From 136f7dcb455dc40b43b49e7e45c56aadbd060411 Mon Sep 17 00:00:00 2001 From: Muhammad Ikhsan Nur Rafid <57042450+Ikhsaaan334@users.noreply.github.com> Date: Tue, 16 Dec 2025 20:26:49 +0700 Subject: [PATCH 1/3] Add files via upload --- readme.MD | 154 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 readme.MD diff --git a/readme.MD b/readme.MD new file mode 100644 index 0000000..b0cdebc --- /dev/null +++ b/readme.MD @@ -0,0 +1,154 @@ +# Flanella + +
+ + **Sahabat Psikologi AI & Aplikasi Jurnal Pribadi Anda** + +
+ + ![Flutter](https://img.shields.io/badge/Flutter-%2302569B.svg?style=for-the-badge&logo=Flutter&logoColor=white) + ![Dart](https://img.shields.io/badge/dart-%230175C2.svg?style=for-the-badge&logo=dart&logoColor=white) + ![NodeJS](https://img.shields.io/badge/node.js-6DA55F?style=for-the-badge&logo=node.js&logoColor=white) + ![Express.js](https://img.shields.io/badge/express.js-%23404d59.svg?style=for-the-badge&logo=express&logoColor=%2361DAFB) + ![Firebase](https://img.shields.io/badge/firebase-%23039BE5.svg?style=for-the-badge&logo=firebase) + ![Google Gemini](https://img.shields.io/badge/Google%20Gemini-8E75B2?style=for-the-badge&logo=google%20bard&logoColor=white) + +
+ +--- + +## 📖 Tentang Flanella + +**Flanella** adalah aplikasi seluler komprehensif yang dirancang untuk mendukung kesehatan mental pengguna. Aplikasi ini menggabungkan kecerdasan buatan (AI) dengan fitur jurnal digital untuk menyediakan ruang aman bagi pengguna dalam mengekspresikan pikiran, mendapatkan dukungan psikologis berbasis AI, dan melacak perjalanan emosional mereka. + +Ditenagai oleh **Google Gemini 2.5 Flash**, Flanella menawarkan percakapan cerdas yang responsif, fitur perangkuman obrolan otomatis menjadi dokumen PDF, serta pengelolaan jurnal yang intuitif. + +## ✨ Fitur Utama + +### 🤖 Pendamping Obrolan AI +- **Percakapan Cerdas**: Berinteraksi dengan AI yang empatik dan responsif menggunakan model Gemini 2.5 Flash dari Google. +- **Pemahaman Konteks**: AI mampu memahami konteks percakapan sebelumnya untuk interaksi yang lebih relevan dan bermakna. +- **Penamaan Sesi Otomatis**: Judul sesi obrolan dibuat secara otomatis berdasarkan topik pembicaraan utama. + +### 📝 Sistem Jurnal Digital +- **Jurnal Harian**: Fitur untuk menulis dan menyimpan catatan harian mengenai pikiran dan perasaan pengguna. +- **Manajemen Data (CRUD)**: Kemudahan dalam Membuat, Membaca, Memperbarui, dan Menghapus entri jurnal. +- **Antarmuka Intuitif**: Desain antarmuka yang bersih dan nyaman untuk pengalaman menulis yang lebih baik. + +### 📄 Perangkuman Cerdas (Smart Summarization) +- **Ekspor ke PDF**: Merangkum sesi percakapan dengan AI secara otomatis dan mengunduhnya dalam format PDF langsung ke perangkat pengguna. +- **Integrasi PDFKit**: Pembuatan dokumen PDF berkualitas tinggi yang diproses di sisi backend. + +### 🏥 Rekomendasi Konsultasi Profesional +- **Akses Cepat**: Tautan langsung ke platform konsultasi kesehatan mental profesional terkemuka: + - **Halodoc** + - **Kalm** + - **Alodokter** + +## 🛠 Teknologi yang Digunakan + +### Frontend (Aplikasi Seluler) +- **Framework**: [Flutter](https://flutter.dev/) +- **Bahasa Pemrograman**: [Dart](https://dart.dev/) +- **Pustaka & Paket Utama**: + - `http`: Menangani permintaan HTTP dan komunikasi dengan API backend. + - `path_provider`: Menyediakan akses ke lokasi penyimpanan file di sistem file perangkat (Android/iOS). + - `url_launcher`: Memungkinkan aplikasi untuk membuka tautan eksternal (browser, email, telepon). + - `curved_navigation_bar`: Komponen navigasi bar bawah dengan animasi yang menarik dan modern. + - `intl`: Menyediakan fasilitas internasionalisasi dan lokalisasi, termasuk pemformatan tanggal dan angka. + - `cupertino_icons`: Set ikon standar gaya iOS untuk konsistensi desain. + +### Backend (API & Layanan) +- **Runtime**: [Node.js](https://nodejs.org/) +- **Framework**: [Express.js](https://expressjs.com/) +- **Database**: [Firebase Firestore](https://firebase.google.com/) +- **Pustaka & Dependensi Utama**: + - `@google/generative-ai`: SDK resmi untuk mengintegrasikan model AI Google Gemini. + - `firebase-admin`: SDK Admin Firebase untuk interaksi server-side dengan layanan Firebase (Firestore, Auth). + - `pdfkit`: Pustaka untuk membuat dokumen PDF yang kompleks dan dapat diunduh secara dinamis. + - `dotenv`: Memuat variabel lingkungan dari file `.env` untuk keamanan konfigurasi. + - `cors`: Middleware untuk mengaktifkan Cross-Origin Resource Sharing pada server Express. + - `axios`: Klien HTTP berbasis Promise untuk melakukan permintaan ke layanan eksternal jika diperlukan. + +## 📸 Tangkapan Layar + +| Halaman Utama | Halaman Obrolan | Halaman Jurnal | +|:---:|:---:|:---:| +| | | | + +## 🚀 Cara Memulai + +Ikuti langkah-langkah berikut untuk menjalankan proyek ini di lingkungan lokal Anda. + +### Prasyarat +- Flutter SDK telah terinstal +- Node.js & npm telah terinstal +- Proyek Firebase telah disiapkan (Firestore & Auth) +- Kunci API Google AI Studio (Gemini API) + +### 1. Instalasi Backend + +Masuk ke direktori backend: +```bash +cd backend +``` + +Instal dependensi yang diperlukan: +```bash +npm install +``` + +Buat file `.env` di dalam folder `backend` dengan konfigurasi berikut: +```env +PORT=3000 +GEMINI_API_KEY=kunci_api_gemini_anda +FIREBASE_PRIVATE_KEY="kunci_privat_firebase_anda" +# Tambahkan konfigurasi firebase lainnya jika diperlukan +``` + +Jalankan server: +```bash +node src/index.js +``` + +### 2. Instalasi Frontend + +Masuk ke direktori aplikasi flutter: +```bash +cd flutter_app +``` + +Instal dependensi paket: +```bash +flutter pub get +``` + +Jalankan aplikasi (pastikan emulator atau perangkat fisik sudah terhubung): +```bash +flutter run +``` + +## 📂 Struktur Proyek + +``` +Psychology-Apps-main/ +├── backend/ # Server Node.js Express +│ ├── src/ +│ │ ├── api/ # Rute API +│ │ ├── config/ # Konfigurasi Firebase & Aplikasi +│ │ ├── controllers/ # Pengendali Permintaan (Controllers) +│ │ ├── services/ # Logika Bisnis & Layanan AI +│ │ └── index.js # Titik Masuk Aplikasi (Entry Point) +│ └── package.json +│ +├── flutter_app/ # Aplikasi Seluler Flutter +│ ├── lib/ +│ │ ├── widgets/ # Komponen UI yang Dapat Digunakan Kembali +│ │ ├── chat_page.dart # Halaman Obrolan +│ │ ├── homepage.dart # Halaman Utama +│ │ ├── journal-page.dart # Halaman Jurnal +│ │ └── main.dart # Titik Masuk Aplikasi Flutter +│ └── pubspec.yaml +│ +└── readme.MD # Dokumentasi Proyek +``` From f1da4be693eab65c8adfd23476c469c7437eba71 Mon Sep 17 00:00:00 2001 From: Muhammad Ikhsan Nur Rafid Date: Tue, 16 Dec 2025 20:53:30 +0700 Subject: [PATCH 2/3] update-all-files --- .idea/.gitignore | 3 + .idea/Psychology-Apps-main.iml | 15 + .idea/caches/deviceStreaming.xml | 1138 + .idea/copilot.data.migration.agent.xml | 6 + .idea/copilot.data.migration.ask.xml | 6 + .idea/copilot.data.migration.ask2agent.xml | 6 + .idea/copilot.data.migration.edit.xml | 6 + .idea/deviceManager.xml | 13 + .idea/libraries/Dart_Packages.xml | 428 + .idea/libraries/Dart_SDK.xml | 31 + .idea/markdown.xml | 8 + .idea/misc.xml | 5 + .idea/modules.xml | 8 + backend/.env.example | 11 + backend/package-lock.json | 1427 +- backend/package.json | 1 + backend/src/Journal.js | 107 + backend/src/api/chat.js | 10 +- backend/src/api/journal.js | 17 + backend/src/config/firebase.js | 28 + backend/src/controllers/chatController.js | 166 +- backend/src/index.js | 2 + backend/src/services/aiService.js | 199 +- .../assets/design/Chat-History Page.png | Bin 0 -> 14257 bytes .../assets/design/Current-_chat_history.png | Bin 0 -> 4593 bytes .../assets/design/Current-_homepage.png | Bin 0 -> 4590 bytes .../assets/design/Current-_journal-page.png | Bin 0 -> 4605 bytes ...t-journal-and-chat-has-created_example.png | Bin 0 -> 61391 bytes flutter_app/assets/design/Homepage.png | Bin 0 -> 47481 bytes flutter_app/assets/design/Journal Page.png | Bin 0 -> 13586 bytes .../design/Settings and Profile Page.png | Bin 0 -> 79352 bytes .../assets/design/WritingJournal Page.png | Bin 0 -> 8343 bytes .../design/example-if-added-new-journal.png | Bin 0 -> 20794 bytes ...e-if-users-addedcreated-alotofjournals.png | Bin 0 -> 51030 bytes ...example-if-users-already-create-a-chat.png | Bin 0 -> 24405 bytes .../assets/design/foto_profile_example.jpg | Bin 0 -> 70104 bytes flutter_app/assets/images/Logo_Halodoc.png | Bin 0 -> 72441 bytes flutter_app/assets/images/alodokter.png | Bin 0 -> 15612 bytes flutter_app/assets/images/logo_Kalm.png | Bin 0 -> 42245 bytes flutter_app/lib/chat_history.dart | 293 + flutter_app/lib/chat_page.dart | 429 +- flutter_app/lib/homepage.dart | 305 + flutter_app/lib/journal-page.dart | 289 + flutter_app/lib/journal_service.dart | 63 + flutter_app/lib/main.dart | 7 +- flutter_app/lib/widgets/custom_navbar.dart | 171 + flutter_app/lib/writing_journal_page.dart | 165 + .../flutter/generated_plugin_registrant.cc | 4 + .../linux/flutter/generated_plugins.cmake | 1 + .../Flutter/GeneratedPluginRegistrant.swift | 4 + flutter_app/pubspec.lock | 199 +- flutter_app/pubspec.yaml | 10 +- .../flutter/generated_plugin_registrant.cc | 3 + .../windows/flutter/generated_plugins.cmake | 1 + node_modules/.bin/fxparser | 16 + node_modules/.bin/fxparser.cmd | 17 + node_modules/.bin/fxparser.ps1 | 28 + node_modules/.bin/mime | 16 + node_modules/.bin/mime.cmd | 17 + node_modules/.bin/mime.ps1 | 28 + node_modules/.bin/proto-loader-gen-types | 16 + node_modules/.bin/proto-loader-gen-types.cmd | 17 + node_modules/.bin/proto-loader-gen-types.ps1 | 28 + node_modules/.bin/semver | 16 + node_modules/.bin/semver.cmd | 17 + node_modules/.bin/semver.ps1 | 28 + node_modules/.bin/uuid | 16 + node_modules/.bin/uuid.cmd | 17 + node_modules/.bin/uuid.ps1 | 28 + node_modules/.package-lock.json | 1964 ++ node_modules/@fastify/busboy/LICENSE | 24 + node_modules/@fastify/busboy/README.md | 270 + .../@fastify/busboy/deps/dicer/LICENSE | 19 + .../@fastify/busboy/deps/dicer/lib/Dicer.js | 213 + .../busboy/deps/dicer/lib/HeaderParser.js | 100 + .../busboy/deps/dicer/lib/PartStream.js | 13 + .../@fastify/busboy/deps/dicer/lib/dicer.d.ts | 164 + .../@fastify/busboy/deps/streamsearch/sbmh.js | 230 + node_modules/@fastify/busboy/lib/main.d.ts | 196 + node_modules/@fastify/busboy/lib/main.js | 85 + .../@fastify/busboy/lib/types/multipart.js | 306 + .../@fastify/busboy/lib/types/urlencoded.js | 190 + .../@fastify/busboy/lib/utils/Decoder.js | 54 + .../@fastify/busboy/lib/utils/basename.js | 14 + .../@fastify/busboy/lib/utils/decodeText.js | 114 + .../@fastify/busboy/lib/utils/getLimit.js | 16 + .../@fastify/busboy/lib/utils/parseParams.js | 201 + node_modules/@fastify/busboy/package.json | 81 + .../app-check-interop-types/README.md | 3 + .../app-check-interop-types/index.d.ts | 51 + .../app-check-interop-types/package.json | 25 + node_modules/@firebase/app-types/README.md | 3 + node_modules/@firebase/app-types/index.d.ts | 129 + node_modules/@firebase/app-types/package.json | 29 + node_modules/@firebase/app-types/private.d.ts | 165 + .../@firebase/auth-interop-types/README.md | 3 + .../@firebase/auth-interop-types/index.d.ts | 35 + .../@firebase/auth-interop-types/package.json | 25 + node_modules/@firebase/component/README.md | 12 + .../@firebase/component/dist/esm/index.d.ts | 20 + .../@firebase/component/dist/esm/index.esm.js | 408 + .../component/dist/esm/index.esm.js.map | 1 + .../@firebase/component/dist/esm/package.json | 1 + .../component/dist/esm/src/component.d.ts | 43 + .../dist/esm/src/component_container.d.ts | 47 + .../component/dist/esm/src/constants.d.ts | 17 + .../component/dist/esm/src/provider.d.ts | 79 + .../component/dist/esm/src/types.d.ts | 62 + .../component/dist/esm/test/setup.d.ts | 17 + .../component/dist/esm/test/util.d.ts | 5 + .../@firebase/component/dist/index.cjs.js | 414 + .../@firebase/component/dist/index.cjs.js.map | 1 + .../@firebase/component/dist/index.d.ts | 20 + .../component/dist/src/component.d.ts | 43 + .../dist/src/component_container.d.ts | 47 + .../component/dist/src/constants.d.ts | 17 + .../component/dist/src/provider.d.ts | 79 + .../@firebase/component/dist/src/types.d.ts | 62 + .../@firebase/component/dist/test/setup.d.ts | 17 + .../@firebase/component/dist/test/util.d.ts | 5 + node_modules/@firebase/component/package.json | 61 + .../@firebase/database-compat/README.md | 5 + .../database-compat/src/api/Database.d.ts | 74 + .../database-compat/src/api/Reference.d.ts | 207 + .../src/api/TransactionResult.d.ts | 26 + .../database-compat/src/api/internal.d.ts | 41 + .../database-compat/src/api/onDisconnect.d.ts | 27 + .../dist/database-compat/src/index.d.ts | 72 + .../dist/database-compat/src/index.node.d.ts | 30 + .../database-compat/src/index.standalone.d.ts | 52 + .../dist/database-compat/src/util/util.d.ts | 17 + .../database-compat/src/util/validation.d.ts | 18 + .../test/browser/crawler_support.test.d.ts | 17 + .../database-compat/test/database.test.d.ts | 17 + .../test/datasnapshot.test.d.ts | 17 + .../database-compat/test/helpers/events.d.ts | 34 + .../database-compat/test/helpers/util.d.ts | 42 + .../dist/database-compat/test/info.test.d.ts | 17 + .../dist/database-compat/test/order.test.d.ts | 17 + .../database-compat/test/order_by.test.d.ts | 17 + .../database-compat/test/promise.test.d.ts | 17 + .../dist/database-compat/test/query.test.d.ts | 17 + .../test/servervalues.test.d.ts | 17 + .../test/transaction.test.d.ts | 17 + .../database-compat/dist/index.esm.js | 860 + .../database-compat/dist/index.esm.js.map | 1 + .../@firebase/database-compat/dist/index.js | 864 + .../database-compat/dist/index.js.map | 1 + .../database-compat/dist/index.standalone.js | 19814 ++++++++++++++++ .../dist/index.standalone.js.map | 1 + .../database-compat/src/api/Database.d.ts | 74 + .../database-compat/src/api/Reference.d.ts | 207 + .../src/api/TransactionResult.d.ts | 26 + .../database-compat/src/api/internal.d.ts | 41 + .../database-compat/src/api/onDisconnect.d.ts | 27 + .../node-esm/database-compat/src/index.d.ts | 32 + .../database-compat/src/index.node.d.ts | 30 + .../database-compat/src/index.standalone.d.ts | 52 + .../database-compat/src/util/util.d.ts | 17 + .../database-compat/src/util/validation.d.ts | 18 + .../test/browser/crawler_support.test.d.ts | 17 + .../database-compat/test/database.test.d.ts | 17 + .../test/datasnapshot.test.d.ts | 17 + .../database-compat/test/helpers/events.d.ts | 34 + .../database-compat/test/helpers/util.d.ts | 42 + .../database-compat/test/info.test.d.ts | 17 + .../database-compat/test/order.test.d.ts | 17 + .../database-compat/test/order_by.test.d.ts | 17 + .../database-compat/test/promise.test.d.ts | 17 + .../database-compat/test/query.test.d.ts | 17 + .../test/servervalues.test.d.ts | 17 + .../test/transaction.test.d.ts | 17 + .../database-compat/dist/node-esm/index.js | 858 + .../dist/node-esm/index.js.map | 1 + .../dist/node-esm/package.json | 1 + .../@firebase/database-compat/package.json | 74 + .../database-compat/standalone/package.json | 7 + .../@firebase/database-types/README.md | 3 + .../@firebase/database-types/index.d.ts | 181 + .../@firebase/database-types/package.json | 29 + node_modules/@firebase/database/README.md | 5 + .../@firebase/database/dist/index.cjs.js | 14089 +++++++++++ .../@firebase/database/dist/index.cjs.js.map | 1 + .../@firebase/database/dist/index.esm.js | 14032 +++++++++++ .../@firebase/database/dist/index.esm.js.map | 1 + .../@firebase/database/dist/index.node.cjs.js | 14109 +++++++++++ .../database/dist/index.node.cjs.js.map | 1 + .../database/dist/index.standalone.js | 14052 +++++++++++ .../database/dist/index.standalone.js.map | 1 + .../@firebase/database/dist/internal.d.ts | 2991 +++ .../database/dist/node-esm/index.node.esm.js | 14048 +++++++++++ .../dist/node-esm/index.node.esm.js.map | 1 + .../database/dist/node-esm/package.json | 1 + .../database/dist/node-esm/src/api.d.ts | 18 + .../dist/node-esm/src/api.standalone.d.ts | 30 + .../dist/node-esm/src/api/Database.d.ts | 137 + .../dist/node-esm/src/api/OnDisconnect.d.ts | 110 + .../dist/node-esm/src/api/Reference.d.ts | 124 + .../dist/node-esm/src/api/Reference_impl.d.ts | 1100 + .../dist/node-esm/src/api/ServerValue.d.ts | 30 + .../dist/node-esm/src/api/Transaction.d.ts | 83 + .../dist/node-esm/src/api/test_access.d.ts | 31 + .../src/core/AppCheckTokenProvider.d.ts | 32 + .../node-esm/src/core/AuthTokenProvider.d.ts | 49 + .../dist/node-esm/src/core/CompoundWrite.d.ts | 81 + .../src/core/PersistentConnection.d.ts | 135 + .../node-esm/src/core/ReadonlyRestClient.d.ts | 60 + .../database/dist/node-esm/src/core/Repo.d.ts | 144 + .../dist/node-esm/src/core/RepoInfo.d.ts | 61 + .../dist/node-esm/src/core/ServerActions.d.ts | 52 + .../node-esm/src/core/SnapshotHolder.d.ts | 26 + .../node-esm/src/core/SparseSnapshotTree.d.ts | 64 + .../dist/node-esm/src/core/SyncPoint.d.ts | 91 + .../dist/node-esm/src/core/SyncTree.d.ts | 166 + .../dist/node-esm/src/core/WriteTree.d.ts | 205 + .../src/core/operation/AckUserWrite.d.ts | 36 + .../src/core/operation/ListenComplete.d.ts | 26 + .../node-esm/src/core/operation/Merge.d.ts | 33 + .../src/core/operation/Operation.d.ts | 45 + .../src/core/operation/Overwrite.d.ts | 28 + .../node-esm/src/core/snap/ChildrenNode.d.ts | 112 + .../dist/node-esm/src/core/snap/IndexMap.d.ts | 43 + .../dist/node-esm/src/core/snap/LeafNode.d.ts | 83 + .../dist/node-esm/src/core/snap/Node.d.ts | 126 + .../dist/node-esm/src/core/snap/childSet.d.ts | 32 + .../node-esm/src/core/snap/comparators.d.ts | 19 + .../node-esm/src/core/snap/indexes/Index.d.ts | 50 + .../src/core/snap/indexes/KeyIndex.d.ts | 34 + .../src/core/snap/indexes/PathIndex.d.ts | 29 + .../src/core/snap/indexes/PriorityIndex.d.ts | 33 + .../src/core/snap/indexes/ValueIndex.d.ts | 31 + .../node-esm/src/core/snap/nodeFromJSON.d.ts | 24 + .../dist/node-esm/src/core/snap/snap.d.ts | 23 + .../src/core/stats/StatsCollection.d.ts | 26 + .../src/core/stats/StatsListener.d.ts | 30 + .../node-esm/src/core/stats/StatsManager.d.ts | 20 + .../src/core/stats/StatsReporter.d.ts | 28 + .../src/core/storage/DOMStorageWrapper.d.ts | 46 + .../src/core/storage/MemoryStorage.d.ts | 27 + .../node-esm/src/core/storage/storage.d.ts | 22 + .../node-esm/src/core/util/EventEmitter.d.ts | 39 + .../node-esm/src/core/util/ImmutableTree.d.ts | 117 + .../node-esm/src/core/util/NextPushId.d.ts | 33 + .../node-esm/src/core/util/OnlineMonitor.d.ts | 31 + .../dist/node-esm/src/core/util/Path.d.ts | 94 + .../node-esm/src/core/util/ServerValues.d.ts | 56 + .../node-esm/src/core/util/SortedMap.d.ts | 324 + .../dist/node-esm/src/core/util/Tree.d.ts | 105 + .../src/core/util/VisibilityMonitor.d.ts | 23 + .../node-esm/src/core/util/libs/parser.d.ts | 32 + .../dist/node-esm/src/core/util/misc.d.ts | 19 + .../dist/node-esm/src/core/util/util.d.ts | 176 + .../node-esm/src/core/util/validation.d.ts | 70 + .../dist/node-esm/src/core/version.d.ts | 23 + .../node-esm/src/core/view/CacheNode.d.ts | 41 + .../dist/node-esm/src/core/view/Change.d.ts | 46 + .../src/core/view/ChildChangeAccumulator.d.ts | 22 + .../src/core/view/CompleteChildSource.d.ts | 55 + .../dist/node-esm/src/core/view/Event.d.ts | 64 + .../src/core/view/EventGenerator.d.ts | 42 + .../node-esm/src/core/view/EventQueue.d.ts | 67 + .../src/core/view/EventRegistration.d.ts | 87 + .../node-esm/src/core/view/QueryParams.d.ts | 95 + .../dist/node-esm/src/core/view/View.d.ts | 59 + .../node-esm/src/core/view/ViewCache.d.ts | 32 + .../node-esm/src/core/view/ViewProcessor.d.ts | 32 + .../src/core/view/filter/IndexedFilter.d.ts | 35 + .../src/core/view/filter/LimitedFilter.d.ts | 47 + .../src/core/view/filter/NodeFilter.d.ts | 54 + .../src/core/view/filter/RangedFilter.d.ts | 47 + .../database/dist/node-esm/src/index.d.ts | 28 + .../dist/node-esm/src/index.node.d.ts | 17 + .../dist/node-esm/src/index.standalone.d.ts | 17 + .../dist/node-esm/src/internal/index.d.ts | 38 + .../src/realtime/BrowserPollConnection.d.ts | 198 + .../node-esm/src/realtime/Connection.d.ts | 102 + .../dist/node-esm/src/realtime/Constants.d.ts | 27 + .../dist/node-esm/src/realtime/Transport.d.ts | 58 + .../src/realtime/TransportManager.d.ts | 50 + .../src/realtime/WebSocketConnection.d.ts | 127 + .../src/realtime/polling/PacketReceiver.d.ts | 38 + .../database/dist/node-esm/src/register.d.ts | 1 + .../test/helpers/EventAccumulator.d.ts | 35 + .../node-esm/test/helpers/syncpoint-util.d.ts | 29 + .../dist/node-esm/test/helpers/util.d.ts | 36 + .../@firebase/database/dist/private.d.ts | 2853 +++ .../@firebase/database/dist/public.d.ts | 1405 ++ .../@firebase/database/dist/src/api.d.ts | 18 + .../database/dist/src/api.standalone.d.ts | 30 + .../database/dist/src/api/Database.d.ts | 137 + .../database/dist/src/api/OnDisconnect.d.ts | 110 + .../database/dist/src/api/Reference.d.ts | 124 + .../database/dist/src/api/Reference_impl.d.ts | 1100 + .../database/dist/src/api/ServerValue.d.ts | 30 + .../database/dist/src/api/Transaction.d.ts | 83 + .../database/dist/src/api/test_access.d.ts | 31 + .../dist/src/core/AppCheckTokenProvider.d.ts | 32 + .../dist/src/core/AuthTokenProvider.d.ts | 49 + .../database/dist/src/core/CompoundWrite.d.ts | 81 + .../dist/src/core/PersistentConnection.d.ts | 135 + .../dist/src/core/ReadonlyRestClient.d.ts | 60 + .../database/dist/src/core/Repo.d.ts | 144 + .../database/dist/src/core/RepoInfo.d.ts | 61 + .../database/dist/src/core/ServerActions.d.ts | 52 + .../dist/src/core/SnapshotHolder.d.ts | 26 + .../dist/src/core/SparseSnapshotTree.d.ts | 64 + .../database/dist/src/core/SyncPoint.d.ts | 91 + .../database/dist/src/core/SyncTree.d.ts | 166 + .../database/dist/src/core/WriteTree.d.ts | 205 + .../dist/src/core/operation/AckUserWrite.d.ts | 36 + .../src/core/operation/ListenComplete.d.ts | 26 + .../dist/src/core/operation/Merge.d.ts | 33 + .../dist/src/core/operation/Operation.d.ts | 45 + .../dist/src/core/operation/Overwrite.d.ts | 28 + .../dist/src/core/snap/ChildrenNode.d.ts | 112 + .../database/dist/src/core/snap/IndexMap.d.ts | 43 + .../database/dist/src/core/snap/LeafNode.d.ts | 83 + .../database/dist/src/core/snap/Node.d.ts | 126 + .../database/dist/src/core/snap/childSet.d.ts | 32 + .../dist/src/core/snap/comparators.d.ts | 19 + .../dist/src/core/snap/indexes/Index.d.ts | 50 + .../dist/src/core/snap/indexes/KeyIndex.d.ts | 34 + .../dist/src/core/snap/indexes/PathIndex.d.ts | 29 + .../src/core/snap/indexes/PriorityIndex.d.ts | 33 + .../src/core/snap/indexes/ValueIndex.d.ts | 31 + .../dist/src/core/snap/nodeFromJSON.d.ts | 24 + .../database/dist/src/core/snap/snap.d.ts | 23 + .../dist/src/core/stats/StatsCollection.d.ts | 26 + .../dist/src/core/stats/StatsListener.d.ts | 30 + .../dist/src/core/stats/StatsManager.d.ts | 20 + .../dist/src/core/stats/StatsReporter.d.ts | 28 + .../src/core/storage/DOMStorageWrapper.d.ts | 46 + .../dist/src/core/storage/MemoryStorage.d.ts | 27 + .../dist/src/core/storage/storage.d.ts | 22 + .../dist/src/core/util/EventEmitter.d.ts | 39 + .../dist/src/core/util/ImmutableTree.d.ts | 117 + .../dist/src/core/util/NextPushId.d.ts | 33 + .../dist/src/core/util/OnlineMonitor.d.ts | 31 + .../database/dist/src/core/util/Path.d.ts | 94 + .../dist/src/core/util/ServerValues.d.ts | 56 + .../dist/src/core/util/SortedMap.d.ts | 324 + .../database/dist/src/core/util/Tree.d.ts | 105 + .../dist/src/core/util/VisibilityMonitor.d.ts | 23 + .../dist/src/core/util/libs/parser.d.ts | 32 + .../database/dist/src/core/util/misc.d.ts | 19 + .../database/dist/src/core/util/util.d.ts | 176 + .../dist/src/core/util/validation.d.ts | 70 + .../database/dist/src/core/version.d.ts | 23 + .../dist/src/core/view/CacheNode.d.ts | 41 + .../database/dist/src/core/view/Change.d.ts | 46 + .../src/core/view/ChildChangeAccumulator.d.ts | 22 + .../src/core/view/CompleteChildSource.d.ts | 55 + .../database/dist/src/core/view/Event.d.ts | 64 + .../dist/src/core/view/EventGenerator.d.ts | 42 + .../dist/src/core/view/EventQueue.d.ts | 67 + .../dist/src/core/view/EventRegistration.d.ts | 87 + .../dist/src/core/view/QueryParams.d.ts | 95 + .../database/dist/src/core/view/View.d.ts | 59 + .../dist/src/core/view/ViewCache.d.ts | 32 + .../dist/src/core/view/ViewProcessor.d.ts | 32 + .../src/core/view/filter/IndexedFilter.d.ts | 35 + .../src/core/view/filter/LimitedFilter.d.ts | 47 + .../dist/src/core/view/filter/NodeFilter.d.ts | 54 + .../src/core/view/filter/RangedFilter.d.ts | 47 + .../@firebase/database/dist/src/index.d.ts | 28 + .../database/dist/src/index.node.d.ts | 17 + .../database/dist/src/index.standalone.d.ts | 17 + .../database/dist/src/internal/index.d.ts | 38 + .../src/realtime/BrowserPollConnection.d.ts | 198 + .../dist/src/realtime/Connection.d.ts | 102 + .../database/dist/src/realtime/Constants.d.ts | 27 + .../database/dist/src/realtime/Transport.d.ts | 58 + .../dist/src/realtime/TransportManager.d.ts | 50 + .../src/realtime/WebSocketConnection.d.ts | 127 + .../src/realtime/polling/PacketReceiver.d.ts | 38 + .../@firebase/database/dist/src/register.d.ts | 1 + .../database/dist/src/tsdoc-metadata.json | 11 + .../dist/test/helpers/EventAccumulator.d.ts | 35 + .../dist/test/helpers/syncpoint-util.d.ts | 29 + .../database/dist/test/helpers/util.d.ts | 36 + node_modules/@firebase/database/package.json | 83 + node_modules/@firebase/logger/README.md | 40 + .../@firebase/logger/dist/esm/index.d.ts | 17 + .../@firebase/logger/dist/esm/index.esm.js | 219 + .../logger/dist/esm/index.esm.js.map | 1 + .../@firebase/logger/dist/esm/package.json | 1 + .../@firebase/logger/dist/esm/src/logger.d.ts | 96 + .../dist/esm/test/custom-logger.test.d.ts | 17 + .../logger/dist/esm/test/logger.test.d.ts | 17 + .../@firebase/logger/dist/index.cjs.js | 225 + .../@firebase/logger/dist/index.cjs.js.map | 1 + node_modules/@firebase/logger/dist/index.d.ts | 17 + .../@firebase/logger/dist/src/logger.d.ts | 96 + .../logger/dist/test/custom-logger.test.d.ts | 17 + .../logger/dist/test/logger.test.d.ts | 17 + node_modules/@firebase/logger/package.json | 60 + node_modules/@firebase/util/README.md | 25 + node_modules/@firebase/util/dist/index.cjs.js | 2392 ++ .../@firebase/util/dist/index.cjs.js.map | 1 + node_modules/@firebase/util/dist/index.d.ts | 39 + node_modules/@firebase/util/dist/index.esm.js | 2318 ++ .../@firebase/util/dist/index.esm.js.map | 1 + .../@firebase/util/dist/index.node.cjs.js | 2411 ++ .../@firebase/util/dist/index.node.cjs.js.map | 1 + .../@firebase/util/dist/index.node.d.ts | 39 + .../@firebase/util/dist/node-esm/index.d.ts | 39 + .../util/dist/node-esm/index.node.d.ts | 39 + .../util/dist/node-esm/index.node.esm.js | 2337 ++ .../util/dist/node-esm/index.node.esm.js.map | 1 + .../@firebase/util/dist/node-esm/package.json | 1 + .../util/dist/node-esm/src/assert.d.ts | 24 + .../util/dist/node-esm/src/compat.d.ts | 20 + .../util/dist/node-esm/src/constants.d.ts | 33 + .../util/dist/node-esm/src/crypt.d.ts | 66 + .../util/dist/node-esm/src/deepCopy.d.ts | 35 + .../util/dist/node-esm/src/defaults.d.ts | 79 + .../util/dist/node-esm/src/deferred.d.ts | 28 + .../util/dist/node-esm/src/emulator.d.ts | 54 + .../util/dist/node-esm/src/environment.d.ts | 92 + .../util/dist/node-esm/src/errors.d.ts | 87 + .../node-esm/src/exponential_backoff.d.ts | 37 + .../util/dist/node-esm/src/formatters.d.ts | 20 + .../util/dist/node-esm/src/global.d.ts | 22 + .../util/dist/node-esm/src/json.d.ts | 29 + .../@firebase/util/dist/node-esm/src/jwt.d.ts | 73 + .../@firebase/util/dist/node-esm/src/obj.d.ts | 30 + .../util/dist/node-esm/src/postinstall.d.ts | 18 + .../util/dist/node-esm/src/promise.d.ts | 21 + .../util/dist/node-esm/src/query.d.ts | 33 + .../util/dist/node-esm/src/sha1.d.ts | 84 + .../util/dist/node-esm/src/subscribe.d.ts | 49 + .../@firebase/util/dist/node-esm/src/url.d.ts | 27 + .../util/dist/node-esm/src/utf8.d.ts | 27 + .../util/dist/node-esm/src/validation.d.ts | 43 + .../util/dist/node-esm/test/base64.test.d.ts | 1 + .../util/dist/node-esm/test/compat.test.d.ts | 17 + .../dist/node-esm/test/deepCopy.test.d.ts | 1 + .../dist/node-esm/test/defaults.test.d.ts | 1 + .../dist/node-esm/test/emulator.test.d.ts | 1 + .../dist/node-esm/test/environments.test.d.ts | 17 + .../util/dist/node-esm/test/errors.test.d.ts | 1 + .../test/exponential_backoff.test.d.ts | 17 + .../util/dist/node-esm/test/object.test.d.ts | 17 + .../dist/node-esm/test/subscribe.test.d.ts | 17 + .../@firebase/util/dist/postinstall.js | 3 + .../@firebase/util/dist/postinstall.mjs | 2 + .../@firebase/util/dist/src/assert.d.ts | 24 + .../@firebase/util/dist/src/compat.d.ts | 20 + .../@firebase/util/dist/src/constants.d.ts | 33 + .../@firebase/util/dist/src/crypt.d.ts | 66 + .../@firebase/util/dist/src/deepCopy.d.ts | 35 + .../@firebase/util/dist/src/defaults.d.ts | 79 + .../@firebase/util/dist/src/deferred.d.ts | 28 + .../@firebase/util/dist/src/emulator.d.ts | 54 + .../@firebase/util/dist/src/environment.d.ts | 92 + .../@firebase/util/dist/src/errors.d.ts | 87 + .../util/dist/src/exponential_backoff.d.ts | 37 + .../@firebase/util/dist/src/formatters.d.ts | 20 + .../@firebase/util/dist/src/global.d.ts | 22 + .../@firebase/util/dist/src/json.d.ts | 29 + node_modules/@firebase/util/dist/src/jwt.d.ts | 73 + node_modules/@firebase/util/dist/src/obj.d.ts | 30 + .../@firebase/util/dist/src/postinstall.d.ts | 18 + .../@firebase/util/dist/src/promise.d.ts | 21 + .../@firebase/util/dist/src/query.d.ts | 33 + .../@firebase/util/dist/src/sha1.d.ts | 84 + .../@firebase/util/dist/src/subscribe.d.ts | 49 + node_modules/@firebase/util/dist/src/url.d.ts | 27 + .../@firebase/util/dist/src/utf8.d.ts | 27 + .../@firebase/util/dist/src/validation.d.ts | 43 + .../@firebase/util/dist/test/base64.test.d.ts | 1 + .../@firebase/util/dist/test/compat.test.d.ts | 17 + .../util/dist/test/deepCopy.test.d.ts | 1 + .../util/dist/test/defaults.test.d.ts | 1 + .../util/dist/test/emulator.test.d.ts | 1 + .../util/dist/test/environments.test.d.ts | 17 + .../@firebase/util/dist/test/errors.test.d.ts | 1 + .../dist/test/exponential_backoff.test.d.ts | 17 + .../@firebase/util/dist/test/object.test.d.ts | 17 + .../util/dist/test/subscribe.test.d.ts | 17 + .../@firebase/util/dist/tsdoc-metadata.json | 11 + .../@firebase/util/dist/util-public.d.ts | 1002 + node_modules/@firebase/util/dist/util.d.ts | 1022 + node_modules/@firebase/util/package.json | 73 + node_modules/@firebase/util/postinstall.js | 153 + node_modules/@google-cloud/firestore/LICENSE | 202 + .../@google-cloud/firestore/README.md | 181 + .../firestore/build/protos/admin_v1.json | 1 + .../build/protos/firestore/bundle.proto | 120 + .../protos/firestore_admin_v1_proto_api.d.ts | 9761 ++++++++ .../protos/firestore_admin_v1_proto_api.js | 1 + .../build/protos/firestore_v1_proto_api.d.ts | 10576 +++++++++ .../build/protos/firestore_v1_proto_api.js | 1 + .../protos/firestore_v1beta1_proto_api.d.ts | 9363 ++++++++ .../protos/firestore_v1beta1_proto_api.js | 1 + .../build/protos/google/api/annotations.proto | 31 + .../build/protos/google/api/client.proto | 480 + .../protos/google/api/field_behavior.proto | 104 + .../build/protos/google/api/http.proto | 371 + .../protos/google/api/launch_stage.proto | 72 + .../build/protos/google/api/resource.proto | 243 + .../google/firestore/admin/v1/backup.proto | 107 + .../google/firestore/admin/v1/database.proto | 321 + .../google/firestore/admin/v1/field.proto | 137 + .../firestore/admin/v1/firestore_admin.proto | 958 + .../google/firestore/admin/v1/index.proto | 198 + .../google/firestore/admin/v1/location.proto | 30 + .../google/firestore/admin/v1/operation.proto | 300 + .../google/firestore/admin/v1/schedule.proto | 95 + .../firestore/v1/aggregation_result.proto | 43 + .../google/firestore/v1/bloom_filter.proto | 73 + .../protos/google/firestore/v1/common.proto | 90 + .../protos/google/firestore/v1/document.proto | 150 + .../google/firestore/v1/firestore.proto | 1128 + .../protos/google/firestore/v1/query.proto | 589 + .../google/firestore/v1/query_profile.proto | 92 + .../protos/google/firestore/v1/write.proto | 286 + .../google/firestore/v1beta1/common.proto | 82 + .../google/firestore/v1beta1/document.proto | 149 + .../google/firestore/v1beta1/firestore.proto | 900 + .../google/firestore/v1beta1/query.proto | 300 + .../undeliverable_first_gen_event.proto | 75 + .../google/firestore/v1beta1/write.proto | 258 + .../google/longrunning/operations.proto | 246 + .../build/protos/google/protobuf/any.proto | 162 + .../protos/google/protobuf/descriptor.proto | 1219 + .../protos/google/protobuf/duration.proto | 115 + .../build/protos/google/protobuf/empty.proto | 51 + .../protos/google/protobuf/field_mask.proto | 245 + .../build/protos/google/protobuf/struct.proto | 95 + .../protos/google/protobuf/timestamp.proto | 144 + .../protos/google/protobuf/wrappers.proto | 123 + .../build/protos/google/rpc/status.proto | 49 + .../build/protos/google/type/dayofweek.proto | 50 + .../build/protos/google/type/latlng.proto | 37 + .../firestore/build/protos/update.sh | 144 + .../firestore/build/protos/v1.json | 1 + .../firestore/build/protos/v1beta1.json | 1 + .../firestore/build/src/aggregate.d.ts | 95 + .../firestore/build/src/aggregate.js | 122 + .../firestore/build/src/backoff.d.ts | 177 + .../firestore/build/src/backoff.js | 225 + .../firestore/build/src/bulk-writer.d.ts | 529 + .../firestore/build/src/bulk-writer.js | 915 + .../firestore/build/src/bundle.d.ts | 24 + .../firestore/build/src/bundle.js | 207 + .../firestore/build/src/collection-group.d.ts | 90 + .../firestore/build/src/collection-group.js | 99 + .../firestore/build/src/convert.d.ts | 81 + .../firestore/build/src/convert.js | 267 + .../firestore/build/src/document-change.d.ts | 155 + .../firestore/build/src/document-change.js | 175 + .../firestore/build/src/document-reader.d.ts | 74 + .../firestore/build/src/document-reader.js | 167 + .../firestore/build/src/document.d.ts | 594 + .../firestore/build/src/document.js | 936 + .../firestore/build/src/field-value.d.ts | 289 + .../firestore/build/src/field-value.js | 523 + .../firestore/build/src/filter.d.ts | 184 + .../firestore/build/src/filter.js | 202 + .../firestore/build/src/geo-point.d.ts | 83 + .../firestore/build/src/geo-point.js | 106 + .../firestore/build/src/index.d.ts | 990 + .../firestore/build/src/index.js | 1555 ++ .../firestore/build/src/logger.d.ts | 37 + .../firestore/build/src/logger.js | 63 + .../firestore/build/src/map-type.d.ts | 18 + .../firestore/build/src/map-type.js | 22 + .../firestore/build/src/order.d.ts | 38 + .../firestore/build/src/order.js | 326 + .../firestore/build/src/path.d.ts | 416 + .../@google-cloud/firestore/build/src/path.js | 656 + .../firestore/build/src/pool.d.ts | 144 + .../@google-cloud/firestore/build/src/pool.js | 379 + .../firestore/build/src/query-partition.d.ts | 96 + .../firestore/build/src/query-partition.js | 144 + .../firestore/build/src/query-profile.d.ts | 94 + .../firestore/build/src/query-profile.js | 119 + .../firestore/build/src/rate-limiter.d.ts | 75 + .../firestore/build/src/rate-limiter.js | 139 + .../firestore/build/src/recursive-delete.d.ts | 166 + .../firestore/build/src/recursive-delete.js | 251 + .../reference/aggregate-query-snapshot.d.ts | 63 + .../src/reference/aggregate-query-snapshot.js | 87 + .../build/src/reference/aggregate-query.d.ts | 119 + .../build/src/reference/aggregate-query.js | 291 + .../src/reference/collection-reference.d.ts | 150 + .../src/reference/collection-reference.js | 287 + .../reference/composite-filter-internal.d.ts | 30 + .../reference/composite-filter-internal.js | 67 + .../build/src/reference/constants.d.ts | 39 + .../build/src/reference/constants.js | 51 + .../src/reference/document-reference.d.ts | 332 + .../build/src/reference/document-reference.js | 521 + .../src/reference/field-filter-internal.d.ts | 58 + .../src/reference/field-filter-internal.js | 113 + .../build/src/reference/field-order.d.ts | 42 + .../build/src/reference/field-order.js | 52 + .../build/src/reference/filter-internal.d.ts | 26 + .../build/src/reference/filter-internal.js | 22 + .../build/src/reference/helpers.d.ts | 68 + .../firestore/build/src/reference/helpers.js | 112 + .../build/src/reference/query-options.d.ts | 76 + .../build/src/reference/query-options.js | 141 + .../build/src/reference/query-snapshot.d.ts | 199 + .../build/src/reference/query-snapshot.js | 254 + .../build/src/reference/query-util.d.ts | 46 + .../build/src/reference/query-util.js | 286 + .../firestore/build/src/reference/query.d.ts | 742 + .../firestore/build/src/reference/query.js | 1152 + .../firestore/build/src/reference/types.d.ts | 66 + .../firestore/build/src/reference/types.js | 46 + .../src/reference/vector-query-options.d.ts | 54 + .../src/reference/vector-query-options.js | 18 + .../src/reference/vector-query-snapshot.d.ts | 191 + .../src/reference/vector-query-snapshot.js | 246 + .../build/src/reference/vector-query.d.ts | 127 + .../build/src/reference/vector-query.js | 210 + .../firestore/build/src/serializer.d.ts | 117 + .../firestore/build/src/serializer.js | 456 + .../firestore/build/src/status-code.d.ts | 38 + .../firestore/build/src/status-code.js | 18 + .../src/telemetry/disabled-trace-util.d.ts | 27 + .../src/telemetry/disabled-trace-util.js | 29 + .../src/telemetry/enabled-trace-util.d.ts | 36 + .../build/src/telemetry/enabled-trace-util.js | 148 + .../firestore/build/src/telemetry/span.d.ts | 28 + .../firestore/build/src/telemetry/span.js | 43 + .../build/src/telemetry/trace-util.d.ts | 74 + .../build/src/telemetry/trace-util.js | 55 + .../firestore/build/src/timestamp.d.ts | 206 + .../firestore/build/src/timestamp.js | 284 + .../firestore/build/src/transaction.d.ts | 262 + .../firestore/build/src/transaction.js | 619 + .../firestore/build/src/types.d.ts | 89 + .../firestore/build/src/types.js | 44 + .../firestore/build/src/util.d.ts | 178 + .../@google-cloud/firestore/build/src/util.js | 305 + .../build/src/v1/firestore_admin_client.d.ts | 1625 ++ .../build/src/v1/firestore_admin_client.js | 1833 ++ .../src/v1/firestore_admin_client_config.json | 139 + .../src/v1/firestore_admin_proto_list.json | 10 + .../build/src/v1/firestore_client.d.ts | 1156 + .../build/src/v1/firestore_client.js | 1271 + .../build/src/v1/firestore_client_config.json | 121 + .../build/src/v1/firestore_proto_list.json | 10 + .../build/src/v1/gapic_metadata.json | 170 + .../firestore/build/src/v1/index.d.ts | 3 + .../firestore/build/src/v1/index.js | 25 + .../build/src/v1beta1/firestore_client.d.ts | 930 + .../build/src/v1beta1/firestore_client.js | 1057 + .../src/v1beta1/firestore_client_config.json | 99 + .../src/v1beta1/firestore_proto_list.json | 8 + .../build/src/v1beta1/gapic_metadata.json | 165 + .../firestore/build/src/v1beta1/index.d.ts | 2 + .../firestore/build/src/v1beta1/index.js | 28 + .../firestore/build/src/validate.d.ts | 178 + .../firestore/build/src/validate.js | 331 + .../firestore/build/src/watch.d.ts | 310 + .../firestore/build/src/watch.js | 668 + .../firestore/build/src/write-batch.d.ts | 287 + .../firestore/build/src/write-batch.js | 668 + .../@google-cloud/firestore/package.json | 115 + .../firestore/types/firestore.d.ts | 3302 +++ .../protos/firestore_admin_v1_proto_api.d.ts | 9761 ++++++++ .../types/protos/firestore_v1_proto_api.d.ts | 10576 +++++++++ .../protos/firestore_v1beta1_proto_api.d.ts | 9363 ++++++++ .../types/v1/firestore_admin_client.d.ts | 2405 ++ .../firestore/types/v1/firestore_client.d.ts | 1450 ++ .../types/v1beta1/firestore_client.d.ts | 1211 + .../@google-cloud/paginator/CHANGELOG.md | 262 + node_modules/@google-cloud/paginator/LICENSE | 202 + .../@google-cloud/paginator/README.md | 136 + .../paginator/build/src/index.d.ts | 131 + .../paginator/build/src/index.js | 210 + .../paginator/build/src/resource-stream.d.ts | 41 + .../paginator/build/src/resource-stream.js | 82 + .../@google-cloud/paginator/package.json | 57 + .../@google-cloud/projectify/CHANGELOG.md | 196 + node_modules/@google-cloud/projectify/LICENSE | 202 + .../@google-cloud/projectify/README.md | 138 + .../projectify/build/src/index.d.ts | 16 + .../projectify/build/src/index.js | 66 + .../@google-cloud/projectify/package.json | 46 + .../@google-cloud/promisify/CHANGELOG.md | 191 + node_modules/@google-cloud/promisify/LICENSE | 202 + .../@google-cloud/promisify/README.md | 156 + .../promisify/build/src/index.d.ts | 61 + .../promisify/build/src/index.js | 148 + .../@google-cloud/promisify/package.json | 50 + node_modules/@google-cloud/storage/LICENSE | 202 + node_modules/@google-cloud/storage/README.md | 302 + .../storage/build/cjs/package.json | 3 + .../storage/build/cjs/src/acl.d.ts | 165 + .../storage/build/cjs/src/acl.js | 718 + .../storage/build/cjs/src/bucket.d.ts | 830 + .../storage/build/cjs/src/bucket.js | 3568 +++ .../storage/build/cjs/src/channel.d.ts | 33 + .../storage/build/cjs/src/channel.js | 104 + .../storage/build/cjs/src/crc32c.d.ts | 143 + .../storage/build/cjs/src/crc32c.js | 261 + .../storage/build/cjs/src/file.d.ts | 982 + .../storage/build/cjs/src/file.js | 3592 +++ .../build/cjs/src/hash-stream-validator.d.ts | 35 + .../build/cjs/src/hash-stream-validator.js | 119 + .../storage/build/cjs/src/hmacKey.d.ts | 93 + .../storage/build/cjs/src/hmacKey.js | 336 + .../storage/build/cjs/src/iam.d.ts | 117 + .../storage/build/cjs/src/iam.js | 306 + .../storage/build/cjs/src/index.d.ts | 57 + .../storage/build/cjs/src/index.js | 95 + .../build/cjs/src/nodejs-common/index.d.ts | 19 + .../build/cjs/src/nodejs-common/index.js | 10 + .../cjs/src/nodejs-common/service-object.d.ts | 217 + .../cjs/src/nodejs-common/service-object.js | 292 + .../build/cjs/src/nodejs-common/service.d.ts | 130 + .../build/cjs/src/nodejs-common/service.js | 219 + .../build/cjs/src/nodejs-common/util.d.ts | 333 + .../build/cjs/src/nodejs-common/util.js | 711 + .../storage/build/cjs/src/notification.d.ts | 106 + .../storage/build/cjs/src/notification.js | 265 + .../build/cjs/src/package-json-helper.cjs | 21 + .../build/cjs/src/resumable-upload.d.ts | 341 + .../storage/build/cjs/src/resumable-upload.js | 909 + .../storage/build/cjs/src/signer.d.ts | 146 + .../storage/build/cjs/src/signer.js | 337 + .../storage/build/cjs/src/storage.d.ts | 730 + .../storage/build/cjs/src/storage.js | 1175 + .../build/cjs/src/transfer-manager.d.ts | 253 + .../storage/build/cjs/src/transfer-manager.js | 694 + .../storage/build/cjs/src/util.d.ts | 85 + .../storage/build/cjs/src/util.js | 280 + .../storage/build/esm/src/acl.d.ts | 165 + .../storage/build/esm/src/acl.js | 714 + .../storage/build/esm/src/bucket.d.ts | 830 + .../storage/build/esm/src/bucket.js | 3534 +++ .../storage/build/esm/src/channel.d.ts | 33 + .../storage/build/esm/src/channel.js | 106 + .../storage/build/esm/src/crc32c.d.ts | 143 + .../storage/build/esm/src/crc32c.js | 254 + .../storage/build/esm/src/file.d.ts | 982 + .../storage/build/esm/src/file.js | 3557 +++ .../build/esm/src/hash-stream-validator.d.ts | 35 + .../build/esm/src/hash-stream-validator.js | 116 + .../storage/build/esm/src/hmacKey.d.ts | 93 + .../storage/build/esm/src/hmacKey.js | 332 + .../storage/build/esm/src/iam.d.ts | 117 + .../storage/build/esm/src/iam.js | 303 + .../storage/build/esm/src/index.d.ts | 57 + .../storage/build/esm/src/index.js | 68 + .../build/esm/src/nodejs-common/index.d.ts | 19 + .../build/esm/src/nodejs-common/index.js | 3 + .../esm/src/nodejs-common/service-object.d.ts | 217 + .../esm/src/nodejs-common/service-object.js | 289 + .../build/esm/src/nodejs-common/service.d.ts | 130 + .../build/esm/src/nodejs-common/service.js | 182 + .../build/esm/src/nodejs-common/util.d.ts | 333 + .../build/esm/src/nodejs-common/util.js | 669 + .../storage/build/esm/src/notification.d.ts | 106 + .../storage/build/esm/src/notification.js | 267 + .../build/esm/src/package-json-helper.cjs | 21 + .../build/esm/src/resumable-upload.d.ts | 341 + .../storage/build/esm/src/resumable-upload.js | 866 + .../storage/build/esm/src/signer.d.ts | 146 + .../storage/build/esm/src/signer.js | 299 + .../storage/build/esm/src/storage.d.ts | 730 + .../storage/build/esm/src/storage.js | 1170 + .../build/esm/src/transfer-manager.d.ts | 253 + .../storage/build/esm/src/transfer-manager.js | 653 + .../storage/build/esm/src/util.d.ts | 85 + .../storage/build/esm/src/util.js | 229 + .../storage/node_modules/.bin/uuid | 16 + .../storage/node_modules/.bin/uuid.cmd | 17 + .../storage/node_modules/.bin/uuid.ps1 | 28 + .../storage/node_modules/uuid/CHANGELOG.md | 229 + .../storage/node_modules/uuid/CONTRIBUTING.md | 18 + .../storage/node_modules/uuid/LICENSE.md | 9 + .../storage/node_modules/uuid/README.md | 505 + .../storage/node_modules/uuid/dist/bin/uuid | 2 + .../uuid/dist/esm-browser/index.js | 9 + .../node_modules/uuid/dist/esm-browser/md5.js | 215 + .../node_modules/uuid/dist/esm-browser/nil.js | 1 + .../uuid/dist/esm-browser/parse.js | 35 + .../uuid/dist/esm-browser/regex.js | 1 + .../node_modules/uuid/dist/esm-browser/rng.js | 19 + .../uuid/dist/esm-browser/sha1.js | 96 + .../uuid/dist/esm-browser/stringify.js | 30 + .../node_modules/uuid/dist/esm-browser/v1.js | 95 + .../node_modules/uuid/dist/esm-browser/v3.js | 4 + .../node_modules/uuid/dist/esm-browser/v35.js | 64 + .../node_modules/uuid/dist/esm-browser/v4.js | 24 + .../node_modules/uuid/dist/esm-browser/v5.js | 4 + .../uuid/dist/esm-browser/validate.js | 7 + .../uuid/dist/esm-browser/version.js | 11 + .../node_modules/uuid/dist/esm-node/index.js | 9 + .../node_modules/uuid/dist/esm-node/md5.js | 13 + .../node_modules/uuid/dist/esm-node/nil.js | 1 + .../node_modules/uuid/dist/esm-node/parse.js | 35 + .../node_modules/uuid/dist/esm-node/regex.js | 1 + .../node_modules/uuid/dist/esm-node/rng.js | 12 + .../node_modules/uuid/dist/esm-node/sha1.js | 13 + .../uuid/dist/esm-node/stringify.js | 29 + .../node_modules/uuid/dist/esm-node/v1.js | 95 + .../node_modules/uuid/dist/esm-node/v3.js | 4 + .../node_modules/uuid/dist/esm-node/v35.js | 64 + .../node_modules/uuid/dist/esm-node/v4.js | 24 + .../node_modules/uuid/dist/esm-node/v5.js | 4 + .../uuid/dist/esm-node/validate.js | 7 + .../uuid/dist/esm-node/version.js | 11 + .../storage/node_modules/uuid/dist/index.js | 79 + .../node_modules/uuid/dist/md5-browser.js | 223 + .../storage/node_modules/uuid/dist/md5.js | 23 + .../storage/node_modules/uuid/dist/nil.js | 8 + .../storage/node_modules/uuid/dist/parse.js | 45 + .../storage/node_modules/uuid/dist/regex.js | 8 + .../node_modules/uuid/dist/rng-browser.js | 26 + .../storage/node_modules/uuid/dist/rng.js | 24 + .../node_modules/uuid/dist/sha1-browser.js | 104 + .../storage/node_modules/uuid/dist/sha1.js | 23 + .../node_modules/uuid/dist/stringify.js | 39 + .../node_modules/uuid/dist/umd/uuid.min.js | 1 + .../node_modules/uuid/dist/umd/uuidNIL.min.js | 1 + .../uuid/dist/umd/uuidParse.min.js | 1 + .../uuid/dist/umd/uuidStringify.min.js | 1 + .../uuid/dist/umd/uuidValidate.min.js | 1 + .../uuid/dist/umd/uuidVersion.min.js | 1 + .../node_modules/uuid/dist/umd/uuidv1.min.js | 1 + .../node_modules/uuid/dist/umd/uuidv3.min.js | 1 + .../node_modules/uuid/dist/umd/uuidv4.min.js | 1 + .../node_modules/uuid/dist/umd/uuidv5.min.js | 1 + .../node_modules/uuid/dist/uuid-bin.js | 85 + .../storage/node_modules/uuid/dist/v1.js | 107 + .../storage/node_modules/uuid/dist/v3.js | 16 + .../storage/node_modules/uuid/dist/v35.js | 78 + .../storage/node_modules/uuid/dist/v4.js | 37 + .../storage/node_modules/uuid/dist/v5.js | 16 + .../node_modules/uuid/dist/validate.js | 17 + .../storage/node_modules/uuid/dist/version.js | 21 + .../storage/node_modules/uuid/package.json | 135 + .../storage/node_modules/uuid/wrapper.mjs | 10 + .../@google-cloud/storage/package.json | 131 + node_modules/@grpc/grpc-js/LICENSE | 201 + node_modules/@grpc/grpc-js/README.md | 84 + .../@grpc/grpc-js/build/src/admin.d.ts | 11 + node_modules/@grpc/grpc-js/build/src/admin.js | 30 + .../@grpc/grpc-js/build/src/admin.js.map | 1 + .../@grpc/grpc-js/build/src/auth-context.d.ts | 5 + .../@grpc/grpc-js/build/src/auth-context.js | 19 + .../grpc-js/build/src/auth-context.js.map | 1 + .../grpc-js/build/src/backoff-timeout.d.ts | 94 + .../grpc-js/build/src/backoff-timeout.js | 191 + .../grpc-js/build/src/backoff-timeout.js.map | 1 + .../grpc-js/build/src/call-credentials.d.ts | 57 + .../grpc-js/build/src/call-credentials.js | 153 + .../grpc-js/build/src/call-credentials.js.map | 1 + .../grpc-js/build/src/call-interface.d.ts | 101 + .../@grpc/grpc-js/build/src/call-interface.js | 100 + .../grpc-js/build/src/call-interface.js.map | 1 + .../@grpc/grpc-js/build/src/call-number.d.ts | 1 + .../@grpc/grpc-js/build/src/call-number.js | 24 + .../grpc-js/build/src/call-number.js.map | 1 + .../@grpc/grpc-js/build/src/call.d.ts | 86 + node_modules/@grpc/grpc-js/build/src/call.js | 152 + .../@grpc/grpc-js/build/src/call.js.map | 1 + .../build/src/certificate-provider.d.ts | 43 + .../grpc-js/build/src/certificate-provider.js | 141 + .../build/src/certificate-provider.js.map | 1 + .../build/src/channel-credentials.d.ts | 119 + .../grpc-js/build/src/channel-credentials.js | 430 + .../build/src/channel-credentials.js.map | 1 + .../grpc-js/build/src/channel-options.d.ts | 81 + .../grpc-js/build/src/channel-options.js | 73 + .../grpc-js/build/src/channel-options.js.map | 1 + .../@grpc/grpc-js/build/src/channel.d.ts | 76 + .../@grpc/grpc-js/build/src/channel.js | 68 + .../@grpc/grpc-js/build/src/channel.js.map | 1 + .../@grpc/grpc-js/build/src/channelz.d.ts | 158 + .../@grpc/grpc-js/build/src/channelz.js | 598 + .../@grpc/grpc-js/build/src/channelz.js.map | 1 + .../build/src/client-interceptors.d.ts | 123 + .../grpc-js/build/src/client-interceptors.js | 434 + .../build/src/client-interceptors.js.map | 1 + .../@grpc/grpc-js/build/src/client.d.ts | 74 + .../@grpc/grpc-js/build/src/client.js | 433 + .../@grpc/grpc-js/build/src/client.js.map | 1 + .../build/src/compression-algorithms.d.ts | 5 + .../build/src/compression-algorithms.js | 26 + .../build/src/compression-algorithms.js.map | 1 + .../grpc-js/build/src/compression-filter.d.ts | 28 + .../grpc-js/build/src/compression-filter.js | 295 + .../build/src/compression-filter.js.map | 1 + .../grpc-js/build/src/connectivity-state.d.ts | 7 + .../grpc-js/build/src/connectivity-state.js | 28 + .../build/src/connectivity-state.js.map | 1 + .../@grpc/grpc-js/build/src/constants.d.ts | 38 + .../@grpc/grpc-js/build/src/constants.js | 64 + .../@grpc/grpc-js/build/src/constants.js.map | 1 + .../build/src/control-plane-status.d.ts | 5 + .../grpc-js/build/src/control-plane-status.js | 42 + .../build/src/control-plane-status.js.map | 1 + .../@grpc/grpc-js/build/src/deadline.d.ts | 22 + .../@grpc/grpc-js/build/src/deadline.js | 108 + .../@grpc/grpc-js/build/src/deadline.js.map | 1 + .../@grpc/grpc-js/build/src/duration.d.ts | 15 + .../@grpc/grpc-js/build/src/duration.js | 74 + .../@grpc/grpc-js/build/src/duration.js.map | 1 + .../@grpc/grpc-js/build/src/environment.d.ts | 1 + .../@grpc/grpc-js/build/src/environment.js | 22 + .../grpc-js/build/src/environment.js.map | 1 + .../@grpc/grpc-js/build/src/error.d.ts | 2 + node_modules/@grpc/grpc-js/build/src/error.js | 40 + .../@grpc/grpc-js/build/src/error.js.map | 1 + .../@grpc/grpc-js/build/src/events.d.ts | 9 + .../@grpc/grpc-js/build/src/events.js | 19 + .../@grpc/grpc-js/build/src/events.js.map | 1 + .../@grpc/grpc-js/build/src/experimental.d.ts | 20 + .../@grpc/grpc-js/build/src/experimental.js | 58 + .../grpc-js/build/src/experimental.js.map | 1 + .../@grpc/grpc-js/build/src/filter-stack.d.ts | 21 + .../@grpc/grpc-js/build/src/filter-stack.js | 82 + .../grpc-js/build/src/filter-stack.js.map | 1 + .../@grpc/grpc-js/build/src/filter.d.ts | 25 + .../@grpc/grpc-js/build/src/filter.js | 38 + .../@grpc/grpc-js/build/src/filter.js.map | 1 + .../grpc-js/build/src/generated/channelz.d.ts | 118 + .../grpc-js/build/src/generated/channelz.js | 3 + .../build/src/generated/channelz.js.map | 1 + .../src/generated/google/protobuf/Any.d.ts | 9 + .../src/generated/google/protobuf/Any.js | 4 + .../src/generated/google/protobuf/Any.js.map | 1 + .../generated/google/protobuf/BoolValue.d.ts | 6 + .../generated/google/protobuf/BoolValue.js | 4 + .../google/protobuf/BoolValue.js.map | 1 + .../generated/google/protobuf/BytesValue.d.ts | 6 + .../generated/google/protobuf/BytesValue.js | 4 + .../google/protobuf/BytesValue.js.map | 1 + .../google/protobuf/DescriptorProto.d.ts | 51 + .../google/protobuf/DescriptorProto.js | 4 + .../google/protobuf/DescriptorProto.js.map | 1 + .../google/protobuf/DoubleValue.d.ts | 6 + .../generated/google/protobuf/DoubleValue.js | 4 + .../google/protobuf/DoubleValue.js.map | 1 + .../generated/google/protobuf/Duration.d.ts | 9 + .../src/generated/google/protobuf/Duration.js | 4 + .../generated/google/protobuf/Duration.js.map | 1 + .../generated/google/protobuf/Edition.d.ts | 16 + .../src/generated/google/protobuf/Edition.js | 19 + .../generated/google/protobuf/Edition.js.map | 1 + .../google/protobuf/EnumDescriptorProto.d.ts | 27 + .../google/protobuf/EnumDescriptorProto.js | 4 + .../protobuf/EnumDescriptorProto.js.map | 1 + .../google/protobuf/EnumOptions.d.ts | 22 + .../generated/google/protobuf/EnumOptions.js | 4 + .../google/protobuf/EnumOptions.js.map | 1 + .../protobuf/EnumValueDescriptorProto.d.ts | 11 + .../protobuf/EnumValueDescriptorProto.js | 4 + .../protobuf/EnumValueDescriptorProto.js.map | 1 + .../google/protobuf/EnumValueOptions.d.ts | 17 + .../google/protobuf/EnumValueOptions.js | 4 + .../google/protobuf/EnumValueOptions.js.map | 1 + .../protobuf/ExtensionRangeOptions.d.ts | 34 + .../google/protobuf/ExtensionRangeOptions.js | 10 + .../protobuf/ExtensionRangeOptions.js.map | 1 + .../generated/google/protobuf/FeatureSet.d.ts | 83 + .../generated/google/protobuf/FeatureSet.js | 56 + .../google/protobuf/FeatureSet.js.map | 1 + .../google/protobuf/FeatureSetDefaults.d.ts | 22 + .../google/protobuf/FeatureSetDefaults.js | 4 + .../google/protobuf/FeatureSetDefaults.js.map | 1 + .../google/protobuf/FieldDescriptorProto.d.ts | 56 + .../google/protobuf/FieldDescriptorProto.js | 32 + .../protobuf/FieldDescriptorProto.js.map | 1 + .../google/protobuf/FieldOptions.d.ts | 99 + .../generated/google/protobuf/FieldOptions.js | 36 + .../google/protobuf/FieldOptions.js.map | 1 + .../google/protobuf/FileDescriptorProto.d.ts | 39 + .../google/protobuf/FileDescriptorProto.js | 4 + .../protobuf/FileDescriptorProto.js.map | 1 + .../google/protobuf/FileDescriptorSet.d.ts | 7 + .../google/protobuf/FileDescriptorSet.js | 4 + .../google/protobuf/FileDescriptorSet.js.map | 1 + .../google/protobuf/FileOptions.d.ts | 61 + .../generated/google/protobuf/FileOptions.js | 11 + .../google/protobuf/FileOptions.js.map | 1 + .../generated/google/protobuf/FloatValue.d.ts | 6 + .../generated/google/protobuf/FloatValue.js | 4 + .../google/protobuf/FloatValue.js.map | 1 + .../google/protobuf/GeneratedCodeInfo.d.ts | 27 + .../google/protobuf/GeneratedCodeInfo.js | 11 + .../google/protobuf/GeneratedCodeInfo.js.map | 1 + .../generated/google/protobuf/Int32Value.d.ts | 6 + .../generated/google/protobuf/Int32Value.js | 4 + .../google/protobuf/Int32Value.js.map | 1 + .../generated/google/protobuf/Int64Value.d.ts | 7 + .../generated/google/protobuf/Int64Value.js | 4 + .../google/protobuf/Int64Value.js.map | 1 + .../google/protobuf/MessageOptions.d.ts | 28 + .../google/protobuf/MessageOptions.js | 4 + .../google/protobuf/MessageOptions.js.map | 1 + .../protobuf/MethodDescriptorProto.d.ts | 17 + .../google/protobuf/MethodDescriptorProto.js | 4 + .../protobuf/MethodDescriptorProto.js.map | 1 + .../google/protobuf/MethodOptions.d.ts | 21 + .../google/protobuf/MethodOptions.js | 11 + .../google/protobuf/MethodOptions.js.map | 1 + .../google/protobuf/OneofDescriptorProto.d.ts | 9 + .../google/protobuf/OneofDescriptorProto.js | 4 + .../protobuf/OneofDescriptorProto.js.map | 1 + .../google/protobuf/OneofOptions.d.ts | 12 + .../generated/google/protobuf/OneofOptions.js | 4 + .../google/protobuf/OneofOptions.js.map | 1 + .../protobuf/ServiceDescriptorProto.d.ts | 12 + .../google/protobuf/ServiceDescriptorProto.js | 4 + .../protobuf/ServiceDescriptorProto.js.map | 1 + .../google/protobuf/ServiceOptions.d.ts | 12 + .../google/protobuf/ServiceOptions.js | 4 + .../google/protobuf/ServiceOptions.js.map | 1 + .../google/protobuf/SourceCodeInfo.d.ts | 20 + .../google/protobuf/SourceCodeInfo.js | 4 + .../google/protobuf/SourceCodeInfo.js.map | 1 + .../google/protobuf/StringValue.d.ts | 6 + .../generated/google/protobuf/StringValue.js | 4 + .../google/protobuf/StringValue.js.map | 1 + .../google/protobuf/SymbolVisibility.d.ts | 7 + .../google/protobuf/SymbolVisibility.js | 10 + .../google/protobuf/SymbolVisibility.js.map | 1 + .../generated/google/protobuf/Timestamp.d.ts | 9 + .../generated/google/protobuf/Timestamp.js | 4 + .../google/protobuf/Timestamp.js.map | 1 + .../google/protobuf/UInt32Value.d.ts | 6 + .../generated/google/protobuf/UInt32Value.js | 4 + .../google/protobuf/UInt32Value.js.map | 1 + .../google/protobuf/UInt64Value.d.ts | 7 + .../generated/google/protobuf/UInt64Value.js | 4 + .../google/protobuf/UInt64Value.js.map | 1 + .../google/protobuf/UninterpretedOption.d.ts | 27 + .../google/protobuf/UninterpretedOption.js | 4 + .../protobuf/UninterpretedOption.js.map | 1 + .../generated/grpc/channelz/v1/Address.d.ts | 79 + .../src/generated/grpc/channelz/v1/Address.js | 4 + .../generated/grpc/channelz/v1/Address.js.map | 1 + .../generated/grpc/channelz/v1/Channel.d.ts | 64 + .../src/generated/grpc/channelz/v1/Channel.js | 4 + .../generated/grpc/channelz/v1/Channel.js.map | 1 + .../channelz/v1/ChannelConnectivityState.d.ts | 24 + .../channelz/v1/ChannelConnectivityState.js | 14 + .../v1/ChannelConnectivityState.js.map | 1 + .../grpc/channelz/v1/ChannelData.d.ts | 72 + .../generated/grpc/channelz/v1/ChannelData.js | 4 + .../grpc/channelz/v1/ChannelData.js.map | 1 + .../grpc/channelz/v1/ChannelRef.d.ts | 27 + .../generated/grpc/channelz/v1/ChannelRef.js | 4 + .../grpc/channelz/v1/ChannelRef.js.map | 1 + .../grpc/channelz/v1/ChannelTrace.d.ts | 41 + .../grpc/channelz/v1/ChannelTrace.js | 4 + .../grpc/channelz/v1/ChannelTrace.js.map | 1 + .../grpc/channelz/v1/ChannelTraceEvent.d.ts | 74 + .../grpc/channelz/v1/ChannelTraceEvent.js | 15 + .../grpc/channelz/v1/ChannelTraceEvent.js.map | 1 + .../generated/grpc/channelz/v1/Channelz.d.ts | 159 + .../generated/grpc/channelz/v1/Channelz.js | 4 + .../grpc/channelz/v1/Channelz.js.map | 1 + .../grpc/channelz/v1/GetChannelRequest.d.ts | 13 + .../grpc/channelz/v1/GetChannelRequest.js | 4 + .../grpc/channelz/v1/GetChannelRequest.js.map | 1 + .../grpc/channelz/v1/GetChannelResponse.d.ts | 15 + .../grpc/channelz/v1/GetChannelResponse.js | 4 + .../channelz/v1/GetChannelResponse.js.map | 1 + .../grpc/channelz/v1/GetServerRequest.d.ts | 13 + .../grpc/channelz/v1/GetServerRequest.js | 4 + .../grpc/channelz/v1/GetServerRequest.js.map | 1 + .../grpc/channelz/v1/GetServerResponse.d.ts | 15 + .../grpc/channelz/v1/GetServerResponse.js | 4 + .../grpc/channelz/v1/GetServerResponse.js.map | 1 + .../channelz/v1/GetServerSocketsRequest.d.ts | 35 + .../channelz/v1/GetServerSocketsRequest.js | 4 + .../v1/GetServerSocketsRequest.js.map | 1 + .../channelz/v1/GetServerSocketsResponse.d.ts | 29 + .../channelz/v1/GetServerSocketsResponse.js | 4 + .../v1/GetServerSocketsResponse.js.map | 1 + .../grpc/channelz/v1/GetServersRequest.d.ts | 33 + .../grpc/channelz/v1/GetServersRequest.js | 4 + .../grpc/channelz/v1/GetServersRequest.js.map | 1 + .../grpc/channelz/v1/GetServersResponse.d.ts | 29 + .../grpc/channelz/v1/GetServersResponse.js | 4 + .../channelz/v1/GetServersResponse.js.map | 1 + .../grpc/channelz/v1/GetSocketRequest.d.ts | 25 + .../grpc/channelz/v1/GetSocketRequest.js | 4 + .../grpc/channelz/v1/GetSocketRequest.js.map | 1 + .../grpc/channelz/v1/GetSocketResponse.d.ts | 15 + .../grpc/channelz/v1/GetSocketResponse.js | 4 + .../grpc/channelz/v1/GetSocketResponse.js.map | 1 + .../channelz/v1/GetSubchannelRequest.d.ts | 13 + .../grpc/channelz/v1/GetSubchannelRequest.js | 4 + .../channelz/v1/GetSubchannelRequest.js.map | 1 + .../channelz/v1/GetSubchannelResponse.d.ts | 15 + .../grpc/channelz/v1/GetSubchannelResponse.js | 4 + .../channelz/v1/GetSubchannelResponse.js.map | 1 + .../channelz/v1/GetTopChannelsRequest.d.ts | 33 + .../grpc/channelz/v1/GetTopChannelsRequest.js | 4 + .../channelz/v1/GetTopChannelsRequest.js.map | 1 + .../channelz/v1/GetTopChannelsResponse.d.ts | 29 + .../channelz/v1/GetTopChannelsResponse.js | 4 + .../channelz/v1/GetTopChannelsResponse.js.map | 1 + .../generated/grpc/channelz/v1/Security.d.ts | 79 + .../generated/grpc/channelz/v1/Security.js | 4 + .../grpc/channelz/v1/Security.js.map | 1 + .../generated/grpc/channelz/v1/Server.d.ts | 41 + .../src/generated/grpc/channelz/v1/Server.js | 4 + .../generated/grpc/channelz/v1/Server.js.map | 1 + .../grpc/channelz/v1/ServerData.d.ts | 53 + .../generated/grpc/channelz/v1/ServerData.js | 4 + .../grpc/channelz/v1/ServerData.js.map | 1 + .../generated/grpc/channelz/v1/ServerRef.d.ts | 27 + .../generated/grpc/channelz/v1/ServerRef.js | 4 + .../grpc/channelz/v1/ServerRef.js.map | 1 + .../generated/grpc/channelz/v1/Socket.d.ts | 66 + .../src/generated/grpc/channelz/v1/Socket.js | 4 + .../generated/grpc/channelz/v1/Socket.js.map | 1 + .../grpc/channelz/v1/SocketData.d.ts | 146 + .../generated/grpc/channelz/v1/SocketData.js | 4 + .../grpc/channelz/v1/SocketData.js.map | 1 + .../grpc/channelz/v1/SocketOption.d.ts | 43 + .../grpc/channelz/v1/SocketOption.js | 4 + .../grpc/channelz/v1/SocketOption.js.map | 1 + .../grpc/channelz/v1/SocketOptionLinger.d.ts | 29 + .../grpc/channelz/v1/SocketOptionLinger.js | 4 + .../channelz/v1/SocketOptionLinger.js.map | 1 + .../grpc/channelz/v1/SocketOptionTcpInfo.d.ts | 70 + .../grpc/channelz/v1/SocketOptionTcpInfo.js | 4 + .../channelz/v1/SocketOptionTcpInfo.js.map | 1 + .../grpc/channelz/v1/SocketOptionTimeout.d.ts | 15 + .../grpc/channelz/v1/SocketOptionTimeout.js | 4 + .../channelz/v1/SocketOptionTimeout.js.map | 1 + .../generated/grpc/channelz/v1/SocketRef.d.ts | 27 + .../generated/grpc/channelz/v1/SocketRef.js | 4 + .../grpc/channelz/v1/SocketRef.js.map | 1 + .../grpc/channelz/v1/Subchannel.d.ts | 66 + .../generated/grpc/channelz/v1/Subchannel.js | 4 + .../grpc/channelz/v1/Subchannel.js.map | 1 + .../grpc/channelz/v1/SubchannelRef.d.ts | 27 + .../grpc/channelz/v1/SubchannelRef.js | 4 + .../grpc/channelz/v1/SubchannelRef.js.map | 1 + .../grpc-js/build/src/generated/orca.d.ts | 145 + .../@grpc/grpc-js/build/src/generated/orca.js | 3 + .../grpc-js/build/src/generated/orca.js.map | 1 + .../src/generated/validate/AnyRules.d.ts | 40 + .../build/src/generated/validate/AnyRules.js | 4 + .../src/generated/validate/AnyRules.js.map | 1 + .../src/generated/validate/BoolRules.d.ts | 18 + .../build/src/generated/validate/BoolRules.js | 4 + .../src/generated/validate/BoolRules.js.map | 1 + .../src/generated/validate/BytesRules.d.ts | 149 + .../src/generated/validate/BytesRules.js | 4 + .../src/generated/validate/BytesRules.js.map | 1 + .../src/generated/validate/DoubleRules.d.ts | 82 + .../src/generated/validate/DoubleRules.js | 4 + .../src/generated/validate/DoubleRules.js.map | 1 + .../src/generated/validate/DurationRules.d.ts | 89 + .../src/generated/validate/DurationRules.js | 4 + .../generated/validate/DurationRules.js.map | 1 + .../src/generated/validate/EnumRules.d.ts | 48 + .../build/src/generated/validate/EnumRules.js | 4 + .../src/generated/validate/EnumRules.js.map | 1 + .../src/generated/validate/FieldRules.d.ts | 98 + .../src/generated/validate/FieldRules.js | 4 + .../src/generated/validate/FieldRules.js.map | 1 + .../src/generated/validate/Fixed32Rules.d.ts | 82 + .../src/generated/validate/Fixed32Rules.js | 4 + .../generated/validate/Fixed32Rules.js.map | 1 + .../src/generated/validate/Fixed64Rules.d.ts | 83 + .../src/generated/validate/Fixed64Rules.js | 4 + .../generated/validate/Fixed64Rules.js.map | 1 + .../src/generated/validate/FloatRules.d.ts | 82 + .../src/generated/validate/FloatRules.js | 4 + .../src/generated/validate/FloatRules.js.map | 1 + .../src/generated/validate/Int32Rules.d.ts | 82 + .../src/generated/validate/Int32Rules.js | 4 + .../src/generated/validate/Int32Rules.js.map | 1 + .../src/generated/validate/Int64Rules.d.ts | 83 + .../src/generated/validate/Int64Rules.js | 4 + .../src/generated/validate/Int64Rules.js.map | 1 + .../src/generated/validate/KnownRegex.d.ts | 30 + .../src/generated/validate/KnownRegex.js | 19 + .../src/generated/validate/KnownRegex.js.map | 1 + .../src/generated/validate/MapRules.d.ts | 62 + .../build/src/generated/validate/MapRules.js | 4 + .../src/generated/validate/MapRules.js.map | 1 + .../src/generated/validate/MessageRules.d.ts | 30 + .../src/generated/validate/MessageRules.js | 4 + .../generated/validate/MessageRules.js.map | 1 + .../src/generated/validate/RepeatedRules.d.ts | 56 + .../src/generated/validate/RepeatedRules.js | 4 + .../generated/validate/RepeatedRules.js.map | 1 + .../src/generated/validate/SFixed32Rules.d.ts | 82 + .../src/generated/validate/SFixed32Rules.js | 4 + .../generated/validate/SFixed32Rules.js.map | 1 + .../src/generated/validate/SFixed64Rules.d.ts | 83 + .../src/generated/validate/SFixed64Rules.js | 4 + .../generated/validate/SFixed64Rules.js.map | 1 + .../src/generated/validate/SInt32Rules.d.ts | 82 + .../src/generated/validate/SInt32Rules.js | 4 + .../src/generated/validate/SInt32Rules.js.map | 1 + .../src/generated/validate/SInt64Rules.d.ts | 83 + .../src/generated/validate/SInt64Rules.js | 4 + .../src/generated/validate/SInt64Rules.js.map | 1 + .../src/generated/validate/StringRules.d.ts | 284 + .../src/generated/validate/StringRules.js | 4 + .../src/generated/validate/StringRules.js.map | 1 + .../generated/validate/TimestampRules.d.ts | 102 + .../src/generated/validate/TimestampRules.js | 4 + .../generated/validate/TimestampRules.js.map | 1 + .../src/generated/validate/UInt32Rules.d.ts | 82 + .../src/generated/validate/UInt32Rules.js | 4 + .../src/generated/validate/UInt32Rules.js.map | 1 + .../src/generated/validate/UInt64Rules.d.ts | 83 + .../src/generated/validate/UInt64Rules.js | 4 + .../src/generated/validate/UInt64Rules.js.map | 1 + .../xds/data/orca/v3/OrcaLoadReport.d.ts | 121 + .../xds/data/orca/v3/OrcaLoadReport.js | 4 + .../xds/data/orca/v3/OrcaLoadReport.js.map | 1 + .../xds/service/orca/v3/OpenRcaService.d.ts | 36 + .../xds/service/orca/v3/OpenRcaService.js | 4 + .../xds/service/orca/v3/OpenRcaService.js.map | 1 + .../orca/v3/OrcaLoadReportRequest.d.ts | 25 + .../service/orca/v3/OrcaLoadReportRequest.js | 4 + .../orca/v3/OrcaLoadReportRequest.js.map | 1 + .../@grpc/grpc-js/build/src/http_proxy.d.ts | 16 + .../@grpc/grpc-js/build/src/http_proxy.js | 274 + .../@grpc/grpc-js/build/src/http_proxy.js.map | 1 + .../@grpc/grpc-js/build/src/index.d.ts | 79 + node_modules/@grpc/grpc-js/build/src/index.js | 148 + .../@grpc/grpc-js/build/src/index.js.map | 1 + .../grpc-js/build/src/internal-channel.d.ts | 124 + .../grpc-js/build/src/internal-channel.js | 605 + .../grpc-js/build/src/internal-channel.js.map | 1 + .../src/load-balancer-child-handler.d.ts | 24 + .../build/src/load-balancer-child-handler.js | 151 + .../src/load-balancer-child-handler.js.map | 1 + .../src/load-balancer-outlier-detection.d.ts | 71 + .../src/load-balancer-outlier-detection.js | 571 + .../load-balancer-outlier-detection.js.map | 1 + .../build/src/load-balancer-pick-first.d.ts | 134 + .../build/src/load-balancer-pick-first.js | 514 + .../build/src/load-balancer-pick-first.js.map | 1 + .../build/src/load-balancer-round-robin.d.ts | 24 + .../build/src/load-balancer-round-robin.js | 204 + .../src/load-balancer-round-robin.js.map | 1 + .../load-balancer-weighted-round-robin.d.ts | 20 + .../src/load-balancer-weighted-round-robin.js | 392 + .../load-balancer-weighted-round-robin.js.map | 1 + .../grpc-js/build/src/load-balancer.d.ts | 101 + .../@grpc/grpc-js/build/src/load-balancer.js | 116 + .../grpc-js/build/src/load-balancer.js.map | 1 + .../build/src/load-balancing-call.d.ts | 49 + .../grpc-js/build/src/load-balancing-call.js | 302 + .../build/src/load-balancing-call.js.map | 1 + .../@grpc/grpc-js/build/src/logging.d.ts | 7 + .../@grpc/grpc-js/build/src/logging.js | 122 + .../@grpc/grpc-js/build/src/logging.js.map | 1 + .../@grpc/grpc-js/build/src/make-client.d.ts | 71 + .../@grpc/grpc-js/build/src/make-client.js | 143 + .../grpc-js/build/src/make-client.js.map | 1 + .../@grpc/grpc-js/build/src/metadata.d.ts | 100 + .../@grpc/grpc-js/build/src/metadata.js | 272 + .../@grpc/grpc-js/build/src/metadata.js.map | 1 + .../grpc-js/build/src/object-stream.d.ts | 27 + .../@grpc/grpc-js/build/src/object-stream.js | 19 + .../grpc-js/build/src/object-stream.js.map | 1 + .../@grpc/grpc-js/build/src/orca.d.ts | 89 + node_modules/@grpc/grpc-js/build/src/orca.js | 323 + .../@grpc/grpc-js/build/src/orca.js.map | 1 + .../@grpc/grpc-js/build/src/picker.d.ts | 95 + .../@grpc/grpc-js/build/src/picker.js | 86 + .../@grpc/grpc-js/build/src/picker.js.map | 1 + .../grpc-js/build/src/priority-queue.d.ts | 50 + .../@grpc/grpc-js/build/src/priority-queue.js | 120 + .../grpc-js/build/src/priority-queue.js.map | 1 + .../@grpc/grpc-js/build/src/resolver-dns.d.ts | 13 + .../@grpc/grpc-js/build/src/resolver-dns.js | 363 + .../grpc-js/build/src/resolver-dns.js.map | 1 + .../@grpc/grpc-js/build/src/resolver-ip.d.ts | 1 + .../@grpc/grpc-js/build/src/resolver-ip.js | 106 + .../grpc-js/build/src/resolver-ip.js.map | 1 + .../@grpc/grpc-js/build/src/resolver-uds.d.ts | 1 + .../@grpc/grpc-js/build/src/resolver-uds.js | 51 + .../grpc-js/build/src/resolver-uds.js.map | 1 + .../@grpc/grpc-js/build/src/resolver.d.ts | 102 + .../@grpc/grpc-js/build/src/resolver.js | 89 + .../@grpc/grpc-js/build/src/resolver.js.map | 1 + .../grpc-js/build/src/resolving-call.d.ts | 54 + .../@grpc/grpc-js/build/src/resolving-call.js | 319 + .../grpc-js/build/src/resolving-call.js.map | 1 + .../build/src/resolving-load-balancer.d.ts | 70 + .../build/src/resolving-load-balancer.js | 304 + .../build/src/resolving-load-balancer.js.map | 1 + .../grpc-js/build/src/retrying-call.d.ts | 100 + .../@grpc/grpc-js/build/src/retrying-call.js | 700 + .../grpc-js/build/src/retrying-call.js.map | 1 + .../@grpc/grpc-js/build/src/server-call.d.ts | 141 + .../@grpc/grpc-js/build/src/server-call.js | 226 + .../grpc-js/build/src/server-call.js.map | 1 + .../grpc-js/build/src/server-credentials.d.ts | 48 + .../grpc-js/build/src/server-credentials.js | 314 + .../build/src/server-credentials.js.map | 1 + .../build/src/server-interceptors.d.ts | 216 + .../grpc-js/build/src/server-interceptors.js | 817 + .../build/src/server-interceptors.js.map | 1 + .../@grpc/grpc-js/build/src/server.d.ts | 140 + .../@grpc/grpc-js/build/src/server.js | 1608 ++ .../@grpc/grpc-js/build/src/server.js.map | 1 + .../grpc-js/build/src/service-config.d.ts | 58 + .../@grpc/grpc-js/build/src/service-config.js | 430 + .../grpc-js/build/src/service-config.js.map | 1 + .../build/src/single-subchannel-channel.d.ts | 25 + .../build/src/single-subchannel-channel.js | 245 + .../src/single-subchannel-channel.js.map | 1 + .../grpc-js/build/src/status-builder.d.ts | 28 + .../@grpc/grpc-js/build/src/status-builder.js | 68 + .../grpc-js/build/src/status-builder.js.map | 1 + .../grpc-js/build/src/stream-decoder.d.ts | 12 + .../@grpc/grpc-js/build/src/stream-decoder.js | 100 + .../grpc-js/build/src/stream-decoder.js.map | 1 + .../grpc-js/build/src/subchannel-address.d.ts | 42 + .../grpc-js/build/src/subchannel-address.js | 202 + .../build/src/subchannel-address.js.map | 1 + .../grpc-js/build/src/subchannel-call.d.ts | 68 + .../grpc-js/build/src/subchannel-call.js | 545 + .../grpc-js/build/src/subchannel-call.js.map | 1 + .../build/src/subchannel-interface.d.ts | 82 + .../grpc-js/build/src/subchannel-interface.js | 114 + .../build/src/subchannel-interface.js.map | 1 + .../grpc-js/build/src/subchannel-pool.d.ts | 40 + .../grpc-js/build/src/subchannel-pool.js | 137 + .../grpc-js/build/src/subchannel-pool.js.map | 1 + .../@grpc/grpc-js/build/src/subchannel.d.ts | 135 + .../@grpc/grpc-js/build/src/subchannel.js | 397 + .../@grpc/grpc-js/build/src/subchannel.js.map | 1 + .../@grpc/grpc-js/build/src/tls-helpers.d.ts | 2 + .../@grpc/grpc-js/build/src/tls-helpers.js | 34 + .../grpc-js/build/src/tls-helpers.js.map | 1 + .../@grpc/grpc-js/build/src/transport.d.ts | 135 + .../@grpc/grpc-js/build/src/transport.js | 640 + .../@grpc/grpc-js/build/src/transport.js.map | 1 + .../@grpc/grpc-js/build/src/uri-parser.d.ts | 13 + .../@grpc/grpc-js/build/src/uri-parser.js | 125 + .../@grpc/grpc-js/build/src/uri-parser.js.map | 1 + .../node_modules/.bin/proto-loader-gen-types | 16 + .../.bin/proto-loader-gen-types.cmd | 17 + .../.bin/proto-loader-gen-types.ps1 | 28 + .../node_modules/@grpc/proto-loader/LICENSE | 201 + .../node_modules/@grpc/proto-loader/README.md | 140 + .../build/bin/proto-loader-gen-types.js | 915 + .../build/bin/proto-loader-gen-types.js.map | 1 + .../@grpc/proto-loader/build/src/index.d.ts | 162 + .../@grpc/proto-loader/build/src/index.js | 246 + .../@grpc/proto-loader/build/src/index.js.map | 1 + .../@grpc/proto-loader/build/src/util.d.ts | 27 + .../@grpc/proto-loader/build/src/util.js | 89 + .../@grpc/proto-loader/build/src/util.js.map | 1 + .../@grpc/proto-loader/package.json | 69 + node_modules/@grpc/grpc-js/package.json | 89 + .../@grpc/grpc-js/proto/channelz.proto | 564 + .../grpc-js/proto/protoc-gen-validate/LICENSE | 202 + .../validate/validate.proto | 797 + node_modules/@grpc/grpc-js/proto/xds/LICENSE | 201 + .../xds/data/orca/v3/orca_load_report.proto | 58 + .../proto/xds/xds/service/orca/v3/orca.proto | 36 + node_modules/@grpc/grpc-js/src/admin.ts | 45 + .../@grpc/grpc-js/src/auth-context.ts | 23 + .../@grpc/grpc-js/src/backoff-timeout.ts | 222 + .../@grpc/grpc-js/src/call-credentials.ts | 227 + .../@grpc/grpc-js/src/call-interface.ts | 208 + node_modules/@grpc/grpc-js/src/call-number.ts | 22 + node_modules/@grpc/grpc-js/src/call.ts | 218 + .../@grpc/grpc-js/src/certificate-provider.ts | 176 + .../@grpc/grpc-js/src/channel-credentials.ts | 523 + .../@grpc/grpc-js/src/channel-options.ts | 128 + node_modules/@grpc/grpc-js/src/channel.ts | 174 + node_modules/@grpc/grpc-js/src/channelz.ts | 909 + .../@grpc/grpc-js/src/client-interceptors.ts | 585 + node_modules/@grpc/grpc-js/src/client.ts | 716 + .../grpc-js/src/compression-algorithms.ts | 22 + .../@grpc/grpc-js/src/compression-filter.ts | 358 + .../@grpc/grpc-js/src/connectivity-state.ts | 24 + node_modules/@grpc/grpc-js/src/constants.ts | 66 + .../@grpc/grpc-js/src/control-plane-status.ts | 43 + node_modules/@grpc/grpc-js/src/deadline.ts | 106 + node_modules/@grpc/grpc-js/src/duration.ts | 79 + node_modules/@grpc/grpc-js/src/environment.ts | 19 + node_modules/@grpc/grpc-js/src/error.ts | 37 + node_modules/@grpc/grpc-js/src/events.ts | 26 + .../@grpc/grpc-js/src/experimental.ts | 73 + .../@grpc/grpc-js/src/filter-stack.ts | 100 + node_modules/@grpc/grpc-js/src/filter.ts | 63 + .../@grpc/grpc-js/src/generated/channelz.ts | 119 + .../src/generated/google/protobuf/Any.ts | 13 + .../generated/google/protobuf/BoolValue.ts | 10 + .../generated/google/protobuf/BytesValue.ts | 10 + .../google/protobuf/DescriptorProto.ts | 59 + .../generated/google/protobuf/DoubleValue.ts | 10 + .../src/generated/google/protobuf/Duration.ts | 13 + .../src/generated/google/protobuf/Edition.ts | 44 + .../google/protobuf/EnumDescriptorProto.ts | 33 + .../generated/google/protobuf/EnumOptions.ts | 26 + .../protobuf/EnumValueDescriptorProto.ts | 15 + .../google/protobuf/EnumValueOptions.ts | 21 + .../google/protobuf/ExtensionRangeOptions.ts | 49 + .../generated/google/protobuf/FeatureSet.ts | 183 + .../google/protobuf/FeatureSetDefaults.ts | 28 + .../google/protobuf/FieldDescriptorProto.ts | 112 + .../generated/google/protobuf/FieldOptions.ts | 165 + .../google/protobuf/FileDescriptorProto.ts | 43 + .../google/protobuf/FileDescriptorSet.ts | 11 + .../generated/google/protobuf/FileOptions.ts | 76 + .../generated/google/protobuf/FloatValue.ts | 10 + .../google/protobuf/GeneratedCodeInfo.ts | 44 + .../generated/google/protobuf/Int32Value.ts | 10 + .../generated/google/protobuf/Int64Value.ts | 11 + .../google/protobuf/MessageOptions.ts | 32 + .../google/protobuf/MethodDescriptorProto.ts | 21 + .../google/protobuf/MethodOptions.ts | 36 + .../google/protobuf/OneofDescriptorProto.ts | 13 + .../generated/google/protobuf/OneofOptions.ts | 16 + .../google/protobuf/ServiceDescriptorProto.ts | 16 + .../google/protobuf/ServiceOptions.ts | 16 + .../google/protobuf/SourceCodeInfo.ts | 26 + .../generated/google/protobuf/StringValue.ts | 10 + .../google/protobuf/SymbolVisibility.ts | 17 + .../generated/google/protobuf/Timestamp.ts | 13 + .../generated/google/protobuf/UInt32Value.ts | 10 + .../generated/google/protobuf/UInt64Value.ts | 11 + .../google/protobuf/UninterpretedOption.ts | 33 + .../src/generated/grpc/channelz/v1/Address.ts | 89 + .../src/generated/grpc/channelz/v1/Channel.ts | 68 + .../channelz/v1/ChannelConnectivityState.ts | 45 + .../generated/grpc/channelz/v1/ChannelData.ts | 76 + .../generated/grpc/channelz/v1/ChannelRef.ts | 31 + .../grpc/channelz/v1/ChannelTrace.ts | 45 + .../grpc/channelz/v1/ChannelTraceEvent.ts | 91 + .../generated/grpc/channelz/v1/Channelz.ts | 178 + .../grpc/channelz/v1/GetChannelRequest.ts | 17 + .../grpc/channelz/v1/GetChannelResponse.ts | 19 + .../grpc/channelz/v1/GetServerRequest.ts | 17 + .../grpc/channelz/v1/GetServerResponse.ts | 19 + .../channelz/v1/GetServerSocketsRequest.ts | 39 + .../channelz/v1/GetServerSocketsResponse.ts | 33 + .../grpc/channelz/v1/GetServersRequest.ts | 37 + .../grpc/channelz/v1/GetServersResponse.ts | 33 + .../grpc/channelz/v1/GetSocketRequest.ts | 29 + .../grpc/channelz/v1/GetSocketResponse.ts | 19 + .../grpc/channelz/v1/GetSubchannelRequest.ts | 17 + .../grpc/channelz/v1/GetSubchannelResponse.ts | 19 + .../grpc/channelz/v1/GetTopChannelsRequest.ts | 37 + .../channelz/v1/GetTopChannelsResponse.ts | 33 + .../generated/grpc/channelz/v1/Security.ts | 87 + .../src/generated/grpc/channelz/v1/Server.ts | 45 + .../generated/grpc/channelz/v1/ServerData.ts | 57 + .../generated/grpc/channelz/v1/ServerRef.ts | 31 + .../src/generated/grpc/channelz/v1/Socket.ts | 70 + .../generated/grpc/channelz/v1/SocketData.ts | 150 + .../grpc/channelz/v1/SocketOption.ts | 47 + .../grpc/channelz/v1/SocketOptionLinger.ts | 33 + .../grpc/channelz/v1/SocketOptionTcpInfo.ts | 74 + .../grpc/channelz/v1/SocketOptionTimeout.ts | 19 + .../generated/grpc/channelz/v1/SocketRef.ts | 31 + .../generated/grpc/channelz/v1/Subchannel.ts | 70 + .../grpc/channelz/v1/SubchannelRef.ts | 31 + .../@grpc/grpc-js/src/generated/orca.ts | 146 + .../src/generated/validate/AnyRules.ts | 44 + .../src/generated/validate/BoolRules.ts | 22 + .../src/generated/validate/BytesRules.ts | 153 + .../src/generated/validate/DoubleRules.ts | 86 + .../src/generated/validate/DurationRules.ts | 93 + .../src/generated/validate/EnumRules.ts | 52 + .../src/generated/validate/FieldRules.ts | 102 + .../src/generated/validate/Fixed32Rules.ts | 86 + .../src/generated/validate/Fixed64Rules.ts | 87 + .../src/generated/validate/FloatRules.ts | 86 + .../src/generated/validate/Int32Rules.ts | 86 + .../src/generated/validate/Int64Rules.ts | 87 + .../src/generated/validate/KnownRegex.ts | 38 + .../src/generated/validate/MapRules.ts | 66 + .../src/generated/validate/MessageRules.ts | 34 + .../src/generated/validate/RepeatedRules.ts | 60 + .../src/generated/validate/SFixed32Rules.ts | 86 + .../src/generated/validate/SFixed64Rules.ts | 87 + .../src/generated/validate/SInt32Rules.ts | 86 + .../src/generated/validate/SInt64Rules.ts | 87 + .../src/generated/validate/StringRules.ts | 288 + .../src/generated/validate/TimestampRules.ts | 106 + .../src/generated/validate/UInt32Rules.ts | 86 + .../src/generated/validate/UInt64Rules.ts | 87 + .../xds/data/orca/v3/OrcaLoadReport.ts | 113 + .../xds/service/orca/v3/OpenRcaService.ts | 43 + .../service/orca/v3/OrcaLoadReportRequest.ts | 29 + node_modules/@grpc/grpc-js/src/http_proxy.ts | 315 + node_modules/@grpc/grpc-js/src/index.ts | 312 + .../@grpc/grpc-js/src/internal-channel.ts | 878 + .../src/load-balancer-child-handler.ts | 173 + .../src/load-balancer-outlier-detection.ts | 840 + .../grpc-js/src/load-balancer-pick-first.ts | 662 + .../grpc-js/src/load-balancer-round-robin.ts | 287 + .../src/load-balancer-weighted-round-robin.ts | 494 + .../@grpc/grpc-js/src/load-balancer.ts | 258 + .../@grpc/grpc-js/src/load-balancing-call.ts | 387 + node_modules/@grpc/grpc-js/src/logging.ts | 134 + node_modules/@grpc/grpc-js/src/make-client.ts | 238 + node_modules/@grpc/grpc-js/src/metadata.ts | 323 + .../@grpc/grpc-js/src/object-stream.ts | 66 + node_modules/@grpc/grpc-js/src/orca.ts | 349 + node_modules/@grpc/grpc-js/src/picker.ts | 157 + .../@grpc/grpc-js/src/priority-queue.ts | 118 + .../@grpc/grpc-js/src/resolver-dns.ts | 449 + node_modules/@grpc/grpc-js/src/resolver-ip.ts | 124 + .../@grpc/grpc-js/src/resolver-uds.ts | 63 + node_modules/@grpc/grpc-js/src/resolver.ts | 176 + .../@grpc/grpc-js/src/resolving-call.ts | 379 + .../grpc-js/src/resolving-load-balancer.ts | 407 + .../@grpc/grpc-js/src/retrying-call.ts | 898 + node_modules/@grpc/grpc-js/src/server-call.ts | 420 + .../@grpc/grpc-js/src/server-credentials.ts | 352 + .../@grpc/grpc-js/src/server-interceptors.ts | 1071 + node_modules/@grpc/grpc-js/src/server.ts | 2212 ++ .../@grpc/grpc-js/src/service-config.ts | 564 + .../grpc-js/src/single-subchannel-channel.ts | 248 + .../@grpc/grpc-js/src/status-builder.ts | 80 + .../@grpc/grpc-js/src/stream-decoder.ts | 110 + .../@grpc/grpc-js/src/subchannel-address.ts | 252 + .../@grpc/grpc-js/src/subchannel-call.ts | 622 + .../@grpc/grpc-js/src/subchannel-interface.ts | 176 + .../@grpc/grpc-js/src/subchannel-pool.ts | 176 + node_modules/@grpc/grpc-js/src/subchannel.ts | 559 + node_modules/@grpc/grpc-js/src/tls-helpers.ts | 35 + node_modules/@grpc/grpc-js/src/transport.ts | 825 + node_modules/@grpc/grpc-js/src/uri-parser.ts | 127 + node_modules/@grpc/proto-loader/LICENSE | 201 + node_modules/@grpc/proto-loader/README.md | 140 + .../build/bin/proto-loader-gen-types.js | 913 + .../build/bin/proto-loader-gen-types.js.map | 1 + .../@grpc/proto-loader/build/src/index.d.ts | 160 + .../@grpc/proto-loader/build/src/index.js | 244 + .../@grpc/proto-loader/build/src/index.js.map | 1 + .../@grpc/proto-loader/build/src/util.d.ts | 27 + .../@grpc/proto-loader/build/src/util.js | 89 + .../@grpc/proto-loader/build/src/util.js.map | 1 + node_modules/@grpc/proto-loader/package.json | 69 + .../@js-sdsl/ordered-map/CHANGELOG.md | 237 + node_modules/@js-sdsl/ordered-map/LICENSE | 21 + node_modules/@js-sdsl/ordered-map/README.md | 270 + .../@js-sdsl/ordered-map/README.zh-CN.md | 272 + .../@js-sdsl/ordered-map/dist/cjs/index.d.ts | 402 + .../@js-sdsl/ordered-map/dist/cjs/index.js | 795 + .../ordered-map/dist/cjs/index.js.map | 1 + .../@js-sdsl/ordered-map/dist/esm/index.d.ts | 402 + .../@js-sdsl/ordered-map/dist/esm/index.js | 975 + .../ordered-map/dist/esm/index.js.map | 1 + .../ordered-map/dist/umd/ordered-map.js | 1157 + .../ordered-map/dist/umd/ordered-map.min.js | 8 + .../dist/umd/ordered-map.min.js.map | 1 + .../@js-sdsl/ordered-map/package.json | 138 + node_modules/@opentelemetry/api/LICENSE | 201 + node_modules/@opentelemetry/api/README.md | 116 + .../api/build/esm/api/context.d.ts | 41 + .../api/build/esm/api/context.js | 110 + .../api/build/esm/api/context.js.map | 1 + .../api/build/esm/api/diag.d.ts | 30 + .../@opentelemetry/api/build/esm/api/diag.js | 121 + .../api/build/esm/api/diag.js.map | 1 + .../api/build/esm/api/metrics.d.ts | 28 + .../api/build/esm/api/metrics.js | 60 + .../api/build/esm/api/metrics.js.map | 1 + .../api/build/esm/api/propagation.d.ts | 49 + .../api/build/esm/api/propagation.js | 89 + .../api/build/esm/api/propagation.js.map | 1 + .../api/build/esm/api/trace.d.ts | 40 + .../@opentelemetry/api/build/esm/api/trace.js | 77 + .../api/build/esm/api/trace.js.map | 1 + .../build/esm/baggage/context-helpers.d.ts | 29 + .../api/build/esm/baggage/context-helpers.js | 56 + .../build/esm/baggage/context-helpers.js.map | 1 + .../esm/baggage/internal/baggage-impl.d.ts | 12 + .../esm/baggage/internal/baggage-impl.js | 98 + .../esm/baggage/internal/baggage-impl.js.map | 1 + .../build/esm/baggage/internal/symbol.d.ts | 5 + .../api/build/esm/baggage/internal/symbol.js | 20 + .../build/esm/baggage/internal/symbol.js.map | 1 + .../api/build/esm/baggage/types.d.ts | 60 + .../api/build/esm/baggage/types.js | 17 + .../api/build/esm/baggage/types.js.map | 1 + .../api/build/esm/baggage/utils.d.ts | 15 + .../api/build/esm/baggage/utils.js | 47 + .../api/build/esm/baggage/utils.js.map | 1 + .../api/build/esm/common/Attributes.d.ts | 15 + .../api/build/esm/common/Attributes.js | 17 + .../api/build/esm/common/Attributes.js.map | 1 + .../api/build/esm/common/Exception.d.ts | 26 + .../api/build/esm/common/Exception.js | 17 + .../api/build/esm/common/Exception.js.map | 1 + .../api/build/esm/common/Time.d.ts | 20 + .../api/build/esm/common/Time.js | 2 + .../api/build/esm/common/Time.js.map | 1 + .../api/build/esm/context-api.d.ts | 4 + .../api/build/esm/context-api.js | 21 + .../api/build/esm/context-api.js.map | 1 + .../build/esm/context/NoopContextManager.d.ts | 9 + .../build/esm/context/NoopContextManager.js | 67 + .../esm/context/NoopContextManager.js.map | 1 + .../api/build/esm/context/context.d.ts | 6 + .../api/build/esm/context/context.js | 52 + .../api/build/esm/context/context.js.map | 1 + .../api/build/esm/context/types.d.ts | 52 + .../api/build/esm/context/types.js | 17 + .../api/build/esm/context/types.js.map | 1 + .../api/build/esm/diag-api.d.ts | 9 + .../@opentelemetry/api/build/esm/diag-api.js | 26 + .../api/build/esm/diag-api.js.map | 1 + .../api/build/esm/diag/ComponentLogger.d.ts | 20 + .../api/build/esm/diag/ComponentLogger.js | 102 + .../api/build/esm/diag/ComponentLogger.js.map | 1 + .../api/build/esm/diag/consoleLogger.d.ts | 38 + .../api/build/esm/diag/consoleLogger.js | 59 + .../api/build/esm/diag/consoleLogger.js.map | 1 + .../esm/diag/internal/logLevelLogger.d.ts | 3 + .../build/esm/diag/internal/logLevelLogger.js | 41 + .../esm/diag/internal/logLevelLogger.js.map | 1 + .../build/esm/diag/internal/noopLogger.d.ts | 8 + .../api/build/esm/diag/internal/noopLogger.js | 31 + .../build/esm/diag/internal/noopLogger.js.map | 1 + .../api/build/esm/diag/types.d.ts | 100 + .../api/build/esm/diag/types.js | 41 + .../api/build/esm/diag/types.js.map | 1 + .../api/build/esm/experimental/index.d.ts | 3 + .../api/build/esm/experimental/index.js | 17 + .../api/build/esm/experimental/index.js.map | 1 + .../experimental/trace/SugaredOptions.d.ts | 13 + .../esm/experimental/trace/SugaredOptions.js | 17 + .../experimental/trace/SugaredOptions.js.map | 1 + .../esm/experimental/trace/SugaredTracer.d.ts | 64 + .../esm/experimental/trace/SugaredTracer.js | 92 + .../experimental/trace/SugaredTracer.js.map | 1 + .../@opentelemetry/api/build/esm/index.d.ts | 54 + .../@opentelemetry/api/build/esm/index.js | 53 + .../@opentelemetry/api/build/esm/index.js.map | 1 + .../api/build/esm/internal/global-utils.d.ts | 18 + .../api/build/esm/internal/global-utils.js | 59 + .../build/esm/internal/global-utils.js.map | 1 + .../api/build/esm/internal/semver.d.ts | 34 + .../api/build/esm/internal/semver.js | 118 + .../api/build/esm/internal/semver.js.map | 1 + .../api/build/esm/metrics-api.d.ts | 4 + .../api/build/esm/metrics-api.js | 21 + .../api/build/esm/metrics-api.js.map | 1 + .../api/build/esm/metrics/Meter.d.ts | 110 + .../api/build/esm/metrics/Meter.js | 17 + .../api/build/esm/metrics/Meter.js.map | 1 + .../api/build/esm/metrics/MeterProvider.d.ts | 17 + .../api/build/esm/metrics/MeterProvider.js | 17 + .../build/esm/metrics/MeterProvider.js.map | 1 + .../api/build/esm/metrics/Metric.d.ts | 115 + .../api/build/esm/metrics/Metric.js | 22 + .../api/build/esm/metrics/Metric.js.map | 1 + .../api/build/esm/metrics/NoopMeter.d.ts | 82 + .../api/build/esm/metrics/NoopMeter.js | 181 + .../api/build/esm/metrics/NoopMeter.js.map | 1 + .../build/esm/metrics/NoopMeterProvider.d.ts | 11 + .../build/esm/metrics/NoopMeterProvider.js | 31 + .../esm/metrics/NoopMeterProvider.js.map | 1 + .../build/esm/metrics/ObservableResult.d.ts | 31 + .../api/build/esm/metrics/ObservableResult.js | 17 + .../build/esm/metrics/ObservableResult.js.map | 1 + .../esm/platform/browser/globalThis.d.ts | 10 + .../build/esm/platform/browser/globalThis.js | 35 + .../esm/platform/browser/globalThis.js.map | 1 + .../api/build/esm/platform/browser/index.d.ts | 2 + .../api/build/esm/platform/browser/index.js | 17 + .../build/esm/platform/browser/index.js.map | 1 + .../api/build/esm/platform/index.d.ts | 2 + .../api/build/esm/platform/index.js | 17 + .../api/build/esm/platform/index.js.map | 1 + .../build/esm/platform/node/globalThis.d.ts | 3 + .../api/build/esm/platform/node/globalThis.js | 19 + .../build/esm/platform/node/globalThis.js.map | 1 + .../api/build/esm/platform/node/index.d.ts | 2 + .../api/build/esm/platform/node/index.js | 17 + .../api/build/esm/platform/node/index.js.map | 1 + .../api/build/esm/propagation-api.d.ts | 4 + .../api/build/esm/propagation-api.js | 21 + .../api/build/esm/propagation-api.js.map | 1 + .../propagation/NoopTextMapPropagator.d.ts | 13 + .../esm/propagation/NoopTextMapPropagator.js | 34 + .../propagation/NoopTextMapPropagator.js.map | 1 + .../esm/propagation/TextMapPropagator.d.ts | 84 + .../esm/propagation/TextMapPropagator.js | 38 + .../esm/propagation/TextMapPropagator.js.map | 1 + .../api/build/esm/trace-api.d.ts | 4 + .../@opentelemetry/api/build/esm/trace-api.js | 21 + .../api/build/esm/trace-api.js.map | 1 + .../api/build/esm/trace/NonRecordingSpan.d.ts | 28 + .../api/build/esm/trace/NonRecordingSpan.js | 68 + .../build/esm/trace/NonRecordingSpan.js.map | 1 + .../api/build/esm/trace/NoopTracer.d.ts | 14 + .../api/build/esm/trace/NoopTracer.js | 76 + .../api/build/esm/trace/NoopTracer.js.map | 1 + .../build/esm/trace/NoopTracerProvider.d.ts | 13 + .../api/build/esm/trace/NoopTracerProvider.js | 32 + .../build/esm/trace/NoopTracerProvider.js.map | 1 + .../api/build/esm/trace/ProxyTracer.d.ts | 27 + .../api/build/esm/trace/ProxyTracer.js | 53 + .../api/build/esm/trace/ProxyTracer.js.map | 1 + .../build/esm/trace/ProxyTracerProvider.d.ts | 25 + .../build/esm/trace/ProxyTracerProvider.js | 54 + .../esm/trace/ProxyTracerProvider.js.map | 1 + .../api/build/esm/trace/Sampler.d.ts | 31 + .../api/build/esm/trace/Sampler.js | 17 + .../api/build/esm/trace/Sampler.js.map | 1 + .../api/build/esm/trace/SamplingResult.d.ts | 49 + .../api/build/esm/trace/SamplingResult.js | 39 + .../api/build/esm/trace/SamplingResult.js.map | 1 + .../api/build/esm/trace/SpanOptions.d.ts | 23 + .../api/build/esm/trace/SpanOptions.js | 17 + .../api/build/esm/trace/SpanOptions.js.map | 1 + .../api/build/esm/trace/attributes.d.ts | 10 + .../api/build/esm/trace/attributes.js | 17 + .../api/build/esm/trace/attributes.js.map | 1 + .../api/build/esm/trace/context-utils.d.ts | 41 + .../api/build/esm/trace/context-utils.js | 73 + .../api/build/esm/trace/context-utils.js.map | 1 + .../esm/trace/internal/tracestate-impl.d.ts | 22 + .../esm/trace/internal/tracestate-impl.js | 102 + .../esm/trace/internal/tracestate-impl.js.map | 1 + .../trace/internal/tracestate-validators.d.ts | 15 + .../trace/internal/tracestate-validators.js | 41 + .../internal/tracestate-validators.js.map | 1 + .../api/build/esm/trace/internal/utils.d.ts | 3 + .../api/build/esm/trace/internal/utils.js | 20 + .../api/build/esm/trace/internal/utils.js.map | 1 + .../esm/trace/invalid-span-constants.d.ts | 5 + .../build/esm/trace/invalid-span-constants.js | 24 + .../esm/trace/invalid-span-constants.js.map | 1 + .../api/build/esm/trace/link.d.ts | 26 + .../api/build/esm/trace/link.js | 17 + .../api/build/esm/trace/link.js.map | 1 + .../api/build/esm/trace/span.d.ts | 120 + .../api/build/esm/trace/span.js | 17 + .../api/build/esm/trace/span.js.map | 1 + .../api/build/esm/trace/span_context.d.ts | 53 + .../api/build/esm/trace/span_context.js | 17 + .../api/build/esm/trace/span_context.js.map | 1 + .../api/build/esm/trace/span_kind.d.ts | 27 + .../api/build/esm/trace/span_kind.js | 43 + .../api/build/esm/trace/span_kind.js.map | 1 + .../build/esm/trace/spancontext-utils.d.ts | 17 + .../api/build/esm/trace/spancontext-utils.js | 42 + .../build/esm/trace/spancontext-utils.js.map | 1 + .../api/build/esm/trace/status.d.ts | 25 + .../api/build/esm/trace/status.js | 20 + .../api/build/esm/trace/status.js.map | 1 + .../api/build/esm/trace/trace_flags.d.ts | 7 + .../api/build/esm/trace/trace_flags.js | 23 + .../api/build/esm/trace/trace_flags.js.map | 1 + .../api/build/esm/trace/trace_state.d.ts | 38 + .../api/build/esm/trace/trace_state.js | 17 + .../api/build/esm/trace/trace_state.js.map | 1 + .../api/build/esm/trace/tracer.d.ts | 71 + .../api/build/esm/trace/tracer.js | 17 + .../api/build/esm/trace/tracer.js.map | 1 + .../api/build/esm/trace/tracer_options.d.ts | 10 + .../api/build/esm/trace/tracer_options.js | 17 + .../api/build/esm/trace/tracer_options.js.map | 1 + .../api/build/esm/trace/tracer_provider.d.ts | 21 + .../api/build/esm/trace/tracer_provider.js | 17 + .../build/esm/trace/tracer_provider.js.map | 1 + .../@opentelemetry/api/build/esm/version.d.ts | 2 + .../@opentelemetry/api/build/esm/version.js | 18 + .../api/build/esm/version.js.map | 1 + .../api/build/esnext/api/context.d.ts | 41 + .../api/build/esnext/api/context.js | 77 + .../api/build/esnext/api/context.js.map | 1 + .../api/build/esnext/api/diag.d.ts | 30 + .../api/build/esnext/api/diag.js | 89 + .../api/build/esnext/api/diag.js.map | 1 + .../api/build/esnext/api/metrics.d.ts | 28 + .../api/build/esnext/api/metrics.js | 57 + .../api/build/esnext/api/metrics.js.map | 1 + .../api/build/esnext/api/propagation.d.ts | 49 + .../api/build/esnext/api/propagation.js | 85 + .../api/build/esnext/api/propagation.js.map | 1 + .../api/build/esnext/api/trace.d.ts | 40 + .../api/build/esnext/api/trace.js | 75 + .../api/build/esnext/api/trace.js.map | 1 + .../build/esnext/baggage/context-helpers.d.ts | 29 + .../build/esnext/baggage/context-helpers.js | 56 + .../esnext/baggage/context-helpers.js.map | 1 + .../esnext/baggage/internal/baggage-impl.d.ts | 12 + .../esnext/baggage/internal/baggage-impl.js | 51 + .../baggage/internal/baggage-impl.js.map | 1 + .../build/esnext/baggage/internal/symbol.d.ts | 5 + .../build/esnext/baggage/internal/symbol.js | 20 + .../esnext/baggage/internal/symbol.js.map | 1 + .../api/build/esnext/baggage/types.d.ts | 60 + .../api/build/esnext/baggage/types.js | 17 + .../api/build/esnext/baggage/types.js.map | 1 + .../api/build/esnext/baggage/utils.d.ts | 15 + .../api/build/esnext/baggage/utils.js | 46 + .../api/build/esnext/baggage/utils.js.map | 1 + .../api/build/esnext/common/Attributes.d.ts | 15 + .../api/build/esnext/common/Attributes.js | 17 + .../api/build/esnext/common/Attributes.js.map | 1 + .../api/build/esnext/common/Exception.d.ts | 26 + .../api/build/esnext/common/Exception.js | 17 + .../api/build/esnext/common/Exception.js.map | 1 + .../api/build/esnext/common/Time.d.ts | 20 + .../api/build/esnext/common/Time.js | 2 + .../api/build/esnext/common/Time.js.map | 1 + .../api/build/esnext/context-api.d.ts | 4 + .../api/build/esnext/context-api.js | 21 + .../api/build/esnext/context-api.js.map | 1 + .../esnext/context/NoopContextManager.d.ts | 9 + .../esnext/context/NoopContextManager.js | 34 + .../esnext/context/NoopContextManager.js.map | 1 + .../api/build/esnext/context/context.d.ts | 6 + .../api/build/esnext/context/context.js | 51 + .../api/build/esnext/context/context.js.map | 1 + .../api/build/esnext/context/types.d.ts | 52 + .../api/build/esnext/context/types.js | 17 + .../api/build/esnext/context/types.js.map | 1 + .../api/build/esnext/diag-api.d.ts | 9 + .../api/build/esnext/diag-api.js | 26 + .../api/build/esnext/diag-api.js.map | 1 + .../build/esnext/diag/ComponentLogger.d.ts | 20 + .../api/build/esnext/diag/ComponentLogger.js | 55 + .../build/esnext/diag/ComponentLogger.js.map | 1 + .../api/build/esnext/diag/consoleLogger.d.ts | 38 + .../api/build/esnext/diag/consoleLogger.js | 53 + .../build/esnext/diag/consoleLogger.js.map | 1 + .../esnext/diag/internal/logLevelLogger.d.ts | 3 + .../esnext/diag/internal/logLevelLogger.js | 41 + .../diag/internal/logLevelLogger.js.map | 1 + .../esnext/diag/internal/noopLogger.d.ts | 8 + .../build/esnext/diag/internal/noopLogger.js | 31 + .../esnext/diag/internal/noopLogger.js.map | 1 + .../api/build/esnext/diag/types.d.ts | 100 + .../api/build/esnext/diag/types.js | 41 + .../api/build/esnext/diag/types.js.map | 1 + .../api/build/esnext/experimental/index.d.ts | 3 + .../api/build/esnext/experimental/index.js | 17 + .../build/esnext/experimental/index.js.map | 1 + .../experimental/trace/SugaredOptions.d.ts | 13 + .../experimental/trace/SugaredOptions.js | 17 + .../experimental/trace/SugaredOptions.js.map | 1 + .../experimental/trace/SugaredTracer.d.ts | 64 + .../experimental/trace/SugaredTracer.js | 88 + .../experimental/trace/SugaredTracer.js.map | 1 + .../api/build/esnext/index.d.ts | 54 + .../@opentelemetry/api/build/esnext/index.js | 53 + .../api/build/esnext/index.js.map | 1 + .../build/esnext/internal/global-utils.d.ts | 18 + .../api/build/esnext/internal/global-utils.js | 58 + .../build/esnext/internal/global-utils.js.map | 1 + .../api/build/esnext/internal/semver.d.ts | 34 + .../api/build/esnext/internal/semver.js | 118 + .../api/build/esnext/internal/semver.js.map | 1 + .../api/build/esnext/metrics-api.d.ts | 4 + .../api/build/esnext/metrics-api.js | 21 + .../api/build/esnext/metrics-api.js.map | 1 + .../api/build/esnext/metrics/Meter.d.ts | 110 + .../api/build/esnext/metrics/Meter.js | 17 + .../api/build/esnext/metrics/Meter.js.map | 1 + .../build/esnext/metrics/MeterProvider.d.ts | 17 + .../api/build/esnext/metrics/MeterProvider.js | 17 + .../build/esnext/metrics/MeterProvider.js.map | 1 + .../api/build/esnext/metrics/Metric.d.ts | 115 + .../api/build/esnext/metrics/Metric.js | 22 + .../api/build/esnext/metrics/Metric.js.map | 1 + .../api/build/esnext/metrics/NoopMeter.d.ts | 82 + .../api/build/esnext/metrics/NoopMeter.js | 113 + .../api/build/esnext/metrics/NoopMeter.js.map | 1 + .../esnext/metrics/NoopMeterProvider.d.ts | 11 + .../build/esnext/metrics/NoopMeterProvider.js | 27 + .../esnext/metrics/NoopMeterProvider.js.map | 1 + .../esnext/metrics/ObservableResult.d.ts | 31 + .../build/esnext/metrics/ObservableResult.js | 17 + .../esnext/metrics/ObservableResult.js.map | 1 + .../esnext/platform/browser/globalThis.d.ts | 10 + .../esnext/platform/browser/globalThis.js | 35 + .../esnext/platform/browser/globalThis.js.map | 1 + .../build/esnext/platform/browser/index.d.ts | 2 + .../build/esnext/platform/browser/index.js | 17 + .../esnext/platform/browser/index.js.map | 1 + .../api/build/esnext/platform/index.d.ts | 2 + .../api/build/esnext/platform/index.js | 17 + .../api/build/esnext/platform/index.js.map | 1 + .../esnext/platform/node/globalThis.d.ts | 3 + .../build/esnext/platform/node/globalThis.js | 19 + .../esnext/platform/node/globalThis.js.map | 1 + .../api/build/esnext/platform/node/index.d.ts | 2 + .../api/build/esnext/platform/node/index.js | 17 + .../build/esnext/platform/node/index.js.map | 1 + .../api/build/esnext/propagation-api.d.ts | 4 + .../api/build/esnext/propagation-api.js | 21 + .../api/build/esnext/propagation-api.js.map | 1 + .../propagation/NoopTextMapPropagator.d.ts | 13 + .../propagation/NoopTextMapPropagator.js | 30 + .../propagation/NoopTextMapPropagator.js.map | 1 + .../esnext/propagation/TextMapPropagator.d.ts | 84 + .../esnext/propagation/TextMapPropagator.js | 38 + .../propagation/TextMapPropagator.js.map | 1 + .../api/build/esnext/trace-api.d.ts | 4 + .../api/build/esnext/trace-api.js | 21 + .../api/build/esnext/trace-api.js.map | 1 + .../build/esnext/trace/NonRecordingSpan.d.ts | 28 + .../build/esnext/trace/NonRecordingSpan.js | 65 + .../esnext/trace/NonRecordingSpan.js.map | 1 + .../api/build/esnext/trace/NoopTracer.d.ts | 14 + .../api/build/esnext/trace/NoopTracer.js | 71 + .../api/build/esnext/trace/NoopTracer.js.map | 1 + .../esnext/trace/NoopTracerProvider.d.ts | 13 + .../build/esnext/trace/NoopTracerProvider.js | 28 + .../esnext/trace/NoopTracerProvider.js.map | 1 + .../api/build/esnext/trace/ProxyTracer.d.ts | 27 + .../api/build/esnext/trace/ProxyTracer.js | 51 + .../api/build/esnext/trace/ProxyTracer.js.map | 1 + .../esnext/trace/ProxyTracerProvider.d.ts | 25 + .../build/esnext/trace/ProxyTracerProvider.js | 50 + .../esnext/trace/ProxyTracerProvider.js.map | 1 + .../api/build/esnext/trace/Sampler.d.ts | 31 + .../api/build/esnext/trace/Sampler.js | 17 + .../api/build/esnext/trace/Sampler.js.map | 1 + .../build/esnext/trace/SamplingResult.d.ts | 49 + .../api/build/esnext/trace/SamplingResult.js | 39 + .../build/esnext/trace/SamplingResult.js.map | 1 + .../api/build/esnext/trace/SpanOptions.d.ts | 23 + .../api/build/esnext/trace/SpanOptions.js | 17 + .../api/build/esnext/trace/SpanOptions.js.map | 1 + .../api/build/esnext/trace/attributes.d.ts | 10 + .../api/build/esnext/trace/attributes.js | 17 + .../api/build/esnext/trace/attributes.js.map | 1 + .../api/build/esnext/trace/context-utils.d.ts | 41 + .../api/build/esnext/trace/context-utils.js | 73 + .../build/esnext/trace/context-utils.js.map | 1 + .../trace/internal/tracestate-impl.d.ts | 22 + .../esnext/trace/internal/tracestate-impl.js | 99 + .../trace/internal/tracestate-impl.js.map | 1 + .../trace/internal/tracestate-validators.d.ts | 15 + .../trace/internal/tracestate-validators.js | 41 + .../internal/tracestate-validators.js.map | 1 + .../build/esnext/trace/internal/utils.d.ts | 3 + .../api/build/esnext/trace/internal/utils.js | 20 + .../build/esnext/trace/internal/utils.js.map | 1 + .../esnext/trace/invalid-span-constants.d.ts | 5 + .../esnext/trace/invalid-span-constants.js | 24 + .../trace/invalid-span-constants.js.map | 1 + .../api/build/esnext/trace/link.d.ts | 26 + .../api/build/esnext/trace/link.js | 17 + .../api/build/esnext/trace/link.js.map | 1 + .../api/build/esnext/trace/span.d.ts | 120 + .../api/build/esnext/trace/span.js | 17 + .../api/build/esnext/trace/span.js.map | 1 + .../api/build/esnext/trace/span_context.d.ts | 53 + .../api/build/esnext/trace/span_context.js | 17 + .../build/esnext/trace/span_context.js.map | 1 + .../api/build/esnext/trace/span_kind.d.ts | 27 + .../api/build/esnext/trace/span_kind.js | 43 + .../api/build/esnext/trace/span_kind.js.map | 1 + .../build/esnext/trace/spancontext-utils.d.ts | 17 + .../build/esnext/trace/spancontext-utils.js | 42 + .../esnext/trace/spancontext-utils.js.map | 1 + .../api/build/esnext/trace/status.d.ts | 25 + .../api/build/esnext/trace/status.js | 20 + .../api/build/esnext/trace/status.js.map | 1 + .../api/build/esnext/trace/trace_flags.d.ts | 7 + .../api/build/esnext/trace/trace_flags.js | 23 + .../api/build/esnext/trace/trace_flags.js.map | 1 + .../api/build/esnext/trace/trace_state.d.ts | 38 + .../api/build/esnext/trace/trace_state.js | 17 + .../api/build/esnext/trace/trace_state.js.map | 1 + .../api/build/esnext/trace/tracer.d.ts | 71 + .../api/build/esnext/trace/tracer.js | 17 + .../api/build/esnext/trace/tracer.js.map | 1 + .../build/esnext/trace/tracer_options.d.ts | 10 + .../api/build/esnext/trace/tracer_options.js | 17 + .../build/esnext/trace/tracer_options.js.map | 1 + .../build/esnext/trace/tracer_provider.d.ts | 21 + .../api/build/esnext/trace/tracer_provider.js | 17 + .../build/esnext/trace/tracer_provider.js.map | 1 + .../api/build/esnext/version.d.ts | 2 + .../api/build/esnext/version.js | 18 + .../api/build/esnext/version.js.map | 1 + .../api/build/src/api/context.d.ts | 41 + .../api/build/src/api/context.js | 81 + .../api/build/src/api/context.js.map | 1 + .../api/build/src/api/diag.d.ts | 30 + .../@opentelemetry/api/build/src/api/diag.js | 93 + .../api/build/src/api/diag.js.map | 1 + .../api/build/src/api/metrics.d.ts | 28 + .../api/build/src/api/metrics.js | 61 + .../api/build/src/api/metrics.js.map | 1 + .../api/build/src/api/propagation.d.ts | 49 + .../api/build/src/api/propagation.js | 89 + .../api/build/src/api/propagation.js.map | 1 + .../api/build/src/api/trace.d.ts | 40 + .../@opentelemetry/api/build/src/api/trace.js | 79 + .../api/build/src/api/trace.js.map | 1 + .../build/src/baggage/context-helpers.d.ts | 29 + .../api/build/src/baggage/context-helpers.js | 63 + .../build/src/baggage/context-helpers.js.map | 1 + .../src/baggage/internal/baggage-impl.d.ts | 12 + .../src/baggage/internal/baggage-impl.js | 55 + .../src/baggage/internal/baggage-impl.js.map | 1 + .../build/src/baggage/internal/symbol.d.ts | 5 + .../api/build/src/baggage/internal/symbol.js | 23 + .../build/src/baggage/internal/symbol.js.map | 1 + .../api/build/src/baggage/types.d.ts | 60 + .../api/build/src/baggage/types.js | 18 + .../api/build/src/baggage/types.js.map | 1 + .../api/build/src/baggage/utils.d.ts | 15 + .../api/build/src/baggage/utils.js | 51 + .../api/build/src/baggage/utils.js.map | 1 + .../api/build/src/common/Attributes.d.ts | 15 + .../api/build/src/common/Attributes.js | 18 + .../api/build/src/common/Attributes.js.map | 1 + .../api/build/src/common/Exception.d.ts | 26 + .../api/build/src/common/Exception.js | 18 + .../api/build/src/common/Exception.js.map | 1 + .../api/build/src/common/Time.d.ts | 20 + .../api/build/src/common/Time.js | 3 + .../api/build/src/common/Time.js.map | 1 + .../api/build/src/context-api.d.ts | 4 + .../api/build/src/context-api.js | 24 + .../api/build/src/context-api.js.map | 1 + .../build/src/context/NoopContextManager.d.ts | 9 + .../build/src/context/NoopContextManager.js | 38 + .../src/context/NoopContextManager.js.map | 1 + .../api/build/src/context/context.d.ts | 6 + .../api/build/src/context/context.js | 55 + .../api/build/src/context/context.js.map | 1 + .../api/build/src/context/types.d.ts | 52 + .../api/build/src/context/types.js | 18 + .../api/build/src/context/types.js.map | 1 + .../api/build/src/diag-api.d.ts | 9 + .../@opentelemetry/api/build/src/diag-api.js | 29 + .../api/build/src/diag-api.js.map | 1 + .../api/build/src/diag/ComponentLogger.d.ts | 20 + .../api/build/src/diag/ComponentLogger.js | 59 + .../api/build/src/diag/ComponentLogger.js.map | 1 + .../api/build/src/diag/consoleLogger.d.ts | 38 + .../api/build/src/diag/consoleLogger.js | 57 + .../api/build/src/diag/consoleLogger.js.map | 1 + .../src/diag/internal/logLevelLogger.d.ts | 3 + .../build/src/diag/internal/logLevelLogger.js | 45 + .../src/diag/internal/logLevelLogger.js.map | 1 + .../build/src/diag/internal/noopLogger.d.ts | 8 + .../api/build/src/diag/internal/noopLogger.js | 35 + .../build/src/diag/internal/noopLogger.js.map | 1 + .../api/build/src/diag/types.d.ts | 100 + .../api/build/src/diag/types.js | 44 + .../api/build/src/diag/types.js.map | 1 + .../api/build/src/experimental/index.d.ts | 3 + .../api/build/src/experimental/index.js | 22 + .../api/build/src/experimental/index.js.map | 1 + .../experimental/trace/SugaredOptions.d.ts | 13 + .../src/experimental/trace/SugaredOptions.js | 18 + .../experimental/trace/SugaredOptions.js.map | 1 + .../src/experimental/trace/SugaredTracer.d.ts | 64 + .../src/experimental/trace/SugaredTracer.js | 93 + .../experimental/trace/SugaredTracer.js.map | 1 + .../@opentelemetry/api/build/src/index.d.ts | 54 + .../@opentelemetry/api/build/src/index.js | 81 + .../@opentelemetry/api/build/src/index.js.map | 1 + .../api/build/src/internal/global-utils.d.ts | 18 + .../api/build/src/internal/global-utils.js | 64 + .../build/src/internal/global-utils.js.map | 1 + .../api/build/src/internal/semver.d.ts | 34 + .../api/build/src/internal/semver.js | 122 + .../api/build/src/internal/semver.js.map | 1 + .../api/build/src/metrics-api.d.ts | 4 + .../api/build/src/metrics-api.js | 24 + .../api/build/src/metrics-api.js.map | 1 + .../api/build/src/metrics/Meter.d.ts | 110 + .../api/build/src/metrics/Meter.js | 18 + .../api/build/src/metrics/Meter.js.map | 1 + .../api/build/src/metrics/MeterProvider.d.ts | 17 + .../api/build/src/metrics/MeterProvider.js | 18 + .../build/src/metrics/MeterProvider.js.map | 1 + .../api/build/src/metrics/Metric.d.ts | 115 + .../api/build/src/metrics/Metric.js | 25 + .../api/build/src/metrics/Metric.js.map | 1 + .../api/build/src/metrics/NoopMeter.d.ts | 82 + .../api/build/src/metrics/NoopMeter.js | 127 + .../api/build/src/metrics/NoopMeter.js.map | 1 + .../build/src/metrics/NoopMeterProvider.d.ts | 11 + .../build/src/metrics/NoopMeterProvider.js | 31 + .../src/metrics/NoopMeterProvider.js.map | 1 + .../build/src/metrics/ObservableResult.d.ts | 31 + .../api/build/src/metrics/ObservableResult.js | 18 + .../build/src/metrics/ObservableResult.js.map | 1 + .../src/platform/browser/globalThis.d.ts | 10 + .../build/src/platform/browser/globalThis.js | 38 + .../src/platform/browser/globalThis.js.map | 1 + .../api/build/src/platform/browser/index.d.ts | 2 + .../api/build/src/platform/browser/index.js | 29 + .../build/src/platform/browser/index.js.map | 1 + .../api/build/src/platform/index.d.ts | 2 + .../api/build/src/platform/index.js | 29 + .../api/build/src/platform/index.js.map | 1 + .../build/src/platform/node/globalThis.d.ts | 3 + .../api/build/src/platform/node/globalThis.js | 22 + .../build/src/platform/node/globalThis.js.map | 1 + .../api/build/src/platform/node/index.d.ts | 2 + .../api/build/src/platform/node/index.js | 29 + .../api/build/src/platform/node/index.js.map | 1 + .../api/build/src/propagation-api.d.ts | 4 + .../api/build/src/propagation-api.js | 24 + .../api/build/src/propagation-api.js.map | 1 + .../propagation/NoopTextMapPropagator.d.ts | 13 + .../src/propagation/NoopTextMapPropagator.js | 34 + .../propagation/NoopTextMapPropagator.js.map | 1 + .../src/propagation/TextMapPropagator.d.ts | 84 + .../src/propagation/TextMapPropagator.js | 41 + .../src/propagation/TextMapPropagator.js.map | 1 + .../api/build/src/trace-api.d.ts | 4 + .../@opentelemetry/api/build/src/trace-api.js | 24 + .../api/build/src/trace-api.js.map | 1 + .../api/build/src/trace/NonRecordingSpan.d.ts | 28 + .../api/build/src/trace/NonRecordingSpan.js | 69 + .../build/src/trace/NonRecordingSpan.js.map | 1 + .../api/build/src/trace/NoopTracer.d.ts | 14 + .../api/build/src/trace/NoopTracer.js | 75 + .../api/build/src/trace/NoopTracer.js.map | 1 + .../build/src/trace/NoopTracerProvider.d.ts | 13 + .../api/build/src/trace/NoopTracerProvider.js | 32 + .../build/src/trace/NoopTracerProvider.js.map | 1 + .../api/build/src/trace/ProxyTracer.d.ts | 27 + .../api/build/src/trace/ProxyTracer.js | 55 + .../api/build/src/trace/ProxyTracer.js.map | 1 + .../build/src/trace/ProxyTracerProvider.d.ts | 25 + .../build/src/trace/ProxyTracerProvider.js | 54 + .../src/trace/ProxyTracerProvider.js.map | 1 + .../api/build/src/trace/Sampler.d.ts | 31 + .../api/build/src/trace/Sampler.js | 18 + .../api/build/src/trace/Sampler.js.map | 1 + .../api/build/src/trace/SamplingResult.d.ts | 49 + .../api/build/src/trace/SamplingResult.js | 42 + .../api/build/src/trace/SamplingResult.js.map | 1 + .../api/build/src/trace/SpanOptions.d.ts | 23 + .../api/build/src/trace/SpanOptions.js | 18 + .../api/build/src/trace/SpanOptions.js.map | 1 + .../api/build/src/trace/attributes.d.ts | 10 + .../api/build/src/trace/attributes.js | 18 + .../api/build/src/trace/attributes.js.map | 1 + .../api/build/src/trace/context-utils.d.ts | 41 + .../api/build/src/trace/context-utils.js | 82 + .../api/build/src/trace/context-utils.js.map | 1 + .../src/trace/internal/tracestate-impl.d.ts | 22 + .../src/trace/internal/tracestate-impl.js | 103 + .../src/trace/internal/tracestate-impl.js.map | 1 + .../trace/internal/tracestate-validators.d.ts | 15 + .../trace/internal/tracestate-validators.js | 46 + .../internal/tracestate-validators.js.map | 1 + .../api/build/src/trace/internal/utils.d.ts | 3 + .../api/build/src/trace/internal/utils.js | 24 + .../api/build/src/trace/internal/utils.js.map | 1 + .../src/trace/invalid-span-constants.d.ts | 5 + .../build/src/trace/invalid-span-constants.js | 27 + .../src/trace/invalid-span-constants.js.map | 1 + .../api/build/src/trace/link.d.ts | 26 + .../api/build/src/trace/link.js | 18 + .../api/build/src/trace/link.js.map | 1 + .../api/build/src/trace/span.d.ts | 120 + .../api/build/src/trace/span.js | 18 + .../api/build/src/trace/span.js.map | 1 + .../api/build/src/trace/span_context.d.ts | 53 + .../api/build/src/trace/span_context.js | 18 + .../api/build/src/trace/span_context.js.map | 1 + .../api/build/src/trace/span_kind.d.ts | 27 + .../api/build/src/trace/span_kind.js | 46 + .../api/build/src/trace/span_kind.js.map | 1 + .../build/src/trace/spancontext-utils.d.ts | 17 + .../api/build/src/trace/spancontext-utils.js | 49 + .../build/src/trace/spancontext-utils.js.map | 1 + .../api/build/src/trace/status.d.ts | 25 + .../api/build/src/trace/status.js | 23 + .../api/build/src/trace/status.js.map | 1 + .../api/build/src/trace/trace_flags.d.ts | 7 + .../api/build/src/trace/trace_flags.js | 26 + .../api/build/src/trace/trace_flags.js.map | 1 + .../api/build/src/trace/trace_state.d.ts | 38 + .../api/build/src/trace/trace_state.js | 18 + .../api/build/src/trace/trace_state.js.map | 1 + .../api/build/src/trace/tracer.d.ts | 71 + .../api/build/src/trace/tracer.js | 18 + .../api/build/src/trace/tracer.js.map | 1 + .../api/build/src/trace/tracer_options.d.ts | 10 + .../api/build/src/trace/tracer_options.js | 18 + .../api/build/src/trace/tracer_options.js.map | 1 + .../api/build/src/trace/tracer_provider.d.ts | 21 + .../api/build/src/trace/tracer_provider.js | 18 + .../build/src/trace/tracer_provider.js.map | 1 + .../@opentelemetry/api/build/src/version.d.ts | 2 + .../@opentelemetry/api/build/src/version.js | 21 + .../api/build/src/version.js.map | 1 + node_modules/@opentelemetry/api/package.json | 113 + node_modules/@protobufjs/aspromise/LICENSE | 26 + node_modules/@protobufjs/aspromise/README.md | 13 + node_modules/@protobufjs/aspromise/index.d.ts | 13 + node_modules/@protobufjs/aspromise/index.js | 52 + .../@protobufjs/aspromise/package.json | 21 + .../@protobufjs/aspromise/tests/index.js | 130 + node_modules/@protobufjs/base64/LICENSE | 26 + node_modules/@protobufjs/base64/README.md | 19 + node_modules/@protobufjs/base64/index.d.ts | 32 + node_modules/@protobufjs/base64/index.js | 139 + node_modules/@protobufjs/base64/package.json | 21 + .../@protobufjs/base64/tests/index.js | 46 + node_modules/@protobufjs/codegen/LICENSE | 26 + node_modules/@protobufjs/codegen/README.md | 49 + node_modules/@protobufjs/codegen/index.d.ts | 31 + node_modules/@protobufjs/codegen/index.js | 99 + node_modules/@protobufjs/codegen/package.json | 13 + .../@protobufjs/codegen/tests/index.js | 13 + node_modules/@protobufjs/eventemitter/LICENSE | 26 + .../@protobufjs/eventemitter/README.md | 22 + .../@protobufjs/eventemitter/index.d.ts | 43 + .../@protobufjs/eventemitter/index.js | 76 + .../@protobufjs/eventemitter/package.json | 21 + .../@protobufjs/eventemitter/tests/index.js | 47 + node_modules/@protobufjs/fetch/LICENSE | 26 + node_modules/@protobufjs/fetch/README.md | 13 + node_modules/@protobufjs/fetch/index.d.ts | 56 + node_modules/@protobufjs/fetch/index.js | 115 + node_modules/@protobufjs/fetch/package.json | 25 + node_modules/@protobufjs/fetch/tests/index.js | 16 + node_modules/@protobufjs/float/LICENSE | 26 + node_modules/@protobufjs/float/README.md | 102 + node_modules/@protobufjs/float/bench/index.js | 87 + node_modules/@protobufjs/float/bench/suite.js | 46 + node_modules/@protobufjs/float/index.d.ts | 83 + node_modules/@protobufjs/float/index.js | 335 + node_modules/@protobufjs/float/package.json | 26 + node_modules/@protobufjs/float/tests/index.js | 100 + node_modules/@protobufjs/inquire/.npmignore | 3 + node_modules/@protobufjs/inquire/LICENSE | 26 + node_modules/@protobufjs/inquire/README.md | 13 + node_modules/@protobufjs/inquire/index.d.ts | 9 + node_modules/@protobufjs/inquire/index.js | 17 + node_modules/@protobufjs/inquire/package.json | 21 + .../@protobufjs/inquire/tests/data/array.js | 1 + .../inquire/tests/data/emptyArray.js | 1 + .../inquire/tests/data/emptyObject.js | 1 + .../@protobufjs/inquire/tests/data/object.js | 1 + .../@protobufjs/inquire/tests/index.js | 20 + node_modules/@protobufjs/path/LICENSE | 26 + node_modules/@protobufjs/path/README.md | 19 + node_modules/@protobufjs/path/index.d.ts | 22 + node_modules/@protobufjs/path/index.js | 65 + node_modules/@protobufjs/path/package.json | 21 + node_modules/@protobufjs/path/tests/index.js | 60 + node_modules/@protobufjs/pool/.npmignore | 3 + node_modules/@protobufjs/pool/LICENSE | 26 + node_modules/@protobufjs/pool/README.md | 13 + node_modules/@protobufjs/pool/index.d.ts | 32 + node_modules/@protobufjs/pool/index.js | 48 + node_modules/@protobufjs/pool/package.json | 21 + node_modules/@protobufjs/pool/tests/index.js | 33 + node_modules/@protobufjs/utf8/.npmignore | 3 + node_modules/@protobufjs/utf8/LICENSE | 26 + node_modules/@protobufjs/utf8/README.md | 20 + node_modules/@protobufjs/utf8/index.d.ts | 24 + node_modules/@protobufjs/utf8/index.js | 105 + node_modules/@protobufjs/utf8/package.json | 21 + .../@protobufjs/utf8/tests/data/utf8.txt | 216 + node_modules/@protobufjs/utf8/tests/index.js | 57 + node_modules/@tootallnate/once/LICENSE | 21 + node_modules/@tootallnate/once/README.md | 93 + .../@tootallnate/once/dist/index.d.ts | 7 + node_modules/@tootallnate/once/dist/index.js | 24 + .../@tootallnate/once/dist/index.js.map | 1 + .../once/dist/overloaded-parameters.d.ts | 231 + .../once/dist/overloaded-parameters.js | 3 + .../once/dist/overloaded-parameters.js.map | 1 + .../@tootallnate/once/dist/types.d.ts | 17 + node_modules/@tootallnate/once/dist/types.js | 3 + .../@tootallnate/once/dist/types.js.map | 1 + node_modules/@tootallnate/once/package.json | 52 + node_modules/@types/body-parser/LICENSE | 21 + node_modules/@types/body-parser/README.md | 15 + node_modules/@types/body-parser/index.d.ts | 95 + node_modules/@types/body-parser/package.json | 64 + node_modules/@types/caseless/LICENSE | 21 + node_modules/@types/caseless/README.md | 48 + node_modules/@types/caseless/index.d.ts | 29 + node_modules/@types/caseless/package.json | 35 + node_modules/@types/connect/LICENSE | 21 + node_modules/@types/connect/README.md | 15 + node_modules/@types/connect/index.d.ts | 91 + node_modules/@types/connect/package.json | 32 + .../@types/express-serve-static-core/LICENSE | 21 + .../express-serve-static-core/README.md | 15 + .../express-serve-static-core/index.d.ts | 1295 + .../express-serve-static-core/package.json | 51 + node_modules/@types/express/LICENSE | 21 + node_modules/@types/express/README.md | 15 + node_modules/@types/express/index.d.ts | 128 + node_modules/@types/express/package.json | 46 + node_modules/@types/http-errors/LICENSE | 21 + node_modules/@types/http-errors/README.md | 15 + node_modules/@types/http-errors/index.d.ts | 77 + node_modules/@types/http-errors/package.json | 36 + node_modules/@types/jsonwebtoken/LICENSE | 21 + node_modules/@types/jsonwebtoken/README.md | 15 + node_modules/@types/jsonwebtoken/index.d.ts | 271 + node_modules/@types/jsonwebtoken/package.json | 84 + node_modules/@types/long/LICENSE | 21 + node_modules/@types/long/README.md | 16 + node_modules/@types/long/index.d.ts | 389 + node_modules/@types/long/package.json | 25 + node_modules/@types/mime/LICENSE | 21 + node_modules/@types/mime/Mime.d.ts | 10 + node_modules/@types/mime/README.md | 15 + node_modules/@types/mime/index.d.ts | 31 + node_modules/@types/mime/lite.d.ts | 7 + node_modules/@types/mime/package.json | 30 + node_modules/@types/ms/LICENSE | 21 + node_modules/@types/ms/README.md | 82 + node_modules/@types/ms/index.d.ts | 63 + node_modules/@types/ms/package.json | 26 + node_modules/@types/node/LICENSE | 21 + node_modules/@types/node/README.md | 15 + node_modules/@types/node/assert.d.ts | 1078 + node_modules/@types/node/assert/strict.d.ts | 111 + node_modules/@types/node/async_hooks.d.ts | 603 + node_modules/@types/node/buffer.buffer.d.ts | 472 + node_modules/@types/node/buffer.d.ts | 1934 ++ node_modules/@types/node/child_process.d.ts | 1476 ++ node_modules/@types/node/cluster.d.ts | 578 + .../@types/node/compatibility/disposable.d.ts | 14 + .../@types/node/compatibility/index.d.ts | 9 + .../@types/node/compatibility/indexable.d.ts | 20 + .../@types/node/compatibility/iterators.d.ts | 20 + node_modules/@types/node/console.d.ts | 452 + node_modules/@types/node/constants.d.ts | 21 + node_modules/@types/node/crypto.d.ts | 4545 ++++ node_modules/@types/node/dgram.d.ts | 600 + .../@types/node/diagnostics_channel.d.ts | 578 + node_modules/@types/node/dns.d.ts | 923 + node_modules/@types/node/dns/promises.d.ts | 503 + node_modules/@types/node/domain.d.ts | 170 + node_modules/@types/node/events.d.ts | 976 + node_modules/@types/node/fs.d.ts | 4461 ++++ node_modules/@types/node/fs/promises.d.ts | 1295 + node_modules/@types/node/globals.d.ts | 172 + .../@types/node/globals.typedarray.d.ts | 38 + node_modules/@types/node/http.d.ts | 2089 ++ node_modules/@types/node/http2.d.ts | 2644 +++ node_modules/@types/node/https.d.ts | 579 + node_modules/@types/node/index.d.ts | 97 + node_modules/@types/node/inspector.d.ts | 253 + .../@types/node/inspector.generated.d.ts | 4052 ++++ node_modules/@types/node/module.d.ts | 891 + node_modules/@types/node/net.d.ts | 1057 + node_modules/@types/node/os.d.ts | 506 + node_modules/@types/node/package.json | 145 + node_modules/@types/node/path.d.ts | 200 + node_modules/@types/node/perf_hooks.d.ts | 968 + node_modules/@types/node/process.d.ts | 2070 ++ node_modules/@types/node/punycode.d.ts | 117 + node_modules/@types/node/querystring.d.ts | 152 + node_modules/@types/node/readline.d.ts | 594 + .../@types/node/readline/promises.d.ts | 161 + node_modules/@types/node/repl.d.ts | 428 + node_modules/@types/node/sea.d.ts | 153 + node_modules/@types/node/sqlite.d.ts | 721 + node_modules/@types/node/stream.d.ts | 1664 ++ .../@types/node/stream/consumers.d.ts | 38 + node_modules/@types/node/stream/promises.d.ts | 90 + node_modules/@types/node/stream/web.d.ts | 622 + node_modules/@types/node/string_decoder.d.ts | 67 + node_modules/@types/node/test.d.ts | 2162 ++ node_modules/@types/node/timers.d.ts | 287 + node_modules/@types/node/timers/promises.d.ts | 108 + node_modules/@types/node/tls.d.ts | 1315 + node_modules/@types/node/trace_events.d.ts | 197 + .../@types/node/ts5.6/buffer.buffer.d.ts | 468 + .../@types/node/ts5.6/globals.typedarray.d.ts | 34 + node_modules/@types/node/ts5.6/index.d.ts | 97 + node_modules/@types/node/tty.d.ts | 208 + node_modules/@types/node/url.d.ts | 984 + node_modules/@types/node/util.d.ts | 2606 ++ node_modules/@types/node/v8.d.ts | 920 + node_modules/@types/node/vm.d.ts | 1000 + node_modules/@types/node/wasi.d.ts | 181 + .../node/web-globals/abortcontroller.d.ts | 34 + .../@types/node/web-globals/domexception.d.ts | 68 + .../@types/node/web-globals/events.d.ts | 97 + .../@types/node/web-globals/fetch.d.ts | 46 + .../@types/node/web-globals/navigator.d.ts | 22 + .../@types/node/web-globals/storage.d.ts | 24 + node_modules/@types/node/worker_threads.d.ts | 784 + node_modules/@types/node/zlib.d.ts | 683 + node_modules/@types/qs/LICENSE | 21 + node_modules/@types/qs/README.md | 15 + node_modules/@types/qs/index.d.ts | 82 + node_modules/@types/qs/package.json | 66 + node_modules/@types/range-parser/LICENSE | 21 + node_modules/@types/range-parser/README.md | 53 + node_modules/@types/range-parser/index.d.ts | 34 + node_modules/@types/range-parser/package.json | 25 + node_modules/@types/request/LICENSE | 21 + node_modules/@types/request/README.md | 15 + node_modules/@types/request/index.d.ts | 395 + node_modules/@types/request/package.json | 71 + node_modules/@types/send/LICENSE | 21 + node_modules/@types/send/README.md | 15 + node_modules/@types/send/index.d.ts | 187 + node_modules/@types/send/package.json | 38 + node_modules/@types/serve-static/LICENSE | 21 + node_modules/@types/serve-static/README.md | 15 + node_modules/@types/serve-static/index.d.ts | 107 + .../node_modules/@types/send/LICENSE | 21 + .../node_modules/@types/send/README.md | 15 + .../node_modules/@types/send/index.d.ts | 225 + .../node_modules/@types/send/package.json | 39 + node_modules/@types/serve-static/package.json | 45 + node_modules/@types/tough-cookie/LICENSE | 21 + node_modules/@types/tough-cookie/README.md | 15 + node_modules/@types/tough-cookie/index.d.ts | 321 + node_modules/@types/tough-cookie/package.json | 35 + node_modules/abort-controller/LICENSE | 21 + node_modules/abort-controller/README.md | 98 + node_modules/abort-controller/browser.js | 13 + node_modules/abort-controller/browser.mjs | 11 + .../dist/abort-controller.d.ts | 43 + .../abort-controller/dist/abort-controller.js | 127 + .../dist/abort-controller.js.map | 1 + .../dist/abort-controller.mjs | 118 + .../dist/abort-controller.mjs.map | 1 + .../dist/abort-controller.umd.js | 5 + .../dist/abort-controller.umd.js.map | 1 + node_modules/abort-controller/package.json | 97 + node_modules/abort-controller/polyfill.js | 21 + node_modules/abort-controller/polyfill.mjs | 19 + node_modules/agent-base/LICENSE | 22 + node_modules/agent-base/README.md | 69 + node_modules/agent-base/dist/helpers.d.ts | 15 + node_modules/agent-base/dist/helpers.d.ts.map | 1 + node_modules/agent-base/dist/helpers.js | 66 + node_modules/agent-base/dist/helpers.js.map | 1 + node_modules/agent-base/dist/index.d.ts | 41 + node_modules/agent-base/dist/index.d.ts.map | 1 + node_modules/agent-base/dist/index.js | 178 + node_modules/agent-base/dist/index.js.map | 1 + node_modules/agent-base/package.json | 46 + node_modules/ansi-regex/index.d.ts | 37 + node_modules/ansi-regex/index.js | 10 + node_modules/ansi-regex/license | 9 + node_modules/ansi-regex/package.json | 55 + node_modules/ansi-regex/readme.md | 78 + node_modules/ansi-styles/index.d.ts | 345 + node_modules/ansi-styles/index.js | 163 + node_modules/ansi-styles/license | 9 + node_modules/ansi-styles/package.json | 56 + node_modules/ansi-styles/readme.md | 152 + node_modules/arrify/index.d.ts | 38 + node_modules/arrify/index.js | 23 + node_modules/arrify/license | 9 + node_modules/arrify/package.json | 35 + node_modules/arrify/readme.md | 39 + node_modules/async-retry/LICENSE.md | 21 + node_modules/async-retry/README.md | 53 + node_modules/async-retry/lib/index.js | 61 + node_modules/async-retry/package.json | 55 + node_modules/asynckit/LICENSE | 21 + node_modules/asynckit/README.md | 233 + node_modules/asynckit/bench.js | 76 + node_modules/asynckit/index.js | 6 + node_modules/asynckit/lib/abort.js | 29 + node_modules/asynckit/lib/async.js | 34 + node_modules/asynckit/lib/defer.js | 26 + node_modules/asynckit/lib/iterate.js | 75 + .../asynckit/lib/readable_asynckit.js | 91 + .../asynckit/lib/readable_parallel.js | 25 + node_modules/asynckit/lib/readable_serial.js | 25 + .../asynckit/lib/readable_serial_ordered.js | 29 + node_modules/asynckit/lib/state.js | 37 + node_modules/asynckit/lib/streamify.js | 141 + node_modules/asynckit/lib/terminator.js | 29 + node_modules/asynckit/package.json | 63 + node_modules/asynckit/parallel.js | 43 + node_modules/asynckit/serial.js | 17 + node_modules/asynckit/serialOrdered.js | 75 + node_modules/asynckit/stream.js | 21 + node_modules/base64-js/LICENSE | 21 + node_modules/base64-js/README.md | 34 + node_modules/base64-js/base64js.min.js | 1 + node_modules/base64-js/index.d.ts | 3 + node_modules/base64-js/index.js | 150 + node_modules/base64-js/package.json | 47 + node_modules/bignumber.js/CHANGELOG.md | 381 + node_modules/bignumber.js/LICENCE.md | 26 + node_modules/bignumber.js/README.md | 289 + node_modules/bignumber.js/bignumber.d.mts | 6 + node_modules/bignumber.js/bignumber.d.ts | 5 + node_modules/bignumber.js/bignumber.js | 2922 +++ node_modules/bignumber.js/bignumber.mjs | 2907 +++ node_modules/bignumber.js/doc/API.html | 2249 ++ node_modules/bignumber.js/package.json | 60 + node_modules/bignumber.js/types.d.ts | 1821 ++ .../buffer-equal-constant-time/.npmignore | 2 + .../buffer-equal-constant-time/.travis.yml | 4 + .../buffer-equal-constant-time/LICENSE.txt | 12 + .../buffer-equal-constant-time/README.md | 50 + .../buffer-equal-constant-time/index.js | 41 + .../buffer-equal-constant-time/package.json | 21 + .../buffer-equal-constant-time/test.js | 42 + .../call-bind-apply-helpers/.eslintrc | 17 + .../.github/FUNDING.yml | 12 + node_modules/call-bind-apply-helpers/.nycrc | 9 + .../call-bind-apply-helpers/CHANGELOG.md | 30 + node_modules/call-bind-apply-helpers/LICENSE | 21 + .../call-bind-apply-helpers/README.md | 62 + .../call-bind-apply-helpers/actualApply.d.ts | 1 + .../call-bind-apply-helpers/actualApply.js | 10 + .../call-bind-apply-helpers/applyBind.d.ts | 19 + .../call-bind-apply-helpers/applyBind.js | 10 + .../functionApply.d.ts | 1 + .../call-bind-apply-helpers/functionApply.js | 4 + .../call-bind-apply-helpers/functionCall.d.ts | 1 + .../call-bind-apply-helpers/functionCall.js | 4 + .../call-bind-apply-helpers/index.d.ts | 64 + node_modules/call-bind-apply-helpers/index.js | 15 + .../call-bind-apply-helpers/package.json | 85 + .../call-bind-apply-helpers/reflectApply.d.ts | 3 + .../call-bind-apply-helpers/reflectApply.js | 4 + .../call-bind-apply-helpers/test/index.js | 63 + .../call-bind-apply-helpers/tsconfig.json | 9 + node_modules/cliui/CHANGELOG.md | 139 + node_modules/cliui/LICENSE.txt | 14 + node_modules/cliui/README.md | 141 + node_modules/cliui/build/index.cjs | 302 + node_modules/cliui/build/index.d.cts | 43 + node_modules/cliui/build/lib/index.js | 287 + node_modules/cliui/build/lib/string-utils.js | 27 + node_modules/cliui/index.mjs | 13 + node_modules/cliui/package.json | 83 + node_modules/color-convert/CHANGELOG.md | 54 + node_modules/color-convert/LICENSE | 21 + node_modules/color-convert/README.md | 68 + node_modules/color-convert/conversions.js | 839 + node_modules/color-convert/index.js | 81 + node_modules/color-convert/package.json | 48 + node_modules/color-convert/route.js | 97 + node_modules/color-name/LICENSE | 8 + node_modules/color-name/README.md | 11 + node_modules/color-name/index.js | 152 + node_modules/color-name/package.json | 28 + node_modules/combined-stream/License | 19 + node_modules/combined-stream/Readme.md | 138 + .../combined-stream/lib/combined_stream.js | 208 + node_modules/combined-stream/package.json | 25 + node_modules/combined-stream/yarn.lock | 17 + node_modules/debug/LICENSE | 20 + node_modules/debug/README.md | 481 + node_modules/debug/package.json | 64 + node_modules/debug/src/browser.js | 272 + node_modules/debug/src/common.js | 292 + node_modules/debug/src/index.js | 10 + node_modules/debug/src/node.js | 263 + node_modules/delayed-stream/.npmignore | 1 + node_modules/delayed-stream/License | 19 + node_modules/delayed-stream/Makefile | 7 + node_modules/delayed-stream/Readme.md | 141 + .../delayed-stream/lib/delayed_stream.js | 107 + node_modules/delayed-stream/package.json | 27 + node_modules/dunder-proto/.eslintrc | 5 + node_modules/dunder-proto/.github/FUNDING.yml | 12 + node_modules/dunder-proto/.nycrc | 13 + node_modules/dunder-proto/CHANGELOG.md | 24 + node_modules/dunder-proto/LICENSE | 21 + node_modules/dunder-proto/README.md | 54 + node_modules/dunder-proto/get.d.ts | 5 + node_modules/dunder-proto/get.js | 30 + node_modules/dunder-proto/package.json | 76 + node_modules/dunder-proto/set.d.ts | 5 + node_modules/dunder-proto/set.js | 35 + node_modules/dunder-proto/test/get.js | 34 + node_modules/dunder-proto/test/index.js | 4 + node_modules/dunder-proto/test/set.js | 50 + node_modules/dunder-proto/tsconfig.json | 9 + node_modules/duplexify/.travis.yml | 9 + node_modules/duplexify/LICENSE | 21 + node_modules/duplexify/README.md | 97 + node_modules/duplexify/example.js | 21 + node_modules/duplexify/index.js | 238 + node_modules/duplexify/package.json | 39 + node_modules/duplexify/test.js | 339 + node_modules/ecdsa-sig-formatter/CODEOWNERS | 1 + node_modules/ecdsa-sig-formatter/LICENSE | 201 + node_modules/ecdsa-sig-formatter/README.md | 65 + node_modules/ecdsa-sig-formatter/package.json | 46 + .../src/ecdsa-sig-formatter.d.ts | 17 + .../src/ecdsa-sig-formatter.js | 187 + .../src/param-bytes-for-alg.js | 23 + node_modules/emoji-regex/LICENSE-MIT.txt | 20 + node_modules/emoji-regex/README.md | 73 + node_modules/emoji-regex/es2015/index.js | 6 + node_modules/emoji-regex/es2015/text.js | 6 + node_modules/emoji-regex/index.d.ts | 23 + node_modules/emoji-regex/index.js | 6 + node_modules/emoji-regex/package.json | 50 + node_modules/emoji-regex/text.js | 6 + node_modules/end-of-stream/LICENSE | 21 + node_modules/end-of-stream/README.md | 54 + node_modules/end-of-stream/index.js | 96 + node_modules/end-of-stream/package.json | 37 + node_modules/es-define-property/.eslintrc | 13 + .../es-define-property/.github/FUNDING.yml | 12 + node_modules/es-define-property/.nycrc | 9 + node_modules/es-define-property/CHANGELOG.md | 29 + node_modules/es-define-property/LICENSE | 21 + node_modules/es-define-property/README.md | 49 + node_modules/es-define-property/index.d.ts | 3 + node_modules/es-define-property/index.js | 14 + node_modules/es-define-property/package.json | 81 + node_modules/es-define-property/test/index.js | 56 + node_modules/es-define-property/tsconfig.json | 10 + node_modules/es-errors/.eslintrc | 5 + node_modules/es-errors/.github/FUNDING.yml | 12 + node_modules/es-errors/CHANGELOG.md | 40 + node_modules/es-errors/LICENSE | 21 + node_modules/es-errors/README.md | 55 + node_modules/es-errors/eval.d.ts | 3 + node_modules/es-errors/eval.js | 4 + node_modules/es-errors/index.d.ts | 3 + node_modules/es-errors/index.js | 4 + node_modules/es-errors/package.json | 80 + node_modules/es-errors/range.d.ts | 3 + node_modules/es-errors/range.js | 4 + node_modules/es-errors/ref.d.ts | 3 + node_modules/es-errors/ref.js | 4 + node_modules/es-errors/syntax.d.ts | 3 + node_modules/es-errors/syntax.js | 4 + node_modules/es-errors/test/index.js | 19 + node_modules/es-errors/tsconfig.json | 49 + node_modules/es-errors/type.d.ts | 3 + node_modules/es-errors/type.js | 4 + node_modules/es-errors/uri.d.ts | 3 + node_modules/es-errors/uri.js | 4 + node_modules/es-object-atoms/.eslintrc | 16 + .../es-object-atoms/.github/FUNDING.yml | 12 + node_modules/es-object-atoms/CHANGELOG.md | 37 + node_modules/es-object-atoms/LICENSE | 21 + node_modules/es-object-atoms/README.md | 63 + .../RequireObjectCoercible.d.ts | 3 + .../es-object-atoms/RequireObjectCoercible.js | 11 + node_modules/es-object-atoms/ToObject.d.ts | 7 + node_modules/es-object-atoms/ToObject.js | 10 + node_modules/es-object-atoms/index.d.ts | 3 + node_modules/es-object-atoms/index.js | 4 + node_modules/es-object-atoms/isObject.d.ts | 3 + node_modules/es-object-atoms/isObject.js | 6 + node_modules/es-object-atoms/package.json | 80 + node_modules/es-object-atoms/test/index.js | 38 + node_modules/es-object-atoms/tsconfig.json | 6 + node_modules/es-set-tostringtag/.eslintrc | 13 + node_modules/es-set-tostringtag/.nycrc | 9 + node_modules/es-set-tostringtag/CHANGELOG.md | 67 + node_modules/es-set-tostringtag/LICENSE | 21 + node_modules/es-set-tostringtag/README.md | 53 + node_modules/es-set-tostringtag/index.d.ts | 10 + node_modules/es-set-tostringtag/index.js | 35 + node_modules/es-set-tostringtag/package.json | 78 + node_modules/es-set-tostringtag/test/index.js | 85 + node_modules/es-set-tostringtag/tsconfig.json | 9 + node_modules/escalade/dist/index.js | 22 + node_modules/escalade/dist/index.mjs | 22 + node_modules/escalade/index.d.mts | 11 + node_modules/escalade/index.d.ts | 15 + node_modules/escalade/license | 9 + node_modules/escalade/package.json | 74 + node_modules/escalade/readme.md | 211 + node_modules/escalade/sync/index.d.mts | 9 + node_modules/escalade/sync/index.d.ts | 13 + node_modules/escalade/sync/index.js | 18 + node_modules/escalade/sync/index.mjs | 18 + node_modules/event-target-shim/LICENSE | 22 + node_modules/event-target-shim/README.md | 293 + .../dist/event-target-shim.js | 871 + .../dist/event-target-shim.js.map | 1 + .../dist/event-target-shim.mjs | 862 + .../dist/event-target-shim.mjs.map | 1 + .../dist/event-target-shim.umd.js | 6 + .../dist/event-target-shim.umd.js.map | 1 + node_modules/event-target-shim/index.d.ts | 399 + node_modules/event-target-shim/package.json | 82 + node_modules/extend/.editorconfig | 20 + node_modules/extend/.eslintrc | 17 + node_modules/extend/.jscs.json | 175 + node_modules/extend/.travis.yml | 230 + node_modules/extend/CHANGELOG.md | 83 + node_modules/extend/LICENSE | 23 + node_modules/extend/README.md | 81 + node_modules/extend/component.json | 32 + node_modules/extend/index.js | 117 + node_modules/extend/package.json | 42 + node_modules/farmhash-modern/LICENSE | 21 + node_modules/farmhash-modern/README.md | 118 + .../bin/bundler/farmhash_modern.js | 4 + .../bin/bundler/farmhash_modern_bg.js | 235 + .../bin/bundler/farmhash_modern_bg.wasm | Bin 0 -> 28329 bytes .../bin/nodejs/farmhash_modern.js | 238 + .../bin/nodejs/farmhash_modern_bg.wasm | Bin 0 -> 28333 bytes node_modules/farmhash-modern/lib/.tsbuildinfo | 1 + node_modules/farmhash-modern/lib/browser.d.ts | 40 + node_modules/farmhash-modern/lib/browser.js | 78 + node_modules/farmhash-modern/lib/index.cjs | 78 + node_modules/farmhash-modern/lib/index.d.cts | 40 + node_modules/farmhash-modern/lib/index.d.mts | 40 + node_modules/farmhash-modern/lib/index.d.ts | 40 + node_modules/farmhash-modern/lib/index.js | 78 + node_modules/farmhash-modern/lib/index.mjs | 78 + node_modules/farmhash-modern/package.json | 78 + node_modules/fast-deep-equal/LICENSE | 21 + node_modules/fast-deep-equal/README.md | 96 + node_modules/fast-deep-equal/es6/index.d.ts | 2 + node_modules/fast-deep-equal/es6/index.js | 72 + node_modules/fast-deep-equal/es6/react.d.ts | 2 + node_modules/fast-deep-equal/es6/react.js | 79 + node_modules/fast-deep-equal/index.d.ts | 4 + node_modules/fast-deep-equal/index.js | 46 + node_modules/fast-deep-equal/package.json | 61 + node_modules/fast-deep-equal/react.d.ts | 2 + node_modules/fast-deep-equal/react.js | 53 + node_modules/fast-xml-parser/CHANGELOG.md | 606 + node_modules/fast-xml-parser/LICENSE | 21 + node_modules/fast-xml-parser/README.md | 237 + node_modules/fast-xml-parser/package.json | 72 + node_modules/fast-xml-parser/src/cli/cli.js | 93 + node_modules/fast-xml-parser/src/cli/man.js | 12 + node_modules/fast-xml-parser/src/cli/read.js | 92 + node_modules/fast-xml-parser/src/fxp.d.ts | 418 + node_modules/fast-xml-parser/src/fxp.js | 11 + .../fast-xml-parser/src/ignoreAttributes.js | 20 + node_modules/fast-xml-parser/src/util.js | 72 + .../fast-xml-parser/src/v5/CharsSymbol.js | 16 + .../fast-xml-parser/src/v5/EntitiesParser.js | 107 + .../fast-xml-parser/src/v5/OptionsBuilder.js | 64 + .../v5/OutputBuilders/BaseOutputBuilder.js | 71 + .../src/v5/OutputBuilders/JsArrBuilder.js | 103 + .../src/v5/OutputBuilders/JsMinArrBuilder.js | 102 + .../src/v5/OutputBuilders/JsObjBuilder.js | 156 + .../v5/OutputBuilders/ParserOptionsBuilder.js | 99 + node_modules/fast-xml-parser/src/v5/Report.js | 0 .../fast-xml-parser/src/v5/TagPath.js | 81 + .../fast-xml-parser/src/v5/TagPathMatcher.js | 15 + .../fast-xml-parser/src/v5/XMLParser.js | 85 + .../fast-xml-parser/src/v5/Xml2JsParser.js | 237 + .../fast-xml-parser/src/v5/XmlPartReader.js | 216 + .../src/v5/XmlSpecialTagsReader.js | 118 + .../src/v5/inputSource/BufferSource.js | 118 + .../src/v5/inputSource/StringSource.js | 123 + .../src/v5/valueParsers/EntitiesParser.js | 107 + .../src/v5/valueParsers/booleanParser.js | 23 + .../src/v5/valueParsers/booleanParserExt.js | 20 + .../src/v5/valueParsers/currency.js | 40 + .../src/v5/valueParsers/join.js | 14 + .../src/v5/valueParsers/number.js | 16 + .../src/v5/valueParsers/trim.js | 8 + .../fast-xml-parser/src/v6/CharsSymbol.js | 16 + .../fast-xml-parser/src/v6/EntitiesParser.js | 104 + .../fast-xml-parser/src/v6/OptionsBuilder.js | 61 + .../v6/OutputBuilders/BaseOutputBuilder.js | 69 + .../src/v6/OutputBuilders/JsArrBuilder.js | 103 + .../src/v6/OutputBuilders/JsMinArrBuilder.js | 100 + .../src/v6/OutputBuilders/JsObjBuilder.js | 154 + .../v6/OutputBuilders/ParserOptionsBuilder.js | 94 + node_modules/fast-xml-parser/src/v6/Report.js | 0 .../fast-xml-parser/src/v6/TagPath.js | 81 + .../fast-xml-parser/src/v6/TagPathMatcher.js | 13 + .../fast-xml-parser/src/v6/XMLParser.js | 83 + .../fast-xml-parser/src/v6/Xml2JsParser.js | 235 + .../fast-xml-parser/src/v6/XmlPartReader.js | 210 + .../src/v6/XmlSpecialTagsReader.js | 111 + .../src/v6/inputSource/BufferSource.js | 116 + .../src/v6/inputSource/StringSource.js | 121 + .../src/v6/valueParsers/EntitiesParser.js | 105 + .../src/v6/valueParsers/booleanParser.js | 22 + .../src/v6/valueParsers/booleanParserExt.js | 19 + .../src/v6/valueParsers/currency.js | 38 + .../src/v6/valueParsers/join.js | 13 + .../src/v6/valueParsers/number.js | 14 + .../src/v6/valueParsers/trim.js | 6 + node_modules/fast-xml-parser/src/validator.js | 425 + .../src/xmlbuilder/json2xml.js | 286 + .../src/xmlbuilder/orderedJs2Xml.js | 135 + .../src/xmlbuilder/prettifyJs2Xml.js | 0 .../src/xmlparser/DocTypeReader.js | 153 + .../src/xmlparser/OptionsBuilder.js | 48 + .../src/xmlparser/OrderedObjParser.js | 606 + .../src/xmlparser/XMLParser.js | 58 + .../src/xmlparser/node2json.js | 113 + .../fast-xml-parser/src/xmlparser/xmlNode.js | 25 + node_modules/faye-websocket/CHANGELOG.md | 139 + node_modules/faye-websocket/LICENSE.md | 12 + node_modules/faye-websocket/README.md | 311 + .../faye-websocket/lib/faye/eventsource.js | 133 + .../faye-websocket/lib/faye/websocket.js | 47 + .../faye-websocket/lib/faye/websocket/api.js | 199 + .../lib/faye/websocket/api/event.js | 22 + .../lib/faye/websocket/api/event_target.js | 30 + .../lib/faye/websocket/client.js | 90 + node_modules/faye-websocket/package.json | 35 + node_modules/firebase-admin/LICENSE | 201 + node_modules/firebase-admin/README.md | 94 + .../app-check-api-client-internal.d.ts | 32 + .../app-check-api-client-internal.js | 214 + .../lib/app-check/app-check-api.d.ts | 129 + .../lib/app-check/app-check-api.js | 19 + .../lib/app-check/app-check-namespace.d.ts | 72 + .../lib/app-check/app-check-namespace.js | 18 + .../lib/app-check/app-check.d.ts | 51 + .../firebase-admin/lib/app-check/app-check.js | 101 + .../firebase-admin/lib/app-check/index.d.ts | 53 + .../firebase-admin/lib/app-check/index.js | 63 + .../lib/app-check/token-generator.d.ts | 25 + .../lib/app-check/token-generator.js | 154 + .../lib/app-check/token-verifier.d.ts | 17 + .../lib/app-check/token-verifier.js | 147 + node_modules/firebase-admin/lib/app/core.d.ts | 187 + node_modules/firebase-admin/lib/app/core.js | 19 + .../lib/app/credential-factory.d.ts | 122 + .../lib/app/credential-factory.js | 149 + .../lib/app/credential-internal.d.ts | 122 + .../lib/app/credential-internal.js | 418 + .../firebase-admin/lib/app/credential.d.ts | 45 + .../firebase-admin/lib/app/credential.js | 19 + .../firebase-admin/lib/app/firebase-app.d.ts | 53 + .../firebase-admin/lib/app/firebase-app.js | 234 + .../lib/app/firebase-namespace.d.ts | 163 + .../lib/app/firebase-namespace.js | 335 + .../firebase-admin/lib/app/index.d.ts | 28 + node_modules/firebase-admin/lib/app/index.js | 34 + .../firebase-admin/lib/app/lifecycle.d.ts | 116 + .../firebase-admin/lib/app/lifecycle.js | 277 + .../auth/action-code-settings-builder.d.ts | 96 + .../lib/auth/action-code-settings-builder.js | 125 + .../lib/auth/auth-api-request.d.ts | 185 + .../lib/auth/auth-api-request.js | 1948 ++ .../firebase-admin/lib/auth/auth-config.d.ts | 851 + .../firebase-admin/lib/auth/auth-config.js | 1186 + .../lib/auth/auth-namespace.d.ts | 257 + .../firebase-admin/lib/auth/auth-namespace.js | 18 + .../firebase-admin/lib/auth/auth.d.ts | 48 + node_modules/firebase-admin/lib/auth/auth.js | 66 + .../firebase-admin/lib/auth/base-auth.d.ts | 640 + .../firebase-admin/lib/auth/base-auth.js | 981 + .../firebase-admin/lib/auth/identifier.d.ts | 57 + .../firebase-admin/lib/auth/identifier.js | 39 + .../firebase-admin/lib/auth/index.d.ts | 58 + node_modules/firebase-admin/lib/auth/index.js | 78 + .../lib/auth/project-config-manager.d.ts | 22 + .../lib/auth/project-config-manager.js | 47 + .../lib/auth/project-config.d.ts | 111 + .../firebase-admin/lib/auth/project-config.js | 183 + .../lib/auth/tenant-manager.d.ts | 146 + .../firebase-admin/lib/auth/tenant-manager.js | 230 + .../firebase-admin/lib/auth/tenant.d.ts | 182 + .../firebase-admin/lib/auth/tenant.js | 273 + .../lib/auth/token-generator.d.ts | 43 + .../lib/auth/token-generator.js | 198 + .../lib/auth/token-verifier.d.ts | 219 + .../firebase-admin/lib/auth/token-verifier.js | 316 + .../lib/auth/user-import-builder.d.ts | 321 + .../lib/auth/user-import-builder.js | 384 + .../firebase-admin/lib/auth/user-record.d.ts | 289 + .../firebase-admin/lib/auth/user-record.js | 411 + .../firebase-admin/lib/credential/index.d.ts | 127 + .../firebase-admin/lib/credential/index.js | 123 + .../data-connect-api-client-internal.d.ts | 37 + .../data-connect-api-client-internal.js | 490 + .../lib/data-connect/data-connect-api.d.ts | 120 + .../lib/data-connect/data-connect-api.js | 19 + .../lib/data-connect/data-connect.d.ts | 135 + .../lib/data-connect/data-connect.js | 138 + .../lib/data-connect/index.d.ts | 46 + .../firebase-admin/lib/data-connect/index.js | 77 + .../lib/data-connect/validate-admin-args.d.ts | 18 + .../lib/data-connect/validate-admin-args.js | 79 + .../lib/database/database-namespace.d.ts | 95 + .../lib/database/database-namespace.js | 23 + .../firebase-admin/lib/database/database.d.ts | 65 + .../firebase-admin/lib/database/database.js | 257 + .../firebase-admin/lib/database/index.d.ts | 91 + .../firebase-admin/lib/database/index.js | 105 + .../firebase-admin/lib/default-namespace.d.ts | 24 + .../firebase-admin/lib/default-namespace.js | 30 + .../firebase-admin/lib/esm/app-check/index.js | 4 + .../firebase-admin/lib/esm/app/index.js | 12 + .../firebase-admin/lib/esm/auth/index.js | 18 + .../lib/esm/data-connect/index.js | 5 + .../firebase-admin/lib/esm/database/index.js | 7 + .../firebase-admin/lib/esm/eventarc/index.js | 5 + .../lib/esm/extensions/index.js | 5 + .../firebase-admin/lib/esm/firestore/index.js | 30 + .../firebase-admin/lib/esm/functions/index.js | 5 + .../lib/esm/installations/index.js | 6 + .../lib/esm/instance-id/index.js | 6 + .../lib/esm/machine-learning/index.js | 5 + .../firebase-admin/lib/esm/messaging/index.js | 6 + .../firebase-admin/lib/esm/package.json | 1 + .../lib/esm/project-management/index.js | 9 + .../lib/esm/remote-config/index.js | 7 + .../lib/esm/security-rules/index.js | 6 + .../firebase-admin/lib/esm/storage/index.js | 5 + .../lib/eventarc/cloudevent.d.ts | 84 + .../firebase-admin/lib/eventarc/cloudevent.js | 19 + .../eventarc/eventarc-client-internal.d.ts | 18 + .../lib/eventarc/eventarc-client-internal.js | 139 + .../lib/eventarc/eventarc-utils.d.ts | 31 + .../lib/eventarc/eventarc-utils.js | 125 + .../firebase-admin/lib/eventarc/eventarc.d.ts | 107 + .../firebase-admin/lib/eventarc/eventarc.js | 125 + .../firebase-admin/lib/eventarc/index.d.ts | 53 + .../firebase-admin/lib/eventarc/index.js | 64 + .../extensions-api-client-internal.d.ts | 30 + .../extensions-api-client-internal.js | 105 + .../lib/extensions/extensions-api.d.ts | 44 + .../lib/extensions/extensions-api.js | 19 + .../lib/extensions/extensions.d.ts | 73 + .../lib/extensions/extensions.js | 122 + .../firebase-admin/lib/extensions/index.d.ts | 53 + .../firebase-admin/lib/extensions/index.js | 64 + .../lib/firebase-namespace-api.d.ts | 91 + .../lib/firebase-namespace-api.js | 58 + .../lib/firestore/firestore-internal.d.ts | 54 + .../lib/firestore/firestore-internal.js | 145 + .../lib/firestore/firestore-namespace.d.ts | 71 + .../lib/firestore/firestore-namespace.js | 52 + .../firebase-admin/lib/firestore/index.d.ts | 130 + .../firebase-admin/lib/firestore/index.js | 66 + .../functions-api-client-internal.d.ts | 52 + .../functions-api-client-internal.js | 372 + .../lib/functions/functions-api.d.ts | 99 + .../lib/functions/functions-api.js | 19 + .../lib/functions/functions.d.ts | 69 + .../firebase-admin/lib/functions/functions.js | 105 + .../firebase-admin/lib/functions/index.d.ts | 53 + .../firebase-admin/lib/functions/index.js | 64 + node_modules/firebase-admin/lib/index.d.ts | 24 + node_modules/firebase-admin/lib/index.js | 37 + .../lib/installations/index.d.ts | 53 + .../firebase-admin/lib/installations/index.js | 65 + .../installations-namespace.d.ts | 55 + .../installations/installations-namespace.js | 18 + .../installations-request-handler.d.ts | 43 + .../installations-request-handler.js | 114 + .../lib/installations/installations.d.ts | 38 + .../lib/installations/installations.js | 58 + .../firebase-admin/lib/instance-id/index.d.ts | 62 + .../firebase-admin/lib/instance-id/index.js | 74 + .../instance-id/instance-id-namespace.d.ts | 38 + .../lib/instance-id/instance-id-namespace.js | 3 + .../lib/instance-id/instance-id.d.ts | 47 + .../lib/instance-id/instance-id.js | 77 + .../lib/machine-learning/index.d.ts | 52 + .../lib/machine-learning/index.js | 63 + .../machine-learning-api-client.d.ts | 96 + .../machine-learning-api-client.js | 290 + .../machine-learning-namespace.d.ts | 81 + .../machine-learning-namespace.js | 18 + .../machine-learning-utils.d.ts | 22 + .../machine-learning-utils.js | 47 + .../machine-learning/machine-learning.d.ts | 173 + .../lib/machine-learning/machine-learning.js | 336 + .../firebase-admin/lib/messaging/index.d.ts | 53 + .../firebase-admin/lib/messaging/index.js | 65 + .../messaging-api-request-internal.d.ts | 61 + .../messaging-api-request-internal.js | 154 + .../lib/messaging/messaging-api.d.ts | 914 + .../lib/messaging/messaging-api.js | 19 + .../messaging/messaging-errors-internal.d.ts | 31 + .../messaging/messaging-errors-internal.js | 104 + .../lib/messaging/messaging-internal.d.ts | 27 + .../lib/messaging/messaging-internal.js | 505 + .../lib/messaging/messaging-namespace.d.ts | 161 + .../lib/messaging/messaging-namespace.js | 18 + .../lib/messaging/messaging.d.ts | 189 + .../firebase-admin/lib/messaging/messaging.js | 442 + .../lib/project-management/android-app.d.ts | 110 + .../lib/project-management/android-app.js | 183 + .../lib/project-management/app-metadata.d.ts | 85 + .../lib/project-management/app-metadata.js | 37 + .../lib/project-management/index.d.ts | 54 + .../lib/project-management/index.js | 70 + .../lib/project-management/ios-app.d.ts | 66 + .../lib/project-management/ios-app.js | 94 + ...oject-management-api-request-internal.d.ts | 17 + ...project-management-api-request-internal.js | 268 + .../project-management-namespace.d.ts | 82 + .../project-management-namespace.js | 18 + .../project-management.d.ts | 115 + .../project-management/project-management.js | 244 + .../condition-evaluator-internal.d.ts | 17 + .../condition-evaluator-internal.js | 230 + .../lib/remote-config/index.d.ts | 52 + .../firebase-admin/lib/remote-config/index.js | 66 + .../remote-config/internal/value-impl.d.ts | 17 + .../lib/remote-config/internal/value-impl.js | 59 + .../remote-config-api-client-internal.d.ts | 28 + .../remote-config-api-client-internal.js | 407 + .../lib/remote-config/remote-config-api.d.ts | 708 + .../lib/remote-config/remote-config-api.js | 122 + .../remote-config-namespace.d.ts | 105 + .../remote-config/remote-config-namespace.js | 18 + .../lib/remote-config/remote-config.d.ts | 121 + .../lib/remote-config/remote-config.js | 529 + .../lib/security-rules/index.d.ts | 50 + .../lib/security-rules/index.js | 63 + .../security-rules-api-client-internal.d.ts | 75 + .../security-rules-api-client-internal.js | 248 + .../security-rules-internal.d.ts | 21 + .../security-rules/security-rules-internal.js | 26 + .../security-rules-namespace.d.ts | 69 + .../security-rules-namespace.js | 18 + .../lib/security-rules/security-rules.d.ts | 195 + .../lib/security-rules/security-rules.js | 319 + .../firebase-admin/lib/storage/index.d.ts | 57 + .../firebase-admin/lib/storage/index.js | 77 + .../lib/storage/storage-namespace.d.ts | 45 + .../lib/storage/storage-namespace.js | 18 + .../firebase-admin/lib/storage/storage.d.ts | 42 + .../firebase-admin/lib/storage/storage.js | 121 + .../firebase-admin/lib/storage/utils.d.ts | 20 + .../firebase-admin/lib/storage/utils.js | 20 + .../firebase-admin/lib/utils/api-request.d.ts | 324 + .../firebase-admin/lib/utils/api-request.js | 1052 + .../lib/utils/crypto-signer.d.ts | 128 + .../firebase-admin/lib/utils/crypto-signer.js | 210 + .../firebase-admin/lib/utils/deep-copy.d.ts | 40 + .../firebase-admin/lib/utils/deep-copy.js | 77 + .../firebase-admin/lib/utils/error.d.ts | 604 + .../firebase-admin/lib/utils/error.js | 1086 + .../firebase-admin/lib/utils/index.d.ts | 147 + .../firebase-admin/lib/utils/index.js | 286 + .../firebase-admin/lib/utils/jwt.d.ts | 130 + node_modules/firebase-admin/lib/utils/jwt.js | 330 + .../firebase-admin/lib/utils/validator.d.ts | 151 + .../firebase-admin/lib/utils/validator.js | 285 + node_modules/firebase-admin/package.json | 277 + node_modules/form-data/CHANGELOG.md | 651 + node_modules/form-data/License | 19 + node_modules/form-data/README.md | 350 + node_modules/form-data/index.d.ts | 51 + node_modules/form-data/lib/browser.js | 4 + node_modules/form-data/lib/form_data.js | 509 + node_modules/form-data/lib/populate.js | 10 + node_modules/form-data/package.json | 83 + node_modules/function-bind/.eslintrc | 21 + .../function-bind/.github/FUNDING.yml | 12 + .../function-bind/.github/SECURITY.md | 3 + node_modules/function-bind/.nycrc | 13 + node_modules/function-bind/CHANGELOG.md | 136 + node_modules/function-bind/LICENSE | 20 + node_modules/function-bind/README.md | 46 + node_modules/function-bind/implementation.js | 84 + node_modules/function-bind/index.js | 5 + node_modules/function-bind/package.json | 87 + node_modules/function-bind/test/.eslintrc | 9 + node_modules/function-bind/test/index.js | 252 + .../functional-red-black-tree/.npmignore | 16 + .../functional-red-black-tree/LICENSE | 22 + .../functional-red-black-tree/README.md | 237 + .../functional-red-black-tree/bench/test.js | 11 + .../functional-red-black-tree/package.json | 40 + .../functional-red-black-tree/rbtree.js | 996 + .../functional-red-black-tree/test/test.js | 479 + node_modules/gaxios/CHANGELOG.md | 397 + node_modules/gaxios/LICENSE | 202 + node_modules/gaxios/README.md | 210 + node_modules/gaxios/build/src/common.d.ts | 274 + node_modules/gaxios/build/src/common.js | 188 + node_modules/gaxios/build/src/common.js.map | 1 + node_modules/gaxios/build/src/gaxios.d.ts | 62 + node_modules/gaxios/build/src/gaxios.js | 480 + node_modules/gaxios/build/src/gaxios.js.map | 1 + node_modules/gaxios/build/src/index.d.ts | 15 + node_modules/gaxios/build/src/index.js | 48 + node_modules/gaxios/build/src/index.js.map | 1 + .../gaxios/build/src/interceptor.d.ts | 25 + node_modules/gaxios/build/src/interceptor.js | 22 + .../gaxios/build/src/interceptor.js.map | 1 + node_modules/gaxios/build/src/retry.d.ts | 8 + node_modules/gaxios/build/src/retry.js | 166 + node_modules/gaxios/build/src/retry.js.map | 1 + node_modules/gaxios/build/src/util.d.ts | 4 + node_modules/gaxios/build/src/util.js | 17 + node_modules/gaxios/build/src/util.js.map | 1 + node_modules/gaxios/node_modules/.bin/uuid | 16 + .../gaxios/node_modules/.bin/uuid.cmd | 17 + .../gaxios/node_modules/.bin/uuid.ps1 | 28 + .../gaxios/node_modules/uuid/CHANGELOG.md | 274 + .../gaxios/node_modules/uuid/CONTRIBUTING.md | 18 + .../gaxios/node_modules/uuid/LICENSE.md | 9 + .../gaxios/node_modules/uuid/README.md | 466 + .../gaxios/node_modules/uuid/dist/bin/uuid | 2 + .../uuid/dist/commonjs-browser/index.js | 79 + .../uuid/dist/commonjs-browser/md5.js | 223 + .../uuid/dist/commonjs-browser/native.js | 11 + .../uuid/dist/commonjs-browser/nil.js | 8 + .../uuid/dist/commonjs-browser/parse.js | 45 + .../uuid/dist/commonjs-browser/regex.js | 8 + .../uuid/dist/commonjs-browser/rng.js | 25 + .../uuid/dist/commonjs-browser/sha1.js | 104 + .../uuid/dist/commonjs-browser/stringify.js | 44 + .../uuid/dist/commonjs-browser/v1.js | 107 + .../uuid/dist/commonjs-browser/v3.js | 16 + .../uuid/dist/commonjs-browser/v35.js | 80 + .../uuid/dist/commonjs-browser/v4.js | 43 + .../uuid/dist/commonjs-browser/v5.js | 16 + .../uuid/dist/commonjs-browser/validate.js | 17 + .../uuid/dist/commonjs-browser/version.js | 21 + .../uuid/dist/esm-browser/index.js | 9 + .../node_modules/uuid/dist/esm-browser/md5.js | 215 + .../uuid/dist/esm-browser/native.js | 4 + .../node_modules/uuid/dist/esm-browser/nil.js | 1 + .../uuid/dist/esm-browser/parse.js | 35 + .../uuid/dist/esm-browser/regex.js | 1 + .../node_modules/uuid/dist/esm-browser/rng.js | 18 + .../uuid/dist/esm-browser/sha1.js | 96 + .../uuid/dist/esm-browser/stringify.js | 33 + .../node_modules/uuid/dist/esm-browser/v1.js | 95 + .../node_modules/uuid/dist/esm-browser/v3.js | 4 + .../node_modules/uuid/dist/esm-browser/v35.js | 66 + .../node_modules/uuid/dist/esm-browser/v4.js | 29 + .../node_modules/uuid/dist/esm-browser/v5.js | 4 + .../uuid/dist/esm-browser/validate.js | 7 + .../uuid/dist/esm-browser/version.js | 11 + .../node_modules/uuid/dist/esm-node/index.js | 9 + .../node_modules/uuid/dist/esm-node/md5.js | 13 + .../node_modules/uuid/dist/esm-node/native.js | 4 + .../node_modules/uuid/dist/esm-node/nil.js | 1 + .../node_modules/uuid/dist/esm-node/parse.js | 35 + .../node_modules/uuid/dist/esm-node/regex.js | 1 + .../node_modules/uuid/dist/esm-node/rng.js | 12 + .../node_modules/uuid/dist/esm-node/sha1.js | 13 + .../uuid/dist/esm-node/stringify.js | 33 + .../node_modules/uuid/dist/esm-node/v1.js | 95 + .../node_modules/uuid/dist/esm-node/v3.js | 4 + .../node_modules/uuid/dist/esm-node/v35.js | 66 + .../node_modules/uuid/dist/esm-node/v4.js | 29 + .../node_modules/uuid/dist/esm-node/v5.js | 4 + .../uuid/dist/esm-node/validate.js | 7 + .../uuid/dist/esm-node/version.js | 11 + .../gaxios/node_modules/uuid/dist/index.js | 79 + .../node_modules/uuid/dist/md5-browser.js | 223 + .../gaxios/node_modules/uuid/dist/md5.js | 23 + .../node_modules/uuid/dist/native-browser.js | 11 + .../gaxios/node_modules/uuid/dist/native.js | 15 + .../gaxios/node_modules/uuid/dist/nil.js | 8 + .../gaxios/node_modules/uuid/dist/parse.js | 45 + .../gaxios/node_modules/uuid/dist/regex.js | 8 + .../node_modules/uuid/dist/rng-browser.js | 25 + .../gaxios/node_modules/uuid/dist/rng.js | 24 + .../node_modules/uuid/dist/sha1-browser.js | 104 + .../gaxios/node_modules/uuid/dist/sha1.js | 23 + .../node_modules/uuid/dist/stringify.js | 44 + .../gaxios/node_modules/uuid/dist/uuid-bin.js | 85 + .../gaxios/node_modules/uuid/dist/v1.js | 107 + .../gaxios/node_modules/uuid/dist/v3.js | 16 + .../gaxios/node_modules/uuid/dist/v35.js | 80 + .../gaxios/node_modules/uuid/dist/v4.js | 43 + .../gaxios/node_modules/uuid/dist/v5.js | 16 + .../gaxios/node_modules/uuid/dist/validate.js | 17 + .../gaxios/node_modules/uuid/dist/version.js | 21 + .../gaxios/node_modules/uuid/package.json | 135 + .../gaxios/node_modules/uuid/wrapper.mjs | 10 + node_modules/gaxios/package.json | 96 + node_modules/gcp-metadata/CHANGELOG.md | 463 + node_modules/gcp-metadata/LICENSE | 202 + node_modules/gcp-metadata/README.md | 235 + .../gcp-metadata/build/src/gcp-residency.d.ts | 57 + .../gcp-metadata/build/src/gcp-residency.js | 114 + .../build/src/gcp-residency.js.map | 1 + .../gcp-metadata/build/src/index.d.ts | 156 + node_modules/gcp-metadata/build/src/index.js | 408 + .../gcp-metadata/build/src/index.js.map | 1 + node_modules/gcp-metadata/package.json | 73 + node_modules/get-caller-file/LICENSE.md | 6 + node_modules/get-caller-file/README.md | 41 + node_modules/get-caller-file/index.d.ts | 2 + node_modules/get-caller-file/index.js | 22 + node_modules/get-caller-file/index.js.map | 1 + node_modules/get-caller-file/package.json | 42 + node_modules/get-intrinsic/.eslintrc | 42 + .../get-intrinsic/.github/FUNDING.yml | 12 + node_modules/get-intrinsic/.nycrc | 9 + node_modules/get-intrinsic/CHANGELOG.md | 186 + node_modules/get-intrinsic/LICENSE | 21 + node_modules/get-intrinsic/README.md | 71 + node_modules/get-intrinsic/index.js | 378 + node_modules/get-intrinsic/package.json | 97 + .../get-intrinsic/test/GetIntrinsic.js | 274 + node_modules/get-proto/.eslintrc | 10 + node_modules/get-proto/.github/FUNDING.yml | 12 + node_modules/get-proto/.nycrc | 9 + node_modules/get-proto/CHANGELOG.md | 21 + node_modules/get-proto/LICENSE | 21 + .../get-proto/Object.getPrototypeOf.d.ts | 5 + .../get-proto/Object.getPrototypeOf.js | 6 + node_modules/get-proto/README.md | 50 + .../get-proto/Reflect.getPrototypeOf.d.ts | 3 + .../get-proto/Reflect.getPrototypeOf.js | 4 + node_modules/get-proto/index.d.ts | 5 + node_modules/get-proto/index.js | 27 + node_modules/get-proto/package.json | 81 + node_modules/get-proto/test/index.js | 68 + node_modules/get-proto/tsconfig.json | 9 + node_modules/google-auth-library/CHANGELOG.md | 1394 ++ node_modules/google-auth-library/LICENSE | 202 + node_modules/google-auth-library/README.md | 1470 ++ .../build/src/auth/authclient.d.ts | 202 + .../build/src/auth/authclient.js | 116 + .../build/src/auth/awsclient.d.ts | 120 + .../build/src/auth/awsclient.js | 164 + .../build/src/auth/awsrequestsigner.d.ts | 40 + .../build/src/auth/awsrequestsigner.js | 209 + .../build/src/auth/baseexternalclient.d.ts | 322 + .../build/src/auth/baseexternalclient.js | 468 + .../build/src/auth/computeclient.d.ts | 37 + .../build/src/auth/computeclient.js | 117 + .../build/src/auth/credentials.d.ts | 75 + .../build/src/auth/credentials.js | 15 + ...defaultawssecuritycredentialssupplier.d.ts | 79 + .../defaultawssecuritycredentialssupplier.js | 196 + .../build/src/auth/downscopedclient.d.ts | 139 + .../build/src/auth/downscopedclient.js | 262 + .../build/src/auth/envDetect.d.ts | 10 + .../build/src/auth/envDetect.js | 89 + .../build/src/auth/executable-response.d.ts | 137 + .../build/src/auth/executable-response.js | 146 + .../externalAccountAuthorizedUserClient.d.ts | 78 + .../externalAccountAuthorizedUserClient.js | 239 + .../build/src/auth/externalclient.d.ts | 26 + .../build/src/auth/externalclient.js | 64 + .../src/auth/filesubjecttokensupplier.d.ts | 42 + .../src/auth/filesubjecttokensupplier.js | 81 + .../build/src/auth/googleauth.d.ts | 375 + .../build/src/auth/googleauth.js | 841 + .../build/src/auth/iam.d.ts | 23 + .../google-auth-library/build/src/auth/iam.js | 41 + .../build/src/auth/identitypoolclient.d.ts | 102 + .../build/src/auth/identitypoolclient.js | 107 + .../build/src/auth/idtokenclient.d.ts | 27 + .../build/src/auth/idtokenclient.js | 55 + .../build/src/auth/impersonated.d.ts | 127 + .../build/src/auth/impersonated.js | 186 + .../build/src/auth/jwtaccess.d.ts | 62 + .../build/src/auth/jwtaccess.js | 192 + .../build/src/auth/jwtclient.d.ts | 117 + .../build/src/auth/jwtclient.js | 284 + .../build/src/auth/loginticket.d.ts | 140 + .../build/src/auth/loginticket.js | 57 + .../build/src/auth/oauth2client.d.ts | 575 + .../build/src/auth/oauth2client.js | 794 + .../build/src/auth/oauth2common.d.ts | 92 + .../build/src/auth/oauth2common.js | 192 + .../build/src/auth/passthrough.d.ts | 38 + .../build/src/auth/passthrough.js | 61 + .../build/src/auth/pluggable-auth-client.d.ts | 155 + .../build/src/auth/pluggable-auth-client.js | 215 + .../src/auth/pluggable-auth-handler.d.ts | 51 + .../build/src/auth/pluggable-auth-handler.js | 156 + .../build/src/auth/refreshclient.d.ts | 50 + .../build/src/auth/refreshclient.js | 132 + .../build/src/auth/stscredentials.d.ts | 114 + .../build/src/auth/stscredentials.js | 109 + .../src/auth/urlsubjecttokensupplier.d.ts | 57 + .../build/src/auth/urlsubjecttokensupplier.js | 63 + .../build/src/crypto/browser/crypto.d.ts | 27 + .../build/src/crypto/browser/crypto.js | 126 + .../build/src/crypto/crypto.d.ts | 44 + .../build/src/crypto/crypto.js | 47 + .../build/src/crypto/node/crypto.d.ts | 25 + .../build/src/crypto/node/crypto.js | 82 + .../google-auth-library/build/src/index.d.ts | 33 + .../google-auth-library/build/src/index.js | 68 + .../build/src/messages.d.ts | 11 + .../google-auth-library/build/src/messages.js | 39 + .../build/src/options.d.ts | 1 + .../google-auth-library/build/src/options.js | 34 + .../build/src/transporters.d.ts | 40 + .../build/src/transporters.js | 110 + .../google-auth-library/build/src/util.d.ts | 151 + .../google-auth-library/build/src/util.js | 125 + node_modules/google-auth-library/package.json | 94 + .../build/protos/compute_operations.d.ts | 7304 ++++++ .../build/protos/compute_operations.js | 1 + .../build/protos/compute_operations.json | 1 + .../build/protos/google/api/annotations.proto | 31 + .../google/api/apikeys/v2/apikeys.proto | 288 + .../google/api/apikeys/v2/resources.proto | 175 + .../build/protos/google/api/auth.proto | 237 + .../build/protos/google/api/backend.proto | 185 + .../build/protos/google/api/billing.proto | 77 + .../build/protos/google/api/client.proto | 427 + .../api/cloudquotas/v1/cloudquotas.proto | 322 + .../google/api/cloudquotas/v1/resources.proto | 311 + .../protos/google/api/config_change.proto | 84 + .../build/protos/google/api/consumer.proto | 82 + .../build/protos/google/api/context.proto | 90 + .../build/protos/google/api/control.proto | 41 + .../protos/google/api/distribution.proto | 213 + .../protos/google/api/documentation.proto | 168 + .../build/protos/google/api/endpoint.proto | 73 + .../protos/google/api/error_reason.proto | 589 + .../v1alpha1/conformance_service.proto | 183 + .../google/api/expr/v1alpha1/checked.proto | 343 + .../google/api/expr/v1alpha1/eval.proto | 118 + .../google/api/expr/v1alpha1/explain.proto | 53 + .../google/api/expr/v1alpha1/syntax.proto | 400 + .../google/api/expr/v1alpha1/value.proto | 115 + .../protos/google/api/expr/v1beta1/decl.proto | 84 + .../protos/google/api/expr/v1beta1/eval.proto | 125 + .../protos/google/api/expr/v1beta1/expr.proto | 265 + .../google/api/expr/v1beta1/source.proto | 62 + .../google/api/expr/v1beta1/value.proto | 114 + .../protos/google/api/field_behavior.proto | 104 + .../build/protos/google/api/field_info.proto | 79 + .../build/protos/google/api/http.proto | 379 + .../build/protos/google/api/httpbody.proto | 81 + .../build/protos/google/api/label.proto | 48 + .../protos/google/api/launch_stage.proto | 72 + .../build/protos/google/api/log.proto | 54 + .../build/protos/google/api/logging.proto | 81 + .../build/protos/google/api/metric.proto | 268 + .../google/api/monitored_resource.proto | 130 + .../build/protos/google/api/monitoring.proto | 107 + .../build/protos/google/api/policy.proto | 85 + .../build/protos/google/api/quota.proto | 184 + .../build/protos/google/api/resource.proto | 238 + .../build/protos/google/api/routing.proto | 461 + .../build/protos/google/api/service.proto | 191 + .../api/servicecontrol/v1/check_error.proto | 124 + .../api/servicecontrol/v1/distribution.proto | 166 + .../api/servicecontrol/v1/http_request.proto | 93 + .../api/servicecontrol/v1/log_entry.proto | 126 + .../api/servicecontrol/v1/metric_value.proto | 81 + .../api/servicecontrol/v1/operation.proto | 123 + .../servicecontrol/v1/quota_controller.proto | 245 + .../v1/service_controller.proto | 260 + .../v2/service_controller.proto | 196 + .../api/servicemanagement/v1/resources.proto | 295 + .../servicemanagement/v1/servicemanager.proto | 508 + .../api/serviceusage/v1/resources.proto | 130 + .../api/serviceusage/v1/serviceusage.proto | 305 + .../api/serviceusage/v1beta1/resources.proto | 458 + .../serviceusage/v1beta1/serviceusage.proto | 793 + .../build/protos/google/api/source_info.proto | 31 + .../protos/google/api/system_parameter.proto | 96 + .../build/protos/google/api/usage.proto | 96 + .../build/protos/google/api/visibility.proto | 113 + .../google/cloud/location/locations.proto | 108 + .../protos/google/iam/v1/iam_policy.proto | 155 + .../google/iam/v1/logging/audit_data.proto | 33 + .../build/protos/google/iam/v1/options.proto | 48 + .../build/protos/google/iam/v1/policy.proto | 410 + .../google/logging/type/http_request.proto | 95 + .../google/logging/type/log_severity.proto | 71 + .../google/longrunning/operations.proto | 247 + .../protos/google/monitoring/v3/alert.proto | 669 + .../google/monitoring/v3/alert_service.proto | 256 + .../protos/google/monitoring/v3/common.proto | 488 + .../google/monitoring/v3/dropped_labels.proto | 46 + .../protos/google/monitoring/v3/group.proto | 90 + .../google/monitoring/v3/group_service.proto | 290 + .../protos/google/monitoring/v3/metric.proto | 239 + .../google/monitoring/v3/metric_service.proto | 522 + .../monitoring/v3/mutation_record.proto | 36 + .../google/monitoring/v3/notification.proto | 195 + .../monitoring/v3/notification_service.proto | 448 + .../google/monitoring/v3/query_service.proto | 48 + .../protos/google/monitoring/v3/service.proto | 457 + .../monitoring/v3/service_service.proto | 352 + .../protos/google/monitoring/v3/snooze.proto | 78 + .../google/monitoring/v3/snooze_service.proto | 210 + .../google/monitoring/v3/span_context.proto | 45 + .../protos/google/monitoring/v3/uptime.proto | 564 + .../google/monitoring/v3/uptime_service.proto | 259 + .../build/protos/google/protobuf/any.proto | 162 + .../build/protos/google/protobuf/api.proto | 207 + .../google/protobuf/bridge/message_set.proto | 76 + .../google/protobuf/compiler/plugin.proto | 180 + .../compiler/ruby/ruby_generated_code.proto | 77 + .../ruby/ruby_generated_code_proto2.proto | 78 + .../ruby_generated_code_proto2_import.proto | 12 + .../ruby/ruby_generated_pkg_explicit.proto | 16 + .../ruby_generated_pkg_explicit_legacy.proto | 16 + .../ruby/ruby_generated_pkg_implicit.proto | 14 + .../protos/google/protobuf/cpp_features.proto | 45 + .../protos/google/protobuf/descriptor.proto | 1225 + .../protos/google/protobuf/duration.proto | 115 + .../editions/codegen_tests/proto2_enum.proto | 26 + .../editions/codegen_tests/proto2_group.proto | 18 + .../codegen_tests/proto2_import.proto | 16 + .../proto2_inline_comments.proto | 33 + .../proto2_multiline_comments.proto | 33 + .../codegen_tests/proto2_optional.proto | 65 + .../codegen_tests/proto2_packed.proto | 14 + .../codegen_tests/proto2_proto3_enum.proto | 18 + .../codegen_tests/proto2_required.proto | 47 + .../codegen_tests/proto2_unpacked.proto | 19 + .../codegen_tests/proto2_utf8_disabled.proto | 16 + .../codegen_tests/proto2_utf8_lite.proto | 17 + .../codegen_tests/proto2_utf8_verify.proto | 14 + .../editions/codegen_tests/proto3_enum.proto | 26 + .../codegen_tests/proto3_implicit.proto | 65 + .../codegen_tests/proto3_import.proto | 16 + .../codegen_tests/proto3_optional.proto | 47 + .../codegen_tests/proto3_packed.proto | 20 + .../codegen_tests/proto3_unpacked.proto | 19 + .../codegen_tests/proto3_utf8_strict.proto | 15 + .../golden/editions_transform_proto2.proto | 129 + .../editions_transform_proto2_lite.proto | 19 + ...tions_transform_proto2_utf8_disabled.proto | 18 + .../golden/editions_transform_proto3.proto | 32 + ...tions_transform_proto3_utf8_disabled.proto | 18 + .../editions/golden/simple_proto2.proto | 14 + .../golden/simple_proto2_import.proto | 16 + .../editions/golden/simple_proto3.proto | 14 + .../proto/editions_transform_proto2.proto | 91 + .../editions_transform_proto2_lite.proto | 20 + ...tions_transform_proto2_utf8_disabled.proto | 19 + .../proto/editions_transform_proto3.proto | 25 + ...tions_transform_proto3_utf8_disabled.proto | 19 + .../build/protos/google/protobuf/empty.proto | 51 + .../protos/google/protobuf/field_mask.proto | 245 + .../protobuf/sample_messages_edition.proto | 427 + .../google/protobuf/source_context.proto | 48 + .../build/protos/google/protobuf/struct.proto | 95 + .../protos/google/protobuf/timestamp.proto | 144 + .../build/protos/google/protobuf/type.proto | 193 + .../google/protobuf/util/json_format.proto | 116 + .../protobuf/util/json_format_proto3.proto | 301 + .../protos/google/protobuf/wrappers.proto | 123 + .../build/protos/google/rpc/code.proto | 186 + .../rpc/context/attribute_context.proto | 344 + .../google/rpc/context/audit_context.proto | 49 + .../protos/google/rpc/error_details.proto | 285 + .../build/protos/google/rpc/http.proto | 64 + .../build/protos/google/rpc/status.proto | 49 + .../protos/google/type/calendar_period.proto | 56 + .../build/protos/google/type/color.proto | 174 + .../build/protos/google/type/date.proto | 52 + .../build/protos/google/type/datetime.proto | 104 + .../build/protos/google/type/dayofweek.proto | 50 + .../build/protos/google/type/decimal.proto | 95 + .../build/protos/google/type/expr.proto | 73 + .../build/protos/google/type/fraction.proto | 33 + .../build/protos/google/type/interval.proto | 46 + .../build/protos/google/type/latlng.proto | 37 + .../protos/google/type/localized_text.proto | 36 + .../build/protos/google/type/money.proto | 42 + .../build/protos/google/type/month.proto | 65 + .../protos/google/type/phone_number.proto | 113 + .../protos/google/type/postal_address.proto | 134 + .../build/protos/google/type/quaternion.proto | 94 + .../build/protos/google/type/timeofday.proto | 44 + .../google-gax/build/protos/http.d.ts | 347 + node_modules/google-gax/build/protos/http.js | 1 + .../google-gax/build/protos/iam_service.d.ts | 5035 ++++ .../google-gax/build/protos/iam_service.js | 1 + .../google-gax/build/protos/iam_service.json | 1 + .../google-gax/build/protos/locations.d.ts | 4060 ++++ .../google-gax/build/protos/locations.js | 1 + .../google-gax/build/protos/locations.json | 1 + .../google-gax/build/protos/operations.d.ts | 4783 ++++ .../google-gax/build/protos/operations.js | 1 + .../google-gax/build/protos/operations.json | 1 + .../google-gax/build/protos/status.json | 1 + .../google-gax/build/src/apiCaller.d.ts | 33 + .../google-gax/build/src/apiCaller.js | 26 + .../google-gax/build/src/apiCaller.js.map | 1 + .../google-gax/build/src/apitypes.d.ts | 63 + node_modules/google-gax/build/src/apitypes.js | 18 + .../google-gax/build/src/apitypes.js.map | 1 + .../src/bundlingCalls/bundleApiCaller.d.ts | 34 + .../src/bundlingCalls/bundleApiCaller.js | 55 + .../src/bundlingCalls/bundleApiCaller.js.map | 1 + .../src/bundlingCalls/bundleDescriptor.d.ts | 57 + .../src/bundlingCalls/bundleDescriptor.js | 73 + .../src/bundlingCalls/bundleDescriptor.js.map | 1 + .../src/bundlingCalls/bundleExecutor.d.ts | 116 + .../build/src/bundlingCalls/bundleExecutor.js | 195 + .../src/bundlingCalls/bundleExecutor.js.map | 1 + .../src/bundlingCalls/bundlingUtils.d.ts | 31 + .../build/src/bundlingCalls/bundlingUtils.js | 72 + .../src/bundlingCalls/bundlingUtils.js.map | 1 + .../build/src/bundlingCalls/task.d.ts | 98 + .../build/src/bundlingCalls/task.js | 228 + .../build/src/bundlingCalls/task.js.map | 1 + node_modules/google-gax/build/src/call.d.ts | 60 + node_modules/google-gax/build/src/call.js | 119 + node_modules/google-gax/build/src/call.js.map | 1 + .../google-gax/build/src/clientInterface.d.ts | 48 + .../google-gax/build/src/clientInterface.js | 20 + .../build/src/clientInterface.js.map | 1 + .../google-gax/build/src/createApiCall.d.ts | 38 + .../google-gax/build/src/createApiCall.js | 122 + .../google-gax/build/src/createApiCall.js.map | 1 + .../google-gax/build/src/descriptor.d.ts | 24 + .../google-gax/build/src/descriptor.js | 27 + .../google-gax/build/src/descriptor.js.map | 1 + .../google-gax/build/src/fallback.d.ts | 166 + node_modules/google-gax/build/src/fallback.js | 350 + .../google-gax/build/src/fallback.js.map | 1 + .../google-gax/build/src/fallbackRest.d.ts | 18 + .../google-gax/build/src/fallbackRest.js | 78 + .../google-gax/build/src/fallbackRest.js.map | 1 + .../build/src/fallbackServiceStub.d.ts | 34 + .../build/src/fallbackServiceStub.js | 152 + .../build/src/fallbackServiceStub.js.map | 1 + .../build/src/featureDetection.d.ts | 18 + .../google-gax/build/src/featureDetection.js | 43 + .../build/src/featureDetection.js.map | 1 + node_modules/google-gax/build/src/gax.d.ts | 381 + node_modules/google-gax/build/src/gax.js | 612 + node_modules/google-gax/build/src/gax.js.map | 1 + .../google-gax/build/src/googleError.d.ts | 74 + .../google-gax/build/src/googleError.js | 225 + .../google-gax/build/src/googleError.js.map | 1 + node_modules/google-gax/build/src/grpc.d.ts | 190 + node_modules/google-gax/build/src/grpc.js | 469 + node_modules/google-gax/build/src/grpc.js.map | 1 + .../google-gax/build/src/iamService.d.ts | 89 + .../google-gax/build/src/iamService.js | 232 + .../google-gax/build/src/iamService.js.map | 1 + .../src/iam_policy_service_client_config.json | 38 + node_modules/google-gax/build/src/index.d.ts | 58 + node_modules/google-gax/build/src/index.js | 95 + .../google-gax/build/src/index.js.map | 1 + .../google-gax/build/src/locationService.d.ts | 127 + .../google-gax/build/src/locationService.js | 357 + .../build/src/locationService.js.map | 1 + .../build/src/locations_client_config.json | 35 + .../longRunningApiCaller.d.ts | 40 + .../longRunningCalls/longRunningApiCaller.js | 72 + .../longRunningApiCaller.js.map | 1 + .../longRunningDescriptor.d.ts | 35 + .../longRunningCalls/longRunningDescriptor.js | 34 + .../longRunningDescriptor.js.map | 1 + .../src/longRunningCalls/longrunning.d.ts | 132 + .../build/src/longRunningCalls/longrunning.js | 280 + .../src/longRunningCalls/longrunning.js.map | 1 + .../src/normalCalls/normalApiCaller.d.ts | 29 + .../build/src/normalCalls/normalApiCaller.js | 44 + .../src/normalCalls/normalApiCaller.js.map | 1 + .../build/src/normalCalls/retries.d.ts | 31 + .../build/src/normalCalls/retries.js | 144 + .../build/src/normalCalls/retries.js.map | 1 + .../build/src/normalCalls/timeout.d.ts | 32 + .../build/src/normalCalls/timeout.js | 47 + .../build/src/normalCalls/timeout.js.map | 1 + .../build/src/operationsClient.d.ts | 315 + .../google-gax/build/src/operationsClient.js | 445 + .../build/src/operationsClient.js.map | 1 + .../build/src/operations_client_config.json | 46 + .../src/paginationCalls/pageDescriptor.d.ts | 43 + .../src/paginationCalls/pageDescriptor.js | 159 + .../src/paginationCalls/pageDescriptor.js.map | 1 + .../src/paginationCalls/pagedApiCaller.d.ts | 80 + .../src/paginationCalls/pagedApiCaller.js | 137 + .../src/paginationCalls/pagedApiCaller.js.map | 1 + .../paginationCalls/resourceCollector.d.ts | 34 + .../src/paginationCalls/resourceCollector.js | 67 + .../paginationCalls/resourceCollector.js.map | 1 + .../google-gax/build/src/pathTemplate.d.ts | 60 + .../google-gax/build/src/pathTemplate.js | 237 + .../google-gax/build/src/pathTemplate.js.map | 1 + .../google-gax/build/src/protobuf.d.ts | 16 + node_modules/google-gax/build/src/protobuf.js | 25 + .../google-gax/build/src/protobuf.js.map | 1 + .../google-gax/build/src/protosList.json | 137 + .../google-gax/build/src/routingHeader.d.ts | 32 + .../google-gax/build/src/routingHeader.js | 37 + .../google-gax/build/src/routingHeader.js.map | 1 + node_modules/google-gax/build/src/status.d.ts | 36 + node_modules/google-gax/build/src/status.js | 77 + .../google-gax/build/src/status.js.map | 1 + .../build/src/streamArrayParser.d.ts | 53 + .../google-gax/build/src/streamArrayParser.js | 150 + .../build/src/streamArrayParser.js.map | 1 + .../src/streamingCalls/streamDescriptor.d.ts | 29 + .../src/streamingCalls/streamDescriptor.js | 38 + .../streamingCalls/streamDescriptor.js.map | 1 + .../build/src/streamingCalls/streaming.d.ts | 125 + .../build/src/streamingCalls/streaming.js | 453 + .../build/src/streamingCalls/streaming.js.map | 1 + .../streamingCalls/streamingApiCaller.d.ts | 35 + .../src/streamingCalls/streamingApiCaller.js | 64 + .../streamingCalls/streamingApiCaller.js.map | 1 + .../google-gax/build/src/transcoding.d.ts | 48 + .../google-gax/build/src/transcoding.js | 281 + .../google-gax/build/src/transcoding.js.map | 1 + node_modules/google-gax/build/src/util.d.ts | 21 + node_modules/google-gax/build/src/util.js | 110 + node_modules/google-gax/build/src/util.js.map | 1 + .../google-gax/build/src/warnings.d.ts | 16 + node_modules/google-gax/build/src/warnings.js | 40 + .../google-gax/build/src/warnings.js.map | 1 + .../google-gax/node_modules/.bin/uuid | 16 + .../google-gax/node_modules/.bin/uuid.cmd | 17 + .../google-gax/node_modules/.bin/uuid.ps1 | 28 + .../google-gax/node_modules/uuid/CHANGELOG.md | 274 + .../node_modules/uuid/CONTRIBUTING.md | 18 + .../google-gax/node_modules/uuid/LICENSE.md | 9 + .../google-gax/node_modules/uuid/README.md | 466 + .../node_modules/uuid/dist/bin/uuid | 2 + .../uuid/dist/commonjs-browser/index.js | 79 + .../uuid/dist/commonjs-browser/md5.js | 223 + .../uuid/dist/commonjs-browser/native.js | 11 + .../uuid/dist/commonjs-browser/nil.js | 8 + .../uuid/dist/commonjs-browser/parse.js | 45 + .../uuid/dist/commonjs-browser/regex.js | 8 + .../uuid/dist/commonjs-browser/rng.js | 25 + .../uuid/dist/commonjs-browser/sha1.js | 104 + .../uuid/dist/commonjs-browser/stringify.js | 44 + .../uuid/dist/commonjs-browser/v1.js | 107 + .../uuid/dist/commonjs-browser/v3.js | 16 + .../uuid/dist/commonjs-browser/v35.js | 80 + .../uuid/dist/commonjs-browser/v4.js | 43 + .../uuid/dist/commonjs-browser/v5.js | 16 + .../uuid/dist/commonjs-browser/validate.js | 17 + .../uuid/dist/commonjs-browser/version.js | 21 + .../uuid/dist/esm-browser/index.js | 9 + .../node_modules/uuid/dist/esm-browser/md5.js | 215 + .../uuid/dist/esm-browser/native.js | 4 + .../node_modules/uuid/dist/esm-browser/nil.js | 1 + .../uuid/dist/esm-browser/parse.js | 35 + .../uuid/dist/esm-browser/regex.js | 1 + .../node_modules/uuid/dist/esm-browser/rng.js | 18 + .../uuid/dist/esm-browser/sha1.js | 96 + .../uuid/dist/esm-browser/stringify.js | 33 + .../node_modules/uuid/dist/esm-browser/v1.js | 95 + .../node_modules/uuid/dist/esm-browser/v3.js | 4 + .../node_modules/uuid/dist/esm-browser/v35.js | 66 + .../node_modules/uuid/dist/esm-browser/v4.js | 29 + .../node_modules/uuid/dist/esm-browser/v5.js | 4 + .../uuid/dist/esm-browser/validate.js | 7 + .../uuid/dist/esm-browser/version.js | 11 + .../node_modules/uuid/dist/esm-node/index.js | 9 + .../node_modules/uuid/dist/esm-node/md5.js | 13 + .../node_modules/uuid/dist/esm-node/native.js | 4 + .../node_modules/uuid/dist/esm-node/nil.js | 1 + .../node_modules/uuid/dist/esm-node/parse.js | 35 + .../node_modules/uuid/dist/esm-node/regex.js | 1 + .../node_modules/uuid/dist/esm-node/rng.js | 12 + .../node_modules/uuid/dist/esm-node/sha1.js | 13 + .../uuid/dist/esm-node/stringify.js | 33 + .../node_modules/uuid/dist/esm-node/v1.js | 95 + .../node_modules/uuid/dist/esm-node/v3.js | 4 + .../node_modules/uuid/dist/esm-node/v35.js | 66 + .../node_modules/uuid/dist/esm-node/v4.js | 29 + .../node_modules/uuid/dist/esm-node/v5.js | 4 + .../uuid/dist/esm-node/validate.js | 7 + .../uuid/dist/esm-node/version.js | 11 + .../node_modules/uuid/dist/index.js | 79 + .../node_modules/uuid/dist/md5-browser.js | 223 + .../google-gax/node_modules/uuid/dist/md5.js | 23 + .../node_modules/uuid/dist/native-browser.js | 11 + .../node_modules/uuid/dist/native.js | 15 + .../google-gax/node_modules/uuid/dist/nil.js | 8 + .../node_modules/uuid/dist/parse.js | 45 + .../node_modules/uuid/dist/regex.js | 8 + .../node_modules/uuid/dist/rng-browser.js | 25 + .../google-gax/node_modules/uuid/dist/rng.js | 24 + .../node_modules/uuid/dist/sha1-browser.js | 104 + .../google-gax/node_modules/uuid/dist/sha1.js | 23 + .../node_modules/uuid/dist/stringify.js | 44 + .../node_modules/uuid/dist/uuid-bin.js | 85 + .../google-gax/node_modules/uuid/dist/v1.js | 107 + .../google-gax/node_modules/uuid/dist/v3.js | 16 + .../google-gax/node_modules/uuid/dist/v35.js | 80 + .../google-gax/node_modules/uuid/dist/v4.js | 43 + .../google-gax/node_modules/uuid/dist/v5.js | 16 + .../node_modules/uuid/dist/validate.js | 17 + .../node_modules/uuid/dist/version.js | 21 + .../google-gax/node_modules/uuid/package.json | 135 + .../google-gax/node_modules/uuid/wrapper.mjs | 10 + node_modules/google-gax/package.json | 113 + node_modules/google-logging-utils/LICENSE | 202 + .../build/src/colours.d.ts | 29 + .../google-logging-utils/build/src/colours.js | 80 + .../build/src/colours.js.map | 1 + .../google-logging-utils/build/src/index.d.ts | 1 + .../google-logging-utils/build/src/index.js | 31 + .../build/src/index.js.map | 1 + .../build/src/logging-utils.d.ts | 222 + .../build/src/logging-utils.js | 406 + .../build/src/logging-utils.js.map | 1 + .../build/src/temporal.d.ts | 45 + .../build/src/temporal.js | 68 + .../build/src/temporal.js.map | 1 + .../google-logging-utils/package.json | 39 + node_modules/gopd/.eslintrc | 16 + node_modules/gopd/.github/FUNDING.yml | 12 + node_modules/gopd/CHANGELOG.md | 45 + node_modules/gopd/LICENSE | 21 + node_modules/gopd/README.md | 40 + node_modules/gopd/gOPD.d.ts | 1 + node_modules/gopd/gOPD.js | 4 + node_modules/gopd/index.d.ts | 5 + node_modules/gopd/index.js | 15 + node_modules/gopd/package.json | 77 + node_modules/gopd/test/index.js | 36 + node_modules/gopd/tsconfig.json | 9 + node_modules/gtoken/CHANGELOG.md | 372 + node_modules/gtoken/LICENSE | 21 + node_modules/gtoken/README.md | 187 + node_modules/gtoken/build/src/index.d.ts | 93 + node_modules/gtoken/build/src/index.js | 276 + node_modules/gtoken/package.json | 62 + node_modules/has-symbols/.eslintrc | 11 + node_modules/has-symbols/.github/FUNDING.yml | 12 + node_modules/has-symbols/.nycrc | 9 + node_modules/has-symbols/CHANGELOG.md | 91 + node_modules/has-symbols/LICENSE | 21 + node_modules/has-symbols/README.md | 46 + node_modules/has-symbols/index.d.ts | 3 + node_modules/has-symbols/index.js | 14 + node_modules/has-symbols/package.json | 111 + node_modules/has-symbols/shams.d.ts | 3 + node_modules/has-symbols/shams.js | 45 + node_modules/has-symbols/test/index.js | 22 + .../has-symbols/test/shams/core-js.js | 29 + .../test/shams/get-own-property-symbols.js | 29 + node_modules/has-symbols/test/tests.js | 58 + node_modules/has-symbols/tsconfig.json | 10 + node_modules/has-tostringtag/.eslintrc | 5 + .../has-tostringtag/.github/FUNDING.yml | 12 + node_modules/has-tostringtag/.nycrc | 13 + node_modules/has-tostringtag/CHANGELOG.md | 42 + node_modules/has-tostringtag/LICENSE | 21 + node_modules/has-tostringtag/README.md | 46 + node_modules/has-tostringtag/index.d.ts | 3 + node_modules/has-tostringtag/index.js | 8 + node_modules/has-tostringtag/package.json | 108 + node_modules/has-tostringtag/shams.d.ts | 3 + node_modules/has-tostringtag/shams.js | 8 + node_modules/has-tostringtag/test/index.js | 21 + .../has-tostringtag/test/shams/core-js.js | 31 + .../test/shams/get-own-property-symbols.js | 30 + node_modules/has-tostringtag/test/tests.js | 15 + node_modules/has-tostringtag/tsconfig.json | 49 + node_modules/hasown/.eslintrc | 5 + node_modules/hasown/.github/FUNDING.yml | 12 + node_modules/hasown/.nycrc | 13 + node_modules/hasown/CHANGELOG.md | 40 + node_modules/hasown/LICENSE | 21 + node_modules/hasown/README.md | 40 + node_modules/hasown/index.d.ts | 3 + node_modules/hasown/index.js | 8 + node_modules/hasown/package.json | 92 + node_modules/hasown/tsconfig.json | 6 + node_modules/html-entities/LICENSE | 19 + node_modules/html-entities/README.md | 220 + .../html-entities/dist/commonjs/index.d.ts | 20 + .../html-entities/dist/commonjs/index.js | 129 + .../html-entities/dist/commonjs/index.js.flow | 52 + .../html-entities/dist/commonjs/index.js.map | 1 + .../dist/commonjs/named-references.js | 50 + .../dist/commonjs/named-references.js.map | 1 + .../dist/commonjs/numeric-unicode-map.js | 34 + .../dist/commonjs/numeric-unicode-map.js.map | 1 + .../html-entities/dist/commonjs/package.json | 3 + .../dist/commonjs/surrogate-pairs.js | 18 + .../dist/commonjs/surrogate-pairs.js.map | 1 + .../html-entities/dist/esm/index.d.ts | 20 + node_modules/html-entities/dist/esm/index.js | 124 + .../html-entities/dist/esm/index.js.map | 1 + .../dist/esm/named-references.js | 47 + .../dist/esm/named-references.js.map | 1 + .../dist/esm/numeric-unicode-map.js | 31 + .../dist/esm/numeric-unicode-map.js.map | 1 + .../html-entities/dist/esm/package.json | 3 + .../html-entities/dist/esm/surrogate-pairs.js | 15 + .../dist/esm/surrogate-pairs.js.map | 1 + node_modules/html-entities/package.json | 106 + node_modules/html-entities/src/index.ts | 164 + .../html-entities/src/named-references.ts | 48 + .../html-entities/src/numeric-unicode-map.ts | 30 + .../html-entities/src/surrogate-pairs.ts | 20 + node_modules/http-parser-js/LICENSE.md | 110 + node_modules/http-parser-js/README.md | 43 + node_modules/http-parser-js/http-parser.d.ts | 181 + node_modules/http-parser-js/http-parser.js | 470 + node_modules/http-parser-js/package.json | 30 + node_modules/http-proxy-agent/README.md | 74 + node_modules/http-proxy-agent/dist/agent.d.ts | 32 + node_modules/http-proxy-agent/dist/agent.js | 145 + .../http-proxy-agent/dist/agent.js.map | 1 + node_modules/http-proxy-agent/dist/index.d.ts | 21 + node_modules/http-proxy-agent/dist/index.js | 14 + .../http-proxy-agent/dist/index.js.map | 1 + .../node_modules/agent-base/README.md | 145 + .../agent-base/dist/src/index.d.ts | 78 + .../node_modules/agent-base/dist/src/index.js | 203 + .../agent-base/dist/src/index.js.map | 1 + .../agent-base/dist/src/promisify.d.ts | 4 + .../agent-base/dist/src/promisify.js | 18 + .../agent-base/dist/src/promisify.js.map | 1 + .../node_modules/agent-base/package.json | 64 + .../node_modules/agent-base/src/index.ts | 345 + .../node_modules/agent-base/src/promisify.ts | 33 + node_modules/http-proxy-agent/package.json | 57 + node_modules/https-proxy-agent/LICENSE | 22 + node_modules/https-proxy-agent/README.md | 70 + .../https-proxy-agent/dist/index.d.ts | 47 + .../https-proxy-agent/dist/index.d.ts.map | 1 + node_modules/https-proxy-agent/dist/index.js | 180 + .../https-proxy-agent/dist/index.js.map | 1 + .../dist/parse-proxy-response.d.ts | 15 + .../dist/parse-proxy-response.d.ts.map | 1 + .../dist/parse-proxy-response.js | 101 + .../dist/parse-proxy-response.js.map | 1 + node_modules/https-proxy-agent/package.json | 50 + node_modules/inherits/LICENSE | 16 + node_modules/inherits/README.md | 42 + node_modules/inherits/inherits.js | 9 + node_modules/inherits/inherits_browser.js | 27 + node_modules/inherits/package.json | 29 + .../is-fullwidth-code-point/index.d.ts | 17 + node_modules/is-fullwidth-code-point/index.js | 50 + node_modules/is-fullwidth-code-point/license | 9 + .../is-fullwidth-code-point/package.json | 42 + .../is-fullwidth-code-point/readme.md | 39 + node_modules/is-stream/index.d.ts | 79 + node_modules/is-stream/index.js | 28 + node_modules/is-stream/license | 9 + node_modules/is-stream/package.json | 42 + node_modules/is-stream/readme.md | 60 + node_modules/jose/LICENSE.md | 21 + node_modules/jose/README.md | 132 + node_modules/jose/dist/browser/index.js | 32 + .../jose/dist/browser/jwe/compact/decrypt.js | 27 + .../jose/dist/browser/jwe/compact/encrypt.js | 26 + .../dist/browser/jwe/flattened/decrypt.js | 166 + .../dist/browser/jwe/flattened/encrypt.js | 175 + .../jose/dist/browser/jwe/general/decrypt.js | 31 + .../jose/dist/browser/jwe/general/encrypt.js | 178 + .../jose/dist/browser/jwk/embedded.js | 17 + .../jose/dist/browser/jwk/thumbprint.js | 53 + node_modules/jose/dist/browser/jwks/local.js | 116 + node_modules/jose/dist/browser/jwks/remote.js | 76 + .../jose/dist/browser/jws/compact/sign.js | 17 + .../jose/dist/browser/jws/compact/verify.js | 21 + .../jose/dist/browser/jws/flattened/sign.js | 81 + .../jose/dist/browser/jws/flattened/verify.js | 115 + .../jose/dist/browser/jws/general/sign.js | 67 + .../jose/dist/browser/jws/general/verify.js | 24 + node_modules/jose/dist/browser/jwt/decrypt.js | 23 + node_modules/jose/dist/browser/jwt/encrypt.js | 68 + node_modules/jose/dist/browser/jwt/produce.js | 54 + node_modules/jose/dist/browser/jwt/sign.js | 21 + .../jose/dist/browser/jwt/unsecured.js | 32 + node_modules/jose/dist/browser/jwt/verify.js | 16 + node_modules/jose/dist/browser/key/export.js | 12 + .../dist/browser/key/generate_key_pair.js | 4 + .../jose/dist/browser/key/generate_secret.js | 4 + node_modules/jose/dist/browser/key/import.js | 50 + .../jose/dist/browser/lib/aesgcmkw.js | 14 + .../jose/dist/browser/lib/buffer_utils.js | 51 + node_modules/jose/dist/browser/lib/cek.js | 20 + .../jose/dist/browser/lib/check_iv_length.js | 8 + .../jose/dist/browser/lib/check_key_type.js | 45 + .../jose/dist/browser/lib/check_p2s.js | 6 + .../jose/dist/browser/lib/crypto_key.js | 152 + .../browser/lib/decrypt_key_management.js | 127 + .../browser/lib/encrypt_key_management.js | 87 + node_modules/jose/dist/browser/lib/epoch.js | 1 + .../jose/dist/browser/lib/format_pem.js | 4 + .../dist/browser/lib/invalid_key_input.js | 30 + .../jose/dist/browser/lib/is_disjoint.js | 22 + .../jose/dist/browser/lib/is_object.js | 16 + node_modules/jose/dist/browser/lib/iv.js | 20 + .../jose/dist/browser/lib/jwt_claims_set.js | 102 + node_modules/jose/dist/browser/lib/secs.js | 44 + .../dist/browser/lib/validate_algorithms.js | 11 + .../jose/dist/browser/lib/validate_crit.js | 34 + node_modules/jose/dist/browser/package.json | 1 + .../jose/dist/browser/runtime/aeskw.js | 32 + .../jose/dist/browser/runtime/asn1.js | 202 + .../jose/dist/browser/runtime/base64url.js | 37 + .../jose/dist/browser/runtime/bogus.js | 6 + .../dist/browser/runtime/check_cek_length.js | 8 + .../dist/browser/runtime/check_key_length.js | 8 + .../jose/dist/browser/runtime/decrypt.js | 85 + .../jose/dist/browser/runtime/digest.js | 6 + .../jose/dist/browser/runtime/ecdhes.js | 46 + .../jose/dist/browser/runtime/encrypt.js | 68 + .../jose/dist/browser/runtime/fetch_jwks.js | 34 + .../jose/dist/browser/runtime/generate.js | 141 + .../browser/runtime/get_sign_verify_key.js | 17 + .../jose/dist/browser/runtime/is_key_like.js | 5 + .../jose/dist/browser/runtime/jwk_to_key.js | 143 + .../jose/dist/browser/runtime/key_to_jwk.js | 21 + .../jose/dist/browser/runtime/pbes2kw.js | 51 + .../jose/dist/browser/runtime/random.js | 2 + .../jose/dist/browser/runtime/rsaes.js | 37 + .../jose/dist/browser/runtime/runtime.js | 1 + .../jose/dist/browser/runtime/sign.js | 11 + .../jose/dist/browser/runtime/subtle_dsa.js | 26 + .../jose/dist/browser/runtime/subtle_rsaes.js | 12 + .../dist/browser/runtime/timing_safe_equal.js | 19 + .../jose/dist/browser/runtime/verify.js | 16 + .../jose/dist/browser/runtime/webcrypto.js | 2 + .../jose/dist/browser/runtime/zlib.js | 7 + .../jose/dist/browser/util/base64url.js | 3 + .../jose/dist/browser/util/decode_jwt.js | 32 + .../browser/util/decode_protected_header.js | 34 + node_modules/jose/dist/browser/util/errors.js | 158 + .../jose/dist/browser/util/runtime.js | 2 + node_modules/jose/dist/node/cjs/index.js | 67 + .../jose/dist/node/cjs/jwe/compact/decrypt.js | 31 + .../jose/dist/node/cjs/jwe/compact/encrypt.js | 30 + .../dist/node/cjs/jwe/flattened/decrypt.js | 170 + .../dist/node/cjs/jwe/flattened/encrypt.js | 179 + .../jose/dist/node/cjs/jwe/general/decrypt.js | 35 + .../jose/dist/node/cjs/jwe/general/encrypt.js | 182 + .../jose/dist/node/cjs/jwk/embedded.js | 21 + .../jose/dist/node/cjs/jwk/thumbprint.js | 58 + node_modules/jose/dist/node/cjs/jwks/local.js | 122 + .../jose/dist/node/cjs/jwks/remote.js | 80 + .../jose/dist/node/cjs/jws/compact/sign.js | 21 + .../jose/dist/node/cjs/jws/compact/verify.js | 25 + .../jose/dist/node/cjs/jws/flattened/sign.js | 85 + .../dist/node/cjs/jws/flattened/verify.js | 119 + .../jose/dist/node/cjs/jws/general/sign.js | 71 + .../jose/dist/node/cjs/jws/general/verify.js | 28 + .../jose/dist/node/cjs/jwt/decrypt.js | 27 + .../jose/dist/node/cjs/jwt/encrypt.js | 72 + .../jose/dist/node/cjs/jwt/produce.js | 58 + node_modules/jose/dist/node/cjs/jwt/sign.js | 25 + .../jose/dist/node/cjs/jwt/unsecured.js | 36 + node_modules/jose/dist/node/cjs/jwt/verify.js | 20 + node_modules/jose/dist/node/cjs/key/export.js | 18 + .../dist/node/cjs/key/generate_key_pair.js | 8 + .../jose/dist/node/cjs/key/generate_secret.js | 8 + node_modules/jose/dist/node/cjs/key/import.js | 57 + .../jose/dist/node/cjs/lib/aesgcmkw.js | 19 + .../jose/dist/node/cjs/lib/buffer_utils.js | 60 + node_modules/jose/dist/node/cjs/lib/cek.js | 24 + .../jose/dist/node/cjs/lib/check_iv_length.js | 10 + .../jose/dist/node/cjs/lib/check_key_type.js | 47 + .../jose/dist/node/cjs/lib/check_p2s.js | 9 + .../jose/dist/node/cjs/lib/crypto_key.js | 157 + .../node/cjs/lib/decrypt_key_management.js | 129 + .../node/cjs/lib/encrypt_key_management.js | 89 + node_modules/jose/dist/node/cjs/lib/epoch.js | 3 + .../dist/node/cjs/lib/invalid_key_input.js | 34 + .../jose/dist/node/cjs/lib/is_disjoint.js | 24 + .../jose/dist/node/cjs/lib/is_object.js | 19 + node_modules/jose/dist/node/cjs/lib/iv.js | 24 + .../jose/dist/node/cjs/lib/jwt_claims_set.js | 104 + node_modules/jose/dist/node/cjs/lib/secs.js | 46 + .../dist/node/cjs/lib/validate_algorithms.js | 13 + .../jose/dist/node/cjs/lib/validate_crit.js | 36 + .../jose/dist/node/cjs/runtime/aeskw.js | 55 + .../jose/dist/node/cjs/runtime/asn1.js | 54 + .../node/cjs/runtime/asn1_sequence_decoder.js | 47 + .../node/cjs/runtime/asn1_sequence_encoder.js | 91 + .../jose/dist/node/cjs/runtime/base64url.js | 25 + .../jose/dist/node/cjs/runtime/cbc_tag.js | 11 + .../dist/node/cjs/runtime/check_cek_length.js | 37 + .../node/cjs/runtime/check_modulus_length.js | 52 + .../jose/dist/node/cjs/runtime/ciphers.js | 8 + .../jose/dist/node/cjs/runtime/decrypt.js | 97 + .../jose/dist/node/cjs/runtime/digest.js | 5 + .../jose/dist/node/cjs/runtime/dsa_digest.js | 25 + .../jose/dist/node/cjs/runtime/ecdhes.js | 70 + .../jose/dist/node/cjs/runtime/encrypt.js | 74 + .../jose/dist/node/cjs/runtime/fetch_jwks.js | 45 + .../jose/dist/node/cjs/runtime/flags.js | 8 + .../jose/dist/node/cjs/runtime/generate.js | 105 + .../dist/node/cjs/runtime/get_named_curve.js | 95 + .../node/cjs/runtime/get_sign_verify_key.js | 24 + .../jose/dist/node/cjs/runtime/hmac_digest.js | 16 + .../jose/dist/node/cjs/runtime/is_key_like.js | 11 + .../dist/node/cjs/runtime/is_key_object.js | 7 + .../jose/dist/node/cjs/runtime/jwk_to_key.js | 118 + .../jose/dist/node/cjs/runtime/key_to_jwk.js | 160 + .../jose/dist/node/cjs/runtime/node_key.js | 78 + .../jose/dist/node/cjs/runtime/pbes2kw.js | 48 + .../jose/dist/node/cjs/runtime/random.js | 5 + .../jose/dist/node/cjs/runtime/rsaes.js | 69 + .../jose/dist/node/cjs/runtime/runtime.js | 3 + .../jose/dist/node/cjs/runtime/sign.js | 25 + .../node/cjs/runtime/timing_safe_equal.js | 5 + .../jose/dist/node/cjs/runtime/verify.js | 38 + .../jose/dist/node/cjs/runtime/webcrypto.js | 11 + .../jose/dist/node/cjs/runtime/zlib.js | 14 + .../jose/dist/node/cjs/util/base64url.js | 6 + .../jose/dist/node/cjs/util/decode_jwt.js | 36 + .../node/cjs/util/decode_protected_header.js | 38 + .../jose/dist/node/cjs/util/errors.js | 177 + .../jose/dist/node/cjs/util/runtime.js | 4 + node_modules/jose/dist/node/esm/index.js | 30 + .../jose/dist/node/esm/jwe/compact/decrypt.js | 27 + .../jose/dist/node/esm/jwe/compact/encrypt.js | 26 + .../dist/node/esm/jwe/flattened/decrypt.js | 166 + .../dist/node/esm/jwe/flattened/encrypt.js | 175 + .../jose/dist/node/esm/jwe/general/decrypt.js | 31 + .../jose/dist/node/esm/jwe/general/encrypt.js | 178 + .../jose/dist/node/esm/jwk/embedded.js | 17 + .../jose/dist/node/esm/jwk/thumbprint.js | 53 + node_modules/jose/dist/node/esm/jwks/local.js | 116 + .../jose/dist/node/esm/jwks/remote.js | 76 + .../jose/dist/node/esm/jws/compact/sign.js | 17 + .../jose/dist/node/esm/jws/compact/verify.js | 21 + .../jose/dist/node/esm/jws/flattened/sign.js | 81 + .../dist/node/esm/jws/flattened/verify.js | 115 + .../jose/dist/node/esm/jws/general/sign.js | 67 + .../jose/dist/node/esm/jws/general/verify.js | 24 + .../jose/dist/node/esm/jwt/decrypt.js | 23 + .../jose/dist/node/esm/jwt/encrypt.js | 68 + .../jose/dist/node/esm/jwt/produce.js | 54 + node_modules/jose/dist/node/esm/jwt/sign.js | 21 + .../jose/dist/node/esm/jwt/unsecured.js | 32 + node_modules/jose/dist/node/esm/jwt/verify.js | 16 + node_modules/jose/dist/node/esm/key/export.js | 12 + .../dist/node/esm/key/generate_key_pair.js | 4 + .../jose/dist/node/esm/key/generate_secret.js | 4 + node_modules/jose/dist/node/esm/key/import.js | 50 + .../jose/dist/node/esm/lib/aesgcmkw.js | 14 + .../jose/dist/node/esm/lib/buffer_utils.js | 51 + node_modules/jose/dist/node/esm/lib/cek.js | 20 + .../jose/dist/node/esm/lib/check_iv_length.js | 8 + .../jose/dist/node/esm/lib/check_key_type.js | 45 + .../jose/dist/node/esm/lib/check_p2s.js | 6 + .../jose/dist/node/esm/lib/crypto_key.js | 152 + .../node/esm/lib/decrypt_key_management.js | 127 + .../node/esm/lib/encrypt_key_management.js | 87 + node_modules/jose/dist/node/esm/lib/epoch.js | 1 + .../dist/node/esm/lib/invalid_key_input.js | 30 + .../jose/dist/node/esm/lib/is_disjoint.js | 22 + .../jose/dist/node/esm/lib/is_object.js | 16 + node_modules/jose/dist/node/esm/lib/iv.js | 20 + .../jose/dist/node/esm/lib/jwt_claims_set.js | 102 + node_modules/jose/dist/node/esm/lib/secs.js | 44 + .../dist/node/esm/lib/validate_algorithms.js | 11 + .../jose/dist/node/esm/lib/validate_crit.js | 34 + node_modules/jose/dist/node/esm/package.json | 1 + .../jose/dist/node/esm/runtime/aeskw.js | 50 + .../jose/dist/node/esm/runtime/asn1.js | 46 + .../node/esm/runtime/asn1_sequence_decoder.js | 44 + .../node/esm/runtime/asn1_sequence_encoder.js | 88 + .../jose/dist/node/esm/runtime/base64url.js | 20 + .../jose/dist/node/esm/runtime/cbc_tag.js | 8 + .../dist/node/esm/runtime/check_cek_length.js | 35 + .../node/esm/runtime/check_modulus_length.js | 48 + .../jose/dist/node/esm/runtime/ciphers.js | 6 + .../jose/dist/node/esm/runtime/decrypt.js | 95 + .../jose/dist/node/esm/runtime/digest.js | 3 + .../jose/dist/node/esm/runtime/dsa_digest.js | 22 + .../jose/dist/node/esm/runtime/ecdhes.js | 64 + .../jose/dist/node/esm/runtime/encrypt.js | 72 + .../jose/dist/node/esm/runtime/fetch_jwks.js | 43 + .../jose/dist/node/esm/runtime/flags.js | 5 + .../jose/dist/node/esm/runtime/generate.js | 100 + .../dist/node/esm/runtime/get_named_curve.js | 91 + .../node/esm/runtime/get_sign_verify_key.js | 21 + .../jose/dist/node/esm/runtime/hmac_digest.js | 13 + .../jose/dist/node/esm/runtime/is_key_like.js | 8 + .../dist/node/esm/runtime/is_key_object.js | 5 + .../jose/dist/node/esm/runtime/jwk_to_key.js | 116 + .../jose/dist/node/esm/runtime/key_to_jwk.js | 158 + .../jose/dist/node/esm/runtime/node_key.js | 75 + .../jose/dist/node/esm/runtime/pbes2kw.js | 43 + .../jose/dist/node/esm/runtime/random.js | 1 + .../jose/dist/node/esm/runtime/rsaes.js | 64 + .../jose/dist/node/esm/runtime/runtime.js | 1 + .../jose/dist/node/esm/runtime/sign.js | 23 + .../node/esm/runtime/timing_safe_equal.js | 3 + .../jose/dist/node/esm/runtime/verify.js | 36 + .../jose/dist/node/esm/runtime/webcrypto.js | 8 + .../jose/dist/node/esm/runtime/zlib.js | 9 + .../jose/dist/node/esm/util/base64url.js | 3 + .../jose/dist/node/esm/util/decode_jwt.js | 32 + .../node/esm/util/decode_protected_header.js | 34 + .../jose/dist/node/esm/util/errors.js | 158 + .../jose/dist/node/esm/util/runtime.js | 2 + node_modules/jose/dist/types/index.d.ts | 48 + .../jose/dist/types/jwe/compact/decrypt.d.ts | 23 + .../jose/dist/types/jwe/compact/encrypt.d.ts | 52 + .../dist/types/jwe/flattened/decrypt.d.ts | 23 + .../dist/types/jwe/flattened/encrypt.d.ts | 80 + .../jose/dist/types/jwe/general/decrypt.d.ts | 23 + .../jose/dist/types/jwe/general/encrypt.d.ts | 60 + .../jose/dist/types/jwk/embedded.d.ts | 9 + .../jose/dist/types/jwk/thumbprint.d.ts | 21 + node_modules/jose/dist/types/jwks/local.d.ts | 26 + node_modules/jose/dist/types/jwks/remote.d.ts | 49 + .../jose/dist/types/jws/compact/sign.d.ts | 24 + .../jose/dist/types/jws/compact/verify.d.ts | 25 + .../jose/dist/types/jws/flattened/sign.d.ts | 32 + .../jose/dist/types/jws/flattened/verify.d.ts | 25 + .../jose/dist/types/jws/general/sign.d.ts | 41 + .../jose/dist/types/jws/general/verify.d.ts | 25 + node_modules/jose/dist/types/jwt/decrypt.d.ts | 27 + node_modules/jose/dist/types/jwt/encrypt.d.ts | 77 + node_modules/jose/dist/types/jwt/produce.d.ts | 54 + node_modules/jose/dist/types/jwt/sign.d.ts | 23 + .../jose/dist/types/jwt/unsecured.d.ts | 21 + node_modules/jose/dist/types/jwt/verify.d.ts | 29 + node_modules/jose/dist/types/key/export.d.ts | 21 + .../dist/types/key/generate_key_pair.d.ts | 36 + .../jose/dist/types/key/generate_secret.d.ts | 19 + node_modules/jose/dist/types/key/import.d.ts | 54 + node_modules/jose/dist/types/types.d.ts | 610 + .../jose/dist/types/util/base64url.d.ts | 19 + .../jose/dist/types/util/decode_jwt.d.ts | 10 + .../types/util/decode_protected_header.d.ts | 8 + node_modules/jose/dist/types/util/errors.d.ts | 151 + .../jose/dist/types/util/runtime.d.ts | 3 + node_modules/jose/package.json | 90 + node_modules/json-bigint/LICENSE | 20 + node_modules/json-bigint/README.md | 240 + node_modules/json-bigint/index.js | 12 + node_modules/json-bigint/lib/parse.js | 443 + node_modules/json-bigint/lib/stringify.js | 384 + node_modules/json-bigint/package.json | 34 + node_modules/jsonwebtoken/LICENSE | 21 + node_modules/jsonwebtoken/README.md | 396 + node_modules/jsonwebtoken/decode.js | 30 + node_modules/jsonwebtoken/index.js | 8 + .../jsonwebtoken/lib/JsonWebTokenError.js | 14 + .../jsonwebtoken/lib/NotBeforeError.js | 13 + .../jsonwebtoken/lib/TokenExpiredError.js | 13 + .../lib/asymmetricKeyDetailsSupported.js | 3 + node_modules/jsonwebtoken/lib/psSupported.js | 3 + .../lib/rsaPssKeyDetailsSupported.js | 3 + node_modules/jsonwebtoken/lib/timespan.js | 18 + .../jsonwebtoken/lib/validateAsymmetricKey.js | 66 + node_modules/jsonwebtoken/package.json | 70 + node_modules/jsonwebtoken/sign.js | 253 + node_modules/jsonwebtoken/verify.js | 263 + node_modules/jwa/LICENSE | 17 + node_modules/jwa/README.md | 150 + node_modules/jwa/index.js | 266 + node_modules/jwa/opslevel.yml | 6 + node_modules/jwa/package.json | 37 + node_modules/jwks-rsa/LICENSE | 21 + node_modules/jwks-rsa/README.md | 83 + node_modules/jwks-rsa/index.d.ts | 130 + node_modules/jwks-rsa/package.json | 74 + node_modules/jwks-rsa/src/JwksClient.js | 91 + .../jwks-rsa/src/errors/ArgumentError.js | 10 + node_modules/jwks-rsa/src/errors/JwksError.js | 10 + .../jwks-rsa/src/errors/JwksRateLimitError.js | 10 + .../src/errors/SigningKeyNotFoundError.js | 10 + node_modules/jwks-rsa/src/errors/index.js | 6 + node_modules/jwks-rsa/src/index.js | 22 + .../jwks-rsa/src/integrations/config.js | 15 + .../jwks-rsa/src/integrations/express.js | 60 + .../jwks-rsa/src/integrations/hapi.js | 59 + node_modules/jwks-rsa/src/integrations/koa.js | 30 + .../jwks-rsa/src/integrations/passport.js | 52 + node_modules/jwks-rsa/src/utils.js | 80 + node_modules/jwks-rsa/src/wrappers/cache.js | 15 + .../jwks-rsa/src/wrappers/callbackSupport.js | 16 + node_modules/jwks-rsa/src/wrappers/index.js | 7 + .../jwks-rsa/src/wrappers/interceptor.js | 30 + .../jwks-rsa/src/wrappers/rateLimit.js | 34 + node_modules/jwks-rsa/src/wrappers/request.js | 52 + node_modules/jws/CHANGELOG.md | 56 + node_modules/jws/LICENSE | 17 + node_modules/jws/index.js | 22 + node_modules/jws/lib/data-stream.js | 55 + node_modules/jws/lib/sign-stream.js | 83 + node_modules/jws/lib/tostring.js | 10 + node_modules/jws/lib/verify-stream.js | 125 + node_modules/jws/opslevel.yml | 6 + node_modules/jws/package.json | 34 + node_modules/jws/readme.md | 255 + node_modules/limiter/.travis.yml | 9 + node_modules/limiter/LICENSE.txt | 19 + node_modules/limiter/README.md | 140 + node_modules/limiter/bower.json | 22 + node_modules/limiter/index.d.ts | 22 + node_modules/limiter/index.js | 3 + node_modules/limiter/lib/clock.js | 13 + node_modules/limiter/lib/rateLimiter.js | 137 + node_modules/limiter/lib/tokenBucket.js | 167 + node_modules/limiter/package.json | 25 + node_modules/limiter/test/ratelimiter-test.js | 20 + node_modules/limiter/test/tokenbucket-test.js | 67 + node_modules/lodash.camelcase/LICENSE | 47 + node_modules/lodash.camelcase/README.md | 18 + node_modules/lodash.camelcase/index.js | 599 + node_modules/lodash.camelcase/package.json | 17 + node_modules/lodash.clonedeep/LICENSE | 47 + node_modules/lodash.clonedeep/README.md | 18 + node_modules/lodash.clonedeep/index.js | 1748 ++ node_modules/lodash.clonedeep/package.json | 17 + node_modules/lodash.includes/LICENSE | 47 + node_modules/lodash.includes/README.md | 18 + node_modules/lodash.includes/index.js | 745 + node_modules/lodash.includes/package.json | 17 + node_modules/lodash.isboolean/LICENSE | 22 + node_modules/lodash.isboolean/README.md | 18 + node_modules/lodash.isboolean/index.js | 70 + node_modules/lodash.isboolean/package.json | 17 + node_modules/lodash.isinteger/LICENSE | 47 + node_modules/lodash.isinteger/README.md | 18 + node_modules/lodash.isinteger/index.js | 265 + node_modules/lodash.isinteger/package.json | 17 + node_modules/lodash.isnumber/LICENSE | 22 + node_modules/lodash.isnumber/README.md | 18 + node_modules/lodash.isnumber/index.js | 79 + node_modules/lodash.isnumber/package.json | 17 + node_modules/lodash.isplainobject/LICENSE | 47 + node_modules/lodash.isplainobject/README.md | 18 + node_modules/lodash.isplainobject/index.js | 139 + .../lodash.isplainobject/package.json | 17 + node_modules/lodash.isstring/LICENSE | 22 + node_modules/lodash.isstring/README.md | 18 + node_modules/lodash.isstring/index.js | 95 + node_modules/lodash.isstring/package.json | 17 + node_modules/lodash.once/LICENSE | 47 + node_modules/lodash.once/README.md | 18 + node_modules/lodash.once/index.js | 294 + node_modules/lodash.once/package.json | 17 + node_modules/long/LICENSE | 202 + node_modules/long/README.md | 286 + node_modules/long/index.d.ts | 2 + node_modules/long/index.js | 1581 ++ node_modules/long/package.json | 58 + node_modules/long/types.d.ts | 474 + node_modules/long/umd/index.d.ts | 3 + node_modules/long/umd/index.js | 1622 ++ node_modules/long/umd/package.json | 3 + node_modules/long/umd/types.d.ts | 474 + node_modules/lru-cache/LICENSE | 15 + node_modules/lru-cache/README.md | 166 + node_modules/lru-cache/index.js | 334 + node_modules/lru-cache/package.json | 34 + node_modules/lru-memoizer/.jshintrc | 41 + node_modules/lru-memoizer/LICENSE | 21 + node_modules/lru-memoizer/README.md | 88 + node_modules/lru-memoizer/lib/async.d.ts | 85 + node_modules/lru-memoizer/lib/async.js | 178 + node_modules/lru-memoizer/lib/freeze.d.ts | 1 + node_modules/lru-memoizer/lib/freeze.js | 23 + node_modules/lru-memoizer/lib/index.d.ts | 2 + node_modules/lru-memoizer/lib/index.js | 4 + node_modules/lru-memoizer/lib/sync.d.ts | 65 + node_modules/lru-memoizer/lib/sync.js | 114 + node_modules/lru-memoizer/lib/util.d.ts | 162 + node_modules/lru-memoizer/lib/util.js | 3 + node_modules/lru-memoizer/package.json | 34 + .../test/lru-memoizer.bypass.test.js | 39 + .../test/lru-memoizer.clone.test.js | 44 + .../test/lru-memoizer.disable.test.js | 49 + .../test/lru-memoizer.events.test.js | 132 + .../test/lru-memoizer.freeze.test.js | 43 + .../test/lru-memoizer.itemmaxage.test.js | 204 + .../test/lru-memoizer.lock.test.js | 36 + .../test/lru-memoizer.nokey.test.js | 43 + .../test/lru-memoizer.queumaxage.test.js | 110 + .../test/lru-memoizer.sync.clone.test.js | 76 + .../test/lru-memoizer.sync.events.test.js | 95 + .../test/lru-memoizer.sync.freeze.js | 74 + .../test/lru-memoizer.sync.test.js | 47 + .../lru-memoizer/test/lru-memoizer.test.js | 88 + node_modules/lru-memoizer/tsconfig.json | 59 + node_modules/math-intrinsics/.eslintrc | 16 + .../math-intrinsics/.github/FUNDING.yml | 12 + node_modules/math-intrinsics/CHANGELOG.md | 24 + node_modules/math-intrinsics/LICENSE | 21 + node_modules/math-intrinsics/README.md | 50 + node_modules/math-intrinsics/abs.d.ts | 1 + node_modules/math-intrinsics/abs.js | 4 + .../constants/maxArrayLength.d.ts | 3 + .../constants/maxArrayLength.js | 4 + .../constants/maxSafeInteger.d.ts | 3 + .../constants/maxSafeInteger.js | 5 + .../math-intrinsics/constants/maxValue.d.ts | 3 + .../math-intrinsics/constants/maxValue.js | 5 + node_modules/math-intrinsics/floor.d.ts | 1 + node_modules/math-intrinsics/floor.js | 4 + node_modules/math-intrinsics/isFinite.d.ts | 3 + node_modules/math-intrinsics/isFinite.js | 12 + node_modules/math-intrinsics/isInteger.d.ts | 3 + node_modules/math-intrinsics/isInteger.js | 16 + node_modules/math-intrinsics/isNaN.d.ts | 1 + node_modules/math-intrinsics/isNaN.js | 6 + .../math-intrinsics/isNegativeZero.d.ts | 3 + .../math-intrinsics/isNegativeZero.js | 6 + node_modules/math-intrinsics/max.d.ts | 1 + node_modules/math-intrinsics/max.js | 4 + node_modules/math-intrinsics/min.d.ts | 1 + node_modules/math-intrinsics/min.js | 4 + node_modules/math-intrinsics/mod.d.ts | 3 + node_modules/math-intrinsics/mod.js | 9 + node_modules/math-intrinsics/package.json | 86 + node_modules/math-intrinsics/pow.d.ts | 1 + node_modules/math-intrinsics/pow.js | 4 + node_modules/math-intrinsics/round.d.ts | 1 + node_modules/math-intrinsics/round.js | 4 + node_modules/math-intrinsics/sign.d.ts | 3 + node_modules/math-intrinsics/sign.js | 11 + node_modules/math-intrinsics/test/index.js | 192 + node_modules/math-intrinsics/tsconfig.json | 3 + node_modules/mime-db/HISTORY.md | 507 + node_modules/mime-db/LICENSE | 23 + node_modules/mime-db/README.md | 100 + node_modules/mime-db/db.json | 8519 +++++++ node_modules/mime-db/index.js | 12 + node_modules/mime-db/package.json | 60 + node_modules/mime-types/HISTORY.md | 397 + node_modules/mime-types/LICENSE | 23 + node_modules/mime-types/README.md | 113 + node_modules/mime-types/index.js | 188 + node_modules/mime-types/package.json | 44 + node_modules/mime/CHANGELOG.md | 312 + node_modules/mime/LICENSE | 21 + node_modules/mime/Mime.js | 97 + node_modules/mime/README.md | 178 + node_modules/mime/cli.js | 46 + node_modules/mime/index.js | 4 + node_modules/mime/lite.js | 4 + node_modules/mime/package.json | 52 + node_modules/mime/types/other.js | 1 + node_modules/mime/types/standard.js | 1 + node_modules/ms/index.js | 162 + node_modules/ms/license.md | 21 + node_modules/ms/package.json | 38 + node_modules/ms/readme.md | 59 + node_modules/node-fetch/LICENSE.md | 22 + node_modules/node-fetch/README.md | 634 + node_modules/node-fetch/browser.js | 25 + node_modules/node-fetch/lib/index.es.js | 1777 ++ node_modules/node-fetch/lib/index.js | 1787 ++ node_modules/node-fetch/lib/index.mjs | 1775 ++ node_modules/node-fetch/package.json | 89 + node_modules/node-forge/LICENSE | 331 + node_modules/node-forge/README.md | 2071 ++ node_modules/node-forge/dist/forge.all.min.js | 2 + .../node-forge/dist/forge.all.min.js.map | 1 + node_modules/node-forge/dist/forge.min.js | 2 + node_modules/node-forge/dist/forge.min.js.map | 1 + .../node-forge/dist/prime.worker.min.js | 2 + .../node-forge/dist/prime.worker.min.js.map | 1 + .../node-forge/flash/swf/SocketPool.swf | Bin 0 -> 21162 bytes node_modules/node-forge/lib/aes.js | 1091 + .../node-forge/lib/aesCipherSuites.js | 282 + node_modules/node-forge/lib/asn1-validator.js | 91 + node_modules/node-forge/lib/asn1.js | 1503 ++ node_modules/node-forge/lib/baseN.js | 186 + node_modules/node-forge/lib/cipher.js | 230 + node_modules/node-forge/lib/cipherModes.js | 999 + node_modules/node-forge/lib/des.js | 496 + node_modules/node-forge/lib/ed25519.js | 1072 + node_modules/node-forge/lib/forge.js | 13 + node_modules/node-forge/lib/form.js | 149 + node_modules/node-forge/lib/hmac.js | 146 + node_modules/node-forge/lib/http.js | 1346 ++ node_modules/node-forge/lib/index.all.js | 16 + node_modules/node-forge/lib/index.js | 33 + node_modules/node-forge/lib/jsbn.js | 1264 + node_modules/node-forge/lib/kem.js | 168 + node_modules/node-forge/lib/log.js | 319 + node_modules/node-forge/lib/md.all.js | 13 + node_modules/node-forge/lib/md.js | 11 + node_modules/node-forge/lib/md5.js | 289 + node_modules/node-forge/lib/mgf.js | 12 + node_modules/node-forge/lib/mgf1.js | 57 + node_modules/node-forge/lib/oids.js | 179 + node_modules/node-forge/lib/pbe.js | 1023 + node_modules/node-forge/lib/pbkdf2.js | 211 + node_modules/node-forge/lib/pem.js | 237 + node_modules/node-forge/lib/pkcs1.js | 276 + node_modules/node-forge/lib/pkcs12.js | 1078 + node_modules/node-forge/lib/pkcs7.js | 1260 + node_modules/node-forge/lib/pkcs7asn1.js | 410 + node_modules/node-forge/lib/pki.js | 102 + node_modules/node-forge/lib/prime.js | 297 + node_modules/node-forge/lib/prime.worker.js | 168 + node_modules/node-forge/lib/prng.js | 419 + node_modules/node-forge/lib/pss.js | 241 + node_modules/node-forge/lib/random.js | 191 + node_modules/node-forge/lib/rc2.js | 410 + node_modules/node-forge/lib/rsa.js | 1949 ++ node_modules/node-forge/lib/sha1.js | 319 + node_modules/node-forge/lib/sha256.js | 327 + node_modules/node-forge/lib/sha512.js | 561 + node_modules/node-forge/lib/socket.js | 287 + node_modules/node-forge/lib/ssh.js | 236 + node_modules/node-forge/lib/tls.js | 4282 ++++ node_modules/node-forge/lib/tlssocket.js | 249 + node_modules/node-forge/lib/util.js | 2652 +++ node_modules/node-forge/lib/x509.js | 3242 +++ node_modules/node-forge/lib/xhr.js | 738 + node_modules/node-forge/package.json | 123 + node_modules/object-hash/LICENSE | 22 + node_modules/object-hash/dist/object_hash.js | 1 + node_modules/object-hash/index.js | 453 + node_modules/object-hash/package.json | 53 + node_modules/object-hash/readme.markdown | 198 + node_modules/once/LICENSE | 15 + node_modules/once/README.md | 79 + node_modules/once/once.js | 42 + node_modules/once/package.json | 33 + node_modules/p-limit/index.d.ts | 42 + node_modules/p-limit/index.js | 71 + node_modules/p-limit/license | 9 + node_modules/p-limit/package.json | 52 + node_modules/p-limit/readme.md | 101 + .../proto3-json-serializer/CHANGELOG.md | 152 + node_modules/proto3-json-serializer/LICENSE | 202 + node_modules/proto3-json-serializer/README.md | 97 + .../proto3-json-serializer/build/src/any.d.ts | 16 + .../proto3-json-serializer/build/src/any.js | 95 + .../build/src/any.js.map | 1 + .../build/src/bytes.d.ts | 3 + .../proto3-json-serializer/build/src/bytes.js | 30 + .../build/src/bytes.js.map | 1 + .../build/src/duration.d.ts | 10 + .../build/src/duration.js | 55 + .../build/src/duration.js.map | 1 + .../build/src/enum.d.ts | 4 + .../proto3-json-serializer/build/src/enum.js | 52 + .../build/src/enum.js.map | 1 + .../build/src/fieldmask.d.ts | 8 + .../build/src/fieldmask.js | 27 + .../build/src/fieldmask.js.map | 1 + .../build/src/fromproto3json.d.ts | 4 + .../build/src/fromproto3json.js | 163 + .../build/src/fromproto3json.js.map | 1 + .../build/src/index.d.ts | 3 + .../proto3-json-serializer/build/src/index.js | 21 + .../build/src/index.js.map | 1 + .../build/src/timestamp.d.ts | 10 + .../build/src/timestamp.js | 57 + .../build/src/timestamp.js.map | 1 + .../build/src/toproto3json.d.ts | 6 + .../build/src/toproto3json.js | 143 + .../build/src/toproto3json.js.map | 1 + .../build/src/types.d.ts | 13 + .../proto3-json-serializer/build/src/types.js | 16 + .../build/src/types.js.map | 1 + .../build/src/util.d.ts | 3 + .../proto3-json-serializer/build/src/util.js | 44 + .../build/src/util.js.map | 1 + .../build/src/value.d.ts | 23 + .../proto3-json-serializer/build/src/value.js | 104 + .../build/src/value.js.map | 1 + .../build/src/wrappers.d.ts | 21 + .../build/src/wrappers.js | 56 + .../build/src/wrappers.js.map | 1 + .../proto3-json-serializer/package.json | 59 + node_modules/protobufjs/LICENSE | 39 + node_modules/protobufjs/README.md | 727 + .../protobufjs/dist/light/protobuf.js | 7833 ++++++ .../protobufjs/dist/light/protobuf.js.map | 1 + .../protobufjs/dist/light/protobuf.min.js | 8 + .../protobufjs/dist/light/protobuf.min.js.map | 1 + .../protobufjs/dist/minimal/protobuf.js | 2736 +++ .../protobufjs/dist/minimal/protobuf.js.map | 1 + .../protobufjs/dist/minimal/protobuf.min.js | 8 + .../dist/minimal/protobuf.min.js.map | 1 + node_modules/protobufjs/dist/protobuf.js | 9637 ++++++++ node_modules/protobufjs/dist/protobuf.js.map | 1 + node_modules/protobufjs/dist/protobuf.min.js | 8 + .../protobufjs/dist/protobuf.min.js.map | 1 + node_modules/protobufjs/ext/debug/README.md | 4 + node_modules/protobufjs/ext/debug/index.js | 71 + .../protobufjs/ext/descriptor/README.md | 72 + .../protobufjs/ext/descriptor/index.d.ts | 191 + .../protobufjs/ext/descriptor/index.js | 1162 + .../protobufjs/ext/descriptor/test.js | 54 + node_modules/protobufjs/google/LICENSE | 27 + node_modules/protobufjs/google/README.md | 1 + .../protobufjs/google/api/annotations.json | 83 + .../protobufjs/google/api/annotations.proto | 11 + node_modules/protobufjs/google/api/http.json | 86 + node_modules/protobufjs/google/api/http.proto | 31 + .../protobufjs/google/protobuf/api.json | 118 + .../protobufjs/google/protobuf/api.proto | 34 + .../google/protobuf/descriptor.json | 1382 ++ .../google/protobuf/descriptor.proto | 535 + .../google/protobuf/source_context.json | 20 + .../google/protobuf/source_context.proto | 7 + .../protobufjs/google/protobuf/type.json | 202 + .../protobufjs/google/protobuf/type.proto | 89 + node_modules/protobufjs/index.d.ts | 2799 +++ node_modules/protobufjs/index.js | 4 + node_modules/protobufjs/light.d.ts | 2 + node_modules/protobufjs/light.js | 4 + node_modules/protobufjs/minimal.d.ts | 2 + node_modules/protobufjs/minimal.js | 4 + node_modules/protobufjs/package.json | 114 + .../protobufjs/scripts/postinstall.js | 32 + node_modules/protobufjs/src/common.js | 399 + node_modules/protobufjs/src/converter.js | 301 + node_modules/protobufjs/src/decoder.js | 127 + node_modules/protobufjs/src/encoder.js | 100 + node_modules/protobufjs/src/enum.js | 223 + node_modules/protobufjs/src/field.js | 453 + node_modules/protobufjs/src/index-light.js | 104 + node_modules/protobufjs/src/index-minimal.js | 36 + node_modules/protobufjs/src/index.js | 12 + node_modules/protobufjs/src/mapfield.js | 126 + node_modules/protobufjs/src/message.js | 139 + node_modules/protobufjs/src/method.js | 160 + node_modules/protobufjs/src/namespace.js | 546 + node_modules/protobufjs/src/object.js | 378 + node_modules/protobufjs/src/oneof.js | 222 + node_modules/protobufjs/src/parse.js | 969 + node_modules/protobufjs/src/reader.js | 416 + node_modules/protobufjs/src/reader_buffer.js | 51 + node_modules/protobufjs/src/root.js | 404 + node_modules/protobufjs/src/roots.js | 18 + node_modules/protobufjs/src/rpc.js | 36 + node_modules/protobufjs/src/rpc/service.js | 142 + node_modules/protobufjs/src/service.js | 189 + node_modules/protobufjs/src/tokenize.js | 416 + node_modules/protobufjs/src/type.js | 614 + node_modules/protobufjs/src/types.js | 196 + node_modules/protobufjs/src/typescript.jsdoc | 15 + node_modules/protobufjs/src/util.js | 215 + node_modules/protobufjs/src/util/longbits.js | 200 + node_modules/protobufjs/src/util/minimal.js | 438 + node_modules/protobufjs/src/verifier.js | 177 + node_modules/protobufjs/src/wrappers.js | 102 + node_modules/protobufjs/src/writer.js | 465 + node_modules/protobufjs/src/writer_buffer.js | 85 + node_modules/protobufjs/tsconfig.json | 8 + node_modules/readable-stream/CONTRIBUTING.md | 38 + node_modules/readable-stream/GOVERNANCE.md | 136 + node_modules/readable-stream/LICENSE | 47 + node_modules/readable-stream/README.md | 106 + .../readable-stream/errors-browser.js | 127 + node_modules/readable-stream/errors.js | 116 + .../readable-stream/experimentalWarning.js | 17 + .../readable-stream/lib/_stream_duplex.js | 126 + .../lib/_stream_passthrough.js | 37 + .../readable-stream/lib/_stream_readable.js | 1027 + .../readable-stream/lib/_stream_transform.js | 190 + .../readable-stream/lib/_stream_writable.js | 641 + .../lib/internal/streams/async_iterator.js | 180 + .../lib/internal/streams/buffer_list.js | 183 + .../lib/internal/streams/destroy.js | 96 + .../lib/internal/streams/end-of-stream.js | 86 + .../lib/internal/streams/from-browser.js | 3 + .../lib/internal/streams/from.js | 52 + .../lib/internal/streams/pipeline.js | 86 + .../lib/internal/streams/state.js | 22 + .../lib/internal/streams/stream-browser.js | 1 + .../lib/internal/streams/stream.js | 1 + node_modules/readable-stream/package.json | 68 + .../readable-stream/readable-browser.js | 9 + node_modules/readable-stream/readable.js | 16 + node_modules/require-directory/.jshintrc | 67 + node_modules/require-directory/.npmignore | 1 + node_modules/require-directory/.travis.yml | 3 + node_modules/require-directory/LICENSE | 22 + .../require-directory/README.markdown | 184 + node_modules/require-directory/index.js | 86 + node_modules/require-directory/package.json | 40 + node_modules/retry-request/CHANGELOG.md | 91 + node_modules/retry-request/index.d.ts | 42 + node_modules/retry-request/index.js | 293 + node_modules/retry-request/license | 20 + node_modules/retry-request/package.json | 48 + node_modules/retry-request/readme.md | 199 + node_modules/retry/License | 21 + node_modules/retry/README.md | 227 + node_modules/retry/example/dns.js | 31 + node_modules/retry/example/stop.js | 40 + node_modules/retry/index.js | 1 + node_modules/retry/lib/retry.js | 100 + node_modules/retry/lib/retry_operation.js | 162 + node_modules/retry/package.json | 36 + node_modules/safe-buffer/LICENSE | 21 + node_modules/safe-buffer/README.md | 584 + node_modules/safe-buffer/index.d.ts | 187 + node_modules/safe-buffer/index.js | 65 + node_modules/safe-buffer/package.json | 51 + node_modules/semver/LICENSE | 15 + node_modules/semver/README.md | 664 + node_modules/semver/bin/semver.js | 191 + node_modules/semver/classes/comparator.js | 143 + node_modules/semver/classes/index.js | 7 + node_modules/semver/classes/range.js | 557 + node_modules/semver/classes/semver.js | 333 + node_modules/semver/functions/clean.js | 8 + node_modules/semver/functions/cmp.js | 54 + node_modules/semver/functions/coerce.js | 62 + .../semver/functions/compare-build.js | 9 + .../semver/functions/compare-loose.js | 5 + node_modules/semver/functions/compare.js | 7 + node_modules/semver/functions/diff.js | 60 + node_modules/semver/functions/eq.js | 5 + node_modules/semver/functions/gt.js | 5 + node_modules/semver/functions/gte.js | 5 + node_modules/semver/functions/inc.js | 21 + node_modules/semver/functions/lt.js | 5 + node_modules/semver/functions/lte.js | 5 + node_modules/semver/functions/major.js | 5 + node_modules/semver/functions/minor.js | 5 + node_modules/semver/functions/neq.js | 5 + node_modules/semver/functions/parse.js | 18 + node_modules/semver/functions/patch.js | 5 + node_modules/semver/functions/prerelease.js | 8 + node_modules/semver/functions/rcompare.js | 5 + node_modules/semver/functions/rsort.js | 5 + node_modules/semver/functions/satisfies.js | 12 + node_modules/semver/functions/sort.js | 5 + node_modules/semver/functions/valid.js | 8 + node_modules/semver/index.js | 91 + node_modules/semver/internal/constants.js | 37 + node_modules/semver/internal/debug.js | 11 + node_modules/semver/internal/identifiers.js | 29 + node_modules/semver/internal/lrucache.js | 42 + node_modules/semver/internal/parse-options.js | 17 + node_modules/semver/internal/re.js | 223 + node_modules/semver/package.json | 78 + node_modules/semver/preload.js | 4 + node_modules/semver/range.bnf | 16 + node_modules/semver/ranges/gtr.js | 6 + node_modules/semver/ranges/intersects.js | 9 + node_modules/semver/ranges/ltr.js | 6 + node_modules/semver/ranges/max-satisfying.js | 27 + node_modules/semver/ranges/min-satisfying.js | 26 + node_modules/semver/ranges/min-version.js | 63 + node_modules/semver/ranges/outside.js | 82 + node_modules/semver/ranges/simplify.js | 49 + node_modules/semver/ranges/subset.js | 249 + node_modules/semver/ranges/to-comparators.js | 10 + node_modules/semver/ranges/valid.js | 13 + node_modules/stream-events/index.d.ts | 5 + node_modules/stream-events/index.js | 30 + node_modules/stream-events/package.json | 38 + node_modules/stream-events/readme.md | 64 + .../stream-shift/.github/workflows/test.yml | 23 + node_modules/stream-shift/LICENSE | 21 + node_modules/stream-shift/README.md | 25 + node_modules/stream-shift/index.js | 21 + node_modules/stream-shift/package.json | 25 + node_modules/stream-shift/test.js | 48 + node_modules/string-width/index.d.ts | 29 + node_modules/string-width/index.js | 47 + node_modules/string-width/license | 9 + node_modules/string-width/package.json | 56 + node_modules/string-width/readme.md | 50 + node_modules/string_decoder/LICENSE | 48 + node_modules/string_decoder/README.md | 47 + .../string_decoder/lib/string_decoder.js | 296 + node_modules/string_decoder/package.json | 34 + node_modules/strip-ansi/index.d.ts | 17 + node_modules/strip-ansi/index.js | 4 + node_modules/strip-ansi/license | 9 + node_modules/strip-ansi/package.json | 54 + node_modules/strip-ansi/readme.md | 46 + node_modules/strnum/.vscode/launch.json | 25 + node_modules/strnum/CHANGELOG.md | 22 + node_modules/strnum/LICENSE | 21 + node_modules/strnum/README.md | 97 + node_modules/strnum/package.json | 30 + node_modules/strnum/strnum.js | 111 + node_modules/strnum/strnum.test.js | 165 + node_modules/stubs/index.js | 35 + node_modules/stubs/package.json | 25 + node_modules/stubs/readme.md | 73 + node_modules/stubs/test.js | 172 + node_modules/teeny-request/CHANGELOG.md | 253 + node_modules/teeny-request/LICENSE | 202 + node_modules/teeny-request/README.md | 95 + .../build/src/TeenyStatistics.d.ts | 127 + .../build/src/TeenyStatistics.js | 156 + .../build/src/TeenyStatistics.js.map | 1 + .../teeny-request/build/src/agents.d.ts | 32 + .../teeny-request/build/src/agents.js | 89 + .../teeny-request/build/src/agents.js.map | 1 + .../teeny-request/build/src/index.d.ts | 76 + node_modules/teeny-request/build/src/index.js | 253 + .../teeny-request/build/src/index.js.map | 1 + .../teeny-request/node_modules/.bin/uuid | 16 + .../teeny-request/node_modules/.bin/uuid.cmd | 17 + .../teeny-request/node_modules/.bin/uuid.ps1 | 28 + .../node_modules/agent-base/README.md | 145 + .../agent-base/dist/src/index.d.ts | 78 + .../node_modules/agent-base/dist/src/index.js | 203 + .../agent-base/dist/src/index.js.map | 1 + .../agent-base/dist/src/promisify.d.ts | 4 + .../agent-base/dist/src/promisify.js | 18 + .../agent-base/dist/src/promisify.js.map | 1 + .../node_modules/agent-base/package.json | 64 + .../node_modules/agent-base/src/index.ts | 345 + .../node_modules/agent-base/src/promisify.ts | 33 + .../node_modules/https-proxy-agent/README.md | 137 + .../https-proxy-agent/dist/agent.d.ts | 30 + .../https-proxy-agent/dist/agent.js | 177 + .../https-proxy-agent/dist/agent.js.map | 1 + .../https-proxy-agent/dist/index.d.ts | 23 + .../https-proxy-agent/dist/index.js | 14 + .../https-proxy-agent/dist/index.js.map | 1 + .../dist/parse-proxy-response.d.ts | 7 + .../dist/parse-proxy-response.js | 66 + .../dist/parse-proxy-response.js.map | 1 + .../https-proxy-agent/package.json | 56 + .../node_modules/uuid/CHANGELOG.md | 274 + .../node_modules/uuid/CONTRIBUTING.md | 18 + .../node_modules/uuid/LICENSE.md | 9 + .../teeny-request/node_modules/uuid/README.md | 466 + .../node_modules/uuid/dist/bin/uuid | 2 + .../uuid/dist/commonjs-browser/index.js | 79 + .../uuid/dist/commonjs-browser/md5.js | 223 + .../uuid/dist/commonjs-browser/native.js | 11 + .../uuid/dist/commonjs-browser/nil.js | 8 + .../uuid/dist/commonjs-browser/parse.js | 45 + .../uuid/dist/commonjs-browser/regex.js | 8 + .../uuid/dist/commonjs-browser/rng.js | 25 + .../uuid/dist/commonjs-browser/sha1.js | 104 + .../uuid/dist/commonjs-browser/stringify.js | 44 + .../uuid/dist/commonjs-browser/v1.js | 107 + .../uuid/dist/commonjs-browser/v3.js | 16 + .../uuid/dist/commonjs-browser/v35.js | 80 + .../uuid/dist/commonjs-browser/v4.js | 43 + .../uuid/dist/commonjs-browser/v5.js | 16 + .../uuid/dist/commonjs-browser/validate.js | 17 + .../uuid/dist/commonjs-browser/version.js | 21 + .../uuid/dist/esm-browser/index.js | 9 + .../node_modules/uuid/dist/esm-browser/md5.js | 215 + .../uuid/dist/esm-browser/native.js | 4 + .../node_modules/uuid/dist/esm-browser/nil.js | 1 + .../uuid/dist/esm-browser/parse.js | 35 + .../uuid/dist/esm-browser/regex.js | 1 + .../node_modules/uuid/dist/esm-browser/rng.js | 18 + .../uuid/dist/esm-browser/sha1.js | 96 + .../uuid/dist/esm-browser/stringify.js | 33 + .../node_modules/uuid/dist/esm-browser/v1.js | 95 + .../node_modules/uuid/dist/esm-browser/v3.js | 4 + .../node_modules/uuid/dist/esm-browser/v35.js | 66 + .../node_modules/uuid/dist/esm-browser/v4.js | 29 + .../node_modules/uuid/dist/esm-browser/v5.js | 4 + .../uuid/dist/esm-browser/validate.js | 7 + .../uuid/dist/esm-browser/version.js | 11 + .../node_modules/uuid/dist/esm-node/index.js | 9 + .../node_modules/uuid/dist/esm-node/md5.js | 13 + .../node_modules/uuid/dist/esm-node/native.js | 4 + .../node_modules/uuid/dist/esm-node/nil.js | 1 + .../node_modules/uuid/dist/esm-node/parse.js | 35 + .../node_modules/uuid/dist/esm-node/regex.js | 1 + .../node_modules/uuid/dist/esm-node/rng.js | 12 + .../node_modules/uuid/dist/esm-node/sha1.js | 13 + .../uuid/dist/esm-node/stringify.js | 33 + .../node_modules/uuid/dist/esm-node/v1.js | 95 + .../node_modules/uuid/dist/esm-node/v3.js | 4 + .../node_modules/uuid/dist/esm-node/v35.js | 66 + .../node_modules/uuid/dist/esm-node/v4.js | 29 + .../node_modules/uuid/dist/esm-node/v5.js | 4 + .../uuid/dist/esm-node/validate.js | 7 + .../uuid/dist/esm-node/version.js | 11 + .../node_modules/uuid/dist/index.js | 79 + .../node_modules/uuid/dist/md5-browser.js | 223 + .../node_modules/uuid/dist/md5.js | 23 + .../node_modules/uuid/dist/native-browser.js | 11 + .../node_modules/uuid/dist/native.js | 15 + .../node_modules/uuid/dist/nil.js | 8 + .../node_modules/uuid/dist/parse.js | 45 + .../node_modules/uuid/dist/regex.js | 8 + .../node_modules/uuid/dist/rng-browser.js | 25 + .../node_modules/uuid/dist/rng.js | 24 + .../node_modules/uuid/dist/sha1-browser.js | 104 + .../node_modules/uuid/dist/sha1.js | 23 + .../node_modules/uuid/dist/stringify.js | 44 + .../node_modules/uuid/dist/uuid-bin.js | 85 + .../node_modules/uuid/dist/v1.js | 107 + .../node_modules/uuid/dist/v3.js | 16 + .../node_modules/uuid/dist/v35.js | 80 + .../node_modules/uuid/dist/v4.js | 43 + .../node_modules/uuid/dist/v5.js | 16 + .../node_modules/uuid/dist/validate.js | 17 + .../node_modules/uuid/dist/version.js | 21 + .../node_modules/uuid/package.json | 135 + .../node_modules/uuid/wrapper.mjs | 10 + node_modules/teeny-request/package.json | 68 + node_modules/tr46/.npmignore | 4 + node_modules/tr46/index.js | 193 + node_modules/tr46/lib/.gitkeep | 0 node_modules/tr46/lib/mappingTable.json | 1 + node_modules/tr46/package.json | 31 + node_modules/tslib/CopyrightNotice.txt | 15 + node_modules/tslib/LICENSE.txt | 12 + node_modules/tslib/README.md | 164 + node_modules/tslib/SECURITY.md | 41 + node_modules/tslib/modules/index.d.ts | 38 + node_modules/tslib/modules/index.js | 70 + node_modules/tslib/modules/package.json | 3 + node_modules/tslib/package.json | 47 + node_modules/tslib/tslib.d.ts | 460 + node_modules/tslib/tslib.es6.html | 1 + node_modules/tslib/tslib.es6.js | 402 + node_modules/tslib/tslib.es6.mjs | 401 + node_modules/tslib/tslib.html | 1 + node_modules/tslib/tslib.js | 484 + node_modules/undici-types/LICENSE | 21 + node_modules/undici-types/README.md | 6 + node_modules/undici-types/agent.d.ts | 31 + node_modules/undici-types/api.d.ts | 43 + node_modules/undici-types/balanced-pool.d.ts | 29 + node_modules/undici-types/cache.d.ts | 36 + node_modules/undici-types/client.d.ts | 108 + node_modules/undici-types/connector.d.ts | 34 + node_modules/undici-types/content-type.d.ts | 21 + node_modules/undici-types/cookies.d.ts | 28 + .../undici-types/diagnostics-channel.d.ts | 66 + node_modules/undici-types/dispatcher.d.ts | 256 + .../undici-types/env-http-proxy-agent.d.ts | 21 + node_modules/undici-types/errors.d.ts | 149 + node_modules/undici-types/eventsource.d.ts | 61 + node_modules/undici-types/fetch.d.ts | 209 + node_modules/undici-types/file.d.ts | 39 + node_modules/undici-types/filereader.d.ts | 54 + node_modules/undici-types/formdata.d.ts | 108 + .../undici-types/global-dispatcher.d.ts | 9 + node_modules/undici-types/global-origin.d.ts | 7 + node_modules/undici-types/handlers.d.ts | 15 + node_modules/undici-types/header.d.ts | 4 + node_modules/undici-types/index.d.ts | 71 + node_modules/undici-types/interceptors.d.ts | 17 + node_modules/undici-types/mock-agent.d.ts | 50 + node_modules/undici-types/mock-client.d.ts | 25 + node_modules/undici-types/mock-errors.d.ts | 12 + .../undici-types/mock-interceptor.d.ts | 93 + node_modules/undici-types/mock-pool.d.ts | 25 + node_modules/undici-types/package.json | 55 + node_modules/undici-types/patch.d.ts | 33 + node_modules/undici-types/pool-stats.d.ts | 19 + node_modules/undici-types/pool.d.ts | 39 + node_modules/undici-types/proxy-agent.d.ts | 28 + node_modules/undici-types/readable.d.ts | 65 + node_modules/undici-types/retry-agent.d.ts | 8 + node_modules/undici-types/retry-handler.d.ts | 116 + node_modules/undici-types/util.d.ts | 18 + node_modules/undici-types/webidl.d.ts | 228 + node_modules/undici-types/websocket.d.ts | 150 + node_modules/util-deprecate/History.md | 16 + node_modules/util-deprecate/LICENSE | 24 + node_modules/util-deprecate/README.md | 53 + node_modules/util-deprecate/browser.js | 67 + node_modules/util-deprecate/node.js | 6 + node_modules/util-deprecate/package.json | 27 + node_modules/uuid/LICENSE.md | 9 + node_modules/uuid/README.md | 510 + node_modules/uuid/dist/cjs-browser/index.d.ts | 15 + node_modules/uuid/dist/cjs-browser/index.js | 31 + node_modules/uuid/dist/cjs-browser/max.d.ts | 2 + node_modules/uuid/dist/cjs-browser/max.js | 3 + node_modules/uuid/dist/cjs-browser/md5.d.ts | 2 + node_modules/uuid/dist/cjs-browser/md5.js | 137 + .../uuid/dist/cjs-browser/native.d.ts | 4 + node_modules/uuid/dist/cjs-browser/native.js | 4 + node_modules/uuid/dist/cjs-browser/nil.d.ts | 2 + node_modules/uuid/dist/cjs-browser/nil.js | 3 + .../uuid/dist/cjs-browser/package.json | 1 + node_modules/uuid/dist/cjs-browser/parse.d.ts | 2 + node_modules/uuid/dist/cjs-browser/parse.js | 11 + node_modules/uuid/dist/cjs-browser/regex.d.ts | 2 + node_modules/uuid/dist/cjs-browser/regex.js | 3 + node_modules/uuid/dist/cjs-browser/rng.d.ts | 1 + node_modules/uuid/dist/cjs-browser/rng.js | 14 + node_modules/uuid/dist/cjs-browser/sha1.d.ts | 2 + node_modules/uuid/dist/cjs-browser/sha1.js | 72 + .../uuid/dist/cjs-browser/stringify.d.ts | 3 + .../uuid/dist/cjs-browser/stringify.js | 39 + node_modules/uuid/dist/cjs-browser/types.d.ts | 21 + node_modules/uuid/dist/cjs-browser/types.js | 2 + .../uuid/dist/cjs-browser/uuid-bin.d.ts | 1 + .../uuid/dist/cjs-browser/uuid-bin.js | 72 + node_modules/uuid/dist/cjs-browser/v1.d.ts | 11 + node_modules/uuid/dist/cjs-browser/v1.js | 87 + .../uuid/dist/cjs-browser/v1ToV6.d.ts | 2 + node_modules/uuid/dist/cjs-browser/v1ToV6.js | 13 + node_modules/uuid/dist/cjs-browser/v3.d.ts | 9 + node_modules/uuid/dist/cjs-browser/v3.js | 14 + node_modules/uuid/dist/cjs-browser/v35.d.ts | 7 + node_modules/uuid/dist/cjs-browser/v35.js | 41 + node_modules/uuid/dist/cjs-browser/v4.d.ts | 4 + node_modules/uuid/dist/cjs-browser/v4.js | 29 + node_modules/uuid/dist/cjs-browser/v5.d.ts | 9 + node_modules/uuid/dist/cjs-browser/v5.js | 14 + node_modules/uuid/dist/cjs-browser/v6.d.ts | 4 + node_modules/uuid/dist/cjs-browser/v6.js | 19 + .../uuid/dist/cjs-browser/v6ToV1.d.ts | 2 + node_modules/uuid/dist/cjs-browser/v6ToV1.js | 13 + node_modules/uuid/dist/cjs-browser/v7.d.ts | 9 + node_modules/uuid/dist/cjs-browser/v7.js | 69 + .../uuid/dist/cjs-browser/validate.d.ts | 2 + .../uuid/dist/cjs-browser/validate.js | 7 + .../uuid/dist/cjs-browser/version.d.ts | 2 + node_modules/uuid/dist/cjs-browser/version.js | 10 + node_modules/uuid/dist/cjs/index.d.ts | 15 + node_modules/uuid/dist/cjs/index.js | 31 + node_modules/uuid/dist/cjs/max.d.ts | 2 + node_modules/uuid/dist/cjs/max.js | 3 + node_modules/uuid/dist/cjs/md5.d.ts | 4 + node_modules/uuid/dist/cjs/md5.js | 13 + node_modules/uuid/dist/cjs/native.d.ts | 6 + node_modules/uuid/dist/cjs/native.js | 4 + node_modules/uuid/dist/cjs/nil.d.ts | 2 + node_modules/uuid/dist/cjs/nil.js | 3 + node_modules/uuid/dist/cjs/package.json | 1 + node_modules/uuid/dist/cjs/parse.d.ts | 2 + node_modules/uuid/dist/cjs/parse.js | 11 + node_modules/uuid/dist/cjs/regex.d.ts | 2 + node_modules/uuid/dist/cjs/regex.js | 3 + node_modules/uuid/dist/cjs/rng.d.ts | 1 + node_modules/uuid/dist/cjs/rng.js | 13 + node_modules/uuid/dist/cjs/sha1.d.ts | 4 + node_modules/uuid/dist/cjs/sha1.js | 13 + node_modules/uuid/dist/cjs/stringify.d.ts | 3 + node_modules/uuid/dist/cjs/stringify.js | 39 + node_modules/uuid/dist/cjs/types.d.ts | 21 + node_modules/uuid/dist/cjs/types.js | 2 + node_modules/uuid/dist/cjs/uuid-bin.d.ts | 1 + node_modules/uuid/dist/cjs/uuid-bin.js | 72 + node_modules/uuid/dist/cjs/v1.d.ts | 11 + node_modules/uuid/dist/cjs/v1.js | 87 + node_modules/uuid/dist/cjs/v1ToV6.d.ts | 2 + node_modules/uuid/dist/cjs/v1ToV6.js | 13 + node_modules/uuid/dist/cjs/v3.d.ts | 9 + node_modules/uuid/dist/cjs/v3.js | 14 + node_modules/uuid/dist/cjs/v35.d.ts | 7 + node_modules/uuid/dist/cjs/v35.js | 41 + node_modules/uuid/dist/cjs/v4.d.ts | 4 + node_modules/uuid/dist/cjs/v4.js | 29 + node_modules/uuid/dist/cjs/v5.d.ts | 9 + node_modules/uuid/dist/cjs/v5.js | 14 + node_modules/uuid/dist/cjs/v6.d.ts | 4 + node_modules/uuid/dist/cjs/v6.js | 19 + node_modules/uuid/dist/cjs/v6ToV1.d.ts | 2 + node_modules/uuid/dist/cjs/v6ToV1.js | 13 + node_modules/uuid/dist/cjs/v7.d.ts | 9 + node_modules/uuid/dist/cjs/v7.js | 69 + node_modules/uuid/dist/cjs/validate.d.ts | 2 + node_modules/uuid/dist/cjs/validate.js | 7 + node_modules/uuid/dist/cjs/version.d.ts | 2 + node_modules/uuid/dist/cjs/version.js | 10 + node_modules/uuid/dist/esm-browser/index.d.ts | 15 + node_modules/uuid/dist/esm-browser/index.js | 14 + node_modules/uuid/dist/esm-browser/max.d.ts | 2 + node_modules/uuid/dist/esm-browser/max.js | 1 + node_modules/uuid/dist/esm-browser/md5.d.ts | 2 + node_modules/uuid/dist/esm-browser/md5.js | 135 + .../uuid/dist/esm-browser/native.d.ts | 4 + node_modules/uuid/dist/esm-browser/native.js | 2 + node_modules/uuid/dist/esm-browser/nil.d.ts | 2 + node_modules/uuid/dist/esm-browser/nil.js | 1 + node_modules/uuid/dist/esm-browser/parse.d.ts | 2 + node_modules/uuid/dist/esm-browser/parse.js | 9 + node_modules/uuid/dist/esm-browser/regex.d.ts | 2 + node_modules/uuid/dist/esm-browser/regex.js | 1 + node_modules/uuid/dist/esm-browser/rng.d.ts | 1 + node_modules/uuid/dist/esm-browser/rng.js | 11 + node_modules/uuid/dist/esm-browser/sha1.d.ts | 2 + node_modules/uuid/dist/esm-browser/sha1.js | 70 + .../uuid/dist/esm-browser/stringify.d.ts | 3 + .../uuid/dist/esm-browser/stringify.js | 35 + node_modules/uuid/dist/esm-browser/types.d.ts | 21 + node_modules/uuid/dist/esm-browser/types.js | 1 + .../uuid/dist/esm-browser/uuid-bin.d.ts | 1 + .../uuid/dist/esm-browser/uuid-bin.js | 70 + node_modules/uuid/dist/esm-browser/v1.d.ts | 11 + node_modules/uuid/dist/esm-browser/v1.js | 83 + .../uuid/dist/esm-browser/v1ToV6.d.ts | 2 + node_modules/uuid/dist/esm-browser/v1ToV6.js | 10 + node_modules/uuid/dist/esm-browser/v3.d.ts | 9 + node_modules/uuid/dist/esm-browser/v3.js | 9 + node_modules/uuid/dist/esm-browser/v35.d.ts | 7 + node_modules/uuid/dist/esm-browser/v35.js | 36 + node_modules/uuid/dist/esm-browser/v4.d.ts | 4 + node_modules/uuid/dist/esm-browser/v4.js | 27 + node_modules/uuid/dist/esm-browser/v5.d.ts | 9 + node_modules/uuid/dist/esm-browser/v5.js | 9 + node_modules/uuid/dist/esm-browser/v6.d.ts | 4 + node_modules/uuid/dist/esm-browser/v6.js | 17 + .../uuid/dist/esm-browser/v6ToV1.d.ts | 2 + node_modules/uuid/dist/esm-browser/v6ToV1.js | 10 + node_modules/uuid/dist/esm-browser/v7.d.ts | 9 + node_modules/uuid/dist/esm-browser/v7.js | 65 + .../uuid/dist/esm-browser/validate.d.ts | 2 + .../uuid/dist/esm-browser/validate.js | 5 + .../uuid/dist/esm-browser/version.d.ts | 2 + node_modules/uuid/dist/esm-browser/version.js | 8 + node_modules/uuid/dist/esm/bin/uuid | 2 + node_modules/uuid/dist/esm/index.d.ts | 15 + node_modules/uuid/dist/esm/index.js | 14 + node_modules/uuid/dist/esm/max.d.ts | 2 + node_modules/uuid/dist/esm/max.js | 1 + node_modules/uuid/dist/esm/md5.d.ts | 4 + node_modules/uuid/dist/esm/md5.js | 11 + node_modules/uuid/dist/esm/native.d.ts | 6 + node_modules/uuid/dist/esm/native.js | 2 + node_modules/uuid/dist/esm/nil.d.ts | 2 + node_modules/uuid/dist/esm/nil.js | 1 + node_modules/uuid/dist/esm/parse.d.ts | 2 + node_modules/uuid/dist/esm/parse.js | 9 + node_modules/uuid/dist/esm/regex.d.ts | 2 + node_modules/uuid/dist/esm/regex.js | 1 + node_modules/uuid/dist/esm/rng.d.ts | 1 + node_modules/uuid/dist/esm/rng.js | 10 + node_modules/uuid/dist/esm/sha1.d.ts | 4 + node_modules/uuid/dist/esm/sha1.js | 11 + node_modules/uuid/dist/esm/stringify.d.ts | 3 + node_modules/uuid/dist/esm/stringify.js | 35 + node_modules/uuid/dist/esm/types.d.ts | 21 + node_modules/uuid/dist/esm/types.js | 1 + node_modules/uuid/dist/esm/uuid-bin.d.ts | 1 + node_modules/uuid/dist/esm/uuid-bin.js | 70 + node_modules/uuid/dist/esm/v1.d.ts | 11 + node_modules/uuid/dist/esm/v1.js | 83 + node_modules/uuid/dist/esm/v1ToV6.d.ts | 2 + node_modules/uuid/dist/esm/v1ToV6.js | 10 + node_modules/uuid/dist/esm/v3.d.ts | 9 + node_modules/uuid/dist/esm/v3.js | 9 + node_modules/uuid/dist/esm/v35.d.ts | 7 + node_modules/uuid/dist/esm/v35.js | 36 + node_modules/uuid/dist/esm/v4.d.ts | 4 + node_modules/uuid/dist/esm/v4.js | 27 + node_modules/uuid/dist/esm/v5.d.ts | 9 + node_modules/uuid/dist/esm/v5.js | 9 + node_modules/uuid/dist/esm/v6.d.ts | 4 + node_modules/uuid/dist/esm/v6.js | 17 + node_modules/uuid/dist/esm/v6ToV1.d.ts | 2 + node_modules/uuid/dist/esm/v6ToV1.js | 10 + node_modules/uuid/dist/esm/v7.d.ts | 9 + node_modules/uuid/dist/esm/v7.js | 65 + node_modules/uuid/dist/esm/validate.d.ts | 2 + node_modules/uuid/dist/esm/validate.js | 5 + node_modules/uuid/dist/esm/version.d.ts | 2 + node_modules/uuid/dist/esm/version.js | 8 + node_modules/uuid/package.json | 132 + node_modules/webidl-conversions/LICENSE.md | 12 + node_modules/webidl-conversions/README.md | 53 + node_modules/webidl-conversions/lib/index.js | 189 + node_modules/webidl-conversions/package.json | 23 + node_modules/websocket-driver/CHANGELOG.md | 142 + node_modules/websocket-driver/LICENSE.md | 12 + node_modules/websocket-driver/README.md | 370 + .../websocket-driver/lib/websocket/driver.js | 43 + .../lib/websocket/driver/base.js | 193 + .../lib/websocket/driver/client.js | 142 + .../lib/websocket/driver/draft75.js | 123 + .../lib/websocket/driver/draft76.js | 117 + .../lib/websocket/driver/headers.js | 35 + .../lib/websocket/driver/hybi.js | 483 + .../lib/websocket/driver/hybi/frame.js | 21 + .../lib/websocket/driver/hybi/message.js | 34 + .../lib/websocket/driver/proxy.js | 99 + .../lib/websocket/driver/server.js | 112 + .../lib/websocket/driver/stream_reader.js | 69 + .../lib/websocket/http_parser.js | 135 + .../websocket-driver/lib/websocket/streams.js | 146 + node_modules/websocket-driver/package.json | 35 + .../websocket-extensions/CHANGELOG.md | 28 + node_modules/websocket-extensions/LICENSE.md | 12 + node_modules/websocket-extensions/README.md | 331 + .../websocket-extensions/lib/parser.js | 103 + .../lib/pipeline/README.md | 607 + .../websocket-extensions/lib/pipeline/cell.js | 53 + .../lib/pipeline/functor.js | 72 + .../lib/pipeline/index.js | 47 + .../lib/pipeline/pledge.js | 37 + .../lib/pipeline/ring_buffer.js | 66 + .../lib/websocket_extensions.js | 162 + .../websocket-extensions/package.json | 29 + node_modules/whatwg-url/LICENSE.txt | 21 + node_modules/whatwg-url/README.md | 67 + node_modules/whatwg-url/lib/URL-impl.js | 200 + node_modules/whatwg-url/lib/URL.js | 196 + node_modules/whatwg-url/lib/public-api.js | 11 + .../whatwg-url/lib/url-state-machine.js | 1297 + node_modules/whatwg-url/lib/utils.js | 20 + node_modules/whatwg-url/package.json | 32 + node_modules/wrap-ansi/index.js | 216 + node_modules/wrap-ansi/license | 9 + node_modules/wrap-ansi/package.json | 62 + node_modules/wrap-ansi/readme.md | 91 + node_modules/wrappy/LICENSE | 15 + node_modules/wrappy/README.md | 36 + node_modules/wrappy/package.json | 29 + node_modules/wrappy/wrappy.js | 33 + node_modules/y18n/CHANGELOG.md | 100 + node_modules/y18n/LICENSE | 13 + node_modules/y18n/README.md | 127 + node_modules/y18n/build/index.cjs | 203 + node_modules/y18n/build/lib/cjs.js | 6 + node_modules/y18n/build/lib/index.js | 174 + .../y18n/build/lib/platform-shims/node.js | 19 + node_modules/y18n/index.mjs | 8 + node_modules/y18n/package.json | 70 + node_modules/yallist/LICENSE | 15 + node_modules/yallist/README.md | 204 + node_modules/yallist/iterator.js | 8 + node_modules/yallist/package.json | 29 + node_modules/yallist/yallist.js | 426 + node_modules/yargs-parser/CHANGELOG.md | 308 + node_modules/yargs-parser/LICENSE.txt | 14 + node_modules/yargs-parser/README.md | 518 + node_modules/yargs-parser/browser.js | 29 + node_modules/yargs-parser/build/index.cjs | 1050 + node_modules/yargs-parser/build/lib/index.js | 62 + .../yargs-parser/build/lib/string-utils.js | 65 + .../build/lib/tokenize-arg-string.js | 40 + .../build/lib/yargs-parser-types.js | 12 + .../yargs-parser/build/lib/yargs-parser.js | 1045 + node_modules/yargs-parser/package.json | 92 + node_modules/yargs/LICENSE | 21 + node_modules/yargs/README.md | 204 + node_modules/yargs/browser.d.ts | 5 + node_modules/yargs/browser.mjs | 7 + node_modules/yargs/build/index.cjs | 1 + node_modules/yargs/build/lib/argsert.js | 62 + node_modules/yargs/build/lib/command.js | 449 + .../yargs/build/lib/completion-templates.js | 48 + node_modules/yargs/build/lib/completion.js | 243 + node_modules/yargs/build/lib/middleware.js | 88 + node_modules/yargs/build/lib/parse-command.js | 32 + .../yargs/build/lib/typings/common-types.js | 9 + .../build/lib/typings/yargs-parser-types.js | 1 + node_modules/yargs/build/lib/usage.js | 584 + .../yargs/build/lib/utils/apply-extends.js | 59 + .../yargs/build/lib/utils/is-promise.js | 5 + .../yargs/build/lib/utils/levenshtein.js | 34 + .../build/lib/utils/maybe-async-result.js | 17 + .../yargs/build/lib/utils/obj-filter.js | 10 + .../yargs/build/lib/utils/process-argv.js | 17 + .../yargs/build/lib/utils/set-blocking.js | 12 + .../yargs/build/lib/utils/which-module.js | 10 + node_modules/yargs/build/lib/validation.js | 305 + node_modules/yargs/build/lib/yargs-factory.js | 1512 ++ node_modules/yargs/build/lib/yerror.js | 9 + node_modules/yargs/helpers/helpers.mjs | 10 + node_modules/yargs/helpers/index.js | 14 + node_modules/yargs/helpers/package.json | 3 + node_modules/yargs/index.cjs | 53 + node_modules/yargs/index.mjs | 8 + .../yargs/lib/platform-shims/browser.mjs | 95 + node_modules/yargs/lib/platform-shims/esm.mjs | 73 + node_modules/yargs/locales/be.json | 46 + node_modules/yargs/locales/cs.json | 51 + node_modules/yargs/locales/de.json | 46 + node_modules/yargs/locales/en.json | 55 + node_modules/yargs/locales/es.json | 46 + node_modules/yargs/locales/fi.json | 49 + node_modules/yargs/locales/fr.json | 53 + node_modules/yargs/locales/hi.json | 49 + node_modules/yargs/locales/hu.json | 46 + node_modules/yargs/locales/id.json | 50 + node_modules/yargs/locales/it.json | 46 + node_modules/yargs/locales/ja.json | 51 + node_modules/yargs/locales/ko.json | 49 + node_modules/yargs/locales/nb.json | 44 + node_modules/yargs/locales/nl.json | 49 + node_modules/yargs/locales/nn.json | 44 + node_modules/yargs/locales/pirate.json | 13 + node_modules/yargs/locales/pl.json | 49 + node_modules/yargs/locales/pt.json | 45 + node_modules/yargs/locales/pt_BR.json | 48 + node_modules/yargs/locales/ru.json | 51 + node_modules/yargs/locales/th.json | 46 + node_modules/yargs/locales/tr.json | 48 + node_modules/yargs/locales/uk_UA.json | 51 + node_modules/yargs/locales/uz.json | 52 + node_modules/yargs/locales/zh_CN.json | 48 + node_modules/yargs/locales/zh_TW.json | 51 + node_modules/yargs/package.json | 123 + node_modules/yargs/yargs | 9 + node_modules/yargs/yargs.mjs | 10 + node_modules/yocto-queue/index.d.ts | 56 + node_modules/yocto-queue/index.js | 68 + node_modules/yocto-queue/license | 9 + node_modules/yocto-queue/package.json | 43 + node_modules/yocto-queue/readme.md | 64 + package-lock.json | 1969 ++ package.json | 5 + 5188 files changed, 769897 insertions(+), 294 deletions(-) create mode 100644 .idea/.gitignore create mode 100644 .idea/Psychology-Apps-main.iml create mode 100644 .idea/caches/deviceStreaming.xml create mode 100644 .idea/copilot.data.migration.agent.xml create mode 100644 .idea/copilot.data.migration.ask.xml create mode 100644 .idea/copilot.data.migration.ask2agent.xml create mode 100644 .idea/copilot.data.migration.edit.xml create mode 100644 .idea/deviceManager.xml create mode 100644 .idea/libraries/Dart_Packages.xml create mode 100644 .idea/libraries/Dart_SDK.xml create mode 100644 .idea/markdown.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 backend/.env.example create mode 100644 backend/src/Journal.js create mode 100644 backend/src/api/journal.js create mode 100644 backend/src/config/firebase.js create mode 100644 flutter_app/assets/design/Chat-History Page.png create mode 100644 flutter_app/assets/design/Current-_chat_history.png create mode 100644 flutter_app/assets/design/Current-_homepage.png create mode 100644 flutter_app/assets/design/Current-_journal-page.png create mode 100644 flutter_app/assets/design/Homepage-if-lastest-journal-and-chat-has-created_example.png create mode 100644 flutter_app/assets/design/Homepage.png create mode 100644 flutter_app/assets/design/Journal Page.png create mode 100644 flutter_app/assets/design/Settings and Profile Page.png create mode 100644 flutter_app/assets/design/WritingJournal Page.png create mode 100644 flutter_app/assets/design/example-if-added-new-journal.png create mode 100644 flutter_app/assets/design/example-if-users-addedcreated-alotofjournals.png create mode 100644 flutter_app/assets/design/example-if-users-already-create-a-chat.png create mode 100644 flutter_app/assets/design/foto_profile_example.jpg create mode 100644 flutter_app/assets/images/Logo_Halodoc.png create mode 100644 flutter_app/assets/images/alodokter.png create mode 100644 flutter_app/assets/images/logo_Kalm.png create mode 100644 flutter_app/lib/chat_history.dart create mode 100644 flutter_app/lib/homepage.dart create mode 100644 flutter_app/lib/journal-page.dart create mode 100644 flutter_app/lib/journal_service.dart create mode 100644 flutter_app/lib/widgets/custom_navbar.dart create mode 100644 flutter_app/lib/writing_journal_page.dart create mode 100644 node_modules/.bin/fxparser create mode 100644 node_modules/.bin/fxparser.cmd create mode 100644 node_modules/.bin/fxparser.ps1 create mode 100644 node_modules/.bin/mime create mode 100644 node_modules/.bin/mime.cmd create mode 100644 node_modules/.bin/mime.ps1 create mode 100644 node_modules/.bin/proto-loader-gen-types create mode 100644 node_modules/.bin/proto-loader-gen-types.cmd create mode 100644 node_modules/.bin/proto-loader-gen-types.ps1 create mode 100644 node_modules/.bin/semver create mode 100644 node_modules/.bin/semver.cmd create mode 100644 node_modules/.bin/semver.ps1 create mode 100644 node_modules/.bin/uuid create mode 100644 node_modules/.bin/uuid.cmd create mode 100644 node_modules/.bin/uuid.ps1 create mode 100644 node_modules/.package-lock.json create mode 100644 node_modules/@fastify/busboy/LICENSE create mode 100644 node_modules/@fastify/busboy/README.md create mode 100644 node_modules/@fastify/busboy/deps/dicer/LICENSE create mode 100644 node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js create mode 100644 node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js create mode 100644 node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js create mode 100644 node_modules/@fastify/busboy/deps/dicer/lib/dicer.d.ts create mode 100644 node_modules/@fastify/busboy/deps/streamsearch/sbmh.js create mode 100644 node_modules/@fastify/busboy/lib/main.d.ts create mode 100644 node_modules/@fastify/busboy/lib/main.js create mode 100644 node_modules/@fastify/busboy/lib/types/multipart.js create mode 100644 node_modules/@fastify/busboy/lib/types/urlencoded.js create mode 100644 node_modules/@fastify/busboy/lib/utils/Decoder.js create mode 100644 node_modules/@fastify/busboy/lib/utils/basename.js create mode 100644 node_modules/@fastify/busboy/lib/utils/decodeText.js create mode 100644 node_modules/@fastify/busboy/lib/utils/getLimit.js create mode 100644 node_modules/@fastify/busboy/lib/utils/parseParams.js create mode 100644 node_modules/@fastify/busboy/package.json create mode 100644 node_modules/@firebase/app-check-interop-types/README.md create mode 100644 node_modules/@firebase/app-check-interop-types/index.d.ts create mode 100644 node_modules/@firebase/app-check-interop-types/package.json create mode 100644 node_modules/@firebase/app-types/README.md create mode 100644 node_modules/@firebase/app-types/index.d.ts create mode 100644 node_modules/@firebase/app-types/package.json create mode 100644 node_modules/@firebase/app-types/private.d.ts create mode 100644 node_modules/@firebase/auth-interop-types/README.md create mode 100644 node_modules/@firebase/auth-interop-types/index.d.ts create mode 100644 node_modules/@firebase/auth-interop-types/package.json create mode 100644 node_modules/@firebase/component/README.md create mode 100644 node_modules/@firebase/component/dist/esm/index.d.ts create mode 100644 node_modules/@firebase/component/dist/esm/index.esm.js create mode 100644 node_modules/@firebase/component/dist/esm/index.esm.js.map create mode 100644 node_modules/@firebase/component/dist/esm/package.json create mode 100644 node_modules/@firebase/component/dist/esm/src/component.d.ts create mode 100644 node_modules/@firebase/component/dist/esm/src/component_container.d.ts create mode 100644 node_modules/@firebase/component/dist/esm/src/constants.d.ts create mode 100644 node_modules/@firebase/component/dist/esm/src/provider.d.ts create mode 100644 node_modules/@firebase/component/dist/esm/src/types.d.ts create mode 100644 node_modules/@firebase/component/dist/esm/test/setup.d.ts create mode 100644 node_modules/@firebase/component/dist/esm/test/util.d.ts create mode 100644 node_modules/@firebase/component/dist/index.cjs.js create mode 100644 node_modules/@firebase/component/dist/index.cjs.js.map create mode 100644 node_modules/@firebase/component/dist/index.d.ts create mode 100644 node_modules/@firebase/component/dist/src/component.d.ts create mode 100644 node_modules/@firebase/component/dist/src/component_container.d.ts create mode 100644 node_modules/@firebase/component/dist/src/constants.d.ts create mode 100644 node_modules/@firebase/component/dist/src/provider.d.ts create mode 100644 node_modules/@firebase/component/dist/src/types.d.ts create mode 100644 node_modules/@firebase/component/dist/test/setup.d.ts create mode 100644 node_modules/@firebase/component/dist/test/util.d.ts create mode 100644 node_modules/@firebase/component/package.json create mode 100644 node_modules/@firebase/database-compat/README.md create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/src/api/Database.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/src/api/Reference.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/src/api/TransactionResult.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/src/api/internal.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/src/api/onDisconnect.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/src/index.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/src/index.node.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/src/index.standalone.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/src/util/util.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/src/util/validation.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/test/browser/crawler_support.test.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/test/database.test.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/test/datasnapshot.test.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/test/helpers/events.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/test/helpers/util.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/test/info.test.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/test/order.test.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/test/order_by.test.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/test/promise.test.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/test/query.test.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/test/servervalues.test.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/database-compat/test/transaction.test.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/index.esm.js create mode 100644 node_modules/@firebase/database-compat/dist/index.esm.js.map create mode 100644 node_modules/@firebase/database-compat/dist/index.js create mode 100644 node_modules/@firebase/database-compat/dist/index.js.map create mode 100644 node_modules/@firebase/database-compat/dist/index.standalone.js create mode 100644 node_modules/@firebase/database-compat/dist/index.standalone.js.map create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/api/Database.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/api/Reference.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/api/TransactionResult.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/api/internal.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/api/onDisconnect.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/index.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/index.node.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/index.standalone.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/util/util.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/util/validation.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/browser/crawler_support.test.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/database.test.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/datasnapshot.test.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/helpers/events.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/helpers/util.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/info.test.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/order.test.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/order_by.test.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/promise.test.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/query.test.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/servervalues.test.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/transaction.test.d.ts create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/index.js create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/index.js.map create mode 100644 node_modules/@firebase/database-compat/dist/node-esm/package.json create mode 100644 node_modules/@firebase/database-compat/package.json create mode 100644 node_modules/@firebase/database-compat/standalone/package.json create mode 100644 node_modules/@firebase/database-types/README.md create mode 100644 node_modules/@firebase/database-types/index.d.ts create mode 100644 node_modules/@firebase/database-types/package.json create mode 100644 node_modules/@firebase/database/README.md create mode 100644 node_modules/@firebase/database/dist/index.cjs.js create mode 100644 node_modules/@firebase/database/dist/index.cjs.js.map create mode 100644 node_modules/@firebase/database/dist/index.esm.js create mode 100644 node_modules/@firebase/database/dist/index.esm.js.map create mode 100644 node_modules/@firebase/database/dist/index.node.cjs.js create mode 100644 node_modules/@firebase/database/dist/index.node.cjs.js.map create mode 100644 node_modules/@firebase/database/dist/index.standalone.js create mode 100644 node_modules/@firebase/database/dist/index.standalone.js.map create mode 100644 node_modules/@firebase/database/dist/internal.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/index.node.esm.js create mode 100644 node_modules/@firebase/database/dist/node-esm/index.node.esm.js.map create mode 100644 node_modules/@firebase/database/dist/node-esm/package.json create mode 100644 node_modules/@firebase/database/dist/node-esm/src/api.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/api.standalone.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/api/Database.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/api/OnDisconnect.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/api/Reference.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/api/Reference_impl.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/api/ServerValue.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/api/Transaction.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/api/test_access.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/AppCheckTokenProvider.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/AuthTokenProvider.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/CompoundWrite.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/PersistentConnection.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/ReadonlyRestClient.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/Repo.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/RepoInfo.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/ServerActions.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/SnapshotHolder.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/SparseSnapshotTree.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/SyncPoint.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/SyncTree.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/WriteTree.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/operation/AckUserWrite.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/operation/ListenComplete.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/operation/Merge.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/operation/Operation.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/operation/Overwrite.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/snap/ChildrenNode.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/snap/IndexMap.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/snap/LeafNode.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/snap/Node.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/snap/childSet.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/snap/comparators.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/snap/indexes/Index.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/snap/indexes/KeyIndex.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/snap/indexes/PathIndex.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/snap/indexes/PriorityIndex.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/snap/indexes/ValueIndex.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/snap/nodeFromJSON.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/snap/snap.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/stats/StatsCollection.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/stats/StatsListener.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/stats/StatsManager.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/stats/StatsReporter.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/storage/DOMStorageWrapper.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/storage/MemoryStorage.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/storage/storage.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/util/EventEmitter.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/util/ImmutableTree.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/util/NextPushId.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/util/OnlineMonitor.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/util/Path.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/util/ServerValues.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/util/SortedMap.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/util/Tree.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/util/VisibilityMonitor.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/util/libs/parser.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/util/misc.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/util/util.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/util/validation.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/version.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/view/CacheNode.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/view/Change.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/view/ChildChangeAccumulator.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/view/CompleteChildSource.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/view/Event.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/view/EventGenerator.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/view/EventQueue.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/view/EventRegistration.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/view/QueryParams.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/view/View.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/view/ViewCache.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/view/ViewProcessor.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/view/filter/IndexedFilter.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/view/filter/LimitedFilter.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/view/filter/NodeFilter.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/core/view/filter/RangedFilter.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/index.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/index.node.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/index.standalone.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/internal/index.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/realtime/BrowserPollConnection.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/realtime/Connection.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/realtime/Constants.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/realtime/Transport.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/realtime/TransportManager.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/realtime/WebSocketConnection.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/realtime/polling/PacketReceiver.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/src/register.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/test/helpers/EventAccumulator.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/test/helpers/syncpoint-util.d.ts create mode 100644 node_modules/@firebase/database/dist/node-esm/test/helpers/util.d.ts create mode 100644 node_modules/@firebase/database/dist/private.d.ts create mode 100644 node_modules/@firebase/database/dist/public.d.ts create mode 100644 node_modules/@firebase/database/dist/src/api.d.ts create mode 100644 node_modules/@firebase/database/dist/src/api.standalone.d.ts create mode 100644 node_modules/@firebase/database/dist/src/api/Database.d.ts create mode 100644 node_modules/@firebase/database/dist/src/api/OnDisconnect.d.ts create mode 100644 node_modules/@firebase/database/dist/src/api/Reference.d.ts create mode 100644 node_modules/@firebase/database/dist/src/api/Reference_impl.d.ts create mode 100644 node_modules/@firebase/database/dist/src/api/ServerValue.d.ts create mode 100644 node_modules/@firebase/database/dist/src/api/Transaction.d.ts create mode 100644 node_modules/@firebase/database/dist/src/api/test_access.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/AppCheckTokenProvider.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/AuthTokenProvider.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/CompoundWrite.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/PersistentConnection.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/ReadonlyRestClient.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/Repo.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/RepoInfo.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/ServerActions.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/SnapshotHolder.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/SparseSnapshotTree.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/SyncPoint.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/SyncTree.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/WriteTree.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/operation/AckUserWrite.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/operation/ListenComplete.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/operation/Merge.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/operation/Operation.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/operation/Overwrite.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/snap/ChildrenNode.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/snap/IndexMap.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/snap/LeafNode.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/snap/Node.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/snap/childSet.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/snap/comparators.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/snap/indexes/Index.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/snap/indexes/KeyIndex.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/snap/indexes/PathIndex.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/snap/indexes/PriorityIndex.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/snap/indexes/ValueIndex.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/snap/nodeFromJSON.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/snap/snap.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/stats/StatsCollection.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/stats/StatsListener.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/stats/StatsManager.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/stats/StatsReporter.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/storage/DOMStorageWrapper.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/storage/MemoryStorage.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/storage/storage.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/util/EventEmitter.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/util/ImmutableTree.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/util/NextPushId.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/util/OnlineMonitor.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/util/Path.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/util/ServerValues.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/util/SortedMap.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/util/Tree.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/util/VisibilityMonitor.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/util/libs/parser.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/util/misc.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/util/util.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/util/validation.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/version.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/view/CacheNode.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/view/Change.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/view/ChildChangeAccumulator.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/view/CompleteChildSource.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/view/Event.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/view/EventGenerator.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/view/EventQueue.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/view/EventRegistration.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/view/QueryParams.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/view/View.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/view/ViewCache.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/view/ViewProcessor.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/view/filter/IndexedFilter.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/view/filter/LimitedFilter.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/view/filter/NodeFilter.d.ts create mode 100644 node_modules/@firebase/database/dist/src/core/view/filter/RangedFilter.d.ts create mode 100644 node_modules/@firebase/database/dist/src/index.d.ts create mode 100644 node_modules/@firebase/database/dist/src/index.node.d.ts create mode 100644 node_modules/@firebase/database/dist/src/index.standalone.d.ts create mode 100644 node_modules/@firebase/database/dist/src/internal/index.d.ts create mode 100644 node_modules/@firebase/database/dist/src/realtime/BrowserPollConnection.d.ts create mode 100644 node_modules/@firebase/database/dist/src/realtime/Connection.d.ts create mode 100644 node_modules/@firebase/database/dist/src/realtime/Constants.d.ts create mode 100644 node_modules/@firebase/database/dist/src/realtime/Transport.d.ts create mode 100644 node_modules/@firebase/database/dist/src/realtime/TransportManager.d.ts create mode 100644 node_modules/@firebase/database/dist/src/realtime/WebSocketConnection.d.ts create mode 100644 node_modules/@firebase/database/dist/src/realtime/polling/PacketReceiver.d.ts create mode 100644 node_modules/@firebase/database/dist/src/register.d.ts create mode 100644 node_modules/@firebase/database/dist/src/tsdoc-metadata.json create mode 100644 node_modules/@firebase/database/dist/test/helpers/EventAccumulator.d.ts create mode 100644 node_modules/@firebase/database/dist/test/helpers/syncpoint-util.d.ts create mode 100644 node_modules/@firebase/database/dist/test/helpers/util.d.ts create mode 100644 node_modules/@firebase/database/package.json create mode 100644 node_modules/@firebase/logger/README.md create mode 100644 node_modules/@firebase/logger/dist/esm/index.d.ts create mode 100644 node_modules/@firebase/logger/dist/esm/index.esm.js create mode 100644 node_modules/@firebase/logger/dist/esm/index.esm.js.map create mode 100644 node_modules/@firebase/logger/dist/esm/package.json create mode 100644 node_modules/@firebase/logger/dist/esm/src/logger.d.ts create mode 100644 node_modules/@firebase/logger/dist/esm/test/custom-logger.test.d.ts create mode 100644 node_modules/@firebase/logger/dist/esm/test/logger.test.d.ts create mode 100644 node_modules/@firebase/logger/dist/index.cjs.js create mode 100644 node_modules/@firebase/logger/dist/index.cjs.js.map create mode 100644 node_modules/@firebase/logger/dist/index.d.ts create mode 100644 node_modules/@firebase/logger/dist/src/logger.d.ts create mode 100644 node_modules/@firebase/logger/dist/test/custom-logger.test.d.ts create mode 100644 node_modules/@firebase/logger/dist/test/logger.test.d.ts create mode 100644 node_modules/@firebase/logger/package.json create mode 100644 node_modules/@firebase/util/README.md create mode 100644 node_modules/@firebase/util/dist/index.cjs.js create mode 100644 node_modules/@firebase/util/dist/index.cjs.js.map create mode 100644 node_modules/@firebase/util/dist/index.d.ts create mode 100644 node_modules/@firebase/util/dist/index.esm.js create mode 100644 node_modules/@firebase/util/dist/index.esm.js.map create mode 100644 node_modules/@firebase/util/dist/index.node.cjs.js create mode 100644 node_modules/@firebase/util/dist/index.node.cjs.js.map create mode 100644 node_modules/@firebase/util/dist/index.node.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/index.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/index.node.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/index.node.esm.js create mode 100644 node_modules/@firebase/util/dist/node-esm/index.node.esm.js.map create mode 100644 node_modules/@firebase/util/dist/node-esm/package.json create mode 100644 node_modules/@firebase/util/dist/node-esm/src/assert.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/compat.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/constants.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/crypt.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/deepCopy.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/defaults.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/deferred.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/emulator.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/environment.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/errors.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/exponential_backoff.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/formatters.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/global.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/json.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/jwt.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/obj.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/postinstall.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/promise.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/query.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/sha1.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/subscribe.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/url.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/utf8.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/src/validation.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/test/base64.test.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/test/compat.test.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/test/deepCopy.test.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/test/defaults.test.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/test/emulator.test.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/test/environments.test.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/test/errors.test.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/test/exponential_backoff.test.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/test/object.test.d.ts create mode 100644 node_modules/@firebase/util/dist/node-esm/test/subscribe.test.d.ts create mode 100644 node_modules/@firebase/util/dist/postinstall.js create mode 100644 node_modules/@firebase/util/dist/postinstall.mjs create mode 100644 node_modules/@firebase/util/dist/src/assert.d.ts create mode 100644 node_modules/@firebase/util/dist/src/compat.d.ts create mode 100644 node_modules/@firebase/util/dist/src/constants.d.ts create mode 100644 node_modules/@firebase/util/dist/src/crypt.d.ts create mode 100644 node_modules/@firebase/util/dist/src/deepCopy.d.ts create mode 100644 node_modules/@firebase/util/dist/src/defaults.d.ts create mode 100644 node_modules/@firebase/util/dist/src/deferred.d.ts create mode 100644 node_modules/@firebase/util/dist/src/emulator.d.ts create mode 100644 node_modules/@firebase/util/dist/src/environment.d.ts create mode 100644 node_modules/@firebase/util/dist/src/errors.d.ts create mode 100644 node_modules/@firebase/util/dist/src/exponential_backoff.d.ts create mode 100644 node_modules/@firebase/util/dist/src/formatters.d.ts create mode 100644 node_modules/@firebase/util/dist/src/global.d.ts create mode 100644 node_modules/@firebase/util/dist/src/json.d.ts create mode 100644 node_modules/@firebase/util/dist/src/jwt.d.ts create mode 100644 node_modules/@firebase/util/dist/src/obj.d.ts create mode 100644 node_modules/@firebase/util/dist/src/postinstall.d.ts create mode 100644 node_modules/@firebase/util/dist/src/promise.d.ts create mode 100644 node_modules/@firebase/util/dist/src/query.d.ts create mode 100644 node_modules/@firebase/util/dist/src/sha1.d.ts create mode 100644 node_modules/@firebase/util/dist/src/subscribe.d.ts create mode 100644 node_modules/@firebase/util/dist/src/url.d.ts create mode 100644 node_modules/@firebase/util/dist/src/utf8.d.ts create mode 100644 node_modules/@firebase/util/dist/src/validation.d.ts create mode 100644 node_modules/@firebase/util/dist/test/base64.test.d.ts create mode 100644 node_modules/@firebase/util/dist/test/compat.test.d.ts create mode 100644 node_modules/@firebase/util/dist/test/deepCopy.test.d.ts create mode 100644 node_modules/@firebase/util/dist/test/defaults.test.d.ts create mode 100644 node_modules/@firebase/util/dist/test/emulator.test.d.ts create mode 100644 node_modules/@firebase/util/dist/test/environments.test.d.ts create mode 100644 node_modules/@firebase/util/dist/test/errors.test.d.ts create mode 100644 node_modules/@firebase/util/dist/test/exponential_backoff.test.d.ts create mode 100644 node_modules/@firebase/util/dist/test/object.test.d.ts create mode 100644 node_modules/@firebase/util/dist/test/subscribe.test.d.ts create mode 100644 node_modules/@firebase/util/dist/tsdoc-metadata.json create mode 100644 node_modules/@firebase/util/dist/util-public.d.ts create mode 100644 node_modules/@firebase/util/dist/util.d.ts create mode 100644 node_modules/@firebase/util/package.json create mode 100644 node_modules/@firebase/util/postinstall.js create mode 100644 node_modules/@google-cloud/firestore/LICENSE create mode 100644 node_modules/@google-cloud/firestore/README.md create mode 100644 node_modules/@google-cloud/firestore/build/protos/admin_v1.json create mode 100644 node_modules/@google-cloud/firestore/build/protos/firestore/bundle.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/firestore_admin_v1_proto_api.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/protos/firestore_admin_v1_proto_api.js create mode 100644 node_modules/@google-cloud/firestore/build/protos/firestore_v1_proto_api.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/protos/firestore_v1_proto_api.js create mode 100644 node_modules/@google-cloud/firestore/build/protos/firestore_v1beta1_proto_api.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/protos/firestore_v1beta1_proto_api.js create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/api/annotations.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/api/client.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/api/field_behavior.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/api/http.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/api/launch_stage.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/api/resource.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/backup.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/database.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/field.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/firestore_admin.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/index.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/location.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/operation.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/schedule.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/aggregation_result.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/bloom_filter.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/common.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/document.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/firestore.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/query.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/query_profile.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/write.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/common.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/document.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/firestore.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/query.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/undeliverable_first_gen_event.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/write.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/longrunning/operations.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/protobuf/any.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/protobuf/descriptor.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/protobuf/duration.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/protobuf/empty.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/protobuf/field_mask.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/protobuf/struct.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/protobuf/timestamp.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/protobuf/wrappers.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/rpc/status.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/type/dayofweek.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/google/type/latlng.proto create mode 100644 node_modules/@google-cloud/firestore/build/protos/update.sh create mode 100644 node_modules/@google-cloud/firestore/build/protos/v1.json create mode 100644 node_modules/@google-cloud/firestore/build/protos/v1beta1.json create mode 100644 node_modules/@google-cloud/firestore/build/src/aggregate.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/aggregate.js create mode 100644 node_modules/@google-cloud/firestore/build/src/backoff.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/backoff.js create mode 100644 node_modules/@google-cloud/firestore/build/src/bulk-writer.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/bulk-writer.js create mode 100644 node_modules/@google-cloud/firestore/build/src/bundle.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/bundle.js create mode 100644 node_modules/@google-cloud/firestore/build/src/collection-group.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/collection-group.js create mode 100644 node_modules/@google-cloud/firestore/build/src/convert.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/convert.js create mode 100644 node_modules/@google-cloud/firestore/build/src/document-change.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/document-change.js create mode 100644 node_modules/@google-cloud/firestore/build/src/document-reader.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/document-reader.js create mode 100644 node_modules/@google-cloud/firestore/build/src/document.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/document.js create mode 100644 node_modules/@google-cloud/firestore/build/src/field-value.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/field-value.js create mode 100644 node_modules/@google-cloud/firestore/build/src/filter.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/filter.js create mode 100644 node_modules/@google-cloud/firestore/build/src/geo-point.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/geo-point.js create mode 100644 node_modules/@google-cloud/firestore/build/src/index.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/index.js create mode 100644 node_modules/@google-cloud/firestore/build/src/logger.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/logger.js create mode 100644 node_modules/@google-cloud/firestore/build/src/map-type.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/map-type.js create mode 100644 node_modules/@google-cloud/firestore/build/src/order.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/order.js create mode 100644 node_modules/@google-cloud/firestore/build/src/path.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/path.js create mode 100644 node_modules/@google-cloud/firestore/build/src/pool.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/pool.js create mode 100644 node_modules/@google-cloud/firestore/build/src/query-partition.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/query-partition.js create mode 100644 node_modules/@google-cloud/firestore/build/src/query-profile.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/query-profile.js create mode 100644 node_modules/@google-cloud/firestore/build/src/rate-limiter.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/rate-limiter.js create mode 100644 node_modules/@google-cloud/firestore/build/src/recursive-delete.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/recursive-delete.js create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/aggregate-query-snapshot.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/aggregate-query-snapshot.js create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/aggregate-query.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/aggregate-query.js create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/collection-reference.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/collection-reference.js create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/composite-filter-internal.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/composite-filter-internal.js create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/constants.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/constants.js create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/document-reference.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/document-reference.js create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/field-filter-internal.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/field-filter-internal.js create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/field-order.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/field-order.js create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/filter-internal.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/filter-internal.js create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/helpers.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/helpers.js create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/query-options.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/query-options.js create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/query-snapshot.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/query-snapshot.js create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/query-util.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/query-util.js create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/query.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/query.js create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/types.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/types.js create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/vector-query-options.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/vector-query-options.js create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/vector-query-snapshot.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/vector-query-snapshot.js create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/vector-query.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/reference/vector-query.js create mode 100644 node_modules/@google-cloud/firestore/build/src/serializer.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/serializer.js create mode 100644 node_modules/@google-cloud/firestore/build/src/status-code.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/status-code.js create mode 100644 node_modules/@google-cloud/firestore/build/src/telemetry/disabled-trace-util.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/telemetry/disabled-trace-util.js create mode 100644 node_modules/@google-cloud/firestore/build/src/telemetry/enabled-trace-util.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/telemetry/enabled-trace-util.js create mode 100644 node_modules/@google-cloud/firestore/build/src/telemetry/span.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/telemetry/span.js create mode 100644 node_modules/@google-cloud/firestore/build/src/telemetry/trace-util.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/telemetry/trace-util.js create mode 100644 node_modules/@google-cloud/firestore/build/src/timestamp.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/timestamp.js create mode 100644 node_modules/@google-cloud/firestore/build/src/transaction.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/transaction.js create mode 100644 node_modules/@google-cloud/firestore/build/src/types.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/types.js create mode 100644 node_modules/@google-cloud/firestore/build/src/util.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/util.js create mode 100644 node_modules/@google-cloud/firestore/build/src/v1/firestore_admin_client.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/v1/firestore_admin_client.js create mode 100644 node_modules/@google-cloud/firestore/build/src/v1/firestore_admin_client_config.json create mode 100644 node_modules/@google-cloud/firestore/build/src/v1/firestore_admin_proto_list.json create mode 100644 node_modules/@google-cloud/firestore/build/src/v1/firestore_client.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/v1/firestore_client.js create mode 100644 node_modules/@google-cloud/firestore/build/src/v1/firestore_client_config.json create mode 100644 node_modules/@google-cloud/firestore/build/src/v1/firestore_proto_list.json create mode 100644 node_modules/@google-cloud/firestore/build/src/v1/gapic_metadata.json create mode 100644 node_modules/@google-cloud/firestore/build/src/v1/index.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/v1/index.js create mode 100644 node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_client.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_client.js create mode 100644 node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_client_config.json create mode 100644 node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_proto_list.json create mode 100644 node_modules/@google-cloud/firestore/build/src/v1beta1/gapic_metadata.json create mode 100644 node_modules/@google-cloud/firestore/build/src/v1beta1/index.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/v1beta1/index.js create mode 100644 node_modules/@google-cloud/firestore/build/src/validate.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/validate.js create mode 100644 node_modules/@google-cloud/firestore/build/src/watch.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/watch.js create mode 100644 node_modules/@google-cloud/firestore/build/src/write-batch.d.ts create mode 100644 node_modules/@google-cloud/firestore/build/src/write-batch.js create mode 100644 node_modules/@google-cloud/firestore/package.json create mode 100644 node_modules/@google-cloud/firestore/types/firestore.d.ts create mode 100644 node_modules/@google-cloud/firestore/types/protos/firestore_admin_v1_proto_api.d.ts create mode 100644 node_modules/@google-cloud/firestore/types/protos/firestore_v1_proto_api.d.ts create mode 100644 node_modules/@google-cloud/firestore/types/protos/firestore_v1beta1_proto_api.d.ts create mode 100644 node_modules/@google-cloud/firestore/types/v1/firestore_admin_client.d.ts create mode 100644 node_modules/@google-cloud/firestore/types/v1/firestore_client.d.ts create mode 100644 node_modules/@google-cloud/firestore/types/v1beta1/firestore_client.d.ts create mode 100644 node_modules/@google-cloud/paginator/CHANGELOG.md create mode 100644 node_modules/@google-cloud/paginator/LICENSE create mode 100644 node_modules/@google-cloud/paginator/README.md create mode 100644 node_modules/@google-cloud/paginator/build/src/index.d.ts create mode 100644 node_modules/@google-cloud/paginator/build/src/index.js create mode 100644 node_modules/@google-cloud/paginator/build/src/resource-stream.d.ts create mode 100644 node_modules/@google-cloud/paginator/build/src/resource-stream.js create mode 100644 node_modules/@google-cloud/paginator/package.json create mode 100644 node_modules/@google-cloud/projectify/CHANGELOG.md create mode 100644 node_modules/@google-cloud/projectify/LICENSE create mode 100644 node_modules/@google-cloud/projectify/README.md create mode 100644 node_modules/@google-cloud/projectify/build/src/index.d.ts create mode 100644 node_modules/@google-cloud/projectify/build/src/index.js create mode 100644 node_modules/@google-cloud/projectify/package.json create mode 100644 node_modules/@google-cloud/promisify/CHANGELOG.md create mode 100644 node_modules/@google-cloud/promisify/LICENSE create mode 100644 node_modules/@google-cloud/promisify/README.md create mode 100644 node_modules/@google-cloud/promisify/build/src/index.d.ts create mode 100644 node_modules/@google-cloud/promisify/build/src/index.js create mode 100644 node_modules/@google-cloud/promisify/package.json create mode 100644 node_modules/@google-cloud/storage/LICENSE create mode 100644 node_modules/@google-cloud/storage/README.md create mode 100644 node_modules/@google-cloud/storage/build/cjs/package.json create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/acl.d.ts create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/acl.js create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/bucket.d.ts create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/bucket.js create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/channel.d.ts create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/channel.js create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/crc32c.d.ts create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/crc32c.js create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/file.d.ts create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/file.js create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/hash-stream-validator.d.ts create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/hash-stream-validator.js create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/hmacKey.d.ts create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/hmacKey.js create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/iam.d.ts create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/iam.js create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/index.d.ts create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/index.js create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/index.d.ts create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/index.js create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/service-object.d.ts create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/service-object.js create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/service.d.ts create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/service.js create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/util.d.ts create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/util.js create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/notification.d.ts create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/notification.js create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/package-json-helper.cjs create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/resumable-upload.d.ts create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/resumable-upload.js create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/signer.d.ts create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/signer.js create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/storage.d.ts create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/storage.js create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/transfer-manager.d.ts create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/transfer-manager.js create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/util.d.ts create mode 100644 node_modules/@google-cloud/storage/build/cjs/src/util.js create mode 100644 node_modules/@google-cloud/storage/build/esm/src/acl.d.ts create mode 100644 node_modules/@google-cloud/storage/build/esm/src/acl.js create mode 100644 node_modules/@google-cloud/storage/build/esm/src/bucket.d.ts create mode 100644 node_modules/@google-cloud/storage/build/esm/src/bucket.js create mode 100644 node_modules/@google-cloud/storage/build/esm/src/channel.d.ts create mode 100644 node_modules/@google-cloud/storage/build/esm/src/channel.js create mode 100644 node_modules/@google-cloud/storage/build/esm/src/crc32c.d.ts create mode 100644 node_modules/@google-cloud/storage/build/esm/src/crc32c.js create mode 100644 node_modules/@google-cloud/storage/build/esm/src/file.d.ts create mode 100644 node_modules/@google-cloud/storage/build/esm/src/file.js create mode 100644 node_modules/@google-cloud/storage/build/esm/src/hash-stream-validator.d.ts create mode 100644 node_modules/@google-cloud/storage/build/esm/src/hash-stream-validator.js create mode 100644 node_modules/@google-cloud/storage/build/esm/src/hmacKey.d.ts create mode 100644 node_modules/@google-cloud/storage/build/esm/src/hmacKey.js create mode 100644 node_modules/@google-cloud/storage/build/esm/src/iam.d.ts create mode 100644 node_modules/@google-cloud/storage/build/esm/src/iam.js create mode 100644 node_modules/@google-cloud/storage/build/esm/src/index.d.ts create mode 100644 node_modules/@google-cloud/storage/build/esm/src/index.js create mode 100644 node_modules/@google-cloud/storage/build/esm/src/nodejs-common/index.d.ts create mode 100644 node_modules/@google-cloud/storage/build/esm/src/nodejs-common/index.js create mode 100644 node_modules/@google-cloud/storage/build/esm/src/nodejs-common/service-object.d.ts create mode 100644 node_modules/@google-cloud/storage/build/esm/src/nodejs-common/service-object.js create mode 100644 node_modules/@google-cloud/storage/build/esm/src/nodejs-common/service.d.ts create mode 100644 node_modules/@google-cloud/storage/build/esm/src/nodejs-common/service.js create mode 100644 node_modules/@google-cloud/storage/build/esm/src/nodejs-common/util.d.ts create mode 100644 node_modules/@google-cloud/storage/build/esm/src/nodejs-common/util.js create mode 100644 node_modules/@google-cloud/storage/build/esm/src/notification.d.ts create mode 100644 node_modules/@google-cloud/storage/build/esm/src/notification.js create mode 100644 node_modules/@google-cloud/storage/build/esm/src/package-json-helper.cjs create mode 100644 node_modules/@google-cloud/storage/build/esm/src/resumable-upload.d.ts create mode 100644 node_modules/@google-cloud/storage/build/esm/src/resumable-upload.js create mode 100644 node_modules/@google-cloud/storage/build/esm/src/signer.d.ts create mode 100644 node_modules/@google-cloud/storage/build/esm/src/signer.js create mode 100644 node_modules/@google-cloud/storage/build/esm/src/storage.d.ts create mode 100644 node_modules/@google-cloud/storage/build/esm/src/storage.js create mode 100644 node_modules/@google-cloud/storage/build/esm/src/transfer-manager.d.ts create mode 100644 node_modules/@google-cloud/storage/build/esm/src/transfer-manager.js create mode 100644 node_modules/@google-cloud/storage/build/esm/src/util.d.ts create mode 100644 node_modules/@google-cloud/storage/build/esm/src/util.js create mode 100644 node_modules/@google-cloud/storage/node_modules/.bin/uuid create mode 100644 node_modules/@google-cloud/storage/node_modules/.bin/uuid.cmd create mode 100644 node_modules/@google-cloud/storage/node_modules/.bin/uuid.ps1 create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/CHANGELOG.md create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/CONTRIBUTING.md create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/LICENSE.md create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/README.md create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/bin/uuid create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/index.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/md5.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/nil.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/parse.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/regex.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/rng.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/sha1.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/stringify.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/v1.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/v3.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/v35.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/v4.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/v5.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/validate.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/version.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/index.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/md5.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/nil.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/parse.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/regex.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/rng.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/sha1.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/stringify.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/v1.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/v3.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/v35.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/v4.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/v5.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/validate.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/version.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/index.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/md5-browser.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/md5.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/nil.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/parse.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/regex.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/rng-browser.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/rng.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/sha1-browser.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/sha1.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/stringify.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuid.min.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidNIL.min.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidParse.min.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidStringify.min.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidValidate.min.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidVersion.min.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidv1.min.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidv3.min.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidv4.min.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidv5.min.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/uuid-bin.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/v1.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/v3.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/v35.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/v4.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/v5.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/validate.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/dist/version.js create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/package.json create mode 100644 node_modules/@google-cloud/storage/node_modules/uuid/wrapper.mjs create mode 100644 node_modules/@google-cloud/storage/package.json create mode 100644 node_modules/@grpc/grpc-js/LICENSE create mode 100644 node_modules/@grpc/grpc-js/README.md create mode 100644 node_modules/@grpc/grpc-js/build/src/admin.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/admin.js create mode 100644 node_modules/@grpc/grpc-js/build/src/admin.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/auth-context.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/auth-context.js create mode 100644 node_modules/@grpc/grpc-js/build/src/auth-context.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/backoff-timeout.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/backoff-timeout.js create mode 100644 node_modules/@grpc/grpc-js/build/src/backoff-timeout.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/call-credentials.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/call-credentials.js create mode 100644 node_modules/@grpc/grpc-js/build/src/call-credentials.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/call-interface.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/call-interface.js create mode 100644 node_modules/@grpc/grpc-js/build/src/call-interface.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/call-number.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/call-number.js create mode 100644 node_modules/@grpc/grpc-js/build/src/call-number.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/call.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/call.js create mode 100644 node_modules/@grpc/grpc-js/build/src/call.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/certificate-provider.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/certificate-provider.js create mode 100644 node_modules/@grpc/grpc-js/build/src/certificate-provider.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/channel-credentials.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/channel-credentials.js create mode 100644 node_modules/@grpc/grpc-js/build/src/channel-credentials.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/channel-options.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/channel-options.js create mode 100644 node_modules/@grpc/grpc-js/build/src/channel-options.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/channel.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/channel.js create mode 100644 node_modules/@grpc/grpc-js/build/src/channel.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/channelz.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/channelz.js create mode 100644 node_modules/@grpc/grpc-js/build/src/channelz.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/client-interceptors.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/client-interceptors.js create mode 100644 node_modules/@grpc/grpc-js/build/src/client-interceptors.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/client.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/client.js create mode 100644 node_modules/@grpc/grpc-js/build/src/client.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/compression-algorithms.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/compression-algorithms.js create mode 100644 node_modules/@grpc/grpc-js/build/src/compression-algorithms.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/compression-filter.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/compression-filter.js create mode 100644 node_modules/@grpc/grpc-js/build/src/compression-filter.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/connectivity-state.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/connectivity-state.js create mode 100644 node_modules/@grpc/grpc-js/build/src/connectivity-state.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/constants.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/constants.js create mode 100644 node_modules/@grpc/grpc-js/build/src/constants.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/control-plane-status.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/control-plane-status.js create mode 100644 node_modules/@grpc/grpc-js/build/src/control-plane-status.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/deadline.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/deadline.js create mode 100644 node_modules/@grpc/grpc-js/build/src/deadline.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/duration.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/duration.js create mode 100644 node_modules/@grpc/grpc-js/build/src/duration.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/environment.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/environment.js create mode 100644 node_modules/@grpc/grpc-js/build/src/environment.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/error.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/error.js create mode 100644 node_modules/@grpc/grpc-js/build/src/error.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/events.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/events.js create mode 100644 node_modules/@grpc/grpc-js/build/src/events.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/experimental.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/experimental.js create mode 100644 node_modules/@grpc/grpc-js/build/src/experimental.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/filter-stack.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/filter-stack.js create mode 100644 node_modules/@grpc/grpc-js/build/src/filter-stack.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/filter.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/filter.js create mode 100644 node_modules/@grpc/grpc-js/build/src/filter.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/channelz.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/channelz.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/channelz.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DescriptorProto.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DescriptorProto.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DescriptorProto.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Edition.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Edition.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Edition.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumDescriptorProto.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumDescriptorProto.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumDescriptorProto.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumOptions.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumOptions.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumOptions.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueDescriptorProto.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueDescriptorProto.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueDescriptorProto.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueOptions.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueOptions.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueOptions.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ExtensionRangeOptions.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ExtensionRangeOptions.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ExtensionRangeOptions.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSet.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSet.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSet.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSetDefaults.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSetDefaults.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSetDefaults.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldDescriptorProto.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldDescriptorProto.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldDescriptorProto.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldOptions.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldOptions.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldOptions.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorProto.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorProto.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorProto.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorSet.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorSet.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorSet.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileOptions.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileOptions.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileOptions.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/GeneratedCodeInfo.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/GeneratedCodeInfo.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/GeneratedCodeInfo.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MessageOptions.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MessageOptions.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MessageOptions.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodDescriptorProto.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodDescriptorProto.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodDescriptorProto.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodOptions.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodOptions.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodOptions.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofDescriptorProto.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofDescriptorProto.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofDescriptorProto.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofOptions.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofOptions.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofOptions.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceDescriptorProto.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceDescriptorProto.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceDescriptorProto.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceOptions.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceOptions.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceOptions.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SourceCodeInfo.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SourceCodeInfo.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SourceCodeInfo.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SymbolVisibility.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SymbolVisibility.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SymbolVisibility.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UninterpretedOption.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UninterpretedOption.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UninterpretedOption.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/orca.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/orca.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/orca.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/AnyRules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/AnyRules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/AnyRules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/BoolRules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/BoolRules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/BoolRules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/BytesRules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/BytesRules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/BytesRules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/DoubleRules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/DoubleRules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/DoubleRules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/DurationRules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/DurationRules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/DurationRules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/EnumRules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/EnumRules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/EnumRules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/FieldRules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/FieldRules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/FieldRules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed32Rules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed32Rules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed32Rules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed64Rules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed64Rules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed64Rules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/FloatRules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/FloatRules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/FloatRules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/Int32Rules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/Int32Rules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/Int32Rules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/Int64Rules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/Int64Rules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/Int64Rules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/KnownRegex.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/KnownRegex.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/KnownRegex.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/MapRules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/MapRules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/MapRules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/MessageRules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/MessageRules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/MessageRules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/RepeatedRules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/RepeatedRules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/RepeatedRules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed32Rules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed32Rules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed32Rules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed64Rules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed64Rules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed64Rules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/SInt32Rules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/SInt32Rules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/SInt32Rules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/SInt64Rules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/SInt64Rules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/SInt64Rules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/StringRules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/StringRules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/StringRules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/TimestampRules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/TimestampRules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/TimestampRules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/UInt32Rules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/UInt32Rules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/UInt32Rules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/UInt64Rules.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/UInt64Rules.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/validate/UInt64Rules.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/xds/data/orca/v3/OrcaLoadReport.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/xds/data/orca/v3/OrcaLoadReport.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/xds/data/orca/v3/OrcaLoadReport.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OpenRcaService.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OpenRcaService.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OpenRcaService.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OrcaLoadReportRequest.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OrcaLoadReportRequest.js create mode 100644 node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OrcaLoadReportRequest.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/http_proxy.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/http_proxy.js create mode 100644 node_modules/@grpc/grpc-js/build/src/http_proxy.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/index.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/index.js create mode 100644 node_modules/@grpc/grpc-js/build/src/index.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/internal-channel.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/internal-channel.js create mode 100644 node_modules/@grpc/grpc-js/build/src/internal-channel.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.js create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancer.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancer.js create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancer.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancing-call.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancing-call.js create mode 100644 node_modules/@grpc/grpc-js/build/src/load-balancing-call.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/logging.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/logging.js create mode 100644 node_modules/@grpc/grpc-js/build/src/logging.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/make-client.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/make-client.js create mode 100644 node_modules/@grpc/grpc-js/build/src/make-client.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/metadata.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/metadata.js create mode 100644 node_modules/@grpc/grpc-js/build/src/metadata.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/object-stream.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/object-stream.js create mode 100644 node_modules/@grpc/grpc-js/build/src/object-stream.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/orca.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/orca.js create mode 100644 node_modules/@grpc/grpc-js/build/src/orca.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/picker.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/picker.js create mode 100644 node_modules/@grpc/grpc-js/build/src/picker.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/priority-queue.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/priority-queue.js create mode 100644 node_modules/@grpc/grpc-js/build/src/priority-queue.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/resolver-dns.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/resolver-dns.js create mode 100644 node_modules/@grpc/grpc-js/build/src/resolver-dns.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/resolver-ip.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/resolver-ip.js create mode 100644 node_modules/@grpc/grpc-js/build/src/resolver-ip.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/resolver-uds.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/resolver-uds.js create mode 100644 node_modules/@grpc/grpc-js/build/src/resolver-uds.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/resolver.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/resolver.js create mode 100644 node_modules/@grpc/grpc-js/build/src/resolver.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/resolving-call.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/resolving-call.js create mode 100644 node_modules/@grpc/grpc-js/build/src/resolving-call.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js create mode 100644 node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/retrying-call.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/retrying-call.js create mode 100644 node_modules/@grpc/grpc-js/build/src/retrying-call.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/server-call.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/server-call.js create mode 100644 node_modules/@grpc/grpc-js/build/src/server-call.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/server-credentials.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/server-credentials.js create mode 100644 node_modules/@grpc/grpc-js/build/src/server-credentials.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/server-interceptors.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/server-interceptors.js create mode 100644 node_modules/@grpc/grpc-js/build/src/server-interceptors.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/server.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/server.js create mode 100644 node_modules/@grpc/grpc-js/build/src/server.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/service-config.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/service-config.js create mode 100644 node_modules/@grpc/grpc-js/build/src/service-config.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.js create mode 100644 node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/status-builder.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/status-builder.js create mode 100644 node_modules/@grpc/grpc-js/build/src/status-builder.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/stream-decoder.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/stream-decoder.js create mode 100644 node_modules/@grpc/grpc-js/build/src/stream-decoder.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/subchannel-address.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/subchannel-address.js create mode 100644 node_modules/@grpc/grpc-js/build/src/subchannel-address.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/subchannel-call.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/subchannel-call.js create mode 100644 node_modules/@grpc/grpc-js/build/src/subchannel-call.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/subchannel-interface.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/subchannel-interface.js create mode 100644 node_modules/@grpc/grpc-js/build/src/subchannel-interface.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/subchannel-pool.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/subchannel-pool.js create mode 100644 node_modules/@grpc/grpc-js/build/src/subchannel-pool.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/subchannel.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/subchannel.js create mode 100644 node_modules/@grpc/grpc-js/build/src/subchannel.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/tls-helpers.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/tls-helpers.js create mode 100644 node_modules/@grpc/grpc-js/build/src/tls-helpers.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/transport.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/transport.js create mode 100644 node_modules/@grpc/grpc-js/build/src/transport.js.map create mode 100644 node_modules/@grpc/grpc-js/build/src/uri-parser.d.ts create mode 100644 node_modules/@grpc/grpc-js/build/src/uri-parser.js create mode 100644 node_modules/@grpc/grpc-js/build/src/uri-parser.js.map create mode 100644 node_modules/@grpc/grpc-js/node_modules/.bin/proto-loader-gen-types create mode 100644 node_modules/@grpc/grpc-js/node_modules/.bin/proto-loader-gen-types.cmd create mode 100644 node_modules/@grpc/grpc-js/node_modules/.bin/proto-loader-gen-types.ps1 create mode 100644 node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/LICENSE create mode 100644 node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/README.md create mode 100644 node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js create mode 100644 node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js.map create mode 100644 node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/index.d.ts create mode 100644 node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/index.js create mode 100644 node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/index.js.map create mode 100644 node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/util.d.ts create mode 100644 node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/util.js create mode 100644 node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/util.js.map create mode 100644 node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/package.json create mode 100644 node_modules/@grpc/grpc-js/package.json create mode 100644 node_modules/@grpc/grpc-js/proto/channelz.proto create mode 100644 node_modules/@grpc/grpc-js/proto/protoc-gen-validate/LICENSE create mode 100644 node_modules/@grpc/grpc-js/proto/protoc-gen-validate/validate/validate.proto create mode 100644 node_modules/@grpc/grpc-js/proto/xds/LICENSE create mode 100644 node_modules/@grpc/grpc-js/proto/xds/xds/data/orca/v3/orca_load_report.proto create mode 100644 node_modules/@grpc/grpc-js/proto/xds/xds/service/orca/v3/orca.proto create mode 100644 node_modules/@grpc/grpc-js/src/admin.ts create mode 100644 node_modules/@grpc/grpc-js/src/auth-context.ts create mode 100644 node_modules/@grpc/grpc-js/src/backoff-timeout.ts create mode 100644 node_modules/@grpc/grpc-js/src/call-credentials.ts create mode 100644 node_modules/@grpc/grpc-js/src/call-interface.ts create mode 100644 node_modules/@grpc/grpc-js/src/call-number.ts create mode 100644 node_modules/@grpc/grpc-js/src/call.ts create mode 100644 node_modules/@grpc/grpc-js/src/certificate-provider.ts create mode 100644 node_modules/@grpc/grpc-js/src/channel-credentials.ts create mode 100644 node_modules/@grpc/grpc-js/src/channel-options.ts create mode 100644 node_modules/@grpc/grpc-js/src/channel.ts create mode 100644 node_modules/@grpc/grpc-js/src/channelz.ts create mode 100644 node_modules/@grpc/grpc-js/src/client-interceptors.ts create mode 100644 node_modules/@grpc/grpc-js/src/client.ts create mode 100644 node_modules/@grpc/grpc-js/src/compression-algorithms.ts create mode 100644 node_modules/@grpc/grpc-js/src/compression-filter.ts create mode 100644 node_modules/@grpc/grpc-js/src/connectivity-state.ts create mode 100644 node_modules/@grpc/grpc-js/src/constants.ts create mode 100644 node_modules/@grpc/grpc-js/src/control-plane-status.ts create mode 100644 node_modules/@grpc/grpc-js/src/deadline.ts create mode 100644 node_modules/@grpc/grpc-js/src/duration.ts create mode 100644 node_modules/@grpc/grpc-js/src/environment.ts create mode 100644 node_modules/@grpc/grpc-js/src/error.ts create mode 100644 node_modules/@grpc/grpc-js/src/events.ts create mode 100644 node_modules/@grpc/grpc-js/src/experimental.ts create mode 100644 node_modules/@grpc/grpc-js/src/filter-stack.ts create mode 100644 node_modules/@grpc/grpc-js/src/filter.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/channelz.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/Any.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/BoolValue.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/BytesValue.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/DescriptorProto.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/DoubleValue.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/Duration.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/Edition.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/EnumDescriptorProto.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/EnumOptions.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/EnumValueDescriptorProto.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/EnumValueOptions.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/ExtensionRangeOptions.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/FeatureSet.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/FeatureSetDefaults.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/FieldDescriptorProto.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/FieldOptions.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/FileDescriptorProto.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/FileDescriptorSet.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/FileOptions.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/FloatValue.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/GeneratedCodeInfo.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/Int32Value.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/Int64Value.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/MessageOptions.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/MethodDescriptorProto.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/MethodOptions.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/OneofDescriptorProto.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/OneofOptions.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/ServiceDescriptorProto.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/ServiceOptions.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/SourceCodeInfo.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/StringValue.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/SymbolVisibility.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/Timestamp.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/UInt32Value.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/UInt64Value.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/google/protobuf/UninterpretedOption.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Address.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Channel.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelConnectivityState.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelData.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelRef.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelTrace.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelTraceEvent.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Channelz.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetChannelRequest.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetChannelResponse.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerRequest.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerResponse.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerSocketsRequest.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerSocketsResponse.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServersRequest.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServersResponse.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSocketRequest.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSocketResponse.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSubchannelRequest.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSubchannelResponse.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetTopChannelsRequest.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetTopChannelsResponse.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Security.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Server.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ServerData.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ServerRef.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Socket.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketData.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOption.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionLinger.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionTimeout.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketRef.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Subchannel.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SubchannelRef.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/orca.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/AnyRules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/BoolRules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/BytesRules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/DoubleRules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/DurationRules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/EnumRules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/FieldRules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/Fixed32Rules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/Fixed64Rules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/FloatRules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/Int32Rules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/Int64Rules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/KnownRegex.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/MapRules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/MessageRules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/RepeatedRules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/SFixed32Rules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/SFixed64Rules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/SInt32Rules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/SInt64Rules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/StringRules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/TimestampRules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/UInt32Rules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/validate/UInt64Rules.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/xds/data/orca/v3/OrcaLoadReport.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/xds/service/orca/v3/OpenRcaService.ts create mode 100644 node_modules/@grpc/grpc-js/src/generated/xds/service/orca/v3/OrcaLoadReportRequest.ts create mode 100644 node_modules/@grpc/grpc-js/src/http_proxy.ts create mode 100644 node_modules/@grpc/grpc-js/src/index.ts create mode 100644 node_modules/@grpc/grpc-js/src/internal-channel.ts create mode 100644 node_modules/@grpc/grpc-js/src/load-balancer-child-handler.ts create mode 100644 node_modules/@grpc/grpc-js/src/load-balancer-outlier-detection.ts create mode 100644 node_modules/@grpc/grpc-js/src/load-balancer-pick-first.ts create mode 100644 node_modules/@grpc/grpc-js/src/load-balancer-round-robin.ts create mode 100644 node_modules/@grpc/grpc-js/src/load-balancer-weighted-round-robin.ts create mode 100644 node_modules/@grpc/grpc-js/src/load-balancer.ts create mode 100644 node_modules/@grpc/grpc-js/src/load-balancing-call.ts create mode 100644 node_modules/@grpc/grpc-js/src/logging.ts create mode 100644 node_modules/@grpc/grpc-js/src/make-client.ts create mode 100644 node_modules/@grpc/grpc-js/src/metadata.ts create mode 100644 node_modules/@grpc/grpc-js/src/object-stream.ts create mode 100644 node_modules/@grpc/grpc-js/src/orca.ts create mode 100644 node_modules/@grpc/grpc-js/src/picker.ts create mode 100644 node_modules/@grpc/grpc-js/src/priority-queue.ts create mode 100644 node_modules/@grpc/grpc-js/src/resolver-dns.ts create mode 100644 node_modules/@grpc/grpc-js/src/resolver-ip.ts create mode 100644 node_modules/@grpc/grpc-js/src/resolver-uds.ts create mode 100644 node_modules/@grpc/grpc-js/src/resolver.ts create mode 100644 node_modules/@grpc/grpc-js/src/resolving-call.ts create mode 100644 node_modules/@grpc/grpc-js/src/resolving-load-balancer.ts create mode 100644 node_modules/@grpc/grpc-js/src/retrying-call.ts create mode 100644 node_modules/@grpc/grpc-js/src/server-call.ts create mode 100644 node_modules/@grpc/grpc-js/src/server-credentials.ts create mode 100644 node_modules/@grpc/grpc-js/src/server-interceptors.ts create mode 100644 node_modules/@grpc/grpc-js/src/server.ts create mode 100644 node_modules/@grpc/grpc-js/src/service-config.ts create mode 100644 node_modules/@grpc/grpc-js/src/single-subchannel-channel.ts create mode 100644 node_modules/@grpc/grpc-js/src/status-builder.ts create mode 100644 node_modules/@grpc/grpc-js/src/stream-decoder.ts create mode 100644 node_modules/@grpc/grpc-js/src/subchannel-address.ts create mode 100644 node_modules/@grpc/grpc-js/src/subchannel-call.ts create mode 100644 node_modules/@grpc/grpc-js/src/subchannel-interface.ts create mode 100644 node_modules/@grpc/grpc-js/src/subchannel-pool.ts create mode 100644 node_modules/@grpc/grpc-js/src/subchannel.ts create mode 100644 node_modules/@grpc/grpc-js/src/tls-helpers.ts create mode 100644 node_modules/@grpc/grpc-js/src/transport.ts create mode 100644 node_modules/@grpc/grpc-js/src/uri-parser.ts create mode 100644 node_modules/@grpc/proto-loader/LICENSE create mode 100644 node_modules/@grpc/proto-loader/README.md create mode 100644 node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js create mode 100644 node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js.map create mode 100644 node_modules/@grpc/proto-loader/build/src/index.d.ts create mode 100644 node_modules/@grpc/proto-loader/build/src/index.js create mode 100644 node_modules/@grpc/proto-loader/build/src/index.js.map create mode 100644 node_modules/@grpc/proto-loader/build/src/util.d.ts create mode 100644 node_modules/@grpc/proto-loader/build/src/util.js create mode 100644 node_modules/@grpc/proto-loader/build/src/util.js.map create mode 100644 node_modules/@grpc/proto-loader/package.json create mode 100644 node_modules/@js-sdsl/ordered-map/CHANGELOG.md create mode 100644 node_modules/@js-sdsl/ordered-map/LICENSE create mode 100644 node_modules/@js-sdsl/ordered-map/README.md create mode 100644 node_modules/@js-sdsl/ordered-map/README.zh-CN.md create mode 100644 node_modules/@js-sdsl/ordered-map/dist/cjs/index.d.ts create mode 100644 node_modules/@js-sdsl/ordered-map/dist/cjs/index.js create mode 100644 node_modules/@js-sdsl/ordered-map/dist/cjs/index.js.map create mode 100644 node_modules/@js-sdsl/ordered-map/dist/esm/index.d.ts create mode 100644 node_modules/@js-sdsl/ordered-map/dist/esm/index.js create mode 100644 node_modules/@js-sdsl/ordered-map/dist/esm/index.js.map create mode 100644 node_modules/@js-sdsl/ordered-map/dist/umd/ordered-map.js create mode 100644 node_modules/@js-sdsl/ordered-map/dist/umd/ordered-map.min.js create mode 100644 node_modules/@js-sdsl/ordered-map/dist/umd/ordered-map.min.js.map create mode 100644 node_modules/@js-sdsl/ordered-map/package.json create mode 100644 node_modules/@opentelemetry/api/LICENSE create mode 100644 node_modules/@opentelemetry/api/README.md create mode 100644 node_modules/@opentelemetry/api/build/esm/api/context.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/api/context.js create mode 100644 node_modules/@opentelemetry/api/build/esm/api/context.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/api/diag.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/api/diag.js create mode 100644 node_modules/@opentelemetry/api/build/esm/api/diag.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/api/metrics.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/api/metrics.js create mode 100644 node_modules/@opentelemetry/api/build/esm/api/metrics.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/api/propagation.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/api/propagation.js create mode 100644 node_modules/@opentelemetry/api/build/esm/api/propagation.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/api/trace.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/api/trace.js create mode 100644 node_modules/@opentelemetry/api/build/esm/api/trace.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.js create mode 100644 node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.js create mode 100644 node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.js create mode 100644 node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/baggage/types.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/baggage/types.js create mode 100644 node_modules/@opentelemetry/api/build/esm/baggage/types.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/baggage/utils.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/baggage/utils.js create mode 100644 node_modules/@opentelemetry/api/build/esm/baggage/utils.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/common/Attributes.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/common/Attributes.js create mode 100644 node_modules/@opentelemetry/api/build/esm/common/Attributes.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/common/Exception.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/common/Exception.js create mode 100644 node_modules/@opentelemetry/api/build/esm/common/Exception.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/common/Time.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/common/Time.js create mode 100644 node_modules/@opentelemetry/api/build/esm/common/Time.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/context-api.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/context-api.js create mode 100644 node_modules/@opentelemetry/api/build/esm/context-api.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js create mode 100644 node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/context/context.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/context/context.js create mode 100644 node_modules/@opentelemetry/api/build/esm/context/context.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/context/types.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/context/types.js create mode 100644 node_modules/@opentelemetry/api/build/esm/context/types.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/diag-api.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/diag-api.js create mode 100644 node_modules/@opentelemetry/api/build/esm/diag-api.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js create mode 100644 node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/diag/consoleLogger.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/diag/consoleLogger.js create mode 100644 node_modules/@opentelemetry/api/build/esm/diag/consoleLogger.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js create mode 100644 node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/diag/internal/noopLogger.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/diag/internal/noopLogger.js create mode 100644 node_modules/@opentelemetry/api/build/esm/diag/internal/noopLogger.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/diag/types.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/diag/types.js create mode 100644 node_modules/@opentelemetry/api/build/esm/diag/types.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/experimental/index.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/experimental/index.js create mode 100644 node_modules/@opentelemetry/api/build/esm/experimental/index.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredOptions.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredOptions.js create mode 100644 node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredOptions.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredTracer.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredTracer.js create mode 100644 node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredTracer.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/index.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/index.js create mode 100644 node_modules/@opentelemetry/api/build/esm/index.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/internal/global-utils.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/internal/global-utils.js create mode 100644 node_modules/@opentelemetry/api/build/esm/internal/global-utils.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/internal/semver.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/internal/semver.js create mode 100644 node_modules/@opentelemetry/api/build/esm/internal/semver.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics-api.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics-api.js create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics-api.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics/Meter.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics/Meter.js create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics/Meter.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics/MeterProvider.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics/MeterProvider.js create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics/MeterProvider.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics/Metric.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics/Metric.js create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics/Metric.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.js create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics/ObservableResult.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics/ObservableResult.js create mode 100644 node_modules/@opentelemetry/api/build/esm/metrics/ObservableResult.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/platform/browser/globalThis.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/platform/browser/globalThis.js create mode 100644 node_modules/@opentelemetry/api/build/esm/platform/browser/globalThis.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/platform/browser/index.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/platform/browser/index.js create mode 100644 node_modules/@opentelemetry/api/build/esm/platform/browser/index.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/platform/index.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/platform/index.js create mode 100644 node_modules/@opentelemetry/api/build/esm/platform/index.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js create mode 100644 node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/platform/node/index.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/platform/node/index.js create mode 100644 node_modules/@opentelemetry/api/build/esm/platform/node/index.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/propagation-api.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/propagation-api.js create mode 100644 node_modules/@opentelemetry/api/build/esm/propagation-api.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.js create mode 100644 node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.js create mode 100644 node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace-api.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace-api.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace-api.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/Sampler.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/Sampler.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/Sampler.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/SpanOptions.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/SpanOptions.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/SpanOptions.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/attributes.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/attributes.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/attributes.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/context-utils.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/context-utils.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/context-utils.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-impl.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-impl.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-impl.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-validators.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-validators.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-validators.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/internal/utils.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/internal/utils.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/internal/utils.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/link.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/link.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/link.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/span.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/span.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/span.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/span_context.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/span_context.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/span_context.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/span_kind.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/span_kind.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/span_kind.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/status.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/status.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/status.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/trace_flags.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/trace_state.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/trace_state.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/trace_state.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/tracer.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/tracer.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/tracer.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/tracer_options.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/tracer_options.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/tracer_options.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/tracer_provider.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/tracer_provider.js create mode 100644 node_modules/@opentelemetry/api/build/esm/trace/tracer_provider.js.map create mode 100644 node_modules/@opentelemetry/api/build/esm/version.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esm/version.js create mode 100644 node_modules/@opentelemetry/api/build/esm/version.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/api/context.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/api/context.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/api/context.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/api/diag.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/api/diag.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/api/diag.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/api/metrics.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/api/metrics.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/api/metrics.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/api/propagation.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/api/propagation.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/api/propagation.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/api/trace.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/api/trace.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/api/trace.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/baggage/context-helpers.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/baggage/context-helpers.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/baggage/context-helpers.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/baggage/internal/baggage-impl.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/baggage/internal/baggage-impl.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/baggage/internal/baggage-impl.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/baggage/internal/symbol.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/baggage/internal/symbol.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/baggage/internal/symbol.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/baggage/types.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/baggage/types.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/baggage/types.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/baggage/utils.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/baggage/utils.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/baggage/utils.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/common/Attributes.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/common/Attributes.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/common/Attributes.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/common/Exception.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/common/Exception.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/common/Exception.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/common/Time.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/common/Time.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/common/Time.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/context-api.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/context-api.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/context-api.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/context/NoopContextManager.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/context/NoopContextManager.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/context/NoopContextManager.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/context/context.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/context/context.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/context/context.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/context/types.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/context/types.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/context/types.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/diag-api.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/diag-api.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/diag-api.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/diag/ComponentLogger.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/diag/ComponentLogger.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/diag/ComponentLogger.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/diag/consoleLogger.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/diag/consoleLogger.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/diag/consoleLogger.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/diag/internal/logLevelLogger.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/diag/internal/logLevelLogger.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/diag/internal/logLevelLogger.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/diag/internal/noopLogger.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/diag/internal/noopLogger.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/diag/internal/noopLogger.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/diag/types.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/diag/types.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/diag/types.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/experimental/index.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/experimental/index.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/experimental/index.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredOptions.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredOptions.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredOptions.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredTracer.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredTracer.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredTracer.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/index.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/index.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/index.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/internal/global-utils.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/internal/global-utils.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/internal/global-utils.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/internal/semver.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/internal/semver.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/internal/semver.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics-api.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics-api.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics-api.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics/Meter.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics/Meter.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics/Meter.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics/MeterProvider.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics/MeterProvider.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics/MeterProvider.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics/Metric.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics/Metric.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics/Metric.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeter.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeter.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeter.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeterProvider.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeterProvider.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeterProvider.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics/ObservableResult.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics/ObservableResult.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/metrics/ObservableResult.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/platform/browser/globalThis.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/platform/browser/globalThis.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/platform/browser/globalThis.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/platform/browser/index.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/platform/browser/index.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/platform/browser/index.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/platform/index.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/platform/index.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/platform/index.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/platform/node/globalThis.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/platform/node/globalThis.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/platform/node/globalThis.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/platform/node/index.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/platform/node/index.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/platform/node/index.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/propagation-api.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/propagation-api.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/propagation-api.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/propagation/NoopTextMapPropagator.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/propagation/NoopTextMapPropagator.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/propagation/NoopTextMapPropagator.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/propagation/TextMapPropagator.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/propagation/TextMapPropagator.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/propagation/TextMapPropagator.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace-api.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace-api.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace-api.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/NonRecordingSpan.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/NonRecordingSpan.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/NonRecordingSpan.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/NoopTracer.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/NoopTracer.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/NoopTracer.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/NoopTracerProvider.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/NoopTracerProvider.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/NoopTracerProvider.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracer.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracer.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracer.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracerProvider.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracerProvider.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracerProvider.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/Sampler.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/Sampler.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/Sampler.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/SamplingResult.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/SamplingResult.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/SamplingResult.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/SpanOptions.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/SpanOptions.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/SpanOptions.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/attributes.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/attributes.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/attributes.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/context-utils.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/context-utils.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/context-utils.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-impl.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-impl.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-impl.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-validators.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-validators.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-validators.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/internal/utils.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/internal/utils.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/internal/utils.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/invalid-span-constants.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/invalid-span-constants.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/invalid-span-constants.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/link.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/link.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/link.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/span.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/span.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/span.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/span_context.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/span_context.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/span_context.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/span_kind.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/span_kind.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/span_kind.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/spancontext-utils.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/spancontext-utils.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/spancontext-utils.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/status.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/status.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/status.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/trace_flags.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/trace_flags.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/trace_flags.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/trace_state.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/trace_state.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/trace_state.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/tracer.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/tracer.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/tracer.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/tracer_options.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/tracer_options.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/tracer_options.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/tracer_provider.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/tracer_provider.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/trace/tracer_provider.js.map create mode 100644 node_modules/@opentelemetry/api/build/esnext/version.d.ts create mode 100644 node_modules/@opentelemetry/api/build/esnext/version.js create mode 100644 node_modules/@opentelemetry/api/build/esnext/version.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/api/context.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/api/context.js create mode 100644 node_modules/@opentelemetry/api/build/src/api/context.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/api/diag.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/api/diag.js create mode 100644 node_modules/@opentelemetry/api/build/src/api/diag.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/api/metrics.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/api/metrics.js create mode 100644 node_modules/@opentelemetry/api/build/src/api/metrics.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/api/propagation.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/api/propagation.js create mode 100644 node_modules/@opentelemetry/api/build/src/api/propagation.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/api/trace.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/api/trace.js create mode 100644 node_modules/@opentelemetry/api/build/src/api/trace.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/baggage/context-helpers.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js create mode 100644 node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js create mode 100644 node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js create mode 100644 node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/baggage/types.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/baggage/types.js create mode 100644 node_modules/@opentelemetry/api/build/src/baggage/types.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/baggage/utils.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/baggage/utils.js create mode 100644 node_modules/@opentelemetry/api/build/src/baggage/utils.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/common/Attributes.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/common/Attributes.js create mode 100644 node_modules/@opentelemetry/api/build/src/common/Attributes.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/common/Exception.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/common/Exception.js create mode 100644 node_modules/@opentelemetry/api/build/src/common/Exception.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/common/Time.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/common/Time.js create mode 100644 node_modules/@opentelemetry/api/build/src/common/Time.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/context-api.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/context-api.js create mode 100644 node_modules/@opentelemetry/api/build/src/context-api.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/context/NoopContextManager.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js create mode 100644 node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/context/context.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/context/context.js create mode 100644 node_modules/@opentelemetry/api/build/src/context/context.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/context/types.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/context/types.js create mode 100644 node_modules/@opentelemetry/api/build/src/context/types.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/diag-api.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/diag-api.js create mode 100644 node_modules/@opentelemetry/api/build/src/diag-api.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js create mode 100644 node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/diag/consoleLogger.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js create mode 100644 node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js create mode 100644 node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/diag/internal/noopLogger.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/diag/internal/noopLogger.js create mode 100644 node_modules/@opentelemetry/api/build/src/diag/internal/noopLogger.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/diag/types.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/diag/types.js create mode 100644 node_modules/@opentelemetry/api/build/src/diag/types.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/experimental/index.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/experimental/index.js create mode 100644 node_modules/@opentelemetry/api/build/src/experimental/index.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredOptions.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredOptions.js create mode 100644 node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredOptions.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredTracer.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredTracer.js create mode 100644 node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredTracer.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/index.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/index.js create mode 100644 node_modules/@opentelemetry/api/build/src/index.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/internal/global-utils.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/internal/global-utils.js create mode 100644 node_modules/@opentelemetry/api/build/src/internal/global-utils.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/internal/semver.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/internal/semver.js create mode 100644 node_modules/@opentelemetry/api/build/src/internal/semver.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/metrics-api.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/metrics-api.js create mode 100644 node_modules/@opentelemetry/api/build/src/metrics-api.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/metrics/Meter.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/metrics/Meter.js create mode 100644 node_modules/@opentelemetry/api/build/src/metrics/Meter.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/metrics/MeterProvider.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/metrics/MeterProvider.js create mode 100644 node_modules/@opentelemetry/api/build/src/metrics/MeterProvider.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/metrics/Metric.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/metrics/Metric.js create mode 100644 node_modules/@opentelemetry/api/build/src/metrics/Metric.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js create mode 100644 node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js create mode 100644 node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/metrics/ObservableResult.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/metrics/ObservableResult.js create mode 100644 node_modules/@opentelemetry/api/build/src/metrics/ObservableResult.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/platform/browser/globalThis.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/platform/browser/globalThis.js create mode 100644 node_modules/@opentelemetry/api/build/src/platform/browser/globalThis.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/platform/browser/index.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/platform/browser/index.js create mode 100644 node_modules/@opentelemetry/api/build/src/platform/browser/index.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/platform/index.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/platform/index.js create mode 100644 node_modules/@opentelemetry/api/build/src/platform/index.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/platform/node/globalThis.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/platform/node/globalThis.js create mode 100644 node_modules/@opentelemetry/api/build/src/platform/node/globalThis.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/platform/node/index.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/platform/node/index.js create mode 100644 node_modules/@opentelemetry/api/build/src/platform/node/index.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/propagation-api.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/propagation-api.js create mode 100644 node_modules/@opentelemetry/api/build/src/propagation-api.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js create mode 100644 node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js create mode 100644 node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace-api.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace-api.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace-api.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/NoopTracer.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/Sampler.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/Sampler.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/Sampler.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/SamplingResult.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/SpanOptions.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/SpanOptions.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/SpanOptions.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/attributes.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/attributes.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/attributes.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/context-utils.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/context-utils.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/context-utils.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/internal/utils.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/internal/utils.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/internal/utils.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/link.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/link.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/link.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/span.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/span.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/span.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/span_context.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/span_context.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/span_context.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/span_kind.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/span_kind.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/span_kind.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/status.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/status.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/status.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/trace_flags.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/trace_flags.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/trace_flags.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/trace_state.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/trace_state.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/trace_state.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/tracer.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/tracer.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/tracer.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/tracer_options.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/tracer_options.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/tracer_options.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/trace/tracer_provider.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/trace/tracer_provider.js create mode 100644 node_modules/@opentelemetry/api/build/src/trace/tracer_provider.js.map create mode 100644 node_modules/@opentelemetry/api/build/src/version.d.ts create mode 100644 node_modules/@opentelemetry/api/build/src/version.js create mode 100644 node_modules/@opentelemetry/api/build/src/version.js.map create mode 100644 node_modules/@opentelemetry/api/package.json create mode 100644 node_modules/@protobufjs/aspromise/LICENSE create mode 100644 node_modules/@protobufjs/aspromise/README.md create mode 100644 node_modules/@protobufjs/aspromise/index.d.ts create mode 100644 node_modules/@protobufjs/aspromise/index.js create mode 100644 node_modules/@protobufjs/aspromise/package.json create mode 100644 node_modules/@protobufjs/aspromise/tests/index.js create mode 100644 node_modules/@protobufjs/base64/LICENSE create mode 100644 node_modules/@protobufjs/base64/README.md create mode 100644 node_modules/@protobufjs/base64/index.d.ts create mode 100644 node_modules/@protobufjs/base64/index.js create mode 100644 node_modules/@protobufjs/base64/package.json create mode 100644 node_modules/@protobufjs/base64/tests/index.js create mode 100644 node_modules/@protobufjs/codegen/LICENSE create mode 100644 node_modules/@protobufjs/codegen/README.md create mode 100644 node_modules/@protobufjs/codegen/index.d.ts create mode 100644 node_modules/@protobufjs/codegen/index.js create mode 100644 node_modules/@protobufjs/codegen/package.json create mode 100644 node_modules/@protobufjs/codegen/tests/index.js create mode 100644 node_modules/@protobufjs/eventemitter/LICENSE create mode 100644 node_modules/@protobufjs/eventemitter/README.md create mode 100644 node_modules/@protobufjs/eventemitter/index.d.ts create mode 100644 node_modules/@protobufjs/eventemitter/index.js create mode 100644 node_modules/@protobufjs/eventemitter/package.json create mode 100644 node_modules/@protobufjs/eventemitter/tests/index.js create mode 100644 node_modules/@protobufjs/fetch/LICENSE create mode 100644 node_modules/@protobufjs/fetch/README.md create mode 100644 node_modules/@protobufjs/fetch/index.d.ts create mode 100644 node_modules/@protobufjs/fetch/index.js create mode 100644 node_modules/@protobufjs/fetch/package.json create mode 100644 node_modules/@protobufjs/fetch/tests/index.js create mode 100644 node_modules/@protobufjs/float/LICENSE create mode 100644 node_modules/@protobufjs/float/README.md create mode 100644 node_modules/@protobufjs/float/bench/index.js create mode 100644 node_modules/@protobufjs/float/bench/suite.js create mode 100644 node_modules/@protobufjs/float/index.d.ts create mode 100644 node_modules/@protobufjs/float/index.js create mode 100644 node_modules/@protobufjs/float/package.json create mode 100644 node_modules/@protobufjs/float/tests/index.js create mode 100644 node_modules/@protobufjs/inquire/.npmignore create mode 100644 node_modules/@protobufjs/inquire/LICENSE create mode 100644 node_modules/@protobufjs/inquire/README.md create mode 100644 node_modules/@protobufjs/inquire/index.d.ts create mode 100644 node_modules/@protobufjs/inquire/index.js create mode 100644 node_modules/@protobufjs/inquire/package.json create mode 100644 node_modules/@protobufjs/inquire/tests/data/array.js create mode 100644 node_modules/@protobufjs/inquire/tests/data/emptyArray.js create mode 100644 node_modules/@protobufjs/inquire/tests/data/emptyObject.js create mode 100644 node_modules/@protobufjs/inquire/tests/data/object.js create mode 100644 node_modules/@protobufjs/inquire/tests/index.js create mode 100644 node_modules/@protobufjs/path/LICENSE create mode 100644 node_modules/@protobufjs/path/README.md create mode 100644 node_modules/@protobufjs/path/index.d.ts create mode 100644 node_modules/@protobufjs/path/index.js create mode 100644 node_modules/@protobufjs/path/package.json create mode 100644 node_modules/@protobufjs/path/tests/index.js create mode 100644 node_modules/@protobufjs/pool/.npmignore create mode 100644 node_modules/@protobufjs/pool/LICENSE create mode 100644 node_modules/@protobufjs/pool/README.md create mode 100644 node_modules/@protobufjs/pool/index.d.ts create mode 100644 node_modules/@protobufjs/pool/index.js create mode 100644 node_modules/@protobufjs/pool/package.json create mode 100644 node_modules/@protobufjs/pool/tests/index.js create mode 100644 node_modules/@protobufjs/utf8/.npmignore create mode 100644 node_modules/@protobufjs/utf8/LICENSE create mode 100644 node_modules/@protobufjs/utf8/README.md create mode 100644 node_modules/@protobufjs/utf8/index.d.ts create mode 100644 node_modules/@protobufjs/utf8/index.js create mode 100644 node_modules/@protobufjs/utf8/package.json create mode 100644 node_modules/@protobufjs/utf8/tests/data/utf8.txt create mode 100644 node_modules/@protobufjs/utf8/tests/index.js create mode 100644 node_modules/@tootallnate/once/LICENSE create mode 100644 node_modules/@tootallnate/once/README.md create mode 100644 node_modules/@tootallnate/once/dist/index.d.ts create mode 100644 node_modules/@tootallnate/once/dist/index.js create mode 100644 node_modules/@tootallnate/once/dist/index.js.map create mode 100644 node_modules/@tootallnate/once/dist/overloaded-parameters.d.ts create mode 100644 node_modules/@tootallnate/once/dist/overloaded-parameters.js create mode 100644 node_modules/@tootallnate/once/dist/overloaded-parameters.js.map create mode 100644 node_modules/@tootallnate/once/dist/types.d.ts create mode 100644 node_modules/@tootallnate/once/dist/types.js create mode 100644 node_modules/@tootallnate/once/dist/types.js.map create mode 100644 node_modules/@tootallnate/once/package.json create mode 100644 node_modules/@types/body-parser/LICENSE create mode 100644 node_modules/@types/body-parser/README.md create mode 100644 node_modules/@types/body-parser/index.d.ts create mode 100644 node_modules/@types/body-parser/package.json create mode 100644 node_modules/@types/caseless/LICENSE create mode 100644 node_modules/@types/caseless/README.md create mode 100644 node_modules/@types/caseless/index.d.ts create mode 100644 node_modules/@types/caseless/package.json create mode 100644 node_modules/@types/connect/LICENSE create mode 100644 node_modules/@types/connect/README.md create mode 100644 node_modules/@types/connect/index.d.ts create mode 100644 node_modules/@types/connect/package.json create mode 100644 node_modules/@types/express-serve-static-core/LICENSE create mode 100644 node_modules/@types/express-serve-static-core/README.md create mode 100644 node_modules/@types/express-serve-static-core/index.d.ts create mode 100644 node_modules/@types/express-serve-static-core/package.json create mode 100644 node_modules/@types/express/LICENSE create mode 100644 node_modules/@types/express/README.md create mode 100644 node_modules/@types/express/index.d.ts create mode 100644 node_modules/@types/express/package.json create mode 100644 node_modules/@types/http-errors/LICENSE create mode 100644 node_modules/@types/http-errors/README.md create mode 100644 node_modules/@types/http-errors/index.d.ts create mode 100644 node_modules/@types/http-errors/package.json create mode 100644 node_modules/@types/jsonwebtoken/LICENSE create mode 100644 node_modules/@types/jsonwebtoken/README.md create mode 100644 node_modules/@types/jsonwebtoken/index.d.ts create mode 100644 node_modules/@types/jsonwebtoken/package.json create mode 100644 node_modules/@types/long/LICENSE create mode 100644 node_modules/@types/long/README.md create mode 100644 node_modules/@types/long/index.d.ts create mode 100644 node_modules/@types/long/package.json create mode 100644 node_modules/@types/mime/LICENSE create mode 100644 node_modules/@types/mime/Mime.d.ts create mode 100644 node_modules/@types/mime/README.md create mode 100644 node_modules/@types/mime/index.d.ts create mode 100644 node_modules/@types/mime/lite.d.ts create mode 100644 node_modules/@types/mime/package.json create mode 100644 node_modules/@types/ms/LICENSE create mode 100644 node_modules/@types/ms/README.md create mode 100644 node_modules/@types/ms/index.d.ts create mode 100644 node_modules/@types/ms/package.json create mode 100644 node_modules/@types/node/LICENSE create mode 100644 node_modules/@types/node/README.md create mode 100644 node_modules/@types/node/assert.d.ts create mode 100644 node_modules/@types/node/assert/strict.d.ts create mode 100644 node_modules/@types/node/async_hooks.d.ts create mode 100644 node_modules/@types/node/buffer.buffer.d.ts create mode 100644 node_modules/@types/node/buffer.d.ts create mode 100644 node_modules/@types/node/child_process.d.ts create mode 100644 node_modules/@types/node/cluster.d.ts create mode 100644 node_modules/@types/node/compatibility/disposable.d.ts create mode 100644 node_modules/@types/node/compatibility/index.d.ts create mode 100644 node_modules/@types/node/compatibility/indexable.d.ts create mode 100644 node_modules/@types/node/compatibility/iterators.d.ts create mode 100644 node_modules/@types/node/console.d.ts create mode 100644 node_modules/@types/node/constants.d.ts create mode 100644 node_modules/@types/node/crypto.d.ts create mode 100644 node_modules/@types/node/dgram.d.ts create mode 100644 node_modules/@types/node/diagnostics_channel.d.ts create mode 100644 node_modules/@types/node/dns.d.ts create mode 100644 node_modules/@types/node/dns/promises.d.ts create mode 100644 node_modules/@types/node/domain.d.ts create mode 100644 node_modules/@types/node/events.d.ts create mode 100644 node_modules/@types/node/fs.d.ts create mode 100644 node_modules/@types/node/fs/promises.d.ts create mode 100644 node_modules/@types/node/globals.d.ts create mode 100644 node_modules/@types/node/globals.typedarray.d.ts create mode 100644 node_modules/@types/node/http.d.ts create mode 100644 node_modules/@types/node/http2.d.ts create mode 100644 node_modules/@types/node/https.d.ts create mode 100644 node_modules/@types/node/index.d.ts create mode 100644 node_modules/@types/node/inspector.d.ts create mode 100644 node_modules/@types/node/inspector.generated.d.ts create mode 100644 node_modules/@types/node/module.d.ts create mode 100644 node_modules/@types/node/net.d.ts create mode 100644 node_modules/@types/node/os.d.ts create mode 100644 node_modules/@types/node/package.json create mode 100644 node_modules/@types/node/path.d.ts create mode 100644 node_modules/@types/node/perf_hooks.d.ts create mode 100644 node_modules/@types/node/process.d.ts create mode 100644 node_modules/@types/node/punycode.d.ts create mode 100644 node_modules/@types/node/querystring.d.ts create mode 100644 node_modules/@types/node/readline.d.ts create mode 100644 node_modules/@types/node/readline/promises.d.ts create mode 100644 node_modules/@types/node/repl.d.ts create mode 100644 node_modules/@types/node/sea.d.ts create mode 100644 node_modules/@types/node/sqlite.d.ts create mode 100644 node_modules/@types/node/stream.d.ts create mode 100644 node_modules/@types/node/stream/consumers.d.ts create mode 100644 node_modules/@types/node/stream/promises.d.ts create mode 100644 node_modules/@types/node/stream/web.d.ts create mode 100644 node_modules/@types/node/string_decoder.d.ts create mode 100644 node_modules/@types/node/test.d.ts create mode 100644 node_modules/@types/node/timers.d.ts create mode 100644 node_modules/@types/node/timers/promises.d.ts create mode 100644 node_modules/@types/node/tls.d.ts create mode 100644 node_modules/@types/node/trace_events.d.ts create mode 100644 node_modules/@types/node/ts5.6/buffer.buffer.d.ts create mode 100644 node_modules/@types/node/ts5.6/globals.typedarray.d.ts create mode 100644 node_modules/@types/node/ts5.6/index.d.ts create mode 100644 node_modules/@types/node/tty.d.ts create mode 100644 node_modules/@types/node/url.d.ts create mode 100644 node_modules/@types/node/util.d.ts create mode 100644 node_modules/@types/node/v8.d.ts create mode 100644 node_modules/@types/node/vm.d.ts create mode 100644 node_modules/@types/node/wasi.d.ts create mode 100644 node_modules/@types/node/web-globals/abortcontroller.d.ts create mode 100644 node_modules/@types/node/web-globals/domexception.d.ts create mode 100644 node_modules/@types/node/web-globals/events.d.ts create mode 100644 node_modules/@types/node/web-globals/fetch.d.ts create mode 100644 node_modules/@types/node/web-globals/navigator.d.ts create mode 100644 node_modules/@types/node/web-globals/storage.d.ts create mode 100644 node_modules/@types/node/worker_threads.d.ts create mode 100644 node_modules/@types/node/zlib.d.ts create mode 100644 node_modules/@types/qs/LICENSE create mode 100644 node_modules/@types/qs/README.md create mode 100644 node_modules/@types/qs/index.d.ts create mode 100644 node_modules/@types/qs/package.json create mode 100644 node_modules/@types/range-parser/LICENSE create mode 100644 node_modules/@types/range-parser/README.md create mode 100644 node_modules/@types/range-parser/index.d.ts create mode 100644 node_modules/@types/range-parser/package.json create mode 100644 node_modules/@types/request/LICENSE create mode 100644 node_modules/@types/request/README.md create mode 100644 node_modules/@types/request/index.d.ts create mode 100644 node_modules/@types/request/package.json create mode 100644 node_modules/@types/send/LICENSE create mode 100644 node_modules/@types/send/README.md create mode 100644 node_modules/@types/send/index.d.ts create mode 100644 node_modules/@types/send/package.json create mode 100644 node_modules/@types/serve-static/LICENSE create mode 100644 node_modules/@types/serve-static/README.md create mode 100644 node_modules/@types/serve-static/index.d.ts create mode 100644 node_modules/@types/serve-static/node_modules/@types/send/LICENSE create mode 100644 node_modules/@types/serve-static/node_modules/@types/send/README.md create mode 100644 node_modules/@types/serve-static/node_modules/@types/send/index.d.ts create mode 100644 node_modules/@types/serve-static/node_modules/@types/send/package.json create mode 100644 node_modules/@types/serve-static/package.json create mode 100644 node_modules/@types/tough-cookie/LICENSE create mode 100644 node_modules/@types/tough-cookie/README.md create mode 100644 node_modules/@types/tough-cookie/index.d.ts create mode 100644 node_modules/@types/tough-cookie/package.json create mode 100644 node_modules/abort-controller/LICENSE create mode 100644 node_modules/abort-controller/README.md create mode 100644 node_modules/abort-controller/browser.js create mode 100644 node_modules/abort-controller/browser.mjs create mode 100644 node_modules/abort-controller/dist/abort-controller.d.ts create mode 100644 node_modules/abort-controller/dist/abort-controller.js create mode 100644 node_modules/abort-controller/dist/abort-controller.js.map create mode 100644 node_modules/abort-controller/dist/abort-controller.mjs create mode 100644 node_modules/abort-controller/dist/abort-controller.mjs.map create mode 100644 node_modules/abort-controller/dist/abort-controller.umd.js create mode 100644 node_modules/abort-controller/dist/abort-controller.umd.js.map create mode 100644 node_modules/abort-controller/package.json create mode 100644 node_modules/abort-controller/polyfill.js create mode 100644 node_modules/abort-controller/polyfill.mjs create mode 100644 node_modules/agent-base/LICENSE create mode 100644 node_modules/agent-base/README.md create mode 100644 node_modules/agent-base/dist/helpers.d.ts create mode 100644 node_modules/agent-base/dist/helpers.d.ts.map create mode 100644 node_modules/agent-base/dist/helpers.js create mode 100644 node_modules/agent-base/dist/helpers.js.map create mode 100644 node_modules/agent-base/dist/index.d.ts create mode 100644 node_modules/agent-base/dist/index.d.ts.map create mode 100644 node_modules/agent-base/dist/index.js create mode 100644 node_modules/agent-base/dist/index.js.map create mode 100644 node_modules/agent-base/package.json create mode 100644 node_modules/ansi-regex/index.d.ts create mode 100644 node_modules/ansi-regex/index.js create mode 100644 node_modules/ansi-regex/license create mode 100644 node_modules/ansi-regex/package.json create mode 100644 node_modules/ansi-regex/readme.md create mode 100644 node_modules/ansi-styles/index.d.ts create mode 100644 node_modules/ansi-styles/index.js create mode 100644 node_modules/ansi-styles/license create mode 100644 node_modules/ansi-styles/package.json create mode 100644 node_modules/ansi-styles/readme.md create mode 100644 node_modules/arrify/index.d.ts create mode 100644 node_modules/arrify/index.js create mode 100644 node_modules/arrify/license create mode 100644 node_modules/arrify/package.json create mode 100644 node_modules/arrify/readme.md create mode 100644 node_modules/async-retry/LICENSE.md create mode 100644 node_modules/async-retry/README.md create mode 100644 node_modules/async-retry/lib/index.js create mode 100644 node_modules/async-retry/package.json create mode 100644 node_modules/asynckit/LICENSE create mode 100644 node_modules/asynckit/README.md create mode 100644 node_modules/asynckit/bench.js create mode 100644 node_modules/asynckit/index.js create mode 100644 node_modules/asynckit/lib/abort.js create mode 100644 node_modules/asynckit/lib/async.js create mode 100644 node_modules/asynckit/lib/defer.js create mode 100644 node_modules/asynckit/lib/iterate.js create mode 100644 node_modules/asynckit/lib/readable_asynckit.js create mode 100644 node_modules/asynckit/lib/readable_parallel.js create mode 100644 node_modules/asynckit/lib/readable_serial.js create mode 100644 node_modules/asynckit/lib/readable_serial_ordered.js create mode 100644 node_modules/asynckit/lib/state.js create mode 100644 node_modules/asynckit/lib/streamify.js create mode 100644 node_modules/asynckit/lib/terminator.js create mode 100644 node_modules/asynckit/package.json create mode 100644 node_modules/asynckit/parallel.js create mode 100644 node_modules/asynckit/serial.js create mode 100644 node_modules/asynckit/serialOrdered.js create mode 100644 node_modules/asynckit/stream.js create mode 100644 node_modules/base64-js/LICENSE create mode 100644 node_modules/base64-js/README.md create mode 100644 node_modules/base64-js/base64js.min.js create mode 100644 node_modules/base64-js/index.d.ts create mode 100644 node_modules/base64-js/index.js create mode 100644 node_modules/base64-js/package.json create mode 100644 node_modules/bignumber.js/CHANGELOG.md create mode 100644 node_modules/bignumber.js/LICENCE.md create mode 100644 node_modules/bignumber.js/README.md create mode 100644 node_modules/bignumber.js/bignumber.d.mts create mode 100644 node_modules/bignumber.js/bignumber.d.ts create mode 100644 node_modules/bignumber.js/bignumber.js create mode 100644 node_modules/bignumber.js/bignumber.mjs create mode 100644 node_modules/bignumber.js/doc/API.html create mode 100644 node_modules/bignumber.js/package.json create mode 100644 node_modules/bignumber.js/types.d.ts create mode 100644 node_modules/buffer-equal-constant-time/.npmignore create mode 100644 node_modules/buffer-equal-constant-time/.travis.yml create mode 100644 node_modules/buffer-equal-constant-time/LICENSE.txt create mode 100644 node_modules/buffer-equal-constant-time/README.md create mode 100644 node_modules/buffer-equal-constant-time/index.js create mode 100644 node_modules/buffer-equal-constant-time/package.json create mode 100644 node_modules/buffer-equal-constant-time/test.js create mode 100644 node_modules/call-bind-apply-helpers/.eslintrc create mode 100644 node_modules/call-bind-apply-helpers/.github/FUNDING.yml create mode 100644 node_modules/call-bind-apply-helpers/.nycrc create mode 100644 node_modules/call-bind-apply-helpers/CHANGELOG.md create mode 100644 node_modules/call-bind-apply-helpers/LICENSE create mode 100644 node_modules/call-bind-apply-helpers/README.md create mode 100644 node_modules/call-bind-apply-helpers/actualApply.d.ts create mode 100644 node_modules/call-bind-apply-helpers/actualApply.js create mode 100644 node_modules/call-bind-apply-helpers/applyBind.d.ts create mode 100644 node_modules/call-bind-apply-helpers/applyBind.js create mode 100644 node_modules/call-bind-apply-helpers/functionApply.d.ts create mode 100644 node_modules/call-bind-apply-helpers/functionApply.js create mode 100644 node_modules/call-bind-apply-helpers/functionCall.d.ts create mode 100644 node_modules/call-bind-apply-helpers/functionCall.js create mode 100644 node_modules/call-bind-apply-helpers/index.d.ts create mode 100644 node_modules/call-bind-apply-helpers/index.js create mode 100644 node_modules/call-bind-apply-helpers/package.json create mode 100644 node_modules/call-bind-apply-helpers/reflectApply.d.ts create mode 100644 node_modules/call-bind-apply-helpers/reflectApply.js create mode 100644 node_modules/call-bind-apply-helpers/test/index.js create mode 100644 node_modules/call-bind-apply-helpers/tsconfig.json create mode 100644 node_modules/cliui/CHANGELOG.md create mode 100644 node_modules/cliui/LICENSE.txt create mode 100644 node_modules/cliui/README.md create mode 100644 node_modules/cliui/build/index.cjs create mode 100644 node_modules/cliui/build/index.d.cts create mode 100644 node_modules/cliui/build/lib/index.js create mode 100644 node_modules/cliui/build/lib/string-utils.js create mode 100644 node_modules/cliui/index.mjs create mode 100644 node_modules/cliui/package.json create mode 100644 node_modules/color-convert/CHANGELOG.md create mode 100644 node_modules/color-convert/LICENSE create mode 100644 node_modules/color-convert/README.md create mode 100644 node_modules/color-convert/conversions.js create mode 100644 node_modules/color-convert/index.js create mode 100644 node_modules/color-convert/package.json create mode 100644 node_modules/color-convert/route.js create mode 100644 node_modules/color-name/LICENSE create mode 100644 node_modules/color-name/README.md create mode 100644 node_modules/color-name/index.js create mode 100644 node_modules/color-name/package.json create mode 100644 node_modules/combined-stream/License create mode 100644 node_modules/combined-stream/Readme.md create mode 100644 node_modules/combined-stream/lib/combined_stream.js create mode 100644 node_modules/combined-stream/package.json create mode 100644 node_modules/combined-stream/yarn.lock create mode 100644 node_modules/debug/LICENSE create mode 100644 node_modules/debug/README.md create mode 100644 node_modules/debug/package.json create mode 100644 node_modules/debug/src/browser.js create mode 100644 node_modules/debug/src/common.js create mode 100644 node_modules/debug/src/index.js create mode 100644 node_modules/debug/src/node.js create mode 100644 node_modules/delayed-stream/.npmignore create mode 100644 node_modules/delayed-stream/License create mode 100644 node_modules/delayed-stream/Makefile create mode 100644 node_modules/delayed-stream/Readme.md create mode 100644 node_modules/delayed-stream/lib/delayed_stream.js create mode 100644 node_modules/delayed-stream/package.json create mode 100644 node_modules/dunder-proto/.eslintrc create mode 100644 node_modules/dunder-proto/.github/FUNDING.yml create mode 100644 node_modules/dunder-proto/.nycrc create mode 100644 node_modules/dunder-proto/CHANGELOG.md create mode 100644 node_modules/dunder-proto/LICENSE create mode 100644 node_modules/dunder-proto/README.md create mode 100644 node_modules/dunder-proto/get.d.ts create mode 100644 node_modules/dunder-proto/get.js create mode 100644 node_modules/dunder-proto/package.json create mode 100644 node_modules/dunder-proto/set.d.ts create mode 100644 node_modules/dunder-proto/set.js create mode 100644 node_modules/dunder-proto/test/get.js create mode 100644 node_modules/dunder-proto/test/index.js create mode 100644 node_modules/dunder-proto/test/set.js create mode 100644 node_modules/dunder-proto/tsconfig.json create mode 100644 node_modules/duplexify/.travis.yml create mode 100644 node_modules/duplexify/LICENSE create mode 100644 node_modules/duplexify/README.md create mode 100644 node_modules/duplexify/example.js create mode 100644 node_modules/duplexify/index.js create mode 100644 node_modules/duplexify/package.json create mode 100644 node_modules/duplexify/test.js create mode 100644 node_modules/ecdsa-sig-formatter/CODEOWNERS create mode 100644 node_modules/ecdsa-sig-formatter/LICENSE create mode 100644 node_modules/ecdsa-sig-formatter/README.md create mode 100644 node_modules/ecdsa-sig-formatter/package.json create mode 100644 node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.d.ts create mode 100644 node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js create mode 100644 node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js create mode 100644 node_modules/emoji-regex/LICENSE-MIT.txt create mode 100644 node_modules/emoji-regex/README.md create mode 100644 node_modules/emoji-regex/es2015/index.js create mode 100644 node_modules/emoji-regex/es2015/text.js create mode 100644 node_modules/emoji-regex/index.d.ts create mode 100644 node_modules/emoji-regex/index.js create mode 100644 node_modules/emoji-regex/package.json create mode 100644 node_modules/emoji-regex/text.js create mode 100644 node_modules/end-of-stream/LICENSE create mode 100644 node_modules/end-of-stream/README.md create mode 100644 node_modules/end-of-stream/index.js create mode 100644 node_modules/end-of-stream/package.json create mode 100644 node_modules/es-define-property/.eslintrc create mode 100644 node_modules/es-define-property/.github/FUNDING.yml create mode 100644 node_modules/es-define-property/.nycrc create mode 100644 node_modules/es-define-property/CHANGELOG.md create mode 100644 node_modules/es-define-property/LICENSE create mode 100644 node_modules/es-define-property/README.md create mode 100644 node_modules/es-define-property/index.d.ts create mode 100644 node_modules/es-define-property/index.js create mode 100644 node_modules/es-define-property/package.json create mode 100644 node_modules/es-define-property/test/index.js create mode 100644 node_modules/es-define-property/tsconfig.json create mode 100644 node_modules/es-errors/.eslintrc create mode 100644 node_modules/es-errors/.github/FUNDING.yml create mode 100644 node_modules/es-errors/CHANGELOG.md create mode 100644 node_modules/es-errors/LICENSE create mode 100644 node_modules/es-errors/README.md create mode 100644 node_modules/es-errors/eval.d.ts create mode 100644 node_modules/es-errors/eval.js create mode 100644 node_modules/es-errors/index.d.ts create mode 100644 node_modules/es-errors/index.js create mode 100644 node_modules/es-errors/package.json create mode 100644 node_modules/es-errors/range.d.ts create mode 100644 node_modules/es-errors/range.js create mode 100644 node_modules/es-errors/ref.d.ts create mode 100644 node_modules/es-errors/ref.js create mode 100644 node_modules/es-errors/syntax.d.ts create mode 100644 node_modules/es-errors/syntax.js create mode 100644 node_modules/es-errors/test/index.js create mode 100644 node_modules/es-errors/tsconfig.json create mode 100644 node_modules/es-errors/type.d.ts create mode 100644 node_modules/es-errors/type.js create mode 100644 node_modules/es-errors/uri.d.ts create mode 100644 node_modules/es-errors/uri.js create mode 100644 node_modules/es-object-atoms/.eslintrc create mode 100644 node_modules/es-object-atoms/.github/FUNDING.yml create mode 100644 node_modules/es-object-atoms/CHANGELOG.md create mode 100644 node_modules/es-object-atoms/LICENSE create mode 100644 node_modules/es-object-atoms/README.md create mode 100644 node_modules/es-object-atoms/RequireObjectCoercible.d.ts create mode 100644 node_modules/es-object-atoms/RequireObjectCoercible.js create mode 100644 node_modules/es-object-atoms/ToObject.d.ts create mode 100644 node_modules/es-object-atoms/ToObject.js create mode 100644 node_modules/es-object-atoms/index.d.ts create mode 100644 node_modules/es-object-atoms/index.js create mode 100644 node_modules/es-object-atoms/isObject.d.ts create mode 100644 node_modules/es-object-atoms/isObject.js create mode 100644 node_modules/es-object-atoms/package.json create mode 100644 node_modules/es-object-atoms/test/index.js create mode 100644 node_modules/es-object-atoms/tsconfig.json create mode 100644 node_modules/es-set-tostringtag/.eslintrc create mode 100644 node_modules/es-set-tostringtag/.nycrc create mode 100644 node_modules/es-set-tostringtag/CHANGELOG.md create mode 100644 node_modules/es-set-tostringtag/LICENSE create mode 100644 node_modules/es-set-tostringtag/README.md create mode 100644 node_modules/es-set-tostringtag/index.d.ts create mode 100644 node_modules/es-set-tostringtag/index.js create mode 100644 node_modules/es-set-tostringtag/package.json create mode 100644 node_modules/es-set-tostringtag/test/index.js create mode 100644 node_modules/es-set-tostringtag/tsconfig.json create mode 100644 node_modules/escalade/dist/index.js create mode 100644 node_modules/escalade/dist/index.mjs create mode 100644 node_modules/escalade/index.d.mts create mode 100644 node_modules/escalade/index.d.ts create mode 100644 node_modules/escalade/license create mode 100644 node_modules/escalade/package.json create mode 100644 node_modules/escalade/readme.md create mode 100644 node_modules/escalade/sync/index.d.mts create mode 100644 node_modules/escalade/sync/index.d.ts create mode 100644 node_modules/escalade/sync/index.js create mode 100644 node_modules/escalade/sync/index.mjs create mode 100644 node_modules/event-target-shim/LICENSE create mode 100644 node_modules/event-target-shim/README.md create mode 100644 node_modules/event-target-shim/dist/event-target-shim.js create mode 100644 node_modules/event-target-shim/dist/event-target-shim.js.map create mode 100644 node_modules/event-target-shim/dist/event-target-shim.mjs create mode 100644 node_modules/event-target-shim/dist/event-target-shim.mjs.map create mode 100644 node_modules/event-target-shim/dist/event-target-shim.umd.js create mode 100644 node_modules/event-target-shim/dist/event-target-shim.umd.js.map create mode 100644 node_modules/event-target-shim/index.d.ts create mode 100644 node_modules/event-target-shim/package.json create mode 100644 node_modules/extend/.editorconfig create mode 100644 node_modules/extend/.eslintrc create mode 100644 node_modules/extend/.jscs.json create mode 100644 node_modules/extend/.travis.yml create mode 100644 node_modules/extend/CHANGELOG.md create mode 100644 node_modules/extend/LICENSE create mode 100644 node_modules/extend/README.md create mode 100644 node_modules/extend/component.json create mode 100644 node_modules/extend/index.js create mode 100644 node_modules/extend/package.json create mode 100644 node_modules/farmhash-modern/LICENSE create mode 100644 node_modules/farmhash-modern/README.md create mode 100644 node_modules/farmhash-modern/bin/bundler/farmhash_modern.js create mode 100644 node_modules/farmhash-modern/bin/bundler/farmhash_modern_bg.js create mode 100644 node_modules/farmhash-modern/bin/bundler/farmhash_modern_bg.wasm create mode 100644 node_modules/farmhash-modern/bin/nodejs/farmhash_modern.js create mode 100644 node_modules/farmhash-modern/bin/nodejs/farmhash_modern_bg.wasm create mode 100644 node_modules/farmhash-modern/lib/.tsbuildinfo create mode 100644 node_modules/farmhash-modern/lib/browser.d.ts create mode 100644 node_modules/farmhash-modern/lib/browser.js create mode 100644 node_modules/farmhash-modern/lib/index.cjs create mode 100644 node_modules/farmhash-modern/lib/index.d.cts create mode 100644 node_modules/farmhash-modern/lib/index.d.mts create mode 100644 node_modules/farmhash-modern/lib/index.d.ts create mode 100644 node_modules/farmhash-modern/lib/index.js create mode 100644 node_modules/farmhash-modern/lib/index.mjs create mode 100644 node_modules/farmhash-modern/package.json create mode 100644 node_modules/fast-deep-equal/LICENSE create mode 100644 node_modules/fast-deep-equal/README.md create mode 100644 node_modules/fast-deep-equal/es6/index.d.ts create mode 100644 node_modules/fast-deep-equal/es6/index.js create mode 100644 node_modules/fast-deep-equal/es6/react.d.ts create mode 100644 node_modules/fast-deep-equal/es6/react.js create mode 100644 node_modules/fast-deep-equal/index.d.ts create mode 100644 node_modules/fast-deep-equal/index.js create mode 100644 node_modules/fast-deep-equal/package.json create mode 100644 node_modules/fast-deep-equal/react.d.ts create mode 100644 node_modules/fast-deep-equal/react.js create mode 100644 node_modules/fast-xml-parser/CHANGELOG.md create mode 100644 node_modules/fast-xml-parser/LICENSE create mode 100644 node_modules/fast-xml-parser/README.md create mode 100644 node_modules/fast-xml-parser/package.json create mode 100644 node_modules/fast-xml-parser/src/cli/cli.js create mode 100644 node_modules/fast-xml-parser/src/cli/man.js create mode 100644 node_modules/fast-xml-parser/src/cli/read.js create mode 100644 node_modules/fast-xml-parser/src/fxp.d.ts create mode 100644 node_modules/fast-xml-parser/src/fxp.js create mode 100644 node_modules/fast-xml-parser/src/ignoreAttributes.js create mode 100644 node_modules/fast-xml-parser/src/util.js create mode 100644 node_modules/fast-xml-parser/src/v5/CharsSymbol.js create mode 100644 node_modules/fast-xml-parser/src/v5/EntitiesParser.js create mode 100644 node_modules/fast-xml-parser/src/v5/OptionsBuilder.js create mode 100644 node_modules/fast-xml-parser/src/v5/OutputBuilders/BaseOutputBuilder.js create mode 100644 node_modules/fast-xml-parser/src/v5/OutputBuilders/JsArrBuilder.js create mode 100644 node_modules/fast-xml-parser/src/v5/OutputBuilders/JsMinArrBuilder.js create mode 100644 node_modules/fast-xml-parser/src/v5/OutputBuilders/JsObjBuilder.js create mode 100644 node_modules/fast-xml-parser/src/v5/OutputBuilders/ParserOptionsBuilder.js create mode 100644 node_modules/fast-xml-parser/src/v5/Report.js create mode 100644 node_modules/fast-xml-parser/src/v5/TagPath.js create mode 100644 node_modules/fast-xml-parser/src/v5/TagPathMatcher.js create mode 100644 node_modules/fast-xml-parser/src/v5/XMLParser.js create mode 100644 node_modules/fast-xml-parser/src/v5/Xml2JsParser.js create mode 100644 node_modules/fast-xml-parser/src/v5/XmlPartReader.js create mode 100644 node_modules/fast-xml-parser/src/v5/XmlSpecialTagsReader.js create mode 100644 node_modules/fast-xml-parser/src/v5/inputSource/BufferSource.js create mode 100644 node_modules/fast-xml-parser/src/v5/inputSource/StringSource.js create mode 100644 node_modules/fast-xml-parser/src/v5/valueParsers/EntitiesParser.js create mode 100644 node_modules/fast-xml-parser/src/v5/valueParsers/booleanParser.js create mode 100644 node_modules/fast-xml-parser/src/v5/valueParsers/booleanParserExt.js create mode 100644 node_modules/fast-xml-parser/src/v5/valueParsers/currency.js create mode 100644 node_modules/fast-xml-parser/src/v5/valueParsers/join.js create mode 100644 node_modules/fast-xml-parser/src/v5/valueParsers/number.js create mode 100644 node_modules/fast-xml-parser/src/v5/valueParsers/trim.js create mode 100644 node_modules/fast-xml-parser/src/v6/CharsSymbol.js create mode 100644 node_modules/fast-xml-parser/src/v6/EntitiesParser.js create mode 100644 node_modules/fast-xml-parser/src/v6/OptionsBuilder.js create mode 100644 node_modules/fast-xml-parser/src/v6/OutputBuilders/BaseOutputBuilder.js create mode 100644 node_modules/fast-xml-parser/src/v6/OutputBuilders/JsArrBuilder.js create mode 100644 node_modules/fast-xml-parser/src/v6/OutputBuilders/JsMinArrBuilder.js create mode 100644 node_modules/fast-xml-parser/src/v6/OutputBuilders/JsObjBuilder.js create mode 100644 node_modules/fast-xml-parser/src/v6/OutputBuilders/ParserOptionsBuilder.js create mode 100644 node_modules/fast-xml-parser/src/v6/Report.js create mode 100644 node_modules/fast-xml-parser/src/v6/TagPath.js create mode 100644 node_modules/fast-xml-parser/src/v6/TagPathMatcher.js create mode 100644 node_modules/fast-xml-parser/src/v6/XMLParser.js create mode 100644 node_modules/fast-xml-parser/src/v6/Xml2JsParser.js create mode 100644 node_modules/fast-xml-parser/src/v6/XmlPartReader.js create mode 100644 node_modules/fast-xml-parser/src/v6/XmlSpecialTagsReader.js create mode 100644 node_modules/fast-xml-parser/src/v6/inputSource/BufferSource.js create mode 100644 node_modules/fast-xml-parser/src/v6/inputSource/StringSource.js create mode 100644 node_modules/fast-xml-parser/src/v6/valueParsers/EntitiesParser.js create mode 100644 node_modules/fast-xml-parser/src/v6/valueParsers/booleanParser.js create mode 100644 node_modules/fast-xml-parser/src/v6/valueParsers/booleanParserExt.js create mode 100644 node_modules/fast-xml-parser/src/v6/valueParsers/currency.js create mode 100644 node_modules/fast-xml-parser/src/v6/valueParsers/join.js create mode 100644 node_modules/fast-xml-parser/src/v6/valueParsers/number.js create mode 100644 node_modules/fast-xml-parser/src/v6/valueParsers/trim.js create mode 100644 node_modules/fast-xml-parser/src/validator.js create mode 100644 node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js create mode 100644 node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js create mode 100644 node_modules/fast-xml-parser/src/xmlbuilder/prettifyJs2Xml.js create mode 100644 node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js create mode 100644 node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js create mode 100644 node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js create mode 100644 node_modules/fast-xml-parser/src/xmlparser/XMLParser.js create mode 100644 node_modules/fast-xml-parser/src/xmlparser/node2json.js create mode 100644 node_modules/fast-xml-parser/src/xmlparser/xmlNode.js create mode 100644 node_modules/faye-websocket/CHANGELOG.md create mode 100644 node_modules/faye-websocket/LICENSE.md create mode 100644 node_modules/faye-websocket/README.md create mode 100644 node_modules/faye-websocket/lib/faye/eventsource.js create mode 100644 node_modules/faye-websocket/lib/faye/websocket.js create mode 100644 node_modules/faye-websocket/lib/faye/websocket/api.js create mode 100644 node_modules/faye-websocket/lib/faye/websocket/api/event.js create mode 100644 node_modules/faye-websocket/lib/faye/websocket/api/event_target.js create mode 100644 node_modules/faye-websocket/lib/faye/websocket/client.js create mode 100644 node_modules/faye-websocket/package.json create mode 100644 node_modules/firebase-admin/LICENSE create mode 100644 node_modules/firebase-admin/README.md create mode 100644 node_modules/firebase-admin/lib/app-check/app-check-api-client-internal.d.ts create mode 100644 node_modules/firebase-admin/lib/app-check/app-check-api-client-internal.js create mode 100644 node_modules/firebase-admin/lib/app-check/app-check-api.d.ts create mode 100644 node_modules/firebase-admin/lib/app-check/app-check-api.js create mode 100644 node_modules/firebase-admin/lib/app-check/app-check-namespace.d.ts create mode 100644 node_modules/firebase-admin/lib/app-check/app-check-namespace.js create mode 100644 node_modules/firebase-admin/lib/app-check/app-check.d.ts create mode 100644 node_modules/firebase-admin/lib/app-check/app-check.js create mode 100644 node_modules/firebase-admin/lib/app-check/index.d.ts create mode 100644 node_modules/firebase-admin/lib/app-check/index.js create mode 100644 node_modules/firebase-admin/lib/app-check/token-generator.d.ts create mode 100644 node_modules/firebase-admin/lib/app-check/token-generator.js create mode 100644 node_modules/firebase-admin/lib/app-check/token-verifier.d.ts create mode 100644 node_modules/firebase-admin/lib/app-check/token-verifier.js create mode 100644 node_modules/firebase-admin/lib/app/core.d.ts create mode 100644 node_modules/firebase-admin/lib/app/core.js create mode 100644 node_modules/firebase-admin/lib/app/credential-factory.d.ts create mode 100644 node_modules/firebase-admin/lib/app/credential-factory.js create mode 100644 node_modules/firebase-admin/lib/app/credential-internal.d.ts create mode 100644 node_modules/firebase-admin/lib/app/credential-internal.js create mode 100644 node_modules/firebase-admin/lib/app/credential.d.ts create mode 100644 node_modules/firebase-admin/lib/app/credential.js create mode 100644 node_modules/firebase-admin/lib/app/firebase-app.d.ts create mode 100644 node_modules/firebase-admin/lib/app/firebase-app.js create mode 100644 node_modules/firebase-admin/lib/app/firebase-namespace.d.ts create mode 100644 node_modules/firebase-admin/lib/app/firebase-namespace.js create mode 100644 node_modules/firebase-admin/lib/app/index.d.ts create mode 100644 node_modules/firebase-admin/lib/app/index.js create mode 100644 node_modules/firebase-admin/lib/app/lifecycle.d.ts create mode 100644 node_modules/firebase-admin/lib/app/lifecycle.js create mode 100644 node_modules/firebase-admin/lib/auth/action-code-settings-builder.d.ts create mode 100644 node_modules/firebase-admin/lib/auth/action-code-settings-builder.js create mode 100644 node_modules/firebase-admin/lib/auth/auth-api-request.d.ts create mode 100644 node_modules/firebase-admin/lib/auth/auth-api-request.js create mode 100644 node_modules/firebase-admin/lib/auth/auth-config.d.ts create mode 100644 node_modules/firebase-admin/lib/auth/auth-config.js create mode 100644 node_modules/firebase-admin/lib/auth/auth-namespace.d.ts create mode 100644 node_modules/firebase-admin/lib/auth/auth-namespace.js create mode 100644 node_modules/firebase-admin/lib/auth/auth.d.ts create mode 100644 node_modules/firebase-admin/lib/auth/auth.js create mode 100644 node_modules/firebase-admin/lib/auth/base-auth.d.ts create mode 100644 node_modules/firebase-admin/lib/auth/base-auth.js create mode 100644 node_modules/firebase-admin/lib/auth/identifier.d.ts create mode 100644 node_modules/firebase-admin/lib/auth/identifier.js create mode 100644 node_modules/firebase-admin/lib/auth/index.d.ts create mode 100644 node_modules/firebase-admin/lib/auth/index.js create mode 100644 node_modules/firebase-admin/lib/auth/project-config-manager.d.ts create mode 100644 node_modules/firebase-admin/lib/auth/project-config-manager.js create mode 100644 node_modules/firebase-admin/lib/auth/project-config.d.ts create mode 100644 node_modules/firebase-admin/lib/auth/project-config.js create mode 100644 node_modules/firebase-admin/lib/auth/tenant-manager.d.ts create mode 100644 node_modules/firebase-admin/lib/auth/tenant-manager.js create mode 100644 node_modules/firebase-admin/lib/auth/tenant.d.ts create mode 100644 node_modules/firebase-admin/lib/auth/tenant.js create mode 100644 node_modules/firebase-admin/lib/auth/token-generator.d.ts create mode 100644 node_modules/firebase-admin/lib/auth/token-generator.js create mode 100644 node_modules/firebase-admin/lib/auth/token-verifier.d.ts create mode 100644 node_modules/firebase-admin/lib/auth/token-verifier.js create mode 100644 node_modules/firebase-admin/lib/auth/user-import-builder.d.ts create mode 100644 node_modules/firebase-admin/lib/auth/user-import-builder.js create mode 100644 node_modules/firebase-admin/lib/auth/user-record.d.ts create mode 100644 node_modules/firebase-admin/lib/auth/user-record.js create mode 100644 node_modules/firebase-admin/lib/credential/index.d.ts create mode 100644 node_modules/firebase-admin/lib/credential/index.js create mode 100644 node_modules/firebase-admin/lib/data-connect/data-connect-api-client-internal.d.ts create mode 100644 node_modules/firebase-admin/lib/data-connect/data-connect-api-client-internal.js create mode 100644 node_modules/firebase-admin/lib/data-connect/data-connect-api.d.ts create mode 100644 node_modules/firebase-admin/lib/data-connect/data-connect-api.js create mode 100644 node_modules/firebase-admin/lib/data-connect/data-connect.d.ts create mode 100644 node_modules/firebase-admin/lib/data-connect/data-connect.js create mode 100644 node_modules/firebase-admin/lib/data-connect/index.d.ts create mode 100644 node_modules/firebase-admin/lib/data-connect/index.js create mode 100644 node_modules/firebase-admin/lib/data-connect/validate-admin-args.d.ts create mode 100644 node_modules/firebase-admin/lib/data-connect/validate-admin-args.js create mode 100644 node_modules/firebase-admin/lib/database/database-namespace.d.ts create mode 100644 node_modules/firebase-admin/lib/database/database-namespace.js create mode 100644 node_modules/firebase-admin/lib/database/database.d.ts create mode 100644 node_modules/firebase-admin/lib/database/database.js create mode 100644 node_modules/firebase-admin/lib/database/index.d.ts create mode 100644 node_modules/firebase-admin/lib/database/index.js create mode 100644 node_modules/firebase-admin/lib/default-namespace.d.ts create mode 100644 node_modules/firebase-admin/lib/default-namespace.js create mode 100644 node_modules/firebase-admin/lib/esm/app-check/index.js create mode 100644 node_modules/firebase-admin/lib/esm/app/index.js create mode 100644 node_modules/firebase-admin/lib/esm/auth/index.js create mode 100644 node_modules/firebase-admin/lib/esm/data-connect/index.js create mode 100644 node_modules/firebase-admin/lib/esm/database/index.js create mode 100644 node_modules/firebase-admin/lib/esm/eventarc/index.js create mode 100644 node_modules/firebase-admin/lib/esm/extensions/index.js create mode 100644 node_modules/firebase-admin/lib/esm/firestore/index.js create mode 100644 node_modules/firebase-admin/lib/esm/functions/index.js create mode 100644 node_modules/firebase-admin/lib/esm/installations/index.js create mode 100644 node_modules/firebase-admin/lib/esm/instance-id/index.js create mode 100644 node_modules/firebase-admin/lib/esm/machine-learning/index.js create mode 100644 node_modules/firebase-admin/lib/esm/messaging/index.js create mode 100644 node_modules/firebase-admin/lib/esm/package.json create mode 100644 node_modules/firebase-admin/lib/esm/project-management/index.js create mode 100644 node_modules/firebase-admin/lib/esm/remote-config/index.js create mode 100644 node_modules/firebase-admin/lib/esm/security-rules/index.js create mode 100644 node_modules/firebase-admin/lib/esm/storage/index.js create mode 100644 node_modules/firebase-admin/lib/eventarc/cloudevent.d.ts create mode 100644 node_modules/firebase-admin/lib/eventarc/cloudevent.js create mode 100644 node_modules/firebase-admin/lib/eventarc/eventarc-client-internal.d.ts create mode 100644 node_modules/firebase-admin/lib/eventarc/eventarc-client-internal.js create mode 100644 node_modules/firebase-admin/lib/eventarc/eventarc-utils.d.ts create mode 100644 node_modules/firebase-admin/lib/eventarc/eventarc-utils.js create mode 100644 node_modules/firebase-admin/lib/eventarc/eventarc.d.ts create mode 100644 node_modules/firebase-admin/lib/eventarc/eventarc.js create mode 100644 node_modules/firebase-admin/lib/eventarc/index.d.ts create mode 100644 node_modules/firebase-admin/lib/eventarc/index.js create mode 100644 node_modules/firebase-admin/lib/extensions/extensions-api-client-internal.d.ts create mode 100644 node_modules/firebase-admin/lib/extensions/extensions-api-client-internal.js create mode 100644 node_modules/firebase-admin/lib/extensions/extensions-api.d.ts create mode 100644 node_modules/firebase-admin/lib/extensions/extensions-api.js create mode 100644 node_modules/firebase-admin/lib/extensions/extensions.d.ts create mode 100644 node_modules/firebase-admin/lib/extensions/extensions.js create mode 100644 node_modules/firebase-admin/lib/extensions/index.d.ts create mode 100644 node_modules/firebase-admin/lib/extensions/index.js create mode 100644 node_modules/firebase-admin/lib/firebase-namespace-api.d.ts create mode 100644 node_modules/firebase-admin/lib/firebase-namespace-api.js create mode 100644 node_modules/firebase-admin/lib/firestore/firestore-internal.d.ts create mode 100644 node_modules/firebase-admin/lib/firestore/firestore-internal.js create mode 100644 node_modules/firebase-admin/lib/firestore/firestore-namespace.d.ts create mode 100644 node_modules/firebase-admin/lib/firestore/firestore-namespace.js create mode 100644 node_modules/firebase-admin/lib/firestore/index.d.ts create mode 100644 node_modules/firebase-admin/lib/firestore/index.js create mode 100644 node_modules/firebase-admin/lib/functions/functions-api-client-internal.d.ts create mode 100644 node_modules/firebase-admin/lib/functions/functions-api-client-internal.js create mode 100644 node_modules/firebase-admin/lib/functions/functions-api.d.ts create mode 100644 node_modules/firebase-admin/lib/functions/functions-api.js create mode 100644 node_modules/firebase-admin/lib/functions/functions.d.ts create mode 100644 node_modules/firebase-admin/lib/functions/functions.js create mode 100644 node_modules/firebase-admin/lib/functions/index.d.ts create mode 100644 node_modules/firebase-admin/lib/functions/index.js create mode 100644 node_modules/firebase-admin/lib/index.d.ts create mode 100644 node_modules/firebase-admin/lib/index.js create mode 100644 node_modules/firebase-admin/lib/installations/index.d.ts create mode 100644 node_modules/firebase-admin/lib/installations/index.js create mode 100644 node_modules/firebase-admin/lib/installations/installations-namespace.d.ts create mode 100644 node_modules/firebase-admin/lib/installations/installations-namespace.js create mode 100644 node_modules/firebase-admin/lib/installations/installations-request-handler.d.ts create mode 100644 node_modules/firebase-admin/lib/installations/installations-request-handler.js create mode 100644 node_modules/firebase-admin/lib/installations/installations.d.ts create mode 100644 node_modules/firebase-admin/lib/installations/installations.js create mode 100644 node_modules/firebase-admin/lib/instance-id/index.d.ts create mode 100644 node_modules/firebase-admin/lib/instance-id/index.js create mode 100644 node_modules/firebase-admin/lib/instance-id/instance-id-namespace.d.ts create mode 100644 node_modules/firebase-admin/lib/instance-id/instance-id-namespace.js create mode 100644 node_modules/firebase-admin/lib/instance-id/instance-id.d.ts create mode 100644 node_modules/firebase-admin/lib/instance-id/instance-id.js create mode 100644 node_modules/firebase-admin/lib/machine-learning/index.d.ts create mode 100644 node_modules/firebase-admin/lib/machine-learning/index.js create mode 100644 node_modules/firebase-admin/lib/machine-learning/machine-learning-api-client.d.ts create mode 100644 node_modules/firebase-admin/lib/machine-learning/machine-learning-api-client.js create mode 100644 node_modules/firebase-admin/lib/machine-learning/machine-learning-namespace.d.ts create mode 100644 node_modules/firebase-admin/lib/machine-learning/machine-learning-namespace.js create mode 100644 node_modules/firebase-admin/lib/machine-learning/machine-learning-utils.d.ts create mode 100644 node_modules/firebase-admin/lib/machine-learning/machine-learning-utils.js create mode 100644 node_modules/firebase-admin/lib/machine-learning/machine-learning.d.ts create mode 100644 node_modules/firebase-admin/lib/machine-learning/machine-learning.js create mode 100644 node_modules/firebase-admin/lib/messaging/index.d.ts create mode 100644 node_modules/firebase-admin/lib/messaging/index.js create mode 100644 node_modules/firebase-admin/lib/messaging/messaging-api-request-internal.d.ts create mode 100644 node_modules/firebase-admin/lib/messaging/messaging-api-request-internal.js create mode 100644 node_modules/firebase-admin/lib/messaging/messaging-api.d.ts create mode 100644 node_modules/firebase-admin/lib/messaging/messaging-api.js create mode 100644 node_modules/firebase-admin/lib/messaging/messaging-errors-internal.d.ts create mode 100644 node_modules/firebase-admin/lib/messaging/messaging-errors-internal.js create mode 100644 node_modules/firebase-admin/lib/messaging/messaging-internal.d.ts create mode 100644 node_modules/firebase-admin/lib/messaging/messaging-internal.js create mode 100644 node_modules/firebase-admin/lib/messaging/messaging-namespace.d.ts create mode 100644 node_modules/firebase-admin/lib/messaging/messaging-namespace.js create mode 100644 node_modules/firebase-admin/lib/messaging/messaging.d.ts create mode 100644 node_modules/firebase-admin/lib/messaging/messaging.js create mode 100644 node_modules/firebase-admin/lib/project-management/android-app.d.ts create mode 100644 node_modules/firebase-admin/lib/project-management/android-app.js create mode 100644 node_modules/firebase-admin/lib/project-management/app-metadata.d.ts create mode 100644 node_modules/firebase-admin/lib/project-management/app-metadata.js create mode 100644 node_modules/firebase-admin/lib/project-management/index.d.ts create mode 100644 node_modules/firebase-admin/lib/project-management/index.js create mode 100644 node_modules/firebase-admin/lib/project-management/ios-app.d.ts create mode 100644 node_modules/firebase-admin/lib/project-management/ios-app.js create mode 100644 node_modules/firebase-admin/lib/project-management/project-management-api-request-internal.d.ts create mode 100644 node_modules/firebase-admin/lib/project-management/project-management-api-request-internal.js create mode 100644 node_modules/firebase-admin/lib/project-management/project-management-namespace.d.ts create mode 100644 node_modules/firebase-admin/lib/project-management/project-management-namespace.js create mode 100644 node_modules/firebase-admin/lib/project-management/project-management.d.ts create mode 100644 node_modules/firebase-admin/lib/project-management/project-management.js create mode 100644 node_modules/firebase-admin/lib/remote-config/condition-evaluator-internal.d.ts create mode 100644 node_modules/firebase-admin/lib/remote-config/condition-evaluator-internal.js create mode 100644 node_modules/firebase-admin/lib/remote-config/index.d.ts create mode 100644 node_modules/firebase-admin/lib/remote-config/index.js create mode 100644 node_modules/firebase-admin/lib/remote-config/internal/value-impl.d.ts create mode 100644 node_modules/firebase-admin/lib/remote-config/internal/value-impl.js create mode 100644 node_modules/firebase-admin/lib/remote-config/remote-config-api-client-internal.d.ts create mode 100644 node_modules/firebase-admin/lib/remote-config/remote-config-api-client-internal.js create mode 100644 node_modules/firebase-admin/lib/remote-config/remote-config-api.d.ts create mode 100644 node_modules/firebase-admin/lib/remote-config/remote-config-api.js create mode 100644 node_modules/firebase-admin/lib/remote-config/remote-config-namespace.d.ts create mode 100644 node_modules/firebase-admin/lib/remote-config/remote-config-namespace.js create mode 100644 node_modules/firebase-admin/lib/remote-config/remote-config.d.ts create mode 100644 node_modules/firebase-admin/lib/remote-config/remote-config.js create mode 100644 node_modules/firebase-admin/lib/security-rules/index.d.ts create mode 100644 node_modules/firebase-admin/lib/security-rules/index.js create mode 100644 node_modules/firebase-admin/lib/security-rules/security-rules-api-client-internal.d.ts create mode 100644 node_modules/firebase-admin/lib/security-rules/security-rules-api-client-internal.js create mode 100644 node_modules/firebase-admin/lib/security-rules/security-rules-internal.d.ts create mode 100644 node_modules/firebase-admin/lib/security-rules/security-rules-internal.js create mode 100644 node_modules/firebase-admin/lib/security-rules/security-rules-namespace.d.ts create mode 100644 node_modules/firebase-admin/lib/security-rules/security-rules-namespace.js create mode 100644 node_modules/firebase-admin/lib/security-rules/security-rules.d.ts create mode 100644 node_modules/firebase-admin/lib/security-rules/security-rules.js create mode 100644 node_modules/firebase-admin/lib/storage/index.d.ts create mode 100644 node_modules/firebase-admin/lib/storage/index.js create mode 100644 node_modules/firebase-admin/lib/storage/storage-namespace.d.ts create mode 100644 node_modules/firebase-admin/lib/storage/storage-namespace.js create mode 100644 node_modules/firebase-admin/lib/storage/storage.d.ts create mode 100644 node_modules/firebase-admin/lib/storage/storage.js create mode 100644 node_modules/firebase-admin/lib/storage/utils.d.ts create mode 100644 node_modules/firebase-admin/lib/storage/utils.js create mode 100644 node_modules/firebase-admin/lib/utils/api-request.d.ts create mode 100644 node_modules/firebase-admin/lib/utils/api-request.js create mode 100644 node_modules/firebase-admin/lib/utils/crypto-signer.d.ts create mode 100644 node_modules/firebase-admin/lib/utils/crypto-signer.js create mode 100644 node_modules/firebase-admin/lib/utils/deep-copy.d.ts create mode 100644 node_modules/firebase-admin/lib/utils/deep-copy.js create mode 100644 node_modules/firebase-admin/lib/utils/error.d.ts create mode 100644 node_modules/firebase-admin/lib/utils/error.js create mode 100644 node_modules/firebase-admin/lib/utils/index.d.ts create mode 100644 node_modules/firebase-admin/lib/utils/index.js create mode 100644 node_modules/firebase-admin/lib/utils/jwt.d.ts create mode 100644 node_modules/firebase-admin/lib/utils/jwt.js create mode 100644 node_modules/firebase-admin/lib/utils/validator.d.ts create mode 100644 node_modules/firebase-admin/lib/utils/validator.js create mode 100644 node_modules/firebase-admin/package.json create mode 100644 node_modules/form-data/CHANGELOG.md create mode 100644 node_modules/form-data/License create mode 100644 node_modules/form-data/README.md create mode 100644 node_modules/form-data/index.d.ts create mode 100644 node_modules/form-data/lib/browser.js create mode 100644 node_modules/form-data/lib/form_data.js create mode 100644 node_modules/form-data/lib/populate.js create mode 100644 node_modules/form-data/package.json create mode 100644 node_modules/function-bind/.eslintrc create mode 100644 node_modules/function-bind/.github/FUNDING.yml create mode 100644 node_modules/function-bind/.github/SECURITY.md create mode 100644 node_modules/function-bind/.nycrc create mode 100644 node_modules/function-bind/CHANGELOG.md create mode 100644 node_modules/function-bind/LICENSE create mode 100644 node_modules/function-bind/README.md create mode 100644 node_modules/function-bind/implementation.js create mode 100644 node_modules/function-bind/index.js create mode 100644 node_modules/function-bind/package.json create mode 100644 node_modules/function-bind/test/.eslintrc create mode 100644 node_modules/function-bind/test/index.js create mode 100644 node_modules/functional-red-black-tree/.npmignore create mode 100644 node_modules/functional-red-black-tree/LICENSE create mode 100644 node_modules/functional-red-black-tree/README.md create mode 100644 node_modules/functional-red-black-tree/bench/test.js create mode 100644 node_modules/functional-red-black-tree/package.json create mode 100644 node_modules/functional-red-black-tree/rbtree.js create mode 100644 node_modules/functional-red-black-tree/test/test.js create mode 100644 node_modules/gaxios/CHANGELOG.md create mode 100644 node_modules/gaxios/LICENSE create mode 100644 node_modules/gaxios/README.md create mode 100644 node_modules/gaxios/build/src/common.d.ts create mode 100644 node_modules/gaxios/build/src/common.js create mode 100644 node_modules/gaxios/build/src/common.js.map create mode 100644 node_modules/gaxios/build/src/gaxios.d.ts create mode 100644 node_modules/gaxios/build/src/gaxios.js create mode 100644 node_modules/gaxios/build/src/gaxios.js.map create mode 100644 node_modules/gaxios/build/src/index.d.ts create mode 100644 node_modules/gaxios/build/src/index.js create mode 100644 node_modules/gaxios/build/src/index.js.map create mode 100644 node_modules/gaxios/build/src/interceptor.d.ts create mode 100644 node_modules/gaxios/build/src/interceptor.js create mode 100644 node_modules/gaxios/build/src/interceptor.js.map create mode 100644 node_modules/gaxios/build/src/retry.d.ts create mode 100644 node_modules/gaxios/build/src/retry.js create mode 100644 node_modules/gaxios/build/src/retry.js.map create mode 100644 node_modules/gaxios/build/src/util.d.ts create mode 100644 node_modules/gaxios/build/src/util.js create mode 100644 node_modules/gaxios/build/src/util.js.map create mode 100644 node_modules/gaxios/node_modules/.bin/uuid create mode 100644 node_modules/gaxios/node_modules/.bin/uuid.cmd create mode 100644 node_modules/gaxios/node_modules/.bin/uuid.ps1 create mode 100644 node_modules/gaxios/node_modules/uuid/CHANGELOG.md create mode 100644 node_modules/gaxios/node_modules/uuid/CONTRIBUTING.md create mode 100644 node_modules/gaxios/node_modules/uuid/LICENSE.md create mode 100644 node_modules/gaxios/node_modules/uuid/README.md create mode 100644 node_modules/gaxios/node_modules/uuid/dist/bin/uuid create mode 100644 node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/index.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/md5.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/native.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/nil.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/parse.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/regex.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/rng.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/sha1.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/stringify.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/v1.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/v3.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/v35.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/v4.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/v5.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/validate.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/version.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-browser/index.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-browser/md5.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-browser/native.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-browser/nil.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-browser/parse.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-browser/regex.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-browser/rng.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-browser/sha1.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-browser/stringify.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-browser/v1.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-browser/v3.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-browser/v35.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-browser/v4.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-browser/v5.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-browser/validate.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-browser/version.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-node/index.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-node/md5.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-node/native.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-node/nil.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-node/parse.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-node/regex.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-node/rng.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-node/sha1.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-node/stringify.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-node/v1.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-node/v3.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-node/v35.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-node/v4.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-node/v5.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-node/validate.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/esm-node/version.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/index.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/md5-browser.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/md5.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/native-browser.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/native.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/nil.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/parse.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/regex.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/rng-browser.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/rng.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/sha1-browser.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/sha1.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/stringify.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/uuid-bin.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/v1.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/v3.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/v35.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/v4.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/v5.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/validate.js create mode 100644 node_modules/gaxios/node_modules/uuid/dist/version.js create mode 100644 node_modules/gaxios/node_modules/uuid/package.json create mode 100644 node_modules/gaxios/node_modules/uuid/wrapper.mjs create mode 100644 node_modules/gaxios/package.json create mode 100644 node_modules/gcp-metadata/CHANGELOG.md create mode 100644 node_modules/gcp-metadata/LICENSE create mode 100644 node_modules/gcp-metadata/README.md create mode 100644 node_modules/gcp-metadata/build/src/gcp-residency.d.ts create mode 100644 node_modules/gcp-metadata/build/src/gcp-residency.js create mode 100644 node_modules/gcp-metadata/build/src/gcp-residency.js.map create mode 100644 node_modules/gcp-metadata/build/src/index.d.ts create mode 100644 node_modules/gcp-metadata/build/src/index.js create mode 100644 node_modules/gcp-metadata/build/src/index.js.map create mode 100644 node_modules/gcp-metadata/package.json create mode 100644 node_modules/get-caller-file/LICENSE.md create mode 100644 node_modules/get-caller-file/README.md create mode 100644 node_modules/get-caller-file/index.d.ts create mode 100644 node_modules/get-caller-file/index.js create mode 100644 node_modules/get-caller-file/index.js.map create mode 100644 node_modules/get-caller-file/package.json create mode 100644 node_modules/get-intrinsic/.eslintrc create mode 100644 node_modules/get-intrinsic/.github/FUNDING.yml create mode 100644 node_modules/get-intrinsic/.nycrc create mode 100644 node_modules/get-intrinsic/CHANGELOG.md create mode 100644 node_modules/get-intrinsic/LICENSE create mode 100644 node_modules/get-intrinsic/README.md create mode 100644 node_modules/get-intrinsic/index.js create mode 100644 node_modules/get-intrinsic/package.json create mode 100644 node_modules/get-intrinsic/test/GetIntrinsic.js create mode 100644 node_modules/get-proto/.eslintrc create mode 100644 node_modules/get-proto/.github/FUNDING.yml create mode 100644 node_modules/get-proto/.nycrc create mode 100644 node_modules/get-proto/CHANGELOG.md create mode 100644 node_modules/get-proto/LICENSE create mode 100644 node_modules/get-proto/Object.getPrototypeOf.d.ts create mode 100644 node_modules/get-proto/Object.getPrototypeOf.js create mode 100644 node_modules/get-proto/README.md create mode 100644 node_modules/get-proto/Reflect.getPrototypeOf.d.ts create mode 100644 node_modules/get-proto/Reflect.getPrototypeOf.js create mode 100644 node_modules/get-proto/index.d.ts create mode 100644 node_modules/get-proto/index.js create mode 100644 node_modules/get-proto/package.json create mode 100644 node_modules/get-proto/test/index.js create mode 100644 node_modules/get-proto/tsconfig.json create mode 100644 node_modules/google-auth-library/CHANGELOG.md create mode 100644 node_modules/google-auth-library/LICENSE create mode 100644 node_modules/google-auth-library/README.md create mode 100644 node_modules/google-auth-library/build/src/auth/authclient.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/authclient.js create mode 100644 node_modules/google-auth-library/build/src/auth/awsclient.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/awsclient.js create mode 100644 node_modules/google-auth-library/build/src/auth/awsrequestsigner.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/awsrequestsigner.js create mode 100644 node_modules/google-auth-library/build/src/auth/baseexternalclient.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/baseexternalclient.js create mode 100644 node_modules/google-auth-library/build/src/auth/computeclient.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/computeclient.js create mode 100644 node_modules/google-auth-library/build/src/auth/credentials.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/credentials.js create mode 100644 node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js create mode 100644 node_modules/google-auth-library/build/src/auth/downscopedclient.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/downscopedclient.js create mode 100644 node_modules/google-auth-library/build/src/auth/envDetect.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/envDetect.js create mode 100644 node_modules/google-auth-library/build/src/auth/executable-response.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/executable-response.js create mode 100644 node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js create mode 100644 node_modules/google-auth-library/build/src/auth/externalclient.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/externalclient.js create mode 100644 node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js create mode 100644 node_modules/google-auth-library/build/src/auth/googleauth.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/googleauth.js create mode 100644 node_modules/google-auth-library/build/src/auth/iam.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/iam.js create mode 100644 node_modules/google-auth-library/build/src/auth/identitypoolclient.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/identitypoolclient.js create mode 100644 node_modules/google-auth-library/build/src/auth/idtokenclient.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/idtokenclient.js create mode 100644 node_modules/google-auth-library/build/src/auth/impersonated.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/impersonated.js create mode 100644 node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/jwtaccess.js create mode 100644 node_modules/google-auth-library/build/src/auth/jwtclient.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/jwtclient.js create mode 100644 node_modules/google-auth-library/build/src/auth/loginticket.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/loginticket.js create mode 100644 node_modules/google-auth-library/build/src/auth/oauth2client.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/oauth2client.js create mode 100644 node_modules/google-auth-library/build/src/auth/oauth2common.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/oauth2common.js create mode 100644 node_modules/google-auth-library/build/src/auth/passthrough.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/passthrough.js create mode 100644 node_modules/google-auth-library/build/src/auth/pluggable-auth-client.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js create mode 100644 node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js create mode 100644 node_modules/google-auth-library/build/src/auth/refreshclient.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/refreshclient.js create mode 100644 node_modules/google-auth-library/build/src/auth/stscredentials.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/stscredentials.js create mode 100644 node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js create mode 100644 node_modules/google-auth-library/build/src/crypto/browser/crypto.d.ts create mode 100644 node_modules/google-auth-library/build/src/crypto/browser/crypto.js create mode 100644 node_modules/google-auth-library/build/src/crypto/crypto.d.ts create mode 100644 node_modules/google-auth-library/build/src/crypto/crypto.js create mode 100644 node_modules/google-auth-library/build/src/crypto/node/crypto.d.ts create mode 100644 node_modules/google-auth-library/build/src/crypto/node/crypto.js create mode 100644 node_modules/google-auth-library/build/src/index.d.ts create mode 100644 node_modules/google-auth-library/build/src/index.js create mode 100644 node_modules/google-auth-library/build/src/messages.d.ts create mode 100644 node_modules/google-auth-library/build/src/messages.js create mode 100644 node_modules/google-auth-library/build/src/options.d.ts create mode 100644 node_modules/google-auth-library/build/src/options.js create mode 100644 node_modules/google-auth-library/build/src/transporters.d.ts create mode 100644 node_modules/google-auth-library/build/src/transporters.js create mode 100644 node_modules/google-auth-library/build/src/util.d.ts create mode 100644 node_modules/google-auth-library/build/src/util.js create mode 100644 node_modules/google-auth-library/package.json create mode 100644 node_modules/google-gax/build/protos/compute_operations.d.ts create mode 100644 node_modules/google-gax/build/protos/compute_operations.js create mode 100644 node_modules/google-gax/build/protos/compute_operations.json create mode 100644 node_modules/google-gax/build/protos/google/api/annotations.proto create mode 100644 node_modules/google-gax/build/protos/google/api/apikeys/v2/apikeys.proto create mode 100644 node_modules/google-gax/build/protos/google/api/apikeys/v2/resources.proto create mode 100644 node_modules/google-gax/build/protos/google/api/auth.proto create mode 100644 node_modules/google-gax/build/protos/google/api/backend.proto create mode 100644 node_modules/google-gax/build/protos/google/api/billing.proto create mode 100644 node_modules/google-gax/build/protos/google/api/client.proto create mode 100644 node_modules/google-gax/build/protos/google/api/cloudquotas/v1/cloudquotas.proto create mode 100644 node_modules/google-gax/build/protos/google/api/cloudquotas/v1/resources.proto create mode 100644 node_modules/google-gax/build/protos/google/api/config_change.proto create mode 100644 node_modules/google-gax/build/protos/google/api/consumer.proto create mode 100644 node_modules/google-gax/build/protos/google/api/context.proto create mode 100644 node_modules/google-gax/build/protos/google/api/control.proto create mode 100644 node_modules/google-gax/build/protos/google/api/distribution.proto create mode 100644 node_modules/google-gax/build/protos/google/api/documentation.proto create mode 100644 node_modules/google-gax/build/protos/google/api/endpoint.proto create mode 100644 node_modules/google-gax/build/protos/google/api/error_reason.proto create mode 100644 node_modules/google-gax/build/protos/google/api/expr/conformance/v1alpha1/conformance_service.proto create mode 100644 node_modules/google-gax/build/protos/google/api/expr/v1alpha1/checked.proto create mode 100644 node_modules/google-gax/build/protos/google/api/expr/v1alpha1/eval.proto create mode 100644 node_modules/google-gax/build/protos/google/api/expr/v1alpha1/explain.proto create mode 100644 node_modules/google-gax/build/protos/google/api/expr/v1alpha1/syntax.proto create mode 100644 node_modules/google-gax/build/protos/google/api/expr/v1alpha1/value.proto create mode 100644 node_modules/google-gax/build/protos/google/api/expr/v1beta1/decl.proto create mode 100644 node_modules/google-gax/build/protos/google/api/expr/v1beta1/eval.proto create mode 100644 node_modules/google-gax/build/protos/google/api/expr/v1beta1/expr.proto create mode 100644 node_modules/google-gax/build/protos/google/api/expr/v1beta1/source.proto create mode 100644 node_modules/google-gax/build/protos/google/api/expr/v1beta1/value.proto create mode 100644 node_modules/google-gax/build/protos/google/api/field_behavior.proto create mode 100644 node_modules/google-gax/build/protos/google/api/field_info.proto create mode 100644 node_modules/google-gax/build/protos/google/api/http.proto create mode 100644 node_modules/google-gax/build/protos/google/api/httpbody.proto create mode 100644 node_modules/google-gax/build/protos/google/api/label.proto create mode 100644 node_modules/google-gax/build/protos/google/api/launch_stage.proto create mode 100644 node_modules/google-gax/build/protos/google/api/log.proto create mode 100644 node_modules/google-gax/build/protos/google/api/logging.proto create mode 100644 node_modules/google-gax/build/protos/google/api/metric.proto create mode 100644 node_modules/google-gax/build/protos/google/api/monitored_resource.proto create mode 100644 node_modules/google-gax/build/protos/google/api/monitoring.proto create mode 100644 node_modules/google-gax/build/protos/google/api/policy.proto create mode 100644 node_modules/google-gax/build/protos/google/api/quota.proto create mode 100644 node_modules/google-gax/build/protos/google/api/resource.proto create mode 100644 node_modules/google-gax/build/protos/google/api/routing.proto create mode 100644 node_modules/google-gax/build/protos/google/api/service.proto create mode 100644 node_modules/google-gax/build/protos/google/api/servicecontrol/v1/check_error.proto create mode 100644 node_modules/google-gax/build/protos/google/api/servicecontrol/v1/distribution.proto create mode 100644 node_modules/google-gax/build/protos/google/api/servicecontrol/v1/http_request.proto create mode 100644 node_modules/google-gax/build/protos/google/api/servicecontrol/v1/log_entry.proto create mode 100644 node_modules/google-gax/build/protos/google/api/servicecontrol/v1/metric_value.proto create mode 100644 node_modules/google-gax/build/protos/google/api/servicecontrol/v1/operation.proto create mode 100644 node_modules/google-gax/build/protos/google/api/servicecontrol/v1/quota_controller.proto create mode 100644 node_modules/google-gax/build/protos/google/api/servicecontrol/v1/service_controller.proto create mode 100644 node_modules/google-gax/build/protos/google/api/servicecontrol/v2/service_controller.proto create mode 100644 node_modules/google-gax/build/protos/google/api/servicemanagement/v1/resources.proto create mode 100644 node_modules/google-gax/build/protos/google/api/servicemanagement/v1/servicemanager.proto create mode 100644 node_modules/google-gax/build/protos/google/api/serviceusage/v1/resources.proto create mode 100644 node_modules/google-gax/build/protos/google/api/serviceusage/v1/serviceusage.proto create mode 100644 node_modules/google-gax/build/protos/google/api/serviceusage/v1beta1/resources.proto create mode 100644 node_modules/google-gax/build/protos/google/api/serviceusage/v1beta1/serviceusage.proto create mode 100644 node_modules/google-gax/build/protos/google/api/source_info.proto create mode 100644 node_modules/google-gax/build/protos/google/api/system_parameter.proto create mode 100644 node_modules/google-gax/build/protos/google/api/usage.proto create mode 100644 node_modules/google-gax/build/protos/google/api/visibility.proto create mode 100644 node_modules/google-gax/build/protos/google/cloud/location/locations.proto create mode 100644 node_modules/google-gax/build/protos/google/iam/v1/iam_policy.proto create mode 100644 node_modules/google-gax/build/protos/google/iam/v1/logging/audit_data.proto create mode 100644 node_modules/google-gax/build/protos/google/iam/v1/options.proto create mode 100644 node_modules/google-gax/build/protos/google/iam/v1/policy.proto create mode 100644 node_modules/google-gax/build/protos/google/logging/type/http_request.proto create mode 100644 node_modules/google-gax/build/protos/google/logging/type/log_severity.proto create mode 100644 node_modules/google-gax/build/protos/google/longrunning/operations.proto create mode 100644 node_modules/google-gax/build/protos/google/monitoring/v3/alert.proto create mode 100644 node_modules/google-gax/build/protos/google/monitoring/v3/alert_service.proto create mode 100644 node_modules/google-gax/build/protos/google/monitoring/v3/common.proto create mode 100644 node_modules/google-gax/build/protos/google/monitoring/v3/dropped_labels.proto create mode 100644 node_modules/google-gax/build/protos/google/monitoring/v3/group.proto create mode 100644 node_modules/google-gax/build/protos/google/monitoring/v3/group_service.proto create mode 100644 node_modules/google-gax/build/protos/google/monitoring/v3/metric.proto create mode 100644 node_modules/google-gax/build/protos/google/monitoring/v3/metric_service.proto create mode 100644 node_modules/google-gax/build/protos/google/monitoring/v3/mutation_record.proto create mode 100644 node_modules/google-gax/build/protos/google/monitoring/v3/notification.proto create mode 100644 node_modules/google-gax/build/protos/google/monitoring/v3/notification_service.proto create mode 100644 node_modules/google-gax/build/protos/google/monitoring/v3/query_service.proto create mode 100644 node_modules/google-gax/build/protos/google/monitoring/v3/service.proto create mode 100644 node_modules/google-gax/build/protos/google/monitoring/v3/service_service.proto create mode 100644 node_modules/google-gax/build/protos/google/monitoring/v3/snooze.proto create mode 100644 node_modules/google-gax/build/protos/google/monitoring/v3/snooze_service.proto create mode 100644 node_modules/google-gax/build/protos/google/monitoring/v3/span_context.proto create mode 100644 node_modules/google-gax/build/protos/google/monitoring/v3/uptime.proto create mode 100644 node_modules/google-gax/build/protos/google/monitoring/v3/uptime_service.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/any.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/api.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/bridge/message_set.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/compiler/plugin.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_code.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_code_proto2.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_code_proto2_import.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_pkg_implicit.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/cpp_features.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/descriptor.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/duration.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_enum.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_group.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_import.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_inline_comments.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_multiline_comments.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_optional.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_packed.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_proto3_enum.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_required.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_unpacked.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_utf8_disabled.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_utf8_lite.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_utf8_verify.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_enum.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_implicit.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_import.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_optional.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_packed.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_unpacked.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_utf8_strict.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/golden/editions_transform_proto2.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/golden/editions_transform_proto2_lite.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/golden/editions_transform_proto2_utf8_disabled.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/golden/editions_transform_proto3.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/golden/editions_transform_proto3_utf8_disabled.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/golden/simple_proto2.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/golden/simple_proto2_import.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/golden/simple_proto3.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/proto/editions_transform_proto2.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/proto/editions_transform_proto2_lite.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/proto/editions_transform_proto2_utf8_disabled.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/proto/editions_transform_proto3.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/editions/proto/editions_transform_proto3_utf8_disabled.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/empty.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/field_mask.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/sample_messages_edition.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/source_context.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/struct.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/timestamp.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/type.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/util/json_format.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/util/json_format_proto3.proto create mode 100644 node_modules/google-gax/build/protos/google/protobuf/wrappers.proto create mode 100644 node_modules/google-gax/build/protos/google/rpc/code.proto create mode 100644 node_modules/google-gax/build/protos/google/rpc/context/attribute_context.proto create mode 100644 node_modules/google-gax/build/protos/google/rpc/context/audit_context.proto create mode 100644 node_modules/google-gax/build/protos/google/rpc/error_details.proto create mode 100644 node_modules/google-gax/build/protos/google/rpc/http.proto create mode 100644 node_modules/google-gax/build/protos/google/rpc/status.proto create mode 100644 node_modules/google-gax/build/protos/google/type/calendar_period.proto create mode 100644 node_modules/google-gax/build/protos/google/type/color.proto create mode 100644 node_modules/google-gax/build/protos/google/type/date.proto create mode 100644 node_modules/google-gax/build/protos/google/type/datetime.proto create mode 100644 node_modules/google-gax/build/protos/google/type/dayofweek.proto create mode 100644 node_modules/google-gax/build/protos/google/type/decimal.proto create mode 100644 node_modules/google-gax/build/protos/google/type/expr.proto create mode 100644 node_modules/google-gax/build/protos/google/type/fraction.proto create mode 100644 node_modules/google-gax/build/protos/google/type/interval.proto create mode 100644 node_modules/google-gax/build/protos/google/type/latlng.proto create mode 100644 node_modules/google-gax/build/protos/google/type/localized_text.proto create mode 100644 node_modules/google-gax/build/protos/google/type/money.proto create mode 100644 node_modules/google-gax/build/protos/google/type/month.proto create mode 100644 node_modules/google-gax/build/protos/google/type/phone_number.proto create mode 100644 node_modules/google-gax/build/protos/google/type/postal_address.proto create mode 100644 node_modules/google-gax/build/protos/google/type/quaternion.proto create mode 100644 node_modules/google-gax/build/protos/google/type/timeofday.proto create mode 100644 node_modules/google-gax/build/protos/http.d.ts create mode 100644 node_modules/google-gax/build/protos/http.js create mode 100644 node_modules/google-gax/build/protos/iam_service.d.ts create mode 100644 node_modules/google-gax/build/protos/iam_service.js create mode 100644 node_modules/google-gax/build/protos/iam_service.json create mode 100644 node_modules/google-gax/build/protos/locations.d.ts create mode 100644 node_modules/google-gax/build/protos/locations.js create mode 100644 node_modules/google-gax/build/protos/locations.json create mode 100644 node_modules/google-gax/build/protos/operations.d.ts create mode 100644 node_modules/google-gax/build/protos/operations.js create mode 100644 node_modules/google-gax/build/protos/operations.json create mode 100644 node_modules/google-gax/build/protos/status.json create mode 100644 node_modules/google-gax/build/src/apiCaller.d.ts create mode 100644 node_modules/google-gax/build/src/apiCaller.js create mode 100644 node_modules/google-gax/build/src/apiCaller.js.map create mode 100644 node_modules/google-gax/build/src/apitypes.d.ts create mode 100644 node_modules/google-gax/build/src/apitypes.js create mode 100644 node_modules/google-gax/build/src/apitypes.js.map create mode 100644 node_modules/google-gax/build/src/bundlingCalls/bundleApiCaller.d.ts create mode 100644 node_modules/google-gax/build/src/bundlingCalls/bundleApiCaller.js create mode 100644 node_modules/google-gax/build/src/bundlingCalls/bundleApiCaller.js.map create mode 100644 node_modules/google-gax/build/src/bundlingCalls/bundleDescriptor.d.ts create mode 100644 node_modules/google-gax/build/src/bundlingCalls/bundleDescriptor.js create mode 100644 node_modules/google-gax/build/src/bundlingCalls/bundleDescriptor.js.map create mode 100644 node_modules/google-gax/build/src/bundlingCalls/bundleExecutor.d.ts create mode 100644 node_modules/google-gax/build/src/bundlingCalls/bundleExecutor.js create mode 100644 node_modules/google-gax/build/src/bundlingCalls/bundleExecutor.js.map create mode 100644 node_modules/google-gax/build/src/bundlingCalls/bundlingUtils.d.ts create mode 100644 node_modules/google-gax/build/src/bundlingCalls/bundlingUtils.js create mode 100644 node_modules/google-gax/build/src/bundlingCalls/bundlingUtils.js.map create mode 100644 node_modules/google-gax/build/src/bundlingCalls/task.d.ts create mode 100644 node_modules/google-gax/build/src/bundlingCalls/task.js create mode 100644 node_modules/google-gax/build/src/bundlingCalls/task.js.map create mode 100644 node_modules/google-gax/build/src/call.d.ts create mode 100644 node_modules/google-gax/build/src/call.js create mode 100644 node_modules/google-gax/build/src/call.js.map create mode 100644 node_modules/google-gax/build/src/clientInterface.d.ts create mode 100644 node_modules/google-gax/build/src/clientInterface.js create mode 100644 node_modules/google-gax/build/src/clientInterface.js.map create mode 100644 node_modules/google-gax/build/src/createApiCall.d.ts create mode 100644 node_modules/google-gax/build/src/createApiCall.js create mode 100644 node_modules/google-gax/build/src/createApiCall.js.map create mode 100644 node_modules/google-gax/build/src/descriptor.d.ts create mode 100644 node_modules/google-gax/build/src/descriptor.js create mode 100644 node_modules/google-gax/build/src/descriptor.js.map create mode 100644 node_modules/google-gax/build/src/fallback.d.ts create mode 100644 node_modules/google-gax/build/src/fallback.js create mode 100644 node_modules/google-gax/build/src/fallback.js.map create mode 100644 node_modules/google-gax/build/src/fallbackRest.d.ts create mode 100644 node_modules/google-gax/build/src/fallbackRest.js create mode 100644 node_modules/google-gax/build/src/fallbackRest.js.map create mode 100644 node_modules/google-gax/build/src/fallbackServiceStub.d.ts create mode 100644 node_modules/google-gax/build/src/fallbackServiceStub.js create mode 100644 node_modules/google-gax/build/src/fallbackServiceStub.js.map create mode 100644 node_modules/google-gax/build/src/featureDetection.d.ts create mode 100644 node_modules/google-gax/build/src/featureDetection.js create mode 100644 node_modules/google-gax/build/src/featureDetection.js.map create mode 100644 node_modules/google-gax/build/src/gax.d.ts create mode 100644 node_modules/google-gax/build/src/gax.js create mode 100644 node_modules/google-gax/build/src/gax.js.map create mode 100644 node_modules/google-gax/build/src/googleError.d.ts create mode 100644 node_modules/google-gax/build/src/googleError.js create mode 100644 node_modules/google-gax/build/src/googleError.js.map create mode 100644 node_modules/google-gax/build/src/grpc.d.ts create mode 100644 node_modules/google-gax/build/src/grpc.js create mode 100644 node_modules/google-gax/build/src/grpc.js.map create mode 100644 node_modules/google-gax/build/src/iamService.d.ts create mode 100644 node_modules/google-gax/build/src/iamService.js create mode 100644 node_modules/google-gax/build/src/iamService.js.map create mode 100644 node_modules/google-gax/build/src/iam_policy_service_client_config.json create mode 100644 node_modules/google-gax/build/src/index.d.ts create mode 100644 node_modules/google-gax/build/src/index.js create mode 100644 node_modules/google-gax/build/src/index.js.map create mode 100644 node_modules/google-gax/build/src/locationService.d.ts create mode 100644 node_modules/google-gax/build/src/locationService.js create mode 100644 node_modules/google-gax/build/src/locationService.js.map create mode 100644 node_modules/google-gax/build/src/locations_client_config.json create mode 100644 node_modules/google-gax/build/src/longRunningCalls/longRunningApiCaller.d.ts create mode 100644 node_modules/google-gax/build/src/longRunningCalls/longRunningApiCaller.js create mode 100644 node_modules/google-gax/build/src/longRunningCalls/longRunningApiCaller.js.map create mode 100644 node_modules/google-gax/build/src/longRunningCalls/longRunningDescriptor.d.ts create mode 100644 node_modules/google-gax/build/src/longRunningCalls/longRunningDescriptor.js create mode 100644 node_modules/google-gax/build/src/longRunningCalls/longRunningDescriptor.js.map create mode 100644 node_modules/google-gax/build/src/longRunningCalls/longrunning.d.ts create mode 100644 node_modules/google-gax/build/src/longRunningCalls/longrunning.js create mode 100644 node_modules/google-gax/build/src/longRunningCalls/longrunning.js.map create mode 100644 node_modules/google-gax/build/src/normalCalls/normalApiCaller.d.ts create mode 100644 node_modules/google-gax/build/src/normalCalls/normalApiCaller.js create mode 100644 node_modules/google-gax/build/src/normalCalls/normalApiCaller.js.map create mode 100644 node_modules/google-gax/build/src/normalCalls/retries.d.ts create mode 100644 node_modules/google-gax/build/src/normalCalls/retries.js create mode 100644 node_modules/google-gax/build/src/normalCalls/retries.js.map create mode 100644 node_modules/google-gax/build/src/normalCalls/timeout.d.ts create mode 100644 node_modules/google-gax/build/src/normalCalls/timeout.js create mode 100644 node_modules/google-gax/build/src/normalCalls/timeout.js.map create mode 100644 node_modules/google-gax/build/src/operationsClient.d.ts create mode 100644 node_modules/google-gax/build/src/operationsClient.js create mode 100644 node_modules/google-gax/build/src/operationsClient.js.map create mode 100644 node_modules/google-gax/build/src/operations_client_config.json create mode 100644 node_modules/google-gax/build/src/paginationCalls/pageDescriptor.d.ts create mode 100644 node_modules/google-gax/build/src/paginationCalls/pageDescriptor.js create mode 100644 node_modules/google-gax/build/src/paginationCalls/pageDescriptor.js.map create mode 100644 node_modules/google-gax/build/src/paginationCalls/pagedApiCaller.d.ts create mode 100644 node_modules/google-gax/build/src/paginationCalls/pagedApiCaller.js create mode 100644 node_modules/google-gax/build/src/paginationCalls/pagedApiCaller.js.map create mode 100644 node_modules/google-gax/build/src/paginationCalls/resourceCollector.d.ts create mode 100644 node_modules/google-gax/build/src/paginationCalls/resourceCollector.js create mode 100644 node_modules/google-gax/build/src/paginationCalls/resourceCollector.js.map create mode 100644 node_modules/google-gax/build/src/pathTemplate.d.ts create mode 100644 node_modules/google-gax/build/src/pathTemplate.js create mode 100644 node_modules/google-gax/build/src/pathTemplate.js.map create mode 100644 node_modules/google-gax/build/src/protobuf.d.ts create mode 100644 node_modules/google-gax/build/src/protobuf.js create mode 100644 node_modules/google-gax/build/src/protobuf.js.map create mode 100644 node_modules/google-gax/build/src/protosList.json create mode 100644 node_modules/google-gax/build/src/routingHeader.d.ts create mode 100644 node_modules/google-gax/build/src/routingHeader.js create mode 100644 node_modules/google-gax/build/src/routingHeader.js.map create mode 100644 node_modules/google-gax/build/src/status.d.ts create mode 100644 node_modules/google-gax/build/src/status.js create mode 100644 node_modules/google-gax/build/src/status.js.map create mode 100644 node_modules/google-gax/build/src/streamArrayParser.d.ts create mode 100644 node_modules/google-gax/build/src/streamArrayParser.js create mode 100644 node_modules/google-gax/build/src/streamArrayParser.js.map create mode 100644 node_modules/google-gax/build/src/streamingCalls/streamDescriptor.d.ts create mode 100644 node_modules/google-gax/build/src/streamingCalls/streamDescriptor.js create mode 100644 node_modules/google-gax/build/src/streamingCalls/streamDescriptor.js.map create mode 100644 node_modules/google-gax/build/src/streamingCalls/streaming.d.ts create mode 100644 node_modules/google-gax/build/src/streamingCalls/streaming.js create mode 100644 node_modules/google-gax/build/src/streamingCalls/streaming.js.map create mode 100644 node_modules/google-gax/build/src/streamingCalls/streamingApiCaller.d.ts create mode 100644 node_modules/google-gax/build/src/streamingCalls/streamingApiCaller.js create mode 100644 node_modules/google-gax/build/src/streamingCalls/streamingApiCaller.js.map create mode 100644 node_modules/google-gax/build/src/transcoding.d.ts create mode 100644 node_modules/google-gax/build/src/transcoding.js create mode 100644 node_modules/google-gax/build/src/transcoding.js.map create mode 100644 node_modules/google-gax/build/src/util.d.ts create mode 100644 node_modules/google-gax/build/src/util.js create mode 100644 node_modules/google-gax/build/src/util.js.map create mode 100644 node_modules/google-gax/build/src/warnings.d.ts create mode 100644 node_modules/google-gax/build/src/warnings.js create mode 100644 node_modules/google-gax/build/src/warnings.js.map create mode 100644 node_modules/google-gax/node_modules/.bin/uuid create mode 100644 node_modules/google-gax/node_modules/.bin/uuid.cmd create mode 100644 node_modules/google-gax/node_modules/.bin/uuid.ps1 create mode 100644 node_modules/google-gax/node_modules/uuid/CHANGELOG.md create mode 100644 node_modules/google-gax/node_modules/uuid/CONTRIBUTING.md create mode 100644 node_modules/google-gax/node_modules/uuid/LICENSE.md create mode 100644 node_modules/google-gax/node_modules/uuid/README.md create mode 100644 node_modules/google-gax/node_modules/uuid/dist/bin/uuid create mode 100644 node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/index.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/md5.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/native.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/nil.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/parse.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/regex.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/rng.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/sha1.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/stringify.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/v1.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/v3.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/v35.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/v4.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/v5.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/validate.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/version.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-browser/index.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-browser/md5.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-browser/native.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-browser/nil.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-browser/parse.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-browser/regex.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-browser/rng.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-browser/sha1.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-browser/stringify.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-browser/v1.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-browser/v3.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-browser/v35.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-browser/v4.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-browser/v5.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-browser/validate.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-browser/version.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-node/index.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-node/md5.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-node/native.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-node/nil.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-node/parse.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-node/regex.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-node/rng.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-node/sha1.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-node/stringify.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-node/v1.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-node/v3.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-node/v35.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-node/v4.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-node/v5.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-node/validate.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/esm-node/version.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/index.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/md5-browser.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/md5.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/native-browser.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/native.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/nil.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/parse.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/regex.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/rng-browser.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/rng.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/sha1-browser.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/sha1.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/stringify.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/uuid-bin.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/v1.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/v3.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/v35.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/v4.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/v5.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/validate.js create mode 100644 node_modules/google-gax/node_modules/uuid/dist/version.js create mode 100644 node_modules/google-gax/node_modules/uuid/package.json create mode 100644 node_modules/google-gax/node_modules/uuid/wrapper.mjs create mode 100644 node_modules/google-gax/package.json create mode 100644 node_modules/google-logging-utils/LICENSE create mode 100644 node_modules/google-logging-utils/build/src/colours.d.ts create mode 100644 node_modules/google-logging-utils/build/src/colours.js create mode 100644 node_modules/google-logging-utils/build/src/colours.js.map create mode 100644 node_modules/google-logging-utils/build/src/index.d.ts create mode 100644 node_modules/google-logging-utils/build/src/index.js create mode 100644 node_modules/google-logging-utils/build/src/index.js.map create mode 100644 node_modules/google-logging-utils/build/src/logging-utils.d.ts create mode 100644 node_modules/google-logging-utils/build/src/logging-utils.js create mode 100644 node_modules/google-logging-utils/build/src/logging-utils.js.map create mode 100644 node_modules/google-logging-utils/build/src/temporal.d.ts create mode 100644 node_modules/google-logging-utils/build/src/temporal.js create mode 100644 node_modules/google-logging-utils/build/src/temporal.js.map create mode 100644 node_modules/google-logging-utils/package.json create mode 100644 node_modules/gopd/.eslintrc create mode 100644 node_modules/gopd/.github/FUNDING.yml create mode 100644 node_modules/gopd/CHANGELOG.md create mode 100644 node_modules/gopd/LICENSE create mode 100644 node_modules/gopd/README.md create mode 100644 node_modules/gopd/gOPD.d.ts create mode 100644 node_modules/gopd/gOPD.js create mode 100644 node_modules/gopd/index.d.ts create mode 100644 node_modules/gopd/index.js create mode 100644 node_modules/gopd/package.json create mode 100644 node_modules/gopd/test/index.js create mode 100644 node_modules/gopd/tsconfig.json create mode 100644 node_modules/gtoken/CHANGELOG.md create mode 100644 node_modules/gtoken/LICENSE create mode 100644 node_modules/gtoken/README.md create mode 100644 node_modules/gtoken/build/src/index.d.ts create mode 100644 node_modules/gtoken/build/src/index.js create mode 100644 node_modules/gtoken/package.json create mode 100644 node_modules/has-symbols/.eslintrc create mode 100644 node_modules/has-symbols/.github/FUNDING.yml create mode 100644 node_modules/has-symbols/.nycrc create mode 100644 node_modules/has-symbols/CHANGELOG.md create mode 100644 node_modules/has-symbols/LICENSE create mode 100644 node_modules/has-symbols/README.md create mode 100644 node_modules/has-symbols/index.d.ts create mode 100644 node_modules/has-symbols/index.js create mode 100644 node_modules/has-symbols/package.json create mode 100644 node_modules/has-symbols/shams.d.ts create mode 100644 node_modules/has-symbols/shams.js create mode 100644 node_modules/has-symbols/test/index.js create mode 100644 node_modules/has-symbols/test/shams/core-js.js create mode 100644 node_modules/has-symbols/test/shams/get-own-property-symbols.js create mode 100644 node_modules/has-symbols/test/tests.js create mode 100644 node_modules/has-symbols/tsconfig.json create mode 100644 node_modules/has-tostringtag/.eslintrc create mode 100644 node_modules/has-tostringtag/.github/FUNDING.yml create mode 100644 node_modules/has-tostringtag/.nycrc create mode 100644 node_modules/has-tostringtag/CHANGELOG.md create mode 100644 node_modules/has-tostringtag/LICENSE create mode 100644 node_modules/has-tostringtag/README.md create mode 100644 node_modules/has-tostringtag/index.d.ts create mode 100644 node_modules/has-tostringtag/index.js create mode 100644 node_modules/has-tostringtag/package.json create mode 100644 node_modules/has-tostringtag/shams.d.ts create mode 100644 node_modules/has-tostringtag/shams.js create mode 100644 node_modules/has-tostringtag/test/index.js create mode 100644 node_modules/has-tostringtag/test/shams/core-js.js create mode 100644 node_modules/has-tostringtag/test/shams/get-own-property-symbols.js create mode 100644 node_modules/has-tostringtag/test/tests.js create mode 100644 node_modules/has-tostringtag/tsconfig.json create mode 100644 node_modules/hasown/.eslintrc create mode 100644 node_modules/hasown/.github/FUNDING.yml create mode 100644 node_modules/hasown/.nycrc create mode 100644 node_modules/hasown/CHANGELOG.md create mode 100644 node_modules/hasown/LICENSE create mode 100644 node_modules/hasown/README.md create mode 100644 node_modules/hasown/index.d.ts create mode 100644 node_modules/hasown/index.js create mode 100644 node_modules/hasown/package.json create mode 100644 node_modules/hasown/tsconfig.json create mode 100644 node_modules/html-entities/LICENSE create mode 100644 node_modules/html-entities/README.md create mode 100644 node_modules/html-entities/dist/commonjs/index.d.ts create mode 100644 node_modules/html-entities/dist/commonjs/index.js create mode 100644 node_modules/html-entities/dist/commonjs/index.js.flow create mode 100644 node_modules/html-entities/dist/commonjs/index.js.map create mode 100644 node_modules/html-entities/dist/commonjs/named-references.js create mode 100644 node_modules/html-entities/dist/commonjs/named-references.js.map create mode 100644 node_modules/html-entities/dist/commonjs/numeric-unicode-map.js create mode 100644 node_modules/html-entities/dist/commonjs/numeric-unicode-map.js.map create mode 100644 node_modules/html-entities/dist/commonjs/package.json create mode 100644 node_modules/html-entities/dist/commonjs/surrogate-pairs.js create mode 100644 node_modules/html-entities/dist/commonjs/surrogate-pairs.js.map create mode 100644 node_modules/html-entities/dist/esm/index.d.ts create mode 100644 node_modules/html-entities/dist/esm/index.js create mode 100644 node_modules/html-entities/dist/esm/index.js.map create mode 100644 node_modules/html-entities/dist/esm/named-references.js create mode 100644 node_modules/html-entities/dist/esm/named-references.js.map create mode 100644 node_modules/html-entities/dist/esm/numeric-unicode-map.js create mode 100644 node_modules/html-entities/dist/esm/numeric-unicode-map.js.map create mode 100644 node_modules/html-entities/dist/esm/package.json create mode 100644 node_modules/html-entities/dist/esm/surrogate-pairs.js create mode 100644 node_modules/html-entities/dist/esm/surrogate-pairs.js.map create mode 100644 node_modules/html-entities/package.json create mode 100644 node_modules/html-entities/src/index.ts create mode 100644 node_modules/html-entities/src/named-references.ts create mode 100644 node_modules/html-entities/src/numeric-unicode-map.ts create mode 100644 node_modules/html-entities/src/surrogate-pairs.ts create mode 100644 node_modules/http-parser-js/LICENSE.md create mode 100644 node_modules/http-parser-js/README.md create mode 100644 node_modules/http-parser-js/http-parser.d.ts create mode 100644 node_modules/http-parser-js/http-parser.js create mode 100644 node_modules/http-parser-js/package.json create mode 100644 node_modules/http-proxy-agent/README.md create mode 100644 node_modules/http-proxy-agent/dist/agent.d.ts create mode 100644 node_modules/http-proxy-agent/dist/agent.js create mode 100644 node_modules/http-proxy-agent/dist/agent.js.map create mode 100644 node_modules/http-proxy-agent/dist/index.d.ts create mode 100644 node_modules/http-proxy-agent/dist/index.js create mode 100644 node_modules/http-proxy-agent/dist/index.js.map create mode 100644 node_modules/http-proxy-agent/node_modules/agent-base/README.md create mode 100644 node_modules/http-proxy-agent/node_modules/agent-base/dist/src/index.d.ts create mode 100644 node_modules/http-proxy-agent/node_modules/agent-base/dist/src/index.js create mode 100644 node_modules/http-proxy-agent/node_modules/agent-base/dist/src/index.js.map create mode 100644 node_modules/http-proxy-agent/node_modules/agent-base/dist/src/promisify.d.ts create mode 100644 node_modules/http-proxy-agent/node_modules/agent-base/dist/src/promisify.js create mode 100644 node_modules/http-proxy-agent/node_modules/agent-base/dist/src/promisify.js.map create mode 100644 node_modules/http-proxy-agent/node_modules/agent-base/package.json create mode 100644 node_modules/http-proxy-agent/node_modules/agent-base/src/index.ts create mode 100644 node_modules/http-proxy-agent/node_modules/agent-base/src/promisify.ts create mode 100644 node_modules/http-proxy-agent/package.json create mode 100644 node_modules/https-proxy-agent/LICENSE create mode 100644 node_modules/https-proxy-agent/README.md create mode 100644 node_modules/https-proxy-agent/dist/index.d.ts create mode 100644 node_modules/https-proxy-agent/dist/index.d.ts.map create mode 100644 node_modules/https-proxy-agent/dist/index.js create mode 100644 node_modules/https-proxy-agent/dist/index.js.map create mode 100644 node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts create mode 100644 node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts.map create mode 100644 node_modules/https-proxy-agent/dist/parse-proxy-response.js create mode 100644 node_modules/https-proxy-agent/dist/parse-proxy-response.js.map create mode 100644 node_modules/https-proxy-agent/package.json create mode 100644 node_modules/inherits/LICENSE create mode 100644 node_modules/inherits/README.md create mode 100644 node_modules/inherits/inherits.js create mode 100644 node_modules/inherits/inherits_browser.js create mode 100644 node_modules/inherits/package.json create mode 100644 node_modules/is-fullwidth-code-point/index.d.ts create mode 100644 node_modules/is-fullwidth-code-point/index.js create mode 100644 node_modules/is-fullwidth-code-point/license create mode 100644 node_modules/is-fullwidth-code-point/package.json create mode 100644 node_modules/is-fullwidth-code-point/readme.md create mode 100644 node_modules/is-stream/index.d.ts create mode 100644 node_modules/is-stream/index.js create mode 100644 node_modules/is-stream/license create mode 100644 node_modules/is-stream/package.json create mode 100644 node_modules/is-stream/readme.md create mode 100644 node_modules/jose/LICENSE.md create mode 100644 node_modules/jose/README.md create mode 100644 node_modules/jose/dist/browser/index.js create mode 100644 node_modules/jose/dist/browser/jwe/compact/decrypt.js create mode 100644 node_modules/jose/dist/browser/jwe/compact/encrypt.js create mode 100644 node_modules/jose/dist/browser/jwe/flattened/decrypt.js create mode 100644 node_modules/jose/dist/browser/jwe/flattened/encrypt.js create mode 100644 node_modules/jose/dist/browser/jwe/general/decrypt.js create mode 100644 node_modules/jose/dist/browser/jwe/general/encrypt.js create mode 100644 node_modules/jose/dist/browser/jwk/embedded.js create mode 100644 node_modules/jose/dist/browser/jwk/thumbprint.js create mode 100644 node_modules/jose/dist/browser/jwks/local.js create mode 100644 node_modules/jose/dist/browser/jwks/remote.js create mode 100644 node_modules/jose/dist/browser/jws/compact/sign.js create mode 100644 node_modules/jose/dist/browser/jws/compact/verify.js create mode 100644 node_modules/jose/dist/browser/jws/flattened/sign.js create mode 100644 node_modules/jose/dist/browser/jws/flattened/verify.js create mode 100644 node_modules/jose/dist/browser/jws/general/sign.js create mode 100644 node_modules/jose/dist/browser/jws/general/verify.js create mode 100644 node_modules/jose/dist/browser/jwt/decrypt.js create mode 100644 node_modules/jose/dist/browser/jwt/encrypt.js create mode 100644 node_modules/jose/dist/browser/jwt/produce.js create mode 100644 node_modules/jose/dist/browser/jwt/sign.js create mode 100644 node_modules/jose/dist/browser/jwt/unsecured.js create mode 100644 node_modules/jose/dist/browser/jwt/verify.js create mode 100644 node_modules/jose/dist/browser/key/export.js create mode 100644 node_modules/jose/dist/browser/key/generate_key_pair.js create mode 100644 node_modules/jose/dist/browser/key/generate_secret.js create mode 100644 node_modules/jose/dist/browser/key/import.js create mode 100644 node_modules/jose/dist/browser/lib/aesgcmkw.js create mode 100644 node_modules/jose/dist/browser/lib/buffer_utils.js create mode 100644 node_modules/jose/dist/browser/lib/cek.js create mode 100644 node_modules/jose/dist/browser/lib/check_iv_length.js create mode 100644 node_modules/jose/dist/browser/lib/check_key_type.js create mode 100644 node_modules/jose/dist/browser/lib/check_p2s.js create mode 100644 node_modules/jose/dist/browser/lib/crypto_key.js create mode 100644 node_modules/jose/dist/browser/lib/decrypt_key_management.js create mode 100644 node_modules/jose/dist/browser/lib/encrypt_key_management.js create mode 100644 node_modules/jose/dist/browser/lib/epoch.js create mode 100644 node_modules/jose/dist/browser/lib/format_pem.js create mode 100644 node_modules/jose/dist/browser/lib/invalid_key_input.js create mode 100644 node_modules/jose/dist/browser/lib/is_disjoint.js create mode 100644 node_modules/jose/dist/browser/lib/is_object.js create mode 100644 node_modules/jose/dist/browser/lib/iv.js create mode 100644 node_modules/jose/dist/browser/lib/jwt_claims_set.js create mode 100644 node_modules/jose/dist/browser/lib/secs.js create mode 100644 node_modules/jose/dist/browser/lib/validate_algorithms.js create mode 100644 node_modules/jose/dist/browser/lib/validate_crit.js create mode 100644 node_modules/jose/dist/browser/package.json create mode 100644 node_modules/jose/dist/browser/runtime/aeskw.js create mode 100644 node_modules/jose/dist/browser/runtime/asn1.js create mode 100644 node_modules/jose/dist/browser/runtime/base64url.js create mode 100644 node_modules/jose/dist/browser/runtime/bogus.js create mode 100644 node_modules/jose/dist/browser/runtime/check_cek_length.js create mode 100644 node_modules/jose/dist/browser/runtime/check_key_length.js create mode 100644 node_modules/jose/dist/browser/runtime/decrypt.js create mode 100644 node_modules/jose/dist/browser/runtime/digest.js create mode 100644 node_modules/jose/dist/browser/runtime/ecdhes.js create mode 100644 node_modules/jose/dist/browser/runtime/encrypt.js create mode 100644 node_modules/jose/dist/browser/runtime/fetch_jwks.js create mode 100644 node_modules/jose/dist/browser/runtime/generate.js create mode 100644 node_modules/jose/dist/browser/runtime/get_sign_verify_key.js create mode 100644 node_modules/jose/dist/browser/runtime/is_key_like.js create mode 100644 node_modules/jose/dist/browser/runtime/jwk_to_key.js create mode 100644 node_modules/jose/dist/browser/runtime/key_to_jwk.js create mode 100644 node_modules/jose/dist/browser/runtime/pbes2kw.js create mode 100644 node_modules/jose/dist/browser/runtime/random.js create mode 100644 node_modules/jose/dist/browser/runtime/rsaes.js create mode 100644 node_modules/jose/dist/browser/runtime/runtime.js create mode 100644 node_modules/jose/dist/browser/runtime/sign.js create mode 100644 node_modules/jose/dist/browser/runtime/subtle_dsa.js create mode 100644 node_modules/jose/dist/browser/runtime/subtle_rsaes.js create mode 100644 node_modules/jose/dist/browser/runtime/timing_safe_equal.js create mode 100644 node_modules/jose/dist/browser/runtime/verify.js create mode 100644 node_modules/jose/dist/browser/runtime/webcrypto.js create mode 100644 node_modules/jose/dist/browser/runtime/zlib.js create mode 100644 node_modules/jose/dist/browser/util/base64url.js create mode 100644 node_modules/jose/dist/browser/util/decode_jwt.js create mode 100644 node_modules/jose/dist/browser/util/decode_protected_header.js create mode 100644 node_modules/jose/dist/browser/util/errors.js create mode 100644 node_modules/jose/dist/browser/util/runtime.js create mode 100644 node_modules/jose/dist/node/cjs/index.js create mode 100644 node_modules/jose/dist/node/cjs/jwe/compact/decrypt.js create mode 100644 node_modules/jose/dist/node/cjs/jwe/compact/encrypt.js create mode 100644 node_modules/jose/dist/node/cjs/jwe/flattened/decrypt.js create mode 100644 node_modules/jose/dist/node/cjs/jwe/flattened/encrypt.js create mode 100644 node_modules/jose/dist/node/cjs/jwe/general/decrypt.js create mode 100644 node_modules/jose/dist/node/cjs/jwe/general/encrypt.js create mode 100644 node_modules/jose/dist/node/cjs/jwk/embedded.js create mode 100644 node_modules/jose/dist/node/cjs/jwk/thumbprint.js create mode 100644 node_modules/jose/dist/node/cjs/jwks/local.js create mode 100644 node_modules/jose/dist/node/cjs/jwks/remote.js create mode 100644 node_modules/jose/dist/node/cjs/jws/compact/sign.js create mode 100644 node_modules/jose/dist/node/cjs/jws/compact/verify.js create mode 100644 node_modules/jose/dist/node/cjs/jws/flattened/sign.js create mode 100644 node_modules/jose/dist/node/cjs/jws/flattened/verify.js create mode 100644 node_modules/jose/dist/node/cjs/jws/general/sign.js create mode 100644 node_modules/jose/dist/node/cjs/jws/general/verify.js create mode 100644 node_modules/jose/dist/node/cjs/jwt/decrypt.js create mode 100644 node_modules/jose/dist/node/cjs/jwt/encrypt.js create mode 100644 node_modules/jose/dist/node/cjs/jwt/produce.js create mode 100644 node_modules/jose/dist/node/cjs/jwt/sign.js create mode 100644 node_modules/jose/dist/node/cjs/jwt/unsecured.js create mode 100644 node_modules/jose/dist/node/cjs/jwt/verify.js create mode 100644 node_modules/jose/dist/node/cjs/key/export.js create mode 100644 node_modules/jose/dist/node/cjs/key/generate_key_pair.js create mode 100644 node_modules/jose/dist/node/cjs/key/generate_secret.js create mode 100644 node_modules/jose/dist/node/cjs/key/import.js create mode 100644 node_modules/jose/dist/node/cjs/lib/aesgcmkw.js create mode 100644 node_modules/jose/dist/node/cjs/lib/buffer_utils.js create mode 100644 node_modules/jose/dist/node/cjs/lib/cek.js create mode 100644 node_modules/jose/dist/node/cjs/lib/check_iv_length.js create mode 100644 node_modules/jose/dist/node/cjs/lib/check_key_type.js create mode 100644 node_modules/jose/dist/node/cjs/lib/check_p2s.js create mode 100644 node_modules/jose/dist/node/cjs/lib/crypto_key.js create mode 100644 node_modules/jose/dist/node/cjs/lib/decrypt_key_management.js create mode 100644 node_modules/jose/dist/node/cjs/lib/encrypt_key_management.js create mode 100644 node_modules/jose/dist/node/cjs/lib/epoch.js create mode 100644 node_modules/jose/dist/node/cjs/lib/invalid_key_input.js create mode 100644 node_modules/jose/dist/node/cjs/lib/is_disjoint.js create mode 100644 node_modules/jose/dist/node/cjs/lib/is_object.js create mode 100644 node_modules/jose/dist/node/cjs/lib/iv.js create mode 100644 node_modules/jose/dist/node/cjs/lib/jwt_claims_set.js create mode 100644 node_modules/jose/dist/node/cjs/lib/secs.js create mode 100644 node_modules/jose/dist/node/cjs/lib/validate_algorithms.js create mode 100644 node_modules/jose/dist/node/cjs/lib/validate_crit.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/aeskw.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/asn1.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/asn1_sequence_decoder.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/asn1_sequence_encoder.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/base64url.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/cbc_tag.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/check_cek_length.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/check_modulus_length.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/ciphers.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/decrypt.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/digest.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/dsa_digest.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/ecdhes.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/encrypt.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/fetch_jwks.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/flags.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/generate.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/get_named_curve.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/get_sign_verify_key.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/hmac_digest.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/is_key_like.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/is_key_object.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/jwk_to_key.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/key_to_jwk.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/node_key.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/pbes2kw.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/random.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/rsaes.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/runtime.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/sign.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/timing_safe_equal.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/verify.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/webcrypto.js create mode 100644 node_modules/jose/dist/node/cjs/runtime/zlib.js create mode 100644 node_modules/jose/dist/node/cjs/util/base64url.js create mode 100644 node_modules/jose/dist/node/cjs/util/decode_jwt.js create mode 100644 node_modules/jose/dist/node/cjs/util/decode_protected_header.js create mode 100644 node_modules/jose/dist/node/cjs/util/errors.js create mode 100644 node_modules/jose/dist/node/cjs/util/runtime.js create mode 100644 node_modules/jose/dist/node/esm/index.js create mode 100644 node_modules/jose/dist/node/esm/jwe/compact/decrypt.js create mode 100644 node_modules/jose/dist/node/esm/jwe/compact/encrypt.js create mode 100644 node_modules/jose/dist/node/esm/jwe/flattened/decrypt.js create mode 100644 node_modules/jose/dist/node/esm/jwe/flattened/encrypt.js create mode 100644 node_modules/jose/dist/node/esm/jwe/general/decrypt.js create mode 100644 node_modules/jose/dist/node/esm/jwe/general/encrypt.js create mode 100644 node_modules/jose/dist/node/esm/jwk/embedded.js create mode 100644 node_modules/jose/dist/node/esm/jwk/thumbprint.js create mode 100644 node_modules/jose/dist/node/esm/jwks/local.js create mode 100644 node_modules/jose/dist/node/esm/jwks/remote.js create mode 100644 node_modules/jose/dist/node/esm/jws/compact/sign.js create mode 100644 node_modules/jose/dist/node/esm/jws/compact/verify.js create mode 100644 node_modules/jose/dist/node/esm/jws/flattened/sign.js create mode 100644 node_modules/jose/dist/node/esm/jws/flattened/verify.js create mode 100644 node_modules/jose/dist/node/esm/jws/general/sign.js create mode 100644 node_modules/jose/dist/node/esm/jws/general/verify.js create mode 100644 node_modules/jose/dist/node/esm/jwt/decrypt.js create mode 100644 node_modules/jose/dist/node/esm/jwt/encrypt.js create mode 100644 node_modules/jose/dist/node/esm/jwt/produce.js create mode 100644 node_modules/jose/dist/node/esm/jwt/sign.js create mode 100644 node_modules/jose/dist/node/esm/jwt/unsecured.js create mode 100644 node_modules/jose/dist/node/esm/jwt/verify.js create mode 100644 node_modules/jose/dist/node/esm/key/export.js create mode 100644 node_modules/jose/dist/node/esm/key/generate_key_pair.js create mode 100644 node_modules/jose/dist/node/esm/key/generate_secret.js create mode 100644 node_modules/jose/dist/node/esm/key/import.js create mode 100644 node_modules/jose/dist/node/esm/lib/aesgcmkw.js create mode 100644 node_modules/jose/dist/node/esm/lib/buffer_utils.js create mode 100644 node_modules/jose/dist/node/esm/lib/cek.js create mode 100644 node_modules/jose/dist/node/esm/lib/check_iv_length.js create mode 100644 node_modules/jose/dist/node/esm/lib/check_key_type.js create mode 100644 node_modules/jose/dist/node/esm/lib/check_p2s.js create mode 100644 node_modules/jose/dist/node/esm/lib/crypto_key.js create mode 100644 node_modules/jose/dist/node/esm/lib/decrypt_key_management.js create mode 100644 node_modules/jose/dist/node/esm/lib/encrypt_key_management.js create mode 100644 node_modules/jose/dist/node/esm/lib/epoch.js create mode 100644 node_modules/jose/dist/node/esm/lib/invalid_key_input.js create mode 100644 node_modules/jose/dist/node/esm/lib/is_disjoint.js create mode 100644 node_modules/jose/dist/node/esm/lib/is_object.js create mode 100644 node_modules/jose/dist/node/esm/lib/iv.js create mode 100644 node_modules/jose/dist/node/esm/lib/jwt_claims_set.js create mode 100644 node_modules/jose/dist/node/esm/lib/secs.js create mode 100644 node_modules/jose/dist/node/esm/lib/validate_algorithms.js create mode 100644 node_modules/jose/dist/node/esm/lib/validate_crit.js create mode 100644 node_modules/jose/dist/node/esm/package.json create mode 100644 node_modules/jose/dist/node/esm/runtime/aeskw.js create mode 100644 node_modules/jose/dist/node/esm/runtime/asn1.js create mode 100644 node_modules/jose/dist/node/esm/runtime/asn1_sequence_decoder.js create mode 100644 node_modules/jose/dist/node/esm/runtime/asn1_sequence_encoder.js create mode 100644 node_modules/jose/dist/node/esm/runtime/base64url.js create mode 100644 node_modules/jose/dist/node/esm/runtime/cbc_tag.js create mode 100644 node_modules/jose/dist/node/esm/runtime/check_cek_length.js create mode 100644 node_modules/jose/dist/node/esm/runtime/check_modulus_length.js create mode 100644 node_modules/jose/dist/node/esm/runtime/ciphers.js create mode 100644 node_modules/jose/dist/node/esm/runtime/decrypt.js create mode 100644 node_modules/jose/dist/node/esm/runtime/digest.js create mode 100644 node_modules/jose/dist/node/esm/runtime/dsa_digest.js create mode 100644 node_modules/jose/dist/node/esm/runtime/ecdhes.js create mode 100644 node_modules/jose/dist/node/esm/runtime/encrypt.js create mode 100644 node_modules/jose/dist/node/esm/runtime/fetch_jwks.js create mode 100644 node_modules/jose/dist/node/esm/runtime/flags.js create mode 100644 node_modules/jose/dist/node/esm/runtime/generate.js create mode 100644 node_modules/jose/dist/node/esm/runtime/get_named_curve.js create mode 100644 node_modules/jose/dist/node/esm/runtime/get_sign_verify_key.js create mode 100644 node_modules/jose/dist/node/esm/runtime/hmac_digest.js create mode 100644 node_modules/jose/dist/node/esm/runtime/is_key_like.js create mode 100644 node_modules/jose/dist/node/esm/runtime/is_key_object.js create mode 100644 node_modules/jose/dist/node/esm/runtime/jwk_to_key.js create mode 100644 node_modules/jose/dist/node/esm/runtime/key_to_jwk.js create mode 100644 node_modules/jose/dist/node/esm/runtime/node_key.js create mode 100644 node_modules/jose/dist/node/esm/runtime/pbes2kw.js create mode 100644 node_modules/jose/dist/node/esm/runtime/random.js create mode 100644 node_modules/jose/dist/node/esm/runtime/rsaes.js create mode 100644 node_modules/jose/dist/node/esm/runtime/runtime.js create mode 100644 node_modules/jose/dist/node/esm/runtime/sign.js create mode 100644 node_modules/jose/dist/node/esm/runtime/timing_safe_equal.js create mode 100644 node_modules/jose/dist/node/esm/runtime/verify.js create mode 100644 node_modules/jose/dist/node/esm/runtime/webcrypto.js create mode 100644 node_modules/jose/dist/node/esm/runtime/zlib.js create mode 100644 node_modules/jose/dist/node/esm/util/base64url.js create mode 100644 node_modules/jose/dist/node/esm/util/decode_jwt.js create mode 100644 node_modules/jose/dist/node/esm/util/decode_protected_header.js create mode 100644 node_modules/jose/dist/node/esm/util/errors.js create mode 100644 node_modules/jose/dist/node/esm/util/runtime.js create mode 100644 node_modules/jose/dist/types/index.d.ts create mode 100644 node_modules/jose/dist/types/jwe/compact/decrypt.d.ts create mode 100644 node_modules/jose/dist/types/jwe/compact/encrypt.d.ts create mode 100644 node_modules/jose/dist/types/jwe/flattened/decrypt.d.ts create mode 100644 node_modules/jose/dist/types/jwe/flattened/encrypt.d.ts create mode 100644 node_modules/jose/dist/types/jwe/general/decrypt.d.ts create mode 100644 node_modules/jose/dist/types/jwe/general/encrypt.d.ts create mode 100644 node_modules/jose/dist/types/jwk/embedded.d.ts create mode 100644 node_modules/jose/dist/types/jwk/thumbprint.d.ts create mode 100644 node_modules/jose/dist/types/jwks/local.d.ts create mode 100644 node_modules/jose/dist/types/jwks/remote.d.ts create mode 100644 node_modules/jose/dist/types/jws/compact/sign.d.ts create mode 100644 node_modules/jose/dist/types/jws/compact/verify.d.ts create mode 100644 node_modules/jose/dist/types/jws/flattened/sign.d.ts create mode 100644 node_modules/jose/dist/types/jws/flattened/verify.d.ts create mode 100644 node_modules/jose/dist/types/jws/general/sign.d.ts create mode 100644 node_modules/jose/dist/types/jws/general/verify.d.ts create mode 100644 node_modules/jose/dist/types/jwt/decrypt.d.ts create mode 100644 node_modules/jose/dist/types/jwt/encrypt.d.ts create mode 100644 node_modules/jose/dist/types/jwt/produce.d.ts create mode 100644 node_modules/jose/dist/types/jwt/sign.d.ts create mode 100644 node_modules/jose/dist/types/jwt/unsecured.d.ts create mode 100644 node_modules/jose/dist/types/jwt/verify.d.ts create mode 100644 node_modules/jose/dist/types/key/export.d.ts create mode 100644 node_modules/jose/dist/types/key/generate_key_pair.d.ts create mode 100644 node_modules/jose/dist/types/key/generate_secret.d.ts create mode 100644 node_modules/jose/dist/types/key/import.d.ts create mode 100644 node_modules/jose/dist/types/types.d.ts create mode 100644 node_modules/jose/dist/types/util/base64url.d.ts create mode 100644 node_modules/jose/dist/types/util/decode_jwt.d.ts create mode 100644 node_modules/jose/dist/types/util/decode_protected_header.d.ts create mode 100644 node_modules/jose/dist/types/util/errors.d.ts create mode 100644 node_modules/jose/dist/types/util/runtime.d.ts create mode 100644 node_modules/jose/package.json create mode 100644 node_modules/json-bigint/LICENSE create mode 100644 node_modules/json-bigint/README.md create mode 100644 node_modules/json-bigint/index.js create mode 100644 node_modules/json-bigint/lib/parse.js create mode 100644 node_modules/json-bigint/lib/stringify.js create mode 100644 node_modules/json-bigint/package.json create mode 100644 node_modules/jsonwebtoken/LICENSE create mode 100644 node_modules/jsonwebtoken/README.md create mode 100644 node_modules/jsonwebtoken/decode.js create mode 100644 node_modules/jsonwebtoken/index.js create mode 100644 node_modules/jsonwebtoken/lib/JsonWebTokenError.js create mode 100644 node_modules/jsonwebtoken/lib/NotBeforeError.js create mode 100644 node_modules/jsonwebtoken/lib/TokenExpiredError.js create mode 100644 node_modules/jsonwebtoken/lib/asymmetricKeyDetailsSupported.js create mode 100644 node_modules/jsonwebtoken/lib/psSupported.js create mode 100644 node_modules/jsonwebtoken/lib/rsaPssKeyDetailsSupported.js create mode 100644 node_modules/jsonwebtoken/lib/timespan.js create mode 100644 node_modules/jsonwebtoken/lib/validateAsymmetricKey.js create mode 100644 node_modules/jsonwebtoken/package.json create mode 100644 node_modules/jsonwebtoken/sign.js create mode 100644 node_modules/jsonwebtoken/verify.js create mode 100644 node_modules/jwa/LICENSE create mode 100644 node_modules/jwa/README.md create mode 100644 node_modules/jwa/index.js create mode 100644 node_modules/jwa/opslevel.yml create mode 100644 node_modules/jwa/package.json create mode 100644 node_modules/jwks-rsa/LICENSE create mode 100644 node_modules/jwks-rsa/README.md create mode 100644 node_modules/jwks-rsa/index.d.ts create mode 100644 node_modules/jwks-rsa/package.json create mode 100644 node_modules/jwks-rsa/src/JwksClient.js create mode 100644 node_modules/jwks-rsa/src/errors/ArgumentError.js create mode 100644 node_modules/jwks-rsa/src/errors/JwksError.js create mode 100644 node_modules/jwks-rsa/src/errors/JwksRateLimitError.js create mode 100644 node_modules/jwks-rsa/src/errors/SigningKeyNotFoundError.js create mode 100644 node_modules/jwks-rsa/src/errors/index.js create mode 100644 node_modules/jwks-rsa/src/index.js create mode 100644 node_modules/jwks-rsa/src/integrations/config.js create mode 100644 node_modules/jwks-rsa/src/integrations/express.js create mode 100644 node_modules/jwks-rsa/src/integrations/hapi.js create mode 100644 node_modules/jwks-rsa/src/integrations/koa.js create mode 100644 node_modules/jwks-rsa/src/integrations/passport.js create mode 100644 node_modules/jwks-rsa/src/utils.js create mode 100644 node_modules/jwks-rsa/src/wrappers/cache.js create mode 100644 node_modules/jwks-rsa/src/wrappers/callbackSupport.js create mode 100644 node_modules/jwks-rsa/src/wrappers/index.js create mode 100644 node_modules/jwks-rsa/src/wrappers/interceptor.js create mode 100644 node_modules/jwks-rsa/src/wrappers/rateLimit.js create mode 100644 node_modules/jwks-rsa/src/wrappers/request.js create mode 100644 node_modules/jws/CHANGELOG.md create mode 100644 node_modules/jws/LICENSE create mode 100644 node_modules/jws/index.js create mode 100644 node_modules/jws/lib/data-stream.js create mode 100644 node_modules/jws/lib/sign-stream.js create mode 100644 node_modules/jws/lib/tostring.js create mode 100644 node_modules/jws/lib/verify-stream.js create mode 100644 node_modules/jws/opslevel.yml create mode 100644 node_modules/jws/package.json create mode 100644 node_modules/jws/readme.md create mode 100644 node_modules/limiter/.travis.yml create mode 100644 node_modules/limiter/LICENSE.txt create mode 100644 node_modules/limiter/README.md create mode 100644 node_modules/limiter/bower.json create mode 100644 node_modules/limiter/index.d.ts create mode 100644 node_modules/limiter/index.js create mode 100644 node_modules/limiter/lib/clock.js create mode 100644 node_modules/limiter/lib/rateLimiter.js create mode 100644 node_modules/limiter/lib/tokenBucket.js create mode 100644 node_modules/limiter/package.json create mode 100644 node_modules/limiter/test/ratelimiter-test.js create mode 100644 node_modules/limiter/test/tokenbucket-test.js create mode 100644 node_modules/lodash.camelcase/LICENSE create mode 100644 node_modules/lodash.camelcase/README.md create mode 100644 node_modules/lodash.camelcase/index.js create mode 100644 node_modules/lodash.camelcase/package.json create mode 100644 node_modules/lodash.clonedeep/LICENSE create mode 100644 node_modules/lodash.clonedeep/README.md create mode 100644 node_modules/lodash.clonedeep/index.js create mode 100644 node_modules/lodash.clonedeep/package.json create mode 100644 node_modules/lodash.includes/LICENSE create mode 100644 node_modules/lodash.includes/README.md create mode 100644 node_modules/lodash.includes/index.js create mode 100644 node_modules/lodash.includes/package.json create mode 100644 node_modules/lodash.isboolean/LICENSE create mode 100644 node_modules/lodash.isboolean/README.md create mode 100644 node_modules/lodash.isboolean/index.js create mode 100644 node_modules/lodash.isboolean/package.json create mode 100644 node_modules/lodash.isinteger/LICENSE create mode 100644 node_modules/lodash.isinteger/README.md create mode 100644 node_modules/lodash.isinteger/index.js create mode 100644 node_modules/lodash.isinteger/package.json create mode 100644 node_modules/lodash.isnumber/LICENSE create mode 100644 node_modules/lodash.isnumber/README.md create mode 100644 node_modules/lodash.isnumber/index.js create mode 100644 node_modules/lodash.isnumber/package.json create mode 100644 node_modules/lodash.isplainobject/LICENSE create mode 100644 node_modules/lodash.isplainobject/README.md create mode 100644 node_modules/lodash.isplainobject/index.js create mode 100644 node_modules/lodash.isplainobject/package.json create mode 100644 node_modules/lodash.isstring/LICENSE create mode 100644 node_modules/lodash.isstring/README.md create mode 100644 node_modules/lodash.isstring/index.js create mode 100644 node_modules/lodash.isstring/package.json create mode 100644 node_modules/lodash.once/LICENSE create mode 100644 node_modules/lodash.once/README.md create mode 100644 node_modules/lodash.once/index.js create mode 100644 node_modules/lodash.once/package.json create mode 100644 node_modules/long/LICENSE create mode 100644 node_modules/long/README.md create mode 100644 node_modules/long/index.d.ts create mode 100644 node_modules/long/index.js create mode 100644 node_modules/long/package.json create mode 100644 node_modules/long/types.d.ts create mode 100644 node_modules/long/umd/index.d.ts create mode 100644 node_modules/long/umd/index.js create mode 100644 node_modules/long/umd/package.json create mode 100644 node_modules/long/umd/types.d.ts create mode 100644 node_modules/lru-cache/LICENSE create mode 100644 node_modules/lru-cache/README.md create mode 100644 node_modules/lru-cache/index.js create mode 100644 node_modules/lru-cache/package.json create mode 100644 node_modules/lru-memoizer/.jshintrc create mode 100644 node_modules/lru-memoizer/LICENSE create mode 100644 node_modules/lru-memoizer/README.md create mode 100644 node_modules/lru-memoizer/lib/async.d.ts create mode 100644 node_modules/lru-memoizer/lib/async.js create mode 100644 node_modules/lru-memoizer/lib/freeze.d.ts create mode 100644 node_modules/lru-memoizer/lib/freeze.js create mode 100644 node_modules/lru-memoizer/lib/index.d.ts create mode 100644 node_modules/lru-memoizer/lib/index.js create mode 100644 node_modules/lru-memoizer/lib/sync.d.ts create mode 100644 node_modules/lru-memoizer/lib/sync.js create mode 100644 node_modules/lru-memoizer/lib/util.d.ts create mode 100644 node_modules/lru-memoizer/lib/util.js create mode 100644 node_modules/lru-memoizer/package.json create mode 100644 node_modules/lru-memoizer/test/lru-memoizer.bypass.test.js create mode 100644 node_modules/lru-memoizer/test/lru-memoizer.clone.test.js create mode 100644 node_modules/lru-memoizer/test/lru-memoizer.disable.test.js create mode 100644 node_modules/lru-memoizer/test/lru-memoizer.events.test.js create mode 100644 node_modules/lru-memoizer/test/lru-memoizer.freeze.test.js create mode 100644 node_modules/lru-memoizer/test/lru-memoizer.itemmaxage.test.js create mode 100644 node_modules/lru-memoizer/test/lru-memoizer.lock.test.js create mode 100644 node_modules/lru-memoizer/test/lru-memoizer.nokey.test.js create mode 100644 node_modules/lru-memoizer/test/lru-memoizer.queumaxage.test.js create mode 100644 node_modules/lru-memoizer/test/lru-memoizer.sync.clone.test.js create mode 100644 node_modules/lru-memoizer/test/lru-memoizer.sync.events.test.js create mode 100644 node_modules/lru-memoizer/test/lru-memoizer.sync.freeze.js create mode 100644 node_modules/lru-memoizer/test/lru-memoizer.sync.test.js create mode 100644 node_modules/lru-memoizer/test/lru-memoizer.test.js create mode 100644 node_modules/lru-memoizer/tsconfig.json create mode 100644 node_modules/math-intrinsics/.eslintrc create mode 100644 node_modules/math-intrinsics/.github/FUNDING.yml create mode 100644 node_modules/math-intrinsics/CHANGELOG.md create mode 100644 node_modules/math-intrinsics/LICENSE create mode 100644 node_modules/math-intrinsics/README.md create mode 100644 node_modules/math-intrinsics/abs.d.ts create mode 100644 node_modules/math-intrinsics/abs.js create mode 100644 node_modules/math-intrinsics/constants/maxArrayLength.d.ts create mode 100644 node_modules/math-intrinsics/constants/maxArrayLength.js create mode 100644 node_modules/math-intrinsics/constants/maxSafeInteger.d.ts create mode 100644 node_modules/math-intrinsics/constants/maxSafeInteger.js create mode 100644 node_modules/math-intrinsics/constants/maxValue.d.ts create mode 100644 node_modules/math-intrinsics/constants/maxValue.js create mode 100644 node_modules/math-intrinsics/floor.d.ts create mode 100644 node_modules/math-intrinsics/floor.js create mode 100644 node_modules/math-intrinsics/isFinite.d.ts create mode 100644 node_modules/math-intrinsics/isFinite.js create mode 100644 node_modules/math-intrinsics/isInteger.d.ts create mode 100644 node_modules/math-intrinsics/isInteger.js create mode 100644 node_modules/math-intrinsics/isNaN.d.ts create mode 100644 node_modules/math-intrinsics/isNaN.js create mode 100644 node_modules/math-intrinsics/isNegativeZero.d.ts create mode 100644 node_modules/math-intrinsics/isNegativeZero.js create mode 100644 node_modules/math-intrinsics/max.d.ts create mode 100644 node_modules/math-intrinsics/max.js create mode 100644 node_modules/math-intrinsics/min.d.ts create mode 100644 node_modules/math-intrinsics/min.js create mode 100644 node_modules/math-intrinsics/mod.d.ts create mode 100644 node_modules/math-intrinsics/mod.js create mode 100644 node_modules/math-intrinsics/package.json create mode 100644 node_modules/math-intrinsics/pow.d.ts create mode 100644 node_modules/math-intrinsics/pow.js create mode 100644 node_modules/math-intrinsics/round.d.ts create mode 100644 node_modules/math-intrinsics/round.js create mode 100644 node_modules/math-intrinsics/sign.d.ts create mode 100644 node_modules/math-intrinsics/sign.js create mode 100644 node_modules/math-intrinsics/test/index.js create mode 100644 node_modules/math-intrinsics/tsconfig.json create mode 100644 node_modules/mime-db/HISTORY.md create mode 100644 node_modules/mime-db/LICENSE create mode 100644 node_modules/mime-db/README.md create mode 100644 node_modules/mime-db/db.json create mode 100644 node_modules/mime-db/index.js create mode 100644 node_modules/mime-db/package.json create mode 100644 node_modules/mime-types/HISTORY.md create mode 100644 node_modules/mime-types/LICENSE create mode 100644 node_modules/mime-types/README.md create mode 100644 node_modules/mime-types/index.js create mode 100644 node_modules/mime-types/package.json create mode 100644 node_modules/mime/CHANGELOG.md create mode 100644 node_modules/mime/LICENSE create mode 100644 node_modules/mime/Mime.js create mode 100644 node_modules/mime/README.md create mode 100644 node_modules/mime/cli.js create mode 100644 node_modules/mime/index.js create mode 100644 node_modules/mime/lite.js create mode 100644 node_modules/mime/package.json create mode 100644 node_modules/mime/types/other.js create mode 100644 node_modules/mime/types/standard.js create mode 100644 node_modules/ms/index.js create mode 100644 node_modules/ms/license.md create mode 100644 node_modules/ms/package.json create mode 100644 node_modules/ms/readme.md create mode 100644 node_modules/node-fetch/LICENSE.md create mode 100644 node_modules/node-fetch/README.md create mode 100644 node_modules/node-fetch/browser.js create mode 100644 node_modules/node-fetch/lib/index.es.js create mode 100644 node_modules/node-fetch/lib/index.js create mode 100644 node_modules/node-fetch/lib/index.mjs create mode 100644 node_modules/node-fetch/package.json create mode 100644 node_modules/node-forge/LICENSE create mode 100644 node_modules/node-forge/README.md create mode 100644 node_modules/node-forge/dist/forge.all.min.js create mode 100644 node_modules/node-forge/dist/forge.all.min.js.map create mode 100644 node_modules/node-forge/dist/forge.min.js create mode 100644 node_modules/node-forge/dist/forge.min.js.map create mode 100644 node_modules/node-forge/dist/prime.worker.min.js create mode 100644 node_modules/node-forge/dist/prime.worker.min.js.map create mode 100644 node_modules/node-forge/flash/swf/SocketPool.swf create mode 100644 node_modules/node-forge/lib/aes.js create mode 100644 node_modules/node-forge/lib/aesCipherSuites.js create mode 100644 node_modules/node-forge/lib/asn1-validator.js create mode 100644 node_modules/node-forge/lib/asn1.js create mode 100644 node_modules/node-forge/lib/baseN.js create mode 100644 node_modules/node-forge/lib/cipher.js create mode 100644 node_modules/node-forge/lib/cipherModes.js create mode 100644 node_modules/node-forge/lib/des.js create mode 100644 node_modules/node-forge/lib/ed25519.js create mode 100644 node_modules/node-forge/lib/forge.js create mode 100644 node_modules/node-forge/lib/form.js create mode 100644 node_modules/node-forge/lib/hmac.js create mode 100644 node_modules/node-forge/lib/http.js create mode 100644 node_modules/node-forge/lib/index.all.js create mode 100644 node_modules/node-forge/lib/index.js create mode 100644 node_modules/node-forge/lib/jsbn.js create mode 100644 node_modules/node-forge/lib/kem.js create mode 100644 node_modules/node-forge/lib/log.js create mode 100644 node_modules/node-forge/lib/md.all.js create mode 100644 node_modules/node-forge/lib/md.js create mode 100644 node_modules/node-forge/lib/md5.js create mode 100644 node_modules/node-forge/lib/mgf.js create mode 100644 node_modules/node-forge/lib/mgf1.js create mode 100644 node_modules/node-forge/lib/oids.js create mode 100644 node_modules/node-forge/lib/pbe.js create mode 100644 node_modules/node-forge/lib/pbkdf2.js create mode 100644 node_modules/node-forge/lib/pem.js create mode 100644 node_modules/node-forge/lib/pkcs1.js create mode 100644 node_modules/node-forge/lib/pkcs12.js create mode 100644 node_modules/node-forge/lib/pkcs7.js create mode 100644 node_modules/node-forge/lib/pkcs7asn1.js create mode 100644 node_modules/node-forge/lib/pki.js create mode 100644 node_modules/node-forge/lib/prime.js create mode 100644 node_modules/node-forge/lib/prime.worker.js create mode 100644 node_modules/node-forge/lib/prng.js create mode 100644 node_modules/node-forge/lib/pss.js create mode 100644 node_modules/node-forge/lib/random.js create mode 100644 node_modules/node-forge/lib/rc2.js create mode 100644 node_modules/node-forge/lib/rsa.js create mode 100644 node_modules/node-forge/lib/sha1.js create mode 100644 node_modules/node-forge/lib/sha256.js create mode 100644 node_modules/node-forge/lib/sha512.js create mode 100644 node_modules/node-forge/lib/socket.js create mode 100644 node_modules/node-forge/lib/ssh.js create mode 100644 node_modules/node-forge/lib/tls.js create mode 100644 node_modules/node-forge/lib/tlssocket.js create mode 100644 node_modules/node-forge/lib/util.js create mode 100644 node_modules/node-forge/lib/x509.js create mode 100644 node_modules/node-forge/lib/xhr.js create mode 100644 node_modules/node-forge/package.json create mode 100644 node_modules/object-hash/LICENSE create mode 100644 node_modules/object-hash/dist/object_hash.js create mode 100644 node_modules/object-hash/index.js create mode 100644 node_modules/object-hash/package.json create mode 100644 node_modules/object-hash/readme.markdown create mode 100644 node_modules/once/LICENSE create mode 100644 node_modules/once/README.md create mode 100644 node_modules/once/once.js create mode 100644 node_modules/once/package.json create mode 100644 node_modules/p-limit/index.d.ts create mode 100644 node_modules/p-limit/index.js create mode 100644 node_modules/p-limit/license create mode 100644 node_modules/p-limit/package.json create mode 100644 node_modules/p-limit/readme.md create mode 100644 node_modules/proto3-json-serializer/CHANGELOG.md create mode 100644 node_modules/proto3-json-serializer/LICENSE create mode 100644 node_modules/proto3-json-serializer/README.md create mode 100644 node_modules/proto3-json-serializer/build/src/any.d.ts create mode 100644 node_modules/proto3-json-serializer/build/src/any.js create mode 100644 node_modules/proto3-json-serializer/build/src/any.js.map create mode 100644 node_modules/proto3-json-serializer/build/src/bytes.d.ts create mode 100644 node_modules/proto3-json-serializer/build/src/bytes.js create mode 100644 node_modules/proto3-json-serializer/build/src/bytes.js.map create mode 100644 node_modules/proto3-json-serializer/build/src/duration.d.ts create mode 100644 node_modules/proto3-json-serializer/build/src/duration.js create mode 100644 node_modules/proto3-json-serializer/build/src/duration.js.map create mode 100644 node_modules/proto3-json-serializer/build/src/enum.d.ts create mode 100644 node_modules/proto3-json-serializer/build/src/enum.js create mode 100644 node_modules/proto3-json-serializer/build/src/enum.js.map create mode 100644 node_modules/proto3-json-serializer/build/src/fieldmask.d.ts create mode 100644 node_modules/proto3-json-serializer/build/src/fieldmask.js create mode 100644 node_modules/proto3-json-serializer/build/src/fieldmask.js.map create mode 100644 node_modules/proto3-json-serializer/build/src/fromproto3json.d.ts create mode 100644 node_modules/proto3-json-serializer/build/src/fromproto3json.js create mode 100644 node_modules/proto3-json-serializer/build/src/fromproto3json.js.map create mode 100644 node_modules/proto3-json-serializer/build/src/index.d.ts create mode 100644 node_modules/proto3-json-serializer/build/src/index.js create mode 100644 node_modules/proto3-json-serializer/build/src/index.js.map create mode 100644 node_modules/proto3-json-serializer/build/src/timestamp.d.ts create mode 100644 node_modules/proto3-json-serializer/build/src/timestamp.js create mode 100644 node_modules/proto3-json-serializer/build/src/timestamp.js.map create mode 100644 node_modules/proto3-json-serializer/build/src/toproto3json.d.ts create mode 100644 node_modules/proto3-json-serializer/build/src/toproto3json.js create mode 100644 node_modules/proto3-json-serializer/build/src/toproto3json.js.map create mode 100644 node_modules/proto3-json-serializer/build/src/types.d.ts create mode 100644 node_modules/proto3-json-serializer/build/src/types.js create mode 100644 node_modules/proto3-json-serializer/build/src/types.js.map create mode 100644 node_modules/proto3-json-serializer/build/src/util.d.ts create mode 100644 node_modules/proto3-json-serializer/build/src/util.js create mode 100644 node_modules/proto3-json-serializer/build/src/util.js.map create mode 100644 node_modules/proto3-json-serializer/build/src/value.d.ts create mode 100644 node_modules/proto3-json-serializer/build/src/value.js create mode 100644 node_modules/proto3-json-serializer/build/src/value.js.map create mode 100644 node_modules/proto3-json-serializer/build/src/wrappers.d.ts create mode 100644 node_modules/proto3-json-serializer/build/src/wrappers.js create mode 100644 node_modules/proto3-json-serializer/build/src/wrappers.js.map create mode 100644 node_modules/proto3-json-serializer/package.json create mode 100644 node_modules/protobufjs/LICENSE create mode 100644 node_modules/protobufjs/README.md create mode 100644 node_modules/protobufjs/dist/light/protobuf.js create mode 100644 node_modules/protobufjs/dist/light/protobuf.js.map create mode 100644 node_modules/protobufjs/dist/light/protobuf.min.js create mode 100644 node_modules/protobufjs/dist/light/protobuf.min.js.map create mode 100644 node_modules/protobufjs/dist/minimal/protobuf.js create mode 100644 node_modules/protobufjs/dist/minimal/protobuf.js.map create mode 100644 node_modules/protobufjs/dist/minimal/protobuf.min.js create mode 100644 node_modules/protobufjs/dist/minimal/protobuf.min.js.map create mode 100644 node_modules/protobufjs/dist/protobuf.js create mode 100644 node_modules/protobufjs/dist/protobuf.js.map create mode 100644 node_modules/protobufjs/dist/protobuf.min.js create mode 100644 node_modules/protobufjs/dist/protobuf.min.js.map create mode 100644 node_modules/protobufjs/ext/debug/README.md create mode 100644 node_modules/protobufjs/ext/debug/index.js create mode 100644 node_modules/protobufjs/ext/descriptor/README.md create mode 100644 node_modules/protobufjs/ext/descriptor/index.d.ts create mode 100644 node_modules/protobufjs/ext/descriptor/index.js create mode 100644 node_modules/protobufjs/ext/descriptor/test.js create mode 100644 node_modules/protobufjs/google/LICENSE create mode 100644 node_modules/protobufjs/google/README.md create mode 100644 node_modules/protobufjs/google/api/annotations.json create mode 100644 node_modules/protobufjs/google/api/annotations.proto create mode 100644 node_modules/protobufjs/google/api/http.json create mode 100644 node_modules/protobufjs/google/api/http.proto create mode 100644 node_modules/protobufjs/google/protobuf/api.json create mode 100644 node_modules/protobufjs/google/protobuf/api.proto create mode 100644 node_modules/protobufjs/google/protobuf/descriptor.json create mode 100644 node_modules/protobufjs/google/protobuf/descriptor.proto create mode 100644 node_modules/protobufjs/google/protobuf/source_context.json create mode 100644 node_modules/protobufjs/google/protobuf/source_context.proto create mode 100644 node_modules/protobufjs/google/protobuf/type.json create mode 100644 node_modules/protobufjs/google/protobuf/type.proto create mode 100644 node_modules/protobufjs/index.d.ts create mode 100644 node_modules/protobufjs/index.js create mode 100644 node_modules/protobufjs/light.d.ts create mode 100644 node_modules/protobufjs/light.js create mode 100644 node_modules/protobufjs/minimal.d.ts create mode 100644 node_modules/protobufjs/minimal.js create mode 100644 node_modules/protobufjs/package.json create mode 100644 node_modules/protobufjs/scripts/postinstall.js create mode 100644 node_modules/protobufjs/src/common.js create mode 100644 node_modules/protobufjs/src/converter.js create mode 100644 node_modules/protobufjs/src/decoder.js create mode 100644 node_modules/protobufjs/src/encoder.js create mode 100644 node_modules/protobufjs/src/enum.js create mode 100644 node_modules/protobufjs/src/field.js create mode 100644 node_modules/protobufjs/src/index-light.js create mode 100644 node_modules/protobufjs/src/index-minimal.js create mode 100644 node_modules/protobufjs/src/index.js create mode 100644 node_modules/protobufjs/src/mapfield.js create mode 100644 node_modules/protobufjs/src/message.js create mode 100644 node_modules/protobufjs/src/method.js create mode 100644 node_modules/protobufjs/src/namespace.js create mode 100644 node_modules/protobufjs/src/object.js create mode 100644 node_modules/protobufjs/src/oneof.js create mode 100644 node_modules/protobufjs/src/parse.js create mode 100644 node_modules/protobufjs/src/reader.js create mode 100644 node_modules/protobufjs/src/reader_buffer.js create mode 100644 node_modules/protobufjs/src/root.js create mode 100644 node_modules/protobufjs/src/roots.js create mode 100644 node_modules/protobufjs/src/rpc.js create mode 100644 node_modules/protobufjs/src/rpc/service.js create mode 100644 node_modules/protobufjs/src/service.js create mode 100644 node_modules/protobufjs/src/tokenize.js create mode 100644 node_modules/protobufjs/src/type.js create mode 100644 node_modules/protobufjs/src/types.js create mode 100644 node_modules/protobufjs/src/typescript.jsdoc create mode 100644 node_modules/protobufjs/src/util.js create mode 100644 node_modules/protobufjs/src/util/longbits.js create mode 100644 node_modules/protobufjs/src/util/minimal.js create mode 100644 node_modules/protobufjs/src/verifier.js create mode 100644 node_modules/protobufjs/src/wrappers.js create mode 100644 node_modules/protobufjs/src/writer.js create mode 100644 node_modules/protobufjs/src/writer_buffer.js create mode 100644 node_modules/protobufjs/tsconfig.json create mode 100644 node_modules/readable-stream/CONTRIBUTING.md create mode 100644 node_modules/readable-stream/GOVERNANCE.md create mode 100644 node_modules/readable-stream/LICENSE create mode 100644 node_modules/readable-stream/README.md create mode 100644 node_modules/readable-stream/errors-browser.js create mode 100644 node_modules/readable-stream/errors.js create mode 100644 node_modules/readable-stream/experimentalWarning.js create mode 100644 node_modules/readable-stream/lib/_stream_duplex.js create mode 100644 node_modules/readable-stream/lib/_stream_passthrough.js create mode 100644 node_modules/readable-stream/lib/_stream_readable.js create mode 100644 node_modules/readable-stream/lib/_stream_transform.js create mode 100644 node_modules/readable-stream/lib/_stream_writable.js create mode 100644 node_modules/readable-stream/lib/internal/streams/async_iterator.js create mode 100644 node_modules/readable-stream/lib/internal/streams/buffer_list.js create mode 100644 node_modules/readable-stream/lib/internal/streams/destroy.js create mode 100644 node_modules/readable-stream/lib/internal/streams/end-of-stream.js create mode 100644 node_modules/readable-stream/lib/internal/streams/from-browser.js create mode 100644 node_modules/readable-stream/lib/internal/streams/from.js create mode 100644 node_modules/readable-stream/lib/internal/streams/pipeline.js create mode 100644 node_modules/readable-stream/lib/internal/streams/state.js create mode 100644 node_modules/readable-stream/lib/internal/streams/stream-browser.js create mode 100644 node_modules/readable-stream/lib/internal/streams/stream.js create mode 100644 node_modules/readable-stream/package.json create mode 100644 node_modules/readable-stream/readable-browser.js create mode 100644 node_modules/readable-stream/readable.js create mode 100644 node_modules/require-directory/.jshintrc create mode 100644 node_modules/require-directory/.npmignore create mode 100644 node_modules/require-directory/.travis.yml create mode 100644 node_modules/require-directory/LICENSE create mode 100644 node_modules/require-directory/README.markdown create mode 100644 node_modules/require-directory/index.js create mode 100644 node_modules/require-directory/package.json create mode 100644 node_modules/retry-request/CHANGELOG.md create mode 100644 node_modules/retry-request/index.d.ts create mode 100644 node_modules/retry-request/index.js create mode 100644 node_modules/retry-request/license create mode 100644 node_modules/retry-request/package.json create mode 100644 node_modules/retry-request/readme.md create mode 100644 node_modules/retry/License create mode 100644 node_modules/retry/README.md create mode 100644 node_modules/retry/example/dns.js create mode 100644 node_modules/retry/example/stop.js create mode 100644 node_modules/retry/index.js create mode 100644 node_modules/retry/lib/retry.js create mode 100644 node_modules/retry/lib/retry_operation.js create mode 100644 node_modules/retry/package.json create mode 100644 node_modules/safe-buffer/LICENSE create mode 100644 node_modules/safe-buffer/README.md create mode 100644 node_modules/safe-buffer/index.d.ts create mode 100644 node_modules/safe-buffer/index.js create mode 100644 node_modules/safe-buffer/package.json create mode 100644 node_modules/semver/LICENSE create mode 100644 node_modules/semver/README.md create mode 100644 node_modules/semver/bin/semver.js create mode 100644 node_modules/semver/classes/comparator.js create mode 100644 node_modules/semver/classes/index.js create mode 100644 node_modules/semver/classes/range.js create mode 100644 node_modules/semver/classes/semver.js create mode 100644 node_modules/semver/functions/clean.js create mode 100644 node_modules/semver/functions/cmp.js create mode 100644 node_modules/semver/functions/coerce.js create mode 100644 node_modules/semver/functions/compare-build.js create mode 100644 node_modules/semver/functions/compare-loose.js create mode 100644 node_modules/semver/functions/compare.js create mode 100644 node_modules/semver/functions/diff.js create mode 100644 node_modules/semver/functions/eq.js create mode 100644 node_modules/semver/functions/gt.js create mode 100644 node_modules/semver/functions/gte.js create mode 100644 node_modules/semver/functions/inc.js create mode 100644 node_modules/semver/functions/lt.js create mode 100644 node_modules/semver/functions/lte.js create mode 100644 node_modules/semver/functions/major.js create mode 100644 node_modules/semver/functions/minor.js create mode 100644 node_modules/semver/functions/neq.js create mode 100644 node_modules/semver/functions/parse.js create mode 100644 node_modules/semver/functions/patch.js create mode 100644 node_modules/semver/functions/prerelease.js create mode 100644 node_modules/semver/functions/rcompare.js create mode 100644 node_modules/semver/functions/rsort.js create mode 100644 node_modules/semver/functions/satisfies.js create mode 100644 node_modules/semver/functions/sort.js create mode 100644 node_modules/semver/functions/valid.js create mode 100644 node_modules/semver/index.js create mode 100644 node_modules/semver/internal/constants.js create mode 100644 node_modules/semver/internal/debug.js create mode 100644 node_modules/semver/internal/identifiers.js create mode 100644 node_modules/semver/internal/lrucache.js create mode 100644 node_modules/semver/internal/parse-options.js create mode 100644 node_modules/semver/internal/re.js create mode 100644 node_modules/semver/package.json create mode 100644 node_modules/semver/preload.js create mode 100644 node_modules/semver/range.bnf create mode 100644 node_modules/semver/ranges/gtr.js create mode 100644 node_modules/semver/ranges/intersects.js create mode 100644 node_modules/semver/ranges/ltr.js create mode 100644 node_modules/semver/ranges/max-satisfying.js create mode 100644 node_modules/semver/ranges/min-satisfying.js create mode 100644 node_modules/semver/ranges/min-version.js create mode 100644 node_modules/semver/ranges/outside.js create mode 100644 node_modules/semver/ranges/simplify.js create mode 100644 node_modules/semver/ranges/subset.js create mode 100644 node_modules/semver/ranges/to-comparators.js create mode 100644 node_modules/semver/ranges/valid.js create mode 100644 node_modules/stream-events/index.d.ts create mode 100644 node_modules/stream-events/index.js create mode 100644 node_modules/stream-events/package.json create mode 100644 node_modules/stream-events/readme.md create mode 100644 node_modules/stream-shift/.github/workflows/test.yml create mode 100644 node_modules/stream-shift/LICENSE create mode 100644 node_modules/stream-shift/README.md create mode 100644 node_modules/stream-shift/index.js create mode 100644 node_modules/stream-shift/package.json create mode 100644 node_modules/stream-shift/test.js create mode 100644 node_modules/string-width/index.d.ts create mode 100644 node_modules/string-width/index.js create mode 100644 node_modules/string-width/license create mode 100644 node_modules/string-width/package.json create mode 100644 node_modules/string-width/readme.md create mode 100644 node_modules/string_decoder/LICENSE create mode 100644 node_modules/string_decoder/README.md create mode 100644 node_modules/string_decoder/lib/string_decoder.js create mode 100644 node_modules/string_decoder/package.json create mode 100644 node_modules/strip-ansi/index.d.ts create mode 100644 node_modules/strip-ansi/index.js create mode 100644 node_modules/strip-ansi/license create mode 100644 node_modules/strip-ansi/package.json create mode 100644 node_modules/strip-ansi/readme.md create mode 100644 node_modules/strnum/.vscode/launch.json create mode 100644 node_modules/strnum/CHANGELOG.md create mode 100644 node_modules/strnum/LICENSE create mode 100644 node_modules/strnum/README.md create mode 100644 node_modules/strnum/package.json create mode 100644 node_modules/strnum/strnum.js create mode 100644 node_modules/strnum/strnum.test.js create mode 100644 node_modules/stubs/index.js create mode 100644 node_modules/stubs/package.json create mode 100644 node_modules/stubs/readme.md create mode 100644 node_modules/stubs/test.js create mode 100644 node_modules/teeny-request/CHANGELOG.md create mode 100644 node_modules/teeny-request/LICENSE create mode 100644 node_modules/teeny-request/README.md create mode 100644 node_modules/teeny-request/build/src/TeenyStatistics.d.ts create mode 100644 node_modules/teeny-request/build/src/TeenyStatistics.js create mode 100644 node_modules/teeny-request/build/src/TeenyStatistics.js.map create mode 100644 node_modules/teeny-request/build/src/agents.d.ts create mode 100644 node_modules/teeny-request/build/src/agents.js create mode 100644 node_modules/teeny-request/build/src/agents.js.map create mode 100644 node_modules/teeny-request/build/src/index.d.ts create mode 100644 node_modules/teeny-request/build/src/index.js create mode 100644 node_modules/teeny-request/build/src/index.js.map create mode 100644 node_modules/teeny-request/node_modules/.bin/uuid create mode 100644 node_modules/teeny-request/node_modules/.bin/uuid.cmd create mode 100644 node_modules/teeny-request/node_modules/.bin/uuid.ps1 create mode 100644 node_modules/teeny-request/node_modules/agent-base/README.md create mode 100644 node_modules/teeny-request/node_modules/agent-base/dist/src/index.d.ts create mode 100644 node_modules/teeny-request/node_modules/agent-base/dist/src/index.js create mode 100644 node_modules/teeny-request/node_modules/agent-base/dist/src/index.js.map create mode 100644 node_modules/teeny-request/node_modules/agent-base/dist/src/promisify.d.ts create mode 100644 node_modules/teeny-request/node_modules/agent-base/dist/src/promisify.js create mode 100644 node_modules/teeny-request/node_modules/agent-base/dist/src/promisify.js.map create mode 100644 node_modules/teeny-request/node_modules/agent-base/package.json create mode 100644 node_modules/teeny-request/node_modules/agent-base/src/index.ts create mode 100644 node_modules/teeny-request/node_modules/agent-base/src/promisify.ts create mode 100644 node_modules/teeny-request/node_modules/https-proxy-agent/README.md create mode 100644 node_modules/teeny-request/node_modules/https-proxy-agent/dist/agent.d.ts create mode 100644 node_modules/teeny-request/node_modules/https-proxy-agent/dist/agent.js create mode 100644 node_modules/teeny-request/node_modules/https-proxy-agent/dist/agent.js.map create mode 100644 node_modules/teeny-request/node_modules/https-proxy-agent/dist/index.d.ts create mode 100644 node_modules/teeny-request/node_modules/https-proxy-agent/dist/index.js create mode 100644 node_modules/teeny-request/node_modules/https-proxy-agent/dist/index.js.map create mode 100644 node_modules/teeny-request/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts create mode 100644 node_modules/teeny-request/node_modules/https-proxy-agent/dist/parse-proxy-response.js create mode 100644 node_modules/teeny-request/node_modules/https-proxy-agent/dist/parse-proxy-response.js.map create mode 100644 node_modules/teeny-request/node_modules/https-proxy-agent/package.json create mode 100644 node_modules/teeny-request/node_modules/uuid/CHANGELOG.md create mode 100644 node_modules/teeny-request/node_modules/uuid/CONTRIBUTING.md create mode 100644 node_modules/teeny-request/node_modules/uuid/LICENSE.md create mode 100644 node_modules/teeny-request/node_modules/uuid/README.md create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/bin/uuid create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/index.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/md5.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/native.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/nil.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/parse.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/regex.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/rng.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/sha1.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/stringify.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/v1.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/v3.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/v35.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/v4.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/v5.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/validate.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/version.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-browser/index.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-browser/md5.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-browser/native.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-browser/nil.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-browser/parse.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-browser/regex.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-browser/rng.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-browser/sha1.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-browser/stringify.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-browser/v1.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-browser/v3.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-browser/v35.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-browser/v4.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-browser/v5.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-browser/validate.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-browser/version.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-node/index.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-node/md5.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-node/native.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-node/nil.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-node/parse.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-node/regex.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-node/rng.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-node/sha1.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-node/stringify.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-node/v1.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-node/v3.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-node/v35.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-node/v4.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-node/v5.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-node/validate.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/esm-node/version.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/index.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/md5-browser.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/md5.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/native-browser.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/native.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/nil.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/parse.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/regex.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/rng-browser.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/rng.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/sha1-browser.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/sha1.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/stringify.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/uuid-bin.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/v1.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/v3.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/v35.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/v4.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/v5.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/validate.js create mode 100644 node_modules/teeny-request/node_modules/uuid/dist/version.js create mode 100644 node_modules/teeny-request/node_modules/uuid/package.json create mode 100644 node_modules/teeny-request/node_modules/uuid/wrapper.mjs create mode 100644 node_modules/teeny-request/package.json create mode 100644 node_modules/tr46/.npmignore create mode 100644 node_modules/tr46/index.js create mode 100644 node_modules/tr46/lib/.gitkeep create mode 100644 node_modules/tr46/lib/mappingTable.json create mode 100644 node_modules/tr46/package.json create mode 100644 node_modules/tslib/CopyrightNotice.txt create mode 100644 node_modules/tslib/LICENSE.txt create mode 100644 node_modules/tslib/README.md create mode 100644 node_modules/tslib/SECURITY.md create mode 100644 node_modules/tslib/modules/index.d.ts create mode 100644 node_modules/tslib/modules/index.js create mode 100644 node_modules/tslib/modules/package.json create mode 100644 node_modules/tslib/package.json create mode 100644 node_modules/tslib/tslib.d.ts create mode 100644 node_modules/tslib/tslib.es6.html create mode 100644 node_modules/tslib/tslib.es6.js create mode 100644 node_modules/tslib/tslib.es6.mjs create mode 100644 node_modules/tslib/tslib.html create mode 100644 node_modules/tslib/tslib.js create mode 100644 node_modules/undici-types/LICENSE create mode 100644 node_modules/undici-types/README.md create mode 100644 node_modules/undici-types/agent.d.ts create mode 100644 node_modules/undici-types/api.d.ts create mode 100644 node_modules/undici-types/balanced-pool.d.ts create mode 100644 node_modules/undici-types/cache.d.ts create mode 100644 node_modules/undici-types/client.d.ts create mode 100644 node_modules/undici-types/connector.d.ts create mode 100644 node_modules/undici-types/content-type.d.ts create mode 100644 node_modules/undici-types/cookies.d.ts create mode 100644 node_modules/undici-types/diagnostics-channel.d.ts create mode 100644 node_modules/undici-types/dispatcher.d.ts create mode 100644 node_modules/undici-types/env-http-proxy-agent.d.ts create mode 100644 node_modules/undici-types/errors.d.ts create mode 100644 node_modules/undici-types/eventsource.d.ts create mode 100644 node_modules/undici-types/fetch.d.ts create mode 100644 node_modules/undici-types/file.d.ts create mode 100644 node_modules/undici-types/filereader.d.ts create mode 100644 node_modules/undici-types/formdata.d.ts create mode 100644 node_modules/undici-types/global-dispatcher.d.ts create mode 100644 node_modules/undici-types/global-origin.d.ts create mode 100644 node_modules/undici-types/handlers.d.ts create mode 100644 node_modules/undici-types/header.d.ts create mode 100644 node_modules/undici-types/index.d.ts create mode 100644 node_modules/undici-types/interceptors.d.ts create mode 100644 node_modules/undici-types/mock-agent.d.ts create mode 100644 node_modules/undici-types/mock-client.d.ts create mode 100644 node_modules/undici-types/mock-errors.d.ts create mode 100644 node_modules/undici-types/mock-interceptor.d.ts create mode 100644 node_modules/undici-types/mock-pool.d.ts create mode 100644 node_modules/undici-types/package.json create mode 100644 node_modules/undici-types/patch.d.ts create mode 100644 node_modules/undici-types/pool-stats.d.ts create mode 100644 node_modules/undici-types/pool.d.ts create mode 100644 node_modules/undici-types/proxy-agent.d.ts create mode 100644 node_modules/undici-types/readable.d.ts create mode 100644 node_modules/undici-types/retry-agent.d.ts create mode 100644 node_modules/undici-types/retry-handler.d.ts create mode 100644 node_modules/undici-types/util.d.ts create mode 100644 node_modules/undici-types/webidl.d.ts create mode 100644 node_modules/undici-types/websocket.d.ts create mode 100644 node_modules/util-deprecate/History.md create mode 100644 node_modules/util-deprecate/LICENSE create mode 100644 node_modules/util-deprecate/README.md create mode 100644 node_modules/util-deprecate/browser.js create mode 100644 node_modules/util-deprecate/node.js create mode 100644 node_modules/util-deprecate/package.json create mode 100644 node_modules/uuid/LICENSE.md create mode 100644 node_modules/uuid/README.md create mode 100644 node_modules/uuid/dist/cjs-browser/index.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/index.js create mode 100644 node_modules/uuid/dist/cjs-browser/max.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/max.js create mode 100644 node_modules/uuid/dist/cjs-browser/md5.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/md5.js create mode 100644 node_modules/uuid/dist/cjs-browser/native.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/native.js create mode 100644 node_modules/uuid/dist/cjs-browser/nil.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/nil.js create mode 100644 node_modules/uuid/dist/cjs-browser/package.json create mode 100644 node_modules/uuid/dist/cjs-browser/parse.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/parse.js create mode 100644 node_modules/uuid/dist/cjs-browser/regex.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/regex.js create mode 100644 node_modules/uuid/dist/cjs-browser/rng.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/rng.js create mode 100644 node_modules/uuid/dist/cjs-browser/sha1.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/sha1.js create mode 100644 node_modules/uuid/dist/cjs-browser/stringify.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/stringify.js create mode 100644 node_modules/uuid/dist/cjs-browser/types.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/types.js create mode 100644 node_modules/uuid/dist/cjs-browser/uuid-bin.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/uuid-bin.js create mode 100644 node_modules/uuid/dist/cjs-browser/v1.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/v1.js create mode 100644 node_modules/uuid/dist/cjs-browser/v1ToV6.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/v1ToV6.js create mode 100644 node_modules/uuid/dist/cjs-browser/v3.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/v3.js create mode 100644 node_modules/uuid/dist/cjs-browser/v35.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/v35.js create mode 100644 node_modules/uuid/dist/cjs-browser/v4.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/v4.js create mode 100644 node_modules/uuid/dist/cjs-browser/v5.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/v5.js create mode 100644 node_modules/uuid/dist/cjs-browser/v6.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/v6.js create mode 100644 node_modules/uuid/dist/cjs-browser/v6ToV1.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/v6ToV1.js create mode 100644 node_modules/uuid/dist/cjs-browser/v7.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/v7.js create mode 100644 node_modules/uuid/dist/cjs-browser/validate.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/validate.js create mode 100644 node_modules/uuid/dist/cjs-browser/version.d.ts create mode 100644 node_modules/uuid/dist/cjs-browser/version.js create mode 100644 node_modules/uuid/dist/cjs/index.d.ts create mode 100644 node_modules/uuid/dist/cjs/index.js create mode 100644 node_modules/uuid/dist/cjs/max.d.ts create mode 100644 node_modules/uuid/dist/cjs/max.js create mode 100644 node_modules/uuid/dist/cjs/md5.d.ts create mode 100644 node_modules/uuid/dist/cjs/md5.js create mode 100644 node_modules/uuid/dist/cjs/native.d.ts create mode 100644 node_modules/uuid/dist/cjs/native.js create mode 100644 node_modules/uuid/dist/cjs/nil.d.ts create mode 100644 node_modules/uuid/dist/cjs/nil.js create mode 100644 node_modules/uuid/dist/cjs/package.json create mode 100644 node_modules/uuid/dist/cjs/parse.d.ts create mode 100644 node_modules/uuid/dist/cjs/parse.js create mode 100644 node_modules/uuid/dist/cjs/regex.d.ts create mode 100644 node_modules/uuid/dist/cjs/regex.js create mode 100644 node_modules/uuid/dist/cjs/rng.d.ts create mode 100644 node_modules/uuid/dist/cjs/rng.js create mode 100644 node_modules/uuid/dist/cjs/sha1.d.ts create mode 100644 node_modules/uuid/dist/cjs/sha1.js create mode 100644 node_modules/uuid/dist/cjs/stringify.d.ts create mode 100644 node_modules/uuid/dist/cjs/stringify.js create mode 100644 node_modules/uuid/dist/cjs/types.d.ts create mode 100644 node_modules/uuid/dist/cjs/types.js create mode 100644 node_modules/uuid/dist/cjs/uuid-bin.d.ts create mode 100644 node_modules/uuid/dist/cjs/uuid-bin.js create mode 100644 node_modules/uuid/dist/cjs/v1.d.ts create mode 100644 node_modules/uuid/dist/cjs/v1.js create mode 100644 node_modules/uuid/dist/cjs/v1ToV6.d.ts create mode 100644 node_modules/uuid/dist/cjs/v1ToV6.js create mode 100644 node_modules/uuid/dist/cjs/v3.d.ts create mode 100644 node_modules/uuid/dist/cjs/v3.js create mode 100644 node_modules/uuid/dist/cjs/v35.d.ts create mode 100644 node_modules/uuid/dist/cjs/v35.js create mode 100644 node_modules/uuid/dist/cjs/v4.d.ts create mode 100644 node_modules/uuid/dist/cjs/v4.js create mode 100644 node_modules/uuid/dist/cjs/v5.d.ts create mode 100644 node_modules/uuid/dist/cjs/v5.js create mode 100644 node_modules/uuid/dist/cjs/v6.d.ts create mode 100644 node_modules/uuid/dist/cjs/v6.js create mode 100644 node_modules/uuid/dist/cjs/v6ToV1.d.ts create mode 100644 node_modules/uuid/dist/cjs/v6ToV1.js create mode 100644 node_modules/uuid/dist/cjs/v7.d.ts create mode 100644 node_modules/uuid/dist/cjs/v7.js create mode 100644 node_modules/uuid/dist/cjs/validate.d.ts create mode 100644 node_modules/uuid/dist/cjs/validate.js create mode 100644 node_modules/uuid/dist/cjs/version.d.ts create mode 100644 node_modules/uuid/dist/cjs/version.js create mode 100644 node_modules/uuid/dist/esm-browser/index.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/index.js create mode 100644 node_modules/uuid/dist/esm-browser/max.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/max.js create mode 100644 node_modules/uuid/dist/esm-browser/md5.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/md5.js create mode 100644 node_modules/uuid/dist/esm-browser/native.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/native.js create mode 100644 node_modules/uuid/dist/esm-browser/nil.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/nil.js create mode 100644 node_modules/uuid/dist/esm-browser/parse.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/parse.js create mode 100644 node_modules/uuid/dist/esm-browser/regex.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/regex.js create mode 100644 node_modules/uuid/dist/esm-browser/rng.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/rng.js create mode 100644 node_modules/uuid/dist/esm-browser/sha1.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/sha1.js create mode 100644 node_modules/uuid/dist/esm-browser/stringify.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/stringify.js create mode 100644 node_modules/uuid/dist/esm-browser/types.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/types.js create mode 100644 node_modules/uuid/dist/esm-browser/uuid-bin.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/uuid-bin.js create mode 100644 node_modules/uuid/dist/esm-browser/v1.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/v1.js create mode 100644 node_modules/uuid/dist/esm-browser/v1ToV6.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/v1ToV6.js create mode 100644 node_modules/uuid/dist/esm-browser/v3.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/v3.js create mode 100644 node_modules/uuid/dist/esm-browser/v35.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/v35.js create mode 100644 node_modules/uuid/dist/esm-browser/v4.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/v4.js create mode 100644 node_modules/uuid/dist/esm-browser/v5.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/v5.js create mode 100644 node_modules/uuid/dist/esm-browser/v6.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/v6.js create mode 100644 node_modules/uuid/dist/esm-browser/v6ToV1.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/v6ToV1.js create mode 100644 node_modules/uuid/dist/esm-browser/v7.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/v7.js create mode 100644 node_modules/uuid/dist/esm-browser/validate.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/validate.js create mode 100644 node_modules/uuid/dist/esm-browser/version.d.ts create mode 100644 node_modules/uuid/dist/esm-browser/version.js create mode 100644 node_modules/uuid/dist/esm/bin/uuid create mode 100644 node_modules/uuid/dist/esm/index.d.ts create mode 100644 node_modules/uuid/dist/esm/index.js create mode 100644 node_modules/uuid/dist/esm/max.d.ts create mode 100644 node_modules/uuid/dist/esm/max.js create mode 100644 node_modules/uuid/dist/esm/md5.d.ts create mode 100644 node_modules/uuid/dist/esm/md5.js create mode 100644 node_modules/uuid/dist/esm/native.d.ts create mode 100644 node_modules/uuid/dist/esm/native.js create mode 100644 node_modules/uuid/dist/esm/nil.d.ts create mode 100644 node_modules/uuid/dist/esm/nil.js create mode 100644 node_modules/uuid/dist/esm/parse.d.ts create mode 100644 node_modules/uuid/dist/esm/parse.js create mode 100644 node_modules/uuid/dist/esm/regex.d.ts create mode 100644 node_modules/uuid/dist/esm/regex.js create mode 100644 node_modules/uuid/dist/esm/rng.d.ts create mode 100644 node_modules/uuid/dist/esm/rng.js create mode 100644 node_modules/uuid/dist/esm/sha1.d.ts create mode 100644 node_modules/uuid/dist/esm/sha1.js create mode 100644 node_modules/uuid/dist/esm/stringify.d.ts create mode 100644 node_modules/uuid/dist/esm/stringify.js create mode 100644 node_modules/uuid/dist/esm/types.d.ts create mode 100644 node_modules/uuid/dist/esm/types.js create mode 100644 node_modules/uuid/dist/esm/uuid-bin.d.ts create mode 100644 node_modules/uuid/dist/esm/uuid-bin.js create mode 100644 node_modules/uuid/dist/esm/v1.d.ts create mode 100644 node_modules/uuid/dist/esm/v1.js create mode 100644 node_modules/uuid/dist/esm/v1ToV6.d.ts create mode 100644 node_modules/uuid/dist/esm/v1ToV6.js create mode 100644 node_modules/uuid/dist/esm/v3.d.ts create mode 100644 node_modules/uuid/dist/esm/v3.js create mode 100644 node_modules/uuid/dist/esm/v35.d.ts create mode 100644 node_modules/uuid/dist/esm/v35.js create mode 100644 node_modules/uuid/dist/esm/v4.d.ts create mode 100644 node_modules/uuid/dist/esm/v4.js create mode 100644 node_modules/uuid/dist/esm/v5.d.ts create mode 100644 node_modules/uuid/dist/esm/v5.js create mode 100644 node_modules/uuid/dist/esm/v6.d.ts create mode 100644 node_modules/uuid/dist/esm/v6.js create mode 100644 node_modules/uuid/dist/esm/v6ToV1.d.ts create mode 100644 node_modules/uuid/dist/esm/v6ToV1.js create mode 100644 node_modules/uuid/dist/esm/v7.d.ts create mode 100644 node_modules/uuid/dist/esm/v7.js create mode 100644 node_modules/uuid/dist/esm/validate.d.ts create mode 100644 node_modules/uuid/dist/esm/validate.js create mode 100644 node_modules/uuid/dist/esm/version.d.ts create mode 100644 node_modules/uuid/dist/esm/version.js create mode 100644 node_modules/uuid/package.json create mode 100644 node_modules/webidl-conversions/LICENSE.md create mode 100644 node_modules/webidl-conversions/README.md create mode 100644 node_modules/webidl-conversions/lib/index.js create mode 100644 node_modules/webidl-conversions/package.json create mode 100644 node_modules/websocket-driver/CHANGELOG.md create mode 100644 node_modules/websocket-driver/LICENSE.md create mode 100644 node_modules/websocket-driver/README.md create mode 100644 node_modules/websocket-driver/lib/websocket/driver.js create mode 100644 node_modules/websocket-driver/lib/websocket/driver/base.js create mode 100644 node_modules/websocket-driver/lib/websocket/driver/client.js create mode 100644 node_modules/websocket-driver/lib/websocket/driver/draft75.js create mode 100644 node_modules/websocket-driver/lib/websocket/driver/draft76.js create mode 100644 node_modules/websocket-driver/lib/websocket/driver/headers.js create mode 100644 node_modules/websocket-driver/lib/websocket/driver/hybi.js create mode 100644 node_modules/websocket-driver/lib/websocket/driver/hybi/frame.js create mode 100644 node_modules/websocket-driver/lib/websocket/driver/hybi/message.js create mode 100644 node_modules/websocket-driver/lib/websocket/driver/proxy.js create mode 100644 node_modules/websocket-driver/lib/websocket/driver/server.js create mode 100644 node_modules/websocket-driver/lib/websocket/driver/stream_reader.js create mode 100644 node_modules/websocket-driver/lib/websocket/http_parser.js create mode 100644 node_modules/websocket-driver/lib/websocket/streams.js create mode 100644 node_modules/websocket-driver/package.json create mode 100644 node_modules/websocket-extensions/CHANGELOG.md create mode 100644 node_modules/websocket-extensions/LICENSE.md create mode 100644 node_modules/websocket-extensions/README.md create mode 100644 node_modules/websocket-extensions/lib/parser.js create mode 100644 node_modules/websocket-extensions/lib/pipeline/README.md create mode 100644 node_modules/websocket-extensions/lib/pipeline/cell.js create mode 100644 node_modules/websocket-extensions/lib/pipeline/functor.js create mode 100644 node_modules/websocket-extensions/lib/pipeline/index.js create mode 100644 node_modules/websocket-extensions/lib/pipeline/pledge.js create mode 100644 node_modules/websocket-extensions/lib/pipeline/ring_buffer.js create mode 100644 node_modules/websocket-extensions/lib/websocket_extensions.js create mode 100644 node_modules/websocket-extensions/package.json create mode 100644 node_modules/whatwg-url/LICENSE.txt create mode 100644 node_modules/whatwg-url/README.md create mode 100644 node_modules/whatwg-url/lib/URL-impl.js create mode 100644 node_modules/whatwg-url/lib/URL.js create mode 100644 node_modules/whatwg-url/lib/public-api.js create mode 100644 node_modules/whatwg-url/lib/url-state-machine.js create mode 100644 node_modules/whatwg-url/lib/utils.js create mode 100644 node_modules/whatwg-url/package.json create mode 100644 node_modules/wrap-ansi/index.js create mode 100644 node_modules/wrap-ansi/license create mode 100644 node_modules/wrap-ansi/package.json create mode 100644 node_modules/wrap-ansi/readme.md create mode 100644 node_modules/wrappy/LICENSE create mode 100644 node_modules/wrappy/README.md create mode 100644 node_modules/wrappy/package.json create mode 100644 node_modules/wrappy/wrappy.js create mode 100644 node_modules/y18n/CHANGELOG.md create mode 100644 node_modules/y18n/LICENSE create mode 100644 node_modules/y18n/README.md create mode 100644 node_modules/y18n/build/index.cjs create mode 100644 node_modules/y18n/build/lib/cjs.js create mode 100644 node_modules/y18n/build/lib/index.js create mode 100644 node_modules/y18n/build/lib/platform-shims/node.js create mode 100644 node_modules/y18n/index.mjs create mode 100644 node_modules/y18n/package.json create mode 100644 node_modules/yallist/LICENSE create mode 100644 node_modules/yallist/README.md create mode 100644 node_modules/yallist/iterator.js create mode 100644 node_modules/yallist/package.json create mode 100644 node_modules/yallist/yallist.js create mode 100644 node_modules/yargs-parser/CHANGELOG.md create mode 100644 node_modules/yargs-parser/LICENSE.txt create mode 100644 node_modules/yargs-parser/README.md create mode 100644 node_modules/yargs-parser/browser.js create mode 100644 node_modules/yargs-parser/build/index.cjs create mode 100644 node_modules/yargs-parser/build/lib/index.js create mode 100644 node_modules/yargs-parser/build/lib/string-utils.js create mode 100644 node_modules/yargs-parser/build/lib/tokenize-arg-string.js create mode 100644 node_modules/yargs-parser/build/lib/yargs-parser-types.js create mode 100644 node_modules/yargs-parser/build/lib/yargs-parser.js create mode 100644 node_modules/yargs-parser/package.json create mode 100644 node_modules/yargs/LICENSE create mode 100644 node_modules/yargs/README.md create mode 100644 node_modules/yargs/browser.d.ts create mode 100644 node_modules/yargs/browser.mjs create mode 100644 node_modules/yargs/build/index.cjs create mode 100644 node_modules/yargs/build/lib/argsert.js create mode 100644 node_modules/yargs/build/lib/command.js create mode 100644 node_modules/yargs/build/lib/completion-templates.js create mode 100644 node_modules/yargs/build/lib/completion.js create mode 100644 node_modules/yargs/build/lib/middleware.js create mode 100644 node_modules/yargs/build/lib/parse-command.js create mode 100644 node_modules/yargs/build/lib/typings/common-types.js create mode 100644 node_modules/yargs/build/lib/typings/yargs-parser-types.js create mode 100644 node_modules/yargs/build/lib/usage.js create mode 100644 node_modules/yargs/build/lib/utils/apply-extends.js create mode 100644 node_modules/yargs/build/lib/utils/is-promise.js create mode 100644 node_modules/yargs/build/lib/utils/levenshtein.js create mode 100644 node_modules/yargs/build/lib/utils/maybe-async-result.js create mode 100644 node_modules/yargs/build/lib/utils/obj-filter.js create mode 100644 node_modules/yargs/build/lib/utils/process-argv.js create mode 100644 node_modules/yargs/build/lib/utils/set-blocking.js create mode 100644 node_modules/yargs/build/lib/utils/which-module.js create mode 100644 node_modules/yargs/build/lib/validation.js create mode 100644 node_modules/yargs/build/lib/yargs-factory.js create mode 100644 node_modules/yargs/build/lib/yerror.js create mode 100644 node_modules/yargs/helpers/helpers.mjs create mode 100644 node_modules/yargs/helpers/index.js create mode 100644 node_modules/yargs/helpers/package.json create mode 100644 node_modules/yargs/index.cjs create mode 100644 node_modules/yargs/index.mjs create mode 100644 node_modules/yargs/lib/platform-shims/browser.mjs create mode 100644 node_modules/yargs/lib/platform-shims/esm.mjs create mode 100644 node_modules/yargs/locales/be.json create mode 100644 node_modules/yargs/locales/cs.json create mode 100644 node_modules/yargs/locales/de.json create mode 100644 node_modules/yargs/locales/en.json create mode 100644 node_modules/yargs/locales/es.json create mode 100644 node_modules/yargs/locales/fi.json create mode 100644 node_modules/yargs/locales/fr.json create mode 100644 node_modules/yargs/locales/hi.json create mode 100644 node_modules/yargs/locales/hu.json create mode 100644 node_modules/yargs/locales/id.json create mode 100644 node_modules/yargs/locales/it.json create mode 100644 node_modules/yargs/locales/ja.json create mode 100644 node_modules/yargs/locales/ko.json create mode 100644 node_modules/yargs/locales/nb.json create mode 100644 node_modules/yargs/locales/nl.json create mode 100644 node_modules/yargs/locales/nn.json create mode 100644 node_modules/yargs/locales/pirate.json create mode 100644 node_modules/yargs/locales/pl.json create mode 100644 node_modules/yargs/locales/pt.json create mode 100644 node_modules/yargs/locales/pt_BR.json create mode 100644 node_modules/yargs/locales/ru.json create mode 100644 node_modules/yargs/locales/th.json create mode 100644 node_modules/yargs/locales/tr.json create mode 100644 node_modules/yargs/locales/uk_UA.json create mode 100644 node_modules/yargs/locales/uz.json create mode 100644 node_modules/yargs/locales/zh_CN.json create mode 100644 node_modules/yargs/locales/zh_TW.json create mode 100644 node_modules/yargs/package.json create mode 100644 node_modules/yargs/yargs create mode 100644 node_modules/yargs/yargs.mjs create mode 100644 node_modules/yocto-queue/index.d.ts create mode 100644 node_modules/yocto-queue/index.js create mode 100644 node_modules/yocto-queue/license create mode 100644 node_modules/yocto-queue/package.json create mode 100644 node_modules/yocto-queue/readme.md create mode 100644 package-lock.json create mode 100644 package.json diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/Psychology-Apps-main.iml b/.idea/Psychology-Apps-main.iml new file mode 100644 index 0000000..979e8c7 --- /dev/null +++ b/.idea/Psychology-Apps-main.iml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/caches/deviceStreaming.xml b/.idea/caches/deviceStreaming.xml new file mode 100644 index 0000000..97cf2b8 --- /dev/null +++ b/.idea/caches/deviceStreaming.xml @@ -0,0 +1,1138 @@ + + + + + + \ No newline at end of file diff --git a/.idea/copilot.data.migration.agent.xml b/.idea/copilot.data.migration.agent.xml new file mode 100644 index 0000000..4ea72a9 --- /dev/null +++ b/.idea/copilot.data.migration.agent.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/copilot.data.migration.ask.xml b/.idea/copilot.data.migration.ask.xml new file mode 100644 index 0000000..7ef04e2 --- /dev/null +++ b/.idea/copilot.data.migration.ask.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/copilot.data.migration.ask2agent.xml b/.idea/copilot.data.migration.ask2agent.xml new file mode 100644 index 0000000..1f2ea11 --- /dev/null +++ b/.idea/copilot.data.migration.ask2agent.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/copilot.data.migration.edit.xml b/.idea/copilot.data.migration.edit.xml new file mode 100644 index 0000000..8648f94 --- /dev/null +++ b/.idea/copilot.data.migration.edit.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/deviceManager.xml b/.idea/deviceManager.xml new file mode 100644 index 0000000..91f9558 --- /dev/null +++ b/.idea/deviceManager.xml @@ -0,0 +1,13 @@ + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Dart_Packages.xml b/.idea/libraries/Dart_Packages.xml new file mode 100644 index 0000000..67fd4a2 --- /dev/null +++ b/.idea/libraries/Dart_Packages.xml @@ -0,0 +1,428 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Dart_SDK.xml b/.idea/libraries/Dart_SDK.xml new file mode 100644 index 0000000..264a949 --- /dev/null +++ b/.idea/libraries/Dart_SDK.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/markdown.xml b/.idea/markdown.xml new file mode 100644 index 0000000..c61ea33 --- /dev/null +++ b/.idea/markdown.xml @@ -0,0 +1,8 @@ + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..6e86672 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..75a2ae5 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/backend/.env.example b/backend/.env.example new file mode 100644 index 0000000..db2a979 --- /dev/null +++ b/backend/.env.example @@ -0,0 +1,11 @@ +FIREBASE_TYPE="service_account" +FIREBASE_PROJECT_ID="your-project-id" +FIREBASE_PRIVATE_KEY_ID="your-private-key-id" +FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nyour-private-key-here\n-----END PRIVATE KEY-----\n" +FIREBASE_CLIENT_EMAIL="your-client-email@your-project-id.iam.gserviceaccount.com" +FIREBASE_CLIENT_ID="your-client-id" +FIREBASE_AUTH_URI="https://accounts.google.com/o/oauth2/auth" +FIREBASE_TOKEN_URI="https://oauth2.googleapis.com/token" +FIREBASE_AUTH_PROVIDER_X509_CERT_URL="https://www.googleapis.com/oauth2/v1/certs" +FIREBASE_CLIENT_X509_CERT_URL="https://www.googleapis.com/robot/v1/metadata/x509/your-client-email.iam.gserviceaccount.com" +FIREBASE_UNIVERSE_DOMAIN="googleapis.com" \ No newline at end of file diff --git a/backend/package-lock.json b/backend/package-lock.json index c562ee1..04c6445 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -15,9 +15,205 @@ "cors": "^2.8.5", "dotenv": "^17.2.3", "express": "^5.1.0", + "firebase-admin": "^13.6.0", "pdfkit": "^0.17.2" } }, + "node_modules/@fastify/busboy": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-3.2.0.tgz", + "integrity": "sha512-m9FVDXU3GT2ITSe0UaMA5rU3QkfC/UXtCU8y0gSN/GugTqtVldOBWIB5V6V3sbmenVZUIpU6f+mPEO2+m5iTaA==", + "license": "MIT" + }, + "node_modules/@firebase/app-check-interop-types": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/@firebase/app-check-interop-types/-/app-check-interop-types-0.3.3.tgz", + "integrity": "sha512-gAlxfPLT2j8bTI/qfe3ahl2I2YcBQ8cFIBdhAQA4I2f3TndcO+22YizyGYuttLHPQEpWkhmpFW60VCFEPg4g5A==", + "license": "Apache-2.0" + }, + "node_modules/@firebase/app-types": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/@firebase/app-types/-/app-types-0.9.3.tgz", + "integrity": "sha512-kRVpIl4vVGJ4baogMDINbyrIOtOxqhkZQg4jTq3l8Lw6WSk0xfpEYzezFu+Kl4ve4fbPl79dvwRtaFqAC/ucCw==", + "license": "Apache-2.0" + }, + "node_modules/@firebase/auth-interop-types": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/@firebase/auth-interop-types/-/auth-interop-types-0.2.4.tgz", + "integrity": "sha512-JPgcXKCuO+CWqGDnigBtvo09HeBs5u/Ktc2GaFj2m01hLarbxthLNm7Fk8iOP1aqAtXV+fnnGj7U28xmk7IwVA==", + "license": "Apache-2.0" + }, + "node_modules/@firebase/component": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/@firebase/component/-/component-0.7.0.tgz", + "integrity": "sha512-wR9En2A+WESUHexjmRHkqtaVH94WLNKt6rmeqZhSLBybg4Wyf0Umk04SZsS6sBq4102ZsDBFwoqMqJYj2IoDSg==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/util": "1.13.0", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@firebase/database": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@firebase/database/-/database-1.1.0.tgz", + "integrity": "sha512-gM6MJFae3pTyNLoc9VcJNuaUDej0ctdjn3cVtILo3D5lpp0dmUHHLFN/pUKe7ImyeB1KAvRlEYxvIHNF04Filg==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/app-check-interop-types": "0.3.3", + "@firebase/auth-interop-types": "0.2.4", + "@firebase/component": "0.7.0", + "@firebase/logger": "0.5.0", + "@firebase/util": "1.13.0", + "faye-websocket": "0.11.4", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@firebase/database-compat": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@firebase/database-compat/-/database-compat-2.1.0.tgz", + "integrity": "sha512-8nYc43RqxScsePVd1qe1xxvWNf0OBnbwHxmXJ7MHSuuTVYFO3eLyLW3PiCKJ9fHnmIz4p4LbieXwz+qtr9PZDg==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.0", + "@firebase/database": "1.1.0", + "@firebase/database-types": "1.0.16", + "@firebase/logger": "0.5.0", + "@firebase/util": "1.13.0", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@firebase/database-types": { + "version": "1.0.16", + "resolved": "https://registry.npmjs.org/@firebase/database-types/-/database-types-1.0.16.tgz", + "integrity": "sha512-xkQLQfU5De7+SPhEGAXFBnDryUWhhlFXelEg2YeZOQMCdoe7dL64DDAd77SQsR+6uoXIZY5MB4y/inCs4GTfcw==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/app-types": "0.9.3", + "@firebase/util": "1.13.0" + } + }, + "node_modules/@firebase/logger": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@firebase/logger/-/logger-0.5.0.tgz", + "integrity": "sha512-cGskaAvkrnh42b3BA3doDWeBmuHFO/Mx5A83rbRDYakPjO9bJtRL3dX7javzc2Rr/JHZf4HlterTW2lUkfeN4g==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@firebase/util": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@firebase/util/-/util-1.13.0.tgz", + "integrity": "sha512-0AZUyYUfpMNcztR5l09izHwXkZpghLgCUaAGjtMwXnCg3bj4ml5VgiwqOMOxJ+Nw4qN/zJAaOQBcJ7KGkWStqQ==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@google-cloud/firestore": { + "version": "7.11.6", + "resolved": "https://registry.npmjs.org/@google-cloud/firestore/-/firestore-7.11.6.tgz", + "integrity": "sha512-EW/O8ktzwLfyWBOsNuhRoMi8lrC3clHM5LVFhGvO1HCsLozCOOXRAlHrYBoE6HL42Sc8yYMuCb2XqcnJ4OOEpw==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@opentelemetry/api": "^1.3.0", + "fast-deep-equal": "^3.1.1", + "functional-red-black-tree": "^1.0.1", + "google-gax": "^4.3.3", + "protobufjs": "^7.2.6" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@google-cloud/paginator": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@google-cloud/paginator/-/paginator-5.0.2.tgz", + "integrity": "sha512-DJS3s0OVH4zFDB1PzjxAsHqJT6sKVbRwwML0ZBP9PbU7Yebtu/7SWMRzvO2J3nUi9pRNITCfu4LJeooM2w4pjg==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "arrify": "^2.0.0", + "extend": "^3.0.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@google-cloud/projectify": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@google-cloud/projectify/-/projectify-4.0.0.tgz", + "integrity": "sha512-MmaX6HeSvyPbWGwFq7mXdo0uQZLGBYCwziiLIGq5JVX+/bdI3SAq6bP98trV5eTWfLuvsMcIC1YJOF2vfteLFA==", + "license": "Apache-2.0", + "optional": true, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@google-cloud/promisify": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@google-cloud/promisify/-/promisify-4.0.0.tgz", + "integrity": "sha512-Orxzlfb9c67A15cq2JQEyVc7wEsmFBmHjZWZYQMUyJ1qivXyMwdyNOs9odi79hze+2zqdTtu1E19IM/FtqZ10g==", + "license": "Apache-2.0", + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@google-cloud/storage": { + "version": "7.18.0", + "resolved": "https://registry.npmjs.org/@google-cloud/storage/-/storage-7.18.0.tgz", + "integrity": "sha512-r3ZwDMiz4nwW6R922Z1pwpePxyRwE5GdevYX63hRmAQUkUQJcBH/79EnQPDv5cOv1mFBgevdNWQfi3tie3dHrQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@google-cloud/paginator": "^5.0.0", + "@google-cloud/projectify": "^4.0.0", + "@google-cloud/promisify": "<4.1.0", + "abort-controller": "^3.0.0", + "async-retry": "^1.3.3", + "duplexify": "^4.1.3", + "fast-xml-parser": "^4.4.1", + "gaxios": "^6.0.2", + "google-auth-library": "^9.6.3", + "html-entities": "^2.5.2", + "mime": "^3.0.0", + "p-limit": "^3.0.1", + "retry-request": "^7.0.0", + "teeny-request": "^9.0.0", + "uuid": "^8.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@google-cloud/storage/node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "license": "MIT", + "optional": true, + "bin": { + "uuid": "dist/bin/uuid" + } + }, "node_modules/@google/genai": { "version": "1.24.0", "resolved": "https://registry.npmjs.org/@google/genai/-/genai-1.24.0.tgz", @@ -48,6 +244,153 @@ "node": ">=18.0.0" } }, + "node_modules/@grpc/grpc-js": { + "version": "1.14.2", + "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.2.tgz", + "integrity": "sha512-QzVUtEFyu05UNx2xr0fCQmStUO17uVQhGNowtxs00IgTZT6/W2PBLfUkj30s0FKJ29VtTa3ArVNIhNP6akQhqA==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@grpc/proto-loader": "^0.8.0", + "@js-sdsl/ordered-map": "^4.4.2" + }, + "engines": { + "node": ">=12.10.0" + } + }, + "node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.8.0.tgz", + "integrity": "sha512-rc1hOQtjIWGxcxpb9aHAfLpIctjEnsDehj0DAiVfBlmT84uvR0uUtN2hEi/ecvWVjXUGf5qPF4qEgiLOx1YIMQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "lodash.camelcase": "^4.3.0", + "long": "^5.0.0", + "protobufjs": "^7.5.3", + "yargs": "^17.7.2" + }, + "bin": { + "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@grpc/proto-loader": { + "version": "0.7.15", + "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.7.15.tgz", + "integrity": "sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "lodash.camelcase": "^4.3.0", + "long": "^5.0.0", + "protobufjs": "^7.2.5", + "yargs": "^17.7.2" + }, + "bin": { + "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@js-sdsl/ordered-map": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@js-sdsl/ordered-map/-/ordered-map-4.4.2.tgz", + "integrity": "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw==", + "license": "MIT", + "optional": true, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/js-sdsl" + } + }, + "node_modules/@opentelemetry/api": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz", + "integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==", + "license": "Apache-2.0", + "optional": true, + "engines": { + "node": ">=8.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", + "optional": true + }, + "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", + "optional": true + }, + "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", + "optional": true + }, + "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", + "optional": true + }, + "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", + "optional": true, + "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", + "optional": true + }, + "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", + "optional": true + }, + "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", + "optional": true + }, + "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", + "optional": true + }, + "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", + "optional": true + }, "node_modules/@swc/helpers": { "version": "0.5.17", "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.17.tgz", @@ -57,6 +400,226 @@ "tslib": "^2.8.0" } }, + "node_modules/@tootallnate/once": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", + "integrity": "sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 10" + } + }, + "node_modules/@types/body-parser": { + "version": "1.19.6", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", + "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==", + "license": "MIT", + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/caseless": { + "version": "0.12.5", + "resolved": "https://registry.npmjs.org/@types/caseless/-/caseless-0.12.5.tgz", + "integrity": "sha512-hWtVTC2q7hc7xZ/RLbxapMvDMgUnDvKvMOpKal4DrMyfGBUfB1oKaZlIRr6mJL+If3bAP6sV/QneGzF6tJjZDg==", + "license": "MIT", + "optional": true + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/express": { + "version": "4.17.25", + "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.25.tgz", + "integrity": "sha512-dVd04UKsfpINUnK0yBoYHDF3xu7xVH4BuDotC/xGuycx4CgbP48X/KF/586bcObxT0HENHXEU8Nqtu6NR+eKhw==", + "license": "MIT", + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "^1" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "4.19.7", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.7.tgz", + "integrity": "sha512-FvPtiIf1LfhzsaIXhv/PHan/2FeQBbtBDtfX2QfvPxdUelMDEckK08SM6nqo1MIZY3RUlfA+HV8+hFUSio78qg==", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/http-errors": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", + "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==", + "license": "MIT" + }, + "node_modules/@types/jsonwebtoken": { + "version": "9.0.10", + "resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.10.tgz", + "integrity": "sha512-asx5hIG9Qmf/1oStypjanR7iKTv0gXQ1Ov/jfrX6kS/EO0OFni8orbmGCn0672NHR3kXHwpAwR+B368ZGN/2rA==", + "license": "MIT", + "dependencies": { + "@types/ms": "*", + "@types/node": "*" + } + }, + "node_modules/@types/long": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/long/-/long-4.0.2.tgz", + "integrity": "sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA==", + "license": "MIT", + "optional": true + }, + "node_modules/@types/mime": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", + "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==", + "license": "MIT" + }, + "node_modules/@types/ms": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz", + "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.19.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.2.tgz", + "integrity": "sha512-LPM2G3Syo1GLzXLGJAKdqoU35XvrWzGJ21/7sgZTUpbkBaOasTj8tjwn6w+hCkqaa1TfJ/w67rJSwYItlJ2mYw==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/qs": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ==", + "license": "MIT" + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", + "license": "MIT" + }, + "node_modules/@types/request": { + "version": "2.48.13", + "resolved": "https://registry.npmjs.org/@types/request/-/request-2.48.13.tgz", + "integrity": "sha512-FGJ6udDNUCjd19pp0Q3iTiDkwhYup7J8hpMW9c4k53NrccQFFWKRho6hvtPPEhnXWKvukfwAlB6DbDz4yhH5Gg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@types/caseless": "*", + "@types/node": "*", + "@types/tough-cookie": "*", + "form-data": "^2.5.5" + } + }, + "node_modules/@types/request/node_modules/form-data": { + "version": "2.5.5", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.5.5.tgz", + "integrity": "sha512-jqdObeR2rxZZbPSGL+3VckHMYtu+f9//KXBsVny6JSX/pa38Fy+bGjuG8eW/H6USNQWhLi8Num++cU2yOCNz4A==", + "license": "MIT", + "optional": true, + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", + "mime-types": "^2.1.35", + "safe-buffer": "^5.2.1" + }, + "engines": { + "node": ">= 0.12" + } + }, + "node_modules/@types/request/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/@types/request/node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "optional": true, + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/@types/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz", + "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "1.15.10", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.10.tgz", + "integrity": "sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw==", + "license": "MIT", + "dependencies": { + "@types/http-errors": "*", + "@types/node": "*", + "@types/send": "<1" + } + }, + "node_modules/@types/serve-static/node_modules/@types/send": { + "version": "0.17.6", + "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.6.tgz", + "integrity": "sha512-Uqt8rPBE8SY0RK8JB1EzVOIZ32uqy8HwdxCnoCOsYrvnswqmFZ/k+9Ikidlk/ImhsdvBsloHbAlewb2IEBV/Og==", + "license": "MIT", + "dependencies": { + "@types/mime": "^1", + "@types/node": "*" + } + }, + "node_modules/@types/tough-cookie": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.5.tgz", + "integrity": "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==", + "license": "MIT", + "optional": true + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "license": "MIT", + "optional": true, + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, "node_modules/accepts": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", @@ -79,6 +642,52 @@ "node": ">= 14" } }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "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", + "optional": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/arrify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-2.0.1.tgz", + "integrity": "sha512-3duEwti880xqi4eAMN8AyR4a0ByT90zoYdLlevfrvU43vb0YZwZVfxOgxWrLXXXpyugL0hNZc9G6BiB5B3nUug==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/async-retry": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/async-retry/-/async-retry-1.3.3.tgz", + "integrity": "sha512-wfr/jstw9xNi/0teMHrRW7dsz3Lt5ARhYNZ2ewpadnhaIp5mbALhOAP+EAdsC7t4Z6wqsDVv9+W6gm1Dk9mEyw==", + "license": "MIT", + "optional": true, + "dependencies": { + "retry": "0.13.1" + } + }, "node_modules/asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", @@ -126,23 +735,27 @@ } }, "node_modules/body-parser": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.0.tgz", - "integrity": "sha512-02qvAaxv8tp7fBa/mw1ga98OGm+eCbqzJOKoRt70sLmfEEi+jyBYVTDGfCL/k06/4EMk/z01gCe7HoCH/f2LTg==", + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.1.tgz", + "integrity": "sha512-nfDwkulwiZYQIGwxdy0RUmowMhKcFVcYXUU7m4QlKYim1rUtg83xm2yjZ40QjDuc291AJjjeSc9b++AWHSgSHw==", "license": "MIT", "dependencies": { "bytes": "^3.1.2", "content-type": "^1.0.5", - "debug": "^4.4.0", + "debug": "^4.4.3", "http-errors": "^2.0.0", - "iconv-lite": "^0.6.3", + "iconv-lite": "^0.7.0", "on-finished": "^2.4.1", "qs": "^6.14.0", - "raw-body": "^3.0.0", - "type-is": "^2.0.0" + "raw-body": "^3.0.1", + "type-is": "^2.0.1" }, "engines": { "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/brotli": { @@ -198,6 +811,21 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "license": "ISC", + "optional": true, + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, "node_modules/clone": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz", @@ -207,6 +835,26 @@ "node": ">=0.8" } }, + "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", + "optional": true, + "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", + "optional": true + }, "node_modules/combined-stream": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", @@ -344,6 +992,19 @@ "node": ">= 0.4" } }, + "node_modules/duplexify": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-4.1.3.tgz", + "integrity": "sha512-M3BmBhwJRZsSx38lZyhE53Csddgzl5R7xGJNk7CVddZD6CcmwMCH8J+7AprIrQKH7TonKxaCjcv27Qmf+sQ+oA==", + "license": "MIT", + "optional": true, + "dependencies": { + "end-of-stream": "^1.4.1", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1", + "stream-shift": "^1.0.2" + } + }, "node_modules/ecdsa-sig-formatter": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", @@ -359,6 +1020,13 @@ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", "license": "MIT" }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT", + "optional": true + }, "node_modules/encodeurl": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", @@ -368,6 +1036,16 @@ "node": ">= 0.8" } }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "optional": true, + "dependencies": { + "once": "^1.4.0" + } + }, "node_modules/es-define-property": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", @@ -413,6 +1091,16 @@ "node": ">= 0.4" } }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=6" + } + }, "node_modules/escape-html": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", @@ -428,6 +1116,16 @@ "node": ">= 0.6" } }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=6" + } + }, "node_modules/express": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz", @@ -476,12 +1174,52 @@ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "license": "MIT" }, + "node_modules/farmhash-modern": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/farmhash-modern/-/farmhash-modern-1.1.0.tgz", + "integrity": "sha512-6ypT4XfgqJk/F3Yuv4SX26I3doUjt0GTG4a+JgWxXQpxXzTBq8fPUeGHfcYMMDPHJHm3yPOSjaeBwBGAHWXCdA==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "license": "MIT" }, + "node_modules/fast-xml-parser": { + "version": "4.5.3", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.5.3.tgz", + "integrity": "sha512-RKihhV+SHsIUGXObeVy9AXiBbFwkVk7Syp8XgwN5U3JV416+Gwp/GO9i0JYKmikykgz/UHRrrV4ROuZEo/T0ig==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "optional": true, + "dependencies": { + "strnum": "^1.1.1" + }, + "bin": { + "fxparser": "src/cli/cli.js" + } + }, + "node_modules/faye-websocket": { + "version": "0.11.4", + "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.11.4.tgz", + "integrity": "sha512-CzbClwlXAuiRQAlUyfqPgvPoNKTckTPGfwZV4ZdAhVcP2lh9KUxJg2b5GkE7XbjKQ3YJnQ9z6D9ntLAlB+tP8g==", + "license": "Apache-2.0", + "dependencies": { + "websocket-driver": ">=0.5.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, "node_modules/finalhandler": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.0.tgz", @@ -499,6 +1237,45 @@ "node": ">= 0.8" } }, + "node_modules/firebase-admin": { + "version": "13.6.0", + "resolved": "https://registry.npmjs.org/firebase-admin/-/firebase-admin-13.6.0.tgz", + "integrity": "sha512-GdPA/t0+Cq8p1JnjFRBmxRxAGvF/kl2yfdhALl38PrRp325YxyQ5aNaHui0XmaKcKiGRFIJ/EgBNWFoDP0onjw==", + "license": "Apache-2.0", + "dependencies": { + "@fastify/busboy": "^3.0.0", + "@firebase/database-compat": "^2.0.0", + "@firebase/database-types": "^1.0.6", + "@types/node": "^22.8.7", + "farmhash-modern": "^1.1.0", + "fast-deep-equal": "^3.1.1", + "google-auth-library": "^9.14.2", + "jsonwebtoken": "^9.0.0", + "jwks-rsa": "^3.1.0", + "node-forge": "^1.3.1", + "uuid": "^11.0.2" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@google-cloud/firestore": "^7.11.0", + "@google-cloud/storage": "^7.14.0" + } + }, + "node_modules/firebase-admin/node_modules/uuid": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz", + "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/esm/bin/uuid" + } + }, "node_modules/follow-redirects": { "version": "1.15.11", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", @@ -600,6 +1377,13 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/functional-red-black-tree": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", + "integrity": "sha512-dsKNQNdj6xA3T+QlADDA7mOSlX0qiMINjn0cgr+eGHGsbSHzTabcIogz2+p/iqP1Xs6EP/sS2SbqH+brGTbq0g==", + "license": "MIT", + "optional": true + }, "node_modules/gaxios": { "version": "6.7.1", "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-6.7.1.tgz", @@ -630,6 +1414,16 @@ "node": ">=14" } }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "optional": true, + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, "node_modules/get-intrinsic": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", @@ -684,6 +1478,30 @@ "node": ">=14" } }, + "node_modules/google-gax": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/google-gax/-/google-gax-4.6.1.tgz", + "integrity": "sha512-V6eky/xz2mcKfAd1Ioxyd6nmA61gao3n01C+YeuIwu3vzM9EDR6wcVzMSIbLMDXWeoi9SHYctXuKYC5uJUT3eQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@grpc/grpc-js": "^1.10.9", + "@grpc/proto-loader": "^0.7.13", + "@types/long": "^4.0.0", + "abort-controller": "^3.0.0", + "duplexify": "^4.0.0", + "google-auth-library": "^9.3.0", + "node-fetch": "^2.7.0", + "object-hash": "^3.0.0", + "proto3-json-serializer": "^2.0.2", + "protobufjs": "^7.3.2", + "retry-request": "^7.0.0", + "uuid": "^9.0.1" + }, + "engines": { + "node": ">=14" + } + }, "node_modules/google-logging-utils": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-0.0.2.tgz", @@ -757,6 +1575,23 @@ "node": ">= 0.4" } }, + "node_modules/html-entities": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/html-entities/-/html-entities-2.6.0.tgz", + "integrity": "sha512-kig+rMn/QOVRvr7c86gQ8lWXq+Hkv6CbAH1hLu+RG338StTpE8Z0b44SDVaqVu7HGKf27frdmUYEs9hTUX/cLQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/mdevils" + }, + { + "type": "patreon", + "url": "https://patreon.com/mdevils" + } + ], + "license": "MIT", + "optional": true + }, "node_modules/http-errors": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", @@ -782,6 +1617,40 @@ "node": ">= 0.8" } }, + "node_modules/http-parser-js": { + "version": "0.5.10", + "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.10.tgz", + "integrity": "sha512-Pysuw9XpUq5dVc/2SMHpuTY01RFl8fttgcyunjL7eEMhGM3cI4eOmiCycJDVCo/7O7ClfQD3SaI6ftDzqOXYMA==", + "license": "MIT" + }, + "node_modules/http-proxy-agent": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz", + "integrity": "sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==", + "license": "MIT", + "optional": true, + "dependencies": { + "@tootallnate/once": "2", + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/http-proxy-agent/node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, "node_modules/https-proxy-agent": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", @@ -796,15 +1665,19 @@ } }, "node_modules/iconv-lite": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", - "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.1.tgz", + "integrity": "sha512-2Tth85cXwGFHfvRgZWszZSvdo+0Xsqmw8k8ZwxScfcBneNUraK+dxRxRm24nszx80Y0TVio8kKLt5sLE7ZCLlw==", "license": "MIT", "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" }, "engines": { "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/inherits": { @@ -822,6 +1695,16 @@ "node": ">= 0.10" } }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=8" + } + }, "node_modules/is-promise": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", @@ -840,6 +1723,15 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/jose": { + "version": "4.15.9", + "resolved": "https://registry.npmjs.org/jose/-/jose-4.15.9.tgz", + "integrity": "sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/jpeg-exif": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/jpeg-exif/-/jpeg-exif-1.1.4.tgz", @@ -855,6 +1747,28 @@ "bignumber.js": "^9.0.0" } }, + "node_modules/jsonwebtoken": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz", + "integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==", + "license": "MIT", + "dependencies": { + "jws": "^4.0.1", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, "node_modules/jwa": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", @@ -866,16 +1780,38 @@ "safe-buffer": "^5.0.1" } }, + "node_modules/jwks-rsa": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/jwks-rsa/-/jwks-rsa-3.2.0.tgz", + "integrity": "sha512-PwchfHcQK/5PSydeKCs1ylNym0w/SSv8a62DgHJ//7x2ZclCoinlsjAfDxAAbpoTPybOum/Jgy+vkvMmKz89Ww==", + "license": "MIT", + "dependencies": { + "@types/express": "^4.17.20", + "@types/jsonwebtoken": "^9.0.4", + "debug": "^4.3.4", + "jose": "^4.15.4", + "limiter": "^1.1.5", + "lru-memoizer": "^2.2.0" + }, + "engines": { + "node": ">=14" + } + }, "node_modules/jws": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.0.tgz", - "integrity": "sha512-KDncfTmOZoOMTFG4mBlG0qUIOlc03fmzH+ru6RgYVZhPkyiy/92Owlt/8UEN+a4TXR1FQetfIpJE8ApdvdVxTg==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", + "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", "license": "MIT", "dependencies": { - "jwa": "^2.0.0", + "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, + "node_modules/limiter": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/limiter/-/limiter-1.1.5.tgz", + "integrity": "sha512-FWWMIEOxz3GwUI4Ts/IvgVy6LPvoMPgjMdQ185nN6psJyBJ4yOpzqm695/h5umdLJg2vW3GR5iG11MAkR2AzJA==" + }, "node_modules/linebreak": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz", @@ -895,6 +1831,90 @@ "node": ">= 0.4" } }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", + "license": "MIT", + "optional": true + }, + "node_modules/lodash.clonedeep": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz", + "integrity": "sha512-H5ZhCF25riFd9uB5UCkVKo61m3S/xZk1x4wA6yp/L3RFP6Z/eHH1ymQcGLo7J3GMPfm0V/7m1tryHuGVxpqEBQ==", + "license": "MIT" + }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", + "license": "MIT" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", + "license": "MIT" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "license": "MIT" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", + "license": "MIT" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", + "license": "MIT" + }, + "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", + "optional": true + }, + "node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/lru-memoizer": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/lru-memoizer/-/lru-memoizer-2.3.0.tgz", + "integrity": "sha512-GXn7gyHAMhO13WSKrIiNfztwxodVsP8IoZ3XfrJV4yH2x0/OeTO/FIaAHTY5YekdGgW94njfuKmyyt1E0mR6Ug==", + "license": "MIT", + "dependencies": { + "lodash.clonedeep": "^4.5.0", + "lru-cache": "6.0.0" + } + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -925,6 +1945,19 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/mime": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz", + "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==", + "license": "MIT", + "optional": true, + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/mime-db": { "version": "1.54.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", @@ -981,6 +2014,15 @@ } } }, + "node_modules/node-forge": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.3.tgz", + "integrity": "sha512-rLvcdSyRCyouf6jcOIPe/BgwG/d7hKjzMKOas33/pHEr6gbq18IK9zV7DiPvzsz0oBJPme6qr6H6kGZuI9/DZg==", + "license": "(BSD-3-Clause OR GPL-2.0)", + "engines": { + "node": ">= 6.13.0" + } + }, "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", @@ -990,6 +2032,16 @@ "node": ">=0.10.0" } }, + "node_modules/object-hash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz", + "integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 6" + } + }, "node_modules/object-inspect": { "version": "1.13.4", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", @@ -1023,6 +2075,22 @@ "wrappy": "1" } }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/pako": { "version": "0.2.9", "resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz", @@ -1066,6 +2134,44 @@ "resolved": "https://registry.npmjs.org/png-js/-/png-js-1.0.0.tgz", "integrity": "sha512-k+YsbhpA9e+EFfKjTCH3VW6aoKlyNYI6NYdTfDL4CIvFnvsuO84ttonmZE7rc+v23SLTH8XX+5w/Ak9v0xGY4g==" }, + "node_modules/proto3-json-serializer": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/proto3-json-serializer/-/proto3-json-serializer-2.0.2.tgz", + "integrity": "sha512-SAzp/O4Yh02jGdRc+uIrGoe87dkN/XtwxfZ4ZyafJHymd79ozp5VG5nyZ7ygqPM5+cpLDjjGnYFUkngonyDPOQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "protobufjs": "^7.2.5" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "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", + "optional": true, + "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/proxy-addr": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", @@ -1140,12 +2246,62 @@ "url": "https://opencollective.com/express" } }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "optional": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/restructure": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/restructure/-/restructure-3.0.2.tgz", "integrity": "sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==", "license": "MIT" }, + "node_modules/retry": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", + "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/retry-request": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/retry-request/-/retry-request-7.0.2.tgz", + "integrity": "sha512-dUOvLMJ0/JJYEn8NrpOaGNE7X3vpI5XlZS/u0ANjqtcZVKnIxP7IgCFwrKTxENw29emmwug53awKtaMm4i9g5w==", + "license": "MIT", + "optional": true, + "dependencies": { + "@types/request": "^2.48.8", + "extend": "^3.0.2", + "teeny-request": "^9.0.0" + }, + "engines": { + "node": ">=14" + } + }, "node_modules/router": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", @@ -1188,6 +2344,18 @@ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "license": "MIT" }, + "node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/send": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/send/-/send-1.2.0.tgz", @@ -1312,6 +2480,125 @@ "node": ">= 0.8" } }, + "node_modules/stream-events": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/stream-events/-/stream-events-1.0.5.tgz", + "integrity": "sha512-E1GUzBSgvct8Jsb3v2X15pjzN1tYebtbLaMg+eBOUOAxgbLoSbT2NS91ckc5lJD1KfLjId+jXJRgo0qnV5Nerg==", + "license": "MIT", + "optional": true, + "dependencies": { + "stubs": "^3.0.0" + } + }, + "node_modules/stream-shift": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.3.tgz", + "integrity": "sha512-76ORR0DO1o1hlKwTbi/DM3EXWGf3ZJYO8cXX5RJwnul2DEg2oyoZyjLNoQM8WsvZiFKCRfC1O0J7iCvie3RZmQ==", + "license": "MIT", + "optional": true + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "optional": true, + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "optional": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "optional": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strnum": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-1.1.2.tgz", + "integrity": "sha512-vrN+B7DBIoTTZjnPNewwhx6cBA/H+IS7rfW68n7XxC1y7uoiGQBxaKzqucGUgavX15dJgiGztLJ8vxuEzwqBdA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "optional": true + }, + "node_modules/stubs": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/stubs/-/stubs-3.0.0.tgz", + "integrity": "sha512-PdHt7hHUJKxvTCgbKX9C1V/ftOcjJQgz8BZwNfV5c4B6dcGqlpelTbJ999jBGZ2jYiPAwcX5dP6oBwVlBlUbxw==", + "license": "MIT", + "optional": true + }, + "node_modules/teeny-request": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/teeny-request/-/teeny-request-9.0.0.tgz", + "integrity": "sha512-resvxdc6Mgb7YEThw6G6bExlXKkv6+YbuzGg9xuXxSgxJF7Ozs+o8Y9+2R3sArdWdW8nOokoQb1yrpFB0pQK2g==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "http-proxy-agent": "^5.0.0", + "https-proxy-agent": "^5.0.0", + "node-fetch": "^2.6.9", + "stream-events": "^1.0.5", + "uuid": "^9.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/teeny-request/node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/teeny-request/node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "license": "MIT", + "optional": true, + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/tiny-inflate": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz", @@ -1353,6 +2640,12 @@ "node": ">= 0.6" } }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "license": "MIT" + }, "node_modules/unicode-properties": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/unicode-properties/-/unicode-properties-1.4.1.tgz", @@ -1382,6 +2675,13 @@ "node": ">= 0.8" } }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT", + "optional": true + }, "node_modules/uuid": { "version": "9.0.1", "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", @@ -1410,6 +2710,29 @@ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", "license": "BSD-2-Clause" }, + "node_modules/websocket-driver": { + "version": "0.7.4", + "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.4.tgz", + "integrity": "sha512-b17KeDIQVjvb0ssuSDF2cYXSg2iztliJ4B9WdsuB6J952qCPKmnVq4DyW5motImXHDC1cBT/1UezrJVsKw5zjg==", + "license": "Apache-2.0", + "dependencies": { + "http-parser-js": ">=0.5.1", + "safe-buffer": ">=5.1.0", + "websocket-extensions": ">=0.1.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/websocket-extensions": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.4.tgz", + "integrity": "sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8.0" + } + }, "node_modules/whatwg-url": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", @@ -1420,6 +2743,24 @@ "webidl-conversions": "^3.0.0" } }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "optional": true, + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", @@ -1446,6 +2787,64 @@ "optional": true } } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "license": "ISC", + "optional": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "license": "ISC" + }, + "node_modules/yargs": { + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "license": "MIT", + "optional": true, + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "license": "ISC", + "optional": true, + "engines": { + "node": ">=12" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } } } } diff --git a/backend/package.json b/backend/package.json index 3eabe41..75c06ee 100644 --- a/backend/package.json +++ b/backend/package.json @@ -17,6 +17,7 @@ "cors": "^2.8.5", "dotenv": "^17.2.3", "express": "^5.1.0", + "firebase-admin": "^13.6.0", "pdfkit": "^0.17.2" } } diff --git a/backend/src/Journal.js b/backend/src/Journal.js new file mode 100644 index 0000000..78ccf31 --- /dev/null +++ b/backend/src/Journal.js @@ -0,0 +1,107 @@ +const db = require("./config/firebase"); + +// --- Journal Controller Logic --- + +// Function to get all journals +const getAllJournals = async (req, res) => { + try { + const journalsRef = db.collection("journals"); + const snapshot = await journalsRef.orderBy("created_at", "desc").get(); + const journals = []; + snapshot.forEach((doc) => { + const data = doc.data(); + journals.push({ + id: doc.id, + title: data.title, + content: data.content, + created_at: data.created_at.toDate(), // Convert Firestore Timestamp to JavaScript Date + time_formatted: data.created_at.toDate().toISOString(), // Optional: for frontend display + }); + }); + + res.status(200).json(journals); + } catch (error) { + console.error("Error getting journals:", error); + res.status(500).json({ error: "Failed to retrieve journals" }); + } +}; + +const createJournal = async (req, res) => { + try { + const { title, content } = req.body; + + if (!title || !content) { + return res.status(400).json({ error: "Title and content cannot be empty" }); + } + + const newJournalRef = db.collection("journals").doc(); + const newJournal = { + title, + content, + created_at: new Date(), // Server-generated timestamp + }; + + await newJournalRef.set(newJournal); + + res.status(201).json({ id: newJournalRef.id, ...newJournal, time_formatted: newJournal.created_at.toISOString() }); + } catch (error) { + console.error("Error creating journal:", error); + res.status(500).json({ error: "Failed to create journal" }); + } +}; + +const updateJournal = async (req, res) => { + try { + const { id } = req.params; + const { title, content } = req.body; + + if (!title && !content) { + return res.status(400).json({ error: "Title or content must be provided" }); + } + + const journalRef = db.collection("journals").doc(id); + const doc = await journalRef.get(); + + if (!doc.exists) { + return res.status(404).json({ error: "Journal not found" }); + } + + const updatedData = {}; + if (title) updatedData.title = title; + if (content) updatedData.content = content; + updatedData.updated_at = new Date(); + + await journalRef.update(updatedData); + + res.status(200).json({ id, ...updatedData }); + } catch (error) { + console.error("Error updating journal:", error); + res.status(500).json({ error: "Failed to update journal" }); + } +}; + +const deleteJournal = async (req, res) => { + try { + const { id } = req.params; + const journalRef = db.collection("journals").doc(id); + const doc = await journalRef.get(); + + if (!doc.exists) { + return res.status(404).json({ error: "Journal not found" }); + } + + await journalRef.delete(); + + res.status(200).json({ message: "Journal deleted successfully" }); + } catch (error) { + console.error("Error deleting journal:", error); + res.status(500).json({ error: "Failed to delete journal" }); + } +}; + +module.exports = { + getAllJournals, + createJournal, + updateJournal, + deleteJournal, +}; diff --git a/backend/src/api/chat.js b/backend/src/api/chat.js index f78f3a5..1c6a09b 100644 --- a/backend/src/api/chat.js +++ b/backend/src/api/chat.js @@ -4,10 +4,16 @@ const express = require("express"); const chatController = require("../controllers/chatController"); const router = express.Router(); -// Alamat untuk mengirim chat biasa +// 1. Kirim Chat (Bisa chat baru atau balasan) router.post("/chat", chatController.handleChat); -// Alamat untuk meminta summary (KEMBALIKAN KE POST) +// 2. Ambil List History (Daftar semua sesi curhat) +router.get("/history", chatController.getChatHistory); + +// 3. Ambil Detail Pesan (Isi chat dalam satu sesi) +router.get("/session/:sessionId", chatController.getSessionMessages); + +// 4. Minta Summary PDF router.post("/summary", chatController.handleSummary); module.exports = router; diff --git a/backend/src/api/journal.js b/backend/src/api/journal.js new file mode 100644 index 0000000..657154b --- /dev/null +++ b/backend/src/api/journal.js @@ -0,0 +1,17 @@ +const express = require("express"); +const journalController = require("../Journal"); +const router = express.Router(); + +// Route to get all journals +router.get("/journals", journalController.getAllJournals); + +// Route to create a new journal +router.post("/journals", journalController.createJournal); + +// Route to update a journal +router.put("/journals/:id", journalController.updateJournal); + +// Route to delete a journal +router.delete("/journals/:id", journalController.deleteJournal); + +module.exports = router; diff --git a/backend/src/config/firebase.js b/backend/src/config/firebase.js new file mode 100644 index 0000000..89e51ad --- /dev/null +++ b/backend/src/config/firebase.js @@ -0,0 +1,28 @@ +const admin = require('firebase-admin'); +require('dotenv').config(); + +// Ganti dengan path ke serviceAccountKey.json Anda +// const serviceAccount = require('./path/to/your/serviceAccountKey.json'); +// Untuk produksi, lebih baik menggunakan variabel lingkungan + +const serviceAccount = { + type: process.env.FIREBASE_TYPE, + project_id: process.env.FIREBASE_PROJECT_ID, + private_key_id: process.env.FIREBASE_PRIVATE_KEY_ID, + private_key: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'), + client_email: process.env.FIREBASE_CLIENT_EMAIL, + client_id: process.env.FIREBASE_CLIENT_ID, + auth_uri: process.env.FIREBASE_AUTH_URI, + token_uri: process.env.FIREBASE_TOKEN_URI, + auth_provider_x509_cert_url: process.env.FIREBASE_AUTH_PROVIDER_X509_CERT_URL, + client_x509_cert_url: process.env.FIREBASE_CLIENT_X509_CERT_URL, + universe_domain: process.env.FIREBASE_UNIVERSE_DOMAIN, +}; + +admin.initializeApp({ + credential: admin.credential.cert(serviceAccount) +}); + +const db = admin.firestore(); + +module.exports = db; diff --git a/backend/src/controllers/chatController.js b/backend/src/controllers/chatController.js index 94a4b27..aaf53e5 100644 --- a/backend/src/controllers/chatController.js +++ b/backend/src/controllers/chatController.js @@ -2,44 +2,171 @@ const aiService = require("../services/aiService"); const PDFDocument = require("pdfkit"); +const db = require("../config/firebase"); // Pastikan path ini benar -// --- Fungsi untuk Handle Chat (Tetap sama, tidak berubah) --- +// --- KONFIGURASI SEMENTARA --- +const HARDCODED_USER_ID = "Orang Baik"; + +// --- 1. Handle Chat (Logic Utama) --- const handleChat = async (req, res) => { try { - const userMessage = req.body.message; - if (!userMessage) { + // sessionId dikirim dari Flutter. Jika null, berarti buat sesi baru. + const { message, sessionId } = req.body; + + if (!message) { return res.status(400).json({ error: "Pesan tidak boleh kosong" }); } - const aiReply = await aiService.getAIChatResponse(userMessage); - res.json({ reply: aiReply }); + + let currentSessionId = sessionId; + let sessionRef; + let sessionTitle = ""; + + // --- LOGIKA: SESI BARU VS SESI LAMA --- + if (!currentSessionId) { + // A. CHAT BARU (Buat Room Baru) + + // Judul otomatis dari 30 huruf pertama + sessionTitle = message.length > 30 ? message.substring(0, 30) + "..." : message; + let preview = message.length > 50 ? message.substring(0, 50) + "..." : message; + + // Simpan Sesi ke Firestore + const newSession = await db.collection("chat_sessions").add({ + userId: HARDCODED_USER_ID, + title: sessionTitle, + preview: preview, + createdAt: new Date(), + updatedAt: new Date(), + }); + + currentSessionId = newSession.id; + sessionRef = newSession; + + } else { + // B. LANJUT CHAT (Pakai Room Lama) + sessionRef = db.collection("chat_sessions").doc(currentSessionId); + + // Update waktu agar naik ke paling atas list + await sessionRef.update({ + updatedAt: new Date(), + preview: message.length > 50 ? message.substring(0, 50) + "..." : message + }); + } + + // --- SIMPAN PESAN & DAPATKAN BALASAN AI --- + + // 1. Simpan pesan User + await sessionRef.collection("messages").add({ + role: "user", + content: message, + createdAt: new Date(), + }); + + // 2. Panggil AI + const aiReply = await aiService.getAIChatResponse(message); + + // 3. Simpan balasan AI + await sessionRef.collection("messages").add({ + role: "model", + content: aiReply, + createdAt: new Date(), + }); + + // 4. Return response + res.json({ + reply: aiReply, + sessionId: currentSessionId, + title: !sessionId ? sessionTitle : undefined + }); + } catch (error) { console.error("Error di chat controller:", error); res.status(500).json({ error: "Terjadi kesalahan pada server" }); } }; -// --- Fungsi untuk Handle Summary (KEMBALIKAN KE VERSI ASLI) --- +// --- 2. Get Chat History List (Untuk Halaman List) --- +const getChatHistory = async (req, res) => { + try { + const snapshot = await db.collection("chat_sessions") + .where("userId", "==", HARDCODED_USER_ID) + .orderBy("updatedAt", "desc") + .get(); + // Jangan lupa dihapus +// console.log("History Chat:", snapshot); + + const history = []; + snapshot.forEach((doc) => { + const data = doc.data(); + history.push({ + id: doc.id, + title: data.title, + preview: data.preview, + updatedAt: data.updatedAt.toDate() + }); + }); + + res.json(history); + } catch (error) { + console.error("Error ambil history:", error); + res.status(500).json({ error: "Gagal mengambil riwayat chat" }); + } +}; + +// --- 3. Get Specific Session Messages (Saat Card diklik) --- +const getSessionMessages = async (req, res) => { + try { + const { sessionId } = req.params; + + const snapshot = await db.collection("chat_sessions") + .doc(sessionId) + .collection("messages") + .orderBy("createdAt", "asc") + .get(); + + const messages = []; + snapshot.forEach((doc) => { + messages.push({ id: doc.id, ...doc.data() }); + }); + + res.json(messages); + } catch (error) { + console.error("Error ambil pesan:", error); + res.status(500).json({ error: "Gagal mengambil pesan" }); + } +}; + +// --- 4. Handle Summary (Tetap sama) --- const handleSummary = async (req, res) => { try { - // 1. AKTIFKAN KEMBALI pengambilan data dari body permintaan - const chatHistory = req.body.history; + const chatHistory = req.body.history || []; + + const journalsRef = db.collection("journals"); + const snapshot = await journalsRef.orderBy("created_at", "desc").get(); + + const journalEntries = []; + snapshot.forEach((doc) => { + const data = doc.data(); + journalEntries.push(`--- JOURNAL ENTRY ---\nTitle: ${data.title}\nContent: ${data.content}\n--- END JOURNAL ENTRY ---`); + }); - // 2. HAPUS data history yang di-hardcode (sudah tidak diperlukan lagi) + const combinedHistory = [ + "--- START CHAT HISTORY ---", + ...chatHistory, + "--- END CHAT HISTORY ---", + "--- START JOURNAL ENTRIES ---", + ...journalEntries, + "--- END JOURNAL ENTRIES ---", + ]; - // 3. AKTIFKAN KEMBALI validasi untuk data yang datang dari frontend - if (!chatHistory || chatHistory.length === 0) { - return res.status(400).json({ error: "Riwayat chat tidak boleh kosong" }); + if (combinedHistory.length === 0) { + return res.status(400).json({ error: "Riwayat chat dan jurnal tidak boleh kosong" }); } - // Sisa kode di bawah ini tetap sama persis - const summaryText = await aiService.getAISummary(chatHistory); + const summaryText = await aiService.getAISummary(combinedHistory); const doc = new PDFDocument(); res.setHeader("Content-Type", "application/pdf"); - res.setHeader( - "Content-Disposition", - 'attachment; filename="ringkasan_curhat.pdf"' - ); + res.setHeader('Content-Disposition', 'attachment; filename="ringkasan_curhat.pdf"'); doc.pipe(res); doc.fontSize(20).text("Ringkasan Konsultasi", { align: "center" }); doc.moveDown(); @@ -51,8 +178,9 @@ const handleSummary = async (req, res) => { } }; -// Ekspor KEDUA fungsi module.exports = { handleChat, + getChatHistory, + getSessionMessages, handleSummary, }; diff --git a/backend/src/index.js b/backend/src/index.js index 5de6317..107e5e4 100644 --- a/backend/src/index.js +++ b/backend/src/index.js @@ -4,6 +4,7 @@ const express = require("express"); const cors = require("cors"); // 1. Panggil file rute yang sudah kita buat const chatRoutes = require("./api/chat"); +const journalRoutes = require("./api/journal"); const app = express(); // Gunakan port dari environment variable jika ada, atau 3000 jika tidak ada @@ -16,6 +17,7 @@ app.use(express.json()); // Middleware untuk membaca body JSON // Beritahu Express: "Untuk setiap permintaan yang alamatnya diawali dengan '/api', // tolong gunakan aturan yang ada di dalam 'chatRoutes'." app.use("/api", chatRoutes); +app.use("/api", journalRoutes); app.listen(port, () => { console.log(`Server backend berjalan di http://localhost:${port}`); diff --git a/backend/src/services/aiService.js b/backend/src/services/aiService.js index c952de7..0420de2 100644 --- a/backend/src/services/aiService.js +++ b/backend/src/services/aiService.js @@ -1,183 +1,74 @@ // backend/src/services/aiService.js -// require("dotenv").config(); -// const { GoogleGenerativeAI } = require("@google/generative-ai"); - -// const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY); -// const model = genAI.getGenerativeModel({ model: "gemini-2.5-flash" }); - -// const getAIChatResponse = async (userMessage) => { -// try { -// // 1. Definisikan "System Prompt" atau instruksi awal -// const systemPrompt = ` -// Anda adalah "Sana", seorang asisten psikologi AI yang hangat, empatik, dan suportif. -// Balaslah curhatan pengguna dengan aturan seperti ini: -// 1. Balas dengan kata-kata sehari-hari atau non-formal (kalimat yang terkesan santai tetapi mengandung empati). -// 2. Jangan menanya-nanyakan hal yang tidak perlu, cukup respons seperti seorang pendengar yang baik. -// 3. Jangan pernah membawa topik tidak senonoh atau menggunakan kata kasar. -// 4. Selalu balas dalam bahasa Indonesia. -// `; - -// // 2. Mulai sesi chat dengan instruksi sistem terlebih dahulu -// const chat = model.startChat({ -// history: [ -// { -// role: "user", -// parts: [{ text: systemPrompt }], -// }, -// { -// role: "model", -// parts: [{ text: "Tentu, saya mengerti. Saya siap mendengarkan." }], // Balasan AI untuk "memakan" instruksi -// }, -// ], -// }); - -// // 3. Kirim pesan pengguna yang sebenarnya -// const result = await chat.sendMessage(userMessage); -// const response = await result.response; -// const aiReply = response.text(); +require("dotenv").config(); +const { GoogleGenerativeAI } = require("@google/generative-ai"); -// return aiReply; -// } catch (error) { -// console.error("Error dari Google Generative AI:", error); -// throw new Error("Gagal mendapatkan balasan dari AI"); -// } -// }; +// Pastikan API Key ada +if (!process.env.GEMINI_API_KEY) { + throw new Error("GEMINI_API_KEY tidak ditemukan di file .env"); +} -// const getAISummary = async (history) => { -// try { -// const fullText = history.join("\n"); -// const prompt = `Ringkaslah percakapan berikut menjadi poin-poin utama yang mudah dipahami oleh seorang psikolog. Fokus pada keluhan utama, perasaan yang diekspresikan, dan potensi pemicu masalah. Gunakan bahasa Indonesia yang formal dan terstruktur:\n\n---\n\n${fullText}`; +// Inisialisasi Client Google Generative AI +const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY); -// const result = await model.generateContent(prompt); -// const response = await result.response; -// return response.text(); -// } catch (error) { -// console.error("Error saat membuat summary dengan AI:", error); -// throw new Error("Gagal membuat ringkasan dari AI"); -// } -// }; +// --- Konfigurasi System Prompt (Persona Sana) --- +const systemPromptSana = ` +**[PERAN DAN TUJUAN]** +Anda adalah "Sana", sebuah AI Companion yang dirancang sebagai ruang aman untuk refleksi diri. Tujuan utama Anda adalah menjadi pendengar yang empatik dan membantu pengguna memahami perasaan mereka sendiri dengan lebih baik. Anda BUKAN terapis dan tidak boleh memberikan nasihat medis. -// module.exports = { -// getAIChatResponse, -// getAISummary, -// }; +**[KEPRIBADIAN]** +Kepribadian Anda hangat, sabar, dan tidak menghakimi. Gunakan gaya bahasa yang santai dan natural seperti teman dekat yang bijaksana. Selalu panggil pengguna dengan sapaan akrab jika nama mereka disebutkan, atau gunakan "kamu". -//API Proxy +**[STRUKTUR RESPONS]** +Setiap balasan Anda harus mengikuti struktur 3 langkah ini: +1. **Validasi:** Mulailah dengan mengakui dan memvalidasi perasaan atau situasi yang dibagikan pengguna. Tunjukkan bahwa Anda mengerti. (Contoh: "Kedengarannya situasi itu membuatmu sangat tertekan," atau "Terima kasih sudah berbagi, itu pasti tidak mudah."). +2. **Refleksi/Perspektif:** Berikan satu kalimat reflektif yang singkat atau perspektif yang menenangkan, tanpa memberikan nasihat. (Contoh: "Tidak apa-apa untuk merasa kewalahan," atau "Penting untuk diingat bahwa perasaanmu itu valid."). +3. **Ajakan (Invitation):** Akhiri dengan sebuah pertanyaan terbuka yang lembut dan tidak memaksa, yang mengundang pengguna untuk bercerita lebih dalam. (Contoh: "Apakah ada bagian tertentu dari perasaan itu yang paling mengganggumu?", "Bagaimana perasaanmu saat ini ketika menceritakannya?", atau "Jika kamu nyaman, boleh ceritakan lebih lanjut?"). -// backend/src/services/aiService.js -require("dotenv").config(); -const axios = require("axios"); // Kita kembali menggunakan axios! +**[BATASAN]** +- Jangan pernah memberikan diagnosis atau nasihat medis. +- Jangan pernah menggunakan bahasa yang kasar, tidak senonoh, atau menghakimi. +- Selalu berkomunikasi dalam Bahasa Indonesia. +`; // --- Fungsi untuk Chat --- const getAIChatResponse = async (userMessage) => { try { - const PROXY_API_KEY = process.env.PROXY_API_KEY; - - if (!PROXY_API_KEY) { - throw new Error("PROXY_API_KEY tidak ditemukan di file .env"); - } - - // 1. URL Endpoint dari panduan teman Anda - const url = - "https://krsbeknjypkg.sg-members-1.clawcloudrun.com/proxy/gemini/v1beta/openai/chat/completions"; // Tambahkan /chat/completions di akhir - - // 2. Body/Payload permintaan, mengikuti format OpenAI - const data = { - model: "gemini-2.5-pro", // Gunakan nama model yang disarankan teman Anda - messages: [ - { - role: "system", - content: ` - **[PERAN DAN TUJUAN]** - Anda adalah "Sana", sebuah AI Companion yang dirancang sebagai ruang aman untuk refleksi diri. Tujuan utama Anda adalah menjadi pendengar yang empatik dan membantu pengguna memahami perasaan mereka sendiri dengan lebih baik. Anda BUKAN terapis dan tidak boleh memberikan nasihat medis. - - **[KEPRIBADIAN]** - Kepribadian Anda hangat, sabar, dan tidak menghakimi. Gunakan gaya bahasa yang santai dan natural seperti teman dekat yang bijaksana. Selalu panggil pengguna dengan sapaan akrab jika nama mereka disebutkan, atau gunakan "kamu". - - **[STRUKTUR RESPONS]** - Setiap balasan Anda harus mengikuti struktur 3 langkah ini: - 1. **Validasi:** Mulailah dengan mengakui dan memvalidasi perasaan atau situasi yang dibagikan pengguna. Tunjukkan bahwa Anda mengerti. (Contoh: "Kedengarannya situasi itu membuatmu sangat tertekan," atau "Terima kasih sudah berbagi, itu pasti tidak mudah."). - 2. **Refleksi/Perspektif:** Berikan satu kalimat reflektif yang singkat atau perspektif yang menenangkan, tanpa memberikan nasihat. (Contoh: "Tidak apa-apa untuk merasa kewalahan," atau "Penting untuk diingat bahwa perasaanmu itu valid."). - 3. **Ajakan (Invitation):** Akhiri dengan sebuah pertanyaan terbuka yang lembut dan tidak memaksa, yang mengundang pengguna untuk bercerita lebih dalam. (Contoh: "Apakah ada bagian tertentu dari perasaan itu yang paling mengganggumu?", "Bagaimana perasaanmu saat ini ketika menceritakannya?", atau "Jika kamu nyaman, boleh ceritakan lebih lanjut?"). - - **[BATASAN]** - - Jangan pernah memberikan diagnosis atau nasihat medis. - - Jangan pernah menggunakan bahasa yang kasar, tidak senonoh, atau menghakimi. - - Selalu berkomunikasi dalam Bahasa Indonesia. - `, - }, - { - role: "user", - content: userMessage, - }, - ], - }; - - // 3. Headers permintaan, termasuk API Key dengan format "Bearer" - const headers = { - Authorization: `Bearer ${PROXY_API_KEY}`, - "Content-Type": "application/json", - }; - - // 4. Mengirim permintaan menggunakan axios - const response = await axios.post(url, data, { headers: headers }); - - let aiReply = response.data.choices[0].message.content; - - // 5. Mengambil balasan dari struktur respons OpenAI + // Menggunakan model gemini-2.5-flash sesuai permintaan + const model = genAI.getGenerativeModel({ + model: "gemini-2.5-flash", + systemInstruction: systemPromptSana, // System prompt masuk di sini + }); + + // Kirim pesan + const result = await model.generateContent(userMessage); + const response = await result.response; + let aiReply = response.text(); + + // Bersihkan format newline berlebih jika perlu aiReply = aiReply.replace(/\n/g, " "); return aiReply; } catch (error) { - if (error.response) { - console.error( - "Error dari Proxy API:", - error.response.status, - error.response.data - ); - } else { - console.error("Error saat mengirim permintaan:", error.message); - } + console.error("Error dari Google Generative AI:", error); throw new Error("Gagal mendapatkan balasan dari AI"); } }; -// --- Fungsi untuk Summary (JUGA HARUS DIUPDATE) --- +// --- Fungsi untuk Summary --- const getAISummary = async (history) => { try { - const PROXY_API_KEY = process.env.PROXY_API_KEY; + // Untuk summary, kita panggil model tanpa systemInstruction khusus Sana + const model = genAI.getGenerativeModel({ model: "gemini-2.5-flash" }); - if (!PROXY_API_KEY) { - throw new Error("PROXY_API_KEY tidak ditemukan di file .env"); - } - - const url = - "https://krsbeknjypkg.sg-members-1.clawcloudrun.com/proxy/gemini/v1beta/openai/chat/completions"; const fullText = history.join("\n"); - const prompt = `Ringkaslah percakapan berikut menjadi poin-poin utama yang mudah dipahami oleh seorang psikolog. Fokus pada keluhan utama, perasaan yang diekspresikan, dan potensi pemicu masalah. Gunakan bahasa Indonesia yang formal dan terstruktur:\n\n---\n\n${fullText}`; - - const data = { - model: "gemini-2.5-pro", - messages: [{ role: "user", content: prompt }], - }; + const prompt = `Ringkaslah percakapan berikut menjadi poin-poin utama yang mudah dipahami oleh seorang psikolog. Fokus pada keluhan utama, perasaan yang diekspresikan, dan potensi pemicu masalah. Pertimbangkan juga content jurnal yang telah diisi pengguna untuk mengetahui informasi tambahan untuk konteks lebih dalam, karakter pengguna, progress pemulihan mental pengguna, dan keseharian pengguna. Gunakan bahasa Indonesia yang formal dan terstruktur:\n\n---\n\n${fullText}`; - const headers = { - Authorization: `Bearer ${PROXY_API_KEY}`, - "Content-Type": "application/json", - }; + const result = await model.generateContent(prompt); + const response = await result.response; - const response = await axios.post(url, data, { headers: headers }); - return response.data.choices[0].message.content; + return response.text(); } catch (error) { - if (error.response) { - console.error( - "Error dari Proxy API saat membuat summary:", - error.response.status, - error.response.data - ); - } else { - console.error("Error saat mengirim permintaan summary:", error.message); - } + console.error("Error saat membuat summary dengan AI:", error); throw new Error("Gagal membuat ringkasan dari AI"); } }; diff --git a/flutter_app/assets/design/Chat-History Page.png b/flutter_app/assets/design/Chat-History Page.png new file mode 100644 index 0000000000000000000000000000000000000000..b929f90d3274aaa5729e5a564e47f3b470436e18 GIT binary patch literal 14257 zcmeHucTiL9_a|aODFUKMN97e%5L9{z5vBPeAR@hlA~iG#9Rh+PAnjEUB%vrsFQG?T zf>dbw=H21%!!-jpvV@VuEGzF;1R>JlA=| zRDls%WgMJw(a_gmVya4JJGMW|#H6VGL{sBM(5a1?(0}rmpc3Rlg8IHs#;IlTfmry% zYk$=;XI^?!^V}jTA|X@PVtlG+;jV;JXUWXei|3M5#HW^s;HBPzkN$3sW|Wc~lx-up*CNv7|2_Mp9w22F0_*jO&638#BX zT1ij5;JZqF`8z9xgg4uoX?aN%cT`>2;Y5emh9B4GpIARa?EmGn5Pu2uvpxgGw;?m= zfgJE%AvrEZ9QBHhMQk;DfGKG7F7D=VI(;-JjTS+BK|9DX!?xs2o%@^OLMMWkwgtP1 zX!`L%L}(8)p%niesdmzTNFYa?l*^>TE7mq#6i`6ABZ(qdj?&wi*b%b-n$ve^ut^_E zmN=Lh4GkFAs2?W0zd4f98a&^MEs^OI)o+kujS)`Irq3tI{79$IVGFFuE%ZH5>gXor zG{WG7)+WhvRaj|2qcx39!R+inMVnnHDg>b|;r=X7!XP#JeK%#i+{Ysx+jcc#slvA# z1!t3rMv>;H4+b4=WW19WGVZ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&7`50zRJ?)UVq~>VbyH+$UN6#W3|Mmsi$%^a%kjY0l4HnhEmfF zvikT4fT@WagnMmdhiFb!a9)5rEihVivLGA;N{PwKI;#(n!-)HP!^$DYq&B;_4{qGI z3NNb9_#eS<9pcMbe1p5-VTr)XVKa^0fQeLne#Nb#8lZBA& z!r`Rn;DVI6oI0!ePx2-_Juu=ym;^mDtl9kh=Aj@dL;+$!R?*JW;`vf(VROTk@j3@ahrGn?){S}T%mWzT-2wKM#fl8ER5wrp3THGUvhc7f1-;N<@Zd{?amkS&Yb4_ z4qjai=N`Z9^RVa1E#PS{6!ZH}ji#2&P(6mG+ar3n+0AH=uX=-g@LX>s+UzS*PGN6) z2*gO3irTuJW)0hw%#z&F8Xd2dFMZ6TcK^#zH8zfHjp1$FpOyf z<*hzdU2>p=GZS>&KraCcu8U#SGeekf>w&{&t4oP!$5e~A24%NY7_x1V4un>x*0^8= zr>w_K$11Xfo>e-x``q54M#Yc5EV}!bhbi$$sq{#YTd&DreEw>l;Ta6^MY3+G`(N%i z`x$4y^(|Yb7{Ruw_AEuC7NB%cF95w{)Wk0o^TKVAmcl;?G zjfqUdIi~%eNpbvtIeeS)ka$~BUwMI<#f}%k5uKI3UJ-$<*T%TB!z*u`mY}lFkk%9~ z+buPQ985d=%vSlU`6P+tgmeEK6;QC(x)`72?zwy?EYxf$gtt;aOG#5#4LaAuPj!MV zohz{N50a13H~+wBNY`B8NH)45%bz{3pUkO!+)w5k()j+o@GH|S&vkC6K5I=$y-@Y8 zkSusfnjbA&&}@`7C+l6;9jEA!`B4{Qi6>I*W4V=dsXEg*=5RUrMOOH*@KDEOhf$4N z$ski=!Fp`xWPleAu=r!cy*l?a%j+NZsRB&5&s_Y!w-X+X(*jtoh1gam#^;Hafo8=c HyQu#LtJ*{r literal 0 HcmV?d00001 diff --git a/flutter_app/assets/design/Current-_chat_history.png b/flutter_app/assets/design/Current-_chat_history.png new file mode 100644 index 0000000000000000000000000000000000000000..979495da38a806d0150af1a8a41be79830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jF}(#7|IkiEoflhBs3gG{J)iVk}-yfnTUOo=7kETkHs&^&wP9Er{t7 zIVRk-?Sq4ZKZiL8rMgq8v}ZT3!S9A2BB_-WUw>8lbg+3kJ*A=um&!4oj`#T+GVUJc z)Frzhg|1VUIxHQta9wlgaTUZiXZUz-mVM~Ag6ShY3I_RwLf7EcDbTMaF9K`y&2OB> z7|15m!mzoxnauOr&__~xCeD>3w9u&bf`ir(CL;~VwPbZjZnMzjYm-gcj&z8qi$c%D zWBf6>)pWnza)hVJ#NEU`LHbC_2wYDqg1l^*e?`vqs9B)v+MGTZ88slOtBYbPTbi3+ z`RaI^2bo{3UE12Nem}5?i+sW9>>jA)0^yziIfU$ov_D_#O4}7s*|I_VZF^}<4B7YS z72jrD^+mI#BTK{!4xy!A7)ld literal 0 HcmV?d00001 diff --git a/flutter_app/assets/design/Current-_homepage.png b/flutter_app/assets/design/Current-_homepage.png new file mode 100644 index 0000000000000000000000000000000000000000..a4ed8913705d4eaaddc4f30043f1783d2c2a4bea GIT binary patch literal 4590 zcmXX}bzBqN_a306bVv^zC?PF^ba#oPOB!AfUT}0vDY1btP>^OYQYop?F)8UrkQ_M> z35mgXzQ5lex6X6#x#!$_KIcC7osoeiB{?fO005xW)>1PD00@fleM3@Wd|ljB(}{1$ z{?)R04FFKk|1AW7tWV5%A;D{7O%*`(clI6p;Et=ZzA^w%1EaXMzY74+Mr*4ng98Z; za;!WV(Jbf=c?E?zcB_}@>KfjENd<%qBKhJ`N)s{ygk{F>1?b9;-w)|dE7T_+8<$c0 z1(r=^KHSl*PtdY$7UY|-O zIu)&$^`l?TS+favC{o?$9Q(s;Z+F)gxmBGNw=q02!ZEPvJ4%BGzo^9+1>2A!FtKk` zRmOc@dHIUnSTMH{+TQ^HUN)0j9PbYg4+}2sGO2&-_b7So;_8~mII%BIDldYc zf6Fktn5vhMEqGP z!CIfm5`B>`XFWJ=nG&Tnj{^Paf)%`ro#iQ`n2v~@34|$k8lm{Nj+dupjg3+Pdoxwu z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(3FoZ-@tDC+%tj(jt54ZV5V|SfTlf5%exncv(jj`>xkG6&WplT$&d$z4Jv~K7TzgD~(7|668h&Y-ki64R zc_g-+;=Jk;k)QLZF6L<*wl$oKi7b&jWXR;m7+sg}Fz@&%oez?qC+XSQ$v$ke3_dXD zSAHaUY1-lNDUG#_7gHKH(*KFkp32^XxYYCBtkoysYTbAtjf~pb+D#G? z63YtY#sJiWh1b|0X;D{OJBHcaeKF_0^UG%QosOJEJKNd-a>0L2HXtZC@#ZGn0nHDM z#dXTQ+m#D4SvvS|b9lX17@TaUASE~|v)9x2q~DVZ64?Fu_mP*pB#eofIBI z*k%)xvLt`141ynM69u}jOYYAX7O?6q`aa#{$~<%7URV1q%{E6R5pjQGry_0plF@~O zrKI0oK~&yq)GuMgBnW?WGck#)mymF()jR?11Z}*|`gmgROO@m7VJa!X!an0Q7mzvz zmR|~y`^LIlz$OL85M4_RQC|Cv1+gzD#X zP`85I^H@%*4Cs6m@x7Uw0dE?(+0U@;Xe1|e`TqV?v`d-ln%Vpxv*|F3KjMQI&eRcx lfrmGn*Qvqy@3*72@Cq$RKe#3M4dIs$&{Wk`sZ+9z{69FE#vT9w literal 0 HcmV?d00001 diff --git a/flutter_app/assets/design/Homepage-if-lastest-journal-and-chat-has-created_example.png b/flutter_app/assets/design/Homepage-if-lastest-journal-and-chat-has-created_example.png new file mode 100644 index 0000000000000000000000000000000000000000..0441997c25fb3a9c42df295b7f919408a25690b7 GIT binary patch literal 61391 zcmeF2Ra9J0@aK`>L4vyk_XKwW3GO=BKyY^%T!IC6cZZ-MgAEoSK?V)(KDZ9<%Wuy< z?&JS$_hHUGb8mOw?&@>;R(dT`ynD^=aRnOM0D4blSZf;quhV}^Tt|AMG67oX9CuvDGCC@sfEH9 zDQ$1WqbH1Dotd=Lg!*hb%u1vmpHP#eP?#x;-%%zPg3I}vWqHYtXFZO#ZAVUFQA{gT zWiRz9-^T+Tm2+&0^AdZ&vWqsx@8v0bzR;&&Vj{7jYa{BQOpC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flutter_app/assets/design/Homepage.png b/flutter_app/assets/design/Homepage.png new file mode 100644 index 0000000000000000000000000000000000000000..7d08e40a61b030ee8e63cb5109af816d8727c752 GIT binary patch literal 47481 zcmeFZWmlU|{O$`yix-N!I}{28r$BLcrxd5S7k77uVlD1&0fM`G@Zj$5?ELmQ>pVIy zV6XMx53*+EPG&M|C7JIv*Ib`FLRnD?9fb%51_lOQM*6!d3=C`*3=CWfG9vVf!L;Tg zwE5^Dt>X*>gNpOt0~Y2_76J4kth1_=7);d!$szO!yoIQOC=5((9O}zY1Q-|~hRkc;YE+)sAEcTDpMJbI&q5k~+n(sbmC5hgB5=0Li-d_XTo?Wr* zdrVwsO+K>i3tEk@fL&23gRv4#XF{;VkR4$V!mz}`aTs`mvBa{zbwgj-f=9uCHuTC4 z$dtjn0fFMklzksRlZYWxD*oO0ugi!3sa=LXbCxUt_x-uJ8iy*ZlJa!PMvY0u`!7^W z)!D_651Bt_(FBCH)t2&I0IB5jeGV*bH+)2Wb3X6w%ToQmxZF4EU%q{Mtx%&I2Dz_) zcFfN9x*I(mCByJGe0gL}-WdDz-yn?iyjF)9iK%)NR(y|%Ick3mL#POk+QzcFIM)nF zsZJ|r=GUp#Dr08mz4crF9QDy2|5#(X7kqNr_)6r(_0;_^wsnrM&i)6Wch<5gDLICHpB-lor`15|1$?Y)__R~d8ah~(Qx)4FPYlsS-4E=UFTV%+we|HCH9 zizudLj+I2_>-NVXY3YSdFFAH5Hod+w~MW^`+f$uiZLzUMf znX8%mSprF}A_D!>L zg`pg5k3txx!|UFp?>-!87;{=Dm4i|d#M0=6FQrHn4o~#H()q63r4i<1+*TCeYd$Vl zw>fY7bJTN`8~^^-)M=gYbC;@4W$a_^KA7R3hgh_kynwXyLHby57X4xHHI_ZtyjnA z5a#!r{Bt>TyHvMI*JnR9U+&zq2ZUnOch~1tTQ6N=Q+vJqtSo@M;skrr*vxdIiZ-3C zSF^0UR5=>gR7)7@lX&!$cpM#SC3`S7@rvG5i`WA}^td^MA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NMpy2@d32S6Wv^~4`_WP0)toE&(>LO8Q23fj8t7>**Vp7GIoVUdqZ(>bM z0pNwQfYHIvm#R46=l_*#MktE8^=k{}5K zHUuF0Ow7WgEoS3nl<;>6)G-s}%FUJM)1O~N;juGBhCC^VF|QYyB}baaXPzx;h$_s# zmbppFSK>#SO8;QGYxmPHc}M5aP}`(&Ejg0M(_+jJWkrE0);d%7P|@7cuKIxo;1VO~*@R=3hV|=4~#IR-Ecuv8MQcm20lG;CzSMX_a6!)Wb4?Lg} z`5hosL8unqo-~eTN{ybIH(sLP@JrHpsoI+|oH#v&A4#`@K=gtxLHa1$WGkHR^YDPxdW95MmG zSy>sAFT}0U)cFfB3*gRvN!8zz(Ua14)59I+35R@3>6HAvtIQA0x-YMK(xKv;N%dR| zI&w6Oq_$z%iP#<_geKIc*kaOuF$FHK7|F(Vp5O~$)k{{Awp(oEw9fXEqmqrH!=XWH zXpuBZek)oJ}Tiq$25`g*>(EoUT3_X5`Os2@)ynfmj_qaBDT z%sMIDoYsGD|5%QD`4TeBYH^HR-^?J@0}PK6C|%tT%<(V_k}#1vaaExmt!Ua94;@|c z6tBGyRe79Ib(B3$&G1wSQaY*OF<~h^618o}0QdIEl}+V^(0zwUn4sj7@QRdYDYjg; zm9$=1q2!G3(~wal0a`(#wN5gvQdARp8?joDNkseKvs_xT#C!w+qx!Jr1@|w+v z|FHw>mMv7omkFUj=2q~6=jUC8?d|kjB#CfuABl1dii_jiUPb1e60_4~0d@|6VX{{e@^r7}F! zVL-&7AVA9$;U+BeLVK5JpGo!RKMS7XVlq6B*TDa@Evxlu{J*D2C}58N=SX0=UXR*% z+^2$ni+E_H(*GLl?lqp5`{xOb`^IZ+f`nZOwnl5K0sL+^`7c^w1vfTGq2}M3s;tKX x5qGOv6ai!{`CKFEfaI~1;A)>RLBhFLU6E;oRqR;mADb)e*ilGb0Po$ literal 0 HcmV?d00001 diff --git a/flutter_app/assets/design/Journal Page.png b/flutter_app/assets/design/Journal Page.png new file mode 100644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AG-({^4gPtKngeRsN3aPZ=PKLj&9dzVONt4_UgCD`Zn z8`Jwa^L{=vb9{VZ??tYw79t)WKi4KZC#xqb7C&6jX2$ z*%@Ule6yk!TAOcoJsbZs?YB;D^lF(4XEg&pvhkgft_nCeB=2NeQr9Vr>3it9~;E^&aShN0F-s7ZwZ3_|t z9CU1+pPjAoO|JTLnAuXE>}y|RTX+rPoY~GfJ>I=e?_|b*_u3$bI|WbM?}V)VsAuS`3<)@xSxyX9pWIiGZ6moHxM@?BKShbOED rRbP0l+XkKeC(Pq literal 0 HcmV?d00001 diff --git a/flutter_app/assets/design/example-if-users-addedcreated-alotofjournals.png b/flutter_app/assets/design/example-if-users-addedcreated-alotofjournals.png new file mode 100644 index 0000000000000000000000000000000000000000..3c67ed688c605217fe7963ebf92f25346f6326be GIT binary patch literal 51030 zcmeF3WmH?=yXR@4I0OoX;MM{y?iwh;ic{L+PH}ev1&T|NQrwG|;>EpKa47CB!Gk-= zq`$fMt~)Pg=0CF5yqOnSIs4?SlYREtIs19O-_Mf>byax+TuNLtG&BN*H!>P%Xpb_` z(9jdHF;ROA#x!S9Z#YhGbX?KU@JRl?9-*aW08u+1xoXIR(aJ}tcTo)tODPp8G_>MvsIb#+&l0pwz()deX5pSuF>pqrRu`Z0(EVA%^@Zh(rfn)_$bfo5k`T| z>-Xxfx4tz@f9uih+qm=8t0$jlktC?8ZzZlQyt1S^vW zj6G&7C(IB`#Q5mBFc_QRsZ<~nszLn!8~;8ACJ9O}=?+1w&}{Az_YCg39d}UnMdP8E z$ITT@z3p6S%V|PFjsD147bK#It!)pnH2wks z+Pb;(p_S0h;%i?=bg3biUvz{beVXs;0S}Aq?YoZUPRK6*Gy55Q)Y)#x>rDo;AAIJ& z2|hC-LJ%U4kiPau7eeJa*vRB^y_7q;J9tuq&F;;?_q)4hIuE)-vDJ{9{xAngk54}c z-WC;#6n|N@TRAaV?i;VZ8?K^zJGFbbNYk?NA@Q?4o?lBV7NE(dD$BPKiRR;yrPGEl z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4oN552wX+vjyoJ8#^bShr@vWV6x@n=7A+ZEs>tWbO%{=zTjUcK2P~O%@k- z3UB^w!jY9zGCM;$YGMQ9!&95rTS*iT+>6>mb0zDeV{7S zfzNbhL+Fa&=lwhNCN9+Bbt%4_>&U#(EdTKWyFZKHwr|?EPqAXImh?2Om3mSBZy)t` z=fAX(Wj*_7+O<9G`V7ZHN**vUOlpqIVrYmEu%H3)$Nv0Ywhf8t5fd4Jz|+;wWt~$( F697A!-!}jN literal 0 HcmV?d00001 diff --git a/flutter_app/assets/design/example-if-users-already-create-a-chat.png b/flutter_app/assets/design/example-if-users-already-create-a-chat.png new file mode 100644 index 0000000000000000000000000000000000000000..963cd5af3b11de75fa8710e6cb7a7a2b2de828d9 GIT binary patch literal 24405 zcmdqIc{JPK`!5<4Eky^kHMZ5#QnV#8#H=V4^U%gzb0TQXF;x}S7Hzduh@prv)D-hj zT0W}ANJ3IllpqL=c|1PfbJn_R-F5CgzjNg@Fbd<81Qfj zaRC4T9>e?hEC2wOEC7J*<4KO=5r<)$vE#2({`VgR007+Q|NXE4P+1p`2U!9v40He$ z10oB@4<|geA=&^yRSNgM3p)VdxM+A!+bWc0dE(StG0#ZGo~M5PyFZu4$>sg`L*Kdo zf&7m9&ieSmH(o2_rw|>qk4Y!wAD*C-^($D{`xZgZEI*#OKN0Zy?ewp=Nm|eBpQE4M z)aq6NJ-i#rEI7tp~T!v^rz{tW=wpHT(?F8u#)h>b;n@8D0#52~!2v_(U#Paw+Ca1wAi=K&O~Q@ix?U9)`TioG()deq`m{N= ze6*T)n}VP=7X95yc4(&XihxgE)Iexk43%@;s9)|40jgTZ3aKL%YmM+b;^xZTwX!Wo zqzXQgZ<888A!ZexvENPBZ_K>fOVi?Gfs^`yhv4 z^9H$7&mon~w|{L{z;(+6CG*ZDKjd*uSt|5zd_bXcIpeu|uCq zWB5Rhh#JKtz$6!6R*)ex36&7|p-@z1vN3SfL1hh9dy{6px3MoO9ztS9Gt%&Ilkkp!>DsUttPcx^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+XvFV`QOzc{{ovys~L3vvh8hKBXy00wVJTyXyBchog!_JY*7a{!4{ka zZ65x2g?6Vw8{XR5x~A&3indznHVJF9UanHb>nGimqK+%3UZA8R2>3G8?{j`Tm*daS zUdTc?^@k5LOWb8W=z1lelyw0QDgN$3~@m6Vld!R9)dElhq)auiW#?P_nkH=aOu_*;3@ zs!U{PpD{jbbTjsCRJooWv*Te%tPjp0VJ;7V|LD3}f2rSp{le@C&vApOi`LU(Yt^_3Q>R}2SEL2!A^Z{N|6^om+caC@Z_LeROOuycbEJc#^*(WK z$2JMItNXKQFzaHd}JPs24C&@dqMCxH&8c?@Tb@Ot2CJ2#%KMlQW%7rZx3-)yCBE)?X< zOp)$W7W*pV(6)1qu}HNU{3oz=C&5a+@&513=U9W|ZO0C?x!iEJ60hR5p0IJXjg9q~ zBIJqG1BO%a{F#Kkh;E6>Yh|L+=rYu8u$?|!!mL~1#1T`pxa#R_<7mIGwVdBKbo75m zIRATuq^4nz?q=hq9!*3%&=)mcvT* z<~eu4^13rt)=0JBWpuA=M}S9|GNQ#SGpZE5dQrOw}ZUz!|vSkf}HmZa`%!l54_{!b<69H WXJp6+FN5DAFu!=+wCaM}gZ~3VgI;6+ literal 0 HcmV?d00001 diff --git a/flutter_app/assets/images/alodokter.png b/flutter_app/assets/images/alodokter.png new file mode 100644 index 0000000000000000000000000000000000000000..39d58c21512b87fbe31b3474e3d3bc55fbdab59c GIT binary patch literal 15612 zcmdUWWl&qu+h@HPyOD8-An!9#F|04?q=rL?6ugaE~hJ1J1yp-6Ct6nA$g z$lkvH*_rqAJF~O9e7KWg?j?tF&v~AoonTdEc>+8tygPU95WIgU1HE(S-Z$X$49-2^ znlH}8cju01+j|*Fn8)9plwc!ut;<`i1evO}pygj>k&%Rcm(z;53%}etb2zTfWH3(N z&rcbj@aJ1|zQ27a8|o@8D~t1z=`Araj>5YaZ;8vE`VmdDNp#`~35uM1HXR<0u}>#^ z?=}ozMb}bSV$FfCyd!f5_4D6o?yyq+yQ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r z)S2AVAlt5T*-vEF&!~TX@M`u+eF6VuWDOCSf;&a*CUD*~b!S{pmsw*#cP7V^!gtkX zRDAzS@yf%isI)OFke+%iAk3>2?-?r)-kF#9|M4X1e?J5IfA2i(e;>vF{3P%H{K)To c=k5Iw%tyKh!NCIm4hg@PRhB7{GXDI(0OAc>uK)l5 literal 0 HcmV?d00001 diff --git a/flutter_app/assets/images/logo_Kalm.png b/flutter_app/assets/images/logo_Kalm.png new file mode 100644 index 0000000000000000000000000000000000000000..cd6fca51889d045da5ecccd1fdea45ebb4faa6f1 GIT binary patch literal 42245 zcmeHwX*iWz`1fNdQ&GlFC62JoRLYp4DB~s+lCgx4j1g&55{`M6u|!I2iXyTz6)K91 znTIl!p+S+}d+oiQ^Z)RE`G0udPu6vvtIo66vxfWr-M@QSYwyAg@kci^Z)e6ZY_qnO zh7pD_DWd-vH^LLP^Lql}52g!R=AIZPwHy6M<9kQd2Oj?ArD^76>~_}cqOFHLrhdlF z&YoY})z-n@$lmshpL>(NGKS^GX=|vP`1a29?xDeCw$SA~yYjXma)%nj<5?OQg4_}^ zKGCoJy(0|2_E)vc{~nL6KPHQ1T_#j?tOJ4~h;=}$0|LX=tzq37uyra}r-F4VpkiR% z8rB4{?i<#9!@4!BTLVa7oeI{eV4Vuqso?(;70mTioW6NIN9Lbfw@HluU^@(-GSg`o z`Z1bn?IM^I{S~y;hW>yJy_MjJ8x^r{VgsvJ?-y^z0H1A4Ybtulq4;l=(C-j#?J>W> z|ELTyWvo3WDCcmj{XGWfMZ5O*g=_z#rno-%x>(2(SVzmc5v`fRI=8G-E)@&w&SKq% zQlT)m9$KssY)l?*HH@7 z^2qWgdk%ed2}{U#%`i9%pAe=6ynd!5)Dm^@V+mv zZHB&tWz@jykH-I|ee$B@<%in9l7g|Xe8pb_7IwZ<-sldW85&*UnXOxWsyOwP3oY`I z=3A!o7b-hva*u_al8tCaRY%SP3{Qj74(8kQHo*U3vxZ*55&A8^SXH#GZ&#T`z1S}a zPZP2=P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ot#3GM{&;4RN&_cItvh9)?nu-qQH$qEta*@Hp33+s zNZyaD^jc{j--Gn>oWL`+j6`7N2bN3tpsmU>5vR zv-)n$*5RES??R!S*LkBW|Ffpwe!L zsr6$W@prUfoEKMStG`{ggM-e>t}{mIi}XqEne|z2s#*ft^U??SZqOjHSNf^%VeLy5 zjAI}Cs${qedTXx)UCIWkIzud$M`q9PKvH>x)>uF9&Yg4Tq^L2DlZiC z-i_pjl5Hh^-}fVlx3N!ZmY)gjnzlCJuW`{ zd)(x$@WnF+RT{FC(nZ_graM?YADsiKCw~e_SjO1;I{V#2r3HvveC1tKZCJT67CKQ~l1A-z4Y#k8m zfWX$RVci2yvo4PVD2QO_`3g5k6JYAFj|FU?xeq2iy-1 createState() => _ChatHistoryScreenState(); +} + +class _ChatHistoryScreenState extends State { + List chatHistory = []; + bool isLoading = true; + + @override + void initState() { + super.initState(); + fetchChatHistory(); + } + + Future fetchChatHistory() async { + try { + // Sesuaikan URL dengan konfigurasi backend Anda + final response = + await http.get(Uri.parse('http://10.0.2.2:3000/api/chat/history')); + + if (response.statusCode == 200) { + setState(() { + chatHistory = json.decode(response.body); + isLoading = false; + }); + } else { + throw Exception('Failed to load history'); + } + } catch (e) { + setState(() { + isLoading = false; + }); + } + } + + // Handle Navbar Navigation + void _onNavBarTap(int index) { + if (index == 1) return; // Sudah di halaman Chat History + + if (index == 0) { + Navigator.pushReplacement( + context, + MaterialPageRoute(builder: (context) => const HomePage(title: '',)), + ); + } else if (index == 2) { + Navigator.pushReplacement( + context, + MaterialPageRoute( + builder: (context) => const JournalPage(title: 'Jurnal')), + ); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFF9E2D2), + body: SafeArea( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Padding( + padding: EdgeInsets.all(20.0), + child: Text( + "Mau lanjut ngobrol nih?", + style: TextStyle( + fontSize: 22, + fontWeight: FontWeight.bold, + color: Color(0xFF4A4A4A), + ), + ), + ), + + // New Chat Button + Padding( + padding: const EdgeInsets.symmetric(horizontal: 20.0), + child: GestureDetector( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => const ChatPage( + title: "Curhat Baru", + ), + ), + ).then((_) => fetchChatHistory()); + }, + child: Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 20), + decoration: BoxDecoration( + color: const Color(0xFFA3C4A0), + borderRadius: BorderRadius.circular(15), + ), + child: Column( + children: [ + const Text( + "Mau Buat\nCurhatan Baru?", + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.white, + fontSize: 16, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 10), + Container( + padding: const EdgeInsets.all(5), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(8), + ), + child: const Icon(Icons.add, color: Color(0xFFA3C4A0)), + ), + ], + ), + ), + ), + ), + + const SizedBox(height: 20), + + // Chat History List + Expanded( + child: isLoading + ? const Center(child: CircularProgressIndicator()) + : chatHistory.isEmpty + ? const Center(child: Text("Belum ada riwayat curhat.")) + : ListView.builder( + padding: const EdgeInsets.symmetric(horizontal: 20), + itemCount: chatHistory.length, + itemBuilder: (context, index) { + final chat = chatHistory[index]; + return Container( + margin: const EdgeInsets.only(bottom: 15), + padding: const EdgeInsets.all(15), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(15), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + chat['title'] ?? "Tanpa Judul", + style: const TextStyle( + fontWeight: FontWeight.bold, + fontSize: 16, + color: Color(0xFF333333), + ), + ), + const SizedBox(height: 5), + Text( + chat['preview'] ?? "...", + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: Colors.grey[600], + fontSize: 14, + ), + ), + const SizedBox(height: 10), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Text( + _formatDate(chat['updatedAt']), + style: TextStyle( + color: Colors.grey[400], + fontSize: 12, + ), + ), + ElevatedButton( + onPressed: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => ChatPage( + title: chat['title'] ?? + "Curhat Lama", + ), + ), + ).then((_) => fetchChatHistory()); + }, + style: ElevatedButton.styleFrom( + backgroundColor: + const Color(0xFFA3C4A0), + shape: RoundedRectangleBorder( + borderRadius: + BorderRadius.circular(8), + ), + padding: const EdgeInsets.symmetric( + horizontal: 20, vertical: 0), + ), + child: const Text( + "Lanjutkan", + style: TextStyle( + color: Colors.white, + fontSize: 12), + ), + ), + ], + ), + ], + ), + ); + }, + ), + ), + ], + ), + ), + // Menggunakan Navbar Lokal yang Sederhana (Flat) + bottomNavigationBar: _buildLocalNavbar(), + ); + } + + // Widget Navbar Lokal Sederhana (Sesuai Gambar) + Widget _buildLocalNavbar() { + return Container( + height: 80, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: const BorderRadius.only( + topLeft: Radius.circular(30), + topRight: Radius.circular(30), + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.05), + blurRadius: 10, + offset: const Offset(0, -5), + ), + ], + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + // Tombol Home (Kiri) + IconButton( + onPressed: () => _onNavBarTap(0), + icon: const Icon( + Icons.home_filled, + size: 32, + color: Color(0xFF8DAC8D), // Warna Sage Green (Tidak Aktif) + ), + ), + // Tombol Tengah (Tulip - Aktif) + IconButton( + onPressed: () {}, // Sedang di halaman ini + icon: const Icon( + Icons.local_florist, // Icon Bunga Tulip + size: 32, + color: Color(0xFF557C56), // Hijau Tua (Aktif) + ), + ), + // Tombol Jurnal (Kanan) + IconButton( + onPressed: () => _onNavBarTap(2), + icon: const Icon( + Icons.edit_note, // Icon Note/Jurnal + size: 34, + color: Color(0xFF8DAC8D), // Warna Sage Green (Tidak Aktif) + ), + ), + ], + ), + ); + } + + String _formatDate(String? dateString) { + if (dateString == null) return ""; + try { + DateTime date = DateTime.parse(dateString); + return "${date.day}/${date.month}/${date.year}"; + } catch (e) { + return dateString; + } + } +} diff --git a/flutter_app/lib/chat_page.dart b/flutter_app/lib/chat_page.dart index ebaf8f2..7025066 100644 --- a/flutter_app/lib/chat_page.dart +++ b/flutter_app/lib/chat_page.dart @@ -1,59 +1,302 @@ import 'package:flutter/material.dart'; +import 'dart:convert'; +import 'package:http/http.dart' as http; +import 'dart:io'; +import 'package:path_provider/path_provider.dart'; -/// Chat page with gradient background, back button, -/// chat input field, send button, and summary button. -class ChatPage extends StatelessWidget { - const ChatPage({super.key}); +class ChatPage extends StatefulWidget { + final String title; + + const ChatPage({super.key, required this.title}); + + @override + State createState() => _ChatPageState(); +} + +class _ChatPageState extends State { + final List<_ChatMessage> _messages = []; + final TextEditingController _inputController = TextEditingController(); + bool _isSending = false; + bool _isSummarizing = false; + + // Ganti jika perlu (misalnya ke IP lokal saat pakai device fisik) + final String _chatEndpoint = 'http://10.0.2.2:3000/api/chat'; + final String _summaryEndpoint = 'http://10.0.2.2:3000/api/summary'; + + Future _sendMessage() async { + final text = _inputController.text.trim(); + if (text.isEmpty || _isSending) return; + + setState(() { + _messages.add(_ChatMessage(text: text, isUser: true)); + _inputController.clear(); + _isSending = true; + }); + + try { + final response = await http.post( + Uri.parse(_chatEndpoint), + headers: {'Content-Type': 'application/json'}, + body: jsonEncode({'message': text}), + ); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body) as Map; + final reply = (data['reply'] ?? '').toString(); + if (reply.isNotEmpty) { + setState(() { + _messages.add(_ChatMessage(text: reply, isUser: false)); + }); + } + } else { + setState(() { + _messages.add( + const _ChatMessage( + text: 'Maaf, terjadi kesalahan pada server.', + isUser: false, + ), + ); + }); + } + } catch (e) { + setState(() { + _messages.add( + const _ChatMessage( + text: 'Tidak dapat terhubung ke server. Pastikan backend berjalan.', + isUser: false, + ), + ); + }); + } finally { + if (mounted) { + setState(() { + _isSending = false; + }); + } + } + } + + Future _downloadSummaryPdf() async { + if (_messages.isEmpty || _isSummarizing) return; + + setState(() { + _isSummarizing = true; + }); + + try { + final history = _messages.map((m) => m.text).toList(); + + final uri = Uri.parse(_summaryEndpoint); + final request = http.Request('POST', uri) + ..headers['Content-Type'] = 'application/json' + ..body = jsonEncode({'history': history}); + + final streamedResponse = await request.send(); + + if (streamedResponse.statusCode == 200) { + final bytes = await streamedResponse.stream.toBytes(); + + final Directory dir = await getApplicationDocumentsDirectory(); + final String filePath = + '${dir.path}/ringkasan_curhat_${DateTime.now().millisecondsSinceEpoch}.pdf'; + + final file = File(filePath); + await file.writeAsBytes(bytes); + + if (!mounted) return; + + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('PDF ringkasan tersimpan di: $filePath'), + duration: const Duration(seconds: 4), + ), + ); + } else { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + 'Gagal membuat ringkasan (kode: ${streamedResponse.statusCode})'), + ), + ); + } + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: + Text('Tidak dapat terhubung ke server summary: ${e.toString()}'), + ), + ); + } finally { + if (mounted) { + setState(() { + _isSummarizing = false; + }); + } + } + } + + @override + void dispose() { + _inputController.dispose(); + super.dispose(); + } @override Widget build(BuildContext context) { return Scaffold( - // Make the body draw behind the system status bar extendBodyBehindAppBar: true, - // We do not use the default app bar because the design - // uses a floating circular back button instead. body: Container( - // Full-screen gradient background using your palette decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ - Color(0xFFF8E8C1), // top - Color(0xFFEEDDC8), // middle - Color(0xFFF7D9C4), // bottom + Color(0xFFF8E8C1), + Color(0xFFEEDDC8), + Color(0xFFF7D9C4), ], ), ), - // Use SafeArea so content does not overlap system UI - child: Stack( - children: [ - /// Positioned circular back button on top-left - Positioned( - // Sedikit diturunkan dari posisi sebelumnya (16 -> 32) - top: 32, - left: 16, - child: _BackButton(), - ), - - /// Bottom area with input and summary button - Align( - alignment: Alignment.bottomCenter, - child: Padding( - // Outer padding from screen edges - padding: const EdgeInsets.fromLTRB(16, 0, 16, 24), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - _ChatInputBar(), - const SizedBox(height: 12), - _SummaryButton(), - ], + child: SafeArea( + child: Stack( + children: [ + Positioned( + top: 16, + left: 16, + child: _BackButton(), + ), + Positioned( + top: 24, + left: 72, + right: 72, + child: Text( + widget.title, + textAlign: TextAlign.center, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + color: Color(0xFF333333), + ), + ), + ), + Positioned( + top: 24, + left: 72, + right: 72, + child: Text( + widget.title, + textAlign: TextAlign.center, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + color: Color(0xFF333333), + ), + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 72, 16, 80), + child: _messages.isEmpty + ? const Center( + child: Text( + 'Mulai curhat ke Sana...' + '\nPesanmu akan muncul di sini.', + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.black54, + fontSize: 14, + ), + ), + ) + : ListView.builder( + itemCount: _messages.length, + itemBuilder: (context, index) { + return _MessageBubble(message: _messages[index]); + }, + ), + ), + Align( + alignment: Alignment.bottomCenter, + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 16), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + _ChatInputBar( + controller: _inputController, + isSending: _isSending, + onSend: _sendMessage, + ), + const SizedBox(height: 8), + _SummaryButton( + isSummarizing: _isSummarizing, + onTap: _downloadSummaryPdf, + ), + ], + ), ), ), + ], + ), + ), + ), + ); + } +} + +class _ChatMessage { + final String text; + final bool isUser; + + const _ChatMessage({required this.text, required this.isUser}); +} + +class _MessageBubble extends StatelessWidget { + final _ChatMessage message; + + const _MessageBubble({required this.message}); + + @override + Widget build(BuildContext context) { + final isUser = message.isUser; + final alignment = isUser ? Alignment.centerRight : Alignment.centerLeft; + final backgroundColor = + isUser ? const Color(0xFFB7D0AF) : Colors.white.withValues(alpha: 0.9); + final textColor = isUser ? Colors.white : Colors.black87; + + return Align( + alignment: alignment, + child: Container( + margin: const EdgeInsets.symmetric(vertical: 4), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + constraints: BoxConstraints( + maxWidth: MediaQuery.of(context).size.width * 0.7, + ), + decoration: BoxDecoration( + color: backgroundColor, + borderRadius: BorderRadius.only( + topLeft: const Radius.circular(16), + topRight: const Radius.circular(16), + bottomLeft: + isUser ? const Radius.circular(16) : const Radius.circular(4), + bottomRight: + isUser ? const Radius.circular(4) : const Radius.circular(16), + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.05), + blurRadius: 4, + offset: const Offset(0, 2), ), ], ), + child: Text( + message.text, + style: TextStyle(color: textColor, fontSize: 14), + ), ), ); } @@ -105,41 +348,16 @@ class _BackButton extends StatelessWidget { /// Bottom chat input bar with rounded white background and /// a circular send button at the right side. -class _ChatInputBar extends StatefulWidget { - const _ChatInputBar(); - - @override - State<_ChatInputBar> createState() => _ChatInputBarState(); -} - -class _ChatInputBarState extends State<_ChatInputBar> { - // Controller untuk memantau isi text field - final TextEditingController _controller = TextEditingController(); +class _ChatInputBar extends StatelessWidget { + final TextEditingController controller; + final bool isSending; + final VoidCallback onSend; - // Menyimpan apakah text field kosong atau tidak - bool _isInputNotEmpty = false; - - @override - void initState() { - super.initState(); - - // Listener untuk update state ketika teks berubah - _controller.addListener(() { - final hasText = _controller.text.trim().isNotEmpty; - if (hasText != _isInputNotEmpty) { - setState(() { - _isInputNotEmpty = hasText; - }); - } - }); - } - - @override - void dispose() { - // Buang controller ketika widget dihapus - _controller.dispose(); - super.dispose(); - } + const _ChatInputBar({ + required this.controller, + required this.isSending, + required this.onSend, + }); @override Widget build(BuildContext context) { @@ -163,7 +381,7 @@ class _ChatInputBarState extends State<_ChatInputBar> { // Expanded text field takes remaining width Expanded( child: TextField( - controller: _controller, + controller: controller, // No explicit border to keep the pill look clean decoration: const InputDecoration( hintText: 'Tulis curhatanmu.....', @@ -176,7 +394,8 @@ class _ChatInputBarState extends State<_ChatInputBar> { /// Circular send button at right side _SendButton( - enabled: _isInputNotEmpty, + enabled: !isSending, + onPressed: onSend, ), ], ), @@ -187,8 +406,12 @@ class _ChatInputBarState extends State<_ChatInputBar> { /// Circular send button with green background and white icon. class _SendButton extends StatelessWidget { final bool enabled; + final VoidCallback onPressed; - const _SendButton({required this.enabled}); + const _SendButton({ + required this.enabled, + required this.onPressed, + }); @override Widget build(BuildContext context) { @@ -206,11 +429,7 @@ class _SendButton extends StatelessWidget { child: InkWell( customBorder: const CircleBorder(), // Hanya boleh di-tap kalau enabled = true - onTap: enabled - ? () { - // TODO: implement send chat logic - } - : null, + onTap: enabled ? onPressed : null, child: Container( width: 36, height: 36, @@ -232,6 +451,14 @@ class _SendButton extends StatelessWidget { /// Summary button that looks like a pill with a small PDF icon /// and text `Summary`, using your red/white palette. class _SummaryButton extends StatelessWidget { + final bool isSummarizing; + final VoidCallback onTap; + + const _SummaryButton({ + required this.isSummarizing, + required this.onTap, + }); + @override Widget build(BuildContext context) { return Material( @@ -239,17 +466,14 @@ class _SummaryButton extends StatelessWidget { borderRadius: BorderRadius.circular(24), child: InkWell( borderRadius: BorderRadius.circular(24), - onTap: () { - // TODO: generate summary PDF - }, + onTap: isSummarizing ? null : onTap, child: Container( padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 8), decoration: BoxDecoration( - color: const Color(0xFFFE3838), // red background + color: const Color(0xFFFE3838), borderRadius: BorderRadius.circular(24), boxShadow: [ BoxShadow( - // use withValues instead of deprecated withOpacity color: Colors.black.withValues(alpha: 0.12), blurRadius: 10, offset: const Offset(0, 4), @@ -259,24 +483,35 @@ class _SummaryButton extends StatelessWidget { child: Row( mainAxisSize: MainAxisSize.min, children: [ - // Small rounded white PDF badge - Container( - padding: - const EdgeInsets.symmetric(horizontal: 6, vertical: 3), - decoration: BoxDecoration( - color: const Color(0xFFFFFFFF), - borderRadius: BorderRadius.circular(6), + if (isSummarizing) ...[ + const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator( + strokeWidth: 2, + valueColor: + AlwaysStoppedAnimation(Color(0xFFFFFFFF)), + ), ), - child: const Icon( - Icons.picture_as_pdf, - size: 19, - color: Color(0xFFFE3838), + ] else ...[ + Container( + padding: const EdgeInsets.symmetric( + horizontal: 6, vertical: 3), + decoration: BoxDecoration( + color: const Color(0xFFFFFFFF), + borderRadius: BorderRadius.circular(6), + ), + child: const Icon( + Icons.picture_as_pdf, + size: 19, + color: Color(0xFFFE3838), + ), ), - ), + ], const SizedBox(width: 8), - const Text( - 'Summary', - style: TextStyle( + Text( + isSummarizing ? 'Membuat summary...' : 'Summary', + style: const TextStyle( color: Color(0xFFFFFFFF), fontWeight: FontWeight.w600, fontSize: 14, diff --git a/flutter_app/lib/homepage.dart b/flutter_app/lib/homepage.dart new file mode 100644 index 0000000..7ff9307 --- /dev/null +++ b/flutter_app/lib/homepage.dart @@ -0,0 +1,305 @@ +// flutter_app/lib/homepage.dart + +import 'package:flutter/material.dart'; +import 'package:url_launcher/url_launcher.dart'; +import 'chat_history.dart'; +import 'journal-page.dart'; + +class HomePage extends StatelessWidget { + const HomePage({super.key, required String title}); + + // Helper function to launch URLs + Future _launchURL(String urlString) async { + final Uri url = Uri.parse(urlString); + if (!await launchUrl(url, mode: LaunchMode.externalApplication)) { + debugPrint('Could not launch $url'); + } + } + + // Function to handle Navbar navigation + void _handleNavigation(BuildContext context, int index) { + if (index == 0) return; // Already on Home + + if (index == 1) { + // Navigate to Chat History + Navigator.pushReplacement( + context, + MaterialPageRoute( + builder: (context) => + const ChatHistoryScreen(title: 'Riwayat Curhat')), + ); + } else if (index == 2) { + // Navigate to Journal + Navigator.pushReplacement( + context, + MaterialPageRoute( + builder: (context) => const JournalPage(title: 'Jurnal')), + ); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFF7D9C4), + body: SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 20.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // --- Header Section --- + Row( + children: [ + Container( + decoration: BoxDecoration( + shape: BoxShape.circle, + border: + Border.all(color: const Color(0xFFFFFFFF), width: 3), + ), + child: const CircleAvatar( + radius: 30, + backgroundImage: + AssetImage('assets/images/foto_profile_example.jpg'), + ), + ), + const SizedBox(width: 16), + const Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Hai Orang Baik,', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + color: Color(0xFF333333), + ), + ), + SizedBox(height: 4), + Text( + 'Jangan lupa untuk tersenyum ya!', + style: TextStyle( + fontSize: 14, + color: Color(0xFF555555), + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ], + ), + + const SizedBox(height: 32), + + // --- Curhatan Section --- + const Text( + 'Curhatan kamu baru baru ini!', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Color(0xFF333333), + ), + ), + const SizedBox(height: 16), + // Placeholder for Chat History + const Center( + child: Padding( + padding: EdgeInsets.symmetric(vertical: 20.0), + child: Text( + 'Masih kosong nih...', + style: TextStyle( + color: Color(0xFF555555), + fontSize: 16, + ), + ), + ), + ), + + const SizedBox(height: 24), + + // --- Jurnal Section --- + const Text( + 'Jurnal kamu akhir-akhir ini!', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Color(0xFF333333), + ), + ), + const SizedBox(height: 16), + // Placeholder for Journal + const Center( + child: Padding( + padding: EdgeInsets.symmetric(vertical: 20.0), + child: Text( + 'Masih kosong nih...', + style: TextStyle( + color: Color(0xFF555555), + fontSize: 16, + ), + ), + ), + ), + + const SizedBox(height: 24), + + // --- Rekomendasi Section --- + const Text( + 'Rekomendasi konsultasi!', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Color(0xFF333333), + ), + ), + const SizedBox(height: 12), + + // White Container for Consultation Cards + Container( + width: double.infinity, + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(20), + ), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + _buildConsultationCard( + imagePath: 'assets/images/Logo_Halodoc.png', + buttonColor: + const Color(0xFFE0004D), // Halodoc Red/Pink + onTap: () => _launchURL('https://www.halodoc.com/'), + ), + const SizedBox(width: 12), + _buildConsultationCard( + imagePath: 'assets/images/logo_Kalm.png', + buttonColor: + const Color(0xFF5C7C8A), // Kalm Grey/Blueish + onTap: () => _launchURL('https://www.kalm.id/'), + ), + const SizedBox(width: 12), + _buildConsultationCard( + imagePath: 'assets/images/alodokter.png', + buttonColor: const Color(0xFF2D74C4), // Alodokter Blue + onTap: () => _launchURL('https://www.alodokter.com/'), + ), + ], + ), + ), + ), + const SizedBox(height: 20), + ], + ), + ), + ), + // Menggunakan Navbar Lokal Sederhana + bottomNavigationBar: _buildLocalNavbar(context), + ); + } + + // Widget Navbar Lokal (Sesuai Gambar Referensi) + Widget _buildLocalNavbar(BuildContext context) { + return Container( + height: 80, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: const BorderRadius.only( + topLeft: Radius.circular(30), + topRight: Radius.circular(30), + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.05), + blurRadius: 10, + offset: const Offset(0, -5), + ), + ], + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + // Tombol Home (Kiri) - AKTIF + IconButton( + onPressed: () {}, // Sudah di Home + icon: const Icon( + Icons.home_filled, + size: 32, + color: Color(0xFF557C56), // Hijau Tua (Aktif) + ), + ), + // Tombol Tengah (Tulip) - TIDAK AKTIF + IconButton( + onPressed: () => _handleNavigation(context, 1), + icon: const Icon( + Icons.local_florist, // Icon Bunga Tulip + size: 32, + color: Color(0xFF8DAC8D), // Sage Green (Tidak Aktif) + ), + ), + // Tombol Jurnal (Kanan) - TIDAK AKTIF + IconButton( + onPressed: () => _handleNavigation(context, 2), + icon: const Icon( + Icons.edit_note, // Icon Note/Jurnal + size: 34, + color: Color(0xFF8DAC8D), // Sage Green (Tidak Aktif) + ), + ), + ], + ), + ); + } + + Widget _buildConsultationCard({ + required String imagePath, + required Color buttonColor, + required VoidCallback onTap, + }) { + return Container( + width: 120, + height: 160, + decoration: BoxDecoration( + border: Border.all(color: Colors.grey.shade300), + borderRadius: BorderRadius.circular(12), + ), + child: Column( + children: [ + Expanded( + child: Padding( + padding: const EdgeInsets.all(12.0), + child: Image.asset( + imagePath, + fit: BoxFit.contain, + ), + ), + ), + InkWell( + onTap: onTap, + child: Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 8), + decoration: BoxDecoration( + color: buttonColor, + borderRadius: const BorderRadius.only( + bottomLeft: Radius.circular(11), + bottomRight: Radius.circular(11), + ), + ), + child: const Text( + 'Hubungi\nSekarang!', + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.white, + fontSize: 12, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ], + ), + ); + } +} diff --git a/flutter_app/lib/journal-page.dart b/flutter_app/lib/journal-page.dart new file mode 100644 index 0000000..b4cd7cf --- /dev/null +++ b/flutter_app/lib/journal-page.dart @@ -0,0 +1,289 @@ +// flutter_app/lib/journal-page.dart + +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'writing_journal_page.dart'; +import 'homepage.dart'; +import 'chat_history.dart'; +import 'journal_service.dart'; // Import Service + +class JournalPage extends StatefulWidget { + const JournalPage({super.key, required String title}); + + @override + State createState() => _JournalPageState(); +} + +class _JournalPageState extends State { + final JournalService _journalService = JournalService(); + List journals = []; + bool isLoading = true; + + @override + void initState() { + super.initState(); + fetchJournals(); + } + + // Logika Fetching sekarang bersih, hanya memanggil Service + Future fetchJournals() async { + try { + final data = await _journalService.getJournals(); + if (mounted) { + setState(() { + journals = data; + isLoading = false; + }); + } + } catch (e) { + debugPrint('Error fetching journals: $e'); + if (mounted) { + setState(() { + isLoading = false; + }); + } + } + } + + void _navigateToWritingPage({Map? journal}) async { + final result = await Navigator.push( + context, + MaterialPageRoute( + builder: (context) => WritingJournalPage(journal: journal), + ), + ); + + if (result == true) { + fetchJournals(); // Refresh list if changes were made + } + } + + // Handle Navbar Navigation + void _onNavBarTap(int index) { + if (index == 2) return; // Sudah di halaman Jurnal + + if (index == 0) { + Navigator.pushReplacement( + context, + MaterialPageRoute(builder: (context) => const HomePage(title: '',)), + ); + } else if (index == 1) { + Navigator.pushReplacement( + context, + MaterialPageRoute( + builder: (context) => + const ChatHistoryScreen(title: 'Riwayat Curhat')), + ); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFF7D9C4), + body: SafeArea( + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Ini list jurnal-mu selama ini!', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + color: Color(0xFF4A4A4A), + ), + ), + const SizedBox(height: 20), + Align( + alignment: Alignment.centerRight, + child: GestureDetector( + onTap: () => _navigateToWritingPage(), + child: Container( + width: 200, + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: const Color(0xFFA1BC98), + borderRadius: BorderRadius.circular(12), + ), + child: Column( + children: [ + const Text( + 'Mau Buat\nJurnal Baru?', + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 16, + ), + ), + const SizedBox(height: 8), + Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(8), + ), + child: const Icon( + Icons.add, + color: Color(0xFFA1BC98), + size: 32, + ), + ), + ], + ), + ), + ), + ), + const SizedBox(height: 20), + Expanded( + child: isLoading + ? const Center(child: CircularProgressIndicator()) + : journals.isEmpty + ? const Center(child: Text('Belum ada jurnal.')) + : GridView.builder( + gridDelegate: + const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 2, + crossAxisSpacing: 16, + mainAxisSpacing: 16, + childAspectRatio: 0.8, + ), + itemCount: journals.length, + itemBuilder: (context, index) { + final journal = journals[index]; + final date = + DateTime.parse(journal['created_at']); + final formattedDate = + DateFormat('dd MMMM yyyy').format(date); + + return GestureDetector( + onTap: () => + _navigateToWritingPage(journal: journal), + child: Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + ), + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text( + journal['title'] ?? 'No Title', + style: const TextStyle( + fontWeight: FontWeight.bold, + fontSize: 16, + ), + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 8), + Text( + journal['content'] ?? '', + style: const TextStyle( + fontSize: 12, + color: Colors.grey, + ), + maxLines: 4, + overflow: TextOverflow.ellipsis, + ), + const Spacer(), + const Divider(), + Text( + formattedDate, + style: const TextStyle( + fontSize: 10, + color: Colors.grey, + ), + ), + const SizedBox(height: 8), + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric( + vertical: 4), + decoration: BoxDecoration( + color: const Color(0xFFA1BC98), + borderRadius: + BorderRadius.circular(8), + ), + child: const Center( + child: Text( + 'Lanjutkan', + style: TextStyle( + color: Colors.white, + fontSize: 12, + ), + ), + ), + ), + ], + ), + ), + ); + }, + ), + ), + ], + ), + ), + ), + // Menggunakan Navbar Lokal Sederhana + bottomNavigationBar: _buildLocalNavbar(), + ); + } + + // Widget Navbar Lokal (Sesuai Gambar Referensi) + Widget _buildLocalNavbar() { + return Container( + height: 80, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: const BorderRadius.only( + topLeft: Radius.circular(30), + topRight: Radius.circular(30), + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.05), + blurRadius: 10, + offset: const Offset(0, -5), + ), + ], + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + // Tombol Home (Kiri) - TIDAK AKTIF + IconButton( + onPressed: () => _onNavBarTap(0), + icon: const Icon( + Icons.home_filled, + size: 32, + color: Color(0xFF8DAC8D), // Sage Green (Tidak Aktif) + ), + ), + // Tombol Tengah (Tulip) - TIDAK AKTIF + IconButton( + onPressed: () => _onNavBarTap(1), + icon: const Icon( + Icons.local_florist, // Icon Bunga Tulip + size: 32, + color: Color(0xFF8DAC8D), // Sage Green (Tidak Aktif) + ), + ), + // Tombol Jurnal (Kanan) - AKTIF + IconButton( + onPressed: () {}, // Sedang di halaman ini + icon: const Icon( + Icons.edit_note, // Icon Note/Jurnal + size: 34, + color: Color(0xFF557C56), // Hijau Tua (Aktif) + ), + ), + ], + ), + ); + } +} diff --git a/flutter_app/lib/journal_service.dart b/flutter_app/lib/journal_service.dart new file mode 100644 index 0000000..8c23ae5 --- /dev/null +++ b/flutter_app/lib/journal_service.dart @@ -0,0 +1,63 @@ +// flutter_app/lib/journal_service.dart + +import 'dart:convert'; +import 'dart:io'; +import 'package:flutter/foundation.dart'; +import 'package:http/http.dart' as http; + +class JournalService { + // Getter untuk Base URL + String get baseUrl { + if (kIsWeb) return 'http://localhost:3000/api/journals'; + if (Platform.isAndroid) return 'http://10.0.2.2:3000/api/journals'; + return 'http://localhost:3000/api/journals'; + } + + // Fungsi Get All Journals (Logika Fetching dipindah ke sini) + Future> getJournals() async { + try { + final response = await http.get(Uri.parse(baseUrl)); + if (response.statusCode == 200) { + return json.decode(response.body); + } else { + throw Exception('Failed to load journals: ${response.statusCode}'); + } + } catch (e) { + rethrow; + } + } + + // Fungsi Create Journal + Future createJournal(String title, String content) async { + final response = await http.post( + Uri.parse(baseUrl), + headers: {'Content-Type': 'application/json'}, + body: jsonEncode({'title': title, 'content': content}), + ); + if (response.statusCode != 201) { + throw Exception('Failed to create journal'); + } + } + + // Fungsi Update Journal + Future updateJournal(String id, String title, String content) async { + final response = await http.put( + Uri.parse('$baseUrl/$id'), + headers: {'Content-Type': 'application/json'}, + body: jsonEncode({'title': title, 'content': content}), + ); + if (response.statusCode != 200) { + throw Exception('Failed to update journal'); + } + } + + // Fungsi Delete Journal + Future deleteJournal(String id) async { + final response = await http.delete( + Uri.parse('$baseUrl/$id'), + ); + if (response.statusCode != 200) { + throw Exception('Failed to delete journal'); + } + } +} diff --git a/flutter_app/lib/main.dart b/flutter_app/lib/main.dart index b7e470b..89be6a4 100644 --- a/flutter_app/lib/main.dart +++ b/flutter_app/lib/main.dart @@ -1,5 +1,5 @@ import 'package:flutter/material.dart'; -import 'chat_page.dart'; +import 'package:flutter_application_1/homepage.dart'; void main() { runApp(const MyApp()); @@ -12,13 +12,12 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, - title: 'EASE - Emotionally Assisting, Summarize Easily AI Chat', + title: 'Flannella', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), - // Set ChatPage as the first screen when the app opens - home: const ChatPage(), + home: const HomePage(title: "Curhatan Baru"), ); } } diff --git a/flutter_app/lib/widgets/custom_navbar.dart b/flutter_app/lib/widgets/custom_navbar.dart new file mode 100644 index 0000000..2e5d923 --- /dev/null +++ b/flutter_app/lib/widgets/custom_navbar.dart @@ -0,0 +1,171 @@ +// flutter_app/lib/widgets/custom_navbar.dart + +import 'package:flutter/material.dart'; + +class CustomNavbar extends StatelessWidget { + final int selectedIndex; + final Function(int) onItemTapped; + + // Warna sesuai request + final Color peachColor = const Color(0xFFF7D9C4); + final Color sageGreenColor = const Color(0xFF8DAC8D); + + const CustomNavbar({ + super.key, + required this.selectedIndex, + required this.onItemTapped, + }); + + @override + Widget build(BuildContext context) { + final width = MediaQuery.of(context).size.width; + final itemWidth = width / 3; // Membagi lebar layar untuk 3 item + + return SizedBox( + height: kBottomNavigationBarHeight + 30, // Tinggi ekstra untuk elemen floating + child: Stack( + clipBehavior: Clip.none, + children: [ + // 1. Layer Bawah: Bar Putih Dasar + Positioned( + bottom: 0, + left: 0, + right: 0, + height: kBottomNavigationBarHeight + 10, + child: Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: const BorderRadius.only( + topLeft: Radius.circular(25), + topRight: Radius.circular(25), + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.05), + blurRadius: 10, + offset: const Offset(0, -5), + ), + ], + ), + ), + ), + + // 2. Layer Tengah: Lengkungan Peach (Bergerak Animasi) + AnimatedPositioned( + duration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + left: selectedIndex * itemWidth, + bottom: kBottomNavigationBarHeight - 5, // Posisi sedikit overlap dengan bar putih + width: itemWidth, + height: 50, + child: CustomPaint( + painter: _PeachCurvePainter(color: peachColor), + ), + ), + + // 3. Layer Atas: Icon Menu dan Tombol Floating + Positioned.fill( + child: Row( + children: [ + _buildNavItem(0, Icons.home_filled, itemWidth), + _buildNavItem(1, Icons.local_florist, itemWidth), // Icon Bunga untuk History + _buildNavItem(2, Icons.edit_note, itemWidth), // Icon Note untuk Jurnal + ], + ), + ), + ], + ), + ); + } + + Widget _buildNavItem(int index, IconData icon, double width) { + final isSelected = index == selectedIndex; + + return GestureDetector( + onTap: () => onItemTapped(index), + behavior: HitTestBehavior.opaque, + child: SizedBox( + width: width, + height: double.infinity, + child: Stack( + alignment: Alignment.center, + children: [ + // Lingkaran Putih (Floating Background) - Muncul saat dipilih + AnimatedPositioned( + duration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + bottom: isSelected ? 45 : 15, // Naik ke atas saat dipilih + child: AnimatedContainer( + duration: const Duration(milliseconds: 300), + width: isSelected ? 56 : 0, // Membesar saat dipilih + height: isSelected ? 56 : 0, + decoration: BoxDecoration( + color: Colors.white, + shape: BoxShape.circle, + boxShadow: isSelected + ? [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.1), + blurRadius: 8, + offset: const Offset(0, 4), + ), + ] + : [], + ), + ), + ), + // Icon + AnimatedPositioned( + duration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + bottom: isSelected ? 58 : 25, // Icon ikut naik + child: Icon( + icon, + size: 30, + color: sageGreenColor, + ), + ), + ], + ), + ), + ); + } +} + +// Class untuk menggambar lengkungan peach di belakang tombol aktif +class _PeachCurvePainter extends CustomPainter { + final Color color; + _PeachCurvePainter({required this.color}); + + @override + void paint(Canvas canvas, Size size) { + final paint = Paint() + ..color = color + ..style = PaintingStyle.fill; + + final path = Path(); + + // Menggambar bentuk bukit landai + path.moveTo(0, size.height); // Mulai dari kiri bawah + + // Kurva naik ke tengah (Bentuk S-curve naik) + path.cubicTo( + size.width * 0.25, size.height, // Control point 1 + size.width * 0.25, 10, // Control point 2 + size.width * 0.5, 10, // Puncak + ); + + // Kurva turun ke kanan (Bentuk S-curve turun) + path.cubicTo( + size.width * 0.75, 10, // Control point 3 + size.width * 0.75, size.height, // Control point 4 + size.width, size.height, // Kanan bawah + ); + + path.close(); + canvas.drawPath(path, paint); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +} diff --git a/flutter_app/lib/writing_journal_page.dart b/flutter_app/lib/writing_journal_page.dart new file mode 100644 index 0000000..9cf0192 --- /dev/null +++ b/flutter_app/lib/writing_journal_page.dart @@ -0,0 +1,165 @@ +// file: lib/writing_journal_page.dart +import 'package:flutter/material.dart'; +import 'journal_service.dart'; + +class WritingJournalPage extends StatefulWidget { + final Map? journal; + + const WritingJournalPage({super.key, this.journal}); + + @override + State createState() => _WritingJournalPageState(); +} + +class _WritingJournalPageState extends State { + final JournalService _journalService = JournalService(); + + late TextEditingController _titleController; + late TextEditingController _contentController; + bool _isEditing = false; + bool _isNew = true; + + @override + void initState() { + super.initState(); + _titleController = TextEditingController(text: widget.journal?['title'] ?? ''); + _contentController = TextEditingController(text: widget.journal?['content'] ?? ''); + _isNew = widget.journal == null; + _isEditing = _isNew; + } + + @override + void dispose() { + _titleController.dispose(); + _contentController.dispose(); + super.dispose(); + } + + Future _handleSave() async { + final title = _titleController.text.trim(); + final content = _contentController.text.trim(); + + // FIX: Simpan referensi messenger SEBELUM proses async (await) + // Ini membuat kita tidak perlu memanggil 'context' di dalam catch block + final messenger = ScaffoldMessenger.of(context); + + if (title.isEmpty && content.isEmpty) { + if (!_isNew) { + await _handleDelete(); + } + return; + } + + try { + if (_isNew) { + await _journalService.createJournal(title, content); + } else { + await _journalService.updateJournal(widget.journal!['id'].toString(), title, content); + } + } catch (e) { + // Gunakan variabel 'messenger' yang sudah disimpan di atas + messenger.showSnackBar( + SnackBar(content: Text('Error saving: $e')), + ); + } + } + + Future _handleDelete() async { + if (_isNew) return; + + // FIX: Simpan referensi messenger SEBELUM proses async + final messenger = ScaffoldMessenger.of(context); + + try { + await _journalService.deleteJournal(widget.journal!['id'].toString()); + } catch (e) { + // Gunakan variabel 'messenger' + messenger.showSnackBar( + SnackBar(content: Text('Error deleting: $e')), + ); + } + } + + @override + Widget build(BuildContext context) { + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + + await _handleSave(); + + // Untuk navigasi, kita tetap wajib cek mounted + if (context.mounted) { + Navigator.pop(context, true); + } + }, + child: Scaffold( + backgroundColor: const Color(0xFFF7D9C4), + appBar: AppBar( + backgroundColor: Colors.transparent, + elevation: 0, + leading: IconButton( + icon: const Icon(Icons.arrow_back_ios, color: Color(0xFFA1BC98)), + onPressed: () async { + await _handleSave(); + // Cek mounted sebelum navigasi + if (context.mounted) { + Navigator.pop(context, true); + } + }, + ), + actions: [ + IconButton( + icon: Icon( + _isEditing ? Icons.check : Icons.edit, + color: const Color(0xFFA1BC98), + ), + onPressed: () { + setState(() { + _isEditing = !_isEditing; + }); + }, + ), + ], + ), + body: Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + children: [ + TextField( + controller: _titleController, + enabled: _isEditing, + style: const TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + color: Colors.black87, + ), + decoration: const InputDecoration( + hintText: '[Judul]', + border: InputBorder.none, + ), + ), + const Divider(color: Colors.grey), + Expanded( + child: TextField( + controller: _contentController, + enabled: _isEditing, + maxLines: null, + style: const TextStyle( + fontSize: 16, + color: Colors.black87, + ), + decoration: const InputDecoration( + hintText: 'Start writing...', + border: InputBorder.none, + ), + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/flutter_app/linux/flutter/generated_plugin_registrant.cc b/flutter_app/linux/flutter/generated_plugin_registrant.cc index e71a16d..f6f23bf 100644 --- a/flutter_app/linux/flutter/generated_plugin_registrant.cc +++ b/flutter_app/linux/flutter/generated_plugin_registrant.cc @@ -6,6 +6,10 @@ #include "generated_plugin_registrant.h" +#include void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); + url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); } diff --git a/flutter_app/linux/flutter/generated_plugins.cmake b/flutter_app/linux/flutter/generated_plugins.cmake index 2e1de87..f16b4c3 100644 --- a/flutter_app/linux/flutter/generated_plugins.cmake +++ b/flutter_app/linux/flutter/generated_plugins.cmake @@ -3,6 +3,7 @@ # list(APPEND FLUTTER_PLUGIN_LIST + url_launcher_linux ) list(APPEND FLUTTER_FFI_PLUGIN_LIST diff --git a/flutter_app/macos/Flutter/GeneratedPluginRegistrant.swift b/flutter_app/macos/Flutter/GeneratedPluginRegistrant.swift index cccf817..a1cdfd0 100644 --- a/flutter_app/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/flutter_app/macos/Flutter/GeneratedPluginRegistrant.swift @@ -5,6 +5,10 @@ import FlutterMacOS import Foundation +import path_provider_foundation +import url_launcher_macos func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) + UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) } diff --git a/flutter_app/pubspec.lock b/flutter_app/pubspec.lock index b4145fc..aac8883 100644 --- a/flutter_app/pubspec.lock +++ b/flutter_app/pubspec.lock @@ -49,6 +49,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.8" + curved_navigation_bar: + dependency: "direct main" + description: + name: curved_navigation_bar + sha256: bb4ab128fcb6f4a9f0f1f72d227db531818b20218984789777f049fcbf919279 + url: "https://pub.dev" + source: hosted + version: "1.0.6" fake_async: dependency: transitive description: @@ -57,6 +65,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "289279317b4b16eb2bb7e271abccd4bf84ec9bdcbe999e278a94b804f5630418" + url: "https://pub.dev" + source: hosted + version: "2.1.4" flutter: dependency: "direct main" description: flutter @@ -75,6 +91,35 @@ packages: description: flutter source: sdk version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + http: + dependency: "direct main" + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + intl: + dependency: "direct main" + description: + name: intl + sha256: "3df61194eb431efc39c4ceba583b95633a403f46c9fd341e550ce0bfa50e9aa5" + url: "https://pub.dev" + source: hosted + version: "0.20.2" leak_tracker: dependency: transitive description: @@ -139,6 +184,70 @@ packages: url: "https://pub.dev" source: hosted version: "1.9.1" + path_provider: + dependency: "direct main" + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "95c68a74d3cab950fd0ed8073d9fab15c1c06eb1f3eec68676e87aabc9ecee5a" + url: "https://pub.dev" + source: hosted + version: "2.2.21" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "97390a0719146c7c3e71b6866c34f1cde92685933165c1c671984390d2aca776" + url: "https://pub.dev" + source: hosted + version: "2.4.4" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" sky_engine: dependency: transitive description: flutter @@ -192,6 +301,78 @@ packages: url: "https://pub.dev" source: hosted version: "0.7.8" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + url_launcher: + dependency: "direct main" + description: + name: url_launcher + sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8 + url: "https://pub.dev" + source: hosted + version: "6.3.2" + url_launcher_android: + dependency: transitive + description: + name: url_launcher_android + sha256: "767344bf3063897b5cf0db830e94f904528e6dd50a6dfaf839f0abf509009611" + url: "https://pub.dev" + source: hosted + version: "6.3.28" + url_launcher_ios: + dependency: transitive + description: + name: url_launcher_ios + sha256: cfde38aa257dae62ffe79c87fab20165dfdf6988c1d31b58ebf59b9106062aad + url: "https://pub.dev" + source: hosted + version: "6.3.6" + url_launcher_linux: + dependency: transitive + description: + name: url_launcher_linux + sha256: d5e14138b3bc193a0f63c10a53c94b91d399df0512b1f29b94a043db7482384a + url: "https://pub.dev" + source: hosted + version: "3.2.2" + url_launcher_macos: + dependency: transitive + description: + name: url_launcher_macos + sha256: "368adf46f71ad3c21b8f06614adb38346f193f3a59ba8fe9a2fd74133070ba18" + url: "https://pub.dev" + source: hosted + version: "3.2.5" + url_launcher_platform_interface: + dependency: transitive + description: + name: url_launcher_platform_interface + sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + url_launcher_web: + dependency: transitive + description: + name: url_launcher_web + sha256: "4bd2b7b4dc4d4d0b94e5babfffbca8eac1a126c7f3d6ecbc1a11013faa3abba2" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + url_launcher_windows: + dependency: transitive + description: + name: url_launcher_windows + sha256: "712c70ab1b99744ff066053cbe3e80c73332b38d46e5e945c98689b2e66fc15f" + url: "https://pub.dev" + source: hosted + version: "3.1.5" vector_math: dependency: transitive description: @@ -208,6 +389,22 @@ packages: url: "https://pub.dev" source: hosted version: "15.0.2" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" sdks: dart: ">=3.9.2 <4.0.0" - flutter: ">=3.18.0-18.0.pre.54" + flutter: ">=3.35.0" diff --git a/flutter_app/pubspec.yaml b/flutter_app/pubspec.yaml index 3036689..4841219 100644 --- a/flutter_app/pubspec.yaml +++ b/flutter_app/pubspec.yaml @@ -34,6 +34,11 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.8 + http: ^1.2.2 + path_provider: ^2.1.4 + intl: ^0.20.2 + url_launcher: ^6.3.2 + curved_navigation_bar: ^1.0.6 dev_dependencies: flutter_test: @@ -58,9 +63,8 @@ flutter: uses-material-design: true # To add assets to your application, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg + assets: + - assets/images/ # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.dev/to/resolution-aware-images diff --git a/flutter_app/windows/flutter/generated_plugin_registrant.cc b/flutter_app/windows/flutter/generated_plugin_registrant.cc index 8b6d468..4f78848 100644 --- a/flutter_app/windows/flutter/generated_plugin_registrant.cc +++ b/flutter_app/windows/flutter/generated_plugin_registrant.cc @@ -6,6 +6,9 @@ #include "generated_plugin_registrant.h" +#include void RegisterPlugins(flutter::PluginRegistry* registry) { + UrlLauncherWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("UrlLauncherWindows")); } diff --git a/flutter_app/windows/flutter/generated_plugins.cmake b/flutter_app/windows/flutter/generated_plugins.cmake index b93c4c3..88b22e5 100644 --- a/flutter_app/windows/flutter/generated_plugins.cmake +++ b/flutter_app/windows/flutter/generated_plugins.cmake @@ -3,6 +3,7 @@ # list(APPEND FLUTTER_PLUGIN_LIST + url_launcher_windows ) list(APPEND FLUTTER_FFI_PLUGIN_LIST diff --git a/node_modules/.bin/fxparser b/node_modules/.bin/fxparser new file mode 100644 index 0000000..c722e41 --- /dev/null +++ b/node_modules/.bin/fxparser @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../fast-xml-parser/src/cli/cli.js" "$@" +else + exec node "$basedir/../fast-xml-parser/src/cli/cli.js" "$@" +fi diff --git a/node_modules/.bin/fxparser.cmd b/node_modules/.bin/fxparser.cmd new file mode 100644 index 0000000..043b763 --- /dev/null +++ b/node_modules/.bin/fxparser.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%\..\fast-xml-parser\src\cli\cli.js" %* diff --git a/node_modules/.bin/fxparser.ps1 b/node_modules/.bin/fxparser.ps1 new file mode 100644 index 0000000..3e7252a --- /dev/null +++ b/node_modules/.bin/fxparser.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/../fast-xml-parser/src/cli/cli.js" $args + } else { + & "$basedir/node$exe" "$basedir/../fast-xml-parser/src/cli/cli.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../fast-xml-parser/src/cli/cli.js" $args + } else { + & "node$exe" "$basedir/../fast-xml-parser/src/cli/cli.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/mime b/node_modules/.bin/mime new file mode 100644 index 0000000..7751de3 --- /dev/null +++ b/node_modules/.bin/mime @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../mime/cli.js" "$@" +else + exec node "$basedir/../mime/cli.js" "$@" +fi diff --git a/node_modules/.bin/mime.cmd b/node_modules/.bin/mime.cmd new file mode 100644 index 0000000..54491f1 --- /dev/null +++ b/node_modules/.bin/mime.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%\..\mime\cli.js" %* diff --git a/node_modules/.bin/mime.ps1 b/node_modules/.bin/mime.ps1 new file mode 100644 index 0000000..2222f40 --- /dev/null +++ b/node_modules/.bin/mime.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/../mime/cli.js" $args + } else { + & "$basedir/node$exe" "$basedir/../mime/cli.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../mime/cli.js" $args + } else { + & "node$exe" "$basedir/../mime/cli.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/proto-loader-gen-types b/node_modules/.bin/proto-loader-gen-types new file mode 100644 index 0000000..03c2fcc --- /dev/null +++ b/node_modules/.bin/proto-loader-gen-types @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../@grpc/proto-loader/build/bin/proto-loader-gen-types.js" "$@" +else + exec node "$basedir/../@grpc/proto-loader/build/bin/proto-loader-gen-types.js" "$@" +fi diff --git a/node_modules/.bin/proto-loader-gen-types.cmd b/node_modules/.bin/proto-loader-gen-types.cmd new file mode 100644 index 0000000..772529b --- /dev/null +++ b/node_modules/.bin/proto-loader-gen-types.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%\..\@grpc\proto-loader\build\bin\proto-loader-gen-types.js" %* diff --git a/node_modules/.bin/proto-loader-gen-types.ps1 b/node_modules/.bin/proto-loader-gen-types.ps1 new file mode 100644 index 0000000..d1db451 --- /dev/null +++ b/node_modules/.bin/proto-loader-gen-types.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/../@grpc/proto-loader/build/bin/proto-loader-gen-types.js" $args + } else { + & "$basedir/node$exe" "$basedir/../@grpc/proto-loader/build/bin/proto-loader-gen-types.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../@grpc/proto-loader/build/bin/proto-loader-gen-types.js" $args + } else { + & "node$exe" "$basedir/../@grpc/proto-loader/build/bin/proto-loader-gen-types.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/semver b/node_modules/.bin/semver new file mode 100644 index 0000000..97c5327 --- /dev/null +++ b/node_modules/.bin/semver @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../semver/bin/semver.js" "$@" +else + exec node "$basedir/../semver/bin/semver.js" "$@" +fi diff --git a/node_modules/.bin/semver.cmd b/node_modules/.bin/semver.cmd new file mode 100644 index 0000000..9913fa9 --- /dev/null +++ b/node_modules/.bin/semver.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%\..\semver\bin\semver.js" %* diff --git a/node_modules/.bin/semver.ps1 b/node_modules/.bin/semver.ps1 new file mode 100644 index 0000000..314717a --- /dev/null +++ b/node_modules/.bin/semver.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/../semver/bin/semver.js" $args + } else { + & "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../semver/bin/semver.js" $args + } else { + & "node$exe" "$basedir/../semver/bin/semver.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/uuid b/node_modules/.bin/uuid new file mode 100644 index 0000000..25cbae6 --- /dev/null +++ b/node_modules/.bin/uuid @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../uuid/dist/esm/bin/uuid" "$@" +else + exec node "$basedir/../uuid/dist/esm/bin/uuid" "$@" +fi diff --git a/node_modules/.bin/uuid.cmd b/node_modules/.bin/uuid.cmd new file mode 100644 index 0000000..3debc70 --- /dev/null +++ b/node_modules/.bin/uuid.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\uuid\dist\esm\bin\uuid" %* diff --git a/node_modules/.bin/uuid.ps1 b/node_modules/.bin/uuid.ps1 new file mode 100644 index 0000000..14f6846 --- /dev/null +++ b/node_modules/.bin/uuid.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../uuid/dist/esm/bin/uuid" $args + } else { + & "$basedir/node$exe" "$basedir/../uuid/dist/esm/bin/uuid" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../uuid/dist/esm/bin/uuid" $args + } else { + & "node$exe" "$basedir/../uuid/dist/esm/bin/uuid" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..d3057d8 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,1964 @@ +{ + "name": "Psychology-Apps", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@fastify/busboy": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-3.2.0.tgz", + "integrity": "sha512-m9FVDXU3GT2ITSe0UaMA5rU3QkfC/UXtCU8y0gSN/GugTqtVldOBWIB5V6V3sbmenVZUIpU6f+mPEO2+m5iTaA==", + "license": "MIT" + }, + "node_modules/@firebase/app-check-interop-types": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/@firebase/app-check-interop-types/-/app-check-interop-types-0.3.3.tgz", + "integrity": "sha512-gAlxfPLT2j8bTI/qfe3ahl2I2YcBQ8cFIBdhAQA4I2f3TndcO+22YizyGYuttLHPQEpWkhmpFW60VCFEPg4g5A==", + "license": "Apache-2.0" + }, + "node_modules/@firebase/app-types": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/@firebase/app-types/-/app-types-0.9.3.tgz", + "integrity": "sha512-kRVpIl4vVGJ4baogMDINbyrIOtOxqhkZQg4jTq3l8Lw6WSk0xfpEYzezFu+Kl4ve4fbPl79dvwRtaFqAC/ucCw==", + "license": "Apache-2.0" + }, + "node_modules/@firebase/auth-interop-types": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/@firebase/auth-interop-types/-/auth-interop-types-0.2.4.tgz", + "integrity": "sha512-JPgcXKCuO+CWqGDnigBtvo09HeBs5u/Ktc2GaFj2m01hLarbxthLNm7Fk8iOP1aqAtXV+fnnGj7U28xmk7IwVA==", + "license": "Apache-2.0" + }, + "node_modules/@firebase/component": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/@firebase/component/-/component-0.7.0.tgz", + "integrity": "sha512-wR9En2A+WESUHexjmRHkqtaVH94WLNKt6rmeqZhSLBybg4Wyf0Umk04SZsS6sBq4102ZsDBFwoqMqJYj2IoDSg==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/util": "1.13.0", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@firebase/database": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@firebase/database/-/database-1.1.0.tgz", + "integrity": "sha512-gM6MJFae3pTyNLoc9VcJNuaUDej0ctdjn3cVtILo3D5lpp0dmUHHLFN/pUKe7ImyeB1KAvRlEYxvIHNF04Filg==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/app-check-interop-types": "0.3.3", + "@firebase/auth-interop-types": "0.2.4", + "@firebase/component": "0.7.0", + "@firebase/logger": "0.5.0", + "@firebase/util": "1.13.0", + "faye-websocket": "0.11.4", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@firebase/database-compat": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@firebase/database-compat/-/database-compat-2.1.0.tgz", + "integrity": "sha512-8nYc43RqxScsePVd1qe1xxvWNf0OBnbwHxmXJ7MHSuuTVYFO3eLyLW3PiCKJ9fHnmIz4p4LbieXwz+qtr9PZDg==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.0", + "@firebase/database": "1.1.0", + "@firebase/database-types": "1.0.16", + "@firebase/logger": "0.5.0", + "@firebase/util": "1.13.0", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@firebase/database-types": { + "version": "1.0.16", + "resolved": "https://registry.npmjs.org/@firebase/database-types/-/database-types-1.0.16.tgz", + "integrity": "sha512-xkQLQfU5De7+SPhEGAXFBnDryUWhhlFXelEg2YeZOQMCdoe7dL64DDAd77SQsR+6uoXIZY5MB4y/inCs4GTfcw==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/app-types": "0.9.3", + "@firebase/util": "1.13.0" + } + }, + "node_modules/@firebase/logger": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@firebase/logger/-/logger-0.5.0.tgz", + "integrity": "sha512-cGskaAvkrnh42b3BA3doDWeBmuHFO/Mx5A83rbRDYakPjO9bJtRL3dX7javzc2Rr/JHZf4HlterTW2lUkfeN4g==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@firebase/util": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@firebase/util/-/util-1.13.0.tgz", + "integrity": "sha512-0AZUyYUfpMNcztR5l09izHwXkZpghLgCUaAGjtMwXnCg3bj4ml5VgiwqOMOxJ+Nw4qN/zJAaOQBcJ7KGkWStqQ==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@google-cloud/firestore": { + "version": "7.11.6", + "resolved": "https://registry.npmjs.org/@google-cloud/firestore/-/firestore-7.11.6.tgz", + "integrity": "sha512-EW/O8ktzwLfyWBOsNuhRoMi8lrC3clHM5LVFhGvO1HCsLozCOOXRAlHrYBoE6HL42Sc8yYMuCb2XqcnJ4OOEpw==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@opentelemetry/api": "^1.3.0", + "fast-deep-equal": "^3.1.1", + "functional-red-black-tree": "^1.0.1", + "google-gax": "^4.3.3", + "protobufjs": "^7.2.6" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@google-cloud/paginator": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@google-cloud/paginator/-/paginator-5.0.2.tgz", + "integrity": "sha512-DJS3s0OVH4zFDB1PzjxAsHqJT6sKVbRwwML0ZBP9PbU7Yebtu/7SWMRzvO2J3nUi9pRNITCfu4LJeooM2w4pjg==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "arrify": "^2.0.0", + "extend": "^3.0.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@google-cloud/projectify": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@google-cloud/projectify/-/projectify-4.0.0.tgz", + "integrity": "sha512-MmaX6HeSvyPbWGwFq7mXdo0uQZLGBYCwziiLIGq5JVX+/bdI3SAq6bP98trV5eTWfLuvsMcIC1YJOF2vfteLFA==", + "license": "Apache-2.0", + "optional": true, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@google-cloud/promisify": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@google-cloud/promisify/-/promisify-4.0.0.tgz", + "integrity": "sha512-Orxzlfb9c67A15cq2JQEyVc7wEsmFBmHjZWZYQMUyJ1qivXyMwdyNOs9odi79hze+2zqdTtu1E19IM/FtqZ10g==", + "license": "Apache-2.0", + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@google-cloud/storage": { + "version": "7.18.0", + "resolved": "https://registry.npmjs.org/@google-cloud/storage/-/storage-7.18.0.tgz", + "integrity": "sha512-r3ZwDMiz4nwW6R922Z1pwpePxyRwE5GdevYX63hRmAQUkUQJcBH/79EnQPDv5cOv1mFBgevdNWQfi3tie3dHrQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@google-cloud/paginator": "^5.0.0", + "@google-cloud/projectify": "^4.0.0", + "@google-cloud/promisify": "<4.1.0", + "abort-controller": "^3.0.0", + "async-retry": "^1.3.3", + "duplexify": "^4.1.3", + "fast-xml-parser": "^4.4.1", + "gaxios": "^6.0.2", + "google-auth-library": "^9.6.3", + "html-entities": "^2.5.2", + "mime": "^3.0.0", + "p-limit": "^3.0.1", + "retry-request": "^7.0.0", + "teeny-request": "^9.0.0", + "uuid": "^8.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@google-cloud/storage/node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "license": "MIT", + "optional": true, + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/@grpc/grpc-js": { + "version": "1.14.2", + "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.2.tgz", + "integrity": "sha512-QzVUtEFyu05UNx2xr0fCQmStUO17uVQhGNowtxs00IgTZT6/W2PBLfUkj30s0FKJ29VtTa3ArVNIhNP6akQhqA==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@grpc/proto-loader": "^0.8.0", + "@js-sdsl/ordered-map": "^4.4.2" + }, + "engines": { + "node": ">=12.10.0" + } + }, + "node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.8.0.tgz", + "integrity": "sha512-rc1hOQtjIWGxcxpb9aHAfLpIctjEnsDehj0DAiVfBlmT84uvR0uUtN2hEi/ecvWVjXUGf5qPF4qEgiLOx1YIMQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "lodash.camelcase": "^4.3.0", + "long": "^5.0.0", + "protobufjs": "^7.5.3", + "yargs": "^17.7.2" + }, + "bin": { + "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@grpc/proto-loader": { + "version": "0.7.15", + "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.7.15.tgz", + "integrity": "sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "lodash.camelcase": "^4.3.0", + "long": "^5.0.0", + "protobufjs": "^7.2.5", + "yargs": "^17.7.2" + }, + "bin": { + "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@js-sdsl/ordered-map": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@js-sdsl/ordered-map/-/ordered-map-4.4.2.tgz", + "integrity": "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw==", + "license": "MIT", + "optional": true, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/js-sdsl" + } + }, + "node_modules/@opentelemetry/api": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz", + "integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==", + "license": "Apache-2.0", + "optional": true, + "engines": { + "node": ">=8.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", + "optional": true + }, + "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", + "optional": true + }, + "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", + "optional": true + }, + "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", + "optional": true + }, + "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", + "optional": true, + "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", + "optional": true + }, + "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", + "optional": true + }, + "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", + "optional": true + }, + "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", + "optional": true + }, + "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", + "optional": true + }, + "node_modules/@tootallnate/once": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", + "integrity": "sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 10" + } + }, + "node_modules/@types/body-parser": { + "version": "1.19.6", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", + "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==", + "license": "MIT", + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/caseless": { + "version": "0.12.5", + "resolved": "https://registry.npmjs.org/@types/caseless/-/caseless-0.12.5.tgz", + "integrity": "sha512-hWtVTC2q7hc7xZ/RLbxapMvDMgUnDvKvMOpKal4DrMyfGBUfB1oKaZlIRr6mJL+If3bAP6sV/QneGzF6tJjZDg==", + "license": "MIT", + "optional": true + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/express": { + "version": "4.17.25", + "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.25.tgz", + "integrity": "sha512-dVd04UKsfpINUnK0yBoYHDF3xu7xVH4BuDotC/xGuycx4CgbP48X/KF/586bcObxT0HENHXEU8Nqtu6NR+eKhw==", + "license": "MIT", + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "^1" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "4.19.7", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.7.tgz", + "integrity": "sha512-FvPtiIf1LfhzsaIXhv/PHan/2FeQBbtBDtfX2QfvPxdUelMDEckK08SM6nqo1MIZY3RUlfA+HV8+hFUSio78qg==", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/http-errors": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", + "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==", + "license": "MIT" + }, + "node_modules/@types/jsonwebtoken": { + "version": "9.0.10", + "resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.10.tgz", + "integrity": "sha512-asx5hIG9Qmf/1oStypjanR7iKTv0gXQ1Ov/jfrX6kS/EO0OFni8orbmGCn0672NHR3kXHwpAwR+B368ZGN/2rA==", + "license": "MIT", + "dependencies": { + "@types/ms": "*", + "@types/node": "*" + } + }, + "node_modules/@types/long": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/long/-/long-4.0.2.tgz", + "integrity": "sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA==", + "license": "MIT", + "optional": true + }, + "node_modules/@types/mime": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", + "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==", + "license": "MIT" + }, + "node_modules/@types/ms": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz", + "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.19.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.2.tgz", + "integrity": "sha512-LPM2G3Syo1GLzXLGJAKdqoU35XvrWzGJ21/7sgZTUpbkBaOasTj8tjwn6w+hCkqaa1TfJ/w67rJSwYItlJ2mYw==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/qs": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ==", + "license": "MIT" + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", + "license": "MIT" + }, + "node_modules/@types/request": { + "version": "2.48.13", + "resolved": "https://registry.npmjs.org/@types/request/-/request-2.48.13.tgz", + "integrity": "sha512-FGJ6udDNUCjd19pp0Q3iTiDkwhYup7J8hpMW9c4k53NrccQFFWKRho6hvtPPEhnXWKvukfwAlB6DbDz4yhH5Gg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@types/caseless": "*", + "@types/node": "*", + "@types/tough-cookie": "*", + "form-data": "^2.5.5" + } + }, + "node_modules/@types/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz", + "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "1.15.10", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.10.tgz", + "integrity": "sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw==", + "license": "MIT", + "dependencies": { + "@types/http-errors": "*", + "@types/node": "*", + "@types/send": "<1" + } + }, + "node_modules/@types/serve-static/node_modules/@types/send": { + "version": "0.17.6", + "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.6.tgz", + "integrity": "sha512-Uqt8rPBE8SY0RK8JB1EzVOIZ32uqy8HwdxCnoCOsYrvnswqmFZ/k+9Ikidlk/ImhsdvBsloHbAlewb2IEBV/Og==", + "license": "MIT", + "dependencies": { + "@types/mime": "^1", + "@types/node": "*" + } + }, + "node_modules/@types/tough-cookie": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.5.tgz", + "integrity": "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==", + "license": "MIT", + "optional": true + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "license": "MIT", + "optional": true, + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "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", + "optional": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/arrify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-2.0.1.tgz", + "integrity": "sha512-3duEwti880xqi4eAMN8AyR4a0ByT90zoYdLlevfrvU43vb0YZwZVfxOgxWrLXXXpyugL0hNZc9G6BiB5B3nUug==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/async-retry": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/async-retry/-/async-retry-1.3.3.tgz", + "integrity": "sha512-wfr/jstw9xNi/0teMHrRW7dsz3Lt5ARhYNZ2ewpadnhaIp5mbALhOAP+EAdsC7t4Z6wqsDVv9+W6gm1Dk9mEyw==", + "license": "MIT", + "optional": true, + "dependencies": { + "retry": "0.13.1" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT", + "optional": true + }, + "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/bignumber.js": { + "version": "9.3.1", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz", + "integrity": "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==", + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "license": "ISC", + "optional": true, + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "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", + "optional": true, + "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", + "optional": true + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "optional": true, + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "optional": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/duplexify": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-4.1.3.tgz", + "integrity": "sha512-M3BmBhwJRZsSx38lZyhE53Csddgzl5R7xGJNk7CVddZD6CcmwMCH8J+7AprIrQKH7TonKxaCjcv27Qmf+sQ+oA==", + "license": "MIT", + "optional": true, + "dependencies": { + "end-of-stream": "^1.4.1", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1", + "stream-shift": "^1.0.2" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT", + "optional": true + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "optional": true, + "dependencies": { + "once": "^1.4.0" + } + }, + "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", + "optional": true, + "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", + "optional": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "optional": true, + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "optional": true, + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "license": "MIT" + }, + "node_modules/farmhash-modern": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/farmhash-modern/-/farmhash-modern-1.1.0.tgz", + "integrity": "sha512-6ypT4XfgqJk/F3Yuv4SX26I3doUjt0GTG4a+JgWxXQpxXzTBq8fPUeGHfcYMMDPHJHm3yPOSjaeBwBGAHWXCdA==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-xml-parser": { + "version": "4.5.3", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.5.3.tgz", + "integrity": "sha512-RKihhV+SHsIUGXObeVy9AXiBbFwkVk7Syp8XgwN5U3JV416+Gwp/GO9i0JYKmikykgz/UHRrrV4ROuZEo/T0ig==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "optional": true, + "dependencies": { + "strnum": "^1.1.1" + }, + "bin": { + "fxparser": "src/cli/cli.js" + } + }, + "node_modules/faye-websocket": { + "version": "0.11.4", + "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.11.4.tgz", + "integrity": "sha512-CzbClwlXAuiRQAlUyfqPgvPoNKTckTPGfwZV4ZdAhVcP2lh9KUxJg2b5GkE7XbjKQ3YJnQ9z6D9ntLAlB+tP8g==", + "license": "Apache-2.0", + "dependencies": { + "websocket-driver": ">=0.5.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/firebase-admin": { + "version": "13.6.0", + "resolved": "https://registry.npmjs.org/firebase-admin/-/firebase-admin-13.6.0.tgz", + "integrity": "sha512-GdPA/t0+Cq8p1JnjFRBmxRxAGvF/kl2yfdhALl38PrRp325YxyQ5aNaHui0XmaKcKiGRFIJ/EgBNWFoDP0onjw==", + "license": "Apache-2.0", + "dependencies": { + "@fastify/busboy": "^3.0.0", + "@firebase/database-compat": "^2.0.0", + "@firebase/database-types": "^1.0.6", + "@types/node": "^22.8.7", + "farmhash-modern": "^1.1.0", + "fast-deep-equal": "^3.1.1", + "google-auth-library": "^9.14.2", + "jsonwebtoken": "^9.0.0", + "jwks-rsa": "^3.1.0", + "node-forge": "^1.3.1", + "uuid": "^11.0.2" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@google-cloud/firestore": "^7.11.0", + "@google-cloud/storage": "^7.14.0" + } + }, + "node_modules/form-data": { + "version": "2.5.5", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.5.5.tgz", + "integrity": "sha512-jqdObeR2rxZZbPSGL+3VckHMYtu+f9//KXBsVny6JSX/pa38Fy+bGjuG8eW/H6USNQWhLi8Num++cU2yOCNz4A==", + "license": "MIT", + "optional": true, + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", + "mime-types": "^2.1.35", + "safe-buffer": "^5.2.1" + }, + "engines": { + "node": ">= 0.12" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "optional": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/functional-red-black-tree": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", + "integrity": "sha512-dsKNQNdj6xA3T+QlADDA7mOSlX0qiMINjn0cgr+eGHGsbSHzTabcIogz2+p/iqP1Xs6EP/sS2SbqH+brGTbq0g==", + "license": "MIT", + "optional": true + }, + "node_modules/gaxios": { + "version": "6.7.1", + "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-6.7.1.tgz", + "integrity": "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ==", + "license": "Apache-2.0", + "dependencies": { + "extend": "^3.0.2", + "https-proxy-agent": "^7.0.1", + "is-stream": "^2.0.0", + "node-fetch": "^2.6.9", + "uuid": "^9.0.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/gaxios/node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/gcp-metadata": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-6.1.1.tgz", + "integrity": "sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A==", + "license": "Apache-2.0", + "dependencies": { + "gaxios": "^6.1.1", + "google-logging-utils": "^0.0.2", + "json-bigint": "^1.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "optional": true, + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "optional": true, + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/google-auth-library": { + "version": "9.15.1", + "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-9.15.1.tgz", + "integrity": "sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng==", + "license": "Apache-2.0", + "dependencies": { + "base64-js": "^1.3.0", + "ecdsa-sig-formatter": "^1.0.11", + "gaxios": "^6.1.1", + "gcp-metadata": "^6.1.0", + "gtoken": "^7.0.0", + "jws": "^4.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/google-gax": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/google-gax/-/google-gax-4.6.1.tgz", + "integrity": "sha512-V6eky/xz2mcKfAd1Ioxyd6nmA61gao3n01C+YeuIwu3vzM9EDR6wcVzMSIbLMDXWeoi9SHYctXuKYC5uJUT3eQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@grpc/grpc-js": "^1.10.9", + "@grpc/proto-loader": "^0.7.13", + "@types/long": "^4.0.0", + "abort-controller": "^3.0.0", + "duplexify": "^4.0.0", + "google-auth-library": "^9.3.0", + "node-fetch": "^2.7.0", + "object-hash": "^3.0.0", + "proto3-json-serializer": "^2.0.2", + "protobufjs": "^7.3.2", + "retry-request": "^7.0.0", + "uuid": "^9.0.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/google-gax/node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "optional": true, + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/google-logging-utils": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-0.0.2.tgz", + "integrity": "sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gtoken": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-7.1.0.tgz", + "integrity": "sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==", + "license": "MIT", + "dependencies": { + "gaxios": "^6.0.0", + "jws": "^4.0.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "optional": true, + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/html-entities": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/html-entities/-/html-entities-2.6.0.tgz", + "integrity": "sha512-kig+rMn/QOVRvr7c86gQ8lWXq+Hkv6CbAH1hLu+RG338StTpE8Z0b44SDVaqVu7HGKf27frdmUYEs9hTUX/cLQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/mdevils" + }, + { + "type": "patreon", + "url": "https://patreon.com/mdevils" + } + ], + "license": "MIT", + "optional": true + }, + "node_modules/http-parser-js": { + "version": "0.5.10", + "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.10.tgz", + "integrity": "sha512-Pysuw9XpUq5dVc/2SMHpuTY01RFl8fttgcyunjL7eEMhGM3cI4eOmiCycJDVCo/7O7ClfQD3SaI6ftDzqOXYMA==", + "license": "MIT" + }, + "node_modules/http-proxy-agent": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz", + "integrity": "sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==", + "license": "MIT", + "optional": true, + "dependencies": { + "@tootallnate/once": "2", + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/http-proxy-agent/node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC", + "optional": true + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jose": { + "version": "4.15.9", + "resolved": "https://registry.npmjs.org/jose/-/jose-4.15.9.tgz", + "integrity": "sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/json-bigint": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz", + "integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==", + "license": "MIT", + "dependencies": { + "bignumber.js": "^9.0.0" + } + }, + "node_modules/jsonwebtoken": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz", + "integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==", + "license": "MIT", + "dependencies": { + "jws": "^4.0.1", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, + "node_modules/jwa": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", + "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jwks-rsa": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/jwks-rsa/-/jwks-rsa-3.2.0.tgz", + "integrity": "sha512-PwchfHcQK/5PSydeKCs1ylNym0w/SSv8a62DgHJ//7x2ZclCoinlsjAfDxAAbpoTPybOum/Jgy+vkvMmKz89Ww==", + "license": "MIT", + "dependencies": { + "@types/express": "^4.17.20", + "@types/jsonwebtoken": "^9.0.4", + "debug": "^4.3.4", + "jose": "^4.15.4", + "limiter": "^1.1.5", + "lru-memoizer": "^2.2.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/jws": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", + "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", + "license": "MIT", + "dependencies": { + "jwa": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/limiter": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/limiter/-/limiter-1.1.5.tgz", + "integrity": "sha512-FWWMIEOxz3GwUI4Ts/IvgVy6LPvoMPgjMdQ185nN6psJyBJ4yOpzqm695/h5umdLJg2vW3GR5iG11MAkR2AzJA==" + }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", + "license": "MIT", + "optional": true + }, + "node_modules/lodash.clonedeep": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz", + "integrity": "sha512-H5ZhCF25riFd9uB5UCkVKo61m3S/xZk1x4wA6yp/L3RFP6Z/eHH1ymQcGLo7J3GMPfm0V/7m1tryHuGVxpqEBQ==", + "license": "MIT" + }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", + "license": "MIT" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", + "license": "MIT" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "license": "MIT" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", + "license": "MIT" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", + "license": "MIT" + }, + "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", + "optional": true + }, + "node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/lru-memoizer": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/lru-memoizer/-/lru-memoizer-2.3.0.tgz", + "integrity": "sha512-GXn7gyHAMhO13WSKrIiNfztwxodVsP8IoZ3XfrJV4yH2x0/OeTO/FIaAHTY5YekdGgW94njfuKmyyt1E0mR6Ug==", + "license": "MIT", + "dependencies": { + "lodash.clonedeep": "^4.5.0", + "lru-cache": "6.0.0" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/mime": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz", + "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==", + "license": "MIT", + "optional": true, + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "optional": true, + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/node-forge": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.3.tgz", + "integrity": "sha512-rLvcdSyRCyouf6jcOIPe/BgwG/d7hKjzMKOas33/pHEr6gbq18IK9zV7DiPvzsz0oBJPme6qr6H6kGZuI9/DZg==", + "license": "(BSD-3-Clause OR GPL-2.0)", + "engines": { + "node": ">= 6.13.0" + } + }, + "node_modules/object-hash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz", + "integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 6" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "optional": true, + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/proto3-json-serializer": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/proto3-json-serializer/-/proto3-json-serializer-2.0.2.tgz", + "integrity": "sha512-SAzp/O4Yh02jGdRc+uIrGoe87dkN/XtwxfZ4ZyafJHymd79ozp5VG5nyZ7ygqPM5+cpLDjjGnYFUkngonyDPOQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "protobufjs": "^7.2.5" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "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", + "optional": true, + "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/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "optional": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/retry": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", + "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/retry-request": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/retry-request/-/retry-request-7.0.2.tgz", + "integrity": "sha512-dUOvLMJ0/JJYEn8NrpOaGNE7X3vpI5XlZS/u0ANjqtcZVKnIxP7IgCFwrKTxENw29emmwug53awKtaMm4i9g5w==", + "license": "MIT", + "optional": true, + "dependencies": { + "@types/request": "^2.48.8", + "extend": "^3.0.2", + "teeny-request": "^9.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/stream-events": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/stream-events/-/stream-events-1.0.5.tgz", + "integrity": "sha512-E1GUzBSgvct8Jsb3v2X15pjzN1tYebtbLaMg+eBOUOAxgbLoSbT2NS91ckc5lJD1KfLjId+jXJRgo0qnV5Nerg==", + "license": "MIT", + "optional": true, + "dependencies": { + "stubs": "^3.0.0" + } + }, + "node_modules/stream-shift": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.3.tgz", + "integrity": "sha512-76ORR0DO1o1hlKwTbi/DM3EXWGf3ZJYO8cXX5RJwnul2DEg2oyoZyjLNoQM8WsvZiFKCRfC1O0J7iCvie3RZmQ==", + "license": "MIT", + "optional": true + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "optional": true, + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "optional": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "optional": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strnum": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-1.1.2.tgz", + "integrity": "sha512-vrN+B7DBIoTTZjnPNewwhx6cBA/H+IS7rfW68n7XxC1y7uoiGQBxaKzqucGUgavX15dJgiGztLJ8vxuEzwqBdA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "optional": true + }, + "node_modules/stubs": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/stubs/-/stubs-3.0.0.tgz", + "integrity": "sha512-PdHt7hHUJKxvTCgbKX9C1V/ftOcjJQgz8BZwNfV5c4B6dcGqlpelTbJ999jBGZ2jYiPAwcX5dP6oBwVlBlUbxw==", + "license": "MIT", + "optional": true + }, + "node_modules/teeny-request": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/teeny-request/-/teeny-request-9.0.0.tgz", + "integrity": "sha512-resvxdc6Mgb7YEThw6G6bExlXKkv6+YbuzGg9xuXxSgxJF7Ozs+o8Y9+2R3sArdWdW8nOokoQb1yrpFB0pQK2g==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "http-proxy-agent": "^5.0.0", + "https-proxy-agent": "^5.0.0", + "node-fetch": "^2.6.9", + "stream-events": "^1.0.5", + "uuid": "^9.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/teeny-request/node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/teeny-request/node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "license": "MIT", + "optional": true, + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/teeny-request/node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "optional": true, + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, + "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/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "license": "MIT" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT", + "optional": true + }, + "node_modules/uuid": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz", + "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/esm/bin/uuid" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/websocket-driver": { + "version": "0.7.4", + "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.4.tgz", + "integrity": "sha512-b17KeDIQVjvb0ssuSDF2cYXSg2iztliJ4B9WdsuB6J952qCPKmnVq4DyW5motImXHDC1cBT/1UezrJVsKw5zjg==", + "license": "Apache-2.0", + "dependencies": { + "http-parser-js": ">=0.5.1", + "safe-buffer": ">=5.1.0", + "websocket-extensions": ">=0.1.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/websocket-extensions": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.4.tgz", + "integrity": "sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "optional": true, + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC", + "optional": true + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "license": "ISC", + "optional": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "license": "ISC" + }, + "node_modules/yargs": { + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "license": "MIT", + "optional": true, + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "license": "ISC", + "optional": true, + "engines": { + "node": ">=12" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/node_modules/@fastify/busboy/LICENSE b/node_modules/@fastify/busboy/LICENSE new file mode 100644 index 0000000..e138e71 --- /dev/null +++ b/node_modules/@fastify/busboy/LICENSE @@ -0,0 +1,24 @@ +MIT License + +Copyright Brian White. All rights reserved. +Copyright (c) 2021-present The Fastify team + +The Fastify team members are listed at https://github.com/fastify/fastify#team. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@fastify/busboy/README.md b/node_modules/@fastify/busboy/README.md new file mode 100644 index 0000000..7334f6f --- /dev/null +++ b/node_modules/@fastify/busboy/README.md @@ -0,0 +1,270 @@ +# busboy + +

+ +
+ +[![NPM version](https://img.shields.io/npm/v/@fastify/busboy.svg?style=flat)](https://www.npmjs.com/package/@fastify/busboy) +[![NPM downloads](https://img.shields.io/npm/dm/@fastify/busboy.svg?style=flat)](https://www.npmjs.com/package/@fastify/busboy) + +
+ +Description +=========== + +A Node.js module for parsing incoming HTML form data. + +This is an officially supported fork by [fastify](https://github.com/fastify/) organization of the amazing library [originally created](https://github.com/mscdex/busboy) by Brian White, +aimed at addressing long-standing issues with it. + +Benchmark (Mean time for 500 Kb payload, 2000 cycles, 1000 cycle warmup): + +| Library | Version | Mean time in nanoseconds (less is better) | +|-----------------------|---------|-------------------------------------------| +| busboy | 0.3.1 | `340114` | +| @fastify/busboy | 1.0.0 | `270984` | + +[Changelog](https://github.com/fastify/busboy/blob/main/CHANGELOG.md) since busboy 0.31. + +Requirements +============ + +* [Node.js](http://nodejs.org/) 10+ + + +Install +======= + + npm i @fastify/busboy + + +Examples +======== + +* Parsing (multipart) with default options: + +```javascript +const http = require('node:http'); +const { inspect } = require('node:util'); +const Busboy = require('@fastify/busboy'); + +http.createServer((req, res) => { + if (req.method === 'POST') { + const busboy = new Busboy({ headers: req.headers }); + busboy.on('file', (fieldname, file, filename, encoding, mimetype) => { + console.log(`File [${fieldname}]: filename: ${filename}, encoding: ${encoding}, mimetype: ${mimetype}`); + file.on('data', data => { + console.log(`File [${fieldname}] got ${data.length} bytes`); + }); + file.on('end', () => { + console.log(`File [${fieldname}] Finished`); + }); + }); + busboy.on('field', (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) => { + console.log(`Field [${fieldname}]: value: ${inspect(val)}`); + }); + busboy.on('finish', () => { + console.log('Done parsing form!'); + res.writeHead(303, { Connection: 'close', Location: '/' }); + res.end(); + }); + req.pipe(busboy); + } else if (req.method === 'GET') { + res.writeHead(200, { Connection: 'close' }); + res.end(` +
+
+
+ +
+ `); + } +}).listen(8000, () => { + console.log('Listening for requests'); +}); + +// Example output, using http://nodejs.org/images/ryan-speaker.jpg as the file: +// +// Listening for requests +// File [filefield]: filename: ryan-speaker.jpg, encoding: binary +// File [filefield] got 11971 bytes +// Field [textfield]: value: 'testing! :-)' +// File [filefield] Finished +// Done parsing form! +``` + +* Save all incoming files to disk: + +```javascript +const http = require('node:http'); +const path = require('node:path'); +const os = require('node:os'); +const fs = require('node:fs'); + +const Busboy = require('@fastify/busboy'); + +http.createServer(function(req, res) { + if (req.method === 'POST') { + const busboy = new Busboy({ headers: req.headers }); + busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { + var saveTo = path.join(os.tmpdir(), path.basename(fieldname)); + file.pipe(fs.createWriteStream(saveTo)); + }); + busboy.on('finish', function() { + res.writeHead(200, { 'Connection': 'close' }); + res.end("That's all folks!"); + }); + return req.pipe(busboy); + } + res.writeHead(404); + res.end(); +}).listen(8000, function() { + console.log('Listening for requests'); +}); +``` + +* Parsing (urlencoded) with default options: + +```javascript +const http = require('node:http'); +const { inspect } = require('node:util'); + +const Busboy = require('@fastify/busboy'); + +http.createServer(function(req, res) { + if (req.method === 'POST') { + const busboy = new Busboy({ headers: req.headers }); + busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { + console.log('File [' + fieldname + ']: filename: ' + filename); + file.on('data', function(data) { + console.log('File [' + fieldname + '] got ' + data.length + ' bytes'); + }); + file.on('end', function() { + console.log('File [' + fieldname + '] Finished'); + }); + }); + busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) { + console.log('Field [' + fieldname + ']: value: ' + inspect(val)); + }); + busboy.on('finish', function() { + console.log('Done parsing form!'); + res.writeHead(303, { Connection: 'close', Location: '/' }); + res.end(); + }); + req.pipe(busboy); + } else if (req.method === 'GET') { + res.writeHead(200, { Connection: 'close' }); + res.end('\ +
\ +
\ +
\ + Node.js rules!
\ + \ +
\ + '); + } +}).listen(8000, function() { + console.log('Listening for requests'); +}); + +// Example output: +// +// Listening for requests +// Field [textfield]: value: 'testing! :-)' +// Field [selectfield]: value: '9001' +// Field [checkfield]: value: 'on' +// Done parsing form! +``` + + +API +=== + +_Busboy_ is a _Writable_ stream + +Busboy (special) events +----------------------- + +* **file**(< _string_ >fieldname, < _ReadableStream_ >stream, < _string_ >filename, < _string_ >transferEncoding, < _string_ >mimeType) - Emitted for each new file form field found. `transferEncoding` contains the 'Content-Transfer-Encoding' value for the file stream. `mimeType` contains the 'Content-Type' value for the file stream. + * Note: if you listen for this event, you should always handle the `stream` no matter if you care about the file contents or not (e.g. you can simply just do `stream.resume();` if you want to discard the contents), otherwise the 'finish' event will never fire on the Busboy instance. However, if you don't care about **any** incoming files, you can simply not listen for the 'file' event at all and any/all files will be automatically and safely discarded (these discarded files do still count towards `files` and `parts` limits). + * If a configured file size limit was reached, `stream` will both have a boolean property `truncated` (best checked at the end of the stream) and emit a 'limit' event to notify you when this happens. + * The property `bytesRead` informs about the number of bytes that have been read so far. + +* **field**(< _string_ >fieldname, < _string_ >value, < _boolean_ >fieldnameTruncated, < _boolean_ >valueTruncated, < _string_ >transferEncoding, < _string_ >mimeType) - Emitted for each new non-file field found. + +* **partsLimit**() - Emitted when specified `parts` limit has been reached. No more 'file' or 'field' events will be emitted. + +* **filesLimit**() - Emitted when specified `files` limit has been reached. No more 'file' events will be emitted. + +* **fieldsLimit**() - Emitted when specified `fields` limit has been reached. No more 'field' events will be emitted. + + +Busboy methods +-------------- + +* **(constructor)**(< _object_ >config) - Creates and returns a new Busboy instance. + + * The constructor takes the following valid `config` settings: + + * **headers** - _object_ - These are the HTTP headers of the incoming request, which are used by individual parsers. + + * **autoDestroy** - _boolean_ - Whether this stream should automatically call .destroy() on itself after ending. (Default: false). + + * **highWaterMark** - _integer_ - highWaterMark to use for this Busboy instance (Default: WritableStream default). + + * **fileHwm** - _integer_ - highWaterMark to use for file streams (Default: ReadableStream default). + + * **defCharset** - _string_ - Default character set to use when one isn't defined (Default: 'utf8'). + + * **preservePath** - _boolean_ - If paths in the multipart 'filename' field shall be preserved. (Default: false). + + * **isPartAFile** - __function__ - Use this function to override the default file detection functionality. It has following parameters: + + * fieldName - __string__ The name of the field. + + * contentType - __string__ The content-type of the part, e.g. `text/plain`, `image/jpeg`, `application/octet-stream` + + * fileName - __string__ The name of a file supplied by the part. + + (Default: `(fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)`) + + * **limits** - _object_ - Various limits on incoming data. Valid properties are: + + * **fieldNameSize** - _integer_ - Max field name size (in bytes) (Default: 100 bytes). + + * **fieldSize** - _integer_ - Max field value size (in bytes) (Default: 1 MiB, which is 1024 x 1024 bytes). + + * **fields** - _integer_ - Max number of non-file fields (Default: Infinity). + + * **fileSize** - _integer_ - For multipart forms, the max file size (in bytes) (Default: Infinity). + + * **files** - _integer_ - For multipart forms, the max number of file fields (Default: Infinity). + + * **parts** - _integer_ - For multipart forms, the max number of parts (fields + files) (Default: Infinity). + + * **headerPairs** - _integer_ - For multipart forms, the max number of header key=>value pairs to parse **Default:** 2000 + + * **headerSize** - _integer_ - For multipart forms, the max size of a multipart header **Default:** 81920. + + * The constructor can throw errors: + + * **Busboy expected an options-Object.** - Busboy expected an Object as first parameters. + + * **Busboy expected an options-Object with headers-attribute.** - The first parameter is lacking of a headers-attribute. + + * **Limit $limit is not a valid number** - Busboy expected the desired limit to be of type number. Busboy throws this Error to prevent a potential security issue by falling silently back to the Busboy-defaults. Potential source for this Error can be the direct use of environment variables without transforming them to the type number. + + * **Unsupported Content-Type.** - The `Content-Type` isn't one Busboy can parse. + + * **Missing Content-Type-header.** - The provided headers don't include `Content-Type` at all. diff --git a/node_modules/@fastify/busboy/deps/dicer/LICENSE b/node_modules/@fastify/busboy/deps/dicer/LICENSE new file mode 100644 index 0000000..290762e --- /dev/null +++ b/node_modules/@fastify/busboy/deps/dicer/LICENSE @@ -0,0 +1,19 @@ +Copyright Brian White. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js b/node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js new file mode 100644 index 0000000..3c8c081 --- /dev/null +++ b/node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js @@ -0,0 +1,213 @@ +'use strict' + +const WritableStream = require('node:stream').Writable +const inherits = require('node:util').inherits + +const StreamSearch = require('../../streamsearch/sbmh') + +const PartStream = require('./PartStream') +const HeaderParser = require('./HeaderParser') + +const DASH = 45 +const B_ONEDASH = Buffer.from('-') +const B_CRLF = Buffer.from('\r\n') +const EMPTY_FN = function () {} + +function Dicer (cfg) { + if (!(this instanceof Dicer)) { return new Dicer(cfg) } + WritableStream.call(this, cfg) + + if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') } + + if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined } + + this._headerFirst = cfg.headerFirst + + this._dashes = 0 + this._parts = 0 + this._finished = false + this._realFinish = false + this._isPreamble = true + this._justMatched = false + this._firstWrite = true + this._inHeader = true + this._part = undefined + this._cb = undefined + this._ignoreData = false + this._partOpts = { highWaterMark: cfg.partHwm } + this._pause = false + + const self = this + this._hparser = new HeaderParser(cfg) + this._hparser.on('header', function (header) { + self._inHeader = false + self._part.emit('header', header) + }) +} +inherits(Dicer, WritableStream) + +Dicer.prototype.emit = function (ev) { + if (ev === 'finish' && !this._realFinish) { + if (!this._finished) { + const self = this + process.nextTick(function () { + self.emit('error', new Error('Unexpected end of multipart data')) + if (self._part && !self._ignoreData) { + const type = (self._isPreamble ? 'Preamble' : 'Part') + self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data')) + self._part.push(null) + process.nextTick(function () { + self._realFinish = true + self.emit('finish') + self._realFinish = false + }) + return + } + self._realFinish = true + self.emit('finish') + self._realFinish = false + }) + } + } else { WritableStream.prototype.emit.apply(this, arguments) } +} + +Dicer.prototype._write = function (data, encoding, cb) { + // ignore unexpected data (e.g. extra trailer data after finished) + if (!this._hparser && !this._bparser) { return cb() } + + if (this._headerFirst && this._isPreamble) { + if (!this._part) { + this._part = new PartStream(this._partOpts) + if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() } + } + const r = this._hparser.push(data) + if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() } + } + + // allows for "easier" testing + if (this._firstWrite) { + this._bparser.push(B_CRLF) + this._firstWrite = false + } + + this._bparser.push(data) + + if (this._pause) { this._cb = cb } else { cb() } +} + +Dicer.prototype.reset = function () { + this._part = undefined + this._bparser = undefined + this._hparser = undefined +} + +Dicer.prototype.setBoundary = function (boundary) { + const self = this + this._bparser = new StreamSearch('\r\n--' + boundary) + this._bparser.on('info', function (isMatch, data, start, end) { + self._oninfo(isMatch, data, start, end) + }) +} + +Dicer.prototype._ignore = function () { + if (this._part && !this._ignoreData) { + this._ignoreData = true + this._part.on('error', EMPTY_FN) + // we must perform some kind of read on the stream even though we are + // ignoring the data, otherwise node's Readable stream will not emit 'end' + // after pushing null to the stream + this._part.resume() + } +} + +Dicer.prototype._oninfo = function (isMatch, data, start, end) { + let buf; const self = this; let i = 0; let r; let shouldWriteMore = true + + if (!this._part && this._justMatched && data) { + while (this._dashes < 2 && (start + i) < end) { + if (data[start + i] === DASH) { + ++i + ++this._dashes + } else { + if (this._dashes) { buf = B_ONEDASH } + this._dashes = 0 + break + } + } + if (this._dashes === 2) { + if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) } + this.reset() + this._finished = true + // no more parts will be added + if (self._parts === 0) { + self._realFinish = true + self.emit('finish') + self._realFinish = false + } + } + if (this._dashes) { return } + } + if (this._justMatched) { this._justMatched = false } + if (!this._part) { + this._part = new PartStream(this._partOpts) + this._part._read = function (n) { + self._unpause() + } + if (this._isPreamble && this.listenerCount('preamble') !== 0) { + this.emit('preamble', this._part) + } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) { + this.emit('part', this._part) + } else { + this._ignore() + } + if (!this._isPreamble) { this._inHeader = true } + } + if (data && start < end && !this._ignoreData) { + if (this._isPreamble || !this._inHeader) { + if (buf) { shouldWriteMore = this._part.push(buf) } + shouldWriteMore = this._part.push(data.slice(start, end)) + if (!shouldWriteMore) { this._pause = true } + } else if (!this._isPreamble && this._inHeader) { + if (buf) { this._hparser.push(buf) } + r = this._hparser.push(data.slice(start, end)) + if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) } + } + } + if (isMatch) { + this._hparser.reset() + if (this._isPreamble) { this._isPreamble = false } else { + if (start !== end) { + ++this._parts + this._part.on('end', function () { + if (--self._parts === 0) { + if (self._finished) { + self._realFinish = true + self.emit('finish') + self._realFinish = false + } else { + self._unpause() + } + } + }) + } + } + this._part.push(null) + this._part = undefined + this._ignoreData = false + this._justMatched = true + this._dashes = 0 + } +} + +Dicer.prototype._unpause = function () { + if (!this._pause) { return } + + this._pause = false + if (this._cb) { + const cb = this._cb + this._cb = undefined + cb() + } +} + +module.exports = Dicer diff --git a/node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js b/node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js new file mode 100644 index 0000000..65f667b --- /dev/null +++ b/node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js @@ -0,0 +1,100 @@ +'use strict' + +const EventEmitter = require('node:events').EventEmitter +const inherits = require('node:util').inherits +const getLimit = require('../../../lib/utils/getLimit') + +const StreamSearch = require('../../streamsearch/sbmh') + +const B_DCRLF = Buffer.from('\r\n\r\n') +const RE_CRLF = /\r\n/g +const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex + +function HeaderParser (cfg) { + EventEmitter.call(this) + + cfg = cfg || {} + const self = this + this.nread = 0 + this.maxed = false + this.npairs = 0 + this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000) + this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024) + this.buffer = '' + this.header = {} + this.finished = false + this.ss = new StreamSearch(B_DCRLF) + this.ss.on('info', function (isMatch, data, start, end) { + if (data && !self.maxed) { + if (self.nread + end - start >= self.maxHeaderSize) { + end = self.maxHeaderSize - self.nread + start + self.nread = self.maxHeaderSize + self.maxed = true + } else { self.nread += (end - start) } + + self.buffer += data.toString('binary', start, end) + } + if (isMatch) { self._finish() } + }) +} +inherits(HeaderParser, EventEmitter) + +HeaderParser.prototype.push = function (data) { + const r = this.ss.push(data) + if (this.finished) { return r } +} + +HeaderParser.prototype.reset = function () { + this.finished = false + this.buffer = '' + this.header = {} + this.ss.reset() +} + +HeaderParser.prototype._finish = function () { + if (this.buffer) { this._parseHeader() } + this.ss.matches = this.ss.maxMatches + const header = this.header + this.header = {} + this.buffer = '' + this.finished = true + this.nread = this.npairs = 0 + this.maxed = false + this.emit('header', header) +} + +HeaderParser.prototype._parseHeader = function () { + if (this.npairs === this.maxHeaderPairs) { return } + + const lines = this.buffer.split(RE_CRLF) + const len = lines.length + let m, h + + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (lines[i].length === 0) { continue } + if (lines[i][0] === '\t' || lines[i][0] === ' ') { + // folded header content + // RFC2822 says to just remove the CRLF and not the whitespace following + // it, so we follow the RFC and include the leading whitespace ... + if (h) { + this.header[h][this.header[h].length - 1] += lines[i] + continue + } + } + + const posColon = lines[i].indexOf(':') + if ( + posColon === -1 || + posColon === 0 + ) { + return + } + m = RE_HDR.exec(lines[i]) + h = m[1].toLowerCase() + this.header[h] = this.header[h] || [] + this.header[h].push((m[2] || '')) + if (++this.npairs === this.maxHeaderPairs) { break } + } +} + +module.exports = HeaderParser diff --git a/node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js b/node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js new file mode 100644 index 0000000..c91da1c --- /dev/null +++ b/node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js @@ -0,0 +1,13 @@ +'use strict' + +const inherits = require('node:util').inherits +const ReadableStream = require('node:stream').Readable + +function PartStream (opts) { + ReadableStream.call(this, opts) +} +inherits(PartStream, ReadableStream) + +PartStream.prototype._read = function (n) {} + +module.exports = PartStream diff --git a/node_modules/@fastify/busboy/deps/dicer/lib/dicer.d.ts b/node_modules/@fastify/busboy/deps/dicer/lib/dicer.d.ts new file mode 100644 index 0000000..3c5b896 --- /dev/null +++ b/node_modules/@fastify/busboy/deps/dicer/lib/dicer.d.ts @@ -0,0 +1,164 @@ +// Type definitions for dicer 0.2 +// Project: https://github.com/mscdex/dicer +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 +/// + +import stream = require("stream"); + +// tslint:disable:unified-signatures + +/** + * A very fast streaming multipart parser for node.js. + * Dicer is a WritableStream + * + * Dicer (special) events: + * - on('finish', ()) - Emitted when all parts have been parsed and the Dicer instance has been ended. + * - on('part', (stream: PartStream)) - Emitted when a new part has been found. + * - on('preamble', (stream: PartStream)) - Emitted for preamble if you should happen to need it (can usually be ignored). + * - on('trailer', (data: Buffer)) - Emitted when trailing data was found after the terminating boundary (as with the preamble, this can usually be ignored too). + */ +export class Dicer extends stream.Writable { + /** + * Creates and returns a new Dicer instance with the following valid config settings: + * + * @param config The configuration to use + */ + constructor(config: Dicer.Config); + /** + * Sets the boundary to use for parsing and performs some initialization needed for parsing. + * You should only need to use this if you set headerFirst to true in the constructor and are parsing the boundary from the preamble header. + * + * @param boundary The boundary to use + */ + setBoundary(boundary: string): void; + addListener(event: "finish", listener: () => void): this; + addListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + addListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + addListener(event: "trailer", listener: (data: Buffer) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "part", listener: (stream: Dicer.PartStream) => void): this; + on(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + on(event: "trailer", listener: (data: Buffer) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "part", listener: (stream: Dicer.PartStream) => void): this; + once(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + once(event: "trailer", listener: (data: Buffer) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + prependListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + prependListener(event: "trailer", listener: (data: Buffer) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + prependOnceListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + prependOnceListener(event: "trailer", listener: (data: Buffer) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + removeListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + removeListener(event: "trailer", listener: (data: Buffer) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "pipe", listener: (src: stream.Readable) => void): this; + removeListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; +} + +declare namespace Dicer { + interface Config { + /** + * This is the boundary used to detect the beginning of a new part. + */ + boundary?: string | undefined; + /** + * If true, preamble header parsing will be performed first. + */ + headerFirst?: boolean | undefined; + /** + * The maximum number of header key=>value pairs to parse Default: 2000 (same as node's http). + */ + maxHeaderPairs?: number | undefined; + } + + /** + * PartStream is a _ReadableStream_ + * + * PartStream (special) events: + * - on('header', (header: object)) - An object containing the header for this particular part. Each property value is an array of one or more string values. + */ + interface PartStream extends stream.Readable { + addListener(event: "header", listener: (header: object) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: "header", listener: (header: object) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "header", listener: (header: object) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "header", listener: (header: object) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "header", listener: (header: object) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: "header", listener: (header: object) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: Buffer | string) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + } +} \ No newline at end of file diff --git a/node_modules/@fastify/busboy/deps/streamsearch/sbmh.js b/node_modules/@fastify/busboy/deps/streamsearch/sbmh.js new file mode 100644 index 0000000..ee04a12 --- /dev/null +++ b/node_modules/@fastify/busboy/deps/streamsearch/sbmh.js @@ -0,0 +1,230 @@ +'use strict' + +/** + * Copyright Brian White. All rights reserved. + * + * @see https://github.com/mscdex/streamsearch + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation + * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool + */ + +const { EventEmitter } = require('node:events') +const { inherits } = require('node:util') + +function SBMH (needle) { + if (typeof needle === 'string') { + needle = Buffer.from(needle) + } + + if (!Buffer.isBuffer(needle)) { + throw new TypeError('The needle has to be a String or a Buffer.') + } + + const needleLength = needle.length + const needleLastCharIndex = needleLength - 1 + + if (needleLength === 0) { + throw new Error('The needle cannot be an empty String/Buffer.') + } + + if (needleLength > 256) { + throw new Error('The needle cannot have a length bigger than 256.') + } + + this.maxMatches = Infinity + this.matches = 0 + + this._occ = new Uint8Array(256) + .fill(needleLength) // Initialize occurrence table. + this._lookbehind_size = 0 + this._needle = needle + this._bufpos = 0 + + this._lookbehind = Buffer.alloc(needleLastCharIndex) + + // Populate occurrence table with analysis of the needle, + // ignoring last letter. + for (var i = 0; i < needleLastCharIndex; ++i) { // eslint-disable-line no-var + this._occ[needle[i]] = needleLastCharIndex - i + } +} +inherits(SBMH, EventEmitter) + +SBMH.prototype.reset = function () { + this._lookbehind_size = 0 + this.matches = 0 + this._bufpos = 0 +} + +SBMH.prototype.push = function (chunk, pos) { + if (!Buffer.isBuffer(chunk)) { + chunk = Buffer.from(chunk, 'binary') + } + const chlen = chunk.length + this._bufpos = pos || 0 + let r + while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) } + return r +} + +SBMH.prototype._sbmh_feed = function (data) { + const len = data.length + const needle = this._needle + const needleLength = needle.length + const needleLastCharIndex = needleLength - 1 + const needleLastChar = needle[needleLastCharIndex] + + // Positive: points to a position in `data` + // pos == 3 points to data[3] + // Negative: points to a position in the lookbehind buffer + // pos == -2 points to lookbehind[lookbehind_size - 2] + let pos = -this._lookbehind_size + let ch + + if (pos < 0) { + // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool + // search with character lookup code that considers both the + // lookbehind buffer and the current round's haystack data. + // + // Loop until + // there is a match. + // or until + // we've moved past the position that requires the + // lookbehind buffer. In this case we switch to the + // optimized loop. + // or until + // the character to look at lies outside the haystack. + while (pos < 0 && pos <= len - needleLength) { + ch = data[pos + needleLastCharIndex] + + if ( + ch === needleLastChar && + this._sbmh_memcmp(data, pos, needleLastCharIndex) + ) { + this._lookbehind_size = 0 + ++this.matches + this.emit('info', true) + return (this._bufpos = pos + needleLength) + } + + pos += this._occ[ch] + } + + // No match. + + while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { + // There's too few data for Boyer-Moore-Horspool to run, + // so let's use a different algorithm to skip as much as + // we can. + // Forward pos until + // the trailing part of lookbehind + data + // looks like the beginning of the needle + // or until + // pos == 0 + ++pos + } + + if (pos >= 0) { + // Discard lookbehind buffer. + this.emit('info', false, this._lookbehind, 0, this._lookbehind_size) + this._lookbehind_size = 0 + } else { + // Cut off part of the lookbehind buffer that has + // been processed and append the entire haystack + // into it. + const bytesToCutOff = this._lookbehind_size + pos + if (bytesToCutOff > 0) { + // The cut off data is guaranteed not to contain the needle. + this.emit('info', false, this._lookbehind, 0, bytesToCutOff) + } + + this._lookbehind_size -= bytesToCutOff + this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, this._lookbehind_size) + + data.copy(this._lookbehind, this._lookbehind_size) + this._lookbehind_size += len + + this._bufpos = len + return len + } + } + + // Lookbehind buffer is now empty. We only need to check if the + // needle is in the haystack. + pos = data.indexOf(needle, pos + this._bufpos) + + if (pos !== -1) { + ++this.matches + if (pos === 0) { this.emit('info', true) } else { this.emit('info', true, data, this._bufpos, pos) } + return (this._bufpos = pos + needleLength) + } + + pos = len - needleLastCharIndex + if (pos < 0) { + pos = 0 + } + + // There was no match. If there's trailing haystack data that we cannot + // match yet using the Boyer-Moore-Horspool algorithm (because the trailing + // data is less than the needle size) then match using a modified + // algorithm that starts matching from the beginning instead of the end. + // Whatever trailing data is left after running this algorithm is added to + // the lookbehind buffer. + while ( + pos !== len && + ( + data[pos] !== needle[0] || + Buffer.compare( + data.subarray(pos + 1, len), + needle.subarray(1, len - pos) + ) !== 0 + ) + ) { + ++pos + } + + if (pos !== len) { + data.copy(this._lookbehind, 0, pos, len) + this._lookbehind_size = len - pos + } + + // Everything until pos is guaranteed not to contain needle data. + if (pos !== 0) { this.emit('info', false, data, this._bufpos, pos) } + + this._bufpos = len + return len +} + +SBMH.prototype._sbmh_lookup_char = function (data, pos) { + return pos < 0 + ? this._lookbehind[this._lookbehind_size + pos] + : data[pos] +} + +SBMH.prototype._sbmh_memcmp = function (data, pos, len) { + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false } + } + return true +} + +module.exports = SBMH diff --git a/node_modules/@fastify/busboy/lib/main.d.ts b/node_modules/@fastify/busboy/lib/main.d.ts new file mode 100644 index 0000000..1948334 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/main.d.ts @@ -0,0 +1,196 @@ +// Definitions by: Jacob Baskin +// BendingBender +// Igor Savin + +/// + +import * as http from 'node:http'; +import { Readable, Writable } from 'node:stream'; +export { Dicer } from "../deps/dicer/lib/dicer"; + +export const Busboy: BusboyConstructor; +export default Busboy; + +export interface BusboyConfig { + /** + * These are the HTTP headers of the incoming request, which are used by individual parsers. + */ + headers: BusboyHeaders; + /** + * `highWaterMark` to use for this Busboy instance. + * @default WritableStream default. + */ + highWaterMark?: number | undefined; + /** + * highWaterMark to use for file streams. + * @default ReadableStream default. + */ + fileHwm?: number | undefined; + /** + * Default character set to use when one isn't defined. + * @default 'utf8' + */ + defCharset?: string | undefined; + /** + * Detect if a Part is a file. + * + * By default a file is detected if contentType + * is application/octet-stream or fileName is not + * undefined. + * + * Modify this to handle e.g. Blobs. + */ + isPartAFile?: (fieldName: string | undefined, contentType: string | undefined, fileName: string | undefined) => boolean; + /** + * If paths in the multipart 'filename' field shall be preserved. + * @default false + */ + preservePath?: boolean | undefined; + /** + * Various limits on incoming data. + */ + limits?: + | { + /** + * Max field name size (in bytes) + * @default 100 bytes + */ + fieldNameSize?: number | undefined; + /** + * Max field value size (in bytes) + * @default 1MB + */ + fieldSize?: number | undefined; + /** + * Max number of non-file fields + * @default Infinity + */ + fields?: number | undefined; + /** + * For multipart forms, the max file size (in bytes) + * @default Infinity + */ + fileSize?: number | undefined; + /** + * For multipart forms, the max number of file fields + * @default Infinity + */ + files?: number | undefined; + /** + * For multipart forms, the max number of parts (fields + files) + * @default Infinity + */ + parts?: number | undefined; + /** + * For multipart forms, the max number of header key=>value pairs to parse + * @default 2000 + */ + headerPairs?: number | undefined; + + /** + * For multipart forms, the max size of a header part + * @default 81920 + */ + headerSize?: number | undefined; + } + | undefined; +} + +export type BusboyHeaders = { 'content-type': string } & http.IncomingHttpHeaders; + +export interface BusboyFileStream extends + Readable { + + truncated: boolean; + + /** + * The number of bytes that have been read so far. + */ + bytesRead: number; +} + +export interface Busboy extends Writable { + addListener(event: Event, listener: BusboyEvents[Event]): this; + + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + on(event: Event, listener: BusboyEvents[Event]): this; + + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: Event, listener: BusboyEvents[Event]): this; + + once(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: Event, listener: BusboyEvents[Event]): this; + + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + off(event: Event, listener: BusboyEvents[Event]): this; + + off(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: Event, listener: BusboyEvents[Event]): this; + + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: Event, listener: BusboyEvents[Event]): this; + + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; +} + +export interface BusboyEvents { + /** + * Emitted for each new file form field found. + * + * * Note: if you listen for this event, you should always handle the `stream` no matter if you care about the + * file contents or not (e.g. you can simply just do `stream.resume();` if you want to discard the contents), + * otherwise the 'finish' event will never fire on the Busboy instance. However, if you don't care about **any** + * incoming files, you can simply not listen for the 'file' event at all and any/all files will be automatically + * and safely discarded (these discarded files do still count towards `files` and `parts` limits). + * * If a configured file size limit was reached, `stream` will both have a boolean property `truncated` + * (best checked at the end of the stream) and emit a 'limit' event to notify you when this happens. + * + * @param listener.transferEncoding Contains the 'Content-Transfer-Encoding' value for the file stream. + * @param listener.mimeType Contains the 'Content-Type' value for the file stream. + */ + file: ( + fieldname: string, + stream: BusboyFileStream, + filename: string, + transferEncoding: string, + mimeType: string, + ) => void; + /** + * Emitted for each new non-file field found. + */ + field: ( + fieldname: string, + value: string, + fieldnameTruncated: boolean, + valueTruncated: boolean, + transferEncoding: string, + mimeType: string, + ) => void; + finish: () => void; + /** + * Emitted when specified `parts` limit has been reached. No more 'file' or 'field' events will be emitted. + */ + partsLimit: () => void; + /** + * Emitted when specified `files` limit has been reached. No more 'file' events will be emitted. + */ + filesLimit: () => void; + /** + * Emitted when specified `fields` limit has been reached. No more 'field' events will be emitted. + */ + fieldsLimit: () => void; + error: (error: unknown) => void; +} + +export interface BusboyConstructor { + (options: BusboyConfig): Busboy; + + new(options: BusboyConfig): Busboy; +} + diff --git a/node_modules/@fastify/busboy/lib/main.js b/node_modules/@fastify/busboy/lib/main.js new file mode 100644 index 0000000..8794beb --- /dev/null +++ b/node_modules/@fastify/busboy/lib/main.js @@ -0,0 +1,85 @@ +'use strict' + +const WritableStream = require('node:stream').Writable +const { inherits } = require('node:util') +const Dicer = require('../deps/dicer/lib/Dicer') + +const MultipartParser = require('./types/multipart') +const UrlencodedParser = require('./types/urlencoded') +const parseParams = require('./utils/parseParams') + +function Busboy (opts) { + if (!(this instanceof Busboy)) { return new Busboy(opts) } + + if (typeof opts !== 'object') { + throw new TypeError('Busboy expected an options-Object.') + } + if (typeof opts.headers !== 'object') { + throw new TypeError('Busboy expected an options-Object with headers-attribute.') + } + if (typeof opts.headers['content-type'] !== 'string') { + throw new TypeError('Missing Content-Type-header.') + } + + const { + headers, + ...streamOptions + } = opts + + this.opts = { + autoDestroy: false, + ...streamOptions + } + WritableStream.call(this, this.opts) + + this._done = false + this._parser = this.getParserByHeaders(headers) + this._finished = false +} +inherits(Busboy, WritableStream) + +Busboy.prototype.emit = function (ev) { + if (ev === 'finish') { + if (!this._done) { + this._parser?.end() + return + } else if (this._finished) { + return + } + this._finished = true + } + WritableStream.prototype.emit.apply(this, arguments) +} + +Busboy.prototype.getParserByHeaders = function (headers) { + const parsed = parseParams(headers['content-type']) + + const cfg = { + defCharset: this.opts.defCharset, + fileHwm: this.opts.fileHwm, + headers, + highWaterMark: this.opts.highWaterMark, + isPartAFile: this.opts.isPartAFile, + limits: this.opts.limits, + parsedConType: parsed, + preservePath: this.opts.preservePath + } + + if (MultipartParser.detect.test(parsed[0])) { + return new MultipartParser(this, cfg) + } + if (UrlencodedParser.detect.test(parsed[0])) { + return new UrlencodedParser(this, cfg) + } + throw new Error('Unsupported Content-Type.') +} + +Busboy.prototype._write = function (chunk, encoding, cb) { + this._parser.write(chunk, cb) +} + +module.exports = Busboy +module.exports.default = Busboy +module.exports.Busboy = Busboy + +module.exports.Dicer = Dicer diff --git a/node_modules/@fastify/busboy/lib/types/multipart.js b/node_modules/@fastify/busboy/lib/types/multipart.js new file mode 100644 index 0000000..d691eca --- /dev/null +++ b/node_modules/@fastify/busboy/lib/types/multipart.js @@ -0,0 +1,306 @@ +'use strict' + +// TODO: +// * support 1 nested multipart level +// (see second multipart example here: +// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data) +// * support limits.fieldNameSize +// -- this will require modifications to utils.parseParams + +const { Readable } = require('node:stream') +const { inherits } = require('node:util') + +const Dicer = require('../../deps/dicer/lib/Dicer') + +const parseParams = require('../utils/parseParams') +const decodeText = require('../utils/decodeText') +const basename = require('../utils/basename') +const getLimit = require('../utils/getLimit') + +const RE_BOUNDARY = /^boundary$/i +const RE_FIELD = /^form-data$/i +const RE_CHARSET = /^charset$/i +const RE_FILENAME = /^filename$/i +const RE_NAME = /^name$/i + +Multipart.detect = /^multipart\/form-data/i +function Multipart (boy, cfg) { + let i + let len + const self = this + let boundary + const limits = cfg.limits + const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)) + const parsedConType = cfg.parsedConType || [] + const defCharset = cfg.defCharset || 'utf8' + const preservePath = cfg.preservePath + const fileOpts = { highWaterMark: cfg.fileHwm } + + for (i = 0, len = parsedConType.length; i < len; ++i) { + if (Array.isArray(parsedConType[i]) && + RE_BOUNDARY.test(parsedConType[i][0])) { + boundary = parsedConType[i][1] + break + } + } + + function checkFinished () { + if (nends === 0 && finished && !boy._done) { + finished = false + self.end() + } + } + + if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') } + + const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + const fileSizeLimit = getLimit(limits, 'fileSize', Infinity) + const filesLimit = getLimit(limits, 'files', Infinity) + const fieldsLimit = getLimit(limits, 'fields', Infinity) + const partsLimit = getLimit(limits, 'parts', Infinity) + const headerPairsLimit = getLimit(limits, 'headerPairs', 2000) + const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024) + + let nfiles = 0 + let nfields = 0 + let nends = 0 + let curFile + let curField + let finished = false + + this._needDrain = false + this._pause = false + this._cb = undefined + this._nparts = 0 + this._boy = boy + + const parserCfg = { + boundary, + maxHeaderPairs: headerPairsLimit, + maxHeaderSize: headerSizeLimit, + partHwm: fileOpts.highWaterMark, + highWaterMark: cfg.highWaterMark + } + + this.parser = new Dicer(parserCfg) + this.parser.on('drain', function () { + self._needDrain = false + if (self._cb && !self._pause) { + const cb = self._cb + self._cb = undefined + cb() + } + }).on('part', function onPart (part) { + if (++self._nparts > partsLimit) { + self.parser.removeListener('part', onPart) + self.parser.on('part', skipPart) + boy.hitPartsLimit = true + boy.emit('partsLimit') + return skipPart(part) + } + + // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let + // us emit 'end' early since we know the part has ended if we are already + // seeing the next part + if (curField) { + const field = curField + field.emit('end') + field.removeAllListeners('end') + } + + part.on('header', function (header) { + let contype + let fieldname + let parsed + let charset + let encoding + let filename + let nsize = 0 + + if (header['content-type']) { + parsed = parseParams(header['content-type'][0]) + if (parsed[0]) { + contype = parsed[0].toLowerCase() + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_CHARSET.test(parsed[i][0])) { + charset = parsed[i][1].toLowerCase() + break + } + } + } + } + + if (contype === undefined) { contype = 'text/plain' } + if (charset === undefined) { charset = defCharset } + + if (header['content-disposition']) { + parsed = parseParams(header['content-disposition'][0]) + if (!RE_FIELD.test(parsed[0])) { return skipPart(part) } + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_NAME.test(parsed[i][0])) { + fieldname = parsed[i][1] + } else if (RE_FILENAME.test(parsed[i][0])) { + filename = parsed[i][1] + if (!preservePath) { filename = basename(filename) } + } + } + } else { return skipPart(part) } + + if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' } + + let onData, + onEnd + + if (isPartAFile(fieldname, contype, filename)) { + // file/binary field + if (nfiles === filesLimit) { + if (!boy.hitFilesLimit) { + boy.hitFilesLimit = true + boy.emit('filesLimit') + } + return skipPart(part) + } + + ++nfiles + + if (boy.listenerCount('file') === 0) { + self.parser._ignore() + return + } + + ++nends + const file = new FileStream(fileOpts) + curFile = file + file.on('end', function () { + --nends + self._pause = false + checkFinished() + if (self._cb && !self._needDrain) { + const cb = self._cb + self._cb = undefined + cb() + } + }) + file._read = function (n) { + if (!self._pause) { return } + self._pause = false + if (self._cb && !self._needDrain) { + const cb = self._cb + self._cb = undefined + cb() + } + } + boy.emit('file', fieldname, file, filename, encoding, contype) + + onData = function (data) { + if ((nsize += data.length) > fileSizeLimit) { + const extralen = fileSizeLimit - nsize + data.length + if (extralen > 0) { file.push(data.slice(0, extralen)) } + file.truncated = true + file.bytesRead = fileSizeLimit + part.removeAllListeners('data') + file.emit('limit') + return + } else if (!file.push(data)) { self._pause = true } + + file.bytesRead = nsize + } + + onEnd = function () { + curFile = undefined + file.push(null) + } + } else { + // non-file field + if (nfields === fieldsLimit) { + if (!boy.hitFieldsLimit) { + boy.hitFieldsLimit = true + boy.emit('fieldsLimit') + } + return skipPart(part) + } + + ++nfields + ++nends + let buffer = '' + let truncated = false + curField = part + + onData = function (data) { + if ((nsize += data.length) > fieldSizeLimit) { + const extralen = (fieldSizeLimit - (nsize - data.length)) + buffer += data.toString('binary', 0, extralen) + truncated = true + part.removeAllListeners('data') + } else { buffer += data.toString('binary') } + } + + onEnd = function () { + curField = undefined + if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) } + boy.emit('field', fieldname, buffer, false, truncated, encoding, contype) + --nends + checkFinished() + } + } + + /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become + broken. Streams2/streams3 is a huge black box of confusion, but + somehow overriding the sync state seems to fix things again (and still + seems to work for previous node versions). + */ + part._readableState.sync = false + + part.on('data', onData) + part.on('end', onEnd) + }).on('error', function (err) { + if (curFile) { curFile.emit('error', err) } + }) + }).on('error', function (err) { + boy.emit('error', err) + }).on('finish', function () { + finished = true + checkFinished() + }) +} + +Multipart.prototype.write = function (chunk, cb) { + const r = this.parser.write(chunk) + if (r && !this._pause) { + cb() + } else { + this._needDrain = !r + this._cb = cb + } +} + +Multipart.prototype.end = function () { + const self = this + + if (self.parser.writable) { + self.parser.end() + } else if (!self._boy._done) { + process.nextTick(function () { + self._boy._done = true + self._boy.emit('finish') + }) + } +} + +function skipPart (part) { + part.resume() +} + +function FileStream (opts) { + Readable.call(this, opts) + + this.bytesRead = 0 + + this.truncated = false +} + +inherits(FileStream, Readable) + +FileStream.prototype._read = function (n) {} + +module.exports = Multipart diff --git a/node_modules/@fastify/busboy/lib/types/urlencoded.js b/node_modules/@fastify/busboy/lib/types/urlencoded.js new file mode 100644 index 0000000..6f5f784 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/types/urlencoded.js @@ -0,0 +1,190 @@ +'use strict' + +const Decoder = require('../utils/Decoder') +const decodeText = require('../utils/decodeText') +const getLimit = require('../utils/getLimit') + +const RE_CHARSET = /^charset$/i + +UrlEncoded.detect = /^application\/x-www-form-urlencoded/i +function UrlEncoded (boy, cfg) { + const limits = cfg.limits + const parsedConType = cfg.parsedConType + this.boy = boy + + this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100) + this.fieldsLimit = getLimit(limits, 'fields', Infinity) + + let charset + for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var + if (Array.isArray(parsedConType[i]) && + RE_CHARSET.test(parsedConType[i][0])) { + charset = parsedConType[i][1].toLowerCase() + break + } + } + + if (charset === undefined) { charset = cfg.defCharset || 'utf8' } + + this.decoder = new Decoder() + this.charset = charset + this._fields = 0 + this._state = 'key' + this._checkingBytes = true + this._bytesKey = 0 + this._bytesVal = 0 + this._key = '' + this._val = '' + this._keyTrunc = false + this._valTrunc = false + this._hitLimit = false +} + +UrlEncoded.prototype.write = function (data, cb) { + if (this._fields === this.fieldsLimit) { + if (!this.boy.hitFieldsLimit) { + this.boy.hitFieldsLimit = true + this.boy.emit('fieldsLimit') + } + return cb() + } + + let idxeq; let idxamp; let i; let p = 0; const len = data.length + + while (p < len) { + if (this._state === 'key') { + idxeq = idxamp = undefined + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p } + if (data[i] === 0x3D/* = */) { + idxeq = i + break + } else if (data[i] === 0x26/* & */) { + idxamp = i + break + } + if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) { + this._hitLimit = true + break + } else if (this._checkingBytes) { ++this._bytesKey } + } + + if (idxeq !== undefined) { + // key with assignment + if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) } + this._state = 'val' + + this._hitLimit = false + this._checkingBytes = true + this._val = '' + this._bytesVal = 0 + this._valTrunc = false + this.decoder.reset() + + p = idxeq + 1 + } else if (idxamp !== undefined) { + // key with no assignment + ++this._fields + let key; const keyTrunc = this._keyTrunc + if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key } + + this._hitLimit = false + this._checkingBytes = true + this._key = '' + this._bytesKey = 0 + this._keyTrunc = false + this.decoder.reset() + + if (key.length) { + this.boy.emit('field', decodeText(key, 'binary', this.charset), + '', + keyTrunc, + false) + } + + p = idxamp + 1 + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) } + p = i + if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false + this._keyTrunc = true + } + } else { + if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) } + p = len + } + } else { + idxamp = undefined + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p } + if (data[i] === 0x26/* & */) { + idxamp = i + break + } + if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) { + this._hitLimit = true + break + } else if (this._checkingBytes) { ++this._bytesVal } + } + + if (idxamp !== undefined) { + ++this._fields + if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) } + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc) + this._state = 'key' + + this._hitLimit = false + this._checkingBytes = true + this._key = '' + this._bytesKey = 0 + this._keyTrunc = false + this.decoder.reset() + + p = idxamp + 1 + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) } + p = i + if ((this._val === '' && this.fieldSizeLimit === 0) || + (this._bytesVal = this._val.length) === this.fieldSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false + this._valTrunc = true + } + } else { + if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) } + p = len + } + } + } + cb() +} + +UrlEncoded.prototype.end = function () { + if (this.boy._done) { return } + + if (this._state === 'key' && this._key.length > 0) { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + '', + this._keyTrunc, + false) + } else if (this._state === 'val') { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc) + } + this.boy._done = true + this.boy.emit('finish') +} + +module.exports = UrlEncoded diff --git a/node_modules/@fastify/busboy/lib/utils/Decoder.js b/node_modules/@fastify/busboy/lib/utils/Decoder.js new file mode 100644 index 0000000..7917678 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/utils/Decoder.js @@ -0,0 +1,54 @@ +'use strict' + +const RE_PLUS = /\+/g + +const HEX = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +] + +function Decoder () { + this.buffer = undefined +} +Decoder.prototype.write = function (str) { + // Replace '+' with ' ' before decoding + str = str.replace(RE_PLUS, ' ') + let res = '' + let i = 0; let p = 0; const len = str.length + for (; i < len; ++i) { + if (this.buffer !== undefined) { + if (!HEX[str.charCodeAt(i)]) { + res += '%' + this.buffer + this.buffer = undefined + --i // retry character + } else { + this.buffer += str[i] + ++p + if (this.buffer.length === 2) { + res += String.fromCharCode(parseInt(this.buffer, 16)) + this.buffer = undefined + } + } + } else if (str[i] === '%') { + if (i > p) { + res += str.substring(p, i) + p = i + } + this.buffer = '' + ++p + } + } + if (p < len && this.buffer === undefined) { res += str.substring(p) } + return res +} +Decoder.prototype.reset = function () { + this.buffer = undefined +} + +module.exports = Decoder diff --git a/node_modules/@fastify/busboy/lib/utils/basename.js b/node_modules/@fastify/busboy/lib/utils/basename.js new file mode 100644 index 0000000..db58819 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/utils/basename.js @@ -0,0 +1,14 @@ +'use strict' + +module.exports = function basename (path) { + if (typeof path !== 'string') { return '' } + for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var + switch (path.charCodeAt(i)) { + case 0x2F: // '/' + case 0x5C: // '\' + path = path.slice(i + 1) + return (path === '..' || path === '.' ? '' : path) + } + } + return (path === '..' || path === '.' ? '' : path) +} diff --git a/node_modules/@fastify/busboy/lib/utils/decodeText.js b/node_modules/@fastify/busboy/lib/utils/decodeText.js new file mode 100644 index 0000000..eac7d35 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/utils/decodeText.js @@ -0,0 +1,114 @@ +'use strict' + +// Node has always utf-8 +const utf8Decoder = new TextDecoder('utf-8') +const textDecoders = new Map([ + ['utf-8', utf8Decoder], + ['utf8', utf8Decoder] +]) + +function getDecoder (charset) { + let lc + while (true) { + switch (charset) { + case 'utf-8': + case 'utf8': + return decoders.utf8 + case 'latin1': + case 'ascii': // TODO: Make these a separate, strict decoder? + case 'us-ascii': + case 'iso-8859-1': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'windows-1252': + case 'iso_8859-1:1987': + case 'cp1252': + case 'x-cp1252': + return decoders.latin1 + case 'utf16le': + case 'utf-16le': + case 'ucs2': + case 'ucs-2': + return decoders.utf16le + case 'base64': + return decoders.base64 + default: + if (lc === undefined) { + lc = true + charset = charset.toLowerCase() + continue + } + return decoders.other.bind(charset) + } + } +} + +const decoders = { + utf8: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.utf8Slice(0, data.length) + }, + + latin1: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + return data + } + return data.latin1Slice(0, data.length) + }, + + utf16le: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.ucs2Slice(0, data.length) + }, + + base64: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.base64Slice(0, data.length) + }, + + other: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + + if (textDecoders.has(this.toString())) { + try { + return textDecoders.get(this).decode(data) + } catch {} + } + return typeof data === 'string' + ? data + : data.toString() + } +} + +function decodeText (text, sourceEncoding, destEncoding) { + if (text) { + return getDecoder(destEncoding)(text, sourceEncoding) + } + return text +} + +module.exports = decodeText diff --git a/node_modules/@fastify/busboy/lib/utils/getLimit.js b/node_modules/@fastify/busboy/lib/utils/getLimit.js new file mode 100644 index 0000000..cb64fd6 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/utils/getLimit.js @@ -0,0 +1,16 @@ +'use strict' + +module.exports = function getLimit (limits, name, defaultLimit) { + if ( + !limits || + limits[name] === undefined || + limits[name] === null + ) { return defaultLimit } + + if ( + typeof limits[name] !== 'number' || + isNaN(limits[name]) + ) { throw new TypeError('Limit ' + name + ' is not a valid number') } + + return limits[name] +} diff --git a/node_modules/@fastify/busboy/lib/utils/parseParams.js b/node_modules/@fastify/busboy/lib/utils/parseParams.js new file mode 100644 index 0000000..d867f4d --- /dev/null +++ b/node_modules/@fastify/busboy/lib/utils/parseParams.js @@ -0,0 +1,201 @@ +/* eslint-disable object-property-newline */ +'use strict' + +const decodeText = require('./decodeText') + +const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g + +const EncodedLookup = { + '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04', + '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09', + '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c', + '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e', + '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12', + '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17', + '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b', + '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d', + '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20', + '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25', + '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a', + '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c', + '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f', + '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33', + '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38', + '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b', + '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e', + '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41', + '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46', + '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a', + '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d', + '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f', + '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54', + '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59', + '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c', + '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e', + '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62', + '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67', + '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b', + '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d', + '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70', + '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75', + '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a', + '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c', + '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f', + '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83', + '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88', + '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b', + '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e', + '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91', + '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96', + '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a', + '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d', + '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f', + '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2', + '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4', + '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7', + '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9', + '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab', + '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac', + '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad', + '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae', + '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0', + '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2', + '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5', + '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7', + '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba', + '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb', + '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc', + '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd', + '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf', + '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0', + '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3', + '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5', + '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8', + '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca', + '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb', + '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc', + '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce', + '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf', + '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1', + '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3', + '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6', + '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8', + '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda', + '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb', + '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd', + '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde', + '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf', + '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1', + '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4', + '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6', + '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9', + '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea', + '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec', + '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed', + '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee', + '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef', + '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2', + '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4', + '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7', + '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9', + '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb', + '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc', + '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd', + '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe', + '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff' +} + +function encodedReplacer (match) { + return EncodedLookup[match] +} + +const STATE_KEY = 0 +const STATE_VALUE = 1 +const STATE_CHARSET = 2 +const STATE_LANG = 3 + +function parseParams (str) { + const res = [] + let state = STATE_KEY + let charset = '' + let inquote = false + let escaping = false + let p = 0 + let tmp = '' + const len = str.length + + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + const char = str[i] + if (char === '\\' && inquote) { + if (escaping) { escaping = false } else { + escaping = true + continue + } + } else if (char === '"') { + if (!escaping) { + if (inquote) { + inquote = false + state = STATE_KEY + // Skip any remaining characters until we hit a semicolon or end of string + // This ensures we don't include characters after the closing quote + while (i + 1 < len && str[i + 1] !== ';') { + ++i + } + } else { inquote = true } + continue + } else { escaping = false } + } else { + if (escaping && inquote) { tmp += '\\' } + escaping = false + if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { + if (state === STATE_CHARSET) { + state = STATE_LANG + charset = tmp.substring(1) + } else { state = STATE_VALUE } + tmp = '' + continue + } else if (state === STATE_KEY && + (char === '*' || char === '=') && + res.length) { + state = char === '*' + ? STATE_CHARSET + : STATE_VALUE + res[p] = [tmp, undefined] + tmp = '' + continue + } else if (!inquote && char === ';') { + state = STATE_KEY + if (charset) { + if (tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } + charset = '' + } else if (tmp.length) { + tmp = decodeText(tmp, 'binary', 'utf8') + } + if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp } + tmp = '' + ++p + continue + } else if (!inquote && (char === ' ' || char === '\t')) { continue } + } + tmp += char + } + if (charset && tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } else if (tmp) { + tmp = decodeText(tmp, 'binary', 'utf8') + } + + if (res[p] === undefined) { + if (tmp) { res[p] = tmp } + } else { res[p][1] = tmp } + + return res +} + +module.exports = parseParams diff --git a/node_modules/@fastify/busboy/package.json b/node_modules/@fastify/busboy/package.json new file mode 100644 index 0000000..af3cfda --- /dev/null +++ b/node_modules/@fastify/busboy/package.json @@ -0,0 +1,81 @@ +{ + "name": "@fastify/busboy", + "version": "3.2.0", + "private": false, + "author": "Brian White ", + "contributors": [ + { + "name": "Igor Savin", + "email": "kibertoad@gmail.com", + "url": "https://github.com/kibertoad" + }, + { + "name": "Aras Abbasi", + "email": "aras.abbasi@gmail.com", + "url": "https://github.com/uzlopak" + } + ], + "description": "A streaming parser for HTML form data for node.js", + "main": "lib/main", + "type": "commonjs", + "types": "lib/main.d.ts", + "scripts": { + "bench:busboy": "cd benchmarks && npm install && npm run benchmark-fastify", + "bench:dicer": "node bench/dicer/dicer-bench-multipart-parser.js", + "coveralls": "nyc report --reporter=lcov", + "lint": "npm run lint:standard", + "lint:fix": "standard --fix", + "lint:standard": "standard --verbose | snazzy", + "test:unit": "c8 --statements 98 --branches 97 --functions 96 --lines 98 node --test", + "test:types": "tsd", + "test": "npm run test:unit && npm run test:types" + }, + "devDependencies": { + "@types/node": "^24.0.8", + "busboy": "^1.6.0", + "c8": "^10.1.2", + "photofinish": "^1.8.0", + "snazzy": "^9.0.0", + "standard": "^17.1.0", + "tinybench": "^4.0.1", + "tsd": "^0.32.0", + "tslib": "^2.8.1", + "typescript": "~5.9.2" + }, + "keywords": [ + "uploads", + "forms", + "multipart", + "form-data" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/fastify/busboy.git" + }, + "bugs": { + "url": "https://github.com/fastify/busboy/issues" + }, + "homepage": "https://github.com/fastify/busboy#readme", + "tsd": { + "directory": "test-types" + }, + "standard": { + "globals": [ + "describe", + "it" + ], + "ignore": [ + "bench" + ] + }, + "files": [ + "README.md", + "LICENSE", + "lib/*", + "deps/encoding/*", + "deps/dicer/lib", + "deps/streamsearch/", + "deps/dicer/LICENSE" + ] +} diff --git a/node_modules/@firebase/app-check-interop-types/README.md b/node_modules/@firebase/app-check-interop-types/README.md new file mode 100644 index 0000000..c54a183 --- /dev/null +++ b/node_modules/@firebase/app-check-interop-types/README.md @@ -0,0 +1,3 @@ +# @firebase/app-check-interop-types + +**This package is not intended for direct usage, and should only be used via the officially supported [firebase](https://www.npmjs.com/package/firebase) package.** diff --git a/node_modules/@firebase/app-check-interop-types/index.d.ts b/node_modules/@firebase/app-check-interop-types/index.d.ts new file mode 100644 index 0000000..cc16c5e --- /dev/null +++ b/node_modules/@firebase/app-check-interop-types/index.d.ts @@ -0,0 +1,51 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export interface FirebaseAppCheckInternal { + // Get the current AttestationToken. Attaches to the most recent in-flight request if one + // is present. Returns null if no token is present and no token requests are in-flight. + getToken(forceRefresh?: boolean): Promise; + + // Always returns a fresh limited-use token suitable for Replay Protection. + // The returned token must be used and consumed as soon as possible. + getLimitedUseToken(): Promise; + + // Registers a listener to changes in the token state. There can be more than one listener + // registered at the same time for one or more FirebaseAppAttestation instances. The + // listeners call back on the UI thread whenever the current token associated with this + // FirebaseAppAttestation changes. + addTokenListener(listener: AppCheckTokenListener): void; + + // Unregisters a listener to changes in the token state. + removeTokenListener(listener: AppCheckTokenListener): void; +} + +type AppCheckTokenListener = (token: AppCheckTokenResult) => void; + +// If the error field is defined, the token field will be populated with a dummy token +interface AppCheckTokenResult { + readonly token: string; + readonly error?: Error; +} + +export type AppCheckInternalComponentName = 'app-check-internal'; + +declare module '@firebase/component' { + interface NameServiceMapping { + 'app-check-internal': FirebaseAppCheckInternal; + } +} diff --git a/node_modules/@firebase/app-check-interop-types/package.json b/node_modules/@firebase/app-check-interop-types/package.json new file mode 100644 index 0000000..c7e4561 --- /dev/null +++ b/node_modules/@firebase/app-check-interop-types/package.json @@ -0,0 +1,25 @@ +{ + "name": "@firebase/app-check-interop-types", + "version": "0.3.3", + "description": "@firebase/app-check-interop-types Types", + "author": "Firebase (https://firebase.google.com/)", + "license": "Apache-2.0", + "scripts": { + "test": "tsc", + "test:ci": "node ../../scripts/run_tests_in_ci.js" + }, + "files": [ + "index.d.ts" + ], + "repository": { + "directory": "packages/app-check-interop-types", + "type": "git", + "url": "git+https://github.com/firebase/firebase-js-sdk.git" + }, + "bugs": { + "url": "https://github.com/firebase/firebase-js-sdk/issues" + }, + "devDependencies": { + "typescript": "5.5.4" + } +} diff --git a/node_modules/@firebase/app-types/README.md b/node_modules/@firebase/app-types/README.md new file mode 100644 index 0000000..931932c --- /dev/null +++ b/node_modules/@firebase/app-types/README.md @@ -0,0 +1,3 @@ +# @firebase/app-types + +**This package is not intended for direct usage, and should only be used via the officially supported [firebase](https://www.npmjs.com/package/firebase) package.** diff --git a/node_modules/@firebase/app-types/index.d.ts b/node_modules/@firebase/app-types/index.d.ts new file mode 100644 index 0000000..72b8fa6 --- /dev/null +++ b/node_modules/@firebase/app-types/index.d.ts @@ -0,0 +1,129 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LogCallback, LogLevelString, LogOptions } from '@firebase/logger'; + +export type FirebaseOptions = { + apiKey?: string; + authDomain?: string; + databaseURL?: string; + projectId?: string; + storageBucket?: string; + messagingSenderId?: string; + appId?: string; + measurementId?: string; +}; + +export interface FirebaseAppConfig { + name?: string; + automaticDataCollectionEnabled?: boolean; +} + +export class FirebaseApp { + /** + * The (read-only) name (identifier) for this App. '[DEFAULT]' is the default + * App. + */ + name: string; + + /** + * The (read-only) configuration options from the app initialization. + */ + options: FirebaseOptions; + + /** + * The settable config flag for GDPR opt-in/opt-out + */ + automaticDataCollectionEnabled: boolean; + + /** + * Make the given App unusable and free resources. + */ + delete(): Promise; +} + +export interface FirebaseNamespace { + /** + * Create (and initialize) a FirebaseApp. + * + * @param options Options to configure the services used in the App. + * @param config The optional config for your firebase app + */ + initializeApp( + options: FirebaseOptions, + config?: FirebaseAppConfig + ): FirebaseApp; + /** + * Create (and initialize) a FirebaseApp. + * + * @param options Options to configure the services used in the App. + * @param name The optional name of the app to initialize ('[DEFAULT]' if + * omitted) + */ + initializeApp(options: FirebaseOptions, name?: string): FirebaseApp; + + app: { + /** + * Retrieve an instance of a FirebaseApp. + * + * Usage: firebase.app() + * + * @param name The optional name of the app to return ('[DEFAULT]' if omitted) + */ + (name?: string): FirebaseApp; + + /** + * For testing FirebaseApp instances: + * app() instanceof firebase.app.App + * + * DO NOT call this constuctor directly (use firebase.app() instead). + */ + App: typeof FirebaseApp; + }; + + /** + * A (read-only) array of all the initialized Apps. + */ + apps: FirebaseApp[]; + + /** + * Registers a library's name and version for platform logging purposes. + * @param library Name of 1p or 3p library (e.g. firestore, angularfire) + * @param version Current version of that library. + */ + registerVersion(library: string, version: string, variant?: string): void; + + // Sets log level for all Firebase components. + setLogLevel(logLevel: LogLevelString): void; + + // Sets log handler for all Firebase components. + onLog(logCallback: LogCallback, options?: LogOptions): void; + + // The current SDK version. + SDK_VERSION: string; +} + +export interface VersionService { + library: string; + version: string; +} + +declare module '@firebase/component' { + interface NameServiceMapping { + 'app-version': VersionService; + 'platform-identifier': VersionService; + } +} diff --git a/node_modules/@firebase/app-types/package.json b/node_modules/@firebase/app-types/package.json new file mode 100644 index 0000000..4c49efb --- /dev/null +++ b/node_modules/@firebase/app-types/package.json @@ -0,0 +1,29 @@ +{ + "name": "@firebase/app-types", + "version": "0.9.3", + "description": "@firebase/app Types", + "author": "Firebase (https://firebase.google.com/)", + "license": "Apache-2.0", + "scripts": { + "test": "tsc", + "test:ci": "node ../../scripts/run_tests_in_ci.js" + }, + "files": [ + "index.d.ts", + "private.d.ts" + ], + "repository": { + "directory": "packages/app-types", + "type": "git", + "url": "git+https://github.com/firebase/firebase-js-sdk.git" + }, + "bugs": { + "url": "https://github.com/firebase/firebase-js-sdk/issues" + }, + "dependency": { + "@firebase/logger": "0.2.6" + }, + "devDependencies": { + "typescript": "5.5.4" + } +} diff --git a/node_modules/@firebase/app-types/private.d.ts b/node_modules/@firebase/app-types/private.d.ts new file mode 100644 index 0000000..410eece --- /dev/null +++ b/node_modules/@firebase/app-types/private.d.ts @@ -0,0 +1,165 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * THIS FILE IS FOR INTERNAL USAGE ONLY, IF YOU ARE NOT DEVELOPING THE FIREBASE + * SDKs, PLEASE DO NOT REFERENCE THIS FILE AS IT MAY CHANGE WITHOUT WARNING + */ + +import { FirebaseApp, FirebaseNamespace } from '@firebase/app-types'; +import { Observer, Subscribe } from '@firebase/util'; +import { FirebaseError, ErrorFactory } from '@firebase/util'; +import { Component, ComponentContainer, Name } from '@firebase/component'; + +export interface FirebaseServiceInternals { + /** + * Delete the service and free it's resources - called from + * app.delete(). + */ + delete(): Promise; +} + +// Services are exposed through instances - each of which is associated with a +// FirebaseApp. +export interface FirebaseService { + app: FirebaseApp; + INTERNAL?: FirebaseServiceInternals; +} + +export type AppHook = (event: string, app: FirebaseApp) => void; + +/** + * Firebase Services create instances given a Firebase App instance and can + * optionally add properties and methods to each FirebaseApp via the extendApp() + * function. + */ +export interface FirebaseServiceFactory { + ( + app: FirebaseApp, + extendApp?: (props: { [prop: string]: any }) => void, + instanceString?: string + ): FirebaseService; +} + +export interface PlatformLoggerService { + getPlatformInfoString(): string; +} + +/** + * All ServiceNamespaces extend from FirebaseServiceNamespace + */ +export interface FirebaseServiceNamespace { + (app?: FirebaseApp): T; +} + +export interface FirebaseAuthTokenData { + accessToken: string; +} + +export interface FirebaseAppInternals { + getToken(refreshToken?: boolean): Promise; + getUid(): string | null; + addAuthTokenListener(fn: (token: string | null) => void): void; + removeAuthTokenListener(fn: (token: string | null) => void): void; + analytics: { + logEvent: ( + eventName: string, + eventParams: { [key: string]: any }, + options?: { global: boolean } + ) => void; + }; +} + +export interface _FirebaseApp extends FirebaseApp { + container: ComponentContainer; + _addComponent(component: Component): void; + _addOrOverwriteComponent(component: Component): void; + _removeServiceInstance(name: string, instanceIdentifier?: string): void; +} +export interface _FirebaseNamespace extends FirebaseNamespace { + INTERNAL: { + /** + * Internal API to register a Firebase Service into the firebase namespace. + * + * Each service will create a child namespace (firebase.) which acts as + * both a namespace for service specific properties, and also as a service + * accessor function (firebase.() or firebase.(app)). + * + * @param name The Firebase Service being registered. + * @param createService Factory function to create a service instance. + * @param serviceProperties Properties to copy to the service's namespace. + * @param appHook All appHooks called before initializeApp returns to caller. + * @param allowMultipleInstances Whether the registered service supports + * multiple instances per app. If not specified, the default is false. + */ + registerComponent( + component: Component + ): FirebaseServiceNamespace | null; + + /** + * Just used for testing to start from a fresh namespace. + */ + createFirebaseNamespace(): FirebaseNamespace; + + /** + * Internal API to install properties on the top-level firebase namespace. + * @prop props The top level properties of this object are copied to the + * namespace. + */ + extendNamespace(props: { [prop: string]: any }): void; + + /** + * Create a Subscribe function. A proxy Observer is created so that + * events can be sent to single Observer to be fanned out automatically. + */ + createSubscribe( + executor: (observer: Observer) => void, + onNoObservers?: (observer: Observer) => void + ): Subscribe; + + /** + * Utility exposed for internal testing. + */ + deepExtend(target: any, source: any): any; + + /** + * Internal API to remove an app from the list of registered apps. + */ + removeApp(name: string): void; + + /** + * registered components. + */ + components: Map; + + /* + * Convert service name to factory name to use. + */ + useAsService(app: FirebaseApp, serviceName: string): string | null; + + /** + * Use to construct all thrown FirebaseError's. + */ + ErrorFactory: typeof ErrorFactory; + }; +} + +declare module '@firebase/component' { + interface NameServiceMapping { + 'platform-logger': PlatformLoggerService; + } +} diff --git a/node_modules/@firebase/auth-interop-types/README.md b/node_modules/@firebase/auth-interop-types/README.md new file mode 100644 index 0000000..67ed638 --- /dev/null +++ b/node_modules/@firebase/auth-interop-types/README.md @@ -0,0 +1,3 @@ +# @firebase/auth-interop-types + +**This package is not intended for direct usage, and should only be used via the officially supported [firebase](https://www.npmjs.com/package/firebase) package.** diff --git a/node_modules/@firebase/auth-interop-types/index.d.ts b/node_modules/@firebase/auth-interop-types/index.d.ts new file mode 100644 index 0000000..6c9eb3d --- /dev/null +++ b/node_modules/@firebase/auth-interop-types/index.d.ts @@ -0,0 +1,35 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export interface FirebaseAuthTokenData { + accessToken: string; +} + +export interface FirebaseAuthInternal { + getToken(refreshToken?: boolean): Promise; + getUid(): string | null; + addAuthTokenListener(fn: (token: string | null) => void): void; + removeAuthTokenListener(fn: (token: string | null) => void): void; +} + +export type FirebaseAuthInternalName = 'auth-internal'; + +declare module '@firebase/component' { + interface NameServiceMapping { + 'auth-internal': FirebaseAuthInternal; + } +} diff --git a/node_modules/@firebase/auth-interop-types/package.json b/node_modules/@firebase/auth-interop-types/package.json new file mode 100644 index 0000000..ecea25d --- /dev/null +++ b/node_modules/@firebase/auth-interop-types/package.json @@ -0,0 +1,25 @@ +{ + "name": "@firebase/auth-interop-types", + "version": "0.2.4", + "description": "@firebase/auth interop Types", + "author": "Firebase (https://firebase.google.com/)", + "license": "Apache-2.0", + "scripts": { + "test": "tsc", + "test:ci": "node ../../scripts/run_tests_in_ci.js" + }, + "files": [ + "index.d.ts" + ], + "repository": { + "directory": "packages/auth-types", + "type": "git", + "url": "git+https://github.com/firebase/firebase-js-sdk.git" + }, + "bugs": { + "url": "https://github.com/firebase/firebase-js-sdk/issues" + }, + "devDependencies": { + "typescript": "5.5.4" + } +} diff --git a/node_modules/@firebase/component/README.md b/node_modules/@firebase/component/README.md new file mode 100644 index 0000000..242dacb --- /dev/null +++ b/node_modules/@firebase/component/README.md @@ -0,0 +1,12 @@ +# @firebase/component + +_NOTE: This is specifically tailored for Firebase JS SDK usage, if you are not a +member of the Firebase team, please avoid using this package_ + +## Usage + +**ES Modules** + +```javascript +import { Component } from '@firebase/component'; +``` diff --git a/node_modules/@firebase/component/dist/esm/index.d.ts b/node_modules/@firebase/component/dist/esm/index.d.ts new file mode 100644 index 0000000..7b21e7b --- /dev/null +++ b/node_modules/@firebase/component/dist/esm/index.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { Component } from './src/component'; +export { ComponentContainer } from './src/component_container'; +export { Provider } from './src/provider'; +export { ComponentType, InstanceFactory, InstantiationMode, NameServiceMapping, Name, InstanceFactoryOptions } from './src/types'; diff --git a/node_modules/@firebase/component/dist/esm/index.esm.js b/node_modules/@firebase/component/dist/esm/index.esm.js new file mode 100644 index 0000000..2c1c094 --- /dev/null +++ b/node_modules/@firebase/component/dist/esm/index.esm.js @@ -0,0 +1,408 @@ +import { Deferred } from '@firebase/util'; + +/** + * Component for service name T, e.g. `auth`, `auth-internal` + */ +class Component { + /** + * + * @param name The public service name, e.g. app, auth, firestore, database + * @param instanceFactory Service factory responsible for creating the public interface + * @param type whether the service provided by the component is public or private + */ + constructor(name, instanceFactory, type) { + this.name = name; + this.instanceFactory = instanceFactory; + this.type = type; + this.multipleInstances = false; + /** + * Properties to be added to the service namespace + */ + this.serviceProps = {}; + this.instantiationMode = "LAZY" /* InstantiationMode.LAZY */; + this.onInstanceCreated = null; + } + setInstantiationMode(mode) { + this.instantiationMode = mode; + return this; + } + setMultipleInstances(multipleInstances) { + this.multipleInstances = multipleInstances; + return this; + } + setServiceProps(props) { + this.serviceProps = props; + return this; + } + setInstanceCreatedCallback(callback) { + this.onInstanceCreated = callback; + return this; + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DEFAULT_ENTRY_NAME = '[DEFAULT]'; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provider for instance for service name T, e.g. 'auth', 'auth-internal' + * NameServiceMapping[T] is an alias for the type of the instance + */ +class Provider { + constructor(name, container) { + this.name = name; + this.container = container; + this.component = null; + this.instances = new Map(); + this.instancesDeferred = new Map(); + this.instancesOptions = new Map(); + this.onInitCallbacks = new Map(); + } + /** + * @param identifier A provider can provide multiple instances of a service + * if this.component.multipleInstances is true. + */ + get(identifier) { + // if multipleInstances is not supported, use the default name + const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier); + if (!this.instancesDeferred.has(normalizedIdentifier)) { + const deferred = new Deferred(); + this.instancesDeferred.set(normalizedIdentifier, deferred); + if (this.isInitialized(normalizedIdentifier) || + this.shouldAutoInitialize()) { + // initialize the service if it can be auto-initialized + try { + const instance = this.getOrInitializeService({ + instanceIdentifier: normalizedIdentifier + }); + if (instance) { + deferred.resolve(instance); + } + } + catch (e) { + // when the instance factory throws an exception during get(), it should not cause + // a fatal error. We just return the unresolved promise in this case. + } + } + } + return this.instancesDeferred.get(normalizedIdentifier).promise; + } + getImmediate(options) { + // if multipleInstances is not supported, use the default name + const normalizedIdentifier = this.normalizeInstanceIdentifier(options?.identifier); + const optional = options?.optional ?? false; + if (this.isInitialized(normalizedIdentifier) || + this.shouldAutoInitialize()) { + try { + return this.getOrInitializeService({ + instanceIdentifier: normalizedIdentifier + }); + } + catch (e) { + if (optional) { + return null; + } + else { + throw e; + } + } + } + else { + // In case a component is not initialized and should/cannot be auto-initialized at the moment, return null if the optional flag is set, or throw + if (optional) { + return null; + } + else { + throw Error(`Service ${this.name} is not available`); + } + } + } + getComponent() { + return this.component; + } + setComponent(component) { + if (component.name !== this.name) { + throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`); + } + if (this.component) { + throw Error(`Component for ${this.name} has already been provided`); + } + this.component = component; + // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`) + if (!this.shouldAutoInitialize()) { + return; + } + // if the service is eager, initialize the default instance + if (isComponentEager(component)) { + try { + this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME }); + } + catch (e) { + // when the instance factory for an eager Component throws an exception during the eager + // initialization, it should not cause a fatal error. + // TODO: Investigate if we need to make it configurable, because some component may want to cause + // a fatal error in this case? + } + } + // Create service instances for the pending promises and resolve them + // NOTE: if this.multipleInstances is false, only the default instance will be created + // and all promises with resolve with it regardless of the identifier. + for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) { + const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier); + try { + // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy. + const instance = this.getOrInitializeService({ + instanceIdentifier: normalizedIdentifier + }); + instanceDeferred.resolve(instance); + } + catch (e) { + // when the instance factory throws an exception, it should not cause + // a fatal error. We just leave the promise unresolved. + } + } + } + clearInstance(identifier = DEFAULT_ENTRY_NAME) { + this.instancesDeferred.delete(identifier); + this.instancesOptions.delete(identifier); + this.instances.delete(identifier); + } + // app.delete() will call this method on every provider to delete the services + // TODO: should we mark the provider as deleted? + async delete() { + const services = Array.from(this.instances.values()); + await Promise.all([ + ...services + .filter(service => 'INTERNAL' in service) // legacy services + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .map(service => service.INTERNAL.delete()), + ...services + .filter(service => '_delete' in service) // modularized services + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .map(service => service._delete()) + ]); + } + isComponentSet() { + return this.component != null; + } + isInitialized(identifier = DEFAULT_ENTRY_NAME) { + return this.instances.has(identifier); + } + getOptions(identifier = DEFAULT_ENTRY_NAME) { + return this.instancesOptions.get(identifier) || {}; + } + initialize(opts = {}) { + const { options = {} } = opts; + const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier); + if (this.isInitialized(normalizedIdentifier)) { + throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`); + } + if (!this.isComponentSet()) { + throw Error(`Component ${this.name} has not been registered yet`); + } + const instance = this.getOrInitializeService({ + instanceIdentifier: normalizedIdentifier, + options + }); + // resolve any pending promise waiting for the service instance + for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) { + const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier); + if (normalizedIdentifier === normalizedDeferredIdentifier) { + instanceDeferred.resolve(instance); + } + } + return instance; + } + /** + * + * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize(). + * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program. + * + * @param identifier An optional instance identifier + * @returns a function to unregister the callback + */ + onInit(callback, identifier) { + const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier); + const existingCallbacks = this.onInitCallbacks.get(normalizedIdentifier) ?? + new Set(); + existingCallbacks.add(callback); + this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks); + const existingInstance = this.instances.get(normalizedIdentifier); + if (existingInstance) { + callback(existingInstance, normalizedIdentifier); + } + return () => { + existingCallbacks.delete(callback); + }; + } + /** + * Invoke onInit callbacks synchronously + * @param instance the service instance` + */ + invokeOnInitCallbacks(instance, identifier) { + const callbacks = this.onInitCallbacks.get(identifier); + if (!callbacks) { + return; + } + for (const callback of callbacks) { + try { + callback(instance, identifier); + } + catch { + // ignore errors in the onInit callback + } + } + } + getOrInitializeService({ instanceIdentifier, options = {} }) { + let instance = this.instances.get(instanceIdentifier); + if (!instance && this.component) { + instance = this.component.instanceFactory(this.container, { + instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier), + options + }); + this.instances.set(instanceIdentifier, instance); + this.instancesOptions.set(instanceIdentifier, options); + /** + * Invoke onInit listeners. + * Note this.component.onInstanceCreated is different, which is used by the component creator, + * while onInit listeners are registered by consumers of the provider. + */ + this.invokeOnInitCallbacks(instance, instanceIdentifier); + /** + * Order is important + * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which + * makes `isInitialized()` return true. + */ + if (this.component.onInstanceCreated) { + try { + this.component.onInstanceCreated(this.container, instanceIdentifier, instance); + } + catch { + // ignore errors in the onInstanceCreatedCallback + } + } + } + return instance || null; + } + normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME) { + if (this.component) { + return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME; + } + else { + return identifier; // assume multiple instances are supported before the component is provided. + } + } + shouldAutoInitialize() { + return (!!this.component && + this.component.instantiationMode !== "EXPLICIT" /* InstantiationMode.EXPLICIT */); + } +} +// undefined should be passed to the service factory for the default instance +function normalizeIdentifierForFactory(identifier) { + return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier; +} +function isComponentEager(component) { + return component.instantiationMode === "EAGER" /* InstantiationMode.EAGER */; +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal` + */ +class ComponentContainer { + constructor(name) { + this.name = name; + this.providers = new Map(); + } + /** + * + * @param component Component being added + * @param overwrite When a component with the same name has already been registered, + * if overwrite is true: overwrite the existing component with the new component and create a new + * provider with the new component. It can be useful in tests where you want to use different mocks + * for different tests. + * if overwrite is false: throw an exception + */ + addComponent(component) { + const provider = this.getProvider(component.name); + if (provider.isComponentSet()) { + throw new Error(`Component ${component.name} has already been registered with ${this.name}`); + } + provider.setComponent(component); + } + addOrOverwriteComponent(component) { + const provider = this.getProvider(component.name); + if (provider.isComponentSet()) { + // delete the existing provider from the container, so we can register the new component + this.providers.delete(component.name); + } + this.addComponent(component); + } + /** + * getProvider provides a type safe interface where it can only be called with a field name + * present in NameServiceMapping interface. + * + * Firebase SDKs providing services should extend NameServiceMapping interface to register + * themselves. + */ + getProvider(name) { + if (this.providers.has(name)) { + return this.providers.get(name); + } + // create a Provider for a service that hasn't registered with Firebase + const provider = new Provider(name, this); + this.providers.set(name, provider); + return provider; + } + getProviders() { + return Array.from(this.providers.values()); + } +} + +export { Component, ComponentContainer, Provider }; +//# sourceMappingURL=index.esm.js.map diff --git a/node_modules/@firebase/component/dist/esm/index.esm.js.map b/node_modules/@firebase/component/dist/esm/index.esm.js.map new file mode 100644 index 0000000..78b937f --- /dev/null +++ b/node_modules/@firebase/component/dist/esm/index.esm.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.esm.js","sources":["../../src/component.ts","../../src/constants.ts","../../src/provider.ts","../../src/component_container.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n InstantiationMode,\n InstanceFactory,\n ComponentType,\n Dictionary,\n Name,\n onInstanceCreatedCallback\n} from './types';\n\n/**\n * Component for service name T, e.g. `auth`, `auth-internal`\n */\nexport class Component {\n multipleInstances = false;\n /**\n * Properties to be added to the service namespace\n */\n serviceProps: Dictionary = {};\n\n instantiationMode = InstantiationMode.LAZY;\n\n onInstanceCreated: onInstanceCreatedCallback | null = null;\n\n /**\n *\n * @param name The public service name, e.g. app, auth, firestore, database\n * @param instanceFactory Service factory responsible for creating the public interface\n * @param type whether the service provided by the component is public or private\n */\n constructor(\n readonly name: T,\n readonly instanceFactory: InstanceFactory,\n readonly type: ComponentType\n ) {}\n\n setInstantiationMode(mode: InstantiationMode): this {\n this.instantiationMode = mode;\n return this;\n }\n\n setMultipleInstances(multipleInstances: boolean): this {\n this.multipleInstances = multipleInstances;\n return this;\n }\n\n setServiceProps(props: Dictionary): this {\n this.serviceProps = props;\n return this;\n }\n\n setInstanceCreatedCallback(callback: onInstanceCreatedCallback): this {\n this.onInstanceCreated = callback;\n return this;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const DEFAULT_ENTRY_NAME = '[DEFAULT]';\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from '@firebase/util';\nimport { ComponentContainer } from './component_container';\nimport { DEFAULT_ENTRY_NAME } from './constants';\nimport {\n InitializeOptions,\n InstantiationMode,\n Name,\n NameServiceMapping,\n OnInitCallBack\n} from './types';\nimport { Component } from './component';\n\n/**\n * Provider for instance for service name T, e.g. 'auth', 'auth-internal'\n * NameServiceMapping[T] is an alias for the type of the instance\n */\nexport class Provider {\n private component: Component | null = null;\n private readonly instances: Map = new Map();\n private readonly instancesDeferred: Map<\n string,\n Deferred\n > = new Map();\n private readonly instancesOptions: Map> =\n new Map();\n private onInitCallbacks: Map>> = new Map();\n\n constructor(\n private readonly name: T,\n private readonly container: ComponentContainer\n ) {}\n\n /**\n * @param identifier A provider can provide multiple instances of a service\n * if this.component.multipleInstances is true.\n */\n get(identifier?: string): Promise {\n // if multipleInstances is not supported, use the default name\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\n\n if (!this.instancesDeferred.has(normalizedIdentifier)) {\n const deferred = new Deferred();\n this.instancesDeferred.set(normalizedIdentifier, deferred);\n\n if (\n this.isInitialized(normalizedIdentifier) ||\n this.shouldAutoInitialize()\n ) {\n // initialize the service if it can be auto-initialized\n try {\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n });\n if (instance) {\n deferred.resolve(instance);\n }\n } catch (e) {\n // when the instance factory throws an exception during get(), it should not cause\n // a fatal error. We just return the unresolved promise in this case.\n }\n }\n }\n\n return this.instancesDeferred.get(normalizedIdentifier)!.promise;\n }\n\n /**\n *\n * @param options.identifier A provider can provide multiple instances of a service\n * if this.component.multipleInstances is true.\n * @param options.optional If optional is false or not provided, the method throws an error when\n * the service is not immediately available.\n * If optional is true, the method returns null if the service is not immediately available.\n */\n getImmediate(options: {\n identifier?: string;\n optional: true;\n }): NameServiceMapping[T] | null;\n getImmediate(options?: {\n identifier?: string;\n optional?: false;\n }): NameServiceMapping[T];\n getImmediate(options?: {\n identifier?: string;\n optional?: boolean;\n }): NameServiceMapping[T] | null {\n // if multipleInstances is not supported, use the default name\n const normalizedIdentifier = this.normalizeInstanceIdentifier(\n options?.identifier\n );\n const optional = options?.optional ?? false;\n\n if (\n this.isInitialized(normalizedIdentifier) ||\n this.shouldAutoInitialize()\n ) {\n try {\n return this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n });\n } catch (e) {\n if (optional) {\n return null;\n } else {\n throw e;\n }\n }\n } else {\n // In case a component is not initialized and should/cannot be auto-initialized at the moment, return null if the optional flag is set, or throw\n if (optional) {\n return null;\n } else {\n throw Error(`Service ${this.name} is not available`);\n }\n }\n }\n\n getComponent(): Component | null {\n return this.component;\n }\n\n setComponent(component: Component): void {\n if (component.name !== this.name) {\n throw Error(\n `Mismatching Component ${component.name} for Provider ${this.name}.`\n );\n }\n\n if (this.component) {\n throw Error(`Component for ${this.name} has already been provided`);\n }\n\n this.component = component;\n\n // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)\n if (!this.shouldAutoInitialize()) {\n return;\n }\n\n // if the service is eager, initialize the default instance\n if (isComponentEager(component)) {\n try {\n this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });\n } catch (e) {\n // when the instance factory for an eager Component throws an exception during the eager\n // initialization, it should not cause a fatal error.\n // TODO: Investigate if we need to make it configurable, because some component may want to cause\n // a fatal error in this case?\n }\n }\n\n // Create service instances for the pending promises and resolve them\n // NOTE: if this.multipleInstances is false, only the default instance will be created\n // and all promises with resolve with it regardless of the identifier.\n for (const [\n instanceIdentifier,\n instanceDeferred\n ] of this.instancesDeferred.entries()) {\n const normalizedIdentifier =\n this.normalizeInstanceIdentifier(instanceIdentifier);\n\n try {\n // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n })!;\n instanceDeferred.resolve(instance);\n } catch (e) {\n // when the instance factory throws an exception, it should not cause\n // a fatal error. We just leave the promise unresolved.\n }\n }\n }\n\n clearInstance(identifier: string = DEFAULT_ENTRY_NAME): void {\n this.instancesDeferred.delete(identifier);\n this.instancesOptions.delete(identifier);\n this.instances.delete(identifier);\n }\n\n // app.delete() will call this method on every provider to delete the services\n // TODO: should we mark the provider as deleted?\n async delete(): Promise {\n const services = Array.from(this.instances.values());\n\n await Promise.all([\n ...services\n .filter(service => 'INTERNAL' in service) // legacy services\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .map(service => (service as any).INTERNAL!.delete()),\n ...services\n .filter(service => '_delete' in service) // modularized services\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .map(service => (service as any)._delete())\n ]);\n }\n\n isComponentSet(): boolean {\n return this.component != null;\n }\n\n isInitialized(identifier: string = DEFAULT_ENTRY_NAME): boolean {\n return this.instances.has(identifier);\n }\n\n getOptions(identifier: string = DEFAULT_ENTRY_NAME): Record {\n return this.instancesOptions.get(identifier) || {};\n }\n\n initialize(opts: InitializeOptions = {}): NameServiceMapping[T] {\n const { options = {} } = opts;\n const normalizedIdentifier = this.normalizeInstanceIdentifier(\n opts.instanceIdentifier\n );\n if (this.isInitialized(normalizedIdentifier)) {\n throw Error(\n `${this.name}(${normalizedIdentifier}) has already been initialized`\n );\n }\n\n if (!this.isComponentSet()) {\n throw Error(`Component ${this.name} has not been registered yet`);\n }\n\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier,\n options\n })!;\n\n // resolve any pending promise waiting for the service instance\n for (const [\n instanceIdentifier,\n instanceDeferred\n ] of this.instancesDeferred.entries()) {\n const normalizedDeferredIdentifier =\n this.normalizeInstanceIdentifier(instanceIdentifier);\n if (normalizedIdentifier === normalizedDeferredIdentifier) {\n instanceDeferred.resolve(instance);\n }\n }\n\n return instance;\n }\n\n /**\n *\n * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().\n * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.\n *\n * @param identifier An optional instance identifier\n * @returns a function to unregister the callback\n */\n onInit(callback: OnInitCallBack, identifier?: string): () => void {\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\n const existingCallbacks =\n this.onInitCallbacks.get(normalizedIdentifier) ??\n new Set>();\n existingCallbacks.add(callback);\n this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);\n\n const existingInstance = this.instances.get(normalizedIdentifier);\n if (existingInstance) {\n callback(existingInstance, normalizedIdentifier);\n }\n\n return () => {\n existingCallbacks.delete(callback);\n };\n }\n\n /**\n * Invoke onInit callbacks synchronously\n * @param instance the service instance`\n */\n private invokeOnInitCallbacks(\n instance: NameServiceMapping[T],\n identifier: string\n ): void {\n const callbacks = this.onInitCallbacks.get(identifier);\n if (!callbacks) {\n return;\n }\n for (const callback of callbacks) {\n try {\n callback(instance, identifier);\n } catch {\n // ignore errors in the onInit callback\n }\n }\n }\n\n private getOrInitializeService({\n instanceIdentifier,\n options = {}\n }: {\n instanceIdentifier: string;\n options?: Record;\n }): NameServiceMapping[T] | null {\n let instance = this.instances.get(instanceIdentifier);\n if (!instance && this.component) {\n instance = this.component.instanceFactory(this.container, {\n instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),\n options\n });\n this.instances.set(instanceIdentifier, instance!);\n this.instancesOptions.set(instanceIdentifier, options);\n\n /**\n * Invoke onInit listeners.\n * Note this.component.onInstanceCreated is different, which is used by the component creator,\n * while onInit listeners are registered by consumers of the provider.\n */\n this.invokeOnInitCallbacks(instance!, instanceIdentifier);\n\n /**\n * Order is important\n * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which\n * makes `isInitialized()` return true.\n */\n if (this.component.onInstanceCreated) {\n try {\n this.component.onInstanceCreated(\n this.container,\n instanceIdentifier,\n instance!\n );\n } catch {\n // ignore errors in the onInstanceCreatedCallback\n }\n }\n }\n\n return instance || null;\n }\n\n private normalizeInstanceIdentifier(\n identifier: string = DEFAULT_ENTRY_NAME\n ): string {\n if (this.component) {\n return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;\n } else {\n return identifier; // assume multiple instances are supported before the component is provided.\n }\n }\n\n private shouldAutoInitialize(): boolean {\n return (\n !!this.component &&\n this.component.instantiationMode !== InstantiationMode.EXPLICIT\n );\n }\n}\n\n// undefined should be passed to the service factory for the default instance\nfunction normalizeIdentifierForFactory(identifier: string): string | undefined {\n return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;\n}\n\nfunction isComponentEager(component: Component): boolean {\n return component.instantiationMode === InstantiationMode.EAGER;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Provider } from './provider';\nimport { Component } from './component';\nimport { Name } from './types';\n\n/**\n * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`\n */\nexport class ComponentContainer {\n private readonly providers = new Map>();\n\n constructor(private readonly name: string) {}\n\n /**\n *\n * @param component Component being added\n * @param overwrite When a component with the same name has already been registered,\n * if overwrite is true: overwrite the existing component with the new component and create a new\n * provider with the new component. It can be useful in tests where you want to use different mocks\n * for different tests.\n * if overwrite is false: throw an exception\n */\n addComponent(component: Component): void {\n const provider = this.getProvider(component.name);\n if (provider.isComponentSet()) {\n throw new Error(\n `Component ${component.name} has already been registered with ${this.name}`\n );\n }\n\n provider.setComponent(component);\n }\n\n addOrOverwriteComponent(component: Component): void {\n const provider = this.getProvider(component.name);\n if (provider.isComponentSet()) {\n // delete the existing provider from the container, so we can register the new component\n this.providers.delete(component.name);\n }\n\n this.addComponent(component);\n }\n\n /**\n * getProvider provides a type safe interface where it can only be called with a field name\n * present in NameServiceMapping interface.\n *\n * Firebase SDKs providing services should extend NameServiceMapping interface to register\n * themselves.\n */\n getProvider(name: T): Provider {\n if (this.providers.has(name)) {\n return this.providers.get(name) as unknown as Provider;\n }\n\n // create a Provider for a service that hasn't registered with Firebase\n const provider = new Provider(name, this);\n this.providers.set(name, provider as unknown as Provider);\n\n return provider as Provider;\n }\n\n getProviders(): Array> {\n return Array.from(this.providers.values());\n }\n}\n"],"names":[],"mappings":";;AAyBA;;AAEG;MACU,SAAS,CAAA;AAWpB;;;;;AAKG;AACH,IAAA,WAAA,CACW,IAAO,EACP,eAAmC,EACnC,IAAmB,EAAA;QAFnB,IAAI,CAAA,IAAA,GAAJ,IAAI,CAAG;QACP,IAAe,CAAA,eAAA,GAAf,eAAe,CAAoB;QACnC,IAAI,CAAA,IAAA,GAAJ,IAAI,CAAe;QAnB9B,IAAiB,CAAA,iBAAA,GAAG,KAAK,CAAC;AAC1B;;AAEG;QACH,IAAY,CAAA,YAAA,GAAe,EAAE,CAAC;AAE9B,QAAA,IAAA,CAAA,iBAAiB,GAA0B,MAAA,8BAAA;QAE3C,IAAiB,CAAA,iBAAA,GAAwC,IAAI,CAAC;KAY1D;AAEJ,IAAA,oBAAoB,CAAC,IAAuB,EAAA;AAC1C,QAAA,IAAI,CAAC,iBAAiB,GAAG,IAAI,CAAC;AAC9B,QAAA,OAAO,IAAI,CAAC;KACb;AAED,IAAA,oBAAoB,CAAC,iBAA0B,EAAA;AAC7C,QAAA,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;AAC3C,QAAA,OAAO,IAAI,CAAC;KACb;AAED,IAAA,eAAe,CAAC,KAAiB,EAAA;AAC/B,QAAA,IAAI,CAAC,YAAY,GAAG,KAAK,CAAC;AAC1B,QAAA,OAAO,IAAI,CAAC;KACb;AAED,IAAA,0BAA0B,CAAC,QAAsC,EAAA;AAC/D,QAAA,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AAC,SAAS,CAAC,IAAI,CAAC,CAAC;AAClD,QAAA,IAAI,QAAQ,CAAC,cAAc,EAAE,EAAE;;YAE7B,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;SACvC;AAED,QAAA,IAAI,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;KAC9B;AAED;;;;;;AAMG;AACH,IAAA,WAAW,CAAiB,IAAO,EAAA;QACjC,IAAI,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE;YAC5B,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAA2B,CAAC;SAC3D;;QAGD,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAAI,IAAI,EAAE,IAAI,CAAC,CAAC;QAC7C,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,QAAqC,CAAC,CAAC;AAEhE,QAAA,OAAO,QAAuB,CAAC;KAChC;IAED,YAAY,GAAA;QACV,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC,CAAC;KAC5C;AACF;;;;"} \ No newline at end of file diff --git a/node_modules/@firebase/component/dist/esm/package.json b/node_modules/@firebase/component/dist/esm/package.json new file mode 100644 index 0000000..7c34deb --- /dev/null +++ b/node_modules/@firebase/component/dist/esm/package.json @@ -0,0 +1 @@ +{"type":"module"} \ No newline at end of file diff --git a/node_modules/@firebase/component/dist/esm/src/component.d.ts b/node_modules/@firebase/component/dist/esm/src/component.d.ts new file mode 100644 index 0000000..debdf77 --- /dev/null +++ b/node_modules/@firebase/component/dist/esm/src/component.d.ts @@ -0,0 +1,43 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { InstantiationMode, InstanceFactory, ComponentType, Dictionary, Name, onInstanceCreatedCallback } from './types'; +/** + * Component for service name T, e.g. `auth`, `auth-internal` + */ +export declare class Component { + readonly name: T; + readonly instanceFactory: InstanceFactory; + readonly type: ComponentType; + multipleInstances: boolean; + /** + * Properties to be added to the service namespace + */ + serviceProps: Dictionary; + instantiationMode: InstantiationMode; + onInstanceCreated: onInstanceCreatedCallback | null; + /** + * + * @param name The public service name, e.g. app, auth, firestore, database + * @param instanceFactory Service factory responsible for creating the public interface + * @param type whether the service provided by the component is public or private + */ + constructor(name: T, instanceFactory: InstanceFactory, type: ComponentType); + setInstantiationMode(mode: InstantiationMode): this; + setMultipleInstances(multipleInstances: boolean): this; + setServiceProps(props: Dictionary): this; + setInstanceCreatedCallback(callback: onInstanceCreatedCallback): this; +} diff --git a/node_modules/@firebase/component/dist/esm/src/component_container.d.ts b/node_modules/@firebase/component/dist/esm/src/component_container.d.ts new file mode 100644 index 0000000..a1322f3 --- /dev/null +++ b/node_modules/@firebase/component/dist/esm/src/component_container.d.ts @@ -0,0 +1,47 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Provider } from './provider'; +import { Component } from './component'; +import { Name } from './types'; +/** + * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal` + */ +export declare class ComponentContainer { + private readonly name; + private readonly providers; + constructor(name: string); + /** + * + * @param component Component being added + * @param overwrite When a component with the same name has already been registered, + * if overwrite is true: overwrite the existing component with the new component and create a new + * provider with the new component. It can be useful in tests where you want to use different mocks + * for different tests. + * if overwrite is false: throw an exception + */ + addComponent(component: Component): void; + addOrOverwriteComponent(component: Component): void; + /** + * getProvider provides a type safe interface where it can only be called with a field name + * present in NameServiceMapping interface. + * + * Firebase SDKs providing services should extend NameServiceMapping interface to register + * themselves. + */ + getProvider(name: T): Provider; + getProviders(): Array>; +} diff --git a/node_modules/@firebase/component/dist/esm/src/constants.d.ts b/node_modules/@firebase/component/dist/esm/src/constants.d.ts new file mode 100644 index 0000000..b069f4e --- /dev/null +++ b/node_modules/@firebase/component/dist/esm/src/constants.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const DEFAULT_ENTRY_NAME = "[DEFAULT]"; diff --git a/node_modules/@firebase/component/dist/esm/src/provider.d.ts b/node_modules/@firebase/component/dist/esm/src/provider.d.ts new file mode 100644 index 0000000..8039aff --- /dev/null +++ b/node_modules/@firebase/component/dist/esm/src/provider.d.ts @@ -0,0 +1,79 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ComponentContainer } from './component_container'; +import { InitializeOptions, Name, NameServiceMapping, OnInitCallBack } from './types'; +import { Component } from './component'; +/** + * Provider for instance for service name T, e.g. 'auth', 'auth-internal' + * NameServiceMapping[T] is an alias for the type of the instance + */ +export declare class Provider { + private readonly name; + private readonly container; + private component; + private readonly instances; + private readonly instancesDeferred; + private readonly instancesOptions; + private onInitCallbacks; + constructor(name: T, container: ComponentContainer); + /** + * @param identifier A provider can provide multiple instances of a service + * if this.component.multipleInstances is true. + */ + get(identifier?: string): Promise; + /** + * + * @param options.identifier A provider can provide multiple instances of a service + * if this.component.multipleInstances is true. + * @param options.optional If optional is false or not provided, the method throws an error when + * the service is not immediately available. + * If optional is true, the method returns null if the service is not immediately available. + */ + getImmediate(options: { + identifier?: string; + optional: true; + }): NameServiceMapping[T] | null; + getImmediate(options?: { + identifier?: string; + optional?: false; + }): NameServiceMapping[T]; + getComponent(): Component | null; + setComponent(component: Component): void; + clearInstance(identifier?: string): void; + delete(): Promise; + isComponentSet(): boolean; + isInitialized(identifier?: string): boolean; + getOptions(identifier?: string): Record; + initialize(opts?: InitializeOptions): NameServiceMapping[T]; + /** + * + * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize(). + * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program. + * + * @param identifier An optional instance identifier + * @returns a function to unregister the callback + */ + onInit(callback: OnInitCallBack, identifier?: string): () => void; + /** + * Invoke onInit callbacks synchronously + * @param instance the service instance` + */ + private invokeOnInitCallbacks; + private getOrInitializeService; + private normalizeInstanceIdentifier; + private shouldAutoInitialize; +} diff --git a/node_modules/@firebase/component/dist/esm/src/types.d.ts b/node_modules/@firebase/component/dist/esm/src/types.d.ts new file mode 100644 index 0000000..40eac68 --- /dev/null +++ b/node_modules/@firebase/component/dist/esm/src/types.d.ts @@ -0,0 +1,62 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ComponentContainer } from './component_container'; +export declare const enum InstantiationMode { + LAZY = "LAZY",// Currently most components are LAZY in JS SDK + EAGER = "EAGER",// EAGER components are initialized immediately upon registration + EXPLICIT = "EXPLICIT" +} +/** + * PUBLIC: A public component provides a set of public APIs to customers. A service namespace will be patched + * onto `firebase` namespace. Assume the component name is `test`, customers will be able + * to get the service by calling `firebase.test()` or `app.test()` where `app` is a `FirebaseApp` instance. + * + * PRIVATE: A private component provides a set of private APIs that are used internally by other + * Firebase SDKs. No service namespace is created in `firebase` namespace and customers have no way to get them. + */ +export declare const enum ComponentType { + PUBLIC = "PUBLIC", + PRIVATE = "PRIVATE", + VERSION = "VERSION" +} +export interface InstanceFactoryOptions { + instanceIdentifier?: string; + options?: {}; +} +export type InitializeOptions = InstanceFactoryOptions; +/** + * Factory to create an instance of type T, given a ComponentContainer. + * ComponentContainer is the IOC container that provides {@link Provider} + * for dependencies. + * + * NOTE: The container only provides {@link Provider} rather than the actual instances of dependencies. + * It is useful for lazily loaded dependencies and optional dependencies. + */ +export type InstanceFactory = (container: ComponentContainer, options: InstanceFactoryOptions) => NameServiceMapping[T]; +export type onInstanceCreatedCallback = (container: ComponentContainer, instanceIdentifier: string, instance: NameServiceMapping[T]) => void; +export interface Dictionary { + [key: string]: unknown; +} +/** + * This interface will be extended by Firebase SDKs to provide service name and service type mapping. + * It is used as a generic constraint to ensure type safety. + */ +export interface NameServiceMapping { +} +export type Name = keyof NameServiceMapping; +export type Service = NameServiceMapping[Name]; +export type OnInitCallBack = (instance: NameServiceMapping[T], identifier: string) => void; diff --git a/node_modules/@firebase/component/dist/esm/test/setup.d.ts b/node_modules/@firebase/component/dist/esm/test/setup.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/node_modules/@firebase/component/dist/esm/test/setup.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/component/dist/esm/test/util.d.ts b/node_modules/@firebase/component/dist/esm/test/util.d.ts new file mode 100644 index 0000000..93dbf0a --- /dev/null +++ b/node_modules/@firebase/component/dist/esm/test/util.d.ts @@ -0,0 +1,5 @@ +import { FirebaseApp } from '@firebase/app-types'; +import { InstanceFactory, InstantiationMode, Name } from '../src/types'; +import { Component } from '../src/component'; +export declare function getFakeApp(appName?: string): FirebaseApp; +export declare function getFakeComponent(name: T, factory: InstanceFactory, multipleInstance?: boolean, instantiationMode?: InstantiationMode): Component; diff --git a/node_modules/@firebase/component/dist/index.cjs.js b/node_modules/@firebase/component/dist/index.cjs.js new file mode 100644 index 0000000..2955acd --- /dev/null +++ b/node_modules/@firebase/component/dist/index.cjs.js @@ -0,0 +1,414 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var util = require('@firebase/util'); + +/** + * Component for service name T, e.g. `auth`, `auth-internal` + */ +class Component { + /** + * + * @param name The public service name, e.g. app, auth, firestore, database + * @param instanceFactory Service factory responsible for creating the public interface + * @param type whether the service provided by the component is public or private + */ + constructor(name, instanceFactory, type) { + this.name = name; + this.instanceFactory = instanceFactory; + this.type = type; + this.multipleInstances = false; + /** + * Properties to be added to the service namespace + */ + this.serviceProps = {}; + this.instantiationMode = "LAZY" /* InstantiationMode.LAZY */; + this.onInstanceCreated = null; + } + setInstantiationMode(mode) { + this.instantiationMode = mode; + return this; + } + setMultipleInstances(multipleInstances) { + this.multipleInstances = multipleInstances; + return this; + } + setServiceProps(props) { + this.serviceProps = props; + return this; + } + setInstanceCreatedCallback(callback) { + this.onInstanceCreated = callback; + return this; + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DEFAULT_ENTRY_NAME = '[DEFAULT]'; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provider for instance for service name T, e.g. 'auth', 'auth-internal' + * NameServiceMapping[T] is an alias for the type of the instance + */ +class Provider { + constructor(name, container) { + this.name = name; + this.container = container; + this.component = null; + this.instances = new Map(); + this.instancesDeferred = new Map(); + this.instancesOptions = new Map(); + this.onInitCallbacks = new Map(); + } + /** + * @param identifier A provider can provide multiple instances of a service + * if this.component.multipleInstances is true. + */ + get(identifier) { + // if multipleInstances is not supported, use the default name + const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier); + if (!this.instancesDeferred.has(normalizedIdentifier)) { + const deferred = new util.Deferred(); + this.instancesDeferred.set(normalizedIdentifier, deferred); + if (this.isInitialized(normalizedIdentifier) || + this.shouldAutoInitialize()) { + // initialize the service if it can be auto-initialized + try { + const instance = this.getOrInitializeService({ + instanceIdentifier: normalizedIdentifier + }); + if (instance) { + deferred.resolve(instance); + } + } + catch (e) { + // when the instance factory throws an exception during get(), it should not cause + // a fatal error. We just return the unresolved promise in this case. + } + } + } + return this.instancesDeferred.get(normalizedIdentifier).promise; + } + getImmediate(options) { + // if multipleInstances is not supported, use the default name + const normalizedIdentifier = this.normalizeInstanceIdentifier(options?.identifier); + const optional = options?.optional ?? false; + if (this.isInitialized(normalizedIdentifier) || + this.shouldAutoInitialize()) { + try { + return this.getOrInitializeService({ + instanceIdentifier: normalizedIdentifier + }); + } + catch (e) { + if (optional) { + return null; + } + else { + throw e; + } + } + } + else { + // In case a component is not initialized and should/cannot be auto-initialized at the moment, return null if the optional flag is set, or throw + if (optional) { + return null; + } + else { + throw Error(`Service ${this.name} is not available`); + } + } + } + getComponent() { + return this.component; + } + setComponent(component) { + if (component.name !== this.name) { + throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`); + } + if (this.component) { + throw Error(`Component for ${this.name} has already been provided`); + } + this.component = component; + // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`) + if (!this.shouldAutoInitialize()) { + return; + } + // if the service is eager, initialize the default instance + if (isComponentEager(component)) { + try { + this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME }); + } + catch (e) { + // when the instance factory for an eager Component throws an exception during the eager + // initialization, it should not cause a fatal error. + // TODO: Investigate if we need to make it configurable, because some component may want to cause + // a fatal error in this case? + } + } + // Create service instances for the pending promises and resolve them + // NOTE: if this.multipleInstances is false, only the default instance will be created + // and all promises with resolve with it regardless of the identifier. + for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) { + const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier); + try { + // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy. + const instance = this.getOrInitializeService({ + instanceIdentifier: normalizedIdentifier + }); + instanceDeferred.resolve(instance); + } + catch (e) { + // when the instance factory throws an exception, it should not cause + // a fatal error. We just leave the promise unresolved. + } + } + } + clearInstance(identifier = DEFAULT_ENTRY_NAME) { + this.instancesDeferred.delete(identifier); + this.instancesOptions.delete(identifier); + this.instances.delete(identifier); + } + // app.delete() will call this method on every provider to delete the services + // TODO: should we mark the provider as deleted? + async delete() { + const services = Array.from(this.instances.values()); + await Promise.all([ + ...services + .filter(service => 'INTERNAL' in service) // legacy services + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .map(service => service.INTERNAL.delete()), + ...services + .filter(service => '_delete' in service) // modularized services + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .map(service => service._delete()) + ]); + } + isComponentSet() { + return this.component != null; + } + isInitialized(identifier = DEFAULT_ENTRY_NAME) { + return this.instances.has(identifier); + } + getOptions(identifier = DEFAULT_ENTRY_NAME) { + return this.instancesOptions.get(identifier) || {}; + } + initialize(opts = {}) { + const { options = {} } = opts; + const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier); + if (this.isInitialized(normalizedIdentifier)) { + throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`); + } + if (!this.isComponentSet()) { + throw Error(`Component ${this.name} has not been registered yet`); + } + const instance = this.getOrInitializeService({ + instanceIdentifier: normalizedIdentifier, + options + }); + // resolve any pending promise waiting for the service instance + for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) { + const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier); + if (normalizedIdentifier === normalizedDeferredIdentifier) { + instanceDeferred.resolve(instance); + } + } + return instance; + } + /** + * + * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize(). + * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program. + * + * @param identifier An optional instance identifier + * @returns a function to unregister the callback + */ + onInit(callback, identifier) { + const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier); + const existingCallbacks = this.onInitCallbacks.get(normalizedIdentifier) ?? + new Set(); + existingCallbacks.add(callback); + this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks); + const existingInstance = this.instances.get(normalizedIdentifier); + if (existingInstance) { + callback(existingInstance, normalizedIdentifier); + } + return () => { + existingCallbacks.delete(callback); + }; + } + /** + * Invoke onInit callbacks synchronously + * @param instance the service instance` + */ + invokeOnInitCallbacks(instance, identifier) { + const callbacks = this.onInitCallbacks.get(identifier); + if (!callbacks) { + return; + } + for (const callback of callbacks) { + try { + callback(instance, identifier); + } + catch { + // ignore errors in the onInit callback + } + } + } + getOrInitializeService({ instanceIdentifier, options = {} }) { + let instance = this.instances.get(instanceIdentifier); + if (!instance && this.component) { + instance = this.component.instanceFactory(this.container, { + instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier), + options + }); + this.instances.set(instanceIdentifier, instance); + this.instancesOptions.set(instanceIdentifier, options); + /** + * Invoke onInit listeners. + * Note this.component.onInstanceCreated is different, which is used by the component creator, + * while onInit listeners are registered by consumers of the provider. + */ + this.invokeOnInitCallbacks(instance, instanceIdentifier); + /** + * Order is important + * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which + * makes `isInitialized()` return true. + */ + if (this.component.onInstanceCreated) { + try { + this.component.onInstanceCreated(this.container, instanceIdentifier, instance); + } + catch { + // ignore errors in the onInstanceCreatedCallback + } + } + } + return instance || null; + } + normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME) { + if (this.component) { + return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME; + } + else { + return identifier; // assume multiple instances are supported before the component is provided. + } + } + shouldAutoInitialize() { + return (!!this.component && + this.component.instantiationMode !== "EXPLICIT" /* InstantiationMode.EXPLICIT */); + } +} +// undefined should be passed to the service factory for the default instance +function normalizeIdentifierForFactory(identifier) { + return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier; +} +function isComponentEager(component) { + return component.instantiationMode === "EAGER" /* InstantiationMode.EAGER */; +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal` + */ +class ComponentContainer { + constructor(name) { + this.name = name; + this.providers = new Map(); + } + /** + * + * @param component Component being added + * @param overwrite When a component with the same name has already been registered, + * if overwrite is true: overwrite the existing component with the new component and create a new + * provider with the new component. It can be useful in tests where you want to use different mocks + * for different tests. + * if overwrite is false: throw an exception + */ + addComponent(component) { + const provider = this.getProvider(component.name); + if (provider.isComponentSet()) { + throw new Error(`Component ${component.name} has already been registered with ${this.name}`); + } + provider.setComponent(component); + } + addOrOverwriteComponent(component) { + const provider = this.getProvider(component.name); + if (provider.isComponentSet()) { + // delete the existing provider from the container, so we can register the new component + this.providers.delete(component.name); + } + this.addComponent(component); + } + /** + * getProvider provides a type safe interface where it can only be called with a field name + * present in NameServiceMapping interface. + * + * Firebase SDKs providing services should extend NameServiceMapping interface to register + * themselves. + */ + getProvider(name) { + if (this.providers.has(name)) { + return this.providers.get(name); + } + // create a Provider for a service that hasn't registered with Firebase + const provider = new Provider(name, this); + this.providers.set(name, provider); + return provider; + } + getProviders() { + return Array.from(this.providers.values()); + } +} + +exports.Component = Component; +exports.ComponentContainer = ComponentContainer; +exports.Provider = Provider; +//# sourceMappingURL=index.cjs.js.map diff --git a/node_modules/@firebase/component/dist/index.cjs.js.map b/node_modules/@firebase/component/dist/index.cjs.js.map new file mode 100644 index 0000000..81291c8 --- /dev/null +++ b/node_modules/@firebase/component/dist/index.cjs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.cjs.js","sources":["../src/component.ts","../src/constants.ts","../src/provider.ts","../src/component_container.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n InstantiationMode,\n InstanceFactory,\n ComponentType,\n Dictionary,\n Name,\n onInstanceCreatedCallback\n} from './types';\n\n/**\n * Component for service name T, e.g. `auth`, `auth-internal`\n */\nexport class Component {\n multipleInstances = false;\n /**\n * Properties to be added to the service namespace\n */\n serviceProps: Dictionary = {};\n\n instantiationMode = InstantiationMode.LAZY;\n\n onInstanceCreated: onInstanceCreatedCallback | null = null;\n\n /**\n *\n * @param name The public service name, e.g. app, auth, firestore, database\n * @param instanceFactory Service factory responsible for creating the public interface\n * @param type whether the service provided by the component is public or private\n */\n constructor(\n readonly name: T,\n readonly instanceFactory: InstanceFactory,\n readonly type: ComponentType\n ) {}\n\n setInstantiationMode(mode: InstantiationMode): this {\n this.instantiationMode = mode;\n return this;\n }\n\n setMultipleInstances(multipleInstances: boolean): this {\n this.multipleInstances = multipleInstances;\n return this;\n }\n\n setServiceProps(props: Dictionary): this {\n this.serviceProps = props;\n return this;\n }\n\n setInstanceCreatedCallback(callback: onInstanceCreatedCallback): this {\n this.onInstanceCreated = callback;\n return this;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const DEFAULT_ENTRY_NAME = '[DEFAULT]';\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from '@firebase/util';\nimport { ComponentContainer } from './component_container';\nimport { DEFAULT_ENTRY_NAME } from './constants';\nimport {\n InitializeOptions,\n InstantiationMode,\n Name,\n NameServiceMapping,\n OnInitCallBack\n} from './types';\nimport { Component } from './component';\n\n/**\n * Provider for instance for service name T, e.g. 'auth', 'auth-internal'\n * NameServiceMapping[T] is an alias for the type of the instance\n */\nexport class Provider {\n private component: Component | null = null;\n private readonly instances: Map = new Map();\n private readonly instancesDeferred: Map<\n string,\n Deferred\n > = new Map();\n private readonly instancesOptions: Map> =\n new Map();\n private onInitCallbacks: Map>> = new Map();\n\n constructor(\n private readonly name: T,\n private readonly container: ComponentContainer\n ) {}\n\n /**\n * @param identifier A provider can provide multiple instances of a service\n * if this.component.multipleInstances is true.\n */\n get(identifier?: string): Promise {\n // if multipleInstances is not supported, use the default name\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\n\n if (!this.instancesDeferred.has(normalizedIdentifier)) {\n const deferred = new Deferred();\n this.instancesDeferred.set(normalizedIdentifier, deferred);\n\n if (\n this.isInitialized(normalizedIdentifier) ||\n this.shouldAutoInitialize()\n ) {\n // initialize the service if it can be auto-initialized\n try {\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n });\n if (instance) {\n deferred.resolve(instance);\n }\n } catch (e) {\n // when the instance factory throws an exception during get(), it should not cause\n // a fatal error. We just return the unresolved promise in this case.\n }\n }\n }\n\n return this.instancesDeferred.get(normalizedIdentifier)!.promise;\n }\n\n /**\n *\n * @param options.identifier A provider can provide multiple instances of a service\n * if this.component.multipleInstances is true.\n * @param options.optional If optional is false or not provided, the method throws an error when\n * the service is not immediately available.\n * If optional is true, the method returns null if the service is not immediately available.\n */\n getImmediate(options: {\n identifier?: string;\n optional: true;\n }): NameServiceMapping[T] | null;\n getImmediate(options?: {\n identifier?: string;\n optional?: false;\n }): NameServiceMapping[T];\n getImmediate(options?: {\n identifier?: string;\n optional?: boolean;\n }): NameServiceMapping[T] | null {\n // if multipleInstances is not supported, use the default name\n const normalizedIdentifier = this.normalizeInstanceIdentifier(\n options?.identifier\n );\n const optional = options?.optional ?? false;\n\n if (\n this.isInitialized(normalizedIdentifier) ||\n this.shouldAutoInitialize()\n ) {\n try {\n return this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n });\n } catch (e) {\n if (optional) {\n return null;\n } else {\n throw e;\n }\n }\n } else {\n // In case a component is not initialized and should/cannot be auto-initialized at the moment, return null if the optional flag is set, or throw\n if (optional) {\n return null;\n } else {\n throw Error(`Service ${this.name} is not available`);\n }\n }\n }\n\n getComponent(): Component | null {\n return this.component;\n }\n\n setComponent(component: Component): void {\n if (component.name !== this.name) {\n throw Error(\n `Mismatching Component ${component.name} for Provider ${this.name}.`\n );\n }\n\n if (this.component) {\n throw Error(`Component for ${this.name} has already been provided`);\n }\n\n this.component = component;\n\n // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)\n if (!this.shouldAutoInitialize()) {\n return;\n }\n\n // if the service is eager, initialize the default instance\n if (isComponentEager(component)) {\n try {\n this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });\n } catch (e) {\n // when the instance factory for an eager Component throws an exception during the eager\n // initialization, it should not cause a fatal error.\n // TODO: Investigate if we need to make it configurable, because some component may want to cause\n // a fatal error in this case?\n }\n }\n\n // Create service instances for the pending promises and resolve them\n // NOTE: if this.multipleInstances is false, only the default instance will be created\n // and all promises with resolve with it regardless of the identifier.\n for (const [\n instanceIdentifier,\n instanceDeferred\n ] of this.instancesDeferred.entries()) {\n const normalizedIdentifier =\n this.normalizeInstanceIdentifier(instanceIdentifier);\n\n try {\n // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n })!;\n instanceDeferred.resolve(instance);\n } catch (e) {\n // when the instance factory throws an exception, it should not cause\n // a fatal error. We just leave the promise unresolved.\n }\n }\n }\n\n clearInstance(identifier: string = DEFAULT_ENTRY_NAME): void {\n this.instancesDeferred.delete(identifier);\n this.instancesOptions.delete(identifier);\n this.instances.delete(identifier);\n }\n\n // app.delete() will call this method on every provider to delete the services\n // TODO: should we mark the provider as deleted?\n async delete(): Promise {\n const services = Array.from(this.instances.values());\n\n await Promise.all([\n ...services\n .filter(service => 'INTERNAL' in service) // legacy services\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .map(service => (service as any).INTERNAL!.delete()),\n ...services\n .filter(service => '_delete' in service) // modularized services\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .map(service => (service as any)._delete())\n ]);\n }\n\n isComponentSet(): boolean {\n return this.component != null;\n }\n\n isInitialized(identifier: string = DEFAULT_ENTRY_NAME): boolean {\n return this.instances.has(identifier);\n }\n\n getOptions(identifier: string = DEFAULT_ENTRY_NAME): Record {\n return this.instancesOptions.get(identifier) || {};\n }\n\n initialize(opts: InitializeOptions = {}): NameServiceMapping[T] {\n const { options = {} } = opts;\n const normalizedIdentifier = this.normalizeInstanceIdentifier(\n opts.instanceIdentifier\n );\n if (this.isInitialized(normalizedIdentifier)) {\n throw Error(\n `${this.name}(${normalizedIdentifier}) has already been initialized`\n );\n }\n\n if (!this.isComponentSet()) {\n throw Error(`Component ${this.name} has not been registered yet`);\n }\n\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier,\n options\n })!;\n\n // resolve any pending promise waiting for the service instance\n for (const [\n instanceIdentifier,\n instanceDeferred\n ] of this.instancesDeferred.entries()) {\n const normalizedDeferredIdentifier =\n this.normalizeInstanceIdentifier(instanceIdentifier);\n if (normalizedIdentifier === normalizedDeferredIdentifier) {\n instanceDeferred.resolve(instance);\n }\n }\n\n return instance;\n }\n\n /**\n *\n * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().\n * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.\n *\n * @param identifier An optional instance identifier\n * @returns a function to unregister the callback\n */\n onInit(callback: OnInitCallBack, identifier?: string): () => void {\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\n const existingCallbacks =\n this.onInitCallbacks.get(normalizedIdentifier) ??\n new Set>();\n existingCallbacks.add(callback);\n this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);\n\n const existingInstance = this.instances.get(normalizedIdentifier);\n if (existingInstance) {\n callback(existingInstance, normalizedIdentifier);\n }\n\n return () => {\n existingCallbacks.delete(callback);\n };\n }\n\n /**\n * Invoke onInit callbacks synchronously\n * @param instance the service instance`\n */\n private invokeOnInitCallbacks(\n instance: NameServiceMapping[T],\n identifier: string\n ): void {\n const callbacks = this.onInitCallbacks.get(identifier);\n if (!callbacks) {\n return;\n }\n for (const callback of callbacks) {\n try {\n callback(instance, identifier);\n } catch {\n // ignore errors in the onInit callback\n }\n }\n }\n\n private getOrInitializeService({\n instanceIdentifier,\n options = {}\n }: {\n instanceIdentifier: string;\n options?: Record;\n }): NameServiceMapping[T] | null {\n let instance = this.instances.get(instanceIdentifier);\n if (!instance && this.component) {\n instance = this.component.instanceFactory(this.container, {\n instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),\n options\n });\n this.instances.set(instanceIdentifier, instance!);\n this.instancesOptions.set(instanceIdentifier, options);\n\n /**\n * Invoke onInit listeners.\n * Note this.component.onInstanceCreated is different, which is used by the component creator,\n * while onInit listeners are registered by consumers of the provider.\n */\n this.invokeOnInitCallbacks(instance!, instanceIdentifier);\n\n /**\n * Order is important\n * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which\n * makes `isInitialized()` return true.\n */\n if (this.component.onInstanceCreated) {\n try {\n this.component.onInstanceCreated(\n this.container,\n instanceIdentifier,\n instance!\n );\n } catch {\n // ignore errors in the onInstanceCreatedCallback\n }\n }\n }\n\n return instance || null;\n }\n\n private normalizeInstanceIdentifier(\n identifier: string = DEFAULT_ENTRY_NAME\n ): string {\n if (this.component) {\n return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;\n } else {\n return identifier; // assume multiple instances are supported before the component is provided.\n }\n }\n\n private shouldAutoInitialize(): boolean {\n return (\n !!this.component &&\n this.component.instantiationMode !== InstantiationMode.EXPLICIT\n );\n }\n}\n\n// undefined should be passed to the service factory for the default instance\nfunction normalizeIdentifierForFactory(identifier: string): string | undefined {\n return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;\n}\n\nfunction isComponentEager(component: Component): boolean {\n return component.instantiationMode === InstantiationMode.EAGER;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Provider } from './provider';\nimport { Component } from './component';\nimport { Name } from './types';\n\n/**\n * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`\n */\nexport class ComponentContainer {\n private readonly providers = new Map>();\n\n constructor(private readonly name: string) {}\n\n /**\n *\n * @param component Component being added\n * @param overwrite When a component with the same name has already been registered,\n * if overwrite is true: overwrite the existing component with the new component and create a new\n * provider with the new component. It can be useful in tests where you want to use different mocks\n * for different tests.\n * if overwrite is false: throw an exception\n */\n addComponent(component: Component): void {\n const provider = this.getProvider(component.name);\n if (provider.isComponentSet()) {\n throw new Error(\n `Component ${component.name} has already been registered with ${this.name}`\n );\n }\n\n provider.setComponent(component);\n }\n\n addOrOverwriteComponent(component: Component): void {\n const provider = this.getProvider(component.name);\n if (provider.isComponentSet()) {\n // delete the existing provider from the container, so we can register the new component\n this.providers.delete(component.name);\n }\n\n this.addComponent(component);\n }\n\n /**\n * getProvider provides a type safe interface where it can only be called with a field name\n * present in NameServiceMapping interface.\n *\n * Firebase SDKs providing services should extend NameServiceMapping interface to register\n * themselves.\n */\n getProvider(name: T): Provider {\n if (this.providers.has(name)) {\n return this.providers.get(name) as unknown as Provider;\n }\n\n // create a Provider for a service that hasn't registered with Firebase\n const provider = new Provider(name, this);\n this.providers.set(name, provider as unknown as Provider);\n\n return provider as Provider;\n }\n\n getProviders(): Array> {\n return Array.from(this.providers.values());\n }\n}\n"],"names":["Deferred"],"mappings":";;;;;;AAyBA;;AAEG;MACU,SAAS,CAAA;AAWpB;;;;;AAKG;AACH,IAAA,WAAA,CACW,IAAO,EACP,eAAmC,EACnC,IAAmB,EAAA;QAFnB,IAAI,CAAA,IAAA,GAAJ,IAAI,CAAG;QACP,IAAe,CAAA,eAAA,GAAf,eAAe,CAAoB;QACnC,IAAI,CAAA,IAAA,GAAJ,IAAI,CAAe;QAnB9B,IAAiB,CAAA,iBAAA,GAAG,KAAK,CAAC;AAC1B;;AAEG;QACH,IAAY,CAAA,YAAA,GAAe,EAAE,CAAC;AAE9B,QAAA,IAAA,CAAA,iBAAiB,GAA0B,MAAA,8BAAA;QAE3C,IAAiB,CAAA,iBAAA,GAAwC,IAAI,CAAC;KAY1D;AAEJ,IAAA,oBAAoB,CAAC,IAAuB,EAAA;AAC1C,QAAA,IAAI,CAAC,iBAAiB,GAAG,IAAI,CAAC;AAC9B,QAAA,OAAO,IAAI,CAAC;KACb;AAED,IAAA,oBAAoB,CAAC,iBAA0B,EAAA;AAC7C,QAAA,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;AAC3C,QAAA,OAAO,IAAI,CAAC;KACb;AAED,IAAA,eAAe,CAAC,KAAiB,EAAA;AAC/B,QAAA,IAAI,CAAC,YAAY,GAAG,KAAK,CAAC;AAC1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AED,IAAA,uBAAuB,CAAiB,SAAuB,EAAA;QAC7D,MAAM,QAAQ,GAAG,IAAI,CAAC,WAAW,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;AAClD,QAAA,IAAI,QAAQ,CAAC,cAAc,EAAE,EAAE;;YAE7B,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;SACvC;AAED,QAAA,IAAI,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;KAC9B;AAED;;;;;;AAMG;AACH,IAAA,WAAW,CAAiB,IAAO,EAAA;QACjC,IAAI,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE;YAC5B,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAA2B,CAAC;SAC3D;;QAGD,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAAI,IAAI,EAAE,IAAI,CAAC,CAAC;QAC7C,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,QAAqC,CAAC,CAAC;AAEhE,QAAA,OAAO,QAAuB,CAAC;KAChC;IAED,YAAY,GAAA;QACV,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC,CAAC;KAC5C;AACF;;;;;;"} \ No newline at end of file diff --git a/node_modules/@firebase/component/dist/index.d.ts b/node_modules/@firebase/component/dist/index.d.ts new file mode 100644 index 0000000..7b21e7b --- /dev/null +++ b/node_modules/@firebase/component/dist/index.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { Component } from './src/component'; +export { ComponentContainer } from './src/component_container'; +export { Provider } from './src/provider'; +export { ComponentType, InstanceFactory, InstantiationMode, NameServiceMapping, Name, InstanceFactoryOptions } from './src/types'; diff --git a/node_modules/@firebase/component/dist/src/component.d.ts b/node_modules/@firebase/component/dist/src/component.d.ts new file mode 100644 index 0000000..debdf77 --- /dev/null +++ b/node_modules/@firebase/component/dist/src/component.d.ts @@ -0,0 +1,43 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { InstantiationMode, InstanceFactory, ComponentType, Dictionary, Name, onInstanceCreatedCallback } from './types'; +/** + * Component for service name T, e.g. `auth`, `auth-internal` + */ +export declare class Component { + readonly name: T; + readonly instanceFactory: InstanceFactory; + readonly type: ComponentType; + multipleInstances: boolean; + /** + * Properties to be added to the service namespace + */ + serviceProps: Dictionary; + instantiationMode: InstantiationMode; + onInstanceCreated: onInstanceCreatedCallback | null; + /** + * + * @param name The public service name, e.g. app, auth, firestore, database + * @param instanceFactory Service factory responsible for creating the public interface + * @param type whether the service provided by the component is public or private + */ + constructor(name: T, instanceFactory: InstanceFactory, type: ComponentType); + setInstantiationMode(mode: InstantiationMode): this; + setMultipleInstances(multipleInstances: boolean): this; + setServiceProps(props: Dictionary): this; + setInstanceCreatedCallback(callback: onInstanceCreatedCallback): this; +} diff --git a/node_modules/@firebase/component/dist/src/component_container.d.ts b/node_modules/@firebase/component/dist/src/component_container.d.ts new file mode 100644 index 0000000..a1322f3 --- /dev/null +++ b/node_modules/@firebase/component/dist/src/component_container.d.ts @@ -0,0 +1,47 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Provider } from './provider'; +import { Component } from './component'; +import { Name } from './types'; +/** + * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal` + */ +export declare class ComponentContainer { + private readonly name; + private readonly providers; + constructor(name: string); + /** + * + * @param component Component being added + * @param overwrite When a component with the same name has already been registered, + * if overwrite is true: overwrite the existing component with the new component and create a new + * provider with the new component. It can be useful in tests where you want to use different mocks + * for different tests. + * if overwrite is false: throw an exception + */ + addComponent(component: Component): void; + addOrOverwriteComponent(component: Component): void; + /** + * getProvider provides a type safe interface where it can only be called with a field name + * present in NameServiceMapping interface. + * + * Firebase SDKs providing services should extend NameServiceMapping interface to register + * themselves. + */ + getProvider(name: T): Provider; + getProviders(): Array>; +} diff --git a/node_modules/@firebase/component/dist/src/constants.d.ts b/node_modules/@firebase/component/dist/src/constants.d.ts new file mode 100644 index 0000000..b069f4e --- /dev/null +++ b/node_modules/@firebase/component/dist/src/constants.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const DEFAULT_ENTRY_NAME = "[DEFAULT]"; diff --git a/node_modules/@firebase/component/dist/src/provider.d.ts b/node_modules/@firebase/component/dist/src/provider.d.ts new file mode 100644 index 0000000..8039aff --- /dev/null +++ b/node_modules/@firebase/component/dist/src/provider.d.ts @@ -0,0 +1,79 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ComponentContainer } from './component_container'; +import { InitializeOptions, Name, NameServiceMapping, OnInitCallBack } from './types'; +import { Component } from './component'; +/** + * Provider for instance for service name T, e.g. 'auth', 'auth-internal' + * NameServiceMapping[T] is an alias for the type of the instance + */ +export declare class Provider { + private readonly name; + private readonly container; + private component; + private readonly instances; + private readonly instancesDeferred; + private readonly instancesOptions; + private onInitCallbacks; + constructor(name: T, container: ComponentContainer); + /** + * @param identifier A provider can provide multiple instances of a service + * if this.component.multipleInstances is true. + */ + get(identifier?: string): Promise; + /** + * + * @param options.identifier A provider can provide multiple instances of a service + * if this.component.multipleInstances is true. + * @param options.optional If optional is false or not provided, the method throws an error when + * the service is not immediately available. + * If optional is true, the method returns null if the service is not immediately available. + */ + getImmediate(options: { + identifier?: string; + optional: true; + }): NameServiceMapping[T] | null; + getImmediate(options?: { + identifier?: string; + optional?: false; + }): NameServiceMapping[T]; + getComponent(): Component | null; + setComponent(component: Component): void; + clearInstance(identifier?: string): void; + delete(): Promise; + isComponentSet(): boolean; + isInitialized(identifier?: string): boolean; + getOptions(identifier?: string): Record; + initialize(opts?: InitializeOptions): NameServiceMapping[T]; + /** + * + * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize(). + * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program. + * + * @param identifier An optional instance identifier + * @returns a function to unregister the callback + */ + onInit(callback: OnInitCallBack, identifier?: string): () => void; + /** + * Invoke onInit callbacks synchronously + * @param instance the service instance` + */ + private invokeOnInitCallbacks; + private getOrInitializeService; + private normalizeInstanceIdentifier; + private shouldAutoInitialize; +} diff --git a/node_modules/@firebase/component/dist/src/types.d.ts b/node_modules/@firebase/component/dist/src/types.d.ts new file mode 100644 index 0000000..40eac68 --- /dev/null +++ b/node_modules/@firebase/component/dist/src/types.d.ts @@ -0,0 +1,62 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ComponentContainer } from './component_container'; +export declare const enum InstantiationMode { + LAZY = "LAZY",// Currently most components are LAZY in JS SDK + EAGER = "EAGER",// EAGER components are initialized immediately upon registration + EXPLICIT = "EXPLICIT" +} +/** + * PUBLIC: A public component provides a set of public APIs to customers. A service namespace will be patched + * onto `firebase` namespace. Assume the component name is `test`, customers will be able + * to get the service by calling `firebase.test()` or `app.test()` where `app` is a `FirebaseApp` instance. + * + * PRIVATE: A private component provides a set of private APIs that are used internally by other + * Firebase SDKs. No service namespace is created in `firebase` namespace and customers have no way to get them. + */ +export declare const enum ComponentType { + PUBLIC = "PUBLIC", + PRIVATE = "PRIVATE", + VERSION = "VERSION" +} +export interface InstanceFactoryOptions { + instanceIdentifier?: string; + options?: {}; +} +export type InitializeOptions = InstanceFactoryOptions; +/** + * Factory to create an instance of type T, given a ComponentContainer. + * ComponentContainer is the IOC container that provides {@link Provider} + * for dependencies. + * + * NOTE: The container only provides {@link Provider} rather than the actual instances of dependencies. + * It is useful for lazily loaded dependencies and optional dependencies. + */ +export type InstanceFactory = (container: ComponentContainer, options: InstanceFactoryOptions) => NameServiceMapping[T]; +export type onInstanceCreatedCallback = (container: ComponentContainer, instanceIdentifier: string, instance: NameServiceMapping[T]) => void; +export interface Dictionary { + [key: string]: unknown; +} +/** + * This interface will be extended by Firebase SDKs to provide service name and service type mapping. + * It is used as a generic constraint to ensure type safety. + */ +export interface NameServiceMapping { +} +export type Name = keyof NameServiceMapping; +export type Service = NameServiceMapping[Name]; +export type OnInitCallBack = (instance: NameServiceMapping[T], identifier: string) => void; diff --git a/node_modules/@firebase/component/dist/test/setup.d.ts b/node_modules/@firebase/component/dist/test/setup.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/node_modules/@firebase/component/dist/test/setup.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/component/dist/test/util.d.ts b/node_modules/@firebase/component/dist/test/util.d.ts new file mode 100644 index 0000000..93dbf0a --- /dev/null +++ b/node_modules/@firebase/component/dist/test/util.d.ts @@ -0,0 +1,5 @@ +import { FirebaseApp } from '@firebase/app-types'; +import { InstanceFactory, InstantiationMode, Name } from '../src/types'; +import { Component } from '../src/component'; +export declare function getFakeApp(appName?: string): FirebaseApp; +export declare function getFakeComponent(name: T, factory: InstanceFactory, multipleInstance?: boolean, instantiationMode?: InstantiationMode): Component; diff --git a/node_modules/@firebase/component/package.json b/node_modules/@firebase/component/package.json new file mode 100644 index 0000000..2b475f1 --- /dev/null +++ b/node_modules/@firebase/component/package.json @@ -0,0 +1,61 @@ +{ + "name": "@firebase/component", + "version": "0.7.0", + "description": "Firebase Component Platform", + "author": "Firebase (https://firebase.google.com/)", + "main": "dist/index.cjs.js", + "browser": "dist/esm/index.esm.js", + "module": "dist/esm/index.esm.js", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "require": "./dist/index.cjs.js", + "default": "./dist/esm/index.esm.js" + }, + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "scripts": { + "lint": "eslint -c .eslintrc.js '**/*.ts' --ignore-path '../../.gitignore'", + "lint:fix": "eslint --fix -c .eslintrc.js '**/*.ts' --ignore-path '../../.gitignore'", + "build": "rollup -c", + "build:deps": "lerna run --scope @firebase/component --include-dependencies build", + "dev": "rollup -c -w", + "test": "run-p --npm-path npm lint test:all", + "test:all": "run-p --npm-path npm test:browser test:node", + "test:ci": "node ../../scripts/run_tests_in_ci.js -s test:all", + "test:browser": "karma start", + "test:node": "TS_NODE_COMPILER_OPTIONS='{\"module\":\"commonjs\"}' nyc --reporter lcovonly -- mocha src/**/*.test.ts --config ../../config/mocharc.node.js", + "trusted-type-check": "tsec -p tsconfig.json --noEmit" + }, + "dependencies": { + "@firebase/util": "1.13.0", + "tslib": "^2.1.0" + }, + "license": "Apache-2.0", + "devDependencies": { + "rollup": "2.79.2", + "rollup-plugin-typescript2": "0.36.0", + "typescript": "5.5.4" + }, + "repository": { + "directory": "packages/component", + "type": "git", + "url": "git+https://github.com/firebase/firebase-js-sdk.git" + }, + "bugs": { + "url": "https://github.com/firebase/firebase-js-sdk/issues" + }, + "typings": "dist/index.d.ts", + "nyc": { + "extension": [ + ".ts" + ], + "reportDir": "./coverage/node" + }, + "engines": { + "node": ">=20.0.0" + } +} diff --git a/node_modules/@firebase/database-compat/README.md b/node_modules/@firebase/database-compat/README.md new file mode 100644 index 0000000..656ab83 --- /dev/null +++ b/node_modules/@firebase/database-compat/README.md @@ -0,0 +1,5 @@ +# @firebase/database-compat + +This is the compatibility layer for the Firebase Realtime Database component of the Firebase JS SDK. + +**This package is not intended for direct usage, and should only be used via the officially supported [firebase](https://www.npmjs.com/package/firebase) package.** diff --git a/node_modules/@firebase/database-compat/dist/database-compat/src/api/Database.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/src/api/Database.d.ts new file mode 100644 index 0000000..d08f4ee --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/src/api/Database.d.ts @@ -0,0 +1,74 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app-types'; +import { FirebaseService } from '@firebase/app-types/private'; +import { forceLongPolling, forceWebSockets, Database as ModularDatabase } from '@firebase/database'; +import { Compat, EmulatorMockTokenOptions } from '@firebase/util'; +import { Reference } from './Reference'; +/** + * Class representing a firebase database. + */ +export declare class Database implements FirebaseService, Compat { + readonly _delegate: ModularDatabase; + readonly app: FirebaseApp; + static readonly ServerValue: { + TIMESTAMP: object; + increment: (delta: number) => object; + }; + /** + * The constructor should not be called by users of our public API. + */ + constructor(_delegate: ModularDatabase, app: FirebaseApp); + INTERNAL: { + delete: () => Promise; + forceWebSockets: typeof forceWebSockets; + forceLongPolling: typeof forceLongPolling; + }; + /** + * Modify this instance to communicate with the Realtime Database emulator. + * + *

Note: This method must be called before performing any other operation. + * + * @param host - the emulator host (ex: localhost) + * @param port - the emulator port (ex: 8080) + * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules + */ + useEmulator(host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions; + }): void; + /** + * Returns a reference to the root or to the path specified in the provided + * argument. + * + * @param path - The relative string path or an existing Reference to a database + * location. + * @throws If a Reference is provided, throws if it does not belong to the + * same project. + * @returns Firebase reference. + */ + ref(path?: string): Reference; + ref(path?: Reference): Reference; + /** + * Returns a reference to the root or the path specified in url. + * We throw a exception if the url is not in the same domain as the + * current repo. + * @returns Firebase reference. + */ + refFromURL(url: string): Reference; + goOffline(): void; + goOnline(): void; +} diff --git a/node_modules/@firebase/database-compat/dist/database-compat/src/api/Reference.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/src/api/Reference.d.ts new file mode 100644 index 0000000..f7f20c5 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/src/api/Reference.d.ts @@ -0,0 +1,207 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DataSnapshot as ModularDataSnapshot, Query as ExpQuery, DatabaseReference as ModularReference } from '@firebase/database'; +import { Compat } from '@firebase/util'; +import { Database } from './Database'; +import { OnDisconnect } from './onDisconnect'; +import { TransactionResult } from './TransactionResult'; +/** + * Class representing a firebase data snapshot. It wraps a SnapshotNode and + * surfaces the public methods (val, forEach, etc.) we want to expose. + */ +export declare class DataSnapshot implements Compat { + readonly _database: Database; + readonly _delegate: ModularDataSnapshot; + constructor(_database: Database, _delegate: ModularDataSnapshot); + /** + * Retrieves the snapshot contents as JSON. Returns null if the snapshot is + * empty. + * + * @returns JSON representation of the DataSnapshot contents, or null if empty. + */ + val(): unknown; + /** + * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting + * the entire node contents. + * @returns JSON representation of the DataSnapshot contents, or null if empty. + */ + exportVal(): unknown; + toJSON(): unknown; + /** + * Returns whether the snapshot contains a non-null value. + * + * @returns Whether the snapshot contains a non-null value, or is empty. + */ + exists(): boolean; + /** + * Returns a DataSnapshot of the specified child node's contents. + * + * @param path - Path to a child. + * @returns DataSnapshot for child node. + */ + child(path: string): DataSnapshot; + /** + * Returns whether the snapshot contains a child at the specified path. + * + * @param path - Path to a child. + * @returns Whether the child exists. + */ + hasChild(path: string): boolean; + /** + * Returns the priority of the object, or null if no priority was set. + * + * @returns The priority. + */ + getPriority(): string | number | null; + /** + * Iterates through child nodes and calls the specified action for each one. + * + * @param action - Callback function to be called + * for each child. + * @returns True if forEach was canceled by action returning true for + * one of the child nodes. + */ + forEach(action: (snapshot: IteratedDataSnapshot) => boolean | void): boolean; + /** + * Returns whether this DataSnapshot has children. + * @returns True if the DataSnapshot contains 1 or more child nodes. + */ + hasChildren(): boolean; + get key(): string; + /** + * Returns the number of children for this DataSnapshot. + * @returns The number of children that this DataSnapshot contains. + */ + numChildren(): number; + /** + * @returns The Firebase reference for the location this snapshot's data came + * from. + */ + getRef(): Reference; + get ref(): Reference; +} +/** + * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined. + */ +export interface IteratedDataSnapshot extends DataSnapshot { + key: string; +} +export interface SnapshotCallback { + (dataSnapshot: DataSnapshot, previousChildName?: string | null): unknown; +} +/** + * A Query represents a filter to be applied to a firebase location. This object purely represents the + * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js. + * + * Since every Firebase reference is a query, Firebase inherits from this object. + */ +export declare class Query implements Compat { + readonly database: Database; + readonly _delegate: ExpQuery; + constructor(database: Database, _delegate: ExpQuery); + on(eventType: string, callback: SnapshotCallback, cancelCallbackOrContext?: ((a: Error) => unknown) | object | null, context?: object | null): SnapshotCallback; + off(eventType?: string, callback?: SnapshotCallback, context?: object | null): void; + /** + * Get the server-value for this query, or return a cached value if not connected. + */ + get(): Promise; + /** + * Attaches a listener, waits for the first event, and then removes the listener + */ + once(eventType: string, callback?: SnapshotCallback, failureCallbackOrContext?: ((a: Error) => void) | object | null, context?: object | null): Promise; + /** + * Set a limit and anchor it to the start of the window. + */ + limitToFirst(limit: number): Query; + /** + * Set a limit and anchor it to the end of the window. + */ + limitToLast(limit: number): Query; + /** + * Given a child path, return a new query ordered by the specified grandchild path. + */ + orderByChild(path: string): Query; + /** + * Return a new query ordered by the KeyIndex + */ + orderByKey(): Query; + /** + * Return a new query ordered by the PriorityIndex + */ + orderByPriority(): Query; + /** + * Return a new query ordered by the ValueIndex + */ + orderByValue(): Query; + startAt(value?: number | string | boolean | null, name?: string | null): Query; + startAfter(value?: number | string | boolean | null, name?: string | null): Query; + endAt(value?: number | string | boolean | null, name?: string | null): Query; + endBefore(value?: number | string | boolean | null, name?: string | null): Query; + /** + * Load the selection of children with exactly the specified value, and, optionally, + * the specified name. + */ + equalTo(value: number | string | boolean | null, name?: string): Query; + /** + * @returns URL for this location. + */ + toString(): string; + toJSON(): string; + /** + * Return true if this query and the provided query are equivalent; otherwise, return false. + */ + isEqual(other: Query): boolean; + /** + * Helper used by .on and .once to extract the context and or cancel arguments. + * @param fnName - The function name (on or once) + * + */ + private static getCancelAndContextArgs_; + get ref(): Reference; +} +export declare class Reference extends Query implements Compat { + readonly database: Database; + readonly _delegate: ModularReference; + then: Promise['then']; + catch: Promise['catch']; + /** + * Call options: + * new Reference(Repo, Path) or + * new Reference(url: string, string|RepoManager) + * + * Externally - this is the firebase.database.Reference type. + */ + constructor(database: Database, _delegate: ModularReference); + /** @returns {?string} */ + getKey(): string | null; + child(pathString: string): Reference; + /** @returns {?Reference} */ + getParent(): Reference | null; + /** @returns {!Reference} */ + getRoot(): Reference; + set(newVal: unknown, onComplete?: (error: Error | null) => void): Promise; + update(values: object, onComplete?: (a: Error | null) => void): Promise; + setWithPriority(newVal: unknown, newPriority: string | number | null, onComplete?: (a: Error | null) => void): Promise; + remove(onComplete?: (a: Error | null) => void): Promise; + transaction(transactionUpdate: (currentData: unknown) => unknown, onComplete?: (error: Error | null, committed: boolean, dataSnapshot: DataSnapshot | null) => void, applyLocally?: boolean): Promise; + setPriority(priority: string | number | null, onComplete?: (a: Error | null) => void): Promise; + push(value?: unknown, onComplete?: (a: Error | null) => void): Reference; + onDisconnect(): OnDisconnect; + get key(): string | null; + get parent(): Reference | null; + get root(): Reference; +} diff --git a/node_modules/@firebase/database-compat/dist/database-compat/src/api/TransactionResult.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/src/api/TransactionResult.d.ts new file mode 100644 index 0000000..b547b76 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/src/api/TransactionResult.d.ts @@ -0,0 +1,26 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DataSnapshot } from './Reference'; +export declare class TransactionResult { + committed: boolean; + snapshot: DataSnapshot; + /** + * A type for the resolve value of Firebase.transaction. + */ + constructor(committed: boolean, snapshot: DataSnapshot); + toJSON(): object; +} diff --git a/node_modules/@firebase/database-compat/dist/database-compat/src/api/internal.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/src/api/internal.d.ts new file mode 100644 index 0000000..458eb4f --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/src/api/internal.d.ts @@ -0,0 +1,41 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseAppCheckInternal } from '@firebase/app-check-interop-types'; +import { FirebaseApp } from '@firebase/app-types'; +import { FirebaseAuthInternal } from '@firebase/auth-interop-types'; +import * as types from '@firebase/database-types'; +/** + * Used by console to create a database based on the app, + * passed database URL and a custom auth implementation. + * + * @param app - A valid FirebaseApp-like object + * @param url - A valid Firebase databaseURL + * @param version - custom version e.g. firebase-admin version + * @param customAuthImpl - custom auth implementation + */ +export declare function initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, namespace, nodeAdmin }: { + app: FirebaseApp; + url: string; + version: string; + customAuthImpl: FirebaseAuthInternal; + customAppCheckImpl?: FirebaseAppCheckInternal; + namespace: T; + nodeAdmin?: boolean; +}): { + instance: types.Database; + namespace: T; +}; diff --git a/node_modules/@firebase/database-compat/dist/database-compat/src/api/onDisconnect.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/src/api/onDisconnect.d.ts new file mode 100644 index 0000000..103874e --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/src/api/onDisconnect.d.ts @@ -0,0 +1,27 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { OnDisconnect as ModularOnDisconnect } from '@firebase/database'; +import { Compat } from '@firebase/util'; +export declare class OnDisconnect implements Compat { + readonly _delegate: ModularOnDisconnect; + constructor(_delegate: ModularOnDisconnect); + cancel(onComplete?: (a: Error | null) => void): Promise; + remove(onComplete?: (a: Error | null) => void): Promise; + set(value: unknown, onComplete?: (a: Error | null) => void): Promise; + setWithPriority(value: unknown, priority: number | string | null, onComplete?: (a: Error | null) => void): Promise; + update(objectToMerge: Record, onComplete?: (a: Error | null) => void): Promise; +} diff --git a/node_modules/@firebase/database-compat/dist/database-compat/src/index.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/src/index.d.ts new file mode 100644 index 0000000..4830a07 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/src/index.d.ts @@ -0,0 +1,72 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseNamespace } from '@firebase/app-compat'; +import * as types from '@firebase/database-types'; +export declare function registerDatabase(instance: FirebaseNamespace): void; +declare module '@firebase/app-compat' { + interface FirebaseNamespace { + database?: { + (app?: FirebaseApp): types.FirebaseDatabase; + enableLogging: typeof types.enableLogging; + ServerValue: types.ServerValue; + Database: typeof types.FirebaseDatabase; + }; + } + interface FirebaseApp { + database?(databaseURL?: string): types.FirebaseDatabase; + } +} + +import { FirebaseApp as FirebaseAppCompat } from "@firebase/app-compat"; +import { type DatabaseReference, type EmulatorMockTokenOptions, type DataSnapshot, type Database, type EventType, type Unsubscribe, type ListenOptions, type OnDisconnect, type ThenableReference, type QueryConstraint, type Query, type TransactionOptions, type TransactionResult } from "@firebase/database"; +declare module "@firebase/database" { + function child(parent: types.Reference, path: string): DatabaseReference; + function connectDatabaseEmulator(db: types.FirebaseDatabase, host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions | string; + }): void; + function get(query: types.Query): Promise; + function getDatabase(app?: FirebaseAppCompat, url?: string): Database; + function goOffline(db: types.FirebaseDatabase): void; + function goOnline(db: types.FirebaseDatabase): void; + function off(query: types.Query, eventType?: EventType, callback?: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown): void; + function onChildAdded(query: types.Query, callback: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; + function onChildAdded(query: types.Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe; + function onChildAdded(query: types.Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; + function onChildChanged(query: types.Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; + function onChildChanged(query: types.Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe; + function onChildChanged(query: types.Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; + function onChildMoved(query: types.Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; + function onChildMoved(query: types.Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe; + function onChildMoved(query: types.Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; + function onChildRemoved(query: types.Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; + function onChildRemoved(query: types.Query, callback: (snapshot: DataSnapshot) => unknown, options: ListenOptions): Unsubscribe; + function onChildRemoved(query: types.Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; + function onDisconnect(ref: types.Reference): OnDisconnect; + function onValue(query: types.Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; + function onValue(query: types.Query, callback: (snapshot: DataSnapshot) => unknown, options: ListenOptions): Unsubscribe; + function onValue(query: types.Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; + function push(parent: types.Reference, value?: unknown): ThenableReference; + function query(query: types.Query, ...queryConstraints: QueryConstraint[]): Query; + function ref(db: types.FirebaseDatabase, path?: string): DatabaseReference; + function refFromURL(db: types.FirebaseDatabase, url: string): DatabaseReference; + function remove(ref: types.Reference): Promise; + function runTransaction(ref: types.Reference, transactionUpdate: (currentData: any) => unknown, options?: TransactionOptions): Promise; + function set(ref: types.Reference, value: unknown): Promise; + function setPriority(ref: types.Reference, priority: string | number | null): Promise; + function setWithPriority(ref: types.Reference, value: unknown, priority: string | number | null): Promise; + function update(ref: types.Reference, values: object): Promise; +} diff --git a/node_modules/@firebase/database-compat/dist/database-compat/src/index.node.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/src/index.node.d.ts new file mode 100644 index 0000000..0e048c8 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/src/index.node.d.ts @@ -0,0 +1,30 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as types from '@firebase/database-types'; +declare module '@firebase/app-compat' { + interface FirebaseNamespace { + database?: { + (app?: FirebaseApp): types.FirebaseDatabase; + enableLogging: typeof types.enableLogging; + ServerValue: types.ServerValue; + Database: typeof types.FirebaseDatabase; + }; + } + interface FirebaseApp { + database?(): types.FirebaseDatabase; + } +} diff --git a/node_modules/@firebase/database-compat/dist/database-compat/src/index.standalone.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/src/index.standalone.d.ts new file mode 100644 index 0000000..02f3e9b --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/src/index.standalone.d.ts @@ -0,0 +1,52 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app-types'; +import { enableLogging } from '@firebase/database'; +import { Database } from './api/Database'; +import * as INTERNAL from './api/internal'; +import { DataSnapshot, Query, Reference } from './api/Reference'; +declare const ServerValue: { + TIMESTAMP: object; + increment: (delta: number) => object; +}; +/** + * A one off register function which returns a database based on the app and + * passed database URL. (Used by the Admin SDK) + * + * @param app - A valid FirebaseApp-like object + * @param url - A valid Firebase databaseURL + * @param version - custom version e.g. firebase-admin version + * @param nodeAdmin - true if the SDK is being initialized from Firebase Admin. + */ +export declare function initStandalone(app: FirebaseApp, url: string, version: string, nodeAdmin?: boolean): { + instance: import("@firebase/database-types").Database; + namespace: { + Reference: typeof Reference; + Query: typeof Query; + Database: typeof Database; + DataSnapshot: typeof DataSnapshot; + enableLogging: typeof enableLogging; + INTERNAL: typeof INTERNAL; + ServerValue: { + TIMESTAMP: object; + increment: (delta: number) => object; + }; + }; +}; +export { Database, Query, Reference, enableLogging, ServerValue }; +export { OnDisconnect } from '@firebase/database'; +export { DataSnapshot } from './api/Reference'; diff --git a/node_modules/@firebase/database-compat/dist/database-compat/src/util/util.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/src/util/util.d.ts new file mode 100644 index 0000000..4d5ad77 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/src/util/util.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const warn: (msg: string) => void; diff --git a/node_modules/@firebase/database-compat/dist/database-compat/src/util/validation.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/src/util/validation.d.ts new file mode 100644 index 0000000..bf47035 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/src/util/validation.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const validateBoolean: (fnName: string, argumentName: string, bool: unknown, optional: boolean) => void; +export declare const validateEventType: (fnName: string, eventType: string, optional: boolean) => void; diff --git a/node_modules/@firebase/database-compat/dist/database-compat/test/browser/crawler_support.test.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/test/browser/crawler_support.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/test/browser/crawler_support.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/database-compat/dist/database-compat/test/database.test.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/test/database.test.d.ts new file mode 100644 index 0000000..cdaeff3 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/test/database.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import '../src/index'; diff --git a/node_modules/@firebase/database-compat/dist/database-compat/test/datasnapshot.test.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/test/datasnapshot.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/test/datasnapshot.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/database-compat/dist/database-compat/test/helpers/events.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/test/helpers/events.d.ts new file mode 100644 index 0000000..58d323c --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/test/helpers/events.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A set of functions to clean up event handlers. + */ +export declare let eventCleanupHandlers: any[]; +/** Clean up outstanding event handlers */ +export declare function eventCleanup(): void; +/** + * Creates a struct which waits for many events. + * @param pathAndEvents - an array of tuples of [Firebase, [event type strings]] + */ +export declare function eventTestHelper(pathAndEvents: any, helperName?: any): { + promise: Promise; + initPromise: Promise; + waiter: () => boolean; + watchesInitializedWaiter: () => boolean; + unregister: () => void; + addExpectedEvents(moreEvents: any): void; +}; diff --git a/node_modules/@firebase/database-compat/dist/database-compat/test/helpers/util.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/test/helpers/util.d.ts new file mode 100644 index 0000000..5f56191 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/test/helpers/util.d.ts @@ -0,0 +1,42 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import '../../src/index'; +import { Path } from '../../../database/src/core/util/Path'; +import { Query, Reference } from '../../src/api/Reference'; +export declare const TEST_PROJECT: any; +export declare const DATABASE_ADDRESS: any; +export declare const DATABASE_URL: any; +export declare function createTestApp(): import("@firebase/app-compat").FirebaseApp; +/** + * Gets or creates a root node to the test namespace. All calls sharing the + * value of opt_i will share an app context. + */ +export declare function getRootNode(i?: number, ref?: string): any; +/** + * Create multiple refs to the same top level + * push key - each on its own Firebase.Context. + */ +export declare function getRandomNode(numNodes?: any): Reference | Reference[]; +export declare function getQueryValue(query: Query): Promise; +export declare function pause(milliseconds: number): Promise; +export declare function getPath(query: Query): string; +export declare function shuffle(arr: any, randFn?: () => number): void; +export declare function getFreshRepo(path: Path): any; +export declare function getFreshRepoFromReference(ref: any): any; +export declare function getSnap(path: any): any; +export declare function getVal(path: any): any; +export declare function canCreateExtraConnections(): boolean; diff --git a/node_modules/@firebase/database-compat/dist/database-compat/test/info.test.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/test/info.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/test/info.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/database-compat/dist/database-compat/test/order.test.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/test/order.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/test/order.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/database-compat/dist/database-compat/test/order_by.test.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/test/order_by.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/test/order_by.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/database-compat/dist/database-compat/test/promise.test.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/test/promise.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/test/promise.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/database-compat/dist/database-compat/test/query.test.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/test/query.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/test/query.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/database-compat/dist/database-compat/test/servervalues.test.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/test/servervalues.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/test/servervalues.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/database-compat/dist/database-compat/test/transaction.test.d.ts b/node_modules/@firebase/database-compat/dist/database-compat/test/transaction.test.d.ts new file mode 100644 index 0000000..cdaeff3 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/database-compat/test/transaction.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import '../src/index'; diff --git a/node_modules/@firebase/database-compat/dist/index.esm.js b/node_modules/@firebase/database-compat/dist/index.esm.js new file mode 100644 index 0000000..c895c89 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/index.esm.js @@ -0,0 +1,860 @@ +import firebase from '@firebase/app-compat'; +import { ComponentContainer, Provider, Component } from '@firebase/component'; +import { _validatePathString, onChildMoved, onChildChanged, onChildRemoved, onChildAdded, onValue, off, get, query, limitToFirst, limitToLast, orderByChild, orderByKey, orderByPriority, orderByValue, startAt, startAfter, endAt, endBefore, equalTo, _ReferenceImpl, _QueryImpl, _QueryParams, child, set, _validateWritablePath, update, setWithPriority, remove, runTransaction, setPriority, push, OnDisconnect as OnDisconnect$1, forceWebSockets, forceLongPolling, connectDatabaseEmulator, refFromURL, ref, goOffline, goOnline, serverTimestamp, increment, _setSDKVersion, _repoManagerDatabaseFromApp, enableLogging } from '@firebase/database'; +import { errorPrefix, validateArgCount, validateCallback, validateContextObject, Deferred } from '@firebase/util'; +import { Logger } from '@firebase/logger'; + +const name = "@firebase/database-compat"; +const version = "2.1.0"; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const logClient = new Logger('@firebase/database-compat'); +const warn = function (msg) { + const message = 'FIREBASE WARNING: ' + msg; + logClient.warn(message); +}; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const validateBoolean = function (fnName, argumentName, bool, optional) { + if (optional && bool === undefined) { + return; + } + if (typeof bool !== 'boolean') { + throw new Error(errorPrefix(fnName, argumentName) + 'must be a boolean.'); + } +}; +const validateEventType = function (fnName, eventType, optional) { + if (optional && eventType === undefined) { + return; + } + switch (eventType) { + case 'value': + case 'child_added': + case 'child_removed': + case 'child_changed': + case 'child_moved': + break; + default: + throw new Error(errorPrefix(fnName, 'eventType') + + 'must be a valid event type = "value", "child_added", "child_removed", ' + + '"child_changed", or "child_moved".'); + } +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class OnDisconnect { + constructor(_delegate) { + this._delegate = _delegate; + } + cancel(onComplete) { + validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length); + validateCallback('OnDisconnect.cancel', 'onComplete', onComplete, true); + const result = this._delegate.cancel(); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + remove(onComplete) { + validateArgCount('OnDisconnect.remove', 0, 1, arguments.length); + validateCallback('OnDisconnect.remove', 'onComplete', onComplete, true); + const result = this._delegate.remove(); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + set(value, onComplete) { + validateArgCount('OnDisconnect.set', 1, 2, arguments.length); + validateCallback('OnDisconnect.set', 'onComplete', onComplete, true); + const result = this._delegate.set(value); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + setWithPriority(value, priority, onComplete) { + validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length); + validateCallback('OnDisconnect.setWithPriority', 'onComplete', onComplete, true); + const result = this._delegate.setWithPriority(value, priority); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + update(objectToMerge, onComplete) { + validateArgCount('OnDisconnect.update', 1, 2, arguments.length); + if (Array.isArray(objectToMerge)) { + const newObjectToMerge = {}; + for (let i = 0; i < objectToMerge.length; ++i) { + newObjectToMerge['' + i] = objectToMerge[i]; + } + objectToMerge = newObjectToMerge; + warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' + + 'existing data, or an Object with integer keys if you really do want to only update some of the children.'); + } + validateCallback('OnDisconnect.update', 'onComplete', onComplete, true); + const result = this._delegate.update(objectToMerge); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class TransactionResult { + /** + * A type for the resolve value of Firebase.transaction. + */ + constructor(committed, snapshot) { + this.committed = committed; + this.snapshot = snapshot; + } + // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary + // for end-users + toJSON() { + validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length); + return { committed: this.committed, snapshot: this.snapshot.toJSON() }; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Class representing a firebase data snapshot. It wraps a SnapshotNode and + * surfaces the public methods (val, forEach, etc.) we want to expose. + */ +class DataSnapshot { + constructor(_database, _delegate) { + this._database = _database; + this._delegate = _delegate; + } + /** + * Retrieves the snapshot contents as JSON. Returns null if the snapshot is + * empty. + * + * @returns JSON representation of the DataSnapshot contents, or null if empty. + */ + val() { + validateArgCount('DataSnapshot.val', 0, 0, arguments.length); + return this._delegate.val(); + } + /** + * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting + * the entire node contents. + * @returns JSON representation of the DataSnapshot contents, or null if empty. + */ + exportVal() { + validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length); + return this._delegate.exportVal(); + } + // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary + // for end-users + toJSON() { + // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content + validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length); + return this._delegate.toJSON(); + } + /** + * Returns whether the snapshot contains a non-null value. + * + * @returns Whether the snapshot contains a non-null value, or is empty. + */ + exists() { + validateArgCount('DataSnapshot.exists', 0, 0, arguments.length); + return this._delegate.exists(); + } + /** + * Returns a DataSnapshot of the specified child node's contents. + * + * @param path - Path to a child. + * @returns DataSnapshot for child node. + */ + child(path) { + validateArgCount('DataSnapshot.child', 0, 1, arguments.length); + // Ensure the childPath is a string (can be a number) + path = String(path); + _validatePathString('DataSnapshot.child', 'path', path, false); + return new DataSnapshot(this._database, this._delegate.child(path)); + } + /** + * Returns whether the snapshot contains a child at the specified path. + * + * @param path - Path to a child. + * @returns Whether the child exists. + */ + hasChild(path) { + validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length); + _validatePathString('DataSnapshot.hasChild', 'path', path, false); + return this._delegate.hasChild(path); + } + /** + * Returns the priority of the object, or null if no priority was set. + * + * @returns The priority. + */ + getPriority() { + validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length); + return this._delegate.priority; + } + /** + * Iterates through child nodes and calls the specified action for each one. + * + * @param action - Callback function to be called + * for each child. + * @returns True if forEach was canceled by action returning true for + * one of the child nodes. + */ + forEach(action) { + validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length); + validateCallback('DataSnapshot.forEach', 'action', action, false); + return this._delegate.forEach(expDataSnapshot => action(new DataSnapshot(this._database, expDataSnapshot))); + } + /** + * Returns whether this DataSnapshot has children. + * @returns True if the DataSnapshot contains 1 or more child nodes. + */ + hasChildren() { + validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length); + return this._delegate.hasChildren(); + } + get key() { + return this._delegate.key; + } + /** + * Returns the number of children for this DataSnapshot. + * @returns The number of children that this DataSnapshot contains. + */ + numChildren() { + validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length); + return this._delegate.size; + } + /** + * @returns The Firebase reference for the location this snapshot's data came + * from. + */ + getRef() { + validateArgCount('DataSnapshot.ref', 0, 0, arguments.length); + return new Reference(this._database, this._delegate.ref); + } + get ref() { + return this.getRef(); + } +} +/** + * A Query represents a filter to be applied to a firebase location. This object purely represents the + * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js. + * + * Since every Firebase reference is a query, Firebase inherits from this object. + */ +class Query { + constructor(database, _delegate) { + this.database = database; + this._delegate = _delegate; + } + on(eventType, callback, cancelCallbackOrContext, context) { + validateArgCount('Query.on', 2, 4, arguments.length); + validateCallback('Query.on', 'callback', callback, false); + const ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context); + const valueCallback = (expSnapshot, previousChildName) => { + callback.call(ret.context, new DataSnapshot(this.database, expSnapshot), previousChildName); + }; + valueCallback.userCallback = callback; + valueCallback.context = ret.context; + const cancelCallback = ret.cancel?.bind(ret.context); + switch (eventType) { + case 'value': + onValue(this._delegate, valueCallback, cancelCallback); + return callback; + case 'child_added': + onChildAdded(this._delegate, valueCallback, cancelCallback); + return callback; + case 'child_removed': + onChildRemoved(this._delegate, valueCallback, cancelCallback); + return callback; + case 'child_changed': + onChildChanged(this._delegate, valueCallback, cancelCallback); + return callback; + case 'child_moved': + onChildMoved(this._delegate, valueCallback, cancelCallback); + return callback; + default: + throw new Error(errorPrefix('Query.on', 'eventType') + + 'must be a valid event type = "value", "child_added", "child_removed", ' + + '"child_changed", or "child_moved".'); + } + } + off(eventType, callback, context) { + validateArgCount('Query.off', 0, 3, arguments.length); + validateEventType('Query.off', eventType, true); + validateCallback('Query.off', 'callback', callback, true); + validateContextObject('Query.off', 'context', context, true); + if (callback) { + const valueCallback = () => { }; + valueCallback.userCallback = callback; + valueCallback.context = context; + off(this._delegate, eventType, valueCallback); + } + else { + off(this._delegate, eventType); + } + } + /** + * Get the server-value for this query, or return a cached value if not connected. + */ + get() { + return get(this._delegate).then(expSnapshot => { + return new DataSnapshot(this.database, expSnapshot); + }); + } + /** + * Attaches a listener, waits for the first event, and then removes the listener + */ + once(eventType, callback, failureCallbackOrContext, context) { + validateArgCount('Query.once', 1, 4, arguments.length); + validateCallback('Query.once', 'callback', callback, true); + const ret = Query.getCancelAndContextArgs_('Query.once', failureCallbackOrContext, context); + const deferred = new Deferred(); + const valueCallback = (expSnapshot, previousChildName) => { + const result = new DataSnapshot(this.database, expSnapshot); + if (callback) { + callback.call(ret.context, result, previousChildName); + } + deferred.resolve(result); + }; + valueCallback.userCallback = callback; + valueCallback.context = ret.context; + const cancelCallback = (error) => { + if (ret.cancel) { + ret.cancel.call(ret.context, error); + } + deferred.reject(error); + }; + switch (eventType) { + case 'value': + onValue(this._delegate, valueCallback, cancelCallback, { + onlyOnce: true + }); + break; + case 'child_added': + onChildAdded(this._delegate, valueCallback, cancelCallback, { + onlyOnce: true + }); + break; + case 'child_removed': + onChildRemoved(this._delegate, valueCallback, cancelCallback, { + onlyOnce: true + }); + break; + case 'child_changed': + onChildChanged(this._delegate, valueCallback, cancelCallback, { + onlyOnce: true + }); + break; + case 'child_moved': + onChildMoved(this._delegate, valueCallback, cancelCallback, { + onlyOnce: true + }); + break; + default: + throw new Error(errorPrefix('Query.once', 'eventType') + + 'must be a valid event type = "value", "child_added", "child_removed", ' + + '"child_changed", or "child_moved".'); + } + return deferred.promise; + } + /** + * Set a limit and anchor it to the start of the window. + */ + limitToFirst(limit) { + validateArgCount('Query.limitToFirst', 1, 1, arguments.length); + return new Query(this.database, query(this._delegate, limitToFirst(limit))); + } + /** + * Set a limit and anchor it to the end of the window. + */ + limitToLast(limit) { + validateArgCount('Query.limitToLast', 1, 1, arguments.length); + return new Query(this.database, query(this._delegate, limitToLast(limit))); + } + /** + * Given a child path, return a new query ordered by the specified grandchild path. + */ + orderByChild(path) { + validateArgCount('Query.orderByChild', 1, 1, arguments.length); + return new Query(this.database, query(this._delegate, orderByChild(path))); + } + /** + * Return a new query ordered by the KeyIndex + */ + orderByKey() { + validateArgCount('Query.orderByKey', 0, 0, arguments.length); + return new Query(this.database, query(this._delegate, orderByKey())); + } + /** + * Return a new query ordered by the PriorityIndex + */ + orderByPriority() { + validateArgCount('Query.orderByPriority', 0, 0, arguments.length); + return new Query(this.database, query(this._delegate, orderByPriority())); + } + /** + * Return a new query ordered by the ValueIndex + */ + orderByValue() { + validateArgCount('Query.orderByValue', 0, 0, arguments.length); + return new Query(this.database, query(this._delegate, orderByValue())); + } + startAt(value = null, name) { + validateArgCount('Query.startAt', 0, 2, arguments.length); + return new Query(this.database, query(this._delegate, startAt(value, name))); + } + startAfter(value = null, name) { + validateArgCount('Query.startAfter', 0, 2, arguments.length); + return new Query(this.database, query(this._delegate, startAfter(value, name))); + } + endAt(value = null, name) { + validateArgCount('Query.endAt', 0, 2, arguments.length); + return new Query(this.database, query(this._delegate, endAt(value, name))); + } + endBefore(value = null, name) { + validateArgCount('Query.endBefore', 0, 2, arguments.length); + return new Query(this.database, query(this._delegate, endBefore(value, name))); + } + /** + * Load the selection of children with exactly the specified value, and, optionally, + * the specified name. + */ + equalTo(value, name) { + validateArgCount('Query.equalTo', 1, 2, arguments.length); + return new Query(this.database, query(this._delegate, equalTo(value, name))); + } + /** + * @returns URL for this location. + */ + toString() { + validateArgCount('Query.toString', 0, 0, arguments.length); + return this._delegate.toString(); + } + // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary + // for end-users. + toJSON() { + // An optional spacer argument is unnecessary for a string. + validateArgCount('Query.toJSON', 0, 1, arguments.length); + return this._delegate.toJSON(); + } + /** + * Return true if this query and the provided query are equivalent; otherwise, return false. + */ + isEqual(other) { + validateArgCount('Query.isEqual', 1, 1, arguments.length); + if (!(other instanceof Query)) { + const error = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.'; + throw new Error(error); + } + return this._delegate.isEqual(other._delegate); + } + /** + * Helper used by .on and .once to extract the context and or cancel arguments. + * @param fnName - The function name (on or once) + * + */ + static getCancelAndContextArgs_(fnName, cancelOrContext, context) { + const ret = { cancel: undefined, context: undefined }; + if (cancelOrContext && context) { + ret.cancel = cancelOrContext; + validateCallback(fnName, 'cancel', ret.cancel, true); + ret.context = context; + validateContextObject(fnName, 'context', ret.context, true); + } + else if (cancelOrContext) { + // we have either a cancel callback or a context. + if (typeof cancelOrContext === 'object' && cancelOrContext !== null) { + // it's a context! + ret.context = cancelOrContext; + } + else if (typeof cancelOrContext === 'function') { + ret.cancel = cancelOrContext; + } + else { + throw new Error(errorPrefix(fnName, 'cancelOrContext') + + ' must either be a cancel callback or a context object.'); + } + } + return ret; + } + get ref() { + return new Reference(this.database, new _ReferenceImpl(this._delegate._repo, this._delegate._path)); + } +} +class Reference extends Query { + /** + * Call options: + * new Reference(Repo, Path) or + * new Reference(url: string, string|RepoManager) + * + * Externally - this is the firebase.database.Reference type. + */ + constructor(database, _delegate) { + super(database, new _QueryImpl(_delegate._repo, _delegate._path, new _QueryParams(), false)); + this.database = database; + this._delegate = _delegate; + } + /** @returns {?string} */ + getKey() { + validateArgCount('Reference.key', 0, 0, arguments.length); + return this._delegate.key; + } + child(pathString) { + validateArgCount('Reference.child', 1, 1, arguments.length); + if (typeof pathString === 'number') { + pathString = String(pathString); + } + return new Reference(this.database, child(this._delegate, pathString)); + } + /** @returns {?Reference} */ + getParent() { + validateArgCount('Reference.parent', 0, 0, arguments.length); + const parent = this._delegate.parent; + return parent ? new Reference(this.database, parent) : null; + } + /** @returns {!Reference} */ + getRoot() { + validateArgCount('Reference.root', 0, 0, arguments.length); + return new Reference(this.database, this._delegate.root); + } + set(newVal, onComplete) { + validateArgCount('Reference.set', 1, 2, arguments.length); + validateCallback('Reference.set', 'onComplete', onComplete, true); + const result = set(this._delegate, newVal); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + update(values, onComplete) { + validateArgCount('Reference.update', 1, 2, arguments.length); + if (Array.isArray(values)) { + const newObjectToMerge = {}; + for (let i = 0; i < values.length; ++i) { + newObjectToMerge['' + i] = values[i]; + } + values = newObjectToMerge; + warn('Passing an Array to Firebase.update() is deprecated. ' + + 'Use set() if you want to overwrite the existing data, or ' + + 'an Object with integer keys if you really do want to ' + + 'only update some of the children.'); + } + _validateWritablePath('Reference.update', this._delegate._path); + validateCallback('Reference.update', 'onComplete', onComplete, true); + const result = update(this._delegate, values); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + setWithPriority(newVal, newPriority, onComplete) { + validateArgCount('Reference.setWithPriority', 2, 3, arguments.length); + validateCallback('Reference.setWithPriority', 'onComplete', onComplete, true); + const result = setWithPriority(this._delegate, newVal, newPriority); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + remove(onComplete) { + validateArgCount('Reference.remove', 0, 1, arguments.length); + validateCallback('Reference.remove', 'onComplete', onComplete, true); + const result = remove(this._delegate); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + transaction(transactionUpdate, onComplete, applyLocally) { + validateArgCount('Reference.transaction', 1, 3, arguments.length); + validateCallback('Reference.transaction', 'transactionUpdate', transactionUpdate, false); + validateCallback('Reference.transaction', 'onComplete', onComplete, true); + validateBoolean('Reference.transaction', 'applyLocally', applyLocally, true); + const result = runTransaction(this._delegate, transactionUpdate, { + applyLocally + }).then(transactionResult => new TransactionResult(transactionResult.committed, new DataSnapshot(this.database, transactionResult.snapshot))); + if (onComplete) { + result.then(transactionResult => onComplete(null, transactionResult.committed, transactionResult.snapshot), error => onComplete(error, false, null)); + } + return result; + } + setPriority(priority, onComplete) { + validateArgCount('Reference.setPriority', 1, 2, arguments.length); + validateCallback('Reference.setPriority', 'onComplete', onComplete, true); + const result = setPriority(this._delegate, priority); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + push(value, onComplete) { + validateArgCount('Reference.push', 0, 2, arguments.length); + validateCallback('Reference.push', 'onComplete', onComplete, true); + const expPromise = push(this._delegate, value); + const promise = expPromise.then(expRef => new Reference(this.database, expRef)); + if (onComplete) { + promise.then(() => onComplete(null), error => onComplete(error)); + } + const result = new Reference(this.database, expPromise); + result.then = promise.then.bind(promise); + result.catch = promise.catch.bind(promise, undefined); + return result; + } + onDisconnect() { + _validateWritablePath('Reference.onDisconnect', this._delegate._path); + return new OnDisconnect(new OnDisconnect$1(this._delegate._repo, this._delegate._path)); + } + get key() { + return this.getKey(); + } + get parent() { + return this.getParent(); + } + get root() { + return this.getRoot(); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Class representing a firebase database. + */ +class Database { + /** + * The constructor should not be called by users of our public API. + */ + constructor(_delegate, app) { + this._delegate = _delegate; + this.app = app; + this.INTERNAL = { + delete: () => this._delegate._delete(), + forceWebSockets, + forceLongPolling + }; + } + /** + * Modify this instance to communicate with the Realtime Database emulator. + * + *

Note: This method must be called before performing any other operation. + * + * @param host - the emulator host (ex: localhost) + * @param port - the emulator port (ex: 8080) + * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules + */ + useEmulator(host, port, options = {}) { + connectDatabaseEmulator(this._delegate, host, port, options); + } + ref(path) { + validateArgCount('database.ref', 0, 1, arguments.length); + if (path instanceof Reference) { + const childRef = refFromURL(this._delegate, path.toString()); + return new Reference(this, childRef); + } + else { + const childRef = ref(this._delegate, path); + return new Reference(this, childRef); + } + } + /** + * Returns a reference to the root or the path specified in url. + * We throw a exception if the url is not in the same domain as the + * current repo. + * @returns Firebase reference. + */ + refFromURL(url) { + const apiName = 'database.refFromURL'; + validateArgCount(apiName, 1, 1, arguments.length); + const childRef = refFromURL(this._delegate, url); + return new Reference(this, childRef); + } + // Make individual repo go offline. + goOffline() { + validateArgCount('database.goOffline', 0, 0, arguments.length); + return goOffline(this._delegate); + } + goOnline() { + validateArgCount('database.goOnline', 0, 0, arguments.length); + return goOnline(this._delegate); + } +} +Database.ServerValue = { + TIMESTAMP: serverTimestamp(), + increment: (delta) => increment(delta) +}; + +/** + * Used by console to create a database based on the app, + * passed database URL and a custom auth implementation. + * + * @param app - A valid FirebaseApp-like object + * @param url - A valid Firebase databaseURL + * @param version - custom version e.g. firebase-admin version + * @param customAuthImpl - custom auth implementation + */ +function initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, namespace, nodeAdmin = false }) { + _setSDKVersion(version); + const container = new ComponentContainer('database-standalone'); + /** + * ComponentContainer('database-standalone') is just a placeholder that doesn't perform + * any actual function. + */ + const authProvider = new Provider('auth-internal', container); + authProvider.setComponent(new Component('auth-internal', () => customAuthImpl, "PRIVATE" /* ComponentType.PRIVATE */)); + let appCheckProvider = undefined; + if (customAppCheckImpl) { + appCheckProvider = new Provider('app-check-internal', container); + appCheckProvider.setComponent(new Component('app-check-internal', () => customAppCheckImpl, "PRIVATE" /* ComponentType.PRIVATE */)); + } + return { + instance: new Database(_repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin), app), + namespace + }; +} + +var INTERNAL = /*#__PURE__*/Object.freeze({ + __proto__: null, + initStandalone: initStandalone +}); + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const ServerValue = Database.ServerValue; +function registerDatabase(instance) { + // Register the Database Service with the 'firebase' namespace. + instance.INTERNAL.registerComponent(new Component('database-compat', (container, { instanceIdentifier: url }) => { + /* Dependencies */ + // getImmediate for FirebaseApp will always succeed + const app = container.getProvider('app-compat').getImmediate(); + const databaseExp = container + .getProvider('database') + .getImmediate({ identifier: url }); + return new Database(databaseExp, app); + }, "PUBLIC" /* ComponentType.PUBLIC */) + .setServiceProps( + // firebase.database namespace properties + { + Reference, + Query, + Database, + DataSnapshot, + enableLogging, + INTERNAL, + ServerValue + }) + .setMultipleInstances(true)); + instance.registerVersion(name, version); +} +registerDatabase(firebase); + +export { registerDatabase }; +//# sourceMappingURL=index.esm.js.map diff --git a/node_modules/@firebase/database-compat/dist/index.esm.js.map b/node_modules/@firebase/database-compat/dist/index.esm.js.map new file mode 100644 index 0000000..77c0d3a --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/index.esm.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.esm.js","sources":["../src/util/util.ts","../src/util/validation.ts","../src/api/onDisconnect.ts","../src/api/TransactionResult.ts","../src/api/Reference.ts","../src/api/Database.ts","../src/api/internal.ts","../src/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nconst logClient = new Logger('@firebase/database-compat');\n\nexport const warn = function (msg: string) {\n const message = 'FIREBASE WARNING: ' + msg;\n logClient.warn(message);\n};\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { errorPrefix as errorPrefixFxn } from '@firebase/util';\n\nexport const validateBoolean = function (\n fnName: string,\n argumentName: string,\n bool: unknown,\n optional: boolean\n) {\n if (optional && bool === undefined) {\n return;\n }\n if (typeof bool !== 'boolean') {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) + 'must be a boolean.'\n );\n }\n};\n\nexport const validateEventType = function (\n fnName: string,\n eventType: string,\n optional: boolean\n) {\n if (optional && eventType === undefined) {\n return;\n }\n\n switch (eventType) {\n case 'value':\n case 'child_added':\n case 'child_removed':\n case 'child_changed':\n case 'child_moved':\n break;\n default:\n throw new Error(\n errorPrefixFxn(fnName, 'eventType') +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".'\n );\n }\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { OnDisconnect as ModularOnDisconnect } from '@firebase/database';\nimport { validateArgCount, validateCallback, Compat } from '@firebase/util';\n\nimport { warn } from '../util/util';\nexport class OnDisconnect implements Compat {\n constructor(readonly _delegate: ModularOnDisconnect) {}\n\n cancel(onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);\n validateCallback('OnDisconnect.cancel', 'onComplete', onComplete, true);\n const result = this._delegate.cancel();\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n remove(onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);\n validateCallback('OnDisconnect.remove', 'onComplete', onComplete, true);\n const result = this._delegate.remove();\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n set(value: unknown, onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('OnDisconnect.set', 1, 2, arguments.length);\n validateCallback('OnDisconnect.set', 'onComplete', onComplete, true);\n const result = this._delegate.set(value);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n setWithPriority(\n value: unknown,\n priority: number | string | null,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length);\n validateCallback(\n 'OnDisconnect.setWithPriority',\n 'onComplete',\n onComplete,\n true\n );\n const result = this._delegate.setWithPriority(value, priority);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n update(\n objectToMerge: Record,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('OnDisconnect.update', 1, 2, arguments.length);\n if (Array.isArray(objectToMerge)) {\n const newObjectToMerge: { [k: string]: unknown } = {};\n for (let i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n warn(\n 'Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' +\n 'existing data, or an Object with integer keys if you really do want to only update some of the children.'\n );\n }\n validateCallback('OnDisconnect.update', 'onComplete', onComplete, true);\n const result = this._delegate.update(objectToMerge);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { validateArgCount } from '@firebase/util';\n\nimport { DataSnapshot } from './Reference';\n\nexport class TransactionResult {\n /**\n * A type for the resolve value of Firebase.transaction.\n */\n constructor(public committed: boolean, public snapshot: DataSnapshot) {}\n\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n toJSON(): object {\n validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n OnDisconnect as ModularOnDisconnect,\n off,\n onChildAdded,\n onChildChanged,\n onChildMoved,\n onChildRemoved,\n onValue,\n EventType,\n limitToFirst,\n query,\n limitToLast,\n orderByChild,\n orderByKey,\n orderByValue,\n orderByPriority,\n startAt,\n startAfter,\n endAt,\n endBefore,\n equalTo,\n get,\n set,\n update,\n setWithPriority,\n remove,\n setPriority,\n push,\n runTransaction,\n child,\n DataSnapshot as ModularDataSnapshot,\n Query as ExpQuery,\n DatabaseReference as ModularReference,\n _QueryImpl,\n _ReferenceImpl,\n _validatePathString,\n _validateWritablePath,\n _UserCallback,\n _QueryParams\n} from '@firebase/database';\nimport {\n Compat,\n Deferred,\n errorPrefix,\n validateArgCount,\n validateCallback,\n validateContextObject\n} from '@firebase/util';\n\nimport { warn } from '../util/util';\nimport { validateBoolean, validateEventType } from '../util/validation';\n\nimport { Database } from './Database';\nimport { OnDisconnect } from './onDisconnect';\nimport { TransactionResult } from './TransactionResult';\n\n/**\n * Class representing a firebase data snapshot. It wraps a SnapshotNode and\n * surfaces the public methods (val, forEach, etc.) we want to expose.\n */\nexport class DataSnapshot implements Compat {\n constructor(\n readonly _database: Database,\n readonly _delegate: ModularDataSnapshot\n ) {}\n\n /**\n * Retrieves the snapshot contents as JSON. Returns null if the snapshot is\n * empty.\n *\n * @returns JSON representation of the DataSnapshot contents, or null if empty.\n */\n val(): unknown {\n validateArgCount('DataSnapshot.val', 0, 0, arguments.length);\n return this._delegate.val();\n }\n\n /**\n * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting\n * the entire node contents.\n * @returns JSON representation of the DataSnapshot contents, or null if empty.\n */\n exportVal(): unknown {\n validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length);\n return this._delegate.exportVal();\n }\n\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n toJSON(): unknown {\n // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content\n validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length);\n return this._delegate.toJSON();\n }\n\n /**\n * Returns whether the snapshot contains a non-null value.\n *\n * @returns Whether the snapshot contains a non-null value, or is empty.\n */\n exists(): boolean {\n validateArgCount('DataSnapshot.exists', 0, 0, arguments.length);\n return this._delegate.exists();\n }\n\n /**\n * Returns a DataSnapshot of the specified child node's contents.\n *\n * @param path - Path to a child.\n * @returns DataSnapshot for child node.\n */\n child(path: string): DataSnapshot {\n validateArgCount('DataSnapshot.child', 0, 1, arguments.length);\n // Ensure the childPath is a string (can be a number)\n path = String(path);\n _validatePathString('DataSnapshot.child', 'path', path, false);\n return new DataSnapshot(this._database, this._delegate.child(path));\n }\n\n /**\n * Returns whether the snapshot contains a child at the specified path.\n *\n * @param path - Path to a child.\n * @returns Whether the child exists.\n */\n hasChild(path: string): boolean {\n validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);\n _validatePathString('DataSnapshot.hasChild', 'path', path, false);\n return this._delegate.hasChild(path);\n }\n\n /**\n * Returns the priority of the object, or null if no priority was set.\n *\n * @returns The priority.\n */\n getPriority(): string | number | null {\n validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);\n return this._delegate.priority;\n }\n\n /**\n * Iterates through child nodes and calls the specified action for each one.\n *\n * @param action - Callback function to be called\n * for each child.\n * @returns True if forEach was canceled by action returning true for\n * one of the child nodes.\n */\n forEach(action: (snapshot: IteratedDataSnapshot) => boolean | void): boolean {\n validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);\n validateCallback('DataSnapshot.forEach', 'action', action, false);\n return this._delegate.forEach(expDataSnapshot =>\n action(new DataSnapshot(this._database, expDataSnapshot))\n );\n }\n\n /**\n * Returns whether this DataSnapshot has children.\n * @returns True if the DataSnapshot contains 1 or more child nodes.\n */\n hasChildren(): boolean {\n validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);\n return this._delegate.hasChildren();\n }\n\n get key() {\n return this._delegate.key;\n }\n\n /**\n * Returns the number of children for this DataSnapshot.\n * @returns The number of children that this DataSnapshot contains.\n */\n numChildren(): number {\n validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);\n return this._delegate.size;\n }\n\n /**\n * @returns The Firebase reference for the location this snapshot's data came\n * from.\n */\n getRef(): Reference {\n validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);\n return new Reference(this._database, this._delegate.ref);\n }\n\n get ref(): Reference {\n return this.getRef();\n }\n}\n\n/**\n * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined.\n */\nexport interface IteratedDataSnapshot extends DataSnapshot {\n key: string; // key of the location of this snapshot.\n}\n\nexport interface SnapshotCallback {\n (dataSnapshot: DataSnapshot, previousChildName?: string | null): unknown;\n}\n\n/**\n * A Query represents a filter to be applied to a firebase location. This object purely represents the\n * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js.\n *\n * Since every Firebase reference is a query, Firebase inherits from this object.\n */\nexport class Query implements Compat {\n constructor(readonly database: Database, readonly _delegate: ExpQuery) {}\n\n on(\n eventType: string,\n callback: SnapshotCallback,\n cancelCallbackOrContext?: ((a: Error) => unknown) | object | null,\n context?: object | null\n ): SnapshotCallback {\n validateArgCount('Query.on', 2, 4, arguments.length);\n validateCallback('Query.on', 'callback', callback, false);\n\n const ret = Query.getCancelAndContextArgs_(\n 'Query.on',\n cancelCallbackOrContext,\n context\n );\n const valueCallback = (expSnapshot, previousChildName?) => {\n callback.call(\n ret.context,\n new DataSnapshot(this.database, expSnapshot),\n previousChildName\n );\n };\n valueCallback.userCallback = callback;\n valueCallback.context = ret.context;\n const cancelCallback = ret.cancel?.bind(ret.context);\n\n switch (eventType) {\n case 'value':\n onValue(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_added':\n onChildAdded(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_removed':\n onChildRemoved(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_changed':\n onChildChanged(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_moved':\n onChildMoved(this._delegate, valueCallback, cancelCallback);\n return callback;\n default:\n throw new Error(\n errorPrefix('Query.on', 'eventType') +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".'\n );\n }\n }\n\n off(\n eventType?: string,\n callback?: SnapshotCallback,\n context?: object | null\n ): void {\n validateArgCount('Query.off', 0, 3, arguments.length);\n validateEventType('Query.off', eventType, true);\n validateCallback('Query.off', 'callback', callback, true);\n validateContextObject('Query.off', 'context', context, true);\n if (callback) {\n const valueCallback: _UserCallback = () => {};\n valueCallback.userCallback = callback;\n valueCallback.context = context;\n off(this._delegate, eventType as EventType, valueCallback);\n } else {\n off(this._delegate, eventType as EventType | undefined);\n }\n }\n\n /**\n * Get the server-value for this query, or return a cached value if not connected.\n */\n get(): Promise {\n return get(this._delegate).then(expSnapshot => {\n return new DataSnapshot(this.database, expSnapshot);\n });\n }\n\n /**\n * Attaches a listener, waits for the first event, and then removes the listener\n */\n once(\n eventType: string,\n callback?: SnapshotCallback,\n failureCallbackOrContext?: ((a: Error) => void) | object | null,\n context?: object | null\n ): Promise {\n validateArgCount('Query.once', 1, 4, arguments.length);\n validateCallback('Query.once', 'callback', callback, true);\n\n const ret = Query.getCancelAndContextArgs_(\n 'Query.once',\n failureCallbackOrContext,\n context\n );\n const deferred = new Deferred();\n const valueCallback: _UserCallback = (expSnapshot, previousChildName?) => {\n const result = new DataSnapshot(this.database, expSnapshot);\n if (callback) {\n callback.call(ret.context, result, previousChildName);\n }\n deferred.resolve(result);\n };\n valueCallback.userCallback = callback;\n valueCallback.context = ret.context;\n const cancelCallback = (error: Error) => {\n if (ret.cancel) {\n ret.cancel.call(ret.context, error);\n }\n deferred.reject(error);\n };\n\n switch (eventType) {\n case 'value':\n onValue(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_added':\n onChildAdded(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_removed':\n onChildRemoved(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_changed':\n onChildChanged(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_moved':\n onChildMoved(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n default:\n throw new Error(\n errorPrefix('Query.once', 'eventType') +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".'\n );\n }\n\n return deferred.promise;\n }\n\n /**\n * Set a limit and anchor it to the start of the window.\n */\n limitToFirst(limit: number): Query {\n validateArgCount('Query.limitToFirst', 1, 1, arguments.length);\n return new Query(this.database, query(this._delegate, limitToFirst(limit)));\n }\n\n /**\n * Set a limit and anchor it to the end of the window.\n */\n limitToLast(limit: number): Query {\n validateArgCount('Query.limitToLast', 1, 1, arguments.length);\n return new Query(this.database, query(this._delegate, limitToLast(limit)));\n }\n\n /**\n * Given a child path, return a new query ordered by the specified grandchild path.\n */\n orderByChild(path: string): Query {\n validateArgCount('Query.orderByChild', 1, 1, arguments.length);\n return new Query(this.database, query(this._delegate, orderByChild(path)));\n }\n\n /**\n * Return a new query ordered by the KeyIndex\n */\n orderByKey(): Query {\n validateArgCount('Query.orderByKey', 0, 0, arguments.length);\n return new Query(this.database, query(this._delegate, orderByKey()));\n }\n\n /**\n * Return a new query ordered by the PriorityIndex\n */\n orderByPriority(): Query {\n validateArgCount('Query.orderByPriority', 0, 0, arguments.length);\n return new Query(this.database, query(this._delegate, orderByPriority()));\n }\n\n /**\n * Return a new query ordered by the ValueIndex\n */\n orderByValue(): Query {\n validateArgCount('Query.orderByValue', 0, 0, arguments.length);\n return new Query(this.database, query(this._delegate, orderByValue()));\n }\n\n startAt(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.startAt', 0, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, startAt(value, name))\n );\n }\n\n startAfter(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.startAfter', 0, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, startAfter(value, name))\n );\n }\n\n endAt(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.endAt', 0, 2, arguments.length);\n return new Query(this.database, query(this._delegate, endAt(value, name)));\n }\n\n endBefore(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.endBefore', 0, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, endBefore(value, name))\n );\n }\n\n /**\n * Load the selection of children with exactly the specified value, and, optionally,\n * the specified name.\n */\n equalTo(value: number | string | boolean | null, name?: string) {\n validateArgCount('Query.equalTo', 1, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, equalTo(value, name))\n );\n }\n\n /**\n * @returns URL for this location.\n */\n toString(): string {\n validateArgCount('Query.toString', 0, 0, arguments.length);\n return this._delegate.toString();\n }\n\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users.\n toJSON() {\n // An optional spacer argument is unnecessary for a string.\n validateArgCount('Query.toJSON', 0, 1, arguments.length);\n return this._delegate.toJSON();\n }\n\n /**\n * Return true if this query and the provided query are equivalent; otherwise, return false.\n */\n isEqual(other: Query): boolean {\n validateArgCount('Query.isEqual', 1, 1, arguments.length);\n if (!(other instanceof Query)) {\n const error =\n 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.';\n throw new Error(error);\n }\n return this._delegate.isEqual(other._delegate);\n }\n\n /**\n * Helper used by .on and .once to extract the context and or cancel arguments.\n * @param fnName - The function name (on or once)\n *\n */\n private static getCancelAndContextArgs_(\n fnName: string,\n cancelOrContext?: ((a: Error) => void) | object | null,\n context?: object | null\n ): { cancel: ((a: Error) => void) | undefined; context: object | undefined } {\n const ret: {\n cancel: ((a: Error) => void) | null;\n context: object | null;\n } = { cancel: undefined, context: undefined };\n if (cancelOrContext && context) {\n ret.cancel = cancelOrContext as (a: Error) => void;\n validateCallback(fnName, 'cancel', ret.cancel, true);\n\n ret.context = context;\n validateContextObject(fnName, 'context', ret.context, true);\n } else if (cancelOrContext) {\n // we have either a cancel callback or a context.\n if (typeof cancelOrContext === 'object' && cancelOrContext !== null) {\n // it's a context!\n ret.context = cancelOrContext;\n } else if (typeof cancelOrContext === 'function') {\n ret.cancel = cancelOrContext as (a: Error) => void;\n } else {\n throw new Error(\n errorPrefix(fnName, 'cancelOrContext') +\n ' must either be a cancel callback or a context object.'\n );\n }\n }\n return ret;\n }\n\n get ref(): Reference {\n return new Reference(\n this.database,\n new _ReferenceImpl(this._delegate._repo, this._delegate._path)\n );\n }\n}\n\nexport class Reference extends Query implements Compat {\n then: Promise['then'];\n catch: Promise['catch'];\n\n /**\n * Call options:\n * new Reference(Repo, Path) or\n * new Reference(url: string, string|RepoManager)\n *\n * Externally - this is the firebase.database.Reference type.\n */\n constructor(\n readonly database: Database,\n readonly _delegate: ModularReference\n ) {\n super(\n database,\n new _QueryImpl(\n _delegate._repo,\n _delegate._path,\n new _QueryParams(),\n false\n )\n );\n }\n\n /** @returns {?string} */\n getKey(): string | null {\n validateArgCount('Reference.key', 0, 0, arguments.length);\n return this._delegate.key;\n }\n\n child(pathString: string): Reference {\n validateArgCount('Reference.child', 1, 1, arguments.length);\n if (typeof pathString === 'number') {\n pathString = String(pathString);\n }\n return new Reference(this.database, child(this._delegate, pathString));\n }\n\n /** @returns {?Reference} */\n getParent(): Reference | null {\n validateArgCount('Reference.parent', 0, 0, arguments.length);\n const parent = this._delegate.parent;\n return parent ? new Reference(this.database, parent) : null;\n }\n\n /** @returns {!Reference} */\n getRoot(): Reference {\n validateArgCount('Reference.root', 0, 0, arguments.length);\n return new Reference(this.database, this._delegate.root);\n }\n\n set(\n newVal: unknown,\n onComplete?: (error: Error | null) => void\n ): Promise {\n validateArgCount('Reference.set', 1, 2, arguments.length);\n validateCallback('Reference.set', 'onComplete', onComplete, true);\n const result = set(this._delegate, newVal);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n update(\n values: object,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('Reference.update', 1, 2, arguments.length);\n\n if (Array.isArray(values)) {\n const newObjectToMerge: { [k: string]: unknown } = {};\n for (let i = 0; i < values.length; ++i) {\n newObjectToMerge['' + i] = values[i];\n }\n values = newObjectToMerge;\n warn(\n 'Passing an Array to Firebase.update() is deprecated. ' +\n 'Use set() if you want to overwrite the existing data, or ' +\n 'an Object with integer keys if you really do want to ' +\n 'only update some of the children.'\n );\n }\n _validateWritablePath('Reference.update', this._delegate._path);\n validateCallback('Reference.update', 'onComplete', onComplete, true);\n\n const result = update(this._delegate, values);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n setWithPriority(\n newVal: unknown,\n newPriority: string | number | null,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);\n validateCallback(\n 'Reference.setWithPriority',\n 'onComplete',\n onComplete,\n true\n );\n\n const result = setWithPriority(this._delegate, newVal, newPriority);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n remove(onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('Reference.remove', 0, 1, arguments.length);\n validateCallback('Reference.remove', 'onComplete', onComplete, true);\n\n const result = remove(this._delegate);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n transaction(\n transactionUpdate: (currentData: unknown) => unknown,\n onComplete?: (\n error: Error | null,\n committed: boolean,\n dataSnapshot: DataSnapshot | null\n ) => void,\n applyLocally?: boolean\n ): Promise {\n validateArgCount('Reference.transaction', 1, 3, arguments.length);\n validateCallback(\n 'Reference.transaction',\n 'transactionUpdate',\n transactionUpdate,\n false\n );\n validateCallback('Reference.transaction', 'onComplete', onComplete, true);\n validateBoolean(\n 'Reference.transaction',\n 'applyLocally',\n applyLocally,\n true\n );\n\n const result = runTransaction(this._delegate, transactionUpdate, {\n applyLocally\n }).then(\n transactionResult =>\n new TransactionResult(\n transactionResult.committed,\n new DataSnapshot(this.database, transactionResult.snapshot)\n )\n );\n if (onComplete) {\n result.then(\n transactionResult =>\n onComplete(\n null,\n transactionResult.committed,\n transactionResult.snapshot\n ),\n error => onComplete(error, false, null)\n );\n }\n return result;\n }\n\n setPriority(\n priority: string | number | null,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('Reference.setPriority', 1, 2, arguments.length);\n validateCallback('Reference.setPriority', 'onComplete', onComplete, true);\n\n const result = setPriority(this._delegate, priority);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n push(value?: unknown, onComplete?: (a: Error | null) => void): Reference {\n validateArgCount('Reference.push', 0, 2, arguments.length);\n validateCallback('Reference.push', 'onComplete', onComplete, true);\n\n const expPromise = push(this._delegate, value);\n const promise = expPromise.then(\n expRef => new Reference(this.database, expRef)\n );\n\n if (onComplete) {\n promise.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n\n const result = new Reference(this.database, expPromise);\n result.then = promise.then.bind(promise);\n result.catch = promise.catch.bind(promise, undefined);\n return result;\n }\n\n onDisconnect(): OnDisconnect {\n _validateWritablePath('Reference.onDisconnect', this._delegate._path);\n return new OnDisconnect(\n new ModularOnDisconnect(this._delegate._repo, this._delegate._path)\n );\n }\n\n get key(): string | null {\n return this.getKey();\n }\n\n get parent(): Reference | null {\n return this.getParent();\n }\n\n get root(): Reference {\n return this.getRoot();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\n\nimport { FirebaseApp } from '@firebase/app-types';\nimport { FirebaseService } from '@firebase/app-types/private';\nimport {\n forceLongPolling,\n forceWebSockets,\n goOnline,\n connectDatabaseEmulator,\n goOffline,\n ref,\n refFromURL,\n increment,\n serverTimestamp,\n Database as ModularDatabase\n} from '@firebase/database';\nimport {\n validateArgCount,\n Compat,\n EmulatorMockTokenOptions\n} from '@firebase/util';\n\nimport { Reference } from './Reference';\n\n/**\n * Class representing a firebase database.\n */\nexport class Database implements FirebaseService, Compat {\n static readonly ServerValue = {\n TIMESTAMP: serverTimestamp(),\n increment: (delta: number) => increment(delta)\n };\n\n /**\n * The constructor should not be called by users of our public API.\n */\n constructor(readonly _delegate: ModularDatabase, readonly app: FirebaseApp) {}\n\n INTERNAL = {\n delete: () => this._delegate._delete(),\n forceWebSockets,\n forceLongPolling\n };\n\n /**\n * Modify this instance to communicate with the Realtime Database emulator.\n *\n *

Note: This method must be called before performing any other operation.\n *\n * @param host - the emulator host (ex: localhost)\n * @param port - the emulator port (ex: 8080)\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\n */\n useEmulator(\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions;\n } = {}\n ): void {\n connectDatabaseEmulator(this._delegate, host, port, options);\n }\n\n /**\n * Returns a reference to the root or to the path specified in the provided\n * argument.\n *\n * @param path - The relative string path or an existing Reference to a database\n * location.\n * @throws If a Reference is provided, throws if it does not belong to the\n * same project.\n * @returns Firebase reference.\n */\n ref(path?: string): Reference;\n ref(path?: Reference): Reference;\n ref(path?: string | Reference): Reference {\n validateArgCount('database.ref', 0, 1, arguments.length);\n if (path instanceof Reference) {\n const childRef = refFromURL(this._delegate, path.toString());\n return new Reference(this, childRef);\n } else {\n const childRef = ref(this._delegate, path);\n return new Reference(this, childRef);\n }\n }\n\n /**\n * Returns a reference to the root or the path specified in url.\n * We throw a exception if the url is not in the same domain as the\n * current repo.\n * @returns Firebase reference.\n */\n refFromURL(url: string): Reference {\n const apiName = 'database.refFromURL';\n validateArgCount(apiName, 1, 1, arguments.length);\n const childRef = refFromURL(this._delegate, url);\n return new Reference(this, childRef);\n }\n\n // Make individual repo go offline.\n goOffline(): void {\n validateArgCount('database.goOffline', 0, 0, arguments.length);\n return goOffline(this._delegate);\n }\n\n goOnline(): void {\n validateArgCount('database.goOnline', 0, 0, arguments.length);\n return goOnline(this._delegate);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n AppCheckInternalComponentName,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport { FirebaseApp } from '@firebase/app-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n Provider\n} from '@firebase/component';\nimport {\n _repoManagerDatabaseFromApp,\n _setSDKVersion\n} from '@firebase/database';\nimport * as types from '@firebase/database-types';\n\nimport { Database } from './Database';\n\n/**\n * Used by console to create a database based on the app,\n * passed database URL and a custom auth implementation.\n *\n * @param app - A valid FirebaseApp-like object\n * @param url - A valid Firebase databaseURL\n * @param version - custom version e.g. firebase-admin version\n * @param customAuthImpl - custom auth implementation\n */\nexport function initStandalone({\n app,\n url,\n version,\n customAuthImpl,\n customAppCheckImpl,\n namespace,\n nodeAdmin = false\n}: {\n app: FirebaseApp;\n url: string;\n version: string;\n customAuthImpl: FirebaseAuthInternal;\n customAppCheckImpl?: FirebaseAppCheckInternal;\n namespace: T;\n nodeAdmin?: boolean;\n}): {\n instance: types.Database;\n namespace: T;\n} {\n _setSDKVersion(version);\n\n const container = new ComponentContainer('database-standalone');\n /**\n * ComponentContainer('database-standalone') is just a placeholder that doesn't perform\n * any actual function.\n */\n const authProvider = new Provider(\n 'auth-internal',\n container\n );\n authProvider.setComponent(\n new Component('auth-internal', () => customAuthImpl, ComponentType.PRIVATE)\n );\n\n let appCheckProvider: Provider = undefined;\n if (customAppCheckImpl) {\n appCheckProvider = new Provider(\n 'app-check-internal',\n container\n );\n appCheckProvider.setComponent(\n new Component(\n 'app-check-internal',\n () => customAppCheckImpl,\n ComponentType.PRIVATE\n )\n );\n }\n\n return {\n instance: new Database(\n _repoManagerDatabaseFromApp(\n app,\n authProvider,\n appCheckProvider,\n url,\n nodeAdmin\n ),\n app\n ) as types.Database,\n namespace\n };\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport firebase, { FirebaseNamespace } from '@firebase/app-compat';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport { Component, ComponentType } from '@firebase/component';\nimport { enableLogging } from '@firebase/database';\nimport * as types from '@firebase/database-types';\n\nimport { name, version } from '../package.json';\nimport { Database } from '../src/api/Database';\nimport * as INTERNAL from '../src/api/internal';\nimport { DataSnapshot, Query, Reference } from '../src/api/Reference';\n\nconst ServerValue = Database.ServerValue;\n\nexport function registerDatabase(instance: FirebaseNamespace) {\n // Register the Database Service with the 'firebase' namespace.\n (instance as unknown as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component(\n 'database-compat',\n (container, { instanceIdentifier: url }) => {\n /* Dependencies */\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app-compat').getImmediate();\n const databaseExp = container\n .getProvider('database')\n .getImmediate({ identifier: url });\n return new Database(databaseExp, app);\n },\n ComponentType.PUBLIC\n )\n .setServiceProps(\n // firebase.database namespace properties\n {\n Reference,\n Query,\n Database,\n DataSnapshot,\n enableLogging,\n INTERNAL,\n ServerValue\n }\n )\n .setMultipleInstances(true)\n );\n\n instance.registerVersion(name, version);\n}\n\nregisterDatabase(firebase);\n\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n database?: {\n (app?: FirebaseApp): types.FirebaseDatabase;\n enableLogging: typeof types.enableLogging;\n ServerValue: types.ServerValue;\n Database: typeof types.FirebaseDatabase;\n };\n }\n interface FirebaseApp {\n database?(databaseURL?: string): types.FirebaseDatabase;\n }\n}\n"],"names":["errorPrefixFxn","ModularOnDisconnect"],"mappings":";;;;;;;;;AAAA;;;;;;;;;;;;;;;AAeG;AAIH,MAAM,SAAS,GAAG,IAAI,MAAM,CAAC,2BAA2B,CAAC,CAAC;AAEnD,MAAM,IAAI,GAAG,UAAU,GAAW,EAAA;AACvC,IAAA,MAAM,OAAO,GAAG,oBAAoB,GAAG,GAAG,CAAC;AAC3C,IAAA,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AAC1B,CAAC;;ACxBD;;;;;;;;;;;;;;;AAeG;AAII,MAAM,eAAe,GAAG,UAC7B,MAAc,EACd,YAAoB,EACpB,IAAa,EACb,QAAiB,EAAA;AAEjB,IAAA,IAAI,QAAQ,IAAI,IAAI,KAAK,SAAS,EAAE;QAClC,OAAO;KACR;AACD,IAAA,IAAI,OAAO,IAAI,KAAK,SAAS,EAAE;AAC7B,QAAA,MAAM,IAAI,KAAK,CACbA,WAAc,CAAC,MAAM,EAAE,YAAY,CAAC,GAAG,oBAAoB,CAC5D,CAAC;KACH;AACH,CAAC,CAAC;AAEK,MAAM,iBAAiB,GAAG,UAC/B,MAAc,EACd,SAAiB,EACjB,QAAiB,EAAA;AAEjB,IAAA,IAAI,QAAQ,IAAI,SAAS,KAAK,SAAS,EAAE;QACvC,OAAO;KACR;IAED,QAAQ,SAAS;AACf,QAAA,KAAK,OAAO,CAAC;AACb,QAAA,KAAK,aAAa,CAAC;AACnB,QAAA,KAAK,eAAe,CAAC;AACrB,QAAA,KAAK,eAAe,CAAC;AACrB,QAAA,KAAK,aAAa;YAChB,MAAM;AACR,QAAA;Y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C,KAAC,EAEF,QAAA,4BAAA;SACE,eAAe;;AAEd,IAAA;QACE,SAAS;QACT,KAAK;QACL,QAAQ;QACR,YAAY;QACZ,aAAa;QACb,QAAQ;QACR,WAAW;KACZ,CACF;AACA,SAAA,oBAAoB,CAAC,IAAI,CAAC,CAC9B,CAAC;AAEF,IAAA,QAAQ,CAAC,eAAe,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AAC1C,CAAC;AAED,gBAAgB,CAAC,QAAQ,CAAC;;;;"} \ No newline at end of file diff --git a/node_modules/@firebase/database-compat/dist/index.js b/node_modules/@firebase/database-compat/dist/index.js new file mode 100644 index 0000000..cbf8613 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/index.js @@ -0,0 +1,864 @@ +'use strict'; + +var firebase = require('@firebase/app-compat'); +var component = require('@firebase/component'); +var database = require('@firebase/database'); +var util = require('@firebase/util'); +var logger = require('@firebase/logger'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var firebase__default = /*#__PURE__*/_interopDefaultLegacy(firebase); + +const name = "@firebase/database-compat"; +const version = "2.1.0"; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const logClient = new logger.Logger('@firebase/database-compat'); +const warn = function (msg) { + const message = 'FIREBASE WARNING: ' + msg; + logClient.warn(message); +}; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const validateBoolean = function (fnName, argumentName, bool, optional) { + if (optional && bool === undefined) { + return; + } + if (typeof bool !== 'boolean') { + throw new Error(util.errorPrefix(fnName, argumentName) + 'must be a boolean.'); + } +}; +const validateEventType = function (fnName, eventType, optional) { + if (optional && eventType === undefined) { + return; + } + switch (eventType) { + case 'value': + case 'child_added': + case 'child_removed': + case 'child_changed': + case 'child_moved': + break; + default: + throw new Error(util.errorPrefix(fnName, 'eventType') + + 'must be a valid event type = "value", "child_added", "child_removed", ' + + '"child_changed", or "child_moved".'); + } +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class OnDisconnect { + constructor(_delegate) { + this._delegate = _delegate; + } + cancel(onComplete) { + util.validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length); + util.validateCallback('OnDisconnect.cancel', 'onComplete', onComplete, true); + const result = this._delegate.cancel(); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + remove(onComplete) { + util.validateArgCount('OnDisconnect.remove', 0, 1, arguments.length); + util.validateCallback('OnDisconnect.remove', 'onComplete', onComplete, true); + const result = this._delegate.remove(); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + set(value, onComplete) { + util.validateArgCount('OnDisconnect.set', 1, 2, arguments.length); + util.validateCallback('OnDisconnect.set', 'onComplete', onComplete, true); + const result = this._delegate.set(value); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + setWithPriority(value, priority, onComplete) { + util.validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length); + util.validateCallback('OnDisconnect.setWithPriority', 'onComplete', onComplete, true); + const result = this._delegate.setWithPriority(value, priority); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + update(objectToMerge, onComplete) { + util.validateArgCount('OnDisconnect.update', 1, 2, arguments.length); + if (Array.isArray(objectToMerge)) { + const newObjectToMerge = {}; + for (let i = 0; i < objectToMerge.length; ++i) { + newObjectToMerge['' + i] = objectToMerge[i]; + } + objectToMerge = newObjectToMerge; + warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' + + 'existing data, or an Object with integer keys if you really do want to only update some of the children.'); + } + util.validateCallback('OnDisconnect.update', 'onComplete', onComplete, true); + const result = this._delegate.update(objectToMerge); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class TransactionResult { + /** + * A type for the resolve value of Firebase.transaction. + */ + constructor(committed, snapshot) { + this.committed = committed; + this.snapshot = snapshot; + } + // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary + // for end-users + toJSON() { + util.validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length); + return { committed: this.committed, snapshot: this.snapshot.toJSON() }; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Class representing a firebase data snapshot. It wraps a SnapshotNode and + * surfaces the public methods (val, forEach, etc.) we want to expose. + */ +class DataSnapshot { + constructor(_database, _delegate) { + this._database = _database; + this._delegate = _delegate; + } + /** + * Retrieves the snapshot contents as JSON. Returns null if the snapshot is + * empty. + * + * @returns JSON representation of the DataSnapshot contents, or null if empty. + */ + val() { + util.validateArgCount('DataSnapshot.val', 0, 0, arguments.length); + return this._delegate.val(); + } + /** + * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting + * the entire node contents. + * @returns JSON representation of the DataSnapshot contents, or null if empty. + */ + exportVal() { + util.validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length); + return this._delegate.exportVal(); + } + // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary + // for end-users + toJSON() { + // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content + util.validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length); + return this._delegate.toJSON(); + } + /** + * Returns whether the snapshot contains a non-null value. + * + * @returns Whether the snapshot contains a non-null value, or is empty. + */ + exists() { + util.validateArgCount('DataSnapshot.exists', 0, 0, arguments.length); + return this._delegate.exists(); + } + /** + * Returns a DataSnapshot of the specified child node's contents. + * + * @param path - Path to a child. + * @returns DataSnapshot for child node. + */ + child(path) { + util.validateArgCount('DataSnapshot.child', 0, 1, arguments.length); + // Ensure the childPath is a string (can be a number) + path = String(path); + database._validatePathString('DataSnapshot.child', 'path', path, false); + return new DataSnapshot(this._database, this._delegate.child(path)); + } + /** + * Returns whether the snapshot contains a child at the specified path. + * + * @param path - Path to a child. + * @returns Whether the child exists. + */ + hasChild(path) { + util.validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length); + database._validatePathString('DataSnapshot.hasChild', 'path', path, false); + return this._delegate.hasChild(path); + } + /** + * Returns the priority of the object, or null if no priority was set. + * + * @returns The priority. + */ + getPriority() { + util.validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length); + return this._delegate.priority; + } + /** + * Iterates through child nodes and calls the specified action for each one. + * + * @param action - Callback function to be called + * for each child. + * @returns True if forEach was canceled by action returning true for + * one of the child nodes. + */ + forEach(action) { + util.validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length); + util.validateCallback('DataSnapshot.forEach', 'action', action, false); + return this._delegate.forEach(expDataSnapshot => action(new DataSnapshot(this._database, expDataSnapshot))); + } + /** + * Returns whether this DataSnapshot has children. + * @returns True if the DataSnapshot contains 1 or more child nodes. + */ + hasChildren() { + util.validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length); + return this._delegate.hasChildren(); + } + get key() { + return this._delegate.key; + } + /** + * Returns the number of children for this DataSnapshot. + * @returns The number of children that this DataSnapshot contains. + */ + numChildren() { + util.validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length); + return this._delegate.size; + } + /** + * @returns The Firebase reference for the location this snapshot's data came + * from. + */ + getRef() { + util.validateArgCount('DataSnapshot.ref', 0, 0, arguments.length); + return new Reference(this._database, this._delegate.ref); + } + get ref() { + return this.getRef(); + } +} +/** + * A Query represents a filter to be applied to a firebase location. This object purely represents the + * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js. + * + * Since every Firebase reference is a query, Firebase inherits from this object. + */ +class Query { + constructor(database, _delegate) { + this.database = database; + this._delegate = _delegate; + } + on(eventType, callback, cancelCallbackOrContext, context) { + util.validateArgCount('Query.on', 2, 4, arguments.length); + util.validateCallback('Query.on', 'callback', callback, false); + const ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context); + const valueCallback = (expSnapshot, previousChildName) => { + callback.call(ret.context, new DataSnapshot(this.database, expSnapshot), previousChildName); + }; + valueCallback.userCallback = callback; + valueCallback.context = ret.context; + const cancelCallback = ret.cancel?.bind(ret.context); + switch (eventType) { + case 'value': + database.onValue(this._delegate, valueCallback, cancelCallback); + return callback; + case 'child_added': + database.onChildAdded(this._delegate, valueCallback, cancelCallback); + return callback; + case 'child_removed': + database.onChildRemoved(this._delegate, valueCallback, cancelCallback); + return callback; + case 'child_changed': + database.onChildChanged(this._delegate, valueCallback, cancelCallback); + return callback; + case 'child_moved': + database.onChildMoved(this._delegate, valueCallback, cancelCallback); + return callback; + default: + throw new Error(util.errorPrefix('Query.on', 'eventType') + + 'must be a valid event type = "value", "child_added", "child_removed", ' + + '"child_changed", or "child_moved".'); + } + } + off(eventType, callback, context) { + util.validateArgCount('Query.off', 0, 3, arguments.length); + validateEventType('Query.off', eventType, true); + util.validateCallback('Query.off', 'callback', callback, true); + util.validateContextObject('Query.off', 'context', context, true); + if (callback) { + const valueCallback = () => { }; + valueCallback.userCallback = callback; + valueCallback.context = context; + database.off(this._delegate, eventType, valueCallback); + } + else { + database.off(this._delegate, eventType); + } + } + /** + * Get the server-value for this query, or return a cached value if not connected. + */ + get() { + return database.get(this._delegate).then(expSnapshot => { + return new DataSnapshot(this.database, expSnapshot); + }); + } + /** + * Attaches a listener, waits for the first event, and then removes the listener + */ + once(eventType, callback, failureCallbackOrContext, context) { + util.validateArgCount('Query.once', 1, 4, arguments.length); + util.validateCallback('Query.once', 'callback', callback, true); + const ret = Query.getCancelAndContextArgs_('Query.once', failureCallbackOrContext, context); + const deferred = new util.Deferred(); + const valueCallback = (expSnapshot, previousChildName) => { + const result = new DataSnapshot(this.database, expSnapshot); + if (callback) { + callback.call(ret.context, result, previousChildName); + } + deferred.resolve(result); + }; + valueCallback.userCallback = callback; + valueCallback.context = ret.context; + const cancelCallback = (error) => { + if (ret.cancel) { + ret.cancel.call(ret.context, error); + } + deferred.reject(error); + }; + switch (eventType) { + case 'value': + database.onValue(this._delegate, valueCallback, cancelCallback, { + onlyOnce: true + }); + break; + case 'child_added': + database.onChildAdded(this._delegate, valueCallback, cancelCallback, { + onlyOnce: true + }); + break; + case 'child_removed': + database.onChildRemoved(this._delegate, valueCallback, cancelCallback, { + onlyOnce: true + }); + break; + case 'child_changed': + database.onChildChanged(this._delegate, valueCallback, cancelCallback, { + onlyOnce: true + }); + break; + case 'child_moved': + database.onChildMoved(this._delegate, valueCallback, cancelCallback, { + onlyOnce: true + }); + break; + default: + throw new Error(util.errorPrefix('Query.once', 'eventType') + + 'must be a valid event type = "value", "child_added", "child_removed", ' + + '"child_changed", or "child_moved".'); + } + return deferred.promise; + } + /** + * Set a limit and anchor it to the start of the window. + */ + limitToFirst(limit) { + util.validateArgCount('Query.limitToFirst', 1, 1, arguments.length); + return new Query(this.database, database.query(this._delegate, database.limitToFirst(limit))); + } + /** + * Set a limit and anchor it to the end of the window. + */ + limitToLast(limit) { + util.validateArgCount('Query.limitToLast', 1, 1, arguments.length); + return new Query(this.database, database.query(this._delegate, database.limitToLast(limit))); + } + /** + * Given a child path, return a new query ordered by the specified grandchild path. + */ + orderByChild(path) { + util.validateArgCount('Query.orderByChild', 1, 1, arguments.length); + return new Query(this.database, database.query(this._delegate, database.orderByChild(path))); + } + /** + * Return a new query ordered by the KeyIndex + */ + orderByKey() { + util.validateArgCount('Query.orderByKey', 0, 0, arguments.length); + return new Query(this.database, database.query(this._delegate, database.orderByKey())); + } + /** + * Return a new query ordered by the PriorityIndex + */ + orderByPriority() { + util.validateArgCount('Query.orderByPriority', 0, 0, arguments.length); + return new Query(this.database, database.query(this._delegate, database.orderByPriority())); + } + /** + * Return a new query ordered by the ValueIndex + */ + orderByValue() { + util.validateArgCount('Query.orderByValue', 0, 0, arguments.length); + return new Query(this.database, database.query(this._delegate, database.orderByValue())); + } + startAt(value = null, name) { + util.validateArgCount('Query.startAt', 0, 2, arguments.length); + return new Query(this.database, database.query(this._delegate, database.startAt(value, name))); + } + startAfter(value = null, name) { + util.validateArgCount('Query.startAfter', 0, 2, arguments.length); + return new Query(this.database, database.query(this._delegate, database.startAfter(value, name))); + } + endAt(value = null, name) { + util.validateArgCount('Query.endAt', 0, 2, arguments.length); + return new Query(this.database, database.query(this._delegate, database.endAt(value, name))); + } + endBefore(value = null, name) { + util.validateArgCount('Query.endBefore', 0, 2, arguments.length); + return new Query(this.database, database.query(this._delegate, database.endBefore(value, name))); + } + /** + * Load the selection of children with exactly the specified value, and, optionally, + * the specified name. + */ + equalTo(value, name) { + util.validateArgCount('Query.equalTo', 1, 2, arguments.length); + return new Query(this.database, database.query(this._delegate, database.equalTo(value, name))); + } + /** + * @returns URL for this location. + */ + toString() { + util.validateArgCount('Query.toString', 0, 0, arguments.length); + return this._delegate.toString(); + } + // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary + // for end-users. + toJSON() { + // An optional spacer argument is unnecessary for a string. + util.validateArgCount('Query.toJSON', 0, 1, arguments.length); + return this._delegate.toJSON(); + } + /** + * Return true if this query and the provided query are equivalent; otherwise, return false. + */ + isEqual(other) { + util.validateArgCount('Query.isEqual', 1, 1, arguments.length); + if (!(other instanceof Query)) { + const error = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.'; + throw new Error(error); + } + return this._delegate.isEqual(other._delegate); + } + /** + * Helper used by .on and .once to extract the context and or cancel arguments. + * @param fnName - The function name (on or once) + * + */ + static getCancelAndContextArgs_(fnName, cancelOrContext, context) { + const ret = { cancel: undefined, context: undefined }; + if (cancelOrContext && context) { + ret.cancel = cancelOrContext; + util.validateCallback(fnName, 'cancel', ret.cancel, true); + ret.context = context; + util.validateContextObject(fnName, 'context', ret.context, true); + } + else if (cancelOrContext) { + // we have either a cancel callback or a context. + if (typeof cancelOrContext === 'object' && cancelOrContext !== null) { + // it's a context! + ret.context = cancelOrContext; + } + else if (typeof cancelOrContext === 'function') { + ret.cancel = cancelOrContext; + } + else { + throw new Error(util.errorPrefix(fnName, 'cancelOrContext') + + ' must either be a cancel callback or a context object.'); + } + } + return ret; + } + get ref() { + return new Reference(this.database, new database._ReferenceImpl(this._delegate._repo, this._delegate._path)); + } +} +class Reference extends Query { + /** + * Call options: + * new Reference(Repo, Path) or + * new Reference(url: string, string|RepoManager) + * + * Externally - this is the firebase.database.Reference type. + */ + constructor(database$1, _delegate) { + super(database$1, new database._QueryImpl(_delegate._repo, _delegate._path, new database._QueryParams(), false)); + this.database = database$1; + this._delegate = _delegate; + } + /** @returns {?string} */ + getKey() { + util.validateArgCount('Reference.key', 0, 0, arguments.length); + return this._delegate.key; + } + child(pathString) { + util.validateArgCount('Reference.child', 1, 1, arguments.length); + if (typeof pathString === 'number') { + pathString = String(pathString); + } + return new Reference(this.database, database.child(this._delegate, pathString)); + } + /** @returns {?Reference} */ + getParent() { + util.validateArgCount('Reference.parent', 0, 0, arguments.length); + const parent = this._delegate.parent; + return parent ? new Reference(this.database, parent) : null; + } + /** @returns {!Reference} */ + getRoot() { + util.validateArgCount('Reference.root', 0, 0, arguments.length); + return new Reference(this.database, this._delegate.root); + } + set(newVal, onComplete) { + util.validateArgCount('Reference.set', 1, 2, arguments.length); + util.validateCallback('Reference.set', 'onComplete', onComplete, true); + const result = database.set(this._delegate, newVal); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + update(values, onComplete) { + util.validateArgCount('Reference.update', 1, 2, arguments.length); + if (Array.isArray(values)) { + const newObjectToMerge = {}; + for (let i = 0; i < values.length; ++i) { + newObjectToMerge['' + i] = values[i]; + } + values = newObjectToMerge; + warn('Passing an Array to Firebase.update() is deprecated. ' + + 'Use set() if you want to overwrite the existing data, or ' + + 'an Object with integer keys if you really do want to ' + + 'only update some of the children.'); + } + database._validateWritablePath('Reference.update', this._delegate._path); + util.validateCallback('Reference.update', 'onComplete', onComplete, true); + const result = database.update(this._delegate, values); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + setWithPriority(newVal, newPriority, onComplete) { + util.validateArgCount('Reference.setWithPriority', 2, 3, arguments.length); + util.validateCallback('Reference.setWithPriority', 'onComplete', onComplete, true); + const result = database.setWithPriority(this._delegate, newVal, newPriority); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + remove(onComplete) { + util.validateArgCount('Reference.remove', 0, 1, arguments.length); + util.validateCallback('Reference.remove', 'onComplete', onComplete, true); + const result = database.remove(this._delegate); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + transaction(transactionUpdate, onComplete, applyLocally) { + util.validateArgCount('Reference.transaction', 1, 3, arguments.length); + util.validateCallback('Reference.transaction', 'transactionUpdate', transactionUpdate, false); + util.validateCallback('Reference.transaction', 'onComplete', onComplete, true); + validateBoolean('Reference.transaction', 'applyLocally', applyLocally, true); + const result = database.runTransaction(this._delegate, transactionUpdate, { + applyLocally + }).then(transactionResult => new TransactionResult(transactionResult.committed, new DataSnapshot(this.database, transactionResult.snapshot))); + if (onComplete) { + result.then(transactionResult => onComplete(null, transactionResult.committed, transactionResult.snapshot), error => onComplete(error, false, null)); + } + return result; + } + setPriority(priority, onComplete) { + util.validateArgCount('Reference.setPriority', 1, 2, arguments.length); + util.validateCallback('Reference.setPriority', 'onComplete', onComplete, true); + const result = database.setPriority(this._delegate, priority); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + push(value, onComplete) { + util.validateArgCount('Reference.push', 0, 2, arguments.length); + util.validateCallback('Reference.push', 'onComplete', onComplete, true); + const expPromise = database.push(this._delegate, value); + const promise = expPromise.then(expRef => new Reference(this.database, expRef)); + if (onComplete) { + promise.then(() => onComplete(null), error => onComplete(error)); + } + const result = new Reference(this.database, expPromise); + result.then = promise.then.bind(promise); + result.catch = promise.catch.bind(promise, undefined); + return result; + } + onDisconnect() { + database._validateWritablePath('Reference.onDisconnect', this._delegate._path); + return new OnDisconnect(new database.OnDisconnect(this._delegate._repo, this._delegate._path)); + } + get key() { + return this.getKey(); + } + get parent() { + return this.getParent(); + } + get root() { + return this.getRoot(); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Class representing a firebase database. + */ +class Database { + /** + * The constructor should not be called by users of our public API. + */ + constructor(_delegate, app) { + this._delegate = _delegate; + this.app = app; + this.INTERNAL = { + delete: () => this._delegate._delete(), + forceWebSockets: database.forceWebSockets, + forceLongPolling: database.forceLongPolling + }; + } + /** + * Modify this instance to communicate with the Realtime Database emulator. + * + *

Note: This method must be called before performing any other operation. + * + * @param host - the emulator host (ex: localhost) + * @param port - the emulator port (ex: 8080) + * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules + */ + useEmulator(host, port, options = {}) { + database.connectDatabaseEmulator(this._delegate, host, port, options); + } + ref(path) { + util.validateArgCount('database.ref', 0, 1, arguments.length); + if (path instanceof Reference) { + const childRef = database.refFromURL(this._delegate, path.toString()); + return new Reference(this, childRef); + } + else { + const childRef = database.ref(this._delegate, path); + return new Reference(this, childRef); + } + } + /** + * Returns a reference to the root or the path specified in url. + * We throw a exception if the url is not in the same domain as the + * current repo. + * @returns Firebase reference. + */ + refFromURL(url) { + const apiName = 'database.refFromURL'; + util.validateArgCount(apiName, 1, 1, arguments.length); + const childRef = database.refFromURL(this._delegate, url); + return new Reference(this, childRef); + } + // Make individual repo go offline. + goOffline() { + util.validateArgCount('database.goOffline', 0, 0, arguments.length); + return database.goOffline(this._delegate); + } + goOnline() { + util.validateArgCount('database.goOnline', 0, 0, arguments.length); + return database.goOnline(this._delegate); + } +} +Database.ServerValue = { + TIMESTAMP: database.serverTimestamp(), + increment: (delta) => database.increment(delta) +}; + +/** + * Used by console to create a database based on the app, + * passed database URL and a custom auth implementation. + * + * @param app - A valid FirebaseApp-like object + * @param url - A valid Firebase databaseURL + * @param version - custom version e.g. firebase-admin version + * @param customAuthImpl - custom auth implementation + */ +function initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, namespace, nodeAdmin = false }) { + database._setSDKVersion(version); + const container = new component.ComponentContainer('database-standalone'); + /** + * ComponentContainer('database-standalone') is just a placeholder that doesn't perform + * any actual function. + */ + const authProvider = new component.Provider('auth-internal', container); + authProvider.setComponent(new component.Component('auth-internal', () => customAuthImpl, "PRIVATE" /* ComponentType.PRIVATE */)); + let appCheckProvider = undefined; + if (customAppCheckImpl) { + appCheckProvider = new component.Provider('app-check-internal', container); + appCheckProvider.setComponent(new component.Component('app-check-internal', () => customAppCheckImpl, "PRIVATE" /* ComponentType.PRIVATE */)); + } + return { + instance: new Database(database._repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin), app), + namespace + }; +} + +var INTERNAL = /*#__PURE__*/Object.freeze({ + __proto__: null, + initStandalone: initStandalone +}); + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const ServerValue = Database.ServerValue; +function registerDatabase(instance) { + // Register the Database Service with the 'firebase' namespace. + instance.INTERNAL.registerComponent(new component.Component('database-compat', (container, { instanceIdentifier: url }) => { + /* Dependencies */ + // getImmediate for FirebaseApp will always succeed + const app = container.getProvider('app-compat').getImmediate(); + const databaseExp = container + .getProvider('database') + .getImmediate({ identifier: url }); + return new Database(databaseExp, app); + }, "PUBLIC" /* ComponentType.PUBLIC */) + .setServiceProps( + // firebase.database namespace properties + { + Reference, + Query, + Database, + DataSnapshot, + enableLogging: database.enableLogging, + INTERNAL, + ServerValue + }) + .setMultipleInstances(true)); + instance.registerVersion(name, version, 'node'); +} +registerDatabase(firebase__default["default"]); +//# sourceMappingURL=index.js.map diff --git a/node_modules/@firebase/database-compat/dist/index.js.map b/node_modules/@firebase/database-compat/dist/index.js.map new file mode 100644 index 0000000..23b0007 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../src/util/util.ts","../src/util/validation.ts","../src/api/onDisconnect.ts","../src/api/TransactionResult.ts","../src/api/Reference.ts","../src/api/Database.ts","../src/api/internal.ts","../src/index.node.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nconst logClient = new Logger('@firebase/database-compat');\n\nexport const warn = function (msg: string) {\n const message = 'FIREBASE WARNING: ' + msg;\n logClient.warn(message);\n};\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { errorPrefix as errorPrefixFxn } from '@firebase/util';\n\nexport const validateBoolean = function (\n fnName: string,\n argumentName: string,\n bool: unknown,\n optional: boolean\n) {\n if (optional && bool === undefined) {\n return;\n }\n if (typeof bool !== 'boolean') {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) + 'must be a boolean.'\n );\n }\n};\n\nexport const validateEventType = function (\n fnName: string,\n eventType: string,\n optional: boolean\n) {\n if (optional && eventType === undefined) {\n return;\n }\n\n switch (eventType) {\n case 'value':\n case 'child_added':\n case 'child_removed':\n case 'child_changed':\n case 'child_moved':\n break;\n default:\n throw new Error(\n errorPrefixFxn(fnName, 'eventType') +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".'\n );\n }\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { OnDisconnect as ModularOnDisconnect } from '@firebase/database';\nimport { validateArgCount, validateCallback, Compat } from '@firebase/util';\n\nimport { warn } from '../util/util';\nexport class OnDisconnect implements Compat {\n constructor(readonly _delegate: ModularOnDisconnect) {}\n\n cancel(onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);\n validateCallback('OnDisconnect.cancel', 'onComplete', onComplete, true);\n const result = this._delegate.cancel();\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n remove(onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);\n validateCallback('OnDisconnect.remove', 'onComplete', onComplete, true);\n const result = this._delegate.remove();\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n set(value: unknown, onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('OnDisconnect.set', 1, 2, arguments.length);\n validateCallback('OnDisconnect.set', 'onComplete', onComplete, true);\n const result = this._delegate.set(value);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n setWithPriority(\n value: unknown,\n priority: number | string | null,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length);\n validateCallback(\n 'OnDisconnect.setWithPriority',\n 'onComplete',\n onComplete,\n true\n );\n const result = this._delegate.setWithPriority(value, priority);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n update(\n objectToMerge: Record,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('OnDisconnect.update', 1, 2, arguments.length);\n if (Array.isArray(objectToMerge)) {\n const newObjectToMerge: { [k: string]: unknown } = {};\n for (let i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n warn(\n 'Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' +\n 'existing data, or an Object with integer keys if you really do want to only update some of the children.'\n );\n }\n validateCallback('OnDisconnect.update', 'onComplete', onComplete, true);\n const result = this._delegate.update(objectToMerge);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { validateArgCount } from '@firebase/util';\n\nimport { DataSnapshot } from './Reference';\n\nexport class TransactionResult {\n /**\n * A type for the resolve value of Firebase.transaction.\n */\n constructor(public committed: boolean, public snapshot: DataSnapshot) {}\n\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n toJSON(): object {\n validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n OnDisconnect as ModularOnDisconnect,\n off,\n onChildAdded,\n onChildChanged,\n onChildMoved,\n onChildRemoved,\n onValue,\n EventType,\n limitToFirst,\n query,\n limitToLast,\n orderByChild,\n orderByKey,\n orderByValue,\n orderByPriority,\n startAt,\n startAfter,\n endAt,\n endBefore,\n equalTo,\n get,\n set,\n update,\n setWithPriority,\n remove,\n setPriority,\n push,\n runTransaction,\n child,\n DataSnapshot as ModularDataSnapshot,\n Query as ExpQuery,\n DatabaseReference as ModularReference,\n _QueryImpl,\n _ReferenceImpl,\n _validatePathString,\n _validateWritablePath,\n _UserCallback,\n _QueryParams\n} from '@firebase/database';\nimport {\n Compat,\n Deferred,\n errorPrefix,\n validateArgCount,\n validateCallback,\n validateContextObject\n} from '@firebase/util';\n\nimport { warn } from '../util/util';\nimport { validateBoolean, validateEventType } from '../util/validation';\n\nimport { Database } from './Database';\nimport { OnDisconnect } from './onDisconnect';\nimport { TransactionResult } from './TransactionResult';\n\n/**\n * Class representing a firebase data snapshot. It wraps a SnapshotNode and\n * surfaces the public methods (val, forEach, etc.) we want to expose.\n */\nexport class DataSnapshot implements Compat {\n constructor(\n readonly _database: Database,\n readonly _delegate: ModularDataSnapshot\n ) {}\n\n /**\n * Retrieves the snapshot contents as JSON. Returns null if the snapshot is\n * empty.\n *\n * @returns JSON representation of the DataSnapshot contents, or null if empty.\n */\n val(): unknown {\n validateArgCount('DataSnapshot.val', 0, 0, arguments.length);\n return this._delegate.val();\n }\n\n /**\n * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting\n * the entire node contents.\n * @returns JSON representation of the DataSnapshot contents, or null if empty.\n */\n exportVal(): unknown {\n validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length);\n return this._delegate.exportVal();\n }\n\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n toJSON(): unknown {\n // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content\n validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length);\n return this._delegate.toJSON();\n }\n\n /**\n * Returns whether the snapshot contains a non-null value.\n *\n * @returns Whether the snapshot contains a non-null value, or is empty.\n */\n exists(): boolean {\n validateArgCount('DataSnapshot.exists', 0, 0, arguments.length);\n return this._delegate.exists();\n }\n\n /**\n * Returns a DataSnapshot of the specified child node's contents.\n *\n * @param path - Path to a child.\n * @returns DataSnapshot for child node.\n */\n child(path: string): DataSnapshot {\n validateArgCount('DataSnapshot.child', 0, 1, arguments.length);\n // Ensure the childPath is a string (can be a number)\n path = String(path);\n _validatePathString('DataSnapshot.child', 'path', path, false);\n return new DataSnapshot(this._database, this._delegate.child(path));\n }\n\n /**\n * Returns whether the snapshot contains a child at the specified path.\n *\n * @param path - Path to a child.\n * @returns Whether the child exists.\n */\n hasChild(path: string): boolean {\n validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);\n _validatePathString('DataSnapshot.hasChild', 'path', path, false);\n return this._delegate.hasChild(path);\n }\n\n /**\n * Returns the priority of the object, or null if no priority was set.\n *\n * @returns The priority.\n */\n getPriority(): string | number | null {\n validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);\n return this._delegate.priority;\n }\n\n /**\n * Iterates through child nodes and calls the specified action for each one.\n *\n * @param action - Callback function to be called\n * for each child.\n * @returns True if forEach was canceled by action returning true for\n * one of the child nodes.\n */\n forEach(action: (snapshot: IteratedDataSnapshot) => boolean | void): boolean {\n validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);\n validateCallback('DataSnapshot.forEach', 'action', action, false);\n return this._delegate.forEach(expDataSnapshot =>\n action(new DataSnapshot(this._database, expDataSnapshot))\n );\n }\n\n /**\n * Returns whether this DataSnapshot has children.\n * @returns True if the DataSnapshot contains 1 or more child nodes.\n */\n hasChildren(): boolean {\n validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);\n return this._delegate.hasChildren();\n }\n\n get key() {\n return this._delegate.key;\n }\n\n /**\n * Returns the number of children for this DataSnapshot.\n * @returns The number of children that this DataSnapshot contains.\n */\n numChildren(): number {\n validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);\n return this._delegate.size;\n }\n\n /**\n * @returns The Firebase reference for the location this snapshot's data came\n * from.\n */\n getRef(): Reference {\n validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);\n return new Reference(this._database, this._delegate.ref);\n }\n\n get ref(): Reference {\n return this.getRef();\n }\n}\n\n/**\n * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined.\n */\nexport interface IteratedDataSnapshot extends DataSnapshot {\n key: string; // key of the location of this snapshot.\n}\n\nexport interface SnapshotCallback {\n (dataSnapshot: DataSnapshot, previousChildName?: string | null): unknown;\n}\n\n/**\n * A Query represents a filter to be applied to a firebase location. This object purely represents the\n * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js.\n *\n * Since every Firebase reference is a query, Firebase inherits from this object.\n */\nexport class Query implements Compat {\n constructor(readonly database: Database, readonly _delegate: ExpQuery) {}\n\n on(\n eventType: string,\n callback: SnapshotCallback,\n cancelCallbackOrContext?: ((a: Error) => unknown) | object | null,\n context?: object | null\n ): SnapshotCallback {\n validateArgCount('Query.on', 2, 4, arguments.length);\n validateCallback('Query.on', 'callback', callback, false);\n\n const ret = Query.getCancelAndContextArgs_(\n 'Query.on',\n cancelCallbackOrContext,\n context\n );\n const valueCallback = (expSnapshot, previousChildName?) => {\n callback.call(\n ret.context,\n new DataSnapshot(this.database, expSnapshot),\n previousChildName\n );\n };\n valueCallback.userCallback = callback;\n valueCallback.context = ret.context;\n const cancelCallback = ret.cancel?.bind(ret.context);\n\n switch (eventType) {\n case 'value':\n onValue(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_added':\n onChildAdded(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_removed':\n onChildRemoved(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_changed':\n onChildChanged(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_moved':\n onChildMoved(this._delegate, valueCallback, cancelCallback);\n return callback;\n default:\n throw new Error(\n errorPrefix('Query.on', 'eventType') +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".'\n );\n }\n }\n\n off(\n eventType?: string,\n callback?: SnapshotCallback,\n context?: object | null\n ): void {\n validateArgCount('Query.off', 0, 3, arguments.length);\n validateEventType('Query.off', eventType, true);\n validateCallback('Query.off', 'callback', callback, true);\n validateContextObject('Query.off', 'context', context, true);\n if (callback) {\n const valueCallback: _UserCallback = () => {};\n valueCallback.userCallback = callback;\n valueCallback.context = context;\n off(this._delegate, eventType as EventType, valueCallback);\n } else {\n off(this._delegate, eventType as EventType | undefined);\n }\n }\n\n /**\n * Get the server-value for this query, or return a cached value if not connected.\n */\n get(): Promise {\n return get(this._delegate).then(expSnapshot => {\n return new DataSnapshot(this.database, expSnapshot);\n });\n }\n\n /**\n * Attaches a listener, waits for the first event, and then removes the listener\n */\n once(\n eventType: string,\n callback?: SnapshotCallback,\n failureCallbackOrContext?: ((a: Error) => void) | object | null,\n context?: object | null\n ): Promise {\n validateArgCount('Query.once', 1, 4, arguments.length);\n validateCallback('Query.once', 'callback', callback, true);\n\n const ret = Query.getCancelAndContextArgs_(\n 'Query.once',\n failureCallbackOrContext,\n context\n );\n const deferred = new Deferred();\n const valueCallback: _UserCallback = (expSnapshot, previousChildName?) => {\n const result = new DataSnapshot(this.database, expSnapshot);\n if (callback) {\n callback.call(ret.context, result, previousChildName);\n }\n deferred.resolve(result);\n };\n valueCallback.userCallback = callback;\n valueCallback.context = ret.context;\n const cancelCallback = (error: Error) => {\n if (ret.cancel) {\n ret.cancel.call(ret.context, error);\n }\n deferred.reject(error);\n };\n\n switch (eventType) {\n case 'value':\n onValue(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_added':\n onChildAdded(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_removed':\n onChildRemoved(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_changed':\n onChildChanged(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_moved':\n onChildMoved(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n default:\n throw new Error(\n errorPrefix('Query.once', 'eventType') +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".'\n );\n }\n\n return deferred.promise;\n }\n\n /**\n * Set a limit and anchor it to the start of the window.\n */\n limitToFirst(limit: number): Query {\n validateArgCount('Query.limitToFirst', 1, 1, arguments.length);\n return new Query(this.database, query(this._delegate, limitToFirst(limit)));\n }\n\n /**\n * Set a limit and anchor it to the end of the window.\n */\n limitToLast(limit: number): Query {\n validateArgCount('Query.limitToLast', 1, 1, arguments.length);\n return new Query(this.database, query(this._delegate, limitToLast(limit)));\n }\n\n /**\n * Given a child path, return a new query ordered by the specified grandchild path.\n */\n orderByChild(path: string): Query {\n validateArgCount('Query.orderByChild', 1, 1, arguments.length);\n return new Query(this.database, query(this._delegate, orderByChild(path)));\n }\n\n /**\n * Return a new query ordered by the KeyIndex\n */\n orderByKey(): Query {\n validateArgCount('Query.orderByKey', 0, 0, arguments.length);\n return new Query(this.database, query(this._delegate, orderByKey()));\n }\n\n /**\n * Return a new query ordered by the PriorityIndex\n */\n orderByPriority(): Query {\n validateArgCount('Query.orderByPriority', 0, 0, arguments.length);\n return new Query(this.database, query(this._delegate, orderByPriority()));\n }\n\n /**\n * Return a new query ordered by the ValueIndex\n */\n orderByValue(): Query {\n validateArgCount('Query.orderByValue', 0, 0, arguments.length);\n return new Query(this.database, query(this._delegate, orderByValue()));\n }\n\n startAt(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.startAt', 0, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, startAt(value, name))\n );\n }\n\n startAfter(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.startAfter', 0, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, startAfter(value, name))\n );\n }\n\n endAt(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.endAt', 0, 2, arguments.length);\n return new Query(this.database, query(this._delegate, endAt(value, name)));\n }\n\n endBefore(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.endBefore', 0, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, endBefore(value, name))\n );\n }\n\n /**\n * Load the selection of children with exactly the specified value, and, optionally,\n * the specified name.\n */\n equalTo(value: number | string | boolean | null, name?: string) {\n validateArgCount('Query.equalTo', 1, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, equalTo(value, name))\n );\n }\n\n /**\n * @returns URL for this location.\n */\n toString(): string {\n validateArgCount('Query.toString', 0, 0, arguments.length);\n return this._delegate.toString();\n }\n\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users.\n toJSON() {\n // An optional spacer argument is unnecessary for a string.\n validateArgCount('Query.toJSON', 0, 1, arguments.length);\n return this._delegate.toJSON();\n }\n\n /**\n * Return true if this query and the provided query are equivalent; otherwise, return false.\n */\n isEqual(other: Query): boolean {\n validateArgCount('Query.isEqual', 1, 1, arguments.length);\n if (!(other instanceof Query)) {\n const error =\n 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.';\n throw new Error(error);\n }\n return this._delegate.isEqual(other._delegate);\n }\n\n /**\n * Helper used by .on and .once to extract the context and or cancel arguments.\n * @param fnName - The function name (on or once)\n *\n */\n private static getCancelAndContextArgs_(\n fnName: string,\n cancelOrContext?: ((a: Error) => void) | object | null,\n context?: object | null\n ): { cancel: ((a: Error) => void) | undefined; context: object | undefined } {\n const ret: {\n cancel: ((a: Error) => void) | null;\n context: object | null;\n } = { cancel: undefined, context: undefined };\n if (cancelOrContext && context) {\n ret.cancel = cancelOrContext as (a: Error) => void;\n validateCallback(fnName, 'cancel', ret.cancel, true);\n\n ret.context = context;\n validateContextObject(fnName, 'context', ret.context, true);\n } else if (cancelOrContext) {\n // we have either a cancel callback or a context.\n if (typeof cancelOrContext === 'object' && cancelOrContext !== null) {\n // it's a context!\n ret.context = cancelOrContext;\n } else if (typeof cancelOrContext === 'function') {\n ret.cancel = cancelOrContext as (a: Error) => void;\n } else {\n throw new Error(\n errorPrefix(fnName, 'cancelOrContext') +\n ' must either be a cancel callback or a context object.'\n );\n }\n }\n return ret;\n }\n\n get ref(): Reference {\n return new Reference(\n this.database,\n new _ReferenceImpl(this._delegate._repo, this._delegate._path)\n );\n }\n}\n\nexport class Reference extends Query implements Compat {\n then: Promise['then'];\n catch: Promise['catch'];\n\n /**\n * Call options:\n * new Reference(Repo, Path) or\n * new Reference(url: string, string|RepoManager)\n *\n * Externally - this is the firebase.database.Reference type.\n */\n constructor(\n readonly database: Database,\n readonly _delegate: ModularReference\n ) {\n super(\n database,\n new _QueryImpl(\n _delegate._repo,\n _delegate._path,\n new _QueryParams(),\n false\n )\n );\n }\n\n /** @returns {?string} */\n getKey(): string | null {\n validateArgCount('Reference.key', 0, 0, arguments.length);\n return this._delegate.key;\n }\n\n child(pathString: string): Reference {\n validateArgCount('Reference.child', 1, 1, arguments.length);\n if (typeof pathString === 'number') {\n pathString = String(pathString);\n }\n return new Reference(this.database, child(this._delegate, pathString));\n }\n\n /** @returns {?Reference} */\n getParent(): Reference | null {\n validateArgCount('Reference.parent', 0, 0, arguments.length);\n const parent = this._delegate.parent;\n return parent ? new Reference(this.database, parent) : null;\n }\n\n /** @returns {!Reference} */\n getRoot(): Reference {\n validateArgCount('Reference.root', 0, 0, arguments.length);\n return new Reference(this.database, this._delegate.root);\n }\n\n set(\n newVal: unknown,\n onComplete?: (error: Error | null) => void\n ): Promise {\n validateArgCount('Reference.set', 1, 2, arguments.length);\n validateCallback('Reference.set', 'onComplete', onComplete, true);\n const result = set(this._delegate, newVal);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n update(\n values: object,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('Reference.update', 1, 2, arguments.length);\n\n if (Array.isArray(values)) {\n const newObjectToMerge: { [k: string]: unknown } = {};\n for (let i = 0; i < values.length; ++i) {\n newObjectToMerge['' + i] = values[i];\n }\n values = newObjectToMerge;\n warn(\n 'Passing an Array to Firebase.update() is deprecated. ' +\n 'Use set() if you want to overwrite the existing data, or ' +\n 'an Object with integer keys if you really do want to ' +\n 'only update some of the children.'\n );\n }\n _validateWritablePath('Reference.update', this._delegate._path);\n validateCallback('Reference.update', 'onComplete', onComplete, true);\n\n const result = update(this._delegate, values);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n setWithPriority(\n newVal: unknown,\n newPriority: string | number | null,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);\n validateCallback(\n 'Reference.setWithPriority',\n 'onComplete',\n onComplete,\n true\n );\n\n const result = setWithPriority(this._delegate, newVal, newPriority);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n remove(onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('Reference.remove', 0, 1, arguments.length);\n validateCallback('Reference.remove', 'onComplete', onComplete, true);\n\n const result = remove(this._delegate);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n transaction(\n transactionUpdate: (currentData: unknown) => unknown,\n onComplete?: (\n error: Error | null,\n committed: boolean,\n dataSnapshot: DataSnapshot | null\n ) => void,\n applyLocally?: boolean\n ): Promise {\n validateArgCount('Reference.transaction', 1, 3, arguments.length);\n validateCallback(\n 'Reference.transaction',\n 'transactionUpdate',\n transactionUpdate,\n false\n );\n validateCallback('Reference.transaction', 'onComplete', onComplete, true);\n validateBoolean(\n 'Reference.transaction',\n 'applyLocally',\n applyLocally,\n true\n );\n\n const result = runTransaction(this._delegate, transactionUpdate, {\n applyLocally\n }).then(\n transactionResult =>\n new TransactionResult(\n transactionResult.committed,\n new DataSnapshot(this.database, transactionResult.snapshot)\n )\n );\n if (onComplete) {\n result.then(\n transactionResult =>\n onComplete(\n null,\n transactionResult.committed,\n transactionResult.snapshot\n ),\n error => onComplete(error, false, null)\n );\n }\n return result;\n }\n\n setPriority(\n priority: string | number | null,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('Reference.setPriority', 1, 2, arguments.length);\n validateCallback('Reference.setPriority', 'onComplete', onComplete, true);\n\n const result = setPriority(this._delegate, priority);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n push(value?: unknown, onComplete?: (a: Error | null) => void): Reference {\n validateArgCount('Reference.push', 0, 2, arguments.length);\n validateCallback('Reference.push', 'onComplete', onComplete, true);\n\n const expPromise = push(this._delegate, value);\n const promise = expPromise.then(\n expRef => new Reference(this.database, expRef)\n );\n\n if (onComplete) {\n promise.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n\n const result = new Reference(this.database, expPromise);\n result.then = promise.then.bind(promise);\n result.catch = promise.catch.bind(promise, undefined);\n return result;\n }\n\n onDisconnect(): OnDisconnect {\n _validateWritablePath('Reference.onDisconnect', this._delegate._path);\n return new OnDisconnect(\n new ModularOnDisconnect(this._delegate._repo, this._delegate._path)\n );\n }\n\n get key(): string | null {\n return this.getKey();\n }\n\n get parent(): Reference | null {\n return this.getParent();\n }\n\n get root(): Reference {\n return this.getRoot();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\n\nimport { FirebaseApp } from '@firebase/app-types';\nimport { FirebaseService } from '@firebase/app-types/private';\nimport {\n forceLongPolling,\n forceWebSockets,\n goOnline,\n connectDatabaseEmulator,\n goOffline,\n ref,\n refFromURL,\n increment,\n serverTimestamp,\n Database as ModularDatabase\n} from '@firebase/database';\nimport {\n validateArgCount,\n Compat,\n EmulatorMockTokenOptions\n} from '@firebase/util';\n\nimport { Reference } from './Reference';\n\n/**\n * Class representing a firebase database.\n */\nexport class Database implements FirebaseService, Compat {\n static readonly ServerValue = {\n TIMESTAMP: serverTimestamp(),\n increment: (delta: number) => increment(delta)\n };\n\n /**\n * The constructor should not be called by users of our public API.\n */\n constructor(readonly _delegate: ModularDatabase, readonly app: FirebaseApp) {}\n\n INTERNAL = {\n delete: () => this._delegate._delete(),\n forceWebSockets,\n forceLongPolling\n };\n\n /**\n * Modify this instance to communicate with the Realtime Database emulator.\n *\n *

Note: This method must be called before performing any other operation.\n *\n * @param host - the emulator host (ex: localhost)\n * @param port - the emulator port (ex: 8080)\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\n */\n useEmulator(\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions;\n } = {}\n ): void {\n connectDatabaseEmulator(this._delegate, host, port, options);\n }\n\n /**\n * Returns a reference to the root or to the path specified in the provided\n * argument.\n *\n * @param path - The relative string path or an existing Reference to a database\n * location.\n * @throws If a Reference is provided, throws if it does not belong to the\n * same project.\n * @returns Firebase reference.\n */\n ref(path?: string): Reference;\n ref(path?: Reference): Reference;\n ref(path?: string | Reference): Reference {\n validateArgCount('database.ref', 0, 1, arguments.length);\n if (path instanceof Reference) {\n const childRef = refFromURL(this._delegate, path.toString());\n return new Reference(this, childRef);\n } else {\n const childRef = ref(this._delegate, path);\n return new Reference(this, childRef);\n }\n }\n\n /**\n * Returns a reference to the root or the path specified in url.\n * We throw a exception if the url is not in the same domain as the\n * current repo.\n * @returns Firebase reference.\n */\n refFromURL(url: string): Reference {\n const apiName = 'database.refFromURL';\n validateArgCount(apiName, 1, 1, arguments.length);\n const childRef = refFromURL(this._delegate, url);\n return new Reference(this, childRef);\n }\n\n // Make individual repo go offline.\n goOffline(): void {\n validateArgCount('database.goOffline', 0, 0, arguments.length);\n return goOffline(this._delegate);\n }\n\n goOnline(): void {\n validateArgCount('database.goOnline', 0, 0, arguments.length);\n return goOnline(this._delegate);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n AppCheckInternalComponentName,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport { FirebaseApp } from '@firebase/app-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n Provider\n} from '@firebase/component';\nimport {\n _repoManagerDatabaseFromApp,\n _setSDKVersion\n} from '@firebase/database';\nimport * as types from '@firebase/database-types';\n\nimport { Database } from './Database';\n\n/**\n * Used by console to create a database based on the app,\n * passed database URL and a custom auth implementation.\n *\n * @param app - A valid FirebaseApp-like object\n * @param url - A valid Firebase databaseURL\n * @param version - custom version e.g. firebase-admin version\n * @param customAuthImpl - custom auth implementation\n */\nexport function initStandalone({\n app,\n url,\n version,\n customAuthImpl,\n customAppCheckImpl,\n namespace,\n nodeAdmin = false\n}: {\n app: FirebaseApp;\n url: string;\n version: string;\n customAuthImpl: FirebaseAuthInternal;\n customAppCheckImpl?: FirebaseAppCheckInternal;\n namespace: T;\n nodeAdmin?: boolean;\n}): {\n instance: types.Database;\n namespace: T;\n} {\n _setSDKVersion(version);\n\n const container = new ComponentContainer('database-standalone');\n /**\n * ComponentContainer('database-standalone') is just a placeholder that doesn't perform\n * any actual function.\n */\n const authProvider = new Provider(\n 'auth-internal',\n container\n );\n authProvider.setComponent(\n new Component('auth-internal', () => customAuthImpl, ComponentType.PRIVATE)\n );\n\n let appCheckProvider: Provider = undefined;\n if (customAppCheckImpl) {\n appCheckProvider = new Provider(\n 'app-check-internal',\n container\n );\n appCheckProvider.setComponent(\n new Component(\n 'app-check-internal',\n () => customAppCheckImpl,\n ComponentType.PRIVATE\n )\n );\n }\n\n return {\n instance: new Database(\n _repoManagerDatabaseFromApp(\n app,\n authProvider,\n appCheckProvider,\n url,\n nodeAdmin\n ),\n app\n ) as types.Database,\n namespace\n };\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport firebase from '@firebase/app-compat';\nimport { FirebaseNamespace } from '@firebase/app-types';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport { Component, ComponentType } from '@firebase/component';\nimport { enableLogging } from '@firebase/database';\nimport * as types from '@firebase/database-types';\n\nimport { name, version } from '../package.json';\nimport { Database } from '../src/api/Database';\nimport * as INTERNAL from '../src/api/internal';\nimport { DataSnapshot, Query, Reference } from '../src/api/Reference';\n\nconst ServerValue = Database.ServerValue;\n\nfunction registerDatabase(instance: FirebaseNamespace) {\n // Register the Database Service with the 'firebase' namespace.\n (instance as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component(\n 'database-compat',\n (container, { instanceIdentifier: url }) => {\n /* Dependencies */\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app-compat').getImmediate();\n const databaseExp = container\n .getProvider('database')\n .getImmediate({ identifier: url });\n return new Database(databaseExp, app);\n },\n ComponentType.PUBLIC\n )\n .setServiceProps(\n // firebase.database namespace properties\n {\n Reference,\n Query,\n Database,\n DataSnapshot,\n enableLogging,\n INTERNAL,\n ServerValue\n }\n )\n .setMultipleInstances(true)\n );\n\n instance.registerVersion(name, version, 'node');\n}\n\nregisterDatabase(firebase);\n\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n database?: {\n (app?: FirebaseApp): types.FirebaseDatabase;\n enableLogging: typeof types.enableLogging;\n ServerValue: types.ServerValue;\n Database: typeof types.FirebaseDatabase;\n };\n }\n interface FirebaseApp {\n database?(): types.FirebaseDatabase;\n }\n}\n"],"names":["Logger","errorPrefixFxn","validateArgCount","validateCallback","_validatePathString","onValue","onChildAdded","onChildRemoved","onChildChanged","onChildMoved","errorPrefix","validateContextObject","off","get","Deferred","query","limitToFirst","limitToLast","orderByChild","orderByKey","orderByPriority","orderByValue","startAt","startAfter","endAt","endBefore","equalTo","_ReferenceImpl","database","_QueryImpl","_QueryParams","child","set","_validateWritablePath","update","setWithPriority","remove","runTransaction","setPriority","push","ModularOnDisconnect","forceWebSockets","forceLongPolling","connectDatabaseEmulator","refFromURL","ref","goOffline","goOnline","serverTimestamp","increment","_setSDKVersion","ComponentContainer","Provider","Component","_repoManagerDatabaseFromApp","enableLogging","firebase"],"mappings":";;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;AAeG;AAIH,MAAM,SAAS,GAAG,IAAIA,aAAM,CAAC,2BAA2B,CAAC,CAAC;AAEnD,MAAM,IAAI,GAAG,UAAU,GAAW,EAAA;AACvC,IAAA,MAAM,OAAO,GAAG,oBAAoB,GAAG,GAAG,CAAC;AAC3C,IAAA,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AAC1B,CAAC;;ACxBD;;;;;;;;;;;;;;;AAeG;AAII,MAAM,eAAe,GAAG,UAC7B,MAAc,EACd,YAAoB,EACpB,IAAa,EACb,QAAiB,EAAA;AAEjB,IAAA,IAAI,QAAQ,IAAI,IAAI,KAAK,SAAS,EAAE;QAClC,OAAO;KACR;AACD,IAAA,IAAI,OAAO,IAAI,KAAK,SAAS,EAAE;AAC7B,QAAA,MAAM,IAAI,KAAK,CACbC,gBAAc,CAAC,MAAM,EAAE,YAAY,CAAC,GAAG,oBAAoB,CAC5D,CAAC;KACH;AACH,CAAC,CAAC;AAEK,MAAM,iBAAiB,GAAG,UAC/B,MAAc,EACd,SAAiB,EACjB,QAAiB,EAAA;AAEjB,IAAA,IAAI,QAAQ,IAAI,SAAS,KAAK,SAAS,EAAE;QACvC,OAAO;KACR;IAED,QAAQ,SAAS;AACf,QAAA,KAAK,OAAO,CAAC;AACb,QAAA,KAAK,aAAa,CAAC;AACnB,QAAA,KAAK,eAAe,CAAC;AACrB,QAAA,KAAK,eAAe,CAAC;AACrB,QAAA,KAAK,aAAa;YAChB,MAAM;AACR,QAAA;YACE,MAAM,IAAI,KAAK,CACbA,gBAAc,CAAC,MAAM,EAAE,WAAW,CAAC;gBACjC,wEAAwE;AACxE,gBAAA,oCAAoC,CACvC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AAU,CAAC;AACvB,aAAA,YAAY,CAAC,EAAE,UAAU,EAAE,GAAG,EAAE,CAAC,CAAC;AACrC,QAAA,OAAO,IAAI,QAAQ,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC;AACxC,KAAC,EAEF,QAAA,4BAAA;SACE,eAAe;;AAEd,IAAA;QACE,SAAS;QACT,KAAK;QACL,QAAQ;QACR,YAAY;uBACZE,sBAAa;QACb,QAAQ;QACR,WAAW;KACZ,CACF;AACA,SAAA,oBAAoB,CAAC,IAAI,CAAC,CAC9B,CAAC;IAEF,QAAQ,CAAC,eAAe,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;AAClD,CAAC;AAED,gBAAgB,CAACC,4BAAQ,CAAC;;"} \ No newline at end of file diff --git a/node_modules/@firebase/database-compat/dist/index.standalone.js b/node_modules/@firebase/database-compat/dist/index.standalone.js new file mode 100644 index 0000000..606d4f2 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/index.standalone.js @@ -0,0 +1,19814 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var require$$2 = require('util'); +var require$$0 = require('buffer'); +var require$$1 = require('events'); +var require$$0$1 = require('stream'); +var require$$1$1 = require('crypto'); +var require$$2$1 = require('url'); +var require$$1$2 = require('net'); +var require$$2$2 = require('tls'); +var require$$2$3 = require('@firebase/util'); +var require$$1$3 = require('@firebase/logger'); +var require$$0$2 = require('@firebase/component'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2); +var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0); +var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1); +var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1); +var require$$1__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$1$1); +var require$$2__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$2$1); +var require$$1__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$1$2); +var require$$2__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$2$2); +var require$$2__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$2$3); +var require$$1__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$1$3); +var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$2); + +function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var a = Object.defineProperty({}, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; +} + +var index_standalone = {}; + +var safeBuffer = {exports: {}}; + +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ + +(function (module, exports) { +/* eslint-disable node/no-deprecated-api */ +var buffer = require$$0__default["default"]; +var Buffer = buffer.Buffer; + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key]; + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer; +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports); + exports.Buffer = SafeBuffer; +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype); + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer); + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +}; + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size); + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding); + } else { + buf.fill(fill); + } + } else { + buf.fill(0); + } + return buf +}; + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +}; + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +}; +}(safeBuffer, safeBuffer.exports)); + +var streams$1 = {}; + +/** + +Streams in a WebSocket connection +--------------------------------- + +We model a WebSocket as two duplex streams: one stream is for the wire protocol +over an I/O socket, and the other is for incoming/outgoing messages. + + + +----------+ +---------+ +----------+ + [1] write(chunk) -->| ~~~~~~~~ +----->| parse() +----->| ~~~~~~~~ +--> emit('data') [2] + | | +----+----+ | | + | | | | | + | IO | | [5] | Messages | + | | V | | + | | +---------+ | | + [4] emit('data') <--+ ~~~~~~~~ |<-----+ frame() |<-----+ ~~~~~~~~ |<-- write(chunk) [3] + +----------+ +---------+ +----------+ + + +Message transfer in each direction is simple: IO receives a byte stream [1] and +sends this stream for parsing. The parser will periodically emit a complete +message text on the Messages stream [2]. Similarly, when messages are written +to the Messages stream [3], they are framed using the WebSocket wire format and +emitted via IO [4]. + +There is a feedback loop via [5] since some input from [1] will be things like +ping, pong and close frames. In these cases the protocol responds by emitting +responses directly back to [4] rather than emitting messages via [2]. + +For the purposes of flow control, we consider the sources of each Readable +stream to be as follows: + +* [2] receives input from [1] +* [4] receives input from [1] and [3] + +The classes below express the relationships described above without prescribing +anything about how parse() and frame() work, other than assuming they emit +'data' events to the IO and Messages streams. They will work with any protocol +driver having these two methods. +**/ + + +var Stream$3 = require$$0__default$1["default"].Stream, + util$c = require$$2__default["default"]; + + +var IO = function(driver) { + this.readable = this.writable = true; + this._paused = false; + this._driver = driver; +}; +util$c.inherits(IO, Stream$3); + +// The IO pause() and resume() methods will be called when the socket we are +// piping to gets backed up and drains. Since IO output [4] comes from IO input +// [1] and Messages input [3], we need to tell both of those to return false +// from write() when this stream is paused. + +IO.prototype.pause = function() { + this._paused = true; + this._driver.messages._paused = true; +}; + +IO.prototype.resume = function() { + this._paused = false; + this.emit('drain'); + + var messages = this._driver.messages; + messages._paused = false; + messages.emit('drain'); +}; + +// When we receive input from a socket, send it to the parser and tell the +// source whether to back off. +IO.prototype.write = function(chunk) { + if (!this.writable) return false; + this._driver.parse(chunk); + return !this._paused; +}; + +// The IO end() method will be called when the socket piping into it emits +// 'close' or 'end', i.e. the socket is closed. In this situation the Messages +// stream will not emit any more data so we emit 'end'. +IO.prototype.end = function(chunk) { + if (!this.writable) return; + if (chunk !== undefined) this.write(chunk); + this.writable = false; + + var messages = this._driver.messages; + if (messages.readable) { + messages.readable = messages.writable = false; + messages.emit('end'); + } +}; + +IO.prototype.destroy = function() { + this.end(); +}; + + +var Messages = function(driver) { + this.readable = this.writable = true; + this._paused = false; + this._driver = driver; +}; +util$c.inherits(Messages, Stream$3); + +// The Messages pause() and resume() methods will be called when the app that's +// processing the messages gets backed up and drains. If we're emitting +// messages too fast we should tell the source to slow down. Message output [2] +// comes from IO input [1]. + +Messages.prototype.pause = function() { + this._driver.io._paused = true; +}; + +Messages.prototype.resume = function() { + this._driver.io._paused = false; + this._driver.io.emit('drain'); +}; + +// When we receive messages from the user, send them to the formatter and tell +// the source whether to back off. +Messages.prototype.write = function(message) { + if (!this.writable) return false; + if (typeof message === 'string') this._driver.text(message); + else this._driver.binary(message); + return !this._paused; +}; + +// The Messages end() method will be called when a stream piping into it emits +// 'end'. Many streams may be piped into the WebSocket and one of them ending +// does not mean the whole socket is done, so just process the input and move +// on leaving the socket open. +Messages.prototype.end = function(message) { + if (message !== undefined) this.write(message); +}; + +Messages.prototype.destroy = function() {}; + + +streams$1.IO = IO; +streams$1.Messages = Messages; + +var Headers$3 = function() { + this.clear(); +}; + +Headers$3.prototype.ALLOWED_DUPLICATES = ['set-cookie', 'set-cookie2', 'warning', 'www-authenticate']; + +Headers$3.prototype.clear = function() { + this._sent = {}; + this._lines = []; +}; + +Headers$3.prototype.set = function(name, value) { + if (value === undefined) return; + + name = this._strip(name); + value = this._strip(value); + + var key = name.toLowerCase(); + if (!this._sent.hasOwnProperty(key) || this.ALLOWED_DUPLICATES.indexOf(key) >= 0) { + this._sent[key] = true; + this._lines.push(name + ': ' + value + '\r\n'); + } +}; + +Headers$3.prototype.toString = function() { + return this._lines.join(''); +}; + +Headers$3.prototype._strip = function(string) { + return string.toString().replace(/^ */, '').replace(/ *$/, ''); +}; + +var headers = Headers$3; + +var Buffer$9 = safeBuffer.exports.Buffer; + +var StreamReader = function() { + this._queue = []; + this._queueSize = 0; + this._offset = 0; +}; + +StreamReader.prototype.put = function(buffer) { + if (!buffer || buffer.length === 0) return; + if (!Buffer$9.isBuffer(buffer)) buffer = Buffer$9.from(buffer); + this._queue.push(buffer); + this._queueSize += buffer.length; +}; + +StreamReader.prototype.read = function(length) { + if (length > this._queueSize) return null; + if (length === 0) return Buffer$9.alloc(0); + + this._queueSize -= length; + + var queue = this._queue, + remain = length, + first = queue[0], + buffers, buffer; + + if (first.length >= length) { + if (first.length === length) { + return queue.shift(); + } else { + buffer = first.slice(0, length); + queue[0] = first.slice(length); + return buffer; + } + } + + for (var i = 0, n = queue.length; i < n; i++) { + if (remain < queue[i].length) break; + remain -= queue[i].length; + } + buffers = queue.splice(0, i); + + if (remain > 0 && queue.length > 0) { + buffers.push(queue[0].slice(0, remain)); + queue[0] = queue[0].slice(remain); + } + return Buffer$9.concat(buffers, length); +}; + +StreamReader.prototype.eachByte = function(callback, context) { + var buffer, n, index; + + while (this._queue.length > 0) { + buffer = this._queue[0]; + n = buffer.length; + + while (this._offset < n) { + index = this._offset; + this._offset += 1; + callback.call(context, buffer[index]); + } + this._offset = 0; + this._queue.shift(); + } +}; + +var stream_reader = StreamReader; + +var Buffer$8 = safeBuffer.exports.Buffer, + Emitter = require$$1__default["default"].EventEmitter, + util$b = require$$2__default["default"], + streams = streams$1, + Headers$2 = headers, + Reader = stream_reader; + +var Base$7 = function(request, url, options) { + Emitter.call(this); + Base$7.validateOptions(options || {}, ['maxLength', 'masking', 'requireMasking', 'protocols']); + + this._request = request; + this._reader = new Reader(); + this._options = options || {}; + this._maxLength = this._options.maxLength || this.MAX_LENGTH; + this._headers = new Headers$2(); + this.__queue = []; + this.readyState = 0; + this.url = url; + + this.io = new streams.IO(this); + this.messages = new streams.Messages(this); + this._bindEventListeners(); +}; +util$b.inherits(Base$7, Emitter); + +Base$7.isWebSocket = function(request) { + var connection = request.headers.connection || '', + upgrade = request.headers.upgrade || ''; + + return request.method === 'GET' && + connection.toLowerCase().split(/ *, */).indexOf('upgrade') >= 0 && + upgrade.toLowerCase() === 'websocket'; +}; + +Base$7.validateOptions = function(options, validKeys) { + for (var key in options) { + if (validKeys.indexOf(key) < 0) + throw new Error('Unrecognized option: ' + key); + } +}; + +var instance$b = { + // This is 64MB, small enough for an average VPS to handle without + // crashing from process out of memory + MAX_LENGTH: 0x3ffffff, + + STATES: ['connecting', 'open', 'closing', 'closed'], + + _bindEventListeners: function() { + var self = this; + + // Protocol errors are informational and do not have to be handled + this.messages.on('error', function() {}); + + this.on('message', function(event) { + var messages = self.messages; + if (messages.readable) messages.emit('data', event.data); + }); + + this.on('error', function(error) { + var messages = self.messages; + if (messages.readable) messages.emit('error', error); + }); + + this.on('close', function() { + var messages = self.messages; + if (!messages.readable) return; + messages.readable = messages.writable = false; + messages.emit('end'); + }); + }, + + getState: function() { + return this.STATES[this.readyState] || null; + }, + + addExtension: function(extension) { + return false; + }, + + setHeader: function(name, value) { + if (this.readyState > 0) return false; + this._headers.set(name, value); + return true; + }, + + start: function() { + if (this.readyState !== 0) return false; + + if (!Base$7.isWebSocket(this._request)) + return this._failHandshake(new Error('Not a WebSocket request')); + + var response; + + try { + response = this._handshakeResponse(); + } catch (error) { + return this._failHandshake(error); + } + + this._write(response); + if (this._stage !== -1) this._open(); + return true; + }, + + _failHandshake: function(error) { + var headers = new Headers$2(); + headers.set('Content-Type', 'text/plain'); + headers.set('Content-Length', Buffer$8.byteLength(error.message, 'utf8')); + + headers = ['HTTP/1.1 400 Bad Request', headers.toString(), error.message]; + this._write(Buffer$8.from(headers.join('\r\n'), 'utf8')); + this._fail('protocol_error', error.message); + + return false; + }, + + text: function(message) { + return this.frame(message); + }, + + binary: function(message) { + return false; + }, + + ping: function() { + return false; + }, + + pong: function() { + return false; + }, + + close: function(reason, code) { + if (this.readyState !== 1) return false; + this.readyState = 3; + this.emit('close', new Base$7.CloseEvent(null, null)); + return true; + }, + + _open: function() { + this.readyState = 1; + this.__queue.forEach(function(args) { this.frame.apply(this, args); }, this); + this.__queue = []; + this.emit('open', new Base$7.OpenEvent()); + }, + + _queue: function(message) { + this.__queue.push(message); + return true; + }, + + _write: function(chunk) { + var io = this.io; + if (io.readable) io.emit('data', chunk); + }, + + _fail: function(type, message) { + this.readyState = 2; + this.emit('error', new Error(message)); + this.close(); + } +}; + +for (var key$b in instance$b) + Base$7.prototype[key$b] = instance$b[key$b]; + + +Base$7.ConnectEvent = function() {}; + +Base$7.OpenEvent = function() {}; + +Base$7.CloseEvent = function(code, reason) { + this.code = code; + this.reason = reason; +}; + +Base$7.MessageEvent = function(data) { + this.data = data; +}; + +Base$7.PingEvent = function(data) { + this.data = data; +}; + +Base$7.PongEvent = function(data) { + this.data = data; +}; + +var base = Base$7; + +var httpParser = {}; + +/*jshint node:true */ +httpParser.HTTPParser = HTTPParser; +function HTTPParser(type) { + if (type !== undefined && type !== HTTPParser.REQUEST && type !== HTTPParser.RESPONSE) { + throw new Error('type must be REQUEST or RESPONSE'); + } + if (type === undefined) ; else { + this.initialize(type); + } + this.maxHeaderSize=HTTPParser.maxHeaderSize; +} +HTTPParser.prototype.initialize = function (type, async_resource) { + if (type !== HTTPParser.REQUEST && type !== HTTPParser.RESPONSE) { + throw new Error('type must be REQUEST or RESPONSE'); + } + this.type = type; + this.state = type + '_LINE'; + this.info = { + headers: [], + upgrade: false + }; + this.trailers = []; + this.line = ''; + this.isChunked = false; + this.connection = ''; + this.headerSize = 0; // for preventing too big headers + this.body_bytes = null; + this.isUserCall = false; + this.hadError = false; +}; + +HTTPParser.encoding = 'ascii'; +HTTPParser.maxHeaderSize = 80 * 1024; // maxHeaderSize (in bytes) is configurable, but 80kb by default; +HTTPParser.REQUEST = 'REQUEST'; +HTTPParser.RESPONSE = 'RESPONSE'; + +// Note: *not* starting with kOnHeaders=0 line the Node parser, because any +// newly added constants (kOnTimeout in Node v12.19.0) will overwrite 0! +var kOnHeaders = HTTPParser.kOnHeaders = 1; +var kOnHeadersComplete = HTTPParser.kOnHeadersComplete = 2; +var kOnBody = HTTPParser.kOnBody = 3; +var kOnMessageComplete = HTTPParser.kOnMessageComplete = 4; + +// Some handler stubs, needed for compatibility +HTTPParser.prototype[kOnHeaders] = +HTTPParser.prototype[kOnHeadersComplete] = +HTTPParser.prototype[kOnBody] = +HTTPParser.prototype[kOnMessageComplete] = function () {}; + +var compatMode0_12 = true; +Object.defineProperty(HTTPParser, 'kOnExecute', { + get: function () { + // hack for backward compatibility + compatMode0_12 = false; + return 99; + } + }); + +var methods = httpParser.methods = HTTPParser.methods = [ + 'DELETE', + 'GET', + 'HEAD', + 'POST', + 'PUT', + 'CONNECT', + 'OPTIONS', + 'TRACE', + 'COPY', + 'LOCK', + 'MKCOL', + 'MOVE', + 'PROPFIND', + 'PROPPATCH', + 'SEARCH', + 'UNLOCK', + 'BIND', + 'REBIND', + 'UNBIND', + 'ACL', + 'REPORT', + 'MKACTIVITY', + 'CHECKOUT', + 'MERGE', + 'M-SEARCH', + 'NOTIFY', + 'SUBSCRIBE', + 'UNSUBSCRIBE', + 'PATCH', + 'PURGE', + 'MKCALENDAR', + 'LINK', + 'UNLINK', + 'SOURCE', +]; +var method_connect = methods.indexOf('CONNECT'); +HTTPParser.prototype.reinitialize = HTTPParser; +HTTPParser.prototype.close = +HTTPParser.prototype.pause = +HTTPParser.prototype.resume = +HTTPParser.prototype.remove = +HTTPParser.prototype.free = function () {}; +HTTPParser.prototype._compatMode0_11 = false; +HTTPParser.prototype.getAsyncId = function() { return 0; }; + +var headerState = { + REQUEST_LINE: true, + RESPONSE_LINE: true, + HEADER: true +}; +HTTPParser.prototype.execute = function (chunk, start, length) { + if (!(this instanceof HTTPParser)) { + throw new TypeError('not a HTTPParser'); + } + + // backward compat to node < 0.11.4 + // Note: the start and length params were removed in newer version + start = start || 0; + length = typeof length === 'number' ? length : chunk.length; + + this.chunk = chunk; + this.offset = start; + var end = this.end = start + length; + try { + while (this.offset < end) { + if (this[this.state]()) { + break; + } + } + } catch (err) { + if (this.isUserCall) { + throw err; + } + this.hadError = true; + return err; + } + this.chunk = null; + length = this.offset - start; + if (headerState[this.state]) { + this.headerSize += length; + if (this.headerSize > (this.maxHeaderSize||HTTPParser.maxHeaderSize)) { + return new Error('max header size exceeded'); + } + } + return length; +}; + +var stateFinishAllowed = { + REQUEST_LINE: true, + RESPONSE_LINE: true, + BODY_RAW: true +}; +HTTPParser.prototype.finish = function () { + if (this.hadError) { + return; + } + if (!stateFinishAllowed[this.state]) { + return new Error('invalid state for EOF'); + } + if (this.state === 'BODY_RAW') { + this.userCall()(this[kOnMessageComplete]()); + } +}; + +// These three methods are used for an internal speed optimization, and it also +// works if theses are noops. Basically consume() asks us to read the bytes +// ourselves, but if we don't do it we get them through execute(). +HTTPParser.prototype.consume = +HTTPParser.prototype.unconsume = +HTTPParser.prototype.getCurrentBuffer = function () {}; + +//For correct error handling - see HTTPParser#execute +//Usage: this.userCall()(userFunction('arg')); +HTTPParser.prototype.userCall = function () { + this.isUserCall = true; + var self = this; + return function (ret) { + self.isUserCall = false; + return ret; + }; +}; + +HTTPParser.prototype.nextRequest = function () { + this.userCall()(this[kOnMessageComplete]()); + this.reinitialize(this.type); +}; + +HTTPParser.prototype.consumeLine = function () { + var end = this.end, + chunk = this.chunk; + for (var i = this.offset; i < end; i++) { + if (chunk[i] === 0x0a) { // \n + var line = this.line + chunk.toString(HTTPParser.encoding, this.offset, i); + if (line.charAt(line.length - 1) === '\r') { + line = line.substr(0, line.length - 1); + } + this.line = ''; + this.offset = i + 1; + return line; + } + } + //line split over multiple chunks + this.line += chunk.toString(HTTPParser.encoding, this.offset, this.end); + this.offset = this.end; +}; + +var headerExp = /^([^: \t]+):[ \t]*((?:.*[^ \t])|)/; +var headerContinueExp = /^[ \t]+(.*[^ \t])/; +HTTPParser.prototype.parseHeader = function (line, headers) { + if (line.indexOf('\r') !== -1) { + throw parseErrorCode('HPE_LF_EXPECTED'); + } + + var match = headerExp.exec(line); + var k = match && match[1]; + if (k) { // skip empty string (malformed header) + headers.push(k); + headers.push(match[2]); + } else { + var matchContinue = headerContinueExp.exec(line); + if (matchContinue && headers.length) { + if (headers[headers.length - 1]) { + headers[headers.length - 1] += ' '; + } + headers[headers.length - 1] += matchContinue[1]; + } + } +}; + +var requestExp = /^([A-Z-]+) ([^ ]+) HTTP\/(\d)\.(\d)$/; +HTTPParser.prototype.REQUEST_LINE = function () { + var line = this.consumeLine(); + if (!line) { + return; + } + var match = requestExp.exec(line); + if (match === null) { + throw parseErrorCode('HPE_INVALID_CONSTANT'); + } + this.info.method = this._compatMode0_11 ? match[1] : methods.indexOf(match[1]); + if (this.info.method === -1) { + throw new Error('invalid request method'); + } + this.info.url = match[2]; + this.info.versionMajor = +match[3]; + this.info.versionMinor = +match[4]; + this.body_bytes = 0; + this.state = 'HEADER'; +}; + +var responseExp = /^HTTP\/(\d)\.(\d) (\d{3}) ?(.*)$/; +HTTPParser.prototype.RESPONSE_LINE = function () { + var line = this.consumeLine(); + if (!line) { + return; + } + var match = responseExp.exec(line); + if (match === null) { + throw parseErrorCode('HPE_INVALID_CONSTANT'); + } + this.info.versionMajor = +match[1]; + this.info.versionMinor = +match[2]; + var statusCode = this.info.statusCode = +match[3]; + this.info.statusMessage = match[4]; + // Implied zero length. + if ((statusCode / 100 | 0) === 1 || statusCode === 204 || statusCode === 304) { + this.body_bytes = 0; + } + this.state = 'HEADER'; +}; + +HTTPParser.prototype.shouldKeepAlive = function () { + if (this.info.versionMajor > 0 && this.info.versionMinor > 0) { + if (this.connection.indexOf('close') !== -1) { + return false; + } + } else if (this.connection.indexOf('keep-alive') === -1) { + return false; + } + if (this.body_bytes !== null || this.isChunked) { // || skipBody + return true; + } + return false; +}; + +HTTPParser.prototype.HEADER = function () { + var line = this.consumeLine(); + if (line === undefined) { + return; + } + var info = this.info; + if (line) { + this.parseHeader(line, info.headers); + } else { + var headers = info.headers; + var hasContentLength = false; + var currentContentLengthValue; + var hasUpgradeHeader = false; + for (var i = 0; i < headers.length; i += 2) { + switch (headers[i].toLowerCase()) { + case 'transfer-encoding': + this.isChunked = headers[i + 1].toLowerCase() === 'chunked'; + break; + case 'content-length': + currentContentLengthValue = +headers[i + 1]; + if (hasContentLength) { + // Fix duplicate Content-Length header with same values. + // Throw error only if values are different. + // Known issues: + // https://github.com/request/request/issues/2091#issuecomment-328715113 + // https://github.com/nodejs/node/issues/6517#issuecomment-216263771 + if (currentContentLengthValue !== this.body_bytes) { + throw parseErrorCode('HPE_UNEXPECTED_CONTENT_LENGTH'); + } + } else { + hasContentLength = true; + this.body_bytes = currentContentLengthValue; + } + break; + case 'connection': + this.connection += headers[i + 1].toLowerCase(); + break; + case 'upgrade': + hasUpgradeHeader = true; + break; + } + } + + // if both isChunked and hasContentLength, isChunked wins + // This is required so the body is parsed using the chunked method, and matches + // Chrome's behavior. We could, maybe, ignore them both (would get chunked + // encoding into the body), and/or disable shouldKeepAlive to be more + // resilient. + if (this.isChunked && hasContentLength) { + hasContentLength = false; + this.body_bytes = null; + } + + // Logic from https://github.com/nodejs/http-parser/blob/921d5585515a153fa00e411cf144280c59b41f90/http_parser.c#L1727-L1737 + // "For responses, "Upgrade: foo" and "Connection: upgrade" are + // mandatory only when it is a 101 Switching Protocols response, + // otherwise it is purely informational, to announce support. + if (hasUpgradeHeader && this.connection.indexOf('upgrade') != -1) { + info.upgrade = this.type === HTTPParser.REQUEST || info.statusCode === 101; + } else { + info.upgrade = info.method === method_connect; + } + + if (this.isChunked && info.upgrade) { + this.isChunked = false; + } + + info.shouldKeepAlive = this.shouldKeepAlive(); + //problem which also exists in original node: we should know skipBody before calling onHeadersComplete + var skipBody; + if (compatMode0_12) { + skipBody = this.userCall()(this[kOnHeadersComplete](info)); + } else { + skipBody = this.userCall()(this[kOnHeadersComplete](info.versionMajor, + info.versionMinor, info.headers, info.method, info.url, info.statusCode, + info.statusMessage, info.upgrade, info.shouldKeepAlive)); + } + if (skipBody === 2) { + this.nextRequest(); + return true; + } else if (this.isChunked && !skipBody) { + this.state = 'BODY_CHUNKHEAD'; + } else if (skipBody || this.body_bytes === 0) { + this.nextRequest(); + // For older versions of node (v6.x and older?), that return skipBody=1 or skipBody=true, + // need this "return true;" if it's an upgrade request. + return info.upgrade; + } else if (this.body_bytes === null) { + this.state = 'BODY_RAW'; + } else { + this.state = 'BODY_SIZED'; + } + } +}; + +HTTPParser.prototype.BODY_CHUNKHEAD = function () { + var line = this.consumeLine(); + if (line === undefined) { + return; + } + this.body_bytes = parseInt(line, 16); + if (!this.body_bytes) { + this.state = 'BODY_CHUNKTRAILERS'; + } else { + this.state = 'BODY_CHUNK'; + } +}; + +HTTPParser.prototype.BODY_CHUNK = function () { + var length = Math.min(this.end - this.offset, this.body_bytes); + // 0, length are for backwards compatibility. See: https://github.com/creationix/http-parser-js/pull/98 + this.userCall()(this[kOnBody](this.chunk.slice(this.offset, this.offset + length), 0, length)); + this.offset += length; + this.body_bytes -= length; + if (!this.body_bytes) { + this.state = 'BODY_CHUNKEMPTYLINE'; + } +}; + +HTTPParser.prototype.BODY_CHUNKEMPTYLINE = function () { + var line = this.consumeLine(); + if (line === undefined) { + return; + } + if (line !== '') { + throw new Error('Expected empty line'); + } + this.state = 'BODY_CHUNKHEAD'; +}; + +HTTPParser.prototype.BODY_CHUNKTRAILERS = function () { + var line = this.consumeLine(); + if (line === undefined) { + return; + } + if (line) { + this.parseHeader(line, this.trailers); + } else { + if (this.trailers.length) { + this.userCall()(this[kOnHeaders](this.trailers, '')); + } + this.nextRequest(); + } +}; + +HTTPParser.prototype.BODY_RAW = function () { + // 0, length are for backwards compatibility. See: https://github.com/creationix/http-parser-js/pull/98 + this.userCall()(this[kOnBody](this.chunk.slice(this.offset, this.end), 0, this.end - this.offset)); + this.offset = this.end; +}; + +HTTPParser.prototype.BODY_SIZED = function () { + var length = Math.min(this.end - this.offset, this.body_bytes); + // 0, length are for backwards compatibility. See: https://github.com/creationix/http-parser-js/pull/98 + this.userCall()(this[kOnBody](this.chunk.slice(this.offset, this.offset + length), 0, length)); + this.offset += length; + this.body_bytes -= length; + if (!this.body_bytes) { + this.nextRequest(); + } +}; + +// backward compat to node < 0.11.6 +['Headers', 'HeadersComplete', 'Body', 'MessageComplete'].forEach(function (name) { + var k = HTTPParser['kOn' + name]; + Object.defineProperty(HTTPParser.prototype, 'on' + name, { + get: function () { + return this[k]; + }, + set: function (to) { + // hack for backward compatibility + this._compatMode0_11 = true; + method_connect = 'CONNECT'; + return (this[k] = to); + } + }); +}); + +function parseErrorCode(code) { + var err = new Error('Parse Error'); + err.code = code; + return err; +} + +var NodeHTTPParser = httpParser.HTTPParser, + Buffer$7 = safeBuffer.exports.Buffer; + +var TYPES = { + request: NodeHTTPParser.REQUEST || 'request', + response: NodeHTTPParser.RESPONSE || 'response' +}; + +var HttpParser$3 = function(type) { + this._type = type; + this._parser = new NodeHTTPParser(TYPES[type]); + this._complete = false; + this.headers = {}; + + var current = null, + self = this; + + this._parser.onHeaderField = function(b, start, length) { + current = b.toString('utf8', start, start + length).toLowerCase(); + }; + + this._parser.onHeaderValue = function(b, start, length) { + var value = b.toString('utf8', start, start + length); + + if (self.headers.hasOwnProperty(current)) + self.headers[current] += ', ' + value; + else + self.headers[current] = value; + }; + + this._parser.onHeadersComplete = this._parser[NodeHTTPParser.kOnHeadersComplete] = + function(majorVersion, minorVersion, headers, method, pathname, statusCode) { + var info = arguments[0]; + + if (typeof info === 'object') { + method = info.method; + pathname = info.url; + statusCode = info.statusCode; + headers = info.headers; + } + + self.method = (typeof method === 'number') ? HttpParser$3.METHODS[method] : method; + self.statusCode = statusCode; + self.url = pathname; + + if (!headers) return; + + for (var i = 0, n = headers.length, key, value; i < n; i += 2) { + key = headers[i].toLowerCase(); + value = headers[i+1]; + if (self.headers.hasOwnProperty(key)) + self.headers[key] += ', ' + value; + else + self.headers[key] = value; + } + + self._complete = true; + }; +}; + +HttpParser$3.METHODS = { + 0: 'DELETE', + 1: 'GET', + 2: 'HEAD', + 3: 'POST', + 4: 'PUT', + 5: 'CONNECT', + 6: 'OPTIONS', + 7: 'TRACE', + 8: 'COPY', + 9: 'LOCK', + 10: 'MKCOL', + 11: 'MOVE', + 12: 'PROPFIND', + 13: 'PROPPATCH', + 14: 'SEARCH', + 15: 'UNLOCK', + 16: 'BIND', + 17: 'REBIND', + 18: 'UNBIND', + 19: 'ACL', + 20: 'REPORT', + 21: 'MKACTIVITY', + 22: 'CHECKOUT', + 23: 'MERGE', + 24: 'M-SEARCH', + 25: 'NOTIFY', + 26: 'SUBSCRIBE', + 27: 'UNSUBSCRIBE', + 28: 'PATCH', + 29: 'PURGE', + 30: 'MKCALENDAR', + 31: 'LINK', + 32: 'UNLINK' +}; + +var VERSION = process.version + ? process.version.match(/[0-9]+/g).map(function(n) { return parseInt(n, 10) }) + : []; + +if (VERSION[0] === 0 && VERSION[1] === 12) { + HttpParser$3.METHODS[16] = 'REPORT'; + HttpParser$3.METHODS[17] = 'MKACTIVITY'; + HttpParser$3.METHODS[18] = 'CHECKOUT'; + HttpParser$3.METHODS[19] = 'MERGE'; + HttpParser$3.METHODS[20] = 'M-SEARCH'; + HttpParser$3.METHODS[21] = 'NOTIFY'; + HttpParser$3.METHODS[22] = 'SUBSCRIBE'; + HttpParser$3.METHODS[23] = 'UNSUBSCRIBE'; + HttpParser$3.METHODS[24] = 'PATCH'; + HttpParser$3.METHODS[25] = 'PURGE'; +} + +HttpParser$3.prototype.isComplete = function() { + return this._complete; +}; + +HttpParser$3.prototype.parse = function(chunk) { + var consumed = this._parser.execute(chunk, 0, chunk.length); + + if (typeof consumed !== 'number') { + this.error = consumed; + this._complete = true; + return; + } + + if (this._complete) + this.body = (consumed < chunk.length) + ? chunk.slice(consumed) + : Buffer$7.alloc(0); +}; + +var http_parser = HttpParser$3; + +var TOKEN = /([!#\$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+)/, + NOTOKEN = /([^!#\$%&'\*\+\-\.\^_`\|~0-9A-Za-z])/g, + QUOTED = /"((?:\\[\x00-\x7f]|[^\x00-\x08\x0a-\x1f\x7f"\\])*)"/, + PARAM = new RegExp(TOKEN.source + '(?:=(?:' + TOKEN.source + '|' + QUOTED.source + '))?'), + EXT = new RegExp(TOKEN.source + '(?: *; *' + PARAM.source + ')*', 'g'), + EXT_LIST = new RegExp('^' + EXT.source + '(?: *, *' + EXT.source + ')*$'), + NUMBER = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?$/; + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +var Parser$1 = { + parseHeader: function(header) { + var offers = new Offers(); + if (header === '' || header === undefined) return offers; + + if (!EXT_LIST.test(header)) + throw new SyntaxError('Invalid Sec-WebSocket-Extensions header: ' + header); + + var values = header.match(EXT); + + values.forEach(function(value) { + var params = value.match(new RegExp(PARAM.source, 'g')), + name = params.shift(), + offer = {}; + + params.forEach(function(param) { + var args = param.match(PARAM), key = args[1], data; + + if (args[2] !== undefined) { + data = args[2]; + } else if (args[3] !== undefined) { + data = args[3].replace(/\\/g, ''); + } else { + data = true; + } + if (NUMBER.test(data)) data = parseFloat(data); + + if (hasOwnProperty.call(offer, key)) { + offer[key] = [].concat(offer[key]); + offer[key].push(data); + } else { + offer[key] = data; + } + }, this); + offers.push(name, offer); + }, this); + + return offers; + }, + + serializeParams: function(name, params) { + var values = []; + + var print = function(key, value) { + if (value instanceof Array) { + value.forEach(function(v) { print(key, v); }); + } else if (value === true) { + values.push(key); + } else if (typeof value === 'number') { + values.push(key + '=' + value); + } else if (NOTOKEN.test(value)) { + values.push(key + '="' + value.replace(/"/g, '\\"') + '"'); + } else { + values.push(key + '=' + value); + } + }; + + for (var key in params) print(key, params[key]); + + return [name].concat(values).join('; '); + } +}; + +var Offers = function() { + this._byName = {}; + this._inOrder = []; +}; + +Offers.prototype.push = function(name, params) { + if (!hasOwnProperty.call(this._byName, name)) + this._byName[name] = []; + + this._byName[name].push(params); + this._inOrder.push({ name: name, params: params }); +}; + +Offers.prototype.eachOffer = function(callback, context) { + var list = this._inOrder; + for (var i = 0, n = list.length; i < n; i++) + callback.call(context, list[i].name, list[i].params); +}; + +Offers.prototype.byName = function(name) { + return this._byName[name] || []; +}; + +Offers.prototype.toArray = function() { + return this._inOrder.slice(); +}; + +var parser = Parser$1; + +var RingBuffer$2 = function(bufferSize) { + this._bufferSize = bufferSize; + this.clear(); +}; + +RingBuffer$2.prototype.clear = function() { + this._buffer = new Array(this._bufferSize); + this._ringOffset = 0; + this._ringSize = this._bufferSize; + this._head = 0; + this._tail = 0; + this.length = 0; +}; + +RingBuffer$2.prototype.push = function(value) { + var expandBuffer = false, + expandRing = false; + + if (this._ringSize < this._bufferSize) { + expandBuffer = (this._tail === 0); + } else if (this._ringOffset === this._ringSize) { + expandBuffer = true; + expandRing = (this._tail === 0); + } + + if (expandBuffer) { + this._tail = this._bufferSize; + this._buffer = this._buffer.concat(new Array(this._bufferSize)); + this._bufferSize = this._buffer.length; + + if (expandRing) + this._ringSize = this._bufferSize; + } + + this._buffer[this._tail] = value; + this.length += 1; + if (this._tail < this._ringSize) this._ringOffset += 1; + this._tail = (this._tail + 1) % this._bufferSize; +}; + +RingBuffer$2.prototype.peek = function() { + if (this.length === 0) return void 0; + return this._buffer[this._head]; +}; + +RingBuffer$2.prototype.shift = function() { + if (this.length === 0) return void 0; + + var value = this._buffer[this._head]; + this._buffer[this._head] = void 0; + this.length -= 1; + this._ringOffset -= 1; + + if (this._ringOffset === 0 && this.length > 0) { + this._head = this._ringSize; + this._ringOffset = this.length; + this._ringSize = this._bufferSize; + } else { + this._head = (this._head + 1) % this._ringSize; + } + return value; +}; + +var ring_buffer = RingBuffer$2; + +var RingBuffer$1 = ring_buffer; + +var Functor$1 = function(session, method) { + this._session = session; + this._method = method; + this._queue = new RingBuffer$1(Functor$1.QUEUE_SIZE); + this._stopped = false; + this.pending = 0; +}; + +Functor$1.QUEUE_SIZE = 8; + +Functor$1.prototype.call = function(error, message, callback, context) { + if (this._stopped) return; + + var record = { error: error, message: message, callback: callback, context: context, done: false }, + called = false, + self = this; + + this._queue.push(record); + + if (record.error) { + record.done = true; + this._stop(); + return this._flushQueue(); + } + + var handler = function(err, msg) { + if (!(called ^ (called = true))) return; + + if (err) { + self._stop(); + record.error = err; + record.message = null; + } else { + record.message = msg; + } + + record.done = true; + self._flushQueue(); + }; + + try { + this._session[this._method](message, handler); + } catch (err) { + handler(err); + } +}; + +Functor$1.prototype._stop = function() { + this.pending = this._queue.length; + this._stopped = true; +}; + +Functor$1.prototype._flushQueue = function() { + var queue = this._queue, record; + + while (queue.length > 0 && queue.peek().done) { + record = queue.shift(); + if (record.error) { + this.pending = 0; + queue.clear(); + } else { + this.pending -= 1; + } + record.callback.call(record.context, record.error, record.message); + } +}; + +var functor = Functor$1; + +var RingBuffer = ring_buffer; + +var Pledge$2 = function() { + this._complete = false; + this._callbacks = new RingBuffer(Pledge$2.QUEUE_SIZE); +}; + +Pledge$2.QUEUE_SIZE = 4; + +Pledge$2.all = function(list) { + var pledge = new Pledge$2(), + pending = list.length, + n = pending; + + if (pending === 0) pledge.done(); + + while (n--) list[n].then(function() { + pending -= 1; + if (pending === 0) pledge.done(); + }); + return pledge; +}; + +Pledge$2.prototype.then = function(callback) { + if (this._complete) callback(); + else this._callbacks.push(callback); +}; + +Pledge$2.prototype.done = function() { + this._complete = true; + var callbacks = this._callbacks, callback; + while (callback = callbacks.shift()) callback(); +}; + +var pledge = Pledge$2; + +var Functor = functor, + Pledge$1 = pledge; + +var Cell$1 = function(tuple) { + this._ext = tuple[0]; + this._session = tuple[1]; + + this._functors = { + incoming: new Functor(this._session, 'processIncomingMessage'), + outgoing: new Functor(this._session, 'processOutgoingMessage') + }; +}; + +Cell$1.prototype.pending = function(direction) { + var functor = this._functors[direction]; + if (!functor._stopped) functor.pending += 1; +}; + +Cell$1.prototype.incoming = function(error, message, callback, context) { + this._exec('incoming', error, message, callback, context); +}; + +Cell$1.prototype.outgoing = function(error, message, callback, context) { + this._exec('outgoing', error, message, callback, context); +}; + +Cell$1.prototype.close = function() { + this._closed = this._closed || new Pledge$1(); + this._doClose(); + return this._closed; +}; + +Cell$1.prototype._exec = function(direction, error, message, callback, context) { + this._functors[direction].call(error, message, function(err, msg) { + if (err) err.message = this._ext.name + ': ' + err.message; + callback.call(context, err, msg); + this._doClose(); + }, this); +}; + +Cell$1.prototype._doClose = function() { + var fin = this._functors.incoming, + fout = this._functors.outgoing; + + if (!this._closed || fin.pending + fout.pending !== 0) return; + if (this._session) this._session.close(); + this._session = null; + this._closed.done(); +}; + +var cell = Cell$1; + +var Cell = cell, + Pledge = pledge; + +var Pipeline$1 = function(sessions) { + this._cells = sessions.map(function(session) { return new Cell(session) }); + this._stopped = { incoming: false, outgoing: false }; +}; + +Pipeline$1.prototype.processIncomingMessage = function(message, callback, context) { + if (this._stopped.incoming) return; + this._loop('incoming', this._cells.length - 1, -1, -1, message, callback, context); +}; + +Pipeline$1.prototype.processOutgoingMessage = function(message, callback, context) { + if (this._stopped.outgoing) return; + this._loop('outgoing', 0, this._cells.length, 1, message, callback, context); +}; + +Pipeline$1.prototype.close = function(callback, context) { + this._stopped = { incoming: true, outgoing: true }; + + var closed = this._cells.map(function(a) { return a.close() }); + if (callback) + Pledge.all(closed).then(function() { callback.call(context); }); +}; + +Pipeline$1.prototype._loop = function(direction, start, end, step, message, callback, context) { + var cells = this._cells, + n = cells.length, + self = this; + + while (n--) cells[n].pending(direction); + + var pipe = function(index, error, msg) { + if (index === end) return callback.call(context, error, msg); + + cells[index][direction](error, msg, function(err, m) { + if (err) self._stopped[direction] = true; + pipe(index + step, err, m); + }); + }; + pipe(start, null, message); +}; + +var pipeline = Pipeline$1; + +var Parser = parser, + Pipeline = pipeline; + +var Extensions$1 = function() { + this._rsv1 = this._rsv2 = this._rsv3 = null; + + this._byName = {}; + this._inOrder = []; + this._sessions = []; + this._index = {}; +}; + +Extensions$1.MESSAGE_OPCODES = [1, 2]; + +var instance$a = { + add: function(ext) { + if (typeof ext.name !== 'string') throw new TypeError('extension.name must be a string'); + if (ext.type !== 'permessage') throw new TypeError('extension.type must be "permessage"'); + + if (typeof ext.rsv1 !== 'boolean') throw new TypeError('extension.rsv1 must be true or false'); + if (typeof ext.rsv2 !== 'boolean') throw new TypeError('extension.rsv2 must be true or false'); + if (typeof ext.rsv3 !== 'boolean') throw new TypeError('extension.rsv3 must be true or false'); + + if (this._byName.hasOwnProperty(ext.name)) + throw new TypeError('An extension with name "' + ext.name + '" is already registered'); + + this._byName[ext.name] = ext; + this._inOrder.push(ext); + }, + + generateOffer: function() { + var sessions = [], + offer = [], + index = {}; + + this._inOrder.forEach(function(ext) { + var session = ext.createClientSession(); + if (!session) return; + + var record = [ext, session]; + sessions.push(record); + index[ext.name] = record; + + var offers = session.generateOffer(); + offers = offers ? [].concat(offers) : []; + + offers.forEach(function(off) { + offer.push(Parser.serializeParams(ext.name, off)); + }, this); + }, this); + + this._sessions = sessions; + this._index = index; + + return offer.length > 0 ? offer.join(', ') : null; + }, + + activate: function(header) { + var responses = Parser.parseHeader(header), + sessions = []; + + responses.eachOffer(function(name, params) { + var record = this._index[name]; + + if (!record) + throw new Error('Server sent an extension response for unknown extension "' + name + '"'); + + var ext = record[0], + session = record[1], + reserved = this._reserved(ext); + + if (reserved) + throw new Error('Server sent two extension responses that use the RSV' + + reserved[0] + ' bit: "' + + reserved[1] + '" and "' + ext.name + '"'); + + if (session.activate(params) !== true) + throw new Error('Server sent unacceptable extension parameters: ' + + Parser.serializeParams(name, params)); + + this._reserve(ext); + sessions.push(record); + }, this); + + this._sessions = sessions; + this._pipeline = new Pipeline(sessions); + }, + + generateResponse: function(header) { + var sessions = [], + response = [], + offers = Parser.parseHeader(header); + + this._inOrder.forEach(function(ext) { + var offer = offers.byName(ext.name); + if (offer.length === 0 || this._reserved(ext)) return; + + var session = ext.createServerSession(offer); + if (!session) return; + + this._reserve(ext); + sessions.push([ext, session]); + response.push(Parser.serializeParams(ext.name, session.generateResponse())); + }, this); + + this._sessions = sessions; + this._pipeline = new Pipeline(sessions); + + return response.length > 0 ? response.join(', ') : null; + }, + + validFrameRsv: function(frame) { + var allowed = { rsv1: false, rsv2: false, rsv3: false }, + ext; + + if (Extensions$1.MESSAGE_OPCODES.indexOf(frame.opcode) >= 0) { + for (var i = 0, n = this._sessions.length; i < n; i++) { + ext = this._sessions[i][0]; + allowed.rsv1 = allowed.rsv1 || ext.rsv1; + allowed.rsv2 = allowed.rsv2 || ext.rsv2; + allowed.rsv3 = allowed.rsv3 || ext.rsv3; + } + } + + return (allowed.rsv1 || !frame.rsv1) && + (allowed.rsv2 || !frame.rsv2) && + (allowed.rsv3 || !frame.rsv3); + }, + + processIncomingMessage: function(message, callback, context) { + this._pipeline.processIncomingMessage(message, callback, context); + }, + + processOutgoingMessage: function(message, callback, context) { + this._pipeline.processOutgoingMessage(message, callback, context); + }, + + close: function(callback, context) { + if (!this._pipeline) return callback.call(context); + this._pipeline.close(callback, context); + }, + + _reserve: function(ext) { + this._rsv1 = this._rsv1 || (ext.rsv1 && ext.name); + this._rsv2 = this._rsv2 || (ext.rsv2 && ext.name); + this._rsv3 = this._rsv3 || (ext.rsv3 && ext.name); + }, + + _reserved: function(ext) { + if (this._rsv1 && ext.rsv1) return [1, this._rsv1]; + if (this._rsv2 && ext.rsv2) return [2, this._rsv2]; + if (this._rsv3 && ext.rsv3) return [3, this._rsv3]; + return false; + } +}; + +for (var key$a in instance$a) + Extensions$1.prototype[key$a] = instance$a[key$a]; + +var websocket_extensions = Extensions$1; + +var Frame$1 = function() {}; + +var instance$9 = { + final: false, + rsv1: false, + rsv2: false, + rsv3: false, + opcode: null, + masked: false, + maskingKey: null, + lengthBytes: 1, + length: 0, + payload: null +}; + +for (var key$9 in instance$9) + Frame$1.prototype[key$9] = instance$9[key$9]; + +var frame = Frame$1; + +var Buffer$6 = safeBuffer.exports.Buffer; + +var Message$1 = function() { + this.rsv1 = false; + this.rsv2 = false; + this.rsv3 = false; + this.opcode = null; + this.length = 0; + this._chunks = []; +}; + +var instance$8 = { + read: function() { + return this.data = this.data || Buffer$6.concat(this._chunks, this.length); + }, + + pushFrame: function(frame) { + this.rsv1 = this.rsv1 || frame.rsv1; + this.rsv2 = this.rsv2 || frame.rsv2; + this.rsv3 = this.rsv3 || frame.rsv3; + + if (this.opcode === null) this.opcode = frame.opcode; + + this._chunks.push(frame.payload); + this.length += frame.length; + } +}; + +for (var key$8 in instance$8) + Message$1.prototype[key$8] = instance$8[key$8]; + +var message = Message$1; + +var Buffer$5 = safeBuffer.exports.Buffer, + crypto$2 = require$$1__default$1["default"], + util$a = require$$2__default["default"], + Extensions = websocket_extensions, + Base$6 = base, + Frame = frame, + Message = message; + +var Hybi$2 = function(request, url, options) { + Base$6.apply(this, arguments); + + this._extensions = new Extensions(); + this._stage = 0; + this._masking = this._options.masking; + this._protocols = this._options.protocols || []; + this._requireMasking = this._options.requireMasking; + this._pingCallbacks = {}; + + if (typeof this._protocols === 'string') + this._protocols = this._protocols.split(/ *, */); + + if (!this._request) return; + + var protos = this._request.headers['sec-websocket-protocol'], + supported = this._protocols; + + if (protos !== undefined) { + if (typeof protos === 'string') protos = protos.split(/ *, */); + this.protocol = protos.filter(function(p) { return supported.indexOf(p) >= 0 })[0]; + } + + this.version = 'hybi-' + Hybi$2.VERSION; +}; +util$a.inherits(Hybi$2, Base$6); + +Hybi$2.VERSION = '13'; + +Hybi$2.mask = function(payload, mask, offset) { + if (!mask || mask.length === 0) return payload; + offset = offset || 0; + + for (var i = 0, n = payload.length - offset; i < n; i++) { + payload[offset + i] = payload[offset + i] ^ mask[i % 4]; + } + return payload; +}; + +Hybi$2.generateAccept = function(key) { + var sha1 = crypto$2.createHash('sha1'); + sha1.update(key + Hybi$2.GUID); + return sha1.digest('base64'); +}; + +Hybi$2.GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; + +var instance$7 = { + FIN: 0x80, + MASK: 0x80, + RSV1: 0x40, + RSV2: 0x20, + RSV3: 0x10, + OPCODE: 0x0F, + LENGTH: 0x7F, + + OPCODES: { + continuation: 0, + text: 1, + binary: 2, + close: 8, + ping: 9, + pong: 10 + }, + + OPCODE_CODES: [0, 1, 2, 8, 9, 10], + MESSAGE_OPCODES: [0, 1, 2], + OPENING_OPCODES: [1, 2], + + ERRORS: { + normal_closure: 1000, + going_away: 1001, + protocol_error: 1002, + unacceptable: 1003, + encoding_error: 1007, + policy_violation: 1008, + too_large: 1009, + extension_error: 1010, + unexpected_condition: 1011 + }, + + ERROR_CODES: [1000, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011], + DEFAULT_ERROR_CODE: 1000, + MIN_RESERVED_ERROR: 3000, + MAX_RESERVED_ERROR: 4999, + + // http://www.w3.org/International/questions/qa-forms-utf-8.en.php + UTF8_MATCH: /^([\x00-\x7F]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2})*$/, + + addExtension: function(extension) { + this._extensions.add(extension); + return true; + }, + + parse: function(chunk) { + this._reader.put(chunk); + var buffer = true; + while (buffer) { + switch (this._stage) { + case 0: + buffer = this._reader.read(1); + if (buffer) this._parseOpcode(buffer[0]); + break; + + case 1: + buffer = this._reader.read(1); + if (buffer) this._parseLength(buffer[0]); + break; + + case 2: + buffer = this._reader.read(this._frame.lengthBytes); + if (buffer) this._parseExtendedLength(buffer); + break; + + case 3: + buffer = this._reader.read(4); + if (buffer) { + this._stage = 4; + this._frame.maskingKey = buffer; + } + break; + + case 4: + buffer = this._reader.read(this._frame.length); + if (buffer) { + this._stage = 0; + this._emitFrame(buffer); + } + break; + + default: + buffer = null; + } + } + }, + + text: function(message) { + if (this.readyState > 1) return false; + return this.frame(message, 'text'); + }, + + binary: function(message) { + if (this.readyState > 1) return false; + return this.frame(message, 'binary'); + }, + + ping: function(message, callback) { + if (this.readyState > 1) return false; + message = message || ''; + if (callback) this._pingCallbacks[message] = callback; + return this.frame(message, 'ping'); + }, + + pong: function(message) { + if (this.readyState > 1) return false; + message = message ||''; + return this.frame(message, 'pong'); + }, + + close: function(reason, code) { + reason = reason || ''; + code = code || this.ERRORS.normal_closure; + + if (this.readyState <= 0) { + this.readyState = 3; + this.emit('close', new Base$6.CloseEvent(code, reason)); + return true; + } else if (this.readyState === 1) { + this.readyState = 2; + this._extensions.close(function() { this.frame(reason, 'close', code); }, this); + return true; + } else { + return false; + } + }, + + frame: function(buffer, type, code) { + if (this.readyState <= 0) return this._queue([buffer, type, code]); + if (this.readyState > 2) return false; + + if (buffer instanceof Array) buffer = Buffer$5.from(buffer); + if (typeof buffer === 'number') buffer = buffer.toString(); + + var message = new Message(), + isText = (typeof buffer === 'string'), + payload, copy; + + message.rsv1 = message.rsv2 = message.rsv3 = false; + message.opcode = this.OPCODES[type || (isText ? 'text' : 'binary')]; + + payload = isText ? Buffer$5.from(buffer, 'utf8') : buffer; + + if (code) { + copy = payload; + payload = Buffer$5.allocUnsafe(2 + copy.length); + payload.writeUInt16BE(code, 0); + copy.copy(payload, 2); + } + message.data = payload; + + var onMessageReady = function(message) { + var frame = new Frame(); + + frame.final = true; + frame.rsv1 = message.rsv1; + frame.rsv2 = message.rsv2; + frame.rsv3 = message.rsv3; + frame.opcode = message.opcode; + frame.masked = !!this._masking; + frame.length = message.data.length; + frame.payload = message.data; + + if (frame.masked) frame.maskingKey = crypto$2.randomBytes(4); + + this._sendFrame(frame); + }; + + if (this.MESSAGE_OPCODES.indexOf(message.opcode) >= 0) + this._extensions.processOutgoingMessage(message, function(error, message) { + if (error) return this._fail('extension_error', error.message); + onMessageReady.call(this, message); + }, this); + else + onMessageReady.call(this, message); + + return true; + }, + + _sendFrame: function(frame) { + var length = frame.length, + header = (length <= 125) ? 2 : (length <= 65535 ? 4 : 10), + offset = header + (frame.masked ? 4 : 0), + buffer = Buffer$5.allocUnsafe(offset + length), + masked = frame.masked ? this.MASK : 0; + + buffer[0] = (frame.final ? this.FIN : 0) | + (frame.rsv1 ? this.RSV1 : 0) | + (frame.rsv2 ? this.RSV2 : 0) | + (frame.rsv3 ? this.RSV3 : 0) | + frame.opcode; + + if (length <= 125) { + buffer[1] = masked | length; + } else if (length <= 65535) { + buffer[1] = masked | 126; + buffer.writeUInt16BE(length, 2); + } else { + buffer[1] = masked | 127; + buffer.writeUInt32BE(Math.floor(length / 0x100000000), 2); + buffer.writeUInt32BE(length % 0x100000000, 6); + } + + frame.payload.copy(buffer, offset); + + if (frame.masked) { + frame.maskingKey.copy(buffer, header); + Hybi$2.mask(buffer, frame.maskingKey, offset); + } + + this._write(buffer); + }, + + _handshakeResponse: function() { + var secKey = this._request.headers['sec-websocket-key'], + version = this._request.headers['sec-websocket-version']; + + if (version !== Hybi$2.VERSION) + throw new Error('Unsupported WebSocket version: ' + version); + + if (typeof secKey !== 'string') + throw new Error('Missing handshake request header: Sec-WebSocket-Key'); + + this._headers.set('Upgrade', 'websocket'); + this._headers.set('Connection', 'Upgrade'); + this._headers.set('Sec-WebSocket-Accept', Hybi$2.generateAccept(secKey)); + + if (this.protocol) this._headers.set('Sec-WebSocket-Protocol', this.protocol); + + var extensions = this._extensions.generateResponse(this._request.headers['sec-websocket-extensions']); + if (extensions) this._headers.set('Sec-WebSocket-Extensions', extensions); + + var start = 'HTTP/1.1 101 Switching Protocols', + headers = [start, this._headers.toString(), '']; + + return Buffer$5.from(headers.join('\r\n'), 'utf8'); + }, + + _shutdown: function(code, reason, error) { + delete this._frame; + delete this._message; + this._stage = 5; + + var sendCloseFrame = (this.readyState === 1); + this.readyState = 2; + + this._extensions.close(function() { + if (sendCloseFrame) this.frame(reason, 'close', code); + this.readyState = 3; + if (error) this.emit('error', new Error(reason)); + this.emit('close', new Base$6.CloseEvent(code, reason)); + }, this); + }, + + _fail: function(type, message) { + if (this.readyState > 1) return; + this._shutdown(this.ERRORS[type], message, true); + }, + + _parseOpcode: function(octet) { + var rsvs = [this.RSV1, this.RSV2, this.RSV3].map(function(rsv) { + return (octet & rsv) === rsv; + }); + + var frame = this._frame = new Frame(); + + frame.final = (octet & this.FIN) === this.FIN; + frame.rsv1 = rsvs[0]; + frame.rsv2 = rsvs[1]; + frame.rsv3 = rsvs[2]; + frame.opcode = (octet & this.OPCODE); + + this._stage = 1; + + if (!this._extensions.validFrameRsv(frame)) + return this._fail('protocol_error', + 'One or more reserved bits are on: reserved1 = ' + (frame.rsv1 ? 1 : 0) + + ', reserved2 = ' + (frame.rsv2 ? 1 : 0) + + ', reserved3 = ' + (frame.rsv3 ? 1 : 0)); + + if (this.OPCODE_CODES.indexOf(frame.opcode) < 0) + return this._fail('protocol_error', 'Unrecognized frame opcode: ' + frame.opcode); + + if (this.MESSAGE_OPCODES.indexOf(frame.opcode) < 0 && !frame.final) + return this._fail('protocol_error', 'Received fragmented control frame: opcode = ' + frame.opcode); + + if (this._message && this.OPENING_OPCODES.indexOf(frame.opcode) >= 0) + return this._fail('protocol_error', 'Received new data frame but previous continuous frame is unfinished'); + }, + + _parseLength: function(octet) { + var frame = this._frame; + frame.masked = (octet & this.MASK) === this.MASK; + frame.length = (octet & this.LENGTH); + + if (frame.length >= 0 && frame.length <= 125) { + this._stage = frame.masked ? 3 : 4; + if (!this._checkFrameLength()) return; + } else { + this._stage = 2; + frame.lengthBytes = (frame.length === 126 ? 2 : 8); + } + + if (this._requireMasking && !frame.masked) + return this._fail('unacceptable', 'Received unmasked frame but masking is required'); + }, + + _parseExtendedLength: function(buffer) { + var frame = this._frame; + frame.length = this._readUInt(buffer); + + this._stage = frame.masked ? 3 : 4; + + if (this.MESSAGE_OPCODES.indexOf(frame.opcode) < 0 && frame.length > 125) + return this._fail('protocol_error', 'Received control frame having too long payload: ' + frame.length); + + if (!this._checkFrameLength()) return; + }, + + _checkFrameLength: function() { + var length = this._message ? this._message.length : 0; + + if (length + this._frame.length > this._maxLength) { + this._fail('too_large', 'WebSocket frame length too large'); + return false; + } else { + return true; + } + }, + + _emitFrame: function(buffer) { + var frame = this._frame, + payload = frame.payload = Hybi$2.mask(buffer, frame.maskingKey), + opcode = frame.opcode, + message, + code, reason, + callbacks, callback; + + delete this._frame; + + if (opcode === this.OPCODES.continuation) { + if (!this._message) return this._fail('protocol_error', 'Received unexpected continuation frame'); + this._message.pushFrame(frame); + } + + if (opcode === this.OPCODES.text || opcode === this.OPCODES.binary) { + this._message = new Message(); + this._message.pushFrame(frame); + } + + if (frame.final && this.MESSAGE_OPCODES.indexOf(opcode) >= 0) + return this._emitMessage(this._message); + + if (opcode === this.OPCODES.close) { + code = (payload.length >= 2) ? payload.readUInt16BE(0) : null; + reason = (payload.length > 2) ? this._encode(payload.slice(2)) : null; + + if (!(payload.length === 0) && + !(code !== null && code >= this.MIN_RESERVED_ERROR && code <= this.MAX_RESERVED_ERROR) && + this.ERROR_CODES.indexOf(code) < 0) + code = this.ERRORS.protocol_error; + + if (payload.length > 125 || (payload.length > 2 && !reason)) + code = this.ERRORS.protocol_error; + + this._shutdown(code || this.DEFAULT_ERROR_CODE, reason || ''); + } + + if (opcode === this.OPCODES.ping) { + this.frame(payload, 'pong'); + this.emit('ping', new Base$6.PingEvent(payload.toString())); + } + + if (opcode === this.OPCODES.pong) { + callbacks = this._pingCallbacks; + message = this._encode(payload); + callback = callbacks[message]; + + delete callbacks[message]; + if (callback) callback(); + + this.emit('pong', new Base$6.PongEvent(payload.toString())); + } + }, + + _emitMessage: function(message) { + var message = this._message; + message.read(); + + delete this._message; + + this._extensions.processIncomingMessage(message, function(error, message) { + if (error) return this._fail('extension_error', error.message); + + var payload = message.data; + if (message.opcode === this.OPCODES.text) payload = this._encode(payload); + + if (payload === null) + return this._fail('encoding_error', 'Could not decode a text frame as UTF-8'); + else + this.emit('message', new Base$6.MessageEvent(payload)); + }, this); + }, + + _encode: function(buffer) { + try { + var string = buffer.toString('binary', 0, buffer.length); + if (!this.UTF8_MATCH.test(string)) return null; + } catch (e) {} + return buffer.toString('utf8', 0, buffer.length); + }, + + _readUInt: function(buffer) { + if (buffer.length === 2) return buffer.readUInt16BE(0); + + return buffer.readUInt32BE(0) * 0x100000000 + + buffer.readUInt32BE(4); + } +}; + +for (var key$7 in instance$7) + Hybi$2.prototype[key$7] = instance$7[key$7]; + +var hybi = Hybi$2; + +var Buffer$4 = safeBuffer.exports.Buffer, + Stream$2 = require$$0__default$1["default"].Stream, + url$2 = require$$2__default$1["default"], + util$9 = require$$2__default["default"], + Base$5 = base, + Headers$1 = headers, + HttpParser$2 = http_parser; + +var PORTS = { 'ws:': 80, 'wss:': 443 }; + +var Proxy$2 = function(client, origin, options) { + this._client = client; + this._http = new HttpParser$2('response'); + this._origin = (typeof client.url === 'object') ? client.url : url$2.parse(client.url); + this._url = (typeof origin === 'object') ? origin : url$2.parse(origin); + this._options = options || {}; + this._state = 0; + + this.readable = this.writable = true; + this._paused = false; + + this._headers = new Headers$1(); + this._headers.set('Host', this._origin.host); + this._headers.set('Connection', 'keep-alive'); + this._headers.set('Proxy-Connection', 'keep-alive'); + + var auth = this._url.auth && Buffer$4.from(this._url.auth, 'utf8').toString('base64'); + if (auth) this._headers.set('Proxy-Authorization', 'Basic ' + auth); +}; +util$9.inherits(Proxy$2, Stream$2); + +var instance$6 = { + setHeader: function(name, value) { + if (this._state !== 0) return false; + this._headers.set(name, value); + return true; + }, + + start: function() { + if (this._state !== 0) return false; + this._state = 1; + + var origin = this._origin, + port = origin.port || PORTS[origin.protocol], + start = 'CONNECT ' + origin.hostname + ':' + port + ' HTTP/1.1'; + + var headers = [start, this._headers.toString(), '']; + + this.emit('data', Buffer$4.from(headers.join('\r\n'), 'utf8')); + return true; + }, + + pause: function() { + this._paused = true; + }, + + resume: function() { + this._paused = false; + this.emit('drain'); + }, + + write: function(chunk) { + if (!this.writable) return false; + + this._http.parse(chunk); + if (!this._http.isComplete()) return !this._paused; + + this.statusCode = this._http.statusCode; + this.headers = this._http.headers; + + if (this.statusCode === 200) { + this.emit('connect', new Base$5.ConnectEvent()); + } else { + var message = "Can't establish a connection to the server at " + this._origin.href; + this.emit('error', new Error(message)); + } + this.end(); + return !this._paused; + }, + + end: function(chunk) { + if (!this.writable) return; + if (chunk !== undefined) this.write(chunk); + this.readable = this.writable = false; + this.emit('close'); + this.emit('end'); + }, + + destroy: function() { + this.end(); + } +}; + +for (var key$6 in instance$6) + Proxy$2.prototype[key$6] = instance$6[key$6]; + +var proxy = Proxy$2; + +var Buffer$3 = safeBuffer.exports.Buffer, + crypto$1 = require$$1__default$1["default"], + url$1 = require$$2__default$1["default"], + util$8 = require$$2__default["default"], + HttpParser$1 = http_parser, + Base$4 = base, + Hybi$1 = hybi, + Proxy$1 = proxy; + +var Client$2 = function(_url, options) { + this.version = 'hybi-' + Hybi$1.VERSION; + Hybi$1.call(this, null, _url, options); + + this.readyState = -1; + this._key = Client$2.generateKey(); + this._accept = Hybi$1.generateAccept(this._key); + this._http = new HttpParser$1('response'); + + var uri = url$1.parse(this.url), + auth = uri.auth && Buffer$3.from(uri.auth, 'utf8').toString('base64'); + + if (this.VALID_PROTOCOLS.indexOf(uri.protocol) < 0) + throw new Error(this.url + ' is not a valid WebSocket URL'); + + this._pathname = (uri.pathname || '/') + (uri.search || ''); + + this._headers.set('Host', uri.host); + this._headers.set('Upgrade', 'websocket'); + this._headers.set('Connection', 'Upgrade'); + this._headers.set('Sec-WebSocket-Key', this._key); + this._headers.set('Sec-WebSocket-Version', Hybi$1.VERSION); + + if (this._protocols.length > 0) + this._headers.set('Sec-WebSocket-Protocol', this._protocols.join(', ')); + + if (auth) + this._headers.set('Authorization', 'Basic ' + auth); +}; +util$8.inherits(Client$2, Hybi$1); + +Client$2.generateKey = function() { + return crypto$1.randomBytes(16).toString('base64'); +}; + +var instance$5 = { + VALID_PROTOCOLS: ['ws:', 'wss:'], + + proxy: function(origin, options) { + return new Proxy$1(this, origin, options); + }, + + start: function() { + if (this.readyState !== -1) return false; + this._write(this._handshakeRequest()); + this.readyState = 0; + return true; + }, + + parse: function(chunk) { + if (this.readyState === 3) return; + if (this.readyState > 0) return Hybi$1.prototype.parse.call(this, chunk); + + this._http.parse(chunk); + if (!this._http.isComplete()) return; + + this._validateHandshake(); + if (this.readyState === 3) return; + + this._open(); + this.parse(this._http.body); + }, + + _handshakeRequest: function() { + var extensions = this._extensions.generateOffer(); + if (extensions) + this._headers.set('Sec-WebSocket-Extensions', extensions); + + var start = 'GET ' + this._pathname + ' HTTP/1.1', + headers = [start, this._headers.toString(), '']; + + return Buffer$3.from(headers.join('\r\n'), 'utf8'); + }, + + _failHandshake: function(message) { + message = 'Error during WebSocket handshake: ' + message; + this.readyState = 3; + this.emit('error', new Error(message)); + this.emit('close', new Base$4.CloseEvent(this.ERRORS.protocol_error, message)); + }, + + _validateHandshake: function() { + this.statusCode = this._http.statusCode; + this.headers = this._http.headers; + + if (this._http.error) + return this._failHandshake(this._http.error.message); + + if (this._http.statusCode !== 101) + return this._failHandshake('Unexpected response code: ' + this._http.statusCode); + + var headers = this._http.headers, + upgrade = headers['upgrade'] || '', + connection = headers['connection'] || '', + accept = headers['sec-websocket-accept'] || '', + protocol = headers['sec-websocket-protocol'] || ''; + + if (upgrade === '') + return this._failHandshake("'Upgrade' header is missing"); + if (upgrade.toLowerCase() !== 'websocket') + return this._failHandshake("'Upgrade' header value is not 'WebSocket'"); + + if (connection === '') + return this._failHandshake("'Connection' header is missing"); + if (connection.toLowerCase() !== 'upgrade') + return this._failHandshake("'Connection' header value is not 'Upgrade'"); + + if (accept !== this._accept) + return this._failHandshake('Sec-WebSocket-Accept mismatch'); + + this.protocol = null; + + if (protocol !== '') { + if (this._protocols.indexOf(protocol) < 0) + return this._failHandshake('Sec-WebSocket-Protocol mismatch'); + else + this.protocol = protocol; + } + + try { + this._extensions.activate(this.headers['sec-websocket-extensions']); + } catch (e) { + return this._failHandshake(e.message); + } + } +}; + +for (var key$5 in instance$5) + Client$2.prototype[key$5] = instance$5[key$5]; + +var client$1 = Client$2; + +var Buffer$2 = safeBuffer.exports.Buffer, + Base$3 = base, + util$7 = require$$2__default["default"]; + +var Draft75$2 = function(request, url, options) { + Base$3.apply(this, arguments); + this._stage = 0; + this.version = 'hixie-75'; + + this._headers.set('Upgrade', 'WebSocket'); + this._headers.set('Connection', 'Upgrade'); + this._headers.set('WebSocket-Origin', this._request.headers.origin); + this._headers.set('WebSocket-Location', this.url); +}; +util$7.inherits(Draft75$2, Base$3); + +var instance$4 = { + close: function() { + if (this.readyState === 3) return false; + this.readyState = 3; + this.emit('close', new Base$3.CloseEvent(null, null)); + return true; + }, + + parse: function(chunk) { + if (this.readyState > 1) return; + + this._reader.put(chunk); + + this._reader.eachByte(function(octet) { + var message; + + switch (this._stage) { + case -1: + this._body.push(octet); + this._sendHandshakeBody(); + break; + + case 0: + this._parseLeadingByte(octet); + break; + + case 1: + this._length = (octet & 0x7F) + 128 * this._length; + + if (this._closing && this._length === 0) { + return this.close(); + } + else if ((octet & 0x80) !== 0x80) { + if (this._length === 0) { + this._stage = 0; + } + else { + this._skipped = 0; + this._stage = 2; + } + } + break; + + case 2: + if (octet === 0xFF) { + this._stage = 0; + message = Buffer$2.from(this._buffer).toString('utf8', 0, this._buffer.length); + this.emit('message', new Base$3.MessageEvent(message)); + } + else { + if (this._length) { + this._skipped += 1; + if (this._skipped === this._length) + this._stage = 0; + } else { + this._buffer.push(octet); + if (this._buffer.length > this._maxLength) return this.close(); + } + } + break; + } + }, this); + }, + + frame: function(buffer) { + if (this.readyState === 0) return this._queue([buffer]); + if (this.readyState > 1) return false; + + if (typeof buffer !== 'string') buffer = buffer.toString(); + + var length = Buffer$2.byteLength(buffer), + frame = Buffer$2.allocUnsafe(length + 2); + + frame[0] = 0x00; + frame.write(buffer, 1); + frame[frame.length - 1] = 0xFF; + + this._write(frame); + return true; + }, + + _handshakeResponse: function() { + var start = 'HTTP/1.1 101 Web Socket Protocol Handshake', + headers = [start, this._headers.toString(), '']; + + return Buffer$2.from(headers.join('\r\n'), 'utf8'); + }, + + _parseLeadingByte: function(octet) { + if ((octet & 0x80) === 0x80) { + this._length = 0; + this._stage = 1; + } else { + delete this._length; + delete this._skipped; + this._buffer = []; + this._stage = 2; + } + } +}; + +for (var key$4 in instance$4) + Draft75$2.prototype[key$4] = instance$4[key$4]; + +var draft75 = Draft75$2; + +var Buffer$1 = safeBuffer.exports.Buffer, + Base$2 = base, + Draft75$1 = draft75, + crypto = require$$1__default$1["default"], + util$6 = require$$2__default["default"]; + + +var numberFromKey = function(key) { + return parseInt((key.match(/[0-9]/g) || []).join(''), 10); +}; + +var spacesInKey = function(key) { + return (key.match(/ /g) || []).length; +}; + + +var Draft76$1 = function(request, url, options) { + Draft75$1.apply(this, arguments); + this._stage = -1; + this._body = []; + this.version = 'hixie-76'; + + this._headers.clear(); + + this._headers.set('Upgrade', 'WebSocket'); + this._headers.set('Connection', 'Upgrade'); + this._headers.set('Sec-WebSocket-Origin', this._request.headers.origin); + this._headers.set('Sec-WebSocket-Location', this.url); +}; +util$6.inherits(Draft76$1, Draft75$1); + +var instance$3 = { + BODY_SIZE: 8, + + start: function() { + if (!Draft75$1.prototype.start.call(this)) return false; + this._started = true; + this._sendHandshakeBody(); + return true; + }, + + close: function() { + if (this.readyState === 3) return false; + if (this.readyState === 1) this._write(Buffer$1.from([0xFF, 0x00])); + this.readyState = 3; + this.emit('close', new Base$2.CloseEvent(null, null)); + return true; + }, + + _handshakeResponse: function() { + var headers = this._request.headers, + key1 = headers['sec-websocket-key1'], + key2 = headers['sec-websocket-key2']; + + if (!key1) throw new Error('Missing required header: Sec-WebSocket-Key1'); + if (!key2) throw new Error('Missing required header: Sec-WebSocket-Key2'); + + var number1 = numberFromKey(key1), + spaces1 = spacesInKey(key1), + + number2 = numberFromKey(key2), + spaces2 = spacesInKey(key2); + + if (number1 % spaces1 !== 0 || number2 % spaces2 !== 0) + throw new Error('Client sent invalid Sec-WebSocket-Key headers'); + + this._keyValues = [number1 / spaces1, number2 / spaces2]; + + var start = 'HTTP/1.1 101 WebSocket Protocol Handshake', + headers = [start, this._headers.toString(), '']; + + return Buffer$1.from(headers.join('\r\n'), 'binary'); + }, + + _handshakeSignature: function() { + if (this._body.length < this.BODY_SIZE) return null; + + var md5 = crypto.createHash('md5'), + buffer = Buffer$1.allocUnsafe(8 + this.BODY_SIZE); + + buffer.writeUInt32BE(this._keyValues[0], 0); + buffer.writeUInt32BE(this._keyValues[1], 4); + Buffer$1.from(this._body).copy(buffer, 8, 0, this.BODY_SIZE); + + md5.update(buffer); + return Buffer$1.from(md5.digest('binary'), 'binary'); + }, + + _sendHandshakeBody: function() { + if (!this._started) return; + var signature = this._handshakeSignature(); + if (!signature) return; + + this._write(signature); + this._stage = 0; + this._open(); + + if (this._body.length > this.BODY_SIZE) + this.parse(this._body.slice(this.BODY_SIZE)); + }, + + _parseLeadingByte: function(octet) { + if (octet !== 0xFF) + return Draft75$1.prototype._parseLeadingByte.call(this, octet); + + this._closing = true; + this._length = 0; + this._stage = 1; + } +}; + +for (var key$3 in instance$3) + Draft76$1.prototype[key$3] = instance$3[key$3]; + +var draft76 = Draft76$1; + +var util$5 = require$$2__default["default"], + HttpParser = http_parser, + Base$1 = base, + Draft75 = draft75, + Draft76 = draft76, + Hybi = hybi; + +var Server$1 = function(options) { + Base$1.call(this, null, null, options); + this._http = new HttpParser('request'); +}; +util$5.inherits(Server$1, Base$1); + +var instance$2 = { + EVENTS: ['open', 'message', 'error', 'close', 'ping', 'pong'], + + _bindEventListeners: function() { + this.messages.on('error', function() {}); + this.on('error', function() {}); + }, + + parse: function(chunk) { + if (this._delegate) return this._delegate.parse(chunk); + + this._http.parse(chunk); + if (!this._http.isComplete()) return; + + this.method = this._http.method; + this.url = this._http.url; + this.headers = this._http.headers; + this.body = this._http.body; + + var self = this; + this._delegate = Server$1.http(this, this._options); + this._delegate.messages = this.messages; + this._delegate.io = this.io; + this._open(); + + this.EVENTS.forEach(function(event) { + this._delegate.on(event, function(e) { self.emit(event, e); }); + }, this); + + this.protocol = this._delegate.protocol; + this.version = this._delegate.version; + + this.parse(this._http.body); + this.emit('connect', new Base$1.ConnectEvent()); + }, + + _open: function() { + this.__queue.forEach(function(msg) { + this._delegate[msg[0]].apply(this._delegate, msg[1]); + }, this); + this.__queue = []; + } +}; + +['addExtension', 'setHeader', 'start', 'frame', 'text', 'binary', 'ping', 'close'].forEach(function(method) { + instance$2[method] = function() { + if (this._delegate) { + return this._delegate[method].apply(this._delegate, arguments); + } else { + this.__queue.push([method, arguments]); + return true; + } + }; +}); + +for (var key$2 in instance$2) + Server$1.prototype[key$2] = instance$2[key$2]; + +Server$1.isSecureRequest = function(request) { + if (request.connection && request.connection.authorized !== undefined) return true; + if (request.socket && request.socket.secure) return true; + + var headers = request.headers; + if (!headers) return false; + if (headers['https'] === 'on') return true; + if (headers['x-forwarded-ssl'] === 'on') return true; + if (headers['x-forwarded-scheme'] === 'https') return true; + if (headers['x-forwarded-proto'] === 'https') return true; + + return false; +}; + +Server$1.determineUrl = function(request) { + var scheme = this.isSecureRequest(request) ? 'wss:' : 'ws:'; + return scheme + '//' + request.headers.host + request.url; +}; + +Server$1.http = function(request, options) { + options = options || {}; + if (options.requireMasking === undefined) options.requireMasking = true; + + var headers = request.headers, + version = headers['sec-websocket-version'], + key = headers['sec-websocket-key'], + key1 = headers['sec-websocket-key1'], + key2 = headers['sec-websocket-key2'], + url = this.determineUrl(request); + + if (version || key) + return new Hybi(request, url, options); + else if (key1 || key2) + return new Draft76(request, url, options); + else + return new Draft75(request, url, options); +}; + +var server = Server$1; + +// Protocol references: +// +// * http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75 +// * http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76 +// * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17 + +var Base = base, + Client$1 = client$1, + Server = server; + +var Driver = { + client: function(url, options) { + options = options || {}; + if (options.masking === undefined) options.masking = true; + return new Client$1(url, options); + }, + + server: function(options) { + options = options || {}; + if (options.requireMasking === undefined) options.requireMasking = true; + return new Server(options); + }, + + http: function() { + return Server.http.apply(Server, arguments); + }, + + isSecureRequest: function(request) { + return Server.isSecureRequest(request); + }, + + isWebSocket: function(request) { + return Base.isWebSocket(request); + }, + + validateOptions: function(options, validKeys) { + Base.validateOptions(options, validKeys); + } +}; + +var driver$4 = Driver; + +var Event$3 = function(eventType, options) { + this.type = eventType; + for (var key in options) + this[key] = options[key]; +}; + +Event$3.prototype.initEvent = function(eventType, canBubble, cancelable) { + this.type = eventType; + this.bubbles = canBubble; + this.cancelable = cancelable; +}; + +Event$3.prototype.stopPropagation = function() {}; +Event$3.prototype.preventDefault = function() {}; + +Event$3.CAPTURING_PHASE = 1; +Event$3.AT_TARGET = 2; +Event$3.BUBBLING_PHASE = 3; + +var event = Event$3; + +var Event$2 = event; + +var EventTarget$2 = { + onopen: null, + onmessage: null, + onerror: null, + onclose: null, + + addEventListener: function(eventType, listener, useCapture) { + this.on(eventType, listener); + }, + + removeEventListener: function(eventType, listener, useCapture) { + this.removeListener(eventType, listener); + }, + + dispatchEvent: function(event) { + event.target = event.currentTarget = this; + event.eventPhase = Event$2.AT_TARGET; + + if (this['on' + event.type]) + this['on' + event.type](event); + + this.emit(event.type, event); + } +}; + +var event_target = EventTarget$2; + +var Stream$1 = require$$0__default$1["default"].Stream, + util$4 = require$$2__default["default"], + driver$3 = driver$4, + EventTarget$1 = event_target, + Event$1 = event; + +var API$3 = function(options) { + options = options || {}; + driver$3.validateOptions(options, ['headers', 'extensions', 'maxLength', 'ping', 'proxy', 'tls', 'ca']); + + this.readable = this.writable = true; + + var headers = options.headers; + if (headers) { + for (var name in headers) this._driver.setHeader(name, headers[name]); + } + + var extensions = options.extensions; + if (extensions) { + [].concat(extensions).forEach(this._driver.addExtension, this._driver); + } + + this._ping = options.ping; + this._pingId = 0; + this.readyState = API$3.CONNECTING; + this.bufferedAmount = 0; + this.protocol = ''; + this.url = this._driver.url; + this.version = this._driver.version; + + var self = this; + + this._driver.on('open', function(e) { self._open(); }); + this._driver.on('message', function(e) { self._receiveMessage(e.data); }); + this._driver.on('close', function(e) { self._beginClose(e.reason, e.code); }); + + this._driver.on('error', function(error) { + self._emitError(error.message); + }); + this.on('error', function() {}); + + this._driver.messages.on('drain', function() { + self.emit('drain'); + }); + + if (this._ping) + this._pingTimer = setInterval(function() { + self._pingId += 1; + self.ping(self._pingId.toString()); + }, this._ping * 1000); + + this._configureStream(); + + if (!this._proxy) { + this._stream.pipe(this._driver.io); + this._driver.io.pipe(this._stream); + } +}; +util$4.inherits(API$3, Stream$1); + +API$3.CONNECTING = 0; +API$3.OPEN = 1; +API$3.CLOSING = 2; +API$3.CLOSED = 3; + +API$3.CLOSE_TIMEOUT = 30000; + +var instance$1 = { + write: function(data) { + return this.send(data); + }, + + end: function(data) { + if (data !== undefined) this.send(data); + this.close(); + }, + + pause: function() { + return this._driver.messages.pause(); + }, + + resume: function() { + return this._driver.messages.resume(); + }, + + send: function(data) { + if (this.readyState > API$3.OPEN) return false; + if (!(data instanceof Buffer)) data = String(data); + return this._driver.messages.write(data); + }, + + ping: function(message, callback) { + if (this.readyState > API$3.OPEN) return false; + return this._driver.ping(message, callback); + }, + + close: function(code, reason) { + if (code === undefined) code = 1000; + if (reason === undefined) reason = ''; + + if (code !== 1000 && (code < 3000 || code > 4999)) + throw new Error("Failed to execute 'close' on WebSocket: " + + "The code must be either 1000, or between 3000 and 4999. " + + code + " is neither."); + + if (this.readyState < API$3.CLOSING) { + var self = this; + this._closeTimer = setTimeout(function() { + self._beginClose('', 1006); + }, API$3.CLOSE_TIMEOUT); + } + + if (this.readyState !== API$3.CLOSED) this.readyState = API$3.CLOSING; + + this._driver.close(reason, code); + }, + + _configureStream: function() { + var self = this; + + this._stream.setTimeout(0); + this._stream.setNoDelay(true); + + ['close', 'end'].forEach(function(event) { + this._stream.on(event, function() { self._finalizeClose(); }); + }, this); + + this._stream.on('error', function(error) { + self._emitError('Network error: ' + self.url + ': ' + error.message); + self._finalizeClose(); + }); + }, + + _open: function() { + if (this.readyState !== API$3.CONNECTING) return; + + this.readyState = API$3.OPEN; + this.protocol = this._driver.protocol || ''; + + var event = new Event$1('open'); + event.initEvent('open', false, false); + this.dispatchEvent(event); + }, + + _receiveMessage: function(data) { + if (this.readyState > API$3.OPEN) return false; + + if (this.readable) this.emit('data', data); + + var event = new Event$1('message', { data: data }); + event.initEvent('message', false, false); + this.dispatchEvent(event); + }, + + _emitError: function(message) { + if (this.readyState >= API$3.CLOSING) return; + + var event = new Event$1('error', { message: message }); + event.initEvent('error', false, false); + this.dispatchEvent(event); + }, + + _beginClose: function(reason, code) { + if (this.readyState === API$3.CLOSED) return; + this.readyState = API$3.CLOSING; + this._closeParams = [reason, code]; + + if (this._stream) { + this._stream.destroy(); + if (!this._stream.readable) this._finalizeClose(); + } + }, + + _finalizeClose: function() { + if (this.readyState === API$3.CLOSED) return; + this.readyState = API$3.CLOSED; + + if (this._closeTimer) clearTimeout(this._closeTimer); + if (this._pingTimer) clearInterval(this._pingTimer); + if (this._stream) this._stream.end(); + + if (this.readable) this.emit('end'); + this.readable = this.writable = false; + + var reason = this._closeParams ? this._closeParams[0] : '', + code = this._closeParams ? this._closeParams[1] : 1006; + + var event = new Event$1('close', { code: code, reason: reason }); + event.initEvent('close', false, false); + this.dispatchEvent(event); + } +}; + +for (var method$1 in instance$1) API$3.prototype[method$1] = instance$1[method$1]; +for (var key$1 in EventTarget$1) API$3.prototype[key$1] = EventTarget$1[key$1]; + +var api = API$3; + +var util$3 = require$$2__default["default"], + net = require$$1__default$2["default"], + tls = require$$2__default$2["default"], + url = require$$2__default$1["default"], + driver$2 = driver$4, + API$2 = api; + +var DEFAULT_PORTS = { 'http:': 80, 'https:': 443, 'ws:':80, 'wss:': 443 }, + SECURE_PROTOCOLS = ['https:', 'wss:']; + +var Client = function(_url, protocols, options) { + options = options || {}; + + this.url = _url; + this._driver = driver$2.client(this.url, { maxLength: options.maxLength, protocols: protocols }); + + ['open', 'error'].forEach(function(event) { + this._driver.on(event, function() { + self.headers = self._driver.headers; + self.statusCode = self._driver.statusCode; + }); + }, this); + + var proxy = options.proxy || {}, + endpoint = url.parse(proxy.origin || this.url), + port = endpoint.port || DEFAULT_PORTS[endpoint.protocol], + secure = SECURE_PROTOCOLS.indexOf(endpoint.protocol) >= 0, + onConnect = function() { self._onConnect(); }, + netOptions = options.net || {}, + originTLS = options.tls || {}, + socketTLS = proxy.origin ? (proxy.tls || {}) : originTLS, + self = this; + + netOptions.host = socketTLS.host = endpoint.hostname; + netOptions.port = socketTLS.port = port; + + originTLS.ca = originTLS.ca || options.ca; + socketTLS.servername = socketTLS.servername || endpoint.hostname; + + this._stream = secure + ? tls.connect(socketTLS, onConnect) + : net.connect(netOptions, onConnect); + + if (proxy.origin) this._configureProxy(proxy, originTLS); + + API$2.call(this, options); +}; +util$3.inherits(Client, API$2); + +Client.prototype._onConnect = function() { + var worker = this._proxy || this._driver; + worker.start(); +}; + +Client.prototype._configureProxy = function(proxy, originTLS) { + var uri = url.parse(this.url), + secure = SECURE_PROTOCOLS.indexOf(uri.protocol) >= 0, + self = this, + name; + + this._proxy = this._driver.proxy(proxy.origin); + + if (proxy.headers) { + for (name in proxy.headers) this._proxy.setHeader(name, proxy.headers[name]); + } + + this._proxy.pipe(this._stream, { end: false }); + this._stream.pipe(this._proxy); + + this._proxy.on('connect', function() { + if (secure) { + var options = { socket: self._stream, servername: uri.hostname }; + for (name in originTLS) options[name] = originTLS[name]; + self._stream = tls.connect(options); + self._configureStream(); + } + self._driver.io.pipe(self._stream); + self._stream.pipe(self._driver.io); + self._driver.start(); + }); + + this._proxy.on('error', function(error) { + self._driver.emit('error', error); + }); +}; + +var client = Client; + +var Stream = require$$0__default$1["default"].Stream, + util$2 = require$$2__default["default"], + driver$1 = driver$4, + Headers = headers, + API$1 = api, + EventTarget = event_target, + Event = event; + +var EventSource = function(request, response, options) { + this.writable = true; + options = options || {}; + + this._stream = response.socket; + this._ping = options.ping || this.DEFAULT_PING; + this._retry = options.retry || this.DEFAULT_RETRY; + + var scheme = driver$1.isSecureRequest(request) ? 'https:' : 'http:'; + this.url = scheme + '//' + request.headers.host + request.url; + this.lastEventId = request.headers['last-event-id'] || ''; + this.readyState = API$1.CONNECTING; + + var headers = new Headers(), + self = this; + + if (options.headers) { + for (var key in options.headers) headers.set(key, options.headers[key]); + } + + if (!this._stream || !this._stream.writable) return; + process.nextTick(function() { self._open(); }); + + this._stream.setTimeout(0); + this._stream.setNoDelay(true); + + var handshake = 'HTTP/1.1 200 OK\r\n' + + 'Content-Type: text/event-stream\r\n' + + 'Cache-Control: no-cache, no-store\r\n' + + 'Connection: close\r\n' + + headers.toString() + + '\r\n' + + 'retry: ' + Math.floor(this._retry * 1000) + '\r\n\r\n'; + + this._write(handshake); + + this._stream.on('drain', function() { self.emit('drain'); }); + + if (this._ping) + this._pingTimer = setInterval(function() { self.ping(); }, this._ping * 1000); + + ['error', 'end'].forEach(function(event) { + self._stream.on(event, function() { self.close(); }); + }); +}; +util$2.inherits(EventSource, Stream); + +EventSource.isEventSource = function(request) { + if (request.method !== 'GET') return false; + var accept = (request.headers.accept || '').split(/\s*,\s*/); + return accept.indexOf('text/event-stream') >= 0; +}; + +var instance = { + DEFAULT_PING: 10, + DEFAULT_RETRY: 5, + + _write: function(chunk) { + if (!this.writable) return false; + try { + return this._stream.write(chunk, 'utf8'); + } catch (e) { + return false; + } + }, + + _open: function() { + if (this.readyState !== API$1.CONNECTING) return; + + this.readyState = API$1.OPEN; + + var event = new Event('open'); + event.initEvent('open', false, false); + this.dispatchEvent(event); + }, + + write: function(message) { + return this.send(message); + }, + + end: function(message) { + if (message !== undefined) this.write(message); + this.close(); + }, + + send: function(message, options) { + if (this.readyState > API$1.OPEN) return false; + + message = String(message).replace(/(\r\n|\r|\n)/g, '$1data: '); + options = options || {}; + + var frame = ''; + if (options.event) frame += 'event: ' + options.event + '\r\n'; + if (options.id) frame += 'id: ' + options.id + '\r\n'; + frame += 'data: ' + message + '\r\n\r\n'; + + return this._write(frame); + }, + + ping: function() { + return this._write(':\r\n\r\n'); + }, + + close: function() { + if (this.readyState > API$1.OPEN) return false; + + this.readyState = API$1.CLOSED; + this.writable = false; + if (this._pingTimer) clearInterval(this._pingTimer); + if (this._stream) this._stream.end(); + + var event = new Event('close'); + event.initEvent('close', false, false); + this.dispatchEvent(event); + + return true; + } +}; + +for (var method in instance) EventSource.prototype[method] = instance[method]; +for (var key in EventTarget) EventSource.prototype[key] = EventTarget[key]; + +var eventsource = EventSource; + +var util$1 = require$$2__default["default"], + driver = driver$4, + API = api; + +var WebSocket$1 = function(request, socket, body, protocols, options) { + options = options || {}; + + this._stream = socket; + this._driver = driver.http(request, { maxLength: options.maxLength, protocols: protocols }); + + var self = this; + if (!this._stream || !this._stream.writable) return; + if (!this._stream.readable) return this._stream.end(); + + var catchup = function() { self._stream.removeListener('data', catchup); }; + this._stream.on('data', catchup); + + API.call(this, options); + + process.nextTick(function() { + self._driver.start(); + self._driver.io.write(body); + }); +}; +util$1.inherits(WebSocket$1, API); + +WebSocket$1.isWebSocket = function(request) { + return driver.isWebSocket(request); +}; + +WebSocket$1.validateOptions = function(options, validKeys) { + driver.validateOptions(options, validKeys); +}; + +WebSocket$1.WebSocket = WebSocket$1; +WebSocket$1.Client = client; +WebSocket$1.EventSource = eventsource; + +var websocket = WebSocket$1; + +var index_cjs = {}; + +const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c); + +let idbProxyableTypes; +let cursorAdvanceMethods; +// This is a function to prevent it throwing up in node environments. +function getIdbProxyableTypes() { + return (idbProxyableTypes || + (idbProxyableTypes = [ + IDBDatabase, + IDBObjectStore, + IDBIndex, + IDBCursor, + IDBTransaction, + ])); +} +// This is a function to prevent it throwing up in node environments. +function getCursorAdvanceMethods() { + return (cursorAdvanceMethods || + (cursorAdvanceMethods = [ + IDBCursor.prototype.advance, + IDBCursor.prototype.continue, + IDBCursor.prototype.continuePrimaryKey, + ])); +} +const cursorRequestMap = new WeakMap(); +const transactionDoneMap = new WeakMap(); +const transactionStoreNamesMap = new WeakMap(); +const transformCache = new WeakMap(); +const reverseTransformCache = new WeakMap(); +function promisifyRequest(request) { + const promise = new Promise((resolve, reject) => { + const unlisten = () => { + request.removeEventListener('success', success); + request.removeEventListener('error', error); + }; + const success = () => { + resolve(wrap(request.result)); + unlisten(); + }; + const error = () => { + reject(request.error); + unlisten(); + }; + request.addEventListener('success', success); + request.addEventListener('error', error); + }); + promise + .then((value) => { + // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval + // (see wrapFunction). + if (value instanceof IDBCursor) { + cursorRequestMap.set(value, request); + } + // Catching to avoid "Uncaught Promise exceptions" + }) + .catch(() => { }); + // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This + // is because we create many promises from a single IDBRequest. + reverseTransformCache.set(promise, request); + return promise; +} +function cacheDonePromiseForTransaction(tx) { + // Early bail if we've already created a done promise for this transaction. + 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); + }); + // Cache it for later retrieval. + transactionDoneMap.set(tx, done); +} +let idbProxyTraps = { + get(target, prop, receiver) { + if (target instanceof IDBTransaction) { + // Special handling for transaction.done. + if (prop === 'done') + return transactionDoneMap.get(target); + // Polyfill for objectStoreNames because of Edge. + if (prop === 'objectStoreNames') { + return target.objectStoreNames || transactionStoreNamesMap.get(target); + } + // Make tx.store return the only store in the transaction, or undefined if there are many. + if (prop === 'store') { + return receiver.objectStoreNames[1] + ? undefined + : receiver.objectStore(receiver.objectStoreNames[0]); + } + } + // Else transform whatever we get back. + return wrap(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) { + // Due to expected object equality (which is enforced by the caching in `wrap`), we + // only create one new func per func. + // Edge doesn't support objectStoreNames (booo), so we polyfill it here. + if (func === IDBDatabase.prototype.transaction && + !('objectStoreNames' in IDBTransaction.prototype)) { + return function (storeNames, ...args) { + const tx = func.call(unwrap(this), storeNames, ...args); + transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]); + return wrap(tx); + }; + } + // Cursor methods are special, as the behaviour is a little more different to standard IDB. In + // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the + // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense + // with real promises, so each advance methods returns a new promise for the cursor object, or + // undefined if the end of the cursor has been reached. + if (getCursorAdvanceMethods().includes(func)) { + return function (...args) { + // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use + // the original object. + func.apply(unwrap(this), args); + return wrap(cursorRequestMap.get(this)); + }; + } + return function (...args) { + // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use + // the original object. + return wrap(func.apply(unwrap(this), args)); + }; +} +function transformCachableValue(value) { + if (typeof value === 'function') + return wrapFunction(value); + // This doesn't return, it just creates a 'done' promise for the transaction, + // which is later returned for transaction.done (see idbObjectHandler). + if (value instanceof IDBTransaction) + cacheDonePromiseForTransaction(value); + if (instanceOfAny(value, getIdbProxyableTypes())) + return new Proxy(value, idbProxyTraps); + // Return the same value back if we're not going to transform it. + return value; +} +function wrap(value) { + // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because + // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached. + if (value instanceof IDBRequest) + return promisifyRequest(value); + // If we've already transformed this value before, reuse the transformed value. + // This is faster, but it also provides object equality. + if (transformCache.has(value)) + return transformCache.get(value); + const newValue = transformCachableValue(value); + // Not all types are transformed. + // These may be primitive types, so they can't be WeakMap keys. + if (newValue !== value) { + transformCache.set(value, newValue); + reverseTransformCache.set(newValue, value); + } + return newValue; +} +const unwrap = (value) => reverseTransformCache.get(value); + +/** + * Open a database. + * + * @param name Name of the database. + * @param version Schema version. + * @param callbacks Additional callbacks. + */ +function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) { + const request = indexedDB.open(name, version); + const openPromise = wrap(request); + if (upgrade) { + request.addEventListener('upgradeneeded', (event) => { + upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(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; +} +/** + * Delete a database. + * + * @param name Name of the database. + */ +function deleteDB(name, { blocked } = {}) { + const request = indexedDB.deleteDatabase(name); + if (blocked) { + request.addEventListener('blocked', (event) => blocked( + // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405 + event.oldVersion, event)); + } + return wrap(request).then(() => undefined); +} + +const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count']; +const writeMethods = ['put', 'add', 'delete', 'clear']; +const cachedMethods = 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) { + // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :( + const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly'); + let target = tx.store; + if (useIndex) + target = target.index(args.shift()); + // Must reject if op rejects. + // If it's a write operation, must reject if tx.done rejects. + // Must reject with op rejection first. + // Must resolve with op value. + // Must handle both promises (no unhandled rejections) + return (await Promise.all([ + target[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 build = /*#__PURE__*/Object.freeze({ + __proto__: null, + deleteDB: deleteDB, + openDB: openDB, + unwrap: unwrap, + wrap: wrap +}); + +var require$$3 = /*@__PURE__*/getAugmentedNamespace(build); + +(function (exports) { + +Object.defineProperty(exports, '__esModule', { value: true }); + +var component = require$$0__default$2["default"]; +var logger$1 = require$$1__default$3["default"]; +var util = require$$2__default$3["default"]; +var idb = require$$3; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class PlatformLoggerServiceImpl { + constructor(container) { + this.container = container; + } + // In initial implementation, this will be called by installations on + // auth token refresh, and installations will send this string. + getPlatformInfoString() { + const providers = this.container.getProviders(); + // Loop through providers and get library/version pairs from any that are + // version components. + return providers + .map(provider => { + if (isVersionServiceProvider(provider)) { + const service = provider.getImmediate(); + return `${service.library}/${service.version}`; + } + else { + return null; + } + }) + .filter(logString => logString) + .join(' '); + } +} +/** + * + * @param provider check if this provider provides a VersionService + * + * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider + * provides VersionService. The provider is not necessarily a 'app-version' + * provider. + */ +function isVersionServiceProvider(provider) { + const component = provider.getComponent(); + return component?.type === "VERSION" /* ComponentType.VERSION */; +} + +const name$q = "@firebase/app"; +const version$1 = "0.14.0"; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const logger = new logger$1.Logger('@firebase/app'); + +const name$p = "@firebase/app-compat"; + +const name$o = "@firebase/analytics-compat"; + +const name$n = "@firebase/analytics"; + +const name$m = "@firebase/app-check-compat"; + +const name$l = "@firebase/app-check"; + +const name$k = "@firebase/auth"; + +const name$j = "@firebase/auth-compat"; + +const name$i = "@firebase/database"; + +const name$h = "@firebase/data-connect"; + +const name$g = "@firebase/database-compat"; + +const name$f = "@firebase/functions"; + +const name$e = "@firebase/functions-compat"; + +const name$d = "@firebase/installations"; + +const name$c = "@firebase/installations-compat"; + +const name$b = "@firebase/messaging"; + +const name$a = "@firebase/messaging-compat"; + +const name$9 = "@firebase/performance"; + +const name$8 = "@firebase/performance-compat"; + +const name$7 = "@firebase/remote-config"; + +const name$6 = "@firebase/remote-config-compat"; + +const name$5 = "@firebase/storage"; + +const name$4 = "@firebase/storage-compat"; + +const name$3 = "@firebase/firestore"; + +const name$2 = "@firebase/ai"; + +const name$1 = "@firebase/firestore-compat"; + +const name = "firebase"; +const version = "12.0.0"; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The default app name + * + * @internal + */ +const DEFAULT_ENTRY_NAME = '[DEFAULT]'; +const PLATFORM_LOG_STRING = { + [name$q]: 'fire-core', + [name$p]: 'fire-core-compat', + [name$n]: 'fire-analytics', + [name$o]: 'fire-analytics-compat', + [name$l]: 'fire-app-check', + [name$m]: 'fire-app-check-compat', + [name$k]: 'fire-auth', + [name$j]: 'fire-auth-compat', + [name$i]: 'fire-rtdb', + [name$h]: 'fire-data-connect', + [name$g]: 'fire-rtdb-compat', + [name$f]: 'fire-fn', + [name$e]: 'fire-fn-compat', + [name$d]: 'fire-iid', + [name$c]: 'fire-iid-compat', + [name$b]: 'fire-fcm', + [name$a]: 'fire-fcm-compat', + [name$9]: 'fire-perf', + [name$8]: 'fire-perf-compat', + [name$7]: 'fire-rc', + [name$6]: 'fire-rc-compat', + [name$5]: 'fire-gcs', + [name$4]: 'fire-gcs-compat', + [name$3]: 'fire-fst', + [name$1]: 'fire-fst-compat', + [name$2]: 'fire-vertex', + 'fire-js': 'fire-js', // Platform identifier for JS SDK. + [name]: 'fire-js-all' +}; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ +const _apps = new Map(); +/** + * @internal + */ +const _serverApps = new Map(); +/** + * Registered components. + * + * @internal + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const _components = new Map(); +/** + * @param component - the component being added to this app's container + * + * @internal + */ +function _addComponent(app, component) { + try { + app.container.addComponent(component); + } + catch (e) { + logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e); + } +} +/** + * + * @internal + */ +function _addOrOverwriteComponent(app, component) { + app.container.addOrOverwriteComponent(component); +} +/** + * + * @param component - the component to register + * @returns whether or not the component is registered successfully + * + * @internal + */ +function _registerComponent(component) { + const componentName = component.name; + if (_components.has(componentName)) { + logger.debug(`There were multiple attempts to register component ${componentName}.`); + return false; + } + _components.set(componentName, component); + // add the component to existing app instances + for (const app of _apps.values()) { + _addComponent(app, component); + } + for (const serverApp of _serverApps.values()) { + _addComponent(serverApp, component); + } + return true; +} +/** + * + * @param app - FirebaseApp instance + * @param name - service name + * + * @returns the provider for the service with the matching name + * + * @internal + */ +function _getProvider(app, name) { + const heartbeatController = app.container + .getProvider('heartbeat') + .getImmediate({ optional: true }); + if (heartbeatController) { + void heartbeatController.triggerHeartbeat(); + } + return app.container.getProvider(name); +} +/** + * + * @param app - FirebaseApp instance + * @param name - service name + * @param instanceIdentifier - service instance identifier in case the service supports multiple instances + * + * @internal + */ +function _removeServiceInstance(app, name, instanceIdentifier = DEFAULT_ENTRY_NAME) { + _getProvider(app, name).clearInstance(instanceIdentifier); +} +/** + * + * @param obj - an object of type FirebaseApp, FirebaseOptions or FirebaseAppSettings. + * + * @returns true if the provide object is of type FirebaseApp. + * + * @internal + */ +function _isFirebaseApp(obj) { + return obj.options !== undefined; +} +/** + * + * @param obj - an object of type FirebaseApp, FirebaseOptions or FirebaseAppSettings. + * + * @returns true if the provided object is of type FirebaseServerAppImpl. + * + * @internal + */ +function _isFirebaseServerAppSettings(obj) { + if (_isFirebaseApp(obj)) { + return false; + } + return ('authIdToken' in obj || + 'appCheckToken' in obj || + 'releaseOnDeref' in obj || + 'automaticDataCollectionEnabled' in obj); +} +/** + * + * @param obj - an object of type FirebaseApp. + * + * @returns true if the provided object is of type FirebaseServerAppImpl. + * + * @internal + */ +function _isFirebaseServerApp(obj) { + if (obj === null || obj === undefined) { + return false; + } + return obj.settings !== undefined; +} +/** + * Test only + * + * @internal + */ +function _clearComponents() { + _components.clear(); +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const ERRORS = { + ["no-app" /* AppError.NO_APP */]: "No Firebase App '{$appName}' has been created - " + + 'call initializeApp() first', + ["bad-app-name" /* AppError.BAD_APP_NAME */]: "Illegal App name: '{$appName}'", + ["duplicate-app" /* AppError.DUPLICATE_APP */]: "Firebase App named '{$appName}' already exists with different options or config", + ["app-deleted" /* AppError.APP_DELETED */]: "Firebase App named '{$appName}' already deleted", + ["server-app-deleted" /* AppError.SERVER_APP_DELETED */]: 'Firebase Server App has been deleted', + ["no-options" /* AppError.NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.', + ["invalid-app-argument" /* AppError.INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' + + 'Firebase App instance.', + ["invalid-log-argument" /* AppError.INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.', + ["idb-open" /* AppError.IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.', + ["idb-get" /* AppError.IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.', + ["idb-set" /* AppError.IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.', + ["idb-delete" /* AppError.IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.', + ["finalization-registry-not-supported" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */]: 'FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.', + ["invalid-server-app-environment" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */]: 'FirebaseServerApp is not for use in browser environments.' +}; +const ERROR_FACTORY = new util.ErrorFactory('app', 'Firebase', ERRORS); + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class FirebaseAppImpl { + constructor(options, config, container) { + this._isDeleted = false; + this._options = { ...options }; + this._config = { ...config }; + this._name = config.name; + this._automaticDataCollectionEnabled = + config.automaticDataCollectionEnabled; + this._container = container; + this.container.addComponent(new component.Component('app', () => this, "PUBLIC" /* ComponentType.PUBLIC */)); + } + get automaticDataCollectionEnabled() { + this.checkDestroyed(); + return this._automaticDataCollectionEnabled; + } + set automaticDataCollectionEnabled(val) { + this.checkDestroyed(); + this._automaticDataCollectionEnabled = val; + } + get name() { + this.checkDestroyed(); + return this._name; + } + get options() { + this.checkDestroyed(); + return this._options; + } + get config() { + this.checkDestroyed(); + return this._config; + } + get container() { + return this._container; + } + get isDeleted() { + return this._isDeleted; + } + set isDeleted(val) { + this._isDeleted = val; + } + /** + * This function will throw an Error if the App has already been deleted - + * use before performing API actions on the App. + */ + checkDestroyed() { + if (this.isDeleted) { + throw ERROR_FACTORY.create("app-deleted" /* AppError.APP_DELETED */, { appName: this._name }); + } + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Parse the token and check to see if the `exp` claim is in the future. +// Reports an error to the console if the token or claim could not be parsed, or if `exp` is in +// the past. +function validateTokenTTL(base64Token, tokenName) { + const secondPart = util.base64Decode(base64Token.split('.')[1]); + if (secondPart === null) { + console.error(`FirebaseServerApp ${tokenName} is invalid: second part could not be parsed.`); + return; + } + const expClaim = JSON.parse(secondPart).exp; + if (expClaim === undefined) { + console.error(`FirebaseServerApp ${tokenName} is invalid: expiration claim could not be parsed`); + return; + } + const exp = JSON.parse(secondPart).exp * 1000; + const now = new Date().getTime(); + const diff = exp - now; + if (diff <= 0) { + console.error(`FirebaseServerApp ${tokenName} is invalid: the token has expired.`); + } +} +class FirebaseServerAppImpl extends FirebaseAppImpl { + constructor(options, serverConfig, name, container) { + // Build configuration parameters for the FirebaseAppImpl base class. + const automaticDataCollectionEnabled = serverConfig.automaticDataCollectionEnabled !== undefined + ? serverConfig.automaticDataCollectionEnabled + : true; + // Create the FirebaseAppSettings object for the FirebaseAppImp constructor. + const config = { + name, + automaticDataCollectionEnabled + }; + if (options.apiKey !== undefined) { + // Construct the parent FirebaseAppImp object. + super(options, config, container); + } + else { + const appImpl = options; + super(appImpl.options, config, container); + } + // Now construct the data for the FirebaseServerAppImpl. + this._serverConfig = { + automaticDataCollectionEnabled, + ...serverConfig + }; + // Ensure that the current time is within the `authIdtoken` window of validity. + if (this._serverConfig.authIdToken) { + validateTokenTTL(this._serverConfig.authIdToken, 'authIdToken'); + } + // Ensure that the current time is within the `appCheckToken` window of validity. + if (this._serverConfig.appCheckToken) { + validateTokenTTL(this._serverConfig.appCheckToken, 'appCheckToken'); + } + this._finalizationRegistry = null; + if (typeof FinalizationRegistry !== 'undefined') { + this._finalizationRegistry = new FinalizationRegistry(() => { + this.automaticCleanup(); + }); + } + this._refCount = 0; + this.incRefCount(this._serverConfig.releaseOnDeref); + // Do not retain a hard reference to the dref object, otherwise the FinalizationRegistry + // will never trigger. + this._serverConfig.releaseOnDeref = undefined; + serverConfig.releaseOnDeref = undefined; + registerVersion(name$q, version$1, 'serverapp'); + } + toJSON() { + return undefined; + } + get refCount() { + return this._refCount; + } + // Increment the reference count of this server app. If an object is provided, register it + // with the finalization registry. + incRefCount(obj) { + if (this.isDeleted) { + return; + } + this._refCount++; + if (obj !== undefined && this._finalizationRegistry !== null) { + this._finalizationRegistry.register(obj, this); + } + } + // Decrement the reference count. + decRefCount() { + if (this.isDeleted) { + return 0; + } + return --this._refCount; + } + // Invoked by the FinalizationRegistry callback to note that this app should go through its + // reference counts and delete itself if no reference count remain. The coordinating logic that + // handles this is in deleteApp(...). + automaticCleanup() { + void deleteApp(this); + } + get settings() { + this.checkDestroyed(); + return this._serverConfig; + } + /** + * This function will throw an Error if the App has already been deleted - + * use before performing API actions on the App. + */ + checkDestroyed() { + if (this.isDeleted) { + throw ERROR_FACTORY.create("server-app-deleted" /* AppError.SERVER_APP_DELETED */); + } + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The current SDK version. + * + * @public + */ +const SDK_VERSION = version; +function initializeApp(_options, rawConfig = {}) { + let options = _options; + if (typeof rawConfig !== 'object') { + const name = rawConfig; + rawConfig = { name }; + } + const config = { + name: DEFAULT_ENTRY_NAME, + automaticDataCollectionEnabled: true, + ...rawConfig + }; + const name = config.name; + if (typeof name !== 'string' || !name) { + throw ERROR_FACTORY.create("bad-app-name" /* AppError.BAD_APP_NAME */, { + appName: String(name) + }); + } + options || (options = util.getDefaultAppConfig()); + if (!options) { + throw ERROR_FACTORY.create("no-options" /* AppError.NO_OPTIONS */); + } + const existingApp = _apps.get(name); + if (existingApp) { + // return the existing app if options and config deep equal the ones in the existing app. + if (util.deepEqual(options, existingApp.options) && + util.deepEqual(config, existingApp.config)) { + return existingApp; + } + else { + throw ERROR_FACTORY.create("duplicate-app" /* AppError.DUPLICATE_APP */, { appName: name }); + } + } + const container = new component.ComponentContainer(name); + for (const component of _components.values()) { + container.addComponent(component); + } + const newApp = new FirebaseAppImpl(options, config, container); + _apps.set(name, newApp); + return newApp; +} +function initializeServerApp(_options, _serverAppConfig = {}) { + if (util.isBrowser() && !util.isWebWorker()) { + // FirebaseServerApp isn't designed to be run in browsers. + throw ERROR_FACTORY.create("invalid-server-app-environment" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */); + } + let firebaseOptions; + let serverAppSettings = _serverAppConfig || {}; + if (_options) { + if (_isFirebaseApp(_options)) { + firebaseOptions = _options.options; + } + else if (_isFirebaseServerAppSettings(_options)) { + serverAppSettings = _options; + } + else { + firebaseOptions = _options; + } + } + if (serverAppSettings.automaticDataCollectionEnabled === undefined) { + serverAppSettings.automaticDataCollectionEnabled = true; + } + firebaseOptions || (firebaseOptions = util.getDefaultAppConfig()); + if (!firebaseOptions) { + throw ERROR_FACTORY.create("no-options" /* AppError.NO_OPTIONS */); + } + // Build an app name based on a hash of the configuration options. + const nameObj = { + ...serverAppSettings, + ...firebaseOptions + }; + // However, Do not mangle the name based on releaseOnDeref, since it will vary between the + // construction of FirebaseServerApp instances. For example, if the object is the request headers. + if (nameObj.releaseOnDeref !== undefined) { + delete nameObj.releaseOnDeref; + } + const hashCode = (s) => { + return [...s].reduce((hash, c) => (Math.imul(31, hash) + c.charCodeAt(0)) | 0, 0); + }; + if (serverAppSettings.releaseOnDeref !== undefined) { + if (typeof FinalizationRegistry === 'undefined') { + throw ERROR_FACTORY.create("finalization-registry-not-supported" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */, {}); + } + } + const nameString = '' + hashCode(JSON.stringify(nameObj)); + const existingApp = _serverApps.get(nameString); + if (existingApp) { + existingApp.incRefCount(serverAppSettings.releaseOnDeref); + return existingApp; + } + const container = new component.ComponentContainer(nameString); + for (const component of _components.values()) { + container.addComponent(component); + } + const newApp = new FirebaseServerAppImpl(firebaseOptions, serverAppSettings, nameString, container); + _serverApps.set(nameString, newApp); + return newApp; +} +/** + * Retrieves a {@link @firebase/app#FirebaseApp} instance. + * + * When called with no arguments, the default app is returned. When an app name + * is provided, the app corresponding to that name is returned. + * + * An exception is thrown if the app being retrieved has not yet been + * initialized. + * + * @example + * ```javascript + * // Return the default app + * const app = getApp(); + * ``` + * + * @example + * ```javascript + * // Return a named app + * const otherApp = getApp("otherApp"); + * ``` + * + * @param name - Optional name of the app to return. If no name is + * provided, the default is `"[DEFAULT]"`. + * + * @returns The app corresponding to the provided app name. + * If no app name is provided, the default app is returned. + * + * @public + */ +function getApp(name = DEFAULT_ENTRY_NAME) { + const app = _apps.get(name); + if (!app && name === DEFAULT_ENTRY_NAME && util.getDefaultAppConfig()) { + return initializeApp(); + } + if (!app) { + throw ERROR_FACTORY.create("no-app" /* AppError.NO_APP */, { appName: name }); + } + return app; +} +/** + * A (read-only) array of all initialized apps. + * @public + */ +function getApps() { + return Array.from(_apps.values()); +} +/** + * Renders this app unusable and frees the resources of all associated + * services. + * + * @example + * ```javascript + * deleteApp(app) + * .then(function() { + * console.log("App deleted successfully"); + * }) + * .catch(function(error) { + * console.log("Error deleting app:", error); + * }); + * ``` + * + * @public + */ +async function deleteApp(app) { + let cleanupProviders = false; + const name = app.name; + if (_apps.has(name)) { + cleanupProviders = true; + _apps.delete(name); + } + else if (_serverApps.has(name)) { + const firebaseServerApp = app; + if (firebaseServerApp.decRefCount() <= 0) { + _serverApps.delete(name); + cleanupProviders = true; + } + } + if (cleanupProviders) { + await Promise.all(app.container + .getProviders() + .map(provider => provider.delete())); + app.isDeleted = true; + } +} +/** + * Registers a library's name and version for platform logging purposes. + * @param library - Name of 1p or 3p library (e.g. firestore, angularfire) + * @param version - Current version of that library. + * @param variant - Bundle variant, e.g., node, rn, etc. + * + * @public + */ +function registerVersion(libraryKeyOrName, version, variant) { + // TODO: We can use this check to whitelist strings when/if we set up + // a good whitelist system. + let library = PLATFORM_LOG_STRING[libraryKeyOrName] ?? libraryKeyOrName; + if (variant) { + library += `-${variant}`; + } + const libraryMismatch = library.match(/\s|\//); + const versionMismatch = version.match(/\s|\//); + if (libraryMismatch || versionMismatch) { + const warning = [ + `Unable to register library "${library}" with version "${version}":` + ]; + if (libraryMismatch) { + warning.push(`library name "${library}" contains illegal characters (whitespace or "/")`); + } + if (libraryMismatch && versionMismatch) { + warning.push('and'); + } + if (versionMismatch) { + warning.push(`version name "${version}" contains illegal characters (whitespace or "/")`); + } + logger.warn(warning.join(' ')); + return; + } + _registerComponent(new component.Component(`${library}-version`, () => ({ library, version }), "VERSION" /* ComponentType.VERSION */)); +} +/** + * Sets log handler for all Firebase SDKs. + * @param logCallback - An optional custom log handler that executes user code whenever + * the Firebase SDK makes a logging call. + * + * @public + */ +function onLog(logCallback, options) { + if (logCallback !== null && typeof logCallback !== 'function') { + throw ERROR_FACTORY.create("invalid-log-argument" /* AppError.INVALID_LOG_ARGUMENT */); + } + logger$1.setUserLogHandler(logCallback, options); +} +/** + * Sets log level for all Firebase SDKs. + * + * All of the log types above the current log level are captured (i.e. if + * you set the log level to `info`, errors are logged, but `debug` and + * `verbose` logs are not). + * + * @public + */ +function setLogLevel(logLevel) { + logger$1.setLogLevel(logLevel); +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DB_NAME = 'firebase-heartbeat-database'; +const DB_VERSION = 1; +const STORE_NAME = 'firebase-heartbeat-store'; +let dbPromise = null; +function getDbPromise() { + if (!dbPromise) { + dbPromise = idb.openDB(DB_NAME, DB_VERSION, { + upgrade: (db, oldVersion) => { + // We don't use 'break' in this switch statement, the fall-through + // behavior is what we want, because if there are multiple versions between + // the old version and the current version, we want ALL the migrations + // that correspond to those versions to run, not only the last one. + // eslint-disable-next-line default-case + switch (oldVersion) { + case 0: + try { + db.createObjectStore(STORE_NAME); + } + catch (e) { + // Safari/iOS browsers throw occasional exceptions on + // db.createObjectStore() that may be a bug. Avoid blocking + // the rest of the app functionality. + console.warn(e); + } + } + } + }).catch(e => { + throw ERROR_FACTORY.create("idb-open" /* AppError.IDB_OPEN */, { + originalErrorMessage: e.message + }); + }); + } + return dbPromise; +} +async function readHeartbeatsFromIndexedDB(app) { + try { + const db = await getDbPromise(); + const tx = db.transaction(STORE_NAME); + const result = await tx.objectStore(STORE_NAME).get(computeKey(app)); + // We already have the value but tx.done can throw, + // so we need to await it here to catch errors + await tx.done; + return result; + } + catch (e) { + if (e instanceof util.FirebaseError) { + logger.warn(e.message); + } + else { + const idbGetError = ERROR_FACTORY.create("idb-get" /* AppError.IDB_GET */, { + originalErrorMessage: e?.message + }); + logger.warn(idbGetError.message); + } + } +} +async function writeHeartbeatsToIndexedDB(app, heartbeatObject) { + try { + const db = await getDbPromise(); + const tx = db.transaction(STORE_NAME, 'readwrite'); + const objectStore = tx.objectStore(STORE_NAME); + await objectStore.put(heartbeatObject, computeKey(app)); + await tx.done; + } + catch (e) { + if (e instanceof util.FirebaseError) { + logger.warn(e.message); + } + else { + const idbGetError = ERROR_FACTORY.create("idb-set" /* AppError.IDB_WRITE */, { + originalErrorMessage: e?.message + }); + logger.warn(idbGetError.message); + } + } +} +function computeKey(app) { + return `${app.name}!${app.options.appId}`; +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const MAX_HEADER_BYTES = 1024; +const MAX_NUM_STORED_HEARTBEATS = 30; +class HeartbeatServiceImpl { + constructor(container) { + this.container = container; + /** + * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate + * the header string. + * Stores one record per date. This will be consolidated into the standard + * format of one record per user agent string before being sent as a header. + * Populated from indexedDB when the controller is instantiated and should + * be kept in sync with indexedDB. + * Leave public for easier testing. + */ + this._heartbeatsCache = null; + const app = this.container.getProvider('app').getImmediate(); + this._storage = new HeartbeatStorageImpl(app); + this._heartbeatsCachePromise = this._storage.read().then(result => { + this._heartbeatsCache = result; + return result; + }); + } + /** + * Called to report a heartbeat. The function will generate + * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it + * to IndexedDB. + * Note that we only store one heartbeat per day. So if a heartbeat for today is + * already logged, subsequent calls to this function in the same day will be ignored. + */ + async triggerHeartbeat() { + try { + const platformLogger = this.container + .getProvider('platform-logger') + .getImmediate(); + // This is the "Firebase user agent" string from the platform logger + // service, not the browser user agent. + const agent = platformLogger.getPlatformInfoString(); + const date = getUTCDateString(); + if (this._heartbeatsCache?.heartbeats == null) { + this._heartbeatsCache = await this._heartbeatsCachePromise; + // If we failed to construct a heartbeats cache, then return immediately. + if (this._heartbeatsCache?.heartbeats == null) { + return; + } + } + // Do not store a heartbeat if one is already stored for this day + // or if a header has already been sent today. + if (this._heartbeatsCache.lastSentHeartbeatDate === date || + this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) { + return; + } + else { + // There is no entry for this date. Create one. + this._heartbeatsCache.heartbeats.push({ date, agent }); + // If the number of stored heartbeats exceeds the maximum number of stored heartbeats, remove the heartbeat with the earliest date. + // Since this is executed each time a heartbeat is pushed, the limit can only be exceeded by one, so only one needs to be removed. + if (this._heartbeatsCache.heartbeats.length > MAX_NUM_STORED_HEARTBEATS) { + const earliestHeartbeatIdx = getEarliestHeartbeatIdx(this._heartbeatsCache.heartbeats); + this._heartbeatsCache.heartbeats.splice(earliestHeartbeatIdx, 1); + } + } + return this._storage.overwrite(this._heartbeatsCache); + } + catch (e) { + logger.warn(e); + } + } + /** + * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly. + * It also clears all heartbeats from memory as well as in IndexedDB. + * + * NOTE: Consuming product SDKs should not send the header if this method + * returns an empty string. + */ + async getHeartbeatsHeader() { + try { + if (this._heartbeatsCache === null) { + await this._heartbeatsCachePromise; + } + // If it's still null or the array is empty, there is no data to send. + if (this._heartbeatsCache?.heartbeats == null || + this._heartbeatsCache.heartbeats.length === 0) { + return ''; + } + const date = getUTCDateString(); + // Extract as many heartbeats from the cache as will fit under the size limit. + const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats); + const headerString = util.base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend })); + // Store last sent date to prevent another being logged/sent for the same day. + this._heartbeatsCache.lastSentHeartbeatDate = date; + if (unsentEntries.length > 0) { + // Store any unsent entries if they exist. + this._heartbeatsCache.heartbeats = unsentEntries; + // This seems more likely than emptying the array (below) to lead to some odd state + // since the cache isn't empty and this will be called again on the next request, + // and is probably safest if we await it. + await this._storage.overwrite(this._heartbeatsCache); + } + else { + this._heartbeatsCache.heartbeats = []; + // Do not wait for this, to reduce latency. + void this._storage.overwrite(this._heartbeatsCache); + } + return headerString; + } + catch (e) { + logger.warn(e); + return ''; + } + } +} +function getUTCDateString() { + const today = new Date(); + // Returns date format 'YYYY-MM-DD' + return today.toISOString().substring(0, 10); +} +function extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) { + // Heartbeats grouped by user agent in the standard format to be sent in + // the header. + const heartbeatsToSend = []; + // Single date format heartbeats that are not sent. + let unsentEntries = heartbeatsCache.slice(); + for (const singleDateHeartbeat of heartbeatsCache) { + // Look for an existing entry with the same user agent. + const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent); + if (!heartbeatEntry) { + // If no entry for this user agent exists, create one. + heartbeatsToSend.push({ + agent: singleDateHeartbeat.agent, + dates: [singleDateHeartbeat.date] + }); + if (countBytes(heartbeatsToSend) > maxSize) { + // If the header would exceed max size, remove the added heartbeat + // entry and stop adding to the header. + heartbeatsToSend.pop(); + break; + } + } + else { + heartbeatEntry.dates.push(singleDateHeartbeat.date); + // If the header would exceed max size, remove the added date + // and stop adding to the header. + if (countBytes(heartbeatsToSend) > maxSize) { + heartbeatEntry.dates.pop(); + break; + } + } + // Pop unsent entry from queue. (Skipped if adding the entry exceeded + // quota and the loop breaks early.) + unsentEntries = unsentEntries.slice(1); + } + return { + heartbeatsToSend, + unsentEntries + }; +} +class HeartbeatStorageImpl { + constructor(app) { + this.app = app; + this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck(); + } + async runIndexedDBEnvironmentCheck() { + if (!util.isIndexedDBAvailable()) { + return false; + } + else { + return util.validateIndexedDBOpenable() + .then(() => true) + .catch(() => false); + } + } + /** + * Read all heartbeats. + */ + async read() { + const canUseIndexedDB = await this._canUseIndexedDBPromise; + if (!canUseIndexedDB) { + return { heartbeats: [] }; + } + else { + const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app); + if (idbHeartbeatObject?.heartbeats) { + return idbHeartbeatObject; + } + else { + return { heartbeats: [] }; + } + } + } + // overwrite the storage with the provided heartbeats + async overwrite(heartbeatsObject) { + const canUseIndexedDB = await this._canUseIndexedDBPromise; + if (!canUseIndexedDB) { + return; + } + else { + const existingHeartbeatsObject = await this.read(); + return writeHeartbeatsToIndexedDB(this.app, { + lastSentHeartbeatDate: heartbeatsObject.lastSentHeartbeatDate ?? + existingHeartbeatsObject.lastSentHeartbeatDate, + heartbeats: heartbeatsObject.heartbeats + }); + } + } + // add heartbeats + async add(heartbeatsObject) { + const canUseIndexedDB = await this._canUseIndexedDBPromise; + if (!canUseIndexedDB) { + return; + } + else { + const existingHeartbeatsObject = await this.read(); + return writeHeartbeatsToIndexedDB(this.app, { + lastSentHeartbeatDate: heartbeatsObject.lastSentHeartbeatDate ?? + existingHeartbeatsObject.lastSentHeartbeatDate, + heartbeats: [ + ...existingHeartbeatsObject.heartbeats, + ...heartbeatsObject.heartbeats + ] + }); + } + } +} +/** + * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped + * in a platform logging header JSON object, stringified, and converted + * to base 64. + */ +function countBytes(heartbeatsCache) { + // base64 has a restricted set of characters, all of which should be 1 byte. + return util.base64urlEncodeWithoutPadding( + // heartbeatsCache wrapper properties + JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length; +} +/** + * Returns the index of the heartbeat with the earliest date. + * If the heartbeats array is empty, -1 is returned. + */ +function getEarliestHeartbeatIdx(heartbeats) { + if (heartbeats.length === 0) { + return -1; + } + let earliestHeartbeatIdx = 0; + let earliestHeartbeatDate = heartbeats[0].date; + for (let i = 1; i < heartbeats.length; i++) { + if (heartbeats[i].date < earliestHeartbeatDate) { + earliestHeartbeatDate = heartbeats[i].date; + earliestHeartbeatIdx = i; + } + } + return earliestHeartbeatIdx; +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function registerCoreComponents(variant) { + _registerComponent(new component.Component('platform-logger', container => new PlatformLoggerServiceImpl(container), "PRIVATE" /* ComponentType.PRIVATE */)); + _registerComponent(new component.Component('heartbeat', container => new HeartbeatServiceImpl(container), "PRIVATE" /* ComponentType.PRIVATE */)); + // Register `app` package. + registerVersion(name$q, version$1, variant); + // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation + registerVersion(name$q, version$1, 'cjs2020'); + // Register platform SDK identifier (no version). + registerVersion('fire-js', ''); +} + +/** + * Firebase App + * + * @remarks This package coordinates the communication between the different Firebase components + * @packageDocumentation + */ +registerCoreComponents('node'); + +Object.defineProperty(exports, 'FirebaseError', { + enumerable: true, + get: function () { return util.FirebaseError; } +}); +exports.SDK_VERSION = SDK_VERSION; +exports._DEFAULT_ENTRY_NAME = DEFAULT_ENTRY_NAME; +exports._addComponent = _addComponent; +exports._addOrOverwriteComponent = _addOrOverwriteComponent; +exports._apps = _apps; +exports._clearComponents = _clearComponents; +exports._components = _components; +exports._getProvider = _getProvider; +exports._isFirebaseApp = _isFirebaseApp; +exports._isFirebaseServerApp = _isFirebaseServerApp; +exports._isFirebaseServerAppSettings = _isFirebaseServerAppSettings; +exports._registerComponent = _registerComponent; +exports._removeServiceInstance = _removeServiceInstance; +exports._serverApps = _serverApps; +exports.deleteApp = deleteApp; +exports.getApp = getApp; +exports.getApps = getApps; +exports.initializeApp = initializeApp; +exports.initializeServerApp = initializeServerApp; +exports.onLog = onLog; +exports.registerVersion = registerVersion; +exports.setLogLevel = setLogLevel; + +}(index_cjs)); + +Object.defineProperty(index_standalone, '__esModule', { value: true }); + +var Websocket = websocket; +var util = require$$2__default$3["default"]; +var logger$1 = require$$1__default$3["default"]; +var app = index_cjs; +var component = require$$0__default$2["default"]; + +function _interopDefaultLegacy$1 (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var Websocket__default = /*#__PURE__*/_interopDefaultLegacy$1(Websocket); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const PROTOCOL_VERSION = '5'; +const VERSION_PARAM = 'v'; +const TRANSPORT_SESSION_PARAM = 's'; +const REFERER_PARAM = 'r'; +const FORGE_REF = 'f'; +// Matches console.firebase.google.com, firebase-console-*.corp.google.com and +// firebase.corp.google.com +const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/; +const LAST_SESSION_PARAM = 'ls'; +const APPLICATION_ID_PARAM = 'p'; +const APP_CHECK_TOKEN_PARAM = 'ac'; +const WEBSOCKET = 'websocket'; +const LONG_POLLING = 'long_polling'; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Wraps a DOM Storage object and: + * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types. + * - prefixes names with "firebase:" to avoid collisions with app data. + * + * We automatically (see storage.js) create two such wrappers, one for sessionStorage, + * and one for localStorage. + * + */ +class DOMStorageWrapper { + /** + * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage) + */ + constructor(domStorage_) { + this.domStorage_ = domStorage_; + // Use a prefix to avoid collisions with other stuff saved by the app. + this.prefix_ = 'firebase:'; + } + /** + * @param key - The key to save the value under + * @param value - The value being stored, or null to remove the key. + */ + set(key, value) { + if (value == null) { + this.domStorage_.removeItem(this.prefixedName_(key)); + } + else { + this.domStorage_.setItem(this.prefixedName_(key), util.stringify(value)); + } + } + /** + * @returns The value that was stored under this key, or null + */ + get(key) { + const storedVal = this.domStorage_.getItem(this.prefixedName_(key)); + if (storedVal == null) { + return null; + } + else { + return util.jsonEval(storedVal); + } + } + remove(key) { + this.domStorage_.removeItem(this.prefixedName_(key)); + } + prefixedName_(name) { + return this.prefix_ + name; + } + toString() { + return this.domStorage_.toString(); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory storage implementation that matches the API of DOMStorageWrapper + * (TODO: create interface for both to implement). + */ +class MemoryStorage { + constructor() { + this.cache_ = {}; + this.isInMemoryStorage = true; + } + set(key, value) { + if (value == null) { + delete this.cache_[key]; + } + else { + this.cache_[key] = value; + } + } + get(key) { + if (util.contains(this.cache_, key)) { + return this.cache_[key]; + } + return null; + } + remove(key) { + delete this.cache_[key]; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage. + * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change + * to reflect this type + * + * @param domStorageName - Name of the underlying storage object + * (e.g. 'localStorage' or 'sessionStorage'). + * @returns Turning off type information until a common interface is defined. + */ +const createStoragefor = function (domStorageName) { + try { + // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception, + // so it must be inside the try/catch. + if (typeof window !== 'undefined' && + typeof window[domStorageName] !== 'undefined') { + // Need to test cache. Just because it's here doesn't mean it works + const domStorage = window[domStorageName]; + domStorage.setItem('firebase:sentinel', 'cache'); + domStorage.removeItem('firebase:sentinel'); + return new DOMStorageWrapper(domStorage); + } + } + catch (e) { } + // Failed to create wrapper. Just return in-memory storage. + // TODO: log? + return new MemoryStorage(); +}; +/** A storage object that lasts across sessions */ +const PersistentStorage = createStoragefor('localStorage'); +/** A storage object that only lasts one session */ +const SessionStorage = createStoragefor('sessionStorage'); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const logClient$1 = new logger$1.Logger('@firebase/database'); +/** + * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called). + */ +const LUIDGenerator = (function () { + let id = 1; + return function () { + return id++; + }; +})(); +/** + * Sha1 hash of the input string + * @param str - The string to hash + * @returns {!string} The resulting hash + */ +const sha1 = function (str) { + const utf8Bytes = util.stringToByteArray(str); + const sha1 = new util.Sha1(); + sha1.update(utf8Bytes); + const sha1Bytes = sha1.digest(); + return util.base64.encodeByteArray(sha1Bytes); +}; +const buildLogMessage_ = function (...varArgs) { + let message = ''; + for (let i = 0; i < varArgs.length; i++) { + const arg = varArgs[i]; + if (Array.isArray(arg) || + (arg && + typeof arg === 'object' && + // eslint-disable-next-line @typescript-eslint/no-explicit-any + typeof arg.length === 'number')) { + message += buildLogMessage_.apply(null, arg); + } + else if (typeof arg === 'object') { + message += util.stringify(arg); + } + else { + message += arg; + } + message += ' '; + } + return message; +}; +/** + * Use this for all debug messages in Firebase. + */ +let logger = null; +/** + * Flag to check for log availability on first log message + */ +let firstLog_ = true; +/** + * The implementation of Firebase.enableLogging (defined here to break dependencies) + * @param logger_ - A flag to turn on logging, or a custom logger + * @param persistent - Whether or not to persist logging settings across refreshes + */ +const enableLogging$1 = function (logger_, persistent) { + util.assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently."); + if (logger_ === true) { + logClient$1.logLevel = logger$1.LogLevel.VERBOSE; + logger = logClient$1.log.bind(logClient$1); + if (persistent) { + SessionStorage.set('logging_enabled', true); + } + } + else if (typeof logger_ === 'function') { + logger = logger_; + } + else { + logger = null; + SessionStorage.remove('logging_enabled'); + } +}; +const log = function (...varArgs) { + if (firstLog_ === true) { + firstLog_ = false; + if (logger === null && SessionStorage.get('logging_enabled') === true) { + enableLogging$1(true); + } + } + if (logger) { + const message = buildLogMessage_.apply(null, varArgs); + logger(message); + } +}; +const logWrapper = function (prefix) { + return function (...varArgs) { + log(prefix, ...varArgs); + }; +}; +const error = function (...varArgs) { + const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs); + logClient$1.error(message); +}; +const fatal = function (...varArgs) { + const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`; + logClient$1.error(message); + throw new Error(message); +}; +const warn$1 = function (...varArgs) { + const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs); + logClient$1.warn(message); +}; +/** + * Logs a warning if the containing page uses https. Called when a call to new Firebase + * does not use https. + */ +const warnIfPageIsSecure = function () { + // Be very careful accessing browser globals. Who knows what may or may not exist. + if (typeof window !== 'undefined' && + window.location && + window.location.protocol && + window.location.protocol.indexOf('https:') !== -1) { + warn$1('Insecure Firebase access from a secure page. ' + + 'Please use https in calls to new Firebase().'); + } +}; +/** + * Returns true if data is NaN, or +/- Infinity. + */ +const isInvalidJSONNumber = function (data) { + return (typeof data === 'number' && + (data !== data || // NaN + data === Number.POSITIVE_INFINITY || + data === Number.NEGATIVE_INFINITY)); +}; +const executeWhenDOMReady = function (fn) { + if (util.isNodeSdk() || document.readyState === 'complete') { + fn(); + } + else { + // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which + // fire before onload), but fall back to onload. + let called = false; + const wrappedFn = function () { + if (!document.body) { + setTimeout(wrappedFn, Math.floor(10)); + return; + } + if (!called) { + called = true; + fn(); + } + }; + if (document.addEventListener) { + document.addEventListener('DOMContentLoaded', wrappedFn, false); + // fallback to onload. + window.addEventListener('load', wrappedFn, false); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (document.attachEvent) { + // IE. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + document.attachEvent('onreadystatechange', () => { + if (document.readyState === 'complete') { + wrappedFn(); + } + }); + // fallback to onload. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + window.attachEvent('onload', wrappedFn); + // jQuery has an extra hack for IE that we could employ (based on + // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old. + // I'm hoping we don't need it. + } + } +}; +/** + * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names + */ +const MIN_NAME = '[MIN_NAME]'; +/** + * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names + */ +const MAX_NAME = '[MAX_NAME]'; +/** + * Compares valid Firebase key names, plus min and max name + */ +const nameCompare = function (a, b) { + if (a === b) { + return 0; + } + else if (a === MIN_NAME || b === MAX_NAME) { + return -1; + } + else if (b === MIN_NAME || a === MAX_NAME) { + return 1; + } + else { + const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b); + if (aAsInt !== null) { + if (bAsInt !== null) { + return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt; + } + else { + return -1; + } + } + else if (bAsInt !== null) { + return 1; + } + else { + return a < b ? -1 : 1; + } + } +}; +/** + * @returns {!number} comparison result. + */ +const stringCompare = function (a, b) { + if (a === b) { + return 0; + } + else if (a < b) { + return -1; + } + else { + return 1; + } +}; +const requireKey = function (key, obj) { + if (obj && key in obj) { + return obj[key]; + } + else { + throw new Error('Missing required key (' + key + ') in object: ' + util.stringify(obj)); + } +}; +const ObjectToUniqueKey = function (obj) { + if (typeof obj !== 'object' || obj === null) { + return util.stringify(obj); + } + const keys = []; + // eslint-disable-next-line guard-for-in + for (const k in obj) { + keys.push(k); + } + // Export as json, but with the keys sorted. + keys.sort(); + let key = '{'; + for (let i = 0; i < keys.length; i++) { + if (i !== 0) { + key += ','; + } + key += util.stringify(keys[i]); + key += ':'; + key += ObjectToUniqueKey(obj[keys[i]]); + } + key += '}'; + return key; +}; +/** + * Splits a string into a number of smaller segments of maximum size + * @param str - The string + * @param segsize - The maximum number of chars in the string. + * @returns The string, split into appropriately-sized chunks + */ +const splitStringBySize = function (str, segsize) { + const len = str.length; + if (len <= segsize) { + return [str]; + } + const dataSegs = []; + for (let c = 0; c < len; c += segsize) { + if (c + segsize > len) { + dataSegs.push(str.substring(c, len)); + } + else { + dataSegs.push(str.substring(c, c + segsize)); + } + } + return dataSegs; +}; +/** + * Apply a function to each (key, value) pair in an object or + * apply a function to each (index, value) pair in an array + * @param obj - The object or array to iterate over + * @param fn - The function to apply + */ +function each(obj, fn) { + for (const key in obj) { + if (obj.hasOwnProperty(key)) { + fn(key, obj[key]); + } + } +} +/** + * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License) + * I made one modification at the end and removed the NaN / Infinity + * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments. + * @param v - A double + * + */ +const doubleToIEEE754String = function (v) { + util.assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL + const ebits = 11, fbits = 52; + const bias = (1 << (ebits - 1)) - 1; + let s, e, f, ln, i; + // Compute sign, exponent, fraction + // Skip NaN / Infinity handling --MJL. + if (v === 0) { + e = 0; + f = 0; + s = 1 / v === -Infinity ? 1 : 0; + } + else { + s = v < 0; + v = Math.abs(v); + if (v >= Math.pow(2, 1 - bias)) { + // Normalized + ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias); + e = ln + bias; + f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits)); + } + else { + // Denormalized + e = 0; + f = Math.round(v / Math.pow(2, 1 - bias - fbits)); + } + } + // Pack sign, exponent, fraction + const bits = []; + for (i = fbits; i; i -= 1) { + bits.push(f % 2 ? 1 : 0); + f = Math.floor(f / 2); + } + for (i = ebits; i; i -= 1) { + bits.push(e % 2 ? 1 : 0); + e = Math.floor(e / 2); + } + bits.push(s ? 1 : 0); + bits.reverse(); + const str = bits.join(''); + // Return the data as a hex string. --MJL + let hexByteString = ''; + for (i = 0; i < 64; i += 8) { + let hexByte = parseInt(str.substr(i, 8), 2).toString(16); + if (hexByte.length === 1) { + hexByte = '0' + hexByte; + } + hexByteString = hexByteString + hexByte; + } + return hexByteString.toLowerCase(); +}; +/** + * Used to detect if we're in a Chrome content script (which executes in an + * isolated environment where long-polling doesn't work). + */ +const isChromeExtensionContentScript = function () { + return !!(typeof window === 'object' && + window['chrome'] && + window['chrome']['extension'] && + !/^chrome/.test(window.location.href)); +}; +/** + * Used to detect if we're in a Windows 8 Store app. + */ +const isWindowsStoreApp = function () { + // Check for the presence of a couple WinRT globals + return typeof Windows === 'object' && typeof Windows.UI === 'object'; +}; +/** + * Converts a server error code to a JavaScript Error + */ +function errorForServerCode(code, query) { + let reason = 'Unknown Error'; + if (code === 'too_big') { + reason = + 'The data requested exceeds the maximum size ' + + 'that can be accessed with a single request.'; + } + else if (code === 'permission_denied') { + reason = "Client doesn't have permission to access the desired data."; + } + else if (code === 'unavailable') { + reason = 'The service is unavailable'; + } + const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error.code = code.toUpperCase(); + return error; +} +/** + * Used to test for integer-looking strings + */ +const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$'); +/** + * For use in keys, the minimum possible 32-bit integer. + */ +const INTEGER_32_MIN = -2147483648; +/** + * For use in keys, the maximum possible 32-bit integer. + */ +const INTEGER_32_MAX = 2147483647; +/** + * If the string contains a 32-bit integer, return it. Else return null. + */ +const tryParseInt = function (str) { + if (INTEGER_REGEXP_.test(str)) { + const intVal = Number(str); + if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) { + return intVal; + } + } + return null; +}; +/** + * Helper to run some code but catch any exceptions and re-throw them later. + * Useful for preventing user callbacks from breaking internal code. + * + * Re-throwing the exception from a setTimeout is a little evil, but it's very + * convenient (we don't have to try to figure out when is a safe point to + * re-throw it), and the behavior seems reasonable: + * + * * If you aren't pausing on exceptions, you get an error in the console with + * the correct stack trace. + * * If you're pausing on all exceptions, the debugger will pause on your + * exception and then again when we rethrow it. + * * If you're only pausing on uncaught exceptions, the debugger will only pause + * on us re-throwing it. + * + * @param fn - The code to guard. + */ +const exceptionGuard = function (fn) { + try { + fn(); + } + catch (e) { + // Re-throw exception when it's safe. + setTimeout(() => { + // It used to be that "throw e" would result in a good console error with + // relevant context, but as of Chrome 39, you just get the firebase.js + // file/line number where we re-throw it, which is useless. So we log + // e.stack explicitly. + const stack = e.stack || ''; + warn$1('Exception was thrown by user callback.', stack); + throw e; + }, Math.floor(0)); + } +}; +/** + * @returns {boolean} true if we think we're currently being crawled. + */ +const beingCrawled = function () { + const userAgent = (typeof window === 'object' && + window['navigator'] && + window['navigator']['userAgent']) || + ''; + // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we + // believe to support JavaScript/AJAX rendering. + // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website + // would have seen the page" is flaky if we don't treat it as a crawler. + return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0); +}; +/** + * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting. + * + * It is removed with clearTimeout() as normal. + * + * @param fn - Function to run. + * @param time - Milliseconds to wait before running. + * @returns The setTimeout() return value. + */ +const setTimeoutNonBlocking = function (fn, time) { + const timeout = setTimeout(fn, time); + // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API. + if (typeof timeout === 'number' && + // @ts-ignore Is only defined in Deno environments. + typeof Deno !== 'undefined' && + // @ts-ignore Deno and unrefTimer are only defined in Deno environments. + Deno['unrefTimer']) { + // @ts-ignore Deno and unrefTimer are only defined in Deno environments. + Deno.unrefTimer(timeout); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (typeof timeout === 'object' && timeout['unref']) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + timeout['unref'](); + } + return timeout; +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A class that holds metadata about a Repo object + */ +class RepoInfo { + /** + * @param host - Hostname portion of the url for the repo + * @param secure - Whether or not this repo is accessed over ssl + * @param namespace - The namespace represented by the repo + * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest). + * @param nodeAdmin - Whether this instance uses Admin SDK credentials + * @param persistenceKey - Override the default session persistence storage key + */ + constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false, isUsingEmulator = false, emulatorOptions = null) { + this.secure = secure; + this.namespace = namespace; + this.webSocketOnly = webSocketOnly; + this.nodeAdmin = nodeAdmin; + this.persistenceKey = persistenceKey; + this.includeNamespaceInQueryParams = includeNamespaceInQueryParams; + this.isUsingEmulator = isUsingEmulator; + this.emulatorOptions = emulatorOptions; + this._host = host.toLowerCase(); + this._domain = this._host.substr(this._host.indexOf('.') + 1); + this.internalHost = + PersistentStorage.get('host:' + host) || this._host; + } + isCacheableHost() { + return this.internalHost.substr(0, 2) === 's-'; + } + isCustomHost() { + return (this._domain !== 'firebaseio.com' && + this._domain !== 'firebaseio-demo.com'); + } + get host() { + return this._host; + } + set host(newHost) { + if (newHost !== this.internalHost) { + this.internalHost = newHost; + if (this.isCacheableHost()) { + PersistentStorage.set('host:' + this._host, this.internalHost); + } + } + } + toString() { + let str = this.toURLString(); + if (this.persistenceKey) { + str += '<' + this.persistenceKey + '>'; + } + return str; + } + toURLString() { + const protocol = this.secure ? 'https://' : 'http://'; + const query = this.includeNamespaceInQueryParams + ? `?ns=${this.namespace}` + : ''; + return `${protocol}${this.host}/${query}`; + } +} +function repoInfoNeedsQueryParam(repoInfo) { + return (repoInfo.host !== repoInfo.internalHost || + repoInfo.isCustomHost() || + repoInfo.includeNamespaceInQueryParams); +} +/** + * Returns the websocket URL for this repo + * @param repoInfo - RepoInfo object + * @param type - of connection + * @param params - list + * @returns The URL for this repo + */ +function repoInfoConnectionURL(repoInfo, type, params) { + util.assert(typeof type === 'string', 'typeof type must == string'); + util.assert(typeof params === 'object', 'typeof params must == object'); + let connURL; + if (type === WEBSOCKET) { + connURL = + (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?'; + } + else if (type === LONG_POLLING) { + connURL = + (repoInfo.secure ? 'https://' : 'http://') + + repoInfo.internalHost + + '/.lp?'; + } + else { + throw new Error('Unknown connection type: ' + type); + } + if (repoInfoNeedsQueryParam(repoInfo)) { + params['ns'] = repoInfo.namespace; + } + const pairs = []; + each(params, (key, value) => { + pairs.push(key + '=' + value); + }); + return connURL + pairs.join('&'); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Tracks a collection of stats. + */ +class StatsCollection { + constructor() { + this.counters_ = {}; + } + incrementCounter(name, amount = 1) { + if (!util.contains(this.counters_, name)) { + this.counters_[name] = 0; + } + this.counters_[name] += amount; + } + get() { + return util.deepCopy(this.counters_); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const collections = {}; +const reporters = {}; +function statsManagerGetCollection(repoInfo) { + const hashString = repoInfo.toString(); + if (!collections[hashString]) { + collections[hashString] = new StatsCollection(); + } + return collections[hashString]; +} +function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) { + const hashString = repoInfo.toString(); + if (!reporters[hashString]) { + reporters[hashString] = creatorFunction(); + } + return reporters[hashString]; +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The semver (www.semver.org) version of the SDK. */ +let SDK_VERSION = ''; +/** + * SDK_VERSION should be set before any database instance is created + * @internal + */ +function setSDKVersion(version) { + SDK_VERSION = version; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const WEBSOCKET_MAX_FRAME_SIZE = 16384; +const WEBSOCKET_KEEPALIVE_INTERVAL = 45000; +let WebSocketImpl = null; +if (typeof MozWebSocket !== 'undefined') { + WebSocketImpl = MozWebSocket; +} +else if (typeof WebSocket !== 'undefined') { + WebSocketImpl = WebSocket; +} +function setWebSocketImpl(impl) { + WebSocketImpl = impl; +} +/** + * Create a new websocket connection with the given callbacks. + */ +class WebSocketConnection { + /** + * @param connId identifier for this transport + * @param repoInfo The info for the websocket endpoint. + * @param applicationId The Firebase App ID for this project. + * @param appCheckToken The App Check Token for this client. + * @param authToken The Auth Token for this client. + * @param transportSessionId Optional transportSessionId if this is connecting + * to an existing transport session + * @param lastSessionId Optional lastSessionId if there was a previous + * connection + */ + constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) { + this.connId = connId; + this.applicationId = applicationId; + this.appCheckToken = appCheckToken; + this.authToken = authToken; + this.keepaliveTimer = null; + this.frames = null; + this.totalFrames = 0; + this.bytesSent = 0; + this.bytesReceived = 0; + this.log_ = logWrapper(this.connId); + this.stats_ = statsManagerGetCollection(repoInfo); + this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId); + this.nodeAdmin = repoInfo.nodeAdmin; + } + /** + * @param repoInfo - The info for the websocket endpoint. + * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport + * session + * @param lastSessionId - Optional lastSessionId if there was a previous connection + * @returns connection url + */ + static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) { + const urlParams = {}; + urlParams[VERSION_PARAM] = PROTOCOL_VERSION; + if (!util.isNodeSdk() && + typeof location !== 'undefined' && + location.hostname && + FORGE_DOMAIN_RE.test(location.hostname)) { + urlParams[REFERER_PARAM] = FORGE_REF; + } + if (transportSessionId) { + urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId; + } + if (lastSessionId) { + urlParams[LAST_SESSION_PARAM] = lastSessionId; + } + if (appCheckToken) { + urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken; + } + if (applicationId) { + urlParams[APPLICATION_ID_PARAM] = applicationId; + } + return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams); + } + /** + * @param onMessage - Callback when messages arrive + * @param onDisconnect - Callback with connection lost. + */ + open(onMessage, onDisconnect) { + this.onDisconnect = onDisconnect; + this.onMessage = onMessage; + this.log_('Websocket connecting to ' + this.connURL); + this.everConnected_ = false; + // Assume failure until proven otherwise. + PersistentStorage.set('previous_websocket_failure', true); + try { + let options; + if (util.isNodeSdk()) { + const device = this.nodeAdmin ? 'AdminNode' : 'Node'; + // UA Format: Firebase//// + options = { + headers: { + 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`, + 'X-Firebase-GMPID': this.applicationId || '' + } + }; + // If using Node with admin creds, AppCheck-related checks are unnecessary. + // Note that we send the credentials here even if they aren't admin credentials, which is + // not a problem. + // Note that this header is just used to bypass appcheck, and the token should still be sent + // through the websocket connection once it is established. + if (this.authToken) { + options.headers['Authorization'] = `Bearer ${this.authToken}`; + } + if (this.appCheckToken) { + options.headers['X-Firebase-AppCheck'] = this.appCheckToken; + } + // Plumb appropriate http_proxy environment variable into faye-websocket if it exists. + const env = process['env']; + const proxy = this.connURL.indexOf('wss://') === 0 + ? env['HTTPS_PROXY'] || env['https_proxy'] + : env['HTTP_PROXY'] || env['http_proxy']; + if (proxy) { + options['proxy'] = { origin: proxy }; + } + } + this.mySock = new WebSocketImpl(this.connURL, [], options); + } + catch (e) { + this.log_('Error instantiating WebSocket.'); + const error = e.message || e.data; + if (error) { + this.log_(error); + } + this.onClosed_(); + return; + } + this.mySock.onopen = () => { + this.log_('Websocket connected.'); + this.everConnected_ = true; + }; + this.mySock.onclose = () => { + this.log_('Websocket connection was disconnected.'); + this.mySock = null; + this.onClosed_(); + }; + this.mySock.onmessage = m => { + this.handleIncomingFrame(m); + }; + this.mySock.onerror = e => { + this.log_('WebSocket error. Closing connection.'); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const error = e.message || e.data; + if (error) { + this.log_(error); + } + this.onClosed_(); + }; + } + /** + * No-op for websockets, we don't need to do anything once the connection is confirmed as open + */ + start() { } + static forceDisallow() { + WebSocketConnection.forceDisallow_ = true; + } + static isAvailable() { + let isOldAndroid = false; + if (typeof navigator !== 'undefined' && navigator.userAgent) { + const oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/; + const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex); + if (oldAndroidMatch && oldAndroidMatch.length > 1) { + if (parseFloat(oldAndroidMatch[1]) < 4.4) { + isOldAndroid = true; + } + } + } + return (!isOldAndroid && + WebSocketImpl !== null && + !WebSocketConnection.forceDisallow_); + } + /** + * Returns true if we previously failed to connect with this transport. + */ + static previouslyFailed() { + // If our persistent storage is actually only in-memory storage, + // we default to assuming that it previously failed to be safe. + return (PersistentStorage.isInMemoryStorage || + PersistentStorage.get('previous_websocket_failure') === true); + } + markConnectionHealthy() { + PersistentStorage.remove('previous_websocket_failure'); + } + appendFrame_(data) { + this.frames.push(data); + if (this.frames.length === this.totalFrames) { + const fullMess = this.frames.join(''); + this.frames = null; + const jsonMess = util.jsonEval(fullMess); + //handle the message + this.onMessage(jsonMess); + } + } + /** + * @param frameCount - The number of frames we are expecting from the server + */ + handleNewFrameCount_(frameCount) { + this.totalFrames = frameCount; + this.frames = []; + } + /** + * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1 + * @returns Any remaining data to be process, or null if there is none + */ + extractFrameCount_(data) { + util.assert(this.frames === null, 'We already have a frame buffer'); + // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced + // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508 + if (data.length <= 6) { + const frameCount = Number(data); + if (!isNaN(frameCount)) { + this.handleNewFrameCount_(frameCount); + return null; + } + } + this.handleNewFrameCount_(1); + return data; + } + /** + * Process a websocket frame that has arrived from the server. + * @param mess - The frame data + */ + handleIncomingFrame(mess) { + if (this.mySock === null) { + return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes. + } + const data = mess['data']; + this.bytesReceived += data.length; + this.stats_.incrementCounter('bytes_received', data.length); + this.resetKeepAlive(); + if (this.frames !== null) { + // we're buffering + this.appendFrame_(data); + } + else { + // try to parse out a frame count, otherwise, assume 1 and process it + const remainingData = this.extractFrameCount_(data); + if (remainingData !== null) { + this.appendFrame_(remainingData); + } + } + } + /** + * Send a message to the server + * @param data - The JSON object to transmit + */ + send(data) { + this.resetKeepAlive(); + const dataStr = util.stringify(data); + this.bytesSent += dataStr.length; + this.stats_.incrementCounter('bytes_sent', dataStr.length); + //We can only fit a certain amount in each websocket frame, so we need to split this request + //up into multiple pieces if it doesn't fit in one request. + const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE); + //Send the length header + if (dataSegs.length > 1) { + this.sendString_(String(dataSegs.length)); + } + //Send the actual data in segments. + for (let i = 0; i < dataSegs.length; i++) { + this.sendString_(dataSegs[i]); + } + } + shutdown_() { + this.isClosed_ = true; + if (this.keepaliveTimer) { + clearInterval(this.keepaliveTimer); + this.keepaliveTimer = null; + } + if (this.mySock) { + this.mySock.close(); + this.mySock = null; + } + } + onClosed_() { + if (!this.isClosed_) { + this.log_('WebSocket is closing itself'); + this.shutdown_(); + // since this is an internal close, trigger the close listener + if (this.onDisconnect) { + this.onDisconnect(this.everConnected_); + this.onDisconnect = null; + } + } + } + /** + * External-facing close handler. + * Close the websocket and kill the connection. + */ + close() { + if (!this.isClosed_) { + this.log_('WebSocket is being closed'); + this.shutdown_(); + } + } + /** + * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after + * the last activity. + */ + resetKeepAlive() { + clearInterval(this.keepaliveTimer); + this.keepaliveTimer = setInterval(() => { + //If there has been no websocket activity for a while, send a no-op + if (this.mySock) { + this.sendString_('0'); + } + this.resetKeepAlive(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL)); + } + /** + * Send a string over the websocket. + * + * @param str - String to send. + */ + sendString_(str) { + // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send() + // calls for some unknown reason. We treat these as an error and disconnect. + // See https://app.asana.com/0/58926111402292/68021340250410 + try { + this.mySock.send(str); + } + catch (e) { + this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.'); + setTimeout(this.onClosed_.bind(this), 0); + } + } +} +/** + * Number of response before we consider the connection "healthy." + */ +WebSocketConnection.responsesRequiredToBeHealthy = 2; +/** + * Time to wait for the connection te become healthy before giving up. + */ +WebSocketConnection.healthyTimeout = 30000; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Abstraction around AppCheck's token fetching capabilities. + */ +class AppCheckTokenProvider { + constructor(app$1, appCheckProvider) { + this.appCheckProvider = appCheckProvider; + this.appName = app$1.name; + if (app._isFirebaseServerApp(app$1) && app$1.settings.appCheckToken) { + this.serverAppAppCheckToken = app$1.settings.appCheckToken; + } + this.appCheck = appCheckProvider?.getImmediate({ optional: true }); + if (!this.appCheck) { + appCheckProvider?.get().then(appCheck => (this.appCheck = appCheck)); + } + } + getToken(forceRefresh) { + if (this.serverAppAppCheckToken) { + if (forceRefresh) { + throw new Error('Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.'); + } + return Promise.resolve({ token: this.serverAppAppCheckToken }); + } + if (!this.appCheck) { + return new Promise((resolve, reject) => { + // Support delayed initialization of FirebaseAppCheck. This allows our + // customers to initialize the RTDB SDK before initializing Firebase + // AppCheck and ensures that all requests are authenticated if a token + // becomes available before the timeout below expires. + setTimeout(() => { + if (this.appCheck) { + this.getToken(forceRefresh).then(resolve, reject); + } + else { + resolve(null); + } + }, 0); + }); + } + return this.appCheck.getToken(forceRefresh); + } + addTokenChangeListener(listener) { + this.appCheckProvider + ?.get() + .then(appCheck => appCheck.addTokenListener(listener)); + } + notifyForInvalidToken() { + warn$1(`Provided AppCheck credentials for the app named "${this.appName}" ` + + 'are invalid. This usually indicates your app was not initialized correctly.'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Abstraction around FirebaseApp's token fetching capabilities. + */ +class FirebaseAuthTokenProvider { + constructor(appName_, firebaseOptions_, authProvider_) { + this.appName_ = appName_; + this.firebaseOptions_ = firebaseOptions_; + this.authProvider_ = authProvider_; + this.auth_ = null; + this.auth_ = authProvider_.getImmediate({ optional: true }); + if (!this.auth_) { + authProvider_.onInit(auth => (this.auth_ = auth)); + } + } + getToken(forceRefresh) { + if (!this.auth_) { + return new Promise((resolve, reject) => { + // Support delayed initialization of FirebaseAuth. This allows our + // customers to initialize the RTDB SDK before initializing Firebase + // Auth and ensures that all requests are authenticated if a token + // becomes available before the timeout below expires. + setTimeout(() => { + if (this.auth_) { + this.getToken(forceRefresh).then(resolve, reject); + } + else { + resolve(null); + } + }, 0); + }); + } + return this.auth_.getToken(forceRefresh).catch(error => { + // TODO: Need to figure out all the cases this is raised and whether + // this makes sense. + if (error && error.code === 'auth/token-not-initialized') { + log('Got auth/token-not-initialized error. Treating as null token.'); + return null; + } + else { + return Promise.reject(error); + } + }); + } + addTokenChangeListener(listener) { + // TODO: We might want to wrap the listener and call it with no args to + // avoid a leaky abstraction, but that makes removing the listener harder. + if (this.auth_) { + this.auth_.addAuthTokenListener(listener); + } + else { + this.authProvider_ + .get() + .then(auth => auth.addAuthTokenListener(listener)); + } + } + removeTokenChangeListener(listener) { + this.authProvider_ + .get() + .then(auth => auth.removeAuthTokenListener(listener)); + } + notifyForInvalidToken() { + let errorMessage = 'Provided authentication credentials for the app named "' + + this.appName_ + + '" are invalid. This usually indicates your app was not ' + + 'initialized correctly. '; + if ('credential' in this.firebaseOptions_) { + errorMessage += + 'Make sure the "credential" property provided to initializeApp() ' + + 'is authorized to access the specified "databaseURL" and is from the correct ' + + 'project.'; + } + else if ('serviceAccount' in this.firebaseOptions_) { + errorMessage += + 'Make sure the "serviceAccount" property provided to initializeApp() ' + + 'is authorized to access the specified "databaseURL" and is from the correct ' + + 'project.'; + } + else { + errorMessage += + 'Make sure the "apiKey" and "databaseURL" properties provided to ' + + 'initializeApp() match the values provided for your app at ' + + 'https://console.firebase.google.com/.'; + } + warn$1(errorMessage); + } +} +/* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */ +class EmulatorTokenProvider { + constructor(accessToken) { + this.accessToken = accessToken; + } + getToken(forceRefresh) { + return Promise.resolve({ + accessToken: this.accessToken + }); + } + addTokenChangeListener(listener) { + // Invoke the listener immediately to match the behavior in Firebase Auth + // (see packages/auth/src/auth.js#L1807) + listener(this.accessToken); + } + removeTokenChangeListener(listener) { } + notifyForInvalidToken() { } +} +/** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */ +EmulatorTokenProvider.OWNER = 'owner'; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This class ensures the packets from the server arrive in order + * This class takes data from the server and ensures it gets passed into the callbacks in order. + */ +class PacketReceiver { + /** + * @param onMessage_ + */ + constructor(onMessage_) { + this.onMessage_ = onMessage_; + this.pendingResponses = []; + this.currentResponseNum = 0; + this.closeAfterResponse = -1; + this.onClose = null; + } + closeAfter(responseNum, callback) { + this.closeAfterResponse = responseNum; + this.onClose = callback; + if (this.closeAfterResponse < this.currentResponseNum) { + this.onClose(); + this.onClose = null; + } + } + /** + * Each message from the server comes with a response number, and an array of data. The responseNumber + * allows us to ensure that we process them in the right order, since we can't be guaranteed that all + * browsers will respond in the same order as the requests we sent + */ + handleResponse(requestNum, data) { + this.pendingResponses[requestNum] = data; + while (this.pendingResponses[this.currentResponseNum]) { + const toProcess = this.pendingResponses[this.currentResponseNum]; + delete this.pendingResponses[this.currentResponseNum]; + for (let i = 0; i < toProcess.length; ++i) { + if (toProcess[i]) { + exceptionGuard(() => { + this.onMessage_(toProcess[i]); + }); + } + } + if (this.currentResponseNum === this.closeAfterResponse) { + if (this.onClose) { + this.onClose(); + this.onClose = null; + } + break; + } + this.currentResponseNum++; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// URL query parameters associated with longpolling +const FIREBASE_LONGPOLL_START_PARAM = 'start'; +const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close'; +const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand'; +const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB'; +const FIREBASE_LONGPOLL_ID_PARAM = 'id'; +const FIREBASE_LONGPOLL_PW_PARAM = 'pw'; +const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser'; +const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb'; +const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg'; +const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts'; +const FIREBASE_LONGPOLL_DATA_PARAM = 'd'; +const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe'; +//Data size constants. +//TODO: Perf: the maximum length actually differs from browser to browser. +// We should check what browser we're on and set accordingly. +const MAX_URL_DATA_SIZE = 1870; +const SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d= +const MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE; +/** + * Keepalive period + * send a fresh request at minimum every 25 seconds. Opera has a maximum request + * length of 30 seconds that we can't exceed. + */ +const KEEPALIVE_REQUEST_INTERVAL = 25000; +/** + * How long to wait before aborting a long-polling connection attempt. + */ +const LP_CONNECT_TIMEOUT = 30000; +/** + * This class manages a single long-polling connection. + */ +class BrowserPollConnection { + /** + * @param connId An identifier for this connection, used for logging + * @param repoInfo The info for the endpoint to send data to. + * @param applicationId The Firebase App ID for this project. + * @param appCheckToken The AppCheck token for this client. + * @param authToken The AuthToken to use for this connection. + * @param transportSessionId Optional transportSessionid if we are + * reconnecting for an existing transport session + * @param lastSessionId Optional lastSessionId if the PersistentConnection has + * already created a connection previously + */ + constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) { + this.connId = connId; + this.repoInfo = repoInfo; + this.applicationId = applicationId; + this.appCheckToken = appCheckToken; + this.authToken = authToken; + this.transportSessionId = transportSessionId; + this.lastSessionId = lastSessionId; + this.bytesSent = 0; + this.bytesReceived = 0; + this.everConnected_ = false; + this.log_ = logWrapper(connId); + this.stats_ = statsManagerGetCollection(repoInfo); + this.urlFn = (params) => { + // Always add the token if we have one. + if (this.appCheckToken) { + params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken; + } + return repoInfoConnectionURL(repoInfo, LONG_POLLING, params); + }; + } + /** + * @param onMessage - Callback when messages arrive + * @param onDisconnect - Callback with connection lost. + */ + open(onMessage, onDisconnect) { + this.curSegmentNum = 0; + this.onDisconnect_ = onDisconnect; + this.myPacketOrderer = new PacketReceiver(onMessage); + this.isClosed_ = false; + this.connectTimeoutTimer_ = setTimeout(() => { + this.log_('Timed out trying to connect.'); + // Make sure we clear the host cache + this.onClosed_(); + this.connectTimeoutTimer_ = null; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(LP_CONNECT_TIMEOUT)); + // Ensure we delay the creation of the iframe until the DOM is loaded. + executeWhenDOMReady(() => { + if (this.isClosed_) { + return; + } + //Set up a callback that gets triggered once a connection is set up. + this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => { + const [command, arg1, arg2, arg3, arg4] = args; + this.incrementIncomingBytes_(args); + if (!this.scriptTagHolder) { + return; // we closed the connection. + } + if (this.connectTimeoutTimer_) { + clearTimeout(this.connectTimeoutTimer_); + this.connectTimeoutTimer_ = null; + } + this.everConnected_ = true; + if (command === FIREBASE_LONGPOLL_START_PARAM) { + this.id = arg1; + this.password = arg2; + } + else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) { + // Don't clear the host cache. We got a response from the server, so we know it's reachable + if (arg1) { + // We aren't expecting any more data (other than what the server's already in the process of sending us + // through our already open polls), so don't send any more. + this.scriptTagHolder.sendNewPolls = false; + // arg1 in this case is the last response number sent by the server. We should try to receive + // all of the responses up to this one before closing + this.myPacketOrderer.closeAfter(arg1, () => { + this.onClosed_(); + }); + } + else { + this.onClosed_(); + } + } + else { + throw new Error('Unrecognized command received: ' + command); + } + }, (...args) => { + const [pN, data] = args; + this.incrementIncomingBytes_(args); + this.myPacketOrderer.handleResponse(pN, data); + }, () => { + this.onClosed_(); + }, this.urlFn); + //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results + //from cache. + const urlParams = {}; + urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't'; + urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000); + if (this.scriptTagHolder.uniqueCallbackIdentifier) { + urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = + this.scriptTagHolder.uniqueCallbackIdentifier; + } + urlParams[VERSION_PARAM] = PROTOCOL_VERSION; + if (this.transportSessionId) { + urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId; + } + if (this.lastSessionId) { + urlParams[LAST_SESSION_PARAM] = this.lastSessionId; + } + if (this.applicationId) { + urlParams[APPLICATION_ID_PARAM] = this.applicationId; + } + if (this.appCheckToken) { + urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken; + } + if (typeof location !== 'undefined' && + location.hostname && + FORGE_DOMAIN_RE.test(location.hostname)) { + urlParams[REFERER_PARAM] = FORGE_REF; + } + const connectURL = this.urlFn(urlParams); + this.log_('Connecting via long-poll to ' + connectURL); + this.scriptTagHolder.addTag(connectURL, () => { + /* do nothing */ + }); + }); + } + /** + * Call this when a handshake has completed successfully and we want to consider the connection established + */ + start() { + this.scriptTagHolder.startLongPoll(this.id, this.password); + this.addDisconnectPingFrame(this.id, this.password); + } + /** + * Forces long polling to be considered as a potential transport + */ + static forceAllow() { + BrowserPollConnection.forceAllow_ = true; + } + /** + * Forces longpolling to not be considered as a potential transport + */ + static forceDisallow() { + BrowserPollConnection.forceDisallow_ = true; + } + // Static method, use string literal so it can be accessed in a generic way + static isAvailable() { + if (util.isNodeSdk()) { + return false; + } + else if (BrowserPollConnection.forceAllow_) { + return true; + } + else { + // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in + // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08). + return (!BrowserPollConnection.forceDisallow_ && + typeof document !== 'undefined' && + document.createElement != null && + !isChromeExtensionContentScript() && + !isWindowsStoreApp()); + } + } + /** + * No-op for polling + */ + markConnectionHealthy() { } + /** + * Stops polling and cleans up the iframe + */ + shutdown_() { + this.isClosed_ = true; + if (this.scriptTagHolder) { + this.scriptTagHolder.close(); + this.scriptTagHolder = null; + } + //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving. + if (this.myDisconnFrame) { + document.body.removeChild(this.myDisconnFrame); + this.myDisconnFrame = null; + } + if (this.connectTimeoutTimer_) { + clearTimeout(this.connectTimeoutTimer_); + this.connectTimeoutTimer_ = null; + } + } + /** + * Triggered when this transport is closed + */ + onClosed_() { + if (!this.isClosed_) { + this.log_('Longpoll is closing itself'); + this.shutdown_(); + if (this.onDisconnect_) { + this.onDisconnect_(this.everConnected_); + this.onDisconnect_ = null; + } + } + } + /** + * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server + * that we've left. + */ + close() { + if (!this.isClosed_) { + this.log_('Longpoll is being closed.'); + this.shutdown_(); + } + } + /** + * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then + * broken into chunks (since URLs have a small maximum length). + * @param data - The JSON data to transmit. + */ + send(data) { + const dataStr = util.stringify(data); + this.bytesSent += dataStr.length; + this.stats_.incrementCounter('bytes_sent', dataStr.length); + //first, lets get the base64-encoded data + const base64data = util.base64Encode(dataStr); + //We can only fit a certain amount in each URL, so we need to split this request + //up into multiple pieces if it doesn't fit in one request. + const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE); + //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number + //of segments so that we can reassemble the packet on the server. + for (let i = 0; i < dataSegs.length; i++) { + this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]); + this.curSegmentNum++; + } + } + /** + * This is how we notify the server that we're leaving. + * We aren't able to send requests with DHTML on a window close event, but we can + * trigger XHR requests in some browsers (everything but Opera basically). + */ + addDisconnectPingFrame(id, pw) { + if (util.isNodeSdk()) { + return; + } + this.myDisconnFrame = document.createElement('iframe'); + const urlParams = {}; + urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't'; + urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id; + urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw; + this.myDisconnFrame.src = this.urlFn(urlParams); + this.myDisconnFrame.style.display = 'none'; + document.body.appendChild(this.myDisconnFrame); + } + /** + * Used to track the bytes received by this client + */ + incrementIncomingBytes_(args) { + // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in. + const bytesReceived = util.stringify(args).length; + this.bytesReceived += bytesReceived; + this.stats_.incrementCounter('bytes_received', bytesReceived); + } +} +/********************************************************************************************* + * A wrapper around an iframe that is used as a long-polling script holder. + *********************************************************************************************/ +class FirebaseIFrameScriptHolder { + /** + * @param commandCB - The callback to be called when control commands are received from the server. + * @param onMessageCB - The callback to be triggered when responses arrive from the server. + * @param onDisconnect - The callback to be triggered when this tag holder is closed + * @param urlFn - A function that provides the URL of the endpoint to send data to. + */ + constructor(commandCB, onMessageCB, onDisconnect, urlFn) { + this.onDisconnect = onDisconnect; + this.urlFn = urlFn; + //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause + //problems in some browsers. + this.outstandingRequests = new Set(); + //A queue of the pending segments waiting for transmission to the server. + this.pendingSegs = []; + //A serial number. We use this for two things: + // 1) A way to ensure the browser doesn't cache responses to polls + // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The + // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute + // JSONP code in the order it was added to the iframe. + this.currentSerial = Math.floor(Math.random() * 100000000); + // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still + // incoming data from the server that we're waiting for). + this.sendNewPolls = true; + if (!util.isNodeSdk()) { + //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the + //iframes where we put the long-polling script tags. We have two callbacks: + // 1) Command Callback - Triggered for control issues, like starting a connection. + // 2) Message Callback - Triggered when new data arrives. + this.uniqueCallbackIdentifier = LUIDGenerator(); + window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB; + window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = + onMessageCB; + //Create an iframe for us to add script tags to. + this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_(); + // Set the iframe's contents. + let script = ''; + // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient + // for ie9, but ie8 needs to do it again in the document itself. + if (this.myIFrame.src && + this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') { + const currentDomain = document.domain; + script = ''; + } + const iframeContents = '' + script + ''; + try { + this.myIFrame.doc.open(); + this.myIFrame.doc.write(iframeContents); + this.myIFrame.doc.close(); + } + catch (e) { + log('frame writing exception'); + if (e.stack) { + log(e.stack); + } + log(e); + } + } + else { + this.commandCB = commandCB; + this.onMessageCB = onMessageCB; + } + } + /** + * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can + * actually use. + */ + static createIFrame_() { + const iframe = document.createElement('iframe'); + iframe.style.display = 'none'; + // This is necessary in order to initialize the document inside the iframe + if (document.body) { + document.body.appendChild(iframe); + try { + // If document.domain has been modified in IE, this will throw an error, and we need to set the + // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute + // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work. + const a = iframe.contentWindow.document; + if (!a) { + // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above. + log('No IE domain setting required'); + } + } + catch (e) { + const domain = document.domain; + iframe.src = + "javascript:void((function(){document.open();document.domain='" + + domain + + "';document.close();})())"; + } + } + else { + // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this + // never gets hit. + throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.'; + } + // Get the document of the iframe in a browser-specific way. + if (iframe.contentDocument) { + iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari + } + else if (iframe.contentWindow) { + iframe.doc = iframe.contentWindow.document; // Internet Explorer + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (iframe.document) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + iframe.doc = iframe.document; //others? + } + return iframe; + } + /** + * Cancel all outstanding queries and remove the frame. + */ + close() { + //Mark this iframe as dead, so no new requests are sent. + this.alive = false; + if (this.myIFrame) { + //We have to actually remove all of the html inside this iframe before removing it from the + //window, or IE will continue loading and executing the script tags we've already added, which + //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this. + this.myIFrame.doc.body.textContent = ''; + setTimeout(() => { + if (this.myIFrame !== null) { + document.body.removeChild(this.myIFrame); + this.myIFrame = null; + } + }, Math.floor(0)); + } + // Protect from being called recursively. + const onDisconnect = this.onDisconnect; + if (onDisconnect) { + this.onDisconnect = null; + onDisconnect(); + } + } + /** + * Actually start the long-polling session by adding the first script tag(s) to the iframe. + * @param id - The ID of this connection + * @param pw - The password for this connection + */ + startLongPoll(id, pw) { + this.myID = id; + this.myPW = pw; + this.alive = true; + //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to. + while (this.newRequest_()) { } + } + /** + * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't + * too many outstanding requests and we are still alive. + * + * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if + * needed. + */ + newRequest_() { + // We keep one outstanding request open all the time to receive data, but if we need to send data + // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically + // close the old request. + if (this.alive && + this.sendNewPolls && + this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) { + //construct our url + this.currentSerial++; + const urlParams = {}; + urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID; + urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW; + urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial; + let theURL = this.urlFn(urlParams); + //Now add as much data as we can. + let curDataString = ''; + let i = 0; + while (this.pendingSegs.length > 0) { + //first, lets see if the next segment will fit. + const nextSeg = this.pendingSegs[0]; + if (nextSeg.d.length + + SEG_HEADER_SIZE + + curDataString.length <= + MAX_URL_DATA_SIZE) { + //great, the segment will fit. Lets append it. + const theSeg = this.pendingSegs.shift(); + curDataString = + curDataString + + '&' + + FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM + + i + + '=' + + theSeg.seg + + '&' + + FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET + + i + + '=' + + theSeg.ts + + '&' + + FIREBASE_LONGPOLL_DATA_PARAM + + i + + '=' + + theSeg.d; + i++; + } + else { + break; + } + } + theURL = theURL + curDataString; + this.addLongPollTag_(theURL, this.currentSerial); + return true; + } + else { + return false; + } + } + /** + * Queue a packet for transmission to the server. + * @param segnum - A sequential id for this packet segment used for reassembly + * @param totalsegs - The total number of segments in this packet + * @param data - The data for this segment. + */ + enqueueSegment(segnum, totalsegs, data) { + //add this to the queue of segments to send. + this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data }); + //send the data immediately if there isn't already data being transmitted, unless + //startLongPoll hasn't been called yet. + if (this.alive) { + this.newRequest_(); + } + } + /** + * Add a script tag for a regular long-poll request. + * @param url - The URL of the script tag. + * @param serial - The serial number of the request. + */ + addLongPollTag_(url, serial) { + //remember that we sent this request. + this.outstandingRequests.add(serial); + const doNewRequest = () => { + this.outstandingRequests.delete(serial); + this.newRequest_(); + }; + // If this request doesn't return on its own accord (by the server sending us some data), we'll + // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open. + const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL)); + const readyStateCB = () => { + // Request completed. Cancel the keepalive. + clearTimeout(keepaliveTimeout); + // Trigger a new request so we can continue receiving data. + doNewRequest(); + }; + this.addTag(url, readyStateCB); + } + /** + * Add an arbitrary script tag to the iframe. + * @param url - The URL for the script tag source. + * @param loadCB - A callback to be triggered once the script has loaded. + */ + addTag(url, loadCB) { + if (util.isNodeSdk()) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.doNodeLongPoll(url, loadCB); + } + else { + setTimeout(() => { + try { + // if we're already closed, don't add this poll + if (!this.sendNewPolls) { + return; + } + const newScript = this.myIFrame.doc.createElement('script'); + newScript.type = 'text/javascript'; + newScript.async = true; + newScript.src = url; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + newScript.onload = newScript.onreadystatechange = + function () { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const rstate = newScript.readyState; + if (!rstate || rstate === 'loaded' || rstate === 'complete') { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + newScript.onload = newScript.onreadystatechange = null; + if (newScript.parentNode) { + newScript.parentNode.removeChild(newScript); + } + loadCB(); + } + }; + newScript.onerror = () => { + log('Long-poll script failed to load: ' + url); + this.sendNewPolls = false; + this.close(); + }; + this.myIFrame.doc.body.appendChild(newScript); + } + catch (e) { + // TODO: we should make this error visible somehow + } + }, Math.floor(1)); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Currently simplistic, this class manages what transport a Connection should use at various stages of its + * lifecycle. + * + * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if + * they are available. + */ +class TransportManager { + static get ALL_TRANSPORTS() { + return [BrowserPollConnection, WebSocketConnection]; + } + /** + * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after + * TransportManager has already set up transports_ + */ + static get IS_TRANSPORT_INITIALIZED() { + return this.globalTransportInitialized_; + } + /** + * @param repoInfo - Metadata around the namespace we're connecting to + */ + constructor(repoInfo) { + this.initTransports_(repoInfo); + } + initTransports_(repoInfo) { + const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable'](); + let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed(); + if (repoInfo.webSocketOnly) { + if (!isWebSocketsAvailable) { + warn$1("wss:// URL used, but browser isn't known to support websockets. Trying anyway."); + } + isSkipPollConnection = true; + } + if (isSkipPollConnection) { + this.transports_ = [WebSocketConnection]; + } + else { + const transports = (this.transports_ = []); + for (const transport of TransportManager.ALL_TRANSPORTS) { + if (transport && transport['isAvailable']()) { + transports.push(transport); + } + } + TransportManager.globalTransportInitialized_ = true; + } + } + /** + * @returns The constructor for the initial transport to use + */ + initialTransport() { + if (this.transports_.length > 0) { + return this.transports_[0]; + } + else { + throw new Error('No transports available'); + } + } + /** + * @returns The constructor for the next transport, or null + */ + upgradeTransport() { + if (this.transports_.length > 1) { + return this.transports_[1]; + } + else { + return null; + } + } +} +// Keeps track of whether the TransportManager has already chosen a transport to use +TransportManager.globalTransportInitialized_ = false; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Abort upgrade attempt if it takes longer than 60s. +const UPGRADE_TIMEOUT = 60000; +// For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses. +// If we haven't sent enough requests within 5s, we'll start sending noop ping requests. +const DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000; +// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data) +// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout +// but we've sent/received enough bytes, we don't cancel the connection. +const BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024; +const BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024; +const MESSAGE_TYPE = 't'; +const MESSAGE_DATA = 'd'; +const CONTROL_SHUTDOWN = 's'; +const CONTROL_RESET = 'r'; +const CONTROL_ERROR = 'e'; +const CONTROL_PONG = 'o'; +const SWITCH_ACK = 'a'; +const END_TRANSMISSION = 'n'; +const PING = 'p'; +const SERVER_HELLO = 'h'; +/** + * Creates a new real-time connection to the server using whichever method works + * best in the current browser. + */ +class Connection { + /** + * @param id - an id for this connection + * @param repoInfo_ - the info for the endpoint to connect to + * @param applicationId_ - the Firebase App ID for this project + * @param appCheckToken_ - The App Check Token for this device. + * @param authToken_ - The auth token for this session. + * @param onMessage_ - the callback to be triggered when a server-push message arrives + * @param onReady_ - the callback to be triggered when this connection is ready to send messages. + * @param onDisconnect_ - the callback to be triggered when a connection was lost + * @param onKill_ - the callback to be triggered when this connection has permanently shut down. + * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server + */ + constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) { + this.id = id; + this.repoInfo_ = repoInfo_; + this.applicationId_ = applicationId_; + this.appCheckToken_ = appCheckToken_; + this.authToken_ = authToken_; + this.onMessage_ = onMessage_; + this.onReady_ = onReady_; + this.onDisconnect_ = onDisconnect_; + this.onKill_ = onKill_; + this.lastSessionId = lastSessionId; + this.connectionCount = 0; + this.pendingDataMessages = []; + this.state_ = 0 /* RealtimeState.CONNECTING */; + this.log_ = logWrapper('c:' + this.id + ':'); + this.transportManager_ = new TransportManager(repoInfo_); + this.log_('Connection created'); + this.start_(); + } + /** + * Starts a connection attempt + */ + start_() { + const conn = this.transportManager_.initialTransport(); + this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId); + // For certain transports (WebSockets), we need to send and receive several messages back and forth before we + // can consider the transport healthy. + this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0; + const onMessageReceived = this.connReceiver_(this.conn_); + const onConnectionLost = this.disconnReceiver_(this.conn_); + this.tx_ = this.conn_; + this.rx_ = this.conn_; + this.secondaryConn_ = null; + this.isHealthy_ = false; + /* + * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame. + * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset. + * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should + * still have the context of your originating frame. + */ + setTimeout(() => { + // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it + this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost); + }, Math.floor(0)); + const healthyTimeoutMS = conn['healthyTimeout'] || 0; + if (healthyTimeoutMS > 0) { + this.healthyTimeout_ = setTimeoutNonBlocking(() => { + this.healthyTimeout_ = null; + if (!this.isHealthy_) { + if (this.conn_ && + this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) { + this.log_('Connection exceeded healthy timeout but has received ' + + this.conn_.bytesReceived + + ' bytes. Marking connection healthy.'); + this.isHealthy_ = true; + this.conn_.markConnectionHealthy(); + } + else if (this.conn_ && + this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) { + this.log_('Connection exceeded healthy timeout but has sent ' + + this.conn_.bytesSent + + ' bytes. Leaving connection alive.'); + // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to + // the server. + } + else { + this.log_('Closing unhealthy connection after timeout.'); + this.close(); + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(healthyTimeoutMS)); + } + } + nextTransportId_() { + return 'c:' + this.id + ':' + this.connectionCount++; + } + disconnReceiver_(conn) { + return everConnected => { + if (conn === this.conn_) { + this.onConnectionLost_(everConnected); + } + else if (conn === this.secondaryConn_) { + this.log_('Secondary connection lost.'); + this.onSecondaryConnectionLost_(); + } + else { + this.log_('closing an old connection'); + } + }; + } + connReceiver_(conn) { + return (message) => { + if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) { + if (conn === this.rx_) { + this.onPrimaryMessageReceived_(message); + } + else if (conn === this.secondaryConn_) { + this.onSecondaryMessageReceived_(message); + } + else { + this.log_('message on old connection'); + } + } + }; + } + /** + * @param dataMsg - An arbitrary data message to be sent to the server + */ + sendRequest(dataMsg) { + // wrap in a data message envelope and send it on + const msg = { t: 'd', d: dataMsg }; + this.sendData_(msg); + } + tryCleanupConnection() { + if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) { + this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId); + this.conn_ = this.secondaryConn_; + this.secondaryConn_ = null; + // the server will shutdown the old connection + } + } + onSecondaryControl_(controlData) { + if (MESSAGE_TYPE in controlData) { + const cmd = controlData[MESSAGE_TYPE]; + if (cmd === SWITCH_ACK) { + this.upgradeIfSecondaryHealthy_(); + } + else if (cmd === CONTROL_RESET) { + // Most likely the session wasn't valid. Abandon the switch attempt + this.log_('Got a reset on secondary, closing it'); + this.secondaryConn_.close(); + // If we were already using this connection for something, than we need to fully close + if (this.tx_ === this.secondaryConn_ || + this.rx_ === this.secondaryConn_) { + this.close(); + } + } + else if (cmd === CONTROL_PONG) { + this.log_('got pong on secondary.'); + this.secondaryResponsesRequired_--; + this.upgradeIfSecondaryHealthy_(); + } + } + } + onSecondaryMessageReceived_(parsedData) { + const layer = requireKey('t', parsedData); + const data = requireKey('d', parsedData); + if (layer === 'c') { + this.onSecondaryControl_(data); + } + else if (layer === 'd') { + // got a data message, but we're still second connection. Need to buffer it up + this.pendingDataMessages.push(data); + } + else { + throw new Error('Unknown protocol layer: ' + layer); + } + } + upgradeIfSecondaryHealthy_() { + if (this.secondaryResponsesRequired_ <= 0) { + this.log_('Secondary connection is healthy.'); + this.isHealthy_ = true; + this.secondaryConn_.markConnectionHealthy(); + this.proceedWithUpgrade_(); + } + else { + // Send a ping to make sure the connection is healthy. + this.log_('sending ping on secondary.'); + this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } }); + } + } + proceedWithUpgrade_() { + // tell this connection to consider itself open + this.secondaryConn_.start(); + // send ack + this.log_('sending client ack on secondary'); + this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } }); + // send end packet on primary transport, switch to sending on this one + // can receive on this one, buffer responses until end received on primary transport + this.log_('Ending transmission on primary'); + this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } }); + this.tx_ = this.secondaryConn_; + this.tryCleanupConnection(); + } + onPrimaryMessageReceived_(parsedData) { + // Must refer to parsedData properties in quotes, so closure doesn't touch them. + const layer = requireKey('t', parsedData); + const data = requireKey('d', parsedData); + if (layer === 'c') { + this.onControl_(data); + } + else if (layer === 'd') { + this.onDataMessage_(data); + } + } + onDataMessage_(message) { + this.onPrimaryResponse_(); + // We don't do anything with data messages, just kick them up a level + this.onMessage_(message); + } + onPrimaryResponse_() { + if (!this.isHealthy_) { + this.primaryResponsesRequired_--; + if (this.primaryResponsesRequired_ <= 0) { + this.log_('Primary connection is healthy.'); + this.isHealthy_ = true; + this.conn_.markConnectionHealthy(); + } + } + } + onControl_(controlData) { + const cmd = requireKey(MESSAGE_TYPE, controlData); + if (MESSAGE_DATA in controlData) { + const payload = controlData[MESSAGE_DATA]; + if (cmd === SERVER_HELLO) { + const handshakePayload = { + ...payload + }; + if (this.repoInfo_.isUsingEmulator) { + // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes. + handshakePayload.h = this.repoInfo_.host; + } + this.onHandshake_(handshakePayload); + } + else if (cmd === END_TRANSMISSION) { + this.log_('recvd end transmission on primary'); + this.rx_ = this.secondaryConn_; + for (let i = 0; i < this.pendingDataMessages.length; ++i) { + this.onDataMessage_(this.pendingDataMessages[i]); + } + this.pendingDataMessages = []; + this.tryCleanupConnection(); + } + else if (cmd === CONTROL_SHUTDOWN) { + // This was previously the 'onKill' callback passed to the lower-level connection + // payload in this case is the reason for the shutdown. Generally a human-readable error + this.onConnectionShutdown_(payload); + } + else if (cmd === CONTROL_RESET) { + // payload in this case is the host we should contact + this.onReset_(payload); + } + else if (cmd === CONTROL_ERROR) { + error('Server Error: ' + payload); + } + else if (cmd === CONTROL_PONG) { + this.log_('got pong on primary.'); + this.onPrimaryResponse_(); + this.sendPingOnPrimaryIfNecessary_(); + } + else { + error('Unknown control packet command: ' + cmd); + } + } + } + /** + * @param handshake - The handshake data returned from the server + */ + onHandshake_(handshake) { + const timestamp = handshake.ts; + const version = handshake.v; + const host = handshake.h; + this.sessionId = handshake.s; + this.repoInfo_.host = host; + // if we've already closed the connection, then don't bother trying to progress further + if (this.state_ === 0 /* RealtimeState.CONNECTING */) { + this.conn_.start(); + this.onConnectionEstablished_(this.conn_, timestamp); + if (PROTOCOL_VERSION !== version) { + warn$1('Protocol version mismatch detected'); + } + // TODO: do we want to upgrade? when? maybe a delay? + this.tryStartUpgrade_(); + } + } + tryStartUpgrade_() { + const conn = this.transportManager_.upgradeTransport(); + if (conn) { + this.startUpgrade_(conn); + } + } + startUpgrade_(conn) { + this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId); + // For certain transports (WebSockets), we need to send and receive several messages back and forth before we + // can consider the transport healthy. + this.secondaryResponsesRequired_ = + conn['responsesRequiredToBeHealthy'] || 0; + const onMessage = this.connReceiver_(this.secondaryConn_); + const onDisconnect = this.disconnReceiver_(this.secondaryConn_); + this.secondaryConn_.open(onMessage, onDisconnect); + // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary. + setTimeoutNonBlocking(() => { + if (this.secondaryConn_) { + this.log_('Timed out trying to upgrade.'); + this.secondaryConn_.close(); + } + }, Math.floor(UPGRADE_TIMEOUT)); + } + onReset_(host) { + this.log_('Reset packet received. New host: ' + host); + this.repoInfo_.host = host; + // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up. + // We don't currently support resets after the connection has already been established + if (this.state_ === 1 /* RealtimeState.CONNECTED */) { + this.close(); + } + else { + // Close whatever connections we have open and start again. + this.closeConnections_(); + this.start_(); + } + } + onConnectionEstablished_(conn, timestamp) { + this.log_('Realtime connection established.'); + this.conn_ = conn; + this.state_ = 1 /* RealtimeState.CONNECTED */; + if (this.onReady_) { + this.onReady_(timestamp, this.sessionId); + this.onReady_ = null; + } + // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy, + // send some pings. + if (this.primaryResponsesRequired_ === 0) { + this.log_('Primary connection is healthy.'); + this.isHealthy_ = true; + } + else { + setTimeoutNonBlocking(() => { + this.sendPingOnPrimaryIfNecessary_(); + }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS)); + } + } + sendPingOnPrimaryIfNecessary_() { + // If the connection isn't considered healthy yet, we'll send a noop ping packet request. + if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) { + this.log_('sending ping on primary.'); + this.sendData_({ t: 'c', d: { t: PING, d: {} } }); + } + } + onSecondaryConnectionLost_() { + const conn = this.secondaryConn_; + this.secondaryConn_ = null; + if (this.tx_ === conn || this.rx_ === conn) { + // we are relying on this connection already in some capacity. Therefore, a failure is real + this.close(); + } + } + /** + * @param everConnected - Whether or not the connection ever reached a server. Used to determine if + * we should flush the host cache + */ + onConnectionLost_(everConnected) { + this.conn_ = null; + // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting + // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess. + if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) { + this.log_('Realtime connection failed.'); + // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away + if (this.repoInfo_.isCacheableHost()) { + PersistentStorage.remove('host:' + this.repoInfo_.host); + // reset the internal host to what we would show the user, i.e. .firebaseio.com + this.repoInfo_.internalHost = this.repoInfo_.host; + } + } + else if (this.state_ === 1 /* RealtimeState.CONNECTED */) { + this.log_('Realtime connection lost.'); + } + this.close(); + } + onConnectionShutdown_(reason) { + this.log_('Connection shutdown command received. Shutting down...'); + if (this.onKill_) { + this.onKill_(reason); + this.onKill_ = null; + } + // We intentionally don't want to fire onDisconnect (kill is a different case), + // so clear the callback. + this.onDisconnect_ = null; + this.close(); + } + sendData_(data) { + if (this.state_ !== 1 /* RealtimeState.CONNECTED */) { + throw 'Connection is not connected'; + } + else { + this.tx_.send(data); + } + } + /** + * Cleans up this connection, calling the appropriate callbacks + */ + close() { + if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) { + this.log_('Closing realtime connection.'); + this.state_ = 2 /* RealtimeState.DISCONNECTED */; + this.closeConnections_(); + if (this.onDisconnect_) { + this.onDisconnect_(); + this.onDisconnect_ = null; + } + } + } + closeConnections_() { + this.log_('Shutting down all connections'); + if (this.conn_) { + this.conn_.close(); + this.conn_ = null; + } + if (this.secondaryConn_) { + this.secondaryConn_.close(); + this.secondaryConn_ = null; + } + if (this.healthyTimeout_) { + clearTimeout(this.healthyTimeout_); + this.healthyTimeout_ = null; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Interface defining the set of actions that can be performed against the Firebase server + * (basically corresponds to our wire protocol). + * + * @interface + */ +class ServerActions { + put(pathString, data, onComplete, hash) { } + merge(pathString, data, onComplete, hash) { } + /** + * Refreshes the auth token for the current connection. + * @param token - The authentication token + */ + refreshAuthToken(token) { } + /** + * Refreshes the app check token for the current connection. + * @param token The app check token + */ + refreshAppCheckToken(token) { } + onDisconnectPut(pathString, data, onComplete) { } + onDisconnectMerge(pathString, data, onComplete) { } + onDisconnectCancel(pathString, onComplete) { } + reportStats(stats) { } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Base class to be used if you want to emit events. Call the constructor with + * the set of allowed event names. + */ +class EventEmitter { + constructor(allowedEvents_) { + this.allowedEvents_ = allowedEvents_; + this.listeners_ = {}; + util.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array'); + } + /** + * To be called by derived classes to trigger events. + */ + trigger(eventType, ...varArgs) { + if (Array.isArray(this.listeners_[eventType])) { + // Clone the list, since callbacks could add/remove listeners. + const listeners = [...this.listeners_[eventType]]; + for (let i = 0; i < listeners.length; i++) { + listeners[i].callback.apply(listeners[i].context, varArgs); + } + } + } + on(eventType, callback, context) { + this.validateEventType_(eventType); + this.listeners_[eventType] = this.listeners_[eventType] || []; + this.listeners_[eventType].push({ callback, context }); + const eventData = this.getInitialEvent(eventType); + if (eventData) { + callback.apply(context, eventData); + } + } + off(eventType, callback, context) { + this.validateEventType_(eventType); + const listeners = this.listeners_[eventType] || []; + for (let i = 0; i < listeners.length; i++) { + if (listeners[i].callback === callback && + (!context || context === listeners[i].context)) { + listeners.splice(i, 1); + return; + } + } + } + validateEventType_(eventType) { + util.assert(this.allowedEvents_.find(et => { + return et === eventType; + }), 'Unknown event: ' + eventType); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Monitors online state (as reported by window.online/offline events). + * + * The expectation is that this could have many false positives (thinks we are online + * when we're not), but no false negatives. So we can safely use it to determine when + * we definitely cannot reach the internet. + */ +class OnlineMonitor extends EventEmitter { + static getInstance() { + return new OnlineMonitor(); + } + constructor() { + super(['online']); + this.online_ = true; + // We've had repeated complaints that Cordova apps can get stuck "offline", e.g. + // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810 + // It would seem that the 'online' event does not always fire consistently. So we disable it + // for Cordova. + if (typeof window !== 'undefined' && + typeof window.addEventListener !== 'undefined' && + !util.isMobileCordova()) { + window.addEventListener('online', () => { + if (!this.online_) { + this.online_ = true; + this.trigger('online', true); + } + }, false); + window.addEventListener('offline', () => { + if (this.online_) { + this.online_ = false; + this.trigger('online', false); + } + }, false); + } + } + getInitialEvent(eventType) { + util.assert(eventType === 'online', 'Unknown event type: ' + eventType); + return [this.online_]; + } + currentlyOnline() { + return this.online_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Maximum key depth. */ +const MAX_PATH_DEPTH = 32; +/** Maximum number of (UTF8) bytes in a Firebase path. */ +const MAX_PATH_LENGTH_BYTES = 768; +/** + * An immutable object representing a parsed path. It's immutable so that you + * can pass them around to other functions without worrying about them changing + * it. + */ +class Path { + /** + * @param pathOrString - Path string to parse, or another path, or the raw + * tokens array + */ + constructor(pathOrString, pieceNum) { + if (pieceNum === void 0) { + this.pieces_ = pathOrString.split('/'); + // Remove empty pieces. + let copyTo = 0; + for (let i = 0; i < this.pieces_.length; i++) { + if (this.pieces_[i].length > 0) { + this.pieces_[copyTo] = this.pieces_[i]; + copyTo++; + } + } + this.pieces_.length = copyTo; + this.pieceNum_ = 0; + } + else { + this.pieces_ = pathOrString; + this.pieceNum_ = pieceNum; + } + } + toString() { + let pathString = ''; + for (let i = this.pieceNum_; i < this.pieces_.length; i++) { + if (this.pieces_[i] !== '') { + pathString += '/' + this.pieces_[i]; + } + } + return pathString || '/'; + } +} +function newEmptyPath() { + return new Path(''); +} +function pathGetFront(path) { + if (path.pieceNum_ >= path.pieces_.length) { + return null; + } + return path.pieces_[path.pieceNum_]; +} +/** + * @returns The number of segments in this path + */ +function pathGetLength(path) { + return path.pieces_.length - path.pieceNum_; +} +function pathPopFront(path) { + let pieceNum = path.pieceNum_; + if (pieceNum < path.pieces_.length) { + pieceNum++; + } + return new Path(path.pieces_, pieceNum); +} +function pathGetBack(path) { + if (path.pieceNum_ < path.pieces_.length) { + return path.pieces_[path.pieces_.length - 1]; + } + return null; +} +function pathToUrlEncodedString(path) { + let pathString = ''; + for (let i = path.pieceNum_; i < path.pieces_.length; i++) { + if (path.pieces_[i] !== '') { + pathString += '/' + encodeURIComponent(String(path.pieces_[i])); + } + } + return pathString || '/'; +} +/** + * Shallow copy of the parts of the path. + * + */ +function pathSlice(path, begin = 0) { + return path.pieces_.slice(path.pieceNum_ + begin); +} +function pathParent(path) { + if (path.pieceNum_ >= path.pieces_.length) { + return null; + } + const pieces = []; + for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) { + pieces.push(path.pieces_[i]); + } + return new Path(pieces, 0); +} +function pathChild(path, childPathObj) { + const pieces = []; + for (let i = path.pieceNum_; i < path.pieces_.length; i++) { + pieces.push(path.pieces_[i]); + } + if (childPathObj instanceof Path) { + for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) { + pieces.push(childPathObj.pieces_[i]); + } + } + else { + const childPieces = childPathObj.split('/'); + for (let i = 0; i < childPieces.length; i++) { + if (childPieces[i].length > 0) { + pieces.push(childPieces[i]); + } + } + } + return new Path(pieces, 0); +} +/** + * @returns True if there are no segments in this path + */ +function pathIsEmpty(path) { + return path.pieceNum_ >= path.pieces_.length; +} +/** + * @returns The path from outerPath to innerPath + */ +function newRelativePath(outerPath, innerPath) { + const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath); + if (outer === null) { + return innerPath; + } + else if (outer === inner) { + return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath)); + } + else { + throw new Error('INTERNAL ERROR: innerPath (' + + innerPath + + ') is not within ' + + 'outerPath (' + + outerPath + + ')'); + } +} +/** + * @returns -1, 0, 1 if left is less, equal, or greater than the right. + */ +function pathCompare(left, right) { + const leftKeys = pathSlice(left, 0); + const rightKeys = pathSlice(right, 0); + for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) { + const cmp = nameCompare(leftKeys[i], rightKeys[i]); + if (cmp !== 0) { + return cmp; + } + } + if (leftKeys.length === rightKeys.length) { + return 0; + } + return leftKeys.length < rightKeys.length ? -1 : 1; +} +/** + * @returns true if paths are the same. + */ +function pathEquals(path, other) { + if (pathGetLength(path) !== pathGetLength(other)) { + return false; + } + for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) { + if (path.pieces_[i] !== other.pieces_[j]) { + return false; + } + } + return true; +} +/** + * @returns True if this path is a parent of (or the same as) other + */ +function pathContains(path, other) { + let i = path.pieceNum_; + let j = other.pieceNum_; + if (pathGetLength(path) > pathGetLength(other)) { + return false; + } + while (i < path.pieces_.length) { + if (path.pieces_[i] !== other.pieces_[j]) { + return false; + } + ++i; + ++j; + } + return true; +} +/** + * Dynamic (mutable) path used to count path lengths. + * + * This class is used to efficiently check paths for valid + * length (in UTF8 bytes) and depth (used in path validation). + * + * Throws Error exception if path is ever invalid. + * + * The definition of a path always begins with '/'. + */ +class ValidationPath { + /** + * @param path - Initial Path. + * @param errorPrefix_ - Prefix for any error messages. + */ + constructor(path, errorPrefix_) { + this.errorPrefix_ = errorPrefix_; + this.parts_ = pathSlice(path, 0); + /** Initialize to number of '/' chars needed in path. */ + this.byteLength_ = Math.max(1, this.parts_.length); + for (let i = 0; i < this.parts_.length; i++) { + this.byteLength_ += util.stringLength(this.parts_[i]); + } + validationPathCheckValid(this); + } +} +function validationPathPush(validationPath, child) { + // Count the needed '/' + if (validationPath.parts_.length > 0) { + validationPath.byteLength_ += 1; + } + validationPath.parts_.push(child); + validationPath.byteLength_ += util.stringLength(child); + validationPathCheckValid(validationPath); +} +function validationPathPop(validationPath) { + const last = validationPath.parts_.pop(); + validationPath.byteLength_ -= util.stringLength(last); + // Un-count the previous '/' + if (validationPath.parts_.length > 0) { + validationPath.byteLength_ -= 1; + } +} +function validationPathCheckValid(validationPath) { + if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) { + throw new Error(validationPath.errorPrefix_ + + 'has a key path longer than ' + + MAX_PATH_LENGTH_BYTES + + ' bytes (' + + validationPath.byteLength_ + + ').'); + } + if (validationPath.parts_.length > MAX_PATH_DEPTH) { + throw new Error(validationPath.errorPrefix_ + + 'path specified exceeds the maximum depth that can be written (' + + MAX_PATH_DEPTH + + ') or object contains a cycle ' + + validationPathToErrorString(validationPath)); + } +} +/** + * String for use in error messages - uses '.' notation for path. + */ +function validationPathToErrorString(validationPath) { + if (validationPath.parts_.length === 0) { + return ''; + } + return "in property '" + validationPath.parts_.join('.') + "'"; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class VisibilityMonitor extends EventEmitter { + static getInstance() { + return new VisibilityMonitor(); + } + constructor() { + super(['visible']); + let hidden; + let visibilityChange; + if (typeof document !== 'undefined' && + typeof document.addEventListener !== 'undefined') { + if (typeof document['hidden'] !== 'undefined') { + // Opera 12.10 and Firefox 18 and later support + visibilityChange = 'visibilitychange'; + hidden = 'hidden'; + } + else if (typeof document['mozHidden'] !== 'undefined') { + visibilityChange = 'mozvisibilitychange'; + hidden = 'mozHidden'; + } + else if (typeof document['msHidden'] !== 'undefined') { + visibilityChange = 'msvisibilitychange'; + hidden = 'msHidden'; + } + else if (typeof document['webkitHidden'] !== 'undefined') { + visibilityChange = 'webkitvisibilitychange'; + hidden = 'webkitHidden'; + } + } + // Initially, we always assume we are visible. This ensures that in browsers + // without page visibility support or in cases where we are never visible + // (e.g. chrome extension), we act as if we are visible, i.e. don't delay + // reconnects + this.visible_ = true; + if (visibilityChange) { + document.addEventListener(visibilityChange, () => { + const visible = !document[hidden]; + if (visible !== this.visible_) { + this.visible_ = visible; + this.trigger('visible', visible); + } + }, false); + } + } + getInitialEvent(eventType) { + util.assert(eventType === 'visible', 'Unknown event type: ' + eventType); + return [this.visible_]; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const RECONNECT_MIN_DELAY = 1000; +const RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858) +const RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server) +const RECONNECT_DELAY_MULTIPLIER = 1.3; +const RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec. +const SERVER_KILL_INTERRUPT_REASON = 'server_kill'; +// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off. +const INVALID_TOKEN_THRESHOLD = 3; +/** + * Firebase connection. Abstracts wire protocol and handles reconnecting. + * + * NOTE: All JSON objects sent to the realtime connection must have property names enclosed + * in quotes to make sure the closure compiler does not minify them. + */ +class PersistentConnection extends ServerActions { + /** + * @param repoInfo_ - Data about the namespace we are connecting to + * @param applicationId_ - The Firebase App ID for this project + * @param onDataUpdate_ - A callback for new data from the server + */ + constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) { + super(); + this.repoInfo_ = repoInfo_; + this.applicationId_ = applicationId_; + this.onDataUpdate_ = onDataUpdate_; + this.onConnectStatus_ = onConnectStatus_; + this.onServerInfoUpdate_ = onServerInfoUpdate_; + this.authTokenProvider_ = authTokenProvider_; + this.appCheckTokenProvider_ = appCheckTokenProvider_; + this.authOverride_ = authOverride_; + // Used for diagnostic logging. + this.id = PersistentConnection.nextPersistentConnectionId_++; + this.log_ = logWrapper('p:' + this.id + ':'); + this.interruptReasons_ = {}; + this.listens = new Map(); + this.outstandingPuts_ = []; + this.outstandingGets_ = []; + this.outstandingPutCount_ = 0; + this.outstandingGetCount_ = 0; + this.onDisconnectRequestQueue_ = []; + this.connected_ = false; + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT; + this.securityDebugCallback_ = null; + this.lastSessionId = null; + this.establishConnectionTimer_ = null; + this.visible_ = false; + // Before we get connected, we keep a queue of pending messages to send. + this.requestCBHash_ = {}; + this.requestNumber_ = 0; + this.realtime_ = null; + this.authToken_ = null; + this.appCheckToken_ = null; + this.forceTokenRefresh_ = false; + this.invalidAuthTokenCount_ = 0; + this.invalidAppCheckTokenCount_ = 0; + this.firstConnection_ = true; + this.lastConnectionAttemptTime_ = null; + this.lastConnectionEstablishedTime_ = null; + if (authOverride_ && !util.isNodeSdk()) { + throw new Error('Auth override specified in options, but not supported on non Node.js platforms'); + } + VisibilityMonitor.getInstance().on('visible', this.onVisible_, this); + if (repoInfo_.host.indexOf('fblocal') === -1) { + OnlineMonitor.getInstance().on('online', this.onOnline_, this); + } + } + sendRequest(action, body, onResponse) { + const curReqNum = ++this.requestNumber_; + const msg = { r: curReqNum, a: action, b: body }; + this.log_(util.stringify(msg)); + util.assert(this.connected_, "sendRequest call when we're not connected not allowed."); + this.realtime_.sendRequest(msg); + if (onResponse) { + this.requestCBHash_[curReqNum] = onResponse; + } + } + get(query) { + this.initConnection_(); + const deferred = new util.Deferred(); + const request = { + p: query._path.toString(), + q: query._queryObject + }; + const outstandingGet = { + action: 'g', + request, + onComplete: (message) => { + const payload = message['d']; + if (message['s'] === 'ok') { + deferred.resolve(payload); + } + else { + deferred.reject(payload); + } + } + }; + this.outstandingGets_.push(outstandingGet); + this.outstandingGetCount_++; + const index = this.outstandingGets_.length - 1; + if (this.connected_) { + this.sendGet_(index); + } + return deferred.promise; + } + listen(query, currentHashFn, tag, onComplete) { + this.initConnection_(); + const queryId = query._queryIdentifier; + const pathString = query._path.toString(); + this.log_('Listen called for ' + pathString + ' ' + queryId); + if (!this.listens.has(pathString)) { + this.listens.set(pathString, new Map()); + } + util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query'); + util.assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`); + const listenSpec = { + onComplete, + hashFn: currentHashFn, + query, + tag + }; + this.listens.get(pathString).set(queryId, listenSpec); + if (this.connected_) { + this.sendListen_(listenSpec); + } + } + sendGet_(index) { + const get = this.outstandingGets_[index]; + this.sendRequest('g', get.request, (message) => { + delete this.outstandingGets_[index]; + this.outstandingGetCount_--; + if (this.outstandingGetCount_ === 0) { + this.outstandingGets_ = []; + } + if (get.onComplete) { + get.onComplete(message); + } + }); + } + sendListen_(listenSpec) { + const query = listenSpec.query; + const pathString = query._path.toString(); + const queryId = query._queryIdentifier; + this.log_('Listen on ' + pathString + ' for ' + queryId); + const req = { /*path*/ p: pathString }; + const action = 'q'; + // Only bother to send query if it's non-default. + if (listenSpec.tag) { + req['q'] = query._queryObject; + req['t'] = listenSpec.tag; + } + req[ /*hash*/'h'] = listenSpec.hashFn(); + this.sendRequest(action, req, (message) => { + const payload = message[ /*data*/'d']; + const status = message[ /*status*/'s']; + // print warnings in any case... + PersistentConnection.warnOnListenWarnings_(payload, query); + const currentListenSpec = this.listens.get(pathString) && + this.listens.get(pathString).get(queryId); + // only trigger actions if the listen hasn't been removed and readded + if (currentListenSpec === listenSpec) { + this.log_('listen response', message); + if (status !== 'ok') { + this.removeListen_(pathString, queryId); + } + if (listenSpec.onComplete) { + listenSpec.onComplete(status, payload); + } + } + }); + } + static warnOnListenWarnings_(payload, query) { + if (payload && typeof payload === 'object' && util.contains(payload, 'w')) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const warnings = util.safeGet(payload, 'w'); + if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) { + const indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"'; + const indexPath = query._path.toString(); + warn$1(`Using an unspecified index. Your data will be downloaded and ` + + `filtered on the client. Consider adding ${indexSpec} at ` + + `${indexPath} to your security rules for better performance.`); + } + } + } + refreshAuthToken(token) { + this.authToken_ = token; + this.log_('Auth token refreshed'); + if (this.authToken_) { + this.tryAuth(); + } + else { + //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete + //the credential so we dont become authenticated next time we connect. + if (this.connected_) { + this.sendRequest('unauth', {}, () => { }); + } + } + this.reduceReconnectDelayIfAdminCredential_(token); + } + reduceReconnectDelayIfAdminCredential_(credential) { + // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client). + // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires. + const isFirebaseSecret = credential && credential.length === 40; + if (isFirebaseSecret || util.isAdmin(credential)) { + this.log_('Admin auth credential detected. Reducing max reconnect time.'); + this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS; + } + } + refreshAppCheckToken(token) { + this.appCheckToken_ = token; + this.log_('App check token refreshed'); + if (this.appCheckToken_) { + this.tryAppCheck(); + } + else { + //If we're connected we want to let the server know to unauthenticate us. + //If we're not connected, simply delete the credential so we dont become + // authenticated next time we connect. + if (this.connected_) { + this.sendRequest('unappeck', {}, () => { }); + } + } + } + /** + * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like + * a auth revoked (the connection is closed). + */ + tryAuth() { + if (this.connected_ && this.authToken_) { + const token = this.authToken_; + const authMethod = util.isValidFormat(token) ? 'auth' : 'gauth'; + const requestData = { cred: token }; + if (this.authOverride_ === null) { + requestData['noauth'] = true; + } + else if (typeof this.authOverride_ === 'object') { + requestData['authvar'] = this.authOverride_; + } + this.sendRequest(authMethod, requestData, (res) => { + const status = res[ /*status*/'s']; + const data = res[ /*data*/'d'] || 'error'; + if (this.authToken_ === token) { + if (status === 'ok') { + this.invalidAuthTokenCount_ = 0; + } + else { + // Triggers reconnect and force refresh for auth token + this.onAuthRevoked_(status, data); + } + } + }); + } + } + /** + * Attempts to authenticate with the given token. If the authentication + * attempt fails, it's triggered like the token was revoked (the connection is + * closed). + */ + tryAppCheck() { + if (this.connected_ && this.appCheckToken_) { + this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => { + const status = res[ /*status*/'s']; + const data = res[ /*data*/'d'] || 'error'; + if (status === 'ok') { + this.invalidAppCheckTokenCount_ = 0; + } + else { + this.onAppCheckRevoked_(status, data); + } + }); + } + } + /** + * @inheritDoc + */ + unlisten(query, tag) { + const pathString = query._path.toString(); + const queryId = query._queryIdentifier; + this.log_('Unlisten called for ' + pathString + ' ' + queryId); + util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query'); + const listen = this.removeListen_(pathString, queryId); + if (listen && this.connected_) { + this.sendUnlisten_(pathString, queryId, query._queryObject, tag); + } + } + sendUnlisten_(pathString, queryId, queryObj, tag) { + this.log_('Unlisten on ' + pathString + ' for ' + queryId); + const req = { /*path*/ p: pathString }; + const action = 'n'; + // Only bother sending queryId if it's non-default. + if (tag) { + req['q'] = queryObj; + req['t'] = tag; + } + this.sendRequest(action, req); + } + onDisconnectPut(pathString, data, onComplete) { + this.initConnection_(); + if (this.connected_) { + this.sendOnDisconnect_('o', pathString, data, onComplete); + } + else { + this.onDisconnectRequestQueue_.push({ + pathString, + action: 'o', + data, + onComplete + }); + } + } + onDisconnectMerge(pathString, data, onComplete) { + this.initConnection_(); + if (this.connected_) { + this.sendOnDisconnect_('om', pathString, data, onComplete); + } + else { + this.onDisconnectRequestQueue_.push({ + pathString, + action: 'om', + data, + onComplete + }); + } + } + onDisconnectCancel(pathString, onComplete) { + this.initConnection_(); + if (this.connected_) { + this.sendOnDisconnect_('oc', pathString, null, onComplete); + } + else { + this.onDisconnectRequestQueue_.push({ + pathString, + action: 'oc', + data: null, + onComplete + }); + } + } + sendOnDisconnect_(action, pathString, data, onComplete) { + const request = { /*path*/ p: pathString, /*data*/ d: data }; + this.log_('onDisconnect ' + action, request); + this.sendRequest(action, request, (response) => { + if (onComplete) { + setTimeout(() => { + onComplete(response[ /*status*/'s'], response[ /* data */'d']); + }, Math.floor(0)); + } + }); + } + put(pathString, data, onComplete, hash) { + this.putInternal('p', pathString, data, onComplete, hash); + } + merge(pathString, data, onComplete, hash) { + this.putInternal('m', pathString, data, onComplete, hash); + } + putInternal(action, pathString, data, onComplete, hash) { + this.initConnection_(); + const request = { + /*path*/ p: pathString, + /*data*/ d: data + }; + if (hash !== undefined) { + request[ /*hash*/'h'] = hash; + } + // TODO: Only keep track of the most recent put for a given path? + this.outstandingPuts_.push({ + action, + request, + onComplete + }); + this.outstandingPutCount_++; + const index = this.outstandingPuts_.length - 1; + if (this.connected_) { + this.sendPut_(index); + } + else { + this.log_('Buffering put: ' + pathString); + } + } + sendPut_(index) { + const action = this.outstandingPuts_[index].action; + const request = this.outstandingPuts_[index].request; + const onComplete = this.outstandingPuts_[index].onComplete; + this.outstandingPuts_[index].queued = this.connected_; + this.sendRequest(action, request, (message) => { + this.log_(action + ' response', message); + delete this.outstandingPuts_[index]; + this.outstandingPutCount_--; + // Clean up array occasionally. + if (this.outstandingPutCount_ === 0) { + this.outstandingPuts_ = []; + } + if (onComplete) { + onComplete(message[ /*status*/'s'], message[ /* data */'d']); + } + }); + } + reportStats(stats) { + // If we're not connected, we just drop the stats. + if (this.connected_) { + const request = { /*counters*/ c: stats }; + this.log_('reportStats', request); + this.sendRequest(/*stats*/ 's', request, result => { + const status = result[ /*status*/'s']; + if (status !== 'ok') { + const errorReason = result[ /* data */'d']; + this.log_('reportStats', 'Error sending stats: ' + errorReason); + } + }); + } + } + onDataMessage_(message) { + if ('r' in message) { + // this is a response + this.log_('from server: ' + util.stringify(message)); + const reqNum = message['r']; + const onResponse = this.requestCBHash_[reqNum]; + if (onResponse) { + delete this.requestCBHash_[reqNum]; + onResponse(message[ /*body*/'b']); + } + } + else if ('error' in message) { + throw 'A server-side error has occurred: ' + message['error']; + } + else if ('a' in message) { + // a and b are action and body, respectively + this.onDataPush_(message['a'], message['b']); + } + } + onDataPush_(action, body) { + this.log_('handleServerMessage', action, body); + if (action === 'd') { + this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], + /*isMerge*/ false, body['t']); + } + else if (action === 'm') { + this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], + /*isMerge=*/ true, body['t']); + } + else if (action === 'c') { + this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']); + } + else if (action === 'ac') { + this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']); + } + else if (action === 'apc') { + this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']); + } + else if (action === 'sd') { + this.onSecurityDebugPacket_(body); + } + else { + error('Unrecognized action received from server: ' + + util.stringify(action) + + '\nAre you using the latest client?'); + } + } + onReady_(timestamp, sessionId) { + this.log_('connection ready'); + this.connected_ = true; + this.lastConnectionEstablishedTime_ = new Date().getTime(); + this.handleTimestamp_(timestamp); + this.lastSessionId = sessionId; + if (this.firstConnection_) { + this.sendConnectStats_(); + } + this.restoreState_(); + this.firstConnection_ = false; + this.onConnectStatus_(true); + } + scheduleConnect_(timeout) { + util.assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?"); + if (this.establishConnectionTimer_) { + clearTimeout(this.establishConnectionTimer_); + } + // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in + // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests). + this.establishConnectionTimer_ = setTimeout(() => { + this.establishConnectionTimer_ = null; + this.establishConnection_(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(timeout)); + } + initConnection_() { + if (!this.realtime_ && this.firstConnection_) { + this.scheduleConnect_(0); + } + } + onVisible_(visible) { + // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine. + if (visible && + !this.visible_ && + this.reconnectDelay_ === this.maxReconnectDelay_) { + this.log_('Window became visible. Reducing delay.'); + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + if (!this.realtime_) { + this.scheduleConnect_(0); + } + } + this.visible_ = visible; + } + onOnline_(online) { + if (online) { + this.log_('Browser went online.'); + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + if (!this.realtime_) { + this.scheduleConnect_(0); + } + } + else { + this.log_('Browser went offline. Killing connection.'); + if (this.realtime_) { + this.realtime_.close(); + } + } + } + onRealtimeDisconnect_() { + this.log_('data client disconnected'); + this.connected_ = false; + this.realtime_ = null; + // Since we don't know if our sent transactions succeeded or not, we need to cancel them. + this.cancelSentTransactions_(); + // Clear out the pending requests. + this.requestCBHash_ = {}; + if (this.shouldReconnect_()) { + if (!this.visible_) { + this.log_("Window isn't visible. Delaying reconnect."); + this.reconnectDelay_ = this.maxReconnectDelay_; + this.lastConnectionAttemptTime_ = new Date().getTime(); + } + else if (this.lastConnectionEstablishedTime_) { + // If we've been connected long enough, reset reconnect delay to minimum. + const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_; + if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) { + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + } + this.lastConnectionEstablishedTime_ = null; + } + const timeSinceLastConnectAttempt = Math.max(0, new Date().getTime() - this.lastConnectionAttemptTime_); + let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt); + reconnectDelay = Math.random() * reconnectDelay; + this.log_('Trying to reconnect in ' + reconnectDelay + 'ms'); + this.scheduleConnect_(reconnectDelay); + // Adjust reconnect delay for next time. + this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER); + } + this.onConnectStatus_(false); + } + async establishConnection_() { + if (this.shouldReconnect_()) { + this.log_('Making a connection attempt'); + this.lastConnectionAttemptTime_ = new Date().getTime(); + this.lastConnectionEstablishedTime_ = null; + const onDataMessage = this.onDataMessage_.bind(this); + const onReady = this.onReady_.bind(this); + const onDisconnect = this.onRealtimeDisconnect_.bind(this); + const connId = this.id + ':' + PersistentConnection.nextConnectionId_++; + const lastSessionId = this.lastSessionId; + let canceled = false; + let connection = null; + const closeFn = function () { + if (connection) { + connection.close(); + } + else { + canceled = true; + onDisconnect(); + } + }; + const sendRequestFn = function (msg) { + util.assert(connection, "sendRequest call when we're not connected not allowed."); + connection.sendRequest(msg); + }; + this.realtime_ = { + close: closeFn, + sendRequest: sendRequestFn + }; + const forceRefresh = this.forceTokenRefresh_; + this.forceTokenRefresh_ = false; + try { + // First fetch auth and app check token, and establish connection after + // fetching the token was successful + const [authToken, appCheckToken] = await Promise.all([ + this.authTokenProvider_.getToken(forceRefresh), + this.appCheckTokenProvider_.getToken(forceRefresh) + ]); + if (!canceled) { + log('getToken() completed. Creating connection.'); + this.authToken_ = authToken && authToken.accessToken; + this.appCheckToken_ = appCheckToken && appCheckToken.token; + connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect, + /* onKill= */ reason => { + warn$1(reason + ' (' + this.repoInfo_.toString() + ')'); + this.interrupt(SERVER_KILL_INTERRUPT_REASON); + }, lastSessionId); + } + else { + log('getToken() completed but was canceled'); + } + } + catch (error) { + this.log_('Failed to get token: ' + error); + if (!canceled) { + if (this.repoInfo_.nodeAdmin) { + // This may be a critical error for the Admin Node.js SDK, so log a warning. + // But getToken() may also just have temporarily failed, so we still want to + // continue retrying. + warn$1(error); + } + closeFn(); + } + } + } + } + interrupt(reason) { + log('Interrupting connection for reason: ' + reason); + this.interruptReasons_[reason] = true; + if (this.realtime_) { + this.realtime_.close(); + } + else { + if (this.establishConnectionTimer_) { + clearTimeout(this.establishConnectionTimer_); + this.establishConnectionTimer_ = null; + } + if (this.connected_) { + this.onRealtimeDisconnect_(); + } + } + } + resume(reason) { + log('Resuming connection for reason: ' + reason); + delete this.interruptReasons_[reason]; + if (util.isEmpty(this.interruptReasons_)) { + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + if (!this.realtime_) { + this.scheduleConnect_(0); + } + } + } + handleTimestamp_(timestamp) { + const delta = timestamp - new Date().getTime(); + this.onServerInfoUpdate_({ serverTimeOffset: delta }); + } + cancelSentTransactions_() { + for (let i = 0; i < this.outstandingPuts_.length; i++) { + const put = this.outstandingPuts_[i]; + if (put && /*hash*/ 'h' in put.request && put.queued) { + if (put.onComplete) { + put.onComplete('disconnect'); + } + delete this.outstandingPuts_[i]; + this.outstandingPutCount_--; + } + } + // Clean up array occasionally. + if (this.outstandingPutCount_ === 0) { + this.outstandingPuts_ = []; + } + } + onListenRevoked_(pathString, query) { + // Remove the listen and manufacture a "permission_denied" error for the failed listen. + let queryId; + if (!query) { + queryId = 'default'; + } + else { + queryId = query.map(q => ObjectToUniqueKey(q)).join('$'); + } + const listen = this.removeListen_(pathString, queryId); + if (listen && listen.onComplete) { + listen.onComplete('permission_denied'); + } + } + removeListen_(pathString, queryId) { + const normalizedPathString = new Path(pathString).toString(); // normalize path. + let listen; + if (this.listens.has(normalizedPathString)) { + const map = this.listens.get(normalizedPathString); + listen = map.get(queryId); + map.delete(queryId); + if (map.size === 0) { + this.listens.delete(normalizedPathString); + } + } + else { + // all listens for this path has already been removed + listen = undefined; + } + return listen; + } + onAuthRevoked_(statusCode, explanation) { + log('Auth token revoked: ' + statusCode + '/' + explanation); + this.authToken_ = null; + this.forceTokenRefresh_ = true; + this.realtime_.close(); + if (statusCode === 'invalid_token' || statusCode === 'permission_denied') { + // We'll wait a couple times before logging the warning / increasing the + // retry period since oauth tokens will report as "invalid" if they're + // just expired. Plus there may be transient issues that resolve themselves. + this.invalidAuthTokenCount_++; + if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) { + // Set a long reconnect delay because recovery is unlikely + this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS; + // Notify the auth token provider that the token is invalid, which will log + // a warning + this.authTokenProvider_.notifyForInvalidToken(); + } + } + } + onAppCheckRevoked_(statusCode, explanation) { + log('App check token revoked: ' + statusCode + '/' + explanation); + this.appCheckToken_ = null; + this.forceTokenRefresh_ = true; + // Note: We don't close the connection as the developer may not have + // enforcement enabled. The backend closes connections with enforcements. + if (statusCode === 'invalid_token' || statusCode === 'permission_denied') { + // We'll wait a couple times before logging the warning / increasing the + // retry period since oauth tokens will report as "invalid" if they're + // just expired. Plus there may be transient issues that resolve themselves. + this.invalidAppCheckTokenCount_++; + if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) { + this.appCheckTokenProvider_.notifyForInvalidToken(); + } + } + } + onSecurityDebugPacket_(body) { + if (this.securityDebugCallback_) { + this.securityDebugCallback_(body); + } + else { + if ('msg' in body) { + console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: ')); + } + } + } + restoreState_() { + //Re-authenticate ourselves if we have a credential stored. + this.tryAuth(); + this.tryAppCheck(); + // Puts depend on having received the corresponding data update from the server before they complete, so we must + // make sure to send listens before puts. + for (const queries of this.listens.values()) { + for (const listenSpec of queries.values()) { + this.sendListen_(listenSpec); + } + } + for (let i = 0; i < this.outstandingPuts_.length; i++) { + if (this.outstandingPuts_[i]) { + this.sendPut_(i); + } + } + while (this.onDisconnectRequestQueue_.length) { + const request = this.onDisconnectRequestQueue_.shift(); + this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete); + } + for (let i = 0; i < this.outstandingGets_.length; i++) { + if (this.outstandingGets_[i]) { + this.sendGet_(i); + } + } + } + /** + * Sends client stats for first connection + */ + sendConnectStats_() { + const stats = {}; + let clientName = 'js'; + if (util.isNodeSdk()) { + if (this.repoInfo_.nodeAdmin) { + clientName = 'admin_node'; + } + else { + clientName = 'node'; + } + } + stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1; + if (util.isMobileCordova()) { + stats['framework.cordova'] = 1; + } + else if (util.isReactNative()) { + stats['framework.reactnative'] = 1; + } + this.reportStats(stats); + } + shouldReconnect_() { + const online = OnlineMonitor.getInstance().currentlyOnline(); + return util.isEmpty(this.interruptReasons_) && online; + } +} +PersistentConnection.nextPersistentConnectionId_ = 0; +/** + * Counter for number of connections created. Mainly used for tagging in the logs + */ +PersistentConnection.nextConnectionId_ = 0; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class NamedNode { + constructor(name, node) { + this.name = name; + this.node = node; + } + static Wrap(name, node) { + return new NamedNode(name, node); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Index { + /** + * @returns A standalone comparison function for + * this index + */ + getCompare() { + return this.compare.bind(this); + } + /** + * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different, + * it's possible that the changes are isolated to parts of the snapshot that are not indexed. + * + * + * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode + */ + indexedValueChanged(oldNode, newNode) { + const oldWrapped = new NamedNode(MIN_NAME, oldNode); + const newWrapped = new NamedNode(MIN_NAME, newNode); + return this.compare(oldWrapped, newWrapped) !== 0; + } + /** + * @returns a node wrapper that will sort equal to or less than + * any other node wrapper, using this index + */ + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let __EMPTY_NODE; +class KeyIndex extends Index { + static get __EMPTY_NODE() { + return __EMPTY_NODE; + } + static set __EMPTY_NODE(val) { + __EMPTY_NODE = val; + } + compare(a, b) { + return nameCompare(a.name, b.name); + } + isDefinedOn(node) { + // We could probably return true here (since every node has a key), but it's never called + // so just leaving unimplemented for now. + throw util.assertionError('KeyIndex.isDefinedOn not expected to be called.'); + } + indexedValueChanged(oldNode, newNode) { + return false; // The key for a node never changes. + } + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } + maxPost() { + // TODO: This should really be created once and cached in a static property, but + // NamedNode isn't defined yet, so I can't use it in a static. Bleh. + return new NamedNode(MAX_NAME, __EMPTY_NODE); + } + makePost(indexValue, name) { + util.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.'); + // We just use empty node, but it'll never be compared, since our comparator only looks at name. + return new NamedNode(indexValue, __EMPTY_NODE); + } + /** + * @returns String representation for inclusion in a query spec + */ + toString() { + return '.key'; + } +} +const KEY_INDEX = new KeyIndex(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An iterator over an LLRBNode. + */ +class SortedMapIterator { + /** + * @param node - Node to iterate. + * @param isReverse_ - Whether or not to iterate in reverse + */ + constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) { + this.isReverse_ = isReverse_; + this.resultGenerator_ = resultGenerator_; + this.nodeStack_ = []; + let cmp = 1; + while (!node.isEmpty()) { + node = node; + cmp = startKey ? comparator(node.key, startKey) : 1; + // flip the comparison if we're going in reverse + if (isReverse_) { + cmp *= -1; + } + if (cmp < 0) { + // This node is less than our start key. ignore it + if (this.isReverse_) { + node = node.left; + } + else { + node = node.right; + } + } + else if (cmp === 0) { + // This node is exactly equal to our start key. Push it on the stack, but stop iterating; + this.nodeStack_.push(node); + break; + } + else { + // This node is greater than our start key, add it to the stack and move to the next one + this.nodeStack_.push(node); + if (this.isReverse_) { + node = node.right; + } + else { + node = node.left; + } + } + } + } + getNext() { + if (this.nodeStack_.length === 0) { + return null; + } + let node = this.nodeStack_.pop(); + let result; + if (this.resultGenerator_) { + result = this.resultGenerator_(node.key, node.value); + } + else { + result = { key: node.key, value: node.value }; + } + if (this.isReverse_) { + node = node.left; + while (!node.isEmpty()) { + this.nodeStack_.push(node); + node = node.right; + } + } + else { + node = node.right; + while (!node.isEmpty()) { + this.nodeStack_.push(node); + node = node.left; + } + } + return result; + } + hasNext() { + return this.nodeStack_.length > 0; + } + peek() { + if (this.nodeStack_.length === 0) { + return null; + } + const node = this.nodeStack_[this.nodeStack_.length - 1]; + if (this.resultGenerator_) { + return this.resultGenerator_(node.key, node.value); + } + else { + return { key: node.key, value: node.value }; + } + } +} +/** + * Represents a node in a Left-leaning Red-Black tree. + */ +class LLRBNode { + /** + * @param key - Key associated with this node. + * @param value - Value associated with this node. + * @param color - Whether this node is red. + * @param left - Left child. + * @param right - Right child. + */ + constructor(key, value, color, left, right) { + this.key = key; + this.value = value; + this.color = color != null ? color : LLRBNode.RED; + this.left = + left != null ? left : SortedMap.EMPTY_NODE; + this.right = + right != null ? right : SortedMap.EMPTY_NODE; + } + /** + * Returns a copy of the current node, optionally replacing pieces of it. + * + * @param key - New key for the node, or null. + * @param value - New value for the node, or null. + * @param color - New color for the node, or null. + * @param left - New left child for the node, or null. + * @param right - New right child for the node, or null. + * @returns The node copy. + */ + copy(key, value, color, left, right) { + return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right); + } + /** + * @returns The total number of nodes in the tree. + */ + count() { + return this.left.count() + 1 + this.right.count(); + } + /** + * @returns True if the tree is empty. + */ + isEmpty() { + return false; + } + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action) { + return (this.left.inorderTraversal(action) || + !!action(this.key, this.value) || + this.right.inorderTraversal(action)); + } + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action) { + return (this.right.reverseTraversal(action) || + action(this.key, this.value) || + this.left.reverseTraversal(action)); + } + /** + * @returns The minimum node in the tree. + */ + min_() { + if (this.left.isEmpty()) { + return this; + } + else { + return this.left.min_(); + } + } + /** + * @returns The maximum key in the tree. + */ + minKey() { + return this.min_().key; + } + /** + * @returns The maximum key in the tree. + */ + maxKey() { + if (this.right.isEmpty()) { + return this.key; + } + else { + return this.right.maxKey(); + } + } + /** + * @param key - Key to insert. + * @param value - Value to insert. + * @param comparator - Comparator. + * @returns New tree, with the key/value added. + */ + insert(key, value, comparator) { + let n = this; + const cmp = comparator(key, n.key); + if (cmp < 0) { + n = n.copy(null, null, null, n.left.insert(key, value, comparator), null); + } + else if (cmp === 0) { + n = n.copy(null, value, null, null, null); + } + else { + n = n.copy(null, null, null, null, n.right.insert(key, value, comparator)); + } + return n.fixUp_(); + } + /** + * @returns New tree, with the minimum key removed. + */ + removeMin_() { + if (this.left.isEmpty()) { + return SortedMap.EMPTY_NODE; + } + let n = this; + if (!n.left.isRed_() && !n.left.left.isRed_()) { + n = n.moveRedLeft_(); + } + n = n.copy(null, null, null, n.left.removeMin_(), null); + return n.fixUp_(); + } + /** + * @param key - The key of the item to remove. + * @param comparator - Comparator. + * @returns New tree, with the specified item removed. + */ + remove(key, comparator) { + let n, smallest; + n = this; + if (comparator(key, n.key) < 0) { + if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) { + n = n.moveRedLeft_(); + } + n = n.copy(null, null, null, n.left.remove(key, comparator), null); + } + else { + if (n.left.isRed_()) { + n = n.rotateRight_(); + } + if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) { + n = n.moveRedRight_(); + } + if (comparator(key, n.key) === 0) { + if (n.right.isEmpty()) { + return SortedMap.EMPTY_NODE; + } + else { + smallest = n.right.min_(); + n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_()); + } + } + n = n.copy(null, null, null, null, n.right.remove(key, comparator)); + } + return n.fixUp_(); + } + /** + * @returns Whether this is a RED node. + */ + isRed_() { + return this.color; + } + /** + * @returns New tree after performing any needed rotations. + */ + fixUp_() { + let n = this; + if (n.right.isRed_() && !n.left.isRed_()) { + n = n.rotateLeft_(); + } + if (n.left.isRed_() && n.left.left.isRed_()) { + n = n.rotateRight_(); + } + if (n.left.isRed_() && n.right.isRed_()) { + n = n.colorFlip_(); + } + return n; + } + /** + * @returns New tree, after moveRedLeft. + */ + moveRedLeft_() { + let n = this.colorFlip_(); + if (n.right.left.isRed_()) { + n = n.copy(null, null, null, null, n.right.rotateRight_()); + n = n.rotateLeft_(); + n = n.colorFlip_(); + } + return n; + } + /** + * @returns New tree, after moveRedRight. + */ + moveRedRight_() { + let n = this.colorFlip_(); + if (n.left.left.isRed_()) { + n = n.rotateRight_(); + n = n.colorFlip_(); + } + return n; + } + /** + * @returns New tree, after rotateLeft. + */ + rotateLeft_() { + const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, nl, null); + } + /** + * @returns New tree, after rotateRight. + */ + rotateRight_() { + const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, nr); + } + /** + * @returns Newt ree, after colorFlip. + */ + colorFlip_() { + const left = this.left.copy(null, null, !this.left.color, null, null); + const right = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, left, right); + } + /** + * For testing. + * + * @returns True if all is well. + */ + checkMaxDepth_() { + const blackDepth = this.check_(); + return Math.pow(2.0, blackDepth) <= this.count() + 1; + } + check_() { + if (this.isRed_() && this.left.isRed_()) { + throw new Error('Red node has red child(' + this.key + ',' + this.value + ')'); + } + if (this.right.isRed_()) { + throw new Error('Right child of (' + this.key + ',' + this.value + ') is red'); + } + const blackDepth = this.left.check_(); + if (blackDepth !== this.right.check_()) { + throw new Error('Black depths differ'); + } + else { + return blackDepth + (this.isRed_() ? 0 : 1); + } + } +} +LLRBNode.RED = true; +LLRBNode.BLACK = false; +/** + * Represents an empty node (a leaf node in the Red-Black Tree). + */ +class LLRBEmptyNode { + /** + * Returns a copy of the current node. + * + * @returns The node copy. + */ + copy(key, value, color, left, right) { + return this; + } + /** + * Returns a copy of the tree, with the specified key/value added. + * + * @param key - Key to be added. + * @param value - Value to be added. + * @param comparator - Comparator. + * @returns New tree, with item added. + */ + insert(key, value, comparator) { + return new LLRBNode(key, value, null); + } + /** + * Returns a copy of the tree, with the specified key removed. + * + * @param key - The key to remove. + * @param comparator - Comparator. + * @returns New tree, with item removed. + */ + remove(key, comparator) { + return this; + } + /** + * @returns The total number of nodes in the tree. + */ + count() { + return 0; + } + /** + * @returns True if the tree is empty. + */ + isEmpty() { + return true; + } + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + inorderTraversal(action) { + return false; + } + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action) { + return false; + } + minKey() { + return null; + } + maxKey() { + return null; + } + check_() { + return 0; + } + /** + * @returns Whether this node is red. + */ + isRed_() { + return false; + } +} +/** + * An immutable sorted map implementation, based on a Left-leaning Red-Black + * tree. + */ +class SortedMap { + /** + * @param comparator_ - Key comparator. + * @param root_ - Optional root node for the map. + */ + constructor(comparator_, root_ = SortedMap.EMPTY_NODE) { + this.comparator_ = comparator_; + this.root_ = root_; + } + /** + * Returns a copy of the map, with the specified key/value added or replaced. + * (TODO: We should perhaps rename this method to 'put') + * + * @param key - Key to be added. + * @param value - Value to be added. + * @returns New map, with item added. + */ + insert(key, value) { + return new SortedMap(this.comparator_, this.root_ + .insert(key, value, this.comparator_) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + /** + * Returns a copy of the map, with the specified key removed. + * + * @param key - The key to remove. + * @returns New map, with item removed. + */ + remove(key) { + return new SortedMap(this.comparator_, this.root_ + .remove(key, this.comparator_) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + /** + * Returns the value of the node with the given key, or null. + * + * @param key - The key to look up. + * @returns The value of the node with the given key, or null if the + * key doesn't exist. + */ + get(key) { + let cmp; + let node = this.root_; + while (!node.isEmpty()) { + cmp = this.comparator_(key, node.key); + if (cmp === 0) { + return node.value; + } + else if (cmp < 0) { + node = node.left; + } + else if (cmp > 0) { + node = node.right; + } + } + return null; + } + /** + * Returns the key of the item *before* the specified key, or null if key is the first item. + * @param key - The key to find the predecessor of + * @returns The predecessor key. + */ + getPredecessorKey(key) { + let cmp, node = this.root_, rightParent = null; + while (!node.isEmpty()) { + cmp = this.comparator_(key, node.key); + if (cmp === 0) { + if (!node.left.isEmpty()) { + node = node.left; + while (!node.right.isEmpty()) { + node = node.right; + } + return node.key; + } + else if (rightParent) { + return rightParent.key; + } + else { + return null; // first item. + } + } + else if (cmp < 0) { + node = node.left; + } + else if (cmp > 0) { + rightParent = node; + node = node.right; + } + } + throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?'); + } + /** + * @returns True if the map is empty. + */ + isEmpty() { + return this.root_.isEmpty(); + } + /** + * @returns The total number of nodes in the map. + */ + count() { + return this.root_.count(); + } + /** + * @returns The minimum key in the map. + */ + minKey() { + return this.root_.minKey(); + } + /** + * @returns The maximum key in the map. + */ + maxKey() { + return this.root_.maxKey(); + } + /** + * Traverses the map in key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action) { + return this.root_.inorderTraversal(action); + } + /** + * Traverses the map in reverse key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns True if the traversal was aborted. + */ + reverseTraversal(action) { + return this.root_.reverseTraversal(action); + } + /** + * Returns an iterator over the SortedMap. + * @returns The iterator. + */ + getIterator(resultGenerator) { + return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator); + } + getIteratorFrom(key, resultGenerator) { + return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator); + } + getReverseIteratorFrom(key, resultGenerator) { + return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator); + } + getReverseIterator(resultGenerator) { + return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator); + } +} +/** + * Always use the same empty node, to reduce memory. + */ +SortedMap.EMPTY_NODE = new LLRBEmptyNode(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function NAME_ONLY_COMPARATOR(left, right) { + return nameCompare(left.name, right.name); +} +function NAME_COMPARATOR(left, right) { + return nameCompare(left, right); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let MAX_NODE$2; +function setMaxNode$1(val) { + MAX_NODE$2 = val; +} +const priorityHashText = function (priority) { + if (typeof priority === 'number') { + return 'number:' + doubleToIEEE754String(priority); + } + else { + return 'string:' + priority; + } +}; +/** + * Validates that a priority snapshot Node is valid. + */ +const validatePriorityNode = function (priorityNode) { + if (priorityNode.isLeafNode()) { + const val = priorityNode.val(); + util.assert(typeof val === 'string' || + typeof val === 'number' || + (typeof val === 'object' && util.contains(val, '.sv')), 'Priority must be a string or number.'); + } + else { + util.assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.'); + } + // Don't call getPriority() on MAX_NODE to avoid hitting assertion. + util.assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own."); +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let __childrenNodeConstructor; +/** + * LeafNode is a class for storing leaf nodes in a DataSnapshot. It + * implements Node and stores the value of the node (a string, + * number, or boolean) accessible via getValue(). + */ +class LeafNode { + static set __childrenNodeConstructor(val) { + __childrenNodeConstructor = val; + } + static get __childrenNodeConstructor() { + return __childrenNodeConstructor; + } + /** + * @param value_ - The value to store in this leaf node. The object type is + * possible in the event of a deferred value + * @param priorityNode_ - The priority of this node. + */ + constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) { + this.value_ = value_; + this.priorityNode_ = priorityNode_; + this.lazyHash_ = null; + util.assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value."); + validatePriorityNode(this.priorityNode_); + } + /** @inheritDoc */ + isLeafNode() { + return true; + } + /** @inheritDoc */ + getPriority() { + return this.priorityNode_; + } + /** @inheritDoc */ + updatePriority(newPriorityNode) { + return new LeafNode(this.value_, newPriorityNode); + } + /** @inheritDoc */ + getImmediateChild(childName) { + // Hack to treat priority as a regular child + if (childName === '.priority') { + return this.priorityNode_; + } + else { + return LeafNode.__childrenNodeConstructor.EMPTY_NODE; + } + } + /** @inheritDoc */ + getChild(path) { + if (pathIsEmpty(path)) { + return this; + } + else if (pathGetFront(path) === '.priority') { + return this.priorityNode_; + } + else { + return LeafNode.__childrenNodeConstructor.EMPTY_NODE; + } + } + hasChild() { + return false; + } + /** @inheritDoc */ + getPredecessorChildName(childName, childNode) { + return null; + } + /** @inheritDoc */ + updateImmediateChild(childName, newChildNode) { + if (childName === '.priority') { + return this.updatePriority(newChildNode); + } + else if (newChildNode.isEmpty() && childName !== '.priority') { + return this; + } + else { + return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_); + } + } + /** @inheritDoc */ + updateChild(path, newChildNode) { + const front = pathGetFront(path); + if (front === null) { + return newChildNode; + } + else if (newChildNode.isEmpty() && front !== '.priority') { + return this; + } + else { + util.assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path'); + return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode)); + } + } + /** @inheritDoc */ + isEmpty() { + return false; + } + /** @inheritDoc */ + numChildren() { + return 0; + } + /** @inheritDoc */ + forEachChild(index, action) { + return false; + } + val(exportFormat) { + if (exportFormat && !this.getPriority().isEmpty()) { + return { + '.value': this.getValue(), + '.priority': this.getPriority().val() + }; + } + else { + return this.getValue(); + } + } + /** @inheritDoc */ + hash() { + if (this.lazyHash_ === null) { + let toHash = ''; + if (!this.priorityNode_.isEmpty()) { + toHash += + 'priority:' + + priorityHashText(this.priorityNode_.val()) + + ':'; + } + const type = typeof this.value_; + toHash += type + ':'; + if (type === 'number') { + toHash += doubleToIEEE754String(this.value_); + } + else { + toHash += this.value_; + } + this.lazyHash_ = sha1(toHash); + } + return this.lazyHash_; + } + /** + * Returns the value of the leaf node. + * @returns The value of the node. + */ + getValue() { + return this.value_; + } + compareTo(other) { + if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) { + return 1; + } + else if (other instanceof LeafNode.__childrenNodeConstructor) { + return -1; + } + else { + util.assert(other.isLeafNode(), 'Unknown node type'); + return this.compareToLeafNode_(other); + } + } + /** + * Comparison specifically for two leaf nodes + */ + compareToLeafNode_(otherLeaf) { + const otherLeafType = typeof otherLeaf.value_; + const thisLeafType = typeof this.value_; + const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType); + const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType); + util.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType); + util.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType); + if (otherIndex === thisIndex) { + // Same type, compare values + if (thisLeafType === 'object') { + // Deferred value nodes are all equal, but we should also never get to this point... + return 0; + } + else { + // Note that this works because true > false, all others are number or string comparisons + if (this.value_ < otherLeaf.value_) { + return -1; + } + else if (this.value_ === otherLeaf.value_) { + return 0; + } + else { + return 1; + } + } + } + else { + return thisIndex - otherIndex; + } + } + withIndex() { + return this; + } + isIndexed() { + return true; + } + equals(other) { + if (other === this) { + return true; + } + else if (other.isLeafNode()) { + const otherLeaf = other; + return (this.value_ === otherLeaf.value_ && + this.priorityNode_.equals(otherLeaf.priorityNode_)); + } + else { + return false; + } + } +} +/** + * The sort order for comparing leaf nodes of different types. If two leaf nodes have + * the same type, the comparison falls back to their value + */ +LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string']; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let nodeFromJSON$1; +let MAX_NODE$1; +function setNodeFromJSON(val) { + nodeFromJSON$1 = val; +} +function setMaxNode(val) { + MAX_NODE$1 = val; +} +class PriorityIndex extends Index { + compare(a, b) { + const aPriority = a.node.getPriority(); + const bPriority = b.node.getPriority(); + const indexCmp = aPriority.compareTo(bPriority); + if (indexCmp === 0) { + return nameCompare(a.name, b.name); + } + else { + return indexCmp; + } + } + isDefinedOn(node) { + return !node.getPriority().isEmpty(); + } + indexedValueChanged(oldNode, newNode) { + return !oldNode.getPriority().equals(newNode.getPriority()); + } + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } + maxPost() { + return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1)); + } + makePost(indexValue, name) { + const priorityNode = nodeFromJSON$1(indexValue); + return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode)); + } + /** + * @returns String representation for inclusion in a query spec + */ + toString() { + return '.priority'; + } +} +const PRIORITY_INDEX = new PriorityIndex(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_2 = Math.log(2); +class Base12Num { + constructor(length) { + const logBase2 = (num) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + parseInt((Math.log(num) / LOG_2), 10); + const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2); + this.count = logBase2(length + 1); + this.current_ = this.count - 1; + const mask = bitMask(this.count); + this.bits_ = (length + 1) & mask; + } + nextBitIsOne() { + //noinspection JSBitwiseOperatorUsage + const result = !(this.bits_ & (0x1 << this.current_)); + this.current_--; + return result; + } +} +/** + * Takes a list of child nodes and constructs a SortedSet using the given comparison + * function + * + * Uses the algorithm described in the paper linked here: + * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458 + * + * @param childList - Unsorted list of children + * @param cmp - The comparison method to be used + * @param keyFn - An optional function to extract K from a node wrapper, if K's + * type is not NamedNode + * @param mapSortFn - An optional override for comparator used by the generated sorted map + */ +const buildChildSet = function (childList, cmp, keyFn, mapSortFn) { + childList.sort(cmp); + const buildBalancedTree = function (low, high) { + const length = high - low; + let namedNode; + let key; + if (length === 0) { + return null; + } + else if (length === 1) { + namedNode = childList[low]; + key = keyFn ? keyFn(namedNode) : namedNode; + return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null); + } + else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const middle = parseInt((length / 2), 10) + low; + const left = buildBalancedTree(low, middle); + const right = buildBalancedTree(middle + 1, high); + namedNode = childList[middle]; + key = keyFn ? keyFn(namedNode) : namedNode; + return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right); + } + }; + const buildFrom12Array = function (base12) { + let node = null; + let root = null; + let index = childList.length; + const buildPennant = function (chunkSize, color) { + const low = index - chunkSize; + const high = index; + index -= chunkSize; + const childTree = buildBalancedTree(low + 1, high); + const namedNode = childList[low]; + const key = keyFn ? keyFn(namedNode) : namedNode; + attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree)); + }; + const attachPennant = function (pennant) { + if (node) { + node.left = pennant; + node = pennant; + } + else { + root = pennant; + node = pennant; + } + }; + for (let i = 0; i < base12.count; ++i) { + const isOne = base12.nextBitIsOne(); + // The number of nodes taken in each slice is 2^(arr.length - (i + 1)) + const chunkSize = Math.pow(2, base12.count - (i + 1)); + if (isOne) { + buildPennant(chunkSize, LLRBNode.BLACK); + } + else { + // current == 2 + buildPennant(chunkSize, LLRBNode.BLACK); + buildPennant(chunkSize, LLRBNode.RED); + } + } + return root; + }; + const base12 = new Base12Num(childList.length); + const root = buildFrom12Array(base12); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return new SortedMap(mapSortFn || cmp, root); +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let _defaultIndexMap; +const fallbackObject = {}; +class IndexMap { + /** + * The default IndexMap for nodes without a priority + */ + static get Default() { + util.assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded'); + _defaultIndexMap = + _defaultIndexMap || + new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX }); + return _defaultIndexMap; + } + constructor(indexes_, indexSet_) { + this.indexes_ = indexes_; + this.indexSet_ = indexSet_; + } + get(indexKey) { + const sortedMap = util.safeGet(this.indexes_, indexKey); + if (!sortedMap) { + throw new Error('No index defined for ' + indexKey); + } + if (sortedMap instanceof SortedMap) { + return sortedMap; + } + else { + // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the + // regular child map + return null; + } + } + hasIndex(indexDefinition) { + return util.contains(this.indexSet_, indexDefinition.toString()); + } + addIndex(indexDefinition, existingChildren) { + util.assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap."); + const childList = []; + let sawIndexedValue = false; + const iter = existingChildren.getIterator(NamedNode.Wrap); + let next = iter.getNext(); + while (next) { + sawIndexedValue = + sawIndexedValue || indexDefinition.isDefinedOn(next.node); + childList.push(next); + next = iter.getNext(); + } + let newIndex; + if (sawIndexedValue) { + newIndex = buildChildSet(childList, indexDefinition.getCompare()); + } + else { + newIndex = fallbackObject; + } + const indexName = indexDefinition.toString(); + const newIndexSet = { ...this.indexSet_ }; + newIndexSet[indexName] = indexDefinition; + const newIndexes = { ...this.indexes_ }; + newIndexes[indexName] = newIndex; + return new IndexMap(newIndexes, newIndexSet); + } + /** + * Ensure that this node is properly tracked in any indexes that we're maintaining + */ + addToIndexes(namedNode, existingChildren) { + const newIndexes = util.map(this.indexes_, (indexedChildren, indexName) => { + const index = util.safeGet(this.indexSet_, indexName); + util.assert(index, 'Missing index implementation for ' + indexName); + if (indexedChildren === fallbackObject) { + // Check to see if we need to index everything + if (index.isDefinedOn(namedNode.node)) { + // We need to build this index + const childList = []; + const iter = existingChildren.getIterator(NamedNode.Wrap); + let next = iter.getNext(); + while (next) { + if (next.name !== namedNode.name) { + childList.push(next); + } + next = iter.getNext(); + } + childList.push(namedNode); + return buildChildSet(childList, index.getCompare()); + } + else { + // No change, this remains a fallback + return fallbackObject; + } + } + else { + const existingSnap = existingChildren.get(namedNode.name); + let newChildren = indexedChildren; + if (existingSnap) { + newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap)); + } + return newChildren.insert(namedNode, namedNode.node); + } + }); + return new IndexMap(newIndexes, this.indexSet_); + } + /** + * Create a new IndexMap instance with the given value removed + */ + removeFromIndexes(namedNode, existingChildren) { + const newIndexes = util.map(this.indexes_, (indexedChildren) => { + if (indexedChildren === fallbackObject) { + // This is the fallback. Just return it, nothing to do in this case + return indexedChildren; + } + else { + const existingSnap = existingChildren.get(namedNode.name); + if (existingSnap) { + return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap)); + } + else { + // No record of this child + return indexedChildren; + } + } + }); + return new IndexMap(newIndexes, this.indexSet_); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO: For memory savings, don't store priorityNode_ if it's empty. +let EMPTY_NODE; +/** + * ChildrenNode is a class for storing internal nodes in a DataSnapshot + * (i.e. nodes with children). It implements Node and stores the + * list of children in the children property, sorted by child name. + */ +class ChildrenNode { + static get EMPTY_NODE() { + return (EMPTY_NODE || + (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default))); + } + /** + * @param children_ - List of children of this node.. + * @param priorityNode_ - The priority of this node (as a snapshot node). + */ + constructor(children_, priorityNode_, indexMap_) { + this.children_ = children_; + this.priorityNode_ = priorityNode_; + this.indexMap_ = indexMap_; + this.lazyHash_ = null; + /** + * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use + * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own + * class instead of an empty ChildrenNode. + */ + if (this.priorityNode_) { + validatePriorityNode(this.priorityNode_); + } + if (this.children_.isEmpty()) { + util.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority'); + } + } + /** @inheritDoc */ + isLeafNode() { + return false; + } + /** @inheritDoc */ + getPriority() { + return this.priorityNode_ || EMPTY_NODE; + } + /** @inheritDoc */ + updatePriority(newPriorityNode) { + if (this.children_.isEmpty()) { + // Don't allow priorities on empty nodes + return this; + } + else { + return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_); + } + } + /** @inheritDoc */ + getImmediateChild(childName) { + // Hack to treat priority as a regular child + if (childName === '.priority') { + return this.getPriority(); + } + else { + const child = this.children_.get(childName); + return child === null ? EMPTY_NODE : child; + } + } + /** @inheritDoc */ + getChild(path) { + const front = pathGetFront(path); + if (front === null) { + return this; + } + return this.getImmediateChild(front).getChild(pathPopFront(path)); + } + /** @inheritDoc */ + hasChild(childName) { + return this.children_.get(childName) !== null; + } + /** @inheritDoc */ + updateImmediateChild(childName, newChildNode) { + util.assert(newChildNode, 'We should always be passing snapshot nodes'); + if (childName === '.priority') { + return this.updatePriority(newChildNode); + } + else { + const namedNode = new NamedNode(childName, newChildNode); + let newChildren, newIndexMap; + if (newChildNode.isEmpty()) { + newChildren = this.children_.remove(childName); + newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_); + } + else { + newChildren = this.children_.insert(childName, newChildNode); + newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_); + } + const newPriority = newChildren.isEmpty() + ? EMPTY_NODE + : this.priorityNode_; + return new ChildrenNode(newChildren, newPriority, newIndexMap); + } + } + /** @inheritDoc */ + updateChild(path, newChildNode) { + const front = pathGetFront(path); + if (front === null) { + return newChildNode; + } + else { + util.assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path'); + const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode); + return this.updateImmediateChild(front, newImmediateChild); + } + } + /** @inheritDoc */ + isEmpty() { + return this.children_.isEmpty(); + } + /** @inheritDoc */ + numChildren() { + return this.children_.count(); + } + /** @inheritDoc */ + val(exportFormat) { + if (this.isEmpty()) { + return null; + } + const obj = {}; + let numKeys = 0, maxKey = 0, allIntegerKeys = true; + this.forEachChild(PRIORITY_INDEX, (key, childNode) => { + obj[key] = childNode.val(exportFormat); + numKeys++; + if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) { + maxKey = Math.max(maxKey, Number(key)); + } + else { + allIntegerKeys = false; + } + }); + if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) { + // convert to array. + const array = []; + // eslint-disable-next-line guard-for-in + for (const key in obj) { + array[key] = obj[key]; + } + return array; + } + else { + if (exportFormat && !this.getPriority().isEmpty()) { + obj['.priority'] = this.getPriority().val(); + } + return obj; + } + } + /** @inheritDoc */ + hash() { + if (this.lazyHash_ === null) { + let toHash = ''; + if (!this.getPriority().isEmpty()) { + toHash += + 'priority:' + + priorityHashText(this.getPriority().val()) + + ':'; + } + this.forEachChild(PRIORITY_INDEX, (key, childNode) => { + const childHash = childNode.hash(); + if (childHash !== '') { + toHash += ':' + key + ':' + childHash; + } + }); + this.lazyHash_ = toHash === '' ? '' : sha1(toHash); + } + return this.lazyHash_; + } + /** @inheritDoc */ + getPredecessorChildName(childName, childNode, index) { + const idx = this.resolveIndex_(index); + if (idx) { + const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode)); + return predecessor ? predecessor.name : null; + } + else { + return this.children_.getPredecessorKey(childName); + } + } + getFirstChildName(indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + const minKey = idx.minKey(); + return minKey && minKey.name; + } + else { + return this.children_.minKey(); + } + } + getFirstChild(indexDefinition) { + const minKey = this.getFirstChildName(indexDefinition); + if (minKey) { + return new NamedNode(minKey, this.children_.get(minKey)); + } + else { + return null; + } + } + /** + * Given an index, return the key name of the largest value we have, according to that index + */ + getLastChildName(indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + const maxKey = idx.maxKey(); + return maxKey && maxKey.name; + } + else { + return this.children_.maxKey(); + } + } + getLastChild(indexDefinition) { + const maxKey = this.getLastChildName(indexDefinition); + if (maxKey) { + return new NamedNode(maxKey, this.children_.get(maxKey)); + } + else { + return null; + } + } + forEachChild(index, action) { + const idx = this.resolveIndex_(index); + if (idx) { + return idx.inorderTraversal(wrappedNode => { + return action(wrappedNode.name, wrappedNode.node); + }); + } + else { + return this.children_.inorderTraversal(action); + } + } + getIterator(indexDefinition) { + return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition); + } + getIteratorFrom(startPost, indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + return idx.getIteratorFrom(startPost, key => key); + } + else { + const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap); + let next = iterator.peek(); + while (next != null && indexDefinition.compare(next, startPost) < 0) { + iterator.getNext(); + next = iterator.peek(); + } + return iterator; + } + } + getReverseIterator(indexDefinition) { + return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition); + } + getReverseIteratorFrom(endPost, indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + return idx.getReverseIteratorFrom(endPost, key => { + return key; + }); + } + else { + const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap); + let next = iterator.peek(); + while (next != null && indexDefinition.compare(next, endPost) > 0) { + iterator.getNext(); + next = iterator.peek(); + } + return iterator; + } + } + compareTo(other) { + if (this.isEmpty()) { + if (other.isEmpty()) { + return 0; + } + else { + return -1; + } + } + else if (other.isLeafNode() || other.isEmpty()) { + return 1; + } + else if (other === MAX_NODE) { + return -1; + } + else { + // Must be another node with children. + return 0; + } + } + withIndex(indexDefinition) { + if (indexDefinition === KEY_INDEX || + this.indexMap_.hasIndex(indexDefinition)) { + return this; + } + else { + const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_); + return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap); + } + } + isIndexed(index) { + return index === KEY_INDEX || this.indexMap_.hasIndex(index); + } + equals(other) { + if (other === this) { + return true; + } + else if (other.isLeafNode()) { + return false; + } + else { + const otherChildrenNode = other; + if (!this.getPriority().equals(otherChildrenNode.getPriority())) { + return false; + } + else if (this.children_.count() === otherChildrenNode.children_.count()) { + const thisIter = this.getIterator(PRIORITY_INDEX); + const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX); + let thisCurrent = thisIter.getNext(); + let otherCurrent = otherIter.getNext(); + while (thisCurrent && otherCurrent) { + if (thisCurrent.name !== otherCurrent.name || + !thisCurrent.node.equals(otherCurrent.node)) { + return false; + } + thisCurrent = thisIter.getNext(); + otherCurrent = otherIter.getNext(); + } + return thisCurrent === null && otherCurrent === null; + } + else { + return false; + } + } + } + /** + * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used + * instead. + * + */ + resolveIndex_(indexDefinition) { + if (indexDefinition === KEY_INDEX) { + return null; + } + else { + return this.indexMap_.get(indexDefinition.toString()); + } + } +} +ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/; +class MaxNode extends ChildrenNode { + constructor() { + super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default); + } + compareTo(other) { + if (other === this) { + return 0; + } + else { + return 1; + } + } + equals(other) { + // Not that we every compare it, but MAX_NODE is only ever equal to itself + return other === this; + } + getPriority() { + return this; + } + getImmediateChild(childName) { + return ChildrenNode.EMPTY_NODE; + } + isEmpty() { + return false; + } +} +/** + * Marker that will sort higher than any other snapshot. + */ +const MAX_NODE = new MaxNode(); +Object.defineProperties(NamedNode, { + MIN: { + value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE) + }, + MAX: { + value: new NamedNode(MAX_NAME, MAX_NODE) + } +}); +/** + * Reference Extensions + */ +KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE; +LeafNode.__childrenNodeConstructor = ChildrenNode; +setMaxNode$1(MAX_NODE); +setMaxNode(MAX_NODE); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const USE_HINZE = true; +/** + * Constructs a snapshot node representing the passed JSON and returns it. + * @param json - JSON to create a node for. + * @param priority - Optional priority to use. This will be ignored if the + * passed JSON contains a .priority property. + */ +function nodeFromJSON(json, priority = null) { + if (json === null) { + return ChildrenNode.EMPTY_NODE; + } + if (typeof json === 'object' && '.priority' in json) { + priority = json['.priority']; + } + util.assert(priority === null || + typeof priority === 'string' || + typeof priority === 'number' || + (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority); + if (typeof json === 'object' && '.value' in json && json['.value'] !== null) { + json = json['.value']; + } + // Valid leaf nodes include non-objects or server-value wrapper objects + if (typeof json !== 'object' || '.sv' in json) { + const jsonLeaf = json; + return new LeafNode(jsonLeaf, nodeFromJSON(priority)); + } + if (!(json instanceof Array) && USE_HINZE) { + const children = []; + let childrenHavePriority = false; + const hinzeJsonObj = json; + each(hinzeJsonObj, (key, child) => { + if (key.substring(0, 1) !== '.') { + // Ignore metadata nodes + const childNode = nodeFromJSON(child); + if (!childNode.isEmpty()) { + childrenHavePriority = + childrenHavePriority || !childNode.getPriority().isEmpty(); + children.push(new NamedNode(key, childNode)); + } + } + }); + if (children.length === 0) { + return ChildrenNode.EMPTY_NODE; + } + const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR); + if (childrenHavePriority) { + const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare()); + return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX })); + } + else { + return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default); + } + } + else { + let node = ChildrenNode.EMPTY_NODE; + each(json, (key, childData) => { + if (util.contains(json, key)) { + if (key.substring(0, 1) !== '.') { + // ignore metadata nodes. + const childNode = nodeFromJSON(childData); + if (childNode.isLeafNode() || !childNode.isEmpty()) { + node = node.updateImmediateChild(key, childNode); + } + } + } + }); + return node.updatePriority(nodeFromJSON(priority)); + } +} +setNodeFromJSON(nodeFromJSON); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class PathIndex extends Index { + constructor(indexPath_) { + super(); + this.indexPath_ = indexPath_; + util.assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key"); + } + extractChild(snap) { + return snap.getChild(this.indexPath_); + } + isDefinedOn(node) { + return !node.getChild(this.indexPath_).isEmpty(); + } + compare(a, b) { + const aChild = this.extractChild(a.node); + const bChild = this.extractChild(b.node); + const indexCmp = aChild.compareTo(bChild); + if (indexCmp === 0) { + return nameCompare(a.name, b.name); + } + else { + return indexCmp; + } + } + makePost(indexValue, name) { + const valueNode = nodeFromJSON(indexValue); + const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode); + return new NamedNode(name, node); + } + maxPost() { + const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE); + return new NamedNode(MAX_NAME, node); + } + toString() { + return pathSlice(this.indexPath_, 0).join('/'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ValueIndex extends Index { + compare(a, b) { + const indexCmp = a.node.compareTo(b.node); + if (indexCmp === 0) { + return nameCompare(a.name, b.name); + } + else { + return indexCmp; + } + } + isDefinedOn(node) { + return true; + } + indexedValueChanged(oldNode, newNode) { + return !oldNode.equals(newNode); + } + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } + maxPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MAX; + } + makePost(indexValue, name) { + const valueNode = nodeFromJSON(indexValue); + return new NamedNode(name, valueNode); + } + /** + * @returns String representation for inclusion in a query spec + */ + toString() { + return '.value'; + } +} +const VALUE_INDEX = new ValueIndex(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function changeValue(snapshotNode) { + return { type: "value" /* ChangeType.VALUE */, snapshotNode }; +} +function changeChildAdded(childName, snapshotNode) { + return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode, childName }; +} +function changeChildRemoved(childName, snapshotNode) { + return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode, childName }; +} +function changeChildChanged(childName, snapshotNode, oldSnap) { + return { + type: "child_changed" /* ChangeType.CHILD_CHANGED */, + snapshotNode, + childName, + oldSnap + }; +} +function changeChildMoved(childName, snapshotNode) { + return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode, childName }; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Doesn't really filter nodes but applies an index to the node and keeps track of any changes + */ +class IndexedFilter { + constructor(index_) { + this.index_ = index_; + } + updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) { + util.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated'); + const oldChild = snap.getImmediateChild(key); + // Check if anything actually changed. + if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) { + // There's an edge case where a child can enter or leave the view because affectedPath was set to null. + // In this case, affectedPath will appear null in both the old and new snapshots. So we need + // to avoid treating these cases as "nothing changed." + if (oldChild.isEmpty() === newChild.isEmpty()) { + // Nothing changed. + // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it. + //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.'); + return snap; + } + } + if (optChangeAccumulator != null) { + if (newChild.isEmpty()) { + if (snap.hasChild(key)) { + optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild)); + } + else { + util.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node'); + } + } + else if (oldChild.isEmpty()) { + optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild)); + } + else { + optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild)); + } + } + if (snap.isLeafNode() && newChild.isEmpty()) { + return snap; + } + else { + // Make sure the node is indexed + return snap.updateImmediateChild(key, newChild).withIndex(this.index_); + } + } + updateFullNode(oldSnap, newSnap, optChangeAccumulator) { + if (optChangeAccumulator != null) { + if (!oldSnap.isLeafNode()) { + oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => { + if (!newSnap.hasChild(key)) { + optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode)); + } + }); + } + if (!newSnap.isLeafNode()) { + newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => { + if (oldSnap.hasChild(key)) { + const oldChild = oldSnap.getImmediateChild(key); + if (!oldChild.equals(childNode)) { + optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild)); + } + } + else { + optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode)); + } + }); + } + } + return newSnap.withIndex(this.index_); + } + updatePriority(oldSnap, newPriority) { + if (oldSnap.isEmpty()) { + return ChildrenNode.EMPTY_NODE; + } + else { + return oldSnap.updatePriority(newPriority); + } + } + filtersNodes() { + return false; + } + getIndexedFilter() { + return this; + } + getIndex() { + return this.index_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node + */ +class RangedFilter { + constructor(params) { + this.indexedFilter_ = new IndexedFilter(params.getIndex()); + this.index_ = params.getIndex(); + this.startPost_ = RangedFilter.getStartPost_(params); + this.endPost_ = RangedFilter.getEndPost_(params); + this.startIsInclusive_ = !params.startAfterSet_; + this.endIsInclusive_ = !params.endBeforeSet_; + } + getStartPost() { + return this.startPost_; + } + getEndPost() { + return this.endPost_; + } + matches(node) { + const isWithinStart = this.startIsInclusive_ + ? this.index_.compare(this.getStartPost(), node) <= 0 + : this.index_.compare(this.getStartPost(), node) < 0; + const isWithinEnd = this.endIsInclusive_ + ? this.index_.compare(node, this.getEndPost()) <= 0 + : this.index_.compare(node, this.getEndPost()) < 0; + return isWithinStart && isWithinEnd; + } + updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) { + if (!this.matches(new NamedNode(key, newChild))) { + newChild = ChildrenNode.EMPTY_NODE; + } + return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator); + } + updateFullNode(oldSnap, newSnap, optChangeAccumulator) { + if (newSnap.isLeafNode()) { + // Make sure we have a children node with the correct index, not a leaf node; + newSnap = ChildrenNode.EMPTY_NODE; + } + let filtered = newSnap.withIndex(this.index_); + // Don't support priorities on queries + filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE); + const self = this; + newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => { + if (!self.matches(new NamedNode(key, childNode))) { + filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE); + } + }); + return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator); + } + updatePriority(oldSnap, newPriority) { + // Don't support priorities on queries + return oldSnap; + } + filtersNodes() { + return true; + } + getIndexedFilter() { + return this.indexedFilter_; + } + getIndex() { + return this.index_; + } + static getStartPost_(params) { + if (params.hasStart()) { + const startName = params.getIndexStartName(); + return params.getIndex().makePost(params.getIndexStartValue(), startName); + } + else { + return params.getIndex().minPost(); + } + } + static getEndPost_(params) { + if (params.hasEnd()) { + const endName = params.getIndexEndName(); + return params.getIndex().makePost(params.getIndexEndValue(), endName); + } + else { + return params.getIndex().maxPost(); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible + */ +class LimitedFilter { + constructor(params) { + this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node); + this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node); + this.withinStartPost = (node) => { + const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node); + return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0; + }; + this.withinEndPost = (node) => { + const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost()); + return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0; + }; + this.rangedFilter_ = new RangedFilter(params); + this.index_ = params.getIndex(); + this.limit_ = params.getLimit(); + this.reverse_ = !params.isViewFromLeft(); + this.startIsInclusive_ = !params.startAfterSet_; + this.endIsInclusive_ = !params.endBeforeSet_; + } + updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) { + if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) { + newChild = ChildrenNode.EMPTY_NODE; + } + if (snap.getImmediateChild(key).equals(newChild)) { + // No change + return snap; + } + else if (snap.numChildren() < this.limit_) { + return this.rangedFilter_ + .getIndexedFilter() + .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator); + } + else { + return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator); + } + } + updateFullNode(oldSnap, newSnap, optChangeAccumulator) { + let filtered; + if (newSnap.isLeafNode() || newSnap.isEmpty()) { + // Make sure we have a children node with the correct index, not a leaf node; + filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_); + } + else { + if (this.limit_ * 2 < newSnap.numChildren() && + newSnap.isIndexed(this.index_)) { + // Easier to build up a snapshot, since what we're given has more than twice the elements we want + filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_); + // anchor to the startPost, endPost, or last element as appropriate + let iterator; + if (this.reverse_) { + iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_); + } + else { + iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_); + } + let count = 0; + while (iterator.hasNext() && count < this.limit_) { + const next = iterator.getNext(); + if (!this.withinDirectionalStart(next)) { + // if we have not reached the start, skip to the next element + continue; + } + else if (!this.withinDirectionalEnd(next)) { + // if we have reached the end, stop adding elements + break; + } + else { + filtered = filtered.updateImmediateChild(next.name, next.node); + count++; + } + } + } + else { + // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one + filtered = newSnap.withIndex(this.index_); + // Don't support priorities on queries + filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE); + let iterator; + if (this.reverse_) { + iterator = filtered.getReverseIterator(this.index_); + } + else { + iterator = filtered.getIterator(this.index_); + } + let count = 0; + while (iterator.hasNext()) { + const next = iterator.getNext(); + const inRange = count < this.limit_ && + this.withinDirectionalStart(next) && + this.withinDirectionalEnd(next); + if (inRange) { + count++; + } + else { + filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE); + } + } + } + } + return this.rangedFilter_ + .getIndexedFilter() + .updateFullNode(oldSnap, filtered, optChangeAccumulator); + } + updatePriority(oldSnap, newPriority) { + // Don't support priorities on queries + return oldSnap; + } + filtersNodes() { + return true; + } + getIndexedFilter() { + return this.rangedFilter_.getIndexedFilter(); + } + getIndex() { + return this.index_; + } + fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) { + // TODO: rename all cache stuff etc to general snap terminology + let cmp; + if (this.reverse_) { + const indexCmp = this.index_.getCompare(); + cmp = (a, b) => indexCmp(b, a); + } + else { + cmp = this.index_.getCompare(); + } + const oldEventCache = snap; + util.assert(oldEventCache.numChildren() === this.limit_, ''); + const newChildNamedNode = new NamedNode(childKey, childSnap); + const windowBoundary = this.reverse_ + ? oldEventCache.getFirstChild(this.index_) + : oldEventCache.getLastChild(this.index_); + const inRange = this.rangedFilter_.matches(newChildNamedNode); + if (oldEventCache.hasChild(childKey)) { + const oldChildSnap = oldEventCache.getImmediateChild(childKey); + let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_); + while (nextChild != null && + (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) { + // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't + // been applied to the limited filter yet. Ignore this next child which will be updated later in + // the limited filter... + nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_); + } + const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode); + const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0; + if (remainsInWindow) { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap)); + } + return oldEventCache.updateImmediateChild(childKey, childSnap); + } + else { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap)); + } + const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE); + const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild); + if (nextChildInRange) { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node)); + } + return newEventCache.updateImmediateChild(nextChild.name, nextChild.node); + } + else { + return newEventCache; + } + } + } + else if (childSnap.isEmpty()) { + // we're deleting a node, but it was not in the window, so ignore it + return snap; + } + else if (inRange) { + if (cmp(windowBoundary, newChildNamedNode) >= 0) { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node)); + changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap)); + } + return oldEventCache + .updateImmediateChild(childKey, childSnap) + .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE); + } + else { + return snap; + } + } + else { + return snap; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a + * range to be returned for a particular location. It is assumed that validation of parameters is done at the + * user-facing API level, so it is not done here. + * + * @internal + */ +class QueryParams { + constructor() { + this.limitSet_ = false; + this.startSet_ = false; + this.startNameSet_ = false; + this.startAfterSet_ = false; // can only be true if startSet_ is true + this.endSet_ = false; + this.endNameSet_ = false; + this.endBeforeSet_ = false; // can only be true if endSet_ is true + this.limit_ = 0; + this.viewFrom_ = ''; + this.indexStartValue_ = null; + this.indexStartName_ = ''; + this.indexEndValue_ = null; + this.indexEndName_ = ''; + this.index_ = PRIORITY_INDEX; + } + hasStart() { + return this.startSet_; + } + /** + * @returns True if it would return from left. + */ + isViewFromLeft() { + if (this.viewFrom_ === '') { + // limit(), rather than limitToFirst or limitToLast was called. + // This means that only one of startSet_ and endSet_ is true. Use them + // to calculate which side of the view to anchor to. If neither is set, + // anchor to the end. + return this.startSet_; + } + else { + return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */; + } + } + /** + * Only valid to call if hasStart() returns true + */ + getIndexStartValue() { + util.assert(this.startSet_, 'Only valid if start has been set'); + return this.indexStartValue_; + } + /** + * Only valid to call if hasStart() returns true. + * Returns the starting key name for the range defined by these query parameters + */ + getIndexStartName() { + util.assert(this.startSet_, 'Only valid if start has been set'); + if (this.startNameSet_) { + return this.indexStartName_; + } + else { + return MIN_NAME; + } + } + hasEnd() { + return this.endSet_; + } + /** + * Only valid to call if hasEnd() returns true. + */ + getIndexEndValue() { + util.assert(this.endSet_, 'Only valid if end has been set'); + return this.indexEndValue_; + } + /** + * Only valid to call if hasEnd() returns true. + * Returns the end key name for the range defined by these query parameters + */ + getIndexEndName() { + util.assert(this.endSet_, 'Only valid if end has been set'); + if (this.endNameSet_) { + return this.indexEndName_; + } + else { + return MAX_NAME; + } + } + hasLimit() { + return this.limitSet_; + } + /** + * @returns True if a limit has been set and it has been explicitly anchored + */ + hasAnchoredLimit() { + return this.limitSet_ && this.viewFrom_ !== ''; + } + /** + * Only valid to call if hasLimit() returns true + */ + getLimit() { + util.assert(this.limitSet_, 'Only valid if limit has been set'); + return this.limit_; + } + getIndex() { + return this.index_; + } + loadsAllData() { + return !(this.startSet_ || this.endSet_ || this.limitSet_); + } + isDefault() { + return this.loadsAllData() && this.index_ === PRIORITY_INDEX; + } + copy() { + const copy = new QueryParams(); + copy.limitSet_ = this.limitSet_; + copy.limit_ = this.limit_; + copy.startSet_ = this.startSet_; + copy.startAfterSet_ = this.startAfterSet_; + copy.indexStartValue_ = this.indexStartValue_; + copy.startNameSet_ = this.startNameSet_; + copy.indexStartName_ = this.indexStartName_; + copy.endSet_ = this.endSet_; + copy.endBeforeSet_ = this.endBeforeSet_; + copy.indexEndValue_ = this.indexEndValue_; + copy.endNameSet_ = this.endNameSet_; + copy.indexEndName_ = this.indexEndName_; + copy.index_ = this.index_; + copy.viewFrom_ = this.viewFrom_; + return copy; + } +} +function queryParamsGetNodeFilter(queryParams) { + if (queryParams.loadsAllData()) { + return new IndexedFilter(queryParams.getIndex()); + } + else if (queryParams.hasLimit()) { + return new LimitedFilter(queryParams); + } + else { + return new RangedFilter(queryParams); + } +} +function queryParamsLimitToFirst(queryParams, newLimit) { + const newParams = queryParams.copy(); + newParams.limitSet_ = true; + newParams.limit_ = newLimit; + newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */; + return newParams; +} +function queryParamsLimitToLast(queryParams, newLimit) { + const newParams = queryParams.copy(); + newParams.limitSet_ = true; + newParams.limit_ = newLimit; + newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */; + return newParams; +} +function queryParamsStartAt(queryParams, indexValue, key) { + const newParams = queryParams.copy(); + newParams.startSet_ = true; + if (indexValue === undefined) { + indexValue = null; + } + newParams.indexStartValue_ = indexValue; + if (key != null) { + newParams.startNameSet_ = true; + newParams.indexStartName_ = key; + } + else { + newParams.startNameSet_ = false; + newParams.indexStartName_ = ''; + } + return newParams; +} +function queryParamsStartAfter(queryParams, indexValue, key) { + let params; + if (queryParams.index_ === KEY_INDEX || !!key) { + params = queryParamsStartAt(queryParams, indexValue, key); + } + else { + params = queryParamsStartAt(queryParams, indexValue, MAX_NAME); + } + params.startAfterSet_ = true; + return params; +} +function queryParamsEndAt(queryParams, indexValue, key) { + const newParams = queryParams.copy(); + newParams.endSet_ = true; + if (indexValue === undefined) { + indexValue = null; + } + newParams.indexEndValue_ = indexValue; + if (key !== undefined) { + newParams.endNameSet_ = true; + newParams.indexEndName_ = key; + } + else { + newParams.endNameSet_ = false; + newParams.indexEndName_ = ''; + } + return newParams; +} +function queryParamsEndBefore(queryParams, indexValue, key) { + let params; + if (queryParams.index_ === KEY_INDEX || !!key) { + params = queryParamsEndAt(queryParams, indexValue, key); + } + else { + params = queryParamsEndAt(queryParams, indexValue, MIN_NAME); + } + params.endBeforeSet_ = true; + return params; +} +function queryParamsOrderBy(queryParams, index) { + const newParams = queryParams.copy(); + newParams.index_ = index; + return newParams; +} +/** + * Returns a set of REST query string parameters representing this query. + * + * @returns query string parameters + */ +function queryParamsToRestQueryStringParameters(queryParams) { + const qs = {}; + if (queryParams.isDefault()) { + return qs; + } + let orderBy; + if (queryParams.index_ === PRIORITY_INDEX) { + orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */; + } + else if (queryParams.index_ === VALUE_INDEX) { + orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */; + } + else if (queryParams.index_ === KEY_INDEX) { + orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */; + } + else { + util.assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!'); + orderBy = queryParams.index_.toString(); + } + qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = util.stringify(orderBy); + if (queryParams.startSet_) { + const startParam = queryParams.startAfterSet_ + ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */ + : "startAt" /* REST_QUERY_CONSTANTS.START_AT */; + qs[startParam] = util.stringify(queryParams.indexStartValue_); + if (queryParams.startNameSet_) { + qs[startParam] += ',' + util.stringify(queryParams.indexStartName_); + } + } + if (queryParams.endSet_) { + const endParam = queryParams.endBeforeSet_ + ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */ + : "endAt" /* REST_QUERY_CONSTANTS.END_AT */; + qs[endParam] = util.stringify(queryParams.indexEndValue_); + if (queryParams.endNameSet_) { + qs[endParam] += ',' + util.stringify(queryParams.indexEndName_); + } + } + if (queryParams.limitSet_) { + if (queryParams.isViewFromLeft()) { + qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_; + } + else { + qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_; + } + } + return qs; +} +function queryParamsGetQueryObject(queryParams) { + const obj = {}; + if (queryParams.startSet_) { + obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] = + queryParams.indexStartValue_; + if (queryParams.startNameSet_) { + obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] = + queryParams.indexStartName_; + } + obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] = + !queryParams.startAfterSet_; + } + if (queryParams.endSet_) { + obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_; + if (queryParams.endNameSet_) { + obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_; + } + obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] = + !queryParams.endBeforeSet_; + } + if (queryParams.limitSet_) { + obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_; + let viewFrom = queryParams.viewFrom_; + if (viewFrom === '') { + if (queryParams.isViewFromLeft()) { + viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */; + } + else { + viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */; + } + } + obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom; + } + // For now, priority index is the default, so we only specify if it's some other index + if (queryParams.index_ !== PRIORITY_INDEX) { + obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString(); + } + return obj; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An implementation of ServerActions that communicates with the server via REST requests. + * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full + * persistent connection (using WebSockets or long-polling) + */ +class ReadonlyRestClient extends ServerActions { + reportStats(stats) { + throw new Error('Method not implemented.'); + } + static getListenId_(query, tag) { + if (tag !== undefined) { + return 'tag$' + tag; + } + else { + util.assert(query._queryParams.isDefault(), "should have a tag if it's not a default query."); + return query._path.toString(); + } + } + /** + * @param repoInfo_ - Data about the namespace we are connecting to + * @param onDataUpdate_ - A callback for new data from the server + */ + constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) { + super(); + this.repoInfo_ = repoInfo_; + this.onDataUpdate_ = onDataUpdate_; + this.authTokenProvider_ = authTokenProvider_; + this.appCheckTokenProvider_ = appCheckTokenProvider_; + /** @private {function(...[*])} */ + this.log_ = logWrapper('p:rest:'); + /** + * We don't actually need to track listens, except to prevent us calling an onComplete for a listen + * that's been removed. :-/ + */ + this.listens_ = {}; + } + /** @inheritDoc */ + listen(query, currentHashFn, tag, onComplete) { + const pathString = query._path.toString(); + this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier); + // Mark this listener so we can tell if it's removed. + const listenId = ReadonlyRestClient.getListenId_(query, tag); + const thisListen = {}; + this.listens_[listenId] = thisListen; + const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams); + this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => { + let data = result; + if (error === 404) { + data = null; + error = null; + } + if (error === null) { + this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag); + } + if (util.safeGet(this.listens_, listenId) === thisListen) { + let status; + if (!error) { + status = 'ok'; + } + else if (error === 401) { + status = 'permission_denied'; + } + else { + status = 'rest_error:' + error; + } + onComplete(status, null); + } + }); + } + /** @inheritDoc */ + unlisten(query, tag) { + const listenId = ReadonlyRestClient.getListenId_(query, tag); + delete this.listens_[listenId]; + } + get(query) { + const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams); + const pathString = query._path.toString(); + const deferred = new util.Deferred(); + this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => { + let data = result; + if (error === 404) { + data = null; + error = null; + } + if (error === null) { + this.onDataUpdate_(pathString, data, + /*isMerge=*/ false, + /*tag=*/ null); + deferred.resolve(data); + } + else { + deferred.reject(new Error(data)); + } + }); + return deferred.promise; + } + /** @inheritDoc */ + refreshAuthToken(token) { + // no-op since we just always call getToken. + } + /** + * Performs a REST request to the given path, with the provided query string parameters, + * and any auth credentials we have. + */ + restRequest_(pathString, queryStringParameters = {}, callback) { + queryStringParameters['format'] = 'export'; + return Promise.all([ + this.authTokenProvider_.getToken(/*forceRefresh=*/ false), + this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false) + ]).then(([authToken, appCheckToken]) => { + if (authToken && authToken.accessToken) { + queryStringParameters['auth'] = authToken.accessToken; + } + if (appCheckToken && appCheckToken.token) { + queryStringParameters['ac'] = appCheckToken.token; + } + const url = (this.repoInfo_.secure ? 'https://' : 'http://') + + this.repoInfo_.host + + pathString + + '?' + + 'ns=' + + this.repoInfo_.namespace + + util.querystring(queryStringParameters); + this.log_('Sending REST request for ' + url); + const xhr = new XMLHttpRequest(); + xhr.onreadystatechange = () => { + if (callback && xhr.readyState === 4) { + this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText); + let res = null; + if (xhr.status >= 200 && xhr.status < 300) { + try { + res = util.jsonEval(xhr.responseText); + } + catch (e) { + warn$1('Failed to parse JSON response for ' + + url + + ': ' + + xhr.responseText); + } + callback(null, res); + } + else { + // 401 and 404 are expected. + if (xhr.status !== 401 && xhr.status !== 404) { + warn$1('Got unsuccessful REST response for ' + + url + + ' Status: ' + + xhr.status); + } + callback(xhr.status); + } + callback = null; + } + }; + xhr.open('GET', url, /*asynchronous=*/ true); + xhr.send(); + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Mutable object which basically just stores a reference to the "latest" immutable snapshot. + */ +class SnapshotHolder { + constructor() { + this.rootNode_ = ChildrenNode.EMPTY_NODE; + } + getNode(path) { + return this.rootNode_.getChild(path); + } + updateSnapshot(path, newSnapshotNode) { + this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newSparseSnapshotTree() { + return { + value: null, + children: new Map() + }; +} +/** + * Stores the given node at the specified path. If there is already a node + * at a shallower path, it merges the new data into that snapshot node. + * + * @param path - Path to look up snapshot for. + * @param data - The new data, or null. + */ +function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) { + if (pathIsEmpty(path)) { + sparseSnapshotTree.value = data; + sparseSnapshotTree.children.clear(); + } + else if (sparseSnapshotTree.value !== null) { + sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data); + } + else { + const childKey = pathGetFront(path); + if (!sparseSnapshotTree.children.has(childKey)) { + sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree()); + } + const child = sparseSnapshotTree.children.get(childKey); + path = pathPopFront(path); + sparseSnapshotTreeRemember(child, path, data); + } +} +/** + * Purge the data at path from the cache. + * + * @param path - Path to look up snapshot for. + * @returns True if this node should now be removed. + */ +function sparseSnapshotTreeForget(sparseSnapshotTree, path) { + if (pathIsEmpty(path)) { + sparseSnapshotTree.value = null; + sparseSnapshotTree.children.clear(); + return true; + } + else { + if (sparseSnapshotTree.value !== null) { + if (sparseSnapshotTree.value.isLeafNode()) { + // We're trying to forget a node that doesn't exist + return false; + } + else { + const value = sparseSnapshotTree.value; + sparseSnapshotTree.value = null; + value.forEachChild(PRIORITY_INDEX, (key, tree) => { + sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree); + }); + return sparseSnapshotTreeForget(sparseSnapshotTree, path); + } + } + else if (sparseSnapshotTree.children.size > 0) { + const childKey = pathGetFront(path); + path = pathPopFront(path); + if (sparseSnapshotTree.children.has(childKey)) { + const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path); + if (safeToRemove) { + sparseSnapshotTree.children.delete(childKey); + } + } + return sparseSnapshotTree.children.size === 0; + } + else { + return true; + } + } +} +/** + * Recursively iterates through all of the stored tree and calls the + * callback on each one. + * + * @param prefixPath - Path to look up node for. + * @param func - The function to invoke for each tree. + */ +function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) { + if (sparseSnapshotTree.value !== null) { + func(prefixPath, sparseSnapshotTree.value); + } + else { + sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => { + const path = new Path(prefixPath.toString() + '/' + key); + sparseSnapshotTreeForEachTree(tree, path, func); + }); + } +} +/** + * Iterates through each immediate child and triggers the callback. + * Only seems to be used in tests. + * + * @param func - The function to invoke for each child. + */ +function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) { + sparseSnapshotTree.children.forEach((tree, key) => { + func(key, tree); + }); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns the delta from the previous call to get stats. + * + * @param collection_ - The collection to "listen" to. + */ +class StatsListener { + constructor(collection_) { + this.collection_ = collection_; + this.last_ = null; + } + get() { + const newStats = this.collection_.get(); + const delta = { ...newStats }; + if (this.last_) { + each(this.last_, (stat, value) => { + delta[stat] = delta[stat] - value; + }); + } + this.last_ = newStats; + return delta; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably +// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10 +// seconds to try to ensure the Firebase connection is established / settled. +const FIRST_STATS_MIN_TIME = 10 * 1000; +const FIRST_STATS_MAX_TIME = 30 * 1000; +// We'll continue to report stats on average every 5 minutes. +const REPORT_STATS_INTERVAL = 5 * 60 * 1000; +class StatsReporter { + constructor(collection, server_) { + this.server_ = server_; + this.statsToReport_ = {}; + this.statsListener_ = new StatsListener(collection); + const timeout = FIRST_STATS_MIN_TIME + + (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random(); + setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout)); + } + reportStats_() { + const stats = this.statsListener_.get(); + const reportedStats = {}; + let haveStatsToReport = false; + each(stats, (stat, value) => { + if (value > 0 && util.contains(this.statsToReport_, stat)) { + reportedStats[stat] = value; + haveStatsToReport = true; + } + }); + if (haveStatsToReport) { + this.server_.reportStats(reportedStats); + } + // queue our next run. + setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @enum + */ +var OperationType; +(function (OperationType) { + OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE"; + OperationType[OperationType["MERGE"] = 1] = "MERGE"; + OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE"; + OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE"; +})(OperationType || (OperationType = {})); +function newOperationSourceUser() { + return { + fromUser: true, + fromServer: false, + queryId: null, + tagged: false + }; +} +function newOperationSourceServer() { + return { + fromUser: false, + fromServer: true, + queryId: null, + tagged: false + }; +} +function newOperationSourceServerTaggedQuery(queryId) { + return { + fromUser: false, + fromServer: true, + queryId, + tagged: true + }; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class AckUserWrite { + /** + * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap. + */ + constructor( + /** @inheritDoc */ path, + /** @inheritDoc */ affectedTree, + /** @inheritDoc */ revert) { + this.path = path; + this.affectedTree = affectedTree; + this.revert = revert; + /** @inheritDoc */ + this.type = OperationType.ACK_USER_WRITE; + /** @inheritDoc */ + this.source = newOperationSourceUser(); + } + operationForChild(childName) { + if (!pathIsEmpty(this.path)) { + util.assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.'); + return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert); + } + else if (this.affectedTree.value != null) { + util.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.'); + // All child locations are affected as well; just return same operation. + return this; + } + else { + const childTree = this.affectedTree.subtree(new Path(childName)); + return new AckUserWrite(newEmptyPath(), childTree, this.revert); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ListenComplete { + constructor(source, path) { + this.source = source; + this.path = path; + /** @inheritDoc */ + this.type = OperationType.LISTEN_COMPLETE; + } + operationForChild(childName) { + if (pathIsEmpty(this.path)) { + return new ListenComplete(this.source, newEmptyPath()); + } + else { + return new ListenComplete(this.source, pathPopFront(this.path)); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Overwrite { + constructor(source, path, snap) { + this.source = source; + this.path = path; + this.snap = snap; + /** @inheritDoc */ + this.type = OperationType.OVERWRITE; + } + operationForChild(childName) { + if (pathIsEmpty(this.path)) { + return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName)); + } + else { + return new Overwrite(this.source, pathPopFront(this.path), this.snap); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Merge { + constructor( + /** @inheritDoc */ source, + /** @inheritDoc */ path, + /** @inheritDoc */ children) { + this.source = source; + this.path = path; + this.children = children; + /** @inheritDoc */ + this.type = OperationType.MERGE; + } + operationForChild(childName) { + if (pathIsEmpty(this.path)) { + const childTree = this.children.subtree(new Path(childName)); + if (childTree.isEmpty()) { + // This child is unaffected + return null; + } + else if (childTree.value) { + // We have a snapshot for the child in question. This becomes an overwrite of the child. + return new Overwrite(this.source, newEmptyPath(), childTree.value); + } + else { + // This is a merge at a deeper level + return new Merge(this.source, newEmptyPath(), childTree); + } + } + else { + util.assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation"); + return new Merge(this.source, pathPopFront(this.path), this.children); + } + } + toString() { + return ('Operation(' + + this.path + + ': ' + + this.source.toString() + + ' merge: ' + + this.children.toString() + + ')'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully + * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g. + * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks + * whether a node potentially had children removed due to a filter. + */ +class CacheNode { + constructor(node_, fullyInitialized_, filtered_) { + this.node_ = node_; + this.fullyInitialized_ = fullyInitialized_; + this.filtered_ = filtered_; + } + /** + * Returns whether this node was fully initialized with either server data or a complete overwrite by the client + */ + isFullyInitialized() { + return this.fullyInitialized_; + } + /** + * Returns whether this node is potentially missing children due to a filter applied to the node + */ + isFiltered() { + return this.filtered_; + } + isCompleteForPath(path) { + if (pathIsEmpty(path)) { + return this.isFullyInitialized() && !this.filtered_; + } + const childKey = pathGetFront(path); + return this.isCompleteForChild(childKey); + } + isCompleteForChild(key) { + return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key)); + } + getNode() { + return this.node_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An EventGenerator is used to convert "raw" changes (Change) as computed by the + * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges() + * for details. + * + */ +class EventGenerator { + constructor(query_) { + this.query_ = query_; + this.index_ = this.query_._queryParams.getIndex(); + } +} +/** + * Given a set of raw changes (no moved events and prevName not specified yet), and a set of + * EventRegistrations that should be notified of these changes, generate the actual events to be raised. + * + * Notes: + * - child_moved events will be synthesized at this time for any child_changed events that affect + * our index. + * - prevName will be calculated based on the index ordering. + */ +function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) { + const events = []; + const moves = []; + changes.forEach(change => { + if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ && + eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) { + moves.push(changeChildMoved(change.childName, change.snapshotNode)); + } + }); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache); + return events; +} +/** + * Given changes of a single change type, generate the corresponding events. + */ +function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) { + const filteredChanges = changes.filter(change => change.type === eventType); + filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b)); + filteredChanges.forEach(change => { + const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache); + registrations.forEach(registration => { + if (registration.respondsTo(change.type)) { + events.push(registration.createEvent(materializedChange, eventGenerator.query_)); + } + }); + }); +} +function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) { + if (change.type === 'value' || change.type === 'child_removed') { + return change; + } + else { + change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_); + return change; + } +} +function eventGeneratorCompareChanges(eventGenerator, a, b) { + if (a.childName == null || b.childName == null) { + throw util.assertionError('Should only compare child_ events.'); + } + const aWrapped = new NamedNode(a.childName, a.snapshotNode); + const bWrapped = new NamedNode(b.childName, b.snapshotNode); + return eventGenerator.index_.compare(aWrapped, bWrapped); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newViewCache(eventCache, serverCache) { + return { eventCache, serverCache }; +} +function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) { + return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache); +} +function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) { + return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered)); +} +function viewCacheGetCompleteEventSnap(viewCache) { + return viewCache.eventCache.isFullyInitialized() + ? viewCache.eventCache.getNode() + : null; +} +function viewCacheGetCompleteServerSnap(viewCache) { + return viewCache.serverCache.isFullyInitialized() + ? viewCache.serverCache.getNode() + : null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let emptyChildrenSingleton; +/** + * Singleton empty children collection. + * + */ +const EmptyChildren = () => { + if (!emptyChildrenSingleton) { + emptyChildrenSingleton = new SortedMap(stringCompare); + } + return emptyChildrenSingleton; +}; +/** + * A tree with immutable elements. + */ +class ImmutableTree { + static fromObject(obj) { + let tree = new ImmutableTree(null); + each(obj, (childPath, childSnap) => { + tree = tree.set(new Path(childPath), childSnap); + }); + return tree; + } + constructor(value, children = EmptyChildren()) { + this.value = value; + this.children = children; + } + /** + * True if the value is empty and there are no children + */ + isEmpty() { + return this.value === null && this.children.isEmpty(); + } + /** + * Given a path and predicate, return the first node and the path to that node + * where the predicate returns true. + * + * TODO Do a perf test -- If we're creating a bunch of `{path: value:}` + * objects on the way back out, it may be better to pass down a pathSoFar obj. + * + * @param relativePath - The remainder of the path + * @param predicate - The predicate to satisfy to return a node + */ + findRootMostMatchingPathAndValue(relativePath, predicate) { + if (this.value != null && predicate(this.value)) { + return { path: newEmptyPath(), value: this.value }; + } + else { + if (pathIsEmpty(relativePath)) { + return null; + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front); + if (child !== null) { + const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate); + if (childExistingPathAndValue != null) { + const fullPath = pathChild(new Path(front), childExistingPathAndValue.path); + return { path: fullPath, value: childExistingPathAndValue.value }; + } + else { + return null; + } + } + else { + return null; + } + } + } + } + /** + * Find, if it exists, the shortest subpath of the given path that points a defined + * value in the tree + */ + findRootMostValueAndPath(relativePath) { + return this.findRootMostMatchingPathAndValue(relativePath, () => true); + } + /** + * @returns The subtree at the given path + */ + subtree(relativePath) { + if (pathIsEmpty(relativePath)) { + return this; + } + else { + const front = pathGetFront(relativePath); + const childTree = this.children.get(front); + if (childTree !== null) { + return childTree.subtree(pathPopFront(relativePath)); + } + else { + return new ImmutableTree(null); + } + } + } + /** + * Sets a value at the specified path. + * + * @param relativePath - Path to set value at. + * @param toSet - Value to set. + * @returns Resulting tree. + */ + set(relativePath, toSet) { + if (pathIsEmpty(relativePath)) { + return new ImmutableTree(toSet, this.children); + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front) || new ImmutableTree(null); + const newChild = child.set(pathPopFront(relativePath), toSet); + const newChildren = this.children.insert(front, newChild); + return new ImmutableTree(this.value, newChildren); + } + } + /** + * Removes the value at the specified path. + * + * @param relativePath - Path to value to remove. + * @returns Resulting tree. + */ + remove(relativePath) { + if (pathIsEmpty(relativePath)) { + if (this.children.isEmpty()) { + return new ImmutableTree(null); + } + else { + return new ImmutableTree(null, this.children); + } + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front); + if (child) { + const newChild = child.remove(pathPopFront(relativePath)); + let newChildren; + if (newChild.isEmpty()) { + newChildren = this.children.remove(front); + } + else { + newChildren = this.children.insert(front, newChild); + } + if (this.value === null && newChildren.isEmpty()) { + return new ImmutableTree(null); + } + else { + return new ImmutableTree(this.value, newChildren); + } + } + else { + return this; + } + } + } + /** + * Gets a value from the tree. + * + * @param relativePath - Path to get value for. + * @returns Value at path, or null. + */ + get(relativePath) { + if (pathIsEmpty(relativePath)) { + return this.value; + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front); + if (child) { + return child.get(pathPopFront(relativePath)); + } + else { + return null; + } + } + } + /** + * Replace the subtree at the specified path with the given new tree. + * + * @param relativePath - Path to replace subtree for. + * @param newTree - New tree. + * @returns Resulting tree. + */ + setTree(relativePath, newTree) { + if (pathIsEmpty(relativePath)) { + return newTree; + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front) || new ImmutableTree(null); + const newChild = child.setTree(pathPopFront(relativePath), newTree); + let newChildren; + if (newChild.isEmpty()) { + newChildren = this.children.remove(front); + } + else { + newChildren = this.children.insert(front, newChild); + } + return new ImmutableTree(this.value, newChildren); + } + } + /** + * Performs a depth first fold on this tree. Transforms a tree into a single + * value, given a function that operates on the path to a node, an optional + * current value, and a map of child names to folded subtrees + */ + fold(fn) { + return this.fold_(newEmptyPath(), fn); + } + /** + * Recursive helper for public-facing fold() method + */ + fold_(pathSoFar, fn) { + const accum = {}; + this.children.inorderTraversal((childKey, childTree) => { + accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn); + }); + return fn(pathSoFar, this.value, accum); + } + /** + * Find the first matching value on the given path. Return the result of applying f to it. + */ + findOnPath(path, f) { + return this.findOnPath_(path, newEmptyPath(), f); + } + findOnPath_(pathToFollow, pathSoFar, f) { + const result = this.value ? f(pathSoFar, this.value) : false; + if (result) { + return result; + } + else { + if (pathIsEmpty(pathToFollow)) { + return null; + } + else { + const front = pathGetFront(pathToFollow); + const nextChild = this.children.get(front); + if (nextChild) { + return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f); + } + else { + return null; + } + } + } + } + foreachOnPath(path, f) { + return this.foreachOnPath_(path, newEmptyPath(), f); + } + foreachOnPath_(pathToFollow, currentRelativePath, f) { + if (pathIsEmpty(pathToFollow)) { + return this; + } + else { + if (this.value) { + f(currentRelativePath, this.value); + } + const front = pathGetFront(pathToFollow); + const nextChild = this.children.get(front); + if (nextChild) { + return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f); + } + else { + return new ImmutableTree(null); + } + } + } + /** + * Calls the given function for each node in the tree that has a value. + * + * @param f - A function to be called with the path from the root of the tree to + * a node, and the value at that node. Called in depth-first order. + */ + foreach(f) { + this.foreach_(newEmptyPath(), f); + } + foreach_(currentRelativePath, f) { + this.children.inorderTraversal((childName, childTree) => { + childTree.foreach_(pathChild(currentRelativePath, childName), f); + }); + if (this.value) { + f(currentRelativePath, this.value); + } + } + foreachChild(f) { + this.children.inorderTraversal((childName, childTree) => { + if (childTree.value) { + f(childName, childTree.value); + } + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with + * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write + * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write + * to reflect the write added. + */ +class CompoundWrite { + constructor(writeTree_) { + this.writeTree_ = writeTree_; + } + static empty() { + return new CompoundWrite(new ImmutableTree(null)); + } +} +function compoundWriteAddWrite(compoundWrite, path, node) { + if (pathIsEmpty(path)) { + return new CompoundWrite(new ImmutableTree(node)); + } + else { + const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path); + if (rootmost != null) { + const rootMostPath = rootmost.path; + let value = rootmost.value; + const relativePath = newRelativePath(rootMostPath, path); + value = value.updateChild(relativePath, node); + return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value)); + } + else { + const subtree = new ImmutableTree(node); + const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree); + return new CompoundWrite(newWriteTree); + } + } +} +function compoundWriteAddWrites(compoundWrite, path, updates) { + let newWrite = compoundWrite; + each(updates, (childKey, node) => { + newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node); + }); + return newWrite; +} +/** + * Will remove a write at the given path and deeper paths. This will not modify a write at a higher + * location, which must be removed by calling this method with that path. + * + * @param compoundWrite - The CompoundWrite to remove. + * @param path - The path at which a write and all deeper writes should be removed + * @returns The new CompoundWrite with the removed path + */ +function compoundWriteRemoveWrite(compoundWrite, path) { + if (pathIsEmpty(path)) { + return CompoundWrite.empty(); + } + else { + const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null)); + return new CompoundWrite(newWriteTree); + } +} +/** + * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be + * considered "complete". + * + * @param compoundWrite - The CompoundWrite to check. + * @param path - The path to check for + * @returns Whether there is a complete write at that path + */ +function compoundWriteHasCompleteWrite(compoundWrite, path) { + return compoundWriteGetCompleteNode(compoundWrite, path) != null; +} +/** + * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate + * writes from deeper paths, but will return child nodes from a more shallow path. + * + * @param compoundWrite - The CompoundWrite to get the node from. + * @param path - The path to get a complete write + * @returns The node if complete at that path, or null otherwise. + */ +function compoundWriteGetCompleteNode(compoundWrite, path) { + const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path); + if (rootmost != null) { + return compoundWrite.writeTree_ + .get(rootmost.path) + .getChild(newRelativePath(rootmost.path, path)); + } + else { + return null; + } +} +/** + * Returns all children that are guaranteed to be a complete overwrite. + * + * @param compoundWrite - The CompoundWrite to get children from. + * @returns A list of all complete children. + */ +function compoundWriteGetCompleteChildren(compoundWrite) { + const children = []; + const node = compoundWrite.writeTree_.value; + if (node != null) { + // If it's a leaf node, it has no children; so nothing to do. + if (!node.isLeafNode()) { + node.forEachChild(PRIORITY_INDEX, (childName, childNode) => { + children.push(new NamedNode(childName, childNode)); + }); + } + } + else { + compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => { + if (childTree.value != null) { + children.push(new NamedNode(childName, childTree.value)); + } + }); + } + return children; +} +function compoundWriteChildCompoundWrite(compoundWrite, path) { + if (pathIsEmpty(path)) { + return compoundWrite; + } + else { + const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path); + if (shadowingNode != null) { + return new CompoundWrite(new ImmutableTree(shadowingNode)); + } + else { + return new CompoundWrite(compoundWrite.writeTree_.subtree(path)); + } + } +} +/** + * Returns true if this CompoundWrite is empty and therefore does not modify any nodes. + * @returns Whether this CompoundWrite is empty + */ +function compoundWriteIsEmpty(compoundWrite) { + return compoundWrite.writeTree_.isEmpty(); +} +/** + * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the + * node + * @param node - The node to apply this CompoundWrite to + * @returns The node with all writes applied + */ +function compoundWriteApply(compoundWrite, node) { + return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node); +} +function applySubtreeWrite(relativePath, writeTree, node) { + if (writeTree.value != null) { + // Since there a write is always a leaf, we're done here + return node.updateChild(relativePath, writeTree.value); + } + else { + let priorityWrite = null; + writeTree.children.inorderTraversal((childKey, childTree) => { + if (childKey === '.priority') { + // Apply priorities at the end so we don't update priorities for either empty nodes or forget + // to apply priorities to empty nodes that are later filled + util.assert(childTree.value !== null, 'Priority writes must always be leaf nodes'); + priorityWrite = childTree.value; + } + else { + node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node); + } + }); + // If there was a priority write, we only apply it if the node is not empty + if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) { + node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite); + } + return node; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path. + * + */ +function writeTreeChildWrites(writeTree, path) { + return newWriteTreeRef(path, writeTree); +} +/** + * Record a new overwrite from user code. + * + * @param visible - This is set to false by some transactions. It should be excluded from event caches + */ +function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) { + util.assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones'); + if (visible === undefined) { + visible = true; + } + writeTree.allWrites.push({ + path, + snap, + writeId, + visible + }); + if (visible) { + writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap); + } + writeTree.lastWriteId = writeId; +} +/** + * Record a new merge from user code. + */ +function writeTreeAddMerge(writeTree, path, changedChildren, writeId) { + util.assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones'); + writeTree.allWrites.push({ + path, + children: changedChildren, + writeId, + visible: true + }); + writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren); + writeTree.lastWriteId = writeId; +} +function writeTreeGetWrite(writeTree, writeId) { + for (let i = 0; i < writeTree.allWrites.length; i++) { + const record = writeTree.allWrites[i]; + if (record.writeId === writeId) { + return record; + } + } + return null; +} +/** + * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates + * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate. + * + * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise + * events as a result). + */ +function writeTreeRemoveWrite(writeTree, writeId) { + // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied + // out of order. + //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId; + //assert(validClear, "Either we don't have this write, or it's the first one in the queue"); + const idx = writeTree.allWrites.findIndex(s => { + return s.writeId === writeId; + }); + util.assert(idx >= 0, 'removeWrite called with nonexistent writeId.'); + const writeToRemove = writeTree.allWrites[idx]; + writeTree.allWrites.splice(idx, 1); + let removedWriteWasVisible = writeToRemove.visible; + let removedWriteOverlapsWithOtherWrites = false; + let i = writeTree.allWrites.length - 1; + while (removedWriteWasVisible && i >= 0) { + const currentWrite = writeTree.allWrites[i]; + if (currentWrite.visible) { + if (i >= idx && + writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) { + // The removed write was completely shadowed by a subsequent write. + removedWriteWasVisible = false; + } + else if (pathContains(writeToRemove.path, currentWrite.path)) { + // Either we're covering some writes or they're covering part of us (depending on which came first). + removedWriteOverlapsWithOtherWrites = true; + } + } + i--; + } + if (!removedWriteWasVisible) { + return false; + } + else if (removedWriteOverlapsWithOtherWrites) { + // There's some shadowing going on. Just rebuild the visible writes from scratch. + writeTreeResetTree_(writeTree); + return true; + } + else { + // There's no shadowing. We can safely just remove the write(s) from visibleWrites. + if (writeToRemove.snap) { + writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path); + } + else { + const children = writeToRemove.children; + each(children, (childName) => { + writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName)); + }); + } + return true; + } +} +function writeTreeRecordContainsPath_(writeRecord, path) { + if (writeRecord.snap) { + return pathContains(writeRecord.path, path); + } + else { + for (const childName in writeRecord.children) { + if (writeRecord.children.hasOwnProperty(childName) && + pathContains(pathChild(writeRecord.path, childName), path)) { + return true; + } + } + return false; + } +} +/** + * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots + */ +function writeTreeResetTree_(writeTree) { + writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath()); + if (writeTree.allWrites.length > 0) { + writeTree.lastWriteId = + writeTree.allWrites[writeTree.allWrites.length - 1].writeId; + } + else { + writeTree.lastWriteId = -1; + } +} +/** + * The default filter used when constructing the tree. Keep everything that's visible. + */ +function writeTreeDefaultFilter_(write) { + return write.visible; +} +/** + * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of + * event data at that path. + */ +function writeTreeLayerTree_(writes, filter, treeRoot) { + let compoundWrite = CompoundWrite.empty(); + for (let i = 0; i < writes.length; ++i) { + const write = writes[i]; + // Theory, a later set will either: + // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction + // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction + if (filter(write)) { + const writePath = write.path; + let relativePath; + if (write.snap) { + if (pathContains(treeRoot, writePath)) { + relativePath = newRelativePath(treeRoot, writePath); + compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap); + } + else if (pathContains(writePath, treeRoot)) { + relativePath = newRelativePath(writePath, treeRoot); + compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath)); + } + else ; + } + else if (write.children) { + if (pathContains(treeRoot, writePath)) { + relativePath = newRelativePath(treeRoot, writePath); + compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children); + } + else if (pathContains(writePath, treeRoot)) { + relativePath = newRelativePath(writePath, treeRoot); + if (pathIsEmpty(relativePath)) { + compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children); + } + else { + const child = util.safeGet(write.children, pathGetFront(relativePath)); + if (child) { + // There exists a child in this node that matches the root path + const deepNode = child.getChild(pathPopFront(relativePath)); + compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode); + } + } + } + else ; + } + else { + throw util.assertionError('WriteRecord should have .snap or .children'); + } + } + } + return compoundWrite; +} +/** + * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden + * writes), attempt to calculate a complete snapshot for the given path + * + * @param writeIdsToExclude - An optional set to be excluded + * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false + */ +function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) { + if (!writeIdsToExclude && !includeHiddenWrites) { + const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath); + if (shadowingNode != null) { + return shadowingNode; + } + else { + const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + if (compoundWriteIsEmpty(subMerge)) { + return completeServerCache; + } + else if (completeServerCache == null && + !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) { + // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow + return null; + } + else { + const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE; + return compoundWriteApply(subMerge, layeredCache); + } + } + } + else { + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) { + return completeServerCache; + } + else { + // If the server cache is null, and we don't have a complete cache, we need to return null + if (!includeHiddenWrites && + completeServerCache == null && + !compoundWriteHasCompleteWrite(merge, newEmptyPath())) { + return null; + } + else { + const filter = function (write) { + return ((write.visible || includeHiddenWrites) && + (!writeIdsToExclude || + !~writeIdsToExclude.indexOf(write.writeId)) && + (pathContains(write.path, treePath) || + pathContains(treePath, write.path))); + }; + const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath); + const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE; + return compoundWriteApply(mergeAtPath, layeredCache); + } + } + } +} +/** + * With optional, underlying server data, attempt to return a children node of children that we have complete data for. + * Used when creating new views, to pre-fill their complete event children snapshot. + */ +function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) { + let completeChildren = ChildrenNode.EMPTY_NODE; + const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath); + if (topLevelSet) { + if (!topLevelSet.isLeafNode()) { + // we're shadowing everything. Return the children. + topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => { + completeChildren = completeChildren.updateImmediateChild(childName, childSnap); + }); + } + return completeChildren; + } + else if (completeServerChildren) { + // Layer any children we have on top of this + // We know we don't have a top-level set, so just enumerate existing children + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => { + const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode); + completeChildren = completeChildren.updateImmediateChild(childName, node); + }); + // Add any complete children we have from the set + compoundWriteGetCompleteChildren(merge).forEach(namedNode => { + completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node); + }); + return completeChildren; + } + else { + // We don't have anything to layer on top of. Layer on any children we have + // Note that we can return an empty snap if we have a defined delete + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + compoundWriteGetCompleteChildren(merge).forEach(namedNode => { + completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node); + }); + return completeChildren; + } +} +/** + * Given that the underlying server data has updated, determine what, if anything, needs to be + * applied to the event cache. + * + * Possibilities: + * + * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data + * + * 2. Some write is completely shadowing. No events to be raised + * + * 3. Is partially shadowed. Events + * + * Either existingEventSnap or existingServerSnap must exist + */ +function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) { + util.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist'); + const path = pathChild(treePath, childPath); + if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) { + // At this point we can probably guarantee that we're in case 2, meaning no events + // May need to check visibility while doing the findRootMostValueAndPath call + return null; + } + else { + // No complete shadowing. We're either partially shadowing or not shadowing at all. + const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path); + if (compoundWriteIsEmpty(childMerge)) { + // We're not shadowing at all. Case 1 + return existingServerSnap.getChild(childPath); + } + else { + // This could be more efficient if the serverNode + updates doesn't change the eventSnap + // However this is tricky to find out, since user updates don't necessary change the server + // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server + // adds nodes, but doesn't change any existing writes. It is therefore not enough to + // only check if the updates change the serverNode. + // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case? + return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath)); + } + } +} +/** + * Returns a complete child for a given server snap after applying all user writes or null if there is no + * complete child for this ChildKey. + */ +function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) { + const path = pathChild(treePath, childKey); + const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path); + if (shadowingNode != null) { + return shadowingNode; + } + else { + if (existingServerSnap.isCompleteForChild(childKey)) { + const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path); + return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey)); + } + else { + return null; + } + } +} +/** + * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at + * a higher path, this will return the child of that write relative to the write and this path. + * Returns null if there is no write at this path. + */ +function writeTreeShadowingWrite(writeTree, path) { + return compoundWriteGetCompleteNode(writeTree.visibleWrites, path); +} +/** + * This method is used when processing child remove events on a query. If we can, we pull in children that were outside + * the window, but may now be in the window. + */ +function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) { + let toIterate; + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath()); + if (shadowingNode != null) { + toIterate = shadowingNode; + } + else if (completeServerData != null) { + toIterate = compoundWriteApply(merge, completeServerData); + } + else { + // no children to iterate on + return []; + } + toIterate = toIterate.withIndex(index); + if (!toIterate.isEmpty() && !toIterate.isLeafNode()) { + const nodes = []; + const cmp = index.getCompare(); + const iter = reverse + ? toIterate.getReverseIteratorFrom(startPost, index) + : toIterate.getIteratorFrom(startPost, index); + let next = iter.getNext(); + while (next && nodes.length < count) { + if (cmp(next, startPost) !== 0) { + nodes.push(next); + } + next = iter.getNext(); + } + return nodes; + } + else { + return []; + } +} +function newWriteTree() { + return { + visibleWrites: CompoundWrite.empty(), + allWrites: [], + lastWriteId: -1 + }; +} +/** + * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used + * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node + * can lead to a more expensive calculation. + * + * @param writeIdsToExclude - Optional writes to exclude. + * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false + */ +function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) { + return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites); +} +/** + * If possible, returns a children node containing all of the complete children we have data for. The returned data is a + * mix of the given server data and write data. + * + */ +function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) { + return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren); +} +/** + * Given that either the underlying server data has updated or the outstanding writes have updated, determine what, + * if anything, needs to be applied to the event cache. + * + * Possibilities: + * + * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data + * + * 2. Some write is completely shadowing. No events to be raised + * + * 3. Is partially shadowed. Events should be raised + * + * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert + * + * + */ +function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) { + return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap); +} +/** + * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at + * a higher path, this will return the child of that write relative to the write and this path. + * Returns null if there is no write at this path. + * + */ +function writeTreeRefShadowingWrite(writeTreeRef, path) { + return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path)); +} +/** + * This method is used when processing child remove events on a query. If we can, we pull in children that were outside + * the window, but may now be in the window + */ +function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) { + return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index); +} +/** + * Returns a complete child for a given server snap after applying all user writes or null if there is no + * complete child for this ChildKey. + */ +function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) { + return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache); +} +/** + * Return a WriteTreeRef for a child. + */ +function writeTreeRefChild(writeTreeRef, childName) { + return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree); +} +function newWriteTreeRef(path, writeTree) { + return { + treePath: path, + writeTree + }; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ChildChangeAccumulator { + constructor() { + this.changeMap = new Map(); + } + trackChildChange(change) { + const type = change.type; + const childKey = change.childName; + util.assert(type === "child_added" /* ChangeType.CHILD_ADDED */ || + type === "child_changed" /* ChangeType.CHILD_CHANGED */ || + type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking'); + util.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.'); + const oldChange = this.changeMap.get(childKey); + if (oldChange) { + const oldType = oldChange.type; + if (type === "child_added" /* ChangeType.CHILD_ADDED */ && + oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) { + this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode)); + } + else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ && + oldType === "child_added" /* ChangeType.CHILD_ADDED */) { + this.changeMap.delete(childKey); + } + else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ && + oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) { + this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap)); + } + else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ && + oldType === "child_added" /* ChangeType.CHILD_ADDED */) { + this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode)); + } + else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ && + oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) { + this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap)); + } + else { + throw util.assertionError('Illegal combination of changes: ' + + change + + ' occurred after ' + + oldChange); + } + } + else { + this.changeMap.set(childKey, change); + } + } + getChanges() { + return Array.from(this.changeMap.values()); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An implementation of CompleteChildSource that never returns any additional children + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class NoCompleteChildSource_ { + getCompleteChild(childKey) { + return null; + } + getChildAfterChild(index, child, reverse) { + return null; + } +} +/** + * Singleton instance. + */ +const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_(); +/** + * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or + * old event caches available to calculate complete children. + */ +class WriteTreeCompleteChildSource { + constructor(writes_, viewCache_, optCompleteServerCache_ = null) { + this.writes_ = writes_; + this.viewCache_ = viewCache_; + this.optCompleteServerCache_ = optCompleteServerCache_; + } + getCompleteChild(childKey) { + const node = this.viewCache_.eventCache; + if (node.isCompleteForChild(childKey)) { + return node.getNode().getImmediateChild(childKey); + } + else { + const serverNode = this.optCompleteServerCache_ != null + ? new CacheNode(this.optCompleteServerCache_, true, false) + : this.viewCache_.serverCache; + return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode); + } + } + getChildAfterChild(index, child, reverse) { + const completeServerData = this.optCompleteServerCache_ != null + ? this.optCompleteServerCache_ + : viewCacheGetCompleteServerSnap(this.viewCache_); + const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index); + if (nodes.length === 0) { + return null; + } + else { + return nodes[0]; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newViewProcessor(filter) { + return { filter }; +} +function viewProcessorAssertIndexed(viewProcessor, viewCache) { + util.assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed'); + util.assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed'); +} +function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) { + const accumulator = new ChildChangeAccumulator(); + let newViewCache, filterServerNode; + if (operation.type === OperationType.OVERWRITE) { + const overwrite = operation; + if (overwrite.source.fromUser) { + newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator); + } + else { + util.assert(overwrite.source.fromServer, 'Unknown source.'); + // We filter the node if it's a tagged update or the node has been previously filtered and the + // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered + // again + filterServerNode = + overwrite.source.tagged || + (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path)); + newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator); + } + } + else if (operation.type === OperationType.MERGE) { + const merge = operation; + if (merge.source.fromUser) { + newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator); + } + else { + util.assert(merge.source.fromServer, 'Unknown source.'); + // We filter the node if it's a tagged update or the node has been previously filtered + filterServerNode = + merge.source.tagged || oldViewCache.serverCache.isFiltered(); + newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator); + } + } + else if (operation.type === OperationType.ACK_USER_WRITE) { + const ackUserWrite = operation; + if (!ackUserWrite.revert) { + newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator); + } + else { + newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator); + } + } + else if (operation.type === OperationType.LISTEN_COMPLETE) { + newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator); + } + else { + throw util.assertionError('Unknown operation type: ' + operation.type); + } + const changes = accumulator.getChanges(); + viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes); + return { viewCache: newViewCache, changes }; +} +function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) { + const eventSnap = newViewCache.eventCache; + if (eventSnap.isFullyInitialized()) { + const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty(); + const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache); + if (accumulator.length > 0 || + !oldViewCache.eventCache.isFullyInitialized() || + (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) || + !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) { + accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache))); + } + } +} +function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) { + const oldEventSnap = viewCache.eventCache; + if (writeTreeRefShadowingWrite(writesCache, changePath) != null) { + // we have a shadowing write, ignore changes + return viewCache; + } + else { + let newEventCache, serverNode; + if (pathIsEmpty(changePath)) { + // TODO: figure out how this plays with "sliding ack windows" + util.assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data'); + if (viewCache.serverCache.isFiltered()) { + // We need to special case this, because we need to only apply writes to complete children, or + // we might end up raising events for incomplete children. If the server data is filtered deep + // writes cannot be guaranteed to be complete + const serverCache = viewCacheGetCompleteServerSnap(viewCache); + const completeChildren = serverCache instanceof ChildrenNode + ? serverCache + : ChildrenNode.EMPTY_NODE; + const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren); + newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator); + } + else { + const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache)); + newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator); + } + } + else { + const childKey = pathGetFront(changePath); + if (childKey === '.priority') { + util.assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components"); + const oldEventNode = oldEventSnap.getNode(); + serverNode = viewCache.serverCache.getNode(); + // we might have overwrites for this priority + const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode); + if (updatedPriority != null) { + newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority); + } + else { + // priority didn't change, keep old node + newEventCache = oldEventSnap.getNode(); + } + } + else { + const childChangePath = pathPopFront(changePath); + // update child + let newEventChild; + if (oldEventSnap.isCompleteForChild(childKey)) { + serverNode = viewCache.serverCache.getNode(); + const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode); + if (eventChildUpdate != null) { + newEventChild = oldEventSnap + .getNode() + .getImmediateChild(childKey) + .updateChild(childChangePath, eventChildUpdate); + } + else { + // Nothing changed, just keep the old child + newEventChild = oldEventSnap.getNode().getImmediateChild(childKey); + } + } + else { + newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache); + } + if (newEventChild != null) { + newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator); + } + else { + // no complete child available or no change + newEventCache = oldEventSnap.getNode(); + } + } + } + return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes()); + } +} +function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) { + const oldServerSnap = oldViewCache.serverCache; + let newServerCache; + const serverFilter = filterServerNode + ? viewProcessor.filter + : viewProcessor.filter.getIndexedFilter(); + if (pathIsEmpty(changePath)) { + newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null); + } + else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) { + // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update + const newServerNode = oldServerSnap + .getNode() + .updateChild(changePath, changedSnap); + newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null); + } + else { + const childKey = pathGetFront(changePath); + if (!oldServerSnap.isCompleteForPath(changePath) && + pathGetLength(changePath) > 1) { + // We don't update incomplete nodes with updates intended for other listeners + return oldViewCache; + } + const childChangePath = pathPopFront(changePath); + const childNode = oldServerSnap.getNode().getImmediateChild(childKey); + const newChildNode = childNode.updateChild(childChangePath, changedSnap); + if (childKey === '.priority') { + newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode); + } + else { + newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null); + } + } + const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes()); + const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache); + return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator); +} +function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) { + const oldEventSnap = oldViewCache.eventCache; + let newViewCache, newEventCache; + const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache); + if (pathIsEmpty(changePath)) { + newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator); + newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes()); + } + else { + const childKey = pathGetFront(changePath); + if (childKey === '.priority') { + newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap); + newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered()); + } + else { + const childChangePath = pathPopFront(changePath); + const oldChild = oldEventSnap.getNode().getImmediateChild(childKey); + let newChild; + if (pathIsEmpty(childChangePath)) { + // Child overwrite, we can replace the child + newChild = changedSnap; + } + else { + const childNode = source.getCompleteChild(childKey); + if (childNode != null) { + if (pathGetBack(childChangePath) === '.priority' && + childNode.getChild(pathParent(childChangePath)).isEmpty()) { + // This is a priority update on an empty node. If this node exists on the server, the + // server will send down the priority in the update, so ignore for now + newChild = childNode; + } + else { + newChild = childNode.updateChild(childChangePath, changedSnap); + } + } + else { + // There is no complete child node available + newChild = ChildrenNode.EMPTY_NODE; + } + } + if (!oldChild.equals(newChild)) { + const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator); + newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes()); + } + else { + newViewCache = oldViewCache; + } + } + } + return newViewCache; +} +function viewProcessorCacheHasChild(viewCache, childKey) { + return viewCache.eventCache.isCompleteForChild(childKey); +} +function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) { + // HACK: In the case of a limit query, there may be some changes that bump things out of the + // window leaving room for new items. It's important we process these changes first, so we + // iterate the changes twice, first processing any that affect items currently in view. + // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server + // and event snap. I'm not sure if this will result in edge cases when a child is in one but + // not the other. + let curViewCache = viewCache; + changedChildren.foreach((relativePath, childNode) => { + const writePath = pathChild(path, relativePath); + if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) { + curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator); + } + }); + changedChildren.foreach((relativePath, childNode) => { + const writePath = pathChild(path, relativePath); + if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) { + curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator); + } + }); + return curViewCache; +} +function viewProcessorApplyMerge(viewProcessor, node, merge) { + merge.foreach((relativePath, childNode) => { + node = node.updateChild(relativePath, childNode); + }); + return node; +} +function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) { + // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and + // wait for the complete data update coming soon. + if (viewCache.serverCache.getNode().isEmpty() && + !viewCache.serverCache.isFullyInitialized()) { + return viewCache; + } + // HACK: In the case of a limit query, there may be some changes that bump things out of the + // window leaving room for new items. It's important we process these changes first, so we + // iterate the changes twice, first processing any that affect items currently in view. + // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server + // and event snap. I'm not sure if this will result in edge cases when a child is in one but + // not the other. + let curViewCache = viewCache; + let viewMergeTree; + if (pathIsEmpty(path)) { + viewMergeTree = changedChildren; + } + else { + viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren); + } + const serverNode = viewCache.serverCache.getNode(); + viewMergeTree.children.inorderTraversal((childKey, childTree) => { + if (serverNode.hasChild(childKey)) { + const serverChild = viewCache.serverCache + .getNode() + .getImmediateChild(childKey); + const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree); + curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator); + } + }); + viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => { + const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) && + childMergeTree.value === null; + if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) { + const serverChild = viewCache.serverCache + .getNode() + .getImmediateChild(childKey); + const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree); + curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator); + } + }); + return curViewCache; +} +function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) { + if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) { + return viewCache; + } + // Only filter server node if it is currently filtered + const filterServerNode = viewCache.serverCache.isFiltered(); + // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update + // now that it won't be shadowed. + const serverCache = viewCache.serverCache; + if (affectedTree.value != null) { + // This is an overwrite. + if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) || + serverCache.isCompleteForPath(ackPath)) { + return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator); + } + else if (pathIsEmpty(ackPath)) { + // This is a goofy edge case where we are acking data at this location but don't have full data. We + // should just re-apply whatever we have in our cache as a merge. + let changedChildren = new ImmutableTree(null); + serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => { + changedChildren = changedChildren.set(new Path(name), node); + }); + return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator); + } + else { + return viewCache; + } + } + else { + // This is a merge. + let changedChildren = new ImmutableTree(null); + affectedTree.foreach((mergePath, value) => { + const serverCachePath = pathChild(ackPath, mergePath); + if (serverCache.isCompleteForPath(serverCachePath)) { + changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath)); + } + }); + return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator); + } +} +function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) { + const oldServerNode = viewCache.serverCache; + const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered()); + return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator); +} +function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) { + let complete; + if (writeTreeRefShadowingWrite(writesCache, path) != null) { + return viewCache; + } + else { + const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache); + const oldEventCache = viewCache.eventCache.getNode(); + let newEventCache; + if (pathIsEmpty(path) || pathGetFront(path) === '.priority') { + let newNode; + if (viewCache.serverCache.isFullyInitialized()) { + newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache)); + } + else { + const serverChildren = viewCache.serverCache.getNode(); + util.assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node'); + newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren); + } + newNode = newNode; + newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator); + } + else { + const childKey = pathGetFront(path); + let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache); + if (newChild == null && + viewCache.serverCache.isCompleteForChild(childKey)) { + newChild = oldEventCache.getImmediateChild(childKey); + } + if (newChild != null) { + newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator); + } + else if (viewCache.eventCache.getNode().hasChild(childKey)) { + // No complete child available, delete the existing one, if any + newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator); + } + else { + newEventCache = oldEventCache; + } + if (newEventCache.isEmpty() && + viewCache.serverCache.isFullyInitialized()) { + // We might have reverted all child writes. Maybe the old event was a leaf node + complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache)); + if (complete.isLeafNode()) { + newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator); + } + } + } + complete = + viewCache.serverCache.isFullyInitialized() || + writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null; + return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes()); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A view represents a specific location and query that has 1 or more event registrations. + * + * It does several things: + * - Maintains the list of event registrations for this location/query. + * - Maintains a cache of the data visible for this location/query. + * - Applies new operations (via applyOperation), updates the cache, and based on the event + * registrations returns the set of events to be raised. + */ +class View { + constructor(query_, initialViewCache) { + this.query_ = query_; + this.eventRegistrations_ = []; + const params = this.query_._queryParams; + const indexFilter = new IndexedFilter(params.getIndex()); + const filter = queryParamsGetNodeFilter(params); + this.processor_ = newViewProcessor(filter); + const initialServerCache = initialViewCache.serverCache; + const initialEventCache = initialViewCache.eventCache; + // Don't filter server node with other filter than index, wait for tagged listen + const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null); + const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null); + const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes()); + const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes()); + this.viewCache_ = newViewCache(newEventCache, newServerCache); + this.eventGenerator_ = new EventGenerator(this.query_); + } + get query() { + return this.query_; + } +} +function viewGetServerCache(view) { + return view.viewCache_.serverCache.getNode(); +} +function viewGetCompleteNode(view) { + return viewCacheGetCompleteEventSnap(view.viewCache_); +} +function viewGetCompleteServerCache(view, path) { + const cache = viewCacheGetCompleteServerSnap(view.viewCache_); + if (cache) { + // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and + // we need to see if it contains the child we're interested in. + if (view.query._queryParams.loadsAllData() || + (!pathIsEmpty(path) && + !cache.getImmediateChild(pathGetFront(path)).isEmpty())) { + return cache.getChild(path); + } + } + return null; +} +function viewIsEmpty(view) { + return view.eventRegistrations_.length === 0; +} +function viewAddEventRegistration(view, eventRegistration) { + view.eventRegistrations_.push(eventRegistration); +} +/** + * @param eventRegistration - If null, remove all callbacks. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @returns Cancel events, if cancelError was provided. + */ +function viewRemoveEventRegistration(view, eventRegistration, cancelError) { + const cancelEvents = []; + if (cancelError) { + util.assert(eventRegistration == null, 'A cancel should cancel all event registrations.'); + const path = view.query._path; + view.eventRegistrations_.forEach(registration => { + const maybeEvent = registration.createCancelEvent(cancelError, path); + if (maybeEvent) { + cancelEvents.push(maybeEvent); + } + }); + } + if (eventRegistration) { + let remaining = []; + for (let i = 0; i < view.eventRegistrations_.length; ++i) { + const existing = view.eventRegistrations_[i]; + if (!existing.matches(eventRegistration)) { + remaining.push(existing); + } + else if (eventRegistration.hasAnyCallback()) { + // We're removing just this one + remaining = remaining.concat(view.eventRegistrations_.slice(i + 1)); + break; + } + } + view.eventRegistrations_ = remaining; + } + else { + view.eventRegistrations_ = []; + } + return cancelEvents; +} +/** + * Applies the given Operation, updates our cache, and returns the appropriate events. + */ +function viewApplyOperation(view, operation, writesCache, completeServerCache) { + if (operation.type === OperationType.MERGE && + operation.source.queryId !== null) { + util.assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges'); + util.assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache'); + } + const oldViewCache = view.viewCache_; + const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache); + viewProcessorAssertIndexed(view.processor_, result.viewCache); + util.assert(result.viewCache.serverCache.isFullyInitialized() || + !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back'); + view.viewCache_ = result.viewCache; + return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null); +} +function viewGetInitialEvents(view, registration) { + const eventSnap = view.viewCache_.eventCache; + const initialChanges = []; + if (!eventSnap.getNode().isLeafNode()) { + const eventNode = eventSnap.getNode(); + eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => { + initialChanges.push(changeChildAdded(key, childNode)); + }); + } + if (eventSnap.isFullyInitialized()) { + initialChanges.push(changeValue(eventSnap.getNode())); + } + return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration); +} +function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) { + const registrations = eventRegistration + ? [eventRegistration] + : view.eventRegistrations_; + return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let referenceConstructor$1; +/** + * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to + * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes + * and user writes (set, transaction, update). + * + * It's responsible for: + * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed). + * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite, + * applyUserOverwrite, etc.) + */ +class SyncPoint { + constructor() { + /** + * The Views being tracked at this location in the tree, stored as a map where the key is a + * queryId and the value is the View for that query. + * + * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case). + */ + this.views = new Map(); + } +} +function syncPointSetReferenceConstructor(val) { + util.assert(!referenceConstructor$1, '__referenceConstructor has already been defined'); + referenceConstructor$1 = val; +} +function syncPointGetReferenceConstructor() { + util.assert(referenceConstructor$1, 'Reference.ts has not been loaded'); + return referenceConstructor$1; +} +function syncPointIsEmpty(syncPoint) { + return syncPoint.views.size === 0; +} +function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) { + const queryId = operation.source.queryId; + if (queryId !== null) { + const view = syncPoint.views.get(queryId); + util.assert(view != null, 'SyncTree gave us an op for an invalid query.'); + return viewApplyOperation(view, operation, writesCache, optCompleteServerCache); + } + else { + let events = []; + for (const view of syncPoint.views.values()) { + events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache)); + } + return events; + } +} +/** + * Get a view for the specified query. + * + * @param query - The query to return a view for + * @param writesCache + * @param serverCache + * @param serverCacheComplete + * @returns Events to raise. + */ +function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) { + const queryId = query._queryIdentifier; + const view = syncPoint.views.get(queryId); + if (!view) { + // TODO: make writesCache take flag for complete server node + let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null); + let eventCacheComplete = false; + if (eventCache) { + eventCacheComplete = true; + } + else if (serverCache instanceof ChildrenNode) { + eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache); + eventCacheComplete = false; + } + else { + eventCache = ChildrenNode.EMPTY_NODE; + eventCacheComplete = false; + } + const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false)); + return new View(query, viewCache); + } + return view; +} +/** + * Add an event callback for the specified query. + * + * @param query + * @param eventRegistration + * @param writesCache + * @param serverCache - Complete server cache, if we have it. + * @param serverCacheComplete + * @returns Events to raise. + */ +function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) { + const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete); + if (!syncPoint.views.has(query._queryIdentifier)) { + syncPoint.views.set(query._queryIdentifier, view); + } + // This is guaranteed to exist now, we just created anything that was missing + viewAddEventRegistration(view, eventRegistration); + return viewGetInitialEvents(view, eventRegistration); +} +/** + * Remove event callback(s). Return cancelEvents if a cancelError is specified. + * + * If query is the default query, we'll check all views for the specified eventRegistration. + * If eventRegistration is null, we'll remove all callbacks for the specified view(s). + * + * @param eventRegistration - If null, remove all callbacks. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @returns removed queries and any cancel events + */ +function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) { + const queryId = query._queryIdentifier; + const removed = []; + let cancelEvents = []; + const hadCompleteView = syncPointHasCompleteView(syncPoint); + if (queryId === 'default') { + // When you do ref.off(...), we search all views for the registration to remove. + for (const [viewQueryId, view] of syncPoint.views.entries()) { + cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError)); + if (viewIsEmpty(view)) { + syncPoint.views.delete(viewQueryId); + // We'll deal with complete views later. + if (!view.query._queryParams.loadsAllData()) { + removed.push(view.query); + } + } + } + } + else { + // remove the callback from the specific view. + const view = syncPoint.views.get(queryId); + if (view) { + cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError)); + if (viewIsEmpty(view)) { + syncPoint.views.delete(queryId); + // We'll deal with complete views later. + if (!view.query._queryParams.loadsAllData()) { + removed.push(view.query); + } + } + } + } + if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) { + // We removed our last complete view. + removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path)); + } + return { removed, events: cancelEvents }; +} +function syncPointGetQueryViews(syncPoint) { + const result = []; + for (const view of syncPoint.views.values()) { + if (!view.query._queryParams.loadsAllData()) { + result.push(view); + } + } + return result; +} +/** + * @param path - The path to the desired complete snapshot + * @returns A complete cache, if it exists + */ +function syncPointGetCompleteServerCache(syncPoint, path) { + let serverCache = null; + for (const view of syncPoint.views.values()) { + serverCache = serverCache || viewGetCompleteServerCache(view, path); + } + return serverCache; +} +function syncPointViewForQuery(syncPoint, query) { + const params = query._queryParams; + if (params.loadsAllData()) { + return syncPointGetCompleteView(syncPoint); + } + else { + const queryId = query._queryIdentifier; + return syncPoint.views.get(queryId); + } +} +function syncPointViewExistsForQuery(syncPoint, query) { + return syncPointViewForQuery(syncPoint, query) != null; +} +function syncPointHasCompleteView(syncPoint) { + return syncPointGetCompleteView(syncPoint) != null; +} +function syncPointGetCompleteView(syncPoint) { + for (const view of syncPoint.views.values()) { + if (view.query._queryParams.loadsAllData()) { + return view; + } + } + return null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let referenceConstructor; +function syncTreeSetReferenceConstructor(val) { + util.assert(!referenceConstructor, '__referenceConstructor has already been defined'); + referenceConstructor = val; +} +function syncTreeGetReferenceConstructor() { + util.assert(referenceConstructor, 'Reference.ts has not been loaded'); + return referenceConstructor; +} +/** + * Static tracker for next query tag. + */ +let syncTreeNextQueryTag_ = 1; +/** + * SyncTree is the central class for managing event callback registration, data caching, views + * (query processing), and event generation. There are typically two SyncTree instances for + * each Repo, one for the normal Firebase data, and one for the .info data. + * + * It has a number of responsibilities, including: + * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()). + * - Applying and caching data changes for user set(), transaction(), and update() calls + * (applyUserOverwrite(), applyUserMerge()). + * - Applying and caching data changes for server data changes (applyServerOverwrite(), + * applyServerMerge()). + * - Generating user-facing events for server and user changes (all of the apply* methods + * return the set of events that need to be raised as a result). + * - Maintaining the appropriate set of server listens to ensure we are always subscribed + * to the correct set of paths and queries to satisfy the current set of user event + * callbacks (listens are started/stopped using the provided listenProvider). + * + * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual + * events are returned to the caller rather than raised synchronously. + * + */ +class SyncTree { + /** + * @param listenProvider_ - Used by SyncTree to start / stop listening + * to server data. + */ + constructor(listenProvider_) { + this.listenProvider_ = listenProvider_; + /** + * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views. + */ + this.syncPointTree_ = new ImmutableTree(null); + /** + * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.). + */ + this.pendingWriteTree_ = newWriteTree(); + this.tagToQueryMap = new Map(); + this.queryToTagMap = new Map(); + } +} +/** + * Apply the data changes for a user-generated set() or transaction() call. + * + * @returns Events to raise. + */ +function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) { + // Record pending write. + writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible); + if (!visible) { + return []; + } + else { + return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData)); + } +} +/** + * Apply the data from a user-generated update() call + * + * @returns Events to raise. + */ +function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) { + // Record pending merge. + writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId); + const changeTree = ImmutableTree.fromObject(changedChildren); + return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree)); +} +/** + * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge(). + * + * @param revert - True if the given write failed and needs to be reverted + * @returns Events to raise. + */ +function syncTreeAckUserWrite(syncTree, writeId, revert = false) { + const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId); + const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId); + if (!needToReevaluate) { + return []; + } + else { + let affectedTree = new ImmutableTree(null); + if (write.snap != null) { + // overwrite + affectedTree = affectedTree.set(newEmptyPath(), true); + } + else { + each(write.children, (pathString) => { + affectedTree = affectedTree.set(new Path(pathString), true); + }); + } + return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert)); + } +} +/** + * Apply new server data for the specified path.. + * + * @returns Events to raise. + */ +function syncTreeApplyServerOverwrite(syncTree, path, newData) { + return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData)); +} +/** + * Apply new server data to be merged in at the specified path. + * + * @returns Events to raise. + */ +function syncTreeApplyServerMerge(syncTree, path, changedChildren) { + const changeTree = ImmutableTree.fromObject(changedChildren); + return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree)); +} +/** + * Apply a listen complete for a query + * + * @returns Events to raise. + */ +function syncTreeApplyListenComplete(syncTree, path) { + return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path)); +} +/** + * Apply a listen complete for a tagged query + * + * @returns Events to raise. + */ +function syncTreeApplyTaggedListenComplete(syncTree, path, tag) { + const queryKey = syncTreeQueryKeyForTag_(syncTree, tag); + if (queryKey) { + const r = syncTreeParseQueryKey_(queryKey); + const queryPath = r.path, queryId = r.queryId; + const relativePath = newRelativePath(queryPath, path); + const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath); + return syncTreeApplyTaggedOperation_(syncTree, queryPath, op); + } + else { + // We've already removed the query. No big deal, ignore the update + return []; + } +} +/** + * Remove event callback(s). + * + * If query is the default query, we'll check all queries for the specified eventRegistration. + * If eventRegistration is null, we'll remove all callbacks for the specified query/queries. + * + * @param eventRegistration - If null, all callbacks are removed. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no + * deduping needs to take place. This flag allows toggling of that behavior + * @returns Cancel events, if cancelError was provided. + */ +function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) { + // Find the syncPoint first. Then deal with whether or not it has matching listeners + const path = query._path; + const maybeSyncPoint = syncTree.syncPointTree_.get(path); + let cancelEvents = []; + // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without + // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and + // not loadsAllData(). + if (maybeSyncPoint && + (query._queryIdentifier === 'default' || + syncPointViewExistsForQuery(maybeSyncPoint, query))) { + const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError); + if (syncPointIsEmpty(maybeSyncPoint)) { + syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path); + } + const removed = removedAndEvents.removed; + cancelEvents = removedAndEvents.events; + if (!skipListenerDedup) { + /** + * We may have just removed one of many listeners and can short-circuit this whole process + * We may also not have removed a default listener, in which case all of the descendant listeners should already be + * properly set up. + */ + // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of + // queryId === 'default' + const removingDefault = -1 !== + removed.findIndex(query => { + return query._queryParams.loadsAllData(); + }); + const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint)); + if (removingDefault && !covered) { + const subtree = syncTree.syncPointTree_.subtree(path); + // There are potentially child listeners. Determine what if any listens we need to send before executing the + // removal + if (!subtree.isEmpty()) { + // We need to fold over our subtree and collect the listeners to send + const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree); + // Ok, we've collected all the listens we need. Set them up. + for (let i = 0; i < newViews.length; ++i) { + const view = newViews[i], newQuery = view.query; + const listener = syncTreeCreateListenerForView_(syncTree, view); + syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete); + } + } + // Otherwise there's nothing below us, so nothing we need to start listening on + } + // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query + // The above block has us covered in terms of making sure we're set up on listens lower in the tree. + // Also, note that if we have a cancelError, it's already been removed at the provider level. + if (!covered && removed.length > 0 && !cancelError) { + // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one + // default. Otherwise, we need to iterate through and cancel each individual query + if (removingDefault) { + // We don't tag default listeners + const defaultTag = null; + syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag); + } + else { + removed.forEach((queryToRemove) => { + const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove)); + syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove); + }); + } + } + } + // Now, clear all of the tags we're tracking for the removed listens + syncTreeRemoveTags_(syncTree, removed); + } + return cancelEvents; +} +/** + * Apply new server data for the specified tagged query. + * + * @returns Events to raise. + */ +function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) { + const queryKey = syncTreeQueryKeyForTag_(syncTree, tag); + if (queryKey != null) { + const r = syncTreeParseQueryKey_(queryKey); + const queryPath = r.path, queryId = r.queryId; + const relativePath = newRelativePath(queryPath, path); + const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap); + return syncTreeApplyTaggedOperation_(syncTree, queryPath, op); + } + else { + // Query must have been removed already + return []; + } +} +/** + * Apply server data to be merged in for the specified tagged query. + * + * @returns Events to raise. + */ +function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) { + const queryKey = syncTreeQueryKeyForTag_(syncTree, tag); + if (queryKey) { + const r = syncTreeParseQueryKey_(queryKey); + const queryPath = r.path, queryId = r.queryId; + const relativePath = newRelativePath(queryPath, path); + const changeTree = ImmutableTree.fromObject(changedChildren); + const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree); + return syncTreeApplyTaggedOperation_(syncTree, queryPath, op); + } + else { + // We've already removed the query. No big deal, ignore the update + return []; + } +} +/** + * Add an event callback for the specified query. + * + * @returns Events to raise. + */ +function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) { + const path = query._path; + let serverCache = null; + let foundAncestorDefaultView = false; + // Any covering writes will necessarily be at the root, so really all we need to find is the server cache. + // Consider optimizing this once there's a better understanding of what actual behavior will be. + syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => { + const relativePath = newRelativePath(pathToSyncPoint, path); + serverCache = + serverCache || syncPointGetCompleteServerCache(sp, relativePath); + foundAncestorDefaultView = + foundAncestorDefaultView || syncPointHasCompleteView(sp); + }); + let syncPoint = syncTree.syncPointTree_.get(path); + if (!syncPoint) { + syncPoint = new SyncPoint(); + syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint); + } + else { + foundAncestorDefaultView = + foundAncestorDefaultView || syncPointHasCompleteView(syncPoint); + serverCache = + serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + let serverCacheComplete; + if (serverCache != null) { + serverCacheComplete = true; + } + else { + serverCacheComplete = false; + serverCache = ChildrenNode.EMPTY_NODE; + const subtree = syncTree.syncPointTree_.subtree(path); + subtree.foreachChild((childName, childSyncPoint) => { + const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath()); + if (completeCache) { + serverCache = serverCache.updateImmediateChild(childName, completeCache); + } + }); + } + const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query); + if (!viewAlreadyExists && !query._queryParams.loadsAllData()) { + // We need to track a tag for this query + const queryKey = syncTreeMakeQueryKey_(query); + util.assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag'); + const tag = syncTreeGetNextQueryTag_(); + syncTree.queryToTagMap.set(queryKey, tag); + syncTree.tagToQueryMap.set(tag, queryKey); + } + const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path); + let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete); + if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) { + const view = syncPointViewForQuery(syncPoint, query); + events = events.concat(syncTreeSetupListener_(syncTree, query, view)); + } + return events; +} +/** + * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a + * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always + * have a listener above, and atomic operations would correctly show a jitter of -> + * as the write is applied locally and then acknowledged at the server. + * + * Note: this method will *include* hidden writes from transaction with applyLocally set to false. + * + * @param path - The path to the data we want + * @param writeIdsToExclude - A specific set to be excluded + */ +function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) { + const includeHiddenSets = true; + const writeTree = syncTree.pendingWriteTree_; + const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => { + const relativePath = newRelativePath(pathSoFar, path); + const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath); + if (serverCache) { + return serverCache; + } + }); + return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets); +} +function syncTreeGetServerValue(syncTree, query) { + const path = query._path; + let serverCache = null; + // Any covering writes will necessarily be at the root, so really all we need to find is the server cache. + // Consider optimizing this once there's a better understanding of what actual behavior will be. + syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => { + const relativePath = newRelativePath(pathToSyncPoint, path); + serverCache = + serverCache || syncPointGetCompleteServerCache(sp, relativePath); + }); + let syncPoint = syncTree.syncPointTree_.get(path); + if (!syncPoint) { + syncPoint = new SyncPoint(); + syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint); + } + else { + serverCache = + serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + const serverCacheComplete = serverCache != null; + const serverCacheNode = serverCacheComplete + ? new CacheNode(serverCache, true, false) + : null; + const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path); + const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete); + return viewGetCompleteNode(view); +} +/** + * A helper method that visits all descendant and ancestor SyncPoints, applying the operation. + * + * NOTES: + * - Descendant SyncPoints will be visited first (since we raise events depth-first). + * + * - We call applyOperation() on each SyncPoint passing three things: + * 1. A version of the Operation that has been made relative to the SyncPoint location. + * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location. + * 3. A snapshot Node with cached server data, if we have it. + * + * - We concatenate all of the events returned by each SyncPoint and return the result. + */ +function syncTreeApplyOperationToSyncPoints_(syncTree, operation) { + return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_, + /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath())); +} +/** + * Recursive helper for applyOperationToSyncPoints_ + */ +function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) { + if (pathIsEmpty(operation.path)) { + return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache); + } + else { + const syncPoint = syncPointTree.get(newEmptyPath()); + // If we don't have cached server data, see if we can get it from this SyncPoint. + if (serverCache == null && syncPoint != null) { + serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + let events = []; + const childName = pathGetFront(operation.path); + const childOperation = operation.operationForChild(childName); + const childTree = syncPointTree.children.get(childName); + if (childTree && childOperation) { + const childServerCache = serverCache + ? serverCache.getImmediateChild(childName) + : null; + const childWritesCache = writeTreeRefChild(writesCache, childName); + events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache)); + } + if (syncPoint) { + events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)); + } + return events; + } +} +/** + * Recursive helper for applyOperationToSyncPoints_ + */ +function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) { + const syncPoint = syncPointTree.get(newEmptyPath()); + // If we don't have cached server data, see if we can get it from this SyncPoint. + if (serverCache == null && syncPoint != null) { + serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + let events = []; + syncPointTree.children.inorderTraversal((childName, childTree) => { + const childServerCache = serverCache + ? serverCache.getImmediateChild(childName) + : null; + const childWritesCache = writeTreeRefChild(writesCache, childName); + const childOperation = operation.operationForChild(childName); + if (childOperation) { + events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache)); + } + }); + if (syncPoint) { + events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)); + } + return events; +} +function syncTreeCreateListenerForView_(syncTree, view) { + const query = view.query; + const tag = syncTreeTagForQuery(syncTree, query); + return { + hashFn: () => { + const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE; + return cache.hash(); + }, + onComplete: (status) => { + if (status === 'ok') { + if (tag) { + return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag); + } + else { + return syncTreeApplyListenComplete(syncTree, query._path); + } + } + else { + // If a listen failed, kill all of the listeners here, not just the one that triggered the error. + // Note that this may need to be scoped to just this listener if we change permissions on filtered children + const error = errorForServerCode(status, query); + return syncTreeRemoveEventRegistration(syncTree, query, + /*eventRegistration*/ null, error); + } + } + }; +} +/** + * Return the tag associated with the given query. + */ +function syncTreeTagForQuery(syncTree, query) { + const queryKey = syncTreeMakeQueryKey_(query); + return syncTree.queryToTagMap.get(queryKey); +} +/** + * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_. + */ +function syncTreeMakeQueryKey_(query) { + return query._path.toString() + '$' + query._queryIdentifier; +} +/** + * Return the query associated with the given tag, if we have one + */ +function syncTreeQueryKeyForTag_(syncTree, tag) { + return syncTree.tagToQueryMap.get(tag); +} +/** + * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId. + */ +function syncTreeParseQueryKey_(queryKey) { + const splitIndex = queryKey.indexOf('$'); + util.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.'); + return { + queryId: queryKey.substr(splitIndex + 1), + path: new Path(queryKey.substr(0, splitIndex)) + }; +} +/** + * A helper method to apply tagged operations + */ +function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) { + const syncPoint = syncTree.syncPointTree_.get(queryPath); + util.assert(syncPoint, "Missing sync point for query tag that we're tracking"); + const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath); + return syncPointApplyOperation(syncPoint, operation, writesCache, null); +} +/** + * This collapses multiple unfiltered views into a single view, since we only need a single + * listener for them. + */ +function syncTreeCollectDistinctViewsForSubTree_(subtree) { + return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => { + if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) { + const completeView = syncPointGetCompleteView(maybeChildSyncPoint); + return [completeView]; + } + else { + // No complete view here, flatten any deeper listens into an array + let views = []; + if (maybeChildSyncPoint) { + views = syncPointGetQueryViews(maybeChildSyncPoint); + } + each(childMap, (_key, childViews) => { + views = views.concat(childViews); + }); + return views; + } + }); +} +/** + * Normalizes a query to a query we send the server for listening + * + * @returns The normalized query + */ +function syncTreeQueryForListening_(query) { + if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) { + // We treat queries that load all data as default queries + // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits + // from Query + return new (syncTreeGetReferenceConstructor())(query._repo, query._path); + } + else { + return query; + } +} +function syncTreeRemoveTags_(syncTree, queries) { + for (let j = 0; j < queries.length; ++j) { + const removedQuery = queries[j]; + if (!removedQuery._queryParams.loadsAllData()) { + // We should have a tag for this + const removedQueryKey = syncTreeMakeQueryKey_(removedQuery); + const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey); + syncTree.queryToTagMap.delete(removedQueryKey); + syncTree.tagToQueryMap.delete(removedQueryTag); + } + } +} +/** + * Static accessor for query tags. + */ +function syncTreeGetNextQueryTag_() { + return syncTreeNextQueryTag_++; +} +/** + * For a given new listen, manage the de-duplication of outstanding subscriptions. + * + * @returns This method can return events to support synchronous data sources + */ +function syncTreeSetupListener_(syncTree, query, view) { + const path = query._path; + const tag = syncTreeTagForQuery(syncTree, query); + const listener = syncTreeCreateListenerForView_(syncTree, view); + const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete); + const subtree = syncTree.syncPointTree_.subtree(path); + // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we + // may need to shadow other listens as well. + if (tag) { + util.assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed"); + } + else { + // Shadow everything at or below this location, this is a default listener. + const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => { + if (!pathIsEmpty(relativePath) && + maybeChildSyncPoint && + syncPointHasCompleteView(maybeChildSyncPoint)) { + return [syncPointGetCompleteView(maybeChildSyncPoint).query]; + } + else { + // No default listener here, flatten any deeper queries into an array + let queries = []; + if (maybeChildSyncPoint) { + queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query)); + } + each(childMap, (_key, childQueries) => { + queries = queries.concat(childQueries); + }); + return queries; + } + }); + for (let i = 0; i < queriesToStop.length; ++i) { + const queryToStop = queriesToStop[i]; + syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop)); + } + } + return events; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ExistingValueProvider { + constructor(node_) { + this.node_ = node_; + } + getImmediateChild(childName) { + const child = this.node_.getImmediateChild(childName); + return new ExistingValueProvider(child); + } + node() { + return this.node_; + } +} +class DeferredValueProvider { + constructor(syncTree, path) { + this.syncTree_ = syncTree; + this.path_ = path; + } + getImmediateChild(childName) { + const childPath = pathChild(this.path_, childName); + return new DeferredValueProvider(this.syncTree_, childPath); + } + node() { + return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_); + } +} +/** + * Generate placeholders for deferred values. + */ +const generateWithValues = function (values) { + values = values || {}; + values['timestamp'] = values['timestamp'] || new Date().getTime(); + return values; +}; +/** + * Value to use when firing local events. When writing server values, fire + * local events with an approximate value, otherwise return value as-is. + */ +const resolveDeferredLeafValue = function (value, existingVal, serverValues) { + if (!value || typeof value !== 'object') { + return value; + } + util.assert('.sv' in value, 'Unexpected leaf node or priority contents'); + if (typeof value['.sv'] === 'string') { + return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues); + } + else if (typeof value['.sv'] === 'object') { + return resolveComplexDeferredValue(value['.sv'], existingVal); + } + else { + util.assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2)); + } +}; +const resolveScalarDeferredValue = function (op, existing, serverValues) { + switch (op) { + case 'timestamp': + return serverValues['timestamp']; + default: + util.assert(false, 'Unexpected server value: ' + op); + } +}; +const resolveComplexDeferredValue = function (op, existing, unused) { + if (!op.hasOwnProperty('increment')) { + util.assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2)); + } + const delta = op['increment']; + if (typeof delta !== 'number') { + util.assert(false, 'Unexpected increment value: ' + delta); + } + const existingNode = existing.node(); + util.assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls'); + // Incrementing a non-number sets the value to the incremented amount + if (!existingNode.isLeafNode()) { + return delta; + } + const leaf = existingNode; + const existingVal = leaf.getValue(); + if (typeof existingVal !== 'number') { + return delta; + } + // No need to do over/underflow arithmetic here because JS only handles floats under the covers + return existingVal + delta; +}; +/** + * Recursively replace all deferred values and priorities in the tree with the + * specified generated replacement values. + * @param path - path to which write is relative + * @param node - new data written at path + * @param syncTree - current data + */ +const resolveDeferredValueTree = function (path, node, syncTree, serverValues) { + return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues); +}; +/** + * Recursively replace all deferred values and priorities in the node with the + * specified generated replacement values. If there are no server values in the node, + * it'll be returned as-is. + */ +const resolveDeferredValueSnapshot = function (node, existing, serverValues) { + return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues); +}; +function resolveDeferredValue(node, existingVal, serverValues) { + const rawPri = node.getPriority().val(); + const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues); + let newNode; + if (node.isLeafNode()) { + const leafNode = node; + const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues); + if (value !== leafNode.getValue() || + priority !== leafNode.getPriority().val()) { + return new LeafNode(value, nodeFromJSON(priority)); + } + else { + return node; + } + } + else { + const childrenNode = node; + newNode = childrenNode; + if (priority !== childrenNode.getPriority().val()) { + newNode = newNode.updatePriority(new LeafNode(priority)); + } + childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => { + const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues); + if (newChildNode !== childNode) { + newNode = newNode.updateImmediateChild(childName, newChildNode); + } + }); + return newNode; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A light-weight tree, traversable by path. Nodes can have both values and children. + * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty + * children. + */ +class Tree { + /** + * @param name - Optional name of the node. + * @param parent - Optional parent node. + * @param node - Optional node to wrap. + */ + constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) { + this.name = name; + this.parent = parent; + this.node = node; + } +} +/** + * Returns a sub-Tree for the given path. + * + * @param pathObj - Path to look up. + * @returns Tree for path. + */ +function treeSubTree(tree, pathObj) { + // TODO: Require pathObj to be Path? + let path = pathObj instanceof Path ? pathObj : new Path(pathObj); + let child = tree, next = pathGetFront(path); + while (next !== null) { + const childNode = util.safeGet(child.node.children, next) || { + children: {}, + childCount: 0 + }; + child = new Tree(next, child, childNode); + path = pathPopFront(path); + next = pathGetFront(path); + } + return child; +} +/** + * Returns the data associated with this tree node. + * + * @returns The data or null if no data exists. + */ +function treeGetValue(tree) { + return tree.node.value; +} +/** + * Sets data to this tree node. + * + * @param value - Value to set. + */ +function treeSetValue(tree, value) { + tree.node.value = value; + treeUpdateParents(tree); +} +/** + * @returns Whether the tree has any children. + */ +function treeHasChildren(tree) { + return tree.node.childCount > 0; +} +/** + * @returns Whether the tree is empty (no value or children). + */ +function treeIsEmpty(tree) { + return treeGetValue(tree) === undefined && !treeHasChildren(tree); +} +/** + * Calls action for each child of this tree node. + * + * @param action - Action to be called for each child. + */ +function treeForEachChild(tree, action) { + each(tree.node.children, (child, childTree) => { + action(new Tree(child, tree, childTree)); + }); +} +/** + * Does a depth-first traversal of this node's descendants, calling action for each one. + * + * @param action - Action to be called for each child. + * @param includeSelf - Whether to call action on this node as well. Defaults to + * false. + * @param childrenFirst - Whether to call action on children before calling it on + * parent. + */ +function treeForEachDescendant(tree, action, includeSelf, childrenFirst) { + if (includeSelf && !childrenFirst) { + action(tree); + } + treeForEachChild(tree, child => { + treeForEachDescendant(child, action, true, childrenFirst); + }); + if (includeSelf && childrenFirst) { + action(tree); + } +} +/** + * Calls action on each ancestor node. + * + * @param action - Action to be called on each parent; return + * true to abort. + * @param includeSelf - Whether to call action on this node as well. + * @returns true if the action callback returned true. + */ +function treeForEachAncestor(tree, action, includeSelf) { + let node = includeSelf ? tree : tree.parent; + while (node !== null) { + if (action(node)) { + return true; + } + node = node.parent; + } + return false; +} +/** + * @returns The path of this tree node, as a Path. + */ +function treeGetPath(tree) { + return new Path(tree.parent === null + ? tree.name + : treeGetPath(tree.parent) + '/' + tree.name); +} +/** + * Adds or removes this child from its parent based on whether it's empty or not. + */ +function treeUpdateParents(tree) { + if (tree.parent !== null) { + treeUpdateChild(tree.parent, tree.name, tree); + } +} +/** + * Adds or removes the passed child to this tree node, depending on whether it's empty. + * + * @param childName - The name of the child to update. + * @param child - The child to update. + */ +function treeUpdateChild(tree, childName, child) { + const childEmpty = treeIsEmpty(child); + const childExists = util.contains(tree.node.children, childName); + if (childEmpty && childExists) { + delete tree.node.children[childName]; + tree.node.childCount--; + treeUpdateParents(tree); + } + else if (!childEmpty && !childExists) { + tree.node.children[childName] = child.node; + tree.node.childCount++; + treeUpdateParents(tree); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * True for invalid Firebase keys + */ +const INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/; +/** + * True for invalid Firebase paths. + * Allows '/' in paths. + */ +const INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/; +/** + * Maximum number of characters to allow in leaf value + */ +const MAX_LEAF_SIZE_ = 10 * 1024 * 1024; +const isValidKey = function (key) { + return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key)); +}; +const isValidPathString = function (pathString) { + return (typeof pathString === 'string' && + pathString.length !== 0 && + !INVALID_PATH_REGEX_.test(pathString)); +}; +const isValidRootPathString = function (pathString) { + if (pathString) { + // Allow '/.info/' at the beginning. + pathString = pathString.replace(/^\/*\.info(\/|$)/, '/'); + } + return isValidPathString(pathString); +}; +const isValidPriority = function (priority) { + return (priority === null || + typeof priority === 'string' || + (typeof priority === 'number' && !isInvalidJSONNumber(priority)) || + (priority && + typeof priority === 'object' && + // eslint-disable-next-line @typescript-eslint/no-explicit-any + util.contains(priority, '.sv'))); +}; +/** + * Pre-validate a datum passed as an argument to Firebase function. + */ +const validateFirebaseDataArg = function (fnName, value, path, optional) { + if (optional && value === undefined) { + return; + } + validateFirebaseData(util.errorPrefix(fnName, 'value'), value, path); +}; +/** + * Validate a data object client-side before sending to server. + */ +const validateFirebaseData = function (errorPrefix, data, path_) { + const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_; + if (data === undefined) { + throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path)); + } + if (typeof data === 'function') { + throw new Error(errorPrefix + + 'contains a function ' + + validationPathToErrorString(path) + + ' with contents = ' + + data.toString()); + } + if (isInvalidJSONNumber(data)) { + throw new Error(errorPrefix + + 'contains ' + + data.toString() + + ' ' + + validationPathToErrorString(path)); + } + // Check max leaf size, but try to avoid the utf8 conversion if we can. + if (typeof data === 'string' && + data.length > MAX_LEAF_SIZE_ / 3 && + util.stringLength(data) > MAX_LEAF_SIZE_) { + throw new Error(errorPrefix + + 'contains a string greater than ' + + MAX_LEAF_SIZE_ + + ' utf8 bytes ' + + validationPathToErrorString(path) + + " ('" + + data.substring(0, 50) + + "...')"); + } + // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON + // to save extra walking of large objects. + if (data && typeof data === 'object') { + let hasDotValue = false; + let hasActualChild = false; + each(data, (key, value) => { + if (key === '.value') { + hasDotValue = true; + } + else if (key !== '.priority' && key !== '.sv') { + hasActualChild = true; + if (!isValidKey(key)) { + throw new Error(errorPrefix + + ' contains an invalid key (' + + key + + ') ' + + validationPathToErrorString(path) + + '. Keys must be non-empty strings ' + + 'and can\'t contain ".", "#", "$", "/", "[", or "]"'); + } + } + validationPathPush(path, key); + validateFirebaseData(errorPrefix, value, path); + validationPathPop(path); + }); + if (hasDotValue && hasActualChild) { + throw new Error(errorPrefix + + ' contains ".value" child ' + + validationPathToErrorString(path) + + ' in addition to actual children.'); + } + } +}; +/** + * Pre-validate paths passed in the firebase function. + */ +const validateFirebaseMergePaths = function (errorPrefix, mergePaths) { + let i, curPath; + for (i = 0; i < mergePaths.length; i++) { + curPath = mergePaths[i]; + const keys = pathSlice(curPath); + for (let j = 0; j < keys.length; j++) { + if (keys[j] === '.priority' && j === keys.length - 1) ; + else if (!isValidKey(keys[j])) { + throw new Error(errorPrefix + + 'contains an invalid key (' + + keys[j] + + ') in path ' + + curPath.toString() + + '. Keys must be non-empty strings ' + + 'and can\'t contain ".", "#", "$", "/", "[", or "]"'); + } + } + } + // Check that update keys are not descendants of each other. + // We rely on the property that sorting guarantees that ancestors come + // right before descendants. + mergePaths.sort(pathCompare); + let prevPath = null; + for (i = 0; i < mergePaths.length; i++) { + curPath = mergePaths[i]; + if (prevPath !== null && pathContains(prevPath, curPath)) { + throw new Error(errorPrefix + + 'contains a path ' + + prevPath.toString() + + ' that is ancestor of another path ' + + curPath.toString()); + } + prevPath = curPath; + } +}; +/** + * pre-validate an object passed as an argument to firebase function ( + * must be an object - e.g. for firebase.update()). + */ +const validateFirebaseMergeDataArg = function (fnName, data, path, optional) { + if (optional && data === undefined) { + return; + } + const errorPrefix = util.errorPrefix(fnName, 'values'); + if (!(data && typeof data === 'object') || Array.isArray(data)) { + throw new Error(errorPrefix + ' must be an object containing the children to replace.'); + } + const mergePaths = []; + each(data, (key, value) => { + const curPath = new Path(key); + validateFirebaseData(errorPrefix, value, pathChild(path, curPath)); + if (pathGetBack(curPath) === '.priority') { + if (!isValidPriority(value)) { + throw new Error(errorPrefix + + "contains an invalid value for '" + + curPath.toString() + + "', which must be a valid " + + 'Firebase priority (a string, finite number, server value, or null).'); + } + } + mergePaths.push(curPath); + }); + validateFirebaseMergePaths(errorPrefix, mergePaths); +}; +const validatePriority = function (fnName, priority, optional) { + if (optional && priority === undefined) { + return; + } + if (isInvalidJSONNumber(priority)) { + throw new Error(util.errorPrefix(fnName, 'priority') + + 'is ' + + priority.toString() + + ', but must be a valid Firebase priority (a string, finite number, ' + + 'server value, or null).'); + } + // Special case to allow importing data with a .sv. + if (!isValidPriority(priority)) { + throw new Error(util.errorPrefix(fnName, 'priority') + + 'must be a valid Firebase priority ' + + '(a string, finite number, server value, or null).'); + } +}; +const validateKey = function (fnName, argumentName, key, optional) { + if (optional && key === undefined) { + return; + } + if (!isValidKey(key)) { + throw new Error(util.errorPrefix(fnName, argumentName) + + 'was an invalid key = "' + + key + + '". Firebase keys must be non-empty strings and ' + + 'can\'t contain ".", "#", "$", "/", "[", or "]").'); + } +}; +/** + * @internal + */ +const validatePathString = function (fnName, argumentName, pathString, optional) { + if (optional && pathString === undefined) { + return; + } + if (!isValidPathString(pathString)) { + throw new Error(util.errorPrefix(fnName, argumentName) + + 'was an invalid path = "' + + pathString + + '". Paths must be non-empty strings and ' + + 'can\'t contain ".", "#", "$", "[", or "]"'); + } +}; +const validateRootPathString = function (fnName, argumentName, pathString, optional) { + if (pathString) { + // Allow '/.info/' at the beginning. + pathString = pathString.replace(/^\/*\.info(\/|$)/, '/'); + } + validatePathString(fnName, argumentName, pathString, optional); +}; +/** + * @internal + */ +const validateWritablePath = function (fnName, path) { + if (pathGetFront(path) === '.info') { + throw new Error(fnName + " failed = Can't modify data under /.info/"); + } +}; +const validateUrl = function (fnName, parsedUrl) { + // TODO = Validate server better. + const pathString = parsedUrl.path.toString(); + if (!(typeof parsedUrl.repoInfo.host === 'string') || + parsedUrl.repoInfo.host.length === 0 || + (!isValidKey(parsedUrl.repoInfo.namespace) && + parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') || + (pathString.length !== 0 && !isValidRootPathString(pathString))) { + throw new Error(util.errorPrefix(fnName, 'url') + + 'must be a valid firebase URL and ' + + 'the path can\'t contain ".", "#", "$", "[", or "]".'); + } +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The event queue serves a few purposes: + * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more + * events being queued. + * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events, + * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call + * left off, ensuring that the events are still raised synchronously and in order. + * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued + * events are raised synchronously. + * + * NOTE: This can all go away if/when we move to async events. + * + */ +class EventQueue { + constructor() { + this.eventLists_ = []; + /** + * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes. + */ + this.recursionDepth_ = 0; + } +} +/** + * @param eventDataList - The new events to queue. + */ +function eventQueueQueueEvents(eventQueue, eventDataList) { + // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly. + let currList = null; + for (let i = 0; i < eventDataList.length; i++) { + const data = eventDataList[i]; + const path = data.getPath(); + if (currList !== null && !pathEquals(path, currList.path)) { + eventQueue.eventLists_.push(currList); + currList = null; + } + if (currList === null) { + currList = { events: [], path }; + } + currList.events.push(data); + } + if (currList) { + eventQueue.eventLists_.push(currList); + } +} +/** + * Queues the specified events and synchronously raises all events (including previously queued ones) + * for the specified path. + * + * It is assumed that the new events are all for the specified path. + * + * @param path - The path to raise events for. + * @param eventDataList - The new events to raise. + */ +function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) { + eventQueueQueueEvents(eventQueue, eventDataList); + eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path)); +} +/** + * Queues the specified events and synchronously raises all events (including previously queued ones) for + * locations related to the specified change path (i.e. all ancestors and descendants). + * + * It is assumed that the new events are all related (ancestor or descendant) to the specified path. + * + * @param changedPath - The path to raise events for. + * @param eventDataList - The events to raise + */ +function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) { + eventQueueQueueEvents(eventQueue, eventDataList); + eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) || + pathContains(changedPath, eventPath)); +} +function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) { + eventQueue.recursionDepth_++; + let sentAll = true; + for (let i = 0; i < eventQueue.eventLists_.length; i++) { + const eventList = eventQueue.eventLists_[i]; + if (eventList) { + const eventPath = eventList.path; + if (predicate(eventPath)) { + eventListRaise(eventQueue.eventLists_[i]); + eventQueue.eventLists_[i] = null; + } + else { + sentAll = false; + } + } + } + if (sentAll) { + eventQueue.eventLists_ = []; + } + eventQueue.recursionDepth_--; +} +/** + * Iterates through the list and raises each event + */ +function eventListRaise(eventList) { + for (let i = 0; i < eventList.events.length; i++) { + const eventData = eventList.events[i]; + if (eventData !== null) { + eventList.events[i] = null; + const eventFn = eventData.getEventRunner(); + if (logger) { + log('event: ' + eventData.toString()); + } + exceptionGuard(eventFn); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const INTERRUPT_REASON = 'repo_interrupt'; +/** + * If a transaction does not succeed after 25 retries, we abort it. Among other + * things this ensure that if there's ever a bug causing a mismatch between + * client / server hashes for some data, we won't retry indefinitely. + */ +const MAX_TRANSACTION_RETRIES = 25; +/** + * A connection to a single data repository. + */ +class Repo { + constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) { + this.repoInfo_ = repoInfo_; + this.forceRestClient_ = forceRestClient_; + this.authTokenProvider_ = authTokenProvider_; + this.appCheckProvider_ = appCheckProvider_; + this.dataUpdateCount = 0; + this.statsListener_ = null; + this.eventQueue_ = new EventQueue(); + this.nextWriteId_ = 1; + this.interceptServerDataCallback_ = null; + /** A list of data pieces and paths to be set when this client disconnects. */ + this.onDisconnect_ = newSparseSnapshotTree(); + /** Stores queues of outstanding transactions for Firebase locations. */ + this.transactionQueueTree_ = new Tree(); + // TODO: This should be @private but it's used by test_access.js and internal.js + this.persistentConnection_ = null; + // This key is intentionally not updated if RepoInfo is later changed or replaced + this.key = this.repoInfo_.toURLString(); + } + /** + * @returns The URL corresponding to the root of this Firebase. + */ + toString() { + return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host); + } +} +function repoStart(repo, appId, authOverride) { + repo.stats_ = statsManagerGetCollection(repo.repoInfo_); + if (repo.forceRestClient_ || beingCrawled()) { + repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => { + repoOnDataUpdate(repo, pathString, data, isMerge, tag); + }, repo.authTokenProvider_, repo.appCheckProvider_); + // Minor hack: Fire onConnect immediately, since there's no actual connection. + setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0); + } + else { + // Validate authOverride + if (typeof authOverride !== 'undefined' && authOverride !== null) { + if (typeof authOverride !== 'object') { + throw new Error('Only objects are supported for option databaseAuthVariableOverride'); + } + try { + util.stringify(authOverride); + } + catch (e) { + throw new Error('Invalid authOverride provided: ' + e); + } + } + repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => { + repoOnDataUpdate(repo, pathString, data, isMerge, tag); + }, (connectStatus) => { + repoOnConnectStatus(repo, connectStatus); + }, (updates) => { + repoOnServerInfoUpdate(repo, updates); + }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride); + repo.server_ = repo.persistentConnection_; + } + repo.authTokenProvider_.addTokenChangeListener(token => { + repo.server_.refreshAuthToken(token); + }); + repo.appCheckProvider_.addTokenChangeListener(result => { + repo.server_.refreshAppCheckToken(result.token); + }); + // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used), + // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created. + repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_)); + // Used for .info. + repo.infoData_ = new SnapshotHolder(); + repo.infoSyncTree_ = new SyncTree({ + startListening: (query, tag, currentHashFn, onComplete) => { + let infoEvents = []; + const node = repo.infoData_.getNode(query._path); + // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events + // on initial data... + if (!node.isEmpty()) { + infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node); + setTimeout(() => { + onComplete('ok'); + }, 0); + } + return infoEvents; + }, + stopListening: () => { } + }); + repoUpdateInfo(repo, 'connected', false); + repo.serverSyncTree_ = new SyncTree({ + startListening: (query, tag, currentHashFn, onComplete) => { + repo.server_.listen(query, currentHashFn, tag, (status, data) => { + const events = onComplete(status, data); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events); + }); + // No synchronous events for network-backed sync trees + return []; + }, + stopListening: (query, tag) => { + repo.server_.unlisten(query, tag); + } + }); +} +/** + * @returns The time in milliseconds, taking the server offset into account if we have one. + */ +function repoServerTime(repo) { + const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset')); + const offset = offsetNode.val() || 0; + return new Date().getTime() + offset; +} +/** + * Generate ServerValues using some variables from the repo object. + */ +function repoGenerateServerValues(repo) { + return generateWithValues({ + timestamp: repoServerTime(repo) + }); +} +/** + * Called by realtime when we get new messages from the server. + */ +function repoOnDataUpdate(repo, pathString, data, isMerge, tag) { + // For testing. + repo.dataUpdateCount++; + const path = new Path(pathString); + data = repo.interceptServerDataCallback_ + ? repo.interceptServerDataCallback_(pathString, data) + : data; + let events = []; + if (tag) { + if (isMerge) { + const taggedChildren = util.map(data, (raw) => nodeFromJSON(raw)); + events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag); + } + else { + const taggedSnap = nodeFromJSON(data); + events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag); + } + } + else if (isMerge) { + const changedChildren = util.map(data, (raw) => nodeFromJSON(raw)); + events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren); + } + else { + const snap = nodeFromJSON(data); + events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap); + } + let affectedPath = path; + if (events.length > 0) { + // Since we have a listener outstanding for each transaction, receiving any events + // is a proxy for some change having occurred. + affectedPath = repoRerunTransactions(repo, path); + } + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events); +} +function repoOnConnectStatus(repo, connectStatus) { + repoUpdateInfo(repo, 'connected', connectStatus); + if (connectStatus === false) { + repoRunOnDisconnectEvents(repo); + } +} +function repoOnServerInfoUpdate(repo, updates) { + each(updates, (key, value) => { + repoUpdateInfo(repo, key, value); + }); +} +function repoUpdateInfo(repo, pathString, value) { + const path = new Path('/.info/' + pathString); + const newNode = nodeFromJSON(value); + repo.infoData_.updateSnapshot(path, newNode); + const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); +} +function repoGetNextWriteId(repo) { + return repo.nextWriteId_++; +} +/** + * The purpose of `getValue` is to return the latest known value + * satisfying `query`. + * + * This method will first check for in-memory cached values + * belonging to active listeners. If they are found, such values + * are considered to be the most up-to-date. + * + * If the client is not connected, this method will wait until the + * repo has established a connection and then request the value for `query`. + * If the client is not able to retrieve the query result for another reason, + * it reports an error. + * + * @param query - The query to surface a value for. + */ +function repoGetValue(repo, query, eventRegistration) { + // Only active queries are cached. There is no persisted cache. + const cached = syncTreeGetServerValue(repo.serverSyncTree_, query); + if (cached != null) { + return Promise.resolve(cached); + } + return repo.server_.get(query).then(payload => { + const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex()); + /** + * Below we simulate the actions of an `onlyOnce` `onValue()` event where: + * Add an event registration, + * Update data at the path, + * Raise any events, + * Cleanup the SyncTree + */ + syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true); + let events; + if (query._queryParams.loadsAllData()) { + events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node); + } + else { + const tag = syncTreeTagForQuery(repo.serverSyncTree_, query); + events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag); + } + /* + * We need to raise events in the scenario where `get()` is called at a parent path, and + * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting + * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree + * and its corresponding serverCache, including the child location where `onValue` is called. Then, + * `onValue` will receive the event from the server, but look at the syncTree and see that the data received + * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired. + * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and + * ensure the corresponding child events will get fired. + */ + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events); + syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true); + return node; + }, err => { + repoLog(repo, 'get for query ' + util.stringify(query) + ' failed: ' + err); + return Promise.reject(new Error(err)); + }); +} +function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) { + repoLog(repo, 'set', { + path: path.toString(), + value: newVal, + priority: newPriority + }); + // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or + // (b) store unresolved paths on JSON parse + const serverValues = repoGenerateServerValues(repo); + const newNodeUnresolved = nodeFromJSON(newVal, newPriority); + const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path); + const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues); + const writeId = repoGetNextWriteId(repo); + const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true); + eventQueueQueueEvents(repo.eventQueue_, events); + repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => { + const success = status === 'ok'; + if (!success) { + warn$1('set at ' + path + ' failed: ' + status); + } + const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents); + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); + const affectedPath = repoAbortTransactions(repo, path); + repoRerunTransactions(repo, affectedPath); + // We queued the events above, so just flush the queue here + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []); +} +function repoUpdate(repo, path, childrenToMerge, onComplete) { + repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge }); + // Start with our existing data and merge each child into it. + let empty = true; + const serverValues = repoGenerateServerValues(repo); + const changedChildren = {}; + each(childrenToMerge, (changedKey, changedValue) => { + empty = false; + changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues); + }); + if (!empty) { + const writeId = repoGetNextWriteId(repo); + const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId); + eventQueueQueueEvents(repo.eventQueue_, events); + repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => { + const success = status === 'ok'; + if (!success) { + warn$1('update at ' + path + ' failed: ' + status); + } + const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success); + const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path; + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents); + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); + each(childrenToMerge, (changedPath) => { + const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath)); + repoRerunTransactions(repo, affectedPath); + }); + // We queued the events above, so just flush the queue here + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []); + } + else { + log("update() called with empty data. Don't do anything."); + repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined); + } +} +/** + * Applies all of the changes stored up in the onDisconnect_ tree. + */ +function repoRunOnDisconnectEvents(repo) { + repoLog(repo, 'onDisconnectEvents'); + const serverValues = repoGenerateServerValues(repo); + const resolvedOnDisconnectTree = newSparseSnapshotTree(); + sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => { + const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues); + sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved); + }); + let events = []; + sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => { + events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap)); + const affectedPath = repoAbortTransactions(repo, path); + repoRerunTransactions(repo, affectedPath); + }); + repo.onDisconnect_ = newSparseSnapshotTree(); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events); +} +function repoOnDisconnectCancel(repo, path, onComplete) { + repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => { + if (status === 'ok') { + sparseSnapshotTreeForget(repo.onDisconnect_, path); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoOnDisconnectSet(repo, path, value, onComplete) { + const newNode = nodeFromJSON(value); + repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => { + if (status === 'ok') { + sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) { + const newNode = nodeFromJSON(value, priority); + repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => { + if (status === 'ok') { + sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) { + if (util.isEmpty(childrenToMerge)) { + log("onDisconnect().update() called with empty data. Don't do anything."); + repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined); + return; + } + repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => { + if (status === 'ok') { + each(childrenToMerge, (childName, childNode) => { + const newChildNode = nodeFromJSON(childNode); + sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode); + }); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoAddEventCallbackForQuery(repo, query, eventRegistration) { + let events; + if (pathGetFront(query._path) === '.info') { + events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration); + } + else { + events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration); + } + eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events); +} +function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) { + // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof + // a little bit by handling the return values anyways. + let events; + if (pathGetFront(query._path) === '.info') { + events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration); + } + else { + events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration); + } + eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events); +} +function repoInterrupt(repo) { + if (repo.persistentConnection_) { + repo.persistentConnection_.interrupt(INTERRUPT_REASON); + } +} +function repoResume(repo) { + if (repo.persistentConnection_) { + repo.persistentConnection_.resume(INTERRUPT_REASON); + } +} +function repoLog(repo, ...varArgs) { + let prefix = ''; + if (repo.persistentConnection_) { + prefix = repo.persistentConnection_.id + ':'; + } + log(prefix, ...varArgs); +} +function repoCallOnCompleteCallback(repo, callback, status, errorReason) { + if (callback) { + exceptionGuard(() => { + if (status === 'ok') { + callback(null); + } + else { + const code = (status || 'error').toUpperCase(); + let message = code; + if (errorReason) { + message += ': ' + errorReason; + } + const error = new Error(message); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error.code = code; + callback(error); + } + }); + } +} +/** + * Creates a new transaction, adds it to the transactions we're tracking, and + * sends it to the server if possible. + * + * @param path - Path at which to do transaction. + * @param transactionUpdate - Update callback. + * @param onComplete - Completion callback. + * @param unwatcher - Function that will be called when the transaction no longer + * need data updates for `path`. + * @param applyLocally - Whether or not to make intermediate results visible + */ +function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) { + repoLog(repo, 'transaction on ' + path); + // Initialize transaction. + const transaction = { + path, + update: transactionUpdate, + onComplete, + // One of TransactionStatus enums. + status: null, + // Used when combining transactions at different locations to figure out + // which one goes first. + order: LUIDGenerator(), + // Whether to raise local events for this transaction. + applyLocally, + // Count of how many times we've retried the transaction. + retryCount: 0, + // Function to call to clean up our .on() listener. + unwatcher, + // Stores why a transaction was aborted. + abortReason: null, + currentWriteId: null, + currentInputSnapshot: null, + currentOutputSnapshotRaw: null, + currentOutputSnapshotResolved: null + }; + // Run transaction initially. + const currentState = repoGetLatestState(repo, path, undefined); + transaction.currentInputSnapshot = currentState; + const newVal = transaction.update(currentState.val()); + if (newVal === undefined) { + // Abort transaction. + transaction.unwatcher(); + transaction.currentOutputSnapshotRaw = null; + transaction.currentOutputSnapshotResolved = null; + if (transaction.onComplete) { + transaction.onComplete(null, false, transaction.currentInputSnapshot); + } + } + else { + validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path); + // Mark as run and add to our queue. + transaction.status = 0 /* TransactionStatus.RUN */; + const queueNode = treeSubTree(repo.transactionQueueTree_, path); + const nodeQueue = treeGetValue(queueNode) || []; + nodeQueue.push(transaction); + treeSetValue(queueNode, nodeQueue); + // Update visibleData and raise events + // Note: We intentionally raise events after updating all of our + // transaction state, since the user could start new transactions from the + // event callbacks. + let priorityForNode; + if (typeof newVal === 'object' && + newVal !== null && + util.contains(newVal, '.priority')) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + priorityForNode = util.safeGet(newVal, '.priority'); + util.assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' + + 'Priority must be a valid string, finite number, server value, or null.'); + } + else { + const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) || + ChildrenNode.EMPTY_NODE; + priorityForNode = currentNode.getPriority().val(); + } + const serverValues = repoGenerateServerValues(repo); + const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode); + const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues); + transaction.currentOutputSnapshotRaw = newNodeUnresolved; + transaction.currentOutputSnapshotResolved = newNode; + transaction.currentWriteId = repoGetNextWriteId(repo); + const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); + repoSendReadyTransactions(repo, repo.transactionQueueTree_); + } +} +/** + * @param excludeSets - A specific set to exclude + */ +function repoGetLatestState(repo, path, excludeSets) { + return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) || + ChildrenNode.EMPTY_NODE); +} +/** + * Sends any already-run transactions that aren't waiting for outstanding + * transactions to complete. + * + * Externally it's called with no arguments, but it calls itself recursively + * with a particular transactionQueueTree node to recurse through the tree. + * + * @param node - transactionQueueTree node to start at. + */ +function repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) { + // Before recursing, make sure any completed transactions are removed. + if (!node) { + repoPruneCompletedTransactionsBelowNode(repo, node); + } + if (treeGetValue(node)) { + const queue = repoBuildTransactionQueue(repo, node); + util.assert(queue.length > 0, 'Sending zero length transaction queue'); + const allRun = queue.every((transaction) => transaction.status === 0 /* TransactionStatus.RUN */); + // If they're all run (and not sent), we can send them. Else, we must wait. + if (allRun) { + repoSendTransactionQueue(repo, treeGetPath(node), queue); + } + } + else if (treeHasChildren(node)) { + treeForEachChild(node, childNode => { + repoSendReadyTransactions(repo, childNode); + }); + } +} +/** + * Given a list of run transactions, send them to the server and then handle + * the result (success or failure). + * + * @param path - The location of the queue. + * @param queue - Queue of transactions under the specified location. + */ +function repoSendTransactionQueue(repo, path, queue) { + // Mark transactions as sent and increment retry count! + const setsToIgnore = queue.map(txn => { + return txn.currentWriteId; + }); + const latestState = repoGetLatestState(repo, path, setsToIgnore); + let snapToSend = latestState; + const latestHash = latestState.hash(); + for (let i = 0; i < queue.length; i++) { + const txn = queue[i]; + util.assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.'); + txn.status = 1 /* TransactionStatus.SENT */; + txn.retryCount++; + const relativePath = newRelativePath(path, txn.path); + // If we've gotten to this point, the output snapshot must be defined. + snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw); + } + const dataToSend = snapToSend.val(true); + const pathToSend = path; + // Send the put. + repo.server_.put(pathToSend.toString(), dataToSend, (status) => { + repoLog(repo, 'transaction put response', { + path: pathToSend.toString(), + status + }); + let events = []; + if (status === 'ok') { + // Queue up the callbacks and fire them after cleaning up all of our + // transaction state, since the callback could trigger more + // transactions or sets. + const callbacks = []; + for (let i = 0; i < queue.length; i++) { + queue[i].status = 2 /* TransactionStatus.COMPLETED */; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId)); + if (queue[i].onComplete) { + // We never unset the output snapshot, and given that this + // transaction is complete, it should be set + callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved)); + } + queue[i].unwatcher(); + } + // Now remove the completed transactions. + repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path)); + // There may be pending transactions that we can now send. + repoSendReadyTransactions(repo, repo.transactionQueueTree_); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); + // Finally, trigger onComplete callbacks. + for (let i = 0; i < callbacks.length; i++) { + exceptionGuard(callbacks[i]); + } + } + else { + // transactions are no longer sent. Update their status appropriately. + if (status === 'datastale') { + for (let i = 0; i < queue.length; i++) { + if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) { + queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */; + } + else { + queue[i].status = 0 /* TransactionStatus.RUN */; + } + } + } + else { + warn$1('transaction at ' + pathToSend.toString() + ' failed: ' + status); + for (let i = 0; i < queue.length; i++) { + queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */; + queue[i].abortReason = status; + } + } + repoRerunTransactions(repo, path); + } + }, latestHash); +} +/** + * Finds all transactions dependent on the data at changedPath and reruns them. + * + * Should be called any time cached data changes. + * + * Return the highest path that was affected by rerunning transactions. This + * is the path at which events need to be raised for. + * + * @param changedPath - The path in mergedData that changed. + * @returns The rootmost path that was affected by rerunning transactions. + */ +function repoRerunTransactions(repo, changedPath) { + const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath); + const path = treeGetPath(rootMostTransactionNode); + const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode); + repoRerunTransactionQueue(repo, queue, path); + return path; +} +/** + * Does all the work of rerunning transactions (as well as cleans up aborted + * transactions and whatnot). + * + * @param queue - The queue of transactions to run. + * @param path - The path the queue is for. + */ +function repoRerunTransactionQueue(repo, queue, path) { + if (queue.length === 0) { + return; // Nothing to do! + } + // Queue up the callbacks and fire them after cleaning up all of our + // transaction state, since the callback could trigger more transactions or + // sets. + const callbacks = []; + let events = []; + // Ignore all of the sets we're going to re-run. + const txnsToRerun = queue.filter(q => { + return q.status === 0 /* TransactionStatus.RUN */; + }); + const setsToIgnore = txnsToRerun.map(q => { + return q.currentWriteId; + }); + for (let i = 0; i < queue.length; i++) { + const transaction = queue[i]; + const relativePath = newRelativePath(path, transaction.path); + let abortTransaction = false, abortReason; + util.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.'); + if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) { + abortTransaction = true; + abortReason = transaction.abortReason; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true)); + } + else if (transaction.status === 0 /* TransactionStatus.RUN */) { + if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) { + abortTransaction = true; + abortReason = 'maxretry'; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true)); + } + else { + // This code reruns a transaction + const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore); + transaction.currentInputSnapshot = currentNode; + const newData = queue[i].update(currentNode.val()); + if (newData !== undefined) { + validateFirebaseData('transaction failed: Data returned ', newData, transaction.path); + let newDataNode = nodeFromJSON(newData); + const hasExplicitPriority = typeof newData === 'object' && + newData != null && + util.contains(newData, '.priority'); + if (!hasExplicitPriority) { + // Keep the old priority if there wasn't a priority explicitly specified. + newDataNode = newDataNode.updatePriority(currentNode.getPriority()); + } + const oldWriteId = transaction.currentWriteId; + const serverValues = repoGenerateServerValues(repo); + const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues); + transaction.currentOutputSnapshotRaw = newDataNode; + transaction.currentOutputSnapshotResolved = newNodeResolved; + transaction.currentWriteId = repoGetNextWriteId(repo); + // Mutates setsToIgnore in place + setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1); + events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally)); + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true)); + } + else { + abortTransaction = true; + abortReason = 'nodata'; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true)); + } + } + } + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); + events = []; + if (abortTransaction) { + // Abort. + queue[i].status = 2 /* TransactionStatus.COMPLETED */; + // Removing a listener can trigger pruning which can muck with + // mergedData/visibleData (as it prunes data). So defer the unwatcher + // until we're done. + (function (unwatcher) { + setTimeout(unwatcher, Math.floor(0)); + })(queue[i].unwatcher); + if (queue[i].onComplete) { + if (abortReason === 'nodata') { + callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot)); + } + else { + callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null)); + } + } + } + } + // Clean up completed transactions. + repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_); + // Now fire callbacks, now that we're in a good, known state. + for (let i = 0; i < callbacks.length; i++) { + exceptionGuard(callbacks[i]); + } + // Try to send the transaction result to the server. + repoSendReadyTransactions(repo, repo.transactionQueueTree_); +} +/** + * Returns the rootmost ancestor node of the specified path that has a pending + * transaction on it, or just returns the node for the given path if there are + * no pending transactions on any ancestor. + * + * @param path - The location to start at. + * @returns The rootmost node with a transaction. + */ +function repoGetAncestorTransactionNode(repo, path) { + let front; + // Start at the root and walk deeper into the tree towards path until we + // find a node with pending transactions. + let transactionNode = repo.transactionQueueTree_; + front = pathGetFront(path); + while (front !== null && treeGetValue(transactionNode) === undefined) { + transactionNode = treeSubTree(transactionNode, front); + path = pathPopFront(path); + front = pathGetFront(path); + } + return transactionNode; +} +/** + * Builds the queue of all transactions at or below the specified + * transactionNode. + * + * @param transactionNode + * @returns The generated queue. + */ +function repoBuildTransactionQueue(repo, transactionNode) { + // Walk any child transaction queues and aggregate them into a single queue. + const transactionQueue = []; + repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue); + // Sort them by the order the transactions were created. + transactionQueue.sort((a, b) => a.order - b.order); + return transactionQueue; +} +function repoAggregateTransactionQueuesForNode(repo, node, queue) { + const nodeQueue = treeGetValue(node); + if (nodeQueue) { + for (let i = 0; i < nodeQueue.length; i++) { + queue.push(nodeQueue[i]); + } + } + treeForEachChild(node, child => { + repoAggregateTransactionQueuesForNode(repo, child, queue); + }); +} +/** + * Remove COMPLETED transactions at or below this node in the transactionQueueTree_. + */ +function repoPruneCompletedTransactionsBelowNode(repo, node) { + const queue = treeGetValue(node); + if (queue) { + let to = 0; + for (let from = 0; from < queue.length; from++) { + if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) { + queue[to] = queue[from]; + to++; + } + } + queue.length = to; + treeSetValue(node, queue.length > 0 ? queue : undefined); + } + treeForEachChild(node, childNode => { + repoPruneCompletedTransactionsBelowNode(repo, childNode); + }); +} +/** + * Aborts all transactions on ancestors or descendants of the specified path. + * Called when doing a set() or update() since we consider them incompatible + * with transactions. + * + * @param path - Path for which we want to abort related transactions. + */ +function repoAbortTransactions(repo, path) { + const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path)); + const transactionNode = treeSubTree(repo.transactionQueueTree_, path); + treeForEachAncestor(transactionNode, (node) => { + repoAbortTransactionsOnNode(repo, node); + }); + repoAbortTransactionsOnNode(repo, transactionNode); + treeForEachDescendant(transactionNode, (node) => { + repoAbortTransactionsOnNode(repo, node); + }); + return affectedPath; +} +/** + * Abort transactions stored in this transaction queue node. + * + * @param node - Node to abort transactions for. + */ +function repoAbortTransactionsOnNode(repo, node) { + const queue = treeGetValue(node); + if (queue) { + // Queue up the callbacks and fire them after cleaning up all of our + // transaction state, since the callback could trigger more transactions + // or sets. + const callbacks = []; + // Go through queue. Any already-sent transactions must be marked for + // abort, while the unsent ones can be immediately aborted and removed. + let events = []; + let lastSent = -1; + for (let i = 0; i < queue.length; i++) { + if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ; + else if (queue[i].status === 1 /* TransactionStatus.SENT */) { + util.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.'); + lastSent = i; + // Mark transaction for abort when it comes back. + queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */; + queue[i].abortReason = 'set'; + } + else { + util.assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort'); + // We can abort it immediately. + queue[i].unwatcher(); + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true)); + if (queue[i].onComplete) { + callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null)); + } + } + } + if (lastSent === -1) { + // We're not waiting for any sent transactions. We can clear the queue. + treeSetValue(node, undefined); + } + else { + // Remove the transactions we aborted. + queue.length = lastSent + 1; + } + // Now fire the callbacks. + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events); + for (let i = 0; i < callbacks.length; i++) { + exceptionGuard(callbacks[i]); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function decodePath(pathString) { + let pathStringDecoded = ''; + const pieces = pathString.split('/'); + for (let i = 0; i < pieces.length; i++) { + if (pieces[i].length > 0) { + let piece = pieces[i]; + try { + piece = decodeURIComponent(piece.replace(/\+/g, ' ')); + } + catch (e) { } + pathStringDecoded += '/' + piece; + } + } + return pathStringDecoded; +} +/** + * @returns key value hash + */ +function decodeQuery(queryString) { + const results = {}; + if (queryString.charAt(0) === '?') { + queryString = queryString.substring(1); + } + for (const segment of queryString.split('&')) { + if (segment.length === 0) { + continue; + } + const kv = segment.split('='); + if (kv.length === 2) { + results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]); + } + else { + warn$1(`Invalid query segment '${segment}' in query '${queryString}'`); + } + } + return results; +} +const parseRepoInfo = function (dataURL, nodeAdmin) { + const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace; + if (parsedUrl.domain === 'firebase.com') { + fatal(parsedUrl.host + + ' is no longer supported. ' + + 'Please use .firebaseio.com instead'); + } + // Catch common error of uninitialized namespace value. + if ((!namespace || namespace === 'undefined') && + parsedUrl.domain !== 'localhost') { + fatal('Cannot parse Firebase url. Please use https://.firebaseio.com'); + } + if (!parsedUrl.secure) { + warnIfPageIsSecure(); + } + const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss'; + return { + repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin, + /*persistenceKey=*/ '', + /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain), + path: new Path(parsedUrl.pathString) + }; +}; +const parseDatabaseURL = function (dataURL) { + // Default to empty strings in the event of a malformed string. + let host = '', domain = '', subdomain = '', pathString = '', namespace = ''; + // Always default to SSL, unless otherwise specified. + let secure = true, scheme = 'https', port = 443; + // Don't do any validation here. The caller is responsible for validating the result of parsing. + if (typeof dataURL === 'string') { + // Parse scheme. + let colonInd = dataURL.indexOf('//'); + if (colonInd >= 0) { + scheme = dataURL.substring(0, colonInd - 1); + dataURL = dataURL.substring(colonInd + 2); + } + // Parse host, path, and query string. + let slashInd = dataURL.indexOf('/'); + if (slashInd === -1) { + slashInd = dataURL.length; + } + let questionMarkInd = dataURL.indexOf('?'); + if (questionMarkInd === -1) { + questionMarkInd = dataURL.length; + } + host = dataURL.substring(0, Math.min(slashInd, questionMarkInd)); + if (slashInd < questionMarkInd) { + // For pathString, questionMarkInd will always come after slashInd + pathString = decodePath(dataURL.substring(slashInd, questionMarkInd)); + } + const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd))); + // If we have a port, use scheme for determining if it's secure. + colonInd = host.indexOf(':'); + if (colonInd >= 0) { + secure = scheme === 'https' || scheme === 'wss'; + port = parseInt(host.substring(colonInd + 1), 10); + } + else { + colonInd = host.length; + } + const hostWithoutPort = host.slice(0, colonInd); + if (hostWithoutPort.toLowerCase() === 'localhost') { + domain = 'localhost'; + } + else if (hostWithoutPort.split('.').length <= 2) { + domain = hostWithoutPort; + } + else { + // Interpret the subdomain of a 3 or more component URL as the namespace name. + const dotInd = host.indexOf('.'); + subdomain = host.substring(0, dotInd).toLowerCase(); + domain = host.substring(dotInd + 1); + // Normalize namespaces to lowercase to share storage / connection. + namespace = subdomain; + } + // Always treat the value of the `ns` as the namespace name if it is present. + if ('ns' in queryParams) { + namespace = queryParams['ns']; + } + } + return { + host, + port, + domain, + subdomain, + secure, + scheme, + pathString, + namespace + }; +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Modeled after base64 web-safe chars, but ordered by ASCII. +const PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'; +/** + * Fancy ID generator that creates 20-character string identifiers with the + * following properties: + * + * 1. They're based on timestamp so that they sort *after* any existing ids. + * 2. They contain 72-bits of random data after the timestamp so that IDs won't + * collide with other clients' IDs. + * 3. They sort *lexicographically* (so the timestamp is converted to characters + * that will sort properly). + * 4. They're monotonically increasing. Even if you generate more than one in + * the same timestamp, the latter ones will sort after the former ones. We do + * this by using the previous random bits but "incrementing" them by 1 (only + * in the case of a timestamp collision). + */ +const nextPushId = (function () { + // Timestamp of last push, used to prevent local collisions if you push twice + // in one ms. + let lastPushTime = 0; + // We generate 72-bits of randomness which get turned into 12 characters and + // appended to the timestamp to prevent collisions with other clients. We + // store the last characters we generated because in the event of a collision, + // we'll use those same characters except "incremented" by one. + const lastRandChars = []; + return function (now) { + const duplicateTime = now === lastPushTime; + lastPushTime = now; + let i; + const timeStampChars = new Array(8); + for (i = 7; i >= 0; i--) { + timeStampChars[i] = PUSH_CHARS.charAt(now % 64); + // NOTE: Can't use << here because javascript will convert to int and lose + // the upper bits. + now = Math.floor(now / 64); + } + util.assert(now === 0, 'Cannot push at time == 0'); + let id = timeStampChars.join(''); + if (!duplicateTime) { + for (i = 0; i < 12; i++) { + lastRandChars[i] = Math.floor(Math.random() * 64); + } + } + else { + // If the timestamp hasn't changed since last push, use the same random + // number, except incremented by 1. + for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) { + lastRandChars[i] = 0; + } + lastRandChars[i]++; + } + for (i = 0; i < 12; i++) { + id += PUSH_CHARS.charAt(lastRandChars[i]); + } + util.assert(id.length === 20, 'nextPushId: Length should be 20.'); + return id; + }; +})(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Encapsulates the data needed to raise an event + */ +class DataEvent { + /** + * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed + * @param eventRegistration - The function to call to with the event data. User provided + * @param snapshot - The data backing the event + * @param prevName - Optional, the name of the previous child for child_* events. + */ + constructor(eventType, eventRegistration, snapshot, prevName) { + this.eventType = eventType; + this.eventRegistration = eventRegistration; + this.snapshot = snapshot; + this.prevName = prevName; + } + getPath() { + const ref = this.snapshot.ref; + if (this.eventType === 'value') { + return ref._path; + } + else { + return ref.parent._path; + } + } + getEventType() { + return this.eventType; + } + getEventRunner() { + return this.eventRegistration.getEventRunner(this); + } + toString() { + return (this.getPath().toString() + + ':' + + this.eventType + + ':' + + util.stringify(this.snapshot.exportVal())); + } +} +class CancelEvent { + constructor(eventRegistration, error, path) { + this.eventRegistration = eventRegistration; + this.error = error; + this.path = path; + } + getPath() { + return this.path; + } + getEventType() { + return 'cancel'; + } + getEventRunner() { + return this.eventRegistration.getEventRunner(this); + } + toString() { + return this.path.toString() + ':cancel'; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A wrapper class that converts events from the database@exp SDK to the legacy + * Database SDK. Events are not converted directly as event registration relies + * on reference comparison of the original user callback (see `matches()`) and + * relies on equality of the legacy SDK's `context` object. + */ +class CallbackContext { + constructor(snapshotCallback, cancelCallback) { + this.snapshotCallback = snapshotCallback; + this.cancelCallback = cancelCallback; + } + onValue(expDataSnapshot, previousChildName) { + this.snapshotCallback.call(null, expDataSnapshot, previousChildName); + } + onCancel(error) { + util.assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback'); + return this.cancelCallback.call(null, error); + } + get hasCancelCallback() { + return !!this.cancelCallback; + } + matches(other) { + return (this.snapshotCallback === other.snapshotCallback || + (this.snapshotCallback.userCallback !== undefined && + this.snapshotCallback.userCallback === + other.snapshotCallback.userCallback && + this.snapshotCallback.context === other.snapshotCallback.context)); + } +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The `onDisconnect` class allows you to write or clear data when your client + * disconnects from the Database server. These updates occur whether your + * client disconnects cleanly or not, so you can rely on them to clean up data + * even if a connection is dropped or a client crashes. + * + * The `onDisconnect` class is most commonly used to manage presence in + * applications where it is useful to detect how many clients are connected and + * when other clients disconnect. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * To avoid problems when a connection is dropped before the requests can be + * transferred to the Database server, these functions should be called before + * writing any data. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time you reconnect. + */ +class OnDisconnect$1 { + /** @hideconstructor */ + constructor(_repo, _path) { + this._repo = _repo; + this._path = _path; + } + /** + * Cancels all previously queued `onDisconnect()` set or update events for this + * location and all children. + * + * If a write has been queued for this location via a `set()` or `update()` at a + * parent location, the write at this location will be canceled, though writes + * to sibling locations will still occur. + * + * @returns Resolves when synchronization to the server is complete. + */ + cancel() { + const deferred = new util.Deferred(); + repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Ensures the data at this location is deleted when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + * + * @returns Resolves when synchronization to the server is complete. + */ + remove() { + validateWritablePath('OnDisconnect.remove', this._path); + const deferred = new util.Deferred(); + repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Ensures the data at this location is set to the specified value when the + * client is disconnected (due to closing the browser, navigating to a new page, + * or network issues). + * + * `set()` is especially useful for implementing "presence" systems, where a + * value should be changed or cleared when a user disconnects so that they + * appear "offline" to other users. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time. + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + set(value) { + validateWritablePath('OnDisconnect.set', this._path); + validateFirebaseDataArg('OnDisconnect.set', value, this._path, false); + const deferred = new util.Deferred(); + repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Ensures the data at this location is set to the specified value and priority + * when the client is disconnected (due to closing the browser, navigating to a + * new page, or network issues). + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + setWithPriority(value, priority) { + validateWritablePath('OnDisconnect.setWithPriority', this._path); + validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false); + validatePriority('OnDisconnect.setWithPriority', priority, false); + const deferred = new util.Deferred(); + repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Writes multiple values at this location when the client is disconnected (due + * to closing the browser, navigating to a new page, or network issues). + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, "name/first") + * from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * @param values - Object containing multiple values. + * @returns Resolves when synchronization to the Database is complete. + */ + update(values) { + validateWritablePath('OnDisconnect.update', this._path); + validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false); + const deferred = new util.Deferred(); + repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { })); + return deferred.promise; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ +class QueryImpl { + /** + * @hideconstructor + */ + constructor(_repo, _path, _queryParams, _orderByCalled) { + this._repo = _repo; + this._path = _path; + this._queryParams = _queryParams; + this._orderByCalled = _orderByCalled; + } + get key() { + if (pathIsEmpty(this._path)) { + return null; + } + else { + return pathGetBack(this._path); + } + } + get ref() { + return new ReferenceImpl(this._repo, this._path); + } + get _queryIdentifier() { + const obj = queryParamsGetQueryObject(this._queryParams); + const id = ObjectToUniqueKey(obj); + return id === '{}' ? 'default' : id; + } + /** + * An object representation of the query parameters used by this Query. + */ + get _queryObject() { + return queryParamsGetQueryObject(this._queryParams); + } + isEqual(other) { + other = util.getModularInstance(other); + if (!(other instanceof QueryImpl)) { + return false; + } + const sameRepo = this._repo === other._repo; + const samePath = pathEquals(this._path, other._path); + const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier; + return sameRepo && samePath && sameQueryIdentifier; + } + toJSON() { + return this.toString(); + } + toString() { + return this._repo.toString() + pathToUrlEncodedString(this._path); + } +} +/** + * Validates that no other order by call has been made + */ +function validateNoPreviousOrderByCall(query, fnName) { + if (query._orderByCalled === true) { + throw new Error(fnName + ": You can't combine multiple orderBy calls."); + } +} +/** + * Validates start/end values for queries. + */ +function validateQueryEndpoints(params) { + let startNode = null; + let endNode = null; + if (params.hasStart()) { + startNode = params.getIndexStartValue(); + } + if (params.hasEnd()) { + endNode = params.getIndexEndValue(); + } + if (params.getIndex() === KEY_INDEX) { + const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' + + 'startAt(), endAt(), or equalTo().'; + const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' + + 'endAt(), endBefore(), or equalTo() must be a string.'; + if (params.hasStart()) { + const startName = params.getIndexStartName(); + if (startName !== MIN_NAME) { + throw new Error(tooManyArgsError); + } + else if (typeof startNode !== 'string') { + throw new Error(wrongArgTypeError); + } + } + if (params.hasEnd()) { + const endName = params.getIndexEndName(); + if (endName !== MAX_NAME) { + throw new Error(tooManyArgsError); + } + else if (typeof endNode !== 'string') { + throw new Error(wrongArgTypeError); + } + } + } + else if (params.getIndex() === PRIORITY_INDEX) { + if ((startNode != null && !isValidPriority(startNode)) || + (endNode != null && !isValidPriority(endNode))) { + throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' + + 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' + + '(null, a number, or a string).'); + } + } + else { + util.assert(params.getIndex() instanceof PathIndex || + params.getIndex() === VALUE_INDEX, 'unknown index type.'); + if ((startNode != null && typeof startNode === 'object') || + (endNode != null && typeof endNode === 'object')) { + throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' + + 'equalTo() cannot be an object.'); + } + } +} +/** + * Validates that limit* has been called with the correct combination of parameters + */ +function validateLimit(params) { + if (params.hasStart() && + params.hasEnd() && + params.hasLimit() && + !params.hasAnchoredLimit()) { + throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " + + 'limitToFirst() or limitToLast() instead.'); + } +} +/** + * @internal + */ +class ReferenceImpl extends QueryImpl { + /** @hideconstructor */ + constructor(repo, path) { + super(repo, path, new QueryParams(), false); + } + get parent() { + const parentPath = pathParent(this._path); + return parentPath === null + ? null + : new ReferenceImpl(this._repo, parentPath); + } + get root() { + let ref = this; + while (ref.parent !== null) { + ref = ref.parent; + } + return ref; + } +} +/** + * A `DataSnapshot` contains data from a Database location. + * + * Any time you read data from the Database, you receive the data as a + * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach + * with `on()` or `once()`. You can extract the contents of the snapshot as a + * JavaScript object by calling the `val()` method. Alternatively, you can + * traverse into the snapshot by calling `child()` to return child snapshots + * (which you could then call `val()` on). + * + * A `DataSnapshot` is an efficiently generated, immutable copy of the data at + * a Database location. It cannot be modified and will never change (to modify + * data, you always call the `set()` method on a `Reference` directly). + */ +class DataSnapshot$1 { + /** + * @param _node - A SnapshotNode to wrap. + * @param ref - The location this snapshot came from. + * @param _index - The iteration order for this snapshot + * @hideconstructor + */ + constructor(_node, + /** + * The location of this DataSnapshot. + */ + ref, _index) { + this._node = _node; + this.ref = ref; + this._index = _index; + } + /** + * Gets the priority value of the data in this `DataSnapshot`. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data} + * ). + */ + get priority() { + // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY) + return this._node.getPriority().val(); + } + /** + * The key (last part of the path) of the location of this `DataSnapshot`. + * + * The last token in a Database location is considered its key. For example, + * "ada" is the key for the /users/ada/ node. Accessing the key on any + * `DataSnapshot` will return the key for the location that generated it. + * However, accessing the key on the root URL of a Database will return + * `null`. + */ + get key() { + return this.ref.key; + } + /** Returns the number of child properties of this `DataSnapshot`. */ + get size() { + return this._node.numChildren(); + } + /** + * Gets another `DataSnapshot` for the location at the specified relative path. + * + * Passing a relative path to the `child()` method of a DataSnapshot returns + * another `DataSnapshot` for the location at the specified relative path. The + * relative path can either be a simple child name (for example, "ada") or a + * deeper, slash-separated path (for example, "ada/name/first"). If the child + * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot` + * whose value is `null`) is returned. + * + * @param path - A relative path to the location of child data. + */ + child(path) { + const childPath = new Path(path); + const childRef = child(this.ref, path); + return new DataSnapshot$1(this._node.getChild(childPath), childRef, PRIORITY_INDEX); + } + /** + * Returns true if this `DataSnapshot` contains any data. It is slightly more + * efficient than using `snapshot.val() !== null`. + */ + exists() { + return !this._node.isEmpty(); + } + /** + * Exports the entire contents of the DataSnapshot as a JavaScript object. + * + * The `exportVal()` method is similar to `val()`, except priority information + * is included (if available), making it suitable for backing up your data. + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + exportVal() { + return this._node.val(true); + } + /** + * Enumerates the top-level children in the `IteratedDataSnapshot`. + * + * Because of the way JavaScript objects work, the ordering of data in the + * JavaScript object returned by `val()` is not guaranteed to match the + * ordering on the server nor the ordering of `onChildAdded()` events. That is + * where `forEach()` comes in handy. It guarantees the children of a + * `DataSnapshot` will be iterated in their query order. + * + * If no explicit `orderBy*()` method is used, results are returned + * ordered by key (unless priorities are used, in which case, results are + * returned by priority). + * + * @param action - A function that will be called for each child DataSnapshot. + * The callback can return true to cancel further enumeration. + * @returns true if enumeration was canceled due to your callback returning + * true. + */ + forEach(action) { + if (this._node.isLeafNode()) { + return false; + } + const childrenNode = this._node; + // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type... + return !!childrenNode.forEachChild(this._index, (key, node) => { + return action(new DataSnapshot$1(node, child(this.ref, key), PRIORITY_INDEX)); + }); + } + /** + * Returns true if the specified child path has (non-null) data. + * + * @param path - A relative path to the location of a potential child. + * @returns `true` if data exists at the specified child path; else + * `false`. + */ + hasChild(path) { + const childPath = new Path(path); + return !this._node.getChild(childPath).isEmpty(); + } + /** + * Returns whether or not the `DataSnapshot` has any non-`null` child + * properties. + * + * You can use `hasChildren()` to determine if a `DataSnapshot` has any + * children. If it does, you can enumerate them using `forEach()`. If it + * doesn't, then either this snapshot contains a primitive value (which can be + * retrieved with `val()`) or it is empty (in which case, `val()` will return + * `null`). + * + * @returns true if this snapshot has any children; else false. + */ + hasChildren() { + if (this._node.isLeafNode()) { + return false; + } + else { + return !this._node.isEmpty(); + } + } + /** + * Returns a JSON-serializable representation of this object. + */ + toJSON() { + return this.exportVal(); + } + /** + * Extracts a JavaScript value from a `DataSnapshot`. + * + * Depending on the data in a `DataSnapshot`, the `val()` method may return a + * scalar type (string, number, or boolean), an array, or an object. It may + * also return null, indicating that the `DataSnapshot` is empty (contains no + * data). + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + val() { + return this._node.val(); + } +} +/** + * + * Returns a `Reference` representing the location in the Database + * corresponding to the provided path. If no path is provided, the `Reference` + * will point to the root of the Database. + * + * @param db - The database instance to obtain a reference for. + * @param path - Optional path representing the location the returned + * `Reference` will point. If not provided, the returned `Reference` will + * point to the root of the Database. + * @returns If a path is provided, a `Reference` + * pointing to the provided path. Otherwise, a `Reference` pointing to the + * root of the Database. + */ +function ref(db, path) { + db = util.getModularInstance(db); + db._checkNotDeleted('ref'); + return path !== undefined ? child(db._root, path) : db._root; +} +/** + * Returns a `Reference` representing the location in the Database + * corresponding to the provided Firebase URL. + * + * An exception is thrown if the URL is not a valid Firebase Database URL or it + * has a different domain than the current `Database` instance. + * + * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored + * and are not applied to the returned `Reference`. + * + * @param db - The database instance to obtain a reference for. + * @param url - The Firebase URL at which the returned `Reference` will + * point. + * @returns A `Reference` pointing to the provided + * Firebase URL. + */ +function refFromURL(db, url) { + db = util.getModularInstance(db); + db._checkNotDeleted('refFromURL'); + const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin); + validateUrl('refFromURL', parsedURL); + const repoInfo = parsedURL.repoInfo; + if (!db._repo.repoInfo_.isCustomHost() && + repoInfo.host !== db._repo.repoInfo_.host) { + fatal('refFromURL' + + ': Host name does not match the current database: ' + + '(found ' + + repoInfo.host + + ' but expected ' + + db._repo.repoInfo_.host + + ')'); + } + return ref(db, parsedURL.path.toString()); +} +/** + * Gets a `Reference` for the location at the specified relative path. + * + * The relative path can either be a simple child name (for example, "ada") or + * a deeper slash-separated path (for example, "ada/name/first"). + * + * @param parent - The parent location. + * @param path - A relative path from this location to the desired child + * location. + * @returns The specified child location. + */ +function child(parent, path) { + parent = util.getModularInstance(parent); + if (pathGetFront(parent._path) === null) { + validateRootPathString('child', 'path', path, false); + } + else { + validatePathString('child', 'path', path, false); + } + return new ReferenceImpl(parent._repo, pathChild(parent._path, path)); +} +/** + * Returns an `OnDisconnect` object - see + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information on how to use it. + * + * @param ref - The reference to add OnDisconnect triggers for. + */ +function onDisconnect(ref) { + ref = util.getModularInstance(ref); + return new OnDisconnect$1(ref._repo, ref._path); +} +/** + * Generates a new child location using a unique key and returns its + * `Reference`. + * + * This is the most common pattern for adding data to a collection of items. + * + * If you provide a value to `push()`, the value is written to the + * generated location. If you don't pass a value, nothing is written to the + * database and the child remains empty (but you can use the `Reference` + * elsewhere). + * + * The unique keys generated by `push()` are ordered by the current time, so the + * resulting list of items is chronologically sorted. The keys are also + * designed to be unguessable (they contain 72 random bits of entropy). + * + * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}. + * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}. + * + * @param parent - The parent location. + * @param value - Optional value to be written at the generated location. + * @returns Combined `Promise` and `Reference`; resolves when write is complete, + * but can be used immediately as the `Reference` to the child location. + */ +function push(parent, value) { + parent = util.getModularInstance(parent); + validateWritablePath('push', parent._path); + validateFirebaseDataArg('push', value, parent._path, true); + const now = repoServerTime(parent._repo); + const name = nextPushId(now); + // push() returns a ThennableReference whose promise is fulfilled with a + // regular Reference. We use child() to create handles to two different + // references. The first is turned into a ThennableReference below by adding + // then() and catch() methods and is used as the return value of push(). The + // second remains a regular Reference and is used as the fulfilled value of + // the first ThennableReference. + const thenablePushRef = child(parent, name); + const pushRef = child(parent, name); + let promise; + if (value != null) { + promise = set(pushRef, value).then(() => pushRef); + } + else { + promise = Promise.resolve(pushRef); + } + thenablePushRef.then = promise.then.bind(promise); + thenablePushRef.catch = promise.then.bind(promise, undefined); + return thenablePushRef; +} +/** + * Removes the data at this Database location. + * + * Any data at child locations will also be deleted. + * + * The effect of the remove will be visible immediately and the corresponding + * event 'value' will be triggered. Synchronization of the remove to the + * Firebase servers will also be started, and the returned Promise will resolve + * when complete. If provided, the onComplete callback will be called + * asynchronously after synchronization has finished. + * + * @param ref - The location to remove. + * @returns Resolves when remove on server is complete. + */ +function remove(ref) { + validateWritablePath('remove', ref._path); + return set(ref, null); +} +/** + * Writes data to this Database location. + * + * This will overwrite any data at this location and all child locations. + * + * The effect of the write will be visible immediately, and the corresponding + * events ("value", "child_added", etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * Passing `null` for the new value is equivalent to calling `remove()`; namely, + * all data at this location and all child locations will be deleted. + * + * `set()` will remove any priority stored at this location, so if priority is + * meant to be preserved, you need to use `setWithPriority()` instead. + * + * Note that modifying data with `set()` will cancel any pending transactions + * at that location, so extreme care should be taken if mixing `set()` and + * `transaction()` to modify the same data. + * + * A single `set()` will generate a single "value" event at the location where + * the `set()` was performed. + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @returns Resolves when write to server is complete. + */ +function set(ref, value) { + ref = util.getModularInstance(ref); + validateWritablePath('set', ref._path); + validateFirebaseDataArg('set', value, ref._path, false); + const deferred = new util.Deferred(); + repoSetWithPriority(ref._repo, ref._path, value, + /*priority=*/ null, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Sets a priority for the data at this Database location. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +function setPriority(ref, priority) { + ref = util.getModularInstance(ref); + validateWritablePath('setPriority', ref._path); + validatePriority('setPriority', priority, false); + const deferred = new util.Deferred(); + repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Writes data the Database location. Like `set()` but also specifies the + * priority for that data. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +function setWithPriority(ref, value, priority) { + validateWritablePath('setWithPriority', ref._path); + validateFirebaseDataArg('setWithPriority', value, ref._path, false); + validatePriority('setWithPriority', priority, false); + if (ref.key === '.length' || ref.key === '.keys') { + throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.'; + } + const deferred = new util.Deferred(); + repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Writes multiple values to the Database at once. + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, + * "name/first") from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * The effect of the write will be visible immediately, and the corresponding + * events ('value', 'child_added', etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * A single `update()` will generate a single "value" event at the location + * where the `update()` was performed, regardless of how many children were + * modified. + * + * Note that modifying data with `update()` will cancel any pending + * transactions at that location, so extreme care should be taken if mixing + * `update()` and `transaction()` to modify the same data. + * + * Passing `null` to `update()` will remove the data at this location. + * + * See + * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}. + * + * @param ref - The location to write to. + * @param values - Object containing multiple values. + * @returns Resolves when update on server is complete. + */ +function update(ref, values) { + validateFirebaseMergeDataArg('update', values, ref._path, false); + const deferred = new util.Deferred(); + repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Gets the most up-to-date result for this query. + * + * @param query - The query to run. + * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is + * available, or rejects if the client is unable to return a value (e.g., if the + * server is unreachable and there is nothing cached). + */ +function get(query) { + query = util.getModularInstance(query); + const callbackContext = new CallbackContext(() => { }); + const container = new ValueEventRegistration(callbackContext); + return repoGetValue(query._repo, query, container).then(node => { + return new DataSnapshot$1(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex()); + }); +} +/** + * Represents registration for 'value' events. + */ +class ValueEventRegistration { + constructor(callbackContext) { + this.callbackContext = callbackContext; + } + respondsTo(eventType) { + return eventType === 'value'; + } + createEvent(change, query) { + const index = query._queryParams.getIndex(); + return new DataEvent('value', this, new DataSnapshot$1(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index)); + } + getEventRunner(eventData) { + if (eventData.getEventType() === 'cancel') { + return () => this.callbackContext.onCancel(eventData.error); + } + else { + return () => this.callbackContext.onValue(eventData.snapshot, null); + } + } + createCancelEvent(error, path) { + if (this.callbackContext.hasCancelCallback) { + return new CancelEvent(this, error, path); + } + else { + return null; + } + } + matches(other) { + if (!(other instanceof ValueEventRegistration)) { + return false; + } + else if (!other.callbackContext || !this.callbackContext) { + // If no callback specified, we consider it to match any callback. + return true; + } + else { + return other.callbackContext.matches(this.callbackContext); + } + } + hasAnyCallback() { + return this.callbackContext !== null; + } +} +/** + * Represents the registration of a child_x event. + */ +class ChildEventRegistration { + constructor(eventType, callbackContext) { + this.eventType = eventType; + this.callbackContext = callbackContext; + } + respondsTo(eventType) { + let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType; + eventToCheck = + eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck; + return this.eventType === eventToCheck; + } + createCancelEvent(error, path) { + if (this.callbackContext.hasCancelCallback) { + return new CancelEvent(this, error, path); + } + else { + return null; + } + } + createEvent(change, query) { + util.assert(change.childName != null, 'Child events should have a childName.'); + const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName); + const index = query._queryParams.getIndex(); + return new DataEvent(change.type, this, new DataSnapshot$1(change.snapshotNode, childRef, index), change.prevName); + } + getEventRunner(eventData) { + if (eventData.getEventType() === 'cancel') { + return () => this.callbackContext.onCancel(eventData.error); + } + else { + return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName); + } + } + matches(other) { + if (other instanceof ChildEventRegistration) { + return (this.eventType === other.eventType && + (!this.callbackContext || + !other.callbackContext || + this.callbackContext.matches(other.callbackContext))); + } + return false; + } + hasAnyCallback() { + return !!this.callbackContext; + } +} +function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) { + let cancelCallback; + if (typeof cancelCallbackOrListenOptions === 'object') { + cancelCallback = undefined; + options = cancelCallbackOrListenOptions; + } + if (typeof cancelCallbackOrListenOptions === 'function') { + cancelCallback = cancelCallbackOrListenOptions; + } + if (options && options.onlyOnce) { + const userCallback = callback; + const onceCallback = (dataSnapshot, previousChildName) => { + repoRemoveEventCallbackForQuery(query._repo, query, container); + userCallback(dataSnapshot, previousChildName); + }; + onceCallback.userCallback = callback.userCallback; + onceCallback.context = callback.context; + callback = onceCallback; + } + const callbackContext = new CallbackContext(callback, cancelCallback || undefined); + const container = eventType === 'value' + ? new ValueEventRegistration(callbackContext) + : new ChildEventRegistration(eventType, callbackContext); + repoAddEventCallbackForQuery(query._repo, query, container); + return () => repoRemoveEventCallbackForQuery(query._repo, query, container); +} +function onValue(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options); +} +function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options); +} +function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options); +} +function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options); +} +function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options); +} +/** + * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener. + * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from + * the respective `on*` callbacks. + * + * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener + * will not automatically remove listeners registered on child nodes, `off()` + * must also be called on any child listeners to remove the callback. + * + * If a callback is not specified, all callbacks for the specified eventType + * will be removed. Similarly, if no eventType is specified, all callbacks + * for the `Reference` will be removed. + * + * Individual listeners can also be removed by invoking their unsubscribe + * callbacks. + * + * @param query - The query that the listener was registered with. + * @param eventType - One of the following strings: "value", "child_added", + * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks + * for the `Reference` will be removed. + * @param callback - The callback function that was passed to `on()` or + * `undefined` to remove all callbacks. + */ +function off(query, eventType, callback) { + let container = null; + const expCallback = callback ? new CallbackContext(callback) : null; + if (eventType === 'value') { + container = new ValueEventRegistration(expCallback); + } + else if (eventType) { + container = new ChildEventRegistration(eventType, expCallback); + } + repoRemoveEventCallbackForQuery(query._repo, query, container); +} +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Database query. `QueryConstraint`s are created by invoking {@link endAt}, + * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link + * limitToFirst}, {@link limitToLast}, {@link orderByChild}, + * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} , + * {@link orderByValue} or {@link equalTo} and + * can then be passed to {@link query} to create a new query instance that + * also contains this `QueryConstraint`. + */ +class QueryConstraint { +} +class QueryEndAtConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'endAt'; + } + _apply(query) { + validateFirebaseDataArg('endAt', this._value, query._path, true); + const newParams = queryParamsEndAt(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasEnd()) { + throw new Error('endAt: Starting point was already set (by another call to endAt, ' + + 'endBefore or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified ending point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name less than or equal + * to the specified key. + * + * You can read more about `endAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to end at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end at, among the children with the previously + * specified priority. This argument is only allowed if ordering by child, + * value, or priority. + */ +function endAt(value, key) { + validateKey('endAt', 'key', key, true); + return new QueryEndAtConstraint(value, key); +} +class QueryEndBeforeConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'endBefore'; + } + _apply(query) { + validateFirebaseDataArg('endBefore', this._value, query._path, false); + const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasEnd()) { + throw new Error('endBefore: Starting point was already set (by another call to endAt, ' + + 'endBefore or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified ending point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is exclusive. If only a value is provided, children + * with a value less than the specified value will be included in the query. + * If a key is specified, then children must have a value less than or equal + * to the specified value and a key name less than the specified key. + * + * @param value - The value to end before. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end before, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +function endBefore(value, key) { + validateKey('endBefore', 'key', key, true); + return new QueryEndBeforeConstraint(value, key); +} +class QueryStartAtConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'startAt'; + } + _apply(query) { + validateFirebaseDataArg('startAt', this._value, query._path, true); + const newParams = queryParamsStartAt(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasStart()) { + throw new Error('startAt: Starting point was already set (by another call to startAt, ' + + 'startBefore or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified starting point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name greater than or + * equal to the specified key. + * + * You can read more about `startAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to start at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at. This argument is only allowed if + * ordering by child, value, or priority. + */ +function startAt(value = null, key) { + validateKey('startAt', 'key', key, true); + return new QueryStartAtConstraint(value, key); +} +class QueryStartAfterConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'startAfter'; + } + _apply(query) { + validateFirebaseDataArg('startAfter', this._value, query._path, false); + const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasStart()) { + throw new Error('startAfter: Starting point was already set (by another call to startAt, ' + + 'startAfter, or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified starting point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is exclusive. If only a value is provided, children + * with a value greater than the specified value will be included in the query. + * If a key is specified, then children must have a value greater than or equal + * to the specified value and a a key name greater than the specified key. + * + * @param value - The value to start after. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start after. This argument is only allowed if + * ordering by child, value, or priority. + */ +function startAfter(value, key) { + validateKey('startAfter', 'key', key, true); + return new QueryStartAfterConstraint(value, key); +} +class QueryLimitToFirstConstraint extends QueryConstraint { + constructor(_limit) { + super(); + this._limit = _limit; + this.type = 'limitToFirst'; + } + _apply(query) { + if (query._queryParams.hasLimit()) { + throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' + + 'or limitToLast).'); + } + return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled); + } +} +/** + * Creates a new `QueryConstraint` that if limited to the first specific number + * of children. + * + * The `limitToFirst()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the first 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToFirst()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +function limitToFirst(limit) { + if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) { + throw new Error('limitToFirst: First argument must be a positive integer.'); + } + return new QueryLimitToFirstConstraint(limit); +} +class QueryLimitToLastConstraint extends QueryConstraint { + constructor(_limit) { + super(); + this._limit = _limit; + this.type = 'limitToLast'; + } + _apply(query) { + if (query._queryParams.hasLimit()) { + throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' + + 'or limitToLast).'); + } + return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled); + } +} +/** + * Creates a new `QueryConstraint` that is limited to return only the last + * specified number of children. + * + * The `limitToLast()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the last 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToLast()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +function limitToLast(limit) { + if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) { + throw new Error('limitToLast: First argument must be a positive integer.'); + } + return new QueryLimitToLastConstraint(limit); +} +class QueryOrderByChildConstraint extends QueryConstraint { + constructor(_path) { + super(); + this._path = _path; + this.type = 'orderByChild'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByChild'); + const parsedPath = new Path(this._path); + if (pathIsEmpty(parsedPath)) { + throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.'); + } + const index = new PathIndex(parsedPath); + const newParams = queryParamsOrderBy(query._queryParams, index); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by the specified child key. + * + * Queries can only order by one key at a time. Calling `orderByChild()` + * multiple times on the same query is an error. + * + * Firebase queries allow you to order your data by any child key on the fly. + * However, if you know in advance what your indexes will be, you can define + * them via the .indexOn rule in your Security Rules for better performance. See + * the{@link https://firebase.google.com/docs/database/security/indexing-data} + * rule for more information. + * + * You can read more about `orderByChild()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + * + * @param path - The path to order by. + */ +function orderByChild(path) { + if (path === '$key') { + throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.'); + } + else if (path === '$priority') { + throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.'); + } + else if (path === '$value') { + throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.'); + } + validatePathString('orderByChild', 'path', path, false); + return new QueryOrderByChildConstraint(path); +} +class QueryOrderByKeyConstraint extends QueryConstraint { + constructor() { + super(...arguments); + this.type = 'orderByKey'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByKey'); + const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by the key. + * + * Sorts the results of a query by their (ascending) key values. + * + * You can read more about `orderByKey()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +function orderByKey() { + return new QueryOrderByKeyConstraint(); +} +class QueryOrderByPriorityConstraint extends QueryConstraint { + constructor() { + super(...arguments); + this.type = 'orderByPriority'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByPriority'); + const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by priority. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data} + * for alternatives to priority. + */ +function orderByPriority() { + return new QueryOrderByPriorityConstraint(); +} +class QueryOrderByValueConstraint extends QueryConstraint { + constructor() { + super(...arguments); + this.type = 'orderByValue'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByValue'); + const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by value. + * + * If the children of a query are all scalar values (string, number, or + * boolean), you can order the results by their (ascending) values. + * + * You can read more about `orderByValue()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +function orderByValue() { + return new QueryOrderByValueConstraint(); +} +class QueryEqualToValueConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'equalTo'; + } + _apply(query) { + validateFirebaseDataArg('equalTo', this._value, query._path, false); + if (query._queryParams.hasStart()) { + throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' + + 'equalTo).'); + } + if (query._queryParams.hasEnd()) { + throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' + + 'equalTo).'); + } + return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query)); + } +} +/** + * Creates a `QueryConstraint` that includes children that match the specified + * value. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The optional key argument can be used to further limit the range of the + * query. If it is specified, then children that have exactly the specified + * value must also have exactly the specified key as their key name. This can be + * used to filter result sets with many matches for the same value. + * + * You can read more about `equalTo()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to match for. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +function equalTo(value, key) { + validateKey('equalTo', 'key', key, true); + return new QueryEqualToValueConstraint(value, key); +} +/** + * Creates a new immutable instance of `Query` that is extended to also include + * additional query constraints. + * + * @param query - The Query instance to use as a base for the new constraints. + * @param queryConstraints - The list of `QueryConstraint`s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +function query(query, ...queryConstraints) { + let queryImpl = util.getModularInstance(query); + for (const constraint of queryConstraints) { + queryImpl = constraint._apply(queryImpl); + } + return queryImpl; +} +/** + * Define reference constructor in various modules + * + * We are doing this here to avoid several circular + * dependency issues + */ +syncPointSetReferenceConstructor(ReferenceImpl); +syncTreeSetReferenceConstructor(ReferenceImpl); + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This variable is also defined in the firebase Node.js Admin SDK. Before + * modifying this definition, consult the definition in: + * + * https://github.com/firebase/firebase-admin-node + * + * and make sure the two are consistent. + */ +const FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST'; +/** + * Creates and caches `Repo` instances. + */ +const repos = {}; +/** + * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes). + */ +let useRestClient = false; +/** + * Update an existing `Repo` in place to point to a new host/port. + */ +function repoManagerApplyEmulatorSettings(repo, hostAndPort, emulatorOptions, tokenProvider) { + const portIndex = hostAndPort.lastIndexOf(':'); + const host = hostAndPort.substring(0, portIndex); + const useSsl = util.isCloudWorkstation(host); + repo.repoInfo_ = new RepoInfo(hostAndPort, + /* secure= */ useSsl, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams, + /*isUsingEmulator=*/ true, emulatorOptions); + if (tokenProvider) { + repo.authTokenProvider_ = tokenProvider; + } +} +/** + * This function should only ever be called to CREATE a new database instance. + * @internal + */ +function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) { + let dbUrl = url || app.options.databaseURL; + if (dbUrl === undefined) { + if (!app.options.projectId) { + fatal("Can't determine Firebase Database URL. Be sure to include " + + ' a Project ID when calling firebase.initializeApp().'); + } + log('Using default host for project ', app.options.projectId); + dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`; + } + let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin); + let repoInfo = parsedUrl.repoInfo; + let isEmulator; + let dbEmulatorHost = undefined; + if (typeof process !== 'undefined' && process.env) { + dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR]; + } + if (dbEmulatorHost) { + isEmulator = true; + dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`; + parsedUrl = parseRepoInfo(dbUrl, nodeAdmin); + repoInfo = parsedUrl.repoInfo; + } + else { + isEmulator = !parsedUrl.repoInfo.secure; + } + const authTokenProvider = nodeAdmin && isEmulator + ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER) + : new FirebaseAuthTokenProvider(app.name, app.options, authProvider); + validateUrl('Invalid Firebase Database URL', parsedUrl); + if (!pathIsEmpty(parsedUrl.path)) { + fatal('Database URL must point to the root of a Firebase Database ' + + '(not including a child path).'); + } + const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app, appCheckProvider)); + return new Database$1(repo, app); +} +/** + * Remove the repo and make sure it is disconnected. + * + */ +function repoManagerDeleteRepo(repo, appName) { + const appRepos = repos[appName]; + // This should never happen... + if (!appRepos || appRepos[repo.key] !== repo) { + fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`); + } + repoInterrupt(repo); + delete appRepos[repo.key]; +} +/** + * Ensures a repo doesn't already exist and then creates one using the + * provided app. + * + * @param repoInfo - The metadata about the Repo + * @returns The Repo object for the specified server / repoName. + */ +function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) { + let appRepos = repos[app.name]; + if (!appRepos) { + appRepos = {}; + repos[app.name] = appRepos; + } + let repo = appRepos[repoInfo.toURLString()]; + if (repo) { + fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.'); + } + repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider); + appRepos[repoInfo.toURLString()] = repo; + return repo; +} +/** + * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos. + */ +function repoManagerForceRestClient(forceRestClient) { + useRestClient = forceRestClient; +} +/** + * Class representing a Firebase Realtime Database. + */ +class Database$1 { + /** @hideconstructor */ + constructor(_repoInternal, + /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */ + app) { + this._repoInternal = _repoInternal; + this.app = app; + /** Represents a `Database` instance. */ + this['type'] = 'database'; + /** Track if the instance has been used (root or repo accessed) */ + this._instanceStarted = false; + } + get _repo() { + if (!this._instanceStarted) { + repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']); + this._instanceStarted = true; + } + return this._repoInternal; + } + get _root() { + if (!this._rootInternal) { + this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath()); + } + return this._rootInternal; + } + _delete() { + if (this._rootInternal !== null) { + repoManagerDeleteRepo(this._repo, this.app.name); + this._repoInternal = null; + this._rootInternal = null; + } + return Promise.resolve(); + } + _checkNotDeleted(apiName) { + if (this._rootInternal === null) { + fatal('Cannot call ' + apiName + ' on a deleted database.'); + } + } +} +function checkTransportInit() { + if (TransportManager.IS_TRANSPORT_INITIALIZED) { + warn$1('Transport has already been initialized. Please call this function before calling ref or setting up a listener'); + } +} +/** + * Force the use of websockets instead of longPolling. + */ +function forceWebSockets() { + checkTransportInit(); + BrowserPollConnection.forceDisallow(); +} +/** + * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL. + */ +function forceLongPolling() { + checkTransportInit(); + WebSocketConnection.forceDisallow(); + BrowserPollConnection.forceAllow(); +} +/** + * Modify the provided instance to communicate with the Realtime Database + * emulator. + * + *

Note: This method must be called before performing any other operation. + * + * @param db - The instance to modify. + * @param host - The emulator host (ex: localhost) + * @param port - The emulator port (ex: 8080) + * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules + */ +function connectDatabaseEmulator(db, host, port, options = {}) { + db = util.getModularInstance(db); + db._checkNotDeleted('useEmulator'); + const hostAndPort = `${host}:${port}`; + const repo = db._repoInternal; + if (db._instanceStarted) { + // If the instance has already been started, then silenty fail if this function is called again + // with the same parameters. If the parameters differ then assert. + if (hostAndPort === db._repoInternal.repoInfo_.host && + util.deepEqual(options, repo.repoInfo_.emulatorOptions)) { + return; + } + fatal('connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.'); + } + let tokenProvider = undefined; + if (repo.repoInfo_.nodeAdmin) { + if (options.mockUserToken) { + fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'); + } + tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER); + } + else if (options.mockUserToken) { + const token = typeof options.mockUserToken === 'string' + ? options.mockUserToken + : util.createMockUserToken(options.mockUserToken, db.app.options.projectId); + tokenProvider = new EmulatorTokenProvider(token); + } + // Workaround to get cookies in Firebase Studio + if (util.isCloudWorkstation(host)) { + void util.pingServer(host); + util.updateEmulatorBanner('Database', true); + } + // Modify the repo to apply emulator settings + repoManagerApplyEmulatorSettings(repo, hostAndPort, options, tokenProvider); +} +/** + * Disconnects from the server (all Database operations will be completed + * offline). + * + * The client automatically maintains a persistent connection to the Database + * server, which will remain active indefinitely and reconnect when + * disconnected. However, the `goOffline()` and `goOnline()` methods may be used + * to control the client connection in cases where a persistent connection is + * undesirable. + * + * While offline, the client will no longer receive data updates from the + * Database. However, all Database operations performed locally will continue to + * immediately fire events, allowing your application to continue behaving + * normally. Additionally, each operation performed locally will automatically + * be queued and retried upon reconnection to the Database server. + * + * To reconnect to the Database and begin receiving remote events, see + * `goOnline()`. + * + * @param db - The instance to disconnect. + */ +function goOffline(db) { + db = util.getModularInstance(db); + db._checkNotDeleted('goOffline'); + repoInterrupt(db._repo); +} +/** + * Reconnects to the server and synchronizes the offline Database state + * with the server state. + * + * This method should be used after disabling the active connection with + * `goOffline()`. Once reconnected, the client will transmit the proper data + * and fire the appropriate events so that your client "catches up" + * automatically. + * + * @param db - The instance to reconnect. + */ +function goOnline(db) { + db = util.getModularInstance(db); + db._checkNotDeleted('goOnline'); + repoResume(db._repo); +} +function enableLogging(logger, persistent) { + enableLogging$1(logger, persistent); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const SERVER_TIMESTAMP = { + '.sv': 'timestamp' +}; +/** + * Returns a placeholder value for auto-populating the current timestamp (time + * since the Unix epoch, in milliseconds) as determined by the Firebase + * servers. + */ +function serverTimestamp() { + return SERVER_TIMESTAMP; +} +/** + * Returns a placeholder value that can be used to atomically increment the + * current database value by the provided delta. + * + * @param delta - the amount to modify the current value atomically. + * @returns A placeholder value for modifying data atomically server-side. + */ +function increment(delta) { + return { + '.sv': { + 'increment': delta + } + }; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A type for the resolve value of {@link runTransaction}. + */ +class TransactionResult$1 { + /** @hideconstructor */ + constructor( + /** Whether the transaction was successfully committed. */ + committed, + /** The resulting data snapshot. */ + snapshot) { + this.committed = committed; + this.snapshot = snapshot; + } + /** Returns a JSON-serializable representation of this object. */ + toJSON() { + return { committed: this.committed, snapshot: this.snapshot.toJSON() }; + } +} +/** + * Atomically modifies the data at this location. + * + * Atomically modify the data at this location. Unlike a normal `set()`, which + * just overwrites the data regardless of its previous value, `runTransaction()` is + * used to modify the existing value to a new value, ensuring there are no + * conflicts with other clients writing to the same location at the same time. + * + * To accomplish this, you pass `runTransaction()` an update function which is + * used to transform the current value into a new value. If another client + * writes to the location before your new value is successfully written, your + * update function will be called again with the new current value, and the + * write will be retried. This will happen repeatedly until your write succeeds + * without conflict or you abort the transaction by not returning a value from + * your update function. + * + * Note: Modifying data with `set()` will cancel any pending transactions at + * that location, so extreme care should be taken if mixing `set()` and + * `runTransaction()` to update the same data. + * + * Note: When using transactions with Security and Firebase Rules in place, be + * aware that a client needs `.read` access in addition to `.write` access in + * order to perform a transaction. This is because the client-side nature of + * transactions requires the client to read the data in order to transactionally + * update it. + * + * @param ref - The location to atomically modify. + * @param transactionUpdate - A developer-supplied function which will be passed + * the current data stored at this location (as a JavaScript object). The + * function should return the new value it would like written (as a JavaScript + * object). If `undefined` is returned (i.e. you return with no arguments) the + * transaction will be aborted and the data at this location will not be + * modified. + * @param options - An options object to configure transactions. + * @returns A `Promise` that can optionally be used instead of the `onComplete` + * callback to handle success and failure. + */ +function runTransaction(ref, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +transactionUpdate, options) { + ref = util.getModularInstance(ref); + validateWritablePath('Reference.transaction', ref._path); + if (ref.key === '.length' || ref.key === '.keys') { + throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.'); + } + const applyLocally = options?.applyLocally ?? true; + const deferred = new util.Deferred(); + const promiseComplete = (error, committed, node) => { + let dataSnapshot = null; + if (error) { + deferred.reject(error); + } + else { + dataSnapshot = new DataSnapshot$1(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX); + deferred.resolve(new TransactionResult$1(committed, dataSnapshot)); + } + }; + // Add a watch to make sure we get server updates. + const unwatcher = onValue(ref, () => { }); + repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally); + return deferred.promise; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +PersistentConnection.prototype.simpleListen = function (pathString, onComplete) { + this.sendRequest('q', { p: pathString }, onComplete); +}; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +PersistentConnection.prototype.echo = function (data, onEcho) { + this.sendRequest('echo', { d: data }, onEcho); +}; +/** + * @internal + */ +const hijackHash = function (newHash) { + const oldPut = PersistentConnection.prototype.put; + PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) { + if (hash !== undefined) { + hash = newHash(); + } + oldPut.call(this, pathString, data, onComplete, hash); + }; + return function () { + PersistentConnection.prototype.put = oldPut; + }; +}; +/** + * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection. + * @internal + */ +const forceRestClient = function (forceRestClient) { + repoManagerForceRestClient(forceRestClient); +}; + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Used by console to create a database based on the app, + * passed database URL and a custom auth implementation. + * @internal + * @param app - A valid FirebaseApp-like object + * @param url - A valid Firebase databaseURL + * @param version - custom version e.g. firebase-admin version + * @param customAppCheckImpl - custom app check implementation + * @param customAuthImpl - custom auth implementation + */ +function _initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, nodeAdmin = false }) { + setSDKVersion(version); + /** + * ComponentContainer('database-standalone') is just a placeholder that doesn't perform + * any actual function. + */ + const componentContainer = new component.ComponentContainer('database-standalone'); + const authProvider = new component.Provider('auth-internal', componentContainer); + let appCheckProvider; + if (customAppCheckImpl) { + appCheckProvider = new component.Provider('app-check-internal', componentContainer); + appCheckProvider.setComponent(new component.Component('app-check-internal', () => customAppCheckImpl, "PRIVATE" /* ComponentType.PRIVATE */)); + } + authProvider.setComponent(new component.Component('auth-internal', () => customAuthImpl, "PRIVATE" /* ComponentType.PRIVATE */)); + return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin); +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +setWebSocketImpl(Websocket__default["default"].Client); + +index_standalone.DataSnapshot = DataSnapshot$1; +index_standalone.Database = Database$1; +var OnDisconnect_1 = index_standalone.OnDisconnect = OnDisconnect$1; +index_standalone.QueryConstraint = QueryConstraint; +index_standalone.TransactionResult = TransactionResult$1; +var _QueryImpl = index_standalone._QueryImpl = QueryImpl; +var _QueryParams = index_standalone._QueryParams = QueryParams; +var _ReferenceImpl = index_standalone._ReferenceImpl = ReferenceImpl; +index_standalone._TEST_ACCESS_forceRestClient = forceRestClient; +index_standalone._TEST_ACCESS_hijackHash = hijackHash; +index_standalone._initStandalone = _initStandalone; +var _repoManagerDatabaseFromApp = index_standalone._repoManagerDatabaseFromApp = repoManagerDatabaseFromApp; +var _setSDKVersion = index_standalone._setSDKVersion = setSDKVersion; +var _validatePathString = index_standalone._validatePathString = validatePathString; +var _validateWritablePath = index_standalone._validateWritablePath = validateWritablePath; +var child_1 = index_standalone.child = child; +var connectDatabaseEmulator_1 = index_standalone.connectDatabaseEmulator = connectDatabaseEmulator; +var enableLogging_1 = index_standalone.enableLogging = enableLogging; +var endAt_1 = index_standalone.endAt = endAt; +var endBefore_1 = index_standalone.endBefore = endBefore; +var equalTo_1 = index_standalone.equalTo = equalTo; +var forceLongPolling_1 = index_standalone.forceLongPolling = forceLongPolling; +var forceWebSockets_1 = index_standalone.forceWebSockets = forceWebSockets; +var get_1 = index_standalone.get = get; +var goOffline_1 = index_standalone.goOffline = goOffline; +var goOnline_1 = index_standalone.goOnline = goOnline; +var increment_1 = index_standalone.increment = increment; +var limitToFirst_1 = index_standalone.limitToFirst = limitToFirst; +var limitToLast_1 = index_standalone.limitToLast = limitToLast; +var off_1 = index_standalone.off = off; +var onChildAdded_1 = index_standalone.onChildAdded = onChildAdded; +var onChildChanged_1 = index_standalone.onChildChanged = onChildChanged; +var onChildMoved_1 = index_standalone.onChildMoved = onChildMoved; +var onChildRemoved_1 = index_standalone.onChildRemoved = onChildRemoved; +index_standalone.onDisconnect = onDisconnect; +var onValue_1 = index_standalone.onValue = onValue; +var orderByChild_1 = index_standalone.orderByChild = orderByChild; +var orderByKey_1 = index_standalone.orderByKey = orderByKey; +var orderByPriority_1 = index_standalone.orderByPriority = orderByPriority; +var orderByValue_1 = index_standalone.orderByValue = orderByValue; +var push_1 = index_standalone.push = push; +var query_1 = index_standalone.query = query; +var ref_1 = index_standalone.ref = ref; +var refFromURL_1 = index_standalone.refFromURL = refFromURL; +var remove_1 = index_standalone.remove = remove; +var runTransaction_1 = index_standalone.runTransaction = runTransaction; +var serverTimestamp_1 = index_standalone.serverTimestamp = serverTimestamp; +var set_1 = index_standalone.set = set; +var setPriority_1 = index_standalone.setPriority = setPriority; +var setWithPriority_1 = index_standalone.setWithPriority = setWithPriority; +var startAfter_1 = index_standalone.startAfter = startAfter; +var startAt_1 = index_standalone.startAt = startAt; +var update_1 = index_standalone.update = update; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const logClient = new require$$1$3.Logger('@firebase/database-compat'); +const warn = function (msg) { + const message = 'FIREBASE WARNING: ' + msg; + logClient.warn(message); +}; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const validateBoolean = function (fnName, argumentName, bool, optional) { + if (optional && bool === undefined) { + return; + } + if (typeof bool !== 'boolean') { + throw new Error(require$$2$3.errorPrefix(fnName, argumentName) + 'must be a boolean.'); + } +}; +const validateEventType = function (fnName, eventType, optional) { + if (optional && eventType === undefined) { + return; + } + switch (eventType) { + case 'value': + case 'child_added': + case 'child_removed': + case 'child_changed': + case 'child_moved': + break; + default: + throw new Error(require$$2$3.errorPrefix(fnName, 'eventType') + + 'must be a valid event type = "value", "child_added", "child_removed", ' + + '"child_changed", or "child_moved".'); + } +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class OnDisconnect { + constructor(_delegate) { + this._delegate = _delegate; + } + cancel(onComplete) { + require$$2$3.validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length); + require$$2$3.validateCallback('OnDisconnect.cancel', 'onComplete', onComplete, true); + const result = this._delegate.cancel(); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + remove(onComplete) { + require$$2$3.validateArgCount('OnDisconnect.remove', 0, 1, arguments.length); + require$$2$3.validateCallback('OnDisconnect.remove', 'onComplete', onComplete, true); + const result = this._delegate.remove(); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + set(value, onComplete) { + require$$2$3.validateArgCount('OnDisconnect.set', 1, 2, arguments.length); + require$$2$3.validateCallback('OnDisconnect.set', 'onComplete', onComplete, true); + const result = this._delegate.set(value); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + setWithPriority(value, priority, onComplete) { + require$$2$3.validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length); + require$$2$3.validateCallback('OnDisconnect.setWithPriority', 'onComplete', onComplete, true); + const result = this._delegate.setWithPriority(value, priority); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + update(objectToMerge, onComplete) { + require$$2$3.validateArgCount('OnDisconnect.update', 1, 2, arguments.length); + if (Array.isArray(objectToMerge)) { + const newObjectToMerge = {}; + for (let i = 0; i < objectToMerge.length; ++i) { + newObjectToMerge['' + i] = objectToMerge[i]; + } + objectToMerge = newObjectToMerge; + warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' + + 'existing data, or an Object with integer keys if you really do want to only update some of the children.'); + } + require$$2$3.validateCallback('OnDisconnect.update', 'onComplete', onComplete, true); + const result = this._delegate.update(objectToMerge); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class TransactionResult { + /** + * A type for the resolve value of Firebase.transaction. + */ + constructor(committed, snapshot) { + this.committed = committed; + this.snapshot = snapshot; + } + // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary + // for end-users + toJSON() { + require$$2$3.validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length); + return { committed: this.committed, snapshot: this.snapshot.toJSON() }; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Class representing a firebase data snapshot. It wraps a SnapshotNode and + * surfaces the public methods (val, forEach, etc.) we want to expose. + */ +class DataSnapshot { + constructor(_database, _delegate) { + this._database = _database; + this._delegate = _delegate; + } + /** + * Retrieves the snapshot contents as JSON. Returns null if the snapshot is + * empty. + * + * @returns JSON representation of the DataSnapshot contents, or null if empty. + */ + val() { + require$$2$3.validateArgCount('DataSnapshot.val', 0, 0, arguments.length); + return this._delegate.val(); + } + /** + * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting + * the entire node contents. + * @returns JSON representation of the DataSnapshot contents, or null if empty. + */ + exportVal() { + require$$2$3.validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length); + return this._delegate.exportVal(); + } + // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary + // for end-users + toJSON() { + // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content + require$$2$3.validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length); + return this._delegate.toJSON(); + } + /** + * Returns whether the snapshot contains a non-null value. + * + * @returns Whether the snapshot contains a non-null value, or is empty. + */ + exists() { + require$$2$3.validateArgCount('DataSnapshot.exists', 0, 0, arguments.length); + return this._delegate.exists(); + } + /** + * Returns a DataSnapshot of the specified child node's contents. + * + * @param path - Path to a child. + * @returns DataSnapshot for child node. + */ + child(path) { + require$$2$3.validateArgCount('DataSnapshot.child', 0, 1, arguments.length); + // Ensure the childPath is a string (can be a number) + path = String(path); + _validatePathString('DataSnapshot.child', 'path', path, false); + return new DataSnapshot(this._database, this._delegate.child(path)); + } + /** + * Returns whether the snapshot contains a child at the specified path. + * + * @param path - Path to a child. + * @returns Whether the child exists. + */ + hasChild(path) { + require$$2$3.validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length); + _validatePathString('DataSnapshot.hasChild', 'path', path, false); + return this._delegate.hasChild(path); + } + /** + * Returns the priority of the object, or null if no priority was set. + * + * @returns The priority. + */ + getPriority() { + require$$2$3.validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length); + return this._delegate.priority; + } + /** + * Iterates through child nodes and calls the specified action for each one. + * + * @param action - Callback function to be called + * for each child. + * @returns True if forEach was canceled by action returning true for + * one of the child nodes. + */ + forEach(action) { + require$$2$3.validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length); + require$$2$3.validateCallback('DataSnapshot.forEach', 'action', action, false); + return this._delegate.forEach(expDataSnapshot => action(new DataSnapshot(this._database, expDataSnapshot))); + } + /** + * Returns whether this DataSnapshot has children. + * @returns True if the DataSnapshot contains 1 or more child nodes. + */ + hasChildren() { + require$$2$3.validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length); + return this._delegate.hasChildren(); + } + get key() { + return this._delegate.key; + } + /** + * Returns the number of children for this DataSnapshot. + * @returns The number of children that this DataSnapshot contains. + */ + numChildren() { + require$$2$3.validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length); + return this._delegate.size; + } + /** + * @returns The Firebase reference for the location this snapshot's data came + * from. + */ + getRef() { + require$$2$3.validateArgCount('DataSnapshot.ref', 0, 0, arguments.length); + return new Reference(this._database, this._delegate.ref); + } + get ref() { + return this.getRef(); + } +} +/** + * A Query represents a filter to be applied to a firebase location. This object purely represents the + * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js. + * + * Since every Firebase reference is a query, Firebase inherits from this object. + */ +class Query { + constructor(database, _delegate) { + this.database = database; + this._delegate = _delegate; + } + on(eventType, callback, cancelCallbackOrContext, context) { + require$$2$3.validateArgCount('Query.on', 2, 4, arguments.length); + require$$2$3.validateCallback('Query.on', 'callback', callback, false); + const ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context); + const valueCallback = (expSnapshot, previousChildName) => { + callback.call(ret.context, new DataSnapshot(this.database, expSnapshot), previousChildName); + }; + valueCallback.userCallback = callback; + valueCallback.context = ret.context; + const cancelCallback = ret.cancel?.bind(ret.context); + switch (eventType) { + case 'value': + onValue_1(this._delegate, valueCallback, cancelCallback); + return callback; + case 'child_added': + onChildAdded_1(this._delegate, valueCallback, cancelCallback); + return callback; + case 'child_removed': + onChildRemoved_1(this._delegate, valueCallback, cancelCallback); + return callback; + case 'child_changed': + onChildChanged_1(this._delegate, valueCallback, cancelCallback); + return callback; + case 'child_moved': + onChildMoved_1(this._delegate, valueCallback, cancelCallback); + return callback; + default: + throw new Error(require$$2$3.errorPrefix('Query.on', 'eventType') + + 'must be a valid event type = "value", "child_added", "child_removed", ' + + '"child_changed", or "child_moved".'); + } + } + off(eventType, callback, context) { + require$$2$3.validateArgCount('Query.off', 0, 3, arguments.length); + validateEventType('Query.off', eventType, true); + require$$2$3.validateCallback('Query.off', 'callback', callback, true); + require$$2$3.validateContextObject('Query.off', 'context', context, true); + if (callback) { + const valueCallback = () => { }; + valueCallback.userCallback = callback; + valueCallback.context = context; + off_1(this._delegate, eventType, valueCallback); + } + else { + off_1(this._delegate, eventType); + } + } + /** + * Get the server-value for this query, or return a cached value if not connected. + */ + get() { + return get_1(this._delegate).then(expSnapshot => { + return new DataSnapshot(this.database, expSnapshot); + }); + } + /** + * Attaches a listener, waits for the first event, and then removes the listener + */ + once(eventType, callback, failureCallbackOrContext, context) { + require$$2$3.validateArgCount('Query.once', 1, 4, arguments.length); + require$$2$3.validateCallback('Query.once', 'callback', callback, true); + const ret = Query.getCancelAndContextArgs_('Query.once', failureCallbackOrContext, context); + const deferred = new require$$2$3.Deferred(); + const valueCallback = (expSnapshot, previousChildName) => { + const result = new DataSnapshot(this.database, expSnapshot); + if (callback) { + callback.call(ret.context, result, previousChildName); + } + deferred.resolve(result); + }; + valueCallback.userCallback = callback; + valueCallback.context = ret.context; + const cancelCallback = (error) => { + if (ret.cancel) { + ret.cancel.call(ret.context, error); + } + deferred.reject(error); + }; + switch (eventType) { + case 'value': + onValue_1(this._delegate, valueCallback, cancelCallback, { + onlyOnce: true + }); + break; + case 'child_added': + onChildAdded_1(this._delegate, valueCallback, cancelCallback, { + onlyOnce: true + }); + break; + case 'child_removed': + onChildRemoved_1(this._delegate, valueCallback, cancelCallback, { + onlyOnce: true + }); + break; + case 'child_changed': + onChildChanged_1(this._delegate, valueCallback, cancelCallback, { + onlyOnce: true + }); + break; + case 'child_moved': + onChildMoved_1(this._delegate, valueCallback, cancelCallback, { + onlyOnce: true + }); + break; + default: + throw new Error(require$$2$3.errorPrefix('Query.once', 'eventType') + + 'must be a valid event type = "value", "child_added", "child_removed", ' + + '"child_changed", or "child_moved".'); + } + return deferred.promise; + } + /** + * Set a limit and anchor it to the start of the window. + */ + limitToFirst(limit) { + require$$2$3.validateArgCount('Query.limitToFirst', 1, 1, arguments.length); + return new Query(this.database, query_1(this._delegate, limitToFirst_1(limit))); + } + /** + * Set a limit and anchor it to the end of the window. + */ + limitToLast(limit) { + require$$2$3.validateArgCount('Query.limitToLast', 1, 1, arguments.length); + return new Query(this.database, query_1(this._delegate, limitToLast_1(limit))); + } + /** + * Given a child path, return a new query ordered by the specified grandchild path. + */ + orderByChild(path) { + require$$2$3.validateArgCount('Query.orderByChild', 1, 1, arguments.length); + return new Query(this.database, query_1(this._delegate, orderByChild_1(path))); + } + /** + * Return a new query ordered by the KeyIndex + */ + orderByKey() { + require$$2$3.validateArgCount('Query.orderByKey', 0, 0, arguments.length); + return new Query(this.database, query_1(this._delegate, orderByKey_1())); + } + /** + * Return a new query ordered by the PriorityIndex + */ + orderByPriority() { + require$$2$3.validateArgCount('Query.orderByPriority', 0, 0, arguments.length); + return new Query(this.database, query_1(this._delegate, orderByPriority_1())); + } + /** + * Return a new query ordered by the ValueIndex + */ + orderByValue() { + require$$2$3.validateArgCount('Query.orderByValue', 0, 0, arguments.length); + return new Query(this.database, query_1(this._delegate, orderByValue_1())); + } + startAt(value = null, name) { + require$$2$3.validateArgCount('Query.startAt', 0, 2, arguments.length); + return new Query(this.database, query_1(this._delegate, startAt_1(value, name))); + } + startAfter(value = null, name) { + require$$2$3.validateArgCount('Query.startAfter', 0, 2, arguments.length); + return new Query(this.database, query_1(this._delegate, startAfter_1(value, name))); + } + endAt(value = null, name) { + require$$2$3.validateArgCount('Query.endAt', 0, 2, arguments.length); + return new Query(this.database, query_1(this._delegate, endAt_1(value, name))); + } + endBefore(value = null, name) { + require$$2$3.validateArgCount('Query.endBefore', 0, 2, arguments.length); + return new Query(this.database, query_1(this._delegate, endBefore_1(value, name))); + } + /** + * Load the selection of children with exactly the specified value, and, optionally, + * the specified name. + */ + equalTo(value, name) { + require$$2$3.validateArgCount('Query.equalTo', 1, 2, arguments.length); + return new Query(this.database, query_1(this._delegate, equalTo_1(value, name))); + } + /** + * @returns URL for this location. + */ + toString() { + require$$2$3.validateArgCount('Query.toString', 0, 0, arguments.length); + return this._delegate.toString(); + } + // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary + // for end-users. + toJSON() { + // An optional spacer argument is unnecessary for a string. + require$$2$3.validateArgCount('Query.toJSON', 0, 1, arguments.length); + return this._delegate.toJSON(); + } + /** + * Return true if this query and the provided query are equivalent; otherwise, return false. + */ + isEqual(other) { + require$$2$3.validateArgCount('Query.isEqual', 1, 1, arguments.length); + if (!(other instanceof Query)) { + const error = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.'; + throw new Error(error); + } + return this._delegate.isEqual(other._delegate); + } + /** + * Helper used by .on and .once to extract the context and or cancel arguments. + * @param fnName - The function name (on or once) + * + */ + static getCancelAndContextArgs_(fnName, cancelOrContext, context) { + const ret = { cancel: undefined, context: undefined }; + if (cancelOrContext && context) { + ret.cancel = cancelOrContext; + require$$2$3.validateCallback(fnName, 'cancel', ret.cancel, true); + ret.context = context; + require$$2$3.validateContextObject(fnName, 'context', ret.context, true); + } + else if (cancelOrContext) { + // we have either a cancel callback or a context. + if (typeof cancelOrContext === 'object' && cancelOrContext !== null) { + // it's a context! + ret.context = cancelOrContext; + } + else if (typeof cancelOrContext === 'function') { + ret.cancel = cancelOrContext; + } + else { + throw new Error(require$$2$3.errorPrefix(fnName, 'cancelOrContext') + + ' must either be a cancel callback or a context object.'); + } + } + return ret; + } + get ref() { + return new Reference(this.database, new _ReferenceImpl(this._delegate._repo, this._delegate._path)); + } +} +class Reference extends Query { + /** + * Call options: + * new Reference(Repo, Path) or + * new Reference(url: string, string|RepoManager) + * + * Externally - this is the firebase.database.Reference type. + */ + constructor(database, _delegate) { + super(database, new _QueryImpl(_delegate._repo, _delegate._path, new _QueryParams(), false)); + this.database = database; + this._delegate = _delegate; + } + /** @returns {?string} */ + getKey() { + require$$2$3.validateArgCount('Reference.key', 0, 0, arguments.length); + return this._delegate.key; + } + child(pathString) { + require$$2$3.validateArgCount('Reference.child', 1, 1, arguments.length); + if (typeof pathString === 'number') { + pathString = String(pathString); + } + return new Reference(this.database, child_1(this._delegate, pathString)); + } + /** @returns {?Reference} */ + getParent() { + require$$2$3.validateArgCount('Reference.parent', 0, 0, arguments.length); + const parent = this._delegate.parent; + return parent ? new Reference(this.database, parent) : null; + } + /** @returns {!Reference} */ + getRoot() { + require$$2$3.validateArgCount('Reference.root', 0, 0, arguments.length); + return new Reference(this.database, this._delegate.root); + } + set(newVal, onComplete) { + require$$2$3.validateArgCount('Reference.set', 1, 2, arguments.length); + require$$2$3.validateCallback('Reference.set', 'onComplete', onComplete, true); + const result = set_1(this._delegate, newVal); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + update(values, onComplete) { + require$$2$3.validateArgCount('Reference.update', 1, 2, arguments.length); + if (Array.isArray(values)) { + const newObjectToMerge = {}; + for (let i = 0; i < values.length; ++i) { + newObjectToMerge['' + i] = values[i]; + } + values = newObjectToMerge; + warn('Passing an Array to Firebase.update() is deprecated. ' + + 'Use set() if you want to overwrite the existing data, or ' + + 'an Object with integer keys if you really do want to ' + + 'only update some of the children.'); + } + _validateWritablePath('Reference.update', this._delegate._path); + require$$2$3.validateCallback('Reference.update', 'onComplete', onComplete, true); + const result = update_1(this._delegate, values); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + setWithPriority(newVal, newPriority, onComplete) { + require$$2$3.validateArgCount('Reference.setWithPriority', 2, 3, arguments.length); + require$$2$3.validateCallback('Reference.setWithPriority', 'onComplete', onComplete, true); + const result = setWithPriority_1(this._delegate, newVal, newPriority); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + remove(onComplete) { + require$$2$3.validateArgCount('Reference.remove', 0, 1, arguments.length); + require$$2$3.validateCallback('Reference.remove', 'onComplete', onComplete, true); + const result = remove_1(this._delegate); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + transaction(transactionUpdate, onComplete, applyLocally) { + require$$2$3.validateArgCount('Reference.transaction', 1, 3, arguments.length); + require$$2$3.validateCallback('Reference.transaction', 'transactionUpdate', transactionUpdate, false); + require$$2$3.validateCallback('Reference.transaction', 'onComplete', onComplete, true); + validateBoolean('Reference.transaction', 'applyLocally', applyLocally, true); + const result = runTransaction_1(this._delegate, transactionUpdate, { + applyLocally + }).then(transactionResult => new TransactionResult(transactionResult.committed, new DataSnapshot(this.database, transactionResult.snapshot))); + if (onComplete) { + result.then(transactionResult => onComplete(null, transactionResult.committed, transactionResult.snapshot), error => onComplete(error, false, null)); + } + return result; + } + setPriority(priority, onComplete) { + require$$2$3.validateArgCount('Reference.setPriority', 1, 2, arguments.length); + require$$2$3.validateCallback('Reference.setPriority', 'onComplete', onComplete, true); + const result = setPriority_1(this._delegate, priority); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + push(value, onComplete) { + require$$2$3.validateArgCount('Reference.push', 0, 2, arguments.length); + require$$2$3.validateCallback('Reference.push', 'onComplete', onComplete, true); + const expPromise = push_1(this._delegate, value); + const promise = expPromise.then(expRef => new Reference(this.database, expRef)); + if (onComplete) { + promise.then(() => onComplete(null), error => onComplete(error)); + } + const result = new Reference(this.database, expPromise); + result.then = promise.then.bind(promise); + result.catch = promise.catch.bind(promise, undefined); + return result; + } + onDisconnect() { + _validateWritablePath('Reference.onDisconnect', this._delegate._path); + return new OnDisconnect(new OnDisconnect_1(this._delegate._repo, this._delegate._path)); + } + get key() { + return this.getKey(); + } + get parent() { + return this.getParent(); + } + get root() { + return this.getRoot(); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Class representing a firebase database. + */ +class Database { + /** + * The constructor should not be called by users of our public API. + */ + constructor(_delegate, app) { + this._delegate = _delegate; + this.app = app; + this.INTERNAL = { + delete: () => this._delegate._delete(), + forceWebSockets: forceWebSockets_1, + forceLongPolling: forceLongPolling_1 + }; + } + /** + * Modify this instance to communicate with the Realtime Database emulator. + * + *

Note: This method must be called before performing any other operation. + * + * @param host - the emulator host (ex: localhost) + * @param port - the emulator port (ex: 8080) + * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules + */ + useEmulator(host, port, options = {}) { + connectDatabaseEmulator_1(this._delegate, host, port, options); + } + ref(path) { + require$$2$3.validateArgCount('database.ref', 0, 1, arguments.length); + if (path instanceof Reference) { + const childRef = refFromURL_1(this._delegate, path.toString()); + return new Reference(this, childRef); + } + else { + const childRef = ref_1(this._delegate, path); + return new Reference(this, childRef); + } + } + /** + * Returns a reference to the root or the path specified in url. + * We throw a exception if the url is not in the same domain as the + * current repo. + * @returns Firebase reference. + */ + refFromURL(url) { + const apiName = 'database.refFromURL'; + require$$2$3.validateArgCount(apiName, 1, 1, arguments.length); + const childRef = refFromURL_1(this._delegate, url); + return new Reference(this, childRef); + } + // Make individual repo go offline. + goOffline() { + require$$2$3.validateArgCount('database.goOffline', 0, 0, arguments.length); + return goOffline_1(this._delegate); + } + goOnline() { + require$$2$3.validateArgCount('database.goOnline', 0, 0, arguments.length); + return goOnline_1(this._delegate); + } +} +Database.ServerValue = { + TIMESTAMP: serverTimestamp_1(), + increment: (delta) => increment_1(delta) +}; + +/** + * Used by console to create a database based on the app, + * passed database URL and a custom auth implementation. + * + * @param app - A valid FirebaseApp-like object + * @param url - A valid Firebase databaseURL + * @param version - custom version e.g. firebase-admin version + * @param customAuthImpl - custom auth implementation + */ +function initStandalone$1({ app, url, version, customAuthImpl, customAppCheckImpl, namespace, nodeAdmin = false }) { + _setSDKVersion(version); + const container = new require$$0$2.ComponentContainer('database-standalone'); + /** + * ComponentContainer('database-standalone') is just a placeholder that doesn't perform + * any actual function. + */ + const authProvider = new require$$0$2.Provider('auth-internal', container); + authProvider.setComponent(new require$$0$2.Component('auth-internal', () => customAuthImpl, "PRIVATE" /* ComponentType.PRIVATE */)); + let appCheckProvider = undefined; + if (customAppCheckImpl) { + appCheckProvider = new require$$0$2.Provider('app-check-internal', container); + appCheckProvider.setComponent(new require$$0$2.Component('app-check-internal', () => customAppCheckImpl, "PRIVATE" /* ComponentType.PRIVATE */)); + } + return { + instance: new Database(_repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin), app), + namespace + }; +} + +var INTERNAL = /*#__PURE__*/Object.freeze({ + __proto__: null, + initStandalone: initStandalone$1 +}); + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const ServerValue = Database.ServerValue; +/** + * A one off register function which returns a database based on the app and + * passed database URL. (Used by the Admin SDK) + * + * @param app - A valid FirebaseApp-like object + * @param url - A valid Firebase databaseURL + * @param version - custom version e.g. firebase-admin version + * @param nodeAdmin - true if the SDK is being initialized from Firebase Admin. + */ +function initStandalone(app, url, version, nodeAdmin = true) { + require$$2$3.CONSTANTS.NODE_ADMIN = nodeAdmin; + return initStandalone$1({ + app, + url, + version, + // firebase-admin-node's app.INTERNAL implements FirebaseAuthInternal interface + // eslint-disable-next-line @typescript-eslint/no-explicit-any + customAuthImpl: app.INTERNAL, + namespace: { + Reference, + Query, + Database, + DataSnapshot, + enableLogging: enableLogging_1, + INTERNAL, + ServerValue + }, + nodeAdmin + }); +} + +exports.DataSnapshot = DataSnapshot; +exports.Database = Database; +exports.OnDisconnect = OnDisconnect_1; +exports.Query = Query; +exports.Reference = Reference; +exports.ServerValue = ServerValue; +exports.enableLogging = enableLogging_1; +exports.initStandalone = initStandalone; +//# sourceMappingURL=index.standalone.js.map diff --git a/node_modules/@firebase/database-compat/dist/index.standalone.js.map b/node_modules/@firebase/database-compat/dist/index.standalone.js.map new file mode 100644 index 0000000..7bd6795 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/index.standalone.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.standalone.js","sources":["../../../node_modules/safe-buffer/index.js","../../../node_modules/websocket-driver/lib/websocket/streams.js","../../../node_modules/websocket-driver/lib/websocket/driver/headers.js","../../../node_modules/websocket-driver/lib/websocket/driver/stream_reader.js","../../../node_modules/websocket-driver/lib/websocket/driver/base.js","../../../node_modules/http-parser-js/http-parser.js","../../../node_modules/websocket-driver/lib/websocket/http_parser.js","../../../node_modules/websocket-extensions/lib/parser.js","../../../node_modules/websocket-extensions/lib/pipeline/ring_buffer.js","../../../node_modules/websocket-extensions/lib/pipeline/functor.js","../../../node_modules/websocket-extensions/lib/pipeline/pledge.js","../../../node_modules/websocket-extensions/lib/pipeline/cell.js","../../../node_modules/websocket-extensions/lib/pipeline/index.js","../../../node_modules/websocket-extensions/lib/websocket_extensions.js","../../../node_modules/websocket-driver/lib/websocket/driver/hybi/frame.js","../../../node_modules/websocket-driver/lib/websocket/driver/hybi/message.js","../../../node_modules/websocket-driver/lib/websocket/driver/hybi.js","../../../node_modules/websocket-driver/lib/websocket/driver/proxy.js","../../../node_modules/websocket-driver/lib/websocket/driver/client.js","../../../node_modules/websocket-driver/lib/websocket/driver/draft75.js","../../../node_modules/websocket-driver/lib/websocket/driver/draft76.js","../../../node_modules/websocket-driver/lib/websocket/driver/server.js","../../../node_modules/websocket-driver/lib/websocket/driver.js","../../../node_modules/faye-websocket/lib/faye/websocket/api/event.js","../../../node_modules/faye-websocket/lib/faye/websocket/api/event_target.js","../../../node_modules/faye-websocket/lib/faye/websocket/api.js","../../../node_modules/faye-websocket/lib/faye/websocket/client.js","../../../node_modules/faye-websocket/lib/faye/eventsource.js","../../../node_modules/faye-websocket/lib/faye/websocket.js","../../../node_modules/idb/build/wrap-idb-value.js","../../../node_modules/idb/build/index.js","../../app/dist/index.cjs.js","../../database/dist/index.standalone.js","../src/util/util.ts","../src/util/validation.ts","../src/api/onDisconnect.ts","../src/api/TransactionResult.ts","../src/api/Reference.ts","../src/api/Database.ts","../src/api/internal.ts","../src/index.standalone.ts"],"sourcesContent":["/*! safe-buffer. MIT License. Feross Aboukhadijeh */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","'use strict';\n\n/**\n\nStreams in a WebSocket connection\n---------------------------------\n\nWe model a WebSocket as two duplex streams: one stream is for the wire protocol\nover an I/O socket, and the other is for incoming/outgoing messages.\n\n\n +----------+ +---------+ +----------+\n [1] write(chunk) -->| ~~~~~~~~ +----->| parse() +----->| ~~~~~~~~ +--> emit('data') [2]\n | | +----+----+ | |\n | | | | |\n | IO | | [5] | Messages |\n | | V | |\n | | +---------+ | |\n [4] emit('data') <--+ ~~~~~~~~ |<-----+ frame() |<-----+ ~~~~~~~~ |<-- write(chunk) [3]\n +----------+ +---------+ +----------+\n\n\nMessage transfer in each direction is simple: IO receives a byte stream [1] and\nsends this stream for parsing. The parser will periodically emit a complete\nmessage text on the Messages stream [2]. Similarly, when messages are written\nto the Messages stream [3], they are framed using the WebSocket wire format and\nemitted via IO [4].\n\nThere is a feedback loop via [5] since some input from [1] will be things like\nping, pong and close frames. In these cases the protocol responds by emitting\nresponses directly back to [4] rather than emitting messages via [2].\n\nFor the purposes of flow control, we consider the sources of each Readable\nstream to be as follows:\n\n* [2] receives input from [1]\n* [4] receives input from [1] and [3]\n\nThe classes below express the relationships described above without prescribing\nanything about how parse() and frame() work, other than assuming they emit\n'data' events to the IO and Messages streams. They will work with any protocol\ndriver having these two methods.\n**/\n\n\nvar Stream = require('stream').Stream,\n util = require('util');\n\n\nvar IO = function(driver) {\n this.readable = this.writable = true;\n this._paused = false;\n this._driver = driver;\n};\nutil.inherits(IO, Stream);\n\n// The IO pause() and resume() methods will be called when the socket we are\n// piping to gets backed up and drains. Since IO output [4] comes from IO input\n// [1] and Messages input [3], we need to tell both of those to return false\n// from write() when this stream is paused.\n\nIO.prototype.pause = function() {\n this._paused = true;\n this._driver.messages._paused = true;\n};\n\nIO.prototype.resume = function() {\n this._paused = false;\n this.emit('drain');\n\n var messages = this._driver.messages;\n messages._paused = false;\n messages.emit('drain');\n};\n\n// When we receive input from a socket, send it to the parser and tell the\n// source whether to back off.\nIO.prototype.write = function(chunk) {\n if (!this.writable) return false;\n this._driver.parse(chunk);\n return !this._paused;\n};\n\n// The IO end() method will be called when the socket piping into it emits\n// 'close' or 'end', i.e. the socket is closed. In this situation the Messages\n// stream will not emit any more data so we emit 'end'.\nIO.prototype.end = function(chunk) {\n if (!this.writable) return;\n if (chunk !== undefined) this.write(chunk);\n this.writable = false;\n\n var messages = this._driver.messages;\n if (messages.readable) {\n messages.readable = messages.writable = false;\n messages.emit('end');\n }\n};\n\nIO.prototype.destroy = function() {\n this.end();\n};\n\n\nvar Messages = function(driver) {\n this.readable = this.writable = true;\n this._paused = false;\n this._driver = driver;\n};\nutil.inherits(Messages, Stream);\n\n// The Messages pause() and resume() methods will be called when the app that's\n// processing the messages gets backed up and drains. If we're emitting\n// messages too fast we should tell the source to slow down. Message output [2]\n// comes from IO input [1].\n\nMessages.prototype.pause = function() {\n this._driver.io._paused = true;\n};\n\nMessages.prototype.resume = function() {\n this._driver.io._paused = false;\n this._driver.io.emit('drain');\n};\n\n// When we receive messages from the user, send them to the formatter and tell\n// the source whether to back off.\nMessages.prototype.write = function(message) {\n if (!this.writable) return false;\n if (typeof message === 'string') this._driver.text(message);\n else this._driver.binary(message);\n return !this._paused;\n};\n\n// The Messages end() method will be called when a stream piping into it emits\n// 'end'. Many streams may be piped into the WebSocket and one of them ending\n// does not mean the whole socket is done, so just process the input and move\n// on leaving the socket open.\nMessages.prototype.end = function(message) {\n if (message !== undefined) this.write(message);\n};\n\nMessages.prototype.destroy = function() {};\n\n\nexports.IO = IO;\nexports.Messages = Messages;\n","'use strict';\n\nvar Headers = function() {\n this.clear();\n};\n\nHeaders.prototype.ALLOWED_DUPLICATES = ['set-cookie', 'set-cookie2', 'warning', 'www-authenticate'];\n\nHeaders.prototype.clear = function() {\n this._sent = {};\n this._lines = [];\n};\n\nHeaders.prototype.set = function(name, value) {\n if (value === undefined) return;\n\n name = this._strip(name);\n value = this._strip(value);\n\n var key = name.toLowerCase();\n if (!this._sent.hasOwnProperty(key) || this.ALLOWED_DUPLICATES.indexOf(key) >= 0) {\n this._sent[key] = true;\n this._lines.push(name + ': ' + value + '\\r\\n');\n }\n};\n\nHeaders.prototype.toString = function() {\n return this._lines.join('');\n};\n\nHeaders.prototype._strip = function(string) {\n return string.toString().replace(/^ */, '').replace(/ *$/, '');\n};\n\nmodule.exports = Headers;\n","'use strict';\n\nvar Buffer = require('safe-buffer').Buffer;\n\nvar StreamReader = function() {\n this._queue = [];\n this._queueSize = 0;\n this._offset = 0;\n};\n\nStreamReader.prototype.put = function(buffer) {\n if (!buffer || buffer.length === 0) return;\n if (!Buffer.isBuffer(buffer)) buffer = Buffer.from(buffer);\n this._queue.push(buffer);\n this._queueSize += buffer.length;\n};\n\nStreamReader.prototype.read = function(length) {\n if (length > this._queueSize) return null;\n if (length === 0) return Buffer.alloc(0);\n\n this._queueSize -= length;\n\n var queue = this._queue,\n remain = length,\n first = queue[0],\n buffers, buffer;\n\n if (first.length >= length) {\n if (first.length === length) {\n return queue.shift();\n } else {\n buffer = first.slice(0, length);\n queue[0] = first.slice(length);\n return buffer;\n }\n }\n\n for (var i = 0, n = queue.length; i < n; i++) {\n if (remain < queue[i].length) break;\n remain -= queue[i].length;\n }\n buffers = queue.splice(0, i);\n\n if (remain > 0 && queue.length > 0) {\n buffers.push(queue[0].slice(0, remain));\n queue[0] = queue[0].slice(remain);\n }\n return Buffer.concat(buffers, length);\n};\n\nStreamReader.prototype.eachByte = function(callback, context) {\n var buffer, n, index;\n\n while (this._queue.length > 0) {\n buffer = this._queue[0];\n n = buffer.length;\n\n while (this._offset < n) {\n index = this._offset;\n this._offset += 1;\n callback.call(context, buffer[index]);\n }\n this._offset = 0;\n this._queue.shift();\n }\n};\n\nmodule.exports = StreamReader;\n","'use strict';\n\nvar Buffer = require('safe-buffer').Buffer,\n Emitter = require('events').EventEmitter,\n util = require('util'),\n streams = require('../streams'),\n Headers = require('./headers'),\n Reader = require('./stream_reader');\n\nvar Base = function(request, url, options) {\n Emitter.call(this);\n Base.validateOptions(options || {}, ['maxLength', 'masking', 'requireMasking', 'protocols']);\n\n this._request = request;\n this._reader = new Reader();\n this._options = options || {};\n this._maxLength = this._options.maxLength || this.MAX_LENGTH;\n this._headers = new Headers();\n this.__queue = [];\n this.readyState = 0;\n this.url = url;\n\n this.io = new streams.IO(this);\n this.messages = new streams.Messages(this);\n this._bindEventListeners();\n};\nutil.inherits(Base, Emitter);\n\nBase.isWebSocket = function(request) {\n var connection = request.headers.connection || '',\n upgrade = request.headers.upgrade || '';\n\n return request.method === 'GET' &&\n connection.toLowerCase().split(/ *, */).indexOf('upgrade') >= 0 &&\n upgrade.toLowerCase() === 'websocket';\n};\n\nBase.validateOptions = function(options, validKeys) {\n for (var key in options) {\n if (validKeys.indexOf(key) < 0)\n throw new Error('Unrecognized option: ' + key);\n }\n};\n\nvar instance = {\n // This is 64MB, small enough for an average VPS to handle without\n // crashing from process out of memory\n MAX_LENGTH: 0x3ffffff,\n\n STATES: ['connecting', 'open', 'closing', 'closed'],\n\n _bindEventListeners: function() {\n var self = this;\n\n // Protocol errors are informational and do not have to be handled\n this.messages.on('error', function() {});\n\n this.on('message', function(event) {\n var messages = self.messages;\n if (messages.readable) messages.emit('data', event.data);\n });\n\n this.on('error', function(error) {\n var messages = self.messages;\n if (messages.readable) messages.emit('error', error);\n });\n\n this.on('close', function() {\n var messages = self.messages;\n if (!messages.readable) return;\n messages.readable = messages.writable = false;\n messages.emit('end');\n });\n },\n\n getState: function() {\n return this.STATES[this.readyState] || null;\n },\n\n addExtension: function(extension) {\n return false;\n },\n\n setHeader: function(name, value) {\n if (this.readyState > 0) return false;\n this._headers.set(name, value);\n return true;\n },\n\n start: function() {\n if (this.readyState !== 0) return false;\n\n if (!Base.isWebSocket(this._request))\n return this._failHandshake(new Error('Not a WebSocket request'));\n\n var response;\n\n try {\n response = this._handshakeResponse();\n } catch (error) {\n return this._failHandshake(error);\n }\n\n this._write(response);\n if (this._stage !== -1) this._open();\n return true;\n },\n\n _failHandshake: function(error) {\n var headers = new Headers();\n headers.set('Content-Type', 'text/plain');\n headers.set('Content-Length', Buffer.byteLength(error.message, 'utf8'));\n\n headers = ['HTTP/1.1 400 Bad Request', headers.toString(), error.message];\n this._write(Buffer.from(headers.join('\\r\\n'), 'utf8'));\n this._fail('protocol_error', error.message);\n\n return false;\n },\n\n text: function(message) {\n return this.frame(message);\n },\n\n binary: function(message) {\n return false;\n },\n\n ping: function() {\n return false;\n },\n\n pong: function() {\n return false;\n },\n\n close: function(reason, code) {\n if (this.readyState !== 1) return false;\n this.readyState = 3;\n this.emit('close', new Base.CloseEvent(null, null));\n return true;\n },\n\n _open: function() {\n this.readyState = 1;\n this.__queue.forEach(function(args) { this.frame.apply(this, args) }, this);\n this.__queue = [];\n this.emit('open', new Base.OpenEvent());\n },\n\n _queue: function(message) {\n this.__queue.push(message);\n return true;\n },\n\n _write: function(chunk) {\n var io = this.io;\n if (io.readable) io.emit('data', chunk);\n },\n\n _fail: function(type, message) {\n this.readyState = 2;\n this.emit('error', new Error(message));\n this.close();\n }\n};\n\nfor (var key in instance)\n Base.prototype[key] = instance[key];\n\n\nBase.ConnectEvent = function() {};\n\nBase.OpenEvent = function() {};\n\nBase.CloseEvent = function(code, reason) {\n this.code = code;\n this.reason = reason;\n};\n\nBase.MessageEvent = function(data) {\n this.data = data;\n};\n\nBase.PingEvent = function(data) {\n this.data = data;\n};\n\nBase.PongEvent = function(data) {\n this.data = data;\n};\n\nmodule.exports = Base;\n","/*jshint node:true */\n\nexports.HTTPParser = HTTPParser;\nfunction HTTPParser(type) {\n if (type !== undefined && type !== HTTPParser.REQUEST && type !== HTTPParser.RESPONSE) {\n throw new Error('type must be REQUEST or RESPONSE');\n }\n if (type === undefined) {\n // Node v12+\n } else {\n this.initialize(type);\n }\n this.maxHeaderSize=HTTPParser.maxHeaderSize\n}\nHTTPParser.prototype.initialize = function (type, async_resource) {\n if (type !== HTTPParser.REQUEST && type !== HTTPParser.RESPONSE) {\n throw new Error('type must be REQUEST or RESPONSE');\n }\n this.type = type;\n this.state = type + '_LINE';\n this.info = {\n headers: [],\n upgrade: false\n };\n this.trailers = [];\n this.line = '';\n this.isChunked = false;\n this.connection = '';\n this.headerSize = 0; // for preventing too big headers\n this.body_bytes = null;\n this.isUserCall = false;\n this.hadError = false;\n};\n\nHTTPParser.encoding = 'ascii';\nHTTPParser.maxHeaderSize = 80 * 1024; // maxHeaderSize (in bytes) is configurable, but 80kb by default;\nHTTPParser.REQUEST = 'REQUEST';\nHTTPParser.RESPONSE = 'RESPONSE';\n\n// Note: *not* starting with kOnHeaders=0 line the Node parser, because any\n// newly added constants (kOnTimeout in Node v12.19.0) will overwrite 0!\nvar kOnHeaders = HTTPParser.kOnHeaders = 1;\nvar kOnHeadersComplete = HTTPParser.kOnHeadersComplete = 2;\nvar kOnBody = HTTPParser.kOnBody = 3;\nvar kOnMessageComplete = HTTPParser.kOnMessageComplete = 4;\n\n// Some handler stubs, needed for compatibility\nHTTPParser.prototype[kOnHeaders] =\nHTTPParser.prototype[kOnHeadersComplete] =\nHTTPParser.prototype[kOnBody] =\nHTTPParser.prototype[kOnMessageComplete] = function () {};\n\nvar compatMode0_12 = true;\nObject.defineProperty(HTTPParser, 'kOnExecute', {\n get: function () {\n // hack for backward compatibility\n compatMode0_12 = false;\n return 99;\n }\n });\n\nvar methods = exports.methods = HTTPParser.methods = [\n 'DELETE',\n 'GET',\n 'HEAD',\n 'POST',\n 'PUT',\n 'CONNECT',\n 'OPTIONS',\n 'TRACE',\n 'COPY',\n 'LOCK',\n 'MKCOL',\n 'MOVE',\n 'PROPFIND',\n 'PROPPATCH',\n 'SEARCH',\n 'UNLOCK',\n 'BIND',\n 'REBIND',\n 'UNBIND',\n 'ACL',\n 'REPORT',\n 'MKACTIVITY',\n 'CHECKOUT',\n 'MERGE',\n 'M-SEARCH',\n 'NOTIFY',\n 'SUBSCRIBE',\n 'UNSUBSCRIBE',\n 'PATCH',\n 'PURGE',\n 'MKCALENDAR',\n 'LINK',\n 'UNLINK',\n 'SOURCE',\n];\nvar method_connect = methods.indexOf('CONNECT');\nHTTPParser.prototype.reinitialize = HTTPParser;\nHTTPParser.prototype.close =\nHTTPParser.prototype.pause =\nHTTPParser.prototype.resume =\nHTTPParser.prototype.remove =\nHTTPParser.prototype.free = function () {};\nHTTPParser.prototype._compatMode0_11 = false;\nHTTPParser.prototype.getAsyncId = function() { return 0; };\n\nvar headerState = {\n REQUEST_LINE: true,\n RESPONSE_LINE: true,\n HEADER: true\n};\nHTTPParser.prototype.execute = function (chunk, start, length) {\n if (!(this instanceof HTTPParser)) {\n throw new TypeError('not a HTTPParser');\n }\n\n // backward compat to node < 0.11.4\n // Note: the start and length params were removed in newer version\n start = start || 0;\n length = typeof length === 'number' ? length : chunk.length;\n\n this.chunk = chunk;\n this.offset = start;\n var end = this.end = start + length;\n try {\n while (this.offset < end) {\n if (this[this.state]()) {\n break;\n }\n }\n } catch (err) {\n if (this.isUserCall) {\n throw err;\n }\n this.hadError = true;\n return err;\n }\n this.chunk = null;\n length = this.offset - start;\n if (headerState[this.state]) {\n this.headerSize += length;\n if (this.headerSize > (this.maxHeaderSize||HTTPParser.maxHeaderSize)) {\n return new Error('max header size exceeded');\n }\n }\n return length;\n};\n\nvar stateFinishAllowed = {\n REQUEST_LINE: true,\n RESPONSE_LINE: true,\n BODY_RAW: true\n};\nHTTPParser.prototype.finish = function () {\n if (this.hadError) {\n return;\n }\n if (!stateFinishAllowed[this.state]) {\n return new Error('invalid state for EOF');\n }\n if (this.state === 'BODY_RAW') {\n this.userCall()(this[kOnMessageComplete]());\n }\n};\n\n// These three methods are used for an internal speed optimization, and it also\n// works if theses are noops. Basically consume() asks us to read the bytes\n// ourselves, but if we don't do it we get them through execute().\nHTTPParser.prototype.consume =\nHTTPParser.prototype.unconsume =\nHTTPParser.prototype.getCurrentBuffer = function () {};\n\n//For correct error handling - see HTTPParser#execute\n//Usage: this.userCall()(userFunction('arg'));\nHTTPParser.prototype.userCall = function () {\n this.isUserCall = true;\n var self = this;\n return function (ret) {\n self.isUserCall = false;\n return ret;\n };\n};\n\nHTTPParser.prototype.nextRequest = function () {\n this.userCall()(this[kOnMessageComplete]());\n this.reinitialize(this.type);\n};\n\nHTTPParser.prototype.consumeLine = function () {\n var end = this.end,\n chunk = this.chunk;\n for (var i = this.offset; i < end; i++) {\n if (chunk[i] === 0x0a) { // \\n\n var line = this.line + chunk.toString(HTTPParser.encoding, this.offset, i);\n if (line.charAt(line.length - 1) === '\\r') {\n line = line.substr(0, line.length - 1);\n }\n this.line = '';\n this.offset = i + 1;\n return line;\n }\n }\n //line split over multiple chunks\n this.line += chunk.toString(HTTPParser.encoding, this.offset, this.end);\n this.offset = this.end;\n};\n\nvar headerExp = /^([^: \\t]+):[ \\t]*((?:.*[^ \\t])|)/;\nvar headerContinueExp = /^[ \\t]+(.*[^ \\t])/;\nHTTPParser.prototype.parseHeader = function (line, headers) {\n if (line.indexOf('\\r') !== -1) {\n throw parseErrorCode('HPE_LF_EXPECTED');\n }\n\n var match = headerExp.exec(line);\n var k = match && match[1];\n if (k) { // skip empty string (malformed header)\n headers.push(k);\n headers.push(match[2]);\n } else {\n var matchContinue = headerContinueExp.exec(line);\n if (matchContinue && headers.length) {\n if (headers[headers.length - 1]) {\n headers[headers.length - 1] += ' ';\n }\n headers[headers.length - 1] += matchContinue[1];\n }\n }\n};\n\nvar requestExp = /^([A-Z-]+) ([^ ]+) HTTP\\/(\\d)\\.(\\d)$/;\nHTTPParser.prototype.REQUEST_LINE = function () {\n var line = this.consumeLine();\n if (!line) {\n return;\n }\n var match = requestExp.exec(line);\n if (match === null) {\n throw parseErrorCode('HPE_INVALID_CONSTANT');\n }\n this.info.method = this._compatMode0_11 ? match[1] : methods.indexOf(match[1]);\n if (this.info.method === -1) {\n throw new Error('invalid request method');\n }\n this.info.url = match[2];\n this.info.versionMajor = +match[3];\n this.info.versionMinor = +match[4];\n this.body_bytes = 0;\n this.state = 'HEADER';\n};\n\nvar responseExp = /^HTTP\\/(\\d)\\.(\\d) (\\d{3}) ?(.*)$/;\nHTTPParser.prototype.RESPONSE_LINE = function () {\n var line = this.consumeLine();\n if (!line) {\n return;\n }\n var match = responseExp.exec(line);\n if (match === null) {\n throw parseErrorCode('HPE_INVALID_CONSTANT');\n }\n this.info.versionMajor = +match[1];\n this.info.versionMinor = +match[2];\n var statusCode = this.info.statusCode = +match[3];\n this.info.statusMessage = match[4];\n // Implied zero length.\n if ((statusCode / 100 | 0) === 1 || statusCode === 204 || statusCode === 304) {\n this.body_bytes = 0;\n }\n this.state = 'HEADER';\n};\n\nHTTPParser.prototype.shouldKeepAlive = function () {\n if (this.info.versionMajor > 0 && this.info.versionMinor > 0) {\n if (this.connection.indexOf('close') !== -1) {\n return false;\n }\n } else if (this.connection.indexOf('keep-alive') === -1) {\n return false;\n }\n if (this.body_bytes !== null || this.isChunked) { // || skipBody\n return true;\n }\n return false;\n};\n\nHTTPParser.prototype.HEADER = function () {\n var line = this.consumeLine();\n if (line === undefined) {\n return;\n }\n var info = this.info;\n if (line) {\n this.parseHeader(line, info.headers);\n } else {\n var headers = info.headers;\n var hasContentLength = false;\n var currentContentLengthValue;\n var hasUpgradeHeader = false;\n for (var i = 0; i < headers.length; i += 2) {\n switch (headers[i].toLowerCase()) {\n case 'transfer-encoding':\n this.isChunked = headers[i + 1].toLowerCase() === 'chunked';\n break;\n case 'content-length':\n currentContentLengthValue = +headers[i + 1];\n if (hasContentLength) {\n // Fix duplicate Content-Length header with same values.\n // Throw error only if values are different.\n // Known issues:\n // https://github.com/request/request/issues/2091#issuecomment-328715113\n // https://github.com/nodejs/node/issues/6517#issuecomment-216263771\n if (currentContentLengthValue !== this.body_bytes) {\n throw parseErrorCode('HPE_UNEXPECTED_CONTENT_LENGTH');\n }\n } else {\n hasContentLength = true;\n this.body_bytes = currentContentLengthValue;\n }\n break;\n case 'connection':\n this.connection += headers[i + 1].toLowerCase();\n break;\n case 'upgrade':\n hasUpgradeHeader = true;\n break;\n }\n }\n\n // if both isChunked and hasContentLength, isChunked wins\n // This is required so the body is parsed using the chunked method, and matches\n // Chrome's behavior. We could, maybe, ignore them both (would get chunked\n // encoding into the body), and/or disable shouldKeepAlive to be more\n // resilient.\n if (this.isChunked && hasContentLength) {\n hasContentLength = false;\n this.body_bytes = null;\n }\n\n // Logic from https://github.com/nodejs/http-parser/blob/921d5585515a153fa00e411cf144280c59b41f90/http_parser.c#L1727-L1737\n // \"For responses, \"Upgrade: foo\" and \"Connection: upgrade\" are\n // mandatory only when it is a 101 Switching Protocols response,\n // otherwise it is purely informational, to announce support.\n if (hasUpgradeHeader && this.connection.indexOf('upgrade') != -1) {\n info.upgrade = this.type === HTTPParser.REQUEST || info.statusCode === 101;\n } else {\n info.upgrade = info.method === method_connect;\n }\n\n if (this.isChunked && info.upgrade) {\n this.isChunked = false;\n }\n\n info.shouldKeepAlive = this.shouldKeepAlive();\n //problem which also exists in original node: we should know skipBody before calling onHeadersComplete\n var skipBody;\n if (compatMode0_12) {\n skipBody = this.userCall()(this[kOnHeadersComplete](info));\n } else {\n skipBody = this.userCall()(this[kOnHeadersComplete](info.versionMajor,\n info.versionMinor, info.headers, info.method, info.url, info.statusCode,\n info.statusMessage, info.upgrade, info.shouldKeepAlive));\n }\n if (skipBody === 2) {\n this.nextRequest();\n return true;\n } else if (this.isChunked && !skipBody) {\n this.state = 'BODY_CHUNKHEAD';\n } else if (skipBody || this.body_bytes === 0) {\n this.nextRequest();\n // For older versions of node (v6.x and older?), that return skipBody=1 or skipBody=true,\n // need this \"return true;\" if it's an upgrade request.\n return info.upgrade;\n } else if (this.body_bytes === null) {\n this.state = 'BODY_RAW';\n } else {\n this.state = 'BODY_SIZED';\n }\n }\n};\n\nHTTPParser.prototype.BODY_CHUNKHEAD = function () {\n var line = this.consumeLine();\n if (line === undefined) {\n return;\n }\n this.body_bytes = parseInt(line, 16);\n if (!this.body_bytes) {\n this.state = 'BODY_CHUNKTRAILERS';\n } else {\n this.state = 'BODY_CHUNK';\n }\n};\n\nHTTPParser.prototype.BODY_CHUNK = function () {\n var length = Math.min(this.end - this.offset, this.body_bytes);\n // 0, length are for backwards compatibility. See: https://github.com/creationix/http-parser-js/pull/98\n this.userCall()(this[kOnBody](this.chunk.slice(this.offset, this.offset + length), 0, length));\n this.offset += length;\n this.body_bytes -= length;\n if (!this.body_bytes) {\n this.state = 'BODY_CHUNKEMPTYLINE';\n }\n};\n\nHTTPParser.prototype.BODY_CHUNKEMPTYLINE = function () {\n var line = this.consumeLine();\n if (line === undefined) {\n return;\n }\n if (line !== '') {\n throw new Error('Expected empty line');\n }\n this.state = 'BODY_CHUNKHEAD';\n};\n\nHTTPParser.prototype.BODY_CHUNKTRAILERS = function () {\n var line = this.consumeLine();\n if (line === undefined) {\n return;\n }\n if (line) {\n this.parseHeader(line, this.trailers);\n } else {\n if (this.trailers.length) {\n this.userCall()(this[kOnHeaders](this.trailers, ''));\n }\n this.nextRequest();\n }\n};\n\nHTTPParser.prototype.BODY_RAW = function () {\n // 0, length are for backwards compatibility. See: https://github.com/creationix/http-parser-js/pull/98\n this.userCall()(this[kOnBody](this.chunk.slice(this.offset, this.end), 0, this.end - this.offset));\n this.offset = this.end;\n};\n\nHTTPParser.prototype.BODY_SIZED = function () {\n var length = Math.min(this.end - this.offset, this.body_bytes);\n // 0, length are for backwards compatibility. See: https://github.com/creationix/http-parser-js/pull/98\n this.userCall()(this[kOnBody](this.chunk.slice(this.offset, this.offset + length), 0, length));\n this.offset += length;\n this.body_bytes -= length;\n if (!this.body_bytes) {\n this.nextRequest();\n }\n};\n\n// backward compat to node < 0.11.6\n['Headers', 'HeadersComplete', 'Body', 'MessageComplete'].forEach(function (name) {\n var k = HTTPParser['kOn' + name];\n Object.defineProperty(HTTPParser.prototype, 'on' + name, {\n get: function () {\n return this[k];\n },\n set: function (to) {\n // hack for backward compatibility\n this._compatMode0_11 = true;\n method_connect = 'CONNECT';\n return (this[k] = to);\n }\n });\n});\n\nfunction parseErrorCode(code) {\n var err = new Error('Parse Error');\n err.code = code;\n return err;\n}\n","'use strict';\n\nvar NodeHTTPParser = require('http-parser-js').HTTPParser,\n Buffer = require('safe-buffer').Buffer;\n\nvar TYPES = {\n request: NodeHTTPParser.REQUEST || 'request',\n response: NodeHTTPParser.RESPONSE || 'response'\n};\n\nvar HttpParser = function(type) {\n this._type = type;\n this._parser = new NodeHTTPParser(TYPES[type]);\n this._complete = false;\n this.headers = {};\n\n var current = null,\n self = this;\n\n this._parser.onHeaderField = function(b, start, length) {\n current = b.toString('utf8', start, start + length).toLowerCase();\n };\n\n this._parser.onHeaderValue = function(b, start, length) {\n var value = b.toString('utf8', start, start + length);\n\n if (self.headers.hasOwnProperty(current))\n self.headers[current] += ', ' + value;\n else\n self.headers[current] = value;\n };\n\n this._parser.onHeadersComplete = this._parser[NodeHTTPParser.kOnHeadersComplete] =\n function(majorVersion, minorVersion, headers, method, pathname, statusCode) {\n var info = arguments[0];\n\n if (typeof info === 'object') {\n method = info.method;\n pathname = info.url;\n statusCode = info.statusCode;\n headers = info.headers;\n }\n\n self.method = (typeof method === 'number') ? HttpParser.METHODS[method] : method;\n self.statusCode = statusCode;\n self.url = pathname;\n\n if (!headers) return;\n\n for (var i = 0, n = headers.length, key, value; i < n; i += 2) {\n key = headers[i].toLowerCase();\n value = headers[i+1];\n if (self.headers.hasOwnProperty(key))\n self.headers[key] += ', ' + value;\n else\n self.headers[key] = value;\n }\n\n self._complete = true;\n };\n};\n\nHttpParser.METHODS = {\n 0: 'DELETE',\n 1: 'GET',\n 2: 'HEAD',\n 3: 'POST',\n 4: 'PUT',\n 5: 'CONNECT',\n 6: 'OPTIONS',\n 7: 'TRACE',\n 8: 'COPY',\n 9: 'LOCK',\n 10: 'MKCOL',\n 11: 'MOVE',\n 12: 'PROPFIND',\n 13: 'PROPPATCH',\n 14: 'SEARCH',\n 15: 'UNLOCK',\n 16: 'BIND',\n 17: 'REBIND',\n 18: 'UNBIND',\n 19: 'ACL',\n 20: 'REPORT',\n 21: 'MKACTIVITY',\n 22: 'CHECKOUT',\n 23: 'MERGE',\n 24: 'M-SEARCH',\n 25: 'NOTIFY',\n 26: 'SUBSCRIBE',\n 27: 'UNSUBSCRIBE',\n 28: 'PATCH',\n 29: 'PURGE',\n 30: 'MKCALENDAR',\n 31: 'LINK',\n 32: 'UNLINK'\n};\n\nvar VERSION = process.version\n ? process.version.match(/[0-9]+/g).map(function(n) { return parseInt(n, 10) })\n : [];\n\nif (VERSION[0] === 0 && VERSION[1] === 12) {\n HttpParser.METHODS[16] = 'REPORT';\n HttpParser.METHODS[17] = 'MKACTIVITY';\n HttpParser.METHODS[18] = 'CHECKOUT';\n HttpParser.METHODS[19] = 'MERGE';\n HttpParser.METHODS[20] = 'M-SEARCH';\n HttpParser.METHODS[21] = 'NOTIFY';\n HttpParser.METHODS[22] = 'SUBSCRIBE';\n HttpParser.METHODS[23] = 'UNSUBSCRIBE';\n HttpParser.METHODS[24] = 'PATCH';\n HttpParser.METHODS[25] = 'PURGE';\n}\n\nHttpParser.prototype.isComplete = function() {\n return this._complete;\n};\n\nHttpParser.prototype.parse = function(chunk) {\n var consumed = this._parser.execute(chunk, 0, chunk.length);\n\n if (typeof consumed !== 'number') {\n this.error = consumed;\n this._complete = true;\n return;\n }\n\n if (this._complete)\n this.body = (consumed < chunk.length)\n ? chunk.slice(consumed)\n : Buffer.alloc(0);\n};\n\nmodule.exports = HttpParser;\n","'use strict';\n\nvar TOKEN = /([!#\\$%&'\\*\\+\\-\\.\\^_`\\|~0-9A-Za-z]+)/,\n NOTOKEN = /([^!#\\$%&'\\*\\+\\-\\.\\^_`\\|~0-9A-Za-z])/g,\n QUOTED = /\"((?:\\\\[\\x00-\\x7f]|[^\\x00-\\x08\\x0a-\\x1f\\x7f\"\\\\])*)\"/,\n PARAM = new RegExp(TOKEN.source + '(?:=(?:' + TOKEN.source + '|' + QUOTED.source + '))?'),\n EXT = new RegExp(TOKEN.source + '(?: *; *' + PARAM.source + ')*', 'g'),\n EXT_LIST = new RegExp('^' + EXT.source + '(?: *, *' + EXT.source + ')*$'),\n NUMBER = /^-?(0|[1-9][0-9]*)(\\.[0-9]+)?$/;\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nvar Parser = {\n parseHeader: function(header) {\n var offers = new Offers();\n if (header === '' || header === undefined) return offers;\n\n if (!EXT_LIST.test(header))\n throw new SyntaxError('Invalid Sec-WebSocket-Extensions header: ' + header);\n\n var values = header.match(EXT);\n\n values.forEach(function(value) {\n var params = value.match(new RegExp(PARAM.source, 'g')),\n name = params.shift(),\n offer = {};\n\n params.forEach(function(param) {\n var args = param.match(PARAM), key = args[1], data;\n\n if (args[2] !== undefined) {\n data = args[2];\n } else if (args[3] !== undefined) {\n data = args[3].replace(/\\\\/g, '');\n } else {\n data = true;\n }\n if (NUMBER.test(data)) data = parseFloat(data);\n\n if (hasOwnProperty.call(offer, key)) {\n offer[key] = [].concat(offer[key]);\n offer[key].push(data);\n } else {\n offer[key] = data;\n }\n }, this);\n offers.push(name, offer);\n }, this);\n\n return offers;\n },\n\n serializeParams: function(name, params) {\n var values = [];\n\n var print = function(key, value) {\n if (value instanceof Array) {\n value.forEach(function(v) { print(key, v) });\n } else if (value === true) {\n values.push(key);\n } else if (typeof value === 'number') {\n values.push(key + '=' + value);\n } else if (NOTOKEN.test(value)) {\n values.push(key + '=\"' + value.replace(/\"/g, '\\\\\"') + '\"');\n } else {\n values.push(key + '=' + value);\n }\n };\n\n for (var key in params) print(key, params[key]);\n\n return [name].concat(values).join('; ');\n }\n};\n\nvar Offers = function() {\n this._byName = {};\n this._inOrder = [];\n};\n\nOffers.prototype.push = function(name, params) {\n if (!hasOwnProperty.call(this._byName, name))\n this._byName[name] = [];\n\n this._byName[name].push(params);\n this._inOrder.push({ name: name, params: params });\n};\n\nOffers.prototype.eachOffer = function(callback, context) {\n var list = this._inOrder;\n for (var i = 0, n = list.length; i < n; i++)\n callback.call(context, list[i].name, list[i].params);\n};\n\nOffers.prototype.byName = function(name) {\n return this._byName[name] || [];\n};\n\nOffers.prototype.toArray = function() {\n return this._inOrder.slice();\n};\n\nmodule.exports = Parser;\n","'use strict';\n\nvar RingBuffer = function(bufferSize) {\n this._bufferSize = bufferSize;\n this.clear();\n};\n\nRingBuffer.prototype.clear = function() {\n this._buffer = new Array(this._bufferSize);\n this._ringOffset = 0;\n this._ringSize = this._bufferSize;\n this._head = 0;\n this._tail = 0;\n this.length = 0;\n};\n\nRingBuffer.prototype.push = function(value) {\n var expandBuffer = false,\n expandRing = false;\n\n if (this._ringSize < this._bufferSize) {\n expandBuffer = (this._tail === 0);\n } else if (this._ringOffset === this._ringSize) {\n expandBuffer = true;\n expandRing = (this._tail === 0);\n }\n\n if (expandBuffer) {\n this._tail = this._bufferSize;\n this._buffer = this._buffer.concat(new Array(this._bufferSize));\n this._bufferSize = this._buffer.length;\n\n if (expandRing)\n this._ringSize = this._bufferSize;\n }\n\n this._buffer[this._tail] = value;\n this.length += 1;\n if (this._tail < this._ringSize) this._ringOffset += 1;\n this._tail = (this._tail + 1) % this._bufferSize;\n};\n\nRingBuffer.prototype.peek = function() {\n if (this.length === 0) return void 0;\n return this._buffer[this._head];\n};\n\nRingBuffer.prototype.shift = function() {\n if (this.length === 0) return void 0;\n\n var value = this._buffer[this._head];\n this._buffer[this._head] = void 0;\n this.length -= 1;\n this._ringOffset -= 1;\n\n if (this._ringOffset === 0 && this.length > 0) {\n this._head = this._ringSize;\n this._ringOffset = this.length;\n this._ringSize = this._bufferSize;\n } else {\n this._head = (this._head + 1) % this._ringSize;\n }\n return value;\n};\n\nmodule.exports = RingBuffer;\n","'use strict';\n\nvar RingBuffer = require('./ring_buffer');\n\nvar Functor = function(session, method) {\n this._session = session;\n this._method = method;\n this._queue = new RingBuffer(Functor.QUEUE_SIZE);\n this._stopped = false;\n this.pending = 0;\n};\n\nFunctor.QUEUE_SIZE = 8;\n\nFunctor.prototype.call = function(error, message, callback, context) {\n if (this._stopped) return;\n\n var record = { error: error, message: message, callback: callback, context: context, done: false },\n called = false,\n self = this;\n\n this._queue.push(record);\n\n if (record.error) {\n record.done = true;\n this._stop();\n return this._flushQueue();\n }\n\n var handler = function(err, msg) {\n if (!(called ^ (called = true))) return;\n\n if (err) {\n self._stop();\n record.error = err;\n record.message = null;\n } else {\n record.message = msg;\n }\n\n record.done = true;\n self._flushQueue();\n };\n\n try {\n this._session[this._method](message, handler);\n } catch (err) {\n handler(err);\n }\n};\n\nFunctor.prototype._stop = function() {\n this.pending = this._queue.length;\n this._stopped = true;\n};\n\nFunctor.prototype._flushQueue = function() {\n var queue = this._queue, record;\n\n while (queue.length > 0 && queue.peek().done) {\n record = queue.shift();\n if (record.error) {\n this.pending = 0;\n queue.clear();\n } else {\n this.pending -= 1;\n }\n record.callback.call(record.context, record.error, record.message);\n }\n};\n\nmodule.exports = Functor;\n","'use strict';\n\nvar RingBuffer = require('./ring_buffer');\n\nvar Pledge = function() {\n this._complete = false;\n this._callbacks = new RingBuffer(Pledge.QUEUE_SIZE);\n};\n\nPledge.QUEUE_SIZE = 4;\n\nPledge.all = function(list) {\n var pledge = new Pledge(),\n pending = list.length,\n n = pending;\n\n if (pending === 0) pledge.done();\n\n while (n--) list[n].then(function() {\n pending -= 1;\n if (pending === 0) pledge.done();\n });\n return pledge;\n};\n\nPledge.prototype.then = function(callback) {\n if (this._complete) callback();\n else this._callbacks.push(callback);\n};\n\nPledge.prototype.done = function() {\n this._complete = true;\n var callbacks = this._callbacks, callback;\n while (callback = callbacks.shift()) callback();\n};\n\nmodule.exports = Pledge;\n","'use strict';\n\nvar Functor = require('./functor'),\n Pledge = require('./pledge');\n\nvar Cell = function(tuple) {\n this._ext = tuple[0];\n this._session = tuple[1];\n\n this._functors = {\n incoming: new Functor(this._session, 'processIncomingMessage'),\n outgoing: new Functor(this._session, 'processOutgoingMessage')\n };\n};\n\nCell.prototype.pending = function(direction) {\n var functor = this._functors[direction];\n if (!functor._stopped) functor.pending += 1;\n};\n\nCell.prototype.incoming = function(error, message, callback, context) {\n this._exec('incoming', error, message, callback, context);\n};\n\nCell.prototype.outgoing = function(error, message, callback, context) {\n this._exec('outgoing', error, message, callback, context);\n};\n\nCell.prototype.close = function() {\n this._closed = this._closed || new Pledge();\n this._doClose();\n return this._closed;\n};\n\nCell.prototype._exec = function(direction, error, message, callback, context) {\n this._functors[direction].call(error, message, function(err, msg) {\n if (err) err.message = this._ext.name + ': ' + err.message;\n callback.call(context, err, msg);\n this._doClose();\n }, this);\n};\n\nCell.prototype._doClose = function() {\n var fin = this._functors.incoming,\n fout = this._functors.outgoing;\n\n if (!this._closed || fin.pending + fout.pending !== 0) return;\n if (this._session) this._session.close();\n this._session = null;\n this._closed.done();\n};\n\nmodule.exports = Cell;\n","'use strict';\n\nvar Cell = require('./cell'),\n Pledge = require('./pledge');\n\nvar Pipeline = function(sessions) {\n this._cells = sessions.map(function(session) { return new Cell(session) });\n this._stopped = { incoming: false, outgoing: false };\n};\n\nPipeline.prototype.processIncomingMessage = function(message, callback, context) {\n if (this._stopped.incoming) return;\n this._loop('incoming', this._cells.length - 1, -1, -1, message, callback, context);\n};\n\nPipeline.prototype.processOutgoingMessage = function(message, callback, context) {\n if (this._stopped.outgoing) return;\n this._loop('outgoing', 0, this._cells.length, 1, message, callback, context);\n};\n\nPipeline.prototype.close = function(callback, context) {\n this._stopped = { incoming: true, outgoing: true };\n\n var closed = this._cells.map(function(a) { return a.close() });\n if (callback)\n Pledge.all(closed).then(function() { callback.call(context) });\n};\n\nPipeline.prototype._loop = function(direction, start, end, step, message, callback, context) {\n var cells = this._cells,\n n = cells.length,\n self = this;\n\n while (n--) cells[n].pending(direction);\n\n var pipe = function(index, error, msg) {\n if (index === end) return callback.call(context, error, msg);\n\n cells[index][direction](error, msg, function(err, m) {\n if (err) self._stopped[direction] = true;\n pipe(index + step, err, m);\n });\n };\n pipe(start, null, message);\n};\n\nmodule.exports = Pipeline;\n","'use strict';\n\nvar Parser = require('./parser'),\n Pipeline = require('./pipeline');\n\nvar Extensions = function() {\n this._rsv1 = this._rsv2 = this._rsv3 = null;\n\n this._byName = {};\n this._inOrder = [];\n this._sessions = [];\n this._index = {};\n};\n\nExtensions.MESSAGE_OPCODES = [1, 2];\n\nvar instance = {\n add: function(ext) {\n if (typeof ext.name !== 'string') throw new TypeError('extension.name must be a string');\n if (ext.type !== 'permessage') throw new TypeError('extension.type must be \"permessage\"');\n\n if (typeof ext.rsv1 !== 'boolean') throw new TypeError('extension.rsv1 must be true or false');\n if (typeof ext.rsv2 !== 'boolean') throw new TypeError('extension.rsv2 must be true or false');\n if (typeof ext.rsv3 !== 'boolean') throw new TypeError('extension.rsv3 must be true or false');\n\n if (this._byName.hasOwnProperty(ext.name))\n throw new TypeError('An extension with name \"' + ext.name + '\" is already registered');\n\n this._byName[ext.name] = ext;\n this._inOrder.push(ext);\n },\n\n generateOffer: function() {\n var sessions = [],\n offer = [],\n index = {};\n\n this._inOrder.forEach(function(ext) {\n var session = ext.createClientSession();\n if (!session) return;\n\n var record = [ext, session];\n sessions.push(record);\n index[ext.name] = record;\n\n var offers = session.generateOffer();\n offers = offers ? [].concat(offers) : [];\n\n offers.forEach(function(off) {\n offer.push(Parser.serializeParams(ext.name, off));\n }, this);\n }, this);\n\n this._sessions = sessions;\n this._index = index;\n\n return offer.length > 0 ? offer.join(', ') : null;\n },\n\n activate: function(header) {\n var responses = Parser.parseHeader(header),\n sessions = [];\n\n responses.eachOffer(function(name, params) {\n var record = this._index[name];\n\n if (!record)\n throw new Error('Server sent an extension response for unknown extension \"' + name + '\"');\n\n var ext = record[0],\n session = record[1],\n reserved = this._reserved(ext);\n\n if (reserved)\n throw new Error('Server sent two extension responses that use the RSV' +\n reserved[0] + ' bit: \"' +\n reserved[1] + '\" and \"' + ext.name + '\"');\n\n if (session.activate(params) !== true)\n throw new Error('Server sent unacceptable extension parameters: ' +\n Parser.serializeParams(name, params));\n\n this._reserve(ext);\n sessions.push(record);\n }, this);\n\n this._sessions = sessions;\n this._pipeline = new Pipeline(sessions);\n },\n\n generateResponse: function(header) {\n var sessions = [],\n response = [],\n offers = Parser.parseHeader(header);\n\n this._inOrder.forEach(function(ext) {\n var offer = offers.byName(ext.name);\n if (offer.length === 0 || this._reserved(ext)) return;\n\n var session = ext.createServerSession(offer);\n if (!session) return;\n\n this._reserve(ext);\n sessions.push([ext, session]);\n response.push(Parser.serializeParams(ext.name, session.generateResponse()));\n }, this);\n\n this._sessions = sessions;\n this._pipeline = new Pipeline(sessions);\n\n return response.length > 0 ? response.join(', ') : null;\n },\n\n validFrameRsv: function(frame) {\n var allowed = { rsv1: false, rsv2: false, rsv3: false },\n ext;\n\n if (Extensions.MESSAGE_OPCODES.indexOf(frame.opcode) >= 0) {\n for (var i = 0, n = this._sessions.length; i < n; i++) {\n ext = this._sessions[i][0];\n allowed.rsv1 = allowed.rsv1 || ext.rsv1;\n allowed.rsv2 = allowed.rsv2 || ext.rsv2;\n allowed.rsv3 = allowed.rsv3 || ext.rsv3;\n }\n }\n\n return (allowed.rsv1 || !frame.rsv1) &&\n (allowed.rsv2 || !frame.rsv2) &&\n (allowed.rsv3 || !frame.rsv3);\n },\n\n processIncomingMessage: function(message, callback, context) {\n this._pipeline.processIncomingMessage(message, callback, context);\n },\n\n processOutgoingMessage: function(message, callback, context) {\n this._pipeline.processOutgoingMessage(message, callback, context);\n },\n\n close: function(callback, context) {\n if (!this._pipeline) return callback.call(context);\n this._pipeline.close(callback, context);\n },\n\n _reserve: function(ext) {\n this._rsv1 = this._rsv1 || (ext.rsv1 && ext.name);\n this._rsv2 = this._rsv2 || (ext.rsv2 && ext.name);\n this._rsv3 = this._rsv3 || (ext.rsv3 && ext.name);\n },\n\n _reserved: function(ext) {\n if (this._rsv1 && ext.rsv1) return [1, this._rsv1];\n if (this._rsv2 && ext.rsv2) return [2, this._rsv2];\n if (this._rsv3 && ext.rsv3) return [3, this._rsv3];\n return false;\n }\n};\n\nfor (var key in instance)\n Extensions.prototype[key] = instance[key];\n\nmodule.exports = Extensions;\n","'use strict';\n\nvar Frame = function() {};\n\nvar instance = {\n final: false,\n rsv1: false,\n rsv2: false,\n rsv3: false,\n opcode: null,\n masked: false,\n maskingKey: null,\n lengthBytes: 1,\n length: 0,\n payload: null\n};\n\nfor (var key in instance)\n Frame.prototype[key] = instance[key];\n\nmodule.exports = Frame;\n","'use strict';\n\nvar Buffer = require('safe-buffer').Buffer;\n\nvar Message = function() {\n this.rsv1 = false;\n this.rsv2 = false;\n this.rsv3 = false;\n this.opcode = null;\n this.length = 0;\n this._chunks = [];\n};\n\nvar instance = {\n read: function() {\n return this.data = this.data || Buffer.concat(this._chunks, this.length);\n },\n\n pushFrame: function(frame) {\n this.rsv1 = this.rsv1 || frame.rsv1;\n this.rsv2 = this.rsv2 || frame.rsv2;\n this.rsv3 = this.rsv3 || frame.rsv3;\n\n if (this.opcode === null) this.opcode = frame.opcode;\n\n this._chunks.push(frame.payload);\n this.length += frame.length;\n }\n};\n\nfor (var key in instance)\n Message.prototype[key] = instance[key];\n\nmodule.exports = Message;\n","'use strict';\n\nvar Buffer = require('safe-buffer').Buffer,\n crypto = require('crypto'),\n util = require('util'),\n Extensions = require('websocket-extensions'),\n Base = require('./base'),\n Frame = require('./hybi/frame'),\n Message = require('./hybi/message');\n\nvar Hybi = function(request, url, options) {\n Base.apply(this, arguments);\n\n this._extensions = new Extensions();\n this._stage = 0;\n this._masking = this._options.masking;\n this._protocols = this._options.protocols || [];\n this._requireMasking = this._options.requireMasking;\n this._pingCallbacks = {};\n\n if (typeof this._protocols === 'string')\n this._protocols = this._protocols.split(/ *, */);\n\n if (!this._request) return;\n\n var protos = this._request.headers['sec-websocket-protocol'],\n supported = this._protocols;\n\n if (protos !== undefined) {\n if (typeof protos === 'string') protos = protos.split(/ *, */);\n this.protocol = protos.filter(function(p) { return supported.indexOf(p) >= 0 })[0];\n }\n\n this.version = 'hybi-' + Hybi.VERSION;\n};\nutil.inherits(Hybi, Base);\n\nHybi.VERSION = '13';\n\nHybi.mask = function(payload, mask, offset) {\n if (!mask || mask.length === 0) return payload;\n offset = offset || 0;\n\n for (var i = 0, n = payload.length - offset; i < n; i++) {\n payload[offset + i] = payload[offset + i] ^ mask[i % 4];\n }\n return payload;\n};\n\nHybi.generateAccept = function(key) {\n var sha1 = crypto.createHash('sha1');\n sha1.update(key + Hybi.GUID);\n return sha1.digest('base64');\n};\n\nHybi.GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';\n\nvar instance = {\n FIN: 0x80,\n MASK: 0x80,\n RSV1: 0x40,\n RSV2: 0x20,\n RSV3: 0x10,\n OPCODE: 0x0F,\n LENGTH: 0x7F,\n\n OPCODES: {\n continuation: 0,\n text: 1,\n binary: 2,\n close: 8,\n ping: 9,\n pong: 10\n },\n\n OPCODE_CODES: [0, 1, 2, 8, 9, 10],\n MESSAGE_OPCODES: [0, 1, 2],\n OPENING_OPCODES: [1, 2],\n\n ERRORS: {\n normal_closure: 1000,\n going_away: 1001,\n protocol_error: 1002,\n unacceptable: 1003,\n encoding_error: 1007,\n policy_violation: 1008,\n too_large: 1009,\n extension_error: 1010,\n unexpected_condition: 1011\n },\n\n ERROR_CODES: [1000, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011],\n DEFAULT_ERROR_CODE: 1000,\n MIN_RESERVED_ERROR: 3000,\n MAX_RESERVED_ERROR: 4999,\n\n // http://www.w3.org/International/questions/qa-forms-utf-8.en.php\n UTF8_MATCH: /^([\\x00-\\x7F]|[\\xC2-\\xDF][\\x80-\\xBF]|\\xE0[\\xA0-\\xBF][\\x80-\\xBF]|[\\xE1-\\xEC\\xEE\\xEF][\\x80-\\xBF]{2}|\\xED[\\x80-\\x9F][\\x80-\\xBF]|\\xF0[\\x90-\\xBF][\\x80-\\xBF]{2}|[\\xF1-\\xF3][\\x80-\\xBF]{3}|\\xF4[\\x80-\\x8F][\\x80-\\xBF]{2})*$/,\n\n addExtension: function(extension) {\n this._extensions.add(extension);\n return true;\n },\n\n parse: function(chunk) {\n this._reader.put(chunk);\n var buffer = true;\n while (buffer) {\n switch (this._stage) {\n case 0:\n buffer = this._reader.read(1);\n if (buffer) this._parseOpcode(buffer[0]);\n break;\n\n case 1:\n buffer = this._reader.read(1);\n if (buffer) this._parseLength(buffer[0]);\n break;\n\n case 2:\n buffer = this._reader.read(this._frame.lengthBytes);\n if (buffer) this._parseExtendedLength(buffer);\n break;\n\n case 3:\n buffer = this._reader.read(4);\n if (buffer) {\n this._stage = 4;\n this._frame.maskingKey = buffer;\n }\n break;\n\n case 4:\n buffer = this._reader.read(this._frame.length);\n if (buffer) {\n this._stage = 0;\n this._emitFrame(buffer);\n }\n break;\n\n default:\n buffer = null;\n }\n }\n },\n\n text: function(message) {\n if (this.readyState > 1) return false;\n return this.frame(message, 'text');\n },\n\n binary: function(message) {\n if (this.readyState > 1) return false;\n return this.frame(message, 'binary');\n },\n\n ping: function(message, callback) {\n if (this.readyState > 1) return false;\n message = message || '';\n if (callback) this._pingCallbacks[message] = callback;\n return this.frame(message, 'ping');\n },\n\n pong: function(message) {\n if (this.readyState > 1) return false;\n message = message ||'';\n return this.frame(message, 'pong');\n },\n\n close: function(reason, code) {\n reason = reason || '';\n code = code || this.ERRORS.normal_closure;\n\n if (this.readyState <= 0) {\n this.readyState = 3;\n this.emit('close', new Base.CloseEvent(code, reason));\n return true;\n } else if (this.readyState === 1) {\n this.readyState = 2;\n this._extensions.close(function() { this.frame(reason, 'close', code) }, this);\n return true;\n } else {\n return false;\n }\n },\n\n frame: function(buffer, type, code) {\n if (this.readyState <= 0) return this._queue([buffer, type, code]);\n if (this.readyState > 2) return false;\n\n if (buffer instanceof Array) buffer = Buffer.from(buffer);\n if (typeof buffer === 'number') buffer = buffer.toString();\n\n var message = new Message(),\n isText = (typeof buffer === 'string'),\n payload, copy;\n\n message.rsv1 = message.rsv2 = message.rsv3 = false;\n message.opcode = this.OPCODES[type || (isText ? 'text' : 'binary')];\n\n payload = isText ? Buffer.from(buffer, 'utf8') : buffer;\n\n if (code) {\n copy = payload;\n payload = Buffer.allocUnsafe(2 + copy.length);\n payload.writeUInt16BE(code, 0);\n copy.copy(payload, 2);\n }\n message.data = payload;\n\n var onMessageReady = function(message) {\n var frame = new Frame();\n\n frame.final = true;\n frame.rsv1 = message.rsv1;\n frame.rsv2 = message.rsv2;\n frame.rsv3 = message.rsv3;\n frame.opcode = message.opcode;\n frame.masked = !!this._masking;\n frame.length = message.data.length;\n frame.payload = message.data;\n\n if (frame.masked) frame.maskingKey = crypto.randomBytes(4);\n\n this._sendFrame(frame);\n };\n\n if (this.MESSAGE_OPCODES.indexOf(message.opcode) >= 0)\n this._extensions.processOutgoingMessage(message, function(error, message) {\n if (error) return this._fail('extension_error', error.message);\n onMessageReady.call(this, message);\n }, this);\n else\n onMessageReady.call(this, message);\n\n return true;\n },\n\n _sendFrame: function(frame) {\n var length = frame.length,\n header = (length <= 125) ? 2 : (length <= 65535 ? 4 : 10),\n offset = header + (frame.masked ? 4 : 0),\n buffer = Buffer.allocUnsafe(offset + length),\n masked = frame.masked ? this.MASK : 0;\n\n buffer[0] = (frame.final ? this.FIN : 0) |\n (frame.rsv1 ? this.RSV1 : 0) |\n (frame.rsv2 ? this.RSV2 : 0) |\n (frame.rsv3 ? this.RSV3 : 0) |\n frame.opcode;\n\n if (length <= 125) {\n buffer[1] = masked | length;\n } else if (length <= 65535) {\n buffer[1] = masked | 126;\n buffer.writeUInt16BE(length, 2);\n } else {\n buffer[1] = masked | 127;\n buffer.writeUInt32BE(Math.floor(length / 0x100000000), 2);\n buffer.writeUInt32BE(length % 0x100000000, 6);\n }\n\n frame.payload.copy(buffer, offset);\n\n if (frame.masked) {\n frame.maskingKey.copy(buffer, header);\n Hybi.mask(buffer, frame.maskingKey, offset);\n }\n\n this._write(buffer);\n },\n\n _handshakeResponse: function() {\n var secKey = this._request.headers['sec-websocket-key'],\n version = this._request.headers['sec-websocket-version'];\n\n if (version !== Hybi.VERSION)\n throw new Error('Unsupported WebSocket version: ' + version);\n\n if (typeof secKey !== 'string')\n throw new Error('Missing handshake request header: Sec-WebSocket-Key');\n\n this._headers.set('Upgrade', 'websocket');\n this._headers.set('Connection', 'Upgrade');\n this._headers.set('Sec-WebSocket-Accept', Hybi.generateAccept(secKey));\n\n if (this.protocol) this._headers.set('Sec-WebSocket-Protocol', this.protocol);\n\n var extensions = this._extensions.generateResponse(this._request.headers['sec-websocket-extensions']);\n if (extensions) this._headers.set('Sec-WebSocket-Extensions', extensions);\n\n var start = 'HTTP/1.1 101 Switching Protocols',\n headers = [start, this._headers.toString(), ''];\n\n return Buffer.from(headers.join('\\r\\n'), 'utf8');\n },\n\n _shutdown: function(code, reason, error) {\n delete this._frame;\n delete this._message;\n this._stage = 5;\n\n var sendCloseFrame = (this.readyState === 1);\n this.readyState = 2;\n\n this._extensions.close(function() {\n if (sendCloseFrame) this.frame(reason, 'close', code);\n this.readyState = 3;\n if (error) this.emit('error', new Error(reason));\n this.emit('close', new Base.CloseEvent(code, reason));\n }, this);\n },\n\n _fail: function(type, message) {\n if (this.readyState > 1) return;\n this._shutdown(this.ERRORS[type], message, true);\n },\n\n _parseOpcode: function(octet) {\n var rsvs = [this.RSV1, this.RSV2, this.RSV3].map(function(rsv) {\n return (octet & rsv) === rsv;\n });\n\n var frame = this._frame = new Frame();\n\n frame.final = (octet & this.FIN) === this.FIN;\n frame.rsv1 = rsvs[0];\n frame.rsv2 = rsvs[1];\n frame.rsv3 = rsvs[2];\n frame.opcode = (octet & this.OPCODE);\n\n this._stage = 1;\n\n if (!this._extensions.validFrameRsv(frame))\n return this._fail('protocol_error',\n 'One or more reserved bits are on: reserved1 = ' + (frame.rsv1 ? 1 : 0) +\n ', reserved2 = ' + (frame.rsv2 ? 1 : 0) +\n ', reserved3 = ' + (frame.rsv3 ? 1 : 0));\n\n if (this.OPCODE_CODES.indexOf(frame.opcode) < 0)\n return this._fail('protocol_error', 'Unrecognized frame opcode: ' + frame.opcode);\n\n if (this.MESSAGE_OPCODES.indexOf(frame.opcode) < 0 && !frame.final)\n return this._fail('protocol_error', 'Received fragmented control frame: opcode = ' + frame.opcode);\n\n if (this._message && this.OPENING_OPCODES.indexOf(frame.opcode) >= 0)\n return this._fail('protocol_error', 'Received new data frame but previous continuous frame is unfinished');\n },\n\n _parseLength: function(octet) {\n var frame = this._frame;\n frame.masked = (octet & this.MASK) === this.MASK;\n frame.length = (octet & this.LENGTH);\n\n if (frame.length >= 0 && frame.length <= 125) {\n this._stage = frame.masked ? 3 : 4;\n if (!this._checkFrameLength()) return;\n } else {\n this._stage = 2;\n frame.lengthBytes = (frame.length === 126 ? 2 : 8);\n }\n\n if (this._requireMasking && !frame.masked)\n return this._fail('unacceptable', 'Received unmasked frame but masking is required');\n },\n\n _parseExtendedLength: function(buffer) {\n var frame = this._frame;\n frame.length = this._readUInt(buffer);\n\n this._stage = frame.masked ? 3 : 4;\n\n if (this.MESSAGE_OPCODES.indexOf(frame.opcode) < 0 && frame.length > 125)\n return this._fail('protocol_error', 'Received control frame having too long payload: ' + frame.length);\n\n if (!this._checkFrameLength()) return;\n },\n\n _checkFrameLength: function() {\n var length = this._message ? this._message.length : 0;\n\n if (length + this._frame.length > this._maxLength) {\n this._fail('too_large', 'WebSocket frame length too large');\n return false;\n } else {\n return true;\n }\n },\n\n _emitFrame: function(buffer) {\n var frame = this._frame,\n payload = frame.payload = Hybi.mask(buffer, frame.maskingKey),\n opcode = frame.opcode,\n message,\n code, reason,\n callbacks, callback;\n\n delete this._frame;\n\n if (opcode === this.OPCODES.continuation) {\n if (!this._message) return this._fail('protocol_error', 'Received unexpected continuation frame');\n this._message.pushFrame(frame);\n }\n\n if (opcode === this.OPCODES.text || opcode === this.OPCODES.binary) {\n this._message = new Message();\n this._message.pushFrame(frame);\n }\n\n if (frame.final && this.MESSAGE_OPCODES.indexOf(opcode) >= 0)\n return this._emitMessage(this._message);\n\n if (opcode === this.OPCODES.close) {\n code = (payload.length >= 2) ? payload.readUInt16BE(0) : null;\n reason = (payload.length > 2) ? this._encode(payload.slice(2)) : null;\n\n if (!(payload.length === 0) &&\n !(code !== null && code >= this.MIN_RESERVED_ERROR && code <= this.MAX_RESERVED_ERROR) &&\n this.ERROR_CODES.indexOf(code) < 0)\n code = this.ERRORS.protocol_error;\n\n if (payload.length > 125 || (payload.length > 2 && !reason))\n code = this.ERRORS.protocol_error;\n\n this._shutdown(code || this.DEFAULT_ERROR_CODE, reason || '');\n }\n\n if (opcode === this.OPCODES.ping) {\n this.frame(payload, 'pong');\n this.emit('ping', new Base.PingEvent(payload.toString()))\n }\n\n if (opcode === this.OPCODES.pong) {\n callbacks = this._pingCallbacks;\n message = this._encode(payload);\n callback = callbacks[message];\n\n delete callbacks[message];\n if (callback) callback()\n\n this.emit('pong', new Base.PongEvent(payload.toString()))\n }\n },\n\n _emitMessage: function(message) {\n var message = this._message;\n message.read();\n\n delete this._message;\n\n this._extensions.processIncomingMessage(message, function(error, message) {\n if (error) return this._fail('extension_error', error.message);\n\n var payload = message.data;\n if (message.opcode === this.OPCODES.text) payload = this._encode(payload);\n\n if (payload === null)\n return this._fail('encoding_error', 'Could not decode a text frame as UTF-8');\n else\n this.emit('message', new Base.MessageEvent(payload));\n }, this);\n },\n\n _encode: function(buffer) {\n try {\n var string = buffer.toString('binary', 0, buffer.length);\n if (!this.UTF8_MATCH.test(string)) return null;\n } catch (e) {}\n return buffer.toString('utf8', 0, buffer.length);\n },\n\n _readUInt: function(buffer) {\n if (buffer.length === 2) return buffer.readUInt16BE(0);\n\n return buffer.readUInt32BE(0) * 0x100000000 +\n buffer.readUInt32BE(4);\n }\n};\n\nfor (var key in instance)\n Hybi.prototype[key] = instance[key];\n\nmodule.exports = Hybi;\n","'use strict';\n\nvar Buffer = require('safe-buffer').Buffer,\n Stream = require('stream').Stream,\n url = require('url'),\n util = require('util'),\n Base = require('./base'),\n Headers = require('./headers'),\n HttpParser = require('../http_parser');\n\nvar PORTS = { 'ws:': 80, 'wss:': 443 };\n\nvar Proxy = function(client, origin, options) {\n this._client = client;\n this._http = new HttpParser('response');\n this._origin = (typeof client.url === 'object') ? client.url : url.parse(client.url);\n this._url = (typeof origin === 'object') ? origin : url.parse(origin);\n this._options = options || {};\n this._state = 0;\n\n this.readable = this.writable = true;\n this._paused = false;\n\n this._headers = new Headers();\n this._headers.set('Host', this._origin.host);\n this._headers.set('Connection', 'keep-alive');\n this._headers.set('Proxy-Connection', 'keep-alive');\n\n var auth = this._url.auth && Buffer.from(this._url.auth, 'utf8').toString('base64');\n if (auth) this._headers.set('Proxy-Authorization', 'Basic ' + auth);\n};\nutil.inherits(Proxy, Stream);\n\nvar instance = {\n setHeader: function(name, value) {\n if (this._state !== 0) return false;\n this._headers.set(name, value);\n return true;\n },\n\n start: function() {\n if (this._state !== 0) return false;\n this._state = 1;\n\n var origin = this._origin,\n port = origin.port || PORTS[origin.protocol],\n start = 'CONNECT ' + origin.hostname + ':' + port + ' HTTP/1.1';\n\n var headers = [start, this._headers.toString(), ''];\n\n this.emit('data', Buffer.from(headers.join('\\r\\n'), 'utf8'));\n return true;\n },\n\n pause: function() {\n this._paused = true;\n },\n\n resume: function() {\n this._paused = false;\n this.emit('drain');\n },\n\n write: function(chunk) {\n if (!this.writable) return false;\n\n this._http.parse(chunk);\n if (!this._http.isComplete()) return !this._paused;\n\n this.statusCode = this._http.statusCode;\n this.headers = this._http.headers;\n\n if (this.statusCode === 200) {\n this.emit('connect', new Base.ConnectEvent());\n } else {\n var message = \"Can't establish a connection to the server at \" + this._origin.href;\n this.emit('error', new Error(message));\n }\n this.end();\n return !this._paused;\n },\n\n end: function(chunk) {\n if (!this.writable) return;\n if (chunk !== undefined) this.write(chunk);\n this.readable = this.writable = false;\n this.emit('close');\n this.emit('end');\n },\n\n destroy: function() {\n this.end();\n }\n};\n\nfor (var key in instance)\n Proxy.prototype[key] = instance[key];\n\nmodule.exports = Proxy;\n","'use strict';\n\nvar Buffer = require('safe-buffer').Buffer,\n crypto = require('crypto'),\n url = require('url'),\n util = require('util'),\n HttpParser = require('../http_parser'),\n Base = require('./base'),\n Hybi = require('./hybi'),\n Proxy = require('./proxy');\n\nvar Client = function(_url, options) {\n this.version = 'hybi-' + Hybi.VERSION;\n Hybi.call(this, null, _url, options);\n\n this.readyState = -1;\n this._key = Client.generateKey();\n this._accept = Hybi.generateAccept(this._key);\n this._http = new HttpParser('response');\n\n var uri = url.parse(this.url),\n auth = uri.auth && Buffer.from(uri.auth, 'utf8').toString('base64');\n\n if (this.VALID_PROTOCOLS.indexOf(uri.protocol) < 0)\n throw new Error(this.url + ' is not a valid WebSocket URL');\n\n this._pathname = (uri.pathname || '/') + (uri.search || '');\n\n this._headers.set('Host', uri.host);\n this._headers.set('Upgrade', 'websocket');\n this._headers.set('Connection', 'Upgrade');\n this._headers.set('Sec-WebSocket-Key', this._key);\n this._headers.set('Sec-WebSocket-Version', Hybi.VERSION);\n\n if (this._protocols.length > 0)\n this._headers.set('Sec-WebSocket-Protocol', this._protocols.join(', '));\n\n if (auth)\n this._headers.set('Authorization', 'Basic ' + auth);\n};\nutil.inherits(Client, Hybi);\n\nClient.generateKey = function() {\n return crypto.randomBytes(16).toString('base64');\n};\n\nvar instance = {\n VALID_PROTOCOLS: ['ws:', 'wss:'],\n\n proxy: function(origin, options) {\n return new Proxy(this, origin, options);\n },\n\n start: function() {\n if (this.readyState !== -1) return false;\n this._write(this._handshakeRequest());\n this.readyState = 0;\n return true;\n },\n\n parse: function(chunk) {\n if (this.readyState === 3) return;\n if (this.readyState > 0) return Hybi.prototype.parse.call(this, chunk);\n\n this._http.parse(chunk);\n if (!this._http.isComplete()) return;\n\n this._validateHandshake();\n if (this.readyState === 3) return;\n\n this._open();\n this.parse(this._http.body);\n },\n\n _handshakeRequest: function() {\n var extensions = this._extensions.generateOffer();\n if (extensions)\n this._headers.set('Sec-WebSocket-Extensions', extensions);\n\n var start = 'GET ' + this._pathname + ' HTTP/1.1',\n headers = [start, this._headers.toString(), ''];\n\n return Buffer.from(headers.join('\\r\\n'), 'utf8');\n },\n\n _failHandshake: function(message) {\n message = 'Error during WebSocket handshake: ' + message;\n this.readyState = 3;\n this.emit('error', new Error(message));\n this.emit('close', new Base.CloseEvent(this.ERRORS.protocol_error, message));\n },\n\n _validateHandshake: function() {\n this.statusCode = this._http.statusCode;\n this.headers = this._http.headers;\n\n if (this._http.error)\n return this._failHandshake(this._http.error.message);\n\n if (this._http.statusCode !== 101)\n return this._failHandshake('Unexpected response code: ' + this._http.statusCode);\n\n var headers = this._http.headers,\n upgrade = headers['upgrade'] || '',\n connection = headers['connection'] || '',\n accept = headers['sec-websocket-accept'] || '',\n protocol = headers['sec-websocket-protocol'] || '';\n\n if (upgrade === '')\n return this._failHandshake(\"'Upgrade' header is missing\");\n if (upgrade.toLowerCase() !== 'websocket')\n return this._failHandshake(\"'Upgrade' header value is not 'WebSocket'\");\n\n if (connection === '')\n return this._failHandshake(\"'Connection' header is missing\");\n if (connection.toLowerCase() !== 'upgrade')\n return this._failHandshake(\"'Connection' header value is not 'Upgrade'\");\n\n if (accept !== this._accept)\n return this._failHandshake('Sec-WebSocket-Accept mismatch');\n\n this.protocol = null;\n\n if (protocol !== '') {\n if (this._protocols.indexOf(protocol) < 0)\n return this._failHandshake('Sec-WebSocket-Protocol mismatch');\n else\n this.protocol = protocol;\n }\n\n try {\n this._extensions.activate(this.headers['sec-websocket-extensions']);\n } catch (e) {\n return this._failHandshake(e.message);\n }\n }\n};\n\nfor (var key in instance)\n Client.prototype[key] = instance[key];\n\nmodule.exports = Client;\n","'use strict';\n\nvar Buffer = require('safe-buffer').Buffer,\n Base = require('./base'),\n util = require('util');\n\nvar Draft75 = function(request, url, options) {\n Base.apply(this, arguments);\n this._stage = 0;\n this.version = 'hixie-75';\n\n this._headers.set('Upgrade', 'WebSocket');\n this._headers.set('Connection', 'Upgrade');\n this._headers.set('WebSocket-Origin', this._request.headers.origin);\n this._headers.set('WebSocket-Location', this.url);\n};\nutil.inherits(Draft75, Base);\n\nvar instance = {\n close: function() {\n if (this.readyState === 3) return false;\n this.readyState = 3;\n this.emit('close', new Base.CloseEvent(null, null));\n return true;\n },\n\n parse: function(chunk) {\n if (this.readyState > 1) return;\n\n this._reader.put(chunk);\n\n this._reader.eachByte(function(octet) {\n var message;\n\n switch (this._stage) {\n case -1:\n this._body.push(octet);\n this._sendHandshakeBody();\n break;\n\n case 0:\n this._parseLeadingByte(octet);\n break;\n\n case 1:\n this._length = (octet & 0x7F) + 128 * this._length;\n\n if (this._closing && this._length === 0) {\n return this.close();\n }\n else if ((octet & 0x80) !== 0x80) {\n if (this._length === 0) {\n this._stage = 0;\n }\n else {\n this._skipped = 0;\n this._stage = 2;\n }\n }\n break;\n\n case 2:\n if (octet === 0xFF) {\n this._stage = 0;\n message = Buffer.from(this._buffer).toString('utf8', 0, this._buffer.length);\n this.emit('message', new Base.MessageEvent(message));\n }\n else {\n if (this._length) {\n this._skipped += 1;\n if (this._skipped === this._length)\n this._stage = 0;\n } else {\n this._buffer.push(octet);\n if (this._buffer.length > this._maxLength) return this.close();\n }\n }\n break;\n }\n }, this);\n },\n\n frame: function(buffer) {\n if (this.readyState === 0) return this._queue([buffer]);\n if (this.readyState > 1) return false;\n\n if (typeof buffer !== 'string') buffer = buffer.toString();\n\n var length = Buffer.byteLength(buffer),\n frame = Buffer.allocUnsafe(length + 2);\n\n frame[0] = 0x00;\n frame.write(buffer, 1);\n frame[frame.length - 1] = 0xFF;\n\n this._write(frame);\n return true;\n },\n\n _handshakeResponse: function() {\n var start = 'HTTP/1.1 101 Web Socket Protocol Handshake',\n headers = [start, this._headers.toString(), ''];\n\n return Buffer.from(headers.join('\\r\\n'), 'utf8');\n },\n\n _parseLeadingByte: function(octet) {\n if ((octet & 0x80) === 0x80) {\n this._length = 0;\n this._stage = 1;\n } else {\n delete this._length;\n delete this._skipped;\n this._buffer = [];\n this._stage = 2;\n }\n }\n};\n\nfor (var key in instance)\n Draft75.prototype[key] = instance[key];\n\nmodule.exports = Draft75;\n","'use strict';\n\nvar Buffer = require('safe-buffer').Buffer,\n Base = require('./base'),\n Draft75 = require('./draft75'),\n crypto = require('crypto'),\n util = require('util');\n\n\nvar numberFromKey = function(key) {\n return parseInt((key.match(/[0-9]/g) || []).join(''), 10);\n};\n\nvar spacesInKey = function(key) {\n return (key.match(/ /g) || []).length;\n};\n\n\nvar Draft76 = function(request, url, options) {\n Draft75.apply(this, arguments);\n this._stage = -1;\n this._body = [];\n this.version = 'hixie-76';\n\n this._headers.clear();\n\n this._headers.set('Upgrade', 'WebSocket');\n this._headers.set('Connection', 'Upgrade');\n this._headers.set('Sec-WebSocket-Origin', this._request.headers.origin);\n this._headers.set('Sec-WebSocket-Location', this.url);\n};\nutil.inherits(Draft76, Draft75);\n\nvar instance = {\n BODY_SIZE: 8,\n\n start: function() {\n if (!Draft75.prototype.start.call(this)) return false;\n this._started = true;\n this._sendHandshakeBody();\n return true;\n },\n\n close: function() {\n if (this.readyState === 3) return false;\n if (this.readyState === 1) this._write(Buffer.from([0xFF, 0x00]));\n this.readyState = 3;\n this.emit('close', new Base.CloseEvent(null, null));\n return true;\n },\n\n _handshakeResponse: function() {\n var headers = this._request.headers,\n key1 = headers['sec-websocket-key1'],\n key2 = headers['sec-websocket-key2'];\n\n if (!key1) throw new Error('Missing required header: Sec-WebSocket-Key1');\n if (!key2) throw new Error('Missing required header: Sec-WebSocket-Key2');\n\n var number1 = numberFromKey(key1),\n spaces1 = spacesInKey(key1),\n\n number2 = numberFromKey(key2),\n spaces2 = spacesInKey(key2);\n\n if (number1 % spaces1 !== 0 || number2 % spaces2 !== 0)\n throw new Error('Client sent invalid Sec-WebSocket-Key headers');\n\n this._keyValues = [number1 / spaces1, number2 / spaces2];\n\n var start = 'HTTP/1.1 101 WebSocket Protocol Handshake',\n headers = [start, this._headers.toString(), ''];\n\n return Buffer.from(headers.join('\\r\\n'), 'binary');\n },\n\n _handshakeSignature: function() {\n if (this._body.length < this.BODY_SIZE) return null;\n\n var md5 = crypto.createHash('md5'),\n buffer = Buffer.allocUnsafe(8 + this.BODY_SIZE);\n\n buffer.writeUInt32BE(this._keyValues[0], 0);\n buffer.writeUInt32BE(this._keyValues[1], 4);\n Buffer.from(this._body).copy(buffer, 8, 0, this.BODY_SIZE);\n\n md5.update(buffer);\n return Buffer.from(md5.digest('binary'), 'binary');\n },\n\n _sendHandshakeBody: function() {\n if (!this._started) return;\n var signature = this._handshakeSignature();\n if (!signature) return;\n\n this._write(signature);\n this._stage = 0;\n this._open();\n\n if (this._body.length > this.BODY_SIZE)\n this.parse(this._body.slice(this.BODY_SIZE));\n },\n\n _parseLeadingByte: function(octet) {\n if (octet !== 0xFF)\n return Draft75.prototype._parseLeadingByte.call(this, octet);\n\n this._closing = true;\n this._length = 0;\n this._stage = 1;\n }\n};\n\nfor (var key in instance)\n Draft76.prototype[key] = instance[key];\n\nmodule.exports = Draft76;\n","'use strict';\n\nvar util = require('util'),\n HttpParser = require('../http_parser'),\n Base = require('./base'),\n Draft75 = require('./draft75'),\n Draft76 = require('./draft76'),\n Hybi = require('./hybi');\n\nvar Server = function(options) {\n Base.call(this, null, null, options);\n this._http = new HttpParser('request');\n};\nutil.inherits(Server, Base);\n\nvar instance = {\n EVENTS: ['open', 'message', 'error', 'close', 'ping', 'pong'],\n\n _bindEventListeners: function() {\n this.messages.on('error', function() {});\n this.on('error', function() {});\n },\n\n parse: function(chunk) {\n if (this._delegate) return this._delegate.parse(chunk);\n\n this._http.parse(chunk);\n if (!this._http.isComplete()) return;\n\n this.method = this._http.method;\n this.url = this._http.url;\n this.headers = this._http.headers;\n this.body = this._http.body;\n\n var self = this;\n this._delegate = Server.http(this, this._options);\n this._delegate.messages = this.messages;\n this._delegate.io = this.io;\n this._open();\n\n this.EVENTS.forEach(function(event) {\n this._delegate.on(event, function(e) { self.emit(event, e) });\n }, this);\n\n this.protocol = this._delegate.protocol;\n this.version = this._delegate.version;\n\n this.parse(this._http.body);\n this.emit('connect', new Base.ConnectEvent());\n },\n\n _open: function() {\n this.__queue.forEach(function(msg) {\n this._delegate[msg[0]].apply(this._delegate, msg[1]);\n }, this);\n this.__queue = [];\n }\n};\n\n['addExtension', 'setHeader', 'start', 'frame', 'text', 'binary', 'ping', 'close'].forEach(function(method) {\n instance[method] = function() {\n if (this._delegate) {\n return this._delegate[method].apply(this._delegate, arguments);\n } else {\n this.__queue.push([method, arguments]);\n return true;\n }\n };\n});\n\nfor (var key in instance)\n Server.prototype[key] = instance[key];\n\nServer.isSecureRequest = function(request) {\n if (request.connection && request.connection.authorized !== undefined) return true;\n if (request.socket && request.socket.secure) return true;\n\n var headers = request.headers;\n if (!headers) return false;\n if (headers['https'] === 'on') return true;\n if (headers['x-forwarded-ssl'] === 'on') return true;\n if (headers['x-forwarded-scheme'] === 'https') return true;\n if (headers['x-forwarded-proto'] === 'https') return true;\n\n return false;\n};\n\nServer.determineUrl = function(request) {\n var scheme = this.isSecureRequest(request) ? 'wss:' : 'ws:';\n return scheme + '//' + request.headers.host + request.url;\n};\n\nServer.http = function(request, options) {\n options = options || {};\n if (options.requireMasking === undefined) options.requireMasking = true;\n\n var headers = request.headers,\n version = headers['sec-websocket-version'],\n key = headers['sec-websocket-key'],\n key1 = headers['sec-websocket-key1'],\n key2 = headers['sec-websocket-key2'],\n url = this.determineUrl(request);\n\n if (version || key)\n return new Hybi(request, url, options);\n else if (key1 || key2)\n return new Draft76(request, url, options);\n else\n return new Draft75(request, url, options);\n};\n\nmodule.exports = Server;\n","'use strict';\n\n// Protocol references:\n//\n// * http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75\n// * http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76\n// * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17\n\nvar Base = require('./driver/base'),\n Client = require('./driver/client'),\n Server = require('./driver/server');\n\nvar Driver = {\n client: function(url, options) {\n options = options || {};\n if (options.masking === undefined) options.masking = true;\n return new Client(url, options);\n },\n\n server: function(options) {\n options = options || {};\n if (options.requireMasking === undefined) options.requireMasking = true;\n return new Server(options);\n },\n\n http: function() {\n return Server.http.apply(Server, arguments);\n },\n\n isSecureRequest: function(request) {\n return Server.isSecureRequest(request);\n },\n\n isWebSocket: function(request) {\n return Base.isWebSocket(request);\n },\n\n validateOptions: function(options, validKeys) {\n Base.validateOptions(options, validKeys);\n }\n};\n\nmodule.exports = Driver;\n","'use strict';\n\nvar Event = function(eventType, options) {\n this.type = eventType;\n for (var key in options)\n this[key] = options[key];\n};\n\nEvent.prototype.initEvent = function(eventType, canBubble, cancelable) {\n this.type = eventType;\n this.bubbles = canBubble;\n this.cancelable = cancelable;\n};\n\nEvent.prototype.stopPropagation = function() {};\nEvent.prototype.preventDefault = function() {};\n\nEvent.CAPTURING_PHASE = 1;\nEvent.AT_TARGET = 2;\nEvent.BUBBLING_PHASE = 3;\n\nmodule.exports = Event;\n","'use strict';\n\nvar Event = require('./event');\n\nvar EventTarget = {\n onopen: null,\n onmessage: null,\n onerror: null,\n onclose: null,\n\n addEventListener: function(eventType, listener, useCapture) {\n this.on(eventType, listener);\n },\n\n removeEventListener: function(eventType, listener, useCapture) {\n this.removeListener(eventType, listener);\n },\n\n dispatchEvent: function(event) {\n event.target = event.currentTarget = this;\n event.eventPhase = Event.AT_TARGET;\n\n if (this['on' + event.type])\n this['on' + event.type](event);\n\n this.emit(event.type, event);\n }\n};\n\nmodule.exports = EventTarget;\n","'use strict';\n\nvar Stream = require('stream').Stream,\n util = require('util'),\n driver = require('websocket-driver'),\n EventTarget = require('./api/event_target'),\n Event = require('./api/event');\n\nvar API = function(options) {\n options = options || {};\n driver.validateOptions(options, ['headers', 'extensions', 'maxLength', 'ping', 'proxy', 'tls', 'ca']);\n\n this.readable = this.writable = true;\n\n var headers = options.headers;\n if (headers) {\n for (var name in headers) this._driver.setHeader(name, headers[name]);\n }\n\n var extensions = options.extensions;\n if (extensions) {\n [].concat(extensions).forEach(this._driver.addExtension, this._driver);\n }\n\n this._ping = options.ping;\n this._pingId = 0;\n this.readyState = API.CONNECTING;\n this.bufferedAmount = 0;\n this.protocol = '';\n this.url = this._driver.url;\n this.version = this._driver.version;\n\n var self = this;\n\n this._driver.on('open', function(e) { self._open() });\n this._driver.on('message', function(e) { self._receiveMessage(e.data) });\n this._driver.on('close', function(e) { self._beginClose(e.reason, e.code) });\n\n this._driver.on('error', function(error) {\n self._emitError(error.message);\n });\n this.on('error', function() {});\n\n this._driver.messages.on('drain', function() {\n self.emit('drain');\n });\n\n if (this._ping)\n this._pingTimer = setInterval(function() {\n self._pingId += 1;\n self.ping(self._pingId.toString());\n }, this._ping * 1000);\n\n this._configureStream();\n\n if (!this._proxy) {\n this._stream.pipe(this._driver.io);\n this._driver.io.pipe(this._stream);\n }\n};\nutil.inherits(API, Stream);\n\nAPI.CONNECTING = 0;\nAPI.OPEN = 1;\nAPI.CLOSING = 2;\nAPI.CLOSED = 3;\n\nAPI.CLOSE_TIMEOUT = 30000;\n\nvar instance = {\n write: function(data) {\n return this.send(data);\n },\n\n end: function(data) {\n if (data !== undefined) this.send(data);\n this.close();\n },\n\n pause: function() {\n return this._driver.messages.pause();\n },\n\n resume: function() {\n return this._driver.messages.resume();\n },\n\n send: function(data) {\n if (this.readyState > API.OPEN) return false;\n if (!(data instanceof Buffer)) data = String(data);\n return this._driver.messages.write(data);\n },\n\n ping: function(message, callback) {\n if (this.readyState > API.OPEN) return false;\n return this._driver.ping(message, callback);\n },\n\n close: function(code, reason) {\n if (code === undefined) code = 1000;\n if (reason === undefined) reason = '';\n\n if (code !== 1000 && (code < 3000 || code > 4999))\n throw new Error(\"Failed to execute 'close' on WebSocket: \" +\n \"The code must be either 1000, or between 3000 and 4999. \" +\n code + \" is neither.\");\n\n if (this.readyState < API.CLOSING) {\n var self = this;\n this._closeTimer = setTimeout(function() {\n self._beginClose('', 1006);\n }, API.CLOSE_TIMEOUT);\n }\n\n if (this.readyState !== API.CLOSED) this.readyState = API.CLOSING;\n\n this._driver.close(reason, code);\n },\n\n _configureStream: function() {\n var self = this;\n\n this._stream.setTimeout(0);\n this._stream.setNoDelay(true);\n\n ['close', 'end'].forEach(function(event) {\n this._stream.on(event, function() { self._finalizeClose() });\n }, this);\n\n this._stream.on('error', function(error) {\n self._emitError('Network error: ' + self.url + ': ' + error.message);\n self._finalizeClose();\n });\n },\n\n _open: function() {\n if (this.readyState !== API.CONNECTING) return;\n\n this.readyState = API.OPEN;\n this.protocol = this._driver.protocol || '';\n\n var event = new Event('open');\n event.initEvent('open', false, false);\n this.dispatchEvent(event);\n },\n\n _receiveMessage: function(data) {\n if (this.readyState > API.OPEN) return false;\n\n if (this.readable) this.emit('data', data);\n\n var event = new Event('message', { data: data });\n event.initEvent('message', false, false);\n this.dispatchEvent(event);\n },\n\n _emitError: function(message) {\n if (this.readyState >= API.CLOSING) return;\n\n var event = new Event('error', { message: message });\n event.initEvent('error', false, false);\n this.dispatchEvent(event);\n },\n\n _beginClose: function(reason, code) {\n if (this.readyState === API.CLOSED) return;\n this.readyState = API.CLOSING;\n this._closeParams = [reason, code];\n\n if (this._stream) {\n this._stream.destroy();\n if (!this._stream.readable) this._finalizeClose();\n }\n },\n\n _finalizeClose: function() {\n if (this.readyState === API.CLOSED) return;\n this.readyState = API.CLOSED;\n\n if (this._closeTimer) clearTimeout(this._closeTimer);\n if (this._pingTimer) clearInterval(this._pingTimer);\n if (this._stream) this._stream.end();\n\n if (this.readable) this.emit('end');\n this.readable = this.writable = false;\n\n var reason = this._closeParams ? this._closeParams[0] : '',\n code = this._closeParams ? this._closeParams[1] : 1006;\n\n var event = new Event('close', { code: code, reason: reason });\n event.initEvent('close', false, false);\n this.dispatchEvent(event);\n }\n};\n\nfor (var method in instance) API.prototype[method] = instance[method];\nfor (var key in EventTarget) API.prototype[key] = EventTarget[key];\n\nmodule.exports = API;\n","'use strict';\n\nvar util = require('util'),\n net = require('net'),\n tls = require('tls'),\n url = require('url'),\n driver = require('websocket-driver'),\n API = require('./api'),\n Event = require('./api/event');\n\nvar DEFAULT_PORTS = { 'http:': 80, 'https:': 443, 'ws:':80, 'wss:': 443 },\n SECURE_PROTOCOLS = ['https:', 'wss:'];\n\nvar Client = function(_url, protocols, options) {\n options = options || {};\n\n this.url = _url;\n this._driver = driver.client(this.url, { maxLength: options.maxLength, protocols: protocols });\n\n ['open', 'error'].forEach(function(event) {\n this._driver.on(event, function() {\n self.headers = self._driver.headers;\n self.statusCode = self._driver.statusCode;\n });\n }, this);\n\n var proxy = options.proxy || {},\n endpoint = url.parse(proxy.origin || this.url),\n port = endpoint.port || DEFAULT_PORTS[endpoint.protocol],\n secure = SECURE_PROTOCOLS.indexOf(endpoint.protocol) >= 0,\n onConnect = function() { self._onConnect() },\n netOptions = options.net || {},\n originTLS = options.tls || {},\n socketTLS = proxy.origin ? (proxy.tls || {}) : originTLS,\n self = this;\n\n netOptions.host = socketTLS.host = endpoint.hostname;\n netOptions.port = socketTLS.port = port;\n\n originTLS.ca = originTLS.ca || options.ca;\n socketTLS.servername = socketTLS.servername || endpoint.hostname;\n\n this._stream = secure\n ? tls.connect(socketTLS, onConnect)\n : net.connect(netOptions, onConnect);\n\n if (proxy.origin) this._configureProxy(proxy, originTLS);\n\n API.call(this, options);\n};\nutil.inherits(Client, API);\n\nClient.prototype._onConnect = function() {\n var worker = this._proxy || this._driver;\n worker.start();\n};\n\nClient.prototype._configureProxy = function(proxy, originTLS) {\n var uri = url.parse(this.url),\n secure = SECURE_PROTOCOLS.indexOf(uri.protocol) >= 0,\n self = this,\n name;\n\n this._proxy = this._driver.proxy(proxy.origin);\n\n if (proxy.headers) {\n for (name in proxy.headers) this._proxy.setHeader(name, proxy.headers[name]);\n }\n\n this._proxy.pipe(this._stream, { end: false });\n this._stream.pipe(this._proxy);\n\n this._proxy.on('connect', function() {\n if (secure) {\n var options = { socket: self._stream, servername: uri.hostname };\n for (name in originTLS) options[name] = originTLS[name];\n self._stream = tls.connect(options);\n self._configureStream();\n }\n self._driver.io.pipe(self._stream);\n self._stream.pipe(self._driver.io);\n self._driver.start();\n });\n\n this._proxy.on('error', function(error) {\n self._driver.emit('error', error);\n });\n};\n\nmodule.exports = Client;\n","'use strict';\n\nvar Stream = require('stream').Stream,\n util = require('util'),\n driver = require('websocket-driver'),\n Headers = require('websocket-driver/lib/websocket/driver/headers'),\n API = require('./websocket/api'),\n EventTarget = require('./websocket/api/event_target'),\n Event = require('./websocket/api/event');\n\nvar EventSource = function(request, response, options) {\n this.writable = true;\n options = options || {};\n\n this._stream = response.socket;\n this._ping = options.ping || this.DEFAULT_PING;\n this._retry = options.retry || this.DEFAULT_RETRY;\n\n var scheme = driver.isSecureRequest(request) ? 'https:' : 'http:';\n this.url = scheme + '//' + request.headers.host + request.url;\n this.lastEventId = request.headers['last-event-id'] || '';\n this.readyState = API.CONNECTING;\n\n var headers = new Headers(),\n self = this;\n\n if (options.headers) {\n for (var key in options.headers) headers.set(key, options.headers[key]);\n }\n\n if (!this._stream || !this._stream.writable) return;\n process.nextTick(function() { self._open() });\n\n this._stream.setTimeout(0);\n this._stream.setNoDelay(true);\n\n var handshake = 'HTTP/1.1 200 OK\\r\\n' +\n 'Content-Type: text/event-stream\\r\\n' +\n 'Cache-Control: no-cache, no-store\\r\\n' +\n 'Connection: close\\r\\n' +\n headers.toString() +\n '\\r\\n' +\n 'retry: ' + Math.floor(this._retry * 1000) + '\\r\\n\\r\\n';\n\n this._write(handshake);\n\n this._stream.on('drain', function() { self.emit('drain') });\n\n if (this._ping)\n this._pingTimer = setInterval(function() { self.ping() }, this._ping * 1000);\n\n ['error', 'end'].forEach(function(event) {\n self._stream.on(event, function() { self.close() });\n });\n};\nutil.inherits(EventSource, Stream);\n\nEventSource.isEventSource = function(request) {\n if (request.method !== 'GET') return false;\n var accept = (request.headers.accept || '').split(/\\s*,\\s*/);\n return accept.indexOf('text/event-stream') >= 0;\n};\n\nvar instance = {\n DEFAULT_PING: 10,\n DEFAULT_RETRY: 5,\n\n _write: function(chunk) {\n if (!this.writable) return false;\n try {\n return this._stream.write(chunk, 'utf8');\n } catch (e) {\n return false;\n }\n },\n\n _open: function() {\n if (this.readyState !== API.CONNECTING) return;\n\n this.readyState = API.OPEN;\n\n var event = new Event('open');\n event.initEvent('open', false, false);\n this.dispatchEvent(event);\n },\n\n write: function(message) {\n return this.send(message);\n },\n\n end: function(message) {\n if (message !== undefined) this.write(message);\n this.close();\n },\n\n send: function(message, options) {\n if (this.readyState > API.OPEN) return false;\n\n message = String(message).replace(/(\\r\\n|\\r|\\n)/g, '$1data: ');\n options = options || {};\n\n var frame = '';\n if (options.event) frame += 'event: ' + options.event + '\\r\\n';\n if (options.id) frame += 'id: ' + options.id + '\\r\\n';\n frame += 'data: ' + message + '\\r\\n\\r\\n';\n\n return this._write(frame);\n },\n\n ping: function() {\n return this._write(':\\r\\n\\r\\n');\n },\n\n close: function() {\n if (this.readyState > API.OPEN) return false;\n\n this.readyState = API.CLOSED;\n this.writable = false;\n if (this._pingTimer) clearInterval(this._pingTimer);\n if (this._stream) this._stream.end();\n\n var event = new Event('close');\n event.initEvent('close', false, false);\n this.dispatchEvent(event);\n\n return true;\n }\n};\n\nfor (var method in instance) EventSource.prototype[method] = instance[method];\nfor (var key in EventTarget) EventSource.prototype[key] = EventTarget[key];\n\nmodule.exports = EventSource;\n","// API references:\n//\n// * https://html.spec.whatwg.org/multipage/comms.html#network\n// * https://dom.spec.whatwg.org/#interface-eventtarget\n// * https://dom.spec.whatwg.org/#interface-event\n\n'use strict';\n\nvar util = require('util'),\n driver = require('websocket-driver'),\n API = require('./websocket/api');\n\nvar WebSocket = function(request, socket, body, protocols, options) {\n options = options || {};\n\n this._stream = socket;\n this._driver = driver.http(request, { maxLength: options.maxLength, protocols: protocols });\n\n var self = this;\n if (!this._stream || !this._stream.writable) return;\n if (!this._stream.readable) return this._stream.end();\n\n var catchup = function() { self._stream.removeListener('data', catchup) };\n this._stream.on('data', catchup);\n\n API.call(this, options);\n\n process.nextTick(function() {\n self._driver.start();\n self._driver.io.write(body);\n });\n};\nutil.inherits(WebSocket, API);\n\nWebSocket.isWebSocket = function(request) {\n return driver.isWebSocket(request);\n};\n\nWebSocket.validateOptions = function(options, validKeys) {\n driver.validateOptions(options, validKeys);\n};\n\nWebSocket.WebSocket = WebSocket;\nWebSocket.Client = require('./websocket/client');\nWebSocket.EventSource = require('./eventsource');\n\nmodule.exports = WebSocket;\n","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);\n });\n }\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event.newVersion, event));\n }\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking) {\n db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));\n }\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event));\n }\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar component = require('@firebase/component');\nvar logger$1 = require('@firebase/logger');\nvar util = require('@firebase/util');\nvar idb = require('idb');\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass PlatformLoggerServiceImpl {\n constructor(container) {\n this.container = container;\n }\n // In initial implementation, this will be called by installations on\n // auth token refresh, and installations will send this string.\n getPlatformInfoString() {\n const providers = this.container.getProviders();\n // Loop through providers and get library/version pairs from any that are\n // version components.\n return providers\n .map(provider => {\n if (isVersionServiceProvider(provider)) {\n const service = provider.getImmediate();\n return `${service.library}/${service.version}`;\n }\n else {\n return null;\n }\n })\n .filter(logString => logString)\n .join(' ');\n }\n}\n/**\n *\n * @param provider check if this provider provides a VersionService\n *\n * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider\n * provides VersionService. The provider is not necessarily a 'app-version'\n * provider.\n */\nfunction isVersionServiceProvider(provider) {\n const component = provider.getComponent();\n return component?.type === \"VERSION\" /* ComponentType.VERSION */;\n}\n\nconst name$q = \"@firebase/app\";\nconst version$1 = \"0.14.0\";\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst logger = new logger$1.Logger('@firebase/app');\n\nconst name$p = \"@firebase/app-compat\";\n\nconst name$o = \"@firebase/analytics-compat\";\n\nconst name$n = \"@firebase/analytics\";\n\nconst name$m = \"@firebase/app-check-compat\";\n\nconst name$l = \"@firebase/app-check\";\n\nconst name$k = \"@firebase/auth\";\n\nconst name$j = \"@firebase/auth-compat\";\n\nconst name$i = \"@firebase/database\";\n\nconst name$h = \"@firebase/data-connect\";\n\nconst name$g = \"@firebase/database-compat\";\n\nconst name$f = \"@firebase/functions\";\n\nconst name$e = \"@firebase/functions-compat\";\n\nconst name$d = \"@firebase/installations\";\n\nconst name$c = \"@firebase/installations-compat\";\n\nconst name$b = \"@firebase/messaging\";\n\nconst name$a = \"@firebase/messaging-compat\";\n\nconst name$9 = \"@firebase/performance\";\n\nconst name$8 = \"@firebase/performance-compat\";\n\nconst name$7 = \"@firebase/remote-config\";\n\nconst name$6 = \"@firebase/remote-config-compat\";\n\nconst name$5 = \"@firebase/storage\";\n\nconst name$4 = \"@firebase/storage-compat\";\n\nconst name$3 = \"@firebase/firestore\";\n\nconst name$2 = \"@firebase/ai\";\n\nconst name$1 = \"@firebase/firestore-compat\";\n\nconst name = \"firebase\";\nconst version = \"12.0.0\";\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The default app name\n *\n * @internal\n */\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\nconst PLATFORM_LOG_STRING = {\n [name$q]: 'fire-core',\n [name$p]: 'fire-core-compat',\n [name$n]: 'fire-analytics',\n [name$o]: 'fire-analytics-compat',\n [name$l]: 'fire-app-check',\n [name$m]: 'fire-app-check-compat',\n [name$k]: 'fire-auth',\n [name$j]: 'fire-auth-compat',\n [name$i]: 'fire-rtdb',\n [name$h]: 'fire-data-connect',\n [name$g]: 'fire-rtdb-compat',\n [name$f]: 'fire-fn',\n [name$e]: 'fire-fn-compat',\n [name$d]: 'fire-iid',\n [name$c]: 'fire-iid-compat',\n [name$b]: 'fire-fcm',\n [name$a]: 'fire-fcm-compat',\n [name$9]: 'fire-perf',\n [name$8]: 'fire-perf-compat',\n [name$7]: 'fire-rc',\n [name$6]: 'fire-rc-compat',\n [name$5]: 'fire-gcs',\n [name$4]: 'fire-gcs-compat',\n [name$3]: 'fire-fst',\n [name$1]: 'fire-fst-compat',\n [name$2]: 'fire-vertex',\n 'fire-js': 'fire-js', // Platform identifier for JS SDK.\n [name]: 'fire-js-all'\n};\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @internal\n */\nconst _apps = new Map();\n/**\n * @internal\n */\nconst _serverApps = new Map();\n/**\n * Registered components.\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst _components = new Map();\n/**\n * @param component - the component being added to this app's container\n *\n * @internal\n */\nfunction _addComponent(app, component) {\n try {\n app.container.addComponent(component);\n }\n catch (e) {\n logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e);\n }\n}\n/**\n *\n * @internal\n */\nfunction _addOrOverwriteComponent(app, component) {\n app.container.addOrOverwriteComponent(component);\n}\n/**\n *\n * @param component - the component to register\n * @returns whether or not the component is registered successfully\n *\n * @internal\n */\nfunction _registerComponent(component) {\n const componentName = component.name;\n if (_components.has(componentName)) {\n logger.debug(`There were multiple attempts to register component ${componentName}.`);\n return false;\n }\n _components.set(componentName, component);\n // add the component to existing app instances\n for (const app of _apps.values()) {\n _addComponent(app, component);\n }\n for (const serverApp of _serverApps.values()) {\n _addComponent(serverApp, component);\n }\n return true;\n}\n/**\n *\n * @param app - FirebaseApp instance\n * @param name - service name\n *\n * @returns the provider for the service with the matching name\n *\n * @internal\n */\nfunction _getProvider(app, name) {\n const heartbeatController = app.container\n .getProvider('heartbeat')\n .getImmediate({ optional: true });\n if (heartbeatController) {\n void heartbeatController.triggerHeartbeat();\n }\n return app.container.getProvider(name);\n}\n/**\n *\n * @param app - FirebaseApp instance\n * @param name - service name\n * @param instanceIdentifier - service instance identifier in case the service supports multiple instances\n *\n * @internal\n */\nfunction _removeServiceInstance(app, name, instanceIdentifier = DEFAULT_ENTRY_NAME) {\n _getProvider(app, name).clearInstance(instanceIdentifier);\n}\n/**\n *\n * @param obj - an object of type FirebaseApp, FirebaseOptions or FirebaseAppSettings.\n *\n * @returns true if the provide object is of type FirebaseApp.\n *\n * @internal\n */\nfunction _isFirebaseApp(obj) {\n return obj.options !== undefined;\n}\n/**\n *\n * @param obj - an object of type FirebaseApp, FirebaseOptions or FirebaseAppSettings.\n *\n * @returns true if the provided object is of type FirebaseServerAppImpl.\n *\n * @internal\n */\nfunction _isFirebaseServerAppSettings(obj) {\n if (_isFirebaseApp(obj)) {\n return false;\n }\n return ('authIdToken' in obj ||\n 'appCheckToken' in obj ||\n 'releaseOnDeref' in obj ||\n 'automaticDataCollectionEnabled' in obj);\n}\n/**\n *\n * @param obj - an object of type FirebaseApp.\n *\n * @returns true if the provided object is of type FirebaseServerAppImpl.\n *\n * @internal\n */\nfunction _isFirebaseServerApp(obj) {\n if (obj === null || obj === undefined) {\n return false;\n }\n return obj.settings !== undefined;\n}\n/**\n * Test only\n *\n * @internal\n */\nfunction _clearComponents() {\n _components.clear();\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst ERRORS = {\n [\"no-app\" /* AppError.NO_APP */]: \"No Firebase App '{$appName}' has been created - \" +\n 'call initializeApp() first',\n [\"bad-app-name\" /* AppError.BAD_APP_NAME */]: \"Illegal App name: '{$appName}'\",\n [\"duplicate-app\" /* AppError.DUPLICATE_APP */]: \"Firebase App named '{$appName}' already exists with different options or config\",\n [\"app-deleted\" /* AppError.APP_DELETED */]: \"Firebase App named '{$appName}' already deleted\",\n [\"server-app-deleted\" /* AppError.SERVER_APP_DELETED */]: 'Firebase Server App has been deleted',\n [\"no-options\" /* AppError.NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.',\n [\"invalid-app-argument\" /* AppError.INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' +\n 'Firebase App instance.',\n [\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.',\n [\"idb-open\" /* AppError.IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',\n [\"idb-get\" /* AppError.IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',\n [\"idb-set\" /* AppError.IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',\n [\"idb-delete\" /* AppError.IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.',\n [\"finalization-registry-not-supported\" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */]: 'FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.',\n [\"invalid-server-app-environment\" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */]: 'FirebaseServerApp is not for use in browser environments.'\n};\nconst ERROR_FACTORY = new util.ErrorFactory('app', 'Firebase', ERRORS);\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass FirebaseAppImpl {\n constructor(options, config, container) {\n this._isDeleted = false;\n this._options = { ...options };\n this._config = { ...config };\n this._name = config.name;\n this._automaticDataCollectionEnabled =\n config.automaticDataCollectionEnabled;\n this._container = container;\n this.container.addComponent(new component.Component('app', () => this, \"PUBLIC\" /* ComponentType.PUBLIC */));\n }\n get automaticDataCollectionEnabled() {\n this.checkDestroyed();\n return this._automaticDataCollectionEnabled;\n }\n set automaticDataCollectionEnabled(val) {\n this.checkDestroyed();\n this._automaticDataCollectionEnabled = val;\n }\n get name() {\n this.checkDestroyed();\n return this._name;\n }\n get options() {\n this.checkDestroyed();\n return this._options;\n }\n get config() {\n this.checkDestroyed();\n return this._config;\n }\n get container() {\n return this._container;\n }\n get isDeleted() {\n return this._isDeleted;\n }\n set isDeleted(val) {\n this._isDeleted = val;\n }\n /**\n * This function will throw an Error if the App has already been deleted -\n * use before performing API actions on the App.\n */\n checkDestroyed() {\n if (this.isDeleted) {\n throw ERROR_FACTORY.create(\"app-deleted\" /* AppError.APP_DELETED */, { appName: this._name });\n }\n }\n}\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Parse the token and check to see if the `exp` claim is in the future.\n// Reports an error to the console if the token or claim could not be parsed, or if `exp` is in\n// the past.\nfunction validateTokenTTL(base64Token, tokenName) {\n const secondPart = util.base64Decode(base64Token.split('.')[1]);\n if (secondPart === null) {\n console.error(`FirebaseServerApp ${tokenName} is invalid: second part could not be parsed.`);\n return;\n }\n const expClaim = JSON.parse(secondPart).exp;\n if (expClaim === undefined) {\n console.error(`FirebaseServerApp ${tokenName} is invalid: expiration claim could not be parsed`);\n return;\n }\n const exp = JSON.parse(secondPart).exp * 1000;\n const now = new Date().getTime();\n const diff = exp - now;\n if (diff <= 0) {\n console.error(`FirebaseServerApp ${tokenName} is invalid: the token has expired.`);\n }\n}\nclass FirebaseServerAppImpl extends FirebaseAppImpl {\n constructor(options, serverConfig, name, container) {\n // Build configuration parameters for the FirebaseAppImpl base class.\n const automaticDataCollectionEnabled = serverConfig.automaticDataCollectionEnabled !== undefined\n ? serverConfig.automaticDataCollectionEnabled\n : true;\n // Create the FirebaseAppSettings object for the FirebaseAppImp constructor.\n const config = {\n name,\n automaticDataCollectionEnabled\n };\n if (options.apiKey !== undefined) {\n // Construct the parent FirebaseAppImp object.\n super(options, config, container);\n }\n else {\n const appImpl = options;\n super(appImpl.options, config, container);\n }\n // Now construct the data for the FirebaseServerAppImpl.\n this._serverConfig = {\n automaticDataCollectionEnabled,\n ...serverConfig\n };\n // Ensure that the current time is within the `authIdtoken` window of validity.\n if (this._serverConfig.authIdToken) {\n validateTokenTTL(this._serverConfig.authIdToken, 'authIdToken');\n }\n // Ensure that the current time is within the `appCheckToken` window of validity.\n if (this._serverConfig.appCheckToken) {\n validateTokenTTL(this._serverConfig.appCheckToken, 'appCheckToken');\n }\n this._finalizationRegistry = null;\n if (typeof FinalizationRegistry !== 'undefined') {\n this._finalizationRegistry = new FinalizationRegistry(() => {\n this.automaticCleanup();\n });\n }\n this._refCount = 0;\n this.incRefCount(this._serverConfig.releaseOnDeref);\n // Do not retain a hard reference to the dref object, otherwise the FinalizationRegistry\n // will never trigger.\n this._serverConfig.releaseOnDeref = undefined;\n serverConfig.releaseOnDeref = undefined;\n registerVersion(name$q, version$1, 'serverapp');\n }\n toJSON() {\n return undefined;\n }\n get refCount() {\n return this._refCount;\n }\n // Increment the reference count of this server app. If an object is provided, register it\n // with the finalization registry.\n incRefCount(obj) {\n if (this.isDeleted) {\n return;\n }\n this._refCount++;\n if (obj !== undefined && this._finalizationRegistry !== null) {\n this._finalizationRegistry.register(obj, this);\n }\n }\n // Decrement the reference count.\n decRefCount() {\n if (this.isDeleted) {\n return 0;\n }\n return --this._refCount;\n }\n // Invoked by the FinalizationRegistry callback to note that this app should go through its\n // reference counts and delete itself if no reference count remain. The coordinating logic that\n // handles this is in deleteApp(...).\n automaticCleanup() {\n void deleteApp(this);\n }\n get settings() {\n this.checkDestroyed();\n return this._serverConfig;\n }\n /**\n * This function will throw an Error if the App has already been deleted -\n * use before performing API actions on the App.\n */\n checkDestroyed() {\n if (this.isDeleted) {\n throw ERROR_FACTORY.create(\"server-app-deleted\" /* AppError.SERVER_APP_DELETED */);\n }\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The current SDK version.\n *\n * @public\n */\nconst SDK_VERSION = version;\nfunction initializeApp(_options, rawConfig = {}) {\n let options = _options;\n if (typeof rawConfig !== 'object') {\n const name = rawConfig;\n rawConfig = { name };\n }\n const config = {\n name: DEFAULT_ENTRY_NAME,\n automaticDataCollectionEnabled: true,\n ...rawConfig\n };\n const name = config.name;\n if (typeof name !== 'string' || !name) {\n throw ERROR_FACTORY.create(\"bad-app-name\" /* AppError.BAD_APP_NAME */, {\n appName: String(name)\n });\n }\n options || (options = util.getDefaultAppConfig());\n if (!options) {\n throw ERROR_FACTORY.create(\"no-options\" /* AppError.NO_OPTIONS */);\n }\n const existingApp = _apps.get(name);\n if (existingApp) {\n // return the existing app if options and config deep equal the ones in the existing app.\n if (util.deepEqual(options, existingApp.options) &&\n util.deepEqual(config, existingApp.config)) {\n return existingApp;\n }\n else {\n throw ERROR_FACTORY.create(\"duplicate-app\" /* AppError.DUPLICATE_APP */, { appName: name });\n }\n }\n const container = new component.ComponentContainer(name);\n for (const component of _components.values()) {\n container.addComponent(component);\n }\n const newApp = new FirebaseAppImpl(options, config, container);\n _apps.set(name, newApp);\n return newApp;\n}\nfunction initializeServerApp(_options, _serverAppConfig = {}) {\n if (util.isBrowser() && !util.isWebWorker()) {\n // FirebaseServerApp isn't designed to be run in browsers.\n throw ERROR_FACTORY.create(\"invalid-server-app-environment\" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */);\n }\n let firebaseOptions;\n let serverAppSettings = _serverAppConfig || {};\n if (_options) {\n if (_isFirebaseApp(_options)) {\n firebaseOptions = _options.options;\n }\n else if (_isFirebaseServerAppSettings(_options)) {\n serverAppSettings = _options;\n }\n else {\n firebaseOptions = _options;\n }\n }\n if (serverAppSettings.automaticDataCollectionEnabled === undefined) {\n serverAppSettings.automaticDataCollectionEnabled = true;\n }\n firebaseOptions || (firebaseOptions = util.getDefaultAppConfig());\n if (!firebaseOptions) {\n throw ERROR_FACTORY.create(\"no-options\" /* AppError.NO_OPTIONS */);\n }\n // Build an app name based on a hash of the configuration options.\n const nameObj = {\n ...serverAppSettings,\n ...firebaseOptions\n };\n // However, Do not mangle the name based on releaseOnDeref, since it will vary between the\n // construction of FirebaseServerApp instances. For example, if the object is the request headers.\n if (nameObj.releaseOnDeref !== undefined) {\n delete nameObj.releaseOnDeref;\n }\n const hashCode = (s) => {\n return [...s].reduce((hash, c) => (Math.imul(31, hash) + c.charCodeAt(0)) | 0, 0);\n };\n if (serverAppSettings.releaseOnDeref !== undefined) {\n if (typeof FinalizationRegistry === 'undefined') {\n throw ERROR_FACTORY.create(\"finalization-registry-not-supported\" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */, {});\n }\n }\n const nameString = '' + hashCode(JSON.stringify(nameObj));\n const existingApp = _serverApps.get(nameString);\n if (existingApp) {\n existingApp.incRefCount(serverAppSettings.releaseOnDeref);\n return existingApp;\n }\n const container = new component.ComponentContainer(nameString);\n for (const component of _components.values()) {\n container.addComponent(component);\n }\n const newApp = new FirebaseServerAppImpl(firebaseOptions, serverAppSettings, nameString, container);\n _serverApps.set(nameString, newApp);\n return newApp;\n}\n/**\n * Retrieves a {@link @firebase/app#FirebaseApp} instance.\n *\n * When called with no arguments, the default app is returned. When an app name\n * is provided, the app corresponding to that name is returned.\n *\n * An exception is thrown if the app being retrieved has not yet been\n * initialized.\n *\n * @example\n * ```javascript\n * // Return the default app\n * const app = getApp();\n * ```\n *\n * @example\n * ```javascript\n * // Return a named app\n * const otherApp = getApp(\"otherApp\");\n * ```\n *\n * @param name - Optional name of the app to return. If no name is\n * provided, the default is `\"[DEFAULT]\"`.\n *\n * @returns The app corresponding to the provided app name.\n * If no app name is provided, the default app is returned.\n *\n * @public\n */\nfunction getApp(name = DEFAULT_ENTRY_NAME) {\n const app = _apps.get(name);\n if (!app && name === DEFAULT_ENTRY_NAME && util.getDefaultAppConfig()) {\n return initializeApp();\n }\n if (!app) {\n throw ERROR_FACTORY.create(\"no-app\" /* AppError.NO_APP */, { appName: name });\n }\n return app;\n}\n/**\n * A (read-only) array of all initialized apps.\n * @public\n */\nfunction getApps() {\n return Array.from(_apps.values());\n}\n/**\n * Renders this app unusable and frees the resources of all associated\n * services.\n *\n * @example\n * ```javascript\n * deleteApp(app)\n * .then(function() {\n * console.log(\"App deleted successfully\");\n * })\n * .catch(function(error) {\n * console.log(\"Error deleting app:\", error);\n * });\n * ```\n *\n * @public\n */\nasync function deleteApp(app) {\n let cleanupProviders = false;\n const name = app.name;\n if (_apps.has(name)) {\n cleanupProviders = true;\n _apps.delete(name);\n }\n else if (_serverApps.has(name)) {\n const firebaseServerApp = app;\n if (firebaseServerApp.decRefCount() <= 0) {\n _serverApps.delete(name);\n cleanupProviders = true;\n }\n }\n if (cleanupProviders) {\n await Promise.all(app.container\n .getProviders()\n .map(provider => provider.delete()));\n app.isDeleted = true;\n }\n}\n/**\n * Registers a library's name and version for platform logging purposes.\n * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)\n * @param version - Current version of that library.\n * @param variant - Bundle variant, e.g., node, rn, etc.\n *\n * @public\n */\nfunction registerVersion(libraryKeyOrName, version, variant) {\n // TODO: We can use this check to whitelist strings when/if we set up\n // a good whitelist system.\n let library = PLATFORM_LOG_STRING[libraryKeyOrName] ?? libraryKeyOrName;\n if (variant) {\n library += `-${variant}`;\n }\n const libraryMismatch = library.match(/\\s|\\//);\n const versionMismatch = version.match(/\\s|\\//);\n if (libraryMismatch || versionMismatch) {\n const warning = [\n `Unable to register library \"${library}\" with version \"${version}\":`\n ];\n if (libraryMismatch) {\n warning.push(`library name \"${library}\" contains illegal characters (whitespace or \"/\")`);\n }\n if (libraryMismatch && versionMismatch) {\n warning.push('and');\n }\n if (versionMismatch) {\n warning.push(`version name \"${version}\" contains illegal characters (whitespace or \"/\")`);\n }\n logger.warn(warning.join(' '));\n return;\n }\n _registerComponent(new component.Component(`${library}-version`, () => ({ library, version }), \"VERSION\" /* ComponentType.VERSION */));\n}\n/**\n * Sets log handler for all Firebase SDKs.\n * @param logCallback - An optional custom log handler that executes user code whenever\n * the Firebase SDK makes a logging call.\n *\n * @public\n */\nfunction onLog(logCallback, options) {\n if (logCallback !== null && typeof logCallback !== 'function') {\n throw ERROR_FACTORY.create(\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */);\n }\n logger$1.setUserLogHandler(logCallback, options);\n}\n/**\n * Sets log level for all Firebase SDKs.\n *\n * All of the log types above the current log level are captured (i.e. if\n * you set the log level to `info`, errors are logged, but `debug` and\n * `verbose` logs are not).\n *\n * @public\n */\nfunction setLogLevel(logLevel) {\n logger$1.setLogLevel(logLevel);\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst DB_NAME = 'firebase-heartbeat-database';\nconst DB_VERSION = 1;\nconst STORE_NAME = 'firebase-heartbeat-store';\nlet dbPromise = null;\nfunction getDbPromise() {\n if (!dbPromise) {\n dbPromise = idb.openDB(DB_NAME, DB_VERSION, {\n upgrade: (db, oldVersion) => {\n // We don't use 'break' in this switch statement, the fall-through\n // behavior is what we want, because if there are multiple versions between\n // the old version and the current version, we want ALL the migrations\n // that correspond to those versions to run, not only the last one.\n // eslint-disable-next-line default-case\n switch (oldVersion) {\n case 0:\n try {\n db.createObjectStore(STORE_NAME);\n }\n catch (e) {\n // Safari/iOS browsers throw occasional exceptions on\n // db.createObjectStore() that may be a bug. Avoid blocking\n // the rest of the app functionality.\n console.warn(e);\n }\n }\n }\n }).catch(e => {\n throw ERROR_FACTORY.create(\"idb-open\" /* AppError.IDB_OPEN */, {\n originalErrorMessage: e.message\n });\n });\n }\n return dbPromise;\n}\nasync function readHeartbeatsFromIndexedDB(app) {\n try {\n const db = await getDbPromise();\n const tx = db.transaction(STORE_NAME);\n const result = await tx.objectStore(STORE_NAME).get(computeKey(app));\n // We already have the value but tx.done can throw,\n // so we need to await it here to catch errors\n await tx.done;\n return result;\n }\n catch (e) {\n if (e instanceof util.FirebaseError) {\n logger.warn(e.message);\n }\n else {\n const idbGetError = ERROR_FACTORY.create(\"idb-get\" /* AppError.IDB_GET */, {\n originalErrorMessage: e?.message\n });\n logger.warn(idbGetError.message);\n }\n }\n}\nasync function writeHeartbeatsToIndexedDB(app, heartbeatObject) {\n try {\n const db = await getDbPromise();\n const tx = db.transaction(STORE_NAME, 'readwrite');\n const objectStore = tx.objectStore(STORE_NAME);\n await objectStore.put(heartbeatObject, computeKey(app));\n await tx.done;\n }\n catch (e) {\n if (e instanceof util.FirebaseError) {\n logger.warn(e.message);\n }\n else {\n const idbGetError = ERROR_FACTORY.create(\"idb-set\" /* AppError.IDB_WRITE */, {\n originalErrorMessage: e?.message\n });\n logger.warn(idbGetError.message);\n }\n }\n}\nfunction computeKey(app) {\n return `${app.name}!${app.options.appId}`;\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst MAX_HEADER_BYTES = 1024;\nconst MAX_NUM_STORED_HEARTBEATS = 30;\nclass HeartbeatServiceImpl {\n constructor(container) {\n this.container = container;\n /**\n * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate\n * the header string.\n * Stores one record per date. This will be consolidated into the standard\n * format of one record per user agent string before being sent as a header.\n * Populated from indexedDB when the controller is instantiated and should\n * be kept in sync with indexedDB.\n * Leave public for easier testing.\n */\n this._heartbeatsCache = null;\n const app = this.container.getProvider('app').getImmediate();\n this._storage = new HeartbeatStorageImpl(app);\n this._heartbeatsCachePromise = this._storage.read().then(result => {\n this._heartbeatsCache = result;\n return result;\n });\n }\n /**\n * Called to report a heartbeat. The function will generate\n * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it\n * to IndexedDB.\n * Note that we only store one heartbeat per day. So if a heartbeat for today is\n * already logged, subsequent calls to this function in the same day will be ignored.\n */\n async triggerHeartbeat() {\n try {\n const platformLogger = this.container\n .getProvider('platform-logger')\n .getImmediate();\n // This is the \"Firebase user agent\" string from the platform logger\n // service, not the browser user agent.\n const agent = platformLogger.getPlatformInfoString();\n const date = getUTCDateString();\n if (this._heartbeatsCache?.heartbeats == null) {\n this._heartbeatsCache = await this._heartbeatsCachePromise;\n // If we failed to construct a heartbeats cache, then return immediately.\n if (this._heartbeatsCache?.heartbeats == null) {\n return;\n }\n }\n // Do not store a heartbeat if one is already stored for this day\n // or if a header has already been sent today.\n if (this._heartbeatsCache.lastSentHeartbeatDate === date ||\n this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) {\n return;\n }\n else {\n // There is no entry for this date. Create one.\n this._heartbeatsCache.heartbeats.push({ date, agent });\n // If the number of stored heartbeats exceeds the maximum number of stored heartbeats, remove the heartbeat with the earliest date.\n // Since this is executed each time a heartbeat is pushed, the limit can only be exceeded by one, so only one needs to be removed.\n if (this._heartbeatsCache.heartbeats.length > MAX_NUM_STORED_HEARTBEATS) {\n const earliestHeartbeatIdx = getEarliestHeartbeatIdx(this._heartbeatsCache.heartbeats);\n this._heartbeatsCache.heartbeats.splice(earliestHeartbeatIdx, 1);\n }\n }\n return this._storage.overwrite(this._heartbeatsCache);\n }\n catch (e) {\n logger.warn(e);\n }\n }\n /**\n * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.\n * It also clears all heartbeats from memory as well as in IndexedDB.\n *\n * NOTE: Consuming product SDKs should not send the header if this method\n * returns an empty string.\n */\n async getHeartbeatsHeader() {\n try {\n if (this._heartbeatsCache === null) {\n await this._heartbeatsCachePromise;\n }\n // If it's still null or the array is empty, there is no data to send.\n if (this._heartbeatsCache?.heartbeats == null ||\n this._heartbeatsCache.heartbeats.length === 0) {\n return '';\n }\n const date = getUTCDateString();\n // Extract as many heartbeats from the cache as will fit under the size limit.\n const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);\n const headerString = util.base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));\n // Store last sent date to prevent another being logged/sent for the same day.\n this._heartbeatsCache.lastSentHeartbeatDate = date;\n if (unsentEntries.length > 0) {\n // Store any unsent entries if they exist.\n this._heartbeatsCache.heartbeats = unsentEntries;\n // This seems more likely than emptying the array (below) to lead to some odd state\n // since the cache isn't empty and this will be called again on the next request,\n // and is probably safest if we await it.\n await this._storage.overwrite(this._heartbeatsCache);\n }\n else {\n this._heartbeatsCache.heartbeats = [];\n // Do not wait for this, to reduce latency.\n void this._storage.overwrite(this._heartbeatsCache);\n }\n return headerString;\n }\n catch (e) {\n logger.warn(e);\n return '';\n }\n }\n}\nfunction getUTCDateString() {\n const today = new Date();\n // Returns date format 'YYYY-MM-DD'\n return today.toISOString().substring(0, 10);\n}\nfunction extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {\n // Heartbeats grouped by user agent in the standard format to be sent in\n // the header.\n const heartbeatsToSend = [];\n // Single date format heartbeats that are not sent.\n let unsentEntries = heartbeatsCache.slice();\n for (const singleDateHeartbeat of heartbeatsCache) {\n // Look for an existing entry with the same user agent.\n const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent);\n if (!heartbeatEntry) {\n // If no entry for this user agent exists, create one.\n heartbeatsToSend.push({\n agent: singleDateHeartbeat.agent,\n dates: [singleDateHeartbeat.date]\n });\n if (countBytes(heartbeatsToSend) > maxSize) {\n // If the header would exceed max size, remove the added heartbeat\n // entry and stop adding to the header.\n heartbeatsToSend.pop();\n break;\n }\n }\n else {\n heartbeatEntry.dates.push(singleDateHeartbeat.date);\n // If the header would exceed max size, remove the added date\n // and stop adding to the header.\n if (countBytes(heartbeatsToSend) > maxSize) {\n heartbeatEntry.dates.pop();\n break;\n }\n }\n // Pop unsent entry from queue. (Skipped if adding the entry exceeded\n // quota and the loop breaks early.)\n unsentEntries = unsentEntries.slice(1);\n }\n return {\n heartbeatsToSend,\n unsentEntries\n };\n}\nclass HeartbeatStorageImpl {\n constructor(app) {\n this.app = app;\n this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\n }\n async runIndexedDBEnvironmentCheck() {\n if (!util.isIndexedDBAvailable()) {\n return false;\n }\n else {\n return util.validateIndexedDBOpenable()\n .then(() => true)\n .catch(() => false);\n }\n }\n /**\n * Read all heartbeats.\n */\n async read() {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return { heartbeats: [] };\n }\n else {\n const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);\n if (idbHeartbeatObject?.heartbeats) {\n return idbHeartbeatObject;\n }\n else {\n return { heartbeats: [] };\n }\n }\n }\n // overwrite the storage with the provided heartbeats\n async overwrite(heartbeatsObject) {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return;\n }\n else {\n const existingHeartbeatsObject = await this.read();\n return writeHeartbeatsToIndexedDB(this.app, {\n lastSentHeartbeatDate: heartbeatsObject.lastSentHeartbeatDate ??\n existingHeartbeatsObject.lastSentHeartbeatDate,\n heartbeats: heartbeatsObject.heartbeats\n });\n }\n }\n // add heartbeats\n async add(heartbeatsObject) {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return;\n }\n else {\n const existingHeartbeatsObject = await this.read();\n return writeHeartbeatsToIndexedDB(this.app, {\n lastSentHeartbeatDate: heartbeatsObject.lastSentHeartbeatDate ??\n existingHeartbeatsObject.lastSentHeartbeatDate,\n heartbeats: [\n ...existingHeartbeatsObject.heartbeats,\n ...heartbeatsObject.heartbeats\n ]\n });\n }\n }\n}\n/**\n * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped\n * in a platform logging header JSON object, stringified, and converted\n * to base 64.\n */\nfunction countBytes(heartbeatsCache) {\n // base64 has a restricted set of characters, all of which should be 1 byte.\n return util.base64urlEncodeWithoutPadding(\n // heartbeatsCache wrapper properties\n JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;\n}\n/**\n * Returns the index of the heartbeat with the earliest date.\n * If the heartbeats array is empty, -1 is returned.\n */\nfunction getEarliestHeartbeatIdx(heartbeats) {\n if (heartbeats.length === 0) {\n return -1;\n }\n let earliestHeartbeatIdx = 0;\n let earliestHeartbeatDate = heartbeats[0].date;\n for (let i = 1; i < heartbeats.length; i++) {\n if (heartbeats[i].date < earliestHeartbeatDate) {\n earliestHeartbeatDate = heartbeats[i].date;\n earliestHeartbeatIdx = i;\n }\n }\n return earliestHeartbeatIdx;\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction registerCoreComponents(variant) {\n _registerComponent(new component.Component('platform-logger', container => new PlatformLoggerServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\n _registerComponent(new component.Component('heartbeat', container => new HeartbeatServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\n // Register `app` package.\n registerVersion(name$q, version$1, variant);\n // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation\n registerVersion(name$q, version$1, 'cjs2020');\n // Register platform SDK identifier (no version).\n registerVersion('fire-js', '');\n}\n\n/**\n * Firebase App\n *\n * @remarks This package coordinates the communication between the different Firebase components\n * @packageDocumentation\n */\nregisterCoreComponents('node');\n\nObject.defineProperty(exports, 'FirebaseError', {\n enumerable: true,\n get: function () { return util.FirebaseError; }\n});\nexports.SDK_VERSION = SDK_VERSION;\nexports._DEFAULT_ENTRY_NAME = DEFAULT_ENTRY_NAME;\nexports._addComponent = _addComponent;\nexports._addOrOverwriteComponent = _addOrOverwriteComponent;\nexports._apps = _apps;\nexports._clearComponents = _clearComponents;\nexports._components = _components;\nexports._getProvider = _getProvider;\nexports._isFirebaseApp = _isFirebaseApp;\nexports._isFirebaseServerApp = _isFirebaseServerApp;\nexports._isFirebaseServerAppSettings = _isFirebaseServerAppSettings;\nexports._registerComponent = _registerComponent;\nexports._removeServiceInstance = _removeServiceInstance;\nexports._serverApps = _serverApps;\nexports.deleteApp = deleteApp;\nexports.getApp = getApp;\nexports.getApps = getApps;\nexports.initializeApp = initializeApp;\nexports.initializeServerApp = initializeServerApp;\nexports.onLog = onLog;\nexports.registerVersion = registerVersion;\nexports.setLogLevel = setLogLevel;\n//# sourceMappingURL=index.cjs.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar Websocket = require('faye-websocket');\nvar util = require('@firebase/util');\nvar logger$1 = require('@firebase/logger');\nvar app = require('@firebase/app');\nvar component = require('@firebase/component');\n\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\n\nvar Websocket__default = /*#__PURE__*/_interopDefaultLegacy(Websocket);\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst PROTOCOL_VERSION = '5';\nconst VERSION_PARAM = 'v';\nconst TRANSPORT_SESSION_PARAM = 's';\nconst REFERER_PARAM = 'r';\nconst FORGE_REF = 'f';\n// Matches console.firebase.google.com, firebase-console-*.corp.google.com and\n// firebase.corp.google.com\nconst FORGE_DOMAIN_RE = /(console\\.firebase|firebase-console-\\w+\\.corp|firebase\\.corp)\\.google\\.com/;\nconst LAST_SESSION_PARAM = 'ls';\nconst APPLICATION_ID_PARAM = 'p';\nconst APP_CHECK_TOKEN_PARAM = 'ac';\nconst WEBSOCKET = 'websocket';\nconst LONG_POLLING = 'long_polling';\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Wraps a DOM Storage object and:\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\n *\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\n * and one for localStorage.\n *\n */\nclass DOMStorageWrapper {\n /**\n * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)\n */\n constructor(domStorage_) {\n this.domStorage_ = domStorage_;\n // Use a prefix to avoid collisions with other stuff saved by the app.\n this.prefix_ = 'firebase:';\n }\n /**\n * @param key - The key to save the value under\n * @param value - The value being stored, or null to remove the key.\n */\n set(key, value) {\n if (value == null) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n else {\n this.domStorage_.setItem(this.prefixedName_(key), util.stringify(value));\n }\n }\n /**\n * @returns The value that was stored under this key, or null\n */\n get(key) {\n const storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n if (storedVal == null) {\n return null;\n }\n else {\n return util.jsonEval(storedVal);\n }\n }\n remove(key) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n prefixedName_(name) {\n return this.prefix_ + name;\n }\n toString() {\n return this.domStorage_.toString();\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\n * (TODO: create interface for both to implement).\n */\nclass MemoryStorage {\n constructor() {\n this.cache_ = {};\n this.isInMemoryStorage = true;\n }\n set(key, value) {\n if (value == null) {\n delete this.cache_[key];\n }\n else {\n this.cache_[key] = value;\n }\n }\n get(key) {\n if (util.contains(this.cache_, key)) {\n return this.cache_[key];\n }\n return null;\n }\n remove(key) {\n delete this.cache_[key];\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\n * to reflect this type\n *\n * @param domStorageName - Name of the underlying storage object\n * (e.g. 'localStorage' or 'sessionStorage').\n * @returns Turning off type information until a common interface is defined.\n */\nconst createStoragefor = function (domStorageName) {\n try {\n // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\n // so it must be inside the try/catch.\n if (typeof window !== 'undefined' &&\n typeof window[domStorageName] !== 'undefined') {\n // Need to test cache. Just because it's here doesn't mean it works\n const domStorage = window[domStorageName];\n domStorage.setItem('firebase:sentinel', 'cache');\n domStorage.removeItem('firebase:sentinel');\n return new DOMStorageWrapper(domStorage);\n }\n }\n catch (e) { }\n // Failed to create wrapper. Just return in-memory storage.\n // TODO: log?\n return new MemoryStorage();\n};\n/** A storage object that lasts across sessions */\nconst PersistentStorage = createStoragefor('localStorage');\n/** A storage object that only lasts one session */\nconst SessionStorage = createStoragefor('sessionStorage');\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst logClient = new logger$1.Logger('@firebase/database');\n/**\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\n */\nconst LUIDGenerator = (function () {\n let id = 1;\n return function () {\n return id++;\n };\n})();\n/**\n * Sha1 hash of the input string\n * @param str - The string to hash\n * @returns {!string} The resulting hash\n */\nconst sha1 = function (str) {\n const utf8Bytes = util.stringToByteArray(str);\n const sha1 = new util.Sha1();\n sha1.update(utf8Bytes);\n const sha1Bytes = sha1.digest();\n return util.base64.encodeByteArray(sha1Bytes);\n};\nconst buildLogMessage_ = function (...varArgs) {\n let message = '';\n for (let i = 0; i < varArgs.length; i++) {\n const arg = varArgs[i];\n if (Array.isArray(arg) ||\n (arg &&\n typeof arg === 'object' &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof arg.length === 'number')) {\n message += buildLogMessage_.apply(null, arg);\n }\n else if (typeof arg === 'object') {\n message += util.stringify(arg);\n }\n else {\n message += arg;\n }\n message += ' ';\n }\n return message;\n};\n/**\n * Use this for all debug messages in Firebase.\n */\nlet logger = null;\n/**\n * Flag to check for log availability on first log message\n */\nlet firstLog_ = true;\n/**\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\n * @param logger_ - A flag to turn on logging, or a custom logger\n * @param persistent - Whether or not to persist logging settings across refreshes\n */\nconst enableLogging$1 = function (logger_, persistent) {\n util.assert(!persistent || logger_ === true || logger_ === false, \"Can't turn on custom loggers persistently.\");\n if (logger_ === true) {\n logClient.logLevel = logger$1.LogLevel.VERBOSE;\n logger = logClient.log.bind(logClient);\n if (persistent) {\n SessionStorage.set('logging_enabled', true);\n }\n }\n else if (typeof logger_ === 'function') {\n logger = logger_;\n }\n else {\n logger = null;\n SessionStorage.remove('logging_enabled');\n }\n};\nconst log = function (...varArgs) {\n if (firstLog_ === true) {\n firstLog_ = false;\n if (logger === null && SessionStorage.get('logging_enabled') === true) {\n enableLogging$1(true);\n }\n }\n if (logger) {\n const message = buildLogMessage_.apply(null, varArgs);\n logger(message);\n }\n};\nconst logWrapper = function (prefix) {\n return function (...varArgs) {\n log(prefix, ...varArgs);\n };\n};\nconst error = function (...varArgs) {\n const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);\n logClient.error(message);\n};\nconst fatal = function (...varArgs) {\n const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;\n logClient.error(message);\n throw new Error(message);\n};\nconst warn = function (...varArgs) {\n const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);\n logClient.warn(message);\n};\n/**\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\n * does not use https.\n */\nconst warnIfPageIsSecure = function () {\n // Be very careful accessing browser globals. Who knows what may or may not exist.\n if (typeof window !== 'undefined' &&\n window.location &&\n window.location.protocol &&\n window.location.protocol.indexOf('https:') !== -1) {\n warn('Insecure Firebase access from a secure page. ' +\n 'Please use https in calls to new Firebase().');\n }\n};\n/**\n * Returns true if data is NaN, or +/- Infinity.\n */\nconst isInvalidJSONNumber = function (data) {\n return (typeof data === 'number' &&\n (data !== data || // NaN\n data === Number.POSITIVE_INFINITY ||\n data === Number.NEGATIVE_INFINITY));\n};\nconst executeWhenDOMReady = function (fn) {\n if (util.isNodeSdk() || document.readyState === 'complete') {\n fn();\n }\n else {\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\n // fire before onload), but fall back to onload.\n let called = false;\n const wrappedFn = function () {\n if (!document.body) {\n setTimeout(wrappedFn, Math.floor(10));\n return;\n }\n if (!called) {\n called = true;\n fn();\n }\n };\n if (document.addEventListener) {\n document.addEventListener('DOMContentLoaded', wrappedFn, false);\n // fallback to onload.\n window.addEventListener('load', wrappedFn, false);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }\n else if (document.attachEvent) {\n // IE.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n document.attachEvent('onreadystatechange', () => {\n if (document.readyState === 'complete') {\n wrappedFn();\n }\n });\n // fallback to onload.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n window.attachEvent('onload', wrappedFn);\n // jQuery has an extra hack for IE that we could employ (based on\n // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\n // I'm hoping we don't need it.\n }\n }\n};\n/**\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\n */\nconst MIN_NAME = '[MIN_NAME]';\n/**\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\n */\nconst MAX_NAME = '[MAX_NAME]';\n/**\n * Compares valid Firebase key names, plus min and max name\n */\nconst nameCompare = function (a, b) {\n if (a === b) {\n return 0;\n }\n else if (a === MIN_NAME || b === MAX_NAME) {\n return -1;\n }\n else if (b === MIN_NAME || a === MAX_NAME) {\n return 1;\n }\n else {\n const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);\n if (aAsInt !== null) {\n if (bAsInt !== null) {\n return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;\n }\n else {\n return -1;\n }\n }\n else if (bAsInt !== null) {\n return 1;\n }\n else {\n return a < b ? -1 : 1;\n }\n }\n};\n/**\n * @returns {!number} comparison result.\n */\nconst stringCompare = function (a, b) {\n if (a === b) {\n return 0;\n }\n else if (a < b) {\n return -1;\n }\n else {\n return 1;\n }\n};\nconst requireKey = function (key, obj) {\n if (obj && key in obj) {\n return obj[key];\n }\n else {\n throw new Error('Missing required key (' + key + ') in object: ' + util.stringify(obj));\n }\n};\nconst ObjectToUniqueKey = function (obj) {\n if (typeof obj !== 'object' || obj === null) {\n return util.stringify(obj);\n }\n const keys = [];\n // eslint-disable-next-line guard-for-in\n for (const k in obj) {\n keys.push(k);\n }\n // Export as json, but with the keys sorted.\n keys.sort();\n let key = '{';\n for (let i = 0; i < keys.length; i++) {\n if (i !== 0) {\n key += ',';\n }\n key += util.stringify(keys[i]);\n key += ':';\n key += ObjectToUniqueKey(obj[keys[i]]);\n }\n key += '}';\n return key;\n};\n/**\n * Splits a string into a number of smaller segments of maximum size\n * @param str - The string\n * @param segsize - The maximum number of chars in the string.\n * @returns The string, split into appropriately-sized chunks\n */\nconst splitStringBySize = function (str, segsize) {\n const len = str.length;\n if (len <= segsize) {\n return [str];\n }\n const dataSegs = [];\n for (let c = 0; c < len; c += segsize) {\n if (c + segsize > len) {\n dataSegs.push(str.substring(c, len));\n }\n else {\n dataSegs.push(str.substring(c, c + segsize));\n }\n }\n return dataSegs;\n};\n/**\n * Apply a function to each (key, value) pair in an object or\n * apply a function to each (index, value) pair in an array\n * @param obj - The object or array to iterate over\n * @param fn - The function to apply\n */\nfunction each(obj, fn) {\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n fn(key, obj[key]);\n }\n }\n}\n/**\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\n * I made one modification at the end and removed the NaN / Infinity\n * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.\n * @param v - A double\n *\n */\nconst doubleToIEEE754String = function (v) {\n util.assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\n const ebits = 11, fbits = 52;\n const bias = (1 << (ebits - 1)) - 1;\n let s, e, f, ln, i;\n // Compute sign, exponent, fraction\n // Skip NaN / Infinity handling --MJL.\n if (v === 0) {\n e = 0;\n f = 0;\n s = 1 / v === -Infinity ? 1 : 0;\n }\n else {\n s = v < 0;\n v = Math.abs(v);\n if (v >= Math.pow(2, 1 - bias)) {\n // Normalized\n ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\n e = ln + bias;\n f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\n }\n else {\n // Denormalized\n e = 0;\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\n }\n }\n // Pack sign, exponent, fraction\n const bits = [];\n for (i = fbits; i; i -= 1) {\n bits.push(f % 2 ? 1 : 0);\n f = Math.floor(f / 2);\n }\n for (i = ebits; i; i -= 1) {\n bits.push(e % 2 ? 1 : 0);\n e = Math.floor(e / 2);\n }\n bits.push(s ? 1 : 0);\n bits.reverse();\n const str = bits.join('');\n // Return the data as a hex string. --MJL\n let hexByteString = '';\n for (i = 0; i < 64; i += 8) {\n let hexByte = parseInt(str.substr(i, 8), 2).toString(16);\n if (hexByte.length === 1) {\n hexByte = '0' + hexByte;\n }\n hexByteString = hexByteString + hexByte;\n }\n return hexByteString.toLowerCase();\n};\n/**\n * Used to detect if we're in a Chrome content script (which executes in an\n * isolated environment where long-polling doesn't work).\n */\nconst isChromeExtensionContentScript = function () {\n return !!(typeof window === 'object' &&\n window['chrome'] &&\n window['chrome']['extension'] &&\n !/^chrome/.test(window.location.href));\n};\n/**\n * Used to detect if we're in a Windows 8 Store app.\n */\nconst isWindowsStoreApp = function () {\n // Check for the presence of a couple WinRT globals\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\n};\n/**\n * Converts a server error code to a JavaScript Error\n */\nfunction errorForServerCode(code, query) {\n let reason = 'Unknown Error';\n if (code === 'too_big') {\n reason =\n 'The data requested exceeds the maximum size ' +\n 'that can be accessed with a single request.';\n }\n else if (code === 'permission_denied') {\n reason = \"Client doesn't have permission to access the desired data.\";\n }\n else if (code === 'unavailable') {\n reason = 'The service is unavailable';\n }\n const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n error.code = code.toUpperCase();\n return error;\n}\n/**\n * Used to test for integer-looking strings\n */\nconst INTEGER_REGEXP_ = new RegExp('^-?(0*)\\\\d{1,10}$');\n/**\n * For use in keys, the minimum possible 32-bit integer.\n */\nconst INTEGER_32_MIN = -2147483648;\n/**\n * For use in keys, the maximum possible 32-bit integer.\n */\nconst INTEGER_32_MAX = 2147483647;\n/**\n * If the string contains a 32-bit integer, return it. Else return null.\n */\nconst tryParseInt = function (str) {\n if (INTEGER_REGEXP_.test(str)) {\n const intVal = Number(str);\n if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {\n return intVal;\n }\n }\n return null;\n};\n/**\n * Helper to run some code but catch any exceptions and re-throw them later.\n * Useful for preventing user callbacks from breaking internal code.\n *\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\n * convenient (we don't have to try to figure out when is a safe point to\n * re-throw it), and the behavior seems reasonable:\n *\n * * If you aren't pausing on exceptions, you get an error in the console with\n * the correct stack trace.\n * * If you're pausing on all exceptions, the debugger will pause on your\n * exception and then again when we rethrow it.\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\n * on us re-throwing it.\n *\n * @param fn - The code to guard.\n */\nconst exceptionGuard = function (fn) {\n try {\n fn();\n }\n catch (e) {\n // Re-throw exception when it's safe.\n setTimeout(() => {\n // It used to be that \"throw e\" would result in a good console error with\n // relevant context, but as of Chrome 39, you just get the firebase.js\n // file/line number where we re-throw it, which is useless. So we log\n // e.stack explicitly.\n const stack = e.stack || '';\n warn('Exception was thrown by user callback.', stack);\n throw e;\n }, Math.floor(0));\n }\n};\n/**\n * @returns {boolean} true if we think we're currently being crawled.\n */\nconst beingCrawled = function () {\n const userAgent = (typeof window === 'object' &&\n window['navigator'] &&\n window['navigator']['userAgent']) ||\n '';\n // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we\n // believe to support JavaScript/AJAX rendering.\n // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\n // would have seen the page\" is flaky if we don't treat it as a crawler.\n return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);\n};\n/**\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\n *\n * It is removed with clearTimeout() as normal.\n *\n * @param fn - Function to run.\n * @param time - Milliseconds to wait before running.\n * @returns The setTimeout() return value.\n */\nconst setTimeoutNonBlocking = function (fn, time) {\n const timeout = setTimeout(fn, time);\n // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.\n if (typeof timeout === 'number' &&\n // @ts-ignore Is only defined in Deno environments.\n typeof Deno !== 'undefined' &&\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\n Deno['unrefTimer']) {\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\n Deno.unrefTimer(timeout);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }\n else if (typeof timeout === 'object' && timeout['unref']) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n timeout['unref']();\n }\n return timeout;\n};\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A class that holds metadata about a Repo object\n */\nclass RepoInfo {\n /**\n * @param host - Hostname portion of the url for the repo\n * @param secure - Whether or not this repo is accessed over ssl\n * @param namespace - The namespace represented by the repo\n * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).\n * @param nodeAdmin - Whether this instance uses Admin SDK credentials\n * @param persistenceKey - Override the default session persistence storage key\n */\n constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false, isUsingEmulator = false, emulatorOptions = null) {\n this.secure = secure;\n this.namespace = namespace;\n this.webSocketOnly = webSocketOnly;\n this.nodeAdmin = nodeAdmin;\n this.persistenceKey = persistenceKey;\n this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;\n this.isUsingEmulator = isUsingEmulator;\n this.emulatorOptions = emulatorOptions;\n this._host = host.toLowerCase();\n this._domain = this._host.substr(this._host.indexOf('.') + 1);\n this.internalHost =\n PersistentStorage.get('host:' + host) || this._host;\n }\n isCacheableHost() {\n return this.internalHost.substr(0, 2) === 's-';\n }\n isCustomHost() {\n return (this._domain !== 'firebaseio.com' &&\n this._domain !== 'firebaseio-demo.com');\n }\n get host() {\n return this._host;\n }\n set host(newHost) {\n if (newHost !== this.internalHost) {\n this.internalHost = newHost;\n if (this.isCacheableHost()) {\n PersistentStorage.set('host:' + this._host, this.internalHost);\n }\n }\n }\n toString() {\n let str = this.toURLString();\n if (this.persistenceKey) {\n str += '<' + this.persistenceKey + '>';\n }\n return str;\n }\n toURLString() {\n const protocol = this.secure ? 'https://' : 'http://';\n const query = this.includeNamespaceInQueryParams\n ? `?ns=${this.namespace}`\n : '';\n return `${protocol}${this.host}/${query}`;\n }\n}\nfunction repoInfoNeedsQueryParam(repoInfo) {\n return (repoInfo.host !== repoInfo.internalHost ||\n repoInfo.isCustomHost() ||\n repoInfo.includeNamespaceInQueryParams);\n}\n/**\n * Returns the websocket URL for this repo\n * @param repoInfo - RepoInfo object\n * @param type - of connection\n * @param params - list\n * @returns The URL for this repo\n */\nfunction repoInfoConnectionURL(repoInfo, type, params) {\n util.assert(typeof type === 'string', 'typeof type must == string');\n util.assert(typeof params === 'object', 'typeof params must == object');\n let connURL;\n if (type === WEBSOCKET) {\n connURL =\n (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';\n }\n else if (type === LONG_POLLING) {\n connURL =\n (repoInfo.secure ? 'https://' : 'http://') +\n repoInfo.internalHost +\n '/.lp?';\n }\n else {\n throw new Error('Unknown connection type: ' + type);\n }\n if (repoInfoNeedsQueryParam(repoInfo)) {\n params['ns'] = repoInfo.namespace;\n }\n const pairs = [];\n each(params, (key, value) => {\n pairs.push(key + '=' + value);\n });\n return connURL + pairs.join('&');\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Tracks a collection of stats.\n */\nclass StatsCollection {\n constructor() {\n this.counters_ = {};\n }\n incrementCounter(name, amount = 1) {\n if (!util.contains(this.counters_, name)) {\n this.counters_[name] = 0;\n }\n this.counters_[name] += amount;\n }\n get() {\n return util.deepCopy(this.counters_);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst collections = {};\nconst reporters = {};\nfunction statsManagerGetCollection(repoInfo) {\n const hashString = repoInfo.toString();\n if (!collections[hashString]) {\n collections[hashString] = new StatsCollection();\n }\n return collections[hashString];\n}\nfunction statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {\n const hashString = repoInfo.toString();\n if (!reporters[hashString]) {\n reporters[hashString] = creatorFunction();\n }\n return reporters[hashString];\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** The semver (www.semver.org) version of the SDK. */\nlet SDK_VERSION = '';\n/**\n * SDK_VERSION should be set before any database instance is created\n * @internal\n */\nfunction setSDKVersion(version) {\n SDK_VERSION = version;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst WEBSOCKET_MAX_FRAME_SIZE = 16384;\nconst WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\nlet WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n}\nelse if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\nfunction setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\n/**\n * Create a new websocket connection with the given callbacks.\n */\nclass WebSocketConnection {\n /**\n * @param connId identifier for this transport\n * @param repoInfo The info for the websocket endpoint.\n * @param applicationId The Firebase App ID for this project.\n * @param appCheckToken The App Check Token for this client.\n * @param authToken The Auth Token for this client.\n * @param transportSessionId Optional transportSessionId if this is connecting\n * to an existing transport session\n * @param lastSessionId Optional lastSessionId if there was a previous\n * connection\n */\n constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.applicationId = applicationId;\n this.appCheckToken = appCheckToken;\n this.authToken = authToken;\n this.keepaliveTimer = null;\n this.frames = null;\n this.totalFrames = 0;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.log_ = logWrapper(this.connId);\n this.stats_ = statsManagerGetCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);\n this.nodeAdmin = repoInfo.nodeAdmin;\n }\n /**\n * @param repoInfo - The info for the websocket endpoint.\n * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param lastSessionId - Optional lastSessionId if there was a previous connection\n * @returns connection url\n */\n static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {\n const urlParams = {};\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\n if (!util.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.hostname &&\n FORGE_DOMAIN_RE.test(location.hostname)) {\n urlParams[REFERER_PARAM] = FORGE_REF;\n }\n if (transportSessionId) {\n urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[LAST_SESSION_PARAM] = lastSessionId;\n }\n if (appCheckToken) {\n urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;\n }\n if (applicationId) {\n urlParams[APPLICATION_ID_PARAM] = applicationId;\n }\n return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);\n }\n /**\n * @param onMessage - Callback when messages arrive\n * @param onDisconnect - Callback with connection lost.\n */\n open(onMessage, onDisconnect) {\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n this.log_('Websocket connecting to ' + this.connURL);\n this.everConnected_ = false;\n // Assume failure until proven otherwise.\n PersistentStorage.set('previous_websocket_failure', true);\n try {\n let options;\n if (util.isNodeSdk()) {\n const device = this.nodeAdmin ? 'AdminNode' : 'Node';\n // UA Format: Firebase////\n options = {\n headers: {\n 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,\n 'X-Firebase-GMPID': this.applicationId || ''\n }\n };\n // If using Node with admin creds, AppCheck-related checks are unnecessary.\n // Note that we send the credentials here even if they aren't admin credentials, which is\n // not a problem.\n // Note that this header is just used to bypass appcheck, and the token should still be sent\n // through the websocket connection once it is established.\n if (this.authToken) {\n options.headers['Authorization'] = `Bearer ${this.authToken}`;\n }\n if (this.appCheckToken) {\n options.headers['X-Firebase-AppCheck'] = this.appCheckToken;\n }\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n const env = process['env'];\n const proxy = this.connURL.indexOf('wss://') === 0\n ? env['HTTPS_PROXY'] || env['https_proxy']\n : env['HTTP_PROXY'] || env['http_proxy'];\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n }\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n }\n catch (e) {\n this.log_('Error instantiating WebSocket.');\n const error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n return;\n }\n this.mySock.onopen = () => {\n this.log_('Websocket connected.');\n this.everConnected_ = true;\n };\n this.mySock.onclose = () => {\n this.log_('Websocket connection was disconnected.');\n this.mySock = null;\n this.onClosed_();\n };\n this.mySock.onmessage = m => {\n this.handleIncomingFrame(m);\n };\n this.mySock.onerror = e => {\n this.log_('WebSocket error. Closing connection.');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n };\n }\n /**\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n */\n start() { }\n static forceDisallow() {\n WebSocketConnection.forceDisallow_ = true;\n }\n static isAvailable() {\n let isOldAndroid = false;\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n const oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n isOldAndroid = true;\n }\n }\n }\n return (!isOldAndroid &&\n WebSocketImpl !== null &&\n !WebSocketConnection.forceDisallow_);\n }\n /**\n * Returns true if we previously failed to connect with this transport.\n */\n static previouslyFailed() {\n // If our persistent storage is actually only in-memory storage,\n // we default to assuming that it previously failed to be safe.\n return (PersistentStorage.isInMemoryStorage ||\n PersistentStorage.get('previous_websocket_failure') === true);\n }\n markConnectionHealthy() {\n PersistentStorage.remove('previous_websocket_failure');\n }\n appendFrame_(data) {\n this.frames.push(data);\n if (this.frames.length === this.totalFrames) {\n const fullMess = this.frames.join('');\n this.frames = null;\n const jsonMess = util.jsonEval(fullMess);\n //handle the message\n this.onMessage(jsonMess);\n }\n }\n /**\n * @param frameCount - The number of frames we are expecting from the server\n */\n handleNewFrameCount_(frameCount) {\n this.totalFrames = frameCount;\n this.frames = [];\n }\n /**\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\n * @returns Any remaining data to be process, or null if there is none\n */\n extractFrameCount_(data) {\n util.assert(this.frames === null, 'We already have a frame buffer');\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\n if (data.length <= 6) {\n const frameCount = Number(data);\n if (!isNaN(frameCount)) {\n this.handleNewFrameCount_(frameCount);\n return null;\n }\n }\n this.handleNewFrameCount_(1);\n return data;\n }\n /**\n * Process a websocket frame that has arrived from the server.\n * @param mess - The frame data\n */\n handleIncomingFrame(mess) {\n if (this.mySock === null) {\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n }\n const data = mess['data'];\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n this.resetKeepAlive();\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n }\n else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n const remainingData = this.extractFrameCount_(data);\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n }\n /**\n * Send a message to the server\n * @param data - The JSON object to transmit\n */\n send(data) {\n this.resetKeepAlive();\n const dataStr = util.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //We can only fit a certain amount in each websocket frame, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n //Send the length header\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n }\n //Send the actual data in segments.\n for (let i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n }\n shutdown_() {\n this.isClosed_ = true;\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n }\n onClosed_() {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_();\n // since this is an internal close, trigger the close listener\n if (this.onDisconnect) {\n this.onDisconnect(this.everConnected_);\n this.onDisconnect = null;\n }\n }\n }\n /**\n * External-facing close handler.\n * Close the websocket and kill the connection.\n */\n close() {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n }\n /**\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\n * the last activity.\n */\n resetKeepAlive() {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(() => {\n //If there has been no websocket activity for a while, send a no-op\n if (this.mySock) {\n this.sendString_('0');\n }\n this.resetKeepAlive();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\n }\n /**\n * Send a string over the websocket.\n *\n * @param str - String to send.\n */\n sendString_(str) {\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n // calls for some unknown reason. We treat these as an error and disconnect.\n // See https://app.asana.com/0/58926111402292/68021340250410\n try {\n this.mySock.send(str);\n }\n catch (e) {\n this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\n setTimeout(this.onClosed_.bind(this), 0);\n }\n }\n}\n/**\n * Number of response before we consider the connection \"healthy.\"\n */\nWebSocketConnection.responsesRequiredToBeHealthy = 2;\n/**\n * Time to wait for the connection te become healthy before giving up.\n */\nWebSocketConnection.healthyTimeout = 30000;\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Abstraction around AppCheck's token fetching capabilities.\n */\nclass AppCheckTokenProvider {\n constructor(app$1, appCheckProvider) {\n this.appCheckProvider = appCheckProvider;\n this.appName = app$1.name;\n if (app._isFirebaseServerApp(app$1) && app$1.settings.appCheckToken) {\n this.serverAppAppCheckToken = app$1.settings.appCheckToken;\n }\n this.appCheck = appCheckProvider?.getImmediate({ optional: true });\n if (!this.appCheck) {\n appCheckProvider?.get().then(appCheck => (this.appCheck = appCheck));\n }\n }\n getToken(forceRefresh) {\n if (this.serverAppAppCheckToken) {\n if (forceRefresh) {\n throw new Error('Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.');\n }\n return Promise.resolve({ token: this.serverAppAppCheckToken });\n }\n if (!this.appCheck) {\n return new Promise((resolve, reject) => {\n // Support delayed initialization of FirebaseAppCheck. This allows our\n // customers to initialize the RTDB SDK before initializing Firebase\n // AppCheck and ensures that all requests are authenticated if a token\n // becomes available before the timeout below expires.\n setTimeout(() => {\n if (this.appCheck) {\n this.getToken(forceRefresh).then(resolve, reject);\n }\n else {\n resolve(null);\n }\n }, 0);\n });\n }\n return this.appCheck.getToken(forceRefresh);\n }\n addTokenChangeListener(listener) {\n this.appCheckProvider\n ?.get()\n .then(appCheck => appCheck.addTokenListener(listener));\n }\n notifyForInvalidToken() {\n warn(`Provided AppCheck credentials for the app named \"${this.appName}\" ` +\n 'are invalid. This usually indicates your app was not initialized correctly.');\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nclass FirebaseAuthTokenProvider {\n constructor(appName_, firebaseOptions_, authProvider_) {\n this.appName_ = appName_;\n this.firebaseOptions_ = firebaseOptions_;\n this.authProvider_ = authProvider_;\n this.auth_ = null;\n this.auth_ = authProvider_.getImmediate({ optional: true });\n if (!this.auth_) {\n authProvider_.onInit(auth => (this.auth_ = auth));\n }\n }\n getToken(forceRefresh) {\n if (!this.auth_) {\n return new Promise((resolve, reject) => {\n // Support delayed initialization of FirebaseAuth. This allows our\n // customers to initialize the RTDB SDK before initializing Firebase\n // Auth and ensures that all requests are authenticated if a token\n // becomes available before the timeout below expires.\n setTimeout(() => {\n if (this.auth_) {\n this.getToken(forceRefresh).then(resolve, reject);\n }\n else {\n resolve(null);\n }\n }, 0);\n });\n }\n return this.auth_.getToken(forceRefresh).catch(error => {\n // TODO: Need to figure out all the cases this is raised and whether\n // this makes sense.\n if (error && error.code === 'auth/token-not-initialized') {\n log('Got auth/token-not-initialized error. Treating as null token.');\n return null;\n }\n else {\n return Promise.reject(error);\n }\n });\n }\n addTokenChangeListener(listener) {\n // TODO: We might want to wrap the listener and call it with no args to\n // avoid a leaky abstraction, but that makes removing the listener harder.\n if (this.auth_) {\n this.auth_.addAuthTokenListener(listener);\n }\n else {\n this.authProvider_\n .get()\n .then(auth => auth.addAuthTokenListener(listener));\n }\n }\n removeTokenChangeListener(listener) {\n this.authProvider_\n .get()\n .then(auth => auth.removeAuthTokenListener(listener));\n }\n notifyForInvalidToken() {\n let errorMessage = 'Provided authentication credentials for the app named \"' +\n this.appName_ +\n '\" are invalid. This usually indicates your app was not ' +\n 'initialized correctly. ';\n if ('credential' in this.firebaseOptions_) {\n errorMessage +=\n 'Make sure the \"credential\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else if ('serviceAccount' in this.firebaseOptions_) {\n errorMessage +=\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else {\n errorMessage +=\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\n 'initializeApp() match the values provided for your app at ' +\n 'https://console.firebase.google.com/.';\n }\n warn(errorMessage);\n }\n}\n/* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */\nclass EmulatorTokenProvider {\n constructor(accessToken) {\n this.accessToken = accessToken;\n }\n getToken(forceRefresh) {\n return Promise.resolve({\n accessToken: this.accessToken\n });\n }\n addTokenChangeListener(listener) {\n // Invoke the listener immediately to match the behavior in Firebase Auth\n // (see packages/auth/src/auth.js#L1807)\n listener(this.accessToken);\n }\n removeTokenChangeListener(listener) { }\n notifyForInvalidToken() { }\n}\n/** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */\nEmulatorTokenProvider.OWNER = 'owner';\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * This class ensures the packets from the server arrive in order\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\n */\nclass PacketReceiver {\n /**\n * @param onMessage_\n */\n constructor(onMessage_) {\n this.onMessage_ = onMessage_;\n this.pendingResponses = [];\n this.currentResponseNum = 0;\n this.closeAfterResponse = -1;\n this.onClose = null;\n }\n closeAfter(responseNum, callback) {\n this.closeAfterResponse = responseNum;\n this.onClose = callback;\n if (this.closeAfterResponse < this.currentResponseNum) {\n this.onClose();\n this.onClose = null;\n }\n }\n /**\n * Each message from the server comes with a response number, and an array of data. The responseNumber\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\n * browsers will respond in the same order as the requests we sent\n */\n handleResponse(requestNum, data) {\n this.pendingResponses[requestNum] = data;\n while (this.pendingResponses[this.currentResponseNum]) {\n const toProcess = this.pendingResponses[this.currentResponseNum];\n delete this.pendingResponses[this.currentResponseNum];\n for (let i = 0; i < toProcess.length; ++i) {\n if (toProcess[i]) {\n exceptionGuard(() => {\n this.onMessage_(toProcess[i]);\n });\n }\n }\n if (this.currentResponseNum === this.closeAfterResponse) {\n if (this.onClose) {\n this.onClose();\n this.onClose = null;\n }\n break;\n }\n this.currentResponseNum++;\n }\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// URL query parameters associated with longpolling\nconst FIREBASE_LONGPOLL_START_PARAM = 'start';\nconst FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\nconst FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\nconst FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\nconst FIREBASE_LONGPOLL_ID_PARAM = 'id';\nconst FIREBASE_LONGPOLL_PW_PARAM = 'pw';\nconst FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\nconst FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\nconst FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\nconst FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\nconst FIREBASE_LONGPOLL_DATA_PARAM = 'd';\nconst FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\n//Data size constants.\n//TODO: Perf: the maximum length actually differs from browser to browser.\n// We should check what browser we're on and set accordingly.\nconst MAX_URL_DATA_SIZE = 1870;\nconst SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\nconst MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\n/**\n * Keepalive period\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\n * length of 30 seconds that we can't exceed.\n */\nconst KEEPALIVE_REQUEST_INTERVAL = 25000;\n/**\n * How long to wait before aborting a long-polling connection attempt.\n */\nconst LP_CONNECT_TIMEOUT = 30000;\n/**\n * This class manages a single long-polling connection.\n */\nclass BrowserPollConnection {\n /**\n * @param connId An identifier for this connection, used for logging\n * @param repoInfo The info for the endpoint to send data to.\n * @param applicationId The Firebase App ID for this project.\n * @param appCheckToken The AppCheck token for this client.\n * @param authToken The AuthToken to use for this connection.\n * @param transportSessionId Optional transportSessionid if we are\n * reconnecting for an existing transport session\n * @param lastSessionId Optional lastSessionId if the PersistentConnection has\n * already created a connection previously\n */\n constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.repoInfo = repoInfo;\n this.applicationId = applicationId;\n this.appCheckToken = appCheckToken;\n this.authToken = authToken;\n this.transportSessionId = transportSessionId;\n this.lastSessionId = lastSessionId;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.everConnected_ = false;\n this.log_ = logWrapper(connId);\n this.stats_ = statsManagerGetCollection(repoInfo);\n this.urlFn = (params) => {\n // Always add the token if we have one.\n if (this.appCheckToken) {\n params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\n }\n return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);\n };\n }\n /**\n * @param onMessage - Callback when messages arrive\n * @param onDisconnect - Callback with connection lost.\n */\n open(onMessage, onDisconnect) {\n this.curSegmentNum = 0;\n this.onDisconnect_ = onDisconnect;\n this.myPacketOrderer = new PacketReceiver(onMessage);\n this.isClosed_ = false;\n this.connectTimeoutTimer_ = setTimeout(() => {\n this.log_('Timed out trying to connect.');\n // Make sure we clear the host cache\n this.onClosed_();\n this.connectTimeoutTimer_ = null;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(LP_CONNECT_TIMEOUT));\n // Ensure we delay the creation of the iframe until the DOM is loaded.\n executeWhenDOMReady(() => {\n if (this.isClosed_) {\n return;\n }\n //Set up a callback that gets triggered once a connection is set up.\n this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => {\n const [command, arg1, arg2, arg3, arg4] = args;\n this.incrementIncomingBytes_(args);\n if (!this.scriptTagHolder) {\n return; // we closed the connection.\n }\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n this.everConnected_ = true;\n if (command === FIREBASE_LONGPOLL_START_PARAM) {\n this.id = arg1;\n this.password = arg2;\n }\n else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {\n // Don't clear the host cache. We got a response from the server, so we know it's reachable\n if (arg1) {\n // We aren't expecting any more data (other than what the server's already in the process of sending us\n // through our already open polls), so don't send any more.\n this.scriptTagHolder.sendNewPolls = false;\n // arg1 in this case is the last response number sent by the server. We should try to receive\n // all of the responses up to this one before closing\n this.myPacketOrderer.closeAfter(arg1, () => {\n this.onClosed_();\n });\n }\n else {\n this.onClosed_();\n }\n }\n else {\n throw new Error('Unrecognized command received: ' + command);\n }\n }, (...args) => {\n const [pN, data] = args;\n this.incrementIncomingBytes_(args);\n this.myPacketOrderer.handleResponse(pN, data);\n }, () => {\n this.onClosed_();\n }, this.urlFn);\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\n //from cache.\n const urlParams = {};\n urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);\n if (this.scriptTagHolder.uniqueCallbackIdentifier) {\n urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =\n this.scriptTagHolder.uniqueCallbackIdentifier;\n }\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\n if (this.transportSessionId) {\n urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;\n }\n if (this.lastSessionId) {\n urlParams[LAST_SESSION_PARAM] = this.lastSessionId;\n }\n if (this.applicationId) {\n urlParams[APPLICATION_ID_PARAM] = this.applicationId;\n }\n if (this.appCheckToken) {\n urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\n }\n if (typeof location !== 'undefined' &&\n location.hostname &&\n FORGE_DOMAIN_RE.test(location.hostname)) {\n urlParams[REFERER_PARAM] = FORGE_REF;\n }\n const connectURL = this.urlFn(urlParams);\n this.log_('Connecting via long-poll to ' + connectURL);\n this.scriptTagHolder.addTag(connectURL, () => {\n /* do nothing */\n });\n });\n }\n /**\n * Call this when a handshake has completed successfully and we want to consider the connection established\n */\n start() {\n this.scriptTagHolder.startLongPoll(this.id, this.password);\n this.addDisconnectPingFrame(this.id, this.password);\n }\n /**\n * Forces long polling to be considered as a potential transport\n */\n static forceAllow() {\n BrowserPollConnection.forceAllow_ = true;\n }\n /**\n * Forces longpolling to not be considered as a potential transport\n */\n static forceDisallow() {\n BrowserPollConnection.forceDisallow_ = true;\n }\n // Static method, use string literal so it can be accessed in a generic way\n static isAvailable() {\n if (util.isNodeSdk()) {\n return false;\n }\n else if (BrowserPollConnection.forceAllow_) {\n return true;\n }\n else {\n // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\n // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\n return (!BrowserPollConnection.forceDisallow_ &&\n typeof document !== 'undefined' &&\n document.createElement != null &&\n !isChromeExtensionContentScript() &&\n !isWindowsStoreApp());\n }\n }\n /**\n * No-op for polling\n */\n markConnectionHealthy() { }\n /**\n * Stops polling and cleans up the iframe\n */\n shutdown_() {\n this.isClosed_ = true;\n if (this.scriptTagHolder) {\n this.scriptTagHolder.close();\n this.scriptTagHolder = null;\n }\n //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\n if (this.myDisconnFrame) {\n document.body.removeChild(this.myDisconnFrame);\n this.myDisconnFrame = null;\n }\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n }\n /**\n * Triggered when this transport is closed\n */\n onClosed_() {\n if (!this.isClosed_) {\n this.log_('Longpoll is closing itself');\n this.shutdown_();\n if (this.onDisconnect_) {\n this.onDisconnect_(this.everConnected_);\n this.onDisconnect_ = null;\n }\n }\n }\n /**\n * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\n * that we've left.\n */\n close() {\n if (!this.isClosed_) {\n this.log_('Longpoll is being closed.');\n this.shutdown_();\n }\n }\n /**\n * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\n * broken into chunks (since URLs have a small maximum length).\n * @param data - The JSON data to transmit.\n */\n send(data) {\n const dataStr = util.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //first, lets get the base64-encoded data\n const base64data = util.base64Encode(dataStr);\n //We can only fit a certain amount in each URL, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\n //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\n //of segments so that we can reassemble the packet on the server.\n for (let i = 0; i < dataSegs.length; i++) {\n this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);\n this.curSegmentNum++;\n }\n }\n /**\n * This is how we notify the server that we're leaving.\n * We aren't able to send requests with DHTML on a window close event, but we can\n * trigger XHR requests in some browsers (everything but Opera basically).\n */\n addDisconnectPingFrame(id, pw) {\n if (util.isNodeSdk()) {\n return;\n }\n this.myDisconnFrame = document.createElement('iframe');\n const urlParams = {};\n urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;\n this.myDisconnFrame.src = this.urlFn(urlParams);\n this.myDisconnFrame.style.display = 'none';\n document.body.appendChild(this.myDisconnFrame);\n }\n /**\n * Used to track the bytes received by this client\n */\n incrementIncomingBytes_(args) {\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\n const bytesReceived = util.stringify(args).length;\n this.bytesReceived += bytesReceived;\n this.stats_.incrementCounter('bytes_received', bytesReceived);\n }\n}\n/*********************************************************************************************\n * A wrapper around an iframe that is used as a long-polling script holder.\n *********************************************************************************************/\nclass FirebaseIFrameScriptHolder {\n /**\n * @param commandCB - The callback to be called when control commands are received from the server.\n * @param onMessageCB - The callback to be triggered when responses arrive from the server.\n * @param onDisconnect - The callback to be triggered when this tag holder is closed\n * @param urlFn - A function that provides the URL of the endpoint to send data to.\n */\n constructor(commandCB, onMessageCB, onDisconnect, urlFn) {\n this.onDisconnect = onDisconnect;\n this.urlFn = urlFn;\n //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\n //problems in some browsers.\n this.outstandingRequests = new Set();\n //A queue of the pending segments waiting for transmission to the server.\n this.pendingSegs = [];\n //A serial number. We use this for two things:\n // 1) A way to ensure the browser doesn't cache responses to polls\n // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\n // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\n // JSONP code in the order it was added to the iframe.\n this.currentSerial = Math.floor(Math.random() * 100000000);\n // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\n // incoming data from the server that we're waiting for).\n this.sendNewPolls = true;\n if (!util.isNodeSdk()) {\n //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\n //iframes where we put the long-polling script tags. We have two callbacks:\n // 1) Command Callback - Triggered for control issues, like starting a connection.\n // 2) Message Callback - Triggered when new data arrives.\n this.uniqueCallbackIdentifier = LUIDGenerator();\n window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;\n window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =\n onMessageCB;\n //Create an iframe for us to add script tags to.\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\n // Set the iframe's contents.\n let script = '';\n // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\n // for ie9, but ie8 needs to do it again in the document itself.\n if (this.myIFrame.src &&\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {\n const currentDomain = document.domain;\n script = '';\n }\n const iframeContents = '' + script + '';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n }\n catch (e) {\n log('frame writing exception');\n if (e.stack) {\n log(e.stack);\n }\n log(e);\n }\n }\n else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n /**\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\n * actually use.\n */\n static createIFrame_() {\n const iframe = document.createElement('iframe');\n iframe.style.display = 'none';\n // This is necessary in order to initialize the document inside the iframe\n if (document.body) {\n document.body.appendChild(iframe);\n try {\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n const a = iframe.contentWindow.document;\n if (!a) {\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n log('No IE domain setting required');\n }\n }\n catch (e) {\n const domain = document.domain;\n iframe.src =\n \"javascript:void((function(){document.open();document.domain='\" +\n domain +\n \"';document.close();})())\";\n }\n }\n else {\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n // never gets hit.\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n }\n // Get the document of the iframe in a browser-specific way.\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n }\n else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }\n else if (iframe.document) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n iframe.doc = iframe.document; //others?\n }\n return iframe;\n }\n /**\n * Cancel all outstanding queries and remove the frame.\n */\n close() {\n //Mark this iframe as dead, so no new requests are sent.\n this.alive = false;\n if (this.myIFrame) {\n //We have to actually remove all of the html inside this iframe before removing it from the\n //window, or IE will continue loading and executing the script tags we've already added, which\n //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.\n this.myIFrame.doc.body.textContent = '';\n setTimeout(() => {\n if (this.myIFrame !== null) {\n document.body.removeChild(this.myIFrame);\n this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n // Protect from being called recursively.\n const onDisconnect = this.onDisconnect;\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\n }\n /**\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\n * @param id - The ID of this connection\n * @param pw - The password for this connection\n */\n startLongPoll(id, pw) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true;\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n while (this.newRequest_()) { }\n }\n /**\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\n * too many outstanding requests and we are still alive.\n *\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\n * needed.\n */\n newRequest_() {\n // We keep one outstanding request open all the time to receive data, but if we need to send data\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\n // close the old request.\n if (this.alive &&\n this.sendNewPolls &&\n this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {\n //construct our url\n this.currentSerial++;\n const urlParams = {};\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n let theURL = this.urlFn(urlParams);\n //Now add as much data as we can.\n let curDataString = '';\n let i = 0;\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n const nextSeg = this.pendingSegs[0];\n if (nextSeg.d.length +\n SEG_HEADER_SIZE +\n curDataString.length <=\n MAX_URL_DATA_SIZE) {\n //great, the segment will fit. Lets append it.\n const theSeg = this.pendingSegs.shift();\n curDataString =\n curDataString +\n '&' +\n FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n i +\n '=' +\n theSeg.seg +\n '&' +\n FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n i +\n '=' +\n theSeg.ts +\n '&' +\n FIREBASE_LONGPOLL_DATA_PARAM +\n i +\n '=' +\n theSeg.d;\n i++;\n }\n else {\n break;\n }\n }\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n return true;\n }\n else {\n return false;\n }\n }\n /**\n * Queue a packet for transmission to the server.\n * @param segnum - A sequential id for this packet segment used for reassembly\n * @param totalsegs - The total number of segments in this packet\n * @param data - The data for this segment.\n */\n enqueueSegment(segnum, totalsegs, data) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n //send the data immediately if there isn't already data being transmitted, unless\n //startLongPoll hasn't been called yet.\n if (this.alive) {\n this.newRequest_();\n }\n }\n /**\n * Add a script tag for a regular long-poll request.\n * @param url - The URL of the script tag.\n * @param serial - The serial number of the request.\n */\n addLongPollTag_(url, serial) {\n //remember that we sent this request.\n this.outstandingRequests.add(serial);\n const doNewRequest = () => {\n this.outstandingRequests.delete(serial);\n this.newRequest_();\n };\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\n const readyStateCB = () => {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout);\n // Trigger a new request so we can continue receiving data.\n doNewRequest();\n };\n this.addTag(url, readyStateCB);\n }\n /**\n * Add an arbitrary script tag to the iframe.\n * @param url - The URL for the script tag source.\n * @param loadCB - A callback to be triggered once the script has loaded.\n */\n addTag(url, loadCB) {\n if (util.isNodeSdk()) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.doNodeLongPoll(url, loadCB);\n }\n else {\n setTimeout(() => {\n try {\n // if we're already closed, don't add this poll\n if (!this.sendNewPolls) {\n return;\n }\n const newScript = this.myIFrame.doc.createElement('script');\n newScript.type = 'text/javascript';\n newScript.async = true;\n newScript.src = url;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n newScript.onload = newScript.onreadystatechange =\n function () {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const rstate = newScript.readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n newScript.onload = newScript.onreadystatechange = null;\n if (newScript.parentNode) {\n newScript.parentNode.removeChild(newScript);\n }\n loadCB();\n }\n };\n newScript.onerror = () => {\n log('Long-poll script failed to load: ' + url);\n this.sendNewPolls = false;\n this.close();\n };\n this.myIFrame.doc.body.appendChild(newScript);\n }\n catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\n * lifecycle.\n *\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\n * they are available.\n */\nclass TransportManager {\n static get ALL_TRANSPORTS() {\n return [BrowserPollConnection, WebSocketConnection];\n }\n /**\n * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after\n * TransportManager has already set up transports_\n */\n static get IS_TRANSPORT_INITIALIZED() {\n return this.globalTransportInitialized_;\n }\n /**\n * @param repoInfo - Metadata around the namespace we're connecting to\n */\n constructor(repoInfo) {\n this.initTransports_(repoInfo);\n }\n initTransports_(repoInfo) {\n const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();\n let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable) {\n warn(\"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\");\n }\n isSkipPollConnection = true;\n }\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection];\n }\n else {\n const transports = (this.transports_ = []);\n for (const transport of TransportManager.ALL_TRANSPORTS) {\n if (transport && transport['isAvailable']()) {\n transports.push(transport);\n }\n }\n TransportManager.globalTransportInitialized_ = true;\n }\n }\n /**\n * @returns The constructor for the initial transport to use\n */\n initialTransport() {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n }\n else {\n throw new Error('No transports available');\n }\n }\n /**\n * @returns The constructor for the next transport, or null\n */\n upgradeTransport() {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n }\n else {\n return null;\n }\n }\n}\n// Keeps track of whether the TransportManager has already chosen a transport to use\nTransportManager.globalTransportInitialized_ = false;\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Abort upgrade attempt if it takes longer than 60s.\nconst UPGRADE_TIMEOUT = 60000;\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\nconst DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\n// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\n// but we've sent/received enough bytes, we don't cancel the connection.\nconst BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\nconst BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\nconst MESSAGE_TYPE = 't';\nconst MESSAGE_DATA = 'd';\nconst CONTROL_SHUTDOWN = 's';\nconst CONTROL_RESET = 'r';\nconst CONTROL_ERROR = 'e';\nconst CONTROL_PONG = 'o';\nconst SWITCH_ACK = 'a';\nconst END_TRANSMISSION = 'n';\nconst PING = 'p';\nconst SERVER_HELLO = 'h';\n/**\n * Creates a new real-time connection to the server using whichever method works\n * best in the current browser.\n */\nclass Connection {\n /**\n * @param id - an id for this connection\n * @param repoInfo_ - the info for the endpoint to connect to\n * @param applicationId_ - the Firebase App ID for this project\n * @param appCheckToken_ - The App Check Token for this device.\n * @param authToken_ - The auth token for this session.\n * @param onMessage_ - the callback to be triggered when a server-push message arrives\n * @param onReady_ - the callback to be triggered when this connection is ready to send messages.\n * @param onDisconnect_ - the callback to be triggered when a connection was lost\n * @param onKill_ - the callback to be triggered when this connection has permanently shut down.\n * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\n */\n constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {\n this.id = id;\n this.repoInfo_ = repoInfo_;\n this.applicationId_ = applicationId_;\n this.appCheckToken_ = appCheckToken_;\n this.authToken_ = authToken_;\n this.onMessage_ = onMessage_;\n this.onReady_ = onReady_;\n this.onDisconnect_ = onDisconnect_;\n this.onKill_ = onKill_;\n this.lastSessionId = lastSessionId;\n this.connectionCount = 0;\n this.pendingDataMessages = [];\n this.state_ = 0 /* RealtimeState.CONNECTING */;\n this.log_ = logWrapper('c:' + this.id + ':');\n this.transportManager_ = new TransportManager(repoInfo_);\n this.log_('Connection created');\n this.start_();\n }\n /**\n * Starts a connection attempt\n */\n start_() {\n const conn = this.transportManager_.initialTransport();\n this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\n const onMessageReceived = this.connReceiver_(this.conn_);\n const onConnectionLost = this.disconnReceiver_(this.conn_);\n this.tx_ = this.conn_;\n this.rx_ = this.conn_;\n this.secondaryConn_ = null;\n this.isHealthy_ = false;\n /*\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\n * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\n * still have the context of your originating frame.\n */\n setTimeout(() => {\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\n this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);\n }, Math.floor(0));\n const healthyTimeoutMS = conn['healthyTimeout'] || 0;\n if (healthyTimeoutMS > 0) {\n this.healthyTimeout_ = setTimeoutNonBlocking(() => {\n this.healthyTimeout_ = null;\n if (!this.isHealthy_) {\n if (this.conn_ &&\n this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {\n this.log_('Connection exceeded healthy timeout but has received ' +\n this.conn_.bytesReceived +\n ' bytes. Marking connection healthy.');\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n }\n else if (this.conn_ &&\n this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {\n this.log_('Connection exceeded healthy timeout but has sent ' +\n this.conn_.bytesSent +\n ' bytes. Leaving connection alive.');\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\n // the server.\n }\n else {\n this.log_('Closing unhealthy connection after timeout.');\n this.close();\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(healthyTimeoutMS));\n }\n }\n nextTransportId_() {\n return 'c:' + this.id + ':' + this.connectionCount++;\n }\n disconnReceiver_(conn) {\n return everConnected => {\n if (conn === this.conn_) {\n this.onConnectionLost_(everConnected);\n }\n else if (conn === this.secondaryConn_) {\n this.log_('Secondary connection lost.');\n this.onSecondaryConnectionLost_();\n }\n else {\n this.log_('closing an old connection');\n }\n };\n }\n connReceiver_(conn) {\n return (message) => {\n if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {\n if (conn === this.rx_) {\n this.onPrimaryMessageReceived_(message);\n }\n else if (conn === this.secondaryConn_) {\n this.onSecondaryMessageReceived_(message);\n }\n else {\n this.log_('message on old connection');\n }\n }\n };\n }\n /**\n * @param dataMsg - An arbitrary data message to be sent to the server\n */\n sendRequest(dataMsg) {\n // wrap in a data message envelope and send it on\n const msg = { t: 'd', d: dataMsg };\n this.sendData_(msg);\n }\n tryCleanupConnection() {\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\n this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);\n this.conn_ = this.secondaryConn_;\n this.secondaryConn_ = null;\n // the server will shutdown the old connection\n }\n }\n onSecondaryControl_(controlData) {\n if (MESSAGE_TYPE in controlData) {\n const cmd = controlData[MESSAGE_TYPE];\n if (cmd === SWITCH_ACK) {\n this.upgradeIfSecondaryHealthy_();\n }\n else if (cmd === CONTROL_RESET) {\n // Most likely the session wasn't valid. Abandon the switch attempt\n this.log_('Got a reset on secondary, closing it');\n this.secondaryConn_.close();\n // If we were already using this connection for something, than we need to fully close\n if (this.tx_ === this.secondaryConn_ ||\n this.rx_ === this.secondaryConn_) {\n this.close();\n }\n }\n else if (cmd === CONTROL_PONG) {\n this.log_('got pong on secondary.');\n this.secondaryResponsesRequired_--;\n this.upgradeIfSecondaryHealthy_();\n }\n }\n }\n onSecondaryMessageReceived_(parsedData) {\n const layer = requireKey('t', parsedData);\n const data = requireKey('d', parsedData);\n if (layer === 'c') {\n this.onSecondaryControl_(data);\n }\n else if (layer === 'd') {\n // got a data message, but we're still second connection. Need to buffer it up\n this.pendingDataMessages.push(data);\n }\n else {\n throw new Error('Unknown protocol layer: ' + layer);\n }\n }\n upgradeIfSecondaryHealthy_() {\n if (this.secondaryResponsesRequired_ <= 0) {\n this.log_('Secondary connection is healthy.');\n this.isHealthy_ = true;\n this.secondaryConn_.markConnectionHealthy();\n this.proceedWithUpgrade_();\n }\n else {\n // Send a ping to make sure the connection is healthy.\n this.log_('sending ping on secondary.');\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\n }\n }\n proceedWithUpgrade_() {\n // tell this connection to consider itself open\n this.secondaryConn_.start();\n // send ack\n this.log_('sending client ack on secondary');\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\n // send end packet on primary transport, switch to sending on this one\n // can receive on this one, buffer responses until end received on primary transport\n this.log_('Ending transmission on primary');\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\n this.tx_ = this.secondaryConn_;\n this.tryCleanupConnection();\n }\n onPrimaryMessageReceived_(parsedData) {\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\n const layer = requireKey('t', parsedData);\n const data = requireKey('d', parsedData);\n if (layer === 'c') {\n this.onControl_(data);\n }\n else if (layer === 'd') {\n this.onDataMessage_(data);\n }\n }\n onDataMessage_(message) {\n this.onPrimaryResponse_();\n // We don't do anything with data messages, just kick them up a level\n this.onMessage_(message);\n }\n onPrimaryResponse_() {\n if (!this.isHealthy_) {\n this.primaryResponsesRequired_--;\n if (this.primaryResponsesRequired_ <= 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n }\n }\n }\n onControl_(controlData) {\n const cmd = requireKey(MESSAGE_TYPE, controlData);\n if (MESSAGE_DATA in controlData) {\n const payload = controlData[MESSAGE_DATA];\n if (cmd === SERVER_HELLO) {\n const handshakePayload = {\n ...payload\n };\n if (this.repoInfo_.isUsingEmulator) {\n // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes.\n handshakePayload.h = this.repoInfo_.host;\n }\n this.onHandshake_(handshakePayload);\n }\n else if (cmd === END_TRANSMISSION) {\n this.log_('recvd end transmission on primary');\n this.rx_ = this.secondaryConn_;\n for (let i = 0; i < this.pendingDataMessages.length; ++i) {\n this.onDataMessage_(this.pendingDataMessages[i]);\n }\n this.pendingDataMessages = [];\n this.tryCleanupConnection();\n }\n else if (cmd === CONTROL_SHUTDOWN) {\n // This was previously the 'onKill' callback passed to the lower-level connection\n // payload in this case is the reason for the shutdown. Generally a human-readable error\n this.onConnectionShutdown_(payload);\n }\n else if (cmd === CONTROL_RESET) {\n // payload in this case is the host we should contact\n this.onReset_(payload);\n }\n else if (cmd === CONTROL_ERROR) {\n error('Server Error: ' + payload);\n }\n else if (cmd === CONTROL_PONG) {\n this.log_('got pong on primary.');\n this.onPrimaryResponse_();\n this.sendPingOnPrimaryIfNecessary_();\n }\n else {\n error('Unknown control packet command: ' + cmd);\n }\n }\n }\n /**\n * @param handshake - The handshake data returned from the server\n */\n onHandshake_(handshake) {\n const timestamp = handshake.ts;\n const version = handshake.v;\n const host = handshake.h;\n this.sessionId = handshake.s;\n this.repoInfo_.host = host;\n // if we've already closed the connection, then don't bother trying to progress further\n if (this.state_ === 0 /* RealtimeState.CONNECTING */) {\n this.conn_.start();\n this.onConnectionEstablished_(this.conn_, timestamp);\n if (PROTOCOL_VERSION !== version) {\n warn('Protocol version mismatch detected');\n }\n // TODO: do we want to upgrade? when? maybe a delay?\n this.tryStartUpgrade_();\n }\n }\n tryStartUpgrade_() {\n const conn = this.transportManager_.upgradeTransport();\n if (conn) {\n this.startUpgrade_(conn);\n }\n }\n startUpgrade_(conn) {\n this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.secondaryResponsesRequired_ =\n conn['responsesRequiredToBeHealthy'] || 0;\n const onMessage = this.connReceiver_(this.secondaryConn_);\n const onDisconnect = this.disconnReceiver_(this.secondaryConn_);\n this.secondaryConn_.open(onMessage, onDisconnect);\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\n setTimeoutNonBlocking(() => {\n if (this.secondaryConn_) {\n this.log_('Timed out trying to upgrade.');\n this.secondaryConn_.close();\n }\n }, Math.floor(UPGRADE_TIMEOUT));\n }\n onReset_(host) {\n this.log_('Reset packet received. New host: ' + host);\n this.repoInfo_.host = host;\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\n // We don't currently support resets after the connection has already been established\n if (this.state_ === 1 /* RealtimeState.CONNECTED */) {\n this.close();\n }\n else {\n // Close whatever connections we have open and start again.\n this.closeConnections_();\n this.start_();\n }\n }\n onConnectionEstablished_(conn, timestamp) {\n this.log_('Realtime connection established.');\n this.conn_ = conn;\n this.state_ = 1 /* RealtimeState.CONNECTED */;\n if (this.onReady_) {\n this.onReady_(timestamp, this.sessionId);\n this.onReady_ = null;\n }\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\n // send some pings.\n if (this.primaryResponsesRequired_ === 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n }\n else {\n setTimeoutNonBlocking(() => {\n this.sendPingOnPrimaryIfNecessary_();\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\n }\n }\n sendPingOnPrimaryIfNecessary_() {\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\n if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {\n this.log_('sending ping on primary.');\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\n }\n }\n onSecondaryConnectionLost_() {\n const conn = this.secondaryConn_;\n this.secondaryConn_ = null;\n if (this.tx_ === conn || this.rx_ === conn) {\n // we are relying on this connection already in some capacity. Therefore, a failure is real\n this.close();\n }\n }\n /**\n * @param everConnected - Whether or not the connection ever reached a server. Used to determine if\n * we should flush the host cache\n */\n onConnectionLost_(everConnected) {\n this.conn_ = null;\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\n if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {\n this.log_('Realtime connection failed.');\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\n if (this.repoInfo_.isCacheableHost()) {\n PersistentStorage.remove('host:' + this.repoInfo_.host);\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\n this.repoInfo_.internalHost = this.repoInfo_.host;\n }\n }\n else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {\n this.log_('Realtime connection lost.');\n }\n this.close();\n }\n onConnectionShutdown_(reason) {\n this.log_('Connection shutdown command received. Shutting down...');\n if (this.onKill_) {\n this.onKill_(reason);\n this.onKill_ = null;\n }\n // We intentionally don't want to fire onDisconnect (kill is a different case),\n // so clear the callback.\n this.onDisconnect_ = null;\n this.close();\n }\n sendData_(data) {\n if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {\n throw 'Connection is not connected';\n }\n else {\n this.tx_.send(data);\n }\n }\n /**\n * Cleans up this connection, calling the appropriate callbacks\n */\n close() {\n if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {\n this.log_('Closing realtime connection.');\n this.state_ = 2 /* RealtimeState.DISCONNECTED */;\n this.closeConnections_();\n if (this.onDisconnect_) {\n this.onDisconnect_();\n this.onDisconnect_ = null;\n }\n }\n }\n closeConnections_() {\n this.log_('Shutting down all connections');\n if (this.conn_) {\n this.conn_.close();\n this.conn_ = null;\n }\n if (this.secondaryConn_) {\n this.secondaryConn_.close();\n this.secondaryConn_ = null;\n }\n if (this.healthyTimeout_) {\n clearTimeout(this.healthyTimeout_);\n this.healthyTimeout_ = null;\n }\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Interface defining the set of actions that can be performed against the Firebase server\n * (basically corresponds to our wire protocol).\n *\n * @interface\n */\nclass ServerActions {\n put(pathString, data, onComplete, hash) { }\n merge(pathString, data, onComplete, hash) { }\n /**\n * Refreshes the auth token for the current connection.\n * @param token - The authentication token\n */\n refreshAuthToken(token) { }\n /**\n * Refreshes the app check token for the current connection.\n * @param token The app check token\n */\n refreshAppCheckToken(token) { }\n onDisconnectPut(pathString, data, onComplete) { }\n onDisconnectMerge(pathString, data, onComplete) { }\n onDisconnectCancel(pathString, onComplete) { }\n reportStats(stats) { }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Base class to be used if you want to emit events. Call the constructor with\n * the set of allowed event names.\n */\nclass EventEmitter {\n constructor(allowedEvents_) {\n this.allowedEvents_ = allowedEvents_;\n this.listeners_ = {};\n util.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');\n }\n /**\n * To be called by derived classes to trigger events.\n */\n trigger(eventType, ...varArgs) {\n if (Array.isArray(this.listeners_[eventType])) {\n // Clone the list, since callbacks could add/remove listeners.\n const listeners = [...this.listeners_[eventType]];\n for (let i = 0; i < listeners.length; i++) {\n listeners[i].callback.apply(listeners[i].context, varArgs);\n }\n }\n }\n on(eventType, callback, context) {\n this.validateEventType_(eventType);\n this.listeners_[eventType] = this.listeners_[eventType] || [];\n this.listeners_[eventType].push({ callback, context });\n const eventData = this.getInitialEvent(eventType);\n if (eventData) {\n callback.apply(context, eventData);\n }\n }\n off(eventType, callback, context) {\n this.validateEventType_(eventType);\n const listeners = this.listeners_[eventType] || [];\n for (let i = 0; i < listeners.length; i++) {\n if (listeners[i].callback === callback &&\n (!context || context === listeners[i].context)) {\n listeners.splice(i, 1);\n return;\n }\n }\n }\n validateEventType_(eventType) {\n util.assert(this.allowedEvents_.find(et => {\n return et === eventType;\n }), 'Unknown event: ' + eventType);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Monitors online state (as reported by window.online/offline events).\n *\n * The expectation is that this could have many false positives (thinks we are online\n * when we're not), but no false negatives. So we can safely use it to determine when\n * we definitely cannot reach the internet.\n */\nclass OnlineMonitor extends EventEmitter {\n static getInstance() {\n return new OnlineMonitor();\n }\n constructor() {\n super(['online']);\n this.online_ = true;\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\n // It would seem that the 'online' event does not always fire consistently. So we disable it\n // for Cordova.\n if (typeof window !== 'undefined' &&\n typeof window.addEventListener !== 'undefined' &&\n !util.isMobileCordova()) {\n window.addEventListener('online', () => {\n if (!this.online_) {\n this.online_ = true;\n this.trigger('online', true);\n }\n }, false);\n window.addEventListener('offline', () => {\n if (this.online_) {\n this.online_ = false;\n this.trigger('online', false);\n }\n }, false);\n }\n }\n getInitialEvent(eventType) {\n util.assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n }\n currentlyOnline() {\n return this.online_;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Maximum key depth. */\nconst MAX_PATH_DEPTH = 32;\n/** Maximum number of (UTF8) bytes in a Firebase path. */\nconst MAX_PATH_LENGTH_BYTES = 768;\n/**\n * An immutable object representing a parsed path. It's immutable so that you\n * can pass them around to other functions without worrying about them changing\n * it.\n */\nclass Path {\n /**\n * @param pathOrString - Path string to parse, or another path, or the raw\n * tokens array\n */\n constructor(pathOrString, pieceNum) {\n if (pieceNum === void 0) {\n this.pieces_ = pathOrString.split('/');\n // Remove empty pieces.\n let copyTo = 0;\n for (let i = 0; i < this.pieces_.length; i++) {\n if (this.pieces_[i].length > 0) {\n this.pieces_[copyTo] = this.pieces_[i];\n copyTo++;\n }\n }\n this.pieces_.length = copyTo;\n this.pieceNum_ = 0;\n }\n else {\n this.pieces_ = pathOrString;\n this.pieceNum_ = pieceNum;\n }\n }\n toString() {\n let pathString = '';\n for (let i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '') {\n pathString += '/' + this.pieces_[i];\n }\n }\n return pathString || '/';\n }\n}\nfunction newEmptyPath() {\n return new Path('');\n}\nfunction pathGetFront(path) {\n if (path.pieceNum_ >= path.pieces_.length) {\n return null;\n }\n return path.pieces_[path.pieceNum_];\n}\n/**\n * @returns The number of segments in this path\n */\nfunction pathGetLength(path) {\n return path.pieces_.length - path.pieceNum_;\n}\nfunction pathPopFront(path) {\n let pieceNum = path.pieceNum_;\n if (pieceNum < path.pieces_.length) {\n pieceNum++;\n }\n return new Path(path.pieces_, pieceNum);\n}\nfunction pathGetBack(path) {\n if (path.pieceNum_ < path.pieces_.length) {\n return path.pieces_[path.pieces_.length - 1];\n }\n return null;\n}\nfunction pathToUrlEncodedString(path) {\n let pathString = '';\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\n if (path.pieces_[i] !== '') {\n pathString += '/' + encodeURIComponent(String(path.pieces_[i]));\n }\n }\n return pathString || '/';\n}\n/**\n * Shallow copy of the parts of the path.\n *\n */\nfunction pathSlice(path, begin = 0) {\n return path.pieces_.slice(path.pieceNum_ + begin);\n}\nfunction pathParent(path) {\n if (path.pieceNum_ >= path.pieces_.length) {\n return null;\n }\n const pieces = [];\n for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {\n pieces.push(path.pieces_[i]);\n }\n return new Path(pieces, 0);\n}\nfunction pathChild(path, childPathObj) {\n const pieces = [];\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\n pieces.push(path.pieces_[i]);\n }\n if (childPathObj instanceof Path) {\n for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\n pieces.push(childPathObj.pieces_[i]);\n }\n }\n else {\n const childPieces = childPathObj.split('/');\n for (let i = 0; i < childPieces.length; i++) {\n if (childPieces[i].length > 0) {\n pieces.push(childPieces[i]);\n }\n }\n }\n return new Path(pieces, 0);\n}\n/**\n * @returns True if there are no segments in this path\n */\nfunction pathIsEmpty(path) {\n return path.pieceNum_ >= path.pieces_.length;\n}\n/**\n * @returns The path from outerPath to innerPath\n */\nfunction newRelativePath(outerPath, innerPath) {\n const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);\n if (outer === null) {\n return innerPath;\n }\n else if (outer === inner) {\n return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));\n }\n else {\n throw new Error('INTERNAL ERROR: innerPath (' +\n innerPath +\n ') is not within ' +\n 'outerPath (' +\n outerPath +\n ')');\n }\n}\n/**\n * @returns -1, 0, 1 if left is less, equal, or greater than the right.\n */\nfunction pathCompare(left, right) {\n const leftKeys = pathSlice(left, 0);\n const rightKeys = pathSlice(right, 0);\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\n const cmp = nameCompare(leftKeys[i], rightKeys[i]);\n if (cmp !== 0) {\n return cmp;\n }\n }\n if (leftKeys.length === rightKeys.length) {\n return 0;\n }\n return leftKeys.length < rightKeys.length ? -1 : 1;\n}\n/**\n * @returns true if paths are the same.\n */\nfunction pathEquals(path, other) {\n if (pathGetLength(path) !== pathGetLength(other)) {\n return false;\n }\n for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {\n if (path.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n }\n return true;\n}\n/**\n * @returns True if this path is a parent of (or the same as) other\n */\nfunction pathContains(path, other) {\n let i = path.pieceNum_;\n let j = other.pieceNum_;\n if (pathGetLength(path) > pathGetLength(other)) {\n return false;\n }\n while (i < path.pieces_.length) {\n if (path.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n ++i;\n ++j;\n }\n return true;\n}\n/**\n * Dynamic (mutable) path used to count path lengths.\n *\n * This class is used to efficiently check paths for valid\n * length (in UTF8 bytes) and depth (used in path validation).\n *\n * Throws Error exception if path is ever invalid.\n *\n * The definition of a path always begins with '/'.\n */\nclass ValidationPath {\n /**\n * @param path - Initial Path.\n * @param errorPrefix_ - Prefix for any error messages.\n */\n constructor(path, errorPrefix_) {\n this.errorPrefix_ = errorPrefix_;\n this.parts_ = pathSlice(path, 0);\n /** Initialize to number of '/' chars needed in path. */\n this.byteLength_ = Math.max(1, this.parts_.length);\n for (let i = 0; i < this.parts_.length; i++) {\n this.byteLength_ += util.stringLength(this.parts_[i]);\n }\n validationPathCheckValid(this);\n }\n}\nfunction validationPathPush(validationPath, child) {\n // Count the needed '/'\n if (validationPath.parts_.length > 0) {\n validationPath.byteLength_ += 1;\n }\n validationPath.parts_.push(child);\n validationPath.byteLength_ += util.stringLength(child);\n validationPathCheckValid(validationPath);\n}\nfunction validationPathPop(validationPath) {\n const last = validationPath.parts_.pop();\n validationPath.byteLength_ -= util.stringLength(last);\n // Un-count the previous '/'\n if (validationPath.parts_.length > 0) {\n validationPath.byteLength_ -= 1;\n }\n}\nfunction validationPathCheckValid(validationPath) {\n if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {\n throw new Error(validationPath.errorPrefix_ +\n 'has a key path longer than ' +\n MAX_PATH_LENGTH_BYTES +\n ' bytes (' +\n validationPath.byteLength_ +\n ').');\n }\n if (validationPath.parts_.length > MAX_PATH_DEPTH) {\n throw new Error(validationPath.errorPrefix_ +\n 'path specified exceeds the maximum depth that can be written (' +\n MAX_PATH_DEPTH +\n ') or object contains a cycle ' +\n validationPathToErrorString(validationPath));\n }\n}\n/**\n * String for use in error messages - uses '.' notation for path.\n */\nfunction validationPathToErrorString(validationPath) {\n if (validationPath.parts_.length === 0) {\n return '';\n }\n return \"in property '\" + validationPath.parts_.join('.') + \"'\";\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass VisibilityMonitor extends EventEmitter {\n static getInstance() {\n return new VisibilityMonitor();\n }\n constructor() {\n super(['visible']);\n let hidden;\n let visibilityChange;\n if (typeof document !== 'undefined' &&\n typeof document.addEventListener !== 'undefined') {\n if (typeof document['hidden'] !== 'undefined') {\n // Opera 12.10 and Firefox 18 and later support\n visibilityChange = 'visibilitychange';\n hidden = 'hidden';\n }\n else if (typeof document['mozHidden'] !== 'undefined') {\n visibilityChange = 'mozvisibilitychange';\n hidden = 'mozHidden';\n }\n else if (typeof document['msHidden'] !== 'undefined') {\n visibilityChange = 'msvisibilitychange';\n hidden = 'msHidden';\n }\n else if (typeof document['webkitHidden'] !== 'undefined') {\n visibilityChange = 'webkitvisibilitychange';\n hidden = 'webkitHidden';\n }\n }\n // Initially, we always assume we are visible. This ensures that in browsers\n // without page visibility support or in cases where we are never visible\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n // reconnects\n this.visible_ = true;\n if (visibilityChange) {\n document.addEventListener(visibilityChange, () => {\n const visible = !document[hidden];\n if (visible !== this.visible_) {\n this.visible_ = visible;\n this.trigger('visible', visible);\n }\n }, false);\n }\n }\n getInitialEvent(eventType) {\n util.assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst RECONNECT_MIN_DELAY = 1000;\nconst RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\nconst RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\nconst RECONNECT_DELAY_MULTIPLIER = 1.3;\nconst RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\nconst SERVER_KILL_INTERRUPT_REASON = 'server_kill';\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\nconst INVALID_TOKEN_THRESHOLD = 3;\n/**\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\n *\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\n * in quotes to make sure the closure compiler does not minify them.\n */\nclass PersistentConnection extends ServerActions {\n /**\n * @param repoInfo_ - Data about the namespace we are connecting to\n * @param applicationId_ - The Firebase App ID for this project\n * @param onDataUpdate_ - A callback for new data from the server\n */\n constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {\n super();\n this.repoInfo_ = repoInfo_;\n this.applicationId_ = applicationId_;\n this.onDataUpdate_ = onDataUpdate_;\n this.onConnectStatus_ = onConnectStatus_;\n this.onServerInfoUpdate_ = onServerInfoUpdate_;\n this.authTokenProvider_ = authTokenProvider_;\n this.appCheckTokenProvider_ = appCheckTokenProvider_;\n this.authOverride_ = authOverride_;\n // Used for diagnostic logging.\n this.id = PersistentConnection.nextPersistentConnectionId_++;\n this.log_ = logWrapper('p:' + this.id + ':');\n this.interruptReasons_ = {};\n this.listens = new Map();\n this.outstandingPuts_ = [];\n this.outstandingGets_ = [];\n this.outstandingPutCount_ = 0;\n this.outstandingGetCount_ = 0;\n this.onDisconnectRequestQueue_ = [];\n this.connected_ = false;\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\n this.securityDebugCallback_ = null;\n this.lastSessionId = null;\n this.establishConnectionTimer_ = null;\n this.visible_ = false;\n // Before we get connected, we keep a queue of pending messages to send.\n this.requestCBHash_ = {};\n this.requestNumber_ = 0;\n this.realtime_ = null;\n this.authToken_ = null;\n this.appCheckToken_ = null;\n this.forceTokenRefresh_ = false;\n this.invalidAuthTokenCount_ = 0;\n this.invalidAppCheckTokenCount_ = 0;\n this.firstConnection_ = true;\n this.lastConnectionAttemptTime_ = null;\n this.lastConnectionEstablishedTime_ = null;\n if (authOverride_ && !util.isNodeSdk()) {\n throw new Error('Auth override specified in options, but not supported on non Node.js platforms');\n }\n VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);\n if (repoInfo_.host.indexOf('fblocal') === -1) {\n OnlineMonitor.getInstance().on('online', this.onOnline_, this);\n }\n }\n sendRequest(action, body, onResponse) {\n const curReqNum = ++this.requestNumber_;\n const msg = { r: curReqNum, a: action, b: body };\n this.log_(util.stringify(msg));\n util.assert(this.connected_, \"sendRequest call when we're not connected not allowed.\");\n this.realtime_.sendRequest(msg);\n if (onResponse) {\n this.requestCBHash_[curReqNum] = onResponse;\n }\n }\n get(query) {\n this.initConnection_();\n const deferred = new util.Deferred();\n const request = {\n p: query._path.toString(),\n q: query._queryObject\n };\n const outstandingGet = {\n action: 'g',\n request,\n onComplete: (message) => {\n const payload = message['d'];\n if (message['s'] === 'ok') {\n deferred.resolve(payload);\n }\n else {\n deferred.reject(payload);\n }\n }\n };\n this.outstandingGets_.push(outstandingGet);\n this.outstandingGetCount_++;\n const index = this.outstandingGets_.length - 1;\n if (this.connected_) {\n this.sendGet_(index);\n }\n return deferred.promise;\n }\n listen(query, currentHashFn, tag, onComplete) {\n this.initConnection_();\n const queryId = query._queryIdentifier;\n const pathString = query._path.toString();\n this.log_('Listen called for ' + pathString + ' ' + queryId);\n if (!this.listens.has(pathString)) {\n this.listens.set(pathString, new Map());\n }\n util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');\n util.assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`);\n const listenSpec = {\n onComplete,\n hashFn: currentHashFn,\n query,\n tag\n };\n this.listens.get(pathString).set(queryId, listenSpec);\n if (this.connected_) {\n this.sendListen_(listenSpec);\n }\n }\n sendGet_(index) {\n const get = this.outstandingGets_[index];\n this.sendRequest('g', get.request, (message) => {\n delete this.outstandingGets_[index];\n this.outstandingGetCount_--;\n if (this.outstandingGetCount_ === 0) {\n this.outstandingGets_ = [];\n }\n if (get.onComplete) {\n get.onComplete(message);\n }\n });\n }\n sendListen_(listenSpec) {\n const query = listenSpec.query;\n const pathString = query._path.toString();\n const queryId = query._queryIdentifier;\n this.log_('Listen on ' + pathString + ' for ' + queryId);\n const req = { /*path*/ p: pathString };\n const action = 'q';\n // Only bother to send query if it's non-default.\n if (listenSpec.tag) {\n req['q'] = query._queryObject;\n req['t'] = listenSpec.tag;\n }\n req[ /*hash*/'h'] = listenSpec.hashFn();\n this.sendRequest(action, req, (message) => {\n const payload = message[ /*data*/'d'];\n const status = message[ /*status*/'s'];\n // print warnings in any case...\n PersistentConnection.warnOnListenWarnings_(payload, query);\n const currentListenSpec = this.listens.get(pathString) &&\n this.listens.get(pathString).get(queryId);\n // only trigger actions if the listen hasn't been removed and readded\n if (currentListenSpec === listenSpec) {\n this.log_('listen response', message);\n if (status !== 'ok') {\n this.removeListen_(pathString, queryId);\n }\n if (listenSpec.onComplete) {\n listenSpec.onComplete(status, payload);\n }\n }\n });\n }\n static warnOnListenWarnings_(payload, query) {\n if (payload && typeof payload === 'object' && util.contains(payload, 'w')) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const warnings = util.safeGet(payload, 'w');\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\n const indexSpec = '\".indexOn\": \"' + query._queryParams.getIndex().toString() + '\"';\n const indexPath = query._path.toString();\n warn(`Using an unspecified index. Your data will be downloaded and ` +\n `filtered on the client. Consider adding ${indexSpec} at ` +\n `${indexPath} to your security rules for better performance.`);\n }\n }\n }\n refreshAuthToken(token) {\n this.authToken_ = token;\n this.log_('Auth token refreshed');\n if (this.authToken_) {\n this.tryAuth();\n }\n else {\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\n //the credential so we dont become authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unauth', {}, () => { });\n }\n }\n this.reduceReconnectDelayIfAdminCredential_(token);\n }\n reduceReconnectDelayIfAdminCredential_(credential) {\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\n const isFirebaseSecret = credential && credential.length === 40;\n if (isFirebaseSecret || util.isAdmin(credential)) {\n this.log_('Admin auth credential detected. Reducing max reconnect time.');\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n }\n }\n refreshAppCheckToken(token) {\n this.appCheckToken_ = token;\n this.log_('App check token refreshed');\n if (this.appCheckToken_) {\n this.tryAppCheck();\n }\n else {\n //If we're connected we want to let the server know to unauthenticate us.\n //If we're not connected, simply delete the credential so we dont become\n // authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unappeck', {}, () => { });\n }\n }\n }\n /**\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\n * a auth revoked (the connection is closed).\n */\n tryAuth() {\n if (this.connected_ && this.authToken_) {\n const token = this.authToken_;\n const authMethod = util.isValidFormat(token) ? 'auth' : 'gauth';\n const requestData = { cred: token };\n if (this.authOverride_ === null) {\n requestData['noauth'] = true;\n }\n else if (typeof this.authOverride_ === 'object') {\n requestData['authvar'] = this.authOverride_;\n }\n this.sendRequest(authMethod, requestData, (res) => {\n const status = res[ /*status*/'s'];\n const data = res[ /*data*/'d'] || 'error';\n if (this.authToken_ === token) {\n if (status === 'ok') {\n this.invalidAuthTokenCount_ = 0;\n }\n else {\n // Triggers reconnect and force refresh for auth token\n this.onAuthRevoked_(status, data);\n }\n }\n });\n }\n }\n /**\n * Attempts to authenticate with the given token. If the authentication\n * attempt fails, it's triggered like the token was revoked (the connection is\n * closed).\n */\n tryAppCheck() {\n if (this.connected_ && this.appCheckToken_) {\n this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => {\n const status = res[ /*status*/'s'];\n const data = res[ /*data*/'d'] || 'error';\n if (status === 'ok') {\n this.invalidAppCheckTokenCount_ = 0;\n }\n else {\n this.onAppCheckRevoked_(status, data);\n }\n });\n }\n }\n /**\n * @inheritDoc\n */\n unlisten(query, tag) {\n const pathString = query._path.toString();\n const queryId = query._queryIdentifier;\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\n util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');\n const listen = this.removeListen_(pathString, queryId);\n if (listen && this.connected_) {\n this.sendUnlisten_(pathString, queryId, query._queryObject, tag);\n }\n }\n sendUnlisten_(pathString, queryId, queryObj, tag) {\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\n const req = { /*path*/ p: pathString };\n const action = 'n';\n // Only bother sending queryId if it's non-default.\n if (tag) {\n req['q'] = queryObj;\n req['t'] = tag;\n }\n this.sendRequest(action, req);\n }\n onDisconnectPut(pathString, data, onComplete) {\n this.initConnection_();\n if (this.connected_) {\n this.sendOnDisconnect_('o', pathString, data, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'o',\n data,\n onComplete\n });\n }\n }\n onDisconnectMerge(pathString, data, onComplete) {\n this.initConnection_();\n if (this.connected_) {\n this.sendOnDisconnect_('om', pathString, data, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'om',\n data,\n onComplete\n });\n }\n }\n onDisconnectCancel(pathString, onComplete) {\n this.initConnection_();\n if (this.connected_) {\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'oc',\n data: null,\n onComplete\n });\n }\n }\n sendOnDisconnect_(action, pathString, data, onComplete) {\n const request = { /*path*/ p: pathString, /*data*/ d: data };\n this.log_('onDisconnect ' + action, request);\n this.sendRequest(action, request, (response) => {\n if (onComplete) {\n setTimeout(() => {\n onComplete(response[ /*status*/'s'], response[ /* data */'d']);\n }, Math.floor(0));\n }\n });\n }\n put(pathString, data, onComplete, hash) {\n this.putInternal('p', pathString, data, onComplete, hash);\n }\n merge(pathString, data, onComplete, hash) {\n this.putInternal('m', pathString, data, onComplete, hash);\n }\n putInternal(action, pathString, data, onComplete, hash) {\n this.initConnection_();\n const request = {\n /*path*/ p: pathString,\n /*data*/ d: data\n };\n if (hash !== undefined) {\n request[ /*hash*/'h'] = hash;\n }\n // TODO: Only keep track of the most recent put for a given path?\n this.outstandingPuts_.push({\n action,\n request,\n onComplete\n });\n this.outstandingPutCount_++;\n const index = this.outstandingPuts_.length - 1;\n if (this.connected_) {\n this.sendPut_(index);\n }\n else {\n this.log_('Buffering put: ' + pathString);\n }\n }\n sendPut_(index) {\n const action = this.outstandingPuts_[index].action;\n const request = this.outstandingPuts_[index].request;\n const onComplete = this.outstandingPuts_[index].onComplete;\n this.outstandingPuts_[index].queued = this.connected_;\n this.sendRequest(action, request, (message) => {\n this.log_(action + ' response', message);\n delete this.outstandingPuts_[index];\n this.outstandingPutCount_--;\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0) {\n this.outstandingPuts_ = [];\n }\n if (onComplete) {\n onComplete(message[ /*status*/'s'], message[ /* data */'d']);\n }\n });\n }\n reportStats(stats) {\n // If we're not connected, we just drop the stats.\n if (this.connected_) {\n const request = { /*counters*/ c: stats };\n this.log_('reportStats', request);\n this.sendRequest(/*stats*/ 's', request, result => {\n const status = result[ /*status*/'s'];\n if (status !== 'ok') {\n const errorReason = result[ /* data */'d'];\n this.log_('reportStats', 'Error sending stats: ' + errorReason);\n }\n });\n }\n }\n onDataMessage_(message) {\n if ('r' in message) {\n // this is a response\n this.log_('from server: ' + util.stringify(message));\n const reqNum = message['r'];\n const onResponse = this.requestCBHash_[reqNum];\n if (onResponse) {\n delete this.requestCBHash_[reqNum];\n onResponse(message[ /*body*/'b']);\n }\n }\n else if ('error' in message) {\n throw 'A server-side error has occurred: ' + message['error'];\n }\n else if ('a' in message) {\n // a and b are action and body, respectively\n this.onDataPush_(message['a'], message['b']);\n }\n }\n onDataPush_(action, body) {\n this.log_('handleServerMessage', action, body);\n if (action === 'd') {\n this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], \n /*isMerge*/ false, body['t']);\n }\n else if (action === 'm') {\n this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], \n /*isMerge=*/ true, body['t']);\n }\n else if (action === 'c') {\n this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);\n }\n else if (action === 'ac') {\n this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);\n }\n else if (action === 'apc') {\n this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);\n }\n else if (action === 'sd') {\n this.onSecurityDebugPacket_(body);\n }\n else {\n error('Unrecognized action received from server: ' +\n util.stringify(action) +\n '\\nAre you using the latest client?');\n }\n }\n onReady_(timestamp, sessionId) {\n this.log_('connection ready');\n this.connected_ = true;\n this.lastConnectionEstablishedTime_ = new Date().getTime();\n this.handleTimestamp_(timestamp);\n this.lastSessionId = sessionId;\n if (this.firstConnection_) {\n this.sendConnectStats_();\n }\n this.restoreState_();\n this.firstConnection_ = false;\n this.onConnectStatus_(true);\n }\n scheduleConnect_(timeout) {\n util.assert(!this.realtime_, \"Scheduling a connect when we're already connected/ing?\");\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n }\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\n this.establishConnectionTimer_ = setTimeout(() => {\n this.establishConnectionTimer_ = null;\n this.establishConnection_();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(timeout));\n }\n initConnection_() {\n if (!this.realtime_ && this.firstConnection_) {\n this.scheduleConnect_(0);\n }\n }\n onVisible_(visible) {\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\n if (visible &&\n !this.visible_ &&\n this.reconnectDelay_ === this.maxReconnectDelay_) {\n this.log_('Window became visible. Reducing delay.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n this.visible_ = visible;\n }\n onOnline_(online) {\n if (online) {\n this.log_('Browser went online.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n else {\n this.log_('Browser went offline. Killing connection.');\n if (this.realtime_) {\n this.realtime_.close();\n }\n }\n }\n onRealtimeDisconnect_() {\n this.log_('data client disconnected');\n this.connected_ = false;\n this.realtime_ = null;\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\n this.cancelSentTransactions_();\n // Clear out the pending requests.\n this.requestCBHash_ = {};\n if (this.shouldReconnect_()) {\n if (!this.visible_) {\n this.log_(\"Window isn't visible. Delaying reconnect.\");\n this.reconnectDelay_ = this.maxReconnectDelay_;\n this.lastConnectionAttemptTime_ = new Date().getTime();\n }\n else if (this.lastConnectionEstablishedTime_) {\n // If we've been connected long enough, reset reconnect delay to minimum.\n const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n }\n this.lastConnectionEstablishedTime_ = null;\n }\n const timeSinceLastConnectAttempt = Math.max(0, new Date().getTime() - this.lastConnectionAttemptTime_);\n let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);\n reconnectDelay = Math.random() * reconnectDelay;\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\n this.scheduleConnect_(reconnectDelay);\n // Adjust reconnect delay for next time.\n this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);\n }\n this.onConnectStatus_(false);\n }\n async establishConnection_() {\n if (this.shouldReconnect_()) {\n this.log_('Making a connection attempt');\n this.lastConnectionAttemptTime_ = new Date().getTime();\n this.lastConnectionEstablishedTime_ = null;\n const onDataMessage = this.onDataMessage_.bind(this);\n const onReady = this.onReady_.bind(this);\n const onDisconnect = this.onRealtimeDisconnect_.bind(this);\n const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;\n const lastSessionId = this.lastSessionId;\n let canceled = false;\n let connection = null;\n const closeFn = function () {\n if (connection) {\n connection.close();\n }\n else {\n canceled = true;\n onDisconnect();\n }\n };\n const sendRequestFn = function (msg) {\n util.assert(connection, \"sendRequest call when we're not connected not allowed.\");\n connection.sendRequest(msg);\n };\n this.realtime_ = {\n close: closeFn,\n sendRequest: sendRequestFn\n };\n const forceRefresh = this.forceTokenRefresh_;\n this.forceTokenRefresh_ = false;\n try {\n // First fetch auth and app check token, and establish connection after\n // fetching the token was successful\n const [authToken, appCheckToken] = await Promise.all([\n this.authTokenProvider_.getToken(forceRefresh),\n this.appCheckTokenProvider_.getToken(forceRefresh)\n ]);\n if (!canceled) {\n log('getToken() completed. Creating connection.');\n this.authToken_ = authToken && authToken.accessToken;\n this.appCheckToken_ = appCheckToken && appCheckToken.token;\n connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect, \n /* onKill= */ reason => {\n warn(reason + ' (' + this.repoInfo_.toString() + ')');\n this.interrupt(SERVER_KILL_INTERRUPT_REASON);\n }, lastSessionId);\n }\n else {\n log('getToken() completed but was canceled');\n }\n }\n catch (error) {\n this.log_('Failed to get token: ' + error);\n if (!canceled) {\n if (this.repoInfo_.nodeAdmin) {\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\n // But getToken() may also just have temporarily failed, so we still want to\n // continue retrying.\n warn(error);\n }\n closeFn();\n }\n }\n }\n }\n interrupt(reason) {\n log('Interrupting connection for reason: ' + reason);\n this.interruptReasons_[reason] = true;\n if (this.realtime_) {\n this.realtime_.close();\n }\n else {\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n this.establishConnectionTimer_ = null;\n }\n if (this.connected_) {\n this.onRealtimeDisconnect_();\n }\n }\n }\n resume(reason) {\n log('Resuming connection for reason: ' + reason);\n delete this.interruptReasons_[reason];\n if (util.isEmpty(this.interruptReasons_)) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n }\n handleTimestamp_(timestamp) {\n const delta = timestamp - new Date().getTime();\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\n }\n cancelSentTransactions_() {\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\n const put = this.outstandingPuts_[i];\n if (put && /*hash*/ 'h' in put.request && put.queued) {\n if (put.onComplete) {\n put.onComplete('disconnect');\n }\n delete this.outstandingPuts_[i];\n this.outstandingPutCount_--;\n }\n }\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0) {\n this.outstandingPuts_ = [];\n }\n }\n onListenRevoked_(pathString, query) {\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\n let queryId;\n if (!query) {\n queryId = 'default';\n }\n else {\n queryId = query.map(q => ObjectToUniqueKey(q)).join('$');\n }\n const listen = this.removeListen_(pathString, queryId);\n if (listen && listen.onComplete) {\n listen.onComplete('permission_denied');\n }\n }\n removeListen_(pathString, queryId) {\n const normalizedPathString = new Path(pathString).toString(); // normalize path.\n let listen;\n if (this.listens.has(normalizedPathString)) {\n const map = this.listens.get(normalizedPathString);\n listen = map.get(queryId);\n map.delete(queryId);\n if (map.size === 0) {\n this.listens.delete(normalizedPathString);\n }\n }\n else {\n // all listens for this path has already been removed\n listen = undefined;\n }\n return listen;\n }\n onAuthRevoked_(statusCode, explanation) {\n log('Auth token revoked: ' + statusCode + '/' + explanation);\n this.authToken_ = null;\n this.forceTokenRefresh_ = true;\n this.realtime_.close();\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAuthTokenCount_++;\n if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\n // Set a long reconnect delay because recovery is unlikely\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n // Notify the auth token provider that the token is invalid, which will log\n // a warning\n this.authTokenProvider_.notifyForInvalidToken();\n }\n }\n }\n onAppCheckRevoked_(statusCode, explanation) {\n log('App check token revoked: ' + statusCode + '/' + explanation);\n this.appCheckToken_ = null;\n this.forceTokenRefresh_ = true;\n // Note: We don't close the connection as the developer may not have\n // enforcement enabled. The backend closes connections with enforcements.\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAppCheckTokenCount_++;\n if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\n this.appCheckTokenProvider_.notifyForInvalidToken();\n }\n }\n }\n onSecurityDebugPacket_(body) {\n if (this.securityDebugCallback_) {\n this.securityDebugCallback_(body);\n }\n else {\n if ('msg' in body) {\n console.log('FIREBASE: ' + body['msg'].replace('\\n', '\\nFIREBASE: '));\n }\n }\n }\n restoreState_() {\n //Re-authenticate ourselves if we have a credential stored.\n this.tryAuth();\n this.tryAppCheck();\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\n // make sure to send listens before puts.\n for (const queries of this.listens.values()) {\n for (const listenSpec of queries.values()) {\n this.sendListen_(listenSpec);\n }\n }\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\n if (this.outstandingPuts_[i]) {\n this.sendPut_(i);\n }\n }\n while (this.onDisconnectRequestQueue_.length) {\n const request = this.onDisconnectRequestQueue_.shift();\n this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);\n }\n for (let i = 0; i < this.outstandingGets_.length; i++) {\n if (this.outstandingGets_[i]) {\n this.sendGet_(i);\n }\n }\n }\n /**\n * Sends client stats for first connection\n */\n sendConnectStats_() {\n const stats = {};\n let clientName = 'js';\n if (util.isNodeSdk()) {\n if (this.repoInfo_.nodeAdmin) {\n clientName = 'admin_node';\n }\n else {\n clientName = 'node';\n }\n }\n stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\\./g, '-')] = 1;\n if (util.isMobileCordova()) {\n stats['framework.cordova'] = 1;\n }\n else if (util.isReactNative()) {\n stats['framework.reactnative'] = 1;\n }\n this.reportStats(stats);\n }\n shouldReconnect_() {\n const online = OnlineMonitor.getInstance().currentlyOnline();\n return util.isEmpty(this.interruptReasons_) && online;\n }\n}\nPersistentConnection.nextPersistentConnectionId_ = 0;\n/**\n * Counter for number of connections created. Mainly used for tagging in the logs\n */\nPersistentConnection.nextConnectionId_ = 0;\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass NamedNode {\n constructor(name, node) {\n this.name = name;\n this.node = node;\n }\n static Wrap(name, node) {\n return new NamedNode(name, node);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass Index {\n /**\n * @returns A standalone comparison function for\n * this index\n */\n getCompare() {\n return this.compare.bind(this);\n }\n /**\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\n *\n *\n * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode\n */\n indexedValueChanged(oldNode, newNode) {\n const oldWrapped = new NamedNode(MIN_NAME, oldNode);\n const newWrapped = new NamedNode(MIN_NAME, newNode);\n return this.compare(oldWrapped, newWrapped) !== 0;\n }\n /**\n * @returns a node wrapper that will sort equal to or less than\n * any other node wrapper, using this index\n */\n minPost() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return NamedNode.MIN;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nlet __EMPTY_NODE;\nclass KeyIndex extends Index {\n static get __EMPTY_NODE() {\n return __EMPTY_NODE;\n }\n static set __EMPTY_NODE(val) {\n __EMPTY_NODE = val;\n }\n compare(a, b) {\n return nameCompare(a.name, b.name);\n }\n isDefinedOn(node) {\n // We could probably return true here (since every node has a key), but it's never called\n // so just leaving unimplemented for now.\n throw util.assertionError('KeyIndex.isDefinedOn not expected to be called.');\n }\n indexedValueChanged(oldNode, newNode) {\n return false; // The key for a node never changes.\n }\n minPost() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return NamedNode.MIN;\n }\n maxPost() {\n // TODO: This should really be created once and cached in a static property, but\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\n return new NamedNode(MAX_NAME, __EMPTY_NODE);\n }\n makePost(indexValue, name) {\n util.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\n return new NamedNode(indexValue, __EMPTY_NODE);\n }\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString() {\n return '.key';\n }\n}\nconst KEY_INDEX = new KeyIndex();\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An iterator over an LLRBNode.\n */\nclass SortedMapIterator {\n /**\n * @param node - Node to iterate.\n * @param isReverse_ - Whether or not to iterate in reverse\n */\n constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) {\n this.isReverse_ = isReverse_;\n this.resultGenerator_ = resultGenerator_;\n this.nodeStack_ = [];\n let cmp = 1;\n while (!node.isEmpty()) {\n node = node;\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse_) {\n cmp *= -1;\n }\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse_) {\n node = node.left;\n }\n else {\n node = node.right;\n }\n }\n else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\n this.nodeStack_.push(node);\n break;\n }\n else {\n // This node is greater than our start key, add it to the stack and move to the next one\n this.nodeStack_.push(node);\n if (this.isReverse_) {\n node = node.right;\n }\n else {\n node = node.left;\n }\n }\n }\n }\n getNext() {\n if (this.nodeStack_.length === 0) {\n return null;\n }\n let node = this.nodeStack_.pop();\n let result;\n if (this.resultGenerator_) {\n result = this.resultGenerator_(node.key, node.value);\n }\n else {\n result = { key: node.key, value: node.value };\n }\n if (this.isReverse_) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.right;\n }\n }\n else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.left;\n }\n }\n return result;\n }\n hasNext() {\n return this.nodeStack_.length > 0;\n }\n peek() {\n if (this.nodeStack_.length === 0) {\n return null;\n }\n const node = this.nodeStack_[this.nodeStack_.length - 1];\n if (this.resultGenerator_) {\n return this.resultGenerator_(node.key, node.value);\n }\n else {\n return { key: node.key, value: node.value };\n }\n }\n}\n/**\n * Represents a node in a Left-leaning Red-Black tree.\n */\nclass LLRBNode {\n /**\n * @param key - Key associated with this node.\n * @param value - Value associated with this node.\n * @param color - Whether this node is red.\n * @param left - Left child.\n * @param right - Right child.\n */\n constructor(key, value, color, left, right) {\n this.key = key;\n this.value = value;\n this.color = color != null ? color : LLRBNode.RED;\n this.left =\n left != null ? left : SortedMap.EMPTY_NODE;\n this.right =\n right != null ? right : SortedMap.EMPTY_NODE;\n }\n /**\n * Returns a copy of the current node, optionally replacing pieces of it.\n *\n * @param key - New key for the node, or null.\n * @param value - New value for the node, or null.\n * @param color - New color for the node, or null.\n * @param left - New left child for the node, or null.\n * @param right - New right child for the node, or null.\n * @returns The node copy.\n */\n copy(key, value, color, left, right) {\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\n }\n /**\n * @returns The total number of nodes in the tree.\n */\n count() {\n return this.left.count() + 1 + this.right.count();\n }\n /**\n * @returns True if the tree is empty.\n */\n isEmpty() {\n return false;\n }\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n inorderTraversal(action) {\n return (this.left.inorderTraversal(action) ||\n !!action(this.key, this.value) ||\n this.right.inorderTraversal(action));\n }\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n reverseTraversal(action) {\n return (this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action));\n }\n /**\n * @returns The minimum node in the tree.\n */\n min_() {\n if (this.left.isEmpty()) {\n return this;\n }\n else {\n return this.left.min_();\n }\n }\n /**\n * @returns The maximum key in the tree.\n */\n minKey() {\n return this.min_().key;\n }\n /**\n * @returns The maximum key in the tree.\n */\n maxKey() {\n if (this.right.isEmpty()) {\n return this.key;\n }\n else {\n return this.right.maxKey();\n }\n }\n /**\n * @param key - Key to insert.\n * @param value - Value to insert.\n * @param comparator - Comparator.\n * @returns New tree, with the key/value added.\n */\n insert(key, value, comparator) {\n let n = this;\n const cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n }\n else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n }\n else {\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\n }\n return n.fixUp_();\n }\n /**\n * @returns New tree, with the minimum key removed.\n */\n removeMin_() {\n if (this.left.isEmpty()) {\n return SortedMap.EMPTY_NODE;\n }\n let n = this;\n if (!n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, n.left.removeMin_(), null);\n return n.fixUp_();\n }\n /**\n * @param key - The key of the item to remove.\n * @param comparator - Comparator.\n * @returns New tree, with the specified item removed.\n */\n remove(key, comparator) {\n let n, smallest;\n n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n }\n else {\n if (n.left.isRed_()) {\n n = n.rotateRight_();\n }\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\n n = n.moveRedRight_();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return SortedMap.EMPTY_NODE;\n }\n else {\n smallest = n.right.min_();\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp_();\n }\n /**\n * @returns Whether this is a RED node.\n */\n isRed_() {\n return this.color;\n }\n /**\n * @returns New tree after performing any needed rotations.\n */\n fixUp_() {\n let n = this;\n if (n.right.isRed_() && !n.left.isRed_()) {\n n = n.rotateLeft_();\n }\n if (n.left.isRed_() && n.left.left.isRed_()) {\n n = n.rotateRight_();\n }\n if (n.left.isRed_() && n.right.isRed_()) {\n n = n.colorFlip_();\n }\n return n;\n }\n /**\n * @returns New tree, after moveRedLeft.\n */\n moveRedLeft_() {\n let n = this.colorFlip_();\n if (n.right.left.isRed_()) {\n n = n.copy(null, null, null, null, n.right.rotateRight_());\n n = n.rotateLeft_();\n n = n.colorFlip_();\n }\n return n;\n }\n /**\n * @returns New tree, after moveRedRight.\n */\n moveRedRight_() {\n let n = this.colorFlip_();\n if (n.left.left.isRed_()) {\n n = n.rotateRight_();\n n = n.colorFlip_();\n }\n return n;\n }\n /**\n * @returns New tree, after rotateLeft.\n */\n rotateLeft_() {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null);\n }\n /**\n * @returns New tree, after rotateRight.\n */\n rotateRight_() {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr);\n }\n /**\n * @returns Newt ree, after colorFlip.\n */\n colorFlip_() {\n const left = this.left.copy(null, null, !this.left.color, null, null);\n const right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n }\n /**\n * For testing.\n *\n * @returns True if all is well.\n */\n checkMaxDepth_() {\n const blackDepth = this.check_();\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\n }\n check_() {\n if (this.isRed_() && this.left.isRed_()) {\n throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed_()) {\n throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n const blackDepth = this.left.check_();\n if (blackDepth !== this.right.check_()) {\n throw new Error('Black depths differ');\n }\n else {\n return blackDepth + (this.isRed_() ? 0 : 1);\n }\n }\n}\nLLRBNode.RED = true;\nLLRBNode.BLACK = false;\n/**\n * Represents an empty node (a leaf node in the Red-Black Tree).\n */\nclass LLRBEmptyNode {\n /**\n * Returns a copy of the current node.\n *\n * @returns The node copy.\n */\n copy(key, value, color, left, right) {\n return this;\n }\n /**\n * Returns a copy of the tree, with the specified key/value added.\n *\n * @param key - Key to be added.\n * @param value - Value to be added.\n * @param comparator - Comparator.\n * @returns New tree, with item added.\n */\n insert(key, value, comparator) {\n return new LLRBNode(key, value, null);\n }\n /**\n * Returns a copy of the tree, with the specified key removed.\n *\n * @param key - The key to remove.\n * @param comparator - Comparator.\n * @returns New tree, with item removed.\n */\n remove(key, comparator) {\n return this;\n }\n /**\n * @returns The total number of nodes in the tree.\n */\n count() {\n return 0;\n }\n /**\n * @returns True if the tree is empty.\n */\n isEmpty() {\n return true;\n }\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n inorderTraversal(action) {\n return false;\n }\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n reverseTraversal(action) {\n return false;\n }\n minKey() {\n return null;\n }\n maxKey() {\n return null;\n }\n check_() {\n return 0;\n }\n /**\n * @returns Whether this node is red.\n */\n isRed_() {\n return false;\n }\n}\n/**\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\n * tree.\n */\nclass SortedMap {\n /**\n * @param comparator_ - Key comparator.\n * @param root_ - Optional root node for the map.\n */\n constructor(comparator_, root_ = SortedMap.EMPTY_NODE) {\n this.comparator_ = comparator_;\n this.root_ = root_;\n }\n /**\n * Returns a copy of the map, with the specified key/value added or replaced.\n * (TODO: We should perhaps rename this method to 'put')\n *\n * @param key - Key to be added.\n * @param value - Value to be added.\n * @returns New map, with item added.\n */\n insert(key, value) {\n return new SortedMap(this.comparator_, this.root_\n .insert(key, value, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null));\n }\n /**\n * Returns a copy of the map, with the specified key removed.\n *\n * @param key - The key to remove.\n * @returns New map, with item removed.\n */\n remove(key) {\n return new SortedMap(this.comparator_, this.root_\n .remove(key, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null));\n }\n /**\n * Returns the value of the node with the given key, or null.\n *\n * @param key - The key to look up.\n * @returns The value of the node with the given key, or null if the\n * key doesn't exist.\n */\n get(key) {\n let cmp;\n let node = this.root_;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n return node.value;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n }\n /**\n * Returns the key of the item *before* the specified key, or null if key is the first item.\n * @param key - The key to find the predecessor of\n * @returns The predecessor key.\n */\n getPredecessorKey(key) {\n let cmp, node = this.root_, rightParent = null;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n if (!node.left.isEmpty()) {\n node = node.left;\n while (!node.right.isEmpty()) {\n node = node.right;\n }\n return node.key;\n }\n else if (rightParent) {\n return rightParent.key;\n }\n else {\n return null; // first item.\n }\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');\n }\n /**\n * @returns True if the map is empty.\n */\n isEmpty() {\n return this.root_.isEmpty();\n }\n /**\n * @returns The total number of nodes in the map.\n */\n count() {\n return this.root_.count();\n }\n /**\n * @returns The minimum key in the map.\n */\n minKey() {\n return this.root_.minKey();\n }\n /**\n * @returns The maximum key in the map.\n */\n maxKey() {\n return this.root_.maxKey();\n }\n /**\n * Traverses the map in key order and calls the specified action function\n * for each key/value pair.\n *\n * @param action - Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @returns The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n inorderTraversal(action) {\n return this.root_.inorderTraversal(action);\n }\n /**\n * Traverses the map in reverse key order and calls the specified action function\n * for each key/value pair.\n *\n * @param action - Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @returns True if the traversal was aborted.\n */\n reverseTraversal(action) {\n return this.root_.reverseTraversal(action);\n }\n /**\n * Returns an iterator over the SortedMap.\n * @returns The iterator.\n */\n getIterator(resultGenerator) {\n return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);\n }\n getIteratorFrom(key, resultGenerator) {\n return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);\n }\n getReverseIteratorFrom(key, resultGenerator) {\n return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);\n }\n getReverseIterator(resultGenerator) {\n return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);\n }\n}\n/**\n * Always use the same empty node, to reduce memory.\n */\nSortedMap.EMPTY_NODE = new LLRBEmptyNode();\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction NAME_ONLY_COMPARATOR(left, right) {\n return nameCompare(left.name, right.name);\n}\nfunction NAME_COMPARATOR(left, right) {\n return nameCompare(left, right);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nlet MAX_NODE$2;\nfunction setMaxNode$1(val) {\n MAX_NODE$2 = val;\n}\nconst priorityHashText = function (priority) {\n if (typeof priority === 'number') {\n return 'number:' + doubleToIEEE754String(priority);\n }\n else {\n return 'string:' + priority;\n }\n};\n/**\n * Validates that a priority snapshot Node is valid.\n */\nconst validatePriorityNode = function (priorityNode) {\n if (priorityNode.isLeafNode()) {\n const val = priorityNode.val();\n util.assert(typeof val === 'string' ||\n typeof val === 'number' ||\n (typeof val === 'object' && util.contains(val, '.sv')), 'Priority must be a string or number.');\n }\n else {\n util.assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');\n }\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\n util.assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), \"Priority nodes can't have a priority of their own.\");\n};\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nlet __childrenNodeConstructor;\n/**\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\n * implements Node and stores the value of the node (a string,\n * number, or boolean) accessible via getValue().\n */\nclass LeafNode {\n static set __childrenNodeConstructor(val) {\n __childrenNodeConstructor = val;\n }\n static get __childrenNodeConstructor() {\n return __childrenNodeConstructor;\n }\n /**\n * @param value_ - The value to store in this leaf node. The object type is\n * possible in the event of a deferred value\n * @param priorityNode_ - The priority of this node.\n */\n constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\n this.value_ = value_;\n this.priorityNode_ = priorityNode_;\n this.lazyHash_ = null;\n util.assert(this.value_ !== undefined && this.value_ !== null, \"LeafNode shouldn't be created with null/undefined value.\");\n validatePriorityNode(this.priorityNode_);\n }\n /** @inheritDoc */\n isLeafNode() {\n return true;\n }\n /** @inheritDoc */\n getPriority() {\n return this.priorityNode_;\n }\n /** @inheritDoc */\n updatePriority(newPriorityNode) {\n return new LeafNode(this.value_, newPriorityNode);\n }\n /** @inheritDoc */\n getImmediateChild(childName) {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.priorityNode_;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n }\n /** @inheritDoc */\n getChild(path) {\n if (pathIsEmpty(path)) {\n return this;\n }\n else if (pathGetFront(path) === '.priority') {\n return this.priorityNode_;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n }\n hasChild() {\n return false;\n }\n /** @inheritDoc */\n getPredecessorChildName(childName, childNode) {\n return null;\n }\n /** @inheritDoc */\n updateImmediateChild(childName, newChildNode) {\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n }\n else if (newChildNode.isEmpty() && childName !== '.priority') {\n return this;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);\n }\n }\n /** @inheritDoc */\n updateChild(path, newChildNode) {\n const front = pathGetFront(path);\n if (front === null) {\n return newChildNode;\n }\n else if (newChildNode.isEmpty() && front !== '.priority') {\n return this;\n }\n else {\n util.assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');\n return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));\n }\n }\n /** @inheritDoc */\n isEmpty() {\n return false;\n }\n /** @inheritDoc */\n numChildren() {\n return 0;\n }\n /** @inheritDoc */\n forEachChild(index, action) {\n return false;\n }\n val(exportFormat) {\n if (exportFormat && !this.getPriority().isEmpty()) {\n return {\n '.value': this.getValue(),\n '.priority': this.getPriority().val()\n };\n }\n else {\n return this.getValue();\n }\n }\n /** @inheritDoc */\n hash() {\n if (this.lazyHash_ === null) {\n let toHash = '';\n if (!this.priorityNode_.isEmpty()) {\n toHash +=\n 'priority:' +\n priorityHashText(this.priorityNode_.val()) +\n ':';\n }\n const type = typeof this.value_;\n toHash += type + ':';\n if (type === 'number') {\n toHash += doubleToIEEE754String(this.value_);\n }\n else {\n toHash += this.value_;\n }\n this.lazyHash_ = sha1(toHash);\n }\n return this.lazyHash_;\n }\n /**\n * Returns the value of the leaf node.\n * @returns The value of the node.\n */\n getValue() {\n return this.value_;\n }\n compareTo(other) {\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\n return 1;\n }\n else if (other instanceof LeafNode.__childrenNodeConstructor) {\n return -1;\n }\n else {\n util.assert(other.isLeafNode(), 'Unknown node type');\n return this.compareToLeafNode_(other);\n }\n }\n /**\n * Comparison specifically for two leaf nodes\n */\n compareToLeafNode_(otherLeaf) {\n const otherLeafType = typeof otherLeaf.value_;\n const thisLeafType = typeof this.value_;\n const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\n const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\n util.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\n util.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\n if (otherIndex === thisIndex) {\n // Same type, compare values\n if (thisLeafType === 'object') {\n // Deferred value nodes are all equal, but we should also never get to this point...\n return 0;\n }\n else {\n // Note that this works because true > false, all others are number or string comparisons\n if (this.value_ < otherLeaf.value_) {\n return -1;\n }\n else if (this.value_ === otherLeaf.value_) {\n return 0;\n }\n else {\n return 1;\n }\n }\n }\n else {\n return thisIndex - otherIndex;\n }\n }\n withIndex() {\n return this;\n }\n isIndexed() {\n return true;\n }\n equals(other) {\n if (other === this) {\n return true;\n }\n else if (other.isLeafNode()) {\n const otherLeaf = other;\n return (this.value_ === otherLeaf.value_ &&\n this.priorityNode_.equals(otherLeaf.priorityNode_));\n }\n else {\n return false;\n }\n }\n}\n/**\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\n * the same type, the comparison falls back to their value\n */\nLeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nlet nodeFromJSON$1;\nlet MAX_NODE$1;\nfunction setNodeFromJSON(val) {\n nodeFromJSON$1 = val;\n}\nfunction setMaxNode(val) {\n MAX_NODE$1 = val;\n}\nclass PriorityIndex extends Index {\n compare(a, b) {\n const aPriority = a.node.getPriority();\n const bPriority = b.node.getPriority();\n const indexCmp = aPriority.compareTo(bPriority);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n }\n isDefinedOn(node) {\n return !node.getPriority().isEmpty();\n }\n indexedValueChanged(oldNode, newNode) {\n return !oldNode.getPriority().equals(newNode.getPriority());\n }\n minPost() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return NamedNode.MIN;\n }\n maxPost() {\n return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));\n }\n makePost(indexValue, name) {\n const priorityNode = nodeFromJSON$1(indexValue);\n return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));\n }\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString() {\n return '.priority';\n }\n}\nconst PRIORITY_INDEX = new PriorityIndex();\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst LOG_2 = Math.log(2);\nclass Base12Num {\n constructor(length) {\n const logBase2 = (num) => \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parseInt((Math.log(num) / LOG_2), 10);\n const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2);\n this.count = logBase2(length + 1);\n this.current_ = this.count - 1;\n const mask = bitMask(this.count);\n this.bits_ = (length + 1) & mask;\n }\n nextBitIsOne() {\n //noinspection JSBitwiseOperatorUsage\n const result = !(this.bits_ & (0x1 << this.current_));\n this.current_--;\n return result;\n }\n}\n/**\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\n * function\n *\n * Uses the algorithm described in the paper linked here:\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\n *\n * @param childList - Unsorted list of children\n * @param cmp - The comparison method to be used\n * @param keyFn - An optional function to extract K from a node wrapper, if K's\n * type is not NamedNode\n * @param mapSortFn - An optional override for comparator used by the generated sorted map\n */\nconst buildChildSet = function (childList, cmp, keyFn, mapSortFn) {\n childList.sort(cmp);\n const buildBalancedTree = function (low, high) {\n const length = high - low;\n let namedNode;\n let key;\n if (length === 0) {\n return null;\n }\n else if (length === 1) {\n namedNode = childList[low];\n key = keyFn ? keyFn(namedNode) : namedNode;\n return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);\n }\n else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const middle = parseInt((length / 2), 10) + low;\n const left = buildBalancedTree(low, middle);\n const right = buildBalancedTree(middle + 1, high);\n namedNode = childList[middle];\n key = keyFn ? keyFn(namedNode) : namedNode;\n return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);\n }\n };\n const buildFrom12Array = function (base12) {\n let node = null;\n let root = null;\n let index = childList.length;\n const buildPennant = function (chunkSize, color) {\n const low = index - chunkSize;\n const high = index;\n index -= chunkSize;\n const childTree = buildBalancedTree(low + 1, high);\n const namedNode = childList[low];\n const key = keyFn ? keyFn(namedNode) : namedNode;\n attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));\n };\n const attachPennant = function (pennant) {\n if (node) {\n node.left = pennant;\n node = pennant;\n }\n else {\n root = pennant;\n node = pennant;\n }\n };\n for (let i = 0; i < base12.count; ++i) {\n const isOne = base12.nextBitIsOne();\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\n const chunkSize = Math.pow(2, base12.count - (i + 1));\n if (isOne) {\n buildPennant(chunkSize, LLRBNode.BLACK);\n }\n else {\n // current == 2\n buildPennant(chunkSize, LLRBNode.BLACK);\n buildPennant(chunkSize, LLRBNode.RED);\n }\n }\n return root;\n };\n const base12 = new Base12Num(childList.length);\n const root = buildFrom12Array(base12);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new SortedMap(mapSortFn || cmp, root);\n};\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nlet _defaultIndexMap;\nconst fallbackObject = {};\nclass IndexMap {\n /**\n * The default IndexMap for nodes without a priority\n */\n static get Default() {\n util.assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');\n _defaultIndexMap =\n _defaultIndexMap ||\n new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });\n return _defaultIndexMap;\n }\n constructor(indexes_, indexSet_) {\n this.indexes_ = indexes_;\n this.indexSet_ = indexSet_;\n }\n get(indexKey) {\n const sortedMap = util.safeGet(this.indexes_, indexKey);\n if (!sortedMap) {\n throw new Error('No index defined for ' + indexKey);\n }\n if (sortedMap instanceof SortedMap) {\n return sortedMap;\n }\n else {\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\n // regular child map\n return null;\n }\n }\n hasIndex(indexDefinition) {\n return util.contains(this.indexSet_, indexDefinition.toString());\n }\n addIndex(indexDefinition, existingChildren) {\n util.assert(indexDefinition !== KEY_INDEX, \"KeyIndex always exists and isn't meant to be added to the IndexMap.\");\n const childList = [];\n let sawIndexedValue = false;\n const iter = existingChildren.getIterator(NamedNode.Wrap);\n let next = iter.getNext();\n while (next) {\n sawIndexedValue =\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\n childList.push(next);\n next = iter.getNext();\n }\n let newIndex;\n if (sawIndexedValue) {\n newIndex = buildChildSet(childList, indexDefinition.getCompare());\n }\n else {\n newIndex = fallbackObject;\n }\n const indexName = indexDefinition.toString();\n const newIndexSet = { ...this.indexSet_ };\n newIndexSet[indexName] = indexDefinition;\n const newIndexes = { ...this.indexes_ };\n newIndexes[indexName] = newIndex;\n return new IndexMap(newIndexes, newIndexSet);\n }\n /**\n * Ensure that this node is properly tracked in any indexes that we're maintaining\n */\n addToIndexes(namedNode, existingChildren) {\n const newIndexes = util.map(this.indexes_, (indexedChildren, indexName) => {\n const index = util.safeGet(this.indexSet_, indexName);\n util.assert(index, 'Missing index implementation for ' + indexName);\n if (indexedChildren === fallbackObject) {\n // Check to see if we need to index everything\n if (index.isDefinedOn(namedNode.node)) {\n // We need to build this index\n const childList = [];\n const iter = existingChildren.getIterator(NamedNode.Wrap);\n let next = iter.getNext();\n while (next) {\n if (next.name !== namedNode.name) {\n childList.push(next);\n }\n next = iter.getNext();\n }\n childList.push(namedNode);\n return buildChildSet(childList, index.getCompare());\n }\n else {\n // No change, this remains a fallback\n return fallbackObject;\n }\n }\n else {\n const existingSnap = existingChildren.get(namedNode.name);\n let newChildren = indexedChildren;\n if (existingSnap) {\n newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));\n }\n return newChildren.insert(namedNode, namedNode.node);\n }\n });\n return new IndexMap(newIndexes, this.indexSet_);\n }\n /**\n * Create a new IndexMap instance with the given value removed\n */\n removeFromIndexes(namedNode, existingChildren) {\n const newIndexes = util.map(this.indexes_, (indexedChildren) => {\n if (indexedChildren === fallbackObject) {\n // This is the fallback. Just return it, nothing to do in this case\n return indexedChildren;\n }\n else {\n const existingSnap = existingChildren.get(namedNode.name);\n if (existingSnap) {\n return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));\n }\n else {\n // No record of this child\n return indexedChildren;\n }\n }\n });\n return new IndexMap(newIndexes, this.indexSet_);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\nlet EMPTY_NODE;\n/**\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\n * (i.e. nodes with children). It implements Node and stores the\n * list of children in the children property, sorted by child name.\n */\nclass ChildrenNode {\n static get EMPTY_NODE() {\n return (EMPTY_NODE ||\n (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));\n }\n /**\n * @param children_ - List of children of this node..\n * @param priorityNode_ - The priority of this node (as a snapshot node).\n */\n constructor(children_, priorityNode_, indexMap_) {\n this.children_ = children_;\n this.priorityNode_ = priorityNode_;\n this.indexMap_ = indexMap_;\n this.lazyHash_ = null;\n /**\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\n * class instead of an empty ChildrenNode.\n */\n if (this.priorityNode_) {\n validatePriorityNode(this.priorityNode_);\n }\n if (this.children_.isEmpty()) {\n util.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');\n }\n }\n /** @inheritDoc */\n isLeafNode() {\n return false;\n }\n /** @inheritDoc */\n getPriority() {\n return this.priorityNode_ || EMPTY_NODE;\n }\n /** @inheritDoc */\n updatePriority(newPriorityNode) {\n if (this.children_.isEmpty()) {\n // Don't allow priorities on empty nodes\n return this;\n }\n else {\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\n }\n }\n /** @inheritDoc */\n getImmediateChild(childName) {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.getPriority();\n }\n else {\n const child = this.children_.get(childName);\n return child === null ? EMPTY_NODE : child;\n }\n }\n /** @inheritDoc */\n getChild(path) {\n const front = pathGetFront(path);\n if (front === null) {\n return this;\n }\n return this.getImmediateChild(front).getChild(pathPopFront(path));\n }\n /** @inheritDoc */\n hasChild(childName) {\n return this.children_.get(childName) !== null;\n }\n /** @inheritDoc */\n updateImmediateChild(childName, newChildNode) {\n util.assert(newChildNode, 'We should always be passing snapshot nodes');\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n }\n else {\n const namedNode = new NamedNode(childName, newChildNode);\n let newChildren, newIndexMap;\n if (newChildNode.isEmpty()) {\n newChildren = this.children_.remove(childName);\n newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);\n }\n else {\n newChildren = this.children_.insert(childName, newChildNode);\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\n }\n const newPriority = newChildren.isEmpty()\n ? EMPTY_NODE\n : this.priorityNode_;\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\n }\n }\n /** @inheritDoc */\n updateChild(path, newChildNode) {\n const front = pathGetFront(path);\n if (front === null) {\n return newChildNode;\n }\n else {\n util.assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');\n const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);\n return this.updateImmediateChild(front, newImmediateChild);\n }\n }\n /** @inheritDoc */\n isEmpty() {\n return this.children_.isEmpty();\n }\n /** @inheritDoc */\n numChildren() {\n return this.children_.count();\n }\n /** @inheritDoc */\n val(exportFormat) {\n if (this.isEmpty()) {\n return null;\n }\n const obj = {};\n let numKeys = 0, maxKey = 0, allIntegerKeys = true;\n this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n obj[key] = childNode.val(exportFormat);\n numKeys++;\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\n maxKey = Math.max(maxKey, Number(key));\n }\n else {\n allIntegerKeys = false;\n }\n });\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\n // convert to array.\n const array = [];\n // eslint-disable-next-line guard-for-in\n for (const key in obj) {\n array[key] = obj[key];\n }\n return array;\n }\n else {\n if (exportFormat && !this.getPriority().isEmpty()) {\n obj['.priority'] = this.getPriority().val();\n }\n return obj;\n }\n }\n /** @inheritDoc */\n hash() {\n if (this.lazyHash_ === null) {\n let toHash = '';\n if (!this.getPriority().isEmpty()) {\n toHash +=\n 'priority:' +\n priorityHashText(this.getPriority().val()) +\n ':';\n }\n this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n const childHash = childNode.hash();\n if (childHash !== '') {\n toHash += ':' + key + ':' + childHash;\n }\n });\n this.lazyHash_ = toHash === '' ? '' : sha1(toHash);\n }\n return this.lazyHash_;\n }\n /** @inheritDoc */\n getPredecessorChildName(childName, childNode, index) {\n const idx = this.resolveIndex_(index);\n if (idx) {\n const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));\n return predecessor ? predecessor.name : null;\n }\n else {\n return this.children_.getPredecessorKey(childName);\n }\n }\n getFirstChildName(indexDefinition) {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n const minKey = idx.minKey();\n return minKey && minKey.name;\n }\n else {\n return this.children_.minKey();\n }\n }\n getFirstChild(indexDefinition) {\n const minKey = this.getFirstChildName(indexDefinition);\n if (minKey) {\n return new NamedNode(minKey, this.children_.get(minKey));\n }\n else {\n return null;\n }\n }\n /**\n * Given an index, return the key name of the largest value we have, according to that index\n */\n getLastChildName(indexDefinition) {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n const maxKey = idx.maxKey();\n return maxKey && maxKey.name;\n }\n else {\n return this.children_.maxKey();\n }\n }\n getLastChild(indexDefinition) {\n const maxKey = this.getLastChildName(indexDefinition);\n if (maxKey) {\n return new NamedNode(maxKey, this.children_.get(maxKey));\n }\n else {\n return null;\n }\n }\n forEachChild(index, action) {\n const idx = this.resolveIndex_(index);\n if (idx) {\n return idx.inorderTraversal(wrappedNode => {\n return action(wrappedNode.name, wrappedNode.node);\n });\n }\n else {\n return this.children_.inorderTraversal(action);\n }\n }\n getIterator(indexDefinition) {\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\n }\n getIteratorFrom(startPost, indexDefinition) {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getIteratorFrom(startPost, key => key);\n }\n else {\n const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);\n let next = iterator.peek();\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n }\n getReverseIterator(indexDefinition) {\n return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);\n }\n getReverseIteratorFrom(endPost, indexDefinition) {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getReverseIteratorFrom(endPost, key => {\n return key;\n });\n }\n else {\n const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);\n let next = iterator.peek();\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n }\n compareTo(other) {\n if (this.isEmpty()) {\n if (other.isEmpty()) {\n return 0;\n }\n else {\n return -1;\n }\n }\n else if (other.isLeafNode() || other.isEmpty()) {\n return 1;\n }\n else if (other === MAX_NODE) {\n return -1;\n }\n else {\n // Must be another node with children.\n return 0;\n }\n }\n withIndex(indexDefinition) {\n if (indexDefinition === KEY_INDEX ||\n this.indexMap_.hasIndex(indexDefinition)) {\n return this;\n }\n else {\n const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\n }\n }\n isIndexed(index) {\n return index === KEY_INDEX || this.indexMap_.hasIndex(index);\n }\n equals(other) {\n if (other === this) {\n return true;\n }\n else if (other.isLeafNode()) {\n return false;\n }\n else {\n const otherChildrenNode = other;\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\n return false;\n }\n else if (this.children_.count() === otherChildrenNode.children_.count()) {\n const thisIter = this.getIterator(PRIORITY_INDEX);\n const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);\n let thisCurrent = thisIter.getNext();\n let otherCurrent = otherIter.getNext();\n while (thisCurrent && otherCurrent) {\n if (thisCurrent.name !== otherCurrent.name ||\n !thisCurrent.node.equals(otherCurrent.node)) {\n return false;\n }\n thisCurrent = thisIter.getNext();\n otherCurrent = otherIter.getNext();\n }\n return thisCurrent === null && otherCurrent === null;\n }\n else {\n return false;\n }\n }\n }\n /**\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\n * instead.\n *\n */\n resolveIndex_(indexDefinition) {\n if (indexDefinition === KEY_INDEX) {\n return null;\n }\n else {\n return this.indexMap_.get(indexDefinition.toString());\n }\n }\n}\nChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\nclass MaxNode extends ChildrenNode {\n constructor() {\n super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default);\n }\n compareTo(other) {\n if (other === this) {\n return 0;\n }\n else {\n return 1;\n }\n }\n equals(other) {\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\n return other === this;\n }\n getPriority() {\n return this;\n }\n getImmediateChild(childName) {\n return ChildrenNode.EMPTY_NODE;\n }\n isEmpty() {\n return false;\n }\n}\n/**\n * Marker that will sort higher than any other snapshot.\n */\nconst MAX_NODE = new MaxNode();\nObject.defineProperties(NamedNode, {\n MIN: {\n value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)\n },\n MAX: {\n value: new NamedNode(MAX_NAME, MAX_NODE)\n }\n});\n/**\n * Reference Extensions\n */\nKeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\nLeafNode.__childrenNodeConstructor = ChildrenNode;\nsetMaxNode$1(MAX_NODE);\nsetMaxNode(MAX_NODE);\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst USE_HINZE = true;\n/**\n * Constructs a snapshot node representing the passed JSON and returns it.\n * @param json - JSON to create a node for.\n * @param priority - Optional priority to use. This will be ignored if the\n * passed JSON contains a .priority property.\n */\nfunction nodeFromJSON(json, priority = null) {\n if (json === null) {\n return ChildrenNode.EMPTY_NODE;\n }\n if (typeof json === 'object' && '.priority' in json) {\n priority = json['.priority'];\n }\n util.assert(priority === null ||\n typeof priority === 'string' ||\n typeof priority === 'number' ||\n (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\n json = json['.value'];\n }\n // Valid leaf nodes include non-objects or server-value wrapper objects\n if (typeof json !== 'object' || '.sv' in json) {\n const jsonLeaf = json;\n return new LeafNode(jsonLeaf, nodeFromJSON(priority));\n }\n if (!(json instanceof Array) && USE_HINZE) {\n const children = [];\n let childrenHavePriority = false;\n const hinzeJsonObj = json;\n each(hinzeJsonObj, (key, child) => {\n if (key.substring(0, 1) !== '.') {\n // Ignore metadata nodes\n const childNode = nodeFromJSON(child);\n if (!childNode.isEmpty()) {\n childrenHavePriority =\n childrenHavePriority || !childNode.getPriority().isEmpty();\n children.push(new NamedNode(key, childNode));\n }\n }\n });\n if (children.length === 0) {\n return ChildrenNode.EMPTY_NODE;\n }\n const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR);\n if (childrenHavePriority) {\n const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare());\n return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));\n }\n else {\n return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);\n }\n }\n else {\n let node = ChildrenNode.EMPTY_NODE;\n each(json, (key, childData) => {\n if (util.contains(json, key)) {\n if (key.substring(0, 1) !== '.') {\n // ignore metadata nodes.\n const childNode = nodeFromJSON(childData);\n if (childNode.isLeafNode() || !childNode.isEmpty()) {\n node = node.updateImmediateChild(key, childNode);\n }\n }\n }\n });\n return node.updatePriority(nodeFromJSON(priority));\n }\n}\nsetNodeFromJSON(nodeFromJSON);\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass PathIndex extends Index {\n constructor(indexPath_) {\n super();\n this.indexPath_ = indexPath_;\n util.assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', \"Can't create PathIndex with empty path or .priority key\");\n }\n extractChild(snap) {\n return snap.getChild(this.indexPath_);\n }\n isDefinedOn(node) {\n return !node.getChild(this.indexPath_).isEmpty();\n }\n compare(a, b) {\n const aChild = this.extractChild(a.node);\n const bChild = this.extractChild(b.node);\n const indexCmp = aChild.compareTo(bChild);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n }\n makePost(indexValue, name) {\n const valueNode = nodeFromJSON(indexValue);\n const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);\n return new NamedNode(name, node);\n }\n maxPost() {\n const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);\n return new NamedNode(MAX_NAME, node);\n }\n toString() {\n return pathSlice(this.indexPath_, 0).join('/');\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass ValueIndex extends Index {\n compare(a, b) {\n const indexCmp = a.node.compareTo(b.node);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n }\n isDefinedOn(node) {\n return true;\n }\n indexedValueChanged(oldNode, newNode) {\n return !oldNode.equals(newNode);\n }\n minPost() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return NamedNode.MIN;\n }\n maxPost() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return NamedNode.MAX;\n }\n makePost(indexValue, name) {\n const valueNode = nodeFromJSON(indexValue);\n return new NamedNode(name, valueNode);\n }\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString() {\n return '.value';\n }\n}\nconst VALUE_INDEX = new ValueIndex();\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction changeValue(snapshotNode) {\n return { type: \"value\" /* ChangeType.VALUE */, snapshotNode };\n}\nfunction changeChildAdded(childName, snapshotNode) {\n return { type: \"child_added\" /* ChangeType.CHILD_ADDED */, snapshotNode, childName };\n}\nfunction changeChildRemoved(childName, snapshotNode) {\n return { type: \"child_removed\" /* ChangeType.CHILD_REMOVED */, snapshotNode, childName };\n}\nfunction changeChildChanged(childName, snapshotNode, oldSnap) {\n return {\n type: \"child_changed\" /* ChangeType.CHILD_CHANGED */,\n snapshotNode,\n childName,\n oldSnap\n };\n}\nfunction changeChildMoved(childName, snapshotNode) {\n return { type: \"child_moved\" /* ChangeType.CHILD_MOVED */, snapshotNode, childName };\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\n */\nclass IndexedFilter {\n constructor(index_) {\n this.index_ = index_;\n }\n updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n util.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');\n const oldChild = snap.getImmediateChild(key);\n // Check if anything actually changed.\n if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\n // to avoid treating these cases as \"nothing changed.\"\n if (oldChild.isEmpty() === newChild.isEmpty()) {\n // Nothing changed.\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\n return snap;\n }\n }\n if (optChangeAccumulator != null) {\n if (newChild.isEmpty()) {\n if (snap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));\n }\n else {\n util.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');\n }\n }\n else if (oldChild.isEmpty()) {\n optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));\n }\n else {\n optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));\n }\n }\n if (snap.isLeafNode() && newChild.isEmpty()) {\n return snap;\n }\n else {\n // Make sure the node is indexed\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\n }\n }\n updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\n if (optChangeAccumulator != null) {\n if (!oldSnap.isLeafNode()) {\n oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (!newSnap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));\n }\n });\n }\n if (!newSnap.isLeafNode()) {\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (oldSnap.hasChild(key)) {\n const oldChild = oldSnap.getImmediateChild(key);\n if (!oldChild.equals(childNode)) {\n optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));\n }\n }\n else {\n optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));\n }\n });\n }\n }\n return newSnap.withIndex(this.index_);\n }\n updatePriority(oldSnap, newPriority) {\n if (oldSnap.isEmpty()) {\n return ChildrenNode.EMPTY_NODE;\n }\n else {\n return oldSnap.updatePriority(newPriority);\n }\n }\n filtersNodes() {\n return false;\n }\n getIndexedFilter() {\n return this;\n }\n getIndex() {\n return this.index_;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n */\nclass RangedFilter {\n constructor(params) {\n this.indexedFilter_ = new IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n this.startIsInclusive_ = !params.startAfterSet_;\n this.endIsInclusive_ = !params.endBeforeSet_;\n }\n getStartPost() {\n return this.startPost_;\n }\n getEndPost() {\n return this.endPost_;\n }\n matches(node) {\n const isWithinStart = this.startIsInclusive_\n ? this.index_.compare(this.getStartPost(), node) <= 0\n : this.index_.compare(this.getStartPost(), node) < 0;\n const isWithinEnd = this.endIsInclusive_\n ? this.index_.compare(node, this.getEndPost()) <= 0\n : this.index_.compare(node, this.getEndPost()) < 0;\n return isWithinStart && isWithinEnd;\n }\n updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.matches(new NamedNode(key, newChild))) {\n newChild = ChildrenNode.EMPTY_NODE;\n }\n return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n }\n updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode.EMPTY_NODE;\n }\n let filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\n const self = this;\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (!self.matches(new NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\n }\n updatePriority(oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n }\n filtersNodes() {\n return true;\n }\n getIndexedFilter() {\n return this.indexedFilter_;\n }\n getIndex() {\n return this.index_;\n }\n static getStartPost_(params) {\n if (params.hasStart()) {\n const startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n }\n else {\n return params.getIndex().minPost();\n }\n }\n static getEndPost_(params) {\n if (params.hasEnd()) {\n const endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n }\n else {\n return params.getIndex().maxPost();\n }\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n */\nclass LimitedFilter {\n constructor(params) {\n this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);\n this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);\n this.withinStartPost = (node) => {\n const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node);\n return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;\n };\n this.withinEndPost = (node) => {\n const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost());\n return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;\n };\n this.rangedFilter_ = new RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n this.startIsInclusive_ = !params.startAfterSet_;\n this.endIsInclusive_ = !params.endBeforeSet_;\n }\n updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {\n newChild = ChildrenNode.EMPTY_NODE;\n }\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n }\n else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_\n .getIndexedFilter()\n .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n }\n else {\n return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\n }\n }\n updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\n let filtered;\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n }\n else {\n if (this.limit_ * 2 < newSnap.numChildren() &&\n newSnap.isIndexed(this.index_)) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n // anchor to the startPost, endPost, or last element as appropriate\n let iterator;\n if (this.reverse_) {\n iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\n }\n else {\n iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\n }\n let count = 0;\n while (iterator.hasNext() && count < this.limit_) {\n const next = iterator.getNext();\n if (!this.withinDirectionalStart(next)) {\n // if we have not reached the start, skip to the next element\n continue;\n }\n else if (!this.withinDirectionalEnd(next)) {\n // if we have reached the end, stop adding elements\n break;\n }\n else {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\n }\n }\n }\n else {\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\n let iterator;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n }\n else {\n iterator = filtered.getIterator(this.index_);\n }\n let count = 0;\n while (iterator.hasNext()) {\n const next = iterator.getNext();\n const inRange = count < this.limit_ &&\n this.withinDirectionalStart(next) &&\n this.withinDirectionalEnd(next);\n if (inRange) {\n count++;\n }\n else {\n filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);\n }\n }\n }\n }\n return this.rangedFilter_\n .getIndexedFilter()\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n }\n updatePriority(oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n }\n filtersNodes() {\n return true;\n }\n getIndexedFilter() {\n return this.rangedFilter_.getIndexedFilter();\n }\n getIndex() {\n return this.index_;\n }\n fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) {\n // TODO: rename all cache stuff etc to general snap terminology\n let cmp;\n if (this.reverse_) {\n const indexCmp = this.index_.getCompare();\n cmp = (a, b) => indexCmp(b, a);\n }\n else {\n cmp = this.index_.getCompare();\n }\n const oldEventCache = snap;\n util.assert(oldEventCache.numChildren() === this.limit_, '');\n const newChildNamedNode = new NamedNode(childKey, childSnap);\n const windowBoundary = this.reverse_\n ? oldEventCache.getFirstChild(this.index_)\n : oldEventCache.getLastChild(this.index_);\n const inRange = this.rangedFilter_.matches(newChildNamedNode);\n if (oldEventCache.hasChild(childKey)) {\n const oldChildSnap = oldEventCache.getImmediateChild(childKey);\n let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\n while (nextChild != null &&\n (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\n // the limited filter...\n nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\n }\n const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n }\n else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));\n }\n const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);\n const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));\n }\n return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\n }\n else {\n return newEventCache;\n }\n }\n }\n else if (childSnap.isEmpty()) {\n // we're deleting a node, but it was not in the window, so ignore it\n return snap;\n }\n else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));\n changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));\n }\n return oldEventCache\n .updateImmediateChild(childKey, childSnap)\n .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);\n }\n else {\n return snap;\n }\n }\n else {\n return snap;\n }\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\n * user-facing API level, so it is not done here.\n *\n * @internal\n */\nclass QueryParams {\n constructor() {\n this.limitSet_ = false;\n this.startSet_ = false;\n this.startNameSet_ = false;\n this.startAfterSet_ = false; // can only be true if startSet_ is true\n this.endSet_ = false;\n this.endNameSet_ = false;\n this.endBeforeSet_ = false; // can only be true if endSet_ is true\n this.limit_ = 0;\n this.viewFrom_ = '';\n this.indexStartValue_ = null;\n this.indexStartName_ = '';\n this.indexEndValue_ = null;\n this.indexEndName_ = '';\n this.index_ = PRIORITY_INDEX;\n }\n hasStart() {\n return this.startSet_;\n }\n /**\n * @returns True if it would return from left.\n */\n isViewFromLeft() {\n if (this.viewFrom_ === '') {\n // limit(), rather than limitToFirst or limitToLast was called.\n // This means that only one of startSet_ and endSet_ is true. Use them\n // to calculate which side of the view to anchor to. If neither is set,\n // anchor to the end.\n return this.startSet_;\n }\n else {\n return this.viewFrom_ === \"l\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;\n }\n }\n /**\n * Only valid to call if hasStart() returns true\n */\n getIndexStartValue() {\n util.assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n }\n /**\n * Only valid to call if hasStart() returns true.\n * Returns the starting key name for the range defined by these query parameters\n */\n getIndexStartName() {\n util.assert(this.startSet_, 'Only valid if start has been set');\n if (this.startNameSet_) {\n return this.indexStartName_;\n }\n else {\n return MIN_NAME;\n }\n }\n hasEnd() {\n return this.endSet_;\n }\n /**\n * Only valid to call if hasEnd() returns true.\n */\n getIndexEndValue() {\n util.assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n }\n /**\n * Only valid to call if hasEnd() returns true.\n * Returns the end key name for the range defined by these query parameters\n */\n getIndexEndName() {\n util.assert(this.endSet_, 'Only valid if end has been set');\n if (this.endNameSet_) {\n return this.indexEndName_;\n }\n else {\n return MAX_NAME;\n }\n }\n hasLimit() {\n return this.limitSet_;\n }\n /**\n * @returns True if a limit has been set and it has been explicitly anchored\n */\n hasAnchoredLimit() {\n return this.limitSet_ && this.viewFrom_ !== '';\n }\n /**\n * Only valid to call if hasLimit() returns true\n */\n getLimit() {\n util.assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n }\n getIndex() {\n return this.index_;\n }\n loadsAllData() {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n }\n isDefault() {\n return this.loadsAllData() && this.index_ === PRIORITY_INDEX;\n }\n copy() {\n const copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.startAfterSet_ = this.startAfterSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.endBeforeSet_ = this.endBeforeSet_;\n copy.indexEndValue_ = this.indexEndValue_;\n copy.endNameSet_ = this.endNameSet_;\n copy.indexEndName_ = this.indexEndName_;\n copy.index_ = this.index_;\n copy.viewFrom_ = this.viewFrom_;\n return copy;\n }\n}\nfunction queryParamsGetNodeFilter(queryParams) {\n if (queryParams.loadsAllData()) {\n return new IndexedFilter(queryParams.getIndex());\n }\n else if (queryParams.hasLimit()) {\n return new LimitedFilter(queryParams);\n }\n else {\n return new RangedFilter(queryParams);\n }\n}\nfunction queryParamsLimitToFirst(queryParams, newLimit) {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = \"l\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;\n return newParams;\n}\nfunction queryParamsLimitToLast(queryParams, newLimit) {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = \"r\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;\n return newParams;\n}\nfunction queryParamsStartAt(queryParams, indexValue, key) {\n const newParams = queryParams.copy();\n newParams.startSet_ = true;\n if (indexValue === undefined) {\n indexValue = null;\n }\n newParams.indexStartValue_ = indexValue;\n if (key != null) {\n newParams.startNameSet_ = true;\n newParams.indexStartName_ = key;\n }\n else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n return newParams;\n}\nfunction queryParamsStartAfter(queryParams, indexValue, key) {\n let params;\n if (queryParams.index_ === KEY_INDEX || !!key) {\n params = queryParamsStartAt(queryParams, indexValue, key);\n }\n else {\n params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);\n }\n params.startAfterSet_ = true;\n return params;\n}\nfunction queryParamsEndAt(queryParams, indexValue, key) {\n const newParams = queryParams.copy();\n newParams.endSet_ = true;\n if (indexValue === undefined) {\n indexValue = null;\n }\n newParams.indexEndValue_ = indexValue;\n if (key !== undefined) {\n newParams.endNameSet_ = true;\n newParams.indexEndName_ = key;\n }\n else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n return newParams;\n}\nfunction queryParamsEndBefore(queryParams, indexValue, key) {\n let params;\n if (queryParams.index_ === KEY_INDEX || !!key) {\n params = queryParamsEndAt(queryParams, indexValue, key);\n }\n else {\n params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);\n }\n params.endBeforeSet_ = true;\n return params;\n}\nfunction queryParamsOrderBy(queryParams, index) {\n const newParams = queryParams.copy();\n newParams.index_ = index;\n return newParams;\n}\n/**\n * Returns a set of REST query string parameters representing this query.\n *\n * @returns query string parameters\n */\nfunction queryParamsToRestQueryStringParameters(queryParams) {\n const qs = {};\n if (queryParams.isDefault()) {\n return qs;\n }\n let orderBy;\n if (queryParams.index_ === PRIORITY_INDEX) {\n orderBy = \"$priority\" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;\n }\n else if (queryParams.index_ === VALUE_INDEX) {\n orderBy = \"$value\" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;\n }\n else if (queryParams.index_ === KEY_INDEX) {\n orderBy = \"$key\" /* REST_QUERY_CONSTANTS.KEY_INDEX */;\n }\n else {\n util.assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');\n orderBy = queryParams.index_.toString();\n }\n qs[\"orderBy\" /* REST_QUERY_CONSTANTS.ORDER_BY */] = util.stringify(orderBy);\n if (queryParams.startSet_) {\n const startParam = queryParams.startAfterSet_\n ? \"startAfter\" /* REST_QUERY_CONSTANTS.START_AFTER */\n : \"startAt\" /* REST_QUERY_CONSTANTS.START_AT */;\n qs[startParam] = util.stringify(queryParams.indexStartValue_);\n if (queryParams.startNameSet_) {\n qs[startParam] += ',' + util.stringify(queryParams.indexStartName_);\n }\n }\n if (queryParams.endSet_) {\n const endParam = queryParams.endBeforeSet_\n ? \"endBefore\" /* REST_QUERY_CONSTANTS.END_BEFORE */\n : \"endAt\" /* REST_QUERY_CONSTANTS.END_AT */;\n qs[endParam] = util.stringify(queryParams.indexEndValue_);\n if (queryParams.endNameSet_) {\n qs[endParam] += ',' + util.stringify(queryParams.indexEndName_);\n }\n }\n if (queryParams.limitSet_) {\n if (queryParams.isViewFromLeft()) {\n qs[\"limitToFirst\" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;\n }\n else {\n qs[\"limitToLast\" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;\n }\n }\n return qs;\n}\nfunction queryParamsGetQueryObject(queryParams) {\n const obj = {};\n if (queryParams.startSet_) {\n obj[\"sp\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =\n queryParams.indexStartValue_;\n if (queryParams.startNameSet_) {\n obj[\"sn\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =\n queryParams.indexStartName_;\n }\n obj[\"sin\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =\n !queryParams.startAfterSet_;\n }\n if (queryParams.endSet_) {\n obj[\"ep\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;\n if (queryParams.endNameSet_) {\n obj[\"en\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;\n }\n obj[\"ein\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =\n !queryParams.endBeforeSet_;\n }\n if (queryParams.limitSet_) {\n obj[\"l\" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;\n let viewFrom = queryParams.viewFrom_;\n if (viewFrom === '') {\n if (queryParams.isViewFromLeft()) {\n viewFrom = \"l\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;\n }\n else {\n viewFrom = \"r\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;\n }\n }\n obj[\"vf\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;\n }\n // For now, priority index is the default, so we only specify if it's some other index\n if (queryParams.index_ !== PRIORITY_INDEX) {\n obj[\"i\" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();\n }\n return obj;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An implementation of ServerActions that communicates with the server via REST requests.\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\n * persistent connection (using WebSockets or long-polling)\n */\nclass ReadonlyRestClient extends ServerActions {\n reportStats(stats) {\n throw new Error('Method not implemented.');\n }\n static getListenId_(query, tag) {\n if (tag !== undefined) {\n return 'tag$' + tag;\n }\n else {\n util.assert(query._queryParams.isDefault(), \"should have a tag if it's not a default query.\");\n return query._path.toString();\n }\n }\n /**\n * @param repoInfo_ - Data about the namespace we are connecting to\n * @param onDataUpdate_ - A callback for new data from the server\n */\n constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {\n super();\n this.repoInfo_ = repoInfo_;\n this.onDataUpdate_ = onDataUpdate_;\n this.authTokenProvider_ = authTokenProvider_;\n this.appCheckTokenProvider_ = appCheckTokenProvider_;\n /** @private {function(...[*])} */\n this.log_ = logWrapper('p:rest:');\n /**\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\n * that's been removed. :-/\n */\n this.listens_ = {};\n }\n /** @inheritDoc */\n listen(query, currentHashFn, tag, onComplete) {\n const pathString = query._path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);\n // Mark this listener so we can tell if it's removed.\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\n const thisListen = {};\n this.listens_[listenId] = thisListen;\n const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);\n this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {\n let data = result;\n if (error === 404) {\n data = null;\n error = null;\n }\n if (error === null) {\n this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n }\n if (util.safeGet(this.listens_, listenId) === thisListen) {\n let status;\n if (!error) {\n status = 'ok';\n }\n else if (error === 401) {\n status = 'permission_denied';\n }\n else {\n status = 'rest_error:' + error;\n }\n onComplete(status, null);\n }\n });\n }\n /** @inheritDoc */\n unlisten(query, tag) {\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n }\n get(query) {\n const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);\n const pathString = query._path.toString();\n const deferred = new util.Deferred();\n this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {\n let data = result;\n if (error === 404) {\n data = null;\n error = null;\n }\n if (error === null) {\n this.onDataUpdate_(pathString, data, \n /*isMerge=*/ false, \n /*tag=*/ null);\n deferred.resolve(data);\n }\n else {\n deferred.reject(new Error(data));\n }\n });\n return deferred.promise;\n }\n /** @inheritDoc */\n refreshAuthToken(token) {\n // no-op since we just always call getToken.\n }\n /**\n * Performs a REST request to the given path, with the provided query string parameters,\n * and any auth credentials we have.\n */\n restRequest_(pathString, queryStringParameters = {}, callback) {\n queryStringParameters['format'] = 'export';\n return Promise.all([\n this.authTokenProvider_.getToken(/*forceRefresh=*/ false),\n this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)\n ]).then(([authToken, appCheckToken]) => {\n if (authToken && authToken.accessToken) {\n queryStringParameters['auth'] = authToken.accessToken;\n }\n if (appCheckToken && appCheckToken.token) {\n queryStringParameters['ac'] = appCheckToken.token;\n }\n const url = (this.repoInfo_.secure ? 'https://' : 'http://') +\n this.repoInfo_.host +\n pathString +\n '?' +\n 'ns=' +\n this.repoInfo_.namespace +\n util.querystring(queryStringParameters);\n this.log_('Sending REST request for ' + url);\n const xhr = new XMLHttpRequest();\n xhr.onreadystatechange = () => {\n if (callback && xhr.readyState === 4) {\n this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\n let res = null;\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = util.jsonEval(xhr.responseText);\n }\n catch (e) {\n warn('Failed to parse JSON response for ' +\n url +\n ': ' +\n xhr.responseText);\n }\n callback(null, res);\n }\n else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n warn('Got unsuccessful REST response for ' +\n url +\n ' Status: ' +\n xhr.status);\n }\n callback(xhr.status);\n }\n callback = null;\n }\n };\n xhr.open('GET', url, /*asynchronous=*/ true);\n xhr.send();\n });\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n */\nclass SnapshotHolder {\n constructor() {\n this.rootNode_ = ChildrenNode.EMPTY_NODE;\n }\n getNode(path) {\n return this.rootNode_.getChild(path);\n }\n updateSnapshot(path, newSnapshotNode) {\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction newSparseSnapshotTree() {\n return {\n value: null,\n children: new Map()\n };\n}\n/**\n * Stores the given node at the specified path. If there is already a node\n * at a shallower path, it merges the new data into that snapshot node.\n *\n * @param path - Path to look up snapshot for.\n * @param data - The new data, or null.\n */\nfunction sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {\n if (pathIsEmpty(path)) {\n sparseSnapshotTree.value = data;\n sparseSnapshotTree.children.clear();\n }\n else if (sparseSnapshotTree.value !== null) {\n sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);\n }\n else {\n const childKey = pathGetFront(path);\n if (!sparseSnapshotTree.children.has(childKey)) {\n sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());\n }\n const child = sparseSnapshotTree.children.get(childKey);\n path = pathPopFront(path);\n sparseSnapshotTreeRemember(child, path, data);\n }\n}\n/**\n * Purge the data at path from the cache.\n *\n * @param path - Path to look up snapshot for.\n * @returns True if this node should now be removed.\n */\nfunction sparseSnapshotTreeForget(sparseSnapshotTree, path) {\n if (pathIsEmpty(path)) {\n sparseSnapshotTree.value = null;\n sparseSnapshotTree.children.clear();\n return true;\n }\n else {\n if (sparseSnapshotTree.value !== null) {\n if (sparseSnapshotTree.value.isLeafNode()) {\n // We're trying to forget a node that doesn't exist\n return false;\n }\n else {\n const value = sparseSnapshotTree.value;\n sparseSnapshotTree.value = null;\n value.forEachChild(PRIORITY_INDEX, (key, tree) => {\n sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);\n });\n return sparseSnapshotTreeForget(sparseSnapshotTree, path);\n }\n }\n else if (sparseSnapshotTree.children.size > 0) {\n const childKey = pathGetFront(path);\n path = pathPopFront(path);\n if (sparseSnapshotTree.children.has(childKey)) {\n const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);\n if (safeToRemove) {\n sparseSnapshotTree.children.delete(childKey);\n }\n }\n return sparseSnapshotTree.children.size === 0;\n }\n else {\n return true;\n }\n }\n}\n/**\n * Recursively iterates through all of the stored tree and calls the\n * callback on each one.\n *\n * @param prefixPath - Path to look up node for.\n * @param func - The function to invoke for each tree.\n */\nfunction sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {\n if (sparseSnapshotTree.value !== null) {\n func(prefixPath, sparseSnapshotTree.value);\n }\n else {\n sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {\n const path = new Path(prefixPath.toString() + '/' + key);\n sparseSnapshotTreeForEachTree(tree, path, func);\n });\n }\n}\n/**\n * Iterates through each immediate child and triggers the callback.\n * Only seems to be used in tests.\n *\n * @param func - The function to invoke for each child.\n */\nfunction sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {\n sparseSnapshotTree.children.forEach((tree, key) => {\n func(key, tree);\n });\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Returns the delta from the previous call to get stats.\n *\n * @param collection_ - The collection to \"listen\" to.\n */\nclass StatsListener {\n constructor(collection_) {\n this.collection_ = collection_;\n this.last_ = null;\n }\n get() {\n const newStats = this.collection_.get();\n const delta = { ...newStats };\n if (this.last_) {\n each(this.last_, (stat, value) => {\n delta[stat] = delta[stat] - value;\n });\n }\n this.last_ = newStats;\n return delta;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\n// seconds to try to ensure the Firebase connection is established / settled.\nconst FIRST_STATS_MIN_TIME = 10 * 1000;\nconst FIRST_STATS_MAX_TIME = 30 * 1000;\n// We'll continue to report stats on average every 5 minutes.\nconst REPORT_STATS_INTERVAL = 5 * 60 * 1000;\nclass StatsReporter {\n constructor(collection, server_) {\n this.server_ = server_;\n this.statsToReport_ = {};\n this.statsListener_ = new StatsListener(collection);\n const timeout = FIRST_STATS_MIN_TIME +\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n }\n reportStats_() {\n const stats = this.statsListener_.get();\n const reportedStats = {};\n let haveStatsToReport = false;\n each(stats, (stat, value) => {\n if (value > 0 && util.contains(this.statsToReport_, stat)) {\n reportedStats[stat] = value;\n haveStatsToReport = true;\n }\n });\n if (haveStatsToReport) {\n this.server_.reportStats(reportedStats);\n }\n // queue our next run.\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n *\n * @enum\n */\nvar OperationType;\n(function (OperationType) {\n OperationType[OperationType[\"OVERWRITE\"] = 0] = \"OVERWRITE\";\n OperationType[OperationType[\"MERGE\"] = 1] = \"MERGE\";\n OperationType[OperationType[\"ACK_USER_WRITE\"] = 2] = \"ACK_USER_WRITE\";\n OperationType[OperationType[\"LISTEN_COMPLETE\"] = 3] = \"LISTEN_COMPLETE\";\n})(OperationType || (OperationType = {}));\nfunction newOperationSourceUser() {\n return {\n fromUser: true,\n fromServer: false,\n queryId: null,\n tagged: false\n };\n}\nfunction newOperationSourceServer() {\n return {\n fromUser: false,\n fromServer: true,\n queryId: null,\n tagged: false\n };\n}\nfunction newOperationSourceServerTaggedQuery(queryId) {\n return {\n fromUser: false,\n fromServer: true,\n queryId,\n tagged: true\n };\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass AckUserWrite {\n /**\n * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.\n */\n constructor(\n /** @inheritDoc */ path, \n /** @inheritDoc */ affectedTree, \n /** @inheritDoc */ revert) {\n this.path = path;\n this.affectedTree = affectedTree;\n this.revert = revert;\n /** @inheritDoc */\n this.type = OperationType.ACK_USER_WRITE;\n /** @inheritDoc */\n this.source = newOperationSourceUser();\n }\n operationForChild(childName) {\n if (!pathIsEmpty(this.path)) {\n util.assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');\n return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);\n }\n else if (this.affectedTree.value != null) {\n util.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');\n // All child locations are affected as well; just return same operation.\n return this;\n }\n else {\n const childTree = this.affectedTree.subtree(new Path(childName));\n return new AckUserWrite(newEmptyPath(), childTree, this.revert);\n }\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass ListenComplete {\n constructor(source, path) {\n this.source = source;\n this.path = path;\n /** @inheritDoc */\n this.type = OperationType.LISTEN_COMPLETE;\n }\n operationForChild(childName) {\n if (pathIsEmpty(this.path)) {\n return new ListenComplete(this.source, newEmptyPath());\n }\n else {\n return new ListenComplete(this.source, pathPopFront(this.path));\n }\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass Overwrite {\n constructor(source, path, snap) {\n this.source = source;\n this.path = path;\n this.snap = snap;\n /** @inheritDoc */\n this.type = OperationType.OVERWRITE;\n }\n operationForChild(childName) {\n if (pathIsEmpty(this.path)) {\n return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));\n }\n else {\n return new Overwrite(this.source, pathPopFront(this.path), this.snap);\n }\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass Merge {\n constructor(\n /** @inheritDoc */ source, \n /** @inheritDoc */ path, \n /** @inheritDoc */ children) {\n this.source = source;\n this.path = path;\n this.children = children;\n /** @inheritDoc */\n this.type = OperationType.MERGE;\n }\n operationForChild(childName) {\n if (pathIsEmpty(this.path)) {\n const childTree = this.children.subtree(new Path(childName));\n if (childTree.isEmpty()) {\n // This child is unaffected\n return null;\n }\n else if (childTree.value) {\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\n return new Overwrite(this.source, newEmptyPath(), childTree.value);\n }\n else {\n // This is a merge at a deeper level\n return new Merge(this.source, newEmptyPath(), childTree);\n }\n }\n else {\n util.assert(pathGetFront(this.path) === childName, \"Can't get a merge for a child not on the path of the operation\");\n return new Merge(this.source, pathPopFront(this.path), this.children);\n }\n }\n toString() {\n return ('Operation(' +\n this.path +\n ': ' +\n this.source.toString() +\n ' merge: ' +\n this.children.toString() +\n ')');\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\n * whether a node potentially had children removed due to a filter.\n */\nclass CacheNode {\n constructor(node_, fullyInitialized_, filtered_) {\n this.node_ = node_;\n this.fullyInitialized_ = fullyInitialized_;\n this.filtered_ = filtered_;\n }\n /**\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\n */\n isFullyInitialized() {\n return this.fullyInitialized_;\n }\n /**\n * Returns whether this node is potentially missing children due to a filter applied to the node\n */\n isFiltered() {\n return this.filtered_;\n }\n isCompleteForPath(path) {\n if (pathIsEmpty(path)) {\n return this.isFullyInitialized() && !this.filtered_;\n }\n const childKey = pathGetFront(path);\n return this.isCompleteForChild(childKey);\n }\n isCompleteForChild(key) {\n return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));\n }\n getNode() {\n return this.node_;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\n * for details.\n *\n */\nclass EventGenerator {\n constructor(query_) {\n this.query_ = query_;\n this.index_ = this.query_._queryParams.getIndex();\n }\n}\n/**\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\n *\n * Notes:\n * - child_moved events will be synthesized at this time for any child_changed events that affect\n * our index.\n * - prevName will be calculated based on the index ordering.\n */\nfunction eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {\n const events = [];\n const moves = [];\n changes.forEach(change => {\n if (change.type === \"child_changed\" /* ChangeType.CHILD_CHANGED */ &&\n eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {\n moves.push(changeChildMoved(change.childName, change.snapshotNode));\n }\n });\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_removed\" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_added\" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_moved\" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_changed\" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"value\" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);\n return events;\n}\n/**\n * Given changes of a single change type, generate the corresponding events.\n */\nfunction eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {\n const filteredChanges = changes.filter(change => change.type === eventType);\n filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b));\n filteredChanges.forEach(change => {\n const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);\n registrations.forEach(registration => {\n if (registration.respondsTo(change.type)) {\n events.push(registration.createEvent(materializedChange, eventGenerator.query_));\n }\n });\n });\n}\nfunction eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n }\n else {\n change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);\n return change;\n }\n}\nfunction eventGeneratorCompareChanges(eventGenerator, a, b) {\n if (a.childName == null || b.childName == null) {\n throw util.assertionError('Should only compare child_ events.');\n }\n const aWrapped = new NamedNode(a.childName, a.snapshotNode);\n const bWrapped = new NamedNode(b.childName, b.snapshotNode);\n return eventGenerator.index_.compare(aWrapped, bWrapped);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction newViewCache(eventCache, serverCache) {\n return { eventCache, serverCache };\n}\nfunction viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {\n return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);\n}\nfunction viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {\n return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));\n}\nfunction viewCacheGetCompleteEventSnap(viewCache) {\n return viewCache.eventCache.isFullyInitialized()\n ? viewCache.eventCache.getNode()\n : null;\n}\nfunction viewCacheGetCompleteServerSnap(viewCache) {\n return viewCache.serverCache.isFullyInitialized()\n ? viewCache.serverCache.getNode()\n : null;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nlet emptyChildrenSingleton;\n/**\n * Singleton empty children collection.\n *\n */\nconst EmptyChildren = () => {\n if (!emptyChildrenSingleton) {\n emptyChildrenSingleton = new SortedMap(stringCompare);\n }\n return emptyChildrenSingleton;\n};\n/**\n * A tree with immutable elements.\n */\nclass ImmutableTree {\n static fromObject(obj) {\n let tree = new ImmutableTree(null);\n each(obj, (childPath, childSnap) => {\n tree = tree.set(new Path(childPath), childSnap);\n });\n return tree;\n }\n constructor(value, children = EmptyChildren()) {\n this.value = value;\n this.children = children;\n }\n /**\n * True if the value is empty and there are no children\n */\n isEmpty() {\n return this.value === null && this.children.isEmpty();\n }\n /**\n * Given a path and predicate, return the first node and the path to that node\n * where the predicate returns true.\n *\n * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`\n * objects on the way back out, it may be better to pass down a pathSoFar obj.\n *\n * @param relativePath - The remainder of the path\n * @param predicate - The predicate to satisfy to return a node\n */\n findRootMostMatchingPathAndValue(relativePath, predicate) {\n if (this.value != null && predicate(this.value)) {\n return { path: newEmptyPath(), value: this.value };\n }\n else {\n if (pathIsEmpty(relativePath)) {\n return null;\n }\n else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child !== null) {\n const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);\n if (childExistingPathAndValue != null) {\n const fullPath = pathChild(new Path(front), childExistingPathAndValue.path);\n return { path: fullPath, value: childExistingPathAndValue.value };\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n }\n }\n }\n /**\n * Find, if it exists, the shortest subpath of the given path that points a defined\n * value in the tree\n */\n findRootMostValueAndPath(relativePath) {\n return this.findRootMostMatchingPathAndValue(relativePath, () => true);\n }\n /**\n * @returns The subtree at the given path\n */\n subtree(relativePath) {\n if (pathIsEmpty(relativePath)) {\n return this;\n }\n else {\n const front = pathGetFront(relativePath);\n const childTree = this.children.get(front);\n if (childTree !== null) {\n return childTree.subtree(pathPopFront(relativePath));\n }\n else {\n return new ImmutableTree(null);\n }\n }\n }\n /**\n * Sets a value at the specified path.\n *\n * @param relativePath - Path to set value at.\n * @param toSet - Value to set.\n * @returns Resulting tree.\n */\n set(relativePath, toSet) {\n if (pathIsEmpty(relativePath)) {\n return new ImmutableTree(toSet, this.children);\n }\n else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front) || new ImmutableTree(null);\n const newChild = child.set(pathPopFront(relativePath), toSet);\n const newChildren = this.children.insert(front, newChild);\n return new ImmutableTree(this.value, newChildren);\n }\n }\n /**\n * Removes the value at the specified path.\n *\n * @param relativePath - Path to value to remove.\n * @returns Resulting tree.\n */\n remove(relativePath) {\n if (pathIsEmpty(relativePath)) {\n if (this.children.isEmpty()) {\n return new ImmutableTree(null);\n }\n else {\n return new ImmutableTree(null, this.children);\n }\n }\n else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child) {\n const newChild = child.remove(pathPopFront(relativePath));\n let newChildren;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n }\n else {\n newChildren = this.children.insert(front, newChild);\n }\n if (this.value === null && newChildren.isEmpty()) {\n return new ImmutableTree(null);\n }\n else {\n return new ImmutableTree(this.value, newChildren);\n }\n }\n else {\n return this;\n }\n }\n }\n /**\n * Gets a value from the tree.\n *\n * @param relativePath - Path to get value for.\n * @returns Value at path, or null.\n */\n get(relativePath) {\n if (pathIsEmpty(relativePath)) {\n return this.value;\n }\n else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child) {\n return child.get(pathPopFront(relativePath));\n }\n else {\n return null;\n }\n }\n }\n /**\n * Replace the subtree at the specified path with the given new tree.\n *\n * @param relativePath - Path to replace subtree for.\n * @param newTree - New tree.\n * @returns Resulting tree.\n */\n setTree(relativePath, newTree) {\n if (pathIsEmpty(relativePath)) {\n return newTree;\n }\n else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front) || new ImmutableTree(null);\n const newChild = child.setTree(pathPopFront(relativePath), newTree);\n let newChildren;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n }\n else {\n newChildren = this.children.insert(front, newChild);\n }\n return new ImmutableTree(this.value, newChildren);\n }\n }\n /**\n * Performs a depth first fold on this tree. Transforms a tree into a single\n * value, given a function that operates on the path to a node, an optional\n * current value, and a map of child names to folded subtrees\n */\n fold(fn) {\n return this.fold_(newEmptyPath(), fn);\n }\n /**\n * Recursive helper for public-facing fold() method\n */\n fold_(pathSoFar, fn) {\n const accum = {};\n this.children.inorderTraversal((childKey, childTree) => {\n accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);\n });\n return fn(pathSoFar, this.value, accum);\n }\n /**\n * Find the first matching value on the given path. Return the result of applying f to it.\n */\n findOnPath(path, f) {\n return this.findOnPath_(path, newEmptyPath(), f);\n }\n findOnPath_(pathToFollow, pathSoFar, f) {\n const result = this.value ? f(pathSoFar, this.value) : false;\n if (result) {\n return result;\n }\n else {\n if (pathIsEmpty(pathToFollow)) {\n return null;\n }\n else {\n const front = pathGetFront(pathToFollow);\n const nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);\n }\n else {\n return null;\n }\n }\n }\n }\n foreachOnPath(path, f) {\n return this.foreachOnPath_(path, newEmptyPath(), f);\n }\n foreachOnPath_(pathToFollow, currentRelativePath, f) {\n if (pathIsEmpty(pathToFollow)) {\n return this;\n }\n else {\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n const front = pathGetFront(pathToFollow);\n const nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);\n }\n else {\n return new ImmutableTree(null);\n }\n }\n }\n /**\n * Calls the given function for each node in the tree that has a value.\n *\n * @param f - A function to be called with the path from the root of the tree to\n * a node, and the value at that node. Called in depth-first order.\n */\n foreach(f) {\n this.foreach_(newEmptyPath(), f);\n }\n foreach_(currentRelativePath, f) {\n this.children.inorderTraversal((childName, childTree) => {\n childTree.foreach_(pathChild(currentRelativePath, childName), f);\n });\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n }\n foreachChild(f) {\n this.children.inorderTraversal((childName, childTree) => {\n if (childTree.value) {\n f(childName, childTree.value);\n }\n });\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\n * to reflect the write added.\n */\nclass CompoundWrite {\n constructor(writeTree_) {\n this.writeTree_ = writeTree_;\n }\n static empty() {\n return new CompoundWrite(new ImmutableTree(null));\n }\n}\nfunction compoundWriteAddWrite(compoundWrite, path, node) {\n if (pathIsEmpty(path)) {\n return new CompoundWrite(new ImmutableTree(node));\n }\n else {\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n const rootMostPath = rootmost.path;\n let value = rootmost.value;\n const relativePath = newRelativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));\n }\n else {\n const subtree = new ImmutableTree(node);\n const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n}\nfunction compoundWriteAddWrites(compoundWrite, path, updates) {\n let newWrite = compoundWrite;\n each(updates, (childKey, node) => {\n newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);\n });\n return newWrite;\n}\n/**\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param compoundWrite - The CompoundWrite to remove.\n * @param path - The path at which a write and all deeper writes should be removed\n * @returns The new CompoundWrite with the removed path\n */\nfunction compoundWriteRemoveWrite(compoundWrite, path) {\n if (pathIsEmpty(path)) {\n return CompoundWrite.empty();\n }\n else {\n const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));\n return new CompoundWrite(newWriteTree);\n }\n}\n/**\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\n * considered \"complete\".\n *\n * @param compoundWrite - The CompoundWrite to check.\n * @param path - The path to check for\n * @returns Whether there is a complete write at that path\n */\nfunction compoundWriteHasCompleteWrite(compoundWrite, path) {\n return compoundWriteGetCompleteNode(compoundWrite, path) != null;\n}\n/**\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\n * writes from deeper paths, but will return child nodes from a more shallow path.\n *\n * @param compoundWrite - The CompoundWrite to get the node from.\n * @param path - The path to get a complete write\n * @returns The node if complete at that path, or null otherwise.\n */\nfunction compoundWriteGetCompleteNode(compoundWrite, path) {\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return compoundWrite.writeTree_\n .get(rootmost.path)\n .getChild(newRelativePath(rootmost.path, path));\n }\n else {\n return null;\n }\n}\n/**\n * Returns all children that are guaranteed to be a complete overwrite.\n *\n * @param compoundWrite - The CompoundWrite to get children from.\n * @returns A list of all complete children.\n */\nfunction compoundWriteGetCompleteChildren(compoundWrite) {\n const children = [];\n const node = compoundWrite.writeTree_.value;\n if (node != null) {\n // If it's a leaf node, it has no children; so nothing to do.\n if (!node.isLeafNode()) {\n node.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\n children.push(new NamedNode(childName, childNode));\n });\n }\n }\n else {\n compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => {\n if (childTree.value != null) {\n children.push(new NamedNode(childName, childTree.value));\n }\n });\n }\n return children;\n}\nfunction compoundWriteChildCompoundWrite(compoundWrite, path) {\n if (pathIsEmpty(path)) {\n return compoundWrite;\n }\n else {\n const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree(shadowingNode));\n }\n else {\n return new CompoundWrite(compoundWrite.writeTree_.subtree(path));\n }\n }\n}\n/**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @returns Whether this CompoundWrite is empty\n */\nfunction compoundWriteIsEmpty(compoundWrite) {\n return compoundWrite.writeTree_.isEmpty();\n}\n/**\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\n * node\n * @param node - The node to apply this CompoundWrite to\n * @returns The node with all writes applied\n */\nfunction compoundWriteApply(compoundWrite, node) {\n return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);\n}\nfunction applySubtreeWrite(relativePath, writeTree, node) {\n if (writeTree.value != null) {\n // Since there a write is always a leaf, we're done here\n return node.updateChild(relativePath, writeTree.value);\n }\n else {\n let priorityWrite = null;\n writeTree.children.inorderTraversal((childKey, childTree) => {\n if (childKey === '.priority') {\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\n // to apply priorities to empty nodes that are later filled\n util.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');\n priorityWrite = childTree.value;\n }\n else {\n node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {\n node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite);\n }\n return node;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n */\nfunction writeTreeChildWrites(writeTree, path) {\n return newWriteTreeRef(path, writeTree);\n}\n/**\n * Record a new overwrite from user code.\n *\n * @param visible - This is set to false by some transactions. It should be excluded from event caches\n */\nfunction writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {\n util.assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');\n if (visible === undefined) {\n visible = true;\n }\n writeTree.allWrites.push({\n path,\n snap,\n writeId,\n visible\n });\n if (visible) {\n writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);\n }\n writeTree.lastWriteId = writeId;\n}\n/**\n * Record a new merge from user code.\n */\nfunction writeTreeAddMerge(writeTree, path, changedChildren, writeId) {\n util.assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');\n writeTree.allWrites.push({\n path,\n children: changedChildren,\n writeId,\n visible: true\n });\n writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);\n writeTree.lastWriteId = writeId;\n}\nfunction writeTreeGetWrite(writeTree, writeId) {\n for (let i = 0; i < writeTree.allWrites.length; i++) {\n const record = writeTree.allWrites[i];\n if (record.writeId === writeId) {\n return record;\n }\n }\n return null;\n}\n/**\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\n *\n * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\nfunction writeTreeRemoveWrite(writeTree, writeId) {\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\n // out of order.\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\n const idx = writeTree.allWrites.findIndex(s => {\n return s.writeId === writeId;\n });\n util.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n const writeToRemove = writeTree.allWrites[idx];\n writeTree.allWrites.splice(idx, 1);\n let removedWriteWasVisible = writeToRemove.visible;\n let removedWriteOverlapsWithOtherWrites = false;\n let i = writeTree.allWrites.length - 1;\n while (removedWriteWasVisible && i >= 0) {\n const currentWrite = writeTree.allWrites[i];\n if (currentWrite.visible) {\n if (i >= idx &&\n writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\n }\n else if (pathContains(writeToRemove.path, currentWrite.path)) {\n // Either we're covering some writes or they're covering part of us (depending on which came first).\n removedWriteOverlapsWithOtherWrites = true;\n }\n }\n i--;\n }\n if (!removedWriteWasVisible) {\n return false;\n }\n else if (removedWriteOverlapsWithOtherWrites) {\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\n writeTreeResetTree_(writeTree);\n return true;\n }\n else {\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\n if (writeToRemove.snap) {\n writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);\n }\n else {\n const children = writeToRemove.children;\n each(children, (childName) => {\n writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));\n });\n }\n return true;\n }\n}\nfunction writeTreeRecordContainsPath_(writeRecord, path) {\n if (writeRecord.snap) {\n return pathContains(writeRecord.path, path);\n }\n else {\n for (const childName in writeRecord.children) {\n if (writeRecord.children.hasOwnProperty(childName) &&\n pathContains(pathChild(writeRecord.path, childName), path)) {\n return true;\n }\n }\n return false;\n }\n}\n/**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\n */\nfunction writeTreeResetTree_(writeTree) {\n writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());\n if (writeTree.allWrites.length > 0) {\n writeTree.lastWriteId =\n writeTree.allWrites[writeTree.allWrites.length - 1].writeId;\n }\n else {\n writeTree.lastWriteId = -1;\n }\n}\n/**\n * The default filter used when constructing the tree. Keep everything that's visible.\n */\nfunction writeTreeDefaultFilter_(write) {\n return write.visible;\n}\n/**\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\n * event data at that path.\n */\nfunction writeTreeLayerTree_(writes, filter, treeRoot) {\n let compoundWrite = CompoundWrite.empty();\n for (let i = 0; i < writes.length; ++i) {\n const write = writes[i];\n // Theory, a later set will either:\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\n if (filter(write)) {\n const writePath = write.path;\n let relativePath;\n if (write.snap) {\n if (pathContains(treeRoot, writePath)) {\n relativePath = newRelativePath(treeRoot, writePath);\n compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);\n }\n else if (pathContains(writePath, treeRoot)) {\n relativePath = newRelativePath(writePath, treeRoot);\n compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));\n }\n else ;\n }\n else if (write.children) {\n if (pathContains(treeRoot, writePath)) {\n relativePath = newRelativePath(treeRoot, writePath);\n compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);\n }\n else if (pathContains(writePath, treeRoot)) {\n relativePath = newRelativePath(writePath, treeRoot);\n if (pathIsEmpty(relativePath)) {\n compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);\n }\n else {\n const child = util.safeGet(write.children, pathGetFront(relativePath));\n if (child) {\n // There exists a child in this node that matches the root path\n const deepNode = child.getChild(pathPopFront(relativePath));\n compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);\n }\n }\n }\n else ;\n }\n else {\n throw util.assertionError('WriteRecord should have .snap or .children');\n }\n }\n }\n return compoundWrite;\n}\n/**\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\n * writes), attempt to calculate a complete snapshot for the given path\n *\n * @param writeIdsToExclude - An optional set to be excluded\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\n */\nfunction writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\n if (compoundWriteIsEmpty(subMerge)) {\n return completeServerCache;\n }\n else if (completeServerCache == null &&\n !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n return null;\n }\n else {\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\n return compoundWriteApply(subMerge, layeredCache);\n }\n }\n }\n else {\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\n if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {\n return completeServerCache;\n }\n else {\n // If the server cache is null, and we don't have a complete cache, we need to return null\n if (!includeHiddenWrites &&\n completeServerCache == null &&\n !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {\n return null;\n }\n else {\n const filter = function (write) {\n return ((write.visible || includeHiddenWrites) &&\n (!writeIdsToExclude ||\n !~writeIdsToExclude.indexOf(write.writeId)) &&\n (pathContains(write.path, treePath) ||\n pathContains(treePath, write.path)));\n };\n const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\n return compoundWriteApply(mergeAtPath, layeredCache);\n }\n }\n }\n}\n/**\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\n * Used when creating new views, to pre-fill their complete event children snapshot.\n */\nfunction writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {\n let completeChildren = ChildrenNode.EMPTY_NODE;\n const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);\n if (topLevelSet) {\n if (!topLevelSet.isLeafNode()) {\n // we're shadowing everything. Return the children.\n topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {\n completeChildren = completeChildren.updateImmediateChild(childName, childSnap);\n });\n }\n return completeChildren;\n }\n else if (completeServerChildren) {\n // Layer any children we have on top of this\n // We know we don't have a top-level set, so just enumerate existing children\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\n completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\n const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode);\n completeChildren = completeChildren.updateImmediateChild(childName, node);\n });\n // Add any complete children we have from the set\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n else {\n // We don't have anything to layer on top of. Layer on any children we have\n // Note that we can return an empty snap if we have a defined delete\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n}\n/**\n * Given that the underlying server data has updated, determine what, if anything, needs to be\n * applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events\n *\n * Either existingEventSnap or existingServerSnap must exist\n */\nfunction writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {\n util.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');\n const path = pathChild(treePath, childPath);\n if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {\n // At this point we can probably guarantee that we're in case 2, meaning no events\n // May need to check visibility while doing the findRootMostValueAndPath call\n return null;\n }\n else {\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\n const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);\n if (compoundWriteIsEmpty(childMerge)) {\n // We're not shadowing at all. Case 1\n return existingServerSnap.getChild(childPath);\n }\n else {\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\n // However this is tricky to find out, since user updates don't necessary change the server\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\n // only check if the updates change the serverNode.\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\n return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));\n }\n }\n}\n/**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n */\nfunction writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {\n const path = pathChild(treePath, childKey);\n const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);\n return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));\n }\n else {\n return null;\n }\n }\n}\n/**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n */\nfunction writeTreeShadowingWrite(writeTree, path) {\n return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\n}\n/**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window.\n */\nfunction writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {\n let toIterate;\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\n const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n }\n else if (completeServerData != null) {\n toIterate = compoundWriteApply(merge, completeServerData);\n }\n else {\n // no children to iterate on\n return [];\n }\n toIterate = toIterate.withIndex(index);\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n const nodes = [];\n const cmp = index.getCompare();\n const iter = reverse\n ? toIterate.getReverseIteratorFrom(startPost, index)\n : toIterate.getIteratorFrom(startPost, index);\n let next = iter.getNext();\n while (next && nodes.length < count) {\n if (cmp(next, startPost) !== 0) {\n nodes.push(next);\n }\n next = iter.getNext();\n }\n return nodes;\n }\n else {\n return [];\n }\n}\nfunction newWriteTree() {\n return {\n visibleWrites: CompoundWrite.empty(),\n allWrites: [],\n lastWriteId: -1\n };\n}\n/**\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\n * can lead to a more expensive calculation.\n *\n * @param writeIdsToExclude - Optional writes to exclude.\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\n */\nfunction writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);\n}\n/**\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\n * mix of the given server data and write data.\n *\n */\nfunction writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {\n return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);\n}\n/**\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\n * if anything, needs to be applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events should be raised\n *\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\n *\n *\n */\nfunction writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {\n return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);\n}\n/**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n */\nfunction writeTreeRefShadowingWrite(writeTreeRef, path) {\n return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));\n}\n/**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window\n */\nfunction writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {\n return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);\n}\n/**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n */\nfunction writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {\n return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);\n}\n/**\n * Return a WriteTreeRef for a child.\n */\nfunction writeTreeRefChild(writeTreeRef, childName) {\n return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);\n}\nfunction newWriteTreeRef(path, writeTree) {\n return {\n treePath: path,\n writeTree\n };\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass ChildChangeAccumulator {\n constructor() {\n this.changeMap = new Map();\n }\n trackChildChange(change) {\n const type = change.type;\n const childKey = change.childName;\n util.assert(type === \"child_added\" /* ChangeType.CHILD_ADDED */ ||\n type === \"child_changed\" /* ChangeType.CHILD_CHANGED */ ||\n type === \"child_removed\" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');\n util.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');\n const oldChange = this.changeMap.get(childKey);\n if (oldChange) {\n const oldType = oldChange.type;\n if (type === \"child_added\" /* ChangeType.CHILD_ADDED */ &&\n oldType === \"child_removed\" /* ChangeType.CHILD_REMOVED */) {\n this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));\n }\n else if (type === \"child_removed\" /* ChangeType.CHILD_REMOVED */ &&\n oldType === \"child_added\" /* ChangeType.CHILD_ADDED */) {\n this.changeMap.delete(childKey);\n }\n else if (type === \"child_removed\" /* ChangeType.CHILD_REMOVED */ &&\n oldType === \"child_changed\" /* ChangeType.CHILD_CHANGED */) {\n this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));\n }\n else if (type === \"child_changed\" /* ChangeType.CHILD_CHANGED */ &&\n oldType === \"child_added\" /* ChangeType.CHILD_ADDED */) {\n this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));\n }\n else if (type === \"child_changed\" /* ChangeType.CHILD_CHANGED */ &&\n oldType === \"child_changed\" /* ChangeType.CHILD_CHANGED */) {\n this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));\n }\n else {\n throw util.assertionError('Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange);\n }\n }\n else {\n this.changeMap.set(childKey, change);\n }\n }\n getChanges() {\n return Array.from(this.changeMap.values());\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An implementation of CompleteChildSource that never returns any additional children\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nclass NoCompleteChildSource_ {\n getCompleteChild(childKey) {\n return null;\n }\n getChildAfterChild(index, child, reverse) {\n return null;\n }\n}\n/**\n * Singleton instance.\n */\nconst NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n/**\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\n * old event caches available to calculate complete children.\n */\nclass WriteTreeCompleteChildSource {\n constructor(writes_, viewCache_, optCompleteServerCache_ = null) {\n this.writes_ = writes_;\n this.viewCache_ = viewCache_;\n this.optCompleteServerCache_ = optCompleteServerCache_;\n }\n getCompleteChild(childKey) {\n const node = this.viewCache_.eventCache;\n if (node.isCompleteForChild(childKey)) {\n return node.getNode().getImmediateChild(childKey);\n }\n else {\n const serverNode = this.optCompleteServerCache_ != null\n ? new CacheNode(this.optCompleteServerCache_, true, false)\n : this.viewCache_.serverCache;\n return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);\n }\n }\n getChildAfterChild(index, child, reverse) {\n const completeServerData = this.optCompleteServerCache_ != null\n ? this.optCompleteServerCache_\n : viewCacheGetCompleteServerSnap(this.viewCache_);\n const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);\n if (nodes.length === 0) {\n return null;\n }\n else {\n return nodes[0];\n }\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction newViewProcessor(filter) {\n return { filter };\n}\nfunction viewProcessorAssertIndexed(viewProcessor, viewCache) {\n util.assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');\n util.assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');\n}\nfunction viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {\n const accumulator = new ChildChangeAccumulator();\n let newViewCache, filterServerNode;\n if (operation.type === OperationType.OVERWRITE) {\n const overwrite = operation;\n if (overwrite.source.fromUser) {\n newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);\n }\n else {\n util.assert(overwrite.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered and the\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\n // again\n filterServerNode =\n overwrite.source.tagged ||\n (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));\n newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === OperationType.MERGE) {\n const merge = operation;\n if (merge.source.fromUser) {\n newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);\n }\n else {\n util.assert(merge.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered\n filterServerNode =\n merge.source.tagged || oldViewCache.serverCache.isFiltered();\n newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === OperationType.ACK_USER_WRITE) {\n const ackUserWrite = operation;\n if (!ackUserWrite.revert) {\n newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);\n }\n else {\n newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);\n }\n }\n else if (operation.type === OperationType.LISTEN_COMPLETE) {\n newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);\n }\n else {\n throw util.assertionError('Unknown operation type: ' + operation.type);\n }\n const changes = accumulator.getChanges();\n viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);\n return { viewCache: newViewCache, changes };\n}\nfunction viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {\n const eventSnap = newViewCache.eventCache;\n if (eventSnap.isFullyInitialized()) {\n const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);\n if (accumulator.length > 0 ||\n !oldViewCache.eventCache.isFullyInitialized() ||\n (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||\n !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {\n accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));\n }\n }\n}\nfunction viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {\n const oldEventSnap = viewCache.eventCache;\n if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n }\n else {\n let newEventCache, serverNode;\n if (pathIsEmpty(changePath)) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n util.assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');\n if (viewCache.serverCache.isFiltered()) {\n // We need to special case this, because we need to only apply writes to complete children, or\n // we might end up raising events for incomplete children. If the server data is filtered deep\n // writes cannot be guaranteed to be complete\n const serverCache = viewCacheGetCompleteServerSnap(viewCache);\n const completeChildren = serverCache instanceof ChildrenNode\n ? serverCache\n : ChildrenNode.EMPTY_NODE;\n const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);\n newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);\n }\n else {\n const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\n newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);\n }\n }\n else {\n const childKey = pathGetFront(changePath);\n if (childKey === '.priority') {\n util.assert(pathGetLength(changePath) === 1, \"Can't have a priority with additional path components\");\n const oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.serverCache.getNode();\n // we might have overwrites for this priority\n const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);\n if (updatedPriority != null) {\n newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);\n }\n else {\n // priority didn't change, keep old node\n newEventCache = oldEventSnap.getNode();\n }\n }\n else {\n const childChangePath = pathPopFront(changePath);\n // update child\n let newEventChild;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.serverCache.getNode();\n const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);\n if (eventChildUpdate != null) {\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey)\n .updateChild(childChangePath, eventChildUpdate);\n }\n else {\n // Nothing changed, just keep the old child\n newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);\n }\n }\n else {\n newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);\n }\n if (newEventChild != null) {\n newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);\n }\n else {\n // no complete child available or no change\n newEventCache = oldEventSnap.getNode();\n }\n }\n }\n return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());\n }\n}\nfunction viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {\n const oldServerSnap = oldViewCache.serverCache;\n let newServerCache;\n const serverFilter = filterServerNode\n ? viewProcessor.filter\n : viewProcessor.filter.getIndexedFilter();\n if (pathIsEmpty(changePath)) {\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);\n }\n else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\n const newServerNode = oldServerSnap\n .getNode()\n .updateChild(changePath, changedSnap);\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);\n }\n else {\n const childKey = pathGetFront(changePath);\n if (!oldServerSnap.isCompleteForPath(changePath) &&\n pathGetLength(changePath) > 1) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n const childChangePath = pathPopFront(changePath);\n const childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n const newChildNode = childNode.updateChild(childChangePath, changedSnap);\n if (childKey === '.priority') {\n newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);\n }\n else {\n newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);\n }\n }\n const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());\n const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);\n return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);\n}\nfunction viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {\n const oldEventSnap = oldViewCache.eventCache;\n let newViewCache, newEventCache;\n const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);\n if (pathIsEmpty(changePath)) {\n newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);\n newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());\n }\n else {\n const childKey = pathGetFront(changePath);\n if (childKey === '.priority') {\n newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);\n newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());\n }\n else {\n const childChangePath = pathPopFront(changePath);\n const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n let newChild;\n if (pathIsEmpty(childChangePath)) {\n // Child overwrite, we can replace the child\n newChild = changedSnap;\n }\n else {\n const childNode = source.getCompleteChild(childKey);\n if (childNode != null) {\n if (pathGetBack(childChangePath) === '.priority' &&\n childNode.getChild(pathParent(childChangePath)).isEmpty()) {\n // This is a priority update on an empty node. If this node exists on the server, the\n // server will send down the priority in the update, so ignore for now\n newChild = childNode;\n }\n else {\n newChild = childNode.updateChild(childChangePath, changedSnap);\n }\n }\n else {\n // There is no complete child node available\n newChild = ChildrenNode.EMPTY_NODE;\n }\n }\n if (!oldChild.equals(newChild)) {\n const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);\n newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());\n }\n else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n}\nfunction viewProcessorCacheHasChild(viewCache, childKey) {\n return viewCache.eventCache.isCompleteForChild(childKey);\n}\nfunction viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n let curViewCache = viewCache;\n changedChildren.foreach((relativePath, childNode) => {\n const writePath = pathChild(path, relativePath);\n if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\n curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n changedChildren.foreach((relativePath, childNode) => {\n const writePath = pathChild(path, relativePath);\n if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\n curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n return curViewCache;\n}\nfunction viewProcessorApplyMerge(viewProcessor, node, merge) {\n merge.foreach((relativePath, childNode) => {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n}\nfunction viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\n // wait for the complete data update coming soon.\n if (viewCache.serverCache.getNode().isEmpty() &&\n !viewCache.serverCache.isFullyInitialized()) {\n return viewCache;\n }\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n let curViewCache = viewCache;\n let viewMergeTree;\n if (pathIsEmpty(path)) {\n viewMergeTree = changedChildren;\n }\n else {\n viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);\n }\n const serverNode = viewCache.serverCache.getNode();\n viewMergeTree.children.inorderTraversal((childKey, childTree) => {\n if (serverNode.hasChild(childKey)) {\n const serverChild = viewCache.serverCache\n .getNode()\n .getImmediateChild(childKey);\n const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);\n curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {\n const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&\n childMergeTree.value === null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n const serverChild = viewCache.serverCache\n .getNode()\n .getImmediateChild(childKey);\n const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);\n curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n return curViewCache;\n}\nfunction viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {\n if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {\n return viewCache;\n }\n // Only filter server node if it is currently filtered\n const filterServerNode = viewCache.serverCache.isFiltered();\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\n // now that it won't be shadowed.\n const serverCache = viewCache.serverCache;\n if (affectedTree.value != null) {\n // This is an overwrite.\n if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)) {\n return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);\n }\n else if (pathIsEmpty(ackPath)) {\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\n // should just re-apply whatever we have in our cache as a merge.\n let changedChildren = new ImmutableTree(null);\n serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {\n changedChildren = changedChildren.set(new Path(name), node);\n });\n return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);\n }\n else {\n return viewCache;\n }\n }\n else {\n // This is a merge.\n let changedChildren = new ImmutableTree(null);\n affectedTree.foreach((mergePath, value) => {\n const serverCachePath = pathChild(ackPath, mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath));\n }\n });\n return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);\n }\n}\nfunction viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {\n const oldServerNode = viewCache.serverCache;\n const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());\n return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);\n}\nfunction viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {\n let complete;\n if (writeTreeRefShadowingWrite(writesCache, path) != null) {\n return viewCache;\n }\n else {\n const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);\n const oldEventCache = viewCache.eventCache.getNode();\n let newEventCache;\n if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {\n let newNode;\n if (viewCache.serverCache.isFullyInitialized()) {\n newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\n }\n else {\n const serverChildren = viewCache.serverCache.getNode();\n util.assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');\n newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);\n }\n newNode = newNode;\n newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);\n }\n else {\n const childKey = pathGetFront(path);\n let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);\n if (newChild == null &&\n viewCache.serverCache.isCompleteForChild(childKey)) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);\n }\n else if (viewCache.eventCache.getNode().hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);\n }\n else {\n newEventCache = oldEventCache;\n }\n if (newEventCache.isEmpty() &&\n viewCache.serverCache.isFullyInitialized()) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\n if (complete.isLeafNode()) {\n newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);\n }\n }\n }\n complete =\n viewCache.serverCache.isFullyInitialized() ||\n writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;\n return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A view represents a specific location and query that has 1 or more event registrations.\n *\n * It does several things:\n * - Maintains the list of event registrations for this location/query.\n * - Maintains a cache of the data visible for this location/query.\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\n * registrations returns the set of events to be raised.\n */\nclass View {\n constructor(query_, initialViewCache) {\n this.query_ = query_;\n this.eventRegistrations_ = [];\n const params = this.query_._queryParams;\n const indexFilter = new IndexedFilter(params.getIndex());\n const filter = queryParamsGetNodeFilter(params);\n this.processor_ = newViewProcessor(filter);\n const initialServerCache = initialViewCache.serverCache;\n const initialEventCache = initialViewCache.eventCache;\n // Don't filter server node with other filter than index, wait for tagged listen\n const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);\n const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);\n const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());\n const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());\n this.viewCache_ = newViewCache(newEventCache, newServerCache);\n this.eventGenerator_ = new EventGenerator(this.query_);\n }\n get query() {\n return this.query_;\n }\n}\nfunction viewGetServerCache(view) {\n return view.viewCache_.serverCache.getNode();\n}\nfunction viewGetCompleteNode(view) {\n return viewCacheGetCompleteEventSnap(view.viewCache_);\n}\nfunction viewGetCompleteServerCache(view, path) {\n const cache = viewCacheGetCompleteServerSnap(view.viewCache_);\n if (cache) {\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\n // we need to see if it contains the child we're interested in.\n if (view.query._queryParams.loadsAllData() ||\n (!pathIsEmpty(path) &&\n !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {\n return cache.getChild(path);\n }\n }\n return null;\n}\nfunction viewIsEmpty(view) {\n return view.eventRegistrations_.length === 0;\n}\nfunction viewAddEventRegistration(view, eventRegistration) {\n view.eventRegistrations_.push(eventRegistration);\n}\n/**\n * @param eventRegistration - If null, remove all callbacks.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @returns Cancel events, if cancelError was provided.\n */\nfunction viewRemoveEventRegistration(view, eventRegistration, cancelError) {\n const cancelEvents = [];\n if (cancelError) {\n util.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');\n const path = view.query._path;\n view.eventRegistrations_.forEach(registration => {\n const maybeEvent = registration.createCancelEvent(cancelError, path);\n if (maybeEvent) {\n cancelEvents.push(maybeEvent);\n }\n });\n }\n if (eventRegistration) {\n let remaining = [];\n for (let i = 0; i < view.eventRegistrations_.length; ++i) {\n const existing = view.eventRegistrations_[i];\n if (!existing.matches(eventRegistration)) {\n remaining.push(existing);\n }\n else if (eventRegistration.hasAnyCallback()) {\n // We're removing just this one\n remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));\n break;\n }\n }\n view.eventRegistrations_ = remaining;\n }\n else {\n view.eventRegistrations_ = [];\n }\n return cancelEvents;\n}\n/**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n */\nfunction viewApplyOperation(view, operation, writesCache, completeServerCache) {\n if (operation.type === OperationType.MERGE &&\n operation.source.queryId !== null) {\n util.assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');\n util.assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');\n }\n const oldViewCache = view.viewCache_;\n const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);\n viewProcessorAssertIndexed(view.processor_, result.viewCache);\n util.assert(result.viewCache.serverCache.isFullyInitialized() ||\n !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');\n view.viewCache_ = result.viewCache;\n return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);\n}\nfunction viewGetInitialEvents(view, registration) {\n const eventSnap = view.viewCache_.eventCache;\n const initialChanges = [];\n if (!eventSnap.getNode().isLeafNode()) {\n const eventNode = eventSnap.getNode();\n eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n initialChanges.push(changeChildAdded(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(changeValue(eventSnap.getNode()));\n }\n return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);\n}\nfunction viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {\n const registrations = eventRegistration\n ? [eventRegistration]\n : view.eventRegistrations_;\n return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nlet referenceConstructor$1;\n/**\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\n * and user writes (set, transaction, update).\n *\n * It's responsible for:\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\n * applyUserOverwrite, etc.)\n */\nclass SyncPoint {\n constructor() {\n /**\n * The Views being tracked at this location in the tree, stored as a map where the key is a\n * queryId and the value is the View for that query.\n *\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\n */\n this.views = new Map();\n }\n}\nfunction syncPointSetReferenceConstructor(val) {\n util.assert(!referenceConstructor$1, '__referenceConstructor has already been defined');\n referenceConstructor$1 = val;\n}\nfunction syncPointGetReferenceConstructor() {\n util.assert(referenceConstructor$1, 'Reference.ts has not been loaded');\n return referenceConstructor$1;\n}\nfunction syncPointIsEmpty(syncPoint) {\n return syncPoint.views.size === 0;\n}\nfunction syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {\n const queryId = operation.source.queryId;\n if (queryId !== null) {\n const view = syncPoint.views.get(queryId);\n util.assert(view != null, 'SyncTree gave us an op for an invalid query.');\n return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);\n }\n else {\n let events = [];\n for (const view of syncPoint.views.values()) {\n events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));\n }\n return events;\n }\n}\n/**\n * Get a view for the specified query.\n *\n * @param query - The query to return a view for\n * @param writesCache\n * @param serverCache\n * @param serverCacheComplete\n * @returns Events to raise.\n */\nfunction syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {\n const queryId = query._queryIdentifier;\n const view = syncPoint.views.get(queryId);\n if (!view) {\n // TODO: make writesCache take flag for complete server node\n let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);\n let eventCacheComplete = false;\n if (eventCache) {\n eventCacheComplete = true;\n }\n else if (serverCache instanceof ChildrenNode) {\n eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);\n eventCacheComplete = false;\n }\n else {\n eventCache = ChildrenNode.EMPTY_NODE;\n eventCacheComplete = false;\n }\n const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));\n return new View(query, viewCache);\n }\n return view;\n}\n/**\n * Add an event callback for the specified query.\n *\n * @param query\n * @param eventRegistration\n * @param writesCache\n * @param serverCache - Complete server cache, if we have it.\n * @param serverCacheComplete\n * @returns Events to raise.\n */\nfunction syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {\n const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);\n if (!syncPoint.views.has(query._queryIdentifier)) {\n syncPoint.views.set(query._queryIdentifier, view);\n }\n // This is guaranteed to exist now, we just created anything that was missing\n viewAddEventRegistration(view, eventRegistration);\n return viewGetInitialEvents(view, eventRegistration);\n}\n/**\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\n *\n * If query is the default query, we'll check all views for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\n *\n * @param eventRegistration - If null, remove all callbacks.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @returns removed queries and any cancel events\n */\nfunction syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {\n const queryId = query._queryIdentifier;\n const removed = [];\n let cancelEvents = [];\n const hadCompleteView = syncPointHasCompleteView(syncPoint);\n if (queryId === 'default') {\n // When you do ref.off(...), we search all views for the registration to remove.\n for (const [viewQueryId, view] of syncPoint.views.entries()) {\n cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));\n if (viewIsEmpty(view)) {\n syncPoint.views.delete(viewQueryId);\n // We'll deal with complete views later.\n if (!view.query._queryParams.loadsAllData()) {\n removed.push(view.query);\n }\n }\n }\n }\n else {\n // remove the callback from the specific view.\n const view = syncPoint.views.get(queryId);\n if (view) {\n cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));\n if (viewIsEmpty(view)) {\n syncPoint.views.delete(queryId);\n // We'll deal with complete views later.\n if (!view.query._queryParams.loadsAllData()) {\n removed.push(view.query);\n }\n }\n }\n }\n if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {\n // We removed our last complete view.\n removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));\n }\n return { removed, events: cancelEvents };\n}\nfunction syncPointGetQueryViews(syncPoint) {\n const result = [];\n for (const view of syncPoint.views.values()) {\n if (!view.query._queryParams.loadsAllData()) {\n result.push(view);\n }\n }\n return result;\n}\n/**\n * @param path - The path to the desired complete snapshot\n * @returns A complete cache, if it exists\n */\nfunction syncPointGetCompleteServerCache(syncPoint, path) {\n let serverCache = null;\n for (const view of syncPoint.views.values()) {\n serverCache = serverCache || viewGetCompleteServerCache(view, path);\n }\n return serverCache;\n}\nfunction syncPointViewForQuery(syncPoint, query) {\n const params = query._queryParams;\n if (params.loadsAllData()) {\n return syncPointGetCompleteView(syncPoint);\n }\n else {\n const queryId = query._queryIdentifier;\n return syncPoint.views.get(queryId);\n }\n}\nfunction syncPointViewExistsForQuery(syncPoint, query) {\n return syncPointViewForQuery(syncPoint, query) != null;\n}\nfunction syncPointHasCompleteView(syncPoint) {\n return syncPointGetCompleteView(syncPoint) != null;\n}\nfunction syncPointGetCompleteView(syncPoint) {\n for (const view of syncPoint.views.values()) {\n if (view.query._queryParams.loadsAllData()) {\n return view;\n }\n }\n return null;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nlet referenceConstructor;\nfunction syncTreeSetReferenceConstructor(val) {\n util.assert(!referenceConstructor, '__referenceConstructor has already been defined');\n referenceConstructor = val;\n}\nfunction syncTreeGetReferenceConstructor() {\n util.assert(referenceConstructor, 'Reference.ts has not been loaded');\n return referenceConstructor;\n}\n/**\n * Static tracker for next query tag.\n */\nlet syncTreeNextQueryTag_ = 1;\n/**\n * SyncTree is the central class for managing event callback registration, data caching, views\n * (query processing), and event generation. There are typically two SyncTree instances for\n * each Repo, one for the normal Firebase data, and one for the .info data.\n *\n * It has a number of responsibilities, including:\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\n * - Applying and caching data changes for user set(), transaction(), and update() calls\n * (applyUserOverwrite(), applyUserMerge()).\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\n * applyServerMerge()).\n * - Generating user-facing events for server and user changes (all of the apply* methods\n * return the set of events that need to be raised as a result).\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\n * to the correct set of paths and queries to satisfy the current set of user event\n * callbacks (listens are started/stopped using the provided listenProvider).\n *\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\n * events are returned to the caller rather than raised synchronously.\n *\n */\nclass SyncTree {\n /**\n * @param listenProvider_ - Used by SyncTree to start / stop listening\n * to server data.\n */\n constructor(listenProvider_) {\n this.listenProvider_ = listenProvider_;\n /**\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\n */\n this.syncPointTree_ = new ImmutableTree(null);\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n */\n this.pendingWriteTree_ = newWriteTree();\n this.tagToQueryMap = new Map();\n this.queryToTagMap = new Map();\n }\n}\n/**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @returns Events to raise.\n */\nfunction syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {\n // Record pending write.\n writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);\n if (!visible) {\n return [];\n }\n else {\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));\n }\n}\n/**\n * Apply the data from a user-generated update() call\n *\n * @returns Events to raise.\n */\nfunction syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {\n // Record pending merge.\n writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);\n const changeTree = ImmutableTree.fromObject(changedChildren);\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));\n}\n/**\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\n *\n * @param revert - True if the given write failed and needs to be reverted\n * @returns Events to raise.\n */\nfunction syncTreeAckUserWrite(syncTree, writeId, revert = false) {\n const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);\n const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);\n if (!needToReevaluate) {\n return [];\n }\n else {\n let affectedTree = new ImmutableTree(null);\n if (write.snap != null) {\n // overwrite\n affectedTree = affectedTree.set(newEmptyPath(), true);\n }\n else {\n each(write.children, (pathString) => {\n affectedTree = affectedTree.set(new Path(pathString), true);\n });\n }\n return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert));\n }\n}\n/**\n * Apply new server data for the specified path..\n *\n * @returns Events to raise.\n */\nfunction syncTreeApplyServerOverwrite(syncTree, path, newData) {\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));\n}\n/**\n * Apply new server data to be merged in at the specified path.\n *\n * @returns Events to raise.\n */\nfunction syncTreeApplyServerMerge(syncTree, path, changedChildren) {\n const changeTree = ImmutableTree.fromObject(changedChildren);\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));\n}\n/**\n * Apply a listen complete for a query\n *\n * @returns Events to raise.\n */\nfunction syncTreeApplyListenComplete(syncTree, path) {\n return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));\n}\n/**\n * Apply a listen complete for a tagged query\n *\n * @returns Events to raise.\n */\nfunction syncTreeApplyTaggedListenComplete(syncTree, path, tag) {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path, queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n}\n/**\n * Remove event callback(s).\n *\n * If query is the default query, we'll check all queries for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\n *\n * @param eventRegistration - If null, all callbacks are removed.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no\n * deduping needs to take place. This flag allows toggling of that behavior\n * @returns Cancel events, if cancelError was provided.\n */\nfunction syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) {\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\n const path = query._path;\n const maybeSyncPoint = syncTree.syncPointTree_.get(path);\n let cancelEvents = [];\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\n // not loadsAllData().\n if (maybeSyncPoint &&\n (query._queryIdentifier === 'default' ||\n syncPointViewExistsForQuery(maybeSyncPoint, query))) {\n const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);\n if (syncPointIsEmpty(maybeSyncPoint)) {\n syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);\n }\n const removed = removedAndEvents.removed;\n cancelEvents = removedAndEvents.events;\n if (!skipListenerDedup) {\n /**\n * We may have just removed one of many listeners and can short-circuit this whole process\n * We may also not have removed a default listener, in which case all of the descendant listeners should already be\n * properly set up.\n */\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\n // queryId === 'default'\n const removingDefault = -1 !==\n removed.findIndex(query => {\n return query._queryParams.loadsAllData();\n });\n const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint));\n if (removingDefault && !covered) {\n const subtree = syncTree.syncPointTree_.subtree(path);\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\n // removal\n if (!subtree.isEmpty()) {\n // We need to fold over our subtree and collect the listeners to send\n const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);\n // Ok, we've collected all the listens we need. Set them up.\n for (let i = 0; i < newViews.length; ++i) {\n const view = newViews[i], newQuery = view.query;\n const listener = syncTreeCreateListenerForView_(syncTree, view);\n syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);\n }\n }\n // Otherwise there's nothing below us, so nothing we need to start listening on\n }\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\n if (!covered && removed.length > 0 && !cancelError) {\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\n // default. Otherwise, we need to iterate through and cancel each individual query\n if (removingDefault) {\n // We don't tag default listeners\n const defaultTag = null;\n syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);\n }\n else {\n removed.forEach((queryToRemove) => {\n const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));\n syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);\n });\n }\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n syncTreeRemoveTags_(syncTree, removed);\n }\n return cancelEvents;\n}\n/**\n * Apply new server data for the specified tagged query.\n *\n * @returns Events to raise.\n */\nfunction syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey != null) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path, queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n }\n else {\n // Query must have been removed already\n return [];\n }\n}\n/**\n * Apply server data to be merged in for the specified tagged query.\n *\n * @returns Events to raise.\n */\nfunction syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path, queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const changeTree = ImmutableTree.fromObject(changedChildren);\n const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n}\n/**\n * Add an event callback for the specified query.\n *\n * @returns Events to raise.\n */\nfunction syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) {\n const path = query._path;\n let serverCache = null;\n let foundAncestorDefaultView = false;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\n const relativePath = newRelativePath(pathToSyncPoint, path);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPointHasCompleteView(sp);\n });\n let syncPoint = syncTree.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint();\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\n }\n else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n let serverCacheComplete;\n if (serverCache != null) {\n serverCacheComplete = true;\n }\n else {\n serverCacheComplete = false;\n serverCache = ChildrenNode.EMPTY_NODE;\n const subtree = syncTree.syncPointTree_.subtree(path);\n subtree.foreachChild((childName, childSyncPoint) => {\n const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(childName, completeCache);\n }\n });\n }\n const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);\n if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {\n // We need to track a tag for this query\n const queryKey = syncTreeMakeQueryKey_(query);\n util.assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');\n const tag = syncTreeGetNextQueryTag_();\n syncTree.queryToTagMap.set(queryKey, tag);\n syncTree.tagToQueryMap.set(tag, queryKey);\n }\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);\n let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);\n if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {\n const view = syncPointViewForQuery(syncPoint, query);\n events = events.concat(syncTreeSetupListener_(syncTree, query, view));\n }\n return events;\n}\n/**\n * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a\n * listener above it, we will get a false \"null\". This shouldn't be a problem because transactions will always\n * have a listener above, and atomic operations would correctly show a jitter of ->\n * as the write is applied locally and then acknowledged at the server.\n *\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\n *\n * @param path - The path to the data we want\n * @param writeIdsToExclude - A specific set to be excluded\n */\nfunction syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {\n const includeHiddenSets = true;\n const writeTree = syncTree.pendingWriteTree_;\n const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => {\n const relativePath = newRelativePath(pathSoFar, path);\n const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);\n if (serverCache) {\n return serverCache;\n }\n });\n return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);\n}\nfunction syncTreeGetServerValue(syncTree, query) {\n const path = query._path;\n let serverCache = null;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\n const relativePath = newRelativePath(pathToSyncPoint, path);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\n });\n let syncPoint = syncTree.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint();\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\n }\n else {\n serverCache =\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n const serverCacheComplete = serverCache != null;\n const serverCacheNode = serverCacheComplete\n ? new CacheNode(serverCache, true, false)\n : null;\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);\n const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);\n return viewGetCompleteNode(view);\n}\n/**\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\n *\n * NOTES:\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\n *\n * - We call applyOperation() on each SyncPoint passing three things:\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\n * 3. A snapshot Node with cached server data, if we have it.\n *\n * - We concatenate all of the events returned by each SyncPoint and return the result.\n */\nfunction syncTreeApplyOperationToSyncPoints_(syncTree, operation) {\n return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_, \n /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));\n}\n/**\n * Recursive helper for applyOperationToSyncPoints_\n */\nfunction syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {\n if (pathIsEmpty(operation.path)) {\n return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);\n }\n else {\n const syncPoint = syncPointTree.get(newEmptyPath());\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n let events = [];\n const childName = pathGetFront(operation.path);\n const childOperation = operation.operationForChild(childName);\n const childTree = syncPointTree.children.get(childName);\n if (childTree && childOperation) {\n const childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n const childWritesCache = writeTreeRefChild(writesCache, childName);\n events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n if (syncPoint) {\n events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));\n }\n return events;\n }\n}\n/**\n * Recursive helper for applyOperationToSyncPoints_\n */\nfunction syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {\n const syncPoint = syncPointTree.get(newEmptyPath());\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n let events = [];\n syncPointTree.children.inorderTraversal((childName, childTree) => {\n const childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n const childWritesCache = writeTreeRefChild(writesCache, childName);\n const childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n });\n if (syncPoint) {\n events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));\n }\n return events;\n}\nfunction syncTreeCreateListenerForView_(syncTree, view) {\n const query = view.query;\n const tag = syncTreeTagForQuery(syncTree, query);\n return {\n hashFn: () => {\n const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: (status) => {\n if (status === 'ok') {\n if (tag) {\n return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);\n }\n else {\n return syncTreeApplyListenComplete(syncTree, query._path);\n }\n }\n else {\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\n const error = errorForServerCode(status, query);\n return syncTreeRemoveEventRegistration(syncTree, query, \n /*eventRegistration*/ null, error);\n }\n }\n };\n}\n/**\n * Return the tag associated with the given query.\n */\nfunction syncTreeTagForQuery(syncTree, query) {\n const queryKey = syncTreeMakeQueryKey_(query);\n return syncTree.queryToTagMap.get(queryKey);\n}\n/**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n */\nfunction syncTreeMakeQueryKey_(query) {\n return query._path.toString() + '$' + query._queryIdentifier;\n}\n/**\n * Return the query associated with the given tag, if we have one\n */\nfunction syncTreeQueryKeyForTag_(syncTree, tag) {\n return syncTree.tagToQueryMap.get(tag);\n}\n/**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n */\nfunction syncTreeParseQueryKey_(queryKey) {\n const splitIndex = queryKey.indexOf('$');\n util.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');\n return {\n queryId: queryKey.substr(splitIndex + 1),\n path: new Path(queryKey.substr(0, splitIndex))\n };\n}\n/**\n * A helper method to apply tagged operations\n */\nfunction syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {\n const syncPoint = syncTree.syncPointTree_.get(queryPath);\n util.assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);\n return syncPointApplyOperation(syncPoint, operation, writesCache, null);\n}\n/**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n */\nfunction syncTreeCollectDistinctViewsForSubTree_(subtree) {\n return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {\n if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {\n const completeView = syncPointGetCompleteView(maybeChildSyncPoint);\n return [completeView];\n }\n else {\n // No complete view here, flatten any deeper listens into an array\n let views = [];\n if (maybeChildSyncPoint) {\n views = syncPointGetQueryViews(maybeChildSyncPoint);\n }\n each(childMap, (_key, childViews) => {\n views = views.concat(childViews);\n });\n return views;\n }\n });\n}\n/**\n * Normalizes a query to a query we send the server for listening\n *\n * @returns The normalized query\n */\nfunction syncTreeQueryForListening_(query) {\n if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {\n // We treat queries that load all data as default queries\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n // from Query\n return new (syncTreeGetReferenceConstructor())(query._repo, query._path);\n }\n else {\n return query;\n }\n}\nfunction syncTreeRemoveTags_(syncTree, queries) {\n for (let j = 0; j < queries.length; ++j) {\n const removedQuery = queries[j];\n if (!removedQuery._queryParams.loadsAllData()) {\n // We should have a tag for this\n const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);\n const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);\n syncTree.queryToTagMap.delete(removedQueryKey);\n syncTree.tagToQueryMap.delete(removedQueryTag);\n }\n }\n}\n/**\n * Static accessor for query tags.\n */\nfunction syncTreeGetNextQueryTag_() {\n return syncTreeNextQueryTag_++;\n}\n/**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @returns This method can return events to support synchronous data sources\n */\nfunction syncTreeSetupListener_(syncTree, query, view) {\n const path = query._path;\n const tag = syncTreeTagForQuery(syncTree, query);\n const listener = syncTreeCreateListenerForView_(syncTree, view);\n const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);\n const subtree = syncTree.syncPointTree_.subtree(path);\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\n // may need to shadow other listens as well.\n if (tag) {\n util.assert(!syncPointHasCompleteView(subtree.value), \"If we're adding a query, it shouldn't be shadowed\");\n }\n else {\n // Shadow everything at or below this location, this is a default listener.\n const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {\n if (!pathIsEmpty(relativePath) &&\n maybeChildSyncPoint &&\n syncPointHasCompleteView(maybeChildSyncPoint)) {\n return [syncPointGetCompleteView(maybeChildSyncPoint).query];\n }\n else {\n // No default listener here, flatten any deeper queries into an array\n let queries = [];\n if (maybeChildSyncPoint) {\n queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query));\n }\n each(childMap, (_key, childQueries) => {\n queries = queries.concat(childQueries);\n });\n return queries;\n }\n });\n for (let i = 0; i < queriesToStop.length; ++i) {\n const queryToStop = queriesToStop[i];\n syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));\n }\n }\n return events;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass ExistingValueProvider {\n constructor(node_) {\n this.node_ = node_;\n }\n getImmediateChild(childName) {\n const child = this.node_.getImmediateChild(childName);\n return new ExistingValueProvider(child);\n }\n node() {\n return this.node_;\n }\n}\nclass DeferredValueProvider {\n constructor(syncTree, path) {\n this.syncTree_ = syncTree;\n this.path_ = path;\n }\n getImmediateChild(childName) {\n const childPath = pathChild(this.path_, childName);\n return new DeferredValueProvider(this.syncTree_, childPath);\n }\n node() {\n return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);\n }\n}\n/**\n * Generate placeholders for deferred values.\n */\nconst generateWithValues = function (values) {\n values = values || {};\n values['timestamp'] = values['timestamp'] || new Date().getTime();\n return values;\n};\n/**\n * Value to use when firing local events. When writing server values, fire\n * local events with an approximate value, otherwise return value as-is.\n */\nconst resolveDeferredLeafValue = function (value, existingVal, serverValues) {\n if (!value || typeof value !== 'object') {\n return value;\n }\n util.assert('.sv' in value, 'Unexpected leaf node or priority contents');\n if (typeof value['.sv'] === 'string') {\n return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);\n }\n else if (typeof value['.sv'] === 'object') {\n return resolveComplexDeferredValue(value['.sv'], existingVal);\n }\n else {\n util.assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));\n }\n};\nconst resolveScalarDeferredValue = function (op, existing, serverValues) {\n switch (op) {\n case 'timestamp':\n return serverValues['timestamp'];\n default:\n util.assert(false, 'Unexpected server value: ' + op);\n }\n};\nconst resolveComplexDeferredValue = function (op, existing, unused) {\n if (!op.hasOwnProperty('increment')) {\n util.assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));\n }\n const delta = op['increment'];\n if (typeof delta !== 'number') {\n util.assert(false, 'Unexpected increment value: ' + delta);\n }\n const existingNode = existing.node();\n util.assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');\n // Incrementing a non-number sets the value to the incremented amount\n if (!existingNode.isLeafNode()) {\n return delta;\n }\n const leaf = existingNode;\n const existingVal = leaf.getValue();\n if (typeof existingVal !== 'number') {\n return delta;\n }\n // No need to do over/underflow arithmetic here because JS only handles floats under the covers\n return existingVal + delta;\n};\n/**\n * Recursively replace all deferred values and priorities in the tree with the\n * specified generated replacement values.\n * @param path - path to which write is relative\n * @param node - new data written at path\n * @param syncTree - current data\n */\nconst resolveDeferredValueTree = function (path, node, syncTree, serverValues) {\n return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);\n};\n/**\n * Recursively replace all deferred values and priorities in the node with the\n * specified generated replacement values. If there are no server values in the node,\n * it'll be returned as-is.\n */\nconst resolveDeferredValueSnapshot = function (node, existing, serverValues) {\n return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);\n};\nfunction resolveDeferredValue(node, existingVal, serverValues) {\n const rawPri = node.getPriority().val();\n const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);\n let newNode;\n if (node.isLeafNode()) {\n const leafNode = node;\n const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);\n if (value !== leafNode.getValue() ||\n priority !== leafNode.getPriority().val()) {\n return new LeafNode(value, nodeFromJSON(priority));\n }\n else {\n return node;\n }\n }\n else {\n const childrenNode = node;\n newNode = childrenNode;\n if (priority !== childrenNode.getPriority().val()) {\n newNode = newNode.updatePriority(new LeafNode(priority));\n }\n childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\n const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);\n if (newChildNode !== childNode) {\n newNode = newNode.updateImmediateChild(childName, newChildNode);\n }\n });\n return newNode;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A light-weight tree, traversable by path. Nodes can have both values and children.\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\n * children.\n */\nclass Tree {\n /**\n * @param name - Optional name of the node.\n * @param parent - Optional parent node.\n * @param node - Optional node to wrap.\n */\n constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) {\n this.name = name;\n this.parent = parent;\n this.node = node;\n }\n}\n/**\n * Returns a sub-Tree for the given path.\n *\n * @param pathObj - Path to look up.\n * @returns Tree for path.\n */\nfunction treeSubTree(tree, pathObj) {\n // TODO: Require pathObj to be Path?\n let path = pathObj instanceof Path ? pathObj : new Path(pathObj);\n let child = tree, next = pathGetFront(path);\n while (next !== null) {\n const childNode = util.safeGet(child.node.children, next) || {\n children: {},\n childCount: 0\n };\n child = new Tree(next, child, childNode);\n path = pathPopFront(path);\n next = pathGetFront(path);\n }\n return child;\n}\n/**\n * Returns the data associated with this tree node.\n *\n * @returns The data or null if no data exists.\n */\nfunction treeGetValue(tree) {\n return tree.node.value;\n}\n/**\n * Sets data to this tree node.\n *\n * @param value - Value to set.\n */\nfunction treeSetValue(tree, value) {\n tree.node.value = value;\n treeUpdateParents(tree);\n}\n/**\n * @returns Whether the tree has any children.\n */\nfunction treeHasChildren(tree) {\n return tree.node.childCount > 0;\n}\n/**\n * @returns Whether the tree is empty (no value or children).\n */\nfunction treeIsEmpty(tree) {\n return treeGetValue(tree) === undefined && !treeHasChildren(tree);\n}\n/**\n * Calls action for each child of this tree node.\n *\n * @param action - Action to be called for each child.\n */\nfunction treeForEachChild(tree, action) {\n each(tree.node.children, (child, childTree) => {\n action(new Tree(child, tree, childTree));\n });\n}\n/**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param action - Action to be called for each child.\n * @param includeSelf - Whether to call action on this node as well. Defaults to\n * false.\n * @param childrenFirst - Whether to call action on children before calling it on\n * parent.\n */\nfunction treeForEachDescendant(tree, action, includeSelf, childrenFirst) {\n if (includeSelf && !childrenFirst) {\n action(tree);\n }\n treeForEachChild(tree, child => {\n treeForEachDescendant(child, action, true, childrenFirst);\n });\n if (includeSelf && childrenFirst) {\n action(tree);\n }\n}\n/**\n * Calls action on each ancestor node.\n *\n * @param action - Action to be called on each parent; return\n * true to abort.\n * @param includeSelf - Whether to call action on this node as well.\n * @returns true if the action callback returned true.\n */\nfunction treeForEachAncestor(tree, action, includeSelf) {\n let node = includeSelf ? tree : tree.parent;\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n node = node.parent;\n }\n return false;\n}\n/**\n * @returns The path of this tree node, as a Path.\n */\nfunction treeGetPath(tree) {\n return new Path(tree.parent === null\n ? tree.name\n : treeGetPath(tree.parent) + '/' + tree.name);\n}\n/**\n * Adds or removes this child from its parent based on whether it's empty or not.\n */\nfunction treeUpdateParents(tree) {\n if (tree.parent !== null) {\n treeUpdateChild(tree.parent, tree.name, tree);\n }\n}\n/**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param childName - The name of the child to update.\n * @param child - The child to update.\n */\nfunction treeUpdateChild(tree, childName, child) {\n const childEmpty = treeIsEmpty(child);\n const childExists = util.contains(tree.node.children, childName);\n if (childEmpty && childExists) {\n delete tree.node.children[childName];\n tree.node.childCount--;\n treeUpdateParents(tree);\n }\n else if (!childEmpty && !childExists) {\n tree.node.children[childName] = child.node;\n tree.node.childCount++;\n treeUpdateParents(tree);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * True for invalid Firebase keys\n */\nconst INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\n/**\n * True for invalid Firebase paths.\n * Allows '/' in paths.\n */\nconst INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\n/**\n * Maximum number of characters to allow in leaf value\n */\nconst MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\nconst isValidKey = function (key) {\n return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));\n};\nconst isValidPathString = function (pathString) {\n return (typeof pathString === 'string' &&\n pathString.length !== 0 &&\n !INVALID_PATH_REGEX_.test(pathString));\n};\nconst isValidRootPathString = function (pathString) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n return isValidPathString(pathString);\n};\nconst isValidPriority = function (priority) {\n return (priority === null ||\n typeof priority === 'string' ||\n (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||\n (priority &&\n typeof priority === 'object' &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n util.contains(priority, '.sv')));\n};\n/**\n * Pre-validate a datum passed as an argument to Firebase function.\n */\nconst validateFirebaseDataArg = function (fnName, value, path, optional) {\n if (optional && value === undefined) {\n return;\n }\n validateFirebaseData(util.errorPrefix(fnName, 'value'), value, path);\n};\n/**\n * Validate a data object client-side before sending to server.\n */\nconst validateFirebaseData = function (errorPrefix, data, path_) {\n const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;\n if (data === undefined) {\n throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));\n }\n if (typeof data === 'function') {\n throw new Error(errorPrefix +\n 'contains a function ' +\n validationPathToErrorString(path) +\n ' with contents = ' +\n data.toString());\n }\n if (isInvalidJSONNumber(data)) {\n throw new Error(errorPrefix +\n 'contains ' +\n data.toString() +\n ' ' +\n validationPathToErrorString(path));\n }\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\n if (typeof data === 'string' &&\n data.length > MAX_LEAF_SIZE_ / 3 &&\n util.stringLength(data) > MAX_LEAF_SIZE_) {\n throw new Error(errorPrefix +\n 'contains a string greater than ' +\n MAX_LEAF_SIZE_ +\n ' utf8 bytes ' +\n validationPathToErrorString(path) +\n \" ('\" +\n data.substring(0, 50) +\n \"...')\");\n }\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\n // to save extra walking of large objects.\n if (data && typeof data === 'object') {\n let hasDotValue = false;\n let hasActualChild = false;\n each(data, (key, value) => {\n if (key === '.value') {\n hasDotValue = true;\n }\n else if (key !== '.priority' && key !== '.sv') {\n hasActualChild = true;\n if (!isValidKey(key)) {\n throw new Error(errorPrefix +\n ' contains an invalid key (' +\n key +\n ') ' +\n validationPathToErrorString(path) +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n }\n }\n validationPathPush(path, key);\n validateFirebaseData(errorPrefix, value, path);\n validationPathPop(path);\n });\n if (hasDotValue && hasActualChild) {\n throw new Error(errorPrefix +\n ' contains \".value\" child ' +\n validationPathToErrorString(path) +\n ' in addition to actual children.');\n }\n }\n};\n/**\n * Pre-validate paths passed in the firebase function.\n */\nconst validateFirebaseMergePaths = function (errorPrefix, mergePaths) {\n let i, curPath;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n const keys = pathSlice(curPath);\n for (let j = 0; j < keys.length; j++) {\n if (keys[j] === '.priority' && j === keys.length - 1) ;\n else if (!isValidKey(keys[j])) {\n throw new Error(errorPrefix +\n 'contains an invalid key (' +\n keys[j] +\n ') in path ' +\n curPath.toString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n }\n }\n }\n // Check that update keys are not descendants of each other.\n // We rely on the property that sorting guarantees that ancestors come\n // right before descendants.\n mergePaths.sort(pathCompare);\n let prevPath = null;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n if (prevPath !== null && pathContains(prevPath, curPath)) {\n throw new Error(errorPrefix +\n 'contains a path ' +\n prevPath.toString() +\n ' that is ancestor of another path ' +\n curPath.toString());\n }\n prevPath = curPath;\n }\n};\n/**\n * pre-validate an object passed as an argument to firebase function (\n * must be an object - e.g. for firebase.update()).\n */\nconst validateFirebaseMergeDataArg = function (fnName, data, path, optional) {\n if (optional && data === undefined) {\n return;\n }\n const errorPrefix = util.errorPrefix(fnName, 'values');\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\n throw new Error(errorPrefix + ' must be an object containing the children to replace.');\n }\n const mergePaths = [];\n each(data, (key, value) => {\n const curPath = new Path(key);\n validateFirebaseData(errorPrefix, value, pathChild(path, curPath));\n if (pathGetBack(curPath) === '.priority') {\n if (!isValidPriority(value)) {\n throw new Error(errorPrefix +\n \"contains an invalid value for '\" +\n curPath.toString() +\n \"', which must be a valid \" +\n 'Firebase priority (a string, finite number, server value, or null).');\n }\n }\n mergePaths.push(curPath);\n });\n validateFirebaseMergePaths(errorPrefix, mergePaths);\n};\nconst validatePriority = function (fnName, priority, optional) {\n if (optional && priority === undefined) {\n return;\n }\n if (isInvalidJSONNumber(priority)) {\n throw new Error(util.errorPrefix(fnName, 'priority') +\n 'is ' +\n priority.toString() +\n ', but must be a valid Firebase priority (a string, finite number, ' +\n 'server value, or null).');\n }\n // Special case to allow importing data with a .sv.\n if (!isValidPriority(priority)) {\n throw new Error(util.errorPrefix(fnName, 'priority') +\n 'must be a valid Firebase priority ' +\n '(a string, finite number, server value, or null).');\n }\n};\nconst validateKey = function (fnName, argumentName, key, optional) {\n if (optional && key === undefined) {\n return;\n }\n if (!isValidKey(key)) {\n throw new Error(util.errorPrefix(fnName, argumentName) +\n 'was an invalid key = \"' +\n key +\n '\". Firebase keys must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").');\n }\n};\n/**\n * @internal\n */\nconst validatePathString = function (fnName, argumentName, pathString, optional) {\n if (optional && pathString === undefined) {\n return;\n }\n if (!isValidPathString(pathString)) {\n throw new Error(util.errorPrefix(fnName, argumentName) +\n 'was an invalid path = \"' +\n pathString +\n '\". Paths must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"');\n }\n};\nconst validateRootPathString = function (fnName, argumentName, pathString, optional) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n validatePathString(fnName, argumentName, pathString, optional);\n};\n/**\n * @internal\n */\nconst validateWritablePath = function (fnName, path) {\n if (pathGetFront(path) === '.info') {\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\n }\n};\nconst validateUrl = function (fnName, parsedUrl) {\n // TODO = Validate server better.\n const pathString = parsedUrl.path.toString();\n if (!(typeof parsedUrl.repoInfo.host === 'string') ||\n parsedUrl.repoInfo.host.length === 0 ||\n (!isValidKey(parsedUrl.repoInfo.namespace) &&\n parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||\n (pathString.length !== 0 && !isValidRootPathString(pathString))) {\n throw new Error(util.errorPrefix(fnName, 'url') +\n 'must be a valid firebase URL and ' +\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".');\n }\n};\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The event queue serves a few purposes:\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\n * events being queued.\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\n * left off, ensuring that the events are still raised synchronously and in order.\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\n * events are raised synchronously.\n *\n * NOTE: This can all go away if/when we move to async events.\n *\n */\nclass EventQueue {\n constructor() {\n this.eventLists_ = [];\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n */\n this.recursionDepth_ = 0;\n }\n}\n/**\n * @param eventDataList - The new events to queue.\n */\nfunction eventQueueQueueEvents(eventQueue, eventDataList) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n let currList = null;\n for (let i = 0; i < eventDataList.length; i++) {\n const data = eventDataList[i];\n const path = data.getPath();\n if (currList !== null && !pathEquals(path, currList.path)) {\n eventQueue.eventLists_.push(currList);\n currList = null;\n }\n if (currList === null) {\n currList = { events: [], path };\n }\n currList.events.push(data);\n }\n if (currList) {\n eventQueue.eventLists_.push(currList);\n }\n}\n/**\n * Queues the specified events and synchronously raises all events (including previously queued ones)\n * for the specified path.\n *\n * It is assumed that the new events are all for the specified path.\n *\n * @param path - The path to raise events for.\n * @param eventDataList - The new events to raise.\n */\nfunction eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {\n eventQueueQueueEvents(eventQueue, eventDataList);\n eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path));\n}\n/**\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\n * locations related to the specified change path (i.e. all ancestors and descendants).\n *\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\n *\n * @param changedPath - The path to raise events for.\n * @param eventDataList - The events to raise\n */\nfunction eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {\n eventQueueQueueEvents(eventQueue, eventDataList);\n eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) ||\n pathContains(changedPath, eventPath));\n}\nfunction eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {\n eventQueue.recursionDepth_++;\n let sentAll = true;\n for (let i = 0; i < eventQueue.eventLists_.length; i++) {\n const eventList = eventQueue.eventLists_[i];\n if (eventList) {\n const eventPath = eventList.path;\n if (predicate(eventPath)) {\n eventListRaise(eventQueue.eventLists_[i]);\n eventQueue.eventLists_[i] = null;\n }\n else {\n sentAll = false;\n }\n }\n }\n if (sentAll) {\n eventQueue.eventLists_ = [];\n }\n eventQueue.recursionDepth_--;\n}\n/**\n * Iterates through the list and raises each event\n */\nfunction eventListRaise(eventList) {\n for (let i = 0; i < eventList.events.length; i++) {\n const eventData = eventList.events[i];\n if (eventData !== null) {\n eventList.events[i] = null;\n const eventFn = eventData.getEventRunner();\n if (logger) {\n log('event: ' + eventData.toString());\n }\n exceptionGuard(eventFn);\n }\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst INTERRUPT_REASON = 'repo_interrupt';\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other\n * things this ensure that if there's ever a bug causing a mismatch between\n * client / server hashes for some data, we won't retry indefinitely.\n */\nconst MAX_TRANSACTION_RETRIES = 25;\n/**\n * A connection to a single data repository.\n */\nclass Repo {\n constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {\n this.repoInfo_ = repoInfo_;\n this.forceRestClient_ = forceRestClient_;\n this.authTokenProvider_ = authTokenProvider_;\n this.appCheckProvider_ = appCheckProvider_;\n this.dataUpdateCount = 0;\n this.statsListener_ = null;\n this.eventQueue_ = new EventQueue();\n this.nextWriteId_ = 1;\n this.interceptServerDataCallback_ = null;\n /** A list of data pieces and paths to be set when this client disconnects. */\n this.onDisconnect_ = newSparseSnapshotTree();\n /** Stores queues of outstanding transactions for Firebase locations. */\n this.transactionQueueTree_ = new Tree();\n // TODO: This should be @private but it's used by test_access.js and internal.js\n this.persistentConnection_ = null;\n // This key is intentionally not updated if RepoInfo is later changed or replaced\n this.key = this.repoInfo_.toURLString();\n }\n /**\n * @returns The URL corresponding to the root of this Firebase.\n */\n toString() {\n return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);\n }\n}\nfunction repoStart(repo, appId, authOverride) {\n repo.stats_ = statsManagerGetCollection(repo.repoInfo_);\n if (repo.forceRestClient_ || beingCrawled()) {\n repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => {\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\n }, repo.authTokenProvider_, repo.appCheckProvider_);\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\n setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);\n }\n else {\n // Validate authOverride\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\n if (typeof authOverride !== 'object') {\n throw new Error('Only objects are supported for option databaseAuthVariableOverride');\n }\n try {\n util.stringify(authOverride);\n }\n catch (e) {\n throw new Error('Invalid authOverride provided: ' + e);\n }\n }\n repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => {\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\n }, (connectStatus) => {\n repoOnConnectStatus(repo, connectStatus);\n }, (updates) => {\n repoOnServerInfoUpdate(repo, updates);\n }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);\n repo.server_ = repo.persistentConnection_;\n }\n repo.authTokenProvider_.addTokenChangeListener(token => {\n repo.server_.refreshAuthToken(token);\n });\n repo.appCheckProvider_.addTokenChangeListener(result => {\n repo.server_.refreshAppCheckToken(result.token);\n });\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\n repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_));\n // Used for .info.\n repo.infoData_ = new SnapshotHolder();\n repo.infoSyncTree_ = new SyncTree({\n startListening: (query, tag, currentHashFn, onComplete) => {\n let infoEvents = [];\n const node = repo.infoData_.getNode(query._path);\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\n // on initial data...\n if (!node.isEmpty()) {\n infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);\n setTimeout(() => {\n onComplete('ok');\n }, 0);\n }\n return infoEvents;\n },\n stopListening: () => { }\n });\n repoUpdateInfo(repo, 'connected', false);\n repo.serverSyncTree_ = new SyncTree({\n startListening: (query, tag, currentHashFn, onComplete) => {\n repo.server_.listen(query, currentHashFn, tag, (status, data) => {\n const events = onComplete(status, data);\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);\n });\n // No synchronous events for network-backed sync trees\n return [];\n },\n stopListening: (query, tag) => {\n repo.server_.unlisten(query, tag);\n }\n });\n}\n/**\n * @returns The time in milliseconds, taking the server offset into account if we have one.\n */\nfunction repoServerTime(repo) {\n const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));\n const offset = offsetNode.val() || 0;\n return new Date().getTime() + offset;\n}\n/**\n * Generate ServerValues using some variables from the repo object.\n */\nfunction repoGenerateServerValues(repo) {\n return generateWithValues({\n timestamp: repoServerTime(repo)\n });\n}\n/**\n * Called by realtime when we get new messages from the server.\n */\nfunction repoOnDataUpdate(repo, pathString, data, isMerge, tag) {\n // For testing.\n repo.dataUpdateCount++;\n const path = new Path(pathString);\n data = repo.interceptServerDataCallback_\n ? repo.interceptServerDataCallback_(pathString, data)\n : data;\n let events = [];\n if (tag) {\n if (isMerge) {\n const taggedChildren = util.map(data, (raw) => nodeFromJSON(raw));\n events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);\n }\n else {\n const taggedSnap = nodeFromJSON(data);\n events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);\n }\n }\n else if (isMerge) {\n const changedChildren = util.map(data, (raw) => nodeFromJSON(raw));\n events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);\n }\n else {\n const snap = nodeFromJSON(data);\n events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);\n }\n let affectedPath = path;\n if (events.length > 0) {\n // Since we have a listener outstanding for each transaction, receiving any events\n // is a proxy for some change having occurred.\n affectedPath = repoRerunTransactions(repo, path);\n }\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);\n}\nfunction repoOnConnectStatus(repo, connectStatus) {\n repoUpdateInfo(repo, 'connected', connectStatus);\n if (connectStatus === false) {\n repoRunOnDisconnectEvents(repo);\n }\n}\nfunction repoOnServerInfoUpdate(repo, updates) {\n each(updates, (key, value) => {\n repoUpdateInfo(repo, key, value);\n });\n}\nfunction repoUpdateInfo(repo, pathString, value) {\n const path = new Path('/.info/' + pathString);\n const newNode = nodeFromJSON(value);\n repo.infoData_.updateSnapshot(path, newNode);\n const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n}\nfunction repoGetNextWriteId(repo) {\n return repo.nextWriteId_++;\n}\n/**\n * The purpose of `getValue` is to return the latest known value\n * satisfying `query`.\n *\n * This method will first check for in-memory cached values\n * belonging to active listeners. If they are found, such values\n * are considered to be the most up-to-date.\n *\n * If the client is not connected, this method will wait until the\n * repo has established a connection and then request the value for `query`.\n * If the client is not able to retrieve the query result for another reason,\n * it reports an error.\n *\n * @param query - The query to surface a value for.\n */\nfunction repoGetValue(repo, query, eventRegistration) {\n // Only active queries are cached. There is no persisted cache.\n const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);\n if (cached != null) {\n return Promise.resolve(cached);\n }\n return repo.server_.get(query).then(payload => {\n const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());\n /**\n * Below we simulate the actions of an `onlyOnce` `onValue()` event where:\n * Add an event registration,\n * Update data at the path,\n * Raise any events,\n * Cleanup the SyncTree\n */\n syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);\n let events;\n if (query._queryParams.loadsAllData()) {\n events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);\n }\n else {\n const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);\n events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);\n }\n /*\n * We need to raise events in the scenario where `get()` is called at a parent path, and\n * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting\n * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree\n * and its corresponding serverCache, including the child location where `onValue` is called. Then,\n * `onValue` will receive the event from the server, but look at the syncTree and see that the data received\n * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.\n * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and\n * ensure the corresponding child events will get fired.\n */\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);\n syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);\n return node;\n }, err => {\n repoLog(repo, 'get for query ' + util.stringify(query) + ' failed: ' + err);\n return Promise.reject(new Error(err));\n });\n}\nfunction repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {\n repoLog(repo, 'set', {\n path: path.toString(),\n value: newVal,\n priority: newPriority\n });\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\n // (b) store unresolved paths on JSON parse\n const serverValues = repoGenerateServerValues(repo);\n const newNodeUnresolved = nodeFromJSON(newVal, newPriority);\n const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);\n const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);\n const writeId = repoGetNextWriteId(repo);\n const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);\n eventQueueQueueEvents(repo.eventQueue_, events);\n repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => {\n const success = status === 'ok';\n if (!success) {\n warn('set at ' + path + ' failed: ' + status);\n }\n const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n });\n const affectedPath = repoAbortTransactions(repo, path);\n repoRerunTransactions(repo, affectedPath);\n // We queued the events above, so just flush the queue here\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);\n}\nfunction repoUpdate(repo, path, childrenToMerge, onComplete) {\n repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });\n // Start with our existing data and merge each child into it.\n let empty = true;\n const serverValues = repoGenerateServerValues(repo);\n const changedChildren = {};\n each(childrenToMerge, (changedKey, changedValue) => {\n empty = false;\n changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);\n });\n if (!empty) {\n const writeId = repoGetNextWriteId(repo);\n const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId);\n eventQueueQueueEvents(repo.eventQueue_, events);\n repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => {\n const success = status === 'ok';\n if (!success) {\n warn('update at ' + path + ' failed: ' + status);\n }\n const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);\n const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n });\n each(childrenToMerge, (changedPath) => {\n const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));\n repoRerunTransactions(repo, affectedPath);\n });\n // We queued the events above, so just flush the queue here\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);\n }\n else {\n log(\"update() called with empty data. Don't do anything.\");\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\n }\n}\n/**\n * Applies all of the changes stored up in the onDisconnect_ tree.\n */\nfunction repoRunOnDisconnectEvents(repo) {\n repoLog(repo, 'onDisconnectEvents');\n const serverValues = repoGenerateServerValues(repo);\n const resolvedOnDisconnectTree = newSparseSnapshotTree();\n sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => {\n const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);\n sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);\n });\n let events = [];\n sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => {\n events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));\n const affectedPath = repoAbortTransactions(repo, path);\n repoRerunTransactions(repo, affectedPath);\n });\n repo.onDisconnect_ = newSparseSnapshotTree();\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);\n}\nfunction repoOnDisconnectCancel(repo, path, onComplete) {\n repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeForget(repo.onDisconnect_, path);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n });\n}\nfunction repoOnDisconnectSet(repo, path, value, onComplete) {\n const newNode = nodeFromJSON(value);\n repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n });\n}\nfunction repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {\n const newNode = nodeFromJSON(value, priority);\n repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n });\n}\nfunction repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {\n if (util.isEmpty(childrenToMerge)) {\n log(\"onDisconnect().update() called with empty data. Don't do anything.\");\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\n return;\n }\n repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => {\n if (status === 'ok') {\n each(childrenToMerge, (childName, childNode) => {\n const newChildNode = nodeFromJSON(childNode);\n sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);\n });\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n });\n}\nfunction repoAddEventCallbackForQuery(repo, query, eventRegistration) {\n let events;\n if (pathGetFront(query._path) === '.info') {\n events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);\n }\n else {\n events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);\n }\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\n}\nfunction repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\n // a little bit by handling the return values anyways.\n let events;\n if (pathGetFront(query._path) === '.info') {\n events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);\n }\n else {\n events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);\n }\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\n}\nfunction repoInterrupt(repo) {\n if (repo.persistentConnection_) {\n repo.persistentConnection_.interrupt(INTERRUPT_REASON);\n }\n}\nfunction repoResume(repo) {\n if (repo.persistentConnection_) {\n repo.persistentConnection_.resume(INTERRUPT_REASON);\n }\n}\nfunction repoLog(repo, ...varArgs) {\n let prefix = '';\n if (repo.persistentConnection_) {\n prefix = repo.persistentConnection_.id + ':';\n }\n log(prefix, ...varArgs);\n}\nfunction repoCallOnCompleteCallback(repo, callback, status, errorReason) {\n if (callback) {\n exceptionGuard(() => {\n if (status === 'ok') {\n callback(null);\n }\n else {\n const code = (status || 'error').toUpperCase();\n let message = code;\n if (errorReason) {\n message += ': ' + errorReason;\n }\n const error = new Error(message);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n error.code = code;\n callback(error);\n }\n });\n }\n}\n/**\n * Creates a new transaction, adds it to the transactions we're tracking, and\n * sends it to the server if possible.\n *\n * @param path - Path at which to do transaction.\n * @param transactionUpdate - Update callback.\n * @param onComplete - Completion callback.\n * @param unwatcher - Function that will be called when the transaction no longer\n * need data updates for `path`.\n * @param applyLocally - Whether or not to make intermediate results visible\n */\nfunction repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {\n repoLog(repo, 'transaction on ' + path);\n // Initialize transaction.\n const transaction = {\n path,\n update: transactionUpdate,\n onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out\n // which one goes first.\n order: LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n };\n // Run transaction initially.\n const currentState = repoGetLatestState(repo, path, undefined);\n transaction.currentInputSnapshot = currentState;\n const newVal = transaction.update(currentState.val());\n if (newVal === undefined) {\n // Abort transaction.\n transaction.unwatcher();\n transaction.currentOutputSnapshotRaw = null;\n transaction.currentOutputSnapshotResolved = null;\n if (transaction.onComplete) {\n transaction.onComplete(null, false, transaction.currentInputSnapshot);\n }\n }\n else {\n validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);\n // Mark as run and add to our queue.\n transaction.status = 0 /* TransactionStatus.RUN */;\n const queueNode = treeSubTree(repo.transactionQueueTree_, path);\n const nodeQueue = treeGetValue(queueNode) || [];\n nodeQueue.push(transaction);\n treeSetValue(queueNode, nodeQueue);\n // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our\n // transaction state, since the user could start new transactions from the\n // event callbacks.\n let priorityForNode;\n if (typeof newVal === 'object' &&\n newVal !== null &&\n util.contains(newVal, '.priority')) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n priorityForNode = util.safeGet(newVal, '.priority');\n util.assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +\n 'Priority must be a valid string, finite number, server value, or null.');\n }\n else {\n const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||\n ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n const serverValues = repoGenerateServerValues(repo);\n const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);\n const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = repoGetNextWriteId(repo);\n const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n }\n}\n/**\n * @param excludeSets - A specific set to exclude\n */\nfunction repoGetLatestState(repo, path, excludeSets) {\n return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||\n ChildrenNode.EMPTY_NODE);\n}\n/**\n * Sends any already-run transactions that aren't waiting for outstanding\n * transactions to complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively\n * with a particular transactionQueueTree node to recurse through the tree.\n *\n * @param node - transactionQueueTree node to start at.\n */\nfunction repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) {\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n repoPruneCompletedTransactionsBelowNode(repo, node);\n }\n if (treeGetValue(node)) {\n const queue = repoBuildTransactionQueue(repo, node);\n util.assert(queue.length > 0, 'Sending zero length transaction queue');\n const allRun = queue.every((transaction) => transaction.status === 0 /* TransactionStatus.RUN */);\n // If they're all run (and not sent), we can send them. Else, we must wait.\n if (allRun) {\n repoSendTransactionQueue(repo, treeGetPath(node), queue);\n }\n }\n else if (treeHasChildren(node)) {\n treeForEachChild(node, childNode => {\n repoSendReadyTransactions(repo, childNode);\n });\n }\n}\n/**\n * Given a list of run transactions, send them to the server and then handle\n * the result (success or failure).\n *\n * @param path - The location of the queue.\n * @param queue - Queue of transactions under the specified location.\n */\nfunction repoSendTransactionQueue(repo, path, queue) {\n // Mark transactions as sent and increment retry count!\n const setsToIgnore = queue.map(txn => {\n return txn.currentWriteId;\n });\n const latestState = repoGetLatestState(repo, path, setsToIgnore);\n let snapToSend = latestState;\n const latestHash = latestState.hash();\n for (let i = 0; i < queue.length; i++) {\n const txn = queue[i];\n util.assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');\n txn.status = 1 /* TransactionStatus.SENT */;\n txn.retryCount++;\n const relativePath = newRelativePath(path, txn.path);\n // If we've gotten to this point, the output snapshot must be defined.\n snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);\n }\n const dataToSend = snapToSend.val(true);\n const pathToSend = path;\n // Send the put.\n repo.server_.put(pathToSend.toString(), dataToSend, (status) => {\n repoLog(repo, 'transaction put response', {\n path: pathToSend.toString(),\n status\n });\n let events = [];\n if (status === 'ok') {\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more\n // transactions or sets.\n const callbacks = [];\n for (let i = 0; i < queue.length; i++) {\n queue[i].status = 2 /* TransactionStatus.COMPLETED */;\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this\n // transaction is complete, it should be set\n callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved));\n }\n queue[i].unwatcher();\n }\n // Now remove the completed transactions.\n repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));\n // There may be pending transactions that we can now send.\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n // Finally, trigger onComplete callbacks.\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n }\n else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (let i = 0; i < queue.length; i++) {\n if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {\n queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;\n }\n else {\n queue[i].status = 0 /* TransactionStatus.RUN */;\n }\n }\n }\n else {\n warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\n for (let i = 0; i < queue.length; i++) {\n queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;\n queue[i].abortReason = status;\n }\n }\n repoRerunTransactions(repo, path);\n }\n }, latestHash);\n}\n/**\n * Finds all transactions dependent on the data at changedPath and reruns them.\n *\n * Should be called any time cached data changes.\n *\n * Return the highest path that was affected by rerunning transactions. This\n * is the path at which events need to be raised for.\n *\n * @param changedPath - The path in mergedData that changed.\n * @returns The rootmost path that was affected by rerunning transactions.\n */\nfunction repoRerunTransactions(repo, changedPath) {\n const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);\n const path = treeGetPath(rootMostTransactionNode);\n const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);\n repoRerunTransactionQueue(repo, queue, path);\n return path;\n}\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted\n * transactions and whatnot).\n *\n * @param queue - The queue of transactions to run.\n * @param path - The path the queue is for.\n */\nfunction repoRerunTransactionQueue(repo, queue, path) {\n if (queue.length === 0) {\n return; // Nothing to do!\n }\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more transactions or\n // sets.\n const callbacks = [];\n let events = [];\n // Ignore all of the sets we're going to re-run.\n const txnsToRerun = queue.filter(q => {\n return q.status === 0 /* TransactionStatus.RUN */;\n });\n const setsToIgnore = txnsToRerun.map(q => {\n return q.currentWriteId;\n });\n for (let i = 0; i < queue.length; i++) {\n const transaction = queue[i];\n const relativePath = newRelativePath(path, transaction.path);\n let abortTransaction = false, abortReason;\n util.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\n if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\n }\n else if (transaction.status === 0 /* TransactionStatus.RUN */) {\n if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\n }\n else {\n // This code reruns a transaction\n const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);\n transaction.currentInputSnapshot = currentNode;\n const newData = queue[i].update(currentNode.val());\n if (newData !== undefined) {\n validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\n let newDataNode = nodeFromJSON(newData);\n const hasExplicitPriority = typeof newData === 'object' &&\n newData != null &&\n util.contains(newData, '.priority');\n if (!hasExplicitPriority) {\n // Keep the old priority if there wasn't a priority explicitly specified.\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n }\n const oldWriteId = transaction.currentWriteId;\n const serverValues = repoGenerateServerValues(repo);\n const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = repoGetNextWriteId(repo);\n // Mutates setsToIgnore in place\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));\n }\n else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\n }\n }\n }\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n events = [];\n if (abortTransaction) {\n // Abort.\n queue[i].status = 2 /* TransactionStatus.COMPLETED */;\n // Removing a listener can trigger pruning which can muck with\n // mergedData/visibleData (as it prunes data). So defer the unwatcher\n // until we're done.\n (function (unwatcher) {\n setTimeout(unwatcher, Math.floor(0));\n })(queue[i].unwatcher);\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot));\n }\n else {\n callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null));\n }\n }\n }\n }\n // Clean up completed transactions.\n repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);\n // Now fire callbacks, now that we're in a good, known state.\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n // Try to send the transaction result to the server.\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n}\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending\n * transaction on it, or just returns the node for the given path if there are\n * no pending transactions on any ancestor.\n *\n * @param path - The location to start at.\n * @returns The rootmost node with a transaction.\n */\nfunction repoGetAncestorTransactionNode(repo, path) {\n let front;\n // Start at the root and walk deeper into the tree towards path until we\n // find a node with pending transactions.\n let transactionNode = repo.transactionQueueTree_;\n front = pathGetFront(path);\n while (front !== null && treeGetValue(transactionNode) === undefined) {\n transactionNode = treeSubTree(transactionNode, front);\n path = pathPopFront(path);\n front = pathGetFront(path);\n }\n return transactionNode;\n}\n/**\n * Builds the queue of all transactions at or below the specified\n * transactionNode.\n *\n * @param transactionNode\n * @returns The generated queue.\n */\nfunction repoBuildTransactionQueue(repo, transactionNode) {\n // Walk any child transaction queues and aggregate them into a single queue.\n const transactionQueue = [];\n repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);\n // Sort them by the order the transactions were created.\n transactionQueue.sort((a, b) => a.order - b.order);\n return transactionQueue;\n}\nfunction repoAggregateTransactionQueuesForNode(repo, node, queue) {\n const nodeQueue = treeGetValue(node);\n if (nodeQueue) {\n for (let i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n treeForEachChild(node, child => {\n repoAggregateTransactionQueuesForNode(repo, child, queue);\n });\n}\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n */\nfunction repoPruneCompletedTransactionsBelowNode(repo, node) {\n const queue = treeGetValue(node);\n if (queue) {\n let to = 0;\n for (let from = 0; from < queue.length; from++) {\n if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {\n queue[to] = queue[from];\n to++;\n }\n }\n queue.length = to;\n treeSetValue(node, queue.length > 0 ? queue : undefined);\n }\n treeForEachChild(node, childNode => {\n repoPruneCompletedTransactionsBelowNode(repo, childNode);\n });\n}\n/**\n * Aborts all transactions on ancestors or descendants of the specified path.\n * Called when doing a set() or update() since we consider them incompatible\n * with transactions.\n *\n * @param path - Path for which we want to abort related transactions.\n */\nfunction repoAbortTransactions(repo, path) {\n const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));\n const transactionNode = treeSubTree(repo.transactionQueueTree_, path);\n treeForEachAncestor(transactionNode, (node) => {\n repoAbortTransactionsOnNode(repo, node);\n });\n repoAbortTransactionsOnNode(repo, transactionNode);\n treeForEachDescendant(transactionNode, (node) => {\n repoAbortTransactionsOnNode(repo, node);\n });\n return affectedPath;\n}\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param node - Node to abort transactions for.\n */\nfunction repoAbortTransactionsOnNode(repo, node) {\n const queue = treeGetValue(node);\n if (queue) {\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more transactions\n // or sets.\n const callbacks = [];\n // Go through queue. Any already-sent transactions must be marked for\n // abort, while the unsent ones can be immediately aborted and removed.\n let events = [];\n let lastSent = -1;\n for (let i = 0; i < queue.length; i++) {\n if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;\n else if (queue[i].status === 1 /* TransactionStatus.SENT */) {\n util.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\n lastSent = i;\n // Mark transaction for abort when it comes back.\n queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;\n queue[i].abortReason = 'set';\n }\n else {\n util.assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');\n // We can abort it immediately.\n queue[i].unwatcher();\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));\n if (queue[i].onComplete) {\n callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));\n }\n }\n }\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n treeSetValue(node, undefined);\n }\n else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n // Now fire the callbacks.\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction decodePath(pathString) {\n let pathStringDecoded = '';\n const pieces = pathString.split('/');\n for (let i = 0; i < pieces.length; i++) {\n if (pieces[i].length > 0) {\n let piece = pieces[i];\n try {\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\n }\n catch (e) { }\n pathStringDecoded += '/' + piece;\n }\n }\n return pathStringDecoded;\n}\n/**\n * @returns key value hash\n */\nfunction decodeQuery(queryString) {\n const results = {};\n if (queryString.charAt(0) === '?') {\n queryString = queryString.substring(1);\n }\n for (const segment of queryString.split('&')) {\n if (segment.length === 0) {\n continue;\n }\n const kv = segment.split('=');\n if (kv.length === 2) {\n results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\n }\n else {\n warn(`Invalid query segment '${segment}' in query '${queryString}'`);\n }\n }\n return results;\n}\nconst parseRepoInfo = function (dataURL, nodeAdmin) {\n const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;\n if (parsedUrl.domain === 'firebase.com') {\n fatal(parsedUrl.host +\n ' is no longer supported. ' +\n 'Please use .firebaseio.com instead');\n }\n // Catch common error of uninitialized namespace value.\n if ((!namespace || namespace === 'undefined') &&\n parsedUrl.domain !== 'localhost') {\n fatal('Cannot parse Firebase url. Please use https://.firebaseio.com');\n }\n if (!parsedUrl.secure) {\n warnIfPageIsSecure();\n }\n const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\n return {\n repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin, \n /*persistenceKey=*/ '', \n /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),\n path: new Path(parsedUrl.pathString)\n };\n};\nconst parseDatabaseURL = function (dataURL) {\n // Default to empty strings in the event of a malformed string.\n let host = '', domain = '', subdomain = '', pathString = '', namespace = '';\n // Always default to SSL, unless otherwise specified.\n let secure = true, scheme = 'https', port = 443;\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\n if (typeof dataURL === 'string') {\n // Parse scheme.\n let colonInd = dataURL.indexOf('//');\n if (colonInd >= 0) {\n scheme = dataURL.substring(0, colonInd - 1);\n dataURL = dataURL.substring(colonInd + 2);\n }\n // Parse host, path, and query string.\n let slashInd = dataURL.indexOf('/');\n if (slashInd === -1) {\n slashInd = dataURL.length;\n }\n let questionMarkInd = dataURL.indexOf('?');\n if (questionMarkInd === -1) {\n questionMarkInd = dataURL.length;\n }\n host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));\n if (slashInd < questionMarkInd) {\n // For pathString, questionMarkInd will always come after slashInd\n pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));\n }\n const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));\n // If we have a port, use scheme for determining if it's secure.\n colonInd = host.indexOf(':');\n if (colonInd >= 0) {\n secure = scheme === 'https' || scheme === 'wss';\n port = parseInt(host.substring(colonInd + 1), 10);\n }\n else {\n colonInd = host.length;\n }\n const hostWithoutPort = host.slice(0, colonInd);\n if (hostWithoutPort.toLowerCase() === 'localhost') {\n domain = 'localhost';\n }\n else if (hostWithoutPort.split('.').length <= 2) {\n domain = hostWithoutPort;\n }\n else {\n // Interpret the subdomain of a 3 or more component URL as the namespace name.\n const dotInd = host.indexOf('.');\n subdomain = host.substring(0, dotInd).toLowerCase();\n domain = host.substring(dotInd + 1);\n // Normalize namespaces to lowercase to share storage / connection.\n namespace = subdomain;\n }\n // Always treat the value of the `ns` as the namespace name if it is present.\n if ('ns' in queryParams) {\n namespace = queryParams['ns'];\n }\n }\n return {\n host,\n port,\n domain,\n subdomain,\n secure,\n scheme,\n pathString,\n namespace\n };\n};\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Modeled after base64 web-safe chars, but ordered by ASCII.\nconst PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n/**\n * Fancy ID generator that creates 20-character string identifiers with the\n * following properties:\n *\n * 1. They're based on timestamp so that they sort *after* any existing ids.\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\n * collide with other clients' IDs.\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\n * that will sort properly).\n * 4. They're monotonically increasing. Even if you generate more than one in\n * the same timestamp, the latter ones will sort after the former ones. We do\n * this by using the previous random bits but \"incrementing\" them by 1 (only\n * in the case of a timestamp collision).\n */\nconst nextPushId = (function () {\n // Timestamp of last push, used to prevent local collisions if you push twice\n // in one ms.\n let lastPushTime = 0;\n // We generate 72-bits of randomness which get turned into 12 characters and\n // appended to the timestamp to prevent collisions with other clients. We\n // store the last characters we generated because in the event of a collision,\n // we'll use those same characters except \"incremented\" by one.\n const lastRandChars = [];\n return function (now) {\n const duplicateTime = now === lastPushTime;\n lastPushTime = now;\n let i;\n const timeStampChars = new Array(8);\n for (i = 7; i >= 0; i--) {\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\n // NOTE: Can't use << here because javascript will convert to int and lose\n // the upper bits.\n now = Math.floor(now / 64);\n }\n util.assert(now === 0, 'Cannot push at time == 0');\n let id = timeStampChars.join('');\n if (!duplicateTime) {\n for (i = 0; i < 12; i++) {\n lastRandChars[i] = Math.floor(Math.random() * 64);\n }\n }\n else {\n // If the timestamp hasn't changed since last push, use the same random\n // number, except incremented by 1.\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\n lastRandChars[i] = 0;\n }\n lastRandChars[i]++;\n }\n for (i = 0; i < 12; i++) {\n id += PUSH_CHARS.charAt(lastRandChars[i]);\n }\n util.assert(id.length === 20, 'nextPushId: Length should be 20.');\n return id;\n };\n})();\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Encapsulates the data needed to raise an event\n */\nclass DataEvent {\n /**\n * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed\n * @param eventRegistration - The function to call to with the event data. User provided\n * @param snapshot - The data backing the event\n * @param prevName - Optional, the name of the previous child for child_* events.\n */\n constructor(eventType, eventRegistration, snapshot, prevName) {\n this.eventType = eventType;\n this.eventRegistration = eventRegistration;\n this.snapshot = snapshot;\n this.prevName = prevName;\n }\n getPath() {\n const ref = this.snapshot.ref;\n if (this.eventType === 'value') {\n return ref._path;\n }\n else {\n return ref.parent._path;\n }\n }\n getEventType() {\n return this.eventType;\n }\n getEventRunner() {\n return this.eventRegistration.getEventRunner(this);\n }\n toString() {\n return (this.getPath().toString() +\n ':' +\n this.eventType +\n ':' +\n util.stringify(this.snapshot.exportVal()));\n }\n}\nclass CancelEvent {\n constructor(eventRegistration, error, path) {\n this.eventRegistration = eventRegistration;\n this.error = error;\n this.path = path;\n }\n getPath() {\n return this.path;\n }\n getEventType() {\n return 'cancel';\n }\n getEventRunner() {\n return this.eventRegistration.getEventRunner(this);\n }\n toString() {\n return this.path.toString() + ':cancel';\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A wrapper class that converts events from the database@exp SDK to the legacy\n * Database SDK. Events are not converted directly as event registration relies\n * on reference comparison of the original user callback (see `matches()`) and\n * relies on equality of the legacy SDK's `context` object.\n */\nclass CallbackContext {\n constructor(snapshotCallback, cancelCallback) {\n this.snapshotCallback = snapshotCallback;\n this.cancelCallback = cancelCallback;\n }\n onValue(expDataSnapshot, previousChildName) {\n this.snapshotCallback.call(null, expDataSnapshot, previousChildName);\n }\n onCancel(error) {\n util.assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');\n return this.cancelCallback.call(null, error);\n }\n get hasCancelCallback() {\n return !!this.cancelCallback;\n }\n matches(other) {\n return (this.snapshotCallback === other.snapshotCallback ||\n (this.snapshotCallback.userCallback !== undefined &&\n this.snapshotCallback.userCallback ===\n other.snapshotCallback.userCallback &&\n this.snapshotCallback.context === other.snapshotCallback.context));\n }\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The `onDisconnect` class allows you to write or clear data when your client\n * disconnects from the Database server. These updates occur whether your\n * client disconnects cleanly or not, so you can rely on them to clean up data\n * even if a connection is dropped or a client crashes.\n *\n * The `onDisconnect` class is most commonly used to manage presence in\n * applications where it is useful to detect how many clients are connected and\n * when other clients disconnect. See\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information.\n *\n * To avoid problems when a connection is dropped before the requests can be\n * transferred to the Database server, these functions should be called before\n * writing any data.\n *\n * Note that `onDisconnect` operations are only triggered once. If you want an\n * operation to occur each time a disconnect occurs, you'll need to re-establish\n * the `onDisconnect` operations each time you reconnect.\n */\nclass OnDisconnect {\n /** @hideconstructor */\n constructor(_repo, _path) {\n this._repo = _repo;\n this._path = _path;\n }\n /**\n * Cancels all previously queued `onDisconnect()` set or update events for this\n * location and all children.\n *\n * If a write has been queued for this location via a `set()` or `update()` at a\n * parent location, the write at this location will be canceled, though writes\n * to sibling locations will still occur.\n *\n * @returns Resolves when synchronization to the server is complete.\n */\n cancel() {\n const deferred = new util.Deferred();\n repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { }));\n return deferred.promise;\n }\n /**\n * Ensures the data at this location is deleted when the client is disconnected\n * (due to closing the browser, navigating to a new page, or network issues).\n *\n * @returns Resolves when synchronization to the server is complete.\n */\n remove() {\n validateWritablePath('OnDisconnect.remove', this._path);\n const deferred = new util.Deferred();\n repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { }));\n return deferred.promise;\n }\n /**\n * Ensures the data at this location is set to the specified value when the\n * client is disconnected (due to closing the browser, navigating to a new page,\n * or network issues).\n *\n * `set()` is especially useful for implementing \"presence\" systems, where a\n * value should be changed or cleared when a user disconnects so that they\n * appear \"offline\" to other users. See\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information.\n *\n * Note that `onDisconnect` operations are only triggered once. If you want an\n * operation to occur each time a disconnect occurs, you'll need to re-establish\n * the `onDisconnect` operations each time.\n *\n * @param value - The value to be written to this location on disconnect (can\n * be an object, array, string, number, boolean, or null).\n * @returns Resolves when synchronization to the Database is complete.\n */\n set(value) {\n validateWritablePath('OnDisconnect.set', this._path);\n validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);\n const deferred = new util.Deferred();\n repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { }));\n return deferred.promise;\n }\n /**\n * Ensures the data at this location is set to the specified value and priority\n * when the client is disconnected (due to closing the browser, navigating to a\n * new page, or network issues).\n *\n * @param value - The value to be written to this location on disconnect (can\n * be an object, array, string, number, boolean, or null).\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when synchronization to the Database is complete.\n */\n setWithPriority(value, priority) {\n validateWritablePath('OnDisconnect.setWithPriority', this._path);\n validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);\n validatePriority('OnDisconnect.setWithPriority', priority, false);\n const deferred = new util.Deferred();\n repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { }));\n return deferred.promise;\n }\n /**\n * Writes multiple values at this location when the client is disconnected (due\n * to closing the browser, navigating to a new page, or network issues).\n *\n * The `values` argument contains multiple property-value pairs that will be\n * written to the Database together. Each child property can either be a simple\n * property (for example, \"name\") or a relative path (for example, \"name/first\")\n * from the current location to the data to update.\n *\n * As opposed to the `set()` method, `update()` can be use to selectively update\n * only the referenced properties at the current location (instead of replacing\n * all the child properties at the current location).\n *\n * @param values - Object containing multiple values.\n * @returns Resolves when synchronization to the Database is complete.\n */\n update(values) {\n validateWritablePath('OnDisconnect.update', this._path);\n validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);\n const deferred = new util.Deferred();\n repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { }));\n return deferred.promise;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @internal\n */\nclass QueryImpl {\n /**\n * @hideconstructor\n */\n constructor(_repo, _path, _queryParams, _orderByCalled) {\n this._repo = _repo;\n this._path = _path;\n this._queryParams = _queryParams;\n this._orderByCalled = _orderByCalled;\n }\n get key() {\n if (pathIsEmpty(this._path)) {\n return null;\n }\n else {\n return pathGetBack(this._path);\n }\n }\n get ref() {\n return new ReferenceImpl(this._repo, this._path);\n }\n get _queryIdentifier() {\n const obj = queryParamsGetQueryObject(this._queryParams);\n const id = ObjectToUniqueKey(obj);\n return id === '{}' ? 'default' : id;\n }\n /**\n * An object representation of the query parameters used by this Query.\n */\n get _queryObject() {\n return queryParamsGetQueryObject(this._queryParams);\n }\n isEqual(other) {\n other = util.getModularInstance(other);\n if (!(other instanceof QueryImpl)) {\n return false;\n }\n const sameRepo = this._repo === other._repo;\n const samePath = pathEquals(this._path, other._path);\n const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;\n return sameRepo && samePath && sameQueryIdentifier;\n }\n toJSON() {\n return this.toString();\n }\n toString() {\n return this._repo.toString() + pathToUrlEncodedString(this._path);\n }\n}\n/**\n * Validates that no other order by call has been made\n */\nfunction validateNoPreviousOrderByCall(query, fnName) {\n if (query._orderByCalled === true) {\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\n }\n}\n/**\n * Validates start/end values for queries.\n */\nfunction validateQueryEndpoints(params) {\n let startNode = null;\n let endNode = null;\n if (params.hasStart()) {\n startNode = params.getIndexStartValue();\n }\n if (params.hasEnd()) {\n endNode = params.getIndexEndValue();\n }\n if (params.getIndex() === KEY_INDEX) {\n const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +\n 'startAt(), endAt(), or equalTo().';\n const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +\n 'endAt(), endBefore(), or equalTo() must be a string.';\n if (params.hasStart()) {\n const startName = params.getIndexStartName();\n if (startName !== MIN_NAME) {\n throw new Error(tooManyArgsError);\n }\n else if (typeof startNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n if (params.hasEnd()) {\n const endName = params.getIndexEndName();\n if (endName !== MAX_NAME) {\n throw new Error(tooManyArgsError);\n }\n else if (typeof endNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n }\n else if (params.getIndex() === PRIORITY_INDEX) {\n if ((startNode != null && !isValidPriority(startNode)) ||\n (endNode != null && !isValidPriority(endNode))) {\n throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +\n 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +\n '(null, a number, or a string).');\n }\n }\n else {\n util.assert(params.getIndex() instanceof PathIndex ||\n params.getIndex() === VALUE_INDEX, 'unknown index type.');\n if ((startNode != null && typeof startNode === 'object') ||\n (endNode != null && typeof endNode === 'object')) {\n throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +\n 'equalTo() cannot be an object.');\n }\n }\n}\n/**\n * Validates that limit* has been called with the correct combination of parameters\n */\nfunction validateLimit(params) {\n if (params.hasStart() &&\n params.hasEnd() &&\n params.hasLimit() &&\n !params.hasAnchoredLimit()) {\n throw new Error(\"Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use \" +\n 'limitToFirst() or limitToLast() instead.');\n }\n}\n/**\n * @internal\n */\nclass ReferenceImpl extends QueryImpl {\n /** @hideconstructor */\n constructor(repo, path) {\n super(repo, path, new QueryParams(), false);\n }\n get parent() {\n const parentPath = pathParent(this._path);\n return parentPath === null\n ? null\n : new ReferenceImpl(this._repo, parentPath);\n }\n get root() {\n let ref = this;\n while (ref.parent !== null) {\n ref = ref.parent;\n }\n return ref;\n }\n}\n/**\n * A `DataSnapshot` contains data from a Database location.\n *\n * Any time you read data from the Database, you receive the data as a\n * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach\n * with `on()` or `once()`. You can extract the contents of the snapshot as a\n * JavaScript object by calling the `val()` method. Alternatively, you can\n * traverse into the snapshot by calling `child()` to return child snapshots\n * (which you could then call `val()` on).\n *\n * A `DataSnapshot` is an efficiently generated, immutable copy of the data at\n * a Database location. It cannot be modified and will never change (to modify\n * data, you always call the `set()` method on a `Reference` directly).\n */\nclass DataSnapshot {\n /**\n * @param _node - A SnapshotNode to wrap.\n * @param ref - The location this snapshot came from.\n * @param _index - The iteration order for this snapshot\n * @hideconstructor\n */\n constructor(_node, \n /**\n * The location of this DataSnapshot.\n */\n ref, _index) {\n this._node = _node;\n this.ref = ref;\n this._index = _index;\n }\n /**\n * Gets the priority value of the data in this `DataSnapshot`.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}\n * ).\n */\n get priority() {\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\n return this._node.getPriority().val();\n }\n /**\n * The key (last part of the path) of the location of this `DataSnapshot`.\n *\n * The last token in a Database location is considered its key. For example,\n * \"ada\" is the key for the /users/ada/ node. Accessing the key on any\n * `DataSnapshot` will return the key for the location that generated it.\n * However, accessing the key on the root URL of a Database will return\n * `null`.\n */\n get key() {\n return this.ref.key;\n }\n /** Returns the number of child properties of this `DataSnapshot`. */\n get size() {\n return this._node.numChildren();\n }\n /**\n * Gets another `DataSnapshot` for the location at the specified relative path.\n *\n * Passing a relative path to the `child()` method of a DataSnapshot returns\n * another `DataSnapshot` for the location at the specified relative path. The\n * relative path can either be a simple child name (for example, \"ada\") or a\n * deeper, slash-separated path (for example, \"ada/name/first\"). If the child\n * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`\n * whose value is `null`) is returned.\n *\n * @param path - A relative path to the location of child data.\n */\n child(path) {\n const childPath = new Path(path);\n const childRef = child(this.ref, path);\n return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);\n }\n /**\n * Returns true if this `DataSnapshot` contains any data. It is slightly more\n * efficient than using `snapshot.val() !== null`.\n */\n exists() {\n return !this._node.isEmpty();\n }\n /**\n * Exports the entire contents of the DataSnapshot as a JavaScript object.\n *\n * The `exportVal()` method is similar to `val()`, except priority information\n * is included (if available), making it suitable for backing up your data.\n *\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\n * Array, string, number, boolean, or `null`).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n exportVal() {\n return this._node.val(true);\n }\n /**\n * Enumerates the top-level children in the `IteratedDataSnapshot`.\n *\n * Because of the way JavaScript objects work, the ordering of data in the\n * JavaScript object returned by `val()` is not guaranteed to match the\n * ordering on the server nor the ordering of `onChildAdded()` events. That is\n * where `forEach()` comes in handy. It guarantees the children of a\n * `DataSnapshot` will be iterated in their query order.\n *\n * If no explicit `orderBy*()` method is used, results are returned\n * ordered by key (unless priorities are used, in which case, results are\n * returned by priority).\n *\n * @param action - A function that will be called for each child DataSnapshot.\n * The callback can return true to cancel further enumeration.\n * @returns true if enumeration was canceled due to your callback returning\n * true.\n */\n forEach(action) {\n if (this._node.isLeafNode()) {\n return false;\n }\n const childrenNode = this._node;\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\n return !!childrenNode.forEachChild(this._index, (key, node) => {\n return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX));\n });\n }\n /**\n * Returns true if the specified child path has (non-null) data.\n *\n * @param path - A relative path to the location of a potential child.\n * @returns `true` if data exists at the specified child path; else\n * `false`.\n */\n hasChild(path) {\n const childPath = new Path(path);\n return !this._node.getChild(childPath).isEmpty();\n }\n /**\n * Returns whether or not the `DataSnapshot` has any non-`null` child\n * properties.\n *\n * You can use `hasChildren()` to determine if a `DataSnapshot` has any\n * children. If it does, you can enumerate them using `forEach()`. If it\n * doesn't, then either this snapshot contains a primitive value (which can be\n * retrieved with `val()`) or it is empty (in which case, `val()` will return\n * `null`).\n *\n * @returns true if this snapshot has any children; else false.\n */\n hasChildren() {\n if (this._node.isLeafNode()) {\n return false;\n }\n else {\n return !this._node.isEmpty();\n }\n }\n /**\n * Returns a JSON-serializable representation of this object.\n */\n toJSON() {\n return this.exportVal();\n }\n /**\n * Extracts a JavaScript value from a `DataSnapshot`.\n *\n * Depending on the data in a `DataSnapshot`, the `val()` method may return a\n * scalar type (string, number, or boolean), an array, or an object. It may\n * also return null, indicating that the `DataSnapshot` is empty (contains no\n * data).\n *\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\n * Array, string, number, boolean, or `null`).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n val() {\n return this._node.val();\n }\n}\n/**\n *\n * Returns a `Reference` representing the location in the Database\n * corresponding to the provided path. If no path is provided, the `Reference`\n * will point to the root of the Database.\n *\n * @param db - The database instance to obtain a reference for.\n * @param path - Optional path representing the location the returned\n * `Reference` will point. If not provided, the returned `Reference` will\n * point to the root of the Database.\n * @returns If a path is provided, a `Reference`\n * pointing to the provided path. Otherwise, a `Reference` pointing to the\n * root of the Database.\n */\nfunction ref(db, path) {\n db = util.getModularInstance(db);\n db._checkNotDeleted('ref');\n return path !== undefined ? child(db._root, path) : db._root;\n}\n/**\n * Returns a `Reference` representing the location in the Database\n * corresponding to the provided Firebase URL.\n *\n * An exception is thrown if the URL is not a valid Firebase Database URL or it\n * has a different domain than the current `Database` instance.\n *\n * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored\n * and are not applied to the returned `Reference`.\n *\n * @param db - The database instance to obtain a reference for.\n * @param url - The Firebase URL at which the returned `Reference` will\n * point.\n * @returns A `Reference` pointing to the provided\n * Firebase URL.\n */\nfunction refFromURL(db, url) {\n db = util.getModularInstance(db);\n db._checkNotDeleted('refFromURL');\n const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\n validateUrl('refFromURL', parsedURL);\n const repoInfo = parsedURL.repoInfo;\n if (!db._repo.repoInfo_.isCustomHost() &&\n repoInfo.host !== db._repo.repoInfo_.host) {\n fatal('refFromURL' +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n db._repo.repoInfo_.host +\n ')');\n }\n return ref(db, parsedURL.path.toString());\n}\n/**\n * Gets a `Reference` for the location at the specified relative path.\n *\n * The relative path can either be a simple child name (for example, \"ada\") or\n * a deeper slash-separated path (for example, \"ada/name/first\").\n *\n * @param parent - The parent location.\n * @param path - A relative path from this location to the desired child\n * location.\n * @returns The specified child location.\n */\nfunction child(parent, path) {\n parent = util.getModularInstance(parent);\n if (pathGetFront(parent._path) === null) {\n validateRootPathString('child', 'path', path, false);\n }\n else {\n validatePathString('child', 'path', path, false);\n }\n return new ReferenceImpl(parent._repo, pathChild(parent._path, path));\n}\n/**\n * Returns an `OnDisconnect` object - see\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information on how to use it.\n *\n * @param ref - The reference to add OnDisconnect triggers for.\n */\nfunction onDisconnect(ref) {\n ref = util.getModularInstance(ref);\n return new OnDisconnect(ref._repo, ref._path);\n}\n/**\n * Generates a new child location using a unique key and returns its\n * `Reference`.\n *\n * This is the most common pattern for adding data to a collection of items.\n *\n * If you provide a value to `push()`, the value is written to the\n * generated location. If you don't pass a value, nothing is written to the\n * database and the child remains empty (but you can use the `Reference`\n * elsewhere).\n *\n * The unique keys generated by `push()` are ordered by the current time, so the\n * resulting list of items is chronologically sorted. The keys are also\n * designed to be unguessable (they contain 72 random bits of entropy).\n *\n * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.\n * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.\n *\n * @param parent - The parent location.\n * @param value - Optional value to be written at the generated location.\n * @returns Combined `Promise` and `Reference`; resolves when write is complete,\n * but can be used immediately as the `Reference` to the child location.\n */\nfunction push(parent, value) {\n parent = util.getModularInstance(parent);\n validateWritablePath('push', parent._path);\n validateFirebaseDataArg('push', value, parent._path, true);\n const now = repoServerTime(parent._repo);\n const name = nextPushId(now);\n // push() returns a ThennableReference whose promise is fulfilled with a\n // regular Reference. We use child() to create handles to two different\n // references. The first is turned into a ThennableReference below by adding\n // then() and catch() methods and is used as the return value of push(). The\n // second remains a regular Reference and is used as the fulfilled value of\n // the first ThennableReference.\n const thenablePushRef = child(parent, name);\n const pushRef = child(parent, name);\n let promise;\n if (value != null) {\n promise = set(pushRef, value).then(() => pushRef);\n }\n else {\n promise = Promise.resolve(pushRef);\n }\n thenablePushRef.then = promise.then.bind(promise);\n thenablePushRef.catch = promise.then.bind(promise, undefined);\n return thenablePushRef;\n}\n/**\n * Removes the data at this Database location.\n *\n * Any data at child locations will also be deleted.\n *\n * The effect of the remove will be visible immediately and the corresponding\n * event 'value' will be triggered. Synchronization of the remove to the\n * Firebase servers will also be started, and the returned Promise will resolve\n * when complete. If provided, the onComplete callback will be called\n * asynchronously after synchronization has finished.\n *\n * @param ref - The location to remove.\n * @returns Resolves when remove on server is complete.\n */\nfunction remove(ref) {\n validateWritablePath('remove', ref._path);\n return set(ref, null);\n}\n/**\n * Writes data to this Database location.\n *\n * This will overwrite any data at this location and all child locations.\n *\n * The effect of the write will be visible immediately, and the corresponding\n * events (\"value\", \"child_added\", etc.) will be triggered. Synchronization of\n * the data to the Firebase servers will also be started, and the returned\n * Promise will resolve when complete. If provided, the `onComplete` callback\n * will be called asynchronously after synchronization has finished.\n *\n * Passing `null` for the new value is equivalent to calling `remove()`; namely,\n * all data at this location and all child locations will be deleted.\n *\n * `set()` will remove any priority stored at this location, so if priority is\n * meant to be preserved, you need to use `setWithPriority()` instead.\n *\n * Note that modifying data with `set()` will cancel any pending transactions\n * at that location, so extreme care should be taken if mixing `set()` and\n * `transaction()` to modify the same data.\n *\n * A single `set()` will generate a single \"value\" event at the location where\n * the `set()` was performed.\n *\n * @param ref - The location to write to.\n * @param value - The value to be written (string, number, boolean, object,\n * array, or null).\n * @returns Resolves when write to server is complete.\n */\nfunction set(ref, value) {\n ref = util.getModularInstance(ref);\n validateWritablePath('set', ref._path);\n validateFirebaseDataArg('set', value, ref._path, false);\n const deferred = new util.Deferred();\n repoSetWithPriority(ref._repo, ref._path, value, \n /*priority=*/ null, deferred.wrapCallback(() => { }));\n return deferred.promise;\n}\n/**\n * Sets a priority for the data at this Database location.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\n * ).\n *\n * @param ref - The location to write to.\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when write to server is complete.\n */\nfunction setPriority(ref, priority) {\n ref = util.getModularInstance(ref);\n validateWritablePath('setPriority', ref._path);\n validatePriority('setPriority', priority, false);\n const deferred = new util.Deferred();\n repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { }));\n return deferred.promise;\n}\n/**\n * Writes data the Database location. Like `set()` but also specifies the\n * priority for that data.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\n * ).\n *\n * @param ref - The location to write to.\n * @param value - The value to be written (string, number, boolean, object,\n * array, or null).\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when write to server is complete.\n */\nfunction setWithPriority(ref, value, priority) {\n validateWritablePath('setWithPriority', ref._path);\n validateFirebaseDataArg('setWithPriority', value, ref._path, false);\n validatePriority('setWithPriority', priority, false);\n if (ref.key === '.length' || ref.key === '.keys') {\n throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';\n }\n const deferred = new util.Deferred();\n repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { }));\n return deferred.promise;\n}\n/**\n * Writes multiple values to the Database at once.\n *\n * The `values` argument contains multiple property-value pairs that will be\n * written to the Database together. Each child property can either be a simple\n * property (for example, \"name\") or a relative path (for example,\n * \"name/first\") from the current location to the data to update.\n *\n * As opposed to the `set()` method, `update()` can be use to selectively update\n * only the referenced properties at the current location (instead of replacing\n * all the child properties at the current location).\n *\n * The effect of the write will be visible immediately, and the corresponding\n * events ('value', 'child_added', etc.) will be triggered. Synchronization of\n * the data to the Firebase servers will also be started, and the returned\n * Promise will resolve when complete. If provided, the `onComplete` callback\n * will be called asynchronously after synchronization has finished.\n *\n * A single `update()` will generate a single \"value\" event at the location\n * where the `update()` was performed, regardless of how many children were\n * modified.\n *\n * Note that modifying data with `update()` will cancel any pending\n * transactions at that location, so extreme care should be taken if mixing\n * `update()` and `transaction()` to modify the same data.\n *\n * Passing `null` to `update()` will remove the data at this location.\n *\n * See\n * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.\n *\n * @param ref - The location to write to.\n * @param values - Object containing multiple values.\n * @returns Resolves when update on server is complete.\n */\nfunction update(ref, values) {\n validateFirebaseMergeDataArg('update', values, ref._path, false);\n const deferred = new util.Deferred();\n repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { }));\n return deferred.promise;\n}\n/**\n * Gets the most up-to-date result for this query.\n *\n * @param query - The query to run.\n * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is\n * available, or rejects if the client is unable to return a value (e.g., if the\n * server is unreachable and there is nothing cached).\n */\nfunction get(query) {\n query = util.getModularInstance(query);\n const callbackContext = new CallbackContext(() => { });\n const container = new ValueEventRegistration(callbackContext);\n return repoGetValue(query._repo, query, container).then(node => {\n return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());\n });\n}\n/**\n * Represents registration for 'value' events.\n */\nclass ValueEventRegistration {\n constructor(callbackContext) {\n this.callbackContext = callbackContext;\n }\n respondsTo(eventType) {\n return eventType === 'value';\n }\n createEvent(change, query) {\n const index = query._queryParams.getIndex();\n return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));\n }\n getEventRunner(eventData) {\n if (eventData.getEventType() === 'cancel') {\n return () => this.callbackContext.onCancel(eventData.error);\n }\n else {\n return () => this.callbackContext.onValue(eventData.snapshot, null);\n }\n }\n createCancelEvent(error, path) {\n if (this.callbackContext.hasCancelCallback) {\n return new CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n }\n matches(other) {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n }\n else if (!other.callbackContext || !this.callbackContext) {\n // If no callback specified, we consider it to match any callback.\n return true;\n }\n else {\n return other.callbackContext.matches(this.callbackContext);\n }\n }\n hasAnyCallback() {\n return this.callbackContext !== null;\n }\n}\n/**\n * Represents the registration of a child_x event.\n */\nclass ChildEventRegistration {\n constructor(eventType, callbackContext) {\n this.eventType = eventType;\n this.callbackContext = callbackContext;\n }\n respondsTo(eventType) {\n let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck =\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return this.eventType === eventToCheck;\n }\n createCancelEvent(error, path) {\n if (this.callbackContext.hasCancelCallback) {\n return new CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n }\n createEvent(change, query) {\n util.assert(change.childName != null, 'Child events should have a childName.');\n const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);\n const index = query._queryParams.getIndex();\n return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);\n }\n getEventRunner(eventData) {\n if (eventData.getEventType() === 'cancel') {\n return () => this.callbackContext.onCancel(eventData.error);\n }\n else {\n return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName);\n }\n }\n matches(other) {\n if (other instanceof ChildEventRegistration) {\n return (this.eventType === other.eventType &&\n (!this.callbackContext ||\n !other.callbackContext ||\n this.callbackContext.matches(other.callbackContext)));\n }\n return false;\n }\n hasAnyCallback() {\n return !!this.callbackContext;\n }\n}\nfunction addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {\n let cancelCallback;\n if (typeof cancelCallbackOrListenOptions === 'object') {\n cancelCallback = undefined;\n options = cancelCallbackOrListenOptions;\n }\n if (typeof cancelCallbackOrListenOptions === 'function') {\n cancelCallback = cancelCallbackOrListenOptions;\n }\n if (options && options.onlyOnce) {\n const userCallback = callback;\n const onceCallback = (dataSnapshot, previousChildName) => {\n repoRemoveEventCallbackForQuery(query._repo, query, container);\n userCallback(dataSnapshot, previousChildName);\n };\n onceCallback.userCallback = callback.userCallback;\n onceCallback.context = callback.context;\n callback = onceCallback;\n }\n const callbackContext = new CallbackContext(callback, cancelCallback || undefined);\n const container = eventType === 'value'\n ? new ValueEventRegistration(callbackContext)\n : new ChildEventRegistration(eventType, callbackContext);\n repoAddEventCallbackForQuery(query._repo, query, container);\n return () => repoRemoveEventCallbackForQuery(query._repo, query, container);\n}\nfunction onValue(query, callback, cancelCallbackOrListenOptions, options) {\n return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);\n}\nfunction onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {\n return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);\n}\nfunction onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {\n return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);\n}\nfunction onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {\n return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);\n}\nfunction onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {\n return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);\n}\n/**\n * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.\n * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from\n * the respective `on*` callbacks.\n *\n * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener\n * will not automatically remove listeners registered on child nodes, `off()`\n * must also be called on any child listeners to remove the callback.\n *\n * If a callback is not specified, all callbacks for the specified eventType\n * will be removed. Similarly, if no eventType is specified, all callbacks\n * for the `Reference` will be removed.\n *\n * Individual listeners can also be removed by invoking their unsubscribe\n * callbacks.\n *\n * @param query - The query that the listener was registered with.\n * @param eventType - One of the following strings: \"value\", \"child_added\",\n * \"child_changed\", \"child_removed\", or \"child_moved.\" If omitted, all callbacks\n * for the `Reference` will be removed.\n * @param callback - The callback function that was passed to `on()` or\n * `undefined` to remove all callbacks.\n */\nfunction off(query, eventType, callback) {\n let container = null;\n const expCallback = callback ? new CallbackContext(callback) : null;\n if (eventType === 'value') {\n container = new ValueEventRegistration(expCallback);\n }\n else if (eventType) {\n container = new ChildEventRegistration(eventType, expCallback);\n }\n repoRemoveEventCallbackForQuery(query._repo, query, container);\n}\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Database query. `QueryConstraint`s are created by invoking {@link endAt},\n * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link\n * limitToFirst}, {@link limitToLast}, {@link orderByChild},\n * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,\n * {@link orderByValue} or {@link equalTo} and\n * can then be passed to {@link query} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nclass QueryConstraint {\n}\nclass QueryEndAtConstraint extends QueryConstraint {\n constructor(_value, _key) {\n super();\n this._value = _value;\n this._key = _key;\n this.type = 'endAt';\n }\n _apply(query) {\n validateFirebaseDataArg('endAt', this._value, query._path, true);\n const newParams = queryParamsEndAt(query._queryParams, this._value, this._key);\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasEnd()) {\n throw new Error('endAt: Starting point was already set (by another call to endAt, ' +\n 'endBefore or equalTo).');\n }\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\n }\n}\n/**\n * Creates a `QueryConstraint` with the specified ending point.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The ending point is inclusive, so children with exactly the specified value\n * will be included in the query. The optional key argument can be used to\n * further limit the range of the query. If it is specified, then children that\n * have exactly the specified value must also have a key name less than or equal\n * to the specified key.\n *\n * You can read more about `endAt()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to end at. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to end at, among the children with the previously\n * specified priority. This argument is only allowed if ordering by child,\n * value, or priority.\n */\nfunction endAt(value, key) {\n validateKey('endAt', 'key', key, true);\n return new QueryEndAtConstraint(value, key);\n}\nclass QueryEndBeforeConstraint extends QueryConstraint {\n constructor(_value, _key) {\n super();\n this._value = _value;\n this._key = _key;\n this.type = 'endBefore';\n }\n _apply(query) {\n validateFirebaseDataArg('endBefore', this._value, query._path, false);\n const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasEnd()) {\n throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +\n 'endBefore or equalTo).');\n }\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\n }\n}\n/**\n * Creates a `QueryConstraint` with the specified ending point (exclusive).\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The ending point is exclusive. If only a value is provided, children\n * with a value less than the specified value will be included in the query.\n * If a key is specified, then children must have a value less than or equal\n * to the specified value and a key name less than the specified key.\n *\n * @param value - The value to end before. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to end before, among the children with the\n * previously specified priority. This argument is only allowed if ordering by\n * child, value, or priority.\n */\nfunction endBefore(value, key) {\n validateKey('endBefore', 'key', key, true);\n return new QueryEndBeforeConstraint(value, key);\n}\nclass QueryStartAtConstraint extends QueryConstraint {\n constructor(_value, _key) {\n super();\n this._value = _value;\n this._key = _key;\n this.type = 'startAt';\n }\n _apply(query) {\n validateFirebaseDataArg('startAt', this._value, query._path, true);\n const newParams = queryParamsStartAt(query._queryParams, this._value, this._key);\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasStart()) {\n throw new Error('startAt: Starting point was already set (by another call to startAt, ' +\n 'startBefore or equalTo).');\n }\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\n }\n}\n/**\n * Creates a `QueryConstraint` with the specified starting point.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The starting point is inclusive, so children with exactly the specified value\n * will be included in the query. The optional key argument can be used to\n * further limit the range of the query. If it is specified, then children that\n * have exactly the specified value must also have a key name greater than or\n * equal to the specified key.\n *\n * You can read more about `startAt()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to start at. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start at. This argument is only allowed if\n * ordering by child, value, or priority.\n */\nfunction startAt(value = null, key) {\n validateKey('startAt', 'key', key, true);\n return new QueryStartAtConstraint(value, key);\n}\nclass QueryStartAfterConstraint extends QueryConstraint {\n constructor(_value, _key) {\n super();\n this._value = _value;\n this._key = _key;\n this.type = 'startAfter';\n }\n _apply(query) {\n validateFirebaseDataArg('startAfter', this._value, query._path, false);\n const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasStart()) {\n throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +\n 'startAfter, or equalTo).');\n }\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\n }\n}\n/**\n * Creates a `QueryConstraint` with the specified starting point (exclusive).\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The starting point is exclusive. If only a value is provided, children\n * with a value greater than the specified value will be included in the query.\n * If a key is specified, then children must have a value greater than or equal\n * to the specified value and a a key name greater than the specified key.\n *\n * @param value - The value to start after. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start after. This argument is only allowed if\n * ordering by child, value, or priority.\n */\nfunction startAfter(value, key) {\n validateKey('startAfter', 'key', key, true);\n return new QueryStartAfterConstraint(value, key);\n}\nclass QueryLimitToFirstConstraint extends QueryConstraint {\n constructor(_limit) {\n super();\n this._limit = _limit;\n this.type = 'limitToFirst';\n }\n _apply(query) {\n if (query._queryParams.hasLimit()) {\n throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +\n 'or limitToLast).');\n }\n return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);\n }\n}\n/**\n * Creates a new `QueryConstraint` that if limited to the first specific number\n * of children.\n *\n * The `limitToFirst()` method is used to set a maximum number of children to be\n * synced for a given callback. If we set a limit of 100, we will initially only\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\n * stored in our Database, a `child_added` event will fire for each message.\n * However, if we have over 100 messages, we will only receive a `child_added`\n * event for the first 100 ordered messages. As items change, we will receive\n * `child_removed` events for each item that drops out of the active list so\n * that the total number stays at 100.\n *\n * You can read more about `limitToFirst()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param limit - The maximum number of nodes to include in this query.\n */\nfunction limitToFirst(limit) {\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\n throw new Error('limitToFirst: First argument must be a positive integer.');\n }\n return new QueryLimitToFirstConstraint(limit);\n}\nclass QueryLimitToLastConstraint extends QueryConstraint {\n constructor(_limit) {\n super();\n this._limit = _limit;\n this.type = 'limitToLast';\n }\n _apply(query) {\n if (query._queryParams.hasLimit()) {\n throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +\n 'or limitToLast).');\n }\n return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);\n }\n}\n/**\n * Creates a new `QueryConstraint` that is limited to return only the last\n * specified number of children.\n *\n * The `limitToLast()` method is used to set a maximum number of children to be\n * synced for a given callback. If we set a limit of 100, we will initially only\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\n * stored in our Database, a `child_added` event will fire for each message.\n * However, if we have over 100 messages, we will only receive a `child_added`\n * event for the last 100 ordered messages. As items change, we will receive\n * `child_removed` events for each item that drops out of the active list so\n * that the total number stays at 100.\n *\n * You can read more about `limitToLast()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param limit - The maximum number of nodes to include in this query.\n */\nfunction limitToLast(limit) {\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\n throw new Error('limitToLast: First argument must be a positive integer.');\n }\n return new QueryLimitToLastConstraint(limit);\n}\nclass QueryOrderByChildConstraint extends QueryConstraint {\n constructor(_path) {\n super();\n this._path = _path;\n this.type = 'orderByChild';\n }\n _apply(query) {\n validateNoPreviousOrderByCall(query, 'orderByChild');\n const parsedPath = new Path(this._path);\n if (pathIsEmpty(parsedPath)) {\n throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');\n }\n const index = new PathIndex(parsedPath);\n const newParams = queryParamsOrderBy(query._queryParams, index);\n validateQueryEndpoints(newParams);\n return new QueryImpl(query._repo, query._path, newParams, \n /*orderByCalled=*/ true);\n }\n}\n/**\n * Creates a new `QueryConstraint` that orders by the specified child key.\n *\n * Queries can only order by one key at a time. Calling `orderByChild()`\n * multiple times on the same query is an error.\n *\n * Firebase queries allow you to order your data by any child key on the fly.\n * However, if you know in advance what your indexes will be, you can define\n * them via the .indexOn rule in your Security Rules for better performance. See\n * the{@link https://firebase.google.com/docs/database/security/indexing-data}\n * rule for more information.\n *\n * You can read more about `orderByChild()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n *\n * @param path - The path to order by.\n */\nfunction orderByChild(path) {\n if (path === '$key') {\n throw new Error('orderByChild: \"$key\" is invalid. Use orderByKey() instead.');\n }\n else if (path === '$priority') {\n throw new Error('orderByChild: \"$priority\" is invalid. Use orderByPriority() instead.');\n }\n else if (path === '$value') {\n throw new Error('orderByChild: \"$value\" is invalid. Use orderByValue() instead.');\n }\n validatePathString('orderByChild', 'path', path, false);\n return new QueryOrderByChildConstraint(path);\n}\nclass QueryOrderByKeyConstraint extends QueryConstraint {\n constructor() {\n super(...arguments);\n this.type = 'orderByKey';\n }\n _apply(query) {\n validateNoPreviousOrderByCall(query, 'orderByKey');\n const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(query._repo, query._path, newParams, \n /*orderByCalled=*/ true);\n }\n}\n/**\n * Creates a new `QueryConstraint` that orders by the key.\n *\n * Sorts the results of a query by their (ascending) key values.\n *\n * You can read more about `orderByKey()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n */\nfunction orderByKey() {\n return new QueryOrderByKeyConstraint();\n}\nclass QueryOrderByPriorityConstraint extends QueryConstraint {\n constructor() {\n super(...arguments);\n this.type = 'orderByPriority';\n }\n _apply(query) {\n validateNoPreviousOrderByCall(query, 'orderByPriority');\n const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(query._repo, query._path, newParams, \n /*orderByCalled=*/ true);\n }\n}\n/**\n * Creates a new `QueryConstraint` that orders by priority.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}\n * for alternatives to priority.\n */\nfunction orderByPriority() {\n return new QueryOrderByPriorityConstraint();\n}\nclass QueryOrderByValueConstraint extends QueryConstraint {\n constructor() {\n super(...arguments);\n this.type = 'orderByValue';\n }\n _apply(query) {\n validateNoPreviousOrderByCall(query, 'orderByValue');\n const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(query._repo, query._path, newParams, \n /*orderByCalled=*/ true);\n }\n}\n/**\n * Creates a new `QueryConstraint` that orders by value.\n *\n * If the children of a query are all scalar values (string, number, or\n * boolean), you can order the results by their (ascending) values.\n *\n * You can read more about `orderByValue()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n */\nfunction orderByValue() {\n return new QueryOrderByValueConstraint();\n}\nclass QueryEqualToValueConstraint extends QueryConstraint {\n constructor(_value, _key) {\n super();\n this._value = _value;\n this._key = _key;\n this.type = 'equalTo';\n }\n _apply(query) {\n validateFirebaseDataArg('equalTo', this._value, query._path, false);\n if (query._queryParams.hasStart()) {\n throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +\n 'equalTo).');\n }\n if (query._queryParams.hasEnd()) {\n throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +\n 'equalTo).');\n }\n return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));\n }\n}\n/**\n * Creates a `QueryConstraint` that includes children that match the specified\n * value.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The optional key argument can be used to further limit the range of the\n * query. If it is specified, then children that have exactly the specified\n * value must also have exactly the specified key as their key name. This can be\n * used to filter result sets with many matches for the same value.\n *\n * You can read more about `equalTo()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to match for. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start at, among the children with the\n * previously specified priority. This argument is only allowed if ordering by\n * child, value, or priority.\n */\nfunction equalTo(value, key) {\n validateKey('equalTo', 'key', key, true);\n return new QueryEqualToValueConstraint(value, key);\n}\n/**\n * Creates a new immutable instance of `Query` that is extended to also include\n * additional query constraints.\n *\n * @param query - The Query instance to use as a base for the new constraints.\n * @param queryConstraints - The list of `QueryConstraint`s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nfunction query(query, ...queryConstraints) {\n let queryImpl = util.getModularInstance(query);\n for (const constraint of queryConstraints) {\n queryImpl = constraint._apply(queryImpl);\n }\n return queryImpl;\n}\n/**\n * Define reference constructor in various modules\n *\n * We are doing this here to avoid several circular\n * dependency issues\n */\nsyncPointSetReferenceConstructor(ReferenceImpl);\nsyncTreeSetReferenceConstructor(ReferenceImpl);\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * This variable is also defined in the firebase Node.js Admin SDK. Before\n * modifying this definition, consult the definition in:\n *\n * https://github.com/firebase/firebase-admin-node\n *\n * and make sure the two are consistent.\n */\nconst FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';\n/**\n * Creates and caches `Repo` instances.\n */\nconst repos = {};\n/**\n * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).\n */\nlet useRestClient = false;\n/**\n * Update an existing `Repo` in place to point to a new host/port.\n */\nfunction repoManagerApplyEmulatorSettings(repo, hostAndPort, emulatorOptions, tokenProvider) {\n const portIndex = hostAndPort.lastIndexOf(':');\n const host = hostAndPort.substring(0, portIndex);\n const useSsl = util.isCloudWorkstation(host);\n repo.repoInfo_ = new RepoInfo(hostAndPort, \n /* secure= */ useSsl, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams, \n /*isUsingEmulator=*/ true, emulatorOptions);\n if (tokenProvider) {\n repo.authTokenProvider_ = tokenProvider;\n }\n}\n/**\n * This function should only ever be called to CREATE a new database instance.\n * @internal\n */\nfunction repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {\n let dbUrl = url || app.options.databaseURL;\n if (dbUrl === undefined) {\n if (!app.options.projectId) {\n fatal(\"Can't determine Firebase Database URL. Be sure to include \" +\n ' a Project ID when calling firebase.initializeApp().');\n }\n log('Using default host for project ', app.options.projectId);\n dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;\n }\n let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\n let repoInfo = parsedUrl.repoInfo;\n let isEmulator;\n let dbEmulatorHost = undefined;\n if (typeof process !== 'undefined' && process.env) {\n dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];\n }\n if (dbEmulatorHost) {\n isEmulator = true;\n dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;\n parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\n repoInfo = parsedUrl.repoInfo;\n }\n else {\n isEmulator = !parsedUrl.repoInfo.secure;\n }\n const authTokenProvider = nodeAdmin && isEmulator\n ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)\n : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);\n validateUrl('Invalid Firebase Database URL', parsedUrl);\n if (!pathIsEmpty(parsedUrl.path)) {\n fatal('Database URL must point to the root of a Firebase Database ' +\n '(not including a child path).');\n }\n const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app, appCheckProvider));\n return new Database(repo, app);\n}\n/**\n * Remove the repo and make sure it is disconnected.\n *\n */\nfunction repoManagerDeleteRepo(repo, appName) {\n const appRepos = repos[appName];\n // This should never happen...\n if (!appRepos || appRepos[repo.key] !== repo) {\n fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);\n }\n repoInterrupt(repo);\n delete appRepos[repo.key];\n}\n/**\n * Ensures a repo doesn't already exist and then creates one using the\n * provided app.\n *\n * @param repoInfo - The metadata about the Repo\n * @returns The Repo object for the specified server / repoName.\n */\nfunction repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {\n let appRepos = repos[app.name];\n if (!appRepos) {\n appRepos = {};\n repos[app.name] = appRepos;\n }\n let repo = appRepos[repoInfo.toURLString()];\n if (repo) {\n fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');\n }\n repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);\n appRepos[repoInfo.toURLString()] = repo;\n return repo;\n}\n/**\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\n */\nfunction repoManagerForceRestClient(forceRestClient) {\n useRestClient = forceRestClient;\n}\n/**\n * Class representing a Firebase Realtime Database.\n */\nclass Database {\n /** @hideconstructor */\n constructor(_repoInternal, \n /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */\n app) {\n this._repoInternal = _repoInternal;\n this.app = app;\n /** Represents a `Database` instance. */\n this['type'] = 'database';\n /** Track if the instance has been used (root or repo accessed) */\n this._instanceStarted = false;\n }\n get _repo() {\n if (!this._instanceStarted) {\n repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);\n this._instanceStarted = true;\n }\n return this._repoInternal;\n }\n get _root() {\n if (!this._rootInternal) {\n this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());\n }\n return this._rootInternal;\n }\n _delete() {\n if (this._rootInternal !== null) {\n repoManagerDeleteRepo(this._repo, this.app.name);\n this._repoInternal = null;\n this._rootInternal = null;\n }\n return Promise.resolve();\n }\n _checkNotDeleted(apiName) {\n if (this._rootInternal === null) {\n fatal('Cannot call ' + apiName + ' on a deleted database.');\n }\n }\n}\nfunction checkTransportInit() {\n if (TransportManager.IS_TRANSPORT_INITIALIZED) {\n warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');\n }\n}\n/**\n * Force the use of websockets instead of longPolling.\n */\nfunction forceWebSockets() {\n checkTransportInit();\n BrowserPollConnection.forceDisallow();\n}\n/**\n * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.\n */\nfunction forceLongPolling() {\n checkTransportInit();\n WebSocketConnection.forceDisallow();\n BrowserPollConnection.forceAllow();\n}\n/**\n * Modify the provided instance to communicate with the Realtime Database\n * emulator.\n *\n *

Note: This method must be called before performing any other operation.\n *\n * @param db - The instance to modify.\n * @param host - The emulator host (ex: localhost)\n * @param port - The emulator port (ex: 8080)\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\n */\nfunction connectDatabaseEmulator(db, host, port, options = {}) {\n db = util.getModularInstance(db);\n db._checkNotDeleted('useEmulator');\n const hostAndPort = `${host}:${port}`;\n const repo = db._repoInternal;\n if (db._instanceStarted) {\n // If the instance has already been started, then silenty fail if this function is called again\n // with the same parameters. If the parameters differ then assert.\n if (hostAndPort === db._repoInternal.repoInfo_.host &&\n util.deepEqual(options, repo.repoInfo_.emulatorOptions)) {\n return;\n }\n fatal('connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.');\n }\n let tokenProvider = undefined;\n if (repo.repoInfo_.nodeAdmin) {\n if (options.mockUserToken) {\n fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the \"firebase\" package instead of \"firebase-admin\".');\n }\n tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);\n }\n else if (options.mockUserToken) {\n const token = typeof options.mockUserToken === 'string'\n ? options.mockUserToken\n : util.createMockUserToken(options.mockUserToken, db.app.options.projectId);\n tokenProvider = new EmulatorTokenProvider(token);\n }\n // Workaround to get cookies in Firebase Studio\n if (util.isCloudWorkstation(host)) {\n void util.pingServer(host);\n util.updateEmulatorBanner('Database', true);\n }\n // Modify the repo to apply emulator settings\n repoManagerApplyEmulatorSettings(repo, hostAndPort, options, tokenProvider);\n}\n/**\n * Disconnects from the server (all Database operations will be completed\n * offline).\n *\n * The client automatically maintains a persistent connection to the Database\n * server, which will remain active indefinitely and reconnect when\n * disconnected. However, the `goOffline()` and `goOnline()` methods may be used\n * to control the client connection in cases where a persistent connection is\n * undesirable.\n *\n * While offline, the client will no longer receive data updates from the\n * Database. However, all Database operations performed locally will continue to\n * immediately fire events, allowing your application to continue behaving\n * normally. Additionally, each operation performed locally will automatically\n * be queued and retried upon reconnection to the Database server.\n *\n * To reconnect to the Database and begin receiving remote events, see\n * `goOnline()`.\n *\n * @param db - The instance to disconnect.\n */\nfunction goOffline(db) {\n db = util.getModularInstance(db);\n db._checkNotDeleted('goOffline');\n repoInterrupt(db._repo);\n}\n/**\n * Reconnects to the server and synchronizes the offline Database state\n * with the server state.\n *\n * This method should be used after disabling the active connection with\n * `goOffline()`. Once reconnected, the client will transmit the proper data\n * and fire the appropriate events so that your client \"catches up\"\n * automatically.\n *\n * @param db - The instance to reconnect.\n */\nfunction goOnline(db) {\n db = util.getModularInstance(db);\n db._checkNotDeleted('goOnline');\n repoResume(db._repo);\n}\nfunction enableLogging(logger, persistent) {\n enableLogging$1(logger, persistent);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst SERVER_TIMESTAMP = {\n '.sv': 'timestamp'\n};\n/**\n * Returns a placeholder value for auto-populating the current timestamp (time\n * since the Unix epoch, in milliseconds) as determined by the Firebase\n * servers.\n */\nfunction serverTimestamp() {\n return SERVER_TIMESTAMP;\n}\n/**\n * Returns a placeholder value that can be used to atomically increment the\n * current database value by the provided delta.\n *\n * @param delta - the amount to modify the current value atomically.\n * @returns A placeholder value for modifying data atomically server-side.\n */\nfunction increment(delta) {\n return {\n '.sv': {\n 'increment': delta\n }\n };\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A type for the resolve value of {@link runTransaction}.\n */\nclass TransactionResult {\n /** @hideconstructor */\n constructor(\n /** Whether the transaction was successfully committed. */\n committed, \n /** The resulting data snapshot. */\n snapshot) {\n this.committed = committed;\n this.snapshot = snapshot;\n }\n /** Returns a JSON-serializable representation of this object. */\n toJSON() {\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n }\n}\n/**\n * Atomically modifies the data at this location.\n *\n * Atomically modify the data at this location. Unlike a normal `set()`, which\n * just overwrites the data regardless of its previous value, `runTransaction()` is\n * used to modify the existing value to a new value, ensuring there are no\n * conflicts with other clients writing to the same location at the same time.\n *\n * To accomplish this, you pass `runTransaction()` an update function which is\n * used to transform the current value into a new value. If another client\n * writes to the location before your new value is successfully written, your\n * update function will be called again with the new current value, and the\n * write will be retried. This will happen repeatedly until your write succeeds\n * without conflict or you abort the transaction by not returning a value from\n * your update function.\n *\n * Note: Modifying data with `set()` will cancel any pending transactions at\n * that location, so extreme care should be taken if mixing `set()` and\n * `runTransaction()` to update the same data.\n *\n * Note: When using transactions with Security and Firebase Rules in place, be\n * aware that a client needs `.read` access in addition to `.write` access in\n * order to perform a transaction. This is because the client-side nature of\n * transactions requires the client to read the data in order to transactionally\n * update it.\n *\n * @param ref - The location to atomically modify.\n * @param transactionUpdate - A developer-supplied function which will be passed\n * the current data stored at this location (as a JavaScript object). The\n * function should return the new value it would like written (as a JavaScript\n * object). If `undefined` is returned (i.e. you return with no arguments) the\n * transaction will be aborted and the data at this location will not be\n * modified.\n * @param options - An options object to configure transactions.\n * @returns A `Promise` that can optionally be used instead of the `onComplete`\n * callback to handle success and failure.\n */\nfunction runTransaction(ref, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntransactionUpdate, options) {\n ref = util.getModularInstance(ref);\n validateWritablePath('Reference.transaction', ref._path);\n if (ref.key === '.length' || ref.key === '.keys') {\n throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');\n }\n const applyLocally = options?.applyLocally ?? true;\n const deferred = new util.Deferred();\n const promiseComplete = (error, committed, node) => {\n let dataSnapshot = null;\n if (error) {\n deferred.reject(error);\n }\n else {\n dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);\n deferred.resolve(new TransactionResult(committed, dataSnapshot));\n }\n };\n // Add a watch to make sure we get server updates.\n const unwatcher = onValue(ref, () => { });\n repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);\n return deferred.promise;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nPersistentConnection;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nPersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nPersistentConnection.prototype.echo = function (data, onEcho) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n// RealTimeConnection properties that we use in tests.\nConnection;\n/**\n * @internal\n */\nconst hijackHash = function (newHash) {\n const oldPut = PersistentConnection.prototype.put;\n PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {\n if (hash !== undefined) {\n hash = newHash();\n }\n oldPut.call(this, pathString, data, onComplete, hash);\n };\n return function () {\n PersistentConnection.prototype.put = oldPut;\n };\n};\nRepoInfo;\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n * @internal\n */\nconst forceRestClient = function (forceRestClient) {\n repoManagerForceRestClient(forceRestClient);\n};\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Used by console to create a database based on the app,\n * passed database URL and a custom auth implementation.\n * @internal\n * @param app - A valid FirebaseApp-like object\n * @param url - A valid Firebase databaseURL\n * @param version - custom version e.g. firebase-admin version\n * @param customAppCheckImpl - custom app check implementation\n * @param customAuthImpl - custom auth implementation\n */\nfunction _initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, nodeAdmin = false }) {\n setSDKVersion(version);\n /**\n * ComponentContainer('database-standalone') is just a placeholder that doesn't perform\n * any actual function.\n */\n const componentContainer = new component.ComponentContainer('database-standalone');\n const authProvider = new component.Provider('auth-internal', componentContainer);\n let appCheckProvider;\n if (customAppCheckImpl) {\n appCheckProvider = new component.Provider('app-check-internal', componentContainer);\n appCheckProvider.setComponent(new component.Component('app-check-internal', () => customAppCheckImpl, \"PRIVATE\" /* ComponentType.PRIVATE */));\n }\n authProvider.setComponent(new component.Component('auth-internal', () => customAuthImpl, \"PRIVATE\" /* ComponentType.PRIVATE */));\n return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin);\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nsetWebSocketImpl(Websocket__default[\"default\"].Client);\n\nexports.DataSnapshot = DataSnapshot;\nexports.Database = Database;\nexports.OnDisconnect = OnDisconnect;\nexports.QueryConstraint = QueryConstraint;\nexports.TransactionResult = TransactionResult;\nexports._QueryImpl = QueryImpl;\nexports._QueryParams = QueryParams;\nexports._ReferenceImpl = ReferenceImpl;\nexports._TEST_ACCESS_forceRestClient = forceRestClient;\nexports._TEST_ACCESS_hijackHash = hijackHash;\nexports._initStandalone = _initStandalone;\nexports._repoManagerDatabaseFromApp = repoManagerDatabaseFromApp;\nexports._setSDKVersion = setSDKVersion;\nexports._validatePathString = validatePathString;\nexports._validateWritablePath = validateWritablePath;\nexports.child = child;\nexports.connectDatabaseEmulator = connectDatabaseEmulator;\nexports.enableLogging = enableLogging;\nexports.endAt = endAt;\nexports.endBefore = endBefore;\nexports.equalTo = equalTo;\nexports.forceLongPolling = forceLongPolling;\nexports.forceWebSockets = forceWebSockets;\nexports.get = get;\nexports.goOffline = goOffline;\nexports.goOnline = goOnline;\nexports.increment = increment;\nexports.limitToFirst = limitToFirst;\nexports.limitToLast = limitToLast;\nexports.off = off;\nexports.onChildAdded = onChildAdded;\nexports.onChildChanged = onChildChanged;\nexports.onChildMoved = onChildMoved;\nexports.onChildRemoved = onChildRemoved;\nexports.onDisconnect = onDisconnect;\nexports.onValue = onValue;\nexports.orderByChild = orderByChild;\nexports.orderByKey = orderByKey;\nexports.orderByPriority = orderByPriority;\nexports.orderByValue = orderByValue;\nexports.push = push;\nexports.query = query;\nexports.ref = ref;\nexports.refFromURL = refFromURL;\nexports.remove = remove;\nexports.runTransaction = runTransaction;\nexports.serverTimestamp = serverTimestamp;\nexports.set = set;\nexports.setPriority = setPriority;\nexports.setWithPriority = setWithPriority;\nexports.startAfter = startAfter;\nexports.startAt = startAt;\nexports.update = update;\n//# sourceMappingURL=index.standalone.js.map\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nconst logClient = new Logger('@firebase/database-compat');\n\nexport const warn = function (msg: string) {\n const message = 'FIREBASE WARNING: ' + msg;\n logClient.warn(message);\n};\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { errorPrefix as errorPrefixFxn } from '@firebase/util';\n\nexport const validateBoolean = function (\n fnName: string,\n argumentName: string,\n bool: unknown,\n optional: boolean\n) {\n if (optional && bool === undefined) {\n return;\n }\n if (typeof bool !== 'boolean') {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) + 'must be a boolean.'\n );\n }\n};\n\nexport const validateEventType = function (\n fnName: string,\n eventType: string,\n optional: boolean\n) {\n if (optional && eventType === undefined) {\n return;\n }\n\n switch (eventType) {\n case 'value':\n case 'child_added':\n case 'child_removed':\n case 'child_changed':\n case 'child_moved':\n break;\n default:\n throw new Error(\n errorPrefixFxn(fnName, 'eventType') +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".'\n );\n }\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { OnDisconnect as ModularOnDisconnect } from '@firebase/database';\nimport { validateArgCount, validateCallback, Compat } from '@firebase/util';\n\nimport { warn } from '../util/util';\nexport class OnDisconnect implements Compat {\n constructor(readonly _delegate: ModularOnDisconnect) {}\n\n cancel(onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);\n validateCallback('OnDisconnect.cancel', 'onComplete', onComplete, true);\n const result = this._delegate.cancel();\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n remove(onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);\n validateCallback('OnDisconnect.remove', 'onComplete', onComplete, true);\n const result = this._delegate.remove();\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n set(value: unknown, onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('OnDisconnect.set', 1, 2, arguments.length);\n validateCallback('OnDisconnect.set', 'onComplete', onComplete, true);\n const result = this._delegate.set(value);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n setWithPriority(\n value: unknown,\n priority: number | string | null,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length);\n validateCallback(\n 'OnDisconnect.setWithPriority',\n 'onComplete',\n onComplete,\n true\n );\n const result = this._delegate.setWithPriority(value, priority);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n update(\n objectToMerge: Record,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('OnDisconnect.update', 1, 2, arguments.length);\n if (Array.isArray(objectToMerge)) {\n const newObjectToMerge: { [k: string]: unknown } = {};\n for (let i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n warn(\n 'Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' +\n 'existing data, or an Object with integer keys if you really do want to only update some of the children.'\n );\n }\n validateCallback('OnDisconnect.update', 'onComplete', onComplete, true);\n const result = this._delegate.update(objectToMerge);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { validateArgCount } from '@firebase/util';\n\nimport { DataSnapshot } from './Reference';\n\nexport class TransactionResult {\n /**\n * A type for the resolve value of Firebase.transaction.\n */\n constructor(public committed: boolean, public snapshot: DataSnapshot) {}\n\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n toJSON(): object {\n validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n OnDisconnect as ModularOnDisconnect,\n off,\n onChildAdded,\n onChildChanged,\n onChildMoved,\n onChildRemoved,\n onValue,\n EventType,\n limitToFirst,\n query,\n limitToLast,\n orderByChild,\n orderByKey,\n orderByValue,\n orderByPriority,\n startAt,\n startAfter,\n endAt,\n endBefore,\n equalTo,\n get,\n set,\n update,\n setWithPriority,\n remove,\n setPriority,\n push,\n runTransaction,\n child,\n DataSnapshot as ModularDataSnapshot,\n Query as ExpQuery,\n DatabaseReference as ModularReference,\n _QueryImpl,\n _ReferenceImpl,\n _validatePathString,\n _validateWritablePath,\n _UserCallback,\n _QueryParams\n} from '@firebase/database';\nimport {\n Compat,\n Deferred,\n errorPrefix,\n validateArgCount,\n validateCallback,\n validateContextObject\n} from '@firebase/util';\n\nimport { warn } from '../util/util';\nimport { validateBoolean, validateEventType } from '../util/validation';\n\nimport { Database } from './Database';\nimport { OnDisconnect } from './onDisconnect';\nimport { TransactionResult } from './TransactionResult';\n\n/**\n * Class representing a firebase data snapshot. It wraps a SnapshotNode and\n * surfaces the public methods (val, forEach, etc.) we want to expose.\n */\nexport class DataSnapshot implements Compat {\n constructor(\n readonly _database: Database,\n readonly _delegate: ModularDataSnapshot\n ) {}\n\n /**\n * Retrieves the snapshot contents as JSON. Returns null if the snapshot is\n * empty.\n *\n * @returns JSON representation of the DataSnapshot contents, or null if empty.\n */\n val(): unknown {\n validateArgCount('DataSnapshot.val', 0, 0, arguments.length);\n return this._delegate.val();\n }\n\n /**\n * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting\n * the entire node contents.\n * @returns JSON representation of the DataSnapshot contents, or null if empty.\n */\n exportVal(): unknown {\n validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length);\n return this._delegate.exportVal();\n }\n\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n toJSON(): unknown {\n // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content\n validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length);\n return this._delegate.toJSON();\n }\n\n /**\n * Returns whether the snapshot contains a non-null value.\n *\n * @returns Whether the snapshot contains a non-null value, or is empty.\n */\n exists(): boolean {\n validateArgCount('DataSnapshot.exists', 0, 0, arguments.length);\n return this._delegate.exists();\n }\n\n /**\n * Returns a DataSnapshot of the specified child node's contents.\n *\n * @param path - Path to a child.\n * @returns DataSnapshot for child node.\n */\n child(path: string): DataSnapshot {\n validateArgCount('DataSnapshot.child', 0, 1, arguments.length);\n // Ensure the childPath is a string (can be a number)\n path = String(path);\n _validatePathString('DataSnapshot.child', 'path', path, false);\n return new DataSnapshot(this._database, this._delegate.child(path));\n }\n\n /**\n * Returns whether the snapshot contains a child at the specified path.\n *\n * @param path - Path to a child.\n * @returns Whether the child exists.\n */\n hasChild(path: string): boolean {\n validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);\n _validatePathString('DataSnapshot.hasChild', 'path', path, false);\n return this._delegate.hasChild(path);\n }\n\n /**\n * Returns the priority of the object, or null if no priority was set.\n *\n * @returns The priority.\n */\n getPriority(): string | number | null {\n validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);\n return this._delegate.priority;\n }\n\n /**\n * Iterates through child nodes and calls the specified action for each one.\n *\n * @param action - Callback function to be called\n * for each child.\n * @returns True if forEach was canceled by action returning true for\n * one of the child nodes.\n */\n forEach(action: (snapshot: IteratedDataSnapshot) => boolean | void): boolean {\n validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);\n validateCallback('DataSnapshot.forEach', 'action', action, false);\n return this._delegate.forEach(expDataSnapshot =>\n action(new DataSnapshot(this._database, expDataSnapshot))\n );\n }\n\n /**\n * Returns whether this DataSnapshot has children.\n * @returns True if the DataSnapshot contains 1 or more child nodes.\n */\n hasChildren(): boolean {\n validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);\n return this._delegate.hasChildren();\n }\n\n get key() {\n return this._delegate.key;\n }\n\n /**\n * Returns the number of children for this DataSnapshot.\n * @returns The number of children that this DataSnapshot contains.\n */\n numChildren(): number {\n validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);\n return this._delegate.size;\n }\n\n /**\n * @returns The Firebase reference for the location this snapshot's data came\n * from.\n */\n getRef(): Reference {\n validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);\n return new Reference(this._database, this._delegate.ref);\n }\n\n get ref(): Reference {\n return this.getRef();\n }\n}\n\n/**\n * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined.\n */\nexport interface IteratedDataSnapshot extends DataSnapshot {\n key: string; // key of the location of this snapshot.\n}\n\nexport interface SnapshotCallback {\n (dataSnapshot: DataSnapshot, previousChildName?: string | null): unknown;\n}\n\n/**\n * A Query represents a filter to be applied to a firebase location. This object purely represents the\n * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js.\n *\n * Since every Firebase reference is a query, Firebase inherits from this object.\n */\nexport class Query implements Compat {\n constructor(readonly database: Database, readonly _delegate: ExpQuery) {}\n\n on(\n eventType: string,\n callback: SnapshotCallback,\n cancelCallbackOrContext?: ((a: Error) => unknown) | object | null,\n context?: object | null\n ): SnapshotCallback {\n validateArgCount('Query.on', 2, 4, arguments.length);\n validateCallback('Query.on', 'callback', callback, false);\n\n const ret = Query.getCancelAndContextArgs_(\n 'Query.on',\n cancelCallbackOrContext,\n context\n );\n const valueCallback = (expSnapshot, previousChildName?) => {\n callback.call(\n ret.context,\n new DataSnapshot(this.database, expSnapshot),\n previousChildName\n );\n };\n valueCallback.userCallback = callback;\n valueCallback.context = ret.context;\n const cancelCallback = ret.cancel?.bind(ret.context);\n\n switch (eventType) {\n case 'value':\n onValue(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_added':\n onChildAdded(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_removed':\n onChildRemoved(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_changed':\n onChildChanged(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_moved':\n onChildMoved(this._delegate, valueCallback, cancelCallback);\n return callback;\n default:\n throw new Error(\n errorPrefix('Query.on', 'eventType') +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".'\n );\n }\n }\n\n off(\n eventType?: string,\n callback?: SnapshotCallback,\n context?: object | null\n ): void {\n validateArgCount('Query.off', 0, 3, arguments.length);\n validateEventType('Query.off', eventType, true);\n validateCallback('Query.off', 'callback', callback, true);\n validateContextObject('Query.off', 'context', context, true);\n if (callback) {\n const valueCallback: _UserCallback = () => {};\n valueCallback.userCallback = callback;\n valueCallback.context = context;\n off(this._delegate, eventType as EventType, valueCallback);\n } else {\n off(this._delegate, eventType as EventType | undefined);\n }\n }\n\n /**\n * Get the server-value for this query, or return a cached value if not connected.\n */\n get(): Promise {\n return get(this._delegate).then(expSnapshot => {\n return new DataSnapshot(this.database, expSnapshot);\n });\n }\n\n /**\n * Attaches a listener, waits for the first event, and then removes the listener\n */\n once(\n eventType: string,\n callback?: SnapshotCallback,\n failureCallbackOrContext?: ((a: Error) => void) | object | null,\n context?: object | null\n ): Promise {\n validateArgCount('Query.once', 1, 4, arguments.length);\n validateCallback('Query.once', 'callback', callback, true);\n\n const ret = Query.getCancelAndContextArgs_(\n 'Query.once',\n failureCallbackOrContext,\n context\n );\n const deferred = new Deferred();\n const valueCallback: _UserCallback = (expSnapshot, previousChildName?) => {\n const result = new DataSnapshot(this.database, expSnapshot);\n if (callback) {\n callback.call(ret.context, result, previousChildName);\n }\n deferred.resolve(result);\n };\n valueCallback.userCallback = callback;\n valueCallback.context = ret.context;\n const cancelCallback = (error: Error) => {\n if (ret.cancel) {\n ret.cancel.call(ret.context, error);\n }\n deferred.reject(error);\n };\n\n switch (eventType) {\n case 'value':\n onValue(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_added':\n onChildAdded(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_removed':\n onChildRemoved(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_changed':\n onChildChanged(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_moved':\n onChildMoved(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n default:\n throw new Error(\n errorPrefix('Query.once', 'eventType') +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".'\n );\n }\n\n return deferred.promise;\n }\n\n /**\n * Set a limit and anchor it to the start of the window.\n */\n limitToFirst(limit: number): Query {\n validateArgCount('Query.limitToFirst', 1, 1, arguments.length);\n return new Query(this.database, query(this._delegate, limitToFirst(limit)));\n }\n\n /**\n * Set a limit and anchor it to the end of the window.\n */\n limitToLast(limit: number): Query {\n validateArgCount('Query.limitToLast', 1, 1, arguments.length);\n return new Query(this.database, query(this._delegate, limitToLast(limit)));\n }\n\n /**\n * Given a child path, return a new query ordered by the specified grandchild path.\n */\n orderByChild(path: string): Query {\n validateArgCount('Query.orderByChild', 1, 1, arguments.length);\n return new Query(this.database, query(this._delegate, orderByChild(path)));\n }\n\n /**\n * Return a new query ordered by the KeyIndex\n */\n orderByKey(): Query {\n validateArgCount('Query.orderByKey', 0, 0, arguments.length);\n return new Query(this.database, query(this._delegate, orderByKey()));\n }\n\n /**\n * Return a new query ordered by the PriorityIndex\n */\n orderByPriority(): Query {\n validateArgCount('Query.orderByPriority', 0, 0, arguments.length);\n return new Query(this.database, query(this._delegate, orderByPriority()));\n }\n\n /**\n * Return a new query ordered by the ValueIndex\n */\n orderByValue(): Query {\n validateArgCount('Query.orderByValue', 0, 0, arguments.length);\n return new Query(this.database, query(this._delegate, orderByValue()));\n }\n\n startAt(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.startAt', 0, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, startAt(value, name))\n );\n }\n\n startAfter(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.startAfter', 0, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, startAfter(value, name))\n );\n }\n\n endAt(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.endAt', 0, 2, arguments.length);\n return new Query(this.database, query(this._delegate, endAt(value, name)));\n }\n\n endBefore(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.endBefore', 0, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, endBefore(value, name))\n );\n }\n\n /**\n * Load the selection of children with exactly the specified value, and, optionally,\n * the specified name.\n */\n equalTo(value: number | string | boolean | null, name?: string) {\n validateArgCount('Query.equalTo', 1, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, equalTo(value, name))\n );\n }\n\n /**\n * @returns URL for this location.\n */\n toString(): string {\n validateArgCount('Query.toString', 0, 0, arguments.length);\n return this._delegate.toString();\n }\n\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users.\n toJSON() {\n // An optional spacer argument is unnecessary for a string.\n validateArgCount('Query.toJSON', 0, 1, arguments.length);\n return this._delegate.toJSON();\n }\n\n /**\n * Return true if this query and the provided query are equivalent; otherwise, return false.\n */\n isEqual(other: Query): boolean {\n validateArgCount('Query.isEqual', 1, 1, arguments.length);\n if (!(other instanceof Query)) {\n const error =\n 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.';\n throw new Error(error);\n }\n return this._delegate.isEqual(other._delegate);\n }\n\n /**\n * Helper used by .on and .once to extract the context and or cancel arguments.\n * @param fnName - The function name (on or once)\n *\n */\n private static getCancelAndContextArgs_(\n fnName: string,\n cancelOrContext?: ((a: Error) => void) | object | null,\n context?: object | null\n ): { cancel: ((a: Error) => void) | undefined; context: object | undefined } {\n const ret: {\n cancel: ((a: Error) => void) | null;\n context: object | null;\n } = { cancel: undefined, context: undefined };\n if (cancelOrContext && context) {\n ret.cancel = cancelOrContext as (a: Error) => void;\n validateCallback(fnName, 'cancel', ret.cancel, true);\n\n ret.context = context;\n validateContextObject(fnName, 'context', ret.context, true);\n } else if (cancelOrContext) {\n // we have either a cancel callback or a context.\n if (typeof cancelOrContext === 'object' && cancelOrContext !== null) {\n // it's a context!\n ret.context = cancelOrContext;\n } else if (typeof cancelOrContext === 'function') {\n ret.cancel = cancelOrContext as (a: Error) => void;\n } else {\n throw new Error(\n errorPrefix(fnName, 'cancelOrContext') +\n ' must either be a cancel callback or a context object.'\n );\n }\n }\n return ret;\n }\n\n get ref(): Reference {\n return new Reference(\n this.database,\n new _ReferenceImpl(this._delegate._repo, this._delegate._path)\n );\n }\n}\n\nexport class Reference extends Query implements Compat {\n then: Promise['then'];\n catch: Promise['catch'];\n\n /**\n * Call options:\n * new Reference(Repo, Path) or\n * new Reference(url: string, string|RepoManager)\n *\n * Externally - this is the firebase.database.Reference type.\n */\n constructor(\n readonly database: Database,\n readonly _delegate: ModularReference\n ) {\n super(\n database,\n new _QueryImpl(\n _delegate._repo,\n _delegate._path,\n new _QueryParams(),\n false\n )\n );\n }\n\n /** @returns {?string} */\n getKey(): string | null {\n validateArgCount('Reference.key', 0, 0, arguments.length);\n return this._delegate.key;\n }\n\n child(pathString: string): Reference {\n validateArgCount('Reference.child', 1, 1, arguments.length);\n if (typeof pathString === 'number') {\n pathString = String(pathString);\n }\n return new Reference(this.database, child(this._delegate, pathString));\n }\n\n /** @returns {?Reference} */\n getParent(): Reference | null {\n validateArgCount('Reference.parent', 0, 0, arguments.length);\n const parent = this._delegate.parent;\n return parent ? new Reference(this.database, parent) : null;\n }\n\n /** @returns {!Reference} */\n getRoot(): Reference {\n validateArgCount('Reference.root', 0, 0, arguments.length);\n return new Reference(this.database, this._delegate.root);\n }\n\n set(\n newVal: unknown,\n onComplete?: (error: Error | null) => void\n ): Promise {\n validateArgCount('Reference.set', 1, 2, arguments.length);\n validateCallback('Reference.set', 'onComplete', onComplete, true);\n const result = set(this._delegate, newVal);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n update(\n values: object,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('Reference.update', 1, 2, arguments.length);\n\n if (Array.isArray(values)) {\n const newObjectToMerge: { [k: string]: unknown } = {};\n for (let i = 0; i < values.length; ++i) {\n newObjectToMerge['' + i] = values[i];\n }\n values = newObjectToMerge;\n warn(\n 'Passing an Array to Firebase.update() is deprecated. ' +\n 'Use set() if you want to overwrite the existing data, or ' +\n 'an Object with integer keys if you really do want to ' +\n 'only update some of the children.'\n );\n }\n _validateWritablePath('Reference.update', this._delegate._path);\n validateCallback('Reference.update', 'onComplete', onComplete, true);\n\n const result = update(this._delegate, values);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n setWithPriority(\n newVal: unknown,\n newPriority: string | number | null,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);\n validateCallback(\n 'Reference.setWithPriority',\n 'onComplete',\n onComplete,\n true\n );\n\n const result = setWithPriority(this._delegate, newVal, newPriority);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n remove(onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('Reference.remove', 0, 1, arguments.length);\n validateCallback('Reference.remove', 'onComplete', onComplete, true);\n\n const result = remove(this._delegate);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n transaction(\n transactionUpdate: (currentData: unknown) => unknown,\n onComplete?: (\n error: Error | null,\n committed: boolean,\n dataSnapshot: DataSnapshot | null\n ) => void,\n applyLocally?: boolean\n ): Promise {\n validateArgCount('Reference.transaction', 1, 3, arguments.length);\n validateCallback(\n 'Reference.transaction',\n 'transactionUpdate',\n transactionUpdate,\n false\n );\n validateCallback('Reference.transaction', 'onComplete', onComplete, true);\n validateBoolean(\n 'Reference.transaction',\n 'applyLocally',\n applyLocally,\n true\n );\n\n const result = runTransaction(this._delegate, transactionUpdate, {\n applyLocally\n }).then(\n transactionResult =>\n new TransactionResult(\n transactionResult.committed,\n new DataSnapshot(this.database, transactionResult.snapshot)\n )\n );\n if (onComplete) {\n result.then(\n transactionResult =>\n onComplete(\n null,\n transactionResult.committed,\n transactionResult.snapshot\n ),\n error => onComplete(error, false, null)\n );\n }\n return result;\n }\n\n setPriority(\n priority: string | number | null,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('Reference.setPriority', 1, 2, arguments.length);\n validateCallback('Reference.setPriority', 'onComplete', onComplete, true);\n\n const result = setPriority(this._delegate, priority);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n push(value?: unknown, onComplete?: (a: Error | null) => void): Reference {\n validateArgCount('Reference.push', 0, 2, arguments.length);\n validateCallback('Reference.push', 'onComplete', onComplete, true);\n\n const expPromise = push(this._delegate, value);\n const promise = expPromise.then(\n expRef => new Reference(this.database, expRef)\n );\n\n if (onComplete) {\n promise.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n\n const result = new Reference(this.database, expPromise);\n result.then = promise.then.bind(promise);\n result.catch = promise.catch.bind(promise, undefined);\n return result;\n }\n\n onDisconnect(): OnDisconnect {\n _validateWritablePath('Reference.onDisconnect', this._delegate._path);\n return new OnDisconnect(\n new ModularOnDisconnect(this._delegate._repo, this._delegate._path)\n );\n }\n\n get key(): string | null {\n return this.getKey();\n }\n\n get parent(): Reference | null {\n return this.getParent();\n }\n\n get root(): Reference {\n return this.getRoot();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\n\nimport { FirebaseApp } from '@firebase/app-types';\nimport { FirebaseService } from '@firebase/app-types/private';\nimport {\n forceLongPolling,\n forceWebSockets,\n goOnline,\n connectDatabaseEmulator,\n goOffline,\n ref,\n refFromURL,\n increment,\n serverTimestamp,\n Database as ModularDatabase\n} from '@firebase/database';\nimport {\n validateArgCount,\n Compat,\n EmulatorMockTokenOptions\n} from '@firebase/util';\n\nimport { Reference } from './Reference';\n\n/**\n * Class representing a firebase database.\n */\nexport class Database implements FirebaseService, Compat {\n static readonly ServerValue = {\n TIMESTAMP: serverTimestamp(),\n increment: (delta: number) => increment(delta)\n };\n\n /**\n * The constructor should not be called by users of our public API.\n */\n constructor(readonly _delegate: ModularDatabase, readonly app: FirebaseApp) {}\n\n INTERNAL = {\n delete: () => this._delegate._delete(),\n forceWebSockets,\n forceLongPolling\n };\n\n /**\n * Modify this instance to communicate with the Realtime Database emulator.\n *\n *

Note: This method must be called before performing any other operation.\n *\n * @param host - the emulator host (ex: localhost)\n * @param port - the emulator port (ex: 8080)\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\n */\n useEmulator(\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions;\n } = {}\n ): void {\n connectDatabaseEmulator(this._delegate, host, port, options);\n }\n\n /**\n * Returns a reference to the root or to the path specified in the provided\n * argument.\n *\n * @param path - The relative string path or an existing Reference to a database\n * location.\n * @throws If a Reference is provided, throws if it does not belong to the\n * same project.\n * @returns Firebase reference.\n */\n ref(path?: string): Reference;\n ref(path?: Reference): Reference;\n ref(path?: string | Reference): Reference {\n validateArgCount('database.ref', 0, 1, arguments.length);\n if (path instanceof Reference) {\n const childRef = refFromURL(this._delegate, path.toString());\n return new Reference(this, childRef);\n } else {\n const childRef = ref(this._delegate, path);\n return new Reference(this, childRef);\n }\n }\n\n /**\n * Returns a reference to the root or the path specified in url.\n * We throw a exception if the url is not in the same domain as the\n * current repo.\n * @returns Firebase reference.\n */\n refFromURL(url: string): Reference {\n const apiName = 'database.refFromURL';\n validateArgCount(apiName, 1, 1, arguments.length);\n const childRef = refFromURL(this._delegate, url);\n return new Reference(this, childRef);\n }\n\n // Make individual repo go offline.\n goOffline(): void {\n validateArgCount('database.goOffline', 0, 0, arguments.length);\n return goOffline(this._delegate);\n }\n\n goOnline(): void {\n validateArgCount('database.goOnline', 0, 0, arguments.length);\n return goOnline(this._delegate);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n AppCheckInternalComponentName,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport { FirebaseApp } from '@firebase/app-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n Provider\n} from '@firebase/component';\nimport {\n _repoManagerDatabaseFromApp,\n _setSDKVersion\n} from '@firebase/database';\nimport * as types from '@firebase/database-types';\n\nimport { Database } from './Database';\n\n/**\n * Used by console to create a database based on the app,\n * passed database URL and a custom auth implementation.\n *\n * @param app - A valid FirebaseApp-like object\n * @param url - A valid Firebase databaseURL\n * @param version - custom version e.g. firebase-admin version\n * @param customAuthImpl - custom auth implementation\n */\nexport function initStandalone({\n app,\n url,\n version,\n customAuthImpl,\n customAppCheckImpl,\n namespace,\n nodeAdmin = false\n}: {\n app: FirebaseApp;\n url: string;\n version: string;\n customAuthImpl: FirebaseAuthInternal;\n customAppCheckImpl?: FirebaseAppCheckInternal;\n namespace: T;\n nodeAdmin?: boolean;\n}): {\n instance: types.Database;\n namespace: T;\n} {\n _setSDKVersion(version);\n\n const container = new ComponentContainer('database-standalone');\n /**\n * ComponentContainer('database-standalone') is just a placeholder that doesn't perform\n * any actual function.\n */\n const authProvider = new Provider(\n 'auth-internal',\n container\n );\n authProvider.setComponent(\n new Component('auth-internal', () => customAuthImpl, ComponentType.PRIVATE)\n );\n\n let appCheckProvider: Provider = undefined;\n if (customAppCheckImpl) {\n appCheckProvider = new Provider(\n 'app-check-internal',\n container\n );\n appCheckProvider.setComponent(\n new Component(\n 'app-check-internal',\n () => customAppCheckImpl,\n ComponentType.PRIVATE\n )\n );\n }\n\n return {\n instance: new Database(\n _repoManagerDatabaseFromApp(\n app,\n authProvider,\n appCheckProvider,\n url,\n nodeAdmin\n ),\n app\n ) as types.Database,\n namespace\n };\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app-types';\nimport { FirebaseAuthInternal } from '@firebase/auth-interop-types';\nimport { enableLogging } from '@firebase/database';\nimport { CONSTANTS } from '@firebase/util';\n\nimport { Database } from './api/Database';\nimport * as INTERNAL from './api/internal';\nimport { DataSnapshot, Query, Reference } from './api/Reference';\n\nconst ServerValue = Database.ServerValue;\n\n/**\n * A one off register function which returns a database based on the app and\n * passed database URL. (Used by the Admin SDK)\n *\n * @param app - A valid FirebaseApp-like object\n * @param url - A valid Firebase databaseURL\n * @param version - custom version e.g. firebase-admin version\n * @param nodeAdmin - true if the SDK is being initialized from Firebase Admin.\n */\nexport function initStandalone(\n app: FirebaseApp,\n url: string,\n version: string,\n nodeAdmin = true\n) {\n CONSTANTS.NODE_ADMIN = nodeAdmin;\n return INTERNAL.initStandalone({\n app,\n url,\n version,\n // firebase-admin-node's app.INTERNAL implements FirebaseAuthInternal interface\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n customAuthImpl: (app as any).INTERNAL as FirebaseAuthInternal,\n namespace: {\n Reference,\n Query,\n Database,\n DataSnapshot,\n enableLogging,\n INTERNAL,\n ServerValue\n },\n nodeAdmin\n });\n}\n\n// Types to export for the admin SDK\nexport { Database, Query, Reference, enableLogging, ServerValue };\nexport { OnDisconnect } from '@firebase/database';\nexport { DataSnapshot } from './api/Reference';\n"],"names":["require$$0","Stream","util","require$$1","streams","Headers","Buffer","require$$2","require$$3","require$$4","require$$5","Base","instance","key","HttpParser","Parser","RingBuffer","Functor","Pledge","Cell","Pipeline","Extensions","Frame","Message","crypto","require$$6","Hybi","url","Proxy","require$$7","Client","client","Draft75","Draft76","Server","driver","Event","EventTarget","API","method","WebSocket","_interopDefaultLegacy","logClient","warn","OnDisconnect","DataSnapshot","Database","TransactionResult","Logger","errorPrefixFxn","validateArgCount","validateCallback","onValue","onChildAdded","onChildRemoved","onChildChanged","onChildMoved","errorPrefix","validateContextObject","off","get","Deferred","query","limitToFirst","limitToLast","orderByChild","orderByKey","orderByPriority","orderByValue","startAt","startAfter","endAt","endBefore","equalTo","child","set","update","setWithPriority","remove","runTransaction","setPriority","push","ModularOnDisconnect","forceWebSockets","forceLongPolling","connectDatabaseEmulator","refFromURL","ref","goOffline","goOnline","serverTimestamp","increment","initStandalone","ComponentContainer","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C;AAChE;;;AAGG;IACH,MAAM,YAAY,GAAG,IAAIC,qBAAQ,CAC/B,eAAe,EACf,SAAS,CACV,CAAC;AACF,IAAA,YAAY,CAAC,YAAY,CACvB,IAAIC,sBAAS,CAAC,eAAe,EAAE,MAAM,cAAc,EAAA,SAAA,6BAAwB,CAC5E,CAAC;IAEF,IAAI,gBAAgB,GAA4C,SAAS,CAAC;IAC1E,IAAI,kBAAkB,EAAE;QACtB,gBAAgB,GAAG,IAAID,qBAAQ,CAC7B,oBAAoB,EACpB,SAAS,CACV,CAAC;AACF,QAAA,gBAAgB,CAAC,YAAY,CAC3B,IAAIC,sBAAS,CACX,oBAAoB,EACpB,MAAM,kBAAkB,EAAA,SAAA,6BAEzB,CACF,CAAC;KACH;IAED,OAAO;AACL,QAAA,QAAQ,EAAE,IAAI,QAAQ,CACpB,2BAA2B,CACzB,GAAG,EACH,YAAY,EACZ,gBAAgB,EAChB,GAAG,EACH,SAAS,CACV,EACD,GAAG,CACc;QACnB,SAAS;KACV,CAAC;AACJ;;;;;;;AC/GA;;;;;;;;;;;;;;;AAeG;AAWH,MAAM,WAAW,GAAG,QAAQ,CAAC,YAAY;AAEzC;;;;;;;;AAQG;AACG,SAAU,cAAc,CAC5B,GAAgB,EAChB,GAAW,EACX,OAAe,EACf,SAAS,GAAG,IAAI,EAAA;AAEhB,IAAAC,sBAAS,CAAC,UAAU,GAAG,SAAS,CAAC;IACjC,OAAOC,gBAAuB,CAAC;QAC7B,GAAG;QACH,GAAG;QACH,OAAO;;;QAGP,cAAc,EAAG,GAAW,CAAC,QAAgC;AAC7D,QAAA,SAAS,EAAE;YACT,SAAS;YACT,KAAK;YACL,QAAQ;YACR,YAAY;2BACZC,eAAa;YACb,QAAQ;YACR,WAAW;AACZ,SAAA;QACD,SAAS;AACV,KAAA,CAAC,CAAC;AACL;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/api/Database.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/api/Database.d.ts new file mode 100644 index 0000000..d08f4ee --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/api/Database.d.ts @@ -0,0 +1,74 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app-types'; +import { FirebaseService } from '@firebase/app-types/private'; +import { forceLongPolling, forceWebSockets, Database as ModularDatabase } from '@firebase/database'; +import { Compat, EmulatorMockTokenOptions } from '@firebase/util'; +import { Reference } from './Reference'; +/** + * Class representing a firebase database. + */ +export declare class Database implements FirebaseService, Compat { + readonly _delegate: ModularDatabase; + readonly app: FirebaseApp; + static readonly ServerValue: { + TIMESTAMP: object; + increment: (delta: number) => object; + }; + /** + * The constructor should not be called by users of our public API. + */ + constructor(_delegate: ModularDatabase, app: FirebaseApp); + INTERNAL: { + delete: () => Promise; + forceWebSockets: typeof forceWebSockets; + forceLongPolling: typeof forceLongPolling; + }; + /** + * Modify this instance to communicate with the Realtime Database emulator. + * + *

Note: This method must be called before performing any other operation. + * + * @param host - the emulator host (ex: localhost) + * @param port - the emulator port (ex: 8080) + * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules + */ + useEmulator(host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions; + }): void; + /** + * Returns a reference to the root or to the path specified in the provided + * argument. + * + * @param path - The relative string path or an existing Reference to a database + * location. + * @throws If a Reference is provided, throws if it does not belong to the + * same project. + * @returns Firebase reference. + */ + ref(path?: string): Reference; + ref(path?: Reference): Reference; + /** + * Returns a reference to the root or the path specified in url. + * We throw a exception if the url is not in the same domain as the + * current repo. + * @returns Firebase reference. + */ + refFromURL(url: string): Reference; + goOffline(): void; + goOnline(): void; +} diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/api/Reference.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/api/Reference.d.ts new file mode 100644 index 0000000..f7f20c5 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/api/Reference.d.ts @@ -0,0 +1,207 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DataSnapshot as ModularDataSnapshot, Query as ExpQuery, DatabaseReference as ModularReference } from '@firebase/database'; +import { Compat } from '@firebase/util'; +import { Database } from './Database'; +import { OnDisconnect } from './onDisconnect'; +import { TransactionResult } from './TransactionResult'; +/** + * Class representing a firebase data snapshot. It wraps a SnapshotNode and + * surfaces the public methods (val, forEach, etc.) we want to expose. + */ +export declare class DataSnapshot implements Compat { + readonly _database: Database; + readonly _delegate: ModularDataSnapshot; + constructor(_database: Database, _delegate: ModularDataSnapshot); + /** + * Retrieves the snapshot contents as JSON. Returns null if the snapshot is + * empty. + * + * @returns JSON representation of the DataSnapshot contents, or null if empty. + */ + val(): unknown; + /** + * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting + * the entire node contents. + * @returns JSON representation of the DataSnapshot contents, or null if empty. + */ + exportVal(): unknown; + toJSON(): unknown; + /** + * Returns whether the snapshot contains a non-null value. + * + * @returns Whether the snapshot contains a non-null value, or is empty. + */ + exists(): boolean; + /** + * Returns a DataSnapshot of the specified child node's contents. + * + * @param path - Path to a child. + * @returns DataSnapshot for child node. + */ + child(path: string): DataSnapshot; + /** + * Returns whether the snapshot contains a child at the specified path. + * + * @param path - Path to a child. + * @returns Whether the child exists. + */ + hasChild(path: string): boolean; + /** + * Returns the priority of the object, or null if no priority was set. + * + * @returns The priority. + */ + getPriority(): string | number | null; + /** + * Iterates through child nodes and calls the specified action for each one. + * + * @param action - Callback function to be called + * for each child. + * @returns True if forEach was canceled by action returning true for + * one of the child nodes. + */ + forEach(action: (snapshot: IteratedDataSnapshot) => boolean | void): boolean; + /** + * Returns whether this DataSnapshot has children. + * @returns True if the DataSnapshot contains 1 or more child nodes. + */ + hasChildren(): boolean; + get key(): string; + /** + * Returns the number of children for this DataSnapshot. + * @returns The number of children that this DataSnapshot contains. + */ + numChildren(): number; + /** + * @returns The Firebase reference for the location this snapshot's data came + * from. + */ + getRef(): Reference; + get ref(): Reference; +} +/** + * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined. + */ +export interface IteratedDataSnapshot extends DataSnapshot { + key: string; +} +export interface SnapshotCallback { + (dataSnapshot: DataSnapshot, previousChildName?: string | null): unknown; +} +/** + * A Query represents a filter to be applied to a firebase location. This object purely represents the + * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js. + * + * Since every Firebase reference is a query, Firebase inherits from this object. + */ +export declare class Query implements Compat { + readonly database: Database; + readonly _delegate: ExpQuery; + constructor(database: Database, _delegate: ExpQuery); + on(eventType: string, callback: SnapshotCallback, cancelCallbackOrContext?: ((a: Error) => unknown) | object | null, context?: object | null): SnapshotCallback; + off(eventType?: string, callback?: SnapshotCallback, context?: object | null): void; + /** + * Get the server-value for this query, or return a cached value if not connected. + */ + get(): Promise; + /** + * Attaches a listener, waits for the first event, and then removes the listener + */ + once(eventType: string, callback?: SnapshotCallback, failureCallbackOrContext?: ((a: Error) => void) | object | null, context?: object | null): Promise; + /** + * Set a limit and anchor it to the start of the window. + */ + limitToFirst(limit: number): Query; + /** + * Set a limit and anchor it to the end of the window. + */ + limitToLast(limit: number): Query; + /** + * Given a child path, return a new query ordered by the specified grandchild path. + */ + orderByChild(path: string): Query; + /** + * Return a new query ordered by the KeyIndex + */ + orderByKey(): Query; + /** + * Return a new query ordered by the PriorityIndex + */ + orderByPriority(): Query; + /** + * Return a new query ordered by the ValueIndex + */ + orderByValue(): Query; + startAt(value?: number | string | boolean | null, name?: string | null): Query; + startAfter(value?: number | string | boolean | null, name?: string | null): Query; + endAt(value?: number | string | boolean | null, name?: string | null): Query; + endBefore(value?: number | string | boolean | null, name?: string | null): Query; + /** + * Load the selection of children with exactly the specified value, and, optionally, + * the specified name. + */ + equalTo(value: number | string | boolean | null, name?: string): Query; + /** + * @returns URL for this location. + */ + toString(): string; + toJSON(): string; + /** + * Return true if this query and the provided query are equivalent; otherwise, return false. + */ + isEqual(other: Query): boolean; + /** + * Helper used by .on and .once to extract the context and or cancel arguments. + * @param fnName - The function name (on or once) + * + */ + private static getCancelAndContextArgs_; + get ref(): Reference; +} +export declare class Reference extends Query implements Compat { + readonly database: Database; + readonly _delegate: ModularReference; + then: Promise['then']; + catch: Promise['catch']; + /** + * Call options: + * new Reference(Repo, Path) or + * new Reference(url: string, string|RepoManager) + * + * Externally - this is the firebase.database.Reference type. + */ + constructor(database: Database, _delegate: ModularReference); + /** @returns {?string} */ + getKey(): string | null; + child(pathString: string): Reference; + /** @returns {?Reference} */ + getParent(): Reference | null; + /** @returns {!Reference} */ + getRoot(): Reference; + set(newVal: unknown, onComplete?: (error: Error | null) => void): Promise; + update(values: object, onComplete?: (a: Error | null) => void): Promise; + setWithPriority(newVal: unknown, newPriority: string | number | null, onComplete?: (a: Error | null) => void): Promise; + remove(onComplete?: (a: Error | null) => void): Promise; + transaction(transactionUpdate: (currentData: unknown) => unknown, onComplete?: (error: Error | null, committed: boolean, dataSnapshot: DataSnapshot | null) => void, applyLocally?: boolean): Promise; + setPriority(priority: string | number | null, onComplete?: (a: Error | null) => void): Promise; + push(value?: unknown, onComplete?: (a: Error | null) => void): Reference; + onDisconnect(): OnDisconnect; + get key(): string | null; + get parent(): Reference | null; + get root(): Reference; +} diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/api/TransactionResult.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/api/TransactionResult.d.ts new file mode 100644 index 0000000..b547b76 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/api/TransactionResult.d.ts @@ -0,0 +1,26 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DataSnapshot } from './Reference'; +export declare class TransactionResult { + committed: boolean; + snapshot: DataSnapshot; + /** + * A type for the resolve value of Firebase.transaction. + */ + constructor(committed: boolean, snapshot: DataSnapshot); + toJSON(): object; +} diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/api/internal.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/api/internal.d.ts new file mode 100644 index 0000000..458eb4f --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/api/internal.d.ts @@ -0,0 +1,41 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseAppCheckInternal } from '@firebase/app-check-interop-types'; +import { FirebaseApp } from '@firebase/app-types'; +import { FirebaseAuthInternal } from '@firebase/auth-interop-types'; +import * as types from '@firebase/database-types'; +/** + * Used by console to create a database based on the app, + * passed database URL and a custom auth implementation. + * + * @param app - A valid FirebaseApp-like object + * @param url - A valid Firebase databaseURL + * @param version - custom version e.g. firebase-admin version + * @param customAuthImpl - custom auth implementation + */ +export declare function initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, namespace, nodeAdmin }: { + app: FirebaseApp; + url: string; + version: string; + customAuthImpl: FirebaseAuthInternal; + customAppCheckImpl?: FirebaseAppCheckInternal; + namespace: T; + nodeAdmin?: boolean; +}): { + instance: types.Database; + namespace: T; +}; diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/api/onDisconnect.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/api/onDisconnect.d.ts new file mode 100644 index 0000000..103874e --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/api/onDisconnect.d.ts @@ -0,0 +1,27 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { OnDisconnect as ModularOnDisconnect } from '@firebase/database'; +import { Compat } from '@firebase/util'; +export declare class OnDisconnect implements Compat { + readonly _delegate: ModularOnDisconnect; + constructor(_delegate: ModularOnDisconnect); + cancel(onComplete?: (a: Error | null) => void): Promise; + remove(onComplete?: (a: Error | null) => void): Promise; + set(value: unknown, onComplete?: (a: Error | null) => void): Promise; + setWithPriority(value: unknown, priority: number | string | null, onComplete?: (a: Error | null) => void): Promise; + update(objectToMerge: Record, onComplete?: (a: Error | null) => void): Promise; +} diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/index.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/index.d.ts new file mode 100644 index 0000000..9754251 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/index.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseNamespace } from '@firebase/app-compat'; +import * as types from '@firebase/database-types'; +export declare function registerDatabase(instance: FirebaseNamespace): void; +declare module '@firebase/app-compat' { + interface FirebaseNamespace { + database?: { + (app?: FirebaseApp): types.FirebaseDatabase; + enableLogging: typeof types.enableLogging; + ServerValue: types.ServerValue; + Database: typeof types.FirebaseDatabase; + }; + } + interface FirebaseApp { + database?(databaseURL?: string): types.FirebaseDatabase; + } +} diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/index.node.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/index.node.d.ts new file mode 100644 index 0000000..0e048c8 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/index.node.d.ts @@ -0,0 +1,30 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as types from '@firebase/database-types'; +declare module '@firebase/app-compat' { + interface FirebaseNamespace { + database?: { + (app?: FirebaseApp): types.FirebaseDatabase; + enableLogging: typeof types.enableLogging; + ServerValue: types.ServerValue; + Database: typeof types.FirebaseDatabase; + }; + } + interface FirebaseApp { + database?(): types.FirebaseDatabase; + } +} diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/index.standalone.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/index.standalone.d.ts new file mode 100644 index 0000000..02f3e9b --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/index.standalone.d.ts @@ -0,0 +1,52 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app-types'; +import { enableLogging } from '@firebase/database'; +import { Database } from './api/Database'; +import * as INTERNAL from './api/internal'; +import { DataSnapshot, Query, Reference } from './api/Reference'; +declare const ServerValue: { + TIMESTAMP: object; + increment: (delta: number) => object; +}; +/** + * A one off register function which returns a database based on the app and + * passed database URL. (Used by the Admin SDK) + * + * @param app - A valid FirebaseApp-like object + * @param url - A valid Firebase databaseURL + * @param version - custom version e.g. firebase-admin version + * @param nodeAdmin - true if the SDK is being initialized from Firebase Admin. + */ +export declare function initStandalone(app: FirebaseApp, url: string, version: string, nodeAdmin?: boolean): { + instance: import("@firebase/database-types").Database; + namespace: { + Reference: typeof Reference; + Query: typeof Query; + Database: typeof Database; + DataSnapshot: typeof DataSnapshot; + enableLogging: typeof enableLogging; + INTERNAL: typeof INTERNAL; + ServerValue: { + TIMESTAMP: object; + increment: (delta: number) => object; + }; + }; +}; +export { Database, Query, Reference, enableLogging, ServerValue }; +export { OnDisconnect } from '@firebase/database'; +export { DataSnapshot } from './api/Reference'; diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/util/util.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/util/util.d.ts new file mode 100644 index 0000000..4d5ad77 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/util/util.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const warn: (msg: string) => void; diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/util/validation.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/util/validation.d.ts new file mode 100644 index 0000000..bf47035 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/src/util/validation.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const validateBoolean: (fnName: string, argumentName: string, bool: unknown, optional: boolean) => void; +export declare const validateEventType: (fnName: string, eventType: string, optional: boolean) => void; diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/browser/crawler_support.test.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/browser/crawler_support.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/browser/crawler_support.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/database.test.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/database.test.d.ts new file mode 100644 index 0000000..cdaeff3 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/database.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import '../src/index'; diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/datasnapshot.test.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/datasnapshot.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/datasnapshot.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/helpers/events.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/helpers/events.d.ts new file mode 100644 index 0000000..58d323c --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/helpers/events.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A set of functions to clean up event handlers. + */ +export declare let eventCleanupHandlers: any[]; +/** Clean up outstanding event handlers */ +export declare function eventCleanup(): void; +/** + * Creates a struct which waits for many events. + * @param pathAndEvents - an array of tuples of [Firebase, [event type strings]] + */ +export declare function eventTestHelper(pathAndEvents: any, helperName?: any): { + promise: Promise; + initPromise: Promise; + waiter: () => boolean; + watchesInitializedWaiter: () => boolean; + unregister: () => void; + addExpectedEvents(moreEvents: any): void; +}; diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/helpers/util.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/helpers/util.d.ts new file mode 100644 index 0000000..5f56191 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/helpers/util.d.ts @@ -0,0 +1,42 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import '../../src/index'; +import { Path } from '../../../database/src/core/util/Path'; +import { Query, Reference } from '../../src/api/Reference'; +export declare const TEST_PROJECT: any; +export declare const DATABASE_ADDRESS: any; +export declare const DATABASE_URL: any; +export declare function createTestApp(): import("@firebase/app-compat").FirebaseApp; +/** + * Gets or creates a root node to the test namespace. All calls sharing the + * value of opt_i will share an app context. + */ +export declare function getRootNode(i?: number, ref?: string): any; +/** + * Create multiple refs to the same top level + * push key - each on its own Firebase.Context. + */ +export declare function getRandomNode(numNodes?: any): Reference | Reference[]; +export declare function getQueryValue(query: Query): Promise; +export declare function pause(milliseconds: number): Promise; +export declare function getPath(query: Query): string; +export declare function shuffle(arr: any, randFn?: () => number): void; +export declare function getFreshRepo(path: Path): any; +export declare function getFreshRepoFromReference(ref: any): any; +export declare function getSnap(path: any): any; +export declare function getVal(path: any): any; +export declare function canCreateExtraConnections(): boolean; diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/info.test.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/info.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/info.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/order.test.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/order.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/order.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/order_by.test.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/order_by.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/order_by.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/promise.test.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/promise.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/promise.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/query.test.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/query.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/query.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/servervalues.test.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/servervalues.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/servervalues.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/transaction.test.d.ts b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/transaction.test.d.ts new file mode 100644 index 0000000..cdaeff3 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/database-compat/test/transaction.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import '../src/index'; diff --git a/node_modules/@firebase/database-compat/dist/node-esm/index.js b/node_modules/@firebase/database-compat/dist/node-esm/index.js new file mode 100644 index 0000000..59f9373 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/index.js @@ -0,0 +1,858 @@ +import firebase from '@firebase/app-compat'; +import { ComponentContainer, Provider, Component } from '@firebase/component'; +import { _validatePathString, onChildMoved, onChildChanged, onChildRemoved, onChildAdded, onValue, off, get, query, limitToFirst, limitToLast, orderByChild, orderByKey, orderByPriority, orderByValue, startAt, startAfter, endAt, endBefore, equalTo, _ReferenceImpl, _QueryImpl, _QueryParams, child, set, _validateWritablePath, update, setWithPriority, remove, runTransaction, setPriority, push, OnDisconnect as OnDisconnect$1, forceWebSockets, forceLongPolling, connectDatabaseEmulator, refFromURL, ref, goOffline, goOnline, serverTimestamp, increment, _setSDKVersion, _repoManagerDatabaseFromApp, enableLogging } from '@firebase/database'; +import { errorPrefix, validateArgCount, validateCallback, validateContextObject, Deferred } from '@firebase/util'; +import { Logger } from '@firebase/logger'; + +const name = "@firebase/database-compat"; +const version = "2.1.0"; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const logClient = new Logger('@firebase/database-compat'); +const warn = function (msg) { + const message = 'FIREBASE WARNING: ' + msg; + logClient.warn(message); +}; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const validateBoolean = function (fnName, argumentName, bool, optional) { + if (optional && bool === undefined) { + return; + } + if (typeof bool !== 'boolean') { + throw new Error(errorPrefix(fnName, argumentName) + 'must be a boolean.'); + } +}; +const validateEventType = function (fnName, eventType, optional) { + if (optional && eventType === undefined) { + return; + } + switch (eventType) { + case 'value': + case 'child_added': + case 'child_removed': + case 'child_changed': + case 'child_moved': + break; + default: + throw new Error(errorPrefix(fnName, 'eventType') + + 'must be a valid event type = "value", "child_added", "child_removed", ' + + '"child_changed", or "child_moved".'); + } +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class OnDisconnect { + constructor(_delegate) { + this._delegate = _delegate; + } + cancel(onComplete) { + validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length); + validateCallback('OnDisconnect.cancel', 'onComplete', onComplete, true); + const result = this._delegate.cancel(); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + remove(onComplete) { + validateArgCount('OnDisconnect.remove', 0, 1, arguments.length); + validateCallback('OnDisconnect.remove', 'onComplete', onComplete, true); + const result = this._delegate.remove(); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + set(value, onComplete) { + validateArgCount('OnDisconnect.set', 1, 2, arguments.length); + validateCallback('OnDisconnect.set', 'onComplete', onComplete, true); + const result = this._delegate.set(value); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + setWithPriority(value, priority, onComplete) { + validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length); + validateCallback('OnDisconnect.setWithPriority', 'onComplete', onComplete, true); + const result = this._delegate.setWithPriority(value, priority); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + update(objectToMerge, onComplete) { + validateArgCount('OnDisconnect.update', 1, 2, arguments.length); + if (Array.isArray(objectToMerge)) { + const newObjectToMerge = {}; + for (let i = 0; i < objectToMerge.length; ++i) { + newObjectToMerge['' + i] = objectToMerge[i]; + } + objectToMerge = newObjectToMerge; + warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' + + 'existing data, or an Object with integer keys if you really do want to only update some of the children.'); + } + validateCallback('OnDisconnect.update', 'onComplete', onComplete, true); + const result = this._delegate.update(objectToMerge); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class TransactionResult { + /** + * A type for the resolve value of Firebase.transaction. + */ + constructor(committed, snapshot) { + this.committed = committed; + this.snapshot = snapshot; + } + // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary + // for end-users + toJSON() { + validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length); + return { committed: this.committed, snapshot: this.snapshot.toJSON() }; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Class representing a firebase data snapshot. It wraps a SnapshotNode and + * surfaces the public methods (val, forEach, etc.) we want to expose. + */ +class DataSnapshot { + constructor(_database, _delegate) { + this._database = _database; + this._delegate = _delegate; + } + /** + * Retrieves the snapshot contents as JSON. Returns null if the snapshot is + * empty. + * + * @returns JSON representation of the DataSnapshot contents, or null if empty. + */ + val() { + validateArgCount('DataSnapshot.val', 0, 0, arguments.length); + return this._delegate.val(); + } + /** + * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting + * the entire node contents. + * @returns JSON representation of the DataSnapshot contents, or null if empty. + */ + exportVal() { + validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length); + return this._delegate.exportVal(); + } + // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary + // for end-users + toJSON() { + // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content + validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length); + return this._delegate.toJSON(); + } + /** + * Returns whether the snapshot contains a non-null value. + * + * @returns Whether the snapshot contains a non-null value, or is empty. + */ + exists() { + validateArgCount('DataSnapshot.exists', 0, 0, arguments.length); + return this._delegate.exists(); + } + /** + * Returns a DataSnapshot of the specified child node's contents. + * + * @param path - Path to a child. + * @returns DataSnapshot for child node. + */ + child(path) { + validateArgCount('DataSnapshot.child', 0, 1, arguments.length); + // Ensure the childPath is a string (can be a number) + path = String(path); + _validatePathString('DataSnapshot.child', 'path', path, false); + return new DataSnapshot(this._database, this._delegate.child(path)); + } + /** + * Returns whether the snapshot contains a child at the specified path. + * + * @param path - Path to a child. + * @returns Whether the child exists. + */ + hasChild(path) { + validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length); + _validatePathString('DataSnapshot.hasChild', 'path', path, false); + return this._delegate.hasChild(path); + } + /** + * Returns the priority of the object, or null if no priority was set. + * + * @returns The priority. + */ + getPriority() { + validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length); + return this._delegate.priority; + } + /** + * Iterates through child nodes and calls the specified action for each one. + * + * @param action - Callback function to be called + * for each child. + * @returns True if forEach was canceled by action returning true for + * one of the child nodes. + */ + forEach(action) { + validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length); + validateCallback('DataSnapshot.forEach', 'action', action, false); + return this._delegate.forEach(expDataSnapshot => action(new DataSnapshot(this._database, expDataSnapshot))); + } + /** + * Returns whether this DataSnapshot has children. + * @returns True if the DataSnapshot contains 1 or more child nodes. + */ + hasChildren() { + validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length); + return this._delegate.hasChildren(); + } + get key() { + return this._delegate.key; + } + /** + * Returns the number of children for this DataSnapshot. + * @returns The number of children that this DataSnapshot contains. + */ + numChildren() { + validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length); + return this._delegate.size; + } + /** + * @returns The Firebase reference for the location this snapshot's data came + * from. + */ + getRef() { + validateArgCount('DataSnapshot.ref', 0, 0, arguments.length); + return new Reference(this._database, this._delegate.ref); + } + get ref() { + return this.getRef(); + } +} +/** + * A Query represents a filter to be applied to a firebase location. This object purely represents the + * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js. + * + * Since every Firebase reference is a query, Firebase inherits from this object. + */ +class Query { + constructor(database, _delegate) { + this.database = database; + this._delegate = _delegate; + } + on(eventType, callback, cancelCallbackOrContext, context) { + validateArgCount('Query.on', 2, 4, arguments.length); + validateCallback('Query.on', 'callback', callback, false); + const ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context); + const valueCallback = (expSnapshot, previousChildName) => { + callback.call(ret.context, new DataSnapshot(this.database, expSnapshot), previousChildName); + }; + valueCallback.userCallback = callback; + valueCallback.context = ret.context; + const cancelCallback = ret.cancel?.bind(ret.context); + switch (eventType) { + case 'value': + onValue(this._delegate, valueCallback, cancelCallback); + return callback; + case 'child_added': + onChildAdded(this._delegate, valueCallback, cancelCallback); + return callback; + case 'child_removed': + onChildRemoved(this._delegate, valueCallback, cancelCallback); + return callback; + case 'child_changed': + onChildChanged(this._delegate, valueCallback, cancelCallback); + return callback; + case 'child_moved': + onChildMoved(this._delegate, valueCallback, cancelCallback); + return callback; + default: + throw new Error(errorPrefix('Query.on', 'eventType') + + 'must be a valid event type = "value", "child_added", "child_removed", ' + + '"child_changed", or "child_moved".'); + } + } + off(eventType, callback, context) { + validateArgCount('Query.off', 0, 3, arguments.length); + validateEventType('Query.off', eventType, true); + validateCallback('Query.off', 'callback', callback, true); + validateContextObject('Query.off', 'context', context, true); + if (callback) { + const valueCallback = () => { }; + valueCallback.userCallback = callback; + valueCallback.context = context; + off(this._delegate, eventType, valueCallback); + } + else { + off(this._delegate, eventType); + } + } + /** + * Get the server-value for this query, or return a cached value if not connected. + */ + get() { + return get(this._delegate).then(expSnapshot => { + return new DataSnapshot(this.database, expSnapshot); + }); + } + /** + * Attaches a listener, waits for the first event, and then removes the listener + */ + once(eventType, callback, failureCallbackOrContext, context) { + validateArgCount('Query.once', 1, 4, arguments.length); + validateCallback('Query.once', 'callback', callback, true); + const ret = Query.getCancelAndContextArgs_('Query.once', failureCallbackOrContext, context); + const deferred = new Deferred(); + const valueCallback = (expSnapshot, previousChildName) => { + const result = new DataSnapshot(this.database, expSnapshot); + if (callback) { + callback.call(ret.context, result, previousChildName); + } + deferred.resolve(result); + }; + valueCallback.userCallback = callback; + valueCallback.context = ret.context; + const cancelCallback = (error) => { + if (ret.cancel) { + ret.cancel.call(ret.context, error); + } + deferred.reject(error); + }; + switch (eventType) { + case 'value': + onValue(this._delegate, valueCallback, cancelCallback, { + onlyOnce: true + }); + break; + case 'child_added': + onChildAdded(this._delegate, valueCallback, cancelCallback, { + onlyOnce: true + }); + break; + case 'child_removed': + onChildRemoved(this._delegate, valueCallback, cancelCallback, { + onlyOnce: true + }); + break; + case 'child_changed': + onChildChanged(this._delegate, valueCallback, cancelCallback, { + onlyOnce: true + }); + break; + case 'child_moved': + onChildMoved(this._delegate, valueCallback, cancelCallback, { + onlyOnce: true + }); + break; + default: + throw new Error(errorPrefix('Query.once', 'eventType') + + 'must be a valid event type = "value", "child_added", "child_removed", ' + + '"child_changed", or "child_moved".'); + } + return deferred.promise; + } + /** + * Set a limit and anchor it to the start of the window. + */ + limitToFirst(limit) { + validateArgCount('Query.limitToFirst', 1, 1, arguments.length); + return new Query(this.database, query(this._delegate, limitToFirst(limit))); + } + /** + * Set a limit and anchor it to the end of the window. + */ + limitToLast(limit) { + validateArgCount('Query.limitToLast', 1, 1, arguments.length); + return new Query(this.database, query(this._delegate, limitToLast(limit))); + } + /** + * Given a child path, return a new query ordered by the specified grandchild path. + */ + orderByChild(path) { + validateArgCount('Query.orderByChild', 1, 1, arguments.length); + return new Query(this.database, query(this._delegate, orderByChild(path))); + } + /** + * Return a new query ordered by the KeyIndex + */ + orderByKey() { + validateArgCount('Query.orderByKey', 0, 0, arguments.length); + return new Query(this.database, query(this._delegate, orderByKey())); + } + /** + * Return a new query ordered by the PriorityIndex + */ + orderByPriority() { + validateArgCount('Query.orderByPriority', 0, 0, arguments.length); + return new Query(this.database, query(this._delegate, orderByPriority())); + } + /** + * Return a new query ordered by the ValueIndex + */ + orderByValue() { + validateArgCount('Query.orderByValue', 0, 0, arguments.length); + return new Query(this.database, query(this._delegate, orderByValue())); + } + startAt(value = null, name) { + validateArgCount('Query.startAt', 0, 2, arguments.length); + return new Query(this.database, query(this._delegate, startAt(value, name))); + } + startAfter(value = null, name) { + validateArgCount('Query.startAfter', 0, 2, arguments.length); + return new Query(this.database, query(this._delegate, startAfter(value, name))); + } + endAt(value = null, name) { + validateArgCount('Query.endAt', 0, 2, arguments.length); + return new Query(this.database, query(this._delegate, endAt(value, name))); + } + endBefore(value = null, name) { + validateArgCount('Query.endBefore', 0, 2, arguments.length); + return new Query(this.database, query(this._delegate, endBefore(value, name))); + } + /** + * Load the selection of children with exactly the specified value, and, optionally, + * the specified name. + */ + equalTo(value, name) { + validateArgCount('Query.equalTo', 1, 2, arguments.length); + return new Query(this.database, query(this._delegate, equalTo(value, name))); + } + /** + * @returns URL for this location. + */ + toString() { + validateArgCount('Query.toString', 0, 0, arguments.length); + return this._delegate.toString(); + } + // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary + // for end-users. + toJSON() { + // An optional spacer argument is unnecessary for a string. + validateArgCount('Query.toJSON', 0, 1, arguments.length); + return this._delegate.toJSON(); + } + /** + * Return true if this query and the provided query are equivalent; otherwise, return false. + */ + isEqual(other) { + validateArgCount('Query.isEqual', 1, 1, arguments.length); + if (!(other instanceof Query)) { + const error = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.'; + throw new Error(error); + } + return this._delegate.isEqual(other._delegate); + } + /** + * Helper used by .on and .once to extract the context and or cancel arguments. + * @param fnName - The function name (on or once) + * + */ + static getCancelAndContextArgs_(fnName, cancelOrContext, context) { + const ret = { cancel: undefined, context: undefined }; + if (cancelOrContext && context) { + ret.cancel = cancelOrContext; + validateCallback(fnName, 'cancel', ret.cancel, true); + ret.context = context; + validateContextObject(fnName, 'context', ret.context, true); + } + else if (cancelOrContext) { + // we have either a cancel callback or a context. + if (typeof cancelOrContext === 'object' && cancelOrContext !== null) { + // it's a context! + ret.context = cancelOrContext; + } + else if (typeof cancelOrContext === 'function') { + ret.cancel = cancelOrContext; + } + else { + throw new Error(errorPrefix(fnName, 'cancelOrContext') + + ' must either be a cancel callback or a context object.'); + } + } + return ret; + } + get ref() { + return new Reference(this.database, new _ReferenceImpl(this._delegate._repo, this._delegate._path)); + } +} +class Reference extends Query { + /** + * Call options: + * new Reference(Repo, Path) or + * new Reference(url: string, string|RepoManager) + * + * Externally - this is the firebase.database.Reference type. + */ + constructor(database, _delegate) { + super(database, new _QueryImpl(_delegate._repo, _delegate._path, new _QueryParams(), false)); + this.database = database; + this._delegate = _delegate; + } + /** @returns {?string} */ + getKey() { + validateArgCount('Reference.key', 0, 0, arguments.length); + return this._delegate.key; + } + child(pathString) { + validateArgCount('Reference.child', 1, 1, arguments.length); + if (typeof pathString === 'number') { + pathString = String(pathString); + } + return new Reference(this.database, child(this._delegate, pathString)); + } + /** @returns {?Reference} */ + getParent() { + validateArgCount('Reference.parent', 0, 0, arguments.length); + const parent = this._delegate.parent; + return parent ? new Reference(this.database, parent) : null; + } + /** @returns {!Reference} */ + getRoot() { + validateArgCount('Reference.root', 0, 0, arguments.length); + return new Reference(this.database, this._delegate.root); + } + set(newVal, onComplete) { + validateArgCount('Reference.set', 1, 2, arguments.length); + validateCallback('Reference.set', 'onComplete', onComplete, true); + const result = set(this._delegate, newVal); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + update(values, onComplete) { + validateArgCount('Reference.update', 1, 2, arguments.length); + if (Array.isArray(values)) { + const newObjectToMerge = {}; + for (let i = 0; i < values.length; ++i) { + newObjectToMerge['' + i] = values[i]; + } + values = newObjectToMerge; + warn('Passing an Array to Firebase.update() is deprecated. ' + + 'Use set() if you want to overwrite the existing data, or ' + + 'an Object with integer keys if you really do want to ' + + 'only update some of the children.'); + } + _validateWritablePath('Reference.update', this._delegate._path); + validateCallback('Reference.update', 'onComplete', onComplete, true); + const result = update(this._delegate, values); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + setWithPriority(newVal, newPriority, onComplete) { + validateArgCount('Reference.setWithPriority', 2, 3, arguments.length); + validateCallback('Reference.setWithPriority', 'onComplete', onComplete, true); + const result = setWithPriority(this._delegate, newVal, newPriority); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + remove(onComplete) { + validateArgCount('Reference.remove', 0, 1, arguments.length); + validateCallback('Reference.remove', 'onComplete', onComplete, true); + const result = remove(this._delegate); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + transaction(transactionUpdate, onComplete, applyLocally) { + validateArgCount('Reference.transaction', 1, 3, arguments.length); + validateCallback('Reference.transaction', 'transactionUpdate', transactionUpdate, false); + validateCallback('Reference.transaction', 'onComplete', onComplete, true); + validateBoolean('Reference.transaction', 'applyLocally', applyLocally, true); + const result = runTransaction(this._delegate, transactionUpdate, { + applyLocally + }).then(transactionResult => new TransactionResult(transactionResult.committed, new DataSnapshot(this.database, transactionResult.snapshot))); + if (onComplete) { + result.then(transactionResult => onComplete(null, transactionResult.committed, transactionResult.snapshot), error => onComplete(error, false, null)); + } + return result; + } + setPriority(priority, onComplete) { + validateArgCount('Reference.setPriority', 1, 2, arguments.length); + validateCallback('Reference.setPriority', 'onComplete', onComplete, true); + const result = setPriority(this._delegate, priority); + if (onComplete) { + result.then(() => onComplete(null), error => onComplete(error)); + } + return result; + } + push(value, onComplete) { + validateArgCount('Reference.push', 0, 2, arguments.length); + validateCallback('Reference.push', 'onComplete', onComplete, true); + const expPromise = push(this._delegate, value); + const promise = expPromise.then(expRef => new Reference(this.database, expRef)); + if (onComplete) { + promise.then(() => onComplete(null), error => onComplete(error)); + } + const result = new Reference(this.database, expPromise); + result.then = promise.then.bind(promise); + result.catch = promise.catch.bind(promise, undefined); + return result; + } + onDisconnect() { + _validateWritablePath('Reference.onDisconnect', this._delegate._path); + return new OnDisconnect(new OnDisconnect$1(this._delegate._repo, this._delegate._path)); + } + get key() { + return this.getKey(); + } + get parent() { + return this.getParent(); + } + get root() { + return this.getRoot(); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Class representing a firebase database. + */ +class Database { + /** + * The constructor should not be called by users of our public API. + */ + constructor(_delegate, app) { + this._delegate = _delegate; + this.app = app; + this.INTERNAL = { + delete: () => this._delegate._delete(), + forceWebSockets, + forceLongPolling + }; + } + /** + * Modify this instance to communicate with the Realtime Database emulator. + * + *

Note: This method must be called before performing any other operation. + * + * @param host - the emulator host (ex: localhost) + * @param port - the emulator port (ex: 8080) + * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules + */ + useEmulator(host, port, options = {}) { + connectDatabaseEmulator(this._delegate, host, port, options); + } + ref(path) { + validateArgCount('database.ref', 0, 1, arguments.length); + if (path instanceof Reference) { + const childRef = refFromURL(this._delegate, path.toString()); + return new Reference(this, childRef); + } + else { + const childRef = ref(this._delegate, path); + return new Reference(this, childRef); + } + } + /** + * Returns a reference to the root or the path specified in url. + * We throw a exception if the url is not in the same domain as the + * current repo. + * @returns Firebase reference. + */ + refFromURL(url) { + const apiName = 'database.refFromURL'; + validateArgCount(apiName, 1, 1, arguments.length); + const childRef = refFromURL(this._delegate, url); + return new Reference(this, childRef); + } + // Make individual repo go offline. + goOffline() { + validateArgCount('database.goOffline', 0, 0, arguments.length); + return goOffline(this._delegate); + } + goOnline() { + validateArgCount('database.goOnline', 0, 0, arguments.length); + return goOnline(this._delegate); + } +} +Database.ServerValue = { + TIMESTAMP: serverTimestamp(), + increment: (delta) => increment(delta) +}; + +/** + * Used by console to create a database based on the app, + * passed database URL and a custom auth implementation. + * + * @param app - A valid FirebaseApp-like object + * @param url - A valid Firebase databaseURL + * @param version - custom version e.g. firebase-admin version + * @param customAuthImpl - custom auth implementation + */ +function initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, namespace, nodeAdmin = false }) { + _setSDKVersion(version); + const container = new ComponentContainer('database-standalone'); + /** + * ComponentContainer('database-standalone') is just a placeholder that doesn't perform + * any actual function. + */ + const authProvider = new Provider('auth-internal', container); + authProvider.setComponent(new Component('auth-internal', () => customAuthImpl, "PRIVATE" /* ComponentType.PRIVATE */)); + let appCheckProvider = undefined; + if (customAppCheckImpl) { + appCheckProvider = new Provider('app-check-internal', container); + appCheckProvider.setComponent(new Component('app-check-internal', () => customAppCheckImpl, "PRIVATE" /* ComponentType.PRIVATE */)); + } + return { + instance: new Database(_repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin), app), + namespace + }; +} + +var INTERNAL = /*#__PURE__*/Object.freeze({ + __proto__: null, + initStandalone: initStandalone +}); + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const ServerValue = Database.ServerValue; +function registerDatabase(instance) { + // Register the Database Service with the 'firebase' namespace. + instance.INTERNAL.registerComponent(new Component('database-compat', (container, { instanceIdentifier: url }) => { + /* Dependencies */ + // getImmediate for FirebaseApp will always succeed + const app = container.getProvider('app-compat').getImmediate(); + const databaseExp = container + .getProvider('database') + .getImmediate({ identifier: url }); + return new Database(databaseExp, app); + }, "PUBLIC" /* ComponentType.PUBLIC */) + .setServiceProps( + // firebase.database namespace properties + { + Reference, + Query, + Database, + DataSnapshot, + enableLogging, + INTERNAL, + ServerValue + }) + .setMultipleInstances(true)); + instance.registerVersion(name, version, 'node'); +} +registerDatabase(firebase); +//# sourceMappingURL=index.js.map diff --git a/node_modules/@firebase/database-compat/dist/node-esm/index.js.map b/node_modules/@firebase/database-compat/dist/node-esm/index.js.map new file mode 100644 index 0000000..7c961e7 --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../../src/util/util.ts","../../src/util/validation.ts","../../src/api/onDisconnect.ts","../../src/api/TransactionResult.ts","../../src/api/Reference.ts","../../src/api/Database.ts","../../src/api/internal.ts","../../src/index.node.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nconst logClient = new Logger('@firebase/database-compat');\n\nexport const warn = function (msg: string) {\n const message = 'FIREBASE WARNING: ' + msg;\n logClient.warn(message);\n};\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { errorPrefix as errorPrefixFxn } from '@firebase/util';\n\nexport const validateBoolean = function (\n fnName: string,\n argumentName: string,\n bool: unknown,\n optional: boolean\n) {\n if (optional && bool === undefined) {\n return;\n }\n if (typeof bool !== 'boolean') {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) + 'must be a boolean.'\n );\n }\n};\n\nexport const validateEventType = function (\n fnName: string,\n eventType: string,\n optional: boolean\n) {\n if (optional && eventType === undefined) {\n return;\n }\n\n switch (eventType) {\n case 'value':\n case 'child_added':\n case 'child_removed':\n case 'child_changed':\n case 'child_moved':\n break;\n default:\n throw new Error(\n errorPrefixFxn(fnName, 'eventType') +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".'\n );\n }\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { OnDisconnect as ModularOnDisconnect } from '@firebase/database';\nimport { validateArgCount, validateCallback, Compat } from '@firebase/util';\n\nimport { warn } from '../util/util';\nexport class OnDisconnect implements Compat {\n constructor(readonly _delegate: ModularOnDisconnect) {}\n\n cancel(onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);\n validateCallback('OnDisconnect.cancel', 'onComplete', onComplete, true);\n const result = this._delegate.cancel();\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n remove(onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);\n validateCallback('OnDisconnect.remove', 'onComplete', onComplete, true);\n const result = this._delegate.remove();\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n set(value: unknown, onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('OnDisconnect.set', 1, 2, arguments.length);\n validateCallback('OnDisconnect.set', 'onComplete', onComplete, true);\n const result = this._delegate.set(value);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n setWithPriority(\n value: unknown,\n priority: number | string | null,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length);\n validateCallback(\n 'OnDisconnect.setWithPriority',\n 'onComplete',\n onComplete,\n true\n );\n const result = this._delegate.setWithPriority(value, priority);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n update(\n objectToMerge: Record,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('OnDisconnect.update', 1, 2, arguments.length);\n if (Array.isArray(objectToMerge)) {\n const newObjectToMerge: { [k: string]: unknown } = {};\n for (let i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n warn(\n 'Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' +\n 'existing data, or an Object with integer keys if you really do want to only update some of the children.'\n );\n }\n validateCallback('OnDisconnect.update', 'onComplete', onComplete, true);\n const result = this._delegate.update(objectToMerge);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { validateArgCount } from '@firebase/util';\n\nimport { DataSnapshot } from './Reference';\n\nexport class TransactionResult {\n /**\n * A type for the resolve value of Firebase.transaction.\n */\n constructor(public committed: boolean, public snapshot: DataSnapshot) {}\n\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n toJSON(): object {\n validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n OnDisconnect as ModularOnDisconnect,\n off,\n onChildAdded,\n onChildChanged,\n onChildMoved,\n onChildRemoved,\n onValue,\n EventType,\n limitToFirst,\n query,\n limitToLast,\n orderByChild,\n orderByKey,\n orderByValue,\n orderByPriority,\n startAt,\n startAfter,\n endAt,\n endBefore,\n equalTo,\n get,\n set,\n update,\n setWithPriority,\n remove,\n setPriority,\n push,\n runTransaction,\n child,\n DataSnapshot as ModularDataSnapshot,\n Query as ExpQuery,\n DatabaseReference as ModularReference,\n _QueryImpl,\n _ReferenceImpl,\n _validatePathString,\n _validateWritablePath,\n _UserCallback,\n _QueryParams\n} from '@firebase/database';\nimport {\n Compat,\n Deferred,\n errorPrefix,\n validateArgCount,\n validateCallback,\n validateContextObject\n} from '@firebase/util';\n\nimport { warn } from '../util/util';\nimport { validateBoolean, validateEventType } from '../util/validation';\n\nimport { Database } from './Database';\nimport { OnDisconnect } from './onDisconnect';\nimport { TransactionResult } from './TransactionResult';\n\n/**\n * Class representing a firebase data snapshot. It wraps a SnapshotNode and\n * surfaces the public methods (val, forEach, etc.) we want to expose.\n */\nexport class DataSnapshot implements Compat {\n constructor(\n readonly _database: Database,\n readonly _delegate: ModularDataSnapshot\n ) {}\n\n /**\n * Retrieves the snapshot contents as JSON. Returns null if the snapshot is\n * empty.\n *\n * @returns JSON representation of the DataSnapshot contents, or null if empty.\n */\n val(): unknown {\n validateArgCount('DataSnapshot.val', 0, 0, arguments.length);\n return this._delegate.val();\n }\n\n /**\n * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting\n * the entire node contents.\n * @returns JSON representation of the DataSnapshot contents, or null if empty.\n */\n exportVal(): unknown {\n validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length);\n return this._delegate.exportVal();\n }\n\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n toJSON(): unknown {\n // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content\n validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length);\n return this._delegate.toJSON();\n }\n\n /**\n * Returns whether the snapshot contains a non-null value.\n *\n * @returns Whether the snapshot contains a non-null value, or is empty.\n */\n exists(): boolean {\n validateArgCount('DataSnapshot.exists', 0, 0, arguments.length);\n return this._delegate.exists();\n }\n\n /**\n * Returns a DataSnapshot of the specified child node's contents.\n *\n * @param path - Path to a child.\n * @returns DataSnapshot for child node.\n */\n child(path: string): DataSnapshot {\n validateArgCount('DataSnapshot.child', 0, 1, arguments.length);\n // Ensure the childPath is a string (can be a number)\n path = String(path);\n _validatePathString('DataSnapshot.child', 'path', path, false);\n return new DataSnapshot(this._database, this._delegate.child(path));\n }\n\n /**\n * Returns whether the snapshot contains a child at the specified path.\n *\n * @param path - Path to a child.\n * @returns Whether the child exists.\n */\n hasChild(path: string): boolean {\n validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);\n _validatePathString('DataSnapshot.hasChild', 'path', path, false);\n return this._delegate.hasChild(path);\n }\n\n /**\n * Returns the priority of the object, or null if no priority was set.\n *\n * @returns The priority.\n */\n getPriority(): string | number | null {\n validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);\n return this._delegate.priority;\n }\n\n /**\n * Iterates through child nodes and calls the specified action for each one.\n *\n * @param action - Callback function to be called\n * for each child.\n * @returns True if forEach was canceled by action returning true for\n * one of the child nodes.\n */\n forEach(action: (snapshot: IteratedDataSnapshot) => boolean | void): boolean {\n validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);\n validateCallback('DataSnapshot.forEach', 'action', action, false);\n return this._delegate.forEach(expDataSnapshot =>\n action(new DataSnapshot(this._database, expDataSnapshot))\n );\n }\n\n /**\n * Returns whether this DataSnapshot has children.\n * @returns True if the DataSnapshot contains 1 or more child nodes.\n */\n hasChildren(): boolean {\n validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);\n return this._delegate.hasChildren();\n }\n\n get key() {\n return this._delegate.key;\n }\n\n /**\n * Returns the number of children for this DataSnapshot.\n * @returns The number of children that this DataSnapshot contains.\n */\n numChildren(): number {\n validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);\n return this._delegate.size;\n }\n\n /**\n * @returns The Firebase reference for the location this snapshot's data came\n * from.\n */\n getRef(): Reference {\n validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);\n return new Reference(this._database, this._delegate.ref);\n }\n\n get ref(): Reference {\n return this.getRef();\n }\n}\n\n/**\n * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined.\n */\nexport interface IteratedDataSnapshot extends DataSnapshot {\n key: string; // key of the location of this snapshot.\n}\n\nexport interface SnapshotCallback {\n (dataSnapshot: DataSnapshot, previousChildName?: string | null): unknown;\n}\n\n/**\n * A Query represents a filter to be applied to a firebase location. This object purely represents the\n * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js.\n *\n * Since every Firebase reference is a query, Firebase inherits from this object.\n */\nexport class Query implements Compat {\n constructor(readonly database: Database, readonly _delegate: ExpQuery) {}\n\n on(\n eventType: string,\n callback: SnapshotCallback,\n cancelCallbackOrContext?: ((a: Error) => unknown) | object | null,\n context?: object | null\n ): SnapshotCallback {\n validateArgCount('Query.on', 2, 4, arguments.length);\n validateCallback('Query.on', 'callback', callback, false);\n\n const ret = Query.getCancelAndContextArgs_(\n 'Query.on',\n cancelCallbackOrContext,\n context\n );\n const valueCallback = (expSnapshot, previousChildName?) => {\n callback.call(\n ret.context,\n new DataSnapshot(this.database, expSnapshot),\n previousChildName\n );\n };\n valueCallback.userCallback = callback;\n valueCallback.context = ret.context;\n const cancelCallback = ret.cancel?.bind(ret.context);\n\n switch (eventType) {\n case 'value':\n onValue(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_added':\n onChildAdded(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_removed':\n onChildRemoved(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_changed':\n onChildChanged(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_moved':\n onChildMoved(this._delegate, valueCallback, cancelCallback);\n return callback;\n default:\n throw new Error(\n errorPrefix('Query.on', 'eventType') +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".'\n );\n }\n }\n\n off(\n eventType?: string,\n callback?: SnapshotCallback,\n context?: object | null\n ): void {\n validateArgCount('Query.off', 0, 3, arguments.length);\n validateEventType('Query.off', eventType, true);\n validateCallback('Query.off', 'callback', callback, true);\n validateContextObject('Query.off', 'context', context, true);\n if (callback) {\n const valueCallback: _UserCallback = () => {};\n valueCallback.userCallback = callback;\n valueCallback.context = context;\n off(this._delegate, eventType as EventType, valueCallback);\n } else {\n off(this._delegate, eventType as EventType | undefined);\n }\n }\n\n /**\n * Get the server-value for this query, or return a cached value if not connected.\n */\n get(): Promise {\n return get(this._delegate).then(expSnapshot => {\n return new DataSnapshot(this.database, expSnapshot);\n });\n }\n\n /**\n * Attaches a listener, waits for the first event, and then removes the listener\n */\n once(\n eventType: string,\n callback?: SnapshotCallback,\n failureCallbackOrContext?: ((a: Error) => void) | object | null,\n context?: object | null\n ): Promise {\n validateArgCount('Query.once', 1, 4, arguments.length);\n validateCallback('Query.once', 'callback', callback, true);\n\n const ret = Query.getCancelAndContextArgs_(\n 'Query.once',\n failureCallbackOrContext,\n context\n );\n const deferred = new Deferred();\n const valueCallback: _UserCallback = (expSnapshot, previousChildName?) => {\n const result = new DataSnapshot(this.database, expSnapshot);\n if (callback) {\n callback.call(ret.context, result, previousChildName);\n }\n deferred.resolve(result);\n };\n valueCallback.userCallback = callback;\n valueCallback.context = ret.context;\n const cancelCallback = (error: Error) => {\n if (ret.cancel) {\n ret.cancel.call(ret.context, error);\n }\n deferred.reject(error);\n };\n\n switch (eventType) {\n case 'value':\n onValue(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_added':\n onChildAdded(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_removed':\n onChildRemoved(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_changed':\n onChildChanged(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_moved':\n onChildMoved(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n default:\n throw new Error(\n errorPrefix('Query.once', 'eventType') +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".'\n );\n }\n\n return deferred.promise;\n }\n\n /**\n * Set a limit and anchor it to the start of the window.\n */\n limitToFirst(limit: number): Query {\n validateArgCount('Query.limitToFirst', 1, 1, arguments.length);\n return new Query(this.database, query(this._delegate, limitToFirst(limit)));\n }\n\n /**\n * Set a limit and anchor it to the end of the window.\n */\n limitToLast(limit: number): Query {\n validateArgCount('Query.limitToLast', 1, 1, arguments.length);\n return new Query(this.database, query(this._delegate, limitToLast(limit)));\n }\n\n /**\n * Given a child path, return a new query ordered by the specified grandchild path.\n */\n orderByChild(path: string): Query {\n validateArgCount('Query.orderByChild', 1, 1, arguments.length);\n return new Query(this.database, query(this._delegate, orderByChild(path)));\n }\n\n /**\n * Return a new query ordered by the KeyIndex\n */\n orderByKey(): Query {\n validateArgCount('Query.orderByKey', 0, 0, arguments.length);\n return new Query(this.database, query(this._delegate, orderByKey()));\n }\n\n /**\n * Return a new query ordered by the PriorityIndex\n */\n orderByPriority(): Query {\n validateArgCount('Query.orderByPriority', 0, 0, arguments.length);\n return new Query(this.database, query(this._delegate, orderByPriority()));\n }\n\n /**\n * Return a new query ordered by the ValueIndex\n */\n orderByValue(): Query {\n validateArgCount('Query.orderByValue', 0, 0, arguments.length);\n return new Query(this.database, query(this._delegate, orderByValue()));\n }\n\n startAt(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.startAt', 0, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, startAt(value, name))\n );\n }\n\n startAfter(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.startAfter', 0, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, startAfter(value, name))\n );\n }\n\n endAt(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.endAt', 0, 2, arguments.length);\n return new Query(this.database, query(this._delegate, endAt(value, name)));\n }\n\n endBefore(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.endBefore', 0, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, endBefore(value, name))\n );\n }\n\n /**\n * Load the selection of children with exactly the specified value, and, optionally,\n * the specified name.\n */\n equalTo(value: number | string | boolean | null, name?: string) {\n validateArgCount('Query.equalTo', 1, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, equalTo(value, name))\n );\n }\n\n /**\n * @returns URL for this location.\n */\n toString(): string {\n validateArgCount('Query.toString', 0, 0, arguments.length);\n return this._delegate.toString();\n }\n\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users.\n toJSON() {\n // An optional spacer argument is unnecessary for a string.\n validateArgCount('Query.toJSON', 0, 1, arguments.length);\n return this._delegate.toJSON();\n }\n\n /**\n * Return true if this query and the provided query are equivalent; otherwise, return false.\n */\n isEqual(other: Query): boolean {\n validateArgCount('Query.isEqual', 1, 1, arguments.length);\n if (!(other instanceof Query)) {\n const error =\n 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.';\n throw new Error(error);\n }\n return this._delegate.isEqual(other._delegate);\n }\n\n /**\n * Helper used by .on and .once to extract the context and or cancel arguments.\n * @param fnName - The function name (on or once)\n *\n */\n private static getCancelAndContextArgs_(\n fnName: string,\n cancelOrContext?: ((a: Error) => void) | object | null,\n context?: object | null\n ): { cancel: ((a: Error) => void) | undefined; context: object | undefined } {\n const ret: {\n cancel: ((a: Error) => void) | null;\n context: object | null;\n } = { cancel: undefined, context: undefined };\n if (cancelOrContext && context) {\n ret.cancel = cancelOrContext as (a: Error) => void;\n validateCallback(fnName, 'cancel', ret.cancel, true);\n\n ret.context = context;\n validateContextObject(fnName, 'context', ret.context, true);\n } else if (cancelOrContext) {\n // we have either a cancel callback or a context.\n if (typeof cancelOrContext === 'object' && cancelOrContext !== null) {\n // it's a context!\n ret.context = cancelOrContext;\n } else if (typeof cancelOrContext === 'function') {\n ret.cancel = cancelOrContext as (a: Error) => void;\n } else {\n throw new Error(\n errorPrefix(fnName, 'cancelOrContext') +\n ' must either be a cancel callback or a context object.'\n );\n }\n }\n return ret;\n }\n\n get ref(): Reference {\n return new Reference(\n this.database,\n new _ReferenceImpl(this._delegate._repo, this._delegate._path)\n );\n }\n}\n\nexport class Reference extends Query implements Compat {\n then: Promise['then'];\n catch: Promise['catch'];\n\n /**\n * Call options:\n * new Reference(Repo, Path) or\n * new Reference(url: string, string|RepoManager)\n *\n * Externally - this is the firebase.database.Reference type.\n */\n constructor(\n readonly database: Database,\n readonly _delegate: ModularReference\n ) {\n super(\n database,\n new _QueryImpl(\n _delegate._repo,\n _delegate._path,\n new _QueryParams(),\n false\n )\n );\n }\n\n /** @returns {?string} */\n getKey(): string | null {\n validateArgCount('Reference.key', 0, 0, arguments.length);\n return this._delegate.key;\n }\n\n child(pathString: string): Reference {\n validateArgCount('Reference.child', 1, 1, arguments.length);\n if (typeof pathString === 'number') {\n pathString = String(pathString);\n }\n return new Reference(this.database, child(this._delegate, pathString));\n }\n\n /** @returns {?Reference} */\n getParent(): Reference | null {\n validateArgCount('Reference.parent', 0, 0, arguments.length);\n const parent = this._delegate.parent;\n return parent ? new Reference(this.database, parent) : null;\n }\n\n /** @returns {!Reference} */\n getRoot(): Reference {\n validateArgCount('Reference.root', 0, 0, arguments.length);\n return new Reference(this.database, this._delegate.root);\n }\n\n set(\n newVal: unknown,\n onComplete?: (error: Error | null) => void\n ): Promise {\n validateArgCount('Reference.set', 1, 2, arguments.length);\n validateCallback('Reference.set', 'onComplete', onComplete, true);\n const result = set(this._delegate, newVal);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n update(\n values: object,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('Reference.update', 1, 2, arguments.length);\n\n if (Array.isArray(values)) {\n const newObjectToMerge: { [k: string]: unknown } = {};\n for (let i = 0; i < values.length; ++i) {\n newObjectToMerge['' + i] = values[i];\n }\n values = newObjectToMerge;\n warn(\n 'Passing an Array to Firebase.update() is deprecated. ' +\n 'Use set() if you want to overwrite the existing data, or ' +\n 'an Object with integer keys if you really do want to ' +\n 'only update some of the children.'\n );\n }\n _validateWritablePath('Reference.update', this._delegate._path);\n validateCallback('Reference.update', 'onComplete', onComplete, true);\n\n const result = update(this._delegate, values);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n setWithPriority(\n newVal: unknown,\n newPriority: string | number | null,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);\n validateCallback(\n 'Reference.setWithPriority',\n 'onComplete',\n onComplete,\n true\n );\n\n const result = setWithPriority(this._delegate, newVal, newPriority);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n remove(onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('Reference.remove', 0, 1, arguments.length);\n validateCallback('Reference.remove', 'onComplete', onComplete, true);\n\n const result = remove(this._delegate);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n transaction(\n transactionUpdate: (currentData: unknown) => unknown,\n onComplete?: (\n error: Error | null,\n committed: boolean,\n dataSnapshot: DataSnapshot | null\n ) => void,\n applyLocally?: boolean\n ): Promise {\n validateArgCount('Reference.transaction', 1, 3, arguments.length);\n validateCallback(\n 'Reference.transaction',\n 'transactionUpdate',\n transactionUpdate,\n false\n );\n validateCallback('Reference.transaction', 'onComplete', onComplete, true);\n validateBoolean(\n 'Reference.transaction',\n 'applyLocally',\n applyLocally,\n true\n );\n\n const result = runTransaction(this._delegate, transactionUpdate, {\n applyLocally\n }).then(\n transactionResult =>\n new TransactionResult(\n transactionResult.committed,\n new DataSnapshot(this.database, transactionResult.snapshot)\n )\n );\n if (onComplete) {\n result.then(\n transactionResult =>\n onComplete(\n null,\n transactionResult.committed,\n transactionResult.snapshot\n ),\n error => onComplete(error, false, null)\n );\n }\n return result;\n }\n\n setPriority(\n priority: string | number | null,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('Reference.setPriority', 1, 2, arguments.length);\n validateCallback('Reference.setPriority', 'onComplete', onComplete, true);\n\n const result = setPriority(this._delegate, priority);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n push(value?: unknown, onComplete?: (a: Error | null) => void): Reference {\n validateArgCount('Reference.push', 0, 2, arguments.length);\n validateCallback('Reference.push', 'onComplete', onComplete, true);\n\n const expPromise = push(this._delegate, value);\n const promise = expPromise.then(\n expRef => new Reference(this.database, expRef)\n );\n\n if (onComplete) {\n promise.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n\n const result = new Reference(this.database, expPromise);\n result.then = promise.then.bind(promise);\n result.catch = promise.catch.bind(promise, undefined);\n return result;\n }\n\n onDisconnect(): OnDisconnect {\n _validateWritablePath('Reference.onDisconnect', this._delegate._path);\n return new OnDisconnect(\n new ModularOnDisconnect(this._delegate._repo, this._delegate._path)\n );\n }\n\n get key(): string | null {\n return this.getKey();\n }\n\n get parent(): Reference | null {\n return this.getParent();\n }\n\n get root(): Reference {\n return this.getRoot();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\n\nimport { FirebaseApp } from '@firebase/app-types';\nimport { FirebaseService } from '@firebase/app-types/private';\nimport {\n forceLongPolling,\n forceWebSockets,\n goOnline,\n connectDatabaseEmulator,\n goOffline,\n ref,\n refFromURL,\n increment,\n serverTimestamp,\n Database as ModularDatabase\n} from '@firebase/database';\nimport {\n validateArgCount,\n Compat,\n EmulatorMockTokenOptions\n} from '@firebase/util';\n\nimport { Reference } from './Reference';\n\n/**\n * Class representing a firebase database.\n */\nexport class Database implements FirebaseService, Compat {\n static readonly ServerValue = {\n TIMESTAMP: serverTimestamp(),\n increment: (delta: number) => increment(delta)\n };\n\n /**\n * The constructor should not be called by users of our public API.\n */\n constructor(readonly _delegate: ModularDatabase, readonly app: FirebaseApp) {}\n\n INTERNAL = {\n delete: () => this._delegate._delete(),\n forceWebSockets,\n forceLongPolling\n };\n\n /**\n * Modify this instance to communicate with the Realtime Database emulator.\n *\n *

Note: This method must be called before performing any other operation.\n *\n * @param host - the emulator host (ex: localhost)\n * @param port - the emulator port (ex: 8080)\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\n */\n useEmulator(\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions;\n } = {}\n ): void {\n connectDatabaseEmulator(this._delegate, host, port, options);\n }\n\n /**\n * Returns a reference to the root or to the path specified in the provided\n * argument.\n *\n * @param path - The relative string path or an existing Reference to a database\n * location.\n * @throws If a Reference is provided, throws if it does not belong to the\n * same project.\n * @returns Firebase reference.\n */\n ref(path?: string): Reference;\n ref(path?: Reference): Reference;\n ref(path?: string | Reference): Reference {\n validateArgCount('database.ref', 0, 1, arguments.length);\n if (path instanceof Reference) {\n const childRef = refFromURL(this._delegate, path.toString());\n return new Reference(this, childRef);\n } else {\n const childRef = ref(this._delegate, path);\n return new Reference(this, childRef);\n }\n }\n\n /**\n * Returns a reference to the root or the path specified in url.\n * We throw a exception if the url is not in the same domain as the\n * current repo.\n * @returns Firebase reference.\n */\n refFromURL(url: string): Reference {\n const apiName = 'database.refFromURL';\n validateArgCount(apiName, 1, 1, arguments.length);\n const childRef = refFromURL(this._delegate, url);\n return new Reference(this, childRef);\n }\n\n // Make individual repo go offline.\n goOffline(): void {\n validateArgCount('database.goOffline', 0, 0, arguments.length);\n return goOffline(this._delegate);\n }\n\n goOnline(): void {\n validateArgCount('database.goOnline', 0, 0, arguments.length);\n return goOnline(this._delegate);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n AppCheckInternalComponentName,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport { FirebaseApp } from '@firebase/app-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n Provider\n} from '@firebase/component';\nimport {\n _repoManagerDatabaseFromApp,\n _setSDKVersion\n} from '@firebase/database';\nimport * as types from '@firebase/database-types';\n\nimport { Database } from './Database';\n\n/**\n * Used by console to create a database based on the app,\n * passed database URL and a custom auth implementation.\n *\n * @param app - A valid FirebaseApp-like object\n * @param url - A valid Firebase databaseURL\n * @param version - custom version e.g. firebase-admin version\n * @param customAuthImpl - custom auth implementation\n */\nexport function initStandalone({\n app,\n url,\n version,\n customAuthImpl,\n customAppCheckImpl,\n namespace,\n nodeAdmin = false\n}: {\n app: FirebaseApp;\n url: string;\n version: string;\n customAuthImpl: FirebaseAuthInternal;\n customAppCheckImpl?: FirebaseAppCheckInternal;\n namespace: T;\n nodeAdmin?: boolean;\n}): {\n instance: types.Database;\n namespace: T;\n} {\n _setSDKVersion(version);\n\n const container = new ComponentContainer('database-standalone');\n /**\n * ComponentContainer('database-standalone') is just a placeholder that doesn't perform\n * any actual function.\n */\n const authProvider = new Provider(\n 'auth-internal',\n container\n );\n authProvider.setComponent(\n new Component('auth-internal', () => customAuthImpl, ComponentType.PRIVATE)\n );\n\n let appCheckProvider: Provider = undefined;\n if (customAppCheckImpl) {\n appCheckProvider = new Provider(\n 'app-check-internal',\n container\n );\n appCheckProvider.setComponent(\n new Component(\n 'app-check-internal',\n () => customAppCheckImpl,\n ComponentType.PRIVATE\n )\n );\n }\n\n return {\n instance: new Database(\n _repoManagerDatabaseFromApp(\n app,\n authProvider,\n appCheckProvider,\n url,\n nodeAdmin\n ),\n app\n ) as types.Database,\n namespace\n };\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport firebase from '@firebase/app-compat';\nimport { FirebaseNamespace } from '@firebase/app-types';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport { Component, ComponentType } from '@firebase/component';\nimport { enableLogging } from '@firebase/database';\nimport * as types from '@firebase/database-types';\n\nimport { name, version } from '../package.json';\nimport { Database } from '../src/api/Database';\nimport * as INTERNAL from '../src/api/internal';\nimport { DataSnapshot, Query, Reference } from '../src/api/Reference';\n\nconst ServerValue = Database.ServerValue;\n\nfunction registerDatabase(instance: FirebaseNamespace) {\n // Register the Database Service with the 'firebase' namespace.\n (instance as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component(\n 'database-compat',\n (container, { instanceIdentifier: url }) => {\n /* Dependencies */\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app-compat').getImmediate();\n const databaseExp = container\n .getProvider('database')\n .getImmediate({ identifier: url });\n return new Database(databaseExp, app);\n },\n ComponentType.PUBLIC\n )\n .setServiceProps(\n // firebase.database namespace properties\n {\n Reference,\n Query,\n Database,\n DataSnapshot,\n enableLogging,\n INTERNAL,\n ServerValue\n }\n )\n .setMultipleInstances(true)\n );\n\n instance.registerVersion(name, version, 'node');\n}\n\nregisterDatabase(firebase);\n\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n database?: {\n (app?: FirebaseApp): types.FirebaseDatabase;\n enableLogging: typeof types.enableLogging;\n ServerValue: types.ServerValue;\n Database: typeof types.FirebaseDatabase;\n };\n }\n interface FirebaseApp {\n database?(): types.FirebaseDatabase;\n }\n}\n"],"names":["errorPrefixFxn","ModularOnDisconnect"],"mappings":";;;;;;;;;AAAA;;;;;;;;;;;;;;;AAeG;AAIH,MAAM,SAAS,GAAG,IAAI,MAAM,CAAC,2BAA2B,CAAC,CAAC;AAEnD,MAAM,IAAI,GAAG,UAAU,GAAW,EAAA;AACvC,IAAA,MAAM,OAAO,GAAG,oBAAoB,GAAG,GAAG,CAAC;AAC3C,IAAA,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;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AAI,QAAQ,CACpB,2BAA2B,CACzB,GAAG,EACH,YAAY,EACZ,gBAAgB,EAChB,GAAG,EACH,SAAS,CACV,EACD,GAAG,CACc;QACnB,SAAS;KACV,CAAC;AACJ;;;;;;;AC/GA;;;;;;;;;;;;;;;AAeG;AAeH,MAAM,WAAW,GAAG,QAAQ,CAAC,WAAW,CAAC;AAEzC,SAAS,gBAAgB,CAAC,QAA2B,EAAA;;AAElD,IAAA,QAA+B,CAAC,QAAQ,CAAC,iBAAiB,CACzD,IAAI,SAAS,CACX,iBAAiB,EACjB,CAAC,SAAS,EAAE,EAAE,kBAAkB,EAAE,GAAG,EAAE,KAAI;;;QAGzC,MAAM,GAAG,GAAG,SAAS,CAAC,WAAW,CAAC,YAAY,CAAC,CAAC,YAAY,EAAE,CAAC;QAC/D,MAAM,WAAW,GAAG,SAAS;aAC1B,WAAW,CAAC,UAAU,CAAC;AACvB,aAAA,YAAY,CAAC,EAAE,UAAU,EAAE,GAAG,EAAE,CAAC,CAAC;AACrC,QAAA,OAAO,IAAI,QAAQ,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC;AACxC,KAAC,EAEF,QAAA,4BAAA;SACE,eAAe;;AAEd,IAAA;QACE,SAAS;QACT,KAAK;QACL,QAAQ;QACR,YAAY;QACZ,aAAa;QACb,QAAQ;QACR,WAAW;KACZ,CACF;AACA,SAAA,oBAAoB,CAAC,IAAI,CAAC,CAC9B,CAAC;IAEF,QAAQ,CAAC,eAAe,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;AAClD,CAAC;AAED,gBAAgB,CAAC,QAAQ,CAAC"} \ No newline at end of file diff --git a/node_modules/@firebase/database-compat/dist/node-esm/package.json b/node_modules/@firebase/database-compat/dist/node-esm/package.json new file mode 100644 index 0000000..7c34deb --- /dev/null +++ b/node_modules/@firebase/database-compat/dist/node-esm/package.json @@ -0,0 +1 @@ +{"type":"module"} \ No newline at end of file diff --git a/node_modules/@firebase/database-compat/package.json b/node_modules/@firebase/database-compat/package.json new file mode 100644 index 0000000..8840022 --- /dev/null +++ b/node_modules/@firebase/database-compat/package.json @@ -0,0 +1,74 @@ +{ + "name": "@firebase/database-compat", + "version": "2.1.0", + "description": "The Realtime Database component of the Firebase JS SDK.", + "author": "Firebase (https://firebase.google.com/)", + "main": "dist/index.js", + "browser": "dist/index.esm.js", + "module": "dist/index.esm.js", + "license": "Apache-2.0", + "typings": "dist/database-compat/src/index.d.ts", + "files": [ + "dist", + "standalone/package.json" + ], + "exports": { + ".": { + "types": "./dist/database-compat/src/index.d.ts", + "node": { + "types": "./dist/database-compat/src/index.node.d.ts", + "import": "./dist/node-esm/index.js", + "require": "./dist/index.js" + }, + "browser": { + "require": "./dist/index.js", + "import": "./dist/index.esm.js" + }, + "default": "./dist/index.esm.js" + }, + "./standalone": { + "types": "./dist/database-compat/src/index.standalone.d.ts", + "node": "./dist/index.standalone.js", + "default": "./dist/index.standalone.js" + }, + "./package.json": "./package.json" + }, + "scripts": { + "lint": "eslint -c .eslintrc.js '**/*.ts' --ignore-path '../../.gitignore'", + "lint:fix": "eslint --fix -c .eslintrc.js '**/*.ts' --ignore-path '../../.gitignore'", + "prettier": "prettier --write '*.js' '*.ts' '@(src|test)/**/*.ts'", + "build": "rollup -c rollup.config.js", + "build:release": "yarn build && yarn add-compat-overloads", + "build:deps": "lerna run --scope @firebase/database-compat --include-dependencies build", + "dev": "rollup -c -w", + "test": "run-p --npm-path npm lint test:browser test:node", + "test:ci": "node ../../scripts/run_tests_in_ci.js -s test", + "test:browser": "karma start", + "test:node": "TS_NODE_FILES=true TS_NODE_CACHE=NO TS_NODE_COMPILER_OPTIONS='{\"module\":\"commonjs\"}' nyc --reporter lcovonly -- mocha 'test/{,!(browser)/**/}*.test.ts' --file src/index.node.ts --config ../../config/mocharc.node.js", + "trusted-type-check": "tsec -p tsconfig.json --noEmit", + "add-compat-overloads": "ts-node-script ../../scripts/build/create-overloads.ts -i ../database/dist/public.d.ts -o dist/database-compat/src/index.d.ts -a -r Database:types.FirebaseDatabase -r Query:types.Query -r DatabaseReference:types.Reference -r FirebaseApp:FirebaseAppCompat --moduleToEnhance @firebase/database" + }, + "dependencies": { + "@firebase/database": "1.1.0", + "@firebase/database-types": "1.0.16", + "@firebase/logger": "0.5.0", + "@firebase/util": "1.13.0", + "@firebase/component": "0.7.0", + "tslib": "^2.1.0" + }, + "devDependencies": { + "@firebase/app-compat": "0.5.0", + "typescript": "5.5.4" + }, + "repository": { + "directory": "packages/database-compat", + "type": "git", + "url": "git+https://github.com/firebase/firebase-js-sdk.git" + }, + "bugs": { + "url": "https://github.com/firebase/firebase-js-sdk/issues" + }, + "engines": { + "node": ">=20.0.0" + } +} diff --git a/node_modules/@firebase/database-compat/standalone/package.json b/node_modules/@firebase/database-compat/standalone/package.json new file mode 100644 index 0000000..f9d3982 --- /dev/null +++ b/node_modules/@firebase/database-compat/standalone/package.json @@ -0,0 +1,7 @@ +{ + "name": "@firebase/database-compat/standalone", + "description": "The entry point for sharing code with Admin SDK", + "main": "../dist/index.standalone.js", + "typings": "../dist/database-compat/src/index.standalone.d.ts", + "private": true +} \ No newline at end of file diff --git a/node_modules/@firebase/database-types/README.md b/node_modules/@firebase/database-types/README.md new file mode 100644 index 0000000..681f6b3 --- /dev/null +++ b/node_modules/@firebase/database-types/README.md @@ -0,0 +1,3 @@ +# @firebase/database-types + +**This package is not intended for direct usage, and should only be used via the officially supported [firebase](https://www.npmjs.com/package/firebase) package.** diff --git a/node_modules/@firebase/database-types/index.d.ts b/node_modules/@firebase/database-types/index.d.ts new file mode 100644 index 0000000..43557eb --- /dev/null +++ b/node_modules/@firebase/database-types/index.d.ts @@ -0,0 +1,181 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { FirebaseApp } from '@firebase/app-types'; +import { EmulatorMockTokenOptions } from '@firebase/util'; + +/** + * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined. + */ +export interface IteratedDataSnapshot extends DataSnapshot { + key: string; // key of the location of this snapshot. +} + +export interface DataSnapshot { + child(path: string): DataSnapshot; + exists(): boolean; + exportVal(): any; + forEach(action: (a: IteratedDataSnapshot) => boolean | void): boolean; + getPriority(): string | number | null; + hasChild(path: string): boolean; + hasChildren(): boolean; + key: string | null; + numChildren(): number; + ref: Reference; + toJSON(): Object | null; + val(): any; +} + +export interface Database { + app: FirebaseApp; + useEmulator( + host: string, + port: number, + options?: { + mockUserToken?: EmulatorMockTokenOptions | string; + } + ): void; + goOffline(): void; + goOnline(): void; + ref(path?: string | Reference): Reference; + refFromURL(url: string): Reference; +} + +export class FirebaseDatabase implements Database { + private constructor(); + app: FirebaseApp; + useEmulator( + host: string, + port: number, + options?: { + mockUserToken?: EmulatorMockTokenOptions | string; + } + ): void; + goOffline(): void; + goOnline(): void; + ref(path?: string | Reference): Reference; + refFromURL(url: string): Reference; +} + +export interface OnDisconnect { + cancel(onComplete?: (a: Error | null) => any): Promise; + remove(onComplete?: (a: Error | null) => any): Promise; + set(value: any, onComplete?: (a: Error | null) => any): Promise; + setWithPriority( + value: any, + priority: number | string | null, + onComplete?: (a: Error | null) => any + ): Promise; + update(values: Object, onComplete?: (a: Error | null) => any): Promise; +} + +type EventType = + | 'value' + | 'child_added' + | 'child_changed' + | 'child_moved' + | 'child_removed'; + +export interface Query { + endBefore(value: number | string | boolean | null, key?: string): Query; + endAt(value: number | string | boolean | null, key?: string): Query; + equalTo(value: number | string | boolean | null, key?: string): Query; + isEqual(other: Query | null): boolean; + limitToFirst(limit: number): Query; + limitToLast(limit: number): Query; + off( + eventType?: EventType, + callback?: (a: DataSnapshot, b?: string | null) => any, + context?: Object | null + ): void; + get(): Promise; + on( + eventType: EventType, + callback: (a: DataSnapshot, b?: string | null) => any, + cancelCallbackOrContext?: ((a: Error) => any) | Object | null, + context?: Object | null + ): (a: DataSnapshot | null, b?: string | null) => any; + once( + eventType: EventType, + successCallback?: (a: DataSnapshot, b?: string | null) => any, + failureCallbackOrContext?: ((a: Error) => void) | Object | null, + context?: Object | null + ): Promise; + orderByChild(path: string): Query; + orderByKey(): Query; + orderByPriority(): Query; + orderByValue(): Query; + ref: Reference; + startAt(value: number | string | boolean | null, key?: string): Query; + startAfter(value: number | string | boolean | null, key?: string): Query; + toJSON(): Object; + toString(): string; +} + +export interface Reference extends Query { + child(path: string): Reference; + key: string | null; + onDisconnect(): OnDisconnect; + parent: Reference | null; + push(value?: any, onComplete?: (a: Error | null) => any): ThenableReference; + remove(onComplete?: (a: Error | null) => void): Promise; + root: Reference; + set(value: any, onComplete?: (a: Error | null) => void): Promise; + setPriority( + priority: string | number | null, + onComplete: (a: Error | null) => void + ): Promise; + setWithPriority( + newVal: any, + newPriority: string | number | null, + onComplete?: (a: Error | null) => void + ): Promise; + transaction( + transactionUpdate: (a: any) => any, + onComplete?: (a: Error | null, b: boolean, c: DataSnapshot | null) => void, + applyLocally?: boolean + ): Promise; + update(values: Object, onComplete?: (a: Error | null) => void): Promise; +} + +export interface ServerValue { + TIMESTAMP: Object; + increment(delta: number): Object; +} + +export interface TransactionResult { + committed: boolean; + snapshot: DataSnapshot; +} + +export interface ThenableReference + extends Reference, + Pick, 'then' | 'catch'> { + key: string; + parent: Reference; +} + +export function enableLogging( + logger?: boolean | ((a: string) => any), + persistent?: boolean +): any; + +declare module '@firebase/component' { + interface NameServiceMapping { + 'database-compat': FirebaseDatabase; + } +} diff --git a/node_modules/@firebase/database-types/package.json b/node_modules/@firebase/database-types/package.json new file mode 100644 index 0000000..b63337a --- /dev/null +++ b/node_modules/@firebase/database-types/package.json @@ -0,0 +1,29 @@ +{ + "name": "@firebase/database-types", + "version": "1.0.16", + "description": "@firebase/database Types", + "author": "Firebase (https://firebase.google.com/)", + "license": "Apache-2.0", + "scripts": { + "test": "tsc", + "test:ci": "node ../../scripts/run_tests_in_ci.js" + }, + "files": [ + "index.d.ts" + ], + "dependencies": { + "@firebase/app-types": "0.9.3", + "@firebase/util": "1.13.0" + }, + "repository": { + "directory": "packages/database-types", + "type": "git", + "url": "git+https://github.com/firebase/firebase-js-sdk.git" + }, + "bugs": { + "url": "https://github.com/firebase/firebase-js-sdk/issues" + }, + "devDependencies": { + "typescript": "5.5.4" + } +} diff --git a/node_modules/@firebase/database/README.md b/node_modules/@firebase/database/README.md new file mode 100644 index 0000000..5fc92cc --- /dev/null +++ b/node_modules/@firebase/database/README.md @@ -0,0 +1,5 @@ +# @firebase/database + +This is the Firebase Realtime Database component of the Firebase JS SDK. + +**This package is not intended for direct usage, and should only be used via the officially supported [firebase](https://www.npmjs.com/package/firebase) package.** diff --git a/node_modules/@firebase/database/dist/index.cjs.js b/node_modules/@firebase/database/dist/index.cjs.js new file mode 100644 index 0000000..243b5d8 --- /dev/null +++ b/node_modules/@firebase/database/dist/index.cjs.js @@ -0,0 +1,14089 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var app = require('@firebase/app'); +var component = require('@firebase/component'); +var util = require('@firebase/util'); +var logger$1 = require('@firebase/logger'); + +const name = "@firebase/database"; +const version = "1.1.0"; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The semver (www.semver.org) version of the SDK. */ +let SDK_VERSION = ''; +/** + * SDK_VERSION should be set before any database instance is created + * @internal + */ +function setSDKVersion(version) { + SDK_VERSION = version; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Wraps a DOM Storage object and: + * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types. + * - prefixes names with "firebase:" to avoid collisions with app data. + * + * We automatically (see storage.js) create two such wrappers, one for sessionStorage, + * and one for localStorage. + * + */ +class DOMStorageWrapper { + /** + * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage) + */ + constructor(domStorage_) { + this.domStorage_ = domStorage_; + // Use a prefix to avoid collisions with other stuff saved by the app. + this.prefix_ = 'firebase:'; + } + /** + * @param key - The key to save the value under + * @param value - The value being stored, or null to remove the key. + */ + set(key, value) { + if (value == null) { + this.domStorage_.removeItem(this.prefixedName_(key)); + } + else { + this.domStorage_.setItem(this.prefixedName_(key), util.stringify(value)); + } + } + /** + * @returns The value that was stored under this key, or null + */ + get(key) { + const storedVal = this.domStorage_.getItem(this.prefixedName_(key)); + if (storedVal == null) { + return null; + } + else { + return util.jsonEval(storedVal); + } + } + remove(key) { + this.domStorage_.removeItem(this.prefixedName_(key)); + } + prefixedName_(name) { + return this.prefix_ + name; + } + toString() { + return this.domStorage_.toString(); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory storage implementation that matches the API of DOMStorageWrapper + * (TODO: create interface for both to implement). + */ +class MemoryStorage { + constructor() { + this.cache_ = {}; + this.isInMemoryStorage = true; + } + set(key, value) { + if (value == null) { + delete this.cache_[key]; + } + else { + this.cache_[key] = value; + } + } + get(key) { + if (util.contains(this.cache_, key)) { + return this.cache_[key]; + } + return null; + } + remove(key) { + delete this.cache_[key]; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage. + * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change + * to reflect this type + * + * @param domStorageName - Name of the underlying storage object + * (e.g. 'localStorage' or 'sessionStorage'). + * @returns Turning off type information until a common interface is defined. + */ +const createStoragefor = function (domStorageName) { + try { + // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception, + // so it must be inside the try/catch. + if (typeof window !== 'undefined' && + typeof window[domStorageName] !== 'undefined') { + // Need to test cache. Just because it's here doesn't mean it works + const domStorage = window[domStorageName]; + domStorage.setItem('firebase:sentinel', 'cache'); + domStorage.removeItem('firebase:sentinel'); + return new DOMStorageWrapper(domStorage); + } + } + catch (e) { } + // Failed to create wrapper. Just return in-memory storage. + // TODO: log? + return new MemoryStorage(); +}; +/** A storage object that lasts across sessions */ +const PersistentStorage = createStoragefor('localStorage'); +/** A storage object that only lasts one session */ +const SessionStorage = createStoragefor('sessionStorage'); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const logClient = new logger$1.Logger('@firebase/database'); +/** + * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called). + */ +const LUIDGenerator = (function () { + let id = 1; + return function () { + return id++; + }; +})(); +/** + * Sha1 hash of the input string + * @param str - The string to hash + * @returns {!string} The resulting hash + */ +const sha1 = function (str) { + const utf8Bytes = util.stringToByteArray(str); + const sha1 = new util.Sha1(); + sha1.update(utf8Bytes); + const sha1Bytes = sha1.digest(); + return util.base64.encodeByteArray(sha1Bytes); +}; +const buildLogMessage_ = function (...varArgs) { + let message = ''; + for (let i = 0; i < varArgs.length; i++) { + const arg = varArgs[i]; + if (Array.isArray(arg) || + (arg && + typeof arg === 'object' && + // eslint-disable-next-line @typescript-eslint/no-explicit-any + typeof arg.length === 'number')) { + message += buildLogMessage_.apply(null, arg); + } + else if (typeof arg === 'object') { + message += util.stringify(arg); + } + else { + message += arg; + } + message += ' '; + } + return message; +}; +/** + * Use this for all debug messages in Firebase. + */ +let logger = null; +/** + * Flag to check for log availability on first log message + */ +let firstLog_ = true; +/** + * The implementation of Firebase.enableLogging (defined here to break dependencies) + * @param logger_ - A flag to turn on logging, or a custom logger + * @param persistent - Whether or not to persist logging settings across refreshes + */ +const enableLogging$1 = function (logger_, persistent) { + util.assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently."); + if (logger_ === true) { + logClient.logLevel = logger$1.LogLevel.VERBOSE; + logger = logClient.log.bind(logClient); + if (persistent) { + SessionStorage.set('logging_enabled', true); + } + } + else if (typeof logger_ === 'function') { + logger = logger_; + } + else { + logger = null; + SessionStorage.remove('logging_enabled'); + } +}; +const log = function (...varArgs) { + if (firstLog_ === true) { + firstLog_ = false; + if (logger === null && SessionStorage.get('logging_enabled') === true) { + enableLogging$1(true); + } + } + if (logger) { + const message = buildLogMessage_.apply(null, varArgs); + logger(message); + } +}; +const logWrapper = function (prefix) { + return function (...varArgs) { + log(prefix, ...varArgs); + }; +}; +const error = function (...varArgs) { + const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs); + logClient.error(message); +}; +const fatal = function (...varArgs) { + const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`; + logClient.error(message); + throw new Error(message); +}; +const warn = function (...varArgs) { + const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs); + logClient.warn(message); +}; +/** + * Logs a warning if the containing page uses https. Called when a call to new Firebase + * does not use https. + */ +const warnIfPageIsSecure = function () { + // Be very careful accessing browser globals. Who knows what may or may not exist. + if (typeof window !== 'undefined' && + window.location && + window.location.protocol && + window.location.protocol.indexOf('https:') !== -1) { + warn('Insecure Firebase access from a secure page. ' + + 'Please use https in calls to new Firebase().'); + } +}; +/** + * Returns true if data is NaN, or +/- Infinity. + */ +const isInvalidJSONNumber = function (data) { + return (typeof data === 'number' && + (data !== data || // NaN + data === Number.POSITIVE_INFINITY || + data === Number.NEGATIVE_INFINITY)); +}; +const executeWhenDOMReady = function (fn) { + if (util.isNodeSdk() || document.readyState === 'complete') { + fn(); + } + else { + // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which + // fire before onload), but fall back to onload. + let called = false; + const wrappedFn = function () { + if (!document.body) { + setTimeout(wrappedFn, Math.floor(10)); + return; + } + if (!called) { + called = true; + fn(); + } + }; + if (document.addEventListener) { + document.addEventListener('DOMContentLoaded', wrappedFn, false); + // fallback to onload. + window.addEventListener('load', wrappedFn, false); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (document.attachEvent) { + // IE. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + document.attachEvent('onreadystatechange', () => { + if (document.readyState === 'complete') { + wrappedFn(); + } + }); + // fallback to onload. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + window.attachEvent('onload', wrappedFn); + // jQuery has an extra hack for IE that we could employ (based on + // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old. + // I'm hoping we don't need it. + } + } +}; +/** + * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names + */ +const MIN_NAME = '[MIN_NAME]'; +/** + * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names + */ +const MAX_NAME = '[MAX_NAME]'; +/** + * Compares valid Firebase key names, plus min and max name + */ +const nameCompare = function (a, b) { + if (a === b) { + return 0; + } + else if (a === MIN_NAME || b === MAX_NAME) { + return -1; + } + else if (b === MIN_NAME || a === MAX_NAME) { + return 1; + } + else { + const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b); + if (aAsInt !== null) { + if (bAsInt !== null) { + return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt; + } + else { + return -1; + } + } + else if (bAsInt !== null) { + return 1; + } + else { + return a < b ? -1 : 1; + } + } +}; +/** + * @returns {!number} comparison result. + */ +const stringCompare = function (a, b) { + if (a === b) { + return 0; + } + else if (a < b) { + return -1; + } + else { + return 1; + } +}; +const requireKey = function (key, obj) { + if (obj && key in obj) { + return obj[key]; + } + else { + throw new Error('Missing required key (' + key + ') in object: ' + util.stringify(obj)); + } +}; +const ObjectToUniqueKey = function (obj) { + if (typeof obj !== 'object' || obj === null) { + return util.stringify(obj); + } + const keys = []; + // eslint-disable-next-line guard-for-in + for (const k in obj) { + keys.push(k); + } + // Export as json, but with the keys sorted. + keys.sort(); + let key = '{'; + for (let i = 0; i < keys.length; i++) { + if (i !== 0) { + key += ','; + } + key += util.stringify(keys[i]); + key += ':'; + key += ObjectToUniqueKey(obj[keys[i]]); + } + key += '}'; + return key; +}; +/** + * Splits a string into a number of smaller segments of maximum size + * @param str - The string + * @param segsize - The maximum number of chars in the string. + * @returns The string, split into appropriately-sized chunks + */ +const splitStringBySize = function (str, segsize) { + const len = str.length; + if (len <= segsize) { + return [str]; + } + const dataSegs = []; + for (let c = 0; c < len; c += segsize) { + if (c + segsize > len) { + dataSegs.push(str.substring(c, len)); + } + else { + dataSegs.push(str.substring(c, c + segsize)); + } + } + return dataSegs; +}; +/** + * Apply a function to each (key, value) pair in an object or + * apply a function to each (index, value) pair in an array + * @param obj - The object or array to iterate over + * @param fn - The function to apply + */ +function each(obj, fn) { + for (const key in obj) { + if (obj.hasOwnProperty(key)) { + fn(key, obj[key]); + } + } +} +/** + * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License) + * I made one modification at the end and removed the NaN / Infinity + * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments. + * @param v - A double + * + */ +const doubleToIEEE754String = function (v) { + util.assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL + const ebits = 11, fbits = 52; + const bias = (1 << (ebits - 1)) - 1; + let s, e, f, ln, i; + // Compute sign, exponent, fraction + // Skip NaN / Infinity handling --MJL. + if (v === 0) { + e = 0; + f = 0; + s = 1 / v === -Infinity ? 1 : 0; + } + else { + s = v < 0; + v = Math.abs(v); + if (v >= Math.pow(2, 1 - bias)) { + // Normalized + ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias); + e = ln + bias; + f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits)); + } + else { + // Denormalized + e = 0; + f = Math.round(v / Math.pow(2, 1 - bias - fbits)); + } + } + // Pack sign, exponent, fraction + const bits = []; + for (i = fbits; i; i -= 1) { + bits.push(f % 2 ? 1 : 0); + f = Math.floor(f / 2); + } + for (i = ebits; i; i -= 1) { + bits.push(e % 2 ? 1 : 0); + e = Math.floor(e / 2); + } + bits.push(s ? 1 : 0); + bits.reverse(); + const str = bits.join(''); + // Return the data as a hex string. --MJL + let hexByteString = ''; + for (i = 0; i < 64; i += 8) { + let hexByte = parseInt(str.substr(i, 8), 2).toString(16); + if (hexByte.length === 1) { + hexByte = '0' + hexByte; + } + hexByteString = hexByteString + hexByte; + } + return hexByteString.toLowerCase(); +}; +/** + * Used to detect if we're in a Chrome content script (which executes in an + * isolated environment where long-polling doesn't work). + */ +const isChromeExtensionContentScript = function () { + return !!(typeof window === 'object' && + window['chrome'] && + window['chrome']['extension'] && + !/^chrome/.test(window.location.href)); +}; +/** + * Used to detect if we're in a Windows 8 Store app. + */ +const isWindowsStoreApp = function () { + // Check for the presence of a couple WinRT globals + return typeof Windows === 'object' && typeof Windows.UI === 'object'; +}; +/** + * Converts a server error code to a JavaScript Error + */ +function errorForServerCode(code, query) { + let reason = 'Unknown Error'; + if (code === 'too_big') { + reason = + 'The data requested exceeds the maximum size ' + + 'that can be accessed with a single request.'; + } + else if (code === 'permission_denied') { + reason = "Client doesn't have permission to access the desired data."; + } + else if (code === 'unavailable') { + reason = 'The service is unavailable'; + } + const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error.code = code.toUpperCase(); + return error; +} +/** + * Used to test for integer-looking strings + */ +const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$'); +/** + * For use in keys, the minimum possible 32-bit integer. + */ +const INTEGER_32_MIN = -2147483648; +/** + * For use in keys, the maximum possible 32-bit integer. + */ +const INTEGER_32_MAX = 2147483647; +/** + * If the string contains a 32-bit integer, return it. Else return null. + */ +const tryParseInt = function (str) { + if (INTEGER_REGEXP_.test(str)) { + const intVal = Number(str); + if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) { + return intVal; + } + } + return null; +}; +/** + * Helper to run some code but catch any exceptions and re-throw them later. + * Useful for preventing user callbacks from breaking internal code. + * + * Re-throwing the exception from a setTimeout is a little evil, but it's very + * convenient (we don't have to try to figure out when is a safe point to + * re-throw it), and the behavior seems reasonable: + * + * * If you aren't pausing on exceptions, you get an error in the console with + * the correct stack trace. + * * If you're pausing on all exceptions, the debugger will pause on your + * exception and then again when we rethrow it. + * * If you're only pausing on uncaught exceptions, the debugger will only pause + * on us re-throwing it. + * + * @param fn - The code to guard. + */ +const exceptionGuard = function (fn) { + try { + fn(); + } + catch (e) { + // Re-throw exception when it's safe. + setTimeout(() => { + // It used to be that "throw e" would result in a good console error with + // relevant context, but as of Chrome 39, you just get the firebase.js + // file/line number where we re-throw it, which is useless. So we log + // e.stack explicitly. + const stack = e.stack || ''; + warn('Exception was thrown by user callback.', stack); + throw e; + }, Math.floor(0)); + } +}; +/** + * @returns {boolean} true if we think we're currently being crawled. + */ +const beingCrawled = function () { + const userAgent = (typeof window === 'object' && + window['navigator'] && + window['navigator']['userAgent']) || + ''; + // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we + // believe to support JavaScript/AJAX rendering. + // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website + // would have seen the page" is flaky if we don't treat it as a crawler. + return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0); +}; +/** + * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting. + * + * It is removed with clearTimeout() as normal. + * + * @param fn - Function to run. + * @param time - Milliseconds to wait before running. + * @returns The setTimeout() return value. + */ +const setTimeoutNonBlocking = function (fn, time) { + const timeout = setTimeout(fn, time); + // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API. + if (typeof timeout === 'number' && + // @ts-ignore Is only defined in Deno environments. + typeof Deno !== 'undefined' && + // @ts-ignore Deno and unrefTimer are only defined in Deno environments. + Deno['unrefTimer']) { + // @ts-ignore Deno and unrefTimer are only defined in Deno environments. + Deno.unrefTimer(timeout); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (typeof timeout === 'object' && timeout['unref']) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + timeout['unref'](); + } + return timeout; +}; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Abstraction around AppCheck's token fetching capabilities. + */ +class AppCheckTokenProvider { + constructor(app$1, appCheckProvider) { + this.appCheckProvider = appCheckProvider; + this.appName = app$1.name; + if (app._isFirebaseServerApp(app$1) && app$1.settings.appCheckToken) { + this.serverAppAppCheckToken = app$1.settings.appCheckToken; + } + this.appCheck = appCheckProvider?.getImmediate({ optional: true }); + if (!this.appCheck) { + appCheckProvider?.get().then(appCheck => (this.appCheck = appCheck)); + } + } + getToken(forceRefresh) { + if (this.serverAppAppCheckToken) { + if (forceRefresh) { + throw new Error('Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.'); + } + return Promise.resolve({ token: this.serverAppAppCheckToken }); + } + if (!this.appCheck) { + return new Promise((resolve, reject) => { + // Support delayed initialization of FirebaseAppCheck. This allows our + // customers to initialize the RTDB SDK before initializing Firebase + // AppCheck and ensures that all requests are authenticated if a token + // becomes available before the timeout below expires. + setTimeout(() => { + if (this.appCheck) { + this.getToken(forceRefresh).then(resolve, reject); + } + else { + resolve(null); + } + }, 0); + }); + } + return this.appCheck.getToken(forceRefresh); + } + addTokenChangeListener(listener) { + this.appCheckProvider + ?.get() + .then(appCheck => appCheck.addTokenListener(listener)); + } + notifyForInvalidToken() { + warn(`Provided AppCheck credentials for the app named "${this.appName}" ` + + 'are invalid. This usually indicates your app was not initialized correctly.'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Abstraction around FirebaseApp's token fetching capabilities. + */ +class FirebaseAuthTokenProvider { + constructor(appName_, firebaseOptions_, authProvider_) { + this.appName_ = appName_; + this.firebaseOptions_ = firebaseOptions_; + this.authProvider_ = authProvider_; + this.auth_ = null; + this.auth_ = authProvider_.getImmediate({ optional: true }); + if (!this.auth_) { + authProvider_.onInit(auth => (this.auth_ = auth)); + } + } + getToken(forceRefresh) { + if (!this.auth_) { + return new Promise((resolve, reject) => { + // Support delayed initialization of FirebaseAuth. This allows our + // customers to initialize the RTDB SDK before initializing Firebase + // Auth and ensures that all requests are authenticated if a token + // becomes available before the timeout below expires. + setTimeout(() => { + if (this.auth_) { + this.getToken(forceRefresh).then(resolve, reject); + } + else { + resolve(null); + } + }, 0); + }); + } + return this.auth_.getToken(forceRefresh).catch(error => { + // TODO: Need to figure out all the cases this is raised and whether + // this makes sense. + if (error && error.code === 'auth/token-not-initialized') { + log('Got auth/token-not-initialized error. Treating as null token.'); + return null; + } + else { + return Promise.reject(error); + } + }); + } + addTokenChangeListener(listener) { + // TODO: We might want to wrap the listener and call it with no args to + // avoid a leaky abstraction, but that makes removing the listener harder. + if (this.auth_) { + this.auth_.addAuthTokenListener(listener); + } + else { + this.authProvider_ + .get() + .then(auth => auth.addAuthTokenListener(listener)); + } + } + removeTokenChangeListener(listener) { + this.authProvider_ + .get() + .then(auth => auth.removeAuthTokenListener(listener)); + } + notifyForInvalidToken() { + let errorMessage = 'Provided authentication credentials for the app named "' + + this.appName_ + + '" are invalid. This usually indicates your app was not ' + + 'initialized correctly. '; + if ('credential' in this.firebaseOptions_) { + errorMessage += + 'Make sure the "credential" property provided to initializeApp() ' + + 'is authorized to access the specified "databaseURL" and is from the correct ' + + 'project.'; + } + else if ('serviceAccount' in this.firebaseOptions_) { + errorMessage += + 'Make sure the "serviceAccount" property provided to initializeApp() ' + + 'is authorized to access the specified "databaseURL" and is from the correct ' + + 'project.'; + } + else { + errorMessage += + 'Make sure the "apiKey" and "databaseURL" properties provided to ' + + 'initializeApp() match the values provided for your app at ' + + 'https://console.firebase.google.com/.'; + } + warn(errorMessage); + } +} +/* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */ +class EmulatorTokenProvider { + constructor(accessToken) { + this.accessToken = accessToken; + } + getToken(forceRefresh) { + return Promise.resolve({ + accessToken: this.accessToken + }); + } + addTokenChangeListener(listener) { + // Invoke the listener immediately to match the behavior in Firebase Auth + // (see packages/auth/src/auth.js#L1807) + listener(this.accessToken); + } + removeTokenChangeListener(listener) { } + notifyForInvalidToken() { } +} +/** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */ +EmulatorTokenProvider.OWNER = 'owner'; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const PROTOCOL_VERSION = '5'; +const VERSION_PARAM = 'v'; +const TRANSPORT_SESSION_PARAM = 's'; +const REFERER_PARAM = 'r'; +const FORGE_REF = 'f'; +// Matches console.firebase.google.com, firebase-console-*.corp.google.com and +// firebase.corp.google.com +const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/; +const LAST_SESSION_PARAM = 'ls'; +const APPLICATION_ID_PARAM = 'p'; +const APP_CHECK_TOKEN_PARAM = 'ac'; +const WEBSOCKET = 'websocket'; +const LONG_POLLING = 'long_polling'; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A class that holds metadata about a Repo object + */ +class RepoInfo { + /** + * @param host - Hostname portion of the url for the repo + * @param secure - Whether or not this repo is accessed over ssl + * @param namespace - The namespace represented by the repo + * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest). + * @param nodeAdmin - Whether this instance uses Admin SDK credentials + * @param persistenceKey - Override the default session persistence storage key + */ + constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false, isUsingEmulator = false, emulatorOptions = null) { + this.secure = secure; + this.namespace = namespace; + this.webSocketOnly = webSocketOnly; + this.nodeAdmin = nodeAdmin; + this.persistenceKey = persistenceKey; + this.includeNamespaceInQueryParams = includeNamespaceInQueryParams; + this.isUsingEmulator = isUsingEmulator; + this.emulatorOptions = emulatorOptions; + this._host = host.toLowerCase(); + this._domain = this._host.substr(this._host.indexOf('.') + 1); + this.internalHost = + PersistentStorage.get('host:' + host) || this._host; + } + isCacheableHost() { + return this.internalHost.substr(0, 2) === 's-'; + } + isCustomHost() { + return (this._domain !== 'firebaseio.com' && + this._domain !== 'firebaseio-demo.com'); + } + get host() { + return this._host; + } + set host(newHost) { + if (newHost !== this.internalHost) { + this.internalHost = newHost; + if (this.isCacheableHost()) { + PersistentStorage.set('host:' + this._host, this.internalHost); + } + } + } + toString() { + let str = this.toURLString(); + if (this.persistenceKey) { + str += '<' + this.persistenceKey + '>'; + } + return str; + } + toURLString() { + const protocol = this.secure ? 'https://' : 'http://'; + const query = this.includeNamespaceInQueryParams + ? `?ns=${this.namespace}` + : ''; + return `${protocol}${this.host}/${query}`; + } +} +function repoInfoNeedsQueryParam(repoInfo) { + return (repoInfo.host !== repoInfo.internalHost || + repoInfo.isCustomHost() || + repoInfo.includeNamespaceInQueryParams); +} +/** + * Returns the websocket URL for this repo + * @param repoInfo - RepoInfo object + * @param type - of connection + * @param params - list + * @returns The URL for this repo + */ +function repoInfoConnectionURL(repoInfo, type, params) { + util.assert(typeof type === 'string', 'typeof type must == string'); + util.assert(typeof params === 'object', 'typeof params must == object'); + let connURL; + if (type === WEBSOCKET) { + connURL = + (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?'; + } + else if (type === LONG_POLLING) { + connURL = + (repoInfo.secure ? 'https://' : 'http://') + + repoInfo.internalHost + + '/.lp?'; + } + else { + throw new Error('Unknown connection type: ' + type); + } + if (repoInfoNeedsQueryParam(repoInfo)) { + params['ns'] = repoInfo.namespace; + } + const pairs = []; + each(params, (key, value) => { + pairs.push(key + '=' + value); + }); + return connURL + pairs.join('&'); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Tracks a collection of stats. + */ +class StatsCollection { + constructor() { + this.counters_ = {}; + } + incrementCounter(name, amount = 1) { + if (!util.contains(this.counters_, name)) { + this.counters_[name] = 0; + } + this.counters_[name] += amount; + } + get() { + return util.deepCopy(this.counters_); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const collections = {}; +const reporters = {}; +function statsManagerGetCollection(repoInfo) { + const hashString = repoInfo.toString(); + if (!collections[hashString]) { + collections[hashString] = new StatsCollection(); + } + return collections[hashString]; +} +function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) { + const hashString = repoInfo.toString(); + if (!reporters[hashString]) { + reporters[hashString] = creatorFunction(); + } + return reporters[hashString]; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This class ensures the packets from the server arrive in order + * This class takes data from the server and ensures it gets passed into the callbacks in order. + */ +class PacketReceiver { + /** + * @param onMessage_ + */ + constructor(onMessage_) { + this.onMessage_ = onMessage_; + this.pendingResponses = []; + this.currentResponseNum = 0; + this.closeAfterResponse = -1; + this.onClose = null; + } + closeAfter(responseNum, callback) { + this.closeAfterResponse = responseNum; + this.onClose = callback; + if (this.closeAfterResponse < this.currentResponseNum) { + this.onClose(); + this.onClose = null; + } + } + /** + * Each message from the server comes with a response number, and an array of data. The responseNumber + * allows us to ensure that we process them in the right order, since we can't be guaranteed that all + * browsers will respond in the same order as the requests we sent + */ + handleResponse(requestNum, data) { + this.pendingResponses[requestNum] = data; + while (this.pendingResponses[this.currentResponseNum]) { + const toProcess = this.pendingResponses[this.currentResponseNum]; + delete this.pendingResponses[this.currentResponseNum]; + for (let i = 0; i < toProcess.length; ++i) { + if (toProcess[i]) { + exceptionGuard(() => { + this.onMessage_(toProcess[i]); + }); + } + } + if (this.currentResponseNum === this.closeAfterResponse) { + if (this.onClose) { + this.onClose(); + this.onClose = null; + } + break; + } + this.currentResponseNum++; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// URL query parameters associated with longpolling +const FIREBASE_LONGPOLL_START_PARAM = 'start'; +const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close'; +const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand'; +const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB'; +const FIREBASE_LONGPOLL_ID_PARAM = 'id'; +const FIREBASE_LONGPOLL_PW_PARAM = 'pw'; +const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser'; +const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb'; +const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg'; +const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts'; +const FIREBASE_LONGPOLL_DATA_PARAM = 'd'; +const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe'; +//Data size constants. +//TODO: Perf: the maximum length actually differs from browser to browser. +// We should check what browser we're on and set accordingly. +const MAX_URL_DATA_SIZE = 1870; +const SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d= +const MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE; +/** + * Keepalive period + * send a fresh request at minimum every 25 seconds. Opera has a maximum request + * length of 30 seconds that we can't exceed. + */ +const KEEPALIVE_REQUEST_INTERVAL = 25000; +/** + * How long to wait before aborting a long-polling connection attempt. + */ +const LP_CONNECT_TIMEOUT = 30000; +/** + * This class manages a single long-polling connection. + */ +class BrowserPollConnection { + /** + * @param connId An identifier for this connection, used for logging + * @param repoInfo The info for the endpoint to send data to. + * @param applicationId The Firebase App ID for this project. + * @param appCheckToken The AppCheck token for this client. + * @param authToken The AuthToken to use for this connection. + * @param transportSessionId Optional transportSessionid if we are + * reconnecting for an existing transport session + * @param lastSessionId Optional lastSessionId if the PersistentConnection has + * already created a connection previously + */ + constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) { + this.connId = connId; + this.repoInfo = repoInfo; + this.applicationId = applicationId; + this.appCheckToken = appCheckToken; + this.authToken = authToken; + this.transportSessionId = transportSessionId; + this.lastSessionId = lastSessionId; + this.bytesSent = 0; + this.bytesReceived = 0; + this.everConnected_ = false; + this.log_ = logWrapper(connId); + this.stats_ = statsManagerGetCollection(repoInfo); + this.urlFn = (params) => { + // Always add the token if we have one. + if (this.appCheckToken) { + params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken; + } + return repoInfoConnectionURL(repoInfo, LONG_POLLING, params); + }; + } + /** + * @param onMessage - Callback when messages arrive + * @param onDisconnect - Callback with connection lost. + */ + open(onMessage, onDisconnect) { + this.curSegmentNum = 0; + this.onDisconnect_ = onDisconnect; + this.myPacketOrderer = new PacketReceiver(onMessage); + this.isClosed_ = false; + this.connectTimeoutTimer_ = setTimeout(() => { + this.log_('Timed out trying to connect.'); + // Make sure we clear the host cache + this.onClosed_(); + this.connectTimeoutTimer_ = null; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(LP_CONNECT_TIMEOUT)); + // Ensure we delay the creation of the iframe until the DOM is loaded. + executeWhenDOMReady(() => { + if (this.isClosed_) { + return; + } + //Set up a callback that gets triggered once a connection is set up. + this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => { + const [command, arg1, arg2, arg3, arg4] = args; + this.incrementIncomingBytes_(args); + if (!this.scriptTagHolder) { + return; // we closed the connection. + } + if (this.connectTimeoutTimer_) { + clearTimeout(this.connectTimeoutTimer_); + this.connectTimeoutTimer_ = null; + } + this.everConnected_ = true; + if (command === FIREBASE_LONGPOLL_START_PARAM) { + this.id = arg1; + this.password = arg2; + } + else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) { + // Don't clear the host cache. We got a response from the server, so we know it's reachable + if (arg1) { + // We aren't expecting any more data (other than what the server's already in the process of sending us + // through our already open polls), so don't send any more. + this.scriptTagHolder.sendNewPolls = false; + // arg1 in this case is the last response number sent by the server. We should try to receive + // all of the responses up to this one before closing + this.myPacketOrderer.closeAfter(arg1, () => { + this.onClosed_(); + }); + } + else { + this.onClosed_(); + } + } + else { + throw new Error('Unrecognized command received: ' + command); + } + }, (...args) => { + const [pN, data] = args; + this.incrementIncomingBytes_(args); + this.myPacketOrderer.handleResponse(pN, data); + }, () => { + this.onClosed_(); + }, this.urlFn); + //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results + //from cache. + const urlParams = {}; + urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't'; + urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000); + if (this.scriptTagHolder.uniqueCallbackIdentifier) { + urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = + this.scriptTagHolder.uniqueCallbackIdentifier; + } + urlParams[VERSION_PARAM] = PROTOCOL_VERSION; + if (this.transportSessionId) { + urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId; + } + if (this.lastSessionId) { + urlParams[LAST_SESSION_PARAM] = this.lastSessionId; + } + if (this.applicationId) { + urlParams[APPLICATION_ID_PARAM] = this.applicationId; + } + if (this.appCheckToken) { + urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken; + } + if (typeof location !== 'undefined' && + location.hostname && + FORGE_DOMAIN_RE.test(location.hostname)) { + urlParams[REFERER_PARAM] = FORGE_REF; + } + const connectURL = this.urlFn(urlParams); + this.log_('Connecting via long-poll to ' + connectURL); + this.scriptTagHolder.addTag(connectURL, () => { + /* do nothing */ + }); + }); + } + /** + * Call this when a handshake has completed successfully and we want to consider the connection established + */ + start() { + this.scriptTagHolder.startLongPoll(this.id, this.password); + this.addDisconnectPingFrame(this.id, this.password); + } + /** + * Forces long polling to be considered as a potential transport + */ + static forceAllow() { + BrowserPollConnection.forceAllow_ = true; + } + /** + * Forces longpolling to not be considered as a potential transport + */ + static forceDisallow() { + BrowserPollConnection.forceDisallow_ = true; + } + // Static method, use string literal so it can be accessed in a generic way + static isAvailable() { + if (util.isNodeSdk()) { + return false; + } + else if (BrowserPollConnection.forceAllow_) { + return true; + } + else { + // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in + // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08). + return (!BrowserPollConnection.forceDisallow_ && + typeof document !== 'undefined' && + document.createElement != null && + !isChromeExtensionContentScript() && + !isWindowsStoreApp()); + } + } + /** + * No-op for polling + */ + markConnectionHealthy() { } + /** + * Stops polling and cleans up the iframe + */ + shutdown_() { + this.isClosed_ = true; + if (this.scriptTagHolder) { + this.scriptTagHolder.close(); + this.scriptTagHolder = null; + } + //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving. + if (this.myDisconnFrame) { + document.body.removeChild(this.myDisconnFrame); + this.myDisconnFrame = null; + } + if (this.connectTimeoutTimer_) { + clearTimeout(this.connectTimeoutTimer_); + this.connectTimeoutTimer_ = null; + } + } + /** + * Triggered when this transport is closed + */ + onClosed_() { + if (!this.isClosed_) { + this.log_('Longpoll is closing itself'); + this.shutdown_(); + if (this.onDisconnect_) { + this.onDisconnect_(this.everConnected_); + this.onDisconnect_ = null; + } + } + } + /** + * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server + * that we've left. + */ + close() { + if (!this.isClosed_) { + this.log_('Longpoll is being closed.'); + this.shutdown_(); + } + } + /** + * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then + * broken into chunks (since URLs have a small maximum length). + * @param data - The JSON data to transmit. + */ + send(data) { + const dataStr = util.stringify(data); + this.bytesSent += dataStr.length; + this.stats_.incrementCounter('bytes_sent', dataStr.length); + //first, lets get the base64-encoded data + const base64data = util.base64Encode(dataStr); + //We can only fit a certain amount in each URL, so we need to split this request + //up into multiple pieces if it doesn't fit in one request. + const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE); + //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number + //of segments so that we can reassemble the packet on the server. + for (let i = 0; i < dataSegs.length; i++) { + this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]); + this.curSegmentNum++; + } + } + /** + * This is how we notify the server that we're leaving. + * We aren't able to send requests with DHTML on a window close event, but we can + * trigger XHR requests in some browsers (everything but Opera basically). + */ + addDisconnectPingFrame(id, pw) { + if (util.isNodeSdk()) { + return; + } + this.myDisconnFrame = document.createElement('iframe'); + const urlParams = {}; + urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't'; + urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id; + urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw; + this.myDisconnFrame.src = this.urlFn(urlParams); + this.myDisconnFrame.style.display = 'none'; + document.body.appendChild(this.myDisconnFrame); + } + /** + * Used to track the bytes received by this client + */ + incrementIncomingBytes_(args) { + // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in. + const bytesReceived = util.stringify(args).length; + this.bytesReceived += bytesReceived; + this.stats_.incrementCounter('bytes_received', bytesReceived); + } +} +/********************************************************************************************* + * A wrapper around an iframe that is used as a long-polling script holder. + *********************************************************************************************/ +class FirebaseIFrameScriptHolder { + /** + * @param commandCB - The callback to be called when control commands are received from the server. + * @param onMessageCB - The callback to be triggered when responses arrive from the server. + * @param onDisconnect - The callback to be triggered when this tag holder is closed + * @param urlFn - A function that provides the URL of the endpoint to send data to. + */ + constructor(commandCB, onMessageCB, onDisconnect, urlFn) { + this.onDisconnect = onDisconnect; + this.urlFn = urlFn; + //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause + //problems in some browsers. + this.outstandingRequests = new Set(); + //A queue of the pending segments waiting for transmission to the server. + this.pendingSegs = []; + //A serial number. We use this for two things: + // 1) A way to ensure the browser doesn't cache responses to polls + // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The + // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute + // JSONP code in the order it was added to the iframe. + this.currentSerial = Math.floor(Math.random() * 100000000); + // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still + // incoming data from the server that we're waiting for). + this.sendNewPolls = true; + if (!util.isNodeSdk()) { + //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the + //iframes where we put the long-polling script tags. We have two callbacks: + // 1) Command Callback - Triggered for control issues, like starting a connection. + // 2) Message Callback - Triggered when new data arrives. + this.uniqueCallbackIdentifier = LUIDGenerator(); + window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB; + window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = + onMessageCB; + //Create an iframe for us to add script tags to. + this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_(); + // Set the iframe's contents. + let script = ''; + // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient + // for ie9, but ie8 needs to do it again in the document itself. + if (this.myIFrame.src && + this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') { + const currentDomain = document.domain; + script = ''; + } + const iframeContents = '' + script + ''; + try { + this.myIFrame.doc.open(); + this.myIFrame.doc.write(iframeContents); + this.myIFrame.doc.close(); + } + catch (e) { + log('frame writing exception'); + if (e.stack) { + log(e.stack); + } + log(e); + } + } + else { + this.commandCB = commandCB; + this.onMessageCB = onMessageCB; + } + } + /** + * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can + * actually use. + */ + static createIFrame_() { + const iframe = document.createElement('iframe'); + iframe.style.display = 'none'; + // This is necessary in order to initialize the document inside the iframe + if (document.body) { + document.body.appendChild(iframe); + try { + // If document.domain has been modified in IE, this will throw an error, and we need to set the + // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute + // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work. + const a = iframe.contentWindow.document; + if (!a) { + // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above. + log('No IE domain setting required'); + } + } + catch (e) { + const domain = document.domain; + iframe.src = + "javascript:void((function(){document.open();document.domain='" + + domain + + "';document.close();})())"; + } + } + else { + // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this + // never gets hit. + throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.'; + } + // Get the document of the iframe in a browser-specific way. + if (iframe.contentDocument) { + iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari + } + else if (iframe.contentWindow) { + iframe.doc = iframe.contentWindow.document; // Internet Explorer + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (iframe.document) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + iframe.doc = iframe.document; //others? + } + return iframe; + } + /** + * Cancel all outstanding queries and remove the frame. + */ + close() { + //Mark this iframe as dead, so no new requests are sent. + this.alive = false; + if (this.myIFrame) { + //We have to actually remove all of the html inside this iframe before removing it from the + //window, or IE will continue loading and executing the script tags we've already added, which + //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this. + this.myIFrame.doc.body.textContent = ''; + setTimeout(() => { + if (this.myIFrame !== null) { + document.body.removeChild(this.myIFrame); + this.myIFrame = null; + } + }, Math.floor(0)); + } + // Protect from being called recursively. + const onDisconnect = this.onDisconnect; + if (onDisconnect) { + this.onDisconnect = null; + onDisconnect(); + } + } + /** + * Actually start the long-polling session by adding the first script tag(s) to the iframe. + * @param id - The ID of this connection + * @param pw - The password for this connection + */ + startLongPoll(id, pw) { + this.myID = id; + this.myPW = pw; + this.alive = true; + //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to. + while (this.newRequest_()) { } + } + /** + * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't + * too many outstanding requests and we are still alive. + * + * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if + * needed. + */ + newRequest_() { + // We keep one outstanding request open all the time to receive data, but if we need to send data + // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically + // close the old request. + if (this.alive && + this.sendNewPolls && + this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) { + //construct our url + this.currentSerial++; + const urlParams = {}; + urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID; + urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW; + urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial; + let theURL = this.urlFn(urlParams); + //Now add as much data as we can. + let curDataString = ''; + let i = 0; + while (this.pendingSegs.length > 0) { + //first, lets see if the next segment will fit. + const nextSeg = this.pendingSegs[0]; + if (nextSeg.d.length + + SEG_HEADER_SIZE + + curDataString.length <= + MAX_URL_DATA_SIZE) { + //great, the segment will fit. Lets append it. + const theSeg = this.pendingSegs.shift(); + curDataString = + curDataString + + '&' + + FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM + + i + + '=' + + theSeg.seg + + '&' + + FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET + + i + + '=' + + theSeg.ts + + '&' + + FIREBASE_LONGPOLL_DATA_PARAM + + i + + '=' + + theSeg.d; + i++; + } + else { + break; + } + } + theURL = theURL + curDataString; + this.addLongPollTag_(theURL, this.currentSerial); + return true; + } + else { + return false; + } + } + /** + * Queue a packet for transmission to the server. + * @param segnum - A sequential id for this packet segment used for reassembly + * @param totalsegs - The total number of segments in this packet + * @param data - The data for this segment. + */ + enqueueSegment(segnum, totalsegs, data) { + //add this to the queue of segments to send. + this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data }); + //send the data immediately if there isn't already data being transmitted, unless + //startLongPoll hasn't been called yet. + if (this.alive) { + this.newRequest_(); + } + } + /** + * Add a script tag for a regular long-poll request. + * @param url - The URL of the script tag. + * @param serial - The serial number of the request. + */ + addLongPollTag_(url, serial) { + //remember that we sent this request. + this.outstandingRequests.add(serial); + const doNewRequest = () => { + this.outstandingRequests.delete(serial); + this.newRequest_(); + }; + // If this request doesn't return on its own accord (by the server sending us some data), we'll + // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open. + const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL)); + const readyStateCB = () => { + // Request completed. Cancel the keepalive. + clearTimeout(keepaliveTimeout); + // Trigger a new request so we can continue receiving data. + doNewRequest(); + }; + this.addTag(url, readyStateCB); + } + /** + * Add an arbitrary script tag to the iframe. + * @param url - The URL for the script tag source. + * @param loadCB - A callback to be triggered once the script has loaded. + */ + addTag(url, loadCB) { + if (util.isNodeSdk()) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.doNodeLongPoll(url, loadCB); + } + else { + setTimeout(() => { + try { + // if we're already closed, don't add this poll + if (!this.sendNewPolls) { + return; + } + const newScript = this.myIFrame.doc.createElement('script'); + newScript.type = 'text/javascript'; + newScript.async = true; + newScript.src = url; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + newScript.onload = newScript.onreadystatechange = + function () { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const rstate = newScript.readyState; + if (!rstate || rstate === 'loaded' || rstate === 'complete') { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + newScript.onload = newScript.onreadystatechange = null; + if (newScript.parentNode) { + newScript.parentNode.removeChild(newScript); + } + loadCB(); + } + }; + newScript.onerror = () => { + log('Long-poll script failed to load: ' + url); + this.sendNewPolls = false; + this.close(); + }; + this.myIFrame.doc.body.appendChild(newScript); + } + catch (e) { + // TODO: we should make this error visible somehow + } + }, Math.floor(1)); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const WEBSOCKET_MAX_FRAME_SIZE = 16384; +const WEBSOCKET_KEEPALIVE_INTERVAL = 45000; +let WebSocketImpl = null; +if (typeof MozWebSocket !== 'undefined') { + WebSocketImpl = MozWebSocket; +} +else if (typeof WebSocket !== 'undefined') { + WebSocketImpl = WebSocket; +} +/** + * Create a new websocket connection with the given callbacks. + */ +class WebSocketConnection { + /** + * @param connId identifier for this transport + * @param repoInfo The info for the websocket endpoint. + * @param applicationId The Firebase App ID for this project. + * @param appCheckToken The App Check Token for this client. + * @param authToken The Auth Token for this client. + * @param transportSessionId Optional transportSessionId if this is connecting + * to an existing transport session + * @param lastSessionId Optional lastSessionId if there was a previous + * connection + */ + constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) { + this.connId = connId; + this.applicationId = applicationId; + this.appCheckToken = appCheckToken; + this.authToken = authToken; + this.keepaliveTimer = null; + this.frames = null; + this.totalFrames = 0; + this.bytesSent = 0; + this.bytesReceived = 0; + this.log_ = logWrapper(this.connId); + this.stats_ = statsManagerGetCollection(repoInfo); + this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId); + this.nodeAdmin = repoInfo.nodeAdmin; + } + /** + * @param repoInfo - The info for the websocket endpoint. + * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport + * session + * @param lastSessionId - Optional lastSessionId if there was a previous connection + * @returns connection url + */ + static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) { + const urlParams = {}; + urlParams[VERSION_PARAM] = PROTOCOL_VERSION; + if (!util.isNodeSdk() && + typeof location !== 'undefined' && + location.hostname && + FORGE_DOMAIN_RE.test(location.hostname)) { + urlParams[REFERER_PARAM] = FORGE_REF; + } + if (transportSessionId) { + urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId; + } + if (lastSessionId) { + urlParams[LAST_SESSION_PARAM] = lastSessionId; + } + if (appCheckToken) { + urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken; + } + if (applicationId) { + urlParams[APPLICATION_ID_PARAM] = applicationId; + } + return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams); + } + /** + * @param onMessage - Callback when messages arrive + * @param onDisconnect - Callback with connection lost. + */ + open(onMessage, onDisconnect) { + this.onDisconnect = onDisconnect; + this.onMessage = onMessage; + this.log_('Websocket connecting to ' + this.connURL); + this.everConnected_ = false; + // Assume failure until proven otherwise. + PersistentStorage.set('previous_websocket_failure', true); + try { + let options; + if (util.isNodeSdk()) { + const device = this.nodeAdmin ? 'AdminNode' : 'Node'; + // UA Format: Firebase//// + options = { + headers: { + 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`, + 'X-Firebase-GMPID': this.applicationId || '' + } + }; + // If using Node with admin creds, AppCheck-related checks are unnecessary. + // Note that we send the credentials here even if they aren't admin credentials, which is + // not a problem. + // Note that this header is just used to bypass appcheck, and the token should still be sent + // through the websocket connection once it is established. + if (this.authToken) { + options.headers['Authorization'] = `Bearer ${this.authToken}`; + } + if (this.appCheckToken) { + options.headers['X-Firebase-AppCheck'] = this.appCheckToken; + } + // Plumb appropriate http_proxy environment variable into faye-websocket if it exists. + const env = process['env']; + const proxy = this.connURL.indexOf('wss://') === 0 + ? env['HTTPS_PROXY'] || env['https_proxy'] + : env['HTTP_PROXY'] || env['http_proxy']; + if (proxy) { + options['proxy'] = { origin: proxy }; + } + } + this.mySock = new WebSocketImpl(this.connURL, [], options); + } + catch (e) { + this.log_('Error instantiating WebSocket.'); + const error = e.message || e.data; + if (error) { + this.log_(error); + } + this.onClosed_(); + return; + } + this.mySock.onopen = () => { + this.log_('Websocket connected.'); + this.everConnected_ = true; + }; + this.mySock.onclose = () => { + this.log_('Websocket connection was disconnected.'); + this.mySock = null; + this.onClosed_(); + }; + this.mySock.onmessage = m => { + this.handleIncomingFrame(m); + }; + this.mySock.onerror = e => { + this.log_('WebSocket error. Closing connection.'); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const error = e.message || e.data; + if (error) { + this.log_(error); + } + this.onClosed_(); + }; + } + /** + * No-op for websockets, we don't need to do anything once the connection is confirmed as open + */ + start() { } + static forceDisallow() { + WebSocketConnection.forceDisallow_ = true; + } + static isAvailable() { + let isOldAndroid = false; + if (typeof navigator !== 'undefined' && navigator.userAgent) { + const oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/; + const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex); + if (oldAndroidMatch && oldAndroidMatch.length > 1) { + if (parseFloat(oldAndroidMatch[1]) < 4.4) { + isOldAndroid = true; + } + } + } + return (!isOldAndroid && + WebSocketImpl !== null && + !WebSocketConnection.forceDisallow_); + } + /** + * Returns true if we previously failed to connect with this transport. + */ + static previouslyFailed() { + // If our persistent storage is actually only in-memory storage, + // we default to assuming that it previously failed to be safe. + return (PersistentStorage.isInMemoryStorage || + PersistentStorage.get('previous_websocket_failure') === true); + } + markConnectionHealthy() { + PersistentStorage.remove('previous_websocket_failure'); + } + appendFrame_(data) { + this.frames.push(data); + if (this.frames.length === this.totalFrames) { + const fullMess = this.frames.join(''); + this.frames = null; + const jsonMess = util.jsonEval(fullMess); + //handle the message + this.onMessage(jsonMess); + } + } + /** + * @param frameCount - The number of frames we are expecting from the server + */ + handleNewFrameCount_(frameCount) { + this.totalFrames = frameCount; + this.frames = []; + } + /** + * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1 + * @returns Any remaining data to be process, or null if there is none + */ + extractFrameCount_(data) { + util.assert(this.frames === null, 'We already have a frame buffer'); + // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced + // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508 + if (data.length <= 6) { + const frameCount = Number(data); + if (!isNaN(frameCount)) { + this.handleNewFrameCount_(frameCount); + return null; + } + } + this.handleNewFrameCount_(1); + return data; + } + /** + * Process a websocket frame that has arrived from the server. + * @param mess - The frame data + */ + handleIncomingFrame(mess) { + if (this.mySock === null) { + return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes. + } + const data = mess['data']; + this.bytesReceived += data.length; + this.stats_.incrementCounter('bytes_received', data.length); + this.resetKeepAlive(); + if (this.frames !== null) { + // we're buffering + this.appendFrame_(data); + } + else { + // try to parse out a frame count, otherwise, assume 1 and process it + const remainingData = this.extractFrameCount_(data); + if (remainingData !== null) { + this.appendFrame_(remainingData); + } + } + } + /** + * Send a message to the server + * @param data - The JSON object to transmit + */ + send(data) { + this.resetKeepAlive(); + const dataStr = util.stringify(data); + this.bytesSent += dataStr.length; + this.stats_.incrementCounter('bytes_sent', dataStr.length); + //We can only fit a certain amount in each websocket frame, so we need to split this request + //up into multiple pieces if it doesn't fit in one request. + const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE); + //Send the length header + if (dataSegs.length > 1) { + this.sendString_(String(dataSegs.length)); + } + //Send the actual data in segments. + for (let i = 0; i < dataSegs.length; i++) { + this.sendString_(dataSegs[i]); + } + } + shutdown_() { + this.isClosed_ = true; + if (this.keepaliveTimer) { + clearInterval(this.keepaliveTimer); + this.keepaliveTimer = null; + } + if (this.mySock) { + this.mySock.close(); + this.mySock = null; + } + } + onClosed_() { + if (!this.isClosed_) { + this.log_('WebSocket is closing itself'); + this.shutdown_(); + // since this is an internal close, trigger the close listener + if (this.onDisconnect) { + this.onDisconnect(this.everConnected_); + this.onDisconnect = null; + } + } + } + /** + * External-facing close handler. + * Close the websocket and kill the connection. + */ + close() { + if (!this.isClosed_) { + this.log_('WebSocket is being closed'); + this.shutdown_(); + } + } + /** + * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after + * the last activity. + */ + resetKeepAlive() { + clearInterval(this.keepaliveTimer); + this.keepaliveTimer = setInterval(() => { + //If there has been no websocket activity for a while, send a no-op + if (this.mySock) { + this.sendString_('0'); + } + this.resetKeepAlive(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL)); + } + /** + * Send a string over the websocket. + * + * @param str - String to send. + */ + sendString_(str) { + // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send() + // calls for some unknown reason. We treat these as an error and disconnect. + // See https://app.asana.com/0/58926111402292/68021340250410 + try { + this.mySock.send(str); + } + catch (e) { + this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.'); + setTimeout(this.onClosed_.bind(this), 0); + } + } +} +/** + * Number of response before we consider the connection "healthy." + */ +WebSocketConnection.responsesRequiredToBeHealthy = 2; +/** + * Time to wait for the connection te become healthy before giving up. + */ +WebSocketConnection.healthyTimeout = 30000; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Currently simplistic, this class manages what transport a Connection should use at various stages of its + * lifecycle. + * + * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if + * they are available. + */ +class TransportManager { + static get ALL_TRANSPORTS() { + return [BrowserPollConnection, WebSocketConnection]; + } + /** + * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after + * TransportManager has already set up transports_ + */ + static get IS_TRANSPORT_INITIALIZED() { + return this.globalTransportInitialized_; + } + /** + * @param repoInfo - Metadata around the namespace we're connecting to + */ + constructor(repoInfo) { + this.initTransports_(repoInfo); + } + initTransports_(repoInfo) { + const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable'](); + let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed(); + if (repoInfo.webSocketOnly) { + if (!isWebSocketsAvailable) { + warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway."); + } + isSkipPollConnection = true; + } + if (isSkipPollConnection) { + this.transports_ = [WebSocketConnection]; + } + else { + const transports = (this.transports_ = []); + for (const transport of TransportManager.ALL_TRANSPORTS) { + if (transport && transport['isAvailable']()) { + transports.push(transport); + } + } + TransportManager.globalTransportInitialized_ = true; + } + } + /** + * @returns The constructor for the initial transport to use + */ + initialTransport() { + if (this.transports_.length > 0) { + return this.transports_[0]; + } + else { + throw new Error('No transports available'); + } + } + /** + * @returns The constructor for the next transport, or null + */ + upgradeTransport() { + if (this.transports_.length > 1) { + return this.transports_[1]; + } + else { + return null; + } + } +} +// Keeps track of whether the TransportManager has already chosen a transport to use +TransportManager.globalTransportInitialized_ = false; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Abort upgrade attempt if it takes longer than 60s. +const UPGRADE_TIMEOUT = 60000; +// For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses. +// If we haven't sent enough requests within 5s, we'll start sending noop ping requests. +const DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000; +// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data) +// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout +// but we've sent/received enough bytes, we don't cancel the connection. +const BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024; +const BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024; +const MESSAGE_TYPE = 't'; +const MESSAGE_DATA = 'd'; +const CONTROL_SHUTDOWN = 's'; +const CONTROL_RESET = 'r'; +const CONTROL_ERROR = 'e'; +const CONTROL_PONG = 'o'; +const SWITCH_ACK = 'a'; +const END_TRANSMISSION = 'n'; +const PING = 'p'; +const SERVER_HELLO = 'h'; +/** + * Creates a new real-time connection to the server using whichever method works + * best in the current browser. + */ +class Connection { + /** + * @param id - an id for this connection + * @param repoInfo_ - the info for the endpoint to connect to + * @param applicationId_ - the Firebase App ID for this project + * @param appCheckToken_ - The App Check Token for this device. + * @param authToken_ - The auth token for this session. + * @param onMessage_ - the callback to be triggered when a server-push message arrives + * @param onReady_ - the callback to be triggered when this connection is ready to send messages. + * @param onDisconnect_ - the callback to be triggered when a connection was lost + * @param onKill_ - the callback to be triggered when this connection has permanently shut down. + * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server + */ + constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) { + this.id = id; + this.repoInfo_ = repoInfo_; + this.applicationId_ = applicationId_; + this.appCheckToken_ = appCheckToken_; + this.authToken_ = authToken_; + this.onMessage_ = onMessage_; + this.onReady_ = onReady_; + this.onDisconnect_ = onDisconnect_; + this.onKill_ = onKill_; + this.lastSessionId = lastSessionId; + this.connectionCount = 0; + this.pendingDataMessages = []; + this.state_ = 0 /* RealtimeState.CONNECTING */; + this.log_ = logWrapper('c:' + this.id + ':'); + this.transportManager_ = new TransportManager(repoInfo_); + this.log_('Connection created'); + this.start_(); + } + /** + * Starts a connection attempt + */ + start_() { + const conn = this.transportManager_.initialTransport(); + this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId); + // For certain transports (WebSockets), we need to send and receive several messages back and forth before we + // can consider the transport healthy. + this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0; + const onMessageReceived = this.connReceiver_(this.conn_); + const onConnectionLost = this.disconnReceiver_(this.conn_); + this.tx_ = this.conn_; + this.rx_ = this.conn_; + this.secondaryConn_ = null; + this.isHealthy_ = false; + /* + * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame. + * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset. + * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should + * still have the context of your originating frame. + */ + setTimeout(() => { + // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it + this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost); + }, Math.floor(0)); + const healthyTimeoutMS = conn['healthyTimeout'] || 0; + if (healthyTimeoutMS > 0) { + this.healthyTimeout_ = setTimeoutNonBlocking(() => { + this.healthyTimeout_ = null; + if (!this.isHealthy_) { + if (this.conn_ && + this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) { + this.log_('Connection exceeded healthy timeout but has received ' + + this.conn_.bytesReceived + + ' bytes. Marking connection healthy.'); + this.isHealthy_ = true; + this.conn_.markConnectionHealthy(); + } + else if (this.conn_ && + this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) { + this.log_('Connection exceeded healthy timeout but has sent ' + + this.conn_.bytesSent + + ' bytes. Leaving connection alive.'); + // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to + // the server. + } + else { + this.log_('Closing unhealthy connection after timeout.'); + this.close(); + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(healthyTimeoutMS)); + } + } + nextTransportId_() { + return 'c:' + this.id + ':' + this.connectionCount++; + } + disconnReceiver_(conn) { + return everConnected => { + if (conn === this.conn_) { + this.onConnectionLost_(everConnected); + } + else if (conn === this.secondaryConn_) { + this.log_('Secondary connection lost.'); + this.onSecondaryConnectionLost_(); + } + else { + this.log_('closing an old connection'); + } + }; + } + connReceiver_(conn) { + return (message) => { + if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) { + if (conn === this.rx_) { + this.onPrimaryMessageReceived_(message); + } + else if (conn === this.secondaryConn_) { + this.onSecondaryMessageReceived_(message); + } + else { + this.log_('message on old connection'); + } + } + }; + } + /** + * @param dataMsg - An arbitrary data message to be sent to the server + */ + sendRequest(dataMsg) { + // wrap in a data message envelope and send it on + const msg = { t: 'd', d: dataMsg }; + this.sendData_(msg); + } + tryCleanupConnection() { + if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) { + this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId); + this.conn_ = this.secondaryConn_; + this.secondaryConn_ = null; + // the server will shutdown the old connection + } + } + onSecondaryControl_(controlData) { + if (MESSAGE_TYPE in controlData) { + const cmd = controlData[MESSAGE_TYPE]; + if (cmd === SWITCH_ACK) { + this.upgradeIfSecondaryHealthy_(); + } + else if (cmd === CONTROL_RESET) { + // Most likely the session wasn't valid. Abandon the switch attempt + this.log_('Got a reset on secondary, closing it'); + this.secondaryConn_.close(); + // If we were already using this connection for something, than we need to fully close + if (this.tx_ === this.secondaryConn_ || + this.rx_ === this.secondaryConn_) { + this.close(); + } + } + else if (cmd === CONTROL_PONG) { + this.log_('got pong on secondary.'); + this.secondaryResponsesRequired_--; + this.upgradeIfSecondaryHealthy_(); + } + } + } + onSecondaryMessageReceived_(parsedData) { + const layer = requireKey('t', parsedData); + const data = requireKey('d', parsedData); + if (layer === 'c') { + this.onSecondaryControl_(data); + } + else if (layer === 'd') { + // got a data message, but we're still second connection. Need to buffer it up + this.pendingDataMessages.push(data); + } + else { + throw new Error('Unknown protocol layer: ' + layer); + } + } + upgradeIfSecondaryHealthy_() { + if (this.secondaryResponsesRequired_ <= 0) { + this.log_('Secondary connection is healthy.'); + this.isHealthy_ = true; + this.secondaryConn_.markConnectionHealthy(); + this.proceedWithUpgrade_(); + } + else { + // Send a ping to make sure the connection is healthy. + this.log_('sending ping on secondary.'); + this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } }); + } + } + proceedWithUpgrade_() { + // tell this connection to consider itself open + this.secondaryConn_.start(); + // send ack + this.log_('sending client ack on secondary'); + this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } }); + // send end packet on primary transport, switch to sending on this one + // can receive on this one, buffer responses until end received on primary transport + this.log_('Ending transmission on primary'); + this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } }); + this.tx_ = this.secondaryConn_; + this.tryCleanupConnection(); + } + onPrimaryMessageReceived_(parsedData) { + // Must refer to parsedData properties in quotes, so closure doesn't touch them. + const layer = requireKey('t', parsedData); + const data = requireKey('d', parsedData); + if (layer === 'c') { + this.onControl_(data); + } + else if (layer === 'd') { + this.onDataMessage_(data); + } + } + onDataMessage_(message) { + this.onPrimaryResponse_(); + // We don't do anything with data messages, just kick them up a level + this.onMessage_(message); + } + onPrimaryResponse_() { + if (!this.isHealthy_) { + this.primaryResponsesRequired_--; + if (this.primaryResponsesRequired_ <= 0) { + this.log_('Primary connection is healthy.'); + this.isHealthy_ = true; + this.conn_.markConnectionHealthy(); + } + } + } + onControl_(controlData) { + const cmd = requireKey(MESSAGE_TYPE, controlData); + if (MESSAGE_DATA in controlData) { + const payload = controlData[MESSAGE_DATA]; + if (cmd === SERVER_HELLO) { + const handshakePayload = { + ...payload + }; + if (this.repoInfo_.isUsingEmulator) { + // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes. + handshakePayload.h = this.repoInfo_.host; + } + this.onHandshake_(handshakePayload); + } + else if (cmd === END_TRANSMISSION) { + this.log_('recvd end transmission on primary'); + this.rx_ = this.secondaryConn_; + for (let i = 0; i < this.pendingDataMessages.length; ++i) { + this.onDataMessage_(this.pendingDataMessages[i]); + } + this.pendingDataMessages = []; + this.tryCleanupConnection(); + } + else if (cmd === CONTROL_SHUTDOWN) { + // This was previously the 'onKill' callback passed to the lower-level connection + // payload in this case is the reason for the shutdown. Generally a human-readable error + this.onConnectionShutdown_(payload); + } + else if (cmd === CONTROL_RESET) { + // payload in this case is the host we should contact + this.onReset_(payload); + } + else if (cmd === CONTROL_ERROR) { + error('Server Error: ' + payload); + } + else if (cmd === CONTROL_PONG) { + this.log_('got pong on primary.'); + this.onPrimaryResponse_(); + this.sendPingOnPrimaryIfNecessary_(); + } + else { + error('Unknown control packet command: ' + cmd); + } + } + } + /** + * @param handshake - The handshake data returned from the server + */ + onHandshake_(handshake) { + const timestamp = handshake.ts; + const version = handshake.v; + const host = handshake.h; + this.sessionId = handshake.s; + this.repoInfo_.host = host; + // if we've already closed the connection, then don't bother trying to progress further + if (this.state_ === 0 /* RealtimeState.CONNECTING */) { + this.conn_.start(); + this.onConnectionEstablished_(this.conn_, timestamp); + if (PROTOCOL_VERSION !== version) { + warn('Protocol version mismatch detected'); + } + // TODO: do we want to upgrade? when? maybe a delay? + this.tryStartUpgrade_(); + } + } + tryStartUpgrade_() { + const conn = this.transportManager_.upgradeTransport(); + if (conn) { + this.startUpgrade_(conn); + } + } + startUpgrade_(conn) { + this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId); + // For certain transports (WebSockets), we need to send and receive several messages back and forth before we + // can consider the transport healthy. + this.secondaryResponsesRequired_ = + conn['responsesRequiredToBeHealthy'] || 0; + const onMessage = this.connReceiver_(this.secondaryConn_); + const onDisconnect = this.disconnReceiver_(this.secondaryConn_); + this.secondaryConn_.open(onMessage, onDisconnect); + // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary. + setTimeoutNonBlocking(() => { + if (this.secondaryConn_) { + this.log_('Timed out trying to upgrade.'); + this.secondaryConn_.close(); + } + }, Math.floor(UPGRADE_TIMEOUT)); + } + onReset_(host) { + this.log_('Reset packet received. New host: ' + host); + this.repoInfo_.host = host; + // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up. + // We don't currently support resets after the connection has already been established + if (this.state_ === 1 /* RealtimeState.CONNECTED */) { + this.close(); + } + else { + // Close whatever connections we have open and start again. + this.closeConnections_(); + this.start_(); + } + } + onConnectionEstablished_(conn, timestamp) { + this.log_('Realtime connection established.'); + this.conn_ = conn; + this.state_ = 1 /* RealtimeState.CONNECTED */; + if (this.onReady_) { + this.onReady_(timestamp, this.sessionId); + this.onReady_ = null; + } + // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy, + // send some pings. + if (this.primaryResponsesRequired_ === 0) { + this.log_('Primary connection is healthy.'); + this.isHealthy_ = true; + } + else { + setTimeoutNonBlocking(() => { + this.sendPingOnPrimaryIfNecessary_(); + }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS)); + } + } + sendPingOnPrimaryIfNecessary_() { + // If the connection isn't considered healthy yet, we'll send a noop ping packet request. + if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) { + this.log_('sending ping on primary.'); + this.sendData_({ t: 'c', d: { t: PING, d: {} } }); + } + } + onSecondaryConnectionLost_() { + const conn = this.secondaryConn_; + this.secondaryConn_ = null; + if (this.tx_ === conn || this.rx_ === conn) { + // we are relying on this connection already in some capacity. Therefore, a failure is real + this.close(); + } + } + /** + * @param everConnected - Whether or not the connection ever reached a server. Used to determine if + * we should flush the host cache + */ + onConnectionLost_(everConnected) { + this.conn_ = null; + // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting + // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess. + if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) { + this.log_('Realtime connection failed.'); + // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away + if (this.repoInfo_.isCacheableHost()) { + PersistentStorage.remove('host:' + this.repoInfo_.host); + // reset the internal host to what we would show the user, i.e. .firebaseio.com + this.repoInfo_.internalHost = this.repoInfo_.host; + } + } + else if (this.state_ === 1 /* RealtimeState.CONNECTED */) { + this.log_('Realtime connection lost.'); + } + this.close(); + } + onConnectionShutdown_(reason) { + this.log_('Connection shutdown command received. Shutting down...'); + if (this.onKill_) { + this.onKill_(reason); + this.onKill_ = null; + } + // We intentionally don't want to fire onDisconnect (kill is a different case), + // so clear the callback. + this.onDisconnect_ = null; + this.close(); + } + sendData_(data) { + if (this.state_ !== 1 /* RealtimeState.CONNECTED */) { + throw 'Connection is not connected'; + } + else { + this.tx_.send(data); + } + } + /** + * Cleans up this connection, calling the appropriate callbacks + */ + close() { + if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) { + this.log_('Closing realtime connection.'); + this.state_ = 2 /* RealtimeState.DISCONNECTED */; + this.closeConnections_(); + if (this.onDisconnect_) { + this.onDisconnect_(); + this.onDisconnect_ = null; + } + } + } + closeConnections_() { + this.log_('Shutting down all connections'); + if (this.conn_) { + this.conn_.close(); + this.conn_ = null; + } + if (this.secondaryConn_) { + this.secondaryConn_.close(); + this.secondaryConn_ = null; + } + if (this.healthyTimeout_) { + clearTimeout(this.healthyTimeout_); + this.healthyTimeout_ = null; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Interface defining the set of actions that can be performed against the Firebase server + * (basically corresponds to our wire protocol). + * + * @interface + */ +class ServerActions { + put(pathString, data, onComplete, hash) { } + merge(pathString, data, onComplete, hash) { } + /** + * Refreshes the auth token for the current connection. + * @param token - The authentication token + */ + refreshAuthToken(token) { } + /** + * Refreshes the app check token for the current connection. + * @param token The app check token + */ + refreshAppCheckToken(token) { } + onDisconnectPut(pathString, data, onComplete) { } + onDisconnectMerge(pathString, data, onComplete) { } + onDisconnectCancel(pathString, onComplete) { } + reportStats(stats) { } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Base class to be used if you want to emit events. Call the constructor with + * the set of allowed event names. + */ +class EventEmitter { + constructor(allowedEvents_) { + this.allowedEvents_ = allowedEvents_; + this.listeners_ = {}; + util.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array'); + } + /** + * To be called by derived classes to trigger events. + */ + trigger(eventType, ...varArgs) { + if (Array.isArray(this.listeners_[eventType])) { + // Clone the list, since callbacks could add/remove listeners. + const listeners = [...this.listeners_[eventType]]; + for (let i = 0; i < listeners.length; i++) { + listeners[i].callback.apply(listeners[i].context, varArgs); + } + } + } + on(eventType, callback, context) { + this.validateEventType_(eventType); + this.listeners_[eventType] = this.listeners_[eventType] || []; + this.listeners_[eventType].push({ callback, context }); + const eventData = this.getInitialEvent(eventType); + if (eventData) { + callback.apply(context, eventData); + } + } + off(eventType, callback, context) { + this.validateEventType_(eventType); + const listeners = this.listeners_[eventType] || []; + for (let i = 0; i < listeners.length; i++) { + if (listeners[i].callback === callback && + (!context || context === listeners[i].context)) { + listeners.splice(i, 1); + return; + } + } + } + validateEventType_(eventType) { + util.assert(this.allowedEvents_.find(et => { + return et === eventType; + }), 'Unknown event: ' + eventType); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Monitors online state (as reported by window.online/offline events). + * + * The expectation is that this could have many false positives (thinks we are online + * when we're not), but no false negatives. So we can safely use it to determine when + * we definitely cannot reach the internet. + */ +class OnlineMonitor extends EventEmitter { + static getInstance() { + return new OnlineMonitor(); + } + constructor() { + super(['online']); + this.online_ = true; + // We've had repeated complaints that Cordova apps can get stuck "offline", e.g. + // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810 + // It would seem that the 'online' event does not always fire consistently. So we disable it + // for Cordova. + if (typeof window !== 'undefined' && + typeof window.addEventListener !== 'undefined' && + !util.isMobileCordova()) { + window.addEventListener('online', () => { + if (!this.online_) { + this.online_ = true; + this.trigger('online', true); + } + }, false); + window.addEventListener('offline', () => { + if (this.online_) { + this.online_ = false; + this.trigger('online', false); + } + }, false); + } + } + getInitialEvent(eventType) { + util.assert(eventType === 'online', 'Unknown event type: ' + eventType); + return [this.online_]; + } + currentlyOnline() { + return this.online_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Maximum key depth. */ +const MAX_PATH_DEPTH = 32; +/** Maximum number of (UTF8) bytes in a Firebase path. */ +const MAX_PATH_LENGTH_BYTES = 768; +/** + * An immutable object representing a parsed path. It's immutable so that you + * can pass them around to other functions without worrying about them changing + * it. + */ +class Path { + /** + * @param pathOrString - Path string to parse, or another path, or the raw + * tokens array + */ + constructor(pathOrString, pieceNum) { + if (pieceNum === void 0) { + this.pieces_ = pathOrString.split('/'); + // Remove empty pieces. + let copyTo = 0; + for (let i = 0; i < this.pieces_.length; i++) { + if (this.pieces_[i].length > 0) { + this.pieces_[copyTo] = this.pieces_[i]; + copyTo++; + } + } + this.pieces_.length = copyTo; + this.pieceNum_ = 0; + } + else { + this.pieces_ = pathOrString; + this.pieceNum_ = pieceNum; + } + } + toString() { + let pathString = ''; + for (let i = this.pieceNum_; i < this.pieces_.length; i++) { + if (this.pieces_[i] !== '') { + pathString += '/' + this.pieces_[i]; + } + } + return pathString || '/'; + } +} +function newEmptyPath() { + return new Path(''); +} +function pathGetFront(path) { + if (path.pieceNum_ >= path.pieces_.length) { + return null; + } + return path.pieces_[path.pieceNum_]; +} +/** + * @returns The number of segments in this path + */ +function pathGetLength(path) { + return path.pieces_.length - path.pieceNum_; +} +function pathPopFront(path) { + let pieceNum = path.pieceNum_; + if (pieceNum < path.pieces_.length) { + pieceNum++; + } + return new Path(path.pieces_, pieceNum); +} +function pathGetBack(path) { + if (path.pieceNum_ < path.pieces_.length) { + return path.pieces_[path.pieces_.length - 1]; + } + return null; +} +function pathToUrlEncodedString(path) { + let pathString = ''; + for (let i = path.pieceNum_; i < path.pieces_.length; i++) { + if (path.pieces_[i] !== '') { + pathString += '/' + encodeURIComponent(String(path.pieces_[i])); + } + } + return pathString || '/'; +} +/** + * Shallow copy of the parts of the path. + * + */ +function pathSlice(path, begin = 0) { + return path.pieces_.slice(path.pieceNum_ + begin); +} +function pathParent(path) { + if (path.pieceNum_ >= path.pieces_.length) { + return null; + } + const pieces = []; + for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) { + pieces.push(path.pieces_[i]); + } + return new Path(pieces, 0); +} +function pathChild(path, childPathObj) { + const pieces = []; + for (let i = path.pieceNum_; i < path.pieces_.length; i++) { + pieces.push(path.pieces_[i]); + } + if (childPathObj instanceof Path) { + for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) { + pieces.push(childPathObj.pieces_[i]); + } + } + else { + const childPieces = childPathObj.split('/'); + for (let i = 0; i < childPieces.length; i++) { + if (childPieces[i].length > 0) { + pieces.push(childPieces[i]); + } + } + } + return new Path(pieces, 0); +} +/** + * @returns True if there are no segments in this path + */ +function pathIsEmpty(path) { + return path.pieceNum_ >= path.pieces_.length; +} +/** + * @returns The path from outerPath to innerPath + */ +function newRelativePath(outerPath, innerPath) { + const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath); + if (outer === null) { + return innerPath; + } + else if (outer === inner) { + return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath)); + } + else { + throw new Error('INTERNAL ERROR: innerPath (' + + innerPath + + ') is not within ' + + 'outerPath (' + + outerPath + + ')'); + } +} +/** + * @returns -1, 0, 1 if left is less, equal, or greater than the right. + */ +function pathCompare(left, right) { + const leftKeys = pathSlice(left, 0); + const rightKeys = pathSlice(right, 0); + for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) { + const cmp = nameCompare(leftKeys[i], rightKeys[i]); + if (cmp !== 0) { + return cmp; + } + } + if (leftKeys.length === rightKeys.length) { + return 0; + } + return leftKeys.length < rightKeys.length ? -1 : 1; +} +/** + * @returns true if paths are the same. + */ +function pathEquals(path, other) { + if (pathGetLength(path) !== pathGetLength(other)) { + return false; + } + for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) { + if (path.pieces_[i] !== other.pieces_[j]) { + return false; + } + } + return true; +} +/** + * @returns True if this path is a parent of (or the same as) other + */ +function pathContains(path, other) { + let i = path.pieceNum_; + let j = other.pieceNum_; + if (pathGetLength(path) > pathGetLength(other)) { + return false; + } + while (i < path.pieces_.length) { + if (path.pieces_[i] !== other.pieces_[j]) { + return false; + } + ++i; + ++j; + } + return true; +} +/** + * Dynamic (mutable) path used to count path lengths. + * + * This class is used to efficiently check paths for valid + * length (in UTF8 bytes) and depth (used in path validation). + * + * Throws Error exception if path is ever invalid. + * + * The definition of a path always begins with '/'. + */ +class ValidationPath { + /** + * @param path - Initial Path. + * @param errorPrefix_ - Prefix for any error messages. + */ + constructor(path, errorPrefix_) { + this.errorPrefix_ = errorPrefix_; + this.parts_ = pathSlice(path, 0); + /** Initialize to number of '/' chars needed in path. */ + this.byteLength_ = Math.max(1, this.parts_.length); + for (let i = 0; i < this.parts_.length; i++) { + this.byteLength_ += util.stringLength(this.parts_[i]); + } + validationPathCheckValid(this); + } +} +function validationPathPush(validationPath, child) { + // Count the needed '/' + if (validationPath.parts_.length > 0) { + validationPath.byteLength_ += 1; + } + validationPath.parts_.push(child); + validationPath.byteLength_ += util.stringLength(child); + validationPathCheckValid(validationPath); +} +function validationPathPop(validationPath) { + const last = validationPath.parts_.pop(); + validationPath.byteLength_ -= util.stringLength(last); + // Un-count the previous '/' + if (validationPath.parts_.length > 0) { + validationPath.byteLength_ -= 1; + } +} +function validationPathCheckValid(validationPath) { + if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) { + throw new Error(validationPath.errorPrefix_ + + 'has a key path longer than ' + + MAX_PATH_LENGTH_BYTES + + ' bytes (' + + validationPath.byteLength_ + + ').'); + } + if (validationPath.parts_.length > MAX_PATH_DEPTH) { + throw new Error(validationPath.errorPrefix_ + + 'path specified exceeds the maximum depth that can be written (' + + MAX_PATH_DEPTH + + ') or object contains a cycle ' + + validationPathToErrorString(validationPath)); + } +} +/** + * String for use in error messages - uses '.' notation for path. + */ +function validationPathToErrorString(validationPath) { + if (validationPath.parts_.length === 0) { + return ''; + } + return "in property '" + validationPath.parts_.join('.') + "'"; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class VisibilityMonitor extends EventEmitter { + static getInstance() { + return new VisibilityMonitor(); + } + constructor() { + super(['visible']); + let hidden; + let visibilityChange; + if (typeof document !== 'undefined' && + typeof document.addEventListener !== 'undefined') { + if (typeof document['hidden'] !== 'undefined') { + // Opera 12.10 and Firefox 18 and later support + visibilityChange = 'visibilitychange'; + hidden = 'hidden'; + } + else if (typeof document['mozHidden'] !== 'undefined') { + visibilityChange = 'mozvisibilitychange'; + hidden = 'mozHidden'; + } + else if (typeof document['msHidden'] !== 'undefined') { + visibilityChange = 'msvisibilitychange'; + hidden = 'msHidden'; + } + else if (typeof document['webkitHidden'] !== 'undefined') { + visibilityChange = 'webkitvisibilitychange'; + hidden = 'webkitHidden'; + } + } + // Initially, we always assume we are visible. This ensures that in browsers + // without page visibility support or in cases where we are never visible + // (e.g. chrome extension), we act as if we are visible, i.e. don't delay + // reconnects + this.visible_ = true; + if (visibilityChange) { + document.addEventListener(visibilityChange, () => { + const visible = !document[hidden]; + if (visible !== this.visible_) { + this.visible_ = visible; + this.trigger('visible', visible); + } + }, false); + } + } + getInitialEvent(eventType) { + util.assert(eventType === 'visible', 'Unknown event type: ' + eventType); + return [this.visible_]; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const RECONNECT_MIN_DELAY = 1000; +const RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858) +const RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server) +const RECONNECT_DELAY_MULTIPLIER = 1.3; +const RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec. +const SERVER_KILL_INTERRUPT_REASON = 'server_kill'; +// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off. +const INVALID_TOKEN_THRESHOLD = 3; +/** + * Firebase connection. Abstracts wire protocol and handles reconnecting. + * + * NOTE: All JSON objects sent to the realtime connection must have property names enclosed + * in quotes to make sure the closure compiler does not minify them. + */ +class PersistentConnection extends ServerActions { + /** + * @param repoInfo_ - Data about the namespace we are connecting to + * @param applicationId_ - The Firebase App ID for this project + * @param onDataUpdate_ - A callback for new data from the server + */ + constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) { + super(); + this.repoInfo_ = repoInfo_; + this.applicationId_ = applicationId_; + this.onDataUpdate_ = onDataUpdate_; + this.onConnectStatus_ = onConnectStatus_; + this.onServerInfoUpdate_ = onServerInfoUpdate_; + this.authTokenProvider_ = authTokenProvider_; + this.appCheckTokenProvider_ = appCheckTokenProvider_; + this.authOverride_ = authOverride_; + // Used for diagnostic logging. + this.id = PersistentConnection.nextPersistentConnectionId_++; + this.log_ = logWrapper('p:' + this.id + ':'); + this.interruptReasons_ = {}; + this.listens = new Map(); + this.outstandingPuts_ = []; + this.outstandingGets_ = []; + this.outstandingPutCount_ = 0; + this.outstandingGetCount_ = 0; + this.onDisconnectRequestQueue_ = []; + this.connected_ = false; + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT; + this.securityDebugCallback_ = null; + this.lastSessionId = null; + this.establishConnectionTimer_ = null; + this.visible_ = false; + // Before we get connected, we keep a queue of pending messages to send. + this.requestCBHash_ = {}; + this.requestNumber_ = 0; + this.realtime_ = null; + this.authToken_ = null; + this.appCheckToken_ = null; + this.forceTokenRefresh_ = false; + this.invalidAuthTokenCount_ = 0; + this.invalidAppCheckTokenCount_ = 0; + this.firstConnection_ = true; + this.lastConnectionAttemptTime_ = null; + this.lastConnectionEstablishedTime_ = null; + if (authOverride_ && !util.isNodeSdk()) { + throw new Error('Auth override specified in options, but not supported on non Node.js platforms'); + } + VisibilityMonitor.getInstance().on('visible', this.onVisible_, this); + if (repoInfo_.host.indexOf('fblocal') === -1) { + OnlineMonitor.getInstance().on('online', this.onOnline_, this); + } + } + sendRequest(action, body, onResponse) { + const curReqNum = ++this.requestNumber_; + const msg = { r: curReqNum, a: action, b: body }; + this.log_(util.stringify(msg)); + util.assert(this.connected_, "sendRequest call when we're not connected not allowed."); + this.realtime_.sendRequest(msg); + if (onResponse) { + this.requestCBHash_[curReqNum] = onResponse; + } + } + get(query) { + this.initConnection_(); + const deferred = new util.Deferred(); + const request = { + p: query._path.toString(), + q: query._queryObject + }; + const outstandingGet = { + action: 'g', + request, + onComplete: (message) => { + const payload = message['d']; + if (message['s'] === 'ok') { + deferred.resolve(payload); + } + else { + deferred.reject(payload); + } + } + }; + this.outstandingGets_.push(outstandingGet); + this.outstandingGetCount_++; + const index = this.outstandingGets_.length - 1; + if (this.connected_) { + this.sendGet_(index); + } + return deferred.promise; + } + listen(query, currentHashFn, tag, onComplete) { + this.initConnection_(); + const queryId = query._queryIdentifier; + const pathString = query._path.toString(); + this.log_('Listen called for ' + pathString + ' ' + queryId); + if (!this.listens.has(pathString)) { + this.listens.set(pathString, new Map()); + } + util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query'); + util.assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`); + const listenSpec = { + onComplete, + hashFn: currentHashFn, + query, + tag + }; + this.listens.get(pathString).set(queryId, listenSpec); + if (this.connected_) { + this.sendListen_(listenSpec); + } + } + sendGet_(index) { + const get = this.outstandingGets_[index]; + this.sendRequest('g', get.request, (message) => { + delete this.outstandingGets_[index]; + this.outstandingGetCount_--; + if (this.outstandingGetCount_ === 0) { + this.outstandingGets_ = []; + } + if (get.onComplete) { + get.onComplete(message); + } + }); + } + sendListen_(listenSpec) { + const query = listenSpec.query; + const pathString = query._path.toString(); + const queryId = query._queryIdentifier; + this.log_('Listen on ' + pathString + ' for ' + queryId); + const req = { /*path*/ p: pathString }; + const action = 'q'; + // Only bother to send query if it's non-default. + if (listenSpec.tag) { + req['q'] = query._queryObject; + req['t'] = listenSpec.tag; + } + req[ /*hash*/'h'] = listenSpec.hashFn(); + this.sendRequest(action, req, (message) => { + const payload = message[ /*data*/'d']; + const status = message[ /*status*/'s']; + // print warnings in any case... + PersistentConnection.warnOnListenWarnings_(payload, query); + const currentListenSpec = this.listens.get(pathString) && + this.listens.get(pathString).get(queryId); + // only trigger actions if the listen hasn't been removed and readded + if (currentListenSpec === listenSpec) { + this.log_('listen response', message); + if (status !== 'ok') { + this.removeListen_(pathString, queryId); + } + if (listenSpec.onComplete) { + listenSpec.onComplete(status, payload); + } + } + }); + } + static warnOnListenWarnings_(payload, query) { + if (payload && typeof payload === 'object' && util.contains(payload, 'w')) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const warnings = util.safeGet(payload, 'w'); + if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) { + const indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"'; + const indexPath = query._path.toString(); + warn(`Using an unspecified index. Your data will be downloaded and ` + + `filtered on the client. Consider adding ${indexSpec} at ` + + `${indexPath} to your security rules for better performance.`); + } + } + } + refreshAuthToken(token) { + this.authToken_ = token; + this.log_('Auth token refreshed'); + if (this.authToken_) { + this.tryAuth(); + } + else { + //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete + //the credential so we dont become authenticated next time we connect. + if (this.connected_) { + this.sendRequest('unauth', {}, () => { }); + } + } + this.reduceReconnectDelayIfAdminCredential_(token); + } + reduceReconnectDelayIfAdminCredential_(credential) { + // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client). + // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires. + const isFirebaseSecret = credential && credential.length === 40; + if (isFirebaseSecret || util.isAdmin(credential)) { + this.log_('Admin auth credential detected. Reducing max reconnect time.'); + this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS; + } + } + refreshAppCheckToken(token) { + this.appCheckToken_ = token; + this.log_('App check token refreshed'); + if (this.appCheckToken_) { + this.tryAppCheck(); + } + else { + //If we're connected we want to let the server know to unauthenticate us. + //If we're not connected, simply delete the credential so we dont become + // authenticated next time we connect. + if (this.connected_) { + this.sendRequest('unappeck', {}, () => { }); + } + } + } + /** + * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like + * a auth revoked (the connection is closed). + */ + tryAuth() { + if (this.connected_ && this.authToken_) { + const token = this.authToken_; + const authMethod = util.isValidFormat(token) ? 'auth' : 'gauth'; + const requestData = { cred: token }; + if (this.authOverride_ === null) { + requestData['noauth'] = true; + } + else if (typeof this.authOverride_ === 'object') { + requestData['authvar'] = this.authOverride_; + } + this.sendRequest(authMethod, requestData, (res) => { + const status = res[ /*status*/'s']; + const data = res[ /*data*/'d'] || 'error'; + if (this.authToken_ === token) { + if (status === 'ok') { + this.invalidAuthTokenCount_ = 0; + } + else { + // Triggers reconnect and force refresh for auth token + this.onAuthRevoked_(status, data); + } + } + }); + } + } + /** + * Attempts to authenticate with the given token. If the authentication + * attempt fails, it's triggered like the token was revoked (the connection is + * closed). + */ + tryAppCheck() { + if (this.connected_ && this.appCheckToken_) { + this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => { + const status = res[ /*status*/'s']; + const data = res[ /*data*/'d'] || 'error'; + if (status === 'ok') { + this.invalidAppCheckTokenCount_ = 0; + } + else { + this.onAppCheckRevoked_(status, data); + } + }); + } + } + /** + * @inheritDoc + */ + unlisten(query, tag) { + const pathString = query._path.toString(); + const queryId = query._queryIdentifier; + this.log_('Unlisten called for ' + pathString + ' ' + queryId); + util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query'); + const listen = this.removeListen_(pathString, queryId); + if (listen && this.connected_) { + this.sendUnlisten_(pathString, queryId, query._queryObject, tag); + } + } + sendUnlisten_(pathString, queryId, queryObj, tag) { + this.log_('Unlisten on ' + pathString + ' for ' + queryId); + const req = { /*path*/ p: pathString }; + const action = 'n'; + // Only bother sending queryId if it's non-default. + if (tag) { + req['q'] = queryObj; + req['t'] = tag; + } + this.sendRequest(action, req); + } + onDisconnectPut(pathString, data, onComplete) { + this.initConnection_(); + if (this.connected_) { + this.sendOnDisconnect_('o', pathString, data, onComplete); + } + else { + this.onDisconnectRequestQueue_.push({ + pathString, + action: 'o', + data, + onComplete + }); + } + } + onDisconnectMerge(pathString, data, onComplete) { + this.initConnection_(); + if (this.connected_) { + this.sendOnDisconnect_('om', pathString, data, onComplete); + } + else { + this.onDisconnectRequestQueue_.push({ + pathString, + action: 'om', + data, + onComplete + }); + } + } + onDisconnectCancel(pathString, onComplete) { + this.initConnection_(); + if (this.connected_) { + this.sendOnDisconnect_('oc', pathString, null, onComplete); + } + else { + this.onDisconnectRequestQueue_.push({ + pathString, + action: 'oc', + data: null, + onComplete + }); + } + } + sendOnDisconnect_(action, pathString, data, onComplete) { + const request = { /*path*/ p: pathString, /*data*/ d: data }; + this.log_('onDisconnect ' + action, request); + this.sendRequest(action, request, (response) => { + if (onComplete) { + setTimeout(() => { + onComplete(response[ /*status*/'s'], response[ /* data */'d']); + }, Math.floor(0)); + } + }); + } + put(pathString, data, onComplete, hash) { + this.putInternal('p', pathString, data, onComplete, hash); + } + merge(pathString, data, onComplete, hash) { + this.putInternal('m', pathString, data, onComplete, hash); + } + putInternal(action, pathString, data, onComplete, hash) { + this.initConnection_(); + const request = { + /*path*/ p: pathString, + /*data*/ d: data + }; + if (hash !== undefined) { + request[ /*hash*/'h'] = hash; + } + // TODO: Only keep track of the most recent put for a given path? + this.outstandingPuts_.push({ + action, + request, + onComplete + }); + this.outstandingPutCount_++; + const index = this.outstandingPuts_.length - 1; + if (this.connected_) { + this.sendPut_(index); + } + else { + this.log_('Buffering put: ' + pathString); + } + } + sendPut_(index) { + const action = this.outstandingPuts_[index].action; + const request = this.outstandingPuts_[index].request; + const onComplete = this.outstandingPuts_[index].onComplete; + this.outstandingPuts_[index].queued = this.connected_; + this.sendRequest(action, request, (message) => { + this.log_(action + ' response', message); + delete this.outstandingPuts_[index]; + this.outstandingPutCount_--; + // Clean up array occasionally. + if (this.outstandingPutCount_ === 0) { + this.outstandingPuts_ = []; + } + if (onComplete) { + onComplete(message[ /*status*/'s'], message[ /* data */'d']); + } + }); + } + reportStats(stats) { + // If we're not connected, we just drop the stats. + if (this.connected_) { + const request = { /*counters*/ c: stats }; + this.log_('reportStats', request); + this.sendRequest(/*stats*/ 's', request, result => { + const status = result[ /*status*/'s']; + if (status !== 'ok') { + const errorReason = result[ /* data */'d']; + this.log_('reportStats', 'Error sending stats: ' + errorReason); + } + }); + } + } + onDataMessage_(message) { + if ('r' in message) { + // this is a response + this.log_('from server: ' + util.stringify(message)); + const reqNum = message['r']; + const onResponse = this.requestCBHash_[reqNum]; + if (onResponse) { + delete this.requestCBHash_[reqNum]; + onResponse(message[ /*body*/'b']); + } + } + else if ('error' in message) { + throw 'A server-side error has occurred: ' + message['error']; + } + else if ('a' in message) { + // a and b are action and body, respectively + this.onDataPush_(message['a'], message['b']); + } + } + onDataPush_(action, body) { + this.log_('handleServerMessage', action, body); + if (action === 'd') { + this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], + /*isMerge*/ false, body['t']); + } + else if (action === 'm') { + this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], + /*isMerge=*/ true, body['t']); + } + else if (action === 'c') { + this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']); + } + else if (action === 'ac') { + this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']); + } + else if (action === 'apc') { + this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']); + } + else if (action === 'sd') { + this.onSecurityDebugPacket_(body); + } + else { + error('Unrecognized action received from server: ' + + util.stringify(action) + + '\nAre you using the latest client?'); + } + } + onReady_(timestamp, sessionId) { + this.log_('connection ready'); + this.connected_ = true; + this.lastConnectionEstablishedTime_ = new Date().getTime(); + this.handleTimestamp_(timestamp); + this.lastSessionId = sessionId; + if (this.firstConnection_) { + this.sendConnectStats_(); + } + this.restoreState_(); + this.firstConnection_ = false; + this.onConnectStatus_(true); + } + scheduleConnect_(timeout) { + util.assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?"); + if (this.establishConnectionTimer_) { + clearTimeout(this.establishConnectionTimer_); + } + // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in + // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests). + this.establishConnectionTimer_ = setTimeout(() => { + this.establishConnectionTimer_ = null; + this.establishConnection_(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(timeout)); + } + initConnection_() { + if (!this.realtime_ && this.firstConnection_) { + this.scheduleConnect_(0); + } + } + onVisible_(visible) { + // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine. + if (visible && + !this.visible_ && + this.reconnectDelay_ === this.maxReconnectDelay_) { + this.log_('Window became visible. Reducing delay.'); + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + if (!this.realtime_) { + this.scheduleConnect_(0); + } + } + this.visible_ = visible; + } + onOnline_(online) { + if (online) { + this.log_('Browser went online.'); + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + if (!this.realtime_) { + this.scheduleConnect_(0); + } + } + else { + this.log_('Browser went offline. Killing connection.'); + if (this.realtime_) { + this.realtime_.close(); + } + } + } + onRealtimeDisconnect_() { + this.log_('data client disconnected'); + this.connected_ = false; + this.realtime_ = null; + // Since we don't know if our sent transactions succeeded or not, we need to cancel them. + this.cancelSentTransactions_(); + // Clear out the pending requests. + this.requestCBHash_ = {}; + if (this.shouldReconnect_()) { + if (!this.visible_) { + this.log_("Window isn't visible. Delaying reconnect."); + this.reconnectDelay_ = this.maxReconnectDelay_; + this.lastConnectionAttemptTime_ = new Date().getTime(); + } + else if (this.lastConnectionEstablishedTime_) { + // If we've been connected long enough, reset reconnect delay to minimum. + const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_; + if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) { + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + } + this.lastConnectionEstablishedTime_ = null; + } + const timeSinceLastConnectAttempt = Math.max(0, new Date().getTime() - this.lastConnectionAttemptTime_); + let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt); + reconnectDelay = Math.random() * reconnectDelay; + this.log_('Trying to reconnect in ' + reconnectDelay + 'ms'); + this.scheduleConnect_(reconnectDelay); + // Adjust reconnect delay for next time. + this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER); + } + this.onConnectStatus_(false); + } + async establishConnection_() { + if (this.shouldReconnect_()) { + this.log_('Making a connection attempt'); + this.lastConnectionAttemptTime_ = new Date().getTime(); + this.lastConnectionEstablishedTime_ = null; + const onDataMessage = this.onDataMessage_.bind(this); + const onReady = this.onReady_.bind(this); + const onDisconnect = this.onRealtimeDisconnect_.bind(this); + const connId = this.id + ':' + PersistentConnection.nextConnectionId_++; + const lastSessionId = this.lastSessionId; + let canceled = false; + let connection = null; + const closeFn = function () { + if (connection) { + connection.close(); + } + else { + canceled = true; + onDisconnect(); + } + }; + const sendRequestFn = function (msg) { + util.assert(connection, "sendRequest call when we're not connected not allowed."); + connection.sendRequest(msg); + }; + this.realtime_ = { + close: closeFn, + sendRequest: sendRequestFn + }; + const forceRefresh = this.forceTokenRefresh_; + this.forceTokenRefresh_ = false; + try { + // First fetch auth and app check token, and establish connection after + // fetching the token was successful + const [authToken, appCheckToken] = await Promise.all([ + this.authTokenProvider_.getToken(forceRefresh), + this.appCheckTokenProvider_.getToken(forceRefresh) + ]); + if (!canceled) { + log('getToken() completed. Creating connection.'); + this.authToken_ = authToken && authToken.accessToken; + this.appCheckToken_ = appCheckToken && appCheckToken.token; + connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect, + /* onKill= */ reason => { + warn(reason + ' (' + this.repoInfo_.toString() + ')'); + this.interrupt(SERVER_KILL_INTERRUPT_REASON); + }, lastSessionId); + } + else { + log('getToken() completed but was canceled'); + } + } + catch (error) { + this.log_('Failed to get token: ' + error); + if (!canceled) { + if (this.repoInfo_.nodeAdmin) { + // This may be a critical error for the Admin Node.js SDK, so log a warning. + // But getToken() may also just have temporarily failed, so we still want to + // continue retrying. + warn(error); + } + closeFn(); + } + } + } + } + interrupt(reason) { + log('Interrupting connection for reason: ' + reason); + this.interruptReasons_[reason] = true; + if (this.realtime_) { + this.realtime_.close(); + } + else { + if (this.establishConnectionTimer_) { + clearTimeout(this.establishConnectionTimer_); + this.establishConnectionTimer_ = null; + } + if (this.connected_) { + this.onRealtimeDisconnect_(); + } + } + } + resume(reason) { + log('Resuming connection for reason: ' + reason); + delete this.interruptReasons_[reason]; + if (util.isEmpty(this.interruptReasons_)) { + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + if (!this.realtime_) { + this.scheduleConnect_(0); + } + } + } + handleTimestamp_(timestamp) { + const delta = timestamp - new Date().getTime(); + this.onServerInfoUpdate_({ serverTimeOffset: delta }); + } + cancelSentTransactions_() { + for (let i = 0; i < this.outstandingPuts_.length; i++) { + const put = this.outstandingPuts_[i]; + if (put && /*hash*/ 'h' in put.request && put.queued) { + if (put.onComplete) { + put.onComplete('disconnect'); + } + delete this.outstandingPuts_[i]; + this.outstandingPutCount_--; + } + } + // Clean up array occasionally. + if (this.outstandingPutCount_ === 0) { + this.outstandingPuts_ = []; + } + } + onListenRevoked_(pathString, query) { + // Remove the listen and manufacture a "permission_denied" error for the failed listen. + let queryId; + if (!query) { + queryId = 'default'; + } + else { + queryId = query.map(q => ObjectToUniqueKey(q)).join('$'); + } + const listen = this.removeListen_(pathString, queryId); + if (listen && listen.onComplete) { + listen.onComplete('permission_denied'); + } + } + removeListen_(pathString, queryId) { + const normalizedPathString = new Path(pathString).toString(); // normalize path. + let listen; + if (this.listens.has(normalizedPathString)) { + const map = this.listens.get(normalizedPathString); + listen = map.get(queryId); + map.delete(queryId); + if (map.size === 0) { + this.listens.delete(normalizedPathString); + } + } + else { + // all listens for this path has already been removed + listen = undefined; + } + return listen; + } + onAuthRevoked_(statusCode, explanation) { + log('Auth token revoked: ' + statusCode + '/' + explanation); + this.authToken_ = null; + this.forceTokenRefresh_ = true; + this.realtime_.close(); + if (statusCode === 'invalid_token' || statusCode === 'permission_denied') { + // We'll wait a couple times before logging the warning / increasing the + // retry period since oauth tokens will report as "invalid" if they're + // just expired. Plus there may be transient issues that resolve themselves. + this.invalidAuthTokenCount_++; + if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) { + // Set a long reconnect delay because recovery is unlikely + this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS; + // Notify the auth token provider that the token is invalid, which will log + // a warning + this.authTokenProvider_.notifyForInvalidToken(); + } + } + } + onAppCheckRevoked_(statusCode, explanation) { + log('App check token revoked: ' + statusCode + '/' + explanation); + this.appCheckToken_ = null; + this.forceTokenRefresh_ = true; + // Note: We don't close the connection as the developer may not have + // enforcement enabled. The backend closes connections with enforcements. + if (statusCode === 'invalid_token' || statusCode === 'permission_denied') { + // We'll wait a couple times before logging the warning / increasing the + // retry period since oauth tokens will report as "invalid" if they're + // just expired. Plus there may be transient issues that resolve themselves. + this.invalidAppCheckTokenCount_++; + if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) { + this.appCheckTokenProvider_.notifyForInvalidToken(); + } + } + } + onSecurityDebugPacket_(body) { + if (this.securityDebugCallback_) { + this.securityDebugCallback_(body); + } + else { + if ('msg' in body) { + console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: ')); + } + } + } + restoreState_() { + //Re-authenticate ourselves if we have a credential stored. + this.tryAuth(); + this.tryAppCheck(); + // Puts depend on having received the corresponding data update from the server before they complete, so we must + // make sure to send listens before puts. + for (const queries of this.listens.values()) { + for (const listenSpec of queries.values()) { + this.sendListen_(listenSpec); + } + } + for (let i = 0; i < this.outstandingPuts_.length; i++) { + if (this.outstandingPuts_[i]) { + this.sendPut_(i); + } + } + while (this.onDisconnectRequestQueue_.length) { + const request = this.onDisconnectRequestQueue_.shift(); + this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete); + } + for (let i = 0; i < this.outstandingGets_.length; i++) { + if (this.outstandingGets_[i]) { + this.sendGet_(i); + } + } + } + /** + * Sends client stats for first connection + */ + sendConnectStats_() { + const stats = {}; + let clientName = 'js'; + if (util.isNodeSdk()) { + if (this.repoInfo_.nodeAdmin) { + clientName = 'admin_node'; + } + else { + clientName = 'node'; + } + } + stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1; + if (util.isMobileCordova()) { + stats['framework.cordova'] = 1; + } + else if (util.isReactNative()) { + stats['framework.reactnative'] = 1; + } + this.reportStats(stats); + } + shouldReconnect_() { + const online = OnlineMonitor.getInstance().currentlyOnline(); + return util.isEmpty(this.interruptReasons_) && online; + } +} +PersistentConnection.nextPersistentConnectionId_ = 0; +/** + * Counter for number of connections created. Mainly used for tagging in the logs + */ +PersistentConnection.nextConnectionId_ = 0; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class NamedNode { + constructor(name, node) { + this.name = name; + this.node = node; + } + static Wrap(name, node) { + return new NamedNode(name, node); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Index { + /** + * @returns A standalone comparison function for + * this index + */ + getCompare() { + return this.compare.bind(this); + } + /** + * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different, + * it's possible that the changes are isolated to parts of the snapshot that are not indexed. + * + * + * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode + */ + indexedValueChanged(oldNode, newNode) { + const oldWrapped = new NamedNode(MIN_NAME, oldNode); + const newWrapped = new NamedNode(MIN_NAME, newNode); + return this.compare(oldWrapped, newWrapped) !== 0; + } + /** + * @returns a node wrapper that will sort equal to or less than + * any other node wrapper, using this index + */ + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let __EMPTY_NODE; +class KeyIndex extends Index { + static get __EMPTY_NODE() { + return __EMPTY_NODE; + } + static set __EMPTY_NODE(val) { + __EMPTY_NODE = val; + } + compare(a, b) { + return nameCompare(a.name, b.name); + } + isDefinedOn(node) { + // We could probably return true here (since every node has a key), but it's never called + // so just leaving unimplemented for now. + throw util.assertionError('KeyIndex.isDefinedOn not expected to be called.'); + } + indexedValueChanged(oldNode, newNode) { + return false; // The key for a node never changes. + } + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } + maxPost() { + // TODO: This should really be created once and cached in a static property, but + // NamedNode isn't defined yet, so I can't use it in a static. Bleh. + return new NamedNode(MAX_NAME, __EMPTY_NODE); + } + makePost(indexValue, name) { + util.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.'); + // We just use empty node, but it'll never be compared, since our comparator only looks at name. + return new NamedNode(indexValue, __EMPTY_NODE); + } + /** + * @returns String representation for inclusion in a query spec + */ + toString() { + return '.key'; + } +} +const KEY_INDEX = new KeyIndex(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An iterator over an LLRBNode. + */ +class SortedMapIterator { + /** + * @param node - Node to iterate. + * @param isReverse_ - Whether or not to iterate in reverse + */ + constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) { + this.isReverse_ = isReverse_; + this.resultGenerator_ = resultGenerator_; + this.nodeStack_ = []; + let cmp = 1; + while (!node.isEmpty()) { + node = node; + cmp = startKey ? comparator(node.key, startKey) : 1; + // flip the comparison if we're going in reverse + if (isReverse_) { + cmp *= -1; + } + if (cmp < 0) { + // This node is less than our start key. ignore it + if (this.isReverse_) { + node = node.left; + } + else { + node = node.right; + } + } + else if (cmp === 0) { + // This node is exactly equal to our start key. Push it on the stack, but stop iterating; + this.nodeStack_.push(node); + break; + } + else { + // This node is greater than our start key, add it to the stack and move to the next one + this.nodeStack_.push(node); + if (this.isReverse_) { + node = node.right; + } + else { + node = node.left; + } + } + } + } + getNext() { + if (this.nodeStack_.length === 0) { + return null; + } + let node = this.nodeStack_.pop(); + let result; + if (this.resultGenerator_) { + result = this.resultGenerator_(node.key, node.value); + } + else { + result = { key: node.key, value: node.value }; + } + if (this.isReverse_) { + node = node.left; + while (!node.isEmpty()) { + this.nodeStack_.push(node); + node = node.right; + } + } + else { + node = node.right; + while (!node.isEmpty()) { + this.nodeStack_.push(node); + node = node.left; + } + } + return result; + } + hasNext() { + return this.nodeStack_.length > 0; + } + peek() { + if (this.nodeStack_.length === 0) { + return null; + } + const node = this.nodeStack_[this.nodeStack_.length - 1]; + if (this.resultGenerator_) { + return this.resultGenerator_(node.key, node.value); + } + else { + return { key: node.key, value: node.value }; + } + } +} +/** + * Represents a node in a Left-leaning Red-Black tree. + */ +class LLRBNode { + /** + * @param key - Key associated with this node. + * @param value - Value associated with this node. + * @param color - Whether this node is red. + * @param left - Left child. + * @param right - Right child. + */ + constructor(key, value, color, left, right) { + this.key = key; + this.value = value; + this.color = color != null ? color : LLRBNode.RED; + this.left = + left != null ? left : SortedMap.EMPTY_NODE; + this.right = + right != null ? right : SortedMap.EMPTY_NODE; + } + /** + * Returns a copy of the current node, optionally replacing pieces of it. + * + * @param key - New key for the node, or null. + * @param value - New value for the node, or null. + * @param color - New color for the node, or null. + * @param left - New left child for the node, or null. + * @param right - New right child for the node, or null. + * @returns The node copy. + */ + copy(key, value, color, left, right) { + return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right); + } + /** + * @returns The total number of nodes in the tree. + */ + count() { + return this.left.count() + 1 + this.right.count(); + } + /** + * @returns True if the tree is empty. + */ + isEmpty() { + return false; + } + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action) { + return (this.left.inorderTraversal(action) || + !!action(this.key, this.value) || + this.right.inorderTraversal(action)); + } + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action) { + return (this.right.reverseTraversal(action) || + action(this.key, this.value) || + this.left.reverseTraversal(action)); + } + /** + * @returns The minimum node in the tree. + */ + min_() { + if (this.left.isEmpty()) { + return this; + } + else { + return this.left.min_(); + } + } + /** + * @returns The maximum key in the tree. + */ + minKey() { + return this.min_().key; + } + /** + * @returns The maximum key in the tree. + */ + maxKey() { + if (this.right.isEmpty()) { + return this.key; + } + else { + return this.right.maxKey(); + } + } + /** + * @param key - Key to insert. + * @param value - Value to insert. + * @param comparator - Comparator. + * @returns New tree, with the key/value added. + */ + insert(key, value, comparator) { + let n = this; + const cmp = comparator(key, n.key); + if (cmp < 0) { + n = n.copy(null, null, null, n.left.insert(key, value, comparator), null); + } + else if (cmp === 0) { + n = n.copy(null, value, null, null, null); + } + else { + n = n.copy(null, null, null, null, n.right.insert(key, value, comparator)); + } + return n.fixUp_(); + } + /** + * @returns New tree, with the minimum key removed. + */ + removeMin_() { + if (this.left.isEmpty()) { + return SortedMap.EMPTY_NODE; + } + let n = this; + if (!n.left.isRed_() && !n.left.left.isRed_()) { + n = n.moveRedLeft_(); + } + n = n.copy(null, null, null, n.left.removeMin_(), null); + return n.fixUp_(); + } + /** + * @param key - The key of the item to remove. + * @param comparator - Comparator. + * @returns New tree, with the specified item removed. + */ + remove(key, comparator) { + let n, smallest; + n = this; + if (comparator(key, n.key) < 0) { + if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) { + n = n.moveRedLeft_(); + } + n = n.copy(null, null, null, n.left.remove(key, comparator), null); + } + else { + if (n.left.isRed_()) { + n = n.rotateRight_(); + } + if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) { + n = n.moveRedRight_(); + } + if (comparator(key, n.key) === 0) { + if (n.right.isEmpty()) { + return SortedMap.EMPTY_NODE; + } + else { + smallest = n.right.min_(); + n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_()); + } + } + n = n.copy(null, null, null, null, n.right.remove(key, comparator)); + } + return n.fixUp_(); + } + /** + * @returns Whether this is a RED node. + */ + isRed_() { + return this.color; + } + /** + * @returns New tree after performing any needed rotations. + */ + fixUp_() { + let n = this; + if (n.right.isRed_() && !n.left.isRed_()) { + n = n.rotateLeft_(); + } + if (n.left.isRed_() && n.left.left.isRed_()) { + n = n.rotateRight_(); + } + if (n.left.isRed_() && n.right.isRed_()) { + n = n.colorFlip_(); + } + return n; + } + /** + * @returns New tree, after moveRedLeft. + */ + moveRedLeft_() { + let n = this.colorFlip_(); + if (n.right.left.isRed_()) { + n = n.copy(null, null, null, null, n.right.rotateRight_()); + n = n.rotateLeft_(); + n = n.colorFlip_(); + } + return n; + } + /** + * @returns New tree, after moveRedRight. + */ + moveRedRight_() { + let n = this.colorFlip_(); + if (n.left.left.isRed_()) { + n = n.rotateRight_(); + n = n.colorFlip_(); + } + return n; + } + /** + * @returns New tree, after rotateLeft. + */ + rotateLeft_() { + const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, nl, null); + } + /** + * @returns New tree, after rotateRight. + */ + rotateRight_() { + const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, nr); + } + /** + * @returns Newt ree, after colorFlip. + */ + colorFlip_() { + const left = this.left.copy(null, null, !this.left.color, null, null); + const right = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, left, right); + } + /** + * For testing. + * + * @returns True if all is well. + */ + checkMaxDepth_() { + const blackDepth = this.check_(); + return Math.pow(2.0, blackDepth) <= this.count() + 1; + } + check_() { + if (this.isRed_() && this.left.isRed_()) { + throw new Error('Red node has red child(' + this.key + ',' + this.value + ')'); + } + if (this.right.isRed_()) { + throw new Error('Right child of (' + this.key + ',' + this.value + ') is red'); + } + const blackDepth = this.left.check_(); + if (blackDepth !== this.right.check_()) { + throw new Error('Black depths differ'); + } + else { + return blackDepth + (this.isRed_() ? 0 : 1); + } + } +} +LLRBNode.RED = true; +LLRBNode.BLACK = false; +/** + * Represents an empty node (a leaf node in the Red-Black Tree). + */ +class LLRBEmptyNode { + /** + * Returns a copy of the current node. + * + * @returns The node copy. + */ + copy(key, value, color, left, right) { + return this; + } + /** + * Returns a copy of the tree, with the specified key/value added. + * + * @param key - Key to be added. + * @param value - Value to be added. + * @param comparator - Comparator. + * @returns New tree, with item added. + */ + insert(key, value, comparator) { + return new LLRBNode(key, value, null); + } + /** + * Returns a copy of the tree, with the specified key removed. + * + * @param key - The key to remove. + * @param comparator - Comparator. + * @returns New tree, with item removed. + */ + remove(key, comparator) { + return this; + } + /** + * @returns The total number of nodes in the tree. + */ + count() { + return 0; + } + /** + * @returns True if the tree is empty. + */ + isEmpty() { + return true; + } + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + inorderTraversal(action) { + return false; + } + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action) { + return false; + } + minKey() { + return null; + } + maxKey() { + return null; + } + check_() { + return 0; + } + /** + * @returns Whether this node is red. + */ + isRed_() { + return false; + } +} +/** + * An immutable sorted map implementation, based on a Left-leaning Red-Black + * tree. + */ +class SortedMap { + /** + * @param comparator_ - Key comparator. + * @param root_ - Optional root node for the map. + */ + constructor(comparator_, root_ = SortedMap.EMPTY_NODE) { + this.comparator_ = comparator_; + this.root_ = root_; + } + /** + * Returns a copy of the map, with the specified key/value added or replaced. + * (TODO: We should perhaps rename this method to 'put') + * + * @param key - Key to be added. + * @param value - Value to be added. + * @returns New map, with item added. + */ + insert(key, value) { + return new SortedMap(this.comparator_, this.root_ + .insert(key, value, this.comparator_) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + /** + * Returns a copy of the map, with the specified key removed. + * + * @param key - The key to remove. + * @returns New map, with item removed. + */ + remove(key) { + return new SortedMap(this.comparator_, this.root_ + .remove(key, this.comparator_) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + /** + * Returns the value of the node with the given key, or null. + * + * @param key - The key to look up. + * @returns The value of the node with the given key, or null if the + * key doesn't exist. + */ + get(key) { + let cmp; + let node = this.root_; + while (!node.isEmpty()) { + cmp = this.comparator_(key, node.key); + if (cmp === 0) { + return node.value; + } + else if (cmp < 0) { + node = node.left; + } + else if (cmp > 0) { + node = node.right; + } + } + return null; + } + /** + * Returns the key of the item *before* the specified key, or null if key is the first item. + * @param key - The key to find the predecessor of + * @returns The predecessor key. + */ + getPredecessorKey(key) { + let cmp, node = this.root_, rightParent = null; + while (!node.isEmpty()) { + cmp = this.comparator_(key, node.key); + if (cmp === 0) { + if (!node.left.isEmpty()) { + node = node.left; + while (!node.right.isEmpty()) { + node = node.right; + } + return node.key; + } + else if (rightParent) { + return rightParent.key; + } + else { + return null; // first item. + } + } + else if (cmp < 0) { + node = node.left; + } + else if (cmp > 0) { + rightParent = node; + node = node.right; + } + } + throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?'); + } + /** + * @returns True if the map is empty. + */ + isEmpty() { + return this.root_.isEmpty(); + } + /** + * @returns The total number of nodes in the map. + */ + count() { + return this.root_.count(); + } + /** + * @returns The minimum key in the map. + */ + minKey() { + return this.root_.minKey(); + } + /** + * @returns The maximum key in the map. + */ + maxKey() { + return this.root_.maxKey(); + } + /** + * Traverses the map in key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action) { + return this.root_.inorderTraversal(action); + } + /** + * Traverses the map in reverse key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns True if the traversal was aborted. + */ + reverseTraversal(action) { + return this.root_.reverseTraversal(action); + } + /** + * Returns an iterator over the SortedMap. + * @returns The iterator. + */ + getIterator(resultGenerator) { + return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator); + } + getIteratorFrom(key, resultGenerator) { + return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator); + } + getReverseIteratorFrom(key, resultGenerator) { + return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator); + } + getReverseIterator(resultGenerator) { + return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator); + } +} +/** + * Always use the same empty node, to reduce memory. + */ +SortedMap.EMPTY_NODE = new LLRBEmptyNode(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function NAME_ONLY_COMPARATOR(left, right) { + return nameCompare(left.name, right.name); +} +function NAME_COMPARATOR(left, right) { + return nameCompare(left, right); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let MAX_NODE$2; +function setMaxNode$1(val) { + MAX_NODE$2 = val; +} +const priorityHashText = function (priority) { + if (typeof priority === 'number') { + return 'number:' + doubleToIEEE754String(priority); + } + else { + return 'string:' + priority; + } +}; +/** + * Validates that a priority snapshot Node is valid. + */ +const validatePriorityNode = function (priorityNode) { + if (priorityNode.isLeafNode()) { + const val = priorityNode.val(); + util.assert(typeof val === 'string' || + typeof val === 'number' || + (typeof val === 'object' && util.contains(val, '.sv')), 'Priority must be a string or number.'); + } + else { + util.assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.'); + } + // Don't call getPriority() on MAX_NODE to avoid hitting assertion. + util.assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own."); +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let __childrenNodeConstructor; +/** + * LeafNode is a class for storing leaf nodes in a DataSnapshot. It + * implements Node and stores the value of the node (a string, + * number, or boolean) accessible via getValue(). + */ +class LeafNode { + static set __childrenNodeConstructor(val) { + __childrenNodeConstructor = val; + } + static get __childrenNodeConstructor() { + return __childrenNodeConstructor; + } + /** + * @param value_ - The value to store in this leaf node. The object type is + * possible in the event of a deferred value + * @param priorityNode_ - The priority of this node. + */ + constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) { + this.value_ = value_; + this.priorityNode_ = priorityNode_; + this.lazyHash_ = null; + util.assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value."); + validatePriorityNode(this.priorityNode_); + } + /** @inheritDoc */ + isLeafNode() { + return true; + } + /** @inheritDoc */ + getPriority() { + return this.priorityNode_; + } + /** @inheritDoc */ + updatePriority(newPriorityNode) { + return new LeafNode(this.value_, newPriorityNode); + } + /** @inheritDoc */ + getImmediateChild(childName) { + // Hack to treat priority as a regular child + if (childName === '.priority') { + return this.priorityNode_; + } + else { + return LeafNode.__childrenNodeConstructor.EMPTY_NODE; + } + } + /** @inheritDoc */ + getChild(path) { + if (pathIsEmpty(path)) { + return this; + } + else if (pathGetFront(path) === '.priority') { + return this.priorityNode_; + } + else { + return LeafNode.__childrenNodeConstructor.EMPTY_NODE; + } + } + hasChild() { + return false; + } + /** @inheritDoc */ + getPredecessorChildName(childName, childNode) { + return null; + } + /** @inheritDoc */ + updateImmediateChild(childName, newChildNode) { + if (childName === '.priority') { + return this.updatePriority(newChildNode); + } + else if (newChildNode.isEmpty() && childName !== '.priority') { + return this; + } + else { + return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_); + } + } + /** @inheritDoc */ + updateChild(path, newChildNode) { + const front = pathGetFront(path); + if (front === null) { + return newChildNode; + } + else if (newChildNode.isEmpty() && front !== '.priority') { + return this; + } + else { + util.assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path'); + return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode)); + } + } + /** @inheritDoc */ + isEmpty() { + return false; + } + /** @inheritDoc */ + numChildren() { + return 0; + } + /** @inheritDoc */ + forEachChild(index, action) { + return false; + } + val(exportFormat) { + if (exportFormat && !this.getPriority().isEmpty()) { + return { + '.value': this.getValue(), + '.priority': this.getPriority().val() + }; + } + else { + return this.getValue(); + } + } + /** @inheritDoc */ + hash() { + if (this.lazyHash_ === null) { + let toHash = ''; + if (!this.priorityNode_.isEmpty()) { + toHash += + 'priority:' + + priorityHashText(this.priorityNode_.val()) + + ':'; + } + const type = typeof this.value_; + toHash += type + ':'; + if (type === 'number') { + toHash += doubleToIEEE754String(this.value_); + } + else { + toHash += this.value_; + } + this.lazyHash_ = sha1(toHash); + } + return this.lazyHash_; + } + /** + * Returns the value of the leaf node. + * @returns The value of the node. + */ + getValue() { + return this.value_; + } + compareTo(other) { + if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) { + return 1; + } + else if (other instanceof LeafNode.__childrenNodeConstructor) { + return -1; + } + else { + util.assert(other.isLeafNode(), 'Unknown node type'); + return this.compareToLeafNode_(other); + } + } + /** + * Comparison specifically for two leaf nodes + */ + compareToLeafNode_(otherLeaf) { + const otherLeafType = typeof otherLeaf.value_; + const thisLeafType = typeof this.value_; + const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType); + const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType); + util.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType); + util.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType); + if (otherIndex === thisIndex) { + // Same type, compare values + if (thisLeafType === 'object') { + // Deferred value nodes are all equal, but we should also never get to this point... + return 0; + } + else { + // Note that this works because true > false, all others are number or string comparisons + if (this.value_ < otherLeaf.value_) { + return -1; + } + else if (this.value_ === otherLeaf.value_) { + return 0; + } + else { + return 1; + } + } + } + else { + return thisIndex - otherIndex; + } + } + withIndex() { + return this; + } + isIndexed() { + return true; + } + equals(other) { + if (other === this) { + return true; + } + else if (other.isLeafNode()) { + const otherLeaf = other; + return (this.value_ === otherLeaf.value_ && + this.priorityNode_.equals(otherLeaf.priorityNode_)); + } + else { + return false; + } + } +} +/** + * The sort order for comparing leaf nodes of different types. If two leaf nodes have + * the same type, the comparison falls back to their value + */ +LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string']; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let nodeFromJSON$1; +let MAX_NODE$1; +function setNodeFromJSON(val) { + nodeFromJSON$1 = val; +} +function setMaxNode(val) { + MAX_NODE$1 = val; +} +class PriorityIndex extends Index { + compare(a, b) { + const aPriority = a.node.getPriority(); + const bPriority = b.node.getPriority(); + const indexCmp = aPriority.compareTo(bPriority); + if (indexCmp === 0) { + return nameCompare(a.name, b.name); + } + else { + return indexCmp; + } + } + isDefinedOn(node) { + return !node.getPriority().isEmpty(); + } + indexedValueChanged(oldNode, newNode) { + return !oldNode.getPriority().equals(newNode.getPriority()); + } + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } + maxPost() { + return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1)); + } + makePost(indexValue, name) { + const priorityNode = nodeFromJSON$1(indexValue); + return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode)); + } + /** + * @returns String representation for inclusion in a query spec + */ + toString() { + return '.priority'; + } +} +const PRIORITY_INDEX = new PriorityIndex(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_2 = Math.log(2); +class Base12Num { + constructor(length) { + const logBase2 = (num) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + parseInt((Math.log(num) / LOG_2), 10); + const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2); + this.count = logBase2(length + 1); + this.current_ = this.count - 1; + const mask = bitMask(this.count); + this.bits_ = (length + 1) & mask; + } + nextBitIsOne() { + //noinspection JSBitwiseOperatorUsage + const result = !(this.bits_ & (0x1 << this.current_)); + this.current_--; + return result; + } +} +/** + * Takes a list of child nodes and constructs a SortedSet using the given comparison + * function + * + * Uses the algorithm described in the paper linked here: + * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458 + * + * @param childList - Unsorted list of children + * @param cmp - The comparison method to be used + * @param keyFn - An optional function to extract K from a node wrapper, if K's + * type is not NamedNode + * @param mapSortFn - An optional override for comparator used by the generated sorted map + */ +const buildChildSet = function (childList, cmp, keyFn, mapSortFn) { + childList.sort(cmp); + const buildBalancedTree = function (low, high) { + const length = high - low; + let namedNode; + let key; + if (length === 0) { + return null; + } + else if (length === 1) { + namedNode = childList[low]; + key = keyFn ? keyFn(namedNode) : namedNode; + return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null); + } + else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const middle = parseInt((length / 2), 10) + low; + const left = buildBalancedTree(low, middle); + const right = buildBalancedTree(middle + 1, high); + namedNode = childList[middle]; + key = keyFn ? keyFn(namedNode) : namedNode; + return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right); + } + }; + const buildFrom12Array = function (base12) { + let node = null; + let root = null; + let index = childList.length; + const buildPennant = function (chunkSize, color) { + const low = index - chunkSize; + const high = index; + index -= chunkSize; + const childTree = buildBalancedTree(low + 1, high); + const namedNode = childList[low]; + const key = keyFn ? keyFn(namedNode) : namedNode; + attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree)); + }; + const attachPennant = function (pennant) { + if (node) { + node.left = pennant; + node = pennant; + } + else { + root = pennant; + node = pennant; + } + }; + for (let i = 0; i < base12.count; ++i) { + const isOne = base12.nextBitIsOne(); + // The number of nodes taken in each slice is 2^(arr.length - (i + 1)) + const chunkSize = Math.pow(2, base12.count - (i + 1)); + if (isOne) { + buildPennant(chunkSize, LLRBNode.BLACK); + } + else { + // current == 2 + buildPennant(chunkSize, LLRBNode.BLACK); + buildPennant(chunkSize, LLRBNode.RED); + } + } + return root; + }; + const base12 = new Base12Num(childList.length); + const root = buildFrom12Array(base12); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return new SortedMap(mapSortFn || cmp, root); +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let _defaultIndexMap; +const fallbackObject = {}; +class IndexMap { + /** + * The default IndexMap for nodes without a priority + */ + static get Default() { + util.assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded'); + _defaultIndexMap = + _defaultIndexMap || + new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX }); + return _defaultIndexMap; + } + constructor(indexes_, indexSet_) { + this.indexes_ = indexes_; + this.indexSet_ = indexSet_; + } + get(indexKey) { + const sortedMap = util.safeGet(this.indexes_, indexKey); + if (!sortedMap) { + throw new Error('No index defined for ' + indexKey); + } + if (sortedMap instanceof SortedMap) { + return sortedMap; + } + else { + // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the + // regular child map + return null; + } + } + hasIndex(indexDefinition) { + return util.contains(this.indexSet_, indexDefinition.toString()); + } + addIndex(indexDefinition, existingChildren) { + util.assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap."); + const childList = []; + let sawIndexedValue = false; + const iter = existingChildren.getIterator(NamedNode.Wrap); + let next = iter.getNext(); + while (next) { + sawIndexedValue = + sawIndexedValue || indexDefinition.isDefinedOn(next.node); + childList.push(next); + next = iter.getNext(); + } + let newIndex; + if (sawIndexedValue) { + newIndex = buildChildSet(childList, indexDefinition.getCompare()); + } + else { + newIndex = fallbackObject; + } + const indexName = indexDefinition.toString(); + const newIndexSet = { ...this.indexSet_ }; + newIndexSet[indexName] = indexDefinition; + const newIndexes = { ...this.indexes_ }; + newIndexes[indexName] = newIndex; + return new IndexMap(newIndexes, newIndexSet); + } + /** + * Ensure that this node is properly tracked in any indexes that we're maintaining + */ + addToIndexes(namedNode, existingChildren) { + const newIndexes = util.map(this.indexes_, (indexedChildren, indexName) => { + const index = util.safeGet(this.indexSet_, indexName); + util.assert(index, 'Missing index implementation for ' + indexName); + if (indexedChildren === fallbackObject) { + // Check to see if we need to index everything + if (index.isDefinedOn(namedNode.node)) { + // We need to build this index + const childList = []; + const iter = existingChildren.getIterator(NamedNode.Wrap); + let next = iter.getNext(); + while (next) { + if (next.name !== namedNode.name) { + childList.push(next); + } + next = iter.getNext(); + } + childList.push(namedNode); + return buildChildSet(childList, index.getCompare()); + } + else { + // No change, this remains a fallback + return fallbackObject; + } + } + else { + const existingSnap = existingChildren.get(namedNode.name); + let newChildren = indexedChildren; + if (existingSnap) { + newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap)); + } + return newChildren.insert(namedNode, namedNode.node); + } + }); + return new IndexMap(newIndexes, this.indexSet_); + } + /** + * Create a new IndexMap instance with the given value removed + */ + removeFromIndexes(namedNode, existingChildren) { + const newIndexes = util.map(this.indexes_, (indexedChildren) => { + if (indexedChildren === fallbackObject) { + // This is the fallback. Just return it, nothing to do in this case + return indexedChildren; + } + else { + const existingSnap = existingChildren.get(namedNode.name); + if (existingSnap) { + return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap)); + } + else { + // No record of this child + return indexedChildren; + } + } + }); + return new IndexMap(newIndexes, this.indexSet_); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO: For memory savings, don't store priorityNode_ if it's empty. +let EMPTY_NODE; +/** + * ChildrenNode is a class for storing internal nodes in a DataSnapshot + * (i.e. nodes with children). It implements Node and stores the + * list of children in the children property, sorted by child name. + */ +class ChildrenNode { + static get EMPTY_NODE() { + return (EMPTY_NODE || + (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default))); + } + /** + * @param children_ - List of children of this node.. + * @param priorityNode_ - The priority of this node (as a snapshot node). + */ + constructor(children_, priorityNode_, indexMap_) { + this.children_ = children_; + this.priorityNode_ = priorityNode_; + this.indexMap_ = indexMap_; + this.lazyHash_ = null; + /** + * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use + * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own + * class instead of an empty ChildrenNode. + */ + if (this.priorityNode_) { + validatePriorityNode(this.priorityNode_); + } + if (this.children_.isEmpty()) { + util.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority'); + } + } + /** @inheritDoc */ + isLeafNode() { + return false; + } + /** @inheritDoc */ + getPriority() { + return this.priorityNode_ || EMPTY_NODE; + } + /** @inheritDoc */ + updatePriority(newPriorityNode) { + if (this.children_.isEmpty()) { + // Don't allow priorities on empty nodes + return this; + } + else { + return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_); + } + } + /** @inheritDoc */ + getImmediateChild(childName) { + // Hack to treat priority as a regular child + if (childName === '.priority') { + return this.getPriority(); + } + else { + const child = this.children_.get(childName); + return child === null ? EMPTY_NODE : child; + } + } + /** @inheritDoc */ + getChild(path) { + const front = pathGetFront(path); + if (front === null) { + return this; + } + return this.getImmediateChild(front).getChild(pathPopFront(path)); + } + /** @inheritDoc */ + hasChild(childName) { + return this.children_.get(childName) !== null; + } + /** @inheritDoc */ + updateImmediateChild(childName, newChildNode) { + util.assert(newChildNode, 'We should always be passing snapshot nodes'); + if (childName === '.priority') { + return this.updatePriority(newChildNode); + } + else { + const namedNode = new NamedNode(childName, newChildNode); + let newChildren, newIndexMap; + if (newChildNode.isEmpty()) { + newChildren = this.children_.remove(childName); + newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_); + } + else { + newChildren = this.children_.insert(childName, newChildNode); + newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_); + } + const newPriority = newChildren.isEmpty() + ? EMPTY_NODE + : this.priorityNode_; + return new ChildrenNode(newChildren, newPriority, newIndexMap); + } + } + /** @inheritDoc */ + updateChild(path, newChildNode) { + const front = pathGetFront(path); + if (front === null) { + return newChildNode; + } + else { + util.assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path'); + const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode); + return this.updateImmediateChild(front, newImmediateChild); + } + } + /** @inheritDoc */ + isEmpty() { + return this.children_.isEmpty(); + } + /** @inheritDoc */ + numChildren() { + return this.children_.count(); + } + /** @inheritDoc */ + val(exportFormat) { + if (this.isEmpty()) { + return null; + } + const obj = {}; + let numKeys = 0, maxKey = 0, allIntegerKeys = true; + this.forEachChild(PRIORITY_INDEX, (key, childNode) => { + obj[key] = childNode.val(exportFormat); + numKeys++; + if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) { + maxKey = Math.max(maxKey, Number(key)); + } + else { + allIntegerKeys = false; + } + }); + if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) { + // convert to array. + const array = []; + // eslint-disable-next-line guard-for-in + for (const key in obj) { + array[key] = obj[key]; + } + return array; + } + else { + if (exportFormat && !this.getPriority().isEmpty()) { + obj['.priority'] = this.getPriority().val(); + } + return obj; + } + } + /** @inheritDoc */ + hash() { + if (this.lazyHash_ === null) { + let toHash = ''; + if (!this.getPriority().isEmpty()) { + toHash += + 'priority:' + + priorityHashText(this.getPriority().val()) + + ':'; + } + this.forEachChild(PRIORITY_INDEX, (key, childNode) => { + const childHash = childNode.hash(); + if (childHash !== '') { + toHash += ':' + key + ':' + childHash; + } + }); + this.lazyHash_ = toHash === '' ? '' : sha1(toHash); + } + return this.lazyHash_; + } + /** @inheritDoc */ + getPredecessorChildName(childName, childNode, index) { + const idx = this.resolveIndex_(index); + if (idx) { + const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode)); + return predecessor ? predecessor.name : null; + } + else { + return this.children_.getPredecessorKey(childName); + } + } + getFirstChildName(indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + const minKey = idx.minKey(); + return minKey && minKey.name; + } + else { + return this.children_.minKey(); + } + } + getFirstChild(indexDefinition) { + const minKey = this.getFirstChildName(indexDefinition); + if (minKey) { + return new NamedNode(minKey, this.children_.get(minKey)); + } + else { + return null; + } + } + /** + * Given an index, return the key name of the largest value we have, according to that index + */ + getLastChildName(indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + const maxKey = idx.maxKey(); + return maxKey && maxKey.name; + } + else { + return this.children_.maxKey(); + } + } + getLastChild(indexDefinition) { + const maxKey = this.getLastChildName(indexDefinition); + if (maxKey) { + return new NamedNode(maxKey, this.children_.get(maxKey)); + } + else { + return null; + } + } + forEachChild(index, action) { + const idx = this.resolveIndex_(index); + if (idx) { + return idx.inorderTraversal(wrappedNode => { + return action(wrappedNode.name, wrappedNode.node); + }); + } + else { + return this.children_.inorderTraversal(action); + } + } + getIterator(indexDefinition) { + return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition); + } + getIteratorFrom(startPost, indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + return idx.getIteratorFrom(startPost, key => key); + } + else { + const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap); + let next = iterator.peek(); + while (next != null && indexDefinition.compare(next, startPost) < 0) { + iterator.getNext(); + next = iterator.peek(); + } + return iterator; + } + } + getReverseIterator(indexDefinition) { + return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition); + } + getReverseIteratorFrom(endPost, indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + return idx.getReverseIteratorFrom(endPost, key => { + return key; + }); + } + else { + const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap); + let next = iterator.peek(); + while (next != null && indexDefinition.compare(next, endPost) > 0) { + iterator.getNext(); + next = iterator.peek(); + } + return iterator; + } + } + compareTo(other) { + if (this.isEmpty()) { + if (other.isEmpty()) { + return 0; + } + else { + return -1; + } + } + else if (other.isLeafNode() || other.isEmpty()) { + return 1; + } + else if (other === MAX_NODE) { + return -1; + } + else { + // Must be another node with children. + return 0; + } + } + withIndex(indexDefinition) { + if (indexDefinition === KEY_INDEX || + this.indexMap_.hasIndex(indexDefinition)) { + return this; + } + else { + const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_); + return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap); + } + } + isIndexed(index) { + return index === KEY_INDEX || this.indexMap_.hasIndex(index); + } + equals(other) { + if (other === this) { + return true; + } + else if (other.isLeafNode()) { + return false; + } + else { + const otherChildrenNode = other; + if (!this.getPriority().equals(otherChildrenNode.getPriority())) { + return false; + } + else if (this.children_.count() === otherChildrenNode.children_.count()) { + const thisIter = this.getIterator(PRIORITY_INDEX); + const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX); + let thisCurrent = thisIter.getNext(); + let otherCurrent = otherIter.getNext(); + while (thisCurrent && otherCurrent) { + if (thisCurrent.name !== otherCurrent.name || + !thisCurrent.node.equals(otherCurrent.node)) { + return false; + } + thisCurrent = thisIter.getNext(); + otherCurrent = otherIter.getNext(); + } + return thisCurrent === null && otherCurrent === null; + } + else { + return false; + } + } + } + /** + * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used + * instead. + * + */ + resolveIndex_(indexDefinition) { + if (indexDefinition === KEY_INDEX) { + return null; + } + else { + return this.indexMap_.get(indexDefinition.toString()); + } + } +} +ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/; +class MaxNode extends ChildrenNode { + constructor() { + super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default); + } + compareTo(other) { + if (other === this) { + return 0; + } + else { + return 1; + } + } + equals(other) { + // Not that we every compare it, but MAX_NODE is only ever equal to itself + return other === this; + } + getPriority() { + return this; + } + getImmediateChild(childName) { + return ChildrenNode.EMPTY_NODE; + } + isEmpty() { + return false; + } +} +/** + * Marker that will sort higher than any other snapshot. + */ +const MAX_NODE = new MaxNode(); +Object.defineProperties(NamedNode, { + MIN: { + value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE) + }, + MAX: { + value: new NamedNode(MAX_NAME, MAX_NODE) + } +}); +/** + * Reference Extensions + */ +KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE; +LeafNode.__childrenNodeConstructor = ChildrenNode; +setMaxNode$1(MAX_NODE); +setMaxNode(MAX_NODE); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const USE_HINZE = true; +/** + * Constructs a snapshot node representing the passed JSON and returns it. + * @param json - JSON to create a node for. + * @param priority - Optional priority to use. This will be ignored if the + * passed JSON contains a .priority property. + */ +function nodeFromJSON(json, priority = null) { + if (json === null) { + return ChildrenNode.EMPTY_NODE; + } + if (typeof json === 'object' && '.priority' in json) { + priority = json['.priority']; + } + util.assert(priority === null || + typeof priority === 'string' || + typeof priority === 'number' || + (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority); + if (typeof json === 'object' && '.value' in json && json['.value'] !== null) { + json = json['.value']; + } + // Valid leaf nodes include non-objects or server-value wrapper objects + if (typeof json !== 'object' || '.sv' in json) { + const jsonLeaf = json; + return new LeafNode(jsonLeaf, nodeFromJSON(priority)); + } + if (!(json instanceof Array) && USE_HINZE) { + const children = []; + let childrenHavePriority = false; + const hinzeJsonObj = json; + each(hinzeJsonObj, (key, child) => { + if (key.substring(0, 1) !== '.') { + // Ignore metadata nodes + const childNode = nodeFromJSON(child); + if (!childNode.isEmpty()) { + childrenHavePriority = + childrenHavePriority || !childNode.getPriority().isEmpty(); + children.push(new NamedNode(key, childNode)); + } + } + }); + if (children.length === 0) { + return ChildrenNode.EMPTY_NODE; + } + const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR); + if (childrenHavePriority) { + const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare()); + return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX })); + } + else { + return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default); + } + } + else { + let node = ChildrenNode.EMPTY_NODE; + each(json, (key, childData) => { + if (util.contains(json, key)) { + if (key.substring(0, 1) !== '.') { + // ignore metadata nodes. + const childNode = nodeFromJSON(childData); + if (childNode.isLeafNode() || !childNode.isEmpty()) { + node = node.updateImmediateChild(key, childNode); + } + } + } + }); + return node.updatePriority(nodeFromJSON(priority)); + } +} +setNodeFromJSON(nodeFromJSON); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class PathIndex extends Index { + constructor(indexPath_) { + super(); + this.indexPath_ = indexPath_; + util.assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key"); + } + extractChild(snap) { + return snap.getChild(this.indexPath_); + } + isDefinedOn(node) { + return !node.getChild(this.indexPath_).isEmpty(); + } + compare(a, b) { + const aChild = this.extractChild(a.node); + const bChild = this.extractChild(b.node); + const indexCmp = aChild.compareTo(bChild); + if (indexCmp === 0) { + return nameCompare(a.name, b.name); + } + else { + return indexCmp; + } + } + makePost(indexValue, name) { + const valueNode = nodeFromJSON(indexValue); + const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode); + return new NamedNode(name, node); + } + maxPost() { + const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE); + return new NamedNode(MAX_NAME, node); + } + toString() { + return pathSlice(this.indexPath_, 0).join('/'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ValueIndex extends Index { + compare(a, b) { + const indexCmp = a.node.compareTo(b.node); + if (indexCmp === 0) { + return nameCompare(a.name, b.name); + } + else { + return indexCmp; + } + } + isDefinedOn(node) { + return true; + } + indexedValueChanged(oldNode, newNode) { + return !oldNode.equals(newNode); + } + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } + maxPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MAX; + } + makePost(indexValue, name) { + const valueNode = nodeFromJSON(indexValue); + return new NamedNode(name, valueNode); + } + /** + * @returns String representation for inclusion in a query spec + */ + toString() { + return '.value'; + } +} +const VALUE_INDEX = new ValueIndex(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function changeValue(snapshotNode) { + return { type: "value" /* ChangeType.VALUE */, snapshotNode }; +} +function changeChildAdded(childName, snapshotNode) { + return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode, childName }; +} +function changeChildRemoved(childName, snapshotNode) { + return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode, childName }; +} +function changeChildChanged(childName, snapshotNode, oldSnap) { + return { + type: "child_changed" /* ChangeType.CHILD_CHANGED */, + snapshotNode, + childName, + oldSnap + }; +} +function changeChildMoved(childName, snapshotNode) { + return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode, childName }; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Doesn't really filter nodes but applies an index to the node and keeps track of any changes + */ +class IndexedFilter { + constructor(index_) { + this.index_ = index_; + } + updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) { + util.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated'); + const oldChild = snap.getImmediateChild(key); + // Check if anything actually changed. + if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) { + // There's an edge case where a child can enter or leave the view because affectedPath was set to null. + // In this case, affectedPath will appear null in both the old and new snapshots. So we need + // to avoid treating these cases as "nothing changed." + if (oldChild.isEmpty() === newChild.isEmpty()) { + // Nothing changed. + // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it. + //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.'); + return snap; + } + } + if (optChangeAccumulator != null) { + if (newChild.isEmpty()) { + if (snap.hasChild(key)) { + optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild)); + } + else { + util.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node'); + } + } + else if (oldChild.isEmpty()) { + optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild)); + } + else { + optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild)); + } + } + if (snap.isLeafNode() && newChild.isEmpty()) { + return snap; + } + else { + // Make sure the node is indexed + return snap.updateImmediateChild(key, newChild).withIndex(this.index_); + } + } + updateFullNode(oldSnap, newSnap, optChangeAccumulator) { + if (optChangeAccumulator != null) { + if (!oldSnap.isLeafNode()) { + oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => { + if (!newSnap.hasChild(key)) { + optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode)); + } + }); + } + if (!newSnap.isLeafNode()) { + newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => { + if (oldSnap.hasChild(key)) { + const oldChild = oldSnap.getImmediateChild(key); + if (!oldChild.equals(childNode)) { + optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild)); + } + } + else { + optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode)); + } + }); + } + } + return newSnap.withIndex(this.index_); + } + updatePriority(oldSnap, newPriority) { + if (oldSnap.isEmpty()) { + return ChildrenNode.EMPTY_NODE; + } + else { + return oldSnap.updatePriority(newPriority); + } + } + filtersNodes() { + return false; + } + getIndexedFilter() { + return this; + } + getIndex() { + return this.index_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node + */ +class RangedFilter { + constructor(params) { + this.indexedFilter_ = new IndexedFilter(params.getIndex()); + this.index_ = params.getIndex(); + this.startPost_ = RangedFilter.getStartPost_(params); + this.endPost_ = RangedFilter.getEndPost_(params); + this.startIsInclusive_ = !params.startAfterSet_; + this.endIsInclusive_ = !params.endBeforeSet_; + } + getStartPost() { + return this.startPost_; + } + getEndPost() { + return this.endPost_; + } + matches(node) { + const isWithinStart = this.startIsInclusive_ + ? this.index_.compare(this.getStartPost(), node) <= 0 + : this.index_.compare(this.getStartPost(), node) < 0; + const isWithinEnd = this.endIsInclusive_ + ? this.index_.compare(node, this.getEndPost()) <= 0 + : this.index_.compare(node, this.getEndPost()) < 0; + return isWithinStart && isWithinEnd; + } + updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) { + if (!this.matches(new NamedNode(key, newChild))) { + newChild = ChildrenNode.EMPTY_NODE; + } + return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator); + } + updateFullNode(oldSnap, newSnap, optChangeAccumulator) { + if (newSnap.isLeafNode()) { + // Make sure we have a children node with the correct index, not a leaf node; + newSnap = ChildrenNode.EMPTY_NODE; + } + let filtered = newSnap.withIndex(this.index_); + // Don't support priorities on queries + filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE); + const self = this; + newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => { + if (!self.matches(new NamedNode(key, childNode))) { + filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE); + } + }); + return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator); + } + updatePriority(oldSnap, newPriority) { + // Don't support priorities on queries + return oldSnap; + } + filtersNodes() { + return true; + } + getIndexedFilter() { + return this.indexedFilter_; + } + getIndex() { + return this.index_; + } + static getStartPost_(params) { + if (params.hasStart()) { + const startName = params.getIndexStartName(); + return params.getIndex().makePost(params.getIndexStartValue(), startName); + } + else { + return params.getIndex().minPost(); + } + } + static getEndPost_(params) { + if (params.hasEnd()) { + const endName = params.getIndexEndName(); + return params.getIndex().makePost(params.getIndexEndValue(), endName); + } + else { + return params.getIndex().maxPost(); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible + */ +class LimitedFilter { + constructor(params) { + this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node); + this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node); + this.withinStartPost = (node) => { + const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node); + return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0; + }; + this.withinEndPost = (node) => { + const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost()); + return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0; + }; + this.rangedFilter_ = new RangedFilter(params); + this.index_ = params.getIndex(); + this.limit_ = params.getLimit(); + this.reverse_ = !params.isViewFromLeft(); + this.startIsInclusive_ = !params.startAfterSet_; + this.endIsInclusive_ = !params.endBeforeSet_; + } + updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) { + if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) { + newChild = ChildrenNode.EMPTY_NODE; + } + if (snap.getImmediateChild(key).equals(newChild)) { + // No change + return snap; + } + else if (snap.numChildren() < this.limit_) { + return this.rangedFilter_ + .getIndexedFilter() + .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator); + } + else { + return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator); + } + } + updateFullNode(oldSnap, newSnap, optChangeAccumulator) { + let filtered; + if (newSnap.isLeafNode() || newSnap.isEmpty()) { + // Make sure we have a children node with the correct index, not a leaf node; + filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_); + } + else { + if (this.limit_ * 2 < newSnap.numChildren() && + newSnap.isIndexed(this.index_)) { + // Easier to build up a snapshot, since what we're given has more than twice the elements we want + filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_); + // anchor to the startPost, endPost, or last element as appropriate + let iterator; + if (this.reverse_) { + iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_); + } + else { + iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_); + } + let count = 0; + while (iterator.hasNext() && count < this.limit_) { + const next = iterator.getNext(); + if (!this.withinDirectionalStart(next)) { + // if we have not reached the start, skip to the next element + continue; + } + else if (!this.withinDirectionalEnd(next)) { + // if we have reached the end, stop adding elements + break; + } + else { + filtered = filtered.updateImmediateChild(next.name, next.node); + count++; + } + } + } + else { + // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one + filtered = newSnap.withIndex(this.index_); + // Don't support priorities on queries + filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE); + let iterator; + if (this.reverse_) { + iterator = filtered.getReverseIterator(this.index_); + } + else { + iterator = filtered.getIterator(this.index_); + } + let count = 0; + while (iterator.hasNext()) { + const next = iterator.getNext(); + const inRange = count < this.limit_ && + this.withinDirectionalStart(next) && + this.withinDirectionalEnd(next); + if (inRange) { + count++; + } + else { + filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE); + } + } + } + } + return this.rangedFilter_ + .getIndexedFilter() + .updateFullNode(oldSnap, filtered, optChangeAccumulator); + } + updatePriority(oldSnap, newPriority) { + // Don't support priorities on queries + return oldSnap; + } + filtersNodes() { + return true; + } + getIndexedFilter() { + return this.rangedFilter_.getIndexedFilter(); + } + getIndex() { + return this.index_; + } + fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) { + // TODO: rename all cache stuff etc to general snap terminology + let cmp; + if (this.reverse_) { + const indexCmp = this.index_.getCompare(); + cmp = (a, b) => indexCmp(b, a); + } + else { + cmp = this.index_.getCompare(); + } + const oldEventCache = snap; + util.assert(oldEventCache.numChildren() === this.limit_, ''); + const newChildNamedNode = new NamedNode(childKey, childSnap); + const windowBoundary = this.reverse_ + ? oldEventCache.getFirstChild(this.index_) + : oldEventCache.getLastChild(this.index_); + const inRange = this.rangedFilter_.matches(newChildNamedNode); + if (oldEventCache.hasChild(childKey)) { + const oldChildSnap = oldEventCache.getImmediateChild(childKey); + let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_); + while (nextChild != null && + (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) { + // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't + // been applied to the limited filter yet. Ignore this next child which will be updated later in + // the limited filter... + nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_); + } + const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode); + const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0; + if (remainsInWindow) { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap)); + } + return oldEventCache.updateImmediateChild(childKey, childSnap); + } + else { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap)); + } + const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE); + const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild); + if (nextChildInRange) { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node)); + } + return newEventCache.updateImmediateChild(nextChild.name, nextChild.node); + } + else { + return newEventCache; + } + } + } + else if (childSnap.isEmpty()) { + // we're deleting a node, but it was not in the window, so ignore it + return snap; + } + else if (inRange) { + if (cmp(windowBoundary, newChildNamedNode) >= 0) { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node)); + changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap)); + } + return oldEventCache + .updateImmediateChild(childKey, childSnap) + .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE); + } + else { + return snap; + } + } + else { + return snap; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a + * range to be returned for a particular location. It is assumed that validation of parameters is done at the + * user-facing API level, so it is not done here. + * + * @internal + */ +class QueryParams { + constructor() { + this.limitSet_ = false; + this.startSet_ = false; + this.startNameSet_ = false; + this.startAfterSet_ = false; // can only be true if startSet_ is true + this.endSet_ = false; + this.endNameSet_ = false; + this.endBeforeSet_ = false; // can only be true if endSet_ is true + this.limit_ = 0; + this.viewFrom_ = ''; + this.indexStartValue_ = null; + this.indexStartName_ = ''; + this.indexEndValue_ = null; + this.indexEndName_ = ''; + this.index_ = PRIORITY_INDEX; + } + hasStart() { + return this.startSet_; + } + /** + * @returns True if it would return from left. + */ + isViewFromLeft() { + if (this.viewFrom_ === '') { + // limit(), rather than limitToFirst or limitToLast was called. + // This means that only one of startSet_ and endSet_ is true. Use them + // to calculate which side of the view to anchor to. If neither is set, + // anchor to the end. + return this.startSet_; + } + else { + return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */; + } + } + /** + * Only valid to call if hasStart() returns true + */ + getIndexStartValue() { + util.assert(this.startSet_, 'Only valid if start has been set'); + return this.indexStartValue_; + } + /** + * Only valid to call if hasStart() returns true. + * Returns the starting key name for the range defined by these query parameters + */ + getIndexStartName() { + util.assert(this.startSet_, 'Only valid if start has been set'); + if (this.startNameSet_) { + return this.indexStartName_; + } + else { + return MIN_NAME; + } + } + hasEnd() { + return this.endSet_; + } + /** + * Only valid to call if hasEnd() returns true. + */ + getIndexEndValue() { + util.assert(this.endSet_, 'Only valid if end has been set'); + return this.indexEndValue_; + } + /** + * Only valid to call if hasEnd() returns true. + * Returns the end key name for the range defined by these query parameters + */ + getIndexEndName() { + util.assert(this.endSet_, 'Only valid if end has been set'); + if (this.endNameSet_) { + return this.indexEndName_; + } + else { + return MAX_NAME; + } + } + hasLimit() { + return this.limitSet_; + } + /** + * @returns True if a limit has been set and it has been explicitly anchored + */ + hasAnchoredLimit() { + return this.limitSet_ && this.viewFrom_ !== ''; + } + /** + * Only valid to call if hasLimit() returns true + */ + getLimit() { + util.assert(this.limitSet_, 'Only valid if limit has been set'); + return this.limit_; + } + getIndex() { + return this.index_; + } + loadsAllData() { + return !(this.startSet_ || this.endSet_ || this.limitSet_); + } + isDefault() { + return this.loadsAllData() && this.index_ === PRIORITY_INDEX; + } + copy() { + const copy = new QueryParams(); + copy.limitSet_ = this.limitSet_; + copy.limit_ = this.limit_; + copy.startSet_ = this.startSet_; + copy.startAfterSet_ = this.startAfterSet_; + copy.indexStartValue_ = this.indexStartValue_; + copy.startNameSet_ = this.startNameSet_; + copy.indexStartName_ = this.indexStartName_; + copy.endSet_ = this.endSet_; + copy.endBeforeSet_ = this.endBeforeSet_; + copy.indexEndValue_ = this.indexEndValue_; + copy.endNameSet_ = this.endNameSet_; + copy.indexEndName_ = this.indexEndName_; + copy.index_ = this.index_; + copy.viewFrom_ = this.viewFrom_; + return copy; + } +} +function queryParamsGetNodeFilter(queryParams) { + if (queryParams.loadsAllData()) { + return new IndexedFilter(queryParams.getIndex()); + } + else if (queryParams.hasLimit()) { + return new LimitedFilter(queryParams); + } + else { + return new RangedFilter(queryParams); + } +} +function queryParamsLimitToFirst(queryParams, newLimit) { + const newParams = queryParams.copy(); + newParams.limitSet_ = true; + newParams.limit_ = newLimit; + newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */; + return newParams; +} +function queryParamsLimitToLast(queryParams, newLimit) { + const newParams = queryParams.copy(); + newParams.limitSet_ = true; + newParams.limit_ = newLimit; + newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */; + return newParams; +} +function queryParamsStartAt(queryParams, indexValue, key) { + const newParams = queryParams.copy(); + newParams.startSet_ = true; + if (indexValue === undefined) { + indexValue = null; + } + newParams.indexStartValue_ = indexValue; + if (key != null) { + newParams.startNameSet_ = true; + newParams.indexStartName_ = key; + } + else { + newParams.startNameSet_ = false; + newParams.indexStartName_ = ''; + } + return newParams; +} +function queryParamsStartAfter(queryParams, indexValue, key) { + let params; + if (queryParams.index_ === KEY_INDEX || !!key) { + params = queryParamsStartAt(queryParams, indexValue, key); + } + else { + params = queryParamsStartAt(queryParams, indexValue, MAX_NAME); + } + params.startAfterSet_ = true; + return params; +} +function queryParamsEndAt(queryParams, indexValue, key) { + const newParams = queryParams.copy(); + newParams.endSet_ = true; + if (indexValue === undefined) { + indexValue = null; + } + newParams.indexEndValue_ = indexValue; + if (key !== undefined) { + newParams.endNameSet_ = true; + newParams.indexEndName_ = key; + } + else { + newParams.endNameSet_ = false; + newParams.indexEndName_ = ''; + } + return newParams; +} +function queryParamsEndBefore(queryParams, indexValue, key) { + let params; + if (queryParams.index_ === KEY_INDEX || !!key) { + params = queryParamsEndAt(queryParams, indexValue, key); + } + else { + params = queryParamsEndAt(queryParams, indexValue, MIN_NAME); + } + params.endBeforeSet_ = true; + return params; +} +function queryParamsOrderBy(queryParams, index) { + const newParams = queryParams.copy(); + newParams.index_ = index; + return newParams; +} +/** + * Returns a set of REST query string parameters representing this query. + * + * @returns query string parameters + */ +function queryParamsToRestQueryStringParameters(queryParams) { + const qs = {}; + if (queryParams.isDefault()) { + return qs; + } + let orderBy; + if (queryParams.index_ === PRIORITY_INDEX) { + orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */; + } + else if (queryParams.index_ === VALUE_INDEX) { + orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */; + } + else if (queryParams.index_ === KEY_INDEX) { + orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */; + } + else { + util.assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!'); + orderBy = queryParams.index_.toString(); + } + qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = util.stringify(orderBy); + if (queryParams.startSet_) { + const startParam = queryParams.startAfterSet_ + ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */ + : "startAt" /* REST_QUERY_CONSTANTS.START_AT */; + qs[startParam] = util.stringify(queryParams.indexStartValue_); + if (queryParams.startNameSet_) { + qs[startParam] += ',' + util.stringify(queryParams.indexStartName_); + } + } + if (queryParams.endSet_) { + const endParam = queryParams.endBeforeSet_ + ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */ + : "endAt" /* REST_QUERY_CONSTANTS.END_AT */; + qs[endParam] = util.stringify(queryParams.indexEndValue_); + if (queryParams.endNameSet_) { + qs[endParam] += ',' + util.stringify(queryParams.indexEndName_); + } + } + if (queryParams.limitSet_) { + if (queryParams.isViewFromLeft()) { + qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_; + } + else { + qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_; + } + } + return qs; +} +function queryParamsGetQueryObject(queryParams) { + const obj = {}; + if (queryParams.startSet_) { + obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] = + queryParams.indexStartValue_; + if (queryParams.startNameSet_) { + obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] = + queryParams.indexStartName_; + } + obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] = + !queryParams.startAfterSet_; + } + if (queryParams.endSet_) { + obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_; + if (queryParams.endNameSet_) { + obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_; + } + obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] = + !queryParams.endBeforeSet_; + } + if (queryParams.limitSet_) { + obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_; + let viewFrom = queryParams.viewFrom_; + if (viewFrom === '') { + if (queryParams.isViewFromLeft()) { + viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */; + } + else { + viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */; + } + } + obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom; + } + // For now, priority index is the default, so we only specify if it's some other index + if (queryParams.index_ !== PRIORITY_INDEX) { + obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString(); + } + return obj; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An implementation of ServerActions that communicates with the server via REST requests. + * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full + * persistent connection (using WebSockets or long-polling) + */ +class ReadonlyRestClient extends ServerActions { + reportStats(stats) { + throw new Error('Method not implemented.'); + } + static getListenId_(query, tag) { + if (tag !== undefined) { + return 'tag$' + tag; + } + else { + util.assert(query._queryParams.isDefault(), "should have a tag if it's not a default query."); + return query._path.toString(); + } + } + /** + * @param repoInfo_ - Data about the namespace we are connecting to + * @param onDataUpdate_ - A callback for new data from the server + */ + constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) { + super(); + this.repoInfo_ = repoInfo_; + this.onDataUpdate_ = onDataUpdate_; + this.authTokenProvider_ = authTokenProvider_; + this.appCheckTokenProvider_ = appCheckTokenProvider_; + /** @private {function(...[*])} */ + this.log_ = logWrapper('p:rest:'); + /** + * We don't actually need to track listens, except to prevent us calling an onComplete for a listen + * that's been removed. :-/ + */ + this.listens_ = {}; + } + /** @inheritDoc */ + listen(query, currentHashFn, tag, onComplete) { + const pathString = query._path.toString(); + this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier); + // Mark this listener so we can tell if it's removed. + const listenId = ReadonlyRestClient.getListenId_(query, tag); + const thisListen = {}; + this.listens_[listenId] = thisListen; + const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams); + this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => { + let data = result; + if (error === 404) { + data = null; + error = null; + } + if (error === null) { + this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag); + } + if (util.safeGet(this.listens_, listenId) === thisListen) { + let status; + if (!error) { + status = 'ok'; + } + else if (error === 401) { + status = 'permission_denied'; + } + else { + status = 'rest_error:' + error; + } + onComplete(status, null); + } + }); + } + /** @inheritDoc */ + unlisten(query, tag) { + const listenId = ReadonlyRestClient.getListenId_(query, tag); + delete this.listens_[listenId]; + } + get(query) { + const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams); + const pathString = query._path.toString(); + const deferred = new util.Deferred(); + this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => { + let data = result; + if (error === 404) { + data = null; + error = null; + } + if (error === null) { + this.onDataUpdate_(pathString, data, + /*isMerge=*/ false, + /*tag=*/ null); + deferred.resolve(data); + } + else { + deferred.reject(new Error(data)); + } + }); + return deferred.promise; + } + /** @inheritDoc */ + refreshAuthToken(token) { + // no-op since we just always call getToken. + } + /** + * Performs a REST request to the given path, with the provided query string parameters, + * and any auth credentials we have. + */ + restRequest_(pathString, queryStringParameters = {}, callback) { + queryStringParameters['format'] = 'export'; + return Promise.all([ + this.authTokenProvider_.getToken(/*forceRefresh=*/ false), + this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false) + ]).then(([authToken, appCheckToken]) => { + if (authToken && authToken.accessToken) { + queryStringParameters['auth'] = authToken.accessToken; + } + if (appCheckToken && appCheckToken.token) { + queryStringParameters['ac'] = appCheckToken.token; + } + const url = (this.repoInfo_.secure ? 'https://' : 'http://') + + this.repoInfo_.host + + pathString + + '?' + + 'ns=' + + this.repoInfo_.namespace + + util.querystring(queryStringParameters); + this.log_('Sending REST request for ' + url); + const xhr = new XMLHttpRequest(); + xhr.onreadystatechange = () => { + if (callback && xhr.readyState === 4) { + this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText); + let res = null; + if (xhr.status >= 200 && xhr.status < 300) { + try { + res = util.jsonEval(xhr.responseText); + } + catch (e) { + warn('Failed to parse JSON response for ' + + url + + ': ' + + xhr.responseText); + } + callback(null, res); + } + else { + // 401 and 404 are expected. + if (xhr.status !== 401 && xhr.status !== 404) { + warn('Got unsuccessful REST response for ' + + url + + ' Status: ' + + xhr.status); + } + callback(xhr.status); + } + callback = null; + } + }; + xhr.open('GET', url, /*asynchronous=*/ true); + xhr.send(); + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Mutable object which basically just stores a reference to the "latest" immutable snapshot. + */ +class SnapshotHolder { + constructor() { + this.rootNode_ = ChildrenNode.EMPTY_NODE; + } + getNode(path) { + return this.rootNode_.getChild(path); + } + updateSnapshot(path, newSnapshotNode) { + this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newSparseSnapshotTree() { + return { + value: null, + children: new Map() + }; +} +/** + * Stores the given node at the specified path. If there is already a node + * at a shallower path, it merges the new data into that snapshot node. + * + * @param path - Path to look up snapshot for. + * @param data - The new data, or null. + */ +function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) { + if (pathIsEmpty(path)) { + sparseSnapshotTree.value = data; + sparseSnapshotTree.children.clear(); + } + else if (sparseSnapshotTree.value !== null) { + sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data); + } + else { + const childKey = pathGetFront(path); + if (!sparseSnapshotTree.children.has(childKey)) { + sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree()); + } + const child = sparseSnapshotTree.children.get(childKey); + path = pathPopFront(path); + sparseSnapshotTreeRemember(child, path, data); + } +} +/** + * Purge the data at path from the cache. + * + * @param path - Path to look up snapshot for. + * @returns True if this node should now be removed. + */ +function sparseSnapshotTreeForget(sparseSnapshotTree, path) { + if (pathIsEmpty(path)) { + sparseSnapshotTree.value = null; + sparseSnapshotTree.children.clear(); + return true; + } + else { + if (sparseSnapshotTree.value !== null) { + if (sparseSnapshotTree.value.isLeafNode()) { + // We're trying to forget a node that doesn't exist + return false; + } + else { + const value = sparseSnapshotTree.value; + sparseSnapshotTree.value = null; + value.forEachChild(PRIORITY_INDEX, (key, tree) => { + sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree); + }); + return sparseSnapshotTreeForget(sparseSnapshotTree, path); + } + } + else if (sparseSnapshotTree.children.size > 0) { + const childKey = pathGetFront(path); + path = pathPopFront(path); + if (sparseSnapshotTree.children.has(childKey)) { + const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path); + if (safeToRemove) { + sparseSnapshotTree.children.delete(childKey); + } + } + return sparseSnapshotTree.children.size === 0; + } + else { + return true; + } + } +} +/** + * Recursively iterates through all of the stored tree and calls the + * callback on each one. + * + * @param prefixPath - Path to look up node for. + * @param func - The function to invoke for each tree. + */ +function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) { + if (sparseSnapshotTree.value !== null) { + func(prefixPath, sparseSnapshotTree.value); + } + else { + sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => { + const path = new Path(prefixPath.toString() + '/' + key); + sparseSnapshotTreeForEachTree(tree, path, func); + }); + } +} +/** + * Iterates through each immediate child and triggers the callback. + * Only seems to be used in tests. + * + * @param func - The function to invoke for each child. + */ +function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) { + sparseSnapshotTree.children.forEach((tree, key) => { + func(key, tree); + }); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns the delta from the previous call to get stats. + * + * @param collection_ - The collection to "listen" to. + */ +class StatsListener { + constructor(collection_) { + this.collection_ = collection_; + this.last_ = null; + } + get() { + const newStats = this.collection_.get(); + const delta = { ...newStats }; + if (this.last_) { + each(this.last_, (stat, value) => { + delta[stat] = delta[stat] - value; + }); + } + this.last_ = newStats; + return delta; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably +// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10 +// seconds to try to ensure the Firebase connection is established / settled. +const FIRST_STATS_MIN_TIME = 10 * 1000; +const FIRST_STATS_MAX_TIME = 30 * 1000; +// We'll continue to report stats on average every 5 minutes. +const REPORT_STATS_INTERVAL = 5 * 60 * 1000; +class StatsReporter { + constructor(collection, server_) { + this.server_ = server_; + this.statsToReport_ = {}; + this.statsListener_ = new StatsListener(collection); + const timeout = FIRST_STATS_MIN_TIME + + (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random(); + setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout)); + } + reportStats_() { + const stats = this.statsListener_.get(); + const reportedStats = {}; + let haveStatsToReport = false; + each(stats, (stat, value) => { + if (value > 0 && util.contains(this.statsToReport_, stat)) { + reportedStats[stat] = value; + haveStatsToReport = true; + } + }); + if (haveStatsToReport) { + this.server_.reportStats(reportedStats); + } + // queue our next run. + setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @enum + */ +var OperationType; +(function (OperationType) { + OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE"; + OperationType[OperationType["MERGE"] = 1] = "MERGE"; + OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE"; + OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE"; +})(OperationType || (OperationType = {})); +function newOperationSourceUser() { + return { + fromUser: true, + fromServer: false, + queryId: null, + tagged: false + }; +} +function newOperationSourceServer() { + return { + fromUser: false, + fromServer: true, + queryId: null, + tagged: false + }; +} +function newOperationSourceServerTaggedQuery(queryId) { + return { + fromUser: false, + fromServer: true, + queryId, + tagged: true + }; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class AckUserWrite { + /** + * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap. + */ + constructor( + /** @inheritDoc */ path, + /** @inheritDoc */ affectedTree, + /** @inheritDoc */ revert) { + this.path = path; + this.affectedTree = affectedTree; + this.revert = revert; + /** @inheritDoc */ + this.type = OperationType.ACK_USER_WRITE; + /** @inheritDoc */ + this.source = newOperationSourceUser(); + } + operationForChild(childName) { + if (!pathIsEmpty(this.path)) { + util.assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.'); + return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert); + } + else if (this.affectedTree.value != null) { + util.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.'); + // All child locations are affected as well; just return same operation. + return this; + } + else { + const childTree = this.affectedTree.subtree(new Path(childName)); + return new AckUserWrite(newEmptyPath(), childTree, this.revert); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ListenComplete { + constructor(source, path) { + this.source = source; + this.path = path; + /** @inheritDoc */ + this.type = OperationType.LISTEN_COMPLETE; + } + operationForChild(childName) { + if (pathIsEmpty(this.path)) { + return new ListenComplete(this.source, newEmptyPath()); + } + else { + return new ListenComplete(this.source, pathPopFront(this.path)); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Overwrite { + constructor(source, path, snap) { + this.source = source; + this.path = path; + this.snap = snap; + /** @inheritDoc */ + this.type = OperationType.OVERWRITE; + } + operationForChild(childName) { + if (pathIsEmpty(this.path)) { + return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName)); + } + else { + return new Overwrite(this.source, pathPopFront(this.path), this.snap); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Merge { + constructor( + /** @inheritDoc */ source, + /** @inheritDoc */ path, + /** @inheritDoc */ children) { + this.source = source; + this.path = path; + this.children = children; + /** @inheritDoc */ + this.type = OperationType.MERGE; + } + operationForChild(childName) { + if (pathIsEmpty(this.path)) { + const childTree = this.children.subtree(new Path(childName)); + if (childTree.isEmpty()) { + // This child is unaffected + return null; + } + else if (childTree.value) { + // We have a snapshot for the child in question. This becomes an overwrite of the child. + return new Overwrite(this.source, newEmptyPath(), childTree.value); + } + else { + // This is a merge at a deeper level + return new Merge(this.source, newEmptyPath(), childTree); + } + } + else { + util.assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation"); + return new Merge(this.source, pathPopFront(this.path), this.children); + } + } + toString() { + return ('Operation(' + + this.path + + ': ' + + this.source.toString() + + ' merge: ' + + this.children.toString() + + ')'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully + * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g. + * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks + * whether a node potentially had children removed due to a filter. + */ +class CacheNode { + constructor(node_, fullyInitialized_, filtered_) { + this.node_ = node_; + this.fullyInitialized_ = fullyInitialized_; + this.filtered_ = filtered_; + } + /** + * Returns whether this node was fully initialized with either server data or a complete overwrite by the client + */ + isFullyInitialized() { + return this.fullyInitialized_; + } + /** + * Returns whether this node is potentially missing children due to a filter applied to the node + */ + isFiltered() { + return this.filtered_; + } + isCompleteForPath(path) { + if (pathIsEmpty(path)) { + return this.isFullyInitialized() && !this.filtered_; + } + const childKey = pathGetFront(path); + return this.isCompleteForChild(childKey); + } + isCompleteForChild(key) { + return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key)); + } + getNode() { + return this.node_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An EventGenerator is used to convert "raw" changes (Change) as computed by the + * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges() + * for details. + * + */ +class EventGenerator { + constructor(query_) { + this.query_ = query_; + this.index_ = this.query_._queryParams.getIndex(); + } +} +/** + * Given a set of raw changes (no moved events and prevName not specified yet), and a set of + * EventRegistrations that should be notified of these changes, generate the actual events to be raised. + * + * Notes: + * - child_moved events will be synthesized at this time for any child_changed events that affect + * our index. + * - prevName will be calculated based on the index ordering. + */ +function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) { + const events = []; + const moves = []; + changes.forEach(change => { + if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ && + eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) { + moves.push(changeChildMoved(change.childName, change.snapshotNode)); + } + }); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache); + return events; +} +/** + * Given changes of a single change type, generate the corresponding events. + */ +function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) { + const filteredChanges = changes.filter(change => change.type === eventType); + filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b)); + filteredChanges.forEach(change => { + const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache); + registrations.forEach(registration => { + if (registration.respondsTo(change.type)) { + events.push(registration.createEvent(materializedChange, eventGenerator.query_)); + } + }); + }); +} +function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) { + if (change.type === 'value' || change.type === 'child_removed') { + return change; + } + else { + change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_); + return change; + } +} +function eventGeneratorCompareChanges(eventGenerator, a, b) { + if (a.childName == null || b.childName == null) { + throw util.assertionError('Should only compare child_ events.'); + } + const aWrapped = new NamedNode(a.childName, a.snapshotNode); + const bWrapped = new NamedNode(b.childName, b.snapshotNode); + return eventGenerator.index_.compare(aWrapped, bWrapped); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newViewCache(eventCache, serverCache) { + return { eventCache, serverCache }; +} +function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) { + return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache); +} +function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) { + return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered)); +} +function viewCacheGetCompleteEventSnap(viewCache) { + return viewCache.eventCache.isFullyInitialized() + ? viewCache.eventCache.getNode() + : null; +} +function viewCacheGetCompleteServerSnap(viewCache) { + return viewCache.serverCache.isFullyInitialized() + ? viewCache.serverCache.getNode() + : null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let emptyChildrenSingleton; +/** + * Singleton empty children collection. + * + */ +const EmptyChildren = () => { + if (!emptyChildrenSingleton) { + emptyChildrenSingleton = new SortedMap(stringCompare); + } + return emptyChildrenSingleton; +}; +/** + * A tree with immutable elements. + */ +class ImmutableTree { + static fromObject(obj) { + let tree = new ImmutableTree(null); + each(obj, (childPath, childSnap) => { + tree = tree.set(new Path(childPath), childSnap); + }); + return tree; + } + constructor(value, children = EmptyChildren()) { + this.value = value; + this.children = children; + } + /** + * True if the value is empty and there are no children + */ + isEmpty() { + return this.value === null && this.children.isEmpty(); + } + /** + * Given a path and predicate, return the first node and the path to that node + * where the predicate returns true. + * + * TODO Do a perf test -- If we're creating a bunch of `{path: value:}` + * objects on the way back out, it may be better to pass down a pathSoFar obj. + * + * @param relativePath - The remainder of the path + * @param predicate - The predicate to satisfy to return a node + */ + findRootMostMatchingPathAndValue(relativePath, predicate) { + if (this.value != null && predicate(this.value)) { + return { path: newEmptyPath(), value: this.value }; + } + else { + if (pathIsEmpty(relativePath)) { + return null; + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front); + if (child !== null) { + const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate); + if (childExistingPathAndValue != null) { + const fullPath = pathChild(new Path(front), childExistingPathAndValue.path); + return { path: fullPath, value: childExistingPathAndValue.value }; + } + else { + return null; + } + } + else { + return null; + } + } + } + } + /** + * Find, if it exists, the shortest subpath of the given path that points a defined + * value in the tree + */ + findRootMostValueAndPath(relativePath) { + return this.findRootMostMatchingPathAndValue(relativePath, () => true); + } + /** + * @returns The subtree at the given path + */ + subtree(relativePath) { + if (pathIsEmpty(relativePath)) { + return this; + } + else { + const front = pathGetFront(relativePath); + const childTree = this.children.get(front); + if (childTree !== null) { + return childTree.subtree(pathPopFront(relativePath)); + } + else { + return new ImmutableTree(null); + } + } + } + /** + * Sets a value at the specified path. + * + * @param relativePath - Path to set value at. + * @param toSet - Value to set. + * @returns Resulting tree. + */ + set(relativePath, toSet) { + if (pathIsEmpty(relativePath)) { + return new ImmutableTree(toSet, this.children); + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front) || new ImmutableTree(null); + const newChild = child.set(pathPopFront(relativePath), toSet); + const newChildren = this.children.insert(front, newChild); + return new ImmutableTree(this.value, newChildren); + } + } + /** + * Removes the value at the specified path. + * + * @param relativePath - Path to value to remove. + * @returns Resulting tree. + */ + remove(relativePath) { + if (pathIsEmpty(relativePath)) { + if (this.children.isEmpty()) { + return new ImmutableTree(null); + } + else { + return new ImmutableTree(null, this.children); + } + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front); + if (child) { + const newChild = child.remove(pathPopFront(relativePath)); + let newChildren; + if (newChild.isEmpty()) { + newChildren = this.children.remove(front); + } + else { + newChildren = this.children.insert(front, newChild); + } + if (this.value === null && newChildren.isEmpty()) { + return new ImmutableTree(null); + } + else { + return new ImmutableTree(this.value, newChildren); + } + } + else { + return this; + } + } + } + /** + * Gets a value from the tree. + * + * @param relativePath - Path to get value for. + * @returns Value at path, or null. + */ + get(relativePath) { + if (pathIsEmpty(relativePath)) { + return this.value; + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front); + if (child) { + return child.get(pathPopFront(relativePath)); + } + else { + return null; + } + } + } + /** + * Replace the subtree at the specified path with the given new tree. + * + * @param relativePath - Path to replace subtree for. + * @param newTree - New tree. + * @returns Resulting tree. + */ + setTree(relativePath, newTree) { + if (pathIsEmpty(relativePath)) { + return newTree; + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front) || new ImmutableTree(null); + const newChild = child.setTree(pathPopFront(relativePath), newTree); + let newChildren; + if (newChild.isEmpty()) { + newChildren = this.children.remove(front); + } + else { + newChildren = this.children.insert(front, newChild); + } + return new ImmutableTree(this.value, newChildren); + } + } + /** + * Performs a depth first fold on this tree. Transforms a tree into a single + * value, given a function that operates on the path to a node, an optional + * current value, and a map of child names to folded subtrees + */ + fold(fn) { + return this.fold_(newEmptyPath(), fn); + } + /** + * Recursive helper for public-facing fold() method + */ + fold_(pathSoFar, fn) { + const accum = {}; + this.children.inorderTraversal((childKey, childTree) => { + accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn); + }); + return fn(pathSoFar, this.value, accum); + } + /** + * Find the first matching value on the given path. Return the result of applying f to it. + */ + findOnPath(path, f) { + return this.findOnPath_(path, newEmptyPath(), f); + } + findOnPath_(pathToFollow, pathSoFar, f) { + const result = this.value ? f(pathSoFar, this.value) : false; + if (result) { + return result; + } + else { + if (pathIsEmpty(pathToFollow)) { + return null; + } + else { + const front = pathGetFront(pathToFollow); + const nextChild = this.children.get(front); + if (nextChild) { + return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f); + } + else { + return null; + } + } + } + } + foreachOnPath(path, f) { + return this.foreachOnPath_(path, newEmptyPath(), f); + } + foreachOnPath_(pathToFollow, currentRelativePath, f) { + if (pathIsEmpty(pathToFollow)) { + return this; + } + else { + if (this.value) { + f(currentRelativePath, this.value); + } + const front = pathGetFront(pathToFollow); + const nextChild = this.children.get(front); + if (nextChild) { + return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f); + } + else { + return new ImmutableTree(null); + } + } + } + /** + * Calls the given function for each node in the tree that has a value. + * + * @param f - A function to be called with the path from the root of the tree to + * a node, and the value at that node. Called in depth-first order. + */ + foreach(f) { + this.foreach_(newEmptyPath(), f); + } + foreach_(currentRelativePath, f) { + this.children.inorderTraversal((childName, childTree) => { + childTree.foreach_(pathChild(currentRelativePath, childName), f); + }); + if (this.value) { + f(currentRelativePath, this.value); + } + } + foreachChild(f) { + this.children.inorderTraversal((childName, childTree) => { + if (childTree.value) { + f(childName, childTree.value); + } + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with + * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write + * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write + * to reflect the write added. + */ +class CompoundWrite { + constructor(writeTree_) { + this.writeTree_ = writeTree_; + } + static empty() { + return new CompoundWrite(new ImmutableTree(null)); + } +} +function compoundWriteAddWrite(compoundWrite, path, node) { + if (pathIsEmpty(path)) { + return new CompoundWrite(new ImmutableTree(node)); + } + else { + const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path); + if (rootmost != null) { + const rootMostPath = rootmost.path; + let value = rootmost.value; + const relativePath = newRelativePath(rootMostPath, path); + value = value.updateChild(relativePath, node); + return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value)); + } + else { + const subtree = new ImmutableTree(node); + const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree); + return new CompoundWrite(newWriteTree); + } + } +} +function compoundWriteAddWrites(compoundWrite, path, updates) { + let newWrite = compoundWrite; + each(updates, (childKey, node) => { + newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node); + }); + return newWrite; +} +/** + * Will remove a write at the given path and deeper paths. This will not modify a write at a higher + * location, which must be removed by calling this method with that path. + * + * @param compoundWrite - The CompoundWrite to remove. + * @param path - The path at which a write and all deeper writes should be removed + * @returns The new CompoundWrite with the removed path + */ +function compoundWriteRemoveWrite(compoundWrite, path) { + if (pathIsEmpty(path)) { + return CompoundWrite.empty(); + } + else { + const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null)); + return new CompoundWrite(newWriteTree); + } +} +/** + * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be + * considered "complete". + * + * @param compoundWrite - The CompoundWrite to check. + * @param path - The path to check for + * @returns Whether there is a complete write at that path + */ +function compoundWriteHasCompleteWrite(compoundWrite, path) { + return compoundWriteGetCompleteNode(compoundWrite, path) != null; +} +/** + * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate + * writes from deeper paths, but will return child nodes from a more shallow path. + * + * @param compoundWrite - The CompoundWrite to get the node from. + * @param path - The path to get a complete write + * @returns The node if complete at that path, or null otherwise. + */ +function compoundWriteGetCompleteNode(compoundWrite, path) { + const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path); + if (rootmost != null) { + return compoundWrite.writeTree_ + .get(rootmost.path) + .getChild(newRelativePath(rootmost.path, path)); + } + else { + return null; + } +} +/** + * Returns all children that are guaranteed to be a complete overwrite. + * + * @param compoundWrite - The CompoundWrite to get children from. + * @returns A list of all complete children. + */ +function compoundWriteGetCompleteChildren(compoundWrite) { + const children = []; + const node = compoundWrite.writeTree_.value; + if (node != null) { + // If it's a leaf node, it has no children; so nothing to do. + if (!node.isLeafNode()) { + node.forEachChild(PRIORITY_INDEX, (childName, childNode) => { + children.push(new NamedNode(childName, childNode)); + }); + } + } + else { + compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => { + if (childTree.value != null) { + children.push(new NamedNode(childName, childTree.value)); + } + }); + } + return children; +} +function compoundWriteChildCompoundWrite(compoundWrite, path) { + if (pathIsEmpty(path)) { + return compoundWrite; + } + else { + const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path); + if (shadowingNode != null) { + return new CompoundWrite(new ImmutableTree(shadowingNode)); + } + else { + return new CompoundWrite(compoundWrite.writeTree_.subtree(path)); + } + } +} +/** + * Returns true if this CompoundWrite is empty and therefore does not modify any nodes. + * @returns Whether this CompoundWrite is empty + */ +function compoundWriteIsEmpty(compoundWrite) { + return compoundWrite.writeTree_.isEmpty(); +} +/** + * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the + * node + * @param node - The node to apply this CompoundWrite to + * @returns The node with all writes applied + */ +function compoundWriteApply(compoundWrite, node) { + return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node); +} +function applySubtreeWrite(relativePath, writeTree, node) { + if (writeTree.value != null) { + // Since there a write is always a leaf, we're done here + return node.updateChild(relativePath, writeTree.value); + } + else { + let priorityWrite = null; + writeTree.children.inorderTraversal((childKey, childTree) => { + if (childKey === '.priority') { + // Apply priorities at the end so we don't update priorities for either empty nodes or forget + // to apply priorities to empty nodes that are later filled + util.assert(childTree.value !== null, 'Priority writes must always be leaf nodes'); + priorityWrite = childTree.value; + } + else { + node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node); + } + }); + // If there was a priority write, we only apply it if the node is not empty + if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) { + node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite); + } + return node; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path. + * + */ +function writeTreeChildWrites(writeTree, path) { + return newWriteTreeRef(path, writeTree); +} +/** + * Record a new overwrite from user code. + * + * @param visible - This is set to false by some transactions. It should be excluded from event caches + */ +function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) { + util.assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones'); + if (visible === undefined) { + visible = true; + } + writeTree.allWrites.push({ + path, + snap, + writeId, + visible + }); + if (visible) { + writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap); + } + writeTree.lastWriteId = writeId; +} +/** + * Record a new merge from user code. + */ +function writeTreeAddMerge(writeTree, path, changedChildren, writeId) { + util.assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones'); + writeTree.allWrites.push({ + path, + children: changedChildren, + writeId, + visible: true + }); + writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren); + writeTree.lastWriteId = writeId; +} +function writeTreeGetWrite(writeTree, writeId) { + for (let i = 0; i < writeTree.allWrites.length; i++) { + const record = writeTree.allWrites[i]; + if (record.writeId === writeId) { + return record; + } + } + return null; +} +/** + * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates + * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate. + * + * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise + * events as a result). + */ +function writeTreeRemoveWrite(writeTree, writeId) { + // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied + // out of order. + //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId; + //assert(validClear, "Either we don't have this write, or it's the first one in the queue"); + const idx = writeTree.allWrites.findIndex(s => { + return s.writeId === writeId; + }); + util.assert(idx >= 0, 'removeWrite called with nonexistent writeId.'); + const writeToRemove = writeTree.allWrites[idx]; + writeTree.allWrites.splice(idx, 1); + let removedWriteWasVisible = writeToRemove.visible; + let removedWriteOverlapsWithOtherWrites = false; + let i = writeTree.allWrites.length - 1; + while (removedWriteWasVisible && i >= 0) { + const currentWrite = writeTree.allWrites[i]; + if (currentWrite.visible) { + if (i >= idx && + writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) { + // The removed write was completely shadowed by a subsequent write. + removedWriteWasVisible = false; + } + else if (pathContains(writeToRemove.path, currentWrite.path)) { + // Either we're covering some writes or they're covering part of us (depending on which came first). + removedWriteOverlapsWithOtherWrites = true; + } + } + i--; + } + if (!removedWriteWasVisible) { + return false; + } + else if (removedWriteOverlapsWithOtherWrites) { + // There's some shadowing going on. Just rebuild the visible writes from scratch. + writeTreeResetTree_(writeTree); + return true; + } + else { + // There's no shadowing. We can safely just remove the write(s) from visibleWrites. + if (writeToRemove.snap) { + writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path); + } + else { + const children = writeToRemove.children; + each(children, (childName) => { + writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName)); + }); + } + return true; + } +} +function writeTreeRecordContainsPath_(writeRecord, path) { + if (writeRecord.snap) { + return pathContains(writeRecord.path, path); + } + else { + for (const childName in writeRecord.children) { + if (writeRecord.children.hasOwnProperty(childName) && + pathContains(pathChild(writeRecord.path, childName), path)) { + return true; + } + } + return false; + } +} +/** + * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots + */ +function writeTreeResetTree_(writeTree) { + writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath()); + if (writeTree.allWrites.length > 0) { + writeTree.lastWriteId = + writeTree.allWrites[writeTree.allWrites.length - 1].writeId; + } + else { + writeTree.lastWriteId = -1; + } +} +/** + * The default filter used when constructing the tree. Keep everything that's visible. + */ +function writeTreeDefaultFilter_(write) { + return write.visible; +} +/** + * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of + * event data at that path. + */ +function writeTreeLayerTree_(writes, filter, treeRoot) { + let compoundWrite = CompoundWrite.empty(); + for (let i = 0; i < writes.length; ++i) { + const write = writes[i]; + // Theory, a later set will either: + // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction + // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction + if (filter(write)) { + const writePath = write.path; + let relativePath; + if (write.snap) { + if (pathContains(treeRoot, writePath)) { + relativePath = newRelativePath(treeRoot, writePath); + compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap); + } + else if (pathContains(writePath, treeRoot)) { + relativePath = newRelativePath(writePath, treeRoot); + compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath)); + } + else ; + } + else if (write.children) { + if (pathContains(treeRoot, writePath)) { + relativePath = newRelativePath(treeRoot, writePath); + compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children); + } + else if (pathContains(writePath, treeRoot)) { + relativePath = newRelativePath(writePath, treeRoot); + if (pathIsEmpty(relativePath)) { + compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children); + } + else { + const child = util.safeGet(write.children, pathGetFront(relativePath)); + if (child) { + // There exists a child in this node that matches the root path + const deepNode = child.getChild(pathPopFront(relativePath)); + compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode); + } + } + } + else ; + } + else { + throw util.assertionError('WriteRecord should have .snap or .children'); + } + } + } + return compoundWrite; +} +/** + * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden + * writes), attempt to calculate a complete snapshot for the given path + * + * @param writeIdsToExclude - An optional set to be excluded + * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false + */ +function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) { + if (!writeIdsToExclude && !includeHiddenWrites) { + const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath); + if (shadowingNode != null) { + return shadowingNode; + } + else { + const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + if (compoundWriteIsEmpty(subMerge)) { + return completeServerCache; + } + else if (completeServerCache == null && + !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) { + // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow + return null; + } + else { + const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE; + return compoundWriteApply(subMerge, layeredCache); + } + } + } + else { + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) { + return completeServerCache; + } + else { + // If the server cache is null, and we don't have a complete cache, we need to return null + if (!includeHiddenWrites && + completeServerCache == null && + !compoundWriteHasCompleteWrite(merge, newEmptyPath())) { + return null; + } + else { + const filter = function (write) { + return ((write.visible || includeHiddenWrites) && + (!writeIdsToExclude || + !~writeIdsToExclude.indexOf(write.writeId)) && + (pathContains(write.path, treePath) || + pathContains(treePath, write.path))); + }; + const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath); + const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE; + return compoundWriteApply(mergeAtPath, layeredCache); + } + } + } +} +/** + * With optional, underlying server data, attempt to return a children node of children that we have complete data for. + * Used when creating new views, to pre-fill their complete event children snapshot. + */ +function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) { + let completeChildren = ChildrenNode.EMPTY_NODE; + const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath); + if (topLevelSet) { + if (!topLevelSet.isLeafNode()) { + // we're shadowing everything. Return the children. + topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => { + completeChildren = completeChildren.updateImmediateChild(childName, childSnap); + }); + } + return completeChildren; + } + else if (completeServerChildren) { + // Layer any children we have on top of this + // We know we don't have a top-level set, so just enumerate existing children + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => { + const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode); + completeChildren = completeChildren.updateImmediateChild(childName, node); + }); + // Add any complete children we have from the set + compoundWriteGetCompleteChildren(merge).forEach(namedNode => { + completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node); + }); + return completeChildren; + } + else { + // We don't have anything to layer on top of. Layer on any children we have + // Note that we can return an empty snap if we have a defined delete + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + compoundWriteGetCompleteChildren(merge).forEach(namedNode => { + completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node); + }); + return completeChildren; + } +} +/** + * Given that the underlying server data has updated, determine what, if anything, needs to be + * applied to the event cache. + * + * Possibilities: + * + * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data + * + * 2. Some write is completely shadowing. No events to be raised + * + * 3. Is partially shadowed. Events + * + * Either existingEventSnap or existingServerSnap must exist + */ +function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) { + util.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist'); + const path = pathChild(treePath, childPath); + if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) { + // At this point we can probably guarantee that we're in case 2, meaning no events + // May need to check visibility while doing the findRootMostValueAndPath call + return null; + } + else { + // No complete shadowing. We're either partially shadowing or not shadowing at all. + const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path); + if (compoundWriteIsEmpty(childMerge)) { + // We're not shadowing at all. Case 1 + return existingServerSnap.getChild(childPath); + } + else { + // This could be more efficient if the serverNode + updates doesn't change the eventSnap + // However this is tricky to find out, since user updates don't necessary change the server + // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server + // adds nodes, but doesn't change any existing writes. It is therefore not enough to + // only check if the updates change the serverNode. + // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case? + return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath)); + } + } +} +/** + * Returns a complete child for a given server snap after applying all user writes or null if there is no + * complete child for this ChildKey. + */ +function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) { + const path = pathChild(treePath, childKey); + const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path); + if (shadowingNode != null) { + return shadowingNode; + } + else { + if (existingServerSnap.isCompleteForChild(childKey)) { + const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path); + return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey)); + } + else { + return null; + } + } +} +/** + * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at + * a higher path, this will return the child of that write relative to the write and this path. + * Returns null if there is no write at this path. + */ +function writeTreeShadowingWrite(writeTree, path) { + return compoundWriteGetCompleteNode(writeTree.visibleWrites, path); +} +/** + * This method is used when processing child remove events on a query. If we can, we pull in children that were outside + * the window, but may now be in the window. + */ +function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) { + let toIterate; + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath()); + if (shadowingNode != null) { + toIterate = shadowingNode; + } + else if (completeServerData != null) { + toIterate = compoundWriteApply(merge, completeServerData); + } + else { + // no children to iterate on + return []; + } + toIterate = toIterate.withIndex(index); + if (!toIterate.isEmpty() && !toIterate.isLeafNode()) { + const nodes = []; + const cmp = index.getCompare(); + const iter = reverse + ? toIterate.getReverseIteratorFrom(startPost, index) + : toIterate.getIteratorFrom(startPost, index); + let next = iter.getNext(); + while (next && nodes.length < count) { + if (cmp(next, startPost) !== 0) { + nodes.push(next); + } + next = iter.getNext(); + } + return nodes; + } + else { + return []; + } +} +function newWriteTree() { + return { + visibleWrites: CompoundWrite.empty(), + allWrites: [], + lastWriteId: -1 + }; +} +/** + * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used + * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node + * can lead to a more expensive calculation. + * + * @param writeIdsToExclude - Optional writes to exclude. + * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false + */ +function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) { + return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites); +} +/** + * If possible, returns a children node containing all of the complete children we have data for. The returned data is a + * mix of the given server data and write data. + * + */ +function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) { + return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren); +} +/** + * Given that either the underlying server data has updated or the outstanding writes have updated, determine what, + * if anything, needs to be applied to the event cache. + * + * Possibilities: + * + * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data + * + * 2. Some write is completely shadowing. No events to be raised + * + * 3. Is partially shadowed. Events should be raised + * + * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert + * + * + */ +function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) { + return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap); +} +/** + * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at + * a higher path, this will return the child of that write relative to the write and this path. + * Returns null if there is no write at this path. + * + */ +function writeTreeRefShadowingWrite(writeTreeRef, path) { + return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path)); +} +/** + * This method is used when processing child remove events on a query. If we can, we pull in children that were outside + * the window, but may now be in the window + */ +function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) { + return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index); +} +/** + * Returns a complete child for a given server snap after applying all user writes or null if there is no + * complete child for this ChildKey. + */ +function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) { + return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache); +} +/** + * Return a WriteTreeRef for a child. + */ +function writeTreeRefChild(writeTreeRef, childName) { + return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree); +} +function newWriteTreeRef(path, writeTree) { + return { + treePath: path, + writeTree + }; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ChildChangeAccumulator { + constructor() { + this.changeMap = new Map(); + } + trackChildChange(change) { + const type = change.type; + const childKey = change.childName; + util.assert(type === "child_added" /* ChangeType.CHILD_ADDED */ || + type === "child_changed" /* ChangeType.CHILD_CHANGED */ || + type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking'); + util.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.'); + const oldChange = this.changeMap.get(childKey); + if (oldChange) { + const oldType = oldChange.type; + if (type === "child_added" /* ChangeType.CHILD_ADDED */ && + oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) { + this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode)); + } + else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ && + oldType === "child_added" /* ChangeType.CHILD_ADDED */) { + this.changeMap.delete(childKey); + } + else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ && + oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) { + this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap)); + } + else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ && + oldType === "child_added" /* ChangeType.CHILD_ADDED */) { + this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode)); + } + else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ && + oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) { + this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap)); + } + else { + throw util.assertionError('Illegal combination of changes: ' + + change + + ' occurred after ' + + oldChange); + } + } + else { + this.changeMap.set(childKey, change); + } + } + getChanges() { + return Array.from(this.changeMap.values()); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An implementation of CompleteChildSource that never returns any additional children + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class NoCompleteChildSource_ { + getCompleteChild(childKey) { + return null; + } + getChildAfterChild(index, child, reverse) { + return null; + } +} +/** + * Singleton instance. + */ +const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_(); +/** + * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or + * old event caches available to calculate complete children. + */ +class WriteTreeCompleteChildSource { + constructor(writes_, viewCache_, optCompleteServerCache_ = null) { + this.writes_ = writes_; + this.viewCache_ = viewCache_; + this.optCompleteServerCache_ = optCompleteServerCache_; + } + getCompleteChild(childKey) { + const node = this.viewCache_.eventCache; + if (node.isCompleteForChild(childKey)) { + return node.getNode().getImmediateChild(childKey); + } + else { + const serverNode = this.optCompleteServerCache_ != null + ? new CacheNode(this.optCompleteServerCache_, true, false) + : this.viewCache_.serverCache; + return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode); + } + } + getChildAfterChild(index, child, reverse) { + const completeServerData = this.optCompleteServerCache_ != null + ? this.optCompleteServerCache_ + : viewCacheGetCompleteServerSnap(this.viewCache_); + const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index); + if (nodes.length === 0) { + return null; + } + else { + return nodes[0]; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newViewProcessor(filter) { + return { filter }; +} +function viewProcessorAssertIndexed(viewProcessor, viewCache) { + util.assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed'); + util.assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed'); +} +function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) { + const accumulator = new ChildChangeAccumulator(); + let newViewCache, filterServerNode; + if (operation.type === OperationType.OVERWRITE) { + const overwrite = operation; + if (overwrite.source.fromUser) { + newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator); + } + else { + util.assert(overwrite.source.fromServer, 'Unknown source.'); + // We filter the node if it's a tagged update or the node has been previously filtered and the + // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered + // again + filterServerNode = + overwrite.source.tagged || + (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path)); + newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator); + } + } + else if (operation.type === OperationType.MERGE) { + const merge = operation; + if (merge.source.fromUser) { + newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator); + } + else { + util.assert(merge.source.fromServer, 'Unknown source.'); + // We filter the node if it's a tagged update or the node has been previously filtered + filterServerNode = + merge.source.tagged || oldViewCache.serverCache.isFiltered(); + newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator); + } + } + else if (operation.type === OperationType.ACK_USER_WRITE) { + const ackUserWrite = operation; + if (!ackUserWrite.revert) { + newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator); + } + else { + newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator); + } + } + else if (operation.type === OperationType.LISTEN_COMPLETE) { + newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator); + } + else { + throw util.assertionError('Unknown operation type: ' + operation.type); + } + const changes = accumulator.getChanges(); + viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes); + return { viewCache: newViewCache, changes }; +} +function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) { + const eventSnap = newViewCache.eventCache; + if (eventSnap.isFullyInitialized()) { + const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty(); + const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache); + if (accumulator.length > 0 || + !oldViewCache.eventCache.isFullyInitialized() || + (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) || + !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) { + accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache))); + } + } +} +function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) { + const oldEventSnap = viewCache.eventCache; + if (writeTreeRefShadowingWrite(writesCache, changePath) != null) { + // we have a shadowing write, ignore changes + return viewCache; + } + else { + let newEventCache, serverNode; + if (pathIsEmpty(changePath)) { + // TODO: figure out how this plays with "sliding ack windows" + util.assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data'); + if (viewCache.serverCache.isFiltered()) { + // We need to special case this, because we need to only apply writes to complete children, or + // we might end up raising events for incomplete children. If the server data is filtered deep + // writes cannot be guaranteed to be complete + const serverCache = viewCacheGetCompleteServerSnap(viewCache); + const completeChildren = serverCache instanceof ChildrenNode + ? serverCache + : ChildrenNode.EMPTY_NODE; + const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren); + newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator); + } + else { + const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache)); + newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator); + } + } + else { + const childKey = pathGetFront(changePath); + if (childKey === '.priority') { + util.assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components"); + const oldEventNode = oldEventSnap.getNode(); + serverNode = viewCache.serverCache.getNode(); + // we might have overwrites for this priority + const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode); + if (updatedPriority != null) { + newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority); + } + else { + // priority didn't change, keep old node + newEventCache = oldEventSnap.getNode(); + } + } + else { + const childChangePath = pathPopFront(changePath); + // update child + let newEventChild; + if (oldEventSnap.isCompleteForChild(childKey)) { + serverNode = viewCache.serverCache.getNode(); + const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode); + if (eventChildUpdate != null) { + newEventChild = oldEventSnap + .getNode() + .getImmediateChild(childKey) + .updateChild(childChangePath, eventChildUpdate); + } + else { + // Nothing changed, just keep the old child + newEventChild = oldEventSnap.getNode().getImmediateChild(childKey); + } + } + else { + newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache); + } + if (newEventChild != null) { + newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator); + } + else { + // no complete child available or no change + newEventCache = oldEventSnap.getNode(); + } + } + } + return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes()); + } +} +function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) { + const oldServerSnap = oldViewCache.serverCache; + let newServerCache; + const serverFilter = filterServerNode + ? viewProcessor.filter + : viewProcessor.filter.getIndexedFilter(); + if (pathIsEmpty(changePath)) { + newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null); + } + else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) { + // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update + const newServerNode = oldServerSnap + .getNode() + .updateChild(changePath, changedSnap); + newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null); + } + else { + const childKey = pathGetFront(changePath); + if (!oldServerSnap.isCompleteForPath(changePath) && + pathGetLength(changePath) > 1) { + // We don't update incomplete nodes with updates intended for other listeners + return oldViewCache; + } + const childChangePath = pathPopFront(changePath); + const childNode = oldServerSnap.getNode().getImmediateChild(childKey); + const newChildNode = childNode.updateChild(childChangePath, changedSnap); + if (childKey === '.priority') { + newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode); + } + else { + newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null); + } + } + const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes()); + const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache); + return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator); +} +function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) { + const oldEventSnap = oldViewCache.eventCache; + let newViewCache, newEventCache; + const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache); + if (pathIsEmpty(changePath)) { + newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator); + newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes()); + } + else { + const childKey = pathGetFront(changePath); + if (childKey === '.priority') { + newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap); + newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered()); + } + else { + const childChangePath = pathPopFront(changePath); + const oldChild = oldEventSnap.getNode().getImmediateChild(childKey); + let newChild; + if (pathIsEmpty(childChangePath)) { + // Child overwrite, we can replace the child + newChild = changedSnap; + } + else { + const childNode = source.getCompleteChild(childKey); + if (childNode != null) { + if (pathGetBack(childChangePath) === '.priority' && + childNode.getChild(pathParent(childChangePath)).isEmpty()) { + // This is a priority update on an empty node. If this node exists on the server, the + // server will send down the priority in the update, so ignore for now + newChild = childNode; + } + else { + newChild = childNode.updateChild(childChangePath, changedSnap); + } + } + else { + // There is no complete child node available + newChild = ChildrenNode.EMPTY_NODE; + } + } + if (!oldChild.equals(newChild)) { + const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator); + newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes()); + } + else { + newViewCache = oldViewCache; + } + } + } + return newViewCache; +} +function viewProcessorCacheHasChild(viewCache, childKey) { + return viewCache.eventCache.isCompleteForChild(childKey); +} +function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) { + // HACK: In the case of a limit query, there may be some changes that bump things out of the + // window leaving room for new items. It's important we process these changes first, so we + // iterate the changes twice, first processing any that affect items currently in view. + // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server + // and event snap. I'm not sure if this will result in edge cases when a child is in one but + // not the other. + let curViewCache = viewCache; + changedChildren.foreach((relativePath, childNode) => { + const writePath = pathChild(path, relativePath); + if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) { + curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator); + } + }); + changedChildren.foreach((relativePath, childNode) => { + const writePath = pathChild(path, relativePath); + if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) { + curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator); + } + }); + return curViewCache; +} +function viewProcessorApplyMerge(viewProcessor, node, merge) { + merge.foreach((relativePath, childNode) => { + node = node.updateChild(relativePath, childNode); + }); + return node; +} +function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) { + // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and + // wait for the complete data update coming soon. + if (viewCache.serverCache.getNode().isEmpty() && + !viewCache.serverCache.isFullyInitialized()) { + return viewCache; + } + // HACK: In the case of a limit query, there may be some changes that bump things out of the + // window leaving room for new items. It's important we process these changes first, so we + // iterate the changes twice, first processing any that affect items currently in view. + // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server + // and event snap. I'm not sure if this will result in edge cases when a child is in one but + // not the other. + let curViewCache = viewCache; + let viewMergeTree; + if (pathIsEmpty(path)) { + viewMergeTree = changedChildren; + } + else { + viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren); + } + const serverNode = viewCache.serverCache.getNode(); + viewMergeTree.children.inorderTraversal((childKey, childTree) => { + if (serverNode.hasChild(childKey)) { + const serverChild = viewCache.serverCache + .getNode() + .getImmediateChild(childKey); + const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree); + curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator); + } + }); + viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => { + const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) && + childMergeTree.value === null; + if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) { + const serverChild = viewCache.serverCache + .getNode() + .getImmediateChild(childKey); + const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree); + curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator); + } + }); + return curViewCache; +} +function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) { + if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) { + return viewCache; + } + // Only filter server node if it is currently filtered + const filterServerNode = viewCache.serverCache.isFiltered(); + // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update + // now that it won't be shadowed. + const serverCache = viewCache.serverCache; + if (affectedTree.value != null) { + // This is an overwrite. + if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) || + serverCache.isCompleteForPath(ackPath)) { + return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator); + } + else if (pathIsEmpty(ackPath)) { + // This is a goofy edge case where we are acking data at this location but don't have full data. We + // should just re-apply whatever we have in our cache as a merge. + let changedChildren = new ImmutableTree(null); + serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => { + changedChildren = changedChildren.set(new Path(name), node); + }); + return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator); + } + else { + return viewCache; + } + } + else { + // This is a merge. + let changedChildren = new ImmutableTree(null); + affectedTree.foreach((mergePath, value) => { + const serverCachePath = pathChild(ackPath, mergePath); + if (serverCache.isCompleteForPath(serverCachePath)) { + changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath)); + } + }); + return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator); + } +} +function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) { + const oldServerNode = viewCache.serverCache; + const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered()); + return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator); +} +function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) { + let complete; + if (writeTreeRefShadowingWrite(writesCache, path) != null) { + return viewCache; + } + else { + const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache); + const oldEventCache = viewCache.eventCache.getNode(); + let newEventCache; + if (pathIsEmpty(path) || pathGetFront(path) === '.priority') { + let newNode; + if (viewCache.serverCache.isFullyInitialized()) { + newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache)); + } + else { + const serverChildren = viewCache.serverCache.getNode(); + util.assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node'); + newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren); + } + newNode = newNode; + newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator); + } + else { + const childKey = pathGetFront(path); + let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache); + if (newChild == null && + viewCache.serverCache.isCompleteForChild(childKey)) { + newChild = oldEventCache.getImmediateChild(childKey); + } + if (newChild != null) { + newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator); + } + else if (viewCache.eventCache.getNode().hasChild(childKey)) { + // No complete child available, delete the existing one, if any + newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator); + } + else { + newEventCache = oldEventCache; + } + if (newEventCache.isEmpty() && + viewCache.serverCache.isFullyInitialized()) { + // We might have reverted all child writes. Maybe the old event was a leaf node + complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache)); + if (complete.isLeafNode()) { + newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator); + } + } + } + complete = + viewCache.serverCache.isFullyInitialized() || + writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null; + return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes()); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A view represents a specific location and query that has 1 or more event registrations. + * + * It does several things: + * - Maintains the list of event registrations for this location/query. + * - Maintains a cache of the data visible for this location/query. + * - Applies new operations (via applyOperation), updates the cache, and based on the event + * registrations returns the set of events to be raised. + */ +class View { + constructor(query_, initialViewCache) { + this.query_ = query_; + this.eventRegistrations_ = []; + const params = this.query_._queryParams; + const indexFilter = new IndexedFilter(params.getIndex()); + const filter = queryParamsGetNodeFilter(params); + this.processor_ = newViewProcessor(filter); + const initialServerCache = initialViewCache.serverCache; + const initialEventCache = initialViewCache.eventCache; + // Don't filter server node with other filter than index, wait for tagged listen + const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null); + const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null); + const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes()); + const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes()); + this.viewCache_ = newViewCache(newEventCache, newServerCache); + this.eventGenerator_ = new EventGenerator(this.query_); + } + get query() { + return this.query_; + } +} +function viewGetServerCache(view) { + return view.viewCache_.serverCache.getNode(); +} +function viewGetCompleteNode(view) { + return viewCacheGetCompleteEventSnap(view.viewCache_); +} +function viewGetCompleteServerCache(view, path) { + const cache = viewCacheGetCompleteServerSnap(view.viewCache_); + if (cache) { + // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and + // we need to see if it contains the child we're interested in. + if (view.query._queryParams.loadsAllData() || + (!pathIsEmpty(path) && + !cache.getImmediateChild(pathGetFront(path)).isEmpty())) { + return cache.getChild(path); + } + } + return null; +} +function viewIsEmpty(view) { + return view.eventRegistrations_.length === 0; +} +function viewAddEventRegistration(view, eventRegistration) { + view.eventRegistrations_.push(eventRegistration); +} +/** + * @param eventRegistration - If null, remove all callbacks. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @returns Cancel events, if cancelError was provided. + */ +function viewRemoveEventRegistration(view, eventRegistration, cancelError) { + const cancelEvents = []; + if (cancelError) { + util.assert(eventRegistration == null, 'A cancel should cancel all event registrations.'); + const path = view.query._path; + view.eventRegistrations_.forEach(registration => { + const maybeEvent = registration.createCancelEvent(cancelError, path); + if (maybeEvent) { + cancelEvents.push(maybeEvent); + } + }); + } + if (eventRegistration) { + let remaining = []; + for (let i = 0; i < view.eventRegistrations_.length; ++i) { + const existing = view.eventRegistrations_[i]; + if (!existing.matches(eventRegistration)) { + remaining.push(existing); + } + else if (eventRegistration.hasAnyCallback()) { + // We're removing just this one + remaining = remaining.concat(view.eventRegistrations_.slice(i + 1)); + break; + } + } + view.eventRegistrations_ = remaining; + } + else { + view.eventRegistrations_ = []; + } + return cancelEvents; +} +/** + * Applies the given Operation, updates our cache, and returns the appropriate events. + */ +function viewApplyOperation(view, operation, writesCache, completeServerCache) { + if (operation.type === OperationType.MERGE && + operation.source.queryId !== null) { + util.assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges'); + util.assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache'); + } + const oldViewCache = view.viewCache_; + const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache); + viewProcessorAssertIndexed(view.processor_, result.viewCache); + util.assert(result.viewCache.serverCache.isFullyInitialized() || + !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back'); + view.viewCache_ = result.viewCache; + return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null); +} +function viewGetInitialEvents(view, registration) { + const eventSnap = view.viewCache_.eventCache; + const initialChanges = []; + if (!eventSnap.getNode().isLeafNode()) { + const eventNode = eventSnap.getNode(); + eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => { + initialChanges.push(changeChildAdded(key, childNode)); + }); + } + if (eventSnap.isFullyInitialized()) { + initialChanges.push(changeValue(eventSnap.getNode())); + } + return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration); +} +function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) { + const registrations = eventRegistration + ? [eventRegistration] + : view.eventRegistrations_; + return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let referenceConstructor$1; +/** + * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to + * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes + * and user writes (set, transaction, update). + * + * It's responsible for: + * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed). + * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite, + * applyUserOverwrite, etc.) + */ +class SyncPoint { + constructor() { + /** + * The Views being tracked at this location in the tree, stored as a map where the key is a + * queryId and the value is the View for that query. + * + * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case). + */ + this.views = new Map(); + } +} +function syncPointSetReferenceConstructor(val) { + util.assert(!referenceConstructor$1, '__referenceConstructor has already been defined'); + referenceConstructor$1 = val; +} +function syncPointGetReferenceConstructor() { + util.assert(referenceConstructor$1, 'Reference.ts has not been loaded'); + return referenceConstructor$1; +} +function syncPointIsEmpty(syncPoint) { + return syncPoint.views.size === 0; +} +function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) { + const queryId = operation.source.queryId; + if (queryId !== null) { + const view = syncPoint.views.get(queryId); + util.assert(view != null, 'SyncTree gave us an op for an invalid query.'); + return viewApplyOperation(view, operation, writesCache, optCompleteServerCache); + } + else { + let events = []; + for (const view of syncPoint.views.values()) { + events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache)); + } + return events; + } +} +/** + * Get a view for the specified query. + * + * @param query - The query to return a view for + * @param writesCache + * @param serverCache + * @param serverCacheComplete + * @returns Events to raise. + */ +function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) { + const queryId = query._queryIdentifier; + const view = syncPoint.views.get(queryId); + if (!view) { + // TODO: make writesCache take flag for complete server node + let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null); + let eventCacheComplete = false; + if (eventCache) { + eventCacheComplete = true; + } + else if (serverCache instanceof ChildrenNode) { + eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache); + eventCacheComplete = false; + } + else { + eventCache = ChildrenNode.EMPTY_NODE; + eventCacheComplete = false; + } + const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false)); + return new View(query, viewCache); + } + return view; +} +/** + * Add an event callback for the specified query. + * + * @param query + * @param eventRegistration + * @param writesCache + * @param serverCache - Complete server cache, if we have it. + * @param serverCacheComplete + * @returns Events to raise. + */ +function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) { + const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete); + if (!syncPoint.views.has(query._queryIdentifier)) { + syncPoint.views.set(query._queryIdentifier, view); + } + // This is guaranteed to exist now, we just created anything that was missing + viewAddEventRegistration(view, eventRegistration); + return viewGetInitialEvents(view, eventRegistration); +} +/** + * Remove event callback(s). Return cancelEvents if a cancelError is specified. + * + * If query is the default query, we'll check all views for the specified eventRegistration. + * If eventRegistration is null, we'll remove all callbacks for the specified view(s). + * + * @param eventRegistration - If null, remove all callbacks. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @returns removed queries and any cancel events + */ +function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) { + const queryId = query._queryIdentifier; + const removed = []; + let cancelEvents = []; + const hadCompleteView = syncPointHasCompleteView(syncPoint); + if (queryId === 'default') { + // When you do ref.off(...), we search all views for the registration to remove. + for (const [viewQueryId, view] of syncPoint.views.entries()) { + cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError)); + if (viewIsEmpty(view)) { + syncPoint.views.delete(viewQueryId); + // We'll deal with complete views later. + if (!view.query._queryParams.loadsAllData()) { + removed.push(view.query); + } + } + } + } + else { + // remove the callback from the specific view. + const view = syncPoint.views.get(queryId); + if (view) { + cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError)); + if (viewIsEmpty(view)) { + syncPoint.views.delete(queryId); + // We'll deal with complete views later. + if (!view.query._queryParams.loadsAllData()) { + removed.push(view.query); + } + } + } + } + if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) { + // We removed our last complete view. + removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path)); + } + return { removed, events: cancelEvents }; +} +function syncPointGetQueryViews(syncPoint) { + const result = []; + for (const view of syncPoint.views.values()) { + if (!view.query._queryParams.loadsAllData()) { + result.push(view); + } + } + return result; +} +/** + * @param path - The path to the desired complete snapshot + * @returns A complete cache, if it exists + */ +function syncPointGetCompleteServerCache(syncPoint, path) { + let serverCache = null; + for (const view of syncPoint.views.values()) { + serverCache = serverCache || viewGetCompleteServerCache(view, path); + } + return serverCache; +} +function syncPointViewForQuery(syncPoint, query) { + const params = query._queryParams; + if (params.loadsAllData()) { + return syncPointGetCompleteView(syncPoint); + } + else { + const queryId = query._queryIdentifier; + return syncPoint.views.get(queryId); + } +} +function syncPointViewExistsForQuery(syncPoint, query) { + return syncPointViewForQuery(syncPoint, query) != null; +} +function syncPointHasCompleteView(syncPoint) { + return syncPointGetCompleteView(syncPoint) != null; +} +function syncPointGetCompleteView(syncPoint) { + for (const view of syncPoint.views.values()) { + if (view.query._queryParams.loadsAllData()) { + return view; + } + } + return null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let referenceConstructor; +function syncTreeSetReferenceConstructor(val) { + util.assert(!referenceConstructor, '__referenceConstructor has already been defined'); + referenceConstructor = val; +} +function syncTreeGetReferenceConstructor() { + util.assert(referenceConstructor, 'Reference.ts has not been loaded'); + return referenceConstructor; +} +/** + * Static tracker for next query tag. + */ +let syncTreeNextQueryTag_ = 1; +/** + * SyncTree is the central class for managing event callback registration, data caching, views + * (query processing), and event generation. There are typically two SyncTree instances for + * each Repo, one for the normal Firebase data, and one for the .info data. + * + * It has a number of responsibilities, including: + * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()). + * - Applying and caching data changes for user set(), transaction(), and update() calls + * (applyUserOverwrite(), applyUserMerge()). + * - Applying and caching data changes for server data changes (applyServerOverwrite(), + * applyServerMerge()). + * - Generating user-facing events for server and user changes (all of the apply* methods + * return the set of events that need to be raised as a result). + * - Maintaining the appropriate set of server listens to ensure we are always subscribed + * to the correct set of paths and queries to satisfy the current set of user event + * callbacks (listens are started/stopped using the provided listenProvider). + * + * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual + * events are returned to the caller rather than raised synchronously. + * + */ +class SyncTree { + /** + * @param listenProvider_ - Used by SyncTree to start / stop listening + * to server data. + */ + constructor(listenProvider_) { + this.listenProvider_ = listenProvider_; + /** + * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views. + */ + this.syncPointTree_ = new ImmutableTree(null); + /** + * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.). + */ + this.pendingWriteTree_ = newWriteTree(); + this.tagToQueryMap = new Map(); + this.queryToTagMap = new Map(); + } +} +/** + * Apply the data changes for a user-generated set() or transaction() call. + * + * @returns Events to raise. + */ +function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) { + // Record pending write. + writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible); + if (!visible) { + return []; + } + else { + return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData)); + } +} +/** + * Apply the data from a user-generated update() call + * + * @returns Events to raise. + */ +function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) { + // Record pending merge. + writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId); + const changeTree = ImmutableTree.fromObject(changedChildren); + return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree)); +} +/** + * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge(). + * + * @param revert - True if the given write failed and needs to be reverted + * @returns Events to raise. + */ +function syncTreeAckUserWrite(syncTree, writeId, revert = false) { + const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId); + const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId); + if (!needToReevaluate) { + return []; + } + else { + let affectedTree = new ImmutableTree(null); + if (write.snap != null) { + // overwrite + affectedTree = affectedTree.set(newEmptyPath(), true); + } + else { + each(write.children, (pathString) => { + affectedTree = affectedTree.set(new Path(pathString), true); + }); + } + return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert)); + } +} +/** + * Apply new server data for the specified path.. + * + * @returns Events to raise. + */ +function syncTreeApplyServerOverwrite(syncTree, path, newData) { + return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData)); +} +/** + * Apply new server data to be merged in at the specified path. + * + * @returns Events to raise. + */ +function syncTreeApplyServerMerge(syncTree, path, changedChildren) { + const changeTree = ImmutableTree.fromObject(changedChildren); + return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree)); +} +/** + * Apply a listen complete for a query + * + * @returns Events to raise. + */ +function syncTreeApplyListenComplete(syncTree, path) { + return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path)); +} +/** + * Apply a listen complete for a tagged query + * + * @returns Events to raise. + */ +function syncTreeApplyTaggedListenComplete(syncTree, path, tag) { + const queryKey = syncTreeQueryKeyForTag_(syncTree, tag); + if (queryKey) { + const r = syncTreeParseQueryKey_(queryKey); + const queryPath = r.path, queryId = r.queryId; + const relativePath = newRelativePath(queryPath, path); + const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath); + return syncTreeApplyTaggedOperation_(syncTree, queryPath, op); + } + else { + // We've already removed the query. No big deal, ignore the update + return []; + } +} +/** + * Remove event callback(s). + * + * If query is the default query, we'll check all queries for the specified eventRegistration. + * If eventRegistration is null, we'll remove all callbacks for the specified query/queries. + * + * @param eventRegistration - If null, all callbacks are removed. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no + * deduping needs to take place. This flag allows toggling of that behavior + * @returns Cancel events, if cancelError was provided. + */ +function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) { + // Find the syncPoint first. Then deal with whether or not it has matching listeners + const path = query._path; + const maybeSyncPoint = syncTree.syncPointTree_.get(path); + let cancelEvents = []; + // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without + // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and + // not loadsAllData(). + if (maybeSyncPoint && + (query._queryIdentifier === 'default' || + syncPointViewExistsForQuery(maybeSyncPoint, query))) { + const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError); + if (syncPointIsEmpty(maybeSyncPoint)) { + syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path); + } + const removed = removedAndEvents.removed; + cancelEvents = removedAndEvents.events; + if (!skipListenerDedup) { + /** + * We may have just removed one of many listeners and can short-circuit this whole process + * We may also not have removed a default listener, in which case all of the descendant listeners should already be + * properly set up. + */ + // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of + // queryId === 'default' + const removingDefault = -1 !== + removed.findIndex(query => { + return query._queryParams.loadsAllData(); + }); + const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint)); + if (removingDefault && !covered) { + const subtree = syncTree.syncPointTree_.subtree(path); + // There are potentially child listeners. Determine what if any listens we need to send before executing the + // removal + if (!subtree.isEmpty()) { + // We need to fold over our subtree and collect the listeners to send + const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree); + // Ok, we've collected all the listens we need. Set them up. + for (let i = 0; i < newViews.length; ++i) { + const view = newViews[i], newQuery = view.query; + const listener = syncTreeCreateListenerForView_(syncTree, view); + syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete); + } + } + // Otherwise there's nothing below us, so nothing we need to start listening on + } + // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query + // The above block has us covered in terms of making sure we're set up on listens lower in the tree. + // Also, note that if we have a cancelError, it's already been removed at the provider level. + if (!covered && removed.length > 0 && !cancelError) { + // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one + // default. Otherwise, we need to iterate through and cancel each individual query + if (removingDefault) { + // We don't tag default listeners + const defaultTag = null; + syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag); + } + else { + removed.forEach((queryToRemove) => { + const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove)); + syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove); + }); + } + } + } + // Now, clear all of the tags we're tracking for the removed listens + syncTreeRemoveTags_(syncTree, removed); + } + return cancelEvents; +} +/** + * Apply new server data for the specified tagged query. + * + * @returns Events to raise. + */ +function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) { + const queryKey = syncTreeQueryKeyForTag_(syncTree, tag); + if (queryKey != null) { + const r = syncTreeParseQueryKey_(queryKey); + const queryPath = r.path, queryId = r.queryId; + const relativePath = newRelativePath(queryPath, path); + const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap); + return syncTreeApplyTaggedOperation_(syncTree, queryPath, op); + } + else { + // Query must have been removed already + return []; + } +} +/** + * Apply server data to be merged in for the specified tagged query. + * + * @returns Events to raise. + */ +function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) { + const queryKey = syncTreeQueryKeyForTag_(syncTree, tag); + if (queryKey) { + const r = syncTreeParseQueryKey_(queryKey); + const queryPath = r.path, queryId = r.queryId; + const relativePath = newRelativePath(queryPath, path); + const changeTree = ImmutableTree.fromObject(changedChildren); + const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree); + return syncTreeApplyTaggedOperation_(syncTree, queryPath, op); + } + else { + // We've already removed the query. No big deal, ignore the update + return []; + } +} +/** + * Add an event callback for the specified query. + * + * @returns Events to raise. + */ +function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) { + const path = query._path; + let serverCache = null; + let foundAncestorDefaultView = false; + // Any covering writes will necessarily be at the root, so really all we need to find is the server cache. + // Consider optimizing this once there's a better understanding of what actual behavior will be. + syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => { + const relativePath = newRelativePath(pathToSyncPoint, path); + serverCache = + serverCache || syncPointGetCompleteServerCache(sp, relativePath); + foundAncestorDefaultView = + foundAncestorDefaultView || syncPointHasCompleteView(sp); + }); + let syncPoint = syncTree.syncPointTree_.get(path); + if (!syncPoint) { + syncPoint = new SyncPoint(); + syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint); + } + else { + foundAncestorDefaultView = + foundAncestorDefaultView || syncPointHasCompleteView(syncPoint); + serverCache = + serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + let serverCacheComplete; + if (serverCache != null) { + serverCacheComplete = true; + } + else { + serverCacheComplete = false; + serverCache = ChildrenNode.EMPTY_NODE; + const subtree = syncTree.syncPointTree_.subtree(path); + subtree.foreachChild((childName, childSyncPoint) => { + const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath()); + if (completeCache) { + serverCache = serverCache.updateImmediateChild(childName, completeCache); + } + }); + } + const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query); + if (!viewAlreadyExists && !query._queryParams.loadsAllData()) { + // We need to track a tag for this query + const queryKey = syncTreeMakeQueryKey_(query); + util.assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag'); + const tag = syncTreeGetNextQueryTag_(); + syncTree.queryToTagMap.set(queryKey, tag); + syncTree.tagToQueryMap.set(tag, queryKey); + } + const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path); + let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete); + if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) { + const view = syncPointViewForQuery(syncPoint, query); + events = events.concat(syncTreeSetupListener_(syncTree, query, view)); + } + return events; +} +/** + * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a + * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always + * have a listener above, and atomic operations would correctly show a jitter of -> + * as the write is applied locally and then acknowledged at the server. + * + * Note: this method will *include* hidden writes from transaction with applyLocally set to false. + * + * @param path - The path to the data we want + * @param writeIdsToExclude - A specific set to be excluded + */ +function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) { + const includeHiddenSets = true; + const writeTree = syncTree.pendingWriteTree_; + const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => { + const relativePath = newRelativePath(pathSoFar, path); + const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath); + if (serverCache) { + return serverCache; + } + }); + return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets); +} +function syncTreeGetServerValue(syncTree, query) { + const path = query._path; + let serverCache = null; + // Any covering writes will necessarily be at the root, so really all we need to find is the server cache. + // Consider optimizing this once there's a better understanding of what actual behavior will be. + syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => { + const relativePath = newRelativePath(pathToSyncPoint, path); + serverCache = + serverCache || syncPointGetCompleteServerCache(sp, relativePath); + }); + let syncPoint = syncTree.syncPointTree_.get(path); + if (!syncPoint) { + syncPoint = new SyncPoint(); + syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint); + } + else { + serverCache = + serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + const serverCacheComplete = serverCache != null; + const serverCacheNode = serverCacheComplete + ? new CacheNode(serverCache, true, false) + : null; + const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path); + const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete); + return viewGetCompleteNode(view); +} +/** + * A helper method that visits all descendant and ancestor SyncPoints, applying the operation. + * + * NOTES: + * - Descendant SyncPoints will be visited first (since we raise events depth-first). + * + * - We call applyOperation() on each SyncPoint passing three things: + * 1. A version of the Operation that has been made relative to the SyncPoint location. + * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location. + * 3. A snapshot Node with cached server data, if we have it. + * + * - We concatenate all of the events returned by each SyncPoint and return the result. + */ +function syncTreeApplyOperationToSyncPoints_(syncTree, operation) { + return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_, + /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath())); +} +/** + * Recursive helper for applyOperationToSyncPoints_ + */ +function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) { + if (pathIsEmpty(operation.path)) { + return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache); + } + else { + const syncPoint = syncPointTree.get(newEmptyPath()); + // If we don't have cached server data, see if we can get it from this SyncPoint. + if (serverCache == null && syncPoint != null) { + serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + let events = []; + const childName = pathGetFront(operation.path); + const childOperation = operation.operationForChild(childName); + const childTree = syncPointTree.children.get(childName); + if (childTree && childOperation) { + const childServerCache = serverCache + ? serverCache.getImmediateChild(childName) + : null; + const childWritesCache = writeTreeRefChild(writesCache, childName); + events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache)); + } + if (syncPoint) { + events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)); + } + return events; + } +} +/** + * Recursive helper for applyOperationToSyncPoints_ + */ +function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) { + const syncPoint = syncPointTree.get(newEmptyPath()); + // If we don't have cached server data, see if we can get it from this SyncPoint. + if (serverCache == null && syncPoint != null) { + serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + let events = []; + syncPointTree.children.inorderTraversal((childName, childTree) => { + const childServerCache = serverCache + ? serverCache.getImmediateChild(childName) + : null; + const childWritesCache = writeTreeRefChild(writesCache, childName); + const childOperation = operation.operationForChild(childName); + if (childOperation) { + events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache)); + } + }); + if (syncPoint) { + events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)); + } + return events; +} +function syncTreeCreateListenerForView_(syncTree, view) { + const query = view.query; + const tag = syncTreeTagForQuery(syncTree, query); + return { + hashFn: () => { + const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE; + return cache.hash(); + }, + onComplete: (status) => { + if (status === 'ok') { + if (tag) { + return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag); + } + else { + return syncTreeApplyListenComplete(syncTree, query._path); + } + } + else { + // If a listen failed, kill all of the listeners here, not just the one that triggered the error. + // Note that this may need to be scoped to just this listener if we change permissions on filtered children + const error = errorForServerCode(status, query); + return syncTreeRemoveEventRegistration(syncTree, query, + /*eventRegistration*/ null, error); + } + } + }; +} +/** + * Return the tag associated with the given query. + */ +function syncTreeTagForQuery(syncTree, query) { + const queryKey = syncTreeMakeQueryKey_(query); + return syncTree.queryToTagMap.get(queryKey); +} +/** + * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_. + */ +function syncTreeMakeQueryKey_(query) { + return query._path.toString() + '$' + query._queryIdentifier; +} +/** + * Return the query associated with the given tag, if we have one + */ +function syncTreeQueryKeyForTag_(syncTree, tag) { + return syncTree.tagToQueryMap.get(tag); +} +/** + * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId. + */ +function syncTreeParseQueryKey_(queryKey) { + const splitIndex = queryKey.indexOf('$'); + util.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.'); + return { + queryId: queryKey.substr(splitIndex + 1), + path: new Path(queryKey.substr(0, splitIndex)) + }; +} +/** + * A helper method to apply tagged operations + */ +function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) { + const syncPoint = syncTree.syncPointTree_.get(queryPath); + util.assert(syncPoint, "Missing sync point for query tag that we're tracking"); + const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath); + return syncPointApplyOperation(syncPoint, operation, writesCache, null); +} +/** + * This collapses multiple unfiltered views into a single view, since we only need a single + * listener for them. + */ +function syncTreeCollectDistinctViewsForSubTree_(subtree) { + return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => { + if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) { + const completeView = syncPointGetCompleteView(maybeChildSyncPoint); + return [completeView]; + } + else { + // No complete view here, flatten any deeper listens into an array + let views = []; + if (maybeChildSyncPoint) { + views = syncPointGetQueryViews(maybeChildSyncPoint); + } + each(childMap, (_key, childViews) => { + views = views.concat(childViews); + }); + return views; + } + }); +} +/** + * Normalizes a query to a query we send the server for listening + * + * @returns The normalized query + */ +function syncTreeQueryForListening_(query) { + if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) { + // We treat queries that load all data as default queries + // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits + // from Query + return new (syncTreeGetReferenceConstructor())(query._repo, query._path); + } + else { + return query; + } +} +function syncTreeRemoveTags_(syncTree, queries) { + for (let j = 0; j < queries.length; ++j) { + const removedQuery = queries[j]; + if (!removedQuery._queryParams.loadsAllData()) { + // We should have a tag for this + const removedQueryKey = syncTreeMakeQueryKey_(removedQuery); + const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey); + syncTree.queryToTagMap.delete(removedQueryKey); + syncTree.tagToQueryMap.delete(removedQueryTag); + } + } +} +/** + * Static accessor for query tags. + */ +function syncTreeGetNextQueryTag_() { + return syncTreeNextQueryTag_++; +} +/** + * For a given new listen, manage the de-duplication of outstanding subscriptions. + * + * @returns This method can return events to support synchronous data sources + */ +function syncTreeSetupListener_(syncTree, query, view) { + const path = query._path; + const tag = syncTreeTagForQuery(syncTree, query); + const listener = syncTreeCreateListenerForView_(syncTree, view); + const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete); + const subtree = syncTree.syncPointTree_.subtree(path); + // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we + // may need to shadow other listens as well. + if (tag) { + util.assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed"); + } + else { + // Shadow everything at or below this location, this is a default listener. + const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => { + if (!pathIsEmpty(relativePath) && + maybeChildSyncPoint && + syncPointHasCompleteView(maybeChildSyncPoint)) { + return [syncPointGetCompleteView(maybeChildSyncPoint).query]; + } + else { + // No default listener here, flatten any deeper queries into an array + let queries = []; + if (maybeChildSyncPoint) { + queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query)); + } + each(childMap, (_key, childQueries) => { + queries = queries.concat(childQueries); + }); + return queries; + } + }); + for (let i = 0; i < queriesToStop.length; ++i) { + const queryToStop = queriesToStop[i]; + syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop)); + } + } + return events; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ExistingValueProvider { + constructor(node_) { + this.node_ = node_; + } + getImmediateChild(childName) { + const child = this.node_.getImmediateChild(childName); + return new ExistingValueProvider(child); + } + node() { + return this.node_; + } +} +class DeferredValueProvider { + constructor(syncTree, path) { + this.syncTree_ = syncTree; + this.path_ = path; + } + getImmediateChild(childName) { + const childPath = pathChild(this.path_, childName); + return new DeferredValueProvider(this.syncTree_, childPath); + } + node() { + return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_); + } +} +/** + * Generate placeholders for deferred values. + */ +const generateWithValues = function (values) { + values = values || {}; + values['timestamp'] = values['timestamp'] || new Date().getTime(); + return values; +}; +/** + * Value to use when firing local events. When writing server values, fire + * local events with an approximate value, otherwise return value as-is. + */ +const resolveDeferredLeafValue = function (value, existingVal, serverValues) { + if (!value || typeof value !== 'object') { + return value; + } + util.assert('.sv' in value, 'Unexpected leaf node or priority contents'); + if (typeof value['.sv'] === 'string') { + return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues); + } + else if (typeof value['.sv'] === 'object') { + return resolveComplexDeferredValue(value['.sv'], existingVal); + } + else { + util.assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2)); + } +}; +const resolveScalarDeferredValue = function (op, existing, serverValues) { + switch (op) { + case 'timestamp': + return serverValues['timestamp']; + default: + util.assert(false, 'Unexpected server value: ' + op); + } +}; +const resolveComplexDeferredValue = function (op, existing, unused) { + if (!op.hasOwnProperty('increment')) { + util.assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2)); + } + const delta = op['increment']; + if (typeof delta !== 'number') { + util.assert(false, 'Unexpected increment value: ' + delta); + } + const existingNode = existing.node(); + util.assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls'); + // Incrementing a non-number sets the value to the incremented amount + if (!existingNode.isLeafNode()) { + return delta; + } + const leaf = existingNode; + const existingVal = leaf.getValue(); + if (typeof existingVal !== 'number') { + return delta; + } + // No need to do over/underflow arithmetic here because JS only handles floats under the covers + return existingVal + delta; +}; +/** + * Recursively replace all deferred values and priorities in the tree with the + * specified generated replacement values. + * @param path - path to which write is relative + * @param node - new data written at path + * @param syncTree - current data + */ +const resolveDeferredValueTree = function (path, node, syncTree, serverValues) { + return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues); +}; +/** + * Recursively replace all deferred values and priorities in the node with the + * specified generated replacement values. If there are no server values in the node, + * it'll be returned as-is. + */ +const resolveDeferredValueSnapshot = function (node, existing, serverValues) { + return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues); +}; +function resolveDeferredValue(node, existingVal, serverValues) { + const rawPri = node.getPriority().val(); + const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues); + let newNode; + if (node.isLeafNode()) { + const leafNode = node; + const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues); + if (value !== leafNode.getValue() || + priority !== leafNode.getPriority().val()) { + return new LeafNode(value, nodeFromJSON(priority)); + } + else { + return node; + } + } + else { + const childrenNode = node; + newNode = childrenNode; + if (priority !== childrenNode.getPriority().val()) { + newNode = newNode.updatePriority(new LeafNode(priority)); + } + childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => { + const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues); + if (newChildNode !== childNode) { + newNode = newNode.updateImmediateChild(childName, newChildNode); + } + }); + return newNode; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A light-weight tree, traversable by path. Nodes can have both values and children. + * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty + * children. + */ +class Tree { + /** + * @param name - Optional name of the node. + * @param parent - Optional parent node. + * @param node - Optional node to wrap. + */ + constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) { + this.name = name; + this.parent = parent; + this.node = node; + } +} +/** + * Returns a sub-Tree for the given path. + * + * @param pathObj - Path to look up. + * @returns Tree for path. + */ +function treeSubTree(tree, pathObj) { + // TODO: Require pathObj to be Path? + let path = pathObj instanceof Path ? pathObj : new Path(pathObj); + let child = tree, next = pathGetFront(path); + while (next !== null) { + const childNode = util.safeGet(child.node.children, next) || { + children: {}, + childCount: 0 + }; + child = new Tree(next, child, childNode); + path = pathPopFront(path); + next = pathGetFront(path); + } + return child; +} +/** + * Returns the data associated with this tree node. + * + * @returns The data or null if no data exists. + */ +function treeGetValue(tree) { + return tree.node.value; +} +/** + * Sets data to this tree node. + * + * @param value - Value to set. + */ +function treeSetValue(tree, value) { + tree.node.value = value; + treeUpdateParents(tree); +} +/** + * @returns Whether the tree has any children. + */ +function treeHasChildren(tree) { + return tree.node.childCount > 0; +} +/** + * @returns Whether the tree is empty (no value or children). + */ +function treeIsEmpty(tree) { + return treeGetValue(tree) === undefined && !treeHasChildren(tree); +} +/** + * Calls action for each child of this tree node. + * + * @param action - Action to be called for each child. + */ +function treeForEachChild(tree, action) { + each(tree.node.children, (child, childTree) => { + action(new Tree(child, tree, childTree)); + }); +} +/** + * Does a depth-first traversal of this node's descendants, calling action for each one. + * + * @param action - Action to be called for each child. + * @param includeSelf - Whether to call action on this node as well. Defaults to + * false. + * @param childrenFirst - Whether to call action on children before calling it on + * parent. + */ +function treeForEachDescendant(tree, action, includeSelf, childrenFirst) { + if (includeSelf && !childrenFirst) { + action(tree); + } + treeForEachChild(tree, child => { + treeForEachDescendant(child, action, true, childrenFirst); + }); + if (includeSelf && childrenFirst) { + action(tree); + } +} +/** + * Calls action on each ancestor node. + * + * @param action - Action to be called on each parent; return + * true to abort. + * @param includeSelf - Whether to call action on this node as well. + * @returns true if the action callback returned true. + */ +function treeForEachAncestor(tree, action, includeSelf) { + let node = includeSelf ? tree : tree.parent; + while (node !== null) { + if (action(node)) { + return true; + } + node = node.parent; + } + return false; +} +/** + * @returns The path of this tree node, as a Path. + */ +function treeGetPath(tree) { + return new Path(tree.parent === null + ? tree.name + : treeGetPath(tree.parent) + '/' + tree.name); +} +/** + * Adds or removes this child from its parent based on whether it's empty or not. + */ +function treeUpdateParents(tree) { + if (tree.parent !== null) { + treeUpdateChild(tree.parent, tree.name, tree); + } +} +/** + * Adds or removes the passed child to this tree node, depending on whether it's empty. + * + * @param childName - The name of the child to update. + * @param child - The child to update. + */ +function treeUpdateChild(tree, childName, child) { + const childEmpty = treeIsEmpty(child); + const childExists = util.contains(tree.node.children, childName); + if (childEmpty && childExists) { + delete tree.node.children[childName]; + tree.node.childCount--; + treeUpdateParents(tree); + } + else if (!childEmpty && !childExists) { + tree.node.children[childName] = child.node; + tree.node.childCount++; + treeUpdateParents(tree); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * True for invalid Firebase keys + */ +const INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/; +/** + * True for invalid Firebase paths. + * Allows '/' in paths. + */ +const INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/; +/** + * Maximum number of characters to allow in leaf value + */ +const MAX_LEAF_SIZE_ = 10 * 1024 * 1024; +const isValidKey = function (key) { + return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key)); +}; +const isValidPathString = function (pathString) { + return (typeof pathString === 'string' && + pathString.length !== 0 && + !INVALID_PATH_REGEX_.test(pathString)); +}; +const isValidRootPathString = function (pathString) { + if (pathString) { + // Allow '/.info/' at the beginning. + pathString = pathString.replace(/^\/*\.info(\/|$)/, '/'); + } + return isValidPathString(pathString); +}; +const isValidPriority = function (priority) { + return (priority === null || + typeof priority === 'string' || + (typeof priority === 'number' && !isInvalidJSONNumber(priority)) || + (priority && + typeof priority === 'object' && + // eslint-disable-next-line @typescript-eslint/no-explicit-any + util.contains(priority, '.sv'))); +}; +/** + * Pre-validate a datum passed as an argument to Firebase function. + */ +const validateFirebaseDataArg = function (fnName, value, path, optional) { + if (optional && value === undefined) { + return; + } + validateFirebaseData(util.errorPrefix(fnName, 'value'), value, path); +}; +/** + * Validate a data object client-side before sending to server. + */ +const validateFirebaseData = function (errorPrefix, data, path_) { + const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_; + if (data === undefined) { + throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path)); + } + if (typeof data === 'function') { + throw new Error(errorPrefix + + 'contains a function ' + + validationPathToErrorString(path) + + ' with contents = ' + + data.toString()); + } + if (isInvalidJSONNumber(data)) { + throw new Error(errorPrefix + + 'contains ' + + data.toString() + + ' ' + + validationPathToErrorString(path)); + } + // Check max leaf size, but try to avoid the utf8 conversion if we can. + if (typeof data === 'string' && + data.length > MAX_LEAF_SIZE_ / 3 && + util.stringLength(data) > MAX_LEAF_SIZE_) { + throw new Error(errorPrefix + + 'contains a string greater than ' + + MAX_LEAF_SIZE_ + + ' utf8 bytes ' + + validationPathToErrorString(path) + + " ('" + + data.substring(0, 50) + + "...')"); + } + // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON + // to save extra walking of large objects. + if (data && typeof data === 'object') { + let hasDotValue = false; + let hasActualChild = false; + each(data, (key, value) => { + if (key === '.value') { + hasDotValue = true; + } + else if (key !== '.priority' && key !== '.sv') { + hasActualChild = true; + if (!isValidKey(key)) { + throw new Error(errorPrefix + + ' contains an invalid key (' + + key + + ') ' + + validationPathToErrorString(path) + + '. Keys must be non-empty strings ' + + 'and can\'t contain ".", "#", "$", "/", "[", or "]"'); + } + } + validationPathPush(path, key); + validateFirebaseData(errorPrefix, value, path); + validationPathPop(path); + }); + if (hasDotValue && hasActualChild) { + throw new Error(errorPrefix + + ' contains ".value" child ' + + validationPathToErrorString(path) + + ' in addition to actual children.'); + } + } +}; +/** + * Pre-validate paths passed in the firebase function. + */ +const validateFirebaseMergePaths = function (errorPrefix, mergePaths) { + let i, curPath; + for (i = 0; i < mergePaths.length; i++) { + curPath = mergePaths[i]; + const keys = pathSlice(curPath); + for (let j = 0; j < keys.length; j++) { + if (keys[j] === '.priority' && j === keys.length - 1) ; + else if (!isValidKey(keys[j])) { + throw new Error(errorPrefix + + 'contains an invalid key (' + + keys[j] + + ') in path ' + + curPath.toString() + + '. Keys must be non-empty strings ' + + 'and can\'t contain ".", "#", "$", "/", "[", or "]"'); + } + } + } + // Check that update keys are not descendants of each other. + // We rely on the property that sorting guarantees that ancestors come + // right before descendants. + mergePaths.sort(pathCompare); + let prevPath = null; + for (i = 0; i < mergePaths.length; i++) { + curPath = mergePaths[i]; + if (prevPath !== null && pathContains(prevPath, curPath)) { + throw new Error(errorPrefix + + 'contains a path ' + + prevPath.toString() + + ' that is ancestor of another path ' + + curPath.toString()); + } + prevPath = curPath; + } +}; +/** + * pre-validate an object passed as an argument to firebase function ( + * must be an object - e.g. for firebase.update()). + */ +const validateFirebaseMergeDataArg = function (fnName, data, path, optional) { + if (optional && data === undefined) { + return; + } + const errorPrefix = util.errorPrefix(fnName, 'values'); + if (!(data && typeof data === 'object') || Array.isArray(data)) { + throw new Error(errorPrefix + ' must be an object containing the children to replace.'); + } + const mergePaths = []; + each(data, (key, value) => { + const curPath = new Path(key); + validateFirebaseData(errorPrefix, value, pathChild(path, curPath)); + if (pathGetBack(curPath) === '.priority') { + if (!isValidPriority(value)) { + throw new Error(errorPrefix + + "contains an invalid value for '" + + curPath.toString() + + "', which must be a valid " + + 'Firebase priority (a string, finite number, server value, or null).'); + } + } + mergePaths.push(curPath); + }); + validateFirebaseMergePaths(errorPrefix, mergePaths); +}; +const validatePriority = function (fnName, priority, optional) { + if (optional && priority === undefined) { + return; + } + if (isInvalidJSONNumber(priority)) { + throw new Error(util.errorPrefix(fnName, 'priority') + + 'is ' + + priority.toString() + + ', but must be a valid Firebase priority (a string, finite number, ' + + 'server value, or null).'); + } + // Special case to allow importing data with a .sv. + if (!isValidPriority(priority)) { + throw new Error(util.errorPrefix(fnName, 'priority') + + 'must be a valid Firebase priority ' + + '(a string, finite number, server value, or null).'); + } +}; +const validateKey = function (fnName, argumentName, key, optional) { + if (optional && key === undefined) { + return; + } + if (!isValidKey(key)) { + throw new Error(util.errorPrefix(fnName, argumentName) + + 'was an invalid key = "' + + key + + '". Firebase keys must be non-empty strings and ' + + 'can\'t contain ".", "#", "$", "/", "[", or "]").'); + } +}; +/** + * @internal + */ +const validatePathString = function (fnName, argumentName, pathString, optional) { + if (optional && pathString === undefined) { + return; + } + if (!isValidPathString(pathString)) { + throw new Error(util.errorPrefix(fnName, argumentName) + + 'was an invalid path = "' + + pathString + + '". Paths must be non-empty strings and ' + + 'can\'t contain ".", "#", "$", "[", or "]"'); + } +}; +const validateRootPathString = function (fnName, argumentName, pathString, optional) { + if (pathString) { + // Allow '/.info/' at the beginning. + pathString = pathString.replace(/^\/*\.info(\/|$)/, '/'); + } + validatePathString(fnName, argumentName, pathString, optional); +}; +/** + * @internal + */ +const validateWritablePath = function (fnName, path) { + if (pathGetFront(path) === '.info') { + throw new Error(fnName + " failed = Can't modify data under /.info/"); + } +}; +const validateUrl = function (fnName, parsedUrl) { + // TODO = Validate server better. + const pathString = parsedUrl.path.toString(); + if (!(typeof parsedUrl.repoInfo.host === 'string') || + parsedUrl.repoInfo.host.length === 0 || + (!isValidKey(parsedUrl.repoInfo.namespace) && + parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') || + (pathString.length !== 0 && !isValidRootPathString(pathString))) { + throw new Error(util.errorPrefix(fnName, 'url') + + 'must be a valid firebase URL and ' + + 'the path can\'t contain ".", "#", "$", "[", or "]".'); + } +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The event queue serves a few purposes: + * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more + * events being queued. + * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events, + * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call + * left off, ensuring that the events are still raised synchronously and in order. + * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued + * events are raised synchronously. + * + * NOTE: This can all go away if/when we move to async events. + * + */ +class EventQueue { + constructor() { + this.eventLists_ = []; + /** + * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes. + */ + this.recursionDepth_ = 0; + } +} +/** + * @param eventDataList - The new events to queue. + */ +function eventQueueQueueEvents(eventQueue, eventDataList) { + // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly. + let currList = null; + for (let i = 0; i < eventDataList.length; i++) { + const data = eventDataList[i]; + const path = data.getPath(); + if (currList !== null && !pathEquals(path, currList.path)) { + eventQueue.eventLists_.push(currList); + currList = null; + } + if (currList === null) { + currList = { events: [], path }; + } + currList.events.push(data); + } + if (currList) { + eventQueue.eventLists_.push(currList); + } +} +/** + * Queues the specified events and synchronously raises all events (including previously queued ones) + * for the specified path. + * + * It is assumed that the new events are all for the specified path. + * + * @param path - The path to raise events for. + * @param eventDataList - The new events to raise. + */ +function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) { + eventQueueQueueEvents(eventQueue, eventDataList); + eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path)); +} +/** + * Queues the specified events and synchronously raises all events (including previously queued ones) for + * locations related to the specified change path (i.e. all ancestors and descendants). + * + * It is assumed that the new events are all related (ancestor or descendant) to the specified path. + * + * @param changedPath - The path to raise events for. + * @param eventDataList - The events to raise + */ +function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) { + eventQueueQueueEvents(eventQueue, eventDataList); + eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) || + pathContains(changedPath, eventPath)); +} +function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) { + eventQueue.recursionDepth_++; + let sentAll = true; + for (let i = 0; i < eventQueue.eventLists_.length; i++) { + const eventList = eventQueue.eventLists_[i]; + if (eventList) { + const eventPath = eventList.path; + if (predicate(eventPath)) { + eventListRaise(eventQueue.eventLists_[i]); + eventQueue.eventLists_[i] = null; + } + else { + sentAll = false; + } + } + } + if (sentAll) { + eventQueue.eventLists_ = []; + } + eventQueue.recursionDepth_--; +} +/** + * Iterates through the list and raises each event + */ +function eventListRaise(eventList) { + for (let i = 0; i < eventList.events.length; i++) { + const eventData = eventList.events[i]; + if (eventData !== null) { + eventList.events[i] = null; + const eventFn = eventData.getEventRunner(); + if (logger) { + log('event: ' + eventData.toString()); + } + exceptionGuard(eventFn); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const INTERRUPT_REASON = 'repo_interrupt'; +/** + * If a transaction does not succeed after 25 retries, we abort it. Among other + * things this ensure that if there's ever a bug causing a mismatch between + * client / server hashes for some data, we won't retry indefinitely. + */ +const MAX_TRANSACTION_RETRIES = 25; +/** + * A connection to a single data repository. + */ +class Repo { + constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) { + this.repoInfo_ = repoInfo_; + this.forceRestClient_ = forceRestClient_; + this.authTokenProvider_ = authTokenProvider_; + this.appCheckProvider_ = appCheckProvider_; + this.dataUpdateCount = 0; + this.statsListener_ = null; + this.eventQueue_ = new EventQueue(); + this.nextWriteId_ = 1; + this.interceptServerDataCallback_ = null; + /** A list of data pieces and paths to be set when this client disconnects. */ + this.onDisconnect_ = newSparseSnapshotTree(); + /** Stores queues of outstanding transactions for Firebase locations. */ + this.transactionQueueTree_ = new Tree(); + // TODO: This should be @private but it's used by test_access.js and internal.js + this.persistentConnection_ = null; + // This key is intentionally not updated if RepoInfo is later changed or replaced + this.key = this.repoInfo_.toURLString(); + } + /** + * @returns The URL corresponding to the root of this Firebase. + */ + toString() { + return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host); + } +} +function repoStart(repo, appId, authOverride) { + repo.stats_ = statsManagerGetCollection(repo.repoInfo_); + if (repo.forceRestClient_ || beingCrawled()) { + repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => { + repoOnDataUpdate(repo, pathString, data, isMerge, tag); + }, repo.authTokenProvider_, repo.appCheckProvider_); + // Minor hack: Fire onConnect immediately, since there's no actual connection. + setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0); + } + else { + // Validate authOverride + if (typeof authOverride !== 'undefined' && authOverride !== null) { + if (typeof authOverride !== 'object') { + throw new Error('Only objects are supported for option databaseAuthVariableOverride'); + } + try { + util.stringify(authOverride); + } + catch (e) { + throw new Error('Invalid authOverride provided: ' + e); + } + } + repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => { + repoOnDataUpdate(repo, pathString, data, isMerge, tag); + }, (connectStatus) => { + repoOnConnectStatus(repo, connectStatus); + }, (updates) => { + repoOnServerInfoUpdate(repo, updates); + }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride); + repo.server_ = repo.persistentConnection_; + } + repo.authTokenProvider_.addTokenChangeListener(token => { + repo.server_.refreshAuthToken(token); + }); + repo.appCheckProvider_.addTokenChangeListener(result => { + repo.server_.refreshAppCheckToken(result.token); + }); + // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used), + // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created. + repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_)); + // Used for .info. + repo.infoData_ = new SnapshotHolder(); + repo.infoSyncTree_ = new SyncTree({ + startListening: (query, tag, currentHashFn, onComplete) => { + let infoEvents = []; + const node = repo.infoData_.getNode(query._path); + // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events + // on initial data... + if (!node.isEmpty()) { + infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node); + setTimeout(() => { + onComplete('ok'); + }, 0); + } + return infoEvents; + }, + stopListening: () => { } + }); + repoUpdateInfo(repo, 'connected', false); + repo.serverSyncTree_ = new SyncTree({ + startListening: (query, tag, currentHashFn, onComplete) => { + repo.server_.listen(query, currentHashFn, tag, (status, data) => { + const events = onComplete(status, data); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events); + }); + // No synchronous events for network-backed sync trees + return []; + }, + stopListening: (query, tag) => { + repo.server_.unlisten(query, tag); + } + }); +} +/** + * @returns The time in milliseconds, taking the server offset into account if we have one. + */ +function repoServerTime(repo) { + const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset')); + const offset = offsetNode.val() || 0; + return new Date().getTime() + offset; +} +/** + * Generate ServerValues using some variables from the repo object. + */ +function repoGenerateServerValues(repo) { + return generateWithValues({ + timestamp: repoServerTime(repo) + }); +} +/** + * Called by realtime when we get new messages from the server. + */ +function repoOnDataUpdate(repo, pathString, data, isMerge, tag) { + // For testing. + repo.dataUpdateCount++; + const path = new Path(pathString); + data = repo.interceptServerDataCallback_ + ? repo.interceptServerDataCallback_(pathString, data) + : data; + let events = []; + if (tag) { + if (isMerge) { + const taggedChildren = util.map(data, (raw) => nodeFromJSON(raw)); + events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag); + } + else { + const taggedSnap = nodeFromJSON(data); + events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag); + } + } + else if (isMerge) { + const changedChildren = util.map(data, (raw) => nodeFromJSON(raw)); + events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren); + } + else { + const snap = nodeFromJSON(data); + events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap); + } + let affectedPath = path; + if (events.length > 0) { + // Since we have a listener outstanding for each transaction, receiving any events + // is a proxy for some change having occurred. + affectedPath = repoRerunTransactions(repo, path); + } + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events); +} +function repoOnConnectStatus(repo, connectStatus) { + repoUpdateInfo(repo, 'connected', connectStatus); + if (connectStatus === false) { + repoRunOnDisconnectEvents(repo); + } +} +function repoOnServerInfoUpdate(repo, updates) { + each(updates, (key, value) => { + repoUpdateInfo(repo, key, value); + }); +} +function repoUpdateInfo(repo, pathString, value) { + const path = new Path('/.info/' + pathString); + const newNode = nodeFromJSON(value); + repo.infoData_.updateSnapshot(path, newNode); + const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); +} +function repoGetNextWriteId(repo) { + return repo.nextWriteId_++; +} +/** + * The purpose of `getValue` is to return the latest known value + * satisfying `query`. + * + * This method will first check for in-memory cached values + * belonging to active listeners. If they are found, such values + * are considered to be the most up-to-date. + * + * If the client is not connected, this method will wait until the + * repo has established a connection and then request the value for `query`. + * If the client is not able to retrieve the query result for another reason, + * it reports an error. + * + * @param query - The query to surface a value for. + */ +function repoGetValue(repo, query, eventRegistration) { + // Only active queries are cached. There is no persisted cache. + const cached = syncTreeGetServerValue(repo.serverSyncTree_, query); + if (cached != null) { + return Promise.resolve(cached); + } + return repo.server_.get(query).then(payload => { + const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex()); + /** + * Below we simulate the actions of an `onlyOnce` `onValue()` event where: + * Add an event registration, + * Update data at the path, + * Raise any events, + * Cleanup the SyncTree + */ + syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true); + let events; + if (query._queryParams.loadsAllData()) { + events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node); + } + else { + const tag = syncTreeTagForQuery(repo.serverSyncTree_, query); + events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag); + } + /* + * We need to raise events in the scenario where `get()` is called at a parent path, and + * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting + * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree + * and its corresponding serverCache, including the child location where `onValue` is called. Then, + * `onValue` will receive the event from the server, but look at the syncTree and see that the data received + * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired. + * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and + * ensure the corresponding child events will get fired. + */ + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events); + syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true); + return node; + }, err => { + repoLog(repo, 'get for query ' + util.stringify(query) + ' failed: ' + err); + return Promise.reject(new Error(err)); + }); +} +function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) { + repoLog(repo, 'set', { + path: path.toString(), + value: newVal, + priority: newPriority + }); + // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or + // (b) store unresolved paths on JSON parse + const serverValues = repoGenerateServerValues(repo); + const newNodeUnresolved = nodeFromJSON(newVal, newPriority); + const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path); + const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues); + const writeId = repoGetNextWriteId(repo); + const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true); + eventQueueQueueEvents(repo.eventQueue_, events); + repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => { + const success = status === 'ok'; + if (!success) { + warn('set at ' + path + ' failed: ' + status); + } + const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents); + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); + const affectedPath = repoAbortTransactions(repo, path); + repoRerunTransactions(repo, affectedPath); + // We queued the events above, so just flush the queue here + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []); +} +function repoUpdate(repo, path, childrenToMerge, onComplete) { + repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge }); + // Start with our existing data and merge each child into it. + let empty = true; + const serverValues = repoGenerateServerValues(repo); + const changedChildren = {}; + each(childrenToMerge, (changedKey, changedValue) => { + empty = false; + changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues); + }); + if (!empty) { + const writeId = repoGetNextWriteId(repo); + const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId); + eventQueueQueueEvents(repo.eventQueue_, events); + repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => { + const success = status === 'ok'; + if (!success) { + warn('update at ' + path + ' failed: ' + status); + } + const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success); + const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path; + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents); + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); + each(childrenToMerge, (changedPath) => { + const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath)); + repoRerunTransactions(repo, affectedPath); + }); + // We queued the events above, so just flush the queue here + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []); + } + else { + log("update() called with empty data. Don't do anything."); + repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined); + } +} +/** + * Applies all of the changes stored up in the onDisconnect_ tree. + */ +function repoRunOnDisconnectEvents(repo) { + repoLog(repo, 'onDisconnectEvents'); + const serverValues = repoGenerateServerValues(repo); + const resolvedOnDisconnectTree = newSparseSnapshotTree(); + sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => { + const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues); + sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved); + }); + let events = []; + sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => { + events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap)); + const affectedPath = repoAbortTransactions(repo, path); + repoRerunTransactions(repo, affectedPath); + }); + repo.onDisconnect_ = newSparseSnapshotTree(); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events); +} +function repoOnDisconnectCancel(repo, path, onComplete) { + repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => { + if (status === 'ok') { + sparseSnapshotTreeForget(repo.onDisconnect_, path); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoOnDisconnectSet(repo, path, value, onComplete) { + const newNode = nodeFromJSON(value); + repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => { + if (status === 'ok') { + sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) { + const newNode = nodeFromJSON(value, priority); + repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => { + if (status === 'ok') { + sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) { + if (util.isEmpty(childrenToMerge)) { + log("onDisconnect().update() called with empty data. Don't do anything."); + repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined); + return; + } + repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => { + if (status === 'ok') { + each(childrenToMerge, (childName, childNode) => { + const newChildNode = nodeFromJSON(childNode); + sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode); + }); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoAddEventCallbackForQuery(repo, query, eventRegistration) { + let events; + if (pathGetFront(query._path) === '.info') { + events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration); + } + else { + events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration); + } + eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events); +} +function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) { + // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof + // a little bit by handling the return values anyways. + let events; + if (pathGetFront(query._path) === '.info') { + events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration); + } + else { + events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration); + } + eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events); +} +function repoInterrupt(repo) { + if (repo.persistentConnection_) { + repo.persistentConnection_.interrupt(INTERRUPT_REASON); + } +} +function repoResume(repo) { + if (repo.persistentConnection_) { + repo.persistentConnection_.resume(INTERRUPT_REASON); + } +} +function repoLog(repo, ...varArgs) { + let prefix = ''; + if (repo.persistentConnection_) { + prefix = repo.persistentConnection_.id + ':'; + } + log(prefix, ...varArgs); +} +function repoCallOnCompleteCallback(repo, callback, status, errorReason) { + if (callback) { + exceptionGuard(() => { + if (status === 'ok') { + callback(null); + } + else { + const code = (status || 'error').toUpperCase(); + let message = code; + if (errorReason) { + message += ': ' + errorReason; + } + const error = new Error(message); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error.code = code; + callback(error); + } + }); + } +} +/** + * Creates a new transaction, adds it to the transactions we're tracking, and + * sends it to the server if possible. + * + * @param path - Path at which to do transaction. + * @param transactionUpdate - Update callback. + * @param onComplete - Completion callback. + * @param unwatcher - Function that will be called when the transaction no longer + * need data updates for `path`. + * @param applyLocally - Whether or not to make intermediate results visible + */ +function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) { + repoLog(repo, 'transaction on ' + path); + // Initialize transaction. + const transaction = { + path, + update: transactionUpdate, + onComplete, + // One of TransactionStatus enums. + status: null, + // Used when combining transactions at different locations to figure out + // which one goes first. + order: LUIDGenerator(), + // Whether to raise local events for this transaction. + applyLocally, + // Count of how many times we've retried the transaction. + retryCount: 0, + // Function to call to clean up our .on() listener. + unwatcher, + // Stores why a transaction was aborted. + abortReason: null, + currentWriteId: null, + currentInputSnapshot: null, + currentOutputSnapshotRaw: null, + currentOutputSnapshotResolved: null + }; + // Run transaction initially. + const currentState = repoGetLatestState(repo, path, undefined); + transaction.currentInputSnapshot = currentState; + const newVal = transaction.update(currentState.val()); + if (newVal === undefined) { + // Abort transaction. + transaction.unwatcher(); + transaction.currentOutputSnapshotRaw = null; + transaction.currentOutputSnapshotResolved = null; + if (transaction.onComplete) { + transaction.onComplete(null, false, transaction.currentInputSnapshot); + } + } + else { + validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path); + // Mark as run and add to our queue. + transaction.status = 0 /* TransactionStatus.RUN */; + const queueNode = treeSubTree(repo.transactionQueueTree_, path); + const nodeQueue = treeGetValue(queueNode) || []; + nodeQueue.push(transaction); + treeSetValue(queueNode, nodeQueue); + // Update visibleData and raise events + // Note: We intentionally raise events after updating all of our + // transaction state, since the user could start new transactions from the + // event callbacks. + let priorityForNode; + if (typeof newVal === 'object' && + newVal !== null && + util.contains(newVal, '.priority')) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + priorityForNode = util.safeGet(newVal, '.priority'); + util.assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' + + 'Priority must be a valid string, finite number, server value, or null.'); + } + else { + const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) || + ChildrenNode.EMPTY_NODE; + priorityForNode = currentNode.getPriority().val(); + } + const serverValues = repoGenerateServerValues(repo); + const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode); + const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues); + transaction.currentOutputSnapshotRaw = newNodeUnresolved; + transaction.currentOutputSnapshotResolved = newNode; + transaction.currentWriteId = repoGetNextWriteId(repo); + const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); + repoSendReadyTransactions(repo, repo.transactionQueueTree_); + } +} +/** + * @param excludeSets - A specific set to exclude + */ +function repoGetLatestState(repo, path, excludeSets) { + return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) || + ChildrenNode.EMPTY_NODE); +} +/** + * Sends any already-run transactions that aren't waiting for outstanding + * transactions to complete. + * + * Externally it's called with no arguments, but it calls itself recursively + * with a particular transactionQueueTree node to recurse through the tree. + * + * @param node - transactionQueueTree node to start at. + */ +function repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) { + // Before recursing, make sure any completed transactions are removed. + if (!node) { + repoPruneCompletedTransactionsBelowNode(repo, node); + } + if (treeGetValue(node)) { + const queue = repoBuildTransactionQueue(repo, node); + util.assert(queue.length > 0, 'Sending zero length transaction queue'); + const allRun = queue.every((transaction) => transaction.status === 0 /* TransactionStatus.RUN */); + // If they're all run (and not sent), we can send them. Else, we must wait. + if (allRun) { + repoSendTransactionQueue(repo, treeGetPath(node), queue); + } + } + else if (treeHasChildren(node)) { + treeForEachChild(node, childNode => { + repoSendReadyTransactions(repo, childNode); + }); + } +} +/** + * Given a list of run transactions, send them to the server and then handle + * the result (success or failure). + * + * @param path - The location of the queue. + * @param queue - Queue of transactions under the specified location. + */ +function repoSendTransactionQueue(repo, path, queue) { + // Mark transactions as sent and increment retry count! + const setsToIgnore = queue.map(txn => { + return txn.currentWriteId; + }); + const latestState = repoGetLatestState(repo, path, setsToIgnore); + let snapToSend = latestState; + const latestHash = latestState.hash(); + for (let i = 0; i < queue.length; i++) { + const txn = queue[i]; + util.assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.'); + txn.status = 1 /* TransactionStatus.SENT */; + txn.retryCount++; + const relativePath = newRelativePath(path, txn.path); + // If we've gotten to this point, the output snapshot must be defined. + snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw); + } + const dataToSend = snapToSend.val(true); + const pathToSend = path; + // Send the put. + repo.server_.put(pathToSend.toString(), dataToSend, (status) => { + repoLog(repo, 'transaction put response', { + path: pathToSend.toString(), + status + }); + let events = []; + if (status === 'ok') { + // Queue up the callbacks and fire them after cleaning up all of our + // transaction state, since the callback could trigger more + // transactions or sets. + const callbacks = []; + for (let i = 0; i < queue.length; i++) { + queue[i].status = 2 /* TransactionStatus.COMPLETED */; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId)); + if (queue[i].onComplete) { + // We never unset the output snapshot, and given that this + // transaction is complete, it should be set + callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved)); + } + queue[i].unwatcher(); + } + // Now remove the completed transactions. + repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path)); + // There may be pending transactions that we can now send. + repoSendReadyTransactions(repo, repo.transactionQueueTree_); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); + // Finally, trigger onComplete callbacks. + for (let i = 0; i < callbacks.length; i++) { + exceptionGuard(callbacks[i]); + } + } + else { + // transactions are no longer sent. Update their status appropriately. + if (status === 'datastale') { + for (let i = 0; i < queue.length; i++) { + if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) { + queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */; + } + else { + queue[i].status = 0 /* TransactionStatus.RUN */; + } + } + } + else { + warn('transaction at ' + pathToSend.toString() + ' failed: ' + status); + for (let i = 0; i < queue.length; i++) { + queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */; + queue[i].abortReason = status; + } + } + repoRerunTransactions(repo, path); + } + }, latestHash); +} +/** + * Finds all transactions dependent on the data at changedPath and reruns them. + * + * Should be called any time cached data changes. + * + * Return the highest path that was affected by rerunning transactions. This + * is the path at which events need to be raised for. + * + * @param changedPath - The path in mergedData that changed. + * @returns The rootmost path that was affected by rerunning transactions. + */ +function repoRerunTransactions(repo, changedPath) { + const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath); + const path = treeGetPath(rootMostTransactionNode); + const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode); + repoRerunTransactionQueue(repo, queue, path); + return path; +} +/** + * Does all the work of rerunning transactions (as well as cleans up aborted + * transactions and whatnot). + * + * @param queue - The queue of transactions to run. + * @param path - The path the queue is for. + */ +function repoRerunTransactionQueue(repo, queue, path) { + if (queue.length === 0) { + return; // Nothing to do! + } + // Queue up the callbacks and fire them after cleaning up all of our + // transaction state, since the callback could trigger more transactions or + // sets. + const callbacks = []; + let events = []; + // Ignore all of the sets we're going to re-run. + const txnsToRerun = queue.filter(q => { + return q.status === 0 /* TransactionStatus.RUN */; + }); + const setsToIgnore = txnsToRerun.map(q => { + return q.currentWriteId; + }); + for (let i = 0; i < queue.length; i++) { + const transaction = queue[i]; + const relativePath = newRelativePath(path, transaction.path); + let abortTransaction = false, abortReason; + util.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.'); + if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) { + abortTransaction = true; + abortReason = transaction.abortReason; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true)); + } + else if (transaction.status === 0 /* TransactionStatus.RUN */) { + if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) { + abortTransaction = true; + abortReason = 'maxretry'; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true)); + } + else { + // This code reruns a transaction + const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore); + transaction.currentInputSnapshot = currentNode; + const newData = queue[i].update(currentNode.val()); + if (newData !== undefined) { + validateFirebaseData('transaction failed: Data returned ', newData, transaction.path); + let newDataNode = nodeFromJSON(newData); + const hasExplicitPriority = typeof newData === 'object' && + newData != null && + util.contains(newData, '.priority'); + if (!hasExplicitPriority) { + // Keep the old priority if there wasn't a priority explicitly specified. + newDataNode = newDataNode.updatePriority(currentNode.getPriority()); + } + const oldWriteId = transaction.currentWriteId; + const serverValues = repoGenerateServerValues(repo); + const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues); + transaction.currentOutputSnapshotRaw = newDataNode; + transaction.currentOutputSnapshotResolved = newNodeResolved; + transaction.currentWriteId = repoGetNextWriteId(repo); + // Mutates setsToIgnore in place + setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1); + events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally)); + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true)); + } + else { + abortTransaction = true; + abortReason = 'nodata'; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true)); + } + } + } + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); + events = []; + if (abortTransaction) { + // Abort. + queue[i].status = 2 /* TransactionStatus.COMPLETED */; + // Removing a listener can trigger pruning which can muck with + // mergedData/visibleData (as it prunes data). So defer the unwatcher + // until we're done. + (function (unwatcher) { + setTimeout(unwatcher, Math.floor(0)); + })(queue[i].unwatcher); + if (queue[i].onComplete) { + if (abortReason === 'nodata') { + callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot)); + } + else { + callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null)); + } + } + } + } + // Clean up completed transactions. + repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_); + // Now fire callbacks, now that we're in a good, known state. + for (let i = 0; i < callbacks.length; i++) { + exceptionGuard(callbacks[i]); + } + // Try to send the transaction result to the server. + repoSendReadyTransactions(repo, repo.transactionQueueTree_); +} +/** + * Returns the rootmost ancestor node of the specified path that has a pending + * transaction on it, or just returns the node for the given path if there are + * no pending transactions on any ancestor. + * + * @param path - The location to start at. + * @returns The rootmost node with a transaction. + */ +function repoGetAncestorTransactionNode(repo, path) { + let front; + // Start at the root and walk deeper into the tree towards path until we + // find a node with pending transactions. + let transactionNode = repo.transactionQueueTree_; + front = pathGetFront(path); + while (front !== null && treeGetValue(transactionNode) === undefined) { + transactionNode = treeSubTree(transactionNode, front); + path = pathPopFront(path); + front = pathGetFront(path); + } + return transactionNode; +} +/** + * Builds the queue of all transactions at or below the specified + * transactionNode. + * + * @param transactionNode + * @returns The generated queue. + */ +function repoBuildTransactionQueue(repo, transactionNode) { + // Walk any child transaction queues and aggregate them into a single queue. + const transactionQueue = []; + repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue); + // Sort them by the order the transactions were created. + transactionQueue.sort((a, b) => a.order - b.order); + return transactionQueue; +} +function repoAggregateTransactionQueuesForNode(repo, node, queue) { + const nodeQueue = treeGetValue(node); + if (nodeQueue) { + for (let i = 0; i < nodeQueue.length; i++) { + queue.push(nodeQueue[i]); + } + } + treeForEachChild(node, child => { + repoAggregateTransactionQueuesForNode(repo, child, queue); + }); +} +/** + * Remove COMPLETED transactions at or below this node in the transactionQueueTree_. + */ +function repoPruneCompletedTransactionsBelowNode(repo, node) { + const queue = treeGetValue(node); + if (queue) { + let to = 0; + for (let from = 0; from < queue.length; from++) { + if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) { + queue[to] = queue[from]; + to++; + } + } + queue.length = to; + treeSetValue(node, queue.length > 0 ? queue : undefined); + } + treeForEachChild(node, childNode => { + repoPruneCompletedTransactionsBelowNode(repo, childNode); + }); +} +/** + * Aborts all transactions on ancestors or descendants of the specified path. + * Called when doing a set() or update() since we consider them incompatible + * with transactions. + * + * @param path - Path for which we want to abort related transactions. + */ +function repoAbortTransactions(repo, path) { + const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path)); + const transactionNode = treeSubTree(repo.transactionQueueTree_, path); + treeForEachAncestor(transactionNode, (node) => { + repoAbortTransactionsOnNode(repo, node); + }); + repoAbortTransactionsOnNode(repo, transactionNode); + treeForEachDescendant(transactionNode, (node) => { + repoAbortTransactionsOnNode(repo, node); + }); + return affectedPath; +} +/** + * Abort transactions stored in this transaction queue node. + * + * @param node - Node to abort transactions for. + */ +function repoAbortTransactionsOnNode(repo, node) { + const queue = treeGetValue(node); + if (queue) { + // Queue up the callbacks and fire them after cleaning up all of our + // transaction state, since the callback could trigger more transactions + // or sets. + const callbacks = []; + // Go through queue. Any already-sent transactions must be marked for + // abort, while the unsent ones can be immediately aborted and removed. + let events = []; + let lastSent = -1; + for (let i = 0; i < queue.length; i++) { + if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ; + else if (queue[i].status === 1 /* TransactionStatus.SENT */) { + util.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.'); + lastSent = i; + // Mark transaction for abort when it comes back. + queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */; + queue[i].abortReason = 'set'; + } + else { + util.assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort'); + // We can abort it immediately. + queue[i].unwatcher(); + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true)); + if (queue[i].onComplete) { + callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null)); + } + } + } + if (lastSent === -1) { + // We're not waiting for any sent transactions. We can clear the queue. + treeSetValue(node, undefined); + } + else { + // Remove the transactions we aborted. + queue.length = lastSent + 1; + } + // Now fire the callbacks. + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events); + for (let i = 0; i < callbacks.length; i++) { + exceptionGuard(callbacks[i]); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function decodePath(pathString) { + let pathStringDecoded = ''; + const pieces = pathString.split('/'); + for (let i = 0; i < pieces.length; i++) { + if (pieces[i].length > 0) { + let piece = pieces[i]; + try { + piece = decodeURIComponent(piece.replace(/\+/g, ' ')); + } + catch (e) { } + pathStringDecoded += '/' + piece; + } + } + return pathStringDecoded; +} +/** + * @returns key value hash + */ +function decodeQuery(queryString) { + const results = {}; + if (queryString.charAt(0) === '?') { + queryString = queryString.substring(1); + } + for (const segment of queryString.split('&')) { + if (segment.length === 0) { + continue; + } + const kv = segment.split('='); + if (kv.length === 2) { + results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]); + } + else { + warn(`Invalid query segment '${segment}' in query '${queryString}'`); + } + } + return results; +} +const parseRepoInfo = function (dataURL, nodeAdmin) { + const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace; + if (parsedUrl.domain === 'firebase.com') { + fatal(parsedUrl.host + + ' is no longer supported. ' + + 'Please use .firebaseio.com instead'); + } + // Catch common error of uninitialized namespace value. + if ((!namespace || namespace === 'undefined') && + parsedUrl.domain !== 'localhost') { + fatal('Cannot parse Firebase url. Please use https://.firebaseio.com'); + } + if (!parsedUrl.secure) { + warnIfPageIsSecure(); + } + const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss'; + return { + repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin, + /*persistenceKey=*/ '', + /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain), + path: new Path(parsedUrl.pathString) + }; +}; +const parseDatabaseURL = function (dataURL) { + // Default to empty strings in the event of a malformed string. + let host = '', domain = '', subdomain = '', pathString = '', namespace = ''; + // Always default to SSL, unless otherwise specified. + let secure = true, scheme = 'https', port = 443; + // Don't do any validation here. The caller is responsible for validating the result of parsing. + if (typeof dataURL === 'string') { + // Parse scheme. + let colonInd = dataURL.indexOf('//'); + if (colonInd >= 0) { + scheme = dataURL.substring(0, colonInd - 1); + dataURL = dataURL.substring(colonInd + 2); + } + // Parse host, path, and query string. + let slashInd = dataURL.indexOf('/'); + if (slashInd === -1) { + slashInd = dataURL.length; + } + let questionMarkInd = dataURL.indexOf('?'); + if (questionMarkInd === -1) { + questionMarkInd = dataURL.length; + } + host = dataURL.substring(0, Math.min(slashInd, questionMarkInd)); + if (slashInd < questionMarkInd) { + // For pathString, questionMarkInd will always come after slashInd + pathString = decodePath(dataURL.substring(slashInd, questionMarkInd)); + } + const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd))); + // If we have a port, use scheme for determining if it's secure. + colonInd = host.indexOf(':'); + if (colonInd >= 0) { + secure = scheme === 'https' || scheme === 'wss'; + port = parseInt(host.substring(colonInd + 1), 10); + } + else { + colonInd = host.length; + } + const hostWithoutPort = host.slice(0, colonInd); + if (hostWithoutPort.toLowerCase() === 'localhost') { + domain = 'localhost'; + } + else if (hostWithoutPort.split('.').length <= 2) { + domain = hostWithoutPort; + } + else { + // Interpret the subdomain of a 3 or more component URL as the namespace name. + const dotInd = host.indexOf('.'); + subdomain = host.substring(0, dotInd).toLowerCase(); + domain = host.substring(dotInd + 1); + // Normalize namespaces to lowercase to share storage / connection. + namespace = subdomain; + } + // Always treat the value of the `ns` as the namespace name if it is present. + if ('ns' in queryParams) { + namespace = queryParams['ns']; + } + } + return { + host, + port, + domain, + subdomain, + secure, + scheme, + pathString, + namespace + }; +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Modeled after base64 web-safe chars, but ordered by ASCII. +const PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'; +/** + * Fancy ID generator that creates 20-character string identifiers with the + * following properties: + * + * 1. They're based on timestamp so that they sort *after* any existing ids. + * 2. They contain 72-bits of random data after the timestamp so that IDs won't + * collide with other clients' IDs. + * 3. They sort *lexicographically* (so the timestamp is converted to characters + * that will sort properly). + * 4. They're monotonically increasing. Even if you generate more than one in + * the same timestamp, the latter ones will sort after the former ones. We do + * this by using the previous random bits but "incrementing" them by 1 (only + * in the case of a timestamp collision). + */ +const nextPushId = (function () { + // Timestamp of last push, used to prevent local collisions if you push twice + // in one ms. + let lastPushTime = 0; + // We generate 72-bits of randomness which get turned into 12 characters and + // appended to the timestamp to prevent collisions with other clients. We + // store the last characters we generated because in the event of a collision, + // we'll use those same characters except "incremented" by one. + const lastRandChars = []; + return function (now) { + const duplicateTime = now === lastPushTime; + lastPushTime = now; + let i; + const timeStampChars = new Array(8); + for (i = 7; i >= 0; i--) { + timeStampChars[i] = PUSH_CHARS.charAt(now % 64); + // NOTE: Can't use << here because javascript will convert to int and lose + // the upper bits. + now = Math.floor(now / 64); + } + util.assert(now === 0, 'Cannot push at time == 0'); + let id = timeStampChars.join(''); + if (!duplicateTime) { + for (i = 0; i < 12; i++) { + lastRandChars[i] = Math.floor(Math.random() * 64); + } + } + else { + // If the timestamp hasn't changed since last push, use the same random + // number, except incremented by 1. + for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) { + lastRandChars[i] = 0; + } + lastRandChars[i]++; + } + for (i = 0; i < 12; i++) { + id += PUSH_CHARS.charAt(lastRandChars[i]); + } + util.assert(id.length === 20, 'nextPushId: Length should be 20.'); + return id; + }; +})(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Encapsulates the data needed to raise an event + */ +class DataEvent { + /** + * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed + * @param eventRegistration - The function to call to with the event data. User provided + * @param snapshot - The data backing the event + * @param prevName - Optional, the name of the previous child for child_* events. + */ + constructor(eventType, eventRegistration, snapshot, prevName) { + this.eventType = eventType; + this.eventRegistration = eventRegistration; + this.snapshot = snapshot; + this.prevName = prevName; + } + getPath() { + const ref = this.snapshot.ref; + if (this.eventType === 'value') { + return ref._path; + } + else { + return ref.parent._path; + } + } + getEventType() { + return this.eventType; + } + getEventRunner() { + return this.eventRegistration.getEventRunner(this); + } + toString() { + return (this.getPath().toString() + + ':' + + this.eventType + + ':' + + util.stringify(this.snapshot.exportVal())); + } +} +class CancelEvent { + constructor(eventRegistration, error, path) { + this.eventRegistration = eventRegistration; + this.error = error; + this.path = path; + } + getPath() { + return this.path; + } + getEventType() { + return 'cancel'; + } + getEventRunner() { + return this.eventRegistration.getEventRunner(this); + } + toString() { + return this.path.toString() + ':cancel'; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A wrapper class that converts events from the database@exp SDK to the legacy + * Database SDK. Events are not converted directly as event registration relies + * on reference comparison of the original user callback (see `matches()`) and + * relies on equality of the legacy SDK's `context` object. + */ +class CallbackContext { + constructor(snapshotCallback, cancelCallback) { + this.snapshotCallback = snapshotCallback; + this.cancelCallback = cancelCallback; + } + onValue(expDataSnapshot, previousChildName) { + this.snapshotCallback.call(null, expDataSnapshot, previousChildName); + } + onCancel(error) { + util.assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback'); + return this.cancelCallback.call(null, error); + } + get hasCancelCallback() { + return !!this.cancelCallback; + } + matches(other) { + return (this.snapshotCallback === other.snapshotCallback || + (this.snapshotCallback.userCallback !== undefined && + this.snapshotCallback.userCallback === + other.snapshotCallback.userCallback && + this.snapshotCallback.context === other.snapshotCallback.context)); + } +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The `onDisconnect` class allows you to write or clear data when your client + * disconnects from the Database server. These updates occur whether your + * client disconnects cleanly or not, so you can rely on them to clean up data + * even if a connection is dropped or a client crashes. + * + * The `onDisconnect` class is most commonly used to manage presence in + * applications where it is useful to detect how many clients are connected and + * when other clients disconnect. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * To avoid problems when a connection is dropped before the requests can be + * transferred to the Database server, these functions should be called before + * writing any data. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time you reconnect. + */ +class OnDisconnect { + /** @hideconstructor */ + constructor(_repo, _path) { + this._repo = _repo; + this._path = _path; + } + /** + * Cancels all previously queued `onDisconnect()` set or update events for this + * location and all children. + * + * If a write has been queued for this location via a `set()` or `update()` at a + * parent location, the write at this location will be canceled, though writes + * to sibling locations will still occur. + * + * @returns Resolves when synchronization to the server is complete. + */ + cancel() { + const deferred = new util.Deferred(); + repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Ensures the data at this location is deleted when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + * + * @returns Resolves when synchronization to the server is complete. + */ + remove() { + validateWritablePath('OnDisconnect.remove', this._path); + const deferred = new util.Deferred(); + repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Ensures the data at this location is set to the specified value when the + * client is disconnected (due to closing the browser, navigating to a new page, + * or network issues). + * + * `set()` is especially useful for implementing "presence" systems, where a + * value should be changed or cleared when a user disconnects so that they + * appear "offline" to other users. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time. + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + set(value) { + validateWritablePath('OnDisconnect.set', this._path); + validateFirebaseDataArg('OnDisconnect.set', value, this._path, false); + const deferred = new util.Deferred(); + repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Ensures the data at this location is set to the specified value and priority + * when the client is disconnected (due to closing the browser, navigating to a + * new page, or network issues). + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + setWithPriority(value, priority) { + validateWritablePath('OnDisconnect.setWithPriority', this._path); + validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false); + validatePriority('OnDisconnect.setWithPriority', priority, false); + const deferred = new util.Deferred(); + repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Writes multiple values at this location when the client is disconnected (due + * to closing the browser, navigating to a new page, or network issues). + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, "name/first") + * from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * @param values - Object containing multiple values. + * @returns Resolves when synchronization to the Database is complete. + */ + update(values) { + validateWritablePath('OnDisconnect.update', this._path); + validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false); + const deferred = new util.Deferred(); + repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { })); + return deferred.promise; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ +class QueryImpl { + /** + * @hideconstructor + */ + constructor(_repo, _path, _queryParams, _orderByCalled) { + this._repo = _repo; + this._path = _path; + this._queryParams = _queryParams; + this._orderByCalled = _orderByCalled; + } + get key() { + if (pathIsEmpty(this._path)) { + return null; + } + else { + return pathGetBack(this._path); + } + } + get ref() { + return new ReferenceImpl(this._repo, this._path); + } + get _queryIdentifier() { + const obj = queryParamsGetQueryObject(this._queryParams); + const id = ObjectToUniqueKey(obj); + return id === '{}' ? 'default' : id; + } + /** + * An object representation of the query parameters used by this Query. + */ + get _queryObject() { + return queryParamsGetQueryObject(this._queryParams); + } + isEqual(other) { + other = util.getModularInstance(other); + if (!(other instanceof QueryImpl)) { + return false; + } + const sameRepo = this._repo === other._repo; + const samePath = pathEquals(this._path, other._path); + const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier; + return sameRepo && samePath && sameQueryIdentifier; + } + toJSON() { + return this.toString(); + } + toString() { + return this._repo.toString() + pathToUrlEncodedString(this._path); + } +} +/** + * Validates that no other order by call has been made + */ +function validateNoPreviousOrderByCall(query, fnName) { + if (query._orderByCalled === true) { + throw new Error(fnName + ": You can't combine multiple orderBy calls."); + } +} +/** + * Validates start/end values for queries. + */ +function validateQueryEndpoints(params) { + let startNode = null; + let endNode = null; + if (params.hasStart()) { + startNode = params.getIndexStartValue(); + } + if (params.hasEnd()) { + endNode = params.getIndexEndValue(); + } + if (params.getIndex() === KEY_INDEX) { + const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' + + 'startAt(), endAt(), or equalTo().'; + const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' + + 'endAt(), endBefore(), or equalTo() must be a string.'; + if (params.hasStart()) { + const startName = params.getIndexStartName(); + if (startName !== MIN_NAME) { + throw new Error(tooManyArgsError); + } + else if (typeof startNode !== 'string') { + throw new Error(wrongArgTypeError); + } + } + if (params.hasEnd()) { + const endName = params.getIndexEndName(); + if (endName !== MAX_NAME) { + throw new Error(tooManyArgsError); + } + else if (typeof endNode !== 'string') { + throw new Error(wrongArgTypeError); + } + } + } + else if (params.getIndex() === PRIORITY_INDEX) { + if ((startNode != null && !isValidPriority(startNode)) || + (endNode != null && !isValidPriority(endNode))) { + throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' + + 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' + + '(null, a number, or a string).'); + } + } + else { + util.assert(params.getIndex() instanceof PathIndex || + params.getIndex() === VALUE_INDEX, 'unknown index type.'); + if ((startNode != null && typeof startNode === 'object') || + (endNode != null && typeof endNode === 'object')) { + throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' + + 'equalTo() cannot be an object.'); + } + } +} +/** + * Validates that limit* has been called with the correct combination of parameters + */ +function validateLimit(params) { + if (params.hasStart() && + params.hasEnd() && + params.hasLimit() && + !params.hasAnchoredLimit()) { + throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " + + 'limitToFirst() or limitToLast() instead.'); + } +} +/** + * @internal + */ +class ReferenceImpl extends QueryImpl { + /** @hideconstructor */ + constructor(repo, path) { + super(repo, path, new QueryParams(), false); + } + get parent() { + const parentPath = pathParent(this._path); + return parentPath === null + ? null + : new ReferenceImpl(this._repo, parentPath); + } + get root() { + let ref = this; + while (ref.parent !== null) { + ref = ref.parent; + } + return ref; + } +} +/** + * A `DataSnapshot` contains data from a Database location. + * + * Any time you read data from the Database, you receive the data as a + * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach + * with `on()` or `once()`. You can extract the contents of the snapshot as a + * JavaScript object by calling the `val()` method. Alternatively, you can + * traverse into the snapshot by calling `child()` to return child snapshots + * (which you could then call `val()` on). + * + * A `DataSnapshot` is an efficiently generated, immutable copy of the data at + * a Database location. It cannot be modified and will never change (to modify + * data, you always call the `set()` method on a `Reference` directly). + */ +class DataSnapshot { + /** + * @param _node - A SnapshotNode to wrap. + * @param ref - The location this snapshot came from. + * @param _index - The iteration order for this snapshot + * @hideconstructor + */ + constructor(_node, + /** + * The location of this DataSnapshot. + */ + ref, _index) { + this._node = _node; + this.ref = ref; + this._index = _index; + } + /** + * Gets the priority value of the data in this `DataSnapshot`. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data} + * ). + */ + get priority() { + // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY) + return this._node.getPriority().val(); + } + /** + * The key (last part of the path) of the location of this `DataSnapshot`. + * + * The last token in a Database location is considered its key. For example, + * "ada" is the key for the /users/ada/ node. Accessing the key on any + * `DataSnapshot` will return the key for the location that generated it. + * However, accessing the key on the root URL of a Database will return + * `null`. + */ + get key() { + return this.ref.key; + } + /** Returns the number of child properties of this `DataSnapshot`. */ + get size() { + return this._node.numChildren(); + } + /** + * Gets another `DataSnapshot` for the location at the specified relative path. + * + * Passing a relative path to the `child()` method of a DataSnapshot returns + * another `DataSnapshot` for the location at the specified relative path. The + * relative path can either be a simple child name (for example, "ada") or a + * deeper, slash-separated path (for example, "ada/name/first"). If the child + * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot` + * whose value is `null`) is returned. + * + * @param path - A relative path to the location of child data. + */ + child(path) { + const childPath = new Path(path); + const childRef = child(this.ref, path); + return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX); + } + /** + * Returns true if this `DataSnapshot` contains any data. It is slightly more + * efficient than using `snapshot.val() !== null`. + */ + exists() { + return !this._node.isEmpty(); + } + /** + * Exports the entire contents of the DataSnapshot as a JavaScript object. + * + * The `exportVal()` method is similar to `val()`, except priority information + * is included (if available), making it suitable for backing up your data. + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + exportVal() { + return this._node.val(true); + } + /** + * Enumerates the top-level children in the `IteratedDataSnapshot`. + * + * Because of the way JavaScript objects work, the ordering of data in the + * JavaScript object returned by `val()` is not guaranteed to match the + * ordering on the server nor the ordering of `onChildAdded()` events. That is + * where `forEach()` comes in handy. It guarantees the children of a + * `DataSnapshot` will be iterated in their query order. + * + * If no explicit `orderBy*()` method is used, results are returned + * ordered by key (unless priorities are used, in which case, results are + * returned by priority). + * + * @param action - A function that will be called for each child DataSnapshot. + * The callback can return true to cancel further enumeration. + * @returns true if enumeration was canceled due to your callback returning + * true. + */ + forEach(action) { + if (this._node.isLeafNode()) { + return false; + } + const childrenNode = this._node; + // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type... + return !!childrenNode.forEachChild(this._index, (key, node) => { + return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX)); + }); + } + /** + * Returns true if the specified child path has (non-null) data. + * + * @param path - A relative path to the location of a potential child. + * @returns `true` if data exists at the specified child path; else + * `false`. + */ + hasChild(path) { + const childPath = new Path(path); + return !this._node.getChild(childPath).isEmpty(); + } + /** + * Returns whether or not the `DataSnapshot` has any non-`null` child + * properties. + * + * You can use `hasChildren()` to determine if a `DataSnapshot` has any + * children. If it does, you can enumerate them using `forEach()`. If it + * doesn't, then either this snapshot contains a primitive value (which can be + * retrieved with `val()`) or it is empty (in which case, `val()` will return + * `null`). + * + * @returns true if this snapshot has any children; else false. + */ + hasChildren() { + if (this._node.isLeafNode()) { + return false; + } + else { + return !this._node.isEmpty(); + } + } + /** + * Returns a JSON-serializable representation of this object. + */ + toJSON() { + return this.exportVal(); + } + /** + * Extracts a JavaScript value from a `DataSnapshot`. + * + * Depending on the data in a `DataSnapshot`, the `val()` method may return a + * scalar type (string, number, or boolean), an array, or an object. It may + * also return null, indicating that the `DataSnapshot` is empty (contains no + * data). + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + val() { + return this._node.val(); + } +} +/** + * + * Returns a `Reference` representing the location in the Database + * corresponding to the provided path. If no path is provided, the `Reference` + * will point to the root of the Database. + * + * @param db - The database instance to obtain a reference for. + * @param path - Optional path representing the location the returned + * `Reference` will point. If not provided, the returned `Reference` will + * point to the root of the Database. + * @returns If a path is provided, a `Reference` + * pointing to the provided path. Otherwise, a `Reference` pointing to the + * root of the Database. + */ +function ref(db, path) { + db = util.getModularInstance(db); + db._checkNotDeleted('ref'); + return path !== undefined ? child(db._root, path) : db._root; +} +/** + * Returns a `Reference` representing the location in the Database + * corresponding to the provided Firebase URL. + * + * An exception is thrown if the URL is not a valid Firebase Database URL or it + * has a different domain than the current `Database` instance. + * + * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored + * and are not applied to the returned `Reference`. + * + * @param db - The database instance to obtain a reference for. + * @param url - The Firebase URL at which the returned `Reference` will + * point. + * @returns A `Reference` pointing to the provided + * Firebase URL. + */ +function refFromURL(db, url) { + db = util.getModularInstance(db); + db._checkNotDeleted('refFromURL'); + const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin); + validateUrl('refFromURL', parsedURL); + const repoInfo = parsedURL.repoInfo; + if (!db._repo.repoInfo_.isCustomHost() && + repoInfo.host !== db._repo.repoInfo_.host) { + fatal('refFromURL' + + ': Host name does not match the current database: ' + + '(found ' + + repoInfo.host + + ' but expected ' + + db._repo.repoInfo_.host + + ')'); + } + return ref(db, parsedURL.path.toString()); +} +/** + * Gets a `Reference` for the location at the specified relative path. + * + * The relative path can either be a simple child name (for example, "ada") or + * a deeper slash-separated path (for example, "ada/name/first"). + * + * @param parent - The parent location. + * @param path - A relative path from this location to the desired child + * location. + * @returns The specified child location. + */ +function child(parent, path) { + parent = util.getModularInstance(parent); + if (pathGetFront(parent._path) === null) { + validateRootPathString('child', 'path', path, false); + } + else { + validatePathString('child', 'path', path, false); + } + return new ReferenceImpl(parent._repo, pathChild(parent._path, path)); +} +/** + * Returns an `OnDisconnect` object - see + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information on how to use it. + * + * @param ref - The reference to add OnDisconnect triggers for. + */ +function onDisconnect(ref) { + ref = util.getModularInstance(ref); + return new OnDisconnect(ref._repo, ref._path); +} +/** + * Generates a new child location using a unique key and returns its + * `Reference`. + * + * This is the most common pattern for adding data to a collection of items. + * + * If you provide a value to `push()`, the value is written to the + * generated location. If you don't pass a value, nothing is written to the + * database and the child remains empty (but you can use the `Reference` + * elsewhere). + * + * The unique keys generated by `push()` are ordered by the current time, so the + * resulting list of items is chronologically sorted. The keys are also + * designed to be unguessable (they contain 72 random bits of entropy). + * + * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}. + * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}. + * + * @param parent - The parent location. + * @param value - Optional value to be written at the generated location. + * @returns Combined `Promise` and `Reference`; resolves when write is complete, + * but can be used immediately as the `Reference` to the child location. + */ +function push(parent, value) { + parent = util.getModularInstance(parent); + validateWritablePath('push', parent._path); + validateFirebaseDataArg('push', value, parent._path, true); + const now = repoServerTime(parent._repo); + const name = nextPushId(now); + // push() returns a ThennableReference whose promise is fulfilled with a + // regular Reference. We use child() to create handles to two different + // references. The first is turned into a ThennableReference below by adding + // then() and catch() methods and is used as the return value of push(). The + // second remains a regular Reference and is used as the fulfilled value of + // the first ThennableReference. + const thenablePushRef = child(parent, name); + const pushRef = child(parent, name); + let promise; + if (value != null) { + promise = set(pushRef, value).then(() => pushRef); + } + else { + promise = Promise.resolve(pushRef); + } + thenablePushRef.then = promise.then.bind(promise); + thenablePushRef.catch = promise.then.bind(promise, undefined); + return thenablePushRef; +} +/** + * Removes the data at this Database location. + * + * Any data at child locations will also be deleted. + * + * The effect of the remove will be visible immediately and the corresponding + * event 'value' will be triggered. Synchronization of the remove to the + * Firebase servers will also be started, and the returned Promise will resolve + * when complete. If provided, the onComplete callback will be called + * asynchronously after synchronization has finished. + * + * @param ref - The location to remove. + * @returns Resolves when remove on server is complete. + */ +function remove(ref) { + validateWritablePath('remove', ref._path); + return set(ref, null); +} +/** + * Writes data to this Database location. + * + * This will overwrite any data at this location and all child locations. + * + * The effect of the write will be visible immediately, and the corresponding + * events ("value", "child_added", etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * Passing `null` for the new value is equivalent to calling `remove()`; namely, + * all data at this location and all child locations will be deleted. + * + * `set()` will remove any priority stored at this location, so if priority is + * meant to be preserved, you need to use `setWithPriority()` instead. + * + * Note that modifying data with `set()` will cancel any pending transactions + * at that location, so extreme care should be taken if mixing `set()` and + * `transaction()` to modify the same data. + * + * A single `set()` will generate a single "value" event at the location where + * the `set()` was performed. + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @returns Resolves when write to server is complete. + */ +function set(ref, value) { + ref = util.getModularInstance(ref); + validateWritablePath('set', ref._path); + validateFirebaseDataArg('set', value, ref._path, false); + const deferred = new util.Deferred(); + repoSetWithPriority(ref._repo, ref._path, value, + /*priority=*/ null, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Sets a priority for the data at this Database location. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +function setPriority(ref, priority) { + ref = util.getModularInstance(ref); + validateWritablePath('setPriority', ref._path); + validatePriority('setPriority', priority, false); + const deferred = new util.Deferred(); + repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Writes data the Database location. Like `set()` but also specifies the + * priority for that data. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +function setWithPriority(ref, value, priority) { + validateWritablePath('setWithPriority', ref._path); + validateFirebaseDataArg('setWithPriority', value, ref._path, false); + validatePriority('setWithPriority', priority, false); + if (ref.key === '.length' || ref.key === '.keys') { + throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.'; + } + const deferred = new util.Deferred(); + repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Writes multiple values to the Database at once. + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, + * "name/first") from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * The effect of the write will be visible immediately, and the corresponding + * events ('value', 'child_added', etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * A single `update()` will generate a single "value" event at the location + * where the `update()` was performed, regardless of how many children were + * modified. + * + * Note that modifying data with `update()` will cancel any pending + * transactions at that location, so extreme care should be taken if mixing + * `update()` and `transaction()` to modify the same data. + * + * Passing `null` to `update()` will remove the data at this location. + * + * See + * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}. + * + * @param ref - The location to write to. + * @param values - Object containing multiple values. + * @returns Resolves when update on server is complete. + */ +function update(ref, values) { + validateFirebaseMergeDataArg('update', values, ref._path, false); + const deferred = new util.Deferred(); + repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Gets the most up-to-date result for this query. + * + * @param query - The query to run. + * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is + * available, or rejects if the client is unable to return a value (e.g., if the + * server is unreachable and there is nothing cached). + */ +function get(query) { + query = util.getModularInstance(query); + const callbackContext = new CallbackContext(() => { }); + const container = new ValueEventRegistration(callbackContext); + return repoGetValue(query._repo, query, container).then(node => { + return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex()); + }); +} +/** + * Represents registration for 'value' events. + */ +class ValueEventRegistration { + constructor(callbackContext) { + this.callbackContext = callbackContext; + } + respondsTo(eventType) { + return eventType === 'value'; + } + createEvent(change, query) { + const index = query._queryParams.getIndex(); + return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index)); + } + getEventRunner(eventData) { + if (eventData.getEventType() === 'cancel') { + return () => this.callbackContext.onCancel(eventData.error); + } + else { + return () => this.callbackContext.onValue(eventData.snapshot, null); + } + } + createCancelEvent(error, path) { + if (this.callbackContext.hasCancelCallback) { + return new CancelEvent(this, error, path); + } + else { + return null; + } + } + matches(other) { + if (!(other instanceof ValueEventRegistration)) { + return false; + } + else if (!other.callbackContext || !this.callbackContext) { + // If no callback specified, we consider it to match any callback. + return true; + } + else { + return other.callbackContext.matches(this.callbackContext); + } + } + hasAnyCallback() { + return this.callbackContext !== null; + } +} +/** + * Represents the registration of a child_x event. + */ +class ChildEventRegistration { + constructor(eventType, callbackContext) { + this.eventType = eventType; + this.callbackContext = callbackContext; + } + respondsTo(eventType) { + let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType; + eventToCheck = + eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck; + return this.eventType === eventToCheck; + } + createCancelEvent(error, path) { + if (this.callbackContext.hasCancelCallback) { + return new CancelEvent(this, error, path); + } + else { + return null; + } + } + createEvent(change, query) { + util.assert(change.childName != null, 'Child events should have a childName.'); + const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName); + const index = query._queryParams.getIndex(); + return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName); + } + getEventRunner(eventData) { + if (eventData.getEventType() === 'cancel') { + return () => this.callbackContext.onCancel(eventData.error); + } + else { + return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName); + } + } + matches(other) { + if (other instanceof ChildEventRegistration) { + return (this.eventType === other.eventType && + (!this.callbackContext || + !other.callbackContext || + this.callbackContext.matches(other.callbackContext))); + } + return false; + } + hasAnyCallback() { + return !!this.callbackContext; + } +} +function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) { + let cancelCallback; + if (typeof cancelCallbackOrListenOptions === 'object') { + cancelCallback = undefined; + options = cancelCallbackOrListenOptions; + } + if (typeof cancelCallbackOrListenOptions === 'function') { + cancelCallback = cancelCallbackOrListenOptions; + } + if (options && options.onlyOnce) { + const userCallback = callback; + const onceCallback = (dataSnapshot, previousChildName) => { + repoRemoveEventCallbackForQuery(query._repo, query, container); + userCallback(dataSnapshot, previousChildName); + }; + onceCallback.userCallback = callback.userCallback; + onceCallback.context = callback.context; + callback = onceCallback; + } + const callbackContext = new CallbackContext(callback, cancelCallback || undefined); + const container = eventType === 'value' + ? new ValueEventRegistration(callbackContext) + : new ChildEventRegistration(eventType, callbackContext); + repoAddEventCallbackForQuery(query._repo, query, container); + return () => repoRemoveEventCallbackForQuery(query._repo, query, container); +} +function onValue(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options); +} +function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options); +} +function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options); +} +function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options); +} +function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options); +} +/** + * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener. + * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from + * the respective `on*` callbacks. + * + * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener + * will not automatically remove listeners registered on child nodes, `off()` + * must also be called on any child listeners to remove the callback. + * + * If a callback is not specified, all callbacks for the specified eventType + * will be removed. Similarly, if no eventType is specified, all callbacks + * for the `Reference` will be removed. + * + * Individual listeners can also be removed by invoking their unsubscribe + * callbacks. + * + * @param query - The query that the listener was registered with. + * @param eventType - One of the following strings: "value", "child_added", + * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks + * for the `Reference` will be removed. + * @param callback - The callback function that was passed to `on()` or + * `undefined` to remove all callbacks. + */ +function off(query, eventType, callback) { + let container = null; + const expCallback = callback ? new CallbackContext(callback) : null; + if (eventType === 'value') { + container = new ValueEventRegistration(expCallback); + } + else if (eventType) { + container = new ChildEventRegistration(eventType, expCallback); + } + repoRemoveEventCallbackForQuery(query._repo, query, container); +} +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Database query. `QueryConstraint`s are created by invoking {@link endAt}, + * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link + * limitToFirst}, {@link limitToLast}, {@link orderByChild}, + * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} , + * {@link orderByValue} or {@link equalTo} and + * can then be passed to {@link query} to create a new query instance that + * also contains this `QueryConstraint`. + */ +class QueryConstraint { +} +class QueryEndAtConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'endAt'; + } + _apply(query) { + validateFirebaseDataArg('endAt', this._value, query._path, true); + const newParams = queryParamsEndAt(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasEnd()) { + throw new Error('endAt: Starting point was already set (by another call to endAt, ' + + 'endBefore or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified ending point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name less than or equal + * to the specified key. + * + * You can read more about `endAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to end at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end at, among the children with the previously + * specified priority. This argument is only allowed if ordering by child, + * value, or priority. + */ +function endAt(value, key) { + validateKey('endAt', 'key', key, true); + return new QueryEndAtConstraint(value, key); +} +class QueryEndBeforeConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'endBefore'; + } + _apply(query) { + validateFirebaseDataArg('endBefore', this._value, query._path, false); + const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasEnd()) { + throw new Error('endBefore: Starting point was already set (by another call to endAt, ' + + 'endBefore or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified ending point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is exclusive. If only a value is provided, children + * with a value less than the specified value will be included in the query. + * If a key is specified, then children must have a value less than or equal + * to the specified value and a key name less than the specified key. + * + * @param value - The value to end before. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end before, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +function endBefore(value, key) { + validateKey('endBefore', 'key', key, true); + return new QueryEndBeforeConstraint(value, key); +} +class QueryStartAtConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'startAt'; + } + _apply(query) { + validateFirebaseDataArg('startAt', this._value, query._path, true); + const newParams = queryParamsStartAt(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasStart()) { + throw new Error('startAt: Starting point was already set (by another call to startAt, ' + + 'startBefore or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified starting point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name greater than or + * equal to the specified key. + * + * You can read more about `startAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to start at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at. This argument is only allowed if + * ordering by child, value, or priority. + */ +function startAt(value = null, key) { + validateKey('startAt', 'key', key, true); + return new QueryStartAtConstraint(value, key); +} +class QueryStartAfterConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'startAfter'; + } + _apply(query) { + validateFirebaseDataArg('startAfter', this._value, query._path, false); + const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasStart()) { + throw new Error('startAfter: Starting point was already set (by another call to startAt, ' + + 'startAfter, or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified starting point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is exclusive. If only a value is provided, children + * with a value greater than the specified value will be included in the query. + * If a key is specified, then children must have a value greater than or equal + * to the specified value and a a key name greater than the specified key. + * + * @param value - The value to start after. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start after. This argument is only allowed if + * ordering by child, value, or priority. + */ +function startAfter(value, key) { + validateKey('startAfter', 'key', key, true); + return new QueryStartAfterConstraint(value, key); +} +class QueryLimitToFirstConstraint extends QueryConstraint { + constructor(_limit) { + super(); + this._limit = _limit; + this.type = 'limitToFirst'; + } + _apply(query) { + if (query._queryParams.hasLimit()) { + throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' + + 'or limitToLast).'); + } + return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled); + } +} +/** + * Creates a new `QueryConstraint` that if limited to the first specific number + * of children. + * + * The `limitToFirst()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the first 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToFirst()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +function limitToFirst(limit) { + if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) { + throw new Error('limitToFirst: First argument must be a positive integer.'); + } + return new QueryLimitToFirstConstraint(limit); +} +class QueryLimitToLastConstraint extends QueryConstraint { + constructor(_limit) { + super(); + this._limit = _limit; + this.type = 'limitToLast'; + } + _apply(query) { + if (query._queryParams.hasLimit()) { + throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' + + 'or limitToLast).'); + } + return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled); + } +} +/** + * Creates a new `QueryConstraint` that is limited to return only the last + * specified number of children. + * + * The `limitToLast()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the last 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToLast()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +function limitToLast(limit) { + if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) { + throw new Error('limitToLast: First argument must be a positive integer.'); + } + return new QueryLimitToLastConstraint(limit); +} +class QueryOrderByChildConstraint extends QueryConstraint { + constructor(_path) { + super(); + this._path = _path; + this.type = 'orderByChild'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByChild'); + const parsedPath = new Path(this._path); + if (pathIsEmpty(parsedPath)) { + throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.'); + } + const index = new PathIndex(parsedPath); + const newParams = queryParamsOrderBy(query._queryParams, index); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by the specified child key. + * + * Queries can only order by one key at a time. Calling `orderByChild()` + * multiple times on the same query is an error. + * + * Firebase queries allow you to order your data by any child key on the fly. + * However, if you know in advance what your indexes will be, you can define + * them via the .indexOn rule in your Security Rules for better performance. See + * the{@link https://firebase.google.com/docs/database/security/indexing-data} + * rule for more information. + * + * You can read more about `orderByChild()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + * + * @param path - The path to order by. + */ +function orderByChild(path) { + if (path === '$key') { + throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.'); + } + else if (path === '$priority') { + throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.'); + } + else if (path === '$value') { + throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.'); + } + validatePathString('orderByChild', 'path', path, false); + return new QueryOrderByChildConstraint(path); +} +class QueryOrderByKeyConstraint extends QueryConstraint { + constructor() { + super(...arguments); + this.type = 'orderByKey'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByKey'); + const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by the key. + * + * Sorts the results of a query by their (ascending) key values. + * + * You can read more about `orderByKey()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +function orderByKey() { + return new QueryOrderByKeyConstraint(); +} +class QueryOrderByPriorityConstraint extends QueryConstraint { + constructor() { + super(...arguments); + this.type = 'orderByPriority'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByPriority'); + const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by priority. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data} + * for alternatives to priority. + */ +function orderByPriority() { + return new QueryOrderByPriorityConstraint(); +} +class QueryOrderByValueConstraint extends QueryConstraint { + constructor() { + super(...arguments); + this.type = 'orderByValue'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByValue'); + const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by value. + * + * If the children of a query are all scalar values (string, number, or + * boolean), you can order the results by their (ascending) values. + * + * You can read more about `orderByValue()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +function orderByValue() { + return new QueryOrderByValueConstraint(); +} +class QueryEqualToValueConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'equalTo'; + } + _apply(query) { + validateFirebaseDataArg('equalTo', this._value, query._path, false); + if (query._queryParams.hasStart()) { + throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' + + 'equalTo).'); + } + if (query._queryParams.hasEnd()) { + throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' + + 'equalTo).'); + } + return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query)); + } +} +/** + * Creates a `QueryConstraint` that includes children that match the specified + * value. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The optional key argument can be used to further limit the range of the + * query. If it is specified, then children that have exactly the specified + * value must also have exactly the specified key as their key name. This can be + * used to filter result sets with many matches for the same value. + * + * You can read more about `equalTo()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to match for. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +function equalTo(value, key) { + validateKey('equalTo', 'key', key, true); + return new QueryEqualToValueConstraint(value, key); +} +/** + * Creates a new immutable instance of `Query` that is extended to also include + * additional query constraints. + * + * @param query - The Query instance to use as a base for the new constraints. + * @param queryConstraints - The list of `QueryConstraint`s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +function query(query, ...queryConstraints) { + let queryImpl = util.getModularInstance(query); + for (const constraint of queryConstraints) { + queryImpl = constraint._apply(queryImpl); + } + return queryImpl; +} +/** + * Define reference constructor in various modules + * + * We are doing this here to avoid several circular + * dependency issues + */ +syncPointSetReferenceConstructor(ReferenceImpl); +syncTreeSetReferenceConstructor(ReferenceImpl); + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This variable is also defined in the firebase Node.js Admin SDK. Before + * modifying this definition, consult the definition in: + * + * https://github.com/firebase/firebase-admin-node + * + * and make sure the two are consistent. + */ +const FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST'; +/** + * Creates and caches `Repo` instances. + */ +const repos = {}; +/** + * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes). + */ +let useRestClient = false; +/** + * Update an existing `Repo` in place to point to a new host/port. + */ +function repoManagerApplyEmulatorSettings(repo, hostAndPort, emulatorOptions, tokenProvider) { + const portIndex = hostAndPort.lastIndexOf(':'); + const host = hostAndPort.substring(0, portIndex); + const useSsl = util.isCloudWorkstation(host); + repo.repoInfo_ = new RepoInfo(hostAndPort, + /* secure= */ useSsl, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams, + /*isUsingEmulator=*/ true, emulatorOptions); + if (tokenProvider) { + repo.authTokenProvider_ = tokenProvider; + } +} +/** + * This function should only ever be called to CREATE a new database instance. + * @internal + */ +function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) { + let dbUrl = url || app.options.databaseURL; + if (dbUrl === undefined) { + if (!app.options.projectId) { + fatal("Can't determine Firebase Database URL. Be sure to include " + + ' a Project ID when calling firebase.initializeApp().'); + } + log('Using default host for project ', app.options.projectId); + dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`; + } + let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin); + let repoInfo = parsedUrl.repoInfo; + let isEmulator; + let dbEmulatorHost = undefined; + if (typeof process !== 'undefined' && process.env) { + dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR]; + } + if (dbEmulatorHost) { + isEmulator = true; + dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`; + parsedUrl = parseRepoInfo(dbUrl, nodeAdmin); + repoInfo = parsedUrl.repoInfo; + } + else { + isEmulator = !parsedUrl.repoInfo.secure; + } + const authTokenProvider = nodeAdmin && isEmulator + ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER) + : new FirebaseAuthTokenProvider(app.name, app.options, authProvider); + validateUrl('Invalid Firebase Database URL', parsedUrl); + if (!pathIsEmpty(parsedUrl.path)) { + fatal('Database URL must point to the root of a Firebase Database ' + + '(not including a child path).'); + } + const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app, appCheckProvider)); + return new Database(repo, app); +} +/** + * Remove the repo and make sure it is disconnected. + * + */ +function repoManagerDeleteRepo(repo, appName) { + const appRepos = repos[appName]; + // This should never happen... + if (!appRepos || appRepos[repo.key] !== repo) { + fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`); + } + repoInterrupt(repo); + delete appRepos[repo.key]; +} +/** + * Ensures a repo doesn't already exist and then creates one using the + * provided app. + * + * @param repoInfo - The metadata about the Repo + * @returns The Repo object for the specified server / repoName. + */ +function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) { + let appRepos = repos[app.name]; + if (!appRepos) { + appRepos = {}; + repos[app.name] = appRepos; + } + let repo = appRepos[repoInfo.toURLString()]; + if (repo) { + fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.'); + } + repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider); + appRepos[repoInfo.toURLString()] = repo; + return repo; +} +/** + * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos. + */ +function repoManagerForceRestClient(forceRestClient) { + useRestClient = forceRestClient; +} +/** + * Class representing a Firebase Realtime Database. + */ +class Database { + /** @hideconstructor */ + constructor(_repoInternal, + /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */ + app) { + this._repoInternal = _repoInternal; + this.app = app; + /** Represents a `Database` instance. */ + this['type'] = 'database'; + /** Track if the instance has been used (root or repo accessed) */ + this._instanceStarted = false; + } + get _repo() { + if (!this._instanceStarted) { + repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']); + this._instanceStarted = true; + } + return this._repoInternal; + } + get _root() { + if (!this._rootInternal) { + this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath()); + } + return this._rootInternal; + } + _delete() { + if (this._rootInternal !== null) { + repoManagerDeleteRepo(this._repo, this.app.name); + this._repoInternal = null; + this._rootInternal = null; + } + return Promise.resolve(); + } + _checkNotDeleted(apiName) { + if (this._rootInternal === null) { + fatal('Cannot call ' + apiName + ' on a deleted database.'); + } + } +} +function checkTransportInit() { + if (TransportManager.IS_TRANSPORT_INITIALIZED) { + warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener'); + } +} +/** + * Force the use of websockets instead of longPolling. + */ +function forceWebSockets() { + checkTransportInit(); + BrowserPollConnection.forceDisallow(); +} +/** + * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL. + */ +function forceLongPolling() { + checkTransportInit(); + WebSocketConnection.forceDisallow(); + BrowserPollConnection.forceAllow(); +} +/** + * Returns the instance of the Realtime Database SDK that is associated with the provided + * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if + * no instance exists or if the existing instance uses a custom database URL. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime + * Database instance is associated with. + * @param url - The URL of the Realtime Database instance to connect to. If not + * provided, the SDK connects to the default instance of the Firebase App. + * @returns The `Database` instance of the provided app. + */ +function getDatabase(app$1 = app.getApp(), url) { + const db = app._getProvider(app$1, 'database').getImmediate({ + identifier: url + }); + if (!db._instanceStarted) { + const emulator = util.getDefaultEmulatorHostnameAndPort('database'); + if (emulator) { + connectDatabaseEmulator(db, ...emulator); + } + } + return db; +} +/** + * Modify the provided instance to communicate with the Realtime Database + * emulator. + * + *

Note: This method must be called before performing any other operation. + * + * @param db - The instance to modify. + * @param host - The emulator host (ex: localhost) + * @param port - The emulator port (ex: 8080) + * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules + */ +function connectDatabaseEmulator(db, host, port, options = {}) { + db = util.getModularInstance(db); + db._checkNotDeleted('useEmulator'); + const hostAndPort = `${host}:${port}`; + const repo = db._repoInternal; + if (db._instanceStarted) { + // If the instance has already been started, then silenty fail if this function is called again + // with the same parameters. If the parameters differ then assert. + if (hostAndPort === db._repoInternal.repoInfo_.host && + util.deepEqual(options, repo.repoInfo_.emulatorOptions)) { + return; + } + fatal('connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.'); + } + let tokenProvider = undefined; + if (repo.repoInfo_.nodeAdmin) { + if (options.mockUserToken) { + fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'); + } + tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER); + } + else if (options.mockUserToken) { + const token = typeof options.mockUserToken === 'string' + ? options.mockUserToken + : util.createMockUserToken(options.mockUserToken, db.app.options.projectId); + tokenProvider = new EmulatorTokenProvider(token); + } + // Workaround to get cookies in Firebase Studio + if (util.isCloudWorkstation(host)) { + void util.pingServer(host); + util.updateEmulatorBanner('Database', true); + } + // Modify the repo to apply emulator settings + repoManagerApplyEmulatorSettings(repo, hostAndPort, options, tokenProvider); +} +/** + * Disconnects from the server (all Database operations will be completed + * offline). + * + * The client automatically maintains a persistent connection to the Database + * server, which will remain active indefinitely and reconnect when + * disconnected. However, the `goOffline()` and `goOnline()` methods may be used + * to control the client connection in cases where a persistent connection is + * undesirable. + * + * While offline, the client will no longer receive data updates from the + * Database. However, all Database operations performed locally will continue to + * immediately fire events, allowing your application to continue behaving + * normally. Additionally, each operation performed locally will automatically + * be queued and retried upon reconnection to the Database server. + * + * To reconnect to the Database and begin receiving remote events, see + * `goOnline()`. + * + * @param db - The instance to disconnect. + */ +function goOffline(db) { + db = util.getModularInstance(db); + db._checkNotDeleted('goOffline'); + repoInterrupt(db._repo); +} +/** + * Reconnects to the server and synchronizes the offline Database state + * with the server state. + * + * This method should be used after disabling the active connection with + * `goOffline()`. Once reconnected, the client will transmit the proper data + * and fire the appropriate events so that your client "catches up" + * automatically. + * + * @param db - The instance to reconnect. + */ +function goOnline(db) { + db = util.getModularInstance(db); + db._checkNotDeleted('goOnline'); + repoResume(db._repo); +} +function enableLogging(logger, persistent) { + enableLogging$1(logger, persistent); +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function registerDatabase(variant) { + setSDKVersion(app.SDK_VERSION); + app._registerComponent(new component.Component('database', (container, { instanceIdentifier: url }) => { + const app = container.getProvider('app').getImmediate(); + const authProvider = container.getProvider('auth-internal'); + const appCheckProvider = container.getProvider('app-check-internal'); + return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url); + }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true)); + app.registerVersion(name, version, variant); + // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation + app.registerVersion(name, version, 'cjs2020'); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const SERVER_TIMESTAMP = { + '.sv': 'timestamp' +}; +/** + * Returns a placeholder value for auto-populating the current timestamp (time + * since the Unix epoch, in milliseconds) as determined by the Firebase + * servers. + */ +function serverTimestamp() { + return SERVER_TIMESTAMP; +} +/** + * Returns a placeholder value that can be used to atomically increment the + * current database value by the provided delta. + * + * @param delta - the amount to modify the current value atomically. + * @returns A placeholder value for modifying data atomically server-side. + */ +function increment(delta) { + return { + '.sv': { + 'increment': delta + } + }; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A type for the resolve value of {@link runTransaction}. + */ +class TransactionResult { + /** @hideconstructor */ + constructor( + /** Whether the transaction was successfully committed. */ + committed, + /** The resulting data snapshot. */ + snapshot) { + this.committed = committed; + this.snapshot = snapshot; + } + /** Returns a JSON-serializable representation of this object. */ + toJSON() { + return { committed: this.committed, snapshot: this.snapshot.toJSON() }; + } +} +/** + * Atomically modifies the data at this location. + * + * Atomically modify the data at this location. Unlike a normal `set()`, which + * just overwrites the data regardless of its previous value, `runTransaction()` is + * used to modify the existing value to a new value, ensuring there are no + * conflicts with other clients writing to the same location at the same time. + * + * To accomplish this, you pass `runTransaction()` an update function which is + * used to transform the current value into a new value. If another client + * writes to the location before your new value is successfully written, your + * update function will be called again with the new current value, and the + * write will be retried. This will happen repeatedly until your write succeeds + * without conflict or you abort the transaction by not returning a value from + * your update function. + * + * Note: Modifying data with `set()` will cancel any pending transactions at + * that location, so extreme care should be taken if mixing `set()` and + * `runTransaction()` to update the same data. + * + * Note: When using transactions with Security and Firebase Rules in place, be + * aware that a client needs `.read` access in addition to `.write` access in + * order to perform a transaction. This is because the client-side nature of + * transactions requires the client to read the data in order to transactionally + * update it. + * + * @param ref - The location to atomically modify. + * @param transactionUpdate - A developer-supplied function which will be passed + * the current data stored at this location (as a JavaScript object). The + * function should return the new value it would like written (as a JavaScript + * object). If `undefined` is returned (i.e. you return with no arguments) the + * transaction will be aborted and the data at this location will not be + * modified. + * @param options - An options object to configure transactions. + * @returns A `Promise` that can optionally be used instead of the `onComplete` + * callback to handle success and failure. + */ +function runTransaction(ref, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +transactionUpdate, options) { + ref = util.getModularInstance(ref); + validateWritablePath('Reference.transaction', ref._path); + if (ref.key === '.length' || ref.key === '.keys') { + throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.'); + } + const applyLocally = options?.applyLocally ?? true; + const deferred = new util.Deferred(); + const promiseComplete = (error, committed, node) => { + let dataSnapshot = null; + if (error) { + deferred.reject(error); + } + else { + dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX); + deferred.resolve(new TransactionResult(committed, dataSnapshot)); + } + }; + // Add a watch to make sure we get server updates. + const unwatcher = onValue(ref, () => { }); + repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally); + return deferred.promise; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +PersistentConnection; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +PersistentConnection.prototype.simpleListen = function (pathString, onComplete) { + this.sendRequest('q', { p: pathString }, onComplete); +}; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +PersistentConnection.prototype.echo = function (data, onEcho) { + this.sendRequest('echo', { d: data }, onEcho); +}; +// RealTimeConnection properties that we use in tests. +Connection; +/** + * @internal + */ +const hijackHash = function (newHash) { + const oldPut = PersistentConnection.prototype.put; + PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) { + if (hash !== undefined) { + hash = newHash(); + } + oldPut.call(this, pathString, data, onComplete, hash); + }; + return function () { + PersistentConnection.prototype.put = oldPut; + }; +}; +RepoInfo; +/** + * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection. + * @internal + */ +const forceRestClient = function (forceRestClient) { + repoManagerForceRestClient(forceRestClient); +}; + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Used by console to create a database based on the app, + * passed database URL and a custom auth implementation. + * @internal + * @param app - A valid FirebaseApp-like object + * @param url - A valid Firebase databaseURL + * @param version - custom version e.g. firebase-admin version + * @param customAppCheckImpl - custom app check implementation + * @param customAuthImpl - custom auth implementation + */ +function _initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, nodeAdmin = false }) { + setSDKVersion(version); + /** + * ComponentContainer('database-standalone') is just a placeholder that doesn't perform + * any actual function. + */ + const componentContainer = new component.ComponentContainer('database-standalone'); + const authProvider = new component.Provider('auth-internal', componentContainer); + let appCheckProvider; + if (customAppCheckImpl) { + appCheckProvider = new component.Provider('app-check-internal', componentContainer); + appCheckProvider.setComponent(new component.Component('app-check-internal', () => customAppCheckImpl, "PRIVATE" /* ComponentType.PRIVATE */)); + } + authProvider.setComponent(new component.Component('auth-internal', () => customAuthImpl, "PRIVATE" /* ComponentType.PRIVATE */)); + return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin); +} + +/** + * Firebase Realtime Database + * + * @packageDocumentation + */ +registerDatabase(); + +exports.DataSnapshot = DataSnapshot; +exports.Database = Database; +exports.OnDisconnect = OnDisconnect; +exports.QueryConstraint = QueryConstraint; +exports.TransactionResult = TransactionResult; +exports._QueryImpl = QueryImpl; +exports._QueryParams = QueryParams; +exports._ReferenceImpl = ReferenceImpl; +exports._TEST_ACCESS_forceRestClient = forceRestClient; +exports._TEST_ACCESS_hijackHash = hijackHash; +exports._initStandalone = _initStandalone; +exports._repoManagerDatabaseFromApp = repoManagerDatabaseFromApp; +exports._setSDKVersion = setSDKVersion; +exports._validatePathString = validatePathString; +exports._validateWritablePath = validateWritablePath; +exports.child = child; +exports.connectDatabaseEmulator = connectDatabaseEmulator; +exports.enableLogging = enableLogging; +exports.endAt = endAt; +exports.endBefore = endBefore; +exports.equalTo = equalTo; +exports.forceLongPolling = forceLongPolling; +exports.forceWebSockets = forceWebSockets; +exports.get = get; +exports.getDatabase = getDatabase; +exports.goOffline = goOffline; +exports.goOnline = goOnline; +exports.increment = increment; +exports.limitToFirst = limitToFirst; +exports.limitToLast = limitToLast; +exports.off = off; +exports.onChildAdded = onChildAdded; +exports.onChildChanged = onChildChanged; +exports.onChildMoved = onChildMoved; +exports.onChildRemoved = onChildRemoved; +exports.onDisconnect = onDisconnect; +exports.onValue = onValue; +exports.orderByChild = orderByChild; +exports.orderByKey = orderByKey; +exports.orderByPriority = orderByPriority; +exports.orderByValue = orderByValue; +exports.push = push; +exports.query = query; +exports.ref = ref; +exports.refFromURL = refFromURL; +exports.remove = remove; +exports.runTransaction = runTransaction; +exports.serverTimestamp = serverTimestamp; +exports.set = set; +exports.setPriority = setPriority; +exports.setWithPriority = setWithPriority; +exports.startAfter = startAfter; +exports.startAt = startAt; +exports.update = update; +//# sourceMappingURL=index.cjs.js.map diff --git a/node_modules/@firebase/database/dist/index.cjs.js.map b/node_modules/@firebase/database/dist/index.cjs.js.map new file mode 100644 index 0000000..0a12e91 --- /dev/null +++ b/node_modules/@firebase/database/dist/index.cjs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.cjs.js","sources":["../src/core/version.ts","../src/core/storage/DOMStorageWrapper.ts","../src/core/storage/MemoryStorage.ts","../src/core/storage/storage.ts","../src/core/util/util.ts","../src/core/AppCheckTokenProvider.ts","../src/core/AuthTokenProvider.ts","../src/realtime/Constants.ts","../src/core/RepoInfo.ts","../src/core/stats/StatsCollection.ts","../src/core/stats/StatsManager.ts","../src/realtime/polling/PacketReceiver.ts","../src/realtime/BrowserPollConnection.ts","../src/realtime/WebSocketConnection.ts","../src/realtime/TransportManager.ts","../src/realtime/Connection.ts","../src/core/ServerActions.ts","../src/core/util/EventEmitter.ts","../src/core/util/OnlineMonitor.ts","../src/core/util/Path.ts","../src/core/util/VisibilityMonitor.ts","../src/core/PersistentConnection.ts","../src/core/snap/Node.ts","../src/core/snap/indexes/Index.ts","../src/core/snap/indexes/KeyIndex.ts","../src/core/util/SortedMap.ts","../src/core/snap/comparators.ts","../src/core/snap/snap.ts","../src/core/snap/LeafNode.ts","../src/core/snap/indexes/PriorityIndex.ts","../src/core/snap/childSet.ts","../src/core/snap/IndexMap.ts","../src/core/snap/ChildrenNode.ts","../src/core/snap/nodeFromJSON.ts","../src/core/snap/indexes/PathIndex.ts","../src/core/snap/indexes/ValueIndex.ts","../src/core/view/Change.ts","../src/core/view/filter/IndexedFilter.ts","../src/core/view/filter/RangedFilter.ts","../src/core/view/filter/LimitedFilter.ts","../src/core/view/QueryParams.ts","../src/core/ReadonlyRestClient.ts","../src/core/SnapshotHolder.ts","../src/core/SparseSnapshotTree.ts","../src/core/stats/StatsListener.ts","../src/core/stats/StatsReporter.ts","../src/core/operation/Operation.ts","../src/core/operation/AckUserWrite.ts","../src/core/operation/ListenComplete.ts","../src/core/operation/Overwrite.ts","../src/core/operation/Merge.ts","../src/core/view/CacheNode.ts","../src/core/view/EventGenerator.ts","../src/core/view/ViewCache.ts","../src/core/util/ImmutableTree.ts","../src/core/CompoundWrite.ts","../src/core/WriteTree.ts","../src/core/view/ChildChangeAccumulator.ts","../src/core/view/CompleteChildSource.ts","../src/core/view/ViewProcessor.ts","../src/core/view/View.ts","../src/core/SyncPoint.ts","../src/core/SyncTree.ts","../src/core/util/ServerValues.ts","../src/core/util/Tree.ts","../src/core/util/validation.ts","../src/core/view/EventQueue.ts","../src/core/Repo.ts","../src/core/util/libs/parser.ts","../src/core/util/NextPushId.ts","../src/core/view/Event.ts","../src/core/view/EventRegistration.ts","../src/api/OnDisconnect.ts","../src/api/Reference_impl.ts","../src/api/Database.ts","../src/register.ts","../src/api/ServerValue.ts","../src/api/Transaction.ts","../src/api/test_access.ts","../src/internal/index.ts","../src/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nexport let SDK_VERSION = '';\n\n/**\n * SDK_VERSION should be set before any database instance is created\n * @internal\n */\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { jsonEval, stringify } from '@firebase/util';\n\n/**\n * Wraps a DOM Storage object and:\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\n *\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\n * and one for localStorage.\n *\n */\nexport class DOMStorageWrapper {\n // Use a prefix to avoid collisions with other stuff saved by the app.\n private prefix_ = 'firebase:';\n\n /**\n * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)\n */\n constructor(private domStorage_: Storage) {}\n\n /**\n * @param key - The key to save the value under\n * @param value - The value being stored, or null to remove the key.\n */\n set(key: string, value: unknown | null) {\n if (value == null) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n } else {\n this.domStorage_.setItem(this.prefixedName_(key), stringify(value));\n }\n }\n\n /**\n * @returns The value that was stored under this key, or null\n */\n get(key: string): unknown {\n const storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n if (storedVal == null) {\n return null;\n } else {\n return jsonEval(storedVal);\n }\n }\n\n remove(key: string) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n\n isInMemoryStorage: boolean;\n\n prefixedName_(name: string): string {\n return this.prefix_ + name;\n }\n\n toString(): string {\n return this.domStorage_.toString();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains } from '@firebase/util';\n\n/**\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\n * (TODO: create interface for both to implement).\n */\nexport class MemoryStorage {\n private cache_: { [k: string]: unknown } = {};\n\n set(key: string, value: unknown | null) {\n if (value == null) {\n delete this.cache_[key];\n } else {\n this.cache_[key] = value;\n }\n }\n\n get(key: string): unknown {\n if (contains(this.cache_, key)) {\n return this.cache_[key];\n }\n return null;\n }\n\n remove(key: string) {\n delete this.cache_[key];\n }\n\n isInMemoryStorage = true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DOMStorageWrapper } from './DOMStorageWrapper';\nimport { MemoryStorage } from './MemoryStorage';\n\ndeclare const window: Window;\n\n/**\n * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\n * to reflect this type\n *\n * @param domStorageName - Name of the underlying storage object\n * (e.g. 'localStorage' or 'sessionStorage').\n * @returns Turning off type information until a common interface is defined.\n */\nconst createStoragefor = function (\n domStorageName: string\n): DOMStorageWrapper | MemoryStorage {\n try {\n // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\n // so it must be inside the try/catch.\n if (\n typeof window !== 'undefined' &&\n typeof window[domStorageName] !== 'undefined'\n ) {\n // Need to test cache. Just because it's here doesn't mean it works\n const domStorage = window[domStorageName];\n domStorage.setItem('firebase:sentinel', 'cache');\n domStorage.removeItem('firebase:sentinel');\n return new DOMStorageWrapper(domStorage);\n }\n } catch (e) {}\n\n // Failed to create wrapper. Just return in-memory storage.\n // TODO: log?\n return new MemoryStorage();\n};\n\n/** A storage object that lasts across sessions */\nexport const PersistentStorage = createStoragefor('localStorage');\n\n/** A storage object that only lasts one session */\nexport const SessionStorage = createStoragefor('sessionStorage');\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel } from '@firebase/logger';\nimport {\n assert,\n base64,\n Sha1,\n stringToByteArray,\n stringify,\n isNodeSdk\n} from '@firebase/util';\n\nimport { SessionStorage } from '../storage/storage';\nimport { QueryContext } from '../view/EventRegistration';\n\ndeclare const window: Window;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ndeclare const Windows: any;\n\nconst logClient = new Logger('@firebase/database');\n\n/**\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\n */\nexport const LUIDGenerator: () => number = (function () {\n let id = 1;\n return function () {\n return id++;\n };\n})();\n\n/**\n * Sha1 hash of the input string\n * @param str - The string to hash\n * @returns {!string} The resulting hash\n */\nexport const sha1 = function (str: string): string {\n const utf8Bytes = stringToByteArray(str);\n const sha1 = new Sha1();\n sha1.update(utf8Bytes);\n const sha1Bytes = sha1.digest();\n return base64.encodeByteArray(sha1Bytes);\n};\n\nconst buildLogMessage_ = function (...varArgs: unknown[]): string {\n let message = '';\n for (let i = 0; i < varArgs.length; i++) {\n const arg = varArgs[i];\n if (\n Array.isArray(arg) ||\n (arg &&\n typeof arg === 'object' &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (arg as any).length === 'number')\n ) {\n message += buildLogMessage_.apply(null, arg);\n } else if (typeof arg === 'object') {\n message += stringify(arg);\n } else {\n message += arg;\n }\n message += ' ';\n }\n\n return message;\n};\n\n/**\n * Use this for all debug messages in Firebase.\n */\nexport let logger: ((a: string) => void) | null = null;\n\n/**\n * Flag to check for log availability on first log message\n */\nlet firstLog_ = true;\n\n/**\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\n * @param logger_ - A flag to turn on logging, or a custom logger\n * @param persistent - Whether or not to persist logging settings across refreshes\n */\nexport const enableLogging = function (\n logger_?: boolean | ((a: string) => void) | null,\n persistent?: boolean\n) {\n assert(\n !persistent || logger_ === true || logger_ === false,\n \"Can't turn on custom loggers persistently.\"\n );\n if (logger_ === true) {\n logClient.logLevel = LogLevel.VERBOSE;\n logger = logClient.log.bind(logClient);\n if (persistent) {\n SessionStorage.set('logging_enabled', true);\n }\n } else if (typeof logger_ === 'function') {\n logger = logger_;\n } else {\n logger = null;\n SessionStorage.remove('logging_enabled');\n }\n};\n\nexport const log = function (...varArgs: unknown[]) {\n if (firstLog_ === true) {\n firstLog_ = false;\n if (logger === null && SessionStorage.get('logging_enabled') === true) {\n enableLogging(true);\n }\n }\n\n if (logger) {\n const message = buildLogMessage_.apply(null, varArgs);\n logger(message);\n }\n};\n\nexport const logWrapper = function (\n prefix: string\n): (...varArgs: unknown[]) => void {\n return function (...varArgs: unknown[]) {\n log(prefix, ...varArgs);\n };\n};\n\nexport const error = function (...varArgs: string[]) {\n const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);\n logClient.error(message);\n};\n\nexport const fatal = function (...varArgs: string[]) {\n const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;\n logClient.error(message);\n throw new Error(message);\n};\n\nexport const warn = function (...varArgs: unknown[]) {\n const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);\n logClient.warn(message);\n};\n\n/**\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\n * does not use https.\n */\nexport const warnIfPageIsSecure = function () {\n // Be very careful accessing browser globals. Who knows what may or may not exist.\n if (\n typeof window !== 'undefined' &&\n window.location &&\n window.location.protocol &&\n window.location.protocol.indexOf('https:') !== -1\n ) {\n warn(\n 'Insecure Firebase access from a secure page. ' +\n 'Please use https in calls to new Firebase().'\n );\n }\n};\n\nexport const warnAboutUnsupportedMethod = function (methodName: string) {\n warn(\n methodName +\n ' is unsupported and will likely change soon. ' +\n 'Please do not use.'\n );\n};\n\n/**\n * Returns true if data is NaN, or +/- Infinity.\n */\nexport const isInvalidJSONNumber = function (data: unknown): boolean {\n return (\n typeof data === 'number' &&\n (data !== data || // NaN\n data === Number.POSITIVE_INFINITY ||\n data === Number.NEGATIVE_INFINITY)\n );\n};\n\nexport const executeWhenDOMReady = function (fn: () => void) {\n if (isNodeSdk() || document.readyState === 'complete') {\n fn();\n } else {\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\n // fire before onload), but fall back to onload.\n\n let called = false;\n const wrappedFn = function () {\n if (!document.body) {\n setTimeout(wrappedFn, Math.floor(10));\n return;\n }\n\n if (!called) {\n called = true;\n fn();\n }\n };\n\n if (document.addEventListener) {\n document.addEventListener('DOMContentLoaded', wrappedFn, false);\n // fallback to onload.\n window.addEventListener('load', wrappedFn, false);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else if ((document as any).attachEvent) {\n // IE.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (document as any).attachEvent('onreadystatechange', () => {\n if (document.readyState === 'complete') {\n wrappedFn();\n }\n });\n // fallback to onload.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (window as any).attachEvent('onload', wrappedFn);\n\n // jQuery has an extra hack for IE that we could employ (based on\n // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\n // I'm hoping we don't need it.\n }\n }\n};\n\n/**\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\n */\nexport const MIN_NAME = '[MIN_NAME]';\n\n/**\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\n */\nexport const MAX_NAME = '[MAX_NAME]';\n\n/**\n * Compares valid Firebase key names, plus min and max name\n */\nexport const nameCompare = function (a: string, b: string): number {\n if (a === b) {\n return 0;\n } else if (a === MIN_NAME || b === MAX_NAME) {\n return -1;\n } else if (b === MIN_NAME || a === MAX_NAME) {\n return 1;\n } else {\n const aAsInt = tryParseInt(a),\n bAsInt = tryParseInt(b);\n\n if (aAsInt !== null) {\n if (bAsInt !== null) {\n return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;\n } else {\n return -1;\n }\n } else if (bAsInt !== null) {\n return 1;\n } else {\n return a < b ? -1 : 1;\n }\n }\n};\n\n/**\n * @returns {!number} comparison result.\n */\nexport const stringCompare = function (a: string, b: string): number {\n if (a === b) {\n return 0;\n } else if (a < b) {\n return -1;\n } else {\n return 1;\n }\n};\n\nexport const requireKey = function (\n key: string,\n obj: { [k: string]: unknown }\n): unknown {\n if (obj && key in obj) {\n return obj[key];\n } else {\n throw new Error(\n 'Missing required key (' + key + ') in object: ' + stringify(obj)\n );\n }\n};\n\nexport const ObjectToUniqueKey = function (obj: unknown): string {\n if (typeof obj !== 'object' || obj === null) {\n return stringify(obj);\n }\n\n const keys = [];\n // eslint-disable-next-line guard-for-in\n for (const k in obj) {\n keys.push(k);\n }\n\n // Export as json, but with the keys sorted.\n keys.sort();\n let key = '{';\n for (let i = 0; i < keys.length; i++) {\n if (i !== 0) {\n key += ',';\n }\n key += stringify(keys[i]);\n key += ':';\n key += ObjectToUniqueKey(obj[keys[i]]);\n }\n\n key += '}';\n return key;\n};\n\n/**\n * Splits a string into a number of smaller segments of maximum size\n * @param str - The string\n * @param segsize - The maximum number of chars in the string.\n * @returns The string, split into appropriately-sized chunks\n */\nexport const splitStringBySize = function (\n str: string,\n segsize: number\n): string[] {\n const len = str.length;\n\n if (len <= segsize) {\n return [str];\n }\n\n const dataSegs = [];\n for (let c = 0; c < len; c += segsize) {\n if (c + segsize > len) {\n dataSegs.push(str.substring(c, len));\n } else {\n dataSegs.push(str.substring(c, c + segsize));\n }\n }\n return dataSegs;\n};\n\n/**\n * Apply a function to each (key, value) pair in an object or\n * apply a function to each (index, value) pair in an array\n * @param obj - The object or array to iterate over\n * @param fn - The function to apply\n */\nexport function each(obj: object, fn: (k: string, v: unknown) => void) {\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n fn(key, obj[key]);\n }\n }\n}\n\n/**\n * Like goog.bind, but doesn't bother to create a closure if opt_context is null/undefined.\n * @param callback - Callback function.\n * @param context - Optional context to bind to.\n *\n */\nexport const bindCallback = function (\n callback: (a: unknown) => void,\n context?: object | null\n): (a: unknown) => void {\n return context ? callback.bind(context) : callback;\n};\n\n/**\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\n * I made one modification at the end and removed the NaN / Infinity\n * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.\n * @param v - A double\n *\n */\nexport const doubleToIEEE754String = function (v: number): string {\n assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\n\n const ebits = 11,\n fbits = 52;\n const bias = (1 << (ebits - 1)) - 1;\n let s, e, f, ln, i;\n\n // Compute sign, exponent, fraction\n // Skip NaN / Infinity handling --MJL.\n if (v === 0) {\n e = 0;\n f = 0;\n s = 1 / v === -Infinity ? 1 : 0;\n } else {\n s = v < 0;\n v = Math.abs(v);\n\n if (v >= Math.pow(2, 1 - bias)) {\n // Normalized\n ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\n e = ln + bias;\n f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\n } else {\n // Denormalized\n e = 0;\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\n }\n }\n\n // Pack sign, exponent, fraction\n const bits = [];\n for (i = fbits; i; i -= 1) {\n bits.push(f % 2 ? 1 : 0);\n f = Math.floor(f / 2);\n }\n for (i = ebits; i; i -= 1) {\n bits.push(e % 2 ? 1 : 0);\n e = Math.floor(e / 2);\n }\n bits.push(s ? 1 : 0);\n bits.reverse();\n const str = bits.join('');\n\n // Return the data as a hex string. --MJL\n let hexByteString = '';\n for (i = 0; i < 64; i += 8) {\n let hexByte = parseInt(str.substr(i, 8), 2).toString(16);\n if (hexByte.length === 1) {\n hexByte = '0' + hexByte;\n }\n hexByteString = hexByteString + hexByte;\n }\n return hexByteString.toLowerCase();\n};\n\n/**\n * Used to detect if we're in a Chrome content script (which executes in an\n * isolated environment where long-polling doesn't work).\n */\nexport const isChromeExtensionContentScript = function (): boolean {\n return !!(\n typeof window === 'object' &&\n window['chrome'] &&\n window['chrome']['extension'] &&\n !/^chrome/.test(window.location.href)\n );\n};\n\n/**\n * Used to detect if we're in a Windows 8 Store app.\n */\nexport const isWindowsStoreApp = function (): boolean {\n // Check for the presence of a couple WinRT globals\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\n};\n\n/**\n * Converts a server error code to a JavaScript Error\n */\nexport function errorForServerCode(code: string, query: QueryContext): Error {\n let reason = 'Unknown Error';\n if (code === 'too_big') {\n reason =\n 'The data requested exceeds the maximum size ' +\n 'that can be accessed with a single request.';\n } else if (code === 'permission_denied') {\n reason = \"Client doesn't have permission to access the desired data.\";\n } else if (code === 'unavailable') {\n reason = 'The service is unavailable';\n }\n\n const error = new Error(\n code + ' at ' + query._path.toString() + ': ' + reason\n );\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (error as any).code = code.toUpperCase();\n return error;\n}\n\n/**\n * Used to test for integer-looking strings\n */\nexport const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\\\d{1,10}$');\n\n/**\n * For use in keys, the minimum possible 32-bit integer.\n */\nexport const INTEGER_32_MIN = -2147483648;\n\n/**\n * For use in keys, the maximum possible 32-bit integer.\n */\nexport const INTEGER_32_MAX = 2147483647;\n\n/**\n * If the string contains a 32-bit integer, return it. Else return null.\n */\nexport const tryParseInt = function (str: string): number | null {\n if (INTEGER_REGEXP_.test(str)) {\n const intVal = Number(str);\n if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {\n return intVal;\n }\n }\n return null;\n};\n\n/**\n * Helper to run some code but catch any exceptions and re-throw them later.\n * Useful for preventing user callbacks from breaking internal code.\n *\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\n * convenient (we don't have to try to figure out when is a safe point to\n * re-throw it), and the behavior seems reasonable:\n *\n * * If you aren't pausing on exceptions, you get an error in the console with\n * the correct stack trace.\n * * If you're pausing on all exceptions, the debugger will pause on your\n * exception and then again when we rethrow it.\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\n * on us re-throwing it.\n *\n * @param fn - The code to guard.\n */\nexport const exceptionGuard = function (fn: () => void) {\n try {\n fn();\n } catch (e) {\n // Re-throw exception when it's safe.\n setTimeout(() => {\n // It used to be that \"throw e\" would result in a good console error with\n // relevant context, but as of Chrome 39, you just get the firebase.js\n // file/line number where we re-throw it, which is useless. So we log\n // e.stack explicitly.\n const stack = e.stack || '';\n warn('Exception was thrown by user callback.', stack);\n throw e;\n }, Math.floor(0));\n }\n};\n\n/**\n * Helper function to safely call opt_callback with the specified arguments. It:\n * 1. Turns into a no-op if opt_callback is null or undefined.\n * 2. Wraps the call inside exceptionGuard to prevent exceptions from breaking our state.\n *\n * @param callback - Optional onComplete callback.\n * @param varArgs - Arbitrary args to be passed to opt_onComplete\n */\nexport const callUserCallback = function (\n // eslint-disable-next-line @typescript-eslint/ban-types\n callback?: Function | null,\n ...varArgs: unknown[]\n) {\n if (typeof callback === 'function') {\n exceptionGuard(() => {\n callback(...varArgs);\n });\n }\n};\n\n/**\n * @returns {boolean} true if we think we're currently being crawled.\n */\nexport const beingCrawled = function (): boolean {\n const userAgent =\n (typeof window === 'object' &&\n window['navigator'] &&\n window['navigator']['userAgent']) ||\n '';\n\n // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we\n // believe to support JavaScript/AJAX rendering.\n // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\n // would have seen the page\" is flaky if we don't treat it as a crawler.\n return (\n userAgent.search(\n /googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i\n ) >= 0\n );\n};\n\n/**\n * Export a property of an object using a getter function.\n */\nexport const exportPropGetter = function (\n object: object,\n name: string,\n fnGet: () => unknown\n) {\n Object.defineProperty(object, name, { get: fnGet });\n};\n\n/**\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\n *\n * It is removed with clearTimeout() as normal.\n *\n * @param fn - Function to run.\n * @param time - Milliseconds to wait before running.\n * @returns The setTimeout() return value.\n */\nexport const setTimeoutNonBlocking = function (\n fn: () => void,\n time: number\n): number | object {\n const timeout: number | object = setTimeout(fn, time);\n // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.\n if (\n typeof timeout === 'number' &&\n // @ts-ignore Is only defined in Deno environments.\n typeof Deno !== 'undefined' &&\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\n Deno['unrefTimer']\n ) {\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\n Deno.unrefTimer(timeout);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else if (typeof timeout === 'object' && (timeout as any)['unref']) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (timeout as any)['unref']();\n }\n\n return timeout;\n};\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _isFirebaseServerApp } from '@firebase/app'; // eslint-disable-line import/no-extraneous-dependencies\nimport {\n AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { warn } from './util/util';\n\n/**\n * Abstraction around AppCheck's token fetching capabilities.\n */\nexport class AppCheckTokenProvider {\n private appCheck?: FirebaseAppCheckInternal;\n private serverAppAppCheckToken?: string;\n private appName: string;\n constructor(\n app: FirebaseApp,\n private appCheckProvider?: Provider\n ) {\n this.appName = app.name;\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n this.appCheck = appCheckProvider?.getImmediate({ optional: true });\n if (!this.appCheck) {\n appCheckProvider?.get().then(appCheck => (this.appCheck = appCheck));\n }\n }\n\n getToken(forceRefresh?: boolean): Promise {\n if (this.serverAppAppCheckToken) {\n if (forceRefresh) {\n throw new Error(\n 'Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.'\n );\n }\n return Promise.resolve({ token: this.serverAppAppCheckToken });\n }\n if (!this.appCheck) {\n return new Promise((resolve, reject) => {\n // Support delayed initialization of FirebaseAppCheck. This allows our\n // customers to initialize the RTDB SDK before initializing Firebase\n // AppCheck and ensures that all requests are authenticated if a token\n // becomes available before the timeout below expires.\n setTimeout(() => {\n if (this.appCheck) {\n this.getToken(forceRefresh).then(resolve, reject);\n } else {\n resolve(null);\n }\n }, 0);\n });\n }\n return this.appCheck.getToken(forceRefresh);\n }\n\n addTokenChangeListener(listener: AppCheckTokenListener) {\n this.appCheckProvider\n ?.get()\n .then(appCheck => appCheck.addTokenListener(listener));\n }\n\n notifyForInvalidToken(): void {\n warn(\n `Provided AppCheck credentials for the app named \"${this.appName}\" ` +\n 'are invalid. This usually indicates your app was not initialized correctly.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseAuthTokenData } from '@firebase/app-types/private';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { log, warn } from './util/util';\n\nexport interface AuthTokenProvider {\n getToken(forceRefresh: boolean): Promise;\n addTokenChangeListener(listener: (token: string | null) => void): void;\n removeTokenChangeListener(listener: (token: string | null) => void): void;\n notifyForInvalidToken(): void;\n}\n\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nexport class FirebaseAuthTokenProvider implements AuthTokenProvider {\n private auth_: FirebaseAuthInternal | null = null;\n\n constructor(\n private appName_: string,\n private firebaseOptions_: object,\n private authProvider_: Provider\n ) {\n this.auth_ = authProvider_.getImmediate({ optional: true });\n if (!this.auth_) {\n authProvider_.onInit(auth => (this.auth_ = auth));\n }\n }\n\n getToken(forceRefresh: boolean): Promise {\n if (!this.auth_) {\n return new Promise((resolve, reject) => {\n // Support delayed initialization of FirebaseAuth. This allows our\n // customers to initialize the RTDB SDK before initializing Firebase\n // Auth and ensures that all requests are authenticated if a token\n // becomes available before the timeout below expires.\n setTimeout(() => {\n if (this.auth_) {\n this.getToken(forceRefresh).then(resolve, reject);\n } else {\n resolve(null);\n }\n }, 0);\n });\n }\n\n return this.auth_.getToken(forceRefresh).catch(error => {\n // TODO: Need to figure out all the cases this is raised and whether\n // this makes sense.\n if (error && error.code === 'auth/token-not-initialized') {\n log('Got auth/token-not-initialized error. Treating as null token.');\n return null;\n } else {\n return Promise.reject(error);\n }\n });\n }\n\n addTokenChangeListener(listener: (token: string | null) => void): void {\n // TODO: We might want to wrap the listener and call it with no args to\n // avoid a leaky abstraction, but that makes removing the listener harder.\n if (this.auth_) {\n this.auth_.addAuthTokenListener(listener);\n } else {\n this.authProvider_\n .get()\n .then(auth => auth.addAuthTokenListener(listener));\n }\n }\n\n removeTokenChangeListener(listener: (token: string | null) => void): void {\n this.authProvider_\n .get()\n .then(auth => auth.removeAuthTokenListener(listener));\n }\n\n notifyForInvalidToken(): void {\n let errorMessage =\n 'Provided authentication credentials for the app named \"' +\n this.appName_ +\n '\" are invalid. This usually indicates your app was not ' +\n 'initialized correctly. ';\n if ('credential' in this.firebaseOptions_) {\n errorMessage +=\n 'Make sure the \"credential\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n } else if ('serviceAccount' in this.firebaseOptions_) {\n errorMessage +=\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n } else {\n errorMessage +=\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\n 'initializeApp() match the values provided for your app at ' +\n 'https://console.firebase.google.com/.';\n }\n warn(errorMessage);\n }\n}\n\n/* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */\nexport class EmulatorTokenProvider implements AuthTokenProvider {\n /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */\n static OWNER = 'owner';\n\n constructor(private accessToken: string) {}\n\n getToken(forceRefresh: boolean): Promise {\n return Promise.resolve({\n accessToken: this.accessToken\n });\n }\n\n addTokenChangeListener(listener: (token: string | null) => void): void {\n // Invoke the listener immediately to match the behavior in Firebase Auth\n // (see packages/auth/src/auth.js#L1807)\n listener(this.accessToken);\n }\n\n removeTokenChangeListener(listener: (token: string | null) => void): void {}\n\n notifyForInvalidToken(): void {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const PROTOCOL_VERSION = '5';\n\nexport const VERSION_PARAM = 'v';\n\nexport const TRANSPORT_SESSION_PARAM = 's';\n\nexport const REFERER_PARAM = 'r';\n\nexport const FORGE_REF = 'f';\n\n// Matches console.firebase.google.com, firebase-console-*.corp.google.com and\n// firebase.corp.google.com\nexport const FORGE_DOMAIN_RE =\n /(console\\.firebase|firebase-console-\\w+\\.corp|firebase\\.corp)\\.google\\.com/;\n\nexport const LAST_SESSION_PARAM = 'ls';\n\nexport const APPLICATION_ID_PARAM = 'p';\n\nexport const APP_CHECK_TOKEN_PARAM = 'ac';\n\nexport const WEBSOCKET = 'websocket';\n\nexport const LONG_POLLING = 'long_polling';\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, EmulatorMockTokenOptions } from '@firebase/util';\n\nimport { LONG_POLLING, WEBSOCKET } from '../realtime/Constants';\n\nimport { PersistentStorage } from './storage/storage';\nimport { each } from './util/util';\n\nexport interface RepoInfoEmulatorOptions {\n mockUserToken?: string | EmulatorMockTokenOptions;\n}\n\n/**\n * A class that holds metadata about a Repo object\n */\nexport class RepoInfo {\n private _host: string;\n private _domain: string;\n internalHost: string;\n\n /**\n * @param host - Hostname portion of the url for the repo\n * @param secure - Whether or not this repo is accessed over ssl\n * @param namespace - The namespace represented by the repo\n * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).\n * @param nodeAdmin - Whether this instance uses Admin SDK credentials\n * @param persistenceKey - Override the default session persistence storage key\n */\n constructor(\n host: string,\n public readonly secure: boolean,\n public readonly namespace: string,\n public readonly webSocketOnly: boolean,\n public readonly nodeAdmin: boolean = false,\n public readonly persistenceKey: string = '',\n public readonly includeNamespaceInQueryParams: boolean = false,\n public readonly isUsingEmulator: boolean = false,\n public readonly emulatorOptions: RepoInfoEmulatorOptions | null = null\n ) {\n this._host = host.toLowerCase();\n this._domain = this._host.substr(this._host.indexOf('.') + 1);\n this.internalHost =\n (PersistentStorage.get('host:' + host) as string) || this._host;\n }\n\n isCacheableHost(): boolean {\n return this.internalHost.substr(0, 2) === 's-';\n }\n\n isCustomHost() {\n return (\n this._domain !== 'firebaseio.com' &&\n this._domain !== 'firebaseio-demo.com'\n );\n }\n\n get host() {\n return this._host;\n }\n\n set host(newHost: string) {\n if (newHost !== this.internalHost) {\n this.internalHost = newHost;\n if (this.isCacheableHost()) {\n PersistentStorage.set('host:' + this._host, this.internalHost);\n }\n }\n }\n\n toString(): string {\n let str = this.toURLString();\n if (this.persistenceKey) {\n str += '<' + this.persistenceKey + '>';\n }\n return str;\n }\n\n toURLString(): string {\n const protocol = this.secure ? 'https://' : 'http://';\n const query = this.includeNamespaceInQueryParams\n ? `?ns=${this.namespace}`\n : '';\n return `${protocol}${this.host}/${query}`;\n }\n}\n\nfunction repoInfoNeedsQueryParam(repoInfo: RepoInfo): boolean {\n return (\n repoInfo.host !== repoInfo.internalHost ||\n repoInfo.isCustomHost() ||\n repoInfo.includeNamespaceInQueryParams\n );\n}\n\n/**\n * Returns the websocket URL for this repo\n * @param repoInfo - RepoInfo object\n * @param type - of connection\n * @param params - list\n * @returns The URL for this repo\n */\nexport function repoInfoConnectionURL(\n repoInfo: RepoInfo,\n type: string,\n params: { [k: string]: string }\n): string {\n assert(typeof type === 'string', 'typeof type must == string');\n assert(typeof params === 'object', 'typeof params must == object');\n\n let connURL: string;\n if (type === WEBSOCKET) {\n connURL =\n (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';\n } else if (type === LONG_POLLING) {\n connURL =\n (repoInfo.secure ? 'https://' : 'http://') +\n repoInfo.internalHost +\n '/.lp?';\n } else {\n throw new Error('Unknown connection type: ' + type);\n }\n if (repoInfoNeedsQueryParam(repoInfo)) {\n params['ns'] = repoInfo.namespace;\n }\n\n const pairs: string[] = [];\n\n each(params, (key: string, value: string) => {\n pairs.push(key + '=' + value);\n });\n\n return connURL + pairs.join('&');\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { deepCopy, contains } from '@firebase/util';\n\n/**\n * Tracks a collection of stats.\n */\nexport class StatsCollection {\n private counters_: { [k: string]: number } = {};\n\n incrementCounter(name: string, amount: number = 1) {\n if (!contains(this.counters_, name)) {\n this.counters_[name] = 0;\n }\n\n this.counters_[name] += amount;\n }\n\n get() {\n return deepCopy(this.counters_);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../RepoInfo';\n\nimport { StatsCollection } from './StatsCollection';\n\nconst collections: { [k: string]: StatsCollection } = {};\nconst reporters: { [k: string]: unknown } = {};\n\nexport function statsManagerGetCollection(repoInfo: RepoInfo): StatsCollection {\n const hashString = repoInfo.toString();\n\n if (!collections[hashString]) {\n collections[hashString] = new StatsCollection();\n }\n\n return collections[hashString];\n}\n\nexport function statsManagerGetOrCreateReporter(\n repoInfo: RepoInfo,\n creatorFunction: () => T\n): T {\n const hashString = repoInfo.toString();\n\n if (!reporters[hashString]) {\n reporters[hashString] = creatorFunction();\n }\n\n return reporters[hashString] as T;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { exceptionGuard } from '../../core/util/util';\n\n/**\n * This class ensures the packets from the server arrive in order\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\n */\nexport class PacketReceiver {\n pendingResponses: unknown[] = [];\n currentResponseNum = 0;\n closeAfterResponse = -1;\n onClose: (() => void) | null = null;\n\n /**\n * @param onMessage_\n */\n constructor(private onMessage_: (a: {}) => void) {}\n\n closeAfter(responseNum: number, callback: () => void) {\n this.closeAfterResponse = responseNum;\n this.onClose = callback;\n if (this.closeAfterResponse < this.currentResponseNum) {\n this.onClose();\n this.onClose = null;\n }\n }\n\n /**\n * Each message from the server comes with a response number, and an array of data. The responseNumber\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\n * browsers will respond in the same order as the requests we sent\n */\n handleResponse(requestNum: number, data: unknown[]) {\n this.pendingResponses[requestNum] = data;\n while (this.pendingResponses[this.currentResponseNum]) {\n const toProcess = this.pendingResponses[\n this.currentResponseNum\n ] as unknown[];\n delete this.pendingResponses[this.currentResponseNum];\n for (let i = 0; i < toProcess.length; ++i) {\n if (toProcess[i]) {\n exceptionGuard(() => {\n this.onMessage_(toProcess[i]);\n });\n }\n }\n if (this.currentResponseNum === this.closeAfterResponse) {\n if (this.onClose) {\n this.onClose();\n this.onClose = null;\n }\n break;\n }\n this.currentResponseNum++;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Encode, isNodeSdk, stringify } from '@firebase/util';\n\nimport { RepoInfo, repoInfoConnectionURL } from '../core/RepoInfo';\nimport { StatsCollection } from '../core/stats/StatsCollection';\nimport { statsManagerGetCollection } from '../core/stats/StatsManager';\nimport {\n executeWhenDOMReady,\n isChromeExtensionContentScript,\n isWindowsStoreApp,\n log,\n logWrapper,\n LUIDGenerator,\n splitStringBySize\n} from '../core/util/util';\n\nimport {\n APP_CHECK_TOKEN_PARAM,\n APPLICATION_ID_PARAM,\n FORGE_DOMAIN_RE,\n FORGE_REF,\n LAST_SESSION_PARAM,\n LONG_POLLING,\n PROTOCOL_VERSION,\n REFERER_PARAM,\n TRANSPORT_SESSION_PARAM,\n VERSION_PARAM\n} from './Constants';\nimport { PacketReceiver } from './polling/PacketReceiver';\nimport { Transport } from './Transport';\n\n// URL query parameters associated with longpolling\nexport const FIREBASE_LONGPOLL_START_PARAM = 'start';\nexport const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\nexport const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\nexport const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\nexport const FIREBASE_LONGPOLL_ID_PARAM = 'id';\nexport const FIREBASE_LONGPOLL_PW_PARAM = 'pw';\nexport const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\nexport const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\nexport const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\nexport const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\nexport const FIREBASE_LONGPOLL_DATA_PARAM = 'd';\nexport const FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = 'disconn';\nexport const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\n\n//Data size constants.\n//TODO: Perf: the maximum length actually differs from browser to browser.\n// We should check what browser we're on and set accordingly.\nconst MAX_URL_DATA_SIZE = 1870;\nconst SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\nconst MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\n\n/**\n * Keepalive period\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\n * length of 30 seconds that we can't exceed.\n */\nconst KEEPALIVE_REQUEST_INTERVAL = 25000;\n\n/**\n * How long to wait before aborting a long-polling connection attempt.\n */\nconst LP_CONNECT_TIMEOUT = 30000;\n\n/**\n * This class manages a single long-polling connection.\n */\nexport class BrowserPollConnection implements Transport {\n bytesSent = 0;\n bytesReceived = 0;\n urlFn: (params: object) => string;\n scriptTagHolder: FirebaseIFrameScriptHolder;\n myDisconnFrame: HTMLIFrameElement;\n curSegmentNum: number;\n myPacketOrderer: PacketReceiver;\n id: string;\n password: string;\n private log_: (...a: unknown[]) => void;\n private stats_: StatsCollection;\n private everConnected_ = false;\n private isClosed_: boolean;\n private connectTimeoutTimer_: number | null;\n private onDisconnect_: ((a?: boolean) => void) | null;\n\n /**\n * @param connId An identifier for this connection, used for logging\n * @param repoInfo The info for the endpoint to send data to.\n * @param applicationId The Firebase App ID for this project.\n * @param appCheckToken The AppCheck token for this client.\n * @param authToken The AuthToken to use for this connection.\n * @param transportSessionId Optional transportSessionid if we are\n * reconnecting for an existing transport session\n * @param lastSessionId Optional lastSessionId if the PersistentConnection has\n * already created a connection previously\n */\n constructor(\n public connId: string,\n public repoInfo: RepoInfo,\n private applicationId?: string,\n private appCheckToken?: string,\n private authToken?: string,\n public transportSessionId?: string,\n public lastSessionId?: string\n ) {\n this.log_ = logWrapper(connId);\n this.stats_ = statsManagerGetCollection(repoInfo);\n this.urlFn = (params: { [k: string]: string }) => {\n // Always add the token if we have one.\n if (this.appCheckToken) {\n params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\n }\n return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);\n };\n }\n\n /**\n * @param onMessage - Callback when messages arrive\n * @param onDisconnect - Callback with connection lost.\n */\n open(onMessage: (msg: {}) => void, onDisconnect: (a?: boolean) => void) {\n this.curSegmentNum = 0;\n this.onDisconnect_ = onDisconnect;\n this.myPacketOrderer = new PacketReceiver(onMessage);\n this.isClosed_ = false;\n\n this.connectTimeoutTimer_ = setTimeout(() => {\n this.log_('Timed out trying to connect.');\n // Make sure we clear the host cache\n this.onClosed_();\n this.connectTimeoutTimer_ = null;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(LP_CONNECT_TIMEOUT)) as any;\n\n // Ensure we delay the creation of the iframe until the DOM is loaded.\n executeWhenDOMReady(() => {\n if (this.isClosed_) {\n return;\n }\n\n //Set up a callback that gets triggered once a connection is set up.\n this.scriptTagHolder = new FirebaseIFrameScriptHolder(\n (...args) => {\n const [command, arg1, arg2, arg3, arg4] = args;\n this.incrementIncomingBytes_(args);\n if (!this.scriptTagHolder) {\n return; // we closed the connection.\n }\n\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n this.everConnected_ = true;\n if (command === FIREBASE_LONGPOLL_START_PARAM) {\n this.id = arg1 as string;\n this.password = arg2 as string;\n } else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {\n // Don't clear the host cache. We got a response from the server, so we know it's reachable\n if (arg1) {\n // We aren't expecting any more data (other than what the server's already in the process of sending us\n // through our already open polls), so don't send any more.\n this.scriptTagHolder.sendNewPolls = false;\n\n // arg1 in this case is the last response number sent by the server. We should try to receive\n // all of the responses up to this one before closing\n this.myPacketOrderer.closeAfter(arg1 as number, () => {\n this.onClosed_();\n });\n } else {\n this.onClosed_();\n }\n } else {\n throw new Error('Unrecognized command received: ' + command);\n }\n },\n (...args) => {\n const [pN, data] = args;\n this.incrementIncomingBytes_(args);\n this.myPacketOrderer.handleResponse(pN as number, data as unknown[]);\n },\n () => {\n this.onClosed_();\n },\n this.urlFn\n );\n\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\n //from cache.\n const urlParams: { [k: string]: string | number } = {};\n urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(\n Math.random() * 100000000\n );\n if (this.scriptTagHolder.uniqueCallbackIdentifier) {\n urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =\n this.scriptTagHolder.uniqueCallbackIdentifier;\n }\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\n if (this.transportSessionId) {\n urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;\n }\n if (this.lastSessionId) {\n urlParams[LAST_SESSION_PARAM] = this.lastSessionId;\n }\n if (this.applicationId) {\n urlParams[APPLICATION_ID_PARAM] = this.applicationId;\n }\n if (this.appCheckToken) {\n urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\n }\n if (\n typeof location !== 'undefined' &&\n location.hostname &&\n FORGE_DOMAIN_RE.test(location.hostname)\n ) {\n urlParams[REFERER_PARAM] = FORGE_REF;\n }\n const connectURL = this.urlFn(urlParams);\n this.log_('Connecting via long-poll to ' + connectURL);\n this.scriptTagHolder.addTag(connectURL, () => {\n /* do nothing */\n });\n });\n }\n\n /**\n * Call this when a handshake has completed successfully and we want to consider the connection established\n */\n start() {\n this.scriptTagHolder.startLongPoll(this.id, this.password);\n this.addDisconnectPingFrame(this.id, this.password);\n }\n\n static forceAllow_: boolean;\n\n /**\n * Forces long polling to be considered as a potential transport\n */\n static forceAllow() {\n BrowserPollConnection.forceAllow_ = true;\n }\n\n static forceDisallow_: boolean;\n\n /**\n * Forces longpolling to not be considered as a potential transport\n */\n static forceDisallow() {\n BrowserPollConnection.forceDisallow_ = true;\n }\n\n // Static method, use string literal so it can be accessed in a generic way\n static isAvailable() {\n if (isNodeSdk()) {\n return false;\n } else if (BrowserPollConnection.forceAllow_) {\n return true;\n } else {\n // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\n // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\n return (\n !BrowserPollConnection.forceDisallow_ &&\n typeof document !== 'undefined' &&\n document.createElement != null &&\n !isChromeExtensionContentScript() &&\n !isWindowsStoreApp()\n );\n }\n }\n\n /**\n * No-op for polling\n */\n markConnectionHealthy() {}\n\n /**\n * Stops polling and cleans up the iframe\n */\n private shutdown_() {\n this.isClosed_ = true;\n\n if (this.scriptTagHolder) {\n this.scriptTagHolder.close();\n this.scriptTagHolder = null;\n }\n\n //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\n if (this.myDisconnFrame) {\n document.body.removeChild(this.myDisconnFrame);\n this.myDisconnFrame = null;\n }\n\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n }\n\n /**\n * Triggered when this transport is closed\n */\n private onClosed_() {\n if (!this.isClosed_) {\n this.log_('Longpoll is closing itself');\n this.shutdown_();\n\n if (this.onDisconnect_) {\n this.onDisconnect_(this.everConnected_);\n this.onDisconnect_ = null;\n }\n }\n }\n\n /**\n * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\n * that we've left.\n */\n close() {\n if (!this.isClosed_) {\n this.log_('Longpoll is being closed.');\n this.shutdown_();\n }\n }\n\n /**\n * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\n * broken into chunks (since URLs have a small maximum length).\n * @param data - The JSON data to transmit.\n */\n send(data: {}) {\n const dataStr = stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n\n //first, lets get the base64-encoded data\n const base64data = base64Encode(dataStr);\n\n //We can only fit a certain amount in each URL, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\n\n //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\n //of segments so that we can reassemble the packet on the server.\n for (let i = 0; i < dataSegs.length; i++) {\n this.scriptTagHolder.enqueueSegment(\n this.curSegmentNum,\n dataSegs.length,\n dataSegs[i]\n );\n this.curSegmentNum++;\n }\n }\n\n /**\n * This is how we notify the server that we're leaving.\n * We aren't able to send requests with DHTML on a window close event, but we can\n * trigger XHR requests in some browsers (everything but Opera basically).\n */\n addDisconnectPingFrame(id: string, pw: string) {\n if (isNodeSdk()) {\n return;\n }\n this.myDisconnFrame = document.createElement('iframe');\n const urlParams: { [k: string]: string } = {};\n urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;\n this.myDisconnFrame.src = this.urlFn(urlParams);\n this.myDisconnFrame.style.display = 'none';\n\n document.body.appendChild(this.myDisconnFrame);\n }\n\n /**\n * Used to track the bytes received by this client\n */\n private incrementIncomingBytes_(args: unknown) {\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\n const bytesReceived = stringify(args).length;\n this.bytesReceived += bytesReceived;\n this.stats_.incrementCounter('bytes_received', bytesReceived);\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport interface IFrameElement extends HTMLIFrameElement {\n doc: Document;\n}\n\n/*********************************************************************************************\n * A wrapper around an iframe that is used as a long-polling script holder.\n *********************************************************************************************/\nexport class FirebaseIFrameScriptHolder {\n //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\n //problems in some browsers.\n outstandingRequests = new Set();\n\n //A queue of the pending segments waiting for transmission to the server.\n pendingSegs: Array<{ seg: number; ts: number; d: unknown }> = [];\n\n //A serial number. We use this for two things:\n // 1) A way to ensure the browser doesn't cache responses to polls\n // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\n // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\n // JSONP code in the order it was added to the iframe.\n currentSerial = Math.floor(Math.random() * 100000000);\n\n // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\n // incoming data from the server that we're waiting for).\n sendNewPolls = true;\n\n uniqueCallbackIdentifier: number;\n myIFrame: IFrameElement;\n alive: boolean;\n myID: string;\n myPW: string;\n commandCB: (command: string, ...args: unknown[]) => void;\n onMessageCB: (...args: unknown[]) => void;\n\n /**\n * @param commandCB - The callback to be called when control commands are received from the server.\n * @param onMessageCB - The callback to be triggered when responses arrive from the server.\n * @param onDisconnect - The callback to be triggered when this tag holder is closed\n * @param urlFn - A function that provides the URL of the endpoint to send data to.\n */\n constructor(\n commandCB: (command: string, ...args: unknown[]) => void,\n onMessageCB: (...args: unknown[]) => void,\n public onDisconnect: () => void,\n public urlFn: (a: object) => string\n ) {\n if (!isNodeSdk()) {\n //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\n //iframes where we put the long-polling script tags. We have two callbacks:\n // 1) Command Callback - Triggered for control issues, like starting a connection.\n // 2) Message Callback - Triggered when new data arrives.\n this.uniqueCallbackIdentifier = LUIDGenerator();\n window[\n FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier\n ] = commandCB;\n window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =\n onMessageCB;\n\n //Create an iframe for us to add script tags to.\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\n\n // Set the iframe's contents.\n let script = '';\n // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\n // for ie9, but ie8 needs to do it again in the document itself.\n if (\n this.myIFrame.src &&\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:'\n ) {\n const currentDomain = document.domain;\n script = '';\n }\n const iframeContents = '' + script + '';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n } catch (e) {\n log('frame writing exception');\n if (e.stack) {\n log(e.stack);\n }\n log(e);\n }\n } else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n\n /**\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\n * actually use.\n */\n private static createIFrame_(): IFrameElement {\n const iframe = document.createElement('iframe') as IFrameElement;\n iframe.style.display = 'none';\n\n // This is necessary in order to initialize the document inside the iframe\n if (document.body) {\n document.body.appendChild(iframe);\n try {\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n const a = iframe.contentWindow.document;\n if (!a) {\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n log('No IE domain setting required');\n }\n } catch (e) {\n const domain = document.domain;\n iframe.src =\n \"javascript:void((function(){document.open();document.domain='\" +\n domain +\n \"';document.close();})())\";\n }\n } else {\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n // never gets hit.\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n }\n\n // Get the document of the iframe in a browser-specific way.\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n } else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else if ((iframe as any).document) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n iframe.doc = (iframe as any).document; //others?\n }\n\n return iframe;\n }\n\n /**\n * Cancel all outstanding queries and remove the frame.\n */\n close() {\n //Mark this iframe as dead, so no new requests are sent.\n this.alive = false;\n\n if (this.myIFrame) {\n //We have to actually remove all of the html inside this iframe before removing it from the\n //window, or IE will continue loading and executing the script tags we've already added, which\n //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.\n this.myIFrame.doc.body.textContent = '';\n setTimeout(() => {\n if (this.myIFrame !== null) {\n document.body.removeChild(this.myIFrame);\n this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n\n // Protect from being called recursively.\n const onDisconnect = this.onDisconnect;\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\n }\n\n /**\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\n * @param id - The ID of this connection\n * @param pw - The password for this connection\n */\n startLongPoll(id: string, pw: string) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true;\n\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n while (this.newRequest_()) {}\n }\n\n /**\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\n * too many outstanding requests and we are still alive.\n *\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\n * needed.\n */\n private newRequest_() {\n // We keep one outstanding request open all the time to receive data, but if we need to send data\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\n // close the old request.\n if (\n this.alive &&\n this.sendNewPolls &&\n this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)\n ) {\n //construct our url\n this.currentSerial++;\n const urlParams: { [k: string]: string | number } = {};\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n let theURL = this.urlFn(urlParams);\n //Now add as much data as we can.\n let curDataString = '';\n let i = 0;\n\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n const nextSeg = this.pendingSegs[0];\n if (\n (nextSeg.d as unknown[]).length +\n SEG_HEADER_SIZE +\n curDataString.length <=\n MAX_URL_DATA_SIZE\n ) {\n //great, the segment will fit. Lets append it.\n const theSeg = this.pendingSegs.shift();\n curDataString =\n curDataString +\n '&' +\n FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n i +\n '=' +\n theSeg.seg +\n '&' +\n FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n i +\n '=' +\n theSeg.ts +\n '&' +\n FIREBASE_LONGPOLL_DATA_PARAM +\n i +\n '=' +\n theSeg.d;\n i++;\n } else {\n break;\n }\n }\n\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Queue a packet for transmission to the server.\n * @param segnum - A sequential id for this packet segment used for reassembly\n * @param totalsegs - The total number of segments in this packet\n * @param data - The data for this segment.\n */\n enqueueSegment(segnum: number, totalsegs: number, data: unknown) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n\n //send the data immediately if there isn't already data being transmitted, unless\n //startLongPoll hasn't been called yet.\n if (this.alive) {\n this.newRequest_();\n }\n }\n\n /**\n * Add a script tag for a regular long-poll request.\n * @param url - The URL of the script tag.\n * @param serial - The serial number of the request.\n */\n private addLongPollTag_(url: string, serial: number) {\n //remember that we sent this request.\n this.outstandingRequests.add(serial);\n\n const doNewRequest = () => {\n this.outstandingRequests.delete(serial);\n this.newRequest_();\n };\n\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n const keepaliveTimeout = setTimeout(\n doNewRequest,\n Math.floor(KEEPALIVE_REQUEST_INTERVAL)\n );\n\n const readyStateCB = () => {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout);\n\n // Trigger a new request so we can continue receiving data.\n doNewRequest();\n };\n\n this.addTag(url, readyStateCB);\n }\n\n /**\n * Add an arbitrary script tag to the iframe.\n * @param url - The URL for the script tag source.\n * @param loadCB - A callback to be triggered once the script has loaded.\n */\n addTag(url: string, loadCB: () => void) {\n if (isNodeSdk()) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any).doNodeLongPoll(url, loadCB);\n } else {\n setTimeout(() => {\n try {\n // if we're already closed, don't add this poll\n if (!this.sendNewPolls) {\n return;\n }\n const newScript = this.myIFrame.doc.createElement('script');\n newScript.type = 'text/javascript';\n newScript.async = true;\n newScript.src = url;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n newScript.onload = (newScript as any).onreadystatechange =\n function () {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const rstate = (newScript as any).readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n newScript.onload = (newScript as any).onreadystatechange = null;\n if (newScript.parentNode) {\n newScript.parentNode.removeChild(newScript);\n }\n loadCB();\n }\n };\n newScript.onerror = () => {\n log('Long-poll script failed to load: ' + url);\n this.sendNewPolls = false;\n this.close();\n };\n this.myIFrame.doc.body.appendChild(newScript);\n } catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, isNodeSdk, jsonEval, stringify } from '@firebase/util';\n\nimport { RepoInfo, repoInfoConnectionURL } from '../core/RepoInfo';\nimport { StatsCollection } from '../core/stats/StatsCollection';\nimport { statsManagerGetCollection } from '../core/stats/StatsManager';\nimport { PersistentStorage } from '../core/storage/storage';\nimport { logWrapper, splitStringBySize } from '../core/util/util';\nimport { SDK_VERSION } from '../core/version';\n\nimport {\n APPLICATION_ID_PARAM,\n APP_CHECK_TOKEN_PARAM,\n FORGE_DOMAIN_RE,\n FORGE_REF,\n LAST_SESSION_PARAM,\n PROTOCOL_VERSION,\n REFERER_PARAM,\n TRANSPORT_SESSION_PARAM,\n VERSION_PARAM,\n WEBSOCKET\n} from './Constants';\nimport { Transport } from './Transport';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ndeclare const MozWebSocket: any;\n\nconst WEBSOCKET_MAX_FRAME_SIZE = 16384;\nconst WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\n\nlet WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n} else if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\n\nexport function setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\n\n/**\n * Create a new websocket connection with the given callbacks.\n */\nexport class WebSocketConnection implements Transport {\n keepaliveTimer: number | null = null;\n frames: string[] | null = null;\n totalFrames = 0;\n bytesSent = 0;\n bytesReceived = 0;\n connURL: string;\n onDisconnect: (a?: boolean) => void;\n onMessage: (msg: {}) => void;\n mySock: WebSocket | null;\n private log_: (...a: unknown[]) => void;\n private stats_: StatsCollection;\n private everConnected_: boolean;\n private isClosed_: boolean;\n private nodeAdmin: boolean;\n\n /**\n * @param connId identifier for this transport\n * @param repoInfo The info for the websocket endpoint.\n * @param applicationId The Firebase App ID for this project.\n * @param appCheckToken The App Check Token for this client.\n * @param authToken The Auth Token for this client.\n * @param transportSessionId Optional transportSessionId if this is connecting\n * to an existing transport session\n * @param lastSessionId Optional lastSessionId if there was a previous\n * connection\n */\n constructor(\n public connId: string,\n repoInfo: RepoInfo,\n private applicationId?: string,\n private appCheckToken?: string,\n private authToken?: string,\n transportSessionId?: string,\n lastSessionId?: string\n ) {\n this.log_ = logWrapper(this.connId);\n this.stats_ = statsManagerGetCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(\n repoInfo,\n transportSessionId,\n lastSessionId,\n appCheckToken,\n applicationId\n );\n this.nodeAdmin = repoInfo.nodeAdmin;\n }\n\n /**\n * @param repoInfo - The info for the websocket endpoint.\n * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param lastSessionId - Optional lastSessionId if there was a previous connection\n * @returns connection url\n */\n private static connectionURL_(\n repoInfo: RepoInfo,\n transportSessionId?: string,\n lastSessionId?: string,\n appCheckToken?: string,\n applicationId?: string\n ): string {\n const urlParams: { [k: string]: string } = {};\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\n\n if (\n !isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.hostname &&\n FORGE_DOMAIN_RE.test(location.hostname)\n ) {\n urlParams[REFERER_PARAM] = FORGE_REF;\n }\n if (transportSessionId) {\n urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[LAST_SESSION_PARAM] = lastSessionId;\n }\n if (appCheckToken) {\n urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;\n }\n if (applicationId) {\n urlParams[APPLICATION_ID_PARAM] = applicationId;\n }\n\n return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);\n }\n\n /**\n * @param onMessage - Callback when messages arrive\n * @param onDisconnect - Callback with connection lost.\n */\n open(onMessage: (msg: {}) => void, onDisconnect: (a?: boolean) => void) {\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n\n this.log_('Websocket connecting to ' + this.connURL);\n\n this.everConnected_ = false;\n // Assume failure until proven otherwise.\n PersistentStorage.set('previous_websocket_failure', true);\n\n try {\n let options: { [k: string]: object };\n if (isNodeSdk()) {\n const device = this.nodeAdmin ? 'AdminNode' : 'Node';\n // UA Format: Firebase////\n options = {\n headers: {\n 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,\n 'X-Firebase-GMPID': this.applicationId || ''\n }\n };\n\n // If using Node with admin creds, AppCheck-related checks are unnecessary.\n // Note that we send the credentials here even if they aren't admin credentials, which is\n // not a problem.\n // Note that this header is just used to bypass appcheck, and the token should still be sent\n // through the websocket connection once it is established.\n if (this.authToken) {\n options.headers['Authorization'] = `Bearer ${this.authToken}`;\n }\n if (this.appCheckToken) {\n options.headers['X-Firebase-AppCheck'] = this.appCheckToken;\n }\n\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n const env = process['env'];\n const proxy =\n this.connURL.indexOf('wss://') === 0\n ? env['HTTPS_PROXY'] || env['https_proxy']\n : env['HTTP_PROXY'] || env['http_proxy'];\n\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n }\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n } catch (e) {\n this.log_('Error instantiating WebSocket.');\n const error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n return;\n }\n\n this.mySock.onopen = () => {\n this.log_('Websocket connected.');\n this.everConnected_ = true;\n };\n\n this.mySock.onclose = () => {\n this.log_('Websocket connection was disconnected.');\n this.mySock = null;\n this.onClosed_();\n };\n\n this.mySock.onmessage = m => {\n this.handleIncomingFrame(m as {});\n };\n\n this.mySock.onerror = e => {\n this.log_('WebSocket error. Closing connection.');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const error = (e as any).message || (e as any).data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n };\n }\n\n /**\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n */\n start() {}\n\n static forceDisallow_: boolean;\n\n static forceDisallow() {\n WebSocketConnection.forceDisallow_ = true;\n }\n\n static isAvailable(): boolean {\n let isOldAndroid = false;\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n const oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n isOldAndroid = true;\n }\n }\n }\n\n return (\n !isOldAndroid &&\n WebSocketImpl !== null &&\n !WebSocketConnection.forceDisallow_\n );\n }\n\n /**\n * Number of response before we consider the connection \"healthy.\"\n */\n static responsesRequiredToBeHealthy = 2;\n\n /**\n * Time to wait for the connection te become healthy before giving up.\n */\n static healthyTimeout = 30000;\n\n /**\n * Returns true if we previously failed to connect with this transport.\n */\n static previouslyFailed(): boolean {\n // If our persistent storage is actually only in-memory storage,\n // we default to assuming that it previously failed to be safe.\n return (\n PersistentStorage.isInMemoryStorage ||\n PersistentStorage.get('previous_websocket_failure') === true\n );\n }\n\n markConnectionHealthy() {\n PersistentStorage.remove('previous_websocket_failure');\n }\n\n private appendFrame_(data: string) {\n this.frames.push(data);\n if (this.frames.length === this.totalFrames) {\n const fullMess = this.frames.join('');\n this.frames = null;\n const jsonMess = jsonEval(fullMess) as object;\n\n //handle the message\n this.onMessage(jsonMess);\n }\n }\n\n /**\n * @param frameCount - The number of frames we are expecting from the server\n */\n private handleNewFrameCount_(frameCount: number) {\n this.totalFrames = frameCount;\n this.frames = [];\n }\n\n /**\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\n * @returns Any remaining data to be process, or null if there is none\n */\n private extractFrameCount_(data: string): string | null {\n assert(this.frames === null, 'We already have a frame buffer');\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\n if (data.length <= 6) {\n const frameCount = Number(data);\n if (!isNaN(frameCount)) {\n this.handleNewFrameCount_(frameCount);\n return null;\n }\n }\n this.handleNewFrameCount_(1);\n return data;\n }\n\n /**\n * Process a websocket frame that has arrived from the server.\n * @param mess - The frame data\n */\n handleIncomingFrame(mess: { [k: string]: unknown }) {\n if (this.mySock === null) {\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n }\n const data = mess['data'] as string;\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n\n this.resetKeepAlive();\n\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n } else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n const remainingData = this.extractFrameCount_(data);\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n }\n\n /**\n * Send a message to the server\n * @param data - The JSON object to transmit\n */\n send(data: {}) {\n this.resetKeepAlive();\n\n const dataStr = stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n\n //We can only fit a certain amount in each websocket frame, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n\n const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n\n //Send the length header\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n }\n\n //Send the actual data in segments.\n for (let i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n }\n\n private shutdown_() {\n this.isClosed_ = true;\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n }\n\n private onClosed_() {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_();\n\n // since this is an internal close, trigger the close listener\n if (this.onDisconnect) {\n this.onDisconnect(this.everConnected_);\n this.onDisconnect = null;\n }\n }\n }\n\n /**\n * External-facing close handler.\n * Close the websocket and kill the connection.\n */\n close() {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n }\n\n /**\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\n * the last activity.\n */\n resetKeepAlive() {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(() => {\n //If there has been no websocket activity for a while, send a no-op\n if (this.mySock) {\n this.sendString_('0');\n }\n this.resetKeepAlive();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL)) as any;\n }\n\n /**\n * Send a string over the websocket.\n *\n * @param str - String to send.\n */\n private sendString_(str: string) {\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n // calls for some unknown reason. We treat these as an error and disconnect.\n // See https://app.asana.com/0/58926111402292/68021340250410\n try {\n this.mySock.send(str);\n } catch (e) {\n this.log_(\n 'Exception thrown from WebSocket.send():',\n e.message || e.data,\n 'Closing connection.'\n );\n setTimeout(this.onClosed_.bind(this), 0);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../core/RepoInfo';\nimport { warn } from '../core/util/util';\n\nimport { BrowserPollConnection } from './BrowserPollConnection';\nimport { TransportConstructor } from './Transport';\nimport { WebSocketConnection } from './WebSocketConnection';\n\n/**\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\n * lifecycle.\n *\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\n * they are available.\n */\nexport class TransportManager {\n private transports_: TransportConstructor[];\n\n // Keeps track of whether the TransportManager has already chosen a transport to use\n static globalTransportInitialized_ = false;\n\n static get ALL_TRANSPORTS() {\n return [BrowserPollConnection, WebSocketConnection];\n }\n\n /**\n * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after\n * TransportManager has already set up transports_\n */\n static get IS_TRANSPORT_INITIALIZED() {\n return this.globalTransportInitialized_;\n }\n\n /**\n * @param repoInfo - Metadata around the namespace we're connecting to\n */\n constructor(repoInfo: RepoInfo) {\n this.initTransports_(repoInfo);\n }\n\n private initTransports_(repoInfo: RepoInfo) {\n const isWebSocketsAvailable: boolean =\n WebSocketConnection && WebSocketConnection['isAvailable']();\n let isSkipPollConnection =\n isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();\n\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable) {\n warn(\n \"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\"\n );\n }\n\n isSkipPollConnection = true;\n }\n\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection];\n } else {\n const transports = (this.transports_ = [] as TransportConstructor[]);\n for (const transport of TransportManager.ALL_TRANSPORTS) {\n if (transport && transport['isAvailable']()) {\n transports.push(transport);\n }\n }\n TransportManager.globalTransportInitialized_ = true;\n }\n }\n\n /**\n * @returns The constructor for the initial transport to use\n */\n initialTransport(): TransportConstructor {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n } else {\n throw new Error('No transports available');\n }\n }\n\n /**\n * @returns The constructor for the next transport, or null\n */\n upgradeTransport(): TransportConstructor | null {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n } else {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../core/RepoInfo';\nimport { PersistentStorage } from '../core/storage/storage';\nimport { Indexable } from '../core/util/misc';\nimport {\n error,\n logWrapper,\n requireKey,\n setTimeoutNonBlocking,\n warn\n} from '../core/util/util';\n\nimport { PROTOCOL_VERSION } from './Constants';\nimport { Transport, TransportConstructor } from './Transport';\nimport { TransportManager } from './TransportManager';\n\n// Abort upgrade attempt if it takes longer than 60s.\nconst UPGRADE_TIMEOUT = 60000;\n\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\nconst DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\n\n// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\n// but we've sent/received enough bytes, we don't cancel the connection.\nconst BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\nconst BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\n\nconst enum RealtimeState {\n CONNECTING,\n CONNECTED,\n DISCONNECTED\n}\n\nconst MESSAGE_TYPE = 't';\nconst MESSAGE_DATA = 'd';\nconst CONTROL_SHUTDOWN = 's';\nconst CONTROL_RESET = 'r';\nconst CONTROL_ERROR = 'e';\nconst CONTROL_PONG = 'o';\nconst SWITCH_ACK = 'a';\nconst END_TRANSMISSION = 'n';\nconst PING = 'p';\n\nconst SERVER_HELLO = 'h';\n\n/**\n * Creates a new real-time connection to the server using whichever method works\n * best in the current browser.\n */\nexport class Connection {\n connectionCount = 0;\n pendingDataMessages: unknown[] = [];\n sessionId: string;\n\n private conn_: Transport;\n private healthyTimeout_: number;\n private isHealthy_: boolean;\n private log_: (...args: unknown[]) => void;\n private primaryResponsesRequired_: number;\n private rx_: Transport;\n private secondaryConn_: Transport;\n private secondaryResponsesRequired_: number;\n private state_ = RealtimeState.CONNECTING;\n private transportManager_: TransportManager;\n private tx_: Transport;\n\n /**\n * @param id - an id for this connection\n * @param repoInfo_ - the info for the endpoint to connect to\n * @param applicationId_ - the Firebase App ID for this project\n * @param appCheckToken_ - The App Check Token for this device.\n * @param authToken_ - The auth token for this session.\n * @param onMessage_ - the callback to be triggered when a server-push message arrives\n * @param onReady_ - the callback to be triggered when this connection is ready to send messages.\n * @param onDisconnect_ - the callback to be triggered when a connection was lost\n * @param onKill_ - the callback to be triggered when this connection has permanently shut down.\n * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\n */\n constructor(\n public id: string,\n private repoInfo_: RepoInfo,\n private applicationId_: string | undefined,\n private appCheckToken_: string | undefined,\n private authToken_: string | undefined,\n private onMessage_: (a: {}) => void,\n private onReady_: (a: number, b: string) => void,\n private onDisconnect_: () => void,\n private onKill_: (a: string) => void,\n public lastSessionId?: string\n ) {\n this.log_ = logWrapper('c:' + this.id + ':');\n this.transportManager_ = new TransportManager(repoInfo_);\n this.log_('Connection created');\n this.start_();\n }\n\n /**\n * Starts a connection attempt\n */\n private start_(): void {\n const conn = this.transportManager_.initialTransport();\n this.conn_ = new conn(\n this.nextTransportId_(),\n this.repoInfo_,\n this.applicationId_,\n this.appCheckToken_,\n this.authToken_,\n null,\n this.lastSessionId\n );\n\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\n\n const onMessageReceived = this.connReceiver_(this.conn_);\n const onConnectionLost = this.disconnReceiver_(this.conn_);\n this.tx_ = this.conn_;\n this.rx_ = this.conn_;\n this.secondaryConn_ = null;\n this.isHealthy_ = false;\n\n /*\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\n * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\n * still have the context of your originating frame.\n */\n setTimeout(() => {\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\n this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);\n }, Math.floor(0));\n\n const healthyTimeoutMS = conn['healthyTimeout'] || 0;\n if (healthyTimeoutMS > 0) {\n this.healthyTimeout_ = setTimeoutNonBlocking(() => {\n this.healthyTimeout_ = null;\n if (!this.isHealthy_) {\n if (\n this.conn_ &&\n this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE\n ) {\n this.log_(\n 'Connection exceeded healthy timeout but has received ' +\n this.conn_.bytesReceived +\n ' bytes. Marking connection healthy.'\n );\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n } else if (\n this.conn_ &&\n this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE\n ) {\n this.log_(\n 'Connection exceeded healthy timeout but has sent ' +\n this.conn_.bytesSent +\n ' bytes. Leaving connection alive.'\n );\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\n // the server.\n } else {\n this.log_('Closing unhealthy connection after timeout.');\n this.close();\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(healthyTimeoutMS)) as any;\n }\n }\n\n private nextTransportId_(): string {\n return 'c:' + this.id + ':' + this.connectionCount++;\n }\n\n private disconnReceiver_(conn) {\n return everConnected => {\n if (conn === this.conn_) {\n this.onConnectionLost_(everConnected);\n } else if (conn === this.secondaryConn_) {\n this.log_('Secondary connection lost.');\n this.onSecondaryConnectionLost_();\n } else {\n this.log_('closing an old connection');\n }\n };\n }\n\n private connReceiver_(conn: Transport) {\n return (message: Indexable) => {\n if (this.state_ !== RealtimeState.DISCONNECTED) {\n if (conn === this.rx_) {\n this.onPrimaryMessageReceived_(message);\n } else if (conn === this.secondaryConn_) {\n this.onSecondaryMessageReceived_(message);\n } else {\n this.log_('message on old connection');\n }\n }\n };\n }\n\n /**\n * @param dataMsg - An arbitrary data message to be sent to the server\n */\n sendRequest(dataMsg: object) {\n // wrap in a data message envelope and send it on\n const msg = { t: 'd', d: dataMsg };\n this.sendData_(msg);\n }\n\n tryCleanupConnection() {\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\n this.log_(\n 'cleaning up and promoting a connection: ' + this.secondaryConn_.connId\n );\n this.conn_ = this.secondaryConn_;\n this.secondaryConn_ = null;\n // the server will shutdown the old connection\n }\n }\n\n private onSecondaryControl_(controlData: { [k: string]: unknown }) {\n if (MESSAGE_TYPE in controlData) {\n const cmd = controlData[MESSAGE_TYPE] as string;\n if (cmd === SWITCH_ACK) {\n this.upgradeIfSecondaryHealthy_();\n } else if (cmd === CONTROL_RESET) {\n // Most likely the session wasn't valid. Abandon the switch attempt\n this.log_('Got a reset on secondary, closing it');\n this.secondaryConn_.close();\n // If we were already using this connection for something, than we need to fully close\n if (\n this.tx_ === this.secondaryConn_ ||\n this.rx_ === this.secondaryConn_\n ) {\n this.close();\n }\n } else if (cmd === CONTROL_PONG) {\n this.log_('got pong on secondary.');\n this.secondaryResponsesRequired_--;\n this.upgradeIfSecondaryHealthy_();\n }\n }\n }\n\n private onSecondaryMessageReceived_(parsedData: Indexable) {\n const layer: string = requireKey('t', parsedData) as string;\n const data: unknown = requireKey('d', parsedData);\n if (layer === 'c') {\n this.onSecondaryControl_(data as Indexable);\n } else if (layer === 'd') {\n // got a data message, but we're still second connection. Need to buffer it up\n this.pendingDataMessages.push(data);\n } else {\n throw new Error('Unknown protocol layer: ' + layer);\n }\n }\n\n private upgradeIfSecondaryHealthy_() {\n if (this.secondaryResponsesRequired_ <= 0) {\n this.log_('Secondary connection is healthy.');\n this.isHealthy_ = true;\n this.secondaryConn_.markConnectionHealthy();\n this.proceedWithUpgrade_();\n } else {\n // Send a ping to make sure the connection is healthy.\n this.log_('sending ping on secondary.');\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\n }\n }\n\n private proceedWithUpgrade_() {\n // tell this connection to consider itself open\n this.secondaryConn_.start();\n // send ack\n this.log_('sending client ack on secondary');\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\n\n // send end packet on primary transport, switch to sending on this one\n // can receive on this one, buffer responses until end received on primary transport\n this.log_('Ending transmission on primary');\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\n this.tx_ = this.secondaryConn_;\n\n this.tryCleanupConnection();\n }\n\n private onPrimaryMessageReceived_(parsedData: { [k: string]: unknown }) {\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\n const layer: string = requireKey('t', parsedData) as string;\n const data: unknown = requireKey('d', parsedData);\n if (layer === 'c') {\n this.onControl_(data as { [k: string]: unknown });\n } else if (layer === 'd') {\n this.onDataMessage_(data);\n }\n }\n\n private onDataMessage_(message: unknown) {\n this.onPrimaryResponse_();\n\n // We don't do anything with data messages, just kick them up a level\n this.onMessage_(message);\n }\n\n private onPrimaryResponse_() {\n if (!this.isHealthy_) {\n this.primaryResponsesRequired_--;\n if (this.primaryResponsesRequired_ <= 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n }\n }\n }\n\n private onControl_(controlData: { [k: string]: unknown }) {\n const cmd: string = requireKey(MESSAGE_TYPE, controlData) as string;\n if (MESSAGE_DATA in controlData) {\n const payload = controlData[MESSAGE_DATA];\n if (cmd === SERVER_HELLO) {\n const handshakePayload = {\n ...(payload as {\n ts: number;\n v: string;\n h: string;\n s: string;\n })\n };\n if (this.repoInfo_.isUsingEmulator) {\n // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes.\n handshakePayload.h = this.repoInfo_.host;\n }\n this.onHandshake_(handshakePayload);\n } else if (cmd === END_TRANSMISSION) {\n this.log_('recvd end transmission on primary');\n this.rx_ = this.secondaryConn_;\n for (let i = 0; i < this.pendingDataMessages.length; ++i) {\n this.onDataMessage_(this.pendingDataMessages[i]);\n }\n this.pendingDataMessages = [];\n this.tryCleanupConnection();\n } else if (cmd === CONTROL_SHUTDOWN) {\n // This was previously the 'onKill' callback passed to the lower-level connection\n // payload in this case is the reason for the shutdown. Generally a human-readable error\n this.onConnectionShutdown_(payload as string);\n } else if (cmd === CONTROL_RESET) {\n // payload in this case is the host we should contact\n this.onReset_(payload as string);\n } else if (cmd === CONTROL_ERROR) {\n error('Server Error: ' + payload);\n } else if (cmd === CONTROL_PONG) {\n this.log_('got pong on primary.');\n this.onPrimaryResponse_();\n this.sendPingOnPrimaryIfNecessary_();\n } else {\n error('Unknown control packet command: ' + cmd);\n }\n }\n }\n\n /**\n * @param handshake - The handshake data returned from the server\n */\n private onHandshake_(handshake: {\n ts: number;\n v: string;\n h: string;\n s: string;\n }): void {\n const timestamp = handshake.ts;\n const version = handshake.v;\n const host = handshake.h;\n this.sessionId = handshake.s;\n this.repoInfo_.host = host;\n // if we've already closed the connection, then don't bother trying to progress further\n if (this.state_ === RealtimeState.CONNECTING) {\n this.conn_.start();\n this.onConnectionEstablished_(this.conn_, timestamp);\n if (PROTOCOL_VERSION !== version) {\n warn('Protocol version mismatch detected');\n }\n // TODO: do we want to upgrade? when? maybe a delay?\n this.tryStartUpgrade_();\n }\n }\n\n private tryStartUpgrade_() {\n const conn = this.transportManager_.upgradeTransport();\n if (conn) {\n this.startUpgrade_(conn);\n }\n }\n\n private startUpgrade_(conn: TransportConstructor) {\n this.secondaryConn_ = new conn(\n this.nextTransportId_(),\n this.repoInfo_,\n this.applicationId_,\n this.appCheckToken_,\n this.authToken_,\n this.sessionId\n );\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.secondaryResponsesRequired_ =\n conn['responsesRequiredToBeHealthy'] || 0;\n\n const onMessage = this.connReceiver_(this.secondaryConn_);\n const onDisconnect = this.disconnReceiver_(this.secondaryConn_);\n this.secondaryConn_.open(onMessage, onDisconnect);\n\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\n setTimeoutNonBlocking(() => {\n if (this.secondaryConn_) {\n this.log_('Timed out trying to upgrade.');\n this.secondaryConn_.close();\n }\n }, Math.floor(UPGRADE_TIMEOUT));\n }\n\n private onReset_(host: string) {\n this.log_('Reset packet received. New host: ' + host);\n this.repoInfo_.host = host;\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\n // We don't currently support resets after the connection has already been established\n if (this.state_ === RealtimeState.CONNECTED) {\n this.close();\n } else {\n // Close whatever connections we have open and start again.\n this.closeConnections_();\n this.start_();\n }\n }\n\n private onConnectionEstablished_(conn: Transport, timestamp: number) {\n this.log_('Realtime connection established.');\n this.conn_ = conn;\n this.state_ = RealtimeState.CONNECTED;\n\n if (this.onReady_) {\n this.onReady_(timestamp, this.sessionId);\n this.onReady_ = null;\n }\n\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\n // send some pings.\n if (this.primaryResponsesRequired_ === 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n } else {\n setTimeoutNonBlocking(() => {\n this.sendPingOnPrimaryIfNecessary_();\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\n }\n }\n\n private sendPingOnPrimaryIfNecessary_() {\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\n if (!this.isHealthy_ && this.state_ === RealtimeState.CONNECTED) {\n this.log_('sending ping on primary.');\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\n }\n }\n\n private onSecondaryConnectionLost_() {\n const conn = this.secondaryConn_;\n this.secondaryConn_ = null;\n if (this.tx_ === conn || this.rx_ === conn) {\n // we are relying on this connection already in some capacity. Therefore, a failure is real\n this.close();\n }\n }\n\n /**\n * @param everConnected - Whether or not the connection ever reached a server. Used to determine if\n * we should flush the host cache\n */\n private onConnectionLost_(everConnected: boolean) {\n this.conn_ = null;\n\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\n if (!everConnected && this.state_ === RealtimeState.CONNECTING) {\n this.log_('Realtime connection failed.');\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\n if (this.repoInfo_.isCacheableHost()) {\n PersistentStorage.remove('host:' + this.repoInfo_.host);\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\n this.repoInfo_.internalHost = this.repoInfo_.host;\n }\n } else if (this.state_ === RealtimeState.CONNECTED) {\n this.log_('Realtime connection lost.');\n }\n\n this.close();\n }\n\n private onConnectionShutdown_(reason: string) {\n this.log_('Connection shutdown command received. Shutting down...');\n\n if (this.onKill_) {\n this.onKill_(reason);\n this.onKill_ = null;\n }\n\n // We intentionally don't want to fire onDisconnect (kill is a different case),\n // so clear the callback.\n this.onDisconnect_ = null;\n\n this.close();\n }\n\n private sendData_(data: object) {\n if (this.state_ !== RealtimeState.CONNECTED) {\n throw 'Connection is not connected';\n } else {\n this.tx_.send(data);\n }\n }\n\n /**\n * Cleans up this connection, calling the appropriate callbacks\n */\n close() {\n if (this.state_ !== RealtimeState.DISCONNECTED) {\n this.log_('Closing realtime connection.');\n this.state_ = RealtimeState.DISCONNECTED;\n\n this.closeConnections_();\n\n if (this.onDisconnect_) {\n this.onDisconnect_();\n this.onDisconnect_ = null;\n }\n }\n }\n\n private closeConnections_() {\n this.log_('Shutting down all connections');\n if (this.conn_) {\n this.conn_.close();\n this.conn_ = null;\n }\n\n if (this.secondaryConn_) {\n this.secondaryConn_.close();\n this.secondaryConn_ = null;\n }\n\n if (this.healthyTimeout_) {\n clearTimeout(this.healthyTimeout_);\n this.healthyTimeout_ = null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QueryContext } from './view/EventRegistration';\n\n/**\n * Interface defining the set of actions that can be performed against the Firebase server\n * (basically corresponds to our wire protocol).\n *\n * @interface\n */\nexport abstract class ServerActions {\n abstract listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ): void;\n\n /**\n * Remove a listen.\n */\n abstract unlisten(query: QueryContext, tag: number | null): void;\n\n /**\n * Get the server value satisfying this query.\n */\n abstract get(query: QueryContext): Promise;\n\n put(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void,\n hash?: string\n ) {}\n\n merge(\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {}\n\n /**\n * Refreshes the auth token for the current connection.\n * @param token - The authentication token\n */\n refreshAuthToken(token: string) {}\n\n /**\n * Refreshes the app check token for the current connection.\n * @param token The app check token\n */\n refreshAppCheckToken(token: string) {}\n\n onDisconnectPut(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n onDisconnectMerge(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n onDisconnectCancel(\n pathString: string,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n reportStats(stats: { [k: string]: unknown }) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\n/**\n * Base class to be used if you want to emit events. Call the constructor with\n * the set of allowed event names.\n */\nexport abstract class EventEmitter {\n private listeners_: {\n [eventType: string]: Array<{\n callback(...args: unknown[]): void;\n context: unknown;\n }>;\n } = {};\n\n constructor(private allowedEvents_: string[]) {\n assert(\n Array.isArray(allowedEvents_) && allowedEvents_.length > 0,\n 'Requires a non-empty array'\n );\n }\n\n /**\n * To be overridden by derived classes in order to fire an initial event when\n * somebody subscribes for data.\n *\n * @returns {Array.<*>} Array of parameters to trigger initial event with.\n */\n abstract getInitialEvent(eventType: string): unknown[];\n\n /**\n * To be called by derived classes to trigger events.\n */\n protected trigger(eventType: string, ...varArgs: unknown[]) {\n if (Array.isArray(this.listeners_[eventType])) {\n // Clone the list, since callbacks could add/remove listeners.\n const listeners = [...this.listeners_[eventType]];\n\n for (let i = 0; i < listeners.length; i++) {\n listeners[i].callback.apply(listeners[i].context, varArgs);\n }\n }\n }\n\n on(eventType: string, callback: (a: unknown) => void, context: unknown) {\n this.validateEventType_(eventType);\n this.listeners_[eventType] = this.listeners_[eventType] || [];\n this.listeners_[eventType].push({ callback, context });\n\n const eventData = this.getInitialEvent(eventType);\n if (eventData) {\n callback.apply(context, eventData);\n }\n }\n\n off(eventType: string, callback: (a: unknown) => void, context: unknown) {\n this.validateEventType_(eventType);\n const listeners = this.listeners_[eventType] || [];\n for (let i = 0; i < listeners.length; i++) {\n if (\n listeners[i].callback === callback &&\n (!context || context === listeners[i].context)\n ) {\n listeners.splice(i, 1);\n return;\n }\n }\n }\n\n private validateEventType_(eventType: string) {\n assert(\n this.allowedEvents_.find(et => {\n return et === eventType;\n }),\n 'Unknown event: ' + eventType\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, isMobileCordova } from '@firebase/util';\n\nimport { EventEmitter } from './EventEmitter';\n\n/**\n * Monitors online state (as reported by window.online/offline events).\n *\n * The expectation is that this could have many false positives (thinks we are online\n * when we're not), but no false negatives. So we can safely use it to determine when\n * we definitely cannot reach the internet.\n */\nexport class OnlineMonitor extends EventEmitter {\n private online_ = true;\n\n static getInstance() {\n return new OnlineMonitor();\n }\n\n constructor() {\n super(['online']);\n\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\n // It would seem that the 'online' event does not always fire consistently. So we disable it\n // for Cordova.\n if (\n typeof window !== 'undefined' &&\n typeof window.addEventListener !== 'undefined' &&\n !isMobileCordova()\n ) {\n window.addEventListener(\n 'online',\n () => {\n if (!this.online_) {\n this.online_ = true;\n this.trigger('online', true);\n }\n },\n false\n );\n\n window.addEventListener(\n 'offline',\n () => {\n if (this.online_) {\n this.online_ = false;\n this.trigger('online', false);\n }\n },\n false\n );\n }\n }\n\n getInitialEvent(eventType: string): boolean[] {\n assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n }\n\n currentlyOnline(): boolean {\n return this.online_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { stringLength } from '@firebase/util';\n\nimport { nameCompare } from './util';\n\n/** Maximum key depth. */\nconst MAX_PATH_DEPTH = 32;\n\n/** Maximum number of (UTF8) bytes in a Firebase path. */\nconst MAX_PATH_LENGTH_BYTES = 768;\n\n/**\n * An immutable object representing a parsed path. It's immutable so that you\n * can pass them around to other functions without worrying about them changing\n * it.\n */\n\nexport class Path {\n pieces_: string[];\n pieceNum_: number;\n\n /**\n * @param pathOrString - Path string to parse, or another path, or the raw\n * tokens array\n */\n constructor(pathOrString: string | string[], pieceNum?: number) {\n if (pieceNum === void 0) {\n this.pieces_ = (pathOrString as string).split('/');\n\n // Remove empty pieces.\n let copyTo = 0;\n for (let i = 0; i < this.pieces_.length; i++) {\n if (this.pieces_[i].length > 0) {\n this.pieces_[copyTo] = this.pieces_[i];\n copyTo++;\n }\n }\n this.pieces_.length = copyTo;\n\n this.pieceNum_ = 0;\n } else {\n this.pieces_ = pathOrString as string[];\n this.pieceNum_ = pieceNum;\n }\n }\n\n toString(): string {\n let pathString = '';\n for (let i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '') {\n pathString += '/' + this.pieces_[i];\n }\n }\n\n return pathString || '/';\n }\n}\n\nexport function newEmptyPath(): Path {\n return new Path('');\n}\n\nexport function pathGetFront(path: Path): string | null {\n if (path.pieceNum_ >= path.pieces_.length) {\n return null;\n }\n\n return path.pieces_[path.pieceNum_];\n}\n\n/**\n * @returns The number of segments in this path\n */\nexport function pathGetLength(path: Path): number {\n return path.pieces_.length - path.pieceNum_;\n}\n\nexport function pathPopFront(path: Path): Path {\n let pieceNum = path.pieceNum_;\n if (pieceNum < path.pieces_.length) {\n pieceNum++;\n }\n return new Path(path.pieces_, pieceNum);\n}\n\nexport function pathGetBack(path: Path): string | null {\n if (path.pieceNum_ < path.pieces_.length) {\n return path.pieces_[path.pieces_.length - 1];\n }\n\n return null;\n}\n\nexport function pathToUrlEncodedString(path: Path): string {\n let pathString = '';\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\n if (path.pieces_[i] !== '') {\n pathString += '/' + encodeURIComponent(String(path.pieces_[i]));\n }\n }\n\n return pathString || '/';\n}\n\n/**\n * Shallow copy of the parts of the path.\n *\n */\nexport function pathSlice(path: Path, begin: number = 0): string[] {\n return path.pieces_.slice(path.pieceNum_ + begin);\n}\n\nexport function pathParent(path: Path): Path | null {\n if (path.pieceNum_ >= path.pieces_.length) {\n return null;\n }\n\n const pieces = [];\n for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {\n pieces.push(path.pieces_[i]);\n }\n\n return new Path(pieces, 0);\n}\n\nexport function pathChild(path: Path, childPathObj: string | Path): Path {\n const pieces = [];\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\n pieces.push(path.pieces_[i]);\n }\n\n if (childPathObj instanceof Path) {\n for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\n pieces.push(childPathObj.pieces_[i]);\n }\n } else {\n const childPieces = childPathObj.split('/');\n for (let i = 0; i < childPieces.length; i++) {\n if (childPieces[i].length > 0) {\n pieces.push(childPieces[i]);\n }\n }\n }\n\n return new Path(pieces, 0);\n}\n\n/**\n * @returns True if there are no segments in this path\n */\nexport function pathIsEmpty(path: Path): boolean {\n return path.pieceNum_ >= path.pieces_.length;\n}\n\n/**\n * @returns The path from outerPath to innerPath\n */\nexport function newRelativePath(outerPath: Path, innerPath: Path): Path {\n const outer = pathGetFront(outerPath),\n inner = pathGetFront(innerPath);\n if (outer === null) {\n return innerPath;\n } else if (outer === inner) {\n return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));\n } else {\n throw new Error(\n 'INTERNAL ERROR: innerPath (' +\n innerPath +\n ') is not within ' +\n 'outerPath (' +\n outerPath +\n ')'\n );\n }\n}\n\n/**\n * @returns -1, 0, 1 if left is less, equal, or greater than the right.\n */\nexport function pathCompare(left: Path, right: Path): number {\n const leftKeys = pathSlice(left, 0);\n const rightKeys = pathSlice(right, 0);\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\n const cmp = nameCompare(leftKeys[i], rightKeys[i]);\n if (cmp !== 0) {\n return cmp;\n }\n }\n if (leftKeys.length === rightKeys.length) {\n return 0;\n }\n return leftKeys.length < rightKeys.length ? -1 : 1;\n}\n\n/**\n * @returns true if paths are the same.\n */\nexport function pathEquals(path: Path, other: Path): boolean {\n if (pathGetLength(path) !== pathGetLength(other)) {\n return false;\n }\n\n for (\n let i = path.pieceNum_, j = other.pieceNum_;\n i <= path.pieces_.length;\n i++, j++\n ) {\n if (path.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * @returns True if this path is a parent of (or the same as) other\n */\nexport function pathContains(path: Path, other: Path): boolean {\n let i = path.pieceNum_;\n let j = other.pieceNum_;\n if (pathGetLength(path) > pathGetLength(other)) {\n return false;\n }\n while (i < path.pieces_.length) {\n if (path.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n ++i;\n ++j;\n }\n return true;\n}\n\n/**\n * Dynamic (mutable) path used to count path lengths.\n *\n * This class is used to efficiently check paths for valid\n * length (in UTF8 bytes) and depth (used in path validation).\n *\n * Throws Error exception if path is ever invalid.\n *\n * The definition of a path always begins with '/'.\n */\nexport class ValidationPath {\n parts_: string[];\n /** Initialize to number of '/' chars needed in path. */\n byteLength_: number;\n\n /**\n * @param path - Initial Path.\n * @param errorPrefix_ - Prefix for any error messages.\n */\n constructor(path: Path, public errorPrefix_: string) {\n this.parts_ = pathSlice(path, 0);\n /** Initialize to number of '/' chars needed in path. */\n this.byteLength_ = Math.max(1, this.parts_.length);\n\n for (let i = 0; i < this.parts_.length; i++) {\n this.byteLength_ += stringLength(this.parts_[i]);\n }\n validationPathCheckValid(this);\n }\n}\n\nexport function validationPathPush(\n validationPath: ValidationPath,\n child: string\n): void {\n // Count the needed '/'\n if (validationPath.parts_.length > 0) {\n validationPath.byteLength_ += 1;\n }\n validationPath.parts_.push(child);\n validationPath.byteLength_ += stringLength(child);\n validationPathCheckValid(validationPath);\n}\n\nexport function validationPathPop(validationPath: ValidationPath): void {\n const last = validationPath.parts_.pop();\n validationPath.byteLength_ -= stringLength(last);\n // Un-count the previous '/'\n if (validationPath.parts_.length > 0) {\n validationPath.byteLength_ -= 1;\n }\n}\n\nfunction validationPathCheckValid(validationPath: ValidationPath): void {\n if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {\n throw new Error(\n validationPath.errorPrefix_ +\n 'has a key path longer than ' +\n MAX_PATH_LENGTH_BYTES +\n ' bytes (' +\n validationPath.byteLength_ +\n ').'\n );\n }\n if (validationPath.parts_.length > MAX_PATH_DEPTH) {\n throw new Error(\n validationPath.errorPrefix_ +\n 'path specified exceeds the maximum depth that can be written (' +\n MAX_PATH_DEPTH +\n ') or object contains a cycle ' +\n validationPathToErrorString(validationPath)\n );\n }\n}\n\n/**\n * String for use in error messages - uses '.' notation for path.\n */\nexport function validationPathToErrorString(\n validationPath: ValidationPath\n): string {\n if (validationPath.parts_.length === 0) {\n return '';\n }\n return \"in property '\" + validationPath.parts_.join('.') + \"'\";\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { EventEmitter } from './EventEmitter';\n\ndeclare const document: Document;\n\nexport class VisibilityMonitor extends EventEmitter {\n private visible_: boolean;\n\n static getInstance() {\n return new VisibilityMonitor();\n }\n\n constructor() {\n super(['visible']);\n let hidden: string;\n let visibilityChange: string;\n if (\n typeof document !== 'undefined' &&\n typeof document.addEventListener !== 'undefined'\n ) {\n if (typeof document['hidden'] !== 'undefined') {\n // Opera 12.10 and Firefox 18 and later support\n visibilityChange = 'visibilitychange';\n hidden = 'hidden';\n } else if (typeof document['mozHidden'] !== 'undefined') {\n visibilityChange = 'mozvisibilitychange';\n hidden = 'mozHidden';\n } else if (typeof document['msHidden'] !== 'undefined') {\n visibilityChange = 'msvisibilitychange';\n hidden = 'msHidden';\n } else if (typeof document['webkitHidden'] !== 'undefined') {\n visibilityChange = 'webkitvisibilitychange';\n hidden = 'webkitHidden';\n }\n }\n\n // Initially, we always assume we are visible. This ensures that in browsers\n // without page visibility support or in cases where we are never visible\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n // reconnects\n this.visible_ = true;\n\n if (visibilityChange) {\n document.addEventListener(\n visibilityChange,\n () => {\n const visible = !document[hidden];\n if (visible !== this.visible_) {\n this.visible_ = visible;\n this.trigger('visible', visible);\n }\n },\n false\n );\n }\n }\n\n getInitialEvent(eventType: string): boolean[] {\n assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n contains,\n Deferred,\n isEmpty,\n isMobileCordova,\n isNodeSdk,\n isReactNative,\n isValidFormat,\n safeGet,\n stringify,\n isAdmin\n} from '@firebase/util';\n\nimport { Connection } from '../realtime/Connection';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { OnlineMonitor } from './util/OnlineMonitor';\nimport { Path } from './util/Path';\nimport { error, log, logWrapper, warn, ObjectToUniqueKey } from './util/util';\nimport { VisibilityMonitor } from './util/VisibilityMonitor';\nimport { SDK_VERSION } from './version';\nimport { QueryContext } from './view/EventRegistration';\n\nconst RECONNECT_MIN_DELAY = 1000;\nconst RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\nconst RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\nconst RECONNECT_DELAY_MULTIPLIER = 1.3;\nconst RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\nconst SERVER_KILL_INTERRUPT_REASON = 'server_kill';\n\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\nconst INVALID_TOKEN_THRESHOLD = 3;\n\ninterface ListenSpec {\n onComplete(s: string, p?: unknown): void;\n\n hashFn(): string;\n\n query: QueryContext;\n tag: number | null;\n}\n\ninterface OnDisconnectRequest {\n pathString: string;\n action: string;\n data: unknown;\n onComplete?: (a: string, b: string) => void;\n}\n\ninterface OutstandingPut {\n action: string;\n request: object;\n queued?: boolean;\n onComplete: (a: string, b?: string) => void;\n}\n\ninterface OutstandingGet {\n request: object;\n onComplete: (response: { [k: string]: unknown }) => void;\n}\n\n/**\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\n *\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\n * in quotes to make sure the closure compiler does not minify them.\n */\nexport class PersistentConnection extends ServerActions {\n // Used for diagnostic logging.\n id = PersistentConnection.nextPersistentConnectionId_++;\n private log_ = logWrapper('p:' + this.id + ':');\n\n private interruptReasons_: { [reason: string]: boolean } = {};\n private readonly listens: Map<\n /* path */ string,\n Map\n > = new Map();\n private outstandingPuts_: OutstandingPut[] = [];\n private outstandingGets_: OutstandingGet[] = [];\n private outstandingPutCount_ = 0;\n private outstandingGetCount_ = 0;\n private onDisconnectRequestQueue_: OnDisconnectRequest[] = [];\n private connected_ = false;\n private reconnectDelay_ = RECONNECT_MIN_DELAY;\n private maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\n private securityDebugCallback_: ((a: object) => void) | null = null;\n lastSessionId: string | null = null;\n\n private establishConnectionTimer_: number | null = null;\n\n private visible_: boolean = false;\n\n // Before we get connected, we keep a queue of pending messages to send.\n private requestCBHash_: { [k: number]: (a: unknown) => void } = {};\n private requestNumber_ = 0;\n\n private realtime_: {\n sendRequest(a: object): void;\n close(): void;\n } | null = null;\n\n private authToken_: string | null = null;\n private appCheckToken_: string | null = null;\n private forceTokenRefresh_ = false;\n private invalidAuthTokenCount_ = 0;\n private invalidAppCheckTokenCount_ = 0;\n\n private firstConnection_ = true;\n private lastConnectionAttemptTime_: number | null = null;\n private lastConnectionEstablishedTime_: number | null = null;\n\n private static nextPersistentConnectionId_ = 0;\n\n /**\n * Counter for number of connections created. Mainly used for tagging in the logs\n */\n private static nextConnectionId_ = 0;\n\n /**\n * @param repoInfo_ - Data about the namespace we are connecting to\n * @param applicationId_ - The Firebase App ID for this project\n * @param onDataUpdate_ - A callback for new data from the server\n */\n constructor(\n private repoInfo_: RepoInfo,\n private applicationId_: string,\n private onDataUpdate_: (\n a: string,\n b: unknown,\n c: boolean,\n d: number | null\n ) => void,\n private onConnectStatus_: (a: boolean) => void,\n private onServerInfoUpdate_: (a: unknown) => void,\n private authTokenProvider_: AuthTokenProvider,\n private appCheckTokenProvider_: AppCheckTokenProvider,\n private authOverride_?: object | null\n ) {\n super();\n\n if (authOverride_ && !isNodeSdk()) {\n throw new Error(\n 'Auth override specified in options, but not supported on non Node.js platforms'\n );\n }\n\n VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);\n\n if (repoInfo_.host.indexOf('fblocal') === -1) {\n OnlineMonitor.getInstance().on('online', this.onOnline_, this);\n }\n }\n\n protected sendRequest(\n action: string,\n body: unknown,\n onResponse?: (a: unknown) => void\n ) {\n const curReqNum = ++this.requestNumber_;\n\n const msg = { r: curReqNum, a: action, b: body };\n this.log_(stringify(msg));\n assert(\n this.connected_,\n \"sendRequest call when we're not connected not allowed.\"\n );\n this.realtime_.sendRequest(msg);\n if (onResponse) {\n this.requestCBHash_[curReqNum] = onResponse;\n }\n }\n\n get(query: QueryContext): Promise {\n this.initConnection_();\n\n const deferred = new Deferred();\n const request = {\n p: query._path.toString(),\n q: query._queryObject\n };\n const outstandingGet = {\n action: 'g',\n request,\n onComplete: (message: { [k: string]: unknown }) => {\n const payload = message['d'] as string;\n if (message['s'] === 'ok') {\n deferred.resolve(payload);\n } else {\n deferred.reject(payload);\n }\n }\n };\n this.outstandingGets_.push(outstandingGet);\n this.outstandingGetCount_++;\n const index = this.outstandingGets_.length - 1;\n\n if (this.connected_) {\n this.sendGet_(index);\n }\n\n return deferred.promise;\n }\n\n listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ) {\n this.initConnection_();\n\n const queryId = query._queryIdentifier;\n const pathString = query._path.toString();\n this.log_('Listen called for ' + pathString + ' ' + queryId);\n if (!this.listens.has(pathString)) {\n this.listens.set(pathString, new Map());\n }\n assert(\n query._queryParams.isDefault() || !query._queryParams.loadsAllData(),\n 'listen() called for non-default but complete query'\n );\n assert(\n !this.listens.get(pathString)!.has(queryId),\n `listen() called twice for same path/queryId.`\n );\n const listenSpec: ListenSpec = {\n onComplete,\n hashFn: currentHashFn,\n query,\n tag\n };\n this.listens.get(pathString)!.set(queryId, listenSpec);\n\n if (this.connected_) {\n this.sendListen_(listenSpec);\n }\n }\n\n private sendGet_(index: number) {\n const get = this.outstandingGets_[index];\n this.sendRequest('g', get.request, (message: { [k: string]: unknown }) => {\n delete this.outstandingGets_[index];\n this.outstandingGetCount_--;\n if (this.outstandingGetCount_ === 0) {\n this.outstandingGets_ = [];\n }\n if (get.onComplete) {\n get.onComplete(message);\n }\n });\n }\n\n private sendListen_(listenSpec: ListenSpec) {\n const query = listenSpec.query;\n const pathString = query._path.toString();\n const queryId = query._queryIdentifier;\n this.log_('Listen on ' + pathString + ' for ' + queryId);\n const req: { [k: string]: unknown } = { /*path*/ p: pathString };\n\n const action = 'q';\n\n // Only bother to send query if it's non-default.\n if (listenSpec.tag) {\n req['q'] = query._queryObject;\n req['t'] = listenSpec.tag;\n }\n\n req[/*hash*/ 'h'] = listenSpec.hashFn();\n\n this.sendRequest(action, req, (message: { [k: string]: unknown }) => {\n const payload: unknown = message[/*data*/ 'd'];\n const status = message[/*status*/ 's'] as string;\n\n // print warnings in any case...\n PersistentConnection.warnOnListenWarnings_(payload, query);\n\n const currentListenSpec =\n this.listens.get(pathString) &&\n this.listens.get(pathString)!.get(queryId);\n // only trigger actions if the listen hasn't been removed and readded\n if (currentListenSpec === listenSpec) {\n this.log_('listen response', message);\n\n if (status !== 'ok') {\n this.removeListen_(pathString, queryId);\n }\n\n if (listenSpec.onComplete) {\n listenSpec.onComplete(status, payload);\n }\n }\n });\n }\n\n private static warnOnListenWarnings_(payload: unknown, query: QueryContext) {\n if (payload && typeof payload === 'object' && contains(payload, 'w')) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const warnings = safeGet(payload as any, 'w');\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\n const indexSpec =\n '\".indexOn\": \"' + query._queryParams.getIndex().toString() + '\"';\n const indexPath = query._path.toString();\n warn(\n `Using an unspecified index. Your data will be downloaded and ` +\n `filtered on the client. Consider adding ${indexSpec} at ` +\n `${indexPath} to your security rules for better performance.`\n );\n }\n }\n }\n\n refreshAuthToken(token: string) {\n this.authToken_ = token;\n this.log_('Auth token refreshed');\n if (this.authToken_) {\n this.tryAuth();\n } else {\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\n //the credential so we dont become authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unauth', {}, () => {});\n }\n }\n\n this.reduceReconnectDelayIfAdminCredential_(token);\n }\n\n private reduceReconnectDelayIfAdminCredential_(credential: string) {\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\n const isFirebaseSecret = credential && credential.length === 40;\n if (isFirebaseSecret || isAdmin(credential)) {\n this.log_(\n 'Admin auth credential detected. Reducing max reconnect time.'\n );\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n }\n }\n\n refreshAppCheckToken(token: string | null) {\n this.appCheckToken_ = token;\n this.log_('App check token refreshed');\n if (this.appCheckToken_) {\n this.tryAppCheck();\n } else {\n //If we're connected we want to let the server know to unauthenticate us.\n //If we're not connected, simply delete the credential so we dont become\n // authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unappeck', {}, () => {});\n }\n }\n }\n\n /**\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\n * a auth revoked (the connection is closed).\n */\n tryAuth() {\n if (this.connected_ && this.authToken_) {\n const token = this.authToken_;\n const authMethod = isValidFormat(token) ? 'auth' : 'gauth';\n const requestData: { [k: string]: unknown } = { cred: token };\n if (this.authOverride_ === null) {\n requestData['noauth'] = true;\n } else if (typeof this.authOverride_ === 'object') {\n requestData['authvar'] = this.authOverride_;\n }\n this.sendRequest(\n authMethod,\n requestData,\n (res: { [k: string]: unknown }) => {\n const status = res[/*status*/ 's'] as string;\n const data = (res[/*data*/ 'd'] as string) || 'error';\n\n if (this.authToken_ === token) {\n if (status === 'ok') {\n this.invalidAuthTokenCount_ = 0;\n } else {\n // Triggers reconnect and force refresh for auth token\n this.onAuthRevoked_(status, data);\n }\n }\n }\n );\n }\n }\n\n /**\n * Attempts to authenticate with the given token. If the authentication\n * attempt fails, it's triggered like the token was revoked (the connection is\n * closed).\n */\n tryAppCheck() {\n if (this.connected_ && this.appCheckToken_) {\n this.sendRequest(\n 'appcheck',\n { 'token': this.appCheckToken_ },\n (res: { [k: string]: unknown }) => {\n const status = res[/*status*/ 's'] as string;\n const data = (res[/*data*/ 'd'] as string) || 'error';\n if (status === 'ok') {\n this.invalidAppCheckTokenCount_ = 0;\n } else {\n this.onAppCheckRevoked_(status, data);\n }\n }\n );\n }\n }\n\n /**\n * @inheritDoc\n */\n unlisten(query: QueryContext, tag: number | null) {\n const pathString = query._path.toString();\n const queryId = query._queryIdentifier;\n\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\n\n assert(\n query._queryParams.isDefault() || !query._queryParams.loadsAllData(),\n 'unlisten() called for non-default but complete query'\n );\n const listen = this.removeListen_(pathString, queryId);\n if (listen && this.connected_) {\n this.sendUnlisten_(pathString, queryId, query._queryObject, tag);\n }\n }\n\n private sendUnlisten_(\n pathString: string,\n queryId: string,\n queryObj: object,\n tag: number | null\n ) {\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\n\n const req: { [k: string]: unknown } = { /*path*/ p: pathString };\n const action = 'n';\n // Only bother sending queryId if it's non-default.\n if (tag) {\n req['q'] = queryObj;\n req['t'] = tag;\n }\n\n this.sendRequest(action, req);\n }\n\n onDisconnectPut(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\n\n if (this.connected_) {\n this.sendOnDisconnect_('o', pathString, data, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'o',\n data,\n onComplete\n });\n }\n }\n\n onDisconnectMerge(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\n\n if (this.connected_) {\n this.sendOnDisconnect_('om', pathString, data, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'om',\n data,\n onComplete\n });\n }\n }\n\n onDisconnectCancel(\n pathString: string,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\n\n if (this.connected_) {\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'oc',\n data: null,\n onComplete\n });\n }\n }\n\n private sendOnDisconnect_(\n action: string,\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string) => void\n ) {\n const request = { /*path*/ p: pathString, /*data*/ d: data };\n this.log_('onDisconnect ' + action, request);\n this.sendRequest(action, request, (response: { [k: string]: unknown }) => {\n if (onComplete) {\n setTimeout(() => {\n onComplete(\n response[/*status*/ 's'] as string,\n response[/* data */ 'd'] as string\n );\n }, Math.floor(0));\n }\n });\n }\n\n put(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void,\n hash?: string\n ) {\n this.putInternal('p', pathString, data, onComplete, hash);\n }\n\n merge(\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {\n this.putInternal('m', pathString, data, onComplete, hash);\n }\n\n putInternal(\n action: string,\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {\n this.initConnection_();\n\n const request: { [k: string]: unknown } = {\n /*path*/ p: pathString,\n /*data*/ d: data\n };\n\n if (hash !== undefined) {\n request[/*hash*/ 'h'] = hash;\n }\n\n // TODO: Only keep track of the most recent put for a given path?\n this.outstandingPuts_.push({\n action,\n request,\n onComplete\n });\n\n this.outstandingPutCount_++;\n const index = this.outstandingPuts_.length - 1;\n\n if (this.connected_) {\n this.sendPut_(index);\n } else {\n this.log_('Buffering put: ' + pathString);\n }\n }\n\n private sendPut_(index: number) {\n const action = this.outstandingPuts_[index].action;\n const request = this.outstandingPuts_[index].request;\n const onComplete = this.outstandingPuts_[index].onComplete;\n this.outstandingPuts_[index].queued = this.connected_;\n\n this.sendRequest(action, request, (message: { [k: string]: unknown }) => {\n this.log_(action + ' response', message);\n\n delete this.outstandingPuts_[index];\n this.outstandingPutCount_--;\n\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0) {\n this.outstandingPuts_ = [];\n }\n\n if (onComplete) {\n onComplete(\n message[/*status*/ 's'] as string,\n message[/* data */ 'd'] as string\n );\n }\n });\n }\n\n reportStats(stats: { [k: string]: unknown }) {\n // If we're not connected, we just drop the stats.\n if (this.connected_) {\n const request = { /*counters*/ c: stats };\n this.log_('reportStats', request);\n\n this.sendRequest(/*stats*/ 's', request, result => {\n const status = result[/*status*/ 's'];\n if (status !== 'ok') {\n const errorReason = result[/* data */ 'd'];\n this.log_('reportStats', 'Error sending stats: ' + errorReason);\n }\n });\n }\n }\n\n private onDataMessage_(message: { [k: string]: unknown }) {\n if ('r' in message) {\n // this is a response\n this.log_('from server: ' + stringify(message));\n const reqNum = message['r'] as string;\n const onResponse = this.requestCBHash_[reqNum];\n if (onResponse) {\n delete this.requestCBHash_[reqNum];\n onResponse(message[/*body*/ 'b']);\n }\n } else if ('error' in message) {\n throw 'A server-side error has occurred: ' + message['error'];\n } else if ('a' in message) {\n // a and b are action and body, respectively\n this.onDataPush_(message['a'] as string, message['b'] as {});\n }\n }\n\n private onDataPush_(action: string, body: { [k: string]: unknown }) {\n this.log_('handleServerMessage', action, body);\n if (action === 'd') {\n this.onDataUpdate_(\n body[/*path*/ 'p'] as string,\n body[/*data*/ 'd'],\n /*isMerge*/ false,\n body['t'] as number\n );\n } else if (action === 'm') {\n this.onDataUpdate_(\n body[/*path*/ 'p'] as string,\n body[/*data*/ 'd'],\n /*isMerge=*/ true,\n body['t'] as number\n );\n } else if (action === 'c') {\n this.onListenRevoked_(\n body[/*path*/ 'p'] as string,\n body[/*query*/ 'q'] as unknown[]\n );\n } else if (action === 'ac') {\n this.onAuthRevoked_(\n body[/*status code*/ 's'] as string,\n body[/* explanation */ 'd'] as string\n );\n } else if (action === 'apc') {\n this.onAppCheckRevoked_(\n body[/*status code*/ 's'] as string,\n body[/* explanation */ 'd'] as string\n );\n } else if (action === 'sd') {\n this.onSecurityDebugPacket_(body);\n } else {\n error(\n 'Unrecognized action received from server: ' +\n stringify(action) +\n '\\nAre you using the latest client?'\n );\n }\n }\n\n private onReady_(timestamp: number, sessionId: string) {\n this.log_('connection ready');\n this.connected_ = true;\n this.lastConnectionEstablishedTime_ = new Date().getTime();\n this.handleTimestamp_(timestamp);\n this.lastSessionId = sessionId;\n if (this.firstConnection_) {\n this.sendConnectStats_();\n }\n this.restoreState_();\n this.firstConnection_ = false;\n this.onConnectStatus_(true);\n }\n\n private scheduleConnect_(timeout: number) {\n assert(\n !this.realtime_,\n \"Scheduling a connect when we're already connected/ing?\"\n );\n\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n }\n\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\n\n this.establishConnectionTimer_ = setTimeout(() => {\n this.establishConnectionTimer_ = null;\n this.establishConnection_();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(timeout)) as any;\n }\n\n private initConnection_() {\n if (!this.realtime_ && this.firstConnection_) {\n this.scheduleConnect_(0);\n }\n }\n\n private onVisible_(visible: boolean) {\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\n if (\n visible &&\n !this.visible_ &&\n this.reconnectDelay_ === this.maxReconnectDelay_\n ) {\n this.log_('Window became visible. Reducing delay.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n this.visible_ = visible;\n }\n\n private onOnline_(online: boolean) {\n if (online) {\n this.log_('Browser went online.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n } else {\n this.log_('Browser went offline. Killing connection.');\n if (this.realtime_) {\n this.realtime_.close();\n }\n }\n }\n\n private onRealtimeDisconnect_() {\n this.log_('data client disconnected');\n this.connected_ = false;\n this.realtime_ = null;\n\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\n this.cancelSentTransactions_();\n\n // Clear out the pending requests.\n this.requestCBHash_ = {};\n\n if (this.shouldReconnect_()) {\n if (!this.visible_) {\n this.log_(\"Window isn't visible. Delaying reconnect.\");\n this.reconnectDelay_ = this.maxReconnectDelay_;\n this.lastConnectionAttemptTime_ = new Date().getTime();\n } else if (this.lastConnectionEstablishedTime_) {\n // If we've been connected long enough, reset reconnect delay to minimum.\n const timeSinceLastConnectSucceeded =\n new Date().getTime() - this.lastConnectionEstablishedTime_;\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n }\n this.lastConnectionEstablishedTime_ = null;\n }\n\n const timeSinceLastConnectAttempt = Math.max(\n 0,\n new Date().getTime() - this.lastConnectionAttemptTime_\n );\n let reconnectDelay = Math.max(\n 0,\n this.reconnectDelay_ - timeSinceLastConnectAttempt\n );\n reconnectDelay = Math.random() * reconnectDelay;\n\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\n this.scheduleConnect_(reconnectDelay);\n\n // Adjust reconnect delay for next time.\n this.reconnectDelay_ = Math.min(\n this.maxReconnectDelay_,\n this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER\n );\n }\n this.onConnectStatus_(false);\n }\n\n private async establishConnection_() {\n if (this.shouldReconnect_()) {\n this.log_('Making a connection attempt');\n this.lastConnectionAttemptTime_ = new Date().getTime();\n this.lastConnectionEstablishedTime_ = null;\n const onDataMessage = this.onDataMessage_.bind(this);\n const onReady = this.onReady_.bind(this);\n const onDisconnect = this.onRealtimeDisconnect_.bind(this);\n const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;\n const lastSessionId = this.lastSessionId;\n let canceled = false;\n let connection: Connection | null = null;\n const closeFn = function () {\n if (connection) {\n connection.close();\n } else {\n canceled = true;\n onDisconnect();\n }\n };\n const sendRequestFn = function (msg: object) {\n assert(\n connection,\n \"sendRequest call when we're not connected not allowed.\"\n );\n connection.sendRequest(msg);\n };\n\n this.realtime_ = {\n close: closeFn,\n sendRequest: sendRequestFn\n };\n\n const forceRefresh = this.forceTokenRefresh_;\n this.forceTokenRefresh_ = false;\n\n try {\n // First fetch auth and app check token, and establish connection after\n // fetching the token was successful\n const [authToken, appCheckToken] = await Promise.all([\n this.authTokenProvider_.getToken(forceRefresh),\n this.appCheckTokenProvider_.getToken(forceRefresh)\n ]);\n\n if (!canceled) {\n log('getToken() completed. Creating connection.');\n this.authToken_ = authToken && authToken.accessToken;\n this.appCheckToken_ = appCheckToken && appCheckToken.token;\n connection = new Connection(\n connId,\n this.repoInfo_,\n this.applicationId_,\n this.appCheckToken_,\n this.authToken_,\n onDataMessage,\n onReady,\n onDisconnect,\n /* onKill= */ reason => {\n warn(reason + ' (' + this.repoInfo_.toString() + ')');\n this.interrupt(SERVER_KILL_INTERRUPT_REASON);\n },\n lastSessionId\n );\n } else {\n log('getToken() completed but was canceled');\n }\n } catch (error) {\n this.log_('Failed to get token: ' + error);\n if (!canceled) {\n if (this.repoInfo_.nodeAdmin) {\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\n // But getToken() may also just have temporarily failed, so we still want to\n // continue retrying.\n warn(error);\n }\n closeFn();\n }\n }\n }\n }\n\n interrupt(reason: string) {\n log('Interrupting connection for reason: ' + reason);\n this.interruptReasons_[reason] = true;\n if (this.realtime_) {\n this.realtime_.close();\n } else {\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n this.establishConnectionTimer_ = null;\n }\n if (this.connected_) {\n this.onRealtimeDisconnect_();\n }\n }\n }\n\n resume(reason: string) {\n log('Resuming connection for reason: ' + reason);\n delete this.interruptReasons_[reason];\n if (isEmpty(this.interruptReasons_)) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n }\n\n private handleTimestamp_(timestamp: number) {\n const delta = timestamp - new Date().getTime();\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\n }\n\n private cancelSentTransactions_() {\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\n const put = this.outstandingPuts_[i];\n if (put && /*hash*/ 'h' in put.request && put.queued) {\n if (put.onComplete) {\n put.onComplete('disconnect');\n }\n\n delete this.outstandingPuts_[i];\n this.outstandingPutCount_--;\n }\n }\n\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0) {\n this.outstandingPuts_ = [];\n }\n }\n\n private onListenRevoked_(pathString: string, query?: unknown[]) {\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\n let queryId;\n if (!query) {\n queryId = 'default';\n } else {\n queryId = query.map(q => ObjectToUniqueKey(q)).join('$');\n }\n const listen = this.removeListen_(pathString, queryId);\n if (listen && listen.onComplete) {\n listen.onComplete('permission_denied');\n }\n }\n\n private removeListen_(pathString: string, queryId: string): ListenSpec {\n const normalizedPathString = new Path(pathString).toString(); // normalize path.\n let listen;\n if (this.listens.has(normalizedPathString)) {\n const map = this.listens.get(normalizedPathString)!;\n listen = map.get(queryId);\n map.delete(queryId);\n if (map.size === 0) {\n this.listens.delete(normalizedPathString);\n }\n } else {\n // all listens for this path has already been removed\n listen = undefined;\n }\n return listen;\n }\n\n private onAuthRevoked_(statusCode: string, explanation: string) {\n log('Auth token revoked: ' + statusCode + '/' + explanation);\n this.authToken_ = null;\n this.forceTokenRefresh_ = true;\n this.realtime_.close();\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAuthTokenCount_++;\n if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\n // Set a long reconnect delay because recovery is unlikely\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n\n // Notify the auth token provider that the token is invalid, which will log\n // a warning\n this.authTokenProvider_.notifyForInvalidToken();\n }\n }\n }\n\n private onAppCheckRevoked_(statusCode: string, explanation: string) {\n log('App check token revoked: ' + statusCode + '/' + explanation);\n this.appCheckToken_ = null;\n this.forceTokenRefresh_ = true;\n // Note: We don't close the connection as the developer may not have\n // enforcement enabled. The backend closes connections with enforcements.\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAppCheckTokenCount_++;\n if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\n this.appCheckTokenProvider_.notifyForInvalidToken();\n }\n }\n }\n\n private onSecurityDebugPacket_(body: { [k: string]: unknown }) {\n if (this.securityDebugCallback_) {\n this.securityDebugCallback_(body);\n } else {\n if ('msg' in body) {\n console.log(\n 'FIREBASE: ' + (body['msg'] as string).replace('\\n', '\\nFIREBASE: ')\n );\n }\n }\n }\n\n private restoreState_() {\n //Re-authenticate ourselves if we have a credential stored.\n this.tryAuth();\n this.tryAppCheck();\n\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\n // make sure to send listens before puts.\n for (const queries of this.listens.values()) {\n for (const listenSpec of queries.values()) {\n this.sendListen_(listenSpec);\n }\n }\n\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\n if (this.outstandingPuts_[i]) {\n this.sendPut_(i);\n }\n }\n\n while (this.onDisconnectRequestQueue_.length) {\n const request = this.onDisconnectRequestQueue_.shift();\n this.sendOnDisconnect_(\n request.action,\n request.pathString,\n request.data,\n request.onComplete\n );\n }\n\n for (let i = 0; i < this.outstandingGets_.length; i++) {\n if (this.outstandingGets_[i]) {\n this.sendGet_(i);\n }\n }\n }\n\n /**\n * Sends client stats for first connection\n */\n private sendConnectStats_() {\n const stats: { [k: string]: number } = {};\n\n let clientName = 'js';\n if (isNodeSdk()) {\n if (this.repoInfo_.nodeAdmin) {\n clientName = 'admin_node';\n } else {\n clientName = 'node';\n }\n }\n\n stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\\./g, '-')] = 1;\n\n if (isMobileCordova()) {\n stats['framework.cordova'] = 1;\n } else if (isReactNative()) {\n stats['framework.reactnative'] = 1;\n }\n this.reportStats(stats);\n }\n\n private shouldReconnect_(): boolean {\n const online = OnlineMonitor.getInstance().currentlyOnline();\n return isEmpty(this.interruptReasons_) && online;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Path } from '../util/Path';\n\nimport { Index } from './indexes/Index';\n\n/**\n * Node is an interface defining the common functionality for nodes in\n * a DataSnapshot.\n *\n * @interface\n */\nexport interface Node {\n /**\n * Whether this node is a leaf node.\n * @returns Whether this is a leaf node.\n */\n isLeafNode(): boolean;\n\n /**\n * Gets the priority of the node.\n * @returns The priority of the node.\n */\n getPriority(): Node;\n\n /**\n * Returns a duplicate node with the new priority.\n * @param newPriorityNode - New priority to set for the node.\n * @returns Node with new priority.\n */\n updatePriority(newPriorityNode: Node): Node;\n\n /**\n * Returns the specified immediate child, or null if it doesn't exist.\n * @param childName - The name of the child to retrieve.\n * @returns The retrieved child, or an empty node.\n */\n getImmediateChild(childName: string): Node;\n\n /**\n * Returns a child by path, or null if it doesn't exist.\n * @param path - The path of the child to retrieve.\n * @returns The retrieved child or an empty node.\n */\n getChild(path: Path): Node;\n\n /**\n * Returns the name of the child immediately prior to the specified childNode, or null.\n * @param childName - The name of the child to find the predecessor of.\n * @param childNode - The node to find the predecessor of.\n * @param index - The index to use to determine the predecessor\n * @returns The name of the predecessor child, or null if childNode is the first child.\n */\n getPredecessorChildName(\n childName: string,\n childNode: Node,\n index: Index\n ): string | null;\n\n /**\n * Returns a duplicate node, with the specified immediate child updated.\n * Any value in the node will be removed.\n * @param childName - The name of the child to update.\n * @param newChildNode - The new child node\n * @returns The updated node.\n */\n updateImmediateChild(childName: string, newChildNode: Node): Node;\n\n /**\n * Returns a duplicate node, with the specified child updated. Any value will\n * be removed.\n * @param path - The path of the child to update.\n * @param newChildNode - The new child node, which may be an empty node\n * @returns The updated node.\n */\n updateChild(path: Path, newChildNode: Node): Node;\n\n /**\n * True if the immediate child specified exists\n */\n hasChild(childName: string): boolean;\n\n /**\n * @returns True if this node has no value or children.\n */\n isEmpty(): boolean;\n\n /**\n * @returns The number of children of this node.\n */\n numChildren(): number;\n\n /**\n * Calls action for each child.\n * @param action - Action to be called for\n * each child. It's passed the child name and the child node.\n * @returns The first truthy value return by action, or the last falsey one\n */\n forEachChild(index: Index, action: (a: string, b: Node) => void): unknown;\n\n /**\n * @param exportFormat - True for export format (also wire protocol format).\n * @returns Value of this node as JSON.\n */\n val(exportFormat?: boolean): unknown;\n\n /**\n * @returns hash representing the node contents.\n */\n hash(): string;\n\n /**\n * @param other - Another node\n * @returns -1 for less than, 0 for equal, 1 for greater than other\n */\n compareTo(other: Node): number;\n\n /**\n * @returns Whether or not this snapshot equals other\n */\n equals(other: Node): boolean;\n\n /**\n * @returns This node, with the specified index now available\n */\n withIndex(indexDefinition: Index): Node;\n\n isIndexed(indexDefinition: Index): boolean;\n}\n\nexport class NamedNode {\n constructor(public name: string, public node: Node) {}\n\n static Wrap(name: string, node: Node) {\n return new NamedNode(name, node);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Comparator } from '../../util/SortedMap';\nimport { MIN_NAME } from '../../util/util';\nimport { Node, NamedNode } from '../Node';\n\nexport abstract class Index {\n abstract compare(a: NamedNode, b: NamedNode): number;\n\n abstract isDefinedOn(node: Node): boolean;\n\n /**\n * @returns A standalone comparison function for\n * this index\n */\n getCompare(): Comparator {\n return this.compare.bind(this);\n }\n\n /**\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\n *\n *\n * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode\n */\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n const oldWrapped = new NamedNode(MIN_NAME, oldNode);\n const newWrapped = new NamedNode(MIN_NAME, newNode);\n return this.compare(oldWrapped, newWrapped) !== 0;\n }\n\n /**\n * @returns a node wrapper that will sort equal to or less than\n * any other node wrapper, using this index\n */\n minPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n\n /**\n * @returns a node wrapper that will sort greater than or equal to\n * any other node wrapper, using this index\n */\n abstract maxPost(): NamedNode;\n\n abstract makePost(indexValue: unknown, name: string): NamedNode;\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n abstract toString(): string;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport { nameCompare, MAX_NAME } from '../../util/util';\nimport { ChildrenNode } from '../ChildrenNode';\nimport { Node, NamedNode } from '../Node';\n\nimport { Index } from './Index';\n\nlet __EMPTY_NODE: ChildrenNode;\n\nexport class KeyIndex extends Index {\n static get __EMPTY_NODE() {\n return __EMPTY_NODE;\n }\n\n static set __EMPTY_NODE(val) {\n __EMPTY_NODE = val;\n }\n compare(a: NamedNode, b: NamedNode): number {\n return nameCompare(a.name, b.name);\n }\n isDefinedOn(node: Node): boolean {\n // We could probably return true here (since every node has a key), but it's never called\n // so just leaving unimplemented for now.\n throw assertionError('KeyIndex.isDefinedOn not expected to be called.');\n }\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return false; // The key for a node never changes.\n }\n minPost() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n maxPost(): NamedNode {\n // TODO: This should really be created once and cached in a static property, but\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\n return new NamedNode(MAX_NAME, __EMPTY_NODE);\n }\n\n makePost(indexValue: string, name: string): NamedNode {\n assert(\n typeof indexValue === 'string',\n 'KeyIndex indexValue must always be a string.'\n );\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\n return new NamedNode(indexValue, __EMPTY_NODE);\n }\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString(): string {\n return '.key';\n }\n}\n\nexport const KEY_INDEX = new KeyIndex();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Implementation of an immutable SortedMap using a Left-leaning\n * Red-Black Tree, adapted from the implementation in Mugs\n * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen\n * (mads379\\@gmail.com).\n *\n * Original paper on Left-leaning Red-Black Trees:\n * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf\n *\n * Invariant 1: No red node has a red child\n * Invariant 2: Every leaf path has the same number of black nodes\n * Invariant 3: Only the left child can be red (left leaning)\n */\n\n// TODO: There are some improvements I'd like to make to improve memory / perf:\n// * Create two prototypes, LLRedNode and LLBlackNode, instead of storing a\n// color property in every node.\n// TODO: It would also be good (and possibly necessary) to create a base\n// interface for LLRBNode and LLRBEmptyNode.\n\nexport type Comparator = (key1: K, key2: K) => number;\n\n/**\n * An iterator over an LLRBNode.\n */\nexport class SortedMapIterator {\n private nodeStack_: Array | LLRBEmptyNode> = [];\n\n /**\n * @param node - Node to iterate.\n * @param isReverse_ - Whether or not to iterate in reverse\n */\n constructor(\n node: LLRBNode | LLRBEmptyNode,\n startKey: K | null,\n comparator: Comparator,\n private isReverse_: boolean,\n private resultGenerator_: ((k: K, v: V) => T) | null = null\n ) {\n let cmp = 1;\n while (!node.isEmpty()) {\n node = node as LLRBNode;\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse_) {\n cmp *= -1;\n }\n\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse_) {\n node = node.left;\n } else {\n node = node.right;\n }\n } else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\n this.nodeStack_.push(node);\n break;\n } else {\n // This node is greater than our start key, add it to the stack and move to the next one\n this.nodeStack_.push(node);\n if (this.isReverse_) {\n node = node.right;\n } else {\n node = node.left;\n }\n }\n }\n }\n\n getNext(): T {\n if (this.nodeStack_.length === 0) {\n return null;\n }\n\n let node = this.nodeStack_.pop();\n let result: T;\n if (this.resultGenerator_) {\n result = this.resultGenerator_(node.key, node.value);\n } else {\n result = { key: node.key, value: node.value } as unknown as T;\n }\n\n if (this.isReverse_) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.right;\n }\n } else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.left;\n }\n }\n\n return result;\n }\n\n hasNext(): boolean {\n return this.nodeStack_.length > 0;\n }\n\n peek(): T {\n if (this.nodeStack_.length === 0) {\n return null;\n }\n\n const node = this.nodeStack_[this.nodeStack_.length - 1];\n if (this.resultGenerator_) {\n return this.resultGenerator_(node.key, node.value);\n } else {\n return { key: node.key, value: node.value } as unknown as T;\n }\n }\n}\n\n/**\n * Represents a node in a Left-leaning Red-Black tree.\n */\nexport class LLRBNode {\n color: boolean;\n left: LLRBNode | LLRBEmptyNode;\n right: LLRBNode | LLRBEmptyNode;\n\n /**\n * @param key - Key associated with this node.\n * @param value - Value associated with this node.\n * @param color - Whether this node is red.\n * @param left - Left child.\n * @param right - Right child.\n */\n constructor(\n public key: K,\n public value: V,\n color: boolean | null,\n left?: LLRBNode | LLRBEmptyNode | null,\n right?: LLRBNode | LLRBEmptyNode | null\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left =\n left != null ? left : (SortedMap.EMPTY_NODE as LLRBEmptyNode);\n this.right =\n right != null ? right : (SortedMap.EMPTY_NODE as LLRBEmptyNode);\n }\n\n static RED = true;\n static BLACK = false;\n\n /**\n * Returns a copy of the current node, optionally replacing pieces of it.\n *\n * @param key - New key for the node, or null.\n * @param value - New value for the node, or null.\n * @param color - New color for the node, or null.\n * @param left - New left child for the node, or null.\n * @param right - New right child for the node, or null.\n * @returns The node copy.\n */\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBNode {\n return new LLRBNode(\n key != null ? key : this.key,\n value != null ? value : this.value,\n color != null ? color : this.color,\n left != null ? left : this.left,\n right != null ? right : this.right\n );\n }\n\n /**\n * @returns The total number of nodes in the tree.\n */\n count(): number {\n return this.left.count() + 1 + this.right.count();\n }\n\n /**\n * @returns True if the tree is empty.\n */\n isEmpty(): boolean {\n return false;\n }\n\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n inorderTraversal(action: (k: K, v: V) => unknown): boolean {\n return (\n this.left.inorderTraversal(action) ||\n !!action(this.key, this.value) ||\n this.right.inorderTraversal(action)\n );\n }\n\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n reverseTraversal(action: (k: K, v: V) => void): boolean {\n return (\n this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action)\n );\n }\n\n /**\n * @returns The minimum node in the tree.\n */\n private min_(): LLRBNode {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode).min_();\n }\n }\n\n /**\n * @returns The maximum key in the tree.\n */\n minKey(): K {\n return this.min_().key;\n }\n\n /**\n * @returns The maximum key in the tree.\n */\n maxKey(): K {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\n }\n\n /**\n * @param key - Key to insert.\n * @param value - Value to insert.\n * @param comparator - Comparator.\n * @returns New tree, with the key/value added.\n */\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n let n: LLRBNode = this;\n const cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n } else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n } else {\n n = n.copy(\n null,\n null,\n null,\n null,\n n.right.insert(key, value, comparator)\n );\n }\n return n.fixUp_();\n }\n\n /**\n * @returns New tree, with the minimum key removed.\n */\n private removeMin_(): LLRBNode | LLRBEmptyNode {\n if (this.left.isEmpty()) {\n return SortedMap.EMPTY_NODE as LLRBEmptyNode;\n }\n let n: LLRBNode = this;\n if (!n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, (n.left as LLRBNode).removeMin_(), null);\n return n.fixUp_();\n }\n\n /**\n * @param key - The key of the item to remove.\n * @param comparator - Comparator.\n * @returns New tree, with the specified item removed.\n */\n remove(\n key: K,\n comparator: Comparator\n ): LLRBNode | LLRBEmptyNode {\n let n, smallest;\n n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n } else {\n if (n.left.isRed_()) {\n n = n.rotateRight_();\n }\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\n n = n.moveRedRight_();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return SortedMap.EMPTY_NODE as LLRBEmptyNode;\n } else {\n smallest = (n.right as LLRBNode).min_();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode).removeMin_()\n );\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp_();\n }\n\n /**\n * @returns Whether this is a RED node.\n */\n isRed_(): boolean {\n return this.color;\n }\n\n /**\n * @returns New tree after performing any needed rotations.\n */\n private fixUp_(): LLRBNode {\n let n: LLRBNode = this;\n if (n.right.isRed_() && !n.left.isRed_()) {\n n = n.rotateLeft_();\n }\n if (n.left.isRed_() && n.left.left.isRed_()) {\n n = n.rotateRight_();\n }\n if (n.left.isRed_() && n.right.isRed_()) {\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @returns New tree, after moveRedLeft.\n */\n private moveRedLeft_(): LLRBNode {\n let n = this.colorFlip_();\n if (n.right.left.isRed_()) {\n n = n.copy(\n null,\n null,\n null,\n null,\n (n.right as LLRBNode).rotateRight_()\n );\n n = n.rotateLeft_();\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @returns New tree, after moveRedRight.\n */\n private moveRedRight_(): LLRBNode {\n let n = this.colorFlip_();\n if (n.left.left.isRed_()) {\n n = n.rotateRight_();\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @returns New tree, after rotateLeft.\n */\n private rotateLeft_(): LLRBNode {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null) as LLRBNode;\n }\n\n /**\n * @returns New tree, after rotateRight.\n */\n private rotateRight_(): LLRBNode {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr) as LLRBNode;\n }\n\n /**\n * @returns Newt ree, after colorFlip.\n */\n private colorFlip_(): LLRBNode {\n const left = this.left.copy(null, null, !this.left.color, null, null);\n const right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n }\n\n /**\n * For testing.\n *\n * @returns True if all is well.\n */\n private checkMaxDepth_(): boolean {\n const blackDepth = this.check_();\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\n }\n\n check_(): number {\n if (this.isRed_() && this.left.isRed_()) {\n throw new Error(\n 'Red node has red child(' + this.key + ',' + this.value + ')'\n );\n }\n if (this.right.isRed_()) {\n throw new Error(\n 'Right child of (' + this.key + ',' + this.value + ') is red'\n );\n }\n const blackDepth = this.left.check_();\n if (blackDepth !== this.right.check_()) {\n throw new Error('Black depths differ');\n } else {\n return blackDepth + (this.isRed_() ? 0 : 1);\n }\n }\n}\n\n/**\n * Represents an empty node (a leaf node in the Red-Black Tree).\n */\nexport class LLRBEmptyNode {\n key: K;\n value: V;\n left: LLRBNode | LLRBEmptyNode;\n right: LLRBNode | LLRBEmptyNode;\n color: boolean;\n\n /**\n * Returns a copy of the current node.\n *\n * @returns The node copy.\n */\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBEmptyNode {\n return this;\n }\n\n /**\n * Returns a copy of the tree, with the specified key/value added.\n *\n * @param key - Key to be added.\n * @param value - Value to be added.\n * @param comparator - Comparator.\n * @returns New tree, with item added.\n */\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n return new LLRBNode(key, value, null);\n }\n\n /**\n * Returns a copy of the tree, with the specified key removed.\n *\n * @param key - The key to remove.\n * @param comparator - Comparator.\n * @returns New tree, with item removed.\n */\n remove(key: K, comparator: Comparator): LLRBEmptyNode {\n return this;\n }\n\n /**\n * @returns The total number of nodes in the tree.\n */\n count(): number {\n return 0;\n }\n\n /**\n * @returns True if the tree is empty.\n */\n isEmpty(): boolean {\n return true;\n }\n\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n inorderTraversal(action: (k: K, v: V) => unknown): boolean {\n return false;\n }\n\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n reverseTraversal(action: (k: K, v: V) => void): boolean {\n return false;\n }\n\n minKey(): null {\n return null;\n }\n\n maxKey(): null {\n return null;\n }\n\n check_(): number {\n return 0;\n }\n\n /**\n * @returns Whether this node is red.\n */\n isRed_() {\n return false;\n }\n}\n\n/**\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\n * tree.\n */\nexport class SortedMap {\n /**\n * Always use the same empty node, to reduce memory.\n */\n static EMPTY_NODE = new LLRBEmptyNode();\n\n /**\n * @param comparator_ - Key comparator.\n * @param root_ - Optional root node for the map.\n */\n constructor(\n private comparator_: Comparator,\n private root_:\n | LLRBNode\n | LLRBEmptyNode = SortedMap.EMPTY_NODE as LLRBEmptyNode\n ) {}\n\n /**\n * Returns a copy of the map, with the specified key/value added or replaced.\n * (TODO: We should perhaps rename this method to 'put')\n *\n * @param key - Key to be added.\n * @param value - Value to be added.\n * @returns New map, with item added.\n */\n insert(key: K, value: V): SortedMap {\n return new SortedMap(\n this.comparator_,\n this.root_\n .insert(key, value, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n /**\n * Returns a copy of the map, with the specified key removed.\n *\n * @param key - The key to remove.\n * @returns New map, with item removed.\n */\n remove(key: K): SortedMap {\n return new SortedMap(\n this.comparator_,\n this.root_\n .remove(key, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n /**\n * Returns the value of the node with the given key, or null.\n *\n * @param key - The key to look up.\n * @returns The value of the node with the given key, or null if the\n * key doesn't exist.\n */\n get(key: K): V | null {\n let cmp;\n let node = this.root_;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n return node.value;\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n }\n\n /**\n * Returns the key of the item *before* the specified key, or null if key is the first item.\n * @param key - The key to find the predecessor of\n * @returns The predecessor key.\n */\n getPredecessorKey(key: K): K | null {\n let cmp,\n node = this.root_,\n rightParent = null;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n if (!node.left.isEmpty()) {\n node = node.left;\n while (!node.right.isEmpty()) {\n node = node.right;\n }\n return node.key;\n } else if (rightParent) {\n return rightParent.key;\n } else {\n return null; // first item.\n }\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n\n throw new Error(\n 'Attempted to find predecessor key for a nonexistent key. What gives?'\n );\n }\n\n /**\n * @returns True if the map is empty.\n */\n isEmpty(): boolean {\n return this.root_.isEmpty();\n }\n\n /**\n * @returns The total number of nodes in the map.\n */\n count(): number {\n return this.root_.count();\n }\n\n /**\n * @returns The minimum key in the map.\n */\n minKey(): K | null {\n return this.root_.minKey();\n }\n\n /**\n * @returns The maximum key in the map.\n */\n maxKey(): K | null {\n return this.root_.maxKey();\n }\n\n /**\n * Traverses the map in key order and calls the specified action function\n * for each key/value pair.\n *\n * @param action - Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @returns The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n inorderTraversal(action: (k: K, v: V) => unknown): boolean {\n return this.root_.inorderTraversal(action);\n }\n\n /**\n * Traverses the map in reverse key order and calls the specified action function\n * for each key/value pair.\n *\n * @param action - Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @returns True if the traversal was aborted.\n */\n reverseTraversal(action: (k: K, v: V) => void): boolean {\n return this.root_.reverseTraversal(action);\n }\n\n /**\n * Returns an iterator over the SortedMap.\n * @returns The iterator.\n */\n getIterator(\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n null,\n this.comparator_,\n false,\n resultGenerator\n );\n }\n\n getIteratorFrom(\n key: K,\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n key,\n this.comparator_,\n false,\n resultGenerator\n );\n }\n\n getReverseIteratorFrom(\n key: K,\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n key,\n this.comparator_,\n true,\n resultGenerator\n );\n }\n\n getReverseIterator(\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n null,\n this.comparator_,\n true,\n resultGenerator\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare } from '../util/util';\n\nimport { NamedNode } from './Node';\n\nexport function NAME_ONLY_COMPARATOR(left: NamedNode, right: NamedNode) {\n return nameCompare(left.name, right.name);\n}\n\nexport function NAME_COMPARATOR(left: string, right: string) {\n return nameCompare(left, right);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, contains } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport { doubleToIEEE754String } from '../util/util';\n\nimport { Node } from './Node';\n\nlet MAX_NODE: Node;\n\nexport function setMaxNode(val: Node) {\n MAX_NODE = val;\n}\n\nexport const priorityHashText = function (priority: string | number): string {\n if (typeof priority === 'number') {\n return 'number:' + doubleToIEEE754String(priority);\n } else {\n return 'string:' + priority;\n }\n};\n\n/**\n * Validates that a priority snapshot Node is valid.\n */\nexport const validatePriorityNode = function (priorityNode: Node) {\n if (priorityNode.isLeafNode()) {\n const val = priorityNode.val();\n assert(\n typeof val === 'string' ||\n typeof val === 'number' ||\n (typeof val === 'object' && contains(val as Indexable, '.sv')),\n 'Priority must be a string or number.'\n );\n } else {\n assert(\n priorityNode === MAX_NODE || priorityNode.isEmpty(),\n 'priority of unexpected type.'\n );\n }\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\n assert(\n priorityNode === MAX_NODE || priorityNode.getPriority().isEmpty(),\n \"Priority nodes can't have a priority of their own.\"\n );\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport {\n Path,\n pathGetFront,\n pathGetLength,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\nimport { doubleToIEEE754String, sha1 } from '../util/util';\n\nimport { ChildrenNodeConstructor } from './ChildrenNode';\nimport { Index } from './indexes/Index';\nimport { Node } from './Node';\nimport { priorityHashText, validatePriorityNode } from './snap';\n\nlet __childrenNodeConstructor: ChildrenNodeConstructor;\n\n/**\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\n * implements Node and stores the value of the node (a string,\n * number, or boolean) accessible via getValue().\n */\nexport class LeafNode implements Node {\n static set __childrenNodeConstructor(val: ChildrenNodeConstructor) {\n __childrenNodeConstructor = val;\n }\n\n static get __childrenNodeConstructor() {\n return __childrenNodeConstructor;\n }\n\n /**\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\n * the same type, the comparison falls back to their value\n */\n static VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n\n private lazyHash_: string | null = null;\n\n /**\n * @param value_ - The value to store in this leaf node. The object type is\n * possible in the event of a deferred value\n * @param priorityNode_ - The priority of this node.\n */\n constructor(\n private readonly value_: string | number | boolean | Indexable,\n private priorityNode_: Node = LeafNode.__childrenNodeConstructor.EMPTY_NODE\n ) {\n assert(\n this.value_ !== undefined && this.value_ !== null,\n \"LeafNode shouldn't be created with null/undefined value.\"\n );\n\n validatePriorityNode(this.priorityNode_);\n }\n\n /** @inheritDoc */\n isLeafNode(): boolean {\n return true;\n }\n\n /** @inheritDoc */\n getPriority(): Node {\n return this.priorityNode_;\n }\n\n /** @inheritDoc */\n updatePriority(newPriorityNode: Node): Node {\n return new LeafNode(this.value_, newPriorityNode);\n }\n\n /** @inheritDoc */\n getImmediateChild(childName: string): Node {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.priorityNode_;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n }\n\n /** @inheritDoc */\n getChild(path: Path): Node {\n if (pathIsEmpty(path)) {\n return this;\n } else if (pathGetFront(path) === '.priority') {\n return this.priorityNode_;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n }\n hasChild(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n getPredecessorChildName(childName: string, childNode: Node): null {\n return null;\n }\n\n /** @inheritDoc */\n updateImmediateChild(childName: string, newChildNode: Node): Node {\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n } else if (newChildNode.isEmpty() && childName !== '.priority') {\n return this;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(\n childName,\n newChildNode\n ).updatePriority(this.priorityNode_);\n }\n }\n\n /** @inheritDoc */\n updateChild(path: Path, newChildNode: Node): Node {\n const front = pathGetFront(path);\n if (front === null) {\n return newChildNode;\n } else if (newChildNode.isEmpty() && front !== '.priority') {\n return this;\n } else {\n assert(\n front !== '.priority' || pathGetLength(path) === 1,\n '.priority must be the last token in a path'\n );\n\n return this.updateImmediateChild(\n front,\n LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(\n pathPopFront(path),\n newChildNode\n )\n );\n }\n }\n\n /** @inheritDoc */\n isEmpty(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n numChildren(): number {\n return 0;\n }\n\n /** @inheritDoc */\n forEachChild(index: Index, action: (s: string, n: Node) => void): boolean {\n return false;\n }\n val(exportFormat?: boolean): {} {\n if (exportFormat && !this.getPriority().isEmpty()) {\n return {\n '.value': this.getValue(),\n '.priority': this.getPriority().val()\n };\n } else {\n return this.getValue();\n }\n }\n\n /** @inheritDoc */\n hash(): string {\n if (this.lazyHash_ === null) {\n let toHash = '';\n if (!this.priorityNode_.isEmpty()) {\n toHash +=\n 'priority:' +\n priorityHashText(this.priorityNode_.val() as number | string) +\n ':';\n }\n\n const type = typeof this.value_;\n toHash += type + ':';\n if (type === 'number') {\n toHash += doubleToIEEE754String(this.value_ as number);\n } else {\n toHash += this.value_;\n }\n this.lazyHash_ = sha1(toHash);\n }\n return this.lazyHash_;\n }\n\n /**\n * Returns the value of the leaf node.\n * @returns The value of the node.\n */\n getValue(): Indexable | string | number | boolean {\n return this.value_;\n }\n compareTo(other: Node): number {\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\n return 1;\n } else if (other instanceof LeafNode.__childrenNodeConstructor) {\n return -1;\n } else {\n assert(other.isLeafNode(), 'Unknown node type');\n return this.compareToLeafNode_(other as LeafNode);\n }\n }\n\n /**\n * Comparison specifically for two leaf nodes\n */\n private compareToLeafNode_(otherLeaf: LeafNode): number {\n const otherLeafType = typeof otherLeaf.value_;\n const thisLeafType = typeof this.value_;\n const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\n const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\n assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\n assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\n if (otherIndex === thisIndex) {\n // Same type, compare values\n if (thisLeafType === 'object') {\n // Deferred value nodes are all equal, but we should also never get to this point...\n return 0;\n } else {\n // Note that this works because true > false, all others are number or string comparisons\n if (this.value_ < otherLeaf.value_) {\n return -1;\n } else if (this.value_ === otherLeaf.value_) {\n return 0;\n } else {\n return 1;\n }\n }\n } else {\n return thisIndex - otherIndex;\n }\n }\n withIndex(): Node {\n return this;\n }\n isIndexed(): boolean {\n return true;\n }\n equals(other: Node): boolean {\n if (other === this) {\n return true;\n } else if (other.isLeafNode()) {\n const otherLeaf = other as LeafNode;\n return (\n this.value_ === otherLeaf.value_ &&\n this.priorityNode_.equals(otherLeaf.priorityNode_)\n );\n } else {\n return false;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare, MAX_NAME } from '../../util/util';\nimport { LeafNode } from '../LeafNode';\nimport { NamedNode, Node } from '../Node';\n\nimport { Index } from './Index';\n\nlet nodeFromJSON: (a: unknown) => Node;\nlet MAX_NODE: Node;\n\nexport function setNodeFromJSON(val: (a: unknown) => Node) {\n nodeFromJSON = val;\n}\n\nexport function setMaxNode(val: Node) {\n MAX_NODE = val;\n}\n\nexport class PriorityIndex extends Index {\n compare(a: NamedNode, b: NamedNode): number {\n const aPriority = a.node.getPriority();\n const bPriority = b.node.getPriority();\n const indexCmp = aPriority.compareTo(bPriority);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n isDefinedOn(node: Node): boolean {\n return !node.getPriority().isEmpty();\n }\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return !oldNode.getPriority().equals(newNode.getPriority());\n }\n minPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n maxPost(): NamedNode {\n return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE));\n }\n\n makePost(indexValue: unknown, name: string): NamedNode {\n const priorityNode = nodeFromJSON(indexValue);\n return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));\n }\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString(): string {\n return '.priority';\n }\n}\n\nexport const PRIORITY_INDEX = new PriorityIndex();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LLRBNode, SortedMap } from '../util/SortedMap';\n\nimport { NamedNode } from './Node';\n\nconst LOG_2 = Math.log(2);\n\nclass Base12Num {\n count: number;\n private current_: number;\n private bits_: number;\n\n constructor(length: number) {\n const logBase2 = (num: number) =>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parseInt((Math.log(num) / LOG_2) as any, 10);\n const bitMask = (bits: number) => parseInt(Array(bits + 1).join('1'), 2);\n this.count = logBase2(length + 1);\n this.current_ = this.count - 1;\n const mask = bitMask(this.count);\n this.bits_ = (length + 1) & mask;\n }\n\n nextBitIsOne(): boolean {\n //noinspection JSBitwiseOperatorUsage\n const result = !(this.bits_ & (0x1 << this.current_));\n this.current_--;\n return result;\n }\n}\n\n/**\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\n * function\n *\n * Uses the algorithm described in the paper linked here:\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\n *\n * @param childList - Unsorted list of children\n * @param cmp - The comparison method to be used\n * @param keyFn - An optional function to extract K from a node wrapper, if K's\n * type is not NamedNode\n * @param mapSortFn - An optional override for comparator used by the generated sorted map\n */\nexport const buildChildSet = function (\n childList: NamedNode[],\n cmp: (a: NamedNode, b: NamedNode) => number,\n keyFn?: (a: NamedNode) => K,\n mapSortFn?: (a: K, b: K) => number\n): SortedMap {\n childList.sort(cmp);\n\n const buildBalancedTree = function (\n low: number,\n high: number\n ): LLRBNode | null {\n const length = high - low;\n let namedNode: NamedNode;\n let key: K;\n if (length === 0) {\n return null;\n } else if (length === 1) {\n namedNode = childList[low];\n key = keyFn ? keyFn(namedNode) : (namedNode as unknown as K);\n return new LLRBNode(\n key,\n namedNode.node as unknown as V,\n LLRBNode.BLACK,\n null,\n null\n );\n } else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const middle = parseInt((length / 2) as any, 10) + low;\n const left = buildBalancedTree(low, middle);\n const right = buildBalancedTree(middle + 1, high);\n namedNode = childList[middle];\n key = keyFn ? keyFn(namedNode) : (namedNode as unknown as K);\n return new LLRBNode(\n key,\n namedNode.node as unknown as V,\n LLRBNode.BLACK,\n left,\n right\n );\n }\n };\n\n const buildFrom12Array = function (base12: Base12Num): LLRBNode {\n let node: LLRBNode = null;\n let root = null;\n let index = childList.length;\n\n const buildPennant = function (chunkSize: number, color: boolean) {\n const low = index - chunkSize;\n const high = index;\n index -= chunkSize;\n const childTree = buildBalancedTree(low + 1, high);\n const namedNode = childList[low];\n const key: K = keyFn ? keyFn(namedNode) : (namedNode as unknown as K);\n attachPennant(\n new LLRBNode(\n key,\n namedNode.node as unknown as V,\n color,\n null,\n childTree\n )\n );\n };\n\n const attachPennant = function (pennant: LLRBNode) {\n if (node) {\n node.left = pennant;\n node = pennant;\n } else {\n root = pennant;\n node = pennant;\n }\n };\n\n for (let i = 0; i < base12.count; ++i) {\n const isOne = base12.nextBitIsOne();\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\n const chunkSize = Math.pow(2, base12.count - (i + 1));\n if (isOne) {\n buildPennant(chunkSize, LLRBNode.BLACK);\n } else {\n // current == 2\n buildPennant(chunkSize, LLRBNode.BLACK);\n buildPennant(chunkSize, LLRBNode.RED);\n }\n }\n return root;\n };\n\n const base12 = new Base12Num(childList.length);\n const root = buildFrom12Array(base12);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new SortedMap(mapSortFn || (cmp as any), root);\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, contains, map, safeGet } from '@firebase/util';\n\nimport { SortedMap } from '../util/SortedMap';\n\nimport { buildChildSet } from './childSet';\nimport { Index } from './indexes/Index';\nimport { KEY_INDEX } from './indexes/KeyIndex';\nimport { PRIORITY_INDEX } from './indexes/PriorityIndex';\nimport { NamedNode, Node } from './Node';\n\nlet _defaultIndexMap: IndexMap;\n\nconst fallbackObject = {};\n\nexport class IndexMap {\n /**\n * The default IndexMap for nodes without a priority\n */\n static get Default(): IndexMap {\n assert(\n fallbackObject && PRIORITY_INDEX,\n 'ChildrenNode.ts has not been loaded'\n );\n _defaultIndexMap =\n _defaultIndexMap ||\n new IndexMap(\n { '.priority': fallbackObject },\n { '.priority': PRIORITY_INDEX }\n );\n return _defaultIndexMap;\n }\n\n constructor(\n private indexes_: {\n [k: string]: SortedMap | /*FallbackType*/ object;\n },\n private indexSet_: { [k: string]: Index }\n ) {}\n\n get(indexKey: string): SortedMap | null {\n const sortedMap = safeGet(this.indexes_, indexKey);\n if (!sortedMap) {\n throw new Error('No index defined for ' + indexKey);\n }\n\n if (sortedMap instanceof SortedMap) {\n return sortedMap;\n } else {\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\n // regular child map\n return null;\n }\n }\n\n hasIndex(indexDefinition: Index): boolean {\n return contains(this.indexSet_, indexDefinition.toString());\n }\n\n addIndex(\n indexDefinition: Index,\n existingChildren: SortedMap\n ): IndexMap {\n assert(\n indexDefinition !== KEY_INDEX,\n \"KeyIndex always exists and isn't meant to be added to the IndexMap.\"\n );\n const childList = [];\n let sawIndexedValue = false;\n const iter = existingChildren.getIterator(NamedNode.Wrap);\n let next = iter.getNext();\n while (next) {\n sawIndexedValue =\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\n childList.push(next);\n next = iter.getNext();\n }\n let newIndex;\n if (sawIndexedValue) {\n newIndex = buildChildSet(childList, indexDefinition.getCompare());\n } else {\n newIndex = fallbackObject;\n }\n const indexName = indexDefinition.toString();\n const newIndexSet = { ...this.indexSet_ };\n newIndexSet[indexName] = indexDefinition;\n const newIndexes = { ...this.indexes_ };\n newIndexes[indexName] = newIndex;\n return new IndexMap(newIndexes, newIndexSet);\n }\n\n /**\n * Ensure that this node is properly tracked in any indexes that we're maintaining\n */\n addToIndexes(\n namedNode: NamedNode,\n existingChildren: SortedMap\n ): IndexMap {\n const newIndexes = map(\n this.indexes_,\n (indexedChildren: SortedMap, indexName: string) => {\n const index = safeGet(this.indexSet_, indexName);\n assert(index, 'Missing index implementation for ' + indexName);\n if (indexedChildren === fallbackObject) {\n // Check to see if we need to index everything\n if (index.isDefinedOn(namedNode.node)) {\n // We need to build this index\n const childList = [];\n const iter = existingChildren.getIterator(NamedNode.Wrap);\n let next = iter.getNext();\n while (next) {\n if (next.name !== namedNode.name) {\n childList.push(next);\n }\n next = iter.getNext();\n }\n childList.push(namedNode);\n return buildChildSet(childList, index.getCompare());\n } else {\n // No change, this remains a fallback\n return fallbackObject;\n }\n } else {\n const existingSnap = existingChildren.get(namedNode.name);\n let newChildren = indexedChildren;\n if (existingSnap) {\n newChildren = newChildren.remove(\n new NamedNode(namedNode.name, existingSnap)\n );\n }\n return newChildren.insert(namedNode, namedNode.node);\n }\n }\n );\n return new IndexMap(newIndexes, this.indexSet_);\n }\n\n /**\n * Create a new IndexMap instance with the given value removed\n */\n removeFromIndexes(\n namedNode: NamedNode,\n existingChildren: SortedMap\n ): IndexMap {\n const newIndexes = map(\n this.indexes_,\n (indexedChildren: SortedMap) => {\n if (indexedChildren === fallbackObject) {\n // This is the fallback. Just return it, nothing to do in this case\n return indexedChildren;\n } else {\n const existingSnap = existingChildren.get(namedNode.name);\n if (existingSnap) {\n return indexedChildren.remove(\n new NamedNode(namedNode.name, existingSnap)\n );\n } else {\n // No record of this child\n return indexedChildren;\n }\n }\n }\n );\n return new IndexMap(newIndexes, this.indexSet_);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Path, pathGetFront, pathGetLength, pathPopFront } from '../util/Path';\nimport { SortedMap, SortedMapIterator } from '../util/SortedMap';\nimport { MAX_NAME, MIN_NAME, sha1 } from '../util/util';\n\nimport { NAME_COMPARATOR } from './comparators';\nimport { Index } from './indexes/Index';\nimport { KEY_INDEX, KeyIndex } from './indexes/KeyIndex';\nimport {\n PRIORITY_INDEX,\n setMaxNode as setPriorityMaxNode\n} from './indexes/PriorityIndex';\nimport { IndexMap } from './IndexMap';\nimport { LeafNode } from './LeafNode';\nimport { NamedNode, Node } from './Node';\nimport { priorityHashText, setMaxNode, validatePriorityNode } from './snap';\n\nexport interface ChildrenNodeConstructor {\n new (\n children_: SortedMap,\n priorityNode_: Node | null,\n indexMap_: IndexMap\n ): ChildrenNode;\n EMPTY_NODE: ChildrenNode;\n}\n\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\n\nlet EMPTY_NODE: ChildrenNode;\n\n/**\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\n * (i.e. nodes with children). It implements Node and stores the\n * list of children in the children property, sorted by child name.\n */\nexport class ChildrenNode implements Node {\n private lazyHash_: string | null = null;\n\n static get EMPTY_NODE(): ChildrenNode {\n return (\n EMPTY_NODE ||\n (EMPTY_NODE = new ChildrenNode(\n new SortedMap(NAME_COMPARATOR),\n null,\n IndexMap.Default\n ))\n );\n }\n\n /**\n * @param children_ - List of children of this node..\n * @param priorityNode_ - The priority of this node (as a snapshot node).\n */\n constructor(\n private readonly children_: SortedMap,\n private readonly priorityNode_: Node | null,\n private indexMap_: IndexMap\n ) {\n /**\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\n * class instead of an empty ChildrenNode.\n */\n if (this.priorityNode_) {\n validatePriorityNode(this.priorityNode_);\n }\n\n if (this.children_.isEmpty()) {\n assert(\n !this.priorityNode_ || this.priorityNode_.isEmpty(),\n 'An empty node cannot have a priority'\n );\n }\n }\n\n /** @inheritDoc */\n isLeafNode(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n getPriority(): Node {\n return this.priorityNode_ || EMPTY_NODE;\n }\n\n /** @inheritDoc */\n updatePriority(newPriorityNode: Node): Node {\n if (this.children_.isEmpty()) {\n // Don't allow priorities on empty nodes\n return this;\n } else {\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\n }\n }\n\n /** @inheritDoc */\n getImmediateChild(childName: string): Node {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.getPriority();\n } else {\n const child = this.children_.get(childName);\n return child === null ? EMPTY_NODE : child;\n }\n }\n\n /** @inheritDoc */\n getChild(path: Path): Node {\n const front = pathGetFront(path);\n if (front === null) {\n return this;\n }\n\n return this.getImmediateChild(front).getChild(pathPopFront(path));\n }\n\n /** @inheritDoc */\n hasChild(childName: string): boolean {\n return this.children_.get(childName) !== null;\n }\n\n /** @inheritDoc */\n updateImmediateChild(childName: string, newChildNode: Node): Node {\n assert(newChildNode, 'We should always be passing snapshot nodes');\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n } else {\n const namedNode = new NamedNode(childName, newChildNode);\n let newChildren, newIndexMap;\n if (newChildNode.isEmpty()) {\n newChildren = this.children_.remove(childName);\n newIndexMap = this.indexMap_.removeFromIndexes(\n namedNode,\n this.children_\n );\n } else {\n newChildren = this.children_.insert(childName, newChildNode);\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\n }\n\n const newPriority = newChildren.isEmpty()\n ? EMPTY_NODE\n : this.priorityNode_;\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\n }\n }\n\n /** @inheritDoc */\n updateChild(path: Path, newChildNode: Node): Node {\n const front = pathGetFront(path);\n if (front === null) {\n return newChildNode;\n } else {\n assert(\n pathGetFront(path) !== '.priority' || pathGetLength(path) === 1,\n '.priority must be the last token in a path'\n );\n const newImmediateChild = this.getImmediateChild(front).updateChild(\n pathPopFront(path),\n newChildNode\n );\n return this.updateImmediateChild(front, newImmediateChild);\n }\n }\n\n /** @inheritDoc */\n isEmpty(): boolean {\n return this.children_.isEmpty();\n }\n\n /** @inheritDoc */\n numChildren(): number {\n return this.children_.count();\n }\n\n private static INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\n\n /** @inheritDoc */\n val(exportFormat?: boolean): object {\n if (this.isEmpty()) {\n return null;\n }\n\n const obj: { [k: string]: unknown } = {};\n let numKeys = 0,\n maxKey = 0,\n allIntegerKeys = true;\n this.forEachChild(PRIORITY_INDEX, (key: string, childNode: Node) => {\n obj[key] = childNode.val(exportFormat);\n\n numKeys++;\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\n maxKey = Math.max(maxKey, Number(key));\n } else {\n allIntegerKeys = false;\n }\n });\n\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\n // convert to array.\n const array: unknown[] = [];\n // eslint-disable-next-line guard-for-in\n for (const key in obj) {\n array[key as unknown as number] = obj[key];\n }\n\n return array;\n } else {\n if (exportFormat && !this.getPriority().isEmpty()) {\n obj['.priority'] = this.getPriority().val();\n }\n return obj;\n }\n }\n\n /** @inheritDoc */\n hash(): string {\n if (this.lazyHash_ === null) {\n let toHash = '';\n if (!this.getPriority().isEmpty()) {\n toHash +=\n 'priority:' +\n priorityHashText(this.getPriority().val() as string | number) +\n ':';\n }\n\n this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n const childHash = childNode.hash();\n if (childHash !== '') {\n toHash += ':' + key + ':' + childHash;\n }\n });\n\n this.lazyHash_ = toHash === '' ? '' : sha1(toHash);\n }\n return this.lazyHash_;\n }\n\n /** @inheritDoc */\n getPredecessorChildName(\n childName: string,\n childNode: Node,\n index: Index\n ): string {\n const idx = this.resolveIndex_(index);\n if (idx) {\n const predecessor = idx.getPredecessorKey(\n new NamedNode(childName, childNode)\n );\n return predecessor ? predecessor.name : null;\n } else {\n return this.children_.getPredecessorKey(childName);\n }\n }\n\n getFirstChildName(indexDefinition: Index): string | null {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n const minKey = idx.minKey();\n return minKey && minKey.name;\n } else {\n return this.children_.minKey();\n }\n }\n\n getFirstChild(indexDefinition: Index): NamedNode | null {\n const minKey = this.getFirstChildName(indexDefinition);\n if (minKey) {\n return new NamedNode(minKey, this.children_.get(minKey));\n } else {\n return null;\n }\n }\n\n /**\n * Given an index, return the key name of the largest value we have, according to that index\n */\n getLastChildName(indexDefinition: Index): string | null {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n const maxKey = idx.maxKey();\n return maxKey && maxKey.name;\n } else {\n return this.children_.maxKey();\n }\n }\n\n getLastChild(indexDefinition: Index): NamedNode | null {\n const maxKey = this.getLastChildName(indexDefinition);\n if (maxKey) {\n return new NamedNode(maxKey, this.children_.get(maxKey));\n } else {\n return null;\n }\n }\n forEachChild(\n index: Index,\n action: (key: string, node: Node) => boolean | void\n ): boolean {\n const idx = this.resolveIndex_(index);\n if (idx) {\n return idx.inorderTraversal(wrappedNode => {\n return action(wrappedNode.name, wrappedNode.node);\n });\n } else {\n return this.children_.inorderTraversal(action);\n }\n }\n\n getIterator(\n indexDefinition: Index\n ): SortedMapIterator {\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\n }\n\n getIteratorFrom(\n startPost: NamedNode,\n indexDefinition: Index\n ): SortedMapIterator {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getIteratorFrom(startPost, key => key);\n } else {\n const iterator = this.children_.getIteratorFrom(\n startPost.name,\n NamedNode.Wrap\n );\n let next = iterator.peek();\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n }\n\n getReverseIterator(\n indexDefinition: Index\n ): SortedMapIterator {\n return this.getReverseIteratorFrom(\n indexDefinition.maxPost(),\n indexDefinition\n );\n }\n\n getReverseIteratorFrom(\n endPost: NamedNode,\n indexDefinition: Index\n ): SortedMapIterator {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getReverseIteratorFrom(endPost, key => {\n return key;\n });\n } else {\n const iterator = this.children_.getReverseIteratorFrom(\n endPost.name,\n NamedNode.Wrap\n );\n let next = iterator.peek();\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n }\n compareTo(other: ChildrenNode): number {\n if (this.isEmpty()) {\n if (other.isEmpty()) {\n return 0;\n } else {\n return -1;\n }\n } else if (other.isLeafNode() || other.isEmpty()) {\n return 1;\n } else if (other === MAX_NODE) {\n return -1;\n } else {\n // Must be another node with children.\n return 0;\n }\n }\n withIndex(indexDefinition: Index): Node {\n if (\n indexDefinition === KEY_INDEX ||\n this.indexMap_.hasIndex(indexDefinition)\n ) {\n return this;\n } else {\n const newIndexMap = this.indexMap_.addIndex(\n indexDefinition,\n this.children_\n );\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\n }\n }\n isIndexed(index: Index): boolean {\n return index === KEY_INDEX || this.indexMap_.hasIndex(index);\n }\n equals(other: Node): boolean {\n if (other === this) {\n return true;\n } else if (other.isLeafNode()) {\n return false;\n } else {\n const otherChildrenNode = other as ChildrenNode;\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\n return false;\n } else if (\n this.children_.count() === otherChildrenNode.children_.count()\n ) {\n const thisIter = this.getIterator(PRIORITY_INDEX);\n const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);\n let thisCurrent = thisIter.getNext();\n let otherCurrent = otherIter.getNext();\n while (thisCurrent && otherCurrent) {\n if (\n thisCurrent.name !== otherCurrent.name ||\n !thisCurrent.node.equals(otherCurrent.node)\n ) {\n return false;\n }\n thisCurrent = thisIter.getNext();\n otherCurrent = otherIter.getNext();\n }\n return thisCurrent === null && otherCurrent === null;\n } else {\n return false;\n }\n }\n }\n\n /**\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\n * instead.\n *\n */\n private resolveIndex_(\n indexDefinition: Index\n ): SortedMap | null {\n if (indexDefinition === KEY_INDEX) {\n return null;\n } else {\n return this.indexMap_.get(indexDefinition.toString());\n }\n }\n}\n\nexport class MaxNode extends ChildrenNode {\n constructor() {\n super(\n new SortedMap(NAME_COMPARATOR),\n ChildrenNode.EMPTY_NODE,\n IndexMap.Default\n );\n }\n\n compareTo(other: Node): number {\n if (other === this) {\n return 0;\n } else {\n return 1;\n }\n }\n\n equals(other: Node): boolean {\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\n return other === this;\n }\n\n getPriority(): MaxNode {\n return this;\n }\n\n getImmediateChild(childName: string): ChildrenNode {\n return ChildrenNode.EMPTY_NODE;\n }\n\n isEmpty(): boolean {\n return false;\n }\n}\n\n/**\n * Marker that will sort higher than any other snapshot.\n */\nexport const MAX_NODE = new MaxNode();\n\n/**\n * Document NamedNode extensions\n */\ndeclare module './Node' {\n interface NamedNode {\n MIN: NamedNode;\n MAX: NamedNode;\n }\n}\n\nObject.defineProperties(NamedNode, {\n MIN: {\n value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)\n },\n MAX: {\n value: new NamedNode(MAX_NAME, MAX_NODE)\n }\n});\n\n/**\n * Reference Extensions\n */\nKeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\nLeafNode.__childrenNodeConstructor = ChildrenNode;\nsetMaxNode(MAX_NODE);\nsetPriorityMaxNode(MAX_NODE);\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains, assert } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport { SortedMap } from '../util/SortedMap';\nimport { each } from '../util/util';\n\nimport { ChildrenNode } from './ChildrenNode';\nimport { buildChildSet } from './childSet';\nimport { NAME_COMPARATOR, NAME_ONLY_COMPARATOR } from './comparators';\nimport { PRIORITY_INDEX, setNodeFromJSON } from './indexes/PriorityIndex';\nimport { IndexMap } from './IndexMap';\nimport { LeafNode } from './LeafNode';\nimport { NamedNode, Node } from './Node';\n\nconst USE_HINZE = true;\n\n/**\n * Constructs a snapshot node representing the passed JSON and returns it.\n * @param json - JSON to create a node for.\n * @param priority - Optional priority to use. This will be ignored if the\n * passed JSON contains a .priority property.\n */\nexport function nodeFromJSON(\n json: unknown | null,\n priority: unknown = null\n): Node {\n if (json === null) {\n return ChildrenNode.EMPTY_NODE;\n }\n\n if (typeof json === 'object' && '.priority' in json) {\n priority = json['.priority'];\n }\n\n assert(\n priority === null ||\n typeof priority === 'string' ||\n typeof priority === 'number' ||\n (typeof priority === 'object' && '.sv' in (priority as object)),\n 'Invalid priority type found: ' + typeof priority\n );\n\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\n json = json['.value'];\n }\n\n // Valid leaf nodes include non-objects or server-value wrapper objects\n if (typeof json !== 'object' || '.sv' in json) {\n const jsonLeaf = json as string | number | boolean | Indexable;\n return new LeafNode(jsonLeaf, nodeFromJSON(priority));\n }\n\n if (!(json instanceof Array) && USE_HINZE) {\n const children: NamedNode[] = [];\n let childrenHavePriority = false;\n const hinzeJsonObj = json;\n each(hinzeJsonObj, (key, child) => {\n if (key.substring(0, 1) !== '.') {\n // Ignore metadata nodes\n const childNode = nodeFromJSON(child);\n if (!childNode.isEmpty()) {\n childrenHavePriority =\n childrenHavePriority || !childNode.getPriority().isEmpty();\n children.push(new NamedNode(key, childNode));\n }\n }\n });\n\n if (children.length === 0) {\n return ChildrenNode.EMPTY_NODE;\n }\n\n const childSet = buildChildSet(\n children,\n NAME_ONLY_COMPARATOR,\n namedNode => namedNode.name,\n NAME_COMPARATOR\n ) as SortedMap;\n if (childrenHavePriority) {\n const sortedChildSet = buildChildSet(\n children,\n PRIORITY_INDEX.getCompare()\n );\n return new ChildrenNode(\n childSet,\n nodeFromJSON(priority),\n new IndexMap(\n { '.priority': sortedChildSet },\n { '.priority': PRIORITY_INDEX }\n )\n );\n } else {\n return new ChildrenNode(\n childSet,\n nodeFromJSON(priority),\n IndexMap.Default\n );\n }\n } else {\n let node: Node = ChildrenNode.EMPTY_NODE;\n each(json, (key: string, childData: unknown) => {\n if (contains(json as object, key)) {\n if (key.substring(0, 1) !== '.') {\n // ignore metadata nodes.\n const childNode = nodeFromJSON(childData);\n if (childNode.isLeafNode() || !childNode.isEmpty()) {\n node = node.updateImmediateChild(key, childNode);\n }\n }\n }\n });\n\n return node.updatePriority(nodeFromJSON(priority));\n }\n}\n\nsetNodeFromJSON(nodeFromJSON);\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Path, pathGetFront, pathIsEmpty, pathSlice } from '../../util/Path';\nimport { MAX_NAME, nameCompare } from '../../util/util';\nimport { ChildrenNode, MAX_NODE } from '../ChildrenNode';\nimport { NamedNode, Node } from '../Node';\nimport { nodeFromJSON } from '../nodeFromJSON';\n\nimport { Index } from './Index';\n\nexport class PathIndex extends Index {\n constructor(private indexPath_: Path) {\n super();\n\n assert(\n !pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority',\n \"Can't create PathIndex with empty path or .priority key\"\n );\n }\n\n protected extractChild(snap: Node): Node {\n return snap.getChild(this.indexPath_);\n }\n isDefinedOn(node: Node): boolean {\n return !node.getChild(this.indexPath_).isEmpty();\n }\n compare(a: NamedNode, b: NamedNode): number {\n const aChild = this.extractChild(a.node);\n const bChild = this.extractChild(b.node);\n const indexCmp = aChild.compareTo(bChild);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n makePost(indexValue: object, name: string): NamedNode {\n const valueNode = nodeFromJSON(indexValue);\n const node = ChildrenNode.EMPTY_NODE.updateChild(\n this.indexPath_,\n valueNode\n );\n return new NamedNode(name, node);\n }\n maxPost(): NamedNode {\n const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);\n return new NamedNode(MAX_NAME, node);\n }\n toString(): string {\n return pathSlice(this.indexPath_, 0).join('/');\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare } from '../../util/util';\nimport { NamedNode, Node } from '../Node';\nimport { nodeFromJSON } from '../nodeFromJSON';\n\nimport { Index } from './Index';\n\nexport class ValueIndex extends Index {\n compare(a: NamedNode, b: NamedNode): number {\n const indexCmp = a.node.compareTo(b.node);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n isDefinedOn(node: Node): boolean {\n return true;\n }\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return !oldNode.equals(newNode);\n }\n minPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n maxPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MAX;\n }\n\n makePost(indexValue: object, name: string): NamedNode {\n const valueNode = nodeFromJSON(indexValue);\n return new NamedNode(name, valueNode);\n }\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString(): string {\n return '.value';\n }\n}\n\nexport const VALUE_INDEX = new ValueIndex();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\n\nexport const enum ChangeType {\n /** Event type for a child added */\n CHILD_ADDED = 'child_added',\n /** Event type for a child removed */\n CHILD_REMOVED = 'child_removed',\n /** Event type for a child changed */\n CHILD_CHANGED = 'child_changed',\n /** Event type for a child moved */\n CHILD_MOVED = 'child_moved',\n /** Event type for a value change */\n VALUE = 'value'\n}\n\nexport interface Change {\n /** @param type - The event type */\n type: ChangeType;\n /** @param snapshotNode - The data */\n snapshotNode: Node;\n /** @param childName - The name for this child, if it's a child even */\n childName?: string;\n /** @param oldSnap - Used for intermediate processing of child changed events */\n oldSnap?: Node;\n /** * @param prevName - The name for the previous child, if applicable */\n prevName?: string | null;\n}\n\nexport function changeValue(snapshotNode: Node): Change {\n return { type: ChangeType.VALUE, snapshotNode };\n}\n\nexport function changeChildAdded(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_ADDED, snapshotNode, childName };\n}\n\nexport function changeChildRemoved(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_REMOVED, snapshotNode, childName };\n}\n\nexport function changeChildChanged(\n childName: string,\n snapshotNode: Node,\n oldSnap: Node\n): Change {\n return {\n type: ChangeType.CHILD_CHANGED,\n snapshotNode,\n childName,\n oldSnap\n };\n}\n\nexport function changeChildMoved(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_MOVED, snapshotNode, childName };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { PRIORITY_INDEX } from '../../snap/indexes/PriorityIndex';\nimport { Node } from '../../snap/Node';\nimport { Path } from '../../util/Path';\nimport {\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from '../Change';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\n\nimport { NodeFilter } from './NodeFilter';\n\n/**\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\n */\nexport class IndexedFilter implements NodeFilter {\n constructor(private readonly index_: Index) {}\n\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n assert(\n snap.isIndexed(this.index_),\n 'A node must be indexed if only a child is updated'\n );\n const oldChild = snap.getImmediateChild(key);\n // Check if anything actually changed.\n if (\n oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))\n ) {\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\n // to avoid treating these cases as \"nothing changed.\"\n if (oldChild.isEmpty() === newChild.isEmpty()) {\n // Nothing changed.\n\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\n return snap;\n }\n }\n\n if (optChangeAccumulator != null) {\n if (newChild.isEmpty()) {\n if (snap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(\n changeChildRemoved(key, oldChild)\n );\n } else {\n assert(\n snap.isLeafNode(),\n 'A child remove without an old child only makes sense on a leaf node'\n );\n }\n } else if (oldChild.isEmpty()) {\n optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));\n } else {\n optChangeAccumulator.trackChildChange(\n changeChildChanged(key, newChild, oldChild)\n );\n }\n }\n if (snap.isLeafNode() && newChild.isEmpty()) {\n return snap;\n } else {\n // Make sure the node is indexed\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\n }\n }\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (optChangeAccumulator != null) {\n if (!oldSnap.isLeafNode()) {\n oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (!newSnap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(\n changeChildRemoved(key, childNode)\n );\n }\n });\n }\n if (!newSnap.isLeafNode()) {\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (oldSnap.hasChild(key)) {\n const oldChild = oldSnap.getImmediateChild(key);\n if (!oldChild.equals(childNode)) {\n optChangeAccumulator.trackChildChange(\n changeChildChanged(key, childNode, oldChild)\n );\n }\n } else {\n optChangeAccumulator.trackChildChange(\n changeChildAdded(key, childNode)\n );\n }\n });\n }\n }\n return newSnap.withIndex(this.index_);\n }\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n if (oldSnap.isEmpty()) {\n return ChildrenNode.EMPTY_NODE;\n } else {\n return oldSnap.updatePriority(newPriority);\n }\n }\n filtersNodes(): boolean {\n return false;\n }\n getIndexedFilter(): IndexedFilter {\n return this;\n }\n getIndex(): Index {\n return this.index_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NamedNode, Node } from '../../../core/snap/Node';\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { PRIORITY_INDEX } from '../../snap/indexes/PriorityIndex';\nimport { Path } from '../../util/Path';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\nimport { QueryParams } from '../QueryParams';\n\nimport { IndexedFilter } from './IndexedFilter';\nimport { NodeFilter } from './NodeFilter';\n\n/**\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n */\nexport class RangedFilter implements NodeFilter {\n private indexedFilter_: IndexedFilter;\n\n private index_: Index;\n\n private startPost_: NamedNode;\n\n private endPost_: NamedNode;\n\n private startIsInclusive_: boolean;\n\n private endIsInclusive_: boolean;\n\n constructor(params: QueryParams) {\n this.indexedFilter_ = new IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n this.startIsInclusive_ = !params.startAfterSet_;\n this.endIsInclusive_ = !params.endBeforeSet_;\n }\n\n getStartPost(): NamedNode {\n return this.startPost_;\n }\n\n getEndPost(): NamedNode {\n return this.endPost_;\n }\n\n matches(node: NamedNode): boolean {\n const isWithinStart = this.startIsInclusive_\n ? this.index_.compare(this.getStartPost(), node) <= 0\n : this.index_.compare(this.getStartPost(), node) < 0;\n const isWithinEnd = this.endIsInclusive_\n ? this.index_.compare(node, this.getEndPost()) <= 0\n : this.index_.compare(node, this.getEndPost()) < 0;\n return isWithinStart && isWithinEnd;\n }\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (!this.matches(new NamedNode(key, newChild))) {\n newChild = ChildrenNode.EMPTY_NODE;\n }\n return this.indexedFilter_.updateChild(\n snap,\n key,\n newChild,\n affectedPath,\n source,\n optChangeAccumulator\n );\n }\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode.EMPTY_NODE;\n }\n let filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\n const self = this;\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (!self.matches(new NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(\n oldSnap,\n filtered,\n optChangeAccumulator\n );\n }\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n // Don't support priorities on queries\n return oldSnap;\n }\n filtersNodes(): boolean {\n return true;\n }\n getIndexedFilter(): IndexedFilter {\n return this.indexedFilter_;\n }\n getIndex(): Index {\n return this.index_;\n }\n\n private static getStartPost_(params: QueryParams): NamedNode {\n if (params.hasStart()) {\n const startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n } else {\n return params.getIndex().minPost();\n }\n }\n\n private static getEndPost_(params: QueryParams): NamedNode {\n if (params.hasEnd()) {\n const endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n } else {\n return params.getIndex().maxPost();\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { NamedNode, Node } from '../../snap/Node';\nimport { Path } from '../../util/Path';\nimport {\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from '../Change';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\nimport { QueryParams } from '../QueryParams';\n\nimport { IndexedFilter } from './IndexedFilter';\nimport { NodeFilter } from './NodeFilter';\nimport { RangedFilter } from './RangedFilter';\n\n/**\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n */\nexport class LimitedFilter implements NodeFilter {\n private readonly rangedFilter_: RangedFilter;\n\n private readonly index_: Index;\n\n private readonly limit_: number;\n\n private readonly reverse_: boolean;\n\n private readonly startIsInclusive_: boolean;\n\n private readonly endIsInclusive_: boolean;\n\n constructor(params: QueryParams) {\n this.rangedFilter_ = new RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n this.startIsInclusive_ = !params.startAfterSet_;\n this.endIsInclusive_ = !params.endBeforeSet_;\n }\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {\n newChild = ChildrenNode.EMPTY_NODE;\n }\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n } else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_\n .getIndexedFilter()\n .updateChild(\n snap,\n key,\n newChild,\n affectedPath,\n source,\n optChangeAccumulator\n );\n } else {\n return this.fullLimitUpdateChild_(\n snap,\n key,\n newChild,\n source,\n optChangeAccumulator\n );\n }\n }\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n let filtered;\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n } else {\n if (\n this.limit_ * 2 < newSnap.numChildren() &&\n newSnap.isIndexed(this.index_)\n ) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n // anchor to the startPost, endPost, or last element as appropriate\n let iterator;\n if (this.reverse_) {\n iterator = (newSnap as ChildrenNode).getReverseIteratorFrom(\n this.rangedFilter_.getEndPost(),\n this.index_\n );\n } else {\n iterator = (newSnap as ChildrenNode).getIteratorFrom(\n this.rangedFilter_.getStartPost(),\n this.index_\n );\n }\n let count = 0;\n while (iterator.hasNext() && count < this.limit_) {\n const next = iterator.getNext();\n if (!this.withinDirectionalStart(next)) {\n // if we have not reached the start, skip to the next element\n continue;\n } else if (!this.withinDirectionalEnd(next)) {\n // if we have reached the end, stop adding elements\n break;\n } else {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\n }\n }\n } else {\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(\n ChildrenNode.EMPTY_NODE\n ) as ChildrenNode;\n\n let iterator;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n } else {\n iterator = filtered.getIterator(this.index_);\n }\n\n let count = 0;\n while (iterator.hasNext()) {\n const next = iterator.getNext();\n const inRange =\n count < this.limit_ &&\n this.withinDirectionalStart(next) &&\n this.withinDirectionalEnd(next);\n if (inRange) {\n count++;\n } else {\n filtered = filtered.updateImmediateChild(\n next.name,\n ChildrenNode.EMPTY_NODE\n );\n }\n }\n }\n }\n return this.rangedFilter_\n .getIndexedFilter()\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n }\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n // Don't support priorities on queries\n return oldSnap;\n }\n filtersNodes(): boolean {\n return true;\n }\n getIndexedFilter(): IndexedFilter {\n return this.rangedFilter_.getIndexedFilter();\n }\n getIndex(): Index {\n return this.index_;\n }\n\n private fullLimitUpdateChild_(\n snap: Node,\n childKey: string,\n childSnap: Node,\n source: CompleteChildSource,\n changeAccumulator: ChildChangeAccumulator | null\n ): Node {\n // TODO: rename all cache stuff etc to general snap terminology\n let cmp;\n if (this.reverse_) {\n const indexCmp = this.index_.getCompare();\n cmp = (a: NamedNode, b: NamedNode) => indexCmp(b, a);\n } else {\n cmp = this.index_.getCompare();\n }\n const oldEventCache = snap as ChildrenNode;\n assert(oldEventCache.numChildren() === this.limit_, '');\n const newChildNamedNode = new NamedNode(childKey, childSnap);\n const windowBoundary = this.reverse_\n ? oldEventCache.getFirstChild(this.index_)\n : (oldEventCache.getLastChild(this.index_) as NamedNode);\n const inRange = this.rangedFilter_.matches(newChildNamedNode);\n if (oldEventCache.hasChild(childKey)) {\n const oldChildSnap = oldEventCache.getImmediateChild(childKey);\n let nextChild = source.getChildAfterChild(\n this.index_,\n windowBoundary,\n this.reverse_\n );\n while (\n nextChild != null &&\n (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))\n ) {\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\n // the limited filter...\n nextChild = source.getChildAfterChild(\n this.index_,\n nextChild,\n this.reverse_\n );\n }\n const compareNext =\n nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n const remainsInWindow =\n inRange && !childSnap.isEmpty() && compareNext >= 0;\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildChanged(childKey, childSnap, oldChildSnap)\n );\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n } else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildRemoved(childKey, oldChildSnap)\n );\n }\n const newEventCache = oldEventCache.updateImmediateChild(\n childKey,\n ChildrenNode.EMPTY_NODE\n );\n const nextChildInRange =\n nextChild != null && this.rangedFilter_.matches(nextChild);\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildAdded(nextChild.name, nextChild.node)\n );\n }\n return newEventCache.updateImmediateChild(\n nextChild.name,\n nextChild.node\n );\n } else {\n return newEventCache;\n }\n }\n } else if (childSnap.isEmpty()) {\n // we're deleting a node, but it was not in the window, so ignore it\n return snap;\n } else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildRemoved(windowBoundary.name, windowBoundary.node)\n );\n changeAccumulator.trackChildChange(\n changeChildAdded(childKey, childSnap)\n );\n }\n return oldEventCache\n .updateImmediateChild(childKey, childSnap)\n .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);\n } else {\n return snap;\n }\n } else {\n return snap;\n }\n }\n\n private withinDirectionalStart = (node: NamedNode) =>\n this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);\n\n private withinDirectionalEnd = (node: NamedNode) =>\n this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);\n\n private withinStartPost = (node: NamedNode) => {\n const compareRes = this.index_.compare(\n this.rangedFilter_.getStartPost(),\n node\n );\n return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;\n };\n\n private withinEndPost = (node: NamedNode) => {\n const compareRes = this.index_.compare(\n node,\n this.rangedFilter_.getEndPost()\n );\n return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, stringify } from '@firebase/util';\n\nimport { Index } from '../snap/indexes/Index';\nimport { KEY_INDEX } from '../snap/indexes/KeyIndex';\nimport { PathIndex } from '../snap/indexes/PathIndex';\nimport { PRIORITY_INDEX, PriorityIndex } from '../snap/indexes/PriorityIndex';\nimport { VALUE_INDEX } from '../snap/indexes/ValueIndex';\nimport { MAX_NAME, MIN_NAME } from '../util/util';\n\nimport { IndexedFilter } from './filter/IndexedFilter';\nimport { LimitedFilter } from './filter/LimitedFilter';\nimport { NodeFilter } from './filter/NodeFilter';\nimport { RangedFilter } from './filter/RangedFilter';\n\n/**\n * Wire Protocol Constants\n */\nconst enum WIRE_PROTOCOL_CONSTANTS {\n INDEX_START_VALUE = 'sp',\n INDEX_START_NAME = 'sn',\n INDEX_START_IS_INCLUSIVE = 'sin',\n INDEX_END_VALUE = 'ep',\n INDEX_END_NAME = 'en',\n INDEX_END_IS_INCLUSIVE = 'ein',\n LIMIT = 'l',\n VIEW_FROM = 'vf',\n VIEW_FROM_LEFT = 'l',\n VIEW_FROM_RIGHT = 'r',\n INDEX = 'i'\n}\n\n/**\n * REST Query Constants\n */\nconst enum REST_QUERY_CONSTANTS {\n ORDER_BY = 'orderBy',\n PRIORITY_INDEX = '$priority',\n VALUE_INDEX = '$value',\n KEY_INDEX = '$key',\n START_AFTER = 'startAfter',\n START_AT = 'startAt',\n END_AT = 'endAt',\n END_BEFORE = 'endBefore',\n LIMIT_TO_FIRST = 'limitToFirst',\n LIMIT_TO_LAST = 'limitToLast'\n}\n\n/**\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\n * user-facing API level, so it is not done here.\n *\n * @internal\n */\nexport class QueryParams {\n limitSet_ = false;\n startSet_ = false;\n startNameSet_ = false;\n startAfterSet_ = false; // can only be true if startSet_ is true\n endSet_ = false;\n endNameSet_ = false;\n endBeforeSet_ = false; // can only be true if endSet_ is true\n limit_ = 0;\n viewFrom_ = '';\n indexStartValue_: unknown | null = null;\n indexStartName_ = '';\n indexEndValue_: unknown | null = null;\n indexEndName_ = '';\n index_: PriorityIndex = PRIORITY_INDEX;\n\n hasStart(): boolean {\n return this.startSet_;\n }\n\n /**\n * @returns True if it would return from left.\n */\n isViewFromLeft(): boolean {\n if (this.viewFrom_ === '') {\n // limit(), rather than limitToFirst or limitToLast was called.\n // This means that only one of startSet_ and endSet_ is true. Use them\n // to calculate which side of the view to anchor to. If neither is set,\n // anchor to the end.\n return this.startSet_;\n } else {\n return this.viewFrom_ === WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n }\n }\n\n /**\n * Only valid to call if hasStart() returns true\n */\n getIndexStartValue(): unknown {\n assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n }\n\n /**\n * Only valid to call if hasStart() returns true.\n * Returns the starting key name for the range defined by these query parameters\n */\n getIndexStartName(): string {\n assert(this.startSet_, 'Only valid if start has been set');\n if (this.startNameSet_) {\n return this.indexStartName_;\n } else {\n return MIN_NAME;\n }\n }\n\n hasEnd(): boolean {\n return this.endSet_;\n }\n\n /**\n * Only valid to call if hasEnd() returns true.\n */\n getIndexEndValue(): unknown {\n assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n }\n\n /**\n * Only valid to call if hasEnd() returns true.\n * Returns the end key name for the range defined by these query parameters\n */\n getIndexEndName(): string {\n assert(this.endSet_, 'Only valid if end has been set');\n if (this.endNameSet_) {\n return this.indexEndName_;\n } else {\n return MAX_NAME;\n }\n }\n\n hasLimit(): boolean {\n return this.limitSet_;\n }\n\n /**\n * @returns True if a limit has been set and it has been explicitly anchored\n */\n hasAnchoredLimit(): boolean {\n return this.limitSet_ && this.viewFrom_ !== '';\n }\n\n /**\n * Only valid to call if hasLimit() returns true\n */\n getLimit(): number {\n assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n }\n\n getIndex(): Index {\n return this.index_;\n }\n\n loadsAllData(): boolean {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n }\n\n isDefault(): boolean {\n return this.loadsAllData() && this.index_ === PRIORITY_INDEX;\n }\n\n copy(): QueryParams {\n const copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.startAfterSet_ = this.startAfterSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.endBeforeSet_ = this.endBeforeSet_;\n copy.indexEndValue_ = this.indexEndValue_;\n copy.endNameSet_ = this.endNameSet_;\n copy.indexEndName_ = this.indexEndName_;\n copy.index_ = this.index_;\n copy.viewFrom_ = this.viewFrom_;\n return copy;\n }\n}\n\nexport function queryParamsGetNodeFilter(queryParams: QueryParams): NodeFilter {\n if (queryParams.loadsAllData()) {\n return new IndexedFilter(queryParams.getIndex());\n } else if (queryParams.hasLimit()) {\n return new LimitedFilter(queryParams);\n } else {\n return new RangedFilter(queryParams);\n }\n}\n\nexport function queryParamsLimit(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n}\n\nexport function queryParamsLimitToFirst(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n return newParams;\n}\n\nexport function queryParamsLimitToLast(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n return newParams;\n}\n\nexport function queryParamsStartAt(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.startSet_ = true;\n if (indexValue === undefined) {\n indexValue = null;\n }\n newParams.indexStartValue_ = indexValue;\n if (key != null) {\n newParams.startNameSet_ = true;\n newParams.indexStartName_ = key;\n } else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n return newParams;\n}\n\nexport function queryParamsStartAfter(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n let params: QueryParams;\n if (queryParams.index_ === KEY_INDEX || !!key) {\n params = queryParamsStartAt(queryParams, indexValue, key);\n } else {\n params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);\n }\n params.startAfterSet_ = true;\n return params;\n}\n\nexport function queryParamsEndAt(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.endSet_ = true;\n if (indexValue === undefined) {\n indexValue = null;\n }\n newParams.indexEndValue_ = indexValue;\n if (key !== undefined) {\n newParams.endNameSet_ = true;\n newParams.indexEndName_ = key;\n } else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n return newParams;\n}\n\nexport function queryParamsEndBefore(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n let params: QueryParams;\n if (queryParams.index_ === KEY_INDEX || !!key) {\n params = queryParamsEndAt(queryParams, indexValue, key);\n } else {\n params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);\n }\n params.endBeforeSet_ = true;\n return params;\n}\n\nexport function queryParamsOrderBy(\n queryParams: QueryParams,\n index: Index\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.index_ = index;\n return newParams;\n}\n\n/**\n * Returns a set of REST query string parameters representing this query.\n *\n * @returns query string parameters\n */\nexport function queryParamsToRestQueryStringParameters(\n queryParams: QueryParams\n): Record {\n const qs: Record = {};\n\n if (queryParams.isDefault()) {\n return qs;\n }\n\n let orderBy;\n if (queryParams.index_ === PRIORITY_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.PRIORITY_INDEX;\n } else if (queryParams.index_ === VALUE_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.VALUE_INDEX;\n } else if (queryParams.index_ === KEY_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.KEY_INDEX;\n } else {\n assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');\n orderBy = queryParams.index_.toString();\n }\n qs[REST_QUERY_CONSTANTS.ORDER_BY] = stringify(orderBy);\n\n if (queryParams.startSet_) {\n const startParam = queryParams.startAfterSet_\n ? REST_QUERY_CONSTANTS.START_AFTER\n : REST_QUERY_CONSTANTS.START_AT;\n qs[startParam] = stringify(queryParams.indexStartValue_);\n if (queryParams.startNameSet_) {\n qs[startParam] += ',' + stringify(queryParams.indexStartName_);\n }\n }\n\n if (queryParams.endSet_) {\n const endParam = queryParams.endBeforeSet_\n ? REST_QUERY_CONSTANTS.END_BEFORE\n : REST_QUERY_CONSTANTS.END_AT;\n qs[endParam] = stringify(queryParams.indexEndValue_);\n if (queryParams.endNameSet_) {\n qs[endParam] += ',' + stringify(queryParams.indexEndName_);\n }\n }\n\n if (queryParams.limitSet_) {\n if (queryParams.isViewFromLeft()) {\n qs[REST_QUERY_CONSTANTS.LIMIT_TO_FIRST] = queryParams.limit_;\n } else {\n qs[REST_QUERY_CONSTANTS.LIMIT_TO_LAST] = queryParams.limit_;\n }\n }\n\n return qs;\n}\n\nexport function queryParamsGetQueryObject(\n queryParams: QueryParams\n): Record {\n const obj: Record = {};\n if (queryParams.startSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] =\n queryParams.indexStartValue_;\n if (queryParams.startNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] =\n queryParams.indexStartName_;\n }\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE] =\n !queryParams.startAfterSet_;\n }\n if (queryParams.endSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = queryParams.indexEndValue_;\n if (queryParams.endNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = queryParams.indexEndName_;\n }\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE] =\n !queryParams.endBeforeSet_;\n }\n if (queryParams.limitSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = queryParams.limit_;\n let viewFrom = queryParams.viewFrom_;\n if (viewFrom === '') {\n if (queryParams.isViewFromLeft()) {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n } else {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n }\n }\n obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom;\n }\n // For now, priority index is the default, so we only specify if it's some other index\n if (queryParams.index_ !== PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = queryParams.index_.toString();\n }\n return obj;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n jsonEval,\n safeGet,\n querystring,\n Deferred\n} from '@firebase/util';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { logWrapper, warn } from './util/util';\nimport { QueryContext } from './view/EventRegistration';\nimport { queryParamsToRestQueryStringParameters } from './view/QueryParams';\n\n/**\n * An implementation of ServerActions that communicates with the server via REST requests.\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\n * persistent connection (using WebSockets or long-polling)\n */\nexport class ReadonlyRestClient extends ServerActions {\n reportStats(stats: { [k: string]: unknown }): void {\n throw new Error('Method not implemented.');\n }\n\n /** @private {function(...[*])} */\n private log_: (...args: unknown[]) => void = logWrapper('p:rest:');\n\n /**\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\n * that's been removed. :-/\n */\n private listens_: { [k: string]: object } = {};\n\n static getListenId_(query: QueryContext, tag?: number | null): string {\n if (tag !== undefined) {\n return 'tag$' + tag;\n } else {\n assert(\n query._queryParams.isDefault(),\n \"should have a tag if it's not a default query.\"\n );\n return query._path.toString();\n }\n }\n\n /**\n * @param repoInfo_ - Data about the namespace we are connecting to\n * @param onDataUpdate_ - A callback for new data from the server\n */\n constructor(\n private repoInfo_: RepoInfo,\n private onDataUpdate_: (\n a: string,\n b: unknown,\n c: boolean,\n d: number | null\n ) => void,\n private authTokenProvider_: AuthTokenProvider,\n private appCheckTokenProvider_: AppCheckTokenProvider\n ) {\n super();\n }\n\n /** @inheritDoc */\n listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ) {\n const pathString = query._path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);\n\n // Mark this listener so we can tell if it's removed.\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\n const thisListen = {};\n this.listens_[listenId] = thisListen;\n\n const queryStringParameters = queryParamsToRestQueryStringParameters(\n query._queryParams\n );\n\n this.restRequest_(\n pathString + '.json',\n queryStringParameters,\n (error, result) => {\n let data = result;\n\n if (error === 404) {\n data = null;\n error = null;\n }\n\n if (error === null) {\n this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n }\n\n if (safeGet(this.listens_, listenId) === thisListen) {\n let status;\n if (!error) {\n status = 'ok';\n } else if (error === 401) {\n status = 'permission_denied';\n } else {\n status = 'rest_error:' + error;\n }\n\n onComplete(status, null);\n }\n }\n );\n }\n\n /** @inheritDoc */\n unlisten(query: QueryContext, tag: number | null) {\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n }\n\n get(query: QueryContext): Promise {\n const queryStringParameters = queryParamsToRestQueryStringParameters(\n query._queryParams\n );\n\n const pathString = query._path.toString();\n\n const deferred = new Deferred();\n\n this.restRequest_(\n pathString + '.json',\n queryStringParameters,\n (error, result) => {\n let data = result;\n\n if (error === 404) {\n data = null;\n error = null;\n }\n\n if (error === null) {\n this.onDataUpdate_(\n pathString,\n data,\n /*isMerge=*/ false,\n /*tag=*/ null\n );\n deferred.resolve(data as string);\n } else {\n deferred.reject(new Error(data as string));\n }\n }\n );\n return deferred.promise;\n }\n\n /** @inheritDoc */\n refreshAuthToken(token: string) {\n // no-op since we just always call getToken.\n }\n\n /**\n * Performs a REST request to the given path, with the provided query string parameters,\n * and any auth credentials we have.\n */\n private restRequest_(\n pathString: string,\n queryStringParameters: { [k: string]: string | number } = {},\n callback: ((a: number | null, b?: unknown) => void) | null\n ) {\n queryStringParameters['format'] = 'export';\n\n return Promise.all([\n this.authTokenProvider_.getToken(/*forceRefresh=*/ false),\n this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)\n ]).then(([authToken, appCheckToken]) => {\n if (authToken && authToken.accessToken) {\n queryStringParameters['auth'] = authToken.accessToken;\n }\n if (appCheckToken && appCheckToken.token) {\n queryStringParameters['ac'] = appCheckToken.token;\n }\n\n const url =\n (this.repoInfo_.secure ? 'https://' : 'http://') +\n this.repoInfo_.host +\n pathString +\n '?' +\n 'ns=' +\n this.repoInfo_.namespace +\n querystring(queryStringParameters);\n\n this.log_('Sending REST request for ' + url);\n const xhr = new XMLHttpRequest();\n xhr.onreadystatechange = () => {\n if (callback && xhr.readyState === 4) {\n this.log_(\n 'REST Response for ' + url + ' received. status:',\n xhr.status,\n 'response:',\n xhr.responseText\n );\n let res = null;\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = jsonEval(xhr.responseText);\n } catch (e) {\n warn(\n 'Failed to parse JSON response for ' +\n url +\n ': ' +\n xhr.responseText\n );\n }\n callback(null, res);\n } else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n warn(\n 'Got unsuccessful REST response for ' +\n url +\n ' Status: ' +\n xhr.status\n );\n }\n callback(xhr.status);\n }\n callback = null;\n }\n };\n\n xhr.open('GET', url, /*asynchronous=*/ true);\n xhr.send();\n });\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { Path } from './util/Path';\n\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n */\nexport class SnapshotHolder {\n private rootNode_: Node = ChildrenNode.EMPTY_NODE;\n\n getNode(path: Path): Node {\n return this.rootNode_.getChild(path);\n }\n\n updateSnapshot(path: Path, newSnapshotNode: Node) {\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { Node } from './snap/Node';\nimport { Path, pathGetFront, pathIsEmpty, pathPopFront } from './util/Path';\n\n/**\n * Helper class to store a sparse set of snapshots.\n */\nexport interface SparseSnapshotTree {\n value: Node | null;\n readonly children: Map;\n}\n\nexport function newSparseSnapshotTree(): SparseSnapshotTree {\n return {\n value: null,\n children: new Map()\n };\n}\n\n/**\n * Gets the node stored at the given path if one exists.\n * Only seems to be used in tests.\n *\n * @param path - Path to look up snapshot for.\n * @returns The retrieved node, or null.\n */\nexport function sparseSnapshotTreeFind(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path\n): Node | null {\n if (sparseSnapshotTree.value != null) {\n return sparseSnapshotTree.value.getChild(path);\n } else if (!pathIsEmpty(path) && sparseSnapshotTree.children.size > 0) {\n const childKey = pathGetFront(path);\n path = pathPopFront(path);\n if (sparseSnapshotTree.children.has(childKey)) {\n const childTree = sparseSnapshotTree.children.get(childKey);\n return sparseSnapshotTreeFind(childTree, path);\n } else {\n return null;\n }\n } else {\n return null;\n }\n}\n\n/**\n * Stores the given node at the specified path. If there is already a node\n * at a shallower path, it merges the new data into that snapshot node.\n *\n * @param path - Path to look up snapshot for.\n * @param data - The new data, or null.\n */\nexport function sparseSnapshotTreeRemember(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path,\n data: Node\n): void {\n if (pathIsEmpty(path)) {\n sparseSnapshotTree.value = data;\n sparseSnapshotTree.children.clear();\n } else if (sparseSnapshotTree.value !== null) {\n sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);\n } else {\n const childKey = pathGetFront(path);\n if (!sparseSnapshotTree.children.has(childKey)) {\n sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());\n }\n\n const child = sparseSnapshotTree.children.get(childKey);\n path = pathPopFront(path);\n sparseSnapshotTreeRemember(child, path, data);\n }\n}\n\n/**\n * Purge the data at path from the cache.\n *\n * @param path - Path to look up snapshot for.\n * @returns True if this node should now be removed.\n */\nexport function sparseSnapshotTreeForget(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path\n): boolean {\n if (pathIsEmpty(path)) {\n sparseSnapshotTree.value = null;\n sparseSnapshotTree.children.clear();\n return true;\n } else {\n if (sparseSnapshotTree.value !== null) {\n if (sparseSnapshotTree.value.isLeafNode()) {\n // We're trying to forget a node that doesn't exist\n return false;\n } else {\n const value = sparseSnapshotTree.value;\n sparseSnapshotTree.value = null;\n\n value.forEachChild(PRIORITY_INDEX, (key, tree) => {\n sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);\n });\n\n return sparseSnapshotTreeForget(sparseSnapshotTree, path);\n }\n } else if (sparseSnapshotTree.children.size > 0) {\n const childKey = pathGetFront(path);\n path = pathPopFront(path);\n if (sparseSnapshotTree.children.has(childKey)) {\n const safeToRemove = sparseSnapshotTreeForget(\n sparseSnapshotTree.children.get(childKey),\n path\n );\n if (safeToRemove) {\n sparseSnapshotTree.children.delete(childKey);\n }\n }\n\n return sparseSnapshotTree.children.size === 0;\n } else {\n return true;\n }\n }\n}\n\n/**\n * Recursively iterates through all of the stored tree and calls the\n * callback on each one.\n *\n * @param prefixPath - Path to look up node for.\n * @param func - The function to invoke for each tree.\n */\nexport function sparseSnapshotTreeForEachTree(\n sparseSnapshotTree: SparseSnapshotTree,\n prefixPath: Path,\n func: (a: Path, b: Node) => unknown\n): void {\n if (sparseSnapshotTree.value !== null) {\n func(prefixPath, sparseSnapshotTree.value);\n } else {\n sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {\n const path = new Path(prefixPath.toString() + '/' + key);\n sparseSnapshotTreeForEachTree(tree, path, func);\n });\n }\n}\n\n/**\n * Iterates through each immediate child and triggers the callback.\n * Only seems to be used in tests.\n *\n * @param func - The function to invoke for each child.\n */\nexport function sparseSnapshotTreeForEachChild(\n sparseSnapshotTree: SparseSnapshotTree,\n func: (a: string, b: SparseSnapshotTree) => void\n): void {\n sparseSnapshotTree.children.forEach((tree, key) => {\n func(key, tree);\n });\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { each } from '../util/util';\n\nimport { StatsCollection } from './StatsCollection';\n\n/**\n * Returns the delta from the previous call to get stats.\n *\n * @param collection_ - The collection to \"listen\" to.\n */\nexport class StatsListener {\n private last_: { [k: string]: number } | null = null;\n\n constructor(private collection_: StatsCollection) {}\n\n get(): { [k: string]: number } {\n const newStats = this.collection_.get();\n\n const delta = { ...newStats };\n if (this.last_) {\n each(this.last_, (stat: string, value: number) => {\n delta[stat] = delta[stat] - value;\n });\n }\n this.last_ = newStats;\n\n return delta;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains } from '@firebase/util';\n\nimport { ServerActions } from '../ServerActions';\nimport { setTimeoutNonBlocking, each } from '../util/util';\n\nimport { StatsCollection } from './StatsCollection';\nimport { StatsListener } from './StatsListener';\n\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\n// seconds to try to ensure the Firebase connection is established / settled.\nconst FIRST_STATS_MIN_TIME = 10 * 1000;\nconst FIRST_STATS_MAX_TIME = 30 * 1000;\n\n// We'll continue to report stats on average every 5 minutes.\nconst REPORT_STATS_INTERVAL = 5 * 60 * 1000;\n\nexport class StatsReporter {\n private statsListener_: StatsListener;\n statsToReport_: { [k: string]: boolean } = {};\n\n constructor(collection: StatsCollection, private server_: ServerActions) {\n this.statsListener_ = new StatsListener(collection);\n\n const timeout =\n FIRST_STATS_MIN_TIME +\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n }\n\n private reportStats_() {\n const stats = this.statsListener_.get();\n const reportedStats: typeof stats = {};\n let haveStatsToReport = false;\n\n each(stats, (stat: string, value: number) => {\n if (value > 0 && contains(this.statsToReport_, stat)) {\n reportedStats[stat] = value;\n haveStatsToReport = true;\n }\n });\n\n if (haveStatsToReport) {\n this.server_.reportStats(reportedStats);\n }\n\n // queue our next run.\n setTimeoutNonBlocking(\n this.reportStats_.bind(this),\n Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL)\n );\n }\n}\n\nexport function statsReporterIncludeStat(\n reporter: StatsReporter,\n stat: string\n) {\n reporter.statsToReport_[stat] = true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Path } from '../util/Path';\n\n/**\n *\n * @enum\n */\nexport enum OperationType {\n OVERWRITE,\n MERGE,\n ACK_USER_WRITE,\n LISTEN_COMPLETE\n}\n\n/**\n * @interface\n */\nexport interface Operation {\n source: OperationSource;\n\n type: OperationType;\n\n path: Path;\n\n operationForChild(childName: string): Operation | null;\n}\n\nexport interface OperationSource {\n fromUser: boolean;\n fromServer: boolean;\n queryId: string | null;\n tagged: boolean;\n}\n\nexport function newOperationSourceUser(): OperationSource {\n return {\n fromUser: true,\n fromServer: false,\n queryId: null,\n tagged: false\n };\n}\n\nexport function newOperationSourceServer(): OperationSource {\n return {\n fromUser: false,\n fromServer: true,\n queryId: null,\n tagged: false\n };\n}\n\nexport function newOperationSourceServerTaggedQuery(\n queryId: string\n): OperationSource {\n return {\n fromUser: false,\n fromServer: true,\n queryId,\n tagged: true\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\n\nimport { newOperationSourceUser, Operation, OperationType } from './Operation';\n\nexport class AckUserWrite implements Operation {\n /** @inheritDoc */\n type = OperationType.ACK_USER_WRITE;\n\n /** @inheritDoc */\n source = newOperationSourceUser();\n\n /**\n * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.\n */\n constructor(\n /** @inheritDoc */ public path: Path,\n /** @inheritDoc */ public affectedTree: ImmutableTree,\n /** @inheritDoc */ public revert: boolean\n ) {}\n operationForChild(childName: string): AckUserWrite {\n if (!pathIsEmpty(this.path)) {\n assert(\n pathGetFront(this.path) === childName,\n 'operationForChild called for unrelated child.'\n );\n return new AckUserWrite(\n pathPopFront(this.path),\n this.affectedTree,\n this.revert\n );\n } else if (this.affectedTree.value != null) {\n assert(\n this.affectedTree.children.isEmpty(),\n 'affectedTree should not have overlapping affected paths.'\n );\n // All child locations are affected as well; just return same operation.\n return this;\n } else {\n const childTree = this.affectedTree.subtree(new Path(childName));\n return new AckUserWrite(newEmptyPath(), childTree, this.revert);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { newEmptyPath, Path, pathIsEmpty, pathPopFront } from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './Operation';\n\nexport class ListenComplete implements Operation {\n /** @inheritDoc */\n type = OperationType.LISTEN_COMPLETE;\n\n constructor(public source: OperationSource, public path: Path) {}\n\n operationForChild(childName: string): ListenComplete {\n if (pathIsEmpty(this.path)) {\n return new ListenComplete(this.source, newEmptyPath());\n } else {\n return new ListenComplete(this.source, pathPopFront(this.path));\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\nimport { newEmptyPath, Path, pathIsEmpty, pathPopFront } from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './Operation';\n\nexport class Overwrite implements Operation {\n /** @inheritDoc */\n type = OperationType.OVERWRITE;\n\n constructor(\n public source: OperationSource,\n public path: Path,\n public snap: Node\n ) {}\n\n operationForChild(childName: string): Overwrite {\n if (pathIsEmpty(this.path)) {\n return new Overwrite(\n this.source,\n newEmptyPath(),\n this.snap.getImmediateChild(childName)\n );\n } else {\n return new Overwrite(this.source, pathPopFront(this.path), this.snap);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Node } from '../snap/Node';\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './Operation';\nimport { Overwrite } from './Overwrite';\n\nexport class Merge implements Operation {\n /** @inheritDoc */\n type = OperationType.MERGE;\n\n constructor(\n /** @inheritDoc */ public source: OperationSource,\n /** @inheritDoc */ public path: Path,\n /** @inheritDoc */ public children: ImmutableTree\n ) {}\n operationForChild(childName: string): Operation {\n if (pathIsEmpty(this.path)) {\n const childTree = this.children.subtree(new Path(childName));\n if (childTree.isEmpty()) {\n // This child is unaffected\n return null;\n } else if (childTree.value) {\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\n return new Overwrite(this.source, newEmptyPath(), childTree.value);\n } else {\n // This is a merge at a deeper level\n return new Merge(this.source, newEmptyPath(), childTree);\n }\n } else {\n assert(\n pathGetFront(this.path) === childName,\n \"Can't get a merge for a child not on the path of the operation\"\n );\n return new Merge(this.source, pathPopFront(this.path), this.children);\n }\n }\n toString(): string {\n return (\n 'Operation(' +\n this.path +\n ': ' +\n this.source.toString() +\n ' merge: ' +\n this.children.toString() +\n ')'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\nimport { Path, pathGetFront, pathIsEmpty } from '../util/Path';\n\n/**\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\n * whether a node potentially had children removed due to a filter.\n */\nexport class CacheNode {\n constructor(\n private node_: Node,\n private fullyInitialized_: boolean,\n private filtered_: boolean\n ) {}\n\n /**\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\n */\n isFullyInitialized(): boolean {\n return this.fullyInitialized_;\n }\n\n /**\n * Returns whether this node is potentially missing children due to a filter applied to the node\n */\n isFiltered(): boolean {\n return this.filtered_;\n }\n\n isCompleteForPath(path: Path): boolean {\n if (pathIsEmpty(path)) {\n return this.isFullyInitialized() && !this.filtered_;\n }\n\n const childKey = pathGetFront(path);\n return this.isCompleteForChild(childKey);\n }\n\n isCompleteForChild(key: string): boolean {\n return (\n (this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key)\n );\n }\n\n getNode(): Node {\n return this.node_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assertionError } from '@firebase/util';\n\nimport { Index } from '../snap/indexes/Index';\nimport { NamedNode, Node } from '../snap/Node';\n\nimport { Change, ChangeType, changeChildMoved } from './Change';\nimport { Event } from './Event';\nimport { EventRegistration, QueryContext } from './EventRegistration';\n\n/**\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\n * for details.\n *\n */\nexport class EventGenerator {\n index_: Index;\n\n constructor(public query_: QueryContext) {\n this.index_ = this.query_._queryParams.getIndex();\n }\n}\n\n/**\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\n *\n * Notes:\n * - child_moved events will be synthesized at this time for any child_changed events that affect\n * our index.\n * - prevName will be calculated based on the index ordering.\n */\nexport function eventGeneratorGenerateEventsForChanges(\n eventGenerator: EventGenerator,\n changes: Change[],\n eventCache: Node,\n eventRegistrations: EventRegistration[]\n): Event[] {\n const events: Event[] = [];\n const moves: Change[] = [];\n\n changes.forEach(change => {\n if (\n change.type === ChangeType.CHILD_CHANGED &&\n eventGenerator.index_.indexedValueChanged(\n change.oldSnap as Node,\n change.snapshotNode\n )\n ) {\n moves.push(changeChildMoved(change.childName, change.snapshotNode));\n }\n });\n\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_REMOVED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_ADDED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_MOVED,\n moves,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_CHANGED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.VALUE,\n changes,\n eventRegistrations,\n eventCache\n );\n\n return events;\n}\n\n/**\n * Given changes of a single change type, generate the corresponding events.\n */\nfunction eventGeneratorGenerateEventsForType(\n eventGenerator: EventGenerator,\n events: Event[],\n eventType: string,\n changes: Change[],\n registrations: EventRegistration[],\n eventCache: Node\n) {\n const filteredChanges = changes.filter(change => change.type === eventType);\n\n filteredChanges.sort((a, b) =>\n eventGeneratorCompareChanges(eventGenerator, a, b)\n );\n filteredChanges.forEach(change => {\n const materializedChange = eventGeneratorMaterializeSingleChange(\n eventGenerator,\n change,\n eventCache\n );\n registrations.forEach(registration => {\n if (registration.respondsTo(change.type)) {\n events.push(\n registration.createEvent(materializedChange, eventGenerator.query_)\n );\n }\n });\n });\n}\n\nfunction eventGeneratorMaterializeSingleChange(\n eventGenerator: EventGenerator,\n change: Change,\n eventCache: Node\n): Change {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n } else {\n change.prevName = eventCache.getPredecessorChildName(\n change.childName,\n change.snapshotNode,\n eventGenerator.index_\n );\n return change;\n }\n}\n\nfunction eventGeneratorCompareChanges(\n eventGenerator: EventGenerator,\n a: Change,\n b: Change\n) {\n if (a.childName == null || b.childName == null) {\n throw assertionError('Should only compare child_ events.');\n }\n const aWrapped = new NamedNode(a.childName, a.snapshotNode);\n const bWrapped = new NamedNode(b.childName, b.snapshotNode);\n return eventGenerator.index_.compare(aWrapped, bWrapped);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\n\nimport { CacheNode } from './CacheNode';\n\n/**\n * Stores the data we have cached for a view.\n *\n * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes).\n */\nexport interface ViewCache {\n readonly eventCache: CacheNode;\n readonly serverCache: CacheNode;\n}\n\nexport function newViewCache(\n eventCache: CacheNode,\n serverCache: CacheNode\n): ViewCache {\n return { eventCache, serverCache };\n}\n\nexport function viewCacheUpdateEventSnap(\n viewCache: ViewCache,\n eventSnap: Node,\n complete: boolean,\n filtered: boolean\n): ViewCache {\n return newViewCache(\n new CacheNode(eventSnap, complete, filtered),\n viewCache.serverCache\n );\n}\n\nexport function viewCacheUpdateServerSnap(\n viewCache: ViewCache,\n serverSnap: Node,\n complete: boolean,\n filtered: boolean\n): ViewCache {\n return newViewCache(\n viewCache.eventCache,\n new CacheNode(serverSnap, complete, filtered)\n );\n}\n\nexport function viewCacheGetCompleteEventSnap(\n viewCache: ViewCache\n): Node | null {\n return viewCache.eventCache.isFullyInitialized()\n ? viewCache.eventCache.getNode()\n : null;\n}\n\nexport function viewCacheGetCompleteServerSnap(\n viewCache: ViewCache\n): Node | null {\n return viewCache.serverCache.isFullyInitialized()\n ? viewCache.serverCache.getNode()\n : null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n newEmptyPath,\n Path,\n pathChild,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from './Path';\nimport { SortedMap } from './SortedMap';\nimport { each, stringCompare } from './util';\n\nlet emptyChildrenSingleton: SortedMap>;\n\n/**\n * Singleton empty children collection.\n *\n */\nconst EmptyChildren = (): SortedMap> => {\n if (!emptyChildrenSingleton) {\n emptyChildrenSingleton = new SortedMap>(\n stringCompare\n );\n }\n return emptyChildrenSingleton;\n};\n\n/**\n * A tree with immutable elements.\n */\nexport class ImmutableTree {\n static fromObject(obj: { [k: string]: T }): ImmutableTree {\n let tree: ImmutableTree = new ImmutableTree(null);\n each(obj, (childPath: string, childSnap: T) => {\n tree = tree.set(new Path(childPath), childSnap);\n });\n return tree;\n }\n\n constructor(\n public readonly value: T | null,\n public readonly children: SortedMap<\n string,\n ImmutableTree\n > = EmptyChildren()\n ) {}\n\n /**\n * True if the value is empty and there are no children\n */\n isEmpty(): boolean {\n return this.value === null && this.children.isEmpty();\n }\n\n /**\n * Given a path and predicate, return the first node and the path to that node\n * where the predicate returns true.\n *\n * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`\n * objects on the way back out, it may be better to pass down a pathSoFar obj.\n *\n * @param relativePath - The remainder of the path\n * @param predicate - The predicate to satisfy to return a node\n */\n findRootMostMatchingPathAndValue(\n relativePath: Path,\n predicate: (a: T) => boolean\n ): { path: Path; value: T } | null {\n if (this.value != null && predicate(this.value)) {\n return { path: newEmptyPath(), value: this.value };\n } else {\n if (pathIsEmpty(relativePath)) {\n return null;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child !== null) {\n const childExistingPathAndValue =\n child.findRootMostMatchingPathAndValue(\n pathPopFront(relativePath),\n predicate\n );\n if (childExistingPathAndValue != null) {\n const fullPath = pathChild(\n new Path(front),\n childExistingPathAndValue.path\n );\n return { path: fullPath, value: childExistingPathAndValue.value };\n } else {\n return null;\n }\n } else {\n return null;\n }\n }\n }\n }\n\n /**\n * Find, if it exists, the shortest subpath of the given path that points a defined\n * value in the tree\n */\n findRootMostValueAndPath(\n relativePath: Path\n ): { path: Path; value: T } | null {\n return this.findRootMostMatchingPathAndValue(relativePath, () => true);\n }\n\n /**\n * @returns The subtree at the given path\n */\n subtree(relativePath: Path): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n return this;\n } else {\n const front = pathGetFront(relativePath);\n const childTree = this.children.get(front);\n if (childTree !== null) {\n return childTree.subtree(pathPopFront(relativePath));\n } else {\n return new ImmutableTree(null);\n }\n }\n }\n\n /**\n * Sets a value at the specified path.\n *\n * @param relativePath - Path to set value at.\n * @param toSet - Value to set.\n * @returns Resulting tree.\n */\n set(relativePath: Path, toSet: T | null): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n return new ImmutableTree(toSet, this.children);\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front) || new ImmutableTree(null);\n const newChild = child.set(pathPopFront(relativePath), toSet);\n const newChildren = this.children.insert(front, newChild);\n return new ImmutableTree(this.value, newChildren);\n }\n }\n\n /**\n * Removes the value at the specified path.\n *\n * @param relativePath - Path to value to remove.\n * @returns Resulting tree.\n */\n remove(relativePath: Path): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n if (this.children.isEmpty()) {\n return new ImmutableTree(null);\n } else {\n return new ImmutableTree(null, this.children);\n }\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child) {\n const newChild = child.remove(pathPopFront(relativePath));\n let newChildren;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n } else {\n newChildren = this.children.insert(front, newChild);\n }\n if (this.value === null && newChildren.isEmpty()) {\n return new ImmutableTree(null);\n } else {\n return new ImmutableTree(this.value, newChildren);\n }\n } else {\n return this;\n }\n }\n }\n\n /**\n * Gets a value from the tree.\n *\n * @param relativePath - Path to get value for.\n * @returns Value at path, or null.\n */\n get(relativePath: Path): T | null {\n if (pathIsEmpty(relativePath)) {\n return this.value;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child) {\n return child.get(pathPopFront(relativePath));\n } else {\n return null;\n }\n }\n }\n\n /**\n * Replace the subtree at the specified path with the given new tree.\n *\n * @param relativePath - Path to replace subtree for.\n * @param newTree - New tree.\n * @returns Resulting tree.\n */\n setTree(relativePath: Path, newTree: ImmutableTree): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n return newTree;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front) || new ImmutableTree(null);\n const newChild = child.setTree(pathPopFront(relativePath), newTree);\n let newChildren;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n } else {\n newChildren = this.children.insert(front, newChild);\n }\n return new ImmutableTree(this.value, newChildren);\n }\n }\n\n /**\n * Performs a depth first fold on this tree. Transforms a tree into a single\n * value, given a function that operates on the path to a node, an optional\n * current value, and a map of child names to folded subtrees\n */\n fold(fn: (path: Path, value: T, children: { [k: string]: V }) => V): V {\n return this.fold_(newEmptyPath(), fn);\n }\n\n /**\n * Recursive helper for public-facing fold() method\n */\n private fold_(\n pathSoFar: Path,\n fn: (path: Path, value: T | null, children: { [k: string]: V }) => V\n ): V {\n const accum: { [k: string]: V } = {};\n this.children.inorderTraversal(\n (childKey: string, childTree: ImmutableTree) => {\n accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);\n }\n );\n return fn(pathSoFar, this.value, accum);\n }\n\n /**\n * Find the first matching value on the given path. Return the result of applying f to it.\n */\n findOnPath(path: Path, f: (path: Path, value: T) => V | null): V | null {\n return this.findOnPath_(path, newEmptyPath(), f);\n }\n\n private findOnPath_(\n pathToFollow: Path,\n pathSoFar: Path,\n f: (path: Path, value: T) => V | null\n ): V | null {\n const result = this.value ? f(pathSoFar, this.value) : false;\n if (result) {\n return result;\n } else {\n if (pathIsEmpty(pathToFollow)) {\n return null;\n } else {\n const front = pathGetFront(pathToFollow)!;\n const nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.findOnPath_(\n pathPopFront(pathToFollow),\n pathChild(pathSoFar, front),\n f\n );\n } else {\n return null;\n }\n }\n }\n }\n\n foreachOnPath(\n path: Path,\n f: (path: Path, value: T) => void\n ): ImmutableTree {\n return this.foreachOnPath_(path, newEmptyPath(), f);\n }\n\n private foreachOnPath_(\n pathToFollow: Path,\n currentRelativePath: Path,\n f: (path: Path, value: T) => void\n ): ImmutableTree {\n if (pathIsEmpty(pathToFollow)) {\n return this;\n } else {\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n const front = pathGetFront(pathToFollow);\n const nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.foreachOnPath_(\n pathPopFront(pathToFollow),\n pathChild(currentRelativePath, front),\n f\n );\n } else {\n return new ImmutableTree(null);\n }\n }\n }\n\n /**\n * Calls the given function for each node in the tree that has a value.\n *\n * @param f - A function to be called with the path from the root of the tree to\n * a node, and the value at that node. Called in depth-first order.\n */\n foreach(f: (path: Path, value: T) => void) {\n this.foreach_(newEmptyPath(), f);\n }\n\n private foreach_(\n currentRelativePath: Path,\n f: (path: Path, value: T) => void\n ) {\n this.children.inorderTraversal((childName, childTree) => {\n childTree.foreach_(pathChild(currentRelativePath, childName), f);\n });\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n }\n\n foreachChild(f: (name: string, value: T) => void) {\n this.children.inorderTraversal(\n (childName: string, childTree: ImmutableTree) => {\n if (childTree.value) {\n f(childName, childTree.value);\n }\n }\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { NamedNode, Node } from './snap/Node';\nimport { ImmutableTree } from './util/ImmutableTree';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathIsEmpty\n} from './util/Path';\nimport { each } from './util/util';\n\n/**\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\n * to reflect the write added.\n */\nexport class CompoundWrite {\n constructor(public writeTree_: ImmutableTree) {}\n\n static empty(): CompoundWrite {\n return new CompoundWrite(new ImmutableTree(null));\n }\n}\n\nexport function compoundWriteAddWrite(\n compoundWrite: CompoundWrite,\n path: Path,\n node: Node\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return new CompoundWrite(new ImmutableTree(node));\n } else {\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n const rootMostPath = rootmost.path;\n let value = rootmost.value;\n const relativePath = newRelativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(\n compoundWrite.writeTree_.set(rootMostPath, value)\n );\n } else {\n const subtree = new ImmutableTree(node);\n const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n}\n\nexport function compoundWriteAddWrites(\n compoundWrite: CompoundWrite,\n path: Path,\n updates: { [name: string]: Node }\n): CompoundWrite {\n let newWrite = compoundWrite;\n each(updates, (childKey: string, node: Node) => {\n newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);\n });\n return newWrite;\n}\n\n/**\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param compoundWrite - The CompoundWrite to remove.\n * @param path - The path at which a write and all deeper writes should be removed\n * @returns The new CompoundWrite with the removed path\n */\nexport function compoundWriteRemoveWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return CompoundWrite.empty();\n } else {\n const newWriteTree = compoundWrite.writeTree_.setTree(\n path,\n new ImmutableTree(null)\n );\n return new CompoundWrite(newWriteTree);\n }\n}\n\n/**\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\n * considered \"complete\".\n *\n * @param compoundWrite - The CompoundWrite to check.\n * @param path - The path to check for\n * @returns Whether there is a complete write at that path\n */\nexport function compoundWriteHasCompleteWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): boolean {\n return compoundWriteGetCompleteNode(compoundWrite, path) != null;\n}\n\n/**\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\n * writes from deeper paths, but will return child nodes from a more shallow path.\n *\n * @param compoundWrite - The CompoundWrite to get the node from.\n * @param path - The path to get a complete write\n * @returns The node if complete at that path, or null otherwise.\n */\nexport function compoundWriteGetCompleteNode(\n compoundWrite: CompoundWrite,\n path: Path\n): Node | null {\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return compoundWrite.writeTree_\n .get(rootmost.path)\n .getChild(newRelativePath(rootmost.path, path));\n } else {\n return null;\n }\n}\n\n/**\n * Returns all children that are guaranteed to be a complete overwrite.\n *\n * @param compoundWrite - The CompoundWrite to get children from.\n * @returns A list of all complete children.\n */\nexport function compoundWriteGetCompleteChildren(\n compoundWrite: CompoundWrite\n): NamedNode[] {\n const children: NamedNode[] = [];\n const node = compoundWrite.writeTree_.value;\n if (node != null) {\n // If it's a leaf node, it has no children; so nothing to do.\n if (!node.isLeafNode()) {\n (node as ChildrenNode).forEachChild(\n PRIORITY_INDEX,\n (childName, childNode) => {\n children.push(new NamedNode(childName, childNode));\n }\n );\n }\n } else {\n compoundWrite.writeTree_.children.inorderTraversal(\n (childName, childTree) => {\n if (childTree.value != null) {\n children.push(new NamedNode(childName, childTree.value));\n }\n }\n );\n }\n return children;\n}\n\nexport function compoundWriteChildCompoundWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return compoundWrite;\n } else {\n const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree(shadowingNode));\n } else {\n return new CompoundWrite(compoundWrite.writeTree_.subtree(path));\n }\n }\n}\n\n/**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @returns Whether this CompoundWrite is empty\n */\nexport function compoundWriteIsEmpty(compoundWrite: CompoundWrite): boolean {\n return compoundWrite.writeTree_.isEmpty();\n}\n\n/**\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\n * node\n * @param node - The node to apply this CompoundWrite to\n * @returns The node with all writes applied\n */\nexport function compoundWriteApply(\n compoundWrite: CompoundWrite,\n node: Node\n): Node {\n return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);\n}\n\nfunction applySubtreeWrite(\n relativePath: Path,\n writeTree: ImmutableTree,\n node: Node\n): Node {\n if (writeTree.value != null) {\n // Since there a write is always a leaf, we're done here\n return node.updateChild(relativePath, writeTree.value);\n } else {\n let priorityWrite = null;\n writeTree.children.inorderTraversal((childKey, childTree) => {\n if (childKey === '.priority') {\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\n // to apply priorities to empty nodes that are later filled\n assert(\n childTree.value !== null,\n 'Priority writes must always be leaf nodes'\n );\n priorityWrite = childTree.value;\n } else {\n node = applySubtreeWrite(\n pathChild(relativePath, childKey),\n childTree,\n node\n );\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {\n node = node.updateChild(\n pathChild(relativePath, '.priority'),\n priorityWrite\n );\n }\n return node;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError, safeGet } from '@firebase/util';\n\nimport {\n CompoundWrite,\n compoundWriteAddWrite,\n compoundWriteAddWrites,\n compoundWriteApply,\n compoundWriteChildCompoundWrite,\n compoundWriteGetCompleteChildren,\n compoundWriteGetCompleteNode,\n compoundWriteHasCompleteWrite,\n compoundWriteIsEmpty,\n compoundWriteRemoveWrite\n} from './CompoundWrite';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Index } from './snap/indexes/Index';\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { NamedNode, Node } from './snap/Node';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathContains,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from './util/Path';\nimport { each } from './util/util';\nimport { CacheNode } from './view/CacheNode';\n\n/**\n * Defines a single user-initiated write operation. May be the result of a set(), transaction(), or update() call. In\n * the case of a set() or transaction, snap will be non-null. In the case of an update(), children will be non-null.\n */\nexport interface WriteRecord {\n writeId: number;\n path: Path;\n snap?: Node | null;\n children?: { [k: string]: Node } | null;\n visible: boolean;\n}\n\n/**\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n */\nexport function writeTreeChildWrites(\n writeTree: WriteTree,\n path: Path\n): WriteTreeRef {\n return newWriteTreeRef(path, writeTree);\n}\n\n/**\n * Record a new overwrite from user code.\n *\n * @param visible - This is set to false by some transactions. It should be excluded from event caches\n */\nexport function writeTreeAddOverwrite(\n writeTree: WriteTree,\n path: Path,\n snap: Node,\n writeId: number,\n visible?: boolean\n) {\n assert(\n writeId > writeTree.lastWriteId,\n 'Stacking an older write on top of newer ones'\n );\n if (visible === undefined) {\n visible = true;\n }\n writeTree.allWrites.push({\n path,\n snap,\n writeId,\n visible\n });\n\n if (visible) {\n writeTree.visibleWrites = compoundWriteAddWrite(\n writeTree.visibleWrites,\n path,\n snap\n );\n }\n writeTree.lastWriteId = writeId;\n}\n\n/**\n * Record a new merge from user code.\n */\nexport function writeTreeAddMerge(\n writeTree: WriteTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n writeId: number\n) {\n assert(\n writeId > writeTree.lastWriteId,\n 'Stacking an older merge on top of newer ones'\n );\n writeTree.allWrites.push({\n path,\n children: changedChildren,\n writeId,\n visible: true\n });\n\n writeTree.visibleWrites = compoundWriteAddWrites(\n writeTree.visibleWrites,\n path,\n changedChildren\n );\n writeTree.lastWriteId = writeId;\n}\n\nexport function writeTreeGetWrite(\n writeTree: WriteTree,\n writeId: number\n): WriteRecord | null {\n for (let i = 0; i < writeTree.allWrites.length; i++) {\n const record = writeTree.allWrites[i];\n if (record.writeId === writeId) {\n return record;\n }\n }\n return null;\n}\n\n/**\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\n *\n * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\nexport function writeTreeRemoveWrite(\n writeTree: WriteTree,\n writeId: number\n): boolean {\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\n // out of order.\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\n\n const idx = writeTree.allWrites.findIndex(s => {\n return s.writeId === writeId;\n });\n assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n const writeToRemove = writeTree.allWrites[idx];\n writeTree.allWrites.splice(idx, 1);\n\n let removedWriteWasVisible = writeToRemove.visible;\n let removedWriteOverlapsWithOtherWrites = false;\n\n let i = writeTree.allWrites.length - 1;\n\n while (removedWriteWasVisible && i >= 0) {\n const currentWrite = writeTree.allWrites[i];\n if (currentWrite.visible) {\n if (\n i >= idx &&\n writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)\n ) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\n } else if (pathContains(writeToRemove.path, currentWrite.path)) {\n // Either we're covering some writes or they're covering part of us (depending on which came first).\n removedWriteOverlapsWithOtherWrites = true;\n }\n }\n i--;\n }\n\n if (!removedWriteWasVisible) {\n return false;\n } else if (removedWriteOverlapsWithOtherWrites) {\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\n writeTreeResetTree_(writeTree);\n return true;\n } else {\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\n if (writeToRemove.snap) {\n writeTree.visibleWrites = compoundWriteRemoveWrite(\n writeTree.visibleWrites,\n writeToRemove.path\n );\n } else {\n const children = writeToRemove.children;\n each(children, (childName: string) => {\n writeTree.visibleWrites = compoundWriteRemoveWrite(\n writeTree.visibleWrites,\n pathChild(writeToRemove.path, childName)\n );\n });\n }\n return true;\n }\n}\n\nfunction writeTreeRecordContainsPath_(\n writeRecord: WriteRecord,\n path: Path\n): boolean {\n if (writeRecord.snap) {\n return pathContains(writeRecord.path, path);\n } else {\n for (const childName in writeRecord.children) {\n if (\n writeRecord.children.hasOwnProperty(childName) &&\n pathContains(pathChild(writeRecord.path, childName), path)\n ) {\n return true;\n }\n }\n return false;\n }\n}\n\n/**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\n */\nfunction writeTreeResetTree_(writeTree: WriteTree) {\n writeTree.visibleWrites = writeTreeLayerTree_(\n writeTree.allWrites,\n writeTreeDefaultFilter_,\n newEmptyPath()\n );\n if (writeTree.allWrites.length > 0) {\n writeTree.lastWriteId =\n writeTree.allWrites[writeTree.allWrites.length - 1].writeId;\n } else {\n writeTree.lastWriteId = -1;\n }\n}\n\n/**\n * The default filter used when constructing the tree. Keep everything that's visible.\n */\nfunction writeTreeDefaultFilter_(write: WriteRecord) {\n return write.visible;\n}\n\n/**\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\n * event data at that path.\n */\nfunction writeTreeLayerTree_(\n writes: WriteRecord[],\n filter: (w: WriteRecord) => boolean,\n treeRoot: Path\n): CompoundWrite {\n let compoundWrite = CompoundWrite.empty();\n for (let i = 0; i < writes.length; ++i) {\n const write = writes[i];\n // Theory, a later set will either:\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\n if (filter(write)) {\n const writePath = write.path;\n let relativePath: Path;\n if (write.snap) {\n if (pathContains(treeRoot, writePath)) {\n relativePath = newRelativePath(treeRoot, writePath);\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n relativePath,\n write.snap\n );\n } else if (pathContains(writePath, treeRoot)) {\n relativePath = newRelativePath(writePath, treeRoot);\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n newEmptyPath(),\n write.snap.getChild(relativePath)\n );\n } else {\n // There is no overlap between root path and write path, ignore write\n }\n } else if (write.children) {\n if (pathContains(treeRoot, writePath)) {\n relativePath = newRelativePath(treeRoot, writePath);\n compoundWrite = compoundWriteAddWrites(\n compoundWrite,\n relativePath,\n write.children\n );\n } else if (pathContains(writePath, treeRoot)) {\n relativePath = newRelativePath(writePath, treeRoot);\n if (pathIsEmpty(relativePath)) {\n compoundWrite = compoundWriteAddWrites(\n compoundWrite,\n newEmptyPath(),\n write.children\n );\n } else {\n const child = safeGet(write.children, pathGetFront(relativePath));\n if (child) {\n // There exists a child in this node that matches the root path\n const deepNode = child.getChild(pathPopFront(relativePath));\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n newEmptyPath(),\n deepNode\n );\n }\n }\n } else {\n // There is no overlap between root path and write path, ignore write\n }\n } else {\n throw assertionError('WriteRecord should have .snap or .children');\n }\n }\n }\n return compoundWrite;\n}\n\n/**\n * Return a complete snapshot for the given path if there's visible write data at that path, else null.\n * No server data is considered.\n *\n */\nexport function writeTreeGetCompleteWriteData(\n writeTree: WriteTree,\n path: Path\n): Node | null {\n return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\n}\n\n/**\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\n * writes), attempt to calculate a complete snapshot for the given path\n *\n * @param writeIdsToExclude - An optional set to be excluded\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\n */\nexport function writeTreeCalcCompleteEventCache(\n writeTree: WriteTree,\n treePath: Path,\n completeServerCache: Node | null,\n writeIdsToExclude?: number[],\n includeHiddenWrites?: boolean\n): Node | null {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n const shadowingNode = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n treePath\n );\n if (shadowingNode != null) {\n return shadowingNode;\n } else {\n const subMerge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n if (compoundWriteIsEmpty(subMerge)) {\n return completeServerCache;\n } else if (\n completeServerCache == null &&\n !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())\n ) {\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n return null;\n } else {\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\n return compoundWriteApply(subMerge, layeredCache);\n }\n }\n } else {\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {\n return completeServerCache;\n } else {\n // If the server cache is null, and we don't have a complete cache, we need to return null\n if (\n !includeHiddenWrites &&\n completeServerCache == null &&\n !compoundWriteHasCompleteWrite(merge, newEmptyPath())\n ) {\n return null;\n } else {\n const filter = function (write: WriteRecord) {\n return (\n (write.visible || includeHiddenWrites) &&\n (!writeIdsToExclude ||\n !~writeIdsToExclude.indexOf(write.writeId)) &&\n (pathContains(write.path, treePath) ||\n pathContains(treePath, write.path))\n );\n };\n const mergeAtPath = writeTreeLayerTree_(\n writeTree.allWrites,\n filter,\n treePath\n );\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\n return compoundWriteApply(mergeAtPath, layeredCache);\n }\n }\n }\n}\n\n/**\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\n * Used when creating new views, to pre-fill their complete event children snapshot.\n */\nexport function writeTreeCalcCompleteEventChildren(\n writeTree: WriteTree,\n treePath: Path,\n completeServerChildren: ChildrenNode | null\n) {\n let completeChildren = ChildrenNode.EMPTY_NODE as Node;\n const topLevelSet = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n treePath\n );\n if (topLevelSet) {\n if (!topLevelSet.isLeafNode()) {\n // we're shadowing everything. Return the children.\n topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {\n completeChildren = completeChildren.updateImmediateChild(\n childName,\n childSnap\n );\n });\n }\n return completeChildren;\n } else if (completeServerChildren) {\n // Layer any children we have on top of this\n // We know we don't have a top-level set, so just enumerate existing children\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n completeServerChildren.forEachChild(\n PRIORITY_INDEX,\n (childName, childNode) => {\n const node = compoundWriteApply(\n compoundWriteChildCompoundWrite(merge, new Path(childName)),\n childNode\n );\n completeChildren = completeChildren.updateImmediateChild(\n childName,\n node\n );\n }\n );\n // Add any complete children we have from the set\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\n completeChildren = completeChildren.updateImmediateChild(\n namedNode.name,\n namedNode.node\n );\n });\n return completeChildren;\n } else {\n // We don't have anything to layer on top of. Layer on any children we have\n // Note that we can return an empty snap if we have a defined delete\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\n completeChildren = completeChildren.updateImmediateChild(\n namedNode.name,\n namedNode.node\n );\n });\n return completeChildren;\n }\n}\n\n/**\n * Given that the underlying server data has updated, determine what, if anything, needs to be\n * applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events\n *\n * Either existingEventSnap or existingServerSnap must exist\n */\nexport function writeTreeCalcEventCacheAfterServerOverwrite(\n writeTree: WriteTree,\n treePath: Path,\n childPath: Path,\n existingEventSnap: Node | null,\n existingServerSnap: Node | null\n): Node | null {\n assert(\n existingEventSnap || existingServerSnap,\n 'Either existingEventSnap or existingServerSnap must exist'\n );\n const path = pathChild(treePath, childPath);\n if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {\n // At this point we can probably guarantee that we're in case 2, meaning no events\n // May need to check visibility while doing the findRootMostValueAndPath call\n return null;\n } else {\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\n const childMerge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n path\n );\n if (compoundWriteIsEmpty(childMerge)) {\n // We're not shadowing at all. Case 1\n return existingServerSnap.getChild(childPath);\n } else {\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\n // However this is tricky to find out, since user updates don't necessary change the server\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\n // only check if the updates change the serverNode.\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\n return compoundWriteApply(\n childMerge,\n existingServerSnap.getChild(childPath)\n );\n }\n }\n}\n\n/**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n */\nexport function writeTreeCalcCompleteChild(\n writeTree: WriteTree,\n treePath: Path,\n childKey: string,\n existingServerSnap: CacheNode\n): Node | null {\n const path = pathChild(treePath, childKey);\n const shadowingNode = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n path\n );\n if (shadowingNode != null) {\n return shadowingNode;\n } else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n const childMerge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n path\n );\n return compoundWriteApply(\n childMerge,\n existingServerSnap.getNode().getImmediateChild(childKey)\n );\n } else {\n return null;\n }\n }\n}\n\n/**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n */\nexport function writeTreeShadowingWrite(\n writeTree: WriteTree,\n path: Path\n): Node | null {\n return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\n}\n\n/**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window.\n */\nexport function writeTreeCalcIndexedSlice(\n writeTree: WriteTree,\n treePath: Path,\n completeServerData: Node | null,\n startPost: NamedNode,\n count: number,\n reverse: boolean,\n index: Index\n): NamedNode[] {\n let toIterate: Node;\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n } else if (completeServerData != null) {\n toIterate = compoundWriteApply(merge, completeServerData);\n } else {\n // no children to iterate on\n return [];\n }\n toIterate = toIterate.withIndex(index);\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n const nodes = [];\n const cmp = index.getCompare();\n const iter = reverse\n ? (toIterate as ChildrenNode).getReverseIteratorFrom(startPost, index)\n : (toIterate as ChildrenNode).getIteratorFrom(startPost, index);\n let next = iter.getNext();\n while (next && nodes.length < count) {\n if (cmp(next, startPost) !== 0) {\n nodes.push(next);\n }\n next = iter.getNext();\n }\n return nodes;\n } else {\n return [];\n }\n}\n\nexport function newWriteTree(): WriteTree {\n return {\n visibleWrites: CompoundWrite.empty(),\n allWrites: [],\n lastWriteId: -1\n };\n}\n\n/**\n * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them\n * with underlying server data (to create \"event cache\" data). Pending writes are added with addOverwrite()\n * and addMerge(), and removed with removeWrite().\n */\nexport interface WriteTree {\n /**\n * A tree tracking the result of applying all visible writes. This does not include transactions with\n * applyLocally=false or writes that are completely shadowed by other writes.\n */\n visibleWrites: CompoundWrite;\n\n /**\n * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary\n * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also\n * used by transactions).\n */\n allWrites: WriteRecord[];\n\n lastWriteId: number;\n}\n\n/**\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\n * can lead to a more expensive calculation.\n *\n * @param writeIdsToExclude - Optional writes to exclude.\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\n */\nexport function writeTreeRefCalcCompleteEventCache(\n writeTreeRef: WriteTreeRef,\n completeServerCache: Node | null,\n writeIdsToExclude?: number[],\n includeHiddenWrites?: boolean\n): Node | null {\n return writeTreeCalcCompleteEventCache(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n completeServerCache,\n writeIdsToExclude,\n includeHiddenWrites\n );\n}\n\n/**\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\n * mix of the given server data and write data.\n *\n */\nexport function writeTreeRefCalcCompleteEventChildren(\n writeTreeRef: WriteTreeRef,\n completeServerChildren: ChildrenNode | null\n): ChildrenNode {\n return writeTreeCalcCompleteEventChildren(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n completeServerChildren\n ) as ChildrenNode;\n}\n\n/**\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\n * if anything, needs to be applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events should be raised\n *\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\n *\n *\n */\nexport function writeTreeRefCalcEventCacheAfterServerOverwrite(\n writeTreeRef: WriteTreeRef,\n path: Path,\n existingEventSnap: Node | null,\n existingServerSnap: Node | null\n): Node | null {\n return writeTreeCalcEventCacheAfterServerOverwrite(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n path,\n existingEventSnap,\n existingServerSnap\n );\n}\n\n/**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n */\nexport function writeTreeRefShadowingWrite(\n writeTreeRef: WriteTreeRef,\n path: Path\n): Node | null {\n return writeTreeShadowingWrite(\n writeTreeRef.writeTree,\n pathChild(writeTreeRef.treePath, path)\n );\n}\n\n/**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window\n */\nexport function writeTreeRefCalcIndexedSlice(\n writeTreeRef: WriteTreeRef,\n completeServerData: Node | null,\n startPost: NamedNode,\n count: number,\n reverse: boolean,\n index: Index\n): NamedNode[] {\n return writeTreeCalcIndexedSlice(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n completeServerData,\n startPost,\n count,\n reverse,\n index\n );\n}\n\n/**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n */\nexport function writeTreeRefCalcCompleteChild(\n writeTreeRef: WriteTreeRef,\n childKey: string,\n existingServerCache: CacheNode\n): Node | null {\n return writeTreeCalcCompleteChild(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n childKey,\n existingServerCache\n );\n}\n\n/**\n * Return a WriteTreeRef for a child.\n */\nexport function writeTreeRefChild(\n writeTreeRef: WriteTreeRef,\n childName: string\n): WriteTreeRef {\n return newWriteTreeRef(\n pathChild(writeTreeRef.treePath, childName),\n writeTreeRef.writeTree\n );\n}\n\nexport function newWriteTreeRef(\n path: Path,\n writeTree: WriteTree\n): WriteTreeRef {\n return {\n treePath: path,\n writeTree\n };\n}\n\n/**\n * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods\n * just proxy to the underlying WriteTree.\n *\n */\nexport interface WriteTreeRef {\n /**\n * The path to this particular write tree ref. Used for calling methods on writeTree_ while exposing a simpler\n * interface to callers.\n */\n readonly treePath: Path;\n\n /**\n * * A reference to the actual tree of write data. All methods are pass-through to the tree, but with the appropriate\n * path prefixed.\n *\n * This lets us make cheap references to points in the tree for sync points without having to copy and maintain all of\n * the data.\n */\n readonly writeTree: WriteTree;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport {\n Change,\n ChangeType,\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from './Change';\n\nexport class ChildChangeAccumulator {\n private readonly changeMap: Map = new Map();\n\n trackChildChange(change: Change) {\n const type = change.type;\n const childKey = change.childName!;\n assert(\n type === ChangeType.CHILD_ADDED ||\n type === ChangeType.CHILD_CHANGED ||\n type === ChangeType.CHILD_REMOVED,\n 'Only child changes supported for tracking'\n );\n assert(\n childKey !== '.priority',\n 'Only non-priority child changes can be tracked.'\n );\n const oldChange = this.changeMap.get(childKey);\n if (oldChange) {\n const oldType = oldChange.type;\n if (\n type === ChangeType.CHILD_ADDED &&\n oldType === ChangeType.CHILD_REMOVED\n ) {\n this.changeMap.set(\n childKey,\n changeChildChanged(\n childKey,\n change.snapshotNode,\n oldChange.snapshotNode\n )\n );\n } else if (\n type === ChangeType.CHILD_REMOVED &&\n oldType === ChangeType.CHILD_ADDED\n ) {\n this.changeMap.delete(childKey);\n } else if (\n type === ChangeType.CHILD_REMOVED &&\n oldType === ChangeType.CHILD_CHANGED\n ) {\n this.changeMap.set(\n childKey,\n changeChildRemoved(childKey, oldChange.oldSnap)\n );\n } else if (\n type === ChangeType.CHILD_CHANGED &&\n oldType === ChangeType.CHILD_ADDED\n ) {\n this.changeMap.set(\n childKey,\n changeChildAdded(childKey, change.snapshotNode)\n );\n } else if (\n type === ChangeType.CHILD_CHANGED &&\n oldType === ChangeType.CHILD_CHANGED\n ) {\n this.changeMap.set(\n childKey,\n changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap)\n );\n } else {\n throw assertionError(\n 'Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange\n );\n }\n } else {\n this.changeMap.set(childKey, change);\n }\n }\n\n getChanges(): Change[] {\n return Array.from(this.changeMap.values());\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Index } from '../snap/indexes/Index';\nimport { NamedNode, Node } from '../snap/Node';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteChild,\n writeTreeRefCalcIndexedSlice\n} from '../WriteTree';\n\nimport { CacheNode } from './CacheNode';\nimport { ViewCache, viewCacheGetCompleteServerSnap } from './ViewCache';\n\n/**\n * Since updates to filtered nodes might require nodes to be pulled in from \"outside\" the node, this interface\n * can help to get complete children that can be pulled in.\n * A class implementing this interface takes potentially multiple sources (e.g. user writes, server data from\n * other views etc.) to try it's best to get a complete child that might be useful in pulling into the view.\n *\n * @interface\n */\nexport interface CompleteChildSource {\n getCompleteChild(childKey: string): Node | null;\n\n getChildAfterChild(\n index: Index,\n child: NamedNode,\n reverse: boolean\n ): NamedNode | null;\n}\n\n/**\n * An implementation of CompleteChildSource that never returns any additional children\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class NoCompleteChildSource_ implements CompleteChildSource {\n getCompleteChild(childKey?: string): Node | null {\n return null;\n }\n getChildAfterChild(\n index?: Index,\n child?: NamedNode,\n reverse?: boolean\n ): NamedNode | null {\n return null;\n }\n}\n\n/**\n * Singleton instance.\n */\nexport const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n\n/**\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\n * old event caches available to calculate complete children.\n */\nexport class WriteTreeCompleteChildSource implements CompleteChildSource {\n constructor(\n private writes_: WriteTreeRef,\n private viewCache_: ViewCache,\n private optCompleteServerCache_: Node | null = null\n ) {}\n getCompleteChild(childKey: string): Node | null {\n const node = this.viewCache_.eventCache;\n if (node.isCompleteForChild(childKey)) {\n return node.getNode().getImmediateChild(childKey);\n } else {\n const serverNode =\n this.optCompleteServerCache_ != null\n ? new CacheNode(this.optCompleteServerCache_, true, false)\n : this.viewCache_.serverCache;\n return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);\n }\n }\n getChildAfterChild(\n index: Index,\n child: NamedNode,\n reverse: boolean\n ): NamedNode | null {\n const completeServerData =\n this.optCompleteServerCache_ != null\n ? this.optCompleteServerCache_\n : viewCacheGetCompleteServerSnap(this.viewCache_);\n const nodes = writeTreeRefCalcIndexedSlice(\n this.writes_,\n completeServerData,\n child,\n 1,\n reverse,\n index\n );\n if (nodes.length === 0) {\n return null;\n } else {\n return nodes[0];\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport { AckUserWrite } from '../operation/AckUserWrite';\nimport { Merge } from '../operation/Merge';\nimport { Operation, OperationType } from '../operation/Operation';\nimport { Overwrite } from '../operation/Overwrite';\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { KEY_INDEX } from '../snap/indexes/KeyIndex';\nimport { Node } from '../snap/Node';\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathChild,\n pathGetBack,\n pathGetFront,\n pathGetLength,\n pathIsEmpty,\n pathParent,\n pathPopFront\n} from '../util/Path';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteChild,\n writeTreeRefCalcCompleteEventCache,\n writeTreeRefCalcCompleteEventChildren,\n writeTreeRefCalcEventCacheAfterServerOverwrite,\n writeTreeRefShadowingWrite\n} from '../WriteTree';\n\nimport { Change, changeValue } from './Change';\nimport { ChildChangeAccumulator } from './ChildChangeAccumulator';\nimport {\n CompleteChildSource,\n NO_COMPLETE_CHILD_SOURCE,\n WriteTreeCompleteChildSource\n} from './CompleteChildSource';\nimport { NodeFilter } from './filter/NodeFilter';\nimport {\n ViewCache,\n viewCacheGetCompleteEventSnap,\n viewCacheGetCompleteServerSnap,\n viewCacheUpdateEventSnap,\n viewCacheUpdateServerSnap\n} from './ViewCache';\n\nexport interface ProcessorResult {\n readonly viewCache: ViewCache;\n readonly changes: Change[];\n}\n\nexport interface ViewProcessor {\n readonly filter: NodeFilter;\n}\n\nexport function newViewProcessor(filter: NodeFilter): ViewProcessor {\n return { filter };\n}\n\nexport function viewProcessorAssertIndexed(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache\n): void {\n assert(\n viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()),\n 'Event snap not indexed'\n );\n assert(\n viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()),\n 'Server snap not indexed'\n );\n}\n\nexport function viewProcessorApplyOperation(\n viewProcessor: ViewProcessor,\n oldViewCache: ViewCache,\n operation: Operation,\n writesCache: WriteTreeRef,\n completeCache: Node | null\n): ProcessorResult {\n const accumulator = new ChildChangeAccumulator();\n let newViewCache, filterServerNode;\n if (operation.type === OperationType.OVERWRITE) {\n const overwrite = operation as Overwrite;\n if (overwrite.source.fromUser) {\n newViewCache = viewProcessorApplyUserOverwrite(\n viewProcessor,\n oldViewCache,\n overwrite.path,\n overwrite.snap,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n assert(overwrite.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered and the\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\n // again\n filterServerNode =\n overwrite.source.tagged ||\n (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));\n newViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\n oldViewCache,\n overwrite.path,\n overwrite.snap,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n } else if (operation.type === OperationType.MERGE) {\n const merge = operation as Merge;\n if (merge.source.fromUser) {\n newViewCache = viewProcessorApplyUserMerge(\n viewProcessor,\n oldViewCache,\n merge.path,\n merge.children,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n assert(merge.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered\n filterServerNode =\n merge.source.tagged || oldViewCache.serverCache.isFiltered();\n newViewCache = viewProcessorApplyServerMerge(\n viewProcessor,\n oldViewCache,\n merge.path,\n merge.children,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n } else if (operation.type === OperationType.ACK_USER_WRITE) {\n const ackUserWrite = operation as AckUserWrite;\n if (!ackUserWrite.revert) {\n newViewCache = viewProcessorAckUserWrite(\n viewProcessor,\n oldViewCache,\n ackUserWrite.path,\n ackUserWrite.affectedTree,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n newViewCache = viewProcessorRevertUserWrite(\n viewProcessor,\n oldViewCache,\n ackUserWrite.path,\n writesCache,\n completeCache,\n accumulator\n );\n }\n } else if (operation.type === OperationType.LISTEN_COMPLETE) {\n newViewCache = viewProcessorListenComplete(\n viewProcessor,\n oldViewCache,\n operation.path,\n writesCache,\n accumulator\n );\n } else {\n throw assertionError('Unknown operation type: ' + operation.type);\n }\n const changes = accumulator.getChanges();\n viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);\n return { viewCache: newViewCache, changes };\n}\n\nfunction viewProcessorMaybeAddValueEvent(\n oldViewCache: ViewCache,\n newViewCache: ViewCache,\n accumulator: Change[]\n): void {\n const eventSnap = newViewCache.eventCache;\n if (eventSnap.isFullyInitialized()) {\n const isLeafOrEmpty =\n eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);\n if (\n accumulator.length > 0 ||\n !oldViewCache.eventCache.isFullyInitialized() ||\n (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||\n !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())\n ) {\n accumulator.push(\n changeValue(viewCacheGetCompleteEventSnap(newViewCache))\n );\n }\n }\n}\n\nfunction viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n changePath: Path,\n writesCache: WriteTreeRef,\n source: CompleteChildSource,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldEventSnap = viewCache.eventCache;\n if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n } else {\n let newEventCache, serverNode;\n if (pathIsEmpty(changePath)) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n assert(\n viewCache.serverCache.isFullyInitialized(),\n 'If change path is empty, we must have complete server data'\n );\n if (viewCache.serverCache.isFiltered()) {\n // We need to special case this, because we need to only apply writes to complete children, or\n // we might end up raising events for incomplete children. If the server data is filtered deep\n // writes cannot be guaranteed to be complete\n const serverCache = viewCacheGetCompleteServerSnap(viewCache);\n const completeChildren =\n serverCache instanceof ChildrenNode\n ? serverCache\n : ChildrenNode.EMPTY_NODE;\n const completeEventChildren = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n completeChildren\n );\n newEventCache = viewProcessor.filter.updateFullNode(\n viewCache.eventCache.getNode(),\n completeEventChildren,\n accumulator\n );\n } else {\n const completeNode = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n newEventCache = viewProcessor.filter.updateFullNode(\n viewCache.eventCache.getNode(),\n completeNode,\n accumulator\n );\n }\n } else {\n const childKey = pathGetFront(changePath);\n if (childKey === '.priority') {\n assert(\n pathGetLength(changePath) === 1,\n \"Can't have a priority with additional path components\"\n );\n const oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.serverCache.getNode();\n // we might have overwrites for this priority\n const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(\n writesCache,\n changePath,\n oldEventNode,\n serverNode\n );\n if (updatedPriority != null) {\n newEventCache = viewProcessor.filter.updatePriority(\n oldEventNode,\n updatedPriority\n );\n } else {\n // priority didn't change, keep old node\n newEventCache = oldEventSnap.getNode();\n }\n } else {\n const childChangePath = pathPopFront(changePath);\n // update child\n let newEventChild;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.serverCache.getNode();\n const eventChildUpdate =\n writeTreeRefCalcEventCacheAfterServerOverwrite(\n writesCache,\n changePath,\n oldEventSnap.getNode(),\n serverNode\n );\n if (eventChildUpdate != null) {\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey)\n .updateChild(childChangePath, eventChildUpdate);\n } else {\n // Nothing changed, just keep the old child\n newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);\n }\n } else {\n newEventChild = writeTreeRefCalcCompleteChild(\n writesCache,\n childKey,\n viewCache.serverCache\n );\n }\n if (newEventChild != null) {\n newEventCache = viewProcessor.filter.updateChild(\n oldEventSnap.getNode(),\n childKey,\n newEventChild,\n childChangePath,\n source,\n accumulator\n );\n } else {\n // no complete child available or no change\n newEventCache = oldEventSnap.getNode();\n }\n }\n }\n return viewCacheUpdateEventSnap(\n viewCache,\n newEventCache,\n oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath),\n viewProcessor.filter.filtersNodes()\n );\n }\n}\n\nfunction viewProcessorApplyServerOverwrite(\n viewProcessor: ViewProcessor,\n oldViewCache: ViewCache,\n changePath: Path,\n changedSnap: Node,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n filterServerNode: boolean,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldServerSnap = oldViewCache.serverCache;\n let newServerCache;\n const serverFilter = filterServerNode\n ? viewProcessor.filter\n : viewProcessor.filter.getIndexedFilter();\n if (pathIsEmpty(changePath)) {\n newServerCache = serverFilter.updateFullNode(\n oldServerSnap.getNode(),\n changedSnap,\n null\n );\n } else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\n const newServerNode = oldServerSnap\n .getNode()\n .updateChild(changePath, changedSnap);\n newServerCache = serverFilter.updateFullNode(\n oldServerSnap.getNode(),\n newServerNode,\n null\n );\n } else {\n const childKey = pathGetFront(changePath);\n if (\n !oldServerSnap.isCompleteForPath(changePath) &&\n pathGetLength(changePath) > 1\n ) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n const childChangePath = pathPopFront(changePath);\n const childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n const newChildNode = childNode.updateChild(childChangePath, changedSnap);\n if (childKey === '.priority') {\n newServerCache = serverFilter.updatePriority(\n oldServerSnap.getNode(),\n newChildNode\n );\n } else {\n newServerCache = serverFilter.updateChild(\n oldServerSnap.getNode(),\n childKey,\n newChildNode,\n childChangePath,\n NO_COMPLETE_CHILD_SOURCE,\n null\n );\n }\n }\n const newViewCache = viewCacheUpdateServerSnap(\n oldViewCache,\n newServerCache,\n oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath),\n serverFilter.filtersNodes()\n );\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n newViewCache,\n completeCache\n );\n return viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor,\n newViewCache,\n changePath,\n writesCache,\n source,\n accumulator\n );\n}\n\nfunction viewProcessorApplyUserOverwrite(\n viewProcessor: ViewProcessor,\n oldViewCache: ViewCache,\n changePath: Path,\n changedSnap: Node,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldEventSnap = oldViewCache.eventCache;\n let newViewCache, newEventCache;\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n oldViewCache,\n completeCache\n );\n if (pathIsEmpty(changePath)) {\n newEventCache = viewProcessor.filter.updateFullNode(\n oldViewCache.eventCache.getNode(),\n changedSnap,\n accumulator\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventCache,\n true,\n viewProcessor.filter.filtersNodes()\n );\n } else {\n const childKey = pathGetFront(changePath);\n if (childKey === '.priority') {\n newEventCache = viewProcessor.filter.updatePriority(\n oldViewCache.eventCache.getNode(),\n changedSnap\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventCache,\n oldEventSnap.isFullyInitialized(),\n oldEventSnap.isFiltered()\n );\n } else {\n const childChangePath = pathPopFront(changePath);\n const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n let newChild;\n if (pathIsEmpty(childChangePath)) {\n // Child overwrite, we can replace the child\n newChild = changedSnap;\n } else {\n const childNode = source.getCompleteChild(childKey);\n if (childNode != null) {\n if (\n pathGetBack(childChangePath) === '.priority' &&\n childNode.getChild(pathParent(childChangePath)).isEmpty()\n ) {\n // This is a priority update on an empty node. If this node exists on the server, the\n // server will send down the priority in the update, so ignore for now\n newChild = childNode;\n } else {\n newChild = childNode.updateChild(childChangePath, changedSnap);\n }\n } else {\n // There is no complete child node available\n newChild = ChildrenNode.EMPTY_NODE;\n }\n }\n if (!oldChild.equals(newChild)) {\n const newEventSnap = viewProcessor.filter.updateChild(\n oldEventSnap.getNode(),\n childKey,\n newChild,\n childChangePath,\n source,\n accumulator\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventSnap,\n oldEventSnap.isFullyInitialized(),\n viewProcessor.filter.filtersNodes()\n );\n } else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n}\n\nfunction viewProcessorCacheHasChild(\n viewCache: ViewCache,\n childKey: string\n): boolean {\n return viewCache.eventCache.isCompleteForChild(childKey);\n}\n\nfunction viewProcessorApplyUserMerge(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n changedChildren: ImmutableTree,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n let curViewCache = viewCache;\n changedChildren.foreach((relativePath, childNode) => {\n const writePath = pathChild(path, relativePath);\n if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\n curViewCache = viewProcessorApplyUserOverwrite(\n viewProcessor,\n curViewCache,\n writePath,\n childNode,\n writesCache,\n serverCache,\n accumulator\n );\n }\n });\n\n changedChildren.foreach((relativePath, childNode) => {\n const writePath = pathChild(path, relativePath);\n if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\n curViewCache = viewProcessorApplyUserOverwrite(\n viewProcessor,\n curViewCache,\n writePath,\n childNode,\n writesCache,\n serverCache,\n accumulator\n );\n }\n });\n\n return curViewCache;\n}\n\nfunction viewProcessorApplyMerge(\n viewProcessor: ViewProcessor,\n node: Node,\n merge: ImmutableTree\n): Node {\n merge.foreach((relativePath, childNode) => {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n}\n\nfunction viewProcessorApplyServerMerge(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n changedChildren: ImmutableTree,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n filterServerNode: boolean,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\n // wait for the complete data update coming soon.\n if (\n viewCache.serverCache.getNode().isEmpty() &&\n !viewCache.serverCache.isFullyInitialized()\n ) {\n return viewCache;\n }\n\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n let curViewCache = viewCache;\n let viewMergeTree: ImmutableTree;\n if (pathIsEmpty(path)) {\n viewMergeTree = changedChildren;\n } else {\n viewMergeTree = new ImmutableTree(null).setTree(\n path,\n changedChildren\n );\n }\n const serverNode = viewCache.serverCache.getNode();\n viewMergeTree.children.inorderTraversal((childKey, childTree) => {\n if (serverNode.hasChild(childKey)) {\n const serverChild = viewCache.serverCache\n .getNode()\n .getImmediateChild(childKey);\n const newChild = viewProcessorApplyMerge(\n viewProcessor,\n serverChild,\n childTree\n );\n curViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\n curViewCache,\n new Path(childKey),\n newChild,\n writesCache,\n serverCache,\n filterServerNode,\n accumulator\n );\n }\n });\n viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {\n const isUnknownDeepMerge =\n !viewCache.serverCache.isCompleteForChild(childKey) &&\n childMergeTree.value === null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n const serverChild = viewCache.serverCache\n .getNode()\n .getImmediateChild(childKey);\n const newChild = viewProcessorApplyMerge(\n viewProcessor,\n serverChild,\n childMergeTree\n );\n curViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\n curViewCache,\n new Path(childKey),\n newChild,\n writesCache,\n serverCache,\n filterServerNode,\n accumulator\n );\n }\n });\n\n return curViewCache;\n}\n\nfunction viewProcessorAckUserWrite(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n ackPath: Path,\n affectedTree: ImmutableTree,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {\n return viewCache;\n }\n\n // Only filter server node if it is currently filtered\n const filterServerNode = viewCache.serverCache.isFiltered();\n\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\n // now that it won't be shadowed.\n const serverCache = viewCache.serverCache;\n if (affectedTree.value != null) {\n // This is an overwrite.\n if (\n (pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)\n ) {\n return viewProcessorApplyServerOverwrite(\n viewProcessor,\n viewCache,\n ackPath,\n serverCache.getNode().getChild(ackPath),\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n } else if (pathIsEmpty(ackPath)) {\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\n // should just re-apply whatever we have in our cache as a merge.\n let changedChildren = new ImmutableTree(null);\n serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {\n changedChildren = changedChildren.set(new Path(name), node);\n });\n return viewProcessorApplyServerMerge(\n viewProcessor,\n viewCache,\n ackPath,\n changedChildren,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n } else {\n return viewCache;\n }\n } else {\n // This is a merge.\n let changedChildren = new ImmutableTree(null);\n affectedTree.foreach((mergePath, value) => {\n const serverCachePath = pathChild(ackPath, mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren = changedChildren.set(\n mergePath,\n serverCache.getNode().getChild(serverCachePath)\n );\n }\n });\n return viewProcessorApplyServerMerge(\n viewProcessor,\n viewCache,\n ackPath,\n changedChildren,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n}\n\nfunction viewProcessorListenComplete(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n writesCache: WriteTreeRef,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldServerNode = viewCache.serverCache;\n const newViewCache = viewCacheUpdateServerSnap(\n viewCache,\n oldServerNode.getNode(),\n oldServerNode.isFullyInitialized() || pathIsEmpty(path),\n oldServerNode.isFiltered()\n );\n return viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor,\n newViewCache,\n path,\n writesCache,\n NO_COMPLETE_CHILD_SOURCE,\n accumulator\n );\n}\n\nfunction viewProcessorRevertUserWrite(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n writesCache: WriteTreeRef,\n completeServerCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n let complete;\n if (writeTreeRefShadowingWrite(writesCache, path) != null) {\n return viewCache;\n } else {\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n viewCache,\n completeServerCache\n );\n const oldEventCache = viewCache.eventCache.getNode();\n let newEventCache;\n if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {\n let newNode;\n if (viewCache.serverCache.isFullyInitialized()) {\n newNode = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n } else {\n const serverChildren = viewCache.serverCache.getNode();\n assert(\n serverChildren instanceof ChildrenNode,\n 'serverChildren would be complete if leaf node'\n );\n newNode = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n serverChildren as ChildrenNode\n );\n }\n newNode = newNode as Node;\n newEventCache = viewProcessor.filter.updateFullNode(\n oldEventCache,\n newNode,\n accumulator\n );\n } else {\n const childKey = pathGetFront(path);\n let newChild = writeTreeRefCalcCompleteChild(\n writesCache,\n childKey,\n viewCache.serverCache\n );\n if (\n newChild == null &&\n viewCache.serverCache.isCompleteForChild(childKey)\n ) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = viewProcessor.filter.updateChild(\n oldEventCache,\n childKey,\n newChild,\n pathPopFront(path),\n source,\n accumulator\n );\n } else if (viewCache.eventCache.getNode().hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = viewProcessor.filter.updateChild(\n oldEventCache,\n childKey,\n ChildrenNode.EMPTY_NODE,\n pathPopFront(path),\n source,\n accumulator\n );\n } else {\n newEventCache = oldEventCache;\n }\n if (\n newEventCache.isEmpty() &&\n viewCache.serverCache.isFullyInitialized()\n ) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n if (complete.isLeafNode()) {\n newEventCache = viewProcessor.filter.updateFullNode(\n newEventCache,\n complete,\n accumulator\n );\n }\n }\n }\n complete =\n viewCache.serverCache.isFullyInitialized() ||\n writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;\n return viewCacheUpdateEventSnap(\n viewCache,\n newEventCache,\n complete,\n viewProcessor.filter.filtersNodes()\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Operation, OperationType } from '../operation/Operation';\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { PRIORITY_INDEX } from '../snap/indexes/PriorityIndex';\nimport { Node } from '../snap/Node';\nimport { Path, pathGetFront, pathIsEmpty } from '../util/Path';\nimport { WriteTreeRef } from '../WriteTree';\n\nimport { CacheNode } from './CacheNode';\nimport { Change, changeChildAdded, changeValue } from './Change';\nimport { CancelEvent, Event } from './Event';\nimport {\n EventGenerator,\n eventGeneratorGenerateEventsForChanges\n} from './EventGenerator';\nimport { EventRegistration, QueryContext } from './EventRegistration';\nimport { IndexedFilter } from './filter/IndexedFilter';\nimport { queryParamsGetNodeFilter } from './QueryParams';\nimport {\n newViewCache,\n ViewCache,\n viewCacheGetCompleteEventSnap,\n viewCacheGetCompleteServerSnap\n} from './ViewCache';\nimport {\n newViewProcessor,\n ViewProcessor,\n viewProcessorApplyOperation,\n viewProcessorAssertIndexed\n} from './ViewProcessor';\n\n/**\n * A view represents a specific location and query that has 1 or more event registrations.\n *\n * It does several things:\n * - Maintains the list of event registrations for this location/query.\n * - Maintains a cache of the data visible for this location/query.\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\n * registrations returns the set of events to be raised.\n */\nexport class View {\n processor_: ViewProcessor;\n viewCache_: ViewCache;\n eventRegistrations_: EventRegistration[] = [];\n eventGenerator_: EventGenerator;\n\n constructor(private query_: QueryContext, initialViewCache: ViewCache) {\n const params = this.query_._queryParams;\n\n const indexFilter = new IndexedFilter(params.getIndex());\n const filter = queryParamsGetNodeFilter(params);\n\n this.processor_ = newViewProcessor(filter);\n\n const initialServerCache = initialViewCache.serverCache;\n const initialEventCache = initialViewCache.eventCache;\n\n // Don't filter server node with other filter than index, wait for tagged listen\n const serverSnap = indexFilter.updateFullNode(\n ChildrenNode.EMPTY_NODE,\n initialServerCache.getNode(),\n null\n );\n const eventSnap = filter.updateFullNode(\n ChildrenNode.EMPTY_NODE,\n initialEventCache.getNode(),\n null\n );\n const newServerCache = new CacheNode(\n serverSnap,\n initialServerCache.isFullyInitialized(),\n indexFilter.filtersNodes()\n );\n const newEventCache = new CacheNode(\n eventSnap,\n initialEventCache.isFullyInitialized(),\n filter.filtersNodes()\n );\n\n this.viewCache_ = newViewCache(newEventCache, newServerCache);\n this.eventGenerator_ = new EventGenerator(this.query_);\n }\n\n get query(): QueryContext {\n return this.query_;\n }\n}\n\nexport function viewGetServerCache(view: View): Node | null {\n return view.viewCache_.serverCache.getNode();\n}\n\nexport function viewGetCompleteNode(view: View): Node | null {\n return viewCacheGetCompleteEventSnap(view.viewCache_);\n}\n\nexport function viewGetCompleteServerCache(\n view: View,\n path: Path\n): Node | null {\n const cache = viewCacheGetCompleteServerSnap(view.viewCache_);\n if (cache) {\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\n // we need to see if it contains the child we're interested in.\n if (\n view.query._queryParams.loadsAllData() ||\n (!pathIsEmpty(path) &&\n !cache.getImmediateChild(pathGetFront(path)).isEmpty())\n ) {\n return cache.getChild(path);\n }\n }\n return null;\n}\n\nexport function viewIsEmpty(view: View): boolean {\n return view.eventRegistrations_.length === 0;\n}\n\nexport function viewAddEventRegistration(\n view: View,\n eventRegistration: EventRegistration\n) {\n view.eventRegistrations_.push(eventRegistration);\n}\n\n/**\n * @param eventRegistration - If null, remove all callbacks.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @returns Cancel events, if cancelError was provided.\n */\nexport function viewRemoveEventRegistration(\n view: View,\n eventRegistration: EventRegistration | null,\n cancelError?: Error\n): Event[] {\n const cancelEvents: CancelEvent[] = [];\n if (cancelError) {\n assert(\n eventRegistration == null,\n 'A cancel should cancel all event registrations.'\n );\n const path = view.query._path;\n view.eventRegistrations_.forEach(registration => {\n const maybeEvent = registration.createCancelEvent(cancelError, path);\n if (maybeEvent) {\n cancelEvents.push(maybeEvent);\n }\n });\n }\n\n if (eventRegistration) {\n let remaining = [];\n for (let i = 0; i < view.eventRegistrations_.length; ++i) {\n const existing = view.eventRegistrations_[i];\n if (!existing.matches(eventRegistration)) {\n remaining.push(existing);\n } else if (eventRegistration.hasAnyCallback()) {\n // We're removing just this one\n remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));\n break;\n }\n }\n view.eventRegistrations_ = remaining;\n } else {\n view.eventRegistrations_ = [];\n }\n return cancelEvents;\n}\n\n/**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n */\nexport function viewApplyOperation(\n view: View,\n operation: Operation,\n writesCache: WriteTreeRef,\n completeServerCache: Node | null\n): Event[] {\n if (\n operation.type === OperationType.MERGE &&\n operation.source.queryId !== null\n ) {\n assert(\n viewCacheGetCompleteServerSnap(view.viewCache_),\n 'We should always have a full cache before handling merges'\n );\n assert(\n viewCacheGetCompleteEventSnap(view.viewCache_),\n 'Missing event cache, even though we have a server cache'\n );\n }\n\n const oldViewCache = view.viewCache_;\n const result = viewProcessorApplyOperation(\n view.processor_,\n oldViewCache,\n operation,\n writesCache,\n completeServerCache\n );\n viewProcessorAssertIndexed(view.processor_, result.viewCache);\n\n assert(\n result.viewCache.serverCache.isFullyInitialized() ||\n !oldViewCache.serverCache.isFullyInitialized(),\n 'Once a server snap is complete, it should never go back'\n );\n\n view.viewCache_ = result.viewCache;\n\n return viewGenerateEventsForChanges_(\n view,\n result.changes,\n result.viewCache.eventCache.getNode(),\n null\n );\n}\n\nexport function viewGetInitialEvents(\n view: View,\n registration: EventRegistration\n): Event[] {\n const eventSnap = view.viewCache_.eventCache;\n const initialChanges: Change[] = [];\n if (!eventSnap.getNode().isLeafNode()) {\n const eventNode = eventSnap.getNode() as ChildrenNode;\n eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n initialChanges.push(changeChildAdded(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(changeValue(eventSnap.getNode()));\n }\n return viewGenerateEventsForChanges_(\n view,\n initialChanges,\n eventSnap.getNode(),\n registration\n );\n}\n\nfunction viewGenerateEventsForChanges_(\n view: View,\n changes: Change[],\n eventCache: Node,\n eventRegistration?: EventRegistration\n): Event[] {\n const registrations = eventRegistration\n ? [eventRegistration]\n : view.eventRegistrations_;\n return eventGeneratorGenerateEventsForChanges(\n view.eventGenerator_,\n changes,\n eventCache,\n registrations\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ReferenceConstructor } from '../api/Reference';\n\nimport { Operation } from './operation/Operation';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { Path } from './util/Path';\nimport { CacheNode } from './view/CacheNode';\nimport { Event } from './view/Event';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\nimport {\n View,\n viewAddEventRegistration,\n viewApplyOperation,\n viewGetCompleteServerCache,\n viewGetInitialEvents,\n viewIsEmpty,\n viewRemoveEventRegistration\n} from './view/View';\nimport { newViewCache } from './view/ViewCache';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteEventCache,\n writeTreeRefCalcCompleteEventChildren\n} from './WriteTree';\n\nlet referenceConstructor: ReferenceConstructor;\n\n/**\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\n * and user writes (set, transaction, update).\n *\n * It's responsible for:\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\n * applyUserOverwrite, etc.)\n */\nexport class SyncPoint {\n /**\n * The Views being tracked at this location in the tree, stored as a map where the key is a\n * queryId and the value is the View for that query.\n *\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\n */\n readonly views: Map = new Map();\n}\n\nexport function syncPointSetReferenceConstructor(\n val: ReferenceConstructor\n): void {\n assert(\n !referenceConstructor,\n '__referenceConstructor has already been defined'\n );\n referenceConstructor = val;\n}\n\nfunction syncPointGetReferenceConstructor(): ReferenceConstructor {\n assert(referenceConstructor, 'Reference.ts has not been loaded');\n return referenceConstructor;\n}\n\nexport function syncPointIsEmpty(syncPoint: SyncPoint): boolean {\n return syncPoint.views.size === 0;\n}\n\nexport function syncPointApplyOperation(\n syncPoint: SyncPoint,\n operation: Operation,\n writesCache: WriteTreeRef,\n optCompleteServerCache: Node | null\n): Event[] {\n const queryId = operation.source.queryId;\n if (queryId !== null) {\n const view = syncPoint.views.get(queryId);\n assert(view != null, 'SyncTree gave us an op for an invalid query.');\n return viewApplyOperation(\n view,\n operation,\n writesCache,\n optCompleteServerCache\n );\n } else {\n let events: Event[] = [];\n\n for (const view of syncPoint.views.values()) {\n events = events.concat(\n viewApplyOperation(view, operation, writesCache, optCompleteServerCache)\n );\n }\n\n return events;\n }\n}\n\n/**\n * Get a view for the specified query.\n *\n * @param query - The query to return a view for\n * @param writesCache\n * @param serverCache\n * @param serverCacheComplete\n * @returns Events to raise.\n */\nexport function syncPointGetView(\n syncPoint: SyncPoint,\n query: QueryContext,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n serverCacheComplete: boolean\n): View {\n const queryId = query._queryIdentifier;\n const view = syncPoint.views.get(queryId);\n if (!view) {\n // TODO: make writesCache take flag for complete server node\n let eventCache = writeTreeRefCalcCompleteEventCache(\n writesCache,\n serverCacheComplete ? serverCache : null\n );\n let eventCacheComplete = false;\n if (eventCache) {\n eventCacheComplete = true;\n } else if (serverCache instanceof ChildrenNode) {\n eventCache = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n serverCache\n );\n eventCacheComplete = false;\n } else {\n eventCache = ChildrenNode.EMPTY_NODE;\n eventCacheComplete = false;\n }\n const viewCache = newViewCache(\n new CacheNode(eventCache, eventCacheComplete, false),\n new CacheNode(serverCache, serverCacheComplete, false)\n );\n return new View(query, viewCache);\n }\n return view;\n}\n\n/**\n * Add an event callback for the specified query.\n *\n * @param query\n * @param eventRegistration\n * @param writesCache\n * @param serverCache - Complete server cache, if we have it.\n * @param serverCacheComplete\n * @returns Events to raise.\n */\nexport function syncPointAddEventRegistration(\n syncPoint: SyncPoint,\n query: QueryContext,\n eventRegistration: EventRegistration,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n serverCacheComplete: boolean\n): Event[] {\n const view = syncPointGetView(\n syncPoint,\n query,\n writesCache,\n serverCache,\n serverCacheComplete\n );\n if (!syncPoint.views.has(query._queryIdentifier)) {\n syncPoint.views.set(query._queryIdentifier, view);\n }\n // This is guaranteed to exist now, we just created anything that was missing\n viewAddEventRegistration(view, eventRegistration);\n return viewGetInitialEvents(view, eventRegistration);\n}\n\n/**\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\n *\n * If query is the default query, we'll check all views for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\n *\n * @param eventRegistration - If null, remove all callbacks.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @returns removed queries and any cancel events\n */\nexport function syncPointRemoveEventRegistration(\n syncPoint: SyncPoint,\n query: QueryContext,\n eventRegistration: EventRegistration | null,\n cancelError?: Error\n): { removed: QueryContext[]; events: Event[] } {\n const queryId = query._queryIdentifier;\n const removed: QueryContext[] = [];\n let cancelEvents: Event[] = [];\n const hadCompleteView = syncPointHasCompleteView(syncPoint);\n if (queryId === 'default') {\n // When you do ref.off(...), we search all views for the registration to remove.\n for (const [viewQueryId, view] of syncPoint.views.entries()) {\n cancelEvents = cancelEvents.concat(\n viewRemoveEventRegistration(view, eventRegistration, cancelError)\n );\n if (viewIsEmpty(view)) {\n syncPoint.views.delete(viewQueryId);\n\n // We'll deal with complete views later.\n if (!view.query._queryParams.loadsAllData()) {\n removed.push(view.query);\n }\n }\n }\n } else {\n // remove the callback from the specific view.\n const view = syncPoint.views.get(queryId);\n if (view) {\n cancelEvents = cancelEvents.concat(\n viewRemoveEventRegistration(view, eventRegistration, cancelError)\n );\n if (viewIsEmpty(view)) {\n syncPoint.views.delete(queryId);\n\n // We'll deal with complete views later.\n if (!view.query._queryParams.loadsAllData()) {\n removed.push(view.query);\n }\n }\n }\n }\n\n if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {\n // We removed our last complete view.\n removed.push(\n new (syncPointGetReferenceConstructor())(query._repo, query._path)\n );\n }\n\n return { removed, events: cancelEvents };\n}\n\nexport function syncPointGetQueryViews(syncPoint: SyncPoint): View[] {\n const result = [];\n for (const view of syncPoint.views.values()) {\n if (!view.query._queryParams.loadsAllData()) {\n result.push(view);\n }\n }\n return result;\n}\n\n/**\n * @param path - The path to the desired complete snapshot\n * @returns A complete cache, if it exists\n */\nexport function syncPointGetCompleteServerCache(\n syncPoint: SyncPoint,\n path: Path\n): Node | null {\n let serverCache: Node | null = null;\n for (const view of syncPoint.views.values()) {\n serverCache = serverCache || viewGetCompleteServerCache(view, path);\n }\n return serverCache;\n}\n\nexport function syncPointViewForQuery(\n syncPoint: SyncPoint,\n query: QueryContext\n): View | null {\n const params = query._queryParams;\n if (params.loadsAllData()) {\n return syncPointGetCompleteView(syncPoint);\n } else {\n const queryId = query._queryIdentifier;\n return syncPoint.views.get(queryId);\n }\n}\n\nexport function syncPointViewExistsForQuery(\n syncPoint: SyncPoint,\n query: QueryContext\n): boolean {\n return syncPointViewForQuery(syncPoint, query) != null;\n}\n\nexport function syncPointHasCompleteView(syncPoint: SyncPoint): boolean {\n return syncPointGetCompleteView(syncPoint) != null;\n}\n\nexport function syncPointGetCompleteView(syncPoint: SyncPoint): View | null {\n for (const view of syncPoint.views.values()) {\n if (view.query._queryParams.loadsAllData()) {\n return view;\n }\n }\n return null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ReferenceConstructor } from '../api/Reference';\n\nimport { AckUserWrite } from './operation/AckUserWrite';\nimport { ListenComplete } from './operation/ListenComplete';\nimport { Merge } from './operation/Merge';\nimport {\n newOperationSourceServer,\n newOperationSourceServerTaggedQuery,\n newOperationSourceUser,\n Operation\n} from './operation/Operation';\nimport { Overwrite } from './operation/Overwrite';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport {\n SyncPoint,\n syncPointAddEventRegistration,\n syncPointApplyOperation,\n syncPointGetCompleteServerCache,\n syncPointGetCompleteView,\n syncPointGetQueryViews,\n syncPointGetView,\n syncPointHasCompleteView,\n syncPointIsEmpty,\n syncPointRemoveEventRegistration,\n syncPointViewExistsForQuery,\n syncPointViewForQuery\n} from './SyncPoint';\nimport { ImmutableTree } from './util/ImmutableTree';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathGetFront,\n pathIsEmpty\n} from './util/Path';\nimport { each, errorForServerCode } from './util/util';\nimport { CacheNode } from './view/CacheNode';\nimport { Event } from './view/Event';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\nimport { View, viewGetCompleteNode, viewGetServerCache } from './view/View';\nimport {\n newWriteTree,\n WriteTree,\n writeTreeAddMerge,\n writeTreeAddOverwrite,\n writeTreeCalcCompleteEventCache,\n writeTreeChildWrites,\n writeTreeGetWrite,\n WriteTreeRef,\n writeTreeRefChild,\n writeTreeRemoveWrite\n} from './WriteTree';\n\nlet referenceConstructor: ReferenceConstructor;\n\nexport function syncTreeSetReferenceConstructor(\n val: ReferenceConstructor\n): void {\n assert(\n !referenceConstructor,\n '__referenceConstructor has already been defined'\n );\n referenceConstructor = val;\n}\n\nfunction syncTreeGetReferenceConstructor(): ReferenceConstructor {\n assert(referenceConstructor, 'Reference.ts has not been loaded');\n return referenceConstructor;\n}\n\nexport interface ListenProvider {\n startListening(\n query: QueryContext,\n tag: number | null,\n hashFn: () => string,\n onComplete: (a: string, b?: unknown) => Event[]\n ): Event[];\n\n stopListening(a: QueryContext, b: number | null): void;\n}\n\n/**\n * Static tracker for next query tag.\n */\nlet syncTreeNextQueryTag_ = 1;\n\nexport function resetSyncTreeTag() {\n syncTreeNextQueryTag_ = 1;\n}\n\n/**\n * SyncTree is the central class for managing event callback registration, data caching, views\n * (query processing), and event generation. There are typically two SyncTree instances for\n * each Repo, one for the normal Firebase data, and one for the .info data.\n *\n * It has a number of responsibilities, including:\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\n * - Applying and caching data changes for user set(), transaction(), and update() calls\n * (applyUserOverwrite(), applyUserMerge()).\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\n * applyServerMerge()).\n * - Generating user-facing events for server and user changes (all of the apply* methods\n * return the set of events that need to be raised as a result).\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\n * to the correct set of paths and queries to satisfy the current set of user event\n * callbacks (listens are started/stopped using the provided listenProvider).\n *\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\n * events are returned to the caller rather than raised synchronously.\n *\n */\nexport class SyncTree {\n /**\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\n */\n syncPointTree_: ImmutableTree = new ImmutableTree(null);\n\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n */\n pendingWriteTree_: WriteTree = newWriteTree();\n\n readonly tagToQueryMap: Map = new Map();\n readonly queryToTagMap: Map = new Map();\n\n /**\n * @param listenProvider_ - Used by SyncTree to start / stop listening\n * to server data.\n */\n constructor(public listenProvider_: ListenProvider) {}\n}\n\n/**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyUserOverwrite(\n syncTree: SyncTree,\n path: Path,\n newData: Node,\n writeId: number,\n visible?: boolean\n): Event[] {\n // Record pending write.\n writeTreeAddOverwrite(\n syncTree.pendingWriteTree_,\n path,\n newData,\n writeId,\n visible\n );\n\n if (!visible) {\n return [];\n } else {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Overwrite(newOperationSourceUser(), path, newData)\n );\n }\n}\n\n/**\n * Apply the data from a user-generated update() call\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyUserMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n writeId: number\n): Event[] {\n // Record pending merge.\n writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);\n\n const changeTree = ImmutableTree.fromObject(changedChildren);\n\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Merge(newOperationSourceUser(), path, changeTree)\n );\n}\n\n/**\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\n *\n * @param revert - True if the given write failed and needs to be reverted\n * @returns Events to raise.\n */\nexport function syncTreeAckUserWrite(\n syncTree: SyncTree,\n writeId: number,\n revert: boolean = false\n) {\n const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);\n const needToReevaluate = writeTreeRemoveWrite(\n syncTree.pendingWriteTree_,\n writeId\n );\n if (!needToReevaluate) {\n return [];\n } else {\n let affectedTree = new ImmutableTree(null);\n if (write.snap != null) {\n // overwrite\n affectedTree = affectedTree.set(newEmptyPath(), true);\n } else {\n each(write.children, (pathString: string) => {\n affectedTree = affectedTree.set(new Path(pathString), true);\n });\n }\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new AckUserWrite(write.path, affectedTree, revert)\n );\n }\n}\n\n/**\n * Apply new server data for the specified path..\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyServerOverwrite(\n syncTree: SyncTree,\n path: Path,\n newData: Node\n): Event[] {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Overwrite(newOperationSourceServer(), path, newData)\n );\n}\n\n/**\n * Apply new server data to be merged in at the specified path.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyServerMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node }\n): Event[] {\n const changeTree = ImmutableTree.fromObject(changedChildren);\n\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Merge(newOperationSourceServer(), path, changeTree)\n );\n}\n\n/**\n * Apply a listen complete for a query\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyListenComplete(\n syncTree: SyncTree,\n path: Path\n): Event[] {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new ListenComplete(newOperationSourceServer(), path)\n );\n}\n\n/**\n * Apply a listen complete for a tagged query\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedListenComplete(\n syncTree: SyncTree,\n path: Path,\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const op = new ListenComplete(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath\n );\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n } else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n}\n\n/**\n * Remove event callback(s).\n *\n * If query is the default query, we'll check all queries for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\n *\n * @param eventRegistration - If null, all callbacks are removed.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no\n * deduping needs to take place. This flag allows toggling of that behavior\n * @returns Cancel events, if cancelError was provided.\n */\nexport function syncTreeRemoveEventRegistration(\n syncTree: SyncTree,\n query: QueryContext,\n eventRegistration: EventRegistration | null,\n cancelError?: Error,\n skipListenerDedup = false\n): Event[] {\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\n const path = query._path;\n const maybeSyncPoint = syncTree.syncPointTree_.get(path);\n let cancelEvents: Event[] = [];\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\n // not loadsAllData().\n if (\n maybeSyncPoint &&\n (query._queryIdentifier === 'default' ||\n syncPointViewExistsForQuery(maybeSyncPoint, query))\n ) {\n const removedAndEvents = syncPointRemoveEventRegistration(\n maybeSyncPoint,\n query,\n eventRegistration,\n cancelError\n );\n if (syncPointIsEmpty(maybeSyncPoint)) {\n syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);\n }\n\n const removed = removedAndEvents.removed;\n cancelEvents = removedAndEvents.events;\n\n if (!skipListenerDedup) {\n /**\n * We may have just removed one of many listeners and can short-circuit this whole process\n * We may also not have removed a default listener, in which case all of the descendant listeners should already be\n * properly set up.\n */\n\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\n // queryId === 'default'\n const removingDefault =\n -1 !==\n removed.findIndex(query => {\n return query._queryParams.loadsAllData();\n });\n const covered = syncTree.syncPointTree_.findOnPath(\n path,\n (relativePath, parentSyncPoint) =>\n syncPointHasCompleteView(parentSyncPoint)\n );\n\n if (removingDefault && !covered) {\n const subtree = syncTree.syncPointTree_.subtree(path);\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\n // removal\n if (!subtree.isEmpty()) {\n // We need to fold over our subtree and collect the listeners to send\n const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);\n\n // Ok, we've collected all the listens we need. Set them up.\n for (let i = 0; i < newViews.length; ++i) {\n const view = newViews[i],\n newQuery = view.query;\n const listener = syncTreeCreateListenerForView_(syncTree, view);\n syncTree.listenProvider_.startListening(\n syncTreeQueryForListening_(newQuery),\n syncTreeTagForQuery(syncTree, newQuery),\n listener.hashFn,\n listener.onComplete\n );\n }\n }\n // Otherwise there's nothing below us, so nothing we need to start listening on\n }\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\n if (!covered && removed.length > 0 && !cancelError) {\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\n // default. Otherwise, we need to iterate through and cancel each individual query\n if (removingDefault) {\n // We don't tag default listeners\n const defaultTag: number | null = null;\n syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(query),\n defaultTag\n );\n } else {\n removed.forEach((queryToRemove: QueryContext) => {\n const tagToRemove = syncTree.queryToTagMap.get(\n syncTreeMakeQueryKey_(queryToRemove)\n );\n syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(queryToRemove),\n tagToRemove\n );\n });\n }\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n syncTreeRemoveTags_(syncTree, removed);\n } else {\n // No-op, this listener must've been already removed\n }\n return cancelEvents;\n}\n\n/**\n * Apply new server data for the specified tagged query.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedQueryOverwrite(\n syncTree: SyncTree,\n path: Path,\n snap: Node,\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey != null) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const op = new Overwrite(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath,\n snap\n );\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n } else {\n // Query must have been removed already\n return [];\n }\n}\n\n/**\n * Apply server data to be merged in for the specified tagged query.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedQueryMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const changeTree = ImmutableTree.fromObject(changedChildren);\n const op = new Merge(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath,\n changeTree\n );\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n } else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n}\n\n/**\n * Add an event callback for the specified query.\n *\n * @returns Events to raise.\n */\nexport function syncTreeAddEventRegistration(\n syncTree: SyncTree,\n query: QueryContext,\n eventRegistration: EventRegistration,\n skipSetupListener = false\n): Event[] {\n const path = query._path;\n\n let serverCache: Node | null = null;\n let foundAncestorDefaultView = false;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\n const relativePath = newRelativePath(pathToSyncPoint, path);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPointHasCompleteView(sp);\n });\n let syncPoint = syncTree.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint();\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\n } else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n\n let serverCacheComplete;\n if (serverCache != null) {\n serverCacheComplete = true;\n } else {\n serverCacheComplete = false;\n serverCache = ChildrenNode.EMPTY_NODE;\n const subtree = syncTree.syncPointTree_.subtree(path);\n subtree.foreachChild((childName, childSyncPoint) => {\n const completeCache = syncPointGetCompleteServerCache(\n childSyncPoint,\n newEmptyPath()\n );\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(\n childName,\n completeCache\n );\n }\n });\n }\n\n const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);\n if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {\n // We need to track a tag for this query\n const queryKey = syncTreeMakeQueryKey_(query);\n assert(\n !syncTree.queryToTagMap.has(queryKey),\n 'View does not exist, but we have a tag'\n );\n const tag = syncTreeGetNextQueryTag_();\n syncTree.queryToTagMap.set(queryKey, tag);\n syncTree.tagToQueryMap.set(tag, queryKey);\n }\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);\n let events = syncPointAddEventRegistration(\n syncPoint,\n query,\n eventRegistration,\n writesCache,\n serverCache,\n serverCacheComplete\n );\n if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {\n const view = syncPointViewForQuery(syncPoint, query);\n events = events.concat(syncTreeSetupListener_(syncTree, query, view));\n }\n return events;\n}\n\n/**\n * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a\n * listener above it, we will get a false \"null\". This shouldn't be a problem because transactions will always\n * have a listener above, and atomic operations would correctly show a jitter of ->\n * as the write is applied locally and then acknowledged at the server.\n *\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\n *\n * @param path - The path to the data we want\n * @param writeIdsToExclude - A specific set to be excluded\n */\nexport function syncTreeCalcCompleteEventCache(\n syncTree: SyncTree,\n path: Path,\n writeIdsToExclude?: number[]\n): Node {\n const includeHiddenSets = true;\n const writeTree = syncTree.pendingWriteTree_;\n const serverCache = syncTree.syncPointTree_.findOnPath(\n path,\n (pathSoFar, syncPoint) => {\n const relativePath = newRelativePath(pathSoFar, path);\n const serverCache = syncPointGetCompleteServerCache(\n syncPoint,\n relativePath\n );\n if (serverCache) {\n return serverCache;\n }\n }\n );\n return writeTreeCalcCompleteEventCache(\n writeTree,\n path,\n serverCache,\n writeIdsToExclude,\n includeHiddenSets\n );\n}\n\nexport function syncTreeGetServerValue(\n syncTree: SyncTree,\n query: QueryContext\n): Node | null {\n const path = query._path;\n let serverCache: Node | null = null;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\n const relativePath = newRelativePath(pathToSyncPoint, path);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\n });\n let syncPoint = syncTree.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint();\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\n } else {\n serverCache =\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n const serverCacheComplete = serverCache != null;\n const serverCacheNode: CacheNode | null = serverCacheComplete\n ? new CacheNode(serverCache, true, false)\n : null;\n const writesCache: WriteTreeRef | null = writeTreeChildWrites(\n syncTree.pendingWriteTree_,\n query._path\n );\n const view: View = syncPointGetView(\n syncPoint,\n query,\n writesCache,\n serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE,\n serverCacheComplete\n );\n return viewGetCompleteNode(view);\n}\n\n/**\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\n *\n * NOTES:\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\n *\n * - We call applyOperation() on each SyncPoint passing three things:\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\n * 3. A snapshot Node with cached server data, if we have it.\n *\n * - We concatenate all of the events returned by each SyncPoint and return the result.\n */\nfunction syncTreeApplyOperationToSyncPoints_(\n syncTree: SyncTree,\n operation: Operation\n): Event[] {\n return syncTreeApplyOperationHelper_(\n operation,\n syncTree.syncPointTree_,\n /*serverCache=*/ null,\n writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath())\n );\n}\n\n/**\n * Recursive helper for applyOperationToSyncPoints_\n */\nfunction syncTreeApplyOperationHelper_(\n operation: Operation,\n syncPointTree: ImmutableTree,\n serverCache: Node | null,\n writesCache: WriteTreeRef\n): Event[] {\n if (pathIsEmpty(operation.path)) {\n return syncTreeApplyOperationDescendantsHelper_(\n operation,\n syncPointTree,\n serverCache,\n writesCache\n );\n } else {\n const syncPoint = syncPointTree.get(newEmptyPath());\n\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n\n let events: Event[] = [];\n const childName = pathGetFront(operation.path);\n const childOperation = operation.operationForChild(childName);\n const childTree = syncPointTree.children.get(childName);\n if (childTree && childOperation) {\n const childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n const childWritesCache = writeTreeRefChild(writesCache, childName);\n events = events.concat(\n syncTreeApplyOperationHelper_(\n childOperation,\n childTree,\n childServerCache,\n childWritesCache\n )\n );\n }\n\n if (syncPoint) {\n events = events.concat(\n syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)\n );\n }\n\n return events;\n }\n}\n\n/**\n * Recursive helper for applyOperationToSyncPoints_\n */\nfunction syncTreeApplyOperationDescendantsHelper_(\n operation: Operation,\n syncPointTree: ImmutableTree,\n serverCache: Node | null,\n writesCache: WriteTreeRef\n): Event[] {\n const syncPoint = syncPointTree.get(newEmptyPath());\n\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n\n let events: Event[] = [];\n syncPointTree.children.inorderTraversal((childName, childTree) => {\n const childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n const childWritesCache = writeTreeRefChild(writesCache, childName);\n const childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(\n syncTreeApplyOperationDescendantsHelper_(\n childOperation,\n childTree,\n childServerCache,\n childWritesCache\n )\n );\n }\n });\n\n if (syncPoint) {\n events = events.concat(\n syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)\n );\n }\n\n return events;\n}\n\nfunction syncTreeCreateListenerForView_(\n syncTree: SyncTree,\n view: View\n): { hashFn(): string; onComplete(a: string, b?: unknown): Event[] } {\n const query = view.query;\n const tag = syncTreeTagForQuery(syncTree, query);\n\n return {\n hashFn: () => {\n const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: (status: string): Event[] => {\n if (status === 'ok') {\n if (tag) {\n return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);\n } else {\n return syncTreeApplyListenComplete(syncTree, query._path);\n }\n } else {\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\n const error = errorForServerCode(status, query);\n return syncTreeRemoveEventRegistration(\n syncTree,\n query,\n /*eventRegistration*/ null,\n error\n );\n }\n }\n };\n}\n\n/**\n * Return the tag associated with the given query.\n */\nexport function syncTreeTagForQuery(\n syncTree: SyncTree,\n query: QueryContext\n): number | null {\n const queryKey = syncTreeMakeQueryKey_(query);\n return syncTree.queryToTagMap.get(queryKey);\n}\n\n/**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n */\nfunction syncTreeMakeQueryKey_(query: QueryContext): string {\n return query._path.toString() + '$' + query._queryIdentifier;\n}\n\n/**\n * Return the query associated with the given tag, if we have one\n */\nfunction syncTreeQueryKeyForTag_(\n syncTree: SyncTree,\n tag: number\n): string | null {\n return syncTree.tagToQueryMap.get(tag);\n}\n\n/**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n */\nfunction syncTreeParseQueryKey_(queryKey: string): {\n queryId: string;\n path: Path;\n} {\n const splitIndex = queryKey.indexOf('$');\n assert(\n splitIndex !== -1 && splitIndex < queryKey.length - 1,\n 'Bad queryKey.'\n );\n return {\n queryId: queryKey.substr(splitIndex + 1),\n path: new Path(queryKey.substr(0, splitIndex))\n };\n}\n\n/**\n * A helper method to apply tagged operations\n */\nfunction syncTreeApplyTaggedOperation_(\n syncTree: SyncTree,\n queryPath: Path,\n operation: Operation\n): Event[] {\n const syncPoint = syncTree.syncPointTree_.get(queryPath);\n assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n const writesCache = writeTreeChildWrites(\n syncTree.pendingWriteTree_,\n queryPath\n );\n return syncPointApplyOperation(syncPoint, operation, writesCache, null);\n}\n\n/**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n */\nfunction syncTreeCollectDistinctViewsForSubTree_(\n subtree: ImmutableTree\n): View[] {\n return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {\n if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {\n const completeView = syncPointGetCompleteView(maybeChildSyncPoint);\n return [completeView];\n } else {\n // No complete view here, flatten any deeper listens into an array\n let views: View[] = [];\n if (maybeChildSyncPoint) {\n views = syncPointGetQueryViews(maybeChildSyncPoint);\n }\n each(childMap, (_key: string, childViews: View[]) => {\n views = views.concat(childViews);\n });\n return views;\n }\n });\n}\n\n/**\n * Normalizes a query to a query we send the server for listening\n *\n * @returns The normalized query\n */\nfunction syncTreeQueryForListening_(query: QueryContext): QueryContext {\n if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {\n // We treat queries that load all data as default queries\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n // from Query\n return new (syncTreeGetReferenceConstructor())(query._repo, query._path);\n } else {\n return query;\n }\n}\n\nfunction syncTreeRemoveTags_(syncTree: SyncTree, queries: QueryContext[]) {\n for (let j = 0; j < queries.length; ++j) {\n const removedQuery = queries[j];\n if (!removedQuery._queryParams.loadsAllData()) {\n // We should have a tag for this\n const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);\n const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);\n syncTree.queryToTagMap.delete(removedQueryKey);\n syncTree.tagToQueryMap.delete(removedQueryTag);\n }\n }\n}\n\n/**\n * Static accessor for query tags.\n */\nfunction syncTreeGetNextQueryTag_(): number {\n return syncTreeNextQueryTag_++;\n}\n\n/**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @returns This method can return events to support synchronous data sources\n */\nfunction syncTreeSetupListener_(\n syncTree: SyncTree,\n query: QueryContext,\n view: View\n): Event[] {\n const path = query._path;\n const tag = syncTreeTagForQuery(syncTree, query);\n const listener = syncTreeCreateListenerForView_(syncTree, view);\n\n const events = syncTree.listenProvider_.startListening(\n syncTreeQueryForListening_(query),\n tag,\n listener.hashFn,\n listener.onComplete\n );\n\n const subtree = syncTree.syncPointTree_.subtree(path);\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\n // may need to shadow other listens as well.\n if (tag) {\n assert(\n !syncPointHasCompleteView(subtree.value),\n \"If we're adding a query, it shouldn't be shadowed\"\n );\n } else {\n // Shadow everything at or below this location, this is a default listener.\n const queriesToStop = subtree.fold(\n (relativePath, maybeChildSyncPoint, childMap) => {\n if (\n !pathIsEmpty(relativePath) &&\n maybeChildSyncPoint &&\n syncPointHasCompleteView(maybeChildSyncPoint)\n ) {\n return [syncPointGetCompleteView(maybeChildSyncPoint).query];\n } else {\n // No default listener here, flatten any deeper queries into an array\n let queries: QueryContext[] = [];\n if (maybeChildSyncPoint) {\n queries = queries.concat(\n syncPointGetQueryViews(maybeChildSyncPoint).map(\n view => view.query\n )\n );\n }\n each(childMap, (_key: string, childQueries: QueryContext[]) => {\n queries = queries.concat(childQueries);\n });\n return queries;\n }\n }\n );\n for (let i = 0; i < queriesToStop.length; ++i) {\n const queryToStop = queriesToStop[i];\n syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(queryToStop),\n syncTreeTagForQuery(syncTree, queryToStop)\n );\n }\n }\n return events;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { PRIORITY_INDEX } from '../snap/indexes/PriorityIndex';\nimport { LeafNode } from '../snap/LeafNode';\nimport { Node } from '../snap/Node';\nimport { nodeFromJSON } from '../snap/nodeFromJSON';\nimport { SyncTree, syncTreeCalcCompleteEventCache } from '../SyncTree';\n\nimport { Indexable } from './misc';\nimport { Path, pathChild } from './Path';\n\n/* It's critical for performance that we do not calculate actual values from a SyncTree\n * unless and until the value is needed. Because we expose both a SyncTree and Node\n * version of deferred value resolution, we ned a wrapper class that will let us share\n * code.\n *\n * @see https://github.com/firebase/firebase-js-sdk/issues/2487\n */\ninterface ValueProvider {\n getImmediateChild(childName: string): ValueProvider;\n node(): Node;\n}\n\nclass ExistingValueProvider implements ValueProvider {\n constructor(readonly node_: Node) {}\n\n getImmediateChild(childName: string): ValueProvider {\n const child = this.node_.getImmediateChild(childName);\n return new ExistingValueProvider(child);\n }\n\n node(): Node {\n return this.node_;\n }\n}\n\nclass DeferredValueProvider implements ValueProvider {\n private syncTree_: SyncTree;\n private path_: Path;\n\n constructor(syncTree: SyncTree, path: Path) {\n this.syncTree_ = syncTree;\n this.path_ = path;\n }\n\n getImmediateChild(childName: string): ValueProvider {\n const childPath = pathChild(this.path_, childName);\n return new DeferredValueProvider(this.syncTree_, childPath);\n }\n\n node(): Node {\n return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);\n }\n}\n\n/**\n * Generate placeholders for deferred values.\n */\nexport const generateWithValues = function (\n values: {\n [k: string]: unknown;\n } | null\n): { [k: string]: unknown } {\n values = values || {};\n values['timestamp'] = values['timestamp'] || new Date().getTime();\n return values;\n};\n\n/**\n * Value to use when firing local events. When writing server values, fire\n * local events with an approximate value, otherwise return value as-is.\n */\nexport const resolveDeferredLeafValue = function (\n value: { [k: string]: unknown } | string | number | boolean,\n existingVal: ValueProvider,\n serverValues: { [k: string]: unknown }\n): string | number | boolean {\n if (!value || typeof value !== 'object') {\n return value as string | number | boolean;\n }\n assert('.sv' in value, 'Unexpected leaf node or priority contents');\n\n if (typeof value['.sv'] === 'string') {\n return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);\n } else if (typeof value['.sv'] === 'object') {\n return resolveComplexDeferredValue(value['.sv'], existingVal, serverValues);\n } else {\n assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));\n }\n};\n\nconst resolveScalarDeferredValue = function (\n op: string,\n existing: ValueProvider,\n serverValues: { [k: string]: unknown }\n): string | number | boolean {\n switch (op) {\n case 'timestamp':\n return serverValues['timestamp'] as string | number | boolean;\n default:\n assert(false, 'Unexpected server value: ' + op);\n }\n};\n\nconst resolveComplexDeferredValue = function (\n op: object,\n existing: ValueProvider,\n unused: { [k: string]: unknown }\n): string | number | boolean {\n if (!op.hasOwnProperty('increment')) {\n assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));\n }\n const delta = op['increment'];\n if (typeof delta !== 'number') {\n assert(false, 'Unexpected increment value: ' + delta);\n }\n\n const existingNode = existing.node();\n assert(\n existingNode !== null && typeof existingNode !== 'undefined',\n 'Expected ChildrenNode.EMPTY_NODE for nulls'\n );\n\n // Incrementing a non-number sets the value to the incremented amount\n if (!existingNode.isLeafNode()) {\n return delta;\n }\n\n const leaf = existingNode as LeafNode;\n const existingVal = leaf.getValue();\n if (typeof existingVal !== 'number') {\n return delta;\n }\n\n // No need to do over/underflow arithmetic here because JS only handles floats under the covers\n return existingVal + delta;\n};\n\n/**\n * Recursively replace all deferred values and priorities in the tree with the\n * specified generated replacement values.\n * @param path - path to which write is relative\n * @param node - new data written at path\n * @param syncTree - current data\n */\nexport const resolveDeferredValueTree = function (\n path: Path,\n node: Node,\n syncTree: SyncTree,\n serverValues: Indexable\n): Node {\n return resolveDeferredValue(\n node,\n new DeferredValueProvider(syncTree, path),\n serverValues\n );\n};\n\n/**\n * Recursively replace all deferred values and priorities in the node with the\n * specified generated replacement values. If there are no server values in the node,\n * it'll be returned as-is.\n */\nexport const resolveDeferredValueSnapshot = function (\n node: Node,\n existing: Node,\n serverValues: Indexable\n): Node {\n return resolveDeferredValue(\n node,\n new ExistingValueProvider(existing),\n serverValues\n );\n};\n\nfunction resolveDeferredValue(\n node: Node,\n existingVal: ValueProvider,\n serverValues: Indexable\n): Node {\n const rawPri = node.getPriority().val() as\n | Indexable\n | boolean\n | null\n | number\n | string;\n const priority = resolveDeferredLeafValue(\n rawPri,\n existingVal.getImmediateChild('.priority'),\n serverValues\n );\n let newNode: Node;\n\n if (node.isLeafNode()) {\n const leafNode = node as LeafNode;\n const value = resolveDeferredLeafValue(\n leafNode.getValue(),\n existingVal,\n serverValues\n );\n if (\n value !== leafNode.getValue() ||\n priority !== leafNode.getPriority().val()\n ) {\n return new LeafNode(value, nodeFromJSON(priority));\n } else {\n return node;\n }\n } else {\n const childrenNode = node as ChildrenNode;\n newNode = childrenNode;\n if (priority !== childrenNode.getPriority().val()) {\n newNode = newNode.updatePriority(new LeafNode(priority));\n }\n childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\n const newChildNode = resolveDeferredValue(\n childNode,\n existingVal.getImmediateChild(childName),\n serverValues\n );\n if (newChildNode !== childNode) {\n newNode = newNode.updateImmediateChild(childName, newChildNode);\n }\n });\n return newNode;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains, safeGet } from '@firebase/util';\n\nimport { Path, pathGetFront, pathPopFront } from './Path';\nimport { each } from './util';\n\n/**\n * Node in a Tree.\n */\nexport interface TreeNode {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n children: Record>;\n childCount: number;\n value?: T;\n}\n\n/**\n * A light-weight tree, traversable by path. Nodes can have both values and children.\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\n * children.\n */\nexport class Tree {\n /**\n * @param name - Optional name of the node.\n * @param parent - Optional parent node.\n * @param node - Optional node to wrap.\n */\n constructor(\n readonly name: string = '',\n readonly parent: Tree | null = null,\n public node: TreeNode = { children: {}, childCount: 0 }\n ) {}\n}\n\n/**\n * Returns a sub-Tree for the given path.\n *\n * @param pathObj - Path to look up.\n * @returns Tree for path.\n */\nexport function treeSubTree(tree: Tree, pathObj: string | Path): Tree {\n // TODO: Require pathObj to be Path?\n let path = pathObj instanceof Path ? pathObj : new Path(pathObj);\n let child = tree,\n next = pathGetFront(path);\n while (next !== null) {\n const childNode = safeGet(child.node.children, next) || {\n children: {},\n childCount: 0\n };\n child = new Tree(next, child, childNode);\n path = pathPopFront(path);\n next = pathGetFront(path);\n }\n\n return child;\n}\n\n/**\n * Returns the data associated with this tree node.\n *\n * @returns The data or null if no data exists.\n */\nexport function treeGetValue(tree: Tree): T | undefined {\n return tree.node.value;\n}\n\n/**\n * Sets data to this tree node.\n *\n * @param value - Value to set.\n */\nexport function treeSetValue(tree: Tree, value: T | undefined): void {\n tree.node.value = value;\n treeUpdateParents(tree);\n}\n\n/**\n * @returns Whether the tree has any children.\n */\nexport function treeHasChildren(tree: Tree): boolean {\n return tree.node.childCount > 0;\n}\n\n/**\n * @returns Whether the tree is empty (no value or children).\n */\nexport function treeIsEmpty(tree: Tree): boolean {\n return treeGetValue(tree) === undefined && !treeHasChildren(tree);\n}\n\n/**\n * Calls action for each child of this tree node.\n *\n * @param action - Action to be called for each child.\n */\nexport function treeForEachChild(\n tree: Tree,\n action: (tree: Tree) => void\n): void {\n each(tree.node.children, (child: string, childTree: TreeNode) => {\n action(new Tree(child, tree, childTree));\n });\n}\n\n/**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param action - Action to be called for each child.\n * @param includeSelf - Whether to call action on this node as well. Defaults to\n * false.\n * @param childrenFirst - Whether to call action on children before calling it on\n * parent.\n */\nexport function treeForEachDescendant(\n tree: Tree,\n action: (tree: Tree) => void,\n includeSelf?: boolean,\n childrenFirst?: boolean\n): void {\n if (includeSelf && !childrenFirst) {\n action(tree);\n }\n\n treeForEachChild(tree, child => {\n treeForEachDescendant(child, action, true, childrenFirst);\n });\n\n if (includeSelf && childrenFirst) {\n action(tree);\n }\n}\n\n/**\n * Calls action on each ancestor node.\n *\n * @param action - Action to be called on each parent; return\n * true to abort.\n * @param includeSelf - Whether to call action on this node as well.\n * @returns true if the action callback returned true.\n */\nexport function treeForEachAncestor(\n tree: Tree,\n action: (tree: Tree) => unknown,\n includeSelf?: boolean\n): boolean {\n let node = includeSelf ? tree : tree.parent;\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n node = node.parent;\n }\n return false;\n}\n\n/**\n * Does a depth-first traversal of this node's descendants. When a descendant with a value\n * is found, action is called on it and traversal does not continue inside the node.\n * Action is *not* called on this node.\n *\n * @param action - Action to be called for each child.\n */\nexport function treeForEachImmediateDescendantWithValue(\n tree: Tree,\n action: (tree: Tree) => void\n): void {\n treeForEachChild(tree, child => {\n if (treeGetValue(child) !== undefined) {\n action(child);\n } else {\n treeForEachImmediateDescendantWithValue(child, action);\n }\n });\n}\n\n/**\n * @returns The path of this tree node, as a Path.\n */\nexport function treeGetPath(tree: Tree) {\n return new Path(\n tree.parent === null\n ? tree.name\n : treeGetPath(tree.parent) + '/' + tree.name\n );\n}\n\n/**\n * Adds or removes this child from its parent based on whether it's empty or not.\n */\nfunction treeUpdateParents(tree: Tree) {\n if (tree.parent !== null) {\n treeUpdateChild(tree.parent, tree.name, tree);\n }\n}\n\n/**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param childName - The name of the child to update.\n * @param child - The child to update.\n */\nfunction treeUpdateChild(tree: Tree, childName: string, child: Tree) {\n const childEmpty = treeIsEmpty(child);\n const childExists = contains(tree.node.children, childName);\n if (childEmpty && childExists) {\n delete tree.node.children[childName];\n tree.node.childCount--;\n treeUpdateParents(tree);\n } else if (!childEmpty && !childExists) {\n tree.node.children[childName] = child.node;\n tree.node.childCount++;\n treeUpdateParents(tree);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n contains,\n errorPrefix as errorPrefixFxn,\n safeGet,\n stringLength\n} from '@firebase/util';\n\nimport { RepoInfo } from '../RepoInfo';\n\nimport {\n Path,\n pathChild,\n pathCompare,\n pathContains,\n pathGetBack,\n pathGetFront,\n pathSlice,\n ValidationPath,\n validationPathPop,\n validationPathPush,\n validationPathToErrorString\n} from './Path';\nimport { each, isInvalidJSONNumber } from './util';\n\n/**\n * True for invalid Firebase keys\n */\nexport const INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\n\n/**\n * True for invalid Firebase paths.\n * Allows '/' in paths.\n */\nexport const INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\n\n/**\n * Maximum number of characters to allow in leaf value\n */\nexport const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\n\nexport const isValidKey = function (key: unknown): boolean {\n return (\n typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key)\n );\n};\n\nexport const isValidPathString = function (pathString: string): boolean {\n return (\n typeof pathString === 'string' &&\n pathString.length !== 0 &&\n !INVALID_PATH_REGEX_.test(pathString)\n );\n};\n\nexport const isValidRootPathString = function (pathString: string): boolean {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n\n return isValidPathString(pathString);\n};\n\nexport const isValidPriority = function (priority: unknown): boolean {\n return (\n priority === null ||\n typeof priority === 'string' ||\n (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||\n (priority &&\n typeof priority === 'object' &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n contains(priority as any, '.sv'))\n );\n};\n\n/**\n * Pre-validate a datum passed as an argument to Firebase function.\n */\nexport const validateFirebaseDataArg = function (\n fnName: string,\n value: unknown,\n path: Path,\n optional: boolean\n) {\n if (optional && value === undefined) {\n return;\n }\n\n validateFirebaseData(errorPrefixFxn(fnName, 'value'), value, path);\n};\n\n/**\n * Validate a data object client-side before sending to server.\n */\nexport const validateFirebaseData = function (\n errorPrefix: string,\n data: unknown,\n path_: Path | ValidationPath\n) {\n const path =\n path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;\n\n if (data === undefined) {\n throw new Error(\n errorPrefix + 'contains undefined ' + validationPathToErrorString(path)\n );\n }\n if (typeof data === 'function') {\n throw new Error(\n errorPrefix +\n 'contains a function ' +\n validationPathToErrorString(path) +\n ' with contents = ' +\n data.toString()\n );\n }\n if (isInvalidJSONNumber(data)) {\n throw new Error(\n errorPrefix +\n 'contains ' +\n data.toString() +\n ' ' +\n validationPathToErrorString(path)\n );\n }\n\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\n if (\n typeof data === 'string' &&\n data.length > MAX_LEAF_SIZE_ / 3 &&\n stringLength(data) > MAX_LEAF_SIZE_\n ) {\n throw new Error(\n errorPrefix +\n 'contains a string greater than ' +\n MAX_LEAF_SIZE_ +\n ' utf8 bytes ' +\n validationPathToErrorString(path) +\n \" ('\" +\n data.substring(0, 50) +\n \"...')\"\n );\n }\n\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\n // to save extra walking of large objects.\n if (data && typeof data === 'object') {\n let hasDotValue = false;\n let hasActualChild = false;\n each(data, (key: string, value: unknown) => {\n if (key === '.value') {\n hasDotValue = true;\n } else if (key !== '.priority' && key !== '.sv') {\n hasActualChild = true;\n if (!isValidKey(key)) {\n throw new Error(\n errorPrefix +\n ' contains an invalid key (' +\n key +\n ') ' +\n validationPathToErrorString(path) +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"'\n );\n }\n }\n\n validationPathPush(path, key);\n validateFirebaseData(errorPrefix, value, path);\n validationPathPop(path);\n });\n\n if (hasDotValue && hasActualChild) {\n throw new Error(\n errorPrefix +\n ' contains \".value\" child ' +\n validationPathToErrorString(path) +\n ' in addition to actual children.'\n );\n }\n }\n};\n\n/**\n * Pre-validate paths passed in the firebase function.\n */\nexport const validateFirebaseMergePaths = function (\n errorPrefix: string,\n mergePaths: Path[]\n) {\n let i, curPath: Path;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n const keys = pathSlice(curPath);\n for (let j = 0; j < keys.length; j++) {\n if (keys[j] === '.priority' && j === keys.length - 1) {\n // .priority is OK\n } else if (!isValidKey(keys[j])) {\n throw new Error(\n errorPrefix +\n 'contains an invalid key (' +\n keys[j] +\n ') in path ' +\n curPath.toString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"'\n );\n }\n }\n }\n\n // Check that update keys are not descendants of each other.\n // We rely on the property that sorting guarantees that ancestors come\n // right before descendants.\n mergePaths.sort(pathCompare);\n let prevPath: Path | null = null;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n if (prevPath !== null && pathContains(prevPath, curPath)) {\n throw new Error(\n errorPrefix +\n 'contains a path ' +\n prevPath.toString() +\n ' that is ancestor of another path ' +\n curPath.toString()\n );\n }\n prevPath = curPath;\n }\n};\n\n/**\n * pre-validate an object passed as an argument to firebase function (\n * must be an object - e.g. for firebase.update()).\n */\nexport const validateFirebaseMergeDataArg = function (\n fnName: string,\n data: unknown,\n path: Path,\n optional: boolean\n) {\n if (optional && data === undefined) {\n return;\n }\n\n const errorPrefix = errorPrefixFxn(fnName, 'values');\n\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\n throw new Error(\n errorPrefix + ' must be an object containing the children to replace.'\n );\n }\n\n const mergePaths: Path[] = [];\n each(data, (key: string, value: unknown) => {\n const curPath = new Path(key);\n validateFirebaseData(errorPrefix, value, pathChild(path, curPath));\n if (pathGetBack(curPath) === '.priority') {\n if (!isValidPriority(value)) {\n throw new Error(\n errorPrefix +\n \"contains an invalid value for '\" +\n curPath.toString() +\n \"', which must be a valid \" +\n 'Firebase priority (a string, finite number, server value, or null).'\n );\n }\n }\n mergePaths.push(curPath);\n });\n validateFirebaseMergePaths(errorPrefix, mergePaths);\n};\n\nexport const validatePriority = function (\n fnName: string,\n priority: unknown,\n optional: boolean\n) {\n if (optional && priority === undefined) {\n return;\n }\n if (isInvalidJSONNumber(priority)) {\n throw new Error(\n errorPrefixFxn(fnName, 'priority') +\n 'is ' +\n priority.toString() +\n ', but must be a valid Firebase priority (a string, finite number, ' +\n 'server value, or null).'\n );\n }\n // Special case to allow importing data with a .sv.\n if (!isValidPriority(priority)) {\n throw new Error(\n errorPrefixFxn(fnName, 'priority') +\n 'must be a valid Firebase priority ' +\n '(a string, finite number, server value, or null).'\n );\n }\n};\n\nexport const validateKey = function (\n fnName: string,\n argumentName: string,\n key: string,\n optional: boolean\n) {\n if (optional && key === undefined) {\n return;\n }\n if (!isValidKey(key)) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'was an invalid key = \"' +\n key +\n '\". Firebase keys must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").'\n );\n }\n};\n\n/**\n * @internal\n */\nexport const validatePathString = function (\n fnName: string,\n argumentName: string,\n pathString: string,\n optional: boolean\n) {\n if (optional && pathString === undefined) {\n return;\n }\n\n if (!isValidPathString(pathString)) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'was an invalid path = \"' +\n pathString +\n '\". Paths must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"'\n );\n }\n};\n\nexport const validateRootPathString = function (\n fnName: string,\n argumentName: string,\n pathString: string,\n optional: boolean\n) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n\n validatePathString(fnName, argumentName, pathString, optional);\n};\n\n/**\n * @internal\n */\nexport const validateWritablePath = function (fnName: string, path: Path) {\n if (pathGetFront(path) === '.info') {\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\n }\n};\n\nexport const validateUrl = function (\n fnName: string,\n parsedUrl: { repoInfo: RepoInfo; path: Path }\n) {\n // TODO = Validate server better.\n const pathString = parsedUrl.path.toString();\n if (\n !(typeof parsedUrl.repoInfo.host === 'string') ||\n parsedUrl.repoInfo.host.length === 0 ||\n (!isValidKey(parsedUrl.repoInfo.namespace) &&\n parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||\n (pathString.length !== 0 && !isValidRootPathString(pathString))\n ) {\n throw new Error(\n errorPrefixFxn(fnName, 'url') +\n 'must be a valid firebase URL and ' +\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".'\n );\n }\n};\n\nexport const validateString = function (\n fnName: string,\n argumentName: string,\n string: unknown,\n optional: boolean\n) {\n if (optional && string === undefined) {\n return;\n }\n if (!(typeof string === 'string')) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) + 'must be a valid string.'\n );\n }\n};\n\nexport const validateObject = function (\n fnName: string,\n argumentName: string,\n obj: unknown,\n optional: boolean\n) {\n if (optional && obj === undefined) {\n return;\n }\n if (!(obj && typeof obj === 'object') || obj === null) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) + 'must be a valid object.'\n );\n }\n};\n\nexport const validateObjectContainsKey = function (\n fnName: string,\n argumentName: string,\n obj: unknown,\n key: string,\n optional: boolean,\n optType?: string\n) {\n const objectContainsKey =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj && typeof obj === 'object' && contains(obj as any, key);\n\n if (!objectContainsKey) {\n if (optional) {\n return;\n } else {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'must contain the key \"' +\n key +\n '\"'\n );\n }\n }\n\n if (optType) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const val = safeGet(obj as any, key);\n if (\n (optType === 'number' && !(typeof val === 'number')) ||\n (optType === 'string' && !(typeof val === 'string')) ||\n (optType === 'boolean' && !(typeof val === 'boolean')) ||\n (optType === 'function' && !(typeof val === 'function')) ||\n (optType === 'object' && !(typeof val === 'object') && val)\n ) {\n if (optional) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'contains invalid value for key \"' +\n key +\n '\" (must be of type \"' +\n optType +\n '\")'\n );\n } else {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'must contain the key \"' +\n key +\n '\" with type \"' +\n optType +\n '\"'\n );\n }\n }\n }\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Path, pathContains, pathEquals } from '../util/Path';\nimport { exceptionGuard, log, logger } from '../util/util';\n\nimport { Event } from './Event';\n\n/**\n * The event queue serves a few purposes:\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\n * events being queued.\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\n * left off, ensuring that the events are still raised synchronously and in order.\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\n * events are raised synchronously.\n *\n * NOTE: This can all go away if/when we move to async events.\n *\n */\nexport class EventQueue {\n eventLists_: EventList[] = [];\n\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n */\n recursionDepth_ = 0;\n}\n\n/**\n * @param eventDataList - The new events to queue.\n */\nexport function eventQueueQueueEvents(\n eventQueue: EventQueue,\n eventDataList: Event[]\n) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n let currList: EventList | null = null;\n for (let i = 0; i < eventDataList.length; i++) {\n const data = eventDataList[i];\n const path = data.getPath();\n if (currList !== null && !pathEquals(path, currList.path)) {\n eventQueue.eventLists_.push(currList);\n currList = null;\n }\n\n if (currList === null) {\n currList = { events: [], path };\n }\n\n currList.events.push(data);\n }\n if (currList) {\n eventQueue.eventLists_.push(currList);\n }\n}\n\n/**\n * Queues the specified events and synchronously raises all events (including previously queued ones)\n * for the specified path.\n *\n * It is assumed that the new events are all for the specified path.\n *\n * @param path - The path to raise events for.\n * @param eventDataList - The new events to raise.\n */\nexport function eventQueueRaiseEventsAtPath(\n eventQueue: EventQueue,\n path: Path,\n eventDataList: Event[]\n) {\n eventQueueQueueEvents(eventQueue, eventDataList);\n eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath =>\n pathEquals(eventPath, path)\n );\n}\n\n/**\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\n * locations related to the specified change path (i.e. all ancestors and descendants).\n *\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\n *\n * @param changedPath - The path to raise events for.\n * @param eventDataList - The events to raise\n */\nexport function eventQueueRaiseEventsForChangedPath(\n eventQueue: EventQueue,\n changedPath: Path,\n eventDataList: Event[]\n) {\n eventQueueQueueEvents(eventQueue, eventDataList);\n eventQueueRaiseQueuedEventsMatchingPredicate(\n eventQueue,\n eventPath =>\n pathContains(eventPath, changedPath) ||\n pathContains(changedPath, eventPath)\n );\n}\n\nfunction eventQueueRaiseQueuedEventsMatchingPredicate(\n eventQueue: EventQueue,\n predicate: (path: Path) => boolean\n) {\n eventQueue.recursionDepth_++;\n\n let sentAll = true;\n for (let i = 0; i < eventQueue.eventLists_.length; i++) {\n const eventList = eventQueue.eventLists_[i];\n if (eventList) {\n const eventPath = eventList.path;\n if (predicate(eventPath)) {\n eventListRaise(eventQueue.eventLists_[i]);\n eventQueue.eventLists_[i] = null;\n } else {\n sentAll = false;\n }\n }\n }\n\n if (sentAll) {\n eventQueue.eventLists_ = [];\n }\n\n eventQueue.recursionDepth_--;\n}\n\ninterface EventList {\n events: Event[];\n path: Path;\n}\n\n/**\n * Iterates through the list and raises each event\n */\nfunction eventListRaise(eventList: EventList) {\n for (let i = 0; i < eventList.events.length; i++) {\n const eventData = eventList.events[i];\n if (eventData !== null) {\n eventList.events[i] = null;\n const eventFn = eventData.getEventRunner();\n if (logger) {\n log('event: ' + eventData.toString());\n }\n exceptionGuard(eventFn);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n contains,\n isEmpty,\n map,\n safeGet,\n stringify\n} from '@firebase/util';\n\nimport { ValueEventRegistration } from '../api/Reference_impl';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { PersistentConnection } from './PersistentConnection';\nimport { ReadonlyRestClient } from './ReadonlyRestClient';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { nodeFromJSON } from './snap/nodeFromJSON';\nimport { SnapshotHolder } from './SnapshotHolder';\nimport {\n newSparseSnapshotTree,\n SparseSnapshotTree,\n sparseSnapshotTreeForEachTree,\n sparseSnapshotTreeForget,\n sparseSnapshotTreeRemember\n} from './SparseSnapshotTree';\nimport { StatsCollection } from './stats/StatsCollection';\nimport { StatsListener } from './stats/StatsListener';\nimport {\n statsManagerGetCollection,\n statsManagerGetOrCreateReporter\n} from './stats/StatsManager';\nimport { StatsReporter, statsReporterIncludeStat } from './stats/StatsReporter';\nimport {\n SyncTree,\n syncTreeAckUserWrite,\n syncTreeAddEventRegistration,\n syncTreeApplyServerMerge,\n syncTreeApplyServerOverwrite,\n syncTreeApplyTaggedQueryMerge,\n syncTreeApplyTaggedQueryOverwrite,\n syncTreeApplyUserMerge,\n syncTreeApplyUserOverwrite,\n syncTreeCalcCompleteEventCache,\n syncTreeGetServerValue,\n syncTreeRemoveEventRegistration,\n syncTreeTagForQuery\n} from './SyncTree';\nimport { Indexable } from './util/misc';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathGetFront,\n pathPopFront\n} from './util/Path';\nimport {\n generateWithValues,\n resolveDeferredValueSnapshot,\n resolveDeferredValueTree\n} from './util/ServerValues';\nimport {\n Tree,\n treeForEachAncestor,\n treeForEachChild,\n treeForEachDescendant,\n treeGetPath,\n treeGetValue,\n treeHasChildren,\n treeSetValue,\n treeSubTree\n} from './util/Tree';\nimport {\n beingCrawled,\n each,\n exceptionGuard,\n log,\n LUIDGenerator,\n warn\n} from './util/util';\nimport { isValidPriority, validateFirebaseData } from './util/validation';\nimport { Event } from './view/Event';\nimport {\n EventQueue,\n eventQueueQueueEvents,\n eventQueueRaiseEventsAtPath,\n eventQueueRaiseEventsForChangedPath\n} from './view/EventQueue';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\n\nconst INTERRUPT_REASON = 'repo_interrupt';\n\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other\n * things this ensure that if there's ever a bug causing a mismatch between\n * client / server hashes for some data, we won't retry indefinitely.\n */\nconst MAX_TRANSACTION_RETRIES = 25;\n\nconst enum TransactionStatus {\n // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the\n // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to\n // mismatched hash.\n RUN,\n\n // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted\n // or rejected yet).\n SENT,\n\n // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be\n // removed when we get a chance to prune completed ones.\n COMPLETED,\n\n // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made).\n // If it comes back as unsuccessful, we'll abort it.\n SENT_NEEDS_ABORT,\n\n // Temporary state used to mark transactions that need to be aborted.\n NEEDS_ABORT\n}\n\ninterface Transaction {\n path: Path;\n update: (a: unknown) => unknown;\n onComplete: (\n error: Error | null,\n committed: boolean,\n node: Node | null\n ) => void;\n status: TransactionStatus;\n order: number;\n applyLocally: boolean;\n retryCount: number;\n unwatcher: () => void;\n abortReason: string | null;\n currentWriteId: number;\n currentInputSnapshot: Node | null;\n currentOutputSnapshotRaw: Node | null;\n currentOutputSnapshotResolved: Node | null;\n}\n\n/**\n * A connection to a single data repository.\n */\nexport class Repo {\n /** Key for uniquely identifying this repo, used in RepoManager */\n readonly key: string;\n\n dataUpdateCount = 0;\n infoSyncTree_: SyncTree;\n serverSyncTree_: SyncTree;\n\n stats_: StatsCollection;\n statsListener_: StatsListener | null = null;\n eventQueue_ = new EventQueue();\n nextWriteId_ = 1;\n server_: ServerActions;\n statsReporter_: StatsReporter;\n infoData_: SnapshotHolder;\n interceptServerDataCallback_: ((a: string, b: unknown) => void) | null = null;\n\n /** A list of data pieces and paths to be set when this client disconnects. */\n onDisconnect_: SparseSnapshotTree = newSparseSnapshotTree();\n\n /** Stores queues of outstanding transactions for Firebase locations. */\n transactionQueueTree_ = new Tree();\n\n // TODO: This should be @private but it's used by test_access.js and internal.js\n persistentConnection_: PersistentConnection | null = null;\n\n constructor(\n public repoInfo_: RepoInfo,\n public forceRestClient_: boolean,\n public authTokenProvider_: AuthTokenProvider,\n public appCheckProvider_: AppCheckTokenProvider\n ) {\n // This key is intentionally not updated if RepoInfo is later changed or replaced\n this.key = this.repoInfo_.toURLString();\n }\n\n /**\n * @returns The URL corresponding to the root of this Firebase.\n */\n toString(): string {\n return (\n (this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host\n );\n }\n}\n\nexport function repoStart(\n repo: Repo,\n appId: string,\n authOverride?: object\n): void {\n repo.stats_ = statsManagerGetCollection(repo.repoInfo_);\n\n if (repo.forceRestClient_ || beingCrawled()) {\n repo.server_ = new ReadonlyRestClient(\n repo.repoInfo_,\n (\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n ) => {\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\n },\n repo.authTokenProvider_,\n repo.appCheckProvider_\n );\n\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\n setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);\n } else {\n // Validate authOverride\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\n if (typeof authOverride !== 'object') {\n throw new Error(\n 'Only objects are supported for option databaseAuthVariableOverride'\n );\n }\n try {\n stringify(authOverride);\n } catch (e) {\n throw new Error('Invalid authOverride provided: ' + e);\n }\n }\n\n repo.persistentConnection_ = new PersistentConnection(\n repo.repoInfo_,\n appId,\n (\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n ) => {\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\n },\n (connectStatus: boolean) => {\n repoOnConnectStatus(repo, connectStatus);\n },\n (updates: object) => {\n repoOnServerInfoUpdate(repo, updates);\n },\n repo.authTokenProvider_,\n repo.appCheckProvider_,\n authOverride\n );\n\n repo.server_ = repo.persistentConnection_;\n }\n\n repo.authTokenProvider_.addTokenChangeListener(token => {\n repo.server_.refreshAuthToken(token);\n });\n\n repo.appCheckProvider_.addTokenChangeListener(result => {\n repo.server_.refreshAppCheckToken(result.token);\n });\n\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\n repo.statsReporter_ = statsManagerGetOrCreateReporter(\n repo.repoInfo_,\n () => new StatsReporter(repo.stats_, repo.server_)\n );\n\n // Used for .info.\n repo.infoData_ = new SnapshotHolder();\n repo.infoSyncTree_ = new SyncTree({\n startListening: (query, tag, currentHashFn, onComplete) => {\n let infoEvents: Event[] = [];\n const node = repo.infoData_.getNode(query._path);\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\n // on initial data...\n if (!node.isEmpty()) {\n infoEvents = syncTreeApplyServerOverwrite(\n repo.infoSyncTree_,\n query._path,\n node\n );\n setTimeout(() => {\n onComplete('ok');\n }, 0);\n }\n return infoEvents;\n },\n stopListening: () => {}\n });\n repoUpdateInfo(repo, 'connected', false);\n\n repo.serverSyncTree_ = new SyncTree({\n startListening: (query, tag, currentHashFn, onComplete) => {\n repo.server_.listen(query, currentHashFn, tag, (status, data) => {\n const events = onComplete(status, data);\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n query._path,\n events\n );\n });\n // No synchronous events for network-backed sync trees\n return [];\n },\n stopListening: (query, tag) => {\n repo.server_.unlisten(query, tag);\n }\n });\n}\n\n/**\n * @returns The time in milliseconds, taking the server offset into account if we have one.\n */\nexport function repoServerTime(repo: Repo): number {\n const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));\n const offset = (offsetNode.val() as number) || 0;\n return new Date().getTime() + offset;\n}\n\n/**\n * Generate ServerValues using some variables from the repo object.\n */\nexport function repoGenerateServerValues(repo: Repo): Indexable {\n return generateWithValues({\n timestamp: repoServerTime(repo)\n });\n}\n\n/**\n * Called by realtime when we get new messages from the server.\n */\nfunction repoOnDataUpdate(\n repo: Repo,\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n): void {\n // For testing.\n repo.dataUpdateCount++;\n const path = new Path(pathString);\n data = repo.interceptServerDataCallback_\n ? repo.interceptServerDataCallback_(pathString, data)\n : data;\n let events = [];\n if (tag) {\n if (isMerge) {\n const taggedChildren = map(\n data as { [k: string]: unknown },\n (raw: unknown) => nodeFromJSON(raw)\n );\n events = syncTreeApplyTaggedQueryMerge(\n repo.serverSyncTree_,\n path,\n taggedChildren,\n tag\n );\n } else {\n const taggedSnap = nodeFromJSON(data);\n events = syncTreeApplyTaggedQueryOverwrite(\n repo.serverSyncTree_,\n path,\n taggedSnap,\n tag\n );\n }\n } else if (isMerge) {\n const changedChildren = map(\n data as { [k: string]: unknown },\n (raw: unknown) => nodeFromJSON(raw)\n );\n events = syncTreeApplyServerMerge(\n repo.serverSyncTree_,\n path,\n changedChildren\n );\n } else {\n const snap = nodeFromJSON(data);\n events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);\n }\n let affectedPath = path;\n if (events.length > 0) {\n // Since we have a listener outstanding for each transaction, receiving any events\n // is a proxy for some change having occurred.\n affectedPath = repoRerunTransactions(repo, path);\n }\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);\n}\n\n// TODO: This should be @private but it's used by test_access.js and internal.js\nexport function repoInterceptServerData(\n repo: Repo,\n callback: ((a: string, b: unknown) => unknown) | null\n): void {\n repo.interceptServerDataCallback_ = callback;\n}\n\nfunction repoOnConnectStatus(repo: Repo, connectStatus: boolean): void {\n repoUpdateInfo(repo, 'connected', connectStatus);\n if (connectStatus === false) {\n repoRunOnDisconnectEvents(repo);\n }\n}\n\nfunction repoOnServerInfoUpdate(repo: Repo, updates: object): void {\n each(updates, (key: string, value: unknown) => {\n repoUpdateInfo(repo, key, value);\n });\n}\n\nfunction repoUpdateInfo(repo: Repo, pathString: string, value: unknown): void {\n const path = new Path('/.info/' + pathString);\n const newNode = nodeFromJSON(value);\n repo.infoData_.updateSnapshot(path, newNode);\n const events = syncTreeApplyServerOverwrite(\n repo.infoSyncTree_,\n path,\n newNode\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n}\n\nfunction repoGetNextWriteId(repo: Repo): number {\n return repo.nextWriteId_++;\n}\n\n/**\n * The purpose of `getValue` is to return the latest known value\n * satisfying `query`.\n *\n * This method will first check for in-memory cached values\n * belonging to active listeners. If they are found, such values\n * are considered to be the most up-to-date.\n *\n * If the client is not connected, this method will wait until the\n * repo has established a connection and then request the value for `query`.\n * If the client is not able to retrieve the query result for another reason,\n * it reports an error.\n *\n * @param query - The query to surface a value for.\n */\nexport function repoGetValue(\n repo: Repo,\n query: QueryContext,\n eventRegistration: ValueEventRegistration\n): Promise {\n // Only active queries are cached. There is no persisted cache.\n const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);\n if (cached != null) {\n return Promise.resolve(cached);\n }\n return repo.server_.get(query).then(\n payload => {\n const node = nodeFromJSON(payload).withIndex(\n query._queryParams.getIndex()\n );\n /**\n * Below we simulate the actions of an `onlyOnce` `onValue()` event where:\n * Add an event registration,\n * Update data at the path,\n * Raise any events,\n * Cleanup the SyncTree\n */\n syncTreeAddEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration,\n true\n );\n let events: Event[];\n if (query._queryParams.loadsAllData()) {\n events = syncTreeApplyServerOverwrite(\n repo.serverSyncTree_,\n query._path,\n node\n );\n } else {\n const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);\n events = syncTreeApplyTaggedQueryOverwrite(\n repo.serverSyncTree_,\n query._path,\n node,\n tag\n );\n }\n /*\n * We need to raise events in the scenario where `get()` is called at a parent path, and\n * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting\n * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree\n * and its corresponding serverCache, including the child location where `onValue` is called. Then,\n * `onValue` will receive the event from the server, but look at the syncTree and see that the data received\n * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.\n * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and\n * ensure the corresponding child events will get fired.\n */\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n query._path,\n events\n );\n syncTreeRemoveEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration,\n null,\n true\n );\n return node;\n },\n err => {\n repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);\n return Promise.reject(new Error(err as string));\n }\n );\n}\n\nexport function repoSetWithPriority(\n repo: Repo,\n path: Path,\n newVal: unknown,\n newPriority: number | string | null,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repoLog(repo, 'set', {\n path: path.toString(),\n value: newVal,\n priority: newPriority\n });\n\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\n // (b) store unresolved paths on JSON parse\n const serverValues = repoGenerateServerValues(repo);\n const newNodeUnresolved = nodeFromJSON(newVal, newPriority);\n const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);\n const newNode = resolveDeferredValueSnapshot(\n newNodeUnresolved,\n existing,\n serverValues\n );\n\n const writeId = repoGetNextWriteId(repo);\n const events = syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n path,\n newNode,\n writeId,\n true\n );\n eventQueueQueueEvents(repo.eventQueue_, events);\n repo.server_.put(\n path.toString(),\n newNodeUnresolved.val(/*export=*/ true),\n (status, errorReason) => {\n const success = status === 'ok';\n if (!success) {\n warn('set at ' + path + ' failed: ' + status);\n }\n\n const clearEvents = syncTreeAckUserWrite(\n repo.serverSyncTree_,\n writeId,\n !success\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n const affectedPath = repoAbortTransactions(repo, path);\n repoRerunTransactions(repo, affectedPath);\n // We queued the events above, so just flush the queue here\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);\n}\n\nexport function repoUpdate(\n repo: Repo,\n path: Path,\n childrenToMerge: { [k: string]: unknown },\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });\n\n // Start with our existing data and merge each child into it.\n let empty = true;\n const serverValues = repoGenerateServerValues(repo);\n const changedChildren: { [k: string]: Node } = {};\n each(childrenToMerge, (changedKey: string, changedValue: unknown) => {\n empty = false;\n changedChildren[changedKey] = resolveDeferredValueTree(\n pathChild(path, changedKey),\n nodeFromJSON(changedValue),\n repo.serverSyncTree_,\n serverValues\n );\n });\n\n if (!empty) {\n const writeId = repoGetNextWriteId(repo);\n const events = syncTreeApplyUserMerge(\n repo.serverSyncTree_,\n path,\n changedChildren,\n writeId\n );\n eventQueueQueueEvents(repo.eventQueue_, events);\n repo.server_.merge(\n path.toString(),\n childrenToMerge,\n (status, errorReason) => {\n const success = status === 'ok';\n if (!success) {\n warn('update at ' + path + ' failed: ' + status);\n }\n\n const clearEvents = syncTreeAckUserWrite(\n repo.serverSyncTree_,\n writeId,\n !success\n );\n const affectedPath =\n clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n affectedPath,\n clearEvents\n );\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n\n each(childrenToMerge, (changedPath: string) => {\n const affectedPath = repoAbortTransactions(\n repo,\n pathChild(path, changedPath)\n );\n repoRerunTransactions(repo, affectedPath);\n });\n\n // We queued the events above, so just flush the queue here\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);\n } else {\n log(\"update() called with empty data. Don't do anything.\");\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\n }\n}\n\n/**\n * Applies all of the changes stored up in the onDisconnect_ tree.\n */\nfunction repoRunOnDisconnectEvents(repo: Repo): void {\n repoLog(repo, 'onDisconnectEvents');\n\n const serverValues = repoGenerateServerValues(repo);\n const resolvedOnDisconnectTree = newSparseSnapshotTree();\n sparseSnapshotTreeForEachTree(\n repo.onDisconnect_,\n newEmptyPath(),\n (path, node) => {\n const resolved = resolveDeferredValueTree(\n path,\n node,\n repo.serverSyncTree_,\n serverValues\n );\n sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);\n }\n );\n let events: Event[] = [];\n\n sparseSnapshotTreeForEachTree(\n resolvedOnDisconnectTree,\n newEmptyPath(),\n (path, snap) => {\n events = events.concat(\n syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap)\n );\n const affectedPath = repoAbortTransactions(repo, path);\n repoRerunTransactions(repo, affectedPath);\n }\n );\n\n repo.onDisconnect_ = newSparseSnapshotTree();\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);\n}\n\nexport function repoOnDisconnectCancel(\n repo: Repo,\n path: Path,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeForget(repo.onDisconnect_, path);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n });\n}\n\nexport function repoOnDisconnectSet(\n repo: Repo,\n path: Path,\n value: unknown,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n const newNode = nodeFromJSON(value);\n repo.server_.onDisconnectPut(\n path.toString(),\n newNode.val(/*export=*/ true),\n (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoOnDisconnectSetWithPriority(\n repo: Repo,\n path: Path,\n value: unknown,\n priority: unknown,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n const newNode = nodeFromJSON(value, priority);\n repo.server_.onDisconnectPut(\n path.toString(),\n newNode.val(/*export=*/ true),\n (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoOnDisconnectUpdate(\n repo: Repo,\n path: Path,\n childrenToMerge: { [k: string]: unknown },\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n if (isEmpty(childrenToMerge)) {\n log(\"onDisconnect().update() called with empty data. Don't do anything.\");\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\n return;\n }\n\n repo.server_.onDisconnectMerge(\n path.toString(),\n childrenToMerge,\n (status, errorReason) => {\n if (status === 'ok') {\n each(childrenToMerge, (childName: string, childNode: unknown) => {\n const newChildNode = nodeFromJSON(childNode);\n sparseSnapshotTreeRemember(\n repo.onDisconnect_,\n pathChild(path, childName),\n newChildNode\n );\n });\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoAddEventCallbackForQuery(\n repo: Repo,\n query: QueryContext,\n eventRegistration: EventRegistration\n): void {\n let events;\n if (pathGetFront(query._path) === '.info') {\n events = syncTreeAddEventRegistration(\n repo.infoSyncTree_,\n query,\n eventRegistration\n );\n } else {\n events = syncTreeAddEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration\n );\n }\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\n}\n\nexport function repoRemoveEventCallbackForQuery(\n repo: Repo,\n query: QueryContext,\n eventRegistration: EventRegistration\n): void {\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\n // a little bit by handling the return values anyways.\n let events;\n if (pathGetFront(query._path) === '.info') {\n events = syncTreeRemoveEventRegistration(\n repo.infoSyncTree_,\n query,\n eventRegistration\n );\n } else {\n events = syncTreeRemoveEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration\n );\n }\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\n}\n\nexport function repoInterrupt(repo: Repo): void {\n if (repo.persistentConnection_) {\n repo.persistentConnection_.interrupt(INTERRUPT_REASON);\n }\n}\n\nexport function repoResume(repo: Repo): void {\n if (repo.persistentConnection_) {\n repo.persistentConnection_.resume(INTERRUPT_REASON);\n }\n}\n\nexport function repoStats(repo: Repo, showDelta: boolean = false): void {\n if (typeof console === 'undefined') {\n return;\n }\n\n let stats: { [k: string]: unknown };\n if (showDelta) {\n if (!repo.statsListener_) {\n repo.statsListener_ = new StatsListener(repo.stats_);\n }\n stats = repo.statsListener_.get();\n } else {\n stats = repo.stats_.get();\n }\n\n const longestName = Object.keys(stats).reduce(\n (previousValue, currentValue) =>\n Math.max(currentValue.length, previousValue),\n 0\n );\n\n each(stats, (stat: string, value: unknown) => {\n let paddedStat = stat;\n // pad stat names to be the same length (plus 2 extra spaces).\n for (let i = stat.length; i < longestName + 2; i++) {\n paddedStat += ' ';\n }\n console.log(paddedStat + value);\n });\n}\n\nexport function repoStatsIncrementCounter(repo: Repo, metric: string): void {\n repo.stats_.incrementCounter(metric);\n statsReporterIncludeStat(repo.statsReporter_, metric);\n}\n\nfunction repoLog(repo: Repo, ...varArgs: unknown[]): void {\n let prefix = '';\n if (repo.persistentConnection_) {\n prefix = repo.persistentConnection_.id + ':';\n }\n log(prefix, ...varArgs);\n}\n\nexport function repoCallOnCompleteCallback(\n repo: Repo,\n callback: ((status: Error | null, errorReason?: string) => void) | null,\n status: string,\n errorReason?: string | null\n): void {\n if (callback) {\n exceptionGuard(() => {\n if (status === 'ok') {\n callback(null);\n } else {\n const code = (status || 'error').toUpperCase();\n let message = code;\n if (errorReason) {\n message += ': ' + errorReason;\n }\n\n const error = new Error(message);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (error as any).code = code;\n callback(error);\n }\n });\n }\n}\n\n/**\n * Creates a new transaction, adds it to the transactions we're tracking, and\n * sends it to the server if possible.\n *\n * @param path - Path at which to do transaction.\n * @param transactionUpdate - Update callback.\n * @param onComplete - Completion callback.\n * @param unwatcher - Function that will be called when the transaction no longer\n * need data updates for `path`.\n * @param applyLocally - Whether or not to make intermediate results visible\n */\nexport function repoStartTransaction(\n repo: Repo,\n path: Path,\n transactionUpdate: (a: unknown) => unknown,\n onComplete: ((error: Error, committed: boolean, node: Node) => void) | null,\n unwatcher: () => void,\n applyLocally: boolean\n): void {\n repoLog(repo, 'transaction on ' + path);\n\n // Initialize transaction.\n const transaction: Transaction = {\n path,\n update: transactionUpdate,\n onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out\n // which one goes first.\n order: LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n };\n\n // Run transaction initially.\n const currentState = repoGetLatestState(repo, path, undefined);\n transaction.currentInputSnapshot = currentState;\n const newVal = transaction.update(currentState.val());\n if (newVal === undefined) {\n // Abort transaction.\n transaction.unwatcher();\n transaction.currentOutputSnapshotRaw = null;\n transaction.currentOutputSnapshotResolved = null;\n if (transaction.onComplete) {\n transaction.onComplete(null, false, transaction.currentInputSnapshot);\n }\n } else {\n validateFirebaseData(\n 'transaction failed: Data returned ',\n newVal,\n transaction.path\n );\n\n // Mark as run and add to our queue.\n transaction.status = TransactionStatus.RUN;\n const queueNode = treeSubTree(repo.transactionQueueTree_, path);\n const nodeQueue = treeGetValue(queueNode) || [];\n nodeQueue.push(transaction);\n\n treeSetValue(queueNode, nodeQueue);\n\n // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our\n // transaction state, since the user could start new transactions from the\n // event callbacks.\n let priorityForNode;\n if (\n typeof newVal === 'object' &&\n newVal !== null &&\n contains(newVal, '.priority')\n ) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n priorityForNode = safeGet(newVal as any, '.priority');\n assert(\n isValidPriority(priorityForNode),\n 'Invalid priority returned by transaction. ' +\n 'Priority must be a valid string, finite number, server value, or null.'\n );\n } else {\n const currentNode =\n syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||\n ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n\n const serverValues = repoGenerateServerValues(repo);\n const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);\n const newNode = resolveDeferredValueSnapshot(\n newNodeUnresolved,\n currentState,\n serverValues\n );\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = repoGetNextWriteId(repo);\n\n const events = syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n path,\n newNode,\n transaction.currentWriteId,\n transaction.applyLocally\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n }\n}\n\n/**\n * @param excludeSets - A specific set to exclude\n */\nfunction repoGetLatestState(\n repo: Repo,\n path: Path,\n excludeSets?: number[]\n): Node {\n return (\n syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||\n ChildrenNode.EMPTY_NODE\n );\n}\n\n/**\n * Sends any already-run transactions that aren't waiting for outstanding\n * transactions to complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively\n * with a particular transactionQueueTree node to recurse through the tree.\n *\n * @param node - transactionQueueTree node to start at.\n */\nfunction repoSendReadyTransactions(\n repo: Repo,\n node: Tree = repo.transactionQueueTree_\n): void {\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n repoPruneCompletedTransactionsBelowNode(repo, node);\n }\n\n if (treeGetValue(node)) {\n const queue = repoBuildTransactionQueue(repo, node);\n assert(queue.length > 0, 'Sending zero length transaction queue');\n\n const allRun = queue.every(\n (transaction: Transaction) => transaction.status === TransactionStatus.RUN\n );\n\n // If they're all run (and not sent), we can send them. Else, we must wait.\n if (allRun) {\n repoSendTransactionQueue(repo, treeGetPath(node), queue);\n }\n } else if (treeHasChildren(node)) {\n treeForEachChild(node, childNode => {\n repoSendReadyTransactions(repo, childNode);\n });\n }\n}\n\n/**\n * Given a list of run transactions, send them to the server and then handle\n * the result (success or failure).\n *\n * @param path - The location of the queue.\n * @param queue - Queue of transactions under the specified location.\n */\nfunction repoSendTransactionQueue(\n repo: Repo,\n path: Path,\n queue: Transaction[]\n): void {\n // Mark transactions as sent and increment retry count!\n const setsToIgnore = queue.map(txn => {\n return txn.currentWriteId;\n });\n const latestState = repoGetLatestState(repo, path, setsToIgnore);\n let snapToSend = latestState;\n const latestHash = latestState.hash();\n for (let i = 0; i < queue.length; i++) {\n const txn = queue[i];\n assert(\n txn.status === TransactionStatus.RUN,\n 'tryToSendTransactionQueue_: items in queue should all be run.'\n );\n txn.status = TransactionStatus.SENT;\n txn.retryCount++;\n const relativePath = newRelativePath(path, txn.path);\n // If we've gotten to this point, the output snapshot must be defined.\n snapToSend = snapToSend.updateChild(\n relativePath /** @type {!Node} */,\n txn.currentOutputSnapshotRaw\n );\n }\n\n const dataToSend = snapToSend.val(true);\n const pathToSend = path;\n\n // Send the put.\n repo.server_.put(\n pathToSend.toString(),\n dataToSend,\n (status: string) => {\n repoLog(repo, 'transaction put response', {\n path: pathToSend.toString(),\n status\n });\n\n let events: Event[] = [];\n if (status === 'ok') {\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more\n // transactions or sets.\n const callbacks = [];\n for (let i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.COMPLETED;\n events = events.concat(\n syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId)\n );\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this\n // transaction is complete, it should be set\n callbacks.push(() =>\n queue[i].onComplete(\n null,\n true,\n queue[i].currentOutputSnapshotResolved\n )\n );\n }\n queue[i].unwatcher();\n }\n\n // Now remove the completed transactions.\n repoPruneCompletedTransactionsBelowNode(\n repo,\n treeSubTree(repo.transactionQueueTree_, path)\n );\n // There may be pending transactions that we can now send.\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n\n // Finally, trigger onComplete callbacks.\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n } else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (let i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n } else {\n queue[i].status = TransactionStatus.RUN;\n }\n }\n } else {\n warn(\n 'transaction at ' + pathToSend.toString() + ' failed: ' + status\n );\n for (let i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n queue[i].abortReason = status;\n }\n }\n\n repoRerunTransactions(repo, path);\n }\n },\n latestHash\n );\n}\n\n/**\n * Finds all transactions dependent on the data at changedPath and reruns them.\n *\n * Should be called any time cached data changes.\n *\n * Return the highest path that was affected by rerunning transactions. This\n * is the path at which events need to be raised for.\n *\n * @param changedPath - The path in mergedData that changed.\n * @returns The rootmost path that was affected by rerunning transactions.\n */\nfunction repoRerunTransactions(repo: Repo, changedPath: Path): Path {\n const rootMostTransactionNode = repoGetAncestorTransactionNode(\n repo,\n changedPath\n );\n const path = treeGetPath(rootMostTransactionNode);\n\n const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);\n repoRerunTransactionQueue(repo, queue, path);\n\n return path;\n}\n\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted\n * transactions and whatnot).\n *\n * @param queue - The queue of transactions to run.\n * @param path - The path the queue is for.\n */\nfunction repoRerunTransactionQueue(\n repo: Repo,\n queue: Transaction[],\n path: Path\n): void {\n if (queue.length === 0) {\n return; // Nothing to do!\n }\n\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more transactions or\n // sets.\n const callbacks = [];\n let events: Event[] = [];\n // Ignore all of the sets we're going to re-run.\n const txnsToRerun = queue.filter(q => {\n return q.status === TransactionStatus.RUN;\n });\n const setsToIgnore = txnsToRerun.map(q => {\n return q.currentWriteId;\n });\n for (let i = 0; i < queue.length; i++) {\n const transaction = queue[i];\n const relativePath = newRelativePath(path, transaction.path);\n let abortTransaction = false,\n abortReason;\n assert(\n relativePath !== null,\n 'rerunTransactionsUnderNode_: relativePath should not be null.'\n );\n\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n } else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n } else {\n // This code reruns a transaction\n const currentNode = repoGetLatestState(\n repo,\n transaction.path,\n setsToIgnore\n );\n transaction.currentInputSnapshot = currentNode;\n const newData = queue[i].update(currentNode.val());\n if (newData !== undefined) {\n validateFirebaseData(\n 'transaction failed: Data returned ',\n newData,\n transaction.path\n );\n let newDataNode = nodeFromJSON(newData);\n const hasExplicitPriority =\n typeof newData === 'object' &&\n newData != null &&\n contains(newData, '.priority');\n if (!hasExplicitPriority) {\n // Keep the old priority if there wasn't a priority explicitly specified.\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n }\n\n const oldWriteId = transaction.currentWriteId;\n const serverValues = repoGenerateServerValues(repo);\n const newNodeResolved = resolveDeferredValueSnapshot(\n newDataNode,\n currentNode,\n serverValues\n );\n\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = repoGetNextWriteId(repo);\n // Mutates setsToIgnore in place\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(\n syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n transaction.path,\n newNodeResolved,\n transaction.currentWriteId,\n transaction.applyLocally\n )\n );\n events = events.concat(\n syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true)\n );\n } else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n }\n }\n }\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n events = [];\n if (abortTransaction) {\n // Abort.\n queue[i].status = TransactionStatus.COMPLETED;\n\n // Removing a listener can trigger pruning which can muck with\n // mergedData/visibleData (as it prunes data). So defer the unwatcher\n // until we're done.\n (function (unwatcher) {\n setTimeout(unwatcher, Math.floor(0));\n })(queue[i].unwatcher);\n\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n callbacks.push(() =>\n queue[i].onComplete(null, false, queue[i].currentInputSnapshot)\n );\n } else {\n callbacks.push(() =>\n queue[i].onComplete(new Error(abortReason), false, null)\n );\n }\n }\n }\n }\n\n // Clean up completed transactions.\n repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);\n\n // Now fire callbacks, now that we're in a good, known state.\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n\n // Try to send the transaction result to the server.\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n}\n\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending\n * transaction on it, or just returns the node for the given path if there are\n * no pending transactions on any ancestor.\n *\n * @param path - The location to start at.\n * @returns The rootmost node with a transaction.\n */\nfunction repoGetAncestorTransactionNode(\n repo: Repo,\n path: Path\n): Tree {\n let front;\n\n // Start at the root and walk deeper into the tree towards path until we\n // find a node with pending transactions.\n let transactionNode = repo.transactionQueueTree_;\n front = pathGetFront(path);\n while (front !== null && treeGetValue(transactionNode) === undefined) {\n transactionNode = treeSubTree(transactionNode, front);\n path = pathPopFront(path);\n front = pathGetFront(path);\n }\n\n return transactionNode;\n}\n\n/**\n * Builds the queue of all transactions at or below the specified\n * transactionNode.\n *\n * @param transactionNode\n * @returns The generated queue.\n */\nfunction repoBuildTransactionQueue(\n repo: Repo,\n transactionNode: Tree\n): Transaction[] {\n // Walk any child transaction queues and aggregate them into a single queue.\n const transactionQueue: Transaction[] = [];\n repoAggregateTransactionQueuesForNode(\n repo,\n transactionNode,\n transactionQueue\n );\n\n // Sort them by the order the transactions were created.\n transactionQueue.sort((a, b) => a.order - b.order);\n\n return transactionQueue;\n}\n\nfunction repoAggregateTransactionQueuesForNode(\n repo: Repo,\n node: Tree,\n queue: Transaction[]\n): void {\n const nodeQueue = treeGetValue(node);\n if (nodeQueue) {\n for (let i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n\n treeForEachChild(node, child => {\n repoAggregateTransactionQueuesForNode(repo, child, queue);\n });\n}\n\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n */\nfunction repoPruneCompletedTransactionsBelowNode(\n repo: Repo,\n node: Tree\n): void {\n const queue = treeGetValue(node);\n if (queue) {\n let to = 0;\n for (let from = 0; from < queue.length; from++) {\n if (queue[from].status !== TransactionStatus.COMPLETED) {\n queue[to] = queue[from];\n to++;\n }\n }\n queue.length = to;\n treeSetValue(node, queue.length > 0 ? queue : undefined);\n }\n\n treeForEachChild(node, childNode => {\n repoPruneCompletedTransactionsBelowNode(repo, childNode);\n });\n}\n\n/**\n * Aborts all transactions on ancestors or descendants of the specified path.\n * Called when doing a set() or update() since we consider them incompatible\n * with transactions.\n *\n * @param path - Path for which we want to abort related transactions.\n */\nfunction repoAbortTransactions(repo: Repo, path: Path): Path {\n const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));\n\n const transactionNode = treeSubTree(repo.transactionQueueTree_, path);\n\n treeForEachAncestor(transactionNode, (node: Tree) => {\n repoAbortTransactionsOnNode(repo, node);\n });\n\n repoAbortTransactionsOnNode(repo, transactionNode);\n\n treeForEachDescendant(transactionNode, (node: Tree) => {\n repoAbortTransactionsOnNode(repo, node);\n });\n\n return affectedPath;\n}\n\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param node - Node to abort transactions for.\n */\nfunction repoAbortTransactionsOnNode(\n repo: Repo,\n node: Tree\n): void {\n const queue = treeGetValue(node);\n if (queue) {\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more transactions\n // or sets.\n const callbacks = [];\n\n // Go through queue. Any already-sent transactions must be marked for\n // abort, while the unsent ones can be immediately aborted and removed.\n let events: Event[] = [];\n let lastSent = -1;\n for (let i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n // Already marked. No action needed.\n } else if (queue[i].status === TransactionStatus.SENT) {\n assert(\n lastSent === i - 1,\n 'All SENT items should be at beginning of queue.'\n );\n lastSent = i;\n // Mark transaction for abort when it comes back.\n queue[i].status = TransactionStatus.SENT_NEEDS_ABORT;\n queue[i].abortReason = 'set';\n } else {\n assert(\n queue[i].status === TransactionStatus.RUN,\n 'Unexpected transaction status in abort'\n );\n // We can abort it immediately.\n queue[i].unwatcher();\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n queue[i].currentWriteId,\n true\n )\n );\n if (queue[i].onComplete) {\n callbacks.push(\n queue[i].onComplete.bind(null, new Error('set'), false, null)\n );\n }\n }\n }\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n treeSetValue(node, undefined);\n } else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n\n // Now fire the callbacks.\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n treeGetPath(node),\n events\n );\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../../RepoInfo';\nimport { Path } from '../Path';\nimport { warnIfPageIsSecure, warn, fatal } from '../util';\n\nfunction decodePath(pathString: string): string {\n let pathStringDecoded = '';\n const pieces = pathString.split('/');\n for (let i = 0; i < pieces.length; i++) {\n if (pieces[i].length > 0) {\n let piece = pieces[i];\n try {\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\n } catch (e) {}\n pathStringDecoded += '/' + piece;\n }\n }\n return pathStringDecoded;\n}\n\n/**\n * @returns key value hash\n */\nfunction decodeQuery(queryString: string): { [key: string]: string } {\n const results = {};\n if (queryString.charAt(0) === '?') {\n queryString = queryString.substring(1);\n }\n for (const segment of queryString.split('&')) {\n if (segment.length === 0) {\n continue;\n }\n const kv = segment.split('=');\n if (kv.length === 2) {\n results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\n } else {\n warn(`Invalid query segment '${segment}' in query '${queryString}'`);\n }\n }\n return results;\n}\n\nexport const parseRepoInfo = function (\n dataURL: string,\n nodeAdmin: boolean\n): { repoInfo: RepoInfo; path: Path } {\n const parsedUrl = parseDatabaseURL(dataURL),\n namespace = parsedUrl.namespace;\n\n if (parsedUrl.domain === 'firebase.com') {\n fatal(\n parsedUrl.host +\n ' is no longer supported. ' +\n 'Please use .firebaseio.com instead'\n );\n }\n\n // Catch common error of uninitialized namespace value.\n if (\n (!namespace || namespace === 'undefined') &&\n parsedUrl.domain !== 'localhost'\n ) {\n fatal(\n 'Cannot parse Firebase url. Please use https://.firebaseio.com'\n );\n }\n\n if (!parsedUrl.secure) {\n warnIfPageIsSecure();\n }\n\n const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\n\n return {\n repoInfo: new RepoInfo(\n parsedUrl.host,\n parsedUrl.secure,\n namespace,\n webSocketOnly,\n nodeAdmin,\n /*persistenceKey=*/ '',\n /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain\n ),\n path: new Path(parsedUrl.pathString)\n };\n};\n\nexport const parseDatabaseURL = function (dataURL: string): {\n host: string;\n port: number;\n domain: string;\n subdomain: string;\n secure: boolean;\n scheme: string;\n pathString: string;\n namespace: string;\n} {\n // Default to empty strings in the event of a malformed string.\n let host = '',\n domain = '',\n subdomain = '',\n pathString = '',\n namespace = '';\n\n // Always default to SSL, unless otherwise specified.\n let secure = true,\n scheme = 'https',\n port = 443;\n\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\n if (typeof dataURL === 'string') {\n // Parse scheme.\n let colonInd = dataURL.indexOf('//');\n if (colonInd >= 0) {\n scheme = dataURL.substring(0, colonInd - 1);\n dataURL = dataURL.substring(colonInd + 2);\n }\n\n // Parse host, path, and query string.\n let slashInd = dataURL.indexOf('/');\n if (slashInd === -1) {\n slashInd = dataURL.length;\n }\n let questionMarkInd = dataURL.indexOf('?');\n if (questionMarkInd === -1) {\n questionMarkInd = dataURL.length;\n }\n host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));\n if (slashInd < questionMarkInd) {\n // For pathString, questionMarkInd will always come after slashInd\n pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));\n }\n const queryParams = decodeQuery(\n dataURL.substring(Math.min(dataURL.length, questionMarkInd))\n );\n\n // If we have a port, use scheme for determining if it's secure.\n colonInd = host.indexOf(':');\n if (colonInd >= 0) {\n secure = scheme === 'https' || scheme === 'wss';\n port = parseInt(host.substring(colonInd + 1), 10);\n } else {\n colonInd = host.length;\n }\n\n const hostWithoutPort = host.slice(0, colonInd);\n if (hostWithoutPort.toLowerCase() === 'localhost') {\n domain = 'localhost';\n } else if (hostWithoutPort.split('.').length <= 2) {\n domain = hostWithoutPort;\n } else {\n // Interpret the subdomain of a 3 or more component URL as the namespace name.\n const dotInd = host.indexOf('.');\n subdomain = host.substring(0, dotInd).toLowerCase();\n domain = host.substring(dotInd + 1);\n // Normalize namespaces to lowercase to share storage / connection.\n namespace = subdomain;\n }\n // Always treat the value of the `ns` as the namespace name if it is present.\n if ('ns' in queryParams) {\n namespace = queryParams['ns'];\n }\n }\n\n return {\n host,\n port,\n domain,\n subdomain,\n secure,\n scheme,\n pathString,\n namespace\n };\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport {\n tryParseInt,\n MAX_NAME,\n MIN_NAME,\n INTEGER_32_MIN,\n INTEGER_32_MAX\n} from '../util/util';\n\n// Modeled after base64 web-safe chars, but ordered by ASCII.\nconst PUSH_CHARS =\n '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n\nconst MIN_PUSH_CHAR = '-';\n\nconst MAX_PUSH_CHAR = 'z';\n\nconst MAX_KEY_LEN = 786;\n\n/**\n * Fancy ID generator that creates 20-character string identifiers with the\n * following properties:\n *\n * 1. They're based on timestamp so that they sort *after* any existing ids.\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\n * collide with other clients' IDs.\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\n * that will sort properly).\n * 4. They're monotonically increasing. Even if you generate more than one in\n * the same timestamp, the latter ones will sort after the former ones. We do\n * this by using the previous random bits but \"incrementing\" them by 1 (only\n * in the case of a timestamp collision).\n */\nexport const nextPushId = (function () {\n // Timestamp of last push, used to prevent local collisions if you push twice\n // in one ms.\n let lastPushTime = 0;\n\n // We generate 72-bits of randomness which get turned into 12 characters and\n // appended to the timestamp to prevent collisions with other clients. We\n // store the last characters we generated because in the event of a collision,\n // we'll use those same characters except \"incremented\" by one.\n const lastRandChars: number[] = [];\n\n return function (now: number) {\n const duplicateTime = now === lastPushTime;\n lastPushTime = now;\n\n let i;\n const timeStampChars = new Array(8);\n for (i = 7; i >= 0; i--) {\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\n // NOTE: Can't use << here because javascript will convert to int and lose\n // the upper bits.\n now = Math.floor(now / 64);\n }\n assert(now === 0, 'Cannot push at time == 0');\n\n let id = timeStampChars.join('');\n\n if (!duplicateTime) {\n for (i = 0; i < 12; i++) {\n lastRandChars[i] = Math.floor(Math.random() * 64);\n }\n } else {\n // If the timestamp hasn't changed since last push, use the same random\n // number, except incremented by 1.\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\n lastRandChars[i] = 0;\n }\n lastRandChars[i]++;\n }\n for (i = 0; i < 12; i++) {\n id += PUSH_CHARS.charAt(lastRandChars[i]);\n }\n assert(id.length === 20, 'nextPushId: Length should be 20.');\n\n return id;\n };\n})();\n\nexport const successor = function (key: string) {\n if (key === '' + INTEGER_32_MAX) {\n // See https://firebase.google.com/docs/database/web/lists-of-data#data-order\n return MIN_PUSH_CHAR;\n }\n const keyAsInt: number = tryParseInt(key);\n if (keyAsInt != null) {\n return '' + (keyAsInt + 1);\n }\n const next = new Array(key.length);\n\n for (let i = 0; i < next.length; i++) {\n next[i] = key.charAt(i);\n }\n\n if (next.length < MAX_KEY_LEN) {\n next.push(MIN_PUSH_CHAR);\n return next.join('');\n }\n\n let i = next.length - 1;\n\n while (i >= 0 && next[i] === MAX_PUSH_CHAR) {\n i--;\n }\n\n // `successor` was called on the largest possible key, so return the\n // MAX_NAME, which sorts larger than all keys.\n if (i === -1) {\n return MAX_NAME;\n }\n\n const source = next[i];\n const sourcePlusOne = PUSH_CHARS.charAt(PUSH_CHARS.indexOf(source) + 1);\n next[i] = sourcePlusOne;\n\n return next.slice(0, i + 1).join('');\n};\n\n// `key` is assumed to be non-empty.\nexport const predecessor = function (key: string) {\n if (key === '' + INTEGER_32_MIN) {\n return MIN_NAME;\n }\n const keyAsInt: number = tryParseInt(key);\n if (keyAsInt != null) {\n return '' + (keyAsInt - 1);\n }\n const next = new Array(key.length);\n for (let i = 0; i < next.length; i++) {\n next[i] = key.charAt(i);\n }\n // If `key` ends in `MIN_PUSH_CHAR`, the largest key lexicographically\n // smaller than `key`, is `key[0:key.length - 1]`. The next key smaller\n // than that, `predecessor(predecessor(key))`, is\n //\n // `key[0:key.length - 2] + (key[key.length - 1] - 1) + \\\n // { MAX_PUSH_CHAR repeated MAX_KEY_LEN - (key.length - 1) times }\n //\n // analogous to increment/decrement for base-10 integers.\n //\n // This works because lexicographic comparison works character-by-character,\n // using length as a tie-breaker if one key is a prefix of the other.\n if (next[next.length - 1] === MIN_PUSH_CHAR) {\n if (next.length === 1) {\n // See https://firebase.google.com/docs/database/web/lists-of-data#orderbykey\n return '' + INTEGER_32_MAX;\n }\n delete next[next.length - 1];\n return next.join('');\n }\n // Replace the last character with it's immediate predecessor, and\n // fill the suffix of the key with MAX_PUSH_CHAR. This is the\n // lexicographically largest possible key smaller than `key`.\n next[next.length - 1] = PUSH_CHARS.charAt(\n PUSH_CHARS.indexOf(next[next.length - 1]) - 1\n );\n return next.join('') + MAX_PUSH_CHAR.repeat(MAX_KEY_LEN - next.length);\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { stringify } from '@firebase/util';\n\nimport { DataSnapshot as ExpDataSnapshot } from '../../api/Reference_impl';\nimport { Path } from '../util/Path';\n\nimport { EventRegistration } from './EventRegistration';\n\n/**\n * Encapsulates the data needed to raise an event\n * @interface\n */\nexport interface Event {\n getPath(): Path;\n\n getEventType(): string;\n\n getEventRunner(): () => void;\n\n toString(): string;\n}\n\n/**\n * One of the following strings: \"value\", \"child_added\", \"child_changed\",\n * \"child_removed\", or \"child_moved.\"\n */\nexport type EventType =\n | 'value'\n | 'child_added'\n | 'child_changed'\n | 'child_moved'\n | 'child_removed';\n\n/**\n * Encapsulates the data needed to raise an event\n */\nexport class DataEvent implements Event {\n /**\n * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed\n * @param eventRegistration - The function to call to with the event data. User provided\n * @param snapshot - The data backing the event\n * @param prevName - Optional, the name of the previous child for child_* events.\n */\n constructor(\n public eventType: EventType,\n public eventRegistration: EventRegistration,\n public snapshot: ExpDataSnapshot,\n public prevName?: string | null\n ) {}\n getPath(): Path {\n const ref = this.snapshot.ref;\n if (this.eventType === 'value') {\n return ref._path;\n } else {\n return ref.parent._path;\n }\n }\n getEventType(): string {\n return this.eventType;\n }\n getEventRunner(): () => void {\n return this.eventRegistration.getEventRunner(this);\n }\n toString(): string {\n return (\n this.getPath().toString() +\n ':' +\n this.eventType +\n ':' +\n stringify(this.snapshot.exportVal())\n );\n }\n}\n\nexport class CancelEvent implements Event {\n constructor(\n public eventRegistration: EventRegistration,\n public error: Error,\n public path: Path\n ) {}\n getPath(): Path {\n return this.path;\n }\n getEventType(): string {\n return 'cancel';\n }\n getEventRunner(): () => void {\n return this.eventRegistration.getEventRunner(this);\n }\n toString(): string {\n return this.path.toString() + ':cancel';\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { DataSnapshot } from '../../api/Reference_impl';\nimport { Repo } from '../Repo';\nimport { Path } from '../util/Path';\n\nimport { Change } from './Change';\nimport { CancelEvent, Event } from './Event';\nimport { QueryParams } from './QueryParams';\n\n/**\n * A user callback. Callbacks issues from the Legacy SDK maintain references\n * to the original user-issued callbacks, which allows equality\n * comparison by reference even though this callbacks are wrapped before\n * they can be passed to the firebase@exp SDK.\n *\n * @internal\n */\nexport interface UserCallback {\n (dataSnapshot: DataSnapshot, previousChildName?: string | null): unknown;\n userCallback?: unknown;\n context?: object | null;\n}\n\n/**\n * A wrapper class that converts events from the database@exp SDK to the legacy\n * Database SDK. Events are not converted directly as event registration relies\n * on reference comparison of the original user callback (see `matches()`) and\n * relies on equality of the legacy SDK's `context` object.\n */\nexport class CallbackContext {\n constructor(\n private readonly snapshotCallback: UserCallback,\n private readonly cancelCallback?: (error: Error) => unknown\n ) {}\n\n onValue(\n expDataSnapshot: DataSnapshot,\n previousChildName?: string | null\n ): void {\n this.snapshotCallback.call(null, expDataSnapshot, previousChildName);\n }\n\n onCancel(error: Error): void {\n assert(\n this.hasCancelCallback,\n 'Raising a cancel event on a listener with no cancel callback'\n );\n return this.cancelCallback.call(null, error);\n }\n\n get hasCancelCallback(): boolean {\n return !!this.cancelCallback;\n }\n\n matches(other: CallbackContext): boolean {\n return (\n this.snapshotCallback === other.snapshotCallback ||\n (this.snapshotCallback.userCallback !== undefined &&\n this.snapshotCallback.userCallback ===\n other.snapshotCallback.userCallback &&\n this.snapshotCallback.context === other.snapshotCallback.context)\n );\n }\n}\n\nexport interface QueryContext {\n readonly _queryIdentifier: string;\n readonly _queryObject: object;\n readonly _repo: Repo;\n readonly _path: Path;\n readonly _queryParams: QueryParams;\n}\n\n/**\n * An EventRegistration is basically an event type ('value', 'child_added', etc.) and a callback\n * to be notified of that type of event.\n *\n * That said, it can also contain a cancel callback to be notified if the event is canceled. And\n * currently, this code is organized around the idea that you would register multiple child_ callbacks\n * together, as a single EventRegistration. Though currently we don't do that.\n */\nexport interface EventRegistration {\n /**\n * True if this container has a callback to trigger for this event type\n */\n respondsTo(eventType: string): boolean;\n\n createEvent(change: Change, query: QueryContext): Event;\n\n /**\n * Given event data, return a function to trigger the user's callback\n */\n getEventRunner(eventData: Event): () => void;\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null;\n\n matches(other: EventRegistration): boolean;\n\n /**\n * False basically means this is a \"dummy\" callback container being used as a sentinel\n * to remove all callback containers of a particular type. (e.g. if the user does\n * ref.off('value') without specifying a specific callback).\n *\n * (TODO: Rework this, since it's hacky)\n *\n */\n hasAnyCallback(): boolean;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from '@firebase/util';\n\nimport {\n Repo,\n repoOnDisconnectCancel,\n repoOnDisconnectSet,\n repoOnDisconnectSetWithPriority,\n repoOnDisconnectUpdate\n} from '../core/Repo';\nimport { Path } from '../core/util/Path';\nimport {\n validateFirebaseDataArg,\n validateFirebaseMergeDataArg,\n validatePriority,\n validateWritablePath\n} from '../core/util/validation';\n\n/**\n * The `onDisconnect` class allows you to write or clear data when your client\n * disconnects from the Database server. These updates occur whether your\n * client disconnects cleanly or not, so you can rely on them to clean up data\n * even if a connection is dropped or a client crashes.\n *\n * The `onDisconnect` class is most commonly used to manage presence in\n * applications where it is useful to detect how many clients are connected and\n * when other clients disconnect. See\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information.\n *\n * To avoid problems when a connection is dropped before the requests can be\n * transferred to the Database server, these functions should be called before\n * writing any data.\n *\n * Note that `onDisconnect` operations are only triggered once. If you want an\n * operation to occur each time a disconnect occurs, you'll need to re-establish\n * the `onDisconnect` operations each time you reconnect.\n */\nexport class OnDisconnect {\n /** @hideconstructor */\n constructor(private _repo: Repo, private _path: Path) {}\n\n /**\n * Cancels all previously queued `onDisconnect()` set or update events for this\n * location and all children.\n *\n * If a write has been queued for this location via a `set()` or `update()` at a\n * parent location, the write at this location will be canceled, though writes\n * to sibling locations will still occur.\n *\n * @returns Resolves when synchronization to the server is complete.\n */\n cancel(): Promise {\n const deferred = new Deferred();\n repoOnDisconnectCancel(\n this._repo,\n this._path,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is deleted when the client is disconnected\n * (due to closing the browser, navigating to a new page, or network issues).\n *\n * @returns Resolves when synchronization to the server is complete.\n */\n remove(): Promise {\n validateWritablePath('OnDisconnect.remove', this._path);\n const deferred = new Deferred();\n repoOnDisconnectSet(\n this._repo,\n this._path,\n null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is set to the specified value when the\n * client is disconnected (due to closing the browser, navigating to a new page,\n * or network issues).\n *\n * `set()` is especially useful for implementing \"presence\" systems, where a\n * value should be changed or cleared when a user disconnects so that they\n * appear \"offline\" to other users. See\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information.\n *\n * Note that `onDisconnect` operations are only triggered once. If you want an\n * operation to occur each time a disconnect occurs, you'll need to re-establish\n * the `onDisconnect` operations each time.\n *\n * @param value - The value to be written to this location on disconnect (can\n * be an object, array, string, number, boolean, or null).\n * @returns Resolves when synchronization to the Database is complete.\n */\n set(value: unknown): Promise {\n validateWritablePath('OnDisconnect.set', this._path);\n validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);\n const deferred = new Deferred();\n repoOnDisconnectSet(\n this._repo,\n this._path,\n value,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is set to the specified value and priority\n * when the client is disconnected (due to closing the browser, navigating to a\n * new page, or network issues).\n *\n * @param value - The value to be written to this location on disconnect (can\n * be an object, array, string, number, boolean, or null).\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when synchronization to the Database is complete.\n */\n setWithPriority(\n value: unknown,\n priority: number | string | null\n ): Promise {\n validateWritablePath('OnDisconnect.setWithPriority', this._path);\n validateFirebaseDataArg(\n 'OnDisconnect.setWithPriority',\n value,\n this._path,\n false\n );\n validatePriority('OnDisconnect.setWithPriority', priority, false);\n\n const deferred = new Deferred();\n repoOnDisconnectSetWithPriority(\n this._repo,\n this._path,\n value,\n priority,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Writes multiple values at this location when the client is disconnected (due\n * to closing the browser, navigating to a new page, or network issues).\n *\n * The `values` argument contains multiple property-value pairs that will be\n * written to the Database together. Each child property can either be a simple\n * property (for example, \"name\") or a relative path (for example, \"name/first\")\n * from the current location to the data to update.\n *\n * As opposed to the `set()` method, `update()` can be use to selectively update\n * only the referenced properties at the current location (instead of replacing\n * all the child properties at the current location).\n *\n * @param values - Object containing multiple values.\n * @returns Resolves when synchronization to the Database is complete.\n */\n update(values: object): Promise {\n validateWritablePath('OnDisconnect.update', this._path);\n validateFirebaseMergeDataArg(\n 'OnDisconnect.update',\n values,\n this._path,\n false\n );\n const deferred = new Deferred();\n repoOnDisconnectUpdate(\n this._repo,\n this._path,\n values as Record,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, getModularInstance, Deferred } from '@firebase/util';\n\nimport {\n Repo,\n repoAddEventCallbackForQuery,\n repoGetValue,\n repoRemoveEventCallbackForQuery,\n repoServerTime,\n repoSetWithPriority,\n repoUpdate\n} from '../core/Repo';\nimport { ChildrenNode } from '../core/snap/ChildrenNode';\nimport { Index } from '../core/snap/indexes/Index';\nimport { KEY_INDEX } from '../core/snap/indexes/KeyIndex';\nimport { PathIndex } from '../core/snap/indexes/PathIndex';\nimport { PRIORITY_INDEX } from '../core/snap/indexes/PriorityIndex';\nimport { VALUE_INDEX } from '../core/snap/indexes/ValueIndex';\nimport { Node } from '../core/snap/Node';\nimport { syncPointSetReferenceConstructor } from '../core/SyncPoint';\nimport { syncTreeSetReferenceConstructor } from '../core/SyncTree';\nimport { parseRepoInfo } from '../core/util/libs/parser';\nimport { nextPushId } from '../core/util/NextPushId';\nimport {\n Path,\n pathEquals,\n pathGetBack,\n pathGetFront,\n pathChild,\n pathParent,\n pathToUrlEncodedString,\n pathIsEmpty\n} from '../core/util/Path';\nimport {\n fatal,\n MAX_NAME,\n MIN_NAME,\n ObjectToUniqueKey\n} from '../core/util/util';\nimport {\n isValidPriority,\n validateFirebaseDataArg,\n validateFirebaseMergeDataArg,\n validateKey,\n validatePathString,\n validatePriority,\n validateRootPathString,\n validateUrl,\n validateWritablePath\n} from '../core/util/validation';\nimport { Change } from '../core/view/Change';\nimport { CancelEvent, DataEvent, EventType } from '../core/view/Event';\nimport {\n CallbackContext,\n EventRegistration,\n QueryContext,\n UserCallback\n} from '../core/view/EventRegistration';\nimport {\n QueryParams,\n queryParamsEndAt,\n queryParamsEndBefore,\n queryParamsGetQueryObject,\n queryParamsLimitToFirst,\n queryParamsLimitToLast,\n queryParamsOrderBy,\n queryParamsStartAfter,\n queryParamsStartAt\n} from '../core/view/QueryParams';\n\nimport { Database } from './Database';\nimport { OnDisconnect } from './OnDisconnect';\nimport {\n ListenOptions,\n Query as Query,\n DatabaseReference,\n Unsubscribe,\n ThenableReference\n} from './Reference';\n\n/**\n * @internal\n */\nexport class QueryImpl implements Query, QueryContext {\n /**\n * @hideconstructor\n */\n constructor(\n readonly _repo: Repo,\n readonly _path: Path,\n readonly _queryParams: QueryParams,\n readonly _orderByCalled: boolean\n ) {}\n\n get key(): string | null {\n if (pathIsEmpty(this._path)) {\n return null;\n } else {\n return pathGetBack(this._path);\n }\n }\n\n get ref(): DatabaseReference {\n return new ReferenceImpl(this._repo, this._path);\n }\n\n get _queryIdentifier(): string {\n const obj = queryParamsGetQueryObject(this._queryParams);\n const id = ObjectToUniqueKey(obj);\n return id === '{}' ? 'default' : id;\n }\n\n /**\n * An object representation of the query parameters used by this Query.\n */\n get _queryObject(): object {\n return queryParamsGetQueryObject(this._queryParams);\n }\n\n isEqual(other: QueryImpl | null): boolean {\n other = getModularInstance(other);\n if (!(other instanceof QueryImpl)) {\n return false;\n }\n\n const sameRepo = this._repo === other._repo;\n const samePath = pathEquals(this._path, other._path);\n const sameQueryIdentifier =\n this._queryIdentifier === other._queryIdentifier;\n\n return sameRepo && samePath && sameQueryIdentifier;\n }\n\n toJSON(): string {\n return this.toString();\n }\n\n toString(): string {\n return this._repo.toString() + pathToUrlEncodedString(this._path);\n }\n}\n\n/**\n * Validates that no other order by call has been made\n */\nfunction validateNoPreviousOrderByCall(query: QueryImpl, fnName: string) {\n if (query._orderByCalled === true) {\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\n }\n}\n\n/**\n * Validates start/end values for queries.\n */\nfunction validateQueryEndpoints(params: QueryParams) {\n let startNode = null;\n let endNode = null;\n if (params.hasStart()) {\n startNode = params.getIndexStartValue();\n }\n if (params.hasEnd()) {\n endNode = params.getIndexEndValue();\n }\n\n if (params.getIndex() === KEY_INDEX) {\n const tooManyArgsError =\n 'Query: When ordering by key, you may only pass one argument to ' +\n 'startAt(), endAt(), or equalTo().';\n const wrongArgTypeError =\n 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +\n 'endAt(), endBefore(), or equalTo() must be a string.';\n if (params.hasStart()) {\n const startName = params.getIndexStartName();\n if (startName !== MIN_NAME) {\n throw new Error(tooManyArgsError);\n } else if (typeof startNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n if (params.hasEnd()) {\n const endName = params.getIndexEndName();\n if (endName !== MAX_NAME) {\n throw new Error(tooManyArgsError);\n } else if (typeof endNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n } else if (params.getIndex() === PRIORITY_INDEX) {\n if (\n (startNode != null && !isValidPriority(startNode)) ||\n (endNode != null && !isValidPriority(endNode))\n ) {\n throw new Error(\n 'Query: When ordering by priority, the first argument passed to startAt(), ' +\n 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +\n '(null, a number, or a string).'\n );\n }\n } else {\n assert(\n params.getIndex() instanceof PathIndex ||\n params.getIndex() === VALUE_INDEX,\n 'unknown index type.'\n );\n if (\n (startNode != null && typeof startNode === 'object') ||\n (endNode != null && typeof endNode === 'object')\n ) {\n throw new Error(\n 'Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +\n 'equalTo() cannot be an object.'\n );\n }\n }\n}\n\n/**\n * Validates that limit* has been called with the correct combination of parameters\n */\nfunction validateLimit(params: QueryParams) {\n if (\n params.hasStart() &&\n params.hasEnd() &&\n params.hasLimit() &&\n !params.hasAnchoredLimit()\n ) {\n throw new Error(\n \"Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use \" +\n 'limitToFirst() or limitToLast() instead.'\n );\n }\n}\n/**\n * @internal\n */\nexport class ReferenceImpl extends QueryImpl implements DatabaseReference {\n /** @hideconstructor */\n constructor(repo: Repo, path: Path) {\n super(repo, path, new QueryParams(), false);\n }\n\n get parent(): ReferenceImpl | null {\n const parentPath = pathParent(this._path);\n return parentPath === null\n ? null\n : new ReferenceImpl(this._repo, parentPath);\n }\n\n get root(): ReferenceImpl {\n let ref: ReferenceImpl = this;\n while (ref.parent !== null) {\n ref = ref.parent;\n }\n return ref;\n }\n}\n\n/**\n * A `DataSnapshot` contains data from a Database location.\n *\n * Any time you read data from the Database, you receive the data as a\n * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach\n * with `on()` or `once()`. You can extract the contents of the snapshot as a\n * JavaScript object by calling the `val()` method. Alternatively, you can\n * traverse into the snapshot by calling `child()` to return child snapshots\n * (which you could then call `val()` on).\n *\n * A `DataSnapshot` is an efficiently generated, immutable copy of the data at\n * a Database location. It cannot be modified and will never change (to modify\n * data, you always call the `set()` method on a `Reference` directly).\n */\nexport class DataSnapshot {\n /**\n * @param _node - A SnapshotNode to wrap.\n * @param ref - The location this snapshot came from.\n * @param _index - The iteration order for this snapshot\n * @hideconstructor\n */\n constructor(\n readonly _node: Node,\n /**\n * The location of this DataSnapshot.\n */\n readonly ref: DatabaseReference,\n readonly _index: Index\n ) {}\n\n /**\n * Gets the priority value of the data in this `DataSnapshot`.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}\n * ).\n */\n get priority(): string | number | null {\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\n return this._node.getPriority().val() as string | number | null;\n }\n\n /**\n * The key (last part of the path) of the location of this `DataSnapshot`.\n *\n * The last token in a Database location is considered its key. For example,\n * \"ada\" is the key for the /users/ada/ node. Accessing the key on any\n * `DataSnapshot` will return the key for the location that generated it.\n * However, accessing the key on the root URL of a Database will return\n * `null`.\n */\n get key(): string | null {\n return this.ref.key;\n }\n\n /** Returns the number of child properties of this `DataSnapshot`. */\n get size(): number {\n return this._node.numChildren();\n }\n\n /**\n * Gets another `DataSnapshot` for the location at the specified relative path.\n *\n * Passing a relative path to the `child()` method of a DataSnapshot returns\n * another `DataSnapshot` for the location at the specified relative path. The\n * relative path can either be a simple child name (for example, \"ada\") or a\n * deeper, slash-separated path (for example, \"ada/name/first\"). If the child\n * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`\n * whose value is `null`) is returned.\n *\n * @param path - A relative path to the location of child data.\n */\n child(path: string): DataSnapshot {\n const childPath = new Path(path);\n const childRef = child(this.ref, path);\n return new DataSnapshot(\n this._node.getChild(childPath),\n childRef,\n PRIORITY_INDEX\n );\n }\n /**\n * Returns true if this `DataSnapshot` contains any data. It is slightly more\n * efficient than using `snapshot.val() !== null`.\n */\n exists(): boolean {\n return !this._node.isEmpty();\n }\n\n /**\n * Exports the entire contents of the DataSnapshot as a JavaScript object.\n *\n * The `exportVal()` method is similar to `val()`, except priority information\n * is included (if available), making it suitable for backing up your data.\n *\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\n * Array, string, number, boolean, or `null`).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n exportVal(): any {\n return this._node.val(true);\n }\n\n /**\n * Enumerates the top-level children in the `IteratedDataSnapshot`.\n *\n * Because of the way JavaScript objects work, the ordering of data in the\n * JavaScript object returned by `val()` is not guaranteed to match the\n * ordering on the server nor the ordering of `onChildAdded()` events. That is\n * where `forEach()` comes in handy. It guarantees the children of a\n * `DataSnapshot` will be iterated in their query order.\n *\n * If no explicit `orderBy*()` method is used, results are returned\n * ordered by key (unless priorities are used, in which case, results are\n * returned by priority).\n *\n * @param action - A function that will be called for each child DataSnapshot.\n * The callback can return true to cancel further enumeration.\n * @returns true if enumeration was canceled due to your callback returning\n * true.\n */\n forEach(action: (child: IteratedDataSnapshot) => boolean | void): boolean {\n if (this._node.isLeafNode()) {\n return false;\n }\n\n const childrenNode = this._node as ChildrenNode;\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\n return !!childrenNode.forEachChild(this._index, (key, node) => {\n return action(\n new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX)\n );\n });\n }\n\n /**\n * Returns true if the specified child path has (non-null) data.\n *\n * @param path - A relative path to the location of a potential child.\n * @returns `true` if data exists at the specified child path; else\n * `false`.\n */\n hasChild(path: string): boolean {\n const childPath = new Path(path);\n return !this._node.getChild(childPath).isEmpty();\n }\n\n /**\n * Returns whether or not the `DataSnapshot` has any non-`null` child\n * properties.\n *\n * You can use `hasChildren()` to determine if a `DataSnapshot` has any\n * children. If it does, you can enumerate them using `forEach()`. If it\n * doesn't, then either this snapshot contains a primitive value (which can be\n * retrieved with `val()`) or it is empty (in which case, `val()` will return\n * `null`).\n *\n * @returns true if this snapshot has any children; else false.\n */\n hasChildren(): boolean {\n if (this._node.isLeafNode()) {\n return false;\n } else {\n return !this._node.isEmpty();\n }\n }\n\n /**\n * Returns a JSON-serializable representation of this object.\n */\n toJSON(): object | null {\n return this.exportVal();\n }\n\n /**\n * Extracts a JavaScript value from a `DataSnapshot`.\n *\n * Depending on the data in a `DataSnapshot`, the `val()` method may return a\n * scalar type (string, number, or boolean), an array, or an object. It may\n * also return null, indicating that the `DataSnapshot` is empty (contains no\n * data).\n *\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\n * Array, string, number, boolean, or `null`).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n val(): any {\n return this._node.val();\n }\n}\n\n/**\n * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined.\n */\nexport interface IteratedDataSnapshot extends DataSnapshot {\n key: string; // key of the location of this snapshot.\n}\n\n/**\n *\n * Returns a `Reference` representing the location in the Database\n * corresponding to the provided path. If no path is provided, the `Reference`\n * will point to the root of the Database.\n *\n * @param db - The database instance to obtain a reference for.\n * @param path - Optional path representing the location the returned\n * `Reference` will point. If not provided, the returned `Reference` will\n * point to the root of the Database.\n * @returns If a path is provided, a `Reference`\n * pointing to the provided path. Otherwise, a `Reference` pointing to the\n * root of the Database.\n */\nexport function ref(db: Database, path?: string): DatabaseReference {\n db = getModularInstance(db);\n db._checkNotDeleted('ref');\n return path !== undefined ? child(db._root, path) : db._root;\n}\n\n/**\n * Returns a `Reference` representing the location in the Database\n * corresponding to the provided Firebase URL.\n *\n * An exception is thrown if the URL is not a valid Firebase Database URL or it\n * has a different domain than the current `Database` instance.\n *\n * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored\n * and are not applied to the returned `Reference`.\n *\n * @param db - The database instance to obtain a reference for.\n * @param url - The Firebase URL at which the returned `Reference` will\n * point.\n * @returns A `Reference` pointing to the provided\n * Firebase URL.\n */\nexport function refFromURL(db: Database, url: string): DatabaseReference {\n db = getModularInstance(db);\n db._checkNotDeleted('refFromURL');\n const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\n validateUrl('refFromURL', parsedURL);\n\n const repoInfo = parsedURL.repoInfo;\n if (\n !db._repo.repoInfo_.isCustomHost() &&\n repoInfo.host !== db._repo.repoInfo_.host\n ) {\n fatal(\n 'refFromURL' +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n db._repo.repoInfo_.host +\n ')'\n );\n }\n\n return ref(db, parsedURL.path.toString());\n}\n/**\n * Gets a `Reference` for the location at the specified relative path.\n *\n * The relative path can either be a simple child name (for example, \"ada\") or\n * a deeper slash-separated path (for example, \"ada/name/first\").\n *\n * @param parent - The parent location.\n * @param path - A relative path from this location to the desired child\n * location.\n * @returns The specified child location.\n */\nexport function child(\n parent: DatabaseReference,\n path: string\n): DatabaseReference {\n parent = getModularInstance(parent);\n if (pathGetFront(parent._path) === null) {\n validateRootPathString('child', 'path', path, false);\n } else {\n validatePathString('child', 'path', path, false);\n }\n return new ReferenceImpl(parent._repo, pathChild(parent._path, path));\n}\n\n/**\n * Returns an `OnDisconnect` object - see\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information on how to use it.\n *\n * @param ref - The reference to add OnDisconnect triggers for.\n */\nexport function onDisconnect(ref: DatabaseReference): OnDisconnect {\n ref = getModularInstance(ref) as ReferenceImpl;\n return new OnDisconnect(ref._repo, ref._path);\n}\n\nexport interface ThenableReferenceImpl\n extends ReferenceImpl,\n Pick, 'then' | 'catch'> {\n key: string;\n parent: ReferenceImpl;\n}\n\n/**\n * Generates a new child location using a unique key and returns its\n * `Reference`.\n *\n * This is the most common pattern for adding data to a collection of items.\n *\n * If you provide a value to `push()`, the value is written to the\n * generated location. If you don't pass a value, nothing is written to the\n * database and the child remains empty (but you can use the `Reference`\n * elsewhere).\n *\n * The unique keys generated by `push()` are ordered by the current time, so the\n * resulting list of items is chronologically sorted. The keys are also\n * designed to be unguessable (they contain 72 random bits of entropy).\n *\n * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.\n * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.\n *\n * @param parent - The parent location.\n * @param value - Optional value to be written at the generated location.\n * @returns Combined `Promise` and `Reference`; resolves when write is complete,\n * but can be used immediately as the `Reference` to the child location.\n */\nexport function push(\n parent: DatabaseReference,\n value?: unknown\n): ThenableReference {\n parent = getModularInstance(parent);\n validateWritablePath('push', parent._path);\n validateFirebaseDataArg('push', value, parent._path, true);\n const now = repoServerTime(parent._repo);\n const name = nextPushId(now);\n\n // push() returns a ThennableReference whose promise is fulfilled with a\n // regular Reference. We use child() to create handles to two different\n // references. The first is turned into a ThennableReference below by adding\n // then() and catch() methods and is used as the return value of push(). The\n // second remains a regular Reference and is used as the fulfilled value of\n // the first ThennableReference.\n const thenablePushRef: Partial = child(\n parent,\n name\n ) as ReferenceImpl;\n const pushRef = child(parent, name) as ReferenceImpl;\n\n let promise: Promise;\n if (value != null) {\n promise = set(pushRef, value).then(() => pushRef);\n } else {\n promise = Promise.resolve(pushRef);\n }\n\n thenablePushRef.then = promise.then.bind(promise);\n thenablePushRef.catch = promise.then.bind(promise, undefined);\n return thenablePushRef as ThenableReferenceImpl;\n}\n\n/**\n * Removes the data at this Database location.\n *\n * Any data at child locations will also be deleted.\n *\n * The effect of the remove will be visible immediately and the corresponding\n * event 'value' will be triggered. Synchronization of the remove to the\n * Firebase servers will also be started, and the returned Promise will resolve\n * when complete. If provided, the onComplete callback will be called\n * asynchronously after synchronization has finished.\n *\n * @param ref - The location to remove.\n * @returns Resolves when remove on server is complete.\n */\nexport function remove(ref: DatabaseReference): Promise {\n validateWritablePath('remove', ref._path);\n return set(ref, null);\n}\n\n/**\n * Writes data to this Database location.\n *\n * This will overwrite any data at this location and all child locations.\n *\n * The effect of the write will be visible immediately, and the corresponding\n * events (\"value\", \"child_added\", etc.) will be triggered. Synchronization of\n * the data to the Firebase servers will also be started, and the returned\n * Promise will resolve when complete. If provided, the `onComplete` callback\n * will be called asynchronously after synchronization has finished.\n *\n * Passing `null` for the new value is equivalent to calling `remove()`; namely,\n * all data at this location and all child locations will be deleted.\n *\n * `set()` will remove any priority stored at this location, so if priority is\n * meant to be preserved, you need to use `setWithPriority()` instead.\n *\n * Note that modifying data with `set()` will cancel any pending transactions\n * at that location, so extreme care should be taken if mixing `set()` and\n * `transaction()` to modify the same data.\n *\n * A single `set()` will generate a single \"value\" event at the location where\n * the `set()` was performed.\n *\n * @param ref - The location to write to.\n * @param value - The value to be written (string, number, boolean, object,\n * array, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function set(ref: DatabaseReference, value: unknown): Promise {\n ref = getModularInstance(ref);\n validateWritablePath('set', ref._path);\n validateFirebaseDataArg('set', value, ref._path, false);\n const deferred = new Deferred();\n repoSetWithPriority(\n ref._repo,\n ref._path,\n value,\n /*priority=*/ null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Sets a priority for the data at this Database location.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\n * ).\n *\n * @param ref - The location to write to.\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function setPriority(\n ref: DatabaseReference,\n priority: string | number | null\n): Promise {\n ref = getModularInstance(ref);\n validateWritablePath('setPriority', ref._path);\n validatePriority('setPriority', priority, false);\n const deferred = new Deferred();\n repoSetWithPriority(\n ref._repo,\n pathChild(ref._path, '.priority'),\n priority,\n null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Writes data the Database location. Like `set()` but also specifies the\n * priority for that data.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\n * ).\n *\n * @param ref - The location to write to.\n * @param value - The value to be written (string, number, boolean, object,\n * array, or null).\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function setWithPriority(\n ref: DatabaseReference,\n value: unknown,\n priority: string | number | null\n): Promise {\n validateWritablePath('setWithPriority', ref._path);\n validateFirebaseDataArg('setWithPriority', value, ref._path, false);\n validatePriority('setWithPriority', priority, false);\n if (ref.key === '.length' || ref.key === '.keys') {\n throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';\n }\n\n const deferred = new Deferred();\n repoSetWithPriority(\n ref._repo,\n ref._path,\n value,\n priority,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Writes multiple values to the Database at once.\n *\n * The `values` argument contains multiple property-value pairs that will be\n * written to the Database together. Each child property can either be a simple\n * property (for example, \"name\") or a relative path (for example,\n * \"name/first\") from the current location to the data to update.\n *\n * As opposed to the `set()` method, `update()` can be use to selectively update\n * only the referenced properties at the current location (instead of replacing\n * all the child properties at the current location).\n *\n * The effect of the write will be visible immediately, and the corresponding\n * events ('value', 'child_added', etc.) will be triggered. Synchronization of\n * the data to the Firebase servers will also be started, and the returned\n * Promise will resolve when complete. If provided, the `onComplete` callback\n * will be called asynchronously after synchronization has finished.\n *\n * A single `update()` will generate a single \"value\" event at the location\n * where the `update()` was performed, regardless of how many children were\n * modified.\n *\n * Note that modifying data with `update()` will cancel any pending\n * transactions at that location, so extreme care should be taken if mixing\n * `update()` and `transaction()` to modify the same data.\n *\n * Passing `null` to `update()` will remove the data at this location.\n *\n * See\n * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.\n *\n * @param ref - The location to write to.\n * @param values - Object containing multiple values.\n * @returns Resolves when update on server is complete.\n */\nexport function update(ref: DatabaseReference, values: object): Promise {\n validateFirebaseMergeDataArg('update', values, ref._path, false);\n const deferred = new Deferred();\n repoUpdate(\n ref._repo,\n ref._path,\n values as Record,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Gets the most up-to-date result for this query.\n *\n * @param query - The query to run.\n * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is\n * available, or rejects if the client is unable to return a value (e.g., if the\n * server is unreachable and there is nothing cached).\n */\nexport function get(query: Query): Promise {\n query = getModularInstance(query) as QueryImpl;\n const callbackContext = new CallbackContext(() => {});\n const container = new ValueEventRegistration(callbackContext);\n return repoGetValue(query._repo, query, container).then(node => {\n return new DataSnapshot(\n node,\n new ReferenceImpl(query._repo, query._path),\n query._queryParams.getIndex()\n );\n });\n}\n/**\n * Represents registration for 'value' events.\n */\nexport class ValueEventRegistration implements EventRegistration {\n constructor(private callbackContext: CallbackContext) {}\n\n respondsTo(eventType: string): boolean {\n return eventType === 'value';\n }\n\n createEvent(change: Change, query: QueryContext): DataEvent {\n const index = query._queryParams.getIndex();\n return new DataEvent(\n 'value',\n this,\n new DataSnapshot(\n change.snapshotNode,\n new ReferenceImpl(query._repo, query._path),\n index\n )\n );\n }\n\n getEventRunner(eventData: CancelEvent | DataEvent): () => void {\n if (eventData.getEventType() === 'cancel') {\n return () =>\n this.callbackContext.onCancel((eventData as CancelEvent).error);\n } else {\n return () =>\n this.callbackContext.onValue((eventData as DataEvent).snapshot, null);\n }\n }\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null {\n if (this.callbackContext.hasCancelCallback) {\n return new CancelEvent(this, error, path);\n } else {\n return null;\n }\n }\n\n matches(other: EventRegistration): boolean {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n } else if (!other.callbackContext || !this.callbackContext) {\n // If no callback specified, we consider it to match any callback.\n return true;\n } else {\n return other.callbackContext.matches(this.callbackContext);\n }\n }\n\n hasAnyCallback(): boolean {\n return this.callbackContext !== null;\n }\n}\n\n/**\n * Represents the registration of a child_x event.\n */\nexport class ChildEventRegistration implements EventRegistration {\n constructor(\n private eventType: string,\n private callbackContext: CallbackContext | null\n ) {}\n\n respondsTo(eventType: string): boolean {\n let eventToCheck =\n eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck =\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return this.eventType === eventToCheck;\n }\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null {\n if (this.callbackContext.hasCancelCallback) {\n return new CancelEvent(this, error, path);\n } else {\n return null;\n }\n }\n\n createEvent(change: Change, query: QueryContext): DataEvent {\n assert(change.childName != null, 'Child events should have a childName.');\n const childRef = child(\n new ReferenceImpl(query._repo, query._path),\n change.childName\n );\n const index = query._queryParams.getIndex();\n return new DataEvent(\n change.type as EventType,\n this,\n new DataSnapshot(change.snapshotNode, childRef, index),\n change.prevName\n );\n }\n\n getEventRunner(eventData: CancelEvent | DataEvent): () => void {\n if (eventData.getEventType() === 'cancel') {\n return () =>\n this.callbackContext.onCancel((eventData as CancelEvent).error);\n } else {\n return () =>\n this.callbackContext.onValue(\n (eventData as DataEvent).snapshot,\n (eventData as DataEvent).prevName\n );\n }\n }\n\n matches(other: EventRegistration): boolean {\n if (other instanceof ChildEventRegistration) {\n return (\n this.eventType === other.eventType &&\n (!this.callbackContext ||\n !other.callbackContext ||\n this.callbackContext.matches(other.callbackContext))\n );\n }\n\n return false;\n }\n\n hasAnyCallback(): boolean {\n return !!this.callbackContext;\n }\n}\n\nfunction addEventListener(\n query: Query,\n eventType: EventType,\n callback: UserCallback,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n) {\n let cancelCallback: ((error: Error) => unknown) | undefined;\n if (typeof cancelCallbackOrListenOptions === 'object') {\n cancelCallback = undefined;\n options = cancelCallbackOrListenOptions;\n }\n if (typeof cancelCallbackOrListenOptions === 'function') {\n cancelCallback = cancelCallbackOrListenOptions;\n }\n\n if (options && options.onlyOnce) {\n const userCallback = callback;\n const onceCallback: UserCallback = (dataSnapshot, previousChildName) => {\n repoRemoveEventCallbackForQuery(query._repo, query, container);\n userCallback(dataSnapshot, previousChildName);\n };\n onceCallback.userCallback = callback.userCallback;\n onceCallback.context = callback.context;\n callback = onceCallback;\n }\n\n const callbackContext = new CallbackContext(\n callback,\n cancelCallback || undefined\n );\n const container =\n eventType === 'value'\n ? new ValueEventRegistration(callbackContext)\n : new ChildEventRegistration(eventType, callbackContext);\n repoAddEventCallbackForQuery(query._repo, query, container);\n return () => repoRemoveEventCallbackForQuery(query._repo, query, container);\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'value',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName?: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_added',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_changed',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_moved',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_removed',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\nexport { EventType };\n\n/**\n * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.\n * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from\n * the respective `on*` callbacks.\n *\n * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener\n * will not automatically remove listeners registered on child nodes, `off()`\n * must also be called on any child listeners to remove the callback.\n *\n * If a callback is not specified, all callbacks for the specified eventType\n * will be removed. Similarly, if no eventType is specified, all callbacks\n * for the `Reference` will be removed.\n *\n * Individual listeners can also be removed by invoking their unsubscribe\n * callbacks.\n *\n * @param query - The query that the listener was registered with.\n * @param eventType - One of the following strings: \"value\", \"child_added\",\n * \"child_changed\", \"child_removed\", or \"child_moved.\" If omitted, all callbacks\n * for the `Reference` will be removed.\n * @param callback - The callback function that was passed to `on()` or\n * `undefined` to remove all callbacks.\n */\nexport function off(\n query: Query,\n eventType?: EventType,\n callback?: (\n snapshot: DataSnapshot,\n previousChildName?: string | null\n ) => unknown\n): void {\n let container: EventRegistration | null = null;\n const expCallback = callback ? new CallbackContext(callback) : null;\n if (eventType === 'value') {\n container = new ValueEventRegistration(expCallback);\n } else if (eventType) {\n container = new ChildEventRegistration(eventType, expCallback);\n }\n repoRemoveEventCallbackForQuery(query._repo, query, container);\n}\n\n/** Describes the different query constraints available in this SDK. */\nexport type QueryConstraintType =\n | 'endAt'\n | 'endBefore'\n | 'startAt'\n | 'startAfter'\n | 'limitToFirst'\n | 'limitToLast'\n | 'orderByChild'\n | 'orderByKey'\n | 'orderByPriority'\n | 'orderByValue'\n | 'equalTo';\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Database query. `QueryConstraint`s are created by invoking {@link endAt},\n * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link\n * limitToFirst}, {@link limitToLast}, {@link orderByChild},\n * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,\n * {@link orderByValue} or {@link equalTo} and\n * can then be passed to {@link query} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nexport abstract class QueryConstraint {\n /** The type of this query constraints */\n abstract readonly type: QueryConstraintType;\n\n /**\n * Takes the provided `Query` and returns a copy of the `Query` with this\n * `QueryConstraint` applied.\n */\n abstract _apply(query: QueryImpl): QueryImpl;\n}\n\nclass QueryEndAtConstraint extends QueryConstraint {\n readonly type = 'endAt';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('endAt', this._value, query._path, true);\n const newParams = queryParamsEndAt(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'endAt: Starting point was already set (by another call to endAt, ' +\n 'endBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified ending point.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The ending point is inclusive, so children with exactly the specified value\n * will be included in the query. The optional key argument can be used to\n * further limit the range of the query. If it is specified, then children that\n * have exactly the specified value must also have a key name less than or equal\n * to the specified key.\n *\n * You can read more about `endAt()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to end at. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to end at, among the children with the previously\n * specified priority. This argument is only allowed if ordering by child,\n * value, or priority.\n */\nexport function endAt(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('endAt', 'key', key, true);\n return new QueryEndAtConstraint(value, key);\n}\n\nclass QueryEndBeforeConstraint extends QueryConstraint {\n readonly type = 'endBefore';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('endBefore', this._value, query._path, false);\n const newParams = queryParamsEndBefore(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'endBefore: Starting point was already set (by another call to endAt, ' +\n 'endBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified ending point (exclusive).\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The ending point is exclusive. If only a value is provided, children\n * with a value less than the specified value will be included in the query.\n * If a key is specified, then children must have a value less than or equal\n * to the specified value and a key name less than the specified key.\n *\n * @param value - The value to end before. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to end before, among the children with the\n * previously specified priority. This argument is only allowed if ordering by\n * child, value, or priority.\n */\nexport function endBefore(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('endBefore', 'key', key, true);\n return new QueryEndBeforeConstraint(value, key);\n}\n\nclass QueryStartAtConstraint extends QueryConstraint {\n readonly type = 'startAt';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('startAt', this._value, query._path, true);\n const newParams = queryParamsStartAt(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'startAt: Starting point was already set (by another call to startAt, ' +\n 'startBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified starting point.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The starting point is inclusive, so children with exactly the specified value\n * will be included in the query. The optional key argument can be used to\n * further limit the range of the query. If it is specified, then children that\n * have exactly the specified value must also have a key name greater than or\n * equal to the specified key.\n *\n * You can read more about `startAt()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to start at. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start at. This argument is only allowed if\n * ordering by child, value, or priority.\n */\nexport function startAt(\n value: number | string | boolean | null = null,\n key?: string\n): QueryConstraint {\n validateKey('startAt', 'key', key, true);\n return new QueryStartAtConstraint(value, key);\n}\n\nclass QueryStartAfterConstraint extends QueryConstraint {\n readonly type = 'startAfter';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('startAfter', this._value, query._path, false);\n const newParams = queryParamsStartAfter(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'startAfter: Starting point was already set (by another call to startAt, ' +\n 'startAfter, or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified starting point (exclusive).\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The starting point is exclusive. If only a value is provided, children\n * with a value greater than the specified value will be included in the query.\n * If a key is specified, then children must have a value greater than or equal\n * to the specified value and a a key name greater than the specified key.\n *\n * @param value - The value to start after. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start after. This argument is only allowed if\n * ordering by child, value, or priority.\n */\nexport function startAfter(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('startAfter', 'key', key, true);\n return new QueryStartAfterConstraint(value, key);\n}\n\nclass QueryLimitToFirstConstraint extends QueryConstraint {\n readonly type = 'limitToFirst';\n\n constructor(private readonly _limit: number) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n if (query._queryParams.hasLimit()) {\n throw new Error(\n 'limitToFirst: Limit was already set (by another call to limitToFirst ' +\n 'or limitToLast).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n queryParamsLimitToFirst(query._queryParams, this._limit),\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that if limited to the first specific number\n * of children.\n *\n * The `limitToFirst()` method is used to set a maximum number of children to be\n * synced for a given callback. If we set a limit of 100, we will initially only\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\n * stored in our Database, a `child_added` event will fire for each message.\n * However, if we have over 100 messages, we will only receive a `child_added`\n * event for the first 100 ordered messages. As items change, we will receive\n * `child_removed` events for each item that drops out of the active list so\n * that the total number stays at 100.\n *\n * You can read more about `limitToFirst()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param limit - The maximum number of nodes to include in this query.\n */\nexport function limitToFirst(limit: number): QueryConstraint {\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\n throw new Error('limitToFirst: First argument must be a positive integer.');\n }\n return new QueryLimitToFirstConstraint(limit);\n}\n\nclass QueryLimitToLastConstraint extends QueryConstraint {\n readonly type = 'limitToLast';\n\n constructor(private readonly _limit: number) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n if (query._queryParams.hasLimit()) {\n throw new Error(\n 'limitToLast: Limit was already set (by another call to limitToFirst ' +\n 'or limitToLast).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n queryParamsLimitToLast(query._queryParams, this._limit),\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that is limited to return only the last\n * specified number of children.\n *\n * The `limitToLast()` method is used to set a maximum number of children to be\n * synced for a given callback. If we set a limit of 100, we will initially only\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\n * stored in our Database, a `child_added` event will fire for each message.\n * However, if we have over 100 messages, we will only receive a `child_added`\n * event for the last 100 ordered messages. As items change, we will receive\n * `child_removed` events for each item that drops out of the active list so\n * that the total number stays at 100.\n *\n * You can read more about `limitToLast()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param limit - The maximum number of nodes to include in this query.\n */\nexport function limitToLast(limit: number): QueryConstraint {\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\n throw new Error('limitToLast: First argument must be a positive integer.');\n }\n\n return new QueryLimitToLastConstraint(limit);\n}\n\nclass QueryOrderByChildConstraint extends QueryConstraint {\n readonly type = 'orderByChild';\n\n constructor(private readonly _path: string) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByChild');\n const parsedPath = new Path(this._path);\n if (pathIsEmpty(parsedPath)) {\n throw new Error(\n 'orderByChild: cannot pass in empty path. Use orderByValue() instead.'\n );\n }\n const index = new PathIndex(parsedPath);\n const newParams = queryParamsOrderBy(query._queryParams, index);\n validateQueryEndpoints(newParams);\n\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by the specified child key.\n *\n * Queries can only order by one key at a time. Calling `orderByChild()`\n * multiple times on the same query is an error.\n *\n * Firebase queries allow you to order your data by any child key on the fly.\n * However, if you know in advance what your indexes will be, you can define\n * them via the .indexOn rule in your Security Rules for better performance. See\n * the{@link https://firebase.google.com/docs/database/security/indexing-data}\n * rule for more information.\n *\n * You can read more about `orderByChild()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n *\n * @param path - The path to order by.\n */\nexport function orderByChild(path: string): QueryConstraint {\n if (path === '$key') {\n throw new Error(\n 'orderByChild: \"$key\" is invalid. Use orderByKey() instead.'\n );\n } else if (path === '$priority') {\n throw new Error(\n 'orderByChild: \"$priority\" is invalid. Use orderByPriority() instead.'\n );\n } else if (path === '$value') {\n throw new Error(\n 'orderByChild: \"$value\" is invalid. Use orderByValue() instead.'\n );\n }\n validatePathString('orderByChild', 'path', path, false);\n return new QueryOrderByChildConstraint(path);\n}\n\nclass QueryOrderByKeyConstraint extends QueryConstraint {\n readonly type = 'orderByKey';\n\n _apply(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByKey');\n const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by the key.\n *\n * Sorts the results of a query by their (ascending) key values.\n *\n * You can read more about `orderByKey()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n */\nexport function orderByKey(): QueryConstraint {\n return new QueryOrderByKeyConstraint();\n}\n\nclass QueryOrderByPriorityConstraint extends QueryConstraint {\n readonly type = 'orderByPriority';\n\n _apply(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByPriority');\n const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by priority.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}\n * for alternatives to priority.\n */\nexport function orderByPriority(): QueryConstraint {\n return new QueryOrderByPriorityConstraint();\n}\n\nclass QueryOrderByValueConstraint extends QueryConstraint {\n readonly type = 'orderByValue';\n\n _apply(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByValue');\n const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by value.\n *\n * If the children of a query are all scalar values (string, number, or\n * boolean), you can order the results by their (ascending) values.\n *\n * You can read more about `orderByValue()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n */\nexport function orderByValue(): QueryConstraint {\n return new QueryOrderByValueConstraint();\n}\n\nclass QueryEqualToValueConstraint extends QueryConstraint {\n readonly type = 'equalTo';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('equalTo', this._value, query._path, false);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'equalTo: Starting point was already set (by another call to startAt/startAfter or ' +\n 'equalTo).'\n );\n }\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'equalTo: Ending point was already set (by another call to endAt/endBefore or ' +\n 'equalTo).'\n );\n }\n return new QueryEndAtConstraint(this._value, this._key)._apply(\n new QueryStartAtConstraint(this._value, this._key)._apply(query)\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` that includes children that match the specified\n * value.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The optional key argument can be used to further limit the range of the\n * query. If it is specified, then children that have exactly the specified\n * value must also have exactly the specified key as their key name. This can be\n * used to filter result sets with many matches for the same value.\n *\n * You can read more about `equalTo()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to match for. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start at, among the children with the\n * previously specified priority. This argument is only allowed if ordering by\n * child, value, or priority.\n */\nexport function equalTo(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('equalTo', 'key', key, true);\n return new QueryEqualToValueConstraint(value, key);\n}\n\n/**\n * Creates a new immutable instance of `Query` that is extended to also include\n * additional query constraints.\n *\n * @param query - The Query instance to use as a base for the new constraints.\n * @param queryConstraints - The list of `QueryConstraint`s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query(\n query: Query,\n ...queryConstraints: QueryConstraint[]\n): Query {\n let queryImpl = getModularInstance(query) as QueryImpl;\n for (const constraint of queryConstraints) {\n queryImpl = constraint._apply(queryImpl);\n }\n return queryImpl;\n}\n\n/**\n * Define reference constructor in various modules\n *\n * We are doing this here to avoid several circular\n * dependency issues\n */\nsyncPointSetReferenceConstructor(ReferenceImpl);\nsyncTreeSetReferenceConstructor(ReferenceImpl);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _FirebaseService,\n _getProvider,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\nimport {\n getModularInstance,\n createMockUserToken,\n deepEqual,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\n} from '@firebase/util';\n\nimport { AppCheckTokenProvider } from '../core/AppCheckTokenProvider';\nimport {\n AuthTokenProvider,\n EmulatorTokenProvider,\n FirebaseAuthTokenProvider\n} from '../core/AuthTokenProvider';\nimport { Repo, repoInterrupt, repoResume, repoStart } from '../core/Repo';\nimport { RepoInfo, RepoInfoEmulatorOptions } from '../core/RepoInfo';\nimport { parseRepoInfo } from '../core/util/libs/parser';\nimport { newEmptyPath, pathIsEmpty } from '../core/util/Path';\nimport {\n warn,\n fatal,\n log,\n enableLogging as enableLoggingImpl\n} from '../core/util/util';\nimport { validateUrl } from '../core/util/validation';\nimport { BrowserPollConnection } from '../realtime/BrowserPollConnection';\nimport { TransportManager } from '../realtime/TransportManager';\nimport { WebSocketConnection } from '../realtime/WebSocketConnection';\n\nimport { ReferenceImpl } from './Reference_impl';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n/**\n * This variable is also defined in the firebase Node.js Admin SDK. Before\n * modifying this definition, consult the definition in:\n *\n * https://github.com/firebase/firebase-admin-node\n *\n * and make sure the two are consistent.\n */\nconst FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';\n\n/**\n * Creates and caches `Repo` instances.\n */\nconst repos: {\n [appName: string]: {\n [dbUrl: string]: Repo;\n };\n} = {};\n\n/**\n * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).\n */\nlet useRestClient = false;\n\n/**\n * Update an existing `Repo` in place to point to a new host/port.\n */\nfunction repoManagerApplyEmulatorSettings(\n repo: Repo,\n hostAndPort: string,\n emulatorOptions: RepoInfoEmulatorOptions,\n tokenProvider?: AuthTokenProvider\n): void {\n const portIndex = hostAndPort.lastIndexOf(':');\n const host = hostAndPort.substring(0, portIndex);\n const useSsl = isCloudWorkstation(host);\n repo.repoInfo_ = new RepoInfo(\n hostAndPort,\n /* secure= */ useSsl,\n repo.repoInfo_.namespace,\n repo.repoInfo_.webSocketOnly,\n repo.repoInfo_.nodeAdmin,\n repo.repoInfo_.persistenceKey,\n repo.repoInfo_.includeNamespaceInQueryParams,\n /*isUsingEmulator=*/ true,\n emulatorOptions\n );\n\n if (tokenProvider) {\n repo.authTokenProvider_ = tokenProvider;\n }\n}\n\n/**\n * This function should only ever be called to CREATE a new database instance.\n * @internal\n */\nexport function repoManagerDatabaseFromApp(\n app: FirebaseApp,\n authProvider: Provider,\n appCheckProvider?: Provider,\n url?: string,\n nodeAdmin?: boolean\n): Database {\n let dbUrl: string | undefined = url || app.options.databaseURL;\n if (dbUrl === undefined) {\n if (!app.options.projectId) {\n fatal(\n \"Can't determine Firebase Database URL. Be sure to include \" +\n ' a Project ID when calling firebase.initializeApp().'\n );\n }\n\n log('Using default host for project ', app.options.projectId);\n dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;\n }\n\n let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\n let repoInfo = parsedUrl.repoInfo;\n\n let isEmulator: boolean;\n\n let dbEmulatorHost: string | undefined = undefined;\n if (typeof process !== 'undefined' && process.env) {\n dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];\n }\n\n if (dbEmulatorHost) {\n isEmulator = true;\n dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;\n parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\n repoInfo = parsedUrl.repoInfo;\n } else {\n isEmulator = !parsedUrl.repoInfo.secure;\n }\n\n const authTokenProvider =\n nodeAdmin && isEmulator\n ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)\n : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);\n\n validateUrl('Invalid Firebase Database URL', parsedUrl);\n if (!pathIsEmpty(parsedUrl.path)) {\n fatal(\n 'Database URL must point to the root of a Firebase Database ' +\n '(not including a child path).'\n );\n }\n\n const repo = repoManagerCreateRepo(\n repoInfo,\n app,\n authTokenProvider,\n new AppCheckTokenProvider(app, appCheckProvider)\n );\n return new Database(repo, app);\n}\n\n/**\n * Remove the repo and make sure it is disconnected.\n *\n */\nfunction repoManagerDeleteRepo(repo: Repo, appName: string): void {\n const appRepos = repos[appName];\n // This should never happen...\n if (!appRepos || appRepos[repo.key] !== repo) {\n fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);\n }\n repoInterrupt(repo);\n delete appRepos[repo.key];\n}\n\n/**\n * Ensures a repo doesn't already exist and then creates one using the\n * provided app.\n *\n * @param repoInfo - The metadata about the Repo\n * @returns The Repo object for the specified server / repoName.\n */\nfunction repoManagerCreateRepo(\n repoInfo: RepoInfo,\n app: FirebaseApp,\n authTokenProvider: AuthTokenProvider,\n appCheckProvider: AppCheckTokenProvider\n): Repo {\n let appRepos = repos[app.name];\n\n if (!appRepos) {\n appRepos = {};\n repos[app.name] = appRepos;\n }\n\n let repo = appRepos[repoInfo.toURLString()];\n if (repo) {\n fatal(\n 'Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.'\n );\n }\n repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);\n appRepos[repoInfo.toURLString()] = repo;\n\n return repo;\n}\n\n/**\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\n */\nexport function repoManagerForceRestClient(forceRestClient: boolean): void {\n useRestClient = forceRestClient;\n}\n\n/**\n * Class representing a Firebase Realtime Database.\n */\nexport class Database implements _FirebaseService {\n /** Represents a `Database` instance. */\n readonly 'type' = 'database';\n\n /** Track if the instance has been used (root or repo accessed) */\n _instanceStarted: boolean = false;\n\n /** Backing state for root_ */\n private _rootInternal?: ReferenceImpl;\n\n /** @hideconstructor */\n constructor(\n public _repoInternal: Repo,\n /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */\n readonly app: FirebaseApp\n ) {}\n\n get _repo(): Repo {\n if (!this._instanceStarted) {\n repoStart(\n this._repoInternal,\n this.app.options.appId,\n this.app.options['databaseAuthVariableOverride']\n );\n this._instanceStarted = true;\n }\n return this._repoInternal;\n }\n\n get _root(): ReferenceImpl {\n if (!this._rootInternal) {\n this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());\n }\n return this._rootInternal;\n }\n\n _delete(): Promise {\n if (this._rootInternal !== null) {\n repoManagerDeleteRepo(this._repo, this.app.name);\n this._repoInternal = null;\n this._rootInternal = null;\n }\n return Promise.resolve();\n }\n\n _checkNotDeleted(apiName: string) {\n if (this._rootInternal === null) {\n fatal('Cannot call ' + apiName + ' on a deleted database.');\n }\n }\n}\n\nfunction checkTransportInit() {\n if (TransportManager.IS_TRANSPORT_INITIALIZED) {\n warn(\n 'Transport has already been initialized. Please call this function before calling ref or setting up a listener'\n );\n }\n}\n\n/**\n * Force the use of websockets instead of longPolling.\n */\nexport function forceWebSockets() {\n checkTransportInit();\n BrowserPollConnection.forceDisallow();\n}\n\n/**\n * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.\n */\nexport function forceLongPolling() {\n checkTransportInit();\n WebSocketConnection.forceDisallow();\n BrowserPollConnection.forceAllow();\n}\n\n/**\n * Returns the instance of the Realtime Database SDK that is associated with the provided\n * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if\n * no instance exists or if the existing instance uses a custom database URL.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime\n * Database instance is associated with.\n * @param url - The URL of the Realtime Database instance to connect to. If not\n * provided, the SDK connects to the default instance of the Firebase App.\n * @returns The `Database` instance of the provided app.\n */\nexport function getDatabase(\n app: FirebaseApp = getApp(),\n url?: string\n): Database {\n const db = _getProvider(app, 'database').getImmediate({\n identifier: url\n }) as Database;\n if (!db._instanceStarted) {\n const emulator = getDefaultEmulatorHostnameAndPort('database');\n if (emulator) {\n connectDatabaseEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * Modify the provided instance to communicate with the Realtime Database\n * emulator.\n *\n *

Note: This method must be called before performing any other operation.\n *\n * @param db - The instance to modify.\n * @param host - The emulator host (ex: localhost)\n * @param port - The emulator port (ex: 8080)\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\n */\nexport function connectDatabaseEmulator(\n db: Database,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n db = getModularInstance(db);\n db._checkNotDeleted('useEmulator');\n\n const hostAndPort = `${host}:${port}`;\n const repo = db._repoInternal;\n if (db._instanceStarted) {\n // If the instance has already been started, then silenty fail if this function is called again\n // with the same parameters. If the parameters differ then assert.\n if (\n hostAndPort === db._repoInternal.repoInfo_.host &&\n deepEqual(options, repo.repoInfo_.emulatorOptions)\n ) {\n return;\n }\n fatal(\n 'connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.'\n );\n }\n\n let tokenProvider: EmulatorTokenProvider | undefined = undefined;\n if (repo.repoInfo_.nodeAdmin) {\n if (options.mockUserToken) {\n fatal(\n 'mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the \"firebase\" package instead of \"firebase-admin\".'\n );\n }\n tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);\n } else if (options.mockUserToken) {\n const token =\n typeof options.mockUserToken === 'string'\n ? options.mockUserToken\n : createMockUserToken(options.mockUserToken, db.app.options.projectId);\n tokenProvider = new EmulatorTokenProvider(token);\n }\n\n // Workaround to get cookies in Firebase Studio\n if (isCloudWorkstation(host)) {\n void pingServer(host);\n updateEmulatorBanner('Database', true);\n }\n\n // Modify the repo to apply emulator settings\n repoManagerApplyEmulatorSettings(repo, hostAndPort, options, tokenProvider);\n}\n\n/**\n * Disconnects from the server (all Database operations will be completed\n * offline).\n *\n * The client automatically maintains a persistent connection to the Database\n * server, which will remain active indefinitely and reconnect when\n * disconnected. However, the `goOffline()` and `goOnline()` methods may be used\n * to control the client connection in cases where a persistent connection is\n * undesirable.\n *\n * While offline, the client will no longer receive data updates from the\n * Database. However, all Database operations performed locally will continue to\n * immediately fire events, allowing your application to continue behaving\n * normally. Additionally, each operation performed locally will automatically\n * be queued and retried upon reconnection to the Database server.\n *\n * To reconnect to the Database and begin receiving remote events, see\n * `goOnline()`.\n *\n * @param db - The instance to disconnect.\n */\nexport function goOffline(db: Database): void {\n db = getModularInstance(db);\n db._checkNotDeleted('goOffline');\n repoInterrupt(db._repo);\n}\n\n/**\n * Reconnects to the server and synchronizes the offline Database state\n * with the server state.\n *\n * This method should be used after disabling the active connection with\n * `goOffline()`. Once reconnected, the client will transmit the proper data\n * and fire the appropriate events so that your client \"catches up\"\n * automatically.\n *\n * @param db - The instance to reconnect.\n */\nexport function goOnline(db: Database): void {\n db = getModularInstance(db);\n db._checkNotDeleted('goOnline');\n repoResume(db._repo);\n}\n\n/**\n * Logs debugging information to the console.\n *\n * @param enabled - Enables logging if `true`, disables logging if `false`.\n * @param persistent - Remembers the logging state between page refreshes if\n * `true`.\n */\nexport function enableLogging(enabled: boolean, persistent?: boolean);\n\n/**\n * Logs debugging information to the console.\n *\n * @param logger - A custom logger function to control how things get logged.\n */\nexport function enableLogging(logger: (message: string) => unknown);\n\nexport function enableLogging(\n logger: boolean | ((message: string) => unknown),\n persistent?: boolean\n): void {\n enableLoggingImpl(logger, persistent);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { name, version } from '../package.json';\nimport { setSDKVersion } from '../src/core/version';\n\nimport { repoManagerDatabaseFromApp } from './api/Database';\n\nexport function registerDatabase(variant?: string): void {\n setSDKVersion(SDK_VERSION);\n _registerComponent(\n new Component(\n 'database',\n (container, { instanceIdentifier: url }) => {\n const app = container.getProvider('app').getImmediate()!;\n const authProvider = container.getProvider('auth-internal');\n const appCheckProvider = container.getProvider('app-check-internal');\n return repoManagerDatabaseFromApp(\n app,\n authProvider,\n appCheckProvider,\n url\n );\n },\n ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n registerVersion(name, version, variant);\n // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst SERVER_TIMESTAMP = {\n '.sv': 'timestamp'\n};\n\n/**\n * Returns a placeholder value for auto-populating the current timestamp (time\n * since the Unix epoch, in milliseconds) as determined by the Firebase\n * servers.\n */\nexport function serverTimestamp(): object {\n return SERVER_TIMESTAMP;\n}\n\n/**\n * Returns a placeholder value that can be used to atomically increment the\n * current database value by the provided delta.\n *\n * @param delta - the amount to modify the current value atomically.\n * @returns A placeholder value for modifying data atomically server-side.\n */\nexport function increment(delta: number): object {\n return {\n '.sv': {\n 'increment': delta\n }\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance, Deferred } from '@firebase/util';\n\nimport { repoStartTransaction } from '../core/Repo';\nimport { PRIORITY_INDEX } from '../core/snap/indexes/PriorityIndex';\nimport { Node } from '../core/snap/Node';\nimport { validateWritablePath } from '../core/util/validation';\n\nimport { DatabaseReference } from './Reference';\nimport { DataSnapshot, onValue, ReferenceImpl } from './Reference_impl';\n\n/** An options object to configure transactions. */\nexport interface TransactionOptions {\n /**\n * By default, events are raised each time the transaction update function\n * runs. So if it is run multiple times, you may see intermediate states. You\n * can set this to false to suppress these intermediate states and instead\n * wait until the transaction has completed before events are raised.\n */\n readonly applyLocally?: boolean;\n}\n\n/**\n * A type for the resolve value of {@link runTransaction}.\n */\nexport class TransactionResult {\n /** @hideconstructor */\n constructor(\n /** Whether the transaction was successfully committed. */\n readonly committed: boolean,\n /** The resulting data snapshot. */\n readonly snapshot: DataSnapshot\n ) {}\n\n /** Returns a JSON-serializable representation of this object. */\n toJSON(): object {\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n }\n}\n\n/**\n * Atomically modifies the data at this location.\n *\n * Atomically modify the data at this location. Unlike a normal `set()`, which\n * just overwrites the data regardless of its previous value, `runTransaction()` is\n * used to modify the existing value to a new value, ensuring there are no\n * conflicts with other clients writing to the same location at the same time.\n *\n * To accomplish this, you pass `runTransaction()` an update function which is\n * used to transform the current value into a new value. If another client\n * writes to the location before your new value is successfully written, your\n * update function will be called again with the new current value, and the\n * write will be retried. This will happen repeatedly until your write succeeds\n * without conflict or you abort the transaction by not returning a value from\n * your update function.\n *\n * Note: Modifying data with `set()` will cancel any pending transactions at\n * that location, so extreme care should be taken if mixing `set()` and\n * `runTransaction()` to update the same data.\n *\n * Note: When using transactions with Security and Firebase Rules in place, be\n * aware that a client needs `.read` access in addition to `.write` access in\n * order to perform a transaction. This is because the client-side nature of\n * transactions requires the client to read the data in order to transactionally\n * update it.\n *\n * @param ref - The location to atomically modify.\n * @param transactionUpdate - A developer-supplied function which will be passed\n * the current data stored at this location (as a JavaScript object). The\n * function should return the new value it would like written (as a JavaScript\n * object). If `undefined` is returned (i.e. you return with no arguments) the\n * transaction will be aborted and the data at this location will not be\n * modified.\n * @param options - An options object to configure transactions.\n * @returns A `Promise` that can optionally be used instead of the `onComplete`\n * callback to handle success and failure.\n */\nexport function runTransaction(\n ref: DatabaseReference,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n transactionUpdate: (currentData: any) => unknown,\n options?: TransactionOptions\n): Promise {\n ref = getModularInstance(ref);\n\n validateWritablePath('Reference.transaction', ref._path);\n\n if (ref.key === '.length' || ref.key === '.keys') {\n throw (\n 'Reference.transaction failed: ' + ref.key + ' is a read-only object.'\n );\n }\n\n const applyLocally = options?.applyLocally ?? true;\n const deferred = new Deferred();\n\n const promiseComplete = (\n error: Error | null,\n committed: boolean,\n node: Node | null\n ) => {\n let dataSnapshot: DataSnapshot | null = null;\n if (error) {\n deferred.reject(error);\n } else {\n dataSnapshot = new DataSnapshot(\n node,\n new ReferenceImpl(ref._repo, ref._path),\n PRIORITY_INDEX\n );\n deferred.resolve(new TransactionResult(committed, dataSnapshot));\n }\n };\n\n // Add a watch to make sure we get server updates.\n const unwatcher = onValue(ref, () => {});\n\n repoStartTransaction(\n ref._repo,\n ref._path,\n transactionUpdate,\n promiseComplete,\n unwatcher,\n applyLocally\n );\n\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PersistentConnection } from '../core/PersistentConnection';\nimport { RepoInfo } from '../core/RepoInfo';\nimport { Connection } from '../realtime/Connection';\n\nimport { repoManagerForceRestClient } from './Database';\n\nexport const DataConnection = PersistentConnection;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(PersistentConnection.prototype as any).simpleListen = function (\n pathString: string,\n onComplete: (a: unknown) => void\n) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(PersistentConnection.prototype as any).echo = function (\n data: unknown,\n onEcho: (a: unknown) => void\n) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n\n// RealTimeConnection properties that we use in tests.\nexport const RealTimeConnection = Connection;\n\n/**\n * @internal\n */\nexport const hijackHash = function (newHash: () => string) {\n const oldPut = PersistentConnection.prototype.put;\n PersistentConnection.prototype.put = function (\n pathString,\n data,\n onComplete,\n hash\n ) {\n if (hash !== undefined) {\n hash = newHash();\n }\n oldPut.call(this, pathString, data, onComplete, hash);\n };\n return function () {\n PersistentConnection.prototype.put = oldPut;\n };\n};\n\nexport const ConnectionTarget = RepoInfo;\n\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n * @internal\n */\nexport const forceRestClient = function (forceRestClient: boolean) {\n repoManagerForceRestClient(forceRestClient);\n};\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebaseAppCheckInternal,\n AppCheckInternalComponentName\n} from '@firebase/app-check-interop-types';\nimport { FirebaseApp } from '@firebase/app-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n Provider\n} from '@firebase/component';\n\nimport { repoManagerDatabaseFromApp } from '../api/Database';\nimport { Database } from '../api.standalone';\nimport { setSDKVersion } from '../core/version';\n\n/**\n * Used by console to create a database based on the app,\n * passed database URL and a custom auth implementation.\n * @internal\n * @param app - A valid FirebaseApp-like object\n * @param url - A valid Firebase databaseURL\n * @param version - custom version e.g. firebase-admin version\n * @param customAppCheckImpl - custom app check implementation\n * @param customAuthImpl - custom auth implementation\n */\nexport function _initStandalone({\n app,\n url,\n version,\n customAuthImpl,\n customAppCheckImpl,\n nodeAdmin = false\n}: {\n app: FirebaseApp;\n url: string;\n version: string;\n customAuthImpl: FirebaseAuthInternal;\n customAppCheckImpl?: FirebaseAppCheckInternal;\n nodeAdmin?: boolean;\n}): Database {\n setSDKVersion(version);\n\n /**\n * ComponentContainer('database-standalone') is just a placeholder that doesn't perform\n * any actual function.\n */\n const componentContainer = new ComponentContainer('database-standalone');\n const authProvider = new Provider(\n 'auth-internal',\n componentContainer\n );\n let appCheckProvider: Provider;\n if (customAppCheckImpl) {\n appCheckProvider = new Provider(\n 'app-check-internal',\n componentContainer\n );\n appCheckProvider.setComponent(\n new Component(\n 'app-check-internal',\n () => customAppCheckImpl,\n ComponentType.PRIVATE\n )\n );\n }\n authProvider.setComponent(\n new Component('auth-internal', () => customAuthImpl, ComponentType.PRIVATE)\n );\n\n return repoManagerDatabaseFromApp(\n app,\n authProvider,\n appCheckProvider,\n url,\n nodeAdmin\n );\n}\n","/**\n * Firebase Realtime Database\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Database } from './api/Database';\nimport { registerDatabase } from './register';\n\nexport * from './api';\n\nregisterDatabase();\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'database': Database;\n }\n}\n"],"names":["stringify","jsonEval","contains","Logger","stringToByteArray","Sha1","base64","enableLogging","assert","LogLevel","isNodeSdk","app","_isFirebaseServerApp","deepCopy","base64Encode","isMobileCordova","stringLength","Deferred","safeGet","isAdmin","isValidFormat","isEmpty","isReactNative","assertionError","MAX_NODE","setMaxNode","nodeFromJSON","map","setPriorityMaxNode","querystring","referenceConstructor","errorPrefixFxn","getModularInstance","isCloudWorkstation","getApp","_getProvider","getDefaultEmulatorHostnameAndPort","deepEqual","createMockUserToken","pingServer","updateEmulatorBanner","enableLoggingImpl","SDK_VERSION","_registerComponent","Component","registerVersion","ComponentContainer","Provider"],"mappings":";;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;AAeG;AAEH;AACO,IAAI,WAAW,GAAG,EAAE,CAAC;AAE5B;;;AAGG;AACG,SAAU,aAAa,CAAC,OAAe,EAAA;IAC3C,WAAW,GAAG,OAAO,CAAC;AACxB;;AC1BA;;;;;;;;;;;;;;;AAeG;AAIH;;;;;;;;AAQG;MACU,iBAAiB,CAAA;AAI5B;;AAEG;AACH,IAAA,WAAA,CAAoB,WAAoB,EAAA;QAApB,IAAW,CAAA,WAAA,GAAX,WAAW,CAAS;;QALhC,IAAO,CAAA,OAAA,GAAG,WAAW,CAAC;KAKc;AAE5C;;;AAGG;IACH,GAAG,CAAC,GAAW,EAAE,KAAqB,EAAA;AACpC,QAAA,IAAI,KAAK,IAAI,IAAI,EAAE;AACjB,YAAA,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC;SACtD;aAAM;AACL,YAAA,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,EAAEA,cAAS,CAAC,KAAK,CAAC,CAAC,CAAC;SACrE;KACF;AAED;;AAEG;AACH,IAAA,GAAG,CAAC,GAAW,EAAA;AACb,QAAA,MAAM,SAAS,GAAG,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC;AACpE,QAAA,IAAI,SAAS,IAAI,IAAI,EAAE;AACrB,YAAA,OAAO,IAAI,CAAC;SACb;aAAM;AACL,YAAA,OAAOC,aAAQ,CAAC,SAAS,CAAC,CAAC;SAC5B;KACF;AAED,IAAA,M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C;IACzE,MAAM,YAAY,GAAG,IAAIC,kBAAQ,CAC/B,eAAe,EACf,kBAAkB,CACnB,CAAC;AACF,IAAA,IAAI,gBAAyD,CAAC;IAC9D,IAAI,kBAAkB,EAAE;QACtB,gBAAgB,GAAG,IAAIA,kBAAQ,CAC7B,oBAAoB,EACpB,kBAAkB,CACnB,CAAC;AACF,QAAA,gBAAgB,CAAC,YAAY,CAC3B,IAAIH,mBAAS,CACX,oBAAoB,EACpB,MAAM,kBAAkB,EAAA,SAAA,6BAEzB,CACF,CAAC;KACH;AACD,IAAA,YAAY,CAAC,YAAY,CACvB,IAAIA,mBAAS,CAAC,eAAe,EAAE,MAAM,cAAc,EAAA,SAAA,6BAAwB,CAC5E,CAAC;AAEF,IAAA,OAAO,0BAA0B,CAC/B,GAAG,EACH,YAAY,EACZ,gBAAgB,EAChB,GAAG,EACH,SAAS,CACV,CAAC;AACJ;;AClGA;;;;AAIG;AAwBH,gBAAgB,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@firebase/database/dist/index.esm.js b/node_modules/@firebase/database/dist/index.esm.js new file mode 100644 index 0000000..f38d894 --- /dev/null +++ b/node_modules/@firebase/database/dist/index.esm.js @@ -0,0 +1,14032 @@ +import { _isFirebaseServerApp, _getProvider, getApp, SDK_VERSION as SDK_VERSION$1, _registerComponent, registerVersion } from '@firebase/app'; +import { Component, ComponentContainer, Provider } from '@firebase/component'; +import { stringify, jsonEval, contains, assert, isNodeSdk, stringToByteArray, Sha1, base64, deepCopy, base64Encode, isMobileCordova, stringLength, Deferred, safeGet, isAdmin, isValidFormat, isEmpty, isReactNative, assertionError, map, querystring, errorPrefix, getModularInstance, getDefaultEmulatorHostnameAndPort, deepEqual, createMockUserToken, isCloudWorkstation, pingServer, updateEmulatorBanner } from '@firebase/util'; +import { Logger, LogLevel } from '@firebase/logger'; + +const name = "@firebase/database"; +const version = "1.1.0"; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The semver (www.semver.org) version of the SDK. */ +let SDK_VERSION = ''; +/** + * SDK_VERSION should be set before any database instance is created + * @internal + */ +function setSDKVersion(version) { + SDK_VERSION = version; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Wraps a DOM Storage object and: + * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types. + * - prefixes names with "firebase:" to avoid collisions with app data. + * + * We automatically (see storage.js) create two such wrappers, one for sessionStorage, + * and one for localStorage. + * + */ +class DOMStorageWrapper { + /** + * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage) + */ + constructor(domStorage_) { + this.domStorage_ = domStorage_; + // Use a prefix to avoid collisions with other stuff saved by the app. + this.prefix_ = 'firebase:'; + } + /** + * @param key - The key to save the value under + * @param value - The value being stored, or null to remove the key. + */ + set(key, value) { + if (value == null) { + this.domStorage_.removeItem(this.prefixedName_(key)); + } + else { + this.domStorage_.setItem(this.prefixedName_(key), stringify(value)); + } + } + /** + * @returns The value that was stored under this key, or null + */ + get(key) { + const storedVal = this.domStorage_.getItem(this.prefixedName_(key)); + if (storedVal == null) { + return null; + } + else { + return jsonEval(storedVal); + } + } + remove(key) { + this.domStorage_.removeItem(this.prefixedName_(key)); + } + prefixedName_(name) { + return this.prefix_ + name; + } + toString() { + return this.domStorage_.toString(); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory storage implementation that matches the API of DOMStorageWrapper + * (TODO: create interface for both to implement). + */ +class MemoryStorage { + constructor() { + this.cache_ = {}; + this.isInMemoryStorage = true; + } + set(key, value) { + if (value == null) { + delete this.cache_[key]; + } + else { + this.cache_[key] = value; + } + } + get(key) { + if (contains(this.cache_, key)) { + return this.cache_[key]; + } + return null; + } + remove(key) { + delete this.cache_[key]; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage. + * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change + * to reflect this type + * + * @param domStorageName - Name of the underlying storage object + * (e.g. 'localStorage' or 'sessionStorage'). + * @returns Turning off type information until a common interface is defined. + */ +const createStoragefor = function (domStorageName) { + try { + // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception, + // so it must be inside the try/catch. + if (typeof window !== 'undefined' && + typeof window[domStorageName] !== 'undefined') { + // Need to test cache. Just because it's here doesn't mean it works + const domStorage = window[domStorageName]; + domStorage.setItem('firebase:sentinel', 'cache'); + domStorage.removeItem('firebase:sentinel'); + return new DOMStorageWrapper(domStorage); + } + } + catch (e) { } + // Failed to create wrapper. Just return in-memory storage. + // TODO: log? + return new MemoryStorage(); +}; +/** A storage object that lasts across sessions */ +const PersistentStorage = createStoragefor('localStorage'); +/** A storage object that only lasts one session */ +const SessionStorage = createStoragefor('sessionStorage'); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const logClient = new Logger('@firebase/database'); +/** + * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called). + */ +const LUIDGenerator = (function () { + let id = 1; + return function () { + return id++; + }; +})(); +/** + * Sha1 hash of the input string + * @param str - The string to hash + * @returns {!string} The resulting hash + */ +const sha1 = function (str) { + const utf8Bytes = stringToByteArray(str); + const sha1 = new Sha1(); + sha1.update(utf8Bytes); + const sha1Bytes = sha1.digest(); + return base64.encodeByteArray(sha1Bytes); +}; +const buildLogMessage_ = function (...varArgs) { + let message = ''; + for (let i = 0; i < varArgs.length; i++) { + const arg = varArgs[i]; + if (Array.isArray(arg) || + (arg && + typeof arg === 'object' && + // eslint-disable-next-line @typescript-eslint/no-explicit-any + typeof arg.length === 'number')) { + message += buildLogMessage_.apply(null, arg); + } + else if (typeof arg === 'object') { + message += stringify(arg); + } + else { + message += arg; + } + message += ' '; + } + return message; +}; +/** + * Use this for all debug messages in Firebase. + */ +let logger = null; +/** + * Flag to check for log availability on first log message + */ +let firstLog_ = true; +/** + * The implementation of Firebase.enableLogging (defined here to break dependencies) + * @param logger_ - A flag to turn on logging, or a custom logger + * @param persistent - Whether or not to persist logging settings across refreshes + */ +const enableLogging$1 = function (logger_, persistent) { + assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently."); + if (logger_ === true) { + logClient.logLevel = LogLevel.VERBOSE; + logger = logClient.log.bind(logClient); + if (persistent) { + SessionStorage.set('logging_enabled', true); + } + } + else if (typeof logger_ === 'function') { + logger = logger_; + } + else { + logger = null; + SessionStorage.remove('logging_enabled'); + } +}; +const log = function (...varArgs) { + if (firstLog_ === true) { + firstLog_ = false; + if (logger === null && SessionStorage.get('logging_enabled') === true) { + enableLogging$1(true); + } + } + if (logger) { + const message = buildLogMessage_.apply(null, varArgs); + logger(message); + } +}; +const logWrapper = function (prefix) { + return function (...varArgs) { + log(prefix, ...varArgs); + }; +}; +const error = function (...varArgs) { + const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs); + logClient.error(message); +}; +const fatal = function (...varArgs) { + const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`; + logClient.error(message); + throw new Error(message); +}; +const warn = function (...varArgs) { + const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs); + logClient.warn(message); +}; +/** + * Logs a warning if the containing page uses https. Called when a call to new Firebase + * does not use https. + */ +const warnIfPageIsSecure = function () { + // Be very careful accessing browser globals. Who knows what may or may not exist. + if (typeof window !== 'undefined' && + window.location && + window.location.protocol && + window.location.protocol.indexOf('https:') !== -1) { + warn('Insecure Firebase access from a secure page. ' + + 'Please use https in calls to new Firebase().'); + } +}; +/** + * Returns true if data is NaN, or +/- Infinity. + */ +const isInvalidJSONNumber = function (data) { + return (typeof data === 'number' && + (data !== data || // NaN + data === Number.POSITIVE_INFINITY || + data === Number.NEGATIVE_INFINITY)); +}; +const executeWhenDOMReady = function (fn) { + if (isNodeSdk() || document.readyState === 'complete') { + fn(); + } + else { + // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which + // fire before onload), but fall back to onload. + let called = false; + const wrappedFn = function () { + if (!document.body) { + setTimeout(wrappedFn, Math.floor(10)); + return; + } + if (!called) { + called = true; + fn(); + } + }; + if (document.addEventListener) { + document.addEventListener('DOMContentLoaded', wrappedFn, false); + // fallback to onload. + window.addEventListener('load', wrappedFn, false); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (document.attachEvent) { + // IE. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + document.attachEvent('onreadystatechange', () => { + if (document.readyState === 'complete') { + wrappedFn(); + } + }); + // fallback to onload. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + window.attachEvent('onload', wrappedFn); + // jQuery has an extra hack for IE that we could employ (based on + // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old. + // I'm hoping we don't need it. + } + } +}; +/** + * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names + */ +const MIN_NAME = '[MIN_NAME]'; +/** + * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names + */ +const MAX_NAME = '[MAX_NAME]'; +/** + * Compares valid Firebase key names, plus min and max name + */ +const nameCompare = function (a, b) { + if (a === b) { + return 0; + } + else if (a === MIN_NAME || b === MAX_NAME) { + return -1; + } + else if (b === MIN_NAME || a === MAX_NAME) { + return 1; + } + else { + const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b); + if (aAsInt !== null) { + if (bAsInt !== null) { + return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt; + } + else { + return -1; + } + } + else if (bAsInt !== null) { + return 1; + } + else { + return a < b ? -1 : 1; + } + } +}; +/** + * @returns {!number} comparison result. + */ +const stringCompare = function (a, b) { + if (a === b) { + return 0; + } + else if (a < b) { + return -1; + } + else { + return 1; + } +}; +const requireKey = function (key, obj) { + if (obj && key in obj) { + return obj[key]; + } + else { + throw new Error('Missing required key (' + key + ') in object: ' + stringify(obj)); + } +}; +const ObjectToUniqueKey = function (obj) { + if (typeof obj !== 'object' || obj === null) { + return stringify(obj); + } + const keys = []; + // eslint-disable-next-line guard-for-in + for (const k in obj) { + keys.push(k); + } + // Export as json, but with the keys sorted. + keys.sort(); + let key = '{'; + for (let i = 0; i < keys.length; i++) { + if (i !== 0) { + key += ','; + } + key += stringify(keys[i]); + key += ':'; + key += ObjectToUniqueKey(obj[keys[i]]); + } + key += '}'; + return key; +}; +/** + * Splits a string into a number of smaller segments of maximum size + * @param str - The string + * @param segsize - The maximum number of chars in the string. + * @returns The string, split into appropriately-sized chunks + */ +const splitStringBySize = function (str, segsize) { + const len = str.length; + if (len <= segsize) { + return [str]; + } + const dataSegs = []; + for (let c = 0; c < len; c += segsize) { + if (c + segsize > len) { + dataSegs.push(str.substring(c, len)); + } + else { + dataSegs.push(str.substring(c, c + segsize)); + } + } + return dataSegs; +}; +/** + * Apply a function to each (key, value) pair in an object or + * apply a function to each (index, value) pair in an array + * @param obj - The object or array to iterate over + * @param fn - The function to apply + */ +function each(obj, fn) { + for (const key in obj) { + if (obj.hasOwnProperty(key)) { + fn(key, obj[key]); + } + } +} +/** + * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License) + * I made one modification at the end and removed the NaN / Infinity + * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments. + * @param v - A double + * + */ +const doubleToIEEE754String = function (v) { + assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL + const ebits = 11, fbits = 52; + const bias = (1 << (ebits - 1)) - 1; + let s, e, f, ln, i; + // Compute sign, exponent, fraction + // Skip NaN / Infinity handling --MJL. + if (v === 0) { + e = 0; + f = 0; + s = 1 / v === -Infinity ? 1 : 0; + } + else { + s = v < 0; + v = Math.abs(v); + if (v >= Math.pow(2, 1 - bias)) { + // Normalized + ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias); + e = ln + bias; + f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits)); + } + else { + // Denormalized + e = 0; + f = Math.round(v / Math.pow(2, 1 - bias - fbits)); + } + } + // Pack sign, exponent, fraction + const bits = []; + for (i = fbits; i; i -= 1) { + bits.push(f % 2 ? 1 : 0); + f = Math.floor(f / 2); + } + for (i = ebits; i; i -= 1) { + bits.push(e % 2 ? 1 : 0); + e = Math.floor(e / 2); + } + bits.push(s ? 1 : 0); + bits.reverse(); + const str = bits.join(''); + // Return the data as a hex string. --MJL + let hexByteString = ''; + for (i = 0; i < 64; i += 8) { + let hexByte = parseInt(str.substr(i, 8), 2).toString(16); + if (hexByte.length === 1) { + hexByte = '0' + hexByte; + } + hexByteString = hexByteString + hexByte; + } + return hexByteString.toLowerCase(); +}; +/** + * Used to detect if we're in a Chrome content script (which executes in an + * isolated environment where long-polling doesn't work). + */ +const isChromeExtensionContentScript = function () { + return !!(typeof window === 'object' && + window['chrome'] && + window['chrome']['extension'] && + !/^chrome/.test(window.location.href)); +}; +/** + * Used to detect if we're in a Windows 8 Store app. + */ +const isWindowsStoreApp = function () { + // Check for the presence of a couple WinRT globals + return typeof Windows === 'object' && typeof Windows.UI === 'object'; +}; +/** + * Converts a server error code to a JavaScript Error + */ +function errorForServerCode(code, query) { + let reason = 'Unknown Error'; + if (code === 'too_big') { + reason = + 'The data requested exceeds the maximum size ' + + 'that can be accessed with a single request.'; + } + else if (code === 'permission_denied') { + reason = "Client doesn't have permission to access the desired data."; + } + else if (code === 'unavailable') { + reason = 'The service is unavailable'; + } + const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error.code = code.toUpperCase(); + return error; +} +/** + * Used to test for integer-looking strings + */ +const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$'); +/** + * For use in keys, the minimum possible 32-bit integer. + */ +const INTEGER_32_MIN = -2147483648; +/** + * For use in keys, the maximum possible 32-bit integer. + */ +const INTEGER_32_MAX = 2147483647; +/** + * If the string contains a 32-bit integer, return it. Else return null. + */ +const tryParseInt = function (str) { + if (INTEGER_REGEXP_.test(str)) { + const intVal = Number(str); + if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) { + return intVal; + } + } + return null; +}; +/** + * Helper to run some code but catch any exceptions and re-throw them later. + * Useful for preventing user callbacks from breaking internal code. + * + * Re-throwing the exception from a setTimeout is a little evil, but it's very + * convenient (we don't have to try to figure out when is a safe point to + * re-throw it), and the behavior seems reasonable: + * + * * If you aren't pausing on exceptions, you get an error in the console with + * the correct stack trace. + * * If you're pausing on all exceptions, the debugger will pause on your + * exception and then again when we rethrow it. + * * If you're only pausing on uncaught exceptions, the debugger will only pause + * on us re-throwing it. + * + * @param fn - The code to guard. + */ +const exceptionGuard = function (fn) { + try { + fn(); + } + catch (e) { + // Re-throw exception when it's safe. + setTimeout(() => { + // It used to be that "throw e" would result in a good console error with + // relevant context, but as of Chrome 39, you just get the firebase.js + // file/line number where we re-throw it, which is useless. So we log + // e.stack explicitly. + const stack = e.stack || ''; + warn('Exception was thrown by user callback.', stack); + throw e; + }, Math.floor(0)); + } +}; +/** + * @returns {boolean} true if we think we're currently being crawled. + */ +const beingCrawled = function () { + const userAgent = (typeof window === 'object' && + window['navigator'] && + window['navigator']['userAgent']) || + ''; + // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we + // believe to support JavaScript/AJAX rendering. + // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website + // would have seen the page" is flaky if we don't treat it as a crawler. + return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0); +}; +/** + * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting. + * + * It is removed with clearTimeout() as normal. + * + * @param fn - Function to run. + * @param time - Milliseconds to wait before running. + * @returns The setTimeout() return value. + */ +const setTimeoutNonBlocking = function (fn, time) { + const timeout = setTimeout(fn, time); + // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API. + if (typeof timeout === 'number' && + // @ts-ignore Is only defined in Deno environments. + typeof Deno !== 'undefined' && + // @ts-ignore Deno and unrefTimer are only defined in Deno environments. + Deno['unrefTimer']) { + // @ts-ignore Deno and unrefTimer are only defined in Deno environments. + Deno.unrefTimer(timeout); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (typeof timeout === 'object' && timeout['unref']) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + timeout['unref'](); + } + return timeout; +}; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Abstraction around AppCheck's token fetching capabilities. + */ +class AppCheckTokenProvider { + constructor(app, appCheckProvider) { + this.appCheckProvider = appCheckProvider; + this.appName = app.name; + if (_isFirebaseServerApp(app) && app.settings.appCheckToken) { + this.serverAppAppCheckToken = app.settings.appCheckToken; + } + this.appCheck = appCheckProvider?.getImmediate({ optional: true }); + if (!this.appCheck) { + appCheckProvider?.get().then(appCheck => (this.appCheck = appCheck)); + } + } + getToken(forceRefresh) { + if (this.serverAppAppCheckToken) { + if (forceRefresh) { + throw new Error('Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.'); + } + return Promise.resolve({ token: this.serverAppAppCheckToken }); + } + if (!this.appCheck) { + return new Promise((resolve, reject) => { + // Support delayed initialization of FirebaseAppCheck. This allows our + // customers to initialize the RTDB SDK before initializing Firebase + // AppCheck and ensures that all requests are authenticated if a token + // becomes available before the timeout below expires. + setTimeout(() => { + if (this.appCheck) { + this.getToken(forceRefresh).then(resolve, reject); + } + else { + resolve(null); + } + }, 0); + }); + } + return this.appCheck.getToken(forceRefresh); + } + addTokenChangeListener(listener) { + this.appCheckProvider + ?.get() + .then(appCheck => appCheck.addTokenListener(listener)); + } + notifyForInvalidToken() { + warn(`Provided AppCheck credentials for the app named "${this.appName}" ` + + 'are invalid. This usually indicates your app was not initialized correctly.'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Abstraction around FirebaseApp's token fetching capabilities. + */ +class FirebaseAuthTokenProvider { + constructor(appName_, firebaseOptions_, authProvider_) { + this.appName_ = appName_; + this.firebaseOptions_ = firebaseOptions_; + this.authProvider_ = authProvider_; + this.auth_ = null; + this.auth_ = authProvider_.getImmediate({ optional: true }); + if (!this.auth_) { + authProvider_.onInit(auth => (this.auth_ = auth)); + } + } + getToken(forceRefresh) { + if (!this.auth_) { + return new Promise((resolve, reject) => { + // Support delayed initialization of FirebaseAuth. This allows our + // customers to initialize the RTDB SDK before initializing Firebase + // Auth and ensures that all requests are authenticated if a token + // becomes available before the timeout below expires. + setTimeout(() => { + if (this.auth_) { + this.getToken(forceRefresh).then(resolve, reject); + } + else { + resolve(null); + } + }, 0); + }); + } + return this.auth_.getToken(forceRefresh).catch(error => { + // TODO: Need to figure out all the cases this is raised and whether + // this makes sense. + if (error && error.code === 'auth/token-not-initialized') { + log('Got auth/token-not-initialized error. Treating as null token.'); + return null; + } + else { + return Promise.reject(error); + } + }); + } + addTokenChangeListener(listener) { + // TODO: We might want to wrap the listener and call it with no args to + // avoid a leaky abstraction, but that makes removing the listener harder. + if (this.auth_) { + this.auth_.addAuthTokenListener(listener); + } + else { + this.authProvider_ + .get() + .then(auth => auth.addAuthTokenListener(listener)); + } + } + removeTokenChangeListener(listener) { + this.authProvider_ + .get() + .then(auth => auth.removeAuthTokenListener(listener)); + } + notifyForInvalidToken() { + let errorMessage = 'Provided authentication credentials for the app named "' + + this.appName_ + + '" are invalid. This usually indicates your app was not ' + + 'initialized correctly. '; + if ('credential' in this.firebaseOptions_) { + errorMessage += + 'Make sure the "credential" property provided to initializeApp() ' + + 'is authorized to access the specified "databaseURL" and is from the correct ' + + 'project.'; + } + else if ('serviceAccount' in this.firebaseOptions_) { + errorMessage += + 'Make sure the "serviceAccount" property provided to initializeApp() ' + + 'is authorized to access the specified "databaseURL" and is from the correct ' + + 'project.'; + } + else { + errorMessage += + 'Make sure the "apiKey" and "databaseURL" properties provided to ' + + 'initializeApp() match the values provided for your app at ' + + 'https://console.firebase.google.com/.'; + } + warn(errorMessage); + } +} +/* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */ +class EmulatorTokenProvider { + constructor(accessToken) { + this.accessToken = accessToken; + } + getToken(forceRefresh) { + return Promise.resolve({ + accessToken: this.accessToken + }); + } + addTokenChangeListener(listener) { + // Invoke the listener immediately to match the behavior in Firebase Auth + // (see packages/auth/src/auth.js#L1807) + listener(this.accessToken); + } + removeTokenChangeListener(listener) { } + notifyForInvalidToken() { } +} +/** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */ +EmulatorTokenProvider.OWNER = 'owner'; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const PROTOCOL_VERSION = '5'; +const VERSION_PARAM = 'v'; +const TRANSPORT_SESSION_PARAM = 's'; +const REFERER_PARAM = 'r'; +const FORGE_REF = 'f'; +// Matches console.firebase.google.com, firebase-console-*.corp.google.com and +// firebase.corp.google.com +const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/; +const LAST_SESSION_PARAM = 'ls'; +const APPLICATION_ID_PARAM = 'p'; +const APP_CHECK_TOKEN_PARAM = 'ac'; +const WEBSOCKET = 'websocket'; +const LONG_POLLING = 'long_polling'; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A class that holds metadata about a Repo object + */ +class RepoInfo { + /** + * @param host - Hostname portion of the url for the repo + * @param secure - Whether or not this repo is accessed over ssl + * @param namespace - The namespace represented by the repo + * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest). + * @param nodeAdmin - Whether this instance uses Admin SDK credentials + * @param persistenceKey - Override the default session persistence storage key + */ + constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false, isUsingEmulator = false, emulatorOptions = null) { + this.secure = secure; + this.namespace = namespace; + this.webSocketOnly = webSocketOnly; + this.nodeAdmin = nodeAdmin; + this.persistenceKey = persistenceKey; + this.includeNamespaceInQueryParams = includeNamespaceInQueryParams; + this.isUsingEmulator = isUsingEmulator; + this.emulatorOptions = emulatorOptions; + this._host = host.toLowerCase(); + this._domain = this._host.substr(this._host.indexOf('.') + 1); + this.internalHost = + PersistentStorage.get('host:' + host) || this._host; + } + isCacheableHost() { + return this.internalHost.substr(0, 2) === 's-'; + } + isCustomHost() { + return (this._domain !== 'firebaseio.com' && + this._domain !== 'firebaseio-demo.com'); + } + get host() { + return this._host; + } + set host(newHost) { + if (newHost !== this.internalHost) { + this.internalHost = newHost; + if (this.isCacheableHost()) { + PersistentStorage.set('host:' + this._host, this.internalHost); + } + } + } + toString() { + let str = this.toURLString(); + if (this.persistenceKey) { + str += '<' + this.persistenceKey + '>'; + } + return str; + } + toURLString() { + const protocol = this.secure ? 'https://' : 'http://'; + const query = this.includeNamespaceInQueryParams + ? `?ns=${this.namespace}` + : ''; + return `${protocol}${this.host}/${query}`; + } +} +function repoInfoNeedsQueryParam(repoInfo) { + return (repoInfo.host !== repoInfo.internalHost || + repoInfo.isCustomHost() || + repoInfo.includeNamespaceInQueryParams); +} +/** + * Returns the websocket URL for this repo + * @param repoInfo - RepoInfo object + * @param type - of connection + * @param params - list + * @returns The URL for this repo + */ +function repoInfoConnectionURL(repoInfo, type, params) { + assert(typeof type === 'string', 'typeof type must == string'); + assert(typeof params === 'object', 'typeof params must == object'); + let connURL; + if (type === WEBSOCKET) { + connURL = + (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?'; + } + else if (type === LONG_POLLING) { + connURL = + (repoInfo.secure ? 'https://' : 'http://') + + repoInfo.internalHost + + '/.lp?'; + } + else { + throw new Error('Unknown connection type: ' + type); + } + if (repoInfoNeedsQueryParam(repoInfo)) { + params['ns'] = repoInfo.namespace; + } + const pairs = []; + each(params, (key, value) => { + pairs.push(key + '=' + value); + }); + return connURL + pairs.join('&'); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Tracks a collection of stats. + */ +class StatsCollection { + constructor() { + this.counters_ = {}; + } + incrementCounter(name, amount = 1) { + if (!contains(this.counters_, name)) { + this.counters_[name] = 0; + } + this.counters_[name] += amount; + } + get() { + return deepCopy(this.counters_); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const collections = {}; +const reporters = {}; +function statsManagerGetCollection(repoInfo) { + const hashString = repoInfo.toString(); + if (!collections[hashString]) { + collections[hashString] = new StatsCollection(); + } + return collections[hashString]; +} +function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) { + const hashString = repoInfo.toString(); + if (!reporters[hashString]) { + reporters[hashString] = creatorFunction(); + } + return reporters[hashString]; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This class ensures the packets from the server arrive in order + * This class takes data from the server and ensures it gets passed into the callbacks in order. + */ +class PacketReceiver { + /** + * @param onMessage_ + */ + constructor(onMessage_) { + this.onMessage_ = onMessage_; + this.pendingResponses = []; + this.currentResponseNum = 0; + this.closeAfterResponse = -1; + this.onClose = null; + } + closeAfter(responseNum, callback) { + this.closeAfterResponse = responseNum; + this.onClose = callback; + if (this.closeAfterResponse < this.currentResponseNum) { + this.onClose(); + this.onClose = null; + } + } + /** + * Each message from the server comes with a response number, and an array of data. The responseNumber + * allows us to ensure that we process them in the right order, since we can't be guaranteed that all + * browsers will respond in the same order as the requests we sent + */ + handleResponse(requestNum, data) { + this.pendingResponses[requestNum] = data; + while (this.pendingResponses[this.currentResponseNum]) { + const toProcess = this.pendingResponses[this.currentResponseNum]; + delete this.pendingResponses[this.currentResponseNum]; + for (let i = 0; i < toProcess.length; ++i) { + if (toProcess[i]) { + exceptionGuard(() => { + this.onMessage_(toProcess[i]); + }); + } + } + if (this.currentResponseNum === this.closeAfterResponse) { + if (this.onClose) { + this.onClose(); + this.onClose = null; + } + break; + } + this.currentResponseNum++; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// URL query parameters associated with longpolling +const FIREBASE_LONGPOLL_START_PARAM = 'start'; +const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close'; +const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand'; +const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB'; +const FIREBASE_LONGPOLL_ID_PARAM = 'id'; +const FIREBASE_LONGPOLL_PW_PARAM = 'pw'; +const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser'; +const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb'; +const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg'; +const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts'; +const FIREBASE_LONGPOLL_DATA_PARAM = 'd'; +const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe'; +//Data size constants. +//TODO: Perf: the maximum length actually differs from browser to browser. +// We should check what browser we're on and set accordingly. +const MAX_URL_DATA_SIZE = 1870; +const SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d= +const MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE; +/** + * Keepalive period + * send a fresh request at minimum every 25 seconds. Opera has a maximum request + * length of 30 seconds that we can't exceed. + */ +const KEEPALIVE_REQUEST_INTERVAL = 25000; +/** + * How long to wait before aborting a long-polling connection attempt. + */ +const LP_CONNECT_TIMEOUT = 30000; +/** + * This class manages a single long-polling connection. + */ +class BrowserPollConnection { + /** + * @param connId An identifier for this connection, used for logging + * @param repoInfo The info for the endpoint to send data to. + * @param applicationId The Firebase App ID for this project. + * @param appCheckToken The AppCheck token for this client. + * @param authToken The AuthToken to use for this connection. + * @param transportSessionId Optional transportSessionid if we are + * reconnecting for an existing transport session + * @param lastSessionId Optional lastSessionId if the PersistentConnection has + * already created a connection previously + */ + constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) { + this.connId = connId; + this.repoInfo = repoInfo; + this.applicationId = applicationId; + this.appCheckToken = appCheckToken; + this.authToken = authToken; + this.transportSessionId = transportSessionId; + this.lastSessionId = lastSessionId; + this.bytesSent = 0; + this.bytesReceived = 0; + this.everConnected_ = false; + this.log_ = logWrapper(connId); + this.stats_ = statsManagerGetCollection(repoInfo); + this.urlFn = (params) => { + // Always add the token if we have one. + if (this.appCheckToken) { + params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken; + } + return repoInfoConnectionURL(repoInfo, LONG_POLLING, params); + }; + } + /** + * @param onMessage - Callback when messages arrive + * @param onDisconnect - Callback with connection lost. + */ + open(onMessage, onDisconnect) { + this.curSegmentNum = 0; + this.onDisconnect_ = onDisconnect; + this.myPacketOrderer = new PacketReceiver(onMessage); + this.isClosed_ = false; + this.connectTimeoutTimer_ = setTimeout(() => { + this.log_('Timed out trying to connect.'); + // Make sure we clear the host cache + this.onClosed_(); + this.connectTimeoutTimer_ = null; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(LP_CONNECT_TIMEOUT)); + // Ensure we delay the creation of the iframe until the DOM is loaded. + executeWhenDOMReady(() => { + if (this.isClosed_) { + return; + } + //Set up a callback that gets triggered once a connection is set up. + this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => { + const [command, arg1, arg2, arg3, arg4] = args; + this.incrementIncomingBytes_(args); + if (!this.scriptTagHolder) { + return; // we closed the connection. + } + if (this.connectTimeoutTimer_) { + clearTimeout(this.connectTimeoutTimer_); + this.connectTimeoutTimer_ = null; + } + this.everConnected_ = true; + if (command === FIREBASE_LONGPOLL_START_PARAM) { + this.id = arg1; + this.password = arg2; + } + else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) { + // Don't clear the host cache. We got a response from the server, so we know it's reachable + if (arg1) { + // We aren't expecting any more data (other than what the server's already in the process of sending us + // through our already open polls), so don't send any more. + this.scriptTagHolder.sendNewPolls = false; + // arg1 in this case is the last response number sent by the server. We should try to receive + // all of the responses up to this one before closing + this.myPacketOrderer.closeAfter(arg1, () => { + this.onClosed_(); + }); + } + else { + this.onClosed_(); + } + } + else { + throw new Error('Unrecognized command received: ' + command); + } + }, (...args) => { + const [pN, data] = args; + this.incrementIncomingBytes_(args); + this.myPacketOrderer.handleResponse(pN, data); + }, () => { + this.onClosed_(); + }, this.urlFn); + //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results + //from cache. + const urlParams = {}; + urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't'; + urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000); + if (this.scriptTagHolder.uniqueCallbackIdentifier) { + urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = + this.scriptTagHolder.uniqueCallbackIdentifier; + } + urlParams[VERSION_PARAM] = PROTOCOL_VERSION; + if (this.transportSessionId) { + urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId; + } + if (this.lastSessionId) { + urlParams[LAST_SESSION_PARAM] = this.lastSessionId; + } + if (this.applicationId) { + urlParams[APPLICATION_ID_PARAM] = this.applicationId; + } + if (this.appCheckToken) { + urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken; + } + if (typeof location !== 'undefined' && + location.hostname && + FORGE_DOMAIN_RE.test(location.hostname)) { + urlParams[REFERER_PARAM] = FORGE_REF; + } + const connectURL = this.urlFn(urlParams); + this.log_('Connecting via long-poll to ' + connectURL); + this.scriptTagHolder.addTag(connectURL, () => { + /* do nothing */ + }); + }); + } + /** + * Call this when a handshake has completed successfully and we want to consider the connection established + */ + start() { + this.scriptTagHolder.startLongPoll(this.id, this.password); + this.addDisconnectPingFrame(this.id, this.password); + } + /** + * Forces long polling to be considered as a potential transport + */ + static forceAllow() { + BrowserPollConnection.forceAllow_ = true; + } + /** + * Forces longpolling to not be considered as a potential transport + */ + static forceDisallow() { + BrowserPollConnection.forceDisallow_ = true; + } + // Static method, use string literal so it can be accessed in a generic way + static isAvailable() { + if (isNodeSdk()) { + return false; + } + else if (BrowserPollConnection.forceAllow_) { + return true; + } + else { + // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in + // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08). + return (!BrowserPollConnection.forceDisallow_ && + typeof document !== 'undefined' && + document.createElement != null && + !isChromeExtensionContentScript() && + !isWindowsStoreApp()); + } + } + /** + * No-op for polling + */ + markConnectionHealthy() { } + /** + * Stops polling and cleans up the iframe + */ + shutdown_() { + this.isClosed_ = true; + if (this.scriptTagHolder) { + this.scriptTagHolder.close(); + this.scriptTagHolder = null; + } + //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving. + if (this.myDisconnFrame) { + document.body.removeChild(this.myDisconnFrame); + this.myDisconnFrame = null; + } + if (this.connectTimeoutTimer_) { + clearTimeout(this.connectTimeoutTimer_); + this.connectTimeoutTimer_ = null; + } + } + /** + * Triggered when this transport is closed + */ + onClosed_() { + if (!this.isClosed_) { + this.log_('Longpoll is closing itself'); + this.shutdown_(); + if (this.onDisconnect_) { + this.onDisconnect_(this.everConnected_); + this.onDisconnect_ = null; + } + } + } + /** + * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server + * that we've left. + */ + close() { + if (!this.isClosed_) { + this.log_('Longpoll is being closed.'); + this.shutdown_(); + } + } + /** + * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then + * broken into chunks (since URLs have a small maximum length). + * @param data - The JSON data to transmit. + */ + send(data) { + const dataStr = stringify(data); + this.bytesSent += dataStr.length; + this.stats_.incrementCounter('bytes_sent', dataStr.length); + //first, lets get the base64-encoded data + const base64data = base64Encode(dataStr); + //We can only fit a certain amount in each URL, so we need to split this request + //up into multiple pieces if it doesn't fit in one request. + const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE); + //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number + //of segments so that we can reassemble the packet on the server. + for (let i = 0; i < dataSegs.length; i++) { + this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]); + this.curSegmentNum++; + } + } + /** + * This is how we notify the server that we're leaving. + * We aren't able to send requests with DHTML on a window close event, but we can + * trigger XHR requests in some browsers (everything but Opera basically). + */ + addDisconnectPingFrame(id, pw) { + if (isNodeSdk()) { + return; + } + this.myDisconnFrame = document.createElement('iframe'); + const urlParams = {}; + urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't'; + urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id; + urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw; + this.myDisconnFrame.src = this.urlFn(urlParams); + this.myDisconnFrame.style.display = 'none'; + document.body.appendChild(this.myDisconnFrame); + } + /** + * Used to track the bytes received by this client + */ + incrementIncomingBytes_(args) { + // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in. + const bytesReceived = stringify(args).length; + this.bytesReceived += bytesReceived; + this.stats_.incrementCounter('bytes_received', bytesReceived); + } +} +/********************************************************************************************* + * A wrapper around an iframe that is used as a long-polling script holder. + *********************************************************************************************/ +class FirebaseIFrameScriptHolder { + /** + * @param commandCB - The callback to be called when control commands are received from the server. + * @param onMessageCB - The callback to be triggered when responses arrive from the server. + * @param onDisconnect - The callback to be triggered when this tag holder is closed + * @param urlFn - A function that provides the URL of the endpoint to send data to. + */ + constructor(commandCB, onMessageCB, onDisconnect, urlFn) { + this.onDisconnect = onDisconnect; + this.urlFn = urlFn; + //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause + //problems in some browsers. + this.outstandingRequests = new Set(); + //A queue of the pending segments waiting for transmission to the server. + this.pendingSegs = []; + //A serial number. We use this for two things: + // 1) A way to ensure the browser doesn't cache responses to polls + // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The + // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute + // JSONP code in the order it was added to the iframe. + this.currentSerial = Math.floor(Math.random() * 100000000); + // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still + // incoming data from the server that we're waiting for). + this.sendNewPolls = true; + if (!isNodeSdk()) { + //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the + //iframes where we put the long-polling script tags. We have two callbacks: + // 1) Command Callback - Triggered for control issues, like starting a connection. + // 2) Message Callback - Triggered when new data arrives. + this.uniqueCallbackIdentifier = LUIDGenerator(); + window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB; + window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = + onMessageCB; + //Create an iframe for us to add script tags to. + this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_(); + // Set the iframe's contents. + let script = ''; + // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient + // for ie9, but ie8 needs to do it again in the document itself. + if (this.myIFrame.src && + this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') { + const currentDomain = document.domain; + script = ''; + } + const iframeContents = '' + script + ''; + try { + this.myIFrame.doc.open(); + this.myIFrame.doc.write(iframeContents); + this.myIFrame.doc.close(); + } + catch (e) { + log('frame writing exception'); + if (e.stack) { + log(e.stack); + } + log(e); + } + } + else { + this.commandCB = commandCB; + this.onMessageCB = onMessageCB; + } + } + /** + * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can + * actually use. + */ + static createIFrame_() { + const iframe = document.createElement('iframe'); + iframe.style.display = 'none'; + // This is necessary in order to initialize the document inside the iframe + if (document.body) { + document.body.appendChild(iframe); + try { + // If document.domain has been modified in IE, this will throw an error, and we need to set the + // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute + // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work. + const a = iframe.contentWindow.document; + if (!a) { + // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above. + log('No IE domain setting required'); + } + } + catch (e) { + const domain = document.domain; + iframe.src = + "javascript:void((function(){document.open();document.domain='" + + domain + + "';document.close();})())"; + } + } + else { + // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this + // never gets hit. + throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.'; + } + // Get the document of the iframe in a browser-specific way. + if (iframe.contentDocument) { + iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari + } + else if (iframe.contentWindow) { + iframe.doc = iframe.contentWindow.document; // Internet Explorer + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (iframe.document) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + iframe.doc = iframe.document; //others? + } + return iframe; + } + /** + * Cancel all outstanding queries and remove the frame. + */ + close() { + //Mark this iframe as dead, so no new requests are sent. + this.alive = false; + if (this.myIFrame) { + //We have to actually remove all of the html inside this iframe before removing it from the + //window, or IE will continue loading and executing the script tags we've already added, which + //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this. + this.myIFrame.doc.body.textContent = ''; + setTimeout(() => { + if (this.myIFrame !== null) { + document.body.removeChild(this.myIFrame); + this.myIFrame = null; + } + }, Math.floor(0)); + } + // Protect from being called recursively. + const onDisconnect = this.onDisconnect; + if (onDisconnect) { + this.onDisconnect = null; + onDisconnect(); + } + } + /** + * Actually start the long-polling session by adding the first script tag(s) to the iframe. + * @param id - The ID of this connection + * @param pw - The password for this connection + */ + startLongPoll(id, pw) { + this.myID = id; + this.myPW = pw; + this.alive = true; + //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to. + while (this.newRequest_()) { } + } + /** + * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't + * too many outstanding requests and we are still alive. + * + * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if + * needed. + */ + newRequest_() { + // We keep one outstanding request open all the time to receive data, but if we need to send data + // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically + // close the old request. + if (this.alive && + this.sendNewPolls && + this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) { + //construct our url + this.currentSerial++; + const urlParams = {}; + urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID; + urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW; + urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial; + let theURL = this.urlFn(urlParams); + //Now add as much data as we can. + let curDataString = ''; + let i = 0; + while (this.pendingSegs.length > 0) { + //first, lets see if the next segment will fit. + const nextSeg = this.pendingSegs[0]; + if (nextSeg.d.length + + SEG_HEADER_SIZE + + curDataString.length <= + MAX_URL_DATA_SIZE) { + //great, the segment will fit. Lets append it. + const theSeg = this.pendingSegs.shift(); + curDataString = + curDataString + + '&' + + FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM + + i + + '=' + + theSeg.seg + + '&' + + FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET + + i + + '=' + + theSeg.ts + + '&' + + FIREBASE_LONGPOLL_DATA_PARAM + + i + + '=' + + theSeg.d; + i++; + } + else { + break; + } + } + theURL = theURL + curDataString; + this.addLongPollTag_(theURL, this.currentSerial); + return true; + } + else { + return false; + } + } + /** + * Queue a packet for transmission to the server. + * @param segnum - A sequential id for this packet segment used for reassembly + * @param totalsegs - The total number of segments in this packet + * @param data - The data for this segment. + */ + enqueueSegment(segnum, totalsegs, data) { + //add this to the queue of segments to send. + this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data }); + //send the data immediately if there isn't already data being transmitted, unless + //startLongPoll hasn't been called yet. + if (this.alive) { + this.newRequest_(); + } + } + /** + * Add a script tag for a regular long-poll request. + * @param url - The URL of the script tag. + * @param serial - The serial number of the request. + */ + addLongPollTag_(url, serial) { + //remember that we sent this request. + this.outstandingRequests.add(serial); + const doNewRequest = () => { + this.outstandingRequests.delete(serial); + this.newRequest_(); + }; + // If this request doesn't return on its own accord (by the server sending us some data), we'll + // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open. + const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL)); + const readyStateCB = () => { + // Request completed. Cancel the keepalive. + clearTimeout(keepaliveTimeout); + // Trigger a new request so we can continue receiving data. + doNewRequest(); + }; + this.addTag(url, readyStateCB); + } + /** + * Add an arbitrary script tag to the iframe. + * @param url - The URL for the script tag source. + * @param loadCB - A callback to be triggered once the script has loaded. + */ + addTag(url, loadCB) { + if (isNodeSdk()) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.doNodeLongPoll(url, loadCB); + } + else { + setTimeout(() => { + try { + // if we're already closed, don't add this poll + if (!this.sendNewPolls) { + return; + } + const newScript = this.myIFrame.doc.createElement('script'); + newScript.type = 'text/javascript'; + newScript.async = true; + newScript.src = url; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + newScript.onload = newScript.onreadystatechange = + function () { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const rstate = newScript.readyState; + if (!rstate || rstate === 'loaded' || rstate === 'complete') { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + newScript.onload = newScript.onreadystatechange = null; + if (newScript.parentNode) { + newScript.parentNode.removeChild(newScript); + } + loadCB(); + } + }; + newScript.onerror = () => { + log('Long-poll script failed to load: ' + url); + this.sendNewPolls = false; + this.close(); + }; + this.myIFrame.doc.body.appendChild(newScript); + } + catch (e) { + // TODO: we should make this error visible somehow + } + }, Math.floor(1)); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const WEBSOCKET_MAX_FRAME_SIZE = 16384; +const WEBSOCKET_KEEPALIVE_INTERVAL = 45000; +let WebSocketImpl = null; +if (typeof MozWebSocket !== 'undefined') { + WebSocketImpl = MozWebSocket; +} +else if (typeof WebSocket !== 'undefined') { + WebSocketImpl = WebSocket; +} +/** + * Create a new websocket connection with the given callbacks. + */ +class WebSocketConnection { + /** + * @param connId identifier for this transport + * @param repoInfo The info for the websocket endpoint. + * @param applicationId The Firebase App ID for this project. + * @param appCheckToken The App Check Token for this client. + * @param authToken The Auth Token for this client. + * @param transportSessionId Optional transportSessionId if this is connecting + * to an existing transport session + * @param lastSessionId Optional lastSessionId if there was a previous + * connection + */ + constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) { + this.connId = connId; + this.applicationId = applicationId; + this.appCheckToken = appCheckToken; + this.authToken = authToken; + this.keepaliveTimer = null; + this.frames = null; + this.totalFrames = 0; + this.bytesSent = 0; + this.bytesReceived = 0; + this.log_ = logWrapper(this.connId); + this.stats_ = statsManagerGetCollection(repoInfo); + this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId); + this.nodeAdmin = repoInfo.nodeAdmin; + } + /** + * @param repoInfo - The info for the websocket endpoint. + * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport + * session + * @param lastSessionId - Optional lastSessionId if there was a previous connection + * @returns connection url + */ + static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) { + const urlParams = {}; + urlParams[VERSION_PARAM] = PROTOCOL_VERSION; + if (!isNodeSdk() && + typeof location !== 'undefined' && + location.hostname && + FORGE_DOMAIN_RE.test(location.hostname)) { + urlParams[REFERER_PARAM] = FORGE_REF; + } + if (transportSessionId) { + urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId; + } + if (lastSessionId) { + urlParams[LAST_SESSION_PARAM] = lastSessionId; + } + if (appCheckToken) { + urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken; + } + if (applicationId) { + urlParams[APPLICATION_ID_PARAM] = applicationId; + } + return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams); + } + /** + * @param onMessage - Callback when messages arrive + * @param onDisconnect - Callback with connection lost. + */ + open(onMessage, onDisconnect) { + this.onDisconnect = onDisconnect; + this.onMessage = onMessage; + this.log_('Websocket connecting to ' + this.connURL); + this.everConnected_ = false; + // Assume failure until proven otherwise. + PersistentStorage.set('previous_websocket_failure', true); + try { + let options; + if (isNodeSdk()) { + const device = this.nodeAdmin ? 'AdminNode' : 'Node'; + // UA Format: Firebase//// + options = { + headers: { + 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`, + 'X-Firebase-GMPID': this.applicationId || '' + } + }; + // If using Node with admin creds, AppCheck-related checks are unnecessary. + // Note that we send the credentials here even if they aren't admin credentials, which is + // not a problem. + // Note that this header is just used to bypass appcheck, and the token should still be sent + // through the websocket connection once it is established. + if (this.authToken) { + options.headers['Authorization'] = `Bearer ${this.authToken}`; + } + if (this.appCheckToken) { + options.headers['X-Firebase-AppCheck'] = this.appCheckToken; + } + // Plumb appropriate http_proxy environment variable into faye-websocket if it exists. + const env = process['env']; + const proxy = this.connURL.indexOf('wss://') === 0 + ? env['HTTPS_PROXY'] || env['https_proxy'] + : env['HTTP_PROXY'] || env['http_proxy']; + if (proxy) { + options['proxy'] = { origin: proxy }; + } + } + this.mySock = new WebSocketImpl(this.connURL, [], options); + } + catch (e) { + this.log_('Error instantiating WebSocket.'); + const error = e.message || e.data; + if (error) { + this.log_(error); + } + this.onClosed_(); + return; + } + this.mySock.onopen = () => { + this.log_('Websocket connected.'); + this.everConnected_ = true; + }; + this.mySock.onclose = () => { + this.log_('Websocket connection was disconnected.'); + this.mySock = null; + this.onClosed_(); + }; + this.mySock.onmessage = m => { + this.handleIncomingFrame(m); + }; + this.mySock.onerror = e => { + this.log_('WebSocket error. Closing connection.'); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const error = e.message || e.data; + if (error) { + this.log_(error); + } + this.onClosed_(); + }; + } + /** + * No-op for websockets, we don't need to do anything once the connection is confirmed as open + */ + start() { } + static forceDisallow() { + WebSocketConnection.forceDisallow_ = true; + } + static isAvailable() { + let isOldAndroid = false; + if (typeof navigator !== 'undefined' && navigator.userAgent) { + const oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/; + const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex); + if (oldAndroidMatch && oldAndroidMatch.length > 1) { + if (parseFloat(oldAndroidMatch[1]) < 4.4) { + isOldAndroid = true; + } + } + } + return (!isOldAndroid && + WebSocketImpl !== null && + !WebSocketConnection.forceDisallow_); + } + /** + * Returns true if we previously failed to connect with this transport. + */ + static previouslyFailed() { + // If our persistent storage is actually only in-memory storage, + // we default to assuming that it previously failed to be safe. + return (PersistentStorage.isInMemoryStorage || + PersistentStorage.get('previous_websocket_failure') === true); + } + markConnectionHealthy() { + PersistentStorage.remove('previous_websocket_failure'); + } + appendFrame_(data) { + this.frames.push(data); + if (this.frames.length === this.totalFrames) { + const fullMess = this.frames.join(''); + this.frames = null; + const jsonMess = jsonEval(fullMess); + //handle the message + this.onMessage(jsonMess); + } + } + /** + * @param frameCount - The number of frames we are expecting from the server + */ + handleNewFrameCount_(frameCount) { + this.totalFrames = frameCount; + this.frames = []; + } + /** + * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1 + * @returns Any remaining data to be process, or null if there is none + */ + extractFrameCount_(data) { + assert(this.frames === null, 'We already have a frame buffer'); + // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced + // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508 + if (data.length <= 6) { + const frameCount = Number(data); + if (!isNaN(frameCount)) { + this.handleNewFrameCount_(frameCount); + return null; + } + } + this.handleNewFrameCount_(1); + return data; + } + /** + * Process a websocket frame that has arrived from the server. + * @param mess - The frame data + */ + handleIncomingFrame(mess) { + if (this.mySock === null) { + return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes. + } + const data = mess['data']; + this.bytesReceived += data.length; + this.stats_.incrementCounter('bytes_received', data.length); + this.resetKeepAlive(); + if (this.frames !== null) { + // we're buffering + this.appendFrame_(data); + } + else { + // try to parse out a frame count, otherwise, assume 1 and process it + const remainingData = this.extractFrameCount_(data); + if (remainingData !== null) { + this.appendFrame_(remainingData); + } + } + } + /** + * Send a message to the server + * @param data - The JSON object to transmit + */ + send(data) { + this.resetKeepAlive(); + const dataStr = stringify(data); + this.bytesSent += dataStr.length; + this.stats_.incrementCounter('bytes_sent', dataStr.length); + //We can only fit a certain amount in each websocket frame, so we need to split this request + //up into multiple pieces if it doesn't fit in one request. + const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE); + //Send the length header + if (dataSegs.length > 1) { + this.sendString_(String(dataSegs.length)); + } + //Send the actual data in segments. + for (let i = 0; i < dataSegs.length; i++) { + this.sendString_(dataSegs[i]); + } + } + shutdown_() { + this.isClosed_ = true; + if (this.keepaliveTimer) { + clearInterval(this.keepaliveTimer); + this.keepaliveTimer = null; + } + if (this.mySock) { + this.mySock.close(); + this.mySock = null; + } + } + onClosed_() { + if (!this.isClosed_) { + this.log_('WebSocket is closing itself'); + this.shutdown_(); + // since this is an internal close, trigger the close listener + if (this.onDisconnect) { + this.onDisconnect(this.everConnected_); + this.onDisconnect = null; + } + } + } + /** + * External-facing close handler. + * Close the websocket and kill the connection. + */ + close() { + if (!this.isClosed_) { + this.log_('WebSocket is being closed'); + this.shutdown_(); + } + } + /** + * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after + * the last activity. + */ + resetKeepAlive() { + clearInterval(this.keepaliveTimer); + this.keepaliveTimer = setInterval(() => { + //If there has been no websocket activity for a while, send a no-op + if (this.mySock) { + this.sendString_('0'); + } + this.resetKeepAlive(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL)); + } + /** + * Send a string over the websocket. + * + * @param str - String to send. + */ + sendString_(str) { + // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send() + // calls for some unknown reason. We treat these as an error and disconnect. + // See https://app.asana.com/0/58926111402292/68021340250410 + try { + this.mySock.send(str); + } + catch (e) { + this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.'); + setTimeout(this.onClosed_.bind(this), 0); + } + } +} +/** + * Number of response before we consider the connection "healthy." + */ +WebSocketConnection.responsesRequiredToBeHealthy = 2; +/** + * Time to wait for the connection te become healthy before giving up. + */ +WebSocketConnection.healthyTimeout = 30000; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Currently simplistic, this class manages what transport a Connection should use at various stages of its + * lifecycle. + * + * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if + * they are available. + */ +class TransportManager { + static get ALL_TRANSPORTS() { + return [BrowserPollConnection, WebSocketConnection]; + } + /** + * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after + * TransportManager has already set up transports_ + */ + static get IS_TRANSPORT_INITIALIZED() { + return this.globalTransportInitialized_; + } + /** + * @param repoInfo - Metadata around the namespace we're connecting to + */ + constructor(repoInfo) { + this.initTransports_(repoInfo); + } + initTransports_(repoInfo) { + const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable'](); + let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed(); + if (repoInfo.webSocketOnly) { + if (!isWebSocketsAvailable) { + warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway."); + } + isSkipPollConnection = true; + } + if (isSkipPollConnection) { + this.transports_ = [WebSocketConnection]; + } + else { + const transports = (this.transports_ = []); + for (const transport of TransportManager.ALL_TRANSPORTS) { + if (transport && transport['isAvailable']()) { + transports.push(transport); + } + } + TransportManager.globalTransportInitialized_ = true; + } + } + /** + * @returns The constructor for the initial transport to use + */ + initialTransport() { + if (this.transports_.length > 0) { + return this.transports_[0]; + } + else { + throw new Error('No transports available'); + } + } + /** + * @returns The constructor for the next transport, or null + */ + upgradeTransport() { + if (this.transports_.length > 1) { + return this.transports_[1]; + } + else { + return null; + } + } +} +// Keeps track of whether the TransportManager has already chosen a transport to use +TransportManager.globalTransportInitialized_ = false; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Abort upgrade attempt if it takes longer than 60s. +const UPGRADE_TIMEOUT = 60000; +// For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses. +// If we haven't sent enough requests within 5s, we'll start sending noop ping requests. +const DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000; +// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data) +// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout +// but we've sent/received enough bytes, we don't cancel the connection. +const BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024; +const BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024; +const MESSAGE_TYPE = 't'; +const MESSAGE_DATA = 'd'; +const CONTROL_SHUTDOWN = 's'; +const CONTROL_RESET = 'r'; +const CONTROL_ERROR = 'e'; +const CONTROL_PONG = 'o'; +const SWITCH_ACK = 'a'; +const END_TRANSMISSION = 'n'; +const PING = 'p'; +const SERVER_HELLO = 'h'; +/** + * Creates a new real-time connection to the server using whichever method works + * best in the current browser. + */ +class Connection { + /** + * @param id - an id for this connection + * @param repoInfo_ - the info for the endpoint to connect to + * @param applicationId_ - the Firebase App ID for this project + * @param appCheckToken_ - The App Check Token for this device. + * @param authToken_ - The auth token for this session. + * @param onMessage_ - the callback to be triggered when a server-push message arrives + * @param onReady_ - the callback to be triggered when this connection is ready to send messages. + * @param onDisconnect_ - the callback to be triggered when a connection was lost + * @param onKill_ - the callback to be triggered when this connection has permanently shut down. + * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server + */ + constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) { + this.id = id; + this.repoInfo_ = repoInfo_; + this.applicationId_ = applicationId_; + this.appCheckToken_ = appCheckToken_; + this.authToken_ = authToken_; + this.onMessage_ = onMessage_; + this.onReady_ = onReady_; + this.onDisconnect_ = onDisconnect_; + this.onKill_ = onKill_; + this.lastSessionId = lastSessionId; + this.connectionCount = 0; + this.pendingDataMessages = []; + this.state_ = 0 /* RealtimeState.CONNECTING */; + this.log_ = logWrapper('c:' + this.id + ':'); + this.transportManager_ = new TransportManager(repoInfo_); + this.log_('Connection created'); + this.start_(); + } + /** + * Starts a connection attempt + */ + start_() { + const conn = this.transportManager_.initialTransport(); + this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId); + // For certain transports (WebSockets), we need to send and receive several messages back and forth before we + // can consider the transport healthy. + this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0; + const onMessageReceived = this.connReceiver_(this.conn_); + const onConnectionLost = this.disconnReceiver_(this.conn_); + this.tx_ = this.conn_; + this.rx_ = this.conn_; + this.secondaryConn_ = null; + this.isHealthy_ = false; + /* + * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame. + * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset. + * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should + * still have the context of your originating frame. + */ + setTimeout(() => { + // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it + this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost); + }, Math.floor(0)); + const healthyTimeoutMS = conn['healthyTimeout'] || 0; + if (healthyTimeoutMS > 0) { + this.healthyTimeout_ = setTimeoutNonBlocking(() => { + this.healthyTimeout_ = null; + if (!this.isHealthy_) { + if (this.conn_ && + this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) { + this.log_('Connection exceeded healthy timeout but has received ' + + this.conn_.bytesReceived + + ' bytes. Marking connection healthy.'); + this.isHealthy_ = true; + this.conn_.markConnectionHealthy(); + } + else if (this.conn_ && + this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) { + this.log_('Connection exceeded healthy timeout but has sent ' + + this.conn_.bytesSent + + ' bytes. Leaving connection alive.'); + // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to + // the server. + } + else { + this.log_('Closing unhealthy connection after timeout.'); + this.close(); + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(healthyTimeoutMS)); + } + } + nextTransportId_() { + return 'c:' + this.id + ':' + this.connectionCount++; + } + disconnReceiver_(conn) { + return everConnected => { + if (conn === this.conn_) { + this.onConnectionLost_(everConnected); + } + else if (conn === this.secondaryConn_) { + this.log_('Secondary connection lost.'); + this.onSecondaryConnectionLost_(); + } + else { + this.log_('closing an old connection'); + } + }; + } + connReceiver_(conn) { + return (message) => { + if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) { + if (conn === this.rx_) { + this.onPrimaryMessageReceived_(message); + } + else if (conn === this.secondaryConn_) { + this.onSecondaryMessageReceived_(message); + } + else { + this.log_('message on old connection'); + } + } + }; + } + /** + * @param dataMsg - An arbitrary data message to be sent to the server + */ + sendRequest(dataMsg) { + // wrap in a data message envelope and send it on + const msg = { t: 'd', d: dataMsg }; + this.sendData_(msg); + } + tryCleanupConnection() { + if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) { + this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId); + this.conn_ = this.secondaryConn_; + this.secondaryConn_ = null; + // the server will shutdown the old connection + } + } + onSecondaryControl_(controlData) { + if (MESSAGE_TYPE in controlData) { + const cmd = controlData[MESSAGE_TYPE]; + if (cmd === SWITCH_ACK) { + this.upgradeIfSecondaryHealthy_(); + } + else if (cmd === CONTROL_RESET) { + // Most likely the session wasn't valid. Abandon the switch attempt + this.log_('Got a reset on secondary, closing it'); + this.secondaryConn_.close(); + // If we were already using this connection for something, than we need to fully close + if (this.tx_ === this.secondaryConn_ || + this.rx_ === this.secondaryConn_) { + this.close(); + } + } + else if (cmd === CONTROL_PONG) { + this.log_('got pong on secondary.'); + this.secondaryResponsesRequired_--; + this.upgradeIfSecondaryHealthy_(); + } + } + } + onSecondaryMessageReceived_(parsedData) { + const layer = requireKey('t', parsedData); + const data = requireKey('d', parsedData); + if (layer === 'c') { + this.onSecondaryControl_(data); + } + else if (layer === 'd') { + // got a data message, but we're still second connection. Need to buffer it up + this.pendingDataMessages.push(data); + } + else { + throw new Error('Unknown protocol layer: ' + layer); + } + } + upgradeIfSecondaryHealthy_() { + if (this.secondaryResponsesRequired_ <= 0) { + this.log_('Secondary connection is healthy.'); + this.isHealthy_ = true; + this.secondaryConn_.markConnectionHealthy(); + this.proceedWithUpgrade_(); + } + else { + // Send a ping to make sure the connection is healthy. + this.log_('sending ping on secondary.'); + this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } }); + } + } + proceedWithUpgrade_() { + // tell this connection to consider itself open + this.secondaryConn_.start(); + // send ack + this.log_('sending client ack on secondary'); + this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } }); + // send end packet on primary transport, switch to sending on this one + // can receive on this one, buffer responses until end received on primary transport + this.log_('Ending transmission on primary'); + this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } }); + this.tx_ = this.secondaryConn_; + this.tryCleanupConnection(); + } + onPrimaryMessageReceived_(parsedData) { + // Must refer to parsedData properties in quotes, so closure doesn't touch them. + const layer = requireKey('t', parsedData); + const data = requireKey('d', parsedData); + if (layer === 'c') { + this.onControl_(data); + } + else if (layer === 'd') { + this.onDataMessage_(data); + } + } + onDataMessage_(message) { + this.onPrimaryResponse_(); + // We don't do anything with data messages, just kick them up a level + this.onMessage_(message); + } + onPrimaryResponse_() { + if (!this.isHealthy_) { + this.primaryResponsesRequired_--; + if (this.primaryResponsesRequired_ <= 0) { + this.log_('Primary connection is healthy.'); + this.isHealthy_ = true; + this.conn_.markConnectionHealthy(); + } + } + } + onControl_(controlData) { + const cmd = requireKey(MESSAGE_TYPE, controlData); + if (MESSAGE_DATA in controlData) { + const payload = controlData[MESSAGE_DATA]; + if (cmd === SERVER_HELLO) { + const handshakePayload = { + ...payload + }; + if (this.repoInfo_.isUsingEmulator) { + // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes. + handshakePayload.h = this.repoInfo_.host; + } + this.onHandshake_(handshakePayload); + } + else if (cmd === END_TRANSMISSION) { + this.log_('recvd end transmission on primary'); + this.rx_ = this.secondaryConn_; + for (let i = 0; i < this.pendingDataMessages.length; ++i) { + this.onDataMessage_(this.pendingDataMessages[i]); + } + this.pendingDataMessages = []; + this.tryCleanupConnection(); + } + else if (cmd === CONTROL_SHUTDOWN) { + // This was previously the 'onKill' callback passed to the lower-level connection + // payload in this case is the reason for the shutdown. Generally a human-readable error + this.onConnectionShutdown_(payload); + } + else if (cmd === CONTROL_RESET) { + // payload in this case is the host we should contact + this.onReset_(payload); + } + else if (cmd === CONTROL_ERROR) { + error('Server Error: ' + payload); + } + else if (cmd === CONTROL_PONG) { + this.log_('got pong on primary.'); + this.onPrimaryResponse_(); + this.sendPingOnPrimaryIfNecessary_(); + } + else { + error('Unknown control packet command: ' + cmd); + } + } + } + /** + * @param handshake - The handshake data returned from the server + */ + onHandshake_(handshake) { + const timestamp = handshake.ts; + const version = handshake.v; + const host = handshake.h; + this.sessionId = handshake.s; + this.repoInfo_.host = host; + // if we've already closed the connection, then don't bother trying to progress further + if (this.state_ === 0 /* RealtimeState.CONNECTING */) { + this.conn_.start(); + this.onConnectionEstablished_(this.conn_, timestamp); + if (PROTOCOL_VERSION !== version) { + warn('Protocol version mismatch detected'); + } + // TODO: do we want to upgrade? when? maybe a delay? + this.tryStartUpgrade_(); + } + } + tryStartUpgrade_() { + const conn = this.transportManager_.upgradeTransport(); + if (conn) { + this.startUpgrade_(conn); + } + } + startUpgrade_(conn) { + this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId); + // For certain transports (WebSockets), we need to send and receive several messages back and forth before we + // can consider the transport healthy. + this.secondaryResponsesRequired_ = + conn['responsesRequiredToBeHealthy'] || 0; + const onMessage = this.connReceiver_(this.secondaryConn_); + const onDisconnect = this.disconnReceiver_(this.secondaryConn_); + this.secondaryConn_.open(onMessage, onDisconnect); + // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary. + setTimeoutNonBlocking(() => { + if (this.secondaryConn_) { + this.log_('Timed out trying to upgrade.'); + this.secondaryConn_.close(); + } + }, Math.floor(UPGRADE_TIMEOUT)); + } + onReset_(host) { + this.log_('Reset packet received. New host: ' + host); + this.repoInfo_.host = host; + // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up. + // We don't currently support resets after the connection has already been established + if (this.state_ === 1 /* RealtimeState.CONNECTED */) { + this.close(); + } + else { + // Close whatever connections we have open and start again. + this.closeConnections_(); + this.start_(); + } + } + onConnectionEstablished_(conn, timestamp) { + this.log_('Realtime connection established.'); + this.conn_ = conn; + this.state_ = 1 /* RealtimeState.CONNECTED */; + if (this.onReady_) { + this.onReady_(timestamp, this.sessionId); + this.onReady_ = null; + } + // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy, + // send some pings. + if (this.primaryResponsesRequired_ === 0) { + this.log_('Primary connection is healthy.'); + this.isHealthy_ = true; + } + else { + setTimeoutNonBlocking(() => { + this.sendPingOnPrimaryIfNecessary_(); + }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS)); + } + } + sendPingOnPrimaryIfNecessary_() { + // If the connection isn't considered healthy yet, we'll send a noop ping packet request. + if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) { + this.log_('sending ping on primary.'); + this.sendData_({ t: 'c', d: { t: PING, d: {} } }); + } + } + onSecondaryConnectionLost_() { + const conn = this.secondaryConn_; + this.secondaryConn_ = null; + if (this.tx_ === conn || this.rx_ === conn) { + // we are relying on this connection already in some capacity. Therefore, a failure is real + this.close(); + } + } + /** + * @param everConnected - Whether or not the connection ever reached a server. Used to determine if + * we should flush the host cache + */ + onConnectionLost_(everConnected) { + this.conn_ = null; + // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting + // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess. + if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) { + this.log_('Realtime connection failed.'); + // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away + if (this.repoInfo_.isCacheableHost()) { + PersistentStorage.remove('host:' + this.repoInfo_.host); + // reset the internal host to what we would show the user, i.e. .firebaseio.com + this.repoInfo_.internalHost = this.repoInfo_.host; + } + } + else if (this.state_ === 1 /* RealtimeState.CONNECTED */) { + this.log_('Realtime connection lost.'); + } + this.close(); + } + onConnectionShutdown_(reason) { + this.log_('Connection shutdown command received. Shutting down...'); + if (this.onKill_) { + this.onKill_(reason); + this.onKill_ = null; + } + // We intentionally don't want to fire onDisconnect (kill is a different case), + // so clear the callback. + this.onDisconnect_ = null; + this.close(); + } + sendData_(data) { + if (this.state_ !== 1 /* RealtimeState.CONNECTED */) { + throw 'Connection is not connected'; + } + else { + this.tx_.send(data); + } + } + /** + * Cleans up this connection, calling the appropriate callbacks + */ + close() { + if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) { + this.log_('Closing realtime connection.'); + this.state_ = 2 /* RealtimeState.DISCONNECTED */; + this.closeConnections_(); + if (this.onDisconnect_) { + this.onDisconnect_(); + this.onDisconnect_ = null; + } + } + } + closeConnections_() { + this.log_('Shutting down all connections'); + if (this.conn_) { + this.conn_.close(); + this.conn_ = null; + } + if (this.secondaryConn_) { + this.secondaryConn_.close(); + this.secondaryConn_ = null; + } + if (this.healthyTimeout_) { + clearTimeout(this.healthyTimeout_); + this.healthyTimeout_ = null; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Interface defining the set of actions that can be performed against the Firebase server + * (basically corresponds to our wire protocol). + * + * @interface + */ +class ServerActions { + put(pathString, data, onComplete, hash) { } + merge(pathString, data, onComplete, hash) { } + /** + * Refreshes the auth token for the current connection. + * @param token - The authentication token + */ + refreshAuthToken(token) { } + /** + * Refreshes the app check token for the current connection. + * @param token The app check token + */ + refreshAppCheckToken(token) { } + onDisconnectPut(pathString, data, onComplete) { } + onDisconnectMerge(pathString, data, onComplete) { } + onDisconnectCancel(pathString, onComplete) { } + reportStats(stats) { } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Base class to be used if you want to emit events. Call the constructor with + * the set of allowed event names. + */ +class EventEmitter { + constructor(allowedEvents_) { + this.allowedEvents_ = allowedEvents_; + this.listeners_ = {}; + assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array'); + } + /** + * To be called by derived classes to trigger events. + */ + trigger(eventType, ...varArgs) { + if (Array.isArray(this.listeners_[eventType])) { + // Clone the list, since callbacks could add/remove listeners. + const listeners = [...this.listeners_[eventType]]; + for (let i = 0; i < listeners.length; i++) { + listeners[i].callback.apply(listeners[i].context, varArgs); + } + } + } + on(eventType, callback, context) { + this.validateEventType_(eventType); + this.listeners_[eventType] = this.listeners_[eventType] || []; + this.listeners_[eventType].push({ callback, context }); + const eventData = this.getInitialEvent(eventType); + if (eventData) { + callback.apply(context, eventData); + } + } + off(eventType, callback, context) { + this.validateEventType_(eventType); + const listeners = this.listeners_[eventType] || []; + for (let i = 0; i < listeners.length; i++) { + if (listeners[i].callback === callback && + (!context || context === listeners[i].context)) { + listeners.splice(i, 1); + return; + } + } + } + validateEventType_(eventType) { + assert(this.allowedEvents_.find(et => { + return et === eventType; + }), 'Unknown event: ' + eventType); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Monitors online state (as reported by window.online/offline events). + * + * The expectation is that this could have many false positives (thinks we are online + * when we're not), but no false negatives. So we can safely use it to determine when + * we definitely cannot reach the internet. + */ +class OnlineMonitor extends EventEmitter { + static getInstance() { + return new OnlineMonitor(); + } + constructor() { + super(['online']); + this.online_ = true; + // We've had repeated complaints that Cordova apps can get stuck "offline", e.g. + // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810 + // It would seem that the 'online' event does not always fire consistently. So we disable it + // for Cordova. + if (typeof window !== 'undefined' && + typeof window.addEventListener !== 'undefined' && + !isMobileCordova()) { + window.addEventListener('online', () => { + if (!this.online_) { + this.online_ = true; + this.trigger('online', true); + } + }, false); + window.addEventListener('offline', () => { + if (this.online_) { + this.online_ = false; + this.trigger('online', false); + } + }, false); + } + } + getInitialEvent(eventType) { + assert(eventType === 'online', 'Unknown event type: ' + eventType); + return [this.online_]; + } + currentlyOnline() { + return this.online_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Maximum key depth. */ +const MAX_PATH_DEPTH = 32; +/** Maximum number of (UTF8) bytes in a Firebase path. */ +const MAX_PATH_LENGTH_BYTES = 768; +/** + * An immutable object representing a parsed path. It's immutable so that you + * can pass them around to other functions without worrying about them changing + * it. + */ +class Path { + /** + * @param pathOrString - Path string to parse, or another path, or the raw + * tokens array + */ + constructor(pathOrString, pieceNum) { + if (pieceNum === void 0) { + this.pieces_ = pathOrString.split('/'); + // Remove empty pieces. + let copyTo = 0; + for (let i = 0; i < this.pieces_.length; i++) { + if (this.pieces_[i].length > 0) { + this.pieces_[copyTo] = this.pieces_[i]; + copyTo++; + } + } + this.pieces_.length = copyTo; + this.pieceNum_ = 0; + } + else { + this.pieces_ = pathOrString; + this.pieceNum_ = pieceNum; + } + } + toString() { + let pathString = ''; + for (let i = this.pieceNum_; i < this.pieces_.length; i++) { + if (this.pieces_[i] !== '') { + pathString += '/' + this.pieces_[i]; + } + } + return pathString || '/'; + } +} +function newEmptyPath() { + return new Path(''); +} +function pathGetFront(path) { + if (path.pieceNum_ >= path.pieces_.length) { + return null; + } + return path.pieces_[path.pieceNum_]; +} +/** + * @returns The number of segments in this path + */ +function pathGetLength(path) { + return path.pieces_.length - path.pieceNum_; +} +function pathPopFront(path) { + let pieceNum = path.pieceNum_; + if (pieceNum < path.pieces_.length) { + pieceNum++; + } + return new Path(path.pieces_, pieceNum); +} +function pathGetBack(path) { + if (path.pieceNum_ < path.pieces_.length) { + return path.pieces_[path.pieces_.length - 1]; + } + return null; +} +function pathToUrlEncodedString(path) { + let pathString = ''; + for (let i = path.pieceNum_; i < path.pieces_.length; i++) { + if (path.pieces_[i] !== '') { + pathString += '/' + encodeURIComponent(String(path.pieces_[i])); + } + } + return pathString || '/'; +} +/** + * Shallow copy of the parts of the path. + * + */ +function pathSlice(path, begin = 0) { + return path.pieces_.slice(path.pieceNum_ + begin); +} +function pathParent(path) { + if (path.pieceNum_ >= path.pieces_.length) { + return null; + } + const pieces = []; + for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) { + pieces.push(path.pieces_[i]); + } + return new Path(pieces, 0); +} +function pathChild(path, childPathObj) { + const pieces = []; + for (let i = path.pieceNum_; i < path.pieces_.length; i++) { + pieces.push(path.pieces_[i]); + } + if (childPathObj instanceof Path) { + for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) { + pieces.push(childPathObj.pieces_[i]); + } + } + else { + const childPieces = childPathObj.split('/'); + for (let i = 0; i < childPieces.length; i++) { + if (childPieces[i].length > 0) { + pieces.push(childPieces[i]); + } + } + } + return new Path(pieces, 0); +} +/** + * @returns True if there are no segments in this path + */ +function pathIsEmpty(path) { + return path.pieceNum_ >= path.pieces_.length; +} +/** + * @returns The path from outerPath to innerPath + */ +function newRelativePath(outerPath, innerPath) { + const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath); + if (outer === null) { + return innerPath; + } + else if (outer === inner) { + return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath)); + } + else { + throw new Error('INTERNAL ERROR: innerPath (' + + innerPath + + ') is not within ' + + 'outerPath (' + + outerPath + + ')'); + } +} +/** + * @returns -1, 0, 1 if left is less, equal, or greater than the right. + */ +function pathCompare(left, right) { + const leftKeys = pathSlice(left, 0); + const rightKeys = pathSlice(right, 0); + for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) { + const cmp = nameCompare(leftKeys[i], rightKeys[i]); + if (cmp !== 0) { + return cmp; + } + } + if (leftKeys.length === rightKeys.length) { + return 0; + } + return leftKeys.length < rightKeys.length ? -1 : 1; +} +/** + * @returns true if paths are the same. + */ +function pathEquals(path, other) { + if (pathGetLength(path) !== pathGetLength(other)) { + return false; + } + for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) { + if (path.pieces_[i] !== other.pieces_[j]) { + return false; + } + } + return true; +} +/** + * @returns True if this path is a parent of (or the same as) other + */ +function pathContains(path, other) { + let i = path.pieceNum_; + let j = other.pieceNum_; + if (pathGetLength(path) > pathGetLength(other)) { + return false; + } + while (i < path.pieces_.length) { + if (path.pieces_[i] !== other.pieces_[j]) { + return false; + } + ++i; + ++j; + } + return true; +} +/** + * Dynamic (mutable) path used to count path lengths. + * + * This class is used to efficiently check paths for valid + * length (in UTF8 bytes) and depth (used in path validation). + * + * Throws Error exception if path is ever invalid. + * + * The definition of a path always begins with '/'. + */ +class ValidationPath { + /** + * @param path - Initial Path. + * @param errorPrefix_ - Prefix for any error messages. + */ + constructor(path, errorPrefix_) { + this.errorPrefix_ = errorPrefix_; + this.parts_ = pathSlice(path, 0); + /** Initialize to number of '/' chars needed in path. */ + this.byteLength_ = Math.max(1, this.parts_.length); + for (let i = 0; i < this.parts_.length; i++) { + this.byteLength_ += stringLength(this.parts_[i]); + } + validationPathCheckValid(this); + } +} +function validationPathPush(validationPath, child) { + // Count the needed '/' + if (validationPath.parts_.length > 0) { + validationPath.byteLength_ += 1; + } + validationPath.parts_.push(child); + validationPath.byteLength_ += stringLength(child); + validationPathCheckValid(validationPath); +} +function validationPathPop(validationPath) { + const last = validationPath.parts_.pop(); + validationPath.byteLength_ -= stringLength(last); + // Un-count the previous '/' + if (validationPath.parts_.length > 0) { + validationPath.byteLength_ -= 1; + } +} +function validationPathCheckValid(validationPath) { + if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) { + throw new Error(validationPath.errorPrefix_ + + 'has a key path longer than ' + + MAX_PATH_LENGTH_BYTES + + ' bytes (' + + validationPath.byteLength_ + + ').'); + } + if (validationPath.parts_.length > MAX_PATH_DEPTH) { + throw new Error(validationPath.errorPrefix_ + + 'path specified exceeds the maximum depth that can be written (' + + MAX_PATH_DEPTH + + ') or object contains a cycle ' + + validationPathToErrorString(validationPath)); + } +} +/** + * String for use in error messages - uses '.' notation for path. + */ +function validationPathToErrorString(validationPath) { + if (validationPath.parts_.length === 0) { + return ''; + } + return "in property '" + validationPath.parts_.join('.') + "'"; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class VisibilityMonitor extends EventEmitter { + static getInstance() { + return new VisibilityMonitor(); + } + constructor() { + super(['visible']); + let hidden; + let visibilityChange; + if (typeof document !== 'undefined' && + typeof document.addEventListener !== 'undefined') { + if (typeof document['hidden'] !== 'undefined') { + // Opera 12.10 and Firefox 18 and later support + visibilityChange = 'visibilitychange'; + hidden = 'hidden'; + } + else if (typeof document['mozHidden'] !== 'undefined') { + visibilityChange = 'mozvisibilitychange'; + hidden = 'mozHidden'; + } + else if (typeof document['msHidden'] !== 'undefined') { + visibilityChange = 'msvisibilitychange'; + hidden = 'msHidden'; + } + else if (typeof document['webkitHidden'] !== 'undefined') { + visibilityChange = 'webkitvisibilitychange'; + hidden = 'webkitHidden'; + } + } + // Initially, we always assume we are visible. This ensures that in browsers + // without page visibility support or in cases where we are never visible + // (e.g. chrome extension), we act as if we are visible, i.e. don't delay + // reconnects + this.visible_ = true; + if (visibilityChange) { + document.addEventListener(visibilityChange, () => { + const visible = !document[hidden]; + if (visible !== this.visible_) { + this.visible_ = visible; + this.trigger('visible', visible); + } + }, false); + } + } + getInitialEvent(eventType) { + assert(eventType === 'visible', 'Unknown event type: ' + eventType); + return [this.visible_]; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const RECONNECT_MIN_DELAY = 1000; +const RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858) +const RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server) +const RECONNECT_DELAY_MULTIPLIER = 1.3; +const RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec. +const SERVER_KILL_INTERRUPT_REASON = 'server_kill'; +// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off. +const INVALID_TOKEN_THRESHOLD = 3; +/** + * Firebase connection. Abstracts wire protocol and handles reconnecting. + * + * NOTE: All JSON objects sent to the realtime connection must have property names enclosed + * in quotes to make sure the closure compiler does not minify them. + */ +class PersistentConnection extends ServerActions { + /** + * @param repoInfo_ - Data about the namespace we are connecting to + * @param applicationId_ - The Firebase App ID for this project + * @param onDataUpdate_ - A callback for new data from the server + */ + constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) { + super(); + this.repoInfo_ = repoInfo_; + this.applicationId_ = applicationId_; + this.onDataUpdate_ = onDataUpdate_; + this.onConnectStatus_ = onConnectStatus_; + this.onServerInfoUpdate_ = onServerInfoUpdate_; + this.authTokenProvider_ = authTokenProvider_; + this.appCheckTokenProvider_ = appCheckTokenProvider_; + this.authOverride_ = authOverride_; + // Used for diagnostic logging. + this.id = PersistentConnection.nextPersistentConnectionId_++; + this.log_ = logWrapper('p:' + this.id + ':'); + this.interruptReasons_ = {}; + this.listens = new Map(); + this.outstandingPuts_ = []; + this.outstandingGets_ = []; + this.outstandingPutCount_ = 0; + this.outstandingGetCount_ = 0; + this.onDisconnectRequestQueue_ = []; + this.connected_ = false; + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT; + this.securityDebugCallback_ = null; + this.lastSessionId = null; + this.establishConnectionTimer_ = null; + this.visible_ = false; + // Before we get connected, we keep a queue of pending messages to send. + this.requestCBHash_ = {}; + this.requestNumber_ = 0; + this.realtime_ = null; + this.authToken_ = null; + this.appCheckToken_ = null; + this.forceTokenRefresh_ = false; + this.invalidAuthTokenCount_ = 0; + this.invalidAppCheckTokenCount_ = 0; + this.firstConnection_ = true; + this.lastConnectionAttemptTime_ = null; + this.lastConnectionEstablishedTime_ = null; + if (authOverride_ && !isNodeSdk()) { + throw new Error('Auth override specified in options, but not supported on non Node.js platforms'); + } + VisibilityMonitor.getInstance().on('visible', this.onVisible_, this); + if (repoInfo_.host.indexOf('fblocal') === -1) { + OnlineMonitor.getInstance().on('online', this.onOnline_, this); + } + } + sendRequest(action, body, onResponse) { + const curReqNum = ++this.requestNumber_; + const msg = { r: curReqNum, a: action, b: body }; + this.log_(stringify(msg)); + assert(this.connected_, "sendRequest call when we're not connected not allowed."); + this.realtime_.sendRequest(msg); + if (onResponse) { + this.requestCBHash_[curReqNum] = onResponse; + } + } + get(query) { + this.initConnection_(); + const deferred = new Deferred(); + const request = { + p: query._path.toString(), + q: query._queryObject + }; + const outstandingGet = { + action: 'g', + request, + onComplete: (message) => { + const payload = message['d']; + if (message['s'] === 'ok') { + deferred.resolve(payload); + } + else { + deferred.reject(payload); + } + } + }; + this.outstandingGets_.push(outstandingGet); + this.outstandingGetCount_++; + const index = this.outstandingGets_.length - 1; + if (this.connected_) { + this.sendGet_(index); + } + return deferred.promise; + } + listen(query, currentHashFn, tag, onComplete) { + this.initConnection_(); + const queryId = query._queryIdentifier; + const pathString = query._path.toString(); + this.log_('Listen called for ' + pathString + ' ' + queryId); + if (!this.listens.has(pathString)) { + this.listens.set(pathString, new Map()); + } + assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query'); + assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`); + const listenSpec = { + onComplete, + hashFn: currentHashFn, + query, + tag + }; + this.listens.get(pathString).set(queryId, listenSpec); + if (this.connected_) { + this.sendListen_(listenSpec); + } + } + sendGet_(index) { + const get = this.outstandingGets_[index]; + this.sendRequest('g', get.request, (message) => { + delete this.outstandingGets_[index]; + this.outstandingGetCount_--; + if (this.outstandingGetCount_ === 0) { + this.outstandingGets_ = []; + } + if (get.onComplete) { + get.onComplete(message); + } + }); + } + sendListen_(listenSpec) { + const query = listenSpec.query; + const pathString = query._path.toString(); + const queryId = query._queryIdentifier; + this.log_('Listen on ' + pathString + ' for ' + queryId); + const req = { /*path*/ p: pathString }; + const action = 'q'; + // Only bother to send query if it's non-default. + if (listenSpec.tag) { + req['q'] = query._queryObject; + req['t'] = listenSpec.tag; + } + req[ /*hash*/'h'] = listenSpec.hashFn(); + this.sendRequest(action, req, (message) => { + const payload = message[ /*data*/'d']; + const status = message[ /*status*/'s']; + // print warnings in any case... + PersistentConnection.warnOnListenWarnings_(payload, query); + const currentListenSpec = this.listens.get(pathString) && + this.listens.get(pathString).get(queryId); + // only trigger actions if the listen hasn't been removed and readded + if (currentListenSpec === listenSpec) { + this.log_('listen response', message); + if (status !== 'ok') { + this.removeListen_(pathString, queryId); + } + if (listenSpec.onComplete) { + listenSpec.onComplete(status, payload); + } + } + }); + } + static warnOnListenWarnings_(payload, query) { + if (payload && typeof payload === 'object' && contains(payload, 'w')) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const warnings = safeGet(payload, 'w'); + if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) { + const indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"'; + const indexPath = query._path.toString(); + warn(`Using an unspecified index. Your data will be downloaded and ` + + `filtered on the client. Consider adding ${indexSpec} at ` + + `${indexPath} to your security rules for better performance.`); + } + } + } + refreshAuthToken(token) { + this.authToken_ = token; + this.log_('Auth token refreshed'); + if (this.authToken_) { + this.tryAuth(); + } + else { + //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete + //the credential so we dont become authenticated next time we connect. + if (this.connected_) { + this.sendRequest('unauth', {}, () => { }); + } + } + this.reduceReconnectDelayIfAdminCredential_(token); + } + reduceReconnectDelayIfAdminCredential_(credential) { + // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client). + // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires. + const isFirebaseSecret = credential && credential.length === 40; + if (isFirebaseSecret || isAdmin(credential)) { + this.log_('Admin auth credential detected. Reducing max reconnect time.'); + this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS; + } + } + refreshAppCheckToken(token) { + this.appCheckToken_ = token; + this.log_('App check token refreshed'); + if (this.appCheckToken_) { + this.tryAppCheck(); + } + else { + //If we're connected we want to let the server know to unauthenticate us. + //If we're not connected, simply delete the credential so we dont become + // authenticated next time we connect. + if (this.connected_) { + this.sendRequest('unappeck', {}, () => { }); + } + } + } + /** + * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like + * a auth revoked (the connection is closed). + */ + tryAuth() { + if (this.connected_ && this.authToken_) { + const token = this.authToken_; + const authMethod = isValidFormat(token) ? 'auth' : 'gauth'; + const requestData = { cred: token }; + if (this.authOverride_ === null) { + requestData['noauth'] = true; + } + else if (typeof this.authOverride_ === 'object') { + requestData['authvar'] = this.authOverride_; + } + this.sendRequest(authMethod, requestData, (res) => { + const status = res[ /*status*/'s']; + const data = res[ /*data*/'d'] || 'error'; + if (this.authToken_ === token) { + if (status === 'ok') { + this.invalidAuthTokenCount_ = 0; + } + else { + // Triggers reconnect and force refresh for auth token + this.onAuthRevoked_(status, data); + } + } + }); + } + } + /** + * Attempts to authenticate with the given token. If the authentication + * attempt fails, it's triggered like the token was revoked (the connection is + * closed). + */ + tryAppCheck() { + if (this.connected_ && this.appCheckToken_) { + this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => { + const status = res[ /*status*/'s']; + const data = res[ /*data*/'d'] || 'error'; + if (status === 'ok') { + this.invalidAppCheckTokenCount_ = 0; + } + else { + this.onAppCheckRevoked_(status, data); + } + }); + } + } + /** + * @inheritDoc + */ + unlisten(query, tag) { + const pathString = query._path.toString(); + const queryId = query._queryIdentifier; + this.log_('Unlisten called for ' + pathString + ' ' + queryId); + assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query'); + const listen = this.removeListen_(pathString, queryId); + if (listen && this.connected_) { + this.sendUnlisten_(pathString, queryId, query._queryObject, tag); + } + } + sendUnlisten_(pathString, queryId, queryObj, tag) { + this.log_('Unlisten on ' + pathString + ' for ' + queryId); + const req = { /*path*/ p: pathString }; + const action = 'n'; + // Only bother sending queryId if it's non-default. + if (tag) { + req['q'] = queryObj; + req['t'] = tag; + } + this.sendRequest(action, req); + } + onDisconnectPut(pathString, data, onComplete) { + this.initConnection_(); + if (this.connected_) { + this.sendOnDisconnect_('o', pathString, data, onComplete); + } + else { + this.onDisconnectRequestQueue_.push({ + pathString, + action: 'o', + data, + onComplete + }); + } + } + onDisconnectMerge(pathString, data, onComplete) { + this.initConnection_(); + if (this.connected_) { + this.sendOnDisconnect_('om', pathString, data, onComplete); + } + else { + this.onDisconnectRequestQueue_.push({ + pathString, + action: 'om', + data, + onComplete + }); + } + } + onDisconnectCancel(pathString, onComplete) { + this.initConnection_(); + if (this.connected_) { + this.sendOnDisconnect_('oc', pathString, null, onComplete); + } + else { + this.onDisconnectRequestQueue_.push({ + pathString, + action: 'oc', + data: null, + onComplete + }); + } + } + sendOnDisconnect_(action, pathString, data, onComplete) { + const request = { /*path*/ p: pathString, /*data*/ d: data }; + this.log_('onDisconnect ' + action, request); + this.sendRequest(action, request, (response) => { + if (onComplete) { + setTimeout(() => { + onComplete(response[ /*status*/'s'], response[ /* data */'d']); + }, Math.floor(0)); + } + }); + } + put(pathString, data, onComplete, hash) { + this.putInternal('p', pathString, data, onComplete, hash); + } + merge(pathString, data, onComplete, hash) { + this.putInternal('m', pathString, data, onComplete, hash); + } + putInternal(action, pathString, data, onComplete, hash) { + this.initConnection_(); + const request = { + /*path*/ p: pathString, + /*data*/ d: data + }; + if (hash !== undefined) { + request[ /*hash*/'h'] = hash; + } + // TODO: Only keep track of the most recent put for a given path? + this.outstandingPuts_.push({ + action, + request, + onComplete + }); + this.outstandingPutCount_++; + const index = this.outstandingPuts_.length - 1; + if (this.connected_) { + this.sendPut_(index); + } + else { + this.log_('Buffering put: ' + pathString); + } + } + sendPut_(index) { + const action = this.outstandingPuts_[index].action; + const request = this.outstandingPuts_[index].request; + const onComplete = this.outstandingPuts_[index].onComplete; + this.outstandingPuts_[index].queued = this.connected_; + this.sendRequest(action, request, (message) => { + this.log_(action + ' response', message); + delete this.outstandingPuts_[index]; + this.outstandingPutCount_--; + // Clean up array occasionally. + if (this.outstandingPutCount_ === 0) { + this.outstandingPuts_ = []; + } + if (onComplete) { + onComplete(message[ /*status*/'s'], message[ /* data */'d']); + } + }); + } + reportStats(stats) { + // If we're not connected, we just drop the stats. + if (this.connected_) { + const request = { /*counters*/ c: stats }; + this.log_('reportStats', request); + this.sendRequest(/*stats*/ 's', request, result => { + const status = result[ /*status*/'s']; + if (status !== 'ok') { + const errorReason = result[ /* data */'d']; + this.log_('reportStats', 'Error sending stats: ' + errorReason); + } + }); + } + } + onDataMessage_(message) { + if ('r' in message) { + // this is a response + this.log_('from server: ' + stringify(message)); + const reqNum = message['r']; + const onResponse = this.requestCBHash_[reqNum]; + if (onResponse) { + delete this.requestCBHash_[reqNum]; + onResponse(message[ /*body*/'b']); + } + } + else if ('error' in message) { + throw 'A server-side error has occurred: ' + message['error']; + } + else if ('a' in message) { + // a and b are action and body, respectively + this.onDataPush_(message['a'], message['b']); + } + } + onDataPush_(action, body) { + this.log_('handleServerMessage', action, body); + if (action === 'd') { + this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], + /*isMerge*/ false, body['t']); + } + else if (action === 'm') { + this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], + /*isMerge=*/ true, body['t']); + } + else if (action === 'c') { + this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']); + } + else if (action === 'ac') { + this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']); + } + else if (action === 'apc') { + this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']); + } + else if (action === 'sd') { + this.onSecurityDebugPacket_(body); + } + else { + error('Unrecognized action received from server: ' + + stringify(action) + + '\nAre you using the latest client?'); + } + } + onReady_(timestamp, sessionId) { + this.log_('connection ready'); + this.connected_ = true; + this.lastConnectionEstablishedTime_ = new Date().getTime(); + this.handleTimestamp_(timestamp); + this.lastSessionId = sessionId; + if (this.firstConnection_) { + this.sendConnectStats_(); + } + this.restoreState_(); + this.firstConnection_ = false; + this.onConnectStatus_(true); + } + scheduleConnect_(timeout) { + assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?"); + if (this.establishConnectionTimer_) { + clearTimeout(this.establishConnectionTimer_); + } + // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in + // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests). + this.establishConnectionTimer_ = setTimeout(() => { + this.establishConnectionTimer_ = null; + this.establishConnection_(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(timeout)); + } + initConnection_() { + if (!this.realtime_ && this.firstConnection_) { + this.scheduleConnect_(0); + } + } + onVisible_(visible) { + // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine. + if (visible && + !this.visible_ && + this.reconnectDelay_ === this.maxReconnectDelay_) { + this.log_('Window became visible. Reducing delay.'); + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + if (!this.realtime_) { + this.scheduleConnect_(0); + } + } + this.visible_ = visible; + } + onOnline_(online) { + if (online) { + this.log_('Browser went online.'); + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + if (!this.realtime_) { + this.scheduleConnect_(0); + } + } + else { + this.log_('Browser went offline. Killing connection.'); + if (this.realtime_) { + this.realtime_.close(); + } + } + } + onRealtimeDisconnect_() { + this.log_('data client disconnected'); + this.connected_ = false; + this.realtime_ = null; + // Since we don't know if our sent transactions succeeded or not, we need to cancel them. + this.cancelSentTransactions_(); + // Clear out the pending requests. + this.requestCBHash_ = {}; + if (this.shouldReconnect_()) { + if (!this.visible_) { + this.log_("Window isn't visible. Delaying reconnect."); + this.reconnectDelay_ = this.maxReconnectDelay_; + this.lastConnectionAttemptTime_ = new Date().getTime(); + } + else if (this.lastConnectionEstablishedTime_) { + // If we've been connected long enough, reset reconnect delay to minimum. + const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_; + if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) { + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + } + this.lastConnectionEstablishedTime_ = null; + } + const timeSinceLastConnectAttempt = Math.max(0, new Date().getTime() - this.lastConnectionAttemptTime_); + let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt); + reconnectDelay = Math.random() * reconnectDelay; + this.log_('Trying to reconnect in ' + reconnectDelay + 'ms'); + this.scheduleConnect_(reconnectDelay); + // Adjust reconnect delay for next time. + this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER); + } + this.onConnectStatus_(false); + } + async establishConnection_() { + if (this.shouldReconnect_()) { + this.log_('Making a connection attempt'); + this.lastConnectionAttemptTime_ = new Date().getTime(); + this.lastConnectionEstablishedTime_ = null; + const onDataMessage = this.onDataMessage_.bind(this); + const onReady = this.onReady_.bind(this); + const onDisconnect = this.onRealtimeDisconnect_.bind(this); + const connId = this.id + ':' + PersistentConnection.nextConnectionId_++; + const lastSessionId = this.lastSessionId; + let canceled = false; + let connection = null; + const closeFn = function () { + if (connection) { + connection.close(); + } + else { + canceled = true; + onDisconnect(); + } + }; + const sendRequestFn = function (msg) { + assert(connection, "sendRequest call when we're not connected not allowed."); + connection.sendRequest(msg); + }; + this.realtime_ = { + close: closeFn, + sendRequest: sendRequestFn + }; + const forceRefresh = this.forceTokenRefresh_; + this.forceTokenRefresh_ = false; + try { + // First fetch auth and app check token, and establish connection after + // fetching the token was successful + const [authToken, appCheckToken] = await Promise.all([ + this.authTokenProvider_.getToken(forceRefresh), + this.appCheckTokenProvider_.getToken(forceRefresh) + ]); + if (!canceled) { + log('getToken() completed. Creating connection.'); + this.authToken_ = authToken && authToken.accessToken; + this.appCheckToken_ = appCheckToken && appCheckToken.token; + connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect, + /* onKill= */ reason => { + warn(reason + ' (' + this.repoInfo_.toString() + ')'); + this.interrupt(SERVER_KILL_INTERRUPT_REASON); + }, lastSessionId); + } + else { + log('getToken() completed but was canceled'); + } + } + catch (error) { + this.log_('Failed to get token: ' + error); + if (!canceled) { + if (this.repoInfo_.nodeAdmin) { + // This may be a critical error for the Admin Node.js SDK, so log a warning. + // But getToken() may also just have temporarily failed, so we still want to + // continue retrying. + warn(error); + } + closeFn(); + } + } + } + } + interrupt(reason) { + log('Interrupting connection for reason: ' + reason); + this.interruptReasons_[reason] = true; + if (this.realtime_) { + this.realtime_.close(); + } + else { + if (this.establishConnectionTimer_) { + clearTimeout(this.establishConnectionTimer_); + this.establishConnectionTimer_ = null; + } + if (this.connected_) { + this.onRealtimeDisconnect_(); + } + } + } + resume(reason) { + log('Resuming connection for reason: ' + reason); + delete this.interruptReasons_[reason]; + if (isEmpty(this.interruptReasons_)) { + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + if (!this.realtime_) { + this.scheduleConnect_(0); + } + } + } + handleTimestamp_(timestamp) { + const delta = timestamp - new Date().getTime(); + this.onServerInfoUpdate_({ serverTimeOffset: delta }); + } + cancelSentTransactions_() { + for (let i = 0; i < this.outstandingPuts_.length; i++) { + const put = this.outstandingPuts_[i]; + if (put && /*hash*/ 'h' in put.request && put.queued) { + if (put.onComplete) { + put.onComplete('disconnect'); + } + delete this.outstandingPuts_[i]; + this.outstandingPutCount_--; + } + } + // Clean up array occasionally. + if (this.outstandingPutCount_ === 0) { + this.outstandingPuts_ = []; + } + } + onListenRevoked_(pathString, query) { + // Remove the listen and manufacture a "permission_denied" error for the failed listen. + let queryId; + if (!query) { + queryId = 'default'; + } + else { + queryId = query.map(q => ObjectToUniqueKey(q)).join('$'); + } + const listen = this.removeListen_(pathString, queryId); + if (listen && listen.onComplete) { + listen.onComplete('permission_denied'); + } + } + removeListen_(pathString, queryId) { + const normalizedPathString = new Path(pathString).toString(); // normalize path. + let listen; + if (this.listens.has(normalizedPathString)) { + const map = this.listens.get(normalizedPathString); + listen = map.get(queryId); + map.delete(queryId); + if (map.size === 0) { + this.listens.delete(normalizedPathString); + } + } + else { + // all listens for this path has already been removed + listen = undefined; + } + return listen; + } + onAuthRevoked_(statusCode, explanation) { + log('Auth token revoked: ' + statusCode + '/' + explanation); + this.authToken_ = null; + this.forceTokenRefresh_ = true; + this.realtime_.close(); + if (statusCode === 'invalid_token' || statusCode === 'permission_denied') { + // We'll wait a couple times before logging the warning / increasing the + // retry period since oauth tokens will report as "invalid" if they're + // just expired. Plus there may be transient issues that resolve themselves. + this.invalidAuthTokenCount_++; + if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) { + // Set a long reconnect delay because recovery is unlikely + this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS; + // Notify the auth token provider that the token is invalid, which will log + // a warning + this.authTokenProvider_.notifyForInvalidToken(); + } + } + } + onAppCheckRevoked_(statusCode, explanation) { + log('App check token revoked: ' + statusCode + '/' + explanation); + this.appCheckToken_ = null; + this.forceTokenRefresh_ = true; + // Note: We don't close the connection as the developer may not have + // enforcement enabled. The backend closes connections with enforcements. + if (statusCode === 'invalid_token' || statusCode === 'permission_denied') { + // We'll wait a couple times before logging the warning / increasing the + // retry period since oauth tokens will report as "invalid" if they're + // just expired. Plus there may be transient issues that resolve themselves. + this.invalidAppCheckTokenCount_++; + if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) { + this.appCheckTokenProvider_.notifyForInvalidToken(); + } + } + } + onSecurityDebugPacket_(body) { + if (this.securityDebugCallback_) { + this.securityDebugCallback_(body); + } + else { + if ('msg' in body) { + console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: ')); + } + } + } + restoreState_() { + //Re-authenticate ourselves if we have a credential stored. + this.tryAuth(); + this.tryAppCheck(); + // Puts depend on having received the corresponding data update from the server before they complete, so we must + // make sure to send listens before puts. + for (const queries of this.listens.values()) { + for (const listenSpec of queries.values()) { + this.sendListen_(listenSpec); + } + } + for (let i = 0; i < this.outstandingPuts_.length; i++) { + if (this.outstandingPuts_[i]) { + this.sendPut_(i); + } + } + while (this.onDisconnectRequestQueue_.length) { + const request = this.onDisconnectRequestQueue_.shift(); + this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete); + } + for (let i = 0; i < this.outstandingGets_.length; i++) { + if (this.outstandingGets_[i]) { + this.sendGet_(i); + } + } + } + /** + * Sends client stats for first connection + */ + sendConnectStats_() { + const stats = {}; + let clientName = 'js'; + if (isNodeSdk()) { + if (this.repoInfo_.nodeAdmin) { + clientName = 'admin_node'; + } + else { + clientName = 'node'; + } + } + stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1; + if (isMobileCordova()) { + stats['framework.cordova'] = 1; + } + else if (isReactNative()) { + stats['framework.reactnative'] = 1; + } + this.reportStats(stats); + } + shouldReconnect_() { + const online = OnlineMonitor.getInstance().currentlyOnline(); + return isEmpty(this.interruptReasons_) && online; + } +} +PersistentConnection.nextPersistentConnectionId_ = 0; +/** + * Counter for number of connections created. Mainly used for tagging in the logs + */ +PersistentConnection.nextConnectionId_ = 0; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class NamedNode { + constructor(name, node) { + this.name = name; + this.node = node; + } + static Wrap(name, node) { + return new NamedNode(name, node); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Index { + /** + * @returns A standalone comparison function for + * this index + */ + getCompare() { + return this.compare.bind(this); + } + /** + * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different, + * it's possible that the changes are isolated to parts of the snapshot that are not indexed. + * + * + * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode + */ + indexedValueChanged(oldNode, newNode) { + const oldWrapped = new NamedNode(MIN_NAME, oldNode); + const newWrapped = new NamedNode(MIN_NAME, newNode); + return this.compare(oldWrapped, newWrapped) !== 0; + } + /** + * @returns a node wrapper that will sort equal to or less than + * any other node wrapper, using this index + */ + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let __EMPTY_NODE; +class KeyIndex extends Index { + static get __EMPTY_NODE() { + return __EMPTY_NODE; + } + static set __EMPTY_NODE(val) { + __EMPTY_NODE = val; + } + compare(a, b) { + return nameCompare(a.name, b.name); + } + isDefinedOn(node) { + // We could probably return true here (since every node has a key), but it's never called + // so just leaving unimplemented for now. + throw assertionError('KeyIndex.isDefinedOn not expected to be called.'); + } + indexedValueChanged(oldNode, newNode) { + return false; // The key for a node never changes. + } + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } + maxPost() { + // TODO: This should really be created once and cached in a static property, but + // NamedNode isn't defined yet, so I can't use it in a static. Bleh. + return new NamedNode(MAX_NAME, __EMPTY_NODE); + } + makePost(indexValue, name) { + assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.'); + // We just use empty node, but it'll never be compared, since our comparator only looks at name. + return new NamedNode(indexValue, __EMPTY_NODE); + } + /** + * @returns String representation for inclusion in a query spec + */ + toString() { + return '.key'; + } +} +const KEY_INDEX = new KeyIndex(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An iterator over an LLRBNode. + */ +class SortedMapIterator { + /** + * @param node - Node to iterate. + * @param isReverse_ - Whether or not to iterate in reverse + */ + constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) { + this.isReverse_ = isReverse_; + this.resultGenerator_ = resultGenerator_; + this.nodeStack_ = []; + let cmp = 1; + while (!node.isEmpty()) { + node = node; + cmp = startKey ? comparator(node.key, startKey) : 1; + // flip the comparison if we're going in reverse + if (isReverse_) { + cmp *= -1; + } + if (cmp < 0) { + // This node is less than our start key. ignore it + if (this.isReverse_) { + node = node.left; + } + else { + node = node.right; + } + } + else if (cmp === 0) { + // This node is exactly equal to our start key. Push it on the stack, but stop iterating; + this.nodeStack_.push(node); + break; + } + else { + // This node is greater than our start key, add it to the stack and move to the next one + this.nodeStack_.push(node); + if (this.isReverse_) { + node = node.right; + } + else { + node = node.left; + } + } + } + } + getNext() { + if (this.nodeStack_.length === 0) { + return null; + } + let node = this.nodeStack_.pop(); + let result; + if (this.resultGenerator_) { + result = this.resultGenerator_(node.key, node.value); + } + else { + result = { key: node.key, value: node.value }; + } + if (this.isReverse_) { + node = node.left; + while (!node.isEmpty()) { + this.nodeStack_.push(node); + node = node.right; + } + } + else { + node = node.right; + while (!node.isEmpty()) { + this.nodeStack_.push(node); + node = node.left; + } + } + return result; + } + hasNext() { + return this.nodeStack_.length > 0; + } + peek() { + if (this.nodeStack_.length === 0) { + return null; + } + const node = this.nodeStack_[this.nodeStack_.length - 1]; + if (this.resultGenerator_) { + return this.resultGenerator_(node.key, node.value); + } + else { + return { key: node.key, value: node.value }; + } + } +} +/** + * Represents a node in a Left-leaning Red-Black tree. + */ +class LLRBNode { + /** + * @param key - Key associated with this node. + * @param value - Value associated with this node. + * @param color - Whether this node is red. + * @param left - Left child. + * @param right - Right child. + */ + constructor(key, value, color, left, right) { + this.key = key; + this.value = value; + this.color = color != null ? color : LLRBNode.RED; + this.left = + left != null ? left : SortedMap.EMPTY_NODE; + this.right = + right != null ? right : SortedMap.EMPTY_NODE; + } + /** + * Returns a copy of the current node, optionally replacing pieces of it. + * + * @param key - New key for the node, or null. + * @param value - New value for the node, or null. + * @param color - New color for the node, or null. + * @param left - New left child for the node, or null. + * @param right - New right child for the node, or null. + * @returns The node copy. + */ + copy(key, value, color, left, right) { + return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right); + } + /** + * @returns The total number of nodes in the tree. + */ + count() { + return this.left.count() + 1 + this.right.count(); + } + /** + * @returns True if the tree is empty. + */ + isEmpty() { + return false; + } + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action) { + return (this.left.inorderTraversal(action) || + !!action(this.key, this.value) || + this.right.inorderTraversal(action)); + } + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action) { + return (this.right.reverseTraversal(action) || + action(this.key, this.value) || + this.left.reverseTraversal(action)); + } + /** + * @returns The minimum node in the tree. + */ + min_() { + if (this.left.isEmpty()) { + return this; + } + else { + return this.left.min_(); + } + } + /** + * @returns The maximum key in the tree. + */ + minKey() { + return this.min_().key; + } + /** + * @returns The maximum key in the tree. + */ + maxKey() { + if (this.right.isEmpty()) { + return this.key; + } + else { + return this.right.maxKey(); + } + } + /** + * @param key - Key to insert. + * @param value - Value to insert. + * @param comparator - Comparator. + * @returns New tree, with the key/value added. + */ + insert(key, value, comparator) { + let n = this; + const cmp = comparator(key, n.key); + if (cmp < 0) { + n = n.copy(null, null, null, n.left.insert(key, value, comparator), null); + } + else if (cmp === 0) { + n = n.copy(null, value, null, null, null); + } + else { + n = n.copy(null, null, null, null, n.right.insert(key, value, comparator)); + } + return n.fixUp_(); + } + /** + * @returns New tree, with the minimum key removed. + */ + removeMin_() { + if (this.left.isEmpty()) { + return SortedMap.EMPTY_NODE; + } + let n = this; + if (!n.left.isRed_() && !n.left.left.isRed_()) { + n = n.moveRedLeft_(); + } + n = n.copy(null, null, null, n.left.removeMin_(), null); + return n.fixUp_(); + } + /** + * @param key - The key of the item to remove. + * @param comparator - Comparator. + * @returns New tree, with the specified item removed. + */ + remove(key, comparator) { + let n, smallest; + n = this; + if (comparator(key, n.key) < 0) { + if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) { + n = n.moveRedLeft_(); + } + n = n.copy(null, null, null, n.left.remove(key, comparator), null); + } + else { + if (n.left.isRed_()) { + n = n.rotateRight_(); + } + if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) { + n = n.moveRedRight_(); + } + if (comparator(key, n.key) === 0) { + if (n.right.isEmpty()) { + return SortedMap.EMPTY_NODE; + } + else { + smallest = n.right.min_(); + n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_()); + } + } + n = n.copy(null, null, null, null, n.right.remove(key, comparator)); + } + return n.fixUp_(); + } + /** + * @returns Whether this is a RED node. + */ + isRed_() { + return this.color; + } + /** + * @returns New tree after performing any needed rotations. + */ + fixUp_() { + let n = this; + if (n.right.isRed_() && !n.left.isRed_()) { + n = n.rotateLeft_(); + } + if (n.left.isRed_() && n.left.left.isRed_()) { + n = n.rotateRight_(); + } + if (n.left.isRed_() && n.right.isRed_()) { + n = n.colorFlip_(); + } + return n; + } + /** + * @returns New tree, after moveRedLeft. + */ + moveRedLeft_() { + let n = this.colorFlip_(); + if (n.right.left.isRed_()) { + n = n.copy(null, null, null, null, n.right.rotateRight_()); + n = n.rotateLeft_(); + n = n.colorFlip_(); + } + return n; + } + /** + * @returns New tree, after moveRedRight. + */ + moveRedRight_() { + let n = this.colorFlip_(); + if (n.left.left.isRed_()) { + n = n.rotateRight_(); + n = n.colorFlip_(); + } + return n; + } + /** + * @returns New tree, after rotateLeft. + */ + rotateLeft_() { + const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, nl, null); + } + /** + * @returns New tree, after rotateRight. + */ + rotateRight_() { + const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, nr); + } + /** + * @returns Newt ree, after colorFlip. + */ + colorFlip_() { + const left = this.left.copy(null, null, !this.left.color, null, null); + const right = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, left, right); + } + /** + * For testing. + * + * @returns True if all is well. + */ + checkMaxDepth_() { + const blackDepth = this.check_(); + return Math.pow(2.0, blackDepth) <= this.count() + 1; + } + check_() { + if (this.isRed_() && this.left.isRed_()) { + throw new Error('Red node has red child(' + this.key + ',' + this.value + ')'); + } + if (this.right.isRed_()) { + throw new Error('Right child of (' + this.key + ',' + this.value + ') is red'); + } + const blackDepth = this.left.check_(); + if (blackDepth !== this.right.check_()) { + throw new Error('Black depths differ'); + } + else { + return blackDepth + (this.isRed_() ? 0 : 1); + } + } +} +LLRBNode.RED = true; +LLRBNode.BLACK = false; +/** + * Represents an empty node (a leaf node in the Red-Black Tree). + */ +class LLRBEmptyNode { + /** + * Returns a copy of the current node. + * + * @returns The node copy. + */ + copy(key, value, color, left, right) { + return this; + } + /** + * Returns a copy of the tree, with the specified key/value added. + * + * @param key - Key to be added. + * @param value - Value to be added. + * @param comparator - Comparator. + * @returns New tree, with item added. + */ + insert(key, value, comparator) { + return new LLRBNode(key, value, null); + } + /** + * Returns a copy of the tree, with the specified key removed. + * + * @param key - The key to remove. + * @param comparator - Comparator. + * @returns New tree, with item removed. + */ + remove(key, comparator) { + return this; + } + /** + * @returns The total number of nodes in the tree. + */ + count() { + return 0; + } + /** + * @returns True if the tree is empty. + */ + isEmpty() { + return true; + } + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + inorderTraversal(action) { + return false; + } + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action) { + return false; + } + minKey() { + return null; + } + maxKey() { + return null; + } + check_() { + return 0; + } + /** + * @returns Whether this node is red. + */ + isRed_() { + return false; + } +} +/** + * An immutable sorted map implementation, based on a Left-leaning Red-Black + * tree. + */ +class SortedMap { + /** + * @param comparator_ - Key comparator. + * @param root_ - Optional root node for the map. + */ + constructor(comparator_, root_ = SortedMap.EMPTY_NODE) { + this.comparator_ = comparator_; + this.root_ = root_; + } + /** + * Returns a copy of the map, with the specified key/value added or replaced. + * (TODO: We should perhaps rename this method to 'put') + * + * @param key - Key to be added. + * @param value - Value to be added. + * @returns New map, with item added. + */ + insert(key, value) { + return new SortedMap(this.comparator_, this.root_ + .insert(key, value, this.comparator_) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + /** + * Returns a copy of the map, with the specified key removed. + * + * @param key - The key to remove. + * @returns New map, with item removed. + */ + remove(key) { + return new SortedMap(this.comparator_, this.root_ + .remove(key, this.comparator_) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + /** + * Returns the value of the node with the given key, or null. + * + * @param key - The key to look up. + * @returns The value of the node with the given key, or null if the + * key doesn't exist. + */ + get(key) { + let cmp; + let node = this.root_; + while (!node.isEmpty()) { + cmp = this.comparator_(key, node.key); + if (cmp === 0) { + return node.value; + } + else if (cmp < 0) { + node = node.left; + } + else if (cmp > 0) { + node = node.right; + } + } + return null; + } + /** + * Returns the key of the item *before* the specified key, or null if key is the first item. + * @param key - The key to find the predecessor of + * @returns The predecessor key. + */ + getPredecessorKey(key) { + let cmp, node = this.root_, rightParent = null; + while (!node.isEmpty()) { + cmp = this.comparator_(key, node.key); + if (cmp === 0) { + if (!node.left.isEmpty()) { + node = node.left; + while (!node.right.isEmpty()) { + node = node.right; + } + return node.key; + } + else if (rightParent) { + return rightParent.key; + } + else { + return null; // first item. + } + } + else if (cmp < 0) { + node = node.left; + } + else if (cmp > 0) { + rightParent = node; + node = node.right; + } + } + throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?'); + } + /** + * @returns True if the map is empty. + */ + isEmpty() { + return this.root_.isEmpty(); + } + /** + * @returns The total number of nodes in the map. + */ + count() { + return this.root_.count(); + } + /** + * @returns The minimum key in the map. + */ + minKey() { + return this.root_.minKey(); + } + /** + * @returns The maximum key in the map. + */ + maxKey() { + return this.root_.maxKey(); + } + /** + * Traverses the map in key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action) { + return this.root_.inorderTraversal(action); + } + /** + * Traverses the map in reverse key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns True if the traversal was aborted. + */ + reverseTraversal(action) { + return this.root_.reverseTraversal(action); + } + /** + * Returns an iterator over the SortedMap. + * @returns The iterator. + */ + getIterator(resultGenerator) { + return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator); + } + getIteratorFrom(key, resultGenerator) { + return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator); + } + getReverseIteratorFrom(key, resultGenerator) { + return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator); + } + getReverseIterator(resultGenerator) { + return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator); + } +} +/** + * Always use the same empty node, to reduce memory. + */ +SortedMap.EMPTY_NODE = new LLRBEmptyNode(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function NAME_ONLY_COMPARATOR(left, right) { + return nameCompare(left.name, right.name); +} +function NAME_COMPARATOR(left, right) { + return nameCompare(left, right); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let MAX_NODE$2; +function setMaxNode$1(val) { + MAX_NODE$2 = val; +} +const priorityHashText = function (priority) { + if (typeof priority === 'number') { + return 'number:' + doubleToIEEE754String(priority); + } + else { + return 'string:' + priority; + } +}; +/** + * Validates that a priority snapshot Node is valid. + */ +const validatePriorityNode = function (priorityNode) { + if (priorityNode.isLeafNode()) { + const val = priorityNode.val(); + assert(typeof val === 'string' || + typeof val === 'number' || + (typeof val === 'object' && contains(val, '.sv')), 'Priority must be a string or number.'); + } + else { + assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.'); + } + // Don't call getPriority() on MAX_NODE to avoid hitting assertion. + assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own."); +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let __childrenNodeConstructor; +/** + * LeafNode is a class for storing leaf nodes in a DataSnapshot. It + * implements Node and stores the value of the node (a string, + * number, or boolean) accessible via getValue(). + */ +class LeafNode { + static set __childrenNodeConstructor(val) { + __childrenNodeConstructor = val; + } + static get __childrenNodeConstructor() { + return __childrenNodeConstructor; + } + /** + * @param value_ - The value to store in this leaf node. The object type is + * possible in the event of a deferred value + * @param priorityNode_ - The priority of this node. + */ + constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) { + this.value_ = value_; + this.priorityNode_ = priorityNode_; + this.lazyHash_ = null; + assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value."); + validatePriorityNode(this.priorityNode_); + } + /** @inheritDoc */ + isLeafNode() { + return true; + } + /** @inheritDoc */ + getPriority() { + return this.priorityNode_; + } + /** @inheritDoc */ + updatePriority(newPriorityNode) { + return new LeafNode(this.value_, newPriorityNode); + } + /** @inheritDoc */ + getImmediateChild(childName) { + // Hack to treat priority as a regular child + if (childName === '.priority') { + return this.priorityNode_; + } + else { + return LeafNode.__childrenNodeConstructor.EMPTY_NODE; + } + } + /** @inheritDoc */ + getChild(path) { + if (pathIsEmpty(path)) { + return this; + } + else if (pathGetFront(path) === '.priority') { + return this.priorityNode_; + } + else { + return LeafNode.__childrenNodeConstructor.EMPTY_NODE; + } + } + hasChild() { + return false; + } + /** @inheritDoc */ + getPredecessorChildName(childName, childNode) { + return null; + } + /** @inheritDoc */ + updateImmediateChild(childName, newChildNode) { + if (childName === '.priority') { + return this.updatePriority(newChildNode); + } + else if (newChildNode.isEmpty() && childName !== '.priority') { + return this; + } + else { + return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_); + } + } + /** @inheritDoc */ + updateChild(path, newChildNode) { + const front = pathGetFront(path); + if (front === null) { + return newChildNode; + } + else if (newChildNode.isEmpty() && front !== '.priority') { + return this; + } + else { + assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path'); + return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode)); + } + } + /** @inheritDoc */ + isEmpty() { + return false; + } + /** @inheritDoc */ + numChildren() { + return 0; + } + /** @inheritDoc */ + forEachChild(index, action) { + return false; + } + val(exportFormat) { + if (exportFormat && !this.getPriority().isEmpty()) { + return { + '.value': this.getValue(), + '.priority': this.getPriority().val() + }; + } + else { + return this.getValue(); + } + } + /** @inheritDoc */ + hash() { + if (this.lazyHash_ === null) { + let toHash = ''; + if (!this.priorityNode_.isEmpty()) { + toHash += + 'priority:' + + priorityHashText(this.priorityNode_.val()) + + ':'; + } + const type = typeof this.value_; + toHash += type + ':'; + if (type === 'number') { + toHash += doubleToIEEE754String(this.value_); + } + else { + toHash += this.value_; + } + this.lazyHash_ = sha1(toHash); + } + return this.lazyHash_; + } + /** + * Returns the value of the leaf node. + * @returns The value of the node. + */ + getValue() { + return this.value_; + } + compareTo(other) { + if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) { + return 1; + } + else if (other instanceof LeafNode.__childrenNodeConstructor) { + return -1; + } + else { + assert(other.isLeafNode(), 'Unknown node type'); + return this.compareToLeafNode_(other); + } + } + /** + * Comparison specifically for two leaf nodes + */ + compareToLeafNode_(otherLeaf) { + const otherLeafType = typeof otherLeaf.value_; + const thisLeafType = typeof this.value_; + const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType); + const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType); + assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType); + assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType); + if (otherIndex === thisIndex) { + // Same type, compare values + if (thisLeafType === 'object') { + // Deferred value nodes are all equal, but we should also never get to this point... + return 0; + } + else { + // Note that this works because true > false, all others are number or string comparisons + if (this.value_ < otherLeaf.value_) { + return -1; + } + else if (this.value_ === otherLeaf.value_) { + return 0; + } + else { + return 1; + } + } + } + else { + return thisIndex - otherIndex; + } + } + withIndex() { + return this; + } + isIndexed() { + return true; + } + equals(other) { + if (other === this) { + return true; + } + else if (other.isLeafNode()) { + const otherLeaf = other; + return (this.value_ === otherLeaf.value_ && + this.priorityNode_.equals(otherLeaf.priorityNode_)); + } + else { + return false; + } + } +} +/** + * The sort order for comparing leaf nodes of different types. If two leaf nodes have + * the same type, the comparison falls back to their value + */ +LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string']; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let nodeFromJSON$1; +let MAX_NODE$1; +function setNodeFromJSON(val) { + nodeFromJSON$1 = val; +} +function setMaxNode(val) { + MAX_NODE$1 = val; +} +class PriorityIndex extends Index { + compare(a, b) { + const aPriority = a.node.getPriority(); + const bPriority = b.node.getPriority(); + const indexCmp = aPriority.compareTo(bPriority); + if (indexCmp === 0) { + return nameCompare(a.name, b.name); + } + else { + return indexCmp; + } + } + isDefinedOn(node) { + return !node.getPriority().isEmpty(); + } + indexedValueChanged(oldNode, newNode) { + return !oldNode.getPriority().equals(newNode.getPriority()); + } + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } + maxPost() { + return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1)); + } + makePost(indexValue, name) { + const priorityNode = nodeFromJSON$1(indexValue); + return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode)); + } + /** + * @returns String representation for inclusion in a query spec + */ + toString() { + return '.priority'; + } +} +const PRIORITY_INDEX = new PriorityIndex(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_2 = Math.log(2); +class Base12Num { + constructor(length) { + const logBase2 = (num) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + parseInt((Math.log(num) / LOG_2), 10); + const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2); + this.count = logBase2(length + 1); + this.current_ = this.count - 1; + const mask = bitMask(this.count); + this.bits_ = (length + 1) & mask; + } + nextBitIsOne() { + //noinspection JSBitwiseOperatorUsage + const result = !(this.bits_ & (0x1 << this.current_)); + this.current_--; + return result; + } +} +/** + * Takes a list of child nodes and constructs a SortedSet using the given comparison + * function + * + * Uses the algorithm described in the paper linked here: + * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458 + * + * @param childList - Unsorted list of children + * @param cmp - The comparison method to be used + * @param keyFn - An optional function to extract K from a node wrapper, if K's + * type is not NamedNode + * @param mapSortFn - An optional override for comparator used by the generated sorted map + */ +const buildChildSet = function (childList, cmp, keyFn, mapSortFn) { + childList.sort(cmp); + const buildBalancedTree = function (low, high) { + const length = high - low; + let namedNode; + let key; + if (length === 0) { + return null; + } + else if (length === 1) { + namedNode = childList[low]; + key = keyFn ? keyFn(namedNode) : namedNode; + return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null); + } + else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const middle = parseInt((length / 2), 10) + low; + const left = buildBalancedTree(low, middle); + const right = buildBalancedTree(middle + 1, high); + namedNode = childList[middle]; + key = keyFn ? keyFn(namedNode) : namedNode; + return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right); + } + }; + const buildFrom12Array = function (base12) { + let node = null; + let root = null; + let index = childList.length; + const buildPennant = function (chunkSize, color) { + const low = index - chunkSize; + const high = index; + index -= chunkSize; + const childTree = buildBalancedTree(low + 1, high); + const namedNode = childList[low]; + const key = keyFn ? keyFn(namedNode) : namedNode; + attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree)); + }; + const attachPennant = function (pennant) { + if (node) { + node.left = pennant; + node = pennant; + } + else { + root = pennant; + node = pennant; + } + }; + for (let i = 0; i < base12.count; ++i) { + const isOne = base12.nextBitIsOne(); + // The number of nodes taken in each slice is 2^(arr.length - (i + 1)) + const chunkSize = Math.pow(2, base12.count - (i + 1)); + if (isOne) { + buildPennant(chunkSize, LLRBNode.BLACK); + } + else { + // current == 2 + buildPennant(chunkSize, LLRBNode.BLACK); + buildPennant(chunkSize, LLRBNode.RED); + } + } + return root; + }; + const base12 = new Base12Num(childList.length); + const root = buildFrom12Array(base12); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return new SortedMap(mapSortFn || cmp, root); +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let _defaultIndexMap; +const fallbackObject = {}; +class IndexMap { + /** + * The default IndexMap for nodes without a priority + */ + static get Default() { + assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded'); + _defaultIndexMap = + _defaultIndexMap || + new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX }); + return _defaultIndexMap; + } + constructor(indexes_, indexSet_) { + this.indexes_ = indexes_; + this.indexSet_ = indexSet_; + } + get(indexKey) { + const sortedMap = safeGet(this.indexes_, indexKey); + if (!sortedMap) { + throw new Error('No index defined for ' + indexKey); + } + if (sortedMap instanceof SortedMap) { + return sortedMap; + } + else { + // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the + // regular child map + return null; + } + } + hasIndex(indexDefinition) { + return contains(this.indexSet_, indexDefinition.toString()); + } + addIndex(indexDefinition, existingChildren) { + assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap."); + const childList = []; + let sawIndexedValue = false; + const iter = existingChildren.getIterator(NamedNode.Wrap); + let next = iter.getNext(); + while (next) { + sawIndexedValue = + sawIndexedValue || indexDefinition.isDefinedOn(next.node); + childList.push(next); + next = iter.getNext(); + } + let newIndex; + if (sawIndexedValue) { + newIndex = buildChildSet(childList, indexDefinition.getCompare()); + } + else { + newIndex = fallbackObject; + } + const indexName = indexDefinition.toString(); + const newIndexSet = { ...this.indexSet_ }; + newIndexSet[indexName] = indexDefinition; + const newIndexes = { ...this.indexes_ }; + newIndexes[indexName] = newIndex; + return new IndexMap(newIndexes, newIndexSet); + } + /** + * Ensure that this node is properly tracked in any indexes that we're maintaining + */ + addToIndexes(namedNode, existingChildren) { + const newIndexes = map(this.indexes_, (indexedChildren, indexName) => { + const index = safeGet(this.indexSet_, indexName); + assert(index, 'Missing index implementation for ' + indexName); + if (indexedChildren === fallbackObject) { + // Check to see if we need to index everything + if (index.isDefinedOn(namedNode.node)) { + // We need to build this index + const childList = []; + const iter = existingChildren.getIterator(NamedNode.Wrap); + let next = iter.getNext(); + while (next) { + if (next.name !== namedNode.name) { + childList.push(next); + } + next = iter.getNext(); + } + childList.push(namedNode); + return buildChildSet(childList, index.getCompare()); + } + else { + // No change, this remains a fallback + return fallbackObject; + } + } + else { + const existingSnap = existingChildren.get(namedNode.name); + let newChildren = indexedChildren; + if (existingSnap) { + newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap)); + } + return newChildren.insert(namedNode, namedNode.node); + } + }); + return new IndexMap(newIndexes, this.indexSet_); + } + /** + * Create a new IndexMap instance with the given value removed + */ + removeFromIndexes(namedNode, existingChildren) { + const newIndexes = map(this.indexes_, (indexedChildren) => { + if (indexedChildren === fallbackObject) { + // This is the fallback. Just return it, nothing to do in this case + return indexedChildren; + } + else { + const existingSnap = existingChildren.get(namedNode.name); + if (existingSnap) { + return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap)); + } + else { + // No record of this child + return indexedChildren; + } + } + }); + return new IndexMap(newIndexes, this.indexSet_); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO: For memory savings, don't store priorityNode_ if it's empty. +let EMPTY_NODE; +/** + * ChildrenNode is a class for storing internal nodes in a DataSnapshot + * (i.e. nodes with children). It implements Node and stores the + * list of children in the children property, sorted by child name. + */ +class ChildrenNode { + static get EMPTY_NODE() { + return (EMPTY_NODE || + (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default))); + } + /** + * @param children_ - List of children of this node.. + * @param priorityNode_ - The priority of this node (as a snapshot node). + */ + constructor(children_, priorityNode_, indexMap_) { + this.children_ = children_; + this.priorityNode_ = priorityNode_; + this.indexMap_ = indexMap_; + this.lazyHash_ = null; + /** + * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use + * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own + * class instead of an empty ChildrenNode. + */ + if (this.priorityNode_) { + validatePriorityNode(this.priorityNode_); + } + if (this.children_.isEmpty()) { + assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority'); + } + } + /** @inheritDoc */ + isLeafNode() { + return false; + } + /** @inheritDoc */ + getPriority() { + return this.priorityNode_ || EMPTY_NODE; + } + /** @inheritDoc */ + updatePriority(newPriorityNode) { + if (this.children_.isEmpty()) { + // Don't allow priorities on empty nodes + return this; + } + else { + return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_); + } + } + /** @inheritDoc */ + getImmediateChild(childName) { + // Hack to treat priority as a regular child + if (childName === '.priority') { + return this.getPriority(); + } + else { + const child = this.children_.get(childName); + return child === null ? EMPTY_NODE : child; + } + } + /** @inheritDoc */ + getChild(path) { + const front = pathGetFront(path); + if (front === null) { + return this; + } + return this.getImmediateChild(front).getChild(pathPopFront(path)); + } + /** @inheritDoc */ + hasChild(childName) { + return this.children_.get(childName) !== null; + } + /** @inheritDoc */ + updateImmediateChild(childName, newChildNode) { + assert(newChildNode, 'We should always be passing snapshot nodes'); + if (childName === '.priority') { + return this.updatePriority(newChildNode); + } + else { + const namedNode = new NamedNode(childName, newChildNode); + let newChildren, newIndexMap; + if (newChildNode.isEmpty()) { + newChildren = this.children_.remove(childName); + newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_); + } + else { + newChildren = this.children_.insert(childName, newChildNode); + newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_); + } + const newPriority = newChildren.isEmpty() + ? EMPTY_NODE + : this.priorityNode_; + return new ChildrenNode(newChildren, newPriority, newIndexMap); + } + } + /** @inheritDoc */ + updateChild(path, newChildNode) { + const front = pathGetFront(path); + if (front === null) { + return newChildNode; + } + else { + assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path'); + const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode); + return this.updateImmediateChild(front, newImmediateChild); + } + } + /** @inheritDoc */ + isEmpty() { + return this.children_.isEmpty(); + } + /** @inheritDoc */ + numChildren() { + return this.children_.count(); + } + /** @inheritDoc */ + val(exportFormat) { + if (this.isEmpty()) { + return null; + } + const obj = {}; + let numKeys = 0, maxKey = 0, allIntegerKeys = true; + this.forEachChild(PRIORITY_INDEX, (key, childNode) => { + obj[key] = childNode.val(exportFormat); + numKeys++; + if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) { + maxKey = Math.max(maxKey, Number(key)); + } + else { + allIntegerKeys = false; + } + }); + if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) { + // convert to array. + const array = []; + // eslint-disable-next-line guard-for-in + for (const key in obj) { + array[key] = obj[key]; + } + return array; + } + else { + if (exportFormat && !this.getPriority().isEmpty()) { + obj['.priority'] = this.getPriority().val(); + } + return obj; + } + } + /** @inheritDoc */ + hash() { + if (this.lazyHash_ === null) { + let toHash = ''; + if (!this.getPriority().isEmpty()) { + toHash += + 'priority:' + + priorityHashText(this.getPriority().val()) + + ':'; + } + this.forEachChild(PRIORITY_INDEX, (key, childNode) => { + const childHash = childNode.hash(); + if (childHash !== '') { + toHash += ':' + key + ':' + childHash; + } + }); + this.lazyHash_ = toHash === '' ? '' : sha1(toHash); + } + return this.lazyHash_; + } + /** @inheritDoc */ + getPredecessorChildName(childName, childNode, index) { + const idx = this.resolveIndex_(index); + if (idx) { + const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode)); + return predecessor ? predecessor.name : null; + } + else { + return this.children_.getPredecessorKey(childName); + } + } + getFirstChildName(indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + const minKey = idx.minKey(); + return minKey && minKey.name; + } + else { + return this.children_.minKey(); + } + } + getFirstChild(indexDefinition) { + const minKey = this.getFirstChildName(indexDefinition); + if (minKey) { + return new NamedNode(minKey, this.children_.get(minKey)); + } + else { + return null; + } + } + /** + * Given an index, return the key name of the largest value we have, according to that index + */ + getLastChildName(indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + const maxKey = idx.maxKey(); + return maxKey && maxKey.name; + } + else { + return this.children_.maxKey(); + } + } + getLastChild(indexDefinition) { + const maxKey = this.getLastChildName(indexDefinition); + if (maxKey) { + return new NamedNode(maxKey, this.children_.get(maxKey)); + } + else { + return null; + } + } + forEachChild(index, action) { + const idx = this.resolveIndex_(index); + if (idx) { + return idx.inorderTraversal(wrappedNode => { + return action(wrappedNode.name, wrappedNode.node); + }); + } + else { + return this.children_.inorderTraversal(action); + } + } + getIterator(indexDefinition) { + return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition); + } + getIteratorFrom(startPost, indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + return idx.getIteratorFrom(startPost, key => key); + } + else { + const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap); + let next = iterator.peek(); + while (next != null && indexDefinition.compare(next, startPost) < 0) { + iterator.getNext(); + next = iterator.peek(); + } + return iterator; + } + } + getReverseIterator(indexDefinition) { + return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition); + } + getReverseIteratorFrom(endPost, indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + return idx.getReverseIteratorFrom(endPost, key => { + return key; + }); + } + else { + const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap); + let next = iterator.peek(); + while (next != null && indexDefinition.compare(next, endPost) > 0) { + iterator.getNext(); + next = iterator.peek(); + } + return iterator; + } + } + compareTo(other) { + if (this.isEmpty()) { + if (other.isEmpty()) { + return 0; + } + else { + return -1; + } + } + else if (other.isLeafNode() || other.isEmpty()) { + return 1; + } + else if (other === MAX_NODE) { + return -1; + } + else { + // Must be another node with children. + return 0; + } + } + withIndex(indexDefinition) { + if (indexDefinition === KEY_INDEX || + this.indexMap_.hasIndex(indexDefinition)) { + return this; + } + else { + const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_); + return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap); + } + } + isIndexed(index) { + return index === KEY_INDEX || this.indexMap_.hasIndex(index); + } + equals(other) { + if (other === this) { + return true; + } + else if (other.isLeafNode()) { + return false; + } + else { + const otherChildrenNode = other; + if (!this.getPriority().equals(otherChildrenNode.getPriority())) { + return false; + } + else if (this.children_.count() === otherChildrenNode.children_.count()) { + const thisIter = this.getIterator(PRIORITY_INDEX); + const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX); + let thisCurrent = thisIter.getNext(); + let otherCurrent = otherIter.getNext(); + while (thisCurrent && otherCurrent) { + if (thisCurrent.name !== otherCurrent.name || + !thisCurrent.node.equals(otherCurrent.node)) { + return false; + } + thisCurrent = thisIter.getNext(); + otherCurrent = otherIter.getNext(); + } + return thisCurrent === null && otherCurrent === null; + } + else { + return false; + } + } + } + /** + * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used + * instead. + * + */ + resolveIndex_(indexDefinition) { + if (indexDefinition === KEY_INDEX) { + return null; + } + else { + return this.indexMap_.get(indexDefinition.toString()); + } + } +} +ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/; +class MaxNode extends ChildrenNode { + constructor() { + super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default); + } + compareTo(other) { + if (other === this) { + return 0; + } + else { + return 1; + } + } + equals(other) { + // Not that we every compare it, but MAX_NODE is only ever equal to itself + return other === this; + } + getPriority() { + return this; + } + getImmediateChild(childName) { + return ChildrenNode.EMPTY_NODE; + } + isEmpty() { + return false; + } +} +/** + * Marker that will sort higher than any other snapshot. + */ +const MAX_NODE = new MaxNode(); +Object.defineProperties(NamedNode, { + MIN: { + value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE) + }, + MAX: { + value: new NamedNode(MAX_NAME, MAX_NODE) + } +}); +/** + * Reference Extensions + */ +KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE; +LeafNode.__childrenNodeConstructor = ChildrenNode; +setMaxNode$1(MAX_NODE); +setMaxNode(MAX_NODE); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const USE_HINZE = true; +/** + * Constructs a snapshot node representing the passed JSON and returns it. + * @param json - JSON to create a node for. + * @param priority - Optional priority to use. This will be ignored if the + * passed JSON contains a .priority property. + */ +function nodeFromJSON(json, priority = null) { + if (json === null) { + return ChildrenNode.EMPTY_NODE; + } + if (typeof json === 'object' && '.priority' in json) { + priority = json['.priority']; + } + assert(priority === null || + typeof priority === 'string' || + typeof priority === 'number' || + (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority); + if (typeof json === 'object' && '.value' in json && json['.value'] !== null) { + json = json['.value']; + } + // Valid leaf nodes include non-objects or server-value wrapper objects + if (typeof json !== 'object' || '.sv' in json) { + const jsonLeaf = json; + return new LeafNode(jsonLeaf, nodeFromJSON(priority)); + } + if (!(json instanceof Array) && USE_HINZE) { + const children = []; + let childrenHavePriority = false; + const hinzeJsonObj = json; + each(hinzeJsonObj, (key, child) => { + if (key.substring(0, 1) !== '.') { + // Ignore metadata nodes + const childNode = nodeFromJSON(child); + if (!childNode.isEmpty()) { + childrenHavePriority = + childrenHavePriority || !childNode.getPriority().isEmpty(); + children.push(new NamedNode(key, childNode)); + } + } + }); + if (children.length === 0) { + return ChildrenNode.EMPTY_NODE; + } + const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR); + if (childrenHavePriority) { + const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare()); + return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX })); + } + else { + return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default); + } + } + else { + let node = ChildrenNode.EMPTY_NODE; + each(json, (key, childData) => { + if (contains(json, key)) { + if (key.substring(0, 1) !== '.') { + // ignore metadata nodes. + const childNode = nodeFromJSON(childData); + if (childNode.isLeafNode() || !childNode.isEmpty()) { + node = node.updateImmediateChild(key, childNode); + } + } + } + }); + return node.updatePriority(nodeFromJSON(priority)); + } +} +setNodeFromJSON(nodeFromJSON); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class PathIndex extends Index { + constructor(indexPath_) { + super(); + this.indexPath_ = indexPath_; + assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key"); + } + extractChild(snap) { + return snap.getChild(this.indexPath_); + } + isDefinedOn(node) { + return !node.getChild(this.indexPath_).isEmpty(); + } + compare(a, b) { + const aChild = this.extractChild(a.node); + const bChild = this.extractChild(b.node); + const indexCmp = aChild.compareTo(bChild); + if (indexCmp === 0) { + return nameCompare(a.name, b.name); + } + else { + return indexCmp; + } + } + makePost(indexValue, name) { + const valueNode = nodeFromJSON(indexValue); + const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode); + return new NamedNode(name, node); + } + maxPost() { + const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE); + return new NamedNode(MAX_NAME, node); + } + toString() { + return pathSlice(this.indexPath_, 0).join('/'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ValueIndex extends Index { + compare(a, b) { + const indexCmp = a.node.compareTo(b.node); + if (indexCmp === 0) { + return nameCompare(a.name, b.name); + } + else { + return indexCmp; + } + } + isDefinedOn(node) { + return true; + } + indexedValueChanged(oldNode, newNode) { + return !oldNode.equals(newNode); + } + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } + maxPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MAX; + } + makePost(indexValue, name) { + const valueNode = nodeFromJSON(indexValue); + return new NamedNode(name, valueNode); + } + /** + * @returns String representation for inclusion in a query spec + */ + toString() { + return '.value'; + } +} +const VALUE_INDEX = new ValueIndex(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function changeValue(snapshotNode) { + return { type: "value" /* ChangeType.VALUE */, snapshotNode }; +} +function changeChildAdded(childName, snapshotNode) { + return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode, childName }; +} +function changeChildRemoved(childName, snapshotNode) { + return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode, childName }; +} +function changeChildChanged(childName, snapshotNode, oldSnap) { + return { + type: "child_changed" /* ChangeType.CHILD_CHANGED */, + snapshotNode, + childName, + oldSnap + }; +} +function changeChildMoved(childName, snapshotNode) { + return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode, childName }; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Doesn't really filter nodes but applies an index to the node and keeps track of any changes + */ +class IndexedFilter { + constructor(index_) { + this.index_ = index_; + } + updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) { + assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated'); + const oldChild = snap.getImmediateChild(key); + // Check if anything actually changed. + if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) { + // There's an edge case where a child can enter or leave the view because affectedPath was set to null. + // In this case, affectedPath will appear null in both the old and new snapshots. So we need + // to avoid treating these cases as "nothing changed." + if (oldChild.isEmpty() === newChild.isEmpty()) { + // Nothing changed. + // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it. + //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.'); + return snap; + } + } + if (optChangeAccumulator != null) { + if (newChild.isEmpty()) { + if (snap.hasChild(key)) { + optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild)); + } + else { + assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node'); + } + } + else if (oldChild.isEmpty()) { + optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild)); + } + else { + optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild)); + } + } + if (snap.isLeafNode() && newChild.isEmpty()) { + return snap; + } + else { + // Make sure the node is indexed + return snap.updateImmediateChild(key, newChild).withIndex(this.index_); + } + } + updateFullNode(oldSnap, newSnap, optChangeAccumulator) { + if (optChangeAccumulator != null) { + if (!oldSnap.isLeafNode()) { + oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => { + if (!newSnap.hasChild(key)) { + optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode)); + } + }); + } + if (!newSnap.isLeafNode()) { + newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => { + if (oldSnap.hasChild(key)) { + const oldChild = oldSnap.getImmediateChild(key); + if (!oldChild.equals(childNode)) { + optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild)); + } + } + else { + optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode)); + } + }); + } + } + return newSnap.withIndex(this.index_); + } + updatePriority(oldSnap, newPriority) { + if (oldSnap.isEmpty()) { + return ChildrenNode.EMPTY_NODE; + } + else { + return oldSnap.updatePriority(newPriority); + } + } + filtersNodes() { + return false; + } + getIndexedFilter() { + return this; + } + getIndex() { + return this.index_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node + */ +class RangedFilter { + constructor(params) { + this.indexedFilter_ = new IndexedFilter(params.getIndex()); + this.index_ = params.getIndex(); + this.startPost_ = RangedFilter.getStartPost_(params); + this.endPost_ = RangedFilter.getEndPost_(params); + this.startIsInclusive_ = !params.startAfterSet_; + this.endIsInclusive_ = !params.endBeforeSet_; + } + getStartPost() { + return this.startPost_; + } + getEndPost() { + return this.endPost_; + } + matches(node) { + const isWithinStart = this.startIsInclusive_ + ? this.index_.compare(this.getStartPost(), node) <= 0 + : this.index_.compare(this.getStartPost(), node) < 0; + const isWithinEnd = this.endIsInclusive_ + ? this.index_.compare(node, this.getEndPost()) <= 0 + : this.index_.compare(node, this.getEndPost()) < 0; + return isWithinStart && isWithinEnd; + } + updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) { + if (!this.matches(new NamedNode(key, newChild))) { + newChild = ChildrenNode.EMPTY_NODE; + } + return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator); + } + updateFullNode(oldSnap, newSnap, optChangeAccumulator) { + if (newSnap.isLeafNode()) { + // Make sure we have a children node with the correct index, not a leaf node; + newSnap = ChildrenNode.EMPTY_NODE; + } + let filtered = newSnap.withIndex(this.index_); + // Don't support priorities on queries + filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE); + const self = this; + newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => { + if (!self.matches(new NamedNode(key, childNode))) { + filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE); + } + }); + return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator); + } + updatePriority(oldSnap, newPriority) { + // Don't support priorities on queries + return oldSnap; + } + filtersNodes() { + return true; + } + getIndexedFilter() { + return this.indexedFilter_; + } + getIndex() { + return this.index_; + } + static getStartPost_(params) { + if (params.hasStart()) { + const startName = params.getIndexStartName(); + return params.getIndex().makePost(params.getIndexStartValue(), startName); + } + else { + return params.getIndex().minPost(); + } + } + static getEndPost_(params) { + if (params.hasEnd()) { + const endName = params.getIndexEndName(); + return params.getIndex().makePost(params.getIndexEndValue(), endName); + } + else { + return params.getIndex().maxPost(); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible + */ +class LimitedFilter { + constructor(params) { + this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node); + this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node); + this.withinStartPost = (node) => { + const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node); + return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0; + }; + this.withinEndPost = (node) => { + const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost()); + return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0; + }; + this.rangedFilter_ = new RangedFilter(params); + this.index_ = params.getIndex(); + this.limit_ = params.getLimit(); + this.reverse_ = !params.isViewFromLeft(); + this.startIsInclusive_ = !params.startAfterSet_; + this.endIsInclusive_ = !params.endBeforeSet_; + } + updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) { + if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) { + newChild = ChildrenNode.EMPTY_NODE; + } + if (snap.getImmediateChild(key).equals(newChild)) { + // No change + return snap; + } + else if (snap.numChildren() < this.limit_) { + return this.rangedFilter_ + .getIndexedFilter() + .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator); + } + else { + return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator); + } + } + updateFullNode(oldSnap, newSnap, optChangeAccumulator) { + let filtered; + if (newSnap.isLeafNode() || newSnap.isEmpty()) { + // Make sure we have a children node with the correct index, not a leaf node; + filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_); + } + else { + if (this.limit_ * 2 < newSnap.numChildren() && + newSnap.isIndexed(this.index_)) { + // Easier to build up a snapshot, since what we're given has more than twice the elements we want + filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_); + // anchor to the startPost, endPost, or last element as appropriate + let iterator; + if (this.reverse_) { + iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_); + } + else { + iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_); + } + let count = 0; + while (iterator.hasNext() && count < this.limit_) { + const next = iterator.getNext(); + if (!this.withinDirectionalStart(next)) { + // if we have not reached the start, skip to the next element + continue; + } + else if (!this.withinDirectionalEnd(next)) { + // if we have reached the end, stop adding elements + break; + } + else { + filtered = filtered.updateImmediateChild(next.name, next.node); + count++; + } + } + } + else { + // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one + filtered = newSnap.withIndex(this.index_); + // Don't support priorities on queries + filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE); + let iterator; + if (this.reverse_) { + iterator = filtered.getReverseIterator(this.index_); + } + else { + iterator = filtered.getIterator(this.index_); + } + let count = 0; + while (iterator.hasNext()) { + const next = iterator.getNext(); + const inRange = count < this.limit_ && + this.withinDirectionalStart(next) && + this.withinDirectionalEnd(next); + if (inRange) { + count++; + } + else { + filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE); + } + } + } + } + return this.rangedFilter_ + .getIndexedFilter() + .updateFullNode(oldSnap, filtered, optChangeAccumulator); + } + updatePriority(oldSnap, newPriority) { + // Don't support priorities on queries + return oldSnap; + } + filtersNodes() { + return true; + } + getIndexedFilter() { + return this.rangedFilter_.getIndexedFilter(); + } + getIndex() { + return this.index_; + } + fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) { + // TODO: rename all cache stuff etc to general snap terminology + let cmp; + if (this.reverse_) { + const indexCmp = this.index_.getCompare(); + cmp = (a, b) => indexCmp(b, a); + } + else { + cmp = this.index_.getCompare(); + } + const oldEventCache = snap; + assert(oldEventCache.numChildren() === this.limit_, ''); + const newChildNamedNode = new NamedNode(childKey, childSnap); + const windowBoundary = this.reverse_ + ? oldEventCache.getFirstChild(this.index_) + : oldEventCache.getLastChild(this.index_); + const inRange = this.rangedFilter_.matches(newChildNamedNode); + if (oldEventCache.hasChild(childKey)) { + const oldChildSnap = oldEventCache.getImmediateChild(childKey); + let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_); + while (nextChild != null && + (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) { + // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't + // been applied to the limited filter yet. Ignore this next child which will be updated later in + // the limited filter... + nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_); + } + const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode); + const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0; + if (remainsInWindow) { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap)); + } + return oldEventCache.updateImmediateChild(childKey, childSnap); + } + else { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap)); + } + const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE); + const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild); + if (nextChildInRange) { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node)); + } + return newEventCache.updateImmediateChild(nextChild.name, nextChild.node); + } + else { + return newEventCache; + } + } + } + else if (childSnap.isEmpty()) { + // we're deleting a node, but it was not in the window, so ignore it + return snap; + } + else if (inRange) { + if (cmp(windowBoundary, newChildNamedNode) >= 0) { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node)); + changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap)); + } + return oldEventCache + .updateImmediateChild(childKey, childSnap) + .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE); + } + else { + return snap; + } + } + else { + return snap; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a + * range to be returned for a particular location. It is assumed that validation of parameters is done at the + * user-facing API level, so it is not done here. + * + * @internal + */ +class QueryParams { + constructor() { + this.limitSet_ = false; + this.startSet_ = false; + this.startNameSet_ = false; + this.startAfterSet_ = false; // can only be true if startSet_ is true + this.endSet_ = false; + this.endNameSet_ = false; + this.endBeforeSet_ = false; // can only be true if endSet_ is true + this.limit_ = 0; + this.viewFrom_ = ''; + this.indexStartValue_ = null; + this.indexStartName_ = ''; + this.indexEndValue_ = null; + this.indexEndName_ = ''; + this.index_ = PRIORITY_INDEX; + } + hasStart() { + return this.startSet_; + } + /** + * @returns True if it would return from left. + */ + isViewFromLeft() { + if (this.viewFrom_ === '') { + // limit(), rather than limitToFirst or limitToLast was called. + // This means that only one of startSet_ and endSet_ is true. Use them + // to calculate which side of the view to anchor to. If neither is set, + // anchor to the end. + return this.startSet_; + } + else { + return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */; + } + } + /** + * Only valid to call if hasStart() returns true + */ + getIndexStartValue() { + assert(this.startSet_, 'Only valid if start has been set'); + return this.indexStartValue_; + } + /** + * Only valid to call if hasStart() returns true. + * Returns the starting key name for the range defined by these query parameters + */ + getIndexStartName() { + assert(this.startSet_, 'Only valid if start has been set'); + if (this.startNameSet_) { + return this.indexStartName_; + } + else { + return MIN_NAME; + } + } + hasEnd() { + return this.endSet_; + } + /** + * Only valid to call if hasEnd() returns true. + */ + getIndexEndValue() { + assert(this.endSet_, 'Only valid if end has been set'); + return this.indexEndValue_; + } + /** + * Only valid to call if hasEnd() returns true. + * Returns the end key name for the range defined by these query parameters + */ + getIndexEndName() { + assert(this.endSet_, 'Only valid if end has been set'); + if (this.endNameSet_) { + return this.indexEndName_; + } + else { + return MAX_NAME; + } + } + hasLimit() { + return this.limitSet_; + } + /** + * @returns True if a limit has been set and it has been explicitly anchored + */ + hasAnchoredLimit() { + return this.limitSet_ && this.viewFrom_ !== ''; + } + /** + * Only valid to call if hasLimit() returns true + */ + getLimit() { + assert(this.limitSet_, 'Only valid if limit has been set'); + return this.limit_; + } + getIndex() { + return this.index_; + } + loadsAllData() { + return !(this.startSet_ || this.endSet_ || this.limitSet_); + } + isDefault() { + return this.loadsAllData() && this.index_ === PRIORITY_INDEX; + } + copy() { + const copy = new QueryParams(); + copy.limitSet_ = this.limitSet_; + copy.limit_ = this.limit_; + copy.startSet_ = this.startSet_; + copy.startAfterSet_ = this.startAfterSet_; + copy.indexStartValue_ = this.indexStartValue_; + copy.startNameSet_ = this.startNameSet_; + copy.indexStartName_ = this.indexStartName_; + copy.endSet_ = this.endSet_; + copy.endBeforeSet_ = this.endBeforeSet_; + copy.indexEndValue_ = this.indexEndValue_; + copy.endNameSet_ = this.endNameSet_; + copy.indexEndName_ = this.indexEndName_; + copy.index_ = this.index_; + copy.viewFrom_ = this.viewFrom_; + return copy; + } +} +function queryParamsGetNodeFilter(queryParams) { + if (queryParams.loadsAllData()) { + return new IndexedFilter(queryParams.getIndex()); + } + else if (queryParams.hasLimit()) { + return new LimitedFilter(queryParams); + } + else { + return new RangedFilter(queryParams); + } +} +function queryParamsLimitToFirst(queryParams, newLimit) { + const newParams = queryParams.copy(); + newParams.limitSet_ = true; + newParams.limit_ = newLimit; + newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */; + return newParams; +} +function queryParamsLimitToLast(queryParams, newLimit) { + const newParams = queryParams.copy(); + newParams.limitSet_ = true; + newParams.limit_ = newLimit; + newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */; + return newParams; +} +function queryParamsStartAt(queryParams, indexValue, key) { + const newParams = queryParams.copy(); + newParams.startSet_ = true; + if (indexValue === undefined) { + indexValue = null; + } + newParams.indexStartValue_ = indexValue; + if (key != null) { + newParams.startNameSet_ = true; + newParams.indexStartName_ = key; + } + else { + newParams.startNameSet_ = false; + newParams.indexStartName_ = ''; + } + return newParams; +} +function queryParamsStartAfter(queryParams, indexValue, key) { + let params; + if (queryParams.index_ === KEY_INDEX || !!key) { + params = queryParamsStartAt(queryParams, indexValue, key); + } + else { + params = queryParamsStartAt(queryParams, indexValue, MAX_NAME); + } + params.startAfterSet_ = true; + return params; +} +function queryParamsEndAt(queryParams, indexValue, key) { + const newParams = queryParams.copy(); + newParams.endSet_ = true; + if (indexValue === undefined) { + indexValue = null; + } + newParams.indexEndValue_ = indexValue; + if (key !== undefined) { + newParams.endNameSet_ = true; + newParams.indexEndName_ = key; + } + else { + newParams.endNameSet_ = false; + newParams.indexEndName_ = ''; + } + return newParams; +} +function queryParamsEndBefore(queryParams, indexValue, key) { + let params; + if (queryParams.index_ === KEY_INDEX || !!key) { + params = queryParamsEndAt(queryParams, indexValue, key); + } + else { + params = queryParamsEndAt(queryParams, indexValue, MIN_NAME); + } + params.endBeforeSet_ = true; + return params; +} +function queryParamsOrderBy(queryParams, index) { + const newParams = queryParams.copy(); + newParams.index_ = index; + return newParams; +} +/** + * Returns a set of REST query string parameters representing this query. + * + * @returns query string parameters + */ +function queryParamsToRestQueryStringParameters(queryParams) { + const qs = {}; + if (queryParams.isDefault()) { + return qs; + } + let orderBy; + if (queryParams.index_ === PRIORITY_INDEX) { + orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */; + } + else if (queryParams.index_ === VALUE_INDEX) { + orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */; + } + else if (queryParams.index_ === KEY_INDEX) { + orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */; + } + else { + assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!'); + orderBy = queryParams.index_.toString(); + } + qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = stringify(orderBy); + if (queryParams.startSet_) { + const startParam = queryParams.startAfterSet_ + ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */ + : "startAt" /* REST_QUERY_CONSTANTS.START_AT */; + qs[startParam] = stringify(queryParams.indexStartValue_); + if (queryParams.startNameSet_) { + qs[startParam] += ',' + stringify(queryParams.indexStartName_); + } + } + if (queryParams.endSet_) { + const endParam = queryParams.endBeforeSet_ + ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */ + : "endAt" /* REST_QUERY_CONSTANTS.END_AT */; + qs[endParam] = stringify(queryParams.indexEndValue_); + if (queryParams.endNameSet_) { + qs[endParam] += ',' + stringify(queryParams.indexEndName_); + } + } + if (queryParams.limitSet_) { + if (queryParams.isViewFromLeft()) { + qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_; + } + else { + qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_; + } + } + return qs; +} +function queryParamsGetQueryObject(queryParams) { + const obj = {}; + if (queryParams.startSet_) { + obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] = + queryParams.indexStartValue_; + if (queryParams.startNameSet_) { + obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] = + queryParams.indexStartName_; + } + obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] = + !queryParams.startAfterSet_; + } + if (queryParams.endSet_) { + obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_; + if (queryParams.endNameSet_) { + obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_; + } + obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] = + !queryParams.endBeforeSet_; + } + if (queryParams.limitSet_) { + obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_; + let viewFrom = queryParams.viewFrom_; + if (viewFrom === '') { + if (queryParams.isViewFromLeft()) { + viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */; + } + else { + viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */; + } + } + obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom; + } + // For now, priority index is the default, so we only specify if it's some other index + if (queryParams.index_ !== PRIORITY_INDEX) { + obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString(); + } + return obj; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An implementation of ServerActions that communicates with the server via REST requests. + * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full + * persistent connection (using WebSockets or long-polling) + */ +class ReadonlyRestClient extends ServerActions { + reportStats(stats) { + throw new Error('Method not implemented.'); + } + static getListenId_(query, tag) { + if (tag !== undefined) { + return 'tag$' + tag; + } + else { + assert(query._queryParams.isDefault(), "should have a tag if it's not a default query."); + return query._path.toString(); + } + } + /** + * @param repoInfo_ - Data about the namespace we are connecting to + * @param onDataUpdate_ - A callback for new data from the server + */ + constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) { + super(); + this.repoInfo_ = repoInfo_; + this.onDataUpdate_ = onDataUpdate_; + this.authTokenProvider_ = authTokenProvider_; + this.appCheckTokenProvider_ = appCheckTokenProvider_; + /** @private {function(...[*])} */ + this.log_ = logWrapper('p:rest:'); + /** + * We don't actually need to track listens, except to prevent us calling an onComplete for a listen + * that's been removed. :-/ + */ + this.listens_ = {}; + } + /** @inheritDoc */ + listen(query, currentHashFn, tag, onComplete) { + const pathString = query._path.toString(); + this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier); + // Mark this listener so we can tell if it's removed. + const listenId = ReadonlyRestClient.getListenId_(query, tag); + const thisListen = {}; + this.listens_[listenId] = thisListen; + const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams); + this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => { + let data = result; + if (error === 404) { + data = null; + error = null; + } + if (error === null) { + this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag); + } + if (safeGet(this.listens_, listenId) === thisListen) { + let status; + if (!error) { + status = 'ok'; + } + else if (error === 401) { + status = 'permission_denied'; + } + else { + status = 'rest_error:' + error; + } + onComplete(status, null); + } + }); + } + /** @inheritDoc */ + unlisten(query, tag) { + const listenId = ReadonlyRestClient.getListenId_(query, tag); + delete this.listens_[listenId]; + } + get(query) { + const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams); + const pathString = query._path.toString(); + const deferred = new Deferred(); + this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => { + let data = result; + if (error === 404) { + data = null; + error = null; + } + if (error === null) { + this.onDataUpdate_(pathString, data, + /*isMerge=*/ false, + /*tag=*/ null); + deferred.resolve(data); + } + else { + deferred.reject(new Error(data)); + } + }); + return deferred.promise; + } + /** @inheritDoc */ + refreshAuthToken(token) { + // no-op since we just always call getToken. + } + /** + * Performs a REST request to the given path, with the provided query string parameters, + * and any auth credentials we have. + */ + restRequest_(pathString, queryStringParameters = {}, callback) { + queryStringParameters['format'] = 'export'; + return Promise.all([ + this.authTokenProvider_.getToken(/*forceRefresh=*/ false), + this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false) + ]).then(([authToken, appCheckToken]) => { + if (authToken && authToken.accessToken) { + queryStringParameters['auth'] = authToken.accessToken; + } + if (appCheckToken && appCheckToken.token) { + queryStringParameters['ac'] = appCheckToken.token; + } + const url = (this.repoInfo_.secure ? 'https://' : 'http://') + + this.repoInfo_.host + + pathString + + '?' + + 'ns=' + + this.repoInfo_.namespace + + querystring(queryStringParameters); + this.log_('Sending REST request for ' + url); + const xhr = new XMLHttpRequest(); + xhr.onreadystatechange = () => { + if (callback && xhr.readyState === 4) { + this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText); + let res = null; + if (xhr.status >= 200 && xhr.status < 300) { + try { + res = jsonEval(xhr.responseText); + } + catch (e) { + warn('Failed to parse JSON response for ' + + url + + ': ' + + xhr.responseText); + } + callback(null, res); + } + else { + // 401 and 404 are expected. + if (xhr.status !== 401 && xhr.status !== 404) { + warn('Got unsuccessful REST response for ' + + url + + ' Status: ' + + xhr.status); + } + callback(xhr.status); + } + callback = null; + } + }; + xhr.open('GET', url, /*asynchronous=*/ true); + xhr.send(); + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Mutable object which basically just stores a reference to the "latest" immutable snapshot. + */ +class SnapshotHolder { + constructor() { + this.rootNode_ = ChildrenNode.EMPTY_NODE; + } + getNode(path) { + return this.rootNode_.getChild(path); + } + updateSnapshot(path, newSnapshotNode) { + this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newSparseSnapshotTree() { + return { + value: null, + children: new Map() + }; +} +/** + * Stores the given node at the specified path. If there is already a node + * at a shallower path, it merges the new data into that snapshot node. + * + * @param path - Path to look up snapshot for. + * @param data - The new data, or null. + */ +function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) { + if (pathIsEmpty(path)) { + sparseSnapshotTree.value = data; + sparseSnapshotTree.children.clear(); + } + else if (sparseSnapshotTree.value !== null) { + sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data); + } + else { + const childKey = pathGetFront(path); + if (!sparseSnapshotTree.children.has(childKey)) { + sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree()); + } + const child = sparseSnapshotTree.children.get(childKey); + path = pathPopFront(path); + sparseSnapshotTreeRemember(child, path, data); + } +} +/** + * Purge the data at path from the cache. + * + * @param path - Path to look up snapshot for. + * @returns True if this node should now be removed. + */ +function sparseSnapshotTreeForget(sparseSnapshotTree, path) { + if (pathIsEmpty(path)) { + sparseSnapshotTree.value = null; + sparseSnapshotTree.children.clear(); + return true; + } + else { + if (sparseSnapshotTree.value !== null) { + if (sparseSnapshotTree.value.isLeafNode()) { + // We're trying to forget a node that doesn't exist + return false; + } + else { + const value = sparseSnapshotTree.value; + sparseSnapshotTree.value = null; + value.forEachChild(PRIORITY_INDEX, (key, tree) => { + sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree); + }); + return sparseSnapshotTreeForget(sparseSnapshotTree, path); + } + } + else if (sparseSnapshotTree.children.size > 0) { + const childKey = pathGetFront(path); + path = pathPopFront(path); + if (sparseSnapshotTree.children.has(childKey)) { + const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path); + if (safeToRemove) { + sparseSnapshotTree.children.delete(childKey); + } + } + return sparseSnapshotTree.children.size === 0; + } + else { + return true; + } + } +} +/** + * Recursively iterates through all of the stored tree and calls the + * callback on each one. + * + * @param prefixPath - Path to look up node for. + * @param func - The function to invoke for each tree. + */ +function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) { + if (sparseSnapshotTree.value !== null) { + func(prefixPath, sparseSnapshotTree.value); + } + else { + sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => { + const path = new Path(prefixPath.toString() + '/' + key); + sparseSnapshotTreeForEachTree(tree, path, func); + }); + } +} +/** + * Iterates through each immediate child and triggers the callback. + * Only seems to be used in tests. + * + * @param func - The function to invoke for each child. + */ +function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) { + sparseSnapshotTree.children.forEach((tree, key) => { + func(key, tree); + }); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns the delta from the previous call to get stats. + * + * @param collection_ - The collection to "listen" to. + */ +class StatsListener { + constructor(collection_) { + this.collection_ = collection_; + this.last_ = null; + } + get() { + const newStats = this.collection_.get(); + const delta = { ...newStats }; + if (this.last_) { + each(this.last_, (stat, value) => { + delta[stat] = delta[stat] - value; + }); + } + this.last_ = newStats; + return delta; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably +// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10 +// seconds to try to ensure the Firebase connection is established / settled. +const FIRST_STATS_MIN_TIME = 10 * 1000; +const FIRST_STATS_MAX_TIME = 30 * 1000; +// We'll continue to report stats on average every 5 minutes. +const REPORT_STATS_INTERVAL = 5 * 60 * 1000; +class StatsReporter { + constructor(collection, server_) { + this.server_ = server_; + this.statsToReport_ = {}; + this.statsListener_ = new StatsListener(collection); + const timeout = FIRST_STATS_MIN_TIME + + (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random(); + setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout)); + } + reportStats_() { + const stats = this.statsListener_.get(); + const reportedStats = {}; + let haveStatsToReport = false; + each(stats, (stat, value) => { + if (value > 0 && contains(this.statsToReport_, stat)) { + reportedStats[stat] = value; + haveStatsToReport = true; + } + }); + if (haveStatsToReport) { + this.server_.reportStats(reportedStats); + } + // queue our next run. + setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @enum + */ +var OperationType; +(function (OperationType) { + OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE"; + OperationType[OperationType["MERGE"] = 1] = "MERGE"; + OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE"; + OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE"; +})(OperationType || (OperationType = {})); +function newOperationSourceUser() { + return { + fromUser: true, + fromServer: false, + queryId: null, + tagged: false + }; +} +function newOperationSourceServer() { + return { + fromUser: false, + fromServer: true, + queryId: null, + tagged: false + }; +} +function newOperationSourceServerTaggedQuery(queryId) { + return { + fromUser: false, + fromServer: true, + queryId, + tagged: true + }; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class AckUserWrite { + /** + * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap. + */ + constructor( + /** @inheritDoc */ path, + /** @inheritDoc */ affectedTree, + /** @inheritDoc */ revert) { + this.path = path; + this.affectedTree = affectedTree; + this.revert = revert; + /** @inheritDoc */ + this.type = OperationType.ACK_USER_WRITE; + /** @inheritDoc */ + this.source = newOperationSourceUser(); + } + operationForChild(childName) { + if (!pathIsEmpty(this.path)) { + assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.'); + return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert); + } + else if (this.affectedTree.value != null) { + assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.'); + // All child locations are affected as well; just return same operation. + return this; + } + else { + const childTree = this.affectedTree.subtree(new Path(childName)); + return new AckUserWrite(newEmptyPath(), childTree, this.revert); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ListenComplete { + constructor(source, path) { + this.source = source; + this.path = path; + /** @inheritDoc */ + this.type = OperationType.LISTEN_COMPLETE; + } + operationForChild(childName) { + if (pathIsEmpty(this.path)) { + return new ListenComplete(this.source, newEmptyPath()); + } + else { + return new ListenComplete(this.source, pathPopFront(this.path)); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Overwrite { + constructor(source, path, snap) { + this.source = source; + this.path = path; + this.snap = snap; + /** @inheritDoc */ + this.type = OperationType.OVERWRITE; + } + operationForChild(childName) { + if (pathIsEmpty(this.path)) { + return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName)); + } + else { + return new Overwrite(this.source, pathPopFront(this.path), this.snap); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Merge { + constructor( + /** @inheritDoc */ source, + /** @inheritDoc */ path, + /** @inheritDoc */ children) { + this.source = source; + this.path = path; + this.children = children; + /** @inheritDoc */ + this.type = OperationType.MERGE; + } + operationForChild(childName) { + if (pathIsEmpty(this.path)) { + const childTree = this.children.subtree(new Path(childName)); + if (childTree.isEmpty()) { + // This child is unaffected + return null; + } + else if (childTree.value) { + // We have a snapshot for the child in question. This becomes an overwrite of the child. + return new Overwrite(this.source, newEmptyPath(), childTree.value); + } + else { + // This is a merge at a deeper level + return new Merge(this.source, newEmptyPath(), childTree); + } + } + else { + assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation"); + return new Merge(this.source, pathPopFront(this.path), this.children); + } + } + toString() { + return ('Operation(' + + this.path + + ': ' + + this.source.toString() + + ' merge: ' + + this.children.toString() + + ')'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully + * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g. + * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks + * whether a node potentially had children removed due to a filter. + */ +class CacheNode { + constructor(node_, fullyInitialized_, filtered_) { + this.node_ = node_; + this.fullyInitialized_ = fullyInitialized_; + this.filtered_ = filtered_; + } + /** + * Returns whether this node was fully initialized with either server data or a complete overwrite by the client + */ + isFullyInitialized() { + return this.fullyInitialized_; + } + /** + * Returns whether this node is potentially missing children due to a filter applied to the node + */ + isFiltered() { + return this.filtered_; + } + isCompleteForPath(path) { + if (pathIsEmpty(path)) { + return this.isFullyInitialized() && !this.filtered_; + } + const childKey = pathGetFront(path); + return this.isCompleteForChild(childKey); + } + isCompleteForChild(key) { + return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key)); + } + getNode() { + return this.node_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An EventGenerator is used to convert "raw" changes (Change) as computed by the + * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges() + * for details. + * + */ +class EventGenerator { + constructor(query_) { + this.query_ = query_; + this.index_ = this.query_._queryParams.getIndex(); + } +} +/** + * Given a set of raw changes (no moved events and prevName not specified yet), and a set of + * EventRegistrations that should be notified of these changes, generate the actual events to be raised. + * + * Notes: + * - child_moved events will be synthesized at this time for any child_changed events that affect + * our index. + * - prevName will be calculated based on the index ordering. + */ +function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) { + const events = []; + const moves = []; + changes.forEach(change => { + if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ && + eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) { + moves.push(changeChildMoved(change.childName, change.snapshotNode)); + } + }); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache); + return events; +} +/** + * Given changes of a single change type, generate the corresponding events. + */ +function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) { + const filteredChanges = changes.filter(change => change.type === eventType); + filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b)); + filteredChanges.forEach(change => { + const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache); + registrations.forEach(registration => { + if (registration.respondsTo(change.type)) { + events.push(registration.createEvent(materializedChange, eventGenerator.query_)); + } + }); + }); +} +function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) { + if (change.type === 'value' || change.type === 'child_removed') { + return change; + } + else { + change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_); + return change; + } +} +function eventGeneratorCompareChanges(eventGenerator, a, b) { + if (a.childName == null || b.childName == null) { + throw assertionError('Should only compare child_ events.'); + } + const aWrapped = new NamedNode(a.childName, a.snapshotNode); + const bWrapped = new NamedNode(b.childName, b.snapshotNode); + return eventGenerator.index_.compare(aWrapped, bWrapped); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newViewCache(eventCache, serverCache) { + return { eventCache, serverCache }; +} +function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) { + return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache); +} +function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) { + return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered)); +} +function viewCacheGetCompleteEventSnap(viewCache) { + return viewCache.eventCache.isFullyInitialized() + ? viewCache.eventCache.getNode() + : null; +} +function viewCacheGetCompleteServerSnap(viewCache) { + return viewCache.serverCache.isFullyInitialized() + ? viewCache.serverCache.getNode() + : null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let emptyChildrenSingleton; +/** + * Singleton empty children collection. + * + */ +const EmptyChildren = () => { + if (!emptyChildrenSingleton) { + emptyChildrenSingleton = new SortedMap(stringCompare); + } + return emptyChildrenSingleton; +}; +/** + * A tree with immutable elements. + */ +class ImmutableTree { + static fromObject(obj) { + let tree = new ImmutableTree(null); + each(obj, (childPath, childSnap) => { + tree = tree.set(new Path(childPath), childSnap); + }); + return tree; + } + constructor(value, children = EmptyChildren()) { + this.value = value; + this.children = children; + } + /** + * True if the value is empty and there are no children + */ + isEmpty() { + return this.value === null && this.children.isEmpty(); + } + /** + * Given a path and predicate, return the first node and the path to that node + * where the predicate returns true. + * + * TODO Do a perf test -- If we're creating a bunch of `{path: value:}` + * objects on the way back out, it may be better to pass down a pathSoFar obj. + * + * @param relativePath - The remainder of the path + * @param predicate - The predicate to satisfy to return a node + */ + findRootMostMatchingPathAndValue(relativePath, predicate) { + if (this.value != null && predicate(this.value)) { + return { path: newEmptyPath(), value: this.value }; + } + else { + if (pathIsEmpty(relativePath)) { + return null; + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front); + if (child !== null) { + const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate); + if (childExistingPathAndValue != null) { + const fullPath = pathChild(new Path(front), childExistingPathAndValue.path); + return { path: fullPath, value: childExistingPathAndValue.value }; + } + else { + return null; + } + } + else { + return null; + } + } + } + } + /** + * Find, if it exists, the shortest subpath of the given path that points a defined + * value in the tree + */ + findRootMostValueAndPath(relativePath) { + return this.findRootMostMatchingPathAndValue(relativePath, () => true); + } + /** + * @returns The subtree at the given path + */ + subtree(relativePath) { + if (pathIsEmpty(relativePath)) { + return this; + } + else { + const front = pathGetFront(relativePath); + const childTree = this.children.get(front); + if (childTree !== null) { + return childTree.subtree(pathPopFront(relativePath)); + } + else { + return new ImmutableTree(null); + } + } + } + /** + * Sets a value at the specified path. + * + * @param relativePath - Path to set value at. + * @param toSet - Value to set. + * @returns Resulting tree. + */ + set(relativePath, toSet) { + if (pathIsEmpty(relativePath)) { + return new ImmutableTree(toSet, this.children); + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front) || new ImmutableTree(null); + const newChild = child.set(pathPopFront(relativePath), toSet); + const newChildren = this.children.insert(front, newChild); + return new ImmutableTree(this.value, newChildren); + } + } + /** + * Removes the value at the specified path. + * + * @param relativePath - Path to value to remove. + * @returns Resulting tree. + */ + remove(relativePath) { + if (pathIsEmpty(relativePath)) { + if (this.children.isEmpty()) { + return new ImmutableTree(null); + } + else { + return new ImmutableTree(null, this.children); + } + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front); + if (child) { + const newChild = child.remove(pathPopFront(relativePath)); + let newChildren; + if (newChild.isEmpty()) { + newChildren = this.children.remove(front); + } + else { + newChildren = this.children.insert(front, newChild); + } + if (this.value === null && newChildren.isEmpty()) { + return new ImmutableTree(null); + } + else { + return new ImmutableTree(this.value, newChildren); + } + } + else { + return this; + } + } + } + /** + * Gets a value from the tree. + * + * @param relativePath - Path to get value for. + * @returns Value at path, or null. + */ + get(relativePath) { + if (pathIsEmpty(relativePath)) { + return this.value; + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front); + if (child) { + return child.get(pathPopFront(relativePath)); + } + else { + return null; + } + } + } + /** + * Replace the subtree at the specified path with the given new tree. + * + * @param relativePath - Path to replace subtree for. + * @param newTree - New tree. + * @returns Resulting tree. + */ + setTree(relativePath, newTree) { + if (pathIsEmpty(relativePath)) { + return newTree; + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front) || new ImmutableTree(null); + const newChild = child.setTree(pathPopFront(relativePath), newTree); + let newChildren; + if (newChild.isEmpty()) { + newChildren = this.children.remove(front); + } + else { + newChildren = this.children.insert(front, newChild); + } + return new ImmutableTree(this.value, newChildren); + } + } + /** + * Performs a depth first fold on this tree. Transforms a tree into a single + * value, given a function that operates on the path to a node, an optional + * current value, and a map of child names to folded subtrees + */ + fold(fn) { + return this.fold_(newEmptyPath(), fn); + } + /** + * Recursive helper for public-facing fold() method + */ + fold_(pathSoFar, fn) { + const accum = {}; + this.children.inorderTraversal((childKey, childTree) => { + accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn); + }); + return fn(pathSoFar, this.value, accum); + } + /** + * Find the first matching value on the given path. Return the result of applying f to it. + */ + findOnPath(path, f) { + return this.findOnPath_(path, newEmptyPath(), f); + } + findOnPath_(pathToFollow, pathSoFar, f) { + const result = this.value ? f(pathSoFar, this.value) : false; + if (result) { + return result; + } + else { + if (pathIsEmpty(pathToFollow)) { + return null; + } + else { + const front = pathGetFront(pathToFollow); + const nextChild = this.children.get(front); + if (nextChild) { + return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f); + } + else { + return null; + } + } + } + } + foreachOnPath(path, f) { + return this.foreachOnPath_(path, newEmptyPath(), f); + } + foreachOnPath_(pathToFollow, currentRelativePath, f) { + if (pathIsEmpty(pathToFollow)) { + return this; + } + else { + if (this.value) { + f(currentRelativePath, this.value); + } + const front = pathGetFront(pathToFollow); + const nextChild = this.children.get(front); + if (nextChild) { + return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f); + } + else { + return new ImmutableTree(null); + } + } + } + /** + * Calls the given function for each node in the tree that has a value. + * + * @param f - A function to be called with the path from the root of the tree to + * a node, and the value at that node. Called in depth-first order. + */ + foreach(f) { + this.foreach_(newEmptyPath(), f); + } + foreach_(currentRelativePath, f) { + this.children.inorderTraversal((childName, childTree) => { + childTree.foreach_(pathChild(currentRelativePath, childName), f); + }); + if (this.value) { + f(currentRelativePath, this.value); + } + } + foreachChild(f) { + this.children.inorderTraversal((childName, childTree) => { + if (childTree.value) { + f(childName, childTree.value); + } + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with + * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write + * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write + * to reflect the write added. + */ +class CompoundWrite { + constructor(writeTree_) { + this.writeTree_ = writeTree_; + } + static empty() { + return new CompoundWrite(new ImmutableTree(null)); + } +} +function compoundWriteAddWrite(compoundWrite, path, node) { + if (pathIsEmpty(path)) { + return new CompoundWrite(new ImmutableTree(node)); + } + else { + const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path); + if (rootmost != null) { + const rootMostPath = rootmost.path; + let value = rootmost.value; + const relativePath = newRelativePath(rootMostPath, path); + value = value.updateChild(relativePath, node); + return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value)); + } + else { + const subtree = new ImmutableTree(node); + const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree); + return new CompoundWrite(newWriteTree); + } + } +} +function compoundWriteAddWrites(compoundWrite, path, updates) { + let newWrite = compoundWrite; + each(updates, (childKey, node) => { + newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node); + }); + return newWrite; +} +/** + * Will remove a write at the given path and deeper paths. This will not modify a write at a higher + * location, which must be removed by calling this method with that path. + * + * @param compoundWrite - The CompoundWrite to remove. + * @param path - The path at which a write and all deeper writes should be removed + * @returns The new CompoundWrite with the removed path + */ +function compoundWriteRemoveWrite(compoundWrite, path) { + if (pathIsEmpty(path)) { + return CompoundWrite.empty(); + } + else { + const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null)); + return new CompoundWrite(newWriteTree); + } +} +/** + * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be + * considered "complete". + * + * @param compoundWrite - The CompoundWrite to check. + * @param path - The path to check for + * @returns Whether there is a complete write at that path + */ +function compoundWriteHasCompleteWrite(compoundWrite, path) { + return compoundWriteGetCompleteNode(compoundWrite, path) != null; +} +/** + * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate + * writes from deeper paths, but will return child nodes from a more shallow path. + * + * @param compoundWrite - The CompoundWrite to get the node from. + * @param path - The path to get a complete write + * @returns The node if complete at that path, or null otherwise. + */ +function compoundWriteGetCompleteNode(compoundWrite, path) { + const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path); + if (rootmost != null) { + return compoundWrite.writeTree_ + .get(rootmost.path) + .getChild(newRelativePath(rootmost.path, path)); + } + else { + return null; + } +} +/** + * Returns all children that are guaranteed to be a complete overwrite. + * + * @param compoundWrite - The CompoundWrite to get children from. + * @returns A list of all complete children. + */ +function compoundWriteGetCompleteChildren(compoundWrite) { + const children = []; + const node = compoundWrite.writeTree_.value; + if (node != null) { + // If it's a leaf node, it has no children; so nothing to do. + if (!node.isLeafNode()) { + node.forEachChild(PRIORITY_INDEX, (childName, childNode) => { + children.push(new NamedNode(childName, childNode)); + }); + } + } + else { + compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => { + if (childTree.value != null) { + children.push(new NamedNode(childName, childTree.value)); + } + }); + } + return children; +} +function compoundWriteChildCompoundWrite(compoundWrite, path) { + if (pathIsEmpty(path)) { + return compoundWrite; + } + else { + const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path); + if (shadowingNode != null) { + return new CompoundWrite(new ImmutableTree(shadowingNode)); + } + else { + return new CompoundWrite(compoundWrite.writeTree_.subtree(path)); + } + } +} +/** + * Returns true if this CompoundWrite is empty and therefore does not modify any nodes. + * @returns Whether this CompoundWrite is empty + */ +function compoundWriteIsEmpty(compoundWrite) { + return compoundWrite.writeTree_.isEmpty(); +} +/** + * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the + * node + * @param node - The node to apply this CompoundWrite to + * @returns The node with all writes applied + */ +function compoundWriteApply(compoundWrite, node) { + return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node); +} +function applySubtreeWrite(relativePath, writeTree, node) { + if (writeTree.value != null) { + // Since there a write is always a leaf, we're done here + return node.updateChild(relativePath, writeTree.value); + } + else { + let priorityWrite = null; + writeTree.children.inorderTraversal((childKey, childTree) => { + if (childKey === '.priority') { + // Apply priorities at the end so we don't update priorities for either empty nodes or forget + // to apply priorities to empty nodes that are later filled + assert(childTree.value !== null, 'Priority writes must always be leaf nodes'); + priorityWrite = childTree.value; + } + else { + node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node); + } + }); + // If there was a priority write, we only apply it if the node is not empty + if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) { + node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite); + } + return node; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path. + * + */ +function writeTreeChildWrites(writeTree, path) { + return newWriteTreeRef(path, writeTree); +} +/** + * Record a new overwrite from user code. + * + * @param visible - This is set to false by some transactions. It should be excluded from event caches + */ +function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) { + assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones'); + if (visible === undefined) { + visible = true; + } + writeTree.allWrites.push({ + path, + snap, + writeId, + visible + }); + if (visible) { + writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap); + } + writeTree.lastWriteId = writeId; +} +/** + * Record a new merge from user code. + */ +function writeTreeAddMerge(writeTree, path, changedChildren, writeId) { + assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones'); + writeTree.allWrites.push({ + path, + children: changedChildren, + writeId, + visible: true + }); + writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren); + writeTree.lastWriteId = writeId; +} +function writeTreeGetWrite(writeTree, writeId) { + for (let i = 0; i < writeTree.allWrites.length; i++) { + const record = writeTree.allWrites[i]; + if (record.writeId === writeId) { + return record; + } + } + return null; +} +/** + * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates + * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate. + * + * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise + * events as a result). + */ +function writeTreeRemoveWrite(writeTree, writeId) { + // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied + // out of order. + //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId; + //assert(validClear, "Either we don't have this write, or it's the first one in the queue"); + const idx = writeTree.allWrites.findIndex(s => { + return s.writeId === writeId; + }); + assert(idx >= 0, 'removeWrite called with nonexistent writeId.'); + const writeToRemove = writeTree.allWrites[idx]; + writeTree.allWrites.splice(idx, 1); + let removedWriteWasVisible = writeToRemove.visible; + let removedWriteOverlapsWithOtherWrites = false; + let i = writeTree.allWrites.length - 1; + while (removedWriteWasVisible && i >= 0) { + const currentWrite = writeTree.allWrites[i]; + if (currentWrite.visible) { + if (i >= idx && + writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) { + // The removed write was completely shadowed by a subsequent write. + removedWriteWasVisible = false; + } + else if (pathContains(writeToRemove.path, currentWrite.path)) { + // Either we're covering some writes or they're covering part of us (depending on which came first). + removedWriteOverlapsWithOtherWrites = true; + } + } + i--; + } + if (!removedWriteWasVisible) { + return false; + } + else if (removedWriteOverlapsWithOtherWrites) { + // There's some shadowing going on. Just rebuild the visible writes from scratch. + writeTreeResetTree_(writeTree); + return true; + } + else { + // There's no shadowing. We can safely just remove the write(s) from visibleWrites. + if (writeToRemove.snap) { + writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path); + } + else { + const children = writeToRemove.children; + each(children, (childName) => { + writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName)); + }); + } + return true; + } +} +function writeTreeRecordContainsPath_(writeRecord, path) { + if (writeRecord.snap) { + return pathContains(writeRecord.path, path); + } + else { + for (const childName in writeRecord.children) { + if (writeRecord.children.hasOwnProperty(childName) && + pathContains(pathChild(writeRecord.path, childName), path)) { + return true; + } + } + return false; + } +} +/** + * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots + */ +function writeTreeResetTree_(writeTree) { + writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath()); + if (writeTree.allWrites.length > 0) { + writeTree.lastWriteId = + writeTree.allWrites[writeTree.allWrites.length - 1].writeId; + } + else { + writeTree.lastWriteId = -1; + } +} +/** + * The default filter used when constructing the tree. Keep everything that's visible. + */ +function writeTreeDefaultFilter_(write) { + return write.visible; +} +/** + * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of + * event data at that path. + */ +function writeTreeLayerTree_(writes, filter, treeRoot) { + let compoundWrite = CompoundWrite.empty(); + for (let i = 0; i < writes.length; ++i) { + const write = writes[i]; + // Theory, a later set will either: + // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction + // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction + if (filter(write)) { + const writePath = write.path; + let relativePath; + if (write.snap) { + if (pathContains(treeRoot, writePath)) { + relativePath = newRelativePath(treeRoot, writePath); + compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap); + } + else if (pathContains(writePath, treeRoot)) { + relativePath = newRelativePath(writePath, treeRoot); + compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath)); + } + else ; + } + else if (write.children) { + if (pathContains(treeRoot, writePath)) { + relativePath = newRelativePath(treeRoot, writePath); + compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children); + } + else if (pathContains(writePath, treeRoot)) { + relativePath = newRelativePath(writePath, treeRoot); + if (pathIsEmpty(relativePath)) { + compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children); + } + else { + const child = safeGet(write.children, pathGetFront(relativePath)); + if (child) { + // There exists a child in this node that matches the root path + const deepNode = child.getChild(pathPopFront(relativePath)); + compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode); + } + } + } + else ; + } + else { + throw assertionError('WriteRecord should have .snap or .children'); + } + } + } + return compoundWrite; +} +/** + * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden + * writes), attempt to calculate a complete snapshot for the given path + * + * @param writeIdsToExclude - An optional set to be excluded + * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false + */ +function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) { + if (!writeIdsToExclude && !includeHiddenWrites) { + const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath); + if (shadowingNode != null) { + return shadowingNode; + } + else { + const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + if (compoundWriteIsEmpty(subMerge)) { + return completeServerCache; + } + else if (completeServerCache == null && + !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) { + // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow + return null; + } + else { + const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE; + return compoundWriteApply(subMerge, layeredCache); + } + } + } + else { + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) { + return completeServerCache; + } + else { + // If the server cache is null, and we don't have a complete cache, we need to return null + if (!includeHiddenWrites && + completeServerCache == null && + !compoundWriteHasCompleteWrite(merge, newEmptyPath())) { + return null; + } + else { + const filter = function (write) { + return ((write.visible || includeHiddenWrites) && + (!writeIdsToExclude || + !~writeIdsToExclude.indexOf(write.writeId)) && + (pathContains(write.path, treePath) || + pathContains(treePath, write.path))); + }; + const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath); + const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE; + return compoundWriteApply(mergeAtPath, layeredCache); + } + } + } +} +/** + * With optional, underlying server data, attempt to return a children node of children that we have complete data for. + * Used when creating new views, to pre-fill their complete event children snapshot. + */ +function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) { + let completeChildren = ChildrenNode.EMPTY_NODE; + const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath); + if (topLevelSet) { + if (!topLevelSet.isLeafNode()) { + // we're shadowing everything. Return the children. + topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => { + completeChildren = completeChildren.updateImmediateChild(childName, childSnap); + }); + } + return completeChildren; + } + else if (completeServerChildren) { + // Layer any children we have on top of this + // We know we don't have a top-level set, so just enumerate existing children + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => { + const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode); + completeChildren = completeChildren.updateImmediateChild(childName, node); + }); + // Add any complete children we have from the set + compoundWriteGetCompleteChildren(merge).forEach(namedNode => { + completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node); + }); + return completeChildren; + } + else { + // We don't have anything to layer on top of. Layer on any children we have + // Note that we can return an empty snap if we have a defined delete + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + compoundWriteGetCompleteChildren(merge).forEach(namedNode => { + completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node); + }); + return completeChildren; + } +} +/** + * Given that the underlying server data has updated, determine what, if anything, needs to be + * applied to the event cache. + * + * Possibilities: + * + * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data + * + * 2. Some write is completely shadowing. No events to be raised + * + * 3. Is partially shadowed. Events + * + * Either existingEventSnap or existingServerSnap must exist + */ +function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) { + assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist'); + const path = pathChild(treePath, childPath); + if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) { + // At this point we can probably guarantee that we're in case 2, meaning no events + // May need to check visibility while doing the findRootMostValueAndPath call + return null; + } + else { + // No complete shadowing. We're either partially shadowing or not shadowing at all. + const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path); + if (compoundWriteIsEmpty(childMerge)) { + // We're not shadowing at all. Case 1 + return existingServerSnap.getChild(childPath); + } + else { + // This could be more efficient if the serverNode + updates doesn't change the eventSnap + // However this is tricky to find out, since user updates don't necessary change the server + // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server + // adds nodes, but doesn't change any existing writes. It is therefore not enough to + // only check if the updates change the serverNode. + // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case? + return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath)); + } + } +} +/** + * Returns a complete child for a given server snap after applying all user writes or null if there is no + * complete child for this ChildKey. + */ +function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) { + const path = pathChild(treePath, childKey); + const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path); + if (shadowingNode != null) { + return shadowingNode; + } + else { + if (existingServerSnap.isCompleteForChild(childKey)) { + const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path); + return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey)); + } + else { + return null; + } + } +} +/** + * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at + * a higher path, this will return the child of that write relative to the write and this path. + * Returns null if there is no write at this path. + */ +function writeTreeShadowingWrite(writeTree, path) { + return compoundWriteGetCompleteNode(writeTree.visibleWrites, path); +} +/** + * This method is used when processing child remove events on a query. If we can, we pull in children that were outside + * the window, but may now be in the window. + */ +function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) { + let toIterate; + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath()); + if (shadowingNode != null) { + toIterate = shadowingNode; + } + else if (completeServerData != null) { + toIterate = compoundWriteApply(merge, completeServerData); + } + else { + // no children to iterate on + return []; + } + toIterate = toIterate.withIndex(index); + if (!toIterate.isEmpty() && !toIterate.isLeafNode()) { + const nodes = []; + const cmp = index.getCompare(); + const iter = reverse + ? toIterate.getReverseIteratorFrom(startPost, index) + : toIterate.getIteratorFrom(startPost, index); + let next = iter.getNext(); + while (next && nodes.length < count) { + if (cmp(next, startPost) !== 0) { + nodes.push(next); + } + next = iter.getNext(); + } + return nodes; + } + else { + return []; + } +} +function newWriteTree() { + return { + visibleWrites: CompoundWrite.empty(), + allWrites: [], + lastWriteId: -1 + }; +} +/** + * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used + * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node + * can lead to a more expensive calculation. + * + * @param writeIdsToExclude - Optional writes to exclude. + * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false + */ +function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) { + return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites); +} +/** + * If possible, returns a children node containing all of the complete children we have data for. The returned data is a + * mix of the given server data and write data. + * + */ +function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) { + return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren); +} +/** + * Given that either the underlying server data has updated or the outstanding writes have updated, determine what, + * if anything, needs to be applied to the event cache. + * + * Possibilities: + * + * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data + * + * 2. Some write is completely shadowing. No events to be raised + * + * 3. Is partially shadowed. Events should be raised + * + * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert + * + * + */ +function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) { + return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap); +} +/** + * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at + * a higher path, this will return the child of that write relative to the write and this path. + * Returns null if there is no write at this path. + * + */ +function writeTreeRefShadowingWrite(writeTreeRef, path) { + return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path)); +} +/** + * This method is used when processing child remove events on a query. If we can, we pull in children that were outside + * the window, but may now be in the window + */ +function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) { + return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index); +} +/** + * Returns a complete child for a given server snap after applying all user writes or null if there is no + * complete child for this ChildKey. + */ +function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) { + return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache); +} +/** + * Return a WriteTreeRef for a child. + */ +function writeTreeRefChild(writeTreeRef, childName) { + return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree); +} +function newWriteTreeRef(path, writeTree) { + return { + treePath: path, + writeTree + }; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ChildChangeAccumulator { + constructor() { + this.changeMap = new Map(); + } + trackChildChange(change) { + const type = change.type; + const childKey = change.childName; + assert(type === "child_added" /* ChangeType.CHILD_ADDED */ || + type === "child_changed" /* ChangeType.CHILD_CHANGED */ || + type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking'); + assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.'); + const oldChange = this.changeMap.get(childKey); + if (oldChange) { + const oldType = oldChange.type; + if (type === "child_added" /* ChangeType.CHILD_ADDED */ && + oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) { + this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode)); + } + else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ && + oldType === "child_added" /* ChangeType.CHILD_ADDED */) { + this.changeMap.delete(childKey); + } + else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ && + oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) { + this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap)); + } + else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ && + oldType === "child_added" /* ChangeType.CHILD_ADDED */) { + this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode)); + } + else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ && + oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) { + this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap)); + } + else { + throw assertionError('Illegal combination of changes: ' + + change + + ' occurred after ' + + oldChange); + } + } + else { + this.changeMap.set(childKey, change); + } + } + getChanges() { + return Array.from(this.changeMap.values()); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An implementation of CompleteChildSource that never returns any additional children + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class NoCompleteChildSource_ { + getCompleteChild(childKey) { + return null; + } + getChildAfterChild(index, child, reverse) { + return null; + } +} +/** + * Singleton instance. + */ +const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_(); +/** + * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or + * old event caches available to calculate complete children. + */ +class WriteTreeCompleteChildSource { + constructor(writes_, viewCache_, optCompleteServerCache_ = null) { + this.writes_ = writes_; + this.viewCache_ = viewCache_; + this.optCompleteServerCache_ = optCompleteServerCache_; + } + getCompleteChild(childKey) { + const node = this.viewCache_.eventCache; + if (node.isCompleteForChild(childKey)) { + return node.getNode().getImmediateChild(childKey); + } + else { + const serverNode = this.optCompleteServerCache_ != null + ? new CacheNode(this.optCompleteServerCache_, true, false) + : this.viewCache_.serverCache; + return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode); + } + } + getChildAfterChild(index, child, reverse) { + const completeServerData = this.optCompleteServerCache_ != null + ? this.optCompleteServerCache_ + : viewCacheGetCompleteServerSnap(this.viewCache_); + const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index); + if (nodes.length === 0) { + return null; + } + else { + return nodes[0]; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newViewProcessor(filter) { + return { filter }; +} +function viewProcessorAssertIndexed(viewProcessor, viewCache) { + assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed'); + assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed'); +} +function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) { + const accumulator = new ChildChangeAccumulator(); + let newViewCache, filterServerNode; + if (operation.type === OperationType.OVERWRITE) { + const overwrite = operation; + if (overwrite.source.fromUser) { + newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator); + } + else { + assert(overwrite.source.fromServer, 'Unknown source.'); + // We filter the node if it's a tagged update or the node has been previously filtered and the + // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered + // again + filterServerNode = + overwrite.source.tagged || + (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path)); + newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator); + } + } + else if (operation.type === OperationType.MERGE) { + const merge = operation; + if (merge.source.fromUser) { + newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator); + } + else { + assert(merge.source.fromServer, 'Unknown source.'); + // We filter the node if it's a tagged update or the node has been previously filtered + filterServerNode = + merge.source.tagged || oldViewCache.serverCache.isFiltered(); + newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator); + } + } + else if (operation.type === OperationType.ACK_USER_WRITE) { + const ackUserWrite = operation; + if (!ackUserWrite.revert) { + newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator); + } + else { + newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator); + } + } + else if (operation.type === OperationType.LISTEN_COMPLETE) { + newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator); + } + else { + throw assertionError('Unknown operation type: ' + operation.type); + } + const changes = accumulator.getChanges(); + viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes); + return { viewCache: newViewCache, changes }; +} +function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) { + const eventSnap = newViewCache.eventCache; + if (eventSnap.isFullyInitialized()) { + const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty(); + const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache); + if (accumulator.length > 0 || + !oldViewCache.eventCache.isFullyInitialized() || + (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) || + !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) { + accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache))); + } + } +} +function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) { + const oldEventSnap = viewCache.eventCache; + if (writeTreeRefShadowingWrite(writesCache, changePath) != null) { + // we have a shadowing write, ignore changes + return viewCache; + } + else { + let newEventCache, serverNode; + if (pathIsEmpty(changePath)) { + // TODO: figure out how this plays with "sliding ack windows" + assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data'); + if (viewCache.serverCache.isFiltered()) { + // We need to special case this, because we need to only apply writes to complete children, or + // we might end up raising events for incomplete children. If the server data is filtered deep + // writes cannot be guaranteed to be complete + const serverCache = viewCacheGetCompleteServerSnap(viewCache); + const completeChildren = serverCache instanceof ChildrenNode + ? serverCache + : ChildrenNode.EMPTY_NODE; + const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren); + newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator); + } + else { + const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache)); + newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator); + } + } + else { + const childKey = pathGetFront(changePath); + if (childKey === '.priority') { + assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components"); + const oldEventNode = oldEventSnap.getNode(); + serverNode = viewCache.serverCache.getNode(); + // we might have overwrites for this priority + const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode); + if (updatedPriority != null) { + newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority); + } + else { + // priority didn't change, keep old node + newEventCache = oldEventSnap.getNode(); + } + } + else { + const childChangePath = pathPopFront(changePath); + // update child + let newEventChild; + if (oldEventSnap.isCompleteForChild(childKey)) { + serverNode = viewCache.serverCache.getNode(); + const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode); + if (eventChildUpdate != null) { + newEventChild = oldEventSnap + .getNode() + .getImmediateChild(childKey) + .updateChild(childChangePath, eventChildUpdate); + } + else { + // Nothing changed, just keep the old child + newEventChild = oldEventSnap.getNode().getImmediateChild(childKey); + } + } + else { + newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache); + } + if (newEventChild != null) { + newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator); + } + else { + // no complete child available or no change + newEventCache = oldEventSnap.getNode(); + } + } + } + return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes()); + } +} +function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) { + const oldServerSnap = oldViewCache.serverCache; + let newServerCache; + const serverFilter = filterServerNode + ? viewProcessor.filter + : viewProcessor.filter.getIndexedFilter(); + if (pathIsEmpty(changePath)) { + newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null); + } + else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) { + // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update + const newServerNode = oldServerSnap + .getNode() + .updateChild(changePath, changedSnap); + newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null); + } + else { + const childKey = pathGetFront(changePath); + if (!oldServerSnap.isCompleteForPath(changePath) && + pathGetLength(changePath) > 1) { + // We don't update incomplete nodes with updates intended for other listeners + return oldViewCache; + } + const childChangePath = pathPopFront(changePath); + const childNode = oldServerSnap.getNode().getImmediateChild(childKey); + const newChildNode = childNode.updateChild(childChangePath, changedSnap); + if (childKey === '.priority') { + newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode); + } + else { + newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null); + } + } + const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes()); + const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache); + return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator); +} +function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) { + const oldEventSnap = oldViewCache.eventCache; + let newViewCache, newEventCache; + const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache); + if (pathIsEmpty(changePath)) { + newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator); + newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes()); + } + else { + const childKey = pathGetFront(changePath); + if (childKey === '.priority') { + newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap); + newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered()); + } + else { + const childChangePath = pathPopFront(changePath); + const oldChild = oldEventSnap.getNode().getImmediateChild(childKey); + let newChild; + if (pathIsEmpty(childChangePath)) { + // Child overwrite, we can replace the child + newChild = changedSnap; + } + else { + const childNode = source.getCompleteChild(childKey); + if (childNode != null) { + if (pathGetBack(childChangePath) === '.priority' && + childNode.getChild(pathParent(childChangePath)).isEmpty()) { + // This is a priority update on an empty node. If this node exists on the server, the + // server will send down the priority in the update, so ignore for now + newChild = childNode; + } + else { + newChild = childNode.updateChild(childChangePath, changedSnap); + } + } + else { + // There is no complete child node available + newChild = ChildrenNode.EMPTY_NODE; + } + } + if (!oldChild.equals(newChild)) { + const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator); + newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes()); + } + else { + newViewCache = oldViewCache; + } + } + } + return newViewCache; +} +function viewProcessorCacheHasChild(viewCache, childKey) { + return viewCache.eventCache.isCompleteForChild(childKey); +} +function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) { + // HACK: In the case of a limit query, there may be some changes that bump things out of the + // window leaving room for new items. It's important we process these changes first, so we + // iterate the changes twice, first processing any that affect items currently in view. + // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server + // and event snap. I'm not sure if this will result in edge cases when a child is in one but + // not the other. + let curViewCache = viewCache; + changedChildren.foreach((relativePath, childNode) => { + const writePath = pathChild(path, relativePath); + if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) { + curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator); + } + }); + changedChildren.foreach((relativePath, childNode) => { + const writePath = pathChild(path, relativePath); + if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) { + curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator); + } + }); + return curViewCache; +} +function viewProcessorApplyMerge(viewProcessor, node, merge) { + merge.foreach((relativePath, childNode) => { + node = node.updateChild(relativePath, childNode); + }); + return node; +} +function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) { + // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and + // wait for the complete data update coming soon. + if (viewCache.serverCache.getNode().isEmpty() && + !viewCache.serverCache.isFullyInitialized()) { + return viewCache; + } + // HACK: In the case of a limit query, there may be some changes that bump things out of the + // window leaving room for new items. It's important we process these changes first, so we + // iterate the changes twice, first processing any that affect items currently in view. + // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server + // and event snap. I'm not sure if this will result in edge cases when a child is in one but + // not the other. + let curViewCache = viewCache; + let viewMergeTree; + if (pathIsEmpty(path)) { + viewMergeTree = changedChildren; + } + else { + viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren); + } + const serverNode = viewCache.serverCache.getNode(); + viewMergeTree.children.inorderTraversal((childKey, childTree) => { + if (serverNode.hasChild(childKey)) { + const serverChild = viewCache.serverCache + .getNode() + .getImmediateChild(childKey); + const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree); + curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator); + } + }); + viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => { + const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) && + childMergeTree.value === null; + if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) { + const serverChild = viewCache.serverCache + .getNode() + .getImmediateChild(childKey); + const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree); + curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator); + } + }); + return curViewCache; +} +function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) { + if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) { + return viewCache; + } + // Only filter server node if it is currently filtered + const filterServerNode = viewCache.serverCache.isFiltered(); + // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update + // now that it won't be shadowed. + const serverCache = viewCache.serverCache; + if (affectedTree.value != null) { + // This is an overwrite. + if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) || + serverCache.isCompleteForPath(ackPath)) { + return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator); + } + else if (pathIsEmpty(ackPath)) { + // This is a goofy edge case where we are acking data at this location but don't have full data. We + // should just re-apply whatever we have in our cache as a merge. + let changedChildren = new ImmutableTree(null); + serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => { + changedChildren = changedChildren.set(new Path(name), node); + }); + return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator); + } + else { + return viewCache; + } + } + else { + // This is a merge. + let changedChildren = new ImmutableTree(null); + affectedTree.foreach((mergePath, value) => { + const serverCachePath = pathChild(ackPath, mergePath); + if (serverCache.isCompleteForPath(serverCachePath)) { + changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath)); + } + }); + return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator); + } +} +function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) { + const oldServerNode = viewCache.serverCache; + const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered()); + return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator); +} +function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) { + let complete; + if (writeTreeRefShadowingWrite(writesCache, path) != null) { + return viewCache; + } + else { + const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache); + const oldEventCache = viewCache.eventCache.getNode(); + let newEventCache; + if (pathIsEmpty(path) || pathGetFront(path) === '.priority') { + let newNode; + if (viewCache.serverCache.isFullyInitialized()) { + newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache)); + } + else { + const serverChildren = viewCache.serverCache.getNode(); + assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node'); + newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren); + } + newNode = newNode; + newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator); + } + else { + const childKey = pathGetFront(path); + let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache); + if (newChild == null && + viewCache.serverCache.isCompleteForChild(childKey)) { + newChild = oldEventCache.getImmediateChild(childKey); + } + if (newChild != null) { + newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator); + } + else if (viewCache.eventCache.getNode().hasChild(childKey)) { + // No complete child available, delete the existing one, if any + newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator); + } + else { + newEventCache = oldEventCache; + } + if (newEventCache.isEmpty() && + viewCache.serverCache.isFullyInitialized()) { + // We might have reverted all child writes. Maybe the old event was a leaf node + complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache)); + if (complete.isLeafNode()) { + newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator); + } + } + } + complete = + viewCache.serverCache.isFullyInitialized() || + writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null; + return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes()); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A view represents a specific location and query that has 1 or more event registrations. + * + * It does several things: + * - Maintains the list of event registrations for this location/query. + * - Maintains a cache of the data visible for this location/query. + * - Applies new operations (via applyOperation), updates the cache, and based on the event + * registrations returns the set of events to be raised. + */ +class View { + constructor(query_, initialViewCache) { + this.query_ = query_; + this.eventRegistrations_ = []; + const params = this.query_._queryParams; + const indexFilter = new IndexedFilter(params.getIndex()); + const filter = queryParamsGetNodeFilter(params); + this.processor_ = newViewProcessor(filter); + const initialServerCache = initialViewCache.serverCache; + const initialEventCache = initialViewCache.eventCache; + // Don't filter server node with other filter than index, wait for tagged listen + const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null); + const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null); + const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes()); + const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes()); + this.viewCache_ = newViewCache(newEventCache, newServerCache); + this.eventGenerator_ = new EventGenerator(this.query_); + } + get query() { + return this.query_; + } +} +function viewGetServerCache(view) { + return view.viewCache_.serverCache.getNode(); +} +function viewGetCompleteNode(view) { + return viewCacheGetCompleteEventSnap(view.viewCache_); +} +function viewGetCompleteServerCache(view, path) { + const cache = viewCacheGetCompleteServerSnap(view.viewCache_); + if (cache) { + // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and + // we need to see if it contains the child we're interested in. + if (view.query._queryParams.loadsAllData() || + (!pathIsEmpty(path) && + !cache.getImmediateChild(pathGetFront(path)).isEmpty())) { + return cache.getChild(path); + } + } + return null; +} +function viewIsEmpty(view) { + return view.eventRegistrations_.length === 0; +} +function viewAddEventRegistration(view, eventRegistration) { + view.eventRegistrations_.push(eventRegistration); +} +/** + * @param eventRegistration - If null, remove all callbacks. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @returns Cancel events, if cancelError was provided. + */ +function viewRemoveEventRegistration(view, eventRegistration, cancelError) { + const cancelEvents = []; + if (cancelError) { + assert(eventRegistration == null, 'A cancel should cancel all event registrations.'); + const path = view.query._path; + view.eventRegistrations_.forEach(registration => { + const maybeEvent = registration.createCancelEvent(cancelError, path); + if (maybeEvent) { + cancelEvents.push(maybeEvent); + } + }); + } + if (eventRegistration) { + let remaining = []; + for (let i = 0; i < view.eventRegistrations_.length; ++i) { + const existing = view.eventRegistrations_[i]; + if (!existing.matches(eventRegistration)) { + remaining.push(existing); + } + else if (eventRegistration.hasAnyCallback()) { + // We're removing just this one + remaining = remaining.concat(view.eventRegistrations_.slice(i + 1)); + break; + } + } + view.eventRegistrations_ = remaining; + } + else { + view.eventRegistrations_ = []; + } + return cancelEvents; +} +/** + * Applies the given Operation, updates our cache, and returns the appropriate events. + */ +function viewApplyOperation(view, operation, writesCache, completeServerCache) { + if (operation.type === OperationType.MERGE && + operation.source.queryId !== null) { + assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges'); + assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache'); + } + const oldViewCache = view.viewCache_; + const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache); + viewProcessorAssertIndexed(view.processor_, result.viewCache); + assert(result.viewCache.serverCache.isFullyInitialized() || + !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back'); + view.viewCache_ = result.viewCache; + return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null); +} +function viewGetInitialEvents(view, registration) { + const eventSnap = view.viewCache_.eventCache; + const initialChanges = []; + if (!eventSnap.getNode().isLeafNode()) { + const eventNode = eventSnap.getNode(); + eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => { + initialChanges.push(changeChildAdded(key, childNode)); + }); + } + if (eventSnap.isFullyInitialized()) { + initialChanges.push(changeValue(eventSnap.getNode())); + } + return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration); +} +function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) { + const registrations = eventRegistration + ? [eventRegistration] + : view.eventRegistrations_; + return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let referenceConstructor$1; +/** + * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to + * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes + * and user writes (set, transaction, update). + * + * It's responsible for: + * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed). + * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite, + * applyUserOverwrite, etc.) + */ +class SyncPoint { + constructor() { + /** + * The Views being tracked at this location in the tree, stored as a map where the key is a + * queryId and the value is the View for that query. + * + * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case). + */ + this.views = new Map(); + } +} +function syncPointSetReferenceConstructor(val) { + assert(!referenceConstructor$1, '__referenceConstructor has already been defined'); + referenceConstructor$1 = val; +} +function syncPointGetReferenceConstructor() { + assert(referenceConstructor$1, 'Reference.ts has not been loaded'); + return referenceConstructor$1; +} +function syncPointIsEmpty(syncPoint) { + return syncPoint.views.size === 0; +} +function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) { + const queryId = operation.source.queryId; + if (queryId !== null) { + const view = syncPoint.views.get(queryId); + assert(view != null, 'SyncTree gave us an op for an invalid query.'); + return viewApplyOperation(view, operation, writesCache, optCompleteServerCache); + } + else { + let events = []; + for (const view of syncPoint.views.values()) { + events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache)); + } + return events; + } +} +/** + * Get a view for the specified query. + * + * @param query - The query to return a view for + * @param writesCache + * @param serverCache + * @param serverCacheComplete + * @returns Events to raise. + */ +function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) { + const queryId = query._queryIdentifier; + const view = syncPoint.views.get(queryId); + if (!view) { + // TODO: make writesCache take flag for complete server node + let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null); + let eventCacheComplete = false; + if (eventCache) { + eventCacheComplete = true; + } + else if (serverCache instanceof ChildrenNode) { + eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache); + eventCacheComplete = false; + } + else { + eventCache = ChildrenNode.EMPTY_NODE; + eventCacheComplete = false; + } + const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false)); + return new View(query, viewCache); + } + return view; +} +/** + * Add an event callback for the specified query. + * + * @param query + * @param eventRegistration + * @param writesCache + * @param serverCache - Complete server cache, if we have it. + * @param serverCacheComplete + * @returns Events to raise. + */ +function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) { + const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete); + if (!syncPoint.views.has(query._queryIdentifier)) { + syncPoint.views.set(query._queryIdentifier, view); + } + // This is guaranteed to exist now, we just created anything that was missing + viewAddEventRegistration(view, eventRegistration); + return viewGetInitialEvents(view, eventRegistration); +} +/** + * Remove event callback(s). Return cancelEvents if a cancelError is specified. + * + * If query is the default query, we'll check all views for the specified eventRegistration. + * If eventRegistration is null, we'll remove all callbacks for the specified view(s). + * + * @param eventRegistration - If null, remove all callbacks. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @returns removed queries and any cancel events + */ +function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) { + const queryId = query._queryIdentifier; + const removed = []; + let cancelEvents = []; + const hadCompleteView = syncPointHasCompleteView(syncPoint); + if (queryId === 'default') { + // When you do ref.off(...), we search all views for the registration to remove. + for (const [viewQueryId, view] of syncPoint.views.entries()) { + cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError)); + if (viewIsEmpty(view)) { + syncPoint.views.delete(viewQueryId); + // We'll deal with complete views later. + if (!view.query._queryParams.loadsAllData()) { + removed.push(view.query); + } + } + } + } + else { + // remove the callback from the specific view. + const view = syncPoint.views.get(queryId); + if (view) { + cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError)); + if (viewIsEmpty(view)) { + syncPoint.views.delete(queryId); + // We'll deal with complete views later. + if (!view.query._queryParams.loadsAllData()) { + removed.push(view.query); + } + } + } + } + if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) { + // We removed our last complete view. + removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path)); + } + return { removed, events: cancelEvents }; +} +function syncPointGetQueryViews(syncPoint) { + const result = []; + for (const view of syncPoint.views.values()) { + if (!view.query._queryParams.loadsAllData()) { + result.push(view); + } + } + return result; +} +/** + * @param path - The path to the desired complete snapshot + * @returns A complete cache, if it exists + */ +function syncPointGetCompleteServerCache(syncPoint, path) { + let serverCache = null; + for (const view of syncPoint.views.values()) { + serverCache = serverCache || viewGetCompleteServerCache(view, path); + } + return serverCache; +} +function syncPointViewForQuery(syncPoint, query) { + const params = query._queryParams; + if (params.loadsAllData()) { + return syncPointGetCompleteView(syncPoint); + } + else { + const queryId = query._queryIdentifier; + return syncPoint.views.get(queryId); + } +} +function syncPointViewExistsForQuery(syncPoint, query) { + return syncPointViewForQuery(syncPoint, query) != null; +} +function syncPointHasCompleteView(syncPoint) { + return syncPointGetCompleteView(syncPoint) != null; +} +function syncPointGetCompleteView(syncPoint) { + for (const view of syncPoint.views.values()) { + if (view.query._queryParams.loadsAllData()) { + return view; + } + } + return null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let referenceConstructor; +function syncTreeSetReferenceConstructor(val) { + assert(!referenceConstructor, '__referenceConstructor has already been defined'); + referenceConstructor = val; +} +function syncTreeGetReferenceConstructor() { + assert(referenceConstructor, 'Reference.ts has not been loaded'); + return referenceConstructor; +} +/** + * Static tracker for next query tag. + */ +let syncTreeNextQueryTag_ = 1; +/** + * SyncTree is the central class for managing event callback registration, data caching, views + * (query processing), and event generation. There are typically two SyncTree instances for + * each Repo, one for the normal Firebase data, and one for the .info data. + * + * It has a number of responsibilities, including: + * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()). + * - Applying and caching data changes for user set(), transaction(), and update() calls + * (applyUserOverwrite(), applyUserMerge()). + * - Applying and caching data changes for server data changes (applyServerOverwrite(), + * applyServerMerge()). + * - Generating user-facing events for server and user changes (all of the apply* methods + * return the set of events that need to be raised as a result). + * - Maintaining the appropriate set of server listens to ensure we are always subscribed + * to the correct set of paths and queries to satisfy the current set of user event + * callbacks (listens are started/stopped using the provided listenProvider). + * + * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual + * events are returned to the caller rather than raised synchronously. + * + */ +class SyncTree { + /** + * @param listenProvider_ - Used by SyncTree to start / stop listening + * to server data. + */ + constructor(listenProvider_) { + this.listenProvider_ = listenProvider_; + /** + * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views. + */ + this.syncPointTree_ = new ImmutableTree(null); + /** + * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.). + */ + this.pendingWriteTree_ = newWriteTree(); + this.tagToQueryMap = new Map(); + this.queryToTagMap = new Map(); + } +} +/** + * Apply the data changes for a user-generated set() or transaction() call. + * + * @returns Events to raise. + */ +function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) { + // Record pending write. + writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible); + if (!visible) { + return []; + } + else { + return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData)); + } +} +/** + * Apply the data from a user-generated update() call + * + * @returns Events to raise. + */ +function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) { + // Record pending merge. + writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId); + const changeTree = ImmutableTree.fromObject(changedChildren); + return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree)); +} +/** + * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge(). + * + * @param revert - True if the given write failed and needs to be reverted + * @returns Events to raise. + */ +function syncTreeAckUserWrite(syncTree, writeId, revert = false) { + const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId); + const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId); + if (!needToReevaluate) { + return []; + } + else { + let affectedTree = new ImmutableTree(null); + if (write.snap != null) { + // overwrite + affectedTree = affectedTree.set(newEmptyPath(), true); + } + else { + each(write.children, (pathString) => { + affectedTree = affectedTree.set(new Path(pathString), true); + }); + } + return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert)); + } +} +/** + * Apply new server data for the specified path.. + * + * @returns Events to raise. + */ +function syncTreeApplyServerOverwrite(syncTree, path, newData) { + return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData)); +} +/** + * Apply new server data to be merged in at the specified path. + * + * @returns Events to raise. + */ +function syncTreeApplyServerMerge(syncTree, path, changedChildren) { + const changeTree = ImmutableTree.fromObject(changedChildren); + return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree)); +} +/** + * Apply a listen complete for a query + * + * @returns Events to raise. + */ +function syncTreeApplyListenComplete(syncTree, path) { + return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path)); +} +/** + * Apply a listen complete for a tagged query + * + * @returns Events to raise. + */ +function syncTreeApplyTaggedListenComplete(syncTree, path, tag) { + const queryKey = syncTreeQueryKeyForTag_(syncTree, tag); + if (queryKey) { + const r = syncTreeParseQueryKey_(queryKey); + const queryPath = r.path, queryId = r.queryId; + const relativePath = newRelativePath(queryPath, path); + const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath); + return syncTreeApplyTaggedOperation_(syncTree, queryPath, op); + } + else { + // We've already removed the query. No big deal, ignore the update + return []; + } +} +/** + * Remove event callback(s). + * + * If query is the default query, we'll check all queries for the specified eventRegistration. + * If eventRegistration is null, we'll remove all callbacks for the specified query/queries. + * + * @param eventRegistration - If null, all callbacks are removed. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no + * deduping needs to take place. This flag allows toggling of that behavior + * @returns Cancel events, if cancelError was provided. + */ +function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) { + // Find the syncPoint first. Then deal with whether or not it has matching listeners + const path = query._path; + const maybeSyncPoint = syncTree.syncPointTree_.get(path); + let cancelEvents = []; + // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without + // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and + // not loadsAllData(). + if (maybeSyncPoint && + (query._queryIdentifier === 'default' || + syncPointViewExistsForQuery(maybeSyncPoint, query))) { + const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError); + if (syncPointIsEmpty(maybeSyncPoint)) { + syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path); + } + const removed = removedAndEvents.removed; + cancelEvents = removedAndEvents.events; + if (!skipListenerDedup) { + /** + * We may have just removed one of many listeners and can short-circuit this whole process + * We may also not have removed a default listener, in which case all of the descendant listeners should already be + * properly set up. + */ + // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of + // queryId === 'default' + const removingDefault = -1 !== + removed.findIndex(query => { + return query._queryParams.loadsAllData(); + }); + const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint)); + if (removingDefault && !covered) { + const subtree = syncTree.syncPointTree_.subtree(path); + // There are potentially child listeners. Determine what if any listens we need to send before executing the + // removal + if (!subtree.isEmpty()) { + // We need to fold over our subtree and collect the listeners to send + const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree); + // Ok, we've collected all the listens we need. Set them up. + for (let i = 0; i < newViews.length; ++i) { + const view = newViews[i], newQuery = view.query; + const listener = syncTreeCreateListenerForView_(syncTree, view); + syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete); + } + } + // Otherwise there's nothing below us, so nothing we need to start listening on + } + // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query + // The above block has us covered in terms of making sure we're set up on listens lower in the tree. + // Also, note that if we have a cancelError, it's already been removed at the provider level. + if (!covered && removed.length > 0 && !cancelError) { + // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one + // default. Otherwise, we need to iterate through and cancel each individual query + if (removingDefault) { + // We don't tag default listeners + const defaultTag = null; + syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag); + } + else { + removed.forEach((queryToRemove) => { + const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove)); + syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove); + }); + } + } + } + // Now, clear all of the tags we're tracking for the removed listens + syncTreeRemoveTags_(syncTree, removed); + } + return cancelEvents; +} +/** + * Apply new server data for the specified tagged query. + * + * @returns Events to raise. + */ +function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) { + const queryKey = syncTreeQueryKeyForTag_(syncTree, tag); + if (queryKey != null) { + const r = syncTreeParseQueryKey_(queryKey); + const queryPath = r.path, queryId = r.queryId; + const relativePath = newRelativePath(queryPath, path); + const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap); + return syncTreeApplyTaggedOperation_(syncTree, queryPath, op); + } + else { + // Query must have been removed already + return []; + } +} +/** + * Apply server data to be merged in for the specified tagged query. + * + * @returns Events to raise. + */ +function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) { + const queryKey = syncTreeQueryKeyForTag_(syncTree, tag); + if (queryKey) { + const r = syncTreeParseQueryKey_(queryKey); + const queryPath = r.path, queryId = r.queryId; + const relativePath = newRelativePath(queryPath, path); + const changeTree = ImmutableTree.fromObject(changedChildren); + const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree); + return syncTreeApplyTaggedOperation_(syncTree, queryPath, op); + } + else { + // We've already removed the query. No big deal, ignore the update + return []; + } +} +/** + * Add an event callback for the specified query. + * + * @returns Events to raise. + */ +function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) { + const path = query._path; + let serverCache = null; + let foundAncestorDefaultView = false; + // Any covering writes will necessarily be at the root, so really all we need to find is the server cache. + // Consider optimizing this once there's a better understanding of what actual behavior will be. + syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => { + const relativePath = newRelativePath(pathToSyncPoint, path); + serverCache = + serverCache || syncPointGetCompleteServerCache(sp, relativePath); + foundAncestorDefaultView = + foundAncestorDefaultView || syncPointHasCompleteView(sp); + }); + let syncPoint = syncTree.syncPointTree_.get(path); + if (!syncPoint) { + syncPoint = new SyncPoint(); + syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint); + } + else { + foundAncestorDefaultView = + foundAncestorDefaultView || syncPointHasCompleteView(syncPoint); + serverCache = + serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + let serverCacheComplete; + if (serverCache != null) { + serverCacheComplete = true; + } + else { + serverCacheComplete = false; + serverCache = ChildrenNode.EMPTY_NODE; + const subtree = syncTree.syncPointTree_.subtree(path); + subtree.foreachChild((childName, childSyncPoint) => { + const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath()); + if (completeCache) { + serverCache = serverCache.updateImmediateChild(childName, completeCache); + } + }); + } + const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query); + if (!viewAlreadyExists && !query._queryParams.loadsAllData()) { + // We need to track a tag for this query + const queryKey = syncTreeMakeQueryKey_(query); + assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag'); + const tag = syncTreeGetNextQueryTag_(); + syncTree.queryToTagMap.set(queryKey, tag); + syncTree.tagToQueryMap.set(tag, queryKey); + } + const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path); + let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete); + if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) { + const view = syncPointViewForQuery(syncPoint, query); + events = events.concat(syncTreeSetupListener_(syncTree, query, view)); + } + return events; +} +/** + * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a + * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always + * have a listener above, and atomic operations would correctly show a jitter of -> + * as the write is applied locally and then acknowledged at the server. + * + * Note: this method will *include* hidden writes from transaction with applyLocally set to false. + * + * @param path - The path to the data we want + * @param writeIdsToExclude - A specific set to be excluded + */ +function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) { + const includeHiddenSets = true; + const writeTree = syncTree.pendingWriteTree_; + const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => { + const relativePath = newRelativePath(pathSoFar, path); + const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath); + if (serverCache) { + return serverCache; + } + }); + return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets); +} +function syncTreeGetServerValue(syncTree, query) { + const path = query._path; + let serverCache = null; + // Any covering writes will necessarily be at the root, so really all we need to find is the server cache. + // Consider optimizing this once there's a better understanding of what actual behavior will be. + syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => { + const relativePath = newRelativePath(pathToSyncPoint, path); + serverCache = + serverCache || syncPointGetCompleteServerCache(sp, relativePath); + }); + let syncPoint = syncTree.syncPointTree_.get(path); + if (!syncPoint) { + syncPoint = new SyncPoint(); + syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint); + } + else { + serverCache = + serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + const serverCacheComplete = serverCache != null; + const serverCacheNode = serverCacheComplete + ? new CacheNode(serverCache, true, false) + : null; + const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path); + const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete); + return viewGetCompleteNode(view); +} +/** + * A helper method that visits all descendant and ancestor SyncPoints, applying the operation. + * + * NOTES: + * - Descendant SyncPoints will be visited first (since we raise events depth-first). + * + * - We call applyOperation() on each SyncPoint passing three things: + * 1. A version of the Operation that has been made relative to the SyncPoint location. + * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location. + * 3. A snapshot Node with cached server data, if we have it. + * + * - We concatenate all of the events returned by each SyncPoint and return the result. + */ +function syncTreeApplyOperationToSyncPoints_(syncTree, operation) { + return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_, + /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath())); +} +/** + * Recursive helper for applyOperationToSyncPoints_ + */ +function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) { + if (pathIsEmpty(operation.path)) { + return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache); + } + else { + const syncPoint = syncPointTree.get(newEmptyPath()); + // If we don't have cached server data, see if we can get it from this SyncPoint. + if (serverCache == null && syncPoint != null) { + serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + let events = []; + const childName = pathGetFront(operation.path); + const childOperation = operation.operationForChild(childName); + const childTree = syncPointTree.children.get(childName); + if (childTree && childOperation) { + const childServerCache = serverCache + ? serverCache.getImmediateChild(childName) + : null; + const childWritesCache = writeTreeRefChild(writesCache, childName); + events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache)); + } + if (syncPoint) { + events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)); + } + return events; + } +} +/** + * Recursive helper for applyOperationToSyncPoints_ + */ +function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) { + const syncPoint = syncPointTree.get(newEmptyPath()); + // If we don't have cached server data, see if we can get it from this SyncPoint. + if (serverCache == null && syncPoint != null) { + serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + let events = []; + syncPointTree.children.inorderTraversal((childName, childTree) => { + const childServerCache = serverCache + ? serverCache.getImmediateChild(childName) + : null; + const childWritesCache = writeTreeRefChild(writesCache, childName); + const childOperation = operation.operationForChild(childName); + if (childOperation) { + events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache)); + } + }); + if (syncPoint) { + events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)); + } + return events; +} +function syncTreeCreateListenerForView_(syncTree, view) { + const query = view.query; + const tag = syncTreeTagForQuery(syncTree, query); + return { + hashFn: () => { + const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE; + return cache.hash(); + }, + onComplete: (status) => { + if (status === 'ok') { + if (tag) { + return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag); + } + else { + return syncTreeApplyListenComplete(syncTree, query._path); + } + } + else { + // If a listen failed, kill all of the listeners here, not just the one that triggered the error. + // Note that this may need to be scoped to just this listener if we change permissions on filtered children + const error = errorForServerCode(status, query); + return syncTreeRemoveEventRegistration(syncTree, query, + /*eventRegistration*/ null, error); + } + } + }; +} +/** + * Return the tag associated with the given query. + */ +function syncTreeTagForQuery(syncTree, query) { + const queryKey = syncTreeMakeQueryKey_(query); + return syncTree.queryToTagMap.get(queryKey); +} +/** + * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_. + */ +function syncTreeMakeQueryKey_(query) { + return query._path.toString() + '$' + query._queryIdentifier; +} +/** + * Return the query associated with the given tag, if we have one + */ +function syncTreeQueryKeyForTag_(syncTree, tag) { + return syncTree.tagToQueryMap.get(tag); +} +/** + * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId. + */ +function syncTreeParseQueryKey_(queryKey) { + const splitIndex = queryKey.indexOf('$'); + assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.'); + return { + queryId: queryKey.substr(splitIndex + 1), + path: new Path(queryKey.substr(0, splitIndex)) + }; +} +/** + * A helper method to apply tagged operations + */ +function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) { + const syncPoint = syncTree.syncPointTree_.get(queryPath); + assert(syncPoint, "Missing sync point for query tag that we're tracking"); + const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath); + return syncPointApplyOperation(syncPoint, operation, writesCache, null); +} +/** + * This collapses multiple unfiltered views into a single view, since we only need a single + * listener for them. + */ +function syncTreeCollectDistinctViewsForSubTree_(subtree) { + return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => { + if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) { + const completeView = syncPointGetCompleteView(maybeChildSyncPoint); + return [completeView]; + } + else { + // No complete view here, flatten any deeper listens into an array + let views = []; + if (maybeChildSyncPoint) { + views = syncPointGetQueryViews(maybeChildSyncPoint); + } + each(childMap, (_key, childViews) => { + views = views.concat(childViews); + }); + return views; + } + }); +} +/** + * Normalizes a query to a query we send the server for listening + * + * @returns The normalized query + */ +function syncTreeQueryForListening_(query) { + if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) { + // We treat queries that load all data as default queries + // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits + // from Query + return new (syncTreeGetReferenceConstructor())(query._repo, query._path); + } + else { + return query; + } +} +function syncTreeRemoveTags_(syncTree, queries) { + for (let j = 0; j < queries.length; ++j) { + const removedQuery = queries[j]; + if (!removedQuery._queryParams.loadsAllData()) { + // We should have a tag for this + const removedQueryKey = syncTreeMakeQueryKey_(removedQuery); + const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey); + syncTree.queryToTagMap.delete(removedQueryKey); + syncTree.tagToQueryMap.delete(removedQueryTag); + } + } +} +/** + * Static accessor for query tags. + */ +function syncTreeGetNextQueryTag_() { + return syncTreeNextQueryTag_++; +} +/** + * For a given new listen, manage the de-duplication of outstanding subscriptions. + * + * @returns This method can return events to support synchronous data sources + */ +function syncTreeSetupListener_(syncTree, query, view) { + const path = query._path; + const tag = syncTreeTagForQuery(syncTree, query); + const listener = syncTreeCreateListenerForView_(syncTree, view); + const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete); + const subtree = syncTree.syncPointTree_.subtree(path); + // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we + // may need to shadow other listens as well. + if (tag) { + assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed"); + } + else { + // Shadow everything at or below this location, this is a default listener. + const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => { + if (!pathIsEmpty(relativePath) && + maybeChildSyncPoint && + syncPointHasCompleteView(maybeChildSyncPoint)) { + return [syncPointGetCompleteView(maybeChildSyncPoint).query]; + } + else { + // No default listener here, flatten any deeper queries into an array + let queries = []; + if (maybeChildSyncPoint) { + queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query)); + } + each(childMap, (_key, childQueries) => { + queries = queries.concat(childQueries); + }); + return queries; + } + }); + for (let i = 0; i < queriesToStop.length; ++i) { + const queryToStop = queriesToStop[i]; + syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop)); + } + } + return events; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ExistingValueProvider { + constructor(node_) { + this.node_ = node_; + } + getImmediateChild(childName) { + const child = this.node_.getImmediateChild(childName); + return new ExistingValueProvider(child); + } + node() { + return this.node_; + } +} +class DeferredValueProvider { + constructor(syncTree, path) { + this.syncTree_ = syncTree; + this.path_ = path; + } + getImmediateChild(childName) { + const childPath = pathChild(this.path_, childName); + return new DeferredValueProvider(this.syncTree_, childPath); + } + node() { + return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_); + } +} +/** + * Generate placeholders for deferred values. + */ +const generateWithValues = function (values) { + values = values || {}; + values['timestamp'] = values['timestamp'] || new Date().getTime(); + return values; +}; +/** + * Value to use when firing local events. When writing server values, fire + * local events with an approximate value, otherwise return value as-is. + */ +const resolveDeferredLeafValue = function (value, existingVal, serverValues) { + if (!value || typeof value !== 'object') { + return value; + } + assert('.sv' in value, 'Unexpected leaf node or priority contents'); + if (typeof value['.sv'] === 'string') { + return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues); + } + else if (typeof value['.sv'] === 'object') { + return resolveComplexDeferredValue(value['.sv'], existingVal); + } + else { + assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2)); + } +}; +const resolveScalarDeferredValue = function (op, existing, serverValues) { + switch (op) { + case 'timestamp': + return serverValues['timestamp']; + default: + assert(false, 'Unexpected server value: ' + op); + } +}; +const resolveComplexDeferredValue = function (op, existing, unused) { + if (!op.hasOwnProperty('increment')) { + assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2)); + } + const delta = op['increment']; + if (typeof delta !== 'number') { + assert(false, 'Unexpected increment value: ' + delta); + } + const existingNode = existing.node(); + assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls'); + // Incrementing a non-number sets the value to the incremented amount + if (!existingNode.isLeafNode()) { + return delta; + } + const leaf = existingNode; + const existingVal = leaf.getValue(); + if (typeof existingVal !== 'number') { + return delta; + } + // No need to do over/underflow arithmetic here because JS only handles floats under the covers + return existingVal + delta; +}; +/** + * Recursively replace all deferred values and priorities in the tree with the + * specified generated replacement values. + * @param path - path to which write is relative + * @param node - new data written at path + * @param syncTree - current data + */ +const resolveDeferredValueTree = function (path, node, syncTree, serverValues) { + return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues); +}; +/** + * Recursively replace all deferred values and priorities in the node with the + * specified generated replacement values. If there are no server values in the node, + * it'll be returned as-is. + */ +const resolveDeferredValueSnapshot = function (node, existing, serverValues) { + return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues); +}; +function resolveDeferredValue(node, existingVal, serverValues) { + const rawPri = node.getPriority().val(); + const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues); + let newNode; + if (node.isLeafNode()) { + const leafNode = node; + const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues); + if (value !== leafNode.getValue() || + priority !== leafNode.getPriority().val()) { + return new LeafNode(value, nodeFromJSON(priority)); + } + else { + return node; + } + } + else { + const childrenNode = node; + newNode = childrenNode; + if (priority !== childrenNode.getPriority().val()) { + newNode = newNode.updatePriority(new LeafNode(priority)); + } + childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => { + const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues); + if (newChildNode !== childNode) { + newNode = newNode.updateImmediateChild(childName, newChildNode); + } + }); + return newNode; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A light-weight tree, traversable by path. Nodes can have both values and children. + * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty + * children. + */ +class Tree { + /** + * @param name - Optional name of the node. + * @param parent - Optional parent node. + * @param node - Optional node to wrap. + */ + constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) { + this.name = name; + this.parent = parent; + this.node = node; + } +} +/** + * Returns a sub-Tree for the given path. + * + * @param pathObj - Path to look up. + * @returns Tree for path. + */ +function treeSubTree(tree, pathObj) { + // TODO: Require pathObj to be Path? + let path = pathObj instanceof Path ? pathObj : new Path(pathObj); + let child = tree, next = pathGetFront(path); + while (next !== null) { + const childNode = safeGet(child.node.children, next) || { + children: {}, + childCount: 0 + }; + child = new Tree(next, child, childNode); + path = pathPopFront(path); + next = pathGetFront(path); + } + return child; +} +/** + * Returns the data associated with this tree node. + * + * @returns The data or null if no data exists. + */ +function treeGetValue(tree) { + return tree.node.value; +} +/** + * Sets data to this tree node. + * + * @param value - Value to set. + */ +function treeSetValue(tree, value) { + tree.node.value = value; + treeUpdateParents(tree); +} +/** + * @returns Whether the tree has any children. + */ +function treeHasChildren(tree) { + return tree.node.childCount > 0; +} +/** + * @returns Whether the tree is empty (no value or children). + */ +function treeIsEmpty(tree) { + return treeGetValue(tree) === undefined && !treeHasChildren(tree); +} +/** + * Calls action for each child of this tree node. + * + * @param action - Action to be called for each child. + */ +function treeForEachChild(tree, action) { + each(tree.node.children, (child, childTree) => { + action(new Tree(child, tree, childTree)); + }); +} +/** + * Does a depth-first traversal of this node's descendants, calling action for each one. + * + * @param action - Action to be called for each child. + * @param includeSelf - Whether to call action on this node as well. Defaults to + * false. + * @param childrenFirst - Whether to call action on children before calling it on + * parent. + */ +function treeForEachDescendant(tree, action, includeSelf, childrenFirst) { + if (includeSelf && !childrenFirst) { + action(tree); + } + treeForEachChild(tree, child => { + treeForEachDescendant(child, action, true, childrenFirst); + }); + if (includeSelf && childrenFirst) { + action(tree); + } +} +/** + * Calls action on each ancestor node. + * + * @param action - Action to be called on each parent; return + * true to abort. + * @param includeSelf - Whether to call action on this node as well. + * @returns true if the action callback returned true. + */ +function treeForEachAncestor(tree, action, includeSelf) { + let node = includeSelf ? tree : tree.parent; + while (node !== null) { + if (action(node)) { + return true; + } + node = node.parent; + } + return false; +} +/** + * @returns The path of this tree node, as a Path. + */ +function treeGetPath(tree) { + return new Path(tree.parent === null + ? tree.name + : treeGetPath(tree.parent) + '/' + tree.name); +} +/** + * Adds or removes this child from its parent based on whether it's empty or not. + */ +function treeUpdateParents(tree) { + if (tree.parent !== null) { + treeUpdateChild(tree.parent, tree.name, tree); + } +} +/** + * Adds or removes the passed child to this tree node, depending on whether it's empty. + * + * @param childName - The name of the child to update. + * @param child - The child to update. + */ +function treeUpdateChild(tree, childName, child) { + const childEmpty = treeIsEmpty(child); + const childExists = contains(tree.node.children, childName); + if (childEmpty && childExists) { + delete tree.node.children[childName]; + tree.node.childCount--; + treeUpdateParents(tree); + } + else if (!childEmpty && !childExists) { + tree.node.children[childName] = child.node; + tree.node.childCount++; + treeUpdateParents(tree); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * True for invalid Firebase keys + */ +const INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/; +/** + * True for invalid Firebase paths. + * Allows '/' in paths. + */ +const INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/; +/** + * Maximum number of characters to allow in leaf value + */ +const MAX_LEAF_SIZE_ = 10 * 1024 * 1024; +const isValidKey = function (key) { + return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key)); +}; +const isValidPathString = function (pathString) { + return (typeof pathString === 'string' && + pathString.length !== 0 && + !INVALID_PATH_REGEX_.test(pathString)); +}; +const isValidRootPathString = function (pathString) { + if (pathString) { + // Allow '/.info/' at the beginning. + pathString = pathString.replace(/^\/*\.info(\/|$)/, '/'); + } + return isValidPathString(pathString); +}; +const isValidPriority = function (priority) { + return (priority === null || + typeof priority === 'string' || + (typeof priority === 'number' && !isInvalidJSONNumber(priority)) || + (priority && + typeof priority === 'object' && + // eslint-disable-next-line @typescript-eslint/no-explicit-any + contains(priority, '.sv'))); +}; +/** + * Pre-validate a datum passed as an argument to Firebase function. + */ +const validateFirebaseDataArg = function (fnName, value, path, optional) { + if (optional && value === undefined) { + return; + } + validateFirebaseData(errorPrefix(fnName, 'value'), value, path); +}; +/** + * Validate a data object client-side before sending to server. + */ +const validateFirebaseData = function (errorPrefix, data, path_) { + const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_; + if (data === undefined) { + throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path)); + } + if (typeof data === 'function') { + throw new Error(errorPrefix + + 'contains a function ' + + validationPathToErrorString(path) + + ' with contents = ' + + data.toString()); + } + if (isInvalidJSONNumber(data)) { + throw new Error(errorPrefix + + 'contains ' + + data.toString() + + ' ' + + validationPathToErrorString(path)); + } + // Check max leaf size, but try to avoid the utf8 conversion if we can. + if (typeof data === 'string' && + data.length > MAX_LEAF_SIZE_ / 3 && + stringLength(data) > MAX_LEAF_SIZE_) { + throw new Error(errorPrefix + + 'contains a string greater than ' + + MAX_LEAF_SIZE_ + + ' utf8 bytes ' + + validationPathToErrorString(path) + + " ('" + + data.substring(0, 50) + + "...')"); + } + // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON + // to save extra walking of large objects. + if (data && typeof data === 'object') { + let hasDotValue = false; + let hasActualChild = false; + each(data, (key, value) => { + if (key === '.value') { + hasDotValue = true; + } + else if (key !== '.priority' && key !== '.sv') { + hasActualChild = true; + if (!isValidKey(key)) { + throw new Error(errorPrefix + + ' contains an invalid key (' + + key + + ') ' + + validationPathToErrorString(path) + + '. Keys must be non-empty strings ' + + 'and can\'t contain ".", "#", "$", "/", "[", or "]"'); + } + } + validationPathPush(path, key); + validateFirebaseData(errorPrefix, value, path); + validationPathPop(path); + }); + if (hasDotValue && hasActualChild) { + throw new Error(errorPrefix + + ' contains ".value" child ' + + validationPathToErrorString(path) + + ' in addition to actual children.'); + } + } +}; +/** + * Pre-validate paths passed in the firebase function. + */ +const validateFirebaseMergePaths = function (errorPrefix, mergePaths) { + let i, curPath; + for (i = 0; i < mergePaths.length; i++) { + curPath = mergePaths[i]; + const keys = pathSlice(curPath); + for (let j = 0; j < keys.length; j++) { + if (keys[j] === '.priority' && j === keys.length - 1) ; + else if (!isValidKey(keys[j])) { + throw new Error(errorPrefix + + 'contains an invalid key (' + + keys[j] + + ') in path ' + + curPath.toString() + + '. Keys must be non-empty strings ' + + 'and can\'t contain ".", "#", "$", "/", "[", or "]"'); + } + } + } + // Check that update keys are not descendants of each other. + // We rely on the property that sorting guarantees that ancestors come + // right before descendants. + mergePaths.sort(pathCompare); + let prevPath = null; + for (i = 0; i < mergePaths.length; i++) { + curPath = mergePaths[i]; + if (prevPath !== null && pathContains(prevPath, curPath)) { + throw new Error(errorPrefix + + 'contains a path ' + + prevPath.toString() + + ' that is ancestor of another path ' + + curPath.toString()); + } + prevPath = curPath; + } +}; +/** + * pre-validate an object passed as an argument to firebase function ( + * must be an object - e.g. for firebase.update()). + */ +const validateFirebaseMergeDataArg = function (fnName, data, path, optional) { + if (optional && data === undefined) { + return; + } + const errorPrefix$1 = errorPrefix(fnName, 'values'); + if (!(data && typeof data === 'object') || Array.isArray(data)) { + throw new Error(errorPrefix$1 + ' must be an object containing the children to replace.'); + } + const mergePaths = []; + each(data, (key, value) => { + const curPath = new Path(key); + validateFirebaseData(errorPrefix$1, value, pathChild(path, curPath)); + if (pathGetBack(curPath) === '.priority') { + if (!isValidPriority(value)) { + throw new Error(errorPrefix$1 + + "contains an invalid value for '" + + curPath.toString() + + "', which must be a valid " + + 'Firebase priority (a string, finite number, server value, or null).'); + } + } + mergePaths.push(curPath); + }); + validateFirebaseMergePaths(errorPrefix$1, mergePaths); +}; +const validatePriority = function (fnName, priority, optional) { + if (optional && priority === undefined) { + return; + } + if (isInvalidJSONNumber(priority)) { + throw new Error(errorPrefix(fnName, 'priority') + + 'is ' + + priority.toString() + + ', but must be a valid Firebase priority (a string, finite number, ' + + 'server value, or null).'); + } + // Special case to allow importing data with a .sv. + if (!isValidPriority(priority)) { + throw new Error(errorPrefix(fnName, 'priority') + + 'must be a valid Firebase priority ' + + '(a string, finite number, server value, or null).'); + } +}; +const validateKey = function (fnName, argumentName, key, optional) { + if (optional && key === undefined) { + return; + } + if (!isValidKey(key)) { + throw new Error(errorPrefix(fnName, argumentName) + + 'was an invalid key = "' + + key + + '". Firebase keys must be non-empty strings and ' + + 'can\'t contain ".", "#", "$", "/", "[", or "]").'); + } +}; +/** + * @internal + */ +const validatePathString = function (fnName, argumentName, pathString, optional) { + if (optional && pathString === undefined) { + return; + } + if (!isValidPathString(pathString)) { + throw new Error(errorPrefix(fnName, argumentName) + + 'was an invalid path = "' + + pathString + + '". Paths must be non-empty strings and ' + + 'can\'t contain ".", "#", "$", "[", or "]"'); + } +}; +const validateRootPathString = function (fnName, argumentName, pathString, optional) { + if (pathString) { + // Allow '/.info/' at the beginning. + pathString = pathString.replace(/^\/*\.info(\/|$)/, '/'); + } + validatePathString(fnName, argumentName, pathString, optional); +}; +/** + * @internal + */ +const validateWritablePath = function (fnName, path) { + if (pathGetFront(path) === '.info') { + throw new Error(fnName + " failed = Can't modify data under /.info/"); + } +}; +const validateUrl = function (fnName, parsedUrl) { + // TODO = Validate server better. + const pathString = parsedUrl.path.toString(); + if (!(typeof parsedUrl.repoInfo.host === 'string') || + parsedUrl.repoInfo.host.length === 0 || + (!isValidKey(parsedUrl.repoInfo.namespace) && + parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') || + (pathString.length !== 0 && !isValidRootPathString(pathString))) { + throw new Error(errorPrefix(fnName, 'url') + + 'must be a valid firebase URL and ' + + 'the path can\'t contain ".", "#", "$", "[", or "]".'); + } +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The event queue serves a few purposes: + * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more + * events being queued. + * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events, + * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call + * left off, ensuring that the events are still raised synchronously and in order. + * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued + * events are raised synchronously. + * + * NOTE: This can all go away if/when we move to async events. + * + */ +class EventQueue { + constructor() { + this.eventLists_ = []; + /** + * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes. + */ + this.recursionDepth_ = 0; + } +} +/** + * @param eventDataList - The new events to queue. + */ +function eventQueueQueueEvents(eventQueue, eventDataList) { + // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly. + let currList = null; + for (let i = 0; i < eventDataList.length; i++) { + const data = eventDataList[i]; + const path = data.getPath(); + if (currList !== null && !pathEquals(path, currList.path)) { + eventQueue.eventLists_.push(currList); + currList = null; + } + if (currList === null) { + currList = { events: [], path }; + } + currList.events.push(data); + } + if (currList) { + eventQueue.eventLists_.push(currList); + } +} +/** + * Queues the specified events and synchronously raises all events (including previously queued ones) + * for the specified path. + * + * It is assumed that the new events are all for the specified path. + * + * @param path - The path to raise events for. + * @param eventDataList - The new events to raise. + */ +function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) { + eventQueueQueueEvents(eventQueue, eventDataList); + eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path)); +} +/** + * Queues the specified events and synchronously raises all events (including previously queued ones) for + * locations related to the specified change path (i.e. all ancestors and descendants). + * + * It is assumed that the new events are all related (ancestor or descendant) to the specified path. + * + * @param changedPath - The path to raise events for. + * @param eventDataList - The events to raise + */ +function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) { + eventQueueQueueEvents(eventQueue, eventDataList); + eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) || + pathContains(changedPath, eventPath)); +} +function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) { + eventQueue.recursionDepth_++; + let sentAll = true; + for (let i = 0; i < eventQueue.eventLists_.length; i++) { + const eventList = eventQueue.eventLists_[i]; + if (eventList) { + const eventPath = eventList.path; + if (predicate(eventPath)) { + eventListRaise(eventQueue.eventLists_[i]); + eventQueue.eventLists_[i] = null; + } + else { + sentAll = false; + } + } + } + if (sentAll) { + eventQueue.eventLists_ = []; + } + eventQueue.recursionDepth_--; +} +/** + * Iterates through the list and raises each event + */ +function eventListRaise(eventList) { + for (let i = 0; i < eventList.events.length; i++) { + const eventData = eventList.events[i]; + if (eventData !== null) { + eventList.events[i] = null; + const eventFn = eventData.getEventRunner(); + if (logger) { + log('event: ' + eventData.toString()); + } + exceptionGuard(eventFn); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const INTERRUPT_REASON = 'repo_interrupt'; +/** + * If a transaction does not succeed after 25 retries, we abort it. Among other + * things this ensure that if there's ever a bug causing a mismatch between + * client / server hashes for some data, we won't retry indefinitely. + */ +const MAX_TRANSACTION_RETRIES = 25; +/** + * A connection to a single data repository. + */ +class Repo { + constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) { + this.repoInfo_ = repoInfo_; + this.forceRestClient_ = forceRestClient_; + this.authTokenProvider_ = authTokenProvider_; + this.appCheckProvider_ = appCheckProvider_; + this.dataUpdateCount = 0; + this.statsListener_ = null; + this.eventQueue_ = new EventQueue(); + this.nextWriteId_ = 1; + this.interceptServerDataCallback_ = null; + /** A list of data pieces and paths to be set when this client disconnects. */ + this.onDisconnect_ = newSparseSnapshotTree(); + /** Stores queues of outstanding transactions for Firebase locations. */ + this.transactionQueueTree_ = new Tree(); + // TODO: This should be @private but it's used by test_access.js and internal.js + this.persistentConnection_ = null; + // This key is intentionally not updated if RepoInfo is later changed or replaced + this.key = this.repoInfo_.toURLString(); + } + /** + * @returns The URL corresponding to the root of this Firebase. + */ + toString() { + return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host); + } +} +function repoStart(repo, appId, authOverride) { + repo.stats_ = statsManagerGetCollection(repo.repoInfo_); + if (repo.forceRestClient_ || beingCrawled()) { + repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => { + repoOnDataUpdate(repo, pathString, data, isMerge, tag); + }, repo.authTokenProvider_, repo.appCheckProvider_); + // Minor hack: Fire onConnect immediately, since there's no actual connection. + setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0); + } + else { + // Validate authOverride + if (typeof authOverride !== 'undefined' && authOverride !== null) { + if (typeof authOverride !== 'object') { + throw new Error('Only objects are supported for option databaseAuthVariableOverride'); + } + try { + stringify(authOverride); + } + catch (e) { + throw new Error('Invalid authOverride provided: ' + e); + } + } + repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => { + repoOnDataUpdate(repo, pathString, data, isMerge, tag); + }, (connectStatus) => { + repoOnConnectStatus(repo, connectStatus); + }, (updates) => { + repoOnServerInfoUpdate(repo, updates); + }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride); + repo.server_ = repo.persistentConnection_; + } + repo.authTokenProvider_.addTokenChangeListener(token => { + repo.server_.refreshAuthToken(token); + }); + repo.appCheckProvider_.addTokenChangeListener(result => { + repo.server_.refreshAppCheckToken(result.token); + }); + // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used), + // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created. + repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_)); + // Used for .info. + repo.infoData_ = new SnapshotHolder(); + repo.infoSyncTree_ = new SyncTree({ + startListening: (query, tag, currentHashFn, onComplete) => { + let infoEvents = []; + const node = repo.infoData_.getNode(query._path); + // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events + // on initial data... + if (!node.isEmpty()) { + infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node); + setTimeout(() => { + onComplete('ok'); + }, 0); + } + return infoEvents; + }, + stopListening: () => { } + }); + repoUpdateInfo(repo, 'connected', false); + repo.serverSyncTree_ = new SyncTree({ + startListening: (query, tag, currentHashFn, onComplete) => { + repo.server_.listen(query, currentHashFn, tag, (status, data) => { + const events = onComplete(status, data); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events); + }); + // No synchronous events for network-backed sync trees + return []; + }, + stopListening: (query, tag) => { + repo.server_.unlisten(query, tag); + } + }); +} +/** + * @returns The time in milliseconds, taking the server offset into account if we have one. + */ +function repoServerTime(repo) { + const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset')); + const offset = offsetNode.val() || 0; + return new Date().getTime() + offset; +} +/** + * Generate ServerValues using some variables from the repo object. + */ +function repoGenerateServerValues(repo) { + return generateWithValues({ + timestamp: repoServerTime(repo) + }); +} +/** + * Called by realtime when we get new messages from the server. + */ +function repoOnDataUpdate(repo, pathString, data, isMerge, tag) { + // For testing. + repo.dataUpdateCount++; + const path = new Path(pathString); + data = repo.interceptServerDataCallback_ + ? repo.interceptServerDataCallback_(pathString, data) + : data; + let events = []; + if (tag) { + if (isMerge) { + const taggedChildren = map(data, (raw) => nodeFromJSON(raw)); + events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag); + } + else { + const taggedSnap = nodeFromJSON(data); + events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag); + } + } + else if (isMerge) { + const changedChildren = map(data, (raw) => nodeFromJSON(raw)); + events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren); + } + else { + const snap = nodeFromJSON(data); + events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap); + } + let affectedPath = path; + if (events.length > 0) { + // Since we have a listener outstanding for each transaction, receiving any events + // is a proxy for some change having occurred. + affectedPath = repoRerunTransactions(repo, path); + } + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events); +} +function repoOnConnectStatus(repo, connectStatus) { + repoUpdateInfo(repo, 'connected', connectStatus); + if (connectStatus === false) { + repoRunOnDisconnectEvents(repo); + } +} +function repoOnServerInfoUpdate(repo, updates) { + each(updates, (key, value) => { + repoUpdateInfo(repo, key, value); + }); +} +function repoUpdateInfo(repo, pathString, value) { + const path = new Path('/.info/' + pathString); + const newNode = nodeFromJSON(value); + repo.infoData_.updateSnapshot(path, newNode); + const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); +} +function repoGetNextWriteId(repo) { + return repo.nextWriteId_++; +} +/** + * The purpose of `getValue` is to return the latest known value + * satisfying `query`. + * + * This method will first check for in-memory cached values + * belonging to active listeners. If they are found, such values + * are considered to be the most up-to-date. + * + * If the client is not connected, this method will wait until the + * repo has established a connection and then request the value for `query`. + * If the client is not able to retrieve the query result for another reason, + * it reports an error. + * + * @param query - The query to surface a value for. + */ +function repoGetValue(repo, query, eventRegistration) { + // Only active queries are cached. There is no persisted cache. + const cached = syncTreeGetServerValue(repo.serverSyncTree_, query); + if (cached != null) { + return Promise.resolve(cached); + } + return repo.server_.get(query).then(payload => { + const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex()); + /** + * Below we simulate the actions of an `onlyOnce` `onValue()` event where: + * Add an event registration, + * Update data at the path, + * Raise any events, + * Cleanup the SyncTree + */ + syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true); + let events; + if (query._queryParams.loadsAllData()) { + events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node); + } + else { + const tag = syncTreeTagForQuery(repo.serverSyncTree_, query); + events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag); + } + /* + * We need to raise events in the scenario where `get()` is called at a parent path, and + * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting + * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree + * and its corresponding serverCache, including the child location where `onValue` is called. Then, + * `onValue` will receive the event from the server, but look at the syncTree and see that the data received + * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired. + * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and + * ensure the corresponding child events will get fired. + */ + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events); + syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true); + return node; + }, err => { + repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err); + return Promise.reject(new Error(err)); + }); +} +function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) { + repoLog(repo, 'set', { + path: path.toString(), + value: newVal, + priority: newPriority + }); + // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or + // (b) store unresolved paths on JSON parse + const serverValues = repoGenerateServerValues(repo); + const newNodeUnresolved = nodeFromJSON(newVal, newPriority); + const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path); + const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues); + const writeId = repoGetNextWriteId(repo); + const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true); + eventQueueQueueEvents(repo.eventQueue_, events); + repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => { + const success = status === 'ok'; + if (!success) { + warn('set at ' + path + ' failed: ' + status); + } + const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents); + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); + const affectedPath = repoAbortTransactions(repo, path); + repoRerunTransactions(repo, affectedPath); + // We queued the events above, so just flush the queue here + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []); +} +function repoUpdate(repo, path, childrenToMerge, onComplete) { + repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge }); + // Start with our existing data and merge each child into it. + let empty = true; + const serverValues = repoGenerateServerValues(repo); + const changedChildren = {}; + each(childrenToMerge, (changedKey, changedValue) => { + empty = false; + changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues); + }); + if (!empty) { + const writeId = repoGetNextWriteId(repo); + const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId); + eventQueueQueueEvents(repo.eventQueue_, events); + repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => { + const success = status === 'ok'; + if (!success) { + warn('update at ' + path + ' failed: ' + status); + } + const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success); + const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path; + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents); + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); + each(childrenToMerge, (changedPath) => { + const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath)); + repoRerunTransactions(repo, affectedPath); + }); + // We queued the events above, so just flush the queue here + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []); + } + else { + log("update() called with empty data. Don't do anything."); + repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined); + } +} +/** + * Applies all of the changes stored up in the onDisconnect_ tree. + */ +function repoRunOnDisconnectEvents(repo) { + repoLog(repo, 'onDisconnectEvents'); + const serverValues = repoGenerateServerValues(repo); + const resolvedOnDisconnectTree = newSparseSnapshotTree(); + sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => { + const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues); + sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved); + }); + let events = []; + sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => { + events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap)); + const affectedPath = repoAbortTransactions(repo, path); + repoRerunTransactions(repo, affectedPath); + }); + repo.onDisconnect_ = newSparseSnapshotTree(); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events); +} +function repoOnDisconnectCancel(repo, path, onComplete) { + repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => { + if (status === 'ok') { + sparseSnapshotTreeForget(repo.onDisconnect_, path); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoOnDisconnectSet(repo, path, value, onComplete) { + const newNode = nodeFromJSON(value); + repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => { + if (status === 'ok') { + sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) { + const newNode = nodeFromJSON(value, priority); + repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => { + if (status === 'ok') { + sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) { + if (isEmpty(childrenToMerge)) { + log("onDisconnect().update() called with empty data. Don't do anything."); + repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined); + return; + } + repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => { + if (status === 'ok') { + each(childrenToMerge, (childName, childNode) => { + const newChildNode = nodeFromJSON(childNode); + sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode); + }); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoAddEventCallbackForQuery(repo, query, eventRegistration) { + let events; + if (pathGetFront(query._path) === '.info') { + events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration); + } + else { + events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration); + } + eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events); +} +function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) { + // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof + // a little bit by handling the return values anyways. + let events; + if (pathGetFront(query._path) === '.info') { + events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration); + } + else { + events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration); + } + eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events); +} +function repoInterrupt(repo) { + if (repo.persistentConnection_) { + repo.persistentConnection_.interrupt(INTERRUPT_REASON); + } +} +function repoResume(repo) { + if (repo.persistentConnection_) { + repo.persistentConnection_.resume(INTERRUPT_REASON); + } +} +function repoLog(repo, ...varArgs) { + let prefix = ''; + if (repo.persistentConnection_) { + prefix = repo.persistentConnection_.id + ':'; + } + log(prefix, ...varArgs); +} +function repoCallOnCompleteCallback(repo, callback, status, errorReason) { + if (callback) { + exceptionGuard(() => { + if (status === 'ok') { + callback(null); + } + else { + const code = (status || 'error').toUpperCase(); + let message = code; + if (errorReason) { + message += ': ' + errorReason; + } + const error = new Error(message); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error.code = code; + callback(error); + } + }); + } +} +/** + * Creates a new transaction, adds it to the transactions we're tracking, and + * sends it to the server if possible. + * + * @param path - Path at which to do transaction. + * @param transactionUpdate - Update callback. + * @param onComplete - Completion callback. + * @param unwatcher - Function that will be called when the transaction no longer + * need data updates for `path`. + * @param applyLocally - Whether or not to make intermediate results visible + */ +function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) { + repoLog(repo, 'transaction on ' + path); + // Initialize transaction. + const transaction = { + path, + update: transactionUpdate, + onComplete, + // One of TransactionStatus enums. + status: null, + // Used when combining transactions at different locations to figure out + // which one goes first. + order: LUIDGenerator(), + // Whether to raise local events for this transaction. + applyLocally, + // Count of how many times we've retried the transaction. + retryCount: 0, + // Function to call to clean up our .on() listener. + unwatcher, + // Stores why a transaction was aborted. + abortReason: null, + currentWriteId: null, + currentInputSnapshot: null, + currentOutputSnapshotRaw: null, + currentOutputSnapshotResolved: null + }; + // Run transaction initially. + const currentState = repoGetLatestState(repo, path, undefined); + transaction.currentInputSnapshot = currentState; + const newVal = transaction.update(currentState.val()); + if (newVal === undefined) { + // Abort transaction. + transaction.unwatcher(); + transaction.currentOutputSnapshotRaw = null; + transaction.currentOutputSnapshotResolved = null; + if (transaction.onComplete) { + transaction.onComplete(null, false, transaction.currentInputSnapshot); + } + } + else { + validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path); + // Mark as run and add to our queue. + transaction.status = 0 /* TransactionStatus.RUN */; + const queueNode = treeSubTree(repo.transactionQueueTree_, path); + const nodeQueue = treeGetValue(queueNode) || []; + nodeQueue.push(transaction); + treeSetValue(queueNode, nodeQueue); + // Update visibleData and raise events + // Note: We intentionally raise events after updating all of our + // transaction state, since the user could start new transactions from the + // event callbacks. + let priorityForNode; + if (typeof newVal === 'object' && + newVal !== null && + contains(newVal, '.priority')) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + priorityForNode = safeGet(newVal, '.priority'); + assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' + + 'Priority must be a valid string, finite number, server value, or null.'); + } + else { + const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) || + ChildrenNode.EMPTY_NODE; + priorityForNode = currentNode.getPriority().val(); + } + const serverValues = repoGenerateServerValues(repo); + const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode); + const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues); + transaction.currentOutputSnapshotRaw = newNodeUnresolved; + transaction.currentOutputSnapshotResolved = newNode; + transaction.currentWriteId = repoGetNextWriteId(repo); + const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); + repoSendReadyTransactions(repo, repo.transactionQueueTree_); + } +} +/** + * @param excludeSets - A specific set to exclude + */ +function repoGetLatestState(repo, path, excludeSets) { + return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) || + ChildrenNode.EMPTY_NODE); +} +/** + * Sends any already-run transactions that aren't waiting for outstanding + * transactions to complete. + * + * Externally it's called with no arguments, but it calls itself recursively + * with a particular transactionQueueTree node to recurse through the tree. + * + * @param node - transactionQueueTree node to start at. + */ +function repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) { + // Before recursing, make sure any completed transactions are removed. + if (!node) { + repoPruneCompletedTransactionsBelowNode(repo, node); + } + if (treeGetValue(node)) { + const queue = repoBuildTransactionQueue(repo, node); + assert(queue.length > 0, 'Sending zero length transaction queue'); + const allRun = queue.every((transaction) => transaction.status === 0 /* TransactionStatus.RUN */); + // If they're all run (and not sent), we can send them. Else, we must wait. + if (allRun) { + repoSendTransactionQueue(repo, treeGetPath(node), queue); + } + } + else if (treeHasChildren(node)) { + treeForEachChild(node, childNode => { + repoSendReadyTransactions(repo, childNode); + }); + } +} +/** + * Given a list of run transactions, send them to the server and then handle + * the result (success or failure). + * + * @param path - The location of the queue. + * @param queue - Queue of transactions under the specified location. + */ +function repoSendTransactionQueue(repo, path, queue) { + // Mark transactions as sent and increment retry count! + const setsToIgnore = queue.map(txn => { + return txn.currentWriteId; + }); + const latestState = repoGetLatestState(repo, path, setsToIgnore); + let snapToSend = latestState; + const latestHash = latestState.hash(); + for (let i = 0; i < queue.length; i++) { + const txn = queue[i]; + assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.'); + txn.status = 1 /* TransactionStatus.SENT */; + txn.retryCount++; + const relativePath = newRelativePath(path, txn.path); + // If we've gotten to this point, the output snapshot must be defined. + snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw); + } + const dataToSend = snapToSend.val(true); + const pathToSend = path; + // Send the put. + repo.server_.put(pathToSend.toString(), dataToSend, (status) => { + repoLog(repo, 'transaction put response', { + path: pathToSend.toString(), + status + }); + let events = []; + if (status === 'ok') { + // Queue up the callbacks and fire them after cleaning up all of our + // transaction state, since the callback could trigger more + // transactions or sets. + const callbacks = []; + for (let i = 0; i < queue.length; i++) { + queue[i].status = 2 /* TransactionStatus.COMPLETED */; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId)); + if (queue[i].onComplete) { + // We never unset the output snapshot, and given that this + // transaction is complete, it should be set + callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved)); + } + queue[i].unwatcher(); + } + // Now remove the completed transactions. + repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path)); + // There may be pending transactions that we can now send. + repoSendReadyTransactions(repo, repo.transactionQueueTree_); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); + // Finally, trigger onComplete callbacks. + for (let i = 0; i < callbacks.length; i++) { + exceptionGuard(callbacks[i]); + } + } + else { + // transactions are no longer sent. Update their status appropriately. + if (status === 'datastale') { + for (let i = 0; i < queue.length; i++) { + if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) { + queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */; + } + else { + queue[i].status = 0 /* TransactionStatus.RUN */; + } + } + } + else { + warn('transaction at ' + pathToSend.toString() + ' failed: ' + status); + for (let i = 0; i < queue.length; i++) { + queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */; + queue[i].abortReason = status; + } + } + repoRerunTransactions(repo, path); + } + }, latestHash); +} +/** + * Finds all transactions dependent on the data at changedPath and reruns them. + * + * Should be called any time cached data changes. + * + * Return the highest path that was affected by rerunning transactions. This + * is the path at which events need to be raised for. + * + * @param changedPath - The path in mergedData that changed. + * @returns The rootmost path that was affected by rerunning transactions. + */ +function repoRerunTransactions(repo, changedPath) { + const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath); + const path = treeGetPath(rootMostTransactionNode); + const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode); + repoRerunTransactionQueue(repo, queue, path); + return path; +} +/** + * Does all the work of rerunning transactions (as well as cleans up aborted + * transactions and whatnot). + * + * @param queue - The queue of transactions to run. + * @param path - The path the queue is for. + */ +function repoRerunTransactionQueue(repo, queue, path) { + if (queue.length === 0) { + return; // Nothing to do! + } + // Queue up the callbacks and fire them after cleaning up all of our + // transaction state, since the callback could trigger more transactions or + // sets. + const callbacks = []; + let events = []; + // Ignore all of the sets we're going to re-run. + const txnsToRerun = queue.filter(q => { + return q.status === 0 /* TransactionStatus.RUN */; + }); + const setsToIgnore = txnsToRerun.map(q => { + return q.currentWriteId; + }); + for (let i = 0; i < queue.length; i++) { + const transaction = queue[i]; + const relativePath = newRelativePath(path, transaction.path); + let abortTransaction = false, abortReason; + assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.'); + if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) { + abortTransaction = true; + abortReason = transaction.abortReason; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true)); + } + else if (transaction.status === 0 /* TransactionStatus.RUN */) { + if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) { + abortTransaction = true; + abortReason = 'maxretry'; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true)); + } + else { + // This code reruns a transaction + const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore); + transaction.currentInputSnapshot = currentNode; + const newData = queue[i].update(currentNode.val()); + if (newData !== undefined) { + validateFirebaseData('transaction failed: Data returned ', newData, transaction.path); + let newDataNode = nodeFromJSON(newData); + const hasExplicitPriority = typeof newData === 'object' && + newData != null && + contains(newData, '.priority'); + if (!hasExplicitPriority) { + // Keep the old priority if there wasn't a priority explicitly specified. + newDataNode = newDataNode.updatePriority(currentNode.getPriority()); + } + const oldWriteId = transaction.currentWriteId; + const serverValues = repoGenerateServerValues(repo); + const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues); + transaction.currentOutputSnapshotRaw = newDataNode; + transaction.currentOutputSnapshotResolved = newNodeResolved; + transaction.currentWriteId = repoGetNextWriteId(repo); + // Mutates setsToIgnore in place + setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1); + events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally)); + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true)); + } + else { + abortTransaction = true; + abortReason = 'nodata'; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true)); + } + } + } + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); + events = []; + if (abortTransaction) { + // Abort. + queue[i].status = 2 /* TransactionStatus.COMPLETED */; + // Removing a listener can trigger pruning which can muck with + // mergedData/visibleData (as it prunes data). So defer the unwatcher + // until we're done. + (function (unwatcher) { + setTimeout(unwatcher, Math.floor(0)); + })(queue[i].unwatcher); + if (queue[i].onComplete) { + if (abortReason === 'nodata') { + callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot)); + } + else { + callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null)); + } + } + } + } + // Clean up completed transactions. + repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_); + // Now fire callbacks, now that we're in a good, known state. + for (let i = 0; i < callbacks.length; i++) { + exceptionGuard(callbacks[i]); + } + // Try to send the transaction result to the server. + repoSendReadyTransactions(repo, repo.transactionQueueTree_); +} +/** + * Returns the rootmost ancestor node of the specified path that has a pending + * transaction on it, or just returns the node for the given path if there are + * no pending transactions on any ancestor. + * + * @param path - The location to start at. + * @returns The rootmost node with a transaction. + */ +function repoGetAncestorTransactionNode(repo, path) { + let front; + // Start at the root and walk deeper into the tree towards path until we + // find a node with pending transactions. + let transactionNode = repo.transactionQueueTree_; + front = pathGetFront(path); + while (front !== null && treeGetValue(transactionNode) === undefined) { + transactionNode = treeSubTree(transactionNode, front); + path = pathPopFront(path); + front = pathGetFront(path); + } + return transactionNode; +} +/** + * Builds the queue of all transactions at or below the specified + * transactionNode. + * + * @param transactionNode + * @returns The generated queue. + */ +function repoBuildTransactionQueue(repo, transactionNode) { + // Walk any child transaction queues and aggregate them into a single queue. + const transactionQueue = []; + repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue); + // Sort them by the order the transactions were created. + transactionQueue.sort((a, b) => a.order - b.order); + return transactionQueue; +} +function repoAggregateTransactionQueuesForNode(repo, node, queue) { + const nodeQueue = treeGetValue(node); + if (nodeQueue) { + for (let i = 0; i < nodeQueue.length; i++) { + queue.push(nodeQueue[i]); + } + } + treeForEachChild(node, child => { + repoAggregateTransactionQueuesForNode(repo, child, queue); + }); +} +/** + * Remove COMPLETED transactions at or below this node in the transactionQueueTree_. + */ +function repoPruneCompletedTransactionsBelowNode(repo, node) { + const queue = treeGetValue(node); + if (queue) { + let to = 0; + for (let from = 0; from < queue.length; from++) { + if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) { + queue[to] = queue[from]; + to++; + } + } + queue.length = to; + treeSetValue(node, queue.length > 0 ? queue : undefined); + } + treeForEachChild(node, childNode => { + repoPruneCompletedTransactionsBelowNode(repo, childNode); + }); +} +/** + * Aborts all transactions on ancestors or descendants of the specified path. + * Called when doing a set() or update() since we consider them incompatible + * with transactions. + * + * @param path - Path for which we want to abort related transactions. + */ +function repoAbortTransactions(repo, path) { + const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path)); + const transactionNode = treeSubTree(repo.transactionQueueTree_, path); + treeForEachAncestor(transactionNode, (node) => { + repoAbortTransactionsOnNode(repo, node); + }); + repoAbortTransactionsOnNode(repo, transactionNode); + treeForEachDescendant(transactionNode, (node) => { + repoAbortTransactionsOnNode(repo, node); + }); + return affectedPath; +} +/** + * Abort transactions stored in this transaction queue node. + * + * @param node - Node to abort transactions for. + */ +function repoAbortTransactionsOnNode(repo, node) { + const queue = treeGetValue(node); + if (queue) { + // Queue up the callbacks and fire them after cleaning up all of our + // transaction state, since the callback could trigger more transactions + // or sets. + const callbacks = []; + // Go through queue. Any already-sent transactions must be marked for + // abort, while the unsent ones can be immediately aborted and removed. + let events = []; + let lastSent = -1; + for (let i = 0; i < queue.length; i++) { + if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ; + else if (queue[i].status === 1 /* TransactionStatus.SENT */) { + assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.'); + lastSent = i; + // Mark transaction for abort when it comes back. + queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */; + queue[i].abortReason = 'set'; + } + else { + assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort'); + // We can abort it immediately. + queue[i].unwatcher(); + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true)); + if (queue[i].onComplete) { + callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null)); + } + } + } + if (lastSent === -1) { + // We're not waiting for any sent transactions. We can clear the queue. + treeSetValue(node, undefined); + } + else { + // Remove the transactions we aborted. + queue.length = lastSent + 1; + } + // Now fire the callbacks. + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events); + for (let i = 0; i < callbacks.length; i++) { + exceptionGuard(callbacks[i]); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function decodePath(pathString) { + let pathStringDecoded = ''; + const pieces = pathString.split('/'); + for (let i = 0; i < pieces.length; i++) { + if (pieces[i].length > 0) { + let piece = pieces[i]; + try { + piece = decodeURIComponent(piece.replace(/\+/g, ' ')); + } + catch (e) { } + pathStringDecoded += '/' + piece; + } + } + return pathStringDecoded; +} +/** + * @returns key value hash + */ +function decodeQuery(queryString) { + const results = {}; + if (queryString.charAt(0) === '?') { + queryString = queryString.substring(1); + } + for (const segment of queryString.split('&')) { + if (segment.length === 0) { + continue; + } + const kv = segment.split('='); + if (kv.length === 2) { + results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]); + } + else { + warn(`Invalid query segment '${segment}' in query '${queryString}'`); + } + } + return results; +} +const parseRepoInfo = function (dataURL, nodeAdmin) { + const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace; + if (parsedUrl.domain === 'firebase.com') { + fatal(parsedUrl.host + + ' is no longer supported. ' + + 'Please use .firebaseio.com instead'); + } + // Catch common error of uninitialized namespace value. + if ((!namespace || namespace === 'undefined') && + parsedUrl.domain !== 'localhost') { + fatal('Cannot parse Firebase url. Please use https://.firebaseio.com'); + } + if (!parsedUrl.secure) { + warnIfPageIsSecure(); + } + const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss'; + return { + repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin, + /*persistenceKey=*/ '', + /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain), + path: new Path(parsedUrl.pathString) + }; +}; +const parseDatabaseURL = function (dataURL) { + // Default to empty strings in the event of a malformed string. + let host = '', domain = '', subdomain = '', pathString = '', namespace = ''; + // Always default to SSL, unless otherwise specified. + let secure = true, scheme = 'https', port = 443; + // Don't do any validation here. The caller is responsible for validating the result of parsing. + if (typeof dataURL === 'string') { + // Parse scheme. + let colonInd = dataURL.indexOf('//'); + if (colonInd >= 0) { + scheme = dataURL.substring(0, colonInd - 1); + dataURL = dataURL.substring(colonInd + 2); + } + // Parse host, path, and query string. + let slashInd = dataURL.indexOf('/'); + if (slashInd === -1) { + slashInd = dataURL.length; + } + let questionMarkInd = dataURL.indexOf('?'); + if (questionMarkInd === -1) { + questionMarkInd = dataURL.length; + } + host = dataURL.substring(0, Math.min(slashInd, questionMarkInd)); + if (slashInd < questionMarkInd) { + // For pathString, questionMarkInd will always come after slashInd + pathString = decodePath(dataURL.substring(slashInd, questionMarkInd)); + } + const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd))); + // If we have a port, use scheme for determining if it's secure. + colonInd = host.indexOf(':'); + if (colonInd >= 0) { + secure = scheme === 'https' || scheme === 'wss'; + port = parseInt(host.substring(colonInd + 1), 10); + } + else { + colonInd = host.length; + } + const hostWithoutPort = host.slice(0, colonInd); + if (hostWithoutPort.toLowerCase() === 'localhost') { + domain = 'localhost'; + } + else if (hostWithoutPort.split('.').length <= 2) { + domain = hostWithoutPort; + } + else { + // Interpret the subdomain of a 3 or more component URL as the namespace name. + const dotInd = host.indexOf('.'); + subdomain = host.substring(0, dotInd).toLowerCase(); + domain = host.substring(dotInd + 1); + // Normalize namespaces to lowercase to share storage / connection. + namespace = subdomain; + } + // Always treat the value of the `ns` as the namespace name if it is present. + if ('ns' in queryParams) { + namespace = queryParams['ns']; + } + } + return { + host, + port, + domain, + subdomain, + secure, + scheme, + pathString, + namespace + }; +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Modeled after base64 web-safe chars, but ordered by ASCII. +const PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'; +/** + * Fancy ID generator that creates 20-character string identifiers with the + * following properties: + * + * 1. They're based on timestamp so that they sort *after* any existing ids. + * 2. They contain 72-bits of random data after the timestamp so that IDs won't + * collide with other clients' IDs. + * 3. They sort *lexicographically* (so the timestamp is converted to characters + * that will sort properly). + * 4. They're monotonically increasing. Even if you generate more than one in + * the same timestamp, the latter ones will sort after the former ones. We do + * this by using the previous random bits but "incrementing" them by 1 (only + * in the case of a timestamp collision). + */ +const nextPushId = (function () { + // Timestamp of last push, used to prevent local collisions if you push twice + // in one ms. + let lastPushTime = 0; + // We generate 72-bits of randomness which get turned into 12 characters and + // appended to the timestamp to prevent collisions with other clients. We + // store the last characters we generated because in the event of a collision, + // we'll use those same characters except "incremented" by one. + const lastRandChars = []; + return function (now) { + const duplicateTime = now === lastPushTime; + lastPushTime = now; + let i; + const timeStampChars = new Array(8); + for (i = 7; i >= 0; i--) { + timeStampChars[i] = PUSH_CHARS.charAt(now % 64); + // NOTE: Can't use << here because javascript will convert to int and lose + // the upper bits. + now = Math.floor(now / 64); + } + assert(now === 0, 'Cannot push at time == 0'); + let id = timeStampChars.join(''); + if (!duplicateTime) { + for (i = 0; i < 12; i++) { + lastRandChars[i] = Math.floor(Math.random() * 64); + } + } + else { + // If the timestamp hasn't changed since last push, use the same random + // number, except incremented by 1. + for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) { + lastRandChars[i] = 0; + } + lastRandChars[i]++; + } + for (i = 0; i < 12; i++) { + id += PUSH_CHARS.charAt(lastRandChars[i]); + } + assert(id.length === 20, 'nextPushId: Length should be 20.'); + return id; + }; +})(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Encapsulates the data needed to raise an event + */ +class DataEvent { + /** + * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed + * @param eventRegistration - The function to call to with the event data. User provided + * @param snapshot - The data backing the event + * @param prevName - Optional, the name of the previous child for child_* events. + */ + constructor(eventType, eventRegistration, snapshot, prevName) { + this.eventType = eventType; + this.eventRegistration = eventRegistration; + this.snapshot = snapshot; + this.prevName = prevName; + } + getPath() { + const ref = this.snapshot.ref; + if (this.eventType === 'value') { + return ref._path; + } + else { + return ref.parent._path; + } + } + getEventType() { + return this.eventType; + } + getEventRunner() { + return this.eventRegistration.getEventRunner(this); + } + toString() { + return (this.getPath().toString() + + ':' + + this.eventType + + ':' + + stringify(this.snapshot.exportVal())); + } +} +class CancelEvent { + constructor(eventRegistration, error, path) { + this.eventRegistration = eventRegistration; + this.error = error; + this.path = path; + } + getPath() { + return this.path; + } + getEventType() { + return 'cancel'; + } + getEventRunner() { + return this.eventRegistration.getEventRunner(this); + } + toString() { + return this.path.toString() + ':cancel'; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A wrapper class that converts events from the database@exp SDK to the legacy + * Database SDK. Events are not converted directly as event registration relies + * on reference comparison of the original user callback (see `matches()`) and + * relies on equality of the legacy SDK's `context` object. + */ +class CallbackContext { + constructor(snapshotCallback, cancelCallback) { + this.snapshotCallback = snapshotCallback; + this.cancelCallback = cancelCallback; + } + onValue(expDataSnapshot, previousChildName) { + this.snapshotCallback.call(null, expDataSnapshot, previousChildName); + } + onCancel(error) { + assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback'); + return this.cancelCallback.call(null, error); + } + get hasCancelCallback() { + return !!this.cancelCallback; + } + matches(other) { + return (this.snapshotCallback === other.snapshotCallback || + (this.snapshotCallback.userCallback !== undefined && + this.snapshotCallback.userCallback === + other.snapshotCallback.userCallback && + this.snapshotCallback.context === other.snapshotCallback.context)); + } +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The `onDisconnect` class allows you to write or clear data when your client + * disconnects from the Database server. These updates occur whether your + * client disconnects cleanly or not, so you can rely on them to clean up data + * even if a connection is dropped or a client crashes. + * + * The `onDisconnect` class is most commonly used to manage presence in + * applications where it is useful to detect how many clients are connected and + * when other clients disconnect. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * To avoid problems when a connection is dropped before the requests can be + * transferred to the Database server, these functions should be called before + * writing any data. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time you reconnect. + */ +class OnDisconnect { + /** @hideconstructor */ + constructor(_repo, _path) { + this._repo = _repo; + this._path = _path; + } + /** + * Cancels all previously queued `onDisconnect()` set or update events for this + * location and all children. + * + * If a write has been queued for this location via a `set()` or `update()` at a + * parent location, the write at this location will be canceled, though writes + * to sibling locations will still occur. + * + * @returns Resolves when synchronization to the server is complete. + */ + cancel() { + const deferred = new Deferred(); + repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Ensures the data at this location is deleted when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + * + * @returns Resolves when synchronization to the server is complete. + */ + remove() { + validateWritablePath('OnDisconnect.remove', this._path); + const deferred = new Deferred(); + repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Ensures the data at this location is set to the specified value when the + * client is disconnected (due to closing the browser, navigating to a new page, + * or network issues). + * + * `set()` is especially useful for implementing "presence" systems, where a + * value should be changed or cleared when a user disconnects so that they + * appear "offline" to other users. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time. + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + set(value) { + validateWritablePath('OnDisconnect.set', this._path); + validateFirebaseDataArg('OnDisconnect.set', value, this._path, false); + const deferred = new Deferred(); + repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Ensures the data at this location is set to the specified value and priority + * when the client is disconnected (due to closing the browser, navigating to a + * new page, or network issues). + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + setWithPriority(value, priority) { + validateWritablePath('OnDisconnect.setWithPriority', this._path); + validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false); + validatePriority('OnDisconnect.setWithPriority', priority, false); + const deferred = new Deferred(); + repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Writes multiple values at this location when the client is disconnected (due + * to closing the browser, navigating to a new page, or network issues). + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, "name/first") + * from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * @param values - Object containing multiple values. + * @returns Resolves when synchronization to the Database is complete. + */ + update(values) { + validateWritablePath('OnDisconnect.update', this._path); + validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false); + const deferred = new Deferred(); + repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { })); + return deferred.promise; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ +class QueryImpl { + /** + * @hideconstructor + */ + constructor(_repo, _path, _queryParams, _orderByCalled) { + this._repo = _repo; + this._path = _path; + this._queryParams = _queryParams; + this._orderByCalled = _orderByCalled; + } + get key() { + if (pathIsEmpty(this._path)) { + return null; + } + else { + return pathGetBack(this._path); + } + } + get ref() { + return new ReferenceImpl(this._repo, this._path); + } + get _queryIdentifier() { + const obj = queryParamsGetQueryObject(this._queryParams); + const id = ObjectToUniqueKey(obj); + return id === '{}' ? 'default' : id; + } + /** + * An object representation of the query parameters used by this Query. + */ + get _queryObject() { + return queryParamsGetQueryObject(this._queryParams); + } + isEqual(other) { + other = getModularInstance(other); + if (!(other instanceof QueryImpl)) { + return false; + } + const sameRepo = this._repo === other._repo; + const samePath = pathEquals(this._path, other._path); + const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier; + return sameRepo && samePath && sameQueryIdentifier; + } + toJSON() { + return this.toString(); + } + toString() { + return this._repo.toString() + pathToUrlEncodedString(this._path); + } +} +/** + * Validates that no other order by call has been made + */ +function validateNoPreviousOrderByCall(query, fnName) { + if (query._orderByCalled === true) { + throw new Error(fnName + ": You can't combine multiple orderBy calls."); + } +} +/** + * Validates start/end values for queries. + */ +function validateQueryEndpoints(params) { + let startNode = null; + let endNode = null; + if (params.hasStart()) { + startNode = params.getIndexStartValue(); + } + if (params.hasEnd()) { + endNode = params.getIndexEndValue(); + } + if (params.getIndex() === KEY_INDEX) { + const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' + + 'startAt(), endAt(), or equalTo().'; + const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' + + 'endAt(), endBefore(), or equalTo() must be a string.'; + if (params.hasStart()) { + const startName = params.getIndexStartName(); + if (startName !== MIN_NAME) { + throw new Error(tooManyArgsError); + } + else if (typeof startNode !== 'string') { + throw new Error(wrongArgTypeError); + } + } + if (params.hasEnd()) { + const endName = params.getIndexEndName(); + if (endName !== MAX_NAME) { + throw new Error(tooManyArgsError); + } + else if (typeof endNode !== 'string') { + throw new Error(wrongArgTypeError); + } + } + } + else if (params.getIndex() === PRIORITY_INDEX) { + if ((startNode != null && !isValidPriority(startNode)) || + (endNode != null && !isValidPriority(endNode))) { + throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' + + 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' + + '(null, a number, or a string).'); + } + } + else { + assert(params.getIndex() instanceof PathIndex || + params.getIndex() === VALUE_INDEX, 'unknown index type.'); + if ((startNode != null && typeof startNode === 'object') || + (endNode != null && typeof endNode === 'object')) { + throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' + + 'equalTo() cannot be an object.'); + } + } +} +/** + * Validates that limit* has been called with the correct combination of parameters + */ +function validateLimit(params) { + if (params.hasStart() && + params.hasEnd() && + params.hasLimit() && + !params.hasAnchoredLimit()) { + throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " + + 'limitToFirst() or limitToLast() instead.'); + } +} +/** + * @internal + */ +class ReferenceImpl extends QueryImpl { + /** @hideconstructor */ + constructor(repo, path) { + super(repo, path, new QueryParams(), false); + } + get parent() { + const parentPath = pathParent(this._path); + return parentPath === null + ? null + : new ReferenceImpl(this._repo, parentPath); + } + get root() { + let ref = this; + while (ref.parent !== null) { + ref = ref.parent; + } + return ref; + } +} +/** + * A `DataSnapshot` contains data from a Database location. + * + * Any time you read data from the Database, you receive the data as a + * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach + * with `on()` or `once()`. You can extract the contents of the snapshot as a + * JavaScript object by calling the `val()` method. Alternatively, you can + * traverse into the snapshot by calling `child()` to return child snapshots + * (which you could then call `val()` on). + * + * A `DataSnapshot` is an efficiently generated, immutable copy of the data at + * a Database location. It cannot be modified and will never change (to modify + * data, you always call the `set()` method on a `Reference` directly). + */ +class DataSnapshot { + /** + * @param _node - A SnapshotNode to wrap. + * @param ref - The location this snapshot came from. + * @param _index - The iteration order for this snapshot + * @hideconstructor + */ + constructor(_node, + /** + * The location of this DataSnapshot. + */ + ref, _index) { + this._node = _node; + this.ref = ref; + this._index = _index; + } + /** + * Gets the priority value of the data in this `DataSnapshot`. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data} + * ). + */ + get priority() { + // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY) + return this._node.getPriority().val(); + } + /** + * The key (last part of the path) of the location of this `DataSnapshot`. + * + * The last token in a Database location is considered its key. For example, + * "ada" is the key for the /users/ada/ node. Accessing the key on any + * `DataSnapshot` will return the key for the location that generated it. + * However, accessing the key on the root URL of a Database will return + * `null`. + */ + get key() { + return this.ref.key; + } + /** Returns the number of child properties of this `DataSnapshot`. */ + get size() { + return this._node.numChildren(); + } + /** + * Gets another `DataSnapshot` for the location at the specified relative path. + * + * Passing a relative path to the `child()` method of a DataSnapshot returns + * another `DataSnapshot` for the location at the specified relative path. The + * relative path can either be a simple child name (for example, "ada") or a + * deeper, slash-separated path (for example, "ada/name/first"). If the child + * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot` + * whose value is `null`) is returned. + * + * @param path - A relative path to the location of child data. + */ + child(path) { + const childPath = new Path(path); + const childRef = child(this.ref, path); + return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX); + } + /** + * Returns true if this `DataSnapshot` contains any data. It is slightly more + * efficient than using `snapshot.val() !== null`. + */ + exists() { + return !this._node.isEmpty(); + } + /** + * Exports the entire contents of the DataSnapshot as a JavaScript object. + * + * The `exportVal()` method is similar to `val()`, except priority information + * is included (if available), making it suitable for backing up your data. + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + exportVal() { + return this._node.val(true); + } + /** + * Enumerates the top-level children in the `IteratedDataSnapshot`. + * + * Because of the way JavaScript objects work, the ordering of data in the + * JavaScript object returned by `val()` is not guaranteed to match the + * ordering on the server nor the ordering of `onChildAdded()` events. That is + * where `forEach()` comes in handy. It guarantees the children of a + * `DataSnapshot` will be iterated in their query order. + * + * If no explicit `orderBy*()` method is used, results are returned + * ordered by key (unless priorities are used, in which case, results are + * returned by priority). + * + * @param action - A function that will be called for each child DataSnapshot. + * The callback can return true to cancel further enumeration. + * @returns true if enumeration was canceled due to your callback returning + * true. + */ + forEach(action) { + if (this._node.isLeafNode()) { + return false; + } + const childrenNode = this._node; + // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type... + return !!childrenNode.forEachChild(this._index, (key, node) => { + return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX)); + }); + } + /** + * Returns true if the specified child path has (non-null) data. + * + * @param path - A relative path to the location of a potential child. + * @returns `true` if data exists at the specified child path; else + * `false`. + */ + hasChild(path) { + const childPath = new Path(path); + return !this._node.getChild(childPath).isEmpty(); + } + /** + * Returns whether or not the `DataSnapshot` has any non-`null` child + * properties. + * + * You can use `hasChildren()` to determine if a `DataSnapshot` has any + * children. If it does, you can enumerate them using `forEach()`. If it + * doesn't, then either this snapshot contains a primitive value (which can be + * retrieved with `val()`) or it is empty (in which case, `val()` will return + * `null`). + * + * @returns true if this snapshot has any children; else false. + */ + hasChildren() { + if (this._node.isLeafNode()) { + return false; + } + else { + return !this._node.isEmpty(); + } + } + /** + * Returns a JSON-serializable representation of this object. + */ + toJSON() { + return this.exportVal(); + } + /** + * Extracts a JavaScript value from a `DataSnapshot`. + * + * Depending on the data in a `DataSnapshot`, the `val()` method may return a + * scalar type (string, number, or boolean), an array, or an object. It may + * also return null, indicating that the `DataSnapshot` is empty (contains no + * data). + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + val() { + return this._node.val(); + } +} +/** + * + * Returns a `Reference` representing the location in the Database + * corresponding to the provided path. If no path is provided, the `Reference` + * will point to the root of the Database. + * + * @param db - The database instance to obtain a reference for. + * @param path - Optional path representing the location the returned + * `Reference` will point. If not provided, the returned `Reference` will + * point to the root of the Database. + * @returns If a path is provided, a `Reference` + * pointing to the provided path. Otherwise, a `Reference` pointing to the + * root of the Database. + */ +function ref(db, path) { + db = getModularInstance(db); + db._checkNotDeleted('ref'); + return path !== undefined ? child(db._root, path) : db._root; +} +/** + * Returns a `Reference` representing the location in the Database + * corresponding to the provided Firebase URL. + * + * An exception is thrown if the URL is not a valid Firebase Database URL or it + * has a different domain than the current `Database` instance. + * + * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored + * and are not applied to the returned `Reference`. + * + * @param db - The database instance to obtain a reference for. + * @param url - The Firebase URL at which the returned `Reference` will + * point. + * @returns A `Reference` pointing to the provided + * Firebase URL. + */ +function refFromURL(db, url) { + db = getModularInstance(db); + db._checkNotDeleted('refFromURL'); + const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin); + validateUrl('refFromURL', parsedURL); + const repoInfo = parsedURL.repoInfo; + if (!db._repo.repoInfo_.isCustomHost() && + repoInfo.host !== db._repo.repoInfo_.host) { + fatal('refFromURL' + + ': Host name does not match the current database: ' + + '(found ' + + repoInfo.host + + ' but expected ' + + db._repo.repoInfo_.host + + ')'); + } + return ref(db, parsedURL.path.toString()); +} +/** + * Gets a `Reference` for the location at the specified relative path. + * + * The relative path can either be a simple child name (for example, "ada") or + * a deeper slash-separated path (for example, "ada/name/first"). + * + * @param parent - The parent location. + * @param path - A relative path from this location to the desired child + * location. + * @returns The specified child location. + */ +function child(parent, path) { + parent = getModularInstance(parent); + if (pathGetFront(parent._path) === null) { + validateRootPathString('child', 'path', path, false); + } + else { + validatePathString('child', 'path', path, false); + } + return new ReferenceImpl(parent._repo, pathChild(parent._path, path)); +} +/** + * Returns an `OnDisconnect` object - see + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information on how to use it. + * + * @param ref - The reference to add OnDisconnect triggers for. + */ +function onDisconnect(ref) { + ref = getModularInstance(ref); + return new OnDisconnect(ref._repo, ref._path); +} +/** + * Generates a new child location using a unique key and returns its + * `Reference`. + * + * This is the most common pattern for adding data to a collection of items. + * + * If you provide a value to `push()`, the value is written to the + * generated location. If you don't pass a value, nothing is written to the + * database and the child remains empty (but you can use the `Reference` + * elsewhere). + * + * The unique keys generated by `push()` are ordered by the current time, so the + * resulting list of items is chronologically sorted. The keys are also + * designed to be unguessable (they contain 72 random bits of entropy). + * + * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}. + * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}. + * + * @param parent - The parent location. + * @param value - Optional value to be written at the generated location. + * @returns Combined `Promise` and `Reference`; resolves when write is complete, + * but can be used immediately as the `Reference` to the child location. + */ +function push(parent, value) { + parent = getModularInstance(parent); + validateWritablePath('push', parent._path); + validateFirebaseDataArg('push', value, parent._path, true); + const now = repoServerTime(parent._repo); + const name = nextPushId(now); + // push() returns a ThennableReference whose promise is fulfilled with a + // regular Reference. We use child() to create handles to two different + // references. The first is turned into a ThennableReference below by adding + // then() and catch() methods and is used as the return value of push(). The + // second remains a regular Reference and is used as the fulfilled value of + // the first ThennableReference. + const thenablePushRef = child(parent, name); + const pushRef = child(parent, name); + let promise; + if (value != null) { + promise = set(pushRef, value).then(() => pushRef); + } + else { + promise = Promise.resolve(pushRef); + } + thenablePushRef.then = promise.then.bind(promise); + thenablePushRef.catch = promise.then.bind(promise, undefined); + return thenablePushRef; +} +/** + * Removes the data at this Database location. + * + * Any data at child locations will also be deleted. + * + * The effect of the remove will be visible immediately and the corresponding + * event 'value' will be triggered. Synchronization of the remove to the + * Firebase servers will also be started, and the returned Promise will resolve + * when complete. If provided, the onComplete callback will be called + * asynchronously after synchronization has finished. + * + * @param ref - The location to remove. + * @returns Resolves when remove on server is complete. + */ +function remove(ref) { + validateWritablePath('remove', ref._path); + return set(ref, null); +} +/** + * Writes data to this Database location. + * + * This will overwrite any data at this location and all child locations. + * + * The effect of the write will be visible immediately, and the corresponding + * events ("value", "child_added", etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * Passing `null` for the new value is equivalent to calling `remove()`; namely, + * all data at this location and all child locations will be deleted. + * + * `set()` will remove any priority stored at this location, so if priority is + * meant to be preserved, you need to use `setWithPriority()` instead. + * + * Note that modifying data with `set()` will cancel any pending transactions + * at that location, so extreme care should be taken if mixing `set()` and + * `transaction()` to modify the same data. + * + * A single `set()` will generate a single "value" event at the location where + * the `set()` was performed. + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @returns Resolves when write to server is complete. + */ +function set(ref, value) { + ref = getModularInstance(ref); + validateWritablePath('set', ref._path); + validateFirebaseDataArg('set', value, ref._path, false); + const deferred = new Deferred(); + repoSetWithPriority(ref._repo, ref._path, value, + /*priority=*/ null, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Sets a priority for the data at this Database location. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +function setPriority(ref, priority) { + ref = getModularInstance(ref); + validateWritablePath('setPriority', ref._path); + validatePriority('setPriority', priority, false); + const deferred = new Deferred(); + repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Writes data the Database location. Like `set()` but also specifies the + * priority for that data. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +function setWithPriority(ref, value, priority) { + validateWritablePath('setWithPriority', ref._path); + validateFirebaseDataArg('setWithPriority', value, ref._path, false); + validatePriority('setWithPriority', priority, false); + if (ref.key === '.length' || ref.key === '.keys') { + throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.'; + } + const deferred = new Deferred(); + repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Writes multiple values to the Database at once. + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, + * "name/first") from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * The effect of the write will be visible immediately, and the corresponding + * events ('value', 'child_added', etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * A single `update()` will generate a single "value" event at the location + * where the `update()` was performed, regardless of how many children were + * modified. + * + * Note that modifying data with `update()` will cancel any pending + * transactions at that location, so extreme care should be taken if mixing + * `update()` and `transaction()` to modify the same data. + * + * Passing `null` to `update()` will remove the data at this location. + * + * See + * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}. + * + * @param ref - The location to write to. + * @param values - Object containing multiple values. + * @returns Resolves when update on server is complete. + */ +function update(ref, values) { + validateFirebaseMergeDataArg('update', values, ref._path, false); + const deferred = new Deferred(); + repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Gets the most up-to-date result for this query. + * + * @param query - The query to run. + * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is + * available, or rejects if the client is unable to return a value (e.g., if the + * server is unreachable and there is nothing cached). + */ +function get(query) { + query = getModularInstance(query); + const callbackContext = new CallbackContext(() => { }); + const container = new ValueEventRegistration(callbackContext); + return repoGetValue(query._repo, query, container).then(node => { + return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex()); + }); +} +/** + * Represents registration for 'value' events. + */ +class ValueEventRegistration { + constructor(callbackContext) { + this.callbackContext = callbackContext; + } + respondsTo(eventType) { + return eventType === 'value'; + } + createEvent(change, query) { + const index = query._queryParams.getIndex(); + return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index)); + } + getEventRunner(eventData) { + if (eventData.getEventType() === 'cancel') { + return () => this.callbackContext.onCancel(eventData.error); + } + else { + return () => this.callbackContext.onValue(eventData.snapshot, null); + } + } + createCancelEvent(error, path) { + if (this.callbackContext.hasCancelCallback) { + return new CancelEvent(this, error, path); + } + else { + return null; + } + } + matches(other) { + if (!(other instanceof ValueEventRegistration)) { + return false; + } + else if (!other.callbackContext || !this.callbackContext) { + // If no callback specified, we consider it to match any callback. + return true; + } + else { + return other.callbackContext.matches(this.callbackContext); + } + } + hasAnyCallback() { + return this.callbackContext !== null; + } +} +/** + * Represents the registration of a child_x event. + */ +class ChildEventRegistration { + constructor(eventType, callbackContext) { + this.eventType = eventType; + this.callbackContext = callbackContext; + } + respondsTo(eventType) { + let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType; + eventToCheck = + eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck; + return this.eventType === eventToCheck; + } + createCancelEvent(error, path) { + if (this.callbackContext.hasCancelCallback) { + return new CancelEvent(this, error, path); + } + else { + return null; + } + } + createEvent(change, query) { + assert(change.childName != null, 'Child events should have a childName.'); + const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName); + const index = query._queryParams.getIndex(); + return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName); + } + getEventRunner(eventData) { + if (eventData.getEventType() === 'cancel') { + return () => this.callbackContext.onCancel(eventData.error); + } + else { + return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName); + } + } + matches(other) { + if (other instanceof ChildEventRegistration) { + return (this.eventType === other.eventType && + (!this.callbackContext || + !other.callbackContext || + this.callbackContext.matches(other.callbackContext))); + } + return false; + } + hasAnyCallback() { + return !!this.callbackContext; + } +} +function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) { + let cancelCallback; + if (typeof cancelCallbackOrListenOptions === 'object') { + cancelCallback = undefined; + options = cancelCallbackOrListenOptions; + } + if (typeof cancelCallbackOrListenOptions === 'function') { + cancelCallback = cancelCallbackOrListenOptions; + } + if (options && options.onlyOnce) { + const userCallback = callback; + const onceCallback = (dataSnapshot, previousChildName) => { + repoRemoveEventCallbackForQuery(query._repo, query, container); + userCallback(dataSnapshot, previousChildName); + }; + onceCallback.userCallback = callback.userCallback; + onceCallback.context = callback.context; + callback = onceCallback; + } + const callbackContext = new CallbackContext(callback, cancelCallback || undefined); + const container = eventType === 'value' + ? new ValueEventRegistration(callbackContext) + : new ChildEventRegistration(eventType, callbackContext); + repoAddEventCallbackForQuery(query._repo, query, container); + return () => repoRemoveEventCallbackForQuery(query._repo, query, container); +} +function onValue(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options); +} +function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options); +} +function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options); +} +function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options); +} +function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options); +} +/** + * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener. + * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from + * the respective `on*` callbacks. + * + * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener + * will not automatically remove listeners registered on child nodes, `off()` + * must also be called on any child listeners to remove the callback. + * + * If a callback is not specified, all callbacks for the specified eventType + * will be removed. Similarly, if no eventType is specified, all callbacks + * for the `Reference` will be removed. + * + * Individual listeners can also be removed by invoking their unsubscribe + * callbacks. + * + * @param query - The query that the listener was registered with. + * @param eventType - One of the following strings: "value", "child_added", + * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks + * for the `Reference` will be removed. + * @param callback - The callback function that was passed to `on()` or + * `undefined` to remove all callbacks. + */ +function off(query, eventType, callback) { + let container = null; + const expCallback = callback ? new CallbackContext(callback) : null; + if (eventType === 'value') { + container = new ValueEventRegistration(expCallback); + } + else if (eventType) { + container = new ChildEventRegistration(eventType, expCallback); + } + repoRemoveEventCallbackForQuery(query._repo, query, container); +} +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Database query. `QueryConstraint`s are created by invoking {@link endAt}, + * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link + * limitToFirst}, {@link limitToLast}, {@link orderByChild}, + * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} , + * {@link orderByValue} or {@link equalTo} and + * can then be passed to {@link query} to create a new query instance that + * also contains this `QueryConstraint`. + */ +class QueryConstraint { +} +class QueryEndAtConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'endAt'; + } + _apply(query) { + validateFirebaseDataArg('endAt', this._value, query._path, true); + const newParams = queryParamsEndAt(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasEnd()) { + throw new Error('endAt: Starting point was already set (by another call to endAt, ' + + 'endBefore or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified ending point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name less than or equal + * to the specified key. + * + * You can read more about `endAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to end at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end at, among the children with the previously + * specified priority. This argument is only allowed if ordering by child, + * value, or priority. + */ +function endAt(value, key) { + validateKey('endAt', 'key', key, true); + return new QueryEndAtConstraint(value, key); +} +class QueryEndBeforeConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'endBefore'; + } + _apply(query) { + validateFirebaseDataArg('endBefore', this._value, query._path, false); + const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasEnd()) { + throw new Error('endBefore: Starting point was already set (by another call to endAt, ' + + 'endBefore or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified ending point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is exclusive. If only a value is provided, children + * with a value less than the specified value will be included in the query. + * If a key is specified, then children must have a value less than or equal + * to the specified value and a key name less than the specified key. + * + * @param value - The value to end before. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end before, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +function endBefore(value, key) { + validateKey('endBefore', 'key', key, true); + return new QueryEndBeforeConstraint(value, key); +} +class QueryStartAtConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'startAt'; + } + _apply(query) { + validateFirebaseDataArg('startAt', this._value, query._path, true); + const newParams = queryParamsStartAt(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasStart()) { + throw new Error('startAt: Starting point was already set (by another call to startAt, ' + + 'startBefore or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified starting point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name greater than or + * equal to the specified key. + * + * You can read more about `startAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to start at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at. This argument is only allowed if + * ordering by child, value, or priority. + */ +function startAt(value = null, key) { + validateKey('startAt', 'key', key, true); + return new QueryStartAtConstraint(value, key); +} +class QueryStartAfterConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'startAfter'; + } + _apply(query) { + validateFirebaseDataArg('startAfter', this._value, query._path, false); + const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasStart()) { + throw new Error('startAfter: Starting point was already set (by another call to startAt, ' + + 'startAfter, or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified starting point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is exclusive. If only a value is provided, children + * with a value greater than the specified value will be included in the query. + * If a key is specified, then children must have a value greater than or equal + * to the specified value and a a key name greater than the specified key. + * + * @param value - The value to start after. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start after. This argument is only allowed if + * ordering by child, value, or priority. + */ +function startAfter(value, key) { + validateKey('startAfter', 'key', key, true); + return new QueryStartAfterConstraint(value, key); +} +class QueryLimitToFirstConstraint extends QueryConstraint { + constructor(_limit) { + super(); + this._limit = _limit; + this.type = 'limitToFirst'; + } + _apply(query) { + if (query._queryParams.hasLimit()) { + throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' + + 'or limitToLast).'); + } + return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled); + } +} +/** + * Creates a new `QueryConstraint` that if limited to the first specific number + * of children. + * + * The `limitToFirst()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the first 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToFirst()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +function limitToFirst(limit) { + if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) { + throw new Error('limitToFirst: First argument must be a positive integer.'); + } + return new QueryLimitToFirstConstraint(limit); +} +class QueryLimitToLastConstraint extends QueryConstraint { + constructor(_limit) { + super(); + this._limit = _limit; + this.type = 'limitToLast'; + } + _apply(query) { + if (query._queryParams.hasLimit()) { + throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' + + 'or limitToLast).'); + } + return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled); + } +} +/** + * Creates a new `QueryConstraint` that is limited to return only the last + * specified number of children. + * + * The `limitToLast()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the last 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToLast()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +function limitToLast(limit) { + if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) { + throw new Error('limitToLast: First argument must be a positive integer.'); + } + return new QueryLimitToLastConstraint(limit); +} +class QueryOrderByChildConstraint extends QueryConstraint { + constructor(_path) { + super(); + this._path = _path; + this.type = 'orderByChild'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByChild'); + const parsedPath = new Path(this._path); + if (pathIsEmpty(parsedPath)) { + throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.'); + } + const index = new PathIndex(parsedPath); + const newParams = queryParamsOrderBy(query._queryParams, index); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by the specified child key. + * + * Queries can only order by one key at a time. Calling `orderByChild()` + * multiple times on the same query is an error. + * + * Firebase queries allow you to order your data by any child key on the fly. + * However, if you know in advance what your indexes will be, you can define + * them via the .indexOn rule in your Security Rules for better performance. See + * the{@link https://firebase.google.com/docs/database/security/indexing-data} + * rule for more information. + * + * You can read more about `orderByChild()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + * + * @param path - The path to order by. + */ +function orderByChild(path) { + if (path === '$key') { + throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.'); + } + else if (path === '$priority') { + throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.'); + } + else if (path === '$value') { + throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.'); + } + validatePathString('orderByChild', 'path', path, false); + return new QueryOrderByChildConstraint(path); +} +class QueryOrderByKeyConstraint extends QueryConstraint { + constructor() { + super(...arguments); + this.type = 'orderByKey'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByKey'); + const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by the key. + * + * Sorts the results of a query by their (ascending) key values. + * + * You can read more about `orderByKey()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +function orderByKey() { + return new QueryOrderByKeyConstraint(); +} +class QueryOrderByPriorityConstraint extends QueryConstraint { + constructor() { + super(...arguments); + this.type = 'orderByPriority'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByPriority'); + const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by priority. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data} + * for alternatives to priority. + */ +function orderByPriority() { + return new QueryOrderByPriorityConstraint(); +} +class QueryOrderByValueConstraint extends QueryConstraint { + constructor() { + super(...arguments); + this.type = 'orderByValue'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByValue'); + const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by value. + * + * If the children of a query are all scalar values (string, number, or + * boolean), you can order the results by their (ascending) values. + * + * You can read more about `orderByValue()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +function orderByValue() { + return new QueryOrderByValueConstraint(); +} +class QueryEqualToValueConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'equalTo'; + } + _apply(query) { + validateFirebaseDataArg('equalTo', this._value, query._path, false); + if (query._queryParams.hasStart()) { + throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' + + 'equalTo).'); + } + if (query._queryParams.hasEnd()) { + throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' + + 'equalTo).'); + } + return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query)); + } +} +/** + * Creates a `QueryConstraint` that includes children that match the specified + * value. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The optional key argument can be used to further limit the range of the + * query. If it is specified, then children that have exactly the specified + * value must also have exactly the specified key as their key name. This can be + * used to filter result sets with many matches for the same value. + * + * You can read more about `equalTo()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to match for. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +function equalTo(value, key) { + validateKey('equalTo', 'key', key, true); + return new QueryEqualToValueConstraint(value, key); +} +/** + * Creates a new immutable instance of `Query` that is extended to also include + * additional query constraints. + * + * @param query - The Query instance to use as a base for the new constraints. + * @param queryConstraints - The list of `QueryConstraint`s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +function query(query, ...queryConstraints) { + let queryImpl = getModularInstance(query); + for (const constraint of queryConstraints) { + queryImpl = constraint._apply(queryImpl); + } + return queryImpl; +} +/** + * Define reference constructor in various modules + * + * We are doing this here to avoid several circular + * dependency issues + */ +syncPointSetReferenceConstructor(ReferenceImpl); +syncTreeSetReferenceConstructor(ReferenceImpl); + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This variable is also defined in the firebase Node.js Admin SDK. Before + * modifying this definition, consult the definition in: + * + * https://github.com/firebase/firebase-admin-node + * + * and make sure the two are consistent. + */ +const FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST'; +/** + * Creates and caches `Repo` instances. + */ +const repos = {}; +/** + * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes). + */ +let useRestClient = false; +/** + * Update an existing `Repo` in place to point to a new host/port. + */ +function repoManagerApplyEmulatorSettings(repo, hostAndPort, emulatorOptions, tokenProvider) { + const portIndex = hostAndPort.lastIndexOf(':'); + const host = hostAndPort.substring(0, portIndex); + const useSsl = isCloudWorkstation(host); + repo.repoInfo_ = new RepoInfo(hostAndPort, + /* secure= */ useSsl, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams, + /*isUsingEmulator=*/ true, emulatorOptions); + if (tokenProvider) { + repo.authTokenProvider_ = tokenProvider; + } +} +/** + * This function should only ever be called to CREATE a new database instance. + * @internal + */ +function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) { + let dbUrl = url || app.options.databaseURL; + if (dbUrl === undefined) { + if (!app.options.projectId) { + fatal("Can't determine Firebase Database URL. Be sure to include " + + ' a Project ID when calling firebase.initializeApp().'); + } + log('Using default host for project ', app.options.projectId); + dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`; + } + let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin); + let repoInfo = parsedUrl.repoInfo; + let isEmulator; + let dbEmulatorHost = undefined; + if (typeof process !== 'undefined' && process.env) { + dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR]; + } + if (dbEmulatorHost) { + isEmulator = true; + dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`; + parsedUrl = parseRepoInfo(dbUrl, nodeAdmin); + repoInfo = parsedUrl.repoInfo; + } + else { + isEmulator = !parsedUrl.repoInfo.secure; + } + const authTokenProvider = nodeAdmin && isEmulator + ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER) + : new FirebaseAuthTokenProvider(app.name, app.options, authProvider); + validateUrl('Invalid Firebase Database URL', parsedUrl); + if (!pathIsEmpty(parsedUrl.path)) { + fatal('Database URL must point to the root of a Firebase Database ' + + '(not including a child path).'); + } + const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app, appCheckProvider)); + return new Database(repo, app); +} +/** + * Remove the repo and make sure it is disconnected. + * + */ +function repoManagerDeleteRepo(repo, appName) { + const appRepos = repos[appName]; + // This should never happen... + if (!appRepos || appRepos[repo.key] !== repo) { + fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`); + } + repoInterrupt(repo); + delete appRepos[repo.key]; +} +/** + * Ensures a repo doesn't already exist and then creates one using the + * provided app. + * + * @param repoInfo - The metadata about the Repo + * @returns The Repo object for the specified server / repoName. + */ +function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) { + let appRepos = repos[app.name]; + if (!appRepos) { + appRepos = {}; + repos[app.name] = appRepos; + } + let repo = appRepos[repoInfo.toURLString()]; + if (repo) { + fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.'); + } + repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider); + appRepos[repoInfo.toURLString()] = repo; + return repo; +} +/** + * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos. + */ +function repoManagerForceRestClient(forceRestClient) { + useRestClient = forceRestClient; +} +/** + * Class representing a Firebase Realtime Database. + */ +class Database { + /** @hideconstructor */ + constructor(_repoInternal, + /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */ + app) { + this._repoInternal = _repoInternal; + this.app = app; + /** Represents a `Database` instance. */ + this['type'] = 'database'; + /** Track if the instance has been used (root or repo accessed) */ + this._instanceStarted = false; + } + get _repo() { + if (!this._instanceStarted) { + repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']); + this._instanceStarted = true; + } + return this._repoInternal; + } + get _root() { + if (!this._rootInternal) { + this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath()); + } + return this._rootInternal; + } + _delete() { + if (this._rootInternal !== null) { + repoManagerDeleteRepo(this._repo, this.app.name); + this._repoInternal = null; + this._rootInternal = null; + } + return Promise.resolve(); + } + _checkNotDeleted(apiName) { + if (this._rootInternal === null) { + fatal('Cannot call ' + apiName + ' on a deleted database.'); + } + } +} +function checkTransportInit() { + if (TransportManager.IS_TRANSPORT_INITIALIZED) { + warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener'); + } +} +/** + * Force the use of websockets instead of longPolling. + */ +function forceWebSockets() { + checkTransportInit(); + BrowserPollConnection.forceDisallow(); +} +/** + * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL. + */ +function forceLongPolling() { + checkTransportInit(); + WebSocketConnection.forceDisallow(); + BrowserPollConnection.forceAllow(); +} +/** + * Returns the instance of the Realtime Database SDK that is associated with the provided + * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if + * no instance exists or if the existing instance uses a custom database URL. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime + * Database instance is associated with. + * @param url - The URL of the Realtime Database instance to connect to. If not + * provided, the SDK connects to the default instance of the Firebase App. + * @returns The `Database` instance of the provided app. + */ +function getDatabase(app = getApp(), url) { + const db = _getProvider(app, 'database').getImmediate({ + identifier: url + }); + if (!db._instanceStarted) { + const emulator = getDefaultEmulatorHostnameAndPort('database'); + if (emulator) { + connectDatabaseEmulator(db, ...emulator); + } + } + return db; +} +/** + * Modify the provided instance to communicate with the Realtime Database + * emulator. + * + *

Note: This method must be called before performing any other operation. + * + * @param db - The instance to modify. + * @param host - The emulator host (ex: localhost) + * @param port - The emulator port (ex: 8080) + * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules + */ +function connectDatabaseEmulator(db, host, port, options = {}) { + db = getModularInstance(db); + db._checkNotDeleted('useEmulator'); + const hostAndPort = `${host}:${port}`; + const repo = db._repoInternal; + if (db._instanceStarted) { + // If the instance has already been started, then silenty fail if this function is called again + // with the same parameters. If the parameters differ then assert. + if (hostAndPort === db._repoInternal.repoInfo_.host && + deepEqual(options, repo.repoInfo_.emulatorOptions)) { + return; + } + fatal('connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.'); + } + let tokenProvider = undefined; + if (repo.repoInfo_.nodeAdmin) { + if (options.mockUserToken) { + fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'); + } + tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER); + } + else if (options.mockUserToken) { + const token = typeof options.mockUserToken === 'string' + ? options.mockUserToken + : createMockUserToken(options.mockUserToken, db.app.options.projectId); + tokenProvider = new EmulatorTokenProvider(token); + } + // Workaround to get cookies in Firebase Studio + if (isCloudWorkstation(host)) { + void pingServer(host); + updateEmulatorBanner('Database', true); + } + // Modify the repo to apply emulator settings + repoManagerApplyEmulatorSettings(repo, hostAndPort, options, tokenProvider); +} +/** + * Disconnects from the server (all Database operations will be completed + * offline). + * + * The client automatically maintains a persistent connection to the Database + * server, which will remain active indefinitely and reconnect when + * disconnected. However, the `goOffline()` and `goOnline()` methods may be used + * to control the client connection in cases where a persistent connection is + * undesirable. + * + * While offline, the client will no longer receive data updates from the + * Database. However, all Database operations performed locally will continue to + * immediately fire events, allowing your application to continue behaving + * normally. Additionally, each operation performed locally will automatically + * be queued and retried upon reconnection to the Database server. + * + * To reconnect to the Database and begin receiving remote events, see + * `goOnline()`. + * + * @param db - The instance to disconnect. + */ +function goOffline(db) { + db = getModularInstance(db); + db._checkNotDeleted('goOffline'); + repoInterrupt(db._repo); +} +/** + * Reconnects to the server and synchronizes the offline Database state + * with the server state. + * + * This method should be used after disabling the active connection with + * `goOffline()`. Once reconnected, the client will transmit the proper data + * and fire the appropriate events so that your client "catches up" + * automatically. + * + * @param db - The instance to reconnect. + */ +function goOnline(db) { + db = getModularInstance(db); + db._checkNotDeleted('goOnline'); + repoResume(db._repo); +} +function enableLogging(logger, persistent) { + enableLogging$1(logger, persistent); +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function registerDatabase(variant) { + setSDKVersion(SDK_VERSION$1); + _registerComponent(new Component('database', (container, { instanceIdentifier: url }) => { + const app = container.getProvider('app').getImmediate(); + const authProvider = container.getProvider('auth-internal'); + const appCheckProvider = container.getProvider('app-check-internal'); + return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url); + }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true)); + registerVersion(name, version, variant); + // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation + registerVersion(name, version, 'esm2020'); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const SERVER_TIMESTAMP = { + '.sv': 'timestamp' +}; +/** + * Returns a placeholder value for auto-populating the current timestamp (time + * since the Unix epoch, in milliseconds) as determined by the Firebase + * servers. + */ +function serverTimestamp() { + return SERVER_TIMESTAMP; +} +/** + * Returns a placeholder value that can be used to atomically increment the + * current database value by the provided delta. + * + * @param delta - the amount to modify the current value atomically. + * @returns A placeholder value for modifying data atomically server-side. + */ +function increment(delta) { + return { + '.sv': { + 'increment': delta + } + }; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A type for the resolve value of {@link runTransaction}. + */ +class TransactionResult { + /** @hideconstructor */ + constructor( + /** Whether the transaction was successfully committed. */ + committed, + /** The resulting data snapshot. */ + snapshot) { + this.committed = committed; + this.snapshot = snapshot; + } + /** Returns a JSON-serializable representation of this object. */ + toJSON() { + return { committed: this.committed, snapshot: this.snapshot.toJSON() }; + } +} +/** + * Atomically modifies the data at this location. + * + * Atomically modify the data at this location. Unlike a normal `set()`, which + * just overwrites the data regardless of its previous value, `runTransaction()` is + * used to modify the existing value to a new value, ensuring there are no + * conflicts with other clients writing to the same location at the same time. + * + * To accomplish this, you pass `runTransaction()` an update function which is + * used to transform the current value into a new value. If another client + * writes to the location before your new value is successfully written, your + * update function will be called again with the new current value, and the + * write will be retried. This will happen repeatedly until your write succeeds + * without conflict or you abort the transaction by not returning a value from + * your update function. + * + * Note: Modifying data with `set()` will cancel any pending transactions at + * that location, so extreme care should be taken if mixing `set()` and + * `runTransaction()` to update the same data. + * + * Note: When using transactions with Security and Firebase Rules in place, be + * aware that a client needs `.read` access in addition to `.write` access in + * order to perform a transaction. This is because the client-side nature of + * transactions requires the client to read the data in order to transactionally + * update it. + * + * @param ref - The location to atomically modify. + * @param transactionUpdate - A developer-supplied function which will be passed + * the current data stored at this location (as a JavaScript object). The + * function should return the new value it would like written (as a JavaScript + * object). If `undefined` is returned (i.e. you return with no arguments) the + * transaction will be aborted and the data at this location will not be + * modified. + * @param options - An options object to configure transactions. + * @returns A `Promise` that can optionally be used instead of the `onComplete` + * callback to handle success and failure. + */ +function runTransaction(ref, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +transactionUpdate, options) { + ref = getModularInstance(ref); + validateWritablePath('Reference.transaction', ref._path); + if (ref.key === '.length' || ref.key === '.keys') { + throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.'); + } + const applyLocally = options?.applyLocally ?? true; + const deferred = new Deferred(); + const promiseComplete = (error, committed, node) => { + let dataSnapshot = null; + if (error) { + deferred.reject(error); + } + else { + dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX); + deferred.resolve(new TransactionResult(committed, dataSnapshot)); + } + }; + // Add a watch to make sure we get server updates. + const unwatcher = onValue(ref, () => { }); + repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally); + return deferred.promise; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +PersistentConnection; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +PersistentConnection.prototype.simpleListen = function (pathString, onComplete) { + this.sendRequest('q', { p: pathString }, onComplete); +}; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +PersistentConnection.prototype.echo = function (data, onEcho) { + this.sendRequest('echo', { d: data }, onEcho); +}; +// RealTimeConnection properties that we use in tests. +Connection; +/** + * @internal + */ +const hijackHash = function (newHash) { + const oldPut = PersistentConnection.prototype.put; + PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) { + if (hash !== undefined) { + hash = newHash(); + } + oldPut.call(this, pathString, data, onComplete, hash); + }; + return function () { + PersistentConnection.prototype.put = oldPut; + }; +}; +RepoInfo; +/** + * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection. + * @internal + */ +const forceRestClient = function (forceRestClient) { + repoManagerForceRestClient(forceRestClient); +}; + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Used by console to create a database based on the app, + * passed database URL and a custom auth implementation. + * @internal + * @param app - A valid FirebaseApp-like object + * @param url - A valid Firebase databaseURL + * @param version - custom version e.g. firebase-admin version + * @param customAppCheckImpl - custom app check implementation + * @param customAuthImpl - custom auth implementation + */ +function _initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, nodeAdmin = false }) { + setSDKVersion(version); + /** + * ComponentContainer('database-standalone') is just a placeholder that doesn't perform + * any actual function. + */ + const componentContainer = new ComponentContainer('database-standalone'); + const authProvider = new Provider('auth-internal', componentContainer); + let appCheckProvider; + if (customAppCheckImpl) { + appCheckProvider = new Provider('app-check-internal', componentContainer); + appCheckProvider.setComponent(new Component('app-check-internal', () => customAppCheckImpl, "PRIVATE" /* ComponentType.PRIVATE */)); + } + authProvider.setComponent(new Component('auth-internal', () => customAuthImpl, "PRIVATE" /* ComponentType.PRIVATE */)); + return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin); +} + +/** + * Firebase Realtime Database + * + * @packageDocumentation + */ +registerDatabase(); + +export { DataSnapshot, Database, OnDisconnect, QueryConstraint, TransactionResult, QueryImpl as _QueryImpl, QueryParams as _QueryParams, ReferenceImpl as _ReferenceImpl, forceRestClient as _TEST_ACCESS_forceRestClient, hijackHash as _TEST_ACCESS_hijackHash, _initStandalone, repoManagerDatabaseFromApp as _repoManagerDatabaseFromApp, setSDKVersion as _setSDKVersion, validatePathString as _validatePathString, validateWritablePath as _validateWritablePath, child, connectDatabaseEmulator, enableLogging, endAt, endBefore, equalTo, forceLongPolling, forceWebSockets, get, getDatabase, goOffline, goOnline, increment, limitToFirst, limitToLast, off, onChildAdded, onChildChanged, onChildMoved, onChildRemoved, onDisconnect, onValue, orderByChild, orderByKey, orderByPriority, orderByValue, push, query, ref, refFromURL, remove, runTransaction, serverTimestamp, set, setPriority, setWithPriority, startAfter, startAt, update }; +//# sourceMappingURL=index.esm.js.map diff --git a/node_modules/@firebase/database/dist/index.esm.js.map b/node_modules/@firebase/database/dist/index.esm.js.map new file mode 100644 index 0000000..ba35777 --- /dev/null +++ b/node_modules/@firebase/database/dist/index.esm.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.esm.js","sources":["../src/core/version.ts","../src/core/storage/DOMStorageWrapper.ts","../src/core/storage/MemoryStorage.ts","../src/core/storage/storage.ts","../src/core/util/util.ts","../src/core/AppCheckTokenProvider.ts","../src/core/AuthTokenProvider.ts","../src/realtime/Constants.ts","../src/core/RepoInfo.ts","../src/core/stats/StatsCollection.ts","../src/core/stats/StatsManager.ts","../src/realtime/polling/PacketReceiver.ts","../src/realtime/BrowserPollConnection.ts","../src/realtime/WebSocketConnection.ts","../src/realtime/TransportManager.ts","../src/realtime/Connection.ts","../src/core/ServerActions.ts","../src/core/util/EventEmitter.ts","../src/core/util/OnlineMonitor.ts","../src/core/util/Path.ts","../src/core/util/VisibilityMonitor.ts","../src/core/PersistentConnection.ts","../src/core/snap/Node.ts","../src/core/snap/indexes/Index.ts","../src/core/snap/indexes/KeyIndex.ts","../src/core/util/SortedMap.ts","../src/core/snap/comparators.ts","../src/core/snap/snap.ts","../src/core/snap/LeafNode.ts","../src/core/snap/indexes/PriorityIndex.ts","../src/core/snap/childSet.ts","../src/core/snap/IndexMap.ts","../src/core/snap/ChildrenNode.ts","../src/core/snap/nodeFromJSON.ts","../src/core/snap/indexes/PathIndex.ts","../src/core/snap/indexes/ValueIndex.ts","../src/core/view/Change.ts","../src/core/view/filter/IndexedFilter.ts","../src/core/view/filter/RangedFilter.ts","../src/core/view/filter/LimitedFilter.ts","../src/core/view/QueryParams.ts","../src/core/ReadonlyRestClient.ts","../src/core/SnapshotHolder.ts","../src/core/SparseSnapshotTree.ts","../src/core/stats/StatsListener.ts","../src/core/stats/StatsReporter.ts","../src/core/operation/Operation.ts","../src/core/operation/AckUserWrite.ts","../src/core/operation/ListenComplete.ts","../src/core/operation/Overwrite.ts","../src/core/operation/Merge.ts","../src/core/view/CacheNode.ts","../src/core/view/EventGenerator.ts","../src/core/view/ViewCache.ts","../src/core/util/ImmutableTree.ts","../src/core/CompoundWrite.ts","../src/core/WriteTree.ts","../src/core/view/ChildChangeAccumulator.ts","../src/core/view/CompleteChildSource.ts","../src/core/view/ViewProcessor.ts","../src/core/view/View.ts","../src/core/SyncPoint.ts","../src/core/SyncTree.ts","../src/core/util/ServerValues.ts","../src/core/util/Tree.ts","../src/core/util/validation.ts","../src/core/view/EventQueue.ts","../src/core/Repo.ts","../src/core/util/libs/parser.ts","../src/core/util/NextPushId.ts","../src/core/view/Event.ts","../src/core/view/EventRegistration.ts","../src/api/OnDisconnect.ts","../src/api/Reference_impl.ts","../src/api/Database.ts","../src/register.ts","../src/api/ServerValue.ts","../src/api/Transaction.ts","../src/api/test_access.ts","../src/internal/index.ts","../src/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nexport let SDK_VERSION = '';\n\n/**\n * SDK_VERSION should be set before any database instance is created\n * @internal\n */\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { jsonEval, stringify } from '@firebase/util';\n\n/**\n * Wraps a DOM Storage object and:\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\n *\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\n * and one for localStorage.\n *\n */\nexport class DOMStorageWrapper {\n // Use a prefix to avoid collisions with other stuff saved by the app.\n private prefix_ = 'firebase:';\n\n /**\n * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)\n */\n constructor(private domStorage_: Storage) {}\n\n /**\n * @param key - The key to save the value under\n * @param value - The value being stored, or null to remove the key.\n */\n set(key: string, value: unknown | null) {\n if (value == null) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n } else {\n this.domStorage_.setItem(this.prefixedName_(key), stringify(value));\n }\n }\n\n /**\n * @returns The value that was stored under this key, or null\n */\n get(key: string): unknown {\n const storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n if (storedVal == null) {\n return null;\n } else {\n return jsonEval(storedVal);\n }\n }\n\n remove(key: string) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n\n isInMemoryStorage: boolean;\n\n prefixedName_(name: string): string {\n return this.prefix_ + name;\n }\n\n toString(): string {\n return this.domStorage_.toString();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains } from '@firebase/util';\n\n/**\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\n * (TODO: create interface for both to implement).\n */\nexport class MemoryStorage {\n private cache_: { [k: string]: unknown } = {};\n\n set(key: string, value: unknown | null) {\n if (value == null) {\n delete this.cache_[key];\n } else {\n this.cache_[key] = value;\n }\n }\n\n get(key: string): unknown {\n if (contains(this.cache_, key)) {\n return this.cache_[key];\n }\n return null;\n }\n\n remove(key: string) {\n delete this.cache_[key];\n }\n\n isInMemoryStorage = true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DOMStorageWrapper } from './DOMStorageWrapper';\nimport { MemoryStorage } from './MemoryStorage';\n\ndeclare const window: Window;\n\n/**\n * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\n * to reflect this type\n *\n * @param domStorageName - Name of the underlying storage object\n * (e.g. 'localStorage' or 'sessionStorage').\n * @returns Turning off type information until a common interface is defined.\n */\nconst createStoragefor = function (\n domStorageName: string\n): DOMStorageWrapper | MemoryStorage {\n try {\n // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\n // so it must be inside the try/catch.\n if (\n typeof window !== 'undefined' &&\n typeof window[domStorageName] !== 'undefined'\n ) {\n // Need to test cache. Just because it's here doesn't mean it works\n const domStorage = window[domStorageName];\n domStorage.setItem('firebase:sentinel', 'cache');\n domStorage.removeItem('firebase:sentinel');\n return new DOMStorageWrapper(domStorage);\n }\n } catch (e) {}\n\n // Failed to create wrapper. Just return in-memory storage.\n // TODO: log?\n return new MemoryStorage();\n};\n\n/** A storage object that lasts across sessions */\nexport const PersistentStorage = createStoragefor('localStorage');\n\n/** A storage object that only lasts one session */\nexport const SessionStorage = createStoragefor('sessionStorage');\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel } from '@firebase/logger';\nimport {\n assert,\n base64,\n Sha1,\n stringToByteArray,\n stringify,\n isNodeSdk\n} from '@firebase/util';\n\nimport { SessionStorage } from '../storage/storage';\nimport { QueryContext } from '../view/EventRegistration';\n\ndeclare const window: Window;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ndeclare const Windows: any;\n\nconst logClient = new Logger('@firebase/database');\n\n/**\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\n */\nexport const LUIDGenerator: () => number = (function () {\n let id = 1;\n return function () {\n return id++;\n };\n})();\n\n/**\n * Sha1 hash of the input string\n * @param str - The string to hash\n * @returns {!string} The resulting hash\n */\nexport const sha1 = function (str: string): string {\n const utf8Bytes = stringToByteArray(str);\n const sha1 = new Sha1();\n sha1.update(utf8Bytes);\n const sha1Bytes = sha1.digest();\n return base64.encodeByteArray(sha1Bytes);\n};\n\nconst buildLogMessage_ = function (...varArgs: unknown[]): string {\n let message = '';\n for (let i = 0; i < varArgs.length; i++) {\n const arg = varArgs[i];\n if (\n Array.isArray(arg) ||\n (arg &&\n typeof arg === 'object' &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (arg as any).length === 'number')\n ) {\n message += buildLogMessage_.apply(null, arg);\n } else if (typeof arg === 'object') {\n message += stringify(arg);\n } else {\n message += arg;\n }\n message += ' ';\n }\n\n return message;\n};\n\n/**\n * Use this for all debug messages in Firebase.\n */\nexport let logger: ((a: string) => void) | null = null;\n\n/**\n * Flag to check for log availability on first log message\n */\nlet firstLog_ = true;\n\n/**\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\n * @param logger_ - A flag to turn on logging, or a custom logger\n * @param persistent - Whether or not to persist logging settings across refreshes\n */\nexport const enableLogging = function (\n logger_?: boolean | ((a: string) => void) | null,\n persistent?: boolean\n) {\n assert(\n !persistent || logger_ === true || logger_ === false,\n \"Can't turn on custom loggers persistently.\"\n );\n if (logger_ === true) {\n logClient.logLevel = LogLevel.VERBOSE;\n logger = logClient.log.bind(logClient);\n if (persistent) {\n SessionStorage.set('logging_enabled', true);\n }\n } else if (typeof logger_ === 'function') {\n logger = logger_;\n } else {\n logger = null;\n SessionStorage.remove('logging_enabled');\n }\n};\n\nexport const log = function (...varArgs: unknown[]) {\n if (firstLog_ === true) {\n firstLog_ = false;\n if (logger === null && SessionStorage.get('logging_enabled') === true) {\n enableLogging(true);\n }\n }\n\n if (logger) {\n const message = buildLogMessage_.apply(null, varArgs);\n logger(message);\n }\n};\n\nexport const logWrapper = function (\n prefix: string\n): (...varArgs: unknown[]) => void {\n return function (...varArgs: unknown[]) {\n log(prefix, ...varArgs);\n };\n};\n\nexport const error = function (...varArgs: string[]) {\n const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);\n logClient.error(message);\n};\n\nexport const fatal = function (...varArgs: string[]) {\n const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;\n logClient.error(message);\n throw new Error(message);\n};\n\nexport const warn = function (...varArgs: unknown[]) {\n const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);\n logClient.warn(message);\n};\n\n/**\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\n * does not use https.\n */\nexport const warnIfPageIsSecure = function () {\n // Be very careful accessing browser globals. Who knows what may or may not exist.\n if (\n typeof window !== 'undefined' &&\n window.location &&\n window.location.protocol &&\n window.location.protocol.indexOf('https:') !== -1\n ) {\n warn(\n 'Insecure Firebase access from a secure page. ' +\n 'Please use https in calls to new Firebase().'\n );\n }\n};\n\nexport const warnAboutUnsupportedMethod = function (methodName: string) {\n warn(\n methodName +\n ' is unsupported and will likely change soon. ' +\n 'Please do not use.'\n );\n};\n\n/**\n * Returns true if data is NaN, or +/- Infinity.\n */\nexport const isInvalidJSONNumber = function (data: unknown): boolean {\n return (\n typeof data === 'number' &&\n (data !== data || // NaN\n data === Number.POSITIVE_INFINITY ||\n data === Number.NEGATIVE_INFINITY)\n );\n};\n\nexport const executeWhenDOMReady = function (fn: () => void) {\n if (isNodeSdk() || document.readyState === 'complete') {\n fn();\n } else {\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\n // fire before onload), but fall back to onload.\n\n let called = false;\n const wrappedFn = function () {\n if (!document.body) {\n setTimeout(wrappedFn, Math.floor(10));\n return;\n }\n\n if (!called) {\n called = true;\n fn();\n }\n };\n\n if (document.addEventListener) {\n document.addEventListener('DOMContentLoaded', wrappedFn, false);\n // fallback to onload.\n window.addEventListener('load', wrappedFn, false);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else if ((document as any).attachEvent) {\n // IE.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (document as any).attachEvent('onreadystatechange', () => {\n if (document.readyState === 'complete') {\n wrappedFn();\n }\n });\n // fallback to onload.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (window as any).attachEvent('onload', wrappedFn);\n\n // jQuery has an extra hack for IE that we could employ (based on\n // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\n // I'm hoping we don't need it.\n }\n }\n};\n\n/**\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\n */\nexport const MIN_NAME = '[MIN_NAME]';\n\n/**\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\n */\nexport const MAX_NAME = '[MAX_NAME]';\n\n/**\n * Compares valid Firebase key names, plus min and max name\n */\nexport const nameCompare = function (a: string, b: string): number {\n if (a === b) {\n return 0;\n } else if (a === MIN_NAME || b === MAX_NAME) {\n return -1;\n } else if (b === MIN_NAME || a === MAX_NAME) {\n return 1;\n } else {\n const aAsInt = tryParseInt(a),\n bAsInt = tryParseInt(b);\n\n if (aAsInt !== null) {\n if (bAsInt !== null) {\n return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;\n } else {\n return -1;\n }\n } else if (bAsInt !== null) {\n return 1;\n } else {\n return a < b ? -1 : 1;\n }\n }\n};\n\n/**\n * @returns {!number} comparison result.\n */\nexport const stringCompare = function (a: string, b: string): number {\n if (a === b) {\n return 0;\n } else if (a < b) {\n return -1;\n } else {\n return 1;\n }\n};\n\nexport const requireKey = function (\n key: string,\n obj: { [k: string]: unknown }\n): unknown {\n if (obj && key in obj) {\n return obj[key];\n } else {\n throw new Error(\n 'Missing required key (' + key + ') in object: ' + stringify(obj)\n );\n }\n};\n\nexport const ObjectToUniqueKey = function (obj: unknown): string {\n if (typeof obj !== 'object' || obj === null) {\n return stringify(obj);\n }\n\n const keys = [];\n // eslint-disable-next-line guard-for-in\n for (const k in obj) {\n keys.push(k);\n }\n\n // Export as json, but with the keys sorted.\n keys.sort();\n let key = '{';\n for (let i = 0; i < keys.length; i++) {\n if (i !== 0) {\n key += ',';\n }\n key += stringify(keys[i]);\n key += ':';\n key += ObjectToUniqueKey(obj[keys[i]]);\n }\n\n key += '}';\n return key;\n};\n\n/**\n * Splits a string into a number of smaller segments of maximum size\n * @param str - The string\n * @param segsize - The maximum number of chars in the string.\n * @returns The string, split into appropriately-sized chunks\n */\nexport const splitStringBySize = function (\n str: string,\n segsize: number\n): string[] {\n const len = str.length;\n\n if (len <= segsize) {\n return [str];\n }\n\n const dataSegs = [];\n for (let c = 0; c < len; c += segsize) {\n if (c + segsize > len) {\n dataSegs.push(str.substring(c, len));\n } else {\n dataSegs.push(str.substring(c, c + segsize));\n }\n }\n return dataSegs;\n};\n\n/**\n * Apply a function to each (key, value) pair in an object or\n * apply a function to each (index, value) pair in an array\n * @param obj - The object or array to iterate over\n * @param fn - The function to apply\n */\nexport function each(obj: object, fn: (k: string, v: unknown) => void) {\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n fn(key, obj[key]);\n }\n }\n}\n\n/**\n * Like goog.bind, but doesn't bother to create a closure if opt_context is null/undefined.\n * @param callback - Callback function.\n * @param context - Optional context to bind to.\n *\n */\nexport const bindCallback = function (\n callback: (a: unknown) => void,\n context?: object | null\n): (a: unknown) => void {\n return context ? callback.bind(context) : callback;\n};\n\n/**\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\n * I made one modification at the end and removed the NaN / Infinity\n * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.\n * @param v - A double\n *\n */\nexport const doubleToIEEE754String = function (v: number): string {\n assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\n\n const ebits = 11,\n fbits = 52;\n const bias = (1 << (ebits - 1)) - 1;\n let s, e, f, ln, i;\n\n // Compute sign, exponent, fraction\n // Skip NaN / Infinity handling --MJL.\n if (v === 0) {\n e = 0;\n f = 0;\n s = 1 / v === -Infinity ? 1 : 0;\n } else {\n s = v < 0;\n v = Math.abs(v);\n\n if (v >= Math.pow(2, 1 - bias)) {\n // Normalized\n ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\n e = ln + bias;\n f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\n } else {\n // Denormalized\n e = 0;\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\n }\n }\n\n // Pack sign, exponent, fraction\n const bits = [];\n for (i = fbits; i; i -= 1) {\n bits.push(f % 2 ? 1 : 0);\n f = Math.floor(f / 2);\n }\n for (i = ebits; i; i -= 1) {\n bits.push(e % 2 ? 1 : 0);\n e = Math.floor(e / 2);\n }\n bits.push(s ? 1 : 0);\n bits.reverse();\n const str = bits.join('');\n\n // Return the data as a hex string. --MJL\n let hexByteString = '';\n for (i = 0; i < 64; i += 8) {\n let hexByte = parseInt(str.substr(i, 8), 2).toString(16);\n if (hexByte.length === 1) {\n hexByte = '0' + hexByte;\n }\n hexByteString = hexByteString + hexByte;\n }\n return hexByteString.toLowerCase();\n};\n\n/**\n * Used to detect if we're in a Chrome content script (which executes in an\n * isolated environment where long-polling doesn't work).\n */\nexport const isChromeExtensionContentScript = function (): boolean {\n return !!(\n typeof window === 'object' &&\n window['chrome'] &&\n window['chrome']['extension'] &&\n !/^chrome/.test(window.location.href)\n );\n};\n\n/**\n * Used to detect if we're in a Windows 8 Store app.\n */\nexport const isWindowsStoreApp = function (): boolean {\n // Check for the presence of a couple WinRT globals\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\n};\n\n/**\n * Converts a server error code to a JavaScript Error\n */\nexport function errorForServerCode(code: string, query: QueryContext): Error {\n let reason = 'Unknown Error';\n if (code === 'too_big') {\n reason =\n 'The data requested exceeds the maximum size ' +\n 'that can be accessed with a single request.';\n } else if (code === 'permission_denied') {\n reason = \"Client doesn't have permission to access the desired data.\";\n } else if (code === 'unavailable') {\n reason = 'The service is unavailable';\n }\n\n const error = new Error(\n code + ' at ' + query._path.toString() + ': ' + reason\n );\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (error as any).code = code.toUpperCase();\n return error;\n}\n\n/**\n * Used to test for integer-looking strings\n */\nexport const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\\\d{1,10}$');\n\n/**\n * For use in keys, the minimum possible 32-bit integer.\n */\nexport const INTEGER_32_MIN = -2147483648;\n\n/**\n * For use in keys, the maximum possible 32-bit integer.\n */\nexport const INTEGER_32_MAX = 2147483647;\n\n/**\n * If the string contains a 32-bit integer, return it. Else return null.\n */\nexport const tryParseInt = function (str: string): number | null {\n if (INTEGER_REGEXP_.test(str)) {\n const intVal = Number(str);\n if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {\n return intVal;\n }\n }\n return null;\n};\n\n/**\n * Helper to run some code but catch any exceptions and re-throw them later.\n * Useful for preventing user callbacks from breaking internal code.\n *\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\n * convenient (we don't have to try to figure out when is a safe point to\n * re-throw it), and the behavior seems reasonable:\n *\n * * If you aren't pausing on exceptions, you get an error in the console with\n * the correct stack trace.\n * * If you're pausing on all exceptions, the debugger will pause on your\n * exception and then again when we rethrow it.\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\n * on us re-throwing it.\n *\n * @param fn - The code to guard.\n */\nexport const exceptionGuard = function (fn: () => void) {\n try {\n fn();\n } catch (e) {\n // Re-throw exception when it's safe.\n setTimeout(() => {\n // It used to be that \"throw e\" would result in a good console error with\n // relevant context, but as of Chrome 39, you just get the firebase.js\n // file/line number where we re-throw it, which is useless. So we log\n // e.stack explicitly.\n const stack = e.stack || '';\n warn('Exception was thrown by user callback.', stack);\n throw e;\n }, Math.floor(0));\n }\n};\n\n/**\n * Helper function to safely call opt_callback with the specified arguments. It:\n * 1. Turns into a no-op if opt_callback is null or undefined.\n * 2. Wraps the call inside exceptionGuard to prevent exceptions from breaking our state.\n *\n * @param callback - Optional onComplete callback.\n * @param varArgs - Arbitrary args to be passed to opt_onComplete\n */\nexport const callUserCallback = function (\n // eslint-disable-next-line @typescript-eslint/ban-types\n callback?: Function | null,\n ...varArgs: unknown[]\n) {\n if (typeof callback === 'function') {\n exceptionGuard(() => {\n callback(...varArgs);\n });\n }\n};\n\n/**\n * @returns {boolean} true if we think we're currently being crawled.\n */\nexport const beingCrawled = function (): boolean {\n const userAgent =\n (typeof window === 'object' &&\n window['navigator'] &&\n window['navigator']['userAgent']) ||\n '';\n\n // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we\n // believe to support JavaScript/AJAX rendering.\n // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\n // would have seen the page\" is flaky if we don't treat it as a crawler.\n return (\n userAgent.search(\n /googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i\n ) >= 0\n );\n};\n\n/**\n * Export a property of an object using a getter function.\n */\nexport const exportPropGetter = function (\n object: object,\n name: string,\n fnGet: () => unknown\n) {\n Object.defineProperty(object, name, { get: fnGet });\n};\n\n/**\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\n *\n * It is removed with clearTimeout() as normal.\n *\n * @param fn - Function to run.\n * @param time - Milliseconds to wait before running.\n * @returns The setTimeout() return value.\n */\nexport const setTimeoutNonBlocking = function (\n fn: () => void,\n time: number\n): number | object {\n const timeout: number | object = setTimeout(fn, time);\n // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.\n if (\n typeof timeout === 'number' &&\n // @ts-ignore Is only defined in Deno environments.\n typeof Deno !== 'undefined' &&\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\n Deno['unrefTimer']\n ) {\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\n Deno.unrefTimer(timeout);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else if (typeof timeout === 'object' && (timeout as any)['unref']) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (timeout as any)['unref']();\n }\n\n return timeout;\n};\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _isFirebaseServerApp } from '@firebase/app'; // eslint-disable-line import/no-extraneous-dependencies\nimport {\n AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { warn } from './util/util';\n\n/**\n * Abstraction around AppCheck's token fetching capabilities.\n */\nexport class AppCheckTokenProvider {\n private appCheck?: FirebaseAppCheckInternal;\n private serverAppAppCheckToken?: string;\n private appName: string;\n constructor(\n app: FirebaseApp,\n private appCheckProvider?: Provider\n ) {\n this.appName = app.name;\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n this.appCheck = appCheckProvider?.getImmediate({ optional: true });\n if (!this.appCheck) {\n appCheckProvider?.get().then(appCheck => (this.appCheck = appCheck));\n }\n }\n\n getToken(forceRefresh?: boolean): Promise {\n if (this.serverAppAppCheckToken) {\n if (forceRefresh) {\n throw new Error(\n 'Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.'\n );\n }\n return Promise.resolve({ token: this.serverAppAppCheckToken });\n }\n if (!this.appCheck) {\n return new Promise((resolve, reject) => {\n // Support delayed initialization of FirebaseAppCheck. This allows our\n // customers to initialize the RTDB SDK before initializing Firebase\n // AppCheck and ensures that all requests are authenticated if a token\n // becomes available before the timeout below expires.\n setTimeout(() => {\n if (this.appCheck) {\n this.getToken(forceRefresh).then(resolve, reject);\n } else {\n resolve(null);\n }\n }, 0);\n });\n }\n return this.appCheck.getToken(forceRefresh);\n }\n\n addTokenChangeListener(listener: AppCheckTokenListener) {\n this.appCheckProvider\n ?.get()\n .then(appCheck => appCheck.addTokenListener(listener));\n }\n\n notifyForInvalidToken(): void {\n warn(\n `Provided AppCheck credentials for the app named \"${this.appName}\" ` +\n 'are invalid. This usually indicates your app was not initialized correctly.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseAuthTokenData } from '@firebase/app-types/private';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { log, warn } from './util/util';\n\nexport interface AuthTokenProvider {\n getToken(forceRefresh: boolean): Promise;\n addTokenChangeListener(listener: (token: string | null) => void): void;\n removeTokenChangeListener(listener: (token: string | null) => void): void;\n notifyForInvalidToken(): void;\n}\n\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nexport class FirebaseAuthTokenProvider implements AuthTokenProvider {\n private auth_: FirebaseAuthInternal | null = null;\n\n constructor(\n private appName_: string,\n private firebaseOptions_: object,\n private authProvider_: Provider\n ) {\n this.auth_ = authProvider_.getImmediate({ optional: true });\n if (!this.auth_) {\n authProvider_.onInit(auth => (this.auth_ = auth));\n }\n }\n\n getToken(forceRefresh: boolean): Promise {\n if (!this.auth_) {\n return new Promise((resolve, reject) => {\n // Support delayed initialization of FirebaseAuth. This allows our\n // customers to initialize the RTDB SDK before initializing Firebase\n // Auth and ensures that all requests are authenticated if a token\n // becomes available before the timeout below expires.\n setTimeout(() => {\n if (this.auth_) {\n this.getToken(forceRefresh).then(resolve, reject);\n } else {\n resolve(null);\n }\n }, 0);\n });\n }\n\n return this.auth_.getToken(forceRefresh).catch(error => {\n // TODO: Need to figure out all the cases this is raised and whether\n // this makes sense.\n if (error && error.code === 'auth/token-not-initialized') {\n log('Got auth/token-not-initialized error. Treating as null token.');\n return null;\n } else {\n return Promise.reject(error);\n }\n });\n }\n\n addTokenChangeListener(listener: (token: string | null) => void): void {\n // TODO: We might want to wrap the listener and call it with no args to\n // avoid a leaky abstraction, but that makes removing the listener harder.\n if (this.auth_) {\n this.auth_.addAuthTokenListener(listener);\n } else {\n this.authProvider_\n .get()\n .then(auth => auth.addAuthTokenListener(listener));\n }\n }\n\n removeTokenChangeListener(listener: (token: string | null) => void): void {\n this.authProvider_\n .get()\n .then(auth => auth.removeAuthTokenListener(listener));\n }\n\n notifyForInvalidToken(): void {\n let errorMessage =\n 'Provided authentication credentials for the app named \"' +\n this.appName_ +\n '\" are invalid. This usually indicates your app was not ' +\n 'initialized correctly. ';\n if ('credential' in this.firebaseOptions_) {\n errorMessage +=\n 'Make sure the \"credential\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n } else if ('serviceAccount' in this.firebaseOptions_) {\n errorMessage +=\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n } else {\n errorMessage +=\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\n 'initializeApp() match the values provided for your app at ' +\n 'https://console.firebase.google.com/.';\n }\n warn(errorMessage);\n }\n}\n\n/* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */\nexport class EmulatorTokenProvider implements AuthTokenProvider {\n /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */\n static OWNER = 'owner';\n\n constructor(private accessToken: string) {}\n\n getToken(forceRefresh: boolean): Promise {\n return Promise.resolve({\n accessToken: this.accessToken\n });\n }\n\n addTokenChangeListener(listener: (token: string | null) => void): void {\n // Invoke the listener immediately to match the behavior in Firebase Auth\n // (see packages/auth/src/auth.js#L1807)\n listener(this.accessToken);\n }\n\n removeTokenChangeListener(listener: (token: string | null) => void): void {}\n\n notifyForInvalidToken(): void {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const PROTOCOL_VERSION = '5';\n\nexport const VERSION_PARAM = 'v';\n\nexport const TRANSPORT_SESSION_PARAM = 's';\n\nexport const REFERER_PARAM = 'r';\n\nexport const FORGE_REF = 'f';\n\n// Matches console.firebase.google.com, firebase-console-*.corp.google.com and\n// firebase.corp.google.com\nexport const FORGE_DOMAIN_RE =\n /(console\\.firebase|firebase-console-\\w+\\.corp|firebase\\.corp)\\.google\\.com/;\n\nexport const LAST_SESSION_PARAM = 'ls';\n\nexport const APPLICATION_ID_PARAM = 'p';\n\nexport const APP_CHECK_TOKEN_PARAM = 'ac';\n\nexport const WEBSOCKET = 'websocket';\n\nexport const LONG_POLLING = 'long_polling';\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, EmulatorMockTokenOptions } from '@firebase/util';\n\nimport { LONG_POLLING, WEBSOCKET } from '../realtime/Constants';\n\nimport { PersistentStorage } from './storage/storage';\nimport { each } from './util/util';\n\nexport interface RepoInfoEmulatorOptions {\n mockUserToken?: string | EmulatorMockTokenOptions;\n}\n\n/**\n * A class that holds metadata about a Repo object\n */\nexport class RepoInfo {\n private _host: string;\n private _domain: string;\n internalHost: string;\n\n /**\n * @param host - Hostname portion of the url for the repo\n * @param secure - Whether or not this repo is accessed over ssl\n * @param namespace - The namespace represented by the repo\n * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).\n * @param nodeAdmin - Whether this instance uses Admin SDK credentials\n * @param persistenceKey - Override the default session persistence storage key\n */\n constructor(\n host: string,\n public readonly secure: boolean,\n public readonly namespace: string,\n public readonly webSocketOnly: boolean,\n public readonly nodeAdmin: boolean = false,\n public readonly persistenceKey: string = '',\n public readonly includeNamespaceInQueryParams: boolean = false,\n public readonly isUsingEmulator: boolean = false,\n public readonly emulatorOptions: RepoInfoEmulatorOptions | null = null\n ) {\n this._host = host.toLowerCase();\n this._domain = this._host.substr(this._host.indexOf('.') + 1);\n this.internalHost =\n (PersistentStorage.get('host:' + host) as string) || this._host;\n }\n\n isCacheableHost(): boolean {\n return this.internalHost.substr(0, 2) === 's-';\n }\n\n isCustomHost() {\n return (\n this._domain !== 'firebaseio.com' &&\n this._domain !== 'firebaseio-demo.com'\n );\n }\n\n get host() {\n return this._host;\n }\n\n set host(newHost: string) {\n if (newHost !== this.internalHost) {\n this.internalHost = newHost;\n if (this.isCacheableHost()) {\n PersistentStorage.set('host:' + this._host, this.internalHost);\n }\n }\n }\n\n toString(): string {\n let str = this.toURLString();\n if (this.persistenceKey) {\n str += '<' + this.persistenceKey + '>';\n }\n return str;\n }\n\n toURLString(): string {\n const protocol = this.secure ? 'https://' : 'http://';\n const query = this.includeNamespaceInQueryParams\n ? `?ns=${this.namespace}`\n : '';\n return `${protocol}${this.host}/${query}`;\n }\n}\n\nfunction repoInfoNeedsQueryParam(repoInfo: RepoInfo): boolean {\n return (\n repoInfo.host !== repoInfo.internalHost ||\n repoInfo.isCustomHost() ||\n repoInfo.includeNamespaceInQueryParams\n );\n}\n\n/**\n * Returns the websocket URL for this repo\n * @param repoInfo - RepoInfo object\n * @param type - of connection\n * @param params - list\n * @returns The URL for this repo\n */\nexport function repoInfoConnectionURL(\n repoInfo: RepoInfo,\n type: string,\n params: { [k: string]: string }\n): string {\n assert(typeof type === 'string', 'typeof type must == string');\n assert(typeof params === 'object', 'typeof params must == object');\n\n let connURL: string;\n if (type === WEBSOCKET) {\n connURL =\n (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';\n } else if (type === LONG_POLLING) {\n connURL =\n (repoInfo.secure ? 'https://' : 'http://') +\n repoInfo.internalHost +\n '/.lp?';\n } else {\n throw new Error('Unknown connection type: ' + type);\n }\n if (repoInfoNeedsQueryParam(repoInfo)) {\n params['ns'] = repoInfo.namespace;\n }\n\n const pairs: string[] = [];\n\n each(params, (key: string, value: string) => {\n pairs.push(key + '=' + value);\n });\n\n return connURL + pairs.join('&');\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { deepCopy, contains } from '@firebase/util';\n\n/**\n * Tracks a collection of stats.\n */\nexport class StatsCollection {\n private counters_: { [k: string]: number } = {};\n\n incrementCounter(name: string, amount: number = 1) {\n if (!contains(this.counters_, name)) {\n this.counters_[name] = 0;\n }\n\n this.counters_[name] += amount;\n }\n\n get() {\n return deepCopy(this.counters_);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../RepoInfo';\n\nimport { StatsCollection } from './StatsCollection';\n\nconst collections: { [k: string]: StatsCollection } = {};\nconst reporters: { [k: string]: unknown } = {};\n\nexport function statsManagerGetCollection(repoInfo: RepoInfo): StatsCollection {\n const hashString = repoInfo.toString();\n\n if (!collections[hashString]) {\n collections[hashString] = new StatsCollection();\n }\n\n return collections[hashString];\n}\n\nexport function statsManagerGetOrCreateReporter(\n repoInfo: RepoInfo,\n creatorFunction: () => T\n): T {\n const hashString = repoInfo.toString();\n\n if (!reporters[hashString]) {\n reporters[hashString] = creatorFunction();\n }\n\n return reporters[hashString] as T;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { exceptionGuard } from '../../core/util/util';\n\n/**\n * This class ensures the packets from the server arrive in order\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\n */\nexport class PacketReceiver {\n pendingResponses: unknown[] = [];\n currentResponseNum = 0;\n closeAfterResponse = -1;\n onClose: (() => void) | null = null;\n\n /**\n * @param onMessage_\n */\n constructor(private onMessage_: (a: {}) => void) {}\n\n closeAfter(responseNum: number, callback: () => void) {\n this.closeAfterResponse = responseNum;\n this.onClose = callback;\n if (this.closeAfterResponse < this.currentResponseNum) {\n this.onClose();\n this.onClose = null;\n }\n }\n\n /**\n * Each message from the server comes with a response number, and an array of data. The responseNumber\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\n * browsers will respond in the same order as the requests we sent\n */\n handleResponse(requestNum: number, data: unknown[]) {\n this.pendingResponses[requestNum] = data;\n while (this.pendingResponses[this.currentResponseNum]) {\n const toProcess = this.pendingResponses[\n this.currentResponseNum\n ] as unknown[];\n delete this.pendingResponses[this.currentResponseNum];\n for (let i = 0; i < toProcess.length; ++i) {\n if (toProcess[i]) {\n exceptionGuard(() => {\n this.onMessage_(toProcess[i]);\n });\n }\n }\n if (this.currentResponseNum === this.closeAfterResponse) {\n if (this.onClose) {\n this.onClose();\n this.onClose = null;\n }\n break;\n }\n this.currentResponseNum++;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Encode, isNodeSdk, stringify } from '@firebase/util';\n\nimport { RepoInfo, repoInfoConnectionURL } from '../core/RepoInfo';\nimport { StatsCollection } from '../core/stats/StatsCollection';\nimport { statsManagerGetCollection } from '../core/stats/StatsManager';\nimport {\n executeWhenDOMReady,\n isChromeExtensionContentScript,\n isWindowsStoreApp,\n log,\n logWrapper,\n LUIDGenerator,\n splitStringBySize\n} from '../core/util/util';\n\nimport {\n APP_CHECK_TOKEN_PARAM,\n APPLICATION_ID_PARAM,\n FORGE_DOMAIN_RE,\n FORGE_REF,\n LAST_SESSION_PARAM,\n LONG_POLLING,\n PROTOCOL_VERSION,\n REFERER_PARAM,\n TRANSPORT_SESSION_PARAM,\n VERSION_PARAM\n} from './Constants';\nimport { PacketReceiver } from './polling/PacketReceiver';\nimport { Transport } from './Transport';\n\n// URL query parameters associated with longpolling\nexport const FIREBASE_LONGPOLL_START_PARAM = 'start';\nexport const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\nexport const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\nexport const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\nexport const FIREBASE_LONGPOLL_ID_PARAM = 'id';\nexport const FIREBASE_LONGPOLL_PW_PARAM = 'pw';\nexport const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\nexport const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\nexport const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\nexport const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\nexport const FIREBASE_LONGPOLL_DATA_PARAM = 'd';\nexport const FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = 'disconn';\nexport const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\n\n//Data size constants.\n//TODO: Perf: the maximum length actually differs from browser to browser.\n// We should check what browser we're on and set accordingly.\nconst MAX_URL_DATA_SIZE = 1870;\nconst SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\nconst MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\n\n/**\n * Keepalive period\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\n * length of 30 seconds that we can't exceed.\n */\nconst KEEPALIVE_REQUEST_INTERVAL = 25000;\n\n/**\n * How long to wait before aborting a long-polling connection attempt.\n */\nconst LP_CONNECT_TIMEOUT = 30000;\n\n/**\n * This class manages a single long-polling connection.\n */\nexport class BrowserPollConnection implements Transport {\n bytesSent = 0;\n bytesReceived = 0;\n urlFn: (params: object) => string;\n scriptTagHolder: FirebaseIFrameScriptHolder;\n myDisconnFrame: HTMLIFrameElement;\n curSegmentNum: number;\n myPacketOrderer: PacketReceiver;\n id: string;\n password: string;\n private log_: (...a: unknown[]) => void;\n private stats_: StatsCollection;\n private everConnected_ = false;\n private isClosed_: boolean;\n private connectTimeoutTimer_: number | null;\n private onDisconnect_: ((a?: boolean) => void) | null;\n\n /**\n * @param connId An identifier for this connection, used for logging\n * @param repoInfo The info for the endpoint to send data to.\n * @param applicationId The Firebase App ID for this project.\n * @param appCheckToken The AppCheck token for this client.\n * @param authToken The AuthToken to use for this connection.\n * @param transportSessionId Optional transportSessionid if we are\n * reconnecting for an existing transport session\n * @param lastSessionId Optional lastSessionId if the PersistentConnection has\n * already created a connection previously\n */\n constructor(\n public connId: string,\n public repoInfo: RepoInfo,\n private applicationId?: string,\n private appCheckToken?: string,\n private authToken?: string,\n public transportSessionId?: string,\n public lastSessionId?: string\n ) {\n this.log_ = logWrapper(connId);\n this.stats_ = statsManagerGetCollection(repoInfo);\n this.urlFn = (params: { [k: string]: string }) => {\n // Always add the token if we have one.\n if (this.appCheckToken) {\n params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\n }\n return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);\n };\n }\n\n /**\n * @param onMessage - Callback when messages arrive\n * @param onDisconnect - Callback with connection lost.\n */\n open(onMessage: (msg: {}) => void, onDisconnect: (a?: boolean) => void) {\n this.curSegmentNum = 0;\n this.onDisconnect_ = onDisconnect;\n this.myPacketOrderer = new PacketReceiver(onMessage);\n this.isClosed_ = false;\n\n this.connectTimeoutTimer_ = setTimeout(() => {\n this.log_('Timed out trying to connect.');\n // Make sure we clear the host cache\n this.onClosed_();\n this.connectTimeoutTimer_ = null;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(LP_CONNECT_TIMEOUT)) as any;\n\n // Ensure we delay the creation of the iframe until the DOM is loaded.\n executeWhenDOMReady(() => {\n if (this.isClosed_) {\n return;\n }\n\n //Set up a callback that gets triggered once a connection is set up.\n this.scriptTagHolder = new FirebaseIFrameScriptHolder(\n (...args) => {\n const [command, arg1, arg2, arg3, arg4] = args;\n this.incrementIncomingBytes_(args);\n if (!this.scriptTagHolder) {\n return; // we closed the connection.\n }\n\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n this.everConnected_ = true;\n if (command === FIREBASE_LONGPOLL_START_PARAM) {\n this.id = arg1 as string;\n this.password = arg2 as string;\n } else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {\n // Don't clear the host cache. We got a response from the server, so we know it's reachable\n if (arg1) {\n // We aren't expecting any more data (other than what the server's already in the process of sending us\n // through our already open polls), so don't send any more.\n this.scriptTagHolder.sendNewPolls = false;\n\n // arg1 in this case is the last response number sent by the server. We should try to receive\n // all of the responses up to this one before closing\n this.myPacketOrderer.closeAfter(arg1 as number, () => {\n this.onClosed_();\n });\n } else {\n this.onClosed_();\n }\n } else {\n throw new Error('Unrecognized command received: ' + command);\n }\n },\n (...args) => {\n const [pN, data] = args;\n this.incrementIncomingBytes_(args);\n this.myPacketOrderer.handleResponse(pN as number, data as unknown[]);\n },\n () => {\n this.onClosed_();\n },\n this.urlFn\n );\n\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\n //from cache.\n const urlParams: { [k: string]: string | number } = {};\n urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(\n Math.random() * 100000000\n );\n if (this.scriptTagHolder.uniqueCallbackIdentifier) {\n urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =\n this.scriptTagHolder.uniqueCallbackIdentifier;\n }\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\n if (this.transportSessionId) {\n urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;\n }\n if (this.lastSessionId) {\n urlParams[LAST_SESSION_PARAM] = this.lastSessionId;\n }\n if (this.applicationId) {\n urlParams[APPLICATION_ID_PARAM] = this.applicationId;\n }\n if (this.appCheckToken) {\n urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\n }\n if (\n typeof location !== 'undefined' &&\n location.hostname &&\n FORGE_DOMAIN_RE.test(location.hostname)\n ) {\n urlParams[REFERER_PARAM] = FORGE_REF;\n }\n const connectURL = this.urlFn(urlParams);\n this.log_('Connecting via long-poll to ' + connectURL);\n this.scriptTagHolder.addTag(connectURL, () => {\n /* do nothing */\n });\n });\n }\n\n /**\n * Call this when a handshake has completed successfully and we want to consider the connection established\n */\n start() {\n this.scriptTagHolder.startLongPoll(this.id, this.password);\n this.addDisconnectPingFrame(this.id, this.password);\n }\n\n static forceAllow_: boolean;\n\n /**\n * Forces long polling to be considered as a potential transport\n */\n static forceAllow() {\n BrowserPollConnection.forceAllow_ = true;\n }\n\n static forceDisallow_: boolean;\n\n /**\n * Forces longpolling to not be considered as a potential transport\n */\n static forceDisallow() {\n BrowserPollConnection.forceDisallow_ = true;\n }\n\n // Static method, use string literal so it can be accessed in a generic way\n static isAvailable() {\n if (isNodeSdk()) {\n return false;\n } else if (BrowserPollConnection.forceAllow_) {\n return true;\n } else {\n // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\n // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\n return (\n !BrowserPollConnection.forceDisallow_ &&\n typeof document !== 'undefined' &&\n document.createElement != null &&\n !isChromeExtensionContentScript() &&\n !isWindowsStoreApp()\n );\n }\n }\n\n /**\n * No-op for polling\n */\n markConnectionHealthy() {}\n\n /**\n * Stops polling and cleans up the iframe\n */\n private shutdown_() {\n this.isClosed_ = true;\n\n if (this.scriptTagHolder) {\n this.scriptTagHolder.close();\n this.scriptTagHolder = null;\n }\n\n //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\n if (this.myDisconnFrame) {\n document.body.removeChild(this.myDisconnFrame);\n this.myDisconnFrame = null;\n }\n\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n }\n\n /**\n * Triggered when this transport is closed\n */\n private onClosed_() {\n if (!this.isClosed_) {\n this.log_('Longpoll is closing itself');\n this.shutdown_();\n\n if (this.onDisconnect_) {\n this.onDisconnect_(this.everConnected_);\n this.onDisconnect_ = null;\n }\n }\n }\n\n /**\n * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\n * that we've left.\n */\n close() {\n if (!this.isClosed_) {\n this.log_('Longpoll is being closed.');\n this.shutdown_();\n }\n }\n\n /**\n * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\n * broken into chunks (since URLs have a small maximum length).\n * @param data - The JSON data to transmit.\n */\n send(data: {}) {\n const dataStr = stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n\n //first, lets get the base64-encoded data\n const base64data = base64Encode(dataStr);\n\n //We can only fit a certain amount in each URL, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\n\n //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\n //of segments so that we can reassemble the packet on the server.\n for (let i = 0; i < dataSegs.length; i++) {\n this.scriptTagHolder.enqueueSegment(\n this.curSegmentNum,\n dataSegs.length,\n dataSegs[i]\n );\n this.curSegmentNum++;\n }\n }\n\n /**\n * This is how we notify the server that we're leaving.\n * We aren't able to send requests with DHTML on a window close event, but we can\n * trigger XHR requests in some browsers (everything but Opera basically).\n */\n addDisconnectPingFrame(id: string, pw: string) {\n if (isNodeSdk()) {\n return;\n }\n this.myDisconnFrame = document.createElement('iframe');\n const urlParams: { [k: string]: string } = {};\n urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;\n this.myDisconnFrame.src = this.urlFn(urlParams);\n this.myDisconnFrame.style.display = 'none';\n\n document.body.appendChild(this.myDisconnFrame);\n }\n\n /**\n * Used to track the bytes received by this client\n */\n private incrementIncomingBytes_(args: unknown) {\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\n const bytesReceived = stringify(args).length;\n this.bytesReceived += bytesReceived;\n this.stats_.incrementCounter('bytes_received', bytesReceived);\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport interface IFrameElement extends HTMLIFrameElement {\n doc: Document;\n}\n\n/*********************************************************************************************\n * A wrapper around an iframe that is used as a long-polling script holder.\n *********************************************************************************************/\nexport class FirebaseIFrameScriptHolder {\n //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\n //problems in some browsers.\n outstandingRequests = new Set();\n\n //A queue of the pending segments waiting for transmission to the server.\n pendingSegs: Array<{ seg: number; ts: number; d: unknown }> = [];\n\n //A serial number. We use this for two things:\n // 1) A way to ensure the browser doesn't cache responses to polls\n // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\n // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\n // JSONP code in the order it was added to the iframe.\n currentSerial = Math.floor(Math.random() * 100000000);\n\n // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\n // incoming data from the server that we're waiting for).\n sendNewPolls = true;\n\n uniqueCallbackIdentifier: number;\n myIFrame: IFrameElement;\n alive: boolean;\n myID: string;\n myPW: string;\n commandCB: (command: string, ...args: unknown[]) => void;\n onMessageCB: (...args: unknown[]) => void;\n\n /**\n * @param commandCB - The callback to be called when control commands are received from the server.\n * @param onMessageCB - The callback to be triggered when responses arrive from the server.\n * @param onDisconnect - The callback to be triggered when this tag holder is closed\n * @param urlFn - A function that provides the URL of the endpoint to send data to.\n */\n constructor(\n commandCB: (command: string, ...args: unknown[]) => void,\n onMessageCB: (...args: unknown[]) => void,\n public onDisconnect: () => void,\n public urlFn: (a: object) => string\n ) {\n if (!isNodeSdk()) {\n //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\n //iframes where we put the long-polling script tags. We have two callbacks:\n // 1) Command Callback - Triggered for control issues, like starting a connection.\n // 2) Message Callback - Triggered when new data arrives.\n this.uniqueCallbackIdentifier = LUIDGenerator();\n window[\n FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier\n ] = commandCB;\n window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =\n onMessageCB;\n\n //Create an iframe for us to add script tags to.\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\n\n // Set the iframe's contents.\n let script = '';\n // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\n // for ie9, but ie8 needs to do it again in the document itself.\n if (\n this.myIFrame.src &&\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:'\n ) {\n const currentDomain = document.domain;\n script = '';\n }\n const iframeContents = '' + script + '';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n } catch (e) {\n log('frame writing exception');\n if (e.stack) {\n log(e.stack);\n }\n log(e);\n }\n } else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n\n /**\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\n * actually use.\n */\n private static createIFrame_(): IFrameElement {\n const iframe = document.createElement('iframe') as IFrameElement;\n iframe.style.display = 'none';\n\n // This is necessary in order to initialize the document inside the iframe\n if (document.body) {\n document.body.appendChild(iframe);\n try {\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n const a = iframe.contentWindow.document;\n if (!a) {\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n log('No IE domain setting required');\n }\n } catch (e) {\n const domain = document.domain;\n iframe.src =\n \"javascript:void((function(){document.open();document.domain='\" +\n domain +\n \"';document.close();})())\";\n }\n } else {\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n // never gets hit.\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n }\n\n // Get the document of the iframe in a browser-specific way.\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n } else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else if ((iframe as any).document) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n iframe.doc = (iframe as any).document; //others?\n }\n\n return iframe;\n }\n\n /**\n * Cancel all outstanding queries and remove the frame.\n */\n close() {\n //Mark this iframe as dead, so no new requests are sent.\n this.alive = false;\n\n if (this.myIFrame) {\n //We have to actually remove all of the html inside this iframe before removing it from the\n //window, or IE will continue loading and executing the script tags we've already added, which\n //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.\n this.myIFrame.doc.body.textContent = '';\n setTimeout(() => {\n if (this.myIFrame !== null) {\n document.body.removeChild(this.myIFrame);\n this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n\n // Protect from being called recursively.\n const onDisconnect = this.onDisconnect;\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\n }\n\n /**\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\n * @param id - The ID of this connection\n * @param pw - The password for this connection\n */\n startLongPoll(id: string, pw: string) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true;\n\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n while (this.newRequest_()) {}\n }\n\n /**\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\n * too many outstanding requests and we are still alive.\n *\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\n * needed.\n */\n private newRequest_() {\n // We keep one outstanding request open all the time to receive data, but if we need to send data\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\n // close the old request.\n if (\n this.alive &&\n this.sendNewPolls &&\n this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)\n ) {\n //construct our url\n this.currentSerial++;\n const urlParams: { [k: string]: string | number } = {};\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n let theURL = this.urlFn(urlParams);\n //Now add as much data as we can.\n let curDataString = '';\n let i = 0;\n\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n const nextSeg = this.pendingSegs[0];\n if (\n (nextSeg.d as unknown[]).length +\n SEG_HEADER_SIZE +\n curDataString.length <=\n MAX_URL_DATA_SIZE\n ) {\n //great, the segment will fit. Lets append it.\n const theSeg = this.pendingSegs.shift();\n curDataString =\n curDataString +\n '&' +\n FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n i +\n '=' +\n theSeg.seg +\n '&' +\n FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n i +\n '=' +\n theSeg.ts +\n '&' +\n FIREBASE_LONGPOLL_DATA_PARAM +\n i +\n '=' +\n theSeg.d;\n i++;\n } else {\n break;\n }\n }\n\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Queue a packet for transmission to the server.\n * @param segnum - A sequential id for this packet segment used for reassembly\n * @param totalsegs - The total number of segments in this packet\n * @param data - The data for this segment.\n */\n enqueueSegment(segnum: number, totalsegs: number, data: unknown) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n\n //send the data immediately if there isn't already data being transmitted, unless\n //startLongPoll hasn't been called yet.\n if (this.alive) {\n this.newRequest_();\n }\n }\n\n /**\n * Add a script tag for a regular long-poll request.\n * @param url - The URL of the script tag.\n * @param serial - The serial number of the request.\n */\n private addLongPollTag_(url: string, serial: number) {\n //remember that we sent this request.\n this.outstandingRequests.add(serial);\n\n const doNewRequest = () => {\n this.outstandingRequests.delete(serial);\n this.newRequest_();\n };\n\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n const keepaliveTimeout = setTimeout(\n doNewRequest,\n Math.floor(KEEPALIVE_REQUEST_INTERVAL)\n );\n\n const readyStateCB = () => {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout);\n\n // Trigger a new request so we can continue receiving data.\n doNewRequest();\n };\n\n this.addTag(url, readyStateCB);\n }\n\n /**\n * Add an arbitrary script tag to the iframe.\n * @param url - The URL for the script tag source.\n * @param loadCB - A callback to be triggered once the script has loaded.\n */\n addTag(url: string, loadCB: () => void) {\n if (isNodeSdk()) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any).doNodeLongPoll(url, loadCB);\n } else {\n setTimeout(() => {\n try {\n // if we're already closed, don't add this poll\n if (!this.sendNewPolls) {\n return;\n }\n const newScript = this.myIFrame.doc.createElement('script');\n newScript.type = 'text/javascript';\n newScript.async = true;\n newScript.src = url;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n newScript.onload = (newScript as any).onreadystatechange =\n function () {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const rstate = (newScript as any).readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n newScript.onload = (newScript as any).onreadystatechange = null;\n if (newScript.parentNode) {\n newScript.parentNode.removeChild(newScript);\n }\n loadCB();\n }\n };\n newScript.onerror = () => {\n log('Long-poll script failed to load: ' + url);\n this.sendNewPolls = false;\n this.close();\n };\n this.myIFrame.doc.body.appendChild(newScript);\n } catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, isNodeSdk, jsonEval, stringify } from '@firebase/util';\n\nimport { RepoInfo, repoInfoConnectionURL } from '../core/RepoInfo';\nimport { StatsCollection } from '../core/stats/StatsCollection';\nimport { statsManagerGetCollection } from '../core/stats/StatsManager';\nimport { PersistentStorage } from '../core/storage/storage';\nimport { logWrapper, splitStringBySize } from '../core/util/util';\nimport { SDK_VERSION } from '../core/version';\n\nimport {\n APPLICATION_ID_PARAM,\n APP_CHECK_TOKEN_PARAM,\n FORGE_DOMAIN_RE,\n FORGE_REF,\n LAST_SESSION_PARAM,\n PROTOCOL_VERSION,\n REFERER_PARAM,\n TRANSPORT_SESSION_PARAM,\n VERSION_PARAM,\n WEBSOCKET\n} from './Constants';\nimport { Transport } from './Transport';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ndeclare const MozWebSocket: any;\n\nconst WEBSOCKET_MAX_FRAME_SIZE = 16384;\nconst WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\n\nlet WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n} else if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\n\nexport function setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\n\n/**\n * Create a new websocket connection with the given callbacks.\n */\nexport class WebSocketConnection implements Transport {\n keepaliveTimer: number | null = null;\n frames: string[] | null = null;\n totalFrames = 0;\n bytesSent = 0;\n bytesReceived = 0;\n connURL: string;\n onDisconnect: (a?: boolean) => void;\n onMessage: (msg: {}) => void;\n mySock: WebSocket | null;\n private log_: (...a: unknown[]) => void;\n private stats_: StatsCollection;\n private everConnected_: boolean;\n private isClosed_: boolean;\n private nodeAdmin: boolean;\n\n /**\n * @param connId identifier for this transport\n * @param repoInfo The info for the websocket endpoint.\n * @param applicationId The Firebase App ID for this project.\n * @param appCheckToken The App Check Token for this client.\n * @param authToken The Auth Token for this client.\n * @param transportSessionId Optional transportSessionId if this is connecting\n * to an existing transport session\n * @param lastSessionId Optional lastSessionId if there was a previous\n * connection\n */\n constructor(\n public connId: string,\n repoInfo: RepoInfo,\n private applicationId?: string,\n private appCheckToken?: string,\n private authToken?: string,\n transportSessionId?: string,\n lastSessionId?: string\n ) {\n this.log_ = logWrapper(this.connId);\n this.stats_ = statsManagerGetCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(\n repoInfo,\n transportSessionId,\n lastSessionId,\n appCheckToken,\n applicationId\n );\n this.nodeAdmin = repoInfo.nodeAdmin;\n }\n\n /**\n * @param repoInfo - The info for the websocket endpoint.\n * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param lastSessionId - Optional lastSessionId if there was a previous connection\n * @returns connection url\n */\n private static connectionURL_(\n repoInfo: RepoInfo,\n transportSessionId?: string,\n lastSessionId?: string,\n appCheckToken?: string,\n applicationId?: string\n ): string {\n const urlParams: { [k: string]: string } = {};\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\n\n if (\n !isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.hostname &&\n FORGE_DOMAIN_RE.test(location.hostname)\n ) {\n urlParams[REFERER_PARAM] = FORGE_REF;\n }\n if (transportSessionId) {\n urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[LAST_SESSION_PARAM] = lastSessionId;\n }\n if (appCheckToken) {\n urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;\n }\n if (applicationId) {\n urlParams[APPLICATION_ID_PARAM] = applicationId;\n }\n\n return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);\n }\n\n /**\n * @param onMessage - Callback when messages arrive\n * @param onDisconnect - Callback with connection lost.\n */\n open(onMessage: (msg: {}) => void, onDisconnect: (a?: boolean) => void) {\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n\n this.log_('Websocket connecting to ' + this.connURL);\n\n this.everConnected_ = false;\n // Assume failure until proven otherwise.\n PersistentStorage.set('previous_websocket_failure', true);\n\n try {\n let options: { [k: string]: object };\n if (isNodeSdk()) {\n const device = this.nodeAdmin ? 'AdminNode' : 'Node';\n // UA Format: Firebase////\n options = {\n headers: {\n 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,\n 'X-Firebase-GMPID': this.applicationId || ''\n }\n };\n\n // If using Node with admin creds, AppCheck-related checks are unnecessary.\n // Note that we send the credentials here even if they aren't admin credentials, which is\n // not a problem.\n // Note that this header is just used to bypass appcheck, and the token should still be sent\n // through the websocket connection once it is established.\n if (this.authToken) {\n options.headers['Authorization'] = `Bearer ${this.authToken}`;\n }\n if (this.appCheckToken) {\n options.headers['X-Firebase-AppCheck'] = this.appCheckToken;\n }\n\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n const env = process['env'];\n const proxy =\n this.connURL.indexOf('wss://') === 0\n ? env['HTTPS_PROXY'] || env['https_proxy']\n : env['HTTP_PROXY'] || env['http_proxy'];\n\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n }\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n } catch (e) {\n this.log_('Error instantiating WebSocket.');\n const error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n return;\n }\n\n this.mySock.onopen = () => {\n this.log_('Websocket connected.');\n this.everConnected_ = true;\n };\n\n this.mySock.onclose = () => {\n this.log_('Websocket connection was disconnected.');\n this.mySock = null;\n this.onClosed_();\n };\n\n this.mySock.onmessage = m => {\n this.handleIncomingFrame(m as {});\n };\n\n this.mySock.onerror = e => {\n this.log_('WebSocket error. Closing connection.');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const error = (e as any).message || (e as any).data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n };\n }\n\n /**\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n */\n start() {}\n\n static forceDisallow_: boolean;\n\n static forceDisallow() {\n WebSocketConnection.forceDisallow_ = true;\n }\n\n static isAvailable(): boolean {\n let isOldAndroid = false;\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n const oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n isOldAndroid = true;\n }\n }\n }\n\n return (\n !isOldAndroid &&\n WebSocketImpl !== null &&\n !WebSocketConnection.forceDisallow_\n );\n }\n\n /**\n * Number of response before we consider the connection \"healthy.\"\n */\n static responsesRequiredToBeHealthy = 2;\n\n /**\n * Time to wait for the connection te become healthy before giving up.\n */\n static healthyTimeout = 30000;\n\n /**\n * Returns true if we previously failed to connect with this transport.\n */\n static previouslyFailed(): boolean {\n // If our persistent storage is actually only in-memory storage,\n // we default to assuming that it previously failed to be safe.\n return (\n PersistentStorage.isInMemoryStorage ||\n PersistentStorage.get('previous_websocket_failure') === true\n );\n }\n\n markConnectionHealthy() {\n PersistentStorage.remove('previous_websocket_failure');\n }\n\n private appendFrame_(data: string) {\n this.frames.push(data);\n if (this.frames.length === this.totalFrames) {\n const fullMess = this.frames.join('');\n this.frames = null;\n const jsonMess = jsonEval(fullMess) as object;\n\n //handle the message\n this.onMessage(jsonMess);\n }\n }\n\n /**\n * @param frameCount - The number of frames we are expecting from the server\n */\n private handleNewFrameCount_(frameCount: number) {\n this.totalFrames = frameCount;\n this.frames = [];\n }\n\n /**\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\n * @returns Any remaining data to be process, or null if there is none\n */\n private extractFrameCount_(data: string): string | null {\n assert(this.frames === null, 'We already have a frame buffer');\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\n if (data.length <= 6) {\n const frameCount = Number(data);\n if (!isNaN(frameCount)) {\n this.handleNewFrameCount_(frameCount);\n return null;\n }\n }\n this.handleNewFrameCount_(1);\n return data;\n }\n\n /**\n * Process a websocket frame that has arrived from the server.\n * @param mess - The frame data\n */\n handleIncomingFrame(mess: { [k: string]: unknown }) {\n if (this.mySock === null) {\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n }\n const data = mess['data'] as string;\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n\n this.resetKeepAlive();\n\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n } else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n const remainingData = this.extractFrameCount_(data);\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n }\n\n /**\n * Send a message to the server\n * @param data - The JSON object to transmit\n */\n send(data: {}) {\n this.resetKeepAlive();\n\n const dataStr = stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n\n //We can only fit a certain amount in each websocket frame, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n\n const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n\n //Send the length header\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n }\n\n //Send the actual data in segments.\n for (let i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n }\n\n private shutdown_() {\n this.isClosed_ = true;\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n }\n\n private onClosed_() {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_();\n\n // since this is an internal close, trigger the close listener\n if (this.onDisconnect) {\n this.onDisconnect(this.everConnected_);\n this.onDisconnect = null;\n }\n }\n }\n\n /**\n * External-facing close handler.\n * Close the websocket and kill the connection.\n */\n close() {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n }\n\n /**\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\n * the last activity.\n */\n resetKeepAlive() {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(() => {\n //If there has been no websocket activity for a while, send a no-op\n if (this.mySock) {\n this.sendString_('0');\n }\n this.resetKeepAlive();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL)) as any;\n }\n\n /**\n * Send a string over the websocket.\n *\n * @param str - String to send.\n */\n private sendString_(str: string) {\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n // calls for some unknown reason. We treat these as an error and disconnect.\n // See https://app.asana.com/0/58926111402292/68021340250410\n try {\n this.mySock.send(str);\n } catch (e) {\n this.log_(\n 'Exception thrown from WebSocket.send():',\n e.message || e.data,\n 'Closing connection.'\n );\n setTimeout(this.onClosed_.bind(this), 0);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../core/RepoInfo';\nimport { warn } from '../core/util/util';\n\nimport { BrowserPollConnection } from './BrowserPollConnection';\nimport { TransportConstructor } from './Transport';\nimport { WebSocketConnection } from './WebSocketConnection';\n\n/**\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\n * lifecycle.\n *\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\n * they are available.\n */\nexport class TransportManager {\n private transports_: TransportConstructor[];\n\n // Keeps track of whether the TransportManager has already chosen a transport to use\n static globalTransportInitialized_ = false;\n\n static get ALL_TRANSPORTS() {\n return [BrowserPollConnection, WebSocketConnection];\n }\n\n /**\n * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after\n * TransportManager has already set up transports_\n */\n static get IS_TRANSPORT_INITIALIZED() {\n return this.globalTransportInitialized_;\n }\n\n /**\n * @param repoInfo - Metadata around the namespace we're connecting to\n */\n constructor(repoInfo: RepoInfo) {\n this.initTransports_(repoInfo);\n }\n\n private initTransports_(repoInfo: RepoInfo) {\n const isWebSocketsAvailable: boolean =\n WebSocketConnection && WebSocketConnection['isAvailable']();\n let isSkipPollConnection =\n isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();\n\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable) {\n warn(\n \"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\"\n );\n }\n\n isSkipPollConnection = true;\n }\n\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection];\n } else {\n const transports = (this.transports_ = [] as TransportConstructor[]);\n for (const transport of TransportManager.ALL_TRANSPORTS) {\n if (transport && transport['isAvailable']()) {\n transports.push(transport);\n }\n }\n TransportManager.globalTransportInitialized_ = true;\n }\n }\n\n /**\n * @returns The constructor for the initial transport to use\n */\n initialTransport(): TransportConstructor {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n } else {\n throw new Error('No transports available');\n }\n }\n\n /**\n * @returns The constructor for the next transport, or null\n */\n upgradeTransport(): TransportConstructor | null {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n } else {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../core/RepoInfo';\nimport { PersistentStorage } from '../core/storage/storage';\nimport { Indexable } from '../core/util/misc';\nimport {\n error,\n logWrapper,\n requireKey,\n setTimeoutNonBlocking,\n warn\n} from '../core/util/util';\n\nimport { PROTOCOL_VERSION } from './Constants';\nimport { Transport, TransportConstructor } from './Transport';\nimport { TransportManager } from './TransportManager';\n\n// Abort upgrade attempt if it takes longer than 60s.\nconst UPGRADE_TIMEOUT = 60000;\n\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\nconst DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\n\n// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\n// but we've sent/received enough bytes, we don't cancel the connection.\nconst BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\nconst BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\n\nconst enum RealtimeState {\n CONNECTING,\n CONNECTED,\n DISCONNECTED\n}\n\nconst MESSAGE_TYPE = 't';\nconst MESSAGE_DATA = 'd';\nconst CONTROL_SHUTDOWN = 's';\nconst CONTROL_RESET = 'r';\nconst CONTROL_ERROR = 'e';\nconst CONTROL_PONG = 'o';\nconst SWITCH_ACK = 'a';\nconst END_TRANSMISSION = 'n';\nconst PING = 'p';\n\nconst SERVER_HELLO = 'h';\n\n/**\n * Creates a new real-time connection to the server using whichever method works\n * best in the current browser.\n */\nexport class Connection {\n connectionCount = 0;\n pendingDataMessages: unknown[] = [];\n sessionId: string;\n\n private conn_: Transport;\n private healthyTimeout_: number;\n private isHealthy_: boolean;\n private log_: (...args: unknown[]) => void;\n private primaryResponsesRequired_: number;\n private rx_: Transport;\n private secondaryConn_: Transport;\n private secondaryResponsesRequired_: number;\n private state_ = RealtimeState.CONNECTING;\n private transportManager_: TransportManager;\n private tx_: Transport;\n\n /**\n * @param id - an id for this connection\n * @param repoInfo_ - the info for the endpoint to connect to\n * @param applicationId_ - the Firebase App ID for this project\n * @param appCheckToken_ - The App Check Token for this device.\n * @param authToken_ - The auth token for this session.\n * @param onMessage_ - the callback to be triggered when a server-push message arrives\n * @param onReady_ - the callback to be triggered when this connection is ready to send messages.\n * @param onDisconnect_ - the callback to be triggered when a connection was lost\n * @param onKill_ - the callback to be triggered when this connection has permanently shut down.\n * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\n */\n constructor(\n public id: string,\n private repoInfo_: RepoInfo,\n private applicationId_: string | undefined,\n private appCheckToken_: string | undefined,\n private authToken_: string | undefined,\n private onMessage_: (a: {}) => void,\n private onReady_: (a: number, b: string) => void,\n private onDisconnect_: () => void,\n private onKill_: (a: string) => void,\n public lastSessionId?: string\n ) {\n this.log_ = logWrapper('c:' + this.id + ':');\n this.transportManager_ = new TransportManager(repoInfo_);\n this.log_('Connection created');\n this.start_();\n }\n\n /**\n * Starts a connection attempt\n */\n private start_(): void {\n const conn = this.transportManager_.initialTransport();\n this.conn_ = new conn(\n this.nextTransportId_(),\n this.repoInfo_,\n this.applicationId_,\n this.appCheckToken_,\n this.authToken_,\n null,\n this.lastSessionId\n );\n\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\n\n const onMessageReceived = this.connReceiver_(this.conn_);\n const onConnectionLost = this.disconnReceiver_(this.conn_);\n this.tx_ = this.conn_;\n this.rx_ = this.conn_;\n this.secondaryConn_ = null;\n this.isHealthy_ = false;\n\n /*\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\n * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\n * still have the context of your originating frame.\n */\n setTimeout(() => {\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\n this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);\n }, Math.floor(0));\n\n const healthyTimeoutMS = conn['healthyTimeout'] || 0;\n if (healthyTimeoutMS > 0) {\n this.healthyTimeout_ = setTimeoutNonBlocking(() => {\n this.healthyTimeout_ = null;\n if (!this.isHealthy_) {\n if (\n this.conn_ &&\n this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE\n ) {\n this.log_(\n 'Connection exceeded healthy timeout but has received ' +\n this.conn_.bytesReceived +\n ' bytes. Marking connection healthy.'\n );\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n } else if (\n this.conn_ &&\n this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE\n ) {\n this.log_(\n 'Connection exceeded healthy timeout but has sent ' +\n this.conn_.bytesSent +\n ' bytes. Leaving connection alive.'\n );\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\n // the server.\n } else {\n this.log_('Closing unhealthy connection after timeout.');\n this.close();\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(healthyTimeoutMS)) as any;\n }\n }\n\n private nextTransportId_(): string {\n return 'c:' + this.id + ':' + this.connectionCount++;\n }\n\n private disconnReceiver_(conn) {\n return everConnected => {\n if (conn === this.conn_) {\n this.onConnectionLost_(everConnected);\n } else if (conn === this.secondaryConn_) {\n this.log_('Secondary connection lost.');\n this.onSecondaryConnectionLost_();\n } else {\n this.log_('closing an old connection');\n }\n };\n }\n\n private connReceiver_(conn: Transport) {\n return (message: Indexable) => {\n if (this.state_ !== RealtimeState.DISCONNECTED) {\n if (conn === this.rx_) {\n this.onPrimaryMessageReceived_(message);\n } else if (conn === this.secondaryConn_) {\n this.onSecondaryMessageReceived_(message);\n } else {\n this.log_('message on old connection');\n }\n }\n };\n }\n\n /**\n * @param dataMsg - An arbitrary data message to be sent to the server\n */\n sendRequest(dataMsg: object) {\n // wrap in a data message envelope and send it on\n const msg = { t: 'd', d: dataMsg };\n this.sendData_(msg);\n }\n\n tryCleanupConnection() {\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\n this.log_(\n 'cleaning up and promoting a connection: ' + this.secondaryConn_.connId\n );\n this.conn_ = this.secondaryConn_;\n this.secondaryConn_ = null;\n // the server will shutdown the old connection\n }\n }\n\n private onSecondaryControl_(controlData: { [k: string]: unknown }) {\n if (MESSAGE_TYPE in controlData) {\n const cmd = controlData[MESSAGE_TYPE] as string;\n if (cmd === SWITCH_ACK) {\n this.upgradeIfSecondaryHealthy_();\n } else if (cmd === CONTROL_RESET) {\n // Most likely the session wasn't valid. Abandon the switch attempt\n this.log_('Got a reset on secondary, closing it');\n this.secondaryConn_.close();\n // If we were already using this connection for something, than we need to fully close\n if (\n this.tx_ === this.secondaryConn_ ||\n this.rx_ === this.secondaryConn_\n ) {\n this.close();\n }\n } else if (cmd === CONTROL_PONG) {\n this.log_('got pong on secondary.');\n this.secondaryResponsesRequired_--;\n this.upgradeIfSecondaryHealthy_();\n }\n }\n }\n\n private onSecondaryMessageReceived_(parsedData: Indexable) {\n const layer: string = requireKey('t', parsedData) as string;\n const data: unknown = requireKey('d', parsedData);\n if (layer === 'c') {\n this.onSecondaryControl_(data as Indexable);\n } else if (layer === 'd') {\n // got a data message, but we're still second connection. Need to buffer it up\n this.pendingDataMessages.push(data);\n } else {\n throw new Error('Unknown protocol layer: ' + layer);\n }\n }\n\n private upgradeIfSecondaryHealthy_() {\n if (this.secondaryResponsesRequired_ <= 0) {\n this.log_('Secondary connection is healthy.');\n this.isHealthy_ = true;\n this.secondaryConn_.markConnectionHealthy();\n this.proceedWithUpgrade_();\n } else {\n // Send a ping to make sure the connection is healthy.\n this.log_('sending ping on secondary.');\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\n }\n }\n\n private proceedWithUpgrade_() {\n // tell this connection to consider itself open\n this.secondaryConn_.start();\n // send ack\n this.log_('sending client ack on secondary');\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\n\n // send end packet on primary transport, switch to sending on this one\n // can receive on this one, buffer responses until end received on primary transport\n this.log_('Ending transmission on primary');\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\n this.tx_ = this.secondaryConn_;\n\n this.tryCleanupConnection();\n }\n\n private onPrimaryMessageReceived_(parsedData: { [k: string]: unknown }) {\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\n const layer: string = requireKey('t', parsedData) as string;\n const data: unknown = requireKey('d', parsedData);\n if (layer === 'c') {\n this.onControl_(data as { [k: string]: unknown });\n } else if (layer === 'd') {\n this.onDataMessage_(data);\n }\n }\n\n private onDataMessage_(message: unknown) {\n this.onPrimaryResponse_();\n\n // We don't do anything with data messages, just kick them up a level\n this.onMessage_(message);\n }\n\n private onPrimaryResponse_() {\n if (!this.isHealthy_) {\n this.primaryResponsesRequired_--;\n if (this.primaryResponsesRequired_ <= 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n }\n }\n }\n\n private onControl_(controlData: { [k: string]: unknown }) {\n const cmd: string = requireKey(MESSAGE_TYPE, controlData) as string;\n if (MESSAGE_DATA in controlData) {\n const payload = controlData[MESSAGE_DATA];\n if (cmd === SERVER_HELLO) {\n const handshakePayload = {\n ...(payload as {\n ts: number;\n v: string;\n h: string;\n s: string;\n })\n };\n if (this.repoInfo_.isUsingEmulator) {\n // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes.\n handshakePayload.h = this.repoInfo_.host;\n }\n this.onHandshake_(handshakePayload);\n } else if (cmd === END_TRANSMISSION) {\n this.log_('recvd end transmission on primary');\n this.rx_ = this.secondaryConn_;\n for (let i = 0; i < this.pendingDataMessages.length; ++i) {\n this.onDataMessage_(this.pendingDataMessages[i]);\n }\n this.pendingDataMessages = [];\n this.tryCleanupConnection();\n } else if (cmd === CONTROL_SHUTDOWN) {\n // This was previously the 'onKill' callback passed to the lower-level connection\n // payload in this case is the reason for the shutdown. Generally a human-readable error\n this.onConnectionShutdown_(payload as string);\n } else if (cmd === CONTROL_RESET) {\n // payload in this case is the host we should contact\n this.onReset_(payload as string);\n } else if (cmd === CONTROL_ERROR) {\n error('Server Error: ' + payload);\n } else if (cmd === CONTROL_PONG) {\n this.log_('got pong on primary.');\n this.onPrimaryResponse_();\n this.sendPingOnPrimaryIfNecessary_();\n } else {\n error('Unknown control packet command: ' + cmd);\n }\n }\n }\n\n /**\n * @param handshake - The handshake data returned from the server\n */\n private onHandshake_(handshake: {\n ts: number;\n v: string;\n h: string;\n s: string;\n }): void {\n const timestamp = handshake.ts;\n const version = handshake.v;\n const host = handshake.h;\n this.sessionId = handshake.s;\n this.repoInfo_.host = host;\n // if we've already closed the connection, then don't bother trying to progress further\n if (this.state_ === RealtimeState.CONNECTING) {\n this.conn_.start();\n this.onConnectionEstablished_(this.conn_, timestamp);\n if (PROTOCOL_VERSION !== version) {\n warn('Protocol version mismatch detected');\n }\n // TODO: do we want to upgrade? when? maybe a delay?\n this.tryStartUpgrade_();\n }\n }\n\n private tryStartUpgrade_() {\n const conn = this.transportManager_.upgradeTransport();\n if (conn) {\n this.startUpgrade_(conn);\n }\n }\n\n private startUpgrade_(conn: TransportConstructor) {\n this.secondaryConn_ = new conn(\n this.nextTransportId_(),\n this.repoInfo_,\n this.applicationId_,\n this.appCheckToken_,\n this.authToken_,\n this.sessionId\n );\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.secondaryResponsesRequired_ =\n conn['responsesRequiredToBeHealthy'] || 0;\n\n const onMessage = this.connReceiver_(this.secondaryConn_);\n const onDisconnect = this.disconnReceiver_(this.secondaryConn_);\n this.secondaryConn_.open(onMessage, onDisconnect);\n\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\n setTimeoutNonBlocking(() => {\n if (this.secondaryConn_) {\n this.log_('Timed out trying to upgrade.');\n this.secondaryConn_.close();\n }\n }, Math.floor(UPGRADE_TIMEOUT));\n }\n\n private onReset_(host: string) {\n this.log_('Reset packet received. New host: ' + host);\n this.repoInfo_.host = host;\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\n // We don't currently support resets after the connection has already been established\n if (this.state_ === RealtimeState.CONNECTED) {\n this.close();\n } else {\n // Close whatever connections we have open and start again.\n this.closeConnections_();\n this.start_();\n }\n }\n\n private onConnectionEstablished_(conn: Transport, timestamp: number) {\n this.log_('Realtime connection established.');\n this.conn_ = conn;\n this.state_ = RealtimeState.CONNECTED;\n\n if (this.onReady_) {\n this.onReady_(timestamp, this.sessionId);\n this.onReady_ = null;\n }\n\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\n // send some pings.\n if (this.primaryResponsesRequired_ === 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n } else {\n setTimeoutNonBlocking(() => {\n this.sendPingOnPrimaryIfNecessary_();\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\n }\n }\n\n private sendPingOnPrimaryIfNecessary_() {\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\n if (!this.isHealthy_ && this.state_ === RealtimeState.CONNECTED) {\n this.log_('sending ping on primary.');\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\n }\n }\n\n private onSecondaryConnectionLost_() {\n const conn = this.secondaryConn_;\n this.secondaryConn_ = null;\n if (this.tx_ === conn || this.rx_ === conn) {\n // we are relying on this connection already in some capacity. Therefore, a failure is real\n this.close();\n }\n }\n\n /**\n * @param everConnected - Whether or not the connection ever reached a server. Used to determine if\n * we should flush the host cache\n */\n private onConnectionLost_(everConnected: boolean) {\n this.conn_ = null;\n\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\n if (!everConnected && this.state_ === RealtimeState.CONNECTING) {\n this.log_('Realtime connection failed.');\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\n if (this.repoInfo_.isCacheableHost()) {\n PersistentStorage.remove('host:' + this.repoInfo_.host);\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\n this.repoInfo_.internalHost = this.repoInfo_.host;\n }\n } else if (this.state_ === RealtimeState.CONNECTED) {\n this.log_('Realtime connection lost.');\n }\n\n this.close();\n }\n\n private onConnectionShutdown_(reason: string) {\n this.log_('Connection shutdown command received. Shutting down...');\n\n if (this.onKill_) {\n this.onKill_(reason);\n this.onKill_ = null;\n }\n\n // We intentionally don't want to fire onDisconnect (kill is a different case),\n // so clear the callback.\n this.onDisconnect_ = null;\n\n this.close();\n }\n\n private sendData_(data: object) {\n if (this.state_ !== RealtimeState.CONNECTED) {\n throw 'Connection is not connected';\n } else {\n this.tx_.send(data);\n }\n }\n\n /**\n * Cleans up this connection, calling the appropriate callbacks\n */\n close() {\n if (this.state_ !== RealtimeState.DISCONNECTED) {\n this.log_('Closing realtime connection.');\n this.state_ = RealtimeState.DISCONNECTED;\n\n this.closeConnections_();\n\n if (this.onDisconnect_) {\n this.onDisconnect_();\n this.onDisconnect_ = null;\n }\n }\n }\n\n private closeConnections_() {\n this.log_('Shutting down all connections');\n if (this.conn_) {\n this.conn_.close();\n this.conn_ = null;\n }\n\n if (this.secondaryConn_) {\n this.secondaryConn_.close();\n this.secondaryConn_ = null;\n }\n\n if (this.healthyTimeout_) {\n clearTimeout(this.healthyTimeout_);\n this.healthyTimeout_ = null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QueryContext } from './view/EventRegistration';\n\n/**\n * Interface defining the set of actions that can be performed against the Firebase server\n * (basically corresponds to our wire protocol).\n *\n * @interface\n */\nexport abstract class ServerActions {\n abstract listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ): void;\n\n /**\n * Remove a listen.\n */\n abstract unlisten(query: QueryContext, tag: number | null): void;\n\n /**\n * Get the server value satisfying this query.\n */\n abstract get(query: QueryContext): Promise;\n\n put(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void,\n hash?: string\n ) {}\n\n merge(\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {}\n\n /**\n * Refreshes the auth token for the current connection.\n * @param token - The authentication token\n */\n refreshAuthToken(token: string) {}\n\n /**\n * Refreshes the app check token for the current connection.\n * @param token The app check token\n */\n refreshAppCheckToken(token: string) {}\n\n onDisconnectPut(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n onDisconnectMerge(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n onDisconnectCancel(\n pathString: string,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n reportStats(stats: { [k: string]: unknown }) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\n/**\n * Base class to be used if you want to emit events. Call the constructor with\n * the set of allowed event names.\n */\nexport abstract class EventEmitter {\n private listeners_: {\n [eventType: string]: Array<{\n callback(...args: unknown[]): void;\n context: unknown;\n }>;\n } = {};\n\n constructor(private allowedEvents_: string[]) {\n assert(\n Array.isArray(allowedEvents_) && allowedEvents_.length > 0,\n 'Requires a non-empty array'\n );\n }\n\n /**\n * To be overridden by derived classes in order to fire an initial event when\n * somebody subscribes for data.\n *\n * @returns {Array.<*>} Array of parameters to trigger initial event with.\n */\n abstract getInitialEvent(eventType: string): unknown[];\n\n /**\n * To be called by derived classes to trigger events.\n */\n protected trigger(eventType: string, ...varArgs: unknown[]) {\n if (Array.isArray(this.listeners_[eventType])) {\n // Clone the list, since callbacks could add/remove listeners.\n const listeners = [...this.listeners_[eventType]];\n\n for (let i = 0; i < listeners.length; i++) {\n listeners[i].callback.apply(listeners[i].context, varArgs);\n }\n }\n }\n\n on(eventType: string, callback: (a: unknown) => void, context: unknown) {\n this.validateEventType_(eventType);\n this.listeners_[eventType] = this.listeners_[eventType] || [];\n this.listeners_[eventType].push({ callback, context });\n\n const eventData = this.getInitialEvent(eventType);\n if (eventData) {\n callback.apply(context, eventData);\n }\n }\n\n off(eventType: string, callback: (a: unknown) => void, context: unknown) {\n this.validateEventType_(eventType);\n const listeners = this.listeners_[eventType] || [];\n for (let i = 0; i < listeners.length; i++) {\n if (\n listeners[i].callback === callback &&\n (!context || context === listeners[i].context)\n ) {\n listeners.splice(i, 1);\n return;\n }\n }\n }\n\n private validateEventType_(eventType: string) {\n assert(\n this.allowedEvents_.find(et => {\n return et === eventType;\n }),\n 'Unknown event: ' + eventType\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, isMobileCordova } from '@firebase/util';\n\nimport { EventEmitter } from './EventEmitter';\n\n/**\n * Monitors online state (as reported by window.online/offline events).\n *\n * The expectation is that this could have many false positives (thinks we are online\n * when we're not), but no false negatives. So we can safely use it to determine when\n * we definitely cannot reach the internet.\n */\nexport class OnlineMonitor extends EventEmitter {\n private online_ = true;\n\n static getInstance() {\n return new OnlineMonitor();\n }\n\n constructor() {\n super(['online']);\n\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\n // It would seem that the 'online' event does not always fire consistently. So we disable it\n // for Cordova.\n if (\n typeof window !== 'undefined' &&\n typeof window.addEventListener !== 'undefined' &&\n !isMobileCordova()\n ) {\n window.addEventListener(\n 'online',\n () => {\n if (!this.online_) {\n this.online_ = true;\n this.trigger('online', true);\n }\n },\n false\n );\n\n window.addEventListener(\n 'offline',\n () => {\n if (this.online_) {\n this.online_ = false;\n this.trigger('online', false);\n }\n },\n false\n );\n }\n }\n\n getInitialEvent(eventType: string): boolean[] {\n assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n }\n\n currentlyOnline(): boolean {\n return this.online_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { stringLength } from '@firebase/util';\n\nimport { nameCompare } from './util';\n\n/** Maximum key depth. */\nconst MAX_PATH_DEPTH = 32;\n\n/** Maximum number of (UTF8) bytes in a Firebase path. */\nconst MAX_PATH_LENGTH_BYTES = 768;\n\n/**\n * An immutable object representing a parsed path. It's immutable so that you\n * can pass them around to other functions without worrying about them changing\n * it.\n */\n\nexport class Path {\n pieces_: string[];\n pieceNum_: number;\n\n /**\n * @param pathOrString - Path string to parse, or another path, or the raw\n * tokens array\n */\n constructor(pathOrString: string | string[], pieceNum?: number) {\n if (pieceNum === void 0) {\n this.pieces_ = (pathOrString as string).split('/');\n\n // Remove empty pieces.\n let copyTo = 0;\n for (let i = 0; i < this.pieces_.length; i++) {\n if (this.pieces_[i].length > 0) {\n this.pieces_[copyTo] = this.pieces_[i];\n copyTo++;\n }\n }\n this.pieces_.length = copyTo;\n\n this.pieceNum_ = 0;\n } else {\n this.pieces_ = pathOrString as string[];\n this.pieceNum_ = pieceNum;\n }\n }\n\n toString(): string {\n let pathString = '';\n for (let i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '') {\n pathString += '/' + this.pieces_[i];\n }\n }\n\n return pathString || '/';\n }\n}\n\nexport function newEmptyPath(): Path {\n return new Path('');\n}\n\nexport function pathGetFront(path: Path): string | null {\n if (path.pieceNum_ >= path.pieces_.length) {\n return null;\n }\n\n return path.pieces_[path.pieceNum_];\n}\n\n/**\n * @returns The number of segments in this path\n */\nexport function pathGetLength(path: Path): number {\n return path.pieces_.length - path.pieceNum_;\n}\n\nexport function pathPopFront(path: Path): Path {\n let pieceNum = path.pieceNum_;\n if (pieceNum < path.pieces_.length) {\n pieceNum++;\n }\n return new Path(path.pieces_, pieceNum);\n}\n\nexport function pathGetBack(path: Path): string | null {\n if (path.pieceNum_ < path.pieces_.length) {\n return path.pieces_[path.pieces_.length - 1];\n }\n\n return null;\n}\n\nexport function pathToUrlEncodedString(path: Path): string {\n let pathString = '';\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\n if (path.pieces_[i] !== '') {\n pathString += '/' + encodeURIComponent(String(path.pieces_[i]));\n }\n }\n\n return pathString || '/';\n}\n\n/**\n * Shallow copy of the parts of the path.\n *\n */\nexport function pathSlice(path: Path, begin: number = 0): string[] {\n return path.pieces_.slice(path.pieceNum_ + begin);\n}\n\nexport function pathParent(path: Path): Path | null {\n if (path.pieceNum_ >= path.pieces_.length) {\n return null;\n }\n\n const pieces = [];\n for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {\n pieces.push(path.pieces_[i]);\n }\n\n return new Path(pieces, 0);\n}\n\nexport function pathChild(path: Path, childPathObj: string | Path): Path {\n const pieces = [];\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\n pieces.push(path.pieces_[i]);\n }\n\n if (childPathObj instanceof Path) {\n for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\n pieces.push(childPathObj.pieces_[i]);\n }\n } else {\n const childPieces = childPathObj.split('/');\n for (let i = 0; i < childPieces.length; i++) {\n if (childPieces[i].length > 0) {\n pieces.push(childPieces[i]);\n }\n }\n }\n\n return new Path(pieces, 0);\n}\n\n/**\n * @returns True if there are no segments in this path\n */\nexport function pathIsEmpty(path: Path): boolean {\n return path.pieceNum_ >= path.pieces_.length;\n}\n\n/**\n * @returns The path from outerPath to innerPath\n */\nexport function newRelativePath(outerPath: Path, innerPath: Path): Path {\n const outer = pathGetFront(outerPath),\n inner = pathGetFront(innerPath);\n if (outer === null) {\n return innerPath;\n } else if (outer === inner) {\n return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));\n } else {\n throw new Error(\n 'INTERNAL ERROR: innerPath (' +\n innerPath +\n ') is not within ' +\n 'outerPath (' +\n outerPath +\n ')'\n );\n }\n}\n\n/**\n * @returns -1, 0, 1 if left is less, equal, or greater than the right.\n */\nexport function pathCompare(left: Path, right: Path): number {\n const leftKeys = pathSlice(left, 0);\n const rightKeys = pathSlice(right, 0);\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\n const cmp = nameCompare(leftKeys[i], rightKeys[i]);\n if (cmp !== 0) {\n return cmp;\n }\n }\n if (leftKeys.length === rightKeys.length) {\n return 0;\n }\n return leftKeys.length < rightKeys.length ? -1 : 1;\n}\n\n/**\n * @returns true if paths are the same.\n */\nexport function pathEquals(path: Path, other: Path): boolean {\n if (pathGetLength(path) !== pathGetLength(other)) {\n return false;\n }\n\n for (\n let i = path.pieceNum_, j = other.pieceNum_;\n i <= path.pieces_.length;\n i++, j++\n ) {\n if (path.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * @returns True if this path is a parent of (or the same as) other\n */\nexport function pathContains(path: Path, other: Path): boolean {\n let i = path.pieceNum_;\n let j = other.pieceNum_;\n if (pathGetLength(path) > pathGetLength(other)) {\n return false;\n }\n while (i < path.pieces_.length) {\n if (path.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n ++i;\n ++j;\n }\n return true;\n}\n\n/**\n * Dynamic (mutable) path used to count path lengths.\n *\n * This class is used to efficiently check paths for valid\n * length (in UTF8 bytes) and depth (used in path validation).\n *\n * Throws Error exception if path is ever invalid.\n *\n * The definition of a path always begins with '/'.\n */\nexport class ValidationPath {\n parts_: string[];\n /** Initialize to number of '/' chars needed in path. */\n byteLength_: number;\n\n /**\n * @param path - Initial Path.\n * @param errorPrefix_ - Prefix for any error messages.\n */\n constructor(path: Path, public errorPrefix_: string) {\n this.parts_ = pathSlice(path, 0);\n /** Initialize to number of '/' chars needed in path. */\n this.byteLength_ = Math.max(1, this.parts_.length);\n\n for (let i = 0; i < this.parts_.length; i++) {\n this.byteLength_ += stringLength(this.parts_[i]);\n }\n validationPathCheckValid(this);\n }\n}\n\nexport function validationPathPush(\n validationPath: ValidationPath,\n child: string\n): void {\n // Count the needed '/'\n if (validationPath.parts_.length > 0) {\n validationPath.byteLength_ += 1;\n }\n validationPath.parts_.push(child);\n validationPath.byteLength_ += stringLength(child);\n validationPathCheckValid(validationPath);\n}\n\nexport function validationPathPop(validationPath: ValidationPath): void {\n const last = validationPath.parts_.pop();\n validationPath.byteLength_ -= stringLength(last);\n // Un-count the previous '/'\n if (validationPath.parts_.length > 0) {\n validationPath.byteLength_ -= 1;\n }\n}\n\nfunction validationPathCheckValid(validationPath: ValidationPath): void {\n if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {\n throw new Error(\n validationPath.errorPrefix_ +\n 'has a key path longer than ' +\n MAX_PATH_LENGTH_BYTES +\n ' bytes (' +\n validationPath.byteLength_ +\n ').'\n );\n }\n if (validationPath.parts_.length > MAX_PATH_DEPTH) {\n throw new Error(\n validationPath.errorPrefix_ +\n 'path specified exceeds the maximum depth that can be written (' +\n MAX_PATH_DEPTH +\n ') or object contains a cycle ' +\n validationPathToErrorString(validationPath)\n );\n }\n}\n\n/**\n * String for use in error messages - uses '.' notation for path.\n */\nexport function validationPathToErrorString(\n validationPath: ValidationPath\n): string {\n if (validationPath.parts_.length === 0) {\n return '';\n }\n return \"in property '\" + validationPath.parts_.join('.') + \"'\";\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { EventEmitter } from './EventEmitter';\n\ndeclare const document: Document;\n\nexport class VisibilityMonitor extends EventEmitter {\n private visible_: boolean;\n\n static getInstance() {\n return new VisibilityMonitor();\n }\n\n constructor() {\n super(['visible']);\n let hidden: string;\n let visibilityChange: string;\n if (\n typeof document !== 'undefined' &&\n typeof document.addEventListener !== 'undefined'\n ) {\n if (typeof document['hidden'] !== 'undefined') {\n // Opera 12.10 and Firefox 18 and later support\n visibilityChange = 'visibilitychange';\n hidden = 'hidden';\n } else if (typeof document['mozHidden'] !== 'undefined') {\n visibilityChange = 'mozvisibilitychange';\n hidden = 'mozHidden';\n } else if (typeof document['msHidden'] !== 'undefined') {\n visibilityChange = 'msvisibilitychange';\n hidden = 'msHidden';\n } else if (typeof document['webkitHidden'] !== 'undefined') {\n visibilityChange = 'webkitvisibilitychange';\n hidden = 'webkitHidden';\n }\n }\n\n // Initially, we always assume we are visible. This ensures that in browsers\n // without page visibility support or in cases where we are never visible\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n // reconnects\n this.visible_ = true;\n\n if (visibilityChange) {\n document.addEventListener(\n visibilityChange,\n () => {\n const visible = !document[hidden];\n if (visible !== this.visible_) {\n this.visible_ = visible;\n this.trigger('visible', visible);\n }\n },\n false\n );\n }\n }\n\n getInitialEvent(eventType: string): boolean[] {\n assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n contains,\n Deferred,\n isEmpty,\n isMobileCordova,\n isNodeSdk,\n isReactNative,\n isValidFormat,\n safeGet,\n stringify,\n isAdmin\n} from '@firebase/util';\n\nimport { Connection } from '../realtime/Connection';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { OnlineMonitor } from './util/OnlineMonitor';\nimport { Path } from './util/Path';\nimport { error, log, logWrapper, warn, ObjectToUniqueKey } from './util/util';\nimport { VisibilityMonitor } from './util/VisibilityMonitor';\nimport { SDK_VERSION } from './version';\nimport { QueryContext } from './view/EventRegistration';\n\nconst RECONNECT_MIN_DELAY = 1000;\nconst RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\nconst RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\nconst RECONNECT_DELAY_MULTIPLIER = 1.3;\nconst RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\nconst SERVER_KILL_INTERRUPT_REASON = 'server_kill';\n\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\nconst INVALID_TOKEN_THRESHOLD = 3;\n\ninterface ListenSpec {\n onComplete(s: string, p?: unknown): void;\n\n hashFn(): string;\n\n query: QueryContext;\n tag: number | null;\n}\n\ninterface OnDisconnectRequest {\n pathString: string;\n action: string;\n data: unknown;\n onComplete?: (a: string, b: string) => void;\n}\n\ninterface OutstandingPut {\n action: string;\n request: object;\n queued?: boolean;\n onComplete: (a: string, b?: string) => void;\n}\n\ninterface OutstandingGet {\n request: object;\n onComplete: (response: { [k: string]: unknown }) => void;\n}\n\n/**\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\n *\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\n * in quotes to make sure the closure compiler does not minify them.\n */\nexport class PersistentConnection extends ServerActions {\n // Used for diagnostic logging.\n id = PersistentConnection.nextPersistentConnectionId_++;\n private log_ = logWrapper('p:' + this.id + ':');\n\n private interruptReasons_: { [reason: string]: boolean } = {};\n private readonly listens: Map<\n /* path */ string,\n Map\n > = new Map();\n private outstandingPuts_: OutstandingPut[] = [];\n private outstandingGets_: OutstandingGet[] = [];\n private outstandingPutCount_ = 0;\n private outstandingGetCount_ = 0;\n private onDisconnectRequestQueue_: OnDisconnectRequest[] = [];\n private connected_ = false;\n private reconnectDelay_ = RECONNECT_MIN_DELAY;\n private maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\n private securityDebugCallback_: ((a: object) => void) | null = null;\n lastSessionId: string | null = null;\n\n private establishConnectionTimer_: number | null = null;\n\n private visible_: boolean = false;\n\n // Before we get connected, we keep a queue of pending messages to send.\n private requestCBHash_: { [k: number]: (a: unknown) => void } = {};\n private requestNumber_ = 0;\n\n private realtime_: {\n sendRequest(a: object): void;\n close(): void;\n } | null = null;\n\n private authToken_: string | null = null;\n private appCheckToken_: string | null = null;\n private forceTokenRefresh_ = false;\n private invalidAuthTokenCount_ = 0;\n private invalidAppCheckTokenCount_ = 0;\n\n private firstConnection_ = true;\n private lastConnectionAttemptTime_: number | null = null;\n private lastConnectionEstablishedTime_: number | null = null;\n\n private static nextPersistentConnectionId_ = 0;\n\n /**\n * Counter for number of connections created. Mainly used for tagging in the logs\n */\n private static nextConnectionId_ = 0;\n\n /**\n * @param repoInfo_ - Data about the namespace we are connecting to\n * @param applicationId_ - The Firebase App ID for this project\n * @param onDataUpdate_ - A callback for new data from the server\n */\n constructor(\n private repoInfo_: RepoInfo,\n private applicationId_: string,\n private onDataUpdate_: (\n a: string,\n b: unknown,\n c: boolean,\n d: number | null\n ) => void,\n private onConnectStatus_: (a: boolean) => void,\n private onServerInfoUpdate_: (a: unknown) => void,\n private authTokenProvider_: AuthTokenProvider,\n private appCheckTokenProvider_: AppCheckTokenProvider,\n private authOverride_?: object | null\n ) {\n super();\n\n if (authOverride_ && !isNodeSdk()) {\n throw new Error(\n 'Auth override specified in options, but not supported on non Node.js platforms'\n );\n }\n\n VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);\n\n if (repoInfo_.host.indexOf('fblocal') === -1) {\n OnlineMonitor.getInstance().on('online', this.onOnline_, this);\n }\n }\n\n protected sendRequest(\n action: string,\n body: unknown,\n onResponse?: (a: unknown) => void\n ) {\n const curReqNum = ++this.requestNumber_;\n\n const msg = { r: curReqNum, a: action, b: body };\n this.log_(stringify(msg));\n assert(\n this.connected_,\n \"sendRequest call when we're not connected not allowed.\"\n );\n this.realtime_.sendRequest(msg);\n if (onResponse) {\n this.requestCBHash_[curReqNum] = onResponse;\n }\n }\n\n get(query: QueryContext): Promise {\n this.initConnection_();\n\n const deferred = new Deferred();\n const request = {\n p: query._path.toString(),\n q: query._queryObject\n };\n const outstandingGet = {\n action: 'g',\n request,\n onComplete: (message: { [k: string]: unknown }) => {\n const payload = message['d'] as string;\n if (message['s'] === 'ok') {\n deferred.resolve(payload);\n } else {\n deferred.reject(payload);\n }\n }\n };\n this.outstandingGets_.push(outstandingGet);\n this.outstandingGetCount_++;\n const index = this.outstandingGets_.length - 1;\n\n if (this.connected_) {\n this.sendGet_(index);\n }\n\n return deferred.promise;\n }\n\n listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ) {\n this.initConnection_();\n\n const queryId = query._queryIdentifier;\n const pathString = query._path.toString();\n this.log_('Listen called for ' + pathString + ' ' + queryId);\n if (!this.listens.has(pathString)) {\n this.listens.set(pathString, new Map());\n }\n assert(\n query._queryParams.isDefault() || !query._queryParams.loadsAllData(),\n 'listen() called for non-default but complete query'\n );\n assert(\n !this.listens.get(pathString)!.has(queryId),\n `listen() called twice for same path/queryId.`\n );\n const listenSpec: ListenSpec = {\n onComplete,\n hashFn: currentHashFn,\n query,\n tag\n };\n this.listens.get(pathString)!.set(queryId, listenSpec);\n\n if (this.connected_) {\n this.sendListen_(listenSpec);\n }\n }\n\n private sendGet_(index: number) {\n const get = this.outstandingGets_[index];\n this.sendRequest('g', get.request, (message: { [k: string]: unknown }) => {\n delete this.outstandingGets_[index];\n this.outstandingGetCount_--;\n if (this.outstandingGetCount_ === 0) {\n this.outstandingGets_ = [];\n }\n if (get.onComplete) {\n get.onComplete(message);\n }\n });\n }\n\n private sendListen_(listenSpec: ListenSpec) {\n const query = listenSpec.query;\n const pathString = query._path.toString();\n const queryId = query._queryIdentifier;\n this.log_('Listen on ' + pathString + ' for ' + queryId);\n const req: { [k: string]: unknown } = { /*path*/ p: pathString };\n\n const action = 'q';\n\n // Only bother to send query if it's non-default.\n if (listenSpec.tag) {\n req['q'] = query._queryObject;\n req['t'] = listenSpec.tag;\n }\n\n req[/*hash*/ 'h'] = listenSpec.hashFn();\n\n this.sendRequest(action, req, (message: { [k: string]: unknown }) => {\n const payload: unknown = message[/*data*/ 'd'];\n const status = message[/*status*/ 's'] as string;\n\n // print warnings in any case...\n PersistentConnection.warnOnListenWarnings_(payload, query);\n\n const currentListenSpec =\n this.listens.get(pathString) &&\n this.listens.get(pathString)!.get(queryId);\n // only trigger actions if the listen hasn't been removed and readded\n if (currentListenSpec === listenSpec) {\n this.log_('listen response', message);\n\n if (status !== 'ok') {\n this.removeListen_(pathString, queryId);\n }\n\n if (listenSpec.onComplete) {\n listenSpec.onComplete(status, payload);\n }\n }\n });\n }\n\n private static warnOnListenWarnings_(payload: unknown, query: QueryContext) {\n if (payload && typeof payload === 'object' && contains(payload, 'w')) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const warnings = safeGet(payload as any, 'w');\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\n const indexSpec =\n '\".indexOn\": \"' + query._queryParams.getIndex().toString() + '\"';\n const indexPath = query._path.toString();\n warn(\n `Using an unspecified index. Your data will be downloaded and ` +\n `filtered on the client. Consider adding ${indexSpec} at ` +\n `${indexPath} to your security rules for better performance.`\n );\n }\n }\n }\n\n refreshAuthToken(token: string) {\n this.authToken_ = token;\n this.log_('Auth token refreshed');\n if (this.authToken_) {\n this.tryAuth();\n } else {\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\n //the credential so we dont become authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unauth', {}, () => {});\n }\n }\n\n this.reduceReconnectDelayIfAdminCredential_(token);\n }\n\n private reduceReconnectDelayIfAdminCredential_(credential: string) {\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\n const isFirebaseSecret = credential && credential.length === 40;\n if (isFirebaseSecret || isAdmin(credential)) {\n this.log_(\n 'Admin auth credential detected. Reducing max reconnect time.'\n );\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n }\n }\n\n refreshAppCheckToken(token: string | null) {\n this.appCheckToken_ = token;\n this.log_('App check token refreshed');\n if (this.appCheckToken_) {\n this.tryAppCheck();\n } else {\n //If we're connected we want to let the server know to unauthenticate us.\n //If we're not connected, simply delete the credential so we dont become\n // authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unappeck', {}, () => {});\n }\n }\n }\n\n /**\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\n * a auth revoked (the connection is closed).\n */\n tryAuth() {\n if (this.connected_ && this.authToken_) {\n const token = this.authToken_;\n const authMethod = isValidFormat(token) ? 'auth' : 'gauth';\n const requestData: { [k: string]: unknown } = { cred: token };\n if (this.authOverride_ === null) {\n requestData['noauth'] = true;\n } else if (typeof this.authOverride_ === 'object') {\n requestData['authvar'] = this.authOverride_;\n }\n this.sendRequest(\n authMethod,\n requestData,\n (res: { [k: string]: unknown }) => {\n const status = res[/*status*/ 's'] as string;\n const data = (res[/*data*/ 'd'] as string) || 'error';\n\n if (this.authToken_ === token) {\n if (status === 'ok') {\n this.invalidAuthTokenCount_ = 0;\n } else {\n // Triggers reconnect and force refresh for auth token\n this.onAuthRevoked_(status, data);\n }\n }\n }\n );\n }\n }\n\n /**\n * Attempts to authenticate with the given token. If the authentication\n * attempt fails, it's triggered like the token was revoked (the connection is\n * closed).\n */\n tryAppCheck() {\n if (this.connected_ && this.appCheckToken_) {\n this.sendRequest(\n 'appcheck',\n { 'token': this.appCheckToken_ },\n (res: { [k: string]: unknown }) => {\n const status = res[/*status*/ 's'] as string;\n const data = (res[/*data*/ 'd'] as string) || 'error';\n if (status === 'ok') {\n this.invalidAppCheckTokenCount_ = 0;\n } else {\n this.onAppCheckRevoked_(status, data);\n }\n }\n );\n }\n }\n\n /**\n * @inheritDoc\n */\n unlisten(query: QueryContext, tag: number | null) {\n const pathString = query._path.toString();\n const queryId = query._queryIdentifier;\n\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\n\n assert(\n query._queryParams.isDefault() || !query._queryParams.loadsAllData(),\n 'unlisten() called for non-default but complete query'\n );\n const listen = this.removeListen_(pathString, queryId);\n if (listen && this.connected_) {\n this.sendUnlisten_(pathString, queryId, query._queryObject, tag);\n }\n }\n\n private sendUnlisten_(\n pathString: string,\n queryId: string,\n queryObj: object,\n tag: number | null\n ) {\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\n\n const req: { [k: string]: unknown } = { /*path*/ p: pathString };\n const action = 'n';\n // Only bother sending queryId if it's non-default.\n if (tag) {\n req['q'] = queryObj;\n req['t'] = tag;\n }\n\n this.sendRequest(action, req);\n }\n\n onDisconnectPut(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\n\n if (this.connected_) {\n this.sendOnDisconnect_('o', pathString, data, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'o',\n data,\n onComplete\n });\n }\n }\n\n onDisconnectMerge(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\n\n if (this.connected_) {\n this.sendOnDisconnect_('om', pathString, data, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'om',\n data,\n onComplete\n });\n }\n }\n\n onDisconnectCancel(\n pathString: string,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\n\n if (this.connected_) {\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'oc',\n data: null,\n onComplete\n });\n }\n }\n\n private sendOnDisconnect_(\n action: string,\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string) => void\n ) {\n const request = { /*path*/ p: pathString, /*data*/ d: data };\n this.log_('onDisconnect ' + action, request);\n this.sendRequest(action, request, (response: { [k: string]: unknown }) => {\n if (onComplete) {\n setTimeout(() => {\n onComplete(\n response[/*status*/ 's'] as string,\n response[/* data */ 'd'] as string\n );\n }, Math.floor(0));\n }\n });\n }\n\n put(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void,\n hash?: string\n ) {\n this.putInternal('p', pathString, data, onComplete, hash);\n }\n\n merge(\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {\n this.putInternal('m', pathString, data, onComplete, hash);\n }\n\n putInternal(\n action: string,\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {\n this.initConnection_();\n\n const request: { [k: string]: unknown } = {\n /*path*/ p: pathString,\n /*data*/ d: data\n };\n\n if (hash !== undefined) {\n request[/*hash*/ 'h'] = hash;\n }\n\n // TODO: Only keep track of the most recent put for a given path?\n this.outstandingPuts_.push({\n action,\n request,\n onComplete\n });\n\n this.outstandingPutCount_++;\n const index = this.outstandingPuts_.length - 1;\n\n if (this.connected_) {\n this.sendPut_(index);\n } else {\n this.log_('Buffering put: ' + pathString);\n }\n }\n\n private sendPut_(index: number) {\n const action = this.outstandingPuts_[index].action;\n const request = this.outstandingPuts_[index].request;\n const onComplete = this.outstandingPuts_[index].onComplete;\n this.outstandingPuts_[index].queued = this.connected_;\n\n this.sendRequest(action, request, (message: { [k: string]: unknown }) => {\n this.log_(action + ' response', message);\n\n delete this.outstandingPuts_[index];\n this.outstandingPutCount_--;\n\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0) {\n this.outstandingPuts_ = [];\n }\n\n if (onComplete) {\n onComplete(\n message[/*status*/ 's'] as string,\n message[/* data */ 'd'] as string\n );\n }\n });\n }\n\n reportStats(stats: { [k: string]: unknown }) {\n // If we're not connected, we just drop the stats.\n if (this.connected_) {\n const request = { /*counters*/ c: stats };\n this.log_('reportStats', request);\n\n this.sendRequest(/*stats*/ 's', request, result => {\n const status = result[/*status*/ 's'];\n if (status !== 'ok') {\n const errorReason = result[/* data */ 'd'];\n this.log_('reportStats', 'Error sending stats: ' + errorReason);\n }\n });\n }\n }\n\n private onDataMessage_(message: { [k: string]: unknown }) {\n if ('r' in message) {\n // this is a response\n this.log_('from server: ' + stringify(message));\n const reqNum = message['r'] as string;\n const onResponse = this.requestCBHash_[reqNum];\n if (onResponse) {\n delete this.requestCBHash_[reqNum];\n onResponse(message[/*body*/ 'b']);\n }\n } else if ('error' in message) {\n throw 'A server-side error has occurred: ' + message['error'];\n } else if ('a' in message) {\n // a and b are action and body, respectively\n this.onDataPush_(message['a'] as string, message['b'] as {});\n }\n }\n\n private onDataPush_(action: string, body: { [k: string]: unknown }) {\n this.log_('handleServerMessage', action, body);\n if (action === 'd') {\n this.onDataUpdate_(\n body[/*path*/ 'p'] as string,\n body[/*data*/ 'd'],\n /*isMerge*/ false,\n body['t'] as number\n );\n } else if (action === 'm') {\n this.onDataUpdate_(\n body[/*path*/ 'p'] as string,\n body[/*data*/ 'd'],\n /*isMerge=*/ true,\n body['t'] as number\n );\n } else if (action === 'c') {\n this.onListenRevoked_(\n body[/*path*/ 'p'] as string,\n body[/*query*/ 'q'] as unknown[]\n );\n } else if (action === 'ac') {\n this.onAuthRevoked_(\n body[/*status code*/ 's'] as string,\n body[/* explanation */ 'd'] as string\n );\n } else if (action === 'apc') {\n this.onAppCheckRevoked_(\n body[/*status code*/ 's'] as string,\n body[/* explanation */ 'd'] as string\n );\n } else if (action === 'sd') {\n this.onSecurityDebugPacket_(body);\n } else {\n error(\n 'Unrecognized action received from server: ' +\n stringify(action) +\n '\\nAre you using the latest client?'\n );\n }\n }\n\n private onReady_(timestamp: number, sessionId: string) {\n this.log_('connection ready');\n this.connected_ = true;\n this.lastConnectionEstablishedTime_ = new Date().getTime();\n this.handleTimestamp_(timestamp);\n this.lastSessionId = sessionId;\n if (this.firstConnection_) {\n this.sendConnectStats_();\n }\n this.restoreState_();\n this.firstConnection_ = false;\n this.onConnectStatus_(true);\n }\n\n private scheduleConnect_(timeout: number) {\n assert(\n !this.realtime_,\n \"Scheduling a connect when we're already connected/ing?\"\n );\n\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n }\n\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\n\n this.establishConnectionTimer_ = setTimeout(() => {\n this.establishConnectionTimer_ = null;\n this.establishConnection_();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(timeout)) as any;\n }\n\n private initConnection_() {\n if (!this.realtime_ && this.firstConnection_) {\n this.scheduleConnect_(0);\n }\n }\n\n private onVisible_(visible: boolean) {\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\n if (\n visible &&\n !this.visible_ &&\n this.reconnectDelay_ === this.maxReconnectDelay_\n ) {\n this.log_('Window became visible. Reducing delay.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n this.visible_ = visible;\n }\n\n private onOnline_(online: boolean) {\n if (online) {\n this.log_('Browser went online.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n } else {\n this.log_('Browser went offline. Killing connection.');\n if (this.realtime_) {\n this.realtime_.close();\n }\n }\n }\n\n private onRealtimeDisconnect_() {\n this.log_('data client disconnected');\n this.connected_ = false;\n this.realtime_ = null;\n\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\n this.cancelSentTransactions_();\n\n // Clear out the pending requests.\n this.requestCBHash_ = {};\n\n if (this.shouldReconnect_()) {\n if (!this.visible_) {\n this.log_(\"Window isn't visible. Delaying reconnect.\");\n this.reconnectDelay_ = this.maxReconnectDelay_;\n this.lastConnectionAttemptTime_ = new Date().getTime();\n } else if (this.lastConnectionEstablishedTime_) {\n // If we've been connected long enough, reset reconnect delay to minimum.\n const timeSinceLastConnectSucceeded =\n new Date().getTime() - this.lastConnectionEstablishedTime_;\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n }\n this.lastConnectionEstablishedTime_ = null;\n }\n\n const timeSinceLastConnectAttempt = Math.max(\n 0,\n new Date().getTime() - this.lastConnectionAttemptTime_\n );\n let reconnectDelay = Math.max(\n 0,\n this.reconnectDelay_ - timeSinceLastConnectAttempt\n );\n reconnectDelay = Math.random() * reconnectDelay;\n\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\n this.scheduleConnect_(reconnectDelay);\n\n // Adjust reconnect delay for next time.\n this.reconnectDelay_ = Math.min(\n this.maxReconnectDelay_,\n this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER\n );\n }\n this.onConnectStatus_(false);\n }\n\n private async establishConnection_() {\n if (this.shouldReconnect_()) {\n this.log_('Making a connection attempt');\n this.lastConnectionAttemptTime_ = new Date().getTime();\n this.lastConnectionEstablishedTime_ = null;\n const onDataMessage = this.onDataMessage_.bind(this);\n const onReady = this.onReady_.bind(this);\n const onDisconnect = this.onRealtimeDisconnect_.bind(this);\n const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;\n const lastSessionId = this.lastSessionId;\n let canceled = false;\n let connection: Connection | null = null;\n const closeFn = function () {\n if (connection) {\n connection.close();\n } else {\n canceled = true;\n onDisconnect();\n }\n };\n const sendRequestFn = function (msg: object) {\n assert(\n connection,\n \"sendRequest call when we're not connected not allowed.\"\n );\n connection.sendRequest(msg);\n };\n\n this.realtime_ = {\n close: closeFn,\n sendRequest: sendRequestFn\n };\n\n const forceRefresh = this.forceTokenRefresh_;\n this.forceTokenRefresh_ = false;\n\n try {\n // First fetch auth and app check token, and establish connection after\n // fetching the token was successful\n const [authToken, appCheckToken] = await Promise.all([\n this.authTokenProvider_.getToken(forceRefresh),\n this.appCheckTokenProvider_.getToken(forceRefresh)\n ]);\n\n if (!canceled) {\n log('getToken() completed. Creating connection.');\n this.authToken_ = authToken && authToken.accessToken;\n this.appCheckToken_ = appCheckToken && appCheckToken.token;\n connection = new Connection(\n connId,\n this.repoInfo_,\n this.applicationId_,\n this.appCheckToken_,\n this.authToken_,\n onDataMessage,\n onReady,\n onDisconnect,\n /* onKill= */ reason => {\n warn(reason + ' (' + this.repoInfo_.toString() + ')');\n this.interrupt(SERVER_KILL_INTERRUPT_REASON);\n },\n lastSessionId\n );\n } else {\n log('getToken() completed but was canceled');\n }\n } catch (error) {\n this.log_('Failed to get token: ' + error);\n if (!canceled) {\n if (this.repoInfo_.nodeAdmin) {\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\n // But getToken() may also just have temporarily failed, so we still want to\n // continue retrying.\n warn(error);\n }\n closeFn();\n }\n }\n }\n }\n\n interrupt(reason: string) {\n log('Interrupting connection for reason: ' + reason);\n this.interruptReasons_[reason] = true;\n if (this.realtime_) {\n this.realtime_.close();\n } else {\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n this.establishConnectionTimer_ = null;\n }\n if (this.connected_) {\n this.onRealtimeDisconnect_();\n }\n }\n }\n\n resume(reason: string) {\n log('Resuming connection for reason: ' + reason);\n delete this.interruptReasons_[reason];\n if (isEmpty(this.interruptReasons_)) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n }\n\n private handleTimestamp_(timestamp: number) {\n const delta = timestamp - new Date().getTime();\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\n }\n\n private cancelSentTransactions_() {\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\n const put = this.outstandingPuts_[i];\n if (put && /*hash*/ 'h' in put.request && put.queued) {\n if (put.onComplete) {\n put.onComplete('disconnect');\n }\n\n delete this.outstandingPuts_[i];\n this.outstandingPutCount_--;\n }\n }\n\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0) {\n this.outstandingPuts_ = [];\n }\n }\n\n private onListenRevoked_(pathString: string, query?: unknown[]) {\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\n let queryId;\n if (!query) {\n queryId = 'default';\n } else {\n queryId = query.map(q => ObjectToUniqueKey(q)).join('$');\n }\n const listen = this.removeListen_(pathString, queryId);\n if (listen && listen.onComplete) {\n listen.onComplete('permission_denied');\n }\n }\n\n private removeListen_(pathString: string, queryId: string): ListenSpec {\n const normalizedPathString = new Path(pathString).toString(); // normalize path.\n let listen;\n if (this.listens.has(normalizedPathString)) {\n const map = this.listens.get(normalizedPathString)!;\n listen = map.get(queryId);\n map.delete(queryId);\n if (map.size === 0) {\n this.listens.delete(normalizedPathString);\n }\n } else {\n // all listens for this path has already been removed\n listen = undefined;\n }\n return listen;\n }\n\n private onAuthRevoked_(statusCode: string, explanation: string) {\n log('Auth token revoked: ' + statusCode + '/' + explanation);\n this.authToken_ = null;\n this.forceTokenRefresh_ = true;\n this.realtime_.close();\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAuthTokenCount_++;\n if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\n // Set a long reconnect delay because recovery is unlikely\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n\n // Notify the auth token provider that the token is invalid, which will log\n // a warning\n this.authTokenProvider_.notifyForInvalidToken();\n }\n }\n }\n\n private onAppCheckRevoked_(statusCode: string, explanation: string) {\n log('App check token revoked: ' + statusCode + '/' + explanation);\n this.appCheckToken_ = null;\n this.forceTokenRefresh_ = true;\n // Note: We don't close the connection as the developer may not have\n // enforcement enabled. The backend closes connections with enforcements.\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAppCheckTokenCount_++;\n if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\n this.appCheckTokenProvider_.notifyForInvalidToken();\n }\n }\n }\n\n private onSecurityDebugPacket_(body: { [k: string]: unknown }) {\n if (this.securityDebugCallback_) {\n this.securityDebugCallback_(body);\n } else {\n if ('msg' in body) {\n console.log(\n 'FIREBASE: ' + (body['msg'] as string).replace('\\n', '\\nFIREBASE: ')\n );\n }\n }\n }\n\n private restoreState_() {\n //Re-authenticate ourselves if we have a credential stored.\n this.tryAuth();\n this.tryAppCheck();\n\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\n // make sure to send listens before puts.\n for (const queries of this.listens.values()) {\n for (const listenSpec of queries.values()) {\n this.sendListen_(listenSpec);\n }\n }\n\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\n if (this.outstandingPuts_[i]) {\n this.sendPut_(i);\n }\n }\n\n while (this.onDisconnectRequestQueue_.length) {\n const request = this.onDisconnectRequestQueue_.shift();\n this.sendOnDisconnect_(\n request.action,\n request.pathString,\n request.data,\n request.onComplete\n );\n }\n\n for (let i = 0; i < this.outstandingGets_.length; i++) {\n if (this.outstandingGets_[i]) {\n this.sendGet_(i);\n }\n }\n }\n\n /**\n * Sends client stats for first connection\n */\n private sendConnectStats_() {\n const stats: { [k: string]: number } = {};\n\n let clientName = 'js';\n if (isNodeSdk()) {\n if (this.repoInfo_.nodeAdmin) {\n clientName = 'admin_node';\n } else {\n clientName = 'node';\n }\n }\n\n stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\\./g, '-')] = 1;\n\n if (isMobileCordova()) {\n stats['framework.cordova'] = 1;\n } else if (isReactNative()) {\n stats['framework.reactnative'] = 1;\n }\n this.reportStats(stats);\n }\n\n private shouldReconnect_(): boolean {\n const online = OnlineMonitor.getInstance().currentlyOnline();\n return isEmpty(this.interruptReasons_) && online;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Path } from '../util/Path';\n\nimport { Index } from './indexes/Index';\n\n/**\n * Node is an interface defining the common functionality for nodes in\n * a DataSnapshot.\n *\n * @interface\n */\nexport interface Node {\n /**\n * Whether this node is a leaf node.\n * @returns Whether this is a leaf node.\n */\n isLeafNode(): boolean;\n\n /**\n * Gets the priority of the node.\n * @returns The priority of the node.\n */\n getPriority(): Node;\n\n /**\n * Returns a duplicate node with the new priority.\n * @param newPriorityNode - New priority to set for the node.\n * @returns Node with new priority.\n */\n updatePriority(newPriorityNode: Node): Node;\n\n /**\n * Returns the specified immediate child, or null if it doesn't exist.\n * @param childName - The name of the child to retrieve.\n * @returns The retrieved child, or an empty node.\n */\n getImmediateChild(childName: string): Node;\n\n /**\n * Returns a child by path, or null if it doesn't exist.\n * @param path - The path of the child to retrieve.\n * @returns The retrieved child or an empty node.\n */\n getChild(path: Path): Node;\n\n /**\n * Returns the name of the child immediately prior to the specified childNode, or null.\n * @param childName - The name of the child to find the predecessor of.\n * @param childNode - The node to find the predecessor of.\n * @param index - The index to use to determine the predecessor\n * @returns The name of the predecessor child, or null if childNode is the first child.\n */\n getPredecessorChildName(\n childName: string,\n childNode: Node,\n index: Index\n ): string | null;\n\n /**\n * Returns a duplicate node, with the specified immediate child updated.\n * Any value in the node will be removed.\n * @param childName - The name of the child to update.\n * @param newChildNode - The new child node\n * @returns The updated node.\n */\n updateImmediateChild(childName: string, newChildNode: Node): Node;\n\n /**\n * Returns a duplicate node, with the specified child updated. Any value will\n * be removed.\n * @param path - The path of the child to update.\n * @param newChildNode - The new child node, which may be an empty node\n * @returns The updated node.\n */\n updateChild(path: Path, newChildNode: Node): Node;\n\n /**\n * True if the immediate child specified exists\n */\n hasChild(childName: string): boolean;\n\n /**\n * @returns True if this node has no value or children.\n */\n isEmpty(): boolean;\n\n /**\n * @returns The number of children of this node.\n */\n numChildren(): number;\n\n /**\n * Calls action for each child.\n * @param action - Action to be called for\n * each child. It's passed the child name and the child node.\n * @returns The first truthy value return by action, or the last falsey one\n */\n forEachChild(index: Index, action: (a: string, b: Node) => void): unknown;\n\n /**\n * @param exportFormat - True for export format (also wire protocol format).\n * @returns Value of this node as JSON.\n */\n val(exportFormat?: boolean): unknown;\n\n /**\n * @returns hash representing the node contents.\n */\n hash(): string;\n\n /**\n * @param other - Another node\n * @returns -1 for less than, 0 for equal, 1 for greater than other\n */\n compareTo(other: Node): number;\n\n /**\n * @returns Whether or not this snapshot equals other\n */\n equals(other: Node): boolean;\n\n /**\n * @returns This node, with the specified index now available\n */\n withIndex(indexDefinition: Index): Node;\n\n isIndexed(indexDefinition: Index): boolean;\n}\n\nexport class NamedNode {\n constructor(public name: string, public node: Node) {}\n\n static Wrap(name: string, node: Node) {\n return new NamedNode(name, node);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Comparator } from '../../util/SortedMap';\nimport { MIN_NAME } from '../../util/util';\nimport { Node, NamedNode } from '../Node';\n\nexport abstract class Index {\n abstract compare(a: NamedNode, b: NamedNode): number;\n\n abstract isDefinedOn(node: Node): boolean;\n\n /**\n * @returns A standalone comparison function for\n * this index\n */\n getCompare(): Comparator {\n return this.compare.bind(this);\n }\n\n /**\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\n *\n *\n * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode\n */\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n const oldWrapped = new NamedNode(MIN_NAME, oldNode);\n const newWrapped = new NamedNode(MIN_NAME, newNode);\n return this.compare(oldWrapped, newWrapped) !== 0;\n }\n\n /**\n * @returns a node wrapper that will sort equal to or less than\n * any other node wrapper, using this index\n */\n minPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n\n /**\n * @returns a node wrapper that will sort greater than or equal to\n * any other node wrapper, using this index\n */\n abstract maxPost(): NamedNode;\n\n abstract makePost(indexValue: unknown, name: string): NamedNode;\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n abstract toString(): string;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport { nameCompare, MAX_NAME } from '../../util/util';\nimport { ChildrenNode } from '../ChildrenNode';\nimport { Node, NamedNode } from '../Node';\n\nimport { Index } from './Index';\n\nlet __EMPTY_NODE: ChildrenNode;\n\nexport class KeyIndex extends Index {\n static get __EMPTY_NODE() {\n return __EMPTY_NODE;\n }\n\n static set __EMPTY_NODE(val) {\n __EMPTY_NODE = val;\n }\n compare(a: NamedNode, b: NamedNode): number {\n return nameCompare(a.name, b.name);\n }\n isDefinedOn(node: Node): boolean {\n // We could probably return true here (since every node has a key), but it's never called\n // so just leaving unimplemented for now.\n throw assertionError('KeyIndex.isDefinedOn not expected to be called.');\n }\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return false; // The key for a node never changes.\n }\n minPost() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n maxPost(): NamedNode {\n // TODO: This should really be created once and cached in a static property, but\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\n return new NamedNode(MAX_NAME, __EMPTY_NODE);\n }\n\n makePost(indexValue: string, name: string): NamedNode {\n assert(\n typeof indexValue === 'string',\n 'KeyIndex indexValue must always be a string.'\n );\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\n return new NamedNode(indexValue, __EMPTY_NODE);\n }\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString(): string {\n return '.key';\n }\n}\n\nexport const KEY_INDEX = new KeyIndex();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Implementation of an immutable SortedMap using a Left-leaning\n * Red-Black Tree, adapted from the implementation in Mugs\n * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen\n * (mads379\\@gmail.com).\n *\n * Original paper on Left-leaning Red-Black Trees:\n * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf\n *\n * Invariant 1: No red node has a red child\n * Invariant 2: Every leaf path has the same number of black nodes\n * Invariant 3: Only the left child can be red (left leaning)\n */\n\n// TODO: There are some improvements I'd like to make to improve memory / perf:\n// * Create two prototypes, LLRedNode and LLBlackNode, instead of storing a\n// color property in every node.\n// TODO: It would also be good (and possibly necessary) to create a base\n// interface for LLRBNode and LLRBEmptyNode.\n\nexport type Comparator = (key1: K, key2: K) => number;\n\n/**\n * An iterator over an LLRBNode.\n */\nexport class SortedMapIterator {\n private nodeStack_: Array | LLRBEmptyNode> = [];\n\n /**\n * @param node - Node to iterate.\n * @param isReverse_ - Whether or not to iterate in reverse\n */\n constructor(\n node: LLRBNode | LLRBEmptyNode,\n startKey: K | null,\n comparator: Comparator,\n private isReverse_: boolean,\n private resultGenerator_: ((k: K, v: V) => T) | null = null\n ) {\n let cmp = 1;\n while (!node.isEmpty()) {\n node = node as LLRBNode;\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse_) {\n cmp *= -1;\n }\n\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse_) {\n node = node.left;\n } else {\n node = node.right;\n }\n } else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\n this.nodeStack_.push(node);\n break;\n } else {\n // This node is greater than our start key, add it to the stack and move to the next one\n this.nodeStack_.push(node);\n if (this.isReverse_) {\n node = node.right;\n } else {\n node = node.left;\n }\n }\n }\n }\n\n getNext(): T {\n if (this.nodeStack_.length === 0) {\n return null;\n }\n\n let node = this.nodeStack_.pop();\n let result: T;\n if (this.resultGenerator_) {\n result = this.resultGenerator_(node.key, node.value);\n } else {\n result = { key: node.key, value: node.value } as unknown as T;\n }\n\n if (this.isReverse_) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.right;\n }\n } else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.left;\n }\n }\n\n return result;\n }\n\n hasNext(): boolean {\n return this.nodeStack_.length > 0;\n }\n\n peek(): T {\n if (this.nodeStack_.length === 0) {\n return null;\n }\n\n const node = this.nodeStack_[this.nodeStack_.length - 1];\n if (this.resultGenerator_) {\n return this.resultGenerator_(node.key, node.value);\n } else {\n return { key: node.key, value: node.value } as unknown as T;\n }\n }\n}\n\n/**\n * Represents a node in a Left-leaning Red-Black tree.\n */\nexport class LLRBNode {\n color: boolean;\n left: LLRBNode | LLRBEmptyNode;\n right: LLRBNode | LLRBEmptyNode;\n\n /**\n * @param key - Key associated with this node.\n * @param value - Value associated with this node.\n * @param color - Whether this node is red.\n * @param left - Left child.\n * @param right - Right child.\n */\n constructor(\n public key: K,\n public value: V,\n color: boolean | null,\n left?: LLRBNode | LLRBEmptyNode | null,\n right?: LLRBNode | LLRBEmptyNode | null\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left =\n left != null ? left : (SortedMap.EMPTY_NODE as LLRBEmptyNode);\n this.right =\n right != null ? right : (SortedMap.EMPTY_NODE as LLRBEmptyNode);\n }\n\n static RED = true;\n static BLACK = false;\n\n /**\n * Returns a copy of the current node, optionally replacing pieces of it.\n *\n * @param key - New key for the node, or null.\n * @param value - New value for the node, or null.\n * @param color - New color for the node, or null.\n * @param left - New left child for the node, or null.\n * @param right - New right child for the node, or null.\n * @returns The node copy.\n */\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBNode {\n return new LLRBNode(\n key != null ? key : this.key,\n value != null ? value : this.value,\n color != null ? color : this.color,\n left != null ? left : this.left,\n right != null ? right : this.right\n );\n }\n\n /**\n * @returns The total number of nodes in the tree.\n */\n count(): number {\n return this.left.count() + 1 + this.right.count();\n }\n\n /**\n * @returns True if the tree is empty.\n */\n isEmpty(): boolean {\n return false;\n }\n\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n inorderTraversal(action: (k: K, v: V) => unknown): boolean {\n return (\n this.left.inorderTraversal(action) ||\n !!action(this.key, this.value) ||\n this.right.inorderTraversal(action)\n );\n }\n\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n reverseTraversal(action: (k: K, v: V) => void): boolean {\n return (\n this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action)\n );\n }\n\n /**\n * @returns The minimum node in the tree.\n */\n private min_(): LLRBNode {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode).min_();\n }\n }\n\n /**\n * @returns The maximum key in the tree.\n */\n minKey(): K {\n return this.min_().key;\n }\n\n /**\n * @returns The maximum key in the tree.\n */\n maxKey(): K {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\n }\n\n /**\n * @param key - Key to insert.\n * @param value - Value to insert.\n * @param comparator - Comparator.\n * @returns New tree, with the key/value added.\n */\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n let n: LLRBNode = this;\n const cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n } else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n } else {\n n = n.copy(\n null,\n null,\n null,\n null,\n n.right.insert(key, value, comparator)\n );\n }\n return n.fixUp_();\n }\n\n /**\n * @returns New tree, with the minimum key removed.\n */\n private removeMin_(): LLRBNode | LLRBEmptyNode {\n if (this.left.isEmpty()) {\n return SortedMap.EMPTY_NODE as LLRBEmptyNode;\n }\n let n: LLRBNode = this;\n if (!n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, (n.left as LLRBNode).removeMin_(), null);\n return n.fixUp_();\n }\n\n /**\n * @param key - The key of the item to remove.\n * @param comparator - Comparator.\n * @returns New tree, with the specified item removed.\n */\n remove(\n key: K,\n comparator: Comparator\n ): LLRBNode | LLRBEmptyNode {\n let n, smallest;\n n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n } else {\n if (n.left.isRed_()) {\n n = n.rotateRight_();\n }\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\n n = n.moveRedRight_();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return SortedMap.EMPTY_NODE as LLRBEmptyNode;\n } else {\n smallest = (n.right as LLRBNode).min_();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode).removeMin_()\n );\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp_();\n }\n\n /**\n * @returns Whether this is a RED node.\n */\n isRed_(): boolean {\n return this.color;\n }\n\n /**\n * @returns New tree after performing any needed rotations.\n */\n private fixUp_(): LLRBNode {\n let n: LLRBNode = this;\n if (n.right.isRed_() && !n.left.isRed_()) {\n n = n.rotateLeft_();\n }\n if (n.left.isRed_() && n.left.left.isRed_()) {\n n = n.rotateRight_();\n }\n if (n.left.isRed_() && n.right.isRed_()) {\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @returns New tree, after moveRedLeft.\n */\n private moveRedLeft_(): LLRBNode {\n let n = this.colorFlip_();\n if (n.right.left.isRed_()) {\n n = n.copy(\n null,\n null,\n null,\n null,\n (n.right as LLRBNode).rotateRight_()\n );\n n = n.rotateLeft_();\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @returns New tree, after moveRedRight.\n */\n private moveRedRight_(): LLRBNode {\n let n = this.colorFlip_();\n if (n.left.left.isRed_()) {\n n = n.rotateRight_();\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @returns New tree, after rotateLeft.\n */\n private rotateLeft_(): LLRBNode {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null) as LLRBNode;\n }\n\n /**\n * @returns New tree, after rotateRight.\n */\n private rotateRight_(): LLRBNode {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr) as LLRBNode;\n }\n\n /**\n * @returns Newt ree, after colorFlip.\n */\n private colorFlip_(): LLRBNode {\n const left = this.left.copy(null, null, !this.left.color, null, null);\n const right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n }\n\n /**\n * For testing.\n *\n * @returns True if all is well.\n */\n private checkMaxDepth_(): boolean {\n const blackDepth = this.check_();\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\n }\n\n check_(): number {\n if (this.isRed_() && this.left.isRed_()) {\n throw new Error(\n 'Red node has red child(' + this.key + ',' + this.value + ')'\n );\n }\n if (this.right.isRed_()) {\n throw new Error(\n 'Right child of (' + this.key + ',' + this.value + ') is red'\n );\n }\n const blackDepth = this.left.check_();\n if (blackDepth !== this.right.check_()) {\n throw new Error('Black depths differ');\n } else {\n return blackDepth + (this.isRed_() ? 0 : 1);\n }\n }\n}\n\n/**\n * Represents an empty node (a leaf node in the Red-Black Tree).\n */\nexport class LLRBEmptyNode {\n key: K;\n value: V;\n left: LLRBNode | LLRBEmptyNode;\n right: LLRBNode | LLRBEmptyNode;\n color: boolean;\n\n /**\n * Returns a copy of the current node.\n *\n * @returns The node copy.\n */\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBEmptyNode {\n return this;\n }\n\n /**\n * Returns a copy of the tree, with the specified key/value added.\n *\n * @param key - Key to be added.\n * @param value - Value to be added.\n * @param comparator - Comparator.\n * @returns New tree, with item added.\n */\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n return new LLRBNode(key, value, null);\n }\n\n /**\n * Returns a copy of the tree, with the specified key removed.\n *\n * @param key - The key to remove.\n * @param comparator - Comparator.\n * @returns New tree, with item removed.\n */\n remove(key: K, comparator: Comparator): LLRBEmptyNode {\n return this;\n }\n\n /**\n * @returns The total number of nodes in the tree.\n */\n count(): number {\n return 0;\n }\n\n /**\n * @returns True if the tree is empty.\n */\n isEmpty(): boolean {\n return true;\n }\n\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n inorderTraversal(action: (k: K, v: V) => unknown): boolean {\n return false;\n }\n\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n reverseTraversal(action: (k: K, v: V) => void): boolean {\n return false;\n }\n\n minKey(): null {\n return null;\n }\n\n maxKey(): null {\n return null;\n }\n\n check_(): number {\n return 0;\n }\n\n /**\n * @returns Whether this node is red.\n */\n isRed_() {\n return false;\n }\n}\n\n/**\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\n * tree.\n */\nexport class SortedMap {\n /**\n * Always use the same empty node, to reduce memory.\n */\n static EMPTY_NODE = new LLRBEmptyNode();\n\n /**\n * @param comparator_ - Key comparator.\n * @param root_ - Optional root node for the map.\n */\n constructor(\n private comparator_: Comparator,\n private root_:\n | LLRBNode\n | LLRBEmptyNode = SortedMap.EMPTY_NODE as LLRBEmptyNode\n ) {}\n\n /**\n * Returns a copy of the map, with the specified key/value added or replaced.\n * (TODO: We should perhaps rename this method to 'put')\n *\n * @param key - Key to be added.\n * @param value - Value to be added.\n * @returns New map, with item added.\n */\n insert(key: K, value: V): SortedMap {\n return new SortedMap(\n this.comparator_,\n this.root_\n .insert(key, value, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n /**\n * Returns a copy of the map, with the specified key removed.\n *\n * @param key - The key to remove.\n * @returns New map, with item removed.\n */\n remove(key: K): SortedMap {\n return new SortedMap(\n this.comparator_,\n this.root_\n .remove(key, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n /**\n * Returns the value of the node with the given key, or null.\n *\n * @param key - The key to look up.\n * @returns The value of the node with the given key, or null if the\n * key doesn't exist.\n */\n get(key: K): V | null {\n let cmp;\n let node = this.root_;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n return node.value;\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n }\n\n /**\n * Returns the key of the item *before* the specified key, or null if key is the first item.\n * @param key - The key to find the predecessor of\n * @returns The predecessor key.\n */\n getPredecessorKey(key: K): K | null {\n let cmp,\n node = this.root_,\n rightParent = null;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n if (!node.left.isEmpty()) {\n node = node.left;\n while (!node.right.isEmpty()) {\n node = node.right;\n }\n return node.key;\n } else if (rightParent) {\n return rightParent.key;\n } else {\n return null; // first item.\n }\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n\n throw new Error(\n 'Attempted to find predecessor key for a nonexistent key. What gives?'\n );\n }\n\n /**\n * @returns True if the map is empty.\n */\n isEmpty(): boolean {\n return this.root_.isEmpty();\n }\n\n /**\n * @returns The total number of nodes in the map.\n */\n count(): number {\n return this.root_.count();\n }\n\n /**\n * @returns The minimum key in the map.\n */\n minKey(): K | null {\n return this.root_.minKey();\n }\n\n /**\n * @returns The maximum key in the map.\n */\n maxKey(): K | null {\n return this.root_.maxKey();\n }\n\n /**\n * Traverses the map in key order and calls the specified action function\n * for each key/value pair.\n *\n * @param action - Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @returns The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n inorderTraversal(action: (k: K, v: V) => unknown): boolean {\n return this.root_.inorderTraversal(action);\n }\n\n /**\n * Traverses the map in reverse key order and calls the specified action function\n * for each key/value pair.\n *\n * @param action - Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @returns True if the traversal was aborted.\n */\n reverseTraversal(action: (k: K, v: V) => void): boolean {\n return this.root_.reverseTraversal(action);\n }\n\n /**\n * Returns an iterator over the SortedMap.\n * @returns The iterator.\n */\n getIterator(\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n null,\n this.comparator_,\n false,\n resultGenerator\n );\n }\n\n getIteratorFrom(\n key: K,\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n key,\n this.comparator_,\n false,\n resultGenerator\n );\n }\n\n getReverseIteratorFrom(\n key: K,\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n key,\n this.comparator_,\n true,\n resultGenerator\n );\n }\n\n getReverseIterator(\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n null,\n this.comparator_,\n true,\n resultGenerator\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare } from '../util/util';\n\nimport { NamedNode } from './Node';\n\nexport function NAME_ONLY_COMPARATOR(left: NamedNode, right: NamedNode) {\n return nameCompare(left.name, right.name);\n}\n\nexport function NAME_COMPARATOR(left: string, right: string) {\n return nameCompare(left, right);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, contains } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport { doubleToIEEE754String } from '../util/util';\n\nimport { Node } from './Node';\n\nlet MAX_NODE: Node;\n\nexport function setMaxNode(val: Node) {\n MAX_NODE = val;\n}\n\nexport const priorityHashText = function (priority: string | number): string {\n if (typeof priority === 'number') {\n return 'number:' + doubleToIEEE754String(priority);\n } else {\n return 'string:' + priority;\n }\n};\n\n/**\n * Validates that a priority snapshot Node is valid.\n */\nexport const validatePriorityNode = function (priorityNode: Node) {\n if (priorityNode.isLeafNode()) {\n const val = priorityNode.val();\n assert(\n typeof val === 'string' ||\n typeof val === 'number' ||\n (typeof val === 'object' && contains(val as Indexable, '.sv')),\n 'Priority must be a string or number.'\n );\n } else {\n assert(\n priorityNode === MAX_NODE || priorityNode.isEmpty(),\n 'priority of unexpected type.'\n );\n }\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\n assert(\n priorityNode === MAX_NODE || priorityNode.getPriority().isEmpty(),\n \"Priority nodes can't have a priority of their own.\"\n );\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport {\n Path,\n pathGetFront,\n pathGetLength,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\nimport { doubleToIEEE754String, sha1 } from '../util/util';\n\nimport { ChildrenNodeConstructor } from './ChildrenNode';\nimport { Index } from './indexes/Index';\nimport { Node } from './Node';\nimport { priorityHashText, validatePriorityNode } from './snap';\n\nlet __childrenNodeConstructor: ChildrenNodeConstructor;\n\n/**\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\n * implements Node and stores the value of the node (a string,\n * number, or boolean) accessible via getValue().\n */\nexport class LeafNode implements Node {\n static set __childrenNodeConstructor(val: ChildrenNodeConstructor) {\n __childrenNodeConstructor = val;\n }\n\n static get __childrenNodeConstructor() {\n return __childrenNodeConstructor;\n }\n\n /**\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\n * the same type, the comparison falls back to their value\n */\n static VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n\n private lazyHash_: string | null = null;\n\n /**\n * @param value_ - The value to store in this leaf node. The object type is\n * possible in the event of a deferred value\n * @param priorityNode_ - The priority of this node.\n */\n constructor(\n private readonly value_: string | number | boolean | Indexable,\n private priorityNode_: Node = LeafNode.__childrenNodeConstructor.EMPTY_NODE\n ) {\n assert(\n this.value_ !== undefined && this.value_ !== null,\n \"LeafNode shouldn't be created with null/undefined value.\"\n );\n\n validatePriorityNode(this.priorityNode_);\n }\n\n /** @inheritDoc */\n isLeafNode(): boolean {\n return true;\n }\n\n /** @inheritDoc */\n getPriority(): Node {\n return this.priorityNode_;\n }\n\n /** @inheritDoc */\n updatePriority(newPriorityNode: Node): Node {\n return new LeafNode(this.value_, newPriorityNode);\n }\n\n /** @inheritDoc */\n getImmediateChild(childName: string): Node {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.priorityNode_;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n }\n\n /** @inheritDoc */\n getChild(path: Path): Node {\n if (pathIsEmpty(path)) {\n return this;\n } else if (pathGetFront(path) === '.priority') {\n return this.priorityNode_;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n }\n hasChild(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n getPredecessorChildName(childName: string, childNode: Node): null {\n return null;\n }\n\n /** @inheritDoc */\n updateImmediateChild(childName: string, newChildNode: Node): Node {\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n } else if (newChildNode.isEmpty() && childName !== '.priority') {\n return this;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(\n childName,\n newChildNode\n ).updatePriority(this.priorityNode_);\n }\n }\n\n /** @inheritDoc */\n updateChild(path: Path, newChildNode: Node): Node {\n const front = pathGetFront(path);\n if (front === null) {\n return newChildNode;\n } else if (newChildNode.isEmpty() && front !== '.priority') {\n return this;\n } else {\n assert(\n front !== '.priority' || pathGetLength(path) === 1,\n '.priority must be the last token in a path'\n );\n\n return this.updateImmediateChild(\n front,\n LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(\n pathPopFront(path),\n newChildNode\n )\n );\n }\n }\n\n /** @inheritDoc */\n isEmpty(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n numChildren(): number {\n return 0;\n }\n\n /** @inheritDoc */\n forEachChild(index: Index, action: (s: string, n: Node) => void): boolean {\n return false;\n }\n val(exportFormat?: boolean): {} {\n if (exportFormat && !this.getPriority().isEmpty()) {\n return {\n '.value': this.getValue(),\n '.priority': this.getPriority().val()\n };\n } else {\n return this.getValue();\n }\n }\n\n /** @inheritDoc */\n hash(): string {\n if (this.lazyHash_ === null) {\n let toHash = '';\n if (!this.priorityNode_.isEmpty()) {\n toHash +=\n 'priority:' +\n priorityHashText(this.priorityNode_.val() as number | string) +\n ':';\n }\n\n const type = typeof this.value_;\n toHash += type + ':';\n if (type === 'number') {\n toHash += doubleToIEEE754String(this.value_ as number);\n } else {\n toHash += this.value_;\n }\n this.lazyHash_ = sha1(toHash);\n }\n return this.lazyHash_;\n }\n\n /**\n * Returns the value of the leaf node.\n * @returns The value of the node.\n */\n getValue(): Indexable | string | number | boolean {\n return this.value_;\n }\n compareTo(other: Node): number {\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\n return 1;\n } else if (other instanceof LeafNode.__childrenNodeConstructor) {\n return -1;\n } else {\n assert(other.isLeafNode(), 'Unknown node type');\n return this.compareToLeafNode_(other as LeafNode);\n }\n }\n\n /**\n * Comparison specifically for two leaf nodes\n */\n private compareToLeafNode_(otherLeaf: LeafNode): number {\n const otherLeafType = typeof otherLeaf.value_;\n const thisLeafType = typeof this.value_;\n const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\n const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\n assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\n assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\n if (otherIndex === thisIndex) {\n // Same type, compare values\n if (thisLeafType === 'object') {\n // Deferred value nodes are all equal, but we should also never get to this point...\n return 0;\n } else {\n // Note that this works because true > false, all others are number or string comparisons\n if (this.value_ < otherLeaf.value_) {\n return -1;\n } else if (this.value_ === otherLeaf.value_) {\n return 0;\n } else {\n return 1;\n }\n }\n } else {\n return thisIndex - otherIndex;\n }\n }\n withIndex(): Node {\n return this;\n }\n isIndexed(): boolean {\n return true;\n }\n equals(other: Node): boolean {\n if (other === this) {\n return true;\n } else if (other.isLeafNode()) {\n const otherLeaf = other as LeafNode;\n return (\n this.value_ === otherLeaf.value_ &&\n this.priorityNode_.equals(otherLeaf.priorityNode_)\n );\n } else {\n return false;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare, MAX_NAME } from '../../util/util';\nimport { LeafNode } from '../LeafNode';\nimport { NamedNode, Node } from '../Node';\n\nimport { Index } from './Index';\n\nlet nodeFromJSON: (a: unknown) => Node;\nlet MAX_NODE: Node;\n\nexport function setNodeFromJSON(val: (a: unknown) => Node) {\n nodeFromJSON = val;\n}\n\nexport function setMaxNode(val: Node) {\n MAX_NODE = val;\n}\n\nexport class PriorityIndex extends Index {\n compare(a: NamedNode, b: NamedNode): number {\n const aPriority = a.node.getPriority();\n const bPriority = b.node.getPriority();\n const indexCmp = aPriority.compareTo(bPriority);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n isDefinedOn(node: Node): boolean {\n return !node.getPriority().isEmpty();\n }\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return !oldNode.getPriority().equals(newNode.getPriority());\n }\n minPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n maxPost(): NamedNode {\n return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE));\n }\n\n makePost(indexValue: unknown, name: string): NamedNode {\n const priorityNode = nodeFromJSON(indexValue);\n return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));\n }\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString(): string {\n return '.priority';\n }\n}\n\nexport const PRIORITY_INDEX = new PriorityIndex();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LLRBNode, SortedMap } from '../util/SortedMap';\n\nimport { NamedNode } from './Node';\n\nconst LOG_2 = Math.log(2);\n\nclass Base12Num {\n count: number;\n private current_: number;\n private bits_: number;\n\n constructor(length: number) {\n const logBase2 = (num: number) =>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parseInt((Math.log(num) / LOG_2) as any, 10);\n const bitMask = (bits: number) => parseInt(Array(bits + 1).join('1'), 2);\n this.count = logBase2(length + 1);\n this.current_ = this.count - 1;\n const mask = bitMask(this.count);\n this.bits_ = (length + 1) & mask;\n }\n\n nextBitIsOne(): boolean {\n //noinspection JSBitwiseOperatorUsage\n const result = !(this.bits_ & (0x1 << this.current_));\n this.current_--;\n return result;\n }\n}\n\n/**\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\n * function\n *\n * Uses the algorithm described in the paper linked here:\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\n *\n * @param childList - Unsorted list of children\n * @param cmp - The comparison method to be used\n * @param keyFn - An optional function to extract K from a node wrapper, if K's\n * type is not NamedNode\n * @param mapSortFn - An optional override for comparator used by the generated sorted map\n */\nexport const buildChildSet = function (\n childList: NamedNode[],\n cmp: (a: NamedNode, b: NamedNode) => number,\n keyFn?: (a: NamedNode) => K,\n mapSortFn?: (a: K, b: K) => number\n): SortedMap {\n childList.sort(cmp);\n\n const buildBalancedTree = function (\n low: number,\n high: number\n ): LLRBNode | null {\n const length = high - low;\n let namedNode: NamedNode;\n let key: K;\n if (length === 0) {\n return null;\n } else if (length === 1) {\n namedNode = childList[low];\n key = keyFn ? keyFn(namedNode) : (namedNode as unknown as K);\n return new LLRBNode(\n key,\n namedNode.node as unknown as V,\n LLRBNode.BLACK,\n null,\n null\n );\n } else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const middle = parseInt((length / 2) as any, 10) + low;\n const left = buildBalancedTree(low, middle);\n const right = buildBalancedTree(middle + 1, high);\n namedNode = childList[middle];\n key = keyFn ? keyFn(namedNode) : (namedNode as unknown as K);\n return new LLRBNode(\n key,\n namedNode.node as unknown as V,\n LLRBNode.BLACK,\n left,\n right\n );\n }\n };\n\n const buildFrom12Array = function (base12: Base12Num): LLRBNode {\n let node: LLRBNode = null;\n let root = null;\n let index = childList.length;\n\n const buildPennant = function (chunkSize: number, color: boolean) {\n const low = index - chunkSize;\n const high = index;\n index -= chunkSize;\n const childTree = buildBalancedTree(low + 1, high);\n const namedNode = childList[low];\n const key: K = keyFn ? keyFn(namedNode) : (namedNode as unknown as K);\n attachPennant(\n new LLRBNode(\n key,\n namedNode.node as unknown as V,\n color,\n null,\n childTree\n )\n );\n };\n\n const attachPennant = function (pennant: LLRBNode) {\n if (node) {\n node.left = pennant;\n node = pennant;\n } else {\n root = pennant;\n node = pennant;\n }\n };\n\n for (let i = 0; i < base12.count; ++i) {\n const isOne = base12.nextBitIsOne();\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\n const chunkSize = Math.pow(2, base12.count - (i + 1));\n if (isOne) {\n buildPennant(chunkSize, LLRBNode.BLACK);\n } else {\n // current == 2\n buildPennant(chunkSize, LLRBNode.BLACK);\n buildPennant(chunkSize, LLRBNode.RED);\n }\n }\n return root;\n };\n\n const base12 = new Base12Num(childList.length);\n const root = buildFrom12Array(base12);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new SortedMap(mapSortFn || (cmp as any), root);\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, contains, map, safeGet } from '@firebase/util';\n\nimport { SortedMap } from '../util/SortedMap';\n\nimport { buildChildSet } from './childSet';\nimport { Index } from './indexes/Index';\nimport { KEY_INDEX } from './indexes/KeyIndex';\nimport { PRIORITY_INDEX } from './indexes/PriorityIndex';\nimport { NamedNode, Node } from './Node';\n\nlet _defaultIndexMap: IndexMap;\n\nconst fallbackObject = {};\n\nexport class IndexMap {\n /**\n * The default IndexMap for nodes without a priority\n */\n static get Default(): IndexMap {\n assert(\n fallbackObject && PRIORITY_INDEX,\n 'ChildrenNode.ts has not been loaded'\n );\n _defaultIndexMap =\n _defaultIndexMap ||\n new IndexMap(\n { '.priority': fallbackObject },\n { '.priority': PRIORITY_INDEX }\n );\n return _defaultIndexMap;\n }\n\n constructor(\n private indexes_: {\n [k: string]: SortedMap | /*FallbackType*/ object;\n },\n private indexSet_: { [k: string]: Index }\n ) {}\n\n get(indexKey: string): SortedMap | null {\n const sortedMap = safeGet(this.indexes_, indexKey);\n if (!sortedMap) {\n throw new Error('No index defined for ' + indexKey);\n }\n\n if (sortedMap instanceof SortedMap) {\n return sortedMap;\n } else {\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\n // regular child map\n return null;\n }\n }\n\n hasIndex(indexDefinition: Index): boolean {\n return contains(this.indexSet_, indexDefinition.toString());\n }\n\n addIndex(\n indexDefinition: Index,\n existingChildren: SortedMap\n ): IndexMap {\n assert(\n indexDefinition !== KEY_INDEX,\n \"KeyIndex always exists and isn't meant to be added to the IndexMap.\"\n );\n const childList = [];\n let sawIndexedValue = false;\n const iter = existingChildren.getIterator(NamedNode.Wrap);\n let next = iter.getNext();\n while (next) {\n sawIndexedValue =\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\n childList.push(next);\n next = iter.getNext();\n }\n let newIndex;\n if (sawIndexedValue) {\n newIndex = buildChildSet(childList, indexDefinition.getCompare());\n } else {\n newIndex = fallbackObject;\n }\n const indexName = indexDefinition.toString();\n const newIndexSet = { ...this.indexSet_ };\n newIndexSet[indexName] = indexDefinition;\n const newIndexes = { ...this.indexes_ };\n newIndexes[indexName] = newIndex;\n return new IndexMap(newIndexes, newIndexSet);\n }\n\n /**\n * Ensure that this node is properly tracked in any indexes that we're maintaining\n */\n addToIndexes(\n namedNode: NamedNode,\n existingChildren: SortedMap\n ): IndexMap {\n const newIndexes = map(\n this.indexes_,\n (indexedChildren: SortedMap, indexName: string) => {\n const index = safeGet(this.indexSet_, indexName);\n assert(index, 'Missing index implementation for ' + indexName);\n if (indexedChildren === fallbackObject) {\n // Check to see if we need to index everything\n if (index.isDefinedOn(namedNode.node)) {\n // We need to build this index\n const childList = [];\n const iter = existingChildren.getIterator(NamedNode.Wrap);\n let next = iter.getNext();\n while (next) {\n if (next.name !== namedNode.name) {\n childList.push(next);\n }\n next = iter.getNext();\n }\n childList.push(namedNode);\n return buildChildSet(childList, index.getCompare());\n } else {\n // No change, this remains a fallback\n return fallbackObject;\n }\n } else {\n const existingSnap = existingChildren.get(namedNode.name);\n let newChildren = indexedChildren;\n if (existingSnap) {\n newChildren = newChildren.remove(\n new NamedNode(namedNode.name, existingSnap)\n );\n }\n return newChildren.insert(namedNode, namedNode.node);\n }\n }\n );\n return new IndexMap(newIndexes, this.indexSet_);\n }\n\n /**\n * Create a new IndexMap instance with the given value removed\n */\n removeFromIndexes(\n namedNode: NamedNode,\n existingChildren: SortedMap\n ): IndexMap {\n const newIndexes = map(\n this.indexes_,\n (indexedChildren: SortedMap) => {\n if (indexedChildren === fallbackObject) {\n // This is the fallback. Just return it, nothing to do in this case\n return indexedChildren;\n } else {\n const existingSnap = existingChildren.get(namedNode.name);\n if (existingSnap) {\n return indexedChildren.remove(\n new NamedNode(namedNode.name, existingSnap)\n );\n } else {\n // No record of this child\n return indexedChildren;\n }\n }\n }\n );\n return new IndexMap(newIndexes, this.indexSet_);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Path, pathGetFront, pathGetLength, pathPopFront } from '../util/Path';\nimport { SortedMap, SortedMapIterator } from '../util/SortedMap';\nimport { MAX_NAME, MIN_NAME, sha1 } from '../util/util';\n\nimport { NAME_COMPARATOR } from './comparators';\nimport { Index } from './indexes/Index';\nimport { KEY_INDEX, KeyIndex } from './indexes/KeyIndex';\nimport {\n PRIORITY_INDEX,\n setMaxNode as setPriorityMaxNode\n} from './indexes/PriorityIndex';\nimport { IndexMap } from './IndexMap';\nimport { LeafNode } from './LeafNode';\nimport { NamedNode, Node } from './Node';\nimport { priorityHashText, setMaxNode, validatePriorityNode } from './snap';\n\nexport interface ChildrenNodeConstructor {\n new (\n children_: SortedMap,\n priorityNode_: Node | null,\n indexMap_: IndexMap\n ): ChildrenNode;\n EMPTY_NODE: ChildrenNode;\n}\n\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\n\nlet EMPTY_NODE: ChildrenNode;\n\n/**\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\n * (i.e. nodes with children). It implements Node and stores the\n * list of children in the children property, sorted by child name.\n */\nexport class ChildrenNode implements Node {\n private lazyHash_: string | null = null;\n\n static get EMPTY_NODE(): ChildrenNode {\n return (\n EMPTY_NODE ||\n (EMPTY_NODE = new ChildrenNode(\n new SortedMap(NAME_COMPARATOR),\n null,\n IndexMap.Default\n ))\n );\n }\n\n /**\n * @param children_ - List of children of this node..\n * @param priorityNode_ - The priority of this node (as a snapshot node).\n */\n constructor(\n private readonly children_: SortedMap,\n private readonly priorityNode_: Node | null,\n private indexMap_: IndexMap\n ) {\n /**\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\n * class instead of an empty ChildrenNode.\n */\n if (this.priorityNode_) {\n validatePriorityNode(this.priorityNode_);\n }\n\n if (this.children_.isEmpty()) {\n assert(\n !this.priorityNode_ || this.priorityNode_.isEmpty(),\n 'An empty node cannot have a priority'\n );\n }\n }\n\n /** @inheritDoc */\n isLeafNode(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n getPriority(): Node {\n return this.priorityNode_ || EMPTY_NODE;\n }\n\n /** @inheritDoc */\n updatePriority(newPriorityNode: Node): Node {\n if (this.children_.isEmpty()) {\n // Don't allow priorities on empty nodes\n return this;\n } else {\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\n }\n }\n\n /** @inheritDoc */\n getImmediateChild(childName: string): Node {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.getPriority();\n } else {\n const child = this.children_.get(childName);\n return child === null ? EMPTY_NODE : child;\n }\n }\n\n /** @inheritDoc */\n getChild(path: Path): Node {\n const front = pathGetFront(path);\n if (front === null) {\n return this;\n }\n\n return this.getImmediateChild(front).getChild(pathPopFront(path));\n }\n\n /** @inheritDoc */\n hasChild(childName: string): boolean {\n return this.children_.get(childName) !== null;\n }\n\n /** @inheritDoc */\n updateImmediateChild(childName: string, newChildNode: Node): Node {\n assert(newChildNode, 'We should always be passing snapshot nodes');\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n } else {\n const namedNode = new NamedNode(childName, newChildNode);\n let newChildren, newIndexMap;\n if (newChildNode.isEmpty()) {\n newChildren = this.children_.remove(childName);\n newIndexMap = this.indexMap_.removeFromIndexes(\n namedNode,\n this.children_\n );\n } else {\n newChildren = this.children_.insert(childName, newChildNode);\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\n }\n\n const newPriority = newChildren.isEmpty()\n ? EMPTY_NODE\n : this.priorityNode_;\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\n }\n }\n\n /** @inheritDoc */\n updateChild(path: Path, newChildNode: Node): Node {\n const front = pathGetFront(path);\n if (front === null) {\n return newChildNode;\n } else {\n assert(\n pathGetFront(path) !== '.priority' || pathGetLength(path) === 1,\n '.priority must be the last token in a path'\n );\n const newImmediateChild = this.getImmediateChild(front).updateChild(\n pathPopFront(path),\n newChildNode\n );\n return this.updateImmediateChild(front, newImmediateChild);\n }\n }\n\n /** @inheritDoc */\n isEmpty(): boolean {\n return this.children_.isEmpty();\n }\n\n /** @inheritDoc */\n numChildren(): number {\n return this.children_.count();\n }\n\n private static INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\n\n /** @inheritDoc */\n val(exportFormat?: boolean): object {\n if (this.isEmpty()) {\n return null;\n }\n\n const obj: { [k: string]: unknown } = {};\n let numKeys = 0,\n maxKey = 0,\n allIntegerKeys = true;\n this.forEachChild(PRIORITY_INDEX, (key: string, childNode: Node) => {\n obj[key] = childNode.val(exportFormat);\n\n numKeys++;\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\n maxKey = Math.max(maxKey, Number(key));\n } else {\n allIntegerKeys = false;\n }\n });\n\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\n // convert to array.\n const array: unknown[] = [];\n // eslint-disable-next-line guard-for-in\n for (const key in obj) {\n array[key as unknown as number] = obj[key];\n }\n\n return array;\n } else {\n if (exportFormat && !this.getPriority().isEmpty()) {\n obj['.priority'] = this.getPriority().val();\n }\n return obj;\n }\n }\n\n /** @inheritDoc */\n hash(): string {\n if (this.lazyHash_ === null) {\n let toHash = '';\n if (!this.getPriority().isEmpty()) {\n toHash +=\n 'priority:' +\n priorityHashText(this.getPriority().val() as string | number) +\n ':';\n }\n\n this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n const childHash = childNode.hash();\n if (childHash !== '') {\n toHash += ':' + key + ':' + childHash;\n }\n });\n\n this.lazyHash_ = toHash === '' ? '' : sha1(toHash);\n }\n return this.lazyHash_;\n }\n\n /** @inheritDoc */\n getPredecessorChildName(\n childName: string,\n childNode: Node,\n index: Index\n ): string {\n const idx = this.resolveIndex_(index);\n if (idx) {\n const predecessor = idx.getPredecessorKey(\n new NamedNode(childName, childNode)\n );\n return predecessor ? predecessor.name : null;\n } else {\n return this.children_.getPredecessorKey(childName);\n }\n }\n\n getFirstChildName(indexDefinition: Index): string | null {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n const minKey = idx.minKey();\n return minKey && minKey.name;\n } else {\n return this.children_.minKey();\n }\n }\n\n getFirstChild(indexDefinition: Index): NamedNode | null {\n const minKey = this.getFirstChildName(indexDefinition);\n if (minKey) {\n return new NamedNode(minKey, this.children_.get(minKey));\n } else {\n return null;\n }\n }\n\n /**\n * Given an index, return the key name of the largest value we have, according to that index\n */\n getLastChildName(indexDefinition: Index): string | null {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n const maxKey = idx.maxKey();\n return maxKey && maxKey.name;\n } else {\n return this.children_.maxKey();\n }\n }\n\n getLastChild(indexDefinition: Index): NamedNode | null {\n const maxKey = this.getLastChildName(indexDefinition);\n if (maxKey) {\n return new NamedNode(maxKey, this.children_.get(maxKey));\n } else {\n return null;\n }\n }\n forEachChild(\n index: Index,\n action: (key: string, node: Node) => boolean | void\n ): boolean {\n const idx = this.resolveIndex_(index);\n if (idx) {\n return idx.inorderTraversal(wrappedNode => {\n return action(wrappedNode.name, wrappedNode.node);\n });\n } else {\n return this.children_.inorderTraversal(action);\n }\n }\n\n getIterator(\n indexDefinition: Index\n ): SortedMapIterator {\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\n }\n\n getIteratorFrom(\n startPost: NamedNode,\n indexDefinition: Index\n ): SortedMapIterator {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getIteratorFrom(startPost, key => key);\n } else {\n const iterator = this.children_.getIteratorFrom(\n startPost.name,\n NamedNode.Wrap\n );\n let next = iterator.peek();\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n }\n\n getReverseIterator(\n indexDefinition: Index\n ): SortedMapIterator {\n return this.getReverseIteratorFrom(\n indexDefinition.maxPost(),\n indexDefinition\n );\n }\n\n getReverseIteratorFrom(\n endPost: NamedNode,\n indexDefinition: Index\n ): SortedMapIterator {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getReverseIteratorFrom(endPost, key => {\n return key;\n });\n } else {\n const iterator = this.children_.getReverseIteratorFrom(\n endPost.name,\n NamedNode.Wrap\n );\n let next = iterator.peek();\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n }\n compareTo(other: ChildrenNode): number {\n if (this.isEmpty()) {\n if (other.isEmpty()) {\n return 0;\n } else {\n return -1;\n }\n } else if (other.isLeafNode() || other.isEmpty()) {\n return 1;\n } else if (other === MAX_NODE) {\n return -1;\n } else {\n // Must be another node with children.\n return 0;\n }\n }\n withIndex(indexDefinition: Index): Node {\n if (\n indexDefinition === KEY_INDEX ||\n this.indexMap_.hasIndex(indexDefinition)\n ) {\n return this;\n } else {\n const newIndexMap = this.indexMap_.addIndex(\n indexDefinition,\n this.children_\n );\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\n }\n }\n isIndexed(index: Index): boolean {\n return index === KEY_INDEX || this.indexMap_.hasIndex(index);\n }\n equals(other: Node): boolean {\n if (other === this) {\n return true;\n } else if (other.isLeafNode()) {\n return false;\n } else {\n const otherChildrenNode = other as ChildrenNode;\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\n return false;\n } else if (\n this.children_.count() === otherChildrenNode.children_.count()\n ) {\n const thisIter = this.getIterator(PRIORITY_INDEX);\n const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);\n let thisCurrent = thisIter.getNext();\n let otherCurrent = otherIter.getNext();\n while (thisCurrent && otherCurrent) {\n if (\n thisCurrent.name !== otherCurrent.name ||\n !thisCurrent.node.equals(otherCurrent.node)\n ) {\n return false;\n }\n thisCurrent = thisIter.getNext();\n otherCurrent = otherIter.getNext();\n }\n return thisCurrent === null && otherCurrent === null;\n } else {\n return false;\n }\n }\n }\n\n /**\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\n * instead.\n *\n */\n private resolveIndex_(\n indexDefinition: Index\n ): SortedMap | null {\n if (indexDefinition === KEY_INDEX) {\n return null;\n } else {\n return this.indexMap_.get(indexDefinition.toString());\n }\n }\n}\n\nexport class MaxNode extends ChildrenNode {\n constructor() {\n super(\n new SortedMap(NAME_COMPARATOR),\n ChildrenNode.EMPTY_NODE,\n IndexMap.Default\n );\n }\n\n compareTo(other: Node): number {\n if (other === this) {\n return 0;\n } else {\n return 1;\n }\n }\n\n equals(other: Node): boolean {\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\n return other === this;\n }\n\n getPriority(): MaxNode {\n return this;\n }\n\n getImmediateChild(childName: string): ChildrenNode {\n return ChildrenNode.EMPTY_NODE;\n }\n\n isEmpty(): boolean {\n return false;\n }\n}\n\n/**\n * Marker that will sort higher than any other snapshot.\n */\nexport const MAX_NODE = new MaxNode();\n\n/**\n * Document NamedNode extensions\n */\ndeclare module './Node' {\n interface NamedNode {\n MIN: NamedNode;\n MAX: NamedNode;\n }\n}\n\nObject.defineProperties(NamedNode, {\n MIN: {\n value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)\n },\n MAX: {\n value: new NamedNode(MAX_NAME, MAX_NODE)\n }\n});\n\n/**\n * Reference Extensions\n */\nKeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\nLeafNode.__childrenNodeConstructor = ChildrenNode;\nsetMaxNode(MAX_NODE);\nsetPriorityMaxNode(MAX_NODE);\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains, assert } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport { SortedMap } from '../util/SortedMap';\nimport { each } from '../util/util';\n\nimport { ChildrenNode } from './ChildrenNode';\nimport { buildChildSet } from './childSet';\nimport { NAME_COMPARATOR, NAME_ONLY_COMPARATOR } from './comparators';\nimport { PRIORITY_INDEX, setNodeFromJSON } from './indexes/PriorityIndex';\nimport { IndexMap } from './IndexMap';\nimport { LeafNode } from './LeafNode';\nimport { NamedNode, Node } from './Node';\n\nconst USE_HINZE = true;\n\n/**\n * Constructs a snapshot node representing the passed JSON and returns it.\n * @param json - JSON to create a node for.\n * @param priority - Optional priority to use. This will be ignored if the\n * passed JSON contains a .priority property.\n */\nexport function nodeFromJSON(\n json: unknown | null,\n priority: unknown = null\n): Node {\n if (json === null) {\n return ChildrenNode.EMPTY_NODE;\n }\n\n if (typeof json === 'object' && '.priority' in json) {\n priority = json['.priority'];\n }\n\n assert(\n priority === null ||\n typeof priority === 'string' ||\n typeof priority === 'number' ||\n (typeof priority === 'object' && '.sv' in (priority as object)),\n 'Invalid priority type found: ' + typeof priority\n );\n\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\n json = json['.value'];\n }\n\n // Valid leaf nodes include non-objects or server-value wrapper objects\n if (typeof json !== 'object' || '.sv' in json) {\n const jsonLeaf = json as string | number | boolean | Indexable;\n return new LeafNode(jsonLeaf, nodeFromJSON(priority));\n }\n\n if (!(json instanceof Array) && USE_HINZE) {\n const children: NamedNode[] = [];\n let childrenHavePriority = false;\n const hinzeJsonObj = json;\n each(hinzeJsonObj, (key, child) => {\n if (key.substring(0, 1) !== '.') {\n // Ignore metadata nodes\n const childNode = nodeFromJSON(child);\n if (!childNode.isEmpty()) {\n childrenHavePriority =\n childrenHavePriority || !childNode.getPriority().isEmpty();\n children.push(new NamedNode(key, childNode));\n }\n }\n });\n\n if (children.length === 0) {\n return ChildrenNode.EMPTY_NODE;\n }\n\n const childSet = buildChildSet(\n children,\n NAME_ONLY_COMPARATOR,\n namedNode => namedNode.name,\n NAME_COMPARATOR\n ) as SortedMap;\n if (childrenHavePriority) {\n const sortedChildSet = buildChildSet(\n children,\n PRIORITY_INDEX.getCompare()\n );\n return new ChildrenNode(\n childSet,\n nodeFromJSON(priority),\n new IndexMap(\n { '.priority': sortedChildSet },\n { '.priority': PRIORITY_INDEX }\n )\n );\n } else {\n return new ChildrenNode(\n childSet,\n nodeFromJSON(priority),\n IndexMap.Default\n );\n }\n } else {\n let node: Node = ChildrenNode.EMPTY_NODE;\n each(json, (key: string, childData: unknown) => {\n if (contains(json as object, key)) {\n if (key.substring(0, 1) !== '.') {\n // ignore metadata nodes.\n const childNode = nodeFromJSON(childData);\n if (childNode.isLeafNode() || !childNode.isEmpty()) {\n node = node.updateImmediateChild(key, childNode);\n }\n }\n }\n });\n\n return node.updatePriority(nodeFromJSON(priority));\n }\n}\n\nsetNodeFromJSON(nodeFromJSON);\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Path, pathGetFront, pathIsEmpty, pathSlice } from '../../util/Path';\nimport { MAX_NAME, nameCompare } from '../../util/util';\nimport { ChildrenNode, MAX_NODE } from '../ChildrenNode';\nimport { NamedNode, Node } from '../Node';\nimport { nodeFromJSON } from '../nodeFromJSON';\n\nimport { Index } from './Index';\n\nexport class PathIndex extends Index {\n constructor(private indexPath_: Path) {\n super();\n\n assert(\n !pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority',\n \"Can't create PathIndex with empty path or .priority key\"\n );\n }\n\n protected extractChild(snap: Node): Node {\n return snap.getChild(this.indexPath_);\n }\n isDefinedOn(node: Node): boolean {\n return !node.getChild(this.indexPath_).isEmpty();\n }\n compare(a: NamedNode, b: NamedNode): number {\n const aChild = this.extractChild(a.node);\n const bChild = this.extractChild(b.node);\n const indexCmp = aChild.compareTo(bChild);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n makePost(indexValue: object, name: string): NamedNode {\n const valueNode = nodeFromJSON(indexValue);\n const node = ChildrenNode.EMPTY_NODE.updateChild(\n this.indexPath_,\n valueNode\n );\n return new NamedNode(name, node);\n }\n maxPost(): NamedNode {\n const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);\n return new NamedNode(MAX_NAME, node);\n }\n toString(): string {\n return pathSlice(this.indexPath_, 0).join('/');\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare } from '../../util/util';\nimport { NamedNode, Node } from '../Node';\nimport { nodeFromJSON } from '../nodeFromJSON';\n\nimport { Index } from './Index';\n\nexport class ValueIndex extends Index {\n compare(a: NamedNode, b: NamedNode): number {\n const indexCmp = a.node.compareTo(b.node);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n isDefinedOn(node: Node): boolean {\n return true;\n }\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return !oldNode.equals(newNode);\n }\n minPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n maxPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MAX;\n }\n\n makePost(indexValue: object, name: string): NamedNode {\n const valueNode = nodeFromJSON(indexValue);\n return new NamedNode(name, valueNode);\n }\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString(): string {\n return '.value';\n }\n}\n\nexport const VALUE_INDEX = new ValueIndex();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\n\nexport const enum ChangeType {\n /** Event type for a child added */\n CHILD_ADDED = 'child_added',\n /** Event type for a child removed */\n CHILD_REMOVED = 'child_removed',\n /** Event type for a child changed */\n CHILD_CHANGED = 'child_changed',\n /** Event type for a child moved */\n CHILD_MOVED = 'child_moved',\n /** Event type for a value change */\n VALUE = 'value'\n}\n\nexport interface Change {\n /** @param type - The event type */\n type: ChangeType;\n /** @param snapshotNode - The data */\n snapshotNode: Node;\n /** @param childName - The name for this child, if it's a child even */\n childName?: string;\n /** @param oldSnap - Used for intermediate processing of child changed events */\n oldSnap?: Node;\n /** * @param prevName - The name for the previous child, if applicable */\n prevName?: string | null;\n}\n\nexport function changeValue(snapshotNode: Node): Change {\n return { type: ChangeType.VALUE, snapshotNode };\n}\n\nexport function changeChildAdded(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_ADDED, snapshotNode, childName };\n}\n\nexport function changeChildRemoved(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_REMOVED, snapshotNode, childName };\n}\n\nexport function changeChildChanged(\n childName: string,\n snapshotNode: Node,\n oldSnap: Node\n): Change {\n return {\n type: ChangeType.CHILD_CHANGED,\n snapshotNode,\n childName,\n oldSnap\n };\n}\n\nexport function changeChildMoved(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_MOVED, snapshotNode, childName };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { PRIORITY_INDEX } from '../../snap/indexes/PriorityIndex';\nimport { Node } from '../../snap/Node';\nimport { Path } from '../../util/Path';\nimport {\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from '../Change';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\n\nimport { NodeFilter } from './NodeFilter';\n\n/**\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\n */\nexport class IndexedFilter implements NodeFilter {\n constructor(private readonly index_: Index) {}\n\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n assert(\n snap.isIndexed(this.index_),\n 'A node must be indexed if only a child is updated'\n );\n const oldChild = snap.getImmediateChild(key);\n // Check if anything actually changed.\n if (\n oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))\n ) {\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\n // to avoid treating these cases as \"nothing changed.\"\n if (oldChild.isEmpty() === newChild.isEmpty()) {\n // Nothing changed.\n\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\n return snap;\n }\n }\n\n if (optChangeAccumulator != null) {\n if (newChild.isEmpty()) {\n if (snap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(\n changeChildRemoved(key, oldChild)\n );\n } else {\n assert(\n snap.isLeafNode(),\n 'A child remove without an old child only makes sense on a leaf node'\n );\n }\n } else if (oldChild.isEmpty()) {\n optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));\n } else {\n optChangeAccumulator.trackChildChange(\n changeChildChanged(key, newChild, oldChild)\n );\n }\n }\n if (snap.isLeafNode() && newChild.isEmpty()) {\n return snap;\n } else {\n // Make sure the node is indexed\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\n }\n }\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (optChangeAccumulator != null) {\n if (!oldSnap.isLeafNode()) {\n oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (!newSnap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(\n changeChildRemoved(key, childNode)\n );\n }\n });\n }\n if (!newSnap.isLeafNode()) {\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (oldSnap.hasChild(key)) {\n const oldChild = oldSnap.getImmediateChild(key);\n if (!oldChild.equals(childNode)) {\n optChangeAccumulator.trackChildChange(\n changeChildChanged(key, childNode, oldChild)\n );\n }\n } else {\n optChangeAccumulator.trackChildChange(\n changeChildAdded(key, childNode)\n );\n }\n });\n }\n }\n return newSnap.withIndex(this.index_);\n }\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n if (oldSnap.isEmpty()) {\n return ChildrenNode.EMPTY_NODE;\n } else {\n return oldSnap.updatePriority(newPriority);\n }\n }\n filtersNodes(): boolean {\n return false;\n }\n getIndexedFilter(): IndexedFilter {\n return this;\n }\n getIndex(): Index {\n return this.index_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NamedNode, Node } from '../../../core/snap/Node';\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { PRIORITY_INDEX } from '../../snap/indexes/PriorityIndex';\nimport { Path } from '../../util/Path';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\nimport { QueryParams } from '../QueryParams';\n\nimport { IndexedFilter } from './IndexedFilter';\nimport { NodeFilter } from './NodeFilter';\n\n/**\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n */\nexport class RangedFilter implements NodeFilter {\n private indexedFilter_: IndexedFilter;\n\n private index_: Index;\n\n private startPost_: NamedNode;\n\n private endPost_: NamedNode;\n\n private startIsInclusive_: boolean;\n\n private endIsInclusive_: boolean;\n\n constructor(params: QueryParams) {\n this.indexedFilter_ = new IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n this.startIsInclusive_ = !params.startAfterSet_;\n this.endIsInclusive_ = !params.endBeforeSet_;\n }\n\n getStartPost(): NamedNode {\n return this.startPost_;\n }\n\n getEndPost(): NamedNode {\n return this.endPost_;\n }\n\n matches(node: NamedNode): boolean {\n const isWithinStart = this.startIsInclusive_\n ? this.index_.compare(this.getStartPost(), node) <= 0\n : this.index_.compare(this.getStartPost(), node) < 0;\n const isWithinEnd = this.endIsInclusive_\n ? this.index_.compare(node, this.getEndPost()) <= 0\n : this.index_.compare(node, this.getEndPost()) < 0;\n return isWithinStart && isWithinEnd;\n }\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (!this.matches(new NamedNode(key, newChild))) {\n newChild = ChildrenNode.EMPTY_NODE;\n }\n return this.indexedFilter_.updateChild(\n snap,\n key,\n newChild,\n affectedPath,\n source,\n optChangeAccumulator\n );\n }\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode.EMPTY_NODE;\n }\n let filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\n const self = this;\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (!self.matches(new NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(\n oldSnap,\n filtered,\n optChangeAccumulator\n );\n }\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n // Don't support priorities on queries\n return oldSnap;\n }\n filtersNodes(): boolean {\n return true;\n }\n getIndexedFilter(): IndexedFilter {\n return this.indexedFilter_;\n }\n getIndex(): Index {\n return this.index_;\n }\n\n private static getStartPost_(params: QueryParams): NamedNode {\n if (params.hasStart()) {\n const startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n } else {\n return params.getIndex().minPost();\n }\n }\n\n private static getEndPost_(params: QueryParams): NamedNode {\n if (params.hasEnd()) {\n const endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n } else {\n return params.getIndex().maxPost();\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { NamedNode, Node } from '../../snap/Node';\nimport { Path } from '../../util/Path';\nimport {\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from '../Change';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\nimport { QueryParams } from '../QueryParams';\n\nimport { IndexedFilter } from './IndexedFilter';\nimport { NodeFilter } from './NodeFilter';\nimport { RangedFilter } from './RangedFilter';\n\n/**\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n */\nexport class LimitedFilter implements NodeFilter {\n private readonly rangedFilter_: RangedFilter;\n\n private readonly index_: Index;\n\n private readonly limit_: number;\n\n private readonly reverse_: boolean;\n\n private readonly startIsInclusive_: boolean;\n\n private readonly endIsInclusive_: boolean;\n\n constructor(params: QueryParams) {\n this.rangedFilter_ = new RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n this.startIsInclusive_ = !params.startAfterSet_;\n this.endIsInclusive_ = !params.endBeforeSet_;\n }\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {\n newChild = ChildrenNode.EMPTY_NODE;\n }\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n } else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_\n .getIndexedFilter()\n .updateChild(\n snap,\n key,\n newChild,\n affectedPath,\n source,\n optChangeAccumulator\n );\n } else {\n return this.fullLimitUpdateChild_(\n snap,\n key,\n newChild,\n source,\n optChangeAccumulator\n );\n }\n }\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n let filtered;\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n } else {\n if (\n this.limit_ * 2 < newSnap.numChildren() &&\n newSnap.isIndexed(this.index_)\n ) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n // anchor to the startPost, endPost, or last element as appropriate\n let iterator;\n if (this.reverse_) {\n iterator = (newSnap as ChildrenNode).getReverseIteratorFrom(\n this.rangedFilter_.getEndPost(),\n this.index_\n );\n } else {\n iterator = (newSnap as ChildrenNode).getIteratorFrom(\n this.rangedFilter_.getStartPost(),\n this.index_\n );\n }\n let count = 0;\n while (iterator.hasNext() && count < this.limit_) {\n const next = iterator.getNext();\n if (!this.withinDirectionalStart(next)) {\n // if we have not reached the start, skip to the next element\n continue;\n } else if (!this.withinDirectionalEnd(next)) {\n // if we have reached the end, stop adding elements\n break;\n } else {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\n }\n }\n } else {\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(\n ChildrenNode.EMPTY_NODE\n ) as ChildrenNode;\n\n let iterator;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n } else {\n iterator = filtered.getIterator(this.index_);\n }\n\n let count = 0;\n while (iterator.hasNext()) {\n const next = iterator.getNext();\n const inRange =\n count < this.limit_ &&\n this.withinDirectionalStart(next) &&\n this.withinDirectionalEnd(next);\n if (inRange) {\n count++;\n } else {\n filtered = filtered.updateImmediateChild(\n next.name,\n ChildrenNode.EMPTY_NODE\n );\n }\n }\n }\n }\n return this.rangedFilter_\n .getIndexedFilter()\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n }\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n // Don't support priorities on queries\n return oldSnap;\n }\n filtersNodes(): boolean {\n return true;\n }\n getIndexedFilter(): IndexedFilter {\n return this.rangedFilter_.getIndexedFilter();\n }\n getIndex(): Index {\n return this.index_;\n }\n\n private fullLimitUpdateChild_(\n snap: Node,\n childKey: string,\n childSnap: Node,\n source: CompleteChildSource,\n changeAccumulator: ChildChangeAccumulator | null\n ): Node {\n // TODO: rename all cache stuff etc to general snap terminology\n let cmp;\n if (this.reverse_) {\n const indexCmp = this.index_.getCompare();\n cmp = (a: NamedNode, b: NamedNode) => indexCmp(b, a);\n } else {\n cmp = this.index_.getCompare();\n }\n const oldEventCache = snap as ChildrenNode;\n assert(oldEventCache.numChildren() === this.limit_, '');\n const newChildNamedNode = new NamedNode(childKey, childSnap);\n const windowBoundary = this.reverse_\n ? oldEventCache.getFirstChild(this.index_)\n : (oldEventCache.getLastChild(this.index_) as NamedNode);\n const inRange = this.rangedFilter_.matches(newChildNamedNode);\n if (oldEventCache.hasChild(childKey)) {\n const oldChildSnap = oldEventCache.getImmediateChild(childKey);\n let nextChild = source.getChildAfterChild(\n this.index_,\n windowBoundary,\n this.reverse_\n );\n while (\n nextChild != null &&\n (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))\n ) {\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\n // the limited filter...\n nextChild = source.getChildAfterChild(\n this.index_,\n nextChild,\n this.reverse_\n );\n }\n const compareNext =\n nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n const remainsInWindow =\n inRange && !childSnap.isEmpty() && compareNext >= 0;\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildChanged(childKey, childSnap, oldChildSnap)\n );\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n } else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildRemoved(childKey, oldChildSnap)\n );\n }\n const newEventCache = oldEventCache.updateImmediateChild(\n childKey,\n ChildrenNode.EMPTY_NODE\n );\n const nextChildInRange =\n nextChild != null && this.rangedFilter_.matches(nextChild);\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildAdded(nextChild.name, nextChild.node)\n );\n }\n return newEventCache.updateImmediateChild(\n nextChild.name,\n nextChild.node\n );\n } else {\n return newEventCache;\n }\n }\n } else if (childSnap.isEmpty()) {\n // we're deleting a node, but it was not in the window, so ignore it\n return snap;\n } else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildRemoved(windowBoundary.name, windowBoundary.node)\n );\n changeAccumulator.trackChildChange(\n changeChildAdded(childKey, childSnap)\n );\n }\n return oldEventCache\n .updateImmediateChild(childKey, childSnap)\n .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);\n } else {\n return snap;\n }\n } else {\n return snap;\n }\n }\n\n private withinDirectionalStart = (node: NamedNode) =>\n this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);\n\n private withinDirectionalEnd = (node: NamedNode) =>\n this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);\n\n private withinStartPost = (node: NamedNode) => {\n const compareRes = this.index_.compare(\n this.rangedFilter_.getStartPost(),\n node\n );\n return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;\n };\n\n private withinEndPost = (node: NamedNode) => {\n const compareRes = this.index_.compare(\n node,\n this.rangedFilter_.getEndPost()\n );\n return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, stringify } from '@firebase/util';\n\nimport { Index } from '../snap/indexes/Index';\nimport { KEY_INDEX } from '../snap/indexes/KeyIndex';\nimport { PathIndex } from '../snap/indexes/PathIndex';\nimport { PRIORITY_INDEX, PriorityIndex } from '../snap/indexes/PriorityIndex';\nimport { VALUE_INDEX } from '../snap/indexes/ValueIndex';\nimport { MAX_NAME, MIN_NAME } from '../util/util';\n\nimport { IndexedFilter } from './filter/IndexedFilter';\nimport { LimitedFilter } from './filter/LimitedFilter';\nimport { NodeFilter } from './filter/NodeFilter';\nimport { RangedFilter } from './filter/RangedFilter';\n\n/**\n * Wire Protocol Constants\n */\nconst enum WIRE_PROTOCOL_CONSTANTS {\n INDEX_START_VALUE = 'sp',\n INDEX_START_NAME = 'sn',\n INDEX_START_IS_INCLUSIVE = 'sin',\n INDEX_END_VALUE = 'ep',\n INDEX_END_NAME = 'en',\n INDEX_END_IS_INCLUSIVE = 'ein',\n LIMIT = 'l',\n VIEW_FROM = 'vf',\n VIEW_FROM_LEFT = 'l',\n VIEW_FROM_RIGHT = 'r',\n INDEX = 'i'\n}\n\n/**\n * REST Query Constants\n */\nconst enum REST_QUERY_CONSTANTS {\n ORDER_BY = 'orderBy',\n PRIORITY_INDEX = '$priority',\n VALUE_INDEX = '$value',\n KEY_INDEX = '$key',\n START_AFTER = 'startAfter',\n START_AT = 'startAt',\n END_AT = 'endAt',\n END_BEFORE = 'endBefore',\n LIMIT_TO_FIRST = 'limitToFirst',\n LIMIT_TO_LAST = 'limitToLast'\n}\n\n/**\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\n * user-facing API level, so it is not done here.\n *\n * @internal\n */\nexport class QueryParams {\n limitSet_ = false;\n startSet_ = false;\n startNameSet_ = false;\n startAfterSet_ = false; // can only be true if startSet_ is true\n endSet_ = false;\n endNameSet_ = false;\n endBeforeSet_ = false; // can only be true if endSet_ is true\n limit_ = 0;\n viewFrom_ = '';\n indexStartValue_: unknown | null = null;\n indexStartName_ = '';\n indexEndValue_: unknown | null = null;\n indexEndName_ = '';\n index_: PriorityIndex = PRIORITY_INDEX;\n\n hasStart(): boolean {\n return this.startSet_;\n }\n\n /**\n * @returns True if it would return from left.\n */\n isViewFromLeft(): boolean {\n if (this.viewFrom_ === '') {\n // limit(), rather than limitToFirst or limitToLast was called.\n // This means that only one of startSet_ and endSet_ is true. Use them\n // to calculate which side of the view to anchor to. If neither is set,\n // anchor to the end.\n return this.startSet_;\n } else {\n return this.viewFrom_ === WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n }\n }\n\n /**\n * Only valid to call if hasStart() returns true\n */\n getIndexStartValue(): unknown {\n assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n }\n\n /**\n * Only valid to call if hasStart() returns true.\n * Returns the starting key name for the range defined by these query parameters\n */\n getIndexStartName(): string {\n assert(this.startSet_, 'Only valid if start has been set');\n if (this.startNameSet_) {\n return this.indexStartName_;\n } else {\n return MIN_NAME;\n }\n }\n\n hasEnd(): boolean {\n return this.endSet_;\n }\n\n /**\n * Only valid to call if hasEnd() returns true.\n */\n getIndexEndValue(): unknown {\n assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n }\n\n /**\n * Only valid to call if hasEnd() returns true.\n * Returns the end key name for the range defined by these query parameters\n */\n getIndexEndName(): string {\n assert(this.endSet_, 'Only valid if end has been set');\n if (this.endNameSet_) {\n return this.indexEndName_;\n } else {\n return MAX_NAME;\n }\n }\n\n hasLimit(): boolean {\n return this.limitSet_;\n }\n\n /**\n * @returns True if a limit has been set and it has been explicitly anchored\n */\n hasAnchoredLimit(): boolean {\n return this.limitSet_ && this.viewFrom_ !== '';\n }\n\n /**\n * Only valid to call if hasLimit() returns true\n */\n getLimit(): number {\n assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n }\n\n getIndex(): Index {\n return this.index_;\n }\n\n loadsAllData(): boolean {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n }\n\n isDefault(): boolean {\n return this.loadsAllData() && this.index_ === PRIORITY_INDEX;\n }\n\n copy(): QueryParams {\n const copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.startAfterSet_ = this.startAfterSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.endBeforeSet_ = this.endBeforeSet_;\n copy.indexEndValue_ = this.indexEndValue_;\n copy.endNameSet_ = this.endNameSet_;\n copy.indexEndName_ = this.indexEndName_;\n copy.index_ = this.index_;\n copy.viewFrom_ = this.viewFrom_;\n return copy;\n }\n}\n\nexport function queryParamsGetNodeFilter(queryParams: QueryParams): NodeFilter {\n if (queryParams.loadsAllData()) {\n return new IndexedFilter(queryParams.getIndex());\n } else if (queryParams.hasLimit()) {\n return new LimitedFilter(queryParams);\n } else {\n return new RangedFilter(queryParams);\n }\n}\n\nexport function queryParamsLimit(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n}\n\nexport function queryParamsLimitToFirst(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n return newParams;\n}\n\nexport function queryParamsLimitToLast(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n return newParams;\n}\n\nexport function queryParamsStartAt(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.startSet_ = true;\n if (indexValue === undefined) {\n indexValue = null;\n }\n newParams.indexStartValue_ = indexValue;\n if (key != null) {\n newParams.startNameSet_ = true;\n newParams.indexStartName_ = key;\n } else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n return newParams;\n}\n\nexport function queryParamsStartAfter(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n let params: QueryParams;\n if (queryParams.index_ === KEY_INDEX || !!key) {\n params = queryParamsStartAt(queryParams, indexValue, key);\n } else {\n params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);\n }\n params.startAfterSet_ = true;\n return params;\n}\n\nexport function queryParamsEndAt(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.endSet_ = true;\n if (indexValue === undefined) {\n indexValue = null;\n }\n newParams.indexEndValue_ = indexValue;\n if (key !== undefined) {\n newParams.endNameSet_ = true;\n newParams.indexEndName_ = key;\n } else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n return newParams;\n}\n\nexport function queryParamsEndBefore(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n let params: QueryParams;\n if (queryParams.index_ === KEY_INDEX || !!key) {\n params = queryParamsEndAt(queryParams, indexValue, key);\n } else {\n params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);\n }\n params.endBeforeSet_ = true;\n return params;\n}\n\nexport function queryParamsOrderBy(\n queryParams: QueryParams,\n index: Index\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.index_ = index;\n return newParams;\n}\n\n/**\n * Returns a set of REST query string parameters representing this query.\n *\n * @returns query string parameters\n */\nexport function queryParamsToRestQueryStringParameters(\n queryParams: QueryParams\n): Record {\n const qs: Record = {};\n\n if (queryParams.isDefault()) {\n return qs;\n }\n\n let orderBy;\n if (queryParams.index_ === PRIORITY_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.PRIORITY_INDEX;\n } else if (queryParams.index_ === VALUE_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.VALUE_INDEX;\n } else if (queryParams.index_ === KEY_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.KEY_INDEX;\n } else {\n assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');\n orderBy = queryParams.index_.toString();\n }\n qs[REST_QUERY_CONSTANTS.ORDER_BY] = stringify(orderBy);\n\n if (queryParams.startSet_) {\n const startParam = queryParams.startAfterSet_\n ? REST_QUERY_CONSTANTS.START_AFTER\n : REST_QUERY_CONSTANTS.START_AT;\n qs[startParam] = stringify(queryParams.indexStartValue_);\n if (queryParams.startNameSet_) {\n qs[startParam] += ',' + stringify(queryParams.indexStartName_);\n }\n }\n\n if (queryParams.endSet_) {\n const endParam = queryParams.endBeforeSet_\n ? REST_QUERY_CONSTANTS.END_BEFORE\n : REST_QUERY_CONSTANTS.END_AT;\n qs[endParam] = stringify(queryParams.indexEndValue_);\n if (queryParams.endNameSet_) {\n qs[endParam] += ',' + stringify(queryParams.indexEndName_);\n }\n }\n\n if (queryParams.limitSet_) {\n if (queryParams.isViewFromLeft()) {\n qs[REST_QUERY_CONSTANTS.LIMIT_TO_FIRST] = queryParams.limit_;\n } else {\n qs[REST_QUERY_CONSTANTS.LIMIT_TO_LAST] = queryParams.limit_;\n }\n }\n\n return qs;\n}\n\nexport function queryParamsGetQueryObject(\n queryParams: QueryParams\n): Record {\n const obj: Record = {};\n if (queryParams.startSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] =\n queryParams.indexStartValue_;\n if (queryParams.startNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] =\n queryParams.indexStartName_;\n }\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE] =\n !queryParams.startAfterSet_;\n }\n if (queryParams.endSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = queryParams.indexEndValue_;\n if (queryParams.endNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = queryParams.indexEndName_;\n }\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE] =\n !queryParams.endBeforeSet_;\n }\n if (queryParams.limitSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = queryParams.limit_;\n let viewFrom = queryParams.viewFrom_;\n if (viewFrom === '') {\n if (queryParams.isViewFromLeft()) {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n } else {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n }\n }\n obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom;\n }\n // For now, priority index is the default, so we only specify if it's some other index\n if (queryParams.index_ !== PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = queryParams.index_.toString();\n }\n return obj;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n jsonEval,\n safeGet,\n querystring,\n Deferred\n} from '@firebase/util';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { logWrapper, warn } from './util/util';\nimport { QueryContext } from './view/EventRegistration';\nimport { queryParamsToRestQueryStringParameters } from './view/QueryParams';\n\n/**\n * An implementation of ServerActions that communicates with the server via REST requests.\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\n * persistent connection (using WebSockets or long-polling)\n */\nexport class ReadonlyRestClient extends ServerActions {\n reportStats(stats: { [k: string]: unknown }): void {\n throw new Error('Method not implemented.');\n }\n\n /** @private {function(...[*])} */\n private log_: (...args: unknown[]) => void = logWrapper('p:rest:');\n\n /**\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\n * that's been removed. :-/\n */\n private listens_: { [k: string]: object } = {};\n\n static getListenId_(query: QueryContext, tag?: number | null): string {\n if (tag !== undefined) {\n return 'tag$' + tag;\n } else {\n assert(\n query._queryParams.isDefault(),\n \"should have a tag if it's not a default query.\"\n );\n return query._path.toString();\n }\n }\n\n /**\n * @param repoInfo_ - Data about the namespace we are connecting to\n * @param onDataUpdate_ - A callback for new data from the server\n */\n constructor(\n private repoInfo_: RepoInfo,\n private onDataUpdate_: (\n a: string,\n b: unknown,\n c: boolean,\n d: number | null\n ) => void,\n private authTokenProvider_: AuthTokenProvider,\n private appCheckTokenProvider_: AppCheckTokenProvider\n ) {\n super();\n }\n\n /** @inheritDoc */\n listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ) {\n const pathString = query._path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);\n\n // Mark this listener so we can tell if it's removed.\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\n const thisListen = {};\n this.listens_[listenId] = thisListen;\n\n const queryStringParameters = queryParamsToRestQueryStringParameters(\n query._queryParams\n );\n\n this.restRequest_(\n pathString + '.json',\n queryStringParameters,\n (error, result) => {\n let data = result;\n\n if (error === 404) {\n data = null;\n error = null;\n }\n\n if (error === null) {\n this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n }\n\n if (safeGet(this.listens_, listenId) === thisListen) {\n let status;\n if (!error) {\n status = 'ok';\n } else if (error === 401) {\n status = 'permission_denied';\n } else {\n status = 'rest_error:' + error;\n }\n\n onComplete(status, null);\n }\n }\n );\n }\n\n /** @inheritDoc */\n unlisten(query: QueryContext, tag: number | null) {\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n }\n\n get(query: QueryContext): Promise {\n const queryStringParameters = queryParamsToRestQueryStringParameters(\n query._queryParams\n );\n\n const pathString = query._path.toString();\n\n const deferred = new Deferred();\n\n this.restRequest_(\n pathString + '.json',\n queryStringParameters,\n (error, result) => {\n let data = result;\n\n if (error === 404) {\n data = null;\n error = null;\n }\n\n if (error === null) {\n this.onDataUpdate_(\n pathString,\n data,\n /*isMerge=*/ false,\n /*tag=*/ null\n );\n deferred.resolve(data as string);\n } else {\n deferred.reject(new Error(data as string));\n }\n }\n );\n return deferred.promise;\n }\n\n /** @inheritDoc */\n refreshAuthToken(token: string) {\n // no-op since we just always call getToken.\n }\n\n /**\n * Performs a REST request to the given path, with the provided query string parameters,\n * and any auth credentials we have.\n */\n private restRequest_(\n pathString: string,\n queryStringParameters: { [k: string]: string | number } = {},\n callback: ((a: number | null, b?: unknown) => void) | null\n ) {\n queryStringParameters['format'] = 'export';\n\n return Promise.all([\n this.authTokenProvider_.getToken(/*forceRefresh=*/ false),\n this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)\n ]).then(([authToken, appCheckToken]) => {\n if (authToken && authToken.accessToken) {\n queryStringParameters['auth'] = authToken.accessToken;\n }\n if (appCheckToken && appCheckToken.token) {\n queryStringParameters['ac'] = appCheckToken.token;\n }\n\n const url =\n (this.repoInfo_.secure ? 'https://' : 'http://') +\n this.repoInfo_.host +\n pathString +\n '?' +\n 'ns=' +\n this.repoInfo_.namespace +\n querystring(queryStringParameters);\n\n this.log_('Sending REST request for ' + url);\n const xhr = new XMLHttpRequest();\n xhr.onreadystatechange = () => {\n if (callback && xhr.readyState === 4) {\n this.log_(\n 'REST Response for ' + url + ' received. status:',\n xhr.status,\n 'response:',\n xhr.responseText\n );\n let res = null;\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = jsonEval(xhr.responseText);\n } catch (e) {\n warn(\n 'Failed to parse JSON response for ' +\n url +\n ': ' +\n xhr.responseText\n );\n }\n callback(null, res);\n } else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n warn(\n 'Got unsuccessful REST response for ' +\n url +\n ' Status: ' +\n xhr.status\n );\n }\n callback(xhr.status);\n }\n callback = null;\n }\n };\n\n xhr.open('GET', url, /*asynchronous=*/ true);\n xhr.send();\n });\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { Path } from './util/Path';\n\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n */\nexport class SnapshotHolder {\n private rootNode_: Node = ChildrenNode.EMPTY_NODE;\n\n getNode(path: Path): Node {\n return this.rootNode_.getChild(path);\n }\n\n updateSnapshot(path: Path, newSnapshotNode: Node) {\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { Node } from './snap/Node';\nimport { Path, pathGetFront, pathIsEmpty, pathPopFront } from './util/Path';\n\n/**\n * Helper class to store a sparse set of snapshots.\n */\nexport interface SparseSnapshotTree {\n value: Node | null;\n readonly children: Map;\n}\n\nexport function newSparseSnapshotTree(): SparseSnapshotTree {\n return {\n value: null,\n children: new Map()\n };\n}\n\n/**\n * Gets the node stored at the given path if one exists.\n * Only seems to be used in tests.\n *\n * @param path - Path to look up snapshot for.\n * @returns The retrieved node, or null.\n */\nexport function sparseSnapshotTreeFind(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path\n): Node | null {\n if (sparseSnapshotTree.value != null) {\n return sparseSnapshotTree.value.getChild(path);\n } else if (!pathIsEmpty(path) && sparseSnapshotTree.children.size > 0) {\n const childKey = pathGetFront(path);\n path = pathPopFront(path);\n if (sparseSnapshotTree.children.has(childKey)) {\n const childTree = sparseSnapshotTree.children.get(childKey);\n return sparseSnapshotTreeFind(childTree, path);\n } else {\n return null;\n }\n } else {\n return null;\n }\n}\n\n/**\n * Stores the given node at the specified path. If there is already a node\n * at a shallower path, it merges the new data into that snapshot node.\n *\n * @param path - Path to look up snapshot for.\n * @param data - The new data, or null.\n */\nexport function sparseSnapshotTreeRemember(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path,\n data: Node\n): void {\n if (pathIsEmpty(path)) {\n sparseSnapshotTree.value = data;\n sparseSnapshotTree.children.clear();\n } else if (sparseSnapshotTree.value !== null) {\n sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);\n } else {\n const childKey = pathGetFront(path);\n if (!sparseSnapshotTree.children.has(childKey)) {\n sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());\n }\n\n const child = sparseSnapshotTree.children.get(childKey);\n path = pathPopFront(path);\n sparseSnapshotTreeRemember(child, path, data);\n }\n}\n\n/**\n * Purge the data at path from the cache.\n *\n * @param path - Path to look up snapshot for.\n * @returns True if this node should now be removed.\n */\nexport function sparseSnapshotTreeForget(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path\n): boolean {\n if (pathIsEmpty(path)) {\n sparseSnapshotTree.value = null;\n sparseSnapshotTree.children.clear();\n return true;\n } else {\n if (sparseSnapshotTree.value !== null) {\n if (sparseSnapshotTree.value.isLeafNode()) {\n // We're trying to forget a node that doesn't exist\n return false;\n } else {\n const value = sparseSnapshotTree.value;\n sparseSnapshotTree.value = null;\n\n value.forEachChild(PRIORITY_INDEX, (key, tree) => {\n sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);\n });\n\n return sparseSnapshotTreeForget(sparseSnapshotTree, path);\n }\n } else if (sparseSnapshotTree.children.size > 0) {\n const childKey = pathGetFront(path);\n path = pathPopFront(path);\n if (sparseSnapshotTree.children.has(childKey)) {\n const safeToRemove = sparseSnapshotTreeForget(\n sparseSnapshotTree.children.get(childKey),\n path\n );\n if (safeToRemove) {\n sparseSnapshotTree.children.delete(childKey);\n }\n }\n\n return sparseSnapshotTree.children.size === 0;\n } else {\n return true;\n }\n }\n}\n\n/**\n * Recursively iterates through all of the stored tree and calls the\n * callback on each one.\n *\n * @param prefixPath - Path to look up node for.\n * @param func - The function to invoke for each tree.\n */\nexport function sparseSnapshotTreeForEachTree(\n sparseSnapshotTree: SparseSnapshotTree,\n prefixPath: Path,\n func: (a: Path, b: Node) => unknown\n): void {\n if (sparseSnapshotTree.value !== null) {\n func(prefixPath, sparseSnapshotTree.value);\n } else {\n sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {\n const path = new Path(prefixPath.toString() + '/' + key);\n sparseSnapshotTreeForEachTree(tree, path, func);\n });\n }\n}\n\n/**\n * Iterates through each immediate child and triggers the callback.\n * Only seems to be used in tests.\n *\n * @param func - The function to invoke for each child.\n */\nexport function sparseSnapshotTreeForEachChild(\n sparseSnapshotTree: SparseSnapshotTree,\n func: (a: string, b: SparseSnapshotTree) => void\n): void {\n sparseSnapshotTree.children.forEach((tree, key) => {\n func(key, tree);\n });\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { each } from '../util/util';\n\nimport { StatsCollection } from './StatsCollection';\n\n/**\n * Returns the delta from the previous call to get stats.\n *\n * @param collection_ - The collection to \"listen\" to.\n */\nexport class StatsListener {\n private last_: { [k: string]: number } | null = null;\n\n constructor(private collection_: StatsCollection) {}\n\n get(): { [k: string]: number } {\n const newStats = this.collection_.get();\n\n const delta = { ...newStats };\n if (this.last_) {\n each(this.last_, (stat: string, value: number) => {\n delta[stat] = delta[stat] - value;\n });\n }\n this.last_ = newStats;\n\n return delta;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains } from '@firebase/util';\n\nimport { ServerActions } from '../ServerActions';\nimport { setTimeoutNonBlocking, each } from '../util/util';\n\nimport { StatsCollection } from './StatsCollection';\nimport { StatsListener } from './StatsListener';\n\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\n// seconds to try to ensure the Firebase connection is established / settled.\nconst FIRST_STATS_MIN_TIME = 10 * 1000;\nconst FIRST_STATS_MAX_TIME = 30 * 1000;\n\n// We'll continue to report stats on average every 5 minutes.\nconst REPORT_STATS_INTERVAL = 5 * 60 * 1000;\n\nexport class StatsReporter {\n private statsListener_: StatsListener;\n statsToReport_: { [k: string]: boolean } = {};\n\n constructor(collection: StatsCollection, private server_: ServerActions) {\n this.statsListener_ = new StatsListener(collection);\n\n const timeout =\n FIRST_STATS_MIN_TIME +\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n }\n\n private reportStats_() {\n const stats = this.statsListener_.get();\n const reportedStats: typeof stats = {};\n let haveStatsToReport = false;\n\n each(stats, (stat: string, value: number) => {\n if (value > 0 && contains(this.statsToReport_, stat)) {\n reportedStats[stat] = value;\n haveStatsToReport = true;\n }\n });\n\n if (haveStatsToReport) {\n this.server_.reportStats(reportedStats);\n }\n\n // queue our next run.\n setTimeoutNonBlocking(\n this.reportStats_.bind(this),\n Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL)\n );\n }\n}\n\nexport function statsReporterIncludeStat(\n reporter: StatsReporter,\n stat: string\n) {\n reporter.statsToReport_[stat] = true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Path } from '../util/Path';\n\n/**\n *\n * @enum\n */\nexport enum OperationType {\n OVERWRITE,\n MERGE,\n ACK_USER_WRITE,\n LISTEN_COMPLETE\n}\n\n/**\n * @interface\n */\nexport interface Operation {\n source: OperationSource;\n\n type: OperationType;\n\n path: Path;\n\n operationForChild(childName: string): Operation | null;\n}\n\nexport interface OperationSource {\n fromUser: boolean;\n fromServer: boolean;\n queryId: string | null;\n tagged: boolean;\n}\n\nexport function newOperationSourceUser(): OperationSource {\n return {\n fromUser: true,\n fromServer: false,\n queryId: null,\n tagged: false\n };\n}\n\nexport function newOperationSourceServer(): OperationSource {\n return {\n fromUser: false,\n fromServer: true,\n queryId: null,\n tagged: false\n };\n}\n\nexport function newOperationSourceServerTaggedQuery(\n queryId: string\n): OperationSource {\n return {\n fromUser: false,\n fromServer: true,\n queryId,\n tagged: true\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\n\nimport { newOperationSourceUser, Operation, OperationType } from './Operation';\n\nexport class AckUserWrite implements Operation {\n /** @inheritDoc */\n type = OperationType.ACK_USER_WRITE;\n\n /** @inheritDoc */\n source = newOperationSourceUser();\n\n /**\n * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.\n */\n constructor(\n /** @inheritDoc */ public path: Path,\n /** @inheritDoc */ public affectedTree: ImmutableTree,\n /** @inheritDoc */ public revert: boolean\n ) {}\n operationForChild(childName: string): AckUserWrite {\n if (!pathIsEmpty(this.path)) {\n assert(\n pathGetFront(this.path) === childName,\n 'operationForChild called for unrelated child.'\n );\n return new AckUserWrite(\n pathPopFront(this.path),\n this.affectedTree,\n this.revert\n );\n } else if (this.affectedTree.value != null) {\n assert(\n this.affectedTree.children.isEmpty(),\n 'affectedTree should not have overlapping affected paths.'\n );\n // All child locations are affected as well; just return same operation.\n return this;\n } else {\n const childTree = this.affectedTree.subtree(new Path(childName));\n return new AckUserWrite(newEmptyPath(), childTree, this.revert);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { newEmptyPath, Path, pathIsEmpty, pathPopFront } from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './Operation';\n\nexport class ListenComplete implements Operation {\n /** @inheritDoc */\n type = OperationType.LISTEN_COMPLETE;\n\n constructor(public source: OperationSource, public path: Path) {}\n\n operationForChild(childName: string): ListenComplete {\n if (pathIsEmpty(this.path)) {\n return new ListenComplete(this.source, newEmptyPath());\n } else {\n return new ListenComplete(this.source, pathPopFront(this.path));\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\nimport { newEmptyPath, Path, pathIsEmpty, pathPopFront } from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './Operation';\n\nexport class Overwrite implements Operation {\n /** @inheritDoc */\n type = OperationType.OVERWRITE;\n\n constructor(\n public source: OperationSource,\n public path: Path,\n public snap: Node\n ) {}\n\n operationForChild(childName: string): Overwrite {\n if (pathIsEmpty(this.path)) {\n return new Overwrite(\n this.source,\n newEmptyPath(),\n this.snap.getImmediateChild(childName)\n );\n } else {\n return new Overwrite(this.source, pathPopFront(this.path), this.snap);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Node } from '../snap/Node';\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './Operation';\nimport { Overwrite } from './Overwrite';\n\nexport class Merge implements Operation {\n /** @inheritDoc */\n type = OperationType.MERGE;\n\n constructor(\n /** @inheritDoc */ public source: OperationSource,\n /** @inheritDoc */ public path: Path,\n /** @inheritDoc */ public children: ImmutableTree\n ) {}\n operationForChild(childName: string): Operation {\n if (pathIsEmpty(this.path)) {\n const childTree = this.children.subtree(new Path(childName));\n if (childTree.isEmpty()) {\n // This child is unaffected\n return null;\n } else if (childTree.value) {\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\n return new Overwrite(this.source, newEmptyPath(), childTree.value);\n } else {\n // This is a merge at a deeper level\n return new Merge(this.source, newEmptyPath(), childTree);\n }\n } else {\n assert(\n pathGetFront(this.path) === childName,\n \"Can't get a merge for a child not on the path of the operation\"\n );\n return new Merge(this.source, pathPopFront(this.path), this.children);\n }\n }\n toString(): string {\n return (\n 'Operation(' +\n this.path +\n ': ' +\n this.source.toString() +\n ' merge: ' +\n this.children.toString() +\n ')'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\nimport { Path, pathGetFront, pathIsEmpty } from '../util/Path';\n\n/**\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\n * whether a node potentially had children removed due to a filter.\n */\nexport class CacheNode {\n constructor(\n private node_: Node,\n private fullyInitialized_: boolean,\n private filtered_: boolean\n ) {}\n\n /**\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\n */\n isFullyInitialized(): boolean {\n return this.fullyInitialized_;\n }\n\n /**\n * Returns whether this node is potentially missing children due to a filter applied to the node\n */\n isFiltered(): boolean {\n return this.filtered_;\n }\n\n isCompleteForPath(path: Path): boolean {\n if (pathIsEmpty(path)) {\n return this.isFullyInitialized() && !this.filtered_;\n }\n\n const childKey = pathGetFront(path);\n return this.isCompleteForChild(childKey);\n }\n\n isCompleteForChild(key: string): boolean {\n return (\n (this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key)\n );\n }\n\n getNode(): Node {\n return this.node_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assertionError } from '@firebase/util';\n\nimport { Index } from '../snap/indexes/Index';\nimport { NamedNode, Node } from '../snap/Node';\n\nimport { Change, ChangeType, changeChildMoved } from './Change';\nimport { Event } from './Event';\nimport { EventRegistration, QueryContext } from './EventRegistration';\n\n/**\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\n * for details.\n *\n */\nexport class EventGenerator {\n index_: Index;\n\n constructor(public query_: QueryContext) {\n this.index_ = this.query_._queryParams.getIndex();\n }\n}\n\n/**\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\n *\n * Notes:\n * - child_moved events will be synthesized at this time for any child_changed events that affect\n * our index.\n * - prevName will be calculated based on the index ordering.\n */\nexport function eventGeneratorGenerateEventsForChanges(\n eventGenerator: EventGenerator,\n changes: Change[],\n eventCache: Node,\n eventRegistrations: EventRegistration[]\n): Event[] {\n const events: Event[] = [];\n const moves: Change[] = [];\n\n changes.forEach(change => {\n if (\n change.type === ChangeType.CHILD_CHANGED &&\n eventGenerator.index_.indexedValueChanged(\n change.oldSnap as Node,\n change.snapshotNode\n )\n ) {\n moves.push(changeChildMoved(change.childName, change.snapshotNode));\n }\n });\n\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_REMOVED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_ADDED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_MOVED,\n moves,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_CHANGED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.VALUE,\n changes,\n eventRegistrations,\n eventCache\n );\n\n return events;\n}\n\n/**\n * Given changes of a single change type, generate the corresponding events.\n */\nfunction eventGeneratorGenerateEventsForType(\n eventGenerator: EventGenerator,\n events: Event[],\n eventType: string,\n changes: Change[],\n registrations: EventRegistration[],\n eventCache: Node\n) {\n const filteredChanges = changes.filter(change => change.type === eventType);\n\n filteredChanges.sort((a, b) =>\n eventGeneratorCompareChanges(eventGenerator, a, b)\n );\n filteredChanges.forEach(change => {\n const materializedChange = eventGeneratorMaterializeSingleChange(\n eventGenerator,\n change,\n eventCache\n );\n registrations.forEach(registration => {\n if (registration.respondsTo(change.type)) {\n events.push(\n registration.createEvent(materializedChange, eventGenerator.query_)\n );\n }\n });\n });\n}\n\nfunction eventGeneratorMaterializeSingleChange(\n eventGenerator: EventGenerator,\n change: Change,\n eventCache: Node\n): Change {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n } else {\n change.prevName = eventCache.getPredecessorChildName(\n change.childName,\n change.snapshotNode,\n eventGenerator.index_\n );\n return change;\n }\n}\n\nfunction eventGeneratorCompareChanges(\n eventGenerator: EventGenerator,\n a: Change,\n b: Change\n) {\n if (a.childName == null || b.childName == null) {\n throw assertionError('Should only compare child_ events.');\n }\n const aWrapped = new NamedNode(a.childName, a.snapshotNode);\n const bWrapped = new NamedNode(b.childName, b.snapshotNode);\n return eventGenerator.index_.compare(aWrapped, bWrapped);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\n\nimport { CacheNode } from './CacheNode';\n\n/**\n * Stores the data we have cached for a view.\n *\n * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes).\n */\nexport interface ViewCache {\n readonly eventCache: CacheNode;\n readonly serverCache: CacheNode;\n}\n\nexport function newViewCache(\n eventCache: CacheNode,\n serverCache: CacheNode\n): ViewCache {\n return { eventCache, serverCache };\n}\n\nexport function viewCacheUpdateEventSnap(\n viewCache: ViewCache,\n eventSnap: Node,\n complete: boolean,\n filtered: boolean\n): ViewCache {\n return newViewCache(\n new CacheNode(eventSnap, complete, filtered),\n viewCache.serverCache\n );\n}\n\nexport function viewCacheUpdateServerSnap(\n viewCache: ViewCache,\n serverSnap: Node,\n complete: boolean,\n filtered: boolean\n): ViewCache {\n return newViewCache(\n viewCache.eventCache,\n new CacheNode(serverSnap, complete, filtered)\n );\n}\n\nexport function viewCacheGetCompleteEventSnap(\n viewCache: ViewCache\n): Node | null {\n return viewCache.eventCache.isFullyInitialized()\n ? viewCache.eventCache.getNode()\n : null;\n}\n\nexport function viewCacheGetCompleteServerSnap(\n viewCache: ViewCache\n): Node | null {\n return viewCache.serverCache.isFullyInitialized()\n ? viewCache.serverCache.getNode()\n : null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n newEmptyPath,\n Path,\n pathChild,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from './Path';\nimport { SortedMap } from './SortedMap';\nimport { each, stringCompare } from './util';\n\nlet emptyChildrenSingleton: SortedMap>;\n\n/**\n * Singleton empty children collection.\n *\n */\nconst EmptyChildren = (): SortedMap> => {\n if (!emptyChildrenSingleton) {\n emptyChildrenSingleton = new SortedMap>(\n stringCompare\n );\n }\n return emptyChildrenSingleton;\n};\n\n/**\n * A tree with immutable elements.\n */\nexport class ImmutableTree {\n static fromObject(obj: { [k: string]: T }): ImmutableTree {\n let tree: ImmutableTree = new ImmutableTree(null);\n each(obj, (childPath: string, childSnap: T) => {\n tree = tree.set(new Path(childPath), childSnap);\n });\n return tree;\n }\n\n constructor(\n public readonly value: T | null,\n public readonly children: SortedMap<\n string,\n ImmutableTree\n > = EmptyChildren()\n ) {}\n\n /**\n * True if the value is empty and there are no children\n */\n isEmpty(): boolean {\n return this.value === null && this.children.isEmpty();\n }\n\n /**\n * Given a path and predicate, return the first node and the path to that node\n * where the predicate returns true.\n *\n * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`\n * objects on the way back out, it may be better to pass down a pathSoFar obj.\n *\n * @param relativePath - The remainder of the path\n * @param predicate - The predicate to satisfy to return a node\n */\n findRootMostMatchingPathAndValue(\n relativePath: Path,\n predicate: (a: T) => boolean\n ): { path: Path; value: T } | null {\n if (this.value != null && predicate(this.value)) {\n return { path: newEmptyPath(), value: this.value };\n } else {\n if (pathIsEmpty(relativePath)) {\n return null;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child !== null) {\n const childExistingPathAndValue =\n child.findRootMostMatchingPathAndValue(\n pathPopFront(relativePath),\n predicate\n );\n if (childExistingPathAndValue != null) {\n const fullPath = pathChild(\n new Path(front),\n childExistingPathAndValue.path\n );\n return { path: fullPath, value: childExistingPathAndValue.value };\n } else {\n return null;\n }\n } else {\n return null;\n }\n }\n }\n }\n\n /**\n * Find, if it exists, the shortest subpath of the given path that points a defined\n * value in the tree\n */\n findRootMostValueAndPath(\n relativePath: Path\n ): { path: Path; value: T } | null {\n return this.findRootMostMatchingPathAndValue(relativePath, () => true);\n }\n\n /**\n * @returns The subtree at the given path\n */\n subtree(relativePath: Path): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n return this;\n } else {\n const front = pathGetFront(relativePath);\n const childTree = this.children.get(front);\n if (childTree !== null) {\n return childTree.subtree(pathPopFront(relativePath));\n } else {\n return new ImmutableTree(null);\n }\n }\n }\n\n /**\n * Sets a value at the specified path.\n *\n * @param relativePath - Path to set value at.\n * @param toSet - Value to set.\n * @returns Resulting tree.\n */\n set(relativePath: Path, toSet: T | null): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n return new ImmutableTree(toSet, this.children);\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front) || new ImmutableTree(null);\n const newChild = child.set(pathPopFront(relativePath), toSet);\n const newChildren = this.children.insert(front, newChild);\n return new ImmutableTree(this.value, newChildren);\n }\n }\n\n /**\n * Removes the value at the specified path.\n *\n * @param relativePath - Path to value to remove.\n * @returns Resulting tree.\n */\n remove(relativePath: Path): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n if (this.children.isEmpty()) {\n return new ImmutableTree(null);\n } else {\n return new ImmutableTree(null, this.children);\n }\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child) {\n const newChild = child.remove(pathPopFront(relativePath));\n let newChildren;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n } else {\n newChildren = this.children.insert(front, newChild);\n }\n if (this.value === null && newChildren.isEmpty()) {\n return new ImmutableTree(null);\n } else {\n return new ImmutableTree(this.value, newChildren);\n }\n } else {\n return this;\n }\n }\n }\n\n /**\n * Gets a value from the tree.\n *\n * @param relativePath - Path to get value for.\n * @returns Value at path, or null.\n */\n get(relativePath: Path): T | null {\n if (pathIsEmpty(relativePath)) {\n return this.value;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child) {\n return child.get(pathPopFront(relativePath));\n } else {\n return null;\n }\n }\n }\n\n /**\n * Replace the subtree at the specified path with the given new tree.\n *\n * @param relativePath - Path to replace subtree for.\n * @param newTree - New tree.\n * @returns Resulting tree.\n */\n setTree(relativePath: Path, newTree: ImmutableTree): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n return newTree;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front) || new ImmutableTree(null);\n const newChild = child.setTree(pathPopFront(relativePath), newTree);\n let newChildren;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n } else {\n newChildren = this.children.insert(front, newChild);\n }\n return new ImmutableTree(this.value, newChildren);\n }\n }\n\n /**\n * Performs a depth first fold on this tree. Transforms a tree into a single\n * value, given a function that operates on the path to a node, an optional\n * current value, and a map of child names to folded subtrees\n */\n fold(fn: (path: Path, value: T, children: { [k: string]: V }) => V): V {\n return this.fold_(newEmptyPath(), fn);\n }\n\n /**\n * Recursive helper for public-facing fold() method\n */\n private fold_(\n pathSoFar: Path,\n fn: (path: Path, value: T | null, children: { [k: string]: V }) => V\n ): V {\n const accum: { [k: string]: V } = {};\n this.children.inorderTraversal(\n (childKey: string, childTree: ImmutableTree) => {\n accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);\n }\n );\n return fn(pathSoFar, this.value, accum);\n }\n\n /**\n * Find the first matching value on the given path. Return the result of applying f to it.\n */\n findOnPath(path: Path, f: (path: Path, value: T) => V | null): V | null {\n return this.findOnPath_(path, newEmptyPath(), f);\n }\n\n private findOnPath_(\n pathToFollow: Path,\n pathSoFar: Path,\n f: (path: Path, value: T) => V | null\n ): V | null {\n const result = this.value ? f(pathSoFar, this.value) : false;\n if (result) {\n return result;\n } else {\n if (pathIsEmpty(pathToFollow)) {\n return null;\n } else {\n const front = pathGetFront(pathToFollow)!;\n const nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.findOnPath_(\n pathPopFront(pathToFollow),\n pathChild(pathSoFar, front),\n f\n );\n } else {\n return null;\n }\n }\n }\n }\n\n foreachOnPath(\n path: Path,\n f: (path: Path, value: T) => void\n ): ImmutableTree {\n return this.foreachOnPath_(path, newEmptyPath(), f);\n }\n\n private foreachOnPath_(\n pathToFollow: Path,\n currentRelativePath: Path,\n f: (path: Path, value: T) => void\n ): ImmutableTree {\n if (pathIsEmpty(pathToFollow)) {\n return this;\n } else {\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n const front = pathGetFront(pathToFollow);\n const nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.foreachOnPath_(\n pathPopFront(pathToFollow),\n pathChild(currentRelativePath, front),\n f\n );\n } else {\n return new ImmutableTree(null);\n }\n }\n }\n\n /**\n * Calls the given function for each node in the tree that has a value.\n *\n * @param f - A function to be called with the path from the root of the tree to\n * a node, and the value at that node. Called in depth-first order.\n */\n foreach(f: (path: Path, value: T) => void) {\n this.foreach_(newEmptyPath(), f);\n }\n\n private foreach_(\n currentRelativePath: Path,\n f: (path: Path, value: T) => void\n ) {\n this.children.inorderTraversal((childName, childTree) => {\n childTree.foreach_(pathChild(currentRelativePath, childName), f);\n });\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n }\n\n foreachChild(f: (name: string, value: T) => void) {\n this.children.inorderTraversal(\n (childName: string, childTree: ImmutableTree) => {\n if (childTree.value) {\n f(childName, childTree.value);\n }\n }\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { NamedNode, Node } from './snap/Node';\nimport { ImmutableTree } from './util/ImmutableTree';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathIsEmpty\n} from './util/Path';\nimport { each } from './util/util';\n\n/**\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\n * to reflect the write added.\n */\nexport class CompoundWrite {\n constructor(public writeTree_: ImmutableTree) {}\n\n static empty(): CompoundWrite {\n return new CompoundWrite(new ImmutableTree(null));\n }\n}\n\nexport function compoundWriteAddWrite(\n compoundWrite: CompoundWrite,\n path: Path,\n node: Node\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return new CompoundWrite(new ImmutableTree(node));\n } else {\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n const rootMostPath = rootmost.path;\n let value = rootmost.value;\n const relativePath = newRelativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(\n compoundWrite.writeTree_.set(rootMostPath, value)\n );\n } else {\n const subtree = new ImmutableTree(node);\n const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n}\n\nexport function compoundWriteAddWrites(\n compoundWrite: CompoundWrite,\n path: Path,\n updates: { [name: string]: Node }\n): CompoundWrite {\n let newWrite = compoundWrite;\n each(updates, (childKey: string, node: Node) => {\n newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);\n });\n return newWrite;\n}\n\n/**\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param compoundWrite - The CompoundWrite to remove.\n * @param path - The path at which a write and all deeper writes should be removed\n * @returns The new CompoundWrite with the removed path\n */\nexport function compoundWriteRemoveWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return CompoundWrite.empty();\n } else {\n const newWriteTree = compoundWrite.writeTree_.setTree(\n path,\n new ImmutableTree(null)\n );\n return new CompoundWrite(newWriteTree);\n }\n}\n\n/**\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\n * considered \"complete\".\n *\n * @param compoundWrite - The CompoundWrite to check.\n * @param path - The path to check for\n * @returns Whether there is a complete write at that path\n */\nexport function compoundWriteHasCompleteWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): boolean {\n return compoundWriteGetCompleteNode(compoundWrite, path) != null;\n}\n\n/**\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\n * writes from deeper paths, but will return child nodes from a more shallow path.\n *\n * @param compoundWrite - The CompoundWrite to get the node from.\n * @param path - The path to get a complete write\n * @returns The node if complete at that path, or null otherwise.\n */\nexport function compoundWriteGetCompleteNode(\n compoundWrite: CompoundWrite,\n path: Path\n): Node | null {\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return compoundWrite.writeTree_\n .get(rootmost.path)\n .getChild(newRelativePath(rootmost.path, path));\n } else {\n return null;\n }\n}\n\n/**\n * Returns all children that are guaranteed to be a complete overwrite.\n *\n * @param compoundWrite - The CompoundWrite to get children from.\n * @returns A list of all complete children.\n */\nexport function compoundWriteGetCompleteChildren(\n compoundWrite: CompoundWrite\n): NamedNode[] {\n const children: NamedNode[] = [];\n const node = compoundWrite.writeTree_.value;\n if (node != null) {\n // If it's a leaf node, it has no children; so nothing to do.\n if (!node.isLeafNode()) {\n (node as ChildrenNode).forEachChild(\n PRIORITY_INDEX,\n (childName, childNode) => {\n children.push(new NamedNode(childName, childNode));\n }\n );\n }\n } else {\n compoundWrite.writeTree_.children.inorderTraversal(\n (childName, childTree) => {\n if (childTree.value != null) {\n children.push(new NamedNode(childName, childTree.value));\n }\n }\n );\n }\n return children;\n}\n\nexport function compoundWriteChildCompoundWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return compoundWrite;\n } else {\n const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree(shadowingNode));\n } else {\n return new CompoundWrite(compoundWrite.writeTree_.subtree(path));\n }\n }\n}\n\n/**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @returns Whether this CompoundWrite is empty\n */\nexport function compoundWriteIsEmpty(compoundWrite: CompoundWrite): boolean {\n return compoundWrite.writeTree_.isEmpty();\n}\n\n/**\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\n * node\n * @param node - The node to apply this CompoundWrite to\n * @returns The node with all writes applied\n */\nexport function compoundWriteApply(\n compoundWrite: CompoundWrite,\n node: Node\n): Node {\n return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);\n}\n\nfunction applySubtreeWrite(\n relativePath: Path,\n writeTree: ImmutableTree,\n node: Node\n): Node {\n if (writeTree.value != null) {\n // Since there a write is always a leaf, we're done here\n return node.updateChild(relativePath, writeTree.value);\n } else {\n let priorityWrite = null;\n writeTree.children.inorderTraversal((childKey, childTree) => {\n if (childKey === '.priority') {\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\n // to apply priorities to empty nodes that are later filled\n assert(\n childTree.value !== null,\n 'Priority writes must always be leaf nodes'\n );\n priorityWrite = childTree.value;\n } else {\n node = applySubtreeWrite(\n pathChild(relativePath, childKey),\n childTree,\n node\n );\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {\n node = node.updateChild(\n pathChild(relativePath, '.priority'),\n priorityWrite\n );\n }\n return node;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError, safeGet } from '@firebase/util';\n\nimport {\n CompoundWrite,\n compoundWriteAddWrite,\n compoundWriteAddWrites,\n compoundWriteApply,\n compoundWriteChildCompoundWrite,\n compoundWriteGetCompleteChildren,\n compoundWriteGetCompleteNode,\n compoundWriteHasCompleteWrite,\n compoundWriteIsEmpty,\n compoundWriteRemoveWrite\n} from './CompoundWrite';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Index } from './snap/indexes/Index';\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { NamedNode, Node } from './snap/Node';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathContains,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from './util/Path';\nimport { each } from './util/util';\nimport { CacheNode } from './view/CacheNode';\n\n/**\n * Defines a single user-initiated write operation. May be the result of a set(), transaction(), or update() call. In\n * the case of a set() or transaction, snap will be non-null. In the case of an update(), children will be non-null.\n */\nexport interface WriteRecord {\n writeId: number;\n path: Path;\n snap?: Node | null;\n children?: { [k: string]: Node } | null;\n visible: boolean;\n}\n\n/**\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n */\nexport function writeTreeChildWrites(\n writeTree: WriteTree,\n path: Path\n): WriteTreeRef {\n return newWriteTreeRef(path, writeTree);\n}\n\n/**\n * Record a new overwrite from user code.\n *\n * @param visible - This is set to false by some transactions. It should be excluded from event caches\n */\nexport function writeTreeAddOverwrite(\n writeTree: WriteTree,\n path: Path,\n snap: Node,\n writeId: number,\n visible?: boolean\n) {\n assert(\n writeId > writeTree.lastWriteId,\n 'Stacking an older write on top of newer ones'\n );\n if (visible === undefined) {\n visible = true;\n }\n writeTree.allWrites.push({\n path,\n snap,\n writeId,\n visible\n });\n\n if (visible) {\n writeTree.visibleWrites = compoundWriteAddWrite(\n writeTree.visibleWrites,\n path,\n snap\n );\n }\n writeTree.lastWriteId = writeId;\n}\n\n/**\n * Record a new merge from user code.\n */\nexport function writeTreeAddMerge(\n writeTree: WriteTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n writeId: number\n) {\n assert(\n writeId > writeTree.lastWriteId,\n 'Stacking an older merge on top of newer ones'\n );\n writeTree.allWrites.push({\n path,\n children: changedChildren,\n writeId,\n visible: true\n });\n\n writeTree.visibleWrites = compoundWriteAddWrites(\n writeTree.visibleWrites,\n path,\n changedChildren\n );\n writeTree.lastWriteId = writeId;\n}\n\nexport function writeTreeGetWrite(\n writeTree: WriteTree,\n writeId: number\n): WriteRecord | null {\n for (let i = 0; i < writeTree.allWrites.length; i++) {\n const record = writeTree.allWrites[i];\n if (record.writeId === writeId) {\n return record;\n }\n }\n return null;\n}\n\n/**\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\n *\n * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\nexport function writeTreeRemoveWrite(\n writeTree: WriteTree,\n writeId: number\n): boolean {\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\n // out of order.\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\n\n const idx = writeTree.allWrites.findIndex(s => {\n return s.writeId === writeId;\n });\n assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n const writeToRemove = writeTree.allWrites[idx];\n writeTree.allWrites.splice(idx, 1);\n\n let removedWriteWasVisible = writeToRemove.visible;\n let removedWriteOverlapsWithOtherWrites = false;\n\n let i = writeTree.allWrites.length - 1;\n\n while (removedWriteWasVisible && i >= 0) {\n const currentWrite = writeTree.allWrites[i];\n if (currentWrite.visible) {\n if (\n i >= idx &&\n writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)\n ) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\n } else if (pathContains(writeToRemove.path, currentWrite.path)) {\n // Either we're covering some writes or they're covering part of us (depending on which came first).\n removedWriteOverlapsWithOtherWrites = true;\n }\n }\n i--;\n }\n\n if (!removedWriteWasVisible) {\n return false;\n } else if (removedWriteOverlapsWithOtherWrites) {\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\n writeTreeResetTree_(writeTree);\n return true;\n } else {\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\n if (writeToRemove.snap) {\n writeTree.visibleWrites = compoundWriteRemoveWrite(\n writeTree.visibleWrites,\n writeToRemove.path\n );\n } else {\n const children = writeToRemove.children;\n each(children, (childName: string) => {\n writeTree.visibleWrites = compoundWriteRemoveWrite(\n writeTree.visibleWrites,\n pathChild(writeToRemove.path, childName)\n );\n });\n }\n return true;\n }\n}\n\nfunction writeTreeRecordContainsPath_(\n writeRecord: WriteRecord,\n path: Path\n): boolean {\n if (writeRecord.snap) {\n return pathContains(writeRecord.path, path);\n } else {\n for (const childName in writeRecord.children) {\n if (\n writeRecord.children.hasOwnProperty(childName) &&\n pathContains(pathChild(writeRecord.path, childName), path)\n ) {\n return true;\n }\n }\n return false;\n }\n}\n\n/**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\n */\nfunction writeTreeResetTree_(writeTree: WriteTree) {\n writeTree.visibleWrites = writeTreeLayerTree_(\n writeTree.allWrites,\n writeTreeDefaultFilter_,\n newEmptyPath()\n );\n if (writeTree.allWrites.length > 0) {\n writeTree.lastWriteId =\n writeTree.allWrites[writeTree.allWrites.length - 1].writeId;\n } else {\n writeTree.lastWriteId = -1;\n }\n}\n\n/**\n * The default filter used when constructing the tree. Keep everything that's visible.\n */\nfunction writeTreeDefaultFilter_(write: WriteRecord) {\n return write.visible;\n}\n\n/**\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\n * event data at that path.\n */\nfunction writeTreeLayerTree_(\n writes: WriteRecord[],\n filter: (w: WriteRecord) => boolean,\n treeRoot: Path\n): CompoundWrite {\n let compoundWrite = CompoundWrite.empty();\n for (let i = 0; i < writes.length; ++i) {\n const write = writes[i];\n // Theory, a later set will either:\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\n if (filter(write)) {\n const writePath = write.path;\n let relativePath: Path;\n if (write.snap) {\n if (pathContains(treeRoot, writePath)) {\n relativePath = newRelativePath(treeRoot, writePath);\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n relativePath,\n write.snap\n );\n } else if (pathContains(writePath, treeRoot)) {\n relativePath = newRelativePath(writePath, treeRoot);\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n newEmptyPath(),\n write.snap.getChild(relativePath)\n );\n } else {\n // There is no overlap between root path and write path, ignore write\n }\n } else if (write.children) {\n if (pathContains(treeRoot, writePath)) {\n relativePath = newRelativePath(treeRoot, writePath);\n compoundWrite = compoundWriteAddWrites(\n compoundWrite,\n relativePath,\n write.children\n );\n } else if (pathContains(writePath, treeRoot)) {\n relativePath = newRelativePath(writePath, treeRoot);\n if (pathIsEmpty(relativePath)) {\n compoundWrite = compoundWriteAddWrites(\n compoundWrite,\n newEmptyPath(),\n write.children\n );\n } else {\n const child = safeGet(write.children, pathGetFront(relativePath));\n if (child) {\n // There exists a child in this node that matches the root path\n const deepNode = child.getChild(pathPopFront(relativePath));\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n newEmptyPath(),\n deepNode\n );\n }\n }\n } else {\n // There is no overlap between root path and write path, ignore write\n }\n } else {\n throw assertionError('WriteRecord should have .snap or .children');\n }\n }\n }\n return compoundWrite;\n}\n\n/**\n * Return a complete snapshot for the given path if there's visible write data at that path, else null.\n * No server data is considered.\n *\n */\nexport function writeTreeGetCompleteWriteData(\n writeTree: WriteTree,\n path: Path\n): Node | null {\n return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\n}\n\n/**\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\n * writes), attempt to calculate a complete snapshot for the given path\n *\n * @param writeIdsToExclude - An optional set to be excluded\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\n */\nexport function writeTreeCalcCompleteEventCache(\n writeTree: WriteTree,\n treePath: Path,\n completeServerCache: Node | null,\n writeIdsToExclude?: number[],\n includeHiddenWrites?: boolean\n): Node | null {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n const shadowingNode = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n treePath\n );\n if (shadowingNode != null) {\n return shadowingNode;\n } else {\n const subMerge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n if (compoundWriteIsEmpty(subMerge)) {\n return completeServerCache;\n } else if (\n completeServerCache == null &&\n !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())\n ) {\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n return null;\n } else {\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\n return compoundWriteApply(subMerge, layeredCache);\n }\n }\n } else {\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {\n return completeServerCache;\n } else {\n // If the server cache is null, and we don't have a complete cache, we need to return null\n if (\n !includeHiddenWrites &&\n completeServerCache == null &&\n !compoundWriteHasCompleteWrite(merge, newEmptyPath())\n ) {\n return null;\n } else {\n const filter = function (write: WriteRecord) {\n return (\n (write.visible || includeHiddenWrites) &&\n (!writeIdsToExclude ||\n !~writeIdsToExclude.indexOf(write.writeId)) &&\n (pathContains(write.path, treePath) ||\n pathContains(treePath, write.path))\n );\n };\n const mergeAtPath = writeTreeLayerTree_(\n writeTree.allWrites,\n filter,\n treePath\n );\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\n return compoundWriteApply(mergeAtPath, layeredCache);\n }\n }\n }\n}\n\n/**\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\n * Used when creating new views, to pre-fill their complete event children snapshot.\n */\nexport function writeTreeCalcCompleteEventChildren(\n writeTree: WriteTree,\n treePath: Path,\n completeServerChildren: ChildrenNode | null\n) {\n let completeChildren = ChildrenNode.EMPTY_NODE as Node;\n const topLevelSet = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n treePath\n );\n if (topLevelSet) {\n if (!topLevelSet.isLeafNode()) {\n // we're shadowing everything. Return the children.\n topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {\n completeChildren = completeChildren.updateImmediateChild(\n childName,\n childSnap\n );\n });\n }\n return completeChildren;\n } else if (completeServerChildren) {\n // Layer any children we have on top of this\n // We know we don't have a top-level set, so just enumerate existing children\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n completeServerChildren.forEachChild(\n PRIORITY_INDEX,\n (childName, childNode) => {\n const node = compoundWriteApply(\n compoundWriteChildCompoundWrite(merge, new Path(childName)),\n childNode\n );\n completeChildren = completeChildren.updateImmediateChild(\n childName,\n node\n );\n }\n );\n // Add any complete children we have from the set\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\n completeChildren = completeChildren.updateImmediateChild(\n namedNode.name,\n namedNode.node\n );\n });\n return completeChildren;\n } else {\n // We don't have anything to layer on top of. Layer on any children we have\n // Note that we can return an empty snap if we have a defined delete\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\n completeChildren = completeChildren.updateImmediateChild(\n namedNode.name,\n namedNode.node\n );\n });\n return completeChildren;\n }\n}\n\n/**\n * Given that the underlying server data has updated, determine what, if anything, needs to be\n * applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events\n *\n * Either existingEventSnap or existingServerSnap must exist\n */\nexport function writeTreeCalcEventCacheAfterServerOverwrite(\n writeTree: WriteTree,\n treePath: Path,\n childPath: Path,\n existingEventSnap: Node | null,\n existingServerSnap: Node | null\n): Node | null {\n assert(\n existingEventSnap || existingServerSnap,\n 'Either existingEventSnap or existingServerSnap must exist'\n );\n const path = pathChild(treePath, childPath);\n if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {\n // At this point we can probably guarantee that we're in case 2, meaning no events\n // May need to check visibility while doing the findRootMostValueAndPath call\n return null;\n } else {\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\n const childMerge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n path\n );\n if (compoundWriteIsEmpty(childMerge)) {\n // We're not shadowing at all. Case 1\n return existingServerSnap.getChild(childPath);\n } else {\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\n // However this is tricky to find out, since user updates don't necessary change the server\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\n // only check if the updates change the serverNode.\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\n return compoundWriteApply(\n childMerge,\n existingServerSnap.getChild(childPath)\n );\n }\n }\n}\n\n/**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n */\nexport function writeTreeCalcCompleteChild(\n writeTree: WriteTree,\n treePath: Path,\n childKey: string,\n existingServerSnap: CacheNode\n): Node | null {\n const path = pathChild(treePath, childKey);\n const shadowingNode = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n path\n );\n if (shadowingNode != null) {\n return shadowingNode;\n } else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n const childMerge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n path\n );\n return compoundWriteApply(\n childMerge,\n existingServerSnap.getNode().getImmediateChild(childKey)\n );\n } else {\n return null;\n }\n }\n}\n\n/**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n */\nexport function writeTreeShadowingWrite(\n writeTree: WriteTree,\n path: Path\n): Node | null {\n return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\n}\n\n/**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window.\n */\nexport function writeTreeCalcIndexedSlice(\n writeTree: WriteTree,\n treePath: Path,\n completeServerData: Node | null,\n startPost: NamedNode,\n count: number,\n reverse: boolean,\n index: Index\n): NamedNode[] {\n let toIterate: Node;\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n } else if (completeServerData != null) {\n toIterate = compoundWriteApply(merge, completeServerData);\n } else {\n // no children to iterate on\n return [];\n }\n toIterate = toIterate.withIndex(index);\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n const nodes = [];\n const cmp = index.getCompare();\n const iter = reverse\n ? (toIterate as ChildrenNode).getReverseIteratorFrom(startPost, index)\n : (toIterate as ChildrenNode).getIteratorFrom(startPost, index);\n let next = iter.getNext();\n while (next && nodes.length < count) {\n if (cmp(next, startPost) !== 0) {\n nodes.push(next);\n }\n next = iter.getNext();\n }\n return nodes;\n } else {\n return [];\n }\n}\n\nexport function newWriteTree(): WriteTree {\n return {\n visibleWrites: CompoundWrite.empty(),\n allWrites: [],\n lastWriteId: -1\n };\n}\n\n/**\n * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them\n * with underlying server data (to create \"event cache\" data). Pending writes are added with addOverwrite()\n * and addMerge(), and removed with removeWrite().\n */\nexport interface WriteTree {\n /**\n * A tree tracking the result of applying all visible writes. This does not include transactions with\n * applyLocally=false or writes that are completely shadowed by other writes.\n */\n visibleWrites: CompoundWrite;\n\n /**\n * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary\n * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also\n * used by transactions).\n */\n allWrites: WriteRecord[];\n\n lastWriteId: number;\n}\n\n/**\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\n * can lead to a more expensive calculation.\n *\n * @param writeIdsToExclude - Optional writes to exclude.\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\n */\nexport function writeTreeRefCalcCompleteEventCache(\n writeTreeRef: WriteTreeRef,\n completeServerCache: Node | null,\n writeIdsToExclude?: number[],\n includeHiddenWrites?: boolean\n): Node | null {\n return writeTreeCalcCompleteEventCache(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n completeServerCache,\n writeIdsToExclude,\n includeHiddenWrites\n );\n}\n\n/**\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\n * mix of the given server data and write data.\n *\n */\nexport function writeTreeRefCalcCompleteEventChildren(\n writeTreeRef: WriteTreeRef,\n completeServerChildren: ChildrenNode | null\n): ChildrenNode {\n return writeTreeCalcCompleteEventChildren(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n completeServerChildren\n ) as ChildrenNode;\n}\n\n/**\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\n * if anything, needs to be applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events should be raised\n *\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\n *\n *\n */\nexport function writeTreeRefCalcEventCacheAfterServerOverwrite(\n writeTreeRef: WriteTreeRef,\n path: Path,\n existingEventSnap: Node | null,\n existingServerSnap: Node | null\n): Node | null {\n return writeTreeCalcEventCacheAfterServerOverwrite(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n path,\n existingEventSnap,\n existingServerSnap\n );\n}\n\n/**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n */\nexport function writeTreeRefShadowingWrite(\n writeTreeRef: WriteTreeRef,\n path: Path\n): Node | null {\n return writeTreeShadowingWrite(\n writeTreeRef.writeTree,\n pathChild(writeTreeRef.treePath, path)\n );\n}\n\n/**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window\n */\nexport function writeTreeRefCalcIndexedSlice(\n writeTreeRef: WriteTreeRef,\n completeServerData: Node | null,\n startPost: NamedNode,\n count: number,\n reverse: boolean,\n index: Index\n): NamedNode[] {\n return writeTreeCalcIndexedSlice(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n completeServerData,\n startPost,\n count,\n reverse,\n index\n );\n}\n\n/**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n */\nexport function writeTreeRefCalcCompleteChild(\n writeTreeRef: WriteTreeRef,\n childKey: string,\n existingServerCache: CacheNode\n): Node | null {\n return writeTreeCalcCompleteChild(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n childKey,\n existingServerCache\n );\n}\n\n/**\n * Return a WriteTreeRef for a child.\n */\nexport function writeTreeRefChild(\n writeTreeRef: WriteTreeRef,\n childName: string\n): WriteTreeRef {\n return newWriteTreeRef(\n pathChild(writeTreeRef.treePath, childName),\n writeTreeRef.writeTree\n );\n}\n\nexport function newWriteTreeRef(\n path: Path,\n writeTree: WriteTree\n): WriteTreeRef {\n return {\n treePath: path,\n writeTree\n };\n}\n\n/**\n * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods\n * just proxy to the underlying WriteTree.\n *\n */\nexport interface WriteTreeRef {\n /**\n * The path to this particular write tree ref. Used for calling methods on writeTree_ while exposing a simpler\n * interface to callers.\n */\n readonly treePath: Path;\n\n /**\n * * A reference to the actual tree of write data. All methods are pass-through to the tree, but with the appropriate\n * path prefixed.\n *\n * This lets us make cheap references to points in the tree for sync points without having to copy and maintain all of\n * the data.\n */\n readonly writeTree: WriteTree;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport {\n Change,\n ChangeType,\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from './Change';\n\nexport class ChildChangeAccumulator {\n private readonly changeMap: Map = new Map();\n\n trackChildChange(change: Change) {\n const type = change.type;\n const childKey = change.childName!;\n assert(\n type === ChangeType.CHILD_ADDED ||\n type === ChangeType.CHILD_CHANGED ||\n type === ChangeType.CHILD_REMOVED,\n 'Only child changes supported for tracking'\n );\n assert(\n childKey !== '.priority',\n 'Only non-priority child changes can be tracked.'\n );\n const oldChange = this.changeMap.get(childKey);\n if (oldChange) {\n const oldType = oldChange.type;\n if (\n type === ChangeType.CHILD_ADDED &&\n oldType === ChangeType.CHILD_REMOVED\n ) {\n this.changeMap.set(\n childKey,\n changeChildChanged(\n childKey,\n change.snapshotNode,\n oldChange.snapshotNode\n )\n );\n } else if (\n type === ChangeType.CHILD_REMOVED &&\n oldType === ChangeType.CHILD_ADDED\n ) {\n this.changeMap.delete(childKey);\n } else if (\n type === ChangeType.CHILD_REMOVED &&\n oldType === ChangeType.CHILD_CHANGED\n ) {\n this.changeMap.set(\n childKey,\n changeChildRemoved(childKey, oldChange.oldSnap)\n );\n } else if (\n type === ChangeType.CHILD_CHANGED &&\n oldType === ChangeType.CHILD_ADDED\n ) {\n this.changeMap.set(\n childKey,\n changeChildAdded(childKey, change.snapshotNode)\n );\n } else if (\n type === ChangeType.CHILD_CHANGED &&\n oldType === ChangeType.CHILD_CHANGED\n ) {\n this.changeMap.set(\n childKey,\n changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap)\n );\n } else {\n throw assertionError(\n 'Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange\n );\n }\n } else {\n this.changeMap.set(childKey, change);\n }\n }\n\n getChanges(): Change[] {\n return Array.from(this.changeMap.values());\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Index } from '../snap/indexes/Index';\nimport { NamedNode, Node } from '../snap/Node';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteChild,\n writeTreeRefCalcIndexedSlice\n} from '../WriteTree';\n\nimport { CacheNode } from './CacheNode';\nimport { ViewCache, viewCacheGetCompleteServerSnap } from './ViewCache';\n\n/**\n * Since updates to filtered nodes might require nodes to be pulled in from \"outside\" the node, this interface\n * can help to get complete children that can be pulled in.\n * A class implementing this interface takes potentially multiple sources (e.g. user writes, server data from\n * other views etc.) to try it's best to get a complete child that might be useful in pulling into the view.\n *\n * @interface\n */\nexport interface CompleteChildSource {\n getCompleteChild(childKey: string): Node | null;\n\n getChildAfterChild(\n index: Index,\n child: NamedNode,\n reverse: boolean\n ): NamedNode | null;\n}\n\n/**\n * An implementation of CompleteChildSource that never returns any additional children\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class NoCompleteChildSource_ implements CompleteChildSource {\n getCompleteChild(childKey?: string): Node | null {\n return null;\n }\n getChildAfterChild(\n index?: Index,\n child?: NamedNode,\n reverse?: boolean\n ): NamedNode | null {\n return null;\n }\n}\n\n/**\n * Singleton instance.\n */\nexport const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n\n/**\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\n * old event caches available to calculate complete children.\n */\nexport class WriteTreeCompleteChildSource implements CompleteChildSource {\n constructor(\n private writes_: WriteTreeRef,\n private viewCache_: ViewCache,\n private optCompleteServerCache_: Node | null = null\n ) {}\n getCompleteChild(childKey: string): Node | null {\n const node = this.viewCache_.eventCache;\n if (node.isCompleteForChild(childKey)) {\n return node.getNode().getImmediateChild(childKey);\n } else {\n const serverNode =\n this.optCompleteServerCache_ != null\n ? new CacheNode(this.optCompleteServerCache_, true, false)\n : this.viewCache_.serverCache;\n return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);\n }\n }\n getChildAfterChild(\n index: Index,\n child: NamedNode,\n reverse: boolean\n ): NamedNode | null {\n const completeServerData =\n this.optCompleteServerCache_ != null\n ? this.optCompleteServerCache_\n : viewCacheGetCompleteServerSnap(this.viewCache_);\n const nodes = writeTreeRefCalcIndexedSlice(\n this.writes_,\n completeServerData,\n child,\n 1,\n reverse,\n index\n );\n if (nodes.length === 0) {\n return null;\n } else {\n return nodes[0];\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport { AckUserWrite } from '../operation/AckUserWrite';\nimport { Merge } from '../operation/Merge';\nimport { Operation, OperationType } from '../operation/Operation';\nimport { Overwrite } from '../operation/Overwrite';\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { KEY_INDEX } from '../snap/indexes/KeyIndex';\nimport { Node } from '../snap/Node';\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathChild,\n pathGetBack,\n pathGetFront,\n pathGetLength,\n pathIsEmpty,\n pathParent,\n pathPopFront\n} from '../util/Path';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteChild,\n writeTreeRefCalcCompleteEventCache,\n writeTreeRefCalcCompleteEventChildren,\n writeTreeRefCalcEventCacheAfterServerOverwrite,\n writeTreeRefShadowingWrite\n} from '../WriteTree';\n\nimport { Change, changeValue } from './Change';\nimport { ChildChangeAccumulator } from './ChildChangeAccumulator';\nimport {\n CompleteChildSource,\n NO_COMPLETE_CHILD_SOURCE,\n WriteTreeCompleteChildSource\n} from './CompleteChildSource';\nimport { NodeFilter } from './filter/NodeFilter';\nimport {\n ViewCache,\n viewCacheGetCompleteEventSnap,\n viewCacheGetCompleteServerSnap,\n viewCacheUpdateEventSnap,\n viewCacheUpdateServerSnap\n} from './ViewCache';\n\nexport interface ProcessorResult {\n readonly viewCache: ViewCache;\n readonly changes: Change[];\n}\n\nexport interface ViewProcessor {\n readonly filter: NodeFilter;\n}\n\nexport function newViewProcessor(filter: NodeFilter): ViewProcessor {\n return { filter };\n}\n\nexport function viewProcessorAssertIndexed(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache\n): void {\n assert(\n viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()),\n 'Event snap not indexed'\n );\n assert(\n viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()),\n 'Server snap not indexed'\n );\n}\n\nexport function viewProcessorApplyOperation(\n viewProcessor: ViewProcessor,\n oldViewCache: ViewCache,\n operation: Operation,\n writesCache: WriteTreeRef,\n completeCache: Node | null\n): ProcessorResult {\n const accumulator = new ChildChangeAccumulator();\n let newViewCache, filterServerNode;\n if (operation.type === OperationType.OVERWRITE) {\n const overwrite = operation as Overwrite;\n if (overwrite.source.fromUser) {\n newViewCache = viewProcessorApplyUserOverwrite(\n viewProcessor,\n oldViewCache,\n overwrite.path,\n overwrite.snap,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n assert(overwrite.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered and the\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\n // again\n filterServerNode =\n overwrite.source.tagged ||\n (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));\n newViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\n oldViewCache,\n overwrite.path,\n overwrite.snap,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n } else if (operation.type === OperationType.MERGE) {\n const merge = operation as Merge;\n if (merge.source.fromUser) {\n newViewCache = viewProcessorApplyUserMerge(\n viewProcessor,\n oldViewCache,\n merge.path,\n merge.children,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n assert(merge.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered\n filterServerNode =\n merge.source.tagged || oldViewCache.serverCache.isFiltered();\n newViewCache = viewProcessorApplyServerMerge(\n viewProcessor,\n oldViewCache,\n merge.path,\n merge.children,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n } else if (operation.type === OperationType.ACK_USER_WRITE) {\n const ackUserWrite = operation as AckUserWrite;\n if (!ackUserWrite.revert) {\n newViewCache = viewProcessorAckUserWrite(\n viewProcessor,\n oldViewCache,\n ackUserWrite.path,\n ackUserWrite.affectedTree,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n newViewCache = viewProcessorRevertUserWrite(\n viewProcessor,\n oldViewCache,\n ackUserWrite.path,\n writesCache,\n completeCache,\n accumulator\n );\n }\n } else if (operation.type === OperationType.LISTEN_COMPLETE) {\n newViewCache = viewProcessorListenComplete(\n viewProcessor,\n oldViewCache,\n operation.path,\n writesCache,\n accumulator\n );\n } else {\n throw assertionError('Unknown operation type: ' + operation.type);\n }\n const changes = accumulator.getChanges();\n viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);\n return { viewCache: newViewCache, changes };\n}\n\nfunction viewProcessorMaybeAddValueEvent(\n oldViewCache: ViewCache,\n newViewCache: ViewCache,\n accumulator: Change[]\n): void {\n const eventSnap = newViewCache.eventCache;\n if (eventSnap.isFullyInitialized()) {\n const isLeafOrEmpty =\n eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);\n if (\n accumulator.length > 0 ||\n !oldViewCache.eventCache.isFullyInitialized() ||\n (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||\n !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())\n ) {\n accumulator.push(\n changeValue(viewCacheGetCompleteEventSnap(newViewCache))\n );\n }\n }\n}\n\nfunction viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n changePath: Path,\n writesCache: WriteTreeRef,\n source: CompleteChildSource,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldEventSnap = viewCache.eventCache;\n if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n } else {\n let newEventCache, serverNode;\n if (pathIsEmpty(changePath)) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n assert(\n viewCache.serverCache.isFullyInitialized(),\n 'If change path is empty, we must have complete server data'\n );\n if (viewCache.serverCache.isFiltered()) {\n // We need to special case this, because we need to only apply writes to complete children, or\n // we might end up raising events for incomplete children. If the server data is filtered deep\n // writes cannot be guaranteed to be complete\n const serverCache = viewCacheGetCompleteServerSnap(viewCache);\n const completeChildren =\n serverCache instanceof ChildrenNode\n ? serverCache\n : ChildrenNode.EMPTY_NODE;\n const completeEventChildren = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n completeChildren\n );\n newEventCache = viewProcessor.filter.updateFullNode(\n viewCache.eventCache.getNode(),\n completeEventChildren,\n accumulator\n );\n } else {\n const completeNode = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n newEventCache = viewProcessor.filter.updateFullNode(\n viewCache.eventCache.getNode(),\n completeNode,\n accumulator\n );\n }\n } else {\n const childKey = pathGetFront(changePath);\n if (childKey === '.priority') {\n assert(\n pathGetLength(changePath) === 1,\n \"Can't have a priority with additional path components\"\n );\n const oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.serverCache.getNode();\n // we might have overwrites for this priority\n const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(\n writesCache,\n changePath,\n oldEventNode,\n serverNode\n );\n if (updatedPriority != null) {\n newEventCache = viewProcessor.filter.updatePriority(\n oldEventNode,\n updatedPriority\n );\n } else {\n // priority didn't change, keep old node\n newEventCache = oldEventSnap.getNode();\n }\n } else {\n const childChangePath = pathPopFront(changePath);\n // update child\n let newEventChild;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.serverCache.getNode();\n const eventChildUpdate =\n writeTreeRefCalcEventCacheAfterServerOverwrite(\n writesCache,\n changePath,\n oldEventSnap.getNode(),\n serverNode\n );\n if (eventChildUpdate != null) {\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey)\n .updateChild(childChangePath, eventChildUpdate);\n } else {\n // Nothing changed, just keep the old child\n newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);\n }\n } else {\n newEventChild = writeTreeRefCalcCompleteChild(\n writesCache,\n childKey,\n viewCache.serverCache\n );\n }\n if (newEventChild != null) {\n newEventCache = viewProcessor.filter.updateChild(\n oldEventSnap.getNode(),\n childKey,\n newEventChild,\n childChangePath,\n source,\n accumulator\n );\n } else {\n // no complete child available or no change\n newEventCache = oldEventSnap.getNode();\n }\n }\n }\n return viewCacheUpdateEventSnap(\n viewCache,\n newEventCache,\n oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath),\n viewProcessor.filter.filtersNodes()\n );\n }\n}\n\nfunction viewProcessorApplyServerOverwrite(\n viewProcessor: ViewProcessor,\n oldViewCache: ViewCache,\n changePath: Path,\n changedSnap: Node,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n filterServerNode: boolean,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldServerSnap = oldViewCache.serverCache;\n let newServerCache;\n const serverFilter = filterServerNode\n ? viewProcessor.filter\n : viewProcessor.filter.getIndexedFilter();\n if (pathIsEmpty(changePath)) {\n newServerCache = serverFilter.updateFullNode(\n oldServerSnap.getNode(),\n changedSnap,\n null\n );\n } else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\n const newServerNode = oldServerSnap\n .getNode()\n .updateChild(changePath, changedSnap);\n newServerCache = serverFilter.updateFullNode(\n oldServerSnap.getNode(),\n newServerNode,\n null\n );\n } else {\n const childKey = pathGetFront(changePath);\n if (\n !oldServerSnap.isCompleteForPath(changePath) &&\n pathGetLength(changePath) > 1\n ) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n const childChangePath = pathPopFront(changePath);\n const childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n const newChildNode = childNode.updateChild(childChangePath, changedSnap);\n if (childKey === '.priority') {\n newServerCache = serverFilter.updatePriority(\n oldServerSnap.getNode(),\n newChildNode\n );\n } else {\n newServerCache = serverFilter.updateChild(\n oldServerSnap.getNode(),\n childKey,\n newChildNode,\n childChangePath,\n NO_COMPLETE_CHILD_SOURCE,\n null\n );\n }\n }\n const newViewCache = viewCacheUpdateServerSnap(\n oldViewCache,\n newServerCache,\n oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath),\n serverFilter.filtersNodes()\n );\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n newViewCache,\n completeCache\n );\n return viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor,\n newViewCache,\n changePath,\n writesCache,\n source,\n accumulator\n );\n}\n\nfunction viewProcessorApplyUserOverwrite(\n viewProcessor: ViewProcessor,\n oldViewCache: ViewCache,\n changePath: Path,\n changedSnap: Node,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldEventSnap = oldViewCache.eventCache;\n let newViewCache, newEventCache;\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n oldViewCache,\n completeCache\n );\n if (pathIsEmpty(changePath)) {\n newEventCache = viewProcessor.filter.updateFullNode(\n oldViewCache.eventCache.getNode(),\n changedSnap,\n accumulator\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventCache,\n true,\n viewProcessor.filter.filtersNodes()\n );\n } else {\n const childKey = pathGetFront(changePath);\n if (childKey === '.priority') {\n newEventCache = viewProcessor.filter.updatePriority(\n oldViewCache.eventCache.getNode(),\n changedSnap\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventCache,\n oldEventSnap.isFullyInitialized(),\n oldEventSnap.isFiltered()\n );\n } else {\n const childChangePath = pathPopFront(changePath);\n const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n let newChild;\n if (pathIsEmpty(childChangePath)) {\n // Child overwrite, we can replace the child\n newChild = changedSnap;\n } else {\n const childNode = source.getCompleteChild(childKey);\n if (childNode != null) {\n if (\n pathGetBack(childChangePath) === '.priority' &&\n childNode.getChild(pathParent(childChangePath)).isEmpty()\n ) {\n // This is a priority update on an empty node. If this node exists on the server, the\n // server will send down the priority in the update, so ignore for now\n newChild = childNode;\n } else {\n newChild = childNode.updateChild(childChangePath, changedSnap);\n }\n } else {\n // There is no complete child node available\n newChild = ChildrenNode.EMPTY_NODE;\n }\n }\n if (!oldChild.equals(newChild)) {\n const newEventSnap = viewProcessor.filter.updateChild(\n oldEventSnap.getNode(),\n childKey,\n newChild,\n childChangePath,\n source,\n accumulator\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventSnap,\n oldEventSnap.isFullyInitialized(),\n viewProcessor.filter.filtersNodes()\n );\n } else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n}\n\nfunction viewProcessorCacheHasChild(\n viewCache: ViewCache,\n childKey: string\n): boolean {\n return viewCache.eventCache.isCompleteForChild(childKey);\n}\n\nfunction viewProcessorApplyUserMerge(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n changedChildren: ImmutableTree,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n let curViewCache = viewCache;\n changedChildren.foreach((relativePath, childNode) => {\n const writePath = pathChild(path, relativePath);\n if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\n curViewCache = viewProcessorApplyUserOverwrite(\n viewProcessor,\n curViewCache,\n writePath,\n childNode,\n writesCache,\n serverCache,\n accumulator\n );\n }\n });\n\n changedChildren.foreach((relativePath, childNode) => {\n const writePath = pathChild(path, relativePath);\n if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\n curViewCache = viewProcessorApplyUserOverwrite(\n viewProcessor,\n curViewCache,\n writePath,\n childNode,\n writesCache,\n serverCache,\n accumulator\n );\n }\n });\n\n return curViewCache;\n}\n\nfunction viewProcessorApplyMerge(\n viewProcessor: ViewProcessor,\n node: Node,\n merge: ImmutableTree\n): Node {\n merge.foreach((relativePath, childNode) => {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n}\n\nfunction viewProcessorApplyServerMerge(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n changedChildren: ImmutableTree,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n filterServerNode: boolean,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\n // wait for the complete data update coming soon.\n if (\n viewCache.serverCache.getNode().isEmpty() &&\n !viewCache.serverCache.isFullyInitialized()\n ) {\n return viewCache;\n }\n\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n let curViewCache = viewCache;\n let viewMergeTree: ImmutableTree;\n if (pathIsEmpty(path)) {\n viewMergeTree = changedChildren;\n } else {\n viewMergeTree = new ImmutableTree(null).setTree(\n path,\n changedChildren\n );\n }\n const serverNode = viewCache.serverCache.getNode();\n viewMergeTree.children.inorderTraversal((childKey, childTree) => {\n if (serverNode.hasChild(childKey)) {\n const serverChild = viewCache.serverCache\n .getNode()\n .getImmediateChild(childKey);\n const newChild = viewProcessorApplyMerge(\n viewProcessor,\n serverChild,\n childTree\n );\n curViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\n curViewCache,\n new Path(childKey),\n newChild,\n writesCache,\n serverCache,\n filterServerNode,\n accumulator\n );\n }\n });\n viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {\n const isUnknownDeepMerge =\n !viewCache.serverCache.isCompleteForChild(childKey) &&\n childMergeTree.value === null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n const serverChild = viewCache.serverCache\n .getNode()\n .getImmediateChild(childKey);\n const newChild = viewProcessorApplyMerge(\n viewProcessor,\n serverChild,\n childMergeTree\n );\n curViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\n curViewCache,\n new Path(childKey),\n newChild,\n writesCache,\n serverCache,\n filterServerNode,\n accumulator\n );\n }\n });\n\n return curViewCache;\n}\n\nfunction viewProcessorAckUserWrite(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n ackPath: Path,\n affectedTree: ImmutableTree,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {\n return viewCache;\n }\n\n // Only filter server node if it is currently filtered\n const filterServerNode = viewCache.serverCache.isFiltered();\n\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\n // now that it won't be shadowed.\n const serverCache = viewCache.serverCache;\n if (affectedTree.value != null) {\n // This is an overwrite.\n if (\n (pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)\n ) {\n return viewProcessorApplyServerOverwrite(\n viewProcessor,\n viewCache,\n ackPath,\n serverCache.getNode().getChild(ackPath),\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n } else if (pathIsEmpty(ackPath)) {\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\n // should just re-apply whatever we have in our cache as a merge.\n let changedChildren = new ImmutableTree(null);\n serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {\n changedChildren = changedChildren.set(new Path(name), node);\n });\n return viewProcessorApplyServerMerge(\n viewProcessor,\n viewCache,\n ackPath,\n changedChildren,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n } else {\n return viewCache;\n }\n } else {\n // This is a merge.\n let changedChildren = new ImmutableTree(null);\n affectedTree.foreach((mergePath, value) => {\n const serverCachePath = pathChild(ackPath, mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren = changedChildren.set(\n mergePath,\n serverCache.getNode().getChild(serverCachePath)\n );\n }\n });\n return viewProcessorApplyServerMerge(\n viewProcessor,\n viewCache,\n ackPath,\n changedChildren,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n}\n\nfunction viewProcessorListenComplete(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n writesCache: WriteTreeRef,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldServerNode = viewCache.serverCache;\n const newViewCache = viewCacheUpdateServerSnap(\n viewCache,\n oldServerNode.getNode(),\n oldServerNode.isFullyInitialized() || pathIsEmpty(path),\n oldServerNode.isFiltered()\n );\n return viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor,\n newViewCache,\n path,\n writesCache,\n NO_COMPLETE_CHILD_SOURCE,\n accumulator\n );\n}\n\nfunction viewProcessorRevertUserWrite(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n writesCache: WriteTreeRef,\n completeServerCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n let complete;\n if (writeTreeRefShadowingWrite(writesCache, path) != null) {\n return viewCache;\n } else {\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n viewCache,\n completeServerCache\n );\n const oldEventCache = viewCache.eventCache.getNode();\n let newEventCache;\n if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {\n let newNode;\n if (viewCache.serverCache.isFullyInitialized()) {\n newNode = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n } else {\n const serverChildren = viewCache.serverCache.getNode();\n assert(\n serverChildren instanceof ChildrenNode,\n 'serverChildren would be complete if leaf node'\n );\n newNode = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n serverChildren as ChildrenNode\n );\n }\n newNode = newNode as Node;\n newEventCache = viewProcessor.filter.updateFullNode(\n oldEventCache,\n newNode,\n accumulator\n );\n } else {\n const childKey = pathGetFront(path);\n let newChild = writeTreeRefCalcCompleteChild(\n writesCache,\n childKey,\n viewCache.serverCache\n );\n if (\n newChild == null &&\n viewCache.serverCache.isCompleteForChild(childKey)\n ) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = viewProcessor.filter.updateChild(\n oldEventCache,\n childKey,\n newChild,\n pathPopFront(path),\n source,\n accumulator\n );\n } else if (viewCache.eventCache.getNode().hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = viewProcessor.filter.updateChild(\n oldEventCache,\n childKey,\n ChildrenNode.EMPTY_NODE,\n pathPopFront(path),\n source,\n accumulator\n );\n } else {\n newEventCache = oldEventCache;\n }\n if (\n newEventCache.isEmpty() &&\n viewCache.serverCache.isFullyInitialized()\n ) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n if (complete.isLeafNode()) {\n newEventCache = viewProcessor.filter.updateFullNode(\n newEventCache,\n complete,\n accumulator\n );\n }\n }\n }\n complete =\n viewCache.serverCache.isFullyInitialized() ||\n writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;\n return viewCacheUpdateEventSnap(\n viewCache,\n newEventCache,\n complete,\n viewProcessor.filter.filtersNodes()\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Operation, OperationType } from '../operation/Operation';\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { PRIORITY_INDEX } from '../snap/indexes/PriorityIndex';\nimport { Node } from '../snap/Node';\nimport { Path, pathGetFront, pathIsEmpty } from '../util/Path';\nimport { WriteTreeRef } from '../WriteTree';\n\nimport { CacheNode } from './CacheNode';\nimport { Change, changeChildAdded, changeValue } from './Change';\nimport { CancelEvent, Event } from './Event';\nimport {\n EventGenerator,\n eventGeneratorGenerateEventsForChanges\n} from './EventGenerator';\nimport { EventRegistration, QueryContext } from './EventRegistration';\nimport { IndexedFilter } from './filter/IndexedFilter';\nimport { queryParamsGetNodeFilter } from './QueryParams';\nimport {\n newViewCache,\n ViewCache,\n viewCacheGetCompleteEventSnap,\n viewCacheGetCompleteServerSnap\n} from './ViewCache';\nimport {\n newViewProcessor,\n ViewProcessor,\n viewProcessorApplyOperation,\n viewProcessorAssertIndexed\n} from './ViewProcessor';\n\n/**\n * A view represents a specific location and query that has 1 or more event registrations.\n *\n * It does several things:\n * - Maintains the list of event registrations for this location/query.\n * - Maintains a cache of the data visible for this location/query.\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\n * registrations returns the set of events to be raised.\n */\nexport class View {\n processor_: ViewProcessor;\n viewCache_: ViewCache;\n eventRegistrations_: EventRegistration[] = [];\n eventGenerator_: EventGenerator;\n\n constructor(private query_: QueryContext, initialViewCache: ViewCache) {\n const params = this.query_._queryParams;\n\n const indexFilter = new IndexedFilter(params.getIndex());\n const filter = queryParamsGetNodeFilter(params);\n\n this.processor_ = newViewProcessor(filter);\n\n const initialServerCache = initialViewCache.serverCache;\n const initialEventCache = initialViewCache.eventCache;\n\n // Don't filter server node with other filter than index, wait for tagged listen\n const serverSnap = indexFilter.updateFullNode(\n ChildrenNode.EMPTY_NODE,\n initialServerCache.getNode(),\n null\n );\n const eventSnap = filter.updateFullNode(\n ChildrenNode.EMPTY_NODE,\n initialEventCache.getNode(),\n null\n );\n const newServerCache = new CacheNode(\n serverSnap,\n initialServerCache.isFullyInitialized(),\n indexFilter.filtersNodes()\n );\n const newEventCache = new CacheNode(\n eventSnap,\n initialEventCache.isFullyInitialized(),\n filter.filtersNodes()\n );\n\n this.viewCache_ = newViewCache(newEventCache, newServerCache);\n this.eventGenerator_ = new EventGenerator(this.query_);\n }\n\n get query(): QueryContext {\n return this.query_;\n }\n}\n\nexport function viewGetServerCache(view: View): Node | null {\n return view.viewCache_.serverCache.getNode();\n}\n\nexport function viewGetCompleteNode(view: View): Node | null {\n return viewCacheGetCompleteEventSnap(view.viewCache_);\n}\n\nexport function viewGetCompleteServerCache(\n view: View,\n path: Path\n): Node | null {\n const cache = viewCacheGetCompleteServerSnap(view.viewCache_);\n if (cache) {\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\n // we need to see if it contains the child we're interested in.\n if (\n view.query._queryParams.loadsAllData() ||\n (!pathIsEmpty(path) &&\n !cache.getImmediateChild(pathGetFront(path)).isEmpty())\n ) {\n return cache.getChild(path);\n }\n }\n return null;\n}\n\nexport function viewIsEmpty(view: View): boolean {\n return view.eventRegistrations_.length === 0;\n}\n\nexport function viewAddEventRegistration(\n view: View,\n eventRegistration: EventRegistration\n) {\n view.eventRegistrations_.push(eventRegistration);\n}\n\n/**\n * @param eventRegistration - If null, remove all callbacks.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @returns Cancel events, if cancelError was provided.\n */\nexport function viewRemoveEventRegistration(\n view: View,\n eventRegistration: EventRegistration | null,\n cancelError?: Error\n): Event[] {\n const cancelEvents: CancelEvent[] = [];\n if (cancelError) {\n assert(\n eventRegistration == null,\n 'A cancel should cancel all event registrations.'\n );\n const path = view.query._path;\n view.eventRegistrations_.forEach(registration => {\n const maybeEvent = registration.createCancelEvent(cancelError, path);\n if (maybeEvent) {\n cancelEvents.push(maybeEvent);\n }\n });\n }\n\n if (eventRegistration) {\n let remaining = [];\n for (let i = 0; i < view.eventRegistrations_.length; ++i) {\n const existing = view.eventRegistrations_[i];\n if (!existing.matches(eventRegistration)) {\n remaining.push(existing);\n } else if (eventRegistration.hasAnyCallback()) {\n // We're removing just this one\n remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));\n break;\n }\n }\n view.eventRegistrations_ = remaining;\n } else {\n view.eventRegistrations_ = [];\n }\n return cancelEvents;\n}\n\n/**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n */\nexport function viewApplyOperation(\n view: View,\n operation: Operation,\n writesCache: WriteTreeRef,\n completeServerCache: Node | null\n): Event[] {\n if (\n operation.type === OperationType.MERGE &&\n operation.source.queryId !== null\n ) {\n assert(\n viewCacheGetCompleteServerSnap(view.viewCache_),\n 'We should always have a full cache before handling merges'\n );\n assert(\n viewCacheGetCompleteEventSnap(view.viewCache_),\n 'Missing event cache, even though we have a server cache'\n );\n }\n\n const oldViewCache = view.viewCache_;\n const result = viewProcessorApplyOperation(\n view.processor_,\n oldViewCache,\n operation,\n writesCache,\n completeServerCache\n );\n viewProcessorAssertIndexed(view.processor_, result.viewCache);\n\n assert(\n result.viewCache.serverCache.isFullyInitialized() ||\n !oldViewCache.serverCache.isFullyInitialized(),\n 'Once a server snap is complete, it should never go back'\n );\n\n view.viewCache_ = result.viewCache;\n\n return viewGenerateEventsForChanges_(\n view,\n result.changes,\n result.viewCache.eventCache.getNode(),\n null\n );\n}\n\nexport function viewGetInitialEvents(\n view: View,\n registration: EventRegistration\n): Event[] {\n const eventSnap = view.viewCache_.eventCache;\n const initialChanges: Change[] = [];\n if (!eventSnap.getNode().isLeafNode()) {\n const eventNode = eventSnap.getNode() as ChildrenNode;\n eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n initialChanges.push(changeChildAdded(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(changeValue(eventSnap.getNode()));\n }\n return viewGenerateEventsForChanges_(\n view,\n initialChanges,\n eventSnap.getNode(),\n registration\n );\n}\n\nfunction viewGenerateEventsForChanges_(\n view: View,\n changes: Change[],\n eventCache: Node,\n eventRegistration?: EventRegistration\n): Event[] {\n const registrations = eventRegistration\n ? [eventRegistration]\n : view.eventRegistrations_;\n return eventGeneratorGenerateEventsForChanges(\n view.eventGenerator_,\n changes,\n eventCache,\n registrations\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ReferenceConstructor } from '../api/Reference';\n\nimport { Operation } from './operation/Operation';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { Path } from './util/Path';\nimport { CacheNode } from './view/CacheNode';\nimport { Event } from './view/Event';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\nimport {\n View,\n viewAddEventRegistration,\n viewApplyOperation,\n viewGetCompleteServerCache,\n viewGetInitialEvents,\n viewIsEmpty,\n viewRemoveEventRegistration\n} from './view/View';\nimport { newViewCache } from './view/ViewCache';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteEventCache,\n writeTreeRefCalcCompleteEventChildren\n} from './WriteTree';\n\nlet referenceConstructor: ReferenceConstructor;\n\n/**\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\n * and user writes (set, transaction, update).\n *\n * It's responsible for:\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\n * applyUserOverwrite, etc.)\n */\nexport class SyncPoint {\n /**\n * The Views being tracked at this location in the tree, stored as a map where the key is a\n * queryId and the value is the View for that query.\n *\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\n */\n readonly views: Map = new Map();\n}\n\nexport function syncPointSetReferenceConstructor(\n val: ReferenceConstructor\n): void {\n assert(\n !referenceConstructor,\n '__referenceConstructor has already been defined'\n );\n referenceConstructor = val;\n}\n\nfunction syncPointGetReferenceConstructor(): ReferenceConstructor {\n assert(referenceConstructor, 'Reference.ts has not been loaded');\n return referenceConstructor;\n}\n\nexport function syncPointIsEmpty(syncPoint: SyncPoint): boolean {\n return syncPoint.views.size === 0;\n}\n\nexport function syncPointApplyOperation(\n syncPoint: SyncPoint,\n operation: Operation,\n writesCache: WriteTreeRef,\n optCompleteServerCache: Node | null\n): Event[] {\n const queryId = operation.source.queryId;\n if (queryId !== null) {\n const view = syncPoint.views.get(queryId);\n assert(view != null, 'SyncTree gave us an op for an invalid query.');\n return viewApplyOperation(\n view,\n operation,\n writesCache,\n optCompleteServerCache\n );\n } else {\n let events: Event[] = [];\n\n for (const view of syncPoint.views.values()) {\n events = events.concat(\n viewApplyOperation(view, operation, writesCache, optCompleteServerCache)\n );\n }\n\n return events;\n }\n}\n\n/**\n * Get a view for the specified query.\n *\n * @param query - The query to return a view for\n * @param writesCache\n * @param serverCache\n * @param serverCacheComplete\n * @returns Events to raise.\n */\nexport function syncPointGetView(\n syncPoint: SyncPoint,\n query: QueryContext,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n serverCacheComplete: boolean\n): View {\n const queryId = query._queryIdentifier;\n const view = syncPoint.views.get(queryId);\n if (!view) {\n // TODO: make writesCache take flag for complete server node\n let eventCache = writeTreeRefCalcCompleteEventCache(\n writesCache,\n serverCacheComplete ? serverCache : null\n );\n let eventCacheComplete = false;\n if (eventCache) {\n eventCacheComplete = true;\n } else if (serverCache instanceof ChildrenNode) {\n eventCache = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n serverCache\n );\n eventCacheComplete = false;\n } else {\n eventCache = ChildrenNode.EMPTY_NODE;\n eventCacheComplete = false;\n }\n const viewCache = newViewCache(\n new CacheNode(eventCache, eventCacheComplete, false),\n new CacheNode(serverCache, serverCacheComplete, false)\n );\n return new View(query, viewCache);\n }\n return view;\n}\n\n/**\n * Add an event callback for the specified query.\n *\n * @param query\n * @param eventRegistration\n * @param writesCache\n * @param serverCache - Complete server cache, if we have it.\n * @param serverCacheComplete\n * @returns Events to raise.\n */\nexport function syncPointAddEventRegistration(\n syncPoint: SyncPoint,\n query: QueryContext,\n eventRegistration: EventRegistration,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n serverCacheComplete: boolean\n): Event[] {\n const view = syncPointGetView(\n syncPoint,\n query,\n writesCache,\n serverCache,\n serverCacheComplete\n );\n if (!syncPoint.views.has(query._queryIdentifier)) {\n syncPoint.views.set(query._queryIdentifier, view);\n }\n // This is guaranteed to exist now, we just created anything that was missing\n viewAddEventRegistration(view, eventRegistration);\n return viewGetInitialEvents(view, eventRegistration);\n}\n\n/**\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\n *\n * If query is the default query, we'll check all views for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\n *\n * @param eventRegistration - If null, remove all callbacks.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @returns removed queries and any cancel events\n */\nexport function syncPointRemoveEventRegistration(\n syncPoint: SyncPoint,\n query: QueryContext,\n eventRegistration: EventRegistration | null,\n cancelError?: Error\n): { removed: QueryContext[]; events: Event[] } {\n const queryId = query._queryIdentifier;\n const removed: QueryContext[] = [];\n let cancelEvents: Event[] = [];\n const hadCompleteView = syncPointHasCompleteView(syncPoint);\n if (queryId === 'default') {\n // When you do ref.off(...), we search all views for the registration to remove.\n for (const [viewQueryId, view] of syncPoint.views.entries()) {\n cancelEvents = cancelEvents.concat(\n viewRemoveEventRegistration(view, eventRegistration, cancelError)\n );\n if (viewIsEmpty(view)) {\n syncPoint.views.delete(viewQueryId);\n\n // We'll deal with complete views later.\n if (!view.query._queryParams.loadsAllData()) {\n removed.push(view.query);\n }\n }\n }\n } else {\n // remove the callback from the specific view.\n const view = syncPoint.views.get(queryId);\n if (view) {\n cancelEvents = cancelEvents.concat(\n viewRemoveEventRegistration(view, eventRegistration, cancelError)\n );\n if (viewIsEmpty(view)) {\n syncPoint.views.delete(queryId);\n\n // We'll deal with complete views later.\n if (!view.query._queryParams.loadsAllData()) {\n removed.push(view.query);\n }\n }\n }\n }\n\n if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {\n // We removed our last complete view.\n removed.push(\n new (syncPointGetReferenceConstructor())(query._repo, query._path)\n );\n }\n\n return { removed, events: cancelEvents };\n}\n\nexport function syncPointGetQueryViews(syncPoint: SyncPoint): View[] {\n const result = [];\n for (const view of syncPoint.views.values()) {\n if (!view.query._queryParams.loadsAllData()) {\n result.push(view);\n }\n }\n return result;\n}\n\n/**\n * @param path - The path to the desired complete snapshot\n * @returns A complete cache, if it exists\n */\nexport function syncPointGetCompleteServerCache(\n syncPoint: SyncPoint,\n path: Path\n): Node | null {\n let serverCache: Node | null = null;\n for (const view of syncPoint.views.values()) {\n serverCache = serverCache || viewGetCompleteServerCache(view, path);\n }\n return serverCache;\n}\n\nexport function syncPointViewForQuery(\n syncPoint: SyncPoint,\n query: QueryContext\n): View | null {\n const params = query._queryParams;\n if (params.loadsAllData()) {\n return syncPointGetCompleteView(syncPoint);\n } else {\n const queryId = query._queryIdentifier;\n return syncPoint.views.get(queryId);\n }\n}\n\nexport function syncPointViewExistsForQuery(\n syncPoint: SyncPoint,\n query: QueryContext\n): boolean {\n return syncPointViewForQuery(syncPoint, query) != null;\n}\n\nexport function syncPointHasCompleteView(syncPoint: SyncPoint): boolean {\n return syncPointGetCompleteView(syncPoint) != null;\n}\n\nexport function syncPointGetCompleteView(syncPoint: SyncPoint): View | null {\n for (const view of syncPoint.views.values()) {\n if (view.query._queryParams.loadsAllData()) {\n return view;\n }\n }\n return null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ReferenceConstructor } from '../api/Reference';\n\nimport { AckUserWrite } from './operation/AckUserWrite';\nimport { ListenComplete } from './operation/ListenComplete';\nimport { Merge } from './operation/Merge';\nimport {\n newOperationSourceServer,\n newOperationSourceServerTaggedQuery,\n newOperationSourceUser,\n Operation\n} from './operation/Operation';\nimport { Overwrite } from './operation/Overwrite';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport {\n SyncPoint,\n syncPointAddEventRegistration,\n syncPointApplyOperation,\n syncPointGetCompleteServerCache,\n syncPointGetCompleteView,\n syncPointGetQueryViews,\n syncPointGetView,\n syncPointHasCompleteView,\n syncPointIsEmpty,\n syncPointRemoveEventRegistration,\n syncPointViewExistsForQuery,\n syncPointViewForQuery\n} from './SyncPoint';\nimport { ImmutableTree } from './util/ImmutableTree';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathGetFront,\n pathIsEmpty\n} from './util/Path';\nimport { each, errorForServerCode } from './util/util';\nimport { CacheNode } from './view/CacheNode';\nimport { Event } from './view/Event';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\nimport { View, viewGetCompleteNode, viewGetServerCache } from './view/View';\nimport {\n newWriteTree,\n WriteTree,\n writeTreeAddMerge,\n writeTreeAddOverwrite,\n writeTreeCalcCompleteEventCache,\n writeTreeChildWrites,\n writeTreeGetWrite,\n WriteTreeRef,\n writeTreeRefChild,\n writeTreeRemoveWrite\n} from './WriteTree';\n\nlet referenceConstructor: ReferenceConstructor;\n\nexport function syncTreeSetReferenceConstructor(\n val: ReferenceConstructor\n): void {\n assert(\n !referenceConstructor,\n '__referenceConstructor has already been defined'\n );\n referenceConstructor = val;\n}\n\nfunction syncTreeGetReferenceConstructor(): ReferenceConstructor {\n assert(referenceConstructor, 'Reference.ts has not been loaded');\n return referenceConstructor;\n}\n\nexport interface ListenProvider {\n startListening(\n query: QueryContext,\n tag: number | null,\n hashFn: () => string,\n onComplete: (a: string, b?: unknown) => Event[]\n ): Event[];\n\n stopListening(a: QueryContext, b: number | null): void;\n}\n\n/**\n * Static tracker for next query tag.\n */\nlet syncTreeNextQueryTag_ = 1;\n\nexport function resetSyncTreeTag() {\n syncTreeNextQueryTag_ = 1;\n}\n\n/**\n * SyncTree is the central class for managing event callback registration, data caching, views\n * (query processing), and event generation. There are typically two SyncTree instances for\n * each Repo, one for the normal Firebase data, and one for the .info data.\n *\n * It has a number of responsibilities, including:\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\n * - Applying and caching data changes for user set(), transaction(), and update() calls\n * (applyUserOverwrite(), applyUserMerge()).\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\n * applyServerMerge()).\n * - Generating user-facing events for server and user changes (all of the apply* methods\n * return the set of events that need to be raised as a result).\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\n * to the correct set of paths and queries to satisfy the current set of user event\n * callbacks (listens are started/stopped using the provided listenProvider).\n *\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\n * events are returned to the caller rather than raised synchronously.\n *\n */\nexport class SyncTree {\n /**\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\n */\n syncPointTree_: ImmutableTree = new ImmutableTree(null);\n\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n */\n pendingWriteTree_: WriteTree = newWriteTree();\n\n readonly tagToQueryMap: Map = new Map();\n readonly queryToTagMap: Map = new Map();\n\n /**\n * @param listenProvider_ - Used by SyncTree to start / stop listening\n * to server data.\n */\n constructor(public listenProvider_: ListenProvider) {}\n}\n\n/**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyUserOverwrite(\n syncTree: SyncTree,\n path: Path,\n newData: Node,\n writeId: number,\n visible?: boolean\n): Event[] {\n // Record pending write.\n writeTreeAddOverwrite(\n syncTree.pendingWriteTree_,\n path,\n newData,\n writeId,\n visible\n );\n\n if (!visible) {\n return [];\n } else {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Overwrite(newOperationSourceUser(), path, newData)\n );\n }\n}\n\n/**\n * Apply the data from a user-generated update() call\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyUserMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n writeId: number\n): Event[] {\n // Record pending merge.\n writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);\n\n const changeTree = ImmutableTree.fromObject(changedChildren);\n\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Merge(newOperationSourceUser(), path, changeTree)\n );\n}\n\n/**\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\n *\n * @param revert - True if the given write failed and needs to be reverted\n * @returns Events to raise.\n */\nexport function syncTreeAckUserWrite(\n syncTree: SyncTree,\n writeId: number,\n revert: boolean = false\n) {\n const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);\n const needToReevaluate = writeTreeRemoveWrite(\n syncTree.pendingWriteTree_,\n writeId\n );\n if (!needToReevaluate) {\n return [];\n } else {\n let affectedTree = new ImmutableTree(null);\n if (write.snap != null) {\n // overwrite\n affectedTree = affectedTree.set(newEmptyPath(), true);\n } else {\n each(write.children, (pathString: string) => {\n affectedTree = affectedTree.set(new Path(pathString), true);\n });\n }\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new AckUserWrite(write.path, affectedTree, revert)\n );\n }\n}\n\n/**\n * Apply new server data for the specified path..\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyServerOverwrite(\n syncTree: SyncTree,\n path: Path,\n newData: Node\n): Event[] {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Overwrite(newOperationSourceServer(), path, newData)\n );\n}\n\n/**\n * Apply new server data to be merged in at the specified path.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyServerMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node }\n): Event[] {\n const changeTree = ImmutableTree.fromObject(changedChildren);\n\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Merge(newOperationSourceServer(), path, changeTree)\n );\n}\n\n/**\n * Apply a listen complete for a query\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyListenComplete(\n syncTree: SyncTree,\n path: Path\n): Event[] {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new ListenComplete(newOperationSourceServer(), path)\n );\n}\n\n/**\n * Apply a listen complete for a tagged query\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedListenComplete(\n syncTree: SyncTree,\n path: Path,\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const op = new ListenComplete(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath\n );\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n } else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n}\n\n/**\n * Remove event callback(s).\n *\n * If query is the default query, we'll check all queries for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\n *\n * @param eventRegistration - If null, all callbacks are removed.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no\n * deduping needs to take place. This flag allows toggling of that behavior\n * @returns Cancel events, if cancelError was provided.\n */\nexport function syncTreeRemoveEventRegistration(\n syncTree: SyncTree,\n query: QueryContext,\n eventRegistration: EventRegistration | null,\n cancelError?: Error,\n skipListenerDedup = false\n): Event[] {\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\n const path = query._path;\n const maybeSyncPoint = syncTree.syncPointTree_.get(path);\n let cancelEvents: Event[] = [];\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\n // not loadsAllData().\n if (\n maybeSyncPoint &&\n (query._queryIdentifier === 'default' ||\n syncPointViewExistsForQuery(maybeSyncPoint, query))\n ) {\n const removedAndEvents = syncPointRemoveEventRegistration(\n maybeSyncPoint,\n query,\n eventRegistration,\n cancelError\n );\n if (syncPointIsEmpty(maybeSyncPoint)) {\n syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);\n }\n\n const removed = removedAndEvents.removed;\n cancelEvents = removedAndEvents.events;\n\n if (!skipListenerDedup) {\n /**\n * We may have just removed one of many listeners and can short-circuit this whole process\n * We may also not have removed a default listener, in which case all of the descendant listeners should already be\n * properly set up.\n */\n\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\n // queryId === 'default'\n const removingDefault =\n -1 !==\n removed.findIndex(query => {\n return query._queryParams.loadsAllData();\n });\n const covered = syncTree.syncPointTree_.findOnPath(\n path,\n (relativePath, parentSyncPoint) =>\n syncPointHasCompleteView(parentSyncPoint)\n );\n\n if (removingDefault && !covered) {\n const subtree = syncTree.syncPointTree_.subtree(path);\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\n // removal\n if (!subtree.isEmpty()) {\n // We need to fold over our subtree and collect the listeners to send\n const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);\n\n // Ok, we've collected all the listens we need. Set them up.\n for (let i = 0; i < newViews.length; ++i) {\n const view = newViews[i],\n newQuery = view.query;\n const listener = syncTreeCreateListenerForView_(syncTree, view);\n syncTree.listenProvider_.startListening(\n syncTreeQueryForListening_(newQuery),\n syncTreeTagForQuery(syncTree, newQuery),\n listener.hashFn,\n listener.onComplete\n );\n }\n }\n // Otherwise there's nothing below us, so nothing we need to start listening on\n }\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\n if (!covered && removed.length > 0 && !cancelError) {\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\n // default. Otherwise, we need to iterate through and cancel each individual query\n if (removingDefault) {\n // We don't tag default listeners\n const defaultTag: number | null = null;\n syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(query),\n defaultTag\n );\n } else {\n removed.forEach((queryToRemove: QueryContext) => {\n const tagToRemove = syncTree.queryToTagMap.get(\n syncTreeMakeQueryKey_(queryToRemove)\n );\n syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(queryToRemove),\n tagToRemove\n );\n });\n }\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n syncTreeRemoveTags_(syncTree, removed);\n } else {\n // No-op, this listener must've been already removed\n }\n return cancelEvents;\n}\n\n/**\n * Apply new server data for the specified tagged query.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedQueryOverwrite(\n syncTree: SyncTree,\n path: Path,\n snap: Node,\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey != null) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const op = new Overwrite(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath,\n snap\n );\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n } else {\n // Query must have been removed already\n return [];\n }\n}\n\n/**\n * Apply server data to be merged in for the specified tagged query.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedQueryMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const changeTree = ImmutableTree.fromObject(changedChildren);\n const op = new Merge(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath,\n changeTree\n );\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n } else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n}\n\n/**\n * Add an event callback for the specified query.\n *\n * @returns Events to raise.\n */\nexport function syncTreeAddEventRegistration(\n syncTree: SyncTree,\n query: QueryContext,\n eventRegistration: EventRegistration,\n skipSetupListener = false\n): Event[] {\n const path = query._path;\n\n let serverCache: Node | null = null;\n let foundAncestorDefaultView = false;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\n const relativePath = newRelativePath(pathToSyncPoint, path);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPointHasCompleteView(sp);\n });\n let syncPoint = syncTree.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint();\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\n } else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n\n let serverCacheComplete;\n if (serverCache != null) {\n serverCacheComplete = true;\n } else {\n serverCacheComplete = false;\n serverCache = ChildrenNode.EMPTY_NODE;\n const subtree = syncTree.syncPointTree_.subtree(path);\n subtree.foreachChild((childName, childSyncPoint) => {\n const completeCache = syncPointGetCompleteServerCache(\n childSyncPoint,\n newEmptyPath()\n );\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(\n childName,\n completeCache\n );\n }\n });\n }\n\n const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);\n if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {\n // We need to track a tag for this query\n const queryKey = syncTreeMakeQueryKey_(query);\n assert(\n !syncTree.queryToTagMap.has(queryKey),\n 'View does not exist, but we have a tag'\n );\n const tag = syncTreeGetNextQueryTag_();\n syncTree.queryToTagMap.set(queryKey, tag);\n syncTree.tagToQueryMap.set(tag, queryKey);\n }\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);\n let events = syncPointAddEventRegistration(\n syncPoint,\n query,\n eventRegistration,\n writesCache,\n serverCache,\n serverCacheComplete\n );\n if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {\n const view = syncPointViewForQuery(syncPoint, query);\n events = events.concat(syncTreeSetupListener_(syncTree, query, view));\n }\n return events;\n}\n\n/**\n * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a\n * listener above it, we will get a false \"null\". This shouldn't be a problem because transactions will always\n * have a listener above, and atomic operations would correctly show a jitter of ->\n * as the write is applied locally and then acknowledged at the server.\n *\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\n *\n * @param path - The path to the data we want\n * @param writeIdsToExclude - A specific set to be excluded\n */\nexport function syncTreeCalcCompleteEventCache(\n syncTree: SyncTree,\n path: Path,\n writeIdsToExclude?: number[]\n): Node {\n const includeHiddenSets = true;\n const writeTree = syncTree.pendingWriteTree_;\n const serverCache = syncTree.syncPointTree_.findOnPath(\n path,\n (pathSoFar, syncPoint) => {\n const relativePath = newRelativePath(pathSoFar, path);\n const serverCache = syncPointGetCompleteServerCache(\n syncPoint,\n relativePath\n );\n if (serverCache) {\n return serverCache;\n }\n }\n );\n return writeTreeCalcCompleteEventCache(\n writeTree,\n path,\n serverCache,\n writeIdsToExclude,\n includeHiddenSets\n );\n}\n\nexport function syncTreeGetServerValue(\n syncTree: SyncTree,\n query: QueryContext\n): Node | null {\n const path = query._path;\n let serverCache: Node | null = null;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\n const relativePath = newRelativePath(pathToSyncPoint, path);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\n });\n let syncPoint = syncTree.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint();\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\n } else {\n serverCache =\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n const serverCacheComplete = serverCache != null;\n const serverCacheNode: CacheNode | null = serverCacheComplete\n ? new CacheNode(serverCache, true, false)\n : null;\n const writesCache: WriteTreeRef | null = writeTreeChildWrites(\n syncTree.pendingWriteTree_,\n query._path\n );\n const view: View = syncPointGetView(\n syncPoint,\n query,\n writesCache,\n serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE,\n serverCacheComplete\n );\n return viewGetCompleteNode(view);\n}\n\n/**\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\n *\n * NOTES:\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\n *\n * - We call applyOperation() on each SyncPoint passing three things:\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\n * 3. A snapshot Node with cached server data, if we have it.\n *\n * - We concatenate all of the events returned by each SyncPoint and return the result.\n */\nfunction syncTreeApplyOperationToSyncPoints_(\n syncTree: SyncTree,\n operation: Operation\n): Event[] {\n return syncTreeApplyOperationHelper_(\n operation,\n syncTree.syncPointTree_,\n /*serverCache=*/ null,\n writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath())\n );\n}\n\n/**\n * Recursive helper for applyOperationToSyncPoints_\n */\nfunction syncTreeApplyOperationHelper_(\n operation: Operation,\n syncPointTree: ImmutableTree,\n serverCache: Node | null,\n writesCache: WriteTreeRef\n): Event[] {\n if (pathIsEmpty(operation.path)) {\n return syncTreeApplyOperationDescendantsHelper_(\n operation,\n syncPointTree,\n serverCache,\n writesCache\n );\n } else {\n const syncPoint = syncPointTree.get(newEmptyPath());\n\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n\n let events: Event[] = [];\n const childName = pathGetFront(operation.path);\n const childOperation = operation.operationForChild(childName);\n const childTree = syncPointTree.children.get(childName);\n if (childTree && childOperation) {\n const childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n const childWritesCache = writeTreeRefChild(writesCache, childName);\n events = events.concat(\n syncTreeApplyOperationHelper_(\n childOperation,\n childTree,\n childServerCache,\n childWritesCache\n )\n );\n }\n\n if (syncPoint) {\n events = events.concat(\n syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)\n );\n }\n\n return events;\n }\n}\n\n/**\n * Recursive helper for applyOperationToSyncPoints_\n */\nfunction syncTreeApplyOperationDescendantsHelper_(\n operation: Operation,\n syncPointTree: ImmutableTree,\n serverCache: Node | null,\n writesCache: WriteTreeRef\n): Event[] {\n const syncPoint = syncPointTree.get(newEmptyPath());\n\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n\n let events: Event[] = [];\n syncPointTree.children.inorderTraversal((childName, childTree) => {\n const childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n const childWritesCache = writeTreeRefChild(writesCache, childName);\n const childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(\n syncTreeApplyOperationDescendantsHelper_(\n childOperation,\n childTree,\n childServerCache,\n childWritesCache\n )\n );\n }\n });\n\n if (syncPoint) {\n events = events.concat(\n syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)\n );\n }\n\n return events;\n}\n\nfunction syncTreeCreateListenerForView_(\n syncTree: SyncTree,\n view: View\n): { hashFn(): string; onComplete(a: string, b?: unknown): Event[] } {\n const query = view.query;\n const tag = syncTreeTagForQuery(syncTree, query);\n\n return {\n hashFn: () => {\n const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: (status: string): Event[] => {\n if (status === 'ok') {\n if (tag) {\n return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);\n } else {\n return syncTreeApplyListenComplete(syncTree, query._path);\n }\n } else {\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\n const error = errorForServerCode(status, query);\n return syncTreeRemoveEventRegistration(\n syncTree,\n query,\n /*eventRegistration*/ null,\n error\n );\n }\n }\n };\n}\n\n/**\n * Return the tag associated with the given query.\n */\nexport function syncTreeTagForQuery(\n syncTree: SyncTree,\n query: QueryContext\n): number | null {\n const queryKey = syncTreeMakeQueryKey_(query);\n return syncTree.queryToTagMap.get(queryKey);\n}\n\n/**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n */\nfunction syncTreeMakeQueryKey_(query: QueryContext): string {\n return query._path.toString() + '$' + query._queryIdentifier;\n}\n\n/**\n * Return the query associated with the given tag, if we have one\n */\nfunction syncTreeQueryKeyForTag_(\n syncTree: SyncTree,\n tag: number\n): string | null {\n return syncTree.tagToQueryMap.get(tag);\n}\n\n/**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n */\nfunction syncTreeParseQueryKey_(queryKey: string): {\n queryId: string;\n path: Path;\n} {\n const splitIndex = queryKey.indexOf('$');\n assert(\n splitIndex !== -1 && splitIndex < queryKey.length - 1,\n 'Bad queryKey.'\n );\n return {\n queryId: queryKey.substr(splitIndex + 1),\n path: new Path(queryKey.substr(0, splitIndex))\n };\n}\n\n/**\n * A helper method to apply tagged operations\n */\nfunction syncTreeApplyTaggedOperation_(\n syncTree: SyncTree,\n queryPath: Path,\n operation: Operation\n): Event[] {\n const syncPoint = syncTree.syncPointTree_.get(queryPath);\n assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n const writesCache = writeTreeChildWrites(\n syncTree.pendingWriteTree_,\n queryPath\n );\n return syncPointApplyOperation(syncPoint, operation, writesCache, null);\n}\n\n/**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n */\nfunction syncTreeCollectDistinctViewsForSubTree_(\n subtree: ImmutableTree\n): View[] {\n return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {\n if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {\n const completeView = syncPointGetCompleteView(maybeChildSyncPoint);\n return [completeView];\n } else {\n // No complete view here, flatten any deeper listens into an array\n let views: View[] = [];\n if (maybeChildSyncPoint) {\n views = syncPointGetQueryViews(maybeChildSyncPoint);\n }\n each(childMap, (_key: string, childViews: View[]) => {\n views = views.concat(childViews);\n });\n return views;\n }\n });\n}\n\n/**\n * Normalizes a query to a query we send the server for listening\n *\n * @returns The normalized query\n */\nfunction syncTreeQueryForListening_(query: QueryContext): QueryContext {\n if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {\n // We treat queries that load all data as default queries\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n // from Query\n return new (syncTreeGetReferenceConstructor())(query._repo, query._path);\n } else {\n return query;\n }\n}\n\nfunction syncTreeRemoveTags_(syncTree: SyncTree, queries: QueryContext[]) {\n for (let j = 0; j < queries.length; ++j) {\n const removedQuery = queries[j];\n if (!removedQuery._queryParams.loadsAllData()) {\n // We should have a tag for this\n const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);\n const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);\n syncTree.queryToTagMap.delete(removedQueryKey);\n syncTree.tagToQueryMap.delete(removedQueryTag);\n }\n }\n}\n\n/**\n * Static accessor for query tags.\n */\nfunction syncTreeGetNextQueryTag_(): number {\n return syncTreeNextQueryTag_++;\n}\n\n/**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @returns This method can return events to support synchronous data sources\n */\nfunction syncTreeSetupListener_(\n syncTree: SyncTree,\n query: QueryContext,\n view: View\n): Event[] {\n const path = query._path;\n const tag = syncTreeTagForQuery(syncTree, query);\n const listener = syncTreeCreateListenerForView_(syncTree, view);\n\n const events = syncTree.listenProvider_.startListening(\n syncTreeQueryForListening_(query),\n tag,\n listener.hashFn,\n listener.onComplete\n );\n\n const subtree = syncTree.syncPointTree_.subtree(path);\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\n // may need to shadow other listens as well.\n if (tag) {\n assert(\n !syncPointHasCompleteView(subtree.value),\n \"If we're adding a query, it shouldn't be shadowed\"\n );\n } else {\n // Shadow everything at or below this location, this is a default listener.\n const queriesToStop = subtree.fold(\n (relativePath, maybeChildSyncPoint, childMap) => {\n if (\n !pathIsEmpty(relativePath) &&\n maybeChildSyncPoint &&\n syncPointHasCompleteView(maybeChildSyncPoint)\n ) {\n return [syncPointGetCompleteView(maybeChildSyncPoint).query];\n } else {\n // No default listener here, flatten any deeper queries into an array\n let queries: QueryContext[] = [];\n if (maybeChildSyncPoint) {\n queries = queries.concat(\n syncPointGetQueryViews(maybeChildSyncPoint).map(\n view => view.query\n )\n );\n }\n each(childMap, (_key: string, childQueries: QueryContext[]) => {\n queries = queries.concat(childQueries);\n });\n return queries;\n }\n }\n );\n for (let i = 0; i < queriesToStop.length; ++i) {\n const queryToStop = queriesToStop[i];\n syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(queryToStop),\n syncTreeTagForQuery(syncTree, queryToStop)\n );\n }\n }\n return events;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { PRIORITY_INDEX } from '../snap/indexes/PriorityIndex';\nimport { LeafNode } from '../snap/LeafNode';\nimport { Node } from '../snap/Node';\nimport { nodeFromJSON } from '../snap/nodeFromJSON';\nimport { SyncTree, syncTreeCalcCompleteEventCache } from '../SyncTree';\n\nimport { Indexable } from './misc';\nimport { Path, pathChild } from './Path';\n\n/* It's critical for performance that we do not calculate actual values from a SyncTree\n * unless and until the value is needed. Because we expose both a SyncTree and Node\n * version of deferred value resolution, we ned a wrapper class that will let us share\n * code.\n *\n * @see https://github.com/firebase/firebase-js-sdk/issues/2487\n */\ninterface ValueProvider {\n getImmediateChild(childName: string): ValueProvider;\n node(): Node;\n}\n\nclass ExistingValueProvider implements ValueProvider {\n constructor(readonly node_: Node) {}\n\n getImmediateChild(childName: string): ValueProvider {\n const child = this.node_.getImmediateChild(childName);\n return new ExistingValueProvider(child);\n }\n\n node(): Node {\n return this.node_;\n }\n}\n\nclass DeferredValueProvider implements ValueProvider {\n private syncTree_: SyncTree;\n private path_: Path;\n\n constructor(syncTree: SyncTree, path: Path) {\n this.syncTree_ = syncTree;\n this.path_ = path;\n }\n\n getImmediateChild(childName: string): ValueProvider {\n const childPath = pathChild(this.path_, childName);\n return new DeferredValueProvider(this.syncTree_, childPath);\n }\n\n node(): Node {\n return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);\n }\n}\n\n/**\n * Generate placeholders for deferred values.\n */\nexport const generateWithValues = function (\n values: {\n [k: string]: unknown;\n } | null\n): { [k: string]: unknown } {\n values = values || {};\n values['timestamp'] = values['timestamp'] || new Date().getTime();\n return values;\n};\n\n/**\n * Value to use when firing local events. When writing server values, fire\n * local events with an approximate value, otherwise return value as-is.\n */\nexport const resolveDeferredLeafValue = function (\n value: { [k: string]: unknown } | string | number | boolean,\n existingVal: ValueProvider,\n serverValues: { [k: string]: unknown }\n): string | number | boolean {\n if (!value || typeof value !== 'object') {\n return value as string | number | boolean;\n }\n assert('.sv' in value, 'Unexpected leaf node or priority contents');\n\n if (typeof value['.sv'] === 'string') {\n return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);\n } else if (typeof value['.sv'] === 'object') {\n return resolveComplexDeferredValue(value['.sv'], existingVal, serverValues);\n } else {\n assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));\n }\n};\n\nconst resolveScalarDeferredValue = function (\n op: string,\n existing: ValueProvider,\n serverValues: { [k: string]: unknown }\n): string | number | boolean {\n switch (op) {\n case 'timestamp':\n return serverValues['timestamp'] as string | number | boolean;\n default:\n assert(false, 'Unexpected server value: ' + op);\n }\n};\n\nconst resolveComplexDeferredValue = function (\n op: object,\n existing: ValueProvider,\n unused: { [k: string]: unknown }\n): string | number | boolean {\n if (!op.hasOwnProperty('increment')) {\n assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));\n }\n const delta = op['increment'];\n if (typeof delta !== 'number') {\n assert(false, 'Unexpected increment value: ' + delta);\n }\n\n const existingNode = existing.node();\n assert(\n existingNode !== null && typeof existingNode !== 'undefined',\n 'Expected ChildrenNode.EMPTY_NODE for nulls'\n );\n\n // Incrementing a non-number sets the value to the incremented amount\n if (!existingNode.isLeafNode()) {\n return delta;\n }\n\n const leaf = existingNode as LeafNode;\n const existingVal = leaf.getValue();\n if (typeof existingVal !== 'number') {\n return delta;\n }\n\n // No need to do over/underflow arithmetic here because JS only handles floats under the covers\n return existingVal + delta;\n};\n\n/**\n * Recursively replace all deferred values and priorities in the tree with the\n * specified generated replacement values.\n * @param path - path to which write is relative\n * @param node - new data written at path\n * @param syncTree - current data\n */\nexport const resolveDeferredValueTree = function (\n path: Path,\n node: Node,\n syncTree: SyncTree,\n serverValues: Indexable\n): Node {\n return resolveDeferredValue(\n node,\n new DeferredValueProvider(syncTree, path),\n serverValues\n );\n};\n\n/**\n * Recursively replace all deferred values and priorities in the node with the\n * specified generated replacement values. If there are no server values in the node,\n * it'll be returned as-is.\n */\nexport const resolveDeferredValueSnapshot = function (\n node: Node,\n existing: Node,\n serverValues: Indexable\n): Node {\n return resolveDeferredValue(\n node,\n new ExistingValueProvider(existing),\n serverValues\n );\n};\n\nfunction resolveDeferredValue(\n node: Node,\n existingVal: ValueProvider,\n serverValues: Indexable\n): Node {\n const rawPri = node.getPriority().val() as\n | Indexable\n | boolean\n | null\n | number\n | string;\n const priority = resolveDeferredLeafValue(\n rawPri,\n existingVal.getImmediateChild('.priority'),\n serverValues\n );\n let newNode: Node;\n\n if (node.isLeafNode()) {\n const leafNode = node as LeafNode;\n const value = resolveDeferredLeafValue(\n leafNode.getValue(),\n existingVal,\n serverValues\n );\n if (\n value !== leafNode.getValue() ||\n priority !== leafNode.getPriority().val()\n ) {\n return new LeafNode(value, nodeFromJSON(priority));\n } else {\n return node;\n }\n } else {\n const childrenNode = node as ChildrenNode;\n newNode = childrenNode;\n if (priority !== childrenNode.getPriority().val()) {\n newNode = newNode.updatePriority(new LeafNode(priority));\n }\n childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\n const newChildNode = resolveDeferredValue(\n childNode,\n existingVal.getImmediateChild(childName),\n serverValues\n );\n if (newChildNode !== childNode) {\n newNode = newNode.updateImmediateChild(childName, newChildNode);\n }\n });\n return newNode;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains, safeGet } from '@firebase/util';\n\nimport { Path, pathGetFront, pathPopFront } from './Path';\nimport { each } from './util';\n\n/**\n * Node in a Tree.\n */\nexport interface TreeNode {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n children: Record>;\n childCount: number;\n value?: T;\n}\n\n/**\n * A light-weight tree, traversable by path. Nodes can have both values and children.\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\n * children.\n */\nexport class Tree {\n /**\n * @param name - Optional name of the node.\n * @param parent - Optional parent node.\n * @param node - Optional node to wrap.\n */\n constructor(\n readonly name: string = '',\n readonly parent: Tree | null = null,\n public node: TreeNode = { children: {}, childCount: 0 }\n ) {}\n}\n\n/**\n * Returns a sub-Tree for the given path.\n *\n * @param pathObj - Path to look up.\n * @returns Tree for path.\n */\nexport function treeSubTree(tree: Tree, pathObj: string | Path): Tree {\n // TODO: Require pathObj to be Path?\n let path = pathObj instanceof Path ? pathObj : new Path(pathObj);\n let child = tree,\n next = pathGetFront(path);\n while (next !== null) {\n const childNode = safeGet(child.node.children, next) || {\n children: {},\n childCount: 0\n };\n child = new Tree(next, child, childNode);\n path = pathPopFront(path);\n next = pathGetFront(path);\n }\n\n return child;\n}\n\n/**\n * Returns the data associated with this tree node.\n *\n * @returns The data or null if no data exists.\n */\nexport function treeGetValue(tree: Tree): T | undefined {\n return tree.node.value;\n}\n\n/**\n * Sets data to this tree node.\n *\n * @param value - Value to set.\n */\nexport function treeSetValue(tree: Tree, value: T | undefined): void {\n tree.node.value = value;\n treeUpdateParents(tree);\n}\n\n/**\n * @returns Whether the tree has any children.\n */\nexport function treeHasChildren(tree: Tree): boolean {\n return tree.node.childCount > 0;\n}\n\n/**\n * @returns Whether the tree is empty (no value or children).\n */\nexport function treeIsEmpty(tree: Tree): boolean {\n return treeGetValue(tree) === undefined && !treeHasChildren(tree);\n}\n\n/**\n * Calls action for each child of this tree node.\n *\n * @param action - Action to be called for each child.\n */\nexport function treeForEachChild(\n tree: Tree,\n action: (tree: Tree) => void\n): void {\n each(tree.node.children, (child: string, childTree: TreeNode) => {\n action(new Tree(child, tree, childTree));\n });\n}\n\n/**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param action - Action to be called for each child.\n * @param includeSelf - Whether to call action on this node as well. Defaults to\n * false.\n * @param childrenFirst - Whether to call action on children before calling it on\n * parent.\n */\nexport function treeForEachDescendant(\n tree: Tree,\n action: (tree: Tree) => void,\n includeSelf?: boolean,\n childrenFirst?: boolean\n): void {\n if (includeSelf && !childrenFirst) {\n action(tree);\n }\n\n treeForEachChild(tree, child => {\n treeForEachDescendant(child, action, true, childrenFirst);\n });\n\n if (includeSelf && childrenFirst) {\n action(tree);\n }\n}\n\n/**\n * Calls action on each ancestor node.\n *\n * @param action - Action to be called on each parent; return\n * true to abort.\n * @param includeSelf - Whether to call action on this node as well.\n * @returns true if the action callback returned true.\n */\nexport function treeForEachAncestor(\n tree: Tree,\n action: (tree: Tree) => unknown,\n includeSelf?: boolean\n): boolean {\n let node = includeSelf ? tree : tree.parent;\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n node = node.parent;\n }\n return false;\n}\n\n/**\n * Does a depth-first traversal of this node's descendants. When a descendant with a value\n * is found, action is called on it and traversal does not continue inside the node.\n * Action is *not* called on this node.\n *\n * @param action - Action to be called for each child.\n */\nexport function treeForEachImmediateDescendantWithValue(\n tree: Tree,\n action: (tree: Tree) => void\n): void {\n treeForEachChild(tree, child => {\n if (treeGetValue(child) !== undefined) {\n action(child);\n } else {\n treeForEachImmediateDescendantWithValue(child, action);\n }\n });\n}\n\n/**\n * @returns The path of this tree node, as a Path.\n */\nexport function treeGetPath(tree: Tree) {\n return new Path(\n tree.parent === null\n ? tree.name\n : treeGetPath(tree.parent) + '/' + tree.name\n );\n}\n\n/**\n * Adds or removes this child from its parent based on whether it's empty or not.\n */\nfunction treeUpdateParents(tree: Tree) {\n if (tree.parent !== null) {\n treeUpdateChild(tree.parent, tree.name, tree);\n }\n}\n\n/**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param childName - The name of the child to update.\n * @param child - The child to update.\n */\nfunction treeUpdateChild(tree: Tree, childName: string, child: Tree) {\n const childEmpty = treeIsEmpty(child);\n const childExists = contains(tree.node.children, childName);\n if (childEmpty && childExists) {\n delete tree.node.children[childName];\n tree.node.childCount--;\n treeUpdateParents(tree);\n } else if (!childEmpty && !childExists) {\n tree.node.children[childName] = child.node;\n tree.node.childCount++;\n treeUpdateParents(tree);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n contains,\n errorPrefix as errorPrefixFxn,\n safeGet,\n stringLength\n} from '@firebase/util';\n\nimport { RepoInfo } from '../RepoInfo';\n\nimport {\n Path,\n pathChild,\n pathCompare,\n pathContains,\n pathGetBack,\n pathGetFront,\n pathSlice,\n ValidationPath,\n validationPathPop,\n validationPathPush,\n validationPathToErrorString\n} from './Path';\nimport { each, isInvalidJSONNumber } from './util';\n\n/**\n * True for invalid Firebase keys\n */\nexport const INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\n\n/**\n * True for invalid Firebase paths.\n * Allows '/' in paths.\n */\nexport const INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\n\n/**\n * Maximum number of characters to allow in leaf value\n */\nexport const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\n\nexport const isValidKey = function (key: unknown): boolean {\n return (\n typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key)\n );\n};\n\nexport const isValidPathString = function (pathString: string): boolean {\n return (\n typeof pathString === 'string' &&\n pathString.length !== 0 &&\n !INVALID_PATH_REGEX_.test(pathString)\n );\n};\n\nexport const isValidRootPathString = function (pathString: string): boolean {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n\n return isValidPathString(pathString);\n};\n\nexport const isValidPriority = function (priority: unknown): boolean {\n return (\n priority === null ||\n typeof priority === 'string' ||\n (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||\n (priority &&\n typeof priority === 'object' &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n contains(priority as any, '.sv'))\n );\n};\n\n/**\n * Pre-validate a datum passed as an argument to Firebase function.\n */\nexport const validateFirebaseDataArg = function (\n fnName: string,\n value: unknown,\n path: Path,\n optional: boolean\n) {\n if (optional && value === undefined) {\n return;\n }\n\n validateFirebaseData(errorPrefixFxn(fnName, 'value'), value, path);\n};\n\n/**\n * Validate a data object client-side before sending to server.\n */\nexport const validateFirebaseData = function (\n errorPrefix: string,\n data: unknown,\n path_: Path | ValidationPath\n) {\n const path =\n path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;\n\n if (data === undefined) {\n throw new Error(\n errorPrefix + 'contains undefined ' + validationPathToErrorString(path)\n );\n }\n if (typeof data === 'function') {\n throw new Error(\n errorPrefix +\n 'contains a function ' +\n validationPathToErrorString(path) +\n ' with contents = ' +\n data.toString()\n );\n }\n if (isInvalidJSONNumber(data)) {\n throw new Error(\n errorPrefix +\n 'contains ' +\n data.toString() +\n ' ' +\n validationPathToErrorString(path)\n );\n }\n\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\n if (\n typeof data === 'string' &&\n data.length > MAX_LEAF_SIZE_ / 3 &&\n stringLength(data) > MAX_LEAF_SIZE_\n ) {\n throw new Error(\n errorPrefix +\n 'contains a string greater than ' +\n MAX_LEAF_SIZE_ +\n ' utf8 bytes ' +\n validationPathToErrorString(path) +\n \" ('\" +\n data.substring(0, 50) +\n \"...')\"\n );\n }\n\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\n // to save extra walking of large objects.\n if (data && typeof data === 'object') {\n let hasDotValue = false;\n let hasActualChild = false;\n each(data, (key: string, value: unknown) => {\n if (key === '.value') {\n hasDotValue = true;\n } else if (key !== '.priority' && key !== '.sv') {\n hasActualChild = true;\n if (!isValidKey(key)) {\n throw new Error(\n errorPrefix +\n ' contains an invalid key (' +\n key +\n ') ' +\n validationPathToErrorString(path) +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"'\n );\n }\n }\n\n validationPathPush(path, key);\n validateFirebaseData(errorPrefix, value, path);\n validationPathPop(path);\n });\n\n if (hasDotValue && hasActualChild) {\n throw new Error(\n errorPrefix +\n ' contains \".value\" child ' +\n validationPathToErrorString(path) +\n ' in addition to actual children.'\n );\n }\n }\n};\n\n/**\n * Pre-validate paths passed in the firebase function.\n */\nexport const validateFirebaseMergePaths = function (\n errorPrefix: string,\n mergePaths: Path[]\n) {\n let i, curPath: Path;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n const keys = pathSlice(curPath);\n for (let j = 0; j < keys.length; j++) {\n if (keys[j] === '.priority' && j === keys.length - 1) {\n // .priority is OK\n } else if (!isValidKey(keys[j])) {\n throw new Error(\n errorPrefix +\n 'contains an invalid key (' +\n keys[j] +\n ') in path ' +\n curPath.toString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"'\n );\n }\n }\n }\n\n // Check that update keys are not descendants of each other.\n // We rely on the property that sorting guarantees that ancestors come\n // right before descendants.\n mergePaths.sort(pathCompare);\n let prevPath: Path | null = null;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n if (prevPath !== null && pathContains(prevPath, curPath)) {\n throw new Error(\n errorPrefix +\n 'contains a path ' +\n prevPath.toString() +\n ' that is ancestor of another path ' +\n curPath.toString()\n );\n }\n prevPath = curPath;\n }\n};\n\n/**\n * pre-validate an object passed as an argument to firebase function (\n * must be an object - e.g. for firebase.update()).\n */\nexport const validateFirebaseMergeDataArg = function (\n fnName: string,\n data: unknown,\n path: Path,\n optional: boolean\n) {\n if (optional && data === undefined) {\n return;\n }\n\n const errorPrefix = errorPrefixFxn(fnName, 'values');\n\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\n throw new Error(\n errorPrefix + ' must be an object containing the children to replace.'\n );\n }\n\n const mergePaths: Path[] = [];\n each(data, (key: string, value: unknown) => {\n const curPath = new Path(key);\n validateFirebaseData(errorPrefix, value, pathChild(path, curPath));\n if (pathGetBack(curPath) === '.priority') {\n if (!isValidPriority(value)) {\n throw new Error(\n errorPrefix +\n \"contains an invalid value for '\" +\n curPath.toString() +\n \"', which must be a valid \" +\n 'Firebase priority (a string, finite number, server value, or null).'\n );\n }\n }\n mergePaths.push(curPath);\n });\n validateFirebaseMergePaths(errorPrefix, mergePaths);\n};\n\nexport const validatePriority = function (\n fnName: string,\n priority: unknown,\n optional: boolean\n) {\n if (optional && priority === undefined) {\n return;\n }\n if (isInvalidJSONNumber(priority)) {\n throw new Error(\n errorPrefixFxn(fnName, 'priority') +\n 'is ' +\n priority.toString() +\n ', but must be a valid Firebase priority (a string, finite number, ' +\n 'server value, or null).'\n );\n }\n // Special case to allow importing data with a .sv.\n if (!isValidPriority(priority)) {\n throw new Error(\n errorPrefixFxn(fnName, 'priority') +\n 'must be a valid Firebase priority ' +\n '(a string, finite number, server value, or null).'\n );\n }\n};\n\nexport const validateKey = function (\n fnName: string,\n argumentName: string,\n key: string,\n optional: boolean\n) {\n if (optional && key === undefined) {\n return;\n }\n if (!isValidKey(key)) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'was an invalid key = \"' +\n key +\n '\". Firebase keys must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").'\n );\n }\n};\n\n/**\n * @internal\n */\nexport const validatePathString = function (\n fnName: string,\n argumentName: string,\n pathString: string,\n optional: boolean\n) {\n if (optional && pathString === undefined) {\n return;\n }\n\n if (!isValidPathString(pathString)) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'was an invalid path = \"' +\n pathString +\n '\". Paths must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"'\n );\n }\n};\n\nexport const validateRootPathString = function (\n fnName: string,\n argumentName: string,\n pathString: string,\n optional: boolean\n) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n\n validatePathString(fnName, argumentName, pathString, optional);\n};\n\n/**\n * @internal\n */\nexport const validateWritablePath = function (fnName: string, path: Path) {\n if (pathGetFront(path) === '.info') {\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\n }\n};\n\nexport const validateUrl = function (\n fnName: string,\n parsedUrl: { repoInfo: RepoInfo; path: Path }\n) {\n // TODO = Validate server better.\n const pathString = parsedUrl.path.toString();\n if (\n !(typeof parsedUrl.repoInfo.host === 'string') ||\n parsedUrl.repoInfo.host.length === 0 ||\n (!isValidKey(parsedUrl.repoInfo.namespace) &&\n parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||\n (pathString.length !== 0 && !isValidRootPathString(pathString))\n ) {\n throw new Error(\n errorPrefixFxn(fnName, 'url') +\n 'must be a valid firebase URL and ' +\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".'\n );\n }\n};\n\nexport const validateString = function (\n fnName: string,\n argumentName: string,\n string: unknown,\n optional: boolean\n) {\n if (optional && string === undefined) {\n return;\n }\n if (!(typeof string === 'string')) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) + 'must be a valid string.'\n );\n }\n};\n\nexport const validateObject = function (\n fnName: string,\n argumentName: string,\n obj: unknown,\n optional: boolean\n) {\n if (optional && obj === undefined) {\n return;\n }\n if (!(obj && typeof obj === 'object') || obj === null) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) + 'must be a valid object.'\n );\n }\n};\n\nexport const validateObjectContainsKey = function (\n fnName: string,\n argumentName: string,\n obj: unknown,\n key: string,\n optional: boolean,\n optType?: string\n) {\n const objectContainsKey =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj && typeof obj === 'object' && contains(obj as any, key);\n\n if (!objectContainsKey) {\n if (optional) {\n return;\n } else {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'must contain the key \"' +\n key +\n '\"'\n );\n }\n }\n\n if (optType) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const val = safeGet(obj as any, key);\n if (\n (optType === 'number' && !(typeof val === 'number')) ||\n (optType === 'string' && !(typeof val === 'string')) ||\n (optType === 'boolean' && !(typeof val === 'boolean')) ||\n (optType === 'function' && !(typeof val === 'function')) ||\n (optType === 'object' && !(typeof val === 'object') && val)\n ) {\n if (optional) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'contains invalid value for key \"' +\n key +\n '\" (must be of type \"' +\n optType +\n '\")'\n );\n } else {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'must contain the key \"' +\n key +\n '\" with type \"' +\n optType +\n '\"'\n );\n }\n }\n }\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Path, pathContains, pathEquals } from '../util/Path';\nimport { exceptionGuard, log, logger } from '../util/util';\n\nimport { Event } from './Event';\n\n/**\n * The event queue serves a few purposes:\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\n * events being queued.\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\n * left off, ensuring that the events are still raised synchronously and in order.\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\n * events are raised synchronously.\n *\n * NOTE: This can all go away if/when we move to async events.\n *\n */\nexport class EventQueue {\n eventLists_: EventList[] = [];\n\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n */\n recursionDepth_ = 0;\n}\n\n/**\n * @param eventDataList - The new events to queue.\n */\nexport function eventQueueQueueEvents(\n eventQueue: EventQueue,\n eventDataList: Event[]\n) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n let currList: EventList | null = null;\n for (let i = 0; i < eventDataList.length; i++) {\n const data = eventDataList[i];\n const path = data.getPath();\n if (currList !== null && !pathEquals(path, currList.path)) {\n eventQueue.eventLists_.push(currList);\n currList = null;\n }\n\n if (currList === null) {\n currList = { events: [], path };\n }\n\n currList.events.push(data);\n }\n if (currList) {\n eventQueue.eventLists_.push(currList);\n }\n}\n\n/**\n * Queues the specified events and synchronously raises all events (including previously queued ones)\n * for the specified path.\n *\n * It is assumed that the new events are all for the specified path.\n *\n * @param path - The path to raise events for.\n * @param eventDataList - The new events to raise.\n */\nexport function eventQueueRaiseEventsAtPath(\n eventQueue: EventQueue,\n path: Path,\n eventDataList: Event[]\n) {\n eventQueueQueueEvents(eventQueue, eventDataList);\n eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath =>\n pathEquals(eventPath, path)\n );\n}\n\n/**\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\n * locations related to the specified change path (i.e. all ancestors and descendants).\n *\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\n *\n * @param changedPath - The path to raise events for.\n * @param eventDataList - The events to raise\n */\nexport function eventQueueRaiseEventsForChangedPath(\n eventQueue: EventQueue,\n changedPath: Path,\n eventDataList: Event[]\n) {\n eventQueueQueueEvents(eventQueue, eventDataList);\n eventQueueRaiseQueuedEventsMatchingPredicate(\n eventQueue,\n eventPath =>\n pathContains(eventPath, changedPath) ||\n pathContains(changedPath, eventPath)\n );\n}\n\nfunction eventQueueRaiseQueuedEventsMatchingPredicate(\n eventQueue: EventQueue,\n predicate: (path: Path) => boolean\n) {\n eventQueue.recursionDepth_++;\n\n let sentAll = true;\n for (let i = 0; i < eventQueue.eventLists_.length; i++) {\n const eventList = eventQueue.eventLists_[i];\n if (eventList) {\n const eventPath = eventList.path;\n if (predicate(eventPath)) {\n eventListRaise(eventQueue.eventLists_[i]);\n eventQueue.eventLists_[i] = null;\n } else {\n sentAll = false;\n }\n }\n }\n\n if (sentAll) {\n eventQueue.eventLists_ = [];\n }\n\n eventQueue.recursionDepth_--;\n}\n\ninterface EventList {\n events: Event[];\n path: Path;\n}\n\n/**\n * Iterates through the list and raises each event\n */\nfunction eventListRaise(eventList: EventList) {\n for (let i = 0; i < eventList.events.length; i++) {\n const eventData = eventList.events[i];\n if (eventData !== null) {\n eventList.events[i] = null;\n const eventFn = eventData.getEventRunner();\n if (logger) {\n log('event: ' + eventData.toString());\n }\n exceptionGuard(eventFn);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n contains,\n isEmpty,\n map,\n safeGet,\n stringify\n} from '@firebase/util';\n\nimport { ValueEventRegistration } from '../api/Reference_impl';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { PersistentConnection } from './PersistentConnection';\nimport { ReadonlyRestClient } from './ReadonlyRestClient';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { nodeFromJSON } from './snap/nodeFromJSON';\nimport { SnapshotHolder } from './SnapshotHolder';\nimport {\n newSparseSnapshotTree,\n SparseSnapshotTree,\n sparseSnapshotTreeForEachTree,\n sparseSnapshotTreeForget,\n sparseSnapshotTreeRemember\n} from './SparseSnapshotTree';\nimport { StatsCollection } from './stats/StatsCollection';\nimport { StatsListener } from './stats/StatsListener';\nimport {\n statsManagerGetCollection,\n statsManagerGetOrCreateReporter\n} from './stats/StatsManager';\nimport { StatsReporter, statsReporterIncludeStat } from './stats/StatsReporter';\nimport {\n SyncTree,\n syncTreeAckUserWrite,\n syncTreeAddEventRegistration,\n syncTreeApplyServerMerge,\n syncTreeApplyServerOverwrite,\n syncTreeApplyTaggedQueryMerge,\n syncTreeApplyTaggedQueryOverwrite,\n syncTreeApplyUserMerge,\n syncTreeApplyUserOverwrite,\n syncTreeCalcCompleteEventCache,\n syncTreeGetServerValue,\n syncTreeRemoveEventRegistration,\n syncTreeTagForQuery\n} from './SyncTree';\nimport { Indexable } from './util/misc';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathGetFront,\n pathPopFront\n} from './util/Path';\nimport {\n generateWithValues,\n resolveDeferredValueSnapshot,\n resolveDeferredValueTree\n} from './util/ServerValues';\nimport {\n Tree,\n treeForEachAncestor,\n treeForEachChild,\n treeForEachDescendant,\n treeGetPath,\n treeGetValue,\n treeHasChildren,\n treeSetValue,\n treeSubTree\n} from './util/Tree';\nimport {\n beingCrawled,\n each,\n exceptionGuard,\n log,\n LUIDGenerator,\n warn\n} from './util/util';\nimport { isValidPriority, validateFirebaseData } from './util/validation';\nimport { Event } from './view/Event';\nimport {\n EventQueue,\n eventQueueQueueEvents,\n eventQueueRaiseEventsAtPath,\n eventQueueRaiseEventsForChangedPath\n} from './view/EventQueue';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\n\nconst INTERRUPT_REASON = 'repo_interrupt';\n\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other\n * things this ensure that if there's ever a bug causing a mismatch between\n * client / server hashes for some data, we won't retry indefinitely.\n */\nconst MAX_TRANSACTION_RETRIES = 25;\n\nconst enum TransactionStatus {\n // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the\n // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to\n // mismatched hash.\n RUN,\n\n // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted\n // or rejected yet).\n SENT,\n\n // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be\n // removed when we get a chance to prune completed ones.\n COMPLETED,\n\n // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made).\n // If it comes back as unsuccessful, we'll abort it.\n SENT_NEEDS_ABORT,\n\n // Temporary state used to mark transactions that need to be aborted.\n NEEDS_ABORT\n}\n\ninterface Transaction {\n path: Path;\n update: (a: unknown) => unknown;\n onComplete: (\n error: Error | null,\n committed: boolean,\n node: Node | null\n ) => void;\n status: TransactionStatus;\n order: number;\n applyLocally: boolean;\n retryCount: number;\n unwatcher: () => void;\n abortReason: string | null;\n currentWriteId: number;\n currentInputSnapshot: Node | null;\n currentOutputSnapshotRaw: Node | null;\n currentOutputSnapshotResolved: Node | null;\n}\n\n/**\n * A connection to a single data repository.\n */\nexport class Repo {\n /** Key for uniquely identifying this repo, used in RepoManager */\n readonly key: string;\n\n dataUpdateCount = 0;\n infoSyncTree_: SyncTree;\n serverSyncTree_: SyncTree;\n\n stats_: StatsCollection;\n statsListener_: StatsListener | null = null;\n eventQueue_ = new EventQueue();\n nextWriteId_ = 1;\n server_: ServerActions;\n statsReporter_: StatsReporter;\n infoData_: SnapshotHolder;\n interceptServerDataCallback_: ((a: string, b: unknown) => void) | null = null;\n\n /** A list of data pieces and paths to be set when this client disconnects. */\n onDisconnect_: SparseSnapshotTree = newSparseSnapshotTree();\n\n /** Stores queues of outstanding transactions for Firebase locations. */\n transactionQueueTree_ = new Tree();\n\n // TODO: This should be @private but it's used by test_access.js and internal.js\n persistentConnection_: PersistentConnection | null = null;\n\n constructor(\n public repoInfo_: RepoInfo,\n public forceRestClient_: boolean,\n public authTokenProvider_: AuthTokenProvider,\n public appCheckProvider_: AppCheckTokenProvider\n ) {\n // This key is intentionally not updated if RepoInfo is later changed or replaced\n this.key = this.repoInfo_.toURLString();\n }\n\n /**\n * @returns The URL corresponding to the root of this Firebase.\n */\n toString(): string {\n return (\n (this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host\n );\n }\n}\n\nexport function repoStart(\n repo: Repo,\n appId: string,\n authOverride?: object\n): void {\n repo.stats_ = statsManagerGetCollection(repo.repoInfo_);\n\n if (repo.forceRestClient_ || beingCrawled()) {\n repo.server_ = new ReadonlyRestClient(\n repo.repoInfo_,\n (\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n ) => {\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\n },\n repo.authTokenProvider_,\n repo.appCheckProvider_\n );\n\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\n setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);\n } else {\n // Validate authOverride\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\n if (typeof authOverride !== 'object') {\n throw new Error(\n 'Only objects are supported for option databaseAuthVariableOverride'\n );\n }\n try {\n stringify(authOverride);\n } catch (e) {\n throw new Error('Invalid authOverride provided: ' + e);\n }\n }\n\n repo.persistentConnection_ = new PersistentConnection(\n repo.repoInfo_,\n appId,\n (\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n ) => {\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\n },\n (connectStatus: boolean) => {\n repoOnConnectStatus(repo, connectStatus);\n },\n (updates: object) => {\n repoOnServerInfoUpdate(repo, updates);\n },\n repo.authTokenProvider_,\n repo.appCheckProvider_,\n authOverride\n );\n\n repo.server_ = repo.persistentConnection_;\n }\n\n repo.authTokenProvider_.addTokenChangeListener(token => {\n repo.server_.refreshAuthToken(token);\n });\n\n repo.appCheckProvider_.addTokenChangeListener(result => {\n repo.server_.refreshAppCheckToken(result.token);\n });\n\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\n repo.statsReporter_ = statsManagerGetOrCreateReporter(\n repo.repoInfo_,\n () => new StatsReporter(repo.stats_, repo.server_)\n );\n\n // Used for .info.\n repo.infoData_ = new SnapshotHolder();\n repo.infoSyncTree_ = new SyncTree({\n startListening: (query, tag, currentHashFn, onComplete) => {\n let infoEvents: Event[] = [];\n const node = repo.infoData_.getNode(query._path);\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\n // on initial data...\n if (!node.isEmpty()) {\n infoEvents = syncTreeApplyServerOverwrite(\n repo.infoSyncTree_,\n query._path,\n node\n );\n setTimeout(() => {\n onComplete('ok');\n }, 0);\n }\n return infoEvents;\n },\n stopListening: () => {}\n });\n repoUpdateInfo(repo, 'connected', false);\n\n repo.serverSyncTree_ = new SyncTree({\n startListening: (query, tag, currentHashFn, onComplete) => {\n repo.server_.listen(query, currentHashFn, tag, (status, data) => {\n const events = onComplete(status, data);\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n query._path,\n events\n );\n });\n // No synchronous events for network-backed sync trees\n return [];\n },\n stopListening: (query, tag) => {\n repo.server_.unlisten(query, tag);\n }\n });\n}\n\n/**\n * @returns The time in milliseconds, taking the server offset into account if we have one.\n */\nexport function repoServerTime(repo: Repo): number {\n const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));\n const offset = (offsetNode.val() as number) || 0;\n return new Date().getTime() + offset;\n}\n\n/**\n * Generate ServerValues using some variables from the repo object.\n */\nexport function repoGenerateServerValues(repo: Repo): Indexable {\n return generateWithValues({\n timestamp: repoServerTime(repo)\n });\n}\n\n/**\n * Called by realtime when we get new messages from the server.\n */\nfunction repoOnDataUpdate(\n repo: Repo,\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n): void {\n // For testing.\n repo.dataUpdateCount++;\n const path = new Path(pathString);\n data = repo.interceptServerDataCallback_\n ? repo.interceptServerDataCallback_(pathString, data)\n : data;\n let events = [];\n if (tag) {\n if (isMerge) {\n const taggedChildren = map(\n data as { [k: string]: unknown },\n (raw: unknown) => nodeFromJSON(raw)\n );\n events = syncTreeApplyTaggedQueryMerge(\n repo.serverSyncTree_,\n path,\n taggedChildren,\n tag\n );\n } else {\n const taggedSnap = nodeFromJSON(data);\n events = syncTreeApplyTaggedQueryOverwrite(\n repo.serverSyncTree_,\n path,\n taggedSnap,\n tag\n );\n }\n } else if (isMerge) {\n const changedChildren = map(\n data as { [k: string]: unknown },\n (raw: unknown) => nodeFromJSON(raw)\n );\n events = syncTreeApplyServerMerge(\n repo.serverSyncTree_,\n path,\n changedChildren\n );\n } else {\n const snap = nodeFromJSON(data);\n events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);\n }\n let affectedPath = path;\n if (events.length > 0) {\n // Since we have a listener outstanding for each transaction, receiving any events\n // is a proxy for some change having occurred.\n affectedPath = repoRerunTransactions(repo, path);\n }\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);\n}\n\n// TODO: This should be @private but it's used by test_access.js and internal.js\nexport function repoInterceptServerData(\n repo: Repo,\n callback: ((a: string, b: unknown) => unknown) | null\n): void {\n repo.interceptServerDataCallback_ = callback;\n}\n\nfunction repoOnConnectStatus(repo: Repo, connectStatus: boolean): void {\n repoUpdateInfo(repo, 'connected', connectStatus);\n if (connectStatus === false) {\n repoRunOnDisconnectEvents(repo);\n }\n}\n\nfunction repoOnServerInfoUpdate(repo: Repo, updates: object): void {\n each(updates, (key: string, value: unknown) => {\n repoUpdateInfo(repo, key, value);\n });\n}\n\nfunction repoUpdateInfo(repo: Repo, pathString: string, value: unknown): void {\n const path = new Path('/.info/' + pathString);\n const newNode = nodeFromJSON(value);\n repo.infoData_.updateSnapshot(path, newNode);\n const events = syncTreeApplyServerOverwrite(\n repo.infoSyncTree_,\n path,\n newNode\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n}\n\nfunction repoGetNextWriteId(repo: Repo): number {\n return repo.nextWriteId_++;\n}\n\n/**\n * The purpose of `getValue` is to return the latest known value\n * satisfying `query`.\n *\n * This method will first check for in-memory cached values\n * belonging to active listeners. If they are found, such values\n * are considered to be the most up-to-date.\n *\n * If the client is not connected, this method will wait until the\n * repo has established a connection and then request the value for `query`.\n * If the client is not able to retrieve the query result for another reason,\n * it reports an error.\n *\n * @param query - The query to surface a value for.\n */\nexport function repoGetValue(\n repo: Repo,\n query: QueryContext,\n eventRegistration: ValueEventRegistration\n): Promise {\n // Only active queries are cached. There is no persisted cache.\n const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);\n if (cached != null) {\n return Promise.resolve(cached);\n }\n return repo.server_.get(query).then(\n payload => {\n const node = nodeFromJSON(payload).withIndex(\n query._queryParams.getIndex()\n );\n /**\n * Below we simulate the actions of an `onlyOnce` `onValue()` event where:\n * Add an event registration,\n * Update data at the path,\n * Raise any events,\n * Cleanup the SyncTree\n */\n syncTreeAddEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration,\n true\n );\n let events: Event[];\n if (query._queryParams.loadsAllData()) {\n events = syncTreeApplyServerOverwrite(\n repo.serverSyncTree_,\n query._path,\n node\n );\n } else {\n const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);\n events = syncTreeApplyTaggedQueryOverwrite(\n repo.serverSyncTree_,\n query._path,\n node,\n tag\n );\n }\n /*\n * We need to raise events in the scenario where `get()` is called at a parent path, and\n * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting\n * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree\n * and its corresponding serverCache, including the child location where `onValue` is called. Then,\n * `onValue` will receive the event from the server, but look at the syncTree and see that the data received\n * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.\n * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and\n * ensure the corresponding child events will get fired.\n */\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n query._path,\n events\n );\n syncTreeRemoveEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration,\n null,\n true\n );\n return node;\n },\n err => {\n repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);\n return Promise.reject(new Error(err as string));\n }\n );\n}\n\nexport function repoSetWithPriority(\n repo: Repo,\n path: Path,\n newVal: unknown,\n newPriority: number | string | null,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repoLog(repo, 'set', {\n path: path.toString(),\n value: newVal,\n priority: newPriority\n });\n\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\n // (b) store unresolved paths on JSON parse\n const serverValues = repoGenerateServerValues(repo);\n const newNodeUnresolved = nodeFromJSON(newVal, newPriority);\n const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);\n const newNode = resolveDeferredValueSnapshot(\n newNodeUnresolved,\n existing,\n serverValues\n );\n\n const writeId = repoGetNextWriteId(repo);\n const events = syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n path,\n newNode,\n writeId,\n true\n );\n eventQueueQueueEvents(repo.eventQueue_, events);\n repo.server_.put(\n path.toString(),\n newNodeUnresolved.val(/*export=*/ true),\n (status, errorReason) => {\n const success = status === 'ok';\n if (!success) {\n warn('set at ' + path + ' failed: ' + status);\n }\n\n const clearEvents = syncTreeAckUserWrite(\n repo.serverSyncTree_,\n writeId,\n !success\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n const affectedPath = repoAbortTransactions(repo, path);\n repoRerunTransactions(repo, affectedPath);\n // We queued the events above, so just flush the queue here\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);\n}\n\nexport function repoUpdate(\n repo: Repo,\n path: Path,\n childrenToMerge: { [k: string]: unknown },\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });\n\n // Start with our existing data and merge each child into it.\n let empty = true;\n const serverValues = repoGenerateServerValues(repo);\n const changedChildren: { [k: string]: Node } = {};\n each(childrenToMerge, (changedKey: string, changedValue: unknown) => {\n empty = false;\n changedChildren[changedKey] = resolveDeferredValueTree(\n pathChild(path, changedKey),\n nodeFromJSON(changedValue),\n repo.serverSyncTree_,\n serverValues\n );\n });\n\n if (!empty) {\n const writeId = repoGetNextWriteId(repo);\n const events = syncTreeApplyUserMerge(\n repo.serverSyncTree_,\n path,\n changedChildren,\n writeId\n );\n eventQueueQueueEvents(repo.eventQueue_, events);\n repo.server_.merge(\n path.toString(),\n childrenToMerge,\n (status, errorReason) => {\n const success = status === 'ok';\n if (!success) {\n warn('update at ' + path + ' failed: ' + status);\n }\n\n const clearEvents = syncTreeAckUserWrite(\n repo.serverSyncTree_,\n writeId,\n !success\n );\n const affectedPath =\n clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n affectedPath,\n clearEvents\n );\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n\n each(childrenToMerge, (changedPath: string) => {\n const affectedPath = repoAbortTransactions(\n repo,\n pathChild(path, changedPath)\n );\n repoRerunTransactions(repo, affectedPath);\n });\n\n // We queued the events above, so just flush the queue here\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);\n } else {\n log(\"update() called with empty data. Don't do anything.\");\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\n }\n}\n\n/**\n * Applies all of the changes stored up in the onDisconnect_ tree.\n */\nfunction repoRunOnDisconnectEvents(repo: Repo): void {\n repoLog(repo, 'onDisconnectEvents');\n\n const serverValues = repoGenerateServerValues(repo);\n const resolvedOnDisconnectTree = newSparseSnapshotTree();\n sparseSnapshotTreeForEachTree(\n repo.onDisconnect_,\n newEmptyPath(),\n (path, node) => {\n const resolved = resolveDeferredValueTree(\n path,\n node,\n repo.serverSyncTree_,\n serverValues\n );\n sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);\n }\n );\n let events: Event[] = [];\n\n sparseSnapshotTreeForEachTree(\n resolvedOnDisconnectTree,\n newEmptyPath(),\n (path, snap) => {\n events = events.concat(\n syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap)\n );\n const affectedPath = repoAbortTransactions(repo, path);\n repoRerunTransactions(repo, affectedPath);\n }\n );\n\n repo.onDisconnect_ = newSparseSnapshotTree();\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);\n}\n\nexport function repoOnDisconnectCancel(\n repo: Repo,\n path: Path,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeForget(repo.onDisconnect_, path);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n });\n}\n\nexport function repoOnDisconnectSet(\n repo: Repo,\n path: Path,\n value: unknown,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n const newNode = nodeFromJSON(value);\n repo.server_.onDisconnectPut(\n path.toString(),\n newNode.val(/*export=*/ true),\n (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoOnDisconnectSetWithPriority(\n repo: Repo,\n path: Path,\n value: unknown,\n priority: unknown,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n const newNode = nodeFromJSON(value, priority);\n repo.server_.onDisconnectPut(\n path.toString(),\n newNode.val(/*export=*/ true),\n (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoOnDisconnectUpdate(\n repo: Repo,\n path: Path,\n childrenToMerge: { [k: string]: unknown },\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n if (isEmpty(childrenToMerge)) {\n log(\"onDisconnect().update() called with empty data. Don't do anything.\");\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\n return;\n }\n\n repo.server_.onDisconnectMerge(\n path.toString(),\n childrenToMerge,\n (status, errorReason) => {\n if (status === 'ok') {\n each(childrenToMerge, (childName: string, childNode: unknown) => {\n const newChildNode = nodeFromJSON(childNode);\n sparseSnapshotTreeRemember(\n repo.onDisconnect_,\n pathChild(path, childName),\n newChildNode\n );\n });\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoAddEventCallbackForQuery(\n repo: Repo,\n query: QueryContext,\n eventRegistration: EventRegistration\n): void {\n let events;\n if (pathGetFront(query._path) === '.info') {\n events = syncTreeAddEventRegistration(\n repo.infoSyncTree_,\n query,\n eventRegistration\n );\n } else {\n events = syncTreeAddEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration\n );\n }\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\n}\n\nexport function repoRemoveEventCallbackForQuery(\n repo: Repo,\n query: QueryContext,\n eventRegistration: EventRegistration\n): void {\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\n // a little bit by handling the return values anyways.\n let events;\n if (pathGetFront(query._path) === '.info') {\n events = syncTreeRemoveEventRegistration(\n repo.infoSyncTree_,\n query,\n eventRegistration\n );\n } else {\n events = syncTreeRemoveEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration\n );\n }\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\n}\n\nexport function repoInterrupt(repo: Repo): void {\n if (repo.persistentConnection_) {\n repo.persistentConnection_.interrupt(INTERRUPT_REASON);\n }\n}\n\nexport function repoResume(repo: Repo): void {\n if (repo.persistentConnection_) {\n repo.persistentConnection_.resume(INTERRUPT_REASON);\n }\n}\n\nexport function repoStats(repo: Repo, showDelta: boolean = false): void {\n if (typeof console === 'undefined') {\n return;\n }\n\n let stats: { [k: string]: unknown };\n if (showDelta) {\n if (!repo.statsListener_) {\n repo.statsListener_ = new StatsListener(repo.stats_);\n }\n stats = repo.statsListener_.get();\n } else {\n stats = repo.stats_.get();\n }\n\n const longestName = Object.keys(stats).reduce(\n (previousValue, currentValue) =>\n Math.max(currentValue.length, previousValue),\n 0\n );\n\n each(stats, (stat: string, value: unknown) => {\n let paddedStat = stat;\n // pad stat names to be the same length (plus 2 extra spaces).\n for (let i = stat.length; i < longestName + 2; i++) {\n paddedStat += ' ';\n }\n console.log(paddedStat + value);\n });\n}\n\nexport function repoStatsIncrementCounter(repo: Repo, metric: string): void {\n repo.stats_.incrementCounter(metric);\n statsReporterIncludeStat(repo.statsReporter_, metric);\n}\n\nfunction repoLog(repo: Repo, ...varArgs: unknown[]): void {\n let prefix = '';\n if (repo.persistentConnection_) {\n prefix = repo.persistentConnection_.id + ':';\n }\n log(prefix, ...varArgs);\n}\n\nexport function repoCallOnCompleteCallback(\n repo: Repo,\n callback: ((status: Error | null, errorReason?: string) => void) | null,\n status: string,\n errorReason?: string | null\n): void {\n if (callback) {\n exceptionGuard(() => {\n if (status === 'ok') {\n callback(null);\n } else {\n const code = (status || 'error').toUpperCase();\n let message = code;\n if (errorReason) {\n message += ': ' + errorReason;\n }\n\n const error = new Error(message);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (error as any).code = code;\n callback(error);\n }\n });\n }\n}\n\n/**\n * Creates a new transaction, adds it to the transactions we're tracking, and\n * sends it to the server if possible.\n *\n * @param path - Path at which to do transaction.\n * @param transactionUpdate - Update callback.\n * @param onComplete - Completion callback.\n * @param unwatcher - Function that will be called when the transaction no longer\n * need data updates for `path`.\n * @param applyLocally - Whether or not to make intermediate results visible\n */\nexport function repoStartTransaction(\n repo: Repo,\n path: Path,\n transactionUpdate: (a: unknown) => unknown,\n onComplete: ((error: Error, committed: boolean, node: Node) => void) | null,\n unwatcher: () => void,\n applyLocally: boolean\n): void {\n repoLog(repo, 'transaction on ' + path);\n\n // Initialize transaction.\n const transaction: Transaction = {\n path,\n update: transactionUpdate,\n onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out\n // which one goes first.\n order: LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n };\n\n // Run transaction initially.\n const currentState = repoGetLatestState(repo, path, undefined);\n transaction.currentInputSnapshot = currentState;\n const newVal = transaction.update(currentState.val());\n if (newVal === undefined) {\n // Abort transaction.\n transaction.unwatcher();\n transaction.currentOutputSnapshotRaw = null;\n transaction.currentOutputSnapshotResolved = null;\n if (transaction.onComplete) {\n transaction.onComplete(null, false, transaction.currentInputSnapshot);\n }\n } else {\n validateFirebaseData(\n 'transaction failed: Data returned ',\n newVal,\n transaction.path\n );\n\n // Mark as run and add to our queue.\n transaction.status = TransactionStatus.RUN;\n const queueNode = treeSubTree(repo.transactionQueueTree_, path);\n const nodeQueue = treeGetValue(queueNode) || [];\n nodeQueue.push(transaction);\n\n treeSetValue(queueNode, nodeQueue);\n\n // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our\n // transaction state, since the user could start new transactions from the\n // event callbacks.\n let priorityForNode;\n if (\n typeof newVal === 'object' &&\n newVal !== null &&\n contains(newVal, '.priority')\n ) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n priorityForNode = safeGet(newVal as any, '.priority');\n assert(\n isValidPriority(priorityForNode),\n 'Invalid priority returned by transaction. ' +\n 'Priority must be a valid string, finite number, server value, or null.'\n );\n } else {\n const currentNode =\n syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||\n ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n\n const serverValues = repoGenerateServerValues(repo);\n const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);\n const newNode = resolveDeferredValueSnapshot(\n newNodeUnresolved,\n currentState,\n serverValues\n );\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = repoGetNextWriteId(repo);\n\n const events = syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n path,\n newNode,\n transaction.currentWriteId,\n transaction.applyLocally\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n }\n}\n\n/**\n * @param excludeSets - A specific set to exclude\n */\nfunction repoGetLatestState(\n repo: Repo,\n path: Path,\n excludeSets?: number[]\n): Node {\n return (\n syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||\n ChildrenNode.EMPTY_NODE\n );\n}\n\n/**\n * Sends any already-run transactions that aren't waiting for outstanding\n * transactions to complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively\n * with a particular transactionQueueTree node to recurse through the tree.\n *\n * @param node - transactionQueueTree node to start at.\n */\nfunction repoSendReadyTransactions(\n repo: Repo,\n node: Tree = repo.transactionQueueTree_\n): void {\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n repoPruneCompletedTransactionsBelowNode(repo, node);\n }\n\n if (treeGetValue(node)) {\n const queue = repoBuildTransactionQueue(repo, node);\n assert(queue.length > 0, 'Sending zero length transaction queue');\n\n const allRun = queue.every(\n (transaction: Transaction) => transaction.status === TransactionStatus.RUN\n );\n\n // If they're all run (and not sent), we can send them. Else, we must wait.\n if (allRun) {\n repoSendTransactionQueue(repo, treeGetPath(node), queue);\n }\n } else if (treeHasChildren(node)) {\n treeForEachChild(node, childNode => {\n repoSendReadyTransactions(repo, childNode);\n });\n }\n}\n\n/**\n * Given a list of run transactions, send them to the server and then handle\n * the result (success or failure).\n *\n * @param path - The location of the queue.\n * @param queue - Queue of transactions under the specified location.\n */\nfunction repoSendTransactionQueue(\n repo: Repo,\n path: Path,\n queue: Transaction[]\n): void {\n // Mark transactions as sent and increment retry count!\n const setsToIgnore = queue.map(txn => {\n return txn.currentWriteId;\n });\n const latestState = repoGetLatestState(repo, path, setsToIgnore);\n let snapToSend = latestState;\n const latestHash = latestState.hash();\n for (let i = 0; i < queue.length; i++) {\n const txn = queue[i];\n assert(\n txn.status === TransactionStatus.RUN,\n 'tryToSendTransactionQueue_: items in queue should all be run.'\n );\n txn.status = TransactionStatus.SENT;\n txn.retryCount++;\n const relativePath = newRelativePath(path, txn.path);\n // If we've gotten to this point, the output snapshot must be defined.\n snapToSend = snapToSend.updateChild(\n relativePath /** @type {!Node} */,\n txn.currentOutputSnapshotRaw\n );\n }\n\n const dataToSend = snapToSend.val(true);\n const pathToSend = path;\n\n // Send the put.\n repo.server_.put(\n pathToSend.toString(),\n dataToSend,\n (status: string) => {\n repoLog(repo, 'transaction put response', {\n path: pathToSend.toString(),\n status\n });\n\n let events: Event[] = [];\n if (status === 'ok') {\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more\n // transactions or sets.\n const callbacks = [];\n for (let i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.COMPLETED;\n events = events.concat(\n syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId)\n );\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this\n // transaction is complete, it should be set\n callbacks.push(() =>\n queue[i].onComplete(\n null,\n true,\n queue[i].currentOutputSnapshotResolved\n )\n );\n }\n queue[i].unwatcher();\n }\n\n // Now remove the completed transactions.\n repoPruneCompletedTransactionsBelowNode(\n repo,\n treeSubTree(repo.transactionQueueTree_, path)\n );\n // There may be pending transactions that we can now send.\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n\n // Finally, trigger onComplete callbacks.\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n } else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (let i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n } else {\n queue[i].status = TransactionStatus.RUN;\n }\n }\n } else {\n warn(\n 'transaction at ' + pathToSend.toString() + ' failed: ' + status\n );\n for (let i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n queue[i].abortReason = status;\n }\n }\n\n repoRerunTransactions(repo, path);\n }\n },\n latestHash\n );\n}\n\n/**\n * Finds all transactions dependent on the data at changedPath and reruns them.\n *\n * Should be called any time cached data changes.\n *\n * Return the highest path that was affected by rerunning transactions. This\n * is the path at which events need to be raised for.\n *\n * @param changedPath - The path in mergedData that changed.\n * @returns The rootmost path that was affected by rerunning transactions.\n */\nfunction repoRerunTransactions(repo: Repo, changedPath: Path): Path {\n const rootMostTransactionNode = repoGetAncestorTransactionNode(\n repo,\n changedPath\n );\n const path = treeGetPath(rootMostTransactionNode);\n\n const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);\n repoRerunTransactionQueue(repo, queue, path);\n\n return path;\n}\n\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted\n * transactions and whatnot).\n *\n * @param queue - The queue of transactions to run.\n * @param path - The path the queue is for.\n */\nfunction repoRerunTransactionQueue(\n repo: Repo,\n queue: Transaction[],\n path: Path\n): void {\n if (queue.length === 0) {\n return; // Nothing to do!\n }\n\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more transactions or\n // sets.\n const callbacks = [];\n let events: Event[] = [];\n // Ignore all of the sets we're going to re-run.\n const txnsToRerun = queue.filter(q => {\n return q.status === TransactionStatus.RUN;\n });\n const setsToIgnore = txnsToRerun.map(q => {\n return q.currentWriteId;\n });\n for (let i = 0; i < queue.length; i++) {\n const transaction = queue[i];\n const relativePath = newRelativePath(path, transaction.path);\n let abortTransaction = false,\n abortReason;\n assert(\n relativePath !== null,\n 'rerunTransactionsUnderNode_: relativePath should not be null.'\n );\n\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n } else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n } else {\n // This code reruns a transaction\n const currentNode = repoGetLatestState(\n repo,\n transaction.path,\n setsToIgnore\n );\n transaction.currentInputSnapshot = currentNode;\n const newData = queue[i].update(currentNode.val());\n if (newData !== undefined) {\n validateFirebaseData(\n 'transaction failed: Data returned ',\n newData,\n transaction.path\n );\n let newDataNode = nodeFromJSON(newData);\n const hasExplicitPriority =\n typeof newData === 'object' &&\n newData != null &&\n contains(newData, '.priority');\n if (!hasExplicitPriority) {\n // Keep the old priority if there wasn't a priority explicitly specified.\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n }\n\n const oldWriteId = transaction.currentWriteId;\n const serverValues = repoGenerateServerValues(repo);\n const newNodeResolved = resolveDeferredValueSnapshot(\n newDataNode,\n currentNode,\n serverValues\n );\n\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = repoGetNextWriteId(repo);\n // Mutates setsToIgnore in place\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(\n syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n transaction.path,\n newNodeResolved,\n transaction.currentWriteId,\n transaction.applyLocally\n )\n );\n events = events.concat(\n syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true)\n );\n } else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n }\n }\n }\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n events = [];\n if (abortTransaction) {\n // Abort.\n queue[i].status = TransactionStatus.COMPLETED;\n\n // Removing a listener can trigger pruning which can muck with\n // mergedData/visibleData (as it prunes data). So defer the unwatcher\n // until we're done.\n (function (unwatcher) {\n setTimeout(unwatcher, Math.floor(0));\n })(queue[i].unwatcher);\n\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n callbacks.push(() =>\n queue[i].onComplete(null, false, queue[i].currentInputSnapshot)\n );\n } else {\n callbacks.push(() =>\n queue[i].onComplete(new Error(abortReason), false, null)\n );\n }\n }\n }\n }\n\n // Clean up completed transactions.\n repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);\n\n // Now fire callbacks, now that we're in a good, known state.\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n\n // Try to send the transaction result to the server.\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n}\n\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending\n * transaction on it, or just returns the node for the given path if there are\n * no pending transactions on any ancestor.\n *\n * @param path - The location to start at.\n * @returns The rootmost node with a transaction.\n */\nfunction repoGetAncestorTransactionNode(\n repo: Repo,\n path: Path\n): Tree {\n let front;\n\n // Start at the root and walk deeper into the tree towards path until we\n // find a node with pending transactions.\n let transactionNode = repo.transactionQueueTree_;\n front = pathGetFront(path);\n while (front !== null && treeGetValue(transactionNode) === undefined) {\n transactionNode = treeSubTree(transactionNode, front);\n path = pathPopFront(path);\n front = pathGetFront(path);\n }\n\n return transactionNode;\n}\n\n/**\n * Builds the queue of all transactions at or below the specified\n * transactionNode.\n *\n * @param transactionNode\n * @returns The generated queue.\n */\nfunction repoBuildTransactionQueue(\n repo: Repo,\n transactionNode: Tree\n): Transaction[] {\n // Walk any child transaction queues and aggregate them into a single queue.\n const transactionQueue: Transaction[] = [];\n repoAggregateTransactionQueuesForNode(\n repo,\n transactionNode,\n transactionQueue\n );\n\n // Sort them by the order the transactions were created.\n transactionQueue.sort((a, b) => a.order - b.order);\n\n return transactionQueue;\n}\n\nfunction repoAggregateTransactionQueuesForNode(\n repo: Repo,\n node: Tree,\n queue: Transaction[]\n): void {\n const nodeQueue = treeGetValue(node);\n if (nodeQueue) {\n for (let i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n\n treeForEachChild(node, child => {\n repoAggregateTransactionQueuesForNode(repo, child, queue);\n });\n}\n\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n */\nfunction repoPruneCompletedTransactionsBelowNode(\n repo: Repo,\n node: Tree\n): void {\n const queue = treeGetValue(node);\n if (queue) {\n let to = 0;\n for (let from = 0; from < queue.length; from++) {\n if (queue[from].status !== TransactionStatus.COMPLETED) {\n queue[to] = queue[from];\n to++;\n }\n }\n queue.length = to;\n treeSetValue(node, queue.length > 0 ? queue : undefined);\n }\n\n treeForEachChild(node, childNode => {\n repoPruneCompletedTransactionsBelowNode(repo, childNode);\n });\n}\n\n/**\n * Aborts all transactions on ancestors or descendants of the specified path.\n * Called when doing a set() or update() since we consider them incompatible\n * with transactions.\n *\n * @param path - Path for which we want to abort related transactions.\n */\nfunction repoAbortTransactions(repo: Repo, path: Path): Path {\n const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));\n\n const transactionNode = treeSubTree(repo.transactionQueueTree_, path);\n\n treeForEachAncestor(transactionNode, (node: Tree) => {\n repoAbortTransactionsOnNode(repo, node);\n });\n\n repoAbortTransactionsOnNode(repo, transactionNode);\n\n treeForEachDescendant(transactionNode, (node: Tree) => {\n repoAbortTransactionsOnNode(repo, node);\n });\n\n return affectedPath;\n}\n\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param node - Node to abort transactions for.\n */\nfunction repoAbortTransactionsOnNode(\n repo: Repo,\n node: Tree\n): void {\n const queue = treeGetValue(node);\n if (queue) {\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more transactions\n // or sets.\n const callbacks = [];\n\n // Go through queue. Any already-sent transactions must be marked for\n // abort, while the unsent ones can be immediately aborted and removed.\n let events: Event[] = [];\n let lastSent = -1;\n for (let i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n // Already marked. No action needed.\n } else if (queue[i].status === TransactionStatus.SENT) {\n assert(\n lastSent === i - 1,\n 'All SENT items should be at beginning of queue.'\n );\n lastSent = i;\n // Mark transaction for abort when it comes back.\n queue[i].status = TransactionStatus.SENT_NEEDS_ABORT;\n queue[i].abortReason = 'set';\n } else {\n assert(\n queue[i].status === TransactionStatus.RUN,\n 'Unexpected transaction status in abort'\n );\n // We can abort it immediately.\n queue[i].unwatcher();\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n queue[i].currentWriteId,\n true\n )\n );\n if (queue[i].onComplete) {\n callbacks.push(\n queue[i].onComplete.bind(null, new Error('set'), false, null)\n );\n }\n }\n }\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n treeSetValue(node, undefined);\n } else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n\n // Now fire the callbacks.\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n treeGetPath(node),\n events\n );\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../../RepoInfo';\nimport { Path } from '../Path';\nimport { warnIfPageIsSecure, warn, fatal } from '../util';\n\nfunction decodePath(pathString: string): string {\n let pathStringDecoded = '';\n const pieces = pathString.split('/');\n for (let i = 0; i < pieces.length; i++) {\n if (pieces[i].length > 0) {\n let piece = pieces[i];\n try {\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\n } catch (e) {}\n pathStringDecoded += '/' + piece;\n }\n }\n return pathStringDecoded;\n}\n\n/**\n * @returns key value hash\n */\nfunction decodeQuery(queryString: string): { [key: string]: string } {\n const results = {};\n if (queryString.charAt(0) === '?') {\n queryString = queryString.substring(1);\n }\n for (const segment of queryString.split('&')) {\n if (segment.length === 0) {\n continue;\n }\n const kv = segment.split('=');\n if (kv.length === 2) {\n results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\n } else {\n warn(`Invalid query segment '${segment}' in query '${queryString}'`);\n }\n }\n return results;\n}\n\nexport const parseRepoInfo = function (\n dataURL: string,\n nodeAdmin: boolean\n): { repoInfo: RepoInfo; path: Path } {\n const parsedUrl = parseDatabaseURL(dataURL),\n namespace = parsedUrl.namespace;\n\n if (parsedUrl.domain === 'firebase.com') {\n fatal(\n parsedUrl.host +\n ' is no longer supported. ' +\n 'Please use .firebaseio.com instead'\n );\n }\n\n // Catch common error of uninitialized namespace value.\n if (\n (!namespace || namespace === 'undefined') &&\n parsedUrl.domain !== 'localhost'\n ) {\n fatal(\n 'Cannot parse Firebase url. Please use https://.firebaseio.com'\n );\n }\n\n if (!parsedUrl.secure) {\n warnIfPageIsSecure();\n }\n\n const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\n\n return {\n repoInfo: new RepoInfo(\n parsedUrl.host,\n parsedUrl.secure,\n namespace,\n webSocketOnly,\n nodeAdmin,\n /*persistenceKey=*/ '',\n /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain\n ),\n path: new Path(parsedUrl.pathString)\n };\n};\n\nexport const parseDatabaseURL = function (dataURL: string): {\n host: string;\n port: number;\n domain: string;\n subdomain: string;\n secure: boolean;\n scheme: string;\n pathString: string;\n namespace: string;\n} {\n // Default to empty strings in the event of a malformed string.\n let host = '',\n domain = '',\n subdomain = '',\n pathString = '',\n namespace = '';\n\n // Always default to SSL, unless otherwise specified.\n let secure = true,\n scheme = 'https',\n port = 443;\n\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\n if (typeof dataURL === 'string') {\n // Parse scheme.\n let colonInd = dataURL.indexOf('//');\n if (colonInd >= 0) {\n scheme = dataURL.substring(0, colonInd - 1);\n dataURL = dataURL.substring(colonInd + 2);\n }\n\n // Parse host, path, and query string.\n let slashInd = dataURL.indexOf('/');\n if (slashInd === -1) {\n slashInd = dataURL.length;\n }\n let questionMarkInd = dataURL.indexOf('?');\n if (questionMarkInd === -1) {\n questionMarkInd = dataURL.length;\n }\n host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));\n if (slashInd < questionMarkInd) {\n // For pathString, questionMarkInd will always come after slashInd\n pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));\n }\n const queryParams = decodeQuery(\n dataURL.substring(Math.min(dataURL.length, questionMarkInd))\n );\n\n // If we have a port, use scheme for determining if it's secure.\n colonInd = host.indexOf(':');\n if (colonInd >= 0) {\n secure = scheme === 'https' || scheme === 'wss';\n port = parseInt(host.substring(colonInd + 1), 10);\n } else {\n colonInd = host.length;\n }\n\n const hostWithoutPort = host.slice(0, colonInd);\n if (hostWithoutPort.toLowerCase() === 'localhost') {\n domain = 'localhost';\n } else if (hostWithoutPort.split('.').length <= 2) {\n domain = hostWithoutPort;\n } else {\n // Interpret the subdomain of a 3 or more component URL as the namespace name.\n const dotInd = host.indexOf('.');\n subdomain = host.substring(0, dotInd).toLowerCase();\n domain = host.substring(dotInd + 1);\n // Normalize namespaces to lowercase to share storage / connection.\n namespace = subdomain;\n }\n // Always treat the value of the `ns` as the namespace name if it is present.\n if ('ns' in queryParams) {\n namespace = queryParams['ns'];\n }\n }\n\n return {\n host,\n port,\n domain,\n subdomain,\n secure,\n scheme,\n pathString,\n namespace\n };\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport {\n tryParseInt,\n MAX_NAME,\n MIN_NAME,\n INTEGER_32_MIN,\n INTEGER_32_MAX\n} from '../util/util';\n\n// Modeled after base64 web-safe chars, but ordered by ASCII.\nconst PUSH_CHARS =\n '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n\nconst MIN_PUSH_CHAR = '-';\n\nconst MAX_PUSH_CHAR = 'z';\n\nconst MAX_KEY_LEN = 786;\n\n/**\n * Fancy ID generator that creates 20-character string identifiers with the\n * following properties:\n *\n * 1. They're based on timestamp so that they sort *after* any existing ids.\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\n * collide with other clients' IDs.\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\n * that will sort properly).\n * 4. They're monotonically increasing. Even if you generate more than one in\n * the same timestamp, the latter ones will sort after the former ones. We do\n * this by using the previous random bits but \"incrementing\" them by 1 (only\n * in the case of a timestamp collision).\n */\nexport const nextPushId = (function () {\n // Timestamp of last push, used to prevent local collisions if you push twice\n // in one ms.\n let lastPushTime = 0;\n\n // We generate 72-bits of randomness which get turned into 12 characters and\n // appended to the timestamp to prevent collisions with other clients. We\n // store the last characters we generated because in the event of a collision,\n // we'll use those same characters except \"incremented\" by one.\n const lastRandChars: number[] = [];\n\n return function (now: number) {\n const duplicateTime = now === lastPushTime;\n lastPushTime = now;\n\n let i;\n const timeStampChars = new Array(8);\n for (i = 7; i >= 0; i--) {\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\n // NOTE: Can't use << here because javascript will convert to int and lose\n // the upper bits.\n now = Math.floor(now / 64);\n }\n assert(now === 0, 'Cannot push at time == 0');\n\n let id = timeStampChars.join('');\n\n if (!duplicateTime) {\n for (i = 0; i < 12; i++) {\n lastRandChars[i] = Math.floor(Math.random() * 64);\n }\n } else {\n // If the timestamp hasn't changed since last push, use the same random\n // number, except incremented by 1.\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\n lastRandChars[i] = 0;\n }\n lastRandChars[i]++;\n }\n for (i = 0; i < 12; i++) {\n id += PUSH_CHARS.charAt(lastRandChars[i]);\n }\n assert(id.length === 20, 'nextPushId: Length should be 20.');\n\n return id;\n };\n})();\n\nexport const successor = function (key: string) {\n if (key === '' + INTEGER_32_MAX) {\n // See https://firebase.google.com/docs/database/web/lists-of-data#data-order\n return MIN_PUSH_CHAR;\n }\n const keyAsInt: number = tryParseInt(key);\n if (keyAsInt != null) {\n return '' + (keyAsInt + 1);\n }\n const next = new Array(key.length);\n\n for (let i = 0; i < next.length; i++) {\n next[i] = key.charAt(i);\n }\n\n if (next.length < MAX_KEY_LEN) {\n next.push(MIN_PUSH_CHAR);\n return next.join('');\n }\n\n let i = next.length - 1;\n\n while (i >= 0 && next[i] === MAX_PUSH_CHAR) {\n i--;\n }\n\n // `successor` was called on the largest possible key, so return the\n // MAX_NAME, which sorts larger than all keys.\n if (i === -1) {\n return MAX_NAME;\n }\n\n const source = next[i];\n const sourcePlusOne = PUSH_CHARS.charAt(PUSH_CHARS.indexOf(source) + 1);\n next[i] = sourcePlusOne;\n\n return next.slice(0, i + 1).join('');\n};\n\n// `key` is assumed to be non-empty.\nexport const predecessor = function (key: string) {\n if (key === '' + INTEGER_32_MIN) {\n return MIN_NAME;\n }\n const keyAsInt: number = tryParseInt(key);\n if (keyAsInt != null) {\n return '' + (keyAsInt - 1);\n }\n const next = new Array(key.length);\n for (let i = 0; i < next.length; i++) {\n next[i] = key.charAt(i);\n }\n // If `key` ends in `MIN_PUSH_CHAR`, the largest key lexicographically\n // smaller than `key`, is `key[0:key.length - 1]`. The next key smaller\n // than that, `predecessor(predecessor(key))`, is\n //\n // `key[0:key.length - 2] + (key[key.length - 1] - 1) + \\\n // { MAX_PUSH_CHAR repeated MAX_KEY_LEN - (key.length - 1) times }\n //\n // analogous to increment/decrement for base-10 integers.\n //\n // This works because lexicographic comparison works character-by-character,\n // using length as a tie-breaker if one key is a prefix of the other.\n if (next[next.length - 1] === MIN_PUSH_CHAR) {\n if (next.length === 1) {\n // See https://firebase.google.com/docs/database/web/lists-of-data#orderbykey\n return '' + INTEGER_32_MAX;\n }\n delete next[next.length - 1];\n return next.join('');\n }\n // Replace the last character with it's immediate predecessor, and\n // fill the suffix of the key with MAX_PUSH_CHAR. This is the\n // lexicographically largest possible key smaller than `key`.\n next[next.length - 1] = PUSH_CHARS.charAt(\n PUSH_CHARS.indexOf(next[next.length - 1]) - 1\n );\n return next.join('') + MAX_PUSH_CHAR.repeat(MAX_KEY_LEN - next.length);\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { stringify } from '@firebase/util';\n\nimport { DataSnapshot as ExpDataSnapshot } from '../../api/Reference_impl';\nimport { Path } from '../util/Path';\n\nimport { EventRegistration } from './EventRegistration';\n\n/**\n * Encapsulates the data needed to raise an event\n * @interface\n */\nexport interface Event {\n getPath(): Path;\n\n getEventType(): string;\n\n getEventRunner(): () => void;\n\n toString(): string;\n}\n\n/**\n * One of the following strings: \"value\", \"child_added\", \"child_changed\",\n * \"child_removed\", or \"child_moved.\"\n */\nexport type EventType =\n | 'value'\n | 'child_added'\n | 'child_changed'\n | 'child_moved'\n | 'child_removed';\n\n/**\n * Encapsulates the data needed to raise an event\n */\nexport class DataEvent implements Event {\n /**\n * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed\n * @param eventRegistration - The function to call to with the event data. User provided\n * @param snapshot - The data backing the event\n * @param prevName - Optional, the name of the previous child for child_* events.\n */\n constructor(\n public eventType: EventType,\n public eventRegistration: EventRegistration,\n public snapshot: ExpDataSnapshot,\n public prevName?: string | null\n ) {}\n getPath(): Path {\n const ref = this.snapshot.ref;\n if (this.eventType === 'value') {\n return ref._path;\n } else {\n return ref.parent._path;\n }\n }\n getEventType(): string {\n return this.eventType;\n }\n getEventRunner(): () => void {\n return this.eventRegistration.getEventRunner(this);\n }\n toString(): string {\n return (\n this.getPath().toString() +\n ':' +\n this.eventType +\n ':' +\n stringify(this.snapshot.exportVal())\n );\n }\n}\n\nexport class CancelEvent implements Event {\n constructor(\n public eventRegistration: EventRegistration,\n public error: Error,\n public path: Path\n ) {}\n getPath(): Path {\n return this.path;\n }\n getEventType(): string {\n return 'cancel';\n }\n getEventRunner(): () => void {\n return this.eventRegistration.getEventRunner(this);\n }\n toString(): string {\n return this.path.toString() + ':cancel';\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { DataSnapshot } from '../../api/Reference_impl';\nimport { Repo } from '../Repo';\nimport { Path } from '../util/Path';\n\nimport { Change } from './Change';\nimport { CancelEvent, Event } from './Event';\nimport { QueryParams } from './QueryParams';\n\n/**\n * A user callback. Callbacks issues from the Legacy SDK maintain references\n * to the original user-issued callbacks, which allows equality\n * comparison by reference even though this callbacks are wrapped before\n * they can be passed to the firebase@exp SDK.\n *\n * @internal\n */\nexport interface UserCallback {\n (dataSnapshot: DataSnapshot, previousChildName?: string | null): unknown;\n userCallback?: unknown;\n context?: object | null;\n}\n\n/**\n * A wrapper class that converts events from the database@exp SDK to the legacy\n * Database SDK. Events are not converted directly as event registration relies\n * on reference comparison of the original user callback (see `matches()`) and\n * relies on equality of the legacy SDK's `context` object.\n */\nexport class CallbackContext {\n constructor(\n private readonly snapshotCallback: UserCallback,\n private readonly cancelCallback?: (error: Error) => unknown\n ) {}\n\n onValue(\n expDataSnapshot: DataSnapshot,\n previousChildName?: string | null\n ): void {\n this.snapshotCallback.call(null, expDataSnapshot, previousChildName);\n }\n\n onCancel(error: Error): void {\n assert(\n this.hasCancelCallback,\n 'Raising a cancel event on a listener with no cancel callback'\n );\n return this.cancelCallback.call(null, error);\n }\n\n get hasCancelCallback(): boolean {\n return !!this.cancelCallback;\n }\n\n matches(other: CallbackContext): boolean {\n return (\n this.snapshotCallback === other.snapshotCallback ||\n (this.snapshotCallback.userCallback !== undefined &&\n this.snapshotCallback.userCallback ===\n other.snapshotCallback.userCallback &&\n this.snapshotCallback.context === other.snapshotCallback.context)\n );\n }\n}\n\nexport interface QueryContext {\n readonly _queryIdentifier: string;\n readonly _queryObject: object;\n readonly _repo: Repo;\n readonly _path: Path;\n readonly _queryParams: QueryParams;\n}\n\n/**\n * An EventRegistration is basically an event type ('value', 'child_added', etc.) and a callback\n * to be notified of that type of event.\n *\n * That said, it can also contain a cancel callback to be notified if the event is canceled. And\n * currently, this code is organized around the idea that you would register multiple child_ callbacks\n * together, as a single EventRegistration. Though currently we don't do that.\n */\nexport interface EventRegistration {\n /**\n * True if this container has a callback to trigger for this event type\n */\n respondsTo(eventType: string): boolean;\n\n createEvent(change: Change, query: QueryContext): Event;\n\n /**\n * Given event data, return a function to trigger the user's callback\n */\n getEventRunner(eventData: Event): () => void;\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null;\n\n matches(other: EventRegistration): boolean;\n\n /**\n * False basically means this is a \"dummy\" callback container being used as a sentinel\n * to remove all callback containers of a particular type. (e.g. if the user does\n * ref.off('value') without specifying a specific callback).\n *\n * (TODO: Rework this, since it's hacky)\n *\n */\n hasAnyCallback(): boolean;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from '@firebase/util';\n\nimport {\n Repo,\n repoOnDisconnectCancel,\n repoOnDisconnectSet,\n repoOnDisconnectSetWithPriority,\n repoOnDisconnectUpdate\n} from '../core/Repo';\nimport { Path } from '../core/util/Path';\nimport {\n validateFirebaseDataArg,\n validateFirebaseMergeDataArg,\n validatePriority,\n validateWritablePath\n} from '../core/util/validation';\n\n/**\n * The `onDisconnect` class allows you to write or clear data when your client\n * disconnects from the Database server. These updates occur whether your\n * client disconnects cleanly or not, so you can rely on them to clean up data\n * even if a connection is dropped or a client crashes.\n *\n * The `onDisconnect` class is most commonly used to manage presence in\n * applications where it is useful to detect how many clients are connected and\n * when other clients disconnect. See\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information.\n *\n * To avoid problems when a connection is dropped before the requests can be\n * transferred to the Database server, these functions should be called before\n * writing any data.\n *\n * Note that `onDisconnect` operations are only triggered once. If you want an\n * operation to occur each time a disconnect occurs, you'll need to re-establish\n * the `onDisconnect` operations each time you reconnect.\n */\nexport class OnDisconnect {\n /** @hideconstructor */\n constructor(private _repo: Repo, private _path: Path) {}\n\n /**\n * Cancels all previously queued `onDisconnect()` set or update events for this\n * location and all children.\n *\n * If a write has been queued for this location via a `set()` or `update()` at a\n * parent location, the write at this location will be canceled, though writes\n * to sibling locations will still occur.\n *\n * @returns Resolves when synchronization to the server is complete.\n */\n cancel(): Promise {\n const deferred = new Deferred();\n repoOnDisconnectCancel(\n this._repo,\n this._path,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is deleted when the client is disconnected\n * (due to closing the browser, navigating to a new page, or network issues).\n *\n * @returns Resolves when synchronization to the server is complete.\n */\n remove(): Promise {\n validateWritablePath('OnDisconnect.remove', this._path);\n const deferred = new Deferred();\n repoOnDisconnectSet(\n this._repo,\n this._path,\n null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is set to the specified value when the\n * client is disconnected (due to closing the browser, navigating to a new page,\n * or network issues).\n *\n * `set()` is especially useful for implementing \"presence\" systems, where a\n * value should be changed or cleared when a user disconnects so that they\n * appear \"offline\" to other users. See\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information.\n *\n * Note that `onDisconnect` operations are only triggered once. If you want an\n * operation to occur each time a disconnect occurs, you'll need to re-establish\n * the `onDisconnect` operations each time.\n *\n * @param value - The value to be written to this location on disconnect (can\n * be an object, array, string, number, boolean, or null).\n * @returns Resolves when synchronization to the Database is complete.\n */\n set(value: unknown): Promise {\n validateWritablePath('OnDisconnect.set', this._path);\n validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);\n const deferred = new Deferred();\n repoOnDisconnectSet(\n this._repo,\n this._path,\n value,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is set to the specified value and priority\n * when the client is disconnected (due to closing the browser, navigating to a\n * new page, or network issues).\n *\n * @param value - The value to be written to this location on disconnect (can\n * be an object, array, string, number, boolean, or null).\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when synchronization to the Database is complete.\n */\n setWithPriority(\n value: unknown,\n priority: number | string | null\n ): Promise {\n validateWritablePath('OnDisconnect.setWithPriority', this._path);\n validateFirebaseDataArg(\n 'OnDisconnect.setWithPriority',\n value,\n this._path,\n false\n );\n validatePriority('OnDisconnect.setWithPriority', priority, false);\n\n const deferred = new Deferred();\n repoOnDisconnectSetWithPriority(\n this._repo,\n this._path,\n value,\n priority,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Writes multiple values at this location when the client is disconnected (due\n * to closing the browser, navigating to a new page, or network issues).\n *\n * The `values` argument contains multiple property-value pairs that will be\n * written to the Database together. Each child property can either be a simple\n * property (for example, \"name\") or a relative path (for example, \"name/first\")\n * from the current location to the data to update.\n *\n * As opposed to the `set()` method, `update()` can be use to selectively update\n * only the referenced properties at the current location (instead of replacing\n * all the child properties at the current location).\n *\n * @param values - Object containing multiple values.\n * @returns Resolves when synchronization to the Database is complete.\n */\n update(values: object): Promise {\n validateWritablePath('OnDisconnect.update', this._path);\n validateFirebaseMergeDataArg(\n 'OnDisconnect.update',\n values,\n this._path,\n false\n );\n const deferred = new Deferred();\n repoOnDisconnectUpdate(\n this._repo,\n this._path,\n values as Record,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, getModularInstance, Deferred } from '@firebase/util';\n\nimport {\n Repo,\n repoAddEventCallbackForQuery,\n repoGetValue,\n repoRemoveEventCallbackForQuery,\n repoServerTime,\n repoSetWithPriority,\n repoUpdate\n} from '../core/Repo';\nimport { ChildrenNode } from '../core/snap/ChildrenNode';\nimport { Index } from '../core/snap/indexes/Index';\nimport { KEY_INDEX } from '../core/snap/indexes/KeyIndex';\nimport { PathIndex } from '../core/snap/indexes/PathIndex';\nimport { PRIORITY_INDEX } from '../core/snap/indexes/PriorityIndex';\nimport { VALUE_INDEX } from '../core/snap/indexes/ValueIndex';\nimport { Node } from '../core/snap/Node';\nimport { syncPointSetReferenceConstructor } from '../core/SyncPoint';\nimport { syncTreeSetReferenceConstructor } from '../core/SyncTree';\nimport { parseRepoInfo } from '../core/util/libs/parser';\nimport { nextPushId } from '../core/util/NextPushId';\nimport {\n Path,\n pathEquals,\n pathGetBack,\n pathGetFront,\n pathChild,\n pathParent,\n pathToUrlEncodedString,\n pathIsEmpty\n} from '../core/util/Path';\nimport {\n fatal,\n MAX_NAME,\n MIN_NAME,\n ObjectToUniqueKey\n} from '../core/util/util';\nimport {\n isValidPriority,\n validateFirebaseDataArg,\n validateFirebaseMergeDataArg,\n validateKey,\n validatePathString,\n validatePriority,\n validateRootPathString,\n validateUrl,\n validateWritablePath\n} from '../core/util/validation';\nimport { Change } from '../core/view/Change';\nimport { CancelEvent, DataEvent, EventType } from '../core/view/Event';\nimport {\n CallbackContext,\n EventRegistration,\n QueryContext,\n UserCallback\n} from '../core/view/EventRegistration';\nimport {\n QueryParams,\n queryParamsEndAt,\n queryParamsEndBefore,\n queryParamsGetQueryObject,\n queryParamsLimitToFirst,\n queryParamsLimitToLast,\n queryParamsOrderBy,\n queryParamsStartAfter,\n queryParamsStartAt\n} from '../core/view/QueryParams';\n\nimport { Database } from './Database';\nimport { OnDisconnect } from './OnDisconnect';\nimport {\n ListenOptions,\n Query as Query,\n DatabaseReference,\n Unsubscribe,\n ThenableReference\n} from './Reference';\n\n/**\n * @internal\n */\nexport class QueryImpl implements Query, QueryContext {\n /**\n * @hideconstructor\n */\n constructor(\n readonly _repo: Repo,\n readonly _path: Path,\n readonly _queryParams: QueryParams,\n readonly _orderByCalled: boolean\n ) {}\n\n get key(): string | null {\n if (pathIsEmpty(this._path)) {\n return null;\n } else {\n return pathGetBack(this._path);\n }\n }\n\n get ref(): DatabaseReference {\n return new ReferenceImpl(this._repo, this._path);\n }\n\n get _queryIdentifier(): string {\n const obj = queryParamsGetQueryObject(this._queryParams);\n const id = ObjectToUniqueKey(obj);\n return id === '{}' ? 'default' : id;\n }\n\n /**\n * An object representation of the query parameters used by this Query.\n */\n get _queryObject(): object {\n return queryParamsGetQueryObject(this._queryParams);\n }\n\n isEqual(other: QueryImpl | null): boolean {\n other = getModularInstance(other);\n if (!(other instanceof QueryImpl)) {\n return false;\n }\n\n const sameRepo = this._repo === other._repo;\n const samePath = pathEquals(this._path, other._path);\n const sameQueryIdentifier =\n this._queryIdentifier === other._queryIdentifier;\n\n return sameRepo && samePath && sameQueryIdentifier;\n }\n\n toJSON(): string {\n return this.toString();\n }\n\n toString(): string {\n return this._repo.toString() + pathToUrlEncodedString(this._path);\n }\n}\n\n/**\n * Validates that no other order by call has been made\n */\nfunction validateNoPreviousOrderByCall(query: QueryImpl, fnName: string) {\n if (query._orderByCalled === true) {\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\n }\n}\n\n/**\n * Validates start/end values for queries.\n */\nfunction validateQueryEndpoints(params: QueryParams) {\n let startNode = null;\n let endNode = null;\n if (params.hasStart()) {\n startNode = params.getIndexStartValue();\n }\n if (params.hasEnd()) {\n endNode = params.getIndexEndValue();\n }\n\n if (params.getIndex() === KEY_INDEX) {\n const tooManyArgsError =\n 'Query: When ordering by key, you may only pass one argument to ' +\n 'startAt(), endAt(), or equalTo().';\n const wrongArgTypeError =\n 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +\n 'endAt(), endBefore(), or equalTo() must be a string.';\n if (params.hasStart()) {\n const startName = params.getIndexStartName();\n if (startName !== MIN_NAME) {\n throw new Error(tooManyArgsError);\n } else if (typeof startNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n if (params.hasEnd()) {\n const endName = params.getIndexEndName();\n if (endName !== MAX_NAME) {\n throw new Error(tooManyArgsError);\n } else if (typeof endNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n } else if (params.getIndex() === PRIORITY_INDEX) {\n if (\n (startNode != null && !isValidPriority(startNode)) ||\n (endNode != null && !isValidPriority(endNode))\n ) {\n throw new Error(\n 'Query: When ordering by priority, the first argument passed to startAt(), ' +\n 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +\n '(null, a number, or a string).'\n );\n }\n } else {\n assert(\n params.getIndex() instanceof PathIndex ||\n params.getIndex() === VALUE_INDEX,\n 'unknown index type.'\n );\n if (\n (startNode != null && typeof startNode === 'object') ||\n (endNode != null && typeof endNode === 'object')\n ) {\n throw new Error(\n 'Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +\n 'equalTo() cannot be an object.'\n );\n }\n }\n}\n\n/**\n * Validates that limit* has been called with the correct combination of parameters\n */\nfunction validateLimit(params: QueryParams) {\n if (\n params.hasStart() &&\n params.hasEnd() &&\n params.hasLimit() &&\n !params.hasAnchoredLimit()\n ) {\n throw new Error(\n \"Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use \" +\n 'limitToFirst() or limitToLast() instead.'\n );\n }\n}\n/**\n * @internal\n */\nexport class ReferenceImpl extends QueryImpl implements DatabaseReference {\n /** @hideconstructor */\n constructor(repo: Repo, path: Path) {\n super(repo, path, new QueryParams(), false);\n }\n\n get parent(): ReferenceImpl | null {\n const parentPath = pathParent(this._path);\n return parentPath === null\n ? null\n : new ReferenceImpl(this._repo, parentPath);\n }\n\n get root(): ReferenceImpl {\n let ref: ReferenceImpl = this;\n while (ref.parent !== null) {\n ref = ref.parent;\n }\n return ref;\n }\n}\n\n/**\n * A `DataSnapshot` contains data from a Database location.\n *\n * Any time you read data from the Database, you receive the data as a\n * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach\n * with `on()` or `once()`. You can extract the contents of the snapshot as a\n * JavaScript object by calling the `val()` method. Alternatively, you can\n * traverse into the snapshot by calling `child()` to return child snapshots\n * (which you could then call `val()` on).\n *\n * A `DataSnapshot` is an efficiently generated, immutable copy of the data at\n * a Database location. It cannot be modified and will never change (to modify\n * data, you always call the `set()` method on a `Reference` directly).\n */\nexport class DataSnapshot {\n /**\n * @param _node - A SnapshotNode to wrap.\n * @param ref - The location this snapshot came from.\n * @param _index - The iteration order for this snapshot\n * @hideconstructor\n */\n constructor(\n readonly _node: Node,\n /**\n * The location of this DataSnapshot.\n */\n readonly ref: DatabaseReference,\n readonly _index: Index\n ) {}\n\n /**\n * Gets the priority value of the data in this `DataSnapshot`.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}\n * ).\n */\n get priority(): string | number | null {\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\n return this._node.getPriority().val() as string | number | null;\n }\n\n /**\n * The key (last part of the path) of the location of this `DataSnapshot`.\n *\n * The last token in a Database location is considered its key. For example,\n * \"ada\" is the key for the /users/ada/ node. Accessing the key on any\n * `DataSnapshot` will return the key for the location that generated it.\n * However, accessing the key on the root URL of a Database will return\n * `null`.\n */\n get key(): string | null {\n return this.ref.key;\n }\n\n /** Returns the number of child properties of this `DataSnapshot`. */\n get size(): number {\n return this._node.numChildren();\n }\n\n /**\n * Gets another `DataSnapshot` for the location at the specified relative path.\n *\n * Passing a relative path to the `child()` method of a DataSnapshot returns\n * another `DataSnapshot` for the location at the specified relative path. The\n * relative path can either be a simple child name (for example, \"ada\") or a\n * deeper, slash-separated path (for example, \"ada/name/first\"). If the child\n * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`\n * whose value is `null`) is returned.\n *\n * @param path - A relative path to the location of child data.\n */\n child(path: string): DataSnapshot {\n const childPath = new Path(path);\n const childRef = child(this.ref, path);\n return new DataSnapshot(\n this._node.getChild(childPath),\n childRef,\n PRIORITY_INDEX\n );\n }\n /**\n * Returns true if this `DataSnapshot` contains any data. It is slightly more\n * efficient than using `snapshot.val() !== null`.\n */\n exists(): boolean {\n return !this._node.isEmpty();\n }\n\n /**\n * Exports the entire contents of the DataSnapshot as a JavaScript object.\n *\n * The `exportVal()` method is similar to `val()`, except priority information\n * is included (if available), making it suitable for backing up your data.\n *\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\n * Array, string, number, boolean, or `null`).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n exportVal(): any {\n return this._node.val(true);\n }\n\n /**\n * Enumerates the top-level children in the `IteratedDataSnapshot`.\n *\n * Because of the way JavaScript objects work, the ordering of data in the\n * JavaScript object returned by `val()` is not guaranteed to match the\n * ordering on the server nor the ordering of `onChildAdded()` events. That is\n * where `forEach()` comes in handy. It guarantees the children of a\n * `DataSnapshot` will be iterated in their query order.\n *\n * If no explicit `orderBy*()` method is used, results are returned\n * ordered by key (unless priorities are used, in which case, results are\n * returned by priority).\n *\n * @param action - A function that will be called for each child DataSnapshot.\n * The callback can return true to cancel further enumeration.\n * @returns true if enumeration was canceled due to your callback returning\n * true.\n */\n forEach(action: (child: IteratedDataSnapshot) => boolean | void): boolean {\n if (this._node.isLeafNode()) {\n return false;\n }\n\n const childrenNode = this._node as ChildrenNode;\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\n return !!childrenNode.forEachChild(this._index, (key, node) => {\n return action(\n new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX)\n );\n });\n }\n\n /**\n * Returns true if the specified child path has (non-null) data.\n *\n * @param path - A relative path to the location of a potential child.\n * @returns `true` if data exists at the specified child path; else\n * `false`.\n */\n hasChild(path: string): boolean {\n const childPath = new Path(path);\n return !this._node.getChild(childPath).isEmpty();\n }\n\n /**\n * Returns whether or not the `DataSnapshot` has any non-`null` child\n * properties.\n *\n * You can use `hasChildren()` to determine if a `DataSnapshot` has any\n * children. If it does, you can enumerate them using `forEach()`. If it\n * doesn't, then either this snapshot contains a primitive value (which can be\n * retrieved with `val()`) or it is empty (in which case, `val()` will return\n * `null`).\n *\n * @returns true if this snapshot has any children; else false.\n */\n hasChildren(): boolean {\n if (this._node.isLeafNode()) {\n return false;\n } else {\n return !this._node.isEmpty();\n }\n }\n\n /**\n * Returns a JSON-serializable representation of this object.\n */\n toJSON(): object | null {\n return this.exportVal();\n }\n\n /**\n * Extracts a JavaScript value from a `DataSnapshot`.\n *\n * Depending on the data in a `DataSnapshot`, the `val()` method may return a\n * scalar type (string, number, or boolean), an array, or an object. It may\n * also return null, indicating that the `DataSnapshot` is empty (contains no\n * data).\n *\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\n * Array, string, number, boolean, or `null`).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n val(): any {\n return this._node.val();\n }\n}\n\n/**\n * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined.\n */\nexport interface IteratedDataSnapshot extends DataSnapshot {\n key: string; // key of the location of this snapshot.\n}\n\n/**\n *\n * Returns a `Reference` representing the location in the Database\n * corresponding to the provided path. If no path is provided, the `Reference`\n * will point to the root of the Database.\n *\n * @param db - The database instance to obtain a reference for.\n * @param path - Optional path representing the location the returned\n * `Reference` will point. If not provided, the returned `Reference` will\n * point to the root of the Database.\n * @returns If a path is provided, a `Reference`\n * pointing to the provided path. Otherwise, a `Reference` pointing to the\n * root of the Database.\n */\nexport function ref(db: Database, path?: string): DatabaseReference {\n db = getModularInstance(db);\n db._checkNotDeleted('ref');\n return path !== undefined ? child(db._root, path) : db._root;\n}\n\n/**\n * Returns a `Reference` representing the location in the Database\n * corresponding to the provided Firebase URL.\n *\n * An exception is thrown if the URL is not a valid Firebase Database URL or it\n * has a different domain than the current `Database` instance.\n *\n * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored\n * and are not applied to the returned `Reference`.\n *\n * @param db - The database instance to obtain a reference for.\n * @param url - The Firebase URL at which the returned `Reference` will\n * point.\n * @returns A `Reference` pointing to the provided\n * Firebase URL.\n */\nexport function refFromURL(db: Database, url: string): DatabaseReference {\n db = getModularInstance(db);\n db._checkNotDeleted('refFromURL');\n const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\n validateUrl('refFromURL', parsedURL);\n\n const repoInfo = parsedURL.repoInfo;\n if (\n !db._repo.repoInfo_.isCustomHost() &&\n repoInfo.host !== db._repo.repoInfo_.host\n ) {\n fatal(\n 'refFromURL' +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n db._repo.repoInfo_.host +\n ')'\n );\n }\n\n return ref(db, parsedURL.path.toString());\n}\n/**\n * Gets a `Reference` for the location at the specified relative path.\n *\n * The relative path can either be a simple child name (for example, \"ada\") or\n * a deeper slash-separated path (for example, \"ada/name/first\").\n *\n * @param parent - The parent location.\n * @param path - A relative path from this location to the desired child\n * location.\n * @returns The specified child location.\n */\nexport function child(\n parent: DatabaseReference,\n path: string\n): DatabaseReference {\n parent = getModularInstance(parent);\n if (pathGetFront(parent._path) === null) {\n validateRootPathString('child', 'path', path, false);\n } else {\n validatePathString('child', 'path', path, false);\n }\n return new ReferenceImpl(parent._repo, pathChild(parent._path, path));\n}\n\n/**\n * Returns an `OnDisconnect` object - see\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information on how to use it.\n *\n * @param ref - The reference to add OnDisconnect triggers for.\n */\nexport function onDisconnect(ref: DatabaseReference): OnDisconnect {\n ref = getModularInstance(ref) as ReferenceImpl;\n return new OnDisconnect(ref._repo, ref._path);\n}\n\nexport interface ThenableReferenceImpl\n extends ReferenceImpl,\n Pick, 'then' | 'catch'> {\n key: string;\n parent: ReferenceImpl;\n}\n\n/**\n * Generates a new child location using a unique key and returns its\n * `Reference`.\n *\n * This is the most common pattern for adding data to a collection of items.\n *\n * If you provide a value to `push()`, the value is written to the\n * generated location. If you don't pass a value, nothing is written to the\n * database and the child remains empty (but you can use the `Reference`\n * elsewhere).\n *\n * The unique keys generated by `push()` are ordered by the current time, so the\n * resulting list of items is chronologically sorted. The keys are also\n * designed to be unguessable (they contain 72 random bits of entropy).\n *\n * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.\n * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.\n *\n * @param parent - The parent location.\n * @param value - Optional value to be written at the generated location.\n * @returns Combined `Promise` and `Reference`; resolves when write is complete,\n * but can be used immediately as the `Reference` to the child location.\n */\nexport function push(\n parent: DatabaseReference,\n value?: unknown\n): ThenableReference {\n parent = getModularInstance(parent);\n validateWritablePath('push', parent._path);\n validateFirebaseDataArg('push', value, parent._path, true);\n const now = repoServerTime(parent._repo);\n const name = nextPushId(now);\n\n // push() returns a ThennableReference whose promise is fulfilled with a\n // regular Reference. We use child() to create handles to two different\n // references. The first is turned into a ThennableReference below by adding\n // then() and catch() methods and is used as the return value of push(). The\n // second remains a regular Reference and is used as the fulfilled value of\n // the first ThennableReference.\n const thenablePushRef: Partial = child(\n parent,\n name\n ) as ReferenceImpl;\n const pushRef = child(parent, name) as ReferenceImpl;\n\n let promise: Promise;\n if (value != null) {\n promise = set(pushRef, value).then(() => pushRef);\n } else {\n promise = Promise.resolve(pushRef);\n }\n\n thenablePushRef.then = promise.then.bind(promise);\n thenablePushRef.catch = promise.then.bind(promise, undefined);\n return thenablePushRef as ThenableReferenceImpl;\n}\n\n/**\n * Removes the data at this Database location.\n *\n * Any data at child locations will also be deleted.\n *\n * The effect of the remove will be visible immediately and the corresponding\n * event 'value' will be triggered. Synchronization of the remove to the\n * Firebase servers will also be started, and the returned Promise will resolve\n * when complete. If provided, the onComplete callback will be called\n * asynchronously after synchronization has finished.\n *\n * @param ref - The location to remove.\n * @returns Resolves when remove on server is complete.\n */\nexport function remove(ref: DatabaseReference): Promise {\n validateWritablePath('remove', ref._path);\n return set(ref, null);\n}\n\n/**\n * Writes data to this Database location.\n *\n * This will overwrite any data at this location and all child locations.\n *\n * The effect of the write will be visible immediately, and the corresponding\n * events (\"value\", \"child_added\", etc.) will be triggered. Synchronization of\n * the data to the Firebase servers will also be started, and the returned\n * Promise will resolve when complete. If provided, the `onComplete` callback\n * will be called asynchronously after synchronization has finished.\n *\n * Passing `null` for the new value is equivalent to calling `remove()`; namely,\n * all data at this location and all child locations will be deleted.\n *\n * `set()` will remove any priority stored at this location, so if priority is\n * meant to be preserved, you need to use `setWithPriority()` instead.\n *\n * Note that modifying data with `set()` will cancel any pending transactions\n * at that location, so extreme care should be taken if mixing `set()` and\n * `transaction()` to modify the same data.\n *\n * A single `set()` will generate a single \"value\" event at the location where\n * the `set()` was performed.\n *\n * @param ref - The location to write to.\n * @param value - The value to be written (string, number, boolean, object,\n * array, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function set(ref: DatabaseReference, value: unknown): Promise {\n ref = getModularInstance(ref);\n validateWritablePath('set', ref._path);\n validateFirebaseDataArg('set', value, ref._path, false);\n const deferred = new Deferred();\n repoSetWithPriority(\n ref._repo,\n ref._path,\n value,\n /*priority=*/ null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Sets a priority for the data at this Database location.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\n * ).\n *\n * @param ref - The location to write to.\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function setPriority(\n ref: DatabaseReference,\n priority: string | number | null\n): Promise {\n ref = getModularInstance(ref);\n validateWritablePath('setPriority', ref._path);\n validatePriority('setPriority', priority, false);\n const deferred = new Deferred();\n repoSetWithPriority(\n ref._repo,\n pathChild(ref._path, '.priority'),\n priority,\n null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Writes data the Database location. Like `set()` but also specifies the\n * priority for that data.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\n * ).\n *\n * @param ref - The location to write to.\n * @param value - The value to be written (string, number, boolean, object,\n * array, or null).\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function setWithPriority(\n ref: DatabaseReference,\n value: unknown,\n priority: string | number | null\n): Promise {\n validateWritablePath('setWithPriority', ref._path);\n validateFirebaseDataArg('setWithPriority', value, ref._path, false);\n validatePriority('setWithPriority', priority, false);\n if (ref.key === '.length' || ref.key === '.keys') {\n throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';\n }\n\n const deferred = new Deferred();\n repoSetWithPriority(\n ref._repo,\n ref._path,\n value,\n priority,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Writes multiple values to the Database at once.\n *\n * The `values` argument contains multiple property-value pairs that will be\n * written to the Database together. Each child property can either be a simple\n * property (for example, \"name\") or a relative path (for example,\n * \"name/first\") from the current location to the data to update.\n *\n * As opposed to the `set()` method, `update()` can be use to selectively update\n * only the referenced properties at the current location (instead of replacing\n * all the child properties at the current location).\n *\n * The effect of the write will be visible immediately, and the corresponding\n * events ('value', 'child_added', etc.) will be triggered. Synchronization of\n * the data to the Firebase servers will also be started, and the returned\n * Promise will resolve when complete. If provided, the `onComplete` callback\n * will be called asynchronously after synchronization has finished.\n *\n * A single `update()` will generate a single \"value\" event at the location\n * where the `update()` was performed, regardless of how many children were\n * modified.\n *\n * Note that modifying data with `update()` will cancel any pending\n * transactions at that location, so extreme care should be taken if mixing\n * `update()` and `transaction()` to modify the same data.\n *\n * Passing `null` to `update()` will remove the data at this location.\n *\n * See\n * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.\n *\n * @param ref - The location to write to.\n * @param values - Object containing multiple values.\n * @returns Resolves when update on server is complete.\n */\nexport function update(ref: DatabaseReference, values: object): Promise {\n validateFirebaseMergeDataArg('update', values, ref._path, false);\n const deferred = new Deferred();\n repoUpdate(\n ref._repo,\n ref._path,\n values as Record,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Gets the most up-to-date result for this query.\n *\n * @param query - The query to run.\n * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is\n * available, or rejects if the client is unable to return a value (e.g., if the\n * server is unreachable and there is nothing cached).\n */\nexport function get(query: Query): Promise {\n query = getModularInstance(query) as QueryImpl;\n const callbackContext = new CallbackContext(() => {});\n const container = new ValueEventRegistration(callbackContext);\n return repoGetValue(query._repo, query, container).then(node => {\n return new DataSnapshot(\n node,\n new ReferenceImpl(query._repo, query._path),\n query._queryParams.getIndex()\n );\n });\n}\n/**\n * Represents registration for 'value' events.\n */\nexport class ValueEventRegistration implements EventRegistration {\n constructor(private callbackContext: CallbackContext) {}\n\n respondsTo(eventType: string): boolean {\n return eventType === 'value';\n }\n\n createEvent(change: Change, query: QueryContext): DataEvent {\n const index = query._queryParams.getIndex();\n return new DataEvent(\n 'value',\n this,\n new DataSnapshot(\n change.snapshotNode,\n new ReferenceImpl(query._repo, query._path),\n index\n )\n );\n }\n\n getEventRunner(eventData: CancelEvent | DataEvent): () => void {\n if (eventData.getEventType() === 'cancel') {\n return () =>\n this.callbackContext.onCancel((eventData as CancelEvent).error);\n } else {\n return () =>\n this.callbackContext.onValue((eventData as DataEvent).snapshot, null);\n }\n }\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null {\n if (this.callbackContext.hasCancelCallback) {\n return new CancelEvent(this, error, path);\n } else {\n return null;\n }\n }\n\n matches(other: EventRegistration): boolean {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n } else if (!other.callbackContext || !this.callbackContext) {\n // If no callback specified, we consider it to match any callback.\n return true;\n } else {\n return other.callbackContext.matches(this.callbackContext);\n }\n }\n\n hasAnyCallback(): boolean {\n return this.callbackContext !== null;\n }\n}\n\n/**\n * Represents the registration of a child_x event.\n */\nexport class ChildEventRegistration implements EventRegistration {\n constructor(\n private eventType: string,\n private callbackContext: CallbackContext | null\n ) {}\n\n respondsTo(eventType: string): boolean {\n let eventToCheck =\n eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck =\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return this.eventType === eventToCheck;\n }\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null {\n if (this.callbackContext.hasCancelCallback) {\n return new CancelEvent(this, error, path);\n } else {\n return null;\n }\n }\n\n createEvent(change: Change, query: QueryContext): DataEvent {\n assert(change.childName != null, 'Child events should have a childName.');\n const childRef = child(\n new ReferenceImpl(query._repo, query._path),\n change.childName\n );\n const index = query._queryParams.getIndex();\n return new DataEvent(\n change.type as EventType,\n this,\n new DataSnapshot(change.snapshotNode, childRef, index),\n change.prevName\n );\n }\n\n getEventRunner(eventData: CancelEvent | DataEvent): () => void {\n if (eventData.getEventType() === 'cancel') {\n return () =>\n this.callbackContext.onCancel((eventData as CancelEvent).error);\n } else {\n return () =>\n this.callbackContext.onValue(\n (eventData as DataEvent).snapshot,\n (eventData as DataEvent).prevName\n );\n }\n }\n\n matches(other: EventRegistration): boolean {\n if (other instanceof ChildEventRegistration) {\n return (\n this.eventType === other.eventType &&\n (!this.callbackContext ||\n !other.callbackContext ||\n this.callbackContext.matches(other.callbackContext))\n );\n }\n\n return false;\n }\n\n hasAnyCallback(): boolean {\n return !!this.callbackContext;\n }\n}\n\nfunction addEventListener(\n query: Query,\n eventType: EventType,\n callback: UserCallback,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n) {\n let cancelCallback: ((error: Error) => unknown) | undefined;\n if (typeof cancelCallbackOrListenOptions === 'object') {\n cancelCallback = undefined;\n options = cancelCallbackOrListenOptions;\n }\n if (typeof cancelCallbackOrListenOptions === 'function') {\n cancelCallback = cancelCallbackOrListenOptions;\n }\n\n if (options && options.onlyOnce) {\n const userCallback = callback;\n const onceCallback: UserCallback = (dataSnapshot, previousChildName) => {\n repoRemoveEventCallbackForQuery(query._repo, query, container);\n userCallback(dataSnapshot, previousChildName);\n };\n onceCallback.userCallback = callback.userCallback;\n onceCallback.context = callback.context;\n callback = onceCallback;\n }\n\n const callbackContext = new CallbackContext(\n callback,\n cancelCallback || undefined\n );\n const container =\n eventType === 'value'\n ? new ValueEventRegistration(callbackContext)\n : new ChildEventRegistration(eventType, callbackContext);\n repoAddEventCallbackForQuery(query._repo, query, container);\n return () => repoRemoveEventCallbackForQuery(query._repo, query, container);\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'value',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName?: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_added',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_changed',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_moved',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_removed',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\nexport { EventType };\n\n/**\n * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.\n * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from\n * the respective `on*` callbacks.\n *\n * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener\n * will not automatically remove listeners registered on child nodes, `off()`\n * must also be called on any child listeners to remove the callback.\n *\n * If a callback is not specified, all callbacks for the specified eventType\n * will be removed. Similarly, if no eventType is specified, all callbacks\n * for the `Reference` will be removed.\n *\n * Individual listeners can also be removed by invoking their unsubscribe\n * callbacks.\n *\n * @param query - The query that the listener was registered with.\n * @param eventType - One of the following strings: \"value\", \"child_added\",\n * \"child_changed\", \"child_removed\", or \"child_moved.\" If omitted, all callbacks\n * for the `Reference` will be removed.\n * @param callback - The callback function that was passed to `on()` or\n * `undefined` to remove all callbacks.\n */\nexport function off(\n query: Query,\n eventType?: EventType,\n callback?: (\n snapshot: DataSnapshot,\n previousChildName?: string | null\n ) => unknown\n): void {\n let container: EventRegistration | null = null;\n const expCallback = callback ? new CallbackContext(callback) : null;\n if (eventType === 'value') {\n container = new ValueEventRegistration(expCallback);\n } else if (eventType) {\n container = new ChildEventRegistration(eventType, expCallback);\n }\n repoRemoveEventCallbackForQuery(query._repo, query, container);\n}\n\n/** Describes the different query constraints available in this SDK. */\nexport type QueryConstraintType =\n | 'endAt'\n | 'endBefore'\n | 'startAt'\n | 'startAfter'\n | 'limitToFirst'\n | 'limitToLast'\n | 'orderByChild'\n | 'orderByKey'\n | 'orderByPriority'\n | 'orderByValue'\n | 'equalTo';\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Database query. `QueryConstraint`s are created by invoking {@link endAt},\n * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link\n * limitToFirst}, {@link limitToLast}, {@link orderByChild},\n * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,\n * {@link orderByValue} or {@link equalTo} and\n * can then be passed to {@link query} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nexport abstract class QueryConstraint {\n /** The type of this query constraints */\n abstract readonly type: QueryConstraintType;\n\n /**\n * Takes the provided `Query` and returns a copy of the `Query` with this\n * `QueryConstraint` applied.\n */\n abstract _apply(query: QueryImpl): QueryImpl;\n}\n\nclass QueryEndAtConstraint extends QueryConstraint {\n readonly type = 'endAt';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('endAt', this._value, query._path, true);\n const newParams = queryParamsEndAt(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'endAt: Starting point was already set (by another call to endAt, ' +\n 'endBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified ending point.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The ending point is inclusive, so children with exactly the specified value\n * will be included in the query. The optional key argument can be used to\n * further limit the range of the query. If it is specified, then children that\n * have exactly the specified value must also have a key name less than or equal\n * to the specified key.\n *\n * You can read more about `endAt()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to end at. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to end at, among the children with the previously\n * specified priority. This argument is only allowed if ordering by child,\n * value, or priority.\n */\nexport function endAt(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('endAt', 'key', key, true);\n return new QueryEndAtConstraint(value, key);\n}\n\nclass QueryEndBeforeConstraint extends QueryConstraint {\n readonly type = 'endBefore';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('endBefore', this._value, query._path, false);\n const newParams = queryParamsEndBefore(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'endBefore: Starting point was already set (by another call to endAt, ' +\n 'endBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified ending point (exclusive).\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The ending point is exclusive. If only a value is provided, children\n * with a value less than the specified value will be included in the query.\n * If a key is specified, then children must have a value less than or equal\n * to the specified value and a key name less than the specified key.\n *\n * @param value - The value to end before. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to end before, among the children with the\n * previously specified priority. This argument is only allowed if ordering by\n * child, value, or priority.\n */\nexport function endBefore(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('endBefore', 'key', key, true);\n return new QueryEndBeforeConstraint(value, key);\n}\n\nclass QueryStartAtConstraint extends QueryConstraint {\n readonly type = 'startAt';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('startAt', this._value, query._path, true);\n const newParams = queryParamsStartAt(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'startAt: Starting point was already set (by another call to startAt, ' +\n 'startBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified starting point.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The starting point is inclusive, so children with exactly the specified value\n * will be included in the query. The optional key argument can be used to\n * further limit the range of the query. If it is specified, then children that\n * have exactly the specified value must also have a key name greater than or\n * equal to the specified key.\n *\n * You can read more about `startAt()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to start at. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start at. This argument is only allowed if\n * ordering by child, value, or priority.\n */\nexport function startAt(\n value: number | string | boolean | null = null,\n key?: string\n): QueryConstraint {\n validateKey('startAt', 'key', key, true);\n return new QueryStartAtConstraint(value, key);\n}\n\nclass QueryStartAfterConstraint extends QueryConstraint {\n readonly type = 'startAfter';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('startAfter', this._value, query._path, false);\n const newParams = queryParamsStartAfter(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'startAfter: Starting point was already set (by another call to startAt, ' +\n 'startAfter, or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified starting point (exclusive).\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The starting point is exclusive. If only a value is provided, children\n * with a value greater than the specified value will be included in the query.\n * If a key is specified, then children must have a value greater than or equal\n * to the specified value and a a key name greater than the specified key.\n *\n * @param value - The value to start after. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start after. This argument is only allowed if\n * ordering by child, value, or priority.\n */\nexport function startAfter(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('startAfter', 'key', key, true);\n return new QueryStartAfterConstraint(value, key);\n}\n\nclass QueryLimitToFirstConstraint extends QueryConstraint {\n readonly type = 'limitToFirst';\n\n constructor(private readonly _limit: number) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n if (query._queryParams.hasLimit()) {\n throw new Error(\n 'limitToFirst: Limit was already set (by another call to limitToFirst ' +\n 'or limitToLast).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n queryParamsLimitToFirst(query._queryParams, this._limit),\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that if limited to the first specific number\n * of children.\n *\n * The `limitToFirst()` method is used to set a maximum number of children to be\n * synced for a given callback. If we set a limit of 100, we will initially only\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\n * stored in our Database, a `child_added` event will fire for each message.\n * However, if we have over 100 messages, we will only receive a `child_added`\n * event for the first 100 ordered messages. As items change, we will receive\n * `child_removed` events for each item that drops out of the active list so\n * that the total number stays at 100.\n *\n * You can read more about `limitToFirst()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param limit - The maximum number of nodes to include in this query.\n */\nexport function limitToFirst(limit: number): QueryConstraint {\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\n throw new Error('limitToFirst: First argument must be a positive integer.');\n }\n return new QueryLimitToFirstConstraint(limit);\n}\n\nclass QueryLimitToLastConstraint extends QueryConstraint {\n readonly type = 'limitToLast';\n\n constructor(private readonly _limit: number) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n if (query._queryParams.hasLimit()) {\n throw new Error(\n 'limitToLast: Limit was already set (by another call to limitToFirst ' +\n 'or limitToLast).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n queryParamsLimitToLast(query._queryParams, this._limit),\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that is limited to return only the last\n * specified number of children.\n *\n * The `limitToLast()` method is used to set a maximum number of children to be\n * synced for a given callback. If we set a limit of 100, we will initially only\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\n * stored in our Database, a `child_added` event will fire for each message.\n * However, if we have over 100 messages, we will only receive a `child_added`\n * event for the last 100 ordered messages. As items change, we will receive\n * `child_removed` events for each item that drops out of the active list so\n * that the total number stays at 100.\n *\n * You can read more about `limitToLast()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param limit - The maximum number of nodes to include in this query.\n */\nexport function limitToLast(limit: number): QueryConstraint {\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\n throw new Error('limitToLast: First argument must be a positive integer.');\n }\n\n return new QueryLimitToLastConstraint(limit);\n}\n\nclass QueryOrderByChildConstraint extends QueryConstraint {\n readonly type = 'orderByChild';\n\n constructor(private readonly _path: string) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByChild');\n const parsedPath = new Path(this._path);\n if (pathIsEmpty(parsedPath)) {\n throw new Error(\n 'orderByChild: cannot pass in empty path. Use orderByValue() instead.'\n );\n }\n const index = new PathIndex(parsedPath);\n const newParams = queryParamsOrderBy(query._queryParams, index);\n validateQueryEndpoints(newParams);\n\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by the specified child key.\n *\n * Queries can only order by one key at a time. Calling `orderByChild()`\n * multiple times on the same query is an error.\n *\n * Firebase queries allow you to order your data by any child key on the fly.\n * However, if you know in advance what your indexes will be, you can define\n * them via the .indexOn rule in your Security Rules for better performance. See\n * the{@link https://firebase.google.com/docs/database/security/indexing-data}\n * rule for more information.\n *\n * You can read more about `orderByChild()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n *\n * @param path - The path to order by.\n */\nexport function orderByChild(path: string): QueryConstraint {\n if (path === '$key') {\n throw new Error(\n 'orderByChild: \"$key\" is invalid. Use orderByKey() instead.'\n );\n } else if (path === '$priority') {\n throw new Error(\n 'orderByChild: \"$priority\" is invalid. Use orderByPriority() instead.'\n );\n } else if (path === '$value') {\n throw new Error(\n 'orderByChild: \"$value\" is invalid. Use orderByValue() instead.'\n );\n }\n validatePathString('orderByChild', 'path', path, false);\n return new QueryOrderByChildConstraint(path);\n}\n\nclass QueryOrderByKeyConstraint extends QueryConstraint {\n readonly type = 'orderByKey';\n\n _apply(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByKey');\n const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by the key.\n *\n * Sorts the results of a query by their (ascending) key values.\n *\n * You can read more about `orderByKey()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n */\nexport function orderByKey(): QueryConstraint {\n return new QueryOrderByKeyConstraint();\n}\n\nclass QueryOrderByPriorityConstraint extends QueryConstraint {\n readonly type = 'orderByPriority';\n\n _apply(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByPriority');\n const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by priority.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}\n * for alternatives to priority.\n */\nexport function orderByPriority(): QueryConstraint {\n return new QueryOrderByPriorityConstraint();\n}\n\nclass QueryOrderByValueConstraint extends QueryConstraint {\n readonly type = 'orderByValue';\n\n _apply(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByValue');\n const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by value.\n *\n * If the children of a query are all scalar values (string, number, or\n * boolean), you can order the results by their (ascending) values.\n *\n * You can read more about `orderByValue()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n */\nexport function orderByValue(): QueryConstraint {\n return new QueryOrderByValueConstraint();\n}\n\nclass QueryEqualToValueConstraint extends QueryConstraint {\n readonly type = 'equalTo';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('equalTo', this._value, query._path, false);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'equalTo: Starting point was already set (by another call to startAt/startAfter or ' +\n 'equalTo).'\n );\n }\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'equalTo: Ending point was already set (by another call to endAt/endBefore or ' +\n 'equalTo).'\n );\n }\n return new QueryEndAtConstraint(this._value, this._key)._apply(\n new QueryStartAtConstraint(this._value, this._key)._apply(query)\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` that includes children that match the specified\n * value.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The optional key argument can be used to further limit the range of the\n * query. If it is specified, then children that have exactly the specified\n * value must also have exactly the specified key as their key name. This can be\n * used to filter result sets with many matches for the same value.\n *\n * You can read more about `equalTo()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to match for. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start at, among the children with the\n * previously specified priority. This argument is only allowed if ordering by\n * child, value, or priority.\n */\nexport function equalTo(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('equalTo', 'key', key, true);\n return new QueryEqualToValueConstraint(value, key);\n}\n\n/**\n * Creates a new immutable instance of `Query` that is extended to also include\n * additional query constraints.\n *\n * @param query - The Query instance to use as a base for the new constraints.\n * @param queryConstraints - The list of `QueryConstraint`s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query(\n query: Query,\n ...queryConstraints: QueryConstraint[]\n): Query {\n let queryImpl = getModularInstance(query) as QueryImpl;\n for (const constraint of queryConstraints) {\n queryImpl = constraint._apply(queryImpl);\n }\n return queryImpl;\n}\n\n/**\n * Define reference constructor in various modules\n *\n * We are doing this here to avoid several circular\n * dependency issues\n */\nsyncPointSetReferenceConstructor(ReferenceImpl);\nsyncTreeSetReferenceConstructor(ReferenceImpl);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _FirebaseService,\n _getProvider,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\nimport {\n getModularInstance,\n createMockUserToken,\n deepEqual,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\n} from '@firebase/util';\n\nimport { AppCheckTokenProvider } from '../core/AppCheckTokenProvider';\nimport {\n AuthTokenProvider,\n EmulatorTokenProvider,\n FirebaseAuthTokenProvider\n} from '../core/AuthTokenProvider';\nimport { Repo, repoInterrupt, repoResume, repoStart } from '../core/Repo';\nimport { RepoInfo, RepoInfoEmulatorOptions } from '../core/RepoInfo';\nimport { parseRepoInfo } from '../core/util/libs/parser';\nimport { newEmptyPath, pathIsEmpty } from '../core/util/Path';\nimport {\n warn,\n fatal,\n log,\n enableLogging as enableLoggingImpl\n} from '../core/util/util';\nimport { validateUrl } from '../core/util/validation';\nimport { BrowserPollConnection } from '../realtime/BrowserPollConnection';\nimport { TransportManager } from '../realtime/TransportManager';\nimport { WebSocketConnection } from '../realtime/WebSocketConnection';\n\nimport { ReferenceImpl } from './Reference_impl';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n/**\n * This variable is also defined in the firebase Node.js Admin SDK. Before\n * modifying this definition, consult the definition in:\n *\n * https://github.com/firebase/firebase-admin-node\n *\n * and make sure the two are consistent.\n */\nconst FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';\n\n/**\n * Creates and caches `Repo` instances.\n */\nconst repos: {\n [appName: string]: {\n [dbUrl: string]: Repo;\n };\n} = {};\n\n/**\n * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).\n */\nlet useRestClient = false;\n\n/**\n * Update an existing `Repo` in place to point to a new host/port.\n */\nfunction repoManagerApplyEmulatorSettings(\n repo: Repo,\n hostAndPort: string,\n emulatorOptions: RepoInfoEmulatorOptions,\n tokenProvider?: AuthTokenProvider\n): void {\n const portIndex = hostAndPort.lastIndexOf(':');\n const host = hostAndPort.substring(0, portIndex);\n const useSsl = isCloudWorkstation(host);\n repo.repoInfo_ = new RepoInfo(\n hostAndPort,\n /* secure= */ useSsl,\n repo.repoInfo_.namespace,\n repo.repoInfo_.webSocketOnly,\n repo.repoInfo_.nodeAdmin,\n repo.repoInfo_.persistenceKey,\n repo.repoInfo_.includeNamespaceInQueryParams,\n /*isUsingEmulator=*/ true,\n emulatorOptions\n );\n\n if (tokenProvider) {\n repo.authTokenProvider_ = tokenProvider;\n }\n}\n\n/**\n * This function should only ever be called to CREATE a new database instance.\n * @internal\n */\nexport function repoManagerDatabaseFromApp(\n app: FirebaseApp,\n authProvider: Provider,\n appCheckProvider?: Provider,\n url?: string,\n nodeAdmin?: boolean\n): Database {\n let dbUrl: string | undefined = url || app.options.databaseURL;\n if (dbUrl === undefined) {\n if (!app.options.projectId) {\n fatal(\n \"Can't determine Firebase Database URL. Be sure to include \" +\n ' a Project ID when calling firebase.initializeApp().'\n );\n }\n\n log('Using default host for project ', app.options.projectId);\n dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;\n }\n\n let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\n let repoInfo = parsedUrl.repoInfo;\n\n let isEmulator: boolean;\n\n let dbEmulatorHost: string | undefined = undefined;\n if (typeof process !== 'undefined' && process.env) {\n dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];\n }\n\n if (dbEmulatorHost) {\n isEmulator = true;\n dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;\n parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\n repoInfo = parsedUrl.repoInfo;\n } else {\n isEmulator = !parsedUrl.repoInfo.secure;\n }\n\n const authTokenProvider =\n nodeAdmin && isEmulator\n ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)\n : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);\n\n validateUrl('Invalid Firebase Database URL', parsedUrl);\n if (!pathIsEmpty(parsedUrl.path)) {\n fatal(\n 'Database URL must point to the root of a Firebase Database ' +\n '(not including a child path).'\n );\n }\n\n const repo = repoManagerCreateRepo(\n repoInfo,\n app,\n authTokenProvider,\n new AppCheckTokenProvider(app, appCheckProvider)\n );\n return new Database(repo, app);\n}\n\n/**\n * Remove the repo and make sure it is disconnected.\n *\n */\nfunction repoManagerDeleteRepo(repo: Repo, appName: string): void {\n const appRepos = repos[appName];\n // This should never happen...\n if (!appRepos || appRepos[repo.key] !== repo) {\n fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);\n }\n repoInterrupt(repo);\n delete appRepos[repo.key];\n}\n\n/**\n * Ensures a repo doesn't already exist and then creates one using the\n * provided app.\n *\n * @param repoInfo - The metadata about the Repo\n * @returns The Repo object for the specified server / repoName.\n */\nfunction repoManagerCreateRepo(\n repoInfo: RepoInfo,\n app: FirebaseApp,\n authTokenProvider: AuthTokenProvider,\n appCheckProvider: AppCheckTokenProvider\n): Repo {\n let appRepos = repos[app.name];\n\n if (!appRepos) {\n appRepos = {};\n repos[app.name] = appRepos;\n }\n\n let repo = appRepos[repoInfo.toURLString()];\n if (repo) {\n fatal(\n 'Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.'\n );\n }\n repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);\n appRepos[repoInfo.toURLString()] = repo;\n\n return repo;\n}\n\n/**\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\n */\nexport function repoManagerForceRestClient(forceRestClient: boolean): void {\n useRestClient = forceRestClient;\n}\n\n/**\n * Class representing a Firebase Realtime Database.\n */\nexport class Database implements _FirebaseService {\n /** Represents a `Database` instance. */\n readonly 'type' = 'database';\n\n /** Track if the instance has been used (root or repo accessed) */\n _instanceStarted: boolean = false;\n\n /** Backing state for root_ */\n private _rootInternal?: ReferenceImpl;\n\n /** @hideconstructor */\n constructor(\n public _repoInternal: Repo,\n /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */\n readonly app: FirebaseApp\n ) {}\n\n get _repo(): Repo {\n if (!this._instanceStarted) {\n repoStart(\n this._repoInternal,\n this.app.options.appId,\n this.app.options['databaseAuthVariableOverride']\n );\n this._instanceStarted = true;\n }\n return this._repoInternal;\n }\n\n get _root(): ReferenceImpl {\n if (!this._rootInternal) {\n this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());\n }\n return this._rootInternal;\n }\n\n _delete(): Promise {\n if (this._rootInternal !== null) {\n repoManagerDeleteRepo(this._repo, this.app.name);\n this._repoInternal = null;\n this._rootInternal = null;\n }\n return Promise.resolve();\n }\n\n _checkNotDeleted(apiName: string) {\n if (this._rootInternal === null) {\n fatal('Cannot call ' + apiName + ' on a deleted database.');\n }\n }\n}\n\nfunction checkTransportInit() {\n if (TransportManager.IS_TRANSPORT_INITIALIZED) {\n warn(\n 'Transport has already been initialized. Please call this function before calling ref or setting up a listener'\n );\n }\n}\n\n/**\n * Force the use of websockets instead of longPolling.\n */\nexport function forceWebSockets() {\n checkTransportInit();\n BrowserPollConnection.forceDisallow();\n}\n\n/**\n * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.\n */\nexport function forceLongPolling() {\n checkTransportInit();\n WebSocketConnection.forceDisallow();\n BrowserPollConnection.forceAllow();\n}\n\n/**\n * Returns the instance of the Realtime Database SDK that is associated with the provided\n * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if\n * no instance exists or if the existing instance uses a custom database URL.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime\n * Database instance is associated with.\n * @param url - The URL of the Realtime Database instance to connect to. If not\n * provided, the SDK connects to the default instance of the Firebase App.\n * @returns The `Database` instance of the provided app.\n */\nexport function getDatabase(\n app: FirebaseApp = getApp(),\n url?: string\n): Database {\n const db = _getProvider(app, 'database').getImmediate({\n identifier: url\n }) as Database;\n if (!db._instanceStarted) {\n const emulator = getDefaultEmulatorHostnameAndPort('database');\n if (emulator) {\n connectDatabaseEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * Modify the provided instance to communicate with the Realtime Database\n * emulator.\n *\n *

Note: This method must be called before performing any other operation.\n *\n * @param db - The instance to modify.\n * @param host - The emulator host (ex: localhost)\n * @param port - The emulator port (ex: 8080)\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\n */\nexport function connectDatabaseEmulator(\n db: Database,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n db = getModularInstance(db);\n db._checkNotDeleted('useEmulator');\n\n const hostAndPort = `${host}:${port}`;\n const repo = db._repoInternal;\n if (db._instanceStarted) {\n // If the instance has already been started, then silenty fail if this function is called again\n // with the same parameters. If the parameters differ then assert.\n if (\n hostAndPort === db._repoInternal.repoInfo_.host &&\n deepEqual(options, repo.repoInfo_.emulatorOptions)\n ) {\n return;\n }\n fatal(\n 'connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.'\n );\n }\n\n let tokenProvider: EmulatorTokenProvider | undefined = undefined;\n if (repo.repoInfo_.nodeAdmin) {\n if (options.mockUserToken) {\n fatal(\n 'mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the \"firebase\" package instead of \"firebase-admin\".'\n );\n }\n tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);\n } else if (options.mockUserToken) {\n const token =\n typeof options.mockUserToken === 'string'\n ? options.mockUserToken\n : createMockUserToken(options.mockUserToken, db.app.options.projectId);\n tokenProvider = new EmulatorTokenProvider(token);\n }\n\n // Workaround to get cookies in Firebase Studio\n if (isCloudWorkstation(host)) {\n void pingServer(host);\n updateEmulatorBanner('Database', true);\n }\n\n // Modify the repo to apply emulator settings\n repoManagerApplyEmulatorSettings(repo, hostAndPort, options, tokenProvider);\n}\n\n/**\n * Disconnects from the server (all Database operations will be completed\n * offline).\n *\n * The client automatically maintains a persistent connection to the Database\n * server, which will remain active indefinitely and reconnect when\n * disconnected. However, the `goOffline()` and `goOnline()` methods may be used\n * to control the client connection in cases where a persistent connection is\n * undesirable.\n *\n * While offline, the client will no longer receive data updates from the\n * Database. However, all Database operations performed locally will continue to\n * immediately fire events, allowing your application to continue behaving\n * normally. Additionally, each operation performed locally will automatically\n * be queued and retried upon reconnection to the Database server.\n *\n * To reconnect to the Database and begin receiving remote events, see\n * `goOnline()`.\n *\n * @param db - The instance to disconnect.\n */\nexport function goOffline(db: Database): void {\n db = getModularInstance(db);\n db._checkNotDeleted('goOffline');\n repoInterrupt(db._repo);\n}\n\n/**\n * Reconnects to the server and synchronizes the offline Database state\n * with the server state.\n *\n * This method should be used after disabling the active connection with\n * `goOffline()`. Once reconnected, the client will transmit the proper data\n * and fire the appropriate events so that your client \"catches up\"\n * automatically.\n *\n * @param db - The instance to reconnect.\n */\nexport function goOnline(db: Database): void {\n db = getModularInstance(db);\n db._checkNotDeleted('goOnline');\n repoResume(db._repo);\n}\n\n/**\n * Logs debugging information to the console.\n *\n * @param enabled - Enables logging if `true`, disables logging if `false`.\n * @param persistent - Remembers the logging state between page refreshes if\n * `true`.\n */\nexport function enableLogging(enabled: boolean, persistent?: boolean);\n\n/**\n * Logs debugging information to the console.\n *\n * @param logger - A custom logger function to control how things get logged.\n */\nexport function enableLogging(logger: (message: string) => unknown);\n\nexport function enableLogging(\n logger: boolean | ((message: string) => unknown),\n persistent?: boolean\n): void {\n enableLoggingImpl(logger, persistent);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { name, version } from '../package.json';\nimport { setSDKVersion } from '../src/core/version';\n\nimport { repoManagerDatabaseFromApp } from './api/Database';\n\nexport function registerDatabase(variant?: string): void {\n setSDKVersion(SDK_VERSION);\n _registerComponent(\n new Component(\n 'database',\n (container, { instanceIdentifier: url }) => {\n const app = container.getProvider('app').getImmediate()!;\n const authProvider = container.getProvider('auth-internal');\n const appCheckProvider = container.getProvider('app-check-internal');\n return repoManagerDatabaseFromApp(\n app,\n authProvider,\n appCheckProvider,\n url\n );\n },\n ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n registerVersion(name, version, variant);\n // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst SERVER_TIMESTAMP = {\n '.sv': 'timestamp'\n};\n\n/**\n * Returns a placeholder value for auto-populating the current timestamp (time\n * since the Unix epoch, in milliseconds) as determined by the Firebase\n * servers.\n */\nexport function serverTimestamp(): object {\n return SERVER_TIMESTAMP;\n}\n\n/**\n * Returns a placeholder value that can be used to atomically increment the\n * current database value by the provided delta.\n *\n * @param delta - the amount to modify the current value atomically.\n * @returns A placeholder value for modifying data atomically server-side.\n */\nexport function increment(delta: number): object {\n return {\n '.sv': {\n 'increment': delta\n }\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance, Deferred } from '@firebase/util';\n\nimport { repoStartTransaction } from '../core/Repo';\nimport { PRIORITY_INDEX } from '../core/snap/indexes/PriorityIndex';\nimport { Node } from '../core/snap/Node';\nimport { validateWritablePath } from '../core/util/validation';\n\nimport { DatabaseReference } from './Reference';\nimport { DataSnapshot, onValue, ReferenceImpl } from './Reference_impl';\n\n/** An options object to configure transactions. */\nexport interface TransactionOptions {\n /**\n * By default, events are raised each time the transaction update function\n * runs. So if it is run multiple times, you may see intermediate states. You\n * can set this to false to suppress these intermediate states and instead\n * wait until the transaction has completed before events are raised.\n */\n readonly applyLocally?: boolean;\n}\n\n/**\n * A type for the resolve value of {@link runTransaction}.\n */\nexport class TransactionResult {\n /** @hideconstructor */\n constructor(\n /** Whether the transaction was successfully committed. */\n readonly committed: boolean,\n /** The resulting data snapshot. */\n readonly snapshot: DataSnapshot\n ) {}\n\n /** Returns a JSON-serializable representation of this object. */\n toJSON(): object {\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n }\n}\n\n/**\n * Atomically modifies the data at this location.\n *\n * Atomically modify the data at this location. Unlike a normal `set()`, which\n * just overwrites the data regardless of its previous value, `runTransaction()` is\n * used to modify the existing value to a new value, ensuring there are no\n * conflicts with other clients writing to the same location at the same time.\n *\n * To accomplish this, you pass `runTransaction()` an update function which is\n * used to transform the current value into a new value. If another client\n * writes to the location before your new value is successfully written, your\n * update function will be called again with the new current value, and the\n * write will be retried. This will happen repeatedly until your write succeeds\n * without conflict or you abort the transaction by not returning a value from\n * your update function.\n *\n * Note: Modifying data with `set()` will cancel any pending transactions at\n * that location, so extreme care should be taken if mixing `set()` and\n * `runTransaction()` to update the same data.\n *\n * Note: When using transactions with Security and Firebase Rules in place, be\n * aware that a client needs `.read` access in addition to `.write` access in\n * order to perform a transaction. This is because the client-side nature of\n * transactions requires the client to read the data in order to transactionally\n * update it.\n *\n * @param ref - The location to atomically modify.\n * @param transactionUpdate - A developer-supplied function which will be passed\n * the current data stored at this location (as a JavaScript object). The\n * function should return the new value it would like written (as a JavaScript\n * object). If `undefined` is returned (i.e. you return with no arguments) the\n * transaction will be aborted and the data at this location will not be\n * modified.\n * @param options - An options object to configure transactions.\n * @returns A `Promise` that can optionally be used instead of the `onComplete`\n * callback to handle success and failure.\n */\nexport function runTransaction(\n ref: DatabaseReference,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n transactionUpdate: (currentData: any) => unknown,\n options?: TransactionOptions\n): Promise {\n ref = getModularInstance(ref);\n\n validateWritablePath('Reference.transaction', ref._path);\n\n if (ref.key === '.length' || ref.key === '.keys') {\n throw (\n 'Reference.transaction failed: ' + ref.key + ' is a read-only object.'\n );\n }\n\n const applyLocally = options?.applyLocally ?? true;\n const deferred = new Deferred();\n\n const promiseComplete = (\n error: Error | null,\n committed: boolean,\n node: Node | null\n ) => {\n let dataSnapshot: DataSnapshot | null = null;\n if (error) {\n deferred.reject(error);\n } else {\n dataSnapshot = new DataSnapshot(\n node,\n new ReferenceImpl(ref._repo, ref._path),\n PRIORITY_INDEX\n );\n deferred.resolve(new TransactionResult(committed, dataSnapshot));\n }\n };\n\n // Add a watch to make sure we get server updates.\n const unwatcher = onValue(ref, () => {});\n\n repoStartTransaction(\n ref._repo,\n ref._path,\n transactionUpdate,\n promiseComplete,\n unwatcher,\n applyLocally\n );\n\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PersistentConnection } from '../core/PersistentConnection';\nimport { RepoInfo } from '../core/RepoInfo';\nimport { Connection } from '../realtime/Connection';\n\nimport { repoManagerForceRestClient } from './Database';\n\nexport const DataConnection = PersistentConnection;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(PersistentConnection.prototype as any).simpleListen = function (\n pathString: string,\n onComplete: (a: unknown) => void\n) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(PersistentConnection.prototype as any).echo = function (\n data: unknown,\n onEcho: (a: unknown) => void\n) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n\n// RealTimeConnection properties that we use in tests.\nexport const RealTimeConnection = Connection;\n\n/**\n * @internal\n */\nexport const hijackHash = function (newHash: () => string) {\n const oldPut = PersistentConnection.prototype.put;\n PersistentConnection.prototype.put = function (\n pathString,\n data,\n onComplete,\n hash\n ) {\n if (hash !== undefined) {\n hash = newHash();\n }\n oldPut.call(this, pathString, data, onComplete, hash);\n };\n return function () {\n PersistentConnection.prototype.put = oldPut;\n };\n};\n\nexport const ConnectionTarget = RepoInfo;\n\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n * @internal\n */\nexport const forceRestClient = function (forceRestClient: boolean) {\n repoManagerForceRestClient(forceRestClient);\n};\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebaseAppCheckInternal,\n AppCheckInternalComponentName\n} from '@firebase/app-check-interop-types';\nimport { FirebaseApp } from '@firebase/app-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n Provider\n} from '@firebase/component';\n\nimport { repoManagerDatabaseFromApp } from '../api/Database';\nimport { Database } from '../api.standalone';\nimport { setSDKVersion } from '../core/version';\n\n/**\n * Used by console to create a database based on the app,\n * passed database URL and a custom auth implementation.\n * @internal\n * @param app - A valid FirebaseApp-like object\n * @param url - A valid Firebase databaseURL\n * @param version - custom version e.g. firebase-admin version\n * @param customAppCheckImpl - custom app check implementation\n * @param customAuthImpl - custom auth implementation\n */\nexport function _initStandalone({\n app,\n url,\n version,\n customAuthImpl,\n customAppCheckImpl,\n nodeAdmin = false\n}: {\n app: FirebaseApp;\n url: string;\n version: string;\n customAuthImpl: FirebaseAuthInternal;\n customAppCheckImpl?: FirebaseAppCheckInternal;\n nodeAdmin?: boolean;\n}): Database {\n setSDKVersion(version);\n\n /**\n * ComponentContainer('database-standalone') is just a placeholder that doesn't perform\n * any actual function.\n */\n const componentContainer = new ComponentContainer('database-standalone');\n const authProvider = new Provider(\n 'auth-internal',\n componentContainer\n );\n let appCheckProvider: Provider;\n if (customAppCheckImpl) {\n appCheckProvider = new Provider(\n 'app-check-internal',\n componentContainer\n );\n appCheckProvider.setComponent(\n new Component(\n 'app-check-internal',\n () => customAppCheckImpl,\n ComponentType.PRIVATE\n )\n );\n }\n authProvider.setComponent(\n new Component('auth-internal', () => customAuthImpl, ComponentType.PRIVATE)\n );\n\n return repoManagerDatabaseFromApp(\n app,\n authProvider,\n appCheckProvider,\n url,\n nodeAdmin\n );\n}\n","/**\n * Firebase Realtime Database\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Database } from './api/Database';\nimport { registerDatabase } from './register';\n\nexport * from './api';\n\nregisterDatabase();\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'database': Database;\n }\n}\n"],"names":["enableLogging","MAX_NODE","setMaxNode","nodeFromJSON","setPriorityMaxNode","referenceConstructor","errorPrefixFxn","errorPrefix","enableLoggingImpl","SDK_VERSION"],"mappings":";;;;;;;;AAAA;;;;;;;;;;;;;;;AAeG;AAEH;AACO,IAAI,WAAW,GAAG,EAAE,CAAC;AAE5B;;;AAGG;AACG,SAAU,aAAa,CAAC,OAAe,EAAA;IAC3C,WAAW,GAAG,OAAO,CAAC;AACxB;;AC1BA;;;;;;;;;;;;;;;AAeG;AAIH;;;;;;;;AAQG;MACU,iBAAiB,CAAA;AAI5B;;AAEG;AACH,IAAA,WAAA,CAAoB,WAAoB,EAAA;QAApB,IAAW,CAAA,WAAA,GAAX,WAAW,CAAS;;QALhC,IAAO,CAAA,OAAA,GAAG,WAAW,CAAC;KAKc;AAE5C;;;AAGG;IACH,GAAG,CAAC,GAAW,EAAE,KAAqB,EAAA;AACpC,QAAA,IAAI,KAAK,IAAI,IAAI,EAAE;AACjB,YAAA,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC;SACtD;aAAM;AACL,Y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AAC,OAAO,CAAC,CAAC;AAEvB;;;AAGG;AACH,IAAA,MAAM,kBAAkB,GAAG,IAAI,kBAAkB,CAAC,qBAAqB,CAAC,CAAC;IACzE,MAAM,YAAY,GAAG,IAAI,QAAQ,CAC/B,eAAe,EACf,kBAAkB,CACnB,CAAC;AACF,IAAA,IAAI,gBAAyD,CAAC;IAC9D,IAAI,kBAAkB,EAAE;QACtB,gBAAgB,GAAG,IAAI,QAAQ,CAC7B,oBAAoB,EACpB,kBAAkB,CACnB,CAAC;AACF,QAAA,gBAAgB,CAAC,YAAY,CAC3B,IAAI,SAAS,CACX,oBAAoB,EACpB,MAAM,kBAAkB,EAAA,SAAA,6BAEzB,CACF,CAAC;KACH;AACD,IAAA,YAAY,CAAC,YAAY,CACvB,IAAI,SAAS,CAAC,eAAe,EAAE,MAAM,cAAc,EAAA,SAAA,6BAAwB,CAC5E,CAAC;AAEF,IAAA,OAAO,0BAA0B,CAC/B,GAAG,EACH,YAAY,EACZ,gBAAgB,EAChB,GAAG,EACH,SAAS,CACV,CAAC;AACJ;;AClGA;;;;AAIG;AAwBH,gBAAgB,EAAE;;;;"} \ No newline at end of file diff --git a/node_modules/@firebase/database/dist/index.node.cjs.js b/node_modules/@firebase/database/dist/index.node.cjs.js new file mode 100644 index 0000000..5819a33 --- /dev/null +++ b/node_modules/@firebase/database/dist/index.node.cjs.js @@ -0,0 +1,14109 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var Websocket = require('faye-websocket'); +var util = require('@firebase/util'); +var logger$1 = require('@firebase/logger'); +var app = require('@firebase/app'); +var component = require('@firebase/component'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var Websocket__default = /*#__PURE__*/_interopDefaultLegacy(Websocket); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const PROTOCOL_VERSION = '5'; +const VERSION_PARAM = 'v'; +const TRANSPORT_SESSION_PARAM = 's'; +const REFERER_PARAM = 'r'; +const FORGE_REF = 'f'; +// Matches console.firebase.google.com, firebase-console-*.corp.google.com and +// firebase.corp.google.com +const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/; +const LAST_SESSION_PARAM = 'ls'; +const APPLICATION_ID_PARAM = 'p'; +const APP_CHECK_TOKEN_PARAM = 'ac'; +const WEBSOCKET = 'websocket'; +const LONG_POLLING = 'long_polling'; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Wraps a DOM Storage object and: + * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types. + * - prefixes names with "firebase:" to avoid collisions with app data. + * + * We automatically (see storage.js) create two such wrappers, one for sessionStorage, + * and one for localStorage. + * + */ +class DOMStorageWrapper { + /** + * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage) + */ + constructor(domStorage_) { + this.domStorage_ = domStorage_; + // Use a prefix to avoid collisions with other stuff saved by the app. + this.prefix_ = 'firebase:'; + } + /** + * @param key - The key to save the value under + * @param value - The value being stored, or null to remove the key. + */ + set(key, value) { + if (value == null) { + this.domStorage_.removeItem(this.prefixedName_(key)); + } + else { + this.domStorage_.setItem(this.prefixedName_(key), util.stringify(value)); + } + } + /** + * @returns The value that was stored under this key, or null + */ + get(key) { + const storedVal = this.domStorage_.getItem(this.prefixedName_(key)); + if (storedVal == null) { + return null; + } + else { + return util.jsonEval(storedVal); + } + } + remove(key) { + this.domStorage_.removeItem(this.prefixedName_(key)); + } + prefixedName_(name) { + return this.prefix_ + name; + } + toString() { + return this.domStorage_.toString(); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory storage implementation that matches the API of DOMStorageWrapper + * (TODO: create interface for both to implement). + */ +class MemoryStorage { + constructor() { + this.cache_ = {}; + this.isInMemoryStorage = true; + } + set(key, value) { + if (value == null) { + delete this.cache_[key]; + } + else { + this.cache_[key] = value; + } + } + get(key) { + if (util.contains(this.cache_, key)) { + return this.cache_[key]; + } + return null; + } + remove(key) { + delete this.cache_[key]; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage. + * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change + * to reflect this type + * + * @param domStorageName - Name of the underlying storage object + * (e.g. 'localStorage' or 'sessionStorage'). + * @returns Turning off type information until a common interface is defined. + */ +const createStoragefor = function (domStorageName) { + try { + // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception, + // so it must be inside the try/catch. + if (typeof window !== 'undefined' && + typeof window[domStorageName] !== 'undefined') { + // Need to test cache. Just because it's here doesn't mean it works + const domStorage = window[domStorageName]; + domStorage.setItem('firebase:sentinel', 'cache'); + domStorage.removeItem('firebase:sentinel'); + return new DOMStorageWrapper(domStorage); + } + } + catch (e) { } + // Failed to create wrapper. Just return in-memory storage. + // TODO: log? + return new MemoryStorage(); +}; +/** A storage object that lasts across sessions */ +const PersistentStorage = createStoragefor('localStorage'); +/** A storage object that only lasts one session */ +const SessionStorage = createStoragefor('sessionStorage'); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const logClient = new logger$1.Logger('@firebase/database'); +/** + * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called). + */ +const LUIDGenerator = (function () { + let id = 1; + return function () { + return id++; + }; +})(); +/** + * Sha1 hash of the input string + * @param str - The string to hash + * @returns {!string} The resulting hash + */ +const sha1 = function (str) { + const utf8Bytes = util.stringToByteArray(str); + const sha1 = new util.Sha1(); + sha1.update(utf8Bytes); + const sha1Bytes = sha1.digest(); + return util.base64.encodeByteArray(sha1Bytes); +}; +const buildLogMessage_ = function (...varArgs) { + let message = ''; + for (let i = 0; i < varArgs.length; i++) { + const arg = varArgs[i]; + if (Array.isArray(arg) || + (arg && + typeof arg === 'object' && + // eslint-disable-next-line @typescript-eslint/no-explicit-any + typeof arg.length === 'number')) { + message += buildLogMessage_.apply(null, arg); + } + else if (typeof arg === 'object') { + message += util.stringify(arg); + } + else { + message += arg; + } + message += ' '; + } + return message; +}; +/** + * Use this for all debug messages in Firebase. + */ +let logger = null; +/** + * Flag to check for log availability on first log message + */ +let firstLog_ = true; +/** + * The implementation of Firebase.enableLogging (defined here to break dependencies) + * @param logger_ - A flag to turn on logging, or a custom logger + * @param persistent - Whether or not to persist logging settings across refreshes + */ +const enableLogging$1 = function (logger_, persistent) { + util.assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently."); + if (logger_ === true) { + logClient.logLevel = logger$1.LogLevel.VERBOSE; + logger = logClient.log.bind(logClient); + if (persistent) { + SessionStorage.set('logging_enabled', true); + } + } + else if (typeof logger_ === 'function') { + logger = logger_; + } + else { + logger = null; + SessionStorage.remove('logging_enabled'); + } +}; +const log = function (...varArgs) { + if (firstLog_ === true) { + firstLog_ = false; + if (logger === null && SessionStorage.get('logging_enabled') === true) { + enableLogging$1(true); + } + } + if (logger) { + const message = buildLogMessage_.apply(null, varArgs); + logger(message); + } +}; +const logWrapper = function (prefix) { + return function (...varArgs) { + log(prefix, ...varArgs); + }; +}; +const error = function (...varArgs) { + const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs); + logClient.error(message); +}; +const fatal = function (...varArgs) { + const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`; + logClient.error(message); + throw new Error(message); +}; +const warn = function (...varArgs) { + const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs); + logClient.warn(message); +}; +/** + * Logs a warning if the containing page uses https. Called when a call to new Firebase + * does not use https. + */ +const warnIfPageIsSecure = function () { + // Be very careful accessing browser globals. Who knows what may or may not exist. + if (typeof window !== 'undefined' && + window.location && + window.location.protocol && + window.location.protocol.indexOf('https:') !== -1) { + warn('Insecure Firebase access from a secure page. ' + + 'Please use https in calls to new Firebase().'); + } +}; +/** + * Returns true if data is NaN, or +/- Infinity. + */ +const isInvalidJSONNumber = function (data) { + return (typeof data === 'number' && + (data !== data || // NaN + data === Number.POSITIVE_INFINITY || + data === Number.NEGATIVE_INFINITY)); +}; +const executeWhenDOMReady = function (fn) { + if (util.isNodeSdk() || document.readyState === 'complete') { + fn(); + } + else { + // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which + // fire before onload), but fall back to onload. + let called = false; + const wrappedFn = function () { + if (!document.body) { + setTimeout(wrappedFn, Math.floor(10)); + return; + } + if (!called) { + called = true; + fn(); + } + }; + if (document.addEventListener) { + document.addEventListener('DOMContentLoaded', wrappedFn, false); + // fallback to onload. + window.addEventListener('load', wrappedFn, false); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (document.attachEvent) { + // IE. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + document.attachEvent('onreadystatechange', () => { + if (document.readyState === 'complete') { + wrappedFn(); + } + }); + // fallback to onload. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + window.attachEvent('onload', wrappedFn); + // jQuery has an extra hack for IE that we could employ (based on + // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old. + // I'm hoping we don't need it. + } + } +}; +/** + * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names + */ +const MIN_NAME = '[MIN_NAME]'; +/** + * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names + */ +const MAX_NAME = '[MAX_NAME]'; +/** + * Compares valid Firebase key names, plus min and max name + */ +const nameCompare = function (a, b) { + if (a === b) { + return 0; + } + else if (a === MIN_NAME || b === MAX_NAME) { + return -1; + } + else if (b === MIN_NAME || a === MAX_NAME) { + return 1; + } + else { + const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b); + if (aAsInt !== null) { + if (bAsInt !== null) { + return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt; + } + else { + return -1; + } + } + else if (bAsInt !== null) { + return 1; + } + else { + return a < b ? -1 : 1; + } + } +}; +/** + * @returns {!number} comparison result. + */ +const stringCompare = function (a, b) { + if (a === b) { + return 0; + } + else if (a < b) { + return -1; + } + else { + return 1; + } +}; +const requireKey = function (key, obj) { + if (obj && key in obj) { + return obj[key]; + } + else { + throw new Error('Missing required key (' + key + ') in object: ' + util.stringify(obj)); + } +}; +const ObjectToUniqueKey = function (obj) { + if (typeof obj !== 'object' || obj === null) { + return util.stringify(obj); + } + const keys = []; + // eslint-disable-next-line guard-for-in + for (const k in obj) { + keys.push(k); + } + // Export as json, but with the keys sorted. + keys.sort(); + let key = '{'; + for (let i = 0; i < keys.length; i++) { + if (i !== 0) { + key += ','; + } + key += util.stringify(keys[i]); + key += ':'; + key += ObjectToUniqueKey(obj[keys[i]]); + } + key += '}'; + return key; +}; +/** + * Splits a string into a number of smaller segments of maximum size + * @param str - The string + * @param segsize - The maximum number of chars in the string. + * @returns The string, split into appropriately-sized chunks + */ +const splitStringBySize = function (str, segsize) { + const len = str.length; + if (len <= segsize) { + return [str]; + } + const dataSegs = []; + for (let c = 0; c < len; c += segsize) { + if (c + segsize > len) { + dataSegs.push(str.substring(c, len)); + } + else { + dataSegs.push(str.substring(c, c + segsize)); + } + } + return dataSegs; +}; +/** + * Apply a function to each (key, value) pair in an object or + * apply a function to each (index, value) pair in an array + * @param obj - The object or array to iterate over + * @param fn - The function to apply + */ +function each(obj, fn) { + for (const key in obj) { + if (obj.hasOwnProperty(key)) { + fn(key, obj[key]); + } + } +} +/** + * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License) + * I made one modification at the end and removed the NaN / Infinity + * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments. + * @param v - A double + * + */ +const doubleToIEEE754String = function (v) { + util.assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL + const ebits = 11, fbits = 52; + const bias = (1 << (ebits - 1)) - 1; + let s, e, f, ln, i; + // Compute sign, exponent, fraction + // Skip NaN / Infinity handling --MJL. + if (v === 0) { + e = 0; + f = 0; + s = 1 / v === -Infinity ? 1 : 0; + } + else { + s = v < 0; + v = Math.abs(v); + if (v >= Math.pow(2, 1 - bias)) { + // Normalized + ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias); + e = ln + bias; + f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits)); + } + else { + // Denormalized + e = 0; + f = Math.round(v / Math.pow(2, 1 - bias - fbits)); + } + } + // Pack sign, exponent, fraction + const bits = []; + for (i = fbits; i; i -= 1) { + bits.push(f % 2 ? 1 : 0); + f = Math.floor(f / 2); + } + for (i = ebits; i; i -= 1) { + bits.push(e % 2 ? 1 : 0); + e = Math.floor(e / 2); + } + bits.push(s ? 1 : 0); + bits.reverse(); + const str = bits.join(''); + // Return the data as a hex string. --MJL + let hexByteString = ''; + for (i = 0; i < 64; i += 8) { + let hexByte = parseInt(str.substr(i, 8), 2).toString(16); + if (hexByte.length === 1) { + hexByte = '0' + hexByte; + } + hexByteString = hexByteString + hexByte; + } + return hexByteString.toLowerCase(); +}; +/** + * Used to detect if we're in a Chrome content script (which executes in an + * isolated environment where long-polling doesn't work). + */ +const isChromeExtensionContentScript = function () { + return !!(typeof window === 'object' && + window['chrome'] && + window['chrome']['extension'] && + !/^chrome/.test(window.location.href)); +}; +/** + * Used to detect if we're in a Windows 8 Store app. + */ +const isWindowsStoreApp = function () { + // Check for the presence of a couple WinRT globals + return typeof Windows === 'object' && typeof Windows.UI === 'object'; +}; +/** + * Converts a server error code to a JavaScript Error + */ +function errorForServerCode(code, query) { + let reason = 'Unknown Error'; + if (code === 'too_big') { + reason = + 'The data requested exceeds the maximum size ' + + 'that can be accessed with a single request.'; + } + else if (code === 'permission_denied') { + reason = "Client doesn't have permission to access the desired data."; + } + else if (code === 'unavailable') { + reason = 'The service is unavailable'; + } + const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error.code = code.toUpperCase(); + return error; +} +/** + * Used to test for integer-looking strings + */ +const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$'); +/** + * For use in keys, the minimum possible 32-bit integer. + */ +const INTEGER_32_MIN = -2147483648; +/** + * For use in keys, the maximum possible 32-bit integer. + */ +const INTEGER_32_MAX = 2147483647; +/** + * If the string contains a 32-bit integer, return it. Else return null. + */ +const tryParseInt = function (str) { + if (INTEGER_REGEXP_.test(str)) { + const intVal = Number(str); + if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) { + return intVal; + } + } + return null; +}; +/** + * Helper to run some code but catch any exceptions and re-throw them later. + * Useful for preventing user callbacks from breaking internal code. + * + * Re-throwing the exception from a setTimeout is a little evil, but it's very + * convenient (we don't have to try to figure out when is a safe point to + * re-throw it), and the behavior seems reasonable: + * + * * If you aren't pausing on exceptions, you get an error in the console with + * the correct stack trace. + * * If you're pausing on all exceptions, the debugger will pause on your + * exception and then again when we rethrow it. + * * If you're only pausing on uncaught exceptions, the debugger will only pause + * on us re-throwing it. + * + * @param fn - The code to guard. + */ +const exceptionGuard = function (fn) { + try { + fn(); + } + catch (e) { + // Re-throw exception when it's safe. + setTimeout(() => { + // It used to be that "throw e" would result in a good console error with + // relevant context, but as of Chrome 39, you just get the firebase.js + // file/line number where we re-throw it, which is useless. So we log + // e.stack explicitly. + const stack = e.stack || ''; + warn('Exception was thrown by user callback.', stack); + throw e; + }, Math.floor(0)); + } +}; +/** + * @returns {boolean} true if we think we're currently being crawled. + */ +const beingCrawled = function () { + const userAgent = (typeof window === 'object' && + window['navigator'] && + window['navigator']['userAgent']) || + ''; + // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we + // believe to support JavaScript/AJAX rendering. + // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website + // would have seen the page" is flaky if we don't treat it as a crawler. + return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0); +}; +/** + * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting. + * + * It is removed with clearTimeout() as normal. + * + * @param fn - Function to run. + * @param time - Milliseconds to wait before running. + * @returns The setTimeout() return value. + */ +const setTimeoutNonBlocking = function (fn, time) { + const timeout = setTimeout(fn, time); + // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API. + if (typeof timeout === 'number' && + // @ts-ignore Is only defined in Deno environments. + typeof Deno !== 'undefined' && + // @ts-ignore Deno and unrefTimer are only defined in Deno environments. + Deno['unrefTimer']) { + // @ts-ignore Deno and unrefTimer are only defined in Deno environments. + Deno.unrefTimer(timeout); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (typeof timeout === 'object' && timeout['unref']) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + timeout['unref'](); + } + return timeout; +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A class that holds metadata about a Repo object + */ +class RepoInfo { + /** + * @param host - Hostname portion of the url for the repo + * @param secure - Whether or not this repo is accessed over ssl + * @param namespace - The namespace represented by the repo + * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest). + * @param nodeAdmin - Whether this instance uses Admin SDK credentials + * @param persistenceKey - Override the default session persistence storage key + */ + constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false, isUsingEmulator = false, emulatorOptions = null) { + this.secure = secure; + this.namespace = namespace; + this.webSocketOnly = webSocketOnly; + this.nodeAdmin = nodeAdmin; + this.persistenceKey = persistenceKey; + this.includeNamespaceInQueryParams = includeNamespaceInQueryParams; + this.isUsingEmulator = isUsingEmulator; + this.emulatorOptions = emulatorOptions; + this._host = host.toLowerCase(); + this._domain = this._host.substr(this._host.indexOf('.') + 1); + this.internalHost = + PersistentStorage.get('host:' + host) || this._host; + } + isCacheableHost() { + return this.internalHost.substr(0, 2) === 's-'; + } + isCustomHost() { + return (this._domain !== 'firebaseio.com' && + this._domain !== 'firebaseio-demo.com'); + } + get host() { + return this._host; + } + set host(newHost) { + if (newHost !== this.internalHost) { + this.internalHost = newHost; + if (this.isCacheableHost()) { + PersistentStorage.set('host:' + this._host, this.internalHost); + } + } + } + toString() { + let str = this.toURLString(); + if (this.persistenceKey) { + str += '<' + this.persistenceKey + '>'; + } + return str; + } + toURLString() { + const protocol = this.secure ? 'https://' : 'http://'; + const query = this.includeNamespaceInQueryParams + ? `?ns=${this.namespace}` + : ''; + return `${protocol}${this.host}/${query}`; + } +} +function repoInfoNeedsQueryParam(repoInfo) { + return (repoInfo.host !== repoInfo.internalHost || + repoInfo.isCustomHost() || + repoInfo.includeNamespaceInQueryParams); +} +/** + * Returns the websocket URL for this repo + * @param repoInfo - RepoInfo object + * @param type - of connection + * @param params - list + * @returns The URL for this repo + */ +function repoInfoConnectionURL(repoInfo, type, params) { + util.assert(typeof type === 'string', 'typeof type must == string'); + util.assert(typeof params === 'object', 'typeof params must == object'); + let connURL; + if (type === WEBSOCKET) { + connURL = + (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?'; + } + else if (type === LONG_POLLING) { + connURL = + (repoInfo.secure ? 'https://' : 'http://') + + repoInfo.internalHost + + '/.lp?'; + } + else { + throw new Error('Unknown connection type: ' + type); + } + if (repoInfoNeedsQueryParam(repoInfo)) { + params['ns'] = repoInfo.namespace; + } + const pairs = []; + each(params, (key, value) => { + pairs.push(key + '=' + value); + }); + return connURL + pairs.join('&'); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Tracks a collection of stats. + */ +class StatsCollection { + constructor() { + this.counters_ = {}; + } + incrementCounter(name, amount = 1) { + if (!util.contains(this.counters_, name)) { + this.counters_[name] = 0; + } + this.counters_[name] += amount; + } + get() { + return util.deepCopy(this.counters_); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const collections = {}; +const reporters = {}; +function statsManagerGetCollection(repoInfo) { + const hashString = repoInfo.toString(); + if (!collections[hashString]) { + collections[hashString] = new StatsCollection(); + } + return collections[hashString]; +} +function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) { + const hashString = repoInfo.toString(); + if (!reporters[hashString]) { + reporters[hashString] = creatorFunction(); + } + return reporters[hashString]; +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The semver (www.semver.org) version of the SDK. */ +let SDK_VERSION = ''; +/** + * SDK_VERSION should be set before any database instance is created + * @internal + */ +function setSDKVersion(version) { + SDK_VERSION = version; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const WEBSOCKET_MAX_FRAME_SIZE = 16384; +const WEBSOCKET_KEEPALIVE_INTERVAL = 45000; +let WebSocketImpl = null; +if (typeof MozWebSocket !== 'undefined') { + WebSocketImpl = MozWebSocket; +} +else if (typeof WebSocket !== 'undefined') { + WebSocketImpl = WebSocket; +} +function setWebSocketImpl(impl) { + WebSocketImpl = impl; +} +/** + * Create a new websocket connection with the given callbacks. + */ +class WebSocketConnection { + /** + * @param connId identifier for this transport + * @param repoInfo The info for the websocket endpoint. + * @param applicationId The Firebase App ID for this project. + * @param appCheckToken The App Check Token for this client. + * @param authToken The Auth Token for this client. + * @param transportSessionId Optional transportSessionId if this is connecting + * to an existing transport session + * @param lastSessionId Optional lastSessionId if there was a previous + * connection + */ + constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) { + this.connId = connId; + this.applicationId = applicationId; + this.appCheckToken = appCheckToken; + this.authToken = authToken; + this.keepaliveTimer = null; + this.frames = null; + this.totalFrames = 0; + this.bytesSent = 0; + this.bytesReceived = 0; + this.log_ = logWrapper(this.connId); + this.stats_ = statsManagerGetCollection(repoInfo); + this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId); + this.nodeAdmin = repoInfo.nodeAdmin; + } + /** + * @param repoInfo - The info for the websocket endpoint. + * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport + * session + * @param lastSessionId - Optional lastSessionId if there was a previous connection + * @returns connection url + */ + static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) { + const urlParams = {}; + urlParams[VERSION_PARAM] = PROTOCOL_VERSION; + if (!util.isNodeSdk() && + typeof location !== 'undefined' && + location.hostname && + FORGE_DOMAIN_RE.test(location.hostname)) { + urlParams[REFERER_PARAM] = FORGE_REF; + } + if (transportSessionId) { + urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId; + } + if (lastSessionId) { + urlParams[LAST_SESSION_PARAM] = lastSessionId; + } + if (appCheckToken) { + urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken; + } + if (applicationId) { + urlParams[APPLICATION_ID_PARAM] = applicationId; + } + return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams); + } + /** + * @param onMessage - Callback when messages arrive + * @param onDisconnect - Callback with connection lost. + */ + open(onMessage, onDisconnect) { + this.onDisconnect = onDisconnect; + this.onMessage = onMessage; + this.log_('Websocket connecting to ' + this.connURL); + this.everConnected_ = false; + // Assume failure until proven otherwise. + PersistentStorage.set('previous_websocket_failure', true); + try { + let options; + if (util.isNodeSdk()) { + const device = this.nodeAdmin ? 'AdminNode' : 'Node'; + // UA Format: Firebase//// + options = { + headers: { + 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`, + 'X-Firebase-GMPID': this.applicationId || '' + } + }; + // If using Node with admin creds, AppCheck-related checks are unnecessary. + // Note that we send the credentials here even if they aren't admin credentials, which is + // not a problem. + // Note that this header is just used to bypass appcheck, and the token should still be sent + // through the websocket connection once it is established. + if (this.authToken) { + options.headers['Authorization'] = `Bearer ${this.authToken}`; + } + if (this.appCheckToken) { + options.headers['X-Firebase-AppCheck'] = this.appCheckToken; + } + // Plumb appropriate http_proxy environment variable into faye-websocket if it exists. + const env = process['env']; + const proxy = this.connURL.indexOf('wss://') === 0 + ? env['HTTPS_PROXY'] || env['https_proxy'] + : env['HTTP_PROXY'] || env['http_proxy']; + if (proxy) { + options['proxy'] = { origin: proxy }; + } + } + this.mySock = new WebSocketImpl(this.connURL, [], options); + } + catch (e) { + this.log_('Error instantiating WebSocket.'); + const error = e.message || e.data; + if (error) { + this.log_(error); + } + this.onClosed_(); + return; + } + this.mySock.onopen = () => { + this.log_('Websocket connected.'); + this.everConnected_ = true; + }; + this.mySock.onclose = () => { + this.log_('Websocket connection was disconnected.'); + this.mySock = null; + this.onClosed_(); + }; + this.mySock.onmessage = m => { + this.handleIncomingFrame(m); + }; + this.mySock.onerror = e => { + this.log_('WebSocket error. Closing connection.'); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const error = e.message || e.data; + if (error) { + this.log_(error); + } + this.onClosed_(); + }; + } + /** + * No-op for websockets, we don't need to do anything once the connection is confirmed as open + */ + start() { } + static forceDisallow() { + WebSocketConnection.forceDisallow_ = true; + } + static isAvailable() { + let isOldAndroid = false; + if (typeof navigator !== 'undefined' && navigator.userAgent) { + const oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/; + const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex); + if (oldAndroidMatch && oldAndroidMatch.length > 1) { + if (parseFloat(oldAndroidMatch[1]) < 4.4) { + isOldAndroid = true; + } + } + } + return (!isOldAndroid && + WebSocketImpl !== null && + !WebSocketConnection.forceDisallow_); + } + /** + * Returns true if we previously failed to connect with this transport. + */ + static previouslyFailed() { + // If our persistent storage is actually only in-memory storage, + // we default to assuming that it previously failed to be safe. + return (PersistentStorage.isInMemoryStorage || + PersistentStorage.get('previous_websocket_failure') === true); + } + markConnectionHealthy() { + PersistentStorage.remove('previous_websocket_failure'); + } + appendFrame_(data) { + this.frames.push(data); + if (this.frames.length === this.totalFrames) { + const fullMess = this.frames.join(''); + this.frames = null; + const jsonMess = util.jsonEval(fullMess); + //handle the message + this.onMessage(jsonMess); + } + } + /** + * @param frameCount - The number of frames we are expecting from the server + */ + handleNewFrameCount_(frameCount) { + this.totalFrames = frameCount; + this.frames = []; + } + /** + * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1 + * @returns Any remaining data to be process, or null if there is none + */ + extractFrameCount_(data) { + util.assert(this.frames === null, 'We already have a frame buffer'); + // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced + // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508 + if (data.length <= 6) { + const frameCount = Number(data); + if (!isNaN(frameCount)) { + this.handleNewFrameCount_(frameCount); + return null; + } + } + this.handleNewFrameCount_(1); + return data; + } + /** + * Process a websocket frame that has arrived from the server. + * @param mess - The frame data + */ + handleIncomingFrame(mess) { + if (this.mySock === null) { + return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes. + } + const data = mess['data']; + this.bytesReceived += data.length; + this.stats_.incrementCounter('bytes_received', data.length); + this.resetKeepAlive(); + if (this.frames !== null) { + // we're buffering + this.appendFrame_(data); + } + else { + // try to parse out a frame count, otherwise, assume 1 and process it + const remainingData = this.extractFrameCount_(data); + if (remainingData !== null) { + this.appendFrame_(remainingData); + } + } + } + /** + * Send a message to the server + * @param data - The JSON object to transmit + */ + send(data) { + this.resetKeepAlive(); + const dataStr = util.stringify(data); + this.bytesSent += dataStr.length; + this.stats_.incrementCounter('bytes_sent', dataStr.length); + //We can only fit a certain amount in each websocket frame, so we need to split this request + //up into multiple pieces if it doesn't fit in one request. + const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE); + //Send the length header + if (dataSegs.length > 1) { + this.sendString_(String(dataSegs.length)); + } + //Send the actual data in segments. + for (let i = 0; i < dataSegs.length; i++) { + this.sendString_(dataSegs[i]); + } + } + shutdown_() { + this.isClosed_ = true; + if (this.keepaliveTimer) { + clearInterval(this.keepaliveTimer); + this.keepaliveTimer = null; + } + if (this.mySock) { + this.mySock.close(); + this.mySock = null; + } + } + onClosed_() { + if (!this.isClosed_) { + this.log_('WebSocket is closing itself'); + this.shutdown_(); + // since this is an internal close, trigger the close listener + if (this.onDisconnect) { + this.onDisconnect(this.everConnected_); + this.onDisconnect = null; + } + } + } + /** + * External-facing close handler. + * Close the websocket and kill the connection. + */ + close() { + if (!this.isClosed_) { + this.log_('WebSocket is being closed'); + this.shutdown_(); + } + } + /** + * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after + * the last activity. + */ + resetKeepAlive() { + clearInterval(this.keepaliveTimer); + this.keepaliveTimer = setInterval(() => { + //If there has been no websocket activity for a while, send a no-op + if (this.mySock) { + this.sendString_('0'); + } + this.resetKeepAlive(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL)); + } + /** + * Send a string over the websocket. + * + * @param str - String to send. + */ + sendString_(str) { + // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send() + // calls for some unknown reason. We treat these as an error and disconnect. + // See https://app.asana.com/0/58926111402292/68021340250410 + try { + this.mySock.send(str); + } + catch (e) { + this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.'); + setTimeout(this.onClosed_.bind(this), 0); + } + } +} +/** + * Number of response before we consider the connection "healthy." + */ +WebSocketConnection.responsesRequiredToBeHealthy = 2; +/** + * Time to wait for the connection te become healthy before giving up. + */ +WebSocketConnection.healthyTimeout = 30000; + +const name = "@firebase/database"; +const version = "1.1.0"; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Abstraction around AppCheck's token fetching capabilities. + */ +class AppCheckTokenProvider { + constructor(app$1, appCheckProvider) { + this.appCheckProvider = appCheckProvider; + this.appName = app$1.name; + if (app._isFirebaseServerApp(app$1) && app$1.settings.appCheckToken) { + this.serverAppAppCheckToken = app$1.settings.appCheckToken; + } + this.appCheck = appCheckProvider?.getImmediate({ optional: true }); + if (!this.appCheck) { + appCheckProvider?.get().then(appCheck => (this.appCheck = appCheck)); + } + } + getToken(forceRefresh) { + if (this.serverAppAppCheckToken) { + if (forceRefresh) { + throw new Error('Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.'); + } + return Promise.resolve({ token: this.serverAppAppCheckToken }); + } + if (!this.appCheck) { + return new Promise((resolve, reject) => { + // Support delayed initialization of FirebaseAppCheck. This allows our + // customers to initialize the RTDB SDK before initializing Firebase + // AppCheck and ensures that all requests are authenticated if a token + // becomes available before the timeout below expires. + setTimeout(() => { + if (this.appCheck) { + this.getToken(forceRefresh).then(resolve, reject); + } + else { + resolve(null); + } + }, 0); + }); + } + return this.appCheck.getToken(forceRefresh); + } + addTokenChangeListener(listener) { + this.appCheckProvider + ?.get() + .then(appCheck => appCheck.addTokenListener(listener)); + } + notifyForInvalidToken() { + warn(`Provided AppCheck credentials for the app named "${this.appName}" ` + + 'are invalid. This usually indicates your app was not initialized correctly.'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Abstraction around FirebaseApp's token fetching capabilities. + */ +class FirebaseAuthTokenProvider { + constructor(appName_, firebaseOptions_, authProvider_) { + this.appName_ = appName_; + this.firebaseOptions_ = firebaseOptions_; + this.authProvider_ = authProvider_; + this.auth_ = null; + this.auth_ = authProvider_.getImmediate({ optional: true }); + if (!this.auth_) { + authProvider_.onInit(auth => (this.auth_ = auth)); + } + } + getToken(forceRefresh) { + if (!this.auth_) { + return new Promise((resolve, reject) => { + // Support delayed initialization of FirebaseAuth. This allows our + // customers to initialize the RTDB SDK before initializing Firebase + // Auth and ensures that all requests are authenticated if a token + // becomes available before the timeout below expires. + setTimeout(() => { + if (this.auth_) { + this.getToken(forceRefresh).then(resolve, reject); + } + else { + resolve(null); + } + }, 0); + }); + } + return this.auth_.getToken(forceRefresh).catch(error => { + // TODO: Need to figure out all the cases this is raised and whether + // this makes sense. + if (error && error.code === 'auth/token-not-initialized') { + log('Got auth/token-not-initialized error. Treating as null token.'); + return null; + } + else { + return Promise.reject(error); + } + }); + } + addTokenChangeListener(listener) { + // TODO: We might want to wrap the listener and call it with no args to + // avoid a leaky abstraction, but that makes removing the listener harder. + if (this.auth_) { + this.auth_.addAuthTokenListener(listener); + } + else { + this.authProvider_ + .get() + .then(auth => auth.addAuthTokenListener(listener)); + } + } + removeTokenChangeListener(listener) { + this.authProvider_ + .get() + .then(auth => auth.removeAuthTokenListener(listener)); + } + notifyForInvalidToken() { + let errorMessage = 'Provided authentication credentials for the app named "' + + this.appName_ + + '" are invalid. This usually indicates your app was not ' + + 'initialized correctly. '; + if ('credential' in this.firebaseOptions_) { + errorMessage += + 'Make sure the "credential" property provided to initializeApp() ' + + 'is authorized to access the specified "databaseURL" and is from the correct ' + + 'project.'; + } + else if ('serviceAccount' in this.firebaseOptions_) { + errorMessage += + 'Make sure the "serviceAccount" property provided to initializeApp() ' + + 'is authorized to access the specified "databaseURL" and is from the correct ' + + 'project.'; + } + else { + errorMessage += + 'Make sure the "apiKey" and "databaseURL" properties provided to ' + + 'initializeApp() match the values provided for your app at ' + + 'https://console.firebase.google.com/.'; + } + warn(errorMessage); + } +} +/* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */ +class EmulatorTokenProvider { + constructor(accessToken) { + this.accessToken = accessToken; + } + getToken(forceRefresh) { + return Promise.resolve({ + accessToken: this.accessToken + }); + } + addTokenChangeListener(listener) { + // Invoke the listener immediately to match the behavior in Firebase Auth + // (see packages/auth/src/auth.js#L1807) + listener(this.accessToken); + } + removeTokenChangeListener(listener) { } + notifyForInvalidToken() { } +} +/** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */ +EmulatorTokenProvider.OWNER = 'owner'; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This class ensures the packets from the server arrive in order + * This class takes data from the server and ensures it gets passed into the callbacks in order. + */ +class PacketReceiver { + /** + * @param onMessage_ + */ + constructor(onMessage_) { + this.onMessage_ = onMessage_; + this.pendingResponses = []; + this.currentResponseNum = 0; + this.closeAfterResponse = -1; + this.onClose = null; + } + closeAfter(responseNum, callback) { + this.closeAfterResponse = responseNum; + this.onClose = callback; + if (this.closeAfterResponse < this.currentResponseNum) { + this.onClose(); + this.onClose = null; + } + } + /** + * Each message from the server comes with a response number, and an array of data. The responseNumber + * allows us to ensure that we process them in the right order, since we can't be guaranteed that all + * browsers will respond in the same order as the requests we sent + */ + handleResponse(requestNum, data) { + this.pendingResponses[requestNum] = data; + while (this.pendingResponses[this.currentResponseNum]) { + const toProcess = this.pendingResponses[this.currentResponseNum]; + delete this.pendingResponses[this.currentResponseNum]; + for (let i = 0; i < toProcess.length; ++i) { + if (toProcess[i]) { + exceptionGuard(() => { + this.onMessage_(toProcess[i]); + }); + } + } + if (this.currentResponseNum === this.closeAfterResponse) { + if (this.onClose) { + this.onClose(); + this.onClose = null; + } + break; + } + this.currentResponseNum++; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// URL query parameters associated with longpolling +const FIREBASE_LONGPOLL_START_PARAM = 'start'; +const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close'; +const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand'; +const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB'; +const FIREBASE_LONGPOLL_ID_PARAM = 'id'; +const FIREBASE_LONGPOLL_PW_PARAM = 'pw'; +const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser'; +const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb'; +const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg'; +const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts'; +const FIREBASE_LONGPOLL_DATA_PARAM = 'd'; +const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe'; +//Data size constants. +//TODO: Perf: the maximum length actually differs from browser to browser. +// We should check what browser we're on and set accordingly. +const MAX_URL_DATA_SIZE = 1870; +const SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d= +const MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE; +/** + * Keepalive period + * send a fresh request at minimum every 25 seconds. Opera has a maximum request + * length of 30 seconds that we can't exceed. + */ +const KEEPALIVE_REQUEST_INTERVAL = 25000; +/** + * How long to wait before aborting a long-polling connection attempt. + */ +const LP_CONNECT_TIMEOUT = 30000; +/** + * This class manages a single long-polling connection. + */ +class BrowserPollConnection { + /** + * @param connId An identifier for this connection, used for logging + * @param repoInfo The info for the endpoint to send data to. + * @param applicationId The Firebase App ID for this project. + * @param appCheckToken The AppCheck token for this client. + * @param authToken The AuthToken to use for this connection. + * @param transportSessionId Optional transportSessionid if we are + * reconnecting for an existing transport session + * @param lastSessionId Optional lastSessionId if the PersistentConnection has + * already created a connection previously + */ + constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) { + this.connId = connId; + this.repoInfo = repoInfo; + this.applicationId = applicationId; + this.appCheckToken = appCheckToken; + this.authToken = authToken; + this.transportSessionId = transportSessionId; + this.lastSessionId = lastSessionId; + this.bytesSent = 0; + this.bytesReceived = 0; + this.everConnected_ = false; + this.log_ = logWrapper(connId); + this.stats_ = statsManagerGetCollection(repoInfo); + this.urlFn = (params) => { + // Always add the token if we have one. + if (this.appCheckToken) { + params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken; + } + return repoInfoConnectionURL(repoInfo, LONG_POLLING, params); + }; + } + /** + * @param onMessage - Callback when messages arrive + * @param onDisconnect - Callback with connection lost. + */ + open(onMessage, onDisconnect) { + this.curSegmentNum = 0; + this.onDisconnect_ = onDisconnect; + this.myPacketOrderer = new PacketReceiver(onMessage); + this.isClosed_ = false; + this.connectTimeoutTimer_ = setTimeout(() => { + this.log_('Timed out trying to connect.'); + // Make sure we clear the host cache + this.onClosed_(); + this.connectTimeoutTimer_ = null; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(LP_CONNECT_TIMEOUT)); + // Ensure we delay the creation of the iframe until the DOM is loaded. + executeWhenDOMReady(() => { + if (this.isClosed_) { + return; + } + //Set up a callback that gets triggered once a connection is set up. + this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => { + const [command, arg1, arg2, arg3, arg4] = args; + this.incrementIncomingBytes_(args); + if (!this.scriptTagHolder) { + return; // we closed the connection. + } + if (this.connectTimeoutTimer_) { + clearTimeout(this.connectTimeoutTimer_); + this.connectTimeoutTimer_ = null; + } + this.everConnected_ = true; + if (command === FIREBASE_LONGPOLL_START_PARAM) { + this.id = arg1; + this.password = arg2; + } + else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) { + // Don't clear the host cache. We got a response from the server, so we know it's reachable + if (arg1) { + // We aren't expecting any more data (other than what the server's already in the process of sending us + // through our already open polls), so don't send any more. + this.scriptTagHolder.sendNewPolls = false; + // arg1 in this case is the last response number sent by the server. We should try to receive + // all of the responses up to this one before closing + this.myPacketOrderer.closeAfter(arg1, () => { + this.onClosed_(); + }); + } + else { + this.onClosed_(); + } + } + else { + throw new Error('Unrecognized command received: ' + command); + } + }, (...args) => { + const [pN, data] = args; + this.incrementIncomingBytes_(args); + this.myPacketOrderer.handleResponse(pN, data); + }, () => { + this.onClosed_(); + }, this.urlFn); + //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results + //from cache. + const urlParams = {}; + urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't'; + urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000); + if (this.scriptTagHolder.uniqueCallbackIdentifier) { + urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = + this.scriptTagHolder.uniqueCallbackIdentifier; + } + urlParams[VERSION_PARAM] = PROTOCOL_VERSION; + if (this.transportSessionId) { + urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId; + } + if (this.lastSessionId) { + urlParams[LAST_SESSION_PARAM] = this.lastSessionId; + } + if (this.applicationId) { + urlParams[APPLICATION_ID_PARAM] = this.applicationId; + } + if (this.appCheckToken) { + urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken; + } + if (typeof location !== 'undefined' && + location.hostname && + FORGE_DOMAIN_RE.test(location.hostname)) { + urlParams[REFERER_PARAM] = FORGE_REF; + } + const connectURL = this.urlFn(urlParams); + this.log_('Connecting via long-poll to ' + connectURL); + this.scriptTagHolder.addTag(connectURL, () => { + /* do nothing */ + }); + }); + } + /** + * Call this when a handshake has completed successfully and we want to consider the connection established + */ + start() { + this.scriptTagHolder.startLongPoll(this.id, this.password); + this.addDisconnectPingFrame(this.id, this.password); + } + /** + * Forces long polling to be considered as a potential transport + */ + static forceAllow() { + BrowserPollConnection.forceAllow_ = true; + } + /** + * Forces longpolling to not be considered as a potential transport + */ + static forceDisallow() { + BrowserPollConnection.forceDisallow_ = true; + } + // Static method, use string literal so it can be accessed in a generic way + static isAvailable() { + if (util.isNodeSdk()) { + return false; + } + else if (BrowserPollConnection.forceAllow_) { + return true; + } + else { + // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in + // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08). + return (!BrowserPollConnection.forceDisallow_ && + typeof document !== 'undefined' && + document.createElement != null && + !isChromeExtensionContentScript() && + !isWindowsStoreApp()); + } + } + /** + * No-op for polling + */ + markConnectionHealthy() { } + /** + * Stops polling and cleans up the iframe + */ + shutdown_() { + this.isClosed_ = true; + if (this.scriptTagHolder) { + this.scriptTagHolder.close(); + this.scriptTagHolder = null; + } + //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving. + if (this.myDisconnFrame) { + document.body.removeChild(this.myDisconnFrame); + this.myDisconnFrame = null; + } + if (this.connectTimeoutTimer_) { + clearTimeout(this.connectTimeoutTimer_); + this.connectTimeoutTimer_ = null; + } + } + /** + * Triggered when this transport is closed + */ + onClosed_() { + if (!this.isClosed_) { + this.log_('Longpoll is closing itself'); + this.shutdown_(); + if (this.onDisconnect_) { + this.onDisconnect_(this.everConnected_); + this.onDisconnect_ = null; + } + } + } + /** + * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server + * that we've left. + */ + close() { + if (!this.isClosed_) { + this.log_('Longpoll is being closed.'); + this.shutdown_(); + } + } + /** + * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then + * broken into chunks (since URLs have a small maximum length). + * @param data - The JSON data to transmit. + */ + send(data) { + const dataStr = util.stringify(data); + this.bytesSent += dataStr.length; + this.stats_.incrementCounter('bytes_sent', dataStr.length); + //first, lets get the base64-encoded data + const base64data = util.base64Encode(dataStr); + //We can only fit a certain amount in each URL, so we need to split this request + //up into multiple pieces if it doesn't fit in one request. + const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE); + //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number + //of segments so that we can reassemble the packet on the server. + for (let i = 0; i < dataSegs.length; i++) { + this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]); + this.curSegmentNum++; + } + } + /** + * This is how we notify the server that we're leaving. + * We aren't able to send requests with DHTML on a window close event, but we can + * trigger XHR requests in some browsers (everything but Opera basically). + */ + addDisconnectPingFrame(id, pw) { + if (util.isNodeSdk()) { + return; + } + this.myDisconnFrame = document.createElement('iframe'); + const urlParams = {}; + urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't'; + urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id; + urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw; + this.myDisconnFrame.src = this.urlFn(urlParams); + this.myDisconnFrame.style.display = 'none'; + document.body.appendChild(this.myDisconnFrame); + } + /** + * Used to track the bytes received by this client + */ + incrementIncomingBytes_(args) { + // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in. + const bytesReceived = util.stringify(args).length; + this.bytesReceived += bytesReceived; + this.stats_.incrementCounter('bytes_received', bytesReceived); + } +} +/********************************************************************************************* + * A wrapper around an iframe that is used as a long-polling script holder. + *********************************************************************************************/ +class FirebaseIFrameScriptHolder { + /** + * @param commandCB - The callback to be called when control commands are received from the server. + * @param onMessageCB - The callback to be triggered when responses arrive from the server. + * @param onDisconnect - The callback to be triggered when this tag holder is closed + * @param urlFn - A function that provides the URL of the endpoint to send data to. + */ + constructor(commandCB, onMessageCB, onDisconnect, urlFn) { + this.onDisconnect = onDisconnect; + this.urlFn = urlFn; + //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause + //problems in some browsers. + this.outstandingRequests = new Set(); + //A queue of the pending segments waiting for transmission to the server. + this.pendingSegs = []; + //A serial number. We use this for two things: + // 1) A way to ensure the browser doesn't cache responses to polls + // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The + // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute + // JSONP code in the order it was added to the iframe. + this.currentSerial = Math.floor(Math.random() * 100000000); + // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still + // incoming data from the server that we're waiting for). + this.sendNewPolls = true; + if (!util.isNodeSdk()) { + //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the + //iframes where we put the long-polling script tags. We have two callbacks: + // 1) Command Callback - Triggered for control issues, like starting a connection. + // 2) Message Callback - Triggered when new data arrives. + this.uniqueCallbackIdentifier = LUIDGenerator(); + window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB; + window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = + onMessageCB; + //Create an iframe for us to add script tags to. + this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_(); + // Set the iframe's contents. + let script = ''; + // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient + // for ie9, but ie8 needs to do it again in the document itself. + if (this.myIFrame.src && + this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') { + const currentDomain = document.domain; + script = ''; + } + const iframeContents = '' + script + ''; + try { + this.myIFrame.doc.open(); + this.myIFrame.doc.write(iframeContents); + this.myIFrame.doc.close(); + } + catch (e) { + log('frame writing exception'); + if (e.stack) { + log(e.stack); + } + log(e); + } + } + else { + this.commandCB = commandCB; + this.onMessageCB = onMessageCB; + } + } + /** + * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can + * actually use. + */ + static createIFrame_() { + const iframe = document.createElement('iframe'); + iframe.style.display = 'none'; + // This is necessary in order to initialize the document inside the iframe + if (document.body) { + document.body.appendChild(iframe); + try { + // If document.domain has been modified in IE, this will throw an error, and we need to set the + // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute + // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work. + const a = iframe.contentWindow.document; + if (!a) { + // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above. + log('No IE domain setting required'); + } + } + catch (e) { + const domain = document.domain; + iframe.src = + "javascript:void((function(){document.open();document.domain='" + + domain + + "';document.close();})())"; + } + } + else { + // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this + // never gets hit. + throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.'; + } + // Get the document of the iframe in a browser-specific way. + if (iframe.contentDocument) { + iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari + } + else if (iframe.contentWindow) { + iframe.doc = iframe.contentWindow.document; // Internet Explorer + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (iframe.document) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + iframe.doc = iframe.document; //others? + } + return iframe; + } + /** + * Cancel all outstanding queries and remove the frame. + */ + close() { + //Mark this iframe as dead, so no new requests are sent. + this.alive = false; + if (this.myIFrame) { + //We have to actually remove all of the html inside this iframe before removing it from the + //window, or IE will continue loading and executing the script tags we've already added, which + //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this. + this.myIFrame.doc.body.textContent = ''; + setTimeout(() => { + if (this.myIFrame !== null) { + document.body.removeChild(this.myIFrame); + this.myIFrame = null; + } + }, Math.floor(0)); + } + // Protect from being called recursively. + const onDisconnect = this.onDisconnect; + if (onDisconnect) { + this.onDisconnect = null; + onDisconnect(); + } + } + /** + * Actually start the long-polling session by adding the first script tag(s) to the iframe. + * @param id - The ID of this connection + * @param pw - The password for this connection + */ + startLongPoll(id, pw) { + this.myID = id; + this.myPW = pw; + this.alive = true; + //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to. + while (this.newRequest_()) { } + } + /** + * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't + * too many outstanding requests and we are still alive. + * + * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if + * needed. + */ + newRequest_() { + // We keep one outstanding request open all the time to receive data, but if we need to send data + // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically + // close the old request. + if (this.alive && + this.sendNewPolls && + this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) { + //construct our url + this.currentSerial++; + const urlParams = {}; + urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID; + urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW; + urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial; + let theURL = this.urlFn(urlParams); + //Now add as much data as we can. + let curDataString = ''; + let i = 0; + while (this.pendingSegs.length > 0) { + //first, lets see if the next segment will fit. + const nextSeg = this.pendingSegs[0]; + if (nextSeg.d.length + + SEG_HEADER_SIZE + + curDataString.length <= + MAX_URL_DATA_SIZE) { + //great, the segment will fit. Lets append it. + const theSeg = this.pendingSegs.shift(); + curDataString = + curDataString + + '&' + + FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM + + i + + '=' + + theSeg.seg + + '&' + + FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET + + i + + '=' + + theSeg.ts + + '&' + + FIREBASE_LONGPOLL_DATA_PARAM + + i + + '=' + + theSeg.d; + i++; + } + else { + break; + } + } + theURL = theURL + curDataString; + this.addLongPollTag_(theURL, this.currentSerial); + return true; + } + else { + return false; + } + } + /** + * Queue a packet for transmission to the server. + * @param segnum - A sequential id for this packet segment used for reassembly + * @param totalsegs - The total number of segments in this packet + * @param data - The data for this segment. + */ + enqueueSegment(segnum, totalsegs, data) { + //add this to the queue of segments to send. + this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data }); + //send the data immediately if there isn't already data being transmitted, unless + //startLongPoll hasn't been called yet. + if (this.alive) { + this.newRequest_(); + } + } + /** + * Add a script tag for a regular long-poll request. + * @param url - The URL of the script tag. + * @param serial - The serial number of the request. + */ + addLongPollTag_(url, serial) { + //remember that we sent this request. + this.outstandingRequests.add(serial); + const doNewRequest = () => { + this.outstandingRequests.delete(serial); + this.newRequest_(); + }; + // If this request doesn't return on its own accord (by the server sending us some data), we'll + // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open. + const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL)); + const readyStateCB = () => { + // Request completed. Cancel the keepalive. + clearTimeout(keepaliveTimeout); + // Trigger a new request so we can continue receiving data. + doNewRequest(); + }; + this.addTag(url, readyStateCB); + } + /** + * Add an arbitrary script tag to the iframe. + * @param url - The URL for the script tag source. + * @param loadCB - A callback to be triggered once the script has loaded. + */ + addTag(url, loadCB) { + if (util.isNodeSdk()) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.doNodeLongPoll(url, loadCB); + } + else { + setTimeout(() => { + try { + // if we're already closed, don't add this poll + if (!this.sendNewPolls) { + return; + } + const newScript = this.myIFrame.doc.createElement('script'); + newScript.type = 'text/javascript'; + newScript.async = true; + newScript.src = url; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + newScript.onload = newScript.onreadystatechange = + function () { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const rstate = newScript.readyState; + if (!rstate || rstate === 'loaded' || rstate === 'complete') { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + newScript.onload = newScript.onreadystatechange = null; + if (newScript.parentNode) { + newScript.parentNode.removeChild(newScript); + } + loadCB(); + } + }; + newScript.onerror = () => { + log('Long-poll script failed to load: ' + url); + this.sendNewPolls = false; + this.close(); + }; + this.myIFrame.doc.body.appendChild(newScript); + } + catch (e) { + // TODO: we should make this error visible somehow + } + }, Math.floor(1)); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Currently simplistic, this class manages what transport a Connection should use at various stages of its + * lifecycle. + * + * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if + * they are available. + */ +class TransportManager { + static get ALL_TRANSPORTS() { + return [BrowserPollConnection, WebSocketConnection]; + } + /** + * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after + * TransportManager has already set up transports_ + */ + static get IS_TRANSPORT_INITIALIZED() { + return this.globalTransportInitialized_; + } + /** + * @param repoInfo - Metadata around the namespace we're connecting to + */ + constructor(repoInfo) { + this.initTransports_(repoInfo); + } + initTransports_(repoInfo) { + const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable'](); + let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed(); + if (repoInfo.webSocketOnly) { + if (!isWebSocketsAvailable) { + warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway."); + } + isSkipPollConnection = true; + } + if (isSkipPollConnection) { + this.transports_ = [WebSocketConnection]; + } + else { + const transports = (this.transports_ = []); + for (const transport of TransportManager.ALL_TRANSPORTS) { + if (transport && transport['isAvailable']()) { + transports.push(transport); + } + } + TransportManager.globalTransportInitialized_ = true; + } + } + /** + * @returns The constructor for the initial transport to use + */ + initialTransport() { + if (this.transports_.length > 0) { + return this.transports_[0]; + } + else { + throw new Error('No transports available'); + } + } + /** + * @returns The constructor for the next transport, or null + */ + upgradeTransport() { + if (this.transports_.length > 1) { + return this.transports_[1]; + } + else { + return null; + } + } +} +// Keeps track of whether the TransportManager has already chosen a transport to use +TransportManager.globalTransportInitialized_ = false; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Abort upgrade attempt if it takes longer than 60s. +const UPGRADE_TIMEOUT = 60000; +// For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses. +// If we haven't sent enough requests within 5s, we'll start sending noop ping requests. +const DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000; +// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data) +// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout +// but we've sent/received enough bytes, we don't cancel the connection. +const BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024; +const BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024; +const MESSAGE_TYPE = 't'; +const MESSAGE_DATA = 'd'; +const CONTROL_SHUTDOWN = 's'; +const CONTROL_RESET = 'r'; +const CONTROL_ERROR = 'e'; +const CONTROL_PONG = 'o'; +const SWITCH_ACK = 'a'; +const END_TRANSMISSION = 'n'; +const PING = 'p'; +const SERVER_HELLO = 'h'; +/** + * Creates a new real-time connection to the server using whichever method works + * best in the current browser. + */ +class Connection { + /** + * @param id - an id for this connection + * @param repoInfo_ - the info for the endpoint to connect to + * @param applicationId_ - the Firebase App ID for this project + * @param appCheckToken_ - The App Check Token for this device. + * @param authToken_ - The auth token for this session. + * @param onMessage_ - the callback to be triggered when a server-push message arrives + * @param onReady_ - the callback to be triggered when this connection is ready to send messages. + * @param onDisconnect_ - the callback to be triggered when a connection was lost + * @param onKill_ - the callback to be triggered when this connection has permanently shut down. + * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server + */ + constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) { + this.id = id; + this.repoInfo_ = repoInfo_; + this.applicationId_ = applicationId_; + this.appCheckToken_ = appCheckToken_; + this.authToken_ = authToken_; + this.onMessage_ = onMessage_; + this.onReady_ = onReady_; + this.onDisconnect_ = onDisconnect_; + this.onKill_ = onKill_; + this.lastSessionId = lastSessionId; + this.connectionCount = 0; + this.pendingDataMessages = []; + this.state_ = 0 /* RealtimeState.CONNECTING */; + this.log_ = logWrapper('c:' + this.id + ':'); + this.transportManager_ = new TransportManager(repoInfo_); + this.log_('Connection created'); + this.start_(); + } + /** + * Starts a connection attempt + */ + start_() { + const conn = this.transportManager_.initialTransport(); + this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId); + // For certain transports (WebSockets), we need to send and receive several messages back and forth before we + // can consider the transport healthy. + this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0; + const onMessageReceived = this.connReceiver_(this.conn_); + const onConnectionLost = this.disconnReceiver_(this.conn_); + this.tx_ = this.conn_; + this.rx_ = this.conn_; + this.secondaryConn_ = null; + this.isHealthy_ = false; + /* + * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame. + * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset. + * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should + * still have the context of your originating frame. + */ + setTimeout(() => { + // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it + this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost); + }, Math.floor(0)); + const healthyTimeoutMS = conn['healthyTimeout'] || 0; + if (healthyTimeoutMS > 0) { + this.healthyTimeout_ = setTimeoutNonBlocking(() => { + this.healthyTimeout_ = null; + if (!this.isHealthy_) { + if (this.conn_ && + this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) { + this.log_('Connection exceeded healthy timeout but has received ' + + this.conn_.bytesReceived + + ' bytes. Marking connection healthy.'); + this.isHealthy_ = true; + this.conn_.markConnectionHealthy(); + } + else if (this.conn_ && + this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) { + this.log_('Connection exceeded healthy timeout but has sent ' + + this.conn_.bytesSent + + ' bytes. Leaving connection alive.'); + // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to + // the server. + } + else { + this.log_('Closing unhealthy connection after timeout.'); + this.close(); + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(healthyTimeoutMS)); + } + } + nextTransportId_() { + return 'c:' + this.id + ':' + this.connectionCount++; + } + disconnReceiver_(conn) { + return everConnected => { + if (conn === this.conn_) { + this.onConnectionLost_(everConnected); + } + else if (conn === this.secondaryConn_) { + this.log_('Secondary connection lost.'); + this.onSecondaryConnectionLost_(); + } + else { + this.log_('closing an old connection'); + } + }; + } + connReceiver_(conn) { + return (message) => { + if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) { + if (conn === this.rx_) { + this.onPrimaryMessageReceived_(message); + } + else if (conn === this.secondaryConn_) { + this.onSecondaryMessageReceived_(message); + } + else { + this.log_('message on old connection'); + } + } + }; + } + /** + * @param dataMsg - An arbitrary data message to be sent to the server + */ + sendRequest(dataMsg) { + // wrap in a data message envelope and send it on + const msg = { t: 'd', d: dataMsg }; + this.sendData_(msg); + } + tryCleanupConnection() { + if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) { + this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId); + this.conn_ = this.secondaryConn_; + this.secondaryConn_ = null; + // the server will shutdown the old connection + } + } + onSecondaryControl_(controlData) { + if (MESSAGE_TYPE in controlData) { + const cmd = controlData[MESSAGE_TYPE]; + if (cmd === SWITCH_ACK) { + this.upgradeIfSecondaryHealthy_(); + } + else if (cmd === CONTROL_RESET) { + // Most likely the session wasn't valid. Abandon the switch attempt + this.log_('Got a reset on secondary, closing it'); + this.secondaryConn_.close(); + // If we were already using this connection for something, than we need to fully close + if (this.tx_ === this.secondaryConn_ || + this.rx_ === this.secondaryConn_) { + this.close(); + } + } + else if (cmd === CONTROL_PONG) { + this.log_('got pong on secondary.'); + this.secondaryResponsesRequired_--; + this.upgradeIfSecondaryHealthy_(); + } + } + } + onSecondaryMessageReceived_(parsedData) { + const layer = requireKey('t', parsedData); + const data = requireKey('d', parsedData); + if (layer === 'c') { + this.onSecondaryControl_(data); + } + else if (layer === 'd') { + // got a data message, but we're still second connection. Need to buffer it up + this.pendingDataMessages.push(data); + } + else { + throw new Error('Unknown protocol layer: ' + layer); + } + } + upgradeIfSecondaryHealthy_() { + if (this.secondaryResponsesRequired_ <= 0) { + this.log_('Secondary connection is healthy.'); + this.isHealthy_ = true; + this.secondaryConn_.markConnectionHealthy(); + this.proceedWithUpgrade_(); + } + else { + // Send a ping to make sure the connection is healthy. + this.log_('sending ping on secondary.'); + this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } }); + } + } + proceedWithUpgrade_() { + // tell this connection to consider itself open + this.secondaryConn_.start(); + // send ack + this.log_('sending client ack on secondary'); + this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } }); + // send end packet on primary transport, switch to sending on this one + // can receive on this one, buffer responses until end received on primary transport + this.log_('Ending transmission on primary'); + this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } }); + this.tx_ = this.secondaryConn_; + this.tryCleanupConnection(); + } + onPrimaryMessageReceived_(parsedData) { + // Must refer to parsedData properties in quotes, so closure doesn't touch them. + const layer = requireKey('t', parsedData); + const data = requireKey('d', parsedData); + if (layer === 'c') { + this.onControl_(data); + } + else if (layer === 'd') { + this.onDataMessage_(data); + } + } + onDataMessage_(message) { + this.onPrimaryResponse_(); + // We don't do anything with data messages, just kick them up a level + this.onMessage_(message); + } + onPrimaryResponse_() { + if (!this.isHealthy_) { + this.primaryResponsesRequired_--; + if (this.primaryResponsesRequired_ <= 0) { + this.log_('Primary connection is healthy.'); + this.isHealthy_ = true; + this.conn_.markConnectionHealthy(); + } + } + } + onControl_(controlData) { + const cmd = requireKey(MESSAGE_TYPE, controlData); + if (MESSAGE_DATA in controlData) { + const payload = controlData[MESSAGE_DATA]; + if (cmd === SERVER_HELLO) { + const handshakePayload = { + ...payload + }; + if (this.repoInfo_.isUsingEmulator) { + // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes. + handshakePayload.h = this.repoInfo_.host; + } + this.onHandshake_(handshakePayload); + } + else if (cmd === END_TRANSMISSION) { + this.log_('recvd end transmission on primary'); + this.rx_ = this.secondaryConn_; + for (let i = 0; i < this.pendingDataMessages.length; ++i) { + this.onDataMessage_(this.pendingDataMessages[i]); + } + this.pendingDataMessages = []; + this.tryCleanupConnection(); + } + else if (cmd === CONTROL_SHUTDOWN) { + // This was previously the 'onKill' callback passed to the lower-level connection + // payload in this case is the reason for the shutdown. Generally a human-readable error + this.onConnectionShutdown_(payload); + } + else if (cmd === CONTROL_RESET) { + // payload in this case is the host we should contact + this.onReset_(payload); + } + else if (cmd === CONTROL_ERROR) { + error('Server Error: ' + payload); + } + else if (cmd === CONTROL_PONG) { + this.log_('got pong on primary.'); + this.onPrimaryResponse_(); + this.sendPingOnPrimaryIfNecessary_(); + } + else { + error('Unknown control packet command: ' + cmd); + } + } + } + /** + * @param handshake - The handshake data returned from the server + */ + onHandshake_(handshake) { + const timestamp = handshake.ts; + const version = handshake.v; + const host = handshake.h; + this.sessionId = handshake.s; + this.repoInfo_.host = host; + // if we've already closed the connection, then don't bother trying to progress further + if (this.state_ === 0 /* RealtimeState.CONNECTING */) { + this.conn_.start(); + this.onConnectionEstablished_(this.conn_, timestamp); + if (PROTOCOL_VERSION !== version) { + warn('Protocol version mismatch detected'); + } + // TODO: do we want to upgrade? when? maybe a delay? + this.tryStartUpgrade_(); + } + } + tryStartUpgrade_() { + const conn = this.transportManager_.upgradeTransport(); + if (conn) { + this.startUpgrade_(conn); + } + } + startUpgrade_(conn) { + this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId); + // For certain transports (WebSockets), we need to send and receive several messages back and forth before we + // can consider the transport healthy. + this.secondaryResponsesRequired_ = + conn['responsesRequiredToBeHealthy'] || 0; + const onMessage = this.connReceiver_(this.secondaryConn_); + const onDisconnect = this.disconnReceiver_(this.secondaryConn_); + this.secondaryConn_.open(onMessage, onDisconnect); + // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary. + setTimeoutNonBlocking(() => { + if (this.secondaryConn_) { + this.log_('Timed out trying to upgrade.'); + this.secondaryConn_.close(); + } + }, Math.floor(UPGRADE_TIMEOUT)); + } + onReset_(host) { + this.log_('Reset packet received. New host: ' + host); + this.repoInfo_.host = host; + // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up. + // We don't currently support resets after the connection has already been established + if (this.state_ === 1 /* RealtimeState.CONNECTED */) { + this.close(); + } + else { + // Close whatever connections we have open and start again. + this.closeConnections_(); + this.start_(); + } + } + onConnectionEstablished_(conn, timestamp) { + this.log_('Realtime connection established.'); + this.conn_ = conn; + this.state_ = 1 /* RealtimeState.CONNECTED */; + if (this.onReady_) { + this.onReady_(timestamp, this.sessionId); + this.onReady_ = null; + } + // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy, + // send some pings. + if (this.primaryResponsesRequired_ === 0) { + this.log_('Primary connection is healthy.'); + this.isHealthy_ = true; + } + else { + setTimeoutNonBlocking(() => { + this.sendPingOnPrimaryIfNecessary_(); + }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS)); + } + } + sendPingOnPrimaryIfNecessary_() { + // If the connection isn't considered healthy yet, we'll send a noop ping packet request. + if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) { + this.log_('sending ping on primary.'); + this.sendData_({ t: 'c', d: { t: PING, d: {} } }); + } + } + onSecondaryConnectionLost_() { + const conn = this.secondaryConn_; + this.secondaryConn_ = null; + if (this.tx_ === conn || this.rx_ === conn) { + // we are relying on this connection already in some capacity. Therefore, a failure is real + this.close(); + } + } + /** + * @param everConnected - Whether or not the connection ever reached a server. Used to determine if + * we should flush the host cache + */ + onConnectionLost_(everConnected) { + this.conn_ = null; + // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting + // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess. + if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) { + this.log_('Realtime connection failed.'); + // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away + if (this.repoInfo_.isCacheableHost()) { + PersistentStorage.remove('host:' + this.repoInfo_.host); + // reset the internal host to what we would show the user, i.e. .firebaseio.com + this.repoInfo_.internalHost = this.repoInfo_.host; + } + } + else if (this.state_ === 1 /* RealtimeState.CONNECTED */) { + this.log_('Realtime connection lost.'); + } + this.close(); + } + onConnectionShutdown_(reason) { + this.log_('Connection shutdown command received. Shutting down...'); + if (this.onKill_) { + this.onKill_(reason); + this.onKill_ = null; + } + // We intentionally don't want to fire onDisconnect (kill is a different case), + // so clear the callback. + this.onDisconnect_ = null; + this.close(); + } + sendData_(data) { + if (this.state_ !== 1 /* RealtimeState.CONNECTED */) { + throw 'Connection is not connected'; + } + else { + this.tx_.send(data); + } + } + /** + * Cleans up this connection, calling the appropriate callbacks + */ + close() { + if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) { + this.log_('Closing realtime connection.'); + this.state_ = 2 /* RealtimeState.DISCONNECTED */; + this.closeConnections_(); + if (this.onDisconnect_) { + this.onDisconnect_(); + this.onDisconnect_ = null; + } + } + } + closeConnections_() { + this.log_('Shutting down all connections'); + if (this.conn_) { + this.conn_.close(); + this.conn_ = null; + } + if (this.secondaryConn_) { + this.secondaryConn_.close(); + this.secondaryConn_ = null; + } + if (this.healthyTimeout_) { + clearTimeout(this.healthyTimeout_); + this.healthyTimeout_ = null; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Interface defining the set of actions that can be performed against the Firebase server + * (basically corresponds to our wire protocol). + * + * @interface + */ +class ServerActions { + put(pathString, data, onComplete, hash) { } + merge(pathString, data, onComplete, hash) { } + /** + * Refreshes the auth token for the current connection. + * @param token - The authentication token + */ + refreshAuthToken(token) { } + /** + * Refreshes the app check token for the current connection. + * @param token The app check token + */ + refreshAppCheckToken(token) { } + onDisconnectPut(pathString, data, onComplete) { } + onDisconnectMerge(pathString, data, onComplete) { } + onDisconnectCancel(pathString, onComplete) { } + reportStats(stats) { } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Base class to be used if you want to emit events. Call the constructor with + * the set of allowed event names. + */ +class EventEmitter { + constructor(allowedEvents_) { + this.allowedEvents_ = allowedEvents_; + this.listeners_ = {}; + util.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array'); + } + /** + * To be called by derived classes to trigger events. + */ + trigger(eventType, ...varArgs) { + if (Array.isArray(this.listeners_[eventType])) { + // Clone the list, since callbacks could add/remove listeners. + const listeners = [...this.listeners_[eventType]]; + for (let i = 0; i < listeners.length; i++) { + listeners[i].callback.apply(listeners[i].context, varArgs); + } + } + } + on(eventType, callback, context) { + this.validateEventType_(eventType); + this.listeners_[eventType] = this.listeners_[eventType] || []; + this.listeners_[eventType].push({ callback, context }); + const eventData = this.getInitialEvent(eventType); + if (eventData) { + callback.apply(context, eventData); + } + } + off(eventType, callback, context) { + this.validateEventType_(eventType); + const listeners = this.listeners_[eventType] || []; + for (let i = 0; i < listeners.length; i++) { + if (listeners[i].callback === callback && + (!context || context === listeners[i].context)) { + listeners.splice(i, 1); + return; + } + } + } + validateEventType_(eventType) { + util.assert(this.allowedEvents_.find(et => { + return et === eventType; + }), 'Unknown event: ' + eventType); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Monitors online state (as reported by window.online/offline events). + * + * The expectation is that this could have many false positives (thinks we are online + * when we're not), but no false negatives. So we can safely use it to determine when + * we definitely cannot reach the internet. + */ +class OnlineMonitor extends EventEmitter { + static getInstance() { + return new OnlineMonitor(); + } + constructor() { + super(['online']); + this.online_ = true; + // We've had repeated complaints that Cordova apps can get stuck "offline", e.g. + // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810 + // It would seem that the 'online' event does not always fire consistently. So we disable it + // for Cordova. + if (typeof window !== 'undefined' && + typeof window.addEventListener !== 'undefined' && + !util.isMobileCordova()) { + window.addEventListener('online', () => { + if (!this.online_) { + this.online_ = true; + this.trigger('online', true); + } + }, false); + window.addEventListener('offline', () => { + if (this.online_) { + this.online_ = false; + this.trigger('online', false); + } + }, false); + } + } + getInitialEvent(eventType) { + util.assert(eventType === 'online', 'Unknown event type: ' + eventType); + return [this.online_]; + } + currentlyOnline() { + return this.online_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Maximum key depth. */ +const MAX_PATH_DEPTH = 32; +/** Maximum number of (UTF8) bytes in a Firebase path. */ +const MAX_PATH_LENGTH_BYTES = 768; +/** + * An immutable object representing a parsed path. It's immutable so that you + * can pass them around to other functions without worrying about them changing + * it. + */ +class Path { + /** + * @param pathOrString - Path string to parse, or another path, or the raw + * tokens array + */ + constructor(pathOrString, pieceNum) { + if (pieceNum === void 0) { + this.pieces_ = pathOrString.split('/'); + // Remove empty pieces. + let copyTo = 0; + for (let i = 0; i < this.pieces_.length; i++) { + if (this.pieces_[i].length > 0) { + this.pieces_[copyTo] = this.pieces_[i]; + copyTo++; + } + } + this.pieces_.length = copyTo; + this.pieceNum_ = 0; + } + else { + this.pieces_ = pathOrString; + this.pieceNum_ = pieceNum; + } + } + toString() { + let pathString = ''; + for (let i = this.pieceNum_; i < this.pieces_.length; i++) { + if (this.pieces_[i] !== '') { + pathString += '/' + this.pieces_[i]; + } + } + return pathString || '/'; + } +} +function newEmptyPath() { + return new Path(''); +} +function pathGetFront(path) { + if (path.pieceNum_ >= path.pieces_.length) { + return null; + } + return path.pieces_[path.pieceNum_]; +} +/** + * @returns The number of segments in this path + */ +function pathGetLength(path) { + return path.pieces_.length - path.pieceNum_; +} +function pathPopFront(path) { + let pieceNum = path.pieceNum_; + if (pieceNum < path.pieces_.length) { + pieceNum++; + } + return new Path(path.pieces_, pieceNum); +} +function pathGetBack(path) { + if (path.pieceNum_ < path.pieces_.length) { + return path.pieces_[path.pieces_.length - 1]; + } + return null; +} +function pathToUrlEncodedString(path) { + let pathString = ''; + for (let i = path.pieceNum_; i < path.pieces_.length; i++) { + if (path.pieces_[i] !== '') { + pathString += '/' + encodeURIComponent(String(path.pieces_[i])); + } + } + return pathString || '/'; +} +/** + * Shallow copy of the parts of the path. + * + */ +function pathSlice(path, begin = 0) { + return path.pieces_.slice(path.pieceNum_ + begin); +} +function pathParent(path) { + if (path.pieceNum_ >= path.pieces_.length) { + return null; + } + const pieces = []; + for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) { + pieces.push(path.pieces_[i]); + } + return new Path(pieces, 0); +} +function pathChild(path, childPathObj) { + const pieces = []; + for (let i = path.pieceNum_; i < path.pieces_.length; i++) { + pieces.push(path.pieces_[i]); + } + if (childPathObj instanceof Path) { + for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) { + pieces.push(childPathObj.pieces_[i]); + } + } + else { + const childPieces = childPathObj.split('/'); + for (let i = 0; i < childPieces.length; i++) { + if (childPieces[i].length > 0) { + pieces.push(childPieces[i]); + } + } + } + return new Path(pieces, 0); +} +/** + * @returns True if there are no segments in this path + */ +function pathIsEmpty(path) { + return path.pieceNum_ >= path.pieces_.length; +} +/** + * @returns The path from outerPath to innerPath + */ +function newRelativePath(outerPath, innerPath) { + const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath); + if (outer === null) { + return innerPath; + } + else if (outer === inner) { + return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath)); + } + else { + throw new Error('INTERNAL ERROR: innerPath (' + + innerPath + + ') is not within ' + + 'outerPath (' + + outerPath + + ')'); + } +} +/** + * @returns -1, 0, 1 if left is less, equal, or greater than the right. + */ +function pathCompare(left, right) { + const leftKeys = pathSlice(left, 0); + const rightKeys = pathSlice(right, 0); + for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) { + const cmp = nameCompare(leftKeys[i], rightKeys[i]); + if (cmp !== 0) { + return cmp; + } + } + if (leftKeys.length === rightKeys.length) { + return 0; + } + return leftKeys.length < rightKeys.length ? -1 : 1; +} +/** + * @returns true if paths are the same. + */ +function pathEquals(path, other) { + if (pathGetLength(path) !== pathGetLength(other)) { + return false; + } + for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) { + if (path.pieces_[i] !== other.pieces_[j]) { + return false; + } + } + return true; +} +/** + * @returns True if this path is a parent of (or the same as) other + */ +function pathContains(path, other) { + let i = path.pieceNum_; + let j = other.pieceNum_; + if (pathGetLength(path) > pathGetLength(other)) { + return false; + } + while (i < path.pieces_.length) { + if (path.pieces_[i] !== other.pieces_[j]) { + return false; + } + ++i; + ++j; + } + return true; +} +/** + * Dynamic (mutable) path used to count path lengths. + * + * This class is used to efficiently check paths for valid + * length (in UTF8 bytes) and depth (used in path validation). + * + * Throws Error exception if path is ever invalid. + * + * The definition of a path always begins with '/'. + */ +class ValidationPath { + /** + * @param path - Initial Path. + * @param errorPrefix_ - Prefix for any error messages. + */ + constructor(path, errorPrefix_) { + this.errorPrefix_ = errorPrefix_; + this.parts_ = pathSlice(path, 0); + /** Initialize to number of '/' chars needed in path. */ + this.byteLength_ = Math.max(1, this.parts_.length); + for (let i = 0; i < this.parts_.length; i++) { + this.byteLength_ += util.stringLength(this.parts_[i]); + } + validationPathCheckValid(this); + } +} +function validationPathPush(validationPath, child) { + // Count the needed '/' + if (validationPath.parts_.length > 0) { + validationPath.byteLength_ += 1; + } + validationPath.parts_.push(child); + validationPath.byteLength_ += util.stringLength(child); + validationPathCheckValid(validationPath); +} +function validationPathPop(validationPath) { + const last = validationPath.parts_.pop(); + validationPath.byteLength_ -= util.stringLength(last); + // Un-count the previous '/' + if (validationPath.parts_.length > 0) { + validationPath.byteLength_ -= 1; + } +} +function validationPathCheckValid(validationPath) { + if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) { + throw new Error(validationPath.errorPrefix_ + + 'has a key path longer than ' + + MAX_PATH_LENGTH_BYTES + + ' bytes (' + + validationPath.byteLength_ + + ').'); + } + if (validationPath.parts_.length > MAX_PATH_DEPTH) { + throw new Error(validationPath.errorPrefix_ + + 'path specified exceeds the maximum depth that can be written (' + + MAX_PATH_DEPTH + + ') or object contains a cycle ' + + validationPathToErrorString(validationPath)); + } +} +/** + * String for use in error messages - uses '.' notation for path. + */ +function validationPathToErrorString(validationPath) { + if (validationPath.parts_.length === 0) { + return ''; + } + return "in property '" + validationPath.parts_.join('.') + "'"; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class VisibilityMonitor extends EventEmitter { + static getInstance() { + return new VisibilityMonitor(); + } + constructor() { + super(['visible']); + let hidden; + let visibilityChange; + if (typeof document !== 'undefined' && + typeof document.addEventListener !== 'undefined') { + if (typeof document['hidden'] !== 'undefined') { + // Opera 12.10 and Firefox 18 and later support + visibilityChange = 'visibilitychange'; + hidden = 'hidden'; + } + else if (typeof document['mozHidden'] !== 'undefined') { + visibilityChange = 'mozvisibilitychange'; + hidden = 'mozHidden'; + } + else if (typeof document['msHidden'] !== 'undefined') { + visibilityChange = 'msvisibilitychange'; + hidden = 'msHidden'; + } + else if (typeof document['webkitHidden'] !== 'undefined') { + visibilityChange = 'webkitvisibilitychange'; + hidden = 'webkitHidden'; + } + } + // Initially, we always assume we are visible. This ensures that in browsers + // without page visibility support or in cases where we are never visible + // (e.g. chrome extension), we act as if we are visible, i.e. don't delay + // reconnects + this.visible_ = true; + if (visibilityChange) { + document.addEventListener(visibilityChange, () => { + const visible = !document[hidden]; + if (visible !== this.visible_) { + this.visible_ = visible; + this.trigger('visible', visible); + } + }, false); + } + } + getInitialEvent(eventType) { + util.assert(eventType === 'visible', 'Unknown event type: ' + eventType); + return [this.visible_]; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const RECONNECT_MIN_DELAY = 1000; +const RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858) +const RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server) +const RECONNECT_DELAY_MULTIPLIER = 1.3; +const RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec. +const SERVER_KILL_INTERRUPT_REASON = 'server_kill'; +// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off. +const INVALID_TOKEN_THRESHOLD = 3; +/** + * Firebase connection. Abstracts wire protocol and handles reconnecting. + * + * NOTE: All JSON objects sent to the realtime connection must have property names enclosed + * in quotes to make sure the closure compiler does not minify them. + */ +class PersistentConnection extends ServerActions { + /** + * @param repoInfo_ - Data about the namespace we are connecting to + * @param applicationId_ - The Firebase App ID for this project + * @param onDataUpdate_ - A callback for new data from the server + */ + constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) { + super(); + this.repoInfo_ = repoInfo_; + this.applicationId_ = applicationId_; + this.onDataUpdate_ = onDataUpdate_; + this.onConnectStatus_ = onConnectStatus_; + this.onServerInfoUpdate_ = onServerInfoUpdate_; + this.authTokenProvider_ = authTokenProvider_; + this.appCheckTokenProvider_ = appCheckTokenProvider_; + this.authOverride_ = authOverride_; + // Used for diagnostic logging. + this.id = PersistentConnection.nextPersistentConnectionId_++; + this.log_ = logWrapper('p:' + this.id + ':'); + this.interruptReasons_ = {}; + this.listens = new Map(); + this.outstandingPuts_ = []; + this.outstandingGets_ = []; + this.outstandingPutCount_ = 0; + this.outstandingGetCount_ = 0; + this.onDisconnectRequestQueue_ = []; + this.connected_ = false; + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT; + this.securityDebugCallback_ = null; + this.lastSessionId = null; + this.establishConnectionTimer_ = null; + this.visible_ = false; + // Before we get connected, we keep a queue of pending messages to send. + this.requestCBHash_ = {}; + this.requestNumber_ = 0; + this.realtime_ = null; + this.authToken_ = null; + this.appCheckToken_ = null; + this.forceTokenRefresh_ = false; + this.invalidAuthTokenCount_ = 0; + this.invalidAppCheckTokenCount_ = 0; + this.firstConnection_ = true; + this.lastConnectionAttemptTime_ = null; + this.lastConnectionEstablishedTime_ = null; + if (authOverride_ && !util.isNodeSdk()) { + throw new Error('Auth override specified in options, but not supported on non Node.js platforms'); + } + VisibilityMonitor.getInstance().on('visible', this.onVisible_, this); + if (repoInfo_.host.indexOf('fblocal') === -1) { + OnlineMonitor.getInstance().on('online', this.onOnline_, this); + } + } + sendRequest(action, body, onResponse) { + const curReqNum = ++this.requestNumber_; + const msg = { r: curReqNum, a: action, b: body }; + this.log_(util.stringify(msg)); + util.assert(this.connected_, "sendRequest call when we're not connected not allowed."); + this.realtime_.sendRequest(msg); + if (onResponse) { + this.requestCBHash_[curReqNum] = onResponse; + } + } + get(query) { + this.initConnection_(); + const deferred = new util.Deferred(); + const request = { + p: query._path.toString(), + q: query._queryObject + }; + const outstandingGet = { + action: 'g', + request, + onComplete: (message) => { + const payload = message['d']; + if (message['s'] === 'ok') { + deferred.resolve(payload); + } + else { + deferred.reject(payload); + } + } + }; + this.outstandingGets_.push(outstandingGet); + this.outstandingGetCount_++; + const index = this.outstandingGets_.length - 1; + if (this.connected_) { + this.sendGet_(index); + } + return deferred.promise; + } + listen(query, currentHashFn, tag, onComplete) { + this.initConnection_(); + const queryId = query._queryIdentifier; + const pathString = query._path.toString(); + this.log_('Listen called for ' + pathString + ' ' + queryId); + if (!this.listens.has(pathString)) { + this.listens.set(pathString, new Map()); + } + util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query'); + util.assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`); + const listenSpec = { + onComplete, + hashFn: currentHashFn, + query, + tag + }; + this.listens.get(pathString).set(queryId, listenSpec); + if (this.connected_) { + this.sendListen_(listenSpec); + } + } + sendGet_(index) { + const get = this.outstandingGets_[index]; + this.sendRequest('g', get.request, (message) => { + delete this.outstandingGets_[index]; + this.outstandingGetCount_--; + if (this.outstandingGetCount_ === 0) { + this.outstandingGets_ = []; + } + if (get.onComplete) { + get.onComplete(message); + } + }); + } + sendListen_(listenSpec) { + const query = listenSpec.query; + const pathString = query._path.toString(); + const queryId = query._queryIdentifier; + this.log_('Listen on ' + pathString + ' for ' + queryId); + const req = { /*path*/ p: pathString }; + const action = 'q'; + // Only bother to send query if it's non-default. + if (listenSpec.tag) { + req['q'] = query._queryObject; + req['t'] = listenSpec.tag; + } + req[ /*hash*/'h'] = listenSpec.hashFn(); + this.sendRequest(action, req, (message) => { + const payload = message[ /*data*/'d']; + const status = message[ /*status*/'s']; + // print warnings in any case... + PersistentConnection.warnOnListenWarnings_(payload, query); + const currentListenSpec = this.listens.get(pathString) && + this.listens.get(pathString).get(queryId); + // only trigger actions if the listen hasn't been removed and readded + if (currentListenSpec === listenSpec) { + this.log_('listen response', message); + if (status !== 'ok') { + this.removeListen_(pathString, queryId); + } + if (listenSpec.onComplete) { + listenSpec.onComplete(status, payload); + } + } + }); + } + static warnOnListenWarnings_(payload, query) { + if (payload && typeof payload === 'object' && util.contains(payload, 'w')) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const warnings = util.safeGet(payload, 'w'); + if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) { + const indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"'; + const indexPath = query._path.toString(); + warn(`Using an unspecified index. Your data will be downloaded and ` + + `filtered on the client. Consider adding ${indexSpec} at ` + + `${indexPath} to your security rules for better performance.`); + } + } + } + refreshAuthToken(token) { + this.authToken_ = token; + this.log_('Auth token refreshed'); + if (this.authToken_) { + this.tryAuth(); + } + else { + //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete + //the credential so we dont become authenticated next time we connect. + if (this.connected_) { + this.sendRequest('unauth', {}, () => { }); + } + } + this.reduceReconnectDelayIfAdminCredential_(token); + } + reduceReconnectDelayIfAdminCredential_(credential) { + // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client). + // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires. + const isFirebaseSecret = credential && credential.length === 40; + if (isFirebaseSecret || util.isAdmin(credential)) { + this.log_('Admin auth credential detected. Reducing max reconnect time.'); + this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS; + } + } + refreshAppCheckToken(token) { + this.appCheckToken_ = token; + this.log_('App check token refreshed'); + if (this.appCheckToken_) { + this.tryAppCheck(); + } + else { + //If we're connected we want to let the server know to unauthenticate us. + //If we're not connected, simply delete the credential so we dont become + // authenticated next time we connect. + if (this.connected_) { + this.sendRequest('unappeck', {}, () => { }); + } + } + } + /** + * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like + * a auth revoked (the connection is closed). + */ + tryAuth() { + if (this.connected_ && this.authToken_) { + const token = this.authToken_; + const authMethod = util.isValidFormat(token) ? 'auth' : 'gauth'; + const requestData = { cred: token }; + if (this.authOverride_ === null) { + requestData['noauth'] = true; + } + else if (typeof this.authOverride_ === 'object') { + requestData['authvar'] = this.authOverride_; + } + this.sendRequest(authMethod, requestData, (res) => { + const status = res[ /*status*/'s']; + const data = res[ /*data*/'d'] || 'error'; + if (this.authToken_ === token) { + if (status === 'ok') { + this.invalidAuthTokenCount_ = 0; + } + else { + // Triggers reconnect and force refresh for auth token + this.onAuthRevoked_(status, data); + } + } + }); + } + } + /** + * Attempts to authenticate with the given token. If the authentication + * attempt fails, it's triggered like the token was revoked (the connection is + * closed). + */ + tryAppCheck() { + if (this.connected_ && this.appCheckToken_) { + this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => { + const status = res[ /*status*/'s']; + const data = res[ /*data*/'d'] || 'error'; + if (status === 'ok') { + this.invalidAppCheckTokenCount_ = 0; + } + else { + this.onAppCheckRevoked_(status, data); + } + }); + } + } + /** + * @inheritDoc + */ + unlisten(query, tag) { + const pathString = query._path.toString(); + const queryId = query._queryIdentifier; + this.log_('Unlisten called for ' + pathString + ' ' + queryId); + util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query'); + const listen = this.removeListen_(pathString, queryId); + if (listen && this.connected_) { + this.sendUnlisten_(pathString, queryId, query._queryObject, tag); + } + } + sendUnlisten_(pathString, queryId, queryObj, tag) { + this.log_('Unlisten on ' + pathString + ' for ' + queryId); + const req = { /*path*/ p: pathString }; + const action = 'n'; + // Only bother sending queryId if it's non-default. + if (tag) { + req['q'] = queryObj; + req['t'] = tag; + } + this.sendRequest(action, req); + } + onDisconnectPut(pathString, data, onComplete) { + this.initConnection_(); + if (this.connected_) { + this.sendOnDisconnect_('o', pathString, data, onComplete); + } + else { + this.onDisconnectRequestQueue_.push({ + pathString, + action: 'o', + data, + onComplete + }); + } + } + onDisconnectMerge(pathString, data, onComplete) { + this.initConnection_(); + if (this.connected_) { + this.sendOnDisconnect_('om', pathString, data, onComplete); + } + else { + this.onDisconnectRequestQueue_.push({ + pathString, + action: 'om', + data, + onComplete + }); + } + } + onDisconnectCancel(pathString, onComplete) { + this.initConnection_(); + if (this.connected_) { + this.sendOnDisconnect_('oc', pathString, null, onComplete); + } + else { + this.onDisconnectRequestQueue_.push({ + pathString, + action: 'oc', + data: null, + onComplete + }); + } + } + sendOnDisconnect_(action, pathString, data, onComplete) { + const request = { /*path*/ p: pathString, /*data*/ d: data }; + this.log_('onDisconnect ' + action, request); + this.sendRequest(action, request, (response) => { + if (onComplete) { + setTimeout(() => { + onComplete(response[ /*status*/'s'], response[ /* data */'d']); + }, Math.floor(0)); + } + }); + } + put(pathString, data, onComplete, hash) { + this.putInternal('p', pathString, data, onComplete, hash); + } + merge(pathString, data, onComplete, hash) { + this.putInternal('m', pathString, data, onComplete, hash); + } + putInternal(action, pathString, data, onComplete, hash) { + this.initConnection_(); + const request = { + /*path*/ p: pathString, + /*data*/ d: data + }; + if (hash !== undefined) { + request[ /*hash*/'h'] = hash; + } + // TODO: Only keep track of the most recent put for a given path? + this.outstandingPuts_.push({ + action, + request, + onComplete + }); + this.outstandingPutCount_++; + const index = this.outstandingPuts_.length - 1; + if (this.connected_) { + this.sendPut_(index); + } + else { + this.log_('Buffering put: ' + pathString); + } + } + sendPut_(index) { + const action = this.outstandingPuts_[index].action; + const request = this.outstandingPuts_[index].request; + const onComplete = this.outstandingPuts_[index].onComplete; + this.outstandingPuts_[index].queued = this.connected_; + this.sendRequest(action, request, (message) => { + this.log_(action + ' response', message); + delete this.outstandingPuts_[index]; + this.outstandingPutCount_--; + // Clean up array occasionally. + if (this.outstandingPutCount_ === 0) { + this.outstandingPuts_ = []; + } + if (onComplete) { + onComplete(message[ /*status*/'s'], message[ /* data */'d']); + } + }); + } + reportStats(stats) { + // If we're not connected, we just drop the stats. + if (this.connected_) { + const request = { /*counters*/ c: stats }; + this.log_('reportStats', request); + this.sendRequest(/*stats*/ 's', request, result => { + const status = result[ /*status*/'s']; + if (status !== 'ok') { + const errorReason = result[ /* data */'d']; + this.log_('reportStats', 'Error sending stats: ' + errorReason); + } + }); + } + } + onDataMessage_(message) { + if ('r' in message) { + // this is a response + this.log_('from server: ' + util.stringify(message)); + const reqNum = message['r']; + const onResponse = this.requestCBHash_[reqNum]; + if (onResponse) { + delete this.requestCBHash_[reqNum]; + onResponse(message[ /*body*/'b']); + } + } + else if ('error' in message) { + throw 'A server-side error has occurred: ' + message['error']; + } + else if ('a' in message) { + // a and b are action and body, respectively + this.onDataPush_(message['a'], message['b']); + } + } + onDataPush_(action, body) { + this.log_('handleServerMessage', action, body); + if (action === 'd') { + this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], + /*isMerge*/ false, body['t']); + } + else if (action === 'm') { + this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], + /*isMerge=*/ true, body['t']); + } + else if (action === 'c') { + this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']); + } + else if (action === 'ac') { + this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']); + } + else if (action === 'apc') { + this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']); + } + else if (action === 'sd') { + this.onSecurityDebugPacket_(body); + } + else { + error('Unrecognized action received from server: ' + + util.stringify(action) + + '\nAre you using the latest client?'); + } + } + onReady_(timestamp, sessionId) { + this.log_('connection ready'); + this.connected_ = true; + this.lastConnectionEstablishedTime_ = new Date().getTime(); + this.handleTimestamp_(timestamp); + this.lastSessionId = sessionId; + if (this.firstConnection_) { + this.sendConnectStats_(); + } + this.restoreState_(); + this.firstConnection_ = false; + this.onConnectStatus_(true); + } + scheduleConnect_(timeout) { + util.assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?"); + if (this.establishConnectionTimer_) { + clearTimeout(this.establishConnectionTimer_); + } + // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in + // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests). + this.establishConnectionTimer_ = setTimeout(() => { + this.establishConnectionTimer_ = null; + this.establishConnection_(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(timeout)); + } + initConnection_() { + if (!this.realtime_ && this.firstConnection_) { + this.scheduleConnect_(0); + } + } + onVisible_(visible) { + // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine. + if (visible && + !this.visible_ && + this.reconnectDelay_ === this.maxReconnectDelay_) { + this.log_('Window became visible. Reducing delay.'); + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + if (!this.realtime_) { + this.scheduleConnect_(0); + } + } + this.visible_ = visible; + } + onOnline_(online) { + if (online) { + this.log_('Browser went online.'); + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + if (!this.realtime_) { + this.scheduleConnect_(0); + } + } + else { + this.log_('Browser went offline. Killing connection.'); + if (this.realtime_) { + this.realtime_.close(); + } + } + } + onRealtimeDisconnect_() { + this.log_('data client disconnected'); + this.connected_ = false; + this.realtime_ = null; + // Since we don't know if our sent transactions succeeded or not, we need to cancel them. + this.cancelSentTransactions_(); + // Clear out the pending requests. + this.requestCBHash_ = {}; + if (this.shouldReconnect_()) { + if (!this.visible_) { + this.log_("Window isn't visible. Delaying reconnect."); + this.reconnectDelay_ = this.maxReconnectDelay_; + this.lastConnectionAttemptTime_ = new Date().getTime(); + } + else if (this.lastConnectionEstablishedTime_) { + // If we've been connected long enough, reset reconnect delay to minimum. + const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_; + if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) { + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + } + this.lastConnectionEstablishedTime_ = null; + } + const timeSinceLastConnectAttempt = Math.max(0, new Date().getTime() - this.lastConnectionAttemptTime_); + let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt); + reconnectDelay = Math.random() * reconnectDelay; + this.log_('Trying to reconnect in ' + reconnectDelay + 'ms'); + this.scheduleConnect_(reconnectDelay); + // Adjust reconnect delay for next time. + this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER); + } + this.onConnectStatus_(false); + } + async establishConnection_() { + if (this.shouldReconnect_()) { + this.log_('Making a connection attempt'); + this.lastConnectionAttemptTime_ = new Date().getTime(); + this.lastConnectionEstablishedTime_ = null; + const onDataMessage = this.onDataMessage_.bind(this); + const onReady = this.onReady_.bind(this); + const onDisconnect = this.onRealtimeDisconnect_.bind(this); + const connId = this.id + ':' + PersistentConnection.nextConnectionId_++; + const lastSessionId = this.lastSessionId; + let canceled = false; + let connection = null; + const closeFn = function () { + if (connection) { + connection.close(); + } + else { + canceled = true; + onDisconnect(); + } + }; + const sendRequestFn = function (msg) { + util.assert(connection, "sendRequest call when we're not connected not allowed."); + connection.sendRequest(msg); + }; + this.realtime_ = { + close: closeFn, + sendRequest: sendRequestFn + }; + const forceRefresh = this.forceTokenRefresh_; + this.forceTokenRefresh_ = false; + try { + // First fetch auth and app check token, and establish connection after + // fetching the token was successful + const [authToken, appCheckToken] = await Promise.all([ + this.authTokenProvider_.getToken(forceRefresh), + this.appCheckTokenProvider_.getToken(forceRefresh) + ]); + if (!canceled) { + log('getToken() completed. Creating connection.'); + this.authToken_ = authToken && authToken.accessToken; + this.appCheckToken_ = appCheckToken && appCheckToken.token; + connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect, + /* onKill= */ reason => { + warn(reason + ' (' + this.repoInfo_.toString() + ')'); + this.interrupt(SERVER_KILL_INTERRUPT_REASON); + }, lastSessionId); + } + else { + log('getToken() completed but was canceled'); + } + } + catch (error) { + this.log_('Failed to get token: ' + error); + if (!canceled) { + if (this.repoInfo_.nodeAdmin) { + // This may be a critical error for the Admin Node.js SDK, so log a warning. + // But getToken() may also just have temporarily failed, so we still want to + // continue retrying. + warn(error); + } + closeFn(); + } + } + } + } + interrupt(reason) { + log('Interrupting connection for reason: ' + reason); + this.interruptReasons_[reason] = true; + if (this.realtime_) { + this.realtime_.close(); + } + else { + if (this.establishConnectionTimer_) { + clearTimeout(this.establishConnectionTimer_); + this.establishConnectionTimer_ = null; + } + if (this.connected_) { + this.onRealtimeDisconnect_(); + } + } + } + resume(reason) { + log('Resuming connection for reason: ' + reason); + delete this.interruptReasons_[reason]; + if (util.isEmpty(this.interruptReasons_)) { + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + if (!this.realtime_) { + this.scheduleConnect_(0); + } + } + } + handleTimestamp_(timestamp) { + const delta = timestamp - new Date().getTime(); + this.onServerInfoUpdate_({ serverTimeOffset: delta }); + } + cancelSentTransactions_() { + for (let i = 0; i < this.outstandingPuts_.length; i++) { + const put = this.outstandingPuts_[i]; + if (put && /*hash*/ 'h' in put.request && put.queued) { + if (put.onComplete) { + put.onComplete('disconnect'); + } + delete this.outstandingPuts_[i]; + this.outstandingPutCount_--; + } + } + // Clean up array occasionally. + if (this.outstandingPutCount_ === 0) { + this.outstandingPuts_ = []; + } + } + onListenRevoked_(pathString, query) { + // Remove the listen and manufacture a "permission_denied" error for the failed listen. + let queryId; + if (!query) { + queryId = 'default'; + } + else { + queryId = query.map(q => ObjectToUniqueKey(q)).join('$'); + } + const listen = this.removeListen_(pathString, queryId); + if (listen && listen.onComplete) { + listen.onComplete('permission_denied'); + } + } + removeListen_(pathString, queryId) { + const normalizedPathString = new Path(pathString).toString(); // normalize path. + let listen; + if (this.listens.has(normalizedPathString)) { + const map = this.listens.get(normalizedPathString); + listen = map.get(queryId); + map.delete(queryId); + if (map.size === 0) { + this.listens.delete(normalizedPathString); + } + } + else { + // all listens for this path has already been removed + listen = undefined; + } + return listen; + } + onAuthRevoked_(statusCode, explanation) { + log('Auth token revoked: ' + statusCode + '/' + explanation); + this.authToken_ = null; + this.forceTokenRefresh_ = true; + this.realtime_.close(); + if (statusCode === 'invalid_token' || statusCode === 'permission_denied') { + // We'll wait a couple times before logging the warning / increasing the + // retry period since oauth tokens will report as "invalid" if they're + // just expired. Plus there may be transient issues that resolve themselves. + this.invalidAuthTokenCount_++; + if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) { + // Set a long reconnect delay because recovery is unlikely + this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS; + // Notify the auth token provider that the token is invalid, which will log + // a warning + this.authTokenProvider_.notifyForInvalidToken(); + } + } + } + onAppCheckRevoked_(statusCode, explanation) { + log('App check token revoked: ' + statusCode + '/' + explanation); + this.appCheckToken_ = null; + this.forceTokenRefresh_ = true; + // Note: We don't close the connection as the developer may not have + // enforcement enabled. The backend closes connections with enforcements. + if (statusCode === 'invalid_token' || statusCode === 'permission_denied') { + // We'll wait a couple times before logging the warning / increasing the + // retry period since oauth tokens will report as "invalid" if they're + // just expired. Plus there may be transient issues that resolve themselves. + this.invalidAppCheckTokenCount_++; + if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) { + this.appCheckTokenProvider_.notifyForInvalidToken(); + } + } + } + onSecurityDebugPacket_(body) { + if (this.securityDebugCallback_) { + this.securityDebugCallback_(body); + } + else { + if ('msg' in body) { + console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: ')); + } + } + } + restoreState_() { + //Re-authenticate ourselves if we have a credential stored. + this.tryAuth(); + this.tryAppCheck(); + // Puts depend on having received the corresponding data update from the server before they complete, so we must + // make sure to send listens before puts. + for (const queries of this.listens.values()) { + for (const listenSpec of queries.values()) { + this.sendListen_(listenSpec); + } + } + for (let i = 0; i < this.outstandingPuts_.length; i++) { + if (this.outstandingPuts_[i]) { + this.sendPut_(i); + } + } + while (this.onDisconnectRequestQueue_.length) { + const request = this.onDisconnectRequestQueue_.shift(); + this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete); + } + for (let i = 0; i < this.outstandingGets_.length; i++) { + if (this.outstandingGets_[i]) { + this.sendGet_(i); + } + } + } + /** + * Sends client stats for first connection + */ + sendConnectStats_() { + const stats = {}; + let clientName = 'js'; + if (util.isNodeSdk()) { + if (this.repoInfo_.nodeAdmin) { + clientName = 'admin_node'; + } + else { + clientName = 'node'; + } + } + stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1; + if (util.isMobileCordova()) { + stats['framework.cordova'] = 1; + } + else if (util.isReactNative()) { + stats['framework.reactnative'] = 1; + } + this.reportStats(stats); + } + shouldReconnect_() { + const online = OnlineMonitor.getInstance().currentlyOnline(); + return util.isEmpty(this.interruptReasons_) && online; + } +} +PersistentConnection.nextPersistentConnectionId_ = 0; +/** + * Counter for number of connections created. Mainly used for tagging in the logs + */ +PersistentConnection.nextConnectionId_ = 0; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class NamedNode { + constructor(name, node) { + this.name = name; + this.node = node; + } + static Wrap(name, node) { + return new NamedNode(name, node); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Index { + /** + * @returns A standalone comparison function for + * this index + */ + getCompare() { + return this.compare.bind(this); + } + /** + * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different, + * it's possible that the changes are isolated to parts of the snapshot that are not indexed. + * + * + * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode + */ + indexedValueChanged(oldNode, newNode) { + const oldWrapped = new NamedNode(MIN_NAME, oldNode); + const newWrapped = new NamedNode(MIN_NAME, newNode); + return this.compare(oldWrapped, newWrapped) !== 0; + } + /** + * @returns a node wrapper that will sort equal to or less than + * any other node wrapper, using this index + */ + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let __EMPTY_NODE; +class KeyIndex extends Index { + static get __EMPTY_NODE() { + return __EMPTY_NODE; + } + static set __EMPTY_NODE(val) { + __EMPTY_NODE = val; + } + compare(a, b) { + return nameCompare(a.name, b.name); + } + isDefinedOn(node) { + // We could probably return true here (since every node has a key), but it's never called + // so just leaving unimplemented for now. + throw util.assertionError('KeyIndex.isDefinedOn not expected to be called.'); + } + indexedValueChanged(oldNode, newNode) { + return false; // The key for a node never changes. + } + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } + maxPost() { + // TODO: This should really be created once and cached in a static property, but + // NamedNode isn't defined yet, so I can't use it in a static. Bleh. + return new NamedNode(MAX_NAME, __EMPTY_NODE); + } + makePost(indexValue, name) { + util.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.'); + // We just use empty node, but it'll never be compared, since our comparator only looks at name. + return new NamedNode(indexValue, __EMPTY_NODE); + } + /** + * @returns String representation for inclusion in a query spec + */ + toString() { + return '.key'; + } +} +const KEY_INDEX = new KeyIndex(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An iterator over an LLRBNode. + */ +class SortedMapIterator { + /** + * @param node - Node to iterate. + * @param isReverse_ - Whether or not to iterate in reverse + */ + constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) { + this.isReverse_ = isReverse_; + this.resultGenerator_ = resultGenerator_; + this.nodeStack_ = []; + let cmp = 1; + while (!node.isEmpty()) { + node = node; + cmp = startKey ? comparator(node.key, startKey) : 1; + // flip the comparison if we're going in reverse + if (isReverse_) { + cmp *= -1; + } + if (cmp < 0) { + // This node is less than our start key. ignore it + if (this.isReverse_) { + node = node.left; + } + else { + node = node.right; + } + } + else if (cmp === 0) { + // This node is exactly equal to our start key. Push it on the stack, but stop iterating; + this.nodeStack_.push(node); + break; + } + else { + // This node is greater than our start key, add it to the stack and move to the next one + this.nodeStack_.push(node); + if (this.isReverse_) { + node = node.right; + } + else { + node = node.left; + } + } + } + } + getNext() { + if (this.nodeStack_.length === 0) { + return null; + } + let node = this.nodeStack_.pop(); + let result; + if (this.resultGenerator_) { + result = this.resultGenerator_(node.key, node.value); + } + else { + result = { key: node.key, value: node.value }; + } + if (this.isReverse_) { + node = node.left; + while (!node.isEmpty()) { + this.nodeStack_.push(node); + node = node.right; + } + } + else { + node = node.right; + while (!node.isEmpty()) { + this.nodeStack_.push(node); + node = node.left; + } + } + return result; + } + hasNext() { + return this.nodeStack_.length > 0; + } + peek() { + if (this.nodeStack_.length === 0) { + return null; + } + const node = this.nodeStack_[this.nodeStack_.length - 1]; + if (this.resultGenerator_) { + return this.resultGenerator_(node.key, node.value); + } + else { + return { key: node.key, value: node.value }; + } + } +} +/** + * Represents a node in a Left-leaning Red-Black tree. + */ +class LLRBNode { + /** + * @param key - Key associated with this node. + * @param value - Value associated with this node. + * @param color - Whether this node is red. + * @param left - Left child. + * @param right - Right child. + */ + constructor(key, value, color, left, right) { + this.key = key; + this.value = value; + this.color = color != null ? color : LLRBNode.RED; + this.left = + left != null ? left : SortedMap.EMPTY_NODE; + this.right = + right != null ? right : SortedMap.EMPTY_NODE; + } + /** + * Returns a copy of the current node, optionally replacing pieces of it. + * + * @param key - New key for the node, or null. + * @param value - New value for the node, or null. + * @param color - New color for the node, or null. + * @param left - New left child for the node, or null. + * @param right - New right child for the node, or null. + * @returns The node copy. + */ + copy(key, value, color, left, right) { + return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right); + } + /** + * @returns The total number of nodes in the tree. + */ + count() { + return this.left.count() + 1 + this.right.count(); + } + /** + * @returns True if the tree is empty. + */ + isEmpty() { + return false; + } + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action) { + return (this.left.inorderTraversal(action) || + !!action(this.key, this.value) || + this.right.inorderTraversal(action)); + } + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action) { + return (this.right.reverseTraversal(action) || + action(this.key, this.value) || + this.left.reverseTraversal(action)); + } + /** + * @returns The minimum node in the tree. + */ + min_() { + if (this.left.isEmpty()) { + return this; + } + else { + return this.left.min_(); + } + } + /** + * @returns The maximum key in the tree. + */ + minKey() { + return this.min_().key; + } + /** + * @returns The maximum key in the tree. + */ + maxKey() { + if (this.right.isEmpty()) { + return this.key; + } + else { + return this.right.maxKey(); + } + } + /** + * @param key - Key to insert. + * @param value - Value to insert. + * @param comparator - Comparator. + * @returns New tree, with the key/value added. + */ + insert(key, value, comparator) { + let n = this; + const cmp = comparator(key, n.key); + if (cmp < 0) { + n = n.copy(null, null, null, n.left.insert(key, value, comparator), null); + } + else if (cmp === 0) { + n = n.copy(null, value, null, null, null); + } + else { + n = n.copy(null, null, null, null, n.right.insert(key, value, comparator)); + } + return n.fixUp_(); + } + /** + * @returns New tree, with the minimum key removed. + */ + removeMin_() { + if (this.left.isEmpty()) { + return SortedMap.EMPTY_NODE; + } + let n = this; + if (!n.left.isRed_() && !n.left.left.isRed_()) { + n = n.moveRedLeft_(); + } + n = n.copy(null, null, null, n.left.removeMin_(), null); + return n.fixUp_(); + } + /** + * @param key - The key of the item to remove. + * @param comparator - Comparator. + * @returns New tree, with the specified item removed. + */ + remove(key, comparator) { + let n, smallest; + n = this; + if (comparator(key, n.key) < 0) { + if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) { + n = n.moveRedLeft_(); + } + n = n.copy(null, null, null, n.left.remove(key, comparator), null); + } + else { + if (n.left.isRed_()) { + n = n.rotateRight_(); + } + if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) { + n = n.moveRedRight_(); + } + if (comparator(key, n.key) === 0) { + if (n.right.isEmpty()) { + return SortedMap.EMPTY_NODE; + } + else { + smallest = n.right.min_(); + n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_()); + } + } + n = n.copy(null, null, null, null, n.right.remove(key, comparator)); + } + return n.fixUp_(); + } + /** + * @returns Whether this is a RED node. + */ + isRed_() { + return this.color; + } + /** + * @returns New tree after performing any needed rotations. + */ + fixUp_() { + let n = this; + if (n.right.isRed_() && !n.left.isRed_()) { + n = n.rotateLeft_(); + } + if (n.left.isRed_() && n.left.left.isRed_()) { + n = n.rotateRight_(); + } + if (n.left.isRed_() && n.right.isRed_()) { + n = n.colorFlip_(); + } + return n; + } + /** + * @returns New tree, after moveRedLeft. + */ + moveRedLeft_() { + let n = this.colorFlip_(); + if (n.right.left.isRed_()) { + n = n.copy(null, null, null, null, n.right.rotateRight_()); + n = n.rotateLeft_(); + n = n.colorFlip_(); + } + return n; + } + /** + * @returns New tree, after moveRedRight. + */ + moveRedRight_() { + let n = this.colorFlip_(); + if (n.left.left.isRed_()) { + n = n.rotateRight_(); + n = n.colorFlip_(); + } + return n; + } + /** + * @returns New tree, after rotateLeft. + */ + rotateLeft_() { + const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, nl, null); + } + /** + * @returns New tree, after rotateRight. + */ + rotateRight_() { + const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, nr); + } + /** + * @returns Newt ree, after colorFlip. + */ + colorFlip_() { + const left = this.left.copy(null, null, !this.left.color, null, null); + const right = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, left, right); + } + /** + * For testing. + * + * @returns True if all is well. + */ + checkMaxDepth_() { + const blackDepth = this.check_(); + return Math.pow(2.0, blackDepth) <= this.count() + 1; + } + check_() { + if (this.isRed_() && this.left.isRed_()) { + throw new Error('Red node has red child(' + this.key + ',' + this.value + ')'); + } + if (this.right.isRed_()) { + throw new Error('Right child of (' + this.key + ',' + this.value + ') is red'); + } + const blackDepth = this.left.check_(); + if (blackDepth !== this.right.check_()) { + throw new Error('Black depths differ'); + } + else { + return blackDepth + (this.isRed_() ? 0 : 1); + } + } +} +LLRBNode.RED = true; +LLRBNode.BLACK = false; +/** + * Represents an empty node (a leaf node in the Red-Black Tree). + */ +class LLRBEmptyNode { + /** + * Returns a copy of the current node. + * + * @returns The node copy. + */ + copy(key, value, color, left, right) { + return this; + } + /** + * Returns a copy of the tree, with the specified key/value added. + * + * @param key - Key to be added. + * @param value - Value to be added. + * @param comparator - Comparator. + * @returns New tree, with item added. + */ + insert(key, value, comparator) { + return new LLRBNode(key, value, null); + } + /** + * Returns a copy of the tree, with the specified key removed. + * + * @param key - The key to remove. + * @param comparator - Comparator. + * @returns New tree, with item removed. + */ + remove(key, comparator) { + return this; + } + /** + * @returns The total number of nodes in the tree. + */ + count() { + return 0; + } + /** + * @returns True if the tree is empty. + */ + isEmpty() { + return true; + } + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + inorderTraversal(action) { + return false; + } + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action) { + return false; + } + minKey() { + return null; + } + maxKey() { + return null; + } + check_() { + return 0; + } + /** + * @returns Whether this node is red. + */ + isRed_() { + return false; + } +} +/** + * An immutable sorted map implementation, based on a Left-leaning Red-Black + * tree. + */ +class SortedMap { + /** + * @param comparator_ - Key comparator. + * @param root_ - Optional root node for the map. + */ + constructor(comparator_, root_ = SortedMap.EMPTY_NODE) { + this.comparator_ = comparator_; + this.root_ = root_; + } + /** + * Returns a copy of the map, with the specified key/value added or replaced. + * (TODO: We should perhaps rename this method to 'put') + * + * @param key - Key to be added. + * @param value - Value to be added. + * @returns New map, with item added. + */ + insert(key, value) { + return new SortedMap(this.comparator_, this.root_ + .insert(key, value, this.comparator_) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + /** + * Returns a copy of the map, with the specified key removed. + * + * @param key - The key to remove. + * @returns New map, with item removed. + */ + remove(key) { + return new SortedMap(this.comparator_, this.root_ + .remove(key, this.comparator_) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + /** + * Returns the value of the node with the given key, or null. + * + * @param key - The key to look up. + * @returns The value of the node with the given key, or null if the + * key doesn't exist. + */ + get(key) { + let cmp; + let node = this.root_; + while (!node.isEmpty()) { + cmp = this.comparator_(key, node.key); + if (cmp === 0) { + return node.value; + } + else if (cmp < 0) { + node = node.left; + } + else if (cmp > 0) { + node = node.right; + } + } + return null; + } + /** + * Returns the key of the item *before* the specified key, or null if key is the first item. + * @param key - The key to find the predecessor of + * @returns The predecessor key. + */ + getPredecessorKey(key) { + let cmp, node = this.root_, rightParent = null; + while (!node.isEmpty()) { + cmp = this.comparator_(key, node.key); + if (cmp === 0) { + if (!node.left.isEmpty()) { + node = node.left; + while (!node.right.isEmpty()) { + node = node.right; + } + return node.key; + } + else if (rightParent) { + return rightParent.key; + } + else { + return null; // first item. + } + } + else if (cmp < 0) { + node = node.left; + } + else if (cmp > 0) { + rightParent = node; + node = node.right; + } + } + throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?'); + } + /** + * @returns True if the map is empty. + */ + isEmpty() { + return this.root_.isEmpty(); + } + /** + * @returns The total number of nodes in the map. + */ + count() { + return this.root_.count(); + } + /** + * @returns The minimum key in the map. + */ + minKey() { + return this.root_.minKey(); + } + /** + * @returns The maximum key in the map. + */ + maxKey() { + return this.root_.maxKey(); + } + /** + * Traverses the map in key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action) { + return this.root_.inorderTraversal(action); + } + /** + * Traverses the map in reverse key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns True if the traversal was aborted. + */ + reverseTraversal(action) { + return this.root_.reverseTraversal(action); + } + /** + * Returns an iterator over the SortedMap. + * @returns The iterator. + */ + getIterator(resultGenerator) { + return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator); + } + getIteratorFrom(key, resultGenerator) { + return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator); + } + getReverseIteratorFrom(key, resultGenerator) { + return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator); + } + getReverseIterator(resultGenerator) { + return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator); + } +} +/** + * Always use the same empty node, to reduce memory. + */ +SortedMap.EMPTY_NODE = new LLRBEmptyNode(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function NAME_ONLY_COMPARATOR(left, right) { + return nameCompare(left.name, right.name); +} +function NAME_COMPARATOR(left, right) { + return nameCompare(left, right); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let MAX_NODE$2; +function setMaxNode$1(val) { + MAX_NODE$2 = val; +} +const priorityHashText = function (priority) { + if (typeof priority === 'number') { + return 'number:' + doubleToIEEE754String(priority); + } + else { + return 'string:' + priority; + } +}; +/** + * Validates that a priority snapshot Node is valid. + */ +const validatePriorityNode = function (priorityNode) { + if (priorityNode.isLeafNode()) { + const val = priorityNode.val(); + util.assert(typeof val === 'string' || + typeof val === 'number' || + (typeof val === 'object' && util.contains(val, '.sv')), 'Priority must be a string or number.'); + } + else { + util.assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.'); + } + // Don't call getPriority() on MAX_NODE to avoid hitting assertion. + util.assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own."); +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let __childrenNodeConstructor; +/** + * LeafNode is a class for storing leaf nodes in a DataSnapshot. It + * implements Node and stores the value of the node (a string, + * number, or boolean) accessible via getValue(). + */ +class LeafNode { + static set __childrenNodeConstructor(val) { + __childrenNodeConstructor = val; + } + static get __childrenNodeConstructor() { + return __childrenNodeConstructor; + } + /** + * @param value_ - The value to store in this leaf node. The object type is + * possible in the event of a deferred value + * @param priorityNode_ - The priority of this node. + */ + constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) { + this.value_ = value_; + this.priorityNode_ = priorityNode_; + this.lazyHash_ = null; + util.assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value."); + validatePriorityNode(this.priorityNode_); + } + /** @inheritDoc */ + isLeafNode() { + return true; + } + /** @inheritDoc */ + getPriority() { + return this.priorityNode_; + } + /** @inheritDoc */ + updatePriority(newPriorityNode) { + return new LeafNode(this.value_, newPriorityNode); + } + /** @inheritDoc */ + getImmediateChild(childName) { + // Hack to treat priority as a regular child + if (childName === '.priority') { + return this.priorityNode_; + } + else { + return LeafNode.__childrenNodeConstructor.EMPTY_NODE; + } + } + /** @inheritDoc */ + getChild(path) { + if (pathIsEmpty(path)) { + return this; + } + else if (pathGetFront(path) === '.priority') { + return this.priorityNode_; + } + else { + return LeafNode.__childrenNodeConstructor.EMPTY_NODE; + } + } + hasChild() { + return false; + } + /** @inheritDoc */ + getPredecessorChildName(childName, childNode) { + return null; + } + /** @inheritDoc */ + updateImmediateChild(childName, newChildNode) { + if (childName === '.priority') { + return this.updatePriority(newChildNode); + } + else if (newChildNode.isEmpty() && childName !== '.priority') { + return this; + } + else { + return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_); + } + } + /** @inheritDoc */ + updateChild(path, newChildNode) { + const front = pathGetFront(path); + if (front === null) { + return newChildNode; + } + else if (newChildNode.isEmpty() && front !== '.priority') { + return this; + } + else { + util.assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path'); + return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode)); + } + } + /** @inheritDoc */ + isEmpty() { + return false; + } + /** @inheritDoc */ + numChildren() { + return 0; + } + /** @inheritDoc */ + forEachChild(index, action) { + return false; + } + val(exportFormat) { + if (exportFormat && !this.getPriority().isEmpty()) { + return { + '.value': this.getValue(), + '.priority': this.getPriority().val() + }; + } + else { + return this.getValue(); + } + } + /** @inheritDoc */ + hash() { + if (this.lazyHash_ === null) { + let toHash = ''; + if (!this.priorityNode_.isEmpty()) { + toHash += + 'priority:' + + priorityHashText(this.priorityNode_.val()) + + ':'; + } + const type = typeof this.value_; + toHash += type + ':'; + if (type === 'number') { + toHash += doubleToIEEE754String(this.value_); + } + else { + toHash += this.value_; + } + this.lazyHash_ = sha1(toHash); + } + return this.lazyHash_; + } + /** + * Returns the value of the leaf node. + * @returns The value of the node. + */ + getValue() { + return this.value_; + } + compareTo(other) { + if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) { + return 1; + } + else if (other instanceof LeafNode.__childrenNodeConstructor) { + return -1; + } + else { + util.assert(other.isLeafNode(), 'Unknown node type'); + return this.compareToLeafNode_(other); + } + } + /** + * Comparison specifically for two leaf nodes + */ + compareToLeafNode_(otherLeaf) { + const otherLeafType = typeof otherLeaf.value_; + const thisLeafType = typeof this.value_; + const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType); + const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType); + util.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType); + util.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType); + if (otherIndex === thisIndex) { + // Same type, compare values + if (thisLeafType === 'object') { + // Deferred value nodes are all equal, but we should also never get to this point... + return 0; + } + else { + // Note that this works because true > false, all others are number or string comparisons + if (this.value_ < otherLeaf.value_) { + return -1; + } + else if (this.value_ === otherLeaf.value_) { + return 0; + } + else { + return 1; + } + } + } + else { + return thisIndex - otherIndex; + } + } + withIndex() { + return this; + } + isIndexed() { + return true; + } + equals(other) { + if (other === this) { + return true; + } + else if (other.isLeafNode()) { + const otherLeaf = other; + return (this.value_ === otherLeaf.value_ && + this.priorityNode_.equals(otherLeaf.priorityNode_)); + } + else { + return false; + } + } +} +/** + * The sort order for comparing leaf nodes of different types. If two leaf nodes have + * the same type, the comparison falls back to their value + */ +LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string']; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let nodeFromJSON$1; +let MAX_NODE$1; +function setNodeFromJSON(val) { + nodeFromJSON$1 = val; +} +function setMaxNode(val) { + MAX_NODE$1 = val; +} +class PriorityIndex extends Index { + compare(a, b) { + const aPriority = a.node.getPriority(); + const bPriority = b.node.getPriority(); + const indexCmp = aPriority.compareTo(bPriority); + if (indexCmp === 0) { + return nameCompare(a.name, b.name); + } + else { + return indexCmp; + } + } + isDefinedOn(node) { + return !node.getPriority().isEmpty(); + } + indexedValueChanged(oldNode, newNode) { + return !oldNode.getPriority().equals(newNode.getPriority()); + } + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } + maxPost() { + return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1)); + } + makePost(indexValue, name) { + const priorityNode = nodeFromJSON$1(indexValue); + return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode)); + } + /** + * @returns String representation for inclusion in a query spec + */ + toString() { + return '.priority'; + } +} +const PRIORITY_INDEX = new PriorityIndex(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_2 = Math.log(2); +class Base12Num { + constructor(length) { + const logBase2 = (num) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + parseInt((Math.log(num) / LOG_2), 10); + const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2); + this.count = logBase2(length + 1); + this.current_ = this.count - 1; + const mask = bitMask(this.count); + this.bits_ = (length + 1) & mask; + } + nextBitIsOne() { + //noinspection JSBitwiseOperatorUsage + const result = !(this.bits_ & (0x1 << this.current_)); + this.current_--; + return result; + } +} +/** + * Takes a list of child nodes and constructs a SortedSet using the given comparison + * function + * + * Uses the algorithm described in the paper linked here: + * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458 + * + * @param childList - Unsorted list of children + * @param cmp - The comparison method to be used + * @param keyFn - An optional function to extract K from a node wrapper, if K's + * type is not NamedNode + * @param mapSortFn - An optional override for comparator used by the generated sorted map + */ +const buildChildSet = function (childList, cmp, keyFn, mapSortFn) { + childList.sort(cmp); + const buildBalancedTree = function (low, high) { + const length = high - low; + let namedNode; + let key; + if (length === 0) { + return null; + } + else if (length === 1) { + namedNode = childList[low]; + key = keyFn ? keyFn(namedNode) : namedNode; + return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null); + } + else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const middle = parseInt((length / 2), 10) + low; + const left = buildBalancedTree(low, middle); + const right = buildBalancedTree(middle + 1, high); + namedNode = childList[middle]; + key = keyFn ? keyFn(namedNode) : namedNode; + return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right); + } + }; + const buildFrom12Array = function (base12) { + let node = null; + let root = null; + let index = childList.length; + const buildPennant = function (chunkSize, color) { + const low = index - chunkSize; + const high = index; + index -= chunkSize; + const childTree = buildBalancedTree(low + 1, high); + const namedNode = childList[low]; + const key = keyFn ? keyFn(namedNode) : namedNode; + attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree)); + }; + const attachPennant = function (pennant) { + if (node) { + node.left = pennant; + node = pennant; + } + else { + root = pennant; + node = pennant; + } + }; + for (let i = 0; i < base12.count; ++i) { + const isOne = base12.nextBitIsOne(); + // The number of nodes taken in each slice is 2^(arr.length - (i + 1)) + const chunkSize = Math.pow(2, base12.count - (i + 1)); + if (isOne) { + buildPennant(chunkSize, LLRBNode.BLACK); + } + else { + // current == 2 + buildPennant(chunkSize, LLRBNode.BLACK); + buildPennant(chunkSize, LLRBNode.RED); + } + } + return root; + }; + const base12 = new Base12Num(childList.length); + const root = buildFrom12Array(base12); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return new SortedMap(mapSortFn || cmp, root); +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let _defaultIndexMap; +const fallbackObject = {}; +class IndexMap { + /** + * The default IndexMap for nodes without a priority + */ + static get Default() { + util.assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded'); + _defaultIndexMap = + _defaultIndexMap || + new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX }); + return _defaultIndexMap; + } + constructor(indexes_, indexSet_) { + this.indexes_ = indexes_; + this.indexSet_ = indexSet_; + } + get(indexKey) { + const sortedMap = util.safeGet(this.indexes_, indexKey); + if (!sortedMap) { + throw new Error('No index defined for ' + indexKey); + } + if (sortedMap instanceof SortedMap) { + return sortedMap; + } + else { + // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the + // regular child map + return null; + } + } + hasIndex(indexDefinition) { + return util.contains(this.indexSet_, indexDefinition.toString()); + } + addIndex(indexDefinition, existingChildren) { + util.assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap."); + const childList = []; + let sawIndexedValue = false; + const iter = existingChildren.getIterator(NamedNode.Wrap); + let next = iter.getNext(); + while (next) { + sawIndexedValue = + sawIndexedValue || indexDefinition.isDefinedOn(next.node); + childList.push(next); + next = iter.getNext(); + } + let newIndex; + if (sawIndexedValue) { + newIndex = buildChildSet(childList, indexDefinition.getCompare()); + } + else { + newIndex = fallbackObject; + } + const indexName = indexDefinition.toString(); + const newIndexSet = { ...this.indexSet_ }; + newIndexSet[indexName] = indexDefinition; + const newIndexes = { ...this.indexes_ }; + newIndexes[indexName] = newIndex; + return new IndexMap(newIndexes, newIndexSet); + } + /** + * Ensure that this node is properly tracked in any indexes that we're maintaining + */ + addToIndexes(namedNode, existingChildren) { + const newIndexes = util.map(this.indexes_, (indexedChildren, indexName) => { + const index = util.safeGet(this.indexSet_, indexName); + util.assert(index, 'Missing index implementation for ' + indexName); + if (indexedChildren === fallbackObject) { + // Check to see if we need to index everything + if (index.isDefinedOn(namedNode.node)) { + // We need to build this index + const childList = []; + const iter = existingChildren.getIterator(NamedNode.Wrap); + let next = iter.getNext(); + while (next) { + if (next.name !== namedNode.name) { + childList.push(next); + } + next = iter.getNext(); + } + childList.push(namedNode); + return buildChildSet(childList, index.getCompare()); + } + else { + // No change, this remains a fallback + return fallbackObject; + } + } + else { + const existingSnap = existingChildren.get(namedNode.name); + let newChildren = indexedChildren; + if (existingSnap) { + newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap)); + } + return newChildren.insert(namedNode, namedNode.node); + } + }); + return new IndexMap(newIndexes, this.indexSet_); + } + /** + * Create a new IndexMap instance with the given value removed + */ + removeFromIndexes(namedNode, existingChildren) { + const newIndexes = util.map(this.indexes_, (indexedChildren) => { + if (indexedChildren === fallbackObject) { + // This is the fallback. Just return it, nothing to do in this case + return indexedChildren; + } + else { + const existingSnap = existingChildren.get(namedNode.name); + if (existingSnap) { + return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap)); + } + else { + // No record of this child + return indexedChildren; + } + } + }); + return new IndexMap(newIndexes, this.indexSet_); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO: For memory savings, don't store priorityNode_ if it's empty. +let EMPTY_NODE; +/** + * ChildrenNode is a class for storing internal nodes in a DataSnapshot + * (i.e. nodes with children). It implements Node and stores the + * list of children in the children property, sorted by child name. + */ +class ChildrenNode { + static get EMPTY_NODE() { + return (EMPTY_NODE || + (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default))); + } + /** + * @param children_ - List of children of this node.. + * @param priorityNode_ - The priority of this node (as a snapshot node). + */ + constructor(children_, priorityNode_, indexMap_) { + this.children_ = children_; + this.priorityNode_ = priorityNode_; + this.indexMap_ = indexMap_; + this.lazyHash_ = null; + /** + * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use + * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own + * class instead of an empty ChildrenNode. + */ + if (this.priorityNode_) { + validatePriorityNode(this.priorityNode_); + } + if (this.children_.isEmpty()) { + util.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority'); + } + } + /** @inheritDoc */ + isLeafNode() { + return false; + } + /** @inheritDoc */ + getPriority() { + return this.priorityNode_ || EMPTY_NODE; + } + /** @inheritDoc */ + updatePriority(newPriorityNode) { + if (this.children_.isEmpty()) { + // Don't allow priorities on empty nodes + return this; + } + else { + return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_); + } + } + /** @inheritDoc */ + getImmediateChild(childName) { + // Hack to treat priority as a regular child + if (childName === '.priority') { + return this.getPriority(); + } + else { + const child = this.children_.get(childName); + return child === null ? EMPTY_NODE : child; + } + } + /** @inheritDoc */ + getChild(path) { + const front = pathGetFront(path); + if (front === null) { + return this; + } + return this.getImmediateChild(front).getChild(pathPopFront(path)); + } + /** @inheritDoc */ + hasChild(childName) { + return this.children_.get(childName) !== null; + } + /** @inheritDoc */ + updateImmediateChild(childName, newChildNode) { + util.assert(newChildNode, 'We should always be passing snapshot nodes'); + if (childName === '.priority') { + return this.updatePriority(newChildNode); + } + else { + const namedNode = new NamedNode(childName, newChildNode); + let newChildren, newIndexMap; + if (newChildNode.isEmpty()) { + newChildren = this.children_.remove(childName); + newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_); + } + else { + newChildren = this.children_.insert(childName, newChildNode); + newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_); + } + const newPriority = newChildren.isEmpty() + ? EMPTY_NODE + : this.priorityNode_; + return new ChildrenNode(newChildren, newPriority, newIndexMap); + } + } + /** @inheritDoc */ + updateChild(path, newChildNode) { + const front = pathGetFront(path); + if (front === null) { + return newChildNode; + } + else { + util.assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path'); + const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode); + return this.updateImmediateChild(front, newImmediateChild); + } + } + /** @inheritDoc */ + isEmpty() { + return this.children_.isEmpty(); + } + /** @inheritDoc */ + numChildren() { + return this.children_.count(); + } + /** @inheritDoc */ + val(exportFormat) { + if (this.isEmpty()) { + return null; + } + const obj = {}; + let numKeys = 0, maxKey = 0, allIntegerKeys = true; + this.forEachChild(PRIORITY_INDEX, (key, childNode) => { + obj[key] = childNode.val(exportFormat); + numKeys++; + if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) { + maxKey = Math.max(maxKey, Number(key)); + } + else { + allIntegerKeys = false; + } + }); + if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) { + // convert to array. + const array = []; + // eslint-disable-next-line guard-for-in + for (const key in obj) { + array[key] = obj[key]; + } + return array; + } + else { + if (exportFormat && !this.getPriority().isEmpty()) { + obj['.priority'] = this.getPriority().val(); + } + return obj; + } + } + /** @inheritDoc */ + hash() { + if (this.lazyHash_ === null) { + let toHash = ''; + if (!this.getPriority().isEmpty()) { + toHash += + 'priority:' + + priorityHashText(this.getPriority().val()) + + ':'; + } + this.forEachChild(PRIORITY_INDEX, (key, childNode) => { + const childHash = childNode.hash(); + if (childHash !== '') { + toHash += ':' + key + ':' + childHash; + } + }); + this.lazyHash_ = toHash === '' ? '' : sha1(toHash); + } + return this.lazyHash_; + } + /** @inheritDoc */ + getPredecessorChildName(childName, childNode, index) { + const idx = this.resolveIndex_(index); + if (idx) { + const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode)); + return predecessor ? predecessor.name : null; + } + else { + return this.children_.getPredecessorKey(childName); + } + } + getFirstChildName(indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + const minKey = idx.minKey(); + return minKey && minKey.name; + } + else { + return this.children_.minKey(); + } + } + getFirstChild(indexDefinition) { + const minKey = this.getFirstChildName(indexDefinition); + if (minKey) { + return new NamedNode(minKey, this.children_.get(minKey)); + } + else { + return null; + } + } + /** + * Given an index, return the key name of the largest value we have, according to that index + */ + getLastChildName(indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + const maxKey = idx.maxKey(); + return maxKey && maxKey.name; + } + else { + return this.children_.maxKey(); + } + } + getLastChild(indexDefinition) { + const maxKey = this.getLastChildName(indexDefinition); + if (maxKey) { + return new NamedNode(maxKey, this.children_.get(maxKey)); + } + else { + return null; + } + } + forEachChild(index, action) { + const idx = this.resolveIndex_(index); + if (idx) { + return idx.inorderTraversal(wrappedNode => { + return action(wrappedNode.name, wrappedNode.node); + }); + } + else { + return this.children_.inorderTraversal(action); + } + } + getIterator(indexDefinition) { + return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition); + } + getIteratorFrom(startPost, indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + return idx.getIteratorFrom(startPost, key => key); + } + else { + const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap); + let next = iterator.peek(); + while (next != null && indexDefinition.compare(next, startPost) < 0) { + iterator.getNext(); + next = iterator.peek(); + } + return iterator; + } + } + getReverseIterator(indexDefinition) { + return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition); + } + getReverseIteratorFrom(endPost, indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + return idx.getReverseIteratorFrom(endPost, key => { + return key; + }); + } + else { + const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap); + let next = iterator.peek(); + while (next != null && indexDefinition.compare(next, endPost) > 0) { + iterator.getNext(); + next = iterator.peek(); + } + return iterator; + } + } + compareTo(other) { + if (this.isEmpty()) { + if (other.isEmpty()) { + return 0; + } + else { + return -1; + } + } + else if (other.isLeafNode() || other.isEmpty()) { + return 1; + } + else if (other === MAX_NODE) { + return -1; + } + else { + // Must be another node with children. + return 0; + } + } + withIndex(indexDefinition) { + if (indexDefinition === KEY_INDEX || + this.indexMap_.hasIndex(indexDefinition)) { + return this; + } + else { + const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_); + return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap); + } + } + isIndexed(index) { + return index === KEY_INDEX || this.indexMap_.hasIndex(index); + } + equals(other) { + if (other === this) { + return true; + } + else if (other.isLeafNode()) { + return false; + } + else { + const otherChildrenNode = other; + if (!this.getPriority().equals(otherChildrenNode.getPriority())) { + return false; + } + else if (this.children_.count() === otherChildrenNode.children_.count()) { + const thisIter = this.getIterator(PRIORITY_INDEX); + const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX); + let thisCurrent = thisIter.getNext(); + let otherCurrent = otherIter.getNext(); + while (thisCurrent && otherCurrent) { + if (thisCurrent.name !== otherCurrent.name || + !thisCurrent.node.equals(otherCurrent.node)) { + return false; + } + thisCurrent = thisIter.getNext(); + otherCurrent = otherIter.getNext(); + } + return thisCurrent === null && otherCurrent === null; + } + else { + return false; + } + } + } + /** + * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used + * instead. + * + */ + resolveIndex_(indexDefinition) { + if (indexDefinition === KEY_INDEX) { + return null; + } + else { + return this.indexMap_.get(indexDefinition.toString()); + } + } +} +ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/; +class MaxNode extends ChildrenNode { + constructor() { + super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default); + } + compareTo(other) { + if (other === this) { + return 0; + } + else { + return 1; + } + } + equals(other) { + // Not that we every compare it, but MAX_NODE is only ever equal to itself + return other === this; + } + getPriority() { + return this; + } + getImmediateChild(childName) { + return ChildrenNode.EMPTY_NODE; + } + isEmpty() { + return false; + } +} +/** + * Marker that will sort higher than any other snapshot. + */ +const MAX_NODE = new MaxNode(); +Object.defineProperties(NamedNode, { + MIN: { + value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE) + }, + MAX: { + value: new NamedNode(MAX_NAME, MAX_NODE) + } +}); +/** + * Reference Extensions + */ +KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE; +LeafNode.__childrenNodeConstructor = ChildrenNode; +setMaxNode$1(MAX_NODE); +setMaxNode(MAX_NODE); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const USE_HINZE = true; +/** + * Constructs a snapshot node representing the passed JSON and returns it. + * @param json - JSON to create a node for. + * @param priority - Optional priority to use. This will be ignored if the + * passed JSON contains a .priority property. + */ +function nodeFromJSON(json, priority = null) { + if (json === null) { + return ChildrenNode.EMPTY_NODE; + } + if (typeof json === 'object' && '.priority' in json) { + priority = json['.priority']; + } + util.assert(priority === null || + typeof priority === 'string' || + typeof priority === 'number' || + (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority); + if (typeof json === 'object' && '.value' in json && json['.value'] !== null) { + json = json['.value']; + } + // Valid leaf nodes include non-objects or server-value wrapper objects + if (typeof json !== 'object' || '.sv' in json) { + const jsonLeaf = json; + return new LeafNode(jsonLeaf, nodeFromJSON(priority)); + } + if (!(json instanceof Array) && USE_HINZE) { + const children = []; + let childrenHavePriority = false; + const hinzeJsonObj = json; + each(hinzeJsonObj, (key, child) => { + if (key.substring(0, 1) !== '.') { + // Ignore metadata nodes + const childNode = nodeFromJSON(child); + if (!childNode.isEmpty()) { + childrenHavePriority = + childrenHavePriority || !childNode.getPriority().isEmpty(); + children.push(new NamedNode(key, childNode)); + } + } + }); + if (children.length === 0) { + return ChildrenNode.EMPTY_NODE; + } + const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR); + if (childrenHavePriority) { + const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare()); + return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX })); + } + else { + return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default); + } + } + else { + let node = ChildrenNode.EMPTY_NODE; + each(json, (key, childData) => { + if (util.contains(json, key)) { + if (key.substring(0, 1) !== '.') { + // ignore metadata nodes. + const childNode = nodeFromJSON(childData); + if (childNode.isLeafNode() || !childNode.isEmpty()) { + node = node.updateImmediateChild(key, childNode); + } + } + } + }); + return node.updatePriority(nodeFromJSON(priority)); + } +} +setNodeFromJSON(nodeFromJSON); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class PathIndex extends Index { + constructor(indexPath_) { + super(); + this.indexPath_ = indexPath_; + util.assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key"); + } + extractChild(snap) { + return snap.getChild(this.indexPath_); + } + isDefinedOn(node) { + return !node.getChild(this.indexPath_).isEmpty(); + } + compare(a, b) { + const aChild = this.extractChild(a.node); + const bChild = this.extractChild(b.node); + const indexCmp = aChild.compareTo(bChild); + if (indexCmp === 0) { + return nameCompare(a.name, b.name); + } + else { + return indexCmp; + } + } + makePost(indexValue, name) { + const valueNode = nodeFromJSON(indexValue); + const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode); + return new NamedNode(name, node); + } + maxPost() { + const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE); + return new NamedNode(MAX_NAME, node); + } + toString() { + return pathSlice(this.indexPath_, 0).join('/'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ValueIndex extends Index { + compare(a, b) { + const indexCmp = a.node.compareTo(b.node); + if (indexCmp === 0) { + return nameCompare(a.name, b.name); + } + else { + return indexCmp; + } + } + isDefinedOn(node) { + return true; + } + indexedValueChanged(oldNode, newNode) { + return !oldNode.equals(newNode); + } + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } + maxPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MAX; + } + makePost(indexValue, name) { + const valueNode = nodeFromJSON(indexValue); + return new NamedNode(name, valueNode); + } + /** + * @returns String representation for inclusion in a query spec + */ + toString() { + return '.value'; + } +} +const VALUE_INDEX = new ValueIndex(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function changeValue(snapshotNode) { + return { type: "value" /* ChangeType.VALUE */, snapshotNode }; +} +function changeChildAdded(childName, snapshotNode) { + return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode, childName }; +} +function changeChildRemoved(childName, snapshotNode) { + return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode, childName }; +} +function changeChildChanged(childName, snapshotNode, oldSnap) { + return { + type: "child_changed" /* ChangeType.CHILD_CHANGED */, + snapshotNode, + childName, + oldSnap + }; +} +function changeChildMoved(childName, snapshotNode) { + return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode, childName }; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Doesn't really filter nodes but applies an index to the node and keeps track of any changes + */ +class IndexedFilter { + constructor(index_) { + this.index_ = index_; + } + updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) { + util.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated'); + const oldChild = snap.getImmediateChild(key); + // Check if anything actually changed. + if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) { + // There's an edge case where a child can enter or leave the view because affectedPath was set to null. + // In this case, affectedPath will appear null in both the old and new snapshots. So we need + // to avoid treating these cases as "nothing changed." + if (oldChild.isEmpty() === newChild.isEmpty()) { + // Nothing changed. + // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it. + //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.'); + return snap; + } + } + if (optChangeAccumulator != null) { + if (newChild.isEmpty()) { + if (snap.hasChild(key)) { + optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild)); + } + else { + util.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node'); + } + } + else if (oldChild.isEmpty()) { + optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild)); + } + else { + optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild)); + } + } + if (snap.isLeafNode() && newChild.isEmpty()) { + return snap; + } + else { + // Make sure the node is indexed + return snap.updateImmediateChild(key, newChild).withIndex(this.index_); + } + } + updateFullNode(oldSnap, newSnap, optChangeAccumulator) { + if (optChangeAccumulator != null) { + if (!oldSnap.isLeafNode()) { + oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => { + if (!newSnap.hasChild(key)) { + optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode)); + } + }); + } + if (!newSnap.isLeafNode()) { + newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => { + if (oldSnap.hasChild(key)) { + const oldChild = oldSnap.getImmediateChild(key); + if (!oldChild.equals(childNode)) { + optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild)); + } + } + else { + optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode)); + } + }); + } + } + return newSnap.withIndex(this.index_); + } + updatePriority(oldSnap, newPriority) { + if (oldSnap.isEmpty()) { + return ChildrenNode.EMPTY_NODE; + } + else { + return oldSnap.updatePriority(newPriority); + } + } + filtersNodes() { + return false; + } + getIndexedFilter() { + return this; + } + getIndex() { + return this.index_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node + */ +class RangedFilter { + constructor(params) { + this.indexedFilter_ = new IndexedFilter(params.getIndex()); + this.index_ = params.getIndex(); + this.startPost_ = RangedFilter.getStartPost_(params); + this.endPost_ = RangedFilter.getEndPost_(params); + this.startIsInclusive_ = !params.startAfterSet_; + this.endIsInclusive_ = !params.endBeforeSet_; + } + getStartPost() { + return this.startPost_; + } + getEndPost() { + return this.endPost_; + } + matches(node) { + const isWithinStart = this.startIsInclusive_ + ? this.index_.compare(this.getStartPost(), node) <= 0 + : this.index_.compare(this.getStartPost(), node) < 0; + const isWithinEnd = this.endIsInclusive_ + ? this.index_.compare(node, this.getEndPost()) <= 0 + : this.index_.compare(node, this.getEndPost()) < 0; + return isWithinStart && isWithinEnd; + } + updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) { + if (!this.matches(new NamedNode(key, newChild))) { + newChild = ChildrenNode.EMPTY_NODE; + } + return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator); + } + updateFullNode(oldSnap, newSnap, optChangeAccumulator) { + if (newSnap.isLeafNode()) { + // Make sure we have a children node with the correct index, not a leaf node; + newSnap = ChildrenNode.EMPTY_NODE; + } + let filtered = newSnap.withIndex(this.index_); + // Don't support priorities on queries + filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE); + const self = this; + newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => { + if (!self.matches(new NamedNode(key, childNode))) { + filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE); + } + }); + return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator); + } + updatePriority(oldSnap, newPriority) { + // Don't support priorities on queries + return oldSnap; + } + filtersNodes() { + return true; + } + getIndexedFilter() { + return this.indexedFilter_; + } + getIndex() { + return this.index_; + } + static getStartPost_(params) { + if (params.hasStart()) { + const startName = params.getIndexStartName(); + return params.getIndex().makePost(params.getIndexStartValue(), startName); + } + else { + return params.getIndex().minPost(); + } + } + static getEndPost_(params) { + if (params.hasEnd()) { + const endName = params.getIndexEndName(); + return params.getIndex().makePost(params.getIndexEndValue(), endName); + } + else { + return params.getIndex().maxPost(); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible + */ +class LimitedFilter { + constructor(params) { + this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node); + this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node); + this.withinStartPost = (node) => { + const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node); + return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0; + }; + this.withinEndPost = (node) => { + const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost()); + return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0; + }; + this.rangedFilter_ = new RangedFilter(params); + this.index_ = params.getIndex(); + this.limit_ = params.getLimit(); + this.reverse_ = !params.isViewFromLeft(); + this.startIsInclusive_ = !params.startAfterSet_; + this.endIsInclusive_ = !params.endBeforeSet_; + } + updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) { + if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) { + newChild = ChildrenNode.EMPTY_NODE; + } + if (snap.getImmediateChild(key).equals(newChild)) { + // No change + return snap; + } + else if (snap.numChildren() < this.limit_) { + return this.rangedFilter_ + .getIndexedFilter() + .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator); + } + else { + return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator); + } + } + updateFullNode(oldSnap, newSnap, optChangeAccumulator) { + let filtered; + if (newSnap.isLeafNode() || newSnap.isEmpty()) { + // Make sure we have a children node with the correct index, not a leaf node; + filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_); + } + else { + if (this.limit_ * 2 < newSnap.numChildren() && + newSnap.isIndexed(this.index_)) { + // Easier to build up a snapshot, since what we're given has more than twice the elements we want + filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_); + // anchor to the startPost, endPost, or last element as appropriate + let iterator; + if (this.reverse_) { + iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_); + } + else { + iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_); + } + let count = 0; + while (iterator.hasNext() && count < this.limit_) { + const next = iterator.getNext(); + if (!this.withinDirectionalStart(next)) { + // if we have not reached the start, skip to the next element + continue; + } + else if (!this.withinDirectionalEnd(next)) { + // if we have reached the end, stop adding elements + break; + } + else { + filtered = filtered.updateImmediateChild(next.name, next.node); + count++; + } + } + } + else { + // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one + filtered = newSnap.withIndex(this.index_); + // Don't support priorities on queries + filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE); + let iterator; + if (this.reverse_) { + iterator = filtered.getReverseIterator(this.index_); + } + else { + iterator = filtered.getIterator(this.index_); + } + let count = 0; + while (iterator.hasNext()) { + const next = iterator.getNext(); + const inRange = count < this.limit_ && + this.withinDirectionalStart(next) && + this.withinDirectionalEnd(next); + if (inRange) { + count++; + } + else { + filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE); + } + } + } + } + return this.rangedFilter_ + .getIndexedFilter() + .updateFullNode(oldSnap, filtered, optChangeAccumulator); + } + updatePriority(oldSnap, newPriority) { + // Don't support priorities on queries + return oldSnap; + } + filtersNodes() { + return true; + } + getIndexedFilter() { + return this.rangedFilter_.getIndexedFilter(); + } + getIndex() { + return this.index_; + } + fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) { + // TODO: rename all cache stuff etc to general snap terminology + let cmp; + if (this.reverse_) { + const indexCmp = this.index_.getCompare(); + cmp = (a, b) => indexCmp(b, a); + } + else { + cmp = this.index_.getCompare(); + } + const oldEventCache = snap; + util.assert(oldEventCache.numChildren() === this.limit_, ''); + const newChildNamedNode = new NamedNode(childKey, childSnap); + const windowBoundary = this.reverse_ + ? oldEventCache.getFirstChild(this.index_) + : oldEventCache.getLastChild(this.index_); + const inRange = this.rangedFilter_.matches(newChildNamedNode); + if (oldEventCache.hasChild(childKey)) { + const oldChildSnap = oldEventCache.getImmediateChild(childKey); + let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_); + while (nextChild != null && + (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) { + // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't + // been applied to the limited filter yet. Ignore this next child which will be updated later in + // the limited filter... + nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_); + } + const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode); + const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0; + if (remainsInWindow) { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap)); + } + return oldEventCache.updateImmediateChild(childKey, childSnap); + } + else { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap)); + } + const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE); + const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild); + if (nextChildInRange) { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node)); + } + return newEventCache.updateImmediateChild(nextChild.name, nextChild.node); + } + else { + return newEventCache; + } + } + } + else if (childSnap.isEmpty()) { + // we're deleting a node, but it was not in the window, so ignore it + return snap; + } + else if (inRange) { + if (cmp(windowBoundary, newChildNamedNode) >= 0) { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node)); + changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap)); + } + return oldEventCache + .updateImmediateChild(childKey, childSnap) + .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE); + } + else { + return snap; + } + } + else { + return snap; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a + * range to be returned for a particular location. It is assumed that validation of parameters is done at the + * user-facing API level, so it is not done here. + * + * @internal + */ +class QueryParams { + constructor() { + this.limitSet_ = false; + this.startSet_ = false; + this.startNameSet_ = false; + this.startAfterSet_ = false; // can only be true if startSet_ is true + this.endSet_ = false; + this.endNameSet_ = false; + this.endBeforeSet_ = false; // can only be true if endSet_ is true + this.limit_ = 0; + this.viewFrom_ = ''; + this.indexStartValue_ = null; + this.indexStartName_ = ''; + this.indexEndValue_ = null; + this.indexEndName_ = ''; + this.index_ = PRIORITY_INDEX; + } + hasStart() { + return this.startSet_; + } + /** + * @returns True if it would return from left. + */ + isViewFromLeft() { + if (this.viewFrom_ === '') { + // limit(), rather than limitToFirst or limitToLast was called. + // This means that only one of startSet_ and endSet_ is true. Use them + // to calculate which side of the view to anchor to. If neither is set, + // anchor to the end. + return this.startSet_; + } + else { + return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */; + } + } + /** + * Only valid to call if hasStart() returns true + */ + getIndexStartValue() { + util.assert(this.startSet_, 'Only valid if start has been set'); + return this.indexStartValue_; + } + /** + * Only valid to call if hasStart() returns true. + * Returns the starting key name for the range defined by these query parameters + */ + getIndexStartName() { + util.assert(this.startSet_, 'Only valid if start has been set'); + if (this.startNameSet_) { + return this.indexStartName_; + } + else { + return MIN_NAME; + } + } + hasEnd() { + return this.endSet_; + } + /** + * Only valid to call if hasEnd() returns true. + */ + getIndexEndValue() { + util.assert(this.endSet_, 'Only valid if end has been set'); + return this.indexEndValue_; + } + /** + * Only valid to call if hasEnd() returns true. + * Returns the end key name for the range defined by these query parameters + */ + getIndexEndName() { + util.assert(this.endSet_, 'Only valid if end has been set'); + if (this.endNameSet_) { + return this.indexEndName_; + } + else { + return MAX_NAME; + } + } + hasLimit() { + return this.limitSet_; + } + /** + * @returns True if a limit has been set and it has been explicitly anchored + */ + hasAnchoredLimit() { + return this.limitSet_ && this.viewFrom_ !== ''; + } + /** + * Only valid to call if hasLimit() returns true + */ + getLimit() { + util.assert(this.limitSet_, 'Only valid if limit has been set'); + return this.limit_; + } + getIndex() { + return this.index_; + } + loadsAllData() { + return !(this.startSet_ || this.endSet_ || this.limitSet_); + } + isDefault() { + return this.loadsAllData() && this.index_ === PRIORITY_INDEX; + } + copy() { + const copy = new QueryParams(); + copy.limitSet_ = this.limitSet_; + copy.limit_ = this.limit_; + copy.startSet_ = this.startSet_; + copy.startAfterSet_ = this.startAfterSet_; + copy.indexStartValue_ = this.indexStartValue_; + copy.startNameSet_ = this.startNameSet_; + copy.indexStartName_ = this.indexStartName_; + copy.endSet_ = this.endSet_; + copy.endBeforeSet_ = this.endBeforeSet_; + copy.indexEndValue_ = this.indexEndValue_; + copy.endNameSet_ = this.endNameSet_; + copy.indexEndName_ = this.indexEndName_; + copy.index_ = this.index_; + copy.viewFrom_ = this.viewFrom_; + return copy; + } +} +function queryParamsGetNodeFilter(queryParams) { + if (queryParams.loadsAllData()) { + return new IndexedFilter(queryParams.getIndex()); + } + else if (queryParams.hasLimit()) { + return new LimitedFilter(queryParams); + } + else { + return new RangedFilter(queryParams); + } +} +function queryParamsLimitToFirst(queryParams, newLimit) { + const newParams = queryParams.copy(); + newParams.limitSet_ = true; + newParams.limit_ = newLimit; + newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */; + return newParams; +} +function queryParamsLimitToLast(queryParams, newLimit) { + const newParams = queryParams.copy(); + newParams.limitSet_ = true; + newParams.limit_ = newLimit; + newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */; + return newParams; +} +function queryParamsStartAt(queryParams, indexValue, key) { + const newParams = queryParams.copy(); + newParams.startSet_ = true; + if (indexValue === undefined) { + indexValue = null; + } + newParams.indexStartValue_ = indexValue; + if (key != null) { + newParams.startNameSet_ = true; + newParams.indexStartName_ = key; + } + else { + newParams.startNameSet_ = false; + newParams.indexStartName_ = ''; + } + return newParams; +} +function queryParamsStartAfter(queryParams, indexValue, key) { + let params; + if (queryParams.index_ === KEY_INDEX || !!key) { + params = queryParamsStartAt(queryParams, indexValue, key); + } + else { + params = queryParamsStartAt(queryParams, indexValue, MAX_NAME); + } + params.startAfterSet_ = true; + return params; +} +function queryParamsEndAt(queryParams, indexValue, key) { + const newParams = queryParams.copy(); + newParams.endSet_ = true; + if (indexValue === undefined) { + indexValue = null; + } + newParams.indexEndValue_ = indexValue; + if (key !== undefined) { + newParams.endNameSet_ = true; + newParams.indexEndName_ = key; + } + else { + newParams.endNameSet_ = false; + newParams.indexEndName_ = ''; + } + return newParams; +} +function queryParamsEndBefore(queryParams, indexValue, key) { + let params; + if (queryParams.index_ === KEY_INDEX || !!key) { + params = queryParamsEndAt(queryParams, indexValue, key); + } + else { + params = queryParamsEndAt(queryParams, indexValue, MIN_NAME); + } + params.endBeforeSet_ = true; + return params; +} +function queryParamsOrderBy(queryParams, index) { + const newParams = queryParams.copy(); + newParams.index_ = index; + return newParams; +} +/** + * Returns a set of REST query string parameters representing this query. + * + * @returns query string parameters + */ +function queryParamsToRestQueryStringParameters(queryParams) { + const qs = {}; + if (queryParams.isDefault()) { + return qs; + } + let orderBy; + if (queryParams.index_ === PRIORITY_INDEX) { + orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */; + } + else if (queryParams.index_ === VALUE_INDEX) { + orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */; + } + else if (queryParams.index_ === KEY_INDEX) { + orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */; + } + else { + util.assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!'); + orderBy = queryParams.index_.toString(); + } + qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = util.stringify(orderBy); + if (queryParams.startSet_) { + const startParam = queryParams.startAfterSet_ + ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */ + : "startAt" /* REST_QUERY_CONSTANTS.START_AT */; + qs[startParam] = util.stringify(queryParams.indexStartValue_); + if (queryParams.startNameSet_) { + qs[startParam] += ',' + util.stringify(queryParams.indexStartName_); + } + } + if (queryParams.endSet_) { + const endParam = queryParams.endBeforeSet_ + ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */ + : "endAt" /* REST_QUERY_CONSTANTS.END_AT */; + qs[endParam] = util.stringify(queryParams.indexEndValue_); + if (queryParams.endNameSet_) { + qs[endParam] += ',' + util.stringify(queryParams.indexEndName_); + } + } + if (queryParams.limitSet_) { + if (queryParams.isViewFromLeft()) { + qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_; + } + else { + qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_; + } + } + return qs; +} +function queryParamsGetQueryObject(queryParams) { + const obj = {}; + if (queryParams.startSet_) { + obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] = + queryParams.indexStartValue_; + if (queryParams.startNameSet_) { + obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] = + queryParams.indexStartName_; + } + obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] = + !queryParams.startAfterSet_; + } + if (queryParams.endSet_) { + obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_; + if (queryParams.endNameSet_) { + obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_; + } + obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] = + !queryParams.endBeforeSet_; + } + if (queryParams.limitSet_) { + obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_; + let viewFrom = queryParams.viewFrom_; + if (viewFrom === '') { + if (queryParams.isViewFromLeft()) { + viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */; + } + else { + viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */; + } + } + obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom; + } + // For now, priority index is the default, so we only specify if it's some other index + if (queryParams.index_ !== PRIORITY_INDEX) { + obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString(); + } + return obj; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An implementation of ServerActions that communicates with the server via REST requests. + * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full + * persistent connection (using WebSockets or long-polling) + */ +class ReadonlyRestClient extends ServerActions { + reportStats(stats) { + throw new Error('Method not implemented.'); + } + static getListenId_(query, tag) { + if (tag !== undefined) { + return 'tag$' + tag; + } + else { + util.assert(query._queryParams.isDefault(), "should have a tag if it's not a default query."); + return query._path.toString(); + } + } + /** + * @param repoInfo_ - Data about the namespace we are connecting to + * @param onDataUpdate_ - A callback for new data from the server + */ + constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) { + super(); + this.repoInfo_ = repoInfo_; + this.onDataUpdate_ = onDataUpdate_; + this.authTokenProvider_ = authTokenProvider_; + this.appCheckTokenProvider_ = appCheckTokenProvider_; + /** @private {function(...[*])} */ + this.log_ = logWrapper('p:rest:'); + /** + * We don't actually need to track listens, except to prevent us calling an onComplete for a listen + * that's been removed. :-/ + */ + this.listens_ = {}; + } + /** @inheritDoc */ + listen(query, currentHashFn, tag, onComplete) { + const pathString = query._path.toString(); + this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier); + // Mark this listener so we can tell if it's removed. + const listenId = ReadonlyRestClient.getListenId_(query, tag); + const thisListen = {}; + this.listens_[listenId] = thisListen; + const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams); + this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => { + let data = result; + if (error === 404) { + data = null; + error = null; + } + if (error === null) { + this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag); + } + if (util.safeGet(this.listens_, listenId) === thisListen) { + let status; + if (!error) { + status = 'ok'; + } + else if (error === 401) { + status = 'permission_denied'; + } + else { + status = 'rest_error:' + error; + } + onComplete(status, null); + } + }); + } + /** @inheritDoc */ + unlisten(query, tag) { + const listenId = ReadonlyRestClient.getListenId_(query, tag); + delete this.listens_[listenId]; + } + get(query) { + const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams); + const pathString = query._path.toString(); + const deferred = new util.Deferred(); + this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => { + let data = result; + if (error === 404) { + data = null; + error = null; + } + if (error === null) { + this.onDataUpdate_(pathString, data, + /*isMerge=*/ false, + /*tag=*/ null); + deferred.resolve(data); + } + else { + deferred.reject(new Error(data)); + } + }); + return deferred.promise; + } + /** @inheritDoc */ + refreshAuthToken(token) { + // no-op since we just always call getToken. + } + /** + * Performs a REST request to the given path, with the provided query string parameters, + * and any auth credentials we have. + */ + restRequest_(pathString, queryStringParameters = {}, callback) { + queryStringParameters['format'] = 'export'; + return Promise.all([ + this.authTokenProvider_.getToken(/*forceRefresh=*/ false), + this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false) + ]).then(([authToken, appCheckToken]) => { + if (authToken && authToken.accessToken) { + queryStringParameters['auth'] = authToken.accessToken; + } + if (appCheckToken && appCheckToken.token) { + queryStringParameters['ac'] = appCheckToken.token; + } + const url = (this.repoInfo_.secure ? 'https://' : 'http://') + + this.repoInfo_.host + + pathString + + '?' + + 'ns=' + + this.repoInfo_.namespace + + util.querystring(queryStringParameters); + this.log_('Sending REST request for ' + url); + const xhr = new XMLHttpRequest(); + xhr.onreadystatechange = () => { + if (callback && xhr.readyState === 4) { + this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText); + let res = null; + if (xhr.status >= 200 && xhr.status < 300) { + try { + res = util.jsonEval(xhr.responseText); + } + catch (e) { + warn('Failed to parse JSON response for ' + + url + + ': ' + + xhr.responseText); + } + callback(null, res); + } + else { + // 401 and 404 are expected. + if (xhr.status !== 401 && xhr.status !== 404) { + warn('Got unsuccessful REST response for ' + + url + + ' Status: ' + + xhr.status); + } + callback(xhr.status); + } + callback = null; + } + }; + xhr.open('GET', url, /*asynchronous=*/ true); + xhr.send(); + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Mutable object which basically just stores a reference to the "latest" immutable snapshot. + */ +class SnapshotHolder { + constructor() { + this.rootNode_ = ChildrenNode.EMPTY_NODE; + } + getNode(path) { + return this.rootNode_.getChild(path); + } + updateSnapshot(path, newSnapshotNode) { + this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newSparseSnapshotTree() { + return { + value: null, + children: new Map() + }; +} +/** + * Stores the given node at the specified path. If there is already a node + * at a shallower path, it merges the new data into that snapshot node. + * + * @param path - Path to look up snapshot for. + * @param data - The new data, or null. + */ +function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) { + if (pathIsEmpty(path)) { + sparseSnapshotTree.value = data; + sparseSnapshotTree.children.clear(); + } + else if (sparseSnapshotTree.value !== null) { + sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data); + } + else { + const childKey = pathGetFront(path); + if (!sparseSnapshotTree.children.has(childKey)) { + sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree()); + } + const child = sparseSnapshotTree.children.get(childKey); + path = pathPopFront(path); + sparseSnapshotTreeRemember(child, path, data); + } +} +/** + * Purge the data at path from the cache. + * + * @param path - Path to look up snapshot for. + * @returns True if this node should now be removed. + */ +function sparseSnapshotTreeForget(sparseSnapshotTree, path) { + if (pathIsEmpty(path)) { + sparseSnapshotTree.value = null; + sparseSnapshotTree.children.clear(); + return true; + } + else { + if (sparseSnapshotTree.value !== null) { + if (sparseSnapshotTree.value.isLeafNode()) { + // We're trying to forget a node that doesn't exist + return false; + } + else { + const value = sparseSnapshotTree.value; + sparseSnapshotTree.value = null; + value.forEachChild(PRIORITY_INDEX, (key, tree) => { + sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree); + }); + return sparseSnapshotTreeForget(sparseSnapshotTree, path); + } + } + else if (sparseSnapshotTree.children.size > 0) { + const childKey = pathGetFront(path); + path = pathPopFront(path); + if (sparseSnapshotTree.children.has(childKey)) { + const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path); + if (safeToRemove) { + sparseSnapshotTree.children.delete(childKey); + } + } + return sparseSnapshotTree.children.size === 0; + } + else { + return true; + } + } +} +/** + * Recursively iterates through all of the stored tree and calls the + * callback on each one. + * + * @param prefixPath - Path to look up node for. + * @param func - The function to invoke for each tree. + */ +function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) { + if (sparseSnapshotTree.value !== null) { + func(prefixPath, sparseSnapshotTree.value); + } + else { + sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => { + const path = new Path(prefixPath.toString() + '/' + key); + sparseSnapshotTreeForEachTree(tree, path, func); + }); + } +} +/** + * Iterates through each immediate child and triggers the callback. + * Only seems to be used in tests. + * + * @param func - The function to invoke for each child. + */ +function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) { + sparseSnapshotTree.children.forEach((tree, key) => { + func(key, tree); + }); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns the delta from the previous call to get stats. + * + * @param collection_ - The collection to "listen" to. + */ +class StatsListener { + constructor(collection_) { + this.collection_ = collection_; + this.last_ = null; + } + get() { + const newStats = this.collection_.get(); + const delta = { ...newStats }; + if (this.last_) { + each(this.last_, (stat, value) => { + delta[stat] = delta[stat] - value; + }); + } + this.last_ = newStats; + return delta; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably +// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10 +// seconds to try to ensure the Firebase connection is established / settled. +const FIRST_STATS_MIN_TIME = 10 * 1000; +const FIRST_STATS_MAX_TIME = 30 * 1000; +// We'll continue to report stats on average every 5 minutes. +const REPORT_STATS_INTERVAL = 5 * 60 * 1000; +class StatsReporter { + constructor(collection, server_) { + this.server_ = server_; + this.statsToReport_ = {}; + this.statsListener_ = new StatsListener(collection); + const timeout = FIRST_STATS_MIN_TIME + + (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random(); + setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout)); + } + reportStats_() { + const stats = this.statsListener_.get(); + const reportedStats = {}; + let haveStatsToReport = false; + each(stats, (stat, value) => { + if (value > 0 && util.contains(this.statsToReport_, stat)) { + reportedStats[stat] = value; + haveStatsToReport = true; + } + }); + if (haveStatsToReport) { + this.server_.reportStats(reportedStats); + } + // queue our next run. + setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @enum + */ +var OperationType; +(function (OperationType) { + OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE"; + OperationType[OperationType["MERGE"] = 1] = "MERGE"; + OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE"; + OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE"; +})(OperationType || (OperationType = {})); +function newOperationSourceUser() { + return { + fromUser: true, + fromServer: false, + queryId: null, + tagged: false + }; +} +function newOperationSourceServer() { + return { + fromUser: false, + fromServer: true, + queryId: null, + tagged: false + }; +} +function newOperationSourceServerTaggedQuery(queryId) { + return { + fromUser: false, + fromServer: true, + queryId, + tagged: true + }; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class AckUserWrite { + /** + * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap. + */ + constructor( + /** @inheritDoc */ path, + /** @inheritDoc */ affectedTree, + /** @inheritDoc */ revert) { + this.path = path; + this.affectedTree = affectedTree; + this.revert = revert; + /** @inheritDoc */ + this.type = OperationType.ACK_USER_WRITE; + /** @inheritDoc */ + this.source = newOperationSourceUser(); + } + operationForChild(childName) { + if (!pathIsEmpty(this.path)) { + util.assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.'); + return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert); + } + else if (this.affectedTree.value != null) { + util.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.'); + // All child locations are affected as well; just return same operation. + return this; + } + else { + const childTree = this.affectedTree.subtree(new Path(childName)); + return new AckUserWrite(newEmptyPath(), childTree, this.revert); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ListenComplete { + constructor(source, path) { + this.source = source; + this.path = path; + /** @inheritDoc */ + this.type = OperationType.LISTEN_COMPLETE; + } + operationForChild(childName) { + if (pathIsEmpty(this.path)) { + return new ListenComplete(this.source, newEmptyPath()); + } + else { + return new ListenComplete(this.source, pathPopFront(this.path)); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Overwrite { + constructor(source, path, snap) { + this.source = source; + this.path = path; + this.snap = snap; + /** @inheritDoc */ + this.type = OperationType.OVERWRITE; + } + operationForChild(childName) { + if (pathIsEmpty(this.path)) { + return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName)); + } + else { + return new Overwrite(this.source, pathPopFront(this.path), this.snap); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Merge { + constructor( + /** @inheritDoc */ source, + /** @inheritDoc */ path, + /** @inheritDoc */ children) { + this.source = source; + this.path = path; + this.children = children; + /** @inheritDoc */ + this.type = OperationType.MERGE; + } + operationForChild(childName) { + if (pathIsEmpty(this.path)) { + const childTree = this.children.subtree(new Path(childName)); + if (childTree.isEmpty()) { + // This child is unaffected + return null; + } + else if (childTree.value) { + // We have a snapshot for the child in question. This becomes an overwrite of the child. + return new Overwrite(this.source, newEmptyPath(), childTree.value); + } + else { + // This is a merge at a deeper level + return new Merge(this.source, newEmptyPath(), childTree); + } + } + else { + util.assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation"); + return new Merge(this.source, pathPopFront(this.path), this.children); + } + } + toString() { + return ('Operation(' + + this.path + + ': ' + + this.source.toString() + + ' merge: ' + + this.children.toString() + + ')'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully + * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g. + * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks + * whether a node potentially had children removed due to a filter. + */ +class CacheNode { + constructor(node_, fullyInitialized_, filtered_) { + this.node_ = node_; + this.fullyInitialized_ = fullyInitialized_; + this.filtered_ = filtered_; + } + /** + * Returns whether this node was fully initialized with either server data or a complete overwrite by the client + */ + isFullyInitialized() { + return this.fullyInitialized_; + } + /** + * Returns whether this node is potentially missing children due to a filter applied to the node + */ + isFiltered() { + return this.filtered_; + } + isCompleteForPath(path) { + if (pathIsEmpty(path)) { + return this.isFullyInitialized() && !this.filtered_; + } + const childKey = pathGetFront(path); + return this.isCompleteForChild(childKey); + } + isCompleteForChild(key) { + return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key)); + } + getNode() { + return this.node_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An EventGenerator is used to convert "raw" changes (Change) as computed by the + * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges() + * for details. + * + */ +class EventGenerator { + constructor(query_) { + this.query_ = query_; + this.index_ = this.query_._queryParams.getIndex(); + } +} +/** + * Given a set of raw changes (no moved events and prevName not specified yet), and a set of + * EventRegistrations that should be notified of these changes, generate the actual events to be raised. + * + * Notes: + * - child_moved events will be synthesized at this time for any child_changed events that affect + * our index. + * - prevName will be calculated based on the index ordering. + */ +function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) { + const events = []; + const moves = []; + changes.forEach(change => { + if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ && + eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) { + moves.push(changeChildMoved(change.childName, change.snapshotNode)); + } + }); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache); + return events; +} +/** + * Given changes of a single change type, generate the corresponding events. + */ +function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) { + const filteredChanges = changes.filter(change => change.type === eventType); + filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b)); + filteredChanges.forEach(change => { + const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache); + registrations.forEach(registration => { + if (registration.respondsTo(change.type)) { + events.push(registration.createEvent(materializedChange, eventGenerator.query_)); + } + }); + }); +} +function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) { + if (change.type === 'value' || change.type === 'child_removed') { + return change; + } + else { + change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_); + return change; + } +} +function eventGeneratorCompareChanges(eventGenerator, a, b) { + if (a.childName == null || b.childName == null) { + throw util.assertionError('Should only compare child_ events.'); + } + const aWrapped = new NamedNode(a.childName, a.snapshotNode); + const bWrapped = new NamedNode(b.childName, b.snapshotNode); + return eventGenerator.index_.compare(aWrapped, bWrapped); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newViewCache(eventCache, serverCache) { + return { eventCache, serverCache }; +} +function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) { + return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache); +} +function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) { + return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered)); +} +function viewCacheGetCompleteEventSnap(viewCache) { + return viewCache.eventCache.isFullyInitialized() + ? viewCache.eventCache.getNode() + : null; +} +function viewCacheGetCompleteServerSnap(viewCache) { + return viewCache.serverCache.isFullyInitialized() + ? viewCache.serverCache.getNode() + : null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let emptyChildrenSingleton; +/** + * Singleton empty children collection. + * + */ +const EmptyChildren = () => { + if (!emptyChildrenSingleton) { + emptyChildrenSingleton = new SortedMap(stringCompare); + } + return emptyChildrenSingleton; +}; +/** + * A tree with immutable elements. + */ +class ImmutableTree { + static fromObject(obj) { + let tree = new ImmutableTree(null); + each(obj, (childPath, childSnap) => { + tree = tree.set(new Path(childPath), childSnap); + }); + return tree; + } + constructor(value, children = EmptyChildren()) { + this.value = value; + this.children = children; + } + /** + * True if the value is empty and there are no children + */ + isEmpty() { + return this.value === null && this.children.isEmpty(); + } + /** + * Given a path and predicate, return the first node and the path to that node + * where the predicate returns true. + * + * TODO Do a perf test -- If we're creating a bunch of `{path: value:}` + * objects on the way back out, it may be better to pass down a pathSoFar obj. + * + * @param relativePath - The remainder of the path + * @param predicate - The predicate to satisfy to return a node + */ + findRootMostMatchingPathAndValue(relativePath, predicate) { + if (this.value != null && predicate(this.value)) { + return { path: newEmptyPath(), value: this.value }; + } + else { + if (pathIsEmpty(relativePath)) { + return null; + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front); + if (child !== null) { + const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate); + if (childExistingPathAndValue != null) { + const fullPath = pathChild(new Path(front), childExistingPathAndValue.path); + return { path: fullPath, value: childExistingPathAndValue.value }; + } + else { + return null; + } + } + else { + return null; + } + } + } + } + /** + * Find, if it exists, the shortest subpath of the given path that points a defined + * value in the tree + */ + findRootMostValueAndPath(relativePath) { + return this.findRootMostMatchingPathAndValue(relativePath, () => true); + } + /** + * @returns The subtree at the given path + */ + subtree(relativePath) { + if (pathIsEmpty(relativePath)) { + return this; + } + else { + const front = pathGetFront(relativePath); + const childTree = this.children.get(front); + if (childTree !== null) { + return childTree.subtree(pathPopFront(relativePath)); + } + else { + return new ImmutableTree(null); + } + } + } + /** + * Sets a value at the specified path. + * + * @param relativePath - Path to set value at. + * @param toSet - Value to set. + * @returns Resulting tree. + */ + set(relativePath, toSet) { + if (pathIsEmpty(relativePath)) { + return new ImmutableTree(toSet, this.children); + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front) || new ImmutableTree(null); + const newChild = child.set(pathPopFront(relativePath), toSet); + const newChildren = this.children.insert(front, newChild); + return new ImmutableTree(this.value, newChildren); + } + } + /** + * Removes the value at the specified path. + * + * @param relativePath - Path to value to remove. + * @returns Resulting tree. + */ + remove(relativePath) { + if (pathIsEmpty(relativePath)) { + if (this.children.isEmpty()) { + return new ImmutableTree(null); + } + else { + return new ImmutableTree(null, this.children); + } + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front); + if (child) { + const newChild = child.remove(pathPopFront(relativePath)); + let newChildren; + if (newChild.isEmpty()) { + newChildren = this.children.remove(front); + } + else { + newChildren = this.children.insert(front, newChild); + } + if (this.value === null && newChildren.isEmpty()) { + return new ImmutableTree(null); + } + else { + return new ImmutableTree(this.value, newChildren); + } + } + else { + return this; + } + } + } + /** + * Gets a value from the tree. + * + * @param relativePath - Path to get value for. + * @returns Value at path, or null. + */ + get(relativePath) { + if (pathIsEmpty(relativePath)) { + return this.value; + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front); + if (child) { + return child.get(pathPopFront(relativePath)); + } + else { + return null; + } + } + } + /** + * Replace the subtree at the specified path with the given new tree. + * + * @param relativePath - Path to replace subtree for. + * @param newTree - New tree. + * @returns Resulting tree. + */ + setTree(relativePath, newTree) { + if (pathIsEmpty(relativePath)) { + return newTree; + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front) || new ImmutableTree(null); + const newChild = child.setTree(pathPopFront(relativePath), newTree); + let newChildren; + if (newChild.isEmpty()) { + newChildren = this.children.remove(front); + } + else { + newChildren = this.children.insert(front, newChild); + } + return new ImmutableTree(this.value, newChildren); + } + } + /** + * Performs a depth first fold on this tree. Transforms a tree into a single + * value, given a function that operates on the path to a node, an optional + * current value, and a map of child names to folded subtrees + */ + fold(fn) { + return this.fold_(newEmptyPath(), fn); + } + /** + * Recursive helper for public-facing fold() method + */ + fold_(pathSoFar, fn) { + const accum = {}; + this.children.inorderTraversal((childKey, childTree) => { + accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn); + }); + return fn(pathSoFar, this.value, accum); + } + /** + * Find the first matching value on the given path. Return the result of applying f to it. + */ + findOnPath(path, f) { + return this.findOnPath_(path, newEmptyPath(), f); + } + findOnPath_(pathToFollow, pathSoFar, f) { + const result = this.value ? f(pathSoFar, this.value) : false; + if (result) { + return result; + } + else { + if (pathIsEmpty(pathToFollow)) { + return null; + } + else { + const front = pathGetFront(pathToFollow); + const nextChild = this.children.get(front); + if (nextChild) { + return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f); + } + else { + return null; + } + } + } + } + foreachOnPath(path, f) { + return this.foreachOnPath_(path, newEmptyPath(), f); + } + foreachOnPath_(pathToFollow, currentRelativePath, f) { + if (pathIsEmpty(pathToFollow)) { + return this; + } + else { + if (this.value) { + f(currentRelativePath, this.value); + } + const front = pathGetFront(pathToFollow); + const nextChild = this.children.get(front); + if (nextChild) { + return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f); + } + else { + return new ImmutableTree(null); + } + } + } + /** + * Calls the given function for each node in the tree that has a value. + * + * @param f - A function to be called with the path from the root of the tree to + * a node, and the value at that node. Called in depth-first order. + */ + foreach(f) { + this.foreach_(newEmptyPath(), f); + } + foreach_(currentRelativePath, f) { + this.children.inorderTraversal((childName, childTree) => { + childTree.foreach_(pathChild(currentRelativePath, childName), f); + }); + if (this.value) { + f(currentRelativePath, this.value); + } + } + foreachChild(f) { + this.children.inorderTraversal((childName, childTree) => { + if (childTree.value) { + f(childName, childTree.value); + } + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with + * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write + * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write + * to reflect the write added. + */ +class CompoundWrite { + constructor(writeTree_) { + this.writeTree_ = writeTree_; + } + static empty() { + return new CompoundWrite(new ImmutableTree(null)); + } +} +function compoundWriteAddWrite(compoundWrite, path, node) { + if (pathIsEmpty(path)) { + return new CompoundWrite(new ImmutableTree(node)); + } + else { + const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path); + if (rootmost != null) { + const rootMostPath = rootmost.path; + let value = rootmost.value; + const relativePath = newRelativePath(rootMostPath, path); + value = value.updateChild(relativePath, node); + return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value)); + } + else { + const subtree = new ImmutableTree(node); + const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree); + return new CompoundWrite(newWriteTree); + } + } +} +function compoundWriteAddWrites(compoundWrite, path, updates) { + let newWrite = compoundWrite; + each(updates, (childKey, node) => { + newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node); + }); + return newWrite; +} +/** + * Will remove a write at the given path and deeper paths. This will not modify a write at a higher + * location, which must be removed by calling this method with that path. + * + * @param compoundWrite - The CompoundWrite to remove. + * @param path - The path at which a write and all deeper writes should be removed + * @returns The new CompoundWrite with the removed path + */ +function compoundWriteRemoveWrite(compoundWrite, path) { + if (pathIsEmpty(path)) { + return CompoundWrite.empty(); + } + else { + const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null)); + return new CompoundWrite(newWriteTree); + } +} +/** + * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be + * considered "complete". + * + * @param compoundWrite - The CompoundWrite to check. + * @param path - The path to check for + * @returns Whether there is a complete write at that path + */ +function compoundWriteHasCompleteWrite(compoundWrite, path) { + return compoundWriteGetCompleteNode(compoundWrite, path) != null; +} +/** + * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate + * writes from deeper paths, but will return child nodes from a more shallow path. + * + * @param compoundWrite - The CompoundWrite to get the node from. + * @param path - The path to get a complete write + * @returns The node if complete at that path, or null otherwise. + */ +function compoundWriteGetCompleteNode(compoundWrite, path) { + const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path); + if (rootmost != null) { + return compoundWrite.writeTree_ + .get(rootmost.path) + .getChild(newRelativePath(rootmost.path, path)); + } + else { + return null; + } +} +/** + * Returns all children that are guaranteed to be a complete overwrite. + * + * @param compoundWrite - The CompoundWrite to get children from. + * @returns A list of all complete children. + */ +function compoundWriteGetCompleteChildren(compoundWrite) { + const children = []; + const node = compoundWrite.writeTree_.value; + if (node != null) { + // If it's a leaf node, it has no children; so nothing to do. + if (!node.isLeafNode()) { + node.forEachChild(PRIORITY_INDEX, (childName, childNode) => { + children.push(new NamedNode(childName, childNode)); + }); + } + } + else { + compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => { + if (childTree.value != null) { + children.push(new NamedNode(childName, childTree.value)); + } + }); + } + return children; +} +function compoundWriteChildCompoundWrite(compoundWrite, path) { + if (pathIsEmpty(path)) { + return compoundWrite; + } + else { + const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path); + if (shadowingNode != null) { + return new CompoundWrite(new ImmutableTree(shadowingNode)); + } + else { + return new CompoundWrite(compoundWrite.writeTree_.subtree(path)); + } + } +} +/** + * Returns true if this CompoundWrite is empty and therefore does not modify any nodes. + * @returns Whether this CompoundWrite is empty + */ +function compoundWriteIsEmpty(compoundWrite) { + return compoundWrite.writeTree_.isEmpty(); +} +/** + * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the + * node + * @param node - The node to apply this CompoundWrite to + * @returns The node with all writes applied + */ +function compoundWriteApply(compoundWrite, node) { + return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node); +} +function applySubtreeWrite(relativePath, writeTree, node) { + if (writeTree.value != null) { + // Since there a write is always a leaf, we're done here + return node.updateChild(relativePath, writeTree.value); + } + else { + let priorityWrite = null; + writeTree.children.inorderTraversal((childKey, childTree) => { + if (childKey === '.priority') { + // Apply priorities at the end so we don't update priorities for either empty nodes or forget + // to apply priorities to empty nodes that are later filled + util.assert(childTree.value !== null, 'Priority writes must always be leaf nodes'); + priorityWrite = childTree.value; + } + else { + node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node); + } + }); + // If there was a priority write, we only apply it if the node is not empty + if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) { + node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite); + } + return node; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path. + * + */ +function writeTreeChildWrites(writeTree, path) { + return newWriteTreeRef(path, writeTree); +} +/** + * Record a new overwrite from user code. + * + * @param visible - This is set to false by some transactions. It should be excluded from event caches + */ +function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) { + util.assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones'); + if (visible === undefined) { + visible = true; + } + writeTree.allWrites.push({ + path, + snap, + writeId, + visible + }); + if (visible) { + writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap); + } + writeTree.lastWriteId = writeId; +} +/** + * Record a new merge from user code. + */ +function writeTreeAddMerge(writeTree, path, changedChildren, writeId) { + util.assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones'); + writeTree.allWrites.push({ + path, + children: changedChildren, + writeId, + visible: true + }); + writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren); + writeTree.lastWriteId = writeId; +} +function writeTreeGetWrite(writeTree, writeId) { + for (let i = 0; i < writeTree.allWrites.length; i++) { + const record = writeTree.allWrites[i]; + if (record.writeId === writeId) { + return record; + } + } + return null; +} +/** + * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates + * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate. + * + * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise + * events as a result). + */ +function writeTreeRemoveWrite(writeTree, writeId) { + // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied + // out of order. + //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId; + //assert(validClear, "Either we don't have this write, or it's the first one in the queue"); + const idx = writeTree.allWrites.findIndex(s => { + return s.writeId === writeId; + }); + util.assert(idx >= 0, 'removeWrite called with nonexistent writeId.'); + const writeToRemove = writeTree.allWrites[idx]; + writeTree.allWrites.splice(idx, 1); + let removedWriteWasVisible = writeToRemove.visible; + let removedWriteOverlapsWithOtherWrites = false; + let i = writeTree.allWrites.length - 1; + while (removedWriteWasVisible && i >= 0) { + const currentWrite = writeTree.allWrites[i]; + if (currentWrite.visible) { + if (i >= idx && + writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) { + // The removed write was completely shadowed by a subsequent write. + removedWriteWasVisible = false; + } + else if (pathContains(writeToRemove.path, currentWrite.path)) { + // Either we're covering some writes or they're covering part of us (depending on which came first). + removedWriteOverlapsWithOtherWrites = true; + } + } + i--; + } + if (!removedWriteWasVisible) { + return false; + } + else if (removedWriteOverlapsWithOtherWrites) { + // There's some shadowing going on. Just rebuild the visible writes from scratch. + writeTreeResetTree_(writeTree); + return true; + } + else { + // There's no shadowing. We can safely just remove the write(s) from visibleWrites. + if (writeToRemove.snap) { + writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path); + } + else { + const children = writeToRemove.children; + each(children, (childName) => { + writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName)); + }); + } + return true; + } +} +function writeTreeRecordContainsPath_(writeRecord, path) { + if (writeRecord.snap) { + return pathContains(writeRecord.path, path); + } + else { + for (const childName in writeRecord.children) { + if (writeRecord.children.hasOwnProperty(childName) && + pathContains(pathChild(writeRecord.path, childName), path)) { + return true; + } + } + return false; + } +} +/** + * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots + */ +function writeTreeResetTree_(writeTree) { + writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath()); + if (writeTree.allWrites.length > 0) { + writeTree.lastWriteId = + writeTree.allWrites[writeTree.allWrites.length - 1].writeId; + } + else { + writeTree.lastWriteId = -1; + } +} +/** + * The default filter used when constructing the tree. Keep everything that's visible. + */ +function writeTreeDefaultFilter_(write) { + return write.visible; +} +/** + * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of + * event data at that path. + */ +function writeTreeLayerTree_(writes, filter, treeRoot) { + let compoundWrite = CompoundWrite.empty(); + for (let i = 0; i < writes.length; ++i) { + const write = writes[i]; + // Theory, a later set will either: + // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction + // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction + if (filter(write)) { + const writePath = write.path; + let relativePath; + if (write.snap) { + if (pathContains(treeRoot, writePath)) { + relativePath = newRelativePath(treeRoot, writePath); + compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap); + } + else if (pathContains(writePath, treeRoot)) { + relativePath = newRelativePath(writePath, treeRoot); + compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath)); + } + else ; + } + else if (write.children) { + if (pathContains(treeRoot, writePath)) { + relativePath = newRelativePath(treeRoot, writePath); + compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children); + } + else if (pathContains(writePath, treeRoot)) { + relativePath = newRelativePath(writePath, treeRoot); + if (pathIsEmpty(relativePath)) { + compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children); + } + else { + const child = util.safeGet(write.children, pathGetFront(relativePath)); + if (child) { + // There exists a child in this node that matches the root path + const deepNode = child.getChild(pathPopFront(relativePath)); + compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode); + } + } + } + else ; + } + else { + throw util.assertionError('WriteRecord should have .snap or .children'); + } + } + } + return compoundWrite; +} +/** + * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden + * writes), attempt to calculate a complete snapshot for the given path + * + * @param writeIdsToExclude - An optional set to be excluded + * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false + */ +function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) { + if (!writeIdsToExclude && !includeHiddenWrites) { + const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath); + if (shadowingNode != null) { + return shadowingNode; + } + else { + const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + if (compoundWriteIsEmpty(subMerge)) { + return completeServerCache; + } + else if (completeServerCache == null && + !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) { + // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow + return null; + } + else { + const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE; + return compoundWriteApply(subMerge, layeredCache); + } + } + } + else { + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) { + return completeServerCache; + } + else { + // If the server cache is null, and we don't have a complete cache, we need to return null + if (!includeHiddenWrites && + completeServerCache == null && + !compoundWriteHasCompleteWrite(merge, newEmptyPath())) { + return null; + } + else { + const filter = function (write) { + return ((write.visible || includeHiddenWrites) && + (!writeIdsToExclude || + !~writeIdsToExclude.indexOf(write.writeId)) && + (pathContains(write.path, treePath) || + pathContains(treePath, write.path))); + }; + const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath); + const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE; + return compoundWriteApply(mergeAtPath, layeredCache); + } + } + } +} +/** + * With optional, underlying server data, attempt to return a children node of children that we have complete data for. + * Used when creating new views, to pre-fill their complete event children snapshot. + */ +function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) { + let completeChildren = ChildrenNode.EMPTY_NODE; + const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath); + if (topLevelSet) { + if (!topLevelSet.isLeafNode()) { + // we're shadowing everything. Return the children. + topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => { + completeChildren = completeChildren.updateImmediateChild(childName, childSnap); + }); + } + return completeChildren; + } + else if (completeServerChildren) { + // Layer any children we have on top of this + // We know we don't have a top-level set, so just enumerate existing children + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => { + const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode); + completeChildren = completeChildren.updateImmediateChild(childName, node); + }); + // Add any complete children we have from the set + compoundWriteGetCompleteChildren(merge).forEach(namedNode => { + completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node); + }); + return completeChildren; + } + else { + // We don't have anything to layer on top of. Layer on any children we have + // Note that we can return an empty snap if we have a defined delete + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + compoundWriteGetCompleteChildren(merge).forEach(namedNode => { + completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node); + }); + return completeChildren; + } +} +/** + * Given that the underlying server data has updated, determine what, if anything, needs to be + * applied to the event cache. + * + * Possibilities: + * + * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data + * + * 2. Some write is completely shadowing. No events to be raised + * + * 3. Is partially shadowed. Events + * + * Either existingEventSnap or existingServerSnap must exist + */ +function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) { + util.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist'); + const path = pathChild(treePath, childPath); + if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) { + // At this point we can probably guarantee that we're in case 2, meaning no events + // May need to check visibility while doing the findRootMostValueAndPath call + return null; + } + else { + // No complete shadowing. We're either partially shadowing or not shadowing at all. + const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path); + if (compoundWriteIsEmpty(childMerge)) { + // We're not shadowing at all. Case 1 + return existingServerSnap.getChild(childPath); + } + else { + // This could be more efficient if the serverNode + updates doesn't change the eventSnap + // However this is tricky to find out, since user updates don't necessary change the server + // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server + // adds nodes, but doesn't change any existing writes. It is therefore not enough to + // only check if the updates change the serverNode. + // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case? + return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath)); + } + } +} +/** + * Returns a complete child for a given server snap after applying all user writes or null if there is no + * complete child for this ChildKey. + */ +function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) { + const path = pathChild(treePath, childKey); + const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path); + if (shadowingNode != null) { + return shadowingNode; + } + else { + if (existingServerSnap.isCompleteForChild(childKey)) { + const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path); + return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey)); + } + else { + return null; + } + } +} +/** + * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at + * a higher path, this will return the child of that write relative to the write and this path. + * Returns null if there is no write at this path. + */ +function writeTreeShadowingWrite(writeTree, path) { + return compoundWriteGetCompleteNode(writeTree.visibleWrites, path); +} +/** + * This method is used when processing child remove events on a query. If we can, we pull in children that were outside + * the window, but may now be in the window. + */ +function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) { + let toIterate; + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath()); + if (shadowingNode != null) { + toIterate = shadowingNode; + } + else if (completeServerData != null) { + toIterate = compoundWriteApply(merge, completeServerData); + } + else { + // no children to iterate on + return []; + } + toIterate = toIterate.withIndex(index); + if (!toIterate.isEmpty() && !toIterate.isLeafNode()) { + const nodes = []; + const cmp = index.getCompare(); + const iter = reverse + ? toIterate.getReverseIteratorFrom(startPost, index) + : toIterate.getIteratorFrom(startPost, index); + let next = iter.getNext(); + while (next && nodes.length < count) { + if (cmp(next, startPost) !== 0) { + nodes.push(next); + } + next = iter.getNext(); + } + return nodes; + } + else { + return []; + } +} +function newWriteTree() { + return { + visibleWrites: CompoundWrite.empty(), + allWrites: [], + lastWriteId: -1 + }; +} +/** + * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used + * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node + * can lead to a more expensive calculation. + * + * @param writeIdsToExclude - Optional writes to exclude. + * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false + */ +function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) { + return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites); +} +/** + * If possible, returns a children node containing all of the complete children we have data for. The returned data is a + * mix of the given server data and write data. + * + */ +function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) { + return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren); +} +/** + * Given that either the underlying server data has updated or the outstanding writes have updated, determine what, + * if anything, needs to be applied to the event cache. + * + * Possibilities: + * + * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data + * + * 2. Some write is completely shadowing. No events to be raised + * + * 3. Is partially shadowed. Events should be raised + * + * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert + * + * + */ +function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) { + return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap); +} +/** + * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at + * a higher path, this will return the child of that write relative to the write and this path. + * Returns null if there is no write at this path. + * + */ +function writeTreeRefShadowingWrite(writeTreeRef, path) { + return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path)); +} +/** + * This method is used when processing child remove events on a query. If we can, we pull in children that were outside + * the window, but may now be in the window + */ +function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) { + return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index); +} +/** + * Returns a complete child for a given server snap after applying all user writes or null if there is no + * complete child for this ChildKey. + */ +function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) { + return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache); +} +/** + * Return a WriteTreeRef for a child. + */ +function writeTreeRefChild(writeTreeRef, childName) { + return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree); +} +function newWriteTreeRef(path, writeTree) { + return { + treePath: path, + writeTree + }; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ChildChangeAccumulator { + constructor() { + this.changeMap = new Map(); + } + trackChildChange(change) { + const type = change.type; + const childKey = change.childName; + util.assert(type === "child_added" /* ChangeType.CHILD_ADDED */ || + type === "child_changed" /* ChangeType.CHILD_CHANGED */ || + type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking'); + util.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.'); + const oldChange = this.changeMap.get(childKey); + if (oldChange) { + const oldType = oldChange.type; + if (type === "child_added" /* ChangeType.CHILD_ADDED */ && + oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) { + this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode)); + } + else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ && + oldType === "child_added" /* ChangeType.CHILD_ADDED */) { + this.changeMap.delete(childKey); + } + else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ && + oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) { + this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap)); + } + else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ && + oldType === "child_added" /* ChangeType.CHILD_ADDED */) { + this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode)); + } + else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ && + oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) { + this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap)); + } + else { + throw util.assertionError('Illegal combination of changes: ' + + change + + ' occurred after ' + + oldChange); + } + } + else { + this.changeMap.set(childKey, change); + } + } + getChanges() { + return Array.from(this.changeMap.values()); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An implementation of CompleteChildSource that never returns any additional children + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class NoCompleteChildSource_ { + getCompleteChild(childKey) { + return null; + } + getChildAfterChild(index, child, reverse) { + return null; + } +} +/** + * Singleton instance. + */ +const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_(); +/** + * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or + * old event caches available to calculate complete children. + */ +class WriteTreeCompleteChildSource { + constructor(writes_, viewCache_, optCompleteServerCache_ = null) { + this.writes_ = writes_; + this.viewCache_ = viewCache_; + this.optCompleteServerCache_ = optCompleteServerCache_; + } + getCompleteChild(childKey) { + const node = this.viewCache_.eventCache; + if (node.isCompleteForChild(childKey)) { + return node.getNode().getImmediateChild(childKey); + } + else { + const serverNode = this.optCompleteServerCache_ != null + ? new CacheNode(this.optCompleteServerCache_, true, false) + : this.viewCache_.serverCache; + return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode); + } + } + getChildAfterChild(index, child, reverse) { + const completeServerData = this.optCompleteServerCache_ != null + ? this.optCompleteServerCache_ + : viewCacheGetCompleteServerSnap(this.viewCache_); + const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index); + if (nodes.length === 0) { + return null; + } + else { + return nodes[0]; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newViewProcessor(filter) { + return { filter }; +} +function viewProcessorAssertIndexed(viewProcessor, viewCache) { + util.assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed'); + util.assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed'); +} +function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) { + const accumulator = new ChildChangeAccumulator(); + let newViewCache, filterServerNode; + if (operation.type === OperationType.OVERWRITE) { + const overwrite = operation; + if (overwrite.source.fromUser) { + newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator); + } + else { + util.assert(overwrite.source.fromServer, 'Unknown source.'); + // We filter the node if it's a tagged update or the node has been previously filtered and the + // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered + // again + filterServerNode = + overwrite.source.tagged || + (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path)); + newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator); + } + } + else if (operation.type === OperationType.MERGE) { + const merge = operation; + if (merge.source.fromUser) { + newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator); + } + else { + util.assert(merge.source.fromServer, 'Unknown source.'); + // We filter the node if it's a tagged update or the node has been previously filtered + filterServerNode = + merge.source.tagged || oldViewCache.serverCache.isFiltered(); + newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator); + } + } + else if (operation.type === OperationType.ACK_USER_WRITE) { + const ackUserWrite = operation; + if (!ackUserWrite.revert) { + newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator); + } + else { + newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator); + } + } + else if (operation.type === OperationType.LISTEN_COMPLETE) { + newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator); + } + else { + throw util.assertionError('Unknown operation type: ' + operation.type); + } + const changes = accumulator.getChanges(); + viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes); + return { viewCache: newViewCache, changes }; +} +function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) { + const eventSnap = newViewCache.eventCache; + if (eventSnap.isFullyInitialized()) { + const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty(); + const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache); + if (accumulator.length > 0 || + !oldViewCache.eventCache.isFullyInitialized() || + (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) || + !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) { + accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache))); + } + } +} +function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) { + const oldEventSnap = viewCache.eventCache; + if (writeTreeRefShadowingWrite(writesCache, changePath) != null) { + // we have a shadowing write, ignore changes + return viewCache; + } + else { + let newEventCache, serverNode; + if (pathIsEmpty(changePath)) { + // TODO: figure out how this plays with "sliding ack windows" + util.assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data'); + if (viewCache.serverCache.isFiltered()) { + // We need to special case this, because we need to only apply writes to complete children, or + // we might end up raising events for incomplete children. If the server data is filtered deep + // writes cannot be guaranteed to be complete + const serverCache = viewCacheGetCompleteServerSnap(viewCache); + const completeChildren = serverCache instanceof ChildrenNode + ? serverCache + : ChildrenNode.EMPTY_NODE; + const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren); + newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator); + } + else { + const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache)); + newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator); + } + } + else { + const childKey = pathGetFront(changePath); + if (childKey === '.priority') { + util.assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components"); + const oldEventNode = oldEventSnap.getNode(); + serverNode = viewCache.serverCache.getNode(); + // we might have overwrites for this priority + const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode); + if (updatedPriority != null) { + newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority); + } + else { + // priority didn't change, keep old node + newEventCache = oldEventSnap.getNode(); + } + } + else { + const childChangePath = pathPopFront(changePath); + // update child + let newEventChild; + if (oldEventSnap.isCompleteForChild(childKey)) { + serverNode = viewCache.serverCache.getNode(); + const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode); + if (eventChildUpdate != null) { + newEventChild = oldEventSnap + .getNode() + .getImmediateChild(childKey) + .updateChild(childChangePath, eventChildUpdate); + } + else { + // Nothing changed, just keep the old child + newEventChild = oldEventSnap.getNode().getImmediateChild(childKey); + } + } + else { + newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache); + } + if (newEventChild != null) { + newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator); + } + else { + // no complete child available or no change + newEventCache = oldEventSnap.getNode(); + } + } + } + return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes()); + } +} +function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) { + const oldServerSnap = oldViewCache.serverCache; + let newServerCache; + const serverFilter = filterServerNode + ? viewProcessor.filter + : viewProcessor.filter.getIndexedFilter(); + if (pathIsEmpty(changePath)) { + newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null); + } + else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) { + // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update + const newServerNode = oldServerSnap + .getNode() + .updateChild(changePath, changedSnap); + newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null); + } + else { + const childKey = pathGetFront(changePath); + if (!oldServerSnap.isCompleteForPath(changePath) && + pathGetLength(changePath) > 1) { + // We don't update incomplete nodes with updates intended for other listeners + return oldViewCache; + } + const childChangePath = pathPopFront(changePath); + const childNode = oldServerSnap.getNode().getImmediateChild(childKey); + const newChildNode = childNode.updateChild(childChangePath, changedSnap); + if (childKey === '.priority') { + newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode); + } + else { + newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null); + } + } + const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes()); + const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache); + return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator); +} +function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) { + const oldEventSnap = oldViewCache.eventCache; + let newViewCache, newEventCache; + const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache); + if (pathIsEmpty(changePath)) { + newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator); + newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes()); + } + else { + const childKey = pathGetFront(changePath); + if (childKey === '.priority') { + newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap); + newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered()); + } + else { + const childChangePath = pathPopFront(changePath); + const oldChild = oldEventSnap.getNode().getImmediateChild(childKey); + let newChild; + if (pathIsEmpty(childChangePath)) { + // Child overwrite, we can replace the child + newChild = changedSnap; + } + else { + const childNode = source.getCompleteChild(childKey); + if (childNode != null) { + if (pathGetBack(childChangePath) === '.priority' && + childNode.getChild(pathParent(childChangePath)).isEmpty()) { + // This is a priority update on an empty node. If this node exists on the server, the + // server will send down the priority in the update, so ignore for now + newChild = childNode; + } + else { + newChild = childNode.updateChild(childChangePath, changedSnap); + } + } + else { + // There is no complete child node available + newChild = ChildrenNode.EMPTY_NODE; + } + } + if (!oldChild.equals(newChild)) { + const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator); + newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes()); + } + else { + newViewCache = oldViewCache; + } + } + } + return newViewCache; +} +function viewProcessorCacheHasChild(viewCache, childKey) { + return viewCache.eventCache.isCompleteForChild(childKey); +} +function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) { + // HACK: In the case of a limit query, there may be some changes that bump things out of the + // window leaving room for new items. It's important we process these changes first, so we + // iterate the changes twice, first processing any that affect items currently in view. + // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server + // and event snap. I'm not sure if this will result in edge cases when a child is in one but + // not the other. + let curViewCache = viewCache; + changedChildren.foreach((relativePath, childNode) => { + const writePath = pathChild(path, relativePath); + if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) { + curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator); + } + }); + changedChildren.foreach((relativePath, childNode) => { + const writePath = pathChild(path, relativePath); + if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) { + curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator); + } + }); + return curViewCache; +} +function viewProcessorApplyMerge(viewProcessor, node, merge) { + merge.foreach((relativePath, childNode) => { + node = node.updateChild(relativePath, childNode); + }); + return node; +} +function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) { + // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and + // wait for the complete data update coming soon. + if (viewCache.serverCache.getNode().isEmpty() && + !viewCache.serverCache.isFullyInitialized()) { + return viewCache; + } + // HACK: In the case of a limit query, there may be some changes that bump things out of the + // window leaving room for new items. It's important we process these changes first, so we + // iterate the changes twice, first processing any that affect items currently in view. + // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server + // and event snap. I'm not sure if this will result in edge cases when a child is in one but + // not the other. + let curViewCache = viewCache; + let viewMergeTree; + if (pathIsEmpty(path)) { + viewMergeTree = changedChildren; + } + else { + viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren); + } + const serverNode = viewCache.serverCache.getNode(); + viewMergeTree.children.inorderTraversal((childKey, childTree) => { + if (serverNode.hasChild(childKey)) { + const serverChild = viewCache.serverCache + .getNode() + .getImmediateChild(childKey); + const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree); + curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator); + } + }); + viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => { + const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) && + childMergeTree.value === null; + if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) { + const serverChild = viewCache.serverCache + .getNode() + .getImmediateChild(childKey); + const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree); + curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator); + } + }); + return curViewCache; +} +function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) { + if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) { + return viewCache; + } + // Only filter server node if it is currently filtered + const filterServerNode = viewCache.serverCache.isFiltered(); + // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update + // now that it won't be shadowed. + const serverCache = viewCache.serverCache; + if (affectedTree.value != null) { + // This is an overwrite. + if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) || + serverCache.isCompleteForPath(ackPath)) { + return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator); + } + else if (pathIsEmpty(ackPath)) { + // This is a goofy edge case where we are acking data at this location but don't have full data. We + // should just re-apply whatever we have in our cache as a merge. + let changedChildren = new ImmutableTree(null); + serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => { + changedChildren = changedChildren.set(new Path(name), node); + }); + return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator); + } + else { + return viewCache; + } + } + else { + // This is a merge. + let changedChildren = new ImmutableTree(null); + affectedTree.foreach((mergePath, value) => { + const serverCachePath = pathChild(ackPath, mergePath); + if (serverCache.isCompleteForPath(serverCachePath)) { + changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath)); + } + }); + return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator); + } +} +function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) { + const oldServerNode = viewCache.serverCache; + const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered()); + return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator); +} +function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) { + let complete; + if (writeTreeRefShadowingWrite(writesCache, path) != null) { + return viewCache; + } + else { + const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache); + const oldEventCache = viewCache.eventCache.getNode(); + let newEventCache; + if (pathIsEmpty(path) || pathGetFront(path) === '.priority') { + let newNode; + if (viewCache.serverCache.isFullyInitialized()) { + newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache)); + } + else { + const serverChildren = viewCache.serverCache.getNode(); + util.assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node'); + newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren); + } + newNode = newNode; + newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator); + } + else { + const childKey = pathGetFront(path); + let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache); + if (newChild == null && + viewCache.serverCache.isCompleteForChild(childKey)) { + newChild = oldEventCache.getImmediateChild(childKey); + } + if (newChild != null) { + newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator); + } + else if (viewCache.eventCache.getNode().hasChild(childKey)) { + // No complete child available, delete the existing one, if any + newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator); + } + else { + newEventCache = oldEventCache; + } + if (newEventCache.isEmpty() && + viewCache.serverCache.isFullyInitialized()) { + // We might have reverted all child writes. Maybe the old event was a leaf node + complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache)); + if (complete.isLeafNode()) { + newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator); + } + } + } + complete = + viewCache.serverCache.isFullyInitialized() || + writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null; + return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes()); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A view represents a specific location and query that has 1 or more event registrations. + * + * It does several things: + * - Maintains the list of event registrations for this location/query. + * - Maintains a cache of the data visible for this location/query. + * - Applies new operations (via applyOperation), updates the cache, and based on the event + * registrations returns the set of events to be raised. + */ +class View { + constructor(query_, initialViewCache) { + this.query_ = query_; + this.eventRegistrations_ = []; + const params = this.query_._queryParams; + const indexFilter = new IndexedFilter(params.getIndex()); + const filter = queryParamsGetNodeFilter(params); + this.processor_ = newViewProcessor(filter); + const initialServerCache = initialViewCache.serverCache; + const initialEventCache = initialViewCache.eventCache; + // Don't filter server node with other filter than index, wait for tagged listen + const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null); + const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null); + const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes()); + const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes()); + this.viewCache_ = newViewCache(newEventCache, newServerCache); + this.eventGenerator_ = new EventGenerator(this.query_); + } + get query() { + return this.query_; + } +} +function viewGetServerCache(view) { + return view.viewCache_.serverCache.getNode(); +} +function viewGetCompleteNode(view) { + return viewCacheGetCompleteEventSnap(view.viewCache_); +} +function viewGetCompleteServerCache(view, path) { + const cache = viewCacheGetCompleteServerSnap(view.viewCache_); + if (cache) { + // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and + // we need to see if it contains the child we're interested in. + if (view.query._queryParams.loadsAllData() || + (!pathIsEmpty(path) && + !cache.getImmediateChild(pathGetFront(path)).isEmpty())) { + return cache.getChild(path); + } + } + return null; +} +function viewIsEmpty(view) { + return view.eventRegistrations_.length === 0; +} +function viewAddEventRegistration(view, eventRegistration) { + view.eventRegistrations_.push(eventRegistration); +} +/** + * @param eventRegistration - If null, remove all callbacks. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @returns Cancel events, if cancelError was provided. + */ +function viewRemoveEventRegistration(view, eventRegistration, cancelError) { + const cancelEvents = []; + if (cancelError) { + util.assert(eventRegistration == null, 'A cancel should cancel all event registrations.'); + const path = view.query._path; + view.eventRegistrations_.forEach(registration => { + const maybeEvent = registration.createCancelEvent(cancelError, path); + if (maybeEvent) { + cancelEvents.push(maybeEvent); + } + }); + } + if (eventRegistration) { + let remaining = []; + for (let i = 0; i < view.eventRegistrations_.length; ++i) { + const existing = view.eventRegistrations_[i]; + if (!existing.matches(eventRegistration)) { + remaining.push(existing); + } + else if (eventRegistration.hasAnyCallback()) { + // We're removing just this one + remaining = remaining.concat(view.eventRegistrations_.slice(i + 1)); + break; + } + } + view.eventRegistrations_ = remaining; + } + else { + view.eventRegistrations_ = []; + } + return cancelEvents; +} +/** + * Applies the given Operation, updates our cache, and returns the appropriate events. + */ +function viewApplyOperation(view, operation, writesCache, completeServerCache) { + if (operation.type === OperationType.MERGE && + operation.source.queryId !== null) { + util.assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges'); + util.assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache'); + } + const oldViewCache = view.viewCache_; + const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache); + viewProcessorAssertIndexed(view.processor_, result.viewCache); + util.assert(result.viewCache.serverCache.isFullyInitialized() || + !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back'); + view.viewCache_ = result.viewCache; + return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null); +} +function viewGetInitialEvents(view, registration) { + const eventSnap = view.viewCache_.eventCache; + const initialChanges = []; + if (!eventSnap.getNode().isLeafNode()) { + const eventNode = eventSnap.getNode(); + eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => { + initialChanges.push(changeChildAdded(key, childNode)); + }); + } + if (eventSnap.isFullyInitialized()) { + initialChanges.push(changeValue(eventSnap.getNode())); + } + return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration); +} +function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) { + const registrations = eventRegistration + ? [eventRegistration] + : view.eventRegistrations_; + return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let referenceConstructor$1; +/** + * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to + * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes + * and user writes (set, transaction, update). + * + * It's responsible for: + * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed). + * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite, + * applyUserOverwrite, etc.) + */ +class SyncPoint { + constructor() { + /** + * The Views being tracked at this location in the tree, stored as a map where the key is a + * queryId and the value is the View for that query. + * + * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case). + */ + this.views = new Map(); + } +} +function syncPointSetReferenceConstructor(val) { + util.assert(!referenceConstructor$1, '__referenceConstructor has already been defined'); + referenceConstructor$1 = val; +} +function syncPointGetReferenceConstructor() { + util.assert(referenceConstructor$1, 'Reference.ts has not been loaded'); + return referenceConstructor$1; +} +function syncPointIsEmpty(syncPoint) { + return syncPoint.views.size === 0; +} +function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) { + const queryId = operation.source.queryId; + if (queryId !== null) { + const view = syncPoint.views.get(queryId); + util.assert(view != null, 'SyncTree gave us an op for an invalid query.'); + return viewApplyOperation(view, operation, writesCache, optCompleteServerCache); + } + else { + let events = []; + for (const view of syncPoint.views.values()) { + events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache)); + } + return events; + } +} +/** + * Get a view for the specified query. + * + * @param query - The query to return a view for + * @param writesCache + * @param serverCache + * @param serverCacheComplete + * @returns Events to raise. + */ +function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) { + const queryId = query._queryIdentifier; + const view = syncPoint.views.get(queryId); + if (!view) { + // TODO: make writesCache take flag for complete server node + let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null); + let eventCacheComplete = false; + if (eventCache) { + eventCacheComplete = true; + } + else if (serverCache instanceof ChildrenNode) { + eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache); + eventCacheComplete = false; + } + else { + eventCache = ChildrenNode.EMPTY_NODE; + eventCacheComplete = false; + } + const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false)); + return new View(query, viewCache); + } + return view; +} +/** + * Add an event callback for the specified query. + * + * @param query + * @param eventRegistration + * @param writesCache + * @param serverCache - Complete server cache, if we have it. + * @param serverCacheComplete + * @returns Events to raise. + */ +function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) { + const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete); + if (!syncPoint.views.has(query._queryIdentifier)) { + syncPoint.views.set(query._queryIdentifier, view); + } + // This is guaranteed to exist now, we just created anything that was missing + viewAddEventRegistration(view, eventRegistration); + return viewGetInitialEvents(view, eventRegistration); +} +/** + * Remove event callback(s). Return cancelEvents if a cancelError is specified. + * + * If query is the default query, we'll check all views for the specified eventRegistration. + * If eventRegistration is null, we'll remove all callbacks for the specified view(s). + * + * @param eventRegistration - If null, remove all callbacks. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @returns removed queries and any cancel events + */ +function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) { + const queryId = query._queryIdentifier; + const removed = []; + let cancelEvents = []; + const hadCompleteView = syncPointHasCompleteView(syncPoint); + if (queryId === 'default') { + // When you do ref.off(...), we search all views for the registration to remove. + for (const [viewQueryId, view] of syncPoint.views.entries()) { + cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError)); + if (viewIsEmpty(view)) { + syncPoint.views.delete(viewQueryId); + // We'll deal with complete views later. + if (!view.query._queryParams.loadsAllData()) { + removed.push(view.query); + } + } + } + } + else { + // remove the callback from the specific view. + const view = syncPoint.views.get(queryId); + if (view) { + cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError)); + if (viewIsEmpty(view)) { + syncPoint.views.delete(queryId); + // We'll deal with complete views later. + if (!view.query._queryParams.loadsAllData()) { + removed.push(view.query); + } + } + } + } + if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) { + // We removed our last complete view. + removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path)); + } + return { removed, events: cancelEvents }; +} +function syncPointGetQueryViews(syncPoint) { + const result = []; + for (const view of syncPoint.views.values()) { + if (!view.query._queryParams.loadsAllData()) { + result.push(view); + } + } + return result; +} +/** + * @param path - The path to the desired complete snapshot + * @returns A complete cache, if it exists + */ +function syncPointGetCompleteServerCache(syncPoint, path) { + let serverCache = null; + for (const view of syncPoint.views.values()) { + serverCache = serverCache || viewGetCompleteServerCache(view, path); + } + return serverCache; +} +function syncPointViewForQuery(syncPoint, query) { + const params = query._queryParams; + if (params.loadsAllData()) { + return syncPointGetCompleteView(syncPoint); + } + else { + const queryId = query._queryIdentifier; + return syncPoint.views.get(queryId); + } +} +function syncPointViewExistsForQuery(syncPoint, query) { + return syncPointViewForQuery(syncPoint, query) != null; +} +function syncPointHasCompleteView(syncPoint) { + return syncPointGetCompleteView(syncPoint) != null; +} +function syncPointGetCompleteView(syncPoint) { + for (const view of syncPoint.views.values()) { + if (view.query._queryParams.loadsAllData()) { + return view; + } + } + return null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let referenceConstructor; +function syncTreeSetReferenceConstructor(val) { + util.assert(!referenceConstructor, '__referenceConstructor has already been defined'); + referenceConstructor = val; +} +function syncTreeGetReferenceConstructor() { + util.assert(referenceConstructor, 'Reference.ts has not been loaded'); + return referenceConstructor; +} +/** + * Static tracker for next query tag. + */ +let syncTreeNextQueryTag_ = 1; +/** + * SyncTree is the central class for managing event callback registration, data caching, views + * (query processing), and event generation. There are typically two SyncTree instances for + * each Repo, one for the normal Firebase data, and one for the .info data. + * + * It has a number of responsibilities, including: + * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()). + * - Applying and caching data changes for user set(), transaction(), and update() calls + * (applyUserOverwrite(), applyUserMerge()). + * - Applying and caching data changes for server data changes (applyServerOverwrite(), + * applyServerMerge()). + * - Generating user-facing events for server and user changes (all of the apply* methods + * return the set of events that need to be raised as a result). + * - Maintaining the appropriate set of server listens to ensure we are always subscribed + * to the correct set of paths and queries to satisfy the current set of user event + * callbacks (listens are started/stopped using the provided listenProvider). + * + * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual + * events are returned to the caller rather than raised synchronously. + * + */ +class SyncTree { + /** + * @param listenProvider_ - Used by SyncTree to start / stop listening + * to server data. + */ + constructor(listenProvider_) { + this.listenProvider_ = listenProvider_; + /** + * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views. + */ + this.syncPointTree_ = new ImmutableTree(null); + /** + * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.). + */ + this.pendingWriteTree_ = newWriteTree(); + this.tagToQueryMap = new Map(); + this.queryToTagMap = new Map(); + } +} +/** + * Apply the data changes for a user-generated set() or transaction() call. + * + * @returns Events to raise. + */ +function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) { + // Record pending write. + writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible); + if (!visible) { + return []; + } + else { + return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData)); + } +} +/** + * Apply the data from a user-generated update() call + * + * @returns Events to raise. + */ +function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) { + // Record pending merge. + writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId); + const changeTree = ImmutableTree.fromObject(changedChildren); + return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree)); +} +/** + * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge(). + * + * @param revert - True if the given write failed and needs to be reverted + * @returns Events to raise. + */ +function syncTreeAckUserWrite(syncTree, writeId, revert = false) { + const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId); + const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId); + if (!needToReevaluate) { + return []; + } + else { + let affectedTree = new ImmutableTree(null); + if (write.snap != null) { + // overwrite + affectedTree = affectedTree.set(newEmptyPath(), true); + } + else { + each(write.children, (pathString) => { + affectedTree = affectedTree.set(new Path(pathString), true); + }); + } + return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert)); + } +} +/** + * Apply new server data for the specified path.. + * + * @returns Events to raise. + */ +function syncTreeApplyServerOverwrite(syncTree, path, newData) { + return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData)); +} +/** + * Apply new server data to be merged in at the specified path. + * + * @returns Events to raise. + */ +function syncTreeApplyServerMerge(syncTree, path, changedChildren) { + const changeTree = ImmutableTree.fromObject(changedChildren); + return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree)); +} +/** + * Apply a listen complete for a query + * + * @returns Events to raise. + */ +function syncTreeApplyListenComplete(syncTree, path) { + return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path)); +} +/** + * Apply a listen complete for a tagged query + * + * @returns Events to raise. + */ +function syncTreeApplyTaggedListenComplete(syncTree, path, tag) { + const queryKey = syncTreeQueryKeyForTag_(syncTree, tag); + if (queryKey) { + const r = syncTreeParseQueryKey_(queryKey); + const queryPath = r.path, queryId = r.queryId; + const relativePath = newRelativePath(queryPath, path); + const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath); + return syncTreeApplyTaggedOperation_(syncTree, queryPath, op); + } + else { + // We've already removed the query. No big deal, ignore the update + return []; + } +} +/** + * Remove event callback(s). + * + * If query is the default query, we'll check all queries for the specified eventRegistration. + * If eventRegistration is null, we'll remove all callbacks for the specified query/queries. + * + * @param eventRegistration - If null, all callbacks are removed. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no + * deduping needs to take place. This flag allows toggling of that behavior + * @returns Cancel events, if cancelError was provided. + */ +function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) { + // Find the syncPoint first. Then deal with whether or not it has matching listeners + const path = query._path; + const maybeSyncPoint = syncTree.syncPointTree_.get(path); + let cancelEvents = []; + // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without + // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and + // not loadsAllData(). + if (maybeSyncPoint && + (query._queryIdentifier === 'default' || + syncPointViewExistsForQuery(maybeSyncPoint, query))) { + const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError); + if (syncPointIsEmpty(maybeSyncPoint)) { + syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path); + } + const removed = removedAndEvents.removed; + cancelEvents = removedAndEvents.events; + if (!skipListenerDedup) { + /** + * We may have just removed one of many listeners and can short-circuit this whole process + * We may also not have removed a default listener, in which case all of the descendant listeners should already be + * properly set up. + */ + // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of + // queryId === 'default' + const removingDefault = -1 !== + removed.findIndex(query => { + return query._queryParams.loadsAllData(); + }); + const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint)); + if (removingDefault && !covered) { + const subtree = syncTree.syncPointTree_.subtree(path); + // There are potentially child listeners. Determine what if any listens we need to send before executing the + // removal + if (!subtree.isEmpty()) { + // We need to fold over our subtree and collect the listeners to send + const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree); + // Ok, we've collected all the listens we need. Set them up. + for (let i = 0; i < newViews.length; ++i) { + const view = newViews[i], newQuery = view.query; + const listener = syncTreeCreateListenerForView_(syncTree, view); + syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete); + } + } + // Otherwise there's nothing below us, so nothing we need to start listening on + } + // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query + // The above block has us covered in terms of making sure we're set up on listens lower in the tree. + // Also, note that if we have a cancelError, it's already been removed at the provider level. + if (!covered && removed.length > 0 && !cancelError) { + // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one + // default. Otherwise, we need to iterate through and cancel each individual query + if (removingDefault) { + // We don't tag default listeners + const defaultTag = null; + syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag); + } + else { + removed.forEach((queryToRemove) => { + const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove)); + syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove); + }); + } + } + } + // Now, clear all of the tags we're tracking for the removed listens + syncTreeRemoveTags_(syncTree, removed); + } + return cancelEvents; +} +/** + * Apply new server data for the specified tagged query. + * + * @returns Events to raise. + */ +function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) { + const queryKey = syncTreeQueryKeyForTag_(syncTree, tag); + if (queryKey != null) { + const r = syncTreeParseQueryKey_(queryKey); + const queryPath = r.path, queryId = r.queryId; + const relativePath = newRelativePath(queryPath, path); + const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap); + return syncTreeApplyTaggedOperation_(syncTree, queryPath, op); + } + else { + // Query must have been removed already + return []; + } +} +/** + * Apply server data to be merged in for the specified tagged query. + * + * @returns Events to raise. + */ +function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) { + const queryKey = syncTreeQueryKeyForTag_(syncTree, tag); + if (queryKey) { + const r = syncTreeParseQueryKey_(queryKey); + const queryPath = r.path, queryId = r.queryId; + const relativePath = newRelativePath(queryPath, path); + const changeTree = ImmutableTree.fromObject(changedChildren); + const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree); + return syncTreeApplyTaggedOperation_(syncTree, queryPath, op); + } + else { + // We've already removed the query. No big deal, ignore the update + return []; + } +} +/** + * Add an event callback for the specified query. + * + * @returns Events to raise. + */ +function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) { + const path = query._path; + let serverCache = null; + let foundAncestorDefaultView = false; + // Any covering writes will necessarily be at the root, so really all we need to find is the server cache. + // Consider optimizing this once there's a better understanding of what actual behavior will be. + syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => { + const relativePath = newRelativePath(pathToSyncPoint, path); + serverCache = + serverCache || syncPointGetCompleteServerCache(sp, relativePath); + foundAncestorDefaultView = + foundAncestorDefaultView || syncPointHasCompleteView(sp); + }); + let syncPoint = syncTree.syncPointTree_.get(path); + if (!syncPoint) { + syncPoint = new SyncPoint(); + syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint); + } + else { + foundAncestorDefaultView = + foundAncestorDefaultView || syncPointHasCompleteView(syncPoint); + serverCache = + serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + let serverCacheComplete; + if (serverCache != null) { + serverCacheComplete = true; + } + else { + serverCacheComplete = false; + serverCache = ChildrenNode.EMPTY_NODE; + const subtree = syncTree.syncPointTree_.subtree(path); + subtree.foreachChild((childName, childSyncPoint) => { + const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath()); + if (completeCache) { + serverCache = serverCache.updateImmediateChild(childName, completeCache); + } + }); + } + const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query); + if (!viewAlreadyExists && !query._queryParams.loadsAllData()) { + // We need to track a tag for this query + const queryKey = syncTreeMakeQueryKey_(query); + util.assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag'); + const tag = syncTreeGetNextQueryTag_(); + syncTree.queryToTagMap.set(queryKey, tag); + syncTree.tagToQueryMap.set(tag, queryKey); + } + const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path); + let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete); + if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) { + const view = syncPointViewForQuery(syncPoint, query); + events = events.concat(syncTreeSetupListener_(syncTree, query, view)); + } + return events; +} +/** + * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a + * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always + * have a listener above, and atomic operations would correctly show a jitter of -> + * as the write is applied locally and then acknowledged at the server. + * + * Note: this method will *include* hidden writes from transaction with applyLocally set to false. + * + * @param path - The path to the data we want + * @param writeIdsToExclude - A specific set to be excluded + */ +function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) { + const includeHiddenSets = true; + const writeTree = syncTree.pendingWriteTree_; + const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => { + const relativePath = newRelativePath(pathSoFar, path); + const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath); + if (serverCache) { + return serverCache; + } + }); + return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets); +} +function syncTreeGetServerValue(syncTree, query) { + const path = query._path; + let serverCache = null; + // Any covering writes will necessarily be at the root, so really all we need to find is the server cache. + // Consider optimizing this once there's a better understanding of what actual behavior will be. + syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => { + const relativePath = newRelativePath(pathToSyncPoint, path); + serverCache = + serverCache || syncPointGetCompleteServerCache(sp, relativePath); + }); + let syncPoint = syncTree.syncPointTree_.get(path); + if (!syncPoint) { + syncPoint = new SyncPoint(); + syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint); + } + else { + serverCache = + serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + const serverCacheComplete = serverCache != null; + const serverCacheNode = serverCacheComplete + ? new CacheNode(serverCache, true, false) + : null; + const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path); + const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete); + return viewGetCompleteNode(view); +} +/** + * A helper method that visits all descendant and ancestor SyncPoints, applying the operation. + * + * NOTES: + * - Descendant SyncPoints will be visited first (since we raise events depth-first). + * + * - We call applyOperation() on each SyncPoint passing three things: + * 1. A version of the Operation that has been made relative to the SyncPoint location. + * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location. + * 3. A snapshot Node with cached server data, if we have it. + * + * - We concatenate all of the events returned by each SyncPoint and return the result. + */ +function syncTreeApplyOperationToSyncPoints_(syncTree, operation) { + return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_, + /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath())); +} +/** + * Recursive helper for applyOperationToSyncPoints_ + */ +function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) { + if (pathIsEmpty(operation.path)) { + return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache); + } + else { + const syncPoint = syncPointTree.get(newEmptyPath()); + // If we don't have cached server data, see if we can get it from this SyncPoint. + if (serverCache == null && syncPoint != null) { + serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + let events = []; + const childName = pathGetFront(operation.path); + const childOperation = operation.operationForChild(childName); + const childTree = syncPointTree.children.get(childName); + if (childTree && childOperation) { + const childServerCache = serverCache + ? serverCache.getImmediateChild(childName) + : null; + const childWritesCache = writeTreeRefChild(writesCache, childName); + events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache)); + } + if (syncPoint) { + events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)); + } + return events; + } +} +/** + * Recursive helper for applyOperationToSyncPoints_ + */ +function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) { + const syncPoint = syncPointTree.get(newEmptyPath()); + // If we don't have cached server data, see if we can get it from this SyncPoint. + if (serverCache == null && syncPoint != null) { + serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + let events = []; + syncPointTree.children.inorderTraversal((childName, childTree) => { + const childServerCache = serverCache + ? serverCache.getImmediateChild(childName) + : null; + const childWritesCache = writeTreeRefChild(writesCache, childName); + const childOperation = operation.operationForChild(childName); + if (childOperation) { + events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache)); + } + }); + if (syncPoint) { + events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)); + } + return events; +} +function syncTreeCreateListenerForView_(syncTree, view) { + const query = view.query; + const tag = syncTreeTagForQuery(syncTree, query); + return { + hashFn: () => { + const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE; + return cache.hash(); + }, + onComplete: (status) => { + if (status === 'ok') { + if (tag) { + return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag); + } + else { + return syncTreeApplyListenComplete(syncTree, query._path); + } + } + else { + // If a listen failed, kill all of the listeners here, not just the one that triggered the error. + // Note that this may need to be scoped to just this listener if we change permissions on filtered children + const error = errorForServerCode(status, query); + return syncTreeRemoveEventRegistration(syncTree, query, + /*eventRegistration*/ null, error); + } + } + }; +} +/** + * Return the tag associated with the given query. + */ +function syncTreeTagForQuery(syncTree, query) { + const queryKey = syncTreeMakeQueryKey_(query); + return syncTree.queryToTagMap.get(queryKey); +} +/** + * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_. + */ +function syncTreeMakeQueryKey_(query) { + return query._path.toString() + '$' + query._queryIdentifier; +} +/** + * Return the query associated with the given tag, if we have one + */ +function syncTreeQueryKeyForTag_(syncTree, tag) { + return syncTree.tagToQueryMap.get(tag); +} +/** + * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId. + */ +function syncTreeParseQueryKey_(queryKey) { + const splitIndex = queryKey.indexOf('$'); + util.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.'); + return { + queryId: queryKey.substr(splitIndex + 1), + path: new Path(queryKey.substr(0, splitIndex)) + }; +} +/** + * A helper method to apply tagged operations + */ +function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) { + const syncPoint = syncTree.syncPointTree_.get(queryPath); + util.assert(syncPoint, "Missing sync point for query tag that we're tracking"); + const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath); + return syncPointApplyOperation(syncPoint, operation, writesCache, null); +} +/** + * This collapses multiple unfiltered views into a single view, since we only need a single + * listener for them. + */ +function syncTreeCollectDistinctViewsForSubTree_(subtree) { + return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => { + if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) { + const completeView = syncPointGetCompleteView(maybeChildSyncPoint); + return [completeView]; + } + else { + // No complete view here, flatten any deeper listens into an array + let views = []; + if (maybeChildSyncPoint) { + views = syncPointGetQueryViews(maybeChildSyncPoint); + } + each(childMap, (_key, childViews) => { + views = views.concat(childViews); + }); + return views; + } + }); +} +/** + * Normalizes a query to a query we send the server for listening + * + * @returns The normalized query + */ +function syncTreeQueryForListening_(query) { + if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) { + // We treat queries that load all data as default queries + // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits + // from Query + return new (syncTreeGetReferenceConstructor())(query._repo, query._path); + } + else { + return query; + } +} +function syncTreeRemoveTags_(syncTree, queries) { + for (let j = 0; j < queries.length; ++j) { + const removedQuery = queries[j]; + if (!removedQuery._queryParams.loadsAllData()) { + // We should have a tag for this + const removedQueryKey = syncTreeMakeQueryKey_(removedQuery); + const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey); + syncTree.queryToTagMap.delete(removedQueryKey); + syncTree.tagToQueryMap.delete(removedQueryTag); + } + } +} +/** + * Static accessor for query tags. + */ +function syncTreeGetNextQueryTag_() { + return syncTreeNextQueryTag_++; +} +/** + * For a given new listen, manage the de-duplication of outstanding subscriptions. + * + * @returns This method can return events to support synchronous data sources + */ +function syncTreeSetupListener_(syncTree, query, view) { + const path = query._path; + const tag = syncTreeTagForQuery(syncTree, query); + const listener = syncTreeCreateListenerForView_(syncTree, view); + const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete); + const subtree = syncTree.syncPointTree_.subtree(path); + // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we + // may need to shadow other listens as well. + if (tag) { + util.assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed"); + } + else { + // Shadow everything at or below this location, this is a default listener. + const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => { + if (!pathIsEmpty(relativePath) && + maybeChildSyncPoint && + syncPointHasCompleteView(maybeChildSyncPoint)) { + return [syncPointGetCompleteView(maybeChildSyncPoint).query]; + } + else { + // No default listener here, flatten any deeper queries into an array + let queries = []; + if (maybeChildSyncPoint) { + queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query)); + } + each(childMap, (_key, childQueries) => { + queries = queries.concat(childQueries); + }); + return queries; + } + }); + for (let i = 0; i < queriesToStop.length; ++i) { + const queryToStop = queriesToStop[i]; + syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop)); + } + } + return events; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ExistingValueProvider { + constructor(node_) { + this.node_ = node_; + } + getImmediateChild(childName) { + const child = this.node_.getImmediateChild(childName); + return new ExistingValueProvider(child); + } + node() { + return this.node_; + } +} +class DeferredValueProvider { + constructor(syncTree, path) { + this.syncTree_ = syncTree; + this.path_ = path; + } + getImmediateChild(childName) { + const childPath = pathChild(this.path_, childName); + return new DeferredValueProvider(this.syncTree_, childPath); + } + node() { + return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_); + } +} +/** + * Generate placeholders for deferred values. + */ +const generateWithValues = function (values) { + values = values || {}; + values['timestamp'] = values['timestamp'] || new Date().getTime(); + return values; +}; +/** + * Value to use when firing local events. When writing server values, fire + * local events with an approximate value, otherwise return value as-is. + */ +const resolveDeferredLeafValue = function (value, existingVal, serverValues) { + if (!value || typeof value !== 'object') { + return value; + } + util.assert('.sv' in value, 'Unexpected leaf node or priority contents'); + if (typeof value['.sv'] === 'string') { + return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues); + } + else if (typeof value['.sv'] === 'object') { + return resolveComplexDeferredValue(value['.sv'], existingVal); + } + else { + util.assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2)); + } +}; +const resolveScalarDeferredValue = function (op, existing, serverValues) { + switch (op) { + case 'timestamp': + return serverValues['timestamp']; + default: + util.assert(false, 'Unexpected server value: ' + op); + } +}; +const resolveComplexDeferredValue = function (op, existing, unused) { + if (!op.hasOwnProperty('increment')) { + util.assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2)); + } + const delta = op['increment']; + if (typeof delta !== 'number') { + util.assert(false, 'Unexpected increment value: ' + delta); + } + const existingNode = existing.node(); + util.assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls'); + // Incrementing a non-number sets the value to the incremented amount + if (!existingNode.isLeafNode()) { + return delta; + } + const leaf = existingNode; + const existingVal = leaf.getValue(); + if (typeof existingVal !== 'number') { + return delta; + } + // No need to do over/underflow arithmetic here because JS only handles floats under the covers + return existingVal + delta; +}; +/** + * Recursively replace all deferred values and priorities in the tree with the + * specified generated replacement values. + * @param path - path to which write is relative + * @param node - new data written at path + * @param syncTree - current data + */ +const resolveDeferredValueTree = function (path, node, syncTree, serverValues) { + return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues); +}; +/** + * Recursively replace all deferred values and priorities in the node with the + * specified generated replacement values. If there are no server values in the node, + * it'll be returned as-is. + */ +const resolveDeferredValueSnapshot = function (node, existing, serverValues) { + return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues); +}; +function resolveDeferredValue(node, existingVal, serverValues) { + const rawPri = node.getPriority().val(); + const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues); + let newNode; + if (node.isLeafNode()) { + const leafNode = node; + const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues); + if (value !== leafNode.getValue() || + priority !== leafNode.getPriority().val()) { + return new LeafNode(value, nodeFromJSON(priority)); + } + else { + return node; + } + } + else { + const childrenNode = node; + newNode = childrenNode; + if (priority !== childrenNode.getPriority().val()) { + newNode = newNode.updatePriority(new LeafNode(priority)); + } + childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => { + const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues); + if (newChildNode !== childNode) { + newNode = newNode.updateImmediateChild(childName, newChildNode); + } + }); + return newNode; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A light-weight tree, traversable by path. Nodes can have both values and children. + * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty + * children. + */ +class Tree { + /** + * @param name - Optional name of the node. + * @param parent - Optional parent node. + * @param node - Optional node to wrap. + */ + constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) { + this.name = name; + this.parent = parent; + this.node = node; + } +} +/** + * Returns a sub-Tree for the given path. + * + * @param pathObj - Path to look up. + * @returns Tree for path. + */ +function treeSubTree(tree, pathObj) { + // TODO: Require pathObj to be Path? + let path = pathObj instanceof Path ? pathObj : new Path(pathObj); + let child = tree, next = pathGetFront(path); + while (next !== null) { + const childNode = util.safeGet(child.node.children, next) || { + children: {}, + childCount: 0 + }; + child = new Tree(next, child, childNode); + path = pathPopFront(path); + next = pathGetFront(path); + } + return child; +} +/** + * Returns the data associated with this tree node. + * + * @returns The data or null if no data exists. + */ +function treeGetValue(tree) { + return tree.node.value; +} +/** + * Sets data to this tree node. + * + * @param value - Value to set. + */ +function treeSetValue(tree, value) { + tree.node.value = value; + treeUpdateParents(tree); +} +/** + * @returns Whether the tree has any children. + */ +function treeHasChildren(tree) { + return tree.node.childCount > 0; +} +/** + * @returns Whether the tree is empty (no value or children). + */ +function treeIsEmpty(tree) { + return treeGetValue(tree) === undefined && !treeHasChildren(tree); +} +/** + * Calls action for each child of this tree node. + * + * @param action - Action to be called for each child. + */ +function treeForEachChild(tree, action) { + each(tree.node.children, (child, childTree) => { + action(new Tree(child, tree, childTree)); + }); +} +/** + * Does a depth-first traversal of this node's descendants, calling action for each one. + * + * @param action - Action to be called for each child. + * @param includeSelf - Whether to call action on this node as well. Defaults to + * false. + * @param childrenFirst - Whether to call action on children before calling it on + * parent. + */ +function treeForEachDescendant(tree, action, includeSelf, childrenFirst) { + if (includeSelf && !childrenFirst) { + action(tree); + } + treeForEachChild(tree, child => { + treeForEachDescendant(child, action, true, childrenFirst); + }); + if (includeSelf && childrenFirst) { + action(tree); + } +} +/** + * Calls action on each ancestor node. + * + * @param action - Action to be called on each parent; return + * true to abort. + * @param includeSelf - Whether to call action on this node as well. + * @returns true if the action callback returned true. + */ +function treeForEachAncestor(tree, action, includeSelf) { + let node = includeSelf ? tree : tree.parent; + while (node !== null) { + if (action(node)) { + return true; + } + node = node.parent; + } + return false; +} +/** + * @returns The path of this tree node, as a Path. + */ +function treeGetPath(tree) { + return new Path(tree.parent === null + ? tree.name + : treeGetPath(tree.parent) + '/' + tree.name); +} +/** + * Adds or removes this child from its parent based on whether it's empty or not. + */ +function treeUpdateParents(tree) { + if (tree.parent !== null) { + treeUpdateChild(tree.parent, tree.name, tree); + } +} +/** + * Adds or removes the passed child to this tree node, depending on whether it's empty. + * + * @param childName - The name of the child to update. + * @param child - The child to update. + */ +function treeUpdateChild(tree, childName, child) { + const childEmpty = treeIsEmpty(child); + const childExists = util.contains(tree.node.children, childName); + if (childEmpty && childExists) { + delete tree.node.children[childName]; + tree.node.childCount--; + treeUpdateParents(tree); + } + else if (!childEmpty && !childExists) { + tree.node.children[childName] = child.node; + tree.node.childCount++; + treeUpdateParents(tree); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * True for invalid Firebase keys + */ +const INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/; +/** + * True for invalid Firebase paths. + * Allows '/' in paths. + */ +const INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/; +/** + * Maximum number of characters to allow in leaf value + */ +const MAX_LEAF_SIZE_ = 10 * 1024 * 1024; +const isValidKey = function (key) { + return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key)); +}; +const isValidPathString = function (pathString) { + return (typeof pathString === 'string' && + pathString.length !== 0 && + !INVALID_PATH_REGEX_.test(pathString)); +}; +const isValidRootPathString = function (pathString) { + if (pathString) { + // Allow '/.info/' at the beginning. + pathString = pathString.replace(/^\/*\.info(\/|$)/, '/'); + } + return isValidPathString(pathString); +}; +const isValidPriority = function (priority) { + return (priority === null || + typeof priority === 'string' || + (typeof priority === 'number' && !isInvalidJSONNumber(priority)) || + (priority && + typeof priority === 'object' && + // eslint-disable-next-line @typescript-eslint/no-explicit-any + util.contains(priority, '.sv'))); +}; +/** + * Pre-validate a datum passed as an argument to Firebase function. + */ +const validateFirebaseDataArg = function (fnName, value, path, optional) { + if (optional && value === undefined) { + return; + } + validateFirebaseData(util.errorPrefix(fnName, 'value'), value, path); +}; +/** + * Validate a data object client-side before sending to server. + */ +const validateFirebaseData = function (errorPrefix, data, path_) { + const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_; + if (data === undefined) { + throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path)); + } + if (typeof data === 'function') { + throw new Error(errorPrefix + + 'contains a function ' + + validationPathToErrorString(path) + + ' with contents = ' + + data.toString()); + } + if (isInvalidJSONNumber(data)) { + throw new Error(errorPrefix + + 'contains ' + + data.toString() + + ' ' + + validationPathToErrorString(path)); + } + // Check max leaf size, but try to avoid the utf8 conversion if we can. + if (typeof data === 'string' && + data.length > MAX_LEAF_SIZE_ / 3 && + util.stringLength(data) > MAX_LEAF_SIZE_) { + throw new Error(errorPrefix + + 'contains a string greater than ' + + MAX_LEAF_SIZE_ + + ' utf8 bytes ' + + validationPathToErrorString(path) + + " ('" + + data.substring(0, 50) + + "...')"); + } + // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON + // to save extra walking of large objects. + if (data && typeof data === 'object') { + let hasDotValue = false; + let hasActualChild = false; + each(data, (key, value) => { + if (key === '.value') { + hasDotValue = true; + } + else if (key !== '.priority' && key !== '.sv') { + hasActualChild = true; + if (!isValidKey(key)) { + throw new Error(errorPrefix + + ' contains an invalid key (' + + key + + ') ' + + validationPathToErrorString(path) + + '. Keys must be non-empty strings ' + + 'and can\'t contain ".", "#", "$", "/", "[", or "]"'); + } + } + validationPathPush(path, key); + validateFirebaseData(errorPrefix, value, path); + validationPathPop(path); + }); + if (hasDotValue && hasActualChild) { + throw new Error(errorPrefix + + ' contains ".value" child ' + + validationPathToErrorString(path) + + ' in addition to actual children.'); + } + } +}; +/** + * Pre-validate paths passed in the firebase function. + */ +const validateFirebaseMergePaths = function (errorPrefix, mergePaths) { + let i, curPath; + for (i = 0; i < mergePaths.length; i++) { + curPath = mergePaths[i]; + const keys = pathSlice(curPath); + for (let j = 0; j < keys.length; j++) { + if (keys[j] === '.priority' && j === keys.length - 1) ; + else if (!isValidKey(keys[j])) { + throw new Error(errorPrefix + + 'contains an invalid key (' + + keys[j] + + ') in path ' + + curPath.toString() + + '. Keys must be non-empty strings ' + + 'and can\'t contain ".", "#", "$", "/", "[", or "]"'); + } + } + } + // Check that update keys are not descendants of each other. + // We rely on the property that sorting guarantees that ancestors come + // right before descendants. + mergePaths.sort(pathCompare); + let prevPath = null; + for (i = 0; i < mergePaths.length; i++) { + curPath = mergePaths[i]; + if (prevPath !== null && pathContains(prevPath, curPath)) { + throw new Error(errorPrefix + + 'contains a path ' + + prevPath.toString() + + ' that is ancestor of another path ' + + curPath.toString()); + } + prevPath = curPath; + } +}; +/** + * pre-validate an object passed as an argument to firebase function ( + * must be an object - e.g. for firebase.update()). + */ +const validateFirebaseMergeDataArg = function (fnName, data, path, optional) { + if (optional && data === undefined) { + return; + } + const errorPrefix = util.errorPrefix(fnName, 'values'); + if (!(data && typeof data === 'object') || Array.isArray(data)) { + throw new Error(errorPrefix + ' must be an object containing the children to replace.'); + } + const mergePaths = []; + each(data, (key, value) => { + const curPath = new Path(key); + validateFirebaseData(errorPrefix, value, pathChild(path, curPath)); + if (pathGetBack(curPath) === '.priority') { + if (!isValidPriority(value)) { + throw new Error(errorPrefix + + "contains an invalid value for '" + + curPath.toString() + + "', which must be a valid " + + 'Firebase priority (a string, finite number, server value, or null).'); + } + } + mergePaths.push(curPath); + }); + validateFirebaseMergePaths(errorPrefix, mergePaths); +}; +const validatePriority = function (fnName, priority, optional) { + if (optional && priority === undefined) { + return; + } + if (isInvalidJSONNumber(priority)) { + throw new Error(util.errorPrefix(fnName, 'priority') + + 'is ' + + priority.toString() + + ', but must be a valid Firebase priority (a string, finite number, ' + + 'server value, or null).'); + } + // Special case to allow importing data with a .sv. + if (!isValidPriority(priority)) { + throw new Error(util.errorPrefix(fnName, 'priority') + + 'must be a valid Firebase priority ' + + '(a string, finite number, server value, or null).'); + } +}; +const validateKey = function (fnName, argumentName, key, optional) { + if (optional && key === undefined) { + return; + } + if (!isValidKey(key)) { + throw new Error(util.errorPrefix(fnName, argumentName) + + 'was an invalid key = "' + + key + + '". Firebase keys must be non-empty strings and ' + + 'can\'t contain ".", "#", "$", "/", "[", or "]").'); + } +}; +/** + * @internal + */ +const validatePathString = function (fnName, argumentName, pathString, optional) { + if (optional && pathString === undefined) { + return; + } + if (!isValidPathString(pathString)) { + throw new Error(util.errorPrefix(fnName, argumentName) + + 'was an invalid path = "' + + pathString + + '". Paths must be non-empty strings and ' + + 'can\'t contain ".", "#", "$", "[", or "]"'); + } +}; +const validateRootPathString = function (fnName, argumentName, pathString, optional) { + if (pathString) { + // Allow '/.info/' at the beginning. + pathString = pathString.replace(/^\/*\.info(\/|$)/, '/'); + } + validatePathString(fnName, argumentName, pathString, optional); +}; +/** + * @internal + */ +const validateWritablePath = function (fnName, path) { + if (pathGetFront(path) === '.info') { + throw new Error(fnName + " failed = Can't modify data under /.info/"); + } +}; +const validateUrl = function (fnName, parsedUrl) { + // TODO = Validate server better. + const pathString = parsedUrl.path.toString(); + if (!(typeof parsedUrl.repoInfo.host === 'string') || + parsedUrl.repoInfo.host.length === 0 || + (!isValidKey(parsedUrl.repoInfo.namespace) && + parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') || + (pathString.length !== 0 && !isValidRootPathString(pathString))) { + throw new Error(util.errorPrefix(fnName, 'url') + + 'must be a valid firebase URL and ' + + 'the path can\'t contain ".", "#", "$", "[", or "]".'); + } +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The event queue serves a few purposes: + * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more + * events being queued. + * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events, + * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call + * left off, ensuring that the events are still raised synchronously and in order. + * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued + * events are raised synchronously. + * + * NOTE: This can all go away if/when we move to async events. + * + */ +class EventQueue { + constructor() { + this.eventLists_ = []; + /** + * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes. + */ + this.recursionDepth_ = 0; + } +} +/** + * @param eventDataList - The new events to queue. + */ +function eventQueueQueueEvents(eventQueue, eventDataList) { + // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly. + let currList = null; + for (let i = 0; i < eventDataList.length; i++) { + const data = eventDataList[i]; + const path = data.getPath(); + if (currList !== null && !pathEquals(path, currList.path)) { + eventQueue.eventLists_.push(currList); + currList = null; + } + if (currList === null) { + currList = { events: [], path }; + } + currList.events.push(data); + } + if (currList) { + eventQueue.eventLists_.push(currList); + } +} +/** + * Queues the specified events and synchronously raises all events (including previously queued ones) + * for the specified path. + * + * It is assumed that the new events are all for the specified path. + * + * @param path - The path to raise events for. + * @param eventDataList - The new events to raise. + */ +function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) { + eventQueueQueueEvents(eventQueue, eventDataList); + eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path)); +} +/** + * Queues the specified events and synchronously raises all events (including previously queued ones) for + * locations related to the specified change path (i.e. all ancestors and descendants). + * + * It is assumed that the new events are all related (ancestor or descendant) to the specified path. + * + * @param changedPath - The path to raise events for. + * @param eventDataList - The events to raise + */ +function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) { + eventQueueQueueEvents(eventQueue, eventDataList); + eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) || + pathContains(changedPath, eventPath)); +} +function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) { + eventQueue.recursionDepth_++; + let sentAll = true; + for (let i = 0; i < eventQueue.eventLists_.length; i++) { + const eventList = eventQueue.eventLists_[i]; + if (eventList) { + const eventPath = eventList.path; + if (predicate(eventPath)) { + eventListRaise(eventQueue.eventLists_[i]); + eventQueue.eventLists_[i] = null; + } + else { + sentAll = false; + } + } + } + if (sentAll) { + eventQueue.eventLists_ = []; + } + eventQueue.recursionDepth_--; +} +/** + * Iterates through the list and raises each event + */ +function eventListRaise(eventList) { + for (let i = 0; i < eventList.events.length; i++) { + const eventData = eventList.events[i]; + if (eventData !== null) { + eventList.events[i] = null; + const eventFn = eventData.getEventRunner(); + if (logger) { + log('event: ' + eventData.toString()); + } + exceptionGuard(eventFn); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const INTERRUPT_REASON = 'repo_interrupt'; +/** + * If a transaction does not succeed after 25 retries, we abort it. Among other + * things this ensure that if there's ever a bug causing a mismatch between + * client / server hashes for some data, we won't retry indefinitely. + */ +const MAX_TRANSACTION_RETRIES = 25; +/** + * A connection to a single data repository. + */ +class Repo { + constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) { + this.repoInfo_ = repoInfo_; + this.forceRestClient_ = forceRestClient_; + this.authTokenProvider_ = authTokenProvider_; + this.appCheckProvider_ = appCheckProvider_; + this.dataUpdateCount = 0; + this.statsListener_ = null; + this.eventQueue_ = new EventQueue(); + this.nextWriteId_ = 1; + this.interceptServerDataCallback_ = null; + /** A list of data pieces and paths to be set when this client disconnects. */ + this.onDisconnect_ = newSparseSnapshotTree(); + /** Stores queues of outstanding transactions for Firebase locations. */ + this.transactionQueueTree_ = new Tree(); + // TODO: This should be @private but it's used by test_access.js and internal.js + this.persistentConnection_ = null; + // This key is intentionally not updated if RepoInfo is later changed or replaced + this.key = this.repoInfo_.toURLString(); + } + /** + * @returns The URL corresponding to the root of this Firebase. + */ + toString() { + return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host); + } +} +function repoStart(repo, appId, authOverride) { + repo.stats_ = statsManagerGetCollection(repo.repoInfo_); + if (repo.forceRestClient_ || beingCrawled()) { + repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => { + repoOnDataUpdate(repo, pathString, data, isMerge, tag); + }, repo.authTokenProvider_, repo.appCheckProvider_); + // Minor hack: Fire onConnect immediately, since there's no actual connection. + setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0); + } + else { + // Validate authOverride + if (typeof authOverride !== 'undefined' && authOverride !== null) { + if (typeof authOverride !== 'object') { + throw new Error('Only objects are supported for option databaseAuthVariableOverride'); + } + try { + util.stringify(authOverride); + } + catch (e) { + throw new Error('Invalid authOverride provided: ' + e); + } + } + repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => { + repoOnDataUpdate(repo, pathString, data, isMerge, tag); + }, (connectStatus) => { + repoOnConnectStatus(repo, connectStatus); + }, (updates) => { + repoOnServerInfoUpdate(repo, updates); + }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride); + repo.server_ = repo.persistentConnection_; + } + repo.authTokenProvider_.addTokenChangeListener(token => { + repo.server_.refreshAuthToken(token); + }); + repo.appCheckProvider_.addTokenChangeListener(result => { + repo.server_.refreshAppCheckToken(result.token); + }); + // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used), + // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created. + repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_)); + // Used for .info. + repo.infoData_ = new SnapshotHolder(); + repo.infoSyncTree_ = new SyncTree({ + startListening: (query, tag, currentHashFn, onComplete) => { + let infoEvents = []; + const node = repo.infoData_.getNode(query._path); + // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events + // on initial data... + if (!node.isEmpty()) { + infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node); + setTimeout(() => { + onComplete('ok'); + }, 0); + } + return infoEvents; + }, + stopListening: () => { } + }); + repoUpdateInfo(repo, 'connected', false); + repo.serverSyncTree_ = new SyncTree({ + startListening: (query, tag, currentHashFn, onComplete) => { + repo.server_.listen(query, currentHashFn, tag, (status, data) => { + const events = onComplete(status, data); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events); + }); + // No synchronous events for network-backed sync trees + return []; + }, + stopListening: (query, tag) => { + repo.server_.unlisten(query, tag); + } + }); +} +/** + * @returns The time in milliseconds, taking the server offset into account if we have one. + */ +function repoServerTime(repo) { + const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset')); + const offset = offsetNode.val() || 0; + return new Date().getTime() + offset; +} +/** + * Generate ServerValues using some variables from the repo object. + */ +function repoGenerateServerValues(repo) { + return generateWithValues({ + timestamp: repoServerTime(repo) + }); +} +/** + * Called by realtime when we get new messages from the server. + */ +function repoOnDataUpdate(repo, pathString, data, isMerge, tag) { + // For testing. + repo.dataUpdateCount++; + const path = new Path(pathString); + data = repo.interceptServerDataCallback_ + ? repo.interceptServerDataCallback_(pathString, data) + : data; + let events = []; + if (tag) { + if (isMerge) { + const taggedChildren = util.map(data, (raw) => nodeFromJSON(raw)); + events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag); + } + else { + const taggedSnap = nodeFromJSON(data); + events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag); + } + } + else if (isMerge) { + const changedChildren = util.map(data, (raw) => nodeFromJSON(raw)); + events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren); + } + else { + const snap = nodeFromJSON(data); + events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap); + } + let affectedPath = path; + if (events.length > 0) { + // Since we have a listener outstanding for each transaction, receiving any events + // is a proxy for some change having occurred. + affectedPath = repoRerunTransactions(repo, path); + } + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events); +} +function repoOnConnectStatus(repo, connectStatus) { + repoUpdateInfo(repo, 'connected', connectStatus); + if (connectStatus === false) { + repoRunOnDisconnectEvents(repo); + } +} +function repoOnServerInfoUpdate(repo, updates) { + each(updates, (key, value) => { + repoUpdateInfo(repo, key, value); + }); +} +function repoUpdateInfo(repo, pathString, value) { + const path = new Path('/.info/' + pathString); + const newNode = nodeFromJSON(value); + repo.infoData_.updateSnapshot(path, newNode); + const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); +} +function repoGetNextWriteId(repo) { + return repo.nextWriteId_++; +} +/** + * The purpose of `getValue` is to return the latest known value + * satisfying `query`. + * + * This method will first check for in-memory cached values + * belonging to active listeners. If they are found, such values + * are considered to be the most up-to-date. + * + * If the client is not connected, this method will wait until the + * repo has established a connection and then request the value for `query`. + * If the client is not able to retrieve the query result for another reason, + * it reports an error. + * + * @param query - The query to surface a value for. + */ +function repoGetValue(repo, query, eventRegistration) { + // Only active queries are cached. There is no persisted cache. + const cached = syncTreeGetServerValue(repo.serverSyncTree_, query); + if (cached != null) { + return Promise.resolve(cached); + } + return repo.server_.get(query).then(payload => { + const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex()); + /** + * Below we simulate the actions of an `onlyOnce` `onValue()` event where: + * Add an event registration, + * Update data at the path, + * Raise any events, + * Cleanup the SyncTree + */ + syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true); + let events; + if (query._queryParams.loadsAllData()) { + events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node); + } + else { + const tag = syncTreeTagForQuery(repo.serverSyncTree_, query); + events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag); + } + /* + * We need to raise events in the scenario where `get()` is called at a parent path, and + * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting + * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree + * and its corresponding serverCache, including the child location where `onValue` is called. Then, + * `onValue` will receive the event from the server, but look at the syncTree and see that the data received + * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired. + * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and + * ensure the corresponding child events will get fired. + */ + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events); + syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true); + return node; + }, err => { + repoLog(repo, 'get for query ' + util.stringify(query) + ' failed: ' + err); + return Promise.reject(new Error(err)); + }); +} +function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) { + repoLog(repo, 'set', { + path: path.toString(), + value: newVal, + priority: newPriority + }); + // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or + // (b) store unresolved paths on JSON parse + const serverValues = repoGenerateServerValues(repo); + const newNodeUnresolved = nodeFromJSON(newVal, newPriority); + const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path); + const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues); + const writeId = repoGetNextWriteId(repo); + const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true); + eventQueueQueueEvents(repo.eventQueue_, events); + repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => { + const success = status === 'ok'; + if (!success) { + warn('set at ' + path + ' failed: ' + status); + } + const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents); + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); + const affectedPath = repoAbortTransactions(repo, path); + repoRerunTransactions(repo, affectedPath); + // We queued the events above, so just flush the queue here + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []); +} +function repoUpdate(repo, path, childrenToMerge, onComplete) { + repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge }); + // Start with our existing data and merge each child into it. + let empty = true; + const serverValues = repoGenerateServerValues(repo); + const changedChildren = {}; + each(childrenToMerge, (changedKey, changedValue) => { + empty = false; + changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues); + }); + if (!empty) { + const writeId = repoGetNextWriteId(repo); + const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId); + eventQueueQueueEvents(repo.eventQueue_, events); + repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => { + const success = status === 'ok'; + if (!success) { + warn('update at ' + path + ' failed: ' + status); + } + const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success); + const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path; + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents); + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); + each(childrenToMerge, (changedPath) => { + const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath)); + repoRerunTransactions(repo, affectedPath); + }); + // We queued the events above, so just flush the queue here + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []); + } + else { + log("update() called with empty data. Don't do anything."); + repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined); + } +} +/** + * Applies all of the changes stored up in the onDisconnect_ tree. + */ +function repoRunOnDisconnectEvents(repo) { + repoLog(repo, 'onDisconnectEvents'); + const serverValues = repoGenerateServerValues(repo); + const resolvedOnDisconnectTree = newSparseSnapshotTree(); + sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => { + const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues); + sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved); + }); + let events = []; + sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => { + events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap)); + const affectedPath = repoAbortTransactions(repo, path); + repoRerunTransactions(repo, affectedPath); + }); + repo.onDisconnect_ = newSparseSnapshotTree(); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events); +} +function repoOnDisconnectCancel(repo, path, onComplete) { + repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => { + if (status === 'ok') { + sparseSnapshotTreeForget(repo.onDisconnect_, path); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoOnDisconnectSet(repo, path, value, onComplete) { + const newNode = nodeFromJSON(value); + repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => { + if (status === 'ok') { + sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) { + const newNode = nodeFromJSON(value, priority); + repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => { + if (status === 'ok') { + sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) { + if (util.isEmpty(childrenToMerge)) { + log("onDisconnect().update() called with empty data. Don't do anything."); + repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined); + return; + } + repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => { + if (status === 'ok') { + each(childrenToMerge, (childName, childNode) => { + const newChildNode = nodeFromJSON(childNode); + sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode); + }); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoAddEventCallbackForQuery(repo, query, eventRegistration) { + let events; + if (pathGetFront(query._path) === '.info') { + events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration); + } + else { + events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration); + } + eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events); +} +function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) { + // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof + // a little bit by handling the return values anyways. + let events; + if (pathGetFront(query._path) === '.info') { + events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration); + } + else { + events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration); + } + eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events); +} +function repoInterrupt(repo) { + if (repo.persistentConnection_) { + repo.persistentConnection_.interrupt(INTERRUPT_REASON); + } +} +function repoResume(repo) { + if (repo.persistentConnection_) { + repo.persistentConnection_.resume(INTERRUPT_REASON); + } +} +function repoLog(repo, ...varArgs) { + let prefix = ''; + if (repo.persistentConnection_) { + prefix = repo.persistentConnection_.id + ':'; + } + log(prefix, ...varArgs); +} +function repoCallOnCompleteCallback(repo, callback, status, errorReason) { + if (callback) { + exceptionGuard(() => { + if (status === 'ok') { + callback(null); + } + else { + const code = (status || 'error').toUpperCase(); + let message = code; + if (errorReason) { + message += ': ' + errorReason; + } + const error = new Error(message); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error.code = code; + callback(error); + } + }); + } +} +/** + * Creates a new transaction, adds it to the transactions we're tracking, and + * sends it to the server if possible. + * + * @param path - Path at which to do transaction. + * @param transactionUpdate - Update callback. + * @param onComplete - Completion callback. + * @param unwatcher - Function that will be called when the transaction no longer + * need data updates for `path`. + * @param applyLocally - Whether or not to make intermediate results visible + */ +function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) { + repoLog(repo, 'transaction on ' + path); + // Initialize transaction. + const transaction = { + path, + update: transactionUpdate, + onComplete, + // One of TransactionStatus enums. + status: null, + // Used when combining transactions at different locations to figure out + // which one goes first. + order: LUIDGenerator(), + // Whether to raise local events for this transaction. + applyLocally, + // Count of how many times we've retried the transaction. + retryCount: 0, + // Function to call to clean up our .on() listener. + unwatcher, + // Stores why a transaction was aborted. + abortReason: null, + currentWriteId: null, + currentInputSnapshot: null, + currentOutputSnapshotRaw: null, + currentOutputSnapshotResolved: null + }; + // Run transaction initially. + const currentState = repoGetLatestState(repo, path, undefined); + transaction.currentInputSnapshot = currentState; + const newVal = transaction.update(currentState.val()); + if (newVal === undefined) { + // Abort transaction. + transaction.unwatcher(); + transaction.currentOutputSnapshotRaw = null; + transaction.currentOutputSnapshotResolved = null; + if (transaction.onComplete) { + transaction.onComplete(null, false, transaction.currentInputSnapshot); + } + } + else { + validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path); + // Mark as run and add to our queue. + transaction.status = 0 /* TransactionStatus.RUN */; + const queueNode = treeSubTree(repo.transactionQueueTree_, path); + const nodeQueue = treeGetValue(queueNode) || []; + nodeQueue.push(transaction); + treeSetValue(queueNode, nodeQueue); + // Update visibleData and raise events + // Note: We intentionally raise events after updating all of our + // transaction state, since the user could start new transactions from the + // event callbacks. + let priorityForNode; + if (typeof newVal === 'object' && + newVal !== null && + util.contains(newVal, '.priority')) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + priorityForNode = util.safeGet(newVal, '.priority'); + util.assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' + + 'Priority must be a valid string, finite number, server value, or null.'); + } + else { + const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) || + ChildrenNode.EMPTY_NODE; + priorityForNode = currentNode.getPriority().val(); + } + const serverValues = repoGenerateServerValues(repo); + const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode); + const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues); + transaction.currentOutputSnapshotRaw = newNodeUnresolved; + transaction.currentOutputSnapshotResolved = newNode; + transaction.currentWriteId = repoGetNextWriteId(repo); + const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); + repoSendReadyTransactions(repo, repo.transactionQueueTree_); + } +} +/** + * @param excludeSets - A specific set to exclude + */ +function repoGetLatestState(repo, path, excludeSets) { + return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) || + ChildrenNode.EMPTY_NODE); +} +/** + * Sends any already-run transactions that aren't waiting for outstanding + * transactions to complete. + * + * Externally it's called with no arguments, but it calls itself recursively + * with a particular transactionQueueTree node to recurse through the tree. + * + * @param node - transactionQueueTree node to start at. + */ +function repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) { + // Before recursing, make sure any completed transactions are removed. + if (!node) { + repoPruneCompletedTransactionsBelowNode(repo, node); + } + if (treeGetValue(node)) { + const queue = repoBuildTransactionQueue(repo, node); + util.assert(queue.length > 0, 'Sending zero length transaction queue'); + const allRun = queue.every((transaction) => transaction.status === 0 /* TransactionStatus.RUN */); + // If they're all run (and not sent), we can send them. Else, we must wait. + if (allRun) { + repoSendTransactionQueue(repo, treeGetPath(node), queue); + } + } + else if (treeHasChildren(node)) { + treeForEachChild(node, childNode => { + repoSendReadyTransactions(repo, childNode); + }); + } +} +/** + * Given a list of run transactions, send them to the server and then handle + * the result (success or failure). + * + * @param path - The location of the queue. + * @param queue - Queue of transactions under the specified location. + */ +function repoSendTransactionQueue(repo, path, queue) { + // Mark transactions as sent and increment retry count! + const setsToIgnore = queue.map(txn => { + return txn.currentWriteId; + }); + const latestState = repoGetLatestState(repo, path, setsToIgnore); + let snapToSend = latestState; + const latestHash = latestState.hash(); + for (let i = 0; i < queue.length; i++) { + const txn = queue[i]; + util.assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.'); + txn.status = 1 /* TransactionStatus.SENT */; + txn.retryCount++; + const relativePath = newRelativePath(path, txn.path); + // If we've gotten to this point, the output snapshot must be defined. + snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw); + } + const dataToSend = snapToSend.val(true); + const pathToSend = path; + // Send the put. + repo.server_.put(pathToSend.toString(), dataToSend, (status) => { + repoLog(repo, 'transaction put response', { + path: pathToSend.toString(), + status + }); + let events = []; + if (status === 'ok') { + // Queue up the callbacks and fire them after cleaning up all of our + // transaction state, since the callback could trigger more + // transactions or sets. + const callbacks = []; + for (let i = 0; i < queue.length; i++) { + queue[i].status = 2 /* TransactionStatus.COMPLETED */; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId)); + if (queue[i].onComplete) { + // We never unset the output snapshot, and given that this + // transaction is complete, it should be set + callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved)); + } + queue[i].unwatcher(); + } + // Now remove the completed transactions. + repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path)); + // There may be pending transactions that we can now send. + repoSendReadyTransactions(repo, repo.transactionQueueTree_); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); + // Finally, trigger onComplete callbacks. + for (let i = 0; i < callbacks.length; i++) { + exceptionGuard(callbacks[i]); + } + } + else { + // transactions are no longer sent. Update their status appropriately. + if (status === 'datastale') { + for (let i = 0; i < queue.length; i++) { + if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) { + queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */; + } + else { + queue[i].status = 0 /* TransactionStatus.RUN */; + } + } + } + else { + warn('transaction at ' + pathToSend.toString() + ' failed: ' + status); + for (let i = 0; i < queue.length; i++) { + queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */; + queue[i].abortReason = status; + } + } + repoRerunTransactions(repo, path); + } + }, latestHash); +} +/** + * Finds all transactions dependent on the data at changedPath and reruns them. + * + * Should be called any time cached data changes. + * + * Return the highest path that was affected by rerunning transactions. This + * is the path at which events need to be raised for. + * + * @param changedPath - The path in mergedData that changed. + * @returns The rootmost path that was affected by rerunning transactions. + */ +function repoRerunTransactions(repo, changedPath) { + const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath); + const path = treeGetPath(rootMostTransactionNode); + const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode); + repoRerunTransactionQueue(repo, queue, path); + return path; +} +/** + * Does all the work of rerunning transactions (as well as cleans up aborted + * transactions and whatnot). + * + * @param queue - The queue of transactions to run. + * @param path - The path the queue is for. + */ +function repoRerunTransactionQueue(repo, queue, path) { + if (queue.length === 0) { + return; // Nothing to do! + } + // Queue up the callbacks and fire them after cleaning up all of our + // transaction state, since the callback could trigger more transactions or + // sets. + const callbacks = []; + let events = []; + // Ignore all of the sets we're going to re-run. + const txnsToRerun = queue.filter(q => { + return q.status === 0 /* TransactionStatus.RUN */; + }); + const setsToIgnore = txnsToRerun.map(q => { + return q.currentWriteId; + }); + for (let i = 0; i < queue.length; i++) { + const transaction = queue[i]; + const relativePath = newRelativePath(path, transaction.path); + let abortTransaction = false, abortReason; + util.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.'); + if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) { + abortTransaction = true; + abortReason = transaction.abortReason; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true)); + } + else if (transaction.status === 0 /* TransactionStatus.RUN */) { + if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) { + abortTransaction = true; + abortReason = 'maxretry'; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true)); + } + else { + // This code reruns a transaction + const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore); + transaction.currentInputSnapshot = currentNode; + const newData = queue[i].update(currentNode.val()); + if (newData !== undefined) { + validateFirebaseData('transaction failed: Data returned ', newData, transaction.path); + let newDataNode = nodeFromJSON(newData); + const hasExplicitPriority = typeof newData === 'object' && + newData != null && + util.contains(newData, '.priority'); + if (!hasExplicitPriority) { + // Keep the old priority if there wasn't a priority explicitly specified. + newDataNode = newDataNode.updatePriority(currentNode.getPriority()); + } + const oldWriteId = transaction.currentWriteId; + const serverValues = repoGenerateServerValues(repo); + const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues); + transaction.currentOutputSnapshotRaw = newDataNode; + transaction.currentOutputSnapshotResolved = newNodeResolved; + transaction.currentWriteId = repoGetNextWriteId(repo); + // Mutates setsToIgnore in place + setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1); + events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally)); + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true)); + } + else { + abortTransaction = true; + abortReason = 'nodata'; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true)); + } + } + } + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); + events = []; + if (abortTransaction) { + // Abort. + queue[i].status = 2 /* TransactionStatus.COMPLETED */; + // Removing a listener can trigger pruning which can muck with + // mergedData/visibleData (as it prunes data). So defer the unwatcher + // until we're done. + (function (unwatcher) { + setTimeout(unwatcher, Math.floor(0)); + })(queue[i].unwatcher); + if (queue[i].onComplete) { + if (abortReason === 'nodata') { + callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot)); + } + else { + callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null)); + } + } + } + } + // Clean up completed transactions. + repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_); + // Now fire callbacks, now that we're in a good, known state. + for (let i = 0; i < callbacks.length; i++) { + exceptionGuard(callbacks[i]); + } + // Try to send the transaction result to the server. + repoSendReadyTransactions(repo, repo.transactionQueueTree_); +} +/** + * Returns the rootmost ancestor node of the specified path that has a pending + * transaction on it, or just returns the node for the given path if there are + * no pending transactions on any ancestor. + * + * @param path - The location to start at. + * @returns The rootmost node with a transaction. + */ +function repoGetAncestorTransactionNode(repo, path) { + let front; + // Start at the root and walk deeper into the tree towards path until we + // find a node with pending transactions. + let transactionNode = repo.transactionQueueTree_; + front = pathGetFront(path); + while (front !== null && treeGetValue(transactionNode) === undefined) { + transactionNode = treeSubTree(transactionNode, front); + path = pathPopFront(path); + front = pathGetFront(path); + } + return transactionNode; +} +/** + * Builds the queue of all transactions at or below the specified + * transactionNode. + * + * @param transactionNode + * @returns The generated queue. + */ +function repoBuildTransactionQueue(repo, transactionNode) { + // Walk any child transaction queues and aggregate them into a single queue. + const transactionQueue = []; + repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue); + // Sort them by the order the transactions were created. + transactionQueue.sort((a, b) => a.order - b.order); + return transactionQueue; +} +function repoAggregateTransactionQueuesForNode(repo, node, queue) { + const nodeQueue = treeGetValue(node); + if (nodeQueue) { + for (let i = 0; i < nodeQueue.length; i++) { + queue.push(nodeQueue[i]); + } + } + treeForEachChild(node, child => { + repoAggregateTransactionQueuesForNode(repo, child, queue); + }); +} +/** + * Remove COMPLETED transactions at or below this node in the transactionQueueTree_. + */ +function repoPruneCompletedTransactionsBelowNode(repo, node) { + const queue = treeGetValue(node); + if (queue) { + let to = 0; + for (let from = 0; from < queue.length; from++) { + if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) { + queue[to] = queue[from]; + to++; + } + } + queue.length = to; + treeSetValue(node, queue.length > 0 ? queue : undefined); + } + treeForEachChild(node, childNode => { + repoPruneCompletedTransactionsBelowNode(repo, childNode); + }); +} +/** + * Aborts all transactions on ancestors or descendants of the specified path. + * Called when doing a set() or update() since we consider them incompatible + * with transactions. + * + * @param path - Path for which we want to abort related transactions. + */ +function repoAbortTransactions(repo, path) { + const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path)); + const transactionNode = treeSubTree(repo.transactionQueueTree_, path); + treeForEachAncestor(transactionNode, (node) => { + repoAbortTransactionsOnNode(repo, node); + }); + repoAbortTransactionsOnNode(repo, transactionNode); + treeForEachDescendant(transactionNode, (node) => { + repoAbortTransactionsOnNode(repo, node); + }); + return affectedPath; +} +/** + * Abort transactions stored in this transaction queue node. + * + * @param node - Node to abort transactions for. + */ +function repoAbortTransactionsOnNode(repo, node) { + const queue = treeGetValue(node); + if (queue) { + // Queue up the callbacks and fire them after cleaning up all of our + // transaction state, since the callback could trigger more transactions + // or sets. + const callbacks = []; + // Go through queue. Any already-sent transactions must be marked for + // abort, while the unsent ones can be immediately aborted and removed. + let events = []; + let lastSent = -1; + for (let i = 0; i < queue.length; i++) { + if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ; + else if (queue[i].status === 1 /* TransactionStatus.SENT */) { + util.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.'); + lastSent = i; + // Mark transaction for abort when it comes back. + queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */; + queue[i].abortReason = 'set'; + } + else { + util.assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort'); + // We can abort it immediately. + queue[i].unwatcher(); + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true)); + if (queue[i].onComplete) { + callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null)); + } + } + } + if (lastSent === -1) { + // We're not waiting for any sent transactions. We can clear the queue. + treeSetValue(node, undefined); + } + else { + // Remove the transactions we aborted. + queue.length = lastSent + 1; + } + // Now fire the callbacks. + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events); + for (let i = 0; i < callbacks.length; i++) { + exceptionGuard(callbacks[i]); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function decodePath(pathString) { + let pathStringDecoded = ''; + const pieces = pathString.split('/'); + for (let i = 0; i < pieces.length; i++) { + if (pieces[i].length > 0) { + let piece = pieces[i]; + try { + piece = decodeURIComponent(piece.replace(/\+/g, ' ')); + } + catch (e) { } + pathStringDecoded += '/' + piece; + } + } + return pathStringDecoded; +} +/** + * @returns key value hash + */ +function decodeQuery(queryString) { + const results = {}; + if (queryString.charAt(0) === '?') { + queryString = queryString.substring(1); + } + for (const segment of queryString.split('&')) { + if (segment.length === 0) { + continue; + } + const kv = segment.split('='); + if (kv.length === 2) { + results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]); + } + else { + warn(`Invalid query segment '${segment}' in query '${queryString}'`); + } + } + return results; +} +const parseRepoInfo = function (dataURL, nodeAdmin) { + const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace; + if (parsedUrl.domain === 'firebase.com') { + fatal(parsedUrl.host + + ' is no longer supported. ' + + 'Please use .firebaseio.com instead'); + } + // Catch common error of uninitialized namespace value. + if ((!namespace || namespace === 'undefined') && + parsedUrl.domain !== 'localhost') { + fatal('Cannot parse Firebase url. Please use https://.firebaseio.com'); + } + if (!parsedUrl.secure) { + warnIfPageIsSecure(); + } + const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss'; + return { + repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin, + /*persistenceKey=*/ '', + /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain), + path: new Path(parsedUrl.pathString) + }; +}; +const parseDatabaseURL = function (dataURL) { + // Default to empty strings in the event of a malformed string. + let host = '', domain = '', subdomain = '', pathString = '', namespace = ''; + // Always default to SSL, unless otherwise specified. + let secure = true, scheme = 'https', port = 443; + // Don't do any validation here. The caller is responsible for validating the result of parsing. + if (typeof dataURL === 'string') { + // Parse scheme. + let colonInd = dataURL.indexOf('//'); + if (colonInd >= 0) { + scheme = dataURL.substring(0, colonInd - 1); + dataURL = dataURL.substring(colonInd + 2); + } + // Parse host, path, and query string. + let slashInd = dataURL.indexOf('/'); + if (slashInd === -1) { + slashInd = dataURL.length; + } + let questionMarkInd = dataURL.indexOf('?'); + if (questionMarkInd === -1) { + questionMarkInd = dataURL.length; + } + host = dataURL.substring(0, Math.min(slashInd, questionMarkInd)); + if (slashInd < questionMarkInd) { + // For pathString, questionMarkInd will always come after slashInd + pathString = decodePath(dataURL.substring(slashInd, questionMarkInd)); + } + const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd))); + // If we have a port, use scheme for determining if it's secure. + colonInd = host.indexOf(':'); + if (colonInd >= 0) { + secure = scheme === 'https' || scheme === 'wss'; + port = parseInt(host.substring(colonInd + 1), 10); + } + else { + colonInd = host.length; + } + const hostWithoutPort = host.slice(0, colonInd); + if (hostWithoutPort.toLowerCase() === 'localhost') { + domain = 'localhost'; + } + else if (hostWithoutPort.split('.').length <= 2) { + domain = hostWithoutPort; + } + else { + // Interpret the subdomain of a 3 or more component URL as the namespace name. + const dotInd = host.indexOf('.'); + subdomain = host.substring(0, dotInd).toLowerCase(); + domain = host.substring(dotInd + 1); + // Normalize namespaces to lowercase to share storage / connection. + namespace = subdomain; + } + // Always treat the value of the `ns` as the namespace name if it is present. + if ('ns' in queryParams) { + namespace = queryParams['ns']; + } + } + return { + host, + port, + domain, + subdomain, + secure, + scheme, + pathString, + namespace + }; +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Modeled after base64 web-safe chars, but ordered by ASCII. +const PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'; +/** + * Fancy ID generator that creates 20-character string identifiers with the + * following properties: + * + * 1. They're based on timestamp so that they sort *after* any existing ids. + * 2. They contain 72-bits of random data after the timestamp so that IDs won't + * collide with other clients' IDs. + * 3. They sort *lexicographically* (so the timestamp is converted to characters + * that will sort properly). + * 4. They're monotonically increasing. Even if you generate more than one in + * the same timestamp, the latter ones will sort after the former ones. We do + * this by using the previous random bits but "incrementing" them by 1 (only + * in the case of a timestamp collision). + */ +const nextPushId = (function () { + // Timestamp of last push, used to prevent local collisions if you push twice + // in one ms. + let lastPushTime = 0; + // We generate 72-bits of randomness which get turned into 12 characters and + // appended to the timestamp to prevent collisions with other clients. We + // store the last characters we generated because in the event of a collision, + // we'll use those same characters except "incremented" by one. + const lastRandChars = []; + return function (now) { + const duplicateTime = now === lastPushTime; + lastPushTime = now; + let i; + const timeStampChars = new Array(8); + for (i = 7; i >= 0; i--) { + timeStampChars[i] = PUSH_CHARS.charAt(now % 64); + // NOTE: Can't use << here because javascript will convert to int and lose + // the upper bits. + now = Math.floor(now / 64); + } + util.assert(now === 0, 'Cannot push at time == 0'); + let id = timeStampChars.join(''); + if (!duplicateTime) { + for (i = 0; i < 12; i++) { + lastRandChars[i] = Math.floor(Math.random() * 64); + } + } + else { + // If the timestamp hasn't changed since last push, use the same random + // number, except incremented by 1. + for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) { + lastRandChars[i] = 0; + } + lastRandChars[i]++; + } + for (i = 0; i < 12; i++) { + id += PUSH_CHARS.charAt(lastRandChars[i]); + } + util.assert(id.length === 20, 'nextPushId: Length should be 20.'); + return id; + }; +})(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Encapsulates the data needed to raise an event + */ +class DataEvent { + /** + * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed + * @param eventRegistration - The function to call to with the event data. User provided + * @param snapshot - The data backing the event + * @param prevName - Optional, the name of the previous child for child_* events. + */ + constructor(eventType, eventRegistration, snapshot, prevName) { + this.eventType = eventType; + this.eventRegistration = eventRegistration; + this.snapshot = snapshot; + this.prevName = prevName; + } + getPath() { + const ref = this.snapshot.ref; + if (this.eventType === 'value') { + return ref._path; + } + else { + return ref.parent._path; + } + } + getEventType() { + return this.eventType; + } + getEventRunner() { + return this.eventRegistration.getEventRunner(this); + } + toString() { + return (this.getPath().toString() + + ':' + + this.eventType + + ':' + + util.stringify(this.snapshot.exportVal())); + } +} +class CancelEvent { + constructor(eventRegistration, error, path) { + this.eventRegistration = eventRegistration; + this.error = error; + this.path = path; + } + getPath() { + return this.path; + } + getEventType() { + return 'cancel'; + } + getEventRunner() { + return this.eventRegistration.getEventRunner(this); + } + toString() { + return this.path.toString() + ':cancel'; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A wrapper class that converts events from the database@exp SDK to the legacy + * Database SDK. Events are not converted directly as event registration relies + * on reference comparison of the original user callback (see `matches()`) and + * relies on equality of the legacy SDK's `context` object. + */ +class CallbackContext { + constructor(snapshotCallback, cancelCallback) { + this.snapshotCallback = snapshotCallback; + this.cancelCallback = cancelCallback; + } + onValue(expDataSnapshot, previousChildName) { + this.snapshotCallback.call(null, expDataSnapshot, previousChildName); + } + onCancel(error) { + util.assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback'); + return this.cancelCallback.call(null, error); + } + get hasCancelCallback() { + return !!this.cancelCallback; + } + matches(other) { + return (this.snapshotCallback === other.snapshotCallback || + (this.snapshotCallback.userCallback !== undefined && + this.snapshotCallback.userCallback === + other.snapshotCallback.userCallback && + this.snapshotCallback.context === other.snapshotCallback.context)); + } +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The `onDisconnect` class allows you to write or clear data when your client + * disconnects from the Database server. These updates occur whether your + * client disconnects cleanly or not, so you can rely on them to clean up data + * even if a connection is dropped or a client crashes. + * + * The `onDisconnect` class is most commonly used to manage presence in + * applications where it is useful to detect how many clients are connected and + * when other clients disconnect. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * To avoid problems when a connection is dropped before the requests can be + * transferred to the Database server, these functions should be called before + * writing any data. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time you reconnect. + */ +class OnDisconnect { + /** @hideconstructor */ + constructor(_repo, _path) { + this._repo = _repo; + this._path = _path; + } + /** + * Cancels all previously queued `onDisconnect()` set or update events for this + * location and all children. + * + * If a write has been queued for this location via a `set()` or `update()` at a + * parent location, the write at this location will be canceled, though writes + * to sibling locations will still occur. + * + * @returns Resolves when synchronization to the server is complete. + */ + cancel() { + const deferred = new util.Deferred(); + repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Ensures the data at this location is deleted when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + * + * @returns Resolves when synchronization to the server is complete. + */ + remove() { + validateWritablePath('OnDisconnect.remove', this._path); + const deferred = new util.Deferred(); + repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Ensures the data at this location is set to the specified value when the + * client is disconnected (due to closing the browser, navigating to a new page, + * or network issues). + * + * `set()` is especially useful for implementing "presence" systems, where a + * value should be changed or cleared when a user disconnects so that they + * appear "offline" to other users. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time. + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + set(value) { + validateWritablePath('OnDisconnect.set', this._path); + validateFirebaseDataArg('OnDisconnect.set', value, this._path, false); + const deferred = new util.Deferred(); + repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Ensures the data at this location is set to the specified value and priority + * when the client is disconnected (due to closing the browser, navigating to a + * new page, or network issues). + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + setWithPriority(value, priority) { + validateWritablePath('OnDisconnect.setWithPriority', this._path); + validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false); + validatePriority('OnDisconnect.setWithPriority', priority, false); + const deferred = new util.Deferred(); + repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Writes multiple values at this location when the client is disconnected (due + * to closing the browser, navigating to a new page, or network issues). + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, "name/first") + * from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * @param values - Object containing multiple values. + * @returns Resolves when synchronization to the Database is complete. + */ + update(values) { + validateWritablePath('OnDisconnect.update', this._path); + validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false); + const deferred = new util.Deferred(); + repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { })); + return deferred.promise; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ +class QueryImpl { + /** + * @hideconstructor + */ + constructor(_repo, _path, _queryParams, _orderByCalled) { + this._repo = _repo; + this._path = _path; + this._queryParams = _queryParams; + this._orderByCalled = _orderByCalled; + } + get key() { + if (pathIsEmpty(this._path)) { + return null; + } + else { + return pathGetBack(this._path); + } + } + get ref() { + return new ReferenceImpl(this._repo, this._path); + } + get _queryIdentifier() { + const obj = queryParamsGetQueryObject(this._queryParams); + const id = ObjectToUniqueKey(obj); + return id === '{}' ? 'default' : id; + } + /** + * An object representation of the query parameters used by this Query. + */ + get _queryObject() { + return queryParamsGetQueryObject(this._queryParams); + } + isEqual(other) { + other = util.getModularInstance(other); + if (!(other instanceof QueryImpl)) { + return false; + } + const sameRepo = this._repo === other._repo; + const samePath = pathEquals(this._path, other._path); + const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier; + return sameRepo && samePath && sameQueryIdentifier; + } + toJSON() { + return this.toString(); + } + toString() { + return this._repo.toString() + pathToUrlEncodedString(this._path); + } +} +/** + * Validates that no other order by call has been made + */ +function validateNoPreviousOrderByCall(query, fnName) { + if (query._orderByCalled === true) { + throw new Error(fnName + ": You can't combine multiple orderBy calls."); + } +} +/** + * Validates start/end values for queries. + */ +function validateQueryEndpoints(params) { + let startNode = null; + let endNode = null; + if (params.hasStart()) { + startNode = params.getIndexStartValue(); + } + if (params.hasEnd()) { + endNode = params.getIndexEndValue(); + } + if (params.getIndex() === KEY_INDEX) { + const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' + + 'startAt(), endAt(), or equalTo().'; + const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' + + 'endAt(), endBefore(), or equalTo() must be a string.'; + if (params.hasStart()) { + const startName = params.getIndexStartName(); + if (startName !== MIN_NAME) { + throw new Error(tooManyArgsError); + } + else if (typeof startNode !== 'string') { + throw new Error(wrongArgTypeError); + } + } + if (params.hasEnd()) { + const endName = params.getIndexEndName(); + if (endName !== MAX_NAME) { + throw new Error(tooManyArgsError); + } + else if (typeof endNode !== 'string') { + throw new Error(wrongArgTypeError); + } + } + } + else if (params.getIndex() === PRIORITY_INDEX) { + if ((startNode != null && !isValidPriority(startNode)) || + (endNode != null && !isValidPriority(endNode))) { + throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' + + 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' + + '(null, a number, or a string).'); + } + } + else { + util.assert(params.getIndex() instanceof PathIndex || + params.getIndex() === VALUE_INDEX, 'unknown index type.'); + if ((startNode != null && typeof startNode === 'object') || + (endNode != null && typeof endNode === 'object')) { + throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' + + 'equalTo() cannot be an object.'); + } + } +} +/** + * Validates that limit* has been called with the correct combination of parameters + */ +function validateLimit(params) { + if (params.hasStart() && + params.hasEnd() && + params.hasLimit() && + !params.hasAnchoredLimit()) { + throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " + + 'limitToFirst() or limitToLast() instead.'); + } +} +/** + * @internal + */ +class ReferenceImpl extends QueryImpl { + /** @hideconstructor */ + constructor(repo, path) { + super(repo, path, new QueryParams(), false); + } + get parent() { + const parentPath = pathParent(this._path); + return parentPath === null + ? null + : new ReferenceImpl(this._repo, parentPath); + } + get root() { + let ref = this; + while (ref.parent !== null) { + ref = ref.parent; + } + return ref; + } +} +/** + * A `DataSnapshot` contains data from a Database location. + * + * Any time you read data from the Database, you receive the data as a + * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach + * with `on()` or `once()`. You can extract the contents of the snapshot as a + * JavaScript object by calling the `val()` method. Alternatively, you can + * traverse into the snapshot by calling `child()` to return child snapshots + * (which you could then call `val()` on). + * + * A `DataSnapshot` is an efficiently generated, immutable copy of the data at + * a Database location. It cannot be modified and will never change (to modify + * data, you always call the `set()` method on a `Reference` directly). + */ +class DataSnapshot { + /** + * @param _node - A SnapshotNode to wrap. + * @param ref - The location this snapshot came from. + * @param _index - The iteration order for this snapshot + * @hideconstructor + */ + constructor(_node, + /** + * The location of this DataSnapshot. + */ + ref, _index) { + this._node = _node; + this.ref = ref; + this._index = _index; + } + /** + * Gets the priority value of the data in this `DataSnapshot`. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data} + * ). + */ + get priority() { + // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY) + return this._node.getPriority().val(); + } + /** + * The key (last part of the path) of the location of this `DataSnapshot`. + * + * The last token in a Database location is considered its key. For example, + * "ada" is the key for the /users/ada/ node. Accessing the key on any + * `DataSnapshot` will return the key for the location that generated it. + * However, accessing the key on the root URL of a Database will return + * `null`. + */ + get key() { + return this.ref.key; + } + /** Returns the number of child properties of this `DataSnapshot`. */ + get size() { + return this._node.numChildren(); + } + /** + * Gets another `DataSnapshot` for the location at the specified relative path. + * + * Passing a relative path to the `child()` method of a DataSnapshot returns + * another `DataSnapshot` for the location at the specified relative path. The + * relative path can either be a simple child name (for example, "ada") or a + * deeper, slash-separated path (for example, "ada/name/first"). If the child + * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot` + * whose value is `null`) is returned. + * + * @param path - A relative path to the location of child data. + */ + child(path) { + const childPath = new Path(path); + const childRef = child(this.ref, path); + return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX); + } + /** + * Returns true if this `DataSnapshot` contains any data. It is slightly more + * efficient than using `snapshot.val() !== null`. + */ + exists() { + return !this._node.isEmpty(); + } + /** + * Exports the entire contents of the DataSnapshot as a JavaScript object. + * + * The `exportVal()` method is similar to `val()`, except priority information + * is included (if available), making it suitable for backing up your data. + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + exportVal() { + return this._node.val(true); + } + /** + * Enumerates the top-level children in the `IteratedDataSnapshot`. + * + * Because of the way JavaScript objects work, the ordering of data in the + * JavaScript object returned by `val()` is not guaranteed to match the + * ordering on the server nor the ordering of `onChildAdded()` events. That is + * where `forEach()` comes in handy. It guarantees the children of a + * `DataSnapshot` will be iterated in their query order. + * + * If no explicit `orderBy*()` method is used, results are returned + * ordered by key (unless priorities are used, in which case, results are + * returned by priority). + * + * @param action - A function that will be called for each child DataSnapshot. + * The callback can return true to cancel further enumeration. + * @returns true if enumeration was canceled due to your callback returning + * true. + */ + forEach(action) { + if (this._node.isLeafNode()) { + return false; + } + const childrenNode = this._node; + // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type... + return !!childrenNode.forEachChild(this._index, (key, node) => { + return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX)); + }); + } + /** + * Returns true if the specified child path has (non-null) data. + * + * @param path - A relative path to the location of a potential child. + * @returns `true` if data exists at the specified child path; else + * `false`. + */ + hasChild(path) { + const childPath = new Path(path); + return !this._node.getChild(childPath).isEmpty(); + } + /** + * Returns whether or not the `DataSnapshot` has any non-`null` child + * properties. + * + * You can use `hasChildren()` to determine if a `DataSnapshot` has any + * children. If it does, you can enumerate them using `forEach()`. If it + * doesn't, then either this snapshot contains a primitive value (which can be + * retrieved with `val()`) or it is empty (in which case, `val()` will return + * `null`). + * + * @returns true if this snapshot has any children; else false. + */ + hasChildren() { + if (this._node.isLeafNode()) { + return false; + } + else { + return !this._node.isEmpty(); + } + } + /** + * Returns a JSON-serializable representation of this object. + */ + toJSON() { + return this.exportVal(); + } + /** + * Extracts a JavaScript value from a `DataSnapshot`. + * + * Depending on the data in a `DataSnapshot`, the `val()` method may return a + * scalar type (string, number, or boolean), an array, or an object. It may + * also return null, indicating that the `DataSnapshot` is empty (contains no + * data). + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + val() { + return this._node.val(); + } +} +/** + * + * Returns a `Reference` representing the location in the Database + * corresponding to the provided path. If no path is provided, the `Reference` + * will point to the root of the Database. + * + * @param db - The database instance to obtain a reference for. + * @param path - Optional path representing the location the returned + * `Reference` will point. If not provided, the returned `Reference` will + * point to the root of the Database. + * @returns If a path is provided, a `Reference` + * pointing to the provided path. Otherwise, a `Reference` pointing to the + * root of the Database. + */ +function ref(db, path) { + db = util.getModularInstance(db); + db._checkNotDeleted('ref'); + return path !== undefined ? child(db._root, path) : db._root; +} +/** + * Returns a `Reference` representing the location in the Database + * corresponding to the provided Firebase URL. + * + * An exception is thrown if the URL is not a valid Firebase Database URL or it + * has a different domain than the current `Database` instance. + * + * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored + * and are not applied to the returned `Reference`. + * + * @param db - The database instance to obtain a reference for. + * @param url - The Firebase URL at which the returned `Reference` will + * point. + * @returns A `Reference` pointing to the provided + * Firebase URL. + */ +function refFromURL(db, url) { + db = util.getModularInstance(db); + db._checkNotDeleted('refFromURL'); + const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin); + validateUrl('refFromURL', parsedURL); + const repoInfo = parsedURL.repoInfo; + if (!db._repo.repoInfo_.isCustomHost() && + repoInfo.host !== db._repo.repoInfo_.host) { + fatal('refFromURL' + + ': Host name does not match the current database: ' + + '(found ' + + repoInfo.host + + ' but expected ' + + db._repo.repoInfo_.host + + ')'); + } + return ref(db, parsedURL.path.toString()); +} +/** + * Gets a `Reference` for the location at the specified relative path. + * + * The relative path can either be a simple child name (for example, "ada") or + * a deeper slash-separated path (for example, "ada/name/first"). + * + * @param parent - The parent location. + * @param path - A relative path from this location to the desired child + * location. + * @returns The specified child location. + */ +function child(parent, path) { + parent = util.getModularInstance(parent); + if (pathGetFront(parent._path) === null) { + validateRootPathString('child', 'path', path, false); + } + else { + validatePathString('child', 'path', path, false); + } + return new ReferenceImpl(parent._repo, pathChild(parent._path, path)); +} +/** + * Returns an `OnDisconnect` object - see + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information on how to use it. + * + * @param ref - The reference to add OnDisconnect triggers for. + */ +function onDisconnect(ref) { + ref = util.getModularInstance(ref); + return new OnDisconnect(ref._repo, ref._path); +} +/** + * Generates a new child location using a unique key and returns its + * `Reference`. + * + * This is the most common pattern for adding data to a collection of items. + * + * If you provide a value to `push()`, the value is written to the + * generated location. If you don't pass a value, nothing is written to the + * database and the child remains empty (but you can use the `Reference` + * elsewhere). + * + * The unique keys generated by `push()` are ordered by the current time, so the + * resulting list of items is chronologically sorted. The keys are also + * designed to be unguessable (they contain 72 random bits of entropy). + * + * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}. + * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}. + * + * @param parent - The parent location. + * @param value - Optional value to be written at the generated location. + * @returns Combined `Promise` and `Reference`; resolves when write is complete, + * but can be used immediately as the `Reference` to the child location. + */ +function push(parent, value) { + parent = util.getModularInstance(parent); + validateWritablePath('push', parent._path); + validateFirebaseDataArg('push', value, parent._path, true); + const now = repoServerTime(parent._repo); + const name = nextPushId(now); + // push() returns a ThennableReference whose promise is fulfilled with a + // regular Reference. We use child() to create handles to two different + // references. The first is turned into a ThennableReference below by adding + // then() and catch() methods and is used as the return value of push(). The + // second remains a regular Reference and is used as the fulfilled value of + // the first ThennableReference. + const thenablePushRef = child(parent, name); + const pushRef = child(parent, name); + let promise; + if (value != null) { + promise = set(pushRef, value).then(() => pushRef); + } + else { + promise = Promise.resolve(pushRef); + } + thenablePushRef.then = promise.then.bind(promise); + thenablePushRef.catch = promise.then.bind(promise, undefined); + return thenablePushRef; +} +/** + * Removes the data at this Database location. + * + * Any data at child locations will also be deleted. + * + * The effect of the remove will be visible immediately and the corresponding + * event 'value' will be triggered. Synchronization of the remove to the + * Firebase servers will also be started, and the returned Promise will resolve + * when complete. If provided, the onComplete callback will be called + * asynchronously after synchronization has finished. + * + * @param ref - The location to remove. + * @returns Resolves when remove on server is complete. + */ +function remove(ref) { + validateWritablePath('remove', ref._path); + return set(ref, null); +} +/** + * Writes data to this Database location. + * + * This will overwrite any data at this location and all child locations. + * + * The effect of the write will be visible immediately, and the corresponding + * events ("value", "child_added", etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * Passing `null` for the new value is equivalent to calling `remove()`; namely, + * all data at this location and all child locations will be deleted. + * + * `set()` will remove any priority stored at this location, so if priority is + * meant to be preserved, you need to use `setWithPriority()` instead. + * + * Note that modifying data with `set()` will cancel any pending transactions + * at that location, so extreme care should be taken if mixing `set()` and + * `transaction()` to modify the same data. + * + * A single `set()` will generate a single "value" event at the location where + * the `set()` was performed. + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @returns Resolves when write to server is complete. + */ +function set(ref, value) { + ref = util.getModularInstance(ref); + validateWritablePath('set', ref._path); + validateFirebaseDataArg('set', value, ref._path, false); + const deferred = new util.Deferred(); + repoSetWithPriority(ref._repo, ref._path, value, + /*priority=*/ null, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Sets a priority for the data at this Database location. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +function setPriority(ref, priority) { + ref = util.getModularInstance(ref); + validateWritablePath('setPriority', ref._path); + validatePriority('setPriority', priority, false); + const deferred = new util.Deferred(); + repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Writes data the Database location. Like `set()` but also specifies the + * priority for that data. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +function setWithPriority(ref, value, priority) { + validateWritablePath('setWithPriority', ref._path); + validateFirebaseDataArg('setWithPriority', value, ref._path, false); + validatePriority('setWithPriority', priority, false); + if (ref.key === '.length' || ref.key === '.keys') { + throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.'; + } + const deferred = new util.Deferred(); + repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Writes multiple values to the Database at once. + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, + * "name/first") from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * The effect of the write will be visible immediately, and the corresponding + * events ('value', 'child_added', etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * A single `update()` will generate a single "value" event at the location + * where the `update()` was performed, regardless of how many children were + * modified. + * + * Note that modifying data with `update()` will cancel any pending + * transactions at that location, so extreme care should be taken if mixing + * `update()` and `transaction()` to modify the same data. + * + * Passing `null` to `update()` will remove the data at this location. + * + * See + * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}. + * + * @param ref - The location to write to. + * @param values - Object containing multiple values. + * @returns Resolves when update on server is complete. + */ +function update(ref, values) { + validateFirebaseMergeDataArg('update', values, ref._path, false); + const deferred = new util.Deferred(); + repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Gets the most up-to-date result for this query. + * + * @param query - The query to run. + * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is + * available, or rejects if the client is unable to return a value (e.g., if the + * server is unreachable and there is nothing cached). + */ +function get(query) { + query = util.getModularInstance(query); + const callbackContext = new CallbackContext(() => { }); + const container = new ValueEventRegistration(callbackContext); + return repoGetValue(query._repo, query, container).then(node => { + return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex()); + }); +} +/** + * Represents registration for 'value' events. + */ +class ValueEventRegistration { + constructor(callbackContext) { + this.callbackContext = callbackContext; + } + respondsTo(eventType) { + return eventType === 'value'; + } + createEvent(change, query) { + const index = query._queryParams.getIndex(); + return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index)); + } + getEventRunner(eventData) { + if (eventData.getEventType() === 'cancel') { + return () => this.callbackContext.onCancel(eventData.error); + } + else { + return () => this.callbackContext.onValue(eventData.snapshot, null); + } + } + createCancelEvent(error, path) { + if (this.callbackContext.hasCancelCallback) { + return new CancelEvent(this, error, path); + } + else { + return null; + } + } + matches(other) { + if (!(other instanceof ValueEventRegistration)) { + return false; + } + else if (!other.callbackContext || !this.callbackContext) { + // If no callback specified, we consider it to match any callback. + return true; + } + else { + return other.callbackContext.matches(this.callbackContext); + } + } + hasAnyCallback() { + return this.callbackContext !== null; + } +} +/** + * Represents the registration of a child_x event. + */ +class ChildEventRegistration { + constructor(eventType, callbackContext) { + this.eventType = eventType; + this.callbackContext = callbackContext; + } + respondsTo(eventType) { + let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType; + eventToCheck = + eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck; + return this.eventType === eventToCheck; + } + createCancelEvent(error, path) { + if (this.callbackContext.hasCancelCallback) { + return new CancelEvent(this, error, path); + } + else { + return null; + } + } + createEvent(change, query) { + util.assert(change.childName != null, 'Child events should have a childName.'); + const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName); + const index = query._queryParams.getIndex(); + return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName); + } + getEventRunner(eventData) { + if (eventData.getEventType() === 'cancel') { + return () => this.callbackContext.onCancel(eventData.error); + } + else { + return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName); + } + } + matches(other) { + if (other instanceof ChildEventRegistration) { + return (this.eventType === other.eventType && + (!this.callbackContext || + !other.callbackContext || + this.callbackContext.matches(other.callbackContext))); + } + return false; + } + hasAnyCallback() { + return !!this.callbackContext; + } +} +function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) { + let cancelCallback; + if (typeof cancelCallbackOrListenOptions === 'object') { + cancelCallback = undefined; + options = cancelCallbackOrListenOptions; + } + if (typeof cancelCallbackOrListenOptions === 'function') { + cancelCallback = cancelCallbackOrListenOptions; + } + if (options && options.onlyOnce) { + const userCallback = callback; + const onceCallback = (dataSnapshot, previousChildName) => { + repoRemoveEventCallbackForQuery(query._repo, query, container); + userCallback(dataSnapshot, previousChildName); + }; + onceCallback.userCallback = callback.userCallback; + onceCallback.context = callback.context; + callback = onceCallback; + } + const callbackContext = new CallbackContext(callback, cancelCallback || undefined); + const container = eventType === 'value' + ? new ValueEventRegistration(callbackContext) + : new ChildEventRegistration(eventType, callbackContext); + repoAddEventCallbackForQuery(query._repo, query, container); + return () => repoRemoveEventCallbackForQuery(query._repo, query, container); +} +function onValue(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options); +} +function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options); +} +function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options); +} +function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options); +} +function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options); +} +/** + * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener. + * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from + * the respective `on*` callbacks. + * + * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener + * will not automatically remove listeners registered on child nodes, `off()` + * must also be called on any child listeners to remove the callback. + * + * If a callback is not specified, all callbacks for the specified eventType + * will be removed. Similarly, if no eventType is specified, all callbacks + * for the `Reference` will be removed. + * + * Individual listeners can also be removed by invoking their unsubscribe + * callbacks. + * + * @param query - The query that the listener was registered with. + * @param eventType - One of the following strings: "value", "child_added", + * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks + * for the `Reference` will be removed. + * @param callback - The callback function that was passed to `on()` or + * `undefined` to remove all callbacks. + */ +function off(query, eventType, callback) { + let container = null; + const expCallback = callback ? new CallbackContext(callback) : null; + if (eventType === 'value') { + container = new ValueEventRegistration(expCallback); + } + else if (eventType) { + container = new ChildEventRegistration(eventType, expCallback); + } + repoRemoveEventCallbackForQuery(query._repo, query, container); +} +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Database query. `QueryConstraint`s are created by invoking {@link endAt}, + * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link + * limitToFirst}, {@link limitToLast}, {@link orderByChild}, + * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} , + * {@link orderByValue} or {@link equalTo} and + * can then be passed to {@link query} to create a new query instance that + * also contains this `QueryConstraint`. + */ +class QueryConstraint { +} +class QueryEndAtConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'endAt'; + } + _apply(query) { + validateFirebaseDataArg('endAt', this._value, query._path, true); + const newParams = queryParamsEndAt(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasEnd()) { + throw new Error('endAt: Starting point was already set (by another call to endAt, ' + + 'endBefore or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified ending point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name less than or equal + * to the specified key. + * + * You can read more about `endAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to end at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end at, among the children with the previously + * specified priority. This argument is only allowed if ordering by child, + * value, or priority. + */ +function endAt(value, key) { + validateKey('endAt', 'key', key, true); + return new QueryEndAtConstraint(value, key); +} +class QueryEndBeforeConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'endBefore'; + } + _apply(query) { + validateFirebaseDataArg('endBefore', this._value, query._path, false); + const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasEnd()) { + throw new Error('endBefore: Starting point was already set (by another call to endAt, ' + + 'endBefore or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified ending point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is exclusive. If only a value is provided, children + * with a value less than the specified value will be included in the query. + * If a key is specified, then children must have a value less than or equal + * to the specified value and a key name less than the specified key. + * + * @param value - The value to end before. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end before, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +function endBefore(value, key) { + validateKey('endBefore', 'key', key, true); + return new QueryEndBeforeConstraint(value, key); +} +class QueryStartAtConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'startAt'; + } + _apply(query) { + validateFirebaseDataArg('startAt', this._value, query._path, true); + const newParams = queryParamsStartAt(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasStart()) { + throw new Error('startAt: Starting point was already set (by another call to startAt, ' + + 'startBefore or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified starting point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name greater than or + * equal to the specified key. + * + * You can read more about `startAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to start at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at. This argument is only allowed if + * ordering by child, value, or priority. + */ +function startAt(value = null, key) { + validateKey('startAt', 'key', key, true); + return new QueryStartAtConstraint(value, key); +} +class QueryStartAfterConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'startAfter'; + } + _apply(query) { + validateFirebaseDataArg('startAfter', this._value, query._path, false); + const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasStart()) { + throw new Error('startAfter: Starting point was already set (by another call to startAt, ' + + 'startAfter, or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified starting point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is exclusive. If only a value is provided, children + * with a value greater than the specified value will be included in the query. + * If a key is specified, then children must have a value greater than or equal + * to the specified value and a a key name greater than the specified key. + * + * @param value - The value to start after. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start after. This argument is only allowed if + * ordering by child, value, or priority. + */ +function startAfter(value, key) { + validateKey('startAfter', 'key', key, true); + return new QueryStartAfterConstraint(value, key); +} +class QueryLimitToFirstConstraint extends QueryConstraint { + constructor(_limit) { + super(); + this._limit = _limit; + this.type = 'limitToFirst'; + } + _apply(query) { + if (query._queryParams.hasLimit()) { + throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' + + 'or limitToLast).'); + } + return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled); + } +} +/** + * Creates a new `QueryConstraint` that if limited to the first specific number + * of children. + * + * The `limitToFirst()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the first 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToFirst()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +function limitToFirst(limit) { + if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) { + throw new Error('limitToFirst: First argument must be a positive integer.'); + } + return new QueryLimitToFirstConstraint(limit); +} +class QueryLimitToLastConstraint extends QueryConstraint { + constructor(_limit) { + super(); + this._limit = _limit; + this.type = 'limitToLast'; + } + _apply(query) { + if (query._queryParams.hasLimit()) { + throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' + + 'or limitToLast).'); + } + return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled); + } +} +/** + * Creates a new `QueryConstraint` that is limited to return only the last + * specified number of children. + * + * The `limitToLast()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the last 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToLast()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +function limitToLast(limit) { + if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) { + throw new Error('limitToLast: First argument must be a positive integer.'); + } + return new QueryLimitToLastConstraint(limit); +} +class QueryOrderByChildConstraint extends QueryConstraint { + constructor(_path) { + super(); + this._path = _path; + this.type = 'orderByChild'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByChild'); + const parsedPath = new Path(this._path); + if (pathIsEmpty(parsedPath)) { + throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.'); + } + const index = new PathIndex(parsedPath); + const newParams = queryParamsOrderBy(query._queryParams, index); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by the specified child key. + * + * Queries can only order by one key at a time. Calling `orderByChild()` + * multiple times on the same query is an error. + * + * Firebase queries allow you to order your data by any child key on the fly. + * However, if you know in advance what your indexes will be, you can define + * them via the .indexOn rule in your Security Rules for better performance. See + * the{@link https://firebase.google.com/docs/database/security/indexing-data} + * rule for more information. + * + * You can read more about `orderByChild()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + * + * @param path - The path to order by. + */ +function orderByChild(path) { + if (path === '$key') { + throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.'); + } + else if (path === '$priority') { + throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.'); + } + else if (path === '$value') { + throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.'); + } + validatePathString('orderByChild', 'path', path, false); + return new QueryOrderByChildConstraint(path); +} +class QueryOrderByKeyConstraint extends QueryConstraint { + constructor() { + super(...arguments); + this.type = 'orderByKey'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByKey'); + const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by the key. + * + * Sorts the results of a query by their (ascending) key values. + * + * You can read more about `orderByKey()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +function orderByKey() { + return new QueryOrderByKeyConstraint(); +} +class QueryOrderByPriorityConstraint extends QueryConstraint { + constructor() { + super(...arguments); + this.type = 'orderByPriority'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByPriority'); + const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by priority. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data} + * for alternatives to priority. + */ +function orderByPriority() { + return new QueryOrderByPriorityConstraint(); +} +class QueryOrderByValueConstraint extends QueryConstraint { + constructor() { + super(...arguments); + this.type = 'orderByValue'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByValue'); + const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by value. + * + * If the children of a query are all scalar values (string, number, or + * boolean), you can order the results by their (ascending) values. + * + * You can read more about `orderByValue()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +function orderByValue() { + return new QueryOrderByValueConstraint(); +} +class QueryEqualToValueConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'equalTo'; + } + _apply(query) { + validateFirebaseDataArg('equalTo', this._value, query._path, false); + if (query._queryParams.hasStart()) { + throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' + + 'equalTo).'); + } + if (query._queryParams.hasEnd()) { + throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' + + 'equalTo).'); + } + return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query)); + } +} +/** + * Creates a `QueryConstraint` that includes children that match the specified + * value. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The optional key argument can be used to further limit the range of the + * query. If it is specified, then children that have exactly the specified + * value must also have exactly the specified key as their key name. This can be + * used to filter result sets with many matches for the same value. + * + * You can read more about `equalTo()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to match for. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +function equalTo(value, key) { + validateKey('equalTo', 'key', key, true); + return new QueryEqualToValueConstraint(value, key); +} +/** + * Creates a new immutable instance of `Query` that is extended to also include + * additional query constraints. + * + * @param query - The Query instance to use as a base for the new constraints. + * @param queryConstraints - The list of `QueryConstraint`s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +function query(query, ...queryConstraints) { + let queryImpl = util.getModularInstance(query); + for (const constraint of queryConstraints) { + queryImpl = constraint._apply(queryImpl); + } + return queryImpl; +} +/** + * Define reference constructor in various modules + * + * We are doing this here to avoid several circular + * dependency issues + */ +syncPointSetReferenceConstructor(ReferenceImpl); +syncTreeSetReferenceConstructor(ReferenceImpl); + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This variable is also defined in the firebase Node.js Admin SDK. Before + * modifying this definition, consult the definition in: + * + * https://github.com/firebase/firebase-admin-node + * + * and make sure the two are consistent. + */ +const FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST'; +/** + * Creates and caches `Repo` instances. + */ +const repos = {}; +/** + * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes). + */ +let useRestClient = false; +/** + * Update an existing `Repo` in place to point to a new host/port. + */ +function repoManagerApplyEmulatorSettings(repo, hostAndPort, emulatorOptions, tokenProvider) { + const portIndex = hostAndPort.lastIndexOf(':'); + const host = hostAndPort.substring(0, portIndex); + const useSsl = util.isCloudWorkstation(host); + repo.repoInfo_ = new RepoInfo(hostAndPort, + /* secure= */ useSsl, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams, + /*isUsingEmulator=*/ true, emulatorOptions); + if (tokenProvider) { + repo.authTokenProvider_ = tokenProvider; + } +} +/** + * This function should only ever be called to CREATE a new database instance. + * @internal + */ +function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) { + let dbUrl = url || app.options.databaseURL; + if (dbUrl === undefined) { + if (!app.options.projectId) { + fatal("Can't determine Firebase Database URL. Be sure to include " + + ' a Project ID when calling firebase.initializeApp().'); + } + log('Using default host for project ', app.options.projectId); + dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`; + } + let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin); + let repoInfo = parsedUrl.repoInfo; + let isEmulator; + let dbEmulatorHost = undefined; + if (typeof process !== 'undefined' && process.env) { + dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR]; + } + if (dbEmulatorHost) { + isEmulator = true; + dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`; + parsedUrl = parseRepoInfo(dbUrl, nodeAdmin); + repoInfo = parsedUrl.repoInfo; + } + else { + isEmulator = !parsedUrl.repoInfo.secure; + } + const authTokenProvider = nodeAdmin && isEmulator + ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER) + : new FirebaseAuthTokenProvider(app.name, app.options, authProvider); + validateUrl('Invalid Firebase Database URL', parsedUrl); + if (!pathIsEmpty(parsedUrl.path)) { + fatal('Database URL must point to the root of a Firebase Database ' + + '(not including a child path).'); + } + const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app, appCheckProvider)); + return new Database(repo, app); +} +/** + * Remove the repo and make sure it is disconnected. + * + */ +function repoManagerDeleteRepo(repo, appName) { + const appRepos = repos[appName]; + // This should never happen... + if (!appRepos || appRepos[repo.key] !== repo) { + fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`); + } + repoInterrupt(repo); + delete appRepos[repo.key]; +} +/** + * Ensures a repo doesn't already exist and then creates one using the + * provided app. + * + * @param repoInfo - The metadata about the Repo + * @returns The Repo object for the specified server / repoName. + */ +function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) { + let appRepos = repos[app.name]; + if (!appRepos) { + appRepos = {}; + repos[app.name] = appRepos; + } + let repo = appRepos[repoInfo.toURLString()]; + if (repo) { + fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.'); + } + repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider); + appRepos[repoInfo.toURLString()] = repo; + return repo; +} +/** + * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos. + */ +function repoManagerForceRestClient(forceRestClient) { + useRestClient = forceRestClient; +} +/** + * Class representing a Firebase Realtime Database. + */ +class Database { + /** @hideconstructor */ + constructor(_repoInternal, + /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */ + app) { + this._repoInternal = _repoInternal; + this.app = app; + /** Represents a `Database` instance. */ + this['type'] = 'database'; + /** Track if the instance has been used (root or repo accessed) */ + this._instanceStarted = false; + } + get _repo() { + if (!this._instanceStarted) { + repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']); + this._instanceStarted = true; + } + return this._repoInternal; + } + get _root() { + if (!this._rootInternal) { + this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath()); + } + return this._rootInternal; + } + _delete() { + if (this._rootInternal !== null) { + repoManagerDeleteRepo(this._repo, this.app.name); + this._repoInternal = null; + this._rootInternal = null; + } + return Promise.resolve(); + } + _checkNotDeleted(apiName) { + if (this._rootInternal === null) { + fatal('Cannot call ' + apiName + ' on a deleted database.'); + } + } +} +function checkTransportInit() { + if (TransportManager.IS_TRANSPORT_INITIALIZED) { + warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener'); + } +} +/** + * Force the use of websockets instead of longPolling. + */ +function forceWebSockets() { + checkTransportInit(); + BrowserPollConnection.forceDisallow(); +} +/** + * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL. + */ +function forceLongPolling() { + checkTransportInit(); + WebSocketConnection.forceDisallow(); + BrowserPollConnection.forceAllow(); +} +/** + * Returns the instance of the Realtime Database SDK that is associated with the provided + * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if + * no instance exists or if the existing instance uses a custom database URL. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime + * Database instance is associated with. + * @param url - The URL of the Realtime Database instance to connect to. If not + * provided, the SDK connects to the default instance of the Firebase App. + * @returns The `Database` instance of the provided app. + */ +function getDatabase(app$1 = app.getApp(), url) { + const db = app._getProvider(app$1, 'database').getImmediate({ + identifier: url + }); + if (!db._instanceStarted) { + const emulator = util.getDefaultEmulatorHostnameAndPort('database'); + if (emulator) { + connectDatabaseEmulator(db, ...emulator); + } + } + return db; +} +/** + * Modify the provided instance to communicate with the Realtime Database + * emulator. + * + *

Note: This method must be called before performing any other operation. + * + * @param db - The instance to modify. + * @param host - The emulator host (ex: localhost) + * @param port - The emulator port (ex: 8080) + * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules + */ +function connectDatabaseEmulator(db, host, port, options = {}) { + db = util.getModularInstance(db); + db._checkNotDeleted('useEmulator'); + const hostAndPort = `${host}:${port}`; + const repo = db._repoInternal; + if (db._instanceStarted) { + // If the instance has already been started, then silenty fail if this function is called again + // with the same parameters. If the parameters differ then assert. + if (hostAndPort === db._repoInternal.repoInfo_.host && + util.deepEqual(options, repo.repoInfo_.emulatorOptions)) { + return; + } + fatal('connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.'); + } + let tokenProvider = undefined; + if (repo.repoInfo_.nodeAdmin) { + if (options.mockUserToken) { + fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'); + } + tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER); + } + else if (options.mockUserToken) { + const token = typeof options.mockUserToken === 'string' + ? options.mockUserToken + : util.createMockUserToken(options.mockUserToken, db.app.options.projectId); + tokenProvider = new EmulatorTokenProvider(token); + } + // Workaround to get cookies in Firebase Studio + if (util.isCloudWorkstation(host)) { + void util.pingServer(host); + util.updateEmulatorBanner('Database', true); + } + // Modify the repo to apply emulator settings + repoManagerApplyEmulatorSettings(repo, hostAndPort, options, tokenProvider); +} +/** + * Disconnects from the server (all Database operations will be completed + * offline). + * + * The client automatically maintains a persistent connection to the Database + * server, which will remain active indefinitely and reconnect when + * disconnected. However, the `goOffline()` and `goOnline()` methods may be used + * to control the client connection in cases where a persistent connection is + * undesirable. + * + * While offline, the client will no longer receive data updates from the + * Database. However, all Database operations performed locally will continue to + * immediately fire events, allowing your application to continue behaving + * normally. Additionally, each operation performed locally will automatically + * be queued and retried upon reconnection to the Database server. + * + * To reconnect to the Database and begin receiving remote events, see + * `goOnline()`. + * + * @param db - The instance to disconnect. + */ +function goOffline(db) { + db = util.getModularInstance(db); + db._checkNotDeleted('goOffline'); + repoInterrupt(db._repo); +} +/** + * Reconnects to the server and synchronizes the offline Database state + * with the server state. + * + * This method should be used after disabling the active connection with + * `goOffline()`. Once reconnected, the client will transmit the proper data + * and fire the appropriate events so that your client "catches up" + * automatically. + * + * @param db - The instance to reconnect. + */ +function goOnline(db) { + db = util.getModularInstance(db); + db._checkNotDeleted('goOnline'); + repoResume(db._repo); +} +function enableLogging(logger, persistent) { + enableLogging$1(logger, persistent); +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function registerDatabase(variant) { + setSDKVersion(app.SDK_VERSION); + app._registerComponent(new component.Component('database', (container, { instanceIdentifier: url }) => { + const app = container.getProvider('app').getImmediate(); + const authProvider = container.getProvider('auth-internal'); + const appCheckProvider = container.getProvider('app-check-internal'); + return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url); + }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true)); + app.registerVersion(name, version, variant); + // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation + app.registerVersion(name, version, 'cjs2020'); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const SERVER_TIMESTAMP = { + '.sv': 'timestamp' +}; +/** + * Returns a placeholder value for auto-populating the current timestamp (time + * since the Unix epoch, in milliseconds) as determined by the Firebase + * servers. + */ +function serverTimestamp() { + return SERVER_TIMESTAMP; +} +/** + * Returns a placeholder value that can be used to atomically increment the + * current database value by the provided delta. + * + * @param delta - the amount to modify the current value atomically. + * @returns A placeholder value for modifying data atomically server-side. + */ +function increment(delta) { + return { + '.sv': { + 'increment': delta + } + }; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A type for the resolve value of {@link runTransaction}. + */ +class TransactionResult { + /** @hideconstructor */ + constructor( + /** Whether the transaction was successfully committed. */ + committed, + /** The resulting data snapshot. */ + snapshot) { + this.committed = committed; + this.snapshot = snapshot; + } + /** Returns a JSON-serializable representation of this object. */ + toJSON() { + return { committed: this.committed, snapshot: this.snapshot.toJSON() }; + } +} +/** + * Atomically modifies the data at this location. + * + * Atomically modify the data at this location. Unlike a normal `set()`, which + * just overwrites the data regardless of its previous value, `runTransaction()` is + * used to modify the existing value to a new value, ensuring there are no + * conflicts with other clients writing to the same location at the same time. + * + * To accomplish this, you pass `runTransaction()` an update function which is + * used to transform the current value into a new value. If another client + * writes to the location before your new value is successfully written, your + * update function will be called again with the new current value, and the + * write will be retried. This will happen repeatedly until your write succeeds + * without conflict or you abort the transaction by not returning a value from + * your update function. + * + * Note: Modifying data with `set()` will cancel any pending transactions at + * that location, so extreme care should be taken if mixing `set()` and + * `runTransaction()` to update the same data. + * + * Note: When using transactions with Security and Firebase Rules in place, be + * aware that a client needs `.read` access in addition to `.write` access in + * order to perform a transaction. This is because the client-side nature of + * transactions requires the client to read the data in order to transactionally + * update it. + * + * @param ref - The location to atomically modify. + * @param transactionUpdate - A developer-supplied function which will be passed + * the current data stored at this location (as a JavaScript object). The + * function should return the new value it would like written (as a JavaScript + * object). If `undefined` is returned (i.e. you return with no arguments) the + * transaction will be aborted and the data at this location will not be + * modified. + * @param options - An options object to configure transactions. + * @returns A `Promise` that can optionally be used instead of the `onComplete` + * callback to handle success and failure. + */ +function runTransaction(ref, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +transactionUpdate, options) { + ref = util.getModularInstance(ref); + validateWritablePath('Reference.transaction', ref._path); + if (ref.key === '.length' || ref.key === '.keys') { + throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.'); + } + const applyLocally = options?.applyLocally ?? true; + const deferred = new util.Deferred(); + const promiseComplete = (error, committed, node) => { + let dataSnapshot = null; + if (error) { + deferred.reject(error); + } + else { + dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX); + deferred.resolve(new TransactionResult(committed, dataSnapshot)); + } + }; + // Add a watch to make sure we get server updates. + const unwatcher = onValue(ref, () => { }); + repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally); + return deferred.promise; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +PersistentConnection; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +PersistentConnection.prototype.simpleListen = function (pathString, onComplete) { + this.sendRequest('q', { p: pathString }, onComplete); +}; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +PersistentConnection.prototype.echo = function (data, onEcho) { + this.sendRequest('echo', { d: data }, onEcho); +}; +// RealTimeConnection properties that we use in tests. +Connection; +/** + * @internal + */ +const hijackHash = function (newHash) { + const oldPut = PersistentConnection.prototype.put; + PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) { + if (hash !== undefined) { + hash = newHash(); + } + oldPut.call(this, pathString, data, onComplete, hash); + }; + return function () { + PersistentConnection.prototype.put = oldPut; + }; +}; +RepoInfo; +/** + * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection. + * @internal + */ +const forceRestClient = function (forceRestClient) { + repoManagerForceRestClient(forceRestClient); +}; + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Used by console to create a database based on the app, + * passed database URL and a custom auth implementation. + * @internal + * @param app - A valid FirebaseApp-like object + * @param url - A valid Firebase databaseURL + * @param version - custom version e.g. firebase-admin version + * @param customAppCheckImpl - custom app check implementation + * @param customAuthImpl - custom auth implementation + */ +function _initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, nodeAdmin = false }) { + setSDKVersion(version); + /** + * ComponentContainer('database-standalone') is just a placeholder that doesn't perform + * any actual function. + */ + const componentContainer = new component.ComponentContainer('database-standalone'); + const authProvider = new component.Provider('auth-internal', componentContainer); + let appCheckProvider; + if (customAppCheckImpl) { + appCheckProvider = new component.Provider('app-check-internal', componentContainer); + appCheckProvider.setComponent(new component.Component('app-check-internal', () => customAppCheckImpl, "PRIVATE" /* ComponentType.PRIVATE */)); + } + authProvider.setComponent(new component.Component('auth-internal', () => customAuthImpl, "PRIVATE" /* ComponentType.PRIVATE */)); + return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin); +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +setWebSocketImpl(Websocket__default["default"].Client); +registerDatabase('node'); + +exports.DataSnapshot = DataSnapshot; +exports.Database = Database; +exports.OnDisconnect = OnDisconnect; +exports.QueryConstraint = QueryConstraint; +exports.TransactionResult = TransactionResult; +exports._QueryImpl = QueryImpl; +exports._QueryParams = QueryParams; +exports._ReferenceImpl = ReferenceImpl; +exports._TEST_ACCESS_forceRestClient = forceRestClient; +exports._TEST_ACCESS_hijackHash = hijackHash; +exports._initStandalone = _initStandalone; +exports._repoManagerDatabaseFromApp = repoManagerDatabaseFromApp; +exports._setSDKVersion = setSDKVersion; +exports._validatePathString = validatePathString; +exports._validateWritablePath = validateWritablePath; +exports.child = child; +exports.connectDatabaseEmulator = connectDatabaseEmulator; +exports.enableLogging = enableLogging; +exports.endAt = endAt; +exports.endBefore = endBefore; +exports.equalTo = equalTo; +exports.forceLongPolling = forceLongPolling; +exports.forceWebSockets = forceWebSockets; +exports.get = get; +exports.getDatabase = getDatabase; +exports.goOffline = goOffline; +exports.goOnline = goOnline; +exports.increment = increment; +exports.limitToFirst = limitToFirst; +exports.limitToLast = limitToLast; +exports.off = off; +exports.onChildAdded = onChildAdded; +exports.onChildChanged = onChildChanged; +exports.onChildMoved = onChildMoved; +exports.onChildRemoved = onChildRemoved; +exports.onDisconnect = onDisconnect; +exports.onValue = onValue; +exports.orderByChild = orderByChild; +exports.orderByKey = orderByKey; +exports.orderByPriority = orderByPriority; +exports.orderByValue = orderByValue; +exports.push = push; +exports.query = query; +exports.ref = ref; +exports.refFromURL = refFromURL; +exports.remove = remove; +exports.runTransaction = runTransaction; +exports.serverTimestamp = serverTimestamp; +exports.set = set; +exports.setPriority = setPriority; +exports.setWithPriority = setWithPriority; +exports.startAfter = startAfter; +exports.startAt = startAt; +exports.update = update; +//# sourceMappingURL=index.node.cjs.js.map diff --git a/node_modules/@firebase/database/dist/index.node.cjs.js.map b/node_modules/@firebase/database/dist/index.node.cjs.js.map new file mode 100644 index 0000000..ddd1055 --- /dev/null +++ b/node_modules/@firebase/database/dist/index.node.cjs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.node.cjs.js","sources":["../src/realtime/Constants.ts","../src/core/storage/DOMStorageWrapper.ts","../src/core/storage/MemoryStorage.ts","../src/core/storage/storage.ts","../src/core/util/util.ts","../src/core/RepoInfo.ts","../src/core/stats/StatsCollection.ts","../src/core/stats/StatsManager.ts","../src/core/version.ts","../src/realtime/WebSocketConnection.ts","../src/core/AppCheckTokenProvider.ts","../src/core/AuthTokenProvider.ts","../src/realtime/polling/PacketReceiver.ts","../src/realtime/BrowserPollConnection.ts","../src/realtime/TransportManager.ts","../src/realtime/Connection.ts","../src/core/ServerActions.ts","../src/core/util/EventEmitter.ts","../src/core/util/OnlineMonitor.ts","../src/core/util/Path.ts","../src/core/util/VisibilityMonitor.ts","../src/core/PersistentConnection.ts","../src/core/snap/Node.ts","../src/core/snap/indexes/Index.ts","../src/core/snap/indexes/KeyIndex.ts","../src/core/util/SortedMap.ts","../src/core/snap/comparators.ts","../src/core/snap/snap.ts","../src/core/snap/LeafNode.ts","../src/core/snap/indexes/PriorityIndex.ts","../src/core/snap/childSet.ts","../src/core/snap/IndexMap.ts","../src/core/snap/ChildrenNode.ts","../src/core/snap/nodeFromJSON.ts","../src/core/snap/indexes/PathIndex.ts","../src/core/snap/indexes/ValueIndex.ts","../src/core/view/Change.ts","../src/core/view/filter/IndexedFilter.ts","../src/core/view/filter/RangedFilter.ts","../src/core/view/filter/LimitedFilter.ts","../src/core/view/QueryParams.ts","../src/core/ReadonlyRestClient.ts","../src/core/SnapshotHolder.ts","../src/core/SparseSnapshotTree.ts","../src/core/stats/StatsListener.ts","../src/core/stats/StatsReporter.ts","../src/core/operation/Operation.ts","../src/core/operation/AckUserWrite.ts","../src/core/operation/ListenComplete.ts","../src/core/operation/Overwrite.ts","../src/core/operation/Merge.ts","../src/core/view/CacheNode.ts","../src/core/view/EventGenerator.ts","../src/core/view/ViewCache.ts","../src/core/util/ImmutableTree.ts","../src/core/CompoundWrite.ts","../src/core/WriteTree.ts","../src/core/view/ChildChangeAccumulator.ts","../src/core/view/CompleteChildSource.ts","../src/core/view/ViewProcessor.ts","../src/core/view/View.ts","../src/core/SyncPoint.ts","../src/core/SyncTree.ts","../src/core/util/ServerValues.ts","../src/core/util/Tree.ts","../src/core/util/validation.ts","../src/core/view/EventQueue.ts","../src/core/Repo.ts","../src/core/util/libs/parser.ts","../src/core/util/NextPushId.ts","../src/core/view/Event.ts","../src/core/view/EventRegistration.ts","../src/api/OnDisconnect.ts","../src/api/Reference_impl.ts","../src/api/Database.ts","../src/register.ts","../src/api/ServerValue.ts","../src/api/Transaction.ts","../src/api/test_access.ts","../src/internal/index.ts","../src/index.node.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const PROTOCOL_VERSION = '5';\n\nexport const VERSION_PARAM = 'v';\n\nexport const TRANSPORT_SESSION_PARAM = 's';\n\nexport const REFERER_PARAM = 'r';\n\nexport const FORGE_REF = 'f';\n\n// Matches console.firebase.google.com, firebase-console-*.corp.google.com and\n// firebase.corp.google.com\nexport const FORGE_DOMAIN_RE =\n /(console\\.firebase|firebase-console-\\w+\\.corp|firebase\\.corp)\\.google\\.com/;\n\nexport const LAST_SESSION_PARAM = 'ls';\n\nexport const APPLICATION_ID_PARAM = 'p';\n\nexport const APP_CHECK_TOKEN_PARAM = 'ac';\n\nexport const WEBSOCKET = 'websocket';\n\nexport const LONG_POLLING = 'long_polling';\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { jsonEval, stringify } from '@firebase/util';\n\n/**\n * Wraps a DOM Storage object and:\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\n *\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\n * and one for localStorage.\n *\n */\nexport class DOMStorageWrapper {\n // Use a prefix to avoid collisions with other stuff saved by the app.\n private prefix_ = 'firebase:';\n\n /**\n * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)\n */\n constructor(private domStorage_: Storage) {}\n\n /**\n * @param key - The key to save the value under\n * @param value - The value being stored, or null to remove the key.\n */\n set(key: string, value: unknown | null) {\n if (value == null) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n } else {\n this.domStorage_.setItem(this.prefixedName_(key), stringify(value));\n }\n }\n\n /**\n * @returns The value that was stored under this key, or null\n */\n get(key: string): unknown {\n const storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n if (storedVal == null) {\n return null;\n } else {\n return jsonEval(storedVal);\n }\n }\n\n remove(key: string) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n\n isInMemoryStorage: boolean;\n\n prefixedName_(name: string): string {\n return this.prefix_ + name;\n }\n\n toString(): string {\n return this.domStorage_.toString();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains } from '@firebase/util';\n\n/**\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\n * (TODO: create interface for both to implement).\n */\nexport class MemoryStorage {\n private cache_: { [k: string]: unknown } = {};\n\n set(key: string, value: unknown | null) {\n if (value == null) {\n delete this.cache_[key];\n } else {\n this.cache_[key] = value;\n }\n }\n\n get(key: string): unknown {\n if (contains(this.cache_, key)) {\n return this.cache_[key];\n }\n return null;\n }\n\n remove(key: string) {\n delete this.cache_[key];\n }\n\n isInMemoryStorage = true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DOMStorageWrapper } from './DOMStorageWrapper';\nimport { MemoryStorage } from './MemoryStorage';\n\ndeclare const window: Window;\n\n/**\n * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\n * to reflect this type\n *\n * @param domStorageName - Name of the underlying storage object\n * (e.g. 'localStorage' or 'sessionStorage').\n * @returns Turning off type information until a common interface is defined.\n */\nconst createStoragefor = function (\n domStorageName: string\n): DOMStorageWrapper | MemoryStorage {\n try {\n // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\n // so it must be inside the try/catch.\n if (\n typeof window !== 'undefined' &&\n typeof window[domStorageName] !== 'undefined'\n ) {\n // Need to test cache. Just because it's here doesn't mean it works\n const domStorage = window[domStorageName];\n domStorage.setItem('firebase:sentinel', 'cache');\n domStorage.removeItem('firebase:sentinel');\n return new DOMStorageWrapper(domStorage);\n }\n } catch (e) {}\n\n // Failed to create wrapper. Just return in-memory storage.\n // TODO: log?\n return new MemoryStorage();\n};\n\n/** A storage object that lasts across sessions */\nexport const PersistentStorage = createStoragefor('localStorage');\n\n/** A storage object that only lasts one session */\nexport const SessionStorage = createStoragefor('sessionStorage');\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel } from '@firebase/logger';\nimport {\n assert,\n base64,\n Sha1,\n stringToByteArray,\n stringify,\n isNodeSdk\n} from '@firebase/util';\n\nimport { SessionStorage } from '../storage/storage';\nimport { QueryContext } from '../view/EventRegistration';\n\ndeclare const window: Window;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ndeclare const Windows: any;\n\nconst logClient = new Logger('@firebase/database');\n\n/**\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\n */\nexport const LUIDGenerator: () => number = (function () {\n let id = 1;\n return function () {\n return id++;\n };\n})();\n\n/**\n * Sha1 hash of the input string\n * @param str - The string to hash\n * @returns {!string} The resulting hash\n */\nexport const sha1 = function (str: string): string {\n const utf8Bytes = stringToByteArray(str);\n const sha1 = new Sha1();\n sha1.update(utf8Bytes);\n const sha1Bytes = sha1.digest();\n return base64.encodeByteArray(sha1Bytes);\n};\n\nconst buildLogMessage_ = function (...varArgs: unknown[]): string {\n let message = '';\n for (let i = 0; i < varArgs.length; i++) {\n const arg = varArgs[i];\n if (\n Array.isArray(arg) ||\n (arg &&\n typeof arg === 'object' &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (arg as any).length === 'number')\n ) {\n message += buildLogMessage_.apply(null, arg);\n } else if (typeof arg === 'object') {\n message += stringify(arg);\n } else {\n message += arg;\n }\n message += ' ';\n }\n\n return message;\n};\n\n/**\n * Use this for all debug messages in Firebase.\n */\nexport let logger: ((a: string) => void) | null = null;\n\n/**\n * Flag to check for log availability on first log message\n */\nlet firstLog_ = true;\n\n/**\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\n * @param logger_ - A flag to turn on logging, or a custom logger\n * @param persistent - Whether or not to persist logging settings across refreshes\n */\nexport const enableLogging = function (\n logger_?: boolean | ((a: string) => void) | null,\n persistent?: boolean\n) {\n assert(\n !persistent || logger_ === true || logger_ === false,\n \"Can't turn on custom loggers persistently.\"\n );\n if (logger_ === true) {\n logClient.logLevel = LogLevel.VERBOSE;\n logger = logClient.log.bind(logClient);\n if (persistent) {\n SessionStorage.set('logging_enabled', true);\n }\n } else if (typeof logger_ === 'function') {\n logger = logger_;\n } else {\n logger = null;\n SessionStorage.remove('logging_enabled');\n }\n};\n\nexport const log = function (...varArgs: unknown[]) {\n if (firstLog_ === true) {\n firstLog_ = false;\n if (logger === null && SessionStorage.get('logging_enabled') === true) {\n enableLogging(true);\n }\n }\n\n if (logger) {\n const message = buildLogMessage_.apply(null, varArgs);\n logger(message);\n }\n};\n\nexport const logWrapper = function (\n prefix: string\n): (...varArgs: unknown[]) => void {\n return function (...varArgs: unknown[]) {\n log(prefix, ...varArgs);\n };\n};\n\nexport const error = function (...varArgs: string[]) {\n const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);\n logClient.error(message);\n};\n\nexport const fatal = function (...varArgs: string[]) {\n const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;\n logClient.error(message);\n throw new Error(message);\n};\n\nexport const warn = function (...varArgs: unknown[]) {\n const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);\n logClient.warn(message);\n};\n\n/**\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\n * does not use https.\n */\nexport const warnIfPageIsSecure = function () {\n // Be very careful accessing browser globals. Who knows what may or may not exist.\n if (\n typeof window !== 'undefined' &&\n window.location &&\n window.location.protocol &&\n window.location.protocol.indexOf('https:') !== -1\n ) {\n warn(\n 'Insecure Firebase access from a secure page. ' +\n 'Please use https in calls to new Firebase().'\n );\n }\n};\n\nexport const warnAboutUnsupportedMethod = function (methodName: string) {\n warn(\n methodName +\n ' is unsupported and will likely change soon. ' +\n 'Please do not use.'\n );\n};\n\n/**\n * Returns true if data is NaN, or +/- Infinity.\n */\nexport const isInvalidJSONNumber = function (data: unknown): boolean {\n return (\n typeof data === 'number' &&\n (data !== data || // NaN\n data === Number.POSITIVE_INFINITY ||\n data === Number.NEGATIVE_INFINITY)\n );\n};\n\nexport const executeWhenDOMReady = function (fn: () => void) {\n if (isNodeSdk() || document.readyState === 'complete') {\n fn();\n } else {\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\n // fire before onload), but fall back to onload.\n\n let called = false;\n const wrappedFn = function () {\n if (!document.body) {\n setTimeout(wrappedFn, Math.floor(10));\n return;\n }\n\n if (!called) {\n called = true;\n fn();\n }\n };\n\n if (document.addEventListener) {\n document.addEventListener('DOMContentLoaded', wrappedFn, false);\n // fallback to onload.\n window.addEventListener('load', wrappedFn, false);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else if ((document as any).attachEvent) {\n // IE.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (document as any).attachEvent('onreadystatechange', () => {\n if (document.readyState === 'complete') {\n wrappedFn();\n }\n });\n // fallback to onload.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (window as any).attachEvent('onload', wrappedFn);\n\n // jQuery has an extra hack for IE that we could employ (based on\n // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\n // I'm hoping we don't need it.\n }\n }\n};\n\n/**\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\n */\nexport const MIN_NAME = '[MIN_NAME]';\n\n/**\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\n */\nexport const MAX_NAME = '[MAX_NAME]';\n\n/**\n * Compares valid Firebase key names, plus min and max name\n */\nexport const nameCompare = function (a: string, b: string): number {\n if (a === b) {\n return 0;\n } else if (a === MIN_NAME || b === MAX_NAME) {\n return -1;\n } else if (b === MIN_NAME || a === MAX_NAME) {\n return 1;\n } else {\n const aAsInt = tryParseInt(a),\n bAsInt = tryParseInt(b);\n\n if (aAsInt !== null) {\n if (bAsInt !== null) {\n return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;\n } else {\n return -1;\n }\n } else if (bAsInt !== null) {\n return 1;\n } else {\n return a < b ? -1 : 1;\n }\n }\n};\n\n/**\n * @returns {!number} comparison result.\n */\nexport const stringCompare = function (a: string, b: string): number {\n if (a === b) {\n return 0;\n } else if (a < b) {\n return -1;\n } else {\n return 1;\n }\n};\n\nexport const requireKey = function (\n key: string,\n obj: { [k: string]: unknown }\n): unknown {\n if (obj && key in obj) {\n return obj[key];\n } else {\n throw new Error(\n 'Missing required key (' + key + ') in object: ' + stringify(obj)\n );\n }\n};\n\nexport const ObjectToUniqueKey = function (obj: unknown): string {\n if (typeof obj !== 'object' || obj === null) {\n return stringify(obj);\n }\n\n const keys = [];\n // eslint-disable-next-line guard-for-in\n for (const k in obj) {\n keys.push(k);\n }\n\n // Export as json, but with the keys sorted.\n keys.sort();\n let key = '{';\n for (let i = 0; i < keys.length; i++) {\n if (i !== 0) {\n key += ',';\n }\n key += stringify(keys[i]);\n key += ':';\n key += ObjectToUniqueKey(obj[keys[i]]);\n }\n\n key += '}';\n return key;\n};\n\n/**\n * Splits a string into a number of smaller segments of maximum size\n * @param str - The string\n * @param segsize - The maximum number of chars in the string.\n * @returns The string, split into appropriately-sized chunks\n */\nexport const splitStringBySize = function (\n str: string,\n segsize: number\n): string[] {\n const len = str.length;\n\n if (len <= segsize) {\n return [str];\n }\n\n const dataSegs = [];\n for (let c = 0; c < len; c += segsize) {\n if (c + segsize > len) {\n dataSegs.push(str.substring(c, len));\n } else {\n dataSegs.push(str.substring(c, c + segsize));\n }\n }\n return dataSegs;\n};\n\n/**\n * Apply a function to each (key, value) pair in an object or\n * apply a function to each (index, value) pair in an array\n * @param obj - The object or array to iterate over\n * @param fn - The function to apply\n */\nexport function each(obj: object, fn: (k: string, v: unknown) => void) {\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n fn(key, obj[key]);\n }\n }\n}\n\n/**\n * Like goog.bind, but doesn't bother to create a closure if opt_context is null/undefined.\n * @param callback - Callback function.\n * @param context - Optional context to bind to.\n *\n */\nexport const bindCallback = function (\n callback: (a: unknown) => void,\n context?: object | null\n): (a: unknown) => void {\n return context ? callback.bind(context) : callback;\n};\n\n/**\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\n * I made one modification at the end and removed the NaN / Infinity\n * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.\n * @param v - A double\n *\n */\nexport const doubleToIEEE754String = function (v: number): string {\n assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\n\n const ebits = 11,\n fbits = 52;\n const bias = (1 << (ebits - 1)) - 1;\n let s, e, f, ln, i;\n\n // Compute sign, exponent, fraction\n // Skip NaN / Infinity handling --MJL.\n if (v === 0) {\n e = 0;\n f = 0;\n s = 1 / v === -Infinity ? 1 : 0;\n } else {\n s = v < 0;\n v = Math.abs(v);\n\n if (v >= Math.pow(2, 1 - bias)) {\n // Normalized\n ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\n e = ln + bias;\n f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\n } else {\n // Denormalized\n e = 0;\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\n }\n }\n\n // Pack sign, exponent, fraction\n const bits = [];\n for (i = fbits; i; i -= 1) {\n bits.push(f % 2 ? 1 : 0);\n f = Math.floor(f / 2);\n }\n for (i = ebits; i; i -= 1) {\n bits.push(e % 2 ? 1 : 0);\n e = Math.floor(e / 2);\n }\n bits.push(s ? 1 : 0);\n bits.reverse();\n const str = bits.join('');\n\n // Return the data as a hex string. --MJL\n let hexByteString = '';\n for (i = 0; i < 64; i += 8) {\n let hexByte = parseInt(str.substr(i, 8), 2).toString(16);\n if (hexByte.length === 1) {\n hexByte = '0' + hexByte;\n }\n hexByteString = hexByteString + hexByte;\n }\n return hexByteString.toLowerCase();\n};\n\n/**\n * Used to detect if we're in a Chrome content script (which executes in an\n * isolated environment where long-polling doesn't work).\n */\nexport const isChromeExtensionContentScript = function (): boolean {\n return !!(\n typeof window === 'object' &&\n window['chrome'] &&\n window['chrome']['extension'] &&\n !/^chrome/.test(window.location.href)\n );\n};\n\n/**\n * Used to detect if we're in a Windows 8 Store app.\n */\nexport const isWindowsStoreApp = function (): boolean {\n // Check for the presence of a couple WinRT globals\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\n};\n\n/**\n * Converts a server error code to a JavaScript Error\n */\nexport function errorForServerCode(code: string, query: QueryContext): Error {\n let reason = 'Unknown Error';\n if (code === 'too_big') {\n reason =\n 'The data requested exceeds the maximum size ' +\n 'that can be accessed with a single request.';\n } else if (code === 'permission_denied') {\n reason = \"Client doesn't have permission to access the desired data.\";\n } else if (code === 'unavailable') {\n reason = 'The service is unavailable';\n }\n\n const error = new Error(\n code + ' at ' + query._path.toString() + ': ' + reason\n );\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (error as any).code = code.toUpperCase();\n return error;\n}\n\n/**\n * Used to test for integer-looking strings\n */\nexport const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\\\d{1,10}$');\n\n/**\n * For use in keys, the minimum possible 32-bit integer.\n */\nexport const INTEGER_32_MIN = -2147483648;\n\n/**\n * For use in keys, the maximum possible 32-bit integer.\n */\nexport const INTEGER_32_MAX = 2147483647;\n\n/**\n * If the string contains a 32-bit integer, return it. Else return null.\n */\nexport const tryParseInt = function (str: string): number | null {\n if (INTEGER_REGEXP_.test(str)) {\n const intVal = Number(str);\n if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {\n return intVal;\n }\n }\n return null;\n};\n\n/**\n * Helper to run some code but catch any exceptions and re-throw them later.\n * Useful for preventing user callbacks from breaking internal code.\n *\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\n * convenient (we don't have to try to figure out when is a safe point to\n * re-throw it), and the behavior seems reasonable:\n *\n * * If you aren't pausing on exceptions, you get an error in the console with\n * the correct stack trace.\n * * If you're pausing on all exceptions, the debugger will pause on your\n * exception and then again when we rethrow it.\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\n * on us re-throwing it.\n *\n * @param fn - The code to guard.\n */\nexport const exceptionGuard = function (fn: () => void) {\n try {\n fn();\n } catch (e) {\n // Re-throw exception when it's safe.\n setTimeout(() => {\n // It used to be that \"throw e\" would result in a good console error with\n // relevant context, but as of Chrome 39, you just get the firebase.js\n // file/line number where we re-throw it, which is useless. So we log\n // e.stack explicitly.\n const stack = e.stack || '';\n warn('Exception was thrown by user callback.', stack);\n throw e;\n }, Math.floor(0));\n }\n};\n\n/**\n * Helper function to safely call opt_callback with the specified arguments. It:\n * 1. Turns into a no-op if opt_callback is null or undefined.\n * 2. Wraps the call inside exceptionGuard to prevent exceptions from breaking our state.\n *\n * @param callback - Optional onComplete callback.\n * @param varArgs - Arbitrary args to be passed to opt_onComplete\n */\nexport const callUserCallback = function (\n // eslint-disable-next-line @typescript-eslint/ban-types\n callback?: Function | null,\n ...varArgs: unknown[]\n) {\n if (typeof callback === 'function') {\n exceptionGuard(() => {\n callback(...varArgs);\n });\n }\n};\n\n/**\n * @returns {boolean} true if we think we're currently being crawled.\n */\nexport const beingCrawled = function (): boolean {\n const userAgent =\n (typeof window === 'object' &&\n window['navigator'] &&\n window['navigator']['userAgent']) ||\n '';\n\n // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we\n // believe to support JavaScript/AJAX rendering.\n // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\n // would have seen the page\" is flaky if we don't treat it as a crawler.\n return (\n userAgent.search(\n /googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i\n ) >= 0\n );\n};\n\n/**\n * Export a property of an object using a getter function.\n */\nexport const exportPropGetter = function (\n object: object,\n name: string,\n fnGet: () => unknown\n) {\n Object.defineProperty(object, name, { get: fnGet });\n};\n\n/**\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\n *\n * It is removed with clearTimeout() as normal.\n *\n * @param fn - Function to run.\n * @param time - Milliseconds to wait before running.\n * @returns The setTimeout() return value.\n */\nexport const setTimeoutNonBlocking = function (\n fn: () => void,\n time: number\n): number | object {\n const timeout: number | object = setTimeout(fn, time);\n // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.\n if (\n typeof timeout === 'number' &&\n // @ts-ignore Is only defined in Deno environments.\n typeof Deno !== 'undefined' &&\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\n Deno['unrefTimer']\n ) {\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\n Deno.unrefTimer(timeout);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else if (typeof timeout === 'object' && (timeout as any)['unref']) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (timeout as any)['unref']();\n }\n\n return timeout;\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, EmulatorMockTokenOptions } from '@firebase/util';\n\nimport { LONG_POLLING, WEBSOCKET } from '../realtime/Constants';\n\nimport { PersistentStorage } from './storage/storage';\nimport { each } from './util/util';\n\nexport interface RepoInfoEmulatorOptions {\n mockUserToken?: string | EmulatorMockTokenOptions;\n}\n\n/**\n * A class that holds metadata about a Repo object\n */\nexport class RepoInfo {\n private _host: string;\n private _domain: string;\n internalHost: string;\n\n /**\n * @param host - Hostname portion of the url for the repo\n * @param secure - Whether or not this repo is accessed over ssl\n * @param namespace - The namespace represented by the repo\n * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).\n * @param nodeAdmin - Whether this instance uses Admin SDK credentials\n * @param persistenceKey - Override the default session persistence storage key\n */\n constructor(\n host: string,\n public readonly secure: boolean,\n public readonly namespace: string,\n public readonly webSocketOnly: boolean,\n public readonly nodeAdmin: boolean = false,\n public readonly persistenceKey: string = '',\n public readonly includeNamespaceInQueryParams: boolean = false,\n public readonly isUsingEmulator: boolean = false,\n public readonly emulatorOptions: RepoInfoEmulatorOptions | null = null\n ) {\n this._host = host.toLowerCase();\n this._domain = this._host.substr(this._host.indexOf('.') + 1);\n this.internalHost =\n (PersistentStorage.get('host:' + host) as string) || this._host;\n }\n\n isCacheableHost(): boolean {\n return this.internalHost.substr(0, 2) === 's-';\n }\n\n isCustomHost() {\n return (\n this._domain !== 'firebaseio.com' &&\n this._domain !== 'firebaseio-demo.com'\n );\n }\n\n get host() {\n return this._host;\n }\n\n set host(newHost: string) {\n if (newHost !== this.internalHost) {\n this.internalHost = newHost;\n if (this.isCacheableHost()) {\n PersistentStorage.set('host:' + this._host, this.internalHost);\n }\n }\n }\n\n toString(): string {\n let str = this.toURLString();\n if (this.persistenceKey) {\n str += '<' + this.persistenceKey + '>';\n }\n return str;\n }\n\n toURLString(): string {\n const protocol = this.secure ? 'https://' : 'http://';\n const query = this.includeNamespaceInQueryParams\n ? `?ns=${this.namespace}`\n : '';\n return `${protocol}${this.host}/${query}`;\n }\n}\n\nfunction repoInfoNeedsQueryParam(repoInfo: RepoInfo): boolean {\n return (\n repoInfo.host !== repoInfo.internalHost ||\n repoInfo.isCustomHost() ||\n repoInfo.includeNamespaceInQueryParams\n );\n}\n\n/**\n * Returns the websocket URL for this repo\n * @param repoInfo - RepoInfo object\n * @param type - of connection\n * @param params - list\n * @returns The URL for this repo\n */\nexport function repoInfoConnectionURL(\n repoInfo: RepoInfo,\n type: string,\n params: { [k: string]: string }\n): string {\n assert(typeof type === 'string', 'typeof type must == string');\n assert(typeof params === 'object', 'typeof params must == object');\n\n let connURL: string;\n if (type === WEBSOCKET) {\n connURL =\n (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';\n } else if (type === LONG_POLLING) {\n connURL =\n (repoInfo.secure ? 'https://' : 'http://') +\n repoInfo.internalHost +\n '/.lp?';\n } else {\n throw new Error('Unknown connection type: ' + type);\n }\n if (repoInfoNeedsQueryParam(repoInfo)) {\n params['ns'] = repoInfo.namespace;\n }\n\n const pairs: string[] = [];\n\n each(params, (key: string, value: string) => {\n pairs.push(key + '=' + value);\n });\n\n return connURL + pairs.join('&');\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { deepCopy, contains } from '@firebase/util';\n\n/**\n * Tracks a collection of stats.\n */\nexport class StatsCollection {\n private counters_: { [k: string]: number } = {};\n\n incrementCounter(name: string, amount: number = 1) {\n if (!contains(this.counters_, name)) {\n this.counters_[name] = 0;\n }\n\n this.counters_[name] += amount;\n }\n\n get() {\n return deepCopy(this.counters_);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../RepoInfo';\n\nimport { StatsCollection } from './StatsCollection';\n\nconst collections: { [k: string]: StatsCollection } = {};\nconst reporters: { [k: string]: unknown } = {};\n\nexport function statsManagerGetCollection(repoInfo: RepoInfo): StatsCollection {\n const hashString = repoInfo.toString();\n\n if (!collections[hashString]) {\n collections[hashString] = new StatsCollection();\n }\n\n return collections[hashString];\n}\n\nexport function statsManagerGetOrCreateReporter(\n repoInfo: RepoInfo,\n creatorFunction: () => T\n): T {\n const hashString = repoInfo.toString();\n\n if (!reporters[hashString]) {\n reporters[hashString] = creatorFunction();\n }\n\n return reporters[hashString] as T;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nexport let SDK_VERSION = '';\n\n/**\n * SDK_VERSION should be set before any database instance is created\n * @internal\n */\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, isNodeSdk, jsonEval, stringify } from '@firebase/util';\n\nimport { RepoInfo, repoInfoConnectionURL } from '../core/RepoInfo';\nimport { StatsCollection } from '../core/stats/StatsCollection';\nimport { statsManagerGetCollection } from '../core/stats/StatsManager';\nimport { PersistentStorage } from '../core/storage/storage';\nimport { logWrapper, splitStringBySize } from '../core/util/util';\nimport { SDK_VERSION } from '../core/version';\n\nimport {\n APPLICATION_ID_PARAM,\n APP_CHECK_TOKEN_PARAM,\n FORGE_DOMAIN_RE,\n FORGE_REF,\n LAST_SESSION_PARAM,\n PROTOCOL_VERSION,\n REFERER_PARAM,\n TRANSPORT_SESSION_PARAM,\n VERSION_PARAM,\n WEBSOCKET\n} from './Constants';\nimport { Transport } from './Transport';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ndeclare const MozWebSocket: any;\n\nconst WEBSOCKET_MAX_FRAME_SIZE = 16384;\nconst WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\n\nlet WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n} else if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\n\nexport function setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\n\n/**\n * Create a new websocket connection with the given callbacks.\n */\nexport class WebSocketConnection implements Transport {\n keepaliveTimer: number | null = null;\n frames: string[] | null = null;\n totalFrames = 0;\n bytesSent = 0;\n bytesReceived = 0;\n connURL: string;\n onDisconnect: (a?: boolean) => void;\n onMessage: (msg: {}) => void;\n mySock: WebSocket | null;\n private log_: (...a: unknown[]) => void;\n private stats_: StatsCollection;\n private everConnected_: boolean;\n private isClosed_: boolean;\n private nodeAdmin: boolean;\n\n /**\n * @param connId identifier for this transport\n * @param repoInfo The info for the websocket endpoint.\n * @param applicationId The Firebase App ID for this project.\n * @param appCheckToken The App Check Token for this client.\n * @param authToken The Auth Token for this client.\n * @param transportSessionId Optional transportSessionId if this is connecting\n * to an existing transport session\n * @param lastSessionId Optional lastSessionId if there was a previous\n * connection\n */\n constructor(\n public connId: string,\n repoInfo: RepoInfo,\n private applicationId?: string,\n private appCheckToken?: string,\n private authToken?: string,\n transportSessionId?: string,\n lastSessionId?: string\n ) {\n this.log_ = logWrapper(this.connId);\n this.stats_ = statsManagerGetCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(\n repoInfo,\n transportSessionId,\n lastSessionId,\n appCheckToken,\n applicationId\n );\n this.nodeAdmin = repoInfo.nodeAdmin;\n }\n\n /**\n * @param repoInfo - The info for the websocket endpoint.\n * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param lastSessionId - Optional lastSessionId if there was a previous connection\n * @returns connection url\n */\n private static connectionURL_(\n repoInfo: RepoInfo,\n transportSessionId?: string,\n lastSessionId?: string,\n appCheckToken?: string,\n applicationId?: string\n ): string {\n const urlParams: { [k: string]: string } = {};\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\n\n if (\n !isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.hostname &&\n FORGE_DOMAIN_RE.test(location.hostname)\n ) {\n urlParams[REFERER_PARAM] = FORGE_REF;\n }\n if (transportSessionId) {\n urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[LAST_SESSION_PARAM] = lastSessionId;\n }\n if (appCheckToken) {\n urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;\n }\n if (applicationId) {\n urlParams[APPLICATION_ID_PARAM] = applicationId;\n }\n\n return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);\n }\n\n /**\n * @param onMessage - Callback when messages arrive\n * @param onDisconnect - Callback with connection lost.\n */\n open(onMessage: (msg: {}) => void, onDisconnect: (a?: boolean) => void) {\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n\n this.log_('Websocket connecting to ' + this.connURL);\n\n this.everConnected_ = false;\n // Assume failure until proven otherwise.\n PersistentStorage.set('previous_websocket_failure', true);\n\n try {\n let options: { [k: string]: object };\n if (isNodeSdk()) {\n const device = this.nodeAdmin ? 'AdminNode' : 'Node';\n // UA Format: Firebase////\n options = {\n headers: {\n 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,\n 'X-Firebase-GMPID': this.applicationId || ''\n }\n };\n\n // If using Node with admin creds, AppCheck-related checks are unnecessary.\n // Note that we send the credentials here even if they aren't admin credentials, which is\n // not a problem.\n // Note that this header is just used to bypass appcheck, and the token should still be sent\n // through the websocket connection once it is established.\n if (this.authToken) {\n options.headers['Authorization'] = `Bearer ${this.authToken}`;\n }\n if (this.appCheckToken) {\n options.headers['X-Firebase-AppCheck'] = this.appCheckToken;\n }\n\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n const env = process['env'];\n const proxy =\n this.connURL.indexOf('wss://') === 0\n ? env['HTTPS_PROXY'] || env['https_proxy']\n : env['HTTP_PROXY'] || env['http_proxy'];\n\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n }\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n } catch (e) {\n this.log_('Error instantiating WebSocket.');\n const error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n return;\n }\n\n this.mySock.onopen = () => {\n this.log_('Websocket connected.');\n this.everConnected_ = true;\n };\n\n this.mySock.onclose = () => {\n this.log_('Websocket connection was disconnected.');\n this.mySock = null;\n this.onClosed_();\n };\n\n this.mySock.onmessage = m => {\n this.handleIncomingFrame(m as {});\n };\n\n this.mySock.onerror = e => {\n this.log_('WebSocket error. Closing connection.');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const error = (e as any).message || (e as any).data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n };\n }\n\n /**\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n */\n start() {}\n\n static forceDisallow_: boolean;\n\n static forceDisallow() {\n WebSocketConnection.forceDisallow_ = true;\n }\n\n static isAvailable(): boolean {\n let isOldAndroid = false;\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n const oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n isOldAndroid = true;\n }\n }\n }\n\n return (\n !isOldAndroid &&\n WebSocketImpl !== null &&\n !WebSocketConnection.forceDisallow_\n );\n }\n\n /**\n * Number of response before we consider the connection \"healthy.\"\n */\n static responsesRequiredToBeHealthy = 2;\n\n /**\n * Time to wait for the connection te become healthy before giving up.\n */\n static healthyTimeout = 30000;\n\n /**\n * Returns true if we previously failed to connect with this transport.\n */\n static previouslyFailed(): boolean {\n // If our persistent storage is actually only in-memory storage,\n // we default to assuming that it previously failed to be safe.\n return (\n PersistentStorage.isInMemoryStorage ||\n PersistentStorage.get('previous_websocket_failure') === true\n );\n }\n\n markConnectionHealthy() {\n PersistentStorage.remove('previous_websocket_failure');\n }\n\n private appendFrame_(data: string) {\n this.frames.push(data);\n if (this.frames.length === this.totalFrames) {\n const fullMess = this.frames.join('');\n this.frames = null;\n const jsonMess = jsonEval(fullMess) as object;\n\n //handle the message\n this.onMessage(jsonMess);\n }\n }\n\n /**\n * @param frameCount - The number of frames we are expecting from the server\n */\n private handleNewFrameCount_(frameCount: number) {\n this.totalFrames = frameCount;\n this.frames = [];\n }\n\n /**\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\n * @returns Any remaining data to be process, or null if there is none\n */\n private extractFrameCount_(data: string): string | null {\n assert(this.frames === null, 'We already have a frame buffer');\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\n if (data.length <= 6) {\n const frameCount = Number(data);\n if (!isNaN(frameCount)) {\n this.handleNewFrameCount_(frameCount);\n return null;\n }\n }\n this.handleNewFrameCount_(1);\n return data;\n }\n\n /**\n * Process a websocket frame that has arrived from the server.\n * @param mess - The frame data\n */\n handleIncomingFrame(mess: { [k: string]: unknown }) {\n if (this.mySock === null) {\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n }\n const data = mess['data'] as string;\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n\n this.resetKeepAlive();\n\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n } else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n const remainingData = this.extractFrameCount_(data);\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n }\n\n /**\n * Send a message to the server\n * @param data - The JSON object to transmit\n */\n send(data: {}) {\n this.resetKeepAlive();\n\n const dataStr = stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n\n //We can only fit a certain amount in each websocket frame, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n\n const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n\n //Send the length header\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n }\n\n //Send the actual data in segments.\n for (let i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n }\n\n private shutdown_() {\n this.isClosed_ = true;\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n }\n\n private onClosed_() {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_();\n\n // since this is an internal close, trigger the close listener\n if (this.onDisconnect) {\n this.onDisconnect(this.everConnected_);\n this.onDisconnect = null;\n }\n }\n }\n\n /**\n * External-facing close handler.\n * Close the websocket and kill the connection.\n */\n close() {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n }\n\n /**\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\n * the last activity.\n */\n resetKeepAlive() {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(() => {\n //If there has been no websocket activity for a while, send a no-op\n if (this.mySock) {\n this.sendString_('0');\n }\n this.resetKeepAlive();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL)) as any;\n }\n\n /**\n * Send a string over the websocket.\n *\n * @param str - String to send.\n */\n private sendString_(str: string) {\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n // calls for some unknown reason. We treat these as an error and disconnect.\n // See https://app.asana.com/0/58926111402292/68021340250410\n try {\n this.mySock.send(str);\n } catch (e) {\n this.log_(\n 'Exception thrown from WebSocket.send():',\n e.message || e.data,\n 'Closing connection.'\n );\n setTimeout(this.onClosed_.bind(this), 0);\n }\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _isFirebaseServerApp } from '@firebase/app'; // eslint-disable-line import/no-extraneous-dependencies\nimport {\n AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { warn } from './util/util';\n\n/**\n * Abstraction around AppCheck's token fetching capabilities.\n */\nexport class AppCheckTokenProvider {\n private appCheck?: FirebaseAppCheckInternal;\n private serverAppAppCheckToken?: string;\n private appName: string;\n constructor(\n app: FirebaseApp,\n private appCheckProvider?: Provider\n ) {\n this.appName = app.name;\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n this.appCheck = appCheckProvider?.getImmediate({ optional: true });\n if (!this.appCheck) {\n appCheckProvider?.get().then(appCheck => (this.appCheck = appCheck));\n }\n }\n\n getToken(forceRefresh?: boolean): Promise {\n if (this.serverAppAppCheckToken) {\n if (forceRefresh) {\n throw new Error(\n 'Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.'\n );\n }\n return Promise.resolve({ token: this.serverAppAppCheckToken });\n }\n if (!this.appCheck) {\n return new Promise((resolve, reject) => {\n // Support delayed initialization of FirebaseAppCheck. This allows our\n // customers to initialize the RTDB SDK before initializing Firebase\n // AppCheck and ensures that all requests are authenticated if a token\n // becomes available before the timeout below expires.\n setTimeout(() => {\n if (this.appCheck) {\n this.getToken(forceRefresh).then(resolve, reject);\n } else {\n resolve(null);\n }\n }, 0);\n });\n }\n return this.appCheck.getToken(forceRefresh);\n }\n\n addTokenChangeListener(listener: AppCheckTokenListener) {\n this.appCheckProvider\n ?.get()\n .then(appCheck => appCheck.addTokenListener(listener));\n }\n\n notifyForInvalidToken(): void {\n warn(\n `Provided AppCheck credentials for the app named \"${this.appName}\" ` +\n 'are invalid. This usually indicates your app was not initialized correctly.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseAuthTokenData } from '@firebase/app-types/private';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { log, warn } from './util/util';\n\nexport interface AuthTokenProvider {\n getToken(forceRefresh: boolean): Promise;\n addTokenChangeListener(listener: (token: string | null) => void): void;\n removeTokenChangeListener(listener: (token: string | null) => void): void;\n notifyForInvalidToken(): void;\n}\n\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nexport class FirebaseAuthTokenProvider implements AuthTokenProvider {\n private auth_: FirebaseAuthInternal | null = null;\n\n constructor(\n private appName_: string,\n private firebaseOptions_: object,\n private authProvider_: Provider\n ) {\n this.auth_ = authProvider_.getImmediate({ optional: true });\n if (!this.auth_) {\n authProvider_.onInit(auth => (this.auth_ = auth));\n }\n }\n\n getToken(forceRefresh: boolean): Promise {\n if (!this.auth_) {\n return new Promise((resolve, reject) => {\n // Support delayed initialization of FirebaseAuth. This allows our\n // customers to initialize the RTDB SDK before initializing Firebase\n // Auth and ensures that all requests are authenticated if a token\n // becomes available before the timeout below expires.\n setTimeout(() => {\n if (this.auth_) {\n this.getToken(forceRefresh).then(resolve, reject);\n } else {\n resolve(null);\n }\n }, 0);\n });\n }\n\n return this.auth_.getToken(forceRefresh).catch(error => {\n // TODO: Need to figure out all the cases this is raised and whether\n // this makes sense.\n if (error && error.code === 'auth/token-not-initialized') {\n log('Got auth/token-not-initialized error. Treating as null token.');\n return null;\n } else {\n return Promise.reject(error);\n }\n });\n }\n\n addTokenChangeListener(listener: (token: string | null) => void): void {\n // TODO: We might want to wrap the listener and call it with no args to\n // avoid a leaky abstraction, but that makes removing the listener harder.\n if (this.auth_) {\n this.auth_.addAuthTokenListener(listener);\n } else {\n this.authProvider_\n .get()\n .then(auth => auth.addAuthTokenListener(listener));\n }\n }\n\n removeTokenChangeListener(listener: (token: string | null) => void): void {\n this.authProvider_\n .get()\n .then(auth => auth.removeAuthTokenListener(listener));\n }\n\n notifyForInvalidToken(): void {\n let errorMessage =\n 'Provided authentication credentials for the app named \"' +\n this.appName_ +\n '\" are invalid. This usually indicates your app was not ' +\n 'initialized correctly. ';\n if ('credential' in this.firebaseOptions_) {\n errorMessage +=\n 'Make sure the \"credential\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n } else if ('serviceAccount' in this.firebaseOptions_) {\n errorMessage +=\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n } else {\n errorMessage +=\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\n 'initializeApp() match the values provided for your app at ' +\n 'https://console.firebase.google.com/.';\n }\n warn(errorMessage);\n }\n}\n\n/* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */\nexport class EmulatorTokenProvider implements AuthTokenProvider {\n /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */\n static OWNER = 'owner';\n\n constructor(private accessToken: string) {}\n\n getToken(forceRefresh: boolean): Promise {\n return Promise.resolve({\n accessToken: this.accessToken\n });\n }\n\n addTokenChangeListener(listener: (token: string | null) => void): void {\n // Invoke the listener immediately to match the behavior in Firebase Auth\n // (see packages/auth/src/auth.js#L1807)\n listener(this.accessToken);\n }\n\n removeTokenChangeListener(listener: (token: string | null) => void): void {}\n\n notifyForInvalidToken(): void {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { exceptionGuard } from '../../core/util/util';\n\n/**\n * This class ensures the packets from the server arrive in order\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\n */\nexport class PacketReceiver {\n pendingResponses: unknown[] = [];\n currentResponseNum = 0;\n closeAfterResponse = -1;\n onClose: (() => void) | null = null;\n\n /**\n * @param onMessage_\n */\n constructor(private onMessage_: (a: {}) => void) {}\n\n closeAfter(responseNum: number, callback: () => void) {\n this.closeAfterResponse = responseNum;\n this.onClose = callback;\n if (this.closeAfterResponse < this.currentResponseNum) {\n this.onClose();\n this.onClose = null;\n }\n }\n\n /**\n * Each message from the server comes with a response number, and an array of data. The responseNumber\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\n * browsers will respond in the same order as the requests we sent\n */\n handleResponse(requestNum: number, data: unknown[]) {\n this.pendingResponses[requestNum] = data;\n while (this.pendingResponses[this.currentResponseNum]) {\n const toProcess = this.pendingResponses[\n this.currentResponseNum\n ] as unknown[];\n delete this.pendingResponses[this.currentResponseNum];\n for (let i = 0; i < toProcess.length; ++i) {\n if (toProcess[i]) {\n exceptionGuard(() => {\n this.onMessage_(toProcess[i]);\n });\n }\n }\n if (this.currentResponseNum === this.closeAfterResponse) {\n if (this.onClose) {\n this.onClose();\n this.onClose = null;\n }\n break;\n }\n this.currentResponseNum++;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Encode, isNodeSdk, stringify } from '@firebase/util';\n\nimport { RepoInfo, repoInfoConnectionURL } from '../core/RepoInfo';\nimport { StatsCollection } from '../core/stats/StatsCollection';\nimport { statsManagerGetCollection } from '../core/stats/StatsManager';\nimport {\n executeWhenDOMReady,\n isChromeExtensionContentScript,\n isWindowsStoreApp,\n log,\n logWrapper,\n LUIDGenerator,\n splitStringBySize\n} from '../core/util/util';\n\nimport {\n APP_CHECK_TOKEN_PARAM,\n APPLICATION_ID_PARAM,\n FORGE_DOMAIN_RE,\n FORGE_REF,\n LAST_SESSION_PARAM,\n LONG_POLLING,\n PROTOCOL_VERSION,\n REFERER_PARAM,\n TRANSPORT_SESSION_PARAM,\n VERSION_PARAM\n} from './Constants';\nimport { PacketReceiver } from './polling/PacketReceiver';\nimport { Transport } from './Transport';\n\n// URL query parameters associated with longpolling\nexport const FIREBASE_LONGPOLL_START_PARAM = 'start';\nexport const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\nexport const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\nexport const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\nexport const FIREBASE_LONGPOLL_ID_PARAM = 'id';\nexport const FIREBASE_LONGPOLL_PW_PARAM = 'pw';\nexport const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\nexport const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\nexport const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\nexport const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\nexport const FIREBASE_LONGPOLL_DATA_PARAM = 'd';\nexport const FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = 'disconn';\nexport const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\n\n//Data size constants.\n//TODO: Perf: the maximum length actually differs from browser to browser.\n// We should check what browser we're on and set accordingly.\nconst MAX_URL_DATA_SIZE = 1870;\nconst SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\nconst MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\n\n/**\n * Keepalive period\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\n * length of 30 seconds that we can't exceed.\n */\nconst KEEPALIVE_REQUEST_INTERVAL = 25000;\n\n/**\n * How long to wait before aborting a long-polling connection attempt.\n */\nconst LP_CONNECT_TIMEOUT = 30000;\n\n/**\n * This class manages a single long-polling connection.\n */\nexport class BrowserPollConnection implements Transport {\n bytesSent = 0;\n bytesReceived = 0;\n urlFn: (params: object) => string;\n scriptTagHolder: FirebaseIFrameScriptHolder;\n myDisconnFrame: HTMLIFrameElement;\n curSegmentNum: number;\n myPacketOrderer: PacketReceiver;\n id: string;\n password: string;\n private log_: (...a: unknown[]) => void;\n private stats_: StatsCollection;\n private everConnected_ = false;\n private isClosed_: boolean;\n private connectTimeoutTimer_: number | null;\n private onDisconnect_: ((a?: boolean) => void) | null;\n\n /**\n * @param connId An identifier for this connection, used for logging\n * @param repoInfo The info for the endpoint to send data to.\n * @param applicationId The Firebase App ID for this project.\n * @param appCheckToken The AppCheck token for this client.\n * @param authToken The AuthToken to use for this connection.\n * @param transportSessionId Optional transportSessionid if we are\n * reconnecting for an existing transport session\n * @param lastSessionId Optional lastSessionId if the PersistentConnection has\n * already created a connection previously\n */\n constructor(\n public connId: string,\n public repoInfo: RepoInfo,\n private applicationId?: string,\n private appCheckToken?: string,\n private authToken?: string,\n public transportSessionId?: string,\n public lastSessionId?: string\n ) {\n this.log_ = logWrapper(connId);\n this.stats_ = statsManagerGetCollection(repoInfo);\n this.urlFn = (params: { [k: string]: string }) => {\n // Always add the token if we have one.\n if (this.appCheckToken) {\n params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\n }\n return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);\n };\n }\n\n /**\n * @param onMessage - Callback when messages arrive\n * @param onDisconnect - Callback with connection lost.\n */\n open(onMessage: (msg: {}) => void, onDisconnect: (a?: boolean) => void) {\n this.curSegmentNum = 0;\n this.onDisconnect_ = onDisconnect;\n this.myPacketOrderer = new PacketReceiver(onMessage);\n this.isClosed_ = false;\n\n this.connectTimeoutTimer_ = setTimeout(() => {\n this.log_('Timed out trying to connect.');\n // Make sure we clear the host cache\n this.onClosed_();\n this.connectTimeoutTimer_ = null;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(LP_CONNECT_TIMEOUT)) as any;\n\n // Ensure we delay the creation of the iframe until the DOM is loaded.\n executeWhenDOMReady(() => {\n if (this.isClosed_) {\n return;\n }\n\n //Set up a callback that gets triggered once a connection is set up.\n this.scriptTagHolder = new FirebaseIFrameScriptHolder(\n (...args) => {\n const [command, arg1, arg2, arg3, arg4] = args;\n this.incrementIncomingBytes_(args);\n if (!this.scriptTagHolder) {\n return; // we closed the connection.\n }\n\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n this.everConnected_ = true;\n if (command === FIREBASE_LONGPOLL_START_PARAM) {\n this.id = arg1 as string;\n this.password = arg2 as string;\n } else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {\n // Don't clear the host cache. We got a response from the server, so we know it's reachable\n if (arg1) {\n // We aren't expecting any more data (other than what the server's already in the process of sending us\n // through our already open polls), so don't send any more.\n this.scriptTagHolder.sendNewPolls = false;\n\n // arg1 in this case is the last response number sent by the server. We should try to receive\n // all of the responses up to this one before closing\n this.myPacketOrderer.closeAfter(arg1 as number, () => {\n this.onClosed_();\n });\n } else {\n this.onClosed_();\n }\n } else {\n throw new Error('Unrecognized command received: ' + command);\n }\n },\n (...args) => {\n const [pN, data] = args;\n this.incrementIncomingBytes_(args);\n this.myPacketOrderer.handleResponse(pN as number, data as unknown[]);\n },\n () => {\n this.onClosed_();\n },\n this.urlFn\n );\n\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\n //from cache.\n const urlParams: { [k: string]: string | number } = {};\n urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(\n Math.random() * 100000000\n );\n if (this.scriptTagHolder.uniqueCallbackIdentifier) {\n urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =\n this.scriptTagHolder.uniqueCallbackIdentifier;\n }\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\n if (this.transportSessionId) {\n urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;\n }\n if (this.lastSessionId) {\n urlParams[LAST_SESSION_PARAM] = this.lastSessionId;\n }\n if (this.applicationId) {\n urlParams[APPLICATION_ID_PARAM] = this.applicationId;\n }\n if (this.appCheckToken) {\n urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\n }\n if (\n typeof location !== 'undefined' &&\n location.hostname &&\n FORGE_DOMAIN_RE.test(location.hostname)\n ) {\n urlParams[REFERER_PARAM] = FORGE_REF;\n }\n const connectURL = this.urlFn(urlParams);\n this.log_('Connecting via long-poll to ' + connectURL);\n this.scriptTagHolder.addTag(connectURL, () => {\n /* do nothing */\n });\n });\n }\n\n /**\n * Call this when a handshake has completed successfully and we want to consider the connection established\n */\n start() {\n this.scriptTagHolder.startLongPoll(this.id, this.password);\n this.addDisconnectPingFrame(this.id, this.password);\n }\n\n static forceAllow_: boolean;\n\n /**\n * Forces long polling to be considered as a potential transport\n */\n static forceAllow() {\n BrowserPollConnection.forceAllow_ = true;\n }\n\n static forceDisallow_: boolean;\n\n /**\n * Forces longpolling to not be considered as a potential transport\n */\n static forceDisallow() {\n BrowserPollConnection.forceDisallow_ = true;\n }\n\n // Static method, use string literal so it can be accessed in a generic way\n static isAvailable() {\n if (isNodeSdk()) {\n return false;\n } else if (BrowserPollConnection.forceAllow_) {\n return true;\n } else {\n // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\n // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\n return (\n !BrowserPollConnection.forceDisallow_ &&\n typeof document !== 'undefined' &&\n document.createElement != null &&\n !isChromeExtensionContentScript() &&\n !isWindowsStoreApp()\n );\n }\n }\n\n /**\n * No-op for polling\n */\n markConnectionHealthy() {}\n\n /**\n * Stops polling and cleans up the iframe\n */\n private shutdown_() {\n this.isClosed_ = true;\n\n if (this.scriptTagHolder) {\n this.scriptTagHolder.close();\n this.scriptTagHolder = null;\n }\n\n //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\n if (this.myDisconnFrame) {\n document.body.removeChild(this.myDisconnFrame);\n this.myDisconnFrame = null;\n }\n\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n }\n\n /**\n * Triggered when this transport is closed\n */\n private onClosed_() {\n if (!this.isClosed_) {\n this.log_('Longpoll is closing itself');\n this.shutdown_();\n\n if (this.onDisconnect_) {\n this.onDisconnect_(this.everConnected_);\n this.onDisconnect_ = null;\n }\n }\n }\n\n /**\n * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\n * that we've left.\n */\n close() {\n if (!this.isClosed_) {\n this.log_('Longpoll is being closed.');\n this.shutdown_();\n }\n }\n\n /**\n * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\n * broken into chunks (since URLs have a small maximum length).\n * @param data - The JSON data to transmit.\n */\n send(data: {}) {\n const dataStr = stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n\n //first, lets get the base64-encoded data\n const base64data = base64Encode(dataStr);\n\n //We can only fit a certain amount in each URL, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\n\n //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\n //of segments so that we can reassemble the packet on the server.\n for (let i = 0; i < dataSegs.length; i++) {\n this.scriptTagHolder.enqueueSegment(\n this.curSegmentNum,\n dataSegs.length,\n dataSegs[i]\n );\n this.curSegmentNum++;\n }\n }\n\n /**\n * This is how we notify the server that we're leaving.\n * We aren't able to send requests with DHTML on a window close event, but we can\n * trigger XHR requests in some browsers (everything but Opera basically).\n */\n addDisconnectPingFrame(id: string, pw: string) {\n if (isNodeSdk()) {\n return;\n }\n this.myDisconnFrame = document.createElement('iframe');\n const urlParams: { [k: string]: string } = {};\n urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;\n this.myDisconnFrame.src = this.urlFn(urlParams);\n this.myDisconnFrame.style.display = 'none';\n\n document.body.appendChild(this.myDisconnFrame);\n }\n\n /**\n * Used to track the bytes received by this client\n */\n private incrementIncomingBytes_(args: unknown) {\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\n const bytesReceived = stringify(args).length;\n this.bytesReceived += bytesReceived;\n this.stats_.incrementCounter('bytes_received', bytesReceived);\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport interface IFrameElement extends HTMLIFrameElement {\n doc: Document;\n}\n\n/*********************************************************************************************\n * A wrapper around an iframe that is used as a long-polling script holder.\n *********************************************************************************************/\nexport class FirebaseIFrameScriptHolder {\n //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\n //problems in some browsers.\n outstandingRequests = new Set();\n\n //A queue of the pending segments waiting for transmission to the server.\n pendingSegs: Array<{ seg: number; ts: number; d: unknown }> = [];\n\n //A serial number. We use this for two things:\n // 1) A way to ensure the browser doesn't cache responses to polls\n // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\n // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\n // JSONP code in the order it was added to the iframe.\n currentSerial = Math.floor(Math.random() * 100000000);\n\n // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\n // incoming data from the server that we're waiting for).\n sendNewPolls = true;\n\n uniqueCallbackIdentifier: number;\n myIFrame: IFrameElement;\n alive: boolean;\n myID: string;\n myPW: string;\n commandCB: (command: string, ...args: unknown[]) => void;\n onMessageCB: (...args: unknown[]) => void;\n\n /**\n * @param commandCB - The callback to be called when control commands are received from the server.\n * @param onMessageCB - The callback to be triggered when responses arrive from the server.\n * @param onDisconnect - The callback to be triggered when this tag holder is closed\n * @param urlFn - A function that provides the URL of the endpoint to send data to.\n */\n constructor(\n commandCB: (command: string, ...args: unknown[]) => void,\n onMessageCB: (...args: unknown[]) => void,\n public onDisconnect: () => void,\n public urlFn: (a: object) => string\n ) {\n if (!isNodeSdk()) {\n //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\n //iframes where we put the long-polling script tags. We have two callbacks:\n // 1) Command Callback - Triggered for control issues, like starting a connection.\n // 2) Message Callback - Triggered when new data arrives.\n this.uniqueCallbackIdentifier = LUIDGenerator();\n window[\n FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier\n ] = commandCB;\n window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =\n onMessageCB;\n\n //Create an iframe for us to add script tags to.\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\n\n // Set the iframe's contents.\n let script = '';\n // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\n // for ie9, but ie8 needs to do it again in the document itself.\n if (\n this.myIFrame.src &&\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:'\n ) {\n const currentDomain = document.domain;\n script = '';\n }\n const iframeContents = '' + script + '';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n } catch (e) {\n log('frame writing exception');\n if (e.stack) {\n log(e.stack);\n }\n log(e);\n }\n } else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n\n /**\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\n * actually use.\n */\n private static createIFrame_(): IFrameElement {\n const iframe = document.createElement('iframe') as IFrameElement;\n iframe.style.display = 'none';\n\n // This is necessary in order to initialize the document inside the iframe\n if (document.body) {\n document.body.appendChild(iframe);\n try {\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n const a = iframe.contentWindow.document;\n if (!a) {\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n log('No IE domain setting required');\n }\n } catch (e) {\n const domain = document.domain;\n iframe.src =\n \"javascript:void((function(){document.open();document.domain='\" +\n domain +\n \"';document.close();})())\";\n }\n } else {\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n // never gets hit.\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n }\n\n // Get the document of the iframe in a browser-specific way.\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n } else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else if ((iframe as any).document) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n iframe.doc = (iframe as any).document; //others?\n }\n\n return iframe;\n }\n\n /**\n * Cancel all outstanding queries and remove the frame.\n */\n close() {\n //Mark this iframe as dead, so no new requests are sent.\n this.alive = false;\n\n if (this.myIFrame) {\n //We have to actually remove all of the html inside this iframe before removing it from the\n //window, or IE will continue loading and executing the script tags we've already added, which\n //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.\n this.myIFrame.doc.body.textContent = '';\n setTimeout(() => {\n if (this.myIFrame !== null) {\n document.body.removeChild(this.myIFrame);\n this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n\n // Protect from being called recursively.\n const onDisconnect = this.onDisconnect;\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\n }\n\n /**\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\n * @param id - The ID of this connection\n * @param pw - The password for this connection\n */\n startLongPoll(id: string, pw: string) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true;\n\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n while (this.newRequest_()) {}\n }\n\n /**\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\n * too many outstanding requests and we are still alive.\n *\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\n * needed.\n */\n private newRequest_() {\n // We keep one outstanding request open all the time to receive data, but if we need to send data\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\n // close the old request.\n if (\n this.alive &&\n this.sendNewPolls &&\n this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)\n ) {\n //construct our url\n this.currentSerial++;\n const urlParams: { [k: string]: string | number } = {};\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n let theURL = this.urlFn(urlParams);\n //Now add as much data as we can.\n let curDataString = '';\n let i = 0;\n\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n const nextSeg = this.pendingSegs[0];\n if (\n (nextSeg.d as unknown[]).length +\n SEG_HEADER_SIZE +\n curDataString.length <=\n MAX_URL_DATA_SIZE\n ) {\n //great, the segment will fit. Lets append it.\n const theSeg = this.pendingSegs.shift();\n curDataString =\n curDataString +\n '&' +\n FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n i +\n '=' +\n theSeg.seg +\n '&' +\n FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n i +\n '=' +\n theSeg.ts +\n '&' +\n FIREBASE_LONGPOLL_DATA_PARAM +\n i +\n '=' +\n theSeg.d;\n i++;\n } else {\n break;\n }\n }\n\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Queue a packet for transmission to the server.\n * @param segnum - A sequential id for this packet segment used for reassembly\n * @param totalsegs - The total number of segments in this packet\n * @param data - The data for this segment.\n */\n enqueueSegment(segnum: number, totalsegs: number, data: unknown) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n\n //send the data immediately if there isn't already data being transmitted, unless\n //startLongPoll hasn't been called yet.\n if (this.alive) {\n this.newRequest_();\n }\n }\n\n /**\n * Add a script tag for a regular long-poll request.\n * @param url - The URL of the script tag.\n * @param serial - The serial number of the request.\n */\n private addLongPollTag_(url: string, serial: number) {\n //remember that we sent this request.\n this.outstandingRequests.add(serial);\n\n const doNewRequest = () => {\n this.outstandingRequests.delete(serial);\n this.newRequest_();\n };\n\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n const keepaliveTimeout = setTimeout(\n doNewRequest,\n Math.floor(KEEPALIVE_REQUEST_INTERVAL)\n );\n\n const readyStateCB = () => {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout);\n\n // Trigger a new request so we can continue receiving data.\n doNewRequest();\n };\n\n this.addTag(url, readyStateCB);\n }\n\n /**\n * Add an arbitrary script tag to the iframe.\n * @param url - The URL for the script tag source.\n * @param loadCB - A callback to be triggered once the script has loaded.\n */\n addTag(url: string, loadCB: () => void) {\n if (isNodeSdk()) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any).doNodeLongPoll(url, loadCB);\n } else {\n setTimeout(() => {\n try {\n // if we're already closed, don't add this poll\n if (!this.sendNewPolls) {\n return;\n }\n const newScript = this.myIFrame.doc.createElement('script');\n newScript.type = 'text/javascript';\n newScript.async = true;\n newScript.src = url;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n newScript.onload = (newScript as any).onreadystatechange =\n function () {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const rstate = (newScript as any).readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n newScript.onload = (newScript as any).onreadystatechange = null;\n if (newScript.parentNode) {\n newScript.parentNode.removeChild(newScript);\n }\n loadCB();\n }\n };\n newScript.onerror = () => {\n log('Long-poll script failed to load: ' + url);\n this.sendNewPolls = false;\n this.close();\n };\n this.myIFrame.doc.body.appendChild(newScript);\n } catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../core/RepoInfo';\nimport { warn } from '../core/util/util';\n\nimport { BrowserPollConnection } from './BrowserPollConnection';\nimport { TransportConstructor } from './Transport';\nimport { WebSocketConnection } from './WebSocketConnection';\n\n/**\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\n * lifecycle.\n *\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\n * they are available.\n */\nexport class TransportManager {\n private transports_: TransportConstructor[];\n\n // Keeps track of whether the TransportManager has already chosen a transport to use\n static globalTransportInitialized_ = false;\n\n static get ALL_TRANSPORTS() {\n return [BrowserPollConnection, WebSocketConnection];\n }\n\n /**\n * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after\n * TransportManager has already set up transports_\n */\n static get IS_TRANSPORT_INITIALIZED() {\n return this.globalTransportInitialized_;\n }\n\n /**\n * @param repoInfo - Metadata around the namespace we're connecting to\n */\n constructor(repoInfo: RepoInfo) {\n this.initTransports_(repoInfo);\n }\n\n private initTransports_(repoInfo: RepoInfo) {\n const isWebSocketsAvailable: boolean =\n WebSocketConnection && WebSocketConnection['isAvailable']();\n let isSkipPollConnection =\n isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();\n\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable) {\n warn(\n \"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\"\n );\n }\n\n isSkipPollConnection = true;\n }\n\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection];\n } else {\n const transports = (this.transports_ = [] as TransportConstructor[]);\n for (const transport of TransportManager.ALL_TRANSPORTS) {\n if (transport && transport['isAvailable']()) {\n transports.push(transport);\n }\n }\n TransportManager.globalTransportInitialized_ = true;\n }\n }\n\n /**\n * @returns The constructor for the initial transport to use\n */\n initialTransport(): TransportConstructor {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n } else {\n throw new Error('No transports available');\n }\n }\n\n /**\n * @returns The constructor for the next transport, or null\n */\n upgradeTransport(): TransportConstructor | null {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n } else {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../core/RepoInfo';\nimport { PersistentStorage } from '../core/storage/storage';\nimport { Indexable } from '../core/util/misc';\nimport {\n error,\n logWrapper,\n requireKey,\n setTimeoutNonBlocking,\n warn\n} from '../core/util/util';\n\nimport { PROTOCOL_VERSION } from './Constants';\nimport { Transport, TransportConstructor } from './Transport';\nimport { TransportManager } from './TransportManager';\n\n// Abort upgrade attempt if it takes longer than 60s.\nconst UPGRADE_TIMEOUT = 60000;\n\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\nconst DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\n\n// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\n// but we've sent/received enough bytes, we don't cancel the connection.\nconst BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\nconst BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\n\nconst enum RealtimeState {\n CONNECTING,\n CONNECTED,\n DISCONNECTED\n}\n\nconst MESSAGE_TYPE = 't';\nconst MESSAGE_DATA = 'd';\nconst CONTROL_SHUTDOWN = 's';\nconst CONTROL_RESET = 'r';\nconst CONTROL_ERROR = 'e';\nconst CONTROL_PONG = 'o';\nconst SWITCH_ACK = 'a';\nconst END_TRANSMISSION = 'n';\nconst PING = 'p';\n\nconst SERVER_HELLO = 'h';\n\n/**\n * Creates a new real-time connection to the server using whichever method works\n * best in the current browser.\n */\nexport class Connection {\n connectionCount = 0;\n pendingDataMessages: unknown[] = [];\n sessionId: string;\n\n private conn_: Transport;\n private healthyTimeout_: number;\n private isHealthy_: boolean;\n private log_: (...args: unknown[]) => void;\n private primaryResponsesRequired_: number;\n private rx_: Transport;\n private secondaryConn_: Transport;\n private secondaryResponsesRequired_: number;\n private state_ = RealtimeState.CONNECTING;\n private transportManager_: TransportManager;\n private tx_: Transport;\n\n /**\n * @param id - an id for this connection\n * @param repoInfo_ - the info for the endpoint to connect to\n * @param applicationId_ - the Firebase App ID for this project\n * @param appCheckToken_ - The App Check Token for this device.\n * @param authToken_ - The auth token for this session.\n * @param onMessage_ - the callback to be triggered when a server-push message arrives\n * @param onReady_ - the callback to be triggered when this connection is ready to send messages.\n * @param onDisconnect_ - the callback to be triggered when a connection was lost\n * @param onKill_ - the callback to be triggered when this connection has permanently shut down.\n * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\n */\n constructor(\n public id: string,\n private repoInfo_: RepoInfo,\n private applicationId_: string | undefined,\n private appCheckToken_: string | undefined,\n private authToken_: string | undefined,\n private onMessage_: (a: {}) => void,\n private onReady_: (a: number, b: string) => void,\n private onDisconnect_: () => void,\n private onKill_: (a: string) => void,\n public lastSessionId?: string\n ) {\n this.log_ = logWrapper('c:' + this.id + ':');\n this.transportManager_ = new TransportManager(repoInfo_);\n this.log_('Connection created');\n this.start_();\n }\n\n /**\n * Starts a connection attempt\n */\n private start_(): void {\n const conn = this.transportManager_.initialTransport();\n this.conn_ = new conn(\n this.nextTransportId_(),\n this.repoInfo_,\n this.applicationId_,\n this.appCheckToken_,\n this.authToken_,\n null,\n this.lastSessionId\n );\n\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\n\n const onMessageReceived = this.connReceiver_(this.conn_);\n const onConnectionLost = this.disconnReceiver_(this.conn_);\n this.tx_ = this.conn_;\n this.rx_ = this.conn_;\n this.secondaryConn_ = null;\n this.isHealthy_ = false;\n\n /*\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\n * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\n * still have the context of your originating frame.\n */\n setTimeout(() => {\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\n this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);\n }, Math.floor(0));\n\n const healthyTimeoutMS = conn['healthyTimeout'] || 0;\n if (healthyTimeoutMS > 0) {\n this.healthyTimeout_ = setTimeoutNonBlocking(() => {\n this.healthyTimeout_ = null;\n if (!this.isHealthy_) {\n if (\n this.conn_ &&\n this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE\n ) {\n this.log_(\n 'Connection exceeded healthy timeout but has received ' +\n this.conn_.bytesReceived +\n ' bytes. Marking connection healthy.'\n );\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n } else if (\n this.conn_ &&\n this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE\n ) {\n this.log_(\n 'Connection exceeded healthy timeout but has sent ' +\n this.conn_.bytesSent +\n ' bytes. Leaving connection alive.'\n );\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\n // the server.\n } else {\n this.log_('Closing unhealthy connection after timeout.');\n this.close();\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(healthyTimeoutMS)) as any;\n }\n }\n\n private nextTransportId_(): string {\n return 'c:' + this.id + ':' + this.connectionCount++;\n }\n\n private disconnReceiver_(conn) {\n return everConnected => {\n if (conn === this.conn_) {\n this.onConnectionLost_(everConnected);\n } else if (conn === this.secondaryConn_) {\n this.log_('Secondary connection lost.');\n this.onSecondaryConnectionLost_();\n } else {\n this.log_('closing an old connection');\n }\n };\n }\n\n private connReceiver_(conn: Transport) {\n return (message: Indexable) => {\n if (this.state_ !== RealtimeState.DISCONNECTED) {\n if (conn === this.rx_) {\n this.onPrimaryMessageReceived_(message);\n } else if (conn === this.secondaryConn_) {\n this.onSecondaryMessageReceived_(message);\n } else {\n this.log_('message on old connection');\n }\n }\n };\n }\n\n /**\n * @param dataMsg - An arbitrary data message to be sent to the server\n */\n sendRequest(dataMsg: object) {\n // wrap in a data message envelope and send it on\n const msg = { t: 'd', d: dataMsg };\n this.sendData_(msg);\n }\n\n tryCleanupConnection() {\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\n this.log_(\n 'cleaning up and promoting a connection: ' + this.secondaryConn_.connId\n );\n this.conn_ = this.secondaryConn_;\n this.secondaryConn_ = null;\n // the server will shutdown the old connection\n }\n }\n\n private onSecondaryControl_(controlData: { [k: string]: unknown }) {\n if (MESSAGE_TYPE in controlData) {\n const cmd = controlData[MESSAGE_TYPE] as string;\n if (cmd === SWITCH_ACK) {\n this.upgradeIfSecondaryHealthy_();\n } else if (cmd === CONTROL_RESET) {\n // Most likely the session wasn't valid. Abandon the switch attempt\n this.log_('Got a reset on secondary, closing it');\n this.secondaryConn_.close();\n // If we were already using this connection for something, than we need to fully close\n if (\n this.tx_ === this.secondaryConn_ ||\n this.rx_ === this.secondaryConn_\n ) {\n this.close();\n }\n } else if (cmd === CONTROL_PONG) {\n this.log_('got pong on secondary.');\n this.secondaryResponsesRequired_--;\n this.upgradeIfSecondaryHealthy_();\n }\n }\n }\n\n private onSecondaryMessageReceived_(parsedData: Indexable) {\n const layer: string = requireKey('t', parsedData) as string;\n const data: unknown = requireKey('d', parsedData);\n if (layer === 'c') {\n this.onSecondaryControl_(data as Indexable);\n } else if (layer === 'd') {\n // got a data message, but we're still second connection. Need to buffer it up\n this.pendingDataMessages.push(data);\n } else {\n throw new Error('Unknown protocol layer: ' + layer);\n }\n }\n\n private upgradeIfSecondaryHealthy_() {\n if (this.secondaryResponsesRequired_ <= 0) {\n this.log_('Secondary connection is healthy.');\n this.isHealthy_ = true;\n this.secondaryConn_.markConnectionHealthy();\n this.proceedWithUpgrade_();\n } else {\n // Send a ping to make sure the connection is healthy.\n this.log_('sending ping on secondary.');\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\n }\n }\n\n private proceedWithUpgrade_() {\n // tell this connection to consider itself open\n this.secondaryConn_.start();\n // send ack\n this.log_('sending client ack on secondary');\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\n\n // send end packet on primary transport, switch to sending on this one\n // can receive on this one, buffer responses until end received on primary transport\n this.log_('Ending transmission on primary');\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\n this.tx_ = this.secondaryConn_;\n\n this.tryCleanupConnection();\n }\n\n private onPrimaryMessageReceived_(parsedData: { [k: string]: unknown }) {\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\n const layer: string = requireKey('t', parsedData) as string;\n const data: unknown = requireKey('d', parsedData);\n if (layer === 'c') {\n this.onControl_(data as { [k: string]: unknown });\n } else if (layer === 'd') {\n this.onDataMessage_(data);\n }\n }\n\n private onDataMessage_(message: unknown) {\n this.onPrimaryResponse_();\n\n // We don't do anything with data messages, just kick them up a level\n this.onMessage_(message);\n }\n\n private onPrimaryResponse_() {\n if (!this.isHealthy_) {\n this.primaryResponsesRequired_--;\n if (this.primaryResponsesRequired_ <= 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n }\n }\n }\n\n private onControl_(controlData: { [k: string]: unknown }) {\n const cmd: string = requireKey(MESSAGE_TYPE, controlData) as string;\n if (MESSAGE_DATA in controlData) {\n const payload = controlData[MESSAGE_DATA];\n if (cmd === SERVER_HELLO) {\n const handshakePayload = {\n ...(payload as {\n ts: number;\n v: string;\n h: string;\n s: string;\n })\n };\n if (this.repoInfo_.isUsingEmulator) {\n // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes.\n handshakePayload.h = this.repoInfo_.host;\n }\n this.onHandshake_(handshakePayload);\n } else if (cmd === END_TRANSMISSION) {\n this.log_('recvd end transmission on primary');\n this.rx_ = this.secondaryConn_;\n for (let i = 0; i < this.pendingDataMessages.length; ++i) {\n this.onDataMessage_(this.pendingDataMessages[i]);\n }\n this.pendingDataMessages = [];\n this.tryCleanupConnection();\n } else if (cmd === CONTROL_SHUTDOWN) {\n // This was previously the 'onKill' callback passed to the lower-level connection\n // payload in this case is the reason for the shutdown. Generally a human-readable error\n this.onConnectionShutdown_(payload as string);\n } else if (cmd === CONTROL_RESET) {\n // payload in this case is the host we should contact\n this.onReset_(payload as string);\n } else if (cmd === CONTROL_ERROR) {\n error('Server Error: ' + payload);\n } else if (cmd === CONTROL_PONG) {\n this.log_('got pong on primary.');\n this.onPrimaryResponse_();\n this.sendPingOnPrimaryIfNecessary_();\n } else {\n error('Unknown control packet command: ' + cmd);\n }\n }\n }\n\n /**\n * @param handshake - The handshake data returned from the server\n */\n private onHandshake_(handshake: {\n ts: number;\n v: string;\n h: string;\n s: string;\n }): void {\n const timestamp = handshake.ts;\n const version = handshake.v;\n const host = handshake.h;\n this.sessionId = handshake.s;\n this.repoInfo_.host = host;\n // if we've already closed the connection, then don't bother trying to progress further\n if (this.state_ === RealtimeState.CONNECTING) {\n this.conn_.start();\n this.onConnectionEstablished_(this.conn_, timestamp);\n if (PROTOCOL_VERSION !== version) {\n warn('Protocol version mismatch detected');\n }\n // TODO: do we want to upgrade? when? maybe a delay?\n this.tryStartUpgrade_();\n }\n }\n\n private tryStartUpgrade_() {\n const conn = this.transportManager_.upgradeTransport();\n if (conn) {\n this.startUpgrade_(conn);\n }\n }\n\n private startUpgrade_(conn: TransportConstructor) {\n this.secondaryConn_ = new conn(\n this.nextTransportId_(),\n this.repoInfo_,\n this.applicationId_,\n this.appCheckToken_,\n this.authToken_,\n this.sessionId\n );\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.secondaryResponsesRequired_ =\n conn['responsesRequiredToBeHealthy'] || 0;\n\n const onMessage = this.connReceiver_(this.secondaryConn_);\n const onDisconnect = this.disconnReceiver_(this.secondaryConn_);\n this.secondaryConn_.open(onMessage, onDisconnect);\n\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\n setTimeoutNonBlocking(() => {\n if (this.secondaryConn_) {\n this.log_('Timed out trying to upgrade.');\n this.secondaryConn_.close();\n }\n }, Math.floor(UPGRADE_TIMEOUT));\n }\n\n private onReset_(host: string) {\n this.log_('Reset packet received. New host: ' + host);\n this.repoInfo_.host = host;\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\n // We don't currently support resets after the connection has already been established\n if (this.state_ === RealtimeState.CONNECTED) {\n this.close();\n } else {\n // Close whatever connections we have open and start again.\n this.closeConnections_();\n this.start_();\n }\n }\n\n private onConnectionEstablished_(conn: Transport, timestamp: number) {\n this.log_('Realtime connection established.');\n this.conn_ = conn;\n this.state_ = RealtimeState.CONNECTED;\n\n if (this.onReady_) {\n this.onReady_(timestamp, this.sessionId);\n this.onReady_ = null;\n }\n\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\n // send some pings.\n if (this.primaryResponsesRequired_ === 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n } else {\n setTimeoutNonBlocking(() => {\n this.sendPingOnPrimaryIfNecessary_();\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\n }\n }\n\n private sendPingOnPrimaryIfNecessary_() {\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\n if (!this.isHealthy_ && this.state_ === RealtimeState.CONNECTED) {\n this.log_('sending ping on primary.');\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\n }\n }\n\n private onSecondaryConnectionLost_() {\n const conn = this.secondaryConn_;\n this.secondaryConn_ = null;\n if (this.tx_ === conn || this.rx_ === conn) {\n // we are relying on this connection already in some capacity. Therefore, a failure is real\n this.close();\n }\n }\n\n /**\n * @param everConnected - Whether or not the connection ever reached a server. Used to determine if\n * we should flush the host cache\n */\n private onConnectionLost_(everConnected: boolean) {\n this.conn_ = null;\n\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\n if (!everConnected && this.state_ === RealtimeState.CONNECTING) {\n this.log_('Realtime connection failed.');\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\n if (this.repoInfo_.isCacheableHost()) {\n PersistentStorage.remove('host:' + this.repoInfo_.host);\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\n this.repoInfo_.internalHost = this.repoInfo_.host;\n }\n } else if (this.state_ === RealtimeState.CONNECTED) {\n this.log_('Realtime connection lost.');\n }\n\n this.close();\n }\n\n private onConnectionShutdown_(reason: string) {\n this.log_('Connection shutdown command received. Shutting down...');\n\n if (this.onKill_) {\n this.onKill_(reason);\n this.onKill_ = null;\n }\n\n // We intentionally don't want to fire onDisconnect (kill is a different case),\n // so clear the callback.\n this.onDisconnect_ = null;\n\n this.close();\n }\n\n private sendData_(data: object) {\n if (this.state_ !== RealtimeState.CONNECTED) {\n throw 'Connection is not connected';\n } else {\n this.tx_.send(data);\n }\n }\n\n /**\n * Cleans up this connection, calling the appropriate callbacks\n */\n close() {\n if (this.state_ !== RealtimeState.DISCONNECTED) {\n this.log_('Closing realtime connection.');\n this.state_ = RealtimeState.DISCONNECTED;\n\n this.closeConnections_();\n\n if (this.onDisconnect_) {\n this.onDisconnect_();\n this.onDisconnect_ = null;\n }\n }\n }\n\n private closeConnections_() {\n this.log_('Shutting down all connections');\n if (this.conn_) {\n this.conn_.close();\n this.conn_ = null;\n }\n\n if (this.secondaryConn_) {\n this.secondaryConn_.close();\n this.secondaryConn_ = null;\n }\n\n if (this.healthyTimeout_) {\n clearTimeout(this.healthyTimeout_);\n this.healthyTimeout_ = null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QueryContext } from './view/EventRegistration';\n\n/**\n * Interface defining the set of actions that can be performed against the Firebase server\n * (basically corresponds to our wire protocol).\n *\n * @interface\n */\nexport abstract class ServerActions {\n abstract listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ): void;\n\n /**\n * Remove a listen.\n */\n abstract unlisten(query: QueryContext, tag: number | null): void;\n\n /**\n * Get the server value satisfying this query.\n */\n abstract get(query: QueryContext): Promise;\n\n put(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void,\n hash?: string\n ) {}\n\n merge(\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {}\n\n /**\n * Refreshes the auth token for the current connection.\n * @param token - The authentication token\n */\n refreshAuthToken(token: string) {}\n\n /**\n * Refreshes the app check token for the current connection.\n * @param token The app check token\n */\n refreshAppCheckToken(token: string) {}\n\n onDisconnectPut(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n onDisconnectMerge(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n onDisconnectCancel(\n pathString: string,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n reportStats(stats: { [k: string]: unknown }) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\n/**\n * Base class to be used if you want to emit events. Call the constructor with\n * the set of allowed event names.\n */\nexport abstract class EventEmitter {\n private listeners_: {\n [eventType: string]: Array<{\n callback(...args: unknown[]): void;\n context: unknown;\n }>;\n } = {};\n\n constructor(private allowedEvents_: string[]) {\n assert(\n Array.isArray(allowedEvents_) && allowedEvents_.length > 0,\n 'Requires a non-empty array'\n );\n }\n\n /**\n * To be overridden by derived classes in order to fire an initial event when\n * somebody subscribes for data.\n *\n * @returns {Array.<*>} Array of parameters to trigger initial event with.\n */\n abstract getInitialEvent(eventType: string): unknown[];\n\n /**\n * To be called by derived classes to trigger events.\n */\n protected trigger(eventType: string, ...varArgs: unknown[]) {\n if (Array.isArray(this.listeners_[eventType])) {\n // Clone the list, since callbacks could add/remove listeners.\n const listeners = [...this.listeners_[eventType]];\n\n for (let i = 0; i < listeners.length; i++) {\n listeners[i].callback.apply(listeners[i].context, varArgs);\n }\n }\n }\n\n on(eventType: string, callback: (a: unknown) => void, context: unknown) {\n this.validateEventType_(eventType);\n this.listeners_[eventType] = this.listeners_[eventType] || [];\n this.listeners_[eventType].push({ callback, context });\n\n const eventData = this.getInitialEvent(eventType);\n if (eventData) {\n callback.apply(context, eventData);\n }\n }\n\n off(eventType: string, callback: (a: unknown) => void, context: unknown) {\n this.validateEventType_(eventType);\n const listeners = this.listeners_[eventType] || [];\n for (let i = 0; i < listeners.length; i++) {\n if (\n listeners[i].callback === callback &&\n (!context || context === listeners[i].context)\n ) {\n listeners.splice(i, 1);\n return;\n }\n }\n }\n\n private validateEventType_(eventType: string) {\n assert(\n this.allowedEvents_.find(et => {\n return et === eventType;\n }),\n 'Unknown event: ' + eventType\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, isMobileCordova } from '@firebase/util';\n\nimport { EventEmitter } from './EventEmitter';\n\n/**\n * Monitors online state (as reported by window.online/offline events).\n *\n * The expectation is that this could have many false positives (thinks we are online\n * when we're not), but no false negatives. So we can safely use it to determine when\n * we definitely cannot reach the internet.\n */\nexport class OnlineMonitor extends EventEmitter {\n private online_ = true;\n\n static getInstance() {\n return new OnlineMonitor();\n }\n\n constructor() {\n super(['online']);\n\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\n // It would seem that the 'online' event does not always fire consistently. So we disable it\n // for Cordova.\n if (\n typeof window !== 'undefined' &&\n typeof window.addEventListener !== 'undefined' &&\n !isMobileCordova()\n ) {\n window.addEventListener(\n 'online',\n () => {\n if (!this.online_) {\n this.online_ = true;\n this.trigger('online', true);\n }\n },\n false\n );\n\n window.addEventListener(\n 'offline',\n () => {\n if (this.online_) {\n this.online_ = false;\n this.trigger('online', false);\n }\n },\n false\n );\n }\n }\n\n getInitialEvent(eventType: string): boolean[] {\n assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n }\n\n currentlyOnline(): boolean {\n return this.online_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { stringLength } from '@firebase/util';\n\nimport { nameCompare } from './util';\n\n/** Maximum key depth. */\nconst MAX_PATH_DEPTH = 32;\n\n/** Maximum number of (UTF8) bytes in a Firebase path. */\nconst MAX_PATH_LENGTH_BYTES = 768;\n\n/**\n * An immutable object representing a parsed path. It's immutable so that you\n * can pass them around to other functions without worrying about them changing\n * it.\n */\n\nexport class Path {\n pieces_: string[];\n pieceNum_: number;\n\n /**\n * @param pathOrString - Path string to parse, or another path, or the raw\n * tokens array\n */\n constructor(pathOrString: string | string[], pieceNum?: number) {\n if (pieceNum === void 0) {\n this.pieces_ = (pathOrString as string).split('/');\n\n // Remove empty pieces.\n let copyTo = 0;\n for (let i = 0; i < this.pieces_.length; i++) {\n if (this.pieces_[i].length > 0) {\n this.pieces_[copyTo] = this.pieces_[i];\n copyTo++;\n }\n }\n this.pieces_.length = copyTo;\n\n this.pieceNum_ = 0;\n } else {\n this.pieces_ = pathOrString as string[];\n this.pieceNum_ = pieceNum;\n }\n }\n\n toString(): string {\n let pathString = '';\n for (let i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '') {\n pathString += '/' + this.pieces_[i];\n }\n }\n\n return pathString || '/';\n }\n}\n\nexport function newEmptyPath(): Path {\n return new Path('');\n}\n\nexport function pathGetFront(path: Path): string | null {\n if (path.pieceNum_ >= path.pieces_.length) {\n return null;\n }\n\n return path.pieces_[path.pieceNum_];\n}\n\n/**\n * @returns The number of segments in this path\n */\nexport function pathGetLength(path: Path): number {\n return path.pieces_.length - path.pieceNum_;\n}\n\nexport function pathPopFront(path: Path): Path {\n let pieceNum = path.pieceNum_;\n if (pieceNum < path.pieces_.length) {\n pieceNum++;\n }\n return new Path(path.pieces_, pieceNum);\n}\n\nexport function pathGetBack(path: Path): string | null {\n if (path.pieceNum_ < path.pieces_.length) {\n return path.pieces_[path.pieces_.length - 1];\n }\n\n return null;\n}\n\nexport function pathToUrlEncodedString(path: Path): string {\n let pathString = '';\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\n if (path.pieces_[i] !== '') {\n pathString += '/' + encodeURIComponent(String(path.pieces_[i]));\n }\n }\n\n return pathString || '/';\n}\n\n/**\n * Shallow copy of the parts of the path.\n *\n */\nexport function pathSlice(path: Path, begin: number = 0): string[] {\n return path.pieces_.slice(path.pieceNum_ + begin);\n}\n\nexport function pathParent(path: Path): Path | null {\n if (path.pieceNum_ >= path.pieces_.length) {\n return null;\n }\n\n const pieces = [];\n for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {\n pieces.push(path.pieces_[i]);\n }\n\n return new Path(pieces, 0);\n}\n\nexport function pathChild(path: Path, childPathObj: string | Path): Path {\n const pieces = [];\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\n pieces.push(path.pieces_[i]);\n }\n\n if (childPathObj instanceof Path) {\n for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\n pieces.push(childPathObj.pieces_[i]);\n }\n } else {\n const childPieces = childPathObj.split('/');\n for (let i = 0; i < childPieces.length; i++) {\n if (childPieces[i].length > 0) {\n pieces.push(childPieces[i]);\n }\n }\n }\n\n return new Path(pieces, 0);\n}\n\n/**\n * @returns True if there are no segments in this path\n */\nexport function pathIsEmpty(path: Path): boolean {\n return path.pieceNum_ >= path.pieces_.length;\n}\n\n/**\n * @returns The path from outerPath to innerPath\n */\nexport function newRelativePath(outerPath: Path, innerPath: Path): Path {\n const outer = pathGetFront(outerPath),\n inner = pathGetFront(innerPath);\n if (outer === null) {\n return innerPath;\n } else if (outer === inner) {\n return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));\n } else {\n throw new Error(\n 'INTERNAL ERROR: innerPath (' +\n innerPath +\n ') is not within ' +\n 'outerPath (' +\n outerPath +\n ')'\n );\n }\n}\n\n/**\n * @returns -1, 0, 1 if left is less, equal, or greater than the right.\n */\nexport function pathCompare(left: Path, right: Path): number {\n const leftKeys = pathSlice(left, 0);\n const rightKeys = pathSlice(right, 0);\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\n const cmp = nameCompare(leftKeys[i], rightKeys[i]);\n if (cmp !== 0) {\n return cmp;\n }\n }\n if (leftKeys.length === rightKeys.length) {\n return 0;\n }\n return leftKeys.length < rightKeys.length ? -1 : 1;\n}\n\n/**\n * @returns true if paths are the same.\n */\nexport function pathEquals(path: Path, other: Path): boolean {\n if (pathGetLength(path) !== pathGetLength(other)) {\n return false;\n }\n\n for (\n let i = path.pieceNum_, j = other.pieceNum_;\n i <= path.pieces_.length;\n i++, j++\n ) {\n if (path.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * @returns True if this path is a parent of (or the same as) other\n */\nexport function pathContains(path: Path, other: Path): boolean {\n let i = path.pieceNum_;\n let j = other.pieceNum_;\n if (pathGetLength(path) > pathGetLength(other)) {\n return false;\n }\n while (i < path.pieces_.length) {\n if (path.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n ++i;\n ++j;\n }\n return true;\n}\n\n/**\n * Dynamic (mutable) path used to count path lengths.\n *\n * This class is used to efficiently check paths for valid\n * length (in UTF8 bytes) and depth (used in path validation).\n *\n * Throws Error exception if path is ever invalid.\n *\n * The definition of a path always begins with '/'.\n */\nexport class ValidationPath {\n parts_: string[];\n /** Initialize to number of '/' chars needed in path. */\n byteLength_: number;\n\n /**\n * @param path - Initial Path.\n * @param errorPrefix_ - Prefix for any error messages.\n */\n constructor(path: Path, public errorPrefix_: string) {\n this.parts_ = pathSlice(path, 0);\n /** Initialize to number of '/' chars needed in path. */\n this.byteLength_ = Math.max(1, this.parts_.length);\n\n for (let i = 0; i < this.parts_.length; i++) {\n this.byteLength_ += stringLength(this.parts_[i]);\n }\n validationPathCheckValid(this);\n }\n}\n\nexport function validationPathPush(\n validationPath: ValidationPath,\n child: string\n): void {\n // Count the needed '/'\n if (validationPath.parts_.length > 0) {\n validationPath.byteLength_ += 1;\n }\n validationPath.parts_.push(child);\n validationPath.byteLength_ += stringLength(child);\n validationPathCheckValid(validationPath);\n}\n\nexport function validationPathPop(validationPath: ValidationPath): void {\n const last = validationPath.parts_.pop();\n validationPath.byteLength_ -= stringLength(last);\n // Un-count the previous '/'\n if (validationPath.parts_.length > 0) {\n validationPath.byteLength_ -= 1;\n }\n}\n\nfunction validationPathCheckValid(validationPath: ValidationPath): void {\n if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {\n throw new Error(\n validationPath.errorPrefix_ +\n 'has a key path longer than ' +\n MAX_PATH_LENGTH_BYTES +\n ' bytes (' +\n validationPath.byteLength_ +\n ').'\n );\n }\n if (validationPath.parts_.length > MAX_PATH_DEPTH) {\n throw new Error(\n validationPath.errorPrefix_ +\n 'path specified exceeds the maximum depth that can be written (' +\n MAX_PATH_DEPTH +\n ') or object contains a cycle ' +\n validationPathToErrorString(validationPath)\n );\n }\n}\n\n/**\n * String for use in error messages - uses '.' notation for path.\n */\nexport function validationPathToErrorString(\n validationPath: ValidationPath\n): string {\n if (validationPath.parts_.length === 0) {\n return '';\n }\n return \"in property '\" + validationPath.parts_.join('.') + \"'\";\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { EventEmitter } from './EventEmitter';\n\ndeclare const document: Document;\n\nexport class VisibilityMonitor extends EventEmitter {\n private visible_: boolean;\n\n static getInstance() {\n return new VisibilityMonitor();\n }\n\n constructor() {\n super(['visible']);\n let hidden: string;\n let visibilityChange: string;\n if (\n typeof document !== 'undefined' &&\n typeof document.addEventListener !== 'undefined'\n ) {\n if (typeof document['hidden'] !== 'undefined') {\n // Opera 12.10 and Firefox 18 and later support\n visibilityChange = 'visibilitychange';\n hidden = 'hidden';\n } else if (typeof document['mozHidden'] !== 'undefined') {\n visibilityChange = 'mozvisibilitychange';\n hidden = 'mozHidden';\n } else if (typeof document['msHidden'] !== 'undefined') {\n visibilityChange = 'msvisibilitychange';\n hidden = 'msHidden';\n } else if (typeof document['webkitHidden'] !== 'undefined') {\n visibilityChange = 'webkitvisibilitychange';\n hidden = 'webkitHidden';\n }\n }\n\n // Initially, we always assume we are visible. This ensures that in browsers\n // without page visibility support or in cases where we are never visible\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n // reconnects\n this.visible_ = true;\n\n if (visibilityChange) {\n document.addEventListener(\n visibilityChange,\n () => {\n const visible = !document[hidden];\n if (visible !== this.visible_) {\n this.visible_ = visible;\n this.trigger('visible', visible);\n }\n },\n false\n );\n }\n }\n\n getInitialEvent(eventType: string): boolean[] {\n assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n contains,\n Deferred,\n isEmpty,\n isMobileCordova,\n isNodeSdk,\n isReactNative,\n isValidFormat,\n safeGet,\n stringify,\n isAdmin\n} from '@firebase/util';\n\nimport { Connection } from '../realtime/Connection';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { OnlineMonitor } from './util/OnlineMonitor';\nimport { Path } from './util/Path';\nimport { error, log, logWrapper, warn, ObjectToUniqueKey } from './util/util';\nimport { VisibilityMonitor } from './util/VisibilityMonitor';\nimport { SDK_VERSION } from './version';\nimport { QueryContext } from './view/EventRegistration';\n\nconst RECONNECT_MIN_DELAY = 1000;\nconst RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\nconst RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\nconst RECONNECT_DELAY_MULTIPLIER = 1.3;\nconst RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\nconst SERVER_KILL_INTERRUPT_REASON = 'server_kill';\n\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\nconst INVALID_TOKEN_THRESHOLD = 3;\n\ninterface ListenSpec {\n onComplete(s: string, p?: unknown): void;\n\n hashFn(): string;\n\n query: QueryContext;\n tag: number | null;\n}\n\ninterface OnDisconnectRequest {\n pathString: string;\n action: string;\n data: unknown;\n onComplete?: (a: string, b: string) => void;\n}\n\ninterface OutstandingPut {\n action: string;\n request: object;\n queued?: boolean;\n onComplete: (a: string, b?: string) => void;\n}\n\ninterface OutstandingGet {\n request: object;\n onComplete: (response: { [k: string]: unknown }) => void;\n}\n\n/**\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\n *\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\n * in quotes to make sure the closure compiler does not minify them.\n */\nexport class PersistentConnection extends ServerActions {\n // Used for diagnostic logging.\n id = PersistentConnection.nextPersistentConnectionId_++;\n private log_ = logWrapper('p:' + this.id + ':');\n\n private interruptReasons_: { [reason: string]: boolean } = {};\n private readonly listens: Map<\n /* path */ string,\n Map\n > = new Map();\n private outstandingPuts_: OutstandingPut[] = [];\n private outstandingGets_: OutstandingGet[] = [];\n private outstandingPutCount_ = 0;\n private outstandingGetCount_ = 0;\n private onDisconnectRequestQueue_: OnDisconnectRequest[] = [];\n private connected_ = false;\n private reconnectDelay_ = RECONNECT_MIN_DELAY;\n private maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\n private securityDebugCallback_: ((a: object) => void) | null = null;\n lastSessionId: string | null = null;\n\n private establishConnectionTimer_: number | null = null;\n\n private visible_: boolean = false;\n\n // Before we get connected, we keep a queue of pending messages to send.\n private requestCBHash_: { [k: number]: (a: unknown) => void } = {};\n private requestNumber_ = 0;\n\n private realtime_: {\n sendRequest(a: object): void;\n close(): void;\n } | null = null;\n\n private authToken_: string | null = null;\n private appCheckToken_: string | null = null;\n private forceTokenRefresh_ = false;\n private invalidAuthTokenCount_ = 0;\n private invalidAppCheckTokenCount_ = 0;\n\n private firstConnection_ = true;\n private lastConnectionAttemptTime_: number | null = null;\n private lastConnectionEstablishedTime_: number | null = null;\n\n private static nextPersistentConnectionId_ = 0;\n\n /**\n * Counter for number of connections created. Mainly used for tagging in the logs\n */\n private static nextConnectionId_ = 0;\n\n /**\n * @param repoInfo_ - Data about the namespace we are connecting to\n * @param applicationId_ - The Firebase App ID for this project\n * @param onDataUpdate_ - A callback for new data from the server\n */\n constructor(\n private repoInfo_: RepoInfo,\n private applicationId_: string,\n private onDataUpdate_: (\n a: string,\n b: unknown,\n c: boolean,\n d: number | null\n ) => void,\n private onConnectStatus_: (a: boolean) => void,\n private onServerInfoUpdate_: (a: unknown) => void,\n private authTokenProvider_: AuthTokenProvider,\n private appCheckTokenProvider_: AppCheckTokenProvider,\n private authOverride_?: object | null\n ) {\n super();\n\n if (authOverride_ && !isNodeSdk()) {\n throw new Error(\n 'Auth override specified in options, but not supported on non Node.js platforms'\n );\n }\n\n VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);\n\n if (repoInfo_.host.indexOf('fblocal') === -1) {\n OnlineMonitor.getInstance().on('online', this.onOnline_, this);\n }\n }\n\n protected sendRequest(\n action: string,\n body: unknown,\n onResponse?: (a: unknown) => void\n ) {\n const curReqNum = ++this.requestNumber_;\n\n const msg = { r: curReqNum, a: action, b: body };\n this.log_(stringify(msg));\n assert(\n this.connected_,\n \"sendRequest call when we're not connected not allowed.\"\n );\n this.realtime_.sendRequest(msg);\n if (onResponse) {\n this.requestCBHash_[curReqNum] = onResponse;\n }\n }\n\n get(query: QueryContext): Promise {\n this.initConnection_();\n\n const deferred = new Deferred();\n const request = {\n p: query._path.toString(),\n q: query._queryObject\n };\n const outstandingGet = {\n action: 'g',\n request,\n onComplete: (message: { [k: string]: unknown }) => {\n const payload = message['d'] as string;\n if (message['s'] === 'ok') {\n deferred.resolve(payload);\n } else {\n deferred.reject(payload);\n }\n }\n };\n this.outstandingGets_.push(outstandingGet);\n this.outstandingGetCount_++;\n const index = this.outstandingGets_.length - 1;\n\n if (this.connected_) {\n this.sendGet_(index);\n }\n\n return deferred.promise;\n }\n\n listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ) {\n this.initConnection_();\n\n const queryId = query._queryIdentifier;\n const pathString = query._path.toString();\n this.log_('Listen called for ' + pathString + ' ' + queryId);\n if (!this.listens.has(pathString)) {\n this.listens.set(pathString, new Map());\n }\n assert(\n query._queryParams.isDefault() || !query._queryParams.loadsAllData(),\n 'listen() called for non-default but complete query'\n );\n assert(\n !this.listens.get(pathString)!.has(queryId),\n `listen() called twice for same path/queryId.`\n );\n const listenSpec: ListenSpec = {\n onComplete,\n hashFn: currentHashFn,\n query,\n tag\n };\n this.listens.get(pathString)!.set(queryId, listenSpec);\n\n if (this.connected_) {\n this.sendListen_(listenSpec);\n }\n }\n\n private sendGet_(index: number) {\n const get = this.outstandingGets_[index];\n this.sendRequest('g', get.request, (message: { [k: string]: unknown }) => {\n delete this.outstandingGets_[index];\n this.outstandingGetCount_--;\n if (this.outstandingGetCount_ === 0) {\n this.outstandingGets_ = [];\n }\n if (get.onComplete) {\n get.onComplete(message);\n }\n });\n }\n\n private sendListen_(listenSpec: ListenSpec) {\n const query = listenSpec.query;\n const pathString = query._path.toString();\n const queryId = query._queryIdentifier;\n this.log_('Listen on ' + pathString + ' for ' + queryId);\n const req: { [k: string]: unknown } = { /*path*/ p: pathString };\n\n const action = 'q';\n\n // Only bother to send query if it's non-default.\n if (listenSpec.tag) {\n req['q'] = query._queryObject;\n req['t'] = listenSpec.tag;\n }\n\n req[/*hash*/ 'h'] = listenSpec.hashFn();\n\n this.sendRequest(action, req, (message: { [k: string]: unknown }) => {\n const payload: unknown = message[/*data*/ 'd'];\n const status = message[/*status*/ 's'] as string;\n\n // print warnings in any case...\n PersistentConnection.warnOnListenWarnings_(payload, query);\n\n const currentListenSpec =\n this.listens.get(pathString) &&\n this.listens.get(pathString)!.get(queryId);\n // only trigger actions if the listen hasn't been removed and readded\n if (currentListenSpec === listenSpec) {\n this.log_('listen response', message);\n\n if (status !== 'ok') {\n this.removeListen_(pathString, queryId);\n }\n\n if (listenSpec.onComplete) {\n listenSpec.onComplete(status, payload);\n }\n }\n });\n }\n\n private static warnOnListenWarnings_(payload: unknown, query: QueryContext) {\n if (payload && typeof payload === 'object' && contains(payload, 'w')) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const warnings = safeGet(payload as any, 'w');\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\n const indexSpec =\n '\".indexOn\": \"' + query._queryParams.getIndex().toString() + '\"';\n const indexPath = query._path.toString();\n warn(\n `Using an unspecified index. Your data will be downloaded and ` +\n `filtered on the client. Consider adding ${indexSpec} at ` +\n `${indexPath} to your security rules for better performance.`\n );\n }\n }\n }\n\n refreshAuthToken(token: string) {\n this.authToken_ = token;\n this.log_('Auth token refreshed');\n if (this.authToken_) {\n this.tryAuth();\n } else {\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\n //the credential so we dont become authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unauth', {}, () => {});\n }\n }\n\n this.reduceReconnectDelayIfAdminCredential_(token);\n }\n\n private reduceReconnectDelayIfAdminCredential_(credential: string) {\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\n const isFirebaseSecret = credential && credential.length === 40;\n if (isFirebaseSecret || isAdmin(credential)) {\n this.log_(\n 'Admin auth credential detected. Reducing max reconnect time.'\n );\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n }\n }\n\n refreshAppCheckToken(token: string | null) {\n this.appCheckToken_ = token;\n this.log_('App check token refreshed');\n if (this.appCheckToken_) {\n this.tryAppCheck();\n } else {\n //If we're connected we want to let the server know to unauthenticate us.\n //If we're not connected, simply delete the credential so we dont become\n // authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unappeck', {}, () => {});\n }\n }\n }\n\n /**\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\n * a auth revoked (the connection is closed).\n */\n tryAuth() {\n if (this.connected_ && this.authToken_) {\n const token = this.authToken_;\n const authMethod = isValidFormat(token) ? 'auth' : 'gauth';\n const requestData: { [k: string]: unknown } = { cred: token };\n if (this.authOverride_ === null) {\n requestData['noauth'] = true;\n } else if (typeof this.authOverride_ === 'object') {\n requestData['authvar'] = this.authOverride_;\n }\n this.sendRequest(\n authMethod,\n requestData,\n (res: { [k: string]: unknown }) => {\n const status = res[/*status*/ 's'] as string;\n const data = (res[/*data*/ 'd'] as string) || 'error';\n\n if (this.authToken_ === token) {\n if (status === 'ok') {\n this.invalidAuthTokenCount_ = 0;\n } else {\n // Triggers reconnect and force refresh for auth token\n this.onAuthRevoked_(status, data);\n }\n }\n }\n );\n }\n }\n\n /**\n * Attempts to authenticate with the given token. If the authentication\n * attempt fails, it's triggered like the token was revoked (the connection is\n * closed).\n */\n tryAppCheck() {\n if (this.connected_ && this.appCheckToken_) {\n this.sendRequest(\n 'appcheck',\n { 'token': this.appCheckToken_ },\n (res: { [k: string]: unknown }) => {\n const status = res[/*status*/ 's'] as string;\n const data = (res[/*data*/ 'd'] as string) || 'error';\n if (status === 'ok') {\n this.invalidAppCheckTokenCount_ = 0;\n } else {\n this.onAppCheckRevoked_(status, data);\n }\n }\n );\n }\n }\n\n /**\n * @inheritDoc\n */\n unlisten(query: QueryContext, tag: number | null) {\n const pathString = query._path.toString();\n const queryId = query._queryIdentifier;\n\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\n\n assert(\n query._queryParams.isDefault() || !query._queryParams.loadsAllData(),\n 'unlisten() called for non-default but complete query'\n );\n const listen = this.removeListen_(pathString, queryId);\n if (listen && this.connected_) {\n this.sendUnlisten_(pathString, queryId, query._queryObject, tag);\n }\n }\n\n private sendUnlisten_(\n pathString: string,\n queryId: string,\n queryObj: object,\n tag: number | null\n ) {\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\n\n const req: { [k: string]: unknown } = { /*path*/ p: pathString };\n const action = 'n';\n // Only bother sending queryId if it's non-default.\n if (tag) {\n req['q'] = queryObj;\n req['t'] = tag;\n }\n\n this.sendRequest(action, req);\n }\n\n onDisconnectPut(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\n\n if (this.connected_) {\n this.sendOnDisconnect_('o', pathString, data, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'o',\n data,\n onComplete\n });\n }\n }\n\n onDisconnectMerge(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\n\n if (this.connected_) {\n this.sendOnDisconnect_('om', pathString, data, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'om',\n data,\n onComplete\n });\n }\n }\n\n onDisconnectCancel(\n pathString: string,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\n\n if (this.connected_) {\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'oc',\n data: null,\n onComplete\n });\n }\n }\n\n private sendOnDisconnect_(\n action: string,\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string) => void\n ) {\n const request = { /*path*/ p: pathString, /*data*/ d: data };\n this.log_('onDisconnect ' + action, request);\n this.sendRequest(action, request, (response: { [k: string]: unknown }) => {\n if (onComplete) {\n setTimeout(() => {\n onComplete(\n response[/*status*/ 's'] as string,\n response[/* data */ 'd'] as string\n );\n }, Math.floor(0));\n }\n });\n }\n\n put(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void,\n hash?: string\n ) {\n this.putInternal('p', pathString, data, onComplete, hash);\n }\n\n merge(\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {\n this.putInternal('m', pathString, data, onComplete, hash);\n }\n\n putInternal(\n action: string,\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {\n this.initConnection_();\n\n const request: { [k: string]: unknown } = {\n /*path*/ p: pathString,\n /*data*/ d: data\n };\n\n if (hash !== undefined) {\n request[/*hash*/ 'h'] = hash;\n }\n\n // TODO: Only keep track of the most recent put for a given path?\n this.outstandingPuts_.push({\n action,\n request,\n onComplete\n });\n\n this.outstandingPutCount_++;\n const index = this.outstandingPuts_.length - 1;\n\n if (this.connected_) {\n this.sendPut_(index);\n } else {\n this.log_('Buffering put: ' + pathString);\n }\n }\n\n private sendPut_(index: number) {\n const action = this.outstandingPuts_[index].action;\n const request = this.outstandingPuts_[index].request;\n const onComplete = this.outstandingPuts_[index].onComplete;\n this.outstandingPuts_[index].queued = this.connected_;\n\n this.sendRequest(action, request, (message: { [k: string]: unknown }) => {\n this.log_(action + ' response', message);\n\n delete this.outstandingPuts_[index];\n this.outstandingPutCount_--;\n\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0) {\n this.outstandingPuts_ = [];\n }\n\n if (onComplete) {\n onComplete(\n message[/*status*/ 's'] as string,\n message[/* data */ 'd'] as string\n );\n }\n });\n }\n\n reportStats(stats: { [k: string]: unknown }) {\n // If we're not connected, we just drop the stats.\n if (this.connected_) {\n const request = { /*counters*/ c: stats };\n this.log_('reportStats', request);\n\n this.sendRequest(/*stats*/ 's', request, result => {\n const status = result[/*status*/ 's'];\n if (status !== 'ok') {\n const errorReason = result[/* data */ 'd'];\n this.log_('reportStats', 'Error sending stats: ' + errorReason);\n }\n });\n }\n }\n\n private onDataMessage_(message: { [k: string]: unknown }) {\n if ('r' in message) {\n // this is a response\n this.log_('from server: ' + stringify(message));\n const reqNum = message['r'] as string;\n const onResponse = this.requestCBHash_[reqNum];\n if (onResponse) {\n delete this.requestCBHash_[reqNum];\n onResponse(message[/*body*/ 'b']);\n }\n } else if ('error' in message) {\n throw 'A server-side error has occurred: ' + message['error'];\n } else if ('a' in message) {\n // a and b are action and body, respectively\n this.onDataPush_(message['a'] as string, message['b'] as {});\n }\n }\n\n private onDataPush_(action: string, body: { [k: string]: unknown }) {\n this.log_('handleServerMessage', action, body);\n if (action === 'd') {\n this.onDataUpdate_(\n body[/*path*/ 'p'] as string,\n body[/*data*/ 'd'],\n /*isMerge*/ false,\n body['t'] as number\n );\n } else if (action === 'm') {\n this.onDataUpdate_(\n body[/*path*/ 'p'] as string,\n body[/*data*/ 'd'],\n /*isMerge=*/ true,\n body['t'] as number\n );\n } else if (action === 'c') {\n this.onListenRevoked_(\n body[/*path*/ 'p'] as string,\n body[/*query*/ 'q'] as unknown[]\n );\n } else if (action === 'ac') {\n this.onAuthRevoked_(\n body[/*status code*/ 's'] as string,\n body[/* explanation */ 'd'] as string\n );\n } else if (action === 'apc') {\n this.onAppCheckRevoked_(\n body[/*status code*/ 's'] as string,\n body[/* explanation */ 'd'] as string\n );\n } else if (action === 'sd') {\n this.onSecurityDebugPacket_(body);\n } else {\n error(\n 'Unrecognized action received from server: ' +\n stringify(action) +\n '\\nAre you using the latest client?'\n );\n }\n }\n\n private onReady_(timestamp: number, sessionId: string) {\n this.log_('connection ready');\n this.connected_ = true;\n this.lastConnectionEstablishedTime_ = new Date().getTime();\n this.handleTimestamp_(timestamp);\n this.lastSessionId = sessionId;\n if (this.firstConnection_) {\n this.sendConnectStats_();\n }\n this.restoreState_();\n this.firstConnection_ = false;\n this.onConnectStatus_(true);\n }\n\n private scheduleConnect_(timeout: number) {\n assert(\n !this.realtime_,\n \"Scheduling a connect when we're already connected/ing?\"\n );\n\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n }\n\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\n\n this.establishConnectionTimer_ = setTimeout(() => {\n this.establishConnectionTimer_ = null;\n this.establishConnection_();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(timeout)) as any;\n }\n\n private initConnection_() {\n if (!this.realtime_ && this.firstConnection_) {\n this.scheduleConnect_(0);\n }\n }\n\n private onVisible_(visible: boolean) {\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\n if (\n visible &&\n !this.visible_ &&\n this.reconnectDelay_ === this.maxReconnectDelay_\n ) {\n this.log_('Window became visible. Reducing delay.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n this.visible_ = visible;\n }\n\n private onOnline_(online: boolean) {\n if (online) {\n this.log_('Browser went online.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n } else {\n this.log_('Browser went offline. Killing connection.');\n if (this.realtime_) {\n this.realtime_.close();\n }\n }\n }\n\n private onRealtimeDisconnect_() {\n this.log_('data client disconnected');\n this.connected_ = false;\n this.realtime_ = null;\n\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\n this.cancelSentTransactions_();\n\n // Clear out the pending requests.\n this.requestCBHash_ = {};\n\n if (this.shouldReconnect_()) {\n if (!this.visible_) {\n this.log_(\"Window isn't visible. Delaying reconnect.\");\n this.reconnectDelay_ = this.maxReconnectDelay_;\n this.lastConnectionAttemptTime_ = new Date().getTime();\n } else if (this.lastConnectionEstablishedTime_) {\n // If we've been connected long enough, reset reconnect delay to minimum.\n const timeSinceLastConnectSucceeded =\n new Date().getTime() - this.lastConnectionEstablishedTime_;\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n }\n this.lastConnectionEstablishedTime_ = null;\n }\n\n const timeSinceLastConnectAttempt = Math.max(\n 0,\n new Date().getTime() - this.lastConnectionAttemptTime_\n );\n let reconnectDelay = Math.max(\n 0,\n this.reconnectDelay_ - timeSinceLastConnectAttempt\n );\n reconnectDelay = Math.random() * reconnectDelay;\n\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\n this.scheduleConnect_(reconnectDelay);\n\n // Adjust reconnect delay for next time.\n this.reconnectDelay_ = Math.min(\n this.maxReconnectDelay_,\n this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER\n );\n }\n this.onConnectStatus_(false);\n }\n\n private async establishConnection_() {\n if (this.shouldReconnect_()) {\n this.log_('Making a connection attempt');\n this.lastConnectionAttemptTime_ = new Date().getTime();\n this.lastConnectionEstablishedTime_ = null;\n const onDataMessage = this.onDataMessage_.bind(this);\n const onReady = this.onReady_.bind(this);\n const onDisconnect = this.onRealtimeDisconnect_.bind(this);\n const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;\n const lastSessionId = this.lastSessionId;\n let canceled = false;\n let connection: Connection | null = null;\n const closeFn = function () {\n if (connection) {\n connection.close();\n } else {\n canceled = true;\n onDisconnect();\n }\n };\n const sendRequestFn = function (msg: object) {\n assert(\n connection,\n \"sendRequest call when we're not connected not allowed.\"\n );\n connection.sendRequest(msg);\n };\n\n this.realtime_ = {\n close: closeFn,\n sendRequest: sendRequestFn\n };\n\n const forceRefresh = this.forceTokenRefresh_;\n this.forceTokenRefresh_ = false;\n\n try {\n // First fetch auth and app check token, and establish connection after\n // fetching the token was successful\n const [authToken, appCheckToken] = await Promise.all([\n this.authTokenProvider_.getToken(forceRefresh),\n this.appCheckTokenProvider_.getToken(forceRefresh)\n ]);\n\n if (!canceled) {\n log('getToken() completed. Creating connection.');\n this.authToken_ = authToken && authToken.accessToken;\n this.appCheckToken_ = appCheckToken && appCheckToken.token;\n connection = new Connection(\n connId,\n this.repoInfo_,\n this.applicationId_,\n this.appCheckToken_,\n this.authToken_,\n onDataMessage,\n onReady,\n onDisconnect,\n /* onKill= */ reason => {\n warn(reason + ' (' + this.repoInfo_.toString() + ')');\n this.interrupt(SERVER_KILL_INTERRUPT_REASON);\n },\n lastSessionId\n );\n } else {\n log('getToken() completed but was canceled');\n }\n } catch (error) {\n this.log_('Failed to get token: ' + error);\n if (!canceled) {\n if (this.repoInfo_.nodeAdmin) {\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\n // But getToken() may also just have temporarily failed, so we still want to\n // continue retrying.\n warn(error);\n }\n closeFn();\n }\n }\n }\n }\n\n interrupt(reason: string) {\n log('Interrupting connection for reason: ' + reason);\n this.interruptReasons_[reason] = true;\n if (this.realtime_) {\n this.realtime_.close();\n } else {\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n this.establishConnectionTimer_ = null;\n }\n if (this.connected_) {\n this.onRealtimeDisconnect_();\n }\n }\n }\n\n resume(reason: string) {\n log('Resuming connection for reason: ' + reason);\n delete this.interruptReasons_[reason];\n if (isEmpty(this.interruptReasons_)) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n }\n\n private handleTimestamp_(timestamp: number) {\n const delta = timestamp - new Date().getTime();\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\n }\n\n private cancelSentTransactions_() {\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\n const put = this.outstandingPuts_[i];\n if (put && /*hash*/ 'h' in put.request && put.queued) {\n if (put.onComplete) {\n put.onComplete('disconnect');\n }\n\n delete this.outstandingPuts_[i];\n this.outstandingPutCount_--;\n }\n }\n\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0) {\n this.outstandingPuts_ = [];\n }\n }\n\n private onListenRevoked_(pathString: string, query?: unknown[]) {\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\n let queryId;\n if (!query) {\n queryId = 'default';\n } else {\n queryId = query.map(q => ObjectToUniqueKey(q)).join('$');\n }\n const listen = this.removeListen_(pathString, queryId);\n if (listen && listen.onComplete) {\n listen.onComplete('permission_denied');\n }\n }\n\n private removeListen_(pathString: string, queryId: string): ListenSpec {\n const normalizedPathString = new Path(pathString).toString(); // normalize path.\n let listen;\n if (this.listens.has(normalizedPathString)) {\n const map = this.listens.get(normalizedPathString)!;\n listen = map.get(queryId);\n map.delete(queryId);\n if (map.size === 0) {\n this.listens.delete(normalizedPathString);\n }\n } else {\n // all listens for this path has already been removed\n listen = undefined;\n }\n return listen;\n }\n\n private onAuthRevoked_(statusCode: string, explanation: string) {\n log('Auth token revoked: ' + statusCode + '/' + explanation);\n this.authToken_ = null;\n this.forceTokenRefresh_ = true;\n this.realtime_.close();\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAuthTokenCount_++;\n if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\n // Set a long reconnect delay because recovery is unlikely\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n\n // Notify the auth token provider that the token is invalid, which will log\n // a warning\n this.authTokenProvider_.notifyForInvalidToken();\n }\n }\n }\n\n private onAppCheckRevoked_(statusCode: string, explanation: string) {\n log('App check token revoked: ' + statusCode + '/' + explanation);\n this.appCheckToken_ = null;\n this.forceTokenRefresh_ = true;\n // Note: We don't close the connection as the developer may not have\n // enforcement enabled. The backend closes connections with enforcements.\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAppCheckTokenCount_++;\n if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\n this.appCheckTokenProvider_.notifyForInvalidToken();\n }\n }\n }\n\n private onSecurityDebugPacket_(body: { [k: string]: unknown }) {\n if (this.securityDebugCallback_) {\n this.securityDebugCallback_(body);\n } else {\n if ('msg' in body) {\n console.log(\n 'FIREBASE: ' + (body['msg'] as string).replace('\\n', '\\nFIREBASE: ')\n );\n }\n }\n }\n\n private restoreState_() {\n //Re-authenticate ourselves if we have a credential stored.\n this.tryAuth();\n this.tryAppCheck();\n\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\n // make sure to send listens before puts.\n for (const queries of this.listens.values()) {\n for (const listenSpec of queries.values()) {\n this.sendListen_(listenSpec);\n }\n }\n\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\n if (this.outstandingPuts_[i]) {\n this.sendPut_(i);\n }\n }\n\n while (this.onDisconnectRequestQueue_.length) {\n const request = this.onDisconnectRequestQueue_.shift();\n this.sendOnDisconnect_(\n request.action,\n request.pathString,\n request.data,\n request.onComplete\n );\n }\n\n for (let i = 0; i < this.outstandingGets_.length; i++) {\n if (this.outstandingGets_[i]) {\n this.sendGet_(i);\n }\n }\n }\n\n /**\n * Sends client stats for first connection\n */\n private sendConnectStats_() {\n const stats: { [k: string]: number } = {};\n\n let clientName = 'js';\n if (isNodeSdk()) {\n if (this.repoInfo_.nodeAdmin) {\n clientName = 'admin_node';\n } else {\n clientName = 'node';\n }\n }\n\n stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\\./g, '-')] = 1;\n\n if (isMobileCordova()) {\n stats['framework.cordova'] = 1;\n } else if (isReactNative()) {\n stats['framework.reactnative'] = 1;\n }\n this.reportStats(stats);\n }\n\n private shouldReconnect_(): boolean {\n const online = OnlineMonitor.getInstance().currentlyOnline();\n return isEmpty(this.interruptReasons_) && online;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Path } from '../util/Path';\n\nimport { Index } from './indexes/Index';\n\n/**\n * Node is an interface defining the common functionality for nodes in\n * a DataSnapshot.\n *\n * @interface\n */\nexport interface Node {\n /**\n * Whether this node is a leaf node.\n * @returns Whether this is a leaf node.\n */\n isLeafNode(): boolean;\n\n /**\n * Gets the priority of the node.\n * @returns The priority of the node.\n */\n getPriority(): Node;\n\n /**\n * Returns a duplicate node with the new priority.\n * @param newPriorityNode - New priority to set for the node.\n * @returns Node with new priority.\n */\n updatePriority(newPriorityNode: Node): Node;\n\n /**\n * Returns the specified immediate child, or null if it doesn't exist.\n * @param childName - The name of the child to retrieve.\n * @returns The retrieved child, or an empty node.\n */\n getImmediateChild(childName: string): Node;\n\n /**\n * Returns a child by path, or null if it doesn't exist.\n * @param path - The path of the child to retrieve.\n * @returns The retrieved child or an empty node.\n */\n getChild(path: Path): Node;\n\n /**\n * Returns the name of the child immediately prior to the specified childNode, or null.\n * @param childName - The name of the child to find the predecessor of.\n * @param childNode - The node to find the predecessor of.\n * @param index - The index to use to determine the predecessor\n * @returns The name of the predecessor child, or null if childNode is the first child.\n */\n getPredecessorChildName(\n childName: string,\n childNode: Node,\n index: Index\n ): string | null;\n\n /**\n * Returns a duplicate node, with the specified immediate child updated.\n * Any value in the node will be removed.\n * @param childName - The name of the child to update.\n * @param newChildNode - The new child node\n * @returns The updated node.\n */\n updateImmediateChild(childName: string, newChildNode: Node): Node;\n\n /**\n * Returns a duplicate node, with the specified child updated. Any value will\n * be removed.\n * @param path - The path of the child to update.\n * @param newChildNode - The new child node, which may be an empty node\n * @returns The updated node.\n */\n updateChild(path: Path, newChildNode: Node): Node;\n\n /**\n * True if the immediate child specified exists\n */\n hasChild(childName: string): boolean;\n\n /**\n * @returns True if this node has no value or children.\n */\n isEmpty(): boolean;\n\n /**\n * @returns The number of children of this node.\n */\n numChildren(): number;\n\n /**\n * Calls action for each child.\n * @param action - Action to be called for\n * each child. It's passed the child name and the child node.\n * @returns The first truthy value return by action, or the last falsey one\n */\n forEachChild(index: Index, action: (a: string, b: Node) => void): unknown;\n\n /**\n * @param exportFormat - True for export format (also wire protocol format).\n * @returns Value of this node as JSON.\n */\n val(exportFormat?: boolean): unknown;\n\n /**\n * @returns hash representing the node contents.\n */\n hash(): string;\n\n /**\n * @param other - Another node\n * @returns -1 for less than, 0 for equal, 1 for greater than other\n */\n compareTo(other: Node): number;\n\n /**\n * @returns Whether or not this snapshot equals other\n */\n equals(other: Node): boolean;\n\n /**\n * @returns This node, with the specified index now available\n */\n withIndex(indexDefinition: Index): Node;\n\n isIndexed(indexDefinition: Index): boolean;\n}\n\nexport class NamedNode {\n constructor(public name: string, public node: Node) {}\n\n static Wrap(name: string, node: Node) {\n return new NamedNode(name, node);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Comparator } from '../../util/SortedMap';\nimport { MIN_NAME } from '../../util/util';\nimport { Node, NamedNode } from '../Node';\n\nexport abstract class Index {\n abstract compare(a: NamedNode, b: NamedNode): number;\n\n abstract isDefinedOn(node: Node): boolean;\n\n /**\n * @returns A standalone comparison function for\n * this index\n */\n getCompare(): Comparator {\n return this.compare.bind(this);\n }\n\n /**\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\n *\n *\n * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode\n */\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n const oldWrapped = new NamedNode(MIN_NAME, oldNode);\n const newWrapped = new NamedNode(MIN_NAME, newNode);\n return this.compare(oldWrapped, newWrapped) !== 0;\n }\n\n /**\n * @returns a node wrapper that will sort equal to or less than\n * any other node wrapper, using this index\n */\n minPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n\n /**\n * @returns a node wrapper that will sort greater than or equal to\n * any other node wrapper, using this index\n */\n abstract maxPost(): NamedNode;\n\n abstract makePost(indexValue: unknown, name: string): NamedNode;\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n abstract toString(): string;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport { nameCompare, MAX_NAME } from '../../util/util';\nimport { ChildrenNode } from '../ChildrenNode';\nimport { Node, NamedNode } from '../Node';\n\nimport { Index } from './Index';\n\nlet __EMPTY_NODE: ChildrenNode;\n\nexport class KeyIndex extends Index {\n static get __EMPTY_NODE() {\n return __EMPTY_NODE;\n }\n\n static set __EMPTY_NODE(val) {\n __EMPTY_NODE = val;\n }\n compare(a: NamedNode, b: NamedNode): number {\n return nameCompare(a.name, b.name);\n }\n isDefinedOn(node: Node): boolean {\n // We could probably return true here (since every node has a key), but it's never called\n // so just leaving unimplemented for now.\n throw assertionError('KeyIndex.isDefinedOn not expected to be called.');\n }\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return false; // The key for a node never changes.\n }\n minPost() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n maxPost(): NamedNode {\n // TODO: This should really be created once and cached in a static property, but\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\n return new NamedNode(MAX_NAME, __EMPTY_NODE);\n }\n\n makePost(indexValue: string, name: string): NamedNode {\n assert(\n typeof indexValue === 'string',\n 'KeyIndex indexValue must always be a string.'\n );\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\n return new NamedNode(indexValue, __EMPTY_NODE);\n }\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString(): string {\n return '.key';\n }\n}\n\nexport const KEY_INDEX = new KeyIndex();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Implementation of an immutable SortedMap using a Left-leaning\n * Red-Black Tree, adapted from the implementation in Mugs\n * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen\n * (mads379\\@gmail.com).\n *\n * Original paper on Left-leaning Red-Black Trees:\n * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf\n *\n * Invariant 1: No red node has a red child\n * Invariant 2: Every leaf path has the same number of black nodes\n * Invariant 3: Only the left child can be red (left leaning)\n */\n\n// TODO: There are some improvements I'd like to make to improve memory / perf:\n// * Create two prototypes, LLRedNode and LLBlackNode, instead of storing a\n// color property in every node.\n// TODO: It would also be good (and possibly necessary) to create a base\n// interface for LLRBNode and LLRBEmptyNode.\n\nexport type Comparator = (key1: K, key2: K) => number;\n\n/**\n * An iterator over an LLRBNode.\n */\nexport class SortedMapIterator {\n private nodeStack_: Array | LLRBEmptyNode> = [];\n\n /**\n * @param node - Node to iterate.\n * @param isReverse_ - Whether or not to iterate in reverse\n */\n constructor(\n node: LLRBNode | LLRBEmptyNode,\n startKey: K | null,\n comparator: Comparator,\n private isReverse_: boolean,\n private resultGenerator_: ((k: K, v: V) => T) | null = null\n ) {\n let cmp = 1;\n while (!node.isEmpty()) {\n node = node as LLRBNode;\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse_) {\n cmp *= -1;\n }\n\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse_) {\n node = node.left;\n } else {\n node = node.right;\n }\n } else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\n this.nodeStack_.push(node);\n break;\n } else {\n // This node is greater than our start key, add it to the stack and move to the next one\n this.nodeStack_.push(node);\n if (this.isReverse_) {\n node = node.right;\n } else {\n node = node.left;\n }\n }\n }\n }\n\n getNext(): T {\n if (this.nodeStack_.length === 0) {\n return null;\n }\n\n let node = this.nodeStack_.pop();\n let result: T;\n if (this.resultGenerator_) {\n result = this.resultGenerator_(node.key, node.value);\n } else {\n result = { key: node.key, value: node.value } as unknown as T;\n }\n\n if (this.isReverse_) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.right;\n }\n } else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.left;\n }\n }\n\n return result;\n }\n\n hasNext(): boolean {\n return this.nodeStack_.length > 0;\n }\n\n peek(): T {\n if (this.nodeStack_.length === 0) {\n return null;\n }\n\n const node = this.nodeStack_[this.nodeStack_.length - 1];\n if (this.resultGenerator_) {\n return this.resultGenerator_(node.key, node.value);\n } else {\n return { key: node.key, value: node.value } as unknown as T;\n }\n }\n}\n\n/**\n * Represents a node in a Left-leaning Red-Black tree.\n */\nexport class LLRBNode {\n color: boolean;\n left: LLRBNode | LLRBEmptyNode;\n right: LLRBNode | LLRBEmptyNode;\n\n /**\n * @param key - Key associated with this node.\n * @param value - Value associated with this node.\n * @param color - Whether this node is red.\n * @param left - Left child.\n * @param right - Right child.\n */\n constructor(\n public key: K,\n public value: V,\n color: boolean | null,\n left?: LLRBNode | LLRBEmptyNode | null,\n right?: LLRBNode | LLRBEmptyNode | null\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left =\n left != null ? left : (SortedMap.EMPTY_NODE as LLRBEmptyNode);\n this.right =\n right != null ? right : (SortedMap.EMPTY_NODE as LLRBEmptyNode);\n }\n\n static RED = true;\n static BLACK = false;\n\n /**\n * Returns a copy of the current node, optionally replacing pieces of it.\n *\n * @param key - New key for the node, or null.\n * @param value - New value for the node, or null.\n * @param color - New color for the node, or null.\n * @param left - New left child for the node, or null.\n * @param right - New right child for the node, or null.\n * @returns The node copy.\n */\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBNode {\n return new LLRBNode(\n key != null ? key : this.key,\n value != null ? value : this.value,\n color != null ? color : this.color,\n left != null ? left : this.left,\n right != null ? right : this.right\n );\n }\n\n /**\n * @returns The total number of nodes in the tree.\n */\n count(): number {\n return this.left.count() + 1 + this.right.count();\n }\n\n /**\n * @returns True if the tree is empty.\n */\n isEmpty(): boolean {\n return false;\n }\n\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n inorderTraversal(action: (k: K, v: V) => unknown): boolean {\n return (\n this.left.inorderTraversal(action) ||\n !!action(this.key, this.value) ||\n this.right.inorderTraversal(action)\n );\n }\n\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n reverseTraversal(action: (k: K, v: V) => void): boolean {\n return (\n this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action)\n );\n }\n\n /**\n * @returns The minimum node in the tree.\n */\n private min_(): LLRBNode {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode).min_();\n }\n }\n\n /**\n * @returns The maximum key in the tree.\n */\n minKey(): K {\n return this.min_().key;\n }\n\n /**\n * @returns The maximum key in the tree.\n */\n maxKey(): K {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\n }\n\n /**\n * @param key - Key to insert.\n * @param value - Value to insert.\n * @param comparator - Comparator.\n * @returns New tree, with the key/value added.\n */\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n let n: LLRBNode = this;\n const cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n } else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n } else {\n n = n.copy(\n null,\n null,\n null,\n null,\n n.right.insert(key, value, comparator)\n );\n }\n return n.fixUp_();\n }\n\n /**\n * @returns New tree, with the minimum key removed.\n */\n private removeMin_(): LLRBNode | LLRBEmptyNode {\n if (this.left.isEmpty()) {\n return SortedMap.EMPTY_NODE as LLRBEmptyNode;\n }\n let n: LLRBNode = this;\n if (!n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, (n.left as LLRBNode).removeMin_(), null);\n return n.fixUp_();\n }\n\n /**\n * @param key - The key of the item to remove.\n * @param comparator - Comparator.\n * @returns New tree, with the specified item removed.\n */\n remove(\n key: K,\n comparator: Comparator\n ): LLRBNode | LLRBEmptyNode {\n let n, smallest;\n n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n } else {\n if (n.left.isRed_()) {\n n = n.rotateRight_();\n }\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\n n = n.moveRedRight_();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return SortedMap.EMPTY_NODE as LLRBEmptyNode;\n } else {\n smallest = (n.right as LLRBNode).min_();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode).removeMin_()\n );\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp_();\n }\n\n /**\n * @returns Whether this is a RED node.\n */\n isRed_(): boolean {\n return this.color;\n }\n\n /**\n * @returns New tree after performing any needed rotations.\n */\n private fixUp_(): LLRBNode {\n let n: LLRBNode = this;\n if (n.right.isRed_() && !n.left.isRed_()) {\n n = n.rotateLeft_();\n }\n if (n.left.isRed_() && n.left.left.isRed_()) {\n n = n.rotateRight_();\n }\n if (n.left.isRed_() && n.right.isRed_()) {\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @returns New tree, after moveRedLeft.\n */\n private moveRedLeft_(): LLRBNode {\n let n = this.colorFlip_();\n if (n.right.left.isRed_()) {\n n = n.copy(\n null,\n null,\n null,\n null,\n (n.right as LLRBNode).rotateRight_()\n );\n n = n.rotateLeft_();\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @returns New tree, after moveRedRight.\n */\n private moveRedRight_(): LLRBNode {\n let n = this.colorFlip_();\n if (n.left.left.isRed_()) {\n n = n.rotateRight_();\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @returns New tree, after rotateLeft.\n */\n private rotateLeft_(): LLRBNode {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null) as LLRBNode;\n }\n\n /**\n * @returns New tree, after rotateRight.\n */\n private rotateRight_(): LLRBNode {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr) as LLRBNode;\n }\n\n /**\n * @returns Newt ree, after colorFlip.\n */\n private colorFlip_(): LLRBNode {\n const left = this.left.copy(null, null, !this.left.color, null, null);\n const right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n }\n\n /**\n * For testing.\n *\n * @returns True if all is well.\n */\n private checkMaxDepth_(): boolean {\n const blackDepth = this.check_();\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\n }\n\n check_(): number {\n if (this.isRed_() && this.left.isRed_()) {\n throw new Error(\n 'Red node has red child(' + this.key + ',' + this.value + ')'\n );\n }\n if (this.right.isRed_()) {\n throw new Error(\n 'Right child of (' + this.key + ',' + this.value + ') is red'\n );\n }\n const blackDepth = this.left.check_();\n if (blackDepth !== this.right.check_()) {\n throw new Error('Black depths differ');\n } else {\n return blackDepth + (this.isRed_() ? 0 : 1);\n }\n }\n}\n\n/**\n * Represents an empty node (a leaf node in the Red-Black Tree).\n */\nexport class LLRBEmptyNode {\n key: K;\n value: V;\n left: LLRBNode | LLRBEmptyNode;\n right: LLRBNode | LLRBEmptyNode;\n color: boolean;\n\n /**\n * Returns a copy of the current node.\n *\n * @returns The node copy.\n */\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBEmptyNode {\n return this;\n }\n\n /**\n * Returns a copy of the tree, with the specified key/value added.\n *\n * @param key - Key to be added.\n * @param value - Value to be added.\n * @param comparator - Comparator.\n * @returns New tree, with item added.\n */\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n return new LLRBNode(key, value, null);\n }\n\n /**\n * Returns a copy of the tree, with the specified key removed.\n *\n * @param key - The key to remove.\n * @param comparator - Comparator.\n * @returns New tree, with item removed.\n */\n remove(key: K, comparator: Comparator): LLRBEmptyNode {\n return this;\n }\n\n /**\n * @returns The total number of nodes in the tree.\n */\n count(): number {\n return 0;\n }\n\n /**\n * @returns True if the tree is empty.\n */\n isEmpty(): boolean {\n return true;\n }\n\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n inorderTraversal(action: (k: K, v: V) => unknown): boolean {\n return false;\n }\n\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n reverseTraversal(action: (k: K, v: V) => void): boolean {\n return false;\n }\n\n minKey(): null {\n return null;\n }\n\n maxKey(): null {\n return null;\n }\n\n check_(): number {\n return 0;\n }\n\n /**\n * @returns Whether this node is red.\n */\n isRed_() {\n return false;\n }\n}\n\n/**\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\n * tree.\n */\nexport class SortedMap {\n /**\n * Always use the same empty node, to reduce memory.\n */\n static EMPTY_NODE = new LLRBEmptyNode();\n\n /**\n * @param comparator_ - Key comparator.\n * @param root_ - Optional root node for the map.\n */\n constructor(\n private comparator_: Comparator,\n private root_:\n | LLRBNode\n | LLRBEmptyNode = SortedMap.EMPTY_NODE as LLRBEmptyNode\n ) {}\n\n /**\n * Returns a copy of the map, with the specified key/value added or replaced.\n * (TODO: We should perhaps rename this method to 'put')\n *\n * @param key - Key to be added.\n * @param value - Value to be added.\n * @returns New map, with item added.\n */\n insert(key: K, value: V): SortedMap {\n return new SortedMap(\n this.comparator_,\n this.root_\n .insert(key, value, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n /**\n * Returns a copy of the map, with the specified key removed.\n *\n * @param key - The key to remove.\n * @returns New map, with item removed.\n */\n remove(key: K): SortedMap {\n return new SortedMap(\n this.comparator_,\n this.root_\n .remove(key, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n /**\n * Returns the value of the node with the given key, or null.\n *\n * @param key - The key to look up.\n * @returns The value of the node with the given key, or null if the\n * key doesn't exist.\n */\n get(key: K): V | null {\n let cmp;\n let node = this.root_;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n return node.value;\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n }\n\n /**\n * Returns the key of the item *before* the specified key, or null if key is the first item.\n * @param key - The key to find the predecessor of\n * @returns The predecessor key.\n */\n getPredecessorKey(key: K): K | null {\n let cmp,\n node = this.root_,\n rightParent = null;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n if (!node.left.isEmpty()) {\n node = node.left;\n while (!node.right.isEmpty()) {\n node = node.right;\n }\n return node.key;\n } else if (rightParent) {\n return rightParent.key;\n } else {\n return null; // first item.\n }\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n\n throw new Error(\n 'Attempted to find predecessor key for a nonexistent key. What gives?'\n );\n }\n\n /**\n * @returns True if the map is empty.\n */\n isEmpty(): boolean {\n return this.root_.isEmpty();\n }\n\n /**\n * @returns The total number of nodes in the map.\n */\n count(): number {\n return this.root_.count();\n }\n\n /**\n * @returns The minimum key in the map.\n */\n minKey(): K | null {\n return this.root_.minKey();\n }\n\n /**\n * @returns The maximum key in the map.\n */\n maxKey(): K | null {\n return this.root_.maxKey();\n }\n\n /**\n * Traverses the map in key order and calls the specified action function\n * for each key/value pair.\n *\n * @param action - Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @returns The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n inorderTraversal(action: (k: K, v: V) => unknown): boolean {\n return this.root_.inorderTraversal(action);\n }\n\n /**\n * Traverses the map in reverse key order and calls the specified action function\n * for each key/value pair.\n *\n * @param action - Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @returns True if the traversal was aborted.\n */\n reverseTraversal(action: (k: K, v: V) => void): boolean {\n return this.root_.reverseTraversal(action);\n }\n\n /**\n * Returns an iterator over the SortedMap.\n * @returns The iterator.\n */\n getIterator(\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n null,\n this.comparator_,\n false,\n resultGenerator\n );\n }\n\n getIteratorFrom(\n key: K,\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n key,\n this.comparator_,\n false,\n resultGenerator\n );\n }\n\n getReverseIteratorFrom(\n key: K,\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n key,\n this.comparator_,\n true,\n resultGenerator\n );\n }\n\n getReverseIterator(\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n null,\n this.comparator_,\n true,\n resultGenerator\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare } from '../util/util';\n\nimport { NamedNode } from './Node';\n\nexport function NAME_ONLY_COMPARATOR(left: NamedNode, right: NamedNode) {\n return nameCompare(left.name, right.name);\n}\n\nexport function NAME_COMPARATOR(left: string, right: string) {\n return nameCompare(left, right);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, contains } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport { doubleToIEEE754String } from '../util/util';\n\nimport { Node } from './Node';\n\nlet MAX_NODE: Node;\n\nexport function setMaxNode(val: Node) {\n MAX_NODE = val;\n}\n\nexport const priorityHashText = function (priority: string | number): string {\n if (typeof priority === 'number') {\n return 'number:' + doubleToIEEE754String(priority);\n } else {\n return 'string:' + priority;\n }\n};\n\n/**\n * Validates that a priority snapshot Node is valid.\n */\nexport const validatePriorityNode = function (priorityNode: Node) {\n if (priorityNode.isLeafNode()) {\n const val = priorityNode.val();\n assert(\n typeof val === 'string' ||\n typeof val === 'number' ||\n (typeof val === 'object' && contains(val as Indexable, '.sv')),\n 'Priority must be a string or number.'\n );\n } else {\n assert(\n priorityNode === MAX_NODE || priorityNode.isEmpty(),\n 'priority of unexpected type.'\n );\n }\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\n assert(\n priorityNode === MAX_NODE || priorityNode.getPriority().isEmpty(),\n \"Priority nodes can't have a priority of their own.\"\n );\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport {\n Path,\n pathGetFront,\n pathGetLength,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\nimport { doubleToIEEE754String, sha1 } from '../util/util';\n\nimport { ChildrenNodeConstructor } from './ChildrenNode';\nimport { Index } from './indexes/Index';\nimport { Node } from './Node';\nimport { priorityHashText, validatePriorityNode } from './snap';\n\nlet __childrenNodeConstructor: ChildrenNodeConstructor;\n\n/**\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\n * implements Node and stores the value of the node (a string,\n * number, or boolean) accessible via getValue().\n */\nexport class LeafNode implements Node {\n static set __childrenNodeConstructor(val: ChildrenNodeConstructor) {\n __childrenNodeConstructor = val;\n }\n\n static get __childrenNodeConstructor() {\n return __childrenNodeConstructor;\n }\n\n /**\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\n * the same type, the comparison falls back to their value\n */\n static VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n\n private lazyHash_: string | null = null;\n\n /**\n * @param value_ - The value to store in this leaf node. The object type is\n * possible in the event of a deferred value\n * @param priorityNode_ - The priority of this node.\n */\n constructor(\n private readonly value_: string | number | boolean | Indexable,\n private priorityNode_: Node = LeafNode.__childrenNodeConstructor.EMPTY_NODE\n ) {\n assert(\n this.value_ !== undefined && this.value_ !== null,\n \"LeafNode shouldn't be created with null/undefined value.\"\n );\n\n validatePriorityNode(this.priorityNode_);\n }\n\n /** @inheritDoc */\n isLeafNode(): boolean {\n return true;\n }\n\n /** @inheritDoc */\n getPriority(): Node {\n return this.priorityNode_;\n }\n\n /** @inheritDoc */\n updatePriority(newPriorityNode: Node): Node {\n return new LeafNode(this.value_, newPriorityNode);\n }\n\n /** @inheritDoc */\n getImmediateChild(childName: string): Node {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.priorityNode_;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n }\n\n /** @inheritDoc */\n getChild(path: Path): Node {\n if (pathIsEmpty(path)) {\n return this;\n } else if (pathGetFront(path) === '.priority') {\n return this.priorityNode_;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n }\n hasChild(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n getPredecessorChildName(childName: string, childNode: Node): null {\n return null;\n }\n\n /** @inheritDoc */\n updateImmediateChild(childName: string, newChildNode: Node): Node {\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n } else if (newChildNode.isEmpty() && childName !== '.priority') {\n return this;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(\n childName,\n newChildNode\n ).updatePriority(this.priorityNode_);\n }\n }\n\n /** @inheritDoc */\n updateChild(path: Path, newChildNode: Node): Node {\n const front = pathGetFront(path);\n if (front === null) {\n return newChildNode;\n } else if (newChildNode.isEmpty() && front !== '.priority') {\n return this;\n } else {\n assert(\n front !== '.priority' || pathGetLength(path) === 1,\n '.priority must be the last token in a path'\n );\n\n return this.updateImmediateChild(\n front,\n LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(\n pathPopFront(path),\n newChildNode\n )\n );\n }\n }\n\n /** @inheritDoc */\n isEmpty(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n numChildren(): number {\n return 0;\n }\n\n /** @inheritDoc */\n forEachChild(index: Index, action: (s: string, n: Node) => void): boolean {\n return false;\n }\n val(exportFormat?: boolean): {} {\n if (exportFormat && !this.getPriority().isEmpty()) {\n return {\n '.value': this.getValue(),\n '.priority': this.getPriority().val()\n };\n } else {\n return this.getValue();\n }\n }\n\n /** @inheritDoc */\n hash(): string {\n if (this.lazyHash_ === null) {\n let toHash = '';\n if (!this.priorityNode_.isEmpty()) {\n toHash +=\n 'priority:' +\n priorityHashText(this.priorityNode_.val() as number | string) +\n ':';\n }\n\n const type = typeof this.value_;\n toHash += type + ':';\n if (type === 'number') {\n toHash += doubleToIEEE754String(this.value_ as number);\n } else {\n toHash += this.value_;\n }\n this.lazyHash_ = sha1(toHash);\n }\n return this.lazyHash_;\n }\n\n /**\n * Returns the value of the leaf node.\n * @returns The value of the node.\n */\n getValue(): Indexable | string | number | boolean {\n return this.value_;\n }\n compareTo(other: Node): number {\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\n return 1;\n } else if (other instanceof LeafNode.__childrenNodeConstructor) {\n return -1;\n } else {\n assert(other.isLeafNode(), 'Unknown node type');\n return this.compareToLeafNode_(other as LeafNode);\n }\n }\n\n /**\n * Comparison specifically for two leaf nodes\n */\n private compareToLeafNode_(otherLeaf: LeafNode): number {\n const otherLeafType = typeof otherLeaf.value_;\n const thisLeafType = typeof this.value_;\n const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\n const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\n assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\n assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\n if (otherIndex === thisIndex) {\n // Same type, compare values\n if (thisLeafType === 'object') {\n // Deferred value nodes are all equal, but we should also never get to this point...\n return 0;\n } else {\n // Note that this works because true > false, all others are number or string comparisons\n if (this.value_ < otherLeaf.value_) {\n return -1;\n } else if (this.value_ === otherLeaf.value_) {\n return 0;\n } else {\n return 1;\n }\n }\n } else {\n return thisIndex - otherIndex;\n }\n }\n withIndex(): Node {\n return this;\n }\n isIndexed(): boolean {\n return true;\n }\n equals(other: Node): boolean {\n if (other === this) {\n return true;\n } else if (other.isLeafNode()) {\n const otherLeaf = other as LeafNode;\n return (\n this.value_ === otherLeaf.value_ &&\n this.priorityNode_.equals(otherLeaf.priorityNode_)\n );\n } else {\n return false;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare, MAX_NAME } from '../../util/util';\nimport { LeafNode } from '../LeafNode';\nimport { NamedNode, Node } from '../Node';\n\nimport { Index } from './Index';\n\nlet nodeFromJSON: (a: unknown) => Node;\nlet MAX_NODE: Node;\n\nexport function setNodeFromJSON(val: (a: unknown) => Node) {\n nodeFromJSON = val;\n}\n\nexport function setMaxNode(val: Node) {\n MAX_NODE = val;\n}\n\nexport class PriorityIndex extends Index {\n compare(a: NamedNode, b: NamedNode): number {\n const aPriority = a.node.getPriority();\n const bPriority = b.node.getPriority();\n const indexCmp = aPriority.compareTo(bPriority);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n isDefinedOn(node: Node): boolean {\n return !node.getPriority().isEmpty();\n }\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return !oldNode.getPriority().equals(newNode.getPriority());\n }\n minPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n maxPost(): NamedNode {\n return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE));\n }\n\n makePost(indexValue: unknown, name: string): NamedNode {\n const priorityNode = nodeFromJSON(indexValue);\n return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));\n }\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString(): string {\n return '.priority';\n }\n}\n\nexport const PRIORITY_INDEX = new PriorityIndex();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LLRBNode, SortedMap } from '../util/SortedMap';\n\nimport { NamedNode } from './Node';\n\nconst LOG_2 = Math.log(2);\n\nclass Base12Num {\n count: number;\n private current_: number;\n private bits_: number;\n\n constructor(length: number) {\n const logBase2 = (num: number) =>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parseInt((Math.log(num) / LOG_2) as any, 10);\n const bitMask = (bits: number) => parseInt(Array(bits + 1).join('1'), 2);\n this.count = logBase2(length + 1);\n this.current_ = this.count - 1;\n const mask = bitMask(this.count);\n this.bits_ = (length + 1) & mask;\n }\n\n nextBitIsOne(): boolean {\n //noinspection JSBitwiseOperatorUsage\n const result = !(this.bits_ & (0x1 << this.current_));\n this.current_--;\n return result;\n }\n}\n\n/**\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\n * function\n *\n * Uses the algorithm described in the paper linked here:\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\n *\n * @param childList - Unsorted list of children\n * @param cmp - The comparison method to be used\n * @param keyFn - An optional function to extract K from a node wrapper, if K's\n * type is not NamedNode\n * @param mapSortFn - An optional override for comparator used by the generated sorted map\n */\nexport const buildChildSet = function (\n childList: NamedNode[],\n cmp: (a: NamedNode, b: NamedNode) => number,\n keyFn?: (a: NamedNode) => K,\n mapSortFn?: (a: K, b: K) => number\n): SortedMap {\n childList.sort(cmp);\n\n const buildBalancedTree = function (\n low: number,\n high: number\n ): LLRBNode | null {\n const length = high - low;\n let namedNode: NamedNode;\n let key: K;\n if (length === 0) {\n return null;\n } else if (length === 1) {\n namedNode = childList[low];\n key = keyFn ? keyFn(namedNode) : (namedNode as unknown as K);\n return new LLRBNode(\n key,\n namedNode.node as unknown as V,\n LLRBNode.BLACK,\n null,\n null\n );\n } else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const middle = parseInt((length / 2) as any, 10) + low;\n const left = buildBalancedTree(low, middle);\n const right = buildBalancedTree(middle + 1, high);\n namedNode = childList[middle];\n key = keyFn ? keyFn(namedNode) : (namedNode as unknown as K);\n return new LLRBNode(\n key,\n namedNode.node as unknown as V,\n LLRBNode.BLACK,\n left,\n right\n );\n }\n };\n\n const buildFrom12Array = function (base12: Base12Num): LLRBNode {\n let node: LLRBNode = null;\n let root = null;\n let index = childList.length;\n\n const buildPennant = function (chunkSize: number, color: boolean) {\n const low = index - chunkSize;\n const high = index;\n index -= chunkSize;\n const childTree = buildBalancedTree(low + 1, high);\n const namedNode = childList[low];\n const key: K = keyFn ? keyFn(namedNode) : (namedNode as unknown as K);\n attachPennant(\n new LLRBNode(\n key,\n namedNode.node as unknown as V,\n color,\n null,\n childTree\n )\n );\n };\n\n const attachPennant = function (pennant: LLRBNode) {\n if (node) {\n node.left = pennant;\n node = pennant;\n } else {\n root = pennant;\n node = pennant;\n }\n };\n\n for (let i = 0; i < base12.count; ++i) {\n const isOne = base12.nextBitIsOne();\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\n const chunkSize = Math.pow(2, base12.count - (i + 1));\n if (isOne) {\n buildPennant(chunkSize, LLRBNode.BLACK);\n } else {\n // current == 2\n buildPennant(chunkSize, LLRBNode.BLACK);\n buildPennant(chunkSize, LLRBNode.RED);\n }\n }\n return root;\n };\n\n const base12 = new Base12Num(childList.length);\n const root = buildFrom12Array(base12);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new SortedMap(mapSortFn || (cmp as any), root);\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, contains, map, safeGet } from '@firebase/util';\n\nimport { SortedMap } from '../util/SortedMap';\n\nimport { buildChildSet } from './childSet';\nimport { Index } from './indexes/Index';\nimport { KEY_INDEX } from './indexes/KeyIndex';\nimport { PRIORITY_INDEX } from './indexes/PriorityIndex';\nimport { NamedNode, Node } from './Node';\n\nlet _defaultIndexMap: IndexMap;\n\nconst fallbackObject = {};\n\nexport class IndexMap {\n /**\n * The default IndexMap for nodes without a priority\n */\n static get Default(): IndexMap {\n assert(\n fallbackObject && PRIORITY_INDEX,\n 'ChildrenNode.ts has not been loaded'\n );\n _defaultIndexMap =\n _defaultIndexMap ||\n new IndexMap(\n { '.priority': fallbackObject },\n { '.priority': PRIORITY_INDEX }\n );\n return _defaultIndexMap;\n }\n\n constructor(\n private indexes_: {\n [k: string]: SortedMap | /*FallbackType*/ object;\n },\n private indexSet_: { [k: string]: Index }\n ) {}\n\n get(indexKey: string): SortedMap | null {\n const sortedMap = safeGet(this.indexes_, indexKey);\n if (!sortedMap) {\n throw new Error('No index defined for ' + indexKey);\n }\n\n if (sortedMap instanceof SortedMap) {\n return sortedMap;\n } else {\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\n // regular child map\n return null;\n }\n }\n\n hasIndex(indexDefinition: Index): boolean {\n return contains(this.indexSet_, indexDefinition.toString());\n }\n\n addIndex(\n indexDefinition: Index,\n existingChildren: SortedMap\n ): IndexMap {\n assert(\n indexDefinition !== KEY_INDEX,\n \"KeyIndex always exists and isn't meant to be added to the IndexMap.\"\n );\n const childList = [];\n let sawIndexedValue = false;\n const iter = existingChildren.getIterator(NamedNode.Wrap);\n let next = iter.getNext();\n while (next) {\n sawIndexedValue =\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\n childList.push(next);\n next = iter.getNext();\n }\n let newIndex;\n if (sawIndexedValue) {\n newIndex = buildChildSet(childList, indexDefinition.getCompare());\n } else {\n newIndex = fallbackObject;\n }\n const indexName = indexDefinition.toString();\n const newIndexSet = { ...this.indexSet_ };\n newIndexSet[indexName] = indexDefinition;\n const newIndexes = { ...this.indexes_ };\n newIndexes[indexName] = newIndex;\n return new IndexMap(newIndexes, newIndexSet);\n }\n\n /**\n * Ensure that this node is properly tracked in any indexes that we're maintaining\n */\n addToIndexes(\n namedNode: NamedNode,\n existingChildren: SortedMap\n ): IndexMap {\n const newIndexes = map(\n this.indexes_,\n (indexedChildren: SortedMap, indexName: string) => {\n const index = safeGet(this.indexSet_, indexName);\n assert(index, 'Missing index implementation for ' + indexName);\n if (indexedChildren === fallbackObject) {\n // Check to see if we need to index everything\n if (index.isDefinedOn(namedNode.node)) {\n // We need to build this index\n const childList = [];\n const iter = existingChildren.getIterator(NamedNode.Wrap);\n let next = iter.getNext();\n while (next) {\n if (next.name !== namedNode.name) {\n childList.push(next);\n }\n next = iter.getNext();\n }\n childList.push(namedNode);\n return buildChildSet(childList, index.getCompare());\n } else {\n // No change, this remains a fallback\n return fallbackObject;\n }\n } else {\n const existingSnap = existingChildren.get(namedNode.name);\n let newChildren = indexedChildren;\n if (existingSnap) {\n newChildren = newChildren.remove(\n new NamedNode(namedNode.name, existingSnap)\n );\n }\n return newChildren.insert(namedNode, namedNode.node);\n }\n }\n );\n return new IndexMap(newIndexes, this.indexSet_);\n }\n\n /**\n * Create a new IndexMap instance with the given value removed\n */\n removeFromIndexes(\n namedNode: NamedNode,\n existingChildren: SortedMap\n ): IndexMap {\n const newIndexes = map(\n this.indexes_,\n (indexedChildren: SortedMap) => {\n if (indexedChildren === fallbackObject) {\n // This is the fallback. Just return it, nothing to do in this case\n return indexedChildren;\n } else {\n const existingSnap = existingChildren.get(namedNode.name);\n if (existingSnap) {\n return indexedChildren.remove(\n new NamedNode(namedNode.name, existingSnap)\n );\n } else {\n // No record of this child\n return indexedChildren;\n }\n }\n }\n );\n return new IndexMap(newIndexes, this.indexSet_);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Path, pathGetFront, pathGetLength, pathPopFront } from '../util/Path';\nimport { SortedMap, SortedMapIterator } from '../util/SortedMap';\nimport { MAX_NAME, MIN_NAME, sha1 } from '../util/util';\n\nimport { NAME_COMPARATOR } from './comparators';\nimport { Index } from './indexes/Index';\nimport { KEY_INDEX, KeyIndex } from './indexes/KeyIndex';\nimport {\n PRIORITY_INDEX,\n setMaxNode as setPriorityMaxNode\n} from './indexes/PriorityIndex';\nimport { IndexMap } from './IndexMap';\nimport { LeafNode } from './LeafNode';\nimport { NamedNode, Node } from './Node';\nimport { priorityHashText, setMaxNode, validatePriorityNode } from './snap';\n\nexport interface ChildrenNodeConstructor {\n new (\n children_: SortedMap,\n priorityNode_: Node | null,\n indexMap_: IndexMap\n ): ChildrenNode;\n EMPTY_NODE: ChildrenNode;\n}\n\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\n\nlet EMPTY_NODE: ChildrenNode;\n\n/**\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\n * (i.e. nodes with children). It implements Node and stores the\n * list of children in the children property, sorted by child name.\n */\nexport class ChildrenNode implements Node {\n private lazyHash_: string | null = null;\n\n static get EMPTY_NODE(): ChildrenNode {\n return (\n EMPTY_NODE ||\n (EMPTY_NODE = new ChildrenNode(\n new SortedMap(NAME_COMPARATOR),\n null,\n IndexMap.Default\n ))\n );\n }\n\n /**\n * @param children_ - List of children of this node..\n * @param priorityNode_ - The priority of this node (as a snapshot node).\n */\n constructor(\n private readonly children_: SortedMap,\n private readonly priorityNode_: Node | null,\n private indexMap_: IndexMap\n ) {\n /**\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\n * class instead of an empty ChildrenNode.\n */\n if (this.priorityNode_) {\n validatePriorityNode(this.priorityNode_);\n }\n\n if (this.children_.isEmpty()) {\n assert(\n !this.priorityNode_ || this.priorityNode_.isEmpty(),\n 'An empty node cannot have a priority'\n );\n }\n }\n\n /** @inheritDoc */\n isLeafNode(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n getPriority(): Node {\n return this.priorityNode_ || EMPTY_NODE;\n }\n\n /** @inheritDoc */\n updatePriority(newPriorityNode: Node): Node {\n if (this.children_.isEmpty()) {\n // Don't allow priorities on empty nodes\n return this;\n } else {\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\n }\n }\n\n /** @inheritDoc */\n getImmediateChild(childName: string): Node {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.getPriority();\n } else {\n const child = this.children_.get(childName);\n return child === null ? EMPTY_NODE : child;\n }\n }\n\n /** @inheritDoc */\n getChild(path: Path): Node {\n const front = pathGetFront(path);\n if (front === null) {\n return this;\n }\n\n return this.getImmediateChild(front).getChild(pathPopFront(path));\n }\n\n /** @inheritDoc */\n hasChild(childName: string): boolean {\n return this.children_.get(childName) !== null;\n }\n\n /** @inheritDoc */\n updateImmediateChild(childName: string, newChildNode: Node): Node {\n assert(newChildNode, 'We should always be passing snapshot nodes');\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n } else {\n const namedNode = new NamedNode(childName, newChildNode);\n let newChildren, newIndexMap;\n if (newChildNode.isEmpty()) {\n newChildren = this.children_.remove(childName);\n newIndexMap = this.indexMap_.removeFromIndexes(\n namedNode,\n this.children_\n );\n } else {\n newChildren = this.children_.insert(childName, newChildNode);\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\n }\n\n const newPriority = newChildren.isEmpty()\n ? EMPTY_NODE\n : this.priorityNode_;\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\n }\n }\n\n /** @inheritDoc */\n updateChild(path: Path, newChildNode: Node): Node {\n const front = pathGetFront(path);\n if (front === null) {\n return newChildNode;\n } else {\n assert(\n pathGetFront(path) !== '.priority' || pathGetLength(path) === 1,\n '.priority must be the last token in a path'\n );\n const newImmediateChild = this.getImmediateChild(front).updateChild(\n pathPopFront(path),\n newChildNode\n );\n return this.updateImmediateChild(front, newImmediateChild);\n }\n }\n\n /** @inheritDoc */\n isEmpty(): boolean {\n return this.children_.isEmpty();\n }\n\n /** @inheritDoc */\n numChildren(): number {\n return this.children_.count();\n }\n\n private static INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\n\n /** @inheritDoc */\n val(exportFormat?: boolean): object {\n if (this.isEmpty()) {\n return null;\n }\n\n const obj: { [k: string]: unknown } = {};\n let numKeys = 0,\n maxKey = 0,\n allIntegerKeys = true;\n this.forEachChild(PRIORITY_INDEX, (key: string, childNode: Node) => {\n obj[key] = childNode.val(exportFormat);\n\n numKeys++;\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\n maxKey = Math.max(maxKey, Number(key));\n } else {\n allIntegerKeys = false;\n }\n });\n\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\n // convert to array.\n const array: unknown[] = [];\n // eslint-disable-next-line guard-for-in\n for (const key in obj) {\n array[key as unknown as number] = obj[key];\n }\n\n return array;\n } else {\n if (exportFormat && !this.getPriority().isEmpty()) {\n obj['.priority'] = this.getPriority().val();\n }\n return obj;\n }\n }\n\n /** @inheritDoc */\n hash(): string {\n if (this.lazyHash_ === null) {\n let toHash = '';\n if (!this.getPriority().isEmpty()) {\n toHash +=\n 'priority:' +\n priorityHashText(this.getPriority().val() as string | number) +\n ':';\n }\n\n this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n const childHash = childNode.hash();\n if (childHash !== '') {\n toHash += ':' + key + ':' + childHash;\n }\n });\n\n this.lazyHash_ = toHash === '' ? '' : sha1(toHash);\n }\n return this.lazyHash_;\n }\n\n /** @inheritDoc */\n getPredecessorChildName(\n childName: string,\n childNode: Node,\n index: Index\n ): string {\n const idx = this.resolveIndex_(index);\n if (idx) {\n const predecessor = idx.getPredecessorKey(\n new NamedNode(childName, childNode)\n );\n return predecessor ? predecessor.name : null;\n } else {\n return this.children_.getPredecessorKey(childName);\n }\n }\n\n getFirstChildName(indexDefinition: Index): string | null {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n const minKey = idx.minKey();\n return minKey && minKey.name;\n } else {\n return this.children_.minKey();\n }\n }\n\n getFirstChild(indexDefinition: Index): NamedNode | null {\n const minKey = this.getFirstChildName(indexDefinition);\n if (minKey) {\n return new NamedNode(minKey, this.children_.get(minKey));\n } else {\n return null;\n }\n }\n\n /**\n * Given an index, return the key name of the largest value we have, according to that index\n */\n getLastChildName(indexDefinition: Index): string | null {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n const maxKey = idx.maxKey();\n return maxKey && maxKey.name;\n } else {\n return this.children_.maxKey();\n }\n }\n\n getLastChild(indexDefinition: Index): NamedNode | null {\n const maxKey = this.getLastChildName(indexDefinition);\n if (maxKey) {\n return new NamedNode(maxKey, this.children_.get(maxKey));\n } else {\n return null;\n }\n }\n forEachChild(\n index: Index,\n action: (key: string, node: Node) => boolean | void\n ): boolean {\n const idx = this.resolveIndex_(index);\n if (idx) {\n return idx.inorderTraversal(wrappedNode => {\n return action(wrappedNode.name, wrappedNode.node);\n });\n } else {\n return this.children_.inorderTraversal(action);\n }\n }\n\n getIterator(\n indexDefinition: Index\n ): SortedMapIterator {\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\n }\n\n getIteratorFrom(\n startPost: NamedNode,\n indexDefinition: Index\n ): SortedMapIterator {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getIteratorFrom(startPost, key => key);\n } else {\n const iterator = this.children_.getIteratorFrom(\n startPost.name,\n NamedNode.Wrap\n );\n let next = iterator.peek();\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n }\n\n getReverseIterator(\n indexDefinition: Index\n ): SortedMapIterator {\n return this.getReverseIteratorFrom(\n indexDefinition.maxPost(),\n indexDefinition\n );\n }\n\n getReverseIteratorFrom(\n endPost: NamedNode,\n indexDefinition: Index\n ): SortedMapIterator {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getReverseIteratorFrom(endPost, key => {\n return key;\n });\n } else {\n const iterator = this.children_.getReverseIteratorFrom(\n endPost.name,\n NamedNode.Wrap\n );\n let next = iterator.peek();\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n }\n compareTo(other: ChildrenNode): number {\n if (this.isEmpty()) {\n if (other.isEmpty()) {\n return 0;\n } else {\n return -1;\n }\n } else if (other.isLeafNode() || other.isEmpty()) {\n return 1;\n } else if (other === MAX_NODE) {\n return -1;\n } else {\n // Must be another node with children.\n return 0;\n }\n }\n withIndex(indexDefinition: Index): Node {\n if (\n indexDefinition === KEY_INDEX ||\n this.indexMap_.hasIndex(indexDefinition)\n ) {\n return this;\n } else {\n const newIndexMap = this.indexMap_.addIndex(\n indexDefinition,\n this.children_\n );\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\n }\n }\n isIndexed(index: Index): boolean {\n return index === KEY_INDEX || this.indexMap_.hasIndex(index);\n }\n equals(other: Node): boolean {\n if (other === this) {\n return true;\n } else if (other.isLeafNode()) {\n return false;\n } else {\n const otherChildrenNode = other as ChildrenNode;\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\n return false;\n } else if (\n this.children_.count() === otherChildrenNode.children_.count()\n ) {\n const thisIter = this.getIterator(PRIORITY_INDEX);\n const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);\n let thisCurrent = thisIter.getNext();\n let otherCurrent = otherIter.getNext();\n while (thisCurrent && otherCurrent) {\n if (\n thisCurrent.name !== otherCurrent.name ||\n !thisCurrent.node.equals(otherCurrent.node)\n ) {\n return false;\n }\n thisCurrent = thisIter.getNext();\n otherCurrent = otherIter.getNext();\n }\n return thisCurrent === null && otherCurrent === null;\n } else {\n return false;\n }\n }\n }\n\n /**\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\n * instead.\n *\n */\n private resolveIndex_(\n indexDefinition: Index\n ): SortedMap | null {\n if (indexDefinition === KEY_INDEX) {\n return null;\n } else {\n return this.indexMap_.get(indexDefinition.toString());\n }\n }\n}\n\nexport class MaxNode extends ChildrenNode {\n constructor() {\n super(\n new SortedMap(NAME_COMPARATOR),\n ChildrenNode.EMPTY_NODE,\n IndexMap.Default\n );\n }\n\n compareTo(other: Node): number {\n if (other === this) {\n return 0;\n } else {\n return 1;\n }\n }\n\n equals(other: Node): boolean {\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\n return other === this;\n }\n\n getPriority(): MaxNode {\n return this;\n }\n\n getImmediateChild(childName: string): ChildrenNode {\n return ChildrenNode.EMPTY_NODE;\n }\n\n isEmpty(): boolean {\n return false;\n }\n}\n\n/**\n * Marker that will sort higher than any other snapshot.\n */\nexport const MAX_NODE = new MaxNode();\n\n/**\n * Document NamedNode extensions\n */\ndeclare module './Node' {\n interface NamedNode {\n MIN: NamedNode;\n MAX: NamedNode;\n }\n}\n\nObject.defineProperties(NamedNode, {\n MIN: {\n value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)\n },\n MAX: {\n value: new NamedNode(MAX_NAME, MAX_NODE)\n }\n});\n\n/**\n * Reference Extensions\n */\nKeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\nLeafNode.__childrenNodeConstructor = ChildrenNode;\nsetMaxNode(MAX_NODE);\nsetPriorityMaxNode(MAX_NODE);\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains, assert } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport { SortedMap } from '../util/SortedMap';\nimport { each } from '../util/util';\n\nimport { ChildrenNode } from './ChildrenNode';\nimport { buildChildSet } from './childSet';\nimport { NAME_COMPARATOR, NAME_ONLY_COMPARATOR } from './comparators';\nimport { PRIORITY_INDEX, setNodeFromJSON } from './indexes/PriorityIndex';\nimport { IndexMap } from './IndexMap';\nimport { LeafNode } from './LeafNode';\nimport { NamedNode, Node } from './Node';\n\nconst USE_HINZE = true;\n\n/**\n * Constructs a snapshot node representing the passed JSON and returns it.\n * @param json - JSON to create a node for.\n * @param priority - Optional priority to use. This will be ignored if the\n * passed JSON contains a .priority property.\n */\nexport function nodeFromJSON(\n json: unknown | null,\n priority: unknown = null\n): Node {\n if (json === null) {\n return ChildrenNode.EMPTY_NODE;\n }\n\n if (typeof json === 'object' && '.priority' in json) {\n priority = json['.priority'];\n }\n\n assert(\n priority === null ||\n typeof priority === 'string' ||\n typeof priority === 'number' ||\n (typeof priority === 'object' && '.sv' in (priority as object)),\n 'Invalid priority type found: ' + typeof priority\n );\n\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\n json = json['.value'];\n }\n\n // Valid leaf nodes include non-objects or server-value wrapper objects\n if (typeof json !== 'object' || '.sv' in json) {\n const jsonLeaf = json as string | number | boolean | Indexable;\n return new LeafNode(jsonLeaf, nodeFromJSON(priority));\n }\n\n if (!(json instanceof Array) && USE_HINZE) {\n const children: NamedNode[] = [];\n let childrenHavePriority = false;\n const hinzeJsonObj = json;\n each(hinzeJsonObj, (key, child) => {\n if (key.substring(0, 1) !== '.') {\n // Ignore metadata nodes\n const childNode = nodeFromJSON(child);\n if (!childNode.isEmpty()) {\n childrenHavePriority =\n childrenHavePriority || !childNode.getPriority().isEmpty();\n children.push(new NamedNode(key, childNode));\n }\n }\n });\n\n if (children.length === 0) {\n return ChildrenNode.EMPTY_NODE;\n }\n\n const childSet = buildChildSet(\n children,\n NAME_ONLY_COMPARATOR,\n namedNode => namedNode.name,\n NAME_COMPARATOR\n ) as SortedMap;\n if (childrenHavePriority) {\n const sortedChildSet = buildChildSet(\n children,\n PRIORITY_INDEX.getCompare()\n );\n return new ChildrenNode(\n childSet,\n nodeFromJSON(priority),\n new IndexMap(\n { '.priority': sortedChildSet },\n { '.priority': PRIORITY_INDEX }\n )\n );\n } else {\n return new ChildrenNode(\n childSet,\n nodeFromJSON(priority),\n IndexMap.Default\n );\n }\n } else {\n let node: Node = ChildrenNode.EMPTY_NODE;\n each(json, (key: string, childData: unknown) => {\n if (contains(json as object, key)) {\n if (key.substring(0, 1) !== '.') {\n // ignore metadata nodes.\n const childNode = nodeFromJSON(childData);\n if (childNode.isLeafNode() || !childNode.isEmpty()) {\n node = node.updateImmediateChild(key, childNode);\n }\n }\n }\n });\n\n return node.updatePriority(nodeFromJSON(priority));\n }\n}\n\nsetNodeFromJSON(nodeFromJSON);\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Path, pathGetFront, pathIsEmpty, pathSlice } from '../../util/Path';\nimport { MAX_NAME, nameCompare } from '../../util/util';\nimport { ChildrenNode, MAX_NODE } from '../ChildrenNode';\nimport { NamedNode, Node } from '../Node';\nimport { nodeFromJSON } from '../nodeFromJSON';\n\nimport { Index } from './Index';\n\nexport class PathIndex extends Index {\n constructor(private indexPath_: Path) {\n super();\n\n assert(\n !pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority',\n \"Can't create PathIndex with empty path or .priority key\"\n );\n }\n\n protected extractChild(snap: Node): Node {\n return snap.getChild(this.indexPath_);\n }\n isDefinedOn(node: Node): boolean {\n return !node.getChild(this.indexPath_).isEmpty();\n }\n compare(a: NamedNode, b: NamedNode): number {\n const aChild = this.extractChild(a.node);\n const bChild = this.extractChild(b.node);\n const indexCmp = aChild.compareTo(bChild);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n makePost(indexValue: object, name: string): NamedNode {\n const valueNode = nodeFromJSON(indexValue);\n const node = ChildrenNode.EMPTY_NODE.updateChild(\n this.indexPath_,\n valueNode\n );\n return new NamedNode(name, node);\n }\n maxPost(): NamedNode {\n const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);\n return new NamedNode(MAX_NAME, node);\n }\n toString(): string {\n return pathSlice(this.indexPath_, 0).join('/');\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare } from '../../util/util';\nimport { NamedNode, Node } from '../Node';\nimport { nodeFromJSON } from '../nodeFromJSON';\n\nimport { Index } from './Index';\n\nexport class ValueIndex extends Index {\n compare(a: NamedNode, b: NamedNode): number {\n const indexCmp = a.node.compareTo(b.node);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n isDefinedOn(node: Node): boolean {\n return true;\n }\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return !oldNode.equals(newNode);\n }\n minPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n maxPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MAX;\n }\n\n makePost(indexValue: object, name: string): NamedNode {\n const valueNode = nodeFromJSON(indexValue);\n return new NamedNode(name, valueNode);\n }\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString(): string {\n return '.value';\n }\n}\n\nexport const VALUE_INDEX = new ValueIndex();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\n\nexport const enum ChangeType {\n /** Event type for a child added */\n CHILD_ADDED = 'child_added',\n /** Event type for a child removed */\n CHILD_REMOVED = 'child_removed',\n /** Event type for a child changed */\n CHILD_CHANGED = 'child_changed',\n /** Event type for a child moved */\n CHILD_MOVED = 'child_moved',\n /** Event type for a value change */\n VALUE = 'value'\n}\n\nexport interface Change {\n /** @param type - The event type */\n type: ChangeType;\n /** @param snapshotNode - The data */\n snapshotNode: Node;\n /** @param childName - The name for this child, if it's a child even */\n childName?: string;\n /** @param oldSnap - Used for intermediate processing of child changed events */\n oldSnap?: Node;\n /** * @param prevName - The name for the previous child, if applicable */\n prevName?: string | null;\n}\n\nexport function changeValue(snapshotNode: Node): Change {\n return { type: ChangeType.VALUE, snapshotNode };\n}\n\nexport function changeChildAdded(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_ADDED, snapshotNode, childName };\n}\n\nexport function changeChildRemoved(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_REMOVED, snapshotNode, childName };\n}\n\nexport function changeChildChanged(\n childName: string,\n snapshotNode: Node,\n oldSnap: Node\n): Change {\n return {\n type: ChangeType.CHILD_CHANGED,\n snapshotNode,\n childName,\n oldSnap\n };\n}\n\nexport function changeChildMoved(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_MOVED, snapshotNode, childName };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { PRIORITY_INDEX } from '../../snap/indexes/PriorityIndex';\nimport { Node } from '../../snap/Node';\nimport { Path } from '../../util/Path';\nimport {\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from '../Change';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\n\nimport { NodeFilter } from './NodeFilter';\n\n/**\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\n */\nexport class IndexedFilter implements NodeFilter {\n constructor(private readonly index_: Index) {}\n\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n assert(\n snap.isIndexed(this.index_),\n 'A node must be indexed if only a child is updated'\n );\n const oldChild = snap.getImmediateChild(key);\n // Check if anything actually changed.\n if (\n oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))\n ) {\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\n // to avoid treating these cases as \"nothing changed.\"\n if (oldChild.isEmpty() === newChild.isEmpty()) {\n // Nothing changed.\n\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\n return snap;\n }\n }\n\n if (optChangeAccumulator != null) {\n if (newChild.isEmpty()) {\n if (snap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(\n changeChildRemoved(key, oldChild)\n );\n } else {\n assert(\n snap.isLeafNode(),\n 'A child remove without an old child only makes sense on a leaf node'\n );\n }\n } else if (oldChild.isEmpty()) {\n optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));\n } else {\n optChangeAccumulator.trackChildChange(\n changeChildChanged(key, newChild, oldChild)\n );\n }\n }\n if (snap.isLeafNode() && newChild.isEmpty()) {\n return snap;\n } else {\n // Make sure the node is indexed\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\n }\n }\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (optChangeAccumulator != null) {\n if (!oldSnap.isLeafNode()) {\n oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (!newSnap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(\n changeChildRemoved(key, childNode)\n );\n }\n });\n }\n if (!newSnap.isLeafNode()) {\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (oldSnap.hasChild(key)) {\n const oldChild = oldSnap.getImmediateChild(key);\n if (!oldChild.equals(childNode)) {\n optChangeAccumulator.trackChildChange(\n changeChildChanged(key, childNode, oldChild)\n );\n }\n } else {\n optChangeAccumulator.trackChildChange(\n changeChildAdded(key, childNode)\n );\n }\n });\n }\n }\n return newSnap.withIndex(this.index_);\n }\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n if (oldSnap.isEmpty()) {\n return ChildrenNode.EMPTY_NODE;\n } else {\n return oldSnap.updatePriority(newPriority);\n }\n }\n filtersNodes(): boolean {\n return false;\n }\n getIndexedFilter(): IndexedFilter {\n return this;\n }\n getIndex(): Index {\n return this.index_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NamedNode, Node } from '../../../core/snap/Node';\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { PRIORITY_INDEX } from '../../snap/indexes/PriorityIndex';\nimport { Path } from '../../util/Path';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\nimport { QueryParams } from '../QueryParams';\n\nimport { IndexedFilter } from './IndexedFilter';\nimport { NodeFilter } from './NodeFilter';\n\n/**\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n */\nexport class RangedFilter implements NodeFilter {\n private indexedFilter_: IndexedFilter;\n\n private index_: Index;\n\n private startPost_: NamedNode;\n\n private endPost_: NamedNode;\n\n private startIsInclusive_: boolean;\n\n private endIsInclusive_: boolean;\n\n constructor(params: QueryParams) {\n this.indexedFilter_ = new IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n this.startIsInclusive_ = !params.startAfterSet_;\n this.endIsInclusive_ = !params.endBeforeSet_;\n }\n\n getStartPost(): NamedNode {\n return this.startPost_;\n }\n\n getEndPost(): NamedNode {\n return this.endPost_;\n }\n\n matches(node: NamedNode): boolean {\n const isWithinStart = this.startIsInclusive_\n ? this.index_.compare(this.getStartPost(), node) <= 0\n : this.index_.compare(this.getStartPost(), node) < 0;\n const isWithinEnd = this.endIsInclusive_\n ? this.index_.compare(node, this.getEndPost()) <= 0\n : this.index_.compare(node, this.getEndPost()) < 0;\n return isWithinStart && isWithinEnd;\n }\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (!this.matches(new NamedNode(key, newChild))) {\n newChild = ChildrenNode.EMPTY_NODE;\n }\n return this.indexedFilter_.updateChild(\n snap,\n key,\n newChild,\n affectedPath,\n source,\n optChangeAccumulator\n );\n }\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode.EMPTY_NODE;\n }\n let filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\n const self = this;\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (!self.matches(new NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(\n oldSnap,\n filtered,\n optChangeAccumulator\n );\n }\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n // Don't support priorities on queries\n return oldSnap;\n }\n filtersNodes(): boolean {\n return true;\n }\n getIndexedFilter(): IndexedFilter {\n return this.indexedFilter_;\n }\n getIndex(): Index {\n return this.index_;\n }\n\n private static getStartPost_(params: QueryParams): NamedNode {\n if (params.hasStart()) {\n const startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n } else {\n return params.getIndex().minPost();\n }\n }\n\n private static getEndPost_(params: QueryParams): NamedNode {\n if (params.hasEnd()) {\n const endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n } else {\n return params.getIndex().maxPost();\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { NamedNode, Node } from '../../snap/Node';\nimport { Path } from '../../util/Path';\nimport {\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from '../Change';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\nimport { QueryParams } from '../QueryParams';\n\nimport { IndexedFilter } from './IndexedFilter';\nimport { NodeFilter } from './NodeFilter';\nimport { RangedFilter } from './RangedFilter';\n\n/**\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n */\nexport class LimitedFilter implements NodeFilter {\n private readonly rangedFilter_: RangedFilter;\n\n private readonly index_: Index;\n\n private readonly limit_: number;\n\n private readonly reverse_: boolean;\n\n private readonly startIsInclusive_: boolean;\n\n private readonly endIsInclusive_: boolean;\n\n constructor(params: QueryParams) {\n this.rangedFilter_ = new RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n this.startIsInclusive_ = !params.startAfterSet_;\n this.endIsInclusive_ = !params.endBeforeSet_;\n }\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {\n newChild = ChildrenNode.EMPTY_NODE;\n }\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n } else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_\n .getIndexedFilter()\n .updateChild(\n snap,\n key,\n newChild,\n affectedPath,\n source,\n optChangeAccumulator\n );\n } else {\n return this.fullLimitUpdateChild_(\n snap,\n key,\n newChild,\n source,\n optChangeAccumulator\n );\n }\n }\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n let filtered;\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n } else {\n if (\n this.limit_ * 2 < newSnap.numChildren() &&\n newSnap.isIndexed(this.index_)\n ) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n // anchor to the startPost, endPost, or last element as appropriate\n let iterator;\n if (this.reverse_) {\n iterator = (newSnap as ChildrenNode).getReverseIteratorFrom(\n this.rangedFilter_.getEndPost(),\n this.index_\n );\n } else {\n iterator = (newSnap as ChildrenNode).getIteratorFrom(\n this.rangedFilter_.getStartPost(),\n this.index_\n );\n }\n let count = 0;\n while (iterator.hasNext() && count < this.limit_) {\n const next = iterator.getNext();\n if (!this.withinDirectionalStart(next)) {\n // if we have not reached the start, skip to the next element\n continue;\n } else if (!this.withinDirectionalEnd(next)) {\n // if we have reached the end, stop adding elements\n break;\n } else {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\n }\n }\n } else {\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(\n ChildrenNode.EMPTY_NODE\n ) as ChildrenNode;\n\n let iterator;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n } else {\n iterator = filtered.getIterator(this.index_);\n }\n\n let count = 0;\n while (iterator.hasNext()) {\n const next = iterator.getNext();\n const inRange =\n count < this.limit_ &&\n this.withinDirectionalStart(next) &&\n this.withinDirectionalEnd(next);\n if (inRange) {\n count++;\n } else {\n filtered = filtered.updateImmediateChild(\n next.name,\n ChildrenNode.EMPTY_NODE\n );\n }\n }\n }\n }\n return this.rangedFilter_\n .getIndexedFilter()\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n }\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n // Don't support priorities on queries\n return oldSnap;\n }\n filtersNodes(): boolean {\n return true;\n }\n getIndexedFilter(): IndexedFilter {\n return this.rangedFilter_.getIndexedFilter();\n }\n getIndex(): Index {\n return this.index_;\n }\n\n private fullLimitUpdateChild_(\n snap: Node,\n childKey: string,\n childSnap: Node,\n source: CompleteChildSource,\n changeAccumulator: ChildChangeAccumulator | null\n ): Node {\n // TODO: rename all cache stuff etc to general snap terminology\n let cmp;\n if (this.reverse_) {\n const indexCmp = this.index_.getCompare();\n cmp = (a: NamedNode, b: NamedNode) => indexCmp(b, a);\n } else {\n cmp = this.index_.getCompare();\n }\n const oldEventCache = snap as ChildrenNode;\n assert(oldEventCache.numChildren() === this.limit_, '');\n const newChildNamedNode = new NamedNode(childKey, childSnap);\n const windowBoundary = this.reverse_\n ? oldEventCache.getFirstChild(this.index_)\n : (oldEventCache.getLastChild(this.index_) as NamedNode);\n const inRange = this.rangedFilter_.matches(newChildNamedNode);\n if (oldEventCache.hasChild(childKey)) {\n const oldChildSnap = oldEventCache.getImmediateChild(childKey);\n let nextChild = source.getChildAfterChild(\n this.index_,\n windowBoundary,\n this.reverse_\n );\n while (\n nextChild != null &&\n (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))\n ) {\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\n // the limited filter...\n nextChild = source.getChildAfterChild(\n this.index_,\n nextChild,\n this.reverse_\n );\n }\n const compareNext =\n nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n const remainsInWindow =\n inRange && !childSnap.isEmpty() && compareNext >= 0;\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildChanged(childKey, childSnap, oldChildSnap)\n );\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n } else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildRemoved(childKey, oldChildSnap)\n );\n }\n const newEventCache = oldEventCache.updateImmediateChild(\n childKey,\n ChildrenNode.EMPTY_NODE\n );\n const nextChildInRange =\n nextChild != null && this.rangedFilter_.matches(nextChild);\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildAdded(nextChild.name, nextChild.node)\n );\n }\n return newEventCache.updateImmediateChild(\n nextChild.name,\n nextChild.node\n );\n } else {\n return newEventCache;\n }\n }\n } else if (childSnap.isEmpty()) {\n // we're deleting a node, but it was not in the window, so ignore it\n return snap;\n } else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildRemoved(windowBoundary.name, windowBoundary.node)\n );\n changeAccumulator.trackChildChange(\n changeChildAdded(childKey, childSnap)\n );\n }\n return oldEventCache\n .updateImmediateChild(childKey, childSnap)\n .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);\n } else {\n return snap;\n }\n } else {\n return snap;\n }\n }\n\n private withinDirectionalStart = (node: NamedNode) =>\n this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);\n\n private withinDirectionalEnd = (node: NamedNode) =>\n this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);\n\n private withinStartPost = (node: NamedNode) => {\n const compareRes = this.index_.compare(\n this.rangedFilter_.getStartPost(),\n node\n );\n return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;\n };\n\n private withinEndPost = (node: NamedNode) => {\n const compareRes = this.index_.compare(\n node,\n this.rangedFilter_.getEndPost()\n );\n return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, stringify } from '@firebase/util';\n\nimport { Index } from '../snap/indexes/Index';\nimport { KEY_INDEX } from '../snap/indexes/KeyIndex';\nimport { PathIndex } from '../snap/indexes/PathIndex';\nimport { PRIORITY_INDEX, PriorityIndex } from '../snap/indexes/PriorityIndex';\nimport { VALUE_INDEX } from '../snap/indexes/ValueIndex';\nimport { MAX_NAME, MIN_NAME } from '../util/util';\n\nimport { IndexedFilter } from './filter/IndexedFilter';\nimport { LimitedFilter } from './filter/LimitedFilter';\nimport { NodeFilter } from './filter/NodeFilter';\nimport { RangedFilter } from './filter/RangedFilter';\n\n/**\n * Wire Protocol Constants\n */\nconst enum WIRE_PROTOCOL_CONSTANTS {\n INDEX_START_VALUE = 'sp',\n INDEX_START_NAME = 'sn',\n INDEX_START_IS_INCLUSIVE = 'sin',\n INDEX_END_VALUE = 'ep',\n INDEX_END_NAME = 'en',\n INDEX_END_IS_INCLUSIVE = 'ein',\n LIMIT = 'l',\n VIEW_FROM = 'vf',\n VIEW_FROM_LEFT = 'l',\n VIEW_FROM_RIGHT = 'r',\n INDEX = 'i'\n}\n\n/**\n * REST Query Constants\n */\nconst enum REST_QUERY_CONSTANTS {\n ORDER_BY = 'orderBy',\n PRIORITY_INDEX = '$priority',\n VALUE_INDEX = '$value',\n KEY_INDEX = '$key',\n START_AFTER = 'startAfter',\n START_AT = 'startAt',\n END_AT = 'endAt',\n END_BEFORE = 'endBefore',\n LIMIT_TO_FIRST = 'limitToFirst',\n LIMIT_TO_LAST = 'limitToLast'\n}\n\n/**\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\n * user-facing API level, so it is not done here.\n *\n * @internal\n */\nexport class QueryParams {\n limitSet_ = false;\n startSet_ = false;\n startNameSet_ = false;\n startAfterSet_ = false; // can only be true if startSet_ is true\n endSet_ = false;\n endNameSet_ = false;\n endBeforeSet_ = false; // can only be true if endSet_ is true\n limit_ = 0;\n viewFrom_ = '';\n indexStartValue_: unknown | null = null;\n indexStartName_ = '';\n indexEndValue_: unknown | null = null;\n indexEndName_ = '';\n index_: PriorityIndex = PRIORITY_INDEX;\n\n hasStart(): boolean {\n return this.startSet_;\n }\n\n /**\n * @returns True if it would return from left.\n */\n isViewFromLeft(): boolean {\n if (this.viewFrom_ === '') {\n // limit(), rather than limitToFirst or limitToLast was called.\n // This means that only one of startSet_ and endSet_ is true. Use them\n // to calculate which side of the view to anchor to. If neither is set,\n // anchor to the end.\n return this.startSet_;\n } else {\n return this.viewFrom_ === WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n }\n }\n\n /**\n * Only valid to call if hasStart() returns true\n */\n getIndexStartValue(): unknown {\n assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n }\n\n /**\n * Only valid to call if hasStart() returns true.\n * Returns the starting key name for the range defined by these query parameters\n */\n getIndexStartName(): string {\n assert(this.startSet_, 'Only valid if start has been set');\n if (this.startNameSet_) {\n return this.indexStartName_;\n } else {\n return MIN_NAME;\n }\n }\n\n hasEnd(): boolean {\n return this.endSet_;\n }\n\n /**\n * Only valid to call if hasEnd() returns true.\n */\n getIndexEndValue(): unknown {\n assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n }\n\n /**\n * Only valid to call if hasEnd() returns true.\n * Returns the end key name for the range defined by these query parameters\n */\n getIndexEndName(): string {\n assert(this.endSet_, 'Only valid if end has been set');\n if (this.endNameSet_) {\n return this.indexEndName_;\n } else {\n return MAX_NAME;\n }\n }\n\n hasLimit(): boolean {\n return this.limitSet_;\n }\n\n /**\n * @returns True if a limit has been set and it has been explicitly anchored\n */\n hasAnchoredLimit(): boolean {\n return this.limitSet_ && this.viewFrom_ !== '';\n }\n\n /**\n * Only valid to call if hasLimit() returns true\n */\n getLimit(): number {\n assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n }\n\n getIndex(): Index {\n return this.index_;\n }\n\n loadsAllData(): boolean {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n }\n\n isDefault(): boolean {\n return this.loadsAllData() && this.index_ === PRIORITY_INDEX;\n }\n\n copy(): QueryParams {\n const copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.startAfterSet_ = this.startAfterSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.endBeforeSet_ = this.endBeforeSet_;\n copy.indexEndValue_ = this.indexEndValue_;\n copy.endNameSet_ = this.endNameSet_;\n copy.indexEndName_ = this.indexEndName_;\n copy.index_ = this.index_;\n copy.viewFrom_ = this.viewFrom_;\n return copy;\n }\n}\n\nexport function queryParamsGetNodeFilter(queryParams: QueryParams): NodeFilter {\n if (queryParams.loadsAllData()) {\n return new IndexedFilter(queryParams.getIndex());\n } else if (queryParams.hasLimit()) {\n return new LimitedFilter(queryParams);\n } else {\n return new RangedFilter(queryParams);\n }\n}\n\nexport function queryParamsLimit(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n}\n\nexport function queryParamsLimitToFirst(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n return newParams;\n}\n\nexport function queryParamsLimitToLast(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n return newParams;\n}\n\nexport function queryParamsStartAt(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.startSet_ = true;\n if (indexValue === undefined) {\n indexValue = null;\n }\n newParams.indexStartValue_ = indexValue;\n if (key != null) {\n newParams.startNameSet_ = true;\n newParams.indexStartName_ = key;\n } else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n return newParams;\n}\n\nexport function queryParamsStartAfter(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n let params: QueryParams;\n if (queryParams.index_ === KEY_INDEX || !!key) {\n params = queryParamsStartAt(queryParams, indexValue, key);\n } else {\n params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);\n }\n params.startAfterSet_ = true;\n return params;\n}\n\nexport function queryParamsEndAt(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.endSet_ = true;\n if (indexValue === undefined) {\n indexValue = null;\n }\n newParams.indexEndValue_ = indexValue;\n if (key !== undefined) {\n newParams.endNameSet_ = true;\n newParams.indexEndName_ = key;\n } else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n return newParams;\n}\n\nexport function queryParamsEndBefore(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n let params: QueryParams;\n if (queryParams.index_ === KEY_INDEX || !!key) {\n params = queryParamsEndAt(queryParams, indexValue, key);\n } else {\n params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);\n }\n params.endBeforeSet_ = true;\n return params;\n}\n\nexport function queryParamsOrderBy(\n queryParams: QueryParams,\n index: Index\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.index_ = index;\n return newParams;\n}\n\n/**\n * Returns a set of REST query string parameters representing this query.\n *\n * @returns query string parameters\n */\nexport function queryParamsToRestQueryStringParameters(\n queryParams: QueryParams\n): Record {\n const qs: Record = {};\n\n if (queryParams.isDefault()) {\n return qs;\n }\n\n let orderBy;\n if (queryParams.index_ === PRIORITY_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.PRIORITY_INDEX;\n } else if (queryParams.index_ === VALUE_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.VALUE_INDEX;\n } else if (queryParams.index_ === KEY_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.KEY_INDEX;\n } else {\n assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');\n orderBy = queryParams.index_.toString();\n }\n qs[REST_QUERY_CONSTANTS.ORDER_BY] = stringify(orderBy);\n\n if (queryParams.startSet_) {\n const startParam = queryParams.startAfterSet_\n ? REST_QUERY_CONSTANTS.START_AFTER\n : REST_QUERY_CONSTANTS.START_AT;\n qs[startParam] = stringify(queryParams.indexStartValue_);\n if (queryParams.startNameSet_) {\n qs[startParam] += ',' + stringify(queryParams.indexStartName_);\n }\n }\n\n if (queryParams.endSet_) {\n const endParam = queryParams.endBeforeSet_\n ? REST_QUERY_CONSTANTS.END_BEFORE\n : REST_QUERY_CONSTANTS.END_AT;\n qs[endParam] = stringify(queryParams.indexEndValue_);\n if (queryParams.endNameSet_) {\n qs[endParam] += ',' + stringify(queryParams.indexEndName_);\n }\n }\n\n if (queryParams.limitSet_) {\n if (queryParams.isViewFromLeft()) {\n qs[REST_QUERY_CONSTANTS.LIMIT_TO_FIRST] = queryParams.limit_;\n } else {\n qs[REST_QUERY_CONSTANTS.LIMIT_TO_LAST] = queryParams.limit_;\n }\n }\n\n return qs;\n}\n\nexport function queryParamsGetQueryObject(\n queryParams: QueryParams\n): Record {\n const obj: Record = {};\n if (queryParams.startSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] =\n queryParams.indexStartValue_;\n if (queryParams.startNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] =\n queryParams.indexStartName_;\n }\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE] =\n !queryParams.startAfterSet_;\n }\n if (queryParams.endSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = queryParams.indexEndValue_;\n if (queryParams.endNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = queryParams.indexEndName_;\n }\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE] =\n !queryParams.endBeforeSet_;\n }\n if (queryParams.limitSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = queryParams.limit_;\n let viewFrom = queryParams.viewFrom_;\n if (viewFrom === '') {\n if (queryParams.isViewFromLeft()) {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n } else {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n }\n }\n obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom;\n }\n // For now, priority index is the default, so we only specify if it's some other index\n if (queryParams.index_ !== PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = queryParams.index_.toString();\n }\n return obj;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n jsonEval,\n safeGet,\n querystring,\n Deferred\n} from '@firebase/util';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { logWrapper, warn } from './util/util';\nimport { QueryContext } from './view/EventRegistration';\nimport { queryParamsToRestQueryStringParameters } from './view/QueryParams';\n\n/**\n * An implementation of ServerActions that communicates with the server via REST requests.\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\n * persistent connection (using WebSockets or long-polling)\n */\nexport class ReadonlyRestClient extends ServerActions {\n reportStats(stats: { [k: string]: unknown }): void {\n throw new Error('Method not implemented.');\n }\n\n /** @private {function(...[*])} */\n private log_: (...args: unknown[]) => void = logWrapper('p:rest:');\n\n /**\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\n * that's been removed. :-/\n */\n private listens_: { [k: string]: object } = {};\n\n static getListenId_(query: QueryContext, tag?: number | null): string {\n if (tag !== undefined) {\n return 'tag$' + tag;\n } else {\n assert(\n query._queryParams.isDefault(),\n \"should have a tag if it's not a default query.\"\n );\n return query._path.toString();\n }\n }\n\n /**\n * @param repoInfo_ - Data about the namespace we are connecting to\n * @param onDataUpdate_ - A callback for new data from the server\n */\n constructor(\n private repoInfo_: RepoInfo,\n private onDataUpdate_: (\n a: string,\n b: unknown,\n c: boolean,\n d: number | null\n ) => void,\n private authTokenProvider_: AuthTokenProvider,\n private appCheckTokenProvider_: AppCheckTokenProvider\n ) {\n super();\n }\n\n /** @inheritDoc */\n listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ) {\n const pathString = query._path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);\n\n // Mark this listener so we can tell if it's removed.\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\n const thisListen = {};\n this.listens_[listenId] = thisListen;\n\n const queryStringParameters = queryParamsToRestQueryStringParameters(\n query._queryParams\n );\n\n this.restRequest_(\n pathString + '.json',\n queryStringParameters,\n (error, result) => {\n let data = result;\n\n if (error === 404) {\n data = null;\n error = null;\n }\n\n if (error === null) {\n this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n }\n\n if (safeGet(this.listens_, listenId) === thisListen) {\n let status;\n if (!error) {\n status = 'ok';\n } else if (error === 401) {\n status = 'permission_denied';\n } else {\n status = 'rest_error:' + error;\n }\n\n onComplete(status, null);\n }\n }\n );\n }\n\n /** @inheritDoc */\n unlisten(query: QueryContext, tag: number | null) {\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n }\n\n get(query: QueryContext): Promise {\n const queryStringParameters = queryParamsToRestQueryStringParameters(\n query._queryParams\n );\n\n const pathString = query._path.toString();\n\n const deferred = new Deferred();\n\n this.restRequest_(\n pathString + '.json',\n queryStringParameters,\n (error, result) => {\n let data = result;\n\n if (error === 404) {\n data = null;\n error = null;\n }\n\n if (error === null) {\n this.onDataUpdate_(\n pathString,\n data,\n /*isMerge=*/ false,\n /*tag=*/ null\n );\n deferred.resolve(data as string);\n } else {\n deferred.reject(new Error(data as string));\n }\n }\n );\n return deferred.promise;\n }\n\n /** @inheritDoc */\n refreshAuthToken(token: string) {\n // no-op since we just always call getToken.\n }\n\n /**\n * Performs a REST request to the given path, with the provided query string parameters,\n * and any auth credentials we have.\n */\n private restRequest_(\n pathString: string,\n queryStringParameters: { [k: string]: string | number } = {},\n callback: ((a: number | null, b?: unknown) => void) | null\n ) {\n queryStringParameters['format'] = 'export';\n\n return Promise.all([\n this.authTokenProvider_.getToken(/*forceRefresh=*/ false),\n this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)\n ]).then(([authToken, appCheckToken]) => {\n if (authToken && authToken.accessToken) {\n queryStringParameters['auth'] = authToken.accessToken;\n }\n if (appCheckToken && appCheckToken.token) {\n queryStringParameters['ac'] = appCheckToken.token;\n }\n\n const url =\n (this.repoInfo_.secure ? 'https://' : 'http://') +\n this.repoInfo_.host +\n pathString +\n '?' +\n 'ns=' +\n this.repoInfo_.namespace +\n querystring(queryStringParameters);\n\n this.log_('Sending REST request for ' + url);\n const xhr = new XMLHttpRequest();\n xhr.onreadystatechange = () => {\n if (callback && xhr.readyState === 4) {\n this.log_(\n 'REST Response for ' + url + ' received. status:',\n xhr.status,\n 'response:',\n xhr.responseText\n );\n let res = null;\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = jsonEval(xhr.responseText);\n } catch (e) {\n warn(\n 'Failed to parse JSON response for ' +\n url +\n ': ' +\n xhr.responseText\n );\n }\n callback(null, res);\n } else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n warn(\n 'Got unsuccessful REST response for ' +\n url +\n ' Status: ' +\n xhr.status\n );\n }\n callback(xhr.status);\n }\n callback = null;\n }\n };\n\n xhr.open('GET', url, /*asynchronous=*/ true);\n xhr.send();\n });\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { Path } from './util/Path';\n\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n */\nexport class SnapshotHolder {\n private rootNode_: Node = ChildrenNode.EMPTY_NODE;\n\n getNode(path: Path): Node {\n return this.rootNode_.getChild(path);\n }\n\n updateSnapshot(path: Path, newSnapshotNode: Node) {\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { Node } from './snap/Node';\nimport { Path, pathGetFront, pathIsEmpty, pathPopFront } from './util/Path';\n\n/**\n * Helper class to store a sparse set of snapshots.\n */\nexport interface SparseSnapshotTree {\n value: Node | null;\n readonly children: Map;\n}\n\nexport function newSparseSnapshotTree(): SparseSnapshotTree {\n return {\n value: null,\n children: new Map()\n };\n}\n\n/**\n * Gets the node stored at the given path if one exists.\n * Only seems to be used in tests.\n *\n * @param path - Path to look up snapshot for.\n * @returns The retrieved node, or null.\n */\nexport function sparseSnapshotTreeFind(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path\n): Node | null {\n if (sparseSnapshotTree.value != null) {\n return sparseSnapshotTree.value.getChild(path);\n } else if (!pathIsEmpty(path) && sparseSnapshotTree.children.size > 0) {\n const childKey = pathGetFront(path);\n path = pathPopFront(path);\n if (sparseSnapshotTree.children.has(childKey)) {\n const childTree = sparseSnapshotTree.children.get(childKey);\n return sparseSnapshotTreeFind(childTree, path);\n } else {\n return null;\n }\n } else {\n return null;\n }\n}\n\n/**\n * Stores the given node at the specified path. If there is already a node\n * at a shallower path, it merges the new data into that snapshot node.\n *\n * @param path - Path to look up snapshot for.\n * @param data - The new data, or null.\n */\nexport function sparseSnapshotTreeRemember(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path,\n data: Node\n): void {\n if (pathIsEmpty(path)) {\n sparseSnapshotTree.value = data;\n sparseSnapshotTree.children.clear();\n } else if (sparseSnapshotTree.value !== null) {\n sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);\n } else {\n const childKey = pathGetFront(path);\n if (!sparseSnapshotTree.children.has(childKey)) {\n sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());\n }\n\n const child = sparseSnapshotTree.children.get(childKey);\n path = pathPopFront(path);\n sparseSnapshotTreeRemember(child, path, data);\n }\n}\n\n/**\n * Purge the data at path from the cache.\n *\n * @param path - Path to look up snapshot for.\n * @returns True if this node should now be removed.\n */\nexport function sparseSnapshotTreeForget(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path\n): boolean {\n if (pathIsEmpty(path)) {\n sparseSnapshotTree.value = null;\n sparseSnapshotTree.children.clear();\n return true;\n } else {\n if (sparseSnapshotTree.value !== null) {\n if (sparseSnapshotTree.value.isLeafNode()) {\n // We're trying to forget a node that doesn't exist\n return false;\n } else {\n const value = sparseSnapshotTree.value;\n sparseSnapshotTree.value = null;\n\n value.forEachChild(PRIORITY_INDEX, (key, tree) => {\n sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);\n });\n\n return sparseSnapshotTreeForget(sparseSnapshotTree, path);\n }\n } else if (sparseSnapshotTree.children.size > 0) {\n const childKey = pathGetFront(path);\n path = pathPopFront(path);\n if (sparseSnapshotTree.children.has(childKey)) {\n const safeToRemove = sparseSnapshotTreeForget(\n sparseSnapshotTree.children.get(childKey),\n path\n );\n if (safeToRemove) {\n sparseSnapshotTree.children.delete(childKey);\n }\n }\n\n return sparseSnapshotTree.children.size === 0;\n } else {\n return true;\n }\n }\n}\n\n/**\n * Recursively iterates through all of the stored tree and calls the\n * callback on each one.\n *\n * @param prefixPath - Path to look up node for.\n * @param func - The function to invoke for each tree.\n */\nexport function sparseSnapshotTreeForEachTree(\n sparseSnapshotTree: SparseSnapshotTree,\n prefixPath: Path,\n func: (a: Path, b: Node) => unknown\n): void {\n if (sparseSnapshotTree.value !== null) {\n func(prefixPath, sparseSnapshotTree.value);\n } else {\n sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {\n const path = new Path(prefixPath.toString() + '/' + key);\n sparseSnapshotTreeForEachTree(tree, path, func);\n });\n }\n}\n\n/**\n * Iterates through each immediate child and triggers the callback.\n * Only seems to be used in tests.\n *\n * @param func - The function to invoke for each child.\n */\nexport function sparseSnapshotTreeForEachChild(\n sparseSnapshotTree: SparseSnapshotTree,\n func: (a: string, b: SparseSnapshotTree) => void\n): void {\n sparseSnapshotTree.children.forEach((tree, key) => {\n func(key, tree);\n });\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { each } from '../util/util';\n\nimport { StatsCollection } from './StatsCollection';\n\n/**\n * Returns the delta from the previous call to get stats.\n *\n * @param collection_ - The collection to \"listen\" to.\n */\nexport class StatsListener {\n private last_: { [k: string]: number } | null = null;\n\n constructor(private collection_: StatsCollection) {}\n\n get(): { [k: string]: number } {\n const newStats = this.collection_.get();\n\n const delta = { ...newStats };\n if (this.last_) {\n each(this.last_, (stat: string, value: number) => {\n delta[stat] = delta[stat] - value;\n });\n }\n this.last_ = newStats;\n\n return delta;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains } from '@firebase/util';\n\nimport { ServerActions } from '../ServerActions';\nimport { setTimeoutNonBlocking, each } from '../util/util';\n\nimport { StatsCollection } from './StatsCollection';\nimport { StatsListener } from './StatsListener';\n\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\n// seconds to try to ensure the Firebase connection is established / settled.\nconst FIRST_STATS_MIN_TIME = 10 * 1000;\nconst FIRST_STATS_MAX_TIME = 30 * 1000;\n\n// We'll continue to report stats on average every 5 minutes.\nconst REPORT_STATS_INTERVAL = 5 * 60 * 1000;\n\nexport class StatsReporter {\n private statsListener_: StatsListener;\n statsToReport_: { [k: string]: boolean } = {};\n\n constructor(collection: StatsCollection, private server_: ServerActions) {\n this.statsListener_ = new StatsListener(collection);\n\n const timeout =\n FIRST_STATS_MIN_TIME +\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n }\n\n private reportStats_() {\n const stats = this.statsListener_.get();\n const reportedStats: typeof stats = {};\n let haveStatsToReport = false;\n\n each(stats, (stat: string, value: number) => {\n if (value > 0 && contains(this.statsToReport_, stat)) {\n reportedStats[stat] = value;\n haveStatsToReport = true;\n }\n });\n\n if (haveStatsToReport) {\n this.server_.reportStats(reportedStats);\n }\n\n // queue our next run.\n setTimeoutNonBlocking(\n this.reportStats_.bind(this),\n Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL)\n );\n }\n}\n\nexport function statsReporterIncludeStat(\n reporter: StatsReporter,\n stat: string\n) {\n reporter.statsToReport_[stat] = true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Path } from '../util/Path';\n\n/**\n *\n * @enum\n */\nexport enum OperationType {\n OVERWRITE,\n MERGE,\n ACK_USER_WRITE,\n LISTEN_COMPLETE\n}\n\n/**\n * @interface\n */\nexport interface Operation {\n source: OperationSource;\n\n type: OperationType;\n\n path: Path;\n\n operationForChild(childName: string): Operation | null;\n}\n\nexport interface OperationSource {\n fromUser: boolean;\n fromServer: boolean;\n queryId: string | null;\n tagged: boolean;\n}\n\nexport function newOperationSourceUser(): OperationSource {\n return {\n fromUser: true,\n fromServer: false,\n queryId: null,\n tagged: false\n };\n}\n\nexport function newOperationSourceServer(): OperationSource {\n return {\n fromUser: false,\n fromServer: true,\n queryId: null,\n tagged: false\n };\n}\n\nexport function newOperationSourceServerTaggedQuery(\n queryId: string\n): OperationSource {\n return {\n fromUser: false,\n fromServer: true,\n queryId,\n tagged: true\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\n\nimport { newOperationSourceUser, Operation, OperationType } from './Operation';\n\nexport class AckUserWrite implements Operation {\n /** @inheritDoc */\n type = OperationType.ACK_USER_WRITE;\n\n /** @inheritDoc */\n source = newOperationSourceUser();\n\n /**\n * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.\n */\n constructor(\n /** @inheritDoc */ public path: Path,\n /** @inheritDoc */ public affectedTree: ImmutableTree,\n /** @inheritDoc */ public revert: boolean\n ) {}\n operationForChild(childName: string): AckUserWrite {\n if (!pathIsEmpty(this.path)) {\n assert(\n pathGetFront(this.path) === childName,\n 'operationForChild called for unrelated child.'\n );\n return new AckUserWrite(\n pathPopFront(this.path),\n this.affectedTree,\n this.revert\n );\n } else if (this.affectedTree.value != null) {\n assert(\n this.affectedTree.children.isEmpty(),\n 'affectedTree should not have overlapping affected paths.'\n );\n // All child locations are affected as well; just return same operation.\n return this;\n } else {\n const childTree = this.affectedTree.subtree(new Path(childName));\n return new AckUserWrite(newEmptyPath(), childTree, this.revert);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { newEmptyPath, Path, pathIsEmpty, pathPopFront } from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './Operation';\n\nexport class ListenComplete implements Operation {\n /** @inheritDoc */\n type = OperationType.LISTEN_COMPLETE;\n\n constructor(public source: OperationSource, public path: Path) {}\n\n operationForChild(childName: string): ListenComplete {\n if (pathIsEmpty(this.path)) {\n return new ListenComplete(this.source, newEmptyPath());\n } else {\n return new ListenComplete(this.source, pathPopFront(this.path));\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\nimport { newEmptyPath, Path, pathIsEmpty, pathPopFront } from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './Operation';\n\nexport class Overwrite implements Operation {\n /** @inheritDoc */\n type = OperationType.OVERWRITE;\n\n constructor(\n public source: OperationSource,\n public path: Path,\n public snap: Node\n ) {}\n\n operationForChild(childName: string): Overwrite {\n if (pathIsEmpty(this.path)) {\n return new Overwrite(\n this.source,\n newEmptyPath(),\n this.snap.getImmediateChild(childName)\n );\n } else {\n return new Overwrite(this.source, pathPopFront(this.path), this.snap);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Node } from '../snap/Node';\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './Operation';\nimport { Overwrite } from './Overwrite';\n\nexport class Merge implements Operation {\n /** @inheritDoc */\n type = OperationType.MERGE;\n\n constructor(\n /** @inheritDoc */ public source: OperationSource,\n /** @inheritDoc */ public path: Path,\n /** @inheritDoc */ public children: ImmutableTree\n ) {}\n operationForChild(childName: string): Operation {\n if (pathIsEmpty(this.path)) {\n const childTree = this.children.subtree(new Path(childName));\n if (childTree.isEmpty()) {\n // This child is unaffected\n return null;\n } else if (childTree.value) {\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\n return new Overwrite(this.source, newEmptyPath(), childTree.value);\n } else {\n // This is a merge at a deeper level\n return new Merge(this.source, newEmptyPath(), childTree);\n }\n } else {\n assert(\n pathGetFront(this.path) === childName,\n \"Can't get a merge for a child not on the path of the operation\"\n );\n return new Merge(this.source, pathPopFront(this.path), this.children);\n }\n }\n toString(): string {\n return (\n 'Operation(' +\n this.path +\n ': ' +\n this.source.toString() +\n ' merge: ' +\n this.children.toString() +\n ')'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\nimport { Path, pathGetFront, pathIsEmpty } from '../util/Path';\n\n/**\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\n * whether a node potentially had children removed due to a filter.\n */\nexport class CacheNode {\n constructor(\n private node_: Node,\n private fullyInitialized_: boolean,\n private filtered_: boolean\n ) {}\n\n /**\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\n */\n isFullyInitialized(): boolean {\n return this.fullyInitialized_;\n }\n\n /**\n * Returns whether this node is potentially missing children due to a filter applied to the node\n */\n isFiltered(): boolean {\n return this.filtered_;\n }\n\n isCompleteForPath(path: Path): boolean {\n if (pathIsEmpty(path)) {\n return this.isFullyInitialized() && !this.filtered_;\n }\n\n const childKey = pathGetFront(path);\n return this.isCompleteForChild(childKey);\n }\n\n isCompleteForChild(key: string): boolean {\n return (\n (this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key)\n );\n }\n\n getNode(): Node {\n return this.node_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assertionError } from '@firebase/util';\n\nimport { Index } from '../snap/indexes/Index';\nimport { NamedNode, Node } from '../snap/Node';\n\nimport { Change, ChangeType, changeChildMoved } from './Change';\nimport { Event } from './Event';\nimport { EventRegistration, QueryContext } from './EventRegistration';\n\n/**\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\n * for details.\n *\n */\nexport class EventGenerator {\n index_: Index;\n\n constructor(public query_: QueryContext) {\n this.index_ = this.query_._queryParams.getIndex();\n }\n}\n\n/**\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\n *\n * Notes:\n * - child_moved events will be synthesized at this time for any child_changed events that affect\n * our index.\n * - prevName will be calculated based on the index ordering.\n */\nexport function eventGeneratorGenerateEventsForChanges(\n eventGenerator: EventGenerator,\n changes: Change[],\n eventCache: Node,\n eventRegistrations: EventRegistration[]\n): Event[] {\n const events: Event[] = [];\n const moves: Change[] = [];\n\n changes.forEach(change => {\n if (\n change.type === ChangeType.CHILD_CHANGED &&\n eventGenerator.index_.indexedValueChanged(\n change.oldSnap as Node,\n change.snapshotNode\n )\n ) {\n moves.push(changeChildMoved(change.childName, change.snapshotNode));\n }\n });\n\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_REMOVED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_ADDED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_MOVED,\n moves,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_CHANGED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.VALUE,\n changes,\n eventRegistrations,\n eventCache\n );\n\n return events;\n}\n\n/**\n * Given changes of a single change type, generate the corresponding events.\n */\nfunction eventGeneratorGenerateEventsForType(\n eventGenerator: EventGenerator,\n events: Event[],\n eventType: string,\n changes: Change[],\n registrations: EventRegistration[],\n eventCache: Node\n) {\n const filteredChanges = changes.filter(change => change.type === eventType);\n\n filteredChanges.sort((a, b) =>\n eventGeneratorCompareChanges(eventGenerator, a, b)\n );\n filteredChanges.forEach(change => {\n const materializedChange = eventGeneratorMaterializeSingleChange(\n eventGenerator,\n change,\n eventCache\n );\n registrations.forEach(registration => {\n if (registration.respondsTo(change.type)) {\n events.push(\n registration.createEvent(materializedChange, eventGenerator.query_)\n );\n }\n });\n });\n}\n\nfunction eventGeneratorMaterializeSingleChange(\n eventGenerator: EventGenerator,\n change: Change,\n eventCache: Node\n): Change {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n } else {\n change.prevName = eventCache.getPredecessorChildName(\n change.childName,\n change.snapshotNode,\n eventGenerator.index_\n );\n return change;\n }\n}\n\nfunction eventGeneratorCompareChanges(\n eventGenerator: EventGenerator,\n a: Change,\n b: Change\n) {\n if (a.childName == null || b.childName == null) {\n throw assertionError('Should only compare child_ events.');\n }\n const aWrapped = new NamedNode(a.childName, a.snapshotNode);\n const bWrapped = new NamedNode(b.childName, b.snapshotNode);\n return eventGenerator.index_.compare(aWrapped, bWrapped);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\n\nimport { CacheNode } from './CacheNode';\n\n/**\n * Stores the data we have cached for a view.\n *\n * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes).\n */\nexport interface ViewCache {\n readonly eventCache: CacheNode;\n readonly serverCache: CacheNode;\n}\n\nexport function newViewCache(\n eventCache: CacheNode,\n serverCache: CacheNode\n): ViewCache {\n return { eventCache, serverCache };\n}\n\nexport function viewCacheUpdateEventSnap(\n viewCache: ViewCache,\n eventSnap: Node,\n complete: boolean,\n filtered: boolean\n): ViewCache {\n return newViewCache(\n new CacheNode(eventSnap, complete, filtered),\n viewCache.serverCache\n );\n}\n\nexport function viewCacheUpdateServerSnap(\n viewCache: ViewCache,\n serverSnap: Node,\n complete: boolean,\n filtered: boolean\n): ViewCache {\n return newViewCache(\n viewCache.eventCache,\n new CacheNode(serverSnap, complete, filtered)\n );\n}\n\nexport function viewCacheGetCompleteEventSnap(\n viewCache: ViewCache\n): Node | null {\n return viewCache.eventCache.isFullyInitialized()\n ? viewCache.eventCache.getNode()\n : null;\n}\n\nexport function viewCacheGetCompleteServerSnap(\n viewCache: ViewCache\n): Node | null {\n return viewCache.serverCache.isFullyInitialized()\n ? viewCache.serverCache.getNode()\n : null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n newEmptyPath,\n Path,\n pathChild,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from './Path';\nimport { SortedMap } from './SortedMap';\nimport { each, stringCompare } from './util';\n\nlet emptyChildrenSingleton: SortedMap>;\n\n/**\n * Singleton empty children collection.\n *\n */\nconst EmptyChildren = (): SortedMap> => {\n if (!emptyChildrenSingleton) {\n emptyChildrenSingleton = new SortedMap>(\n stringCompare\n );\n }\n return emptyChildrenSingleton;\n};\n\n/**\n * A tree with immutable elements.\n */\nexport class ImmutableTree {\n static fromObject(obj: { [k: string]: T }): ImmutableTree {\n let tree: ImmutableTree = new ImmutableTree(null);\n each(obj, (childPath: string, childSnap: T) => {\n tree = tree.set(new Path(childPath), childSnap);\n });\n return tree;\n }\n\n constructor(\n public readonly value: T | null,\n public readonly children: SortedMap<\n string,\n ImmutableTree\n > = EmptyChildren()\n ) {}\n\n /**\n * True if the value is empty and there are no children\n */\n isEmpty(): boolean {\n return this.value === null && this.children.isEmpty();\n }\n\n /**\n * Given a path and predicate, return the first node and the path to that node\n * where the predicate returns true.\n *\n * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`\n * objects on the way back out, it may be better to pass down a pathSoFar obj.\n *\n * @param relativePath - The remainder of the path\n * @param predicate - The predicate to satisfy to return a node\n */\n findRootMostMatchingPathAndValue(\n relativePath: Path,\n predicate: (a: T) => boolean\n ): { path: Path; value: T } | null {\n if (this.value != null && predicate(this.value)) {\n return { path: newEmptyPath(), value: this.value };\n } else {\n if (pathIsEmpty(relativePath)) {\n return null;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child !== null) {\n const childExistingPathAndValue =\n child.findRootMostMatchingPathAndValue(\n pathPopFront(relativePath),\n predicate\n );\n if (childExistingPathAndValue != null) {\n const fullPath = pathChild(\n new Path(front),\n childExistingPathAndValue.path\n );\n return { path: fullPath, value: childExistingPathAndValue.value };\n } else {\n return null;\n }\n } else {\n return null;\n }\n }\n }\n }\n\n /**\n * Find, if it exists, the shortest subpath of the given path that points a defined\n * value in the tree\n */\n findRootMostValueAndPath(\n relativePath: Path\n ): { path: Path; value: T } | null {\n return this.findRootMostMatchingPathAndValue(relativePath, () => true);\n }\n\n /**\n * @returns The subtree at the given path\n */\n subtree(relativePath: Path): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n return this;\n } else {\n const front = pathGetFront(relativePath);\n const childTree = this.children.get(front);\n if (childTree !== null) {\n return childTree.subtree(pathPopFront(relativePath));\n } else {\n return new ImmutableTree(null);\n }\n }\n }\n\n /**\n * Sets a value at the specified path.\n *\n * @param relativePath - Path to set value at.\n * @param toSet - Value to set.\n * @returns Resulting tree.\n */\n set(relativePath: Path, toSet: T | null): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n return new ImmutableTree(toSet, this.children);\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front) || new ImmutableTree(null);\n const newChild = child.set(pathPopFront(relativePath), toSet);\n const newChildren = this.children.insert(front, newChild);\n return new ImmutableTree(this.value, newChildren);\n }\n }\n\n /**\n * Removes the value at the specified path.\n *\n * @param relativePath - Path to value to remove.\n * @returns Resulting tree.\n */\n remove(relativePath: Path): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n if (this.children.isEmpty()) {\n return new ImmutableTree(null);\n } else {\n return new ImmutableTree(null, this.children);\n }\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child) {\n const newChild = child.remove(pathPopFront(relativePath));\n let newChildren;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n } else {\n newChildren = this.children.insert(front, newChild);\n }\n if (this.value === null && newChildren.isEmpty()) {\n return new ImmutableTree(null);\n } else {\n return new ImmutableTree(this.value, newChildren);\n }\n } else {\n return this;\n }\n }\n }\n\n /**\n * Gets a value from the tree.\n *\n * @param relativePath - Path to get value for.\n * @returns Value at path, or null.\n */\n get(relativePath: Path): T | null {\n if (pathIsEmpty(relativePath)) {\n return this.value;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child) {\n return child.get(pathPopFront(relativePath));\n } else {\n return null;\n }\n }\n }\n\n /**\n * Replace the subtree at the specified path with the given new tree.\n *\n * @param relativePath - Path to replace subtree for.\n * @param newTree - New tree.\n * @returns Resulting tree.\n */\n setTree(relativePath: Path, newTree: ImmutableTree): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n return newTree;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front) || new ImmutableTree(null);\n const newChild = child.setTree(pathPopFront(relativePath), newTree);\n let newChildren;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n } else {\n newChildren = this.children.insert(front, newChild);\n }\n return new ImmutableTree(this.value, newChildren);\n }\n }\n\n /**\n * Performs a depth first fold on this tree. Transforms a tree into a single\n * value, given a function that operates on the path to a node, an optional\n * current value, and a map of child names to folded subtrees\n */\n fold(fn: (path: Path, value: T, children: { [k: string]: V }) => V): V {\n return this.fold_(newEmptyPath(), fn);\n }\n\n /**\n * Recursive helper for public-facing fold() method\n */\n private fold_(\n pathSoFar: Path,\n fn: (path: Path, value: T | null, children: { [k: string]: V }) => V\n ): V {\n const accum: { [k: string]: V } = {};\n this.children.inorderTraversal(\n (childKey: string, childTree: ImmutableTree) => {\n accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);\n }\n );\n return fn(pathSoFar, this.value, accum);\n }\n\n /**\n * Find the first matching value on the given path. Return the result of applying f to it.\n */\n findOnPath(path: Path, f: (path: Path, value: T) => V | null): V | null {\n return this.findOnPath_(path, newEmptyPath(), f);\n }\n\n private findOnPath_(\n pathToFollow: Path,\n pathSoFar: Path,\n f: (path: Path, value: T) => V | null\n ): V | null {\n const result = this.value ? f(pathSoFar, this.value) : false;\n if (result) {\n return result;\n } else {\n if (pathIsEmpty(pathToFollow)) {\n return null;\n } else {\n const front = pathGetFront(pathToFollow)!;\n const nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.findOnPath_(\n pathPopFront(pathToFollow),\n pathChild(pathSoFar, front),\n f\n );\n } else {\n return null;\n }\n }\n }\n }\n\n foreachOnPath(\n path: Path,\n f: (path: Path, value: T) => void\n ): ImmutableTree {\n return this.foreachOnPath_(path, newEmptyPath(), f);\n }\n\n private foreachOnPath_(\n pathToFollow: Path,\n currentRelativePath: Path,\n f: (path: Path, value: T) => void\n ): ImmutableTree {\n if (pathIsEmpty(pathToFollow)) {\n return this;\n } else {\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n const front = pathGetFront(pathToFollow);\n const nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.foreachOnPath_(\n pathPopFront(pathToFollow),\n pathChild(currentRelativePath, front),\n f\n );\n } else {\n return new ImmutableTree(null);\n }\n }\n }\n\n /**\n * Calls the given function for each node in the tree that has a value.\n *\n * @param f - A function to be called with the path from the root of the tree to\n * a node, and the value at that node. Called in depth-first order.\n */\n foreach(f: (path: Path, value: T) => void) {\n this.foreach_(newEmptyPath(), f);\n }\n\n private foreach_(\n currentRelativePath: Path,\n f: (path: Path, value: T) => void\n ) {\n this.children.inorderTraversal((childName, childTree) => {\n childTree.foreach_(pathChild(currentRelativePath, childName), f);\n });\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n }\n\n foreachChild(f: (name: string, value: T) => void) {\n this.children.inorderTraversal(\n (childName: string, childTree: ImmutableTree) => {\n if (childTree.value) {\n f(childName, childTree.value);\n }\n }\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { NamedNode, Node } from './snap/Node';\nimport { ImmutableTree } from './util/ImmutableTree';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathIsEmpty\n} from './util/Path';\nimport { each } from './util/util';\n\n/**\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\n * to reflect the write added.\n */\nexport class CompoundWrite {\n constructor(public writeTree_: ImmutableTree) {}\n\n static empty(): CompoundWrite {\n return new CompoundWrite(new ImmutableTree(null));\n }\n}\n\nexport function compoundWriteAddWrite(\n compoundWrite: CompoundWrite,\n path: Path,\n node: Node\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return new CompoundWrite(new ImmutableTree(node));\n } else {\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n const rootMostPath = rootmost.path;\n let value = rootmost.value;\n const relativePath = newRelativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(\n compoundWrite.writeTree_.set(rootMostPath, value)\n );\n } else {\n const subtree = new ImmutableTree(node);\n const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n}\n\nexport function compoundWriteAddWrites(\n compoundWrite: CompoundWrite,\n path: Path,\n updates: { [name: string]: Node }\n): CompoundWrite {\n let newWrite = compoundWrite;\n each(updates, (childKey: string, node: Node) => {\n newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);\n });\n return newWrite;\n}\n\n/**\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param compoundWrite - The CompoundWrite to remove.\n * @param path - The path at which a write and all deeper writes should be removed\n * @returns The new CompoundWrite with the removed path\n */\nexport function compoundWriteRemoveWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return CompoundWrite.empty();\n } else {\n const newWriteTree = compoundWrite.writeTree_.setTree(\n path,\n new ImmutableTree(null)\n );\n return new CompoundWrite(newWriteTree);\n }\n}\n\n/**\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\n * considered \"complete\".\n *\n * @param compoundWrite - The CompoundWrite to check.\n * @param path - The path to check for\n * @returns Whether there is a complete write at that path\n */\nexport function compoundWriteHasCompleteWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): boolean {\n return compoundWriteGetCompleteNode(compoundWrite, path) != null;\n}\n\n/**\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\n * writes from deeper paths, but will return child nodes from a more shallow path.\n *\n * @param compoundWrite - The CompoundWrite to get the node from.\n * @param path - The path to get a complete write\n * @returns The node if complete at that path, or null otherwise.\n */\nexport function compoundWriteGetCompleteNode(\n compoundWrite: CompoundWrite,\n path: Path\n): Node | null {\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return compoundWrite.writeTree_\n .get(rootmost.path)\n .getChild(newRelativePath(rootmost.path, path));\n } else {\n return null;\n }\n}\n\n/**\n * Returns all children that are guaranteed to be a complete overwrite.\n *\n * @param compoundWrite - The CompoundWrite to get children from.\n * @returns A list of all complete children.\n */\nexport function compoundWriteGetCompleteChildren(\n compoundWrite: CompoundWrite\n): NamedNode[] {\n const children: NamedNode[] = [];\n const node = compoundWrite.writeTree_.value;\n if (node != null) {\n // If it's a leaf node, it has no children; so nothing to do.\n if (!node.isLeafNode()) {\n (node as ChildrenNode).forEachChild(\n PRIORITY_INDEX,\n (childName, childNode) => {\n children.push(new NamedNode(childName, childNode));\n }\n );\n }\n } else {\n compoundWrite.writeTree_.children.inorderTraversal(\n (childName, childTree) => {\n if (childTree.value != null) {\n children.push(new NamedNode(childName, childTree.value));\n }\n }\n );\n }\n return children;\n}\n\nexport function compoundWriteChildCompoundWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return compoundWrite;\n } else {\n const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree(shadowingNode));\n } else {\n return new CompoundWrite(compoundWrite.writeTree_.subtree(path));\n }\n }\n}\n\n/**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @returns Whether this CompoundWrite is empty\n */\nexport function compoundWriteIsEmpty(compoundWrite: CompoundWrite): boolean {\n return compoundWrite.writeTree_.isEmpty();\n}\n\n/**\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\n * node\n * @param node - The node to apply this CompoundWrite to\n * @returns The node with all writes applied\n */\nexport function compoundWriteApply(\n compoundWrite: CompoundWrite,\n node: Node\n): Node {\n return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);\n}\n\nfunction applySubtreeWrite(\n relativePath: Path,\n writeTree: ImmutableTree,\n node: Node\n): Node {\n if (writeTree.value != null) {\n // Since there a write is always a leaf, we're done here\n return node.updateChild(relativePath, writeTree.value);\n } else {\n let priorityWrite = null;\n writeTree.children.inorderTraversal((childKey, childTree) => {\n if (childKey === '.priority') {\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\n // to apply priorities to empty nodes that are later filled\n assert(\n childTree.value !== null,\n 'Priority writes must always be leaf nodes'\n );\n priorityWrite = childTree.value;\n } else {\n node = applySubtreeWrite(\n pathChild(relativePath, childKey),\n childTree,\n node\n );\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {\n node = node.updateChild(\n pathChild(relativePath, '.priority'),\n priorityWrite\n );\n }\n return node;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError, safeGet } from '@firebase/util';\n\nimport {\n CompoundWrite,\n compoundWriteAddWrite,\n compoundWriteAddWrites,\n compoundWriteApply,\n compoundWriteChildCompoundWrite,\n compoundWriteGetCompleteChildren,\n compoundWriteGetCompleteNode,\n compoundWriteHasCompleteWrite,\n compoundWriteIsEmpty,\n compoundWriteRemoveWrite\n} from './CompoundWrite';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Index } from './snap/indexes/Index';\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { NamedNode, Node } from './snap/Node';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathContains,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from './util/Path';\nimport { each } from './util/util';\nimport { CacheNode } from './view/CacheNode';\n\n/**\n * Defines a single user-initiated write operation. May be the result of a set(), transaction(), or update() call. In\n * the case of a set() or transaction, snap will be non-null. In the case of an update(), children will be non-null.\n */\nexport interface WriteRecord {\n writeId: number;\n path: Path;\n snap?: Node | null;\n children?: { [k: string]: Node } | null;\n visible: boolean;\n}\n\n/**\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n */\nexport function writeTreeChildWrites(\n writeTree: WriteTree,\n path: Path\n): WriteTreeRef {\n return newWriteTreeRef(path, writeTree);\n}\n\n/**\n * Record a new overwrite from user code.\n *\n * @param visible - This is set to false by some transactions. It should be excluded from event caches\n */\nexport function writeTreeAddOverwrite(\n writeTree: WriteTree,\n path: Path,\n snap: Node,\n writeId: number,\n visible?: boolean\n) {\n assert(\n writeId > writeTree.lastWriteId,\n 'Stacking an older write on top of newer ones'\n );\n if (visible === undefined) {\n visible = true;\n }\n writeTree.allWrites.push({\n path,\n snap,\n writeId,\n visible\n });\n\n if (visible) {\n writeTree.visibleWrites = compoundWriteAddWrite(\n writeTree.visibleWrites,\n path,\n snap\n );\n }\n writeTree.lastWriteId = writeId;\n}\n\n/**\n * Record a new merge from user code.\n */\nexport function writeTreeAddMerge(\n writeTree: WriteTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n writeId: number\n) {\n assert(\n writeId > writeTree.lastWriteId,\n 'Stacking an older merge on top of newer ones'\n );\n writeTree.allWrites.push({\n path,\n children: changedChildren,\n writeId,\n visible: true\n });\n\n writeTree.visibleWrites = compoundWriteAddWrites(\n writeTree.visibleWrites,\n path,\n changedChildren\n );\n writeTree.lastWriteId = writeId;\n}\n\nexport function writeTreeGetWrite(\n writeTree: WriteTree,\n writeId: number\n): WriteRecord | null {\n for (let i = 0; i < writeTree.allWrites.length; i++) {\n const record = writeTree.allWrites[i];\n if (record.writeId === writeId) {\n return record;\n }\n }\n return null;\n}\n\n/**\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\n *\n * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\nexport function writeTreeRemoveWrite(\n writeTree: WriteTree,\n writeId: number\n): boolean {\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\n // out of order.\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\n\n const idx = writeTree.allWrites.findIndex(s => {\n return s.writeId === writeId;\n });\n assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n const writeToRemove = writeTree.allWrites[idx];\n writeTree.allWrites.splice(idx, 1);\n\n let removedWriteWasVisible = writeToRemove.visible;\n let removedWriteOverlapsWithOtherWrites = false;\n\n let i = writeTree.allWrites.length - 1;\n\n while (removedWriteWasVisible && i >= 0) {\n const currentWrite = writeTree.allWrites[i];\n if (currentWrite.visible) {\n if (\n i >= idx &&\n writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)\n ) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\n } else if (pathContains(writeToRemove.path, currentWrite.path)) {\n // Either we're covering some writes or they're covering part of us (depending on which came first).\n removedWriteOverlapsWithOtherWrites = true;\n }\n }\n i--;\n }\n\n if (!removedWriteWasVisible) {\n return false;\n } else if (removedWriteOverlapsWithOtherWrites) {\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\n writeTreeResetTree_(writeTree);\n return true;\n } else {\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\n if (writeToRemove.snap) {\n writeTree.visibleWrites = compoundWriteRemoveWrite(\n writeTree.visibleWrites,\n writeToRemove.path\n );\n } else {\n const children = writeToRemove.children;\n each(children, (childName: string) => {\n writeTree.visibleWrites = compoundWriteRemoveWrite(\n writeTree.visibleWrites,\n pathChild(writeToRemove.path, childName)\n );\n });\n }\n return true;\n }\n}\n\nfunction writeTreeRecordContainsPath_(\n writeRecord: WriteRecord,\n path: Path\n): boolean {\n if (writeRecord.snap) {\n return pathContains(writeRecord.path, path);\n } else {\n for (const childName in writeRecord.children) {\n if (\n writeRecord.children.hasOwnProperty(childName) &&\n pathContains(pathChild(writeRecord.path, childName), path)\n ) {\n return true;\n }\n }\n return false;\n }\n}\n\n/**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\n */\nfunction writeTreeResetTree_(writeTree: WriteTree) {\n writeTree.visibleWrites = writeTreeLayerTree_(\n writeTree.allWrites,\n writeTreeDefaultFilter_,\n newEmptyPath()\n );\n if (writeTree.allWrites.length > 0) {\n writeTree.lastWriteId =\n writeTree.allWrites[writeTree.allWrites.length - 1].writeId;\n } else {\n writeTree.lastWriteId = -1;\n }\n}\n\n/**\n * The default filter used when constructing the tree. Keep everything that's visible.\n */\nfunction writeTreeDefaultFilter_(write: WriteRecord) {\n return write.visible;\n}\n\n/**\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\n * event data at that path.\n */\nfunction writeTreeLayerTree_(\n writes: WriteRecord[],\n filter: (w: WriteRecord) => boolean,\n treeRoot: Path\n): CompoundWrite {\n let compoundWrite = CompoundWrite.empty();\n for (let i = 0; i < writes.length; ++i) {\n const write = writes[i];\n // Theory, a later set will either:\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\n if (filter(write)) {\n const writePath = write.path;\n let relativePath: Path;\n if (write.snap) {\n if (pathContains(treeRoot, writePath)) {\n relativePath = newRelativePath(treeRoot, writePath);\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n relativePath,\n write.snap\n );\n } else if (pathContains(writePath, treeRoot)) {\n relativePath = newRelativePath(writePath, treeRoot);\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n newEmptyPath(),\n write.snap.getChild(relativePath)\n );\n } else {\n // There is no overlap between root path and write path, ignore write\n }\n } else if (write.children) {\n if (pathContains(treeRoot, writePath)) {\n relativePath = newRelativePath(treeRoot, writePath);\n compoundWrite = compoundWriteAddWrites(\n compoundWrite,\n relativePath,\n write.children\n );\n } else if (pathContains(writePath, treeRoot)) {\n relativePath = newRelativePath(writePath, treeRoot);\n if (pathIsEmpty(relativePath)) {\n compoundWrite = compoundWriteAddWrites(\n compoundWrite,\n newEmptyPath(),\n write.children\n );\n } else {\n const child = safeGet(write.children, pathGetFront(relativePath));\n if (child) {\n // There exists a child in this node that matches the root path\n const deepNode = child.getChild(pathPopFront(relativePath));\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n newEmptyPath(),\n deepNode\n );\n }\n }\n } else {\n // There is no overlap between root path and write path, ignore write\n }\n } else {\n throw assertionError('WriteRecord should have .snap or .children');\n }\n }\n }\n return compoundWrite;\n}\n\n/**\n * Return a complete snapshot for the given path if there's visible write data at that path, else null.\n * No server data is considered.\n *\n */\nexport function writeTreeGetCompleteWriteData(\n writeTree: WriteTree,\n path: Path\n): Node | null {\n return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\n}\n\n/**\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\n * writes), attempt to calculate a complete snapshot for the given path\n *\n * @param writeIdsToExclude - An optional set to be excluded\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\n */\nexport function writeTreeCalcCompleteEventCache(\n writeTree: WriteTree,\n treePath: Path,\n completeServerCache: Node | null,\n writeIdsToExclude?: number[],\n includeHiddenWrites?: boolean\n): Node | null {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n const shadowingNode = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n treePath\n );\n if (shadowingNode != null) {\n return shadowingNode;\n } else {\n const subMerge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n if (compoundWriteIsEmpty(subMerge)) {\n return completeServerCache;\n } else if (\n completeServerCache == null &&\n !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())\n ) {\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n return null;\n } else {\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\n return compoundWriteApply(subMerge, layeredCache);\n }\n }\n } else {\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {\n return completeServerCache;\n } else {\n // If the server cache is null, and we don't have a complete cache, we need to return null\n if (\n !includeHiddenWrites &&\n completeServerCache == null &&\n !compoundWriteHasCompleteWrite(merge, newEmptyPath())\n ) {\n return null;\n } else {\n const filter = function (write: WriteRecord) {\n return (\n (write.visible || includeHiddenWrites) &&\n (!writeIdsToExclude ||\n !~writeIdsToExclude.indexOf(write.writeId)) &&\n (pathContains(write.path, treePath) ||\n pathContains(treePath, write.path))\n );\n };\n const mergeAtPath = writeTreeLayerTree_(\n writeTree.allWrites,\n filter,\n treePath\n );\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\n return compoundWriteApply(mergeAtPath, layeredCache);\n }\n }\n }\n}\n\n/**\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\n * Used when creating new views, to pre-fill their complete event children snapshot.\n */\nexport function writeTreeCalcCompleteEventChildren(\n writeTree: WriteTree,\n treePath: Path,\n completeServerChildren: ChildrenNode | null\n) {\n let completeChildren = ChildrenNode.EMPTY_NODE as Node;\n const topLevelSet = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n treePath\n );\n if (topLevelSet) {\n if (!topLevelSet.isLeafNode()) {\n // we're shadowing everything. Return the children.\n topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {\n completeChildren = completeChildren.updateImmediateChild(\n childName,\n childSnap\n );\n });\n }\n return completeChildren;\n } else if (completeServerChildren) {\n // Layer any children we have on top of this\n // We know we don't have a top-level set, so just enumerate existing children\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n completeServerChildren.forEachChild(\n PRIORITY_INDEX,\n (childName, childNode) => {\n const node = compoundWriteApply(\n compoundWriteChildCompoundWrite(merge, new Path(childName)),\n childNode\n );\n completeChildren = completeChildren.updateImmediateChild(\n childName,\n node\n );\n }\n );\n // Add any complete children we have from the set\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\n completeChildren = completeChildren.updateImmediateChild(\n namedNode.name,\n namedNode.node\n );\n });\n return completeChildren;\n } else {\n // We don't have anything to layer on top of. Layer on any children we have\n // Note that we can return an empty snap if we have a defined delete\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\n completeChildren = completeChildren.updateImmediateChild(\n namedNode.name,\n namedNode.node\n );\n });\n return completeChildren;\n }\n}\n\n/**\n * Given that the underlying server data has updated, determine what, if anything, needs to be\n * applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events\n *\n * Either existingEventSnap or existingServerSnap must exist\n */\nexport function writeTreeCalcEventCacheAfterServerOverwrite(\n writeTree: WriteTree,\n treePath: Path,\n childPath: Path,\n existingEventSnap: Node | null,\n existingServerSnap: Node | null\n): Node | null {\n assert(\n existingEventSnap || existingServerSnap,\n 'Either existingEventSnap or existingServerSnap must exist'\n );\n const path = pathChild(treePath, childPath);\n if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {\n // At this point we can probably guarantee that we're in case 2, meaning no events\n // May need to check visibility while doing the findRootMostValueAndPath call\n return null;\n } else {\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\n const childMerge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n path\n );\n if (compoundWriteIsEmpty(childMerge)) {\n // We're not shadowing at all. Case 1\n return existingServerSnap.getChild(childPath);\n } else {\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\n // However this is tricky to find out, since user updates don't necessary change the server\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\n // only check if the updates change the serverNode.\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\n return compoundWriteApply(\n childMerge,\n existingServerSnap.getChild(childPath)\n );\n }\n }\n}\n\n/**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n */\nexport function writeTreeCalcCompleteChild(\n writeTree: WriteTree,\n treePath: Path,\n childKey: string,\n existingServerSnap: CacheNode\n): Node | null {\n const path = pathChild(treePath, childKey);\n const shadowingNode = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n path\n );\n if (shadowingNode != null) {\n return shadowingNode;\n } else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n const childMerge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n path\n );\n return compoundWriteApply(\n childMerge,\n existingServerSnap.getNode().getImmediateChild(childKey)\n );\n } else {\n return null;\n }\n }\n}\n\n/**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n */\nexport function writeTreeShadowingWrite(\n writeTree: WriteTree,\n path: Path\n): Node | null {\n return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\n}\n\n/**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window.\n */\nexport function writeTreeCalcIndexedSlice(\n writeTree: WriteTree,\n treePath: Path,\n completeServerData: Node | null,\n startPost: NamedNode,\n count: number,\n reverse: boolean,\n index: Index\n): NamedNode[] {\n let toIterate: Node;\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n } else if (completeServerData != null) {\n toIterate = compoundWriteApply(merge, completeServerData);\n } else {\n // no children to iterate on\n return [];\n }\n toIterate = toIterate.withIndex(index);\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n const nodes = [];\n const cmp = index.getCompare();\n const iter = reverse\n ? (toIterate as ChildrenNode).getReverseIteratorFrom(startPost, index)\n : (toIterate as ChildrenNode).getIteratorFrom(startPost, index);\n let next = iter.getNext();\n while (next && nodes.length < count) {\n if (cmp(next, startPost) !== 0) {\n nodes.push(next);\n }\n next = iter.getNext();\n }\n return nodes;\n } else {\n return [];\n }\n}\n\nexport function newWriteTree(): WriteTree {\n return {\n visibleWrites: CompoundWrite.empty(),\n allWrites: [],\n lastWriteId: -1\n };\n}\n\n/**\n * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them\n * with underlying server data (to create \"event cache\" data). Pending writes are added with addOverwrite()\n * and addMerge(), and removed with removeWrite().\n */\nexport interface WriteTree {\n /**\n * A tree tracking the result of applying all visible writes. This does not include transactions with\n * applyLocally=false or writes that are completely shadowed by other writes.\n */\n visibleWrites: CompoundWrite;\n\n /**\n * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary\n * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also\n * used by transactions).\n */\n allWrites: WriteRecord[];\n\n lastWriteId: number;\n}\n\n/**\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\n * can lead to a more expensive calculation.\n *\n * @param writeIdsToExclude - Optional writes to exclude.\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\n */\nexport function writeTreeRefCalcCompleteEventCache(\n writeTreeRef: WriteTreeRef,\n completeServerCache: Node | null,\n writeIdsToExclude?: number[],\n includeHiddenWrites?: boolean\n): Node | null {\n return writeTreeCalcCompleteEventCache(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n completeServerCache,\n writeIdsToExclude,\n includeHiddenWrites\n );\n}\n\n/**\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\n * mix of the given server data and write data.\n *\n */\nexport function writeTreeRefCalcCompleteEventChildren(\n writeTreeRef: WriteTreeRef,\n completeServerChildren: ChildrenNode | null\n): ChildrenNode {\n return writeTreeCalcCompleteEventChildren(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n completeServerChildren\n ) as ChildrenNode;\n}\n\n/**\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\n * if anything, needs to be applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events should be raised\n *\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\n *\n *\n */\nexport function writeTreeRefCalcEventCacheAfterServerOverwrite(\n writeTreeRef: WriteTreeRef,\n path: Path,\n existingEventSnap: Node | null,\n existingServerSnap: Node | null\n): Node | null {\n return writeTreeCalcEventCacheAfterServerOverwrite(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n path,\n existingEventSnap,\n existingServerSnap\n );\n}\n\n/**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n */\nexport function writeTreeRefShadowingWrite(\n writeTreeRef: WriteTreeRef,\n path: Path\n): Node | null {\n return writeTreeShadowingWrite(\n writeTreeRef.writeTree,\n pathChild(writeTreeRef.treePath, path)\n );\n}\n\n/**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window\n */\nexport function writeTreeRefCalcIndexedSlice(\n writeTreeRef: WriteTreeRef,\n completeServerData: Node | null,\n startPost: NamedNode,\n count: number,\n reverse: boolean,\n index: Index\n): NamedNode[] {\n return writeTreeCalcIndexedSlice(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n completeServerData,\n startPost,\n count,\n reverse,\n index\n );\n}\n\n/**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n */\nexport function writeTreeRefCalcCompleteChild(\n writeTreeRef: WriteTreeRef,\n childKey: string,\n existingServerCache: CacheNode\n): Node | null {\n return writeTreeCalcCompleteChild(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n childKey,\n existingServerCache\n );\n}\n\n/**\n * Return a WriteTreeRef for a child.\n */\nexport function writeTreeRefChild(\n writeTreeRef: WriteTreeRef,\n childName: string\n): WriteTreeRef {\n return newWriteTreeRef(\n pathChild(writeTreeRef.treePath, childName),\n writeTreeRef.writeTree\n );\n}\n\nexport function newWriteTreeRef(\n path: Path,\n writeTree: WriteTree\n): WriteTreeRef {\n return {\n treePath: path,\n writeTree\n };\n}\n\n/**\n * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods\n * just proxy to the underlying WriteTree.\n *\n */\nexport interface WriteTreeRef {\n /**\n * The path to this particular write tree ref. Used for calling methods on writeTree_ while exposing a simpler\n * interface to callers.\n */\n readonly treePath: Path;\n\n /**\n * * A reference to the actual tree of write data. All methods are pass-through to the tree, but with the appropriate\n * path prefixed.\n *\n * This lets us make cheap references to points in the tree for sync points without having to copy and maintain all of\n * the data.\n */\n readonly writeTree: WriteTree;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport {\n Change,\n ChangeType,\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from './Change';\n\nexport class ChildChangeAccumulator {\n private readonly changeMap: Map = new Map();\n\n trackChildChange(change: Change) {\n const type = change.type;\n const childKey = change.childName!;\n assert(\n type === ChangeType.CHILD_ADDED ||\n type === ChangeType.CHILD_CHANGED ||\n type === ChangeType.CHILD_REMOVED,\n 'Only child changes supported for tracking'\n );\n assert(\n childKey !== '.priority',\n 'Only non-priority child changes can be tracked.'\n );\n const oldChange = this.changeMap.get(childKey);\n if (oldChange) {\n const oldType = oldChange.type;\n if (\n type === ChangeType.CHILD_ADDED &&\n oldType === ChangeType.CHILD_REMOVED\n ) {\n this.changeMap.set(\n childKey,\n changeChildChanged(\n childKey,\n change.snapshotNode,\n oldChange.snapshotNode\n )\n );\n } else if (\n type === ChangeType.CHILD_REMOVED &&\n oldType === ChangeType.CHILD_ADDED\n ) {\n this.changeMap.delete(childKey);\n } else if (\n type === ChangeType.CHILD_REMOVED &&\n oldType === ChangeType.CHILD_CHANGED\n ) {\n this.changeMap.set(\n childKey,\n changeChildRemoved(childKey, oldChange.oldSnap)\n );\n } else if (\n type === ChangeType.CHILD_CHANGED &&\n oldType === ChangeType.CHILD_ADDED\n ) {\n this.changeMap.set(\n childKey,\n changeChildAdded(childKey, change.snapshotNode)\n );\n } else if (\n type === ChangeType.CHILD_CHANGED &&\n oldType === ChangeType.CHILD_CHANGED\n ) {\n this.changeMap.set(\n childKey,\n changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap)\n );\n } else {\n throw assertionError(\n 'Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange\n );\n }\n } else {\n this.changeMap.set(childKey, change);\n }\n }\n\n getChanges(): Change[] {\n return Array.from(this.changeMap.values());\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Index } from '../snap/indexes/Index';\nimport { NamedNode, Node } from '../snap/Node';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteChild,\n writeTreeRefCalcIndexedSlice\n} from '../WriteTree';\n\nimport { CacheNode } from './CacheNode';\nimport { ViewCache, viewCacheGetCompleteServerSnap } from './ViewCache';\n\n/**\n * Since updates to filtered nodes might require nodes to be pulled in from \"outside\" the node, this interface\n * can help to get complete children that can be pulled in.\n * A class implementing this interface takes potentially multiple sources (e.g. user writes, server data from\n * other views etc.) to try it's best to get a complete child that might be useful in pulling into the view.\n *\n * @interface\n */\nexport interface CompleteChildSource {\n getCompleteChild(childKey: string): Node | null;\n\n getChildAfterChild(\n index: Index,\n child: NamedNode,\n reverse: boolean\n ): NamedNode | null;\n}\n\n/**\n * An implementation of CompleteChildSource that never returns any additional children\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class NoCompleteChildSource_ implements CompleteChildSource {\n getCompleteChild(childKey?: string): Node | null {\n return null;\n }\n getChildAfterChild(\n index?: Index,\n child?: NamedNode,\n reverse?: boolean\n ): NamedNode | null {\n return null;\n }\n}\n\n/**\n * Singleton instance.\n */\nexport const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n\n/**\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\n * old event caches available to calculate complete children.\n */\nexport class WriteTreeCompleteChildSource implements CompleteChildSource {\n constructor(\n private writes_: WriteTreeRef,\n private viewCache_: ViewCache,\n private optCompleteServerCache_: Node | null = null\n ) {}\n getCompleteChild(childKey: string): Node | null {\n const node = this.viewCache_.eventCache;\n if (node.isCompleteForChild(childKey)) {\n return node.getNode().getImmediateChild(childKey);\n } else {\n const serverNode =\n this.optCompleteServerCache_ != null\n ? new CacheNode(this.optCompleteServerCache_, true, false)\n : this.viewCache_.serverCache;\n return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);\n }\n }\n getChildAfterChild(\n index: Index,\n child: NamedNode,\n reverse: boolean\n ): NamedNode | null {\n const completeServerData =\n this.optCompleteServerCache_ != null\n ? this.optCompleteServerCache_\n : viewCacheGetCompleteServerSnap(this.viewCache_);\n const nodes = writeTreeRefCalcIndexedSlice(\n this.writes_,\n completeServerData,\n child,\n 1,\n reverse,\n index\n );\n if (nodes.length === 0) {\n return null;\n } else {\n return nodes[0];\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport { AckUserWrite } from '../operation/AckUserWrite';\nimport { Merge } from '../operation/Merge';\nimport { Operation, OperationType } from '../operation/Operation';\nimport { Overwrite } from '../operation/Overwrite';\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { KEY_INDEX } from '../snap/indexes/KeyIndex';\nimport { Node } from '../snap/Node';\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathChild,\n pathGetBack,\n pathGetFront,\n pathGetLength,\n pathIsEmpty,\n pathParent,\n pathPopFront\n} from '../util/Path';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteChild,\n writeTreeRefCalcCompleteEventCache,\n writeTreeRefCalcCompleteEventChildren,\n writeTreeRefCalcEventCacheAfterServerOverwrite,\n writeTreeRefShadowingWrite\n} from '../WriteTree';\n\nimport { Change, changeValue } from './Change';\nimport { ChildChangeAccumulator } from './ChildChangeAccumulator';\nimport {\n CompleteChildSource,\n NO_COMPLETE_CHILD_SOURCE,\n WriteTreeCompleteChildSource\n} from './CompleteChildSource';\nimport { NodeFilter } from './filter/NodeFilter';\nimport {\n ViewCache,\n viewCacheGetCompleteEventSnap,\n viewCacheGetCompleteServerSnap,\n viewCacheUpdateEventSnap,\n viewCacheUpdateServerSnap\n} from './ViewCache';\n\nexport interface ProcessorResult {\n readonly viewCache: ViewCache;\n readonly changes: Change[];\n}\n\nexport interface ViewProcessor {\n readonly filter: NodeFilter;\n}\n\nexport function newViewProcessor(filter: NodeFilter): ViewProcessor {\n return { filter };\n}\n\nexport function viewProcessorAssertIndexed(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache\n): void {\n assert(\n viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()),\n 'Event snap not indexed'\n );\n assert(\n viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()),\n 'Server snap not indexed'\n );\n}\n\nexport function viewProcessorApplyOperation(\n viewProcessor: ViewProcessor,\n oldViewCache: ViewCache,\n operation: Operation,\n writesCache: WriteTreeRef,\n completeCache: Node | null\n): ProcessorResult {\n const accumulator = new ChildChangeAccumulator();\n let newViewCache, filterServerNode;\n if (operation.type === OperationType.OVERWRITE) {\n const overwrite = operation as Overwrite;\n if (overwrite.source.fromUser) {\n newViewCache = viewProcessorApplyUserOverwrite(\n viewProcessor,\n oldViewCache,\n overwrite.path,\n overwrite.snap,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n assert(overwrite.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered and the\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\n // again\n filterServerNode =\n overwrite.source.tagged ||\n (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));\n newViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\n oldViewCache,\n overwrite.path,\n overwrite.snap,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n } else if (operation.type === OperationType.MERGE) {\n const merge = operation as Merge;\n if (merge.source.fromUser) {\n newViewCache = viewProcessorApplyUserMerge(\n viewProcessor,\n oldViewCache,\n merge.path,\n merge.children,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n assert(merge.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered\n filterServerNode =\n merge.source.tagged || oldViewCache.serverCache.isFiltered();\n newViewCache = viewProcessorApplyServerMerge(\n viewProcessor,\n oldViewCache,\n merge.path,\n merge.children,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n } else if (operation.type === OperationType.ACK_USER_WRITE) {\n const ackUserWrite = operation as AckUserWrite;\n if (!ackUserWrite.revert) {\n newViewCache = viewProcessorAckUserWrite(\n viewProcessor,\n oldViewCache,\n ackUserWrite.path,\n ackUserWrite.affectedTree,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n newViewCache = viewProcessorRevertUserWrite(\n viewProcessor,\n oldViewCache,\n ackUserWrite.path,\n writesCache,\n completeCache,\n accumulator\n );\n }\n } else if (operation.type === OperationType.LISTEN_COMPLETE) {\n newViewCache = viewProcessorListenComplete(\n viewProcessor,\n oldViewCache,\n operation.path,\n writesCache,\n accumulator\n );\n } else {\n throw assertionError('Unknown operation type: ' + operation.type);\n }\n const changes = accumulator.getChanges();\n viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);\n return { viewCache: newViewCache, changes };\n}\n\nfunction viewProcessorMaybeAddValueEvent(\n oldViewCache: ViewCache,\n newViewCache: ViewCache,\n accumulator: Change[]\n): void {\n const eventSnap = newViewCache.eventCache;\n if (eventSnap.isFullyInitialized()) {\n const isLeafOrEmpty =\n eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);\n if (\n accumulator.length > 0 ||\n !oldViewCache.eventCache.isFullyInitialized() ||\n (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||\n !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())\n ) {\n accumulator.push(\n changeValue(viewCacheGetCompleteEventSnap(newViewCache))\n );\n }\n }\n}\n\nfunction viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n changePath: Path,\n writesCache: WriteTreeRef,\n source: CompleteChildSource,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldEventSnap = viewCache.eventCache;\n if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n } else {\n let newEventCache, serverNode;\n if (pathIsEmpty(changePath)) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n assert(\n viewCache.serverCache.isFullyInitialized(),\n 'If change path is empty, we must have complete server data'\n );\n if (viewCache.serverCache.isFiltered()) {\n // We need to special case this, because we need to only apply writes to complete children, or\n // we might end up raising events for incomplete children. If the server data is filtered deep\n // writes cannot be guaranteed to be complete\n const serverCache = viewCacheGetCompleteServerSnap(viewCache);\n const completeChildren =\n serverCache instanceof ChildrenNode\n ? serverCache\n : ChildrenNode.EMPTY_NODE;\n const completeEventChildren = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n completeChildren\n );\n newEventCache = viewProcessor.filter.updateFullNode(\n viewCache.eventCache.getNode(),\n completeEventChildren,\n accumulator\n );\n } else {\n const completeNode = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n newEventCache = viewProcessor.filter.updateFullNode(\n viewCache.eventCache.getNode(),\n completeNode,\n accumulator\n );\n }\n } else {\n const childKey = pathGetFront(changePath);\n if (childKey === '.priority') {\n assert(\n pathGetLength(changePath) === 1,\n \"Can't have a priority with additional path components\"\n );\n const oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.serverCache.getNode();\n // we might have overwrites for this priority\n const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(\n writesCache,\n changePath,\n oldEventNode,\n serverNode\n );\n if (updatedPriority != null) {\n newEventCache = viewProcessor.filter.updatePriority(\n oldEventNode,\n updatedPriority\n );\n } else {\n // priority didn't change, keep old node\n newEventCache = oldEventSnap.getNode();\n }\n } else {\n const childChangePath = pathPopFront(changePath);\n // update child\n let newEventChild;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.serverCache.getNode();\n const eventChildUpdate =\n writeTreeRefCalcEventCacheAfterServerOverwrite(\n writesCache,\n changePath,\n oldEventSnap.getNode(),\n serverNode\n );\n if (eventChildUpdate != null) {\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey)\n .updateChild(childChangePath, eventChildUpdate);\n } else {\n // Nothing changed, just keep the old child\n newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);\n }\n } else {\n newEventChild = writeTreeRefCalcCompleteChild(\n writesCache,\n childKey,\n viewCache.serverCache\n );\n }\n if (newEventChild != null) {\n newEventCache = viewProcessor.filter.updateChild(\n oldEventSnap.getNode(),\n childKey,\n newEventChild,\n childChangePath,\n source,\n accumulator\n );\n } else {\n // no complete child available or no change\n newEventCache = oldEventSnap.getNode();\n }\n }\n }\n return viewCacheUpdateEventSnap(\n viewCache,\n newEventCache,\n oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath),\n viewProcessor.filter.filtersNodes()\n );\n }\n}\n\nfunction viewProcessorApplyServerOverwrite(\n viewProcessor: ViewProcessor,\n oldViewCache: ViewCache,\n changePath: Path,\n changedSnap: Node,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n filterServerNode: boolean,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldServerSnap = oldViewCache.serverCache;\n let newServerCache;\n const serverFilter = filterServerNode\n ? viewProcessor.filter\n : viewProcessor.filter.getIndexedFilter();\n if (pathIsEmpty(changePath)) {\n newServerCache = serverFilter.updateFullNode(\n oldServerSnap.getNode(),\n changedSnap,\n null\n );\n } else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\n const newServerNode = oldServerSnap\n .getNode()\n .updateChild(changePath, changedSnap);\n newServerCache = serverFilter.updateFullNode(\n oldServerSnap.getNode(),\n newServerNode,\n null\n );\n } else {\n const childKey = pathGetFront(changePath);\n if (\n !oldServerSnap.isCompleteForPath(changePath) &&\n pathGetLength(changePath) > 1\n ) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n const childChangePath = pathPopFront(changePath);\n const childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n const newChildNode = childNode.updateChild(childChangePath, changedSnap);\n if (childKey === '.priority') {\n newServerCache = serverFilter.updatePriority(\n oldServerSnap.getNode(),\n newChildNode\n );\n } else {\n newServerCache = serverFilter.updateChild(\n oldServerSnap.getNode(),\n childKey,\n newChildNode,\n childChangePath,\n NO_COMPLETE_CHILD_SOURCE,\n null\n );\n }\n }\n const newViewCache = viewCacheUpdateServerSnap(\n oldViewCache,\n newServerCache,\n oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath),\n serverFilter.filtersNodes()\n );\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n newViewCache,\n completeCache\n );\n return viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor,\n newViewCache,\n changePath,\n writesCache,\n source,\n accumulator\n );\n}\n\nfunction viewProcessorApplyUserOverwrite(\n viewProcessor: ViewProcessor,\n oldViewCache: ViewCache,\n changePath: Path,\n changedSnap: Node,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldEventSnap = oldViewCache.eventCache;\n let newViewCache, newEventCache;\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n oldViewCache,\n completeCache\n );\n if (pathIsEmpty(changePath)) {\n newEventCache = viewProcessor.filter.updateFullNode(\n oldViewCache.eventCache.getNode(),\n changedSnap,\n accumulator\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventCache,\n true,\n viewProcessor.filter.filtersNodes()\n );\n } else {\n const childKey = pathGetFront(changePath);\n if (childKey === '.priority') {\n newEventCache = viewProcessor.filter.updatePriority(\n oldViewCache.eventCache.getNode(),\n changedSnap\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventCache,\n oldEventSnap.isFullyInitialized(),\n oldEventSnap.isFiltered()\n );\n } else {\n const childChangePath = pathPopFront(changePath);\n const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n let newChild;\n if (pathIsEmpty(childChangePath)) {\n // Child overwrite, we can replace the child\n newChild = changedSnap;\n } else {\n const childNode = source.getCompleteChild(childKey);\n if (childNode != null) {\n if (\n pathGetBack(childChangePath) === '.priority' &&\n childNode.getChild(pathParent(childChangePath)).isEmpty()\n ) {\n // This is a priority update on an empty node. If this node exists on the server, the\n // server will send down the priority in the update, so ignore for now\n newChild = childNode;\n } else {\n newChild = childNode.updateChild(childChangePath, changedSnap);\n }\n } else {\n // There is no complete child node available\n newChild = ChildrenNode.EMPTY_NODE;\n }\n }\n if (!oldChild.equals(newChild)) {\n const newEventSnap = viewProcessor.filter.updateChild(\n oldEventSnap.getNode(),\n childKey,\n newChild,\n childChangePath,\n source,\n accumulator\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventSnap,\n oldEventSnap.isFullyInitialized(),\n viewProcessor.filter.filtersNodes()\n );\n } else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n}\n\nfunction viewProcessorCacheHasChild(\n viewCache: ViewCache,\n childKey: string\n): boolean {\n return viewCache.eventCache.isCompleteForChild(childKey);\n}\n\nfunction viewProcessorApplyUserMerge(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n changedChildren: ImmutableTree,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n let curViewCache = viewCache;\n changedChildren.foreach((relativePath, childNode) => {\n const writePath = pathChild(path, relativePath);\n if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\n curViewCache = viewProcessorApplyUserOverwrite(\n viewProcessor,\n curViewCache,\n writePath,\n childNode,\n writesCache,\n serverCache,\n accumulator\n );\n }\n });\n\n changedChildren.foreach((relativePath, childNode) => {\n const writePath = pathChild(path, relativePath);\n if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\n curViewCache = viewProcessorApplyUserOverwrite(\n viewProcessor,\n curViewCache,\n writePath,\n childNode,\n writesCache,\n serverCache,\n accumulator\n );\n }\n });\n\n return curViewCache;\n}\n\nfunction viewProcessorApplyMerge(\n viewProcessor: ViewProcessor,\n node: Node,\n merge: ImmutableTree\n): Node {\n merge.foreach((relativePath, childNode) => {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n}\n\nfunction viewProcessorApplyServerMerge(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n changedChildren: ImmutableTree,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n filterServerNode: boolean,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\n // wait for the complete data update coming soon.\n if (\n viewCache.serverCache.getNode().isEmpty() &&\n !viewCache.serverCache.isFullyInitialized()\n ) {\n return viewCache;\n }\n\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n let curViewCache = viewCache;\n let viewMergeTree: ImmutableTree;\n if (pathIsEmpty(path)) {\n viewMergeTree = changedChildren;\n } else {\n viewMergeTree = new ImmutableTree(null).setTree(\n path,\n changedChildren\n );\n }\n const serverNode = viewCache.serverCache.getNode();\n viewMergeTree.children.inorderTraversal((childKey, childTree) => {\n if (serverNode.hasChild(childKey)) {\n const serverChild = viewCache.serverCache\n .getNode()\n .getImmediateChild(childKey);\n const newChild = viewProcessorApplyMerge(\n viewProcessor,\n serverChild,\n childTree\n );\n curViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\n curViewCache,\n new Path(childKey),\n newChild,\n writesCache,\n serverCache,\n filterServerNode,\n accumulator\n );\n }\n });\n viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {\n const isUnknownDeepMerge =\n !viewCache.serverCache.isCompleteForChild(childKey) &&\n childMergeTree.value === null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n const serverChild = viewCache.serverCache\n .getNode()\n .getImmediateChild(childKey);\n const newChild = viewProcessorApplyMerge(\n viewProcessor,\n serverChild,\n childMergeTree\n );\n curViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\n curViewCache,\n new Path(childKey),\n newChild,\n writesCache,\n serverCache,\n filterServerNode,\n accumulator\n );\n }\n });\n\n return curViewCache;\n}\n\nfunction viewProcessorAckUserWrite(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n ackPath: Path,\n affectedTree: ImmutableTree,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {\n return viewCache;\n }\n\n // Only filter server node if it is currently filtered\n const filterServerNode = viewCache.serverCache.isFiltered();\n\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\n // now that it won't be shadowed.\n const serverCache = viewCache.serverCache;\n if (affectedTree.value != null) {\n // This is an overwrite.\n if (\n (pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)\n ) {\n return viewProcessorApplyServerOverwrite(\n viewProcessor,\n viewCache,\n ackPath,\n serverCache.getNode().getChild(ackPath),\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n } else if (pathIsEmpty(ackPath)) {\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\n // should just re-apply whatever we have in our cache as a merge.\n let changedChildren = new ImmutableTree(null);\n serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {\n changedChildren = changedChildren.set(new Path(name), node);\n });\n return viewProcessorApplyServerMerge(\n viewProcessor,\n viewCache,\n ackPath,\n changedChildren,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n } else {\n return viewCache;\n }\n } else {\n // This is a merge.\n let changedChildren = new ImmutableTree(null);\n affectedTree.foreach((mergePath, value) => {\n const serverCachePath = pathChild(ackPath, mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren = changedChildren.set(\n mergePath,\n serverCache.getNode().getChild(serverCachePath)\n );\n }\n });\n return viewProcessorApplyServerMerge(\n viewProcessor,\n viewCache,\n ackPath,\n changedChildren,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n}\n\nfunction viewProcessorListenComplete(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n writesCache: WriteTreeRef,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldServerNode = viewCache.serverCache;\n const newViewCache = viewCacheUpdateServerSnap(\n viewCache,\n oldServerNode.getNode(),\n oldServerNode.isFullyInitialized() || pathIsEmpty(path),\n oldServerNode.isFiltered()\n );\n return viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor,\n newViewCache,\n path,\n writesCache,\n NO_COMPLETE_CHILD_SOURCE,\n accumulator\n );\n}\n\nfunction viewProcessorRevertUserWrite(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n writesCache: WriteTreeRef,\n completeServerCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n let complete;\n if (writeTreeRefShadowingWrite(writesCache, path) != null) {\n return viewCache;\n } else {\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n viewCache,\n completeServerCache\n );\n const oldEventCache = viewCache.eventCache.getNode();\n let newEventCache;\n if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {\n let newNode;\n if (viewCache.serverCache.isFullyInitialized()) {\n newNode = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n } else {\n const serverChildren = viewCache.serverCache.getNode();\n assert(\n serverChildren instanceof ChildrenNode,\n 'serverChildren would be complete if leaf node'\n );\n newNode = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n serverChildren as ChildrenNode\n );\n }\n newNode = newNode as Node;\n newEventCache = viewProcessor.filter.updateFullNode(\n oldEventCache,\n newNode,\n accumulator\n );\n } else {\n const childKey = pathGetFront(path);\n let newChild = writeTreeRefCalcCompleteChild(\n writesCache,\n childKey,\n viewCache.serverCache\n );\n if (\n newChild == null &&\n viewCache.serverCache.isCompleteForChild(childKey)\n ) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = viewProcessor.filter.updateChild(\n oldEventCache,\n childKey,\n newChild,\n pathPopFront(path),\n source,\n accumulator\n );\n } else if (viewCache.eventCache.getNode().hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = viewProcessor.filter.updateChild(\n oldEventCache,\n childKey,\n ChildrenNode.EMPTY_NODE,\n pathPopFront(path),\n source,\n accumulator\n );\n } else {\n newEventCache = oldEventCache;\n }\n if (\n newEventCache.isEmpty() &&\n viewCache.serverCache.isFullyInitialized()\n ) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n if (complete.isLeafNode()) {\n newEventCache = viewProcessor.filter.updateFullNode(\n newEventCache,\n complete,\n accumulator\n );\n }\n }\n }\n complete =\n viewCache.serverCache.isFullyInitialized() ||\n writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;\n return viewCacheUpdateEventSnap(\n viewCache,\n newEventCache,\n complete,\n viewProcessor.filter.filtersNodes()\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Operation, OperationType } from '../operation/Operation';\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { PRIORITY_INDEX } from '../snap/indexes/PriorityIndex';\nimport { Node } from '../snap/Node';\nimport { Path, pathGetFront, pathIsEmpty } from '../util/Path';\nimport { WriteTreeRef } from '../WriteTree';\n\nimport { CacheNode } from './CacheNode';\nimport { Change, changeChildAdded, changeValue } from './Change';\nimport { CancelEvent, Event } from './Event';\nimport {\n EventGenerator,\n eventGeneratorGenerateEventsForChanges\n} from './EventGenerator';\nimport { EventRegistration, QueryContext } from './EventRegistration';\nimport { IndexedFilter } from './filter/IndexedFilter';\nimport { queryParamsGetNodeFilter } from './QueryParams';\nimport {\n newViewCache,\n ViewCache,\n viewCacheGetCompleteEventSnap,\n viewCacheGetCompleteServerSnap\n} from './ViewCache';\nimport {\n newViewProcessor,\n ViewProcessor,\n viewProcessorApplyOperation,\n viewProcessorAssertIndexed\n} from './ViewProcessor';\n\n/**\n * A view represents a specific location and query that has 1 or more event registrations.\n *\n * It does several things:\n * - Maintains the list of event registrations for this location/query.\n * - Maintains a cache of the data visible for this location/query.\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\n * registrations returns the set of events to be raised.\n */\nexport class View {\n processor_: ViewProcessor;\n viewCache_: ViewCache;\n eventRegistrations_: EventRegistration[] = [];\n eventGenerator_: EventGenerator;\n\n constructor(private query_: QueryContext, initialViewCache: ViewCache) {\n const params = this.query_._queryParams;\n\n const indexFilter = new IndexedFilter(params.getIndex());\n const filter = queryParamsGetNodeFilter(params);\n\n this.processor_ = newViewProcessor(filter);\n\n const initialServerCache = initialViewCache.serverCache;\n const initialEventCache = initialViewCache.eventCache;\n\n // Don't filter server node with other filter than index, wait for tagged listen\n const serverSnap = indexFilter.updateFullNode(\n ChildrenNode.EMPTY_NODE,\n initialServerCache.getNode(),\n null\n );\n const eventSnap = filter.updateFullNode(\n ChildrenNode.EMPTY_NODE,\n initialEventCache.getNode(),\n null\n );\n const newServerCache = new CacheNode(\n serverSnap,\n initialServerCache.isFullyInitialized(),\n indexFilter.filtersNodes()\n );\n const newEventCache = new CacheNode(\n eventSnap,\n initialEventCache.isFullyInitialized(),\n filter.filtersNodes()\n );\n\n this.viewCache_ = newViewCache(newEventCache, newServerCache);\n this.eventGenerator_ = new EventGenerator(this.query_);\n }\n\n get query(): QueryContext {\n return this.query_;\n }\n}\n\nexport function viewGetServerCache(view: View): Node | null {\n return view.viewCache_.serverCache.getNode();\n}\n\nexport function viewGetCompleteNode(view: View): Node | null {\n return viewCacheGetCompleteEventSnap(view.viewCache_);\n}\n\nexport function viewGetCompleteServerCache(\n view: View,\n path: Path\n): Node | null {\n const cache = viewCacheGetCompleteServerSnap(view.viewCache_);\n if (cache) {\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\n // we need to see if it contains the child we're interested in.\n if (\n view.query._queryParams.loadsAllData() ||\n (!pathIsEmpty(path) &&\n !cache.getImmediateChild(pathGetFront(path)).isEmpty())\n ) {\n return cache.getChild(path);\n }\n }\n return null;\n}\n\nexport function viewIsEmpty(view: View): boolean {\n return view.eventRegistrations_.length === 0;\n}\n\nexport function viewAddEventRegistration(\n view: View,\n eventRegistration: EventRegistration\n) {\n view.eventRegistrations_.push(eventRegistration);\n}\n\n/**\n * @param eventRegistration - If null, remove all callbacks.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @returns Cancel events, if cancelError was provided.\n */\nexport function viewRemoveEventRegistration(\n view: View,\n eventRegistration: EventRegistration | null,\n cancelError?: Error\n): Event[] {\n const cancelEvents: CancelEvent[] = [];\n if (cancelError) {\n assert(\n eventRegistration == null,\n 'A cancel should cancel all event registrations.'\n );\n const path = view.query._path;\n view.eventRegistrations_.forEach(registration => {\n const maybeEvent = registration.createCancelEvent(cancelError, path);\n if (maybeEvent) {\n cancelEvents.push(maybeEvent);\n }\n });\n }\n\n if (eventRegistration) {\n let remaining = [];\n for (let i = 0; i < view.eventRegistrations_.length; ++i) {\n const existing = view.eventRegistrations_[i];\n if (!existing.matches(eventRegistration)) {\n remaining.push(existing);\n } else if (eventRegistration.hasAnyCallback()) {\n // We're removing just this one\n remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));\n break;\n }\n }\n view.eventRegistrations_ = remaining;\n } else {\n view.eventRegistrations_ = [];\n }\n return cancelEvents;\n}\n\n/**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n */\nexport function viewApplyOperation(\n view: View,\n operation: Operation,\n writesCache: WriteTreeRef,\n completeServerCache: Node | null\n): Event[] {\n if (\n operation.type === OperationType.MERGE &&\n operation.source.queryId !== null\n ) {\n assert(\n viewCacheGetCompleteServerSnap(view.viewCache_),\n 'We should always have a full cache before handling merges'\n );\n assert(\n viewCacheGetCompleteEventSnap(view.viewCache_),\n 'Missing event cache, even though we have a server cache'\n );\n }\n\n const oldViewCache = view.viewCache_;\n const result = viewProcessorApplyOperation(\n view.processor_,\n oldViewCache,\n operation,\n writesCache,\n completeServerCache\n );\n viewProcessorAssertIndexed(view.processor_, result.viewCache);\n\n assert(\n result.viewCache.serverCache.isFullyInitialized() ||\n !oldViewCache.serverCache.isFullyInitialized(),\n 'Once a server snap is complete, it should never go back'\n );\n\n view.viewCache_ = result.viewCache;\n\n return viewGenerateEventsForChanges_(\n view,\n result.changes,\n result.viewCache.eventCache.getNode(),\n null\n );\n}\n\nexport function viewGetInitialEvents(\n view: View,\n registration: EventRegistration\n): Event[] {\n const eventSnap = view.viewCache_.eventCache;\n const initialChanges: Change[] = [];\n if (!eventSnap.getNode().isLeafNode()) {\n const eventNode = eventSnap.getNode() as ChildrenNode;\n eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n initialChanges.push(changeChildAdded(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(changeValue(eventSnap.getNode()));\n }\n return viewGenerateEventsForChanges_(\n view,\n initialChanges,\n eventSnap.getNode(),\n registration\n );\n}\n\nfunction viewGenerateEventsForChanges_(\n view: View,\n changes: Change[],\n eventCache: Node,\n eventRegistration?: EventRegistration\n): Event[] {\n const registrations = eventRegistration\n ? [eventRegistration]\n : view.eventRegistrations_;\n return eventGeneratorGenerateEventsForChanges(\n view.eventGenerator_,\n changes,\n eventCache,\n registrations\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ReferenceConstructor } from '../api/Reference';\n\nimport { Operation } from './operation/Operation';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { Path } from './util/Path';\nimport { CacheNode } from './view/CacheNode';\nimport { Event } from './view/Event';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\nimport {\n View,\n viewAddEventRegistration,\n viewApplyOperation,\n viewGetCompleteServerCache,\n viewGetInitialEvents,\n viewIsEmpty,\n viewRemoveEventRegistration\n} from './view/View';\nimport { newViewCache } from './view/ViewCache';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteEventCache,\n writeTreeRefCalcCompleteEventChildren\n} from './WriteTree';\n\nlet referenceConstructor: ReferenceConstructor;\n\n/**\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\n * and user writes (set, transaction, update).\n *\n * It's responsible for:\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\n * applyUserOverwrite, etc.)\n */\nexport class SyncPoint {\n /**\n * The Views being tracked at this location in the tree, stored as a map where the key is a\n * queryId and the value is the View for that query.\n *\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\n */\n readonly views: Map = new Map();\n}\n\nexport function syncPointSetReferenceConstructor(\n val: ReferenceConstructor\n): void {\n assert(\n !referenceConstructor,\n '__referenceConstructor has already been defined'\n );\n referenceConstructor = val;\n}\n\nfunction syncPointGetReferenceConstructor(): ReferenceConstructor {\n assert(referenceConstructor, 'Reference.ts has not been loaded');\n return referenceConstructor;\n}\n\nexport function syncPointIsEmpty(syncPoint: SyncPoint): boolean {\n return syncPoint.views.size === 0;\n}\n\nexport function syncPointApplyOperation(\n syncPoint: SyncPoint,\n operation: Operation,\n writesCache: WriteTreeRef,\n optCompleteServerCache: Node | null\n): Event[] {\n const queryId = operation.source.queryId;\n if (queryId !== null) {\n const view = syncPoint.views.get(queryId);\n assert(view != null, 'SyncTree gave us an op for an invalid query.');\n return viewApplyOperation(\n view,\n operation,\n writesCache,\n optCompleteServerCache\n );\n } else {\n let events: Event[] = [];\n\n for (const view of syncPoint.views.values()) {\n events = events.concat(\n viewApplyOperation(view, operation, writesCache, optCompleteServerCache)\n );\n }\n\n return events;\n }\n}\n\n/**\n * Get a view for the specified query.\n *\n * @param query - The query to return a view for\n * @param writesCache\n * @param serverCache\n * @param serverCacheComplete\n * @returns Events to raise.\n */\nexport function syncPointGetView(\n syncPoint: SyncPoint,\n query: QueryContext,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n serverCacheComplete: boolean\n): View {\n const queryId = query._queryIdentifier;\n const view = syncPoint.views.get(queryId);\n if (!view) {\n // TODO: make writesCache take flag for complete server node\n let eventCache = writeTreeRefCalcCompleteEventCache(\n writesCache,\n serverCacheComplete ? serverCache : null\n );\n let eventCacheComplete = false;\n if (eventCache) {\n eventCacheComplete = true;\n } else if (serverCache instanceof ChildrenNode) {\n eventCache = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n serverCache\n );\n eventCacheComplete = false;\n } else {\n eventCache = ChildrenNode.EMPTY_NODE;\n eventCacheComplete = false;\n }\n const viewCache = newViewCache(\n new CacheNode(eventCache, eventCacheComplete, false),\n new CacheNode(serverCache, serverCacheComplete, false)\n );\n return new View(query, viewCache);\n }\n return view;\n}\n\n/**\n * Add an event callback for the specified query.\n *\n * @param query\n * @param eventRegistration\n * @param writesCache\n * @param serverCache - Complete server cache, if we have it.\n * @param serverCacheComplete\n * @returns Events to raise.\n */\nexport function syncPointAddEventRegistration(\n syncPoint: SyncPoint,\n query: QueryContext,\n eventRegistration: EventRegistration,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n serverCacheComplete: boolean\n): Event[] {\n const view = syncPointGetView(\n syncPoint,\n query,\n writesCache,\n serverCache,\n serverCacheComplete\n );\n if (!syncPoint.views.has(query._queryIdentifier)) {\n syncPoint.views.set(query._queryIdentifier, view);\n }\n // This is guaranteed to exist now, we just created anything that was missing\n viewAddEventRegistration(view, eventRegistration);\n return viewGetInitialEvents(view, eventRegistration);\n}\n\n/**\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\n *\n * If query is the default query, we'll check all views for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\n *\n * @param eventRegistration - If null, remove all callbacks.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @returns removed queries and any cancel events\n */\nexport function syncPointRemoveEventRegistration(\n syncPoint: SyncPoint,\n query: QueryContext,\n eventRegistration: EventRegistration | null,\n cancelError?: Error\n): { removed: QueryContext[]; events: Event[] } {\n const queryId = query._queryIdentifier;\n const removed: QueryContext[] = [];\n let cancelEvents: Event[] = [];\n const hadCompleteView = syncPointHasCompleteView(syncPoint);\n if (queryId === 'default') {\n // When you do ref.off(...), we search all views for the registration to remove.\n for (const [viewQueryId, view] of syncPoint.views.entries()) {\n cancelEvents = cancelEvents.concat(\n viewRemoveEventRegistration(view, eventRegistration, cancelError)\n );\n if (viewIsEmpty(view)) {\n syncPoint.views.delete(viewQueryId);\n\n // We'll deal with complete views later.\n if (!view.query._queryParams.loadsAllData()) {\n removed.push(view.query);\n }\n }\n }\n } else {\n // remove the callback from the specific view.\n const view = syncPoint.views.get(queryId);\n if (view) {\n cancelEvents = cancelEvents.concat(\n viewRemoveEventRegistration(view, eventRegistration, cancelError)\n );\n if (viewIsEmpty(view)) {\n syncPoint.views.delete(queryId);\n\n // We'll deal with complete views later.\n if (!view.query._queryParams.loadsAllData()) {\n removed.push(view.query);\n }\n }\n }\n }\n\n if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {\n // We removed our last complete view.\n removed.push(\n new (syncPointGetReferenceConstructor())(query._repo, query._path)\n );\n }\n\n return { removed, events: cancelEvents };\n}\n\nexport function syncPointGetQueryViews(syncPoint: SyncPoint): View[] {\n const result = [];\n for (const view of syncPoint.views.values()) {\n if (!view.query._queryParams.loadsAllData()) {\n result.push(view);\n }\n }\n return result;\n}\n\n/**\n * @param path - The path to the desired complete snapshot\n * @returns A complete cache, if it exists\n */\nexport function syncPointGetCompleteServerCache(\n syncPoint: SyncPoint,\n path: Path\n): Node | null {\n let serverCache: Node | null = null;\n for (const view of syncPoint.views.values()) {\n serverCache = serverCache || viewGetCompleteServerCache(view, path);\n }\n return serverCache;\n}\n\nexport function syncPointViewForQuery(\n syncPoint: SyncPoint,\n query: QueryContext\n): View | null {\n const params = query._queryParams;\n if (params.loadsAllData()) {\n return syncPointGetCompleteView(syncPoint);\n } else {\n const queryId = query._queryIdentifier;\n return syncPoint.views.get(queryId);\n }\n}\n\nexport function syncPointViewExistsForQuery(\n syncPoint: SyncPoint,\n query: QueryContext\n): boolean {\n return syncPointViewForQuery(syncPoint, query) != null;\n}\n\nexport function syncPointHasCompleteView(syncPoint: SyncPoint): boolean {\n return syncPointGetCompleteView(syncPoint) != null;\n}\n\nexport function syncPointGetCompleteView(syncPoint: SyncPoint): View | null {\n for (const view of syncPoint.views.values()) {\n if (view.query._queryParams.loadsAllData()) {\n return view;\n }\n }\n return null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ReferenceConstructor } from '../api/Reference';\n\nimport { AckUserWrite } from './operation/AckUserWrite';\nimport { ListenComplete } from './operation/ListenComplete';\nimport { Merge } from './operation/Merge';\nimport {\n newOperationSourceServer,\n newOperationSourceServerTaggedQuery,\n newOperationSourceUser,\n Operation\n} from './operation/Operation';\nimport { Overwrite } from './operation/Overwrite';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport {\n SyncPoint,\n syncPointAddEventRegistration,\n syncPointApplyOperation,\n syncPointGetCompleteServerCache,\n syncPointGetCompleteView,\n syncPointGetQueryViews,\n syncPointGetView,\n syncPointHasCompleteView,\n syncPointIsEmpty,\n syncPointRemoveEventRegistration,\n syncPointViewExistsForQuery,\n syncPointViewForQuery\n} from './SyncPoint';\nimport { ImmutableTree } from './util/ImmutableTree';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathGetFront,\n pathIsEmpty\n} from './util/Path';\nimport { each, errorForServerCode } from './util/util';\nimport { CacheNode } from './view/CacheNode';\nimport { Event } from './view/Event';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\nimport { View, viewGetCompleteNode, viewGetServerCache } from './view/View';\nimport {\n newWriteTree,\n WriteTree,\n writeTreeAddMerge,\n writeTreeAddOverwrite,\n writeTreeCalcCompleteEventCache,\n writeTreeChildWrites,\n writeTreeGetWrite,\n WriteTreeRef,\n writeTreeRefChild,\n writeTreeRemoveWrite\n} from './WriteTree';\n\nlet referenceConstructor: ReferenceConstructor;\n\nexport function syncTreeSetReferenceConstructor(\n val: ReferenceConstructor\n): void {\n assert(\n !referenceConstructor,\n '__referenceConstructor has already been defined'\n );\n referenceConstructor = val;\n}\n\nfunction syncTreeGetReferenceConstructor(): ReferenceConstructor {\n assert(referenceConstructor, 'Reference.ts has not been loaded');\n return referenceConstructor;\n}\n\nexport interface ListenProvider {\n startListening(\n query: QueryContext,\n tag: number | null,\n hashFn: () => string,\n onComplete: (a: string, b?: unknown) => Event[]\n ): Event[];\n\n stopListening(a: QueryContext, b: number | null): void;\n}\n\n/**\n * Static tracker for next query tag.\n */\nlet syncTreeNextQueryTag_ = 1;\n\nexport function resetSyncTreeTag() {\n syncTreeNextQueryTag_ = 1;\n}\n\n/**\n * SyncTree is the central class for managing event callback registration, data caching, views\n * (query processing), and event generation. There are typically two SyncTree instances for\n * each Repo, one for the normal Firebase data, and one for the .info data.\n *\n * It has a number of responsibilities, including:\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\n * - Applying and caching data changes for user set(), transaction(), and update() calls\n * (applyUserOverwrite(), applyUserMerge()).\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\n * applyServerMerge()).\n * - Generating user-facing events for server and user changes (all of the apply* methods\n * return the set of events that need to be raised as a result).\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\n * to the correct set of paths and queries to satisfy the current set of user event\n * callbacks (listens are started/stopped using the provided listenProvider).\n *\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\n * events are returned to the caller rather than raised synchronously.\n *\n */\nexport class SyncTree {\n /**\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\n */\n syncPointTree_: ImmutableTree = new ImmutableTree(null);\n\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n */\n pendingWriteTree_: WriteTree = newWriteTree();\n\n readonly tagToQueryMap: Map = new Map();\n readonly queryToTagMap: Map = new Map();\n\n /**\n * @param listenProvider_ - Used by SyncTree to start / stop listening\n * to server data.\n */\n constructor(public listenProvider_: ListenProvider) {}\n}\n\n/**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyUserOverwrite(\n syncTree: SyncTree,\n path: Path,\n newData: Node,\n writeId: number,\n visible?: boolean\n): Event[] {\n // Record pending write.\n writeTreeAddOverwrite(\n syncTree.pendingWriteTree_,\n path,\n newData,\n writeId,\n visible\n );\n\n if (!visible) {\n return [];\n } else {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Overwrite(newOperationSourceUser(), path, newData)\n );\n }\n}\n\n/**\n * Apply the data from a user-generated update() call\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyUserMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n writeId: number\n): Event[] {\n // Record pending merge.\n writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);\n\n const changeTree = ImmutableTree.fromObject(changedChildren);\n\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Merge(newOperationSourceUser(), path, changeTree)\n );\n}\n\n/**\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\n *\n * @param revert - True if the given write failed and needs to be reverted\n * @returns Events to raise.\n */\nexport function syncTreeAckUserWrite(\n syncTree: SyncTree,\n writeId: number,\n revert: boolean = false\n) {\n const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);\n const needToReevaluate = writeTreeRemoveWrite(\n syncTree.pendingWriteTree_,\n writeId\n );\n if (!needToReevaluate) {\n return [];\n } else {\n let affectedTree = new ImmutableTree(null);\n if (write.snap != null) {\n // overwrite\n affectedTree = affectedTree.set(newEmptyPath(), true);\n } else {\n each(write.children, (pathString: string) => {\n affectedTree = affectedTree.set(new Path(pathString), true);\n });\n }\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new AckUserWrite(write.path, affectedTree, revert)\n );\n }\n}\n\n/**\n * Apply new server data for the specified path..\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyServerOverwrite(\n syncTree: SyncTree,\n path: Path,\n newData: Node\n): Event[] {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Overwrite(newOperationSourceServer(), path, newData)\n );\n}\n\n/**\n * Apply new server data to be merged in at the specified path.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyServerMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node }\n): Event[] {\n const changeTree = ImmutableTree.fromObject(changedChildren);\n\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Merge(newOperationSourceServer(), path, changeTree)\n );\n}\n\n/**\n * Apply a listen complete for a query\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyListenComplete(\n syncTree: SyncTree,\n path: Path\n): Event[] {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new ListenComplete(newOperationSourceServer(), path)\n );\n}\n\n/**\n * Apply a listen complete for a tagged query\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedListenComplete(\n syncTree: SyncTree,\n path: Path,\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const op = new ListenComplete(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath\n );\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n } else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n}\n\n/**\n * Remove event callback(s).\n *\n * If query is the default query, we'll check all queries for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\n *\n * @param eventRegistration - If null, all callbacks are removed.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no\n * deduping needs to take place. This flag allows toggling of that behavior\n * @returns Cancel events, if cancelError was provided.\n */\nexport function syncTreeRemoveEventRegistration(\n syncTree: SyncTree,\n query: QueryContext,\n eventRegistration: EventRegistration | null,\n cancelError?: Error,\n skipListenerDedup = false\n): Event[] {\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\n const path = query._path;\n const maybeSyncPoint = syncTree.syncPointTree_.get(path);\n let cancelEvents: Event[] = [];\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\n // not loadsAllData().\n if (\n maybeSyncPoint &&\n (query._queryIdentifier === 'default' ||\n syncPointViewExistsForQuery(maybeSyncPoint, query))\n ) {\n const removedAndEvents = syncPointRemoveEventRegistration(\n maybeSyncPoint,\n query,\n eventRegistration,\n cancelError\n );\n if (syncPointIsEmpty(maybeSyncPoint)) {\n syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);\n }\n\n const removed = removedAndEvents.removed;\n cancelEvents = removedAndEvents.events;\n\n if (!skipListenerDedup) {\n /**\n * We may have just removed one of many listeners and can short-circuit this whole process\n * We may also not have removed a default listener, in which case all of the descendant listeners should already be\n * properly set up.\n */\n\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\n // queryId === 'default'\n const removingDefault =\n -1 !==\n removed.findIndex(query => {\n return query._queryParams.loadsAllData();\n });\n const covered = syncTree.syncPointTree_.findOnPath(\n path,\n (relativePath, parentSyncPoint) =>\n syncPointHasCompleteView(parentSyncPoint)\n );\n\n if (removingDefault && !covered) {\n const subtree = syncTree.syncPointTree_.subtree(path);\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\n // removal\n if (!subtree.isEmpty()) {\n // We need to fold over our subtree and collect the listeners to send\n const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);\n\n // Ok, we've collected all the listens we need. Set them up.\n for (let i = 0; i < newViews.length; ++i) {\n const view = newViews[i],\n newQuery = view.query;\n const listener = syncTreeCreateListenerForView_(syncTree, view);\n syncTree.listenProvider_.startListening(\n syncTreeQueryForListening_(newQuery),\n syncTreeTagForQuery(syncTree, newQuery),\n listener.hashFn,\n listener.onComplete\n );\n }\n }\n // Otherwise there's nothing below us, so nothing we need to start listening on\n }\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\n if (!covered && removed.length > 0 && !cancelError) {\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\n // default. Otherwise, we need to iterate through and cancel each individual query\n if (removingDefault) {\n // We don't tag default listeners\n const defaultTag: number | null = null;\n syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(query),\n defaultTag\n );\n } else {\n removed.forEach((queryToRemove: QueryContext) => {\n const tagToRemove = syncTree.queryToTagMap.get(\n syncTreeMakeQueryKey_(queryToRemove)\n );\n syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(queryToRemove),\n tagToRemove\n );\n });\n }\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n syncTreeRemoveTags_(syncTree, removed);\n } else {\n // No-op, this listener must've been already removed\n }\n return cancelEvents;\n}\n\n/**\n * Apply new server data for the specified tagged query.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedQueryOverwrite(\n syncTree: SyncTree,\n path: Path,\n snap: Node,\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey != null) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const op = new Overwrite(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath,\n snap\n );\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n } else {\n // Query must have been removed already\n return [];\n }\n}\n\n/**\n * Apply server data to be merged in for the specified tagged query.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedQueryMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const changeTree = ImmutableTree.fromObject(changedChildren);\n const op = new Merge(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath,\n changeTree\n );\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n } else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n}\n\n/**\n * Add an event callback for the specified query.\n *\n * @returns Events to raise.\n */\nexport function syncTreeAddEventRegistration(\n syncTree: SyncTree,\n query: QueryContext,\n eventRegistration: EventRegistration,\n skipSetupListener = false\n): Event[] {\n const path = query._path;\n\n let serverCache: Node | null = null;\n let foundAncestorDefaultView = false;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\n const relativePath = newRelativePath(pathToSyncPoint, path);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPointHasCompleteView(sp);\n });\n let syncPoint = syncTree.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint();\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\n } else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n\n let serverCacheComplete;\n if (serverCache != null) {\n serverCacheComplete = true;\n } else {\n serverCacheComplete = false;\n serverCache = ChildrenNode.EMPTY_NODE;\n const subtree = syncTree.syncPointTree_.subtree(path);\n subtree.foreachChild((childName, childSyncPoint) => {\n const completeCache = syncPointGetCompleteServerCache(\n childSyncPoint,\n newEmptyPath()\n );\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(\n childName,\n completeCache\n );\n }\n });\n }\n\n const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);\n if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {\n // We need to track a tag for this query\n const queryKey = syncTreeMakeQueryKey_(query);\n assert(\n !syncTree.queryToTagMap.has(queryKey),\n 'View does not exist, but we have a tag'\n );\n const tag = syncTreeGetNextQueryTag_();\n syncTree.queryToTagMap.set(queryKey, tag);\n syncTree.tagToQueryMap.set(tag, queryKey);\n }\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);\n let events = syncPointAddEventRegistration(\n syncPoint,\n query,\n eventRegistration,\n writesCache,\n serverCache,\n serverCacheComplete\n );\n if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {\n const view = syncPointViewForQuery(syncPoint, query);\n events = events.concat(syncTreeSetupListener_(syncTree, query, view));\n }\n return events;\n}\n\n/**\n * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a\n * listener above it, we will get a false \"null\". This shouldn't be a problem because transactions will always\n * have a listener above, and atomic operations would correctly show a jitter of ->\n * as the write is applied locally and then acknowledged at the server.\n *\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\n *\n * @param path - The path to the data we want\n * @param writeIdsToExclude - A specific set to be excluded\n */\nexport function syncTreeCalcCompleteEventCache(\n syncTree: SyncTree,\n path: Path,\n writeIdsToExclude?: number[]\n): Node {\n const includeHiddenSets = true;\n const writeTree = syncTree.pendingWriteTree_;\n const serverCache = syncTree.syncPointTree_.findOnPath(\n path,\n (pathSoFar, syncPoint) => {\n const relativePath = newRelativePath(pathSoFar, path);\n const serverCache = syncPointGetCompleteServerCache(\n syncPoint,\n relativePath\n );\n if (serverCache) {\n return serverCache;\n }\n }\n );\n return writeTreeCalcCompleteEventCache(\n writeTree,\n path,\n serverCache,\n writeIdsToExclude,\n includeHiddenSets\n );\n}\n\nexport function syncTreeGetServerValue(\n syncTree: SyncTree,\n query: QueryContext\n): Node | null {\n const path = query._path;\n let serverCache: Node | null = null;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\n const relativePath = newRelativePath(pathToSyncPoint, path);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\n });\n let syncPoint = syncTree.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint();\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\n } else {\n serverCache =\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n const serverCacheComplete = serverCache != null;\n const serverCacheNode: CacheNode | null = serverCacheComplete\n ? new CacheNode(serverCache, true, false)\n : null;\n const writesCache: WriteTreeRef | null = writeTreeChildWrites(\n syncTree.pendingWriteTree_,\n query._path\n );\n const view: View = syncPointGetView(\n syncPoint,\n query,\n writesCache,\n serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE,\n serverCacheComplete\n );\n return viewGetCompleteNode(view);\n}\n\n/**\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\n *\n * NOTES:\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\n *\n * - We call applyOperation() on each SyncPoint passing three things:\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\n * 3. A snapshot Node with cached server data, if we have it.\n *\n * - We concatenate all of the events returned by each SyncPoint and return the result.\n */\nfunction syncTreeApplyOperationToSyncPoints_(\n syncTree: SyncTree,\n operation: Operation\n): Event[] {\n return syncTreeApplyOperationHelper_(\n operation,\n syncTree.syncPointTree_,\n /*serverCache=*/ null,\n writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath())\n );\n}\n\n/**\n * Recursive helper for applyOperationToSyncPoints_\n */\nfunction syncTreeApplyOperationHelper_(\n operation: Operation,\n syncPointTree: ImmutableTree,\n serverCache: Node | null,\n writesCache: WriteTreeRef\n): Event[] {\n if (pathIsEmpty(operation.path)) {\n return syncTreeApplyOperationDescendantsHelper_(\n operation,\n syncPointTree,\n serverCache,\n writesCache\n );\n } else {\n const syncPoint = syncPointTree.get(newEmptyPath());\n\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n\n let events: Event[] = [];\n const childName = pathGetFront(operation.path);\n const childOperation = operation.operationForChild(childName);\n const childTree = syncPointTree.children.get(childName);\n if (childTree && childOperation) {\n const childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n const childWritesCache = writeTreeRefChild(writesCache, childName);\n events = events.concat(\n syncTreeApplyOperationHelper_(\n childOperation,\n childTree,\n childServerCache,\n childWritesCache\n )\n );\n }\n\n if (syncPoint) {\n events = events.concat(\n syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)\n );\n }\n\n return events;\n }\n}\n\n/**\n * Recursive helper for applyOperationToSyncPoints_\n */\nfunction syncTreeApplyOperationDescendantsHelper_(\n operation: Operation,\n syncPointTree: ImmutableTree,\n serverCache: Node | null,\n writesCache: WriteTreeRef\n): Event[] {\n const syncPoint = syncPointTree.get(newEmptyPath());\n\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n\n let events: Event[] = [];\n syncPointTree.children.inorderTraversal((childName, childTree) => {\n const childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n const childWritesCache = writeTreeRefChild(writesCache, childName);\n const childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(\n syncTreeApplyOperationDescendantsHelper_(\n childOperation,\n childTree,\n childServerCache,\n childWritesCache\n )\n );\n }\n });\n\n if (syncPoint) {\n events = events.concat(\n syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)\n );\n }\n\n return events;\n}\n\nfunction syncTreeCreateListenerForView_(\n syncTree: SyncTree,\n view: View\n): { hashFn(): string; onComplete(a: string, b?: unknown): Event[] } {\n const query = view.query;\n const tag = syncTreeTagForQuery(syncTree, query);\n\n return {\n hashFn: () => {\n const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: (status: string): Event[] => {\n if (status === 'ok') {\n if (tag) {\n return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);\n } else {\n return syncTreeApplyListenComplete(syncTree, query._path);\n }\n } else {\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\n const error = errorForServerCode(status, query);\n return syncTreeRemoveEventRegistration(\n syncTree,\n query,\n /*eventRegistration*/ null,\n error\n );\n }\n }\n };\n}\n\n/**\n * Return the tag associated with the given query.\n */\nexport function syncTreeTagForQuery(\n syncTree: SyncTree,\n query: QueryContext\n): number | null {\n const queryKey = syncTreeMakeQueryKey_(query);\n return syncTree.queryToTagMap.get(queryKey);\n}\n\n/**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n */\nfunction syncTreeMakeQueryKey_(query: QueryContext): string {\n return query._path.toString() + '$' + query._queryIdentifier;\n}\n\n/**\n * Return the query associated with the given tag, if we have one\n */\nfunction syncTreeQueryKeyForTag_(\n syncTree: SyncTree,\n tag: number\n): string | null {\n return syncTree.tagToQueryMap.get(tag);\n}\n\n/**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n */\nfunction syncTreeParseQueryKey_(queryKey: string): {\n queryId: string;\n path: Path;\n} {\n const splitIndex = queryKey.indexOf('$');\n assert(\n splitIndex !== -1 && splitIndex < queryKey.length - 1,\n 'Bad queryKey.'\n );\n return {\n queryId: queryKey.substr(splitIndex + 1),\n path: new Path(queryKey.substr(0, splitIndex))\n };\n}\n\n/**\n * A helper method to apply tagged operations\n */\nfunction syncTreeApplyTaggedOperation_(\n syncTree: SyncTree,\n queryPath: Path,\n operation: Operation\n): Event[] {\n const syncPoint = syncTree.syncPointTree_.get(queryPath);\n assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n const writesCache = writeTreeChildWrites(\n syncTree.pendingWriteTree_,\n queryPath\n );\n return syncPointApplyOperation(syncPoint, operation, writesCache, null);\n}\n\n/**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n */\nfunction syncTreeCollectDistinctViewsForSubTree_(\n subtree: ImmutableTree\n): View[] {\n return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {\n if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {\n const completeView = syncPointGetCompleteView(maybeChildSyncPoint);\n return [completeView];\n } else {\n // No complete view here, flatten any deeper listens into an array\n let views: View[] = [];\n if (maybeChildSyncPoint) {\n views = syncPointGetQueryViews(maybeChildSyncPoint);\n }\n each(childMap, (_key: string, childViews: View[]) => {\n views = views.concat(childViews);\n });\n return views;\n }\n });\n}\n\n/**\n * Normalizes a query to a query we send the server for listening\n *\n * @returns The normalized query\n */\nfunction syncTreeQueryForListening_(query: QueryContext): QueryContext {\n if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {\n // We treat queries that load all data as default queries\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n // from Query\n return new (syncTreeGetReferenceConstructor())(query._repo, query._path);\n } else {\n return query;\n }\n}\n\nfunction syncTreeRemoveTags_(syncTree: SyncTree, queries: QueryContext[]) {\n for (let j = 0; j < queries.length; ++j) {\n const removedQuery = queries[j];\n if (!removedQuery._queryParams.loadsAllData()) {\n // We should have a tag for this\n const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);\n const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);\n syncTree.queryToTagMap.delete(removedQueryKey);\n syncTree.tagToQueryMap.delete(removedQueryTag);\n }\n }\n}\n\n/**\n * Static accessor for query tags.\n */\nfunction syncTreeGetNextQueryTag_(): number {\n return syncTreeNextQueryTag_++;\n}\n\n/**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @returns This method can return events to support synchronous data sources\n */\nfunction syncTreeSetupListener_(\n syncTree: SyncTree,\n query: QueryContext,\n view: View\n): Event[] {\n const path = query._path;\n const tag = syncTreeTagForQuery(syncTree, query);\n const listener = syncTreeCreateListenerForView_(syncTree, view);\n\n const events = syncTree.listenProvider_.startListening(\n syncTreeQueryForListening_(query),\n tag,\n listener.hashFn,\n listener.onComplete\n );\n\n const subtree = syncTree.syncPointTree_.subtree(path);\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\n // may need to shadow other listens as well.\n if (tag) {\n assert(\n !syncPointHasCompleteView(subtree.value),\n \"If we're adding a query, it shouldn't be shadowed\"\n );\n } else {\n // Shadow everything at or below this location, this is a default listener.\n const queriesToStop = subtree.fold(\n (relativePath, maybeChildSyncPoint, childMap) => {\n if (\n !pathIsEmpty(relativePath) &&\n maybeChildSyncPoint &&\n syncPointHasCompleteView(maybeChildSyncPoint)\n ) {\n return [syncPointGetCompleteView(maybeChildSyncPoint).query];\n } else {\n // No default listener here, flatten any deeper queries into an array\n let queries: QueryContext[] = [];\n if (maybeChildSyncPoint) {\n queries = queries.concat(\n syncPointGetQueryViews(maybeChildSyncPoint).map(\n view => view.query\n )\n );\n }\n each(childMap, (_key: string, childQueries: QueryContext[]) => {\n queries = queries.concat(childQueries);\n });\n return queries;\n }\n }\n );\n for (let i = 0; i < queriesToStop.length; ++i) {\n const queryToStop = queriesToStop[i];\n syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(queryToStop),\n syncTreeTagForQuery(syncTree, queryToStop)\n );\n }\n }\n return events;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { PRIORITY_INDEX } from '../snap/indexes/PriorityIndex';\nimport { LeafNode } from '../snap/LeafNode';\nimport { Node } from '../snap/Node';\nimport { nodeFromJSON } from '../snap/nodeFromJSON';\nimport { SyncTree, syncTreeCalcCompleteEventCache } from '../SyncTree';\n\nimport { Indexable } from './misc';\nimport { Path, pathChild } from './Path';\n\n/* It's critical for performance that we do not calculate actual values from a SyncTree\n * unless and until the value is needed. Because we expose both a SyncTree and Node\n * version of deferred value resolution, we ned a wrapper class that will let us share\n * code.\n *\n * @see https://github.com/firebase/firebase-js-sdk/issues/2487\n */\ninterface ValueProvider {\n getImmediateChild(childName: string): ValueProvider;\n node(): Node;\n}\n\nclass ExistingValueProvider implements ValueProvider {\n constructor(readonly node_: Node) {}\n\n getImmediateChild(childName: string): ValueProvider {\n const child = this.node_.getImmediateChild(childName);\n return new ExistingValueProvider(child);\n }\n\n node(): Node {\n return this.node_;\n }\n}\n\nclass DeferredValueProvider implements ValueProvider {\n private syncTree_: SyncTree;\n private path_: Path;\n\n constructor(syncTree: SyncTree, path: Path) {\n this.syncTree_ = syncTree;\n this.path_ = path;\n }\n\n getImmediateChild(childName: string): ValueProvider {\n const childPath = pathChild(this.path_, childName);\n return new DeferredValueProvider(this.syncTree_, childPath);\n }\n\n node(): Node {\n return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);\n }\n}\n\n/**\n * Generate placeholders for deferred values.\n */\nexport const generateWithValues = function (\n values: {\n [k: string]: unknown;\n } | null\n): { [k: string]: unknown } {\n values = values || {};\n values['timestamp'] = values['timestamp'] || new Date().getTime();\n return values;\n};\n\n/**\n * Value to use when firing local events. When writing server values, fire\n * local events with an approximate value, otherwise return value as-is.\n */\nexport const resolveDeferredLeafValue = function (\n value: { [k: string]: unknown } | string | number | boolean,\n existingVal: ValueProvider,\n serverValues: { [k: string]: unknown }\n): string | number | boolean {\n if (!value || typeof value !== 'object') {\n return value as string | number | boolean;\n }\n assert('.sv' in value, 'Unexpected leaf node or priority contents');\n\n if (typeof value['.sv'] === 'string') {\n return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);\n } else if (typeof value['.sv'] === 'object') {\n return resolveComplexDeferredValue(value['.sv'], existingVal, serverValues);\n } else {\n assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));\n }\n};\n\nconst resolveScalarDeferredValue = function (\n op: string,\n existing: ValueProvider,\n serverValues: { [k: string]: unknown }\n): string | number | boolean {\n switch (op) {\n case 'timestamp':\n return serverValues['timestamp'] as string | number | boolean;\n default:\n assert(false, 'Unexpected server value: ' + op);\n }\n};\n\nconst resolveComplexDeferredValue = function (\n op: object,\n existing: ValueProvider,\n unused: { [k: string]: unknown }\n): string | number | boolean {\n if (!op.hasOwnProperty('increment')) {\n assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));\n }\n const delta = op['increment'];\n if (typeof delta !== 'number') {\n assert(false, 'Unexpected increment value: ' + delta);\n }\n\n const existingNode = existing.node();\n assert(\n existingNode !== null && typeof existingNode !== 'undefined',\n 'Expected ChildrenNode.EMPTY_NODE for nulls'\n );\n\n // Incrementing a non-number sets the value to the incremented amount\n if (!existingNode.isLeafNode()) {\n return delta;\n }\n\n const leaf = existingNode as LeafNode;\n const existingVal = leaf.getValue();\n if (typeof existingVal !== 'number') {\n return delta;\n }\n\n // No need to do over/underflow arithmetic here because JS only handles floats under the covers\n return existingVal + delta;\n};\n\n/**\n * Recursively replace all deferred values and priorities in the tree with the\n * specified generated replacement values.\n * @param path - path to which write is relative\n * @param node - new data written at path\n * @param syncTree - current data\n */\nexport const resolveDeferredValueTree = function (\n path: Path,\n node: Node,\n syncTree: SyncTree,\n serverValues: Indexable\n): Node {\n return resolveDeferredValue(\n node,\n new DeferredValueProvider(syncTree, path),\n serverValues\n );\n};\n\n/**\n * Recursively replace all deferred values and priorities in the node with the\n * specified generated replacement values. If there are no server values in the node,\n * it'll be returned as-is.\n */\nexport const resolveDeferredValueSnapshot = function (\n node: Node,\n existing: Node,\n serverValues: Indexable\n): Node {\n return resolveDeferredValue(\n node,\n new ExistingValueProvider(existing),\n serverValues\n );\n};\n\nfunction resolveDeferredValue(\n node: Node,\n existingVal: ValueProvider,\n serverValues: Indexable\n): Node {\n const rawPri = node.getPriority().val() as\n | Indexable\n | boolean\n | null\n | number\n | string;\n const priority = resolveDeferredLeafValue(\n rawPri,\n existingVal.getImmediateChild('.priority'),\n serverValues\n );\n let newNode: Node;\n\n if (node.isLeafNode()) {\n const leafNode = node as LeafNode;\n const value = resolveDeferredLeafValue(\n leafNode.getValue(),\n existingVal,\n serverValues\n );\n if (\n value !== leafNode.getValue() ||\n priority !== leafNode.getPriority().val()\n ) {\n return new LeafNode(value, nodeFromJSON(priority));\n } else {\n return node;\n }\n } else {\n const childrenNode = node as ChildrenNode;\n newNode = childrenNode;\n if (priority !== childrenNode.getPriority().val()) {\n newNode = newNode.updatePriority(new LeafNode(priority));\n }\n childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\n const newChildNode = resolveDeferredValue(\n childNode,\n existingVal.getImmediateChild(childName),\n serverValues\n );\n if (newChildNode !== childNode) {\n newNode = newNode.updateImmediateChild(childName, newChildNode);\n }\n });\n return newNode;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains, safeGet } from '@firebase/util';\n\nimport { Path, pathGetFront, pathPopFront } from './Path';\nimport { each } from './util';\n\n/**\n * Node in a Tree.\n */\nexport interface TreeNode {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n children: Record>;\n childCount: number;\n value?: T;\n}\n\n/**\n * A light-weight tree, traversable by path. Nodes can have both values and children.\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\n * children.\n */\nexport class Tree {\n /**\n * @param name - Optional name of the node.\n * @param parent - Optional parent node.\n * @param node - Optional node to wrap.\n */\n constructor(\n readonly name: string = '',\n readonly parent: Tree | null = null,\n public node: TreeNode = { children: {}, childCount: 0 }\n ) {}\n}\n\n/**\n * Returns a sub-Tree for the given path.\n *\n * @param pathObj - Path to look up.\n * @returns Tree for path.\n */\nexport function treeSubTree(tree: Tree, pathObj: string | Path): Tree {\n // TODO: Require pathObj to be Path?\n let path = pathObj instanceof Path ? pathObj : new Path(pathObj);\n let child = tree,\n next = pathGetFront(path);\n while (next !== null) {\n const childNode = safeGet(child.node.children, next) || {\n children: {},\n childCount: 0\n };\n child = new Tree(next, child, childNode);\n path = pathPopFront(path);\n next = pathGetFront(path);\n }\n\n return child;\n}\n\n/**\n * Returns the data associated with this tree node.\n *\n * @returns The data or null if no data exists.\n */\nexport function treeGetValue(tree: Tree): T | undefined {\n return tree.node.value;\n}\n\n/**\n * Sets data to this tree node.\n *\n * @param value - Value to set.\n */\nexport function treeSetValue(tree: Tree, value: T | undefined): void {\n tree.node.value = value;\n treeUpdateParents(tree);\n}\n\n/**\n * @returns Whether the tree has any children.\n */\nexport function treeHasChildren(tree: Tree): boolean {\n return tree.node.childCount > 0;\n}\n\n/**\n * @returns Whether the tree is empty (no value or children).\n */\nexport function treeIsEmpty(tree: Tree): boolean {\n return treeGetValue(tree) === undefined && !treeHasChildren(tree);\n}\n\n/**\n * Calls action for each child of this tree node.\n *\n * @param action - Action to be called for each child.\n */\nexport function treeForEachChild(\n tree: Tree,\n action: (tree: Tree) => void\n): void {\n each(tree.node.children, (child: string, childTree: TreeNode) => {\n action(new Tree(child, tree, childTree));\n });\n}\n\n/**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param action - Action to be called for each child.\n * @param includeSelf - Whether to call action on this node as well. Defaults to\n * false.\n * @param childrenFirst - Whether to call action on children before calling it on\n * parent.\n */\nexport function treeForEachDescendant(\n tree: Tree,\n action: (tree: Tree) => void,\n includeSelf?: boolean,\n childrenFirst?: boolean\n): void {\n if (includeSelf && !childrenFirst) {\n action(tree);\n }\n\n treeForEachChild(tree, child => {\n treeForEachDescendant(child, action, true, childrenFirst);\n });\n\n if (includeSelf && childrenFirst) {\n action(tree);\n }\n}\n\n/**\n * Calls action on each ancestor node.\n *\n * @param action - Action to be called on each parent; return\n * true to abort.\n * @param includeSelf - Whether to call action on this node as well.\n * @returns true if the action callback returned true.\n */\nexport function treeForEachAncestor(\n tree: Tree,\n action: (tree: Tree) => unknown,\n includeSelf?: boolean\n): boolean {\n let node = includeSelf ? tree : tree.parent;\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n node = node.parent;\n }\n return false;\n}\n\n/**\n * Does a depth-first traversal of this node's descendants. When a descendant with a value\n * is found, action is called on it and traversal does not continue inside the node.\n * Action is *not* called on this node.\n *\n * @param action - Action to be called for each child.\n */\nexport function treeForEachImmediateDescendantWithValue(\n tree: Tree,\n action: (tree: Tree) => void\n): void {\n treeForEachChild(tree, child => {\n if (treeGetValue(child) !== undefined) {\n action(child);\n } else {\n treeForEachImmediateDescendantWithValue(child, action);\n }\n });\n}\n\n/**\n * @returns The path of this tree node, as a Path.\n */\nexport function treeGetPath(tree: Tree) {\n return new Path(\n tree.parent === null\n ? tree.name\n : treeGetPath(tree.parent) + '/' + tree.name\n );\n}\n\n/**\n * Adds or removes this child from its parent based on whether it's empty or not.\n */\nfunction treeUpdateParents(tree: Tree) {\n if (tree.parent !== null) {\n treeUpdateChild(tree.parent, tree.name, tree);\n }\n}\n\n/**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param childName - The name of the child to update.\n * @param child - The child to update.\n */\nfunction treeUpdateChild(tree: Tree, childName: string, child: Tree) {\n const childEmpty = treeIsEmpty(child);\n const childExists = contains(tree.node.children, childName);\n if (childEmpty && childExists) {\n delete tree.node.children[childName];\n tree.node.childCount--;\n treeUpdateParents(tree);\n } else if (!childEmpty && !childExists) {\n tree.node.children[childName] = child.node;\n tree.node.childCount++;\n treeUpdateParents(tree);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n contains,\n errorPrefix as errorPrefixFxn,\n safeGet,\n stringLength\n} from '@firebase/util';\n\nimport { RepoInfo } from '../RepoInfo';\n\nimport {\n Path,\n pathChild,\n pathCompare,\n pathContains,\n pathGetBack,\n pathGetFront,\n pathSlice,\n ValidationPath,\n validationPathPop,\n validationPathPush,\n validationPathToErrorString\n} from './Path';\nimport { each, isInvalidJSONNumber } from './util';\n\n/**\n * True for invalid Firebase keys\n */\nexport const INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\n\n/**\n * True for invalid Firebase paths.\n * Allows '/' in paths.\n */\nexport const INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\n\n/**\n * Maximum number of characters to allow in leaf value\n */\nexport const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\n\nexport const isValidKey = function (key: unknown): boolean {\n return (\n typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key)\n );\n};\n\nexport const isValidPathString = function (pathString: string): boolean {\n return (\n typeof pathString === 'string' &&\n pathString.length !== 0 &&\n !INVALID_PATH_REGEX_.test(pathString)\n );\n};\n\nexport const isValidRootPathString = function (pathString: string): boolean {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n\n return isValidPathString(pathString);\n};\n\nexport const isValidPriority = function (priority: unknown): boolean {\n return (\n priority === null ||\n typeof priority === 'string' ||\n (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||\n (priority &&\n typeof priority === 'object' &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n contains(priority as any, '.sv'))\n );\n};\n\n/**\n * Pre-validate a datum passed as an argument to Firebase function.\n */\nexport const validateFirebaseDataArg = function (\n fnName: string,\n value: unknown,\n path: Path,\n optional: boolean\n) {\n if (optional && value === undefined) {\n return;\n }\n\n validateFirebaseData(errorPrefixFxn(fnName, 'value'), value, path);\n};\n\n/**\n * Validate a data object client-side before sending to server.\n */\nexport const validateFirebaseData = function (\n errorPrefix: string,\n data: unknown,\n path_: Path | ValidationPath\n) {\n const path =\n path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;\n\n if (data === undefined) {\n throw new Error(\n errorPrefix + 'contains undefined ' + validationPathToErrorString(path)\n );\n }\n if (typeof data === 'function') {\n throw new Error(\n errorPrefix +\n 'contains a function ' +\n validationPathToErrorString(path) +\n ' with contents = ' +\n data.toString()\n );\n }\n if (isInvalidJSONNumber(data)) {\n throw new Error(\n errorPrefix +\n 'contains ' +\n data.toString() +\n ' ' +\n validationPathToErrorString(path)\n );\n }\n\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\n if (\n typeof data === 'string' &&\n data.length > MAX_LEAF_SIZE_ / 3 &&\n stringLength(data) > MAX_LEAF_SIZE_\n ) {\n throw new Error(\n errorPrefix +\n 'contains a string greater than ' +\n MAX_LEAF_SIZE_ +\n ' utf8 bytes ' +\n validationPathToErrorString(path) +\n \" ('\" +\n data.substring(0, 50) +\n \"...')\"\n );\n }\n\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\n // to save extra walking of large objects.\n if (data && typeof data === 'object') {\n let hasDotValue = false;\n let hasActualChild = false;\n each(data, (key: string, value: unknown) => {\n if (key === '.value') {\n hasDotValue = true;\n } else if (key !== '.priority' && key !== '.sv') {\n hasActualChild = true;\n if (!isValidKey(key)) {\n throw new Error(\n errorPrefix +\n ' contains an invalid key (' +\n key +\n ') ' +\n validationPathToErrorString(path) +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"'\n );\n }\n }\n\n validationPathPush(path, key);\n validateFirebaseData(errorPrefix, value, path);\n validationPathPop(path);\n });\n\n if (hasDotValue && hasActualChild) {\n throw new Error(\n errorPrefix +\n ' contains \".value\" child ' +\n validationPathToErrorString(path) +\n ' in addition to actual children.'\n );\n }\n }\n};\n\n/**\n * Pre-validate paths passed in the firebase function.\n */\nexport const validateFirebaseMergePaths = function (\n errorPrefix: string,\n mergePaths: Path[]\n) {\n let i, curPath: Path;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n const keys = pathSlice(curPath);\n for (let j = 0; j < keys.length; j++) {\n if (keys[j] === '.priority' && j === keys.length - 1) {\n // .priority is OK\n } else if (!isValidKey(keys[j])) {\n throw new Error(\n errorPrefix +\n 'contains an invalid key (' +\n keys[j] +\n ') in path ' +\n curPath.toString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"'\n );\n }\n }\n }\n\n // Check that update keys are not descendants of each other.\n // We rely on the property that sorting guarantees that ancestors come\n // right before descendants.\n mergePaths.sort(pathCompare);\n let prevPath: Path | null = null;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n if (prevPath !== null && pathContains(prevPath, curPath)) {\n throw new Error(\n errorPrefix +\n 'contains a path ' +\n prevPath.toString() +\n ' that is ancestor of another path ' +\n curPath.toString()\n );\n }\n prevPath = curPath;\n }\n};\n\n/**\n * pre-validate an object passed as an argument to firebase function (\n * must be an object - e.g. for firebase.update()).\n */\nexport const validateFirebaseMergeDataArg = function (\n fnName: string,\n data: unknown,\n path: Path,\n optional: boolean\n) {\n if (optional && data === undefined) {\n return;\n }\n\n const errorPrefix = errorPrefixFxn(fnName, 'values');\n\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\n throw new Error(\n errorPrefix + ' must be an object containing the children to replace.'\n );\n }\n\n const mergePaths: Path[] = [];\n each(data, (key: string, value: unknown) => {\n const curPath = new Path(key);\n validateFirebaseData(errorPrefix, value, pathChild(path, curPath));\n if (pathGetBack(curPath) === '.priority') {\n if (!isValidPriority(value)) {\n throw new Error(\n errorPrefix +\n \"contains an invalid value for '\" +\n curPath.toString() +\n \"', which must be a valid \" +\n 'Firebase priority (a string, finite number, server value, or null).'\n );\n }\n }\n mergePaths.push(curPath);\n });\n validateFirebaseMergePaths(errorPrefix, mergePaths);\n};\n\nexport const validatePriority = function (\n fnName: string,\n priority: unknown,\n optional: boolean\n) {\n if (optional && priority === undefined) {\n return;\n }\n if (isInvalidJSONNumber(priority)) {\n throw new Error(\n errorPrefixFxn(fnName, 'priority') +\n 'is ' +\n priority.toString() +\n ', but must be a valid Firebase priority (a string, finite number, ' +\n 'server value, or null).'\n );\n }\n // Special case to allow importing data with a .sv.\n if (!isValidPriority(priority)) {\n throw new Error(\n errorPrefixFxn(fnName, 'priority') +\n 'must be a valid Firebase priority ' +\n '(a string, finite number, server value, or null).'\n );\n }\n};\n\nexport const validateKey = function (\n fnName: string,\n argumentName: string,\n key: string,\n optional: boolean\n) {\n if (optional && key === undefined) {\n return;\n }\n if (!isValidKey(key)) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'was an invalid key = \"' +\n key +\n '\". Firebase keys must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").'\n );\n }\n};\n\n/**\n * @internal\n */\nexport const validatePathString = function (\n fnName: string,\n argumentName: string,\n pathString: string,\n optional: boolean\n) {\n if (optional && pathString === undefined) {\n return;\n }\n\n if (!isValidPathString(pathString)) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'was an invalid path = \"' +\n pathString +\n '\". Paths must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"'\n );\n }\n};\n\nexport const validateRootPathString = function (\n fnName: string,\n argumentName: string,\n pathString: string,\n optional: boolean\n) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n\n validatePathString(fnName, argumentName, pathString, optional);\n};\n\n/**\n * @internal\n */\nexport const validateWritablePath = function (fnName: string, path: Path) {\n if (pathGetFront(path) === '.info') {\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\n }\n};\n\nexport const validateUrl = function (\n fnName: string,\n parsedUrl: { repoInfo: RepoInfo; path: Path }\n) {\n // TODO = Validate server better.\n const pathString = parsedUrl.path.toString();\n if (\n !(typeof parsedUrl.repoInfo.host === 'string') ||\n parsedUrl.repoInfo.host.length === 0 ||\n (!isValidKey(parsedUrl.repoInfo.namespace) &&\n parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||\n (pathString.length !== 0 && !isValidRootPathString(pathString))\n ) {\n throw new Error(\n errorPrefixFxn(fnName, 'url') +\n 'must be a valid firebase URL and ' +\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".'\n );\n }\n};\n\nexport const validateString = function (\n fnName: string,\n argumentName: string,\n string: unknown,\n optional: boolean\n) {\n if (optional && string === undefined) {\n return;\n }\n if (!(typeof string === 'string')) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) + 'must be a valid string.'\n );\n }\n};\n\nexport const validateObject = function (\n fnName: string,\n argumentName: string,\n obj: unknown,\n optional: boolean\n) {\n if (optional && obj === undefined) {\n return;\n }\n if (!(obj && typeof obj === 'object') || obj === null) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) + 'must be a valid object.'\n );\n }\n};\n\nexport const validateObjectContainsKey = function (\n fnName: string,\n argumentName: string,\n obj: unknown,\n key: string,\n optional: boolean,\n optType?: string\n) {\n const objectContainsKey =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj && typeof obj === 'object' && contains(obj as any, key);\n\n if (!objectContainsKey) {\n if (optional) {\n return;\n } else {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'must contain the key \"' +\n key +\n '\"'\n );\n }\n }\n\n if (optType) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const val = safeGet(obj as any, key);\n if (\n (optType === 'number' && !(typeof val === 'number')) ||\n (optType === 'string' && !(typeof val === 'string')) ||\n (optType === 'boolean' && !(typeof val === 'boolean')) ||\n (optType === 'function' && !(typeof val === 'function')) ||\n (optType === 'object' && !(typeof val === 'object') && val)\n ) {\n if (optional) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'contains invalid value for key \"' +\n key +\n '\" (must be of type \"' +\n optType +\n '\")'\n );\n } else {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'must contain the key \"' +\n key +\n '\" with type \"' +\n optType +\n '\"'\n );\n }\n }\n }\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Path, pathContains, pathEquals } from '../util/Path';\nimport { exceptionGuard, log, logger } from '../util/util';\n\nimport { Event } from './Event';\n\n/**\n * The event queue serves a few purposes:\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\n * events being queued.\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\n * left off, ensuring that the events are still raised synchronously and in order.\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\n * events are raised synchronously.\n *\n * NOTE: This can all go away if/when we move to async events.\n *\n */\nexport class EventQueue {\n eventLists_: EventList[] = [];\n\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n */\n recursionDepth_ = 0;\n}\n\n/**\n * @param eventDataList - The new events to queue.\n */\nexport function eventQueueQueueEvents(\n eventQueue: EventQueue,\n eventDataList: Event[]\n) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n let currList: EventList | null = null;\n for (let i = 0; i < eventDataList.length; i++) {\n const data = eventDataList[i];\n const path = data.getPath();\n if (currList !== null && !pathEquals(path, currList.path)) {\n eventQueue.eventLists_.push(currList);\n currList = null;\n }\n\n if (currList === null) {\n currList = { events: [], path };\n }\n\n currList.events.push(data);\n }\n if (currList) {\n eventQueue.eventLists_.push(currList);\n }\n}\n\n/**\n * Queues the specified events and synchronously raises all events (including previously queued ones)\n * for the specified path.\n *\n * It is assumed that the new events are all for the specified path.\n *\n * @param path - The path to raise events for.\n * @param eventDataList - The new events to raise.\n */\nexport function eventQueueRaiseEventsAtPath(\n eventQueue: EventQueue,\n path: Path,\n eventDataList: Event[]\n) {\n eventQueueQueueEvents(eventQueue, eventDataList);\n eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath =>\n pathEquals(eventPath, path)\n );\n}\n\n/**\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\n * locations related to the specified change path (i.e. all ancestors and descendants).\n *\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\n *\n * @param changedPath - The path to raise events for.\n * @param eventDataList - The events to raise\n */\nexport function eventQueueRaiseEventsForChangedPath(\n eventQueue: EventQueue,\n changedPath: Path,\n eventDataList: Event[]\n) {\n eventQueueQueueEvents(eventQueue, eventDataList);\n eventQueueRaiseQueuedEventsMatchingPredicate(\n eventQueue,\n eventPath =>\n pathContains(eventPath, changedPath) ||\n pathContains(changedPath, eventPath)\n );\n}\n\nfunction eventQueueRaiseQueuedEventsMatchingPredicate(\n eventQueue: EventQueue,\n predicate: (path: Path) => boolean\n) {\n eventQueue.recursionDepth_++;\n\n let sentAll = true;\n for (let i = 0; i < eventQueue.eventLists_.length; i++) {\n const eventList = eventQueue.eventLists_[i];\n if (eventList) {\n const eventPath = eventList.path;\n if (predicate(eventPath)) {\n eventListRaise(eventQueue.eventLists_[i]);\n eventQueue.eventLists_[i] = null;\n } else {\n sentAll = false;\n }\n }\n }\n\n if (sentAll) {\n eventQueue.eventLists_ = [];\n }\n\n eventQueue.recursionDepth_--;\n}\n\ninterface EventList {\n events: Event[];\n path: Path;\n}\n\n/**\n * Iterates through the list and raises each event\n */\nfunction eventListRaise(eventList: EventList) {\n for (let i = 0; i < eventList.events.length; i++) {\n const eventData = eventList.events[i];\n if (eventData !== null) {\n eventList.events[i] = null;\n const eventFn = eventData.getEventRunner();\n if (logger) {\n log('event: ' + eventData.toString());\n }\n exceptionGuard(eventFn);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n contains,\n isEmpty,\n map,\n safeGet,\n stringify\n} from '@firebase/util';\n\nimport { ValueEventRegistration } from '../api/Reference_impl';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { PersistentConnection } from './PersistentConnection';\nimport { ReadonlyRestClient } from './ReadonlyRestClient';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { nodeFromJSON } from './snap/nodeFromJSON';\nimport { SnapshotHolder } from './SnapshotHolder';\nimport {\n newSparseSnapshotTree,\n SparseSnapshotTree,\n sparseSnapshotTreeForEachTree,\n sparseSnapshotTreeForget,\n sparseSnapshotTreeRemember\n} from './SparseSnapshotTree';\nimport { StatsCollection } from './stats/StatsCollection';\nimport { StatsListener } from './stats/StatsListener';\nimport {\n statsManagerGetCollection,\n statsManagerGetOrCreateReporter\n} from './stats/StatsManager';\nimport { StatsReporter, statsReporterIncludeStat } from './stats/StatsReporter';\nimport {\n SyncTree,\n syncTreeAckUserWrite,\n syncTreeAddEventRegistration,\n syncTreeApplyServerMerge,\n syncTreeApplyServerOverwrite,\n syncTreeApplyTaggedQueryMerge,\n syncTreeApplyTaggedQueryOverwrite,\n syncTreeApplyUserMerge,\n syncTreeApplyUserOverwrite,\n syncTreeCalcCompleteEventCache,\n syncTreeGetServerValue,\n syncTreeRemoveEventRegistration,\n syncTreeTagForQuery\n} from './SyncTree';\nimport { Indexable } from './util/misc';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathGetFront,\n pathPopFront\n} from './util/Path';\nimport {\n generateWithValues,\n resolveDeferredValueSnapshot,\n resolveDeferredValueTree\n} from './util/ServerValues';\nimport {\n Tree,\n treeForEachAncestor,\n treeForEachChild,\n treeForEachDescendant,\n treeGetPath,\n treeGetValue,\n treeHasChildren,\n treeSetValue,\n treeSubTree\n} from './util/Tree';\nimport {\n beingCrawled,\n each,\n exceptionGuard,\n log,\n LUIDGenerator,\n warn\n} from './util/util';\nimport { isValidPriority, validateFirebaseData } from './util/validation';\nimport { Event } from './view/Event';\nimport {\n EventQueue,\n eventQueueQueueEvents,\n eventQueueRaiseEventsAtPath,\n eventQueueRaiseEventsForChangedPath\n} from './view/EventQueue';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\n\nconst INTERRUPT_REASON = 'repo_interrupt';\n\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other\n * things this ensure that if there's ever a bug causing a mismatch between\n * client / server hashes for some data, we won't retry indefinitely.\n */\nconst MAX_TRANSACTION_RETRIES = 25;\n\nconst enum TransactionStatus {\n // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the\n // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to\n // mismatched hash.\n RUN,\n\n // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted\n // or rejected yet).\n SENT,\n\n // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be\n // removed when we get a chance to prune completed ones.\n COMPLETED,\n\n // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made).\n // If it comes back as unsuccessful, we'll abort it.\n SENT_NEEDS_ABORT,\n\n // Temporary state used to mark transactions that need to be aborted.\n NEEDS_ABORT\n}\n\ninterface Transaction {\n path: Path;\n update: (a: unknown) => unknown;\n onComplete: (\n error: Error | null,\n committed: boolean,\n node: Node | null\n ) => void;\n status: TransactionStatus;\n order: number;\n applyLocally: boolean;\n retryCount: number;\n unwatcher: () => void;\n abortReason: string | null;\n currentWriteId: number;\n currentInputSnapshot: Node | null;\n currentOutputSnapshotRaw: Node | null;\n currentOutputSnapshotResolved: Node | null;\n}\n\n/**\n * A connection to a single data repository.\n */\nexport class Repo {\n /** Key for uniquely identifying this repo, used in RepoManager */\n readonly key: string;\n\n dataUpdateCount = 0;\n infoSyncTree_: SyncTree;\n serverSyncTree_: SyncTree;\n\n stats_: StatsCollection;\n statsListener_: StatsListener | null = null;\n eventQueue_ = new EventQueue();\n nextWriteId_ = 1;\n server_: ServerActions;\n statsReporter_: StatsReporter;\n infoData_: SnapshotHolder;\n interceptServerDataCallback_: ((a: string, b: unknown) => void) | null = null;\n\n /** A list of data pieces and paths to be set when this client disconnects. */\n onDisconnect_: SparseSnapshotTree = newSparseSnapshotTree();\n\n /** Stores queues of outstanding transactions for Firebase locations. */\n transactionQueueTree_ = new Tree();\n\n // TODO: This should be @private but it's used by test_access.js and internal.js\n persistentConnection_: PersistentConnection | null = null;\n\n constructor(\n public repoInfo_: RepoInfo,\n public forceRestClient_: boolean,\n public authTokenProvider_: AuthTokenProvider,\n public appCheckProvider_: AppCheckTokenProvider\n ) {\n // This key is intentionally not updated if RepoInfo is later changed or replaced\n this.key = this.repoInfo_.toURLString();\n }\n\n /**\n * @returns The URL corresponding to the root of this Firebase.\n */\n toString(): string {\n return (\n (this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host\n );\n }\n}\n\nexport function repoStart(\n repo: Repo,\n appId: string,\n authOverride?: object\n): void {\n repo.stats_ = statsManagerGetCollection(repo.repoInfo_);\n\n if (repo.forceRestClient_ || beingCrawled()) {\n repo.server_ = new ReadonlyRestClient(\n repo.repoInfo_,\n (\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n ) => {\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\n },\n repo.authTokenProvider_,\n repo.appCheckProvider_\n );\n\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\n setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);\n } else {\n // Validate authOverride\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\n if (typeof authOverride !== 'object') {\n throw new Error(\n 'Only objects are supported for option databaseAuthVariableOverride'\n );\n }\n try {\n stringify(authOverride);\n } catch (e) {\n throw new Error('Invalid authOverride provided: ' + e);\n }\n }\n\n repo.persistentConnection_ = new PersistentConnection(\n repo.repoInfo_,\n appId,\n (\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n ) => {\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\n },\n (connectStatus: boolean) => {\n repoOnConnectStatus(repo, connectStatus);\n },\n (updates: object) => {\n repoOnServerInfoUpdate(repo, updates);\n },\n repo.authTokenProvider_,\n repo.appCheckProvider_,\n authOverride\n );\n\n repo.server_ = repo.persistentConnection_;\n }\n\n repo.authTokenProvider_.addTokenChangeListener(token => {\n repo.server_.refreshAuthToken(token);\n });\n\n repo.appCheckProvider_.addTokenChangeListener(result => {\n repo.server_.refreshAppCheckToken(result.token);\n });\n\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\n repo.statsReporter_ = statsManagerGetOrCreateReporter(\n repo.repoInfo_,\n () => new StatsReporter(repo.stats_, repo.server_)\n );\n\n // Used for .info.\n repo.infoData_ = new SnapshotHolder();\n repo.infoSyncTree_ = new SyncTree({\n startListening: (query, tag, currentHashFn, onComplete) => {\n let infoEvents: Event[] = [];\n const node = repo.infoData_.getNode(query._path);\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\n // on initial data...\n if (!node.isEmpty()) {\n infoEvents = syncTreeApplyServerOverwrite(\n repo.infoSyncTree_,\n query._path,\n node\n );\n setTimeout(() => {\n onComplete('ok');\n }, 0);\n }\n return infoEvents;\n },\n stopListening: () => {}\n });\n repoUpdateInfo(repo, 'connected', false);\n\n repo.serverSyncTree_ = new SyncTree({\n startListening: (query, tag, currentHashFn, onComplete) => {\n repo.server_.listen(query, currentHashFn, tag, (status, data) => {\n const events = onComplete(status, data);\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n query._path,\n events\n );\n });\n // No synchronous events for network-backed sync trees\n return [];\n },\n stopListening: (query, tag) => {\n repo.server_.unlisten(query, tag);\n }\n });\n}\n\n/**\n * @returns The time in milliseconds, taking the server offset into account if we have one.\n */\nexport function repoServerTime(repo: Repo): number {\n const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));\n const offset = (offsetNode.val() as number) || 0;\n return new Date().getTime() + offset;\n}\n\n/**\n * Generate ServerValues using some variables from the repo object.\n */\nexport function repoGenerateServerValues(repo: Repo): Indexable {\n return generateWithValues({\n timestamp: repoServerTime(repo)\n });\n}\n\n/**\n * Called by realtime when we get new messages from the server.\n */\nfunction repoOnDataUpdate(\n repo: Repo,\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n): void {\n // For testing.\n repo.dataUpdateCount++;\n const path = new Path(pathString);\n data = repo.interceptServerDataCallback_\n ? repo.interceptServerDataCallback_(pathString, data)\n : data;\n let events = [];\n if (tag) {\n if (isMerge) {\n const taggedChildren = map(\n data as { [k: string]: unknown },\n (raw: unknown) => nodeFromJSON(raw)\n );\n events = syncTreeApplyTaggedQueryMerge(\n repo.serverSyncTree_,\n path,\n taggedChildren,\n tag\n );\n } else {\n const taggedSnap = nodeFromJSON(data);\n events = syncTreeApplyTaggedQueryOverwrite(\n repo.serverSyncTree_,\n path,\n taggedSnap,\n tag\n );\n }\n } else if (isMerge) {\n const changedChildren = map(\n data as { [k: string]: unknown },\n (raw: unknown) => nodeFromJSON(raw)\n );\n events = syncTreeApplyServerMerge(\n repo.serverSyncTree_,\n path,\n changedChildren\n );\n } else {\n const snap = nodeFromJSON(data);\n events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);\n }\n let affectedPath = path;\n if (events.length > 0) {\n // Since we have a listener outstanding for each transaction, receiving any events\n // is a proxy for some change having occurred.\n affectedPath = repoRerunTransactions(repo, path);\n }\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);\n}\n\n// TODO: This should be @private but it's used by test_access.js and internal.js\nexport function repoInterceptServerData(\n repo: Repo,\n callback: ((a: string, b: unknown) => unknown) | null\n): void {\n repo.interceptServerDataCallback_ = callback;\n}\n\nfunction repoOnConnectStatus(repo: Repo, connectStatus: boolean): void {\n repoUpdateInfo(repo, 'connected', connectStatus);\n if (connectStatus === false) {\n repoRunOnDisconnectEvents(repo);\n }\n}\n\nfunction repoOnServerInfoUpdate(repo: Repo, updates: object): void {\n each(updates, (key: string, value: unknown) => {\n repoUpdateInfo(repo, key, value);\n });\n}\n\nfunction repoUpdateInfo(repo: Repo, pathString: string, value: unknown): void {\n const path = new Path('/.info/' + pathString);\n const newNode = nodeFromJSON(value);\n repo.infoData_.updateSnapshot(path, newNode);\n const events = syncTreeApplyServerOverwrite(\n repo.infoSyncTree_,\n path,\n newNode\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n}\n\nfunction repoGetNextWriteId(repo: Repo): number {\n return repo.nextWriteId_++;\n}\n\n/**\n * The purpose of `getValue` is to return the latest known value\n * satisfying `query`.\n *\n * This method will first check for in-memory cached values\n * belonging to active listeners. If they are found, such values\n * are considered to be the most up-to-date.\n *\n * If the client is not connected, this method will wait until the\n * repo has established a connection and then request the value for `query`.\n * If the client is not able to retrieve the query result for another reason,\n * it reports an error.\n *\n * @param query - The query to surface a value for.\n */\nexport function repoGetValue(\n repo: Repo,\n query: QueryContext,\n eventRegistration: ValueEventRegistration\n): Promise {\n // Only active queries are cached. There is no persisted cache.\n const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);\n if (cached != null) {\n return Promise.resolve(cached);\n }\n return repo.server_.get(query).then(\n payload => {\n const node = nodeFromJSON(payload).withIndex(\n query._queryParams.getIndex()\n );\n /**\n * Below we simulate the actions of an `onlyOnce` `onValue()` event where:\n * Add an event registration,\n * Update data at the path,\n * Raise any events,\n * Cleanup the SyncTree\n */\n syncTreeAddEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration,\n true\n );\n let events: Event[];\n if (query._queryParams.loadsAllData()) {\n events = syncTreeApplyServerOverwrite(\n repo.serverSyncTree_,\n query._path,\n node\n );\n } else {\n const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);\n events = syncTreeApplyTaggedQueryOverwrite(\n repo.serverSyncTree_,\n query._path,\n node,\n tag\n );\n }\n /*\n * We need to raise events in the scenario where `get()` is called at a parent path, and\n * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting\n * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree\n * and its corresponding serverCache, including the child location where `onValue` is called. Then,\n * `onValue` will receive the event from the server, but look at the syncTree and see that the data received\n * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.\n * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and\n * ensure the corresponding child events will get fired.\n */\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n query._path,\n events\n );\n syncTreeRemoveEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration,\n null,\n true\n );\n return node;\n },\n err => {\n repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);\n return Promise.reject(new Error(err as string));\n }\n );\n}\n\nexport function repoSetWithPriority(\n repo: Repo,\n path: Path,\n newVal: unknown,\n newPriority: number | string | null,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repoLog(repo, 'set', {\n path: path.toString(),\n value: newVal,\n priority: newPriority\n });\n\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\n // (b) store unresolved paths on JSON parse\n const serverValues = repoGenerateServerValues(repo);\n const newNodeUnresolved = nodeFromJSON(newVal, newPriority);\n const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);\n const newNode = resolveDeferredValueSnapshot(\n newNodeUnresolved,\n existing,\n serverValues\n );\n\n const writeId = repoGetNextWriteId(repo);\n const events = syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n path,\n newNode,\n writeId,\n true\n );\n eventQueueQueueEvents(repo.eventQueue_, events);\n repo.server_.put(\n path.toString(),\n newNodeUnresolved.val(/*export=*/ true),\n (status, errorReason) => {\n const success = status === 'ok';\n if (!success) {\n warn('set at ' + path + ' failed: ' + status);\n }\n\n const clearEvents = syncTreeAckUserWrite(\n repo.serverSyncTree_,\n writeId,\n !success\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n const affectedPath = repoAbortTransactions(repo, path);\n repoRerunTransactions(repo, affectedPath);\n // We queued the events above, so just flush the queue here\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);\n}\n\nexport function repoUpdate(\n repo: Repo,\n path: Path,\n childrenToMerge: { [k: string]: unknown },\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });\n\n // Start with our existing data and merge each child into it.\n let empty = true;\n const serverValues = repoGenerateServerValues(repo);\n const changedChildren: { [k: string]: Node } = {};\n each(childrenToMerge, (changedKey: string, changedValue: unknown) => {\n empty = false;\n changedChildren[changedKey] = resolveDeferredValueTree(\n pathChild(path, changedKey),\n nodeFromJSON(changedValue),\n repo.serverSyncTree_,\n serverValues\n );\n });\n\n if (!empty) {\n const writeId = repoGetNextWriteId(repo);\n const events = syncTreeApplyUserMerge(\n repo.serverSyncTree_,\n path,\n changedChildren,\n writeId\n );\n eventQueueQueueEvents(repo.eventQueue_, events);\n repo.server_.merge(\n path.toString(),\n childrenToMerge,\n (status, errorReason) => {\n const success = status === 'ok';\n if (!success) {\n warn('update at ' + path + ' failed: ' + status);\n }\n\n const clearEvents = syncTreeAckUserWrite(\n repo.serverSyncTree_,\n writeId,\n !success\n );\n const affectedPath =\n clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n affectedPath,\n clearEvents\n );\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n\n each(childrenToMerge, (changedPath: string) => {\n const affectedPath = repoAbortTransactions(\n repo,\n pathChild(path, changedPath)\n );\n repoRerunTransactions(repo, affectedPath);\n });\n\n // We queued the events above, so just flush the queue here\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);\n } else {\n log(\"update() called with empty data. Don't do anything.\");\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\n }\n}\n\n/**\n * Applies all of the changes stored up in the onDisconnect_ tree.\n */\nfunction repoRunOnDisconnectEvents(repo: Repo): void {\n repoLog(repo, 'onDisconnectEvents');\n\n const serverValues = repoGenerateServerValues(repo);\n const resolvedOnDisconnectTree = newSparseSnapshotTree();\n sparseSnapshotTreeForEachTree(\n repo.onDisconnect_,\n newEmptyPath(),\n (path, node) => {\n const resolved = resolveDeferredValueTree(\n path,\n node,\n repo.serverSyncTree_,\n serverValues\n );\n sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);\n }\n );\n let events: Event[] = [];\n\n sparseSnapshotTreeForEachTree(\n resolvedOnDisconnectTree,\n newEmptyPath(),\n (path, snap) => {\n events = events.concat(\n syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap)\n );\n const affectedPath = repoAbortTransactions(repo, path);\n repoRerunTransactions(repo, affectedPath);\n }\n );\n\n repo.onDisconnect_ = newSparseSnapshotTree();\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);\n}\n\nexport function repoOnDisconnectCancel(\n repo: Repo,\n path: Path,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeForget(repo.onDisconnect_, path);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n });\n}\n\nexport function repoOnDisconnectSet(\n repo: Repo,\n path: Path,\n value: unknown,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n const newNode = nodeFromJSON(value);\n repo.server_.onDisconnectPut(\n path.toString(),\n newNode.val(/*export=*/ true),\n (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoOnDisconnectSetWithPriority(\n repo: Repo,\n path: Path,\n value: unknown,\n priority: unknown,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n const newNode = nodeFromJSON(value, priority);\n repo.server_.onDisconnectPut(\n path.toString(),\n newNode.val(/*export=*/ true),\n (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoOnDisconnectUpdate(\n repo: Repo,\n path: Path,\n childrenToMerge: { [k: string]: unknown },\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n if (isEmpty(childrenToMerge)) {\n log(\"onDisconnect().update() called with empty data. Don't do anything.\");\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\n return;\n }\n\n repo.server_.onDisconnectMerge(\n path.toString(),\n childrenToMerge,\n (status, errorReason) => {\n if (status === 'ok') {\n each(childrenToMerge, (childName: string, childNode: unknown) => {\n const newChildNode = nodeFromJSON(childNode);\n sparseSnapshotTreeRemember(\n repo.onDisconnect_,\n pathChild(path, childName),\n newChildNode\n );\n });\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoAddEventCallbackForQuery(\n repo: Repo,\n query: QueryContext,\n eventRegistration: EventRegistration\n): void {\n let events;\n if (pathGetFront(query._path) === '.info') {\n events = syncTreeAddEventRegistration(\n repo.infoSyncTree_,\n query,\n eventRegistration\n );\n } else {\n events = syncTreeAddEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration\n );\n }\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\n}\n\nexport function repoRemoveEventCallbackForQuery(\n repo: Repo,\n query: QueryContext,\n eventRegistration: EventRegistration\n): void {\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\n // a little bit by handling the return values anyways.\n let events;\n if (pathGetFront(query._path) === '.info') {\n events = syncTreeRemoveEventRegistration(\n repo.infoSyncTree_,\n query,\n eventRegistration\n );\n } else {\n events = syncTreeRemoveEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration\n );\n }\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\n}\n\nexport function repoInterrupt(repo: Repo): void {\n if (repo.persistentConnection_) {\n repo.persistentConnection_.interrupt(INTERRUPT_REASON);\n }\n}\n\nexport function repoResume(repo: Repo): void {\n if (repo.persistentConnection_) {\n repo.persistentConnection_.resume(INTERRUPT_REASON);\n }\n}\n\nexport function repoStats(repo: Repo, showDelta: boolean = false): void {\n if (typeof console === 'undefined') {\n return;\n }\n\n let stats: { [k: string]: unknown };\n if (showDelta) {\n if (!repo.statsListener_) {\n repo.statsListener_ = new StatsListener(repo.stats_);\n }\n stats = repo.statsListener_.get();\n } else {\n stats = repo.stats_.get();\n }\n\n const longestName = Object.keys(stats).reduce(\n (previousValue, currentValue) =>\n Math.max(currentValue.length, previousValue),\n 0\n );\n\n each(stats, (stat: string, value: unknown) => {\n let paddedStat = stat;\n // pad stat names to be the same length (plus 2 extra spaces).\n for (let i = stat.length; i < longestName + 2; i++) {\n paddedStat += ' ';\n }\n console.log(paddedStat + value);\n });\n}\n\nexport function repoStatsIncrementCounter(repo: Repo, metric: string): void {\n repo.stats_.incrementCounter(metric);\n statsReporterIncludeStat(repo.statsReporter_, metric);\n}\n\nfunction repoLog(repo: Repo, ...varArgs: unknown[]): void {\n let prefix = '';\n if (repo.persistentConnection_) {\n prefix = repo.persistentConnection_.id + ':';\n }\n log(prefix, ...varArgs);\n}\n\nexport function repoCallOnCompleteCallback(\n repo: Repo,\n callback: ((status: Error | null, errorReason?: string) => void) | null,\n status: string,\n errorReason?: string | null\n): void {\n if (callback) {\n exceptionGuard(() => {\n if (status === 'ok') {\n callback(null);\n } else {\n const code = (status || 'error').toUpperCase();\n let message = code;\n if (errorReason) {\n message += ': ' + errorReason;\n }\n\n const error = new Error(message);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (error as any).code = code;\n callback(error);\n }\n });\n }\n}\n\n/**\n * Creates a new transaction, adds it to the transactions we're tracking, and\n * sends it to the server if possible.\n *\n * @param path - Path at which to do transaction.\n * @param transactionUpdate - Update callback.\n * @param onComplete - Completion callback.\n * @param unwatcher - Function that will be called when the transaction no longer\n * need data updates for `path`.\n * @param applyLocally - Whether or not to make intermediate results visible\n */\nexport function repoStartTransaction(\n repo: Repo,\n path: Path,\n transactionUpdate: (a: unknown) => unknown,\n onComplete: ((error: Error, committed: boolean, node: Node) => void) | null,\n unwatcher: () => void,\n applyLocally: boolean\n): void {\n repoLog(repo, 'transaction on ' + path);\n\n // Initialize transaction.\n const transaction: Transaction = {\n path,\n update: transactionUpdate,\n onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out\n // which one goes first.\n order: LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n };\n\n // Run transaction initially.\n const currentState = repoGetLatestState(repo, path, undefined);\n transaction.currentInputSnapshot = currentState;\n const newVal = transaction.update(currentState.val());\n if (newVal === undefined) {\n // Abort transaction.\n transaction.unwatcher();\n transaction.currentOutputSnapshotRaw = null;\n transaction.currentOutputSnapshotResolved = null;\n if (transaction.onComplete) {\n transaction.onComplete(null, false, transaction.currentInputSnapshot);\n }\n } else {\n validateFirebaseData(\n 'transaction failed: Data returned ',\n newVal,\n transaction.path\n );\n\n // Mark as run and add to our queue.\n transaction.status = TransactionStatus.RUN;\n const queueNode = treeSubTree(repo.transactionQueueTree_, path);\n const nodeQueue = treeGetValue(queueNode) || [];\n nodeQueue.push(transaction);\n\n treeSetValue(queueNode, nodeQueue);\n\n // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our\n // transaction state, since the user could start new transactions from the\n // event callbacks.\n let priorityForNode;\n if (\n typeof newVal === 'object' &&\n newVal !== null &&\n contains(newVal, '.priority')\n ) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n priorityForNode = safeGet(newVal as any, '.priority');\n assert(\n isValidPriority(priorityForNode),\n 'Invalid priority returned by transaction. ' +\n 'Priority must be a valid string, finite number, server value, or null.'\n );\n } else {\n const currentNode =\n syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||\n ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n\n const serverValues = repoGenerateServerValues(repo);\n const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);\n const newNode = resolveDeferredValueSnapshot(\n newNodeUnresolved,\n currentState,\n serverValues\n );\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = repoGetNextWriteId(repo);\n\n const events = syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n path,\n newNode,\n transaction.currentWriteId,\n transaction.applyLocally\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n }\n}\n\n/**\n * @param excludeSets - A specific set to exclude\n */\nfunction repoGetLatestState(\n repo: Repo,\n path: Path,\n excludeSets?: number[]\n): Node {\n return (\n syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||\n ChildrenNode.EMPTY_NODE\n );\n}\n\n/**\n * Sends any already-run transactions that aren't waiting for outstanding\n * transactions to complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively\n * with a particular transactionQueueTree node to recurse through the tree.\n *\n * @param node - transactionQueueTree node to start at.\n */\nfunction repoSendReadyTransactions(\n repo: Repo,\n node: Tree = repo.transactionQueueTree_\n): void {\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n repoPruneCompletedTransactionsBelowNode(repo, node);\n }\n\n if (treeGetValue(node)) {\n const queue = repoBuildTransactionQueue(repo, node);\n assert(queue.length > 0, 'Sending zero length transaction queue');\n\n const allRun = queue.every(\n (transaction: Transaction) => transaction.status === TransactionStatus.RUN\n );\n\n // If they're all run (and not sent), we can send them. Else, we must wait.\n if (allRun) {\n repoSendTransactionQueue(repo, treeGetPath(node), queue);\n }\n } else if (treeHasChildren(node)) {\n treeForEachChild(node, childNode => {\n repoSendReadyTransactions(repo, childNode);\n });\n }\n}\n\n/**\n * Given a list of run transactions, send them to the server and then handle\n * the result (success or failure).\n *\n * @param path - The location of the queue.\n * @param queue - Queue of transactions under the specified location.\n */\nfunction repoSendTransactionQueue(\n repo: Repo,\n path: Path,\n queue: Transaction[]\n): void {\n // Mark transactions as sent and increment retry count!\n const setsToIgnore = queue.map(txn => {\n return txn.currentWriteId;\n });\n const latestState = repoGetLatestState(repo, path, setsToIgnore);\n let snapToSend = latestState;\n const latestHash = latestState.hash();\n for (let i = 0; i < queue.length; i++) {\n const txn = queue[i];\n assert(\n txn.status === TransactionStatus.RUN,\n 'tryToSendTransactionQueue_: items in queue should all be run.'\n );\n txn.status = TransactionStatus.SENT;\n txn.retryCount++;\n const relativePath = newRelativePath(path, txn.path);\n // If we've gotten to this point, the output snapshot must be defined.\n snapToSend = snapToSend.updateChild(\n relativePath /** @type {!Node} */,\n txn.currentOutputSnapshotRaw\n );\n }\n\n const dataToSend = snapToSend.val(true);\n const pathToSend = path;\n\n // Send the put.\n repo.server_.put(\n pathToSend.toString(),\n dataToSend,\n (status: string) => {\n repoLog(repo, 'transaction put response', {\n path: pathToSend.toString(),\n status\n });\n\n let events: Event[] = [];\n if (status === 'ok') {\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more\n // transactions or sets.\n const callbacks = [];\n for (let i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.COMPLETED;\n events = events.concat(\n syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId)\n );\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this\n // transaction is complete, it should be set\n callbacks.push(() =>\n queue[i].onComplete(\n null,\n true,\n queue[i].currentOutputSnapshotResolved\n )\n );\n }\n queue[i].unwatcher();\n }\n\n // Now remove the completed transactions.\n repoPruneCompletedTransactionsBelowNode(\n repo,\n treeSubTree(repo.transactionQueueTree_, path)\n );\n // There may be pending transactions that we can now send.\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n\n // Finally, trigger onComplete callbacks.\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n } else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (let i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n } else {\n queue[i].status = TransactionStatus.RUN;\n }\n }\n } else {\n warn(\n 'transaction at ' + pathToSend.toString() + ' failed: ' + status\n );\n for (let i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n queue[i].abortReason = status;\n }\n }\n\n repoRerunTransactions(repo, path);\n }\n },\n latestHash\n );\n}\n\n/**\n * Finds all transactions dependent on the data at changedPath and reruns them.\n *\n * Should be called any time cached data changes.\n *\n * Return the highest path that was affected by rerunning transactions. This\n * is the path at which events need to be raised for.\n *\n * @param changedPath - The path in mergedData that changed.\n * @returns The rootmost path that was affected by rerunning transactions.\n */\nfunction repoRerunTransactions(repo: Repo, changedPath: Path): Path {\n const rootMostTransactionNode = repoGetAncestorTransactionNode(\n repo,\n changedPath\n );\n const path = treeGetPath(rootMostTransactionNode);\n\n const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);\n repoRerunTransactionQueue(repo, queue, path);\n\n return path;\n}\n\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted\n * transactions and whatnot).\n *\n * @param queue - The queue of transactions to run.\n * @param path - The path the queue is for.\n */\nfunction repoRerunTransactionQueue(\n repo: Repo,\n queue: Transaction[],\n path: Path\n): void {\n if (queue.length === 0) {\n return; // Nothing to do!\n }\n\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more transactions or\n // sets.\n const callbacks = [];\n let events: Event[] = [];\n // Ignore all of the sets we're going to re-run.\n const txnsToRerun = queue.filter(q => {\n return q.status === TransactionStatus.RUN;\n });\n const setsToIgnore = txnsToRerun.map(q => {\n return q.currentWriteId;\n });\n for (let i = 0; i < queue.length; i++) {\n const transaction = queue[i];\n const relativePath = newRelativePath(path, transaction.path);\n let abortTransaction = false,\n abortReason;\n assert(\n relativePath !== null,\n 'rerunTransactionsUnderNode_: relativePath should not be null.'\n );\n\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n } else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n } else {\n // This code reruns a transaction\n const currentNode = repoGetLatestState(\n repo,\n transaction.path,\n setsToIgnore\n );\n transaction.currentInputSnapshot = currentNode;\n const newData = queue[i].update(currentNode.val());\n if (newData !== undefined) {\n validateFirebaseData(\n 'transaction failed: Data returned ',\n newData,\n transaction.path\n );\n let newDataNode = nodeFromJSON(newData);\n const hasExplicitPriority =\n typeof newData === 'object' &&\n newData != null &&\n contains(newData, '.priority');\n if (!hasExplicitPriority) {\n // Keep the old priority if there wasn't a priority explicitly specified.\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n }\n\n const oldWriteId = transaction.currentWriteId;\n const serverValues = repoGenerateServerValues(repo);\n const newNodeResolved = resolveDeferredValueSnapshot(\n newDataNode,\n currentNode,\n serverValues\n );\n\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = repoGetNextWriteId(repo);\n // Mutates setsToIgnore in place\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(\n syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n transaction.path,\n newNodeResolved,\n transaction.currentWriteId,\n transaction.applyLocally\n )\n );\n events = events.concat(\n syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true)\n );\n } else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n }\n }\n }\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n events = [];\n if (abortTransaction) {\n // Abort.\n queue[i].status = TransactionStatus.COMPLETED;\n\n // Removing a listener can trigger pruning which can muck with\n // mergedData/visibleData (as it prunes data). So defer the unwatcher\n // until we're done.\n (function (unwatcher) {\n setTimeout(unwatcher, Math.floor(0));\n })(queue[i].unwatcher);\n\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n callbacks.push(() =>\n queue[i].onComplete(null, false, queue[i].currentInputSnapshot)\n );\n } else {\n callbacks.push(() =>\n queue[i].onComplete(new Error(abortReason), false, null)\n );\n }\n }\n }\n }\n\n // Clean up completed transactions.\n repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);\n\n // Now fire callbacks, now that we're in a good, known state.\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n\n // Try to send the transaction result to the server.\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n}\n\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending\n * transaction on it, or just returns the node for the given path if there are\n * no pending transactions on any ancestor.\n *\n * @param path - The location to start at.\n * @returns The rootmost node with a transaction.\n */\nfunction repoGetAncestorTransactionNode(\n repo: Repo,\n path: Path\n): Tree {\n let front;\n\n // Start at the root and walk deeper into the tree towards path until we\n // find a node with pending transactions.\n let transactionNode = repo.transactionQueueTree_;\n front = pathGetFront(path);\n while (front !== null && treeGetValue(transactionNode) === undefined) {\n transactionNode = treeSubTree(transactionNode, front);\n path = pathPopFront(path);\n front = pathGetFront(path);\n }\n\n return transactionNode;\n}\n\n/**\n * Builds the queue of all transactions at or below the specified\n * transactionNode.\n *\n * @param transactionNode\n * @returns The generated queue.\n */\nfunction repoBuildTransactionQueue(\n repo: Repo,\n transactionNode: Tree\n): Transaction[] {\n // Walk any child transaction queues and aggregate them into a single queue.\n const transactionQueue: Transaction[] = [];\n repoAggregateTransactionQueuesForNode(\n repo,\n transactionNode,\n transactionQueue\n );\n\n // Sort them by the order the transactions were created.\n transactionQueue.sort((a, b) => a.order - b.order);\n\n return transactionQueue;\n}\n\nfunction repoAggregateTransactionQueuesForNode(\n repo: Repo,\n node: Tree,\n queue: Transaction[]\n): void {\n const nodeQueue = treeGetValue(node);\n if (nodeQueue) {\n for (let i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n\n treeForEachChild(node, child => {\n repoAggregateTransactionQueuesForNode(repo, child, queue);\n });\n}\n\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n */\nfunction repoPruneCompletedTransactionsBelowNode(\n repo: Repo,\n node: Tree\n): void {\n const queue = treeGetValue(node);\n if (queue) {\n let to = 0;\n for (let from = 0; from < queue.length; from++) {\n if (queue[from].status !== TransactionStatus.COMPLETED) {\n queue[to] = queue[from];\n to++;\n }\n }\n queue.length = to;\n treeSetValue(node, queue.length > 0 ? queue : undefined);\n }\n\n treeForEachChild(node, childNode => {\n repoPruneCompletedTransactionsBelowNode(repo, childNode);\n });\n}\n\n/**\n * Aborts all transactions on ancestors or descendants of the specified path.\n * Called when doing a set() or update() since we consider them incompatible\n * with transactions.\n *\n * @param path - Path for which we want to abort related transactions.\n */\nfunction repoAbortTransactions(repo: Repo, path: Path): Path {\n const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));\n\n const transactionNode = treeSubTree(repo.transactionQueueTree_, path);\n\n treeForEachAncestor(transactionNode, (node: Tree) => {\n repoAbortTransactionsOnNode(repo, node);\n });\n\n repoAbortTransactionsOnNode(repo, transactionNode);\n\n treeForEachDescendant(transactionNode, (node: Tree) => {\n repoAbortTransactionsOnNode(repo, node);\n });\n\n return affectedPath;\n}\n\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param node - Node to abort transactions for.\n */\nfunction repoAbortTransactionsOnNode(\n repo: Repo,\n node: Tree\n): void {\n const queue = treeGetValue(node);\n if (queue) {\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more transactions\n // or sets.\n const callbacks = [];\n\n // Go through queue. Any already-sent transactions must be marked for\n // abort, while the unsent ones can be immediately aborted and removed.\n let events: Event[] = [];\n let lastSent = -1;\n for (let i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n // Already marked. No action needed.\n } else if (queue[i].status === TransactionStatus.SENT) {\n assert(\n lastSent === i - 1,\n 'All SENT items should be at beginning of queue.'\n );\n lastSent = i;\n // Mark transaction for abort when it comes back.\n queue[i].status = TransactionStatus.SENT_NEEDS_ABORT;\n queue[i].abortReason = 'set';\n } else {\n assert(\n queue[i].status === TransactionStatus.RUN,\n 'Unexpected transaction status in abort'\n );\n // We can abort it immediately.\n queue[i].unwatcher();\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n queue[i].currentWriteId,\n true\n )\n );\n if (queue[i].onComplete) {\n callbacks.push(\n queue[i].onComplete.bind(null, new Error('set'), false, null)\n );\n }\n }\n }\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n treeSetValue(node, undefined);\n } else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n\n // Now fire the callbacks.\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n treeGetPath(node),\n events\n );\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../../RepoInfo';\nimport { Path } from '../Path';\nimport { warnIfPageIsSecure, warn, fatal } from '../util';\n\nfunction decodePath(pathString: string): string {\n let pathStringDecoded = '';\n const pieces = pathString.split('/');\n for (let i = 0; i < pieces.length; i++) {\n if (pieces[i].length > 0) {\n let piece = pieces[i];\n try {\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\n } catch (e) {}\n pathStringDecoded += '/' + piece;\n }\n }\n return pathStringDecoded;\n}\n\n/**\n * @returns key value hash\n */\nfunction decodeQuery(queryString: string): { [key: string]: string } {\n const results = {};\n if (queryString.charAt(0) === '?') {\n queryString = queryString.substring(1);\n }\n for (const segment of queryString.split('&')) {\n if (segment.length === 0) {\n continue;\n }\n const kv = segment.split('=');\n if (kv.length === 2) {\n results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\n } else {\n warn(`Invalid query segment '${segment}' in query '${queryString}'`);\n }\n }\n return results;\n}\n\nexport const parseRepoInfo = function (\n dataURL: string,\n nodeAdmin: boolean\n): { repoInfo: RepoInfo; path: Path } {\n const parsedUrl = parseDatabaseURL(dataURL),\n namespace = parsedUrl.namespace;\n\n if (parsedUrl.domain === 'firebase.com') {\n fatal(\n parsedUrl.host +\n ' is no longer supported. ' +\n 'Please use .firebaseio.com instead'\n );\n }\n\n // Catch common error of uninitialized namespace value.\n if (\n (!namespace || namespace === 'undefined') &&\n parsedUrl.domain !== 'localhost'\n ) {\n fatal(\n 'Cannot parse Firebase url. Please use https://.firebaseio.com'\n );\n }\n\n if (!parsedUrl.secure) {\n warnIfPageIsSecure();\n }\n\n const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\n\n return {\n repoInfo: new RepoInfo(\n parsedUrl.host,\n parsedUrl.secure,\n namespace,\n webSocketOnly,\n nodeAdmin,\n /*persistenceKey=*/ '',\n /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain\n ),\n path: new Path(parsedUrl.pathString)\n };\n};\n\nexport const parseDatabaseURL = function (dataURL: string): {\n host: string;\n port: number;\n domain: string;\n subdomain: string;\n secure: boolean;\n scheme: string;\n pathString: string;\n namespace: string;\n} {\n // Default to empty strings in the event of a malformed string.\n let host = '',\n domain = '',\n subdomain = '',\n pathString = '',\n namespace = '';\n\n // Always default to SSL, unless otherwise specified.\n let secure = true,\n scheme = 'https',\n port = 443;\n\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\n if (typeof dataURL === 'string') {\n // Parse scheme.\n let colonInd = dataURL.indexOf('//');\n if (colonInd >= 0) {\n scheme = dataURL.substring(0, colonInd - 1);\n dataURL = dataURL.substring(colonInd + 2);\n }\n\n // Parse host, path, and query string.\n let slashInd = dataURL.indexOf('/');\n if (slashInd === -1) {\n slashInd = dataURL.length;\n }\n let questionMarkInd = dataURL.indexOf('?');\n if (questionMarkInd === -1) {\n questionMarkInd = dataURL.length;\n }\n host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));\n if (slashInd < questionMarkInd) {\n // For pathString, questionMarkInd will always come after slashInd\n pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));\n }\n const queryParams = decodeQuery(\n dataURL.substring(Math.min(dataURL.length, questionMarkInd))\n );\n\n // If we have a port, use scheme for determining if it's secure.\n colonInd = host.indexOf(':');\n if (colonInd >= 0) {\n secure = scheme === 'https' || scheme === 'wss';\n port = parseInt(host.substring(colonInd + 1), 10);\n } else {\n colonInd = host.length;\n }\n\n const hostWithoutPort = host.slice(0, colonInd);\n if (hostWithoutPort.toLowerCase() === 'localhost') {\n domain = 'localhost';\n } else if (hostWithoutPort.split('.').length <= 2) {\n domain = hostWithoutPort;\n } else {\n // Interpret the subdomain of a 3 or more component URL as the namespace name.\n const dotInd = host.indexOf('.');\n subdomain = host.substring(0, dotInd).toLowerCase();\n domain = host.substring(dotInd + 1);\n // Normalize namespaces to lowercase to share storage / connection.\n namespace = subdomain;\n }\n // Always treat the value of the `ns` as the namespace name if it is present.\n if ('ns' in queryParams) {\n namespace = queryParams['ns'];\n }\n }\n\n return {\n host,\n port,\n domain,\n subdomain,\n secure,\n scheme,\n pathString,\n namespace\n };\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport {\n tryParseInt,\n MAX_NAME,\n MIN_NAME,\n INTEGER_32_MIN,\n INTEGER_32_MAX\n} from '../util/util';\n\n// Modeled after base64 web-safe chars, but ordered by ASCII.\nconst PUSH_CHARS =\n '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n\nconst MIN_PUSH_CHAR = '-';\n\nconst MAX_PUSH_CHAR = 'z';\n\nconst MAX_KEY_LEN = 786;\n\n/**\n * Fancy ID generator that creates 20-character string identifiers with the\n * following properties:\n *\n * 1. They're based on timestamp so that they sort *after* any existing ids.\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\n * collide with other clients' IDs.\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\n * that will sort properly).\n * 4. They're monotonically increasing. Even if you generate more than one in\n * the same timestamp, the latter ones will sort after the former ones. We do\n * this by using the previous random bits but \"incrementing\" them by 1 (only\n * in the case of a timestamp collision).\n */\nexport const nextPushId = (function () {\n // Timestamp of last push, used to prevent local collisions if you push twice\n // in one ms.\n let lastPushTime = 0;\n\n // We generate 72-bits of randomness which get turned into 12 characters and\n // appended to the timestamp to prevent collisions with other clients. We\n // store the last characters we generated because in the event of a collision,\n // we'll use those same characters except \"incremented\" by one.\n const lastRandChars: number[] = [];\n\n return function (now: number) {\n const duplicateTime = now === lastPushTime;\n lastPushTime = now;\n\n let i;\n const timeStampChars = new Array(8);\n for (i = 7; i >= 0; i--) {\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\n // NOTE: Can't use << here because javascript will convert to int and lose\n // the upper bits.\n now = Math.floor(now / 64);\n }\n assert(now === 0, 'Cannot push at time == 0');\n\n let id = timeStampChars.join('');\n\n if (!duplicateTime) {\n for (i = 0; i < 12; i++) {\n lastRandChars[i] = Math.floor(Math.random() * 64);\n }\n } else {\n // If the timestamp hasn't changed since last push, use the same random\n // number, except incremented by 1.\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\n lastRandChars[i] = 0;\n }\n lastRandChars[i]++;\n }\n for (i = 0; i < 12; i++) {\n id += PUSH_CHARS.charAt(lastRandChars[i]);\n }\n assert(id.length === 20, 'nextPushId: Length should be 20.');\n\n return id;\n };\n})();\n\nexport const successor = function (key: string) {\n if (key === '' + INTEGER_32_MAX) {\n // See https://firebase.google.com/docs/database/web/lists-of-data#data-order\n return MIN_PUSH_CHAR;\n }\n const keyAsInt: number = tryParseInt(key);\n if (keyAsInt != null) {\n return '' + (keyAsInt + 1);\n }\n const next = new Array(key.length);\n\n for (let i = 0; i < next.length; i++) {\n next[i] = key.charAt(i);\n }\n\n if (next.length < MAX_KEY_LEN) {\n next.push(MIN_PUSH_CHAR);\n return next.join('');\n }\n\n let i = next.length - 1;\n\n while (i >= 0 && next[i] === MAX_PUSH_CHAR) {\n i--;\n }\n\n // `successor` was called on the largest possible key, so return the\n // MAX_NAME, which sorts larger than all keys.\n if (i === -1) {\n return MAX_NAME;\n }\n\n const source = next[i];\n const sourcePlusOne = PUSH_CHARS.charAt(PUSH_CHARS.indexOf(source) + 1);\n next[i] = sourcePlusOne;\n\n return next.slice(0, i + 1).join('');\n};\n\n// `key` is assumed to be non-empty.\nexport const predecessor = function (key: string) {\n if (key === '' + INTEGER_32_MIN) {\n return MIN_NAME;\n }\n const keyAsInt: number = tryParseInt(key);\n if (keyAsInt != null) {\n return '' + (keyAsInt - 1);\n }\n const next = new Array(key.length);\n for (let i = 0; i < next.length; i++) {\n next[i] = key.charAt(i);\n }\n // If `key` ends in `MIN_PUSH_CHAR`, the largest key lexicographically\n // smaller than `key`, is `key[0:key.length - 1]`. The next key smaller\n // than that, `predecessor(predecessor(key))`, is\n //\n // `key[0:key.length - 2] + (key[key.length - 1] - 1) + \\\n // { MAX_PUSH_CHAR repeated MAX_KEY_LEN - (key.length - 1) times }\n //\n // analogous to increment/decrement for base-10 integers.\n //\n // This works because lexicographic comparison works character-by-character,\n // using length as a tie-breaker if one key is a prefix of the other.\n if (next[next.length - 1] === MIN_PUSH_CHAR) {\n if (next.length === 1) {\n // See https://firebase.google.com/docs/database/web/lists-of-data#orderbykey\n return '' + INTEGER_32_MAX;\n }\n delete next[next.length - 1];\n return next.join('');\n }\n // Replace the last character with it's immediate predecessor, and\n // fill the suffix of the key with MAX_PUSH_CHAR. This is the\n // lexicographically largest possible key smaller than `key`.\n next[next.length - 1] = PUSH_CHARS.charAt(\n PUSH_CHARS.indexOf(next[next.length - 1]) - 1\n );\n return next.join('') + MAX_PUSH_CHAR.repeat(MAX_KEY_LEN - next.length);\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { stringify } from '@firebase/util';\n\nimport { DataSnapshot as ExpDataSnapshot } from '../../api/Reference_impl';\nimport { Path } from '../util/Path';\n\nimport { EventRegistration } from './EventRegistration';\n\n/**\n * Encapsulates the data needed to raise an event\n * @interface\n */\nexport interface Event {\n getPath(): Path;\n\n getEventType(): string;\n\n getEventRunner(): () => void;\n\n toString(): string;\n}\n\n/**\n * One of the following strings: \"value\", \"child_added\", \"child_changed\",\n * \"child_removed\", or \"child_moved.\"\n */\nexport type EventType =\n | 'value'\n | 'child_added'\n | 'child_changed'\n | 'child_moved'\n | 'child_removed';\n\n/**\n * Encapsulates the data needed to raise an event\n */\nexport class DataEvent implements Event {\n /**\n * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed\n * @param eventRegistration - The function to call to with the event data. User provided\n * @param snapshot - The data backing the event\n * @param prevName - Optional, the name of the previous child for child_* events.\n */\n constructor(\n public eventType: EventType,\n public eventRegistration: EventRegistration,\n public snapshot: ExpDataSnapshot,\n public prevName?: string | null\n ) {}\n getPath(): Path {\n const ref = this.snapshot.ref;\n if (this.eventType === 'value') {\n return ref._path;\n } else {\n return ref.parent._path;\n }\n }\n getEventType(): string {\n return this.eventType;\n }\n getEventRunner(): () => void {\n return this.eventRegistration.getEventRunner(this);\n }\n toString(): string {\n return (\n this.getPath().toString() +\n ':' +\n this.eventType +\n ':' +\n stringify(this.snapshot.exportVal())\n );\n }\n}\n\nexport class CancelEvent implements Event {\n constructor(\n public eventRegistration: EventRegistration,\n public error: Error,\n public path: Path\n ) {}\n getPath(): Path {\n return this.path;\n }\n getEventType(): string {\n return 'cancel';\n }\n getEventRunner(): () => void {\n return this.eventRegistration.getEventRunner(this);\n }\n toString(): string {\n return this.path.toString() + ':cancel';\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { DataSnapshot } from '../../api/Reference_impl';\nimport { Repo } from '../Repo';\nimport { Path } from '../util/Path';\n\nimport { Change } from './Change';\nimport { CancelEvent, Event } from './Event';\nimport { QueryParams } from './QueryParams';\n\n/**\n * A user callback. Callbacks issues from the Legacy SDK maintain references\n * to the original user-issued callbacks, which allows equality\n * comparison by reference even though this callbacks are wrapped before\n * they can be passed to the firebase@exp SDK.\n *\n * @internal\n */\nexport interface UserCallback {\n (dataSnapshot: DataSnapshot, previousChildName?: string | null): unknown;\n userCallback?: unknown;\n context?: object | null;\n}\n\n/**\n * A wrapper class that converts events from the database@exp SDK to the legacy\n * Database SDK. Events are not converted directly as event registration relies\n * on reference comparison of the original user callback (see `matches()`) and\n * relies on equality of the legacy SDK's `context` object.\n */\nexport class CallbackContext {\n constructor(\n private readonly snapshotCallback: UserCallback,\n private readonly cancelCallback?: (error: Error) => unknown\n ) {}\n\n onValue(\n expDataSnapshot: DataSnapshot,\n previousChildName?: string | null\n ): void {\n this.snapshotCallback.call(null, expDataSnapshot, previousChildName);\n }\n\n onCancel(error: Error): void {\n assert(\n this.hasCancelCallback,\n 'Raising a cancel event on a listener with no cancel callback'\n );\n return this.cancelCallback.call(null, error);\n }\n\n get hasCancelCallback(): boolean {\n return !!this.cancelCallback;\n }\n\n matches(other: CallbackContext): boolean {\n return (\n this.snapshotCallback === other.snapshotCallback ||\n (this.snapshotCallback.userCallback !== undefined &&\n this.snapshotCallback.userCallback ===\n other.snapshotCallback.userCallback &&\n this.snapshotCallback.context === other.snapshotCallback.context)\n );\n }\n}\n\nexport interface QueryContext {\n readonly _queryIdentifier: string;\n readonly _queryObject: object;\n readonly _repo: Repo;\n readonly _path: Path;\n readonly _queryParams: QueryParams;\n}\n\n/**\n * An EventRegistration is basically an event type ('value', 'child_added', etc.) and a callback\n * to be notified of that type of event.\n *\n * That said, it can also contain a cancel callback to be notified if the event is canceled. And\n * currently, this code is organized around the idea that you would register multiple child_ callbacks\n * together, as a single EventRegistration. Though currently we don't do that.\n */\nexport interface EventRegistration {\n /**\n * True if this container has a callback to trigger for this event type\n */\n respondsTo(eventType: string): boolean;\n\n createEvent(change: Change, query: QueryContext): Event;\n\n /**\n * Given event data, return a function to trigger the user's callback\n */\n getEventRunner(eventData: Event): () => void;\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null;\n\n matches(other: EventRegistration): boolean;\n\n /**\n * False basically means this is a \"dummy\" callback container being used as a sentinel\n * to remove all callback containers of a particular type. (e.g. if the user does\n * ref.off('value') without specifying a specific callback).\n *\n * (TODO: Rework this, since it's hacky)\n *\n */\n hasAnyCallback(): boolean;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from '@firebase/util';\n\nimport {\n Repo,\n repoOnDisconnectCancel,\n repoOnDisconnectSet,\n repoOnDisconnectSetWithPriority,\n repoOnDisconnectUpdate\n} from '../core/Repo';\nimport { Path } from '../core/util/Path';\nimport {\n validateFirebaseDataArg,\n validateFirebaseMergeDataArg,\n validatePriority,\n validateWritablePath\n} from '../core/util/validation';\n\n/**\n * The `onDisconnect` class allows you to write or clear data when your client\n * disconnects from the Database server. These updates occur whether your\n * client disconnects cleanly or not, so you can rely on them to clean up data\n * even if a connection is dropped or a client crashes.\n *\n * The `onDisconnect` class is most commonly used to manage presence in\n * applications where it is useful to detect how many clients are connected and\n * when other clients disconnect. See\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information.\n *\n * To avoid problems when a connection is dropped before the requests can be\n * transferred to the Database server, these functions should be called before\n * writing any data.\n *\n * Note that `onDisconnect` operations are only triggered once. If you want an\n * operation to occur each time a disconnect occurs, you'll need to re-establish\n * the `onDisconnect` operations each time you reconnect.\n */\nexport class OnDisconnect {\n /** @hideconstructor */\n constructor(private _repo: Repo, private _path: Path) {}\n\n /**\n * Cancels all previously queued `onDisconnect()` set or update events for this\n * location and all children.\n *\n * If a write has been queued for this location via a `set()` or `update()` at a\n * parent location, the write at this location will be canceled, though writes\n * to sibling locations will still occur.\n *\n * @returns Resolves when synchronization to the server is complete.\n */\n cancel(): Promise {\n const deferred = new Deferred();\n repoOnDisconnectCancel(\n this._repo,\n this._path,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is deleted when the client is disconnected\n * (due to closing the browser, navigating to a new page, or network issues).\n *\n * @returns Resolves when synchronization to the server is complete.\n */\n remove(): Promise {\n validateWritablePath('OnDisconnect.remove', this._path);\n const deferred = new Deferred();\n repoOnDisconnectSet(\n this._repo,\n this._path,\n null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is set to the specified value when the\n * client is disconnected (due to closing the browser, navigating to a new page,\n * or network issues).\n *\n * `set()` is especially useful for implementing \"presence\" systems, where a\n * value should be changed or cleared when a user disconnects so that they\n * appear \"offline\" to other users. See\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information.\n *\n * Note that `onDisconnect` operations are only triggered once. If you want an\n * operation to occur each time a disconnect occurs, you'll need to re-establish\n * the `onDisconnect` operations each time.\n *\n * @param value - The value to be written to this location on disconnect (can\n * be an object, array, string, number, boolean, or null).\n * @returns Resolves when synchronization to the Database is complete.\n */\n set(value: unknown): Promise {\n validateWritablePath('OnDisconnect.set', this._path);\n validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);\n const deferred = new Deferred();\n repoOnDisconnectSet(\n this._repo,\n this._path,\n value,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is set to the specified value and priority\n * when the client is disconnected (due to closing the browser, navigating to a\n * new page, or network issues).\n *\n * @param value - The value to be written to this location on disconnect (can\n * be an object, array, string, number, boolean, or null).\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when synchronization to the Database is complete.\n */\n setWithPriority(\n value: unknown,\n priority: number | string | null\n ): Promise {\n validateWritablePath('OnDisconnect.setWithPriority', this._path);\n validateFirebaseDataArg(\n 'OnDisconnect.setWithPriority',\n value,\n this._path,\n false\n );\n validatePriority('OnDisconnect.setWithPriority', priority, false);\n\n const deferred = new Deferred();\n repoOnDisconnectSetWithPriority(\n this._repo,\n this._path,\n value,\n priority,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Writes multiple values at this location when the client is disconnected (due\n * to closing the browser, navigating to a new page, or network issues).\n *\n * The `values` argument contains multiple property-value pairs that will be\n * written to the Database together. Each child property can either be a simple\n * property (for example, \"name\") or a relative path (for example, \"name/first\")\n * from the current location to the data to update.\n *\n * As opposed to the `set()` method, `update()` can be use to selectively update\n * only the referenced properties at the current location (instead of replacing\n * all the child properties at the current location).\n *\n * @param values - Object containing multiple values.\n * @returns Resolves when synchronization to the Database is complete.\n */\n update(values: object): Promise {\n validateWritablePath('OnDisconnect.update', this._path);\n validateFirebaseMergeDataArg(\n 'OnDisconnect.update',\n values,\n this._path,\n false\n );\n const deferred = new Deferred();\n repoOnDisconnectUpdate(\n this._repo,\n this._path,\n values as Record,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, getModularInstance, Deferred } from '@firebase/util';\n\nimport {\n Repo,\n repoAddEventCallbackForQuery,\n repoGetValue,\n repoRemoveEventCallbackForQuery,\n repoServerTime,\n repoSetWithPriority,\n repoUpdate\n} from '../core/Repo';\nimport { ChildrenNode } from '../core/snap/ChildrenNode';\nimport { Index } from '../core/snap/indexes/Index';\nimport { KEY_INDEX } from '../core/snap/indexes/KeyIndex';\nimport { PathIndex } from '../core/snap/indexes/PathIndex';\nimport { PRIORITY_INDEX } from '../core/snap/indexes/PriorityIndex';\nimport { VALUE_INDEX } from '../core/snap/indexes/ValueIndex';\nimport { Node } from '../core/snap/Node';\nimport { syncPointSetReferenceConstructor } from '../core/SyncPoint';\nimport { syncTreeSetReferenceConstructor } from '../core/SyncTree';\nimport { parseRepoInfo } from '../core/util/libs/parser';\nimport { nextPushId } from '../core/util/NextPushId';\nimport {\n Path,\n pathEquals,\n pathGetBack,\n pathGetFront,\n pathChild,\n pathParent,\n pathToUrlEncodedString,\n pathIsEmpty\n} from '../core/util/Path';\nimport {\n fatal,\n MAX_NAME,\n MIN_NAME,\n ObjectToUniqueKey\n} from '../core/util/util';\nimport {\n isValidPriority,\n validateFirebaseDataArg,\n validateFirebaseMergeDataArg,\n validateKey,\n validatePathString,\n validatePriority,\n validateRootPathString,\n validateUrl,\n validateWritablePath\n} from '../core/util/validation';\nimport { Change } from '../core/view/Change';\nimport { CancelEvent, DataEvent, EventType } from '../core/view/Event';\nimport {\n CallbackContext,\n EventRegistration,\n QueryContext,\n UserCallback\n} from '../core/view/EventRegistration';\nimport {\n QueryParams,\n queryParamsEndAt,\n queryParamsEndBefore,\n queryParamsGetQueryObject,\n queryParamsLimitToFirst,\n queryParamsLimitToLast,\n queryParamsOrderBy,\n queryParamsStartAfter,\n queryParamsStartAt\n} from '../core/view/QueryParams';\n\nimport { Database } from './Database';\nimport { OnDisconnect } from './OnDisconnect';\nimport {\n ListenOptions,\n Query as Query,\n DatabaseReference,\n Unsubscribe,\n ThenableReference\n} from './Reference';\n\n/**\n * @internal\n */\nexport class QueryImpl implements Query, QueryContext {\n /**\n * @hideconstructor\n */\n constructor(\n readonly _repo: Repo,\n readonly _path: Path,\n readonly _queryParams: QueryParams,\n readonly _orderByCalled: boolean\n ) {}\n\n get key(): string | null {\n if (pathIsEmpty(this._path)) {\n return null;\n } else {\n return pathGetBack(this._path);\n }\n }\n\n get ref(): DatabaseReference {\n return new ReferenceImpl(this._repo, this._path);\n }\n\n get _queryIdentifier(): string {\n const obj = queryParamsGetQueryObject(this._queryParams);\n const id = ObjectToUniqueKey(obj);\n return id === '{}' ? 'default' : id;\n }\n\n /**\n * An object representation of the query parameters used by this Query.\n */\n get _queryObject(): object {\n return queryParamsGetQueryObject(this._queryParams);\n }\n\n isEqual(other: QueryImpl | null): boolean {\n other = getModularInstance(other);\n if (!(other instanceof QueryImpl)) {\n return false;\n }\n\n const sameRepo = this._repo === other._repo;\n const samePath = pathEquals(this._path, other._path);\n const sameQueryIdentifier =\n this._queryIdentifier === other._queryIdentifier;\n\n return sameRepo && samePath && sameQueryIdentifier;\n }\n\n toJSON(): string {\n return this.toString();\n }\n\n toString(): string {\n return this._repo.toString() + pathToUrlEncodedString(this._path);\n }\n}\n\n/**\n * Validates that no other order by call has been made\n */\nfunction validateNoPreviousOrderByCall(query: QueryImpl, fnName: string) {\n if (query._orderByCalled === true) {\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\n }\n}\n\n/**\n * Validates start/end values for queries.\n */\nfunction validateQueryEndpoints(params: QueryParams) {\n let startNode = null;\n let endNode = null;\n if (params.hasStart()) {\n startNode = params.getIndexStartValue();\n }\n if (params.hasEnd()) {\n endNode = params.getIndexEndValue();\n }\n\n if (params.getIndex() === KEY_INDEX) {\n const tooManyArgsError =\n 'Query: When ordering by key, you may only pass one argument to ' +\n 'startAt(), endAt(), or equalTo().';\n const wrongArgTypeError =\n 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +\n 'endAt(), endBefore(), or equalTo() must be a string.';\n if (params.hasStart()) {\n const startName = params.getIndexStartName();\n if (startName !== MIN_NAME) {\n throw new Error(tooManyArgsError);\n } else if (typeof startNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n if (params.hasEnd()) {\n const endName = params.getIndexEndName();\n if (endName !== MAX_NAME) {\n throw new Error(tooManyArgsError);\n } else if (typeof endNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n } else if (params.getIndex() === PRIORITY_INDEX) {\n if (\n (startNode != null && !isValidPriority(startNode)) ||\n (endNode != null && !isValidPriority(endNode))\n ) {\n throw new Error(\n 'Query: When ordering by priority, the first argument passed to startAt(), ' +\n 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +\n '(null, a number, or a string).'\n );\n }\n } else {\n assert(\n params.getIndex() instanceof PathIndex ||\n params.getIndex() === VALUE_INDEX,\n 'unknown index type.'\n );\n if (\n (startNode != null && typeof startNode === 'object') ||\n (endNode != null && typeof endNode === 'object')\n ) {\n throw new Error(\n 'Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +\n 'equalTo() cannot be an object.'\n );\n }\n }\n}\n\n/**\n * Validates that limit* has been called with the correct combination of parameters\n */\nfunction validateLimit(params: QueryParams) {\n if (\n params.hasStart() &&\n params.hasEnd() &&\n params.hasLimit() &&\n !params.hasAnchoredLimit()\n ) {\n throw new Error(\n \"Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use \" +\n 'limitToFirst() or limitToLast() instead.'\n );\n }\n}\n/**\n * @internal\n */\nexport class ReferenceImpl extends QueryImpl implements DatabaseReference {\n /** @hideconstructor */\n constructor(repo: Repo, path: Path) {\n super(repo, path, new QueryParams(), false);\n }\n\n get parent(): ReferenceImpl | null {\n const parentPath = pathParent(this._path);\n return parentPath === null\n ? null\n : new ReferenceImpl(this._repo, parentPath);\n }\n\n get root(): ReferenceImpl {\n let ref: ReferenceImpl = this;\n while (ref.parent !== null) {\n ref = ref.parent;\n }\n return ref;\n }\n}\n\n/**\n * A `DataSnapshot` contains data from a Database location.\n *\n * Any time you read data from the Database, you receive the data as a\n * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach\n * with `on()` or `once()`. You can extract the contents of the snapshot as a\n * JavaScript object by calling the `val()` method. Alternatively, you can\n * traverse into the snapshot by calling `child()` to return child snapshots\n * (which you could then call `val()` on).\n *\n * A `DataSnapshot` is an efficiently generated, immutable copy of the data at\n * a Database location. It cannot be modified and will never change (to modify\n * data, you always call the `set()` method on a `Reference` directly).\n */\nexport class DataSnapshot {\n /**\n * @param _node - A SnapshotNode to wrap.\n * @param ref - The location this snapshot came from.\n * @param _index - The iteration order for this snapshot\n * @hideconstructor\n */\n constructor(\n readonly _node: Node,\n /**\n * The location of this DataSnapshot.\n */\n readonly ref: DatabaseReference,\n readonly _index: Index\n ) {}\n\n /**\n * Gets the priority value of the data in this `DataSnapshot`.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}\n * ).\n */\n get priority(): string | number | null {\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\n return this._node.getPriority().val() as string | number | null;\n }\n\n /**\n * The key (last part of the path) of the location of this `DataSnapshot`.\n *\n * The last token in a Database location is considered its key. For example,\n * \"ada\" is the key for the /users/ada/ node. Accessing the key on any\n * `DataSnapshot` will return the key for the location that generated it.\n * However, accessing the key on the root URL of a Database will return\n * `null`.\n */\n get key(): string | null {\n return this.ref.key;\n }\n\n /** Returns the number of child properties of this `DataSnapshot`. */\n get size(): number {\n return this._node.numChildren();\n }\n\n /**\n * Gets another `DataSnapshot` for the location at the specified relative path.\n *\n * Passing a relative path to the `child()` method of a DataSnapshot returns\n * another `DataSnapshot` for the location at the specified relative path. The\n * relative path can either be a simple child name (for example, \"ada\") or a\n * deeper, slash-separated path (for example, \"ada/name/first\"). If the child\n * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`\n * whose value is `null`) is returned.\n *\n * @param path - A relative path to the location of child data.\n */\n child(path: string): DataSnapshot {\n const childPath = new Path(path);\n const childRef = child(this.ref, path);\n return new DataSnapshot(\n this._node.getChild(childPath),\n childRef,\n PRIORITY_INDEX\n );\n }\n /**\n * Returns true if this `DataSnapshot` contains any data. It is slightly more\n * efficient than using `snapshot.val() !== null`.\n */\n exists(): boolean {\n return !this._node.isEmpty();\n }\n\n /**\n * Exports the entire contents of the DataSnapshot as a JavaScript object.\n *\n * The `exportVal()` method is similar to `val()`, except priority information\n * is included (if available), making it suitable for backing up your data.\n *\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\n * Array, string, number, boolean, or `null`).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n exportVal(): any {\n return this._node.val(true);\n }\n\n /**\n * Enumerates the top-level children in the `IteratedDataSnapshot`.\n *\n * Because of the way JavaScript objects work, the ordering of data in the\n * JavaScript object returned by `val()` is not guaranteed to match the\n * ordering on the server nor the ordering of `onChildAdded()` events. That is\n * where `forEach()` comes in handy. It guarantees the children of a\n * `DataSnapshot` will be iterated in their query order.\n *\n * If no explicit `orderBy*()` method is used, results are returned\n * ordered by key (unless priorities are used, in which case, results are\n * returned by priority).\n *\n * @param action - A function that will be called for each child DataSnapshot.\n * The callback can return true to cancel further enumeration.\n * @returns true if enumeration was canceled due to your callback returning\n * true.\n */\n forEach(action: (child: IteratedDataSnapshot) => boolean | void): boolean {\n if (this._node.isLeafNode()) {\n return false;\n }\n\n const childrenNode = this._node as ChildrenNode;\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\n return !!childrenNode.forEachChild(this._index, (key, node) => {\n return action(\n new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX)\n );\n });\n }\n\n /**\n * Returns true if the specified child path has (non-null) data.\n *\n * @param path - A relative path to the location of a potential child.\n * @returns `true` if data exists at the specified child path; else\n * `false`.\n */\n hasChild(path: string): boolean {\n const childPath = new Path(path);\n return !this._node.getChild(childPath).isEmpty();\n }\n\n /**\n * Returns whether or not the `DataSnapshot` has any non-`null` child\n * properties.\n *\n * You can use `hasChildren()` to determine if a `DataSnapshot` has any\n * children. If it does, you can enumerate them using `forEach()`. If it\n * doesn't, then either this snapshot contains a primitive value (which can be\n * retrieved with `val()`) or it is empty (in which case, `val()` will return\n * `null`).\n *\n * @returns true if this snapshot has any children; else false.\n */\n hasChildren(): boolean {\n if (this._node.isLeafNode()) {\n return false;\n } else {\n return !this._node.isEmpty();\n }\n }\n\n /**\n * Returns a JSON-serializable representation of this object.\n */\n toJSON(): object | null {\n return this.exportVal();\n }\n\n /**\n * Extracts a JavaScript value from a `DataSnapshot`.\n *\n * Depending on the data in a `DataSnapshot`, the `val()` method may return a\n * scalar type (string, number, or boolean), an array, or an object. It may\n * also return null, indicating that the `DataSnapshot` is empty (contains no\n * data).\n *\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\n * Array, string, number, boolean, or `null`).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n val(): any {\n return this._node.val();\n }\n}\n\n/**\n * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined.\n */\nexport interface IteratedDataSnapshot extends DataSnapshot {\n key: string; // key of the location of this snapshot.\n}\n\n/**\n *\n * Returns a `Reference` representing the location in the Database\n * corresponding to the provided path. If no path is provided, the `Reference`\n * will point to the root of the Database.\n *\n * @param db - The database instance to obtain a reference for.\n * @param path - Optional path representing the location the returned\n * `Reference` will point. If not provided, the returned `Reference` will\n * point to the root of the Database.\n * @returns If a path is provided, a `Reference`\n * pointing to the provided path. Otherwise, a `Reference` pointing to the\n * root of the Database.\n */\nexport function ref(db: Database, path?: string): DatabaseReference {\n db = getModularInstance(db);\n db._checkNotDeleted('ref');\n return path !== undefined ? child(db._root, path) : db._root;\n}\n\n/**\n * Returns a `Reference` representing the location in the Database\n * corresponding to the provided Firebase URL.\n *\n * An exception is thrown if the URL is not a valid Firebase Database URL or it\n * has a different domain than the current `Database` instance.\n *\n * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored\n * and are not applied to the returned `Reference`.\n *\n * @param db - The database instance to obtain a reference for.\n * @param url - The Firebase URL at which the returned `Reference` will\n * point.\n * @returns A `Reference` pointing to the provided\n * Firebase URL.\n */\nexport function refFromURL(db: Database, url: string): DatabaseReference {\n db = getModularInstance(db);\n db._checkNotDeleted('refFromURL');\n const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\n validateUrl('refFromURL', parsedURL);\n\n const repoInfo = parsedURL.repoInfo;\n if (\n !db._repo.repoInfo_.isCustomHost() &&\n repoInfo.host !== db._repo.repoInfo_.host\n ) {\n fatal(\n 'refFromURL' +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n db._repo.repoInfo_.host +\n ')'\n );\n }\n\n return ref(db, parsedURL.path.toString());\n}\n/**\n * Gets a `Reference` for the location at the specified relative path.\n *\n * The relative path can either be a simple child name (for example, \"ada\") or\n * a deeper slash-separated path (for example, \"ada/name/first\").\n *\n * @param parent - The parent location.\n * @param path - A relative path from this location to the desired child\n * location.\n * @returns The specified child location.\n */\nexport function child(\n parent: DatabaseReference,\n path: string\n): DatabaseReference {\n parent = getModularInstance(parent);\n if (pathGetFront(parent._path) === null) {\n validateRootPathString('child', 'path', path, false);\n } else {\n validatePathString('child', 'path', path, false);\n }\n return new ReferenceImpl(parent._repo, pathChild(parent._path, path));\n}\n\n/**\n * Returns an `OnDisconnect` object - see\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information on how to use it.\n *\n * @param ref - The reference to add OnDisconnect triggers for.\n */\nexport function onDisconnect(ref: DatabaseReference): OnDisconnect {\n ref = getModularInstance(ref) as ReferenceImpl;\n return new OnDisconnect(ref._repo, ref._path);\n}\n\nexport interface ThenableReferenceImpl\n extends ReferenceImpl,\n Pick, 'then' | 'catch'> {\n key: string;\n parent: ReferenceImpl;\n}\n\n/**\n * Generates a new child location using a unique key and returns its\n * `Reference`.\n *\n * This is the most common pattern for adding data to a collection of items.\n *\n * If you provide a value to `push()`, the value is written to the\n * generated location. If you don't pass a value, nothing is written to the\n * database and the child remains empty (but you can use the `Reference`\n * elsewhere).\n *\n * The unique keys generated by `push()` are ordered by the current time, so the\n * resulting list of items is chronologically sorted. The keys are also\n * designed to be unguessable (they contain 72 random bits of entropy).\n *\n * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.\n * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.\n *\n * @param parent - The parent location.\n * @param value - Optional value to be written at the generated location.\n * @returns Combined `Promise` and `Reference`; resolves when write is complete,\n * but can be used immediately as the `Reference` to the child location.\n */\nexport function push(\n parent: DatabaseReference,\n value?: unknown\n): ThenableReference {\n parent = getModularInstance(parent);\n validateWritablePath('push', parent._path);\n validateFirebaseDataArg('push', value, parent._path, true);\n const now = repoServerTime(parent._repo);\n const name = nextPushId(now);\n\n // push() returns a ThennableReference whose promise is fulfilled with a\n // regular Reference. We use child() to create handles to two different\n // references. The first is turned into a ThennableReference below by adding\n // then() and catch() methods and is used as the return value of push(). The\n // second remains a regular Reference and is used as the fulfilled value of\n // the first ThennableReference.\n const thenablePushRef: Partial = child(\n parent,\n name\n ) as ReferenceImpl;\n const pushRef = child(parent, name) as ReferenceImpl;\n\n let promise: Promise;\n if (value != null) {\n promise = set(pushRef, value).then(() => pushRef);\n } else {\n promise = Promise.resolve(pushRef);\n }\n\n thenablePushRef.then = promise.then.bind(promise);\n thenablePushRef.catch = promise.then.bind(promise, undefined);\n return thenablePushRef as ThenableReferenceImpl;\n}\n\n/**\n * Removes the data at this Database location.\n *\n * Any data at child locations will also be deleted.\n *\n * The effect of the remove will be visible immediately and the corresponding\n * event 'value' will be triggered. Synchronization of the remove to the\n * Firebase servers will also be started, and the returned Promise will resolve\n * when complete. If provided, the onComplete callback will be called\n * asynchronously after synchronization has finished.\n *\n * @param ref - The location to remove.\n * @returns Resolves when remove on server is complete.\n */\nexport function remove(ref: DatabaseReference): Promise {\n validateWritablePath('remove', ref._path);\n return set(ref, null);\n}\n\n/**\n * Writes data to this Database location.\n *\n * This will overwrite any data at this location and all child locations.\n *\n * The effect of the write will be visible immediately, and the corresponding\n * events (\"value\", \"child_added\", etc.) will be triggered. Synchronization of\n * the data to the Firebase servers will also be started, and the returned\n * Promise will resolve when complete. If provided, the `onComplete` callback\n * will be called asynchronously after synchronization has finished.\n *\n * Passing `null` for the new value is equivalent to calling `remove()`; namely,\n * all data at this location and all child locations will be deleted.\n *\n * `set()` will remove any priority stored at this location, so if priority is\n * meant to be preserved, you need to use `setWithPriority()` instead.\n *\n * Note that modifying data with `set()` will cancel any pending transactions\n * at that location, so extreme care should be taken if mixing `set()` and\n * `transaction()` to modify the same data.\n *\n * A single `set()` will generate a single \"value\" event at the location where\n * the `set()` was performed.\n *\n * @param ref - The location to write to.\n * @param value - The value to be written (string, number, boolean, object,\n * array, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function set(ref: DatabaseReference, value: unknown): Promise {\n ref = getModularInstance(ref);\n validateWritablePath('set', ref._path);\n validateFirebaseDataArg('set', value, ref._path, false);\n const deferred = new Deferred();\n repoSetWithPriority(\n ref._repo,\n ref._path,\n value,\n /*priority=*/ null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Sets a priority for the data at this Database location.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\n * ).\n *\n * @param ref - The location to write to.\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function setPriority(\n ref: DatabaseReference,\n priority: string | number | null\n): Promise {\n ref = getModularInstance(ref);\n validateWritablePath('setPriority', ref._path);\n validatePriority('setPriority', priority, false);\n const deferred = new Deferred();\n repoSetWithPriority(\n ref._repo,\n pathChild(ref._path, '.priority'),\n priority,\n null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Writes data the Database location. Like `set()` but also specifies the\n * priority for that data.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\n * ).\n *\n * @param ref - The location to write to.\n * @param value - The value to be written (string, number, boolean, object,\n * array, or null).\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function setWithPriority(\n ref: DatabaseReference,\n value: unknown,\n priority: string | number | null\n): Promise {\n validateWritablePath('setWithPriority', ref._path);\n validateFirebaseDataArg('setWithPriority', value, ref._path, false);\n validatePriority('setWithPriority', priority, false);\n if (ref.key === '.length' || ref.key === '.keys') {\n throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';\n }\n\n const deferred = new Deferred();\n repoSetWithPriority(\n ref._repo,\n ref._path,\n value,\n priority,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Writes multiple values to the Database at once.\n *\n * The `values` argument contains multiple property-value pairs that will be\n * written to the Database together. Each child property can either be a simple\n * property (for example, \"name\") or a relative path (for example,\n * \"name/first\") from the current location to the data to update.\n *\n * As opposed to the `set()` method, `update()` can be use to selectively update\n * only the referenced properties at the current location (instead of replacing\n * all the child properties at the current location).\n *\n * The effect of the write will be visible immediately, and the corresponding\n * events ('value', 'child_added', etc.) will be triggered. Synchronization of\n * the data to the Firebase servers will also be started, and the returned\n * Promise will resolve when complete. If provided, the `onComplete` callback\n * will be called asynchronously after synchronization has finished.\n *\n * A single `update()` will generate a single \"value\" event at the location\n * where the `update()` was performed, regardless of how many children were\n * modified.\n *\n * Note that modifying data with `update()` will cancel any pending\n * transactions at that location, so extreme care should be taken if mixing\n * `update()` and `transaction()` to modify the same data.\n *\n * Passing `null` to `update()` will remove the data at this location.\n *\n * See\n * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.\n *\n * @param ref - The location to write to.\n * @param values - Object containing multiple values.\n * @returns Resolves when update on server is complete.\n */\nexport function update(ref: DatabaseReference, values: object): Promise {\n validateFirebaseMergeDataArg('update', values, ref._path, false);\n const deferred = new Deferred();\n repoUpdate(\n ref._repo,\n ref._path,\n values as Record,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Gets the most up-to-date result for this query.\n *\n * @param query - The query to run.\n * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is\n * available, or rejects if the client is unable to return a value (e.g., if the\n * server is unreachable and there is nothing cached).\n */\nexport function get(query: Query): Promise {\n query = getModularInstance(query) as QueryImpl;\n const callbackContext = new CallbackContext(() => {});\n const container = new ValueEventRegistration(callbackContext);\n return repoGetValue(query._repo, query, container).then(node => {\n return new DataSnapshot(\n node,\n new ReferenceImpl(query._repo, query._path),\n query._queryParams.getIndex()\n );\n });\n}\n/**\n * Represents registration for 'value' events.\n */\nexport class ValueEventRegistration implements EventRegistration {\n constructor(private callbackContext: CallbackContext) {}\n\n respondsTo(eventType: string): boolean {\n return eventType === 'value';\n }\n\n createEvent(change: Change, query: QueryContext): DataEvent {\n const index = query._queryParams.getIndex();\n return new DataEvent(\n 'value',\n this,\n new DataSnapshot(\n change.snapshotNode,\n new ReferenceImpl(query._repo, query._path),\n index\n )\n );\n }\n\n getEventRunner(eventData: CancelEvent | DataEvent): () => void {\n if (eventData.getEventType() === 'cancel') {\n return () =>\n this.callbackContext.onCancel((eventData as CancelEvent).error);\n } else {\n return () =>\n this.callbackContext.onValue((eventData as DataEvent).snapshot, null);\n }\n }\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null {\n if (this.callbackContext.hasCancelCallback) {\n return new CancelEvent(this, error, path);\n } else {\n return null;\n }\n }\n\n matches(other: EventRegistration): boolean {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n } else if (!other.callbackContext || !this.callbackContext) {\n // If no callback specified, we consider it to match any callback.\n return true;\n } else {\n return other.callbackContext.matches(this.callbackContext);\n }\n }\n\n hasAnyCallback(): boolean {\n return this.callbackContext !== null;\n }\n}\n\n/**\n * Represents the registration of a child_x event.\n */\nexport class ChildEventRegistration implements EventRegistration {\n constructor(\n private eventType: string,\n private callbackContext: CallbackContext | null\n ) {}\n\n respondsTo(eventType: string): boolean {\n let eventToCheck =\n eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck =\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return this.eventType === eventToCheck;\n }\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null {\n if (this.callbackContext.hasCancelCallback) {\n return new CancelEvent(this, error, path);\n } else {\n return null;\n }\n }\n\n createEvent(change: Change, query: QueryContext): DataEvent {\n assert(change.childName != null, 'Child events should have a childName.');\n const childRef = child(\n new ReferenceImpl(query._repo, query._path),\n change.childName\n );\n const index = query._queryParams.getIndex();\n return new DataEvent(\n change.type as EventType,\n this,\n new DataSnapshot(change.snapshotNode, childRef, index),\n change.prevName\n );\n }\n\n getEventRunner(eventData: CancelEvent | DataEvent): () => void {\n if (eventData.getEventType() === 'cancel') {\n return () =>\n this.callbackContext.onCancel((eventData as CancelEvent).error);\n } else {\n return () =>\n this.callbackContext.onValue(\n (eventData as DataEvent).snapshot,\n (eventData as DataEvent).prevName\n );\n }\n }\n\n matches(other: EventRegistration): boolean {\n if (other instanceof ChildEventRegistration) {\n return (\n this.eventType === other.eventType &&\n (!this.callbackContext ||\n !other.callbackContext ||\n this.callbackContext.matches(other.callbackContext))\n );\n }\n\n return false;\n }\n\n hasAnyCallback(): boolean {\n return !!this.callbackContext;\n }\n}\n\nfunction addEventListener(\n query: Query,\n eventType: EventType,\n callback: UserCallback,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n) {\n let cancelCallback: ((error: Error) => unknown) | undefined;\n if (typeof cancelCallbackOrListenOptions === 'object') {\n cancelCallback = undefined;\n options = cancelCallbackOrListenOptions;\n }\n if (typeof cancelCallbackOrListenOptions === 'function') {\n cancelCallback = cancelCallbackOrListenOptions;\n }\n\n if (options && options.onlyOnce) {\n const userCallback = callback;\n const onceCallback: UserCallback = (dataSnapshot, previousChildName) => {\n repoRemoveEventCallbackForQuery(query._repo, query, container);\n userCallback(dataSnapshot, previousChildName);\n };\n onceCallback.userCallback = callback.userCallback;\n onceCallback.context = callback.context;\n callback = onceCallback;\n }\n\n const callbackContext = new CallbackContext(\n callback,\n cancelCallback || undefined\n );\n const container =\n eventType === 'value'\n ? new ValueEventRegistration(callbackContext)\n : new ChildEventRegistration(eventType, callbackContext);\n repoAddEventCallbackForQuery(query._repo, query, container);\n return () => repoRemoveEventCallbackForQuery(query._repo, query, container);\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'value',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName?: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_added',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_changed',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_moved',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_removed',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\nexport { EventType };\n\n/**\n * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.\n * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from\n * the respective `on*` callbacks.\n *\n * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener\n * will not automatically remove listeners registered on child nodes, `off()`\n * must also be called on any child listeners to remove the callback.\n *\n * If a callback is not specified, all callbacks for the specified eventType\n * will be removed. Similarly, if no eventType is specified, all callbacks\n * for the `Reference` will be removed.\n *\n * Individual listeners can also be removed by invoking their unsubscribe\n * callbacks.\n *\n * @param query - The query that the listener was registered with.\n * @param eventType - One of the following strings: \"value\", \"child_added\",\n * \"child_changed\", \"child_removed\", or \"child_moved.\" If omitted, all callbacks\n * for the `Reference` will be removed.\n * @param callback - The callback function that was passed to `on()` or\n * `undefined` to remove all callbacks.\n */\nexport function off(\n query: Query,\n eventType?: EventType,\n callback?: (\n snapshot: DataSnapshot,\n previousChildName?: string | null\n ) => unknown\n): void {\n let container: EventRegistration | null = null;\n const expCallback = callback ? new CallbackContext(callback) : null;\n if (eventType === 'value') {\n container = new ValueEventRegistration(expCallback);\n } else if (eventType) {\n container = new ChildEventRegistration(eventType, expCallback);\n }\n repoRemoveEventCallbackForQuery(query._repo, query, container);\n}\n\n/** Describes the different query constraints available in this SDK. */\nexport type QueryConstraintType =\n | 'endAt'\n | 'endBefore'\n | 'startAt'\n | 'startAfter'\n | 'limitToFirst'\n | 'limitToLast'\n | 'orderByChild'\n | 'orderByKey'\n | 'orderByPriority'\n | 'orderByValue'\n | 'equalTo';\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Database query. `QueryConstraint`s are created by invoking {@link endAt},\n * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link\n * limitToFirst}, {@link limitToLast}, {@link orderByChild},\n * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,\n * {@link orderByValue} or {@link equalTo} and\n * can then be passed to {@link query} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nexport abstract class QueryConstraint {\n /** The type of this query constraints */\n abstract readonly type: QueryConstraintType;\n\n /**\n * Takes the provided `Query` and returns a copy of the `Query` with this\n * `QueryConstraint` applied.\n */\n abstract _apply(query: QueryImpl): QueryImpl;\n}\n\nclass QueryEndAtConstraint extends QueryConstraint {\n readonly type = 'endAt';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('endAt', this._value, query._path, true);\n const newParams = queryParamsEndAt(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'endAt: Starting point was already set (by another call to endAt, ' +\n 'endBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified ending point.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The ending point is inclusive, so children with exactly the specified value\n * will be included in the query. The optional key argument can be used to\n * further limit the range of the query. If it is specified, then children that\n * have exactly the specified value must also have a key name less than or equal\n * to the specified key.\n *\n * You can read more about `endAt()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to end at. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to end at, among the children with the previously\n * specified priority. This argument is only allowed if ordering by child,\n * value, or priority.\n */\nexport function endAt(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('endAt', 'key', key, true);\n return new QueryEndAtConstraint(value, key);\n}\n\nclass QueryEndBeforeConstraint extends QueryConstraint {\n readonly type = 'endBefore';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('endBefore', this._value, query._path, false);\n const newParams = queryParamsEndBefore(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'endBefore: Starting point was already set (by another call to endAt, ' +\n 'endBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified ending point (exclusive).\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The ending point is exclusive. If only a value is provided, children\n * with a value less than the specified value will be included in the query.\n * If a key is specified, then children must have a value less than or equal\n * to the specified value and a key name less than the specified key.\n *\n * @param value - The value to end before. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to end before, among the children with the\n * previously specified priority. This argument is only allowed if ordering by\n * child, value, or priority.\n */\nexport function endBefore(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('endBefore', 'key', key, true);\n return new QueryEndBeforeConstraint(value, key);\n}\n\nclass QueryStartAtConstraint extends QueryConstraint {\n readonly type = 'startAt';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('startAt', this._value, query._path, true);\n const newParams = queryParamsStartAt(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'startAt: Starting point was already set (by another call to startAt, ' +\n 'startBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified starting point.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The starting point is inclusive, so children with exactly the specified value\n * will be included in the query. The optional key argument can be used to\n * further limit the range of the query. If it is specified, then children that\n * have exactly the specified value must also have a key name greater than or\n * equal to the specified key.\n *\n * You can read more about `startAt()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to start at. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start at. This argument is only allowed if\n * ordering by child, value, or priority.\n */\nexport function startAt(\n value: number | string | boolean | null = null,\n key?: string\n): QueryConstraint {\n validateKey('startAt', 'key', key, true);\n return new QueryStartAtConstraint(value, key);\n}\n\nclass QueryStartAfterConstraint extends QueryConstraint {\n readonly type = 'startAfter';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('startAfter', this._value, query._path, false);\n const newParams = queryParamsStartAfter(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'startAfter: Starting point was already set (by another call to startAt, ' +\n 'startAfter, or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified starting point (exclusive).\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The starting point is exclusive. If only a value is provided, children\n * with a value greater than the specified value will be included in the query.\n * If a key is specified, then children must have a value greater than or equal\n * to the specified value and a a key name greater than the specified key.\n *\n * @param value - The value to start after. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start after. This argument is only allowed if\n * ordering by child, value, or priority.\n */\nexport function startAfter(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('startAfter', 'key', key, true);\n return new QueryStartAfterConstraint(value, key);\n}\n\nclass QueryLimitToFirstConstraint extends QueryConstraint {\n readonly type = 'limitToFirst';\n\n constructor(private readonly _limit: number) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n if (query._queryParams.hasLimit()) {\n throw new Error(\n 'limitToFirst: Limit was already set (by another call to limitToFirst ' +\n 'or limitToLast).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n queryParamsLimitToFirst(query._queryParams, this._limit),\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that if limited to the first specific number\n * of children.\n *\n * The `limitToFirst()` method is used to set a maximum number of children to be\n * synced for a given callback. If we set a limit of 100, we will initially only\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\n * stored in our Database, a `child_added` event will fire for each message.\n * However, if we have over 100 messages, we will only receive a `child_added`\n * event for the first 100 ordered messages. As items change, we will receive\n * `child_removed` events for each item that drops out of the active list so\n * that the total number stays at 100.\n *\n * You can read more about `limitToFirst()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param limit - The maximum number of nodes to include in this query.\n */\nexport function limitToFirst(limit: number): QueryConstraint {\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\n throw new Error('limitToFirst: First argument must be a positive integer.');\n }\n return new QueryLimitToFirstConstraint(limit);\n}\n\nclass QueryLimitToLastConstraint extends QueryConstraint {\n readonly type = 'limitToLast';\n\n constructor(private readonly _limit: number) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n if (query._queryParams.hasLimit()) {\n throw new Error(\n 'limitToLast: Limit was already set (by another call to limitToFirst ' +\n 'or limitToLast).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n queryParamsLimitToLast(query._queryParams, this._limit),\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that is limited to return only the last\n * specified number of children.\n *\n * The `limitToLast()` method is used to set a maximum number of children to be\n * synced for a given callback. If we set a limit of 100, we will initially only\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\n * stored in our Database, a `child_added` event will fire for each message.\n * However, if we have over 100 messages, we will only receive a `child_added`\n * event for the last 100 ordered messages. As items change, we will receive\n * `child_removed` events for each item that drops out of the active list so\n * that the total number stays at 100.\n *\n * You can read more about `limitToLast()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param limit - The maximum number of nodes to include in this query.\n */\nexport function limitToLast(limit: number): QueryConstraint {\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\n throw new Error('limitToLast: First argument must be a positive integer.');\n }\n\n return new QueryLimitToLastConstraint(limit);\n}\n\nclass QueryOrderByChildConstraint extends QueryConstraint {\n readonly type = 'orderByChild';\n\n constructor(private readonly _path: string) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByChild');\n const parsedPath = new Path(this._path);\n if (pathIsEmpty(parsedPath)) {\n throw new Error(\n 'orderByChild: cannot pass in empty path. Use orderByValue() instead.'\n );\n }\n const index = new PathIndex(parsedPath);\n const newParams = queryParamsOrderBy(query._queryParams, index);\n validateQueryEndpoints(newParams);\n\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by the specified child key.\n *\n * Queries can only order by one key at a time. Calling `orderByChild()`\n * multiple times on the same query is an error.\n *\n * Firebase queries allow you to order your data by any child key on the fly.\n * However, if you know in advance what your indexes will be, you can define\n * them via the .indexOn rule in your Security Rules for better performance. See\n * the{@link https://firebase.google.com/docs/database/security/indexing-data}\n * rule for more information.\n *\n * You can read more about `orderByChild()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n *\n * @param path - The path to order by.\n */\nexport function orderByChild(path: string): QueryConstraint {\n if (path === '$key') {\n throw new Error(\n 'orderByChild: \"$key\" is invalid. Use orderByKey() instead.'\n );\n } else if (path === '$priority') {\n throw new Error(\n 'orderByChild: \"$priority\" is invalid. Use orderByPriority() instead.'\n );\n } else if (path === '$value') {\n throw new Error(\n 'orderByChild: \"$value\" is invalid. Use orderByValue() instead.'\n );\n }\n validatePathString('orderByChild', 'path', path, false);\n return new QueryOrderByChildConstraint(path);\n}\n\nclass QueryOrderByKeyConstraint extends QueryConstraint {\n readonly type = 'orderByKey';\n\n _apply(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByKey');\n const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by the key.\n *\n * Sorts the results of a query by their (ascending) key values.\n *\n * You can read more about `orderByKey()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n */\nexport function orderByKey(): QueryConstraint {\n return new QueryOrderByKeyConstraint();\n}\n\nclass QueryOrderByPriorityConstraint extends QueryConstraint {\n readonly type = 'orderByPriority';\n\n _apply(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByPriority');\n const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by priority.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}\n * for alternatives to priority.\n */\nexport function orderByPriority(): QueryConstraint {\n return new QueryOrderByPriorityConstraint();\n}\n\nclass QueryOrderByValueConstraint extends QueryConstraint {\n readonly type = 'orderByValue';\n\n _apply(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByValue');\n const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by value.\n *\n * If the children of a query are all scalar values (string, number, or\n * boolean), you can order the results by their (ascending) values.\n *\n * You can read more about `orderByValue()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n */\nexport function orderByValue(): QueryConstraint {\n return new QueryOrderByValueConstraint();\n}\n\nclass QueryEqualToValueConstraint extends QueryConstraint {\n readonly type = 'equalTo';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('equalTo', this._value, query._path, false);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'equalTo: Starting point was already set (by another call to startAt/startAfter or ' +\n 'equalTo).'\n );\n }\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'equalTo: Ending point was already set (by another call to endAt/endBefore or ' +\n 'equalTo).'\n );\n }\n return new QueryEndAtConstraint(this._value, this._key)._apply(\n new QueryStartAtConstraint(this._value, this._key)._apply(query)\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` that includes children that match the specified\n * value.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The optional key argument can be used to further limit the range of the\n * query. If it is specified, then children that have exactly the specified\n * value must also have exactly the specified key as their key name. This can be\n * used to filter result sets with many matches for the same value.\n *\n * You can read more about `equalTo()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to match for. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start at, among the children with the\n * previously specified priority. This argument is only allowed if ordering by\n * child, value, or priority.\n */\nexport function equalTo(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('equalTo', 'key', key, true);\n return new QueryEqualToValueConstraint(value, key);\n}\n\n/**\n * Creates a new immutable instance of `Query` that is extended to also include\n * additional query constraints.\n *\n * @param query - The Query instance to use as a base for the new constraints.\n * @param queryConstraints - The list of `QueryConstraint`s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query(\n query: Query,\n ...queryConstraints: QueryConstraint[]\n): Query {\n let queryImpl = getModularInstance(query) as QueryImpl;\n for (const constraint of queryConstraints) {\n queryImpl = constraint._apply(queryImpl);\n }\n return queryImpl;\n}\n\n/**\n * Define reference constructor in various modules\n *\n * We are doing this here to avoid several circular\n * dependency issues\n */\nsyncPointSetReferenceConstructor(ReferenceImpl);\nsyncTreeSetReferenceConstructor(ReferenceImpl);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _FirebaseService,\n _getProvider,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\nimport {\n getModularInstance,\n createMockUserToken,\n deepEqual,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\n} from '@firebase/util';\n\nimport { AppCheckTokenProvider } from '../core/AppCheckTokenProvider';\nimport {\n AuthTokenProvider,\n EmulatorTokenProvider,\n FirebaseAuthTokenProvider\n} from '../core/AuthTokenProvider';\nimport { Repo, repoInterrupt, repoResume, repoStart } from '../core/Repo';\nimport { RepoInfo, RepoInfoEmulatorOptions } from '../core/RepoInfo';\nimport { parseRepoInfo } from '../core/util/libs/parser';\nimport { newEmptyPath, pathIsEmpty } from '../core/util/Path';\nimport {\n warn,\n fatal,\n log,\n enableLogging as enableLoggingImpl\n} from '../core/util/util';\nimport { validateUrl } from '../core/util/validation';\nimport { BrowserPollConnection } from '../realtime/BrowserPollConnection';\nimport { TransportManager } from '../realtime/TransportManager';\nimport { WebSocketConnection } from '../realtime/WebSocketConnection';\n\nimport { ReferenceImpl } from './Reference_impl';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n/**\n * This variable is also defined in the firebase Node.js Admin SDK. Before\n * modifying this definition, consult the definition in:\n *\n * https://github.com/firebase/firebase-admin-node\n *\n * and make sure the two are consistent.\n */\nconst FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';\n\n/**\n * Creates and caches `Repo` instances.\n */\nconst repos: {\n [appName: string]: {\n [dbUrl: string]: Repo;\n };\n} = {};\n\n/**\n * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).\n */\nlet useRestClient = false;\n\n/**\n * Update an existing `Repo` in place to point to a new host/port.\n */\nfunction repoManagerApplyEmulatorSettings(\n repo: Repo,\n hostAndPort: string,\n emulatorOptions: RepoInfoEmulatorOptions,\n tokenProvider?: AuthTokenProvider\n): void {\n const portIndex = hostAndPort.lastIndexOf(':');\n const host = hostAndPort.substring(0, portIndex);\n const useSsl = isCloudWorkstation(host);\n repo.repoInfo_ = new RepoInfo(\n hostAndPort,\n /* secure= */ useSsl,\n repo.repoInfo_.namespace,\n repo.repoInfo_.webSocketOnly,\n repo.repoInfo_.nodeAdmin,\n repo.repoInfo_.persistenceKey,\n repo.repoInfo_.includeNamespaceInQueryParams,\n /*isUsingEmulator=*/ true,\n emulatorOptions\n );\n\n if (tokenProvider) {\n repo.authTokenProvider_ = tokenProvider;\n }\n}\n\n/**\n * This function should only ever be called to CREATE a new database instance.\n * @internal\n */\nexport function repoManagerDatabaseFromApp(\n app: FirebaseApp,\n authProvider: Provider,\n appCheckProvider?: Provider,\n url?: string,\n nodeAdmin?: boolean\n): Database {\n let dbUrl: string | undefined = url || app.options.databaseURL;\n if (dbUrl === undefined) {\n if (!app.options.projectId) {\n fatal(\n \"Can't determine Firebase Database URL. Be sure to include \" +\n ' a Project ID when calling firebase.initializeApp().'\n );\n }\n\n log('Using default host for project ', app.options.projectId);\n dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;\n }\n\n let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\n let repoInfo = parsedUrl.repoInfo;\n\n let isEmulator: boolean;\n\n let dbEmulatorHost: string | undefined = undefined;\n if (typeof process !== 'undefined' && process.env) {\n dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];\n }\n\n if (dbEmulatorHost) {\n isEmulator = true;\n dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;\n parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\n repoInfo = parsedUrl.repoInfo;\n } else {\n isEmulator = !parsedUrl.repoInfo.secure;\n }\n\n const authTokenProvider =\n nodeAdmin && isEmulator\n ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)\n : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);\n\n validateUrl('Invalid Firebase Database URL', parsedUrl);\n if (!pathIsEmpty(parsedUrl.path)) {\n fatal(\n 'Database URL must point to the root of a Firebase Database ' +\n '(not including a child path).'\n );\n }\n\n const repo = repoManagerCreateRepo(\n repoInfo,\n app,\n authTokenProvider,\n new AppCheckTokenProvider(app, appCheckProvider)\n );\n return new Database(repo, app);\n}\n\n/**\n * Remove the repo and make sure it is disconnected.\n *\n */\nfunction repoManagerDeleteRepo(repo: Repo, appName: string): void {\n const appRepos = repos[appName];\n // This should never happen...\n if (!appRepos || appRepos[repo.key] !== repo) {\n fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);\n }\n repoInterrupt(repo);\n delete appRepos[repo.key];\n}\n\n/**\n * Ensures a repo doesn't already exist and then creates one using the\n * provided app.\n *\n * @param repoInfo - The metadata about the Repo\n * @returns The Repo object for the specified server / repoName.\n */\nfunction repoManagerCreateRepo(\n repoInfo: RepoInfo,\n app: FirebaseApp,\n authTokenProvider: AuthTokenProvider,\n appCheckProvider: AppCheckTokenProvider\n): Repo {\n let appRepos = repos[app.name];\n\n if (!appRepos) {\n appRepos = {};\n repos[app.name] = appRepos;\n }\n\n let repo = appRepos[repoInfo.toURLString()];\n if (repo) {\n fatal(\n 'Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.'\n );\n }\n repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);\n appRepos[repoInfo.toURLString()] = repo;\n\n return repo;\n}\n\n/**\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\n */\nexport function repoManagerForceRestClient(forceRestClient: boolean): void {\n useRestClient = forceRestClient;\n}\n\n/**\n * Class representing a Firebase Realtime Database.\n */\nexport class Database implements _FirebaseService {\n /** Represents a `Database` instance. */\n readonly 'type' = 'database';\n\n /** Track if the instance has been used (root or repo accessed) */\n _instanceStarted: boolean = false;\n\n /** Backing state for root_ */\n private _rootInternal?: ReferenceImpl;\n\n /** @hideconstructor */\n constructor(\n public _repoInternal: Repo,\n /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */\n readonly app: FirebaseApp\n ) {}\n\n get _repo(): Repo {\n if (!this._instanceStarted) {\n repoStart(\n this._repoInternal,\n this.app.options.appId,\n this.app.options['databaseAuthVariableOverride']\n );\n this._instanceStarted = true;\n }\n return this._repoInternal;\n }\n\n get _root(): ReferenceImpl {\n if (!this._rootInternal) {\n this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());\n }\n return this._rootInternal;\n }\n\n _delete(): Promise {\n if (this._rootInternal !== null) {\n repoManagerDeleteRepo(this._repo, this.app.name);\n this._repoInternal = null;\n this._rootInternal = null;\n }\n return Promise.resolve();\n }\n\n _checkNotDeleted(apiName: string) {\n if (this._rootInternal === null) {\n fatal('Cannot call ' + apiName + ' on a deleted database.');\n }\n }\n}\n\nfunction checkTransportInit() {\n if (TransportManager.IS_TRANSPORT_INITIALIZED) {\n warn(\n 'Transport has already been initialized. Please call this function before calling ref or setting up a listener'\n );\n }\n}\n\n/**\n * Force the use of websockets instead of longPolling.\n */\nexport function forceWebSockets() {\n checkTransportInit();\n BrowserPollConnection.forceDisallow();\n}\n\n/**\n * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.\n */\nexport function forceLongPolling() {\n checkTransportInit();\n WebSocketConnection.forceDisallow();\n BrowserPollConnection.forceAllow();\n}\n\n/**\n * Returns the instance of the Realtime Database SDK that is associated with the provided\n * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if\n * no instance exists or if the existing instance uses a custom database URL.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime\n * Database instance is associated with.\n * @param url - The URL of the Realtime Database instance to connect to. If not\n * provided, the SDK connects to the default instance of the Firebase App.\n * @returns The `Database` instance of the provided app.\n */\nexport function getDatabase(\n app: FirebaseApp = getApp(),\n url?: string\n): Database {\n const db = _getProvider(app, 'database').getImmediate({\n identifier: url\n }) as Database;\n if (!db._instanceStarted) {\n const emulator = getDefaultEmulatorHostnameAndPort('database');\n if (emulator) {\n connectDatabaseEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * Modify the provided instance to communicate with the Realtime Database\n * emulator.\n *\n *

Note: This method must be called before performing any other operation.\n *\n * @param db - The instance to modify.\n * @param host - The emulator host (ex: localhost)\n * @param port - The emulator port (ex: 8080)\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\n */\nexport function connectDatabaseEmulator(\n db: Database,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n db = getModularInstance(db);\n db._checkNotDeleted('useEmulator');\n\n const hostAndPort = `${host}:${port}`;\n const repo = db._repoInternal;\n if (db._instanceStarted) {\n // If the instance has already been started, then silenty fail if this function is called again\n // with the same parameters. If the parameters differ then assert.\n if (\n hostAndPort === db._repoInternal.repoInfo_.host &&\n deepEqual(options, repo.repoInfo_.emulatorOptions)\n ) {\n return;\n }\n fatal(\n 'connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.'\n );\n }\n\n let tokenProvider: EmulatorTokenProvider | undefined = undefined;\n if (repo.repoInfo_.nodeAdmin) {\n if (options.mockUserToken) {\n fatal(\n 'mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the \"firebase\" package instead of \"firebase-admin\".'\n );\n }\n tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);\n } else if (options.mockUserToken) {\n const token =\n typeof options.mockUserToken === 'string'\n ? options.mockUserToken\n : createMockUserToken(options.mockUserToken, db.app.options.projectId);\n tokenProvider = new EmulatorTokenProvider(token);\n }\n\n // Workaround to get cookies in Firebase Studio\n if (isCloudWorkstation(host)) {\n void pingServer(host);\n updateEmulatorBanner('Database', true);\n }\n\n // Modify the repo to apply emulator settings\n repoManagerApplyEmulatorSettings(repo, hostAndPort, options, tokenProvider);\n}\n\n/**\n * Disconnects from the server (all Database operations will be completed\n * offline).\n *\n * The client automatically maintains a persistent connection to the Database\n * server, which will remain active indefinitely and reconnect when\n * disconnected. However, the `goOffline()` and `goOnline()` methods may be used\n * to control the client connection in cases where a persistent connection is\n * undesirable.\n *\n * While offline, the client will no longer receive data updates from the\n * Database. However, all Database operations performed locally will continue to\n * immediately fire events, allowing your application to continue behaving\n * normally. Additionally, each operation performed locally will automatically\n * be queued and retried upon reconnection to the Database server.\n *\n * To reconnect to the Database and begin receiving remote events, see\n * `goOnline()`.\n *\n * @param db - The instance to disconnect.\n */\nexport function goOffline(db: Database): void {\n db = getModularInstance(db);\n db._checkNotDeleted('goOffline');\n repoInterrupt(db._repo);\n}\n\n/**\n * Reconnects to the server and synchronizes the offline Database state\n * with the server state.\n *\n * This method should be used after disabling the active connection with\n * `goOffline()`. Once reconnected, the client will transmit the proper data\n * and fire the appropriate events so that your client \"catches up\"\n * automatically.\n *\n * @param db - The instance to reconnect.\n */\nexport function goOnline(db: Database): void {\n db = getModularInstance(db);\n db._checkNotDeleted('goOnline');\n repoResume(db._repo);\n}\n\n/**\n * Logs debugging information to the console.\n *\n * @param enabled - Enables logging if `true`, disables logging if `false`.\n * @param persistent - Remembers the logging state between page refreshes if\n * `true`.\n */\nexport function enableLogging(enabled: boolean, persistent?: boolean);\n\n/**\n * Logs debugging information to the console.\n *\n * @param logger - A custom logger function to control how things get logged.\n */\nexport function enableLogging(logger: (message: string) => unknown);\n\nexport function enableLogging(\n logger: boolean | ((message: string) => unknown),\n persistent?: boolean\n): void {\n enableLoggingImpl(logger, persistent);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { name, version } from '../package.json';\nimport { setSDKVersion } from '../src/core/version';\n\nimport { repoManagerDatabaseFromApp } from './api/Database';\n\nexport function registerDatabase(variant?: string): void {\n setSDKVersion(SDK_VERSION);\n _registerComponent(\n new Component(\n 'database',\n (container, { instanceIdentifier: url }) => {\n const app = container.getProvider('app').getImmediate()!;\n const authProvider = container.getProvider('auth-internal');\n const appCheckProvider = container.getProvider('app-check-internal');\n return repoManagerDatabaseFromApp(\n app,\n authProvider,\n appCheckProvider,\n url\n );\n },\n ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n registerVersion(name, version, variant);\n // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst SERVER_TIMESTAMP = {\n '.sv': 'timestamp'\n};\n\n/**\n * Returns a placeholder value for auto-populating the current timestamp (time\n * since the Unix epoch, in milliseconds) as determined by the Firebase\n * servers.\n */\nexport function serverTimestamp(): object {\n return SERVER_TIMESTAMP;\n}\n\n/**\n * Returns a placeholder value that can be used to atomically increment the\n * current database value by the provided delta.\n *\n * @param delta - the amount to modify the current value atomically.\n * @returns A placeholder value for modifying data atomically server-side.\n */\nexport function increment(delta: number): object {\n return {\n '.sv': {\n 'increment': delta\n }\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance, Deferred } from '@firebase/util';\n\nimport { repoStartTransaction } from '../core/Repo';\nimport { PRIORITY_INDEX } from '../core/snap/indexes/PriorityIndex';\nimport { Node } from '../core/snap/Node';\nimport { validateWritablePath } from '../core/util/validation';\n\nimport { DatabaseReference } from './Reference';\nimport { DataSnapshot, onValue, ReferenceImpl } from './Reference_impl';\n\n/** An options object to configure transactions. */\nexport interface TransactionOptions {\n /**\n * By default, events are raised each time the transaction update function\n * runs. So if it is run multiple times, you may see intermediate states. You\n * can set this to false to suppress these intermediate states and instead\n * wait until the transaction has completed before events are raised.\n */\n readonly applyLocally?: boolean;\n}\n\n/**\n * A type for the resolve value of {@link runTransaction}.\n */\nexport class TransactionResult {\n /** @hideconstructor */\n constructor(\n /** Whether the transaction was successfully committed. */\n readonly committed: boolean,\n /** The resulting data snapshot. */\n readonly snapshot: DataSnapshot\n ) {}\n\n /** Returns a JSON-serializable representation of this object. */\n toJSON(): object {\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n }\n}\n\n/**\n * Atomically modifies the data at this location.\n *\n * Atomically modify the data at this location. Unlike a normal `set()`, which\n * just overwrites the data regardless of its previous value, `runTransaction()` is\n * used to modify the existing value to a new value, ensuring there are no\n * conflicts with other clients writing to the same location at the same time.\n *\n * To accomplish this, you pass `runTransaction()` an update function which is\n * used to transform the current value into a new value. If another client\n * writes to the location before your new value is successfully written, your\n * update function will be called again with the new current value, and the\n * write will be retried. This will happen repeatedly until your write succeeds\n * without conflict or you abort the transaction by not returning a value from\n * your update function.\n *\n * Note: Modifying data with `set()` will cancel any pending transactions at\n * that location, so extreme care should be taken if mixing `set()` and\n * `runTransaction()` to update the same data.\n *\n * Note: When using transactions with Security and Firebase Rules in place, be\n * aware that a client needs `.read` access in addition to `.write` access in\n * order to perform a transaction. This is because the client-side nature of\n * transactions requires the client to read the data in order to transactionally\n * update it.\n *\n * @param ref - The location to atomically modify.\n * @param transactionUpdate - A developer-supplied function which will be passed\n * the current data stored at this location (as a JavaScript object). The\n * function should return the new value it would like written (as a JavaScript\n * object). If `undefined` is returned (i.e. you return with no arguments) the\n * transaction will be aborted and the data at this location will not be\n * modified.\n * @param options - An options object to configure transactions.\n * @returns A `Promise` that can optionally be used instead of the `onComplete`\n * callback to handle success and failure.\n */\nexport function runTransaction(\n ref: DatabaseReference,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n transactionUpdate: (currentData: any) => unknown,\n options?: TransactionOptions\n): Promise {\n ref = getModularInstance(ref);\n\n validateWritablePath('Reference.transaction', ref._path);\n\n if (ref.key === '.length' || ref.key === '.keys') {\n throw (\n 'Reference.transaction failed: ' + ref.key + ' is a read-only object.'\n );\n }\n\n const applyLocally = options?.applyLocally ?? true;\n const deferred = new Deferred();\n\n const promiseComplete = (\n error: Error | null,\n committed: boolean,\n node: Node | null\n ) => {\n let dataSnapshot: DataSnapshot | null = null;\n if (error) {\n deferred.reject(error);\n } else {\n dataSnapshot = new DataSnapshot(\n node,\n new ReferenceImpl(ref._repo, ref._path),\n PRIORITY_INDEX\n );\n deferred.resolve(new TransactionResult(committed, dataSnapshot));\n }\n };\n\n // Add a watch to make sure we get server updates.\n const unwatcher = onValue(ref, () => {});\n\n repoStartTransaction(\n ref._repo,\n ref._path,\n transactionUpdate,\n promiseComplete,\n unwatcher,\n applyLocally\n );\n\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PersistentConnection } from '../core/PersistentConnection';\nimport { RepoInfo } from '../core/RepoInfo';\nimport { Connection } from '../realtime/Connection';\n\nimport { repoManagerForceRestClient } from './Database';\n\nexport const DataConnection = PersistentConnection;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(PersistentConnection.prototype as any).simpleListen = function (\n pathString: string,\n onComplete: (a: unknown) => void\n) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(PersistentConnection.prototype as any).echo = function (\n data: unknown,\n onEcho: (a: unknown) => void\n) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n\n// RealTimeConnection properties that we use in tests.\nexport const RealTimeConnection = Connection;\n\n/**\n * @internal\n */\nexport const hijackHash = function (newHash: () => string) {\n const oldPut = PersistentConnection.prototype.put;\n PersistentConnection.prototype.put = function (\n pathString,\n data,\n onComplete,\n hash\n ) {\n if (hash !== undefined) {\n hash = newHash();\n }\n oldPut.call(this, pathString, data, onComplete, hash);\n };\n return function () {\n PersistentConnection.prototype.put = oldPut;\n };\n};\n\nexport const ConnectionTarget = RepoInfo;\n\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n * @internal\n */\nexport const forceRestClient = function (forceRestClient: boolean) {\n repoManagerForceRestClient(forceRestClient);\n};\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebaseAppCheckInternal,\n AppCheckInternalComponentName\n} from '@firebase/app-check-interop-types';\nimport { FirebaseApp } from '@firebase/app-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n Provider\n} from '@firebase/component';\n\nimport { repoManagerDatabaseFromApp } from '../api/Database';\nimport { Database } from '../api.standalone';\nimport { setSDKVersion } from '../core/version';\n\n/**\n * Used by console to create a database based on the app,\n * passed database URL and a custom auth implementation.\n * @internal\n * @param app - A valid FirebaseApp-like object\n * @param url - A valid Firebase databaseURL\n * @param version - custom version e.g. firebase-admin version\n * @param customAppCheckImpl - custom app check implementation\n * @param customAuthImpl - custom auth implementation\n */\nexport function _initStandalone({\n app,\n url,\n version,\n customAuthImpl,\n customAppCheckImpl,\n nodeAdmin = false\n}: {\n app: FirebaseApp;\n url: string;\n version: string;\n customAuthImpl: FirebaseAuthInternal;\n customAppCheckImpl?: FirebaseAppCheckInternal;\n nodeAdmin?: boolean;\n}): Database {\n setSDKVersion(version);\n\n /**\n * ComponentContainer('database-standalone') is just a placeholder that doesn't perform\n * any actual function.\n */\n const componentContainer = new ComponentContainer('database-standalone');\n const authProvider = new Provider(\n 'auth-internal',\n componentContainer\n );\n let appCheckProvider: Provider;\n if (customAppCheckImpl) {\n appCheckProvider = new Provider(\n 'app-check-internal',\n componentContainer\n );\n appCheckProvider.setComponent(\n new Component(\n 'app-check-internal',\n () => customAppCheckImpl,\n ComponentType.PRIVATE\n )\n );\n }\n authProvider.setComponent(\n new Component('auth-internal', () => customAuthImpl, ComponentType.PRIVATE)\n );\n\n return repoManagerDatabaseFromApp(\n app,\n authProvider,\n appCheckProvider,\n url,\n nodeAdmin\n );\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Use default import to import a cjs library, so we can provide a esm entrypoint for Nodejs.\n// We can't use named import here because otherwise you will get the following error:\n// \"SyntaxError: Named export 'Client' not found. The requested module 'faye-websocket' is a CommonJS module\".\n// We can change back to using named imports once the lib provides an esm build, however they are not planning to.\n// see https://github.com/faye/faye-websocket-node/issues/82\nimport Websocket from 'faye-websocket';\n\nimport { setWebSocketImpl } from '../src/realtime/WebSocketConnection';\n\nimport { registerDatabase } from './register';\n\nsetWebSocketImpl(Websocket.Client);\n\nexport * from './api';\n\nregisterDatabase('node');\n"],"names":["stringify","jsonEval","contains","Logger","stringToByteArray","Sha1","base64","enableLogging","assert","LogLevel","isNodeSdk","deepCopy","app","_isFirebaseServerApp","base64Encode","isMobileCordova","stringLength","Deferred","safeGet","isAdmin","isValidFormat","isEmpty","isReactNative","assertionError","MAX_NODE","setMaxNode","nodeFromJSON","map","setPriorityMaxNode","querystring","referenceConstructor","errorPrefixFxn","getModularInstance","isCloudWorkstation","getApp","_getProvider","getDefaultEmulatorHostnameAndPort","deepEqual","createMockUserToken","pingServer","updateEmulatorBanner","enableLoggingImpl","SDK_VERSION","_registerComponent","Component","registerVersion","ComponentContainer","Provider","Websocket"],"mappings":";;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;AAeG;AAEI,MAAM,gBAAgB,GAA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X,oBAAoB,EACpB,MAAM,kBAAkB,EAAA,SAAA,6BAEzB,CACF,CAAC;KACH;AACD,IAAA,YAAY,CAAC,YAAY,CACvB,IAAIA,mBAAS,CAAC,eAAe,EAAE,MAAM,cAAc,EAAA,SAAA,6BAAwB,CAC5E,CAAC;AAEF,IAAA,OAAO,0BAA0B,CAC/B,GAAG,EACH,YAAY,EACZ,gBAAgB,EAChB,GAAG,EACH,SAAS,CACV,CAAC;AACJ;;AClGA;;;;;;;;;;;;;;;AAeG;AAaH,gBAAgB,CAACI,6BAAS,CAAC,MAAM,CAAC,CAAC;AAInC,gBAAgB,CAAC,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@firebase/database/dist/index.standalone.js b/node_modules/@firebase/database/dist/index.standalone.js new file mode 100644 index 0000000..218af6a --- /dev/null +++ b/node_modules/@firebase/database/dist/index.standalone.js @@ -0,0 +1,14052 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var Websocket = require('faye-websocket'); +var util = require('@firebase/util'); +var logger$1 = require('@firebase/logger'); +var app = require('@firebase/app'); +var component = require('@firebase/component'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var Websocket__default = /*#__PURE__*/_interopDefaultLegacy(Websocket); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const PROTOCOL_VERSION = '5'; +const VERSION_PARAM = 'v'; +const TRANSPORT_SESSION_PARAM = 's'; +const REFERER_PARAM = 'r'; +const FORGE_REF = 'f'; +// Matches console.firebase.google.com, firebase-console-*.corp.google.com and +// firebase.corp.google.com +const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/; +const LAST_SESSION_PARAM = 'ls'; +const APPLICATION_ID_PARAM = 'p'; +const APP_CHECK_TOKEN_PARAM = 'ac'; +const WEBSOCKET = 'websocket'; +const LONG_POLLING = 'long_polling'; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Wraps a DOM Storage object and: + * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types. + * - prefixes names with "firebase:" to avoid collisions with app data. + * + * We automatically (see storage.js) create two such wrappers, one for sessionStorage, + * and one for localStorage. + * + */ +class DOMStorageWrapper { + /** + * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage) + */ + constructor(domStorage_) { + this.domStorage_ = domStorage_; + // Use a prefix to avoid collisions with other stuff saved by the app. + this.prefix_ = 'firebase:'; + } + /** + * @param key - The key to save the value under + * @param value - The value being stored, or null to remove the key. + */ + set(key, value) { + if (value == null) { + this.domStorage_.removeItem(this.prefixedName_(key)); + } + else { + this.domStorage_.setItem(this.prefixedName_(key), util.stringify(value)); + } + } + /** + * @returns The value that was stored under this key, or null + */ + get(key) { + const storedVal = this.domStorage_.getItem(this.prefixedName_(key)); + if (storedVal == null) { + return null; + } + else { + return util.jsonEval(storedVal); + } + } + remove(key) { + this.domStorage_.removeItem(this.prefixedName_(key)); + } + prefixedName_(name) { + return this.prefix_ + name; + } + toString() { + return this.domStorage_.toString(); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory storage implementation that matches the API of DOMStorageWrapper + * (TODO: create interface for both to implement). + */ +class MemoryStorage { + constructor() { + this.cache_ = {}; + this.isInMemoryStorage = true; + } + set(key, value) { + if (value == null) { + delete this.cache_[key]; + } + else { + this.cache_[key] = value; + } + } + get(key) { + if (util.contains(this.cache_, key)) { + return this.cache_[key]; + } + return null; + } + remove(key) { + delete this.cache_[key]; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage. + * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change + * to reflect this type + * + * @param domStorageName - Name of the underlying storage object + * (e.g. 'localStorage' or 'sessionStorage'). + * @returns Turning off type information until a common interface is defined. + */ +const createStoragefor = function (domStorageName) { + try { + // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception, + // so it must be inside the try/catch. + if (typeof window !== 'undefined' && + typeof window[domStorageName] !== 'undefined') { + // Need to test cache. Just because it's here doesn't mean it works + const domStorage = window[domStorageName]; + domStorage.setItem('firebase:sentinel', 'cache'); + domStorage.removeItem('firebase:sentinel'); + return new DOMStorageWrapper(domStorage); + } + } + catch (e) { } + // Failed to create wrapper. Just return in-memory storage. + // TODO: log? + return new MemoryStorage(); +}; +/** A storage object that lasts across sessions */ +const PersistentStorage = createStoragefor('localStorage'); +/** A storage object that only lasts one session */ +const SessionStorage = createStoragefor('sessionStorage'); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const logClient = new logger$1.Logger('@firebase/database'); +/** + * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called). + */ +const LUIDGenerator = (function () { + let id = 1; + return function () { + return id++; + }; +})(); +/** + * Sha1 hash of the input string + * @param str - The string to hash + * @returns {!string} The resulting hash + */ +const sha1 = function (str) { + const utf8Bytes = util.stringToByteArray(str); + const sha1 = new util.Sha1(); + sha1.update(utf8Bytes); + const sha1Bytes = sha1.digest(); + return util.base64.encodeByteArray(sha1Bytes); +}; +const buildLogMessage_ = function (...varArgs) { + let message = ''; + for (let i = 0; i < varArgs.length; i++) { + const arg = varArgs[i]; + if (Array.isArray(arg) || + (arg && + typeof arg === 'object' && + // eslint-disable-next-line @typescript-eslint/no-explicit-any + typeof arg.length === 'number')) { + message += buildLogMessage_.apply(null, arg); + } + else if (typeof arg === 'object') { + message += util.stringify(arg); + } + else { + message += arg; + } + message += ' '; + } + return message; +}; +/** + * Use this for all debug messages in Firebase. + */ +let logger = null; +/** + * Flag to check for log availability on first log message + */ +let firstLog_ = true; +/** + * The implementation of Firebase.enableLogging (defined here to break dependencies) + * @param logger_ - A flag to turn on logging, or a custom logger + * @param persistent - Whether or not to persist logging settings across refreshes + */ +const enableLogging$1 = function (logger_, persistent) { + util.assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently."); + if (logger_ === true) { + logClient.logLevel = logger$1.LogLevel.VERBOSE; + logger = logClient.log.bind(logClient); + if (persistent) { + SessionStorage.set('logging_enabled', true); + } + } + else if (typeof logger_ === 'function') { + logger = logger_; + } + else { + logger = null; + SessionStorage.remove('logging_enabled'); + } +}; +const log = function (...varArgs) { + if (firstLog_ === true) { + firstLog_ = false; + if (logger === null && SessionStorage.get('logging_enabled') === true) { + enableLogging$1(true); + } + } + if (logger) { + const message = buildLogMessage_.apply(null, varArgs); + logger(message); + } +}; +const logWrapper = function (prefix) { + return function (...varArgs) { + log(prefix, ...varArgs); + }; +}; +const error = function (...varArgs) { + const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs); + logClient.error(message); +}; +const fatal = function (...varArgs) { + const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`; + logClient.error(message); + throw new Error(message); +}; +const warn = function (...varArgs) { + const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs); + logClient.warn(message); +}; +/** + * Logs a warning if the containing page uses https. Called when a call to new Firebase + * does not use https. + */ +const warnIfPageIsSecure = function () { + // Be very careful accessing browser globals. Who knows what may or may not exist. + if (typeof window !== 'undefined' && + window.location && + window.location.protocol && + window.location.protocol.indexOf('https:') !== -1) { + warn('Insecure Firebase access from a secure page. ' + + 'Please use https in calls to new Firebase().'); + } +}; +/** + * Returns true if data is NaN, or +/- Infinity. + */ +const isInvalidJSONNumber = function (data) { + return (typeof data === 'number' && + (data !== data || // NaN + data === Number.POSITIVE_INFINITY || + data === Number.NEGATIVE_INFINITY)); +}; +const executeWhenDOMReady = function (fn) { + if (util.isNodeSdk() || document.readyState === 'complete') { + fn(); + } + else { + // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which + // fire before onload), but fall back to onload. + let called = false; + const wrappedFn = function () { + if (!document.body) { + setTimeout(wrappedFn, Math.floor(10)); + return; + } + if (!called) { + called = true; + fn(); + } + }; + if (document.addEventListener) { + document.addEventListener('DOMContentLoaded', wrappedFn, false); + // fallback to onload. + window.addEventListener('load', wrappedFn, false); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (document.attachEvent) { + // IE. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + document.attachEvent('onreadystatechange', () => { + if (document.readyState === 'complete') { + wrappedFn(); + } + }); + // fallback to onload. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + window.attachEvent('onload', wrappedFn); + // jQuery has an extra hack for IE that we could employ (based on + // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old. + // I'm hoping we don't need it. + } + } +}; +/** + * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names + */ +const MIN_NAME = '[MIN_NAME]'; +/** + * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names + */ +const MAX_NAME = '[MAX_NAME]'; +/** + * Compares valid Firebase key names, plus min and max name + */ +const nameCompare = function (a, b) { + if (a === b) { + return 0; + } + else if (a === MIN_NAME || b === MAX_NAME) { + return -1; + } + else if (b === MIN_NAME || a === MAX_NAME) { + return 1; + } + else { + const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b); + if (aAsInt !== null) { + if (bAsInt !== null) { + return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt; + } + else { + return -1; + } + } + else if (bAsInt !== null) { + return 1; + } + else { + return a < b ? -1 : 1; + } + } +}; +/** + * @returns {!number} comparison result. + */ +const stringCompare = function (a, b) { + if (a === b) { + return 0; + } + else if (a < b) { + return -1; + } + else { + return 1; + } +}; +const requireKey = function (key, obj) { + if (obj && key in obj) { + return obj[key]; + } + else { + throw new Error('Missing required key (' + key + ') in object: ' + util.stringify(obj)); + } +}; +const ObjectToUniqueKey = function (obj) { + if (typeof obj !== 'object' || obj === null) { + return util.stringify(obj); + } + const keys = []; + // eslint-disable-next-line guard-for-in + for (const k in obj) { + keys.push(k); + } + // Export as json, but with the keys sorted. + keys.sort(); + let key = '{'; + for (let i = 0; i < keys.length; i++) { + if (i !== 0) { + key += ','; + } + key += util.stringify(keys[i]); + key += ':'; + key += ObjectToUniqueKey(obj[keys[i]]); + } + key += '}'; + return key; +}; +/** + * Splits a string into a number of smaller segments of maximum size + * @param str - The string + * @param segsize - The maximum number of chars in the string. + * @returns The string, split into appropriately-sized chunks + */ +const splitStringBySize = function (str, segsize) { + const len = str.length; + if (len <= segsize) { + return [str]; + } + const dataSegs = []; + for (let c = 0; c < len; c += segsize) { + if (c + segsize > len) { + dataSegs.push(str.substring(c, len)); + } + else { + dataSegs.push(str.substring(c, c + segsize)); + } + } + return dataSegs; +}; +/** + * Apply a function to each (key, value) pair in an object or + * apply a function to each (index, value) pair in an array + * @param obj - The object or array to iterate over + * @param fn - The function to apply + */ +function each(obj, fn) { + for (const key in obj) { + if (obj.hasOwnProperty(key)) { + fn(key, obj[key]); + } + } +} +/** + * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License) + * I made one modification at the end and removed the NaN / Infinity + * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments. + * @param v - A double + * + */ +const doubleToIEEE754String = function (v) { + util.assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL + const ebits = 11, fbits = 52; + const bias = (1 << (ebits - 1)) - 1; + let s, e, f, ln, i; + // Compute sign, exponent, fraction + // Skip NaN / Infinity handling --MJL. + if (v === 0) { + e = 0; + f = 0; + s = 1 / v === -Infinity ? 1 : 0; + } + else { + s = v < 0; + v = Math.abs(v); + if (v >= Math.pow(2, 1 - bias)) { + // Normalized + ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias); + e = ln + bias; + f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits)); + } + else { + // Denormalized + e = 0; + f = Math.round(v / Math.pow(2, 1 - bias - fbits)); + } + } + // Pack sign, exponent, fraction + const bits = []; + for (i = fbits; i; i -= 1) { + bits.push(f % 2 ? 1 : 0); + f = Math.floor(f / 2); + } + for (i = ebits; i; i -= 1) { + bits.push(e % 2 ? 1 : 0); + e = Math.floor(e / 2); + } + bits.push(s ? 1 : 0); + bits.reverse(); + const str = bits.join(''); + // Return the data as a hex string. --MJL + let hexByteString = ''; + for (i = 0; i < 64; i += 8) { + let hexByte = parseInt(str.substr(i, 8), 2).toString(16); + if (hexByte.length === 1) { + hexByte = '0' + hexByte; + } + hexByteString = hexByteString + hexByte; + } + return hexByteString.toLowerCase(); +}; +/** + * Used to detect if we're in a Chrome content script (which executes in an + * isolated environment where long-polling doesn't work). + */ +const isChromeExtensionContentScript = function () { + return !!(typeof window === 'object' && + window['chrome'] && + window['chrome']['extension'] && + !/^chrome/.test(window.location.href)); +}; +/** + * Used to detect if we're in a Windows 8 Store app. + */ +const isWindowsStoreApp = function () { + // Check for the presence of a couple WinRT globals + return typeof Windows === 'object' && typeof Windows.UI === 'object'; +}; +/** + * Converts a server error code to a JavaScript Error + */ +function errorForServerCode(code, query) { + let reason = 'Unknown Error'; + if (code === 'too_big') { + reason = + 'The data requested exceeds the maximum size ' + + 'that can be accessed with a single request.'; + } + else if (code === 'permission_denied') { + reason = "Client doesn't have permission to access the desired data."; + } + else if (code === 'unavailable') { + reason = 'The service is unavailable'; + } + const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error.code = code.toUpperCase(); + return error; +} +/** + * Used to test for integer-looking strings + */ +const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$'); +/** + * For use in keys, the minimum possible 32-bit integer. + */ +const INTEGER_32_MIN = -2147483648; +/** + * For use in keys, the maximum possible 32-bit integer. + */ +const INTEGER_32_MAX = 2147483647; +/** + * If the string contains a 32-bit integer, return it. Else return null. + */ +const tryParseInt = function (str) { + if (INTEGER_REGEXP_.test(str)) { + const intVal = Number(str); + if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) { + return intVal; + } + } + return null; +}; +/** + * Helper to run some code but catch any exceptions and re-throw them later. + * Useful for preventing user callbacks from breaking internal code. + * + * Re-throwing the exception from a setTimeout is a little evil, but it's very + * convenient (we don't have to try to figure out when is a safe point to + * re-throw it), and the behavior seems reasonable: + * + * * If you aren't pausing on exceptions, you get an error in the console with + * the correct stack trace. + * * If you're pausing on all exceptions, the debugger will pause on your + * exception and then again when we rethrow it. + * * If you're only pausing on uncaught exceptions, the debugger will only pause + * on us re-throwing it. + * + * @param fn - The code to guard. + */ +const exceptionGuard = function (fn) { + try { + fn(); + } + catch (e) { + // Re-throw exception when it's safe. + setTimeout(() => { + // It used to be that "throw e" would result in a good console error with + // relevant context, but as of Chrome 39, you just get the firebase.js + // file/line number where we re-throw it, which is useless. So we log + // e.stack explicitly. + const stack = e.stack || ''; + warn('Exception was thrown by user callback.', stack); + throw e; + }, Math.floor(0)); + } +}; +/** + * @returns {boolean} true if we think we're currently being crawled. + */ +const beingCrawled = function () { + const userAgent = (typeof window === 'object' && + window['navigator'] && + window['navigator']['userAgent']) || + ''; + // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we + // believe to support JavaScript/AJAX rendering. + // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website + // would have seen the page" is flaky if we don't treat it as a crawler. + return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0); +}; +/** + * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting. + * + * It is removed with clearTimeout() as normal. + * + * @param fn - Function to run. + * @param time - Milliseconds to wait before running. + * @returns The setTimeout() return value. + */ +const setTimeoutNonBlocking = function (fn, time) { + const timeout = setTimeout(fn, time); + // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API. + if (typeof timeout === 'number' && + // @ts-ignore Is only defined in Deno environments. + typeof Deno !== 'undefined' && + // @ts-ignore Deno and unrefTimer are only defined in Deno environments. + Deno['unrefTimer']) { + // @ts-ignore Deno and unrefTimer are only defined in Deno environments. + Deno.unrefTimer(timeout); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (typeof timeout === 'object' && timeout['unref']) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + timeout['unref'](); + } + return timeout; +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A class that holds metadata about a Repo object + */ +class RepoInfo { + /** + * @param host - Hostname portion of the url for the repo + * @param secure - Whether or not this repo is accessed over ssl + * @param namespace - The namespace represented by the repo + * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest). + * @param nodeAdmin - Whether this instance uses Admin SDK credentials + * @param persistenceKey - Override the default session persistence storage key + */ + constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false, isUsingEmulator = false, emulatorOptions = null) { + this.secure = secure; + this.namespace = namespace; + this.webSocketOnly = webSocketOnly; + this.nodeAdmin = nodeAdmin; + this.persistenceKey = persistenceKey; + this.includeNamespaceInQueryParams = includeNamespaceInQueryParams; + this.isUsingEmulator = isUsingEmulator; + this.emulatorOptions = emulatorOptions; + this._host = host.toLowerCase(); + this._domain = this._host.substr(this._host.indexOf('.') + 1); + this.internalHost = + PersistentStorage.get('host:' + host) || this._host; + } + isCacheableHost() { + return this.internalHost.substr(0, 2) === 's-'; + } + isCustomHost() { + return (this._domain !== 'firebaseio.com' && + this._domain !== 'firebaseio-demo.com'); + } + get host() { + return this._host; + } + set host(newHost) { + if (newHost !== this.internalHost) { + this.internalHost = newHost; + if (this.isCacheableHost()) { + PersistentStorage.set('host:' + this._host, this.internalHost); + } + } + } + toString() { + let str = this.toURLString(); + if (this.persistenceKey) { + str += '<' + this.persistenceKey + '>'; + } + return str; + } + toURLString() { + const protocol = this.secure ? 'https://' : 'http://'; + const query = this.includeNamespaceInQueryParams + ? `?ns=${this.namespace}` + : ''; + return `${protocol}${this.host}/${query}`; + } +} +function repoInfoNeedsQueryParam(repoInfo) { + return (repoInfo.host !== repoInfo.internalHost || + repoInfo.isCustomHost() || + repoInfo.includeNamespaceInQueryParams); +} +/** + * Returns the websocket URL for this repo + * @param repoInfo - RepoInfo object + * @param type - of connection + * @param params - list + * @returns The URL for this repo + */ +function repoInfoConnectionURL(repoInfo, type, params) { + util.assert(typeof type === 'string', 'typeof type must == string'); + util.assert(typeof params === 'object', 'typeof params must == object'); + let connURL; + if (type === WEBSOCKET) { + connURL = + (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?'; + } + else if (type === LONG_POLLING) { + connURL = + (repoInfo.secure ? 'https://' : 'http://') + + repoInfo.internalHost + + '/.lp?'; + } + else { + throw new Error('Unknown connection type: ' + type); + } + if (repoInfoNeedsQueryParam(repoInfo)) { + params['ns'] = repoInfo.namespace; + } + const pairs = []; + each(params, (key, value) => { + pairs.push(key + '=' + value); + }); + return connURL + pairs.join('&'); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Tracks a collection of stats. + */ +class StatsCollection { + constructor() { + this.counters_ = {}; + } + incrementCounter(name, amount = 1) { + if (!util.contains(this.counters_, name)) { + this.counters_[name] = 0; + } + this.counters_[name] += amount; + } + get() { + return util.deepCopy(this.counters_); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const collections = {}; +const reporters = {}; +function statsManagerGetCollection(repoInfo) { + const hashString = repoInfo.toString(); + if (!collections[hashString]) { + collections[hashString] = new StatsCollection(); + } + return collections[hashString]; +} +function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) { + const hashString = repoInfo.toString(); + if (!reporters[hashString]) { + reporters[hashString] = creatorFunction(); + } + return reporters[hashString]; +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The semver (www.semver.org) version of the SDK. */ +let SDK_VERSION = ''; +/** + * SDK_VERSION should be set before any database instance is created + * @internal + */ +function setSDKVersion(version) { + SDK_VERSION = version; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const WEBSOCKET_MAX_FRAME_SIZE = 16384; +const WEBSOCKET_KEEPALIVE_INTERVAL = 45000; +let WebSocketImpl = null; +if (typeof MozWebSocket !== 'undefined') { + WebSocketImpl = MozWebSocket; +} +else if (typeof WebSocket !== 'undefined') { + WebSocketImpl = WebSocket; +} +function setWebSocketImpl(impl) { + WebSocketImpl = impl; +} +/** + * Create a new websocket connection with the given callbacks. + */ +class WebSocketConnection { + /** + * @param connId identifier for this transport + * @param repoInfo The info for the websocket endpoint. + * @param applicationId The Firebase App ID for this project. + * @param appCheckToken The App Check Token for this client. + * @param authToken The Auth Token for this client. + * @param transportSessionId Optional transportSessionId if this is connecting + * to an existing transport session + * @param lastSessionId Optional lastSessionId if there was a previous + * connection + */ + constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) { + this.connId = connId; + this.applicationId = applicationId; + this.appCheckToken = appCheckToken; + this.authToken = authToken; + this.keepaliveTimer = null; + this.frames = null; + this.totalFrames = 0; + this.bytesSent = 0; + this.bytesReceived = 0; + this.log_ = logWrapper(this.connId); + this.stats_ = statsManagerGetCollection(repoInfo); + this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId); + this.nodeAdmin = repoInfo.nodeAdmin; + } + /** + * @param repoInfo - The info for the websocket endpoint. + * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport + * session + * @param lastSessionId - Optional lastSessionId if there was a previous connection + * @returns connection url + */ + static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) { + const urlParams = {}; + urlParams[VERSION_PARAM] = PROTOCOL_VERSION; + if (!util.isNodeSdk() && + typeof location !== 'undefined' && + location.hostname && + FORGE_DOMAIN_RE.test(location.hostname)) { + urlParams[REFERER_PARAM] = FORGE_REF; + } + if (transportSessionId) { + urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId; + } + if (lastSessionId) { + urlParams[LAST_SESSION_PARAM] = lastSessionId; + } + if (appCheckToken) { + urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken; + } + if (applicationId) { + urlParams[APPLICATION_ID_PARAM] = applicationId; + } + return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams); + } + /** + * @param onMessage - Callback when messages arrive + * @param onDisconnect - Callback with connection lost. + */ + open(onMessage, onDisconnect) { + this.onDisconnect = onDisconnect; + this.onMessage = onMessage; + this.log_('Websocket connecting to ' + this.connURL); + this.everConnected_ = false; + // Assume failure until proven otherwise. + PersistentStorage.set('previous_websocket_failure', true); + try { + let options; + if (util.isNodeSdk()) { + const device = this.nodeAdmin ? 'AdminNode' : 'Node'; + // UA Format: Firebase//// + options = { + headers: { + 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`, + 'X-Firebase-GMPID': this.applicationId || '' + } + }; + // If using Node with admin creds, AppCheck-related checks are unnecessary. + // Note that we send the credentials here even if they aren't admin credentials, which is + // not a problem. + // Note that this header is just used to bypass appcheck, and the token should still be sent + // through the websocket connection once it is established. + if (this.authToken) { + options.headers['Authorization'] = `Bearer ${this.authToken}`; + } + if (this.appCheckToken) { + options.headers['X-Firebase-AppCheck'] = this.appCheckToken; + } + // Plumb appropriate http_proxy environment variable into faye-websocket if it exists. + const env = process['env']; + const proxy = this.connURL.indexOf('wss://') === 0 + ? env['HTTPS_PROXY'] || env['https_proxy'] + : env['HTTP_PROXY'] || env['http_proxy']; + if (proxy) { + options['proxy'] = { origin: proxy }; + } + } + this.mySock = new WebSocketImpl(this.connURL, [], options); + } + catch (e) { + this.log_('Error instantiating WebSocket.'); + const error = e.message || e.data; + if (error) { + this.log_(error); + } + this.onClosed_(); + return; + } + this.mySock.onopen = () => { + this.log_('Websocket connected.'); + this.everConnected_ = true; + }; + this.mySock.onclose = () => { + this.log_('Websocket connection was disconnected.'); + this.mySock = null; + this.onClosed_(); + }; + this.mySock.onmessage = m => { + this.handleIncomingFrame(m); + }; + this.mySock.onerror = e => { + this.log_('WebSocket error. Closing connection.'); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const error = e.message || e.data; + if (error) { + this.log_(error); + } + this.onClosed_(); + }; + } + /** + * No-op for websockets, we don't need to do anything once the connection is confirmed as open + */ + start() { } + static forceDisallow() { + WebSocketConnection.forceDisallow_ = true; + } + static isAvailable() { + let isOldAndroid = false; + if (typeof navigator !== 'undefined' && navigator.userAgent) { + const oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/; + const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex); + if (oldAndroidMatch && oldAndroidMatch.length > 1) { + if (parseFloat(oldAndroidMatch[1]) < 4.4) { + isOldAndroid = true; + } + } + } + return (!isOldAndroid && + WebSocketImpl !== null && + !WebSocketConnection.forceDisallow_); + } + /** + * Returns true if we previously failed to connect with this transport. + */ + static previouslyFailed() { + // If our persistent storage is actually only in-memory storage, + // we default to assuming that it previously failed to be safe. + return (PersistentStorage.isInMemoryStorage || + PersistentStorage.get('previous_websocket_failure') === true); + } + markConnectionHealthy() { + PersistentStorage.remove('previous_websocket_failure'); + } + appendFrame_(data) { + this.frames.push(data); + if (this.frames.length === this.totalFrames) { + const fullMess = this.frames.join(''); + this.frames = null; + const jsonMess = util.jsonEval(fullMess); + //handle the message + this.onMessage(jsonMess); + } + } + /** + * @param frameCount - The number of frames we are expecting from the server + */ + handleNewFrameCount_(frameCount) { + this.totalFrames = frameCount; + this.frames = []; + } + /** + * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1 + * @returns Any remaining data to be process, or null if there is none + */ + extractFrameCount_(data) { + util.assert(this.frames === null, 'We already have a frame buffer'); + // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced + // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508 + if (data.length <= 6) { + const frameCount = Number(data); + if (!isNaN(frameCount)) { + this.handleNewFrameCount_(frameCount); + return null; + } + } + this.handleNewFrameCount_(1); + return data; + } + /** + * Process a websocket frame that has arrived from the server. + * @param mess - The frame data + */ + handleIncomingFrame(mess) { + if (this.mySock === null) { + return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes. + } + const data = mess['data']; + this.bytesReceived += data.length; + this.stats_.incrementCounter('bytes_received', data.length); + this.resetKeepAlive(); + if (this.frames !== null) { + // we're buffering + this.appendFrame_(data); + } + else { + // try to parse out a frame count, otherwise, assume 1 and process it + const remainingData = this.extractFrameCount_(data); + if (remainingData !== null) { + this.appendFrame_(remainingData); + } + } + } + /** + * Send a message to the server + * @param data - The JSON object to transmit + */ + send(data) { + this.resetKeepAlive(); + const dataStr = util.stringify(data); + this.bytesSent += dataStr.length; + this.stats_.incrementCounter('bytes_sent', dataStr.length); + //We can only fit a certain amount in each websocket frame, so we need to split this request + //up into multiple pieces if it doesn't fit in one request. + const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE); + //Send the length header + if (dataSegs.length > 1) { + this.sendString_(String(dataSegs.length)); + } + //Send the actual data in segments. + for (let i = 0; i < dataSegs.length; i++) { + this.sendString_(dataSegs[i]); + } + } + shutdown_() { + this.isClosed_ = true; + if (this.keepaliveTimer) { + clearInterval(this.keepaliveTimer); + this.keepaliveTimer = null; + } + if (this.mySock) { + this.mySock.close(); + this.mySock = null; + } + } + onClosed_() { + if (!this.isClosed_) { + this.log_('WebSocket is closing itself'); + this.shutdown_(); + // since this is an internal close, trigger the close listener + if (this.onDisconnect) { + this.onDisconnect(this.everConnected_); + this.onDisconnect = null; + } + } + } + /** + * External-facing close handler. + * Close the websocket and kill the connection. + */ + close() { + if (!this.isClosed_) { + this.log_('WebSocket is being closed'); + this.shutdown_(); + } + } + /** + * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after + * the last activity. + */ + resetKeepAlive() { + clearInterval(this.keepaliveTimer); + this.keepaliveTimer = setInterval(() => { + //If there has been no websocket activity for a while, send a no-op + if (this.mySock) { + this.sendString_('0'); + } + this.resetKeepAlive(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL)); + } + /** + * Send a string over the websocket. + * + * @param str - String to send. + */ + sendString_(str) { + // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send() + // calls for some unknown reason. We treat these as an error and disconnect. + // See https://app.asana.com/0/58926111402292/68021340250410 + try { + this.mySock.send(str); + } + catch (e) { + this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.'); + setTimeout(this.onClosed_.bind(this), 0); + } + } +} +/** + * Number of response before we consider the connection "healthy." + */ +WebSocketConnection.responsesRequiredToBeHealthy = 2; +/** + * Time to wait for the connection te become healthy before giving up. + */ +WebSocketConnection.healthyTimeout = 30000; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Abstraction around AppCheck's token fetching capabilities. + */ +class AppCheckTokenProvider { + constructor(app$1, appCheckProvider) { + this.appCheckProvider = appCheckProvider; + this.appName = app$1.name; + if (app._isFirebaseServerApp(app$1) && app$1.settings.appCheckToken) { + this.serverAppAppCheckToken = app$1.settings.appCheckToken; + } + this.appCheck = appCheckProvider?.getImmediate({ optional: true }); + if (!this.appCheck) { + appCheckProvider?.get().then(appCheck => (this.appCheck = appCheck)); + } + } + getToken(forceRefresh) { + if (this.serverAppAppCheckToken) { + if (forceRefresh) { + throw new Error('Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.'); + } + return Promise.resolve({ token: this.serverAppAppCheckToken }); + } + if (!this.appCheck) { + return new Promise((resolve, reject) => { + // Support delayed initialization of FirebaseAppCheck. This allows our + // customers to initialize the RTDB SDK before initializing Firebase + // AppCheck and ensures that all requests are authenticated if a token + // becomes available before the timeout below expires. + setTimeout(() => { + if (this.appCheck) { + this.getToken(forceRefresh).then(resolve, reject); + } + else { + resolve(null); + } + }, 0); + }); + } + return this.appCheck.getToken(forceRefresh); + } + addTokenChangeListener(listener) { + this.appCheckProvider + ?.get() + .then(appCheck => appCheck.addTokenListener(listener)); + } + notifyForInvalidToken() { + warn(`Provided AppCheck credentials for the app named "${this.appName}" ` + + 'are invalid. This usually indicates your app was not initialized correctly.'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Abstraction around FirebaseApp's token fetching capabilities. + */ +class FirebaseAuthTokenProvider { + constructor(appName_, firebaseOptions_, authProvider_) { + this.appName_ = appName_; + this.firebaseOptions_ = firebaseOptions_; + this.authProvider_ = authProvider_; + this.auth_ = null; + this.auth_ = authProvider_.getImmediate({ optional: true }); + if (!this.auth_) { + authProvider_.onInit(auth => (this.auth_ = auth)); + } + } + getToken(forceRefresh) { + if (!this.auth_) { + return new Promise((resolve, reject) => { + // Support delayed initialization of FirebaseAuth. This allows our + // customers to initialize the RTDB SDK before initializing Firebase + // Auth and ensures that all requests are authenticated if a token + // becomes available before the timeout below expires. + setTimeout(() => { + if (this.auth_) { + this.getToken(forceRefresh).then(resolve, reject); + } + else { + resolve(null); + } + }, 0); + }); + } + return this.auth_.getToken(forceRefresh).catch(error => { + // TODO: Need to figure out all the cases this is raised and whether + // this makes sense. + if (error && error.code === 'auth/token-not-initialized') { + log('Got auth/token-not-initialized error. Treating as null token.'); + return null; + } + else { + return Promise.reject(error); + } + }); + } + addTokenChangeListener(listener) { + // TODO: We might want to wrap the listener and call it with no args to + // avoid a leaky abstraction, but that makes removing the listener harder. + if (this.auth_) { + this.auth_.addAuthTokenListener(listener); + } + else { + this.authProvider_ + .get() + .then(auth => auth.addAuthTokenListener(listener)); + } + } + removeTokenChangeListener(listener) { + this.authProvider_ + .get() + .then(auth => auth.removeAuthTokenListener(listener)); + } + notifyForInvalidToken() { + let errorMessage = 'Provided authentication credentials for the app named "' + + this.appName_ + + '" are invalid. This usually indicates your app was not ' + + 'initialized correctly. '; + if ('credential' in this.firebaseOptions_) { + errorMessage += + 'Make sure the "credential" property provided to initializeApp() ' + + 'is authorized to access the specified "databaseURL" and is from the correct ' + + 'project.'; + } + else if ('serviceAccount' in this.firebaseOptions_) { + errorMessage += + 'Make sure the "serviceAccount" property provided to initializeApp() ' + + 'is authorized to access the specified "databaseURL" and is from the correct ' + + 'project.'; + } + else { + errorMessage += + 'Make sure the "apiKey" and "databaseURL" properties provided to ' + + 'initializeApp() match the values provided for your app at ' + + 'https://console.firebase.google.com/.'; + } + warn(errorMessage); + } +} +/* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */ +class EmulatorTokenProvider { + constructor(accessToken) { + this.accessToken = accessToken; + } + getToken(forceRefresh) { + return Promise.resolve({ + accessToken: this.accessToken + }); + } + addTokenChangeListener(listener) { + // Invoke the listener immediately to match the behavior in Firebase Auth + // (see packages/auth/src/auth.js#L1807) + listener(this.accessToken); + } + removeTokenChangeListener(listener) { } + notifyForInvalidToken() { } +} +/** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */ +EmulatorTokenProvider.OWNER = 'owner'; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This class ensures the packets from the server arrive in order + * This class takes data from the server and ensures it gets passed into the callbacks in order. + */ +class PacketReceiver { + /** + * @param onMessage_ + */ + constructor(onMessage_) { + this.onMessage_ = onMessage_; + this.pendingResponses = []; + this.currentResponseNum = 0; + this.closeAfterResponse = -1; + this.onClose = null; + } + closeAfter(responseNum, callback) { + this.closeAfterResponse = responseNum; + this.onClose = callback; + if (this.closeAfterResponse < this.currentResponseNum) { + this.onClose(); + this.onClose = null; + } + } + /** + * Each message from the server comes with a response number, and an array of data. The responseNumber + * allows us to ensure that we process them in the right order, since we can't be guaranteed that all + * browsers will respond in the same order as the requests we sent + */ + handleResponse(requestNum, data) { + this.pendingResponses[requestNum] = data; + while (this.pendingResponses[this.currentResponseNum]) { + const toProcess = this.pendingResponses[this.currentResponseNum]; + delete this.pendingResponses[this.currentResponseNum]; + for (let i = 0; i < toProcess.length; ++i) { + if (toProcess[i]) { + exceptionGuard(() => { + this.onMessage_(toProcess[i]); + }); + } + } + if (this.currentResponseNum === this.closeAfterResponse) { + if (this.onClose) { + this.onClose(); + this.onClose = null; + } + break; + } + this.currentResponseNum++; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// URL query parameters associated with longpolling +const FIREBASE_LONGPOLL_START_PARAM = 'start'; +const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close'; +const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand'; +const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB'; +const FIREBASE_LONGPOLL_ID_PARAM = 'id'; +const FIREBASE_LONGPOLL_PW_PARAM = 'pw'; +const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser'; +const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb'; +const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg'; +const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts'; +const FIREBASE_LONGPOLL_DATA_PARAM = 'd'; +const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe'; +//Data size constants. +//TODO: Perf: the maximum length actually differs from browser to browser. +// We should check what browser we're on and set accordingly. +const MAX_URL_DATA_SIZE = 1870; +const SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d= +const MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE; +/** + * Keepalive period + * send a fresh request at minimum every 25 seconds. Opera has a maximum request + * length of 30 seconds that we can't exceed. + */ +const KEEPALIVE_REQUEST_INTERVAL = 25000; +/** + * How long to wait before aborting a long-polling connection attempt. + */ +const LP_CONNECT_TIMEOUT = 30000; +/** + * This class manages a single long-polling connection. + */ +class BrowserPollConnection { + /** + * @param connId An identifier for this connection, used for logging + * @param repoInfo The info for the endpoint to send data to. + * @param applicationId The Firebase App ID for this project. + * @param appCheckToken The AppCheck token for this client. + * @param authToken The AuthToken to use for this connection. + * @param transportSessionId Optional transportSessionid if we are + * reconnecting for an existing transport session + * @param lastSessionId Optional lastSessionId if the PersistentConnection has + * already created a connection previously + */ + constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) { + this.connId = connId; + this.repoInfo = repoInfo; + this.applicationId = applicationId; + this.appCheckToken = appCheckToken; + this.authToken = authToken; + this.transportSessionId = transportSessionId; + this.lastSessionId = lastSessionId; + this.bytesSent = 0; + this.bytesReceived = 0; + this.everConnected_ = false; + this.log_ = logWrapper(connId); + this.stats_ = statsManagerGetCollection(repoInfo); + this.urlFn = (params) => { + // Always add the token if we have one. + if (this.appCheckToken) { + params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken; + } + return repoInfoConnectionURL(repoInfo, LONG_POLLING, params); + }; + } + /** + * @param onMessage - Callback when messages arrive + * @param onDisconnect - Callback with connection lost. + */ + open(onMessage, onDisconnect) { + this.curSegmentNum = 0; + this.onDisconnect_ = onDisconnect; + this.myPacketOrderer = new PacketReceiver(onMessage); + this.isClosed_ = false; + this.connectTimeoutTimer_ = setTimeout(() => { + this.log_('Timed out trying to connect.'); + // Make sure we clear the host cache + this.onClosed_(); + this.connectTimeoutTimer_ = null; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(LP_CONNECT_TIMEOUT)); + // Ensure we delay the creation of the iframe until the DOM is loaded. + executeWhenDOMReady(() => { + if (this.isClosed_) { + return; + } + //Set up a callback that gets triggered once a connection is set up. + this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => { + const [command, arg1, arg2, arg3, arg4] = args; + this.incrementIncomingBytes_(args); + if (!this.scriptTagHolder) { + return; // we closed the connection. + } + if (this.connectTimeoutTimer_) { + clearTimeout(this.connectTimeoutTimer_); + this.connectTimeoutTimer_ = null; + } + this.everConnected_ = true; + if (command === FIREBASE_LONGPOLL_START_PARAM) { + this.id = arg1; + this.password = arg2; + } + else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) { + // Don't clear the host cache. We got a response from the server, so we know it's reachable + if (arg1) { + // We aren't expecting any more data (other than what the server's already in the process of sending us + // through our already open polls), so don't send any more. + this.scriptTagHolder.sendNewPolls = false; + // arg1 in this case is the last response number sent by the server. We should try to receive + // all of the responses up to this one before closing + this.myPacketOrderer.closeAfter(arg1, () => { + this.onClosed_(); + }); + } + else { + this.onClosed_(); + } + } + else { + throw new Error('Unrecognized command received: ' + command); + } + }, (...args) => { + const [pN, data] = args; + this.incrementIncomingBytes_(args); + this.myPacketOrderer.handleResponse(pN, data); + }, () => { + this.onClosed_(); + }, this.urlFn); + //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results + //from cache. + const urlParams = {}; + urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't'; + urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000); + if (this.scriptTagHolder.uniqueCallbackIdentifier) { + urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = + this.scriptTagHolder.uniqueCallbackIdentifier; + } + urlParams[VERSION_PARAM] = PROTOCOL_VERSION; + if (this.transportSessionId) { + urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId; + } + if (this.lastSessionId) { + urlParams[LAST_SESSION_PARAM] = this.lastSessionId; + } + if (this.applicationId) { + urlParams[APPLICATION_ID_PARAM] = this.applicationId; + } + if (this.appCheckToken) { + urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken; + } + if (typeof location !== 'undefined' && + location.hostname && + FORGE_DOMAIN_RE.test(location.hostname)) { + urlParams[REFERER_PARAM] = FORGE_REF; + } + const connectURL = this.urlFn(urlParams); + this.log_('Connecting via long-poll to ' + connectURL); + this.scriptTagHolder.addTag(connectURL, () => { + /* do nothing */ + }); + }); + } + /** + * Call this when a handshake has completed successfully and we want to consider the connection established + */ + start() { + this.scriptTagHolder.startLongPoll(this.id, this.password); + this.addDisconnectPingFrame(this.id, this.password); + } + /** + * Forces long polling to be considered as a potential transport + */ + static forceAllow() { + BrowserPollConnection.forceAllow_ = true; + } + /** + * Forces longpolling to not be considered as a potential transport + */ + static forceDisallow() { + BrowserPollConnection.forceDisallow_ = true; + } + // Static method, use string literal so it can be accessed in a generic way + static isAvailable() { + if (util.isNodeSdk()) { + return false; + } + else if (BrowserPollConnection.forceAllow_) { + return true; + } + else { + // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in + // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08). + return (!BrowserPollConnection.forceDisallow_ && + typeof document !== 'undefined' && + document.createElement != null && + !isChromeExtensionContentScript() && + !isWindowsStoreApp()); + } + } + /** + * No-op for polling + */ + markConnectionHealthy() { } + /** + * Stops polling and cleans up the iframe + */ + shutdown_() { + this.isClosed_ = true; + if (this.scriptTagHolder) { + this.scriptTagHolder.close(); + this.scriptTagHolder = null; + } + //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving. + if (this.myDisconnFrame) { + document.body.removeChild(this.myDisconnFrame); + this.myDisconnFrame = null; + } + if (this.connectTimeoutTimer_) { + clearTimeout(this.connectTimeoutTimer_); + this.connectTimeoutTimer_ = null; + } + } + /** + * Triggered when this transport is closed + */ + onClosed_() { + if (!this.isClosed_) { + this.log_('Longpoll is closing itself'); + this.shutdown_(); + if (this.onDisconnect_) { + this.onDisconnect_(this.everConnected_); + this.onDisconnect_ = null; + } + } + } + /** + * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server + * that we've left. + */ + close() { + if (!this.isClosed_) { + this.log_('Longpoll is being closed.'); + this.shutdown_(); + } + } + /** + * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then + * broken into chunks (since URLs have a small maximum length). + * @param data - The JSON data to transmit. + */ + send(data) { + const dataStr = util.stringify(data); + this.bytesSent += dataStr.length; + this.stats_.incrementCounter('bytes_sent', dataStr.length); + //first, lets get the base64-encoded data + const base64data = util.base64Encode(dataStr); + //We can only fit a certain amount in each URL, so we need to split this request + //up into multiple pieces if it doesn't fit in one request. + const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE); + //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number + //of segments so that we can reassemble the packet on the server. + for (let i = 0; i < dataSegs.length; i++) { + this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]); + this.curSegmentNum++; + } + } + /** + * This is how we notify the server that we're leaving. + * We aren't able to send requests with DHTML on a window close event, but we can + * trigger XHR requests in some browsers (everything but Opera basically). + */ + addDisconnectPingFrame(id, pw) { + if (util.isNodeSdk()) { + return; + } + this.myDisconnFrame = document.createElement('iframe'); + const urlParams = {}; + urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't'; + urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id; + urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw; + this.myDisconnFrame.src = this.urlFn(urlParams); + this.myDisconnFrame.style.display = 'none'; + document.body.appendChild(this.myDisconnFrame); + } + /** + * Used to track the bytes received by this client + */ + incrementIncomingBytes_(args) { + // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in. + const bytesReceived = util.stringify(args).length; + this.bytesReceived += bytesReceived; + this.stats_.incrementCounter('bytes_received', bytesReceived); + } +} +/********************************************************************************************* + * A wrapper around an iframe that is used as a long-polling script holder. + *********************************************************************************************/ +class FirebaseIFrameScriptHolder { + /** + * @param commandCB - The callback to be called when control commands are received from the server. + * @param onMessageCB - The callback to be triggered when responses arrive from the server. + * @param onDisconnect - The callback to be triggered when this tag holder is closed + * @param urlFn - A function that provides the URL of the endpoint to send data to. + */ + constructor(commandCB, onMessageCB, onDisconnect, urlFn) { + this.onDisconnect = onDisconnect; + this.urlFn = urlFn; + //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause + //problems in some browsers. + this.outstandingRequests = new Set(); + //A queue of the pending segments waiting for transmission to the server. + this.pendingSegs = []; + //A serial number. We use this for two things: + // 1) A way to ensure the browser doesn't cache responses to polls + // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The + // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute + // JSONP code in the order it was added to the iframe. + this.currentSerial = Math.floor(Math.random() * 100000000); + // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still + // incoming data from the server that we're waiting for). + this.sendNewPolls = true; + if (!util.isNodeSdk()) { + //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the + //iframes where we put the long-polling script tags. We have two callbacks: + // 1) Command Callback - Triggered for control issues, like starting a connection. + // 2) Message Callback - Triggered when new data arrives. + this.uniqueCallbackIdentifier = LUIDGenerator(); + window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB; + window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = + onMessageCB; + //Create an iframe for us to add script tags to. + this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_(); + // Set the iframe's contents. + let script = ''; + // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient + // for ie9, but ie8 needs to do it again in the document itself. + if (this.myIFrame.src && + this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') { + const currentDomain = document.domain; + script = ''; + } + const iframeContents = '' + script + ''; + try { + this.myIFrame.doc.open(); + this.myIFrame.doc.write(iframeContents); + this.myIFrame.doc.close(); + } + catch (e) { + log('frame writing exception'); + if (e.stack) { + log(e.stack); + } + log(e); + } + } + else { + this.commandCB = commandCB; + this.onMessageCB = onMessageCB; + } + } + /** + * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can + * actually use. + */ + static createIFrame_() { + const iframe = document.createElement('iframe'); + iframe.style.display = 'none'; + // This is necessary in order to initialize the document inside the iframe + if (document.body) { + document.body.appendChild(iframe); + try { + // If document.domain has been modified in IE, this will throw an error, and we need to set the + // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute + // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work. + const a = iframe.contentWindow.document; + if (!a) { + // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above. + log('No IE domain setting required'); + } + } + catch (e) { + const domain = document.domain; + iframe.src = + "javascript:void((function(){document.open();document.domain='" + + domain + + "';document.close();})())"; + } + } + else { + // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this + // never gets hit. + throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.'; + } + // Get the document of the iframe in a browser-specific way. + if (iframe.contentDocument) { + iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari + } + else if (iframe.contentWindow) { + iframe.doc = iframe.contentWindow.document; // Internet Explorer + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (iframe.document) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + iframe.doc = iframe.document; //others? + } + return iframe; + } + /** + * Cancel all outstanding queries and remove the frame. + */ + close() { + //Mark this iframe as dead, so no new requests are sent. + this.alive = false; + if (this.myIFrame) { + //We have to actually remove all of the html inside this iframe before removing it from the + //window, or IE will continue loading and executing the script tags we've already added, which + //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this. + this.myIFrame.doc.body.textContent = ''; + setTimeout(() => { + if (this.myIFrame !== null) { + document.body.removeChild(this.myIFrame); + this.myIFrame = null; + } + }, Math.floor(0)); + } + // Protect from being called recursively. + const onDisconnect = this.onDisconnect; + if (onDisconnect) { + this.onDisconnect = null; + onDisconnect(); + } + } + /** + * Actually start the long-polling session by adding the first script tag(s) to the iframe. + * @param id - The ID of this connection + * @param pw - The password for this connection + */ + startLongPoll(id, pw) { + this.myID = id; + this.myPW = pw; + this.alive = true; + //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to. + while (this.newRequest_()) { } + } + /** + * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't + * too many outstanding requests and we are still alive. + * + * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if + * needed. + */ + newRequest_() { + // We keep one outstanding request open all the time to receive data, but if we need to send data + // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically + // close the old request. + if (this.alive && + this.sendNewPolls && + this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) { + //construct our url + this.currentSerial++; + const urlParams = {}; + urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID; + urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW; + urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial; + let theURL = this.urlFn(urlParams); + //Now add as much data as we can. + let curDataString = ''; + let i = 0; + while (this.pendingSegs.length > 0) { + //first, lets see if the next segment will fit. + const nextSeg = this.pendingSegs[0]; + if (nextSeg.d.length + + SEG_HEADER_SIZE + + curDataString.length <= + MAX_URL_DATA_SIZE) { + //great, the segment will fit. Lets append it. + const theSeg = this.pendingSegs.shift(); + curDataString = + curDataString + + '&' + + FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM + + i + + '=' + + theSeg.seg + + '&' + + FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET + + i + + '=' + + theSeg.ts + + '&' + + FIREBASE_LONGPOLL_DATA_PARAM + + i + + '=' + + theSeg.d; + i++; + } + else { + break; + } + } + theURL = theURL + curDataString; + this.addLongPollTag_(theURL, this.currentSerial); + return true; + } + else { + return false; + } + } + /** + * Queue a packet for transmission to the server. + * @param segnum - A sequential id for this packet segment used for reassembly + * @param totalsegs - The total number of segments in this packet + * @param data - The data for this segment. + */ + enqueueSegment(segnum, totalsegs, data) { + //add this to the queue of segments to send. + this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data }); + //send the data immediately if there isn't already data being transmitted, unless + //startLongPoll hasn't been called yet. + if (this.alive) { + this.newRequest_(); + } + } + /** + * Add a script tag for a regular long-poll request. + * @param url - The URL of the script tag. + * @param serial - The serial number of the request. + */ + addLongPollTag_(url, serial) { + //remember that we sent this request. + this.outstandingRequests.add(serial); + const doNewRequest = () => { + this.outstandingRequests.delete(serial); + this.newRequest_(); + }; + // If this request doesn't return on its own accord (by the server sending us some data), we'll + // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open. + const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL)); + const readyStateCB = () => { + // Request completed. Cancel the keepalive. + clearTimeout(keepaliveTimeout); + // Trigger a new request so we can continue receiving data. + doNewRequest(); + }; + this.addTag(url, readyStateCB); + } + /** + * Add an arbitrary script tag to the iframe. + * @param url - The URL for the script tag source. + * @param loadCB - A callback to be triggered once the script has loaded. + */ + addTag(url, loadCB) { + if (util.isNodeSdk()) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.doNodeLongPoll(url, loadCB); + } + else { + setTimeout(() => { + try { + // if we're already closed, don't add this poll + if (!this.sendNewPolls) { + return; + } + const newScript = this.myIFrame.doc.createElement('script'); + newScript.type = 'text/javascript'; + newScript.async = true; + newScript.src = url; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + newScript.onload = newScript.onreadystatechange = + function () { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const rstate = newScript.readyState; + if (!rstate || rstate === 'loaded' || rstate === 'complete') { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + newScript.onload = newScript.onreadystatechange = null; + if (newScript.parentNode) { + newScript.parentNode.removeChild(newScript); + } + loadCB(); + } + }; + newScript.onerror = () => { + log('Long-poll script failed to load: ' + url); + this.sendNewPolls = false; + this.close(); + }; + this.myIFrame.doc.body.appendChild(newScript); + } + catch (e) { + // TODO: we should make this error visible somehow + } + }, Math.floor(1)); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Currently simplistic, this class manages what transport a Connection should use at various stages of its + * lifecycle. + * + * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if + * they are available. + */ +class TransportManager { + static get ALL_TRANSPORTS() { + return [BrowserPollConnection, WebSocketConnection]; + } + /** + * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after + * TransportManager has already set up transports_ + */ + static get IS_TRANSPORT_INITIALIZED() { + return this.globalTransportInitialized_; + } + /** + * @param repoInfo - Metadata around the namespace we're connecting to + */ + constructor(repoInfo) { + this.initTransports_(repoInfo); + } + initTransports_(repoInfo) { + const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable'](); + let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed(); + if (repoInfo.webSocketOnly) { + if (!isWebSocketsAvailable) { + warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway."); + } + isSkipPollConnection = true; + } + if (isSkipPollConnection) { + this.transports_ = [WebSocketConnection]; + } + else { + const transports = (this.transports_ = []); + for (const transport of TransportManager.ALL_TRANSPORTS) { + if (transport && transport['isAvailable']()) { + transports.push(transport); + } + } + TransportManager.globalTransportInitialized_ = true; + } + } + /** + * @returns The constructor for the initial transport to use + */ + initialTransport() { + if (this.transports_.length > 0) { + return this.transports_[0]; + } + else { + throw new Error('No transports available'); + } + } + /** + * @returns The constructor for the next transport, or null + */ + upgradeTransport() { + if (this.transports_.length > 1) { + return this.transports_[1]; + } + else { + return null; + } + } +} +// Keeps track of whether the TransportManager has already chosen a transport to use +TransportManager.globalTransportInitialized_ = false; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Abort upgrade attempt if it takes longer than 60s. +const UPGRADE_TIMEOUT = 60000; +// For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses. +// If we haven't sent enough requests within 5s, we'll start sending noop ping requests. +const DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000; +// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data) +// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout +// but we've sent/received enough bytes, we don't cancel the connection. +const BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024; +const BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024; +const MESSAGE_TYPE = 't'; +const MESSAGE_DATA = 'd'; +const CONTROL_SHUTDOWN = 's'; +const CONTROL_RESET = 'r'; +const CONTROL_ERROR = 'e'; +const CONTROL_PONG = 'o'; +const SWITCH_ACK = 'a'; +const END_TRANSMISSION = 'n'; +const PING = 'p'; +const SERVER_HELLO = 'h'; +/** + * Creates a new real-time connection to the server using whichever method works + * best in the current browser. + */ +class Connection { + /** + * @param id - an id for this connection + * @param repoInfo_ - the info for the endpoint to connect to + * @param applicationId_ - the Firebase App ID for this project + * @param appCheckToken_ - The App Check Token for this device. + * @param authToken_ - The auth token for this session. + * @param onMessage_ - the callback to be triggered when a server-push message arrives + * @param onReady_ - the callback to be triggered when this connection is ready to send messages. + * @param onDisconnect_ - the callback to be triggered when a connection was lost + * @param onKill_ - the callback to be triggered when this connection has permanently shut down. + * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server + */ + constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) { + this.id = id; + this.repoInfo_ = repoInfo_; + this.applicationId_ = applicationId_; + this.appCheckToken_ = appCheckToken_; + this.authToken_ = authToken_; + this.onMessage_ = onMessage_; + this.onReady_ = onReady_; + this.onDisconnect_ = onDisconnect_; + this.onKill_ = onKill_; + this.lastSessionId = lastSessionId; + this.connectionCount = 0; + this.pendingDataMessages = []; + this.state_ = 0 /* RealtimeState.CONNECTING */; + this.log_ = logWrapper('c:' + this.id + ':'); + this.transportManager_ = new TransportManager(repoInfo_); + this.log_('Connection created'); + this.start_(); + } + /** + * Starts a connection attempt + */ + start_() { + const conn = this.transportManager_.initialTransport(); + this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId); + // For certain transports (WebSockets), we need to send and receive several messages back and forth before we + // can consider the transport healthy. + this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0; + const onMessageReceived = this.connReceiver_(this.conn_); + const onConnectionLost = this.disconnReceiver_(this.conn_); + this.tx_ = this.conn_; + this.rx_ = this.conn_; + this.secondaryConn_ = null; + this.isHealthy_ = false; + /* + * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame. + * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset. + * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should + * still have the context of your originating frame. + */ + setTimeout(() => { + // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it + this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost); + }, Math.floor(0)); + const healthyTimeoutMS = conn['healthyTimeout'] || 0; + if (healthyTimeoutMS > 0) { + this.healthyTimeout_ = setTimeoutNonBlocking(() => { + this.healthyTimeout_ = null; + if (!this.isHealthy_) { + if (this.conn_ && + this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) { + this.log_('Connection exceeded healthy timeout but has received ' + + this.conn_.bytesReceived + + ' bytes. Marking connection healthy.'); + this.isHealthy_ = true; + this.conn_.markConnectionHealthy(); + } + else if (this.conn_ && + this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) { + this.log_('Connection exceeded healthy timeout but has sent ' + + this.conn_.bytesSent + + ' bytes. Leaving connection alive.'); + // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to + // the server. + } + else { + this.log_('Closing unhealthy connection after timeout.'); + this.close(); + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(healthyTimeoutMS)); + } + } + nextTransportId_() { + return 'c:' + this.id + ':' + this.connectionCount++; + } + disconnReceiver_(conn) { + return everConnected => { + if (conn === this.conn_) { + this.onConnectionLost_(everConnected); + } + else if (conn === this.secondaryConn_) { + this.log_('Secondary connection lost.'); + this.onSecondaryConnectionLost_(); + } + else { + this.log_('closing an old connection'); + } + }; + } + connReceiver_(conn) { + return (message) => { + if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) { + if (conn === this.rx_) { + this.onPrimaryMessageReceived_(message); + } + else if (conn === this.secondaryConn_) { + this.onSecondaryMessageReceived_(message); + } + else { + this.log_('message on old connection'); + } + } + }; + } + /** + * @param dataMsg - An arbitrary data message to be sent to the server + */ + sendRequest(dataMsg) { + // wrap in a data message envelope and send it on + const msg = { t: 'd', d: dataMsg }; + this.sendData_(msg); + } + tryCleanupConnection() { + if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) { + this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId); + this.conn_ = this.secondaryConn_; + this.secondaryConn_ = null; + // the server will shutdown the old connection + } + } + onSecondaryControl_(controlData) { + if (MESSAGE_TYPE in controlData) { + const cmd = controlData[MESSAGE_TYPE]; + if (cmd === SWITCH_ACK) { + this.upgradeIfSecondaryHealthy_(); + } + else if (cmd === CONTROL_RESET) { + // Most likely the session wasn't valid. Abandon the switch attempt + this.log_('Got a reset on secondary, closing it'); + this.secondaryConn_.close(); + // If we were already using this connection for something, than we need to fully close + if (this.tx_ === this.secondaryConn_ || + this.rx_ === this.secondaryConn_) { + this.close(); + } + } + else if (cmd === CONTROL_PONG) { + this.log_('got pong on secondary.'); + this.secondaryResponsesRequired_--; + this.upgradeIfSecondaryHealthy_(); + } + } + } + onSecondaryMessageReceived_(parsedData) { + const layer = requireKey('t', parsedData); + const data = requireKey('d', parsedData); + if (layer === 'c') { + this.onSecondaryControl_(data); + } + else if (layer === 'd') { + // got a data message, but we're still second connection. Need to buffer it up + this.pendingDataMessages.push(data); + } + else { + throw new Error('Unknown protocol layer: ' + layer); + } + } + upgradeIfSecondaryHealthy_() { + if (this.secondaryResponsesRequired_ <= 0) { + this.log_('Secondary connection is healthy.'); + this.isHealthy_ = true; + this.secondaryConn_.markConnectionHealthy(); + this.proceedWithUpgrade_(); + } + else { + // Send a ping to make sure the connection is healthy. + this.log_('sending ping on secondary.'); + this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } }); + } + } + proceedWithUpgrade_() { + // tell this connection to consider itself open + this.secondaryConn_.start(); + // send ack + this.log_('sending client ack on secondary'); + this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } }); + // send end packet on primary transport, switch to sending on this one + // can receive on this one, buffer responses until end received on primary transport + this.log_('Ending transmission on primary'); + this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } }); + this.tx_ = this.secondaryConn_; + this.tryCleanupConnection(); + } + onPrimaryMessageReceived_(parsedData) { + // Must refer to parsedData properties in quotes, so closure doesn't touch them. + const layer = requireKey('t', parsedData); + const data = requireKey('d', parsedData); + if (layer === 'c') { + this.onControl_(data); + } + else if (layer === 'd') { + this.onDataMessage_(data); + } + } + onDataMessage_(message) { + this.onPrimaryResponse_(); + // We don't do anything with data messages, just kick them up a level + this.onMessage_(message); + } + onPrimaryResponse_() { + if (!this.isHealthy_) { + this.primaryResponsesRequired_--; + if (this.primaryResponsesRequired_ <= 0) { + this.log_('Primary connection is healthy.'); + this.isHealthy_ = true; + this.conn_.markConnectionHealthy(); + } + } + } + onControl_(controlData) { + const cmd = requireKey(MESSAGE_TYPE, controlData); + if (MESSAGE_DATA in controlData) { + const payload = controlData[MESSAGE_DATA]; + if (cmd === SERVER_HELLO) { + const handshakePayload = { + ...payload + }; + if (this.repoInfo_.isUsingEmulator) { + // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes. + handshakePayload.h = this.repoInfo_.host; + } + this.onHandshake_(handshakePayload); + } + else if (cmd === END_TRANSMISSION) { + this.log_('recvd end transmission on primary'); + this.rx_ = this.secondaryConn_; + for (let i = 0; i < this.pendingDataMessages.length; ++i) { + this.onDataMessage_(this.pendingDataMessages[i]); + } + this.pendingDataMessages = []; + this.tryCleanupConnection(); + } + else if (cmd === CONTROL_SHUTDOWN) { + // This was previously the 'onKill' callback passed to the lower-level connection + // payload in this case is the reason for the shutdown. Generally a human-readable error + this.onConnectionShutdown_(payload); + } + else if (cmd === CONTROL_RESET) { + // payload in this case is the host we should contact + this.onReset_(payload); + } + else if (cmd === CONTROL_ERROR) { + error('Server Error: ' + payload); + } + else if (cmd === CONTROL_PONG) { + this.log_('got pong on primary.'); + this.onPrimaryResponse_(); + this.sendPingOnPrimaryIfNecessary_(); + } + else { + error('Unknown control packet command: ' + cmd); + } + } + } + /** + * @param handshake - The handshake data returned from the server + */ + onHandshake_(handshake) { + const timestamp = handshake.ts; + const version = handshake.v; + const host = handshake.h; + this.sessionId = handshake.s; + this.repoInfo_.host = host; + // if we've already closed the connection, then don't bother trying to progress further + if (this.state_ === 0 /* RealtimeState.CONNECTING */) { + this.conn_.start(); + this.onConnectionEstablished_(this.conn_, timestamp); + if (PROTOCOL_VERSION !== version) { + warn('Protocol version mismatch detected'); + } + // TODO: do we want to upgrade? when? maybe a delay? + this.tryStartUpgrade_(); + } + } + tryStartUpgrade_() { + const conn = this.transportManager_.upgradeTransport(); + if (conn) { + this.startUpgrade_(conn); + } + } + startUpgrade_(conn) { + this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId); + // For certain transports (WebSockets), we need to send and receive several messages back and forth before we + // can consider the transport healthy. + this.secondaryResponsesRequired_ = + conn['responsesRequiredToBeHealthy'] || 0; + const onMessage = this.connReceiver_(this.secondaryConn_); + const onDisconnect = this.disconnReceiver_(this.secondaryConn_); + this.secondaryConn_.open(onMessage, onDisconnect); + // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary. + setTimeoutNonBlocking(() => { + if (this.secondaryConn_) { + this.log_('Timed out trying to upgrade.'); + this.secondaryConn_.close(); + } + }, Math.floor(UPGRADE_TIMEOUT)); + } + onReset_(host) { + this.log_('Reset packet received. New host: ' + host); + this.repoInfo_.host = host; + // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up. + // We don't currently support resets after the connection has already been established + if (this.state_ === 1 /* RealtimeState.CONNECTED */) { + this.close(); + } + else { + // Close whatever connections we have open and start again. + this.closeConnections_(); + this.start_(); + } + } + onConnectionEstablished_(conn, timestamp) { + this.log_('Realtime connection established.'); + this.conn_ = conn; + this.state_ = 1 /* RealtimeState.CONNECTED */; + if (this.onReady_) { + this.onReady_(timestamp, this.sessionId); + this.onReady_ = null; + } + // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy, + // send some pings. + if (this.primaryResponsesRequired_ === 0) { + this.log_('Primary connection is healthy.'); + this.isHealthy_ = true; + } + else { + setTimeoutNonBlocking(() => { + this.sendPingOnPrimaryIfNecessary_(); + }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS)); + } + } + sendPingOnPrimaryIfNecessary_() { + // If the connection isn't considered healthy yet, we'll send a noop ping packet request. + if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) { + this.log_('sending ping on primary.'); + this.sendData_({ t: 'c', d: { t: PING, d: {} } }); + } + } + onSecondaryConnectionLost_() { + const conn = this.secondaryConn_; + this.secondaryConn_ = null; + if (this.tx_ === conn || this.rx_ === conn) { + // we are relying on this connection already in some capacity. Therefore, a failure is real + this.close(); + } + } + /** + * @param everConnected - Whether or not the connection ever reached a server. Used to determine if + * we should flush the host cache + */ + onConnectionLost_(everConnected) { + this.conn_ = null; + // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting + // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess. + if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) { + this.log_('Realtime connection failed.'); + // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away + if (this.repoInfo_.isCacheableHost()) { + PersistentStorage.remove('host:' + this.repoInfo_.host); + // reset the internal host to what we would show the user, i.e. .firebaseio.com + this.repoInfo_.internalHost = this.repoInfo_.host; + } + } + else if (this.state_ === 1 /* RealtimeState.CONNECTED */) { + this.log_('Realtime connection lost.'); + } + this.close(); + } + onConnectionShutdown_(reason) { + this.log_('Connection shutdown command received. Shutting down...'); + if (this.onKill_) { + this.onKill_(reason); + this.onKill_ = null; + } + // We intentionally don't want to fire onDisconnect (kill is a different case), + // so clear the callback. + this.onDisconnect_ = null; + this.close(); + } + sendData_(data) { + if (this.state_ !== 1 /* RealtimeState.CONNECTED */) { + throw 'Connection is not connected'; + } + else { + this.tx_.send(data); + } + } + /** + * Cleans up this connection, calling the appropriate callbacks + */ + close() { + if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) { + this.log_('Closing realtime connection.'); + this.state_ = 2 /* RealtimeState.DISCONNECTED */; + this.closeConnections_(); + if (this.onDisconnect_) { + this.onDisconnect_(); + this.onDisconnect_ = null; + } + } + } + closeConnections_() { + this.log_('Shutting down all connections'); + if (this.conn_) { + this.conn_.close(); + this.conn_ = null; + } + if (this.secondaryConn_) { + this.secondaryConn_.close(); + this.secondaryConn_ = null; + } + if (this.healthyTimeout_) { + clearTimeout(this.healthyTimeout_); + this.healthyTimeout_ = null; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Interface defining the set of actions that can be performed against the Firebase server + * (basically corresponds to our wire protocol). + * + * @interface + */ +class ServerActions { + put(pathString, data, onComplete, hash) { } + merge(pathString, data, onComplete, hash) { } + /** + * Refreshes the auth token for the current connection. + * @param token - The authentication token + */ + refreshAuthToken(token) { } + /** + * Refreshes the app check token for the current connection. + * @param token The app check token + */ + refreshAppCheckToken(token) { } + onDisconnectPut(pathString, data, onComplete) { } + onDisconnectMerge(pathString, data, onComplete) { } + onDisconnectCancel(pathString, onComplete) { } + reportStats(stats) { } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Base class to be used if you want to emit events. Call the constructor with + * the set of allowed event names. + */ +class EventEmitter { + constructor(allowedEvents_) { + this.allowedEvents_ = allowedEvents_; + this.listeners_ = {}; + util.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array'); + } + /** + * To be called by derived classes to trigger events. + */ + trigger(eventType, ...varArgs) { + if (Array.isArray(this.listeners_[eventType])) { + // Clone the list, since callbacks could add/remove listeners. + const listeners = [...this.listeners_[eventType]]; + for (let i = 0; i < listeners.length; i++) { + listeners[i].callback.apply(listeners[i].context, varArgs); + } + } + } + on(eventType, callback, context) { + this.validateEventType_(eventType); + this.listeners_[eventType] = this.listeners_[eventType] || []; + this.listeners_[eventType].push({ callback, context }); + const eventData = this.getInitialEvent(eventType); + if (eventData) { + callback.apply(context, eventData); + } + } + off(eventType, callback, context) { + this.validateEventType_(eventType); + const listeners = this.listeners_[eventType] || []; + for (let i = 0; i < listeners.length; i++) { + if (listeners[i].callback === callback && + (!context || context === listeners[i].context)) { + listeners.splice(i, 1); + return; + } + } + } + validateEventType_(eventType) { + util.assert(this.allowedEvents_.find(et => { + return et === eventType; + }), 'Unknown event: ' + eventType); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Monitors online state (as reported by window.online/offline events). + * + * The expectation is that this could have many false positives (thinks we are online + * when we're not), but no false negatives. So we can safely use it to determine when + * we definitely cannot reach the internet. + */ +class OnlineMonitor extends EventEmitter { + static getInstance() { + return new OnlineMonitor(); + } + constructor() { + super(['online']); + this.online_ = true; + // We've had repeated complaints that Cordova apps can get stuck "offline", e.g. + // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810 + // It would seem that the 'online' event does not always fire consistently. So we disable it + // for Cordova. + if (typeof window !== 'undefined' && + typeof window.addEventListener !== 'undefined' && + !util.isMobileCordova()) { + window.addEventListener('online', () => { + if (!this.online_) { + this.online_ = true; + this.trigger('online', true); + } + }, false); + window.addEventListener('offline', () => { + if (this.online_) { + this.online_ = false; + this.trigger('online', false); + } + }, false); + } + } + getInitialEvent(eventType) { + util.assert(eventType === 'online', 'Unknown event type: ' + eventType); + return [this.online_]; + } + currentlyOnline() { + return this.online_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Maximum key depth. */ +const MAX_PATH_DEPTH = 32; +/** Maximum number of (UTF8) bytes in a Firebase path. */ +const MAX_PATH_LENGTH_BYTES = 768; +/** + * An immutable object representing a parsed path. It's immutable so that you + * can pass them around to other functions without worrying about them changing + * it. + */ +class Path { + /** + * @param pathOrString - Path string to parse, or another path, or the raw + * tokens array + */ + constructor(pathOrString, pieceNum) { + if (pieceNum === void 0) { + this.pieces_ = pathOrString.split('/'); + // Remove empty pieces. + let copyTo = 0; + for (let i = 0; i < this.pieces_.length; i++) { + if (this.pieces_[i].length > 0) { + this.pieces_[copyTo] = this.pieces_[i]; + copyTo++; + } + } + this.pieces_.length = copyTo; + this.pieceNum_ = 0; + } + else { + this.pieces_ = pathOrString; + this.pieceNum_ = pieceNum; + } + } + toString() { + let pathString = ''; + for (let i = this.pieceNum_; i < this.pieces_.length; i++) { + if (this.pieces_[i] !== '') { + pathString += '/' + this.pieces_[i]; + } + } + return pathString || '/'; + } +} +function newEmptyPath() { + return new Path(''); +} +function pathGetFront(path) { + if (path.pieceNum_ >= path.pieces_.length) { + return null; + } + return path.pieces_[path.pieceNum_]; +} +/** + * @returns The number of segments in this path + */ +function pathGetLength(path) { + return path.pieces_.length - path.pieceNum_; +} +function pathPopFront(path) { + let pieceNum = path.pieceNum_; + if (pieceNum < path.pieces_.length) { + pieceNum++; + } + return new Path(path.pieces_, pieceNum); +} +function pathGetBack(path) { + if (path.pieceNum_ < path.pieces_.length) { + return path.pieces_[path.pieces_.length - 1]; + } + return null; +} +function pathToUrlEncodedString(path) { + let pathString = ''; + for (let i = path.pieceNum_; i < path.pieces_.length; i++) { + if (path.pieces_[i] !== '') { + pathString += '/' + encodeURIComponent(String(path.pieces_[i])); + } + } + return pathString || '/'; +} +/** + * Shallow copy of the parts of the path. + * + */ +function pathSlice(path, begin = 0) { + return path.pieces_.slice(path.pieceNum_ + begin); +} +function pathParent(path) { + if (path.pieceNum_ >= path.pieces_.length) { + return null; + } + const pieces = []; + for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) { + pieces.push(path.pieces_[i]); + } + return new Path(pieces, 0); +} +function pathChild(path, childPathObj) { + const pieces = []; + for (let i = path.pieceNum_; i < path.pieces_.length; i++) { + pieces.push(path.pieces_[i]); + } + if (childPathObj instanceof Path) { + for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) { + pieces.push(childPathObj.pieces_[i]); + } + } + else { + const childPieces = childPathObj.split('/'); + for (let i = 0; i < childPieces.length; i++) { + if (childPieces[i].length > 0) { + pieces.push(childPieces[i]); + } + } + } + return new Path(pieces, 0); +} +/** + * @returns True if there are no segments in this path + */ +function pathIsEmpty(path) { + return path.pieceNum_ >= path.pieces_.length; +} +/** + * @returns The path from outerPath to innerPath + */ +function newRelativePath(outerPath, innerPath) { + const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath); + if (outer === null) { + return innerPath; + } + else if (outer === inner) { + return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath)); + } + else { + throw new Error('INTERNAL ERROR: innerPath (' + + innerPath + + ') is not within ' + + 'outerPath (' + + outerPath + + ')'); + } +} +/** + * @returns -1, 0, 1 if left is less, equal, or greater than the right. + */ +function pathCompare(left, right) { + const leftKeys = pathSlice(left, 0); + const rightKeys = pathSlice(right, 0); + for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) { + const cmp = nameCompare(leftKeys[i], rightKeys[i]); + if (cmp !== 0) { + return cmp; + } + } + if (leftKeys.length === rightKeys.length) { + return 0; + } + return leftKeys.length < rightKeys.length ? -1 : 1; +} +/** + * @returns true if paths are the same. + */ +function pathEquals(path, other) { + if (pathGetLength(path) !== pathGetLength(other)) { + return false; + } + for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) { + if (path.pieces_[i] !== other.pieces_[j]) { + return false; + } + } + return true; +} +/** + * @returns True if this path is a parent of (or the same as) other + */ +function pathContains(path, other) { + let i = path.pieceNum_; + let j = other.pieceNum_; + if (pathGetLength(path) > pathGetLength(other)) { + return false; + } + while (i < path.pieces_.length) { + if (path.pieces_[i] !== other.pieces_[j]) { + return false; + } + ++i; + ++j; + } + return true; +} +/** + * Dynamic (mutable) path used to count path lengths. + * + * This class is used to efficiently check paths for valid + * length (in UTF8 bytes) and depth (used in path validation). + * + * Throws Error exception if path is ever invalid. + * + * The definition of a path always begins with '/'. + */ +class ValidationPath { + /** + * @param path - Initial Path. + * @param errorPrefix_ - Prefix for any error messages. + */ + constructor(path, errorPrefix_) { + this.errorPrefix_ = errorPrefix_; + this.parts_ = pathSlice(path, 0); + /** Initialize to number of '/' chars needed in path. */ + this.byteLength_ = Math.max(1, this.parts_.length); + for (let i = 0; i < this.parts_.length; i++) { + this.byteLength_ += util.stringLength(this.parts_[i]); + } + validationPathCheckValid(this); + } +} +function validationPathPush(validationPath, child) { + // Count the needed '/' + if (validationPath.parts_.length > 0) { + validationPath.byteLength_ += 1; + } + validationPath.parts_.push(child); + validationPath.byteLength_ += util.stringLength(child); + validationPathCheckValid(validationPath); +} +function validationPathPop(validationPath) { + const last = validationPath.parts_.pop(); + validationPath.byteLength_ -= util.stringLength(last); + // Un-count the previous '/' + if (validationPath.parts_.length > 0) { + validationPath.byteLength_ -= 1; + } +} +function validationPathCheckValid(validationPath) { + if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) { + throw new Error(validationPath.errorPrefix_ + + 'has a key path longer than ' + + MAX_PATH_LENGTH_BYTES + + ' bytes (' + + validationPath.byteLength_ + + ').'); + } + if (validationPath.parts_.length > MAX_PATH_DEPTH) { + throw new Error(validationPath.errorPrefix_ + + 'path specified exceeds the maximum depth that can be written (' + + MAX_PATH_DEPTH + + ') or object contains a cycle ' + + validationPathToErrorString(validationPath)); + } +} +/** + * String for use in error messages - uses '.' notation for path. + */ +function validationPathToErrorString(validationPath) { + if (validationPath.parts_.length === 0) { + return ''; + } + return "in property '" + validationPath.parts_.join('.') + "'"; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class VisibilityMonitor extends EventEmitter { + static getInstance() { + return new VisibilityMonitor(); + } + constructor() { + super(['visible']); + let hidden; + let visibilityChange; + if (typeof document !== 'undefined' && + typeof document.addEventListener !== 'undefined') { + if (typeof document['hidden'] !== 'undefined') { + // Opera 12.10 and Firefox 18 and later support + visibilityChange = 'visibilitychange'; + hidden = 'hidden'; + } + else if (typeof document['mozHidden'] !== 'undefined') { + visibilityChange = 'mozvisibilitychange'; + hidden = 'mozHidden'; + } + else if (typeof document['msHidden'] !== 'undefined') { + visibilityChange = 'msvisibilitychange'; + hidden = 'msHidden'; + } + else if (typeof document['webkitHidden'] !== 'undefined') { + visibilityChange = 'webkitvisibilitychange'; + hidden = 'webkitHidden'; + } + } + // Initially, we always assume we are visible. This ensures that in browsers + // without page visibility support or in cases where we are never visible + // (e.g. chrome extension), we act as if we are visible, i.e. don't delay + // reconnects + this.visible_ = true; + if (visibilityChange) { + document.addEventListener(visibilityChange, () => { + const visible = !document[hidden]; + if (visible !== this.visible_) { + this.visible_ = visible; + this.trigger('visible', visible); + } + }, false); + } + } + getInitialEvent(eventType) { + util.assert(eventType === 'visible', 'Unknown event type: ' + eventType); + return [this.visible_]; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const RECONNECT_MIN_DELAY = 1000; +const RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858) +const RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server) +const RECONNECT_DELAY_MULTIPLIER = 1.3; +const RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec. +const SERVER_KILL_INTERRUPT_REASON = 'server_kill'; +// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off. +const INVALID_TOKEN_THRESHOLD = 3; +/** + * Firebase connection. Abstracts wire protocol and handles reconnecting. + * + * NOTE: All JSON objects sent to the realtime connection must have property names enclosed + * in quotes to make sure the closure compiler does not minify them. + */ +class PersistentConnection extends ServerActions { + /** + * @param repoInfo_ - Data about the namespace we are connecting to + * @param applicationId_ - The Firebase App ID for this project + * @param onDataUpdate_ - A callback for new data from the server + */ + constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) { + super(); + this.repoInfo_ = repoInfo_; + this.applicationId_ = applicationId_; + this.onDataUpdate_ = onDataUpdate_; + this.onConnectStatus_ = onConnectStatus_; + this.onServerInfoUpdate_ = onServerInfoUpdate_; + this.authTokenProvider_ = authTokenProvider_; + this.appCheckTokenProvider_ = appCheckTokenProvider_; + this.authOverride_ = authOverride_; + // Used for diagnostic logging. + this.id = PersistentConnection.nextPersistentConnectionId_++; + this.log_ = logWrapper('p:' + this.id + ':'); + this.interruptReasons_ = {}; + this.listens = new Map(); + this.outstandingPuts_ = []; + this.outstandingGets_ = []; + this.outstandingPutCount_ = 0; + this.outstandingGetCount_ = 0; + this.onDisconnectRequestQueue_ = []; + this.connected_ = false; + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT; + this.securityDebugCallback_ = null; + this.lastSessionId = null; + this.establishConnectionTimer_ = null; + this.visible_ = false; + // Before we get connected, we keep a queue of pending messages to send. + this.requestCBHash_ = {}; + this.requestNumber_ = 0; + this.realtime_ = null; + this.authToken_ = null; + this.appCheckToken_ = null; + this.forceTokenRefresh_ = false; + this.invalidAuthTokenCount_ = 0; + this.invalidAppCheckTokenCount_ = 0; + this.firstConnection_ = true; + this.lastConnectionAttemptTime_ = null; + this.lastConnectionEstablishedTime_ = null; + if (authOverride_ && !util.isNodeSdk()) { + throw new Error('Auth override specified in options, but not supported on non Node.js platforms'); + } + VisibilityMonitor.getInstance().on('visible', this.onVisible_, this); + if (repoInfo_.host.indexOf('fblocal') === -1) { + OnlineMonitor.getInstance().on('online', this.onOnline_, this); + } + } + sendRequest(action, body, onResponse) { + const curReqNum = ++this.requestNumber_; + const msg = { r: curReqNum, a: action, b: body }; + this.log_(util.stringify(msg)); + util.assert(this.connected_, "sendRequest call when we're not connected not allowed."); + this.realtime_.sendRequest(msg); + if (onResponse) { + this.requestCBHash_[curReqNum] = onResponse; + } + } + get(query) { + this.initConnection_(); + const deferred = new util.Deferred(); + const request = { + p: query._path.toString(), + q: query._queryObject + }; + const outstandingGet = { + action: 'g', + request, + onComplete: (message) => { + const payload = message['d']; + if (message['s'] === 'ok') { + deferred.resolve(payload); + } + else { + deferred.reject(payload); + } + } + }; + this.outstandingGets_.push(outstandingGet); + this.outstandingGetCount_++; + const index = this.outstandingGets_.length - 1; + if (this.connected_) { + this.sendGet_(index); + } + return deferred.promise; + } + listen(query, currentHashFn, tag, onComplete) { + this.initConnection_(); + const queryId = query._queryIdentifier; + const pathString = query._path.toString(); + this.log_('Listen called for ' + pathString + ' ' + queryId); + if (!this.listens.has(pathString)) { + this.listens.set(pathString, new Map()); + } + util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query'); + util.assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`); + const listenSpec = { + onComplete, + hashFn: currentHashFn, + query, + tag + }; + this.listens.get(pathString).set(queryId, listenSpec); + if (this.connected_) { + this.sendListen_(listenSpec); + } + } + sendGet_(index) { + const get = this.outstandingGets_[index]; + this.sendRequest('g', get.request, (message) => { + delete this.outstandingGets_[index]; + this.outstandingGetCount_--; + if (this.outstandingGetCount_ === 0) { + this.outstandingGets_ = []; + } + if (get.onComplete) { + get.onComplete(message); + } + }); + } + sendListen_(listenSpec) { + const query = listenSpec.query; + const pathString = query._path.toString(); + const queryId = query._queryIdentifier; + this.log_('Listen on ' + pathString + ' for ' + queryId); + const req = { /*path*/ p: pathString }; + const action = 'q'; + // Only bother to send query if it's non-default. + if (listenSpec.tag) { + req['q'] = query._queryObject; + req['t'] = listenSpec.tag; + } + req[ /*hash*/'h'] = listenSpec.hashFn(); + this.sendRequest(action, req, (message) => { + const payload = message[ /*data*/'d']; + const status = message[ /*status*/'s']; + // print warnings in any case... + PersistentConnection.warnOnListenWarnings_(payload, query); + const currentListenSpec = this.listens.get(pathString) && + this.listens.get(pathString).get(queryId); + // only trigger actions if the listen hasn't been removed and readded + if (currentListenSpec === listenSpec) { + this.log_('listen response', message); + if (status !== 'ok') { + this.removeListen_(pathString, queryId); + } + if (listenSpec.onComplete) { + listenSpec.onComplete(status, payload); + } + } + }); + } + static warnOnListenWarnings_(payload, query) { + if (payload && typeof payload === 'object' && util.contains(payload, 'w')) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const warnings = util.safeGet(payload, 'w'); + if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) { + const indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"'; + const indexPath = query._path.toString(); + warn(`Using an unspecified index. Your data will be downloaded and ` + + `filtered on the client. Consider adding ${indexSpec} at ` + + `${indexPath} to your security rules for better performance.`); + } + } + } + refreshAuthToken(token) { + this.authToken_ = token; + this.log_('Auth token refreshed'); + if (this.authToken_) { + this.tryAuth(); + } + else { + //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete + //the credential so we dont become authenticated next time we connect. + if (this.connected_) { + this.sendRequest('unauth', {}, () => { }); + } + } + this.reduceReconnectDelayIfAdminCredential_(token); + } + reduceReconnectDelayIfAdminCredential_(credential) { + // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client). + // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires. + const isFirebaseSecret = credential && credential.length === 40; + if (isFirebaseSecret || util.isAdmin(credential)) { + this.log_('Admin auth credential detected. Reducing max reconnect time.'); + this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS; + } + } + refreshAppCheckToken(token) { + this.appCheckToken_ = token; + this.log_('App check token refreshed'); + if (this.appCheckToken_) { + this.tryAppCheck(); + } + else { + //If we're connected we want to let the server know to unauthenticate us. + //If we're not connected, simply delete the credential so we dont become + // authenticated next time we connect. + if (this.connected_) { + this.sendRequest('unappeck', {}, () => { }); + } + } + } + /** + * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like + * a auth revoked (the connection is closed). + */ + tryAuth() { + if (this.connected_ && this.authToken_) { + const token = this.authToken_; + const authMethod = util.isValidFormat(token) ? 'auth' : 'gauth'; + const requestData = { cred: token }; + if (this.authOverride_ === null) { + requestData['noauth'] = true; + } + else if (typeof this.authOverride_ === 'object') { + requestData['authvar'] = this.authOverride_; + } + this.sendRequest(authMethod, requestData, (res) => { + const status = res[ /*status*/'s']; + const data = res[ /*data*/'d'] || 'error'; + if (this.authToken_ === token) { + if (status === 'ok') { + this.invalidAuthTokenCount_ = 0; + } + else { + // Triggers reconnect and force refresh for auth token + this.onAuthRevoked_(status, data); + } + } + }); + } + } + /** + * Attempts to authenticate with the given token. If the authentication + * attempt fails, it's triggered like the token was revoked (the connection is + * closed). + */ + tryAppCheck() { + if (this.connected_ && this.appCheckToken_) { + this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => { + const status = res[ /*status*/'s']; + const data = res[ /*data*/'d'] || 'error'; + if (status === 'ok') { + this.invalidAppCheckTokenCount_ = 0; + } + else { + this.onAppCheckRevoked_(status, data); + } + }); + } + } + /** + * @inheritDoc + */ + unlisten(query, tag) { + const pathString = query._path.toString(); + const queryId = query._queryIdentifier; + this.log_('Unlisten called for ' + pathString + ' ' + queryId); + util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query'); + const listen = this.removeListen_(pathString, queryId); + if (listen && this.connected_) { + this.sendUnlisten_(pathString, queryId, query._queryObject, tag); + } + } + sendUnlisten_(pathString, queryId, queryObj, tag) { + this.log_('Unlisten on ' + pathString + ' for ' + queryId); + const req = { /*path*/ p: pathString }; + const action = 'n'; + // Only bother sending queryId if it's non-default. + if (tag) { + req['q'] = queryObj; + req['t'] = tag; + } + this.sendRequest(action, req); + } + onDisconnectPut(pathString, data, onComplete) { + this.initConnection_(); + if (this.connected_) { + this.sendOnDisconnect_('o', pathString, data, onComplete); + } + else { + this.onDisconnectRequestQueue_.push({ + pathString, + action: 'o', + data, + onComplete + }); + } + } + onDisconnectMerge(pathString, data, onComplete) { + this.initConnection_(); + if (this.connected_) { + this.sendOnDisconnect_('om', pathString, data, onComplete); + } + else { + this.onDisconnectRequestQueue_.push({ + pathString, + action: 'om', + data, + onComplete + }); + } + } + onDisconnectCancel(pathString, onComplete) { + this.initConnection_(); + if (this.connected_) { + this.sendOnDisconnect_('oc', pathString, null, onComplete); + } + else { + this.onDisconnectRequestQueue_.push({ + pathString, + action: 'oc', + data: null, + onComplete + }); + } + } + sendOnDisconnect_(action, pathString, data, onComplete) { + const request = { /*path*/ p: pathString, /*data*/ d: data }; + this.log_('onDisconnect ' + action, request); + this.sendRequest(action, request, (response) => { + if (onComplete) { + setTimeout(() => { + onComplete(response[ /*status*/'s'], response[ /* data */'d']); + }, Math.floor(0)); + } + }); + } + put(pathString, data, onComplete, hash) { + this.putInternal('p', pathString, data, onComplete, hash); + } + merge(pathString, data, onComplete, hash) { + this.putInternal('m', pathString, data, onComplete, hash); + } + putInternal(action, pathString, data, onComplete, hash) { + this.initConnection_(); + const request = { + /*path*/ p: pathString, + /*data*/ d: data + }; + if (hash !== undefined) { + request[ /*hash*/'h'] = hash; + } + // TODO: Only keep track of the most recent put for a given path? + this.outstandingPuts_.push({ + action, + request, + onComplete + }); + this.outstandingPutCount_++; + const index = this.outstandingPuts_.length - 1; + if (this.connected_) { + this.sendPut_(index); + } + else { + this.log_('Buffering put: ' + pathString); + } + } + sendPut_(index) { + const action = this.outstandingPuts_[index].action; + const request = this.outstandingPuts_[index].request; + const onComplete = this.outstandingPuts_[index].onComplete; + this.outstandingPuts_[index].queued = this.connected_; + this.sendRequest(action, request, (message) => { + this.log_(action + ' response', message); + delete this.outstandingPuts_[index]; + this.outstandingPutCount_--; + // Clean up array occasionally. + if (this.outstandingPutCount_ === 0) { + this.outstandingPuts_ = []; + } + if (onComplete) { + onComplete(message[ /*status*/'s'], message[ /* data */'d']); + } + }); + } + reportStats(stats) { + // If we're not connected, we just drop the stats. + if (this.connected_) { + const request = { /*counters*/ c: stats }; + this.log_('reportStats', request); + this.sendRequest(/*stats*/ 's', request, result => { + const status = result[ /*status*/'s']; + if (status !== 'ok') { + const errorReason = result[ /* data */'d']; + this.log_('reportStats', 'Error sending stats: ' + errorReason); + } + }); + } + } + onDataMessage_(message) { + if ('r' in message) { + // this is a response + this.log_('from server: ' + util.stringify(message)); + const reqNum = message['r']; + const onResponse = this.requestCBHash_[reqNum]; + if (onResponse) { + delete this.requestCBHash_[reqNum]; + onResponse(message[ /*body*/'b']); + } + } + else if ('error' in message) { + throw 'A server-side error has occurred: ' + message['error']; + } + else if ('a' in message) { + // a and b are action and body, respectively + this.onDataPush_(message['a'], message['b']); + } + } + onDataPush_(action, body) { + this.log_('handleServerMessage', action, body); + if (action === 'd') { + this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], + /*isMerge*/ false, body['t']); + } + else if (action === 'm') { + this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], + /*isMerge=*/ true, body['t']); + } + else if (action === 'c') { + this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']); + } + else if (action === 'ac') { + this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']); + } + else if (action === 'apc') { + this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']); + } + else if (action === 'sd') { + this.onSecurityDebugPacket_(body); + } + else { + error('Unrecognized action received from server: ' + + util.stringify(action) + + '\nAre you using the latest client?'); + } + } + onReady_(timestamp, sessionId) { + this.log_('connection ready'); + this.connected_ = true; + this.lastConnectionEstablishedTime_ = new Date().getTime(); + this.handleTimestamp_(timestamp); + this.lastSessionId = sessionId; + if (this.firstConnection_) { + this.sendConnectStats_(); + } + this.restoreState_(); + this.firstConnection_ = false; + this.onConnectStatus_(true); + } + scheduleConnect_(timeout) { + util.assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?"); + if (this.establishConnectionTimer_) { + clearTimeout(this.establishConnectionTimer_); + } + // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in + // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests). + this.establishConnectionTimer_ = setTimeout(() => { + this.establishConnectionTimer_ = null; + this.establishConnection_(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(timeout)); + } + initConnection_() { + if (!this.realtime_ && this.firstConnection_) { + this.scheduleConnect_(0); + } + } + onVisible_(visible) { + // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine. + if (visible && + !this.visible_ && + this.reconnectDelay_ === this.maxReconnectDelay_) { + this.log_('Window became visible. Reducing delay.'); + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + if (!this.realtime_) { + this.scheduleConnect_(0); + } + } + this.visible_ = visible; + } + onOnline_(online) { + if (online) { + this.log_('Browser went online.'); + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + if (!this.realtime_) { + this.scheduleConnect_(0); + } + } + else { + this.log_('Browser went offline. Killing connection.'); + if (this.realtime_) { + this.realtime_.close(); + } + } + } + onRealtimeDisconnect_() { + this.log_('data client disconnected'); + this.connected_ = false; + this.realtime_ = null; + // Since we don't know if our sent transactions succeeded or not, we need to cancel them. + this.cancelSentTransactions_(); + // Clear out the pending requests. + this.requestCBHash_ = {}; + if (this.shouldReconnect_()) { + if (!this.visible_) { + this.log_("Window isn't visible. Delaying reconnect."); + this.reconnectDelay_ = this.maxReconnectDelay_; + this.lastConnectionAttemptTime_ = new Date().getTime(); + } + else if (this.lastConnectionEstablishedTime_) { + // If we've been connected long enough, reset reconnect delay to minimum. + const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_; + if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) { + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + } + this.lastConnectionEstablishedTime_ = null; + } + const timeSinceLastConnectAttempt = Math.max(0, new Date().getTime() - this.lastConnectionAttemptTime_); + let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt); + reconnectDelay = Math.random() * reconnectDelay; + this.log_('Trying to reconnect in ' + reconnectDelay + 'ms'); + this.scheduleConnect_(reconnectDelay); + // Adjust reconnect delay for next time. + this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER); + } + this.onConnectStatus_(false); + } + async establishConnection_() { + if (this.shouldReconnect_()) { + this.log_('Making a connection attempt'); + this.lastConnectionAttemptTime_ = new Date().getTime(); + this.lastConnectionEstablishedTime_ = null; + const onDataMessage = this.onDataMessage_.bind(this); + const onReady = this.onReady_.bind(this); + const onDisconnect = this.onRealtimeDisconnect_.bind(this); + const connId = this.id + ':' + PersistentConnection.nextConnectionId_++; + const lastSessionId = this.lastSessionId; + let canceled = false; + let connection = null; + const closeFn = function () { + if (connection) { + connection.close(); + } + else { + canceled = true; + onDisconnect(); + } + }; + const sendRequestFn = function (msg) { + util.assert(connection, "sendRequest call when we're not connected not allowed."); + connection.sendRequest(msg); + }; + this.realtime_ = { + close: closeFn, + sendRequest: sendRequestFn + }; + const forceRefresh = this.forceTokenRefresh_; + this.forceTokenRefresh_ = false; + try { + // First fetch auth and app check token, and establish connection after + // fetching the token was successful + const [authToken, appCheckToken] = await Promise.all([ + this.authTokenProvider_.getToken(forceRefresh), + this.appCheckTokenProvider_.getToken(forceRefresh) + ]); + if (!canceled) { + log('getToken() completed. Creating connection.'); + this.authToken_ = authToken && authToken.accessToken; + this.appCheckToken_ = appCheckToken && appCheckToken.token; + connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect, + /* onKill= */ reason => { + warn(reason + ' (' + this.repoInfo_.toString() + ')'); + this.interrupt(SERVER_KILL_INTERRUPT_REASON); + }, lastSessionId); + } + else { + log('getToken() completed but was canceled'); + } + } + catch (error) { + this.log_('Failed to get token: ' + error); + if (!canceled) { + if (this.repoInfo_.nodeAdmin) { + // This may be a critical error for the Admin Node.js SDK, so log a warning. + // But getToken() may also just have temporarily failed, so we still want to + // continue retrying. + warn(error); + } + closeFn(); + } + } + } + } + interrupt(reason) { + log('Interrupting connection for reason: ' + reason); + this.interruptReasons_[reason] = true; + if (this.realtime_) { + this.realtime_.close(); + } + else { + if (this.establishConnectionTimer_) { + clearTimeout(this.establishConnectionTimer_); + this.establishConnectionTimer_ = null; + } + if (this.connected_) { + this.onRealtimeDisconnect_(); + } + } + } + resume(reason) { + log('Resuming connection for reason: ' + reason); + delete this.interruptReasons_[reason]; + if (util.isEmpty(this.interruptReasons_)) { + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + if (!this.realtime_) { + this.scheduleConnect_(0); + } + } + } + handleTimestamp_(timestamp) { + const delta = timestamp - new Date().getTime(); + this.onServerInfoUpdate_({ serverTimeOffset: delta }); + } + cancelSentTransactions_() { + for (let i = 0; i < this.outstandingPuts_.length; i++) { + const put = this.outstandingPuts_[i]; + if (put && /*hash*/ 'h' in put.request && put.queued) { + if (put.onComplete) { + put.onComplete('disconnect'); + } + delete this.outstandingPuts_[i]; + this.outstandingPutCount_--; + } + } + // Clean up array occasionally. + if (this.outstandingPutCount_ === 0) { + this.outstandingPuts_ = []; + } + } + onListenRevoked_(pathString, query) { + // Remove the listen and manufacture a "permission_denied" error for the failed listen. + let queryId; + if (!query) { + queryId = 'default'; + } + else { + queryId = query.map(q => ObjectToUniqueKey(q)).join('$'); + } + const listen = this.removeListen_(pathString, queryId); + if (listen && listen.onComplete) { + listen.onComplete('permission_denied'); + } + } + removeListen_(pathString, queryId) { + const normalizedPathString = new Path(pathString).toString(); // normalize path. + let listen; + if (this.listens.has(normalizedPathString)) { + const map = this.listens.get(normalizedPathString); + listen = map.get(queryId); + map.delete(queryId); + if (map.size === 0) { + this.listens.delete(normalizedPathString); + } + } + else { + // all listens for this path has already been removed + listen = undefined; + } + return listen; + } + onAuthRevoked_(statusCode, explanation) { + log('Auth token revoked: ' + statusCode + '/' + explanation); + this.authToken_ = null; + this.forceTokenRefresh_ = true; + this.realtime_.close(); + if (statusCode === 'invalid_token' || statusCode === 'permission_denied') { + // We'll wait a couple times before logging the warning / increasing the + // retry period since oauth tokens will report as "invalid" if they're + // just expired. Plus there may be transient issues that resolve themselves. + this.invalidAuthTokenCount_++; + if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) { + // Set a long reconnect delay because recovery is unlikely + this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS; + // Notify the auth token provider that the token is invalid, which will log + // a warning + this.authTokenProvider_.notifyForInvalidToken(); + } + } + } + onAppCheckRevoked_(statusCode, explanation) { + log('App check token revoked: ' + statusCode + '/' + explanation); + this.appCheckToken_ = null; + this.forceTokenRefresh_ = true; + // Note: We don't close the connection as the developer may not have + // enforcement enabled. The backend closes connections with enforcements. + if (statusCode === 'invalid_token' || statusCode === 'permission_denied') { + // We'll wait a couple times before logging the warning / increasing the + // retry period since oauth tokens will report as "invalid" if they're + // just expired. Plus there may be transient issues that resolve themselves. + this.invalidAppCheckTokenCount_++; + if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) { + this.appCheckTokenProvider_.notifyForInvalidToken(); + } + } + } + onSecurityDebugPacket_(body) { + if (this.securityDebugCallback_) { + this.securityDebugCallback_(body); + } + else { + if ('msg' in body) { + console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: ')); + } + } + } + restoreState_() { + //Re-authenticate ourselves if we have a credential stored. + this.tryAuth(); + this.tryAppCheck(); + // Puts depend on having received the corresponding data update from the server before they complete, so we must + // make sure to send listens before puts. + for (const queries of this.listens.values()) { + for (const listenSpec of queries.values()) { + this.sendListen_(listenSpec); + } + } + for (let i = 0; i < this.outstandingPuts_.length; i++) { + if (this.outstandingPuts_[i]) { + this.sendPut_(i); + } + } + while (this.onDisconnectRequestQueue_.length) { + const request = this.onDisconnectRequestQueue_.shift(); + this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete); + } + for (let i = 0; i < this.outstandingGets_.length; i++) { + if (this.outstandingGets_[i]) { + this.sendGet_(i); + } + } + } + /** + * Sends client stats for first connection + */ + sendConnectStats_() { + const stats = {}; + let clientName = 'js'; + if (util.isNodeSdk()) { + if (this.repoInfo_.nodeAdmin) { + clientName = 'admin_node'; + } + else { + clientName = 'node'; + } + } + stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1; + if (util.isMobileCordova()) { + stats['framework.cordova'] = 1; + } + else if (util.isReactNative()) { + stats['framework.reactnative'] = 1; + } + this.reportStats(stats); + } + shouldReconnect_() { + const online = OnlineMonitor.getInstance().currentlyOnline(); + return util.isEmpty(this.interruptReasons_) && online; + } +} +PersistentConnection.nextPersistentConnectionId_ = 0; +/** + * Counter for number of connections created. Mainly used for tagging in the logs + */ +PersistentConnection.nextConnectionId_ = 0; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class NamedNode { + constructor(name, node) { + this.name = name; + this.node = node; + } + static Wrap(name, node) { + return new NamedNode(name, node); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Index { + /** + * @returns A standalone comparison function for + * this index + */ + getCompare() { + return this.compare.bind(this); + } + /** + * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different, + * it's possible that the changes are isolated to parts of the snapshot that are not indexed. + * + * + * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode + */ + indexedValueChanged(oldNode, newNode) { + const oldWrapped = new NamedNode(MIN_NAME, oldNode); + const newWrapped = new NamedNode(MIN_NAME, newNode); + return this.compare(oldWrapped, newWrapped) !== 0; + } + /** + * @returns a node wrapper that will sort equal to or less than + * any other node wrapper, using this index + */ + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let __EMPTY_NODE; +class KeyIndex extends Index { + static get __EMPTY_NODE() { + return __EMPTY_NODE; + } + static set __EMPTY_NODE(val) { + __EMPTY_NODE = val; + } + compare(a, b) { + return nameCompare(a.name, b.name); + } + isDefinedOn(node) { + // We could probably return true here (since every node has a key), but it's never called + // so just leaving unimplemented for now. + throw util.assertionError('KeyIndex.isDefinedOn not expected to be called.'); + } + indexedValueChanged(oldNode, newNode) { + return false; // The key for a node never changes. + } + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } + maxPost() { + // TODO: This should really be created once and cached in a static property, but + // NamedNode isn't defined yet, so I can't use it in a static. Bleh. + return new NamedNode(MAX_NAME, __EMPTY_NODE); + } + makePost(indexValue, name) { + util.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.'); + // We just use empty node, but it'll never be compared, since our comparator only looks at name. + return new NamedNode(indexValue, __EMPTY_NODE); + } + /** + * @returns String representation for inclusion in a query spec + */ + toString() { + return '.key'; + } +} +const KEY_INDEX = new KeyIndex(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An iterator over an LLRBNode. + */ +class SortedMapIterator { + /** + * @param node - Node to iterate. + * @param isReverse_ - Whether or not to iterate in reverse + */ + constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) { + this.isReverse_ = isReverse_; + this.resultGenerator_ = resultGenerator_; + this.nodeStack_ = []; + let cmp = 1; + while (!node.isEmpty()) { + node = node; + cmp = startKey ? comparator(node.key, startKey) : 1; + // flip the comparison if we're going in reverse + if (isReverse_) { + cmp *= -1; + } + if (cmp < 0) { + // This node is less than our start key. ignore it + if (this.isReverse_) { + node = node.left; + } + else { + node = node.right; + } + } + else if (cmp === 0) { + // This node is exactly equal to our start key. Push it on the stack, but stop iterating; + this.nodeStack_.push(node); + break; + } + else { + // This node is greater than our start key, add it to the stack and move to the next one + this.nodeStack_.push(node); + if (this.isReverse_) { + node = node.right; + } + else { + node = node.left; + } + } + } + } + getNext() { + if (this.nodeStack_.length === 0) { + return null; + } + let node = this.nodeStack_.pop(); + let result; + if (this.resultGenerator_) { + result = this.resultGenerator_(node.key, node.value); + } + else { + result = { key: node.key, value: node.value }; + } + if (this.isReverse_) { + node = node.left; + while (!node.isEmpty()) { + this.nodeStack_.push(node); + node = node.right; + } + } + else { + node = node.right; + while (!node.isEmpty()) { + this.nodeStack_.push(node); + node = node.left; + } + } + return result; + } + hasNext() { + return this.nodeStack_.length > 0; + } + peek() { + if (this.nodeStack_.length === 0) { + return null; + } + const node = this.nodeStack_[this.nodeStack_.length - 1]; + if (this.resultGenerator_) { + return this.resultGenerator_(node.key, node.value); + } + else { + return { key: node.key, value: node.value }; + } + } +} +/** + * Represents a node in a Left-leaning Red-Black tree. + */ +class LLRBNode { + /** + * @param key - Key associated with this node. + * @param value - Value associated with this node. + * @param color - Whether this node is red. + * @param left - Left child. + * @param right - Right child. + */ + constructor(key, value, color, left, right) { + this.key = key; + this.value = value; + this.color = color != null ? color : LLRBNode.RED; + this.left = + left != null ? left : SortedMap.EMPTY_NODE; + this.right = + right != null ? right : SortedMap.EMPTY_NODE; + } + /** + * Returns a copy of the current node, optionally replacing pieces of it. + * + * @param key - New key for the node, or null. + * @param value - New value for the node, or null. + * @param color - New color for the node, or null. + * @param left - New left child for the node, or null. + * @param right - New right child for the node, or null. + * @returns The node copy. + */ + copy(key, value, color, left, right) { + return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right); + } + /** + * @returns The total number of nodes in the tree. + */ + count() { + return this.left.count() + 1 + this.right.count(); + } + /** + * @returns True if the tree is empty. + */ + isEmpty() { + return false; + } + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action) { + return (this.left.inorderTraversal(action) || + !!action(this.key, this.value) || + this.right.inorderTraversal(action)); + } + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action) { + return (this.right.reverseTraversal(action) || + action(this.key, this.value) || + this.left.reverseTraversal(action)); + } + /** + * @returns The minimum node in the tree. + */ + min_() { + if (this.left.isEmpty()) { + return this; + } + else { + return this.left.min_(); + } + } + /** + * @returns The maximum key in the tree. + */ + minKey() { + return this.min_().key; + } + /** + * @returns The maximum key in the tree. + */ + maxKey() { + if (this.right.isEmpty()) { + return this.key; + } + else { + return this.right.maxKey(); + } + } + /** + * @param key - Key to insert. + * @param value - Value to insert. + * @param comparator - Comparator. + * @returns New tree, with the key/value added. + */ + insert(key, value, comparator) { + let n = this; + const cmp = comparator(key, n.key); + if (cmp < 0) { + n = n.copy(null, null, null, n.left.insert(key, value, comparator), null); + } + else if (cmp === 0) { + n = n.copy(null, value, null, null, null); + } + else { + n = n.copy(null, null, null, null, n.right.insert(key, value, comparator)); + } + return n.fixUp_(); + } + /** + * @returns New tree, with the minimum key removed. + */ + removeMin_() { + if (this.left.isEmpty()) { + return SortedMap.EMPTY_NODE; + } + let n = this; + if (!n.left.isRed_() && !n.left.left.isRed_()) { + n = n.moveRedLeft_(); + } + n = n.copy(null, null, null, n.left.removeMin_(), null); + return n.fixUp_(); + } + /** + * @param key - The key of the item to remove. + * @param comparator - Comparator. + * @returns New tree, with the specified item removed. + */ + remove(key, comparator) { + let n, smallest; + n = this; + if (comparator(key, n.key) < 0) { + if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) { + n = n.moveRedLeft_(); + } + n = n.copy(null, null, null, n.left.remove(key, comparator), null); + } + else { + if (n.left.isRed_()) { + n = n.rotateRight_(); + } + if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) { + n = n.moveRedRight_(); + } + if (comparator(key, n.key) === 0) { + if (n.right.isEmpty()) { + return SortedMap.EMPTY_NODE; + } + else { + smallest = n.right.min_(); + n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_()); + } + } + n = n.copy(null, null, null, null, n.right.remove(key, comparator)); + } + return n.fixUp_(); + } + /** + * @returns Whether this is a RED node. + */ + isRed_() { + return this.color; + } + /** + * @returns New tree after performing any needed rotations. + */ + fixUp_() { + let n = this; + if (n.right.isRed_() && !n.left.isRed_()) { + n = n.rotateLeft_(); + } + if (n.left.isRed_() && n.left.left.isRed_()) { + n = n.rotateRight_(); + } + if (n.left.isRed_() && n.right.isRed_()) { + n = n.colorFlip_(); + } + return n; + } + /** + * @returns New tree, after moveRedLeft. + */ + moveRedLeft_() { + let n = this.colorFlip_(); + if (n.right.left.isRed_()) { + n = n.copy(null, null, null, null, n.right.rotateRight_()); + n = n.rotateLeft_(); + n = n.colorFlip_(); + } + return n; + } + /** + * @returns New tree, after moveRedRight. + */ + moveRedRight_() { + let n = this.colorFlip_(); + if (n.left.left.isRed_()) { + n = n.rotateRight_(); + n = n.colorFlip_(); + } + return n; + } + /** + * @returns New tree, after rotateLeft. + */ + rotateLeft_() { + const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, nl, null); + } + /** + * @returns New tree, after rotateRight. + */ + rotateRight_() { + const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, nr); + } + /** + * @returns Newt ree, after colorFlip. + */ + colorFlip_() { + const left = this.left.copy(null, null, !this.left.color, null, null); + const right = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, left, right); + } + /** + * For testing. + * + * @returns True if all is well. + */ + checkMaxDepth_() { + const blackDepth = this.check_(); + return Math.pow(2.0, blackDepth) <= this.count() + 1; + } + check_() { + if (this.isRed_() && this.left.isRed_()) { + throw new Error('Red node has red child(' + this.key + ',' + this.value + ')'); + } + if (this.right.isRed_()) { + throw new Error('Right child of (' + this.key + ',' + this.value + ') is red'); + } + const blackDepth = this.left.check_(); + if (blackDepth !== this.right.check_()) { + throw new Error('Black depths differ'); + } + else { + return blackDepth + (this.isRed_() ? 0 : 1); + } + } +} +LLRBNode.RED = true; +LLRBNode.BLACK = false; +/** + * Represents an empty node (a leaf node in the Red-Black Tree). + */ +class LLRBEmptyNode { + /** + * Returns a copy of the current node. + * + * @returns The node copy. + */ + copy(key, value, color, left, right) { + return this; + } + /** + * Returns a copy of the tree, with the specified key/value added. + * + * @param key - Key to be added. + * @param value - Value to be added. + * @param comparator - Comparator. + * @returns New tree, with item added. + */ + insert(key, value, comparator) { + return new LLRBNode(key, value, null); + } + /** + * Returns a copy of the tree, with the specified key removed. + * + * @param key - The key to remove. + * @param comparator - Comparator. + * @returns New tree, with item removed. + */ + remove(key, comparator) { + return this; + } + /** + * @returns The total number of nodes in the tree. + */ + count() { + return 0; + } + /** + * @returns True if the tree is empty. + */ + isEmpty() { + return true; + } + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + inorderTraversal(action) { + return false; + } + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action) { + return false; + } + minKey() { + return null; + } + maxKey() { + return null; + } + check_() { + return 0; + } + /** + * @returns Whether this node is red. + */ + isRed_() { + return false; + } +} +/** + * An immutable sorted map implementation, based on a Left-leaning Red-Black + * tree. + */ +class SortedMap { + /** + * @param comparator_ - Key comparator. + * @param root_ - Optional root node for the map. + */ + constructor(comparator_, root_ = SortedMap.EMPTY_NODE) { + this.comparator_ = comparator_; + this.root_ = root_; + } + /** + * Returns a copy of the map, with the specified key/value added or replaced. + * (TODO: We should perhaps rename this method to 'put') + * + * @param key - Key to be added. + * @param value - Value to be added. + * @returns New map, with item added. + */ + insert(key, value) { + return new SortedMap(this.comparator_, this.root_ + .insert(key, value, this.comparator_) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + /** + * Returns a copy of the map, with the specified key removed. + * + * @param key - The key to remove. + * @returns New map, with item removed. + */ + remove(key) { + return new SortedMap(this.comparator_, this.root_ + .remove(key, this.comparator_) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + /** + * Returns the value of the node with the given key, or null. + * + * @param key - The key to look up. + * @returns The value of the node with the given key, or null if the + * key doesn't exist. + */ + get(key) { + let cmp; + let node = this.root_; + while (!node.isEmpty()) { + cmp = this.comparator_(key, node.key); + if (cmp === 0) { + return node.value; + } + else if (cmp < 0) { + node = node.left; + } + else if (cmp > 0) { + node = node.right; + } + } + return null; + } + /** + * Returns the key of the item *before* the specified key, or null if key is the first item. + * @param key - The key to find the predecessor of + * @returns The predecessor key. + */ + getPredecessorKey(key) { + let cmp, node = this.root_, rightParent = null; + while (!node.isEmpty()) { + cmp = this.comparator_(key, node.key); + if (cmp === 0) { + if (!node.left.isEmpty()) { + node = node.left; + while (!node.right.isEmpty()) { + node = node.right; + } + return node.key; + } + else if (rightParent) { + return rightParent.key; + } + else { + return null; // first item. + } + } + else if (cmp < 0) { + node = node.left; + } + else if (cmp > 0) { + rightParent = node; + node = node.right; + } + } + throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?'); + } + /** + * @returns True if the map is empty. + */ + isEmpty() { + return this.root_.isEmpty(); + } + /** + * @returns The total number of nodes in the map. + */ + count() { + return this.root_.count(); + } + /** + * @returns The minimum key in the map. + */ + minKey() { + return this.root_.minKey(); + } + /** + * @returns The maximum key in the map. + */ + maxKey() { + return this.root_.maxKey(); + } + /** + * Traverses the map in key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action) { + return this.root_.inorderTraversal(action); + } + /** + * Traverses the map in reverse key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns True if the traversal was aborted. + */ + reverseTraversal(action) { + return this.root_.reverseTraversal(action); + } + /** + * Returns an iterator over the SortedMap. + * @returns The iterator. + */ + getIterator(resultGenerator) { + return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator); + } + getIteratorFrom(key, resultGenerator) { + return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator); + } + getReverseIteratorFrom(key, resultGenerator) { + return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator); + } + getReverseIterator(resultGenerator) { + return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator); + } +} +/** + * Always use the same empty node, to reduce memory. + */ +SortedMap.EMPTY_NODE = new LLRBEmptyNode(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function NAME_ONLY_COMPARATOR(left, right) { + return nameCompare(left.name, right.name); +} +function NAME_COMPARATOR(left, right) { + return nameCompare(left, right); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let MAX_NODE$2; +function setMaxNode$1(val) { + MAX_NODE$2 = val; +} +const priorityHashText = function (priority) { + if (typeof priority === 'number') { + return 'number:' + doubleToIEEE754String(priority); + } + else { + return 'string:' + priority; + } +}; +/** + * Validates that a priority snapshot Node is valid. + */ +const validatePriorityNode = function (priorityNode) { + if (priorityNode.isLeafNode()) { + const val = priorityNode.val(); + util.assert(typeof val === 'string' || + typeof val === 'number' || + (typeof val === 'object' && util.contains(val, '.sv')), 'Priority must be a string or number.'); + } + else { + util.assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.'); + } + // Don't call getPriority() on MAX_NODE to avoid hitting assertion. + util.assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own."); +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let __childrenNodeConstructor; +/** + * LeafNode is a class for storing leaf nodes in a DataSnapshot. It + * implements Node and stores the value of the node (a string, + * number, or boolean) accessible via getValue(). + */ +class LeafNode { + static set __childrenNodeConstructor(val) { + __childrenNodeConstructor = val; + } + static get __childrenNodeConstructor() { + return __childrenNodeConstructor; + } + /** + * @param value_ - The value to store in this leaf node. The object type is + * possible in the event of a deferred value + * @param priorityNode_ - The priority of this node. + */ + constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) { + this.value_ = value_; + this.priorityNode_ = priorityNode_; + this.lazyHash_ = null; + util.assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value."); + validatePriorityNode(this.priorityNode_); + } + /** @inheritDoc */ + isLeafNode() { + return true; + } + /** @inheritDoc */ + getPriority() { + return this.priorityNode_; + } + /** @inheritDoc */ + updatePriority(newPriorityNode) { + return new LeafNode(this.value_, newPriorityNode); + } + /** @inheritDoc */ + getImmediateChild(childName) { + // Hack to treat priority as a regular child + if (childName === '.priority') { + return this.priorityNode_; + } + else { + return LeafNode.__childrenNodeConstructor.EMPTY_NODE; + } + } + /** @inheritDoc */ + getChild(path) { + if (pathIsEmpty(path)) { + return this; + } + else if (pathGetFront(path) === '.priority') { + return this.priorityNode_; + } + else { + return LeafNode.__childrenNodeConstructor.EMPTY_NODE; + } + } + hasChild() { + return false; + } + /** @inheritDoc */ + getPredecessorChildName(childName, childNode) { + return null; + } + /** @inheritDoc */ + updateImmediateChild(childName, newChildNode) { + if (childName === '.priority') { + return this.updatePriority(newChildNode); + } + else if (newChildNode.isEmpty() && childName !== '.priority') { + return this; + } + else { + return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_); + } + } + /** @inheritDoc */ + updateChild(path, newChildNode) { + const front = pathGetFront(path); + if (front === null) { + return newChildNode; + } + else if (newChildNode.isEmpty() && front !== '.priority') { + return this; + } + else { + util.assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path'); + return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode)); + } + } + /** @inheritDoc */ + isEmpty() { + return false; + } + /** @inheritDoc */ + numChildren() { + return 0; + } + /** @inheritDoc */ + forEachChild(index, action) { + return false; + } + val(exportFormat) { + if (exportFormat && !this.getPriority().isEmpty()) { + return { + '.value': this.getValue(), + '.priority': this.getPriority().val() + }; + } + else { + return this.getValue(); + } + } + /** @inheritDoc */ + hash() { + if (this.lazyHash_ === null) { + let toHash = ''; + if (!this.priorityNode_.isEmpty()) { + toHash += + 'priority:' + + priorityHashText(this.priorityNode_.val()) + + ':'; + } + const type = typeof this.value_; + toHash += type + ':'; + if (type === 'number') { + toHash += doubleToIEEE754String(this.value_); + } + else { + toHash += this.value_; + } + this.lazyHash_ = sha1(toHash); + } + return this.lazyHash_; + } + /** + * Returns the value of the leaf node. + * @returns The value of the node. + */ + getValue() { + return this.value_; + } + compareTo(other) { + if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) { + return 1; + } + else if (other instanceof LeafNode.__childrenNodeConstructor) { + return -1; + } + else { + util.assert(other.isLeafNode(), 'Unknown node type'); + return this.compareToLeafNode_(other); + } + } + /** + * Comparison specifically for two leaf nodes + */ + compareToLeafNode_(otherLeaf) { + const otherLeafType = typeof otherLeaf.value_; + const thisLeafType = typeof this.value_; + const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType); + const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType); + util.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType); + util.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType); + if (otherIndex === thisIndex) { + // Same type, compare values + if (thisLeafType === 'object') { + // Deferred value nodes are all equal, but we should also never get to this point... + return 0; + } + else { + // Note that this works because true > false, all others are number or string comparisons + if (this.value_ < otherLeaf.value_) { + return -1; + } + else if (this.value_ === otherLeaf.value_) { + return 0; + } + else { + return 1; + } + } + } + else { + return thisIndex - otherIndex; + } + } + withIndex() { + return this; + } + isIndexed() { + return true; + } + equals(other) { + if (other === this) { + return true; + } + else if (other.isLeafNode()) { + const otherLeaf = other; + return (this.value_ === otherLeaf.value_ && + this.priorityNode_.equals(otherLeaf.priorityNode_)); + } + else { + return false; + } + } +} +/** + * The sort order for comparing leaf nodes of different types. If two leaf nodes have + * the same type, the comparison falls back to their value + */ +LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string']; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let nodeFromJSON$1; +let MAX_NODE$1; +function setNodeFromJSON(val) { + nodeFromJSON$1 = val; +} +function setMaxNode(val) { + MAX_NODE$1 = val; +} +class PriorityIndex extends Index { + compare(a, b) { + const aPriority = a.node.getPriority(); + const bPriority = b.node.getPriority(); + const indexCmp = aPriority.compareTo(bPriority); + if (indexCmp === 0) { + return nameCompare(a.name, b.name); + } + else { + return indexCmp; + } + } + isDefinedOn(node) { + return !node.getPriority().isEmpty(); + } + indexedValueChanged(oldNode, newNode) { + return !oldNode.getPriority().equals(newNode.getPriority()); + } + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } + maxPost() { + return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1)); + } + makePost(indexValue, name) { + const priorityNode = nodeFromJSON$1(indexValue); + return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode)); + } + /** + * @returns String representation for inclusion in a query spec + */ + toString() { + return '.priority'; + } +} +const PRIORITY_INDEX = new PriorityIndex(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_2 = Math.log(2); +class Base12Num { + constructor(length) { + const logBase2 = (num) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + parseInt((Math.log(num) / LOG_2), 10); + const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2); + this.count = logBase2(length + 1); + this.current_ = this.count - 1; + const mask = bitMask(this.count); + this.bits_ = (length + 1) & mask; + } + nextBitIsOne() { + //noinspection JSBitwiseOperatorUsage + const result = !(this.bits_ & (0x1 << this.current_)); + this.current_--; + return result; + } +} +/** + * Takes a list of child nodes and constructs a SortedSet using the given comparison + * function + * + * Uses the algorithm described in the paper linked here: + * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458 + * + * @param childList - Unsorted list of children + * @param cmp - The comparison method to be used + * @param keyFn - An optional function to extract K from a node wrapper, if K's + * type is not NamedNode + * @param mapSortFn - An optional override for comparator used by the generated sorted map + */ +const buildChildSet = function (childList, cmp, keyFn, mapSortFn) { + childList.sort(cmp); + const buildBalancedTree = function (low, high) { + const length = high - low; + let namedNode; + let key; + if (length === 0) { + return null; + } + else if (length === 1) { + namedNode = childList[low]; + key = keyFn ? keyFn(namedNode) : namedNode; + return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null); + } + else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const middle = parseInt((length / 2), 10) + low; + const left = buildBalancedTree(low, middle); + const right = buildBalancedTree(middle + 1, high); + namedNode = childList[middle]; + key = keyFn ? keyFn(namedNode) : namedNode; + return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right); + } + }; + const buildFrom12Array = function (base12) { + let node = null; + let root = null; + let index = childList.length; + const buildPennant = function (chunkSize, color) { + const low = index - chunkSize; + const high = index; + index -= chunkSize; + const childTree = buildBalancedTree(low + 1, high); + const namedNode = childList[low]; + const key = keyFn ? keyFn(namedNode) : namedNode; + attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree)); + }; + const attachPennant = function (pennant) { + if (node) { + node.left = pennant; + node = pennant; + } + else { + root = pennant; + node = pennant; + } + }; + for (let i = 0; i < base12.count; ++i) { + const isOne = base12.nextBitIsOne(); + // The number of nodes taken in each slice is 2^(arr.length - (i + 1)) + const chunkSize = Math.pow(2, base12.count - (i + 1)); + if (isOne) { + buildPennant(chunkSize, LLRBNode.BLACK); + } + else { + // current == 2 + buildPennant(chunkSize, LLRBNode.BLACK); + buildPennant(chunkSize, LLRBNode.RED); + } + } + return root; + }; + const base12 = new Base12Num(childList.length); + const root = buildFrom12Array(base12); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return new SortedMap(mapSortFn || cmp, root); +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let _defaultIndexMap; +const fallbackObject = {}; +class IndexMap { + /** + * The default IndexMap for nodes without a priority + */ + static get Default() { + util.assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded'); + _defaultIndexMap = + _defaultIndexMap || + new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX }); + return _defaultIndexMap; + } + constructor(indexes_, indexSet_) { + this.indexes_ = indexes_; + this.indexSet_ = indexSet_; + } + get(indexKey) { + const sortedMap = util.safeGet(this.indexes_, indexKey); + if (!sortedMap) { + throw new Error('No index defined for ' + indexKey); + } + if (sortedMap instanceof SortedMap) { + return sortedMap; + } + else { + // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the + // regular child map + return null; + } + } + hasIndex(indexDefinition) { + return util.contains(this.indexSet_, indexDefinition.toString()); + } + addIndex(indexDefinition, existingChildren) { + util.assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap."); + const childList = []; + let sawIndexedValue = false; + const iter = existingChildren.getIterator(NamedNode.Wrap); + let next = iter.getNext(); + while (next) { + sawIndexedValue = + sawIndexedValue || indexDefinition.isDefinedOn(next.node); + childList.push(next); + next = iter.getNext(); + } + let newIndex; + if (sawIndexedValue) { + newIndex = buildChildSet(childList, indexDefinition.getCompare()); + } + else { + newIndex = fallbackObject; + } + const indexName = indexDefinition.toString(); + const newIndexSet = { ...this.indexSet_ }; + newIndexSet[indexName] = indexDefinition; + const newIndexes = { ...this.indexes_ }; + newIndexes[indexName] = newIndex; + return new IndexMap(newIndexes, newIndexSet); + } + /** + * Ensure that this node is properly tracked in any indexes that we're maintaining + */ + addToIndexes(namedNode, existingChildren) { + const newIndexes = util.map(this.indexes_, (indexedChildren, indexName) => { + const index = util.safeGet(this.indexSet_, indexName); + util.assert(index, 'Missing index implementation for ' + indexName); + if (indexedChildren === fallbackObject) { + // Check to see if we need to index everything + if (index.isDefinedOn(namedNode.node)) { + // We need to build this index + const childList = []; + const iter = existingChildren.getIterator(NamedNode.Wrap); + let next = iter.getNext(); + while (next) { + if (next.name !== namedNode.name) { + childList.push(next); + } + next = iter.getNext(); + } + childList.push(namedNode); + return buildChildSet(childList, index.getCompare()); + } + else { + // No change, this remains a fallback + return fallbackObject; + } + } + else { + const existingSnap = existingChildren.get(namedNode.name); + let newChildren = indexedChildren; + if (existingSnap) { + newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap)); + } + return newChildren.insert(namedNode, namedNode.node); + } + }); + return new IndexMap(newIndexes, this.indexSet_); + } + /** + * Create a new IndexMap instance with the given value removed + */ + removeFromIndexes(namedNode, existingChildren) { + const newIndexes = util.map(this.indexes_, (indexedChildren) => { + if (indexedChildren === fallbackObject) { + // This is the fallback. Just return it, nothing to do in this case + return indexedChildren; + } + else { + const existingSnap = existingChildren.get(namedNode.name); + if (existingSnap) { + return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap)); + } + else { + // No record of this child + return indexedChildren; + } + } + }); + return new IndexMap(newIndexes, this.indexSet_); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO: For memory savings, don't store priorityNode_ if it's empty. +let EMPTY_NODE; +/** + * ChildrenNode is a class for storing internal nodes in a DataSnapshot + * (i.e. nodes with children). It implements Node and stores the + * list of children in the children property, sorted by child name. + */ +class ChildrenNode { + static get EMPTY_NODE() { + return (EMPTY_NODE || + (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default))); + } + /** + * @param children_ - List of children of this node.. + * @param priorityNode_ - The priority of this node (as a snapshot node). + */ + constructor(children_, priorityNode_, indexMap_) { + this.children_ = children_; + this.priorityNode_ = priorityNode_; + this.indexMap_ = indexMap_; + this.lazyHash_ = null; + /** + * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use + * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own + * class instead of an empty ChildrenNode. + */ + if (this.priorityNode_) { + validatePriorityNode(this.priorityNode_); + } + if (this.children_.isEmpty()) { + util.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority'); + } + } + /** @inheritDoc */ + isLeafNode() { + return false; + } + /** @inheritDoc */ + getPriority() { + return this.priorityNode_ || EMPTY_NODE; + } + /** @inheritDoc */ + updatePriority(newPriorityNode) { + if (this.children_.isEmpty()) { + // Don't allow priorities on empty nodes + return this; + } + else { + return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_); + } + } + /** @inheritDoc */ + getImmediateChild(childName) { + // Hack to treat priority as a regular child + if (childName === '.priority') { + return this.getPriority(); + } + else { + const child = this.children_.get(childName); + return child === null ? EMPTY_NODE : child; + } + } + /** @inheritDoc */ + getChild(path) { + const front = pathGetFront(path); + if (front === null) { + return this; + } + return this.getImmediateChild(front).getChild(pathPopFront(path)); + } + /** @inheritDoc */ + hasChild(childName) { + return this.children_.get(childName) !== null; + } + /** @inheritDoc */ + updateImmediateChild(childName, newChildNode) { + util.assert(newChildNode, 'We should always be passing snapshot nodes'); + if (childName === '.priority') { + return this.updatePriority(newChildNode); + } + else { + const namedNode = new NamedNode(childName, newChildNode); + let newChildren, newIndexMap; + if (newChildNode.isEmpty()) { + newChildren = this.children_.remove(childName); + newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_); + } + else { + newChildren = this.children_.insert(childName, newChildNode); + newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_); + } + const newPriority = newChildren.isEmpty() + ? EMPTY_NODE + : this.priorityNode_; + return new ChildrenNode(newChildren, newPriority, newIndexMap); + } + } + /** @inheritDoc */ + updateChild(path, newChildNode) { + const front = pathGetFront(path); + if (front === null) { + return newChildNode; + } + else { + util.assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path'); + const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode); + return this.updateImmediateChild(front, newImmediateChild); + } + } + /** @inheritDoc */ + isEmpty() { + return this.children_.isEmpty(); + } + /** @inheritDoc */ + numChildren() { + return this.children_.count(); + } + /** @inheritDoc */ + val(exportFormat) { + if (this.isEmpty()) { + return null; + } + const obj = {}; + let numKeys = 0, maxKey = 0, allIntegerKeys = true; + this.forEachChild(PRIORITY_INDEX, (key, childNode) => { + obj[key] = childNode.val(exportFormat); + numKeys++; + if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) { + maxKey = Math.max(maxKey, Number(key)); + } + else { + allIntegerKeys = false; + } + }); + if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) { + // convert to array. + const array = []; + // eslint-disable-next-line guard-for-in + for (const key in obj) { + array[key] = obj[key]; + } + return array; + } + else { + if (exportFormat && !this.getPriority().isEmpty()) { + obj['.priority'] = this.getPriority().val(); + } + return obj; + } + } + /** @inheritDoc */ + hash() { + if (this.lazyHash_ === null) { + let toHash = ''; + if (!this.getPriority().isEmpty()) { + toHash += + 'priority:' + + priorityHashText(this.getPriority().val()) + + ':'; + } + this.forEachChild(PRIORITY_INDEX, (key, childNode) => { + const childHash = childNode.hash(); + if (childHash !== '') { + toHash += ':' + key + ':' + childHash; + } + }); + this.lazyHash_ = toHash === '' ? '' : sha1(toHash); + } + return this.lazyHash_; + } + /** @inheritDoc */ + getPredecessorChildName(childName, childNode, index) { + const idx = this.resolveIndex_(index); + if (idx) { + const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode)); + return predecessor ? predecessor.name : null; + } + else { + return this.children_.getPredecessorKey(childName); + } + } + getFirstChildName(indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + const minKey = idx.minKey(); + return minKey && minKey.name; + } + else { + return this.children_.minKey(); + } + } + getFirstChild(indexDefinition) { + const minKey = this.getFirstChildName(indexDefinition); + if (minKey) { + return new NamedNode(minKey, this.children_.get(minKey)); + } + else { + return null; + } + } + /** + * Given an index, return the key name of the largest value we have, according to that index + */ + getLastChildName(indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + const maxKey = idx.maxKey(); + return maxKey && maxKey.name; + } + else { + return this.children_.maxKey(); + } + } + getLastChild(indexDefinition) { + const maxKey = this.getLastChildName(indexDefinition); + if (maxKey) { + return new NamedNode(maxKey, this.children_.get(maxKey)); + } + else { + return null; + } + } + forEachChild(index, action) { + const idx = this.resolveIndex_(index); + if (idx) { + return idx.inorderTraversal(wrappedNode => { + return action(wrappedNode.name, wrappedNode.node); + }); + } + else { + return this.children_.inorderTraversal(action); + } + } + getIterator(indexDefinition) { + return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition); + } + getIteratorFrom(startPost, indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + return idx.getIteratorFrom(startPost, key => key); + } + else { + const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap); + let next = iterator.peek(); + while (next != null && indexDefinition.compare(next, startPost) < 0) { + iterator.getNext(); + next = iterator.peek(); + } + return iterator; + } + } + getReverseIterator(indexDefinition) { + return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition); + } + getReverseIteratorFrom(endPost, indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + return idx.getReverseIteratorFrom(endPost, key => { + return key; + }); + } + else { + const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap); + let next = iterator.peek(); + while (next != null && indexDefinition.compare(next, endPost) > 0) { + iterator.getNext(); + next = iterator.peek(); + } + return iterator; + } + } + compareTo(other) { + if (this.isEmpty()) { + if (other.isEmpty()) { + return 0; + } + else { + return -1; + } + } + else if (other.isLeafNode() || other.isEmpty()) { + return 1; + } + else if (other === MAX_NODE) { + return -1; + } + else { + // Must be another node with children. + return 0; + } + } + withIndex(indexDefinition) { + if (indexDefinition === KEY_INDEX || + this.indexMap_.hasIndex(indexDefinition)) { + return this; + } + else { + const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_); + return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap); + } + } + isIndexed(index) { + return index === KEY_INDEX || this.indexMap_.hasIndex(index); + } + equals(other) { + if (other === this) { + return true; + } + else if (other.isLeafNode()) { + return false; + } + else { + const otherChildrenNode = other; + if (!this.getPriority().equals(otherChildrenNode.getPriority())) { + return false; + } + else if (this.children_.count() === otherChildrenNode.children_.count()) { + const thisIter = this.getIterator(PRIORITY_INDEX); + const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX); + let thisCurrent = thisIter.getNext(); + let otherCurrent = otherIter.getNext(); + while (thisCurrent && otherCurrent) { + if (thisCurrent.name !== otherCurrent.name || + !thisCurrent.node.equals(otherCurrent.node)) { + return false; + } + thisCurrent = thisIter.getNext(); + otherCurrent = otherIter.getNext(); + } + return thisCurrent === null && otherCurrent === null; + } + else { + return false; + } + } + } + /** + * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used + * instead. + * + */ + resolveIndex_(indexDefinition) { + if (indexDefinition === KEY_INDEX) { + return null; + } + else { + return this.indexMap_.get(indexDefinition.toString()); + } + } +} +ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/; +class MaxNode extends ChildrenNode { + constructor() { + super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default); + } + compareTo(other) { + if (other === this) { + return 0; + } + else { + return 1; + } + } + equals(other) { + // Not that we every compare it, but MAX_NODE is only ever equal to itself + return other === this; + } + getPriority() { + return this; + } + getImmediateChild(childName) { + return ChildrenNode.EMPTY_NODE; + } + isEmpty() { + return false; + } +} +/** + * Marker that will sort higher than any other snapshot. + */ +const MAX_NODE = new MaxNode(); +Object.defineProperties(NamedNode, { + MIN: { + value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE) + }, + MAX: { + value: new NamedNode(MAX_NAME, MAX_NODE) + } +}); +/** + * Reference Extensions + */ +KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE; +LeafNode.__childrenNodeConstructor = ChildrenNode; +setMaxNode$1(MAX_NODE); +setMaxNode(MAX_NODE); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const USE_HINZE = true; +/** + * Constructs a snapshot node representing the passed JSON and returns it. + * @param json - JSON to create a node for. + * @param priority - Optional priority to use. This will be ignored if the + * passed JSON contains a .priority property. + */ +function nodeFromJSON(json, priority = null) { + if (json === null) { + return ChildrenNode.EMPTY_NODE; + } + if (typeof json === 'object' && '.priority' in json) { + priority = json['.priority']; + } + util.assert(priority === null || + typeof priority === 'string' || + typeof priority === 'number' || + (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority); + if (typeof json === 'object' && '.value' in json && json['.value'] !== null) { + json = json['.value']; + } + // Valid leaf nodes include non-objects or server-value wrapper objects + if (typeof json !== 'object' || '.sv' in json) { + const jsonLeaf = json; + return new LeafNode(jsonLeaf, nodeFromJSON(priority)); + } + if (!(json instanceof Array) && USE_HINZE) { + const children = []; + let childrenHavePriority = false; + const hinzeJsonObj = json; + each(hinzeJsonObj, (key, child) => { + if (key.substring(0, 1) !== '.') { + // Ignore metadata nodes + const childNode = nodeFromJSON(child); + if (!childNode.isEmpty()) { + childrenHavePriority = + childrenHavePriority || !childNode.getPriority().isEmpty(); + children.push(new NamedNode(key, childNode)); + } + } + }); + if (children.length === 0) { + return ChildrenNode.EMPTY_NODE; + } + const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR); + if (childrenHavePriority) { + const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare()); + return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX })); + } + else { + return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default); + } + } + else { + let node = ChildrenNode.EMPTY_NODE; + each(json, (key, childData) => { + if (util.contains(json, key)) { + if (key.substring(0, 1) !== '.') { + // ignore metadata nodes. + const childNode = nodeFromJSON(childData); + if (childNode.isLeafNode() || !childNode.isEmpty()) { + node = node.updateImmediateChild(key, childNode); + } + } + } + }); + return node.updatePriority(nodeFromJSON(priority)); + } +} +setNodeFromJSON(nodeFromJSON); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class PathIndex extends Index { + constructor(indexPath_) { + super(); + this.indexPath_ = indexPath_; + util.assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key"); + } + extractChild(snap) { + return snap.getChild(this.indexPath_); + } + isDefinedOn(node) { + return !node.getChild(this.indexPath_).isEmpty(); + } + compare(a, b) { + const aChild = this.extractChild(a.node); + const bChild = this.extractChild(b.node); + const indexCmp = aChild.compareTo(bChild); + if (indexCmp === 0) { + return nameCompare(a.name, b.name); + } + else { + return indexCmp; + } + } + makePost(indexValue, name) { + const valueNode = nodeFromJSON(indexValue); + const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode); + return new NamedNode(name, node); + } + maxPost() { + const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE); + return new NamedNode(MAX_NAME, node); + } + toString() { + return pathSlice(this.indexPath_, 0).join('/'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ValueIndex extends Index { + compare(a, b) { + const indexCmp = a.node.compareTo(b.node); + if (indexCmp === 0) { + return nameCompare(a.name, b.name); + } + else { + return indexCmp; + } + } + isDefinedOn(node) { + return true; + } + indexedValueChanged(oldNode, newNode) { + return !oldNode.equals(newNode); + } + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } + maxPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MAX; + } + makePost(indexValue, name) { + const valueNode = nodeFromJSON(indexValue); + return new NamedNode(name, valueNode); + } + /** + * @returns String representation for inclusion in a query spec + */ + toString() { + return '.value'; + } +} +const VALUE_INDEX = new ValueIndex(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function changeValue(snapshotNode) { + return { type: "value" /* ChangeType.VALUE */, snapshotNode }; +} +function changeChildAdded(childName, snapshotNode) { + return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode, childName }; +} +function changeChildRemoved(childName, snapshotNode) { + return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode, childName }; +} +function changeChildChanged(childName, snapshotNode, oldSnap) { + return { + type: "child_changed" /* ChangeType.CHILD_CHANGED */, + snapshotNode, + childName, + oldSnap + }; +} +function changeChildMoved(childName, snapshotNode) { + return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode, childName }; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Doesn't really filter nodes but applies an index to the node and keeps track of any changes + */ +class IndexedFilter { + constructor(index_) { + this.index_ = index_; + } + updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) { + util.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated'); + const oldChild = snap.getImmediateChild(key); + // Check if anything actually changed. + if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) { + // There's an edge case where a child can enter or leave the view because affectedPath was set to null. + // In this case, affectedPath will appear null in both the old and new snapshots. So we need + // to avoid treating these cases as "nothing changed." + if (oldChild.isEmpty() === newChild.isEmpty()) { + // Nothing changed. + // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it. + //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.'); + return snap; + } + } + if (optChangeAccumulator != null) { + if (newChild.isEmpty()) { + if (snap.hasChild(key)) { + optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild)); + } + else { + util.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node'); + } + } + else if (oldChild.isEmpty()) { + optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild)); + } + else { + optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild)); + } + } + if (snap.isLeafNode() && newChild.isEmpty()) { + return snap; + } + else { + // Make sure the node is indexed + return snap.updateImmediateChild(key, newChild).withIndex(this.index_); + } + } + updateFullNode(oldSnap, newSnap, optChangeAccumulator) { + if (optChangeAccumulator != null) { + if (!oldSnap.isLeafNode()) { + oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => { + if (!newSnap.hasChild(key)) { + optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode)); + } + }); + } + if (!newSnap.isLeafNode()) { + newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => { + if (oldSnap.hasChild(key)) { + const oldChild = oldSnap.getImmediateChild(key); + if (!oldChild.equals(childNode)) { + optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild)); + } + } + else { + optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode)); + } + }); + } + } + return newSnap.withIndex(this.index_); + } + updatePriority(oldSnap, newPriority) { + if (oldSnap.isEmpty()) { + return ChildrenNode.EMPTY_NODE; + } + else { + return oldSnap.updatePriority(newPriority); + } + } + filtersNodes() { + return false; + } + getIndexedFilter() { + return this; + } + getIndex() { + return this.index_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node + */ +class RangedFilter { + constructor(params) { + this.indexedFilter_ = new IndexedFilter(params.getIndex()); + this.index_ = params.getIndex(); + this.startPost_ = RangedFilter.getStartPost_(params); + this.endPost_ = RangedFilter.getEndPost_(params); + this.startIsInclusive_ = !params.startAfterSet_; + this.endIsInclusive_ = !params.endBeforeSet_; + } + getStartPost() { + return this.startPost_; + } + getEndPost() { + return this.endPost_; + } + matches(node) { + const isWithinStart = this.startIsInclusive_ + ? this.index_.compare(this.getStartPost(), node) <= 0 + : this.index_.compare(this.getStartPost(), node) < 0; + const isWithinEnd = this.endIsInclusive_ + ? this.index_.compare(node, this.getEndPost()) <= 0 + : this.index_.compare(node, this.getEndPost()) < 0; + return isWithinStart && isWithinEnd; + } + updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) { + if (!this.matches(new NamedNode(key, newChild))) { + newChild = ChildrenNode.EMPTY_NODE; + } + return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator); + } + updateFullNode(oldSnap, newSnap, optChangeAccumulator) { + if (newSnap.isLeafNode()) { + // Make sure we have a children node with the correct index, not a leaf node; + newSnap = ChildrenNode.EMPTY_NODE; + } + let filtered = newSnap.withIndex(this.index_); + // Don't support priorities on queries + filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE); + const self = this; + newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => { + if (!self.matches(new NamedNode(key, childNode))) { + filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE); + } + }); + return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator); + } + updatePriority(oldSnap, newPriority) { + // Don't support priorities on queries + return oldSnap; + } + filtersNodes() { + return true; + } + getIndexedFilter() { + return this.indexedFilter_; + } + getIndex() { + return this.index_; + } + static getStartPost_(params) { + if (params.hasStart()) { + const startName = params.getIndexStartName(); + return params.getIndex().makePost(params.getIndexStartValue(), startName); + } + else { + return params.getIndex().minPost(); + } + } + static getEndPost_(params) { + if (params.hasEnd()) { + const endName = params.getIndexEndName(); + return params.getIndex().makePost(params.getIndexEndValue(), endName); + } + else { + return params.getIndex().maxPost(); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible + */ +class LimitedFilter { + constructor(params) { + this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node); + this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node); + this.withinStartPost = (node) => { + const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node); + return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0; + }; + this.withinEndPost = (node) => { + const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost()); + return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0; + }; + this.rangedFilter_ = new RangedFilter(params); + this.index_ = params.getIndex(); + this.limit_ = params.getLimit(); + this.reverse_ = !params.isViewFromLeft(); + this.startIsInclusive_ = !params.startAfterSet_; + this.endIsInclusive_ = !params.endBeforeSet_; + } + updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) { + if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) { + newChild = ChildrenNode.EMPTY_NODE; + } + if (snap.getImmediateChild(key).equals(newChild)) { + // No change + return snap; + } + else if (snap.numChildren() < this.limit_) { + return this.rangedFilter_ + .getIndexedFilter() + .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator); + } + else { + return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator); + } + } + updateFullNode(oldSnap, newSnap, optChangeAccumulator) { + let filtered; + if (newSnap.isLeafNode() || newSnap.isEmpty()) { + // Make sure we have a children node with the correct index, not a leaf node; + filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_); + } + else { + if (this.limit_ * 2 < newSnap.numChildren() && + newSnap.isIndexed(this.index_)) { + // Easier to build up a snapshot, since what we're given has more than twice the elements we want + filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_); + // anchor to the startPost, endPost, or last element as appropriate + let iterator; + if (this.reverse_) { + iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_); + } + else { + iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_); + } + let count = 0; + while (iterator.hasNext() && count < this.limit_) { + const next = iterator.getNext(); + if (!this.withinDirectionalStart(next)) { + // if we have not reached the start, skip to the next element + continue; + } + else if (!this.withinDirectionalEnd(next)) { + // if we have reached the end, stop adding elements + break; + } + else { + filtered = filtered.updateImmediateChild(next.name, next.node); + count++; + } + } + } + else { + // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one + filtered = newSnap.withIndex(this.index_); + // Don't support priorities on queries + filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE); + let iterator; + if (this.reverse_) { + iterator = filtered.getReverseIterator(this.index_); + } + else { + iterator = filtered.getIterator(this.index_); + } + let count = 0; + while (iterator.hasNext()) { + const next = iterator.getNext(); + const inRange = count < this.limit_ && + this.withinDirectionalStart(next) && + this.withinDirectionalEnd(next); + if (inRange) { + count++; + } + else { + filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE); + } + } + } + } + return this.rangedFilter_ + .getIndexedFilter() + .updateFullNode(oldSnap, filtered, optChangeAccumulator); + } + updatePriority(oldSnap, newPriority) { + // Don't support priorities on queries + return oldSnap; + } + filtersNodes() { + return true; + } + getIndexedFilter() { + return this.rangedFilter_.getIndexedFilter(); + } + getIndex() { + return this.index_; + } + fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) { + // TODO: rename all cache stuff etc to general snap terminology + let cmp; + if (this.reverse_) { + const indexCmp = this.index_.getCompare(); + cmp = (a, b) => indexCmp(b, a); + } + else { + cmp = this.index_.getCompare(); + } + const oldEventCache = snap; + util.assert(oldEventCache.numChildren() === this.limit_, ''); + const newChildNamedNode = new NamedNode(childKey, childSnap); + const windowBoundary = this.reverse_ + ? oldEventCache.getFirstChild(this.index_) + : oldEventCache.getLastChild(this.index_); + const inRange = this.rangedFilter_.matches(newChildNamedNode); + if (oldEventCache.hasChild(childKey)) { + const oldChildSnap = oldEventCache.getImmediateChild(childKey); + let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_); + while (nextChild != null && + (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) { + // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't + // been applied to the limited filter yet. Ignore this next child which will be updated later in + // the limited filter... + nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_); + } + const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode); + const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0; + if (remainsInWindow) { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap)); + } + return oldEventCache.updateImmediateChild(childKey, childSnap); + } + else { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap)); + } + const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE); + const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild); + if (nextChildInRange) { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node)); + } + return newEventCache.updateImmediateChild(nextChild.name, nextChild.node); + } + else { + return newEventCache; + } + } + } + else if (childSnap.isEmpty()) { + // we're deleting a node, but it was not in the window, so ignore it + return snap; + } + else if (inRange) { + if (cmp(windowBoundary, newChildNamedNode) >= 0) { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node)); + changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap)); + } + return oldEventCache + .updateImmediateChild(childKey, childSnap) + .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE); + } + else { + return snap; + } + } + else { + return snap; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a + * range to be returned for a particular location. It is assumed that validation of parameters is done at the + * user-facing API level, so it is not done here. + * + * @internal + */ +class QueryParams { + constructor() { + this.limitSet_ = false; + this.startSet_ = false; + this.startNameSet_ = false; + this.startAfterSet_ = false; // can only be true if startSet_ is true + this.endSet_ = false; + this.endNameSet_ = false; + this.endBeforeSet_ = false; // can only be true if endSet_ is true + this.limit_ = 0; + this.viewFrom_ = ''; + this.indexStartValue_ = null; + this.indexStartName_ = ''; + this.indexEndValue_ = null; + this.indexEndName_ = ''; + this.index_ = PRIORITY_INDEX; + } + hasStart() { + return this.startSet_; + } + /** + * @returns True if it would return from left. + */ + isViewFromLeft() { + if (this.viewFrom_ === '') { + // limit(), rather than limitToFirst or limitToLast was called. + // This means that only one of startSet_ and endSet_ is true. Use them + // to calculate which side of the view to anchor to. If neither is set, + // anchor to the end. + return this.startSet_; + } + else { + return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */; + } + } + /** + * Only valid to call if hasStart() returns true + */ + getIndexStartValue() { + util.assert(this.startSet_, 'Only valid if start has been set'); + return this.indexStartValue_; + } + /** + * Only valid to call if hasStart() returns true. + * Returns the starting key name for the range defined by these query parameters + */ + getIndexStartName() { + util.assert(this.startSet_, 'Only valid if start has been set'); + if (this.startNameSet_) { + return this.indexStartName_; + } + else { + return MIN_NAME; + } + } + hasEnd() { + return this.endSet_; + } + /** + * Only valid to call if hasEnd() returns true. + */ + getIndexEndValue() { + util.assert(this.endSet_, 'Only valid if end has been set'); + return this.indexEndValue_; + } + /** + * Only valid to call if hasEnd() returns true. + * Returns the end key name for the range defined by these query parameters + */ + getIndexEndName() { + util.assert(this.endSet_, 'Only valid if end has been set'); + if (this.endNameSet_) { + return this.indexEndName_; + } + else { + return MAX_NAME; + } + } + hasLimit() { + return this.limitSet_; + } + /** + * @returns True if a limit has been set and it has been explicitly anchored + */ + hasAnchoredLimit() { + return this.limitSet_ && this.viewFrom_ !== ''; + } + /** + * Only valid to call if hasLimit() returns true + */ + getLimit() { + util.assert(this.limitSet_, 'Only valid if limit has been set'); + return this.limit_; + } + getIndex() { + return this.index_; + } + loadsAllData() { + return !(this.startSet_ || this.endSet_ || this.limitSet_); + } + isDefault() { + return this.loadsAllData() && this.index_ === PRIORITY_INDEX; + } + copy() { + const copy = new QueryParams(); + copy.limitSet_ = this.limitSet_; + copy.limit_ = this.limit_; + copy.startSet_ = this.startSet_; + copy.startAfterSet_ = this.startAfterSet_; + copy.indexStartValue_ = this.indexStartValue_; + copy.startNameSet_ = this.startNameSet_; + copy.indexStartName_ = this.indexStartName_; + copy.endSet_ = this.endSet_; + copy.endBeforeSet_ = this.endBeforeSet_; + copy.indexEndValue_ = this.indexEndValue_; + copy.endNameSet_ = this.endNameSet_; + copy.indexEndName_ = this.indexEndName_; + copy.index_ = this.index_; + copy.viewFrom_ = this.viewFrom_; + return copy; + } +} +function queryParamsGetNodeFilter(queryParams) { + if (queryParams.loadsAllData()) { + return new IndexedFilter(queryParams.getIndex()); + } + else if (queryParams.hasLimit()) { + return new LimitedFilter(queryParams); + } + else { + return new RangedFilter(queryParams); + } +} +function queryParamsLimitToFirst(queryParams, newLimit) { + const newParams = queryParams.copy(); + newParams.limitSet_ = true; + newParams.limit_ = newLimit; + newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */; + return newParams; +} +function queryParamsLimitToLast(queryParams, newLimit) { + const newParams = queryParams.copy(); + newParams.limitSet_ = true; + newParams.limit_ = newLimit; + newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */; + return newParams; +} +function queryParamsStartAt(queryParams, indexValue, key) { + const newParams = queryParams.copy(); + newParams.startSet_ = true; + if (indexValue === undefined) { + indexValue = null; + } + newParams.indexStartValue_ = indexValue; + if (key != null) { + newParams.startNameSet_ = true; + newParams.indexStartName_ = key; + } + else { + newParams.startNameSet_ = false; + newParams.indexStartName_ = ''; + } + return newParams; +} +function queryParamsStartAfter(queryParams, indexValue, key) { + let params; + if (queryParams.index_ === KEY_INDEX || !!key) { + params = queryParamsStartAt(queryParams, indexValue, key); + } + else { + params = queryParamsStartAt(queryParams, indexValue, MAX_NAME); + } + params.startAfterSet_ = true; + return params; +} +function queryParamsEndAt(queryParams, indexValue, key) { + const newParams = queryParams.copy(); + newParams.endSet_ = true; + if (indexValue === undefined) { + indexValue = null; + } + newParams.indexEndValue_ = indexValue; + if (key !== undefined) { + newParams.endNameSet_ = true; + newParams.indexEndName_ = key; + } + else { + newParams.endNameSet_ = false; + newParams.indexEndName_ = ''; + } + return newParams; +} +function queryParamsEndBefore(queryParams, indexValue, key) { + let params; + if (queryParams.index_ === KEY_INDEX || !!key) { + params = queryParamsEndAt(queryParams, indexValue, key); + } + else { + params = queryParamsEndAt(queryParams, indexValue, MIN_NAME); + } + params.endBeforeSet_ = true; + return params; +} +function queryParamsOrderBy(queryParams, index) { + const newParams = queryParams.copy(); + newParams.index_ = index; + return newParams; +} +/** + * Returns a set of REST query string parameters representing this query. + * + * @returns query string parameters + */ +function queryParamsToRestQueryStringParameters(queryParams) { + const qs = {}; + if (queryParams.isDefault()) { + return qs; + } + let orderBy; + if (queryParams.index_ === PRIORITY_INDEX) { + orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */; + } + else if (queryParams.index_ === VALUE_INDEX) { + orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */; + } + else if (queryParams.index_ === KEY_INDEX) { + orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */; + } + else { + util.assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!'); + orderBy = queryParams.index_.toString(); + } + qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = util.stringify(orderBy); + if (queryParams.startSet_) { + const startParam = queryParams.startAfterSet_ + ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */ + : "startAt" /* REST_QUERY_CONSTANTS.START_AT */; + qs[startParam] = util.stringify(queryParams.indexStartValue_); + if (queryParams.startNameSet_) { + qs[startParam] += ',' + util.stringify(queryParams.indexStartName_); + } + } + if (queryParams.endSet_) { + const endParam = queryParams.endBeforeSet_ + ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */ + : "endAt" /* REST_QUERY_CONSTANTS.END_AT */; + qs[endParam] = util.stringify(queryParams.indexEndValue_); + if (queryParams.endNameSet_) { + qs[endParam] += ',' + util.stringify(queryParams.indexEndName_); + } + } + if (queryParams.limitSet_) { + if (queryParams.isViewFromLeft()) { + qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_; + } + else { + qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_; + } + } + return qs; +} +function queryParamsGetQueryObject(queryParams) { + const obj = {}; + if (queryParams.startSet_) { + obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] = + queryParams.indexStartValue_; + if (queryParams.startNameSet_) { + obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] = + queryParams.indexStartName_; + } + obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] = + !queryParams.startAfterSet_; + } + if (queryParams.endSet_) { + obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_; + if (queryParams.endNameSet_) { + obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_; + } + obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] = + !queryParams.endBeforeSet_; + } + if (queryParams.limitSet_) { + obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_; + let viewFrom = queryParams.viewFrom_; + if (viewFrom === '') { + if (queryParams.isViewFromLeft()) { + viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */; + } + else { + viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */; + } + } + obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom; + } + // For now, priority index is the default, so we only specify if it's some other index + if (queryParams.index_ !== PRIORITY_INDEX) { + obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString(); + } + return obj; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An implementation of ServerActions that communicates with the server via REST requests. + * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full + * persistent connection (using WebSockets or long-polling) + */ +class ReadonlyRestClient extends ServerActions { + reportStats(stats) { + throw new Error('Method not implemented.'); + } + static getListenId_(query, tag) { + if (tag !== undefined) { + return 'tag$' + tag; + } + else { + util.assert(query._queryParams.isDefault(), "should have a tag if it's not a default query."); + return query._path.toString(); + } + } + /** + * @param repoInfo_ - Data about the namespace we are connecting to + * @param onDataUpdate_ - A callback for new data from the server + */ + constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) { + super(); + this.repoInfo_ = repoInfo_; + this.onDataUpdate_ = onDataUpdate_; + this.authTokenProvider_ = authTokenProvider_; + this.appCheckTokenProvider_ = appCheckTokenProvider_; + /** @private {function(...[*])} */ + this.log_ = logWrapper('p:rest:'); + /** + * We don't actually need to track listens, except to prevent us calling an onComplete for a listen + * that's been removed. :-/ + */ + this.listens_ = {}; + } + /** @inheritDoc */ + listen(query, currentHashFn, tag, onComplete) { + const pathString = query._path.toString(); + this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier); + // Mark this listener so we can tell if it's removed. + const listenId = ReadonlyRestClient.getListenId_(query, tag); + const thisListen = {}; + this.listens_[listenId] = thisListen; + const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams); + this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => { + let data = result; + if (error === 404) { + data = null; + error = null; + } + if (error === null) { + this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag); + } + if (util.safeGet(this.listens_, listenId) === thisListen) { + let status; + if (!error) { + status = 'ok'; + } + else if (error === 401) { + status = 'permission_denied'; + } + else { + status = 'rest_error:' + error; + } + onComplete(status, null); + } + }); + } + /** @inheritDoc */ + unlisten(query, tag) { + const listenId = ReadonlyRestClient.getListenId_(query, tag); + delete this.listens_[listenId]; + } + get(query) { + const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams); + const pathString = query._path.toString(); + const deferred = new util.Deferred(); + this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => { + let data = result; + if (error === 404) { + data = null; + error = null; + } + if (error === null) { + this.onDataUpdate_(pathString, data, + /*isMerge=*/ false, + /*tag=*/ null); + deferred.resolve(data); + } + else { + deferred.reject(new Error(data)); + } + }); + return deferred.promise; + } + /** @inheritDoc */ + refreshAuthToken(token) { + // no-op since we just always call getToken. + } + /** + * Performs a REST request to the given path, with the provided query string parameters, + * and any auth credentials we have. + */ + restRequest_(pathString, queryStringParameters = {}, callback) { + queryStringParameters['format'] = 'export'; + return Promise.all([ + this.authTokenProvider_.getToken(/*forceRefresh=*/ false), + this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false) + ]).then(([authToken, appCheckToken]) => { + if (authToken && authToken.accessToken) { + queryStringParameters['auth'] = authToken.accessToken; + } + if (appCheckToken && appCheckToken.token) { + queryStringParameters['ac'] = appCheckToken.token; + } + const url = (this.repoInfo_.secure ? 'https://' : 'http://') + + this.repoInfo_.host + + pathString + + '?' + + 'ns=' + + this.repoInfo_.namespace + + util.querystring(queryStringParameters); + this.log_('Sending REST request for ' + url); + const xhr = new XMLHttpRequest(); + xhr.onreadystatechange = () => { + if (callback && xhr.readyState === 4) { + this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText); + let res = null; + if (xhr.status >= 200 && xhr.status < 300) { + try { + res = util.jsonEval(xhr.responseText); + } + catch (e) { + warn('Failed to parse JSON response for ' + + url + + ': ' + + xhr.responseText); + } + callback(null, res); + } + else { + // 401 and 404 are expected. + if (xhr.status !== 401 && xhr.status !== 404) { + warn('Got unsuccessful REST response for ' + + url + + ' Status: ' + + xhr.status); + } + callback(xhr.status); + } + callback = null; + } + }; + xhr.open('GET', url, /*asynchronous=*/ true); + xhr.send(); + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Mutable object which basically just stores a reference to the "latest" immutable snapshot. + */ +class SnapshotHolder { + constructor() { + this.rootNode_ = ChildrenNode.EMPTY_NODE; + } + getNode(path) { + return this.rootNode_.getChild(path); + } + updateSnapshot(path, newSnapshotNode) { + this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newSparseSnapshotTree() { + return { + value: null, + children: new Map() + }; +} +/** + * Stores the given node at the specified path. If there is already a node + * at a shallower path, it merges the new data into that snapshot node. + * + * @param path - Path to look up snapshot for. + * @param data - The new data, or null. + */ +function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) { + if (pathIsEmpty(path)) { + sparseSnapshotTree.value = data; + sparseSnapshotTree.children.clear(); + } + else if (sparseSnapshotTree.value !== null) { + sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data); + } + else { + const childKey = pathGetFront(path); + if (!sparseSnapshotTree.children.has(childKey)) { + sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree()); + } + const child = sparseSnapshotTree.children.get(childKey); + path = pathPopFront(path); + sparseSnapshotTreeRemember(child, path, data); + } +} +/** + * Purge the data at path from the cache. + * + * @param path - Path to look up snapshot for. + * @returns True if this node should now be removed. + */ +function sparseSnapshotTreeForget(sparseSnapshotTree, path) { + if (pathIsEmpty(path)) { + sparseSnapshotTree.value = null; + sparseSnapshotTree.children.clear(); + return true; + } + else { + if (sparseSnapshotTree.value !== null) { + if (sparseSnapshotTree.value.isLeafNode()) { + // We're trying to forget a node that doesn't exist + return false; + } + else { + const value = sparseSnapshotTree.value; + sparseSnapshotTree.value = null; + value.forEachChild(PRIORITY_INDEX, (key, tree) => { + sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree); + }); + return sparseSnapshotTreeForget(sparseSnapshotTree, path); + } + } + else if (sparseSnapshotTree.children.size > 0) { + const childKey = pathGetFront(path); + path = pathPopFront(path); + if (sparseSnapshotTree.children.has(childKey)) { + const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path); + if (safeToRemove) { + sparseSnapshotTree.children.delete(childKey); + } + } + return sparseSnapshotTree.children.size === 0; + } + else { + return true; + } + } +} +/** + * Recursively iterates through all of the stored tree and calls the + * callback on each one. + * + * @param prefixPath - Path to look up node for. + * @param func - The function to invoke for each tree. + */ +function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) { + if (sparseSnapshotTree.value !== null) { + func(prefixPath, sparseSnapshotTree.value); + } + else { + sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => { + const path = new Path(prefixPath.toString() + '/' + key); + sparseSnapshotTreeForEachTree(tree, path, func); + }); + } +} +/** + * Iterates through each immediate child and triggers the callback. + * Only seems to be used in tests. + * + * @param func - The function to invoke for each child. + */ +function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) { + sparseSnapshotTree.children.forEach((tree, key) => { + func(key, tree); + }); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns the delta from the previous call to get stats. + * + * @param collection_ - The collection to "listen" to. + */ +class StatsListener { + constructor(collection_) { + this.collection_ = collection_; + this.last_ = null; + } + get() { + const newStats = this.collection_.get(); + const delta = { ...newStats }; + if (this.last_) { + each(this.last_, (stat, value) => { + delta[stat] = delta[stat] - value; + }); + } + this.last_ = newStats; + return delta; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably +// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10 +// seconds to try to ensure the Firebase connection is established / settled. +const FIRST_STATS_MIN_TIME = 10 * 1000; +const FIRST_STATS_MAX_TIME = 30 * 1000; +// We'll continue to report stats on average every 5 minutes. +const REPORT_STATS_INTERVAL = 5 * 60 * 1000; +class StatsReporter { + constructor(collection, server_) { + this.server_ = server_; + this.statsToReport_ = {}; + this.statsListener_ = new StatsListener(collection); + const timeout = FIRST_STATS_MIN_TIME + + (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random(); + setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout)); + } + reportStats_() { + const stats = this.statsListener_.get(); + const reportedStats = {}; + let haveStatsToReport = false; + each(stats, (stat, value) => { + if (value > 0 && util.contains(this.statsToReport_, stat)) { + reportedStats[stat] = value; + haveStatsToReport = true; + } + }); + if (haveStatsToReport) { + this.server_.reportStats(reportedStats); + } + // queue our next run. + setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @enum + */ +var OperationType; +(function (OperationType) { + OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE"; + OperationType[OperationType["MERGE"] = 1] = "MERGE"; + OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE"; + OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE"; +})(OperationType || (OperationType = {})); +function newOperationSourceUser() { + return { + fromUser: true, + fromServer: false, + queryId: null, + tagged: false + }; +} +function newOperationSourceServer() { + return { + fromUser: false, + fromServer: true, + queryId: null, + tagged: false + }; +} +function newOperationSourceServerTaggedQuery(queryId) { + return { + fromUser: false, + fromServer: true, + queryId, + tagged: true + }; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class AckUserWrite { + /** + * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap. + */ + constructor( + /** @inheritDoc */ path, + /** @inheritDoc */ affectedTree, + /** @inheritDoc */ revert) { + this.path = path; + this.affectedTree = affectedTree; + this.revert = revert; + /** @inheritDoc */ + this.type = OperationType.ACK_USER_WRITE; + /** @inheritDoc */ + this.source = newOperationSourceUser(); + } + operationForChild(childName) { + if (!pathIsEmpty(this.path)) { + util.assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.'); + return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert); + } + else if (this.affectedTree.value != null) { + util.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.'); + // All child locations are affected as well; just return same operation. + return this; + } + else { + const childTree = this.affectedTree.subtree(new Path(childName)); + return new AckUserWrite(newEmptyPath(), childTree, this.revert); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ListenComplete { + constructor(source, path) { + this.source = source; + this.path = path; + /** @inheritDoc */ + this.type = OperationType.LISTEN_COMPLETE; + } + operationForChild(childName) { + if (pathIsEmpty(this.path)) { + return new ListenComplete(this.source, newEmptyPath()); + } + else { + return new ListenComplete(this.source, pathPopFront(this.path)); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Overwrite { + constructor(source, path, snap) { + this.source = source; + this.path = path; + this.snap = snap; + /** @inheritDoc */ + this.type = OperationType.OVERWRITE; + } + operationForChild(childName) { + if (pathIsEmpty(this.path)) { + return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName)); + } + else { + return new Overwrite(this.source, pathPopFront(this.path), this.snap); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Merge { + constructor( + /** @inheritDoc */ source, + /** @inheritDoc */ path, + /** @inheritDoc */ children) { + this.source = source; + this.path = path; + this.children = children; + /** @inheritDoc */ + this.type = OperationType.MERGE; + } + operationForChild(childName) { + if (pathIsEmpty(this.path)) { + const childTree = this.children.subtree(new Path(childName)); + if (childTree.isEmpty()) { + // This child is unaffected + return null; + } + else if (childTree.value) { + // We have a snapshot for the child in question. This becomes an overwrite of the child. + return new Overwrite(this.source, newEmptyPath(), childTree.value); + } + else { + // This is a merge at a deeper level + return new Merge(this.source, newEmptyPath(), childTree); + } + } + else { + util.assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation"); + return new Merge(this.source, pathPopFront(this.path), this.children); + } + } + toString() { + return ('Operation(' + + this.path + + ': ' + + this.source.toString() + + ' merge: ' + + this.children.toString() + + ')'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully + * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g. + * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks + * whether a node potentially had children removed due to a filter. + */ +class CacheNode { + constructor(node_, fullyInitialized_, filtered_) { + this.node_ = node_; + this.fullyInitialized_ = fullyInitialized_; + this.filtered_ = filtered_; + } + /** + * Returns whether this node was fully initialized with either server data or a complete overwrite by the client + */ + isFullyInitialized() { + return this.fullyInitialized_; + } + /** + * Returns whether this node is potentially missing children due to a filter applied to the node + */ + isFiltered() { + return this.filtered_; + } + isCompleteForPath(path) { + if (pathIsEmpty(path)) { + return this.isFullyInitialized() && !this.filtered_; + } + const childKey = pathGetFront(path); + return this.isCompleteForChild(childKey); + } + isCompleteForChild(key) { + return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key)); + } + getNode() { + return this.node_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An EventGenerator is used to convert "raw" changes (Change) as computed by the + * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges() + * for details. + * + */ +class EventGenerator { + constructor(query_) { + this.query_ = query_; + this.index_ = this.query_._queryParams.getIndex(); + } +} +/** + * Given a set of raw changes (no moved events and prevName not specified yet), and a set of + * EventRegistrations that should be notified of these changes, generate the actual events to be raised. + * + * Notes: + * - child_moved events will be synthesized at this time for any child_changed events that affect + * our index. + * - prevName will be calculated based on the index ordering. + */ +function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) { + const events = []; + const moves = []; + changes.forEach(change => { + if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ && + eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) { + moves.push(changeChildMoved(change.childName, change.snapshotNode)); + } + }); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache); + return events; +} +/** + * Given changes of a single change type, generate the corresponding events. + */ +function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) { + const filteredChanges = changes.filter(change => change.type === eventType); + filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b)); + filteredChanges.forEach(change => { + const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache); + registrations.forEach(registration => { + if (registration.respondsTo(change.type)) { + events.push(registration.createEvent(materializedChange, eventGenerator.query_)); + } + }); + }); +} +function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) { + if (change.type === 'value' || change.type === 'child_removed') { + return change; + } + else { + change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_); + return change; + } +} +function eventGeneratorCompareChanges(eventGenerator, a, b) { + if (a.childName == null || b.childName == null) { + throw util.assertionError('Should only compare child_ events.'); + } + const aWrapped = new NamedNode(a.childName, a.snapshotNode); + const bWrapped = new NamedNode(b.childName, b.snapshotNode); + return eventGenerator.index_.compare(aWrapped, bWrapped); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newViewCache(eventCache, serverCache) { + return { eventCache, serverCache }; +} +function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) { + return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache); +} +function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) { + return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered)); +} +function viewCacheGetCompleteEventSnap(viewCache) { + return viewCache.eventCache.isFullyInitialized() + ? viewCache.eventCache.getNode() + : null; +} +function viewCacheGetCompleteServerSnap(viewCache) { + return viewCache.serverCache.isFullyInitialized() + ? viewCache.serverCache.getNode() + : null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let emptyChildrenSingleton; +/** + * Singleton empty children collection. + * + */ +const EmptyChildren = () => { + if (!emptyChildrenSingleton) { + emptyChildrenSingleton = new SortedMap(stringCompare); + } + return emptyChildrenSingleton; +}; +/** + * A tree with immutable elements. + */ +class ImmutableTree { + static fromObject(obj) { + let tree = new ImmutableTree(null); + each(obj, (childPath, childSnap) => { + tree = tree.set(new Path(childPath), childSnap); + }); + return tree; + } + constructor(value, children = EmptyChildren()) { + this.value = value; + this.children = children; + } + /** + * True if the value is empty and there are no children + */ + isEmpty() { + return this.value === null && this.children.isEmpty(); + } + /** + * Given a path and predicate, return the first node and the path to that node + * where the predicate returns true. + * + * TODO Do a perf test -- If we're creating a bunch of `{path: value:}` + * objects on the way back out, it may be better to pass down a pathSoFar obj. + * + * @param relativePath - The remainder of the path + * @param predicate - The predicate to satisfy to return a node + */ + findRootMostMatchingPathAndValue(relativePath, predicate) { + if (this.value != null && predicate(this.value)) { + return { path: newEmptyPath(), value: this.value }; + } + else { + if (pathIsEmpty(relativePath)) { + return null; + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front); + if (child !== null) { + const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate); + if (childExistingPathAndValue != null) { + const fullPath = pathChild(new Path(front), childExistingPathAndValue.path); + return { path: fullPath, value: childExistingPathAndValue.value }; + } + else { + return null; + } + } + else { + return null; + } + } + } + } + /** + * Find, if it exists, the shortest subpath of the given path that points a defined + * value in the tree + */ + findRootMostValueAndPath(relativePath) { + return this.findRootMostMatchingPathAndValue(relativePath, () => true); + } + /** + * @returns The subtree at the given path + */ + subtree(relativePath) { + if (pathIsEmpty(relativePath)) { + return this; + } + else { + const front = pathGetFront(relativePath); + const childTree = this.children.get(front); + if (childTree !== null) { + return childTree.subtree(pathPopFront(relativePath)); + } + else { + return new ImmutableTree(null); + } + } + } + /** + * Sets a value at the specified path. + * + * @param relativePath - Path to set value at. + * @param toSet - Value to set. + * @returns Resulting tree. + */ + set(relativePath, toSet) { + if (pathIsEmpty(relativePath)) { + return new ImmutableTree(toSet, this.children); + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front) || new ImmutableTree(null); + const newChild = child.set(pathPopFront(relativePath), toSet); + const newChildren = this.children.insert(front, newChild); + return new ImmutableTree(this.value, newChildren); + } + } + /** + * Removes the value at the specified path. + * + * @param relativePath - Path to value to remove. + * @returns Resulting tree. + */ + remove(relativePath) { + if (pathIsEmpty(relativePath)) { + if (this.children.isEmpty()) { + return new ImmutableTree(null); + } + else { + return new ImmutableTree(null, this.children); + } + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front); + if (child) { + const newChild = child.remove(pathPopFront(relativePath)); + let newChildren; + if (newChild.isEmpty()) { + newChildren = this.children.remove(front); + } + else { + newChildren = this.children.insert(front, newChild); + } + if (this.value === null && newChildren.isEmpty()) { + return new ImmutableTree(null); + } + else { + return new ImmutableTree(this.value, newChildren); + } + } + else { + return this; + } + } + } + /** + * Gets a value from the tree. + * + * @param relativePath - Path to get value for. + * @returns Value at path, or null. + */ + get(relativePath) { + if (pathIsEmpty(relativePath)) { + return this.value; + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front); + if (child) { + return child.get(pathPopFront(relativePath)); + } + else { + return null; + } + } + } + /** + * Replace the subtree at the specified path with the given new tree. + * + * @param relativePath - Path to replace subtree for. + * @param newTree - New tree. + * @returns Resulting tree. + */ + setTree(relativePath, newTree) { + if (pathIsEmpty(relativePath)) { + return newTree; + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front) || new ImmutableTree(null); + const newChild = child.setTree(pathPopFront(relativePath), newTree); + let newChildren; + if (newChild.isEmpty()) { + newChildren = this.children.remove(front); + } + else { + newChildren = this.children.insert(front, newChild); + } + return new ImmutableTree(this.value, newChildren); + } + } + /** + * Performs a depth first fold on this tree. Transforms a tree into a single + * value, given a function that operates on the path to a node, an optional + * current value, and a map of child names to folded subtrees + */ + fold(fn) { + return this.fold_(newEmptyPath(), fn); + } + /** + * Recursive helper for public-facing fold() method + */ + fold_(pathSoFar, fn) { + const accum = {}; + this.children.inorderTraversal((childKey, childTree) => { + accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn); + }); + return fn(pathSoFar, this.value, accum); + } + /** + * Find the first matching value on the given path. Return the result of applying f to it. + */ + findOnPath(path, f) { + return this.findOnPath_(path, newEmptyPath(), f); + } + findOnPath_(pathToFollow, pathSoFar, f) { + const result = this.value ? f(pathSoFar, this.value) : false; + if (result) { + return result; + } + else { + if (pathIsEmpty(pathToFollow)) { + return null; + } + else { + const front = pathGetFront(pathToFollow); + const nextChild = this.children.get(front); + if (nextChild) { + return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f); + } + else { + return null; + } + } + } + } + foreachOnPath(path, f) { + return this.foreachOnPath_(path, newEmptyPath(), f); + } + foreachOnPath_(pathToFollow, currentRelativePath, f) { + if (pathIsEmpty(pathToFollow)) { + return this; + } + else { + if (this.value) { + f(currentRelativePath, this.value); + } + const front = pathGetFront(pathToFollow); + const nextChild = this.children.get(front); + if (nextChild) { + return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f); + } + else { + return new ImmutableTree(null); + } + } + } + /** + * Calls the given function for each node in the tree that has a value. + * + * @param f - A function to be called with the path from the root of the tree to + * a node, and the value at that node. Called in depth-first order. + */ + foreach(f) { + this.foreach_(newEmptyPath(), f); + } + foreach_(currentRelativePath, f) { + this.children.inorderTraversal((childName, childTree) => { + childTree.foreach_(pathChild(currentRelativePath, childName), f); + }); + if (this.value) { + f(currentRelativePath, this.value); + } + } + foreachChild(f) { + this.children.inorderTraversal((childName, childTree) => { + if (childTree.value) { + f(childName, childTree.value); + } + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with + * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write + * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write + * to reflect the write added. + */ +class CompoundWrite { + constructor(writeTree_) { + this.writeTree_ = writeTree_; + } + static empty() { + return new CompoundWrite(new ImmutableTree(null)); + } +} +function compoundWriteAddWrite(compoundWrite, path, node) { + if (pathIsEmpty(path)) { + return new CompoundWrite(new ImmutableTree(node)); + } + else { + const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path); + if (rootmost != null) { + const rootMostPath = rootmost.path; + let value = rootmost.value; + const relativePath = newRelativePath(rootMostPath, path); + value = value.updateChild(relativePath, node); + return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value)); + } + else { + const subtree = new ImmutableTree(node); + const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree); + return new CompoundWrite(newWriteTree); + } + } +} +function compoundWriteAddWrites(compoundWrite, path, updates) { + let newWrite = compoundWrite; + each(updates, (childKey, node) => { + newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node); + }); + return newWrite; +} +/** + * Will remove a write at the given path and deeper paths. This will not modify a write at a higher + * location, which must be removed by calling this method with that path. + * + * @param compoundWrite - The CompoundWrite to remove. + * @param path - The path at which a write and all deeper writes should be removed + * @returns The new CompoundWrite with the removed path + */ +function compoundWriteRemoveWrite(compoundWrite, path) { + if (pathIsEmpty(path)) { + return CompoundWrite.empty(); + } + else { + const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null)); + return new CompoundWrite(newWriteTree); + } +} +/** + * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be + * considered "complete". + * + * @param compoundWrite - The CompoundWrite to check. + * @param path - The path to check for + * @returns Whether there is a complete write at that path + */ +function compoundWriteHasCompleteWrite(compoundWrite, path) { + return compoundWriteGetCompleteNode(compoundWrite, path) != null; +} +/** + * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate + * writes from deeper paths, but will return child nodes from a more shallow path. + * + * @param compoundWrite - The CompoundWrite to get the node from. + * @param path - The path to get a complete write + * @returns The node if complete at that path, or null otherwise. + */ +function compoundWriteGetCompleteNode(compoundWrite, path) { + const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path); + if (rootmost != null) { + return compoundWrite.writeTree_ + .get(rootmost.path) + .getChild(newRelativePath(rootmost.path, path)); + } + else { + return null; + } +} +/** + * Returns all children that are guaranteed to be a complete overwrite. + * + * @param compoundWrite - The CompoundWrite to get children from. + * @returns A list of all complete children. + */ +function compoundWriteGetCompleteChildren(compoundWrite) { + const children = []; + const node = compoundWrite.writeTree_.value; + if (node != null) { + // If it's a leaf node, it has no children; so nothing to do. + if (!node.isLeafNode()) { + node.forEachChild(PRIORITY_INDEX, (childName, childNode) => { + children.push(new NamedNode(childName, childNode)); + }); + } + } + else { + compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => { + if (childTree.value != null) { + children.push(new NamedNode(childName, childTree.value)); + } + }); + } + return children; +} +function compoundWriteChildCompoundWrite(compoundWrite, path) { + if (pathIsEmpty(path)) { + return compoundWrite; + } + else { + const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path); + if (shadowingNode != null) { + return new CompoundWrite(new ImmutableTree(shadowingNode)); + } + else { + return new CompoundWrite(compoundWrite.writeTree_.subtree(path)); + } + } +} +/** + * Returns true if this CompoundWrite is empty and therefore does not modify any nodes. + * @returns Whether this CompoundWrite is empty + */ +function compoundWriteIsEmpty(compoundWrite) { + return compoundWrite.writeTree_.isEmpty(); +} +/** + * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the + * node + * @param node - The node to apply this CompoundWrite to + * @returns The node with all writes applied + */ +function compoundWriteApply(compoundWrite, node) { + return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node); +} +function applySubtreeWrite(relativePath, writeTree, node) { + if (writeTree.value != null) { + // Since there a write is always a leaf, we're done here + return node.updateChild(relativePath, writeTree.value); + } + else { + let priorityWrite = null; + writeTree.children.inorderTraversal((childKey, childTree) => { + if (childKey === '.priority') { + // Apply priorities at the end so we don't update priorities for either empty nodes or forget + // to apply priorities to empty nodes that are later filled + util.assert(childTree.value !== null, 'Priority writes must always be leaf nodes'); + priorityWrite = childTree.value; + } + else { + node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node); + } + }); + // If there was a priority write, we only apply it if the node is not empty + if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) { + node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite); + } + return node; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path. + * + */ +function writeTreeChildWrites(writeTree, path) { + return newWriteTreeRef(path, writeTree); +} +/** + * Record a new overwrite from user code. + * + * @param visible - This is set to false by some transactions. It should be excluded from event caches + */ +function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) { + util.assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones'); + if (visible === undefined) { + visible = true; + } + writeTree.allWrites.push({ + path, + snap, + writeId, + visible + }); + if (visible) { + writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap); + } + writeTree.lastWriteId = writeId; +} +/** + * Record a new merge from user code. + */ +function writeTreeAddMerge(writeTree, path, changedChildren, writeId) { + util.assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones'); + writeTree.allWrites.push({ + path, + children: changedChildren, + writeId, + visible: true + }); + writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren); + writeTree.lastWriteId = writeId; +} +function writeTreeGetWrite(writeTree, writeId) { + for (let i = 0; i < writeTree.allWrites.length; i++) { + const record = writeTree.allWrites[i]; + if (record.writeId === writeId) { + return record; + } + } + return null; +} +/** + * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates + * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate. + * + * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise + * events as a result). + */ +function writeTreeRemoveWrite(writeTree, writeId) { + // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied + // out of order. + //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId; + //assert(validClear, "Either we don't have this write, or it's the first one in the queue"); + const idx = writeTree.allWrites.findIndex(s => { + return s.writeId === writeId; + }); + util.assert(idx >= 0, 'removeWrite called with nonexistent writeId.'); + const writeToRemove = writeTree.allWrites[idx]; + writeTree.allWrites.splice(idx, 1); + let removedWriteWasVisible = writeToRemove.visible; + let removedWriteOverlapsWithOtherWrites = false; + let i = writeTree.allWrites.length - 1; + while (removedWriteWasVisible && i >= 0) { + const currentWrite = writeTree.allWrites[i]; + if (currentWrite.visible) { + if (i >= idx && + writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) { + // The removed write was completely shadowed by a subsequent write. + removedWriteWasVisible = false; + } + else if (pathContains(writeToRemove.path, currentWrite.path)) { + // Either we're covering some writes or they're covering part of us (depending on which came first). + removedWriteOverlapsWithOtherWrites = true; + } + } + i--; + } + if (!removedWriteWasVisible) { + return false; + } + else if (removedWriteOverlapsWithOtherWrites) { + // There's some shadowing going on. Just rebuild the visible writes from scratch. + writeTreeResetTree_(writeTree); + return true; + } + else { + // There's no shadowing. We can safely just remove the write(s) from visibleWrites. + if (writeToRemove.snap) { + writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path); + } + else { + const children = writeToRemove.children; + each(children, (childName) => { + writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName)); + }); + } + return true; + } +} +function writeTreeRecordContainsPath_(writeRecord, path) { + if (writeRecord.snap) { + return pathContains(writeRecord.path, path); + } + else { + for (const childName in writeRecord.children) { + if (writeRecord.children.hasOwnProperty(childName) && + pathContains(pathChild(writeRecord.path, childName), path)) { + return true; + } + } + return false; + } +} +/** + * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots + */ +function writeTreeResetTree_(writeTree) { + writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath()); + if (writeTree.allWrites.length > 0) { + writeTree.lastWriteId = + writeTree.allWrites[writeTree.allWrites.length - 1].writeId; + } + else { + writeTree.lastWriteId = -1; + } +} +/** + * The default filter used when constructing the tree. Keep everything that's visible. + */ +function writeTreeDefaultFilter_(write) { + return write.visible; +} +/** + * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of + * event data at that path. + */ +function writeTreeLayerTree_(writes, filter, treeRoot) { + let compoundWrite = CompoundWrite.empty(); + for (let i = 0; i < writes.length; ++i) { + const write = writes[i]; + // Theory, a later set will either: + // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction + // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction + if (filter(write)) { + const writePath = write.path; + let relativePath; + if (write.snap) { + if (pathContains(treeRoot, writePath)) { + relativePath = newRelativePath(treeRoot, writePath); + compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap); + } + else if (pathContains(writePath, treeRoot)) { + relativePath = newRelativePath(writePath, treeRoot); + compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath)); + } + else ; + } + else if (write.children) { + if (pathContains(treeRoot, writePath)) { + relativePath = newRelativePath(treeRoot, writePath); + compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children); + } + else if (pathContains(writePath, treeRoot)) { + relativePath = newRelativePath(writePath, treeRoot); + if (pathIsEmpty(relativePath)) { + compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children); + } + else { + const child = util.safeGet(write.children, pathGetFront(relativePath)); + if (child) { + // There exists a child in this node that matches the root path + const deepNode = child.getChild(pathPopFront(relativePath)); + compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode); + } + } + } + else ; + } + else { + throw util.assertionError('WriteRecord should have .snap or .children'); + } + } + } + return compoundWrite; +} +/** + * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden + * writes), attempt to calculate a complete snapshot for the given path + * + * @param writeIdsToExclude - An optional set to be excluded + * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false + */ +function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) { + if (!writeIdsToExclude && !includeHiddenWrites) { + const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath); + if (shadowingNode != null) { + return shadowingNode; + } + else { + const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + if (compoundWriteIsEmpty(subMerge)) { + return completeServerCache; + } + else if (completeServerCache == null && + !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) { + // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow + return null; + } + else { + const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE; + return compoundWriteApply(subMerge, layeredCache); + } + } + } + else { + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) { + return completeServerCache; + } + else { + // If the server cache is null, and we don't have a complete cache, we need to return null + if (!includeHiddenWrites && + completeServerCache == null && + !compoundWriteHasCompleteWrite(merge, newEmptyPath())) { + return null; + } + else { + const filter = function (write) { + return ((write.visible || includeHiddenWrites) && + (!writeIdsToExclude || + !~writeIdsToExclude.indexOf(write.writeId)) && + (pathContains(write.path, treePath) || + pathContains(treePath, write.path))); + }; + const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath); + const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE; + return compoundWriteApply(mergeAtPath, layeredCache); + } + } + } +} +/** + * With optional, underlying server data, attempt to return a children node of children that we have complete data for. + * Used when creating new views, to pre-fill their complete event children snapshot. + */ +function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) { + let completeChildren = ChildrenNode.EMPTY_NODE; + const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath); + if (topLevelSet) { + if (!topLevelSet.isLeafNode()) { + // we're shadowing everything. Return the children. + topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => { + completeChildren = completeChildren.updateImmediateChild(childName, childSnap); + }); + } + return completeChildren; + } + else if (completeServerChildren) { + // Layer any children we have on top of this + // We know we don't have a top-level set, so just enumerate existing children + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => { + const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode); + completeChildren = completeChildren.updateImmediateChild(childName, node); + }); + // Add any complete children we have from the set + compoundWriteGetCompleteChildren(merge).forEach(namedNode => { + completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node); + }); + return completeChildren; + } + else { + // We don't have anything to layer on top of. Layer on any children we have + // Note that we can return an empty snap if we have a defined delete + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + compoundWriteGetCompleteChildren(merge).forEach(namedNode => { + completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node); + }); + return completeChildren; + } +} +/** + * Given that the underlying server data has updated, determine what, if anything, needs to be + * applied to the event cache. + * + * Possibilities: + * + * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data + * + * 2. Some write is completely shadowing. No events to be raised + * + * 3. Is partially shadowed. Events + * + * Either existingEventSnap or existingServerSnap must exist + */ +function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) { + util.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist'); + const path = pathChild(treePath, childPath); + if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) { + // At this point we can probably guarantee that we're in case 2, meaning no events + // May need to check visibility while doing the findRootMostValueAndPath call + return null; + } + else { + // No complete shadowing. We're either partially shadowing or not shadowing at all. + const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path); + if (compoundWriteIsEmpty(childMerge)) { + // We're not shadowing at all. Case 1 + return existingServerSnap.getChild(childPath); + } + else { + // This could be more efficient if the serverNode + updates doesn't change the eventSnap + // However this is tricky to find out, since user updates don't necessary change the server + // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server + // adds nodes, but doesn't change any existing writes. It is therefore not enough to + // only check if the updates change the serverNode. + // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case? + return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath)); + } + } +} +/** + * Returns a complete child for a given server snap after applying all user writes or null if there is no + * complete child for this ChildKey. + */ +function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) { + const path = pathChild(treePath, childKey); + const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path); + if (shadowingNode != null) { + return shadowingNode; + } + else { + if (existingServerSnap.isCompleteForChild(childKey)) { + const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path); + return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey)); + } + else { + return null; + } + } +} +/** + * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at + * a higher path, this will return the child of that write relative to the write and this path. + * Returns null if there is no write at this path. + */ +function writeTreeShadowingWrite(writeTree, path) { + return compoundWriteGetCompleteNode(writeTree.visibleWrites, path); +} +/** + * This method is used when processing child remove events on a query. If we can, we pull in children that were outside + * the window, but may now be in the window. + */ +function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) { + let toIterate; + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath()); + if (shadowingNode != null) { + toIterate = shadowingNode; + } + else if (completeServerData != null) { + toIterate = compoundWriteApply(merge, completeServerData); + } + else { + // no children to iterate on + return []; + } + toIterate = toIterate.withIndex(index); + if (!toIterate.isEmpty() && !toIterate.isLeafNode()) { + const nodes = []; + const cmp = index.getCompare(); + const iter = reverse + ? toIterate.getReverseIteratorFrom(startPost, index) + : toIterate.getIteratorFrom(startPost, index); + let next = iter.getNext(); + while (next && nodes.length < count) { + if (cmp(next, startPost) !== 0) { + nodes.push(next); + } + next = iter.getNext(); + } + return nodes; + } + else { + return []; + } +} +function newWriteTree() { + return { + visibleWrites: CompoundWrite.empty(), + allWrites: [], + lastWriteId: -1 + }; +} +/** + * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used + * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node + * can lead to a more expensive calculation. + * + * @param writeIdsToExclude - Optional writes to exclude. + * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false + */ +function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) { + return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites); +} +/** + * If possible, returns a children node containing all of the complete children we have data for. The returned data is a + * mix of the given server data and write data. + * + */ +function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) { + return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren); +} +/** + * Given that either the underlying server data has updated or the outstanding writes have updated, determine what, + * if anything, needs to be applied to the event cache. + * + * Possibilities: + * + * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data + * + * 2. Some write is completely shadowing. No events to be raised + * + * 3. Is partially shadowed. Events should be raised + * + * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert + * + * + */ +function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) { + return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap); +} +/** + * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at + * a higher path, this will return the child of that write relative to the write and this path. + * Returns null if there is no write at this path. + * + */ +function writeTreeRefShadowingWrite(writeTreeRef, path) { + return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path)); +} +/** + * This method is used when processing child remove events on a query. If we can, we pull in children that were outside + * the window, but may now be in the window + */ +function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) { + return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index); +} +/** + * Returns a complete child for a given server snap after applying all user writes or null if there is no + * complete child for this ChildKey. + */ +function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) { + return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache); +} +/** + * Return a WriteTreeRef for a child. + */ +function writeTreeRefChild(writeTreeRef, childName) { + return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree); +} +function newWriteTreeRef(path, writeTree) { + return { + treePath: path, + writeTree + }; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ChildChangeAccumulator { + constructor() { + this.changeMap = new Map(); + } + trackChildChange(change) { + const type = change.type; + const childKey = change.childName; + util.assert(type === "child_added" /* ChangeType.CHILD_ADDED */ || + type === "child_changed" /* ChangeType.CHILD_CHANGED */ || + type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking'); + util.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.'); + const oldChange = this.changeMap.get(childKey); + if (oldChange) { + const oldType = oldChange.type; + if (type === "child_added" /* ChangeType.CHILD_ADDED */ && + oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) { + this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode)); + } + else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ && + oldType === "child_added" /* ChangeType.CHILD_ADDED */) { + this.changeMap.delete(childKey); + } + else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ && + oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) { + this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap)); + } + else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ && + oldType === "child_added" /* ChangeType.CHILD_ADDED */) { + this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode)); + } + else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ && + oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) { + this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap)); + } + else { + throw util.assertionError('Illegal combination of changes: ' + + change + + ' occurred after ' + + oldChange); + } + } + else { + this.changeMap.set(childKey, change); + } + } + getChanges() { + return Array.from(this.changeMap.values()); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An implementation of CompleteChildSource that never returns any additional children + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class NoCompleteChildSource_ { + getCompleteChild(childKey) { + return null; + } + getChildAfterChild(index, child, reverse) { + return null; + } +} +/** + * Singleton instance. + */ +const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_(); +/** + * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or + * old event caches available to calculate complete children. + */ +class WriteTreeCompleteChildSource { + constructor(writes_, viewCache_, optCompleteServerCache_ = null) { + this.writes_ = writes_; + this.viewCache_ = viewCache_; + this.optCompleteServerCache_ = optCompleteServerCache_; + } + getCompleteChild(childKey) { + const node = this.viewCache_.eventCache; + if (node.isCompleteForChild(childKey)) { + return node.getNode().getImmediateChild(childKey); + } + else { + const serverNode = this.optCompleteServerCache_ != null + ? new CacheNode(this.optCompleteServerCache_, true, false) + : this.viewCache_.serverCache; + return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode); + } + } + getChildAfterChild(index, child, reverse) { + const completeServerData = this.optCompleteServerCache_ != null + ? this.optCompleteServerCache_ + : viewCacheGetCompleteServerSnap(this.viewCache_); + const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index); + if (nodes.length === 0) { + return null; + } + else { + return nodes[0]; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newViewProcessor(filter) { + return { filter }; +} +function viewProcessorAssertIndexed(viewProcessor, viewCache) { + util.assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed'); + util.assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed'); +} +function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) { + const accumulator = new ChildChangeAccumulator(); + let newViewCache, filterServerNode; + if (operation.type === OperationType.OVERWRITE) { + const overwrite = operation; + if (overwrite.source.fromUser) { + newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator); + } + else { + util.assert(overwrite.source.fromServer, 'Unknown source.'); + // We filter the node if it's a tagged update or the node has been previously filtered and the + // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered + // again + filterServerNode = + overwrite.source.tagged || + (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path)); + newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator); + } + } + else if (operation.type === OperationType.MERGE) { + const merge = operation; + if (merge.source.fromUser) { + newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator); + } + else { + util.assert(merge.source.fromServer, 'Unknown source.'); + // We filter the node if it's a tagged update or the node has been previously filtered + filterServerNode = + merge.source.tagged || oldViewCache.serverCache.isFiltered(); + newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator); + } + } + else if (operation.type === OperationType.ACK_USER_WRITE) { + const ackUserWrite = operation; + if (!ackUserWrite.revert) { + newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator); + } + else { + newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator); + } + } + else if (operation.type === OperationType.LISTEN_COMPLETE) { + newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator); + } + else { + throw util.assertionError('Unknown operation type: ' + operation.type); + } + const changes = accumulator.getChanges(); + viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes); + return { viewCache: newViewCache, changes }; +} +function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) { + const eventSnap = newViewCache.eventCache; + if (eventSnap.isFullyInitialized()) { + const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty(); + const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache); + if (accumulator.length > 0 || + !oldViewCache.eventCache.isFullyInitialized() || + (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) || + !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) { + accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache))); + } + } +} +function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) { + const oldEventSnap = viewCache.eventCache; + if (writeTreeRefShadowingWrite(writesCache, changePath) != null) { + // we have a shadowing write, ignore changes + return viewCache; + } + else { + let newEventCache, serverNode; + if (pathIsEmpty(changePath)) { + // TODO: figure out how this plays with "sliding ack windows" + util.assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data'); + if (viewCache.serverCache.isFiltered()) { + // We need to special case this, because we need to only apply writes to complete children, or + // we might end up raising events for incomplete children. If the server data is filtered deep + // writes cannot be guaranteed to be complete + const serverCache = viewCacheGetCompleteServerSnap(viewCache); + const completeChildren = serverCache instanceof ChildrenNode + ? serverCache + : ChildrenNode.EMPTY_NODE; + const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren); + newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator); + } + else { + const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache)); + newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator); + } + } + else { + const childKey = pathGetFront(changePath); + if (childKey === '.priority') { + util.assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components"); + const oldEventNode = oldEventSnap.getNode(); + serverNode = viewCache.serverCache.getNode(); + // we might have overwrites for this priority + const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode); + if (updatedPriority != null) { + newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority); + } + else { + // priority didn't change, keep old node + newEventCache = oldEventSnap.getNode(); + } + } + else { + const childChangePath = pathPopFront(changePath); + // update child + let newEventChild; + if (oldEventSnap.isCompleteForChild(childKey)) { + serverNode = viewCache.serverCache.getNode(); + const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode); + if (eventChildUpdate != null) { + newEventChild = oldEventSnap + .getNode() + .getImmediateChild(childKey) + .updateChild(childChangePath, eventChildUpdate); + } + else { + // Nothing changed, just keep the old child + newEventChild = oldEventSnap.getNode().getImmediateChild(childKey); + } + } + else { + newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache); + } + if (newEventChild != null) { + newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator); + } + else { + // no complete child available or no change + newEventCache = oldEventSnap.getNode(); + } + } + } + return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes()); + } +} +function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) { + const oldServerSnap = oldViewCache.serverCache; + let newServerCache; + const serverFilter = filterServerNode + ? viewProcessor.filter + : viewProcessor.filter.getIndexedFilter(); + if (pathIsEmpty(changePath)) { + newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null); + } + else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) { + // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update + const newServerNode = oldServerSnap + .getNode() + .updateChild(changePath, changedSnap); + newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null); + } + else { + const childKey = pathGetFront(changePath); + if (!oldServerSnap.isCompleteForPath(changePath) && + pathGetLength(changePath) > 1) { + // We don't update incomplete nodes with updates intended for other listeners + return oldViewCache; + } + const childChangePath = pathPopFront(changePath); + const childNode = oldServerSnap.getNode().getImmediateChild(childKey); + const newChildNode = childNode.updateChild(childChangePath, changedSnap); + if (childKey === '.priority') { + newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode); + } + else { + newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null); + } + } + const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes()); + const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache); + return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator); +} +function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) { + const oldEventSnap = oldViewCache.eventCache; + let newViewCache, newEventCache; + const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache); + if (pathIsEmpty(changePath)) { + newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator); + newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes()); + } + else { + const childKey = pathGetFront(changePath); + if (childKey === '.priority') { + newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap); + newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered()); + } + else { + const childChangePath = pathPopFront(changePath); + const oldChild = oldEventSnap.getNode().getImmediateChild(childKey); + let newChild; + if (pathIsEmpty(childChangePath)) { + // Child overwrite, we can replace the child + newChild = changedSnap; + } + else { + const childNode = source.getCompleteChild(childKey); + if (childNode != null) { + if (pathGetBack(childChangePath) === '.priority' && + childNode.getChild(pathParent(childChangePath)).isEmpty()) { + // This is a priority update on an empty node. If this node exists on the server, the + // server will send down the priority in the update, so ignore for now + newChild = childNode; + } + else { + newChild = childNode.updateChild(childChangePath, changedSnap); + } + } + else { + // There is no complete child node available + newChild = ChildrenNode.EMPTY_NODE; + } + } + if (!oldChild.equals(newChild)) { + const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator); + newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes()); + } + else { + newViewCache = oldViewCache; + } + } + } + return newViewCache; +} +function viewProcessorCacheHasChild(viewCache, childKey) { + return viewCache.eventCache.isCompleteForChild(childKey); +} +function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) { + // HACK: In the case of a limit query, there may be some changes that bump things out of the + // window leaving room for new items. It's important we process these changes first, so we + // iterate the changes twice, first processing any that affect items currently in view. + // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server + // and event snap. I'm not sure if this will result in edge cases when a child is in one but + // not the other. + let curViewCache = viewCache; + changedChildren.foreach((relativePath, childNode) => { + const writePath = pathChild(path, relativePath); + if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) { + curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator); + } + }); + changedChildren.foreach((relativePath, childNode) => { + const writePath = pathChild(path, relativePath); + if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) { + curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator); + } + }); + return curViewCache; +} +function viewProcessorApplyMerge(viewProcessor, node, merge) { + merge.foreach((relativePath, childNode) => { + node = node.updateChild(relativePath, childNode); + }); + return node; +} +function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) { + // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and + // wait for the complete data update coming soon. + if (viewCache.serverCache.getNode().isEmpty() && + !viewCache.serverCache.isFullyInitialized()) { + return viewCache; + } + // HACK: In the case of a limit query, there may be some changes that bump things out of the + // window leaving room for new items. It's important we process these changes first, so we + // iterate the changes twice, first processing any that affect items currently in view. + // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server + // and event snap. I'm not sure if this will result in edge cases when a child is in one but + // not the other. + let curViewCache = viewCache; + let viewMergeTree; + if (pathIsEmpty(path)) { + viewMergeTree = changedChildren; + } + else { + viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren); + } + const serverNode = viewCache.serverCache.getNode(); + viewMergeTree.children.inorderTraversal((childKey, childTree) => { + if (serverNode.hasChild(childKey)) { + const serverChild = viewCache.serverCache + .getNode() + .getImmediateChild(childKey); + const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree); + curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator); + } + }); + viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => { + const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) && + childMergeTree.value === null; + if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) { + const serverChild = viewCache.serverCache + .getNode() + .getImmediateChild(childKey); + const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree); + curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator); + } + }); + return curViewCache; +} +function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) { + if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) { + return viewCache; + } + // Only filter server node if it is currently filtered + const filterServerNode = viewCache.serverCache.isFiltered(); + // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update + // now that it won't be shadowed. + const serverCache = viewCache.serverCache; + if (affectedTree.value != null) { + // This is an overwrite. + if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) || + serverCache.isCompleteForPath(ackPath)) { + return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator); + } + else if (pathIsEmpty(ackPath)) { + // This is a goofy edge case where we are acking data at this location but don't have full data. We + // should just re-apply whatever we have in our cache as a merge. + let changedChildren = new ImmutableTree(null); + serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => { + changedChildren = changedChildren.set(new Path(name), node); + }); + return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator); + } + else { + return viewCache; + } + } + else { + // This is a merge. + let changedChildren = new ImmutableTree(null); + affectedTree.foreach((mergePath, value) => { + const serverCachePath = pathChild(ackPath, mergePath); + if (serverCache.isCompleteForPath(serverCachePath)) { + changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath)); + } + }); + return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator); + } +} +function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) { + const oldServerNode = viewCache.serverCache; + const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered()); + return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator); +} +function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) { + let complete; + if (writeTreeRefShadowingWrite(writesCache, path) != null) { + return viewCache; + } + else { + const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache); + const oldEventCache = viewCache.eventCache.getNode(); + let newEventCache; + if (pathIsEmpty(path) || pathGetFront(path) === '.priority') { + let newNode; + if (viewCache.serverCache.isFullyInitialized()) { + newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache)); + } + else { + const serverChildren = viewCache.serverCache.getNode(); + util.assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node'); + newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren); + } + newNode = newNode; + newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator); + } + else { + const childKey = pathGetFront(path); + let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache); + if (newChild == null && + viewCache.serverCache.isCompleteForChild(childKey)) { + newChild = oldEventCache.getImmediateChild(childKey); + } + if (newChild != null) { + newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator); + } + else if (viewCache.eventCache.getNode().hasChild(childKey)) { + // No complete child available, delete the existing one, if any + newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator); + } + else { + newEventCache = oldEventCache; + } + if (newEventCache.isEmpty() && + viewCache.serverCache.isFullyInitialized()) { + // We might have reverted all child writes. Maybe the old event was a leaf node + complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache)); + if (complete.isLeafNode()) { + newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator); + } + } + } + complete = + viewCache.serverCache.isFullyInitialized() || + writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null; + return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes()); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A view represents a specific location and query that has 1 or more event registrations. + * + * It does several things: + * - Maintains the list of event registrations for this location/query. + * - Maintains a cache of the data visible for this location/query. + * - Applies new operations (via applyOperation), updates the cache, and based on the event + * registrations returns the set of events to be raised. + */ +class View { + constructor(query_, initialViewCache) { + this.query_ = query_; + this.eventRegistrations_ = []; + const params = this.query_._queryParams; + const indexFilter = new IndexedFilter(params.getIndex()); + const filter = queryParamsGetNodeFilter(params); + this.processor_ = newViewProcessor(filter); + const initialServerCache = initialViewCache.serverCache; + const initialEventCache = initialViewCache.eventCache; + // Don't filter server node with other filter than index, wait for tagged listen + const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null); + const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null); + const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes()); + const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes()); + this.viewCache_ = newViewCache(newEventCache, newServerCache); + this.eventGenerator_ = new EventGenerator(this.query_); + } + get query() { + return this.query_; + } +} +function viewGetServerCache(view) { + return view.viewCache_.serverCache.getNode(); +} +function viewGetCompleteNode(view) { + return viewCacheGetCompleteEventSnap(view.viewCache_); +} +function viewGetCompleteServerCache(view, path) { + const cache = viewCacheGetCompleteServerSnap(view.viewCache_); + if (cache) { + // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and + // we need to see if it contains the child we're interested in. + if (view.query._queryParams.loadsAllData() || + (!pathIsEmpty(path) && + !cache.getImmediateChild(pathGetFront(path)).isEmpty())) { + return cache.getChild(path); + } + } + return null; +} +function viewIsEmpty(view) { + return view.eventRegistrations_.length === 0; +} +function viewAddEventRegistration(view, eventRegistration) { + view.eventRegistrations_.push(eventRegistration); +} +/** + * @param eventRegistration - If null, remove all callbacks. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @returns Cancel events, if cancelError was provided. + */ +function viewRemoveEventRegistration(view, eventRegistration, cancelError) { + const cancelEvents = []; + if (cancelError) { + util.assert(eventRegistration == null, 'A cancel should cancel all event registrations.'); + const path = view.query._path; + view.eventRegistrations_.forEach(registration => { + const maybeEvent = registration.createCancelEvent(cancelError, path); + if (maybeEvent) { + cancelEvents.push(maybeEvent); + } + }); + } + if (eventRegistration) { + let remaining = []; + for (let i = 0; i < view.eventRegistrations_.length; ++i) { + const existing = view.eventRegistrations_[i]; + if (!existing.matches(eventRegistration)) { + remaining.push(existing); + } + else if (eventRegistration.hasAnyCallback()) { + // We're removing just this one + remaining = remaining.concat(view.eventRegistrations_.slice(i + 1)); + break; + } + } + view.eventRegistrations_ = remaining; + } + else { + view.eventRegistrations_ = []; + } + return cancelEvents; +} +/** + * Applies the given Operation, updates our cache, and returns the appropriate events. + */ +function viewApplyOperation(view, operation, writesCache, completeServerCache) { + if (operation.type === OperationType.MERGE && + operation.source.queryId !== null) { + util.assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges'); + util.assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache'); + } + const oldViewCache = view.viewCache_; + const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache); + viewProcessorAssertIndexed(view.processor_, result.viewCache); + util.assert(result.viewCache.serverCache.isFullyInitialized() || + !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back'); + view.viewCache_ = result.viewCache; + return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null); +} +function viewGetInitialEvents(view, registration) { + const eventSnap = view.viewCache_.eventCache; + const initialChanges = []; + if (!eventSnap.getNode().isLeafNode()) { + const eventNode = eventSnap.getNode(); + eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => { + initialChanges.push(changeChildAdded(key, childNode)); + }); + } + if (eventSnap.isFullyInitialized()) { + initialChanges.push(changeValue(eventSnap.getNode())); + } + return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration); +} +function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) { + const registrations = eventRegistration + ? [eventRegistration] + : view.eventRegistrations_; + return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let referenceConstructor$1; +/** + * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to + * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes + * and user writes (set, transaction, update). + * + * It's responsible for: + * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed). + * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite, + * applyUserOverwrite, etc.) + */ +class SyncPoint { + constructor() { + /** + * The Views being tracked at this location in the tree, stored as a map where the key is a + * queryId and the value is the View for that query. + * + * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case). + */ + this.views = new Map(); + } +} +function syncPointSetReferenceConstructor(val) { + util.assert(!referenceConstructor$1, '__referenceConstructor has already been defined'); + referenceConstructor$1 = val; +} +function syncPointGetReferenceConstructor() { + util.assert(referenceConstructor$1, 'Reference.ts has not been loaded'); + return referenceConstructor$1; +} +function syncPointIsEmpty(syncPoint) { + return syncPoint.views.size === 0; +} +function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) { + const queryId = operation.source.queryId; + if (queryId !== null) { + const view = syncPoint.views.get(queryId); + util.assert(view != null, 'SyncTree gave us an op for an invalid query.'); + return viewApplyOperation(view, operation, writesCache, optCompleteServerCache); + } + else { + let events = []; + for (const view of syncPoint.views.values()) { + events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache)); + } + return events; + } +} +/** + * Get a view for the specified query. + * + * @param query - The query to return a view for + * @param writesCache + * @param serverCache + * @param serverCacheComplete + * @returns Events to raise. + */ +function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) { + const queryId = query._queryIdentifier; + const view = syncPoint.views.get(queryId); + if (!view) { + // TODO: make writesCache take flag for complete server node + let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null); + let eventCacheComplete = false; + if (eventCache) { + eventCacheComplete = true; + } + else if (serverCache instanceof ChildrenNode) { + eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache); + eventCacheComplete = false; + } + else { + eventCache = ChildrenNode.EMPTY_NODE; + eventCacheComplete = false; + } + const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false)); + return new View(query, viewCache); + } + return view; +} +/** + * Add an event callback for the specified query. + * + * @param query + * @param eventRegistration + * @param writesCache + * @param serverCache - Complete server cache, if we have it. + * @param serverCacheComplete + * @returns Events to raise. + */ +function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) { + const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete); + if (!syncPoint.views.has(query._queryIdentifier)) { + syncPoint.views.set(query._queryIdentifier, view); + } + // This is guaranteed to exist now, we just created anything that was missing + viewAddEventRegistration(view, eventRegistration); + return viewGetInitialEvents(view, eventRegistration); +} +/** + * Remove event callback(s). Return cancelEvents if a cancelError is specified. + * + * If query is the default query, we'll check all views for the specified eventRegistration. + * If eventRegistration is null, we'll remove all callbacks for the specified view(s). + * + * @param eventRegistration - If null, remove all callbacks. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @returns removed queries and any cancel events + */ +function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) { + const queryId = query._queryIdentifier; + const removed = []; + let cancelEvents = []; + const hadCompleteView = syncPointHasCompleteView(syncPoint); + if (queryId === 'default') { + // When you do ref.off(...), we search all views for the registration to remove. + for (const [viewQueryId, view] of syncPoint.views.entries()) { + cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError)); + if (viewIsEmpty(view)) { + syncPoint.views.delete(viewQueryId); + // We'll deal with complete views later. + if (!view.query._queryParams.loadsAllData()) { + removed.push(view.query); + } + } + } + } + else { + // remove the callback from the specific view. + const view = syncPoint.views.get(queryId); + if (view) { + cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError)); + if (viewIsEmpty(view)) { + syncPoint.views.delete(queryId); + // We'll deal with complete views later. + if (!view.query._queryParams.loadsAllData()) { + removed.push(view.query); + } + } + } + } + if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) { + // We removed our last complete view. + removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path)); + } + return { removed, events: cancelEvents }; +} +function syncPointGetQueryViews(syncPoint) { + const result = []; + for (const view of syncPoint.views.values()) { + if (!view.query._queryParams.loadsAllData()) { + result.push(view); + } + } + return result; +} +/** + * @param path - The path to the desired complete snapshot + * @returns A complete cache, if it exists + */ +function syncPointGetCompleteServerCache(syncPoint, path) { + let serverCache = null; + for (const view of syncPoint.views.values()) { + serverCache = serverCache || viewGetCompleteServerCache(view, path); + } + return serverCache; +} +function syncPointViewForQuery(syncPoint, query) { + const params = query._queryParams; + if (params.loadsAllData()) { + return syncPointGetCompleteView(syncPoint); + } + else { + const queryId = query._queryIdentifier; + return syncPoint.views.get(queryId); + } +} +function syncPointViewExistsForQuery(syncPoint, query) { + return syncPointViewForQuery(syncPoint, query) != null; +} +function syncPointHasCompleteView(syncPoint) { + return syncPointGetCompleteView(syncPoint) != null; +} +function syncPointGetCompleteView(syncPoint) { + for (const view of syncPoint.views.values()) { + if (view.query._queryParams.loadsAllData()) { + return view; + } + } + return null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let referenceConstructor; +function syncTreeSetReferenceConstructor(val) { + util.assert(!referenceConstructor, '__referenceConstructor has already been defined'); + referenceConstructor = val; +} +function syncTreeGetReferenceConstructor() { + util.assert(referenceConstructor, 'Reference.ts has not been loaded'); + return referenceConstructor; +} +/** + * Static tracker for next query tag. + */ +let syncTreeNextQueryTag_ = 1; +/** + * SyncTree is the central class for managing event callback registration, data caching, views + * (query processing), and event generation. There are typically two SyncTree instances for + * each Repo, one for the normal Firebase data, and one for the .info data. + * + * It has a number of responsibilities, including: + * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()). + * - Applying and caching data changes for user set(), transaction(), and update() calls + * (applyUserOverwrite(), applyUserMerge()). + * - Applying and caching data changes for server data changes (applyServerOverwrite(), + * applyServerMerge()). + * - Generating user-facing events for server and user changes (all of the apply* methods + * return the set of events that need to be raised as a result). + * - Maintaining the appropriate set of server listens to ensure we are always subscribed + * to the correct set of paths and queries to satisfy the current set of user event + * callbacks (listens are started/stopped using the provided listenProvider). + * + * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual + * events are returned to the caller rather than raised synchronously. + * + */ +class SyncTree { + /** + * @param listenProvider_ - Used by SyncTree to start / stop listening + * to server data. + */ + constructor(listenProvider_) { + this.listenProvider_ = listenProvider_; + /** + * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views. + */ + this.syncPointTree_ = new ImmutableTree(null); + /** + * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.). + */ + this.pendingWriteTree_ = newWriteTree(); + this.tagToQueryMap = new Map(); + this.queryToTagMap = new Map(); + } +} +/** + * Apply the data changes for a user-generated set() or transaction() call. + * + * @returns Events to raise. + */ +function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) { + // Record pending write. + writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible); + if (!visible) { + return []; + } + else { + return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData)); + } +} +/** + * Apply the data from a user-generated update() call + * + * @returns Events to raise. + */ +function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) { + // Record pending merge. + writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId); + const changeTree = ImmutableTree.fromObject(changedChildren); + return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree)); +} +/** + * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge(). + * + * @param revert - True if the given write failed and needs to be reverted + * @returns Events to raise. + */ +function syncTreeAckUserWrite(syncTree, writeId, revert = false) { + const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId); + const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId); + if (!needToReevaluate) { + return []; + } + else { + let affectedTree = new ImmutableTree(null); + if (write.snap != null) { + // overwrite + affectedTree = affectedTree.set(newEmptyPath(), true); + } + else { + each(write.children, (pathString) => { + affectedTree = affectedTree.set(new Path(pathString), true); + }); + } + return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert)); + } +} +/** + * Apply new server data for the specified path.. + * + * @returns Events to raise. + */ +function syncTreeApplyServerOverwrite(syncTree, path, newData) { + return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData)); +} +/** + * Apply new server data to be merged in at the specified path. + * + * @returns Events to raise. + */ +function syncTreeApplyServerMerge(syncTree, path, changedChildren) { + const changeTree = ImmutableTree.fromObject(changedChildren); + return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree)); +} +/** + * Apply a listen complete for a query + * + * @returns Events to raise. + */ +function syncTreeApplyListenComplete(syncTree, path) { + return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path)); +} +/** + * Apply a listen complete for a tagged query + * + * @returns Events to raise. + */ +function syncTreeApplyTaggedListenComplete(syncTree, path, tag) { + const queryKey = syncTreeQueryKeyForTag_(syncTree, tag); + if (queryKey) { + const r = syncTreeParseQueryKey_(queryKey); + const queryPath = r.path, queryId = r.queryId; + const relativePath = newRelativePath(queryPath, path); + const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath); + return syncTreeApplyTaggedOperation_(syncTree, queryPath, op); + } + else { + // We've already removed the query. No big deal, ignore the update + return []; + } +} +/** + * Remove event callback(s). + * + * If query is the default query, we'll check all queries for the specified eventRegistration. + * If eventRegistration is null, we'll remove all callbacks for the specified query/queries. + * + * @param eventRegistration - If null, all callbacks are removed. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no + * deduping needs to take place. This flag allows toggling of that behavior + * @returns Cancel events, if cancelError was provided. + */ +function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) { + // Find the syncPoint first. Then deal with whether or not it has matching listeners + const path = query._path; + const maybeSyncPoint = syncTree.syncPointTree_.get(path); + let cancelEvents = []; + // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without + // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and + // not loadsAllData(). + if (maybeSyncPoint && + (query._queryIdentifier === 'default' || + syncPointViewExistsForQuery(maybeSyncPoint, query))) { + const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError); + if (syncPointIsEmpty(maybeSyncPoint)) { + syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path); + } + const removed = removedAndEvents.removed; + cancelEvents = removedAndEvents.events; + if (!skipListenerDedup) { + /** + * We may have just removed one of many listeners and can short-circuit this whole process + * We may also not have removed a default listener, in which case all of the descendant listeners should already be + * properly set up. + */ + // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of + // queryId === 'default' + const removingDefault = -1 !== + removed.findIndex(query => { + return query._queryParams.loadsAllData(); + }); + const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint)); + if (removingDefault && !covered) { + const subtree = syncTree.syncPointTree_.subtree(path); + // There are potentially child listeners. Determine what if any listens we need to send before executing the + // removal + if (!subtree.isEmpty()) { + // We need to fold over our subtree and collect the listeners to send + const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree); + // Ok, we've collected all the listens we need. Set them up. + for (let i = 0; i < newViews.length; ++i) { + const view = newViews[i], newQuery = view.query; + const listener = syncTreeCreateListenerForView_(syncTree, view); + syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete); + } + } + // Otherwise there's nothing below us, so nothing we need to start listening on + } + // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query + // The above block has us covered in terms of making sure we're set up on listens lower in the tree. + // Also, note that if we have a cancelError, it's already been removed at the provider level. + if (!covered && removed.length > 0 && !cancelError) { + // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one + // default. Otherwise, we need to iterate through and cancel each individual query + if (removingDefault) { + // We don't tag default listeners + const defaultTag = null; + syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag); + } + else { + removed.forEach((queryToRemove) => { + const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove)); + syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove); + }); + } + } + } + // Now, clear all of the tags we're tracking for the removed listens + syncTreeRemoveTags_(syncTree, removed); + } + return cancelEvents; +} +/** + * Apply new server data for the specified tagged query. + * + * @returns Events to raise. + */ +function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) { + const queryKey = syncTreeQueryKeyForTag_(syncTree, tag); + if (queryKey != null) { + const r = syncTreeParseQueryKey_(queryKey); + const queryPath = r.path, queryId = r.queryId; + const relativePath = newRelativePath(queryPath, path); + const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap); + return syncTreeApplyTaggedOperation_(syncTree, queryPath, op); + } + else { + // Query must have been removed already + return []; + } +} +/** + * Apply server data to be merged in for the specified tagged query. + * + * @returns Events to raise. + */ +function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) { + const queryKey = syncTreeQueryKeyForTag_(syncTree, tag); + if (queryKey) { + const r = syncTreeParseQueryKey_(queryKey); + const queryPath = r.path, queryId = r.queryId; + const relativePath = newRelativePath(queryPath, path); + const changeTree = ImmutableTree.fromObject(changedChildren); + const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree); + return syncTreeApplyTaggedOperation_(syncTree, queryPath, op); + } + else { + // We've already removed the query. No big deal, ignore the update + return []; + } +} +/** + * Add an event callback for the specified query. + * + * @returns Events to raise. + */ +function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) { + const path = query._path; + let serverCache = null; + let foundAncestorDefaultView = false; + // Any covering writes will necessarily be at the root, so really all we need to find is the server cache. + // Consider optimizing this once there's a better understanding of what actual behavior will be. + syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => { + const relativePath = newRelativePath(pathToSyncPoint, path); + serverCache = + serverCache || syncPointGetCompleteServerCache(sp, relativePath); + foundAncestorDefaultView = + foundAncestorDefaultView || syncPointHasCompleteView(sp); + }); + let syncPoint = syncTree.syncPointTree_.get(path); + if (!syncPoint) { + syncPoint = new SyncPoint(); + syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint); + } + else { + foundAncestorDefaultView = + foundAncestorDefaultView || syncPointHasCompleteView(syncPoint); + serverCache = + serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + let serverCacheComplete; + if (serverCache != null) { + serverCacheComplete = true; + } + else { + serverCacheComplete = false; + serverCache = ChildrenNode.EMPTY_NODE; + const subtree = syncTree.syncPointTree_.subtree(path); + subtree.foreachChild((childName, childSyncPoint) => { + const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath()); + if (completeCache) { + serverCache = serverCache.updateImmediateChild(childName, completeCache); + } + }); + } + const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query); + if (!viewAlreadyExists && !query._queryParams.loadsAllData()) { + // We need to track a tag for this query + const queryKey = syncTreeMakeQueryKey_(query); + util.assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag'); + const tag = syncTreeGetNextQueryTag_(); + syncTree.queryToTagMap.set(queryKey, tag); + syncTree.tagToQueryMap.set(tag, queryKey); + } + const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path); + let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete); + if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) { + const view = syncPointViewForQuery(syncPoint, query); + events = events.concat(syncTreeSetupListener_(syncTree, query, view)); + } + return events; +} +/** + * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a + * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always + * have a listener above, and atomic operations would correctly show a jitter of -> + * as the write is applied locally and then acknowledged at the server. + * + * Note: this method will *include* hidden writes from transaction with applyLocally set to false. + * + * @param path - The path to the data we want + * @param writeIdsToExclude - A specific set to be excluded + */ +function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) { + const includeHiddenSets = true; + const writeTree = syncTree.pendingWriteTree_; + const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => { + const relativePath = newRelativePath(pathSoFar, path); + const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath); + if (serverCache) { + return serverCache; + } + }); + return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets); +} +function syncTreeGetServerValue(syncTree, query) { + const path = query._path; + let serverCache = null; + // Any covering writes will necessarily be at the root, so really all we need to find is the server cache. + // Consider optimizing this once there's a better understanding of what actual behavior will be. + syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => { + const relativePath = newRelativePath(pathToSyncPoint, path); + serverCache = + serverCache || syncPointGetCompleteServerCache(sp, relativePath); + }); + let syncPoint = syncTree.syncPointTree_.get(path); + if (!syncPoint) { + syncPoint = new SyncPoint(); + syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint); + } + else { + serverCache = + serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + const serverCacheComplete = serverCache != null; + const serverCacheNode = serverCacheComplete + ? new CacheNode(serverCache, true, false) + : null; + const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path); + const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete); + return viewGetCompleteNode(view); +} +/** + * A helper method that visits all descendant and ancestor SyncPoints, applying the operation. + * + * NOTES: + * - Descendant SyncPoints will be visited first (since we raise events depth-first). + * + * - We call applyOperation() on each SyncPoint passing three things: + * 1. A version of the Operation that has been made relative to the SyncPoint location. + * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location. + * 3. A snapshot Node with cached server data, if we have it. + * + * - We concatenate all of the events returned by each SyncPoint and return the result. + */ +function syncTreeApplyOperationToSyncPoints_(syncTree, operation) { + return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_, + /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath())); +} +/** + * Recursive helper for applyOperationToSyncPoints_ + */ +function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) { + if (pathIsEmpty(operation.path)) { + return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache); + } + else { + const syncPoint = syncPointTree.get(newEmptyPath()); + // If we don't have cached server data, see if we can get it from this SyncPoint. + if (serverCache == null && syncPoint != null) { + serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + let events = []; + const childName = pathGetFront(operation.path); + const childOperation = operation.operationForChild(childName); + const childTree = syncPointTree.children.get(childName); + if (childTree && childOperation) { + const childServerCache = serverCache + ? serverCache.getImmediateChild(childName) + : null; + const childWritesCache = writeTreeRefChild(writesCache, childName); + events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache)); + } + if (syncPoint) { + events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)); + } + return events; + } +} +/** + * Recursive helper for applyOperationToSyncPoints_ + */ +function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) { + const syncPoint = syncPointTree.get(newEmptyPath()); + // If we don't have cached server data, see if we can get it from this SyncPoint. + if (serverCache == null && syncPoint != null) { + serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + let events = []; + syncPointTree.children.inorderTraversal((childName, childTree) => { + const childServerCache = serverCache + ? serverCache.getImmediateChild(childName) + : null; + const childWritesCache = writeTreeRefChild(writesCache, childName); + const childOperation = operation.operationForChild(childName); + if (childOperation) { + events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache)); + } + }); + if (syncPoint) { + events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)); + } + return events; +} +function syncTreeCreateListenerForView_(syncTree, view) { + const query = view.query; + const tag = syncTreeTagForQuery(syncTree, query); + return { + hashFn: () => { + const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE; + return cache.hash(); + }, + onComplete: (status) => { + if (status === 'ok') { + if (tag) { + return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag); + } + else { + return syncTreeApplyListenComplete(syncTree, query._path); + } + } + else { + // If a listen failed, kill all of the listeners here, not just the one that triggered the error. + // Note that this may need to be scoped to just this listener if we change permissions on filtered children + const error = errorForServerCode(status, query); + return syncTreeRemoveEventRegistration(syncTree, query, + /*eventRegistration*/ null, error); + } + } + }; +} +/** + * Return the tag associated with the given query. + */ +function syncTreeTagForQuery(syncTree, query) { + const queryKey = syncTreeMakeQueryKey_(query); + return syncTree.queryToTagMap.get(queryKey); +} +/** + * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_. + */ +function syncTreeMakeQueryKey_(query) { + return query._path.toString() + '$' + query._queryIdentifier; +} +/** + * Return the query associated with the given tag, if we have one + */ +function syncTreeQueryKeyForTag_(syncTree, tag) { + return syncTree.tagToQueryMap.get(tag); +} +/** + * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId. + */ +function syncTreeParseQueryKey_(queryKey) { + const splitIndex = queryKey.indexOf('$'); + util.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.'); + return { + queryId: queryKey.substr(splitIndex + 1), + path: new Path(queryKey.substr(0, splitIndex)) + }; +} +/** + * A helper method to apply tagged operations + */ +function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) { + const syncPoint = syncTree.syncPointTree_.get(queryPath); + util.assert(syncPoint, "Missing sync point for query tag that we're tracking"); + const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath); + return syncPointApplyOperation(syncPoint, operation, writesCache, null); +} +/** + * This collapses multiple unfiltered views into a single view, since we only need a single + * listener for them. + */ +function syncTreeCollectDistinctViewsForSubTree_(subtree) { + return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => { + if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) { + const completeView = syncPointGetCompleteView(maybeChildSyncPoint); + return [completeView]; + } + else { + // No complete view here, flatten any deeper listens into an array + let views = []; + if (maybeChildSyncPoint) { + views = syncPointGetQueryViews(maybeChildSyncPoint); + } + each(childMap, (_key, childViews) => { + views = views.concat(childViews); + }); + return views; + } + }); +} +/** + * Normalizes a query to a query we send the server for listening + * + * @returns The normalized query + */ +function syncTreeQueryForListening_(query) { + if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) { + // We treat queries that load all data as default queries + // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits + // from Query + return new (syncTreeGetReferenceConstructor())(query._repo, query._path); + } + else { + return query; + } +} +function syncTreeRemoveTags_(syncTree, queries) { + for (let j = 0; j < queries.length; ++j) { + const removedQuery = queries[j]; + if (!removedQuery._queryParams.loadsAllData()) { + // We should have a tag for this + const removedQueryKey = syncTreeMakeQueryKey_(removedQuery); + const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey); + syncTree.queryToTagMap.delete(removedQueryKey); + syncTree.tagToQueryMap.delete(removedQueryTag); + } + } +} +/** + * Static accessor for query tags. + */ +function syncTreeGetNextQueryTag_() { + return syncTreeNextQueryTag_++; +} +/** + * For a given new listen, manage the de-duplication of outstanding subscriptions. + * + * @returns This method can return events to support synchronous data sources + */ +function syncTreeSetupListener_(syncTree, query, view) { + const path = query._path; + const tag = syncTreeTagForQuery(syncTree, query); + const listener = syncTreeCreateListenerForView_(syncTree, view); + const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete); + const subtree = syncTree.syncPointTree_.subtree(path); + // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we + // may need to shadow other listens as well. + if (tag) { + util.assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed"); + } + else { + // Shadow everything at or below this location, this is a default listener. + const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => { + if (!pathIsEmpty(relativePath) && + maybeChildSyncPoint && + syncPointHasCompleteView(maybeChildSyncPoint)) { + return [syncPointGetCompleteView(maybeChildSyncPoint).query]; + } + else { + // No default listener here, flatten any deeper queries into an array + let queries = []; + if (maybeChildSyncPoint) { + queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query)); + } + each(childMap, (_key, childQueries) => { + queries = queries.concat(childQueries); + }); + return queries; + } + }); + for (let i = 0; i < queriesToStop.length; ++i) { + const queryToStop = queriesToStop[i]; + syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop)); + } + } + return events; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ExistingValueProvider { + constructor(node_) { + this.node_ = node_; + } + getImmediateChild(childName) { + const child = this.node_.getImmediateChild(childName); + return new ExistingValueProvider(child); + } + node() { + return this.node_; + } +} +class DeferredValueProvider { + constructor(syncTree, path) { + this.syncTree_ = syncTree; + this.path_ = path; + } + getImmediateChild(childName) { + const childPath = pathChild(this.path_, childName); + return new DeferredValueProvider(this.syncTree_, childPath); + } + node() { + return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_); + } +} +/** + * Generate placeholders for deferred values. + */ +const generateWithValues = function (values) { + values = values || {}; + values['timestamp'] = values['timestamp'] || new Date().getTime(); + return values; +}; +/** + * Value to use when firing local events. When writing server values, fire + * local events with an approximate value, otherwise return value as-is. + */ +const resolveDeferredLeafValue = function (value, existingVal, serverValues) { + if (!value || typeof value !== 'object') { + return value; + } + util.assert('.sv' in value, 'Unexpected leaf node or priority contents'); + if (typeof value['.sv'] === 'string') { + return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues); + } + else if (typeof value['.sv'] === 'object') { + return resolveComplexDeferredValue(value['.sv'], existingVal); + } + else { + util.assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2)); + } +}; +const resolveScalarDeferredValue = function (op, existing, serverValues) { + switch (op) { + case 'timestamp': + return serverValues['timestamp']; + default: + util.assert(false, 'Unexpected server value: ' + op); + } +}; +const resolveComplexDeferredValue = function (op, existing, unused) { + if (!op.hasOwnProperty('increment')) { + util.assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2)); + } + const delta = op['increment']; + if (typeof delta !== 'number') { + util.assert(false, 'Unexpected increment value: ' + delta); + } + const existingNode = existing.node(); + util.assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls'); + // Incrementing a non-number sets the value to the incremented amount + if (!existingNode.isLeafNode()) { + return delta; + } + const leaf = existingNode; + const existingVal = leaf.getValue(); + if (typeof existingVal !== 'number') { + return delta; + } + // No need to do over/underflow arithmetic here because JS only handles floats under the covers + return existingVal + delta; +}; +/** + * Recursively replace all deferred values and priorities in the tree with the + * specified generated replacement values. + * @param path - path to which write is relative + * @param node - new data written at path + * @param syncTree - current data + */ +const resolveDeferredValueTree = function (path, node, syncTree, serverValues) { + return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues); +}; +/** + * Recursively replace all deferred values and priorities in the node with the + * specified generated replacement values. If there are no server values in the node, + * it'll be returned as-is. + */ +const resolveDeferredValueSnapshot = function (node, existing, serverValues) { + return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues); +}; +function resolveDeferredValue(node, existingVal, serverValues) { + const rawPri = node.getPriority().val(); + const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues); + let newNode; + if (node.isLeafNode()) { + const leafNode = node; + const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues); + if (value !== leafNode.getValue() || + priority !== leafNode.getPriority().val()) { + return new LeafNode(value, nodeFromJSON(priority)); + } + else { + return node; + } + } + else { + const childrenNode = node; + newNode = childrenNode; + if (priority !== childrenNode.getPriority().val()) { + newNode = newNode.updatePriority(new LeafNode(priority)); + } + childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => { + const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues); + if (newChildNode !== childNode) { + newNode = newNode.updateImmediateChild(childName, newChildNode); + } + }); + return newNode; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A light-weight tree, traversable by path. Nodes can have both values and children. + * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty + * children. + */ +class Tree { + /** + * @param name - Optional name of the node. + * @param parent - Optional parent node. + * @param node - Optional node to wrap. + */ + constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) { + this.name = name; + this.parent = parent; + this.node = node; + } +} +/** + * Returns a sub-Tree for the given path. + * + * @param pathObj - Path to look up. + * @returns Tree for path. + */ +function treeSubTree(tree, pathObj) { + // TODO: Require pathObj to be Path? + let path = pathObj instanceof Path ? pathObj : new Path(pathObj); + let child = tree, next = pathGetFront(path); + while (next !== null) { + const childNode = util.safeGet(child.node.children, next) || { + children: {}, + childCount: 0 + }; + child = new Tree(next, child, childNode); + path = pathPopFront(path); + next = pathGetFront(path); + } + return child; +} +/** + * Returns the data associated with this tree node. + * + * @returns The data or null if no data exists. + */ +function treeGetValue(tree) { + return tree.node.value; +} +/** + * Sets data to this tree node. + * + * @param value - Value to set. + */ +function treeSetValue(tree, value) { + tree.node.value = value; + treeUpdateParents(tree); +} +/** + * @returns Whether the tree has any children. + */ +function treeHasChildren(tree) { + return tree.node.childCount > 0; +} +/** + * @returns Whether the tree is empty (no value or children). + */ +function treeIsEmpty(tree) { + return treeGetValue(tree) === undefined && !treeHasChildren(tree); +} +/** + * Calls action for each child of this tree node. + * + * @param action - Action to be called for each child. + */ +function treeForEachChild(tree, action) { + each(tree.node.children, (child, childTree) => { + action(new Tree(child, tree, childTree)); + }); +} +/** + * Does a depth-first traversal of this node's descendants, calling action for each one. + * + * @param action - Action to be called for each child. + * @param includeSelf - Whether to call action on this node as well. Defaults to + * false. + * @param childrenFirst - Whether to call action on children before calling it on + * parent. + */ +function treeForEachDescendant(tree, action, includeSelf, childrenFirst) { + if (includeSelf && !childrenFirst) { + action(tree); + } + treeForEachChild(tree, child => { + treeForEachDescendant(child, action, true, childrenFirst); + }); + if (includeSelf && childrenFirst) { + action(tree); + } +} +/** + * Calls action on each ancestor node. + * + * @param action - Action to be called on each parent; return + * true to abort. + * @param includeSelf - Whether to call action on this node as well. + * @returns true if the action callback returned true. + */ +function treeForEachAncestor(tree, action, includeSelf) { + let node = includeSelf ? tree : tree.parent; + while (node !== null) { + if (action(node)) { + return true; + } + node = node.parent; + } + return false; +} +/** + * @returns The path of this tree node, as a Path. + */ +function treeGetPath(tree) { + return new Path(tree.parent === null + ? tree.name + : treeGetPath(tree.parent) + '/' + tree.name); +} +/** + * Adds or removes this child from its parent based on whether it's empty or not. + */ +function treeUpdateParents(tree) { + if (tree.parent !== null) { + treeUpdateChild(tree.parent, tree.name, tree); + } +} +/** + * Adds or removes the passed child to this tree node, depending on whether it's empty. + * + * @param childName - The name of the child to update. + * @param child - The child to update. + */ +function treeUpdateChild(tree, childName, child) { + const childEmpty = treeIsEmpty(child); + const childExists = util.contains(tree.node.children, childName); + if (childEmpty && childExists) { + delete tree.node.children[childName]; + tree.node.childCount--; + treeUpdateParents(tree); + } + else if (!childEmpty && !childExists) { + tree.node.children[childName] = child.node; + tree.node.childCount++; + treeUpdateParents(tree); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * True for invalid Firebase keys + */ +const INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/; +/** + * True for invalid Firebase paths. + * Allows '/' in paths. + */ +const INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/; +/** + * Maximum number of characters to allow in leaf value + */ +const MAX_LEAF_SIZE_ = 10 * 1024 * 1024; +const isValidKey = function (key) { + return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key)); +}; +const isValidPathString = function (pathString) { + return (typeof pathString === 'string' && + pathString.length !== 0 && + !INVALID_PATH_REGEX_.test(pathString)); +}; +const isValidRootPathString = function (pathString) { + if (pathString) { + // Allow '/.info/' at the beginning. + pathString = pathString.replace(/^\/*\.info(\/|$)/, '/'); + } + return isValidPathString(pathString); +}; +const isValidPriority = function (priority) { + return (priority === null || + typeof priority === 'string' || + (typeof priority === 'number' && !isInvalidJSONNumber(priority)) || + (priority && + typeof priority === 'object' && + // eslint-disable-next-line @typescript-eslint/no-explicit-any + util.contains(priority, '.sv'))); +}; +/** + * Pre-validate a datum passed as an argument to Firebase function. + */ +const validateFirebaseDataArg = function (fnName, value, path, optional) { + if (optional && value === undefined) { + return; + } + validateFirebaseData(util.errorPrefix(fnName, 'value'), value, path); +}; +/** + * Validate a data object client-side before sending to server. + */ +const validateFirebaseData = function (errorPrefix, data, path_) { + const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_; + if (data === undefined) { + throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path)); + } + if (typeof data === 'function') { + throw new Error(errorPrefix + + 'contains a function ' + + validationPathToErrorString(path) + + ' with contents = ' + + data.toString()); + } + if (isInvalidJSONNumber(data)) { + throw new Error(errorPrefix + + 'contains ' + + data.toString() + + ' ' + + validationPathToErrorString(path)); + } + // Check max leaf size, but try to avoid the utf8 conversion if we can. + if (typeof data === 'string' && + data.length > MAX_LEAF_SIZE_ / 3 && + util.stringLength(data) > MAX_LEAF_SIZE_) { + throw new Error(errorPrefix + + 'contains a string greater than ' + + MAX_LEAF_SIZE_ + + ' utf8 bytes ' + + validationPathToErrorString(path) + + " ('" + + data.substring(0, 50) + + "...')"); + } + // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON + // to save extra walking of large objects. + if (data && typeof data === 'object') { + let hasDotValue = false; + let hasActualChild = false; + each(data, (key, value) => { + if (key === '.value') { + hasDotValue = true; + } + else if (key !== '.priority' && key !== '.sv') { + hasActualChild = true; + if (!isValidKey(key)) { + throw new Error(errorPrefix + + ' contains an invalid key (' + + key + + ') ' + + validationPathToErrorString(path) + + '. Keys must be non-empty strings ' + + 'and can\'t contain ".", "#", "$", "/", "[", or "]"'); + } + } + validationPathPush(path, key); + validateFirebaseData(errorPrefix, value, path); + validationPathPop(path); + }); + if (hasDotValue && hasActualChild) { + throw new Error(errorPrefix + + ' contains ".value" child ' + + validationPathToErrorString(path) + + ' in addition to actual children.'); + } + } +}; +/** + * Pre-validate paths passed in the firebase function. + */ +const validateFirebaseMergePaths = function (errorPrefix, mergePaths) { + let i, curPath; + for (i = 0; i < mergePaths.length; i++) { + curPath = mergePaths[i]; + const keys = pathSlice(curPath); + for (let j = 0; j < keys.length; j++) { + if (keys[j] === '.priority' && j === keys.length - 1) ; + else if (!isValidKey(keys[j])) { + throw new Error(errorPrefix + + 'contains an invalid key (' + + keys[j] + + ') in path ' + + curPath.toString() + + '. Keys must be non-empty strings ' + + 'and can\'t contain ".", "#", "$", "/", "[", or "]"'); + } + } + } + // Check that update keys are not descendants of each other. + // We rely on the property that sorting guarantees that ancestors come + // right before descendants. + mergePaths.sort(pathCompare); + let prevPath = null; + for (i = 0; i < mergePaths.length; i++) { + curPath = mergePaths[i]; + if (prevPath !== null && pathContains(prevPath, curPath)) { + throw new Error(errorPrefix + + 'contains a path ' + + prevPath.toString() + + ' that is ancestor of another path ' + + curPath.toString()); + } + prevPath = curPath; + } +}; +/** + * pre-validate an object passed as an argument to firebase function ( + * must be an object - e.g. for firebase.update()). + */ +const validateFirebaseMergeDataArg = function (fnName, data, path, optional) { + if (optional && data === undefined) { + return; + } + const errorPrefix = util.errorPrefix(fnName, 'values'); + if (!(data && typeof data === 'object') || Array.isArray(data)) { + throw new Error(errorPrefix + ' must be an object containing the children to replace.'); + } + const mergePaths = []; + each(data, (key, value) => { + const curPath = new Path(key); + validateFirebaseData(errorPrefix, value, pathChild(path, curPath)); + if (pathGetBack(curPath) === '.priority') { + if (!isValidPriority(value)) { + throw new Error(errorPrefix + + "contains an invalid value for '" + + curPath.toString() + + "', which must be a valid " + + 'Firebase priority (a string, finite number, server value, or null).'); + } + } + mergePaths.push(curPath); + }); + validateFirebaseMergePaths(errorPrefix, mergePaths); +}; +const validatePriority = function (fnName, priority, optional) { + if (optional && priority === undefined) { + return; + } + if (isInvalidJSONNumber(priority)) { + throw new Error(util.errorPrefix(fnName, 'priority') + + 'is ' + + priority.toString() + + ', but must be a valid Firebase priority (a string, finite number, ' + + 'server value, or null).'); + } + // Special case to allow importing data with a .sv. + if (!isValidPriority(priority)) { + throw new Error(util.errorPrefix(fnName, 'priority') + + 'must be a valid Firebase priority ' + + '(a string, finite number, server value, or null).'); + } +}; +const validateKey = function (fnName, argumentName, key, optional) { + if (optional && key === undefined) { + return; + } + if (!isValidKey(key)) { + throw new Error(util.errorPrefix(fnName, argumentName) + + 'was an invalid key = "' + + key + + '". Firebase keys must be non-empty strings and ' + + 'can\'t contain ".", "#", "$", "/", "[", or "]").'); + } +}; +/** + * @internal + */ +const validatePathString = function (fnName, argumentName, pathString, optional) { + if (optional && pathString === undefined) { + return; + } + if (!isValidPathString(pathString)) { + throw new Error(util.errorPrefix(fnName, argumentName) + + 'was an invalid path = "' + + pathString + + '". Paths must be non-empty strings and ' + + 'can\'t contain ".", "#", "$", "[", or "]"'); + } +}; +const validateRootPathString = function (fnName, argumentName, pathString, optional) { + if (pathString) { + // Allow '/.info/' at the beginning. + pathString = pathString.replace(/^\/*\.info(\/|$)/, '/'); + } + validatePathString(fnName, argumentName, pathString, optional); +}; +/** + * @internal + */ +const validateWritablePath = function (fnName, path) { + if (pathGetFront(path) === '.info') { + throw new Error(fnName + " failed = Can't modify data under /.info/"); + } +}; +const validateUrl = function (fnName, parsedUrl) { + // TODO = Validate server better. + const pathString = parsedUrl.path.toString(); + if (!(typeof parsedUrl.repoInfo.host === 'string') || + parsedUrl.repoInfo.host.length === 0 || + (!isValidKey(parsedUrl.repoInfo.namespace) && + parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') || + (pathString.length !== 0 && !isValidRootPathString(pathString))) { + throw new Error(util.errorPrefix(fnName, 'url') + + 'must be a valid firebase URL and ' + + 'the path can\'t contain ".", "#", "$", "[", or "]".'); + } +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The event queue serves a few purposes: + * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more + * events being queued. + * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events, + * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call + * left off, ensuring that the events are still raised synchronously and in order. + * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued + * events are raised synchronously. + * + * NOTE: This can all go away if/when we move to async events. + * + */ +class EventQueue { + constructor() { + this.eventLists_ = []; + /** + * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes. + */ + this.recursionDepth_ = 0; + } +} +/** + * @param eventDataList - The new events to queue. + */ +function eventQueueQueueEvents(eventQueue, eventDataList) { + // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly. + let currList = null; + for (let i = 0; i < eventDataList.length; i++) { + const data = eventDataList[i]; + const path = data.getPath(); + if (currList !== null && !pathEquals(path, currList.path)) { + eventQueue.eventLists_.push(currList); + currList = null; + } + if (currList === null) { + currList = { events: [], path }; + } + currList.events.push(data); + } + if (currList) { + eventQueue.eventLists_.push(currList); + } +} +/** + * Queues the specified events and synchronously raises all events (including previously queued ones) + * for the specified path. + * + * It is assumed that the new events are all for the specified path. + * + * @param path - The path to raise events for. + * @param eventDataList - The new events to raise. + */ +function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) { + eventQueueQueueEvents(eventQueue, eventDataList); + eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path)); +} +/** + * Queues the specified events and synchronously raises all events (including previously queued ones) for + * locations related to the specified change path (i.e. all ancestors and descendants). + * + * It is assumed that the new events are all related (ancestor or descendant) to the specified path. + * + * @param changedPath - The path to raise events for. + * @param eventDataList - The events to raise + */ +function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) { + eventQueueQueueEvents(eventQueue, eventDataList); + eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) || + pathContains(changedPath, eventPath)); +} +function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) { + eventQueue.recursionDepth_++; + let sentAll = true; + for (let i = 0; i < eventQueue.eventLists_.length; i++) { + const eventList = eventQueue.eventLists_[i]; + if (eventList) { + const eventPath = eventList.path; + if (predicate(eventPath)) { + eventListRaise(eventQueue.eventLists_[i]); + eventQueue.eventLists_[i] = null; + } + else { + sentAll = false; + } + } + } + if (sentAll) { + eventQueue.eventLists_ = []; + } + eventQueue.recursionDepth_--; +} +/** + * Iterates through the list and raises each event + */ +function eventListRaise(eventList) { + for (let i = 0; i < eventList.events.length; i++) { + const eventData = eventList.events[i]; + if (eventData !== null) { + eventList.events[i] = null; + const eventFn = eventData.getEventRunner(); + if (logger) { + log('event: ' + eventData.toString()); + } + exceptionGuard(eventFn); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const INTERRUPT_REASON = 'repo_interrupt'; +/** + * If a transaction does not succeed after 25 retries, we abort it. Among other + * things this ensure that if there's ever a bug causing a mismatch between + * client / server hashes for some data, we won't retry indefinitely. + */ +const MAX_TRANSACTION_RETRIES = 25; +/** + * A connection to a single data repository. + */ +class Repo { + constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) { + this.repoInfo_ = repoInfo_; + this.forceRestClient_ = forceRestClient_; + this.authTokenProvider_ = authTokenProvider_; + this.appCheckProvider_ = appCheckProvider_; + this.dataUpdateCount = 0; + this.statsListener_ = null; + this.eventQueue_ = new EventQueue(); + this.nextWriteId_ = 1; + this.interceptServerDataCallback_ = null; + /** A list of data pieces and paths to be set when this client disconnects. */ + this.onDisconnect_ = newSparseSnapshotTree(); + /** Stores queues of outstanding transactions for Firebase locations. */ + this.transactionQueueTree_ = new Tree(); + // TODO: This should be @private but it's used by test_access.js and internal.js + this.persistentConnection_ = null; + // This key is intentionally not updated if RepoInfo is later changed or replaced + this.key = this.repoInfo_.toURLString(); + } + /** + * @returns The URL corresponding to the root of this Firebase. + */ + toString() { + return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host); + } +} +function repoStart(repo, appId, authOverride) { + repo.stats_ = statsManagerGetCollection(repo.repoInfo_); + if (repo.forceRestClient_ || beingCrawled()) { + repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => { + repoOnDataUpdate(repo, pathString, data, isMerge, tag); + }, repo.authTokenProvider_, repo.appCheckProvider_); + // Minor hack: Fire onConnect immediately, since there's no actual connection. + setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0); + } + else { + // Validate authOverride + if (typeof authOverride !== 'undefined' && authOverride !== null) { + if (typeof authOverride !== 'object') { + throw new Error('Only objects are supported for option databaseAuthVariableOverride'); + } + try { + util.stringify(authOverride); + } + catch (e) { + throw new Error('Invalid authOverride provided: ' + e); + } + } + repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => { + repoOnDataUpdate(repo, pathString, data, isMerge, tag); + }, (connectStatus) => { + repoOnConnectStatus(repo, connectStatus); + }, (updates) => { + repoOnServerInfoUpdate(repo, updates); + }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride); + repo.server_ = repo.persistentConnection_; + } + repo.authTokenProvider_.addTokenChangeListener(token => { + repo.server_.refreshAuthToken(token); + }); + repo.appCheckProvider_.addTokenChangeListener(result => { + repo.server_.refreshAppCheckToken(result.token); + }); + // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used), + // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created. + repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_)); + // Used for .info. + repo.infoData_ = new SnapshotHolder(); + repo.infoSyncTree_ = new SyncTree({ + startListening: (query, tag, currentHashFn, onComplete) => { + let infoEvents = []; + const node = repo.infoData_.getNode(query._path); + // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events + // on initial data... + if (!node.isEmpty()) { + infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node); + setTimeout(() => { + onComplete('ok'); + }, 0); + } + return infoEvents; + }, + stopListening: () => { } + }); + repoUpdateInfo(repo, 'connected', false); + repo.serverSyncTree_ = new SyncTree({ + startListening: (query, tag, currentHashFn, onComplete) => { + repo.server_.listen(query, currentHashFn, tag, (status, data) => { + const events = onComplete(status, data); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events); + }); + // No synchronous events for network-backed sync trees + return []; + }, + stopListening: (query, tag) => { + repo.server_.unlisten(query, tag); + } + }); +} +/** + * @returns The time in milliseconds, taking the server offset into account if we have one. + */ +function repoServerTime(repo) { + const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset')); + const offset = offsetNode.val() || 0; + return new Date().getTime() + offset; +} +/** + * Generate ServerValues using some variables from the repo object. + */ +function repoGenerateServerValues(repo) { + return generateWithValues({ + timestamp: repoServerTime(repo) + }); +} +/** + * Called by realtime when we get new messages from the server. + */ +function repoOnDataUpdate(repo, pathString, data, isMerge, tag) { + // For testing. + repo.dataUpdateCount++; + const path = new Path(pathString); + data = repo.interceptServerDataCallback_ + ? repo.interceptServerDataCallback_(pathString, data) + : data; + let events = []; + if (tag) { + if (isMerge) { + const taggedChildren = util.map(data, (raw) => nodeFromJSON(raw)); + events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag); + } + else { + const taggedSnap = nodeFromJSON(data); + events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag); + } + } + else if (isMerge) { + const changedChildren = util.map(data, (raw) => nodeFromJSON(raw)); + events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren); + } + else { + const snap = nodeFromJSON(data); + events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap); + } + let affectedPath = path; + if (events.length > 0) { + // Since we have a listener outstanding for each transaction, receiving any events + // is a proxy for some change having occurred. + affectedPath = repoRerunTransactions(repo, path); + } + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events); +} +function repoOnConnectStatus(repo, connectStatus) { + repoUpdateInfo(repo, 'connected', connectStatus); + if (connectStatus === false) { + repoRunOnDisconnectEvents(repo); + } +} +function repoOnServerInfoUpdate(repo, updates) { + each(updates, (key, value) => { + repoUpdateInfo(repo, key, value); + }); +} +function repoUpdateInfo(repo, pathString, value) { + const path = new Path('/.info/' + pathString); + const newNode = nodeFromJSON(value); + repo.infoData_.updateSnapshot(path, newNode); + const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); +} +function repoGetNextWriteId(repo) { + return repo.nextWriteId_++; +} +/** + * The purpose of `getValue` is to return the latest known value + * satisfying `query`. + * + * This method will first check for in-memory cached values + * belonging to active listeners. If they are found, such values + * are considered to be the most up-to-date. + * + * If the client is not connected, this method will wait until the + * repo has established a connection and then request the value for `query`. + * If the client is not able to retrieve the query result for another reason, + * it reports an error. + * + * @param query - The query to surface a value for. + */ +function repoGetValue(repo, query, eventRegistration) { + // Only active queries are cached. There is no persisted cache. + const cached = syncTreeGetServerValue(repo.serverSyncTree_, query); + if (cached != null) { + return Promise.resolve(cached); + } + return repo.server_.get(query).then(payload => { + const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex()); + /** + * Below we simulate the actions of an `onlyOnce` `onValue()` event where: + * Add an event registration, + * Update data at the path, + * Raise any events, + * Cleanup the SyncTree + */ + syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true); + let events; + if (query._queryParams.loadsAllData()) { + events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node); + } + else { + const tag = syncTreeTagForQuery(repo.serverSyncTree_, query); + events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag); + } + /* + * We need to raise events in the scenario where `get()` is called at a parent path, and + * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting + * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree + * and its corresponding serverCache, including the child location where `onValue` is called. Then, + * `onValue` will receive the event from the server, but look at the syncTree and see that the data received + * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired. + * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and + * ensure the corresponding child events will get fired. + */ + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events); + syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true); + return node; + }, err => { + repoLog(repo, 'get for query ' + util.stringify(query) + ' failed: ' + err); + return Promise.reject(new Error(err)); + }); +} +function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) { + repoLog(repo, 'set', { + path: path.toString(), + value: newVal, + priority: newPriority + }); + // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or + // (b) store unresolved paths on JSON parse + const serverValues = repoGenerateServerValues(repo); + const newNodeUnresolved = nodeFromJSON(newVal, newPriority); + const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path); + const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues); + const writeId = repoGetNextWriteId(repo); + const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true); + eventQueueQueueEvents(repo.eventQueue_, events); + repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => { + const success = status === 'ok'; + if (!success) { + warn('set at ' + path + ' failed: ' + status); + } + const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents); + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); + const affectedPath = repoAbortTransactions(repo, path); + repoRerunTransactions(repo, affectedPath); + // We queued the events above, so just flush the queue here + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []); +} +function repoUpdate(repo, path, childrenToMerge, onComplete) { + repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge }); + // Start with our existing data and merge each child into it. + let empty = true; + const serverValues = repoGenerateServerValues(repo); + const changedChildren = {}; + each(childrenToMerge, (changedKey, changedValue) => { + empty = false; + changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues); + }); + if (!empty) { + const writeId = repoGetNextWriteId(repo); + const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId); + eventQueueQueueEvents(repo.eventQueue_, events); + repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => { + const success = status === 'ok'; + if (!success) { + warn('update at ' + path + ' failed: ' + status); + } + const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success); + const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path; + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents); + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); + each(childrenToMerge, (changedPath) => { + const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath)); + repoRerunTransactions(repo, affectedPath); + }); + // We queued the events above, so just flush the queue here + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []); + } + else { + log("update() called with empty data. Don't do anything."); + repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined); + } +} +/** + * Applies all of the changes stored up in the onDisconnect_ tree. + */ +function repoRunOnDisconnectEvents(repo) { + repoLog(repo, 'onDisconnectEvents'); + const serverValues = repoGenerateServerValues(repo); + const resolvedOnDisconnectTree = newSparseSnapshotTree(); + sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => { + const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues); + sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved); + }); + let events = []; + sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => { + events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap)); + const affectedPath = repoAbortTransactions(repo, path); + repoRerunTransactions(repo, affectedPath); + }); + repo.onDisconnect_ = newSparseSnapshotTree(); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events); +} +function repoOnDisconnectCancel(repo, path, onComplete) { + repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => { + if (status === 'ok') { + sparseSnapshotTreeForget(repo.onDisconnect_, path); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoOnDisconnectSet(repo, path, value, onComplete) { + const newNode = nodeFromJSON(value); + repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => { + if (status === 'ok') { + sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) { + const newNode = nodeFromJSON(value, priority); + repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => { + if (status === 'ok') { + sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) { + if (util.isEmpty(childrenToMerge)) { + log("onDisconnect().update() called with empty data. Don't do anything."); + repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined); + return; + } + repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => { + if (status === 'ok') { + each(childrenToMerge, (childName, childNode) => { + const newChildNode = nodeFromJSON(childNode); + sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode); + }); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoAddEventCallbackForQuery(repo, query, eventRegistration) { + let events; + if (pathGetFront(query._path) === '.info') { + events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration); + } + else { + events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration); + } + eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events); +} +function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) { + // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof + // a little bit by handling the return values anyways. + let events; + if (pathGetFront(query._path) === '.info') { + events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration); + } + else { + events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration); + } + eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events); +} +function repoInterrupt(repo) { + if (repo.persistentConnection_) { + repo.persistentConnection_.interrupt(INTERRUPT_REASON); + } +} +function repoResume(repo) { + if (repo.persistentConnection_) { + repo.persistentConnection_.resume(INTERRUPT_REASON); + } +} +function repoLog(repo, ...varArgs) { + let prefix = ''; + if (repo.persistentConnection_) { + prefix = repo.persistentConnection_.id + ':'; + } + log(prefix, ...varArgs); +} +function repoCallOnCompleteCallback(repo, callback, status, errorReason) { + if (callback) { + exceptionGuard(() => { + if (status === 'ok') { + callback(null); + } + else { + const code = (status || 'error').toUpperCase(); + let message = code; + if (errorReason) { + message += ': ' + errorReason; + } + const error = new Error(message); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error.code = code; + callback(error); + } + }); + } +} +/** + * Creates a new transaction, adds it to the transactions we're tracking, and + * sends it to the server if possible. + * + * @param path - Path at which to do transaction. + * @param transactionUpdate - Update callback. + * @param onComplete - Completion callback. + * @param unwatcher - Function that will be called when the transaction no longer + * need data updates for `path`. + * @param applyLocally - Whether or not to make intermediate results visible + */ +function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) { + repoLog(repo, 'transaction on ' + path); + // Initialize transaction. + const transaction = { + path, + update: transactionUpdate, + onComplete, + // One of TransactionStatus enums. + status: null, + // Used when combining transactions at different locations to figure out + // which one goes first. + order: LUIDGenerator(), + // Whether to raise local events for this transaction. + applyLocally, + // Count of how many times we've retried the transaction. + retryCount: 0, + // Function to call to clean up our .on() listener. + unwatcher, + // Stores why a transaction was aborted. + abortReason: null, + currentWriteId: null, + currentInputSnapshot: null, + currentOutputSnapshotRaw: null, + currentOutputSnapshotResolved: null + }; + // Run transaction initially. + const currentState = repoGetLatestState(repo, path, undefined); + transaction.currentInputSnapshot = currentState; + const newVal = transaction.update(currentState.val()); + if (newVal === undefined) { + // Abort transaction. + transaction.unwatcher(); + transaction.currentOutputSnapshotRaw = null; + transaction.currentOutputSnapshotResolved = null; + if (transaction.onComplete) { + transaction.onComplete(null, false, transaction.currentInputSnapshot); + } + } + else { + validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path); + // Mark as run and add to our queue. + transaction.status = 0 /* TransactionStatus.RUN */; + const queueNode = treeSubTree(repo.transactionQueueTree_, path); + const nodeQueue = treeGetValue(queueNode) || []; + nodeQueue.push(transaction); + treeSetValue(queueNode, nodeQueue); + // Update visibleData and raise events + // Note: We intentionally raise events after updating all of our + // transaction state, since the user could start new transactions from the + // event callbacks. + let priorityForNode; + if (typeof newVal === 'object' && + newVal !== null && + util.contains(newVal, '.priority')) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + priorityForNode = util.safeGet(newVal, '.priority'); + util.assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' + + 'Priority must be a valid string, finite number, server value, or null.'); + } + else { + const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) || + ChildrenNode.EMPTY_NODE; + priorityForNode = currentNode.getPriority().val(); + } + const serverValues = repoGenerateServerValues(repo); + const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode); + const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues); + transaction.currentOutputSnapshotRaw = newNodeUnresolved; + transaction.currentOutputSnapshotResolved = newNode; + transaction.currentWriteId = repoGetNextWriteId(repo); + const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); + repoSendReadyTransactions(repo, repo.transactionQueueTree_); + } +} +/** + * @param excludeSets - A specific set to exclude + */ +function repoGetLatestState(repo, path, excludeSets) { + return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) || + ChildrenNode.EMPTY_NODE); +} +/** + * Sends any already-run transactions that aren't waiting for outstanding + * transactions to complete. + * + * Externally it's called with no arguments, but it calls itself recursively + * with a particular transactionQueueTree node to recurse through the tree. + * + * @param node - transactionQueueTree node to start at. + */ +function repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) { + // Before recursing, make sure any completed transactions are removed. + if (!node) { + repoPruneCompletedTransactionsBelowNode(repo, node); + } + if (treeGetValue(node)) { + const queue = repoBuildTransactionQueue(repo, node); + util.assert(queue.length > 0, 'Sending zero length transaction queue'); + const allRun = queue.every((transaction) => transaction.status === 0 /* TransactionStatus.RUN */); + // If they're all run (and not sent), we can send them. Else, we must wait. + if (allRun) { + repoSendTransactionQueue(repo, treeGetPath(node), queue); + } + } + else if (treeHasChildren(node)) { + treeForEachChild(node, childNode => { + repoSendReadyTransactions(repo, childNode); + }); + } +} +/** + * Given a list of run transactions, send them to the server and then handle + * the result (success or failure). + * + * @param path - The location of the queue. + * @param queue - Queue of transactions under the specified location. + */ +function repoSendTransactionQueue(repo, path, queue) { + // Mark transactions as sent and increment retry count! + const setsToIgnore = queue.map(txn => { + return txn.currentWriteId; + }); + const latestState = repoGetLatestState(repo, path, setsToIgnore); + let snapToSend = latestState; + const latestHash = latestState.hash(); + for (let i = 0; i < queue.length; i++) { + const txn = queue[i]; + util.assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.'); + txn.status = 1 /* TransactionStatus.SENT */; + txn.retryCount++; + const relativePath = newRelativePath(path, txn.path); + // If we've gotten to this point, the output snapshot must be defined. + snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw); + } + const dataToSend = snapToSend.val(true); + const pathToSend = path; + // Send the put. + repo.server_.put(pathToSend.toString(), dataToSend, (status) => { + repoLog(repo, 'transaction put response', { + path: pathToSend.toString(), + status + }); + let events = []; + if (status === 'ok') { + // Queue up the callbacks and fire them after cleaning up all of our + // transaction state, since the callback could trigger more + // transactions or sets. + const callbacks = []; + for (let i = 0; i < queue.length; i++) { + queue[i].status = 2 /* TransactionStatus.COMPLETED */; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId)); + if (queue[i].onComplete) { + // We never unset the output snapshot, and given that this + // transaction is complete, it should be set + callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved)); + } + queue[i].unwatcher(); + } + // Now remove the completed transactions. + repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path)); + // There may be pending transactions that we can now send. + repoSendReadyTransactions(repo, repo.transactionQueueTree_); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); + // Finally, trigger onComplete callbacks. + for (let i = 0; i < callbacks.length; i++) { + exceptionGuard(callbacks[i]); + } + } + else { + // transactions are no longer sent. Update their status appropriately. + if (status === 'datastale') { + for (let i = 0; i < queue.length; i++) { + if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) { + queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */; + } + else { + queue[i].status = 0 /* TransactionStatus.RUN */; + } + } + } + else { + warn('transaction at ' + pathToSend.toString() + ' failed: ' + status); + for (let i = 0; i < queue.length; i++) { + queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */; + queue[i].abortReason = status; + } + } + repoRerunTransactions(repo, path); + } + }, latestHash); +} +/** + * Finds all transactions dependent on the data at changedPath and reruns them. + * + * Should be called any time cached data changes. + * + * Return the highest path that was affected by rerunning transactions. This + * is the path at which events need to be raised for. + * + * @param changedPath - The path in mergedData that changed. + * @returns The rootmost path that was affected by rerunning transactions. + */ +function repoRerunTransactions(repo, changedPath) { + const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath); + const path = treeGetPath(rootMostTransactionNode); + const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode); + repoRerunTransactionQueue(repo, queue, path); + return path; +} +/** + * Does all the work of rerunning transactions (as well as cleans up aborted + * transactions and whatnot). + * + * @param queue - The queue of transactions to run. + * @param path - The path the queue is for. + */ +function repoRerunTransactionQueue(repo, queue, path) { + if (queue.length === 0) { + return; // Nothing to do! + } + // Queue up the callbacks and fire them after cleaning up all of our + // transaction state, since the callback could trigger more transactions or + // sets. + const callbacks = []; + let events = []; + // Ignore all of the sets we're going to re-run. + const txnsToRerun = queue.filter(q => { + return q.status === 0 /* TransactionStatus.RUN */; + }); + const setsToIgnore = txnsToRerun.map(q => { + return q.currentWriteId; + }); + for (let i = 0; i < queue.length; i++) { + const transaction = queue[i]; + const relativePath = newRelativePath(path, transaction.path); + let abortTransaction = false, abortReason; + util.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.'); + if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) { + abortTransaction = true; + abortReason = transaction.abortReason; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true)); + } + else if (transaction.status === 0 /* TransactionStatus.RUN */) { + if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) { + abortTransaction = true; + abortReason = 'maxretry'; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true)); + } + else { + // This code reruns a transaction + const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore); + transaction.currentInputSnapshot = currentNode; + const newData = queue[i].update(currentNode.val()); + if (newData !== undefined) { + validateFirebaseData('transaction failed: Data returned ', newData, transaction.path); + let newDataNode = nodeFromJSON(newData); + const hasExplicitPriority = typeof newData === 'object' && + newData != null && + util.contains(newData, '.priority'); + if (!hasExplicitPriority) { + // Keep the old priority if there wasn't a priority explicitly specified. + newDataNode = newDataNode.updatePriority(currentNode.getPriority()); + } + const oldWriteId = transaction.currentWriteId; + const serverValues = repoGenerateServerValues(repo); + const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues); + transaction.currentOutputSnapshotRaw = newDataNode; + transaction.currentOutputSnapshotResolved = newNodeResolved; + transaction.currentWriteId = repoGetNextWriteId(repo); + // Mutates setsToIgnore in place + setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1); + events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally)); + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true)); + } + else { + abortTransaction = true; + abortReason = 'nodata'; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true)); + } + } + } + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); + events = []; + if (abortTransaction) { + // Abort. + queue[i].status = 2 /* TransactionStatus.COMPLETED */; + // Removing a listener can trigger pruning which can muck with + // mergedData/visibleData (as it prunes data). So defer the unwatcher + // until we're done. + (function (unwatcher) { + setTimeout(unwatcher, Math.floor(0)); + })(queue[i].unwatcher); + if (queue[i].onComplete) { + if (abortReason === 'nodata') { + callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot)); + } + else { + callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null)); + } + } + } + } + // Clean up completed transactions. + repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_); + // Now fire callbacks, now that we're in a good, known state. + for (let i = 0; i < callbacks.length; i++) { + exceptionGuard(callbacks[i]); + } + // Try to send the transaction result to the server. + repoSendReadyTransactions(repo, repo.transactionQueueTree_); +} +/** + * Returns the rootmost ancestor node of the specified path that has a pending + * transaction on it, or just returns the node for the given path if there are + * no pending transactions on any ancestor. + * + * @param path - The location to start at. + * @returns The rootmost node with a transaction. + */ +function repoGetAncestorTransactionNode(repo, path) { + let front; + // Start at the root and walk deeper into the tree towards path until we + // find a node with pending transactions. + let transactionNode = repo.transactionQueueTree_; + front = pathGetFront(path); + while (front !== null && treeGetValue(transactionNode) === undefined) { + transactionNode = treeSubTree(transactionNode, front); + path = pathPopFront(path); + front = pathGetFront(path); + } + return transactionNode; +} +/** + * Builds the queue of all transactions at or below the specified + * transactionNode. + * + * @param transactionNode + * @returns The generated queue. + */ +function repoBuildTransactionQueue(repo, transactionNode) { + // Walk any child transaction queues and aggregate them into a single queue. + const transactionQueue = []; + repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue); + // Sort them by the order the transactions were created. + transactionQueue.sort((a, b) => a.order - b.order); + return transactionQueue; +} +function repoAggregateTransactionQueuesForNode(repo, node, queue) { + const nodeQueue = treeGetValue(node); + if (nodeQueue) { + for (let i = 0; i < nodeQueue.length; i++) { + queue.push(nodeQueue[i]); + } + } + treeForEachChild(node, child => { + repoAggregateTransactionQueuesForNode(repo, child, queue); + }); +} +/** + * Remove COMPLETED transactions at or below this node in the transactionQueueTree_. + */ +function repoPruneCompletedTransactionsBelowNode(repo, node) { + const queue = treeGetValue(node); + if (queue) { + let to = 0; + for (let from = 0; from < queue.length; from++) { + if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) { + queue[to] = queue[from]; + to++; + } + } + queue.length = to; + treeSetValue(node, queue.length > 0 ? queue : undefined); + } + treeForEachChild(node, childNode => { + repoPruneCompletedTransactionsBelowNode(repo, childNode); + }); +} +/** + * Aborts all transactions on ancestors or descendants of the specified path. + * Called when doing a set() or update() since we consider them incompatible + * with transactions. + * + * @param path - Path for which we want to abort related transactions. + */ +function repoAbortTransactions(repo, path) { + const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path)); + const transactionNode = treeSubTree(repo.transactionQueueTree_, path); + treeForEachAncestor(transactionNode, (node) => { + repoAbortTransactionsOnNode(repo, node); + }); + repoAbortTransactionsOnNode(repo, transactionNode); + treeForEachDescendant(transactionNode, (node) => { + repoAbortTransactionsOnNode(repo, node); + }); + return affectedPath; +} +/** + * Abort transactions stored in this transaction queue node. + * + * @param node - Node to abort transactions for. + */ +function repoAbortTransactionsOnNode(repo, node) { + const queue = treeGetValue(node); + if (queue) { + // Queue up the callbacks and fire them after cleaning up all of our + // transaction state, since the callback could trigger more transactions + // or sets. + const callbacks = []; + // Go through queue. Any already-sent transactions must be marked for + // abort, while the unsent ones can be immediately aborted and removed. + let events = []; + let lastSent = -1; + for (let i = 0; i < queue.length; i++) { + if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ; + else if (queue[i].status === 1 /* TransactionStatus.SENT */) { + util.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.'); + lastSent = i; + // Mark transaction for abort when it comes back. + queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */; + queue[i].abortReason = 'set'; + } + else { + util.assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort'); + // We can abort it immediately. + queue[i].unwatcher(); + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true)); + if (queue[i].onComplete) { + callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null)); + } + } + } + if (lastSent === -1) { + // We're not waiting for any sent transactions. We can clear the queue. + treeSetValue(node, undefined); + } + else { + // Remove the transactions we aborted. + queue.length = lastSent + 1; + } + // Now fire the callbacks. + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events); + for (let i = 0; i < callbacks.length; i++) { + exceptionGuard(callbacks[i]); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function decodePath(pathString) { + let pathStringDecoded = ''; + const pieces = pathString.split('/'); + for (let i = 0; i < pieces.length; i++) { + if (pieces[i].length > 0) { + let piece = pieces[i]; + try { + piece = decodeURIComponent(piece.replace(/\+/g, ' ')); + } + catch (e) { } + pathStringDecoded += '/' + piece; + } + } + return pathStringDecoded; +} +/** + * @returns key value hash + */ +function decodeQuery(queryString) { + const results = {}; + if (queryString.charAt(0) === '?') { + queryString = queryString.substring(1); + } + for (const segment of queryString.split('&')) { + if (segment.length === 0) { + continue; + } + const kv = segment.split('='); + if (kv.length === 2) { + results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]); + } + else { + warn(`Invalid query segment '${segment}' in query '${queryString}'`); + } + } + return results; +} +const parseRepoInfo = function (dataURL, nodeAdmin) { + const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace; + if (parsedUrl.domain === 'firebase.com') { + fatal(parsedUrl.host + + ' is no longer supported. ' + + 'Please use .firebaseio.com instead'); + } + // Catch common error of uninitialized namespace value. + if ((!namespace || namespace === 'undefined') && + parsedUrl.domain !== 'localhost') { + fatal('Cannot parse Firebase url. Please use https://.firebaseio.com'); + } + if (!parsedUrl.secure) { + warnIfPageIsSecure(); + } + const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss'; + return { + repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin, + /*persistenceKey=*/ '', + /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain), + path: new Path(parsedUrl.pathString) + }; +}; +const parseDatabaseURL = function (dataURL) { + // Default to empty strings in the event of a malformed string. + let host = '', domain = '', subdomain = '', pathString = '', namespace = ''; + // Always default to SSL, unless otherwise specified. + let secure = true, scheme = 'https', port = 443; + // Don't do any validation here. The caller is responsible for validating the result of parsing. + if (typeof dataURL === 'string') { + // Parse scheme. + let colonInd = dataURL.indexOf('//'); + if (colonInd >= 0) { + scheme = dataURL.substring(0, colonInd - 1); + dataURL = dataURL.substring(colonInd + 2); + } + // Parse host, path, and query string. + let slashInd = dataURL.indexOf('/'); + if (slashInd === -1) { + slashInd = dataURL.length; + } + let questionMarkInd = dataURL.indexOf('?'); + if (questionMarkInd === -1) { + questionMarkInd = dataURL.length; + } + host = dataURL.substring(0, Math.min(slashInd, questionMarkInd)); + if (slashInd < questionMarkInd) { + // For pathString, questionMarkInd will always come after slashInd + pathString = decodePath(dataURL.substring(slashInd, questionMarkInd)); + } + const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd))); + // If we have a port, use scheme for determining if it's secure. + colonInd = host.indexOf(':'); + if (colonInd >= 0) { + secure = scheme === 'https' || scheme === 'wss'; + port = parseInt(host.substring(colonInd + 1), 10); + } + else { + colonInd = host.length; + } + const hostWithoutPort = host.slice(0, colonInd); + if (hostWithoutPort.toLowerCase() === 'localhost') { + domain = 'localhost'; + } + else if (hostWithoutPort.split('.').length <= 2) { + domain = hostWithoutPort; + } + else { + // Interpret the subdomain of a 3 or more component URL as the namespace name. + const dotInd = host.indexOf('.'); + subdomain = host.substring(0, dotInd).toLowerCase(); + domain = host.substring(dotInd + 1); + // Normalize namespaces to lowercase to share storage / connection. + namespace = subdomain; + } + // Always treat the value of the `ns` as the namespace name if it is present. + if ('ns' in queryParams) { + namespace = queryParams['ns']; + } + } + return { + host, + port, + domain, + subdomain, + secure, + scheme, + pathString, + namespace + }; +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Modeled after base64 web-safe chars, but ordered by ASCII. +const PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'; +/** + * Fancy ID generator that creates 20-character string identifiers with the + * following properties: + * + * 1. They're based on timestamp so that they sort *after* any existing ids. + * 2. They contain 72-bits of random data after the timestamp so that IDs won't + * collide with other clients' IDs. + * 3. They sort *lexicographically* (so the timestamp is converted to characters + * that will sort properly). + * 4. They're monotonically increasing. Even if you generate more than one in + * the same timestamp, the latter ones will sort after the former ones. We do + * this by using the previous random bits but "incrementing" them by 1 (only + * in the case of a timestamp collision). + */ +const nextPushId = (function () { + // Timestamp of last push, used to prevent local collisions if you push twice + // in one ms. + let lastPushTime = 0; + // We generate 72-bits of randomness which get turned into 12 characters and + // appended to the timestamp to prevent collisions with other clients. We + // store the last characters we generated because in the event of a collision, + // we'll use those same characters except "incremented" by one. + const lastRandChars = []; + return function (now) { + const duplicateTime = now === lastPushTime; + lastPushTime = now; + let i; + const timeStampChars = new Array(8); + for (i = 7; i >= 0; i--) { + timeStampChars[i] = PUSH_CHARS.charAt(now % 64); + // NOTE: Can't use << here because javascript will convert to int and lose + // the upper bits. + now = Math.floor(now / 64); + } + util.assert(now === 0, 'Cannot push at time == 0'); + let id = timeStampChars.join(''); + if (!duplicateTime) { + for (i = 0; i < 12; i++) { + lastRandChars[i] = Math.floor(Math.random() * 64); + } + } + else { + // If the timestamp hasn't changed since last push, use the same random + // number, except incremented by 1. + for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) { + lastRandChars[i] = 0; + } + lastRandChars[i]++; + } + for (i = 0; i < 12; i++) { + id += PUSH_CHARS.charAt(lastRandChars[i]); + } + util.assert(id.length === 20, 'nextPushId: Length should be 20.'); + return id; + }; +})(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Encapsulates the data needed to raise an event + */ +class DataEvent { + /** + * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed + * @param eventRegistration - The function to call to with the event data. User provided + * @param snapshot - The data backing the event + * @param prevName - Optional, the name of the previous child for child_* events. + */ + constructor(eventType, eventRegistration, snapshot, prevName) { + this.eventType = eventType; + this.eventRegistration = eventRegistration; + this.snapshot = snapshot; + this.prevName = prevName; + } + getPath() { + const ref = this.snapshot.ref; + if (this.eventType === 'value') { + return ref._path; + } + else { + return ref.parent._path; + } + } + getEventType() { + return this.eventType; + } + getEventRunner() { + return this.eventRegistration.getEventRunner(this); + } + toString() { + return (this.getPath().toString() + + ':' + + this.eventType + + ':' + + util.stringify(this.snapshot.exportVal())); + } +} +class CancelEvent { + constructor(eventRegistration, error, path) { + this.eventRegistration = eventRegistration; + this.error = error; + this.path = path; + } + getPath() { + return this.path; + } + getEventType() { + return 'cancel'; + } + getEventRunner() { + return this.eventRegistration.getEventRunner(this); + } + toString() { + return this.path.toString() + ':cancel'; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A wrapper class that converts events from the database@exp SDK to the legacy + * Database SDK. Events are not converted directly as event registration relies + * on reference comparison of the original user callback (see `matches()`) and + * relies on equality of the legacy SDK's `context` object. + */ +class CallbackContext { + constructor(snapshotCallback, cancelCallback) { + this.snapshotCallback = snapshotCallback; + this.cancelCallback = cancelCallback; + } + onValue(expDataSnapshot, previousChildName) { + this.snapshotCallback.call(null, expDataSnapshot, previousChildName); + } + onCancel(error) { + util.assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback'); + return this.cancelCallback.call(null, error); + } + get hasCancelCallback() { + return !!this.cancelCallback; + } + matches(other) { + return (this.snapshotCallback === other.snapshotCallback || + (this.snapshotCallback.userCallback !== undefined && + this.snapshotCallback.userCallback === + other.snapshotCallback.userCallback && + this.snapshotCallback.context === other.snapshotCallback.context)); + } +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The `onDisconnect` class allows you to write or clear data when your client + * disconnects from the Database server. These updates occur whether your + * client disconnects cleanly or not, so you can rely on them to clean up data + * even if a connection is dropped or a client crashes. + * + * The `onDisconnect` class is most commonly used to manage presence in + * applications where it is useful to detect how many clients are connected and + * when other clients disconnect. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * To avoid problems when a connection is dropped before the requests can be + * transferred to the Database server, these functions should be called before + * writing any data. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time you reconnect. + */ +class OnDisconnect { + /** @hideconstructor */ + constructor(_repo, _path) { + this._repo = _repo; + this._path = _path; + } + /** + * Cancels all previously queued `onDisconnect()` set or update events for this + * location and all children. + * + * If a write has been queued for this location via a `set()` or `update()` at a + * parent location, the write at this location will be canceled, though writes + * to sibling locations will still occur. + * + * @returns Resolves when synchronization to the server is complete. + */ + cancel() { + const deferred = new util.Deferred(); + repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Ensures the data at this location is deleted when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + * + * @returns Resolves when synchronization to the server is complete. + */ + remove() { + validateWritablePath('OnDisconnect.remove', this._path); + const deferred = new util.Deferred(); + repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Ensures the data at this location is set to the specified value when the + * client is disconnected (due to closing the browser, navigating to a new page, + * or network issues). + * + * `set()` is especially useful for implementing "presence" systems, where a + * value should be changed or cleared when a user disconnects so that they + * appear "offline" to other users. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time. + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + set(value) { + validateWritablePath('OnDisconnect.set', this._path); + validateFirebaseDataArg('OnDisconnect.set', value, this._path, false); + const deferred = new util.Deferred(); + repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Ensures the data at this location is set to the specified value and priority + * when the client is disconnected (due to closing the browser, navigating to a + * new page, or network issues). + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + setWithPriority(value, priority) { + validateWritablePath('OnDisconnect.setWithPriority', this._path); + validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false); + validatePriority('OnDisconnect.setWithPriority', priority, false); + const deferred = new util.Deferred(); + repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Writes multiple values at this location when the client is disconnected (due + * to closing the browser, navigating to a new page, or network issues). + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, "name/first") + * from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * @param values - Object containing multiple values. + * @returns Resolves when synchronization to the Database is complete. + */ + update(values) { + validateWritablePath('OnDisconnect.update', this._path); + validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false); + const deferred = new util.Deferred(); + repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { })); + return deferred.promise; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ +class QueryImpl { + /** + * @hideconstructor + */ + constructor(_repo, _path, _queryParams, _orderByCalled) { + this._repo = _repo; + this._path = _path; + this._queryParams = _queryParams; + this._orderByCalled = _orderByCalled; + } + get key() { + if (pathIsEmpty(this._path)) { + return null; + } + else { + return pathGetBack(this._path); + } + } + get ref() { + return new ReferenceImpl(this._repo, this._path); + } + get _queryIdentifier() { + const obj = queryParamsGetQueryObject(this._queryParams); + const id = ObjectToUniqueKey(obj); + return id === '{}' ? 'default' : id; + } + /** + * An object representation of the query parameters used by this Query. + */ + get _queryObject() { + return queryParamsGetQueryObject(this._queryParams); + } + isEqual(other) { + other = util.getModularInstance(other); + if (!(other instanceof QueryImpl)) { + return false; + } + const sameRepo = this._repo === other._repo; + const samePath = pathEquals(this._path, other._path); + const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier; + return sameRepo && samePath && sameQueryIdentifier; + } + toJSON() { + return this.toString(); + } + toString() { + return this._repo.toString() + pathToUrlEncodedString(this._path); + } +} +/** + * Validates that no other order by call has been made + */ +function validateNoPreviousOrderByCall(query, fnName) { + if (query._orderByCalled === true) { + throw new Error(fnName + ": You can't combine multiple orderBy calls."); + } +} +/** + * Validates start/end values for queries. + */ +function validateQueryEndpoints(params) { + let startNode = null; + let endNode = null; + if (params.hasStart()) { + startNode = params.getIndexStartValue(); + } + if (params.hasEnd()) { + endNode = params.getIndexEndValue(); + } + if (params.getIndex() === KEY_INDEX) { + const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' + + 'startAt(), endAt(), or equalTo().'; + const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' + + 'endAt(), endBefore(), or equalTo() must be a string.'; + if (params.hasStart()) { + const startName = params.getIndexStartName(); + if (startName !== MIN_NAME) { + throw new Error(tooManyArgsError); + } + else if (typeof startNode !== 'string') { + throw new Error(wrongArgTypeError); + } + } + if (params.hasEnd()) { + const endName = params.getIndexEndName(); + if (endName !== MAX_NAME) { + throw new Error(tooManyArgsError); + } + else if (typeof endNode !== 'string') { + throw new Error(wrongArgTypeError); + } + } + } + else if (params.getIndex() === PRIORITY_INDEX) { + if ((startNode != null && !isValidPriority(startNode)) || + (endNode != null && !isValidPriority(endNode))) { + throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' + + 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' + + '(null, a number, or a string).'); + } + } + else { + util.assert(params.getIndex() instanceof PathIndex || + params.getIndex() === VALUE_INDEX, 'unknown index type.'); + if ((startNode != null && typeof startNode === 'object') || + (endNode != null && typeof endNode === 'object')) { + throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' + + 'equalTo() cannot be an object.'); + } + } +} +/** + * Validates that limit* has been called with the correct combination of parameters + */ +function validateLimit(params) { + if (params.hasStart() && + params.hasEnd() && + params.hasLimit() && + !params.hasAnchoredLimit()) { + throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " + + 'limitToFirst() or limitToLast() instead.'); + } +} +/** + * @internal + */ +class ReferenceImpl extends QueryImpl { + /** @hideconstructor */ + constructor(repo, path) { + super(repo, path, new QueryParams(), false); + } + get parent() { + const parentPath = pathParent(this._path); + return parentPath === null + ? null + : new ReferenceImpl(this._repo, parentPath); + } + get root() { + let ref = this; + while (ref.parent !== null) { + ref = ref.parent; + } + return ref; + } +} +/** + * A `DataSnapshot` contains data from a Database location. + * + * Any time you read data from the Database, you receive the data as a + * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach + * with `on()` or `once()`. You can extract the contents of the snapshot as a + * JavaScript object by calling the `val()` method. Alternatively, you can + * traverse into the snapshot by calling `child()` to return child snapshots + * (which you could then call `val()` on). + * + * A `DataSnapshot` is an efficiently generated, immutable copy of the data at + * a Database location. It cannot be modified and will never change (to modify + * data, you always call the `set()` method on a `Reference` directly). + */ +class DataSnapshot { + /** + * @param _node - A SnapshotNode to wrap. + * @param ref - The location this snapshot came from. + * @param _index - The iteration order for this snapshot + * @hideconstructor + */ + constructor(_node, + /** + * The location of this DataSnapshot. + */ + ref, _index) { + this._node = _node; + this.ref = ref; + this._index = _index; + } + /** + * Gets the priority value of the data in this `DataSnapshot`. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data} + * ). + */ + get priority() { + // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY) + return this._node.getPriority().val(); + } + /** + * The key (last part of the path) of the location of this `DataSnapshot`. + * + * The last token in a Database location is considered its key. For example, + * "ada" is the key for the /users/ada/ node. Accessing the key on any + * `DataSnapshot` will return the key for the location that generated it. + * However, accessing the key on the root URL of a Database will return + * `null`. + */ + get key() { + return this.ref.key; + } + /** Returns the number of child properties of this `DataSnapshot`. */ + get size() { + return this._node.numChildren(); + } + /** + * Gets another `DataSnapshot` for the location at the specified relative path. + * + * Passing a relative path to the `child()` method of a DataSnapshot returns + * another `DataSnapshot` for the location at the specified relative path. The + * relative path can either be a simple child name (for example, "ada") or a + * deeper, slash-separated path (for example, "ada/name/first"). If the child + * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot` + * whose value is `null`) is returned. + * + * @param path - A relative path to the location of child data. + */ + child(path) { + const childPath = new Path(path); + const childRef = child(this.ref, path); + return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX); + } + /** + * Returns true if this `DataSnapshot` contains any data. It is slightly more + * efficient than using `snapshot.val() !== null`. + */ + exists() { + return !this._node.isEmpty(); + } + /** + * Exports the entire contents of the DataSnapshot as a JavaScript object. + * + * The `exportVal()` method is similar to `val()`, except priority information + * is included (if available), making it suitable for backing up your data. + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + exportVal() { + return this._node.val(true); + } + /** + * Enumerates the top-level children in the `IteratedDataSnapshot`. + * + * Because of the way JavaScript objects work, the ordering of data in the + * JavaScript object returned by `val()` is not guaranteed to match the + * ordering on the server nor the ordering of `onChildAdded()` events. That is + * where `forEach()` comes in handy. It guarantees the children of a + * `DataSnapshot` will be iterated in their query order. + * + * If no explicit `orderBy*()` method is used, results are returned + * ordered by key (unless priorities are used, in which case, results are + * returned by priority). + * + * @param action - A function that will be called for each child DataSnapshot. + * The callback can return true to cancel further enumeration. + * @returns true if enumeration was canceled due to your callback returning + * true. + */ + forEach(action) { + if (this._node.isLeafNode()) { + return false; + } + const childrenNode = this._node; + // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type... + return !!childrenNode.forEachChild(this._index, (key, node) => { + return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX)); + }); + } + /** + * Returns true if the specified child path has (non-null) data. + * + * @param path - A relative path to the location of a potential child. + * @returns `true` if data exists at the specified child path; else + * `false`. + */ + hasChild(path) { + const childPath = new Path(path); + return !this._node.getChild(childPath).isEmpty(); + } + /** + * Returns whether or not the `DataSnapshot` has any non-`null` child + * properties. + * + * You can use `hasChildren()` to determine if a `DataSnapshot` has any + * children. If it does, you can enumerate them using `forEach()`. If it + * doesn't, then either this snapshot contains a primitive value (which can be + * retrieved with `val()`) or it is empty (in which case, `val()` will return + * `null`). + * + * @returns true if this snapshot has any children; else false. + */ + hasChildren() { + if (this._node.isLeafNode()) { + return false; + } + else { + return !this._node.isEmpty(); + } + } + /** + * Returns a JSON-serializable representation of this object. + */ + toJSON() { + return this.exportVal(); + } + /** + * Extracts a JavaScript value from a `DataSnapshot`. + * + * Depending on the data in a `DataSnapshot`, the `val()` method may return a + * scalar type (string, number, or boolean), an array, or an object. It may + * also return null, indicating that the `DataSnapshot` is empty (contains no + * data). + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + val() { + return this._node.val(); + } +} +/** + * + * Returns a `Reference` representing the location in the Database + * corresponding to the provided path. If no path is provided, the `Reference` + * will point to the root of the Database. + * + * @param db - The database instance to obtain a reference for. + * @param path - Optional path representing the location the returned + * `Reference` will point. If not provided, the returned `Reference` will + * point to the root of the Database. + * @returns If a path is provided, a `Reference` + * pointing to the provided path. Otherwise, a `Reference` pointing to the + * root of the Database. + */ +function ref(db, path) { + db = util.getModularInstance(db); + db._checkNotDeleted('ref'); + return path !== undefined ? child(db._root, path) : db._root; +} +/** + * Returns a `Reference` representing the location in the Database + * corresponding to the provided Firebase URL. + * + * An exception is thrown if the URL is not a valid Firebase Database URL or it + * has a different domain than the current `Database` instance. + * + * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored + * and are not applied to the returned `Reference`. + * + * @param db - The database instance to obtain a reference for. + * @param url - The Firebase URL at which the returned `Reference` will + * point. + * @returns A `Reference` pointing to the provided + * Firebase URL. + */ +function refFromURL(db, url) { + db = util.getModularInstance(db); + db._checkNotDeleted('refFromURL'); + const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin); + validateUrl('refFromURL', parsedURL); + const repoInfo = parsedURL.repoInfo; + if (!db._repo.repoInfo_.isCustomHost() && + repoInfo.host !== db._repo.repoInfo_.host) { + fatal('refFromURL' + + ': Host name does not match the current database: ' + + '(found ' + + repoInfo.host + + ' but expected ' + + db._repo.repoInfo_.host + + ')'); + } + return ref(db, parsedURL.path.toString()); +} +/** + * Gets a `Reference` for the location at the specified relative path. + * + * The relative path can either be a simple child name (for example, "ada") or + * a deeper slash-separated path (for example, "ada/name/first"). + * + * @param parent - The parent location. + * @param path - A relative path from this location to the desired child + * location. + * @returns The specified child location. + */ +function child(parent, path) { + parent = util.getModularInstance(parent); + if (pathGetFront(parent._path) === null) { + validateRootPathString('child', 'path', path, false); + } + else { + validatePathString('child', 'path', path, false); + } + return new ReferenceImpl(parent._repo, pathChild(parent._path, path)); +} +/** + * Returns an `OnDisconnect` object - see + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information on how to use it. + * + * @param ref - The reference to add OnDisconnect triggers for. + */ +function onDisconnect(ref) { + ref = util.getModularInstance(ref); + return new OnDisconnect(ref._repo, ref._path); +} +/** + * Generates a new child location using a unique key and returns its + * `Reference`. + * + * This is the most common pattern for adding data to a collection of items. + * + * If you provide a value to `push()`, the value is written to the + * generated location. If you don't pass a value, nothing is written to the + * database and the child remains empty (but you can use the `Reference` + * elsewhere). + * + * The unique keys generated by `push()` are ordered by the current time, so the + * resulting list of items is chronologically sorted. The keys are also + * designed to be unguessable (they contain 72 random bits of entropy). + * + * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}. + * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}. + * + * @param parent - The parent location. + * @param value - Optional value to be written at the generated location. + * @returns Combined `Promise` and `Reference`; resolves when write is complete, + * but can be used immediately as the `Reference` to the child location. + */ +function push(parent, value) { + parent = util.getModularInstance(parent); + validateWritablePath('push', parent._path); + validateFirebaseDataArg('push', value, parent._path, true); + const now = repoServerTime(parent._repo); + const name = nextPushId(now); + // push() returns a ThennableReference whose promise is fulfilled with a + // regular Reference. We use child() to create handles to two different + // references. The first is turned into a ThennableReference below by adding + // then() and catch() methods and is used as the return value of push(). The + // second remains a regular Reference and is used as the fulfilled value of + // the first ThennableReference. + const thenablePushRef = child(parent, name); + const pushRef = child(parent, name); + let promise; + if (value != null) { + promise = set(pushRef, value).then(() => pushRef); + } + else { + promise = Promise.resolve(pushRef); + } + thenablePushRef.then = promise.then.bind(promise); + thenablePushRef.catch = promise.then.bind(promise, undefined); + return thenablePushRef; +} +/** + * Removes the data at this Database location. + * + * Any data at child locations will also be deleted. + * + * The effect of the remove will be visible immediately and the corresponding + * event 'value' will be triggered. Synchronization of the remove to the + * Firebase servers will also be started, and the returned Promise will resolve + * when complete. If provided, the onComplete callback will be called + * asynchronously after synchronization has finished. + * + * @param ref - The location to remove. + * @returns Resolves when remove on server is complete. + */ +function remove(ref) { + validateWritablePath('remove', ref._path); + return set(ref, null); +} +/** + * Writes data to this Database location. + * + * This will overwrite any data at this location and all child locations. + * + * The effect of the write will be visible immediately, and the corresponding + * events ("value", "child_added", etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * Passing `null` for the new value is equivalent to calling `remove()`; namely, + * all data at this location and all child locations will be deleted. + * + * `set()` will remove any priority stored at this location, so if priority is + * meant to be preserved, you need to use `setWithPriority()` instead. + * + * Note that modifying data with `set()` will cancel any pending transactions + * at that location, so extreme care should be taken if mixing `set()` and + * `transaction()` to modify the same data. + * + * A single `set()` will generate a single "value" event at the location where + * the `set()` was performed. + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @returns Resolves when write to server is complete. + */ +function set(ref, value) { + ref = util.getModularInstance(ref); + validateWritablePath('set', ref._path); + validateFirebaseDataArg('set', value, ref._path, false); + const deferred = new util.Deferred(); + repoSetWithPriority(ref._repo, ref._path, value, + /*priority=*/ null, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Sets a priority for the data at this Database location. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +function setPriority(ref, priority) { + ref = util.getModularInstance(ref); + validateWritablePath('setPriority', ref._path); + validatePriority('setPriority', priority, false); + const deferred = new util.Deferred(); + repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Writes data the Database location. Like `set()` but also specifies the + * priority for that data. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +function setWithPriority(ref, value, priority) { + validateWritablePath('setWithPriority', ref._path); + validateFirebaseDataArg('setWithPriority', value, ref._path, false); + validatePriority('setWithPriority', priority, false); + if (ref.key === '.length' || ref.key === '.keys') { + throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.'; + } + const deferred = new util.Deferred(); + repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Writes multiple values to the Database at once. + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, + * "name/first") from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * The effect of the write will be visible immediately, and the corresponding + * events ('value', 'child_added', etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * A single `update()` will generate a single "value" event at the location + * where the `update()` was performed, regardless of how many children were + * modified. + * + * Note that modifying data with `update()` will cancel any pending + * transactions at that location, so extreme care should be taken if mixing + * `update()` and `transaction()` to modify the same data. + * + * Passing `null` to `update()` will remove the data at this location. + * + * See + * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}. + * + * @param ref - The location to write to. + * @param values - Object containing multiple values. + * @returns Resolves when update on server is complete. + */ +function update(ref, values) { + validateFirebaseMergeDataArg('update', values, ref._path, false); + const deferred = new util.Deferred(); + repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Gets the most up-to-date result for this query. + * + * @param query - The query to run. + * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is + * available, or rejects if the client is unable to return a value (e.g., if the + * server is unreachable and there is nothing cached). + */ +function get(query) { + query = util.getModularInstance(query); + const callbackContext = new CallbackContext(() => { }); + const container = new ValueEventRegistration(callbackContext); + return repoGetValue(query._repo, query, container).then(node => { + return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex()); + }); +} +/** + * Represents registration for 'value' events. + */ +class ValueEventRegistration { + constructor(callbackContext) { + this.callbackContext = callbackContext; + } + respondsTo(eventType) { + return eventType === 'value'; + } + createEvent(change, query) { + const index = query._queryParams.getIndex(); + return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index)); + } + getEventRunner(eventData) { + if (eventData.getEventType() === 'cancel') { + return () => this.callbackContext.onCancel(eventData.error); + } + else { + return () => this.callbackContext.onValue(eventData.snapshot, null); + } + } + createCancelEvent(error, path) { + if (this.callbackContext.hasCancelCallback) { + return new CancelEvent(this, error, path); + } + else { + return null; + } + } + matches(other) { + if (!(other instanceof ValueEventRegistration)) { + return false; + } + else if (!other.callbackContext || !this.callbackContext) { + // If no callback specified, we consider it to match any callback. + return true; + } + else { + return other.callbackContext.matches(this.callbackContext); + } + } + hasAnyCallback() { + return this.callbackContext !== null; + } +} +/** + * Represents the registration of a child_x event. + */ +class ChildEventRegistration { + constructor(eventType, callbackContext) { + this.eventType = eventType; + this.callbackContext = callbackContext; + } + respondsTo(eventType) { + let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType; + eventToCheck = + eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck; + return this.eventType === eventToCheck; + } + createCancelEvent(error, path) { + if (this.callbackContext.hasCancelCallback) { + return new CancelEvent(this, error, path); + } + else { + return null; + } + } + createEvent(change, query) { + util.assert(change.childName != null, 'Child events should have a childName.'); + const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName); + const index = query._queryParams.getIndex(); + return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName); + } + getEventRunner(eventData) { + if (eventData.getEventType() === 'cancel') { + return () => this.callbackContext.onCancel(eventData.error); + } + else { + return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName); + } + } + matches(other) { + if (other instanceof ChildEventRegistration) { + return (this.eventType === other.eventType && + (!this.callbackContext || + !other.callbackContext || + this.callbackContext.matches(other.callbackContext))); + } + return false; + } + hasAnyCallback() { + return !!this.callbackContext; + } +} +function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) { + let cancelCallback; + if (typeof cancelCallbackOrListenOptions === 'object') { + cancelCallback = undefined; + options = cancelCallbackOrListenOptions; + } + if (typeof cancelCallbackOrListenOptions === 'function') { + cancelCallback = cancelCallbackOrListenOptions; + } + if (options && options.onlyOnce) { + const userCallback = callback; + const onceCallback = (dataSnapshot, previousChildName) => { + repoRemoveEventCallbackForQuery(query._repo, query, container); + userCallback(dataSnapshot, previousChildName); + }; + onceCallback.userCallback = callback.userCallback; + onceCallback.context = callback.context; + callback = onceCallback; + } + const callbackContext = new CallbackContext(callback, cancelCallback || undefined); + const container = eventType === 'value' + ? new ValueEventRegistration(callbackContext) + : new ChildEventRegistration(eventType, callbackContext); + repoAddEventCallbackForQuery(query._repo, query, container); + return () => repoRemoveEventCallbackForQuery(query._repo, query, container); +} +function onValue(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options); +} +function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options); +} +function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options); +} +function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options); +} +function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options); +} +/** + * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener. + * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from + * the respective `on*` callbacks. + * + * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener + * will not automatically remove listeners registered on child nodes, `off()` + * must also be called on any child listeners to remove the callback. + * + * If a callback is not specified, all callbacks for the specified eventType + * will be removed. Similarly, if no eventType is specified, all callbacks + * for the `Reference` will be removed. + * + * Individual listeners can also be removed by invoking their unsubscribe + * callbacks. + * + * @param query - The query that the listener was registered with. + * @param eventType - One of the following strings: "value", "child_added", + * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks + * for the `Reference` will be removed. + * @param callback - The callback function that was passed to `on()` or + * `undefined` to remove all callbacks. + */ +function off(query, eventType, callback) { + let container = null; + const expCallback = callback ? new CallbackContext(callback) : null; + if (eventType === 'value') { + container = new ValueEventRegistration(expCallback); + } + else if (eventType) { + container = new ChildEventRegistration(eventType, expCallback); + } + repoRemoveEventCallbackForQuery(query._repo, query, container); +} +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Database query. `QueryConstraint`s are created by invoking {@link endAt}, + * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link + * limitToFirst}, {@link limitToLast}, {@link orderByChild}, + * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} , + * {@link orderByValue} or {@link equalTo} and + * can then be passed to {@link query} to create a new query instance that + * also contains this `QueryConstraint`. + */ +class QueryConstraint { +} +class QueryEndAtConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'endAt'; + } + _apply(query) { + validateFirebaseDataArg('endAt', this._value, query._path, true); + const newParams = queryParamsEndAt(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasEnd()) { + throw new Error('endAt: Starting point was already set (by another call to endAt, ' + + 'endBefore or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified ending point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name less than or equal + * to the specified key. + * + * You can read more about `endAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to end at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end at, among the children with the previously + * specified priority. This argument is only allowed if ordering by child, + * value, or priority. + */ +function endAt(value, key) { + validateKey('endAt', 'key', key, true); + return new QueryEndAtConstraint(value, key); +} +class QueryEndBeforeConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'endBefore'; + } + _apply(query) { + validateFirebaseDataArg('endBefore', this._value, query._path, false); + const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasEnd()) { + throw new Error('endBefore: Starting point was already set (by another call to endAt, ' + + 'endBefore or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified ending point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is exclusive. If only a value is provided, children + * with a value less than the specified value will be included in the query. + * If a key is specified, then children must have a value less than or equal + * to the specified value and a key name less than the specified key. + * + * @param value - The value to end before. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end before, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +function endBefore(value, key) { + validateKey('endBefore', 'key', key, true); + return new QueryEndBeforeConstraint(value, key); +} +class QueryStartAtConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'startAt'; + } + _apply(query) { + validateFirebaseDataArg('startAt', this._value, query._path, true); + const newParams = queryParamsStartAt(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasStart()) { + throw new Error('startAt: Starting point was already set (by another call to startAt, ' + + 'startBefore or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified starting point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name greater than or + * equal to the specified key. + * + * You can read more about `startAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to start at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at. This argument is only allowed if + * ordering by child, value, or priority. + */ +function startAt(value = null, key) { + validateKey('startAt', 'key', key, true); + return new QueryStartAtConstraint(value, key); +} +class QueryStartAfterConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'startAfter'; + } + _apply(query) { + validateFirebaseDataArg('startAfter', this._value, query._path, false); + const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasStart()) { + throw new Error('startAfter: Starting point was already set (by another call to startAt, ' + + 'startAfter, or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified starting point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is exclusive. If only a value is provided, children + * with a value greater than the specified value will be included in the query. + * If a key is specified, then children must have a value greater than or equal + * to the specified value and a a key name greater than the specified key. + * + * @param value - The value to start after. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start after. This argument is only allowed if + * ordering by child, value, or priority. + */ +function startAfter(value, key) { + validateKey('startAfter', 'key', key, true); + return new QueryStartAfterConstraint(value, key); +} +class QueryLimitToFirstConstraint extends QueryConstraint { + constructor(_limit) { + super(); + this._limit = _limit; + this.type = 'limitToFirst'; + } + _apply(query) { + if (query._queryParams.hasLimit()) { + throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' + + 'or limitToLast).'); + } + return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled); + } +} +/** + * Creates a new `QueryConstraint` that if limited to the first specific number + * of children. + * + * The `limitToFirst()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the first 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToFirst()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +function limitToFirst(limit) { + if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) { + throw new Error('limitToFirst: First argument must be a positive integer.'); + } + return new QueryLimitToFirstConstraint(limit); +} +class QueryLimitToLastConstraint extends QueryConstraint { + constructor(_limit) { + super(); + this._limit = _limit; + this.type = 'limitToLast'; + } + _apply(query) { + if (query._queryParams.hasLimit()) { + throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' + + 'or limitToLast).'); + } + return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled); + } +} +/** + * Creates a new `QueryConstraint` that is limited to return only the last + * specified number of children. + * + * The `limitToLast()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the last 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToLast()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +function limitToLast(limit) { + if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) { + throw new Error('limitToLast: First argument must be a positive integer.'); + } + return new QueryLimitToLastConstraint(limit); +} +class QueryOrderByChildConstraint extends QueryConstraint { + constructor(_path) { + super(); + this._path = _path; + this.type = 'orderByChild'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByChild'); + const parsedPath = new Path(this._path); + if (pathIsEmpty(parsedPath)) { + throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.'); + } + const index = new PathIndex(parsedPath); + const newParams = queryParamsOrderBy(query._queryParams, index); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by the specified child key. + * + * Queries can only order by one key at a time. Calling `orderByChild()` + * multiple times on the same query is an error. + * + * Firebase queries allow you to order your data by any child key on the fly. + * However, if you know in advance what your indexes will be, you can define + * them via the .indexOn rule in your Security Rules for better performance. See + * the{@link https://firebase.google.com/docs/database/security/indexing-data} + * rule for more information. + * + * You can read more about `orderByChild()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + * + * @param path - The path to order by. + */ +function orderByChild(path) { + if (path === '$key') { + throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.'); + } + else if (path === '$priority') { + throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.'); + } + else if (path === '$value') { + throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.'); + } + validatePathString('orderByChild', 'path', path, false); + return new QueryOrderByChildConstraint(path); +} +class QueryOrderByKeyConstraint extends QueryConstraint { + constructor() { + super(...arguments); + this.type = 'orderByKey'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByKey'); + const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by the key. + * + * Sorts the results of a query by their (ascending) key values. + * + * You can read more about `orderByKey()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +function orderByKey() { + return new QueryOrderByKeyConstraint(); +} +class QueryOrderByPriorityConstraint extends QueryConstraint { + constructor() { + super(...arguments); + this.type = 'orderByPriority'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByPriority'); + const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by priority. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data} + * for alternatives to priority. + */ +function orderByPriority() { + return new QueryOrderByPriorityConstraint(); +} +class QueryOrderByValueConstraint extends QueryConstraint { + constructor() { + super(...arguments); + this.type = 'orderByValue'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByValue'); + const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by value. + * + * If the children of a query are all scalar values (string, number, or + * boolean), you can order the results by their (ascending) values. + * + * You can read more about `orderByValue()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +function orderByValue() { + return new QueryOrderByValueConstraint(); +} +class QueryEqualToValueConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'equalTo'; + } + _apply(query) { + validateFirebaseDataArg('equalTo', this._value, query._path, false); + if (query._queryParams.hasStart()) { + throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' + + 'equalTo).'); + } + if (query._queryParams.hasEnd()) { + throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' + + 'equalTo).'); + } + return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query)); + } +} +/** + * Creates a `QueryConstraint` that includes children that match the specified + * value. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The optional key argument can be used to further limit the range of the + * query. If it is specified, then children that have exactly the specified + * value must also have exactly the specified key as their key name. This can be + * used to filter result sets with many matches for the same value. + * + * You can read more about `equalTo()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to match for. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +function equalTo(value, key) { + validateKey('equalTo', 'key', key, true); + return new QueryEqualToValueConstraint(value, key); +} +/** + * Creates a new immutable instance of `Query` that is extended to also include + * additional query constraints. + * + * @param query - The Query instance to use as a base for the new constraints. + * @param queryConstraints - The list of `QueryConstraint`s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +function query(query, ...queryConstraints) { + let queryImpl = util.getModularInstance(query); + for (const constraint of queryConstraints) { + queryImpl = constraint._apply(queryImpl); + } + return queryImpl; +} +/** + * Define reference constructor in various modules + * + * We are doing this here to avoid several circular + * dependency issues + */ +syncPointSetReferenceConstructor(ReferenceImpl); +syncTreeSetReferenceConstructor(ReferenceImpl); + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This variable is also defined in the firebase Node.js Admin SDK. Before + * modifying this definition, consult the definition in: + * + * https://github.com/firebase/firebase-admin-node + * + * and make sure the two are consistent. + */ +const FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST'; +/** + * Creates and caches `Repo` instances. + */ +const repos = {}; +/** + * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes). + */ +let useRestClient = false; +/** + * Update an existing `Repo` in place to point to a new host/port. + */ +function repoManagerApplyEmulatorSettings(repo, hostAndPort, emulatorOptions, tokenProvider) { + const portIndex = hostAndPort.lastIndexOf(':'); + const host = hostAndPort.substring(0, portIndex); + const useSsl = util.isCloudWorkstation(host); + repo.repoInfo_ = new RepoInfo(hostAndPort, + /* secure= */ useSsl, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams, + /*isUsingEmulator=*/ true, emulatorOptions); + if (tokenProvider) { + repo.authTokenProvider_ = tokenProvider; + } +} +/** + * This function should only ever be called to CREATE a new database instance. + * @internal + */ +function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) { + let dbUrl = url || app.options.databaseURL; + if (dbUrl === undefined) { + if (!app.options.projectId) { + fatal("Can't determine Firebase Database URL. Be sure to include " + + ' a Project ID when calling firebase.initializeApp().'); + } + log('Using default host for project ', app.options.projectId); + dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`; + } + let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin); + let repoInfo = parsedUrl.repoInfo; + let isEmulator; + let dbEmulatorHost = undefined; + if (typeof process !== 'undefined' && process.env) { + dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR]; + } + if (dbEmulatorHost) { + isEmulator = true; + dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`; + parsedUrl = parseRepoInfo(dbUrl, nodeAdmin); + repoInfo = parsedUrl.repoInfo; + } + else { + isEmulator = !parsedUrl.repoInfo.secure; + } + const authTokenProvider = nodeAdmin && isEmulator + ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER) + : new FirebaseAuthTokenProvider(app.name, app.options, authProvider); + validateUrl('Invalid Firebase Database URL', parsedUrl); + if (!pathIsEmpty(parsedUrl.path)) { + fatal('Database URL must point to the root of a Firebase Database ' + + '(not including a child path).'); + } + const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app, appCheckProvider)); + return new Database(repo, app); +} +/** + * Remove the repo and make sure it is disconnected. + * + */ +function repoManagerDeleteRepo(repo, appName) { + const appRepos = repos[appName]; + // This should never happen... + if (!appRepos || appRepos[repo.key] !== repo) { + fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`); + } + repoInterrupt(repo); + delete appRepos[repo.key]; +} +/** + * Ensures a repo doesn't already exist and then creates one using the + * provided app. + * + * @param repoInfo - The metadata about the Repo + * @returns The Repo object for the specified server / repoName. + */ +function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) { + let appRepos = repos[app.name]; + if (!appRepos) { + appRepos = {}; + repos[app.name] = appRepos; + } + let repo = appRepos[repoInfo.toURLString()]; + if (repo) { + fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.'); + } + repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider); + appRepos[repoInfo.toURLString()] = repo; + return repo; +} +/** + * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos. + */ +function repoManagerForceRestClient(forceRestClient) { + useRestClient = forceRestClient; +} +/** + * Class representing a Firebase Realtime Database. + */ +class Database { + /** @hideconstructor */ + constructor(_repoInternal, + /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */ + app) { + this._repoInternal = _repoInternal; + this.app = app; + /** Represents a `Database` instance. */ + this['type'] = 'database'; + /** Track if the instance has been used (root or repo accessed) */ + this._instanceStarted = false; + } + get _repo() { + if (!this._instanceStarted) { + repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']); + this._instanceStarted = true; + } + return this._repoInternal; + } + get _root() { + if (!this._rootInternal) { + this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath()); + } + return this._rootInternal; + } + _delete() { + if (this._rootInternal !== null) { + repoManagerDeleteRepo(this._repo, this.app.name); + this._repoInternal = null; + this._rootInternal = null; + } + return Promise.resolve(); + } + _checkNotDeleted(apiName) { + if (this._rootInternal === null) { + fatal('Cannot call ' + apiName + ' on a deleted database.'); + } + } +} +function checkTransportInit() { + if (TransportManager.IS_TRANSPORT_INITIALIZED) { + warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener'); + } +} +/** + * Force the use of websockets instead of longPolling. + */ +function forceWebSockets() { + checkTransportInit(); + BrowserPollConnection.forceDisallow(); +} +/** + * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL. + */ +function forceLongPolling() { + checkTransportInit(); + WebSocketConnection.forceDisallow(); + BrowserPollConnection.forceAllow(); +} +/** + * Modify the provided instance to communicate with the Realtime Database + * emulator. + * + *

Note: This method must be called before performing any other operation. + * + * @param db - The instance to modify. + * @param host - The emulator host (ex: localhost) + * @param port - The emulator port (ex: 8080) + * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules + */ +function connectDatabaseEmulator(db, host, port, options = {}) { + db = util.getModularInstance(db); + db._checkNotDeleted('useEmulator'); + const hostAndPort = `${host}:${port}`; + const repo = db._repoInternal; + if (db._instanceStarted) { + // If the instance has already been started, then silenty fail if this function is called again + // with the same parameters. If the parameters differ then assert. + if (hostAndPort === db._repoInternal.repoInfo_.host && + util.deepEqual(options, repo.repoInfo_.emulatorOptions)) { + return; + } + fatal('connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.'); + } + let tokenProvider = undefined; + if (repo.repoInfo_.nodeAdmin) { + if (options.mockUserToken) { + fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'); + } + tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER); + } + else if (options.mockUserToken) { + const token = typeof options.mockUserToken === 'string' + ? options.mockUserToken + : util.createMockUserToken(options.mockUserToken, db.app.options.projectId); + tokenProvider = new EmulatorTokenProvider(token); + } + // Workaround to get cookies in Firebase Studio + if (util.isCloudWorkstation(host)) { + void util.pingServer(host); + util.updateEmulatorBanner('Database', true); + } + // Modify the repo to apply emulator settings + repoManagerApplyEmulatorSettings(repo, hostAndPort, options, tokenProvider); +} +/** + * Disconnects from the server (all Database operations will be completed + * offline). + * + * The client automatically maintains a persistent connection to the Database + * server, which will remain active indefinitely and reconnect when + * disconnected. However, the `goOffline()` and `goOnline()` methods may be used + * to control the client connection in cases where a persistent connection is + * undesirable. + * + * While offline, the client will no longer receive data updates from the + * Database. However, all Database operations performed locally will continue to + * immediately fire events, allowing your application to continue behaving + * normally. Additionally, each operation performed locally will automatically + * be queued and retried upon reconnection to the Database server. + * + * To reconnect to the Database and begin receiving remote events, see + * `goOnline()`. + * + * @param db - The instance to disconnect. + */ +function goOffline(db) { + db = util.getModularInstance(db); + db._checkNotDeleted('goOffline'); + repoInterrupt(db._repo); +} +/** + * Reconnects to the server and synchronizes the offline Database state + * with the server state. + * + * This method should be used after disabling the active connection with + * `goOffline()`. Once reconnected, the client will transmit the proper data + * and fire the appropriate events so that your client "catches up" + * automatically. + * + * @param db - The instance to reconnect. + */ +function goOnline(db) { + db = util.getModularInstance(db); + db._checkNotDeleted('goOnline'); + repoResume(db._repo); +} +function enableLogging(logger, persistent) { + enableLogging$1(logger, persistent); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const SERVER_TIMESTAMP = { + '.sv': 'timestamp' +}; +/** + * Returns a placeholder value for auto-populating the current timestamp (time + * since the Unix epoch, in milliseconds) as determined by the Firebase + * servers. + */ +function serverTimestamp() { + return SERVER_TIMESTAMP; +} +/** + * Returns a placeholder value that can be used to atomically increment the + * current database value by the provided delta. + * + * @param delta - the amount to modify the current value atomically. + * @returns A placeholder value for modifying data atomically server-side. + */ +function increment(delta) { + return { + '.sv': { + 'increment': delta + } + }; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A type for the resolve value of {@link runTransaction}. + */ +class TransactionResult { + /** @hideconstructor */ + constructor( + /** Whether the transaction was successfully committed. */ + committed, + /** The resulting data snapshot. */ + snapshot) { + this.committed = committed; + this.snapshot = snapshot; + } + /** Returns a JSON-serializable representation of this object. */ + toJSON() { + return { committed: this.committed, snapshot: this.snapshot.toJSON() }; + } +} +/** + * Atomically modifies the data at this location. + * + * Atomically modify the data at this location. Unlike a normal `set()`, which + * just overwrites the data regardless of its previous value, `runTransaction()` is + * used to modify the existing value to a new value, ensuring there are no + * conflicts with other clients writing to the same location at the same time. + * + * To accomplish this, you pass `runTransaction()` an update function which is + * used to transform the current value into a new value. If another client + * writes to the location before your new value is successfully written, your + * update function will be called again with the new current value, and the + * write will be retried. This will happen repeatedly until your write succeeds + * without conflict or you abort the transaction by not returning a value from + * your update function. + * + * Note: Modifying data with `set()` will cancel any pending transactions at + * that location, so extreme care should be taken if mixing `set()` and + * `runTransaction()` to update the same data. + * + * Note: When using transactions with Security and Firebase Rules in place, be + * aware that a client needs `.read` access in addition to `.write` access in + * order to perform a transaction. This is because the client-side nature of + * transactions requires the client to read the data in order to transactionally + * update it. + * + * @param ref - The location to atomically modify. + * @param transactionUpdate - A developer-supplied function which will be passed + * the current data stored at this location (as a JavaScript object). The + * function should return the new value it would like written (as a JavaScript + * object). If `undefined` is returned (i.e. you return with no arguments) the + * transaction will be aborted and the data at this location will not be + * modified. + * @param options - An options object to configure transactions. + * @returns A `Promise` that can optionally be used instead of the `onComplete` + * callback to handle success and failure. + */ +function runTransaction(ref, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +transactionUpdate, options) { + ref = util.getModularInstance(ref); + validateWritablePath('Reference.transaction', ref._path); + if (ref.key === '.length' || ref.key === '.keys') { + throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.'); + } + const applyLocally = options?.applyLocally ?? true; + const deferred = new util.Deferred(); + const promiseComplete = (error, committed, node) => { + let dataSnapshot = null; + if (error) { + deferred.reject(error); + } + else { + dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX); + deferred.resolve(new TransactionResult(committed, dataSnapshot)); + } + }; + // Add a watch to make sure we get server updates. + const unwatcher = onValue(ref, () => { }); + repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally); + return deferred.promise; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +PersistentConnection; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +PersistentConnection.prototype.simpleListen = function (pathString, onComplete) { + this.sendRequest('q', { p: pathString }, onComplete); +}; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +PersistentConnection.prototype.echo = function (data, onEcho) { + this.sendRequest('echo', { d: data }, onEcho); +}; +// RealTimeConnection properties that we use in tests. +Connection; +/** + * @internal + */ +const hijackHash = function (newHash) { + const oldPut = PersistentConnection.prototype.put; + PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) { + if (hash !== undefined) { + hash = newHash(); + } + oldPut.call(this, pathString, data, onComplete, hash); + }; + return function () { + PersistentConnection.prototype.put = oldPut; + }; +}; +RepoInfo; +/** + * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection. + * @internal + */ +const forceRestClient = function (forceRestClient) { + repoManagerForceRestClient(forceRestClient); +}; + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Used by console to create a database based on the app, + * passed database URL and a custom auth implementation. + * @internal + * @param app - A valid FirebaseApp-like object + * @param url - A valid Firebase databaseURL + * @param version - custom version e.g. firebase-admin version + * @param customAppCheckImpl - custom app check implementation + * @param customAuthImpl - custom auth implementation + */ +function _initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, nodeAdmin = false }) { + setSDKVersion(version); + /** + * ComponentContainer('database-standalone') is just a placeholder that doesn't perform + * any actual function. + */ + const componentContainer = new component.ComponentContainer('database-standalone'); + const authProvider = new component.Provider('auth-internal', componentContainer); + let appCheckProvider; + if (customAppCheckImpl) { + appCheckProvider = new component.Provider('app-check-internal', componentContainer); + appCheckProvider.setComponent(new component.Component('app-check-internal', () => customAppCheckImpl, "PRIVATE" /* ComponentType.PRIVATE */)); + } + authProvider.setComponent(new component.Component('auth-internal', () => customAuthImpl, "PRIVATE" /* ComponentType.PRIVATE */)); + return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin); +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +setWebSocketImpl(Websocket__default["default"].Client); + +exports.DataSnapshot = DataSnapshot; +exports.Database = Database; +exports.OnDisconnect = OnDisconnect; +exports.QueryConstraint = QueryConstraint; +exports.TransactionResult = TransactionResult; +exports._QueryImpl = QueryImpl; +exports._QueryParams = QueryParams; +exports._ReferenceImpl = ReferenceImpl; +exports._TEST_ACCESS_forceRestClient = forceRestClient; +exports._TEST_ACCESS_hijackHash = hijackHash; +exports._initStandalone = _initStandalone; +exports._repoManagerDatabaseFromApp = repoManagerDatabaseFromApp; +exports._setSDKVersion = setSDKVersion; +exports._validatePathString = validatePathString; +exports._validateWritablePath = validateWritablePath; +exports.child = child; +exports.connectDatabaseEmulator = connectDatabaseEmulator; +exports.enableLogging = enableLogging; +exports.endAt = endAt; +exports.endBefore = endBefore; +exports.equalTo = equalTo; +exports.forceLongPolling = forceLongPolling; +exports.forceWebSockets = forceWebSockets; +exports.get = get; +exports.goOffline = goOffline; +exports.goOnline = goOnline; +exports.increment = increment; +exports.limitToFirst = limitToFirst; +exports.limitToLast = limitToLast; +exports.off = off; +exports.onChildAdded = onChildAdded; +exports.onChildChanged = onChildChanged; +exports.onChildMoved = onChildMoved; +exports.onChildRemoved = onChildRemoved; +exports.onDisconnect = onDisconnect; +exports.onValue = onValue; +exports.orderByChild = orderByChild; +exports.orderByKey = orderByKey; +exports.orderByPriority = orderByPriority; +exports.orderByValue = orderByValue; +exports.push = push; +exports.query = query; +exports.ref = ref; +exports.refFromURL = refFromURL; +exports.remove = remove; +exports.runTransaction = runTransaction; +exports.serverTimestamp = serverTimestamp; +exports.set = set; +exports.setPriority = setPriority; +exports.setWithPriority = setWithPriority; +exports.startAfter = startAfter; +exports.startAt = startAt; +exports.update = update; +//# sourceMappingURL=index.standalone.js.map diff --git a/node_modules/@firebase/database/dist/index.standalone.js.map b/node_modules/@firebase/database/dist/index.standalone.js.map new file mode 100644 index 0000000..920efc5 --- /dev/null +++ b/node_modules/@firebase/database/dist/index.standalone.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.standalone.js","sources":["../src/realtime/Constants.ts","../src/core/storage/DOMStorageWrapper.ts","../src/core/storage/MemoryStorage.ts","../src/core/storage/storage.ts","../src/core/util/util.ts","../src/core/RepoInfo.ts","../src/core/stats/StatsCollection.ts","../src/core/stats/StatsManager.ts","../src/core/version.ts","../src/realtime/WebSocketConnection.ts","../src/core/AppCheckTokenProvider.ts","../src/core/AuthTokenProvider.ts","../src/realtime/polling/PacketReceiver.ts","../src/realtime/BrowserPollConnection.ts","../src/realtime/TransportManager.ts","../src/realtime/Connection.ts","../src/core/ServerActions.ts","../src/core/util/EventEmitter.ts","../src/core/util/OnlineMonitor.ts","../src/core/util/Path.ts","../src/core/util/VisibilityMonitor.ts","../src/core/PersistentConnection.ts","../src/core/snap/Node.ts","../src/core/snap/indexes/Index.ts","../src/core/snap/indexes/KeyIndex.ts","../src/core/util/SortedMap.ts","../src/core/snap/comparators.ts","../src/core/snap/snap.ts","../src/core/snap/LeafNode.ts","../src/core/snap/indexes/PriorityIndex.ts","../src/core/snap/childSet.ts","../src/core/snap/IndexMap.ts","../src/core/snap/ChildrenNode.ts","../src/core/snap/nodeFromJSON.ts","../src/core/snap/indexes/PathIndex.ts","../src/core/snap/indexes/ValueIndex.ts","../src/core/view/Change.ts","../src/core/view/filter/IndexedFilter.ts","../src/core/view/filter/RangedFilter.ts","../src/core/view/filter/LimitedFilter.ts","../src/core/view/QueryParams.ts","../src/core/ReadonlyRestClient.ts","../src/core/SnapshotHolder.ts","../src/core/SparseSnapshotTree.ts","../src/core/stats/StatsListener.ts","../src/core/stats/StatsReporter.ts","../src/core/operation/Operation.ts","../src/core/operation/AckUserWrite.ts","../src/core/operation/ListenComplete.ts","../src/core/operation/Overwrite.ts","../src/core/operation/Merge.ts","../src/core/view/CacheNode.ts","../src/core/view/EventGenerator.ts","../src/core/view/ViewCache.ts","../src/core/util/ImmutableTree.ts","../src/core/CompoundWrite.ts","../src/core/WriteTree.ts","../src/core/view/ChildChangeAccumulator.ts","../src/core/view/CompleteChildSource.ts","../src/core/view/ViewProcessor.ts","../src/core/view/View.ts","../src/core/SyncPoint.ts","../src/core/SyncTree.ts","../src/core/util/ServerValues.ts","../src/core/util/Tree.ts","../src/core/util/validation.ts","../src/core/view/EventQueue.ts","../src/core/Repo.ts","../src/core/util/libs/parser.ts","../src/core/util/NextPushId.ts","../src/core/view/Event.ts","../src/core/view/EventRegistration.ts","../src/api/OnDisconnect.ts","../src/api/Reference_impl.ts","../src/api/Database.ts","../src/api/ServerValue.ts","../src/api/Transaction.ts","../src/api/test_access.ts","../src/internal/index.ts","../src/index.standalone.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const PROTOCOL_VERSION = '5';\n\nexport const VERSION_PARAM = 'v';\n\nexport const TRANSPORT_SESSION_PARAM = 's';\n\nexport const REFERER_PARAM = 'r';\n\nexport const FORGE_REF = 'f';\n\n// Matches console.firebase.google.com, firebase-console-*.corp.google.com and\n// firebase.corp.google.com\nexport const FORGE_DOMAIN_RE =\n /(console\\.firebase|firebase-console-\\w+\\.corp|firebase\\.corp)\\.google\\.com/;\n\nexport const LAST_SESSION_PARAM = 'ls';\n\nexport const APPLICATION_ID_PARAM = 'p';\n\nexport const APP_CHECK_TOKEN_PARAM = 'ac';\n\nexport const WEBSOCKET = 'websocket';\n\nexport const LONG_POLLING = 'long_polling';\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { jsonEval, stringify } from '@firebase/util';\n\n/**\n * Wraps a DOM Storage object and:\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\n *\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\n * and one for localStorage.\n *\n */\nexport class DOMStorageWrapper {\n // Use a prefix to avoid collisions with other stuff saved by the app.\n private prefix_ = 'firebase:';\n\n /**\n * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)\n */\n constructor(private domStorage_: Storage) {}\n\n /**\n * @param key - The key to save the value under\n * @param value - The value being stored, or null to remove the key.\n */\n set(key: string, value: unknown | null) {\n if (value == null) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n } else {\n this.domStorage_.setItem(this.prefixedName_(key), stringify(value));\n }\n }\n\n /**\n * @returns The value that was stored under this key, or null\n */\n get(key: string): unknown {\n const storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n if (storedVal == null) {\n return null;\n } else {\n return jsonEval(storedVal);\n }\n }\n\n remove(key: string) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n\n isInMemoryStorage: boolean;\n\n prefixedName_(name: string): string {\n return this.prefix_ + name;\n }\n\n toString(): string {\n return this.domStorage_.toString();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains } from '@firebase/util';\n\n/**\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\n * (TODO: create interface for both to implement).\n */\nexport class MemoryStorage {\n private cache_: { [k: string]: unknown } = {};\n\n set(key: string, value: unknown | null) {\n if (value == null) {\n delete this.cache_[key];\n } else {\n this.cache_[key] = value;\n }\n }\n\n get(key: string): unknown {\n if (contains(this.cache_, key)) {\n return this.cache_[key];\n }\n return null;\n }\n\n remove(key: string) {\n delete this.cache_[key];\n }\n\n isInMemoryStorage = true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DOMStorageWrapper } from './DOMStorageWrapper';\nimport { MemoryStorage } from './MemoryStorage';\n\ndeclare const window: Window;\n\n/**\n * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\n * to reflect this type\n *\n * @param domStorageName - Name of the underlying storage object\n * (e.g. 'localStorage' or 'sessionStorage').\n * @returns Turning off type information until a common interface is defined.\n */\nconst createStoragefor = function (\n domStorageName: string\n): DOMStorageWrapper | MemoryStorage {\n try {\n // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\n // so it must be inside the try/catch.\n if (\n typeof window !== 'undefined' &&\n typeof window[domStorageName] !== 'undefined'\n ) {\n // Need to test cache. Just because it's here doesn't mean it works\n const domStorage = window[domStorageName];\n domStorage.setItem('firebase:sentinel', 'cache');\n domStorage.removeItem('firebase:sentinel');\n return new DOMStorageWrapper(domStorage);\n }\n } catch (e) {}\n\n // Failed to create wrapper. Just return in-memory storage.\n // TODO: log?\n return new MemoryStorage();\n};\n\n/** A storage object that lasts across sessions */\nexport const PersistentStorage = createStoragefor('localStorage');\n\n/** A storage object that only lasts one session */\nexport const SessionStorage = createStoragefor('sessionStorage');\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel } from '@firebase/logger';\nimport {\n assert,\n base64,\n Sha1,\n stringToByteArray,\n stringify,\n isNodeSdk\n} from '@firebase/util';\n\nimport { SessionStorage } from '../storage/storage';\nimport { QueryContext } from '../view/EventRegistration';\n\ndeclare const window: Window;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ndeclare const Windows: any;\n\nconst logClient = new Logger('@firebase/database');\n\n/**\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\n */\nexport const LUIDGenerator: () => number = (function () {\n let id = 1;\n return function () {\n return id++;\n };\n})();\n\n/**\n * Sha1 hash of the input string\n * @param str - The string to hash\n * @returns {!string} The resulting hash\n */\nexport const sha1 = function (str: string): string {\n const utf8Bytes = stringToByteArray(str);\n const sha1 = new Sha1();\n sha1.update(utf8Bytes);\n const sha1Bytes = sha1.digest();\n return base64.encodeByteArray(sha1Bytes);\n};\n\nconst buildLogMessage_ = function (...varArgs: unknown[]): string {\n let message = '';\n for (let i = 0; i < varArgs.length; i++) {\n const arg = varArgs[i];\n if (\n Array.isArray(arg) ||\n (arg &&\n typeof arg === 'object' &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (arg as any).length === 'number')\n ) {\n message += buildLogMessage_.apply(null, arg);\n } else if (typeof arg === 'object') {\n message += stringify(arg);\n } else {\n message += arg;\n }\n message += ' ';\n }\n\n return message;\n};\n\n/**\n * Use this for all debug messages in Firebase.\n */\nexport let logger: ((a: string) => void) | null = null;\n\n/**\n * Flag to check for log availability on first log message\n */\nlet firstLog_ = true;\n\n/**\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\n * @param logger_ - A flag to turn on logging, or a custom logger\n * @param persistent - Whether or not to persist logging settings across refreshes\n */\nexport const enableLogging = function (\n logger_?: boolean | ((a: string) => void) | null,\n persistent?: boolean\n) {\n assert(\n !persistent || logger_ === true || logger_ === false,\n \"Can't turn on custom loggers persistently.\"\n );\n if (logger_ === true) {\n logClient.logLevel = LogLevel.VERBOSE;\n logger = logClient.log.bind(logClient);\n if (persistent) {\n SessionStorage.set('logging_enabled', true);\n }\n } else if (typeof logger_ === 'function') {\n logger = logger_;\n } else {\n logger = null;\n SessionStorage.remove('logging_enabled');\n }\n};\n\nexport const log = function (...varArgs: unknown[]) {\n if (firstLog_ === true) {\n firstLog_ = false;\n if (logger === null && SessionStorage.get('logging_enabled') === true) {\n enableLogging(true);\n }\n }\n\n if (logger) {\n const message = buildLogMessage_.apply(null, varArgs);\n logger(message);\n }\n};\n\nexport const logWrapper = function (\n prefix: string\n): (...varArgs: unknown[]) => void {\n return function (...varArgs: unknown[]) {\n log(prefix, ...varArgs);\n };\n};\n\nexport const error = function (...varArgs: string[]) {\n const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);\n logClient.error(message);\n};\n\nexport const fatal = function (...varArgs: string[]) {\n const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;\n logClient.error(message);\n throw new Error(message);\n};\n\nexport const warn = function (...varArgs: unknown[]) {\n const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);\n logClient.warn(message);\n};\n\n/**\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\n * does not use https.\n */\nexport const warnIfPageIsSecure = function () {\n // Be very careful accessing browser globals. Who knows what may or may not exist.\n if (\n typeof window !== 'undefined' &&\n window.location &&\n window.location.protocol &&\n window.location.protocol.indexOf('https:') !== -1\n ) {\n warn(\n 'Insecure Firebase access from a secure page. ' +\n 'Please use https in calls to new Firebase().'\n );\n }\n};\n\nexport const warnAboutUnsupportedMethod = function (methodName: string) {\n warn(\n methodName +\n ' is unsupported and will likely change soon. ' +\n 'Please do not use.'\n );\n};\n\n/**\n * Returns true if data is NaN, or +/- Infinity.\n */\nexport const isInvalidJSONNumber = function (data: unknown): boolean {\n return (\n typeof data === 'number' &&\n (data !== data || // NaN\n data === Number.POSITIVE_INFINITY ||\n data === Number.NEGATIVE_INFINITY)\n );\n};\n\nexport const executeWhenDOMReady = function (fn: () => void) {\n if (isNodeSdk() || document.readyState === 'complete') {\n fn();\n } else {\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\n // fire before onload), but fall back to onload.\n\n let called = false;\n const wrappedFn = function () {\n if (!document.body) {\n setTimeout(wrappedFn, Math.floor(10));\n return;\n }\n\n if (!called) {\n called = true;\n fn();\n }\n };\n\n if (document.addEventListener) {\n document.addEventListener('DOMContentLoaded', wrappedFn, false);\n // fallback to onload.\n window.addEventListener('load', wrappedFn, false);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else if ((document as any).attachEvent) {\n // IE.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (document as any).attachEvent('onreadystatechange', () => {\n if (document.readyState === 'complete') {\n wrappedFn();\n }\n });\n // fallback to onload.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (window as any).attachEvent('onload', wrappedFn);\n\n // jQuery has an extra hack for IE that we could employ (based on\n // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\n // I'm hoping we don't need it.\n }\n }\n};\n\n/**\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\n */\nexport const MIN_NAME = '[MIN_NAME]';\n\n/**\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\n */\nexport const MAX_NAME = '[MAX_NAME]';\n\n/**\n * Compares valid Firebase key names, plus min and max name\n */\nexport const nameCompare = function (a: string, b: string): number {\n if (a === b) {\n return 0;\n } else if (a === MIN_NAME || b === MAX_NAME) {\n return -1;\n } else if (b === MIN_NAME || a === MAX_NAME) {\n return 1;\n } else {\n const aAsInt = tryParseInt(a),\n bAsInt = tryParseInt(b);\n\n if (aAsInt !== null) {\n if (bAsInt !== null) {\n return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;\n } else {\n return -1;\n }\n } else if (bAsInt !== null) {\n return 1;\n } else {\n return a < b ? -1 : 1;\n }\n }\n};\n\n/**\n * @returns {!number} comparison result.\n */\nexport const stringCompare = function (a: string, b: string): number {\n if (a === b) {\n return 0;\n } else if (a < b) {\n return -1;\n } else {\n return 1;\n }\n};\n\nexport const requireKey = function (\n key: string,\n obj: { [k: string]: unknown }\n): unknown {\n if (obj && key in obj) {\n return obj[key];\n } else {\n throw new Error(\n 'Missing required key (' + key + ') in object: ' + stringify(obj)\n );\n }\n};\n\nexport const ObjectToUniqueKey = function (obj: unknown): string {\n if (typeof obj !== 'object' || obj === null) {\n return stringify(obj);\n }\n\n const keys = [];\n // eslint-disable-next-line guard-for-in\n for (const k in obj) {\n keys.push(k);\n }\n\n // Export as json, but with the keys sorted.\n keys.sort();\n let key = '{';\n for (let i = 0; i < keys.length; i++) {\n if (i !== 0) {\n key += ',';\n }\n key += stringify(keys[i]);\n key += ':';\n key += ObjectToUniqueKey(obj[keys[i]]);\n }\n\n key += '}';\n return key;\n};\n\n/**\n * Splits a string into a number of smaller segments of maximum size\n * @param str - The string\n * @param segsize - The maximum number of chars in the string.\n * @returns The string, split into appropriately-sized chunks\n */\nexport const splitStringBySize = function (\n str: string,\n segsize: number\n): string[] {\n const len = str.length;\n\n if (len <= segsize) {\n return [str];\n }\n\n const dataSegs = [];\n for (let c = 0; c < len; c += segsize) {\n if (c + segsize > len) {\n dataSegs.push(str.substring(c, len));\n } else {\n dataSegs.push(str.substring(c, c + segsize));\n }\n }\n return dataSegs;\n};\n\n/**\n * Apply a function to each (key, value) pair in an object or\n * apply a function to each (index, value) pair in an array\n * @param obj - The object or array to iterate over\n * @param fn - The function to apply\n */\nexport function each(obj: object, fn: (k: string, v: unknown) => void) {\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n fn(key, obj[key]);\n }\n }\n}\n\n/**\n * Like goog.bind, but doesn't bother to create a closure if opt_context is null/undefined.\n * @param callback - Callback function.\n * @param context - Optional context to bind to.\n *\n */\nexport const bindCallback = function (\n callback: (a: unknown) => void,\n context?: object | null\n): (a: unknown) => void {\n return context ? callback.bind(context) : callback;\n};\n\n/**\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\n * I made one modification at the end and removed the NaN / Infinity\n * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.\n * @param v - A double\n *\n */\nexport const doubleToIEEE754String = function (v: number): string {\n assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\n\n const ebits = 11,\n fbits = 52;\n const bias = (1 << (ebits - 1)) - 1;\n let s, e, f, ln, i;\n\n // Compute sign, exponent, fraction\n // Skip NaN / Infinity handling --MJL.\n if (v === 0) {\n e = 0;\n f = 0;\n s = 1 / v === -Infinity ? 1 : 0;\n } else {\n s = v < 0;\n v = Math.abs(v);\n\n if (v >= Math.pow(2, 1 - bias)) {\n // Normalized\n ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\n e = ln + bias;\n f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\n } else {\n // Denormalized\n e = 0;\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\n }\n }\n\n // Pack sign, exponent, fraction\n const bits = [];\n for (i = fbits; i; i -= 1) {\n bits.push(f % 2 ? 1 : 0);\n f = Math.floor(f / 2);\n }\n for (i = ebits; i; i -= 1) {\n bits.push(e % 2 ? 1 : 0);\n e = Math.floor(e / 2);\n }\n bits.push(s ? 1 : 0);\n bits.reverse();\n const str = bits.join('');\n\n // Return the data as a hex string. --MJL\n let hexByteString = '';\n for (i = 0; i < 64; i += 8) {\n let hexByte = parseInt(str.substr(i, 8), 2).toString(16);\n if (hexByte.length === 1) {\n hexByte = '0' + hexByte;\n }\n hexByteString = hexByteString + hexByte;\n }\n return hexByteString.toLowerCase();\n};\n\n/**\n * Used to detect if we're in a Chrome content script (which executes in an\n * isolated environment where long-polling doesn't work).\n */\nexport const isChromeExtensionContentScript = function (): boolean {\n return !!(\n typeof window === 'object' &&\n window['chrome'] &&\n window['chrome']['extension'] &&\n !/^chrome/.test(window.location.href)\n );\n};\n\n/**\n * Used to detect if we're in a Windows 8 Store app.\n */\nexport const isWindowsStoreApp = function (): boolean {\n // Check for the presence of a couple WinRT globals\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\n};\n\n/**\n * Converts a server error code to a JavaScript Error\n */\nexport function errorForServerCode(code: string, query: QueryContext): Error {\n let reason = 'Unknown Error';\n if (code === 'too_big') {\n reason =\n 'The data requested exceeds the maximum size ' +\n 'that can be accessed with a single request.';\n } else if (code === 'permission_denied') {\n reason = \"Client doesn't have permission to access the desired data.\";\n } else if (code === 'unavailable') {\n reason = 'The service is unavailable';\n }\n\n const error = new Error(\n code + ' at ' + query._path.toString() + ': ' + reason\n );\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (error as any).code = code.toUpperCase();\n return error;\n}\n\n/**\n * Used to test for integer-looking strings\n */\nexport const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\\\d{1,10}$');\n\n/**\n * For use in keys, the minimum possible 32-bit integer.\n */\nexport const INTEGER_32_MIN = -2147483648;\n\n/**\n * For use in keys, the maximum possible 32-bit integer.\n */\nexport const INTEGER_32_MAX = 2147483647;\n\n/**\n * If the string contains a 32-bit integer, return it. Else return null.\n */\nexport const tryParseInt = function (str: string): number | null {\n if (INTEGER_REGEXP_.test(str)) {\n const intVal = Number(str);\n if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {\n return intVal;\n }\n }\n return null;\n};\n\n/**\n * Helper to run some code but catch any exceptions and re-throw them later.\n * Useful for preventing user callbacks from breaking internal code.\n *\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\n * convenient (we don't have to try to figure out when is a safe point to\n * re-throw it), and the behavior seems reasonable:\n *\n * * If you aren't pausing on exceptions, you get an error in the console with\n * the correct stack trace.\n * * If you're pausing on all exceptions, the debugger will pause on your\n * exception and then again when we rethrow it.\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\n * on us re-throwing it.\n *\n * @param fn - The code to guard.\n */\nexport const exceptionGuard = function (fn: () => void) {\n try {\n fn();\n } catch (e) {\n // Re-throw exception when it's safe.\n setTimeout(() => {\n // It used to be that \"throw e\" would result in a good console error with\n // relevant context, but as of Chrome 39, you just get the firebase.js\n // file/line number where we re-throw it, which is useless. So we log\n // e.stack explicitly.\n const stack = e.stack || '';\n warn('Exception was thrown by user callback.', stack);\n throw e;\n }, Math.floor(0));\n }\n};\n\n/**\n * Helper function to safely call opt_callback with the specified arguments. It:\n * 1. Turns into a no-op if opt_callback is null or undefined.\n * 2. Wraps the call inside exceptionGuard to prevent exceptions from breaking our state.\n *\n * @param callback - Optional onComplete callback.\n * @param varArgs - Arbitrary args to be passed to opt_onComplete\n */\nexport const callUserCallback = function (\n // eslint-disable-next-line @typescript-eslint/ban-types\n callback?: Function | null,\n ...varArgs: unknown[]\n) {\n if (typeof callback === 'function') {\n exceptionGuard(() => {\n callback(...varArgs);\n });\n }\n};\n\n/**\n * @returns {boolean} true if we think we're currently being crawled.\n */\nexport const beingCrawled = function (): boolean {\n const userAgent =\n (typeof window === 'object' &&\n window['navigator'] &&\n window['navigator']['userAgent']) ||\n '';\n\n // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we\n // believe to support JavaScript/AJAX rendering.\n // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\n // would have seen the page\" is flaky if we don't treat it as a crawler.\n return (\n userAgent.search(\n /googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i\n ) >= 0\n );\n};\n\n/**\n * Export a property of an object using a getter function.\n */\nexport const exportPropGetter = function (\n object: object,\n name: string,\n fnGet: () => unknown\n) {\n Object.defineProperty(object, name, { get: fnGet });\n};\n\n/**\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\n *\n * It is removed with clearTimeout() as normal.\n *\n * @param fn - Function to run.\n * @param time - Milliseconds to wait before running.\n * @returns The setTimeout() return value.\n */\nexport const setTimeoutNonBlocking = function (\n fn: () => void,\n time: number\n): number | object {\n const timeout: number | object = setTimeout(fn, time);\n // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.\n if (\n typeof timeout === 'number' &&\n // @ts-ignore Is only defined in Deno environments.\n typeof Deno !== 'undefined' &&\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\n Deno['unrefTimer']\n ) {\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\n Deno.unrefTimer(timeout);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else if (typeof timeout === 'object' && (timeout as any)['unref']) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (timeout as any)['unref']();\n }\n\n return timeout;\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, EmulatorMockTokenOptions } from '@firebase/util';\n\nimport { LONG_POLLING, WEBSOCKET } from '../realtime/Constants';\n\nimport { PersistentStorage } from './storage/storage';\nimport { each } from './util/util';\n\nexport interface RepoInfoEmulatorOptions {\n mockUserToken?: string | EmulatorMockTokenOptions;\n}\n\n/**\n * A class that holds metadata about a Repo object\n */\nexport class RepoInfo {\n private _host: string;\n private _domain: string;\n internalHost: string;\n\n /**\n * @param host - Hostname portion of the url for the repo\n * @param secure - Whether or not this repo is accessed over ssl\n * @param namespace - The namespace represented by the repo\n * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).\n * @param nodeAdmin - Whether this instance uses Admin SDK credentials\n * @param persistenceKey - Override the default session persistence storage key\n */\n constructor(\n host: string,\n public readonly secure: boolean,\n public readonly namespace: string,\n public readonly webSocketOnly: boolean,\n public readonly nodeAdmin: boolean = false,\n public readonly persistenceKey: string = '',\n public readonly includeNamespaceInQueryParams: boolean = false,\n public readonly isUsingEmulator: boolean = false,\n public readonly emulatorOptions: RepoInfoEmulatorOptions | null = null\n ) {\n this._host = host.toLowerCase();\n this._domain = this._host.substr(this._host.indexOf('.') + 1);\n this.internalHost =\n (PersistentStorage.get('host:' + host) as string) || this._host;\n }\n\n isCacheableHost(): boolean {\n return this.internalHost.substr(0, 2) === 's-';\n }\n\n isCustomHost() {\n return (\n this._domain !== 'firebaseio.com' &&\n this._domain !== 'firebaseio-demo.com'\n );\n }\n\n get host() {\n return this._host;\n }\n\n set host(newHost: string) {\n if (newHost !== this.internalHost) {\n this.internalHost = newHost;\n if (this.isCacheableHost()) {\n PersistentStorage.set('host:' + this._host, this.internalHost);\n }\n }\n }\n\n toString(): string {\n let str = this.toURLString();\n if (this.persistenceKey) {\n str += '<' + this.persistenceKey + '>';\n }\n return str;\n }\n\n toURLString(): string {\n const protocol = this.secure ? 'https://' : 'http://';\n const query = this.includeNamespaceInQueryParams\n ? `?ns=${this.namespace}`\n : '';\n return `${protocol}${this.host}/${query}`;\n }\n}\n\nfunction repoInfoNeedsQueryParam(repoInfo: RepoInfo): boolean {\n return (\n repoInfo.host !== repoInfo.internalHost ||\n repoInfo.isCustomHost() ||\n repoInfo.includeNamespaceInQueryParams\n );\n}\n\n/**\n * Returns the websocket URL for this repo\n * @param repoInfo - RepoInfo object\n * @param type - of connection\n * @param params - list\n * @returns The URL for this repo\n */\nexport function repoInfoConnectionURL(\n repoInfo: RepoInfo,\n type: string,\n params: { [k: string]: string }\n): string {\n assert(typeof type === 'string', 'typeof type must == string');\n assert(typeof params === 'object', 'typeof params must == object');\n\n let connURL: string;\n if (type === WEBSOCKET) {\n connURL =\n (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';\n } else if (type === LONG_POLLING) {\n connURL =\n (repoInfo.secure ? 'https://' : 'http://') +\n repoInfo.internalHost +\n '/.lp?';\n } else {\n throw new Error('Unknown connection type: ' + type);\n }\n if (repoInfoNeedsQueryParam(repoInfo)) {\n params['ns'] = repoInfo.namespace;\n }\n\n const pairs: string[] = [];\n\n each(params, (key: string, value: string) => {\n pairs.push(key + '=' + value);\n });\n\n return connURL + pairs.join('&');\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { deepCopy, contains } from '@firebase/util';\n\n/**\n * Tracks a collection of stats.\n */\nexport class StatsCollection {\n private counters_: { [k: string]: number } = {};\n\n incrementCounter(name: string, amount: number = 1) {\n if (!contains(this.counters_, name)) {\n this.counters_[name] = 0;\n }\n\n this.counters_[name] += amount;\n }\n\n get() {\n return deepCopy(this.counters_);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../RepoInfo';\n\nimport { StatsCollection } from './StatsCollection';\n\nconst collections: { [k: string]: StatsCollection } = {};\nconst reporters: { [k: string]: unknown } = {};\n\nexport function statsManagerGetCollection(repoInfo: RepoInfo): StatsCollection {\n const hashString = repoInfo.toString();\n\n if (!collections[hashString]) {\n collections[hashString] = new StatsCollection();\n }\n\n return collections[hashString];\n}\n\nexport function statsManagerGetOrCreateReporter(\n repoInfo: RepoInfo,\n creatorFunction: () => T\n): T {\n const hashString = repoInfo.toString();\n\n if (!reporters[hashString]) {\n reporters[hashString] = creatorFunction();\n }\n\n return reporters[hashString] as T;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nexport let SDK_VERSION = '';\n\n/**\n * SDK_VERSION should be set before any database instance is created\n * @internal\n */\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, isNodeSdk, jsonEval, stringify } from '@firebase/util';\n\nimport { RepoInfo, repoInfoConnectionURL } from '../core/RepoInfo';\nimport { StatsCollection } from '../core/stats/StatsCollection';\nimport { statsManagerGetCollection } from '../core/stats/StatsManager';\nimport { PersistentStorage } from '../core/storage/storage';\nimport { logWrapper, splitStringBySize } from '../core/util/util';\nimport { SDK_VERSION } from '../core/version';\n\nimport {\n APPLICATION_ID_PARAM,\n APP_CHECK_TOKEN_PARAM,\n FORGE_DOMAIN_RE,\n FORGE_REF,\n LAST_SESSION_PARAM,\n PROTOCOL_VERSION,\n REFERER_PARAM,\n TRANSPORT_SESSION_PARAM,\n VERSION_PARAM,\n WEBSOCKET\n} from './Constants';\nimport { Transport } from './Transport';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ndeclare const MozWebSocket: any;\n\nconst WEBSOCKET_MAX_FRAME_SIZE = 16384;\nconst WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\n\nlet WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n} else if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\n\nexport function setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\n\n/**\n * Create a new websocket connection with the given callbacks.\n */\nexport class WebSocketConnection implements Transport {\n keepaliveTimer: number | null = null;\n frames: string[] | null = null;\n totalFrames = 0;\n bytesSent = 0;\n bytesReceived = 0;\n connURL: string;\n onDisconnect: (a?: boolean) => void;\n onMessage: (msg: {}) => void;\n mySock: WebSocket | null;\n private log_: (...a: unknown[]) => void;\n private stats_: StatsCollection;\n private everConnected_: boolean;\n private isClosed_: boolean;\n private nodeAdmin: boolean;\n\n /**\n * @param connId identifier for this transport\n * @param repoInfo The info for the websocket endpoint.\n * @param applicationId The Firebase App ID for this project.\n * @param appCheckToken The App Check Token for this client.\n * @param authToken The Auth Token for this client.\n * @param transportSessionId Optional transportSessionId if this is connecting\n * to an existing transport session\n * @param lastSessionId Optional lastSessionId if there was a previous\n * connection\n */\n constructor(\n public connId: string,\n repoInfo: RepoInfo,\n private applicationId?: string,\n private appCheckToken?: string,\n private authToken?: string,\n transportSessionId?: string,\n lastSessionId?: string\n ) {\n this.log_ = logWrapper(this.connId);\n this.stats_ = statsManagerGetCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(\n repoInfo,\n transportSessionId,\n lastSessionId,\n appCheckToken,\n applicationId\n );\n this.nodeAdmin = repoInfo.nodeAdmin;\n }\n\n /**\n * @param repoInfo - The info for the websocket endpoint.\n * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param lastSessionId - Optional lastSessionId if there was a previous connection\n * @returns connection url\n */\n private static connectionURL_(\n repoInfo: RepoInfo,\n transportSessionId?: string,\n lastSessionId?: string,\n appCheckToken?: string,\n applicationId?: string\n ): string {\n const urlParams: { [k: string]: string } = {};\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\n\n if (\n !isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.hostname &&\n FORGE_DOMAIN_RE.test(location.hostname)\n ) {\n urlParams[REFERER_PARAM] = FORGE_REF;\n }\n if (transportSessionId) {\n urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[LAST_SESSION_PARAM] = lastSessionId;\n }\n if (appCheckToken) {\n urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;\n }\n if (applicationId) {\n urlParams[APPLICATION_ID_PARAM] = applicationId;\n }\n\n return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);\n }\n\n /**\n * @param onMessage - Callback when messages arrive\n * @param onDisconnect - Callback with connection lost.\n */\n open(onMessage: (msg: {}) => void, onDisconnect: (a?: boolean) => void) {\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n\n this.log_('Websocket connecting to ' + this.connURL);\n\n this.everConnected_ = false;\n // Assume failure until proven otherwise.\n PersistentStorage.set('previous_websocket_failure', true);\n\n try {\n let options: { [k: string]: object };\n if (isNodeSdk()) {\n const device = this.nodeAdmin ? 'AdminNode' : 'Node';\n // UA Format: Firebase////\n options = {\n headers: {\n 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,\n 'X-Firebase-GMPID': this.applicationId || ''\n }\n };\n\n // If using Node with admin creds, AppCheck-related checks are unnecessary.\n // Note that we send the credentials here even if they aren't admin credentials, which is\n // not a problem.\n // Note that this header is just used to bypass appcheck, and the token should still be sent\n // through the websocket connection once it is established.\n if (this.authToken) {\n options.headers['Authorization'] = `Bearer ${this.authToken}`;\n }\n if (this.appCheckToken) {\n options.headers['X-Firebase-AppCheck'] = this.appCheckToken;\n }\n\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n const env = process['env'];\n const proxy =\n this.connURL.indexOf('wss://') === 0\n ? env['HTTPS_PROXY'] || env['https_proxy']\n : env['HTTP_PROXY'] || env['http_proxy'];\n\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n }\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n } catch (e) {\n this.log_('Error instantiating WebSocket.');\n const error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n return;\n }\n\n this.mySock.onopen = () => {\n this.log_('Websocket connected.');\n this.everConnected_ = true;\n };\n\n this.mySock.onclose = () => {\n this.log_('Websocket connection was disconnected.');\n this.mySock = null;\n this.onClosed_();\n };\n\n this.mySock.onmessage = m => {\n this.handleIncomingFrame(m as {});\n };\n\n this.mySock.onerror = e => {\n this.log_('WebSocket error. Closing connection.');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const error = (e as any).message || (e as any).data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n };\n }\n\n /**\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n */\n start() {}\n\n static forceDisallow_: boolean;\n\n static forceDisallow() {\n WebSocketConnection.forceDisallow_ = true;\n }\n\n static isAvailable(): boolean {\n let isOldAndroid = false;\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n const oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n isOldAndroid = true;\n }\n }\n }\n\n return (\n !isOldAndroid &&\n WebSocketImpl !== null &&\n !WebSocketConnection.forceDisallow_\n );\n }\n\n /**\n * Number of response before we consider the connection \"healthy.\"\n */\n static responsesRequiredToBeHealthy = 2;\n\n /**\n * Time to wait for the connection te become healthy before giving up.\n */\n static healthyTimeout = 30000;\n\n /**\n * Returns true if we previously failed to connect with this transport.\n */\n static previouslyFailed(): boolean {\n // If our persistent storage is actually only in-memory storage,\n // we default to assuming that it previously failed to be safe.\n return (\n PersistentStorage.isInMemoryStorage ||\n PersistentStorage.get('previous_websocket_failure') === true\n );\n }\n\n markConnectionHealthy() {\n PersistentStorage.remove('previous_websocket_failure');\n }\n\n private appendFrame_(data: string) {\n this.frames.push(data);\n if (this.frames.length === this.totalFrames) {\n const fullMess = this.frames.join('');\n this.frames = null;\n const jsonMess = jsonEval(fullMess) as object;\n\n //handle the message\n this.onMessage(jsonMess);\n }\n }\n\n /**\n * @param frameCount - The number of frames we are expecting from the server\n */\n private handleNewFrameCount_(frameCount: number) {\n this.totalFrames = frameCount;\n this.frames = [];\n }\n\n /**\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\n * @returns Any remaining data to be process, or null if there is none\n */\n private extractFrameCount_(data: string): string | null {\n assert(this.frames === null, 'We already have a frame buffer');\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\n if (data.length <= 6) {\n const frameCount = Number(data);\n if (!isNaN(frameCount)) {\n this.handleNewFrameCount_(frameCount);\n return null;\n }\n }\n this.handleNewFrameCount_(1);\n return data;\n }\n\n /**\n * Process a websocket frame that has arrived from the server.\n * @param mess - The frame data\n */\n handleIncomingFrame(mess: { [k: string]: unknown }) {\n if (this.mySock === null) {\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n }\n const data = mess['data'] as string;\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n\n this.resetKeepAlive();\n\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n } else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n const remainingData = this.extractFrameCount_(data);\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n }\n\n /**\n * Send a message to the server\n * @param data - The JSON object to transmit\n */\n send(data: {}) {\n this.resetKeepAlive();\n\n const dataStr = stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n\n //We can only fit a certain amount in each websocket frame, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n\n const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n\n //Send the length header\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n }\n\n //Send the actual data in segments.\n for (let i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n }\n\n private shutdown_() {\n this.isClosed_ = true;\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n }\n\n private onClosed_() {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_();\n\n // since this is an internal close, trigger the close listener\n if (this.onDisconnect) {\n this.onDisconnect(this.everConnected_);\n this.onDisconnect = null;\n }\n }\n }\n\n /**\n * External-facing close handler.\n * Close the websocket and kill the connection.\n */\n close() {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n }\n\n /**\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\n * the last activity.\n */\n resetKeepAlive() {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(() => {\n //If there has been no websocket activity for a while, send a no-op\n if (this.mySock) {\n this.sendString_('0');\n }\n this.resetKeepAlive();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL)) as any;\n }\n\n /**\n * Send a string over the websocket.\n *\n * @param str - String to send.\n */\n private sendString_(str: string) {\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n // calls for some unknown reason. We treat these as an error and disconnect.\n // See https://app.asana.com/0/58926111402292/68021340250410\n try {\n this.mySock.send(str);\n } catch (e) {\n this.log_(\n 'Exception thrown from WebSocket.send():',\n e.message || e.data,\n 'Closing connection.'\n );\n setTimeout(this.onClosed_.bind(this), 0);\n }\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _isFirebaseServerApp } from '@firebase/app'; // eslint-disable-line import/no-extraneous-dependencies\nimport {\n AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { warn } from './util/util';\n\n/**\n * Abstraction around AppCheck's token fetching capabilities.\n */\nexport class AppCheckTokenProvider {\n private appCheck?: FirebaseAppCheckInternal;\n private serverAppAppCheckToken?: string;\n private appName: string;\n constructor(\n app: FirebaseApp,\n private appCheckProvider?: Provider\n ) {\n this.appName = app.name;\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n this.appCheck = appCheckProvider?.getImmediate({ optional: true });\n if (!this.appCheck) {\n appCheckProvider?.get().then(appCheck => (this.appCheck = appCheck));\n }\n }\n\n getToken(forceRefresh?: boolean): Promise {\n if (this.serverAppAppCheckToken) {\n if (forceRefresh) {\n throw new Error(\n 'Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.'\n );\n }\n return Promise.resolve({ token: this.serverAppAppCheckToken });\n }\n if (!this.appCheck) {\n return new Promise((resolve, reject) => {\n // Support delayed initialization of FirebaseAppCheck. This allows our\n // customers to initialize the RTDB SDK before initializing Firebase\n // AppCheck and ensures that all requests are authenticated if a token\n // becomes available before the timeout below expires.\n setTimeout(() => {\n if (this.appCheck) {\n this.getToken(forceRefresh).then(resolve, reject);\n } else {\n resolve(null);\n }\n }, 0);\n });\n }\n return this.appCheck.getToken(forceRefresh);\n }\n\n addTokenChangeListener(listener: AppCheckTokenListener) {\n this.appCheckProvider\n ?.get()\n .then(appCheck => appCheck.addTokenListener(listener));\n }\n\n notifyForInvalidToken(): void {\n warn(\n `Provided AppCheck credentials for the app named \"${this.appName}\" ` +\n 'are invalid. This usually indicates your app was not initialized correctly.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseAuthTokenData } from '@firebase/app-types/private';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { log, warn } from './util/util';\n\nexport interface AuthTokenProvider {\n getToken(forceRefresh: boolean): Promise;\n addTokenChangeListener(listener: (token: string | null) => void): void;\n removeTokenChangeListener(listener: (token: string | null) => void): void;\n notifyForInvalidToken(): void;\n}\n\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nexport class FirebaseAuthTokenProvider implements AuthTokenProvider {\n private auth_: FirebaseAuthInternal | null = null;\n\n constructor(\n private appName_: string,\n private firebaseOptions_: object,\n private authProvider_: Provider\n ) {\n this.auth_ = authProvider_.getImmediate({ optional: true });\n if (!this.auth_) {\n authProvider_.onInit(auth => (this.auth_ = auth));\n }\n }\n\n getToken(forceRefresh: boolean): Promise {\n if (!this.auth_) {\n return new Promise((resolve, reject) => {\n // Support delayed initialization of FirebaseAuth. This allows our\n // customers to initialize the RTDB SDK before initializing Firebase\n // Auth and ensures that all requests are authenticated if a token\n // becomes available before the timeout below expires.\n setTimeout(() => {\n if (this.auth_) {\n this.getToken(forceRefresh).then(resolve, reject);\n } else {\n resolve(null);\n }\n }, 0);\n });\n }\n\n return this.auth_.getToken(forceRefresh).catch(error => {\n // TODO: Need to figure out all the cases this is raised and whether\n // this makes sense.\n if (error && error.code === 'auth/token-not-initialized') {\n log('Got auth/token-not-initialized error. Treating as null token.');\n return null;\n } else {\n return Promise.reject(error);\n }\n });\n }\n\n addTokenChangeListener(listener: (token: string | null) => void): void {\n // TODO: We might want to wrap the listener and call it with no args to\n // avoid a leaky abstraction, but that makes removing the listener harder.\n if (this.auth_) {\n this.auth_.addAuthTokenListener(listener);\n } else {\n this.authProvider_\n .get()\n .then(auth => auth.addAuthTokenListener(listener));\n }\n }\n\n removeTokenChangeListener(listener: (token: string | null) => void): void {\n this.authProvider_\n .get()\n .then(auth => auth.removeAuthTokenListener(listener));\n }\n\n notifyForInvalidToken(): void {\n let errorMessage =\n 'Provided authentication credentials for the app named \"' +\n this.appName_ +\n '\" are invalid. This usually indicates your app was not ' +\n 'initialized correctly. ';\n if ('credential' in this.firebaseOptions_) {\n errorMessage +=\n 'Make sure the \"credential\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n } else if ('serviceAccount' in this.firebaseOptions_) {\n errorMessage +=\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n } else {\n errorMessage +=\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\n 'initializeApp() match the values provided for your app at ' +\n 'https://console.firebase.google.com/.';\n }\n warn(errorMessage);\n }\n}\n\n/* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */\nexport class EmulatorTokenProvider implements AuthTokenProvider {\n /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */\n static OWNER = 'owner';\n\n constructor(private accessToken: string) {}\n\n getToken(forceRefresh: boolean): Promise {\n return Promise.resolve({\n accessToken: this.accessToken\n });\n }\n\n addTokenChangeListener(listener: (token: string | null) => void): void {\n // Invoke the listener immediately to match the behavior in Firebase Auth\n // (see packages/auth/src/auth.js#L1807)\n listener(this.accessToken);\n }\n\n removeTokenChangeListener(listener: (token: string | null) => void): void {}\n\n notifyForInvalidToken(): void {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { exceptionGuard } from '../../core/util/util';\n\n/**\n * This class ensures the packets from the server arrive in order\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\n */\nexport class PacketReceiver {\n pendingResponses: unknown[] = [];\n currentResponseNum = 0;\n closeAfterResponse = -1;\n onClose: (() => void) | null = null;\n\n /**\n * @param onMessage_\n */\n constructor(private onMessage_: (a: {}) => void) {}\n\n closeAfter(responseNum: number, callback: () => void) {\n this.closeAfterResponse = responseNum;\n this.onClose = callback;\n if (this.closeAfterResponse < this.currentResponseNum) {\n this.onClose();\n this.onClose = null;\n }\n }\n\n /**\n * Each message from the server comes with a response number, and an array of data. The responseNumber\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\n * browsers will respond in the same order as the requests we sent\n */\n handleResponse(requestNum: number, data: unknown[]) {\n this.pendingResponses[requestNum] = data;\n while (this.pendingResponses[this.currentResponseNum]) {\n const toProcess = this.pendingResponses[\n this.currentResponseNum\n ] as unknown[];\n delete this.pendingResponses[this.currentResponseNum];\n for (let i = 0; i < toProcess.length; ++i) {\n if (toProcess[i]) {\n exceptionGuard(() => {\n this.onMessage_(toProcess[i]);\n });\n }\n }\n if (this.currentResponseNum === this.closeAfterResponse) {\n if (this.onClose) {\n this.onClose();\n this.onClose = null;\n }\n break;\n }\n this.currentResponseNum++;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Encode, isNodeSdk, stringify } from '@firebase/util';\n\nimport { RepoInfo, repoInfoConnectionURL } from '../core/RepoInfo';\nimport { StatsCollection } from '../core/stats/StatsCollection';\nimport { statsManagerGetCollection } from '../core/stats/StatsManager';\nimport {\n executeWhenDOMReady,\n isChromeExtensionContentScript,\n isWindowsStoreApp,\n log,\n logWrapper,\n LUIDGenerator,\n splitStringBySize\n} from '../core/util/util';\n\nimport {\n APP_CHECK_TOKEN_PARAM,\n APPLICATION_ID_PARAM,\n FORGE_DOMAIN_RE,\n FORGE_REF,\n LAST_SESSION_PARAM,\n LONG_POLLING,\n PROTOCOL_VERSION,\n REFERER_PARAM,\n TRANSPORT_SESSION_PARAM,\n VERSION_PARAM\n} from './Constants';\nimport { PacketReceiver } from './polling/PacketReceiver';\nimport { Transport } from './Transport';\n\n// URL query parameters associated with longpolling\nexport const FIREBASE_LONGPOLL_START_PARAM = 'start';\nexport const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\nexport const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\nexport const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\nexport const FIREBASE_LONGPOLL_ID_PARAM = 'id';\nexport const FIREBASE_LONGPOLL_PW_PARAM = 'pw';\nexport const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\nexport const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\nexport const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\nexport const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\nexport const FIREBASE_LONGPOLL_DATA_PARAM = 'd';\nexport const FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = 'disconn';\nexport const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\n\n//Data size constants.\n//TODO: Perf: the maximum length actually differs from browser to browser.\n// We should check what browser we're on and set accordingly.\nconst MAX_URL_DATA_SIZE = 1870;\nconst SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\nconst MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\n\n/**\n * Keepalive period\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\n * length of 30 seconds that we can't exceed.\n */\nconst KEEPALIVE_REQUEST_INTERVAL = 25000;\n\n/**\n * How long to wait before aborting a long-polling connection attempt.\n */\nconst LP_CONNECT_TIMEOUT = 30000;\n\n/**\n * This class manages a single long-polling connection.\n */\nexport class BrowserPollConnection implements Transport {\n bytesSent = 0;\n bytesReceived = 0;\n urlFn: (params: object) => string;\n scriptTagHolder: FirebaseIFrameScriptHolder;\n myDisconnFrame: HTMLIFrameElement;\n curSegmentNum: number;\n myPacketOrderer: PacketReceiver;\n id: string;\n password: string;\n private log_: (...a: unknown[]) => void;\n private stats_: StatsCollection;\n private everConnected_ = false;\n private isClosed_: boolean;\n private connectTimeoutTimer_: number | null;\n private onDisconnect_: ((a?: boolean) => void) | null;\n\n /**\n * @param connId An identifier for this connection, used for logging\n * @param repoInfo The info for the endpoint to send data to.\n * @param applicationId The Firebase App ID for this project.\n * @param appCheckToken The AppCheck token for this client.\n * @param authToken The AuthToken to use for this connection.\n * @param transportSessionId Optional transportSessionid if we are\n * reconnecting for an existing transport session\n * @param lastSessionId Optional lastSessionId if the PersistentConnection has\n * already created a connection previously\n */\n constructor(\n public connId: string,\n public repoInfo: RepoInfo,\n private applicationId?: string,\n private appCheckToken?: string,\n private authToken?: string,\n public transportSessionId?: string,\n public lastSessionId?: string\n ) {\n this.log_ = logWrapper(connId);\n this.stats_ = statsManagerGetCollection(repoInfo);\n this.urlFn = (params: { [k: string]: string }) => {\n // Always add the token if we have one.\n if (this.appCheckToken) {\n params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\n }\n return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);\n };\n }\n\n /**\n * @param onMessage - Callback when messages arrive\n * @param onDisconnect - Callback with connection lost.\n */\n open(onMessage: (msg: {}) => void, onDisconnect: (a?: boolean) => void) {\n this.curSegmentNum = 0;\n this.onDisconnect_ = onDisconnect;\n this.myPacketOrderer = new PacketReceiver(onMessage);\n this.isClosed_ = false;\n\n this.connectTimeoutTimer_ = setTimeout(() => {\n this.log_('Timed out trying to connect.');\n // Make sure we clear the host cache\n this.onClosed_();\n this.connectTimeoutTimer_ = null;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(LP_CONNECT_TIMEOUT)) as any;\n\n // Ensure we delay the creation of the iframe until the DOM is loaded.\n executeWhenDOMReady(() => {\n if (this.isClosed_) {\n return;\n }\n\n //Set up a callback that gets triggered once a connection is set up.\n this.scriptTagHolder = new FirebaseIFrameScriptHolder(\n (...args) => {\n const [command, arg1, arg2, arg3, arg4] = args;\n this.incrementIncomingBytes_(args);\n if (!this.scriptTagHolder) {\n return; // we closed the connection.\n }\n\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n this.everConnected_ = true;\n if (command === FIREBASE_LONGPOLL_START_PARAM) {\n this.id = arg1 as string;\n this.password = arg2 as string;\n } else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {\n // Don't clear the host cache. We got a response from the server, so we know it's reachable\n if (arg1) {\n // We aren't expecting any more data (other than what the server's already in the process of sending us\n // through our already open polls), so don't send any more.\n this.scriptTagHolder.sendNewPolls = false;\n\n // arg1 in this case is the last response number sent by the server. We should try to receive\n // all of the responses up to this one before closing\n this.myPacketOrderer.closeAfter(arg1 as number, () => {\n this.onClosed_();\n });\n } else {\n this.onClosed_();\n }\n } else {\n throw new Error('Unrecognized command received: ' + command);\n }\n },\n (...args) => {\n const [pN, data] = args;\n this.incrementIncomingBytes_(args);\n this.myPacketOrderer.handleResponse(pN as number, data as unknown[]);\n },\n () => {\n this.onClosed_();\n },\n this.urlFn\n );\n\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\n //from cache.\n const urlParams: { [k: string]: string | number } = {};\n urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(\n Math.random() * 100000000\n );\n if (this.scriptTagHolder.uniqueCallbackIdentifier) {\n urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =\n this.scriptTagHolder.uniqueCallbackIdentifier;\n }\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\n if (this.transportSessionId) {\n urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;\n }\n if (this.lastSessionId) {\n urlParams[LAST_SESSION_PARAM] = this.lastSessionId;\n }\n if (this.applicationId) {\n urlParams[APPLICATION_ID_PARAM] = this.applicationId;\n }\n if (this.appCheckToken) {\n urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\n }\n if (\n typeof location !== 'undefined' &&\n location.hostname &&\n FORGE_DOMAIN_RE.test(location.hostname)\n ) {\n urlParams[REFERER_PARAM] = FORGE_REF;\n }\n const connectURL = this.urlFn(urlParams);\n this.log_('Connecting via long-poll to ' + connectURL);\n this.scriptTagHolder.addTag(connectURL, () => {\n /* do nothing */\n });\n });\n }\n\n /**\n * Call this when a handshake has completed successfully and we want to consider the connection established\n */\n start() {\n this.scriptTagHolder.startLongPoll(this.id, this.password);\n this.addDisconnectPingFrame(this.id, this.password);\n }\n\n static forceAllow_: boolean;\n\n /**\n * Forces long polling to be considered as a potential transport\n */\n static forceAllow() {\n BrowserPollConnection.forceAllow_ = true;\n }\n\n static forceDisallow_: boolean;\n\n /**\n * Forces longpolling to not be considered as a potential transport\n */\n static forceDisallow() {\n BrowserPollConnection.forceDisallow_ = true;\n }\n\n // Static method, use string literal so it can be accessed in a generic way\n static isAvailable() {\n if (isNodeSdk()) {\n return false;\n } else if (BrowserPollConnection.forceAllow_) {\n return true;\n } else {\n // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\n // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\n return (\n !BrowserPollConnection.forceDisallow_ &&\n typeof document !== 'undefined' &&\n document.createElement != null &&\n !isChromeExtensionContentScript() &&\n !isWindowsStoreApp()\n );\n }\n }\n\n /**\n * No-op for polling\n */\n markConnectionHealthy() {}\n\n /**\n * Stops polling and cleans up the iframe\n */\n private shutdown_() {\n this.isClosed_ = true;\n\n if (this.scriptTagHolder) {\n this.scriptTagHolder.close();\n this.scriptTagHolder = null;\n }\n\n //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\n if (this.myDisconnFrame) {\n document.body.removeChild(this.myDisconnFrame);\n this.myDisconnFrame = null;\n }\n\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n }\n\n /**\n * Triggered when this transport is closed\n */\n private onClosed_() {\n if (!this.isClosed_) {\n this.log_('Longpoll is closing itself');\n this.shutdown_();\n\n if (this.onDisconnect_) {\n this.onDisconnect_(this.everConnected_);\n this.onDisconnect_ = null;\n }\n }\n }\n\n /**\n * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\n * that we've left.\n */\n close() {\n if (!this.isClosed_) {\n this.log_('Longpoll is being closed.');\n this.shutdown_();\n }\n }\n\n /**\n * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\n * broken into chunks (since URLs have a small maximum length).\n * @param data - The JSON data to transmit.\n */\n send(data: {}) {\n const dataStr = stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n\n //first, lets get the base64-encoded data\n const base64data = base64Encode(dataStr);\n\n //We can only fit a certain amount in each URL, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\n\n //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\n //of segments so that we can reassemble the packet on the server.\n for (let i = 0; i < dataSegs.length; i++) {\n this.scriptTagHolder.enqueueSegment(\n this.curSegmentNum,\n dataSegs.length,\n dataSegs[i]\n );\n this.curSegmentNum++;\n }\n }\n\n /**\n * This is how we notify the server that we're leaving.\n * We aren't able to send requests with DHTML on a window close event, but we can\n * trigger XHR requests in some browsers (everything but Opera basically).\n */\n addDisconnectPingFrame(id: string, pw: string) {\n if (isNodeSdk()) {\n return;\n }\n this.myDisconnFrame = document.createElement('iframe');\n const urlParams: { [k: string]: string } = {};\n urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;\n this.myDisconnFrame.src = this.urlFn(urlParams);\n this.myDisconnFrame.style.display = 'none';\n\n document.body.appendChild(this.myDisconnFrame);\n }\n\n /**\n * Used to track the bytes received by this client\n */\n private incrementIncomingBytes_(args: unknown) {\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\n const bytesReceived = stringify(args).length;\n this.bytesReceived += bytesReceived;\n this.stats_.incrementCounter('bytes_received', bytesReceived);\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport interface IFrameElement extends HTMLIFrameElement {\n doc: Document;\n}\n\n/*********************************************************************************************\n * A wrapper around an iframe that is used as a long-polling script holder.\n *********************************************************************************************/\nexport class FirebaseIFrameScriptHolder {\n //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\n //problems in some browsers.\n outstandingRequests = new Set();\n\n //A queue of the pending segments waiting for transmission to the server.\n pendingSegs: Array<{ seg: number; ts: number; d: unknown }> = [];\n\n //A serial number. We use this for two things:\n // 1) A way to ensure the browser doesn't cache responses to polls\n // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\n // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\n // JSONP code in the order it was added to the iframe.\n currentSerial = Math.floor(Math.random() * 100000000);\n\n // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\n // incoming data from the server that we're waiting for).\n sendNewPolls = true;\n\n uniqueCallbackIdentifier: number;\n myIFrame: IFrameElement;\n alive: boolean;\n myID: string;\n myPW: string;\n commandCB: (command: string, ...args: unknown[]) => void;\n onMessageCB: (...args: unknown[]) => void;\n\n /**\n * @param commandCB - The callback to be called when control commands are received from the server.\n * @param onMessageCB - The callback to be triggered when responses arrive from the server.\n * @param onDisconnect - The callback to be triggered when this tag holder is closed\n * @param urlFn - A function that provides the URL of the endpoint to send data to.\n */\n constructor(\n commandCB: (command: string, ...args: unknown[]) => void,\n onMessageCB: (...args: unknown[]) => void,\n public onDisconnect: () => void,\n public urlFn: (a: object) => string\n ) {\n if (!isNodeSdk()) {\n //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\n //iframes where we put the long-polling script tags. We have two callbacks:\n // 1) Command Callback - Triggered for control issues, like starting a connection.\n // 2) Message Callback - Triggered when new data arrives.\n this.uniqueCallbackIdentifier = LUIDGenerator();\n window[\n FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier\n ] = commandCB;\n window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =\n onMessageCB;\n\n //Create an iframe for us to add script tags to.\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\n\n // Set the iframe's contents.\n let script = '';\n // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\n // for ie9, but ie8 needs to do it again in the document itself.\n if (\n this.myIFrame.src &&\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:'\n ) {\n const currentDomain = document.domain;\n script = '';\n }\n const iframeContents = '' + script + '';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n } catch (e) {\n log('frame writing exception');\n if (e.stack) {\n log(e.stack);\n }\n log(e);\n }\n } else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n\n /**\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\n * actually use.\n */\n private static createIFrame_(): IFrameElement {\n const iframe = document.createElement('iframe') as IFrameElement;\n iframe.style.display = 'none';\n\n // This is necessary in order to initialize the document inside the iframe\n if (document.body) {\n document.body.appendChild(iframe);\n try {\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n const a = iframe.contentWindow.document;\n if (!a) {\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n log('No IE domain setting required');\n }\n } catch (e) {\n const domain = document.domain;\n iframe.src =\n \"javascript:void((function(){document.open();document.domain='\" +\n domain +\n \"';document.close();})())\";\n }\n } else {\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n // never gets hit.\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n }\n\n // Get the document of the iframe in a browser-specific way.\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n } else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else if ((iframe as any).document) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n iframe.doc = (iframe as any).document; //others?\n }\n\n return iframe;\n }\n\n /**\n * Cancel all outstanding queries and remove the frame.\n */\n close() {\n //Mark this iframe as dead, so no new requests are sent.\n this.alive = false;\n\n if (this.myIFrame) {\n //We have to actually remove all of the html inside this iframe before removing it from the\n //window, or IE will continue loading and executing the script tags we've already added, which\n //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.\n this.myIFrame.doc.body.textContent = '';\n setTimeout(() => {\n if (this.myIFrame !== null) {\n document.body.removeChild(this.myIFrame);\n this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n\n // Protect from being called recursively.\n const onDisconnect = this.onDisconnect;\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\n }\n\n /**\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\n * @param id - The ID of this connection\n * @param pw - The password for this connection\n */\n startLongPoll(id: string, pw: string) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true;\n\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n while (this.newRequest_()) {}\n }\n\n /**\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\n * too many outstanding requests and we are still alive.\n *\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\n * needed.\n */\n private newRequest_() {\n // We keep one outstanding request open all the time to receive data, but if we need to send data\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\n // close the old request.\n if (\n this.alive &&\n this.sendNewPolls &&\n this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)\n ) {\n //construct our url\n this.currentSerial++;\n const urlParams: { [k: string]: string | number } = {};\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n let theURL = this.urlFn(urlParams);\n //Now add as much data as we can.\n let curDataString = '';\n let i = 0;\n\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n const nextSeg = this.pendingSegs[0];\n if (\n (nextSeg.d as unknown[]).length +\n SEG_HEADER_SIZE +\n curDataString.length <=\n MAX_URL_DATA_SIZE\n ) {\n //great, the segment will fit. Lets append it.\n const theSeg = this.pendingSegs.shift();\n curDataString =\n curDataString +\n '&' +\n FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n i +\n '=' +\n theSeg.seg +\n '&' +\n FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n i +\n '=' +\n theSeg.ts +\n '&' +\n FIREBASE_LONGPOLL_DATA_PARAM +\n i +\n '=' +\n theSeg.d;\n i++;\n } else {\n break;\n }\n }\n\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Queue a packet for transmission to the server.\n * @param segnum - A sequential id for this packet segment used for reassembly\n * @param totalsegs - The total number of segments in this packet\n * @param data - The data for this segment.\n */\n enqueueSegment(segnum: number, totalsegs: number, data: unknown) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n\n //send the data immediately if there isn't already data being transmitted, unless\n //startLongPoll hasn't been called yet.\n if (this.alive) {\n this.newRequest_();\n }\n }\n\n /**\n * Add a script tag for a regular long-poll request.\n * @param url - The URL of the script tag.\n * @param serial - The serial number of the request.\n */\n private addLongPollTag_(url: string, serial: number) {\n //remember that we sent this request.\n this.outstandingRequests.add(serial);\n\n const doNewRequest = () => {\n this.outstandingRequests.delete(serial);\n this.newRequest_();\n };\n\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n const keepaliveTimeout = setTimeout(\n doNewRequest,\n Math.floor(KEEPALIVE_REQUEST_INTERVAL)\n );\n\n const readyStateCB = () => {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout);\n\n // Trigger a new request so we can continue receiving data.\n doNewRequest();\n };\n\n this.addTag(url, readyStateCB);\n }\n\n /**\n * Add an arbitrary script tag to the iframe.\n * @param url - The URL for the script tag source.\n * @param loadCB - A callback to be triggered once the script has loaded.\n */\n addTag(url: string, loadCB: () => void) {\n if (isNodeSdk()) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any).doNodeLongPoll(url, loadCB);\n } else {\n setTimeout(() => {\n try {\n // if we're already closed, don't add this poll\n if (!this.sendNewPolls) {\n return;\n }\n const newScript = this.myIFrame.doc.createElement('script');\n newScript.type = 'text/javascript';\n newScript.async = true;\n newScript.src = url;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n newScript.onload = (newScript as any).onreadystatechange =\n function () {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const rstate = (newScript as any).readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n newScript.onload = (newScript as any).onreadystatechange = null;\n if (newScript.parentNode) {\n newScript.parentNode.removeChild(newScript);\n }\n loadCB();\n }\n };\n newScript.onerror = () => {\n log('Long-poll script failed to load: ' + url);\n this.sendNewPolls = false;\n this.close();\n };\n this.myIFrame.doc.body.appendChild(newScript);\n } catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../core/RepoInfo';\nimport { warn } from '../core/util/util';\n\nimport { BrowserPollConnection } from './BrowserPollConnection';\nimport { TransportConstructor } from './Transport';\nimport { WebSocketConnection } from './WebSocketConnection';\n\n/**\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\n * lifecycle.\n *\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\n * they are available.\n */\nexport class TransportManager {\n private transports_: TransportConstructor[];\n\n // Keeps track of whether the TransportManager has already chosen a transport to use\n static globalTransportInitialized_ = false;\n\n static get ALL_TRANSPORTS() {\n return [BrowserPollConnection, WebSocketConnection];\n }\n\n /**\n * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after\n * TransportManager has already set up transports_\n */\n static get IS_TRANSPORT_INITIALIZED() {\n return this.globalTransportInitialized_;\n }\n\n /**\n * @param repoInfo - Metadata around the namespace we're connecting to\n */\n constructor(repoInfo: RepoInfo) {\n this.initTransports_(repoInfo);\n }\n\n private initTransports_(repoInfo: RepoInfo) {\n const isWebSocketsAvailable: boolean =\n WebSocketConnection && WebSocketConnection['isAvailable']();\n let isSkipPollConnection =\n isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();\n\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable) {\n warn(\n \"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\"\n );\n }\n\n isSkipPollConnection = true;\n }\n\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection];\n } else {\n const transports = (this.transports_ = [] as TransportConstructor[]);\n for (const transport of TransportManager.ALL_TRANSPORTS) {\n if (transport && transport['isAvailable']()) {\n transports.push(transport);\n }\n }\n TransportManager.globalTransportInitialized_ = true;\n }\n }\n\n /**\n * @returns The constructor for the initial transport to use\n */\n initialTransport(): TransportConstructor {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n } else {\n throw new Error('No transports available');\n }\n }\n\n /**\n * @returns The constructor for the next transport, or null\n */\n upgradeTransport(): TransportConstructor | null {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n } else {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../core/RepoInfo';\nimport { PersistentStorage } from '../core/storage/storage';\nimport { Indexable } from '../core/util/misc';\nimport {\n error,\n logWrapper,\n requireKey,\n setTimeoutNonBlocking,\n warn\n} from '../core/util/util';\n\nimport { PROTOCOL_VERSION } from './Constants';\nimport { Transport, TransportConstructor } from './Transport';\nimport { TransportManager } from './TransportManager';\n\n// Abort upgrade attempt if it takes longer than 60s.\nconst UPGRADE_TIMEOUT = 60000;\n\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\nconst DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\n\n// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\n// but we've sent/received enough bytes, we don't cancel the connection.\nconst BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\nconst BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\n\nconst enum RealtimeState {\n CONNECTING,\n CONNECTED,\n DISCONNECTED\n}\n\nconst MESSAGE_TYPE = 't';\nconst MESSAGE_DATA = 'd';\nconst CONTROL_SHUTDOWN = 's';\nconst CONTROL_RESET = 'r';\nconst CONTROL_ERROR = 'e';\nconst CONTROL_PONG = 'o';\nconst SWITCH_ACK = 'a';\nconst END_TRANSMISSION = 'n';\nconst PING = 'p';\n\nconst SERVER_HELLO = 'h';\n\n/**\n * Creates a new real-time connection to the server using whichever method works\n * best in the current browser.\n */\nexport class Connection {\n connectionCount = 0;\n pendingDataMessages: unknown[] = [];\n sessionId: string;\n\n private conn_: Transport;\n private healthyTimeout_: number;\n private isHealthy_: boolean;\n private log_: (...args: unknown[]) => void;\n private primaryResponsesRequired_: number;\n private rx_: Transport;\n private secondaryConn_: Transport;\n private secondaryResponsesRequired_: number;\n private state_ = RealtimeState.CONNECTING;\n private transportManager_: TransportManager;\n private tx_: Transport;\n\n /**\n * @param id - an id for this connection\n * @param repoInfo_ - the info for the endpoint to connect to\n * @param applicationId_ - the Firebase App ID for this project\n * @param appCheckToken_ - The App Check Token for this device.\n * @param authToken_ - The auth token for this session.\n * @param onMessage_ - the callback to be triggered when a server-push message arrives\n * @param onReady_ - the callback to be triggered when this connection is ready to send messages.\n * @param onDisconnect_ - the callback to be triggered when a connection was lost\n * @param onKill_ - the callback to be triggered when this connection has permanently shut down.\n * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\n */\n constructor(\n public id: string,\n private repoInfo_: RepoInfo,\n private applicationId_: string | undefined,\n private appCheckToken_: string | undefined,\n private authToken_: string | undefined,\n private onMessage_: (a: {}) => void,\n private onReady_: (a: number, b: string) => void,\n private onDisconnect_: () => void,\n private onKill_: (a: string) => void,\n public lastSessionId?: string\n ) {\n this.log_ = logWrapper('c:' + this.id + ':');\n this.transportManager_ = new TransportManager(repoInfo_);\n this.log_('Connection created');\n this.start_();\n }\n\n /**\n * Starts a connection attempt\n */\n private start_(): void {\n const conn = this.transportManager_.initialTransport();\n this.conn_ = new conn(\n this.nextTransportId_(),\n this.repoInfo_,\n this.applicationId_,\n this.appCheckToken_,\n this.authToken_,\n null,\n this.lastSessionId\n );\n\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\n\n const onMessageReceived = this.connReceiver_(this.conn_);\n const onConnectionLost = this.disconnReceiver_(this.conn_);\n this.tx_ = this.conn_;\n this.rx_ = this.conn_;\n this.secondaryConn_ = null;\n this.isHealthy_ = false;\n\n /*\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\n * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\n * still have the context of your originating frame.\n */\n setTimeout(() => {\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\n this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);\n }, Math.floor(0));\n\n const healthyTimeoutMS = conn['healthyTimeout'] || 0;\n if (healthyTimeoutMS > 0) {\n this.healthyTimeout_ = setTimeoutNonBlocking(() => {\n this.healthyTimeout_ = null;\n if (!this.isHealthy_) {\n if (\n this.conn_ &&\n this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE\n ) {\n this.log_(\n 'Connection exceeded healthy timeout but has received ' +\n this.conn_.bytesReceived +\n ' bytes. Marking connection healthy.'\n );\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n } else if (\n this.conn_ &&\n this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE\n ) {\n this.log_(\n 'Connection exceeded healthy timeout but has sent ' +\n this.conn_.bytesSent +\n ' bytes. Leaving connection alive.'\n );\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\n // the server.\n } else {\n this.log_('Closing unhealthy connection after timeout.');\n this.close();\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(healthyTimeoutMS)) as any;\n }\n }\n\n private nextTransportId_(): string {\n return 'c:' + this.id + ':' + this.connectionCount++;\n }\n\n private disconnReceiver_(conn) {\n return everConnected => {\n if (conn === this.conn_) {\n this.onConnectionLost_(everConnected);\n } else if (conn === this.secondaryConn_) {\n this.log_('Secondary connection lost.');\n this.onSecondaryConnectionLost_();\n } else {\n this.log_('closing an old connection');\n }\n };\n }\n\n private connReceiver_(conn: Transport) {\n return (message: Indexable) => {\n if (this.state_ !== RealtimeState.DISCONNECTED) {\n if (conn === this.rx_) {\n this.onPrimaryMessageReceived_(message);\n } else if (conn === this.secondaryConn_) {\n this.onSecondaryMessageReceived_(message);\n } else {\n this.log_('message on old connection');\n }\n }\n };\n }\n\n /**\n * @param dataMsg - An arbitrary data message to be sent to the server\n */\n sendRequest(dataMsg: object) {\n // wrap in a data message envelope and send it on\n const msg = { t: 'd', d: dataMsg };\n this.sendData_(msg);\n }\n\n tryCleanupConnection() {\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\n this.log_(\n 'cleaning up and promoting a connection: ' + this.secondaryConn_.connId\n );\n this.conn_ = this.secondaryConn_;\n this.secondaryConn_ = null;\n // the server will shutdown the old connection\n }\n }\n\n private onSecondaryControl_(controlData: { [k: string]: unknown }) {\n if (MESSAGE_TYPE in controlData) {\n const cmd = controlData[MESSAGE_TYPE] as string;\n if (cmd === SWITCH_ACK) {\n this.upgradeIfSecondaryHealthy_();\n } else if (cmd === CONTROL_RESET) {\n // Most likely the session wasn't valid. Abandon the switch attempt\n this.log_('Got a reset on secondary, closing it');\n this.secondaryConn_.close();\n // If we were already using this connection for something, than we need to fully close\n if (\n this.tx_ === this.secondaryConn_ ||\n this.rx_ === this.secondaryConn_\n ) {\n this.close();\n }\n } else if (cmd === CONTROL_PONG) {\n this.log_('got pong on secondary.');\n this.secondaryResponsesRequired_--;\n this.upgradeIfSecondaryHealthy_();\n }\n }\n }\n\n private onSecondaryMessageReceived_(parsedData: Indexable) {\n const layer: string = requireKey('t', parsedData) as string;\n const data: unknown = requireKey('d', parsedData);\n if (layer === 'c') {\n this.onSecondaryControl_(data as Indexable);\n } else if (layer === 'd') {\n // got a data message, but we're still second connection. Need to buffer it up\n this.pendingDataMessages.push(data);\n } else {\n throw new Error('Unknown protocol layer: ' + layer);\n }\n }\n\n private upgradeIfSecondaryHealthy_() {\n if (this.secondaryResponsesRequired_ <= 0) {\n this.log_('Secondary connection is healthy.');\n this.isHealthy_ = true;\n this.secondaryConn_.markConnectionHealthy();\n this.proceedWithUpgrade_();\n } else {\n // Send a ping to make sure the connection is healthy.\n this.log_('sending ping on secondary.');\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\n }\n }\n\n private proceedWithUpgrade_() {\n // tell this connection to consider itself open\n this.secondaryConn_.start();\n // send ack\n this.log_('sending client ack on secondary');\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\n\n // send end packet on primary transport, switch to sending on this one\n // can receive on this one, buffer responses until end received on primary transport\n this.log_('Ending transmission on primary');\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\n this.tx_ = this.secondaryConn_;\n\n this.tryCleanupConnection();\n }\n\n private onPrimaryMessageReceived_(parsedData: { [k: string]: unknown }) {\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\n const layer: string = requireKey('t', parsedData) as string;\n const data: unknown = requireKey('d', parsedData);\n if (layer === 'c') {\n this.onControl_(data as { [k: string]: unknown });\n } else if (layer === 'd') {\n this.onDataMessage_(data);\n }\n }\n\n private onDataMessage_(message: unknown) {\n this.onPrimaryResponse_();\n\n // We don't do anything with data messages, just kick them up a level\n this.onMessage_(message);\n }\n\n private onPrimaryResponse_() {\n if (!this.isHealthy_) {\n this.primaryResponsesRequired_--;\n if (this.primaryResponsesRequired_ <= 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n }\n }\n }\n\n private onControl_(controlData: { [k: string]: unknown }) {\n const cmd: string = requireKey(MESSAGE_TYPE, controlData) as string;\n if (MESSAGE_DATA in controlData) {\n const payload = controlData[MESSAGE_DATA];\n if (cmd === SERVER_HELLO) {\n const handshakePayload = {\n ...(payload as {\n ts: number;\n v: string;\n h: string;\n s: string;\n })\n };\n if (this.repoInfo_.isUsingEmulator) {\n // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes.\n handshakePayload.h = this.repoInfo_.host;\n }\n this.onHandshake_(handshakePayload);\n } else if (cmd === END_TRANSMISSION) {\n this.log_('recvd end transmission on primary');\n this.rx_ = this.secondaryConn_;\n for (let i = 0; i < this.pendingDataMessages.length; ++i) {\n this.onDataMessage_(this.pendingDataMessages[i]);\n }\n this.pendingDataMessages = [];\n this.tryCleanupConnection();\n } else if (cmd === CONTROL_SHUTDOWN) {\n // This was previously the 'onKill' callback passed to the lower-level connection\n // payload in this case is the reason for the shutdown. Generally a human-readable error\n this.onConnectionShutdown_(payload as string);\n } else if (cmd === CONTROL_RESET) {\n // payload in this case is the host we should contact\n this.onReset_(payload as string);\n } else if (cmd === CONTROL_ERROR) {\n error('Server Error: ' + payload);\n } else if (cmd === CONTROL_PONG) {\n this.log_('got pong on primary.');\n this.onPrimaryResponse_();\n this.sendPingOnPrimaryIfNecessary_();\n } else {\n error('Unknown control packet command: ' + cmd);\n }\n }\n }\n\n /**\n * @param handshake - The handshake data returned from the server\n */\n private onHandshake_(handshake: {\n ts: number;\n v: string;\n h: string;\n s: string;\n }): void {\n const timestamp = handshake.ts;\n const version = handshake.v;\n const host = handshake.h;\n this.sessionId = handshake.s;\n this.repoInfo_.host = host;\n // if we've already closed the connection, then don't bother trying to progress further\n if (this.state_ === RealtimeState.CONNECTING) {\n this.conn_.start();\n this.onConnectionEstablished_(this.conn_, timestamp);\n if (PROTOCOL_VERSION !== version) {\n warn('Protocol version mismatch detected');\n }\n // TODO: do we want to upgrade? when? maybe a delay?\n this.tryStartUpgrade_();\n }\n }\n\n private tryStartUpgrade_() {\n const conn = this.transportManager_.upgradeTransport();\n if (conn) {\n this.startUpgrade_(conn);\n }\n }\n\n private startUpgrade_(conn: TransportConstructor) {\n this.secondaryConn_ = new conn(\n this.nextTransportId_(),\n this.repoInfo_,\n this.applicationId_,\n this.appCheckToken_,\n this.authToken_,\n this.sessionId\n );\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.secondaryResponsesRequired_ =\n conn['responsesRequiredToBeHealthy'] || 0;\n\n const onMessage = this.connReceiver_(this.secondaryConn_);\n const onDisconnect = this.disconnReceiver_(this.secondaryConn_);\n this.secondaryConn_.open(onMessage, onDisconnect);\n\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\n setTimeoutNonBlocking(() => {\n if (this.secondaryConn_) {\n this.log_('Timed out trying to upgrade.');\n this.secondaryConn_.close();\n }\n }, Math.floor(UPGRADE_TIMEOUT));\n }\n\n private onReset_(host: string) {\n this.log_('Reset packet received. New host: ' + host);\n this.repoInfo_.host = host;\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\n // We don't currently support resets after the connection has already been established\n if (this.state_ === RealtimeState.CONNECTED) {\n this.close();\n } else {\n // Close whatever connections we have open and start again.\n this.closeConnections_();\n this.start_();\n }\n }\n\n private onConnectionEstablished_(conn: Transport, timestamp: number) {\n this.log_('Realtime connection established.');\n this.conn_ = conn;\n this.state_ = RealtimeState.CONNECTED;\n\n if (this.onReady_) {\n this.onReady_(timestamp, this.sessionId);\n this.onReady_ = null;\n }\n\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\n // send some pings.\n if (this.primaryResponsesRequired_ === 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n } else {\n setTimeoutNonBlocking(() => {\n this.sendPingOnPrimaryIfNecessary_();\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\n }\n }\n\n private sendPingOnPrimaryIfNecessary_() {\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\n if (!this.isHealthy_ && this.state_ === RealtimeState.CONNECTED) {\n this.log_('sending ping on primary.');\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\n }\n }\n\n private onSecondaryConnectionLost_() {\n const conn = this.secondaryConn_;\n this.secondaryConn_ = null;\n if (this.tx_ === conn || this.rx_ === conn) {\n // we are relying on this connection already in some capacity. Therefore, a failure is real\n this.close();\n }\n }\n\n /**\n * @param everConnected - Whether or not the connection ever reached a server. Used to determine if\n * we should flush the host cache\n */\n private onConnectionLost_(everConnected: boolean) {\n this.conn_ = null;\n\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\n if (!everConnected && this.state_ === RealtimeState.CONNECTING) {\n this.log_('Realtime connection failed.');\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\n if (this.repoInfo_.isCacheableHost()) {\n PersistentStorage.remove('host:' + this.repoInfo_.host);\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\n this.repoInfo_.internalHost = this.repoInfo_.host;\n }\n } else if (this.state_ === RealtimeState.CONNECTED) {\n this.log_('Realtime connection lost.');\n }\n\n this.close();\n }\n\n private onConnectionShutdown_(reason: string) {\n this.log_('Connection shutdown command received. Shutting down...');\n\n if (this.onKill_) {\n this.onKill_(reason);\n this.onKill_ = null;\n }\n\n // We intentionally don't want to fire onDisconnect (kill is a different case),\n // so clear the callback.\n this.onDisconnect_ = null;\n\n this.close();\n }\n\n private sendData_(data: object) {\n if (this.state_ !== RealtimeState.CONNECTED) {\n throw 'Connection is not connected';\n } else {\n this.tx_.send(data);\n }\n }\n\n /**\n * Cleans up this connection, calling the appropriate callbacks\n */\n close() {\n if (this.state_ !== RealtimeState.DISCONNECTED) {\n this.log_('Closing realtime connection.');\n this.state_ = RealtimeState.DISCONNECTED;\n\n this.closeConnections_();\n\n if (this.onDisconnect_) {\n this.onDisconnect_();\n this.onDisconnect_ = null;\n }\n }\n }\n\n private closeConnections_() {\n this.log_('Shutting down all connections');\n if (this.conn_) {\n this.conn_.close();\n this.conn_ = null;\n }\n\n if (this.secondaryConn_) {\n this.secondaryConn_.close();\n this.secondaryConn_ = null;\n }\n\n if (this.healthyTimeout_) {\n clearTimeout(this.healthyTimeout_);\n this.healthyTimeout_ = null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QueryContext } from './view/EventRegistration';\n\n/**\n * Interface defining the set of actions that can be performed against the Firebase server\n * (basically corresponds to our wire protocol).\n *\n * @interface\n */\nexport abstract class ServerActions {\n abstract listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ): void;\n\n /**\n * Remove a listen.\n */\n abstract unlisten(query: QueryContext, tag: number | null): void;\n\n /**\n * Get the server value satisfying this query.\n */\n abstract get(query: QueryContext): Promise;\n\n put(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void,\n hash?: string\n ) {}\n\n merge(\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {}\n\n /**\n * Refreshes the auth token for the current connection.\n * @param token - The authentication token\n */\n refreshAuthToken(token: string) {}\n\n /**\n * Refreshes the app check token for the current connection.\n * @param token The app check token\n */\n refreshAppCheckToken(token: string) {}\n\n onDisconnectPut(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n onDisconnectMerge(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n onDisconnectCancel(\n pathString: string,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n reportStats(stats: { [k: string]: unknown }) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\n/**\n * Base class to be used if you want to emit events. Call the constructor with\n * the set of allowed event names.\n */\nexport abstract class EventEmitter {\n private listeners_: {\n [eventType: string]: Array<{\n callback(...args: unknown[]): void;\n context: unknown;\n }>;\n } = {};\n\n constructor(private allowedEvents_: string[]) {\n assert(\n Array.isArray(allowedEvents_) && allowedEvents_.length > 0,\n 'Requires a non-empty array'\n );\n }\n\n /**\n * To be overridden by derived classes in order to fire an initial event when\n * somebody subscribes for data.\n *\n * @returns {Array.<*>} Array of parameters to trigger initial event with.\n */\n abstract getInitialEvent(eventType: string): unknown[];\n\n /**\n * To be called by derived classes to trigger events.\n */\n protected trigger(eventType: string, ...varArgs: unknown[]) {\n if (Array.isArray(this.listeners_[eventType])) {\n // Clone the list, since callbacks could add/remove listeners.\n const listeners = [...this.listeners_[eventType]];\n\n for (let i = 0; i < listeners.length; i++) {\n listeners[i].callback.apply(listeners[i].context, varArgs);\n }\n }\n }\n\n on(eventType: string, callback: (a: unknown) => void, context: unknown) {\n this.validateEventType_(eventType);\n this.listeners_[eventType] = this.listeners_[eventType] || [];\n this.listeners_[eventType].push({ callback, context });\n\n const eventData = this.getInitialEvent(eventType);\n if (eventData) {\n callback.apply(context, eventData);\n }\n }\n\n off(eventType: string, callback: (a: unknown) => void, context: unknown) {\n this.validateEventType_(eventType);\n const listeners = this.listeners_[eventType] || [];\n for (let i = 0; i < listeners.length; i++) {\n if (\n listeners[i].callback === callback &&\n (!context || context === listeners[i].context)\n ) {\n listeners.splice(i, 1);\n return;\n }\n }\n }\n\n private validateEventType_(eventType: string) {\n assert(\n this.allowedEvents_.find(et => {\n return et === eventType;\n }),\n 'Unknown event: ' + eventType\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, isMobileCordova } from '@firebase/util';\n\nimport { EventEmitter } from './EventEmitter';\n\n/**\n * Monitors online state (as reported by window.online/offline events).\n *\n * The expectation is that this could have many false positives (thinks we are online\n * when we're not), but no false negatives. So we can safely use it to determine when\n * we definitely cannot reach the internet.\n */\nexport class OnlineMonitor extends EventEmitter {\n private online_ = true;\n\n static getInstance() {\n return new OnlineMonitor();\n }\n\n constructor() {\n super(['online']);\n\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\n // It would seem that the 'online' event does not always fire consistently. So we disable it\n // for Cordova.\n if (\n typeof window !== 'undefined' &&\n typeof window.addEventListener !== 'undefined' &&\n !isMobileCordova()\n ) {\n window.addEventListener(\n 'online',\n () => {\n if (!this.online_) {\n this.online_ = true;\n this.trigger('online', true);\n }\n },\n false\n );\n\n window.addEventListener(\n 'offline',\n () => {\n if (this.online_) {\n this.online_ = false;\n this.trigger('online', false);\n }\n },\n false\n );\n }\n }\n\n getInitialEvent(eventType: string): boolean[] {\n assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n }\n\n currentlyOnline(): boolean {\n return this.online_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { stringLength } from '@firebase/util';\n\nimport { nameCompare } from './util';\n\n/** Maximum key depth. */\nconst MAX_PATH_DEPTH = 32;\n\n/** Maximum number of (UTF8) bytes in a Firebase path. */\nconst MAX_PATH_LENGTH_BYTES = 768;\n\n/**\n * An immutable object representing a parsed path. It's immutable so that you\n * can pass them around to other functions without worrying about them changing\n * it.\n */\n\nexport class Path {\n pieces_: string[];\n pieceNum_: number;\n\n /**\n * @param pathOrString - Path string to parse, or another path, or the raw\n * tokens array\n */\n constructor(pathOrString: string | string[], pieceNum?: number) {\n if (pieceNum === void 0) {\n this.pieces_ = (pathOrString as string).split('/');\n\n // Remove empty pieces.\n let copyTo = 0;\n for (let i = 0; i < this.pieces_.length; i++) {\n if (this.pieces_[i].length > 0) {\n this.pieces_[copyTo] = this.pieces_[i];\n copyTo++;\n }\n }\n this.pieces_.length = copyTo;\n\n this.pieceNum_ = 0;\n } else {\n this.pieces_ = pathOrString as string[];\n this.pieceNum_ = pieceNum;\n }\n }\n\n toString(): string {\n let pathString = '';\n for (let i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '') {\n pathString += '/' + this.pieces_[i];\n }\n }\n\n return pathString || '/';\n }\n}\n\nexport function newEmptyPath(): Path {\n return new Path('');\n}\n\nexport function pathGetFront(path: Path): string | null {\n if (path.pieceNum_ >= path.pieces_.length) {\n return null;\n }\n\n return path.pieces_[path.pieceNum_];\n}\n\n/**\n * @returns The number of segments in this path\n */\nexport function pathGetLength(path: Path): number {\n return path.pieces_.length - path.pieceNum_;\n}\n\nexport function pathPopFront(path: Path): Path {\n let pieceNum = path.pieceNum_;\n if (pieceNum < path.pieces_.length) {\n pieceNum++;\n }\n return new Path(path.pieces_, pieceNum);\n}\n\nexport function pathGetBack(path: Path): string | null {\n if (path.pieceNum_ < path.pieces_.length) {\n return path.pieces_[path.pieces_.length - 1];\n }\n\n return null;\n}\n\nexport function pathToUrlEncodedString(path: Path): string {\n let pathString = '';\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\n if (path.pieces_[i] !== '') {\n pathString += '/' + encodeURIComponent(String(path.pieces_[i]));\n }\n }\n\n return pathString || '/';\n}\n\n/**\n * Shallow copy of the parts of the path.\n *\n */\nexport function pathSlice(path: Path, begin: number = 0): string[] {\n return path.pieces_.slice(path.pieceNum_ + begin);\n}\n\nexport function pathParent(path: Path): Path | null {\n if (path.pieceNum_ >= path.pieces_.length) {\n return null;\n }\n\n const pieces = [];\n for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {\n pieces.push(path.pieces_[i]);\n }\n\n return new Path(pieces, 0);\n}\n\nexport function pathChild(path: Path, childPathObj: string | Path): Path {\n const pieces = [];\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\n pieces.push(path.pieces_[i]);\n }\n\n if (childPathObj instanceof Path) {\n for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\n pieces.push(childPathObj.pieces_[i]);\n }\n } else {\n const childPieces = childPathObj.split('/');\n for (let i = 0; i < childPieces.length; i++) {\n if (childPieces[i].length > 0) {\n pieces.push(childPieces[i]);\n }\n }\n }\n\n return new Path(pieces, 0);\n}\n\n/**\n * @returns True if there are no segments in this path\n */\nexport function pathIsEmpty(path: Path): boolean {\n return path.pieceNum_ >= path.pieces_.length;\n}\n\n/**\n * @returns The path from outerPath to innerPath\n */\nexport function newRelativePath(outerPath: Path, innerPath: Path): Path {\n const outer = pathGetFront(outerPath),\n inner = pathGetFront(innerPath);\n if (outer === null) {\n return innerPath;\n } else if (outer === inner) {\n return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));\n } else {\n throw new Error(\n 'INTERNAL ERROR: innerPath (' +\n innerPath +\n ') is not within ' +\n 'outerPath (' +\n outerPath +\n ')'\n );\n }\n}\n\n/**\n * @returns -1, 0, 1 if left is less, equal, or greater than the right.\n */\nexport function pathCompare(left: Path, right: Path): number {\n const leftKeys = pathSlice(left, 0);\n const rightKeys = pathSlice(right, 0);\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\n const cmp = nameCompare(leftKeys[i], rightKeys[i]);\n if (cmp !== 0) {\n return cmp;\n }\n }\n if (leftKeys.length === rightKeys.length) {\n return 0;\n }\n return leftKeys.length < rightKeys.length ? -1 : 1;\n}\n\n/**\n * @returns true if paths are the same.\n */\nexport function pathEquals(path: Path, other: Path): boolean {\n if (pathGetLength(path) !== pathGetLength(other)) {\n return false;\n }\n\n for (\n let i = path.pieceNum_, j = other.pieceNum_;\n i <= path.pieces_.length;\n i++, j++\n ) {\n if (path.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * @returns True if this path is a parent of (or the same as) other\n */\nexport function pathContains(path: Path, other: Path): boolean {\n let i = path.pieceNum_;\n let j = other.pieceNum_;\n if (pathGetLength(path) > pathGetLength(other)) {\n return false;\n }\n while (i < path.pieces_.length) {\n if (path.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n ++i;\n ++j;\n }\n return true;\n}\n\n/**\n * Dynamic (mutable) path used to count path lengths.\n *\n * This class is used to efficiently check paths for valid\n * length (in UTF8 bytes) and depth (used in path validation).\n *\n * Throws Error exception if path is ever invalid.\n *\n * The definition of a path always begins with '/'.\n */\nexport class ValidationPath {\n parts_: string[];\n /** Initialize to number of '/' chars needed in path. */\n byteLength_: number;\n\n /**\n * @param path - Initial Path.\n * @param errorPrefix_ - Prefix for any error messages.\n */\n constructor(path: Path, public errorPrefix_: string) {\n this.parts_ = pathSlice(path, 0);\n /** Initialize to number of '/' chars needed in path. */\n this.byteLength_ = Math.max(1, this.parts_.length);\n\n for (let i = 0; i < this.parts_.length; i++) {\n this.byteLength_ += stringLength(this.parts_[i]);\n }\n validationPathCheckValid(this);\n }\n}\n\nexport function validationPathPush(\n validationPath: ValidationPath,\n child: string\n): void {\n // Count the needed '/'\n if (validationPath.parts_.length > 0) {\n validationPath.byteLength_ += 1;\n }\n validationPath.parts_.push(child);\n validationPath.byteLength_ += stringLength(child);\n validationPathCheckValid(validationPath);\n}\n\nexport function validationPathPop(validationPath: ValidationPath): void {\n const last = validationPath.parts_.pop();\n validationPath.byteLength_ -= stringLength(last);\n // Un-count the previous '/'\n if (validationPath.parts_.length > 0) {\n validationPath.byteLength_ -= 1;\n }\n}\n\nfunction validationPathCheckValid(validationPath: ValidationPath): void {\n if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {\n throw new Error(\n validationPath.errorPrefix_ +\n 'has a key path longer than ' +\n MAX_PATH_LENGTH_BYTES +\n ' bytes (' +\n validationPath.byteLength_ +\n ').'\n );\n }\n if (validationPath.parts_.length > MAX_PATH_DEPTH) {\n throw new Error(\n validationPath.errorPrefix_ +\n 'path specified exceeds the maximum depth that can be written (' +\n MAX_PATH_DEPTH +\n ') or object contains a cycle ' +\n validationPathToErrorString(validationPath)\n );\n }\n}\n\n/**\n * String for use in error messages - uses '.' notation for path.\n */\nexport function validationPathToErrorString(\n validationPath: ValidationPath\n): string {\n if (validationPath.parts_.length === 0) {\n return '';\n }\n return \"in property '\" + validationPath.parts_.join('.') + \"'\";\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { EventEmitter } from './EventEmitter';\n\ndeclare const document: Document;\n\nexport class VisibilityMonitor extends EventEmitter {\n private visible_: boolean;\n\n static getInstance() {\n return new VisibilityMonitor();\n }\n\n constructor() {\n super(['visible']);\n let hidden: string;\n let visibilityChange: string;\n if (\n typeof document !== 'undefined' &&\n typeof document.addEventListener !== 'undefined'\n ) {\n if (typeof document['hidden'] !== 'undefined') {\n // Opera 12.10 and Firefox 18 and later support\n visibilityChange = 'visibilitychange';\n hidden = 'hidden';\n } else if (typeof document['mozHidden'] !== 'undefined') {\n visibilityChange = 'mozvisibilitychange';\n hidden = 'mozHidden';\n } else if (typeof document['msHidden'] !== 'undefined') {\n visibilityChange = 'msvisibilitychange';\n hidden = 'msHidden';\n } else if (typeof document['webkitHidden'] !== 'undefined') {\n visibilityChange = 'webkitvisibilitychange';\n hidden = 'webkitHidden';\n }\n }\n\n // Initially, we always assume we are visible. This ensures that in browsers\n // without page visibility support or in cases where we are never visible\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n // reconnects\n this.visible_ = true;\n\n if (visibilityChange) {\n document.addEventListener(\n visibilityChange,\n () => {\n const visible = !document[hidden];\n if (visible !== this.visible_) {\n this.visible_ = visible;\n this.trigger('visible', visible);\n }\n },\n false\n );\n }\n }\n\n getInitialEvent(eventType: string): boolean[] {\n assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n contains,\n Deferred,\n isEmpty,\n isMobileCordova,\n isNodeSdk,\n isReactNative,\n isValidFormat,\n safeGet,\n stringify,\n isAdmin\n} from '@firebase/util';\n\nimport { Connection } from '../realtime/Connection';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { OnlineMonitor } from './util/OnlineMonitor';\nimport { Path } from './util/Path';\nimport { error, log, logWrapper, warn, ObjectToUniqueKey } from './util/util';\nimport { VisibilityMonitor } from './util/VisibilityMonitor';\nimport { SDK_VERSION } from './version';\nimport { QueryContext } from './view/EventRegistration';\n\nconst RECONNECT_MIN_DELAY = 1000;\nconst RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\nconst RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\nconst RECONNECT_DELAY_MULTIPLIER = 1.3;\nconst RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\nconst SERVER_KILL_INTERRUPT_REASON = 'server_kill';\n\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\nconst INVALID_TOKEN_THRESHOLD = 3;\n\ninterface ListenSpec {\n onComplete(s: string, p?: unknown): void;\n\n hashFn(): string;\n\n query: QueryContext;\n tag: number | null;\n}\n\ninterface OnDisconnectRequest {\n pathString: string;\n action: string;\n data: unknown;\n onComplete?: (a: string, b: string) => void;\n}\n\ninterface OutstandingPut {\n action: string;\n request: object;\n queued?: boolean;\n onComplete: (a: string, b?: string) => void;\n}\n\ninterface OutstandingGet {\n request: object;\n onComplete: (response: { [k: string]: unknown }) => void;\n}\n\n/**\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\n *\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\n * in quotes to make sure the closure compiler does not minify them.\n */\nexport class PersistentConnection extends ServerActions {\n // Used for diagnostic logging.\n id = PersistentConnection.nextPersistentConnectionId_++;\n private log_ = logWrapper('p:' + this.id + ':');\n\n private interruptReasons_: { [reason: string]: boolean } = {};\n private readonly listens: Map<\n /* path */ string,\n Map\n > = new Map();\n private outstandingPuts_: OutstandingPut[] = [];\n private outstandingGets_: OutstandingGet[] = [];\n private outstandingPutCount_ = 0;\n private outstandingGetCount_ = 0;\n private onDisconnectRequestQueue_: OnDisconnectRequest[] = [];\n private connected_ = false;\n private reconnectDelay_ = RECONNECT_MIN_DELAY;\n private maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\n private securityDebugCallback_: ((a: object) => void) | null = null;\n lastSessionId: string | null = null;\n\n private establishConnectionTimer_: number | null = null;\n\n private visible_: boolean = false;\n\n // Before we get connected, we keep a queue of pending messages to send.\n private requestCBHash_: { [k: number]: (a: unknown) => void } = {};\n private requestNumber_ = 0;\n\n private realtime_: {\n sendRequest(a: object): void;\n close(): void;\n } | null = null;\n\n private authToken_: string | null = null;\n private appCheckToken_: string | null = null;\n private forceTokenRefresh_ = false;\n private invalidAuthTokenCount_ = 0;\n private invalidAppCheckTokenCount_ = 0;\n\n private firstConnection_ = true;\n private lastConnectionAttemptTime_: number | null = null;\n private lastConnectionEstablishedTime_: number | null = null;\n\n private static nextPersistentConnectionId_ = 0;\n\n /**\n * Counter for number of connections created. Mainly used for tagging in the logs\n */\n private static nextConnectionId_ = 0;\n\n /**\n * @param repoInfo_ - Data about the namespace we are connecting to\n * @param applicationId_ - The Firebase App ID for this project\n * @param onDataUpdate_ - A callback for new data from the server\n */\n constructor(\n private repoInfo_: RepoInfo,\n private applicationId_: string,\n private onDataUpdate_: (\n a: string,\n b: unknown,\n c: boolean,\n d: number | null\n ) => void,\n private onConnectStatus_: (a: boolean) => void,\n private onServerInfoUpdate_: (a: unknown) => void,\n private authTokenProvider_: AuthTokenProvider,\n private appCheckTokenProvider_: AppCheckTokenProvider,\n private authOverride_?: object | null\n ) {\n super();\n\n if (authOverride_ && !isNodeSdk()) {\n throw new Error(\n 'Auth override specified in options, but not supported on non Node.js platforms'\n );\n }\n\n VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);\n\n if (repoInfo_.host.indexOf('fblocal') === -1) {\n OnlineMonitor.getInstance().on('online', this.onOnline_, this);\n }\n }\n\n protected sendRequest(\n action: string,\n body: unknown,\n onResponse?: (a: unknown) => void\n ) {\n const curReqNum = ++this.requestNumber_;\n\n const msg = { r: curReqNum, a: action, b: body };\n this.log_(stringify(msg));\n assert(\n this.connected_,\n \"sendRequest call when we're not connected not allowed.\"\n );\n this.realtime_.sendRequest(msg);\n if (onResponse) {\n this.requestCBHash_[curReqNum] = onResponse;\n }\n }\n\n get(query: QueryContext): Promise {\n this.initConnection_();\n\n const deferred = new Deferred();\n const request = {\n p: query._path.toString(),\n q: query._queryObject\n };\n const outstandingGet = {\n action: 'g',\n request,\n onComplete: (message: { [k: string]: unknown }) => {\n const payload = message['d'] as string;\n if (message['s'] === 'ok') {\n deferred.resolve(payload);\n } else {\n deferred.reject(payload);\n }\n }\n };\n this.outstandingGets_.push(outstandingGet);\n this.outstandingGetCount_++;\n const index = this.outstandingGets_.length - 1;\n\n if (this.connected_) {\n this.sendGet_(index);\n }\n\n return deferred.promise;\n }\n\n listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ) {\n this.initConnection_();\n\n const queryId = query._queryIdentifier;\n const pathString = query._path.toString();\n this.log_('Listen called for ' + pathString + ' ' + queryId);\n if (!this.listens.has(pathString)) {\n this.listens.set(pathString, new Map());\n }\n assert(\n query._queryParams.isDefault() || !query._queryParams.loadsAllData(),\n 'listen() called for non-default but complete query'\n );\n assert(\n !this.listens.get(pathString)!.has(queryId),\n `listen() called twice for same path/queryId.`\n );\n const listenSpec: ListenSpec = {\n onComplete,\n hashFn: currentHashFn,\n query,\n tag\n };\n this.listens.get(pathString)!.set(queryId, listenSpec);\n\n if (this.connected_) {\n this.sendListen_(listenSpec);\n }\n }\n\n private sendGet_(index: number) {\n const get = this.outstandingGets_[index];\n this.sendRequest('g', get.request, (message: { [k: string]: unknown }) => {\n delete this.outstandingGets_[index];\n this.outstandingGetCount_--;\n if (this.outstandingGetCount_ === 0) {\n this.outstandingGets_ = [];\n }\n if (get.onComplete) {\n get.onComplete(message);\n }\n });\n }\n\n private sendListen_(listenSpec: ListenSpec) {\n const query = listenSpec.query;\n const pathString = query._path.toString();\n const queryId = query._queryIdentifier;\n this.log_('Listen on ' + pathString + ' for ' + queryId);\n const req: { [k: string]: unknown } = { /*path*/ p: pathString };\n\n const action = 'q';\n\n // Only bother to send query if it's non-default.\n if (listenSpec.tag) {\n req['q'] = query._queryObject;\n req['t'] = listenSpec.tag;\n }\n\n req[/*hash*/ 'h'] = listenSpec.hashFn();\n\n this.sendRequest(action, req, (message: { [k: string]: unknown }) => {\n const payload: unknown = message[/*data*/ 'd'];\n const status = message[/*status*/ 's'] as string;\n\n // print warnings in any case...\n PersistentConnection.warnOnListenWarnings_(payload, query);\n\n const currentListenSpec =\n this.listens.get(pathString) &&\n this.listens.get(pathString)!.get(queryId);\n // only trigger actions if the listen hasn't been removed and readded\n if (currentListenSpec === listenSpec) {\n this.log_('listen response', message);\n\n if (status !== 'ok') {\n this.removeListen_(pathString, queryId);\n }\n\n if (listenSpec.onComplete) {\n listenSpec.onComplete(status, payload);\n }\n }\n });\n }\n\n private static warnOnListenWarnings_(payload: unknown, query: QueryContext) {\n if (payload && typeof payload === 'object' && contains(payload, 'w')) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const warnings = safeGet(payload as any, 'w');\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\n const indexSpec =\n '\".indexOn\": \"' + query._queryParams.getIndex().toString() + '\"';\n const indexPath = query._path.toString();\n warn(\n `Using an unspecified index. Your data will be downloaded and ` +\n `filtered on the client. Consider adding ${indexSpec} at ` +\n `${indexPath} to your security rules for better performance.`\n );\n }\n }\n }\n\n refreshAuthToken(token: string) {\n this.authToken_ = token;\n this.log_('Auth token refreshed');\n if (this.authToken_) {\n this.tryAuth();\n } else {\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\n //the credential so we dont become authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unauth', {}, () => {});\n }\n }\n\n this.reduceReconnectDelayIfAdminCredential_(token);\n }\n\n private reduceReconnectDelayIfAdminCredential_(credential: string) {\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\n const isFirebaseSecret = credential && credential.length === 40;\n if (isFirebaseSecret || isAdmin(credential)) {\n this.log_(\n 'Admin auth credential detected. Reducing max reconnect time.'\n );\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n }\n }\n\n refreshAppCheckToken(token: string | null) {\n this.appCheckToken_ = token;\n this.log_('App check token refreshed');\n if (this.appCheckToken_) {\n this.tryAppCheck();\n } else {\n //If we're connected we want to let the server know to unauthenticate us.\n //If we're not connected, simply delete the credential so we dont become\n // authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unappeck', {}, () => {});\n }\n }\n }\n\n /**\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\n * a auth revoked (the connection is closed).\n */\n tryAuth() {\n if (this.connected_ && this.authToken_) {\n const token = this.authToken_;\n const authMethod = isValidFormat(token) ? 'auth' : 'gauth';\n const requestData: { [k: string]: unknown } = { cred: token };\n if (this.authOverride_ === null) {\n requestData['noauth'] = true;\n } else if (typeof this.authOverride_ === 'object') {\n requestData['authvar'] = this.authOverride_;\n }\n this.sendRequest(\n authMethod,\n requestData,\n (res: { [k: string]: unknown }) => {\n const status = res[/*status*/ 's'] as string;\n const data = (res[/*data*/ 'd'] as string) || 'error';\n\n if (this.authToken_ === token) {\n if (status === 'ok') {\n this.invalidAuthTokenCount_ = 0;\n } else {\n // Triggers reconnect and force refresh for auth token\n this.onAuthRevoked_(status, data);\n }\n }\n }\n );\n }\n }\n\n /**\n * Attempts to authenticate with the given token. If the authentication\n * attempt fails, it's triggered like the token was revoked (the connection is\n * closed).\n */\n tryAppCheck() {\n if (this.connected_ && this.appCheckToken_) {\n this.sendRequest(\n 'appcheck',\n { 'token': this.appCheckToken_ },\n (res: { [k: string]: unknown }) => {\n const status = res[/*status*/ 's'] as string;\n const data = (res[/*data*/ 'd'] as string) || 'error';\n if (status === 'ok') {\n this.invalidAppCheckTokenCount_ = 0;\n } else {\n this.onAppCheckRevoked_(status, data);\n }\n }\n );\n }\n }\n\n /**\n * @inheritDoc\n */\n unlisten(query: QueryContext, tag: number | null) {\n const pathString = query._path.toString();\n const queryId = query._queryIdentifier;\n\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\n\n assert(\n query._queryParams.isDefault() || !query._queryParams.loadsAllData(),\n 'unlisten() called for non-default but complete query'\n );\n const listen = this.removeListen_(pathString, queryId);\n if (listen && this.connected_) {\n this.sendUnlisten_(pathString, queryId, query._queryObject, tag);\n }\n }\n\n private sendUnlisten_(\n pathString: string,\n queryId: string,\n queryObj: object,\n tag: number | null\n ) {\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\n\n const req: { [k: string]: unknown } = { /*path*/ p: pathString };\n const action = 'n';\n // Only bother sending queryId if it's non-default.\n if (tag) {\n req['q'] = queryObj;\n req['t'] = tag;\n }\n\n this.sendRequest(action, req);\n }\n\n onDisconnectPut(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\n\n if (this.connected_) {\n this.sendOnDisconnect_('o', pathString, data, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'o',\n data,\n onComplete\n });\n }\n }\n\n onDisconnectMerge(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\n\n if (this.connected_) {\n this.sendOnDisconnect_('om', pathString, data, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'om',\n data,\n onComplete\n });\n }\n }\n\n onDisconnectCancel(\n pathString: string,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\n\n if (this.connected_) {\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'oc',\n data: null,\n onComplete\n });\n }\n }\n\n private sendOnDisconnect_(\n action: string,\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string) => void\n ) {\n const request = { /*path*/ p: pathString, /*data*/ d: data };\n this.log_('onDisconnect ' + action, request);\n this.sendRequest(action, request, (response: { [k: string]: unknown }) => {\n if (onComplete) {\n setTimeout(() => {\n onComplete(\n response[/*status*/ 's'] as string,\n response[/* data */ 'd'] as string\n );\n }, Math.floor(0));\n }\n });\n }\n\n put(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void,\n hash?: string\n ) {\n this.putInternal('p', pathString, data, onComplete, hash);\n }\n\n merge(\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {\n this.putInternal('m', pathString, data, onComplete, hash);\n }\n\n putInternal(\n action: string,\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {\n this.initConnection_();\n\n const request: { [k: string]: unknown } = {\n /*path*/ p: pathString,\n /*data*/ d: data\n };\n\n if (hash !== undefined) {\n request[/*hash*/ 'h'] = hash;\n }\n\n // TODO: Only keep track of the most recent put for a given path?\n this.outstandingPuts_.push({\n action,\n request,\n onComplete\n });\n\n this.outstandingPutCount_++;\n const index = this.outstandingPuts_.length - 1;\n\n if (this.connected_) {\n this.sendPut_(index);\n } else {\n this.log_('Buffering put: ' + pathString);\n }\n }\n\n private sendPut_(index: number) {\n const action = this.outstandingPuts_[index].action;\n const request = this.outstandingPuts_[index].request;\n const onComplete = this.outstandingPuts_[index].onComplete;\n this.outstandingPuts_[index].queued = this.connected_;\n\n this.sendRequest(action, request, (message: { [k: string]: unknown }) => {\n this.log_(action + ' response', message);\n\n delete this.outstandingPuts_[index];\n this.outstandingPutCount_--;\n\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0) {\n this.outstandingPuts_ = [];\n }\n\n if (onComplete) {\n onComplete(\n message[/*status*/ 's'] as string,\n message[/* data */ 'd'] as string\n );\n }\n });\n }\n\n reportStats(stats: { [k: string]: unknown }) {\n // If we're not connected, we just drop the stats.\n if (this.connected_) {\n const request = { /*counters*/ c: stats };\n this.log_('reportStats', request);\n\n this.sendRequest(/*stats*/ 's', request, result => {\n const status = result[/*status*/ 's'];\n if (status !== 'ok') {\n const errorReason = result[/* data */ 'd'];\n this.log_('reportStats', 'Error sending stats: ' + errorReason);\n }\n });\n }\n }\n\n private onDataMessage_(message: { [k: string]: unknown }) {\n if ('r' in message) {\n // this is a response\n this.log_('from server: ' + stringify(message));\n const reqNum = message['r'] as string;\n const onResponse = this.requestCBHash_[reqNum];\n if (onResponse) {\n delete this.requestCBHash_[reqNum];\n onResponse(message[/*body*/ 'b']);\n }\n } else if ('error' in message) {\n throw 'A server-side error has occurred: ' + message['error'];\n } else if ('a' in message) {\n // a and b are action and body, respectively\n this.onDataPush_(message['a'] as string, message['b'] as {});\n }\n }\n\n private onDataPush_(action: string, body: { [k: string]: unknown }) {\n this.log_('handleServerMessage', action, body);\n if (action === 'd') {\n this.onDataUpdate_(\n body[/*path*/ 'p'] as string,\n body[/*data*/ 'd'],\n /*isMerge*/ false,\n body['t'] as number\n );\n } else if (action === 'm') {\n this.onDataUpdate_(\n body[/*path*/ 'p'] as string,\n body[/*data*/ 'd'],\n /*isMerge=*/ true,\n body['t'] as number\n );\n } else if (action === 'c') {\n this.onListenRevoked_(\n body[/*path*/ 'p'] as string,\n body[/*query*/ 'q'] as unknown[]\n );\n } else if (action === 'ac') {\n this.onAuthRevoked_(\n body[/*status code*/ 's'] as string,\n body[/* explanation */ 'd'] as string\n );\n } else if (action === 'apc') {\n this.onAppCheckRevoked_(\n body[/*status code*/ 's'] as string,\n body[/* explanation */ 'd'] as string\n );\n } else if (action === 'sd') {\n this.onSecurityDebugPacket_(body);\n } else {\n error(\n 'Unrecognized action received from server: ' +\n stringify(action) +\n '\\nAre you using the latest client?'\n );\n }\n }\n\n private onReady_(timestamp: number, sessionId: string) {\n this.log_('connection ready');\n this.connected_ = true;\n this.lastConnectionEstablishedTime_ = new Date().getTime();\n this.handleTimestamp_(timestamp);\n this.lastSessionId = sessionId;\n if (this.firstConnection_) {\n this.sendConnectStats_();\n }\n this.restoreState_();\n this.firstConnection_ = false;\n this.onConnectStatus_(true);\n }\n\n private scheduleConnect_(timeout: number) {\n assert(\n !this.realtime_,\n \"Scheduling a connect when we're already connected/ing?\"\n );\n\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n }\n\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\n\n this.establishConnectionTimer_ = setTimeout(() => {\n this.establishConnectionTimer_ = null;\n this.establishConnection_();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(timeout)) as any;\n }\n\n private initConnection_() {\n if (!this.realtime_ && this.firstConnection_) {\n this.scheduleConnect_(0);\n }\n }\n\n private onVisible_(visible: boolean) {\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\n if (\n visible &&\n !this.visible_ &&\n this.reconnectDelay_ === this.maxReconnectDelay_\n ) {\n this.log_('Window became visible. Reducing delay.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n this.visible_ = visible;\n }\n\n private onOnline_(online: boolean) {\n if (online) {\n this.log_('Browser went online.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n } else {\n this.log_('Browser went offline. Killing connection.');\n if (this.realtime_) {\n this.realtime_.close();\n }\n }\n }\n\n private onRealtimeDisconnect_() {\n this.log_('data client disconnected');\n this.connected_ = false;\n this.realtime_ = null;\n\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\n this.cancelSentTransactions_();\n\n // Clear out the pending requests.\n this.requestCBHash_ = {};\n\n if (this.shouldReconnect_()) {\n if (!this.visible_) {\n this.log_(\"Window isn't visible. Delaying reconnect.\");\n this.reconnectDelay_ = this.maxReconnectDelay_;\n this.lastConnectionAttemptTime_ = new Date().getTime();\n } else if (this.lastConnectionEstablishedTime_) {\n // If we've been connected long enough, reset reconnect delay to minimum.\n const timeSinceLastConnectSucceeded =\n new Date().getTime() - this.lastConnectionEstablishedTime_;\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n }\n this.lastConnectionEstablishedTime_ = null;\n }\n\n const timeSinceLastConnectAttempt = Math.max(\n 0,\n new Date().getTime() - this.lastConnectionAttemptTime_\n );\n let reconnectDelay = Math.max(\n 0,\n this.reconnectDelay_ - timeSinceLastConnectAttempt\n );\n reconnectDelay = Math.random() * reconnectDelay;\n\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\n this.scheduleConnect_(reconnectDelay);\n\n // Adjust reconnect delay for next time.\n this.reconnectDelay_ = Math.min(\n this.maxReconnectDelay_,\n this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER\n );\n }\n this.onConnectStatus_(false);\n }\n\n private async establishConnection_() {\n if (this.shouldReconnect_()) {\n this.log_('Making a connection attempt');\n this.lastConnectionAttemptTime_ = new Date().getTime();\n this.lastConnectionEstablishedTime_ = null;\n const onDataMessage = this.onDataMessage_.bind(this);\n const onReady = this.onReady_.bind(this);\n const onDisconnect = this.onRealtimeDisconnect_.bind(this);\n const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;\n const lastSessionId = this.lastSessionId;\n let canceled = false;\n let connection: Connection | null = null;\n const closeFn = function () {\n if (connection) {\n connection.close();\n } else {\n canceled = true;\n onDisconnect();\n }\n };\n const sendRequestFn = function (msg: object) {\n assert(\n connection,\n \"sendRequest call when we're not connected not allowed.\"\n );\n connection.sendRequest(msg);\n };\n\n this.realtime_ = {\n close: closeFn,\n sendRequest: sendRequestFn\n };\n\n const forceRefresh = this.forceTokenRefresh_;\n this.forceTokenRefresh_ = false;\n\n try {\n // First fetch auth and app check token, and establish connection after\n // fetching the token was successful\n const [authToken, appCheckToken] = await Promise.all([\n this.authTokenProvider_.getToken(forceRefresh),\n this.appCheckTokenProvider_.getToken(forceRefresh)\n ]);\n\n if (!canceled) {\n log('getToken() completed. Creating connection.');\n this.authToken_ = authToken && authToken.accessToken;\n this.appCheckToken_ = appCheckToken && appCheckToken.token;\n connection = new Connection(\n connId,\n this.repoInfo_,\n this.applicationId_,\n this.appCheckToken_,\n this.authToken_,\n onDataMessage,\n onReady,\n onDisconnect,\n /* onKill= */ reason => {\n warn(reason + ' (' + this.repoInfo_.toString() + ')');\n this.interrupt(SERVER_KILL_INTERRUPT_REASON);\n },\n lastSessionId\n );\n } else {\n log('getToken() completed but was canceled');\n }\n } catch (error) {\n this.log_('Failed to get token: ' + error);\n if (!canceled) {\n if (this.repoInfo_.nodeAdmin) {\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\n // But getToken() may also just have temporarily failed, so we still want to\n // continue retrying.\n warn(error);\n }\n closeFn();\n }\n }\n }\n }\n\n interrupt(reason: string) {\n log('Interrupting connection for reason: ' + reason);\n this.interruptReasons_[reason] = true;\n if (this.realtime_) {\n this.realtime_.close();\n } else {\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n this.establishConnectionTimer_ = null;\n }\n if (this.connected_) {\n this.onRealtimeDisconnect_();\n }\n }\n }\n\n resume(reason: string) {\n log('Resuming connection for reason: ' + reason);\n delete this.interruptReasons_[reason];\n if (isEmpty(this.interruptReasons_)) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n }\n\n private handleTimestamp_(timestamp: number) {\n const delta = timestamp - new Date().getTime();\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\n }\n\n private cancelSentTransactions_() {\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\n const put = this.outstandingPuts_[i];\n if (put && /*hash*/ 'h' in put.request && put.queued) {\n if (put.onComplete) {\n put.onComplete('disconnect');\n }\n\n delete this.outstandingPuts_[i];\n this.outstandingPutCount_--;\n }\n }\n\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0) {\n this.outstandingPuts_ = [];\n }\n }\n\n private onListenRevoked_(pathString: string, query?: unknown[]) {\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\n let queryId;\n if (!query) {\n queryId = 'default';\n } else {\n queryId = query.map(q => ObjectToUniqueKey(q)).join('$');\n }\n const listen = this.removeListen_(pathString, queryId);\n if (listen && listen.onComplete) {\n listen.onComplete('permission_denied');\n }\n }\n\n private removeListen_(pathString: string, queryId: string): ListenSpec {\n const normalizedPathString = new Path(pathString).toString(); // normalize path.\n let listen;\n if (this.listens.has(normalizedPathString)) {\n const map = this.listens.get(normalizedPathString)!;\n listen = map.get(queryId);\n map.delete(queryId);\n if (map.size === 0) {\n this.listens.delete(normalizedPathString);\n }\n } else {\n // all listens for this path has already been removed\n listen = undefined;\n }\n return listen;\n }\n\n private onAuthRevoked_(statusCode: string, explanation: string) {\n log('Auth token revoked: ' + statusCode + '/' + explanation);\n this.authToken_ = null;\n this.forceTokenRefresh_ = true;\n this.realtime_.close();\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAuthTokenCount_++;\n if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\n // Set a long reconnect delay because recovery is unlikely\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n\n // Notify the auth token provider that the token is invalid, which will log\n // a warning\n this.authTokenProvider_.notifyForInvalidToken();\n }\n }\n }\n\n private onAppCheckRevoked_(statusCode: string, explanation: string) {\n log('App check token revoked: ' + statusCode + '/' + explanation);\n this.appCheckToken_ = null;\n this.forceTokenRefresh_ = true;\n // Note: We don't close the connection as the developer may not have\n // enforcement enabled. The backend closes connections with enforcements.\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAppCheckTokenCount_++;\n if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\n this.appCheckTokenProvider_.notifyForInvalidToken();\n }\n }\n }\n\n private onSecurityDebugPacket_(body: { [k: string]: unknown }) {\n if (this.securityDebugCallback_) {\n this.securityDebugCallback_(body);\n } else {\n if ('msg' in body) {\n console.log(\n 'FIREBASE: ' + (body['msg'] as string).replace('\\n', '\\nFIREBASE: ')\n );\n }\n }\n }\n\n private restoreState_() {\n //Re-authenticate ourselves if we have a credential stored.\n this.tryAuth();\n this.tryAppCheck();\n\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\n // make sure to send listens before puts.\n for (const queries of this.listens.values()) {\n for (const listenSpec of queries.values()) {\n this.sendListen_(listenSpec);\n }\n }\n\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\n if (this.outstandingPuts_[i]) {\n this.sendPut_(i);\n }\n }\n\n while (this.onDisconnectRequestQueue_.length) {\n const request = this.onDisconnectRequestQueue_.shift();\n this.sendOnDisconnect_(\n request.action,\n request.pathString,\n request.data,\n request.onComplete\n );\n }\n\n for (let i = 0; i < this.outstandingGets_.length; i++) {\n if (this.outstandingGets_[i]) {\n this.sendGet_(i);\n }\n }\n }\n\n /**\n * Sends client stats for first connection\n */\n private sendConnectStats_() {\n const stats: { [k: string]: number } = {};\n\n let clientName = 'js';\n if (isNodeSdk()) {\n if (this.repoInfo_.nodeAdmin) {\n clientName = 'admin_node';\n } else {\n clientName = 'node';\n }\n }\n\n stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\\./g, '-')] = 1;\n\n if (isMobileCordova()) {\n stats['framework.cordova'] = 1;\n } else if (isReactNative()) {\n stats['framework.reactnative'] = 1;\n }\n this.reportStats(stats);\n }\n\n private shouldReconnect_(): boolean {\n const online = OnlineMonitor.getInstance().currentlyOnline();\n return isEmpty(this.interruptReasons_) && online;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Path } from '../util/Path';\n\nimport { Index } from './indexes/Index';\n\n/**\n * Node is an interface defining the common functionality for nodes in\n * a DataSnapshot.\n *\n * @interface\n */\nexport interface Node {\n /**\n * Whether this node is a leaf node.\n * @returns Whether this is a leaf node.\n */\n isLeafNode(): boolean;\n\n /**\n * Gets the priority of the node.\n * @returns The priority of the node.\n */\n getPriority(): Node;\n\n /**\n * Returns a duplicate node with the new priority.\n * @param newPriorityNode - New priority to set for the node.\n * @returns Node with new priority.\n */\n updatePriority(newPriorityNode: Node): Node;\n\n /**\n * Returns the specified immediate child, or null if it doesn't exist.\n * @param childName - The name of the child to retrieve.\n * @returns The retrieved child, or an empty node.\n */\n getImmediateChild(childName: string): Node;\n\n /**\n * Returns a child by path, or null if it doesn't exist.\n * @param path - The path of the child to retrieve.\n * @returns The retrieved child or an empty node.\n */\n getChild(path: Path): Node;\n\n /**\n * Returns the name of the child immediately prior to the specified childNode, or null.\n * @param childName - The name of the child to find the predecessor of.\n * @param childNode - The node to find the predecessor of.\n * @param index - The index to use to determine the predecessor\n * @returns The name of the predecessor child, or null if childNode is the first child.\n */\n getPredecessorChildName(\n childName: string,\n childNode: Node,\n index: Index\n ): string | null;\n\n /**\n * Returns a duplicate node, with the specified immediate child updated.\n * Any value in the node will be removed.\n * @param childName - The name of the child to update.\n * @param newChildNode - The new child node\n * @returns The updated node.\n */\n updateImmediateChild(childName: string, newChildNode: Node): Node;\n\n /**\n * Returns a duplicate node, with the specified child updated. Any value will\n * be removed.\n * @param path - The path of the child to update.\n * @param newChildNode - The new child node, which may be an empty node\n * @returns The updated node.\n */\n updateChild(path: Path, newChildNode: Node): Node;\n\n /**\n * True if the immediate child specified exists\n */\n hasChild(childName: string): boolean;\n\n /**\n * @returns True if this node has no value or children.\n */\n isEmpty(): boolean;\n\n /**\n * @returns The number of children of this node.\n */\n numChildren(): number;\n\n /**\n * Calls action for each child.\n * @param action - Action to be called for\n * each child. It's passed the child name and the child node.\n * @returns The first truthy value return by action, or the last falsey one\n */\n forEachChild(index: Index, action: (a: string, b: Node) => void): unknown;\n\n /**\n * @param exportFormat - True for export format (also wire protocol format).\n * @returns Value of this node as JSON.\n */\n val(exportFormat?: boolean): unknown;\n\n /**\n * @returns hash representing the node contents.\n */\n hash(): string;\n\n /**\n * @param other - Another node\n * @returns -1 for less than, 0 for equal, 1 for greater than other\n */\n compareTo(other: Node): number;\n\n /**\n * @returns Whether or not this snapshot equals other\n */\n equals(other: Node): boolean;\n\n /**\n * @returns This node, with the specified index now available\n */\n withIndex(indexDefinition: Index): Node;\n\n isIndexed(indexDefinition: Index): boolean;\n}\n\nexport class NamedNode {\n constructor(public name: string, public node: Node) {}\n\n static Wrap(name: string, node: Node) {\n return new NamedNode(name, node);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Comparator } from '../../util/SortedMap';\nimport { MIN_NAME } from '../../util/util';\nimport { Node, NamedNode } from '../Node';\n\nexport abstract class Index {\n abstract compare(a: NamedNode, b: NamedNode): number;\n\n abstract isDefinedOn(node: Node): boolean;\n\n /**\n * @returns A standalone comparison function for\n * this index\n */\n getCompare(): Comparator {\n return this.compare.bind(this);\n }\n\n /**\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\n *\n *\n * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode\n */\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n const oldWrapped = new NamedNode(MIN_NAME, oldNode);\n const newWrapped = new NamedNode(MIN_NAME, newNode);\n return this.compare(oldWrapped, newWrapped) !== 0;\n }\n\n /**\n * @returns a node wrapper that will sort equal to or less than\n * any other node wrapper, using this index\n */\n minPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n\n /**\n * @returns a node wrapper that will sort greater than or equal to\n * any other node wrapper, using this index\n */\n abstract maxPost(): NamedNode;\n\n abstract makePost(indexValue: unknown, name: string): NamedNode;\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n abstract toString(): string;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport { nameCompare, MAX_NAME } from '../../util/util';\nimport { ChildrenNode } from '../ChildrenNode';\nimport { Node, NamedNode } from '../Node';\n\nimport { Index } from './Index';\n\nlet __EMPTY_NODE: ChildrenNode;\n\nexport class KeyIndex extends Index {\n static get __EMPTY_NODE() {\n return __EMPTY_NODE;\n }\n\n static set __EMPTY_NODE(val) {\n __EMPTY_NODE = val;\n }\n compare(a: NamedNode, b: NamedNode): number {\n return nameCompare(a.name, b.name);\n }\n isDefinedOn(node: Node): boolean {\n // We could probably return true here (since every node has a key), but it's never called\n // so just leaving unimplemented for now.\n throw assertionError('KeyIndex.isDefinedOn not expected to be called.');\n }\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return false; // The key for a node never changes.\n }\n minPost() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n maxPost(): NamedNode {\n // TODO: This should really be created once and cached in a static property, but\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\n return new NamedNode(MAX_NAME, __EMPTY_NODE);\n }\n\n makePost(indexValue: string, name: string): NamedNode {\n assert(\n typeof indexValue === 'string',\n 'KeyIndex indexValue must always be a string.'\n );\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\n return new NamedNode(indexValue, __EMPTY_NODE);\n }\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString(): string {\n return '.key';\n }\n}\n\nexport const KEY_INDEX = new KeyIndex();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Implementation of an immutable SortedMap using a Left-leaning\n * Red-Black Tree, adapted from the implementation in Mugs\n * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen\n * (mads379\\@gmail.com).\n *\n * Original paper on Left-leaning Red-Black Trees:\n * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf\n *\n * Invariant 1: No red node has a red child\n * Invariant 2: Every leaf path has the same number of black nodes\n * Invariant 3: Only the left child can be red (left leaning)\n */\n\n// TODO: There are some improvements I'd like to make to improve memory / perf:\n// * Create two prototypes, LLRedNode and LLBlackNode, instead of storing a\n// color property in every node.\n// TODO: It would also be good (and possibly necessary) to create a base\n// interface for LLRBNode and LLRBEmptyNode.\n\nexport type Comparator = (key1: K, key2: K) => number;\n\n/**\n * An iterator over an LLRBNode.\n */\nexport class SortedMapIterator {\n private nodeStack_: Array | LLRBEmptyNode> = [];\n\n /**\n * @param node - Node to iterate.\n * @param isReverse_ - Whether or not to iterate in reverse\n */\n constructor(\n node: LLRBNode | LLRBEmptyNode,\n startKey: K | null,\n comparator: Comparator,\n private isReverse_: boolean,\n private resultGenerator_: ((k: K, v: V) => T) | null = null\n ) {\n let cmp = 1;\n while (!node.isEmpty()) {\n node = node as LLRBNode;\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse_) {\n cmp *= -1;\n }\n\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse_) {\n node = node.left;\n } else {\n node = node.right;\n }\n } else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\n this.nodeStack_.push(node);\n break;\n } else {\n // This node is greater than our start key, add it to the stack and move to the next one\n this.nodeStack_.push(node);\n if (this.isReverse_) {\n node = node.right;\n } else {\n node = node.left;\n }\n }\n }\n }\n\n getNext(): T {\n if (this.nodeStack_.length === 0) {\n return null;\n }\n\n let node = this.nodeStack_.pop();\n let result: T;\n if (this.resultGenerator_) {\n result = this.resultGenerator_(node.key, node.value);\n } else {\n result = { key: node.key, value: node.value } as unknown as T;\n }\n\n if (this.isReverse_) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.right;\n }\n } else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.left;\n }\n }\n\n return result;\n }\n\n hasNext(): boolean {\n return this.nodeStack_.length > 0;\n }\n\n peek(): T {\n if (this.nodeStack_.length === 0) {\n return null;\n }\n\n const node = this.nodeStack_[this.nodeStack_.length - 1];\n if (this.resultGenerator_) {\n return this.resultGenerator_(node.key, node.value);\n } else {\n return { key: node.key, value: node.value } as unknown as T;\n }\n }\n}\n\n/**\n * Represents a node in a Left-leaning Red-Black tree.\n */\nexport class LLRBNode {\n color: boolean;\n left: LLRBNode | LLRBEmptyNode;\n right: LLRBNode | LLRBEmptyNode;\n\n /**\n * @param key - Key associated with this node.\n * @param value - Value associated with this node.\n * @param color - Whether this node is red.\n * @param left - Left child.\n * @param right - Right child.\n */\n constructor(\n public key: K,\n public value: V,\n color: boolean | null,\n left?: LLRBNode | LLRBEmptyNode | null,\n right?: LLRBNode | LLRBEmptyNode | null\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left =\n left != null ? left : (SortedMap.EMPTY_NODE as LLRBEmptyNode);\n this.right =\n right != null ? right : (SortedMap.EMPTY_NODE as LLRBEmptyNode);\n }\n\n static RED = true;\n static BLACK = false;\n\n /**\n * Returns a copy of the current node, optionally replacing pieces of it.\n *\n * @param key - New key for the node, or null.\n * @param value - New value for the node, or null.\n * @param color - New color for the node, or null.\n * @param left - New left child for the node, or null.\n * @param right - New right child for the node, or null.\n * @returns The node copy.\n */\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBNode {\n return new LLRBNode(\n key != null ? key : this.key,\n value != null ? value : this.value,\n color != null ? color : this.color,\n left != null ? left : this.left,\n right != null ? right : this.right\n );\n }\n\n /**\n * @returns The total number of nodes in the tree.\n */\n count(): number {\n return this.left.count() + 1 + this.right.count();\n }\n\n /**\n * @returns True if the tree is empty.\n */\n isEmpty(): boolean {\n return false;\n }\n\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n inorderTraversal(action: (k: K, v: V) => unknown): boolean {\n return (\n this.left.inorderTraversal(action) ||\n !!action(this.key, this.value) ||\n this.right.inorderTraversal(action)\n );\n }\n\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n reverseTraversal(action: (k: K, v: V) => void): boolean {\n return (\n this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action)\n );\n }\n\n /**\n * @returns The minimum node in the tree.\n */\n private min_(): LLRBNode {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode).min_();\n }\n }\n\n /**\n * @returns The maximum key in the tree.\n */\n minKey(): K {\n return this.min_().key;\n }\n\n /**\n * @returns The maximum key in the tree.\n */\n maxKey(): K {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\n }\n\n /**\n * @param key - Key to insert.\n * @param value - Value to insert.\n * @param comparator - Comparator.\n * @returns New tree, with the key/value added.\n */\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n let n: LLRBNode = this;\n const cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n } else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n } else {\n n = n.copy(\n null,\n null,\n null,\n null,\n n.right.insert(key, value, comparator)\n );\n }\n return n.fixUp_();\n }\n\n /**\n * @returns New tree, with the minimum key removed.\n */\n private removeMin_(): LLRBNode | LLRBEmptyNode {\n if (this.left.isEmpty()) {\n return SortedMap.EMPTY_NODE as LLRBEmptyNode;\n }\n let n: LLRBNode = this;\n if (!n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, (n.left as LLRBNode).removeMin_(), null);\n return n.fixUp_();\n }\n\n /**\n * @param key - The key of the item to remove.\n * @param comparator - Comparator.\n * @returns New tree, with the specified item removed.\n */\n remove(\n key: K,\n comparator: Comparator\n ): LLRBNode | LLRBEmptyNode {\n let n, smallest;\n n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n } else {\n if (n.left.isRed_()) {\n n = n.rotateRight_();\n }\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\n n = n.moveRedRight_();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return SortedMap.EMPTY_NODE as LLRBEmptyNode;\n } else {\n smallest = (n.right as LLRBNode).min_();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode).removeMin_()\n );\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp_();\n }\n\n /**\n * @returns Whether this is a RED node.\n */\n isRed_(): boolean {\n return this.color;\n }\n\n /**\n * @returns New tree after performing any needed rotations.\n */\n private fixUp_(): LLRBNode {\n let n: LLRBNode = this;\n if (n.right.isRed_() && !n.left.isRed_()) {\n n = n.rotateLeft_();\n }\n if (n.left.isRed_() && n.left.left.isRed_()) {\n n = n.rotateRight_();\n }\n if (n.left.isRed_() && n.right.isRed_()) {\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @returns New tree, after moveRedLeft.\n */\n private moveRedLeft_(): LLRBNode {\n let n = this.colorFlip_();\n if (n.right.left.isRed_()) {\n n = n.copy(\n null,\n null,\n null,\n null,\n (n.right as LLRBNode).rotateRight_()\n );\n n = n.rotateLeft_();\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @returns New tree, after moveRedRight.\n */\n private moveRedRight_(): LLRBNode {\n let n = this.colorFlip_();\n if (n.left.left.isRed_()) {\n n = n.rotateRight_();\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @returns New tree, after rotateLeft.\n */\n private rotateLeft_(): LLRBNode {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null) as LLRBNode;\n }\n\n /**\n * @returns New tree, after rotateRight.\n */\n private rotateRight_(): LLRBNode {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr) as LLRBNode;\n }\n\n /**\n * @returns Newt ree, after colorFlip.\n */\n private colorFlip_(): LLRBNode {\n const left = this.left.copy(null, null, !this.left.color, null, null);\n const right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n }\n\n /**\n * For testing.\n *\n * @returns True if all is well.\n */\n private checkMaxDepth_(): boolean {\n const blackDepth = this.check_();\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\n }\n\n check_(): number {\n if (this.isRed_() && this.left.isRed_()) {\n throw new Error(\n 'Red node has red child(' + this.key + ',' + this.value + ')'\n );\n }\n if (this.right.isRed_()) {\n throw new Error(\n 'Right child of (' + this.key + ',' + this.value + ') is red'\n );\n }\n const blackDepth = this.left.check_();\n if (blackDepth !== this.right.check_()) {\n throw new Error('Black depths differ');\n } else {\n return blackDepth + (this.isRed_() ? 0 : 1);\n }\n }\n}\n\n/**\n * Represents an empty node (a leaf node in the Red-Black Tree).\n */\nexport class LLRBEmptyNode {\n key: K;\n value: V;\n left: LLRBNode | LLRBEmptyNode;\n right: LLRBNode | LLRBEmptyNode;\n color: boolean;\n\n /**\n * Returns a copy of the current node.\n *\n * @returns The node copy.\n */\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBEmptyNode {\n return this;\n }\n\n /**\n * Returns a copy of the tree, with the specified key/value added.\n *\n * @param key - Key to be added.\n * @param value - Value to be added.\n * @param comparator - Comparator.\n * @returns New tree, with item added.\n */\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n return new LLRBNode(key, value, null);\n }\n\n /**\n * Returns a copy of the tree, with the specified key removed.\n *\n * @param key - The key to remove.\n * @param comparator - Comparator.\n * @returns New tree, with item removed.\n */\n remove(key: K, comparator: Comparator): LLRBEmptyNode {\n return this;\n }\n\n /**\n * @returns The total number of nodes in the tree.\n */\n count(): number {\n return 0;\n }\n\n /**\n * @returns True if the tree is empty.\n */\n isEmpty(): boolean {\n return true;\n }\n\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n inorderTraversal(action: (k: K, v: V) => unknown): boolean {\n return false;\n }\n\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n reverseTraversal(action: (k: K, v: V) => void): boolean {\n return false;\n }\n\n minKey(): null {\n return null;\n }\n\n maxKey(): null {\n return null;\n }\n\n check_(): number {\n return 0;\n }\n\n /**\n * @returns Whether this node is red.\n */\n isRed_() {\n return false;\n }\n}\n\n/**\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\n * tree.\n */\nexport class SortedMap {\n /**\n * Always use the same empty node, to reduce memory.\n */\n static EMPTY_NODE = new LLRBEmptyNode();\n\n /**\n * @param comparator_ - Key comparator.\n * @param root_ - Optional root node for the map.\n */\n constructor(\n private comparator_: Comparator,\n private root_:\n | LLRBNode\n | LLRBEmptyNode = SortedMap.EMPTY_NODE as LLRBEmptyNode\n ) {}\n\n /**\n * Returns a copy of the map, with the specified key/value added or replaced.\n * (TODO: We should perhaps rename this method to 'put')\n *\n * @param key - Key to be added.\n * @param value - Value to be added.\n * @returns New map, with item added.\n */\n insert(key: K, value: V): SortedMap {\n return new SortedMap(\n this.comparator_,\n this.root_\n .insert(key, value, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n /**\n * Returns a copy of the map, with the specified key removed.\n *\n * @param key - The key to remove.\n * @returns New map, with item removed.\n */\n remove(key: K): SortedMap {\n return new SortedMap(\n this.comparator_,\n this.root_\n .remove(key, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n /**\n * Returns the value of the node with the given key, or null.\n *\n * @param key - The key to look up.\n * @returns The value of the node with the given key, or null if the\n * key doesn't exist.\n */\n get(key: K): V | null {\n let cmp;\n let node = this.root_;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n return node.value;\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n }\n\n /**\n * Returns the key of the item *before* the specified key, or null if key is the first item.\n * @param key - The key to find the predecessor of\n * @returns The predecessor key.\n */\n getPredecessorKey(key: K): K | null {\n let cmp,\n node = this.root_,\n rightParent = null;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n if (!node.left.isEmpty()) {\n node = node.left;\n while (!node.right.isEmpty()) {\n node = node.right;\n }\n return node.key;\n } else if (rightParent) {\n return rightParent.key;\n } else {\n return null; // first item.\n }\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n\n throw new Error(\n 'Attempted to find predecessor key for a nonexistent key. What gives?'\n );\n }\n\n /**\n * @returns True if the map is empty.\n */\n isEmpty(): boolean {\n return this.root_.isEmpty();\n }\n\n /**\n * @returns The total number of nodes in the map.\n */\n count(): number {\n return this.root_.count();\n }\n\n /**\n * @returns The minimum key in the map.\n */\n minKey(): K | null {\n return this.root_.minKey();\n }\n\n /**\n * @returns The maximum key in the map.\n */\n maxKey(): K | null {\n return this.root_.maxKey();\n }\n\n /**\n * Traverses the map in key order and calls the specified action function\n * for each key/value pair.\n *\n * @param action - Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @returns The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n inorderTraversal(action: (k: K, v: V) => unknown): boolean {\n return this.root_.inorderTraversal(action);\n }\n\n /**\n * Traverses the map in reverse key order and calls the specified action function\n * for each key/value pair.\n *\n * @param action - Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @returns True if the traversal was aborted.\n */\n reverseTraversal(action: (k: K, v: V) => void): boolean {\n return this.root_.reverseTraversal(action);\n }\n\n /**\n * Returns an iterator over the SortedMap.\n * @returns The iterator.\n */\n getIterator(\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n null,\n this.comparator_,\n false,\n resultGenerator\n );\n }\n\n getIteratorFrom(\n key: K,\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n key,\n this.comparator_,\n false,\n resultGenerator\n );\n }\n\n getReverseIteratorFrom(\n key: K,\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n key,\n this.comparator_,\n true,\n resultGenerator\n );\n }\n\n getReverseIterator(\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n null,\n this.comparator_,\n true,\n resultGenerator\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare } from '../util/util';\n\nimport { NamedNode } from './Node';\n\nexport function NAME_ONLY_COMPARATOR(left: NamedNode, right: NamedNode) {\n return nameCompare(left.name, right.name);\n}\n\nexport function NAME_COMPARATOR(left: string, right: string) {\n return nameCompare(left, right);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, contains } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport { doubleToIEEE754String } from '../util/util';\n\nimport { Node } from './Node';\n\nlet MAX_NODE: Node;\n\nexport function setMaxNode(val: Node) {\n MAX_NODE = val;\n}\n\nexport const priorityHashText = function (priority: string | number): string {\n if (typeof priority === 'number') {\n return 'number:' + doubleToIEEE754String(priority);\n } else {\n return 'string:' + priority;\n }\n};\n\n/**\n * Validates that a priority snapshot Node is valid.\n */\nexport const validatePriorityNode = function (priorityNode: Node) {\n if (priorityNode.isLeafNode()) {\n const val = priorityNode.val();\n assert(\n typeof val === 'string' ||\n typeof val === 'number' ||\n (typeof val === 'object' && contains(val as Indexable, '.sv')),\n 'Priority must be a string or number.'\n );\n } else {\n assert(\n priorityNode === MAX_NODE || priorityNode.isEmpty(),\n 'priority of unexpected type.'\n );\n }\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\n assert(\n priorityNode === MAX_NODE || priorityNode.getPriority().isEmpty(),\n \"Priority nodes can't have a priority of their own.\"\n );\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport {\n Path,\n pathGetFront,\n pathGetLength,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\nimport { doubleToIEEE754String, sha1 } from '../util/util';\n\nimport { ChildrenNodeConstructor } from './ChildrenNode';\nimport { Index } from './indexes/Index';\nimport { Node } from './Node';\nimport { priorityHashText, validatePriorityNode } from './snap';\n\nlet __childrenNodeConstructor: ChildrenNodeConstructor;\n\n/**\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\n * implements Node and stores the value of the node (a string,\n * number, or boolean) accessible via getValue().\n */\nexport class LeafNode implements Node {\n static set __childrenNodeConstructor(val: ChildrenNodeConstructor) {\n __childrenNodeConstructor = val;\n }\n\n static get __childrenNodeConstructor() {\n return __childrenNodeConstructor;\n }\n\n /**\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\n * the same type, the comparison falls back to their value\n */\n static VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n\n private lazyHash_: string | null = null;\n\n /**\n * @param value_ - The value to store in this leaf node. The object type is\n * possible in the event of a deferred value\n * @param priorityNode_ - The priority of this node.\n */\n constructor(\n private readonly value_: string | number | boolean | Indexable,\n private priorityNode_: Node = LeafNode.__childrenNodeConstructor.EMPTY_NODE\n ) {\n assert(\n this.value_ !== undefined && this.value_ !== null,\n \"LeafNode shouldn't be created with null/undefined value.\"\n );\n\n validatePriorityNode(this.priorityNode_);\n }\n\n /** @inheritDoc */\n isLeafNode(): boolean {\n return true;\n }\n\n /** @inheritDoc */\n getPriority(): Node {\n return this.priorityNode_;\n }\n\n /** @inheritDoc */\n updatePriority(newPriorityNode: Node): Node {\n return new LeafNode(this.value_, newPriorityNode);\n }\n\n /** @inheritDoc */\n getImmediateChild(childName: string): Node {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.priorityNode_;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n }\n\n /** @inheritDoc */\n getChild(path: Path): Node {\n if (pathIsEmpty(path)) {\n return this;\n } else if (pathGetFront(path) === '.priority') {\n return this.priorityNode_;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n }\n hasChild(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n getPredecessorChildName(childName: string, childNode: Node): null {\n return null;\n }\n\n /** @inheritDoc */\n updateImmediateChild(childName: string, newChildNode: Node): Node {\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n } else if (newChildNode.isEmpty() && childName !== '.priority') {\n return this;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(\n childName,\n newChildNode\n ).updatePriority(this.priorityNode_);\n }\n }\n\n /** @inheritDoc */\n updateChild(path: Path, newChildNode: Node): Node {\n const front = pathGetFront(path);\n if (front === null) {\n return newChildNode;\n } else if (newChildNode.isEmpty() && front !== '.priority') {\n return this;\n } else {\n assert(\n front !== '.priority' || pathGetLength(path) === 1,\n '.priority must be the last token in a path'\n );\n\n return this.updateImmediateChild(\n front,\n LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(\n pathPopFront(path),\n newChildNode\n )\n );\n }\n }\n\n /** @inheritDoc */\n isEmpty(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n numChildren(): number {\n return 0;\n }\n\n /** @inheritDoc */\n forEachChild(index: Index, action: (s: string, n: Node) => void): boolean {\n return false;\n }\n val(exportFormat?: boolean): {} {\n if (exportFormat && !this.getPriority().isEmpty()) {\n return {\n '.value': this.getValue(),\n '.priority': this.getPriority().val()\n };\n } else {\n return this.getValue();\n }\n }\n\n /** @inheritDoc */\n hash(): string {\n if (this.lazyHash_ === null) {\n let toHash = '';\n if (!this.priorityNode_.isEmpty()) {\n toHash +=\n 'priority:' +\n priorityHashText(this.priorityNode_.val() as number | string) +\n ':';\n }\n\n const type = typeof this.value_;\n toHash += type + ':';\n if (type === 'number') {\n toHash += doubleToIEEE754String(this.value_ as number);\n } else {\n toHash += this.value_;\n }\n this.lazyHash_ = sha1(toHash);\n }\n return this.lazyHash_;\n }\n\n /**\n * Returns the value of the leaf node.\n * @returns The value of the node.\n */\n getValue(): Indexable | string | number | boolean {\n return this.value_;\n }\n compareTo(other: Node): number {\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\n return 1;\n } else if (other instanceof LeafNode.__childrenNodeConstructor) {\n return -1;\n } else {\n assert(other.isLeafNode(), 'Unknown node type');\n return this.compareToLeafNode_(other as LeafNode);\n }\n }\n\n /**\n * Comparison specifically for two leaf nodes\n */\n private compareToLeafNode_(otherLeaf: LeafNode): number {\n const otherLeafType = typeof otherLeaf.value_;\n const thisLeafType = typeof this.value_;\n const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\n const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\n assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\n assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\n if (otherIndex === thisIndex) {\n // Same type, compare values\n if (thisLeafType === 'object') {\n // Deferred value nodes are all equal, but we should also never get to this point...\n return 0;\n } else {\n // Note that this works because true > false, all others are number or string comparisons\n if (this.value_ < otherLeaf.value_) {\n return -1;\n } else if (this.value_ === otherLeaf.value_) {\n return 0;\n } else {\n return 1;\n }\n }\n } else {\n return thisIndex - otherIndex;\n }\n }\n withIndex(): Node {\n return this;\n }\n isIndexed(): boolean {\n return true;\n }\n equals(other: Node): boolean {\n if (other === this) {\n return true;\n } else if (other.isLeafNode()) {\n const otherLeaf = other as LeafNode;\n return (\n this.value_ === otherLeaf.value_ &&\n this.priorityNode_.equals(otherLeaf.priorityNode_)\n );\n } else {\n return false;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare, MAX_NAME } from '../../util/util';\nimport { LeafNode } from '../LeafNode';\nimport { NamedNode, Node } from '../Node';\n\nimport { Index } from './Index';\n\nlet nodeFromJSON: (a: unknown) => Node;\nlet MAX_NODE: Node;\n\nexport function setNodeFromJSON(val: (a: unknown) => Node) {\n nodeFromJSON = val;\n}\n\nexport function setMaxNode(val: Node) {\n MAX_NODE = val;\n}\n\nexport class PriorityIndex extends Index {\n compare(a: NamedNode, b: NamedNode): number {\n const aPriority = a.node.getPriority();\n const bPriority = b.node.getPriority();\n const indexCmp = aPriority.compareTo(bPriority);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n isDefinedOn(node: Node): boolean {\n return !node.getPriority().isEmpty();\n }\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return !oldNode.getPriority().equals(newNode.getPriority());\n }\n minPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n maxPost(): NamedNode {\n return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE));\n }\n\n makePost(indexValue: unknown, name: string): NamedNode {\n const priorityNode = nodeFromJSON(indexValue);\n return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));\n }\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString(): string {\n return '.priority';\n }\n}\n\nexport const PRIORITY_INDEX = new PriorityIndex();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LLRBNode, SortedMap } from '../util/SortedMap';\n\nimport { NamedNode } from './Node';\n\nconst LOG_2 = Math.log(2);\n\nclass Base12Num {\n count: number;\n private current_: number;\n private bits_: number;\n\n constructor(length: number) {\n const logBase2 = (num: number) =>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parseInt((Math.log(num) / LOG_2) as any, 10);\n const bitMask = (bits: number) => parseInt(Array(bits + 1).join('1'), 2);\n this.count = logBase2(length + 1);\n this.current_ = this.count - 1;\n const mask = bitMask(this.count);\n this.bits_ = (length + 1) & mask;\n }\n\n nextBitIsOne(): boolean {\n //noinspection JSBitwiseOperatorUsage\n const result = !(this.bits_ & (0x1 << this.current_));\n this.current_--;\n return result;\n }\n}\n\n/**\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\n * function\n *\n * Uses the algorithm described in the paper linked here:\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\n *\n * @param childList - Unsorted list of children\n * @param cmp - The comparison method to be used\n * @param keyFn - An optional function to extract K from a node wrapper, if K's\n * type is not NamedNode\n * @param mapSortFn - An optional override for comparator used by the generated sorted map\n */\nexport const buildChildSet = function (\n childList: NamedNode[],\n cmp: (a: NamedNode, b: NamedNode) => number,\n keyFn?: (a: NamedNode) => K,\n mapSortFn?: (a: K, b: K) => number\n): SortedMap {\n childList.sort(cmp);\n\n const buildBalancedTree = function (\n low: number,\n high: number\n ): LLRBNode | null {\n const length = high - low;\n let namedNode: NamedNode;\n let key: K;\n if (length === 0) {\n return null;\n } else if (length === 1) {\n namedNode = childList[low];\n key = keyFn ? keyFn(namedNode) : (namedNode as unknown as K);\n return new LLRBNode(\n key,\n namedNode.node as unknown as V,\n LLRBNode.BLACK,\n null,\n null\n );\n } else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const middle = parseInt((length / 2) as any, 10) + low;\n const left = buildBalancedTree(low, middle);\n const right = buildBalancedTree(middle + 1, high);\n namedNode = childList[middle];\n key = keyFn ? keyFn(namedNode) : (namedNode as unknown as K);\n return new LLRBNode(\n key,\n namedNode.node as unknown as V,\n LLRBNode.BLACK,\n left,\n right\n );\n }\n };\n\n const buildFrom12Array = function (base12: Base12Num): LLRBNode {\n let node: LLRBNode = null;\n let root = null;\n let index = childList.length;\n\n const buildPennant = function (chunkSize: number, color: boolean) {\n const low = index - chunkSize;\n const high = index;\n index -= chunkSize;\n const childTree = buildBalancedTree(low + 1, high);\n const namedNode = childList[low];\n const key: K = keyFn ? keyFn(namedNode) : (namedNode as unknown as K);\n attachPennant(\n new LLRBNode(\n key,\n namedNode.node as unknown as V,\n color,\n null,\n childTree\n )\n );\n };\n\n const attachPennant = function (pennant: LLRBNode) {\n if (node) {\n node.left = pennant;\n node = pennant;\n } else {\n root = pennant;\n node = pennant;\n }\n };\n\n for (let i = 0; i < base12.count; ++i) {\n const isOne = base12.nextBitIsOne();\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\n const chunkSize = Math.pow(2, base12.count - (i + 1));\n if (isOne) {\n buildPennant(chunkSize, LLRBNode.BLACK);\n } else {\n // current == 2\n buildPennant(chunkSize, LLRBNode.BLACK);\n buildPennant(chunkSize, LLRBNode.RED);\n }\n }\n return root;\n };\n\n const base12 = new Base12Num(childList.length);\n const root = buildFrom12Array(base12);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new SortedMap(mapSortFn || (cmp as any), root);\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, contains, map, safeGet } from '@firebase/util';\n\nimport { SortedMap } from '../util/SortedMap';\n\nimport { buildChildSet } from './childSet';\nimport { Index } from './indexes/Index';\nimport { KEY_INDEX } from './indexes/KeyIndex';\nimport { PRIORITY_INDEX } from './indexes/PriorityIndex';\nimport { NamedNode, Node } from './Node';\n\nlet _defaultIndexMap: IndexMap;\n\nconst fallbackObject = {};\n\nexport class IndexMap {\n /**\n * The default IndexMap for nodes without a priority\n */\n static get Default(): IndexMap {\n assert(\n fallbackObject && PRIORITY_INDEX,\n 'ChildrenNode.ts has not been loaded'\n );\n _defaultIndexMap =\n _defaultIndexMap ||\n new IndexMap(\n { '.priority': fallbackObject },\n { '.priority': PRIORITY_INDEX }\n );\n return _defaultIndexMap;\n }\n\n constructor(\n private indexes_: {\n [k: string]: SortedMap | /*FallbackType*/ object;\n },\n private indexSet_: { [k: string]: Index }\n ) {}\n\n get(indexKey: string): SortedMap | null {\n const sortedMap = safeGet(this.indexes_, indexKey);\n if (!sortedMap) {\n throw new Error('No index defined for ' + indexKey);\n }\n\n if (sortedMap instanceof SortedMap) {\n return sortedMap;\n } else {\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\n // regular child map\n return null;\n }\n }\n\n hasIndex(indexDefinition: Index): boolean {\n return contains(this.indexSet_, indexDefinition.toString());\n }\n\n addIndex(\n indexDefinition: Index,\n existingChildren: SortedMap\n ): IndexMap {\n assert(\n indexDefinition !== KEY_INDEX,\n \"KeyIndex always exists and isn't meant to be added to the IndexMap.\"\n );\n const childList = [];\n let sawIndexedValue = false;\n const iter = existingChildren.getIterator(NamedNode.Wrap);\n let next = iter.getNext();\n while (next) {\n sawIndexedValue =\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\n childList.push(next);\n next = iter.getNext();\n }\n let newIndex;\n if (sawIndexedValue) {\n newIndex = buildChildSet(childList, indexDefinition.getCompare());\n } else {\n newIndex = fallbackObject;\n }\n const indexName = indexDefinition.toString();\n const newIndexSet = { ...this.indexSet_ };\n newIndexSet[indexName] = indexDefinition;\n const newIndexes = { ...this.indexes_ };\n newIndexes[indexName] = newIndex;\n return new IndexMap(newIndexes, newIndexSet);\n }\n\n /**\n * Ensure that this node is properly tracked in any indexes that we're maintaining\n */\n addToIndexes(\n namedNode: NamedNode,\n existingChildren: SortedMap\n ): IndexMap {\n const newIndexes = map(\n this.indexes_,\n (indexedChildren: SortedMap, indexName: string) => {\n const index = safeGet(this.indexSet_, indexName);\n assert(index, 'Missing index implementation for ' + indexName);\n if (indexedChildren === fallbackObject) {\n // Check to see if we need to index everything\n if (index.isDefinedOn(namedNode.node)) {\n // We need to build this index\n const childList = [];\n const iter = existingChildren.getIterator(NamedNode.Wrap);\n let next = iter.getNext();\n while (next) {\n if (next.name !== namedNode.name) {\n childList.push(next);\n }\n next = iter.getNext();\n }\n childList.push(namedNode);\n return buildChildSet(childList, index.getCompare());\n } else {\n // No change, this remains a fallback\n return fallbackObject;\n }\n } else {\n const existingSnap = existingChildren.get(namedNode.name);\n let newChildren = indexedChildren;\n if (existingSnap) {\n newChildren = newChildren.remove(\n new NamedNode(namedNode.name, existingSnap)\n );\n }\n return newChildren.insert(namedNode, namedNode.node);\n }\n }\n );\n return new IndexMap(newIndexes, this.indexSet_);\n }\n\n /**\n * Create a new IndexMap instance with the given value removed\n */\n removeFromIndexes(\n namedNode: NamedNode,\n existingChildren: SortedMap\n ): IndexMap {\n const newIndexes = map(\n this.indexes_,\n (indexedChildren: SortedMap) => {\n if (indexedChildren === fallbackObject) {\n // This is the fallback. Just return it, nothing to do in this case\n return indexedChildren;\n } else {\n const existingSnap = existingChildren.get(namedNode.name);\n if (existingSnap) {\n return indexedChildren.remove(\n new NamedNode(namedNode.name, existingSnap)\n );\n } else {\n // No record of this child\n return indexedChildren;\n }\n }\n }\n );\n return new IndexMap(newIndexes, this.indexSet_);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Path, pathGetFront, pathGetLength, pathPopFront } from '../util/Path';\nimport { SortedMap, SortedMapIterator } from '../util/SortedMap';\nimport { MAX_NAME, MIN_NAME, sha1 } from '../util/util';\n\nimport { NAME_COMPARATOR } from './comparators';\nimport { Index } from './indexes/Index';\nimport { KEY_INDEX, KeyIndex } from './indexes/KeyIndex';\nimport {\n PRIORITY_INDEX,\n setMaxNode as setPriorityMaxNode\n} from './indexes/PriorityIndex';\nimport { IndexMap } from './IndexMap';\nimport { LeafNode } from './LeafNode';\nimport { NamedNode, Node } from './Node';\nimport { priorityHashText, setMaxNode, validatePriorityNode } from './snap';\n\nexport interface ChildrenNodeConstructor {\n new (\n children_: SortedMap,\n priorityNode_: Node | null,\n indexMap_: IndexMap\n ): ChildrenNode;\n EMPTY_NODE: ChildrenNode;\n}\n\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\n\nlet EMPTY_NODE: ChildrenNode;\n\n/**\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\n * (i.e. nodes with children). It implements Node and stores the\n * list of children in the children property, sorted by child name.\n */\nexport class ChildrenNode implements Node {\n private lazyHash_: string | null = null;\n\n static get EMPTY_NODE(): ChildrenNode {\n return (\n EMPTY_NODE ||\n (EMPTY_NODE = new ChildrenNode(\n new SortedMap(NAME_COMPARATOR),\n null,\n IndexMap.Default\n ))\n );\n }\n\n /**\n * @param children_ - List of children of this node..\n * @param priorityNode_ - The priority of this node (as a snapshot node).\n */\n constructor(\n private readonly children_: SortedMap,\n private readonly priorityNode_: Node | null,\n private indexMap_: IndexMap\n ) {\n /**\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\n * class instead of an empty ChildrenNode.\n */\n if (this.priorityNode_) {\n validatePriorityNode(this.priorityNode_);\n }\n\n if (this.children_.isEmpty()) {\n assert(\n !this.priorityNode_ || this.priorityNode_.isEmpty(),\n 'An empty node cannot have a priority'\n );\n }\n }\n\n /** @inheritDoc */\n isLeafNode(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n getPriority(): Node {\n return this.priorityNode_ || EMPTY_NODE;\n }\n\n /** @inheritDoc */\n updatePriority(newPriorityNode: Node): Node {\n if (this.children_.isEmpty()) {\n // Don't allow priorities on empty nodes\n return this;\n } else {\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\n }\n }\n\n /** @inheritDoc */\n getImmediateChild(childName: string): Node {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.getPriority();\n } else {\n const child = this.children_.get(childName);\n return child === null ? EMPTY_NODE : child;\n }\n }\n\n /** @inheritDoc */\n getChild(path: Path): Node {\n const front = pathGetFront(path);\n if (front === null) {\n return this;\n }\n\n return this.getImmediateChild(front).getChild(pathPopFront(path));\n }\n\n /** @inheritDoc */\n hasChild(childName: string): boolean {\n return this.children_.get(childName) !== null;\n }\n\n /** @inheritDoc */\n updateImmediateChild(childName: string, newChildNode: Node): Node {\n assert(newChildNode, 'We should always be passing snapshot nodes');\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n } else {\n const namedNode = new NamedNode(childName, newChildNode);\n let newChildren, newIndexMap;\n if (newChildNode.isEmpty()) {\n newChildren = this.children_.remove(childName);\n newIndexMap = this.indexMap_.removeFromIndexes(\n namedNode,\n this.children_\n );\n } else {\n newChildren = this.children_.insert(childName, newChildNode);\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\n }\n\n const newPriority = newChildren.isEmpty()\n ? EMPTY_NODE\n : this.priorityNode_;\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\n }\n }\n\n /** @inheritDoc */\n updateChild(path: Path, newChildNode: Node): Node {\n const front = pathGetFront(path);\n if (front === null) {\n return newChildNode;\n } else {\n assert(\n pathGetFront(path) !== '.priority' || pathGetLength(path) === 1,\n '.priority must be the last token in a path'\n );\n const newImmediateChild = this.getImmediateChild(front).updateChild(\n pathPopFront(path),\n newChildNode\n );\n return this.updateImmediateChild(front, newImmediateChild);\n }\n }\n\n /** @inheritDoc */\n isEmpty(): boolean {\n return this.children_.isEmpty();\n }\n\n /** @inheritDoc */\n numChildren(): number {\n return this.children_.count();\n }\n\n private static INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\n\n /** @inheritDoc */\n val(exportFormat?: boolean): object {\n if (this.isEmpty()) {\n return null;\n }\n\n const obj: { [k: string]: unknown } = {};\n let numKeys = 0,\n maxKey = 0,\n allIntegerKeys = true;\n this.forEachChild(PRIORITY_INDEX, (key: string, childNode: Node) => {\n obj[key] = childNode.val(exportFormat);\n\n numKeys++;\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\n maxKey = Math.max(maxKey, Number(key));\n } else {\n allIntegerKeys = false;\n }\n });\n\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\n // convert to array.\n const array: unknown[] = [];\n // eslint-disable-next-line guard-for-in\n for (const key in obj) {\n array[key as unknown as number] = obj[key];\n }\n\n return array;\n } else {\n if (exportFormat && !this.getPriority().isEmpty()) {\n obj['.priority'] = this.getPriority().val();\n }\n return obj;\n }\n }\n\n /** @inheritDoc */\n hash(): string {\n if (this.lazyHash_ === null) {\n let toHash = '';\n if (!this.getPriority().isEmpty()) {\n toHash +=\n 'priority:' +\n priorityHashText(this.getPriority().val() as string | number) +\n ':';\n }\n\n this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n const childHash = childNode.hash();\n if (childHash !== '') {\n toHash += ':' + key + ':' + childHash;\n }\n });\n\n this.lazyHash_ = toHash === '' ? '' : sha1(toHash);\n }\n return this.lazyHash_;\n }\n\n /** @inheritDoc */\n getPredecessorChildName(\n childName: string,\n childNode: Node,\n index: Index\n ): string {\n const idx = this.resolveIndex_(index);\n if (idx) {\n const predecessor = idx.getPredecessorKey(\n new NamedNode(childName, childNode)\n );\n return predecessor ? predecessor.name : null;\n } else {\n return this.children_.getPredecessorKey(childName);\n }\n }\n\n getFirstChildName(indexDefinition: Index): string | null {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n const minKey = idx.minKey();\n return minKey && minKey.name;\n } else {\n return this.children_.minKey();\n }\n }\n\n getFirstChild(indexDefinition: Index): NamedNode | null {\n const minKey = this.getFirstChildName(indexDefinition);\n if (minKey) {\n return new NamedNode(minKey, this.children_.get(minKey));\n } else {\n return null;\n }\n }\n\n /**\n * Given an index, return the key name of the largest value we have, according to that index\n */\n getLastChildName(indexDefinition: Index): string | null {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n const maxKey = idx.maxKey();\n return maxKey && maxKey.name;\n } else {\n return this.children_.maxKey();\n }\n }\n\n getLastChild(indexDefinition: Index): NamedNode | null {\n const maxKey = this.getLastChildName(indexDefinition);\n if (maxKey) {\n return new NamedNode(maxKey, this.children_.get(maxKey));\n } else {\n return null;\n }\n }\n forEachChild(\n index: Index,\n action: (key: string, node: Node) => boolean | void\n ): boolean {\n const idx = this.resolveIndex_(index);\n if (idx) {\n return idx.inorderTraversal(wrappedNode => {\n return action(wrappedNode.name, wrappedNode.node);\n });\n } else {\n return this.children_.inorderTraversal(action);\n }\n }\n\n getIterator(\n indexDefinition: Index\n ): SortedMapIterator {\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\n }\n\n getIteratorFrom(\n startPost: NamedNode,\n indexDefinition: Index\n ): SortedMapIterator {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getIteratorFrom(startPost, key => key);\n } else {\n const iterator = this.children_.getIteratorFrom(\n startPost.name,\n NamedNode.Wrap\n );\n let next = iterator.peek();\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n }\n\n getReverseIterator(\n indexDefinition: Index\n ): SortedMapIterator {\n return this.getReverseIteratorFrom(\n indexDefinition.maxPost(),\n indexDefinition\n );\n }\n\n getReverseIteratorFrom(\n endPost: NamedNode,\n indexDefinition: Index\n ): SortedMapIterator {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getReverseIteratorFrom(endPost, key => {\n return key;\n });\n } else {\n const iterator = this.children_.getReverseIteratorFrom(\n endPost.name,\n NamedNode.Wrap\n );\n let next = iterator.peek();\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n }\n compareTo(other: ChildrenNode): number {\n if (this.isEmpty()) {\n if (other.isEmpty()) {\n return 0;\n } else {\n return -1;\n }\n } else if (other.isLeafNode() || other.isEmpty()) {\n return 1;\n } else if (other === MAX_NODE) {\n return -1;\n } else {\n // Must be another node with children.\n return 0;\n }\n }\n withIndex(indexDefinition: Index): Node {\n if (\n indexDefinition === KEY_INDEX ||\n this.indexMap_.hasIndex(indexDefinition)\n ) {\n return this;\n } else {\n const newIndexMap = this.indexMap_.addIndex(\n indexDefinition,\n this.children_\n );\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\n }\n }\n isIndexed(index: Index): boolean {\n return index === KEY_INDEX || this.indexMap_.hasIndex(index);\n }\n equals(other: Node): boolean {\n if (other === this) {\n return true;\n } else if (other.isLeafNode()) {\n return false;\n } else {\n const otherChildrenNode = other as ChildrenNode;\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\n return false;\n } else if (\n this.children_.count() === otherChildrenNode.children_.count()\n ) {\n const thisIter = this.getIterator(PRIORITY_INDEX);\n const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);\n let thisCurrent = thisIter.getNext();\n let otherCurrent = otherIter.getNext();\n while (thisCurrent && otherCurrent) {\n if (\n thisCurrent.name !== otherCurrent.name ||\n !thisCurrent.node.equals(otherCurrent.node)\n ) {\n return false;\n }\n thisCurrent = thisIter.getNext();\n otherCurrent = otherIter.getNext();\n }\n return thisCurrent === null && otherCurrent === null;\n } else {\n return false;\n }\n }\n }\n\n /**\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\n * instead.\n *\n */\n private resolveIndex_(\n indexDefinition: Index\n ): SortedMap | null {\n if (indexDefinition === KEY_INDEX) {\n return null;\n } else {\n return this.indexMap_.get(indexDefinition.toString());\n }\n }\n}\n\nexport class MaxNode extends ChildrenNode {\n constructor() {\n super(\n new SortedMap(NAME_COMPARATOR),\n ChildrenNode.EMPTY_NODE,\n IndexMap.Default\n );\n }\n\n compareTo(other: Node): number {\n if (other === this) {\n return 0;\n } else {\n return 1;\n }\n }\n\n equals(other: Node): boolean {\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\n return other === this;\n }\n\n getPriority(): MaxNode {\n return this;\n }\n\n getImmediateChild(childName: string): ChildrenNode {\n return ChildrenNode.EMPTY_NODE;\n }\n\n isEmpty(): boolean {\n return false;\n }\n}\n\n/**\n * Marker that will sort higher than any other snapshot.\n */\nexport const MAX_NODE = new MaxNode();\n\n/**\n * Document NamedNode extensions\n */\ndeclare module './Node' {\n interface NamedNode {\n MIN: NamedNode;\n MAX: NamedNode;\n }\n}\n\nObject.defineProperties(NamedNode, {\n MIN: {\n value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)\n },\n MAX: {\n value: new NamedNode(MAX_NAME, MAX_NODE)\n }\n});\n\n/**\n * Reference Extensions\n */\nKeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\nLeafNode.__childrenNodeConstructor = ChildrenNode;\nsetMaxNode(MAX_NODE);\nsetPriorityMaxNode(MAX_NODE);\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains, assert } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport { SortedMap } from '../util/SortedMap';\nimport { each } from '../util/util';\n\nimport { ChildrenNode } from './ChildrenNode';\nimport { buildChildSet } from './childSet';\nimport { NAME_COMPARATOR, NAME_ONLY_COMPARATOR } from './comparators';\nimport { PRIORITY_INDEX, setNodeFromJSON } from './indexes/PriorityIndex';\nimport { IndexMap } from './IndexMap';\nimport { LeafNode } from './LeafNode';\nimport { NamedNode, Node } from './Node';\n\nconst USE_HINZE = true;\n\n/**\n * Constructs a snapshot node representing the passed JSON and returns it.\n * @param json - JSON to create a node for.\n * @param priority - Optional priority to use. This will be ignored if the\n * passed JSON contains a .priority property.\n */\nexport function nodeFromJSON(\n json: unknown | null,\n priority: unknown = null\n): Node {\n if (json === null) {\n return ChildrenNode.EMPTY_NODE;\n }\n\n if (typeof json === 'object' && '.priority' in json) {\n priority = json['.priority'];\n }\n\n assert(\n priority === null ||\n typeof priority === 'string' ||\n typeof priority === 'number' ||\n (typeof priority === 'object' && '.sv' in (priority as object)),\n 'Invalid priority type found: ' + typeof priority\n );\n\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\n json = json['.value'];\n }\n\n // Valid leaf nodes include non-objects or server-value wrapper objects\n if (typeof json !== 'object' || '.sv' in json) {\n const jsonLeaf = json as string | number | boolean | Indexable;\n return new LeafNode(jsonLeaf, nodeFromJSON(priority));\n }\n\n if (!(json instanceof Array) && USE_HINZE) {\n const children: NamedNode[] = [];\n let childrenHavePriority = false;\n const hinzeJsonObj = json;\n each(hinzeJsonObj, (key, child) => {\n if (key.substring(0, 1) !== '.') {\n // Ignore metadata nodes\n const childNode = nodeFromJSON(child);\n if (!childNode.isEmpty()) {\n childrenHavePriority =\n childrenHavePriority || !childNode.getPriority().isEmpty();\n children.push(new NamedNode(key, childNode));\n }\n }\n });\n\n if (children.length === 0) {\n return ChildrenNode.EMPTY_NODE;\n }\n\n const childSet = buildChildSet(\n children,\n NAME_ONLY_COMPARATOR,\n namedNode => namedNode.name,\n NAME_COMPARATOR\n ) as SortedMap;\n if (childrenHavePriority) {\n const sortedChildSet = buildChildSet(\n children,\n PRIORITY_INDEX.getCompare()\n );\n return new ChildrenNode(\n childSet,\n nodeFromJSON(priority),\n new IndexMap(\n { '.priority': sortedChildSet },\n { '.priority': PRIORITY_INDEX }\n )\n );\n } else {\n return new ChildrenNode(\n childSet,\n nodeFromJSON(priority),\n IndexMap.Default\n );\n }\n } else {\n let node: Node = ChildrenNode.EMPTY_NODE;\n each(json, (key: string, childData: unknown) => {\n if (contains(json as object, key)) {\n if (key.substring(0, 1) !== '.') {\n // ignore metadata nodes.\n const childNode = nodeFromJSON(childData);\n if (childNode.isLeafNode() || !childNode.isEmpty()) {\n node = node.updateImmediateChild(key, childNode);\n }\n }\n }\n });\n\n return node.updatePriority(nodeFromJSON(priority));\n }\n}\n\nsetNodeFromJSON(nodeFromJSON);\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Path, pathGetFront, pathIsEmpty, pathSlice } from '../../util/Path';\nimport { MAX_NAME, nameCompare } from '../../util/util';\nimport { ChildrenNode, MAX_NODE } from '../ChildrenNode';\nimport { NamedNode, Node } from '../Node';\nimport { nodeFromJSON } from '../nodeFromJSON';\n\nimport { Index } from './Index';\n\nexport class PathIndex extends Index {\n constructor(private indexPath_: Path) {\n super();\n\n assert(\n !pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority',\n \"Can't create PathIndex with empty path or .priority key\"\n );\n }\n\n protected extractChild(snap: Node): Node {\n return snap.getChild(this.indexPath_);\n }\n isDefinedOn(node: Node): boolean {\n return !node.getChild(this.indexPath_).isEmpty();\n }\n compare(a: NamedNode, b: NamedNode): number {\n const aChild = this.extractChild(a.node);\n const bChild = this.extractChild(b.node);\n const indexCmp = aChild.compareTo(bChild);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n makePost(indexValue: object, name: string): NamedNode {\n const valueNode = nodeFromJSON(indexValue);\n const node = ChildrenNode.EMPTY_NODE.updateChild(\n this.indexPath_,\n valueNode\n );\n return new NamedNode(name, node);\n }\n maxPost(): NamedNode {\n const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);\n return new NamedNode(MAX_NAME, node);\n }\n toString(): string {\n return pathSlice(this.indexPath_, 0).join('/');\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare } from '../../util/util';\nimport { NamedNode, Node } from '../Node';\nimport { nodeFromJSON } from '../nodeFromJSON';\n\nimport { Index } from './Index';\n\nexport class ValueIndex extends Index {\n compare(a: NamedNode, b: NamedNode): number {\n const indexCmp = a.node.compareTo(b.node);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n isDefinedOn(node: Node): boolean {\n return true;\n }\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return !oldNode.equals(newNode);\n }\n minPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n maxPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MAX;\n }\n\n makePost(indexValue: object, name: string): NamedNode {\n const valueNode = nodeFromJSON(indexValue);\n return new NamedNode(name, valueNode);\n }\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString(): string {\n return '.value';\n }\n}\n\nexport const VALUE_INDEX = new ValueIndex();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\n\nexport const enum ChangeType {\n /** Event type for a child added */\n CHILD_ADDED = 'child_added',\n /** Event type for a child removed */\n CHILD_REMOVED = 'child_removed',\n /** Event type for a child changed */\n CHILD_CHANGED = 'child_changed',\n /** Event type for a child moved */\n CHILD_MOVED = 'child_moved',\n /** Event type for a value change */\n VALUE = 'value'\n}\n\nexport interface Change {\n /** @param type - The event type */\n type: ChangeType;\n /** @param snapshotNode - The data */\n snapshotNode: Node;\n /** @param childName - The name for this child, if it's a child even */\n childName?: string;\n /** @param oldSnap - Used for intermediate processing of child changed events */\n oldSnap?: Node;\n /** * @param prevName - The name for the previous child, if applicable */\n prevName?: string | null;\n}\n\nexport function changeValue(snapshotNode: Node): Change {\n return { type: ChangeType.VALUE, snapshotNode };\n}\n\nexport function changeChildAdded(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_ADDED, snapshotNode, childName };\n}\n\nexport function changeChildRemoved(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_REMOVED, snapshotNode, childName };\n}\n\nexport function changeChildChanged(\n childName: string,\n snapshotNode: Node,\n oldSnap: Node\n): Change {\n return {\n type: ChangeType.CHILD_CHANGED,\n snapshotNode,\n childName,\n oldSnap\n };\n}\n\nexport function changeChildMoved(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_MOVED, snapshotNode, childName };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { PRIORITY_INDEX } from '../../snap/indexes/PriorityIndex';\nimport { Node } from '../../snap/Node';\nimport { Path } from '../../util/Path';\nimport {\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from '../Change';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\n\nimport { NodeFilter } from './NodeFilter';\n\n/**\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\n */\nexport class IndexedFilter implements NodeFilter {\n constructor(private readonly index_: Index) {}\n\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n assert(\n snap.isIndexed(this.index_),\n 'A node must be indexed if only a child is updated'\n );\n const oldChild = snap.getImmediateChild(key);\n // Check if anything actually changed.\n if (\n oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))\n ) {\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\n // to avoid treating these cases as \"nothing changed.\"\n if (oldChild.isEmpty() === newChild.isEmpty()) {\n // Nothing changed.\n\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\n return snap;\n }\n }\n\n if (optChangeAccumulator != null) {\n if (newChild.isEmpty()) {\n if (snap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(\n changeChildRemoved(key, oldChild)\n );\n } else {\n assert(\n snap.isLeafNode(),\n 'A child remove without an old child only makes sense on a leaf node'\n );\n }\n } else if (oldChild.isEmpty()) {\n optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));\n } else {\n optChangeAccumulator.trackChildChange(\n changeChildChanged(key, newChild, oldChild)\n );\n }\n }\n if (snap.isLeafNode() && newChild.isEmpty()) {\n return snap;\n } else {\n // Make sure the node is indexed\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\n }\n }\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (optChangeAccumulator != null) {\n if (!oldSnap.isLeafNode()) {\n oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (!newSnap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(\n changeChildRemoved(key, childNode)\n );\n }\n });\n }\n if (!newSnap.isLeafNode()) {\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (oldSnap.hasChild(key)) {\n const oldChild = oldSnap.getImmediateChild(key);\n if (!oldChild.equals(childNode)) {\n optChangeAccumulator.trackChildChange(\n changeChildChanged(key, childNode, oldChild)\n );\n }\n } else {\n optChangeAccumulator.trackChildChange(\n changeChildAdded(key, childNode)\n );\n }\n });\n }\n }\n return newSnap.withIndex(this.index_);\n }\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n if (oldSnap.isEmpty()) {\n return ChildrenNode.EMPTY_NODE;\n } else {\n return oldSnap.updatePriority(newPriority);\n }\n }\n filtersNodes(): boolean {\n return false;\n }\n getIndexedFilter(): IndexedFilter {\n return this;\n }\n getIndex(): Index {\n return this.index_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NamedNode, Node } from '../../../core/snap/Node';\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { PRIORITY_INDEX } from '../../snap/indexes/PriorityIndex';\nimport { Path } from '../../util/Path';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\nimport { QueryParams } from '../QueryParams';\n\nimport { IndexedFilter } from './IndexedFilter';\nimport { NodeFilter } from './NodeFilter';\n\n/**\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n */\nexport class RangedFilter implements NodeFilter {\n private indexedFilter_: IndexedFilter;\n\n private index_: Index;\n\n private startPost_: NamedNode;\n\n private endPost_: NamedNode;\n\n private startIsInclusive_: boolean;\n\n private endIsInclusive_: boolean;\n\n constructor(params: QueryParams) {\n this.indexedFilter_ = new IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n this.startIsInclusive_ = !params.startAfterSet_;\n this.endIsInclusive_ = !params.endBeforeSet_;\n }\n\n getStartPost(): NamedNode {\n return this.startPost_;\n }\n\n getEndPost(): NamedNode {\n return this.endPost_;\n }\n\n matches(node: NamedNode): boolean {\n const isWithinStart = this.startIsInclusive_\n ? this.index_.compare(this.getStartPost(), node) <= 0\n : this.index_.compare(this.getStartPost(), node) < 0;\n const isWithinEnd = this.endIsInclusive_\n ? this.index_.compare(node, this.getEndPost()) <= 0\n : this.index_.compare(node, this.getEndPost()) < 0;\n return isWithinStart && isWithinEnd;\n }\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (!this.matches(new NamedNode(key, newChild))) {\n newChild = ChildrenNode.EMPTY_NODE;\n }\n return this.indexedFilter_.updateChild(\n snap,\n key,\n newChild,\n affectedPath,\n source,\n optChangeAccumulator\n );\n }\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode.EMPTY_NODE;\n }\n let filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\n const self = this;\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (!self.matches(new NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(\n oldSnap,\n filtered,\n optChangeAccumulator\n );\n }\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n // Don't support priorities on queries\n return oldSnap;\n }\n filtersNodes(): boolean {\n return true;\n }\n getIndexedFilter(): IndexedFilter {\n return this.indexedFilter_;\n }\n getIndex(): Index {\n return this.index_;\n }\n\n private static getStartPost_(params: QueryParams): NamedNode {\n if (params.hasStart()) {\n const startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n } else {\n return params.getIndex().minPost();\n }\n }\n\n private static getEndPost_(params: QueryParams): NamedNode {\n if (params.hasEnd()) {\n const endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n } else {\n return params.getIndex().maxPost();\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { NamedNode, Node } from '../../snap/Node';\nimport { Path } from '../../util/Path';\nimport {\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from '../Change';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\nimport { QueryParams } from '../QueryParams';\n\nimport { IndexedFilter } from './IndexedFilter';\nimport { NodeFilter } from './NodeFilter';\nimport { RangedFilter } from './RangedFilter';\n\n/**\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n */\nexport class LimitedFilter implements NodeFilter {\n private readonly rangedFilter_: RangedFilter;\n\n private readonly index_: Index;\n\n private readonly limit_: number;\n\n private readonly reverse_: boolean;\n\n private readonly startIsInclusive_: boolean;\n\n private readonly endIsInclusive_: boolean;\n\n constructor(params: QueryParams) {\n this.rangedFilter_ = new RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n this.startIsInclusive_ = !params.startAfterSet_;\n this.endIsInclusive_ = !params.endBeforeSet_;\n }\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {\n newChild = ChildrenNode.EMPTY_NODE;\n }\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n } else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_\n .getIndexedFilter()\n .updateChild(\n snap,\n key,\n newChild,\n affectedPath,\n source,\n optChangeAccumulator\n );\n } else {\n return this.fullLimitUpdateChild_(\n snap,\n key,\n newChild,\n source,\n optChangeAccumulator\n );\n }\n }\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n let filtered;\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n } else {\n if (\n this.limit_ * 2 < newSnap.numChildren() &&\n newSnap.isIndexed(this.index_)\n ) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n // anchor to the startPost, endPost, or last element as appropriate\n let iterator;\n if (this.reverse_) {\n iterator = (newSnap as ChildrenNode).getReverseIteratorFrom(\n this.rangedFilter_.getEndPost(),\n this.index_\n );\n } else {\n iterator = (newSnap as ChildrenNode).getIteratorFrom(\n this.rangedFilter_.getStartPost(),\n this.index_\n );\n }\n let count = 0;\n while (iterator.hasNext() && count < this.limit_) {\n const next = iterator.getNext();\n if (!this.withinDirectionalStart(next)) {\n // if we have not reached the start, skip to the next element\n continue;\n } else if (!this.withinDirectionalEnd(next)) {\n // if we have reached the end, stop adding elements\n break;\n } else {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\n }\n }\n } else {\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(\n ChildrenNode.EMPTY_NODE\n ) as ChildrenNode;\n\n let iterator;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n } else {\n iterator = filtered.getIterator(this.index_);\n }\n\n let count = 0;\n while (iterator.hasNext()) {\n const next = iterator.getNext();\n const inRange =\n count < this.limit_ &&\n this.withinDirectionalStart(next) &&\n this.withinDirectionalEnd(next);\n if (inRange) {\n count++;\n } else {\n filtered = filtered.updateImmediateChild(\n next.name,\n ChildrenNode.EMPTY_NODE\n );\n }\n }\n }\n }\n return this.rangedFilter_\n .getIndexedFilter()\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n }\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n // Don't support priorities on queries\n return oldSnap;\n }\n filtersNodes(): boolean {\n return true;\n }\n getIndexedFilter(): IndexedFilter {\n return this.rangedFilter_.getIndexedFilter();\n }\n getIndex(): Index {\n return this.index_;\n }\n\n private fullLimitUpdateChild_(\n snap: Node,\n childKey: string,\n childSnap: Node,\n source: CompleteChildSource,\n changeAccumulator: ChildChangeAccumulator | null\n ): Node {\n // TODO: rename all cache stuff etc to general snap terminology\n let cmp;\n if (this.reverse_) {\n const indexCmp = this.index_.getCompare();\n cmp = (a: NamedNode, b: NamedNode) => indexCmp(b, a);\n } else {\n cmp = this.index_.getCompare();\n }\n const oldEventCache = snap as ChildrenNode;\n assert(oldEventCache.numChildren() === this.limit_, '');\n const newChildNamedNode = new NamedNode(childKey, childSnap);\n const windowBoundary = this.reverse_\n ? oldEventCache.getFirstChild(this.index_)\n : (oldEventCache.getLastChild(this.index_) as NamedNode);\n const inRange = this.rangedFilter_.matches(newChildNamedNode);\n if (oldEventCache.hasChild(childKey)) {\n const oldChildSnap = oldEventCache.getImmediateChild(childKey);\n let nextChild = source.getChildAfterChild(\n this.index_,\n windowBoundary,\n this.reverse_\n );\n while (\n nextChild != null &&\n (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))\n ) {\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\n // the limited filter...\n nextChild = source.getChildAfterChild(\n this.index_,\n nextChild,\n this.reverse_\n );\n }\n const compareNext =\n nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n const remainsInWindow =\n inRange && !childSnap.isEmpty() && compareNext >= 0;\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildChanged(childKey, childSnap, oldChildSnap)\n );\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n } else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildRemoved(childKey, oldChildSnap)\n );\n }\n const newEventCache = oldEventCache.updateImmediateChild(\n childKey,\n ChildrenNode.EMPTY_NODE\n );\n const nextChildInRange =\n nextChild != null && this.rangedFilter_.matches(nextChild);\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildAdded(nextChild.name, nextChild.node)\n );\n }\n return newEventCache.updateImmediateChild(\n nextChild.name,\n nextChild.node\n );\n } else {\n return newEventCache;\n }\n }\n } else if (childSnap.isEmpty()) {\n // we're deleting a node, but it was not in the window, so ignore it\n return snap;\n } else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildRemoved(windowBoundary.name, windowBoundary.node)\n );\n changeAccumulator.trackChildChange(\n changeChildAdded(childKey, childSnap)\n );\n }\n return oldEventCache\n .updateImmediateChild(childKey, childSnap)\n .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);\n } else {\n return snap;\n }\n } else {\n return snap;\n }\n }\n\n private withinDirectionalStart = (node: NamedNode) =>\n this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);\n\n private withinDirectionalEnd = (node: NamedNode) =>\n this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);\n\n private withinStartPost = (node: NamedNode) => {\n const compareRes = this.index_.compare(\n this.rangedFilter_.getStartPost(),\n node\n );\n return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;\n };\n\n private withinEndPost = (node: NamedNode) => {\n const compareRes = this.index_.compare(\n node,\n this.rangedFilter_.getEndPost()\n );\n return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, stringify } from '@firebase/util';\n\nimport { Index } from '../snap/indexes/Index';\nimport { KEY_INDEX } from '../snap/indexes/KeyIndex';\nimport { PathIndex } from '../snap/indexes/PathIndex';\nimport { PRIORITY_INDEX, PriorityIndex } from '../snap/indexes/PriorityIndex';\nimport { VALUE_INDEX } from '../snap/indexes/ValueIndex';\nimport { MAX_NAME, MIN_NAME } from '../util/util';\n\nimport { IndexedFilter } from './filter/IndexedFilter';\nimport { LimitedFilter } from './filter/LimitedFilter';\nimport { NodeFilter } from './filter/NodeFilter';\nimport { RangedFilter } from './filter/RangedFilter';\n\n/**\n * Wire Protocol Constants\n */\nconst enum WIRE_PROTOCOL_CONSTANTS {\n INDEX_START_VALUE = 'sp',\n INDEX_START_NAME = 'sn',\n INDEX_START_IS_INCLUSIVE = 'sin',\n INDEX_END_VALUE = 'ep',\n INDEX_END_NAME = 'en',\n INDEX_END_IS_INCLUSIVE = 'ein',\n LIMIT = 'l',\n VIEW_FROM = 'vf',\n VIEW_FROM_LEFT = 'l',\n VIEW_FROM_RIGHT = 'r',\n INDEX = 'i'\n}\n\n/**\n * REST Query Constants\n */\nconst enum REST_QUERY_CONSTANTS {\n ORDER_BY = 'orderBy',\n PRIORITY_INDEX = '$priority',\n VALUE_INDEX = '$value',\n KEY_INDEX = '$key',\n START_AFTER = 'startAfter',\n START_AT = 'startAt',\n END_AT = 'endAt',\n END_BEFORE = 'endBefore',\n LIMIT_TO_FIRST = 'limitToFirst',\n LIMIT_TO_LAST = 'limitToLast'\n}\n\n/**\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\n * user-facing API level, so it is not done here.\n *\n * @internal\n */\nexport class QueryParams {\n limitSet_ = false;\n startSet_ = false;\n startNameSet_ = false;\n startAfterSet_ = false; // can only be true if startSet_ is true\n endSet_ = false;\n endNameSet_ = false;\n endBeforeSet_ = false; // can only be true if endSet_ is true\n limit_ = 0;\n viewFrom_ = '';\n indexStartValue_: unknown | null = null;\n indexStartName_ = '';\n indexEndValue_: unknown | null = null;\n indexEndName_ = '';\n index_: PriorityIndex = PRIORITY_INDEX;\n\n hasStart(): boolean {\n return this.startSet_;\n }\n\n /**\n * @returns True if it would return from left.\n */\n isViewFromLeft(): boolean {\n if (this.viewFrom_ === '') {\n // limit(), rather than limitToFirst or limitToLast was called.\n // This means that only one of startSet_ and endSet_ is true. Use them\n // to calculate which side of the view to anchor to. If neither is set,\n // anchor to the end.\n return this.startSet_;\n } else {\n return this.viewFrom_ === WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n }\n }\n\n /**\n * Only valid to call if hasStart() returns true\n */\n getIndexStartValue(): unknown {\n assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n }\n\n /**\n * Only valid to call if hasStart() returns true.\n * Returns the starting key name for the range defined by these query parameters\n */\n getIndexStartName(): string {\n assert(this.startSet_, 'Only valid if start has been set');\n if (this.startNameSet_) {\n return this.indexStartName_;\n } else {\n return MIN_NAME;\n }\n }\n\n hasEnd(): boolean {\n return this.endSet_;\n }\n\n /**\n * Only valid to call if hasEnd() returns true.\n */\n getIndexEndValue(): unknown {\n assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n }\n\n /**\n * Only valid to call if hasEnd() returns true.\n * Returns the end key name for the range defined by these query parameters\n */\n getIndexEndName(): string {\n assert(this.endSet_, 'Only valid if end has been set');\n if (this.endNameSet_) {\n return this.indexEndName_;\n } else {\n return MAX_NAME;\n }\n }\n\n hasLimit(): boolean {\n return this.limitSet_;\n }\n\n /**\n * @returns True if a limit has been set and it has been explicitly anchored\n */\n hasAnchoredLimit(): boolean {\n return this.limitSet_ && this.viewFrom_ !== '';\n }\n\n /**\n * Only valid to call if hasLimit() returns true\n */\n getLimit(): number {\n assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n }\n\n getIndex(): Index {\n return this.index_;\n }\n\n loadsAllData(): boolean {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n }\n\n isDefault(): boolean {\n return this.loadsAllData() && this.index_ === PRIORITY_INDEX;\n }\n\n copy(): QueryParams {\n const copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.startAfterSet_ = this.startAfterSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.endBeforeSet_ = this.endBeforeSet_;\n copy.indexEndValue_ = this.indexEndValue_;\n copy.endNameSet_ = this.endNameSet_;\n copy.indexEndName_ = this.indexEndName_;\n copy.index_ = this.index_;\n copy.viewFrom_ = this.viewFrom_;\n return copy;\n }\n}\n\nexport function queryParamsGetNodeFilter(queryParams: QueryParams): NodeFilter {\n if (queryParams.loadsAllData()) {\n return new IndexedFilter(queryParams.getIndex());\n } else if (queryParams.hasLimit()) {\n return new LimitedFilter(queryParams);\n } else {\n return new RangedFilter(queryParams);\n }\n}\n\nexport function queryParamsLimit(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n}\n\nexport function queryParamsLimitToFirst(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n return newParams;\n}\n\nexport function queryParamsLimitToLast(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n return newParams;\n}\n\nexport function queryParamsStartAt(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.startSet_ = true;\n if (indexValue === undefined) {\n indexValue = null;\n }\n newParams.indexStartValue_ = indexValue;\n if (key != null) {\n newParams.startNameSet_ = true;\n newParams.indexStartName_ = key;\n } else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n return newParams;\n}\n\nexport function queryParamsStartAfter(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n let params: QueryParams;\n if (queryParams.index_ === KEY_INDEX || !!key) {\n params = queryParamsStartAt(queryParams, indexValue, key);\n } else {\n params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);\n }\n params.startAfterSet_ = true;\n return params;\n}\n\nexport function queryParamsEndAt(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.endSet_ = true;\n if (indexValue === undefined) {\n indexValue = null;\n }\n newParams.indexEndValue_ = indexValue;\n if (key !== undefined) {\n newParams.endNameSet_ = true;\n newParams.indexEndName_ = key;\n } else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n return newParams;\n}\n\nexport function queryParamsEndBefore(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n let params: QueryParams;\n if (queryParams.index_ === KEY_INDEX || !!key) {\n params = queryParamsEndAt(queryParams, indexValue, key);\n } else {\n params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);\n }\n params.endBeforeSet_ = true;\n return params;\n}\n\nexport function queryParamsOrderBy(\n queryParams: QueryParams,\n index: Index\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.index_ = index;\n return newParams;\n}\n\n/**\n * Returns a set of REST query string parameters representing this query.\n *\n * @returns query string parameters\n */\nexport function queryParamsToRestQueryStringParameters(\n queryParams: QueryParams\n): Record {\n const qs: Record = {};\n\n if (queryParams.isDefault()) {\n return qs;\n }\n\n let orderBy;\n if (queryParams.index_ === PRIORITY_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.PRIORITY_INDEX;\n } else if (queryParams.index_ === VALUE_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.VALUE_INDEX;\n } else if (queryParams.index_ === KEY_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.KEY_INDEX;\n } else {\n assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');\n orderBy = queryParams.index_.toString();\n }\n qs[REST_QUERY_CONSTANTS.ORDER_BY] = stringify(orderBy);\n\n if (queryParams.startSet_) {\n const startParam = queryParams.startAfterSet_\n ? REST_QUERY_CONSTANTS.START_AFTER\n : REST_QUERY_CONSTANTS.START_AT;\n qs[startParam] = stringify(queryParams.indexStartValue_);\n if (queryParams.startNameSet_) {\n qs[startParam] += ',' + stringify(queryParams.indexStartName_);\n }\n }\n\n if (queryParams.endSet_) {\n const endParam = queryParams.endBeforeSet_\n ? REST_QUERY_CONSTANTS.END_BEFORE\n : REST_QUERY_CONSTANTS.END_AT;\n qs[endParam] = stringify(queryParams.indexEndValue_);\n if (queryParams.endNameSet_) {\n qs[endParam] += ',' + stringify(queryParams.indexEndName_);\n }\n }\n\n if (queryParams.limitSet_) {\n if (queryParams.isViewFromLeft()) {\n qs[REST_QUERY_CONSTANTS.LIMIT_TO_FIRST] = queryParams.limit_;\n } else {\n qs[REST_QUERY_CONSTANTS.LIMIT_TO_LAST] = queryParams.limit_;\n }\n }\n\n return qs;\n}\n\nexport function queryParamsGetQueryObject(\n queryParams: QueryParams\n): Record {\n const obj: Record = {};\n if (queryParams.startSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] =\n queryParams.indexStartValue_;\n if (queryParams.startNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] =\n queryParams.indexStartName_;\n }\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE] =\n !queryParams.startAfterSet_;\n }\n if (queryParams.endSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = queryParams.indexEndValue_;\n if (queryParams.endNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = queryParams.indexEndName_;\n }\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE] =\n !queryParams.endBeforeSet_;\n }\n if (queryParams.limitSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = queryParams.limit_;\n let viewFrom = queryParams.viewFrom_;\n if (viewFrom === '') {\n if (queryParams.isViewFromLeft()) {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n } else {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n }\n }\n obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom;\n }\n // For now, priority index is the default, so we only specify if it's some other index\n if (queryParams.index_ !== PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = queryParams.index_.toString();\n }\n return obj;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n jsonEval,\n safeGet,\n querystring,\n Deferred\n} from '@firebase/util';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { logWrapper, warn } from './util/util';\nimport { QueryContext } from './view/EventRegistration';\nimport { queryParamsToRestQueryStringParameters } from './view/QueryParams';\n\n/**\n * An implementation of ServerActions that communicates with the server via REST requests.\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\n * persistent connection (using WebSockets or long-polling)\n */\nexport class ReadonlyRestClient extends ServerActions {\n reportStats(stats: { [k: string]: unknown }): void {\n throw new Error('Method not implemented.');\n }\n\n /** @private {function(...[*])} */\n private log_: (...args: unknown[]) => void = logWrapper('p:rest:');\n\n /**\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\n * that's been removed. :-/\n */\n private listens_: { [k: string]: object } = {};\n\n static getListenId_(query: QueryContext, tag?: number | null): string {\n if (tag !== undefined) {\n return 'tag$' + tag;\n } else {\n assert(\n query._queryParams.isDefault(),\n \"should have a tag if it's not a default query.\"\n );\n return query._path.toString();\n }\n }\n\n /**\n * @param repoInfo_ - Data about the namespace we are connecting to\n * @param onDataUpdate_ - A callback for new data from the server\n */\n constructor(\n private repoInfo_: RepoInfo,\n private onDataUpdate_: (\n a: string,\n b: unknown,\n c: boolean,\n d: number | null\n ) => void,\n private authTokenProvider_: AuthTokenProvider,\n private appCheckTokenProvider_: AppCheckTokenProvider\n ) {\n super();\n }\n\n /** @inheritDoc */\n listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ) {\n const pathString = query._path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);\n\n // Mark this listener so we can tell if it's removed.\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\n const thisListen = {};\n this.listens_[listenId] = thisListen;\n\n const queryStringParameters = queryParamsToRestQueryStringParameters(\n query._queryParams\n );\n\n this.restRequest_(\n pathString + '.json',\n queryStringParameters,\n (error, result) => {\n let data = result;\n\n if (error === 404) {\n data = null;\n error = null;\n }\n\n if (error === null) {\n this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n }\n\n if (safeGet(this.listens_, listenId) === thisListen) {\n let status;\n if (!error) {\n status = 'ok';\n } else if (error === 401) {\n status = 'permission_denied';\n } else {\n status = 'rest_error:' + error;\n }\n\n onComplete(status, null);\n }\n }\n );\n }\n\n /** @inheritDoc */\n unlisten(query: QueryContext, tag: number | null) {\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n }\n\n get(query: QueryContext): Promise {\n const queryStringParameters = queryParamsToRestQueryStringParameters(\n query._queryParams\n );\n\n const pathString = query._path.toString();\n\n const deferred = new Deferred();\n\n this.restRequest_(\n pathString + '.json',\n queryStringParameters,\n (error, result) => {\n let data = result;\n\n if (error === 404) {\n data = null;\n error = null;\n }\n\n if (error === null) {\n this.onDataUpdate_(\n pathString,\n data,\n /*isMerge=*/ false,\n /*tag=*/ null\n );\n deferred.resolve(data as string);\n } else {\n deferred.reject(new Error(data as string));\n }\n }\n );\n return deferred.promise;\n }\n\n /** @inheritDoc */\n refreshAuthToken(token: string) {\n // no-op since we just always call getToken.\n }\n\n /**\n * Performs a REST request to the given path, with the provided query string parameters,\n * and any auth credentials we have.\n */\n private restRequest_(\n pathString: string,\n queryStringParameters: { [k: string]: string | number } = {},\n callback: ((a: number | null, b?: unknown) => void) | null\n ) {\n queryStringParameters['format'] = 'export';\n\n return Promise.all([\n this.authTokenProvider_.getToken(/*forceRefresh=*/ false),\n this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)\n ]).then(([authToken, appCheckToken]) => {\n if (authToken && authToken.accessToken) {\n queryStringParameters['auth'] = authToken.accessToken;\n }\n if (appCheckToken && appCheckToken.token) {\n queryStringParameters['ac'] = appCheckToken.token;\n }\n\n const url =\n (this.repoInfo_.secure ? 'https://' : 'http://') +\n this.repoInfo_.host +\n pathString +\n '?' +\n 'ns=' +\n this.repoInfo_.namespace +\n querystring(queryStringParameters);\n\n this.log_('Sending REST request for ' + url);\n const xhr = new XMLHttpRequest();\n xhr.onreadystatechange = () => {\n if (callback && xhr.readyState === 4) {\n this.log_(\n 'REST Response for ' + url + ' received. status:',\n xhr.status,\n 'response:',\n xhr.responseText\n );\n let res = null;\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = jsonEval(xhr.responseText);\n } catch (e) {\n warn(\n 'Failed to parse JSON response for ' +\n url +\n ': ' +\n xhr.responseText\n );\n }\n callback(null, res);\n } else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n warn(\n 'Got unsuccessful REST response for ' +\n url +\n ' Status: ' +\n xhr.status\n );\n }\n callback(xhr.status);\n }\n callback = null;\n }\n };\n\n xhr.open('GET', url, /*asynchronous=*/ true);\n xhr.send();\n });\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { Path } from './util/Path';\n\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n */\nexport class SnapshotHolder {\n private rootNode_: Node = ChildrenNode.EMPTY_NODE;\n\n getNode(path: Path): Node {\n return this.rootNode_.getChild(path);\n }\n\n updateSnapshot(path: Path, newSnapshotNode: Node) {\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { Node } from './snap/Node';\nimport { Path, pathGetFront, pathIsEmpty, pathPopFront } from './util/Path';\n\n/**\n * Helper class to store a sparse set of snapshots.\n */\nexport interface SparseSnapshotTree {\n value: Node | null;\n readonly children: Map;\n}\n\nexport function newSparseSnapshotTree(): SparseSnapshotTree {\n return {\n value: null,\n children: new Map()\n };\n}\n\n/**\n * Gets the node stored at the given path if one exists.\n * Only seems to be used in tests.\n *\n * @param path - Path to look up snapshot for.\n * @returns The retrieved node, or null.\n */\nexport function sparseSnapshotTreeFind(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path\n): Node | null {\n if (sparseSnapshotTree.value != null) {\n return sparseSnapshotTree.value.getChild(path);\n } else if (!pathIsEmpty(path) && sparseSnapshotTree.children.size > 0) {\n const childKey = pathGetFront(path);\n path = pathPopFront(path);\n if (sparseSnapshotTree.children.has(childKey)) {\n const childTree = sparseSnapshotTree.children.get(childKey);\n return sparseSnapshotTreeFind(childTree, path);\n } else {\n return null;\n }\n } else {\n return null;\n }\n}\n\n/**\n * Stores the given node at the specified path. If there is already a node\n * at a shallower path, it merges the new data into that snapshot node.\n *\n * @param path - Path to look up snapshot for.\n * @param data - The new data, or null.\n */\nexport function sparseSnapshotTreeRemember(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path,\n data: Node\n): void {\n if (pathIsEmpty(path)) {\n sparseSnapshotTree.value = data;\n sparseSnapshotTree.children.clear();\n } else if (sparseSnapshotTree.value !== null) {\n sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);\n } else {\n const childKey = pathGetFront(path);\n if (!sparseSnapshotTree.children.has(childKey)) {\n sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());\n }\n\n const child = sparseSnapshotTree.children.get(childKey);\n path = pathPopFront(path);\n sparseSnapshotTreeRemember(child, path, data);\n }\n}\n\n/**\n * Purge the data at path from the cache.\n *\n * @param path - Path to look up snapshot for.\n * @returns True if this node should now be removed.\n */\nexport function sparseSnapshotTreeForget(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path\n): boolean {\n if (pathIsEmpty(path)) {\n sparseSnapshotTree.value = null;\n sparseSnapshotTree.children.clear();\n return true;\n } else {\n if (sparseSnapshotTree.value !== null) {\n if (sparseSnapshotTree.value.isLeafNode()) {\n // We're trying to forget a node that doesn't exist\n return false;\n } else {\n const value = sparseSnapshotTree.value;\n sparseSnapshotTree.value = null;\n\n value.forEachChild(PRIORITY_INDEX, (key, tree) => {\n sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);\n });\n\n return sparseSnapshotTreeForget(sparseSnapshotTree, path);\n }\n } else if (sparseSnapshotTree.children.size > 0) {\n const childKey = pathGetFront(path);\n path = pathPopFront(path);\n if (sparseSnapshotTree.children.has(childKey)) {\n const safeToRemove = sparseSnapshotTreeForget(\n sparseSnapshotTree.children.get(childKey),\n path\n );\n if (safeToRemove) {\n sparseSnapshotTree.children.delete(childKey);\n }\n }\n\n return sparseSnapshotTree.children.size === 0;\n } else {\n return true;\n }\n }\n}\n\n/**\n * Recursively iterates through all of the stored tree and calls the\n * callback on each one.\n *\n * @param prefixPath - Path to look up node for.\n * @param func - The function to invoke for each tree.\n */\nexport function sparseSnapshotTreeForEachTree(\n sparseSnapshotTree: SparseSnapshotTree,\n prefixPath: Path,\n func: (a: Path, b: Node) => unknown\n): void {\n if (sparseSnapshotTree.value !== null) {\n func(prefixPath, sparseSnapshotTree.value);\n } else {\n sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {\n const path = new Path(prefixPath.toString() + '/' + key);\n sparseSnapshotTreeForEachTree(tree, path, func);\n });\n }\n}\n\n/**\n * Iterates through each immediate child and triggers the callback.\n * Only seems to be used in tests.\n *\n * @param func - The function to invoke for each child.\n */\nexport function sparseSnapshotTreeForEachChild(\n sparseSnapshotTree: SparseSnapshotTree,\n func: (a: string, b: SparseSnapshotTree) => void\n): void {\n sparseSnapshotTree.children.forEach((tree, key) => {\n func(key, tree);\n });\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { each } from '../util/util';\n\nimport { StatsCollection } from './StatsCollection';\n\n/**\n * Returns the delta from the previous call to get stats.\n *\n * @param collection_ - The collection to \"listen\" to.\n */\nexport class StatsListener {\n private last_: { [k: string]: number } | null = null;\n\n constructor(private collection_: StatsCollection) {}\n\n get(): { [k: string]: number } {\n const newStats = this.collection_.get();\n\n const delta = { ...newStats };\n if (this.last_) {\n each(this.last_, (stat: string, value: number) => {\n delta[stat] = delta[stat] - value;\n });\n }\n this.last_ = newStats;\n\n return delta;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains } from '@firebase/util';\n\nimport { ServerActions } from '../ServerActions';\nimport { setTimeoutNonBlocking, each } from '../util/util';\n\nimport { StatsCollection } from './StatsCollection';\nimport { StatsListener } from './StatsListener';\n\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\n// seconds to try to ensure the Firebase connection is established / settled.\nconst FIRST_STATS_MIN_TIME = 10 * 1000;\nconst FIRST_STATS_MAX_TIME = 30 * 1000;\n\n// We'll continue to report stats on average every 5 minutes.\nconst REPORT_STATS_INTERVAL = 5 * 60 * 1000;\n\nexport class StatsReporter {\n private statsListener_: StatsListener;\n statsToReport_: { [k: string]: boolean } = {};\n\n constructor(collection: StatsCollection, private server_: ServerActions) {\n this.statsListener_ = new StatsListener(collection);\n\n const timeout =\n FIRST_STATS_MIN_TIME +\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n }\n\n private reportStats_() {\n const stats = this.statsListener_.get();\n const reportedStats: typeof stats = {};\n let haveStatsToReport = false;\n\n each(stats, (stat: string, value: number) => {\n if (value > 0 && contains(this.statsToReport_, stat)) {\n reportedStats[stat] = value;\n haveStatsToReport = true;\n }\n });\n\n if (haveStatsToReport) {\n this.server_.reportStats(reportedStats);\n }\n\n // queue our next run.\n setTimeoutNonBlocking(\n this.reportStats_.bind(this),\n Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL)\n );\n }\n}\n\nexport function statsReporterIncludeStat(\n reporter: StatsReporter,\n stat: string\n) {\n reporter.statsToReport_[stat] = true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Path } from '../util/Path';\n\n/**\n *\n * @enum\n */\nexport enum OperationType {\n OVERWRITE,\n MERGE,\n ACK_USER_WRITE,\n LISTEN_COMPLETE\n}\n\n/**\n * @interface\n */\nexport interface Operation {\n source: OperationSource;\n\n type: OperationType;\n\n path: Path;\n\n operationForChild(childName: string): Operation | null;\n}\n\nexport interface OperationSource {\n fromUser: boolean;\n fromServer: boolean;\n queryId: string | null;\n tagged: boolean;\n}\n\nexport function newOperationSourceUser(): OperationSource {\n return {\n fromUser: true,\n fromServer: false,\n queryId: null,\n tagged: false\n };\n}\n\nexport function newOperationSourceServer(): OperationSource {\n return {\n fromUser: false,\n fromServer: true,\n queryId: null,\n tagged: false\n };\n}\n\nexport function newOperationSourceServerTaggedQuery(\n queryId: string\n): OperationSource {\n return {\n fromUser: false,\n fromServer: true,\n queryId,\n tagged: true\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\n\nimport { newOperationSourceUser, Operation, OperationType } from './Operation';\n\nexport class AckUserWrite implements Operation {\n /** @inheritDoc */\n type = OperationType.ACK_USER_WRITE;\n\n /** @inheritDoc */\n source = newOperationSourceUser();\n\n /**\n * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.\n */\n constructor(\n /** @inheritDoc */ public path: Path,\n /** @inheritDoc */ public affectedTree: ImmutableTree,\n /** @inheritDoc */ public revert: boolean\n ) {}\n operationForChild(childName: string): AckUserWrite {\n if (!pathIsEmpty(this.path)) {\n assert(\n pathGetFront(this.path) === childName,\n 'operationForChild called for unrelated child.'\n );\n return new AckUserWrite(\n pathPopFront(this.path),\n this.affectedTree,\n this.revert\n );\n } else if (this.affectedTree.value != null) {\n assert(\n this.affectedTree.children.isEmpty(),\n 'affectedTree should not have overlapping affected paths.'\n );\n // All child locations are affected as well; just return same operation.\n return this;\n } else {\n const childTree = this.affectedTree.subtree(new Path(childName));\n return new AckUserWrite(newEmptyPath(), childTree, this.revert);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { newEmptyPath, Path, pathIsEmpty, pathPopFront } from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './Operation';\n\nexport class ListenComplete implements Operation {\n /** @inheritDoc */\n type = OperationType.LISTEN_COMPLETE;\n\n constructor(public source: OperationSource, public path: Path) {}\n\n operationForChild(childName: string): ListenComplete {\n if (pathIsEmpty(this.path)) {\n return new ListenComplete(this.source, newEmptyPath());\n } else {\n return new ListenComplete(this.source, pathPopFront(this.path));\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\nimport { newEmptyPath, Path, pathIsEmpty, pathPopFront } from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './Operation';\n\nexport class Overwrite implements Operation {\n /** @inheritDoc */\n type = OperationType.OVERWRITE;\n\n constructor(\n public source: OperationSource,\n public path: Path,\n public snap: Node\n ) {}\n\n operationForChild(childName: string): Overwrite {\n if (pathIsEmpty(this.path)) {\n return new Overwrite(\n this.source,\n newEmptyPath(),\n this.snap.getImmediateChild(childName)\n );\n } else {\n return new Overwrite(this.source, pathPopFront(this.path), this.snap);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Node } from '../snap/Node';\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './Operation';\nimport { Overwrite } from './Overwrite';\n\nexport class Merge implements Operation {\n /** @inheritDoc */\n type = OperationType.MERGE;\n\n constructor(\n /** @inheritDoc */ public source: OperationSource,\n /** @inheritDoc */ public path: Path,\n /** @inheritDoc */ public children: ImmutableTree\n ) {}\n operationForChild(childName: string): Operation {\n if (pathIsEmpty(this.path)) {\n const childTree = this.children.subtree(new Path(childName));\n if (childTree.isEmpty()) {\n // This child is unaffected\n return null;\n } else if (childTree.value) {\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\n return new Overwrite(this.source, newEmptyPath(), childTree.value);\n } else {\n // This is a merge at a deeper level\n return new Merge(this.source, newEmptyPath(), childTree);\n }\n } else {\n assert(\n pathGetFront(this.path) === childName,\n \"Can't get a merge for a child not on the path of the operation\"\n );\n return new Merge(this.source, pathPopFront(this.path), this.children);\n }\n }\n toString(): string {\n return (\n 'Operation(' +\n this.path +\n ': ' +\n this.source.toString() +\n ' merge: ' +\n this.children.toString() +\n ')'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\nimport { Path, pathGetFront, pathIsEmpty } from '../util/Path';\n\n/**\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\n * whether a node potentially had children removed due to a filter.\n */\nexport class CacheNode {\n constructor(\n private node_: Node,\n private fullyInitialized_: boolean,\n private filtered_: boolean\n ) {}\n\n /**\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\n */\n isFullyInitialized(): boolean {\n return this.fullyInitialized_;\n }\n\n /**\n * Returns whether this node is potentially missing children due to a filter applied to the node\n */\n isFiltered(): boolean {\n return this.filtered_;\n }\n\n isCompleteForPath(path: Path): boolean {\n if (pathIsEmpty(path)) {\n return this.isFullyInitialized() && !this.filtered_;\n }\n\n const childKey = pathGetFront(path);\n return this.isCompleteForChild(childKey);\n }\n\n isCompleteForChild(key: string): boolean {\n return (\n (this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key)\n );\n }\n\n getNode(): Node {\n return this.node_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assertionError } from '@firebase/util';\n\nimport { Index } from '../snap/indexes/Index';\nimport { NamedNode, Node } from '../snap/Node';\n\nimport { Change, ChangeType, changeChildMoved } from './Change';\nimport { Event } from './Event';\nimport { EventRegistration, QueryContext } from './EventRegistration';\n\n/**\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\n * for details.\n *\n */\nexport class EventGenerator {\n index_: Index;\n\n constructor(public query_: QueryContext) {\n this.index_ = this.query_._queryParams.getIndex();\n }\n}\n\n/**\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\n *\n * Notes:\n * - child_moved events will be synthesized at this time for any child_changed events that affect\n * our index.\n * - prevName will be calculated based on the index ordering.\n */\nexport function eventGeneratorGenerateEventsForChanges(\n eventGenerator: EventGenerator,\n changes: Change[],\n eventCache: Node,\n eventRegistrations: EventRegistration[]\n): Event[] {\n const events: Event[] = [];\n const moves: Change[] = [];\n\n changes.forEach(change => {\n if (\n change.type === ChangeType.CHILD_CHANGED &&\n eventGenerator.index_.indexedValueChanged(\n change.oldSnap as Node,\n change.snapshotNode\n )\n ) {\n moves.push(changeChildMoved(change.childName, change.snapshotNode));\n }\n });\n\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_REMOVED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_ADDED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_MOVED,\n moves,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_CHANGED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.VALUE,\n changes,\n eventRegistrations,\n eventCache\n );\n\n return events;\n}\n\n/**\n * Given changes of a single change type, generate the corresponding events.\n */\nfunction eventGeneratorGenerateEventsForType(\n eventGenerator: EventGenerator,\n events: Event[],\n eventType: string,\n changes: Change[],\n registrations: EventRegistration[],\n eventCache: Node\n) {\n const filteredChanges = changes.filter(change => change.type === eventType);\n\n filteredChanges.sort((a, b) =>\n eventGeneratorCompareChanges(eventGenerator, a, b)\n );\n filteredChanges.forEach(change => {\n const materializedChange = eventGeneratorMaterializeSingleChange(\n eventGenerator,\n change,\n eventCache\n );\n registrations.forEach(registration => {\n if (registration.respondsTo(change.type)) {\n events.push(\n registration.createEvent(materializedChange, eventGenerator.query_)\n );\n }\n });\n });\n}\n\nfunction eventGeneratorMaterializeSingleChange(\n eventGenerator: EventGenerator,\n change: Change,\n eventCache: Node\n): Change {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n } else {\n change.prevName = eventCache.getPredecessorChildName(\n change.childName,\n change.snapshotNode,\n eventGenerator.index_\n );\n return change;\n }\n}\n\nfunction eventGeneratorCompareChanges(\n eventGenerator: EventGenerator,\n a: Change,\n b: Change\n) {\n if (a.childName == null || b.childName == null) {\n throw assertionError('Should only compare child_ events.');\n }\n const aWrapped = new NamedNode(a.childName, a.snapshotNode);\n const bWrapped = new NamedNode(b.childName, b.snapshotNode);\n return eventGenerator.index_.compare(aWrapped, bWrapped);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\n\nimport { CacheNode } from './CacheNode';\n\n/**\n * Stores the data we have cached for a view.\n *\n * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes).\n */\nexport interface ViewCache {\n readonly eventCache: CacheNode;\n readonly serverCache: CacheNode;\n}\n\nexport function newViewCache(\n eventCache: CacheNode,\n serverCache: CacheNode\n): ViewCache {\n return { eventCache, serverCache };\n}\n\nexport function viewCacheUpdateEventSnap(\n viewCache: ViewCache,\n eventSnap: Node,\n complete: boolean,\n filtered: boolean\n): ViewCache {\n return newViewCache(\n new CacheNode(eventSnap, complete, filtered),\n viewCache.serverCache\n );\n}\n\nexport function viewCacheUpdateServerSnap(\n viewCache: ViewCache,\n serverSnap: Node,\n complete: boolean,\n filtered: boolean\n): ViewCache {\n return newViewCache(\n viewCache.eventCache,\n new CacheNode(serverSnap, complete, filtered)\n );\n}\n\nexport function viewCacheGetCompleteEventSnap(\n viewCache: ViewCache\n): Node | null {\n return viewCache.eventCache.isFullyInitialized()\n ? viewCache.eventCache.getNode()\n : null;\n}\n\nexport function viewCacheGetCompleteServerSnap(\n viewCache: ViewCache\n): Node | null {\n return viewCache.serverCache.isFullyInitialized()\n ? viewCache.serverCache.getNode()\n : null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n newEmptyPath,\n Path,\n pathChild,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from './Path';\nimport { SortedMap } from './SortedMap';\nimport { each, stringCompare } from './util';\n\nlet emptyChildrenSingleton: SortedMap>;\n\n/**\n * Singleton empty children collection.\n *\n */\nconst EmptyChildren = (): SortedMap> => {\n if (!emptyChildrenSingleton) {\n emptyChildrenSingleton = new SortedMap>(\n stringCompare\n );\n }\n return emptyChildrenSingleton;\n};\n\n/**\n * A tree with immutable elements.\n */\nexport class ImmutableTree {\n static fromObject(obj: { [k: string]: T }): ImmutableTree {\n let tree: ImmutableTree = new ImmutableTree(null);\n each(obj, (childPath: string, childSnap: T) => {\n tree = tree.set(new Path(childPath), childSnap);\n });\n return tree;\n }\n\n constructor(\n public readonly value: T | null,\n public readonly children: SortedMap<\n string,\n ImmutableTree\n > = EmptyChildren()\n ) {}\n\n /**\n * True if the value is empty and there are no children\n */\n isEmpty(): boolean {\n return this.value === null && this.children.isEmpty();\n }\n\n /**\n * Given a path and predicate, return the first node and the path to that node\n * where the predicate returns true.\n *\n * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`\n * objects on the way back out, it may be better to pass down a pathSoFar obj.\n *\n * @param relativePath - The remainder of the path\n * @param predicate - The predicate to satisfy to return a node\n */\n findRootMostMatchingPathAndValue(\n relativePath: Path,\n predicate: (a: T) => boolean\n ): { path: Path; value: T } | null {\n if (this.value != null && predicate(this.value)) {\n return { path: newEmptyPath(), value: this.value };\n } else {\n if (pathIsEmpty(relativePath)) {\n return null;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child !== null) {\n const childExistingPathAndValue =\n child.findRootMostMatchingPathAndValue(\n pathPopFront(relativePath),\n predicate\n );\n if (childExistingPathAndValue != null) {\n const fullPath = pathChild(\n new Path(front),\n childExistingPathAndValue.path\n );\n return { path: fullPath, value: childExistingPathAndValue.value };\n } else {\n return null;\n }\n } else {\n return null;\n }\n }\n }\n }\n\n /**\n * Find, if it exists, the shortest subpath of the given path that points a defined\n * value in the tree\n */\n findRootMostValueAndPath(\n relativePath: Path\n ): { path: Path; value: T } | null {\n return this.findRootMostMatchingPathAndValue(relativePath, () => true);\n }\n\n /**\n * @returns The subtree at the given path\n */\n subtree(relativePath: Path): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n return this;\n } else {\n const front = pathGetFront(relativePath);\n const childTree = this.children.get(front);\n if (childTree !== null) {\n return childTree.subtree(pathPopFront(relativePath));\n } else {\n return new ImmutableTree(null);\n }\n }\n }\n\n /**\n * Sets a value at the specified path.\n *\n * @param relativePath - Path to set value at.\n * @param toSet - Value to set.\n * @returns Resulting tree.\n */\n set(relativePath: Path, toSet: T | null): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n return new ImmutableTree(toSet, this.children);\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front) || new ImmutableTree(null);\n const newChild = child.set(pathPopFront(relativePath), toSet);\n const newChildren = this.children.insert(front, newChild);\n return new ImmutableTree(this.value, newChildren);\n }\n }\n\n /**\n * Removes the value at the specified path.\n *\n * @param relativePath - Path to value to remove.\n * @returns Resulting tree.\n */\n remove(relativePath: Path): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n if (this.children.isEmpty()) {\n return new ImmutableTree(null);\n } else {\n return new ImmutableTree(null, this.children);\n }\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child) {\n const newChild = child.remove(pathPopFront(relativePath));\n let newChildren;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n } else {\n newChildren = this.children.insert(front, newChild);\n }\n if (this.value === null && newChildren.isEmpty()) {\n return new ImmutableTree(null);\n } else {\n return new ImmutableTree(this.value, newChildren);\n }\n } else {\n return this;\n }\n }\n }\n\n /**\n * Gets a value from the tree.\n *\n * @param relativePath - Path to get value for.\n * @returns Value at path, or null.\n */\n get(relativePath: Path): T | null {\n if (pathIsEmpty(relativePath)) {\n return this.value;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child) {\n return child.get(pathPopFront(relativePath));\n } else {\n return null;\n }\n }\n }\n\n /**\n * Replace the subtree at the specified path with the given new tree.\n *\n * @param relativePath - Path to replace subtree for.\n * @param newTree - New tree.\n * @returns Resulting tree.\n */\n setTree(relativePath: Path, newTree: ImmutableTree): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n return newTree;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front) || new ImmutableTree(null);\n const newChild = child.setTree(pathPopFront(relativePath), newTree);\n let newChildren;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n } else {\n newChildren = this.children.insert(front, newChild);\n }\n return new ImmutableTree(this.value, newChildren);\n }\n }\n\n /**\n * Performs a depth first fold on this tree. Transforms a tree into a single\n * value, given a function that operates on the path to a node, an optional\n * current value, and a map of child names to folded subtrees\n */\n fold(fn: (path: Path, value: T, children: { [k: string]: V }) => V): V {\n return this.fold_(newEmptyPath(), fn);\n }\n\n /**\n * Recursive helper for public-facing fold() method\n */\n private fold_(\n pathSoFar: Path,\n fn: (path: Path, value: T | null, children: { [k: string]: V }) => V\n ): V {\n const accum: { [k: string]: V } = {};\n this.children.inorderTraversal(\n (childKey: string, childTree: ImmutableTree) => {\n accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);\n }\n );\n return fn(pathSoFar, this.value, accum);\n }\n\n /**\n * Find the first matching value on the given path. Return the result of applying f to it.\n */\n findOnPath(path: Path, f: (path: Path, value: T) => V | null): V | null {\n return this.findOnPath_(path, newEmptyPath(), f);\n }\n\n private findOnPath_(\n pathToFollow: Path,\n pathSoFar: Path,\n f: (path: Path, value: T) => V | null\n ): V | null {\n const result = this.value ? f(pathSoFar, this.value) : false;\n if (result) {\n return result;\n } else {\n if (pathIsEmpty(pathToFollow)) {\n return null;\n } else {\n const front = pathGetFront(pathToFollow)!;\n const nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.findOnPath_(\n pathPopFront(pathToFollow),\n pathChild(pathSoFar, front),\n f\n );\n } else {\n return null;\n }\n }\n }\n }\n\n foreachOnPath(\n path: Path,\n f: (path: Path, value: T) => void\n ): ImmutableTree {\n return this.foreachOnPath_(path, newEmptyPath(), f);\n }\n\n private foreachOnPath_(\n pathToFollow: Path,\n currentRelativePath: Path,\n f: (path: Path, value: T) => void\n ): ImmutableTree {\n if (pathIsEmpty(pathToFollow)) {\n return this;\n } else {\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n const front = pathGetFront(pathToFollow);\n const nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.foreachOnPath_(\n pathPopFront(pathToFollow),\n pathChild(currentRelativePath, front),\n f\n );\n } else {\n return new ImmutableTree(null);\n }\n }\n }\n\n /**\n * Calls the given function for each node in the tree that has a value.\n *\n * @param f - A function to be called with the path from the root of the tree to\n * a node, and the value at that node. Called in depth-first order.\n */\n foreach(f: (path: Path, value: T) => void) {\n this.foreach_(newEmptyPath(), f);\n }\n\n private foreach_(\n currentRelativePath: Path,\n f: (path: Path, value: T) => void\n ) {\n this.children.inorderTraversal((childName, childTree) => {\n childTree.foreach_(pathChild(currentRelativePath, childName), f);\n });\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n }\n\n foreachChild(f: (name: string, value: T) => void) {\n this.children.inorderTraversal(\n (childName: string, childTree: ImmutableTree) => {\n if (childTree.value) {\n f(childName, childTree.value);\n }\n }\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { NamedNode, Node } from './snap/Node';\nimport { ImmutableTree } from './util/ImmutableTree';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathIsEmpty\n} from './util/Path';\nimport { each } from './util/util';\n\n/**\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\n * to reflect the write added.\n */\nexport class CompoundWrite {\n constructor(public writeTree_: ImmutableTree) {}\n\n static empty(): CompoundWrite {\n return new CompoundWrite(new ImmutableTree(null));\n }\n}\n\nexport function compoundWriteAddWrite(\n compoundWrite: CompoundWrite,\n path: Path,\n node: Node\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return new CompoundWrite(new ImmutableTree(node));\n } else {\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n const rootMostPath = rootmost.path;\n let value = rootmost.value;\n const relativePath = newRelativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(\n compoundWrite.writeTree_.set(rootMostPath, value)\n );\n } else {\n const subtree = new ImmutableTree(node);\n const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n}\n\nexport function compoundWriteAddWrites(\n compoundWrite: CompoundWrite,\n path: Path,\n updates: { [name: string]: Node }\n): CompoundWrite {\n let newWrite = compoundWrite;\n each(updates, (childKey: string, node: Node) => {\n newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);\n });\n return newWrite;\n}\n\n/**\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param compoundWrite - The CompoundWrite to remove.\n * @param path - The path at which a write and all deeper writes should be removed\n * @returns The new CompoundWrite with the removed path\n */\nexport function compoundWriteRemoveWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return CompoundWrite.empty();\n } else {\n const newWriteTree = compoundWrite.writeTree_.setTree(\n path,\n new ImmutableTree(null)\n );\n return new CompoundWrite(newWriteTree);\n }\n}\n\n/**\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\n * considered \"complete\".\n *\n * @param compoundWrite - The CompoundWrite to check.\n * @param path - The path to check for\n * @returns Whether there is a complete write at that path\n */\nexport function compoundWriteHasCompleteWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): boolean {\n return compoundWriteGetCompleteNode(compoundWrite, path) != null;\n}\n\n/**\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\n * writes from deeper paths, but will return child nodes from a more shallow path.\n *\n * @param compoundWrite - The CompoundWrite to get the node from.\n * @param path - The path to get a complete write\n * @returns The node if complete at that path, or null otherwise.\n */\nexport function compoundWriteGetCompleteNode(\n compoundWrite: CompoundWrite,\n path: Path\n): Node | null {\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return compoundWrite.writeTree_\n .get(rootmost.path)\n .getChild(newRelativePath(rootmost.path, path));\n } else {\n return null;\n }\n}\n\n/**\n * Returns all children that are guaranteed to be a complete overwrite.\n *\n * @param compoundWrite - The CompoundWrite to get children from.\n * @returns A list of all complete children.\n */\nexport function compoundWriteGetCompleteChildren(\n compoundWrite: CompoundWrite\n): NamedNode[] {\n const children: NamedNode[] = [];\n const node = compoundWrite.writeTree_.value;\n if (node != null) {\n // If it's a leaf node, it has no children; so nothing to do.\n if (!node.isLeafNode()) {\n (node as ChildrenNode).forEachChild(\n PRIORITY_INDEX,\n (childName, childNode) => {\n children.push(new NamedNode(childName, childNode));\n }\n );\n }\n } else {\n compoundWrite.writeTree_.children.inorderTraversal(\n (childName, childTree) => {\n if (childTree.value != null) {\n children.push(new NamedNode(childName, childTree.value));\n }\n }\n );\n }\n return children;\n}\n\nexport function compoundWriteChildCompoundWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return compoundWrite;\n } else {\n const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree(shadowingNode));\n } else {\n return new CompoundWrite(compoundWrite.writeTree_.subtree(path));\n }\n }\n}\n\n/**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @returns Whether this CompoundWrite is empty\n */\nexport function compoundWriteIsEmpty(compoundWrite: CompoundWrite): boolean {\n return compoundWrite.writeTree_.isEmpty();\n}\n\n/**\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\n * node\n * @param node - The node to apply this CompoundWrite to\n * @returns The node with all writes applied\n */\nexport function compoundWriteApply(\n compoundWrite: CompoundWrite,\n node: Node\n): Node {\n return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);\n}\n\nfunction applySubtreeWrite(\n relativePath: Path,\n writeTree: ImmutableTree,\n node: Node\n): Node {\n if (writeTree.value != null) {\n // Since there a write is always a leaf, we're done here\n return node.updateChild(relativePath, writeTree.value);\n } else {\n let priorityWrite = null;\n writeTree.children.inorderTraversal((childKey, childTree) => {\n if (childKey === '.priority') {\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\n // to apply priorities to empty nodes that are later filled\n assert(\n childTree.value !== null,\n 'Priority writes must always be leaf nodes'\n );\n priorityWrite = childTree.value;\n } else {\n node = applySubtreeWrite(\n pathChild(relativePath, childKey),\n childTree,\n node\n );\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {\n node = node.updateChild(\n pathChild(relativePath, '.priority'),\n priorityWrite\n );\n }\n return node;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError, safeGet } from '@firebase/util';\n\nimport {\n CompoundWrite,\n compoundWriteAddWrite,\n compoundWriteAddWrites,\n compoundWriteApply,\n compoundWriteChildCompoundWrite,\n compoundWriteGetCompleteChildren,\n compoundWriteGetCompleteNode,\n compoundWriteHasCompleteWrite,\n compoundWriteIsEmpty,\n compoundWriteRemoveWrite\n} from './CompoundWrite';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Index } from './snap/indexes/Index';\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { NamedNode, Node } from './snap/Node';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathContains,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from './util/Path';\nimport { each } from './util/util';\nimport { CacheNode } from './view/CacheNode';\n\n/**\n * Defines a single user-initiated write operation. May be the result of a set(), transaction(), or update() call. In\n * the case of a set() or transaction, snap will be non-null. In the case of an update(), children will be non-null.\n */\nexport interface WriteRecord {\n writeId: number;\n path: Path;\n snap?: Node | null;\n children?: { [k: string]: Node } | null;\n visible: boolean;\n}\n\n/**\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n */\nexport function writeTreeChildWrites(\n writeTree: WriteTree,\n path: Path\n): WriteTreeRef {\n return newWriteTreeRef(path, writeTree);\n}\n\n/**\n * Record a new overwrite from user code.\n *\n * @param visible - This is set to false by some transactions. It should be excluded from event caches\n */\nexport function writeTreeAddOverwrite(\n writeTree: WriteTree,\n path: Path,\n snap: Node,\n writeId: number,\n visible?: boolean\n) {\n assert(\n writeId > writeTree.lastWriteId,\n 'Stacking an older write on top of newer ones'\n );\n if (visible === undefined) {\n visible = true;\n }\n writeTree.allWrites.push({\n path,\n snap,\n writeId,\n visible\n });\n\n if (visible) {\n writeTree.visibleWrites = compoundWriteAddWrite(\n writeTree.visibleWrites,\n path,\n snap\n );\n }\n writeTree.lastWriteId = writeId;\n}\n\n/**\n * Record a new merge from user code.\n */\nexport function writeTreeAddMerge(\n writeTree: WriteTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n writeId: number\n) {\n assert(\n writeId > writeTree.lastWriteId,\n 'Stacking an older merge on top of newer ones'\n );\n writeTree.allWrites.push({\n path,\n children: changedChildren,\n writeId,\n visible: true\n });\n\n writeTree.visibleWrites = compoundWriteAddWrites(\n writeTree.visibleWrites,\n path,\n changedChildren\n );\n writeTree.lastWriteId = writeId;\n}\n\nexport function writeTreeGetWrite(\n writeTree: WriteTree,\n writeId: number\n): WriteRecord | null {\n for (let i = 0; i < writeTree.allWrites.length; i++) {\n const record = writeTree.allWrites[i];\n if (record.writeId === writeId) {\n return record;\n }\n }\n return null;\n}\n\n/**\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\n *\n * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\nexport function writeTreeRemoveWrite(\n writeTree: WriteTree,\n writeId: number\n): boolean {\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\n // out of order.\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\n\n const idx = writeTree.allWrites.findIndex(s => {\n return s.writeId === writeId;\n });\n assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n const writeToRemove = writeTree.allWrites[idx];\n writeTree.allWrites.splice(idx, 1);\n\n let removedWriteWasVisible = writeToRemove.visible;\n let removedWriteOverlapsWithOtherWrites = false;\n\n let i = writeTree.allWrites.length - 1;\n\n while (removedWriteWasVisible && i >= 0) {\n const currentWrite = writeTree.allWrites[i];\n if (currentWrite.visible) {\n if (\n i >= idx &&\n writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)\n ) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\n } else if (pathContains(writeToRemove.path, currentWrite.path)) {\n // Either we're covering some writes or they're covering part of us (depending on which came first).\n removedWriteOverlapsWithOtherWrites = true;\n }\n }\n i--;\n }\n\n if (!removedWriteWasVisible) {\n return false;\n } else if (removedWriteOverlapsWithOtherWrites) {\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\n writeTreeResetTree_(writeTree);\n return true;\n } else {\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\n if (writeToRemove.snap) {\n writeTree.visibleWrites = compoundWriteRemoveWrite(\n writeTree.visibleWrites,\n writeToRemove.path\n );\n } else {\n const children = writeToRemove.children;\n each(children, (childName: string) => {\n writeTree.visibleWrites = compoundWriteRemoveWrite(\n writeTree.visibleWrites,\n pathChild(writeToRemove.path, childName)\n );\n });\n }\n return true;\n }\n}\n\nfunction writeTreeRecordContainsPath_(\n writeRecord: WriteRecord,\n path: Path\n): boolean {\n if (writeRecord.snap) {\n return pathContains(writeRecord.path, path);\n } else {\n for (const childName in writeRecord.children) {\n if (\n writeRecord.children.hasOwnProperty(childName) &&\n pathContains(pathChild(writeRecord.path, childName), path)\n ) {\n return true;\n }\n }\n return false;\n }\n}\n\n/**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\n */\nfunction writeTreeResetTree_(writeTree: WriteTree) {\n writeTree.visibleWrites = writeTreeLayerTree_(\n writeTree.allWrites,\n writeTreeDefaultFilter_,\n newEmptyPath()\n );\n if (writeTree.allWrites.length > 0) {\n writeTree.lastWriteId =\n writeTree.allWrites[writeTree.allWrites.length - 1].writeId;\n } else {\n writeTree.lastWriteId = -1;\n }\n}\n\n/**\n * The default filter used when constructing the tree. Keep everything that's visible.\n */\nfunction writeTreeDefaultFilter_(write: WriteRecord) {\n return write.visible;\n}\n\n/**\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\n * event data at that path.\n */\nfunction writeTreeLayerTree_(\n writes: WriteRecord[],\n filter: (w: WriteRecord) => boolean,\n treeRoot: Path\n): CompoundWrite {\n let compoundWrite = CompoundWrite.empty();\n for (let i = 0; i < writes.length; ++i) {\n const write = writes[i];\n // Theory, a later set will either:\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\n if (filter(write)) {\n const writePath = write.path;\n let relativePath: Path;\n if (write.snap) {\n if (pathContains(treeRoot, writePath)) {\n relativePath = newRelativePath(treeRoot, writePath);\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n relativePath,\n write.snap\n );\n } else if (pathContains(writePath, treeRoot)) {\n relativePath = newRelativePath(writePath, treeRoot);\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n newEmptyPath(),\n write.snap.getChild(relativePath)\n );\n } else {\n // There is no overlap between root path and write path, ignore write\n }\n } else if (write.children) {\n if (pathContains(treeRoot, writePath)) {\n relativePath = newRelativePath(treeRoot, writePath);\n compoundWrite = compoundWriteAddWrites(\n compoundWrite,\n relativePath,\n write.children\n );\n } else if (pathContains(writePath, treeRoot)) {\n relativePath = newRelativePath(writePath, treeRoot);\n if (pathIsEmpty(relativePath)) {\n compoundWrite = compoundWriteAddWrites(\n compoundWrite,\n newEmptyPath(),\n write.children\n );\n } else {\n const child = safeGet(write.children, pathGetFront(relativePath));\n if (child) {\n // There exists a child in this node that matches the root path\n const deepNode = child.getChild(pathPopFront(relativePath));\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n newEmptyPath(),\n deepNode\n );\n }\n }\n } else {\n // There is no overlap between root path and write path, ignore write\n }\n } else {\n throw assertionError('WriteRecord should have .snap or .children');\n }\n }\n }\n return compoundWrite;\n}\n\n/**\n * Return a complete snapshot for the given path if there's visible write data at that path, else null.\n * No server data is considered.\n *\n */\nexport function writeTreeGetCompleteWriteData(\n writeTree: WriteTree,\n path: Path\n): Node | null {\n return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\n}\n\n/**\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\n * writes), attempt to calculate a complete snapshot for the given path\n *\n * @param writeIdsToExclude - An optional set to be excluded\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\n */\nexport function writeTreeCalcCompleteEventCache(\n writeTree: WriteTree,\n treePath: Path,\n completeServerCache: Node | null,\n writeIdsToExclude?: number[],\n includeHiddenWrites?: boolean\n): Node | null {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n const shadowingNode = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n treePath\n );\n if (shadowingNode != null) {\n return shadowingNode;\n } else {\n const subMerge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n if (compoundWriteIsEmpty(subMerge)) {\n return completeServerCache;\n } else if (\n completeServerCache == null &&\n !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())\n ) {\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n return null;\n } else {\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\n return compoundWriteApply(subMerge, layeredCache);\n }\n }\n } else {\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {\n return completeServerCache;\n } else {\n // If the server cache is null, and we don't have a complete cache, we need to return null\n if (\n !includeHiddenWrites &&\n completeServerCache == null &&\n !compoundWriteHasCompleteWrite(merge, newEmptyPath())\n ) {\n return null;\n } else {\n const filter = function (write: WriteRecord) {\n return (\n (write.visible || includeHiddenWrites) &&\n (!writeIdsToExclude ||\n !~writeIdsToExclude.indexOf(write.writeId)) &&\n (pathContains(write.path, treePath) ||\n pathContains(treePath, write.path))\n );\n };\n const mergeAtPath = writeTreeLayerTree_(\n writeTree.allWrites,\n filter,\n treePath\n );\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\n return compoundWriteApply(mergeAtPath, layeredCache);\n }\n }\n }\n}\n\n/**\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\n * Used when creating new views, to pre-fill their complete event children snapshot.\n */\nexport function writeTreeCalcCompleteEventChildren(\n writeTree: WriteTree,\n treePath: Path,\n completeServerChildren: ChildrenNode | null\n) {\n let completeChildren = ChildrenNode.EMPTY_NODE as Node;\n const topLevelSet = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n treePath\n );\n if (topLevelSet) {\n if (!topLevelSet.isLeafNode()) {\n // we're shadowing everything. Return the children.\n topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {\n completeChildren = completeChildren.updateImmediateChild(\n childName,\n childSnap\n );\n });\n }\n return completeChildren;\n } else if (completeServerChildren) {\n // Layer any children we have on top of this\n // We know we don't have a top-level set, so just enumerate existing children\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n completeServerChildren.forEachChild(\n PRIORITY_INDEX,\n (childName, childNode) => {\n const node = compoundWriteApply(\n compoundWriteChildCompoundWrite(merge, new Path(childName)),\n childNode\n );\n completeChildren = completeChildren.updateImmediateChild(\n childName,\n node\n );\n }\n );\n // Add any complete children we have from the set\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\n completeChildren = completeChildren.updateImmediateChild(\n namedNode.name,\n namedNode.node\n );\n });\n return completeChildren;\n } else {\n // We don't have anything to layer on top of. Layer on any children we have\n // Note that we can return an empty snap if we have a defined delete\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\n completeChildren = completeChildren.updateImmediateChild(\n namedNode.name,\n namedNode.node\n );\n });\n return completeChildren;\n }\n}\n\n/**\n * Given that the underlying server data has updated, determine what, if anything, needs to be\n * applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events\n *\n * Either existingEventSnap or existingServerSnap must exist\n */\nexport function writeTreeCalcEventCacheAfterServerOverwrite(\n writeTree: WriteTree,\n treePath: Path,\n childPath: Path,\n existingEventSnap: Node | null,\n existingServerSnap: Node | null\n): Node | null {\n assert(\n existingEventSnap || existingServerSnap,\n 'Either existingEventSnap or existingServerSnap must exist'\n );\n const path = pathChild(treePath, childPath);\n if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {\n // At this point we can probably guarantee that we're in case 2, meaning no events\n // May need to check visibility while doing the findRootMostValueAndPath call\n return null;\n } else {\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\n const childMerge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n path\n );\n if (compoundWriteIsEmpty(childMerge)) {\n // We're not shadowing at all. Case 1\n return existingServerSnap.getChild(childPath);\n } else {\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\n // However this is tricky to find out, since user updates don't necessary change the server\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\n // only check if the updates change the serverNode.\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\n return compoundWriteApply(\n childMerge,\n existingServerSnap.getChild(childPath)\n );\n }\n }\n}\n\n/**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n */\nexport function writeTreeCalcCompleteChild(\n writeTree: WriteTree,\n treePath: Path,\n childKey: string,\n existingServerSnap: CacheNode\n): Node | null {\n const path = pathChild(treePath, childKey);\n const shadowingNode = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n path\n );\n if (shadowingNode != null) {\n return shadowingNode;\n } else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n const childMerge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n path\n );\n return compoundWriteApply(\n childMerge,\n existingServerSnap.getNode().getImmediateChild(childKey)\n );\n } else {\n return null;\n }\n }\n}\n\n/**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n */\nexport function writeTreeShadowingWrite(\n writeTree: WriteTree,\n path: Path\n): Node | null {\n return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\n}\n\n/**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window.\n */\nexport function writeTreeCalcIndexedSlice(\n writeTree: WriteTree,\n treePath: Path,\n completeServerData: Node | null,\n startPost: NamedNode,\n count: number,\n reverse: boolean,\n index: Index\n): NamedNode[] {\n let toIterate: Node;\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n } else if (completeServerData != null) {\n toIterate = compoundWriteApply(merge, completeServerData);\n } else {\n // no children to iterate on\n return [];\n }\n toIterate = toIterate.withIndex(index);\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n const nodes = [];\n const cmp = index.getCompare();\n const iter = reverse\n ? (toIterate as ChildrenNode).getReverseIteratorFrom(startPost, index)\n : (toIterate as ChildrenNode).getIteratorFrom(startPost, index);\n let next = iter.getNext();\n while (next && nodes.length < count) {\n if (cmp(next, startPost) !== 0) {\n nodes.push(next);\n }\n next = iter.getNext();\n }\n return nodes;\n } else {\n return [];\n }\n}\n\nexport function newWriteTree(): WriteTree {\n return {\n visibleWrites: CompoundWrite.empty(),\n allWrites: [],\n lastWriteId: -1\n };\n}\n\n/**\n * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them\n * with underlying server data (to create \"event cache\" data). Pending writes are added with addOverwrite()\n * and addMerge(), and removed with removeWrite().\n */\nexport interface WriteTree {\n /**\n * A tree tracking the result of applying all visible writes. This does not include transactions with\n * applyLocally=false or writes that are completely shadowed by other writes.\n */\n visibleWrites: CompoundWrite;\n\n /**\n * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary\n * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also\n * used by transactions).\n */\n allWrites: WriteRecord[];\n\n lastWriteId: number;\n}\n\n/**\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\n * can lead to a more expensive calculation.\n *\n * @param writeIdsToExclude - Optional writes to exclude.\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\n */\nexport function writeTreeRefCalcCompleteEventCache(\n writeTreeRef: WriteTreeRef,\n completeServerCache: Node | null,\n writeIdsToExclude?: number[],\n includeHiddenWrites?: boolean\n): Node | null {\n return writeTreeCalcCompleteEventCache(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n completeServerCache,\n writeIdsToExclude,\n includeHiddenWrites\n );\n}\n\n/**\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\n * mix of the given server data and write data.\n *\n */\nexport function writeTreeRefCalcCompleteEventChildren(\n writeTreeRef: WriteTreeRef,\n completeServerChildren: ChildrenNode | null\n): ChildrenNode {\n return writeTreeCalcCompleteEventChildren(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n completeServerChildren\n ) as ChildrenNode;\n}\n\n/**\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\n * if anything, needs to be applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events should be raised\n *\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\n *\n *\n */\nexport function writeTreeRefCalcEventCacheAfterServerOverwrite(\n writeTreeRef: WriteTreeRef,\n path: Path,\n existingEventSnap: Node | null,\n existingServerSnap: Node | null\n): Node | null {\n return writeTreeCalcEventCacheAfterServerOverwrite(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n path,\n existingEventSnap,\n existingServerSnap\n );\n}\n\n/**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n */\nexport function writeTreeRefShadowingWrite(\n writeTreeRef: WriteTreeRef,\n path: Path\n): Node | null {\n return writeTreeShadowingWrite(\n writeTreeRef.writeTree,\n pathChild(writeTreeRef.treePath, path)\n );\n}\n\n/**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window\n */\nexport function writeTreeRefCalcIndexedSlice(\n writeTreeRef: WriteTreeRef,\n completeServerData: Node | null,\n startPost: NamedNode,\n count: number,\n reverse: boolean,\n index: Index\n): NamedNode[] {\n return writeTreeCalcIndexedSlice(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n completeServerData,\n startPost,\n count,\n reverse,\n index\n );\n}\n\n/**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n */\nexport function writeTreeRefCalcCompleteChild(\n writeTreeRef: WriteTreeRef,\n childKey: string,\n existingServerCache: CacheNode\n): Node | null {\n return writeTreeCalcCompleteChild(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n childKey,\n existingServerCache\n );\n}\n\n/**\n * Return a WriteTreeRef for a child.\n */\nexport function writeTreeRefChild(\n writeTreeRef: WriteTreeRef,\n childName: string\n): WriteTreeRef {\n return newWriteTreeRef(\n pathChild(writeTreeRef.treePath, childName),\n writeTreeRef.writeTree\n );\n}\n\nexport function newWriteTreeRef(\n path: Path,\n writeTree: WriteTree\n): WriteTreeRef {\n return {\n treePath: path,\n writeTree\n };\n}\n\n/**\n * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods\n * just proxy to the underlying WriteTree.\n *\n */\nexport interface WriteTreeRef {\n /**\n * The path to this particular write tree ref. Used for calling methods on writeTree_ while exposing a simpler\n * interface to callers.\n */\n readonly treePath: Path;\n\n /**\n * * A reference to the actual tree of write data. All methods are pass-through to the tree, but with the appropriate\n * path prefixed.\n *\n * This lets us make cheap references to points in the tree for sync points without having to copy and maintain all of\n * the data.\n */\n readonly writeTree: WriteTree;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport {\n Change,\n ChangeType,\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from './Change';\n\nexport class ChildChangeAccumulator {\n private readonly changeMap: Map = new Map();\n\n trackChildChange(change: Change) {\n const type = change.type;\n const childKey = change.childName!;\n assert(\n type === ChangeType.CHILD_ADDED ||\n type === ChangeType.CHILD_CHANGED ||\n type === ChangeType.CHILD_REMOVED,\n 'Only child changes supported for tracking'\n );\n assert(\n childKey !== '.priority',\n 'Only non-priority child changes can be tracked.'\n );\n const oldChange = this.changeMap.get(childKey);\n if (oldChange) {\n const oldType = oldChange.type;\n if (\n type === ChangeType.CHILD_ADDED &&\n oldType === ChangeType.CHILD_REMOVED\n ) {\n this.changeMap.set(\n childKey,\n changeChildChanged(\n childKey,\n change.snapshotNode,\n oldChange.snapshotNode\n )\n );\n } else if (\n type === ChangeType.CHILD_REMOVED &&\n oldType === ChangeType.CHILD_ADDED\n ) {\n this.changeMap.delete(childKey);\n } else if (\n type === ChangeType.CHILD_REMOVED &&\n oldType === ChangeType.CHILD_CHANGED\n ) {\n this.changeMap.set(\n childKey,\n changeChildRemoved(childKey, oldChange.oldSnap)\n );\n } else if (\n type === ChangeType.CHILD_CHANGED &&\n oldType === ChangeType.CHILD_ADDED\n ) {\n this.changeMap.set(\n childKey,\n changeChildAdded(childKey, change.snapshotNode)\n );\n } else if (\n type === ChangeType.CHILD_CHANGED &&\n oldType === ChangeType.CHILD_CHANGED\n ) {\n this.changeMap.set(\n childKey,\n changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap)\n );\n } else {\n throw assertionError(\n 'Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange\n );\n }\n } else {\n this.changeMap.set(childKey, change);\n }\n }\n\n getChanges(): Change[] {\n return Array.from(this.changeMap.values());\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Index } from '../snap/indexes/Index';\nimport { NamedNode, Node } from '../snap/Node';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteChild,\n writeTreeRefCalcIndexedSlice\n} from '../WriteTree';\n\nimport { CacheNode } from './CacheNode';\nimport { ViewCache, viewCacheGetCompleteServerSnap } from './ViewCache';\n\n/**\n * Since updates to filtered nodes might require nodes to be pulled in from \"outside\" the node, this interface\n * can help to get complete children that can be pulled in.\n * A class implementing this interface takes potentially multiple sources (e.g. user writes, server data from\n * other views etc.) to try it's best to get a complete child that might be useful in pulling into the view.\n *\n * @interface\n */\nexport interface CompleteChildSource {\n getCompleteChild(childKey: string): Node | null;\n\n getChildAfterChild(\n index: Index,\n child: NamedNode,\n reverse: boolean\n ): NamedNode | null;\n}\n\n/**\n * An implementation of CompleteChildSource that never returns any additional children\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class NoCompleteChildSource_ implements CompleteChildSource {\n getCompleteChild(childKey?: string): Node | null {\n return null;\n }\n getChildAfterChild(\n index?: Index,\n child?: NamedNode,\n reverse?: boolean\n ): NamedNode | null {\n return null;\n }\n}\n\n/**\n * Singleton instance.\n */\nexport const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n\n/**\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\n * old event caches available to calculate complete children.\n */\nexport class WriteTreeCompleteChildSource implements CompleteChildSource {\n constructor(\n private writes_: WriteTreeRef,\n private viewCache_: ViewCache,\n private optCompleteServerCache_: Node | null = null\n ) {}\n getCompleteChild(childKey: string): Node | null {\n const node = this.viewCache_.eventCache;\n if (node.isCompleteForChild(childKey)) {\n return node.getNode().getImmediateChild(childKey);\n } else {\n const serverNode =\n this.optCompleteServerCache_ != null\n ? new CacheNode(this.optCompleteServerCache_, true, false)\n : this.viewCache_.serverCache;\n return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);\n }\n }\n getChildAfterChild(\n index: Index,\n child: NamedNode,\n reverse: boolean\n ): NamedNode | null {\n const completeServerData =\n this.optCompleteServerCache_ != null\n ? this.optCompleteServerCache_\n : viewCacheGetCompleteServerSnap(this.viewCache_);\n const nodes = writeTreeRefCalcIndexedSlice(\n this.writes_,\n completeServerData,\n child,\n 1,\n reverse,\n index\n );\n if (nodes.length === 0) {\n return null;\n } else {\n return nodes[0];\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport { AckUserWrite } from '../operation/AckUserWrite';\nimport { Merge } from '../operation/Merge';\nimport { Operation, OperationType } from '../operation/Operation';\nimport { Overwrite } from '../operation/Overwrite';\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { KEY_INDEX } from '../snap/indexes/KeyIndex';\nimport { Node } from '../snap/Node';\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathChild,\n pathGetBack,\n pathGetFront,\n pathGetLength,\n pathIsEmpty,\n pathParent,\n pathPopFront\n} from '../util/Path';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteChild,\n writeTreeRefCalcCompleteEventCache,\n writeTreeRefCalcCompleteEventChildren,\n writeTreeRefCalcEventCacheAfterServerOverwrite,\n writeTreeRefShadowingWrite\n} from '../WriteTree';\n\nimport { Change, changeValue } from './Change';\nimport { ChildChangeAccumulator } from './ChildChangeAccumulator';\nimport {\n CompleteChildSource,\n NO_COMPLETE_CHILD_SOURCE,\n WriteTreeCompleteChildSource\n} from './CompleteChildSource';\nimport { NodeFilter } from './filter/NodeFilter';\nimport {\n ViewCache,\n viewCacheGetCompleteEventSnap,\n viewCacheGetCompleteServerSnap,\n viewCacheUpdateEventSnap,\n viewCacheUpdateServerSnap\n} from './ViewCache';\n\nexport interface ProcessorResult {\n readonly viewCache: ViewCache;\n readonly changes: Change[];\n}\n\nexport interface ViewProcessor {\n readonly filter: NodeFilter;\n}\n\nexport function newViewProcessor(filter: NodeFilter): ViewProcessor {\n return { filter };\n}\n\nexport function viewProcessorAssertIndexed(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache\n): void {\n assert(\n viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()),\n 'Event snap not indexed'\n );\n assert(\n viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()),\n 'Server snap not indexed'\n );\n}\n\nexport function viewProcessorApplyOperation(\n viewProcessor: ViewProcessor,\n oldViewCache: ViewCache,\n operation: Operation,\n writesCache: WriteTreeRef,\n completeCache: Node | null\n): ProcessorResult {\n const accumulator = new ChildChangeAccumulator();\n let newViewCache, filterServerNode;\n if (operation.type === OperationType.OVERWRITE) {\n const overwrite = operation as Overwrite;\n if (overwrite.source.fromUser) {\n newViewCache = viewProcessorApplyUserOverwrite(\n viewProcessor,\n oldViewCache,\n overwrite.path,\n overwrite.snap,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n assert(overwrite.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered and the\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\n // again\n filterServerNode =\n overwrite.source.tagged ||\n (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));\n newViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\n oldViewCache,\n overwrite.path,\n overwrite.snap,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n } else if (operation.type === OperationType.MERGE) {\n const merge = operation as Merge;\n if (merge.source.fromUser) {\n newViewCache = viewProcessorApplyUserMerge(\n viewProcessor,\n oldViewCache,\n merge.path,\n merge.children,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n assert(merge.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered\n filterServerNode =\n merge.source.tagged || oldViewCache.serverCache.isFiltered();\n newViewCache = viewProcessorApplyServerMerge(\n viewProcessor,\n oldViewCache,\n merge.path,\n merge.children,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n } else if (operation.type === OperationType.ACK_USER_WRITE) {\n const ackUserWrite = operation as AckUserWrite;\n if (!ackUserWrite.revert) {\n newViewCache = viewProcessorAckUserWrite(\n viewProcessor,\n oldViewCache,\n ackUserWrite.path,\n ackUserWrite.affectedTree,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n newViewCache = viewProcessorRevertUserWrite(\n viewProcessor,\n oldViewCache,\n ackUserWrite.path,\n writesCache,\n completeCache,\n accumulator\n );\n }\n } else if (operation.type === OperationType.LISTEN_COMPLETE) {\n newViewCache = viewProcessorListenComplete(\n viewProcessor,\n oldViewCache,\n operation.path,\n writesCache,\n accumulator\n );\n } else {\n throw assertionError('Unknown operation type: ' + operation.type);\n }\n const changes = accumulator.getChanges();\n viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);\n return { viewCache: newViewCache, changes };\n}\n\nfunction viewProcessorMaybeAddValueEvent(\n oldViewCache: ViewCache,\n newViewCache: ViewCache,\n accumulator: Change[]\n): void {\n const eventSnap = newViewCache.eventCache;\n if (eventSnap.isFullyInitialized()) {\n const isLeafOrEmpty =\n eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);\n if (\n accumulator.length > 0 ||\n !oldViewCache.eventCache.isFullyInitialized() ||\n (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||\n !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())\n ) {\n accumulator.push(\n changeValue(viewCacheGetCompleteEventSnap(newViewCache))\n );\n }\n }\n}\n\nfunction viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n changePath: Path,\n writesCache: WriteTreeRef,\n source: CompleteChildSource,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldEventSnap = viewCache.eventCache;\n if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n } else {\n let newEventCache, serverNode;\n if (pathIsEmpty(changePath)) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n assert(\n viewCache.serverCache.isFullyInitialized(),\n 'If change path is empty, we must have complete server data'\n );\n if (viewCache.serverCache.isFiltered()) {\n // We need to special case this, because we need to only apply writes to complete children, or\n // we might end up raising events for incomplete children. If the server data is filtered deep\n // writes cannot be guaranteed to be complete\n const serverCache = viewCacheGetCompleteServerSnap(viewCache);\n const completeChildren =\n serverCache instanceof ChildrenNode\n ? serverCache\n : ChildrenNode.EMPTY_NODE;\n const completeEventChildren = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n completeChildren\n );\n newEventCache = viewProcessor.filter.updateFullNode(\n viewCache.eventCache.getNode(),\n completeEventChildren,\n accumulator\n );\n } else {\n const completeNode = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n newEventCache = viewProcessor.filter.updateFullNode(\n viewCache.eventCache.getNode(),\n completeNode,\n accumulator\n );\n }\n } else {\n const childKey = pathGetFront(changePath);\n if (childKey === '.priority') {\n assert(\n pathGetLength(changePath) === 1,\n \"Can't have a priority with additional path components\"\n );\n const oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.serverCache.getNode();\n // we might have overwrites for this priority\n const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(\n writesCache,\n changePath,\n oldEventNode,\n serverNode\n );\n if (updatedPriority != null) {\n newEventCache = viewProcessor.filter.updatePriority(\n oldEventNode,\n updatedPriority\n );\n } else {\n // priority didn't change, keep old node\n newEventCache = oldEventSnap.getNode();\n }\n } else {\n const childChangePath = pathPopFront(changePath);\n // update child\n let newEventChild;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.serverCache.getNode();\n const eventChildUpdate =\n writeTreeRefCalcEventCacheAfterServerOverwrite(\n writesCache,\n changePath,\n oldEventSnap.getNode(),\n serverNode\n );\n if (eventChildUpdate != null) {\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey)\n .updateChild(childChangePath, eventChildUpdate);\n } else {\n // Nothing changed, just keep the old child\n newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);\n }\n } else {\n newEventChild = writeTreeRefCalcCompleteChild(\n writesCache,\n childKey,\n viewCache.serverCache\n );\n }\n if (newEventChild != null) {\n newEventCache = viewProcessor.filter.updateChild(\n oldEventSnap.getNode(),\n childKey,\n newEventChild,\n childChangePath,\n source,\n accumulator\n );\n } else {\n // no complete child available or no change\n newEventCache = oldEventSnap.getNode();\n }\n }\n }\n return viewCacheUpdateEventSnap(\n viewCache,\n newEventCache,\n oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath),\n viewProcessor.filter.filtersNodes()\n );\n }\n}\n\nfunction viewProcessorApplyServerOverwrite(\n viewProcessor: ViewProcessor,\n oldViewCache: ViewCache,\n changePath: Path,\n changedSnap: Node,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n filterServerNode: boolean,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldServerSnap = oldViewCache.serverCache;\n let newServerCache;\n const serverFilter = filterServerNode\n ? viewProcessor.filter\n : viewProcessor.filter.getIndexedFilter();\n if (pathIsEmpty(changePath)) {\n newServerCache = serverFilter.updateFullNode(\n oldServerSnap.getNode(),\n changedSnap,\n null\n );\n } else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\n const newServerNode = oldServerSnap\n .getNode()\n .updateChild(changePath, changedSnap);\n newServerCache = serverFilter.updateFullNode(\n oldServerSnap.getNode(),\n newServerNode,\n null\n );\n } else {\n const childKey = pathGetFront(changePath);\n if (\n !oldServerSnap.isCompleteForPath(changePath) &&\n pathGetLength(changePath) > 1\n ) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n const childChangePath = pathPopFront(changePath);\n const childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n const newChildNode = childNode.updateChild(childChangePath, changedSnap);\n if (childKey === '.priority') {\n newServerCache = serverFilter.updatePriority(\n oldServerSnap.getNode(),\n newChildNode\n );\n } else {\n newServerCache = serverFilter.updateChild(\n oldServerSnap.getNode(),\n childKey,\n newChildNode,\n childChangePath,\n NO_COMPLETE_CHILD_SOURCE,\n null\n );\n }\n }\n const newViewCache = viewCacheUpdateServerSnap(\n oldViewCache,\n newServerCache,\n oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath),\n serverFilter.filtersNodes()\n );\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n newViewCache,\n completeCache\n );\n return viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor,\n newViewCache,\n changePath,\n writesCache,\n source,\n accumulator\n );\n}\n\nfunction viewProcessorApplyUserOverwrite(\n viewProcessor: ViewProcessor,\n oldViewCache: ViewCache,\n changePath: Path,\n changedSnap: Node,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldEventSnap = oldViewCache.eventCache;\n let newViewCache, newEventCache;\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n oldViewCache,\n completeCache\n );\n if (pathIsEmpty(changePath)) {\n newEventCache = viewProcessor.filter.updateFullNode(\n oldViewCache.eventCache.getNode(),\n changedSnap,\n accumulator\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventCache,\n true,\n viewProcessor.filter.filtersNodes()\n );\n } else {\n const childKey = pathGetFront(changePath);\n if (childKey === '.priority') {\n newEventCache = viewProcessor.filter.updatePriority(\n oldViewCache.eventCache.getNode(),\n changedSnap\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventCache,\n oldEventSnap.isFullyInitialized(),\n oldEventSnap.isFiltered()\n );\n } else {\n const childChangePath = pathPopFront(changePath);\n const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n let newChild;\n if (pathIsEmpty(childChangePath)) {\n // Child overwrite, we can replace the child\n newChild = changedSnap;\n } else {\n const childNode = source.getCompleteChild(childKey);\n if (childNode != null) {\n if (\n pathGetBack(childChangePath) === '.priority' &&\n childNode.getChild(pathParent(childChangePath)).isEmpty()\n ) {\n // This is a priority update on an empty node. If this node exists on the server, the\n // server will send down the priority in the update, so ignore for now\n newChild = childNode;\n } else {\n newChild = childNode.updateChild(childChangePath, changedSnap);\n }\n } else {\n // There is no complete child node available\n newChild = ChildrenNode.EMPTY_NODE;\n }\n }\n if (!oldChild.equals(newChild)) {\n const newEventSnap = viewProcessor.filter.updateChild(\n oldEventSnap.getNode(),\n childKey,\n newChild,\n childChangePath,\n source,\n accumulator\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventSnap,\n oldEventSnap.isFullyInitialized(),\n viewProcessor.filter.filtersNodes()\n );\n } else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n}\n\nfunction viewProcessorCacheHasChild(\n viewCache: ViewCache,\n childKey: string\n): boolean {\n return viewCache.eventCache.isCompleteForChild(childKey);\n}\n\nfunction viewProcessorApplyUserMerge(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n changedChildren: ImmutableTree,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n let curViewCache = viewCache;\n changedChildren.foreach((relativePath, childNode) => {\n const writePath = pathChild(path, relativePath);\n if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\n curViewCache = viewProcessorApplyUserOverwrite(\n viewProcessor,\n curViewCache,\n writePath,\n childNode,\n writesCache,\n serverCache,\n accumulator\n );\n }\n });\n\n changedChildren.foreach((relativePath, childNode) => {\n const writePath = pathChild(path, relativePath);\n if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\n curViewCache = viewProcessorApplyUserOverwrite(\n viewProcessor,\n curViewCache,\n writePath,\n childNode,\n writesCache,\n serverCache,\n accumulator\n );\n }\n });\n\n return curViewCache;\n}\n\nfunction viewProcessorApplyMerge(\n viewProcessor: ViewProcessor,\n node: Node,\n merge: ImmutableTree\n): Node {\n merge.foreach((relativePath, childNode) => {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n}\n\nfunction viewProcessorApplyServerMerge(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n changedChildren: ImmutableTree,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n filterServerNode: boolean,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\n // wait for the complete data update coming soon.\n if (\n viewCache.serverCache.getNode().isEmpty() &&\n !viewCache.serverCache.isFullyInitialized()\n ) {\n return viewCache;\n }\n\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n let curViewCache = viewCache;\n let viewMergeTree: ImmutableTree;\n if (pathIsEmpty(path)) {\n viewMergeTree = changedChildren;\n } else {\n viewMergeTree = new ImmutableTree(null).setTree(\n path,\n changedChildren\n );\n }\n const serverNode = viewCache.serverCache.getNode();\n viewMergeTree.children.inorderTraversal((childKey, childTree) => {\n if (serverNode.hasChild(childKey)) {\n const serverChild = viewCache.serverCache\n .getNode()\n .getImmediateChild(childKey);\n const newChild = viewProcessorApplyMerge(\n viewProcessor,\n serverChild,\n childTree\n );\n curViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\n curViewCache,\n new Path(childKey),\n newChild,\n writesCache,\n serverCache,\n filterServerNode,\n accumulator\n );\n }\n });\n viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {\n const isUnknownDeepMerge =\n !viewCache.serverCache.isCompleteForChild(childKey) &&\n childMergeTree.value === null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n const serverChild = viewCache.serverCache\n .getNode()\n .getImmediateChild(childKey);\n const newChild = viewProcessorApplyMerge(\n viewProcessor,\n serverChild,\n childMergeTree\n );\n curViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\n curViewCache,\n new Path(childKey),\n newChild,\n writesCache,\n serverCache,\n filterServerNode,\n accumulator\n );\n }\n });\n\n return curViewCache;\n}\n\nfunction viewProcessorAckUserWrite(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n ackPath: Path,\n affectedTree: ImmutableTree,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {\n return viewCache;\n }\n\n // Only filter server node if it is currently filtered\n const filterServerNode = viewCache.serverCache.isFiltered();\n\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\n // now that it won't be shadowed.\n const serverCache = viewCache.serverCache;\n if (affectedTree.value != null) {\n // This is an overwrite.\n if (\n (pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)\n ) {\n return viewProcessorApplyServerOverwrite(\n viewProcessor,\n viewCache,\n ackPath,\n serverCache.getNode().getChild(ackPath),\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n } else if (pathIsEmpty(ackPath)) {\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\n // should just re-apply whatever we have in our cache as a merge.\n let changedChildren = new ImmutableTree(null);\n serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {\n changedChildren = changedChildren.set(new Path(name), node);\n });\n return viewProcessorApplyServerMerge(\n viewProcessor,\n viewCache,\n ackPath,\n changedChildren,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n } else {\n return viewCache;\n }\n } else {\n // This is a merge.\n let changedChildren = new ImmutableTree(null);\n affectedTree.foreach((mergePath, value) => {\n const serverCachePath = pathChild(ackPath, mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren = changedChildren.set(\n mergePath,\n serverCache.getNode().getChild(serverCachePath)\n );\n }\n });\n return viewProcessorApplyServerMerge(\n viewProcessor,\n viewCache,\n ackPath,\n changedChildren,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n}\n\nfunction viewProcessorListenComplete(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n writesCache: WriteTreeRef,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldServerNode = viewCache.serverCache;\n const newViewCache = viewCacheUpdateServerSnap(\n viewCache,\n oldServerNode.getNode(),\n oldServerNode.isFullyInitialized() || pathIsEmpty(path),\n oldServerNode.isFiltered()\n );\n return viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor,\n newViewCache,\n path,\n writesCache,\n NO_COMPLETE_CHILD_SOURCE,\n accumulator\n );\n}\n\nfunction viewProcessorRevertUserWrite(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n writesCache: WriteTreeRef,\n completeServerCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n let complete;\n if (writeTreeRefShadowingWrite(writesCache, path) != null) {\n return viewCache;\n } else {\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n viewCache,\n completeServerCache\n );\n const oldEventCache = viewCache.eventCache.getNode();\n let newEventCache;\n if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {\n let newNode;\n if (viewCache.serverCache.isFullyInitialized()) {\n newNode = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n } else {\n const serverChildren = viewCache.serverCache.getNode();\n assert(\n serverChildren instanceof ChildrenNode,\n 'serverChildren would be complete if leaf node'\n );\n newNode = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n serverChildren as ChildrenNode\n );\n }\n newNode = newNode as Node;\n newEventCache = viewProcessor.filter.updateFullNode(\n oldEventCache,\n newNode,\n accumulator\n );\n } else {\n const childKey = pathGetFront(path);\n let newChild = writeTreeRefCalcCompleteChild(\n writesCache,\n childKey,\n viewCache.serverCache\n );\n if (\n newChild == null &&\n viewCache.serverCache.isCompleteForChild(childKey)\n ) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = viewProcessor.filter.updateChild(\n oldEventCache,\n childKey,\n newChild,\n pathPopFront(path),\n source,\n accumulator\n );\n } else if (viewCache.eventCache.getNode().hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = viewProcessor.filter.updateChild(\n oldEventCache,\n childKey,\n ChildrenNode.EMPTY_NODE,\n pathPopFront(path),\n source,\n accumulator\n );\n } else {\n newEventCache = oldEventCache;\n }\n if (\n newEventCache.isEmpty() &&\n viewCache.serverCache.isFullyInitialized()\n ) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n if (complete.isLeafNode()) {\n newEventCache = viewProcessor.filter.updateFullNode(\n newEventCache,\n complete,\n accumulator\n );\n }\n }\n }\n complete =\n viewCache.serverCache.isFullyInitialized() ||\n writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;\n return viewCacheUpdateEventSnap(\n viewCache,\n newEventCache,\n complete,\n viewProcessor.filter.filtersNodes()\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Operation, OperationType } from '../operation/Operation';\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { PRIORITY_INDEX } from '../snap/indexes/PriorityIndex';\nimport { Node } from '../snap/Node';\nimport { Path, pathGetFront, pathIsEmpty } from '../util/Path';\nimport { WriteTreeRef } from '../WriteTree';\n\nimport { CacheNode } from './CacheNode';\nimport { Change, changeChildAdded, changeValue } from './Change';\nimport { CancelEvent, Event } from './Event';\nimport {\n EventGenerator,\n eventGeneratorGenerateEventsForChanges\n} from './EventGenerator';\nimport { EventRegistration, QueryContext } from './EventRegistration';\nimport { IndexedFilter } from './filter/IndexedFilter';\nimport { queryParamsGetNodeFilter } from './QueryParams';\nimport {\n newViewCache,\n ViewCache,\n viewCacheGetCompleteEventSnap,\n viewCacheGetCompleteServerSnap\n} from './ViewCache';\nimport {\n newViewProcessor,\n ViewProcessor,\n viewProcessorApplyOperation,\n viewProcessorAssertIndexed\n} from './ViewProcessor';\n\n/**\n * A view represents a specific location and query that has 1 or more event registrations.\n *\n * It does several things:\n * - Maintains the list of event registrations for this location/query.\n * - Maintains a cache of the data visible for this location/query.\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\n * registrations returns the set of events to be raised.\n */\nexport class View {\n processor_: ViewProcessor;\n viewCache_: ViewCache;\n eventRegistrations_: EventRegistration[] = [];\n eventGenerator_: EventGenerator;\n\n constructor(private query_: QueryContext, initialViewCache: ViewCache) {\n const params = this.query_._queryParams;\n\n const indexFilter = new IndexedFilter(params.getIndex());\n const filter = queryParamsGetNodeFilter(params);\n\n this.processor_ = newViewProcessor(filter);\n\n const initialServerCache = initialViewCache.serverCache;\n const initialEventCache = initialViewCache.eventCache;\n\n // Don't filter server node with other filter than index, wait for tagged listen\n const serverSnap = indexFilter.updateFullNode(\n ChildrenNode.EMPTY_NODE,\n initialServerCache.getNode(),\n null\n );\n const eventSnap = filter.updateFullNode(\n ChildrenNode.EMPTY_NODE,\n initialEventCache.getNode(),\n null\n );\n const newServerCache = new CacheNode(\n serverSnap,\n initialServerCache.isFullyInitialized(),\n indexFilter.filtersNodes()\n );\n const newEventCache = new CacheNode(\n eventSnap,\n initialEventCache.isFullyInitialized(),\n filter.filtersNodes()\n );\n\n this.viewCache_ = newViewCache(newEventCache, newServerCache);\n this.eventGenerator_ = new EventGenerator(this.query_);\n }\n\n get query(): QueryContext {\n return this.query_;\n }\n}\n\nexport function viewGetServerCache(view: View): Node | null {\n return view.viewCache_.serverCache.getNode();\n}\n\nexport function viewGetCompleteNode(view: View): Node | null {\n return viewCacheGetCompleteEventSnap(view.viewCache_);\n}\n\nexport function viewGetCompleteServerCache(\n view: View,\n path: Path\n): Node | null {\n const cache = viewCacheGetCompleteServerSnap(view.viewCache_);\n if (cache) {\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\n // we need to see if it contains the child we're interested in.\n if (\n view.query._queryParams.loadsAllData() ||\n (!pathIsEmpty(path) &&\n !cache.getImmediateChild(pathGetFront(path)).isEmpty())\n ) {\n return cache.getChild(path);\n }\n }\n return null;\n}\n\nexport function viewIsEmpty(view: View): boolean {\n return view.eventRegistrations_.length === 0;\n}\n\nexport function viewAddEventRegistration(\n view: View,\n eventRegistration: EventRegistration\n) {\n view.eventRegistrations_.push(eventRegistration);\n}\n\n/**\n * @param eventRegistration - If null, remove all callbacks.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @returns Cancel events, if cancelError was provided.\n */\nexport function viewRemoveEventRegistration(\n view: View,\n eventRegistration: EventRegistration | null,\n cancelError?: Error\n): Event[] {\n const cancelEvents: CancelEvent[] = [];\n if (cancelError) {\n assert(\n eventRegistration == null,\n 'A cancel should cancel all event registrations.'\n );\n const path = view.query._path;\n view.eventRegistrations_.forEach(registration => {\n const maybeEvent = registration.createCancelEvent(cancelError, path);\n if (maybeEvent) {\n cancelEvents.push(maybeEvent);\n }\n });\n }\n\n if (eventRegistration) {\n let remaining = [];\n for (let i = 0; i < view.eventRegistrations_.length; ++i) {\n const existing = view.eventRegistrations_[i];\n if (!existing.matches(eventRegistration)) {\n remaining.push(existing);\n } else if (eventRegistration.hasAnyCallback()) {\n // We're removing just this one\n remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));\n break;\n }\n }\n view.eventRegistrations_ = remaining;\n } else {\n view.eventRegistrations_ = [];\n }\n return cancelEvents;\n}\n\n/**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n */\nexport function viewApplyOperation(\n view: View,\n operation: Operation,\n writesCache: WriteTreeRef,\n completeServerCache: Node | null\n): Event[] {\n if (\n operation.type === OperationType.MERGE &&\n operation.source.queryId !== null\n ) {\n assert(\n viewCacheGetCompleteServerSnap(view.viewCache_),\n 'We should always have a full cache before handling merges'\n );\n assert(\n viewCacheGetCompleteEventSnap(view.viewCache_),\n 'Missing event cache, even though we have a server cache'\n );\n }\n\n const oldViewCache = view.viewCache_;\n const result = viewProcessorApplyOperation(\n view.processor_,\n oldViewCache,\n operation,\n writesCache,\n completeServerCache\n );\n viewProcessorAssertIndexed(view.processor_, result.viewCache);\n\n assert(\n result.viewCache.serverCache.isFullyInitialized() ||\n !oldViewCache.serverCache.isFullyInitialized(),\n 'Once a server snap is complete, it should never go back'\n );\n\n view.viewCache_ = result.viewCache;\n\n return viewGenerateEventsForChanges_(\n view,\n result.changes,\n result.viewCache.eventCache.getNode(),\n null\n );\n}\n\nexport function viewGetInitialEvents(\n view: View,\n registration: EventRegistration\n): Event[] {\n const eventSnap = view.viewCache_.eventCache;\n const initialChanges: Change[] = [];\n if (!eventSnap.getNode().isLeafNode()) {\n const eventNode = eventSnap.getNode() as ChildrenNode;\n eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n initialChanges.push(changeChildAdded(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(changeValue(eventSnap.getNode()));\n }\n return viewGenerateEventsForChanges_(\n view,\n initialChanges,\n eventSnap.getNode(),\n registration\n );\n}\n\nfunction viewGenerateEventsForChanges_(\n view: View,\n changes: Change[],\n eventCache: Node,\n eventRegistration?: EventRegistration\n): Event[] {\n const registrations = eventRegistration\n ? [eventRegistration]\n : view.eventRegistrations_;\n return eventGeneratorGenerateEventsForChanges(\n view.eventGenerator_,\n changes,\n eventCache,\n registrations\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ReferenceConstructor } from '../api/Reference';\n\nimport { Operation } from './operation/Operation';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { Path } from './util/Path';\nimport { CacheNode } from './view/CacheNode';\nimport { Event } from './view/Event';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\nimport {\n View,\n viewAddEventRegistration,\n viewApplyOperation,\n viewGetCompleteServerCache,\n viewGetInitialEvents,\n viewIsEmpty,\n viewRemoveEventRegistration\n} from './view/View';\nimport { newViewCache } from './view/ViewCache';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteEventCache,\n writeTreeRefCalcCompleteEventChildren\n} from './WriteTree';\n\nlet referenceConstructor: ReferenceConstructor;\n\n/**\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\n * and user writes (set, transaction, update).\n *\n * It's responsible for:\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\n * applyUserOverwrite, etc.)\n */\nexport class SyncPoint {\n /**\n * The Views being tracked at this location in the tree, stored as a map where the key is a\n * queryId and the value is the View for that query.\n *\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\n */\n readonly views: Map = new Map();\n}\n\nexport function syncPointSetReferenceConstructor(\n val: ReferenceConstructor\n): void {\n assert(\n !referenceConstructor,\n '__referenceConstructor has already been defined'\n );\n referenceConstructor = val;\n}\n\nfunction syncPointGetReferenceConstructor(): ReferenceConstructor {\n assert(referenceConstructor, 'Reference.ts has not been loaded');\n return referenceConstructor;\n}\n\nexport function syncPointIsEmpty(syncPoint: SyncPoint): boolean {\n return syncPoint.views.size === 0;\n}\n\nexport function syncPointApplyOperation(\n syncPoint: SyncPoint,\n operation: Operation,\n writesCache: WriteTreeRef,\n optCompleteServerCache: Node | null\n): Event[] {\n const queryId = operation.source.queryId;\n if (queryId !== null) {\n const view = syncPoint.views.get(queryId);\n assert(view != null, 'SyncTree gave us an op for an invalid query.');\n return viewApplyOperation(\n view,\n operation,\n writesCache,\n optCompleteServerCache\n );\n } else {\n let events: Event[] = [];\n\n for (const view of syncPoint.views.values()) {\n events = events.concat(\n viewApplyOperation(view, operation, writesCache, optCompleteServerCache)\n );\n }\n\n return events;\n }\n}\n\n/**\n * Get a view for the specified query.\n *\n * @param query - The query to return a view for\n * @param writesCache\n * @param serverCache\n * @param serverCacheComplete\n * @returns Events to raise.\n */\nexport function syncPointGetView(\n syncPoint: SyncPoint,\n query: QueryContext,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n serverCacheComplete: boolean\n): View {\n const queryId = query._queryIdentifier;\n const view = syncPoint.views.get(queryId);\n if (!view) {\n // TODO: make writesCache take flag for complete server node\n let eventCache = writeTreeRefCalcCompleteEventCache(\n writesCache,\n serverCacheComplete ? serverCache : null\n );\n let eventCacheComplete = false;\n if (eventCache) {\n eventCacheComplete = true;\n } else if (serverCache instanceof ChildrenNode) {\n eventCache = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n serverCache\n );\n eventCacheComplete = false;\n } else {\n eventCache = ChildrenNode.EMPTY_NODE;\n eventCacheComplete = false;\n }\n const viewCache = newViewCache(\n new CacheNode(eventCache, eventCacheComplete, false),\n new CacheNode(serverCache, serverCacheComplete, false)\n );\n return new View(query, viewCache);\n }\n return view;\n}\n\n/**\n * Add an event callback for the specified query.\n *\n * @param query\n * @param eventRegistration\n * @param writesCache\n * @param serverCache - Complete server cache, if we have it.\n * @param serverCacheComplete\n * @returns Events to raise.\n */\nexport function syncPointAddEventRegistration(\n syncPoint: SyncPoint,\n query: QueryContext,\n eventRegistration: EventRegistration,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n serverCacheComplete: boolean\n): Event[] {\n const view = syncPointGetView(\n syncPoint,\n query,\n writesCache,\n serverCache,\n serverCacheComplete\n );\n if (!syncPoint.views.has(query._queryIdentifier)) {\n syncPoint.views.set(query._queryIdentifier, view);\n }\n // This is guaranteed to exist now, we just created anything that was missing\n viewAddEventRegistration(view, eventRegistration);\n return viewGetInitialEvents(view, eventRegistration);\n}\n\n/**\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\n *\n * If query is the default query, we'll check all views for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\n *\n * @param eventRegistration - If null, remove all callbacks.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @returns removed queries and any cancel events\n */\nexport function syncPointRemoveEventRegistration(\n syncPoint: SyncPoint,\n query: QueryContext,\n eventRegistration: EventRegistration | null,\n cancelError?: Error\n): { removed: QueryContext[]; events: Event[] } {\n const queryId = query._queryIdentifier;\n const removed: QueryContext[] = [];\n let cancelEvents: Event[] = [];\n const hadCompleteView = syncPointHasCompleteView(syncPoint);\n if (queryId === 'default') {\n // When you do ref.off(...), we search all views for the registration to remove.\n for (const [viewQueryId, view] of syncPoint.views.entries()) {\n cancelEvents = cancelEvents.concat(\n viewRemoveEventRegistration(view, eventRegistration, cancelError)\n );\n if (viewIsEmpty(view)) {\n syncPoint.views.delete(viewQueryId);\n\n // We'll deal with complete views later.\n if (!view.query._queryParams.loadsAllData()) {\n removed.push(view.query);\n }\n }\n }\n } else {\n // remove the callback from the specific view.\n const view = syncPoint.views.get(queryId);\n if (view) {\n cancelEvents = cancelEvents.concat(\n viewRemoveEventRegistration(view, eventRegistration, cancelError)\n );\n if (viewIsEmpty(view)) {\n syncPoint.views.delete(queryId);\n\n // We'll deal with complete views later.\n if (!view.query._queryParams.loadsAllData()) {\n removed.push(view.query);\n }\n }\n }\n }\n\n if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {\n // We removed our last complete view.\n removed.push(\n new (syncPointGetReferenceConstructor())(query._repo, query._path)\n );\n }\n\n return { removed, events: cancelEvents };\n}\n\nexport function syncPointGetQueryViews(syncPoint: SyncPoint): View[] {\n const result = [];\n for (const view of syncPoint.views.values()) {\n if (!view.query._queryParams.loadsAllData()) {\n result.push(view);\n }\n }\n return result;\n}\n\n/**\n * @param path - The path to the desired complete snapshot\n * @returns A complete cache, if it exists\n */\nexport function syncPointGetCompleteServerCache(\n syncPoint: SyncPoint,\n path: Path\n): Node | null {\n let serverCache: Node | null = null;\n for (const view of syncPoint.views.values()) {\n serverCache = serverCache || viewGetCompleteServerCache(view, path);\n }\n return serverCache;\n}\n\nexport function syncPointViewForQuery(\n syncPoint: SyncPoint,\n query: QueryContext\n): View | null {\n const params = query._queryParams;\n if (params.loadsAllData()) {\n return syncPointGetCompleteView(syncPoint);\n } else {\n const queryId = query._queryIdentifier;\n return syncPoint.views.get(queryId);\n }\n}\n\nexport function syncPointViewExistsForQuery(\n syncPoint: SyncPoint,\n query: QueryContext\n): boolean {\n return syncPointViewForQuery(syncPoint, query) != null;\n}\n\nexport function syncPointHasCompleteView(syncPoint: SyncPoint): boolean {\n return syncPointGetCompleteView(syncPoint) != null;\n}\n\nexport function syncPointGetCompleteView(syncPoint: SyncPoint): View | null {\n for (const view of syncPoint.views.values()) {\n if (view.query._queryParams.loadsAllData()) {\n return view;\n }\n }\n return null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ReferenceConstructor } from '../api/Reference';\n\nimport { AckUserWrite } from './operation/AckUserWrite';\nimport { ListenComplete } from './operation/ListenComplete';\nimport { Merge } from './operation/Merge';\nimport {\n newOperationSourceServer,\n newOperationSourceServerTaggedQuery,\n newOperationSourceUser,\n Operation\n} from './operation/Operation';\nimport { Overwrite } from './operation/Overwrite';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport {\n SyncPoint,\n syncPointAddEventRegistration,\n syncPointApplyOperation,\n syncPointGetCompleteServerCache,\n syncPointGetCompleteView,\n syncPointGetQueryViews,\n syncPointGetView,\n syncPointHasCompleteView,\n syncPointIsEmpty,\n syncPointRemoveEventRegistration,\n syncPointViewExistsForQuery,\n syncPointViewForQuery\n} from './SyncPoint';\nimport { ImmutableTree } from './util/ImmutableTree';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathGetFront,\n pathIsEmpty\n} from './util/Path';\nimport { each, errorForServerCode } from './util/util';\nimport { CacheNode } from './view/CacheNode';\nimport { Event } from './view/Event';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\nimport { View, viewGetCompleteNode, viewGetServerCache } from './view/View';\nimport {\n newWriteTree,\n WriteTree,\n writeTreeAddMerge,\n writeTreeAddOverwrite,\n writeTreeCalcCompleteEventCache,\n writeTreeChildWrites,\n writeTreeGetWrite,\n WriteTreeRef,\n writeTreeRefChild,\n writeTreeRemoveWrite\n} from './WriteTree';\n\nlet referenceConstructor: ReferenceConstructor;\n\nexport function syncTreeSetReferenceConstructor(\n val: ReferenceConstructor\n): void {\n assert(\n !referenceConstructor,\n '__referenceConstructor has already been defined'\n );\n referenceConstructor = val;\n}\n\nfunction syncTreeGetReferenceConstructor(): ReferenceConstructor {\n assert(referenceConstructor, 'Reference.ts has not been loaded');\n return referenceConstructor;\n}\n\nexport interface ListenProvider {\n startListening(\n query: QueryContext,\n tag: number | null,\n hashFn: () => string,\n onComplete: (a: string, b?: unknown) => Event[]\n ): Event[];\n\n stopListening(a: QueryContext, b: number | null): void;\n}\n\n/**\n * Static tracker for next query tag.\n */\nlet syncTreeNextQueryTag_ = 1;\n\nexport function resetSyncTreeTag() {\n syncTreeNextQueryTag_ = 1;\n}\n\n/**\n * SyncTree is the central class for managing event callback registration, data caching, views\n * (query processing), and event generation. There are typically two SyncTree instances for\n * each Repo, one for the normal Firebase data, and one for the .info data.\n *\n * It has a number of responsibilities, including:\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\n * - Applying and caching data changes for user set(), transaction(), and update() calls\n * (applyUserOverwrite(), applyUserMerge()).\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\n * applyServerMerge()).\n * - Generating user-facing events for server and user changes (all of the apply* methods\n * return the set of events that need to be raised as a result).\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\n * to the correct set of paths and queries to satisfy the current set of user event\n * callbacks (listens are started/stopped using the provided listenProvider).\n *\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\n * events are returned to the caller rather than raised synchronously.\n *\n */\nexport class SyncTree {\n /**\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\n */\n syncPointTree_: ImmutableTree = new ImmutableTree(null);\n\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n */\n pendingWriteTree_: WriteTree = newWriteTree();\n\n readonly tagToQueryMap: Map = new Map();\n readonly queryToTagMap: Map = new Map();\n\n /**\n * @param listenProvider_ - Used by SyncTree to start / stop listening\n * to server data.\n */\n constructor(public listenProvider_: ListenProvider) {}\n}\n\n/**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyUserOverwrite(\n syncTree: SyncTree,\n path: Path,\n newData: Node,\n writeId: number,\n visible?: boolean\n): Event[] {\n // Record pending write.\n writeTreeAddOverwrite(\n syncTree.pendingWriteTree_,\n path,\n newData,\n writeId,\n visible\n );\n\n if (!visible) {\n return [];\n } else {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Overwrite(newOperationSourceUser(), path, newData)\n );\n }\n}\n\n/**\n * Apply the data from a user-generated update() call\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyUserMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n writeId: number\n): Event[] {\n // Record pending merge.\n writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);\n\n const changeTree = ImmutableTree.fromObject(changedChildren);\n\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Merge(newOperationSourceUser(), path, changeTree)\n );\n}\n\n/**\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\n *\n * @param revert - True if the given write failed and needs to be reverted\n * @returns Events to raise.\n */\nexport function syncTreeAckUserWrite(\n syncTree: SyncTree,\n writeId: number,\n revert: boolean = false\n) {\n const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);\n const needToReevaluate = writeTreeRemoveWrite(\n syncTree.pendingWriteTree_,\n writeId\n );\n if (!needToReevaluate) {\n return [];\n } else {\n let affectedTree = new ImmutableTree(null);\n if (write.snap != null) {\n // overwrite\n affectedTree = affectedTree.set(newEmptyPath(), true);\n } else {\n each(write.children, (pathString: string) => {\n affectedTree = affectedTree.set(new Path(pathString), true);\n });\n }\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new AckUserWrite(write.path, affectedTree, revert)\n );\n }\n}\n\n/**\n * Apply new server data for the specified path..\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyServerOverwrite(\n syncTree: SyncTree,\n path: Path,\n newData: Node\n): Event[] {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Overwrite(newOperationSourceServer(), path, newData)\n );\n}\n\n/**\n * Apply new server data to be merged in at the specified path.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyServerMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node }\n): Event[] {\n const changeTree = ImmutableTree.fromObject(changedChildren);\n\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Merge(newOperationSourceServer(), path, changeTree)\n );\n}\n\n/**\n * Apply a listen complete for a query\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyListenComplete(\n syncTree: SyncTree,\n path: Path\n): Event[] {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new ListenComplete(newOperationSourceServer(), path)\n );\n}\n\n/**\n * Apply a listen complete for a tagged query\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedListenComplete(\n syncTree: SyncTree,\n path: Path,\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const op = new ListenComplete(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath\n );\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n } else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n}\n\n/**\n * Remove event callback(s).\n *\n * If query is the default query, we'll check all queries for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\n *\n * @param eventRegistration - If null, all callbacks are removed.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no\n * deduping needs to take place. This flag allows toggling of that behavior\n * @returns Cancel events, if cancelError was provided.\n */\nexport function syncTreeRemoveEventRegistration(\n syncTree: SyncTree,\n query: QueryContext,\n eventRegistration: EventRegistration | null,\n cancelError?: Error,\n skipListenerDedup = false\n): Event[] {\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\n const path = query._path;\n const maybeSyncPoint = syncTree.syncPointTree_.get(path);\n let cancelEvents: Event[] = [];\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\n // not loadsAllData().\n if (\n maybeSyncPoint &&\n (query._queryIdentifier === 'default' ||\n syncPointViewExistsForQuery(maybeSyncPoint, query))\n ) {\n const removedAndEvents = syncPointRemoveEventRegistration(\n maybeSyncPoint,\n query,\n eventRegistration,\n cancelError\n );\n if (syncPointIsEmpty(maybeSyncPoint)) {\n syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);\n }\n\n const removed = removedAndEvents.removed;\n cancelEvents = removedAndEvents.events;\n\n if (!skipListenerDedup) {\n /**\n * We may have just removed one of many listeners and can short-circuit this whole process\n * We may also not have removed a default listener, in which case all of the descendant listeners should already be\n * properly set up.\n */\n\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\n // queryId === 'default'\n const removingDefault =\n -1 !==\n removed.findIndex(query => {\n return query._queryParams.loadsAllData();\n });\n const covered = syncTree.syncPointTree_.findOnPath(\n path,\n (relativePath, parentSyncPoint) =>\n syncPointHasCompleteView(parentSyncPoint)\n );\n\n if (removingDefault && !covered) {\n const subtree = syncTree.syncPointTree_.subtree(path);\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\n // removal\n if (!subtree.isEmpty()) {\n // We need to fold over our subtree and collect the listeners to send\n const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);\n\n // Ok, we've collected all the listens we need. Set them up.\n for (let i = 0; i < newViews.length; ++i) {\n const view = newViews[i],\n newQuery = view.query;\n const listener = syncTreeCreateListenerForView_(syncTree, view);\n syncTree.listenProvider_.startListening(\n syncTreeQueryForListening_(newQuery),\n syncTreeTagForQuery(syncTree, newQuery),\n listener.hashFn,\n listener.onComplete\n );\n }\n }\n // Otherwise there's nothing below us, so nothing we need to start listening on\n }\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\n if (!covered && removed.length > 0 && !cancelError) {\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\n // default. Otherwise, we need to iterate through and cancel each individual query\n if (removingDefault) {\n // We don't tag default listeners\n const defaultTag: number | null = null;\n syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(query),\n defaultTag\n );\n } else {\n removed.forEach((queryToRemove: QueryContext) => {\n const tagToRemove = syncTree.queryToTagMap.get(\n syncTreeMakeQueryKey_(queryToRemove)\n );\n syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(queryToRemove),\n tagToRemove\n );\n });\n }\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n syncTreeRemoveTags_(syncTree, removed);\n } else {\n // No-op, this listener must've been already removed\n }\n return cancelEvents;\n}\n\n/**\n * Apply new server data for the specified tagged query.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedQueryOverwrite(\n syncTree: SyncTree,\n path: Path,\n snap: Node,\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey != null) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const op = new Overwrite(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath,\n snap\n );\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n } else {\n // Query must have been removed already\n return [];\n }\n}\n\n/**\n * Apply server data to be merged in for the specified tagged query.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedQueryMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const changeTree = ImmutableTree.fromObject(changedChildren);\n const op = new Merge(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath,\n changeTree\n );\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n } else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n}\n\n/**\n * Add an event callback for the specified query.\n *\n * @returns Events to raise.\n */\nexport function syncTreeAddEventRegistration(\n syncTree: SyncTree,\n query: QueryContext,\n eventRegistration: EventRegistration,\n skipSetupListener = false\n): Event[] {\n const path = query._path;\n\n let serverCache: Node | null = null;\n let foundAncestorDefaultView = false;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\n const relativePath = newRelativePath(pathToSyncPoint, path);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPointHasCompleteView(sp);\n });\n let syncPoint = syncTree.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint();\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\n } else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n\n let serverCacheComplete;\n if (serverCache != null) {\n serverCacheComplete = true;\n } else {\n serverCacheComplete = false;\n serverCache = ChildrenNode.EMPTY_NODE;\n const subtree = syncTree.syncPointTree_.subtree(path);\n subtree.foreachChild((childName, childSyncPoint) => {\n const completeCache = syncPointGetCompleteServerCache(\n childSyncPoint,\n newEmptyPath()\n );\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(\n childName,\n completeCache\n );\n }\n });\n }\n\n const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);\n if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {\n // We need to track a tag for this query\n const queryKey = syncTreeMakeQueryKey_(query);\n assert(\n !syncTree.queryToTagMap.has(queryKey),\n 'View does not exist, but we have a tag'\n );\n const tag = syncTreeGetNextQueryTag_();\n syncTree.queryToTagMap.set(queryKey, tag);\n syncTree.tagToQueryMap.set(tag, queryKey);\n }\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);\n let events = syncPointAddEventRegistration(\n syncPoint,\n query,\n eventRegistration,\n writesCache,\n serverCache,\n serverCacheComplete\n );\n if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {\n const view = syncPointViewForQuery(syncPoint, query);\n events = events.concat(syncTreeSetupListener_(syncTree, query, view));\n }\n return events;\n}\n\n/**\n * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a\n * listener above it, we will get a false \"null\". This shouldn't be a problem because transactions will always\n * have a listener above, and atomic operations would correctly show a jitter of ->\n * as the write is applied locally and then acknowledged at the server.\n *\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\n *\n * @param path - The path to the data we want\n * @param writeIdsToExclude - A specific set to be excluded\n */\nexport function syncTreeCalcCompleteEventCache(\n syncTree: SyncTree,\n path: Path,\n writeIdsToExclude?: number[]\n): Node {\n const includeHiddenSets = true;\n const writeTree = syncTree.pendingWriteTree_;\n const serverCache = syncTree.syncPointTree_.findOnPath(\n path,\n (pathSoFar, syncPoint) => {\n const relativePath = newRelativePath(pathSoFar, path);\n const serverCache = syncPointGetCompleteServerCache(\n syncPoint,\n relativePath\n );\n if (serverCache) {\n return serverCache;\n }\n }\n );\n return writeTreeCalcCompleteEventCache(\n writeTree,\n path,\n serverCache,\n writeIdsToExclude,\n includeHiddenSets\n );\n}\n\nexport function syncTreeGetServerValue(\n syncTree: SyncTree,\n query: QueryContext\n): Node | null {\n const path = query._path;\n let serverCache: Node | null = null;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\n const relativePath = newRelativePath(pathToSyncPoint, path);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\n });\n let syncPoint = syncTree.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint();\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\n } else {\n serverCache =\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n const serverCacheComplete = serverCache != null;\n const serverCacheNode: CacheNode | null = serverCacheComplete\n ? new CacheNode(serverCache, true, false)\n : null;\n const writesCache: WriteTreeRef | null = writeTreeChildWrites(\n syncTree.pendingWriteTree_,\n query._path\n );\n const view: View = syncPointGetView(\n syncPoint,\n query,\n writesCache,\n serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE,\n serverCacheComplete\n );\n return viewGetCompleteNode(view);\n}\n\n/**\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\n *\n * NOTES:\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\n *\n * - We call applyOperation() on each SyncPoint passing three things:\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\n * 3. A snapshot Node with cached server data, if we have it.\n *\n * - We concatenate all of the events returned by each SyncPoint and return the result.\n */\nfunction syncTreeApplyOperationToSyncPoints_(\n syncTree: SyncTree,\n operation: Operation\n): Event[] {\n return syncTreeApplyOperationHelper_(\n operation,\n syncTree.syncPointTree_,\n /*serverCache=*/ null,\n writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath())\n );\n}\n\n/**\n * Recursive helper for applyOperationToSyncPoints_\n */\nfunction syncTreeApplyOperationHelper_(\n operation: Operation,\n syncPointTree: ImmutableTree,\n serverCache: Node | null,\n writesCache: WriteTreeRef\n): Event[] {\n if (pathIsEmpty(operation.path)) {\n return syncTreeApplyOperationDescendantsHelper_(\n operation,\n syncPointTree,\n serverCache,\n writesCache\n );\n } else {\n const syncPoint = syncPointTree.get(newEmptyPath());\n\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n\n let events: Event[] = [];\n const childName = pathGetFront(operation.path);\n const childOperation = operation.operationForChild(childName);\n const childTree = syncPointTree.children.get(childName);\n if (childTree && childOperation) {\n const childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n const childWritesCache = writeTreeRefChild(writesCache, childName);\n events = events.concat(\n syncTreeApplyOperationHelper_(\n childOperation,\n childTree,\n childServerCache,\n childWritesCache\n )\n );\n }\n\n if (syncPoint) {\n events = events.concat(\n syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)\n );\n }\n\n return events;\n }\n}\n\n/**\n * Recursive helper for applyOperationToSyncPoints_\n */\nfunction syncTreeApplyOperationDescendantsHelper_(\n operation: Operation,\n syncPointTree: ImmutableTree,\n serverCache: Node | null,\n writesCache: WriteTreeRef\n): Event[] {\n const syncPoint = syncPointTree.get(newEmptyPath());\n\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n\n let events: Event[] = [];\n syncPointTree.children.inorderTraversal((childName, childTree) => {\n const childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n const childWritesCache = writeTreeRefChild(writesCache, childName);\n const childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(\n syncTreeApplyOperationDescendantsHelper_(\n childOperation,\n childTree,\n childServerCache,\n childWritesCache\n )\n );\n }\n });\n\n if (syncPoint) {\n events = events.concat(\n syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)\n );\n }\n\n return events;\n}\n\nfunction syncTreeCreateListenerForView_(\n syncTree: SyncTree,\n view: View\n): { hashFn(): string; onComplete(a: string, b?: unknown): Event[] } {\n const query = view.query;\n const tag = syncTreeTagForQuery(syncTree, query);\n\n return {\n hashFn: () => {\n const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: (status: string): Event[] => {\n if (status === 'ok') {\n if (tag) {\n return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);\n } else {\n return syncTreeApplyListenComplete(syncTree, query._path);\n }\n } else {\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\n const error = errorForServerCode(status, query);\n return syncTreeRemoveEventRegistration(\n syncTree,\n query,\n /*eventRegistration*/ null,\n error\n );\n }\n }\n };\n}\n\n/**\n * Return the tag associated with the given query.\n */\nexport function syncTreeTagForQuery(\n syncTree: SyncTree,\n query: QueryContext\n): number | null {\n const queryKey = syncTreeMakeQueryKey_(query);\n return syncTree.queryToTagMap.get(queryKey);\n}\n\n/**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n */\nfunction syncTreeMakeQueryKey_(query: QueryContext): string {\n return query._path.toString() + '$' + query._queryIdentifier;\n}\n\n/**\n * Return the query associated with the given tag, if we have one\n */\nfunction syncTreeQueryKeyForTag_(\n syncTree: SyncTree,\n tag: number\n): string | null {\n return syncTree.tagToQueryMap.get(tag);\n}\n\n/**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n */\nfunction syncTreeParseQueryKey_(queryKey: string): {\n queryId: string;\n path: Path;\n} {\n const splitIndex = queryKey.indexOf('$');\n assert(\n splitIndex !== -1 && splitIndex < queryKey.length - 1,\n 'Bad queryKey.'\n );\n return {\n queryId: queryKey.substr(splitIndex + 1),\n path: new Path(queryKey.substr(0, splitIndex))\n };\n}\n\n/**\n * A helper method to apply tagged operations\n */\nfunction syncTreeApplyTaggedOperation_(\n syncTree: SyncTree,\n queryPath: Path,\n operation: Operation\n): Event[] {\n const syncPoint = syncTree.syncPointTree_.get(queryPath);\n assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n const writesCache = writeTreeChildWrites(\n syncTree.pendingWriteTree_,\n queryPath\n );\n return syncPointApplyOperation(syncPoint, operation, writesCache, null);\n}\n\n/**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n */\nfunction syncTreeCollectDistinctViewsForSubTree_(\n subtree: ImmutableTree\n): View[] {\n return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {\n if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {\n const completeView = syncPointGetCompleteView(maybeChildSyncPoint);\n return [completeView];\n } else {\n // No complete view here, flatten any deeper listens into an array\n let views: View[] = [];\n if (maybeChildSyncPoint) {\n views = syncPointGetQueryViews(maybeChildSyncPoint);\n }\n each(childMap, (_key: string, childViews: View[]) => {\n views = views.concat(childViews);\n });\n return views;\n }\n });\n}\n\n/**\n * Normalizes a query to a query we send the server for listening\n *\n * @returns The normalized query\n */\nfunction syncTreeQueryForListening_(query: QueryContext): QueryContext {\n if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {\n // We treat queries that load all data as default queries\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n // from Query\n return new (syncTreeGetReferenceConstructor())(query._repo, query._path);\n } else {\n return query;\n }\n}\n\nfunction syncTreeRemoveTags_(syncTree: SyncTree, queries: QueryContext[]) {\n for (let j = 0; j < queries.length; ++j) {\n const removedQuery = queries[j];\n if (!removedQuery._queryParams.loadsAllData()) {\n // We should have a tag for this\n const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);\n const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);\n syncTree.queryToTagMap.delete(removedQueryKey);\n syncTree.tagToQueryMap.delete(removedQueryTag);\n }\n }\n}\n\n/**\n * Static accessor for query tags.\n */\nfunction syncTreeGetNextQueryTag_(): number {\n return syncTreeNextQueryTag_++;\n}\n\n/**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @returns This method can return events to support synchronous data sources\n */\nfunction syncTreeSetupListener_(\n syncTree: SyncTree,\n query: QueryContext,\n view: View\n): Event[] {\n const path = query._path;\n const tag = syncTreeTagForQuery(syncTree, query);\n const listener = syncTreeCreateListenerForView_(syncTree, view);\n\n const events = syncTree.listenProvider_.startListening(\n syncTreeQueryForListening_(query),\n tag,\n listener.hashFn,\n listener.onComplete\n );\n\n const subtree = syncTree.syncPointTree_.subtree(path);\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\n // may need to shadow other listens as well.\n if (tag) {\n assert(\n !syncPointHasCompleteView(subtree.value),\n \"If we're adding a query, it shouldn't be shadowed\"\n );\n } else {\n // Shadow everything at or below this location, this is a default listener.\n const queriesToStop = subtree.fold(\n (relativePath, maybeChildSyncPoint, childMap) => {\n if (\n !pathIsEmpty(relativePath) &&\n maybeChildSyncPoint &&\n syncPointHasCompleteView(maybeChildSyncPoint)\n ) {\n return [syncPointGetCompleteView(maybeChildSyncPoint).query];\n } else {\n // No default listener here, flatten any deeper queries into an array\n let queries: QueryContext[] = [];\n if (maybeChildSyncPoint) {\n queries = queries.concat(\n syncPointGetQueryViews(maybeChildSyncPoint).map(\n view => view.query\n )\n );\n }\n each(childMap, (_key: string, childQueries: QueryContext[]) => {\n queries = queries.concat(childQueries);\n });\n return queries;\n }\n }\n );\n for (let i = 0; i < queriesToStop.length; ++i) {\n const queryToStop = queriesToStop[i];\n syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(queryToStop),\n syncTreeTagForQuery(syncTree, queryToStop)\n );\n }\n }\n return events;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { PRIORITY_INDEX } from '../snap/indexes/PriorityIndex';\nimport { LeafNode } from '../snap/LeafNode';\nimport { Node } from '../snap/Node';\nimport { nodeFromJSON } from '../snap/nodeFromJSON';\nimport { SyncTree, syncTreeCalcCompleteEventCache } from '../SyncTree';\n\nimport { Indexable } from './misc';\nimport { Path, pathChild } from './Path';\n\n/* It's critical for performance that we do not calculate actual values from a SyncTree\n * unless and until the value is needed. Because we expose both a SyncTree and Node\n * version of deferred value resolution, we ned a wrapper class that will let us share\n * code.\n *\n * @see https://github.com/firebase/firebase-js-sdk/issues/2487\n */\ninterface ValueProvider {\n getImmediateChild(childName: string): ValueProvider;\n node(): Node;\n}\n\nclass ExistingValueProvider implements ValueProvider {\n constructor(readonly node_: Node) {}\n\n getImmediateChild(childName: string): ValueProvider {\n const child = this.node_.getImmediateChild(childName);\n return new ExistingValueProvider(child);\n }\n\n node(): Node {\n return this.node_;\n }\n}\n\nclass DeferredValueProvider implements ValueProvider {\n private syncTree_: SyncTree;\n private path_: Path;\n\n constructor(syncTree: SyncTree, path: Path) {\n this.syncTree_ = syncTree;\n this.path_ = path;\n }\n\n getImmediateChild(childName: string): ValueProvider {\n const childPath = pathChild(this.path_, childName);\n return new DeferredValueProvider(this.syncTree_, childPath);\n }\n\n node(): Node {\n return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);\n }\n}\n\n/**\n * Generate placeholders for deferred values.\n */\nexport const generateWithValues = function (\n values: {\n [k: string]: unknown;\n } | null\n): { [k: string]: unknown } {\n values = values || {};\n values['timestamp'] = values['timestamp'] || new Date().getTime();\n return values;\n};\n\n/**\n * Value to use when firing local events. When writing server values, fire\n * local events with an approximate value, otherwise return value as-is.\n */\nexport const resolveDeferredLeafValue = function (\n value: { [k: string]: unknown } | string | number | boolean,\n existingVal: ValueProvider,\n serverValues: { [k: string]: unknown }\n): string | number | boolean {\n if (!value || typeof value !== 'object') {\n return value as string | number | boolean;\n }\n assert('.sv' in value, 'Unexpected leaf node or priority contents');\n\n if (typeof value['.sv'] === 'string') {\n return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);\n } else if (typeof value['.sv'] === 'object') {\n return resolveComplexDeferredValue(value['.sv'], existingVal, serverValues);\n } else {\n assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));\n }\n};\n\nconst resolveScalarDeferredValue = function (\n op: string,\n existing: ValueProvider,\n serverValues: { [k: string]: unknown }\n): string | number | boolean {\n switch (op) {\n case 'timestamp':\n return serverValues['timestamp'] as string | number | boolean;\n default:\n assert(false, 'Unexpected server value: ' + op);\n }\n};\n\nconst resolveComplexDeferredValue = function (\n op: object,\n existing: ValueProvider,\n unused: { [k: string]: unknown }\n): string | number | boolean {\n if (!op.hasOwnProperty('increment')) {\n assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));\n }\n const delta = op['increment'];\n if (typeof delta !== 'number') {\n assert(false, 'Unexpected increment value: ' + delta);\n }\n\n const existingNode = existing.node();\n assert(\n existingNode !== null && typeof existingNode !== 'undefined',\n 'Expected ChildrenNode.EMPTY_NODE for nulls'\n );\n\n // Incrementing a non-number sets the value to the incremented amount\n if (!existingNode.isLeafNode()) {\n return delta;\n }\n\n const leaf = existingNode as LeafNode;\n const existingVal = leaf.getValue();\n if (typeof existingVal !== 'number') {\n return delta;\n }\n\n // No need to do over/underflow arithmetic here because JS only handles floats under the covers\n return existingVal + delta;\n};\n\n/**\n * Recursively replace all deferred values and priorities in the tree with the\n * specified generated replacement values.\n * @param path - path to which write is relative\n * @param node - new data written at path\n * @param syncTree - current data\n */\nexport const resolveDeferredValueTree = function (\n path: Path,\n node: Node,\n syncTree: SyncTree,\n serverValues: Indexable\n): Node {\n return resolveDeferredValue(\n node,\n new DeferredValueProvider(syncTree, path),\n serverValues\n );\n};\n\n/**\n * Recursively replace all deferred values and priorities in the node with the\n * specified generated replacement values. If there are no server values in the node,\n * it'll be returned as-is.\n */\nexport const resolveDeferredValueSnapshot = function (\n node: Node,\n existing: Node,\n serverValues: Indexable\n): Node {\n return resolveDeferredValue(\n node,\n new ExistingValueProvider(existing),\n serverValues\n );\n};\n\nfunction resolveDeferredValue(\n node: Node,\n existingVal: ValueProvider,\n serverValues: Indexable\n): Node {\n const rawPri = node.getPriority().val() as\n | Indexable\n | boolean\n | null\n | number\n | string;\n const priority = resolveDeferredLeafValue(\n rawPri,\n existingVal.getImmediateChild('.priority'),\n serverValues\n );\n let newNode: Node;\n\n if (node.isLeafNode()) {\n const leafNode = node as LeafNode;\n const value = resolveDeferredLeafValue(\n leafNode.getValue(),\n existingVal,\n serverValues\n );\n if (\n value !== leafNode.getValue() ||\n priority !== leafNode.getPriority().val()\n ) {\n return new LeafNode(value, nodeFromJSON(priority));\n } else {\n return node;\n }\n } else {\n const childrenNode = node as ChildrenNode;\n newNode = childrenNode;\n if (priority !== childrenNode.getPriority().val()) {\n newNode = newNode.updatePriority(new LeafNode(priority));\n }\n childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\n const newChildNode = resolveDeferredValue(\n childNode,\n existingVal.getImmediateChild(childName),\n serverValues\n );\n if (newChildNode !== childNode) {\n newNode = newNode.updateImmediateChild(childName, newChildNode);\n }\n });\n return newNode;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains, safeGet } from '@firebase/util';\n\nimport { Path, pathGetFront, pathPopFront } from './Path';\nimport { each } from './util';\n\n/**\n * Node in a Tree.\n */\nexport interface TreeNode {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n children: Record>;\n childCount: number;\n value?: T;\n}\n\n/**\n * A light-weight tree, traversable by path. Nodes can have both values and children.\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\n * children.\n */\nexport class Tree {\n /**\n * @param name - Optional name of the node.\n * @param parent - Optional parent node.\n * @param node - Optional node to wrap.\n */\n constructor(\n readonly name: string = '',\n readonly parent: Tree | null = null,\n public node: TreeNode = { children: {}, childCount: 0 }\n ) {}\n}\n\n/**\n * Returns a sub-Tree for the given path.\n *\n * @param pathObj - Path to look up.\n * @returns Tree for path.\n */\nexport function treeSubTree(tree: Tree, pathObj: string | Path): Tree {\n // TODO: Require pathObj to be Path?\n let path = pathObj instanceof Path ? pathObj : new Path(pathObj);\n let child = tree,\n next = pathGetFront(path);\n while (next !== null) {\n const childNode = safeGet(child.node.children, next) || {\n children: {},\n childCount: 0\n };\n child = new Tree(next, child, childNode);\n path = pathPopFront(path);\n next = pathGetFront(path);\n }\n\n return child;\n}\n\n/**\n * Returns the data associated with this tree node.\n *\n * @returns The data or null if no data exists.\n */\nexport function treeGetValue(tree: Tree): T | undefined {\n return tree.node.value;\n}\n\n/**\n * Sets data to this tree node.\n *\n * @param value - Value to set.\n */\nexport function treeSetValue(tree: Tree, value: T | undefined): void {\n tree.node.value = value;\n treeUpdateParents(tree);\n}\n\n/**\n * @returns Whether the tree has any children.\n */\nexport function treeHasChildren(tree: Tree): boolean {\n return tree.node.childCount > 0;\n}\n\n/**\n * @returns Whether the tree is empty (no value or children).\n */\nexport function treeIsEmpty(tree: Tree): boolean {\n return treeGetValue(tree) === undefined && !treeHasChildren(tree);\n}\n\n/**\n * Calls action for each child of this tree node.\n *\n * @param action - Action to be called for each child.\n */\nexport function treeForEachChild(\n tree: Tree,\n action: (tree: Tree) => void\n): void {\n each(tree.node.children, (child: string, childTree: TreeNode) => {\n action(new Tree(child, tree, childTree));\n });\n}\n\n/**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param action - Action to be called for each child.\n * @param includeSelf - Whether to call action on this node as well. Defaults to\n * false.\n * @param childrenFirst - Whether to call action on children before calling it on\n * parent.\n */\nexport function treeForEachDescendant(\n tree: Tree,\n action: (tree: Tree) => void,\n includeSelf?: boolean,\n childrenFirst?: boolean\n): void {\n if (includeSelf && !childrenFirst) {\n action(tree);\n }\n\n treeForEachChild(tree, child => {\n treeForEachDescendant(child, action, true, childrenFirst);\n });\n\n if (includeSelf && childrenFirst) {\n action(tree);\n }\n}\n\n/**\n * Calls action on each ancestor node.\n *\n * @param action - Action to be called on each parent; return\n * true to abort.\n * @param includeSelf - Whether to call action on this node as well.\n * @returns true if the action callback returned true.\n */\nexport function treeForEachAncestor(\n tree: Tree,\n action: (tree: Tree) => unknown,\n includeSelf?: boolean\n): boolean {\n let node = includeSelf ? tree : tree.parent;\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n node = node.parent;\n }\n return false;\n}\n\n/**\n * Does a depth-first traversal of this node's descendants. When a descendant with a value\n * is found, action is called on it and traversal does not continue inside the node.\n * Action is *not* called on this node.\n *\n * @param action - Action to be called for each child.\n */\nexport function treeForEachImmediateDescendantWithValue(\n tree: Tree,\n action: (tree: Tree) => void\n): void {\n treeForEachChild(tree, child => {\n if (treeGetValue(child) !== undefined) {\n action(child);\n } else {\n treeForEachImmediateDescendantWithValue(child, action);\n }\n });\n}\n\n/**\n * @returns The path of this tree node, as a Path.\n */\nexport function treeGetPath(tree: Tree) {\n return new Path(\n tree.parent === null\n ? tree.name\n : treeGetPath(tree.parent) + '/' + tree.name\n );\n}\n\n/**\n * Adds or removes this child from its parent based on whether it's empty or not.\n */\nfunction treeUpdateParents(tree: Tree) {\n if (tree.parent !== null) {\n treeUpdateChild(tree.parent, tree.name, tree);\n }\n}\n\n/**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param childName - The name of the child to update.\n * @param child - The child to update.\n */\nfunction treeUpdateChild(tree: Tree, childName: string, child: Tree) {\n const childEmpty = treeIsEmpty(child);\n const childExists = contains(tree.node.children, childName);\n if (childEmpty && childExists) {\n delete tree.node.children[childName];\n tree.node.childCount--;\n treeUpdateParents(tree);\n } else if (!childEmpty && !childExists) {\n tree.node.children[childName] = child.node;\n tree.node.childCount++;\n treeUpdateParents(tree);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n contains,\n errorPrefix as errorPrefixFxn,\n safeGet,\n stringLength\n} from '@firebase/util';\n\nimport { RepoInfo } from '../RepoInfo';\n\nimport {\n Path,\n pathChild,\n pathCompare,\n pathContains,\n pathGetBack,\n pathGetFront,\n pathSlice,\n ValidationPath,\n validationPathPop,\n validationPathPush,\n validationPathToErrorString\n} from './Path';\nimport { each, isInvalidJSONNumber } from './util';\n\n/**\n * True for invalid Firebase keys\n */\nexport const INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\n\n/**\n * True for invalid Firebase paths.\n * Allows '/' in paths.\n */\nexport const INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\n\n/**\n * Maximum number of characters to allow in leaf value\n */\nexport const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\n\nexport const isValidKey = function (key: unknown): boolean {\n return (\n typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key)\n );\n};\n\nexport const isValidPathString = function (pathString: string): boolean {\n return (\n typeof pathString === 'string' &&\n pathString.length !== 0 &&\n !INVALID_PATH_REGEX_.test(pathString)\n );\n};\n\nexport const isValidRootPathString = function (pathString: string): boolean {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n\n return isValidPathString(pathString);\n};\n\nexport const isValidPriority = function (priority: unknown): boolean {\n return (\n priority === null ||\n typeof priority === 'string' ||\n (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||\n (priority &&\n typeof priority === 'object' &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n contains(priority as any, '.sv'))\n );\n};\n\n/**\n * Pre-validate a datum passed as an argument to Firebase function.\n */\nexport const validateFirebaseDataArg = function (\n fnName: string,\n value: unknown,\n path: Path,\n optional: boolean\n) {\n if (optional && value === undefined) {\n return;\n }\n\n validateFirebaseData(errorPrefixFxn(fnName, 'value'), value, path);\n};\n\n/**\n * Validate a data object client-side before sending to server.\n */\nexport const validateFirebaseData = function (\n errorPrefix: string,\n data: unknown,\n path_: Path | ValidationPath\n) {\n const path =\n path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;\n\n if (data === undefined) {\n throw new Error(\n errorPrefix + 'contains undefined ' + validationPathToErrorString(path)\n );\n }\n if (typeof data === 'function') {\n throw new Error(\n errorPrefix +\n 'contains a function ' +\n validationPathToErrorString(path) +\n ' with contents = ' +\n data.toString()\n );\n }\n if (isInvalidJSONNumber(data)) {\n throw new Error(\n errorPrefix +\n 'contains ' +\n data.toString() +\n ' ' +\n validationPathToErrorString(path)\n );\n }\n\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\n if (\n typeof data === 'string' &&\n data.length > MAX_LEAF_SIZE_ / 3 &&\n stringLength(data) > MAX_LEAF_SIZE_\n ) {\n throw new Error(\n errorPrefix +\n 'contains a string greater than ' +\n MAX_LEAF_SIZE_ +\n ' utf8 bytes ' +\n validationPathToErrorString(path) +\n \" ('\" +\n data.substring(0, 50) +\n \"...')\"\n );\n }\n\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\n // to save extra walking of large objects.\n if (data && typeof data === 'object') {\n let hasDotValue = false;\n let hasActualChild = false;\n each(data, (key: string, value: unknown) => {\n if (key === '.value') {\n hasDotValue = true;\n } else if (key !== '.priority' && key !== '.sv') {\n hasActualChild = true;\n if (!isValidKey(key)) {\n throw new Error(\n errorPrefix +\n ' contains an invalid key (' +\n key +\n ') ' +\n validationPathToErrorString(path) +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"'\n );\n }\n }\n\n validationPathPush(path, key);\n validateFirebaseData(errorPrefix, value, path);\n validationPathPop(path);\n });\n\n if (hasDotValue && hasActualChild) {\n throw new Error(\n errorPrefix +\n ' contains \".value\" child ' +\n validationPathToErrorString(path) +\n ' in addition to actual children.'\n );\n }\n }\n};\n\n/**\n * Pre-validate paths passed in the firebase function.\n */\nexport const validateFirebaseMergePaths = function (\n errorPrefix: string,\n mergePaths: Path[]\n) {\n let i, curPath: Path;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n const keys = pathSlice(curPath);\n for (let j = 0; j < keys.length; j++) {\n if (keys[j] === '.priority' && j === keys.length - 1) {\n // .priority is OK\n } else if (!isValidKey(keys[j])) {\n throw new Error(\n errorPrefix +\n 'contains an invalid key (' +\n keys[j] +\n ') in path ' +\n curPath.toString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"'\n );\n }\n }\n }\n\n // Check that update keys are not descendants of each other.\n // We rely on the property that sorting guarantees that ancestors come\n // right before descendants.\n mergePaths.sort(pathCompare);\n let prevPath: Path | null = null;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n if (prevPath !== null && pathContains(prevPath, curPath)) {\n throw new Error(\n errorPrefix +\n 'contains a path ' +\n prevPath.toString() +\n ' that is ancestor of another path ' +\n curPath.toString()\n );\n }\n prevPath = curPath;\n }\n};\n\n/**\n * pre-validate an object passed as an argument to firebase function (\n * must be an object - e.g. for firebase.update()).\n */\nexport const validateFirebaseMergeDataArg = function (\n fnName: string,\n data: unknown,\n path: Path,\n optional: boolean\n) {\n if (optional && data === undefined) {\n return;\n }\n\n const errorPrefix = errorPrefixFxn(fnName, 'values');\n\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\n throw new Error(\n errorPrefix + ' must be an object containing the children to replace.'\n );\n }\n\n const mergePaths: Path[] = [];\n each(data, (key: string, value: unknown) => {\n const curPath = new Path(key);\n validateFirebaseData(errorPrefix, value, pathChild(path, curPath));\n if (pathGetBack(curPath) === '.priority') {\n if (!isValidPriority(value)) {\n throw new Error(\n errorPrefix +\n \"contains an invalid value for '\" +\n curPath.toString() +\n \"', which must be a valid \" +\n 'Firebase priority (a string, finite number, server value, or null).'\n );\n }\n }\n mergePaths.push(curPath);\n });\n validateFirebaseMergePaths(errorPrefix, mergePaths);\n};\n\nexport const validatePriority = function (\n fnName: string,\n priority: unknown,\n optional: boolean\n) {\n if (optional && priority === undefined) {\n return;\n }\n if (isInvalidJSONNumber(priority)) {\n throw new Error(\n errorPrefixFxn(fnName, 'priority') +\n 'is ' +\n priority.toString() +\n ', but must be a valid Firebase priority (a string, finite number, ' +\n 'server value, or null).'\n );\n }\n // Special case to allow importing data with a .sv.\n if (!isValidPriority(priority)) {\n throw new Error(\n errorPrefixFxn(fnName, 'priority') +\n 'must be a valid Firebase priority ' +\n '(a string, finite number, server value, or null).'\n );\n }\n};\n\nexport const validateKey = function (\n fnName: string,\n argumentName: string,\n key: string,\n optional: boolean\n) {\n if (optional && key === undefined) {\n return;\n }\n if (!isValidKey(key)) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'was an invalid key = \"' +\n key +\n '\". Firebase keys must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").'\n );\n }\n};\n\n/**\n * @internal\n */\nexport const validatePathString = function (\n fnName: string,\n argumentName: string,\n pathString: string,\n optional: boolean\n) {\n if (optional && pathString === undefined) {\n return;\n }\n\n if (!isValidPathString(pathString)) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'was an invalid path = \"' +\n pathString +\n '\". Paths must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"'\n );\n }\n};\n\nexport const validateRootPathString = function (\n fnName: string,\n argumentName: string,\n pathString: string,\n optional: boolean\n) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n\n validatePathString(fnName, argumentName, pathString, optional);\n};\n\n/**\n * @internal\n */\nexport const validateWritablePath = function (fnName: string, path: Path) {\n if (pathGetFront(path) === '.info') {\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\n }\n};\n\nexport const validateUrl = function (\n fnName: string,\n parsedUrl: { repoInfo: RepoInfo; path: Path }\n) {\n // TODO = Validate server better.\n const pathString = parsedUrl.path.toString();\n if (\n !(typeof parsedUrl.repoInfo.host === 'string') ||\n parsedUrl.repoInfo.host.length === 0 ||\n (!isValidKey(parsedUrl.repoInfo.namespace) &&\n parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||\n (pathString.length !== 0 && !isValidRootPathString(pathString))\n ) {\n throw new Error(\n errorPrefixFxn(fnName, 'url') +\n 'must be a valid firebase URL and ' +\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".'\n );\n }\n};\n\nexport const validateString = function (\n fnName: string,\n argumentName: string,\n string: unknown,\n optional: boolean\n) {\n if (optional && string === undefined) {\n return;\n }\n if (!(typeof string === 'string')) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) + 'must be a valid string.'\n );\n }\n};\n\nexport const validateObject = function (\n fnName: string,\n argumentName: string,\n obj: unknown,\n optional: boolean\n) {\n if (optional && obj === undefined) {\n return;\n }\n if (!(obj && typeof obj === 'object') || obj === null) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) + 'must be a valid object.'\n );\n }\n};\n\nexport const validateObjectContainsKey = function (\n fnName: string,\n argumentName: string,\n obj: unknown,\n key: string,\n optional: boolean,\n optType?: string\n) {\n const objectContainsKey =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj && typeof obj === 'object' && contains(obj as any, key);\n\n if (!objectContainsKey) {\n if (optional) {\n return;\n } else {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'must contain the key \"' +\n key +\n '\"'\n );\n }\n }\n\n if (optType) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const val = safeGet(obj as any, key);\n if (\n (optType === 'number' && !(typeof val === 'number')) ||\n (optType === 'string' && !(typeof val === 'string')) ||\n (optType === 'boolean' && !(typeof val === 'boolean')) ||\n (optType === 'function' && !(typeof val === 'function')) ||\n (optType === 'object' && !(typeof val === 'object') && val)\n ) {\n if (optional) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'contains invalid value for key \"' +\n key +\n '\" (must be of type \"' +\n optType +\n '\")'\n );\n } else {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'must contain the key \"' +\n key +\n '\" with type \"' +\n optType +\n '\"'\n );\n }\n }\n }\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Path, pathContains, pathEquals } from '../util/Path';\nimport { exceptionGuard, log, logger } from '../util/util';\n\nimport { Event } from './Event';\n\n/**\n * The event queue serves a few purposes:\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\n * events being queued.\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\n * left off, ensuring that the events are still raised synchronously and in order.\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\n * events are raised synchronously.\n *\n * NOTE: This can all go away if/when we move to async events.\n *\n */\nexport class EventQueue {\n eventLists_: EventList[] = [];\n\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n */\n recursionDepth_ = 0;\n}\n\n/**\n * @param eventDataList - The new events to queue.\n */\nexport function eventQueueQueueEvents(\n eventQueue: EventQueue,\n eventDataList: Event[]\n) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n let currList: EventList | null = null;\n for (let i = 0; i < eventDataList.length; i++) {\n const data = eventDataList[i];\n const path = data.getPath();\n if (currList !== null && !pathEquals(path, currList.path)) {\n eventQueue.eventLists_.push(currList);\n currList = null;\n }\n\n if (currList === null) {\n currList = { events: [], path };\n }\n\n currList.events.push(data);\n }\n if (currList) {\n eventQueue.eventLists_.push(currList);\n }\n}\n\n/**\n * Queues the specified events and synchronously raises all events (including previously queued ones)\n * for the specified path.\n *\n * It is assumed that the new events are all for the specified path.\n *\n * @param path - The path to raise events for.\n * @param eventDataList - The new events to raise.\n */\nexport function eventQueueRaiseEventsAtPath(\n eventQueue: EventQueue,\n path: Path,\n eventDataList: Event[]\n) {\n eventQueueQueueEvents(eventQueue, eventDataList);\n eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath =>\n pathEquals(eventPath, path)\n );\n}\n\n/**\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\n * locations related to the specified change path (i.e. all ancestors and descendants).\n *\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\n *\n * @param changedPath - The path to raise events for.\n * @param eventDataList - The events to raise\n */\nexport function eventQueueRaiseEventsForChangedPath(\n eventQueue: EventQueue,\n changedPath: Path,\n eventDataList: Event[]\n) {\n eventQueueQueueEvents(eventQueue, eventDataList);\n eventQueueRaiseQueuedEventsMatchingPredicate(\n eventQueue,\n eventPath =>\n pathContains(eventPath, changedPath) ||\n pathContains(changedPath, eventPath)\n );\n}\n\nfunction eventQueueRaiseQueuedEventsMatchingPredicate(\n eventQueue: EventQueue,\n predicate: (path: Path) => boolean\n) {\n eventQueue.recursionDepth_++;\n\n let sentAll = true;\n for (let i = 0; i < eventQueue.eventLists_.length; i++) {\n const eventList = eventQueue.eventLists_[i];\n if (eventList) {\n const eventPath = eventList.path;\n if (predicate(eventPath)) {\n eventListRaise(eventQueue.eventLists_[i]);\n eventQueue.eventLists_[i] = null;\n } else {\n sentAll = false;\n }\n }\n }\n\n if (sentAll) {\n eventQueue.eventLists_ = [];\n }\n\n eventQueue.recursionDepth_--;\n}\n\ninterface EventList {\n events: Event[];\n path: Path;\n}\n\n/**\n * Iterates through the list and raises each event\n */\nfunction eventListRaise(eventList: EventList) {\n for (let i = 0; i < eventList.events.length; i++) {\n const eventData = eventList.events[i];\n if (eventData !== null) {\n eventList.events[i] = null;\n const eventFn = eventData.getEventRunner();\n if (logger) {\n log('event: ' + eventData.toString());\n }\n exceptionGuard(eventFn);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n contains,\n isEmpty,\n map,\n safeGet,\n stringify\n} from '@firebase/util';\n\nimport { ValueEventRegistration } from '../api/Reference_impl';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { PersistentConnection } from './PersistentConnection';\nimport { ReadonlyRestClient } from './ReadonlyRestClient';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { nodeFromJSON } from './snap/nodeFromJSON';\nimport { SnapshotHolder } from './SnapshotHolder';\nimport {\n newSparseSnapshotTree,\n SparseSnapshotTree,\n sparseSnapshotTreeForEachTree,\n sparseSnapshotTreeForget,\n sparseSnapshotTreeRemember\n} from './SparseSnapshotTree';\nimport { StatsCollection } from './stats/StatsCollection';\nimport { StatsListener } from './stats/StatsListener';\nimport {\n statsManagerGetCollection,\n statsManagerGetOrCreateReporter\n} from './stats/StatsManager';\nimport { StatsReporter, statsReporterIncludeStat } from './stats/StatsReporter';\nimport {\n SyncTree,\n syncTreeAckUserWrite,\n syncTreeAddEventRegistration,\n syncTreeApplyServerMerge,\n syncTreeApplyServerOverwrite,\n syncTreeApplyTaggedQueryMerge,\n syncTreeApplyTaggedQueryOverwrite,\n syncTreeApplyUserMerge,\n syncTreeApplyUserOverwrite,\n syncTreeCalcCompleteEventCache,\n syncTreeGetServerValue,\n syncTreeRemoveEventRegistration,\n syncTreeTagForQuery\n} from './SyncTree';\nimport { Indexable } from './util/misc';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathGetFront,\n pathPopFront\n} from './util/Path';\nimport {\n generateWithValues,\n resolveDeferredValueSnapshot,\n resolveDeferredValueTree\n} from './util/ServerValues';\nimport {\n Tree,\n treeForEachAncestor,\n treeForEachChild,\n treeForEachDescendant,\n treeGetPath,\n treeGetValue,\n treeHasChildren,\n treeSetValue,\n treeSubTree\n} from './util/Tree';\nimport {\n beingCrawled,\n each,\n exceptionGuard,\n log,\n LUIDGenerator,\n warn\n} from './util/util';\nimport { isValidPriority, validateFirebaseData } from './util/validation';\nimport { Event } from './view/Event';\nimport {\n EventQueue,\n eventQueueQueueEvents,\n eventQueueRaiseEventsAtPath,\n eventQueueRaiseEventsForChangedPath\n} from './view/EventQueue';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\n\nconst INTERRUPT_REASON = 'repo_interrupt';\n\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other\n * things this ensure that if there's ever a bug causing a mismatch between\n * client / server hashes for some data, we won't retry indefinitely.\n */\nconst MAX_TRANSACTION_RETRIES = 25;\n\nconst enum TransactionStatus {\n // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the\n // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to\n // mismatched hash.\n RUN,\n\n // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted\n // or rejected yet).\n SENT,\n\n // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be\n // removed when we get a chance to prune completed ones.\n COMPLETED,\n\n // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made).\n // If it comes back as unsuccessful, we'll abort it.\n SENT_NEEDS_ABORT,\n\n // Temporary state used to mark transactions that need to be aborted.\n NEEDS_ABORT\n}\n\ninterface Transaction {\n path: Path;\n update: (a: unknown) => unknown;\n onComplete: (\n error: Error | null,\n committed: boolean,\n node: Node | null\n ) => void;\n status: TransactionStatus;\n order: number;\n applyLocally: boolean;\n retryCount: number;\n unwatcher: () => void;\n abortReason: string | null;\n currentWriteId: number;\n currentInputSnapshot: Node | null;\n currentOutputSnapshotRaw: Node | null;\n currentOutputSnapshotResolved: Node | null;\n}\n\n/**\n * A connection to a single data repository.\n */\nexport class Repo {\n /** Key for uniquely identifying this repo, used in RepoManager */\n readonly key: string;\n\n dataUpdateCount = 0;\n infoSyncTree_: SyncTree;\n serverSyncTree_: SyncTree;\n\n stats_: StatsCollection;\n statsListener_: StatsListener | null = null;\n eventQueue_ = new EventQueue();\n nextWriteId_ = 1;\n server_: ServerActions;\n statsReporter_: StatsReporter;\n infoData_: SnapshotHolder;\n interceptServerDataCallback_: ((a: string, b: unknown) => void) | null = null;\n\n /** A list of data pieces and paths to be set when this client disconnects. */\n onDisconnect_: SparseSnapshotTree = newSparseSnapshotTree();\n\n /** Stores queues of outstanding transactions for Firebase locations. */\n transactionQueueTree_ = new Tree();\n\n // TODO: This should be @private but it's used by test_access.js and internal.js\n persistentConnection_: PersistentConnection | null = null;\n\n constructor(\n public repoInfo_: RepoInfo,\n public forceRestClient_: boolean,\n public authTokenProvider_: AuthTokenProvider,\n public appCheckProvider_: AppCheckTokenProvider\n ) {\n // This key is intentionally not updated if RepoInfo is later changed or replaced\n this.key = this.repoInfo_.toURLString();\n }\n\n /**\n * @returns The URL corresponding to the root of this Firebase.\n */\n toString(): string {\n return (\n (this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host\n );\n }\n}\n\nexport function repoStart(\n repo: Repo,\n appId: string,\n authOverride?: object\n): void {\n repo.stats_ = statsManagerGetCollection(repo.repoInfo_);\n\n if (repo.forceRestClient_ || beingCrawled()) {\n repo.server_ = new ReadonlyRestClient(\n repo.repoInfo_,\n (\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n ) => {\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\n },\n repo.authTokenProvider_,\n repo.appCheckProvider_\n );\n\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\n setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);\n } else {\n // Validate authOverride\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\n if (typeof authOverride !== 'object') {\n throw new Error(\n 'Only objects are supported for option databaseAuthVariableOverride'\n );\n }\n try {\n stringify(authOverride);\n } catch (e) {\n throw new Error('Invalid authOverride provided: ' + e);\n }\n }\n\n repo.persistentConnection_ = new PersistentConnection(\n repo.repoInfo_,\n appId,\n (\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n ) => {\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\n },\n (connectStatus: boolean) => {\n repoOnConnectStatus(repo, connectStatus);\n },\n (updates: object) => {\n repoOnServerInfoUpdate(repo, updates);\n },\n repo.authTokenProvider_,\n repo.appCheckProvider_,\n authOverride\n );\n\n repo.server_ = repo.persistentConnection_;\n }\n\n repo.authTokenProvider_.addTokenChangeListener(token => {\n repo.server_.refreshAuthToken(token);\n });\n\n repo.appCheckProvider_.addTokenChangeListener(result => {\n repo.server_.refreshAppCheckToken(result.token);\n });\n\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\n repo.statsReporter_ = statsManagerGetOrCreateReporter(\n repo.repoInfo_,\n () => new StatsReporter(repo.stats_, repo.server_)\n );\n\n // Used for .info.\n repo.infoData_ = new SnapshotHolder();\n repo.infoSyncTree_ = new SyncTree({\n startListening: (query, tag, currentHashFn, onComplete) => {\n let infoEvents: Event[] = [];\n const node = repo.infoData_.getNode(query._path);\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\n // on initial data...\n if (!node.isEmpty()) {\n infoEvents = syncTreeApplyServerOverwrite(\n repo.infoSyncTree_,\n query._path,\n node\n );\n setTimeout(() => {\n onComplete('ok');\n }, 0);\n }\n return infoEvents;\n },\n stopListening: () => {}\n });\n repoUpdateInfo(repo, 'connected', false);\n\n repo.serverSyncTree_ = new SyncTree({\n startListening: (query, tag, currentHashFn, onComplete) => {\n repo.server_.listen(query, currentHashFn, tag, (status, data) => {\n const events = onComplete(status, data);\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n query._path,\n events\n );\n });\n // No synchronous events for network-backed sync trees\n return [];\n },\n stopListening: (query, tag) => {\n repo.server_.unlisten(query, tag);\n }\n });\n}\n\n/**\n * @returns The time in milliseconds, taking the server offset into account if we have one.\n */\nexport function repoServerTime(repo: Repo): number {\n const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));\n const offset = (offsetNode.val() as number) || 0;\n return new Date().getTime() + offset;\n}\n\n/**\n * Generate ServerValues using some variables from the repo object.\n */\nexport function repoGenerateServerValues(repo: Repo): Indexable {\n return generateWithValues({\n timestamp: repoServerTime(repo)\n });\n}\n\n/**\n * Called by realtime when we get new messages from the server.\n */\nfunction repoOnDataUpdate(\n repo: Repo,\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n): void {\n // For testing.\n repo.dataUpdateCount++;\n const path = new Path(pathString);\n data = repo.interceptServerDataCallback_\n ? repo.interceptServerDataCallback_(pathString, data)\n : data;\n let events = [];\n if (tag) {\n if (isMerge) {\n const taggedChildren = map(\n data as { [k: string]: unknown },\n (raw: unknown) => nodeFromJSON(raw)\n );\n events = syncTreeApplyTaggedQueryMerge(\n repo.serverSyncTree_,\n path,\n taggedChildren,\n tag\n );\n } else {\n const taggedSnap = nodeFromJSON(data);\n events = syncTreeApplyTaggedQueryOverwrite(\n repo.serverSyncTree_,\n path,\n taggedSnap,\n tag\n );\n }\n } else if (isMerge) {\n const changedChildren = map(\n data as { [k: string]: unknown },\n (raw: unknown) => nodeFromJSON(raw)\n );\n events = syncTreeApplyServerMerge(\n repo.serverSyncTree_,\n path,\n changedChildren\n );\n } else {\n const snap = nodeFromJSON(data);\n events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);\n }\n let affectedPath = path;\n if (events.length > 0) {\n // Since we have a listener outstanding for each transaction, receiving any events\n // is a proxy for some change having occurred.\n affectedPath = repoRerunTransactions(repo, path);\n }\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);\n}\n\n// TODO: This should be @private but it's used by test_access.js and internal.js\nexport function repoInterceptServerData(\n repo: Repo,\n callback: ((a: string, b: unknown) => unknown) | null\n): void {\n repo.interceptServerDataCallback_ = callback;\n}\n\nfunction repoOnConnectStatus(repo: Repo, connectStatus: boolean): void {\n repoUpdateInfo(repo, 'connected', connectStatus);\n if (connectStatus === false) {\n repoRunOnDisconnectEvents(repo);\n }\n}\n\nfunction repoOnServerInfoUpdate(repo: Repo, updates: object): void {\n each(updates, (key: string, value: unknown) => {\n repoUpdateInfo(repo, key, value);\n });\n}\n\nfunction repoUpdateInfo(repo: Repo, pathString: string, value: unknown): void {\n const path = new Path('/.info/' + pathString);\n const newNode = nodeFromJSON(value);\n repo.infoData_.updateSnapshot(path, newNode);\n const events = syncTreeApplyServerOverwrite(\n repo.infoSyncTree_,\n path,\n newNode\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n}\n\nfunction repoGetNextWriteId(repo: Repo): number {\n return repo.nextWriteId_++;\n}\n\n/**\n * The purpose of `getValue` is to return the latest known value\n * satisfying `query`.\n *\n * This method will first check for in-memory cached values\n * belonging to active listeners. If they are found, such values\n * are considered to be the most up-to-date.\n *\n * If the client is not connected, this method will wait until the\n * repo has established a connection and then request the value for `query`.\n * If the client is not able to retrieve the query result for another reason,\n * it reports an error.\n *\n * @param query - The query to surface a value for.\n */\nexport function repoGetValue(\n repo: Repo,\n query: QueryContext,\n eventRegistration: ValueEventRegistration\n): Promise {\n // Only active queries are cached. There is no persisted cache.\n const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);\n if (cached != null) {\n return Promise.resolve(cached);\n }\n return repo.server_.get(query).then(\n payload => {\n const node = nodeFromJSON(payload).withIndex(\n query._queryParams.getIndex()\n );\n /**\n * Below we simulate the actions of an `onlyOnce` `onValue()` event where:\n * Add an event registration,\n * Update data at the path,\n * Raise any events,\n * Cleanup the SyncTree\n */\n syncTreeAddEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration,\n true\n );\n let events: Event[];\n if (query._queryParams.loadsAllData()) {\n events = syncTreeApplyServerOverwrite(\n repo.serverSyncTree_,\n query._path,\n node\n );\n } else {\n const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);\n events = syncTreeApplyTaggedQueryOverwrite(\n repo.serverSyncTree_,\n query._path,\n node,\n tag\n );\n }\n /*\n * We need to raise events in the scenario where `get()` is called at a parent path, and\n * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting\n * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree\n * and its corresponding serverCache, including the child location where `onValue` is called. Then,\n * `onValue` will receive the event from the server, but look at the syncTree and see that the data received\n * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.\n * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and\n * ensure the corresponding child events will get fired.\n */\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n query._path,\n events\n );\n syncTreeRemoveEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration,\n null,\n true\n );\n return node;\n },\n err => {\n repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);\n return Promise.reject(new Error(err as string));\n }\n );\n}\n\nexport function repoSetWithPriority(\n repo: Repo,\n path: Path,\n newVal: unknown,\n newPriority: number | string | null,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repoLog(repo, 'set', {\n path: path.toString(),\n value: newVal,\n priority: newPriority\n });\n\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\n // (b) store unresolved paths on JSON parse\n const serverValues = repoGenerateServerValues(repo);\n const newNodeUnresolved = nodeFromJSON(newVal, newPriority);\n const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);\n const newNode = resolveDeferredValueSnapshot(\n newNodeUnresolved,\n existing,\n serverValues\n );\n\n const writeId = repoGetNextWriteId(repo);\n const events = syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n path,\n newNode,\n writeId,\n true\n );\n eventQueueQueueEvents(repo.eventQueue_, events);\n repo.server_.put(\n path.toString(),\n newNodeUnresolved.val(/*export=*/ true),\n (status, errorReason) => {\n const success = status === 'ok';\n if (!success) {\n warn('set at ' + path + ' failed: ' + status);\n }\n\n const clearEvents = syncTreeAckUserWrite(\n repo.serverSyncTree_,\n writeId,\n !success\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n const affectedPath = repoAbortTransactions(repo, path);\n repoRerunTransactions(repo, affectedPath);\n // We queued the events above, so just flush the queue here\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);\n}\n\nexport function repoUpdate(\n repo: Repo,\n path: Path,\n childrenToMerge: { [k: string]: unknown },\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });\n\n // Start with our existing data and merge each child into it.\n let empty = true;\n const serverValues = repoGenerateServerValues(repo);\n const changedChildren: { [k: string]: Node } = {};\n each(childrenToMerge, (changedKey: string, changedValue: unknown) => {\n empty = false;\n changedChildren[changedKey] = resolveDeferredValueTree(\n pathChild(path, changedKey),\n nodeFromJSON(changedValue),\n repo.serverSyncTree_,\n serverValues\n );\n });\n\n if (!empty) {\n const writeId = repoGetNextWriteId(repo);\n const events = syncTreeApplyUserMerge(\n repo.serverSyncTree_,\n path,\n changedChildren,\n writeId\n );\n eventQueueQueueEvents(repo.eventQueue_, events);\n repo.server_.merge(\n path.toString(),\n childrenToMerge,\n (status, errorReason) => {\n const success = status === 'ok';\n if (!success) {\n warn('update at ' + path + ' failed: ' + status);\n }\n\n const clearEvents = syncTreeAckUserWrite(\n repo.serverSyncTree_,\n writeId,\n !success\n );\n const affectedPath =\n clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n affectedPath,\n clearEvents\n );\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n\n each(childrenToMerge, (changedPath: string) => {\n const affectedPath = repoAbortTransactions(\n repo,\n pathChild(path, changedPath)\n );\n repoRerunTransactions(repo, affectedPath);\n });\n\n // We queued the events above, so just flush the queue here\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);\n } else {\n log(\"update() called with empty data. Don't do anything.\");\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\n }\n}\n\n/**\n * Applies all of the changes stored up in the onDisconnect_ tree.\n */\nfunction repoRunOnDisconnectEvents(repo: Repo): void {\n repoLog(repo, 'onDisconnectEvents');\n\n const serverValues = repoGenerateServerValues(repo);\n const resolvedOnDisconnectTree = newSparseSnapshotTree();\n sparseSnapshotTreeForEachTree(\n repo.onDisconnect_,\n newEmptyPath(),\n (path, node) => {\n const resolved = resolveDeferredValueTree(\n path,\n node,\n repo.serverSyncTree_,\n serverValues\n );\n sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);\n }\n );\n let events: Event[] = [];\n\n sparseSnapshotTreeForEachTree(\n resolvedOnDisconnectTree,\n newEmptyPath(),\n (path, snap) => {\n events = events.concat(\n syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap)\n );\n const affectedPath = repoAbortTransactions(repo, path);\n repoRerunTransactions(repo, affectedPath);\n }\n );\n\n repo.onDisconnect_ = newSparseSnapshotTree();\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);\n}\n\nexport function repoOnDisconnectCancel(\n repo: Repo,\n path: Path,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeForget(repo.onDisconnect_, path);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n });\n}\n\nexport function repoOnDisconnectSet(\n repo: Repo,\n path: Path,\n value: unknown,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n const newNode = nodeFromJSON(value);\n repo.server_.onDisconnectPut(\n path.toString(),\n newNode.val(/*export=*/ true),\n (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoOnDisconnectSetWithPriority(\n repo: Repo,\n path: Path,\n value: unknown,\n priority: unknown,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n const newNode = nodeFromJSON(value, priority);\n repo.server_.onDisconnectPut(\n path.toString(),\n newNode.val(/*export=*/ true),\n (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoOnDisconnectUpdate(\n repo: Repo,\n path: Path,\n childrenToMerge: { [k: string]: unknown },\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n if (isEmpty(childrenToMerge)) {\n log(\"onDisconnect().update() called with empty data. Don't do anything.\");\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\n return;\n }\n\n repo.server_.onDisconnectMerge(\n path.toString(),\n childrenToMerge,\n (status, errorReason) => {\n if (status === 'ok') {\n each(childrenToMerge, (childName: string, childNode: unknown) => {\n const newChildNode = nodeFromJSON(childNode);\n sparseSnapshotTreeRemember(\n repo.onDisconnect_,\n pathChild(path, childName),\n newChildNode\n );\n });\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoAddEventCallbackForQuery(\n repo: Repo,\n query: QueryContext,\n eventRegistration: EventRegistration\n): void {\n let events;\n if (pathGetFront(query._path) === '.info') {\n events = syncTreeAddEventRegistration(\n repo.infoSyncTree_,\n query,\n eventRegistration\n );\n } else {\n events = syncTreeAddEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration\n );\n }\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\n}\n\nexport function repoRemoveEventCallbackForQuery(\n repo: Repo,\n query: QueryContext,\n eventRegistration: EventRegistration\n): void {\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\n // a little bit by handling the return values anyways.\n let events;\n if (pathGetFront(query._path) === '.info') {\n events = syncTreeRemoveEventRegistration(\n repo.infoSyncTree_,\n query,\n eventRegistration\n );\n } else {\n events = syncTreeRemoveEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration\n );\n }\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\n}\n\nexport function repoInterrupt(repo: Repo): void {\n if (repo.persistentConnection_) {\n repo.persistentConnection_.interrupt(INTERRUPT_REASON);\n }\n}\n\nexport function repoResume(repo: Repo): void {\n if (repo.persistentConnection_) {\n repo.persistentConnection_.resume(INTERRUPT_REASON);\n }\n}\n\nexport function repoStats(repo: Repo, showDelta: boolean = false): void {\n if (typeof console === 'undefined') {\n return;\n }\n\n let stats: { [k: string]: unknown };\n if (showDelta) {\n if (!repo.statsListener_) {\n repo.statsListener_ = new StatsListener(repo.stats_);\n }\n stats = repo.statsListener_.get();\n } else {\n stats = repo.stats_.get();\n }\n\n const longestName = Object.keys(stats).reduce(\n (previousValue, currentValue) =>\n Math.max(currentValue.length, previousValue),\n 0\n );\n\n each(stats, (stat: string, value: unknown) => {\n let paddedStat = stat;\n // pad stat names to be the same length (plus 2 extra spaces).\n for (let i = stat.length; i < longestName + 2; i++) {\n paddedStat += ' ';\n }\n console.log(paddedStat + value);\n });\n}\n\nexport function repoStatsIncrementCounter(repo: Repo, metric: string): void {\n repo.stats_.incrementCounter(metric);\n statsReporterIncludeStat(repo.statsReporter_, metric);\n}\n\nfunction repoLog(repo: Repo, ...varArgs: unknown[]): void {\n let prefix = '';\n if (repo.persistentConnection_) {\n prefix = repo.persistentConnection_.id + ':';\n }\n log(prefix, ...varArgs);\n}\n\nexport function repoCallOnCompleteCallback(\n repo: Repo,\n callback: ((status: Error | null, errorReason?: string) => void) | null,\n status: string,\n errorReason?: string | null\n): void {\n if (callback) {\n exceptionGuard(() => {\n if (status === 'ok') {\n callback(null);\n } else {\n const code = (status || 'error').toUpperCase();\n let message = code;\n if (errorReason) {\n message += ': ' + errorReason;\n }\n\n const error = new Error(message);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (error as any).code = code;\n callback(error);\n }\n });\n }\n}\n\n/**\n * Creates a new transaction, adds it to the transactions we're tracking, and\n * sends it to the server if possible.\n *\n * @param path - Path at which to do transaction.\n * @param transactionUpdate - Update callback.\n * @param onComplete - Completion callback.\n * @param unwatcher - Function that will be called when the transaction no longer\n * need data updates for `path`.\n * @param applyLocally - Whether or not to make intermediate results visible\n */\nexport function repoStartTransaction(\n repo: Repo,\n path: Path,\n transactionUpdate: (a: unknown) => unknown,\n onComplete: ((error: Error, committed: boolean, node: Node) => void) | null,\n unwatcher: () => void,\n applyLocally: boolean\n): void {\n repoLog(repo, 'transaction on ' + path);\n\n // Initialize transaction.\n const transaction: Transaction = {\n path,\n update: transactionUpdate,\n onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out\n // which one goes first.\n order: LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n };\n\n // Run transaction initially.\n const currentState = repoGetLatestState(repo, path, undefined);\n transaction.currentInputSnapshot = currentState;\n const newVal = transaction.update(currentState.val());\n if (newVal === undefined) {\n // Abort transaction.\n transaction.unwatcher();\n transaction.currentOutputSnapshotRaw = null;\n transaction.currentOutputSnapshotResolved = null;\n if (transaction.onComplete) {\n transaction.onComplete(null, false, transaction.currentInputSnapshot);\n }\n } else {\n validateFirebaseData(\n 'transaction failed: Data returned ',\n newVal,\n transaction.path\n );\n\n // Mark as run and add to our queue.\n transaction.status = TransactionStatus.RUN;\n const queueNode = treeSubTree(repo.transactionQueueTree_, path);\n const nodeQueue = treeGetValue(queueNode) || [];\n nodeQueue.push(transaction);\n\n treeSetValue(queueNode, nodeQueue);\n\n // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our\n // transaction state, since the user could start new transactions from the\n // event callbacks.\n let priorityForNode;\n if (\n typeof newVal === 'object' &&\n newVal !== null &&\n contains(newVal, '.priority')\n ) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n priorityForNode = safeGet(newVal as any, '.priority');\n assert(\n isValidPriority(priorityForNode),\n 'Invalid priority returned by transaction. ' +\n 'Priority must be a valid string, finite number, server value, or null.'\n );\n } else {\n const currentNode =\n syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||\n ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n\n const serverValues = repoGenerateServerValues(repo);\n const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);\n const newNode = resolveDeferredValueSnapshot(\n newNodeUnresolved,\n currentState,\n serverValues\n );\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = repoGetNextWriteId(repo);\n\n const events = syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n path,\n newNode,\n transaction.currentWriteId,\n transaction.applyLocally\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n }\n}\n\n/**\n * @param excludeSets - A specific set to exclude\n */\nfunction repoGetLatestState(\n repo: Repo,\n path: Path,\n excludeSets?: number[]\n): Node {\n return (\n syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||\n ChildrenNode.EMPTY_NODE\n );\n}\n\n/**\n * Sends any already-run transactions that aren't waiting for outstanding\n * transactions to complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively\n * with a particular transactionQueueTree node to recurse through the tree.\n *\n * @param node - transactionQueueTree node to start at.\n */\nfunction repoSendReadyTransactions(\n repo: Repo,\n node: Tree = repo.transactionQueueTree_\n): void {\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n repoPruneCompletedTransactionsBelowNode(repo, node);\n }\n\n if (treeGetValue(node)) {\n const queue = repoBuildTransactionQueue(repo, node);\n assert(queue.length > 0, 'Sending zero length transaction queue');\n\n const allRun = queue.every(\n (transaction: Transaction) => transaction.status === TransactionStatus.RUN\n );\n\n // If they're all run (and not sent), we can send them. Else, we must wait.\n if (allRun) {\n repoSendTransactionQueue(repo, treeGetPath(node), queue);\n }\n } else if (treeHasChildren(node)) {\n treeForEachChild(node, childNode => {\n repoSendReadyTransactions(repo, childNode);\n });\n }\n}\n\n/**\n * Given a list of run transactions, send them to the server and then handle\n * the result (success or failure).\n *\n * @param path - The location of the queue.\n * @param queue - Queue of transactions under the specified location.\n */\nfunction repoSendTransactionQueue(\n repo: Repo,\n path: Path,\n queue: Transaction[]\n): void {\n // Mark transactions as sent and increment retry count!\n const setsToIgnore = queue.map(txn => {\n return txn.currentWriteId;\n });\n const latestState = repoGetLatestState(repo, path, setsToIgnore);\n let snapToSend = latestState;\n const latestHash = latestState.hash();\n for (let i = 0; i < queue.length; i++) {\n const txn = queue[i];\n assert(\n txn.status === TransactionStatus.RUN,\n 'tryToSendTransactionQueue_: items in queue should all be run.'\n );\n txn.status = TransactionStatus.SENT;\n txn.retryCount++;\n const relativePath = newRelativePath(path, txn.path);\n // If we've gotten to this point, the output snapshot must be defined.\n snapToSend = snapToSend.updateChild(\n relativePath /** @type {!Node} */,\n txn.currentOutputSnapshotRaw\n );\n }\n\n const dataToSend = snapToSend.val(true);\n const pathToSend = path;\n\n // Send the put.\n repo.server_.put(\n pathToSend.toString(),\n dataToSend,\n (status: string) => {\n repoLog(repo, 'transaction put response', {\n path: pathToSend.toString(),\n status\n });\n\n let events: Event[] = [];\n if (status === 'ok') {\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more\n // transactions or sets.\n const callbacks = [];\n for (let i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.COMPLETED;\n events = events.concat(\n syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId)\n );\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this\n // transaction is complete, it should be set\n callbacks.push(() =>\n queue[i].onComplete(\n null,\n true,\n queue[i].currentOutputSnapshotResolved\n )\n );\n }\n queue[i].unwatcher();\n }\n\n // Now remove the completed transactions.\n repoPruneCompletedTransactionsBelowNode(\n repo,\n treeSubTree(repo.transactionQueueTree_, path)\n );\n // There may be pending transactions that we can now send.\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n\n // Finally, trigger onComplete callbacks.\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n } else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (let i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n } else {\n queue[i].status = TransactionStatus.RUN;\n }\n }\n } else {\n warn(\n 'transaction at ' + pathToSend.toString() + ' failed: ' + status\n );\n for (let i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n queue[i].abortReason = status;\n }\n }\n\n repoRerunTransactions(repo, path);\n }\n },\n latestHash\n );\n}\n\n/**\n * Finds all transactions dependent on the data at changedPath and reruns them.\n *\n * Should be called any time cached data changes.\n *\n * Return the highest path that was affected by rerunning transactions. This\n * is the path at which events need to be raised for.\n *\n * @param changedPath - The path in mergedData that changed.\n * @returns The rootmost path that was affected by rerunning transactions.\n */\nfunction repoRerunTransactions(repo: Repo, changedPath: Path): Path {\n const rootMostTransactionNode = repoGetAncestorTransactionNode(\n repo,\n changedPath\n );\n const path = treeGetPath(rootMostTransactionNode);\n\n const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);\n repoRerunTransactionQueue(repo, queue, path);\n\n return path;\n}\n\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted\n * transactions and whatnot).\n *\n * @param queue - The queue of transactions to run.\n * @param path - The path the queue is for.\n */\nfunction repoRerunTransactionQueue(\n repo: Repo,\n queue: Transaction[],\n path: Path\n): void {\n if (queue.length === 0) {\n return; // Nothing to do!\n }\n\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more transactions or\n // sets.\n const callbacks = [];\n let events: Event[] = [];\n // Ignore all of the sets we're going to re-run.\n const txnsToRerun = queue.filter(q => {\n return q.status === TransactionStatus.RUN;\n });\n const setsToIgnore = txnsToRerun.map(q => {\n return q.currentWriteId;\n });\n for (let i = 0; i < queue.length; i++) {\n const transaction = queue[i];\n const relativePath = newRelativePath(path, transaction.path);\n let abortTransaction = false,\n abortReason;\n assert(\n relativePath !== null,\n 'rerunTransactionsUnderNode_: relativePath should not be null.'\n );\n\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n } else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n } else {\n // This code reruns a transaction\n const currentNode = repoGetLatestState(\n repo,\n transaction.path,\n setsToIgnore\n );\n transaction.currentInputSnapshot = currentNode;\n const newData = queue[i].update(currentNode.val());\n if (newData !== undefined) {\n validateFirebaseData(\n 'transaction failed: Data returned ',\n newData,\n transaction.path\n );\n let newDataNode = nodeFromJSON(newData);\n const hasExplicitPriority =\n typeof newData === 'object' &&\n newData != null &&\n contains(newData, '.priority');\n if (!hasExplicitPriority) {\n // Keep the old priority if there wasn't a priority explicitly specified.\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n }\n\n const oldWriteId = transaction.currentWriteId;\n const serverValues = repoGenerateServerValues(repo);\n const newNodeResolved = resolveDeferredValueSnapshot(\n newDataNode,\n currentNode,\n serverValues\n );\n\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = repoGetNextWriteId(repo);\n // Mutates setsToIgnore in place\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(\n syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n transaction.path,\n newNodeResolved,\n transaction.currentWriteId,\n transaction.applyLocally\n )\n );\n events = events.concat(\n syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true)\n );\n } else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n }\n }\n }\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n events = [];\n if (abortTransaction) {\n // Abort.\n queue[i].status = TransactionStatus.COMPLETED;\n\n // Removing a listener can trigger pruning which can muck with\n // mergedData/visibleData (as it prunes data). So defer the unwatcher\n // until we're done.\n (function (unwatcher) {\n setTimeout(unwatcher, Math.floor(0));\n })(queue[i].unwatcher);\n\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n callbacks.push(() =>\n queue[i].onComplete(null, false, queue[i].currentInputSnapshot)\n );\n } else {\n callbacks.push(() =>\n queue[i].onComplete(new Error(abortReason), false, null)\n );\n }\n }\n }\n }\n\n // Clean up completed transactions.\n repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);\n\n // Now fire callbacks, now that we're in a good, known state.\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n\n // Try to send the transaction result to the server.\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n}\n\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending\n * transaction on it, or just returns the node for the given path if there are\n * no pending transactions on any ancestor.\n *\n * @param path - The location to start at.\n * @returns The rootmost node with a transaction.\n */\nfunction repoGetAncestorTransactionNode(\n repo: Repo,\n path: Path\n): Tree {\n let front;\n\n // Start at the root and walk deeper into the tree towards path until we\n // find a node with pending transactions.\n let transactionNode = repo.transactionQueueTree_;\n front = pathGetFront(path);\n while (front !== null && treeGetValue(transactionNode) === undefined) {\n transactionNode = treeSubTree(transactionNode, front);\n path = pathPopFront(path);\n front = pathGetFront(path);\n }\n\n return transactionNode;\n}\n\n/**\n * Builds the queue of all transactions at or below the specified\n * transactionNode.\n *\n * @param transactionNode\n * @returns The generated queue.\n */\nfunction repoBuildTransactionQueue(\n repo: Repo,\n transactionNode: Tree\n): Transaction[] {\n // Walk any child transaction queues and aggregate them into a single queue.\n const transactionQueue: Transaction[] = [];\n repoAggregateTransactionQueuesForNode(\n repo,\n transactionNode,\n transactionQueue\n );\n\n // Sort them by the order the transactions were created.\n transactionQueue.sort((a, b) => a.order - b.order);\n\n return transactionQueue;\n}\n\nfunction repoAggregateTransactionQueuesForNode(\n repo: Repo,\n node: Tree,\n queue: Transaction[]\n): void {\n const nodeQueue = treeGetValue(node);\n if (nodeQueue) {\n for (let i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n\n treeForEachChild(node, child => {\n repoAggregateTransactionQueuesForNode(repo, child, queue);\n });\n}\n\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n */\nfunction repoPruneCompletedTransactionsBelowNode(\n repo: Repo,\n node: Tree\n): void {\n const queue = treeGetValue(node);\n if (queue) {\n let to = 0;\n for (let from = 0; from < queue.length; from++) {\n if (queue[from].status !== TransactionStatus.COMPLETED) {\n queue[to] = queue[from];\n to++;\n }\n }\n queue.length = to;\n treeSetValue(node, queue.length > 0 ? queue : undefined);\n }\n\n treeForEachChild(node, childNode => {\n repoPruneCompletedTransactionsBelowNode(repo, childNode);\n });\n}\n\n/**\n * Aborts all transactions on ancestors or descendants of the specified path.\n * Called when doing a set() or update() since we consider them incompatible\n * with transactions.\n *\n * @param path - Path for which we want to abort related transactions.\n */\nfunction repoAbortTransactions(repo: Repo, path: Path): Path {\n const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));\n\n const transactionNode = treeSubTree(repo.transactionQueueTree_, path);\n\n treeForEachAncestor(transactionNode, (node: Tree) => {\n repoAbortTransactionsOnNode(repo, node);\n });\n\n repoAbortTransactionsOnNode(repo, transactionNode);\n\n treeForEachDescendant(transactionNode, (node: Tree) => {\n repoAbortTransactionsOnNode(repo, node);\n });\n\n return affectedPath;\n}\n\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param node - Node to abort transactions for.\n */\nfunction repoAbortTransactionsOnNode(\n repo: Repo,\n node: Tree\n): void {\n const queue = treeGetValue(node);\n if (queue) {\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more transactions\n // or sets.\n const callbacks = [];\n\n // Go through queue. Any already-sent transactions must be marked for\n // abort, while the unsent ones can be immediately aborted and removed.\n let events: Event[] = [];\n let lastSent = -1;\n for (let i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n // Already marked. No action needed.\n } else if (queue[i].status === TransactionStatus.SENT) {\n assert(\n lastSent === i - 1,\n 'All SENT items should be at beginning of queue.'\n );\n lastSent = i;\n // Mark transaction for abort when it comes back.\n queue[i].status = TransactionStatus.SENT_NEEDS_ABORT;\n queue[i].abortReason = 'set';\n } else {\n assert(\n queue[i].status === TransactionStatus.RUN,\n 'Unexpected transaction status in abort'\n );\n // We can abort it immediately.\n queue[i].unwatcher();\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n queue[i].currentWriteId,\n true\n )\n );\n if (queue[i].onComplete) {\n callbacks.push(\n queue[i].onComplete.bind(null, new Error('set'), false, null)\n );\n }\n }\n }\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n treeSetValue(node, undefined);\n } else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n\n // Now fire the callbacks.\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n treeGetPath(node),\n events\n );\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../../RepoInfo';\nimport { Path } from '../Path';\nimport { warnIfPageIsSecure, warn, fatal } from '../util';\n\nfunction decodePath(pathString: string): string {\n let pathStringDecoded = '';\n const pieces = pathString.split('/');\n for (let i = 0; i < pieces.length; i++) {\n if (pieces[i].length > 0) {\n let piece = pieces[i];\n try {\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\n } catch (e) {}\n pathStringDecoded += '/' + piece;\n }\n }\n return pathStringDecoded;\n}\n\n/**\n * @returns key value hash\n */\nfunction decodeQuery(queryString: string): { [key: string]: string } {\n const results = {};\n if (queryString.charAt(0) === '?') {\n queryString = queryString.substring(1);\n }\n for (const segment of queryString.split('&')) {\n if (segment.length === 0) {\n continue;\n }\n const kv = segment.split('=');\n if (kv.length === 2) {\n results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\n } else {\n warn(`Invalid query segment '${segment}' in query '${queryString}'`);\n }\n }\n return results;\n}\n\nexport const parseRepoInfo = function (\n dataURL: string,\n nodeAdmin: boolean\n): { repoInfo: RepoInfo; path: Path } {\n const parsedUrl = parseDatabaseURL(dataURL),\n namespace = parsedUrl.namespace;\n\n if (parsedUrl.domain === 'firebase.com') {\n fatal(\n parsedUrl.host +\n ' is no longer supported. ' +\n 'Please use .firebaseio.com instead'\n );\n }\n\n // Catch common error of uninitialized namespace value.\n if (\n (!namespace || namespace === 'undefined') &&\n parsedUrl.domain !== 'localhost'\n ) {\n fatal(\n 'Cannot parse Firebase url. Please use https://.firebaseio.com'\n );\n }\n\n if (!parsedUrl.secure) {\n warnIfPageIsSecure();\n }\n\n const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\n\n return {\n repoInfo: new RepoInfo(\n parsedUrl.host,\n parsedUrl.secure,\n namespace,\n webSocketOnly,\n nodeAdmin,\n /*persistenceKey=*/ '',\n /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain\n ),\n path: new Path(parsedUrl.pathString)\n };\n};\n\nexport const parseDatabaseURL = function (dataURL: string): {\n host: string;\n port: number;\n domain: string;\n subdomain: string;\n secure: boolean;\n scheme: string;\n pathString: string;\n namespace: string;\n} {\n // Default to empty strings in the event of a malformed string.\n let host = '',\n domain = '',\n subdomain = '',\n pathString = '',\n namespace = '';\n\n // Always default to SSL, unless otherwise specified.\n let secure = true,\n scheme = 'https',\n port = 443;\n\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\n if (typeof dataURL === 'string') {\n // Parse scheme.\n let colonInd = dataURL.indexOf('//');\n if (colonInd >= 0) {\n scheme = dataURL.substring(0, colonInd - 1);\n dataURL = dataURL.substring(colonInd + 2);\n }\n\n // Parse host, path, and query string.\n let slashInd = dataURL.indexOf('/');\n if (slashInd === -1) {\n slashInd = dataURL.length;\n }\n let questionMarkInd = dataURL.indexOf('?');\n if (questionMarkInd === -1) {\n questionMarkInd = dataURL.length;\n }\n host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));\n if (slashInd < questionMarkInd) {\n // For pathString, questionMarkInd will always come after slashInd\n pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));\n }\n const queryParams = decodeQuery(\n dataURL.substring(Math.min(dataURL.length, questionMarkInd))\n );\n\n // If we have a port, use scheme for determining if it's secure.\n colonInd = host.indexOf(':');\n if (colonInd >= 0) {\n secure = scheme === 'https' || scheme === 'wss';\n port = parseInt(host.substring(colonInd + 1), 10);\n } else {\n colonInd = host.length;\n }\n\n const hostWithoutPort = host.slice(0, colonInd);\n if (hostWithoutPort.toLowerCase() === 'localhost') {\n domain = 'localhost';\n } else if (hostWithoutPort.split('.').length <= 2) {\n domain = hostWithoutPort;\n } else {\n // Interpret the subdomain of a 3 or more component URL as the namespace name.\n const dotInd = host.indexOf('.');\n subdomain = host.substring(0, dotInd).toLowerCase();\n domain = host.substring(dotInd + 1);\n // Normalize namespaces to lowercase to share storage / connection.\n namespace = subdomain;\n }\n // Always treat the value of the `ns` as the namespace name if it is present.\n if ('ns' in queryParams) {\n namespace = queryParams['ns'];\n }\n }\n\n return {\n host,\n port,\n domain,\n subdomain,\n secure,\n scheme,\n pathString,\n namespace\n };\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport {\n tryParseInt,\n MAX_NAME,\n MIN_NAME,\n INTEGER_32_MIN,\n INTEGER_32_MAX\n} from '../util/util';\n\n// Modeled after base64 web-safe chars, but ordered by ASCII.\nconst PUSH_CHARS =\n '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n\nconst MIN_PUSH_CHAR = '-';\n\nconst MAX_PUSH_CHAR = 'z';\n\nconst MAX_KEY_LEN = 786;\n\n/**\n * Fancy ID generator that creates 20-character string identifiers with the\n * following properties:\n *\n * 1. They're based on timestamp so that they sort *after* any existing ids.\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\n * collide with other clients' IDs.\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\n * that will sort properly).\n * 4. They're monotonically increasing. Even if you generate more than one in\n * the same timestamp, the latter ones will sort after the former ones. We do\n * this by using the previous random bits but \"incrementing\" them by 1 (only\n * in the case of a timestamp collision).\n */\nexport const nextPushId = (function () {\n // Timestamp of last push, used to prevent local collisions if you push twice\n // in one ms.\n let lastPushTime = 0;\n\n // We generate 72-bits of randomness which get turned into 12 characters and\n // appended to the timestamp to prevent collisions with other clients. We\n // store the last characters we generated because in the event of a collision,\n // we'll use those same characters except \"incremented\" by one.\n const lastRandChars: number[] = [];\n\n return function (now: number) {\n const duplicateTime = now === lastPushTime;\n lastPushTime = now;\n\n let i;\n const timeStampChars = new Array(8);\n for (i = 7; i >= 0; i--) {\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\n // NOTE: Can't use << here because javascript will convert to int and lose\n // the upper bits.\n now = Math.floor(now / 64);\n }\n assert(now === 0, 'Cannot push at time == 0');\n\n let id = timeStampChars.join('');\n\n if (!duplicateTime) {\n for (i = 0; i < 12; i++) {\n lastRandChars[i] = Math.floor(Math.random() * 64);\n }\n } else {\n // If the timestamp hasn't changed since last push, use the same random\n // number, except incremented by 1.\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\n lastRandChars[i] = 0;\n }\n lastRandChars[i]++;\n }\n for (i = 0; i < 12; i++) {\n id += PUSH_CHARS.charAt(lastRandChars[i]);\n }\n assert(id.length === 20, 'nextPushId: Length should be 20.');\n\n return id;\n };\n})();\n\nexport const successor = function (key: string) {\n if (key === '' + INTEGER_32_MAX) {\n // See https://firebase.google.com/docs/database/web/lists-of-data#data-order\n return MIN_PUSH_CHAR;\n }\n const keyAsInt: number = tryParseInt(key);\n if (keyAsInt != null) {\n return '' + (keyAsInt + 1);\n }\n const next = new Array(key.length);\n\n for (let i = 0; i < next.length; i++) {\n next[i] = key.charAt(i);\n }\n\n if (next.length < MAX_KEY_LEN) {\n next.push(MIN_PUSH_CHAR);\n return next.join('');\n }\n\n let i = next.length - 1;\n\n while (i >= 0 && next[i] === MAX_PUSH_CHAR) {\n i--;\n }\n\n // `successor` was called on the largest possible key, so return the\n // MAX_NAME, which sorts larger than all keys.\n if (i === -1) {\n return MAX_NAME;\n }\n\n const source = next[i];\n const sourcePlusOne = PUSH_CHARS.charAt(PUSH_CHARS.indexOf(source) + 1);\n next[i] = sourcePlusOne;\n\n return next.slice(0, i + 1).join('');\n};\n\n// `key` is assumed to be non-empty.\nexport const predecessor = function (key: string) {\n if (key === '' + INTEGER_32_MIN) {\n return MIN_NAME;\n }\n const keyAsInt: number = tryParseInt(key);\n if (keyAsInt != null) {\n return '' + (keyAsInt - 1);\n }\n const next = new Array(key.length);\n for (let i = 0; i < next.length; i++) {\n next[i] = key.charAt(i);\n }\n // If `key` ends in `MIN_PUSH_CHAR`, the largest key lexicographically\n // smaller than `key`, is `key[0:key.length - 1]`. The next key smaller\n // than that, `predecessor(predecessor(key))`, is\n //\n // `key[0:key.length - 2] + (key[key.length - 1] - 1) + \\\n // { MAX_PUSH_CHAR repeated MAX_KEY_LEN - (key.length - 1) times }\n //\n // analogous to increment/decrement for base-10 integers.\n //\n // This works because lexicographic comparison works character-by-character,\n // using length as a tie-breaker if one key is a prefix of the other.\n if (next[next.length - 1] === MIN_PUSH_CHAR) {\n if (next.length === 1) {\n // See https://firebase.google.com/docs/database/web/lists-of-data#orderbykey\n return '' + INTEGER_32_MAX;\n }\n delete next[next.length - 1];\n return next.join('');\n }\n // Replace the last character with it's immediate predecessor, and\n // fill the suffix of the key with MAX_PUSH_CHAR. This is the\n // lexicographically largest possible key smaller than `key`.\n next[next.length - 1] = PUSH_CHARS.charAt(\n PUSH_CHARS.indexOf(next[next.length - 1]) - 1\n );\n return next.join('') + MAX_PUSH_CHAR.repeat(MAX_KEY_LEN - next.length);\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { stringify } from '@firebase/util';\n\nimport { DataSnapshot as ExpDataSnapshot } from '../../api/Reference_impl';\nimport { Path } from '../util/Path';\n\nimport { EventRegistration } from './EventRegistration';\n\n/**\n * Encapsulates the data needed to raise an event\n * @interface\n */\nexport interface Event {\n getPath(): Path;\n\n getEventType(): string;\n\n getEventRunner(): () => void;\n\n toString(): string;\n}\n\n/**\n * One of the following strings: \"value\", \"child_added\", \"child_changed\",\n * \"child_removed\", or \"child_moved.\"\n */\nexport type EventType =\n | 'value'\n | 'child_added'\n | 'child_changed'\n | 'child_moved'\n | 'child_removed';\n\n/**\n * Encapsulates the data needed to raise an event\n */\nexport class DataEvent implements Event {\n /**\n * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed\n * @param eventRegistration - The function to call to with the event data. User provided\n * @param snapshot - The data backing the event\n * @param prevName - Optional, the name of the previous child for child_* events.\n */\n constructor(\n public eventType: EventType,\n public eventRegistration: EventRegistration,\n public snapshot: ExpDataSnapshot,\n public prevName?: string | null\n ) {}\n getPath(): Path {\n const ref = this.snapshot.ref;\n if (this.eventType === 'value') {\n return ref._path;\n } else {\n return ref.parent._path;\n }\n }\n getEventType(): string {\n return this.eventType;\n }\n getEventRunner(): () => void {\n return this.eventRegistration.getEventRunner(this);\n }\n toString(): string {\n return (\n this.getPath().toString() +\n ':' +\n this.eventType +\n ':' +\n stringify(this.snapshot.exportVal())\n );\n }\n}\n\nexport class CancelEvent implements Event {\n constructor(\n public eventRegistration: EventRegistration,\n public error: Error,\n public path: Path\n ) {}\n getPath(): Path {\n return this.path;\n }\n getEventType(): string {\n return 'cancel';\n }\n getEventRunner(): () => void {\n return this.eventRegistration.getEventRunner(this);\n }\n toString(): string {\n return this.path.toString() + ':cancel';\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { DataSnapshot } from '../../api/Reference_impl';\nimport { Repo } from '../Repo';\nimport { Path } from '../util/Path';\n\nimport { Change } from './Change';\nimport { CancelEvent, Event } from './Event';\nimport { QueryParams } from './QueryParams';\n\n/**\n * A user callback. Callbacks issues from the Legacy SDK maintain references\n * to the original user-issued callbacks, which allows equality\n * comparison by reference even though this callbacks are wrapped before\n * they can be passed to the firebase@exp SDK.\n *\n * @internal\n */\nexport interface UserCallback {\n (dataSnapshot: DataSnapshot, previousChildName?: string | null): unknown;\n userCallback?: unknown;\n context?: object | null;\n}\n\n/**\n * A wrapper class that converts events from the database@exp SDK to the legacy\n * Database SDK. Events are not converted directly as event registration relies\n * on reference comparison of the original user callback (see `matches()`) and\n * relies on equality of the legacy SDK's `context` object.\n */\nexport class CallbackContext {\n constructor(\n private readonly snapshotCallback: UserCallback,\n private readonly cancelCallback?: (error: Error) => unknown\n ) {}\n\n onValue(\n expDataSnapshot: DataSnapshot,\n previousChildName?: string | null\n ): void {\n this.snapshotCallback.call(null, expDataSnapshot, previousChildName);\n }\n\n onCancel(error: Error): void {\n assert(\n this.hasCancelCallback,\n 'Raising a cancel event on a listener with no cancel callback'\n );\n return this.cancelCallback.call(null, error);\n }\n\n get hasCancelCallback(): boolean {\n return !!this.cancelCallback;\n }\n\n matches(other: CallbackContext): boolean {\n return (\n this.snapshotCallback === other.snapshotCallback ||\n (this.snapshotCallback.userCallback !== undefined &&\n this.snapshotCallback.userCallback ===\n other.snapshotCallback.userCallback &&\n this.snapshotCallback.context === other.snapshotCallback.context)\n );\n }\n}\n\nexport interface QueryContext {\n readonly _queryIdentifier: string;\n readonly _queryObject: object;\n readonly _repo: Repo;\n readonly _path: Path;\n readonly _queryParams: QueryParams;\n}\n\n/**\n * An EventRegistration is basically an event type ('value', 'child_added', etc.) and a callback\n * to be notified of that type of event.\n *\n * That said, it can also contain a cancel callback to be notified if the event is canceled. And\n * currently, this code is organized around the idea that you would register multiple child_ callbacks\n * together, as a single EventRegistration. Though currently we don't do that.\n */\nexport interface EventRegistration {\n /**\n * True if this container has a callback to trigger for this event type\n */\n respondsTo(eventType: string): boolean;\n\n createEvent(change: Change, query: QueryContext): Event;\n\n /**\n * Given event data, return a function to trigger the user's callback\n */\n getEventRunner(eventData: Event): () => void;\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null;\n\n matches(other: EventRegistration): boolean;\n\n /**\n * False basically means this is a \"dummy\" callback container being used as a sentinel\n * to remove all callback containers of a particular type. (e.g. if the user does\n * ref.off('value') without specifying a specific callback).\n *\n * (TODO: Rework this, since it's hacky)\n *\n */\n hasAnyCallback(): boolean;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from '@firebase/util';\n\nimport {\n Repo,\n repoOnDisconnectCancel,\n repoOnDisconnectSet,\n repoOnDisconnectSetWithPriority,\n repoOnDisconnectUpdate\n} from '../core/Repo';\nimport { Path } from '../core/util/Path';\nimport {\n validateFirebaseDataArg,\n validateFirebaseMergeDataArg,\n validatePriority,\n validateWritablePath\n} from '../core/util/validation';\n\n/**\n * The `onDisconnect` class allows you to write or clear data when your client\n * disconnects from the Database server. These updates occur whether your\n * client disconnects cleanly or not, so you can rely on them to clean up data\n * even if a connection is dropped or a client crashes.\n *\n * The `onDisconnect` class is most commonly used to manage presence in\n * applications where it is useful to detect how many clients are connected and\n * when other clients disconnect. See\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information.\n *\n * To avoid problems when a connection is dropped before the requests can be\n * transferred to the Database server, these functions should be called before\n * writing any data.\n *\n * Note that `onDisconnect` operations are only triggered once. If you want an\n * operation to occur each time a disconnect occurs, you'll need to re-establish\n * the `onDisconnect` operations each time you reconnect.\n */\nexport class OnDisconnect {\n /** @hideconstructor */\n constructor(private _repo: Repo, private _path: Path) {}\n\n /**\n * Cancels all previously queued `onDisconnect()` set or update events for this\n * location and all children.\n *\n * If a write has been queued for this location via a `set()` or `update()` at a\n * parent location, the write at this location will be canceled, though writes\n * to sibling locations will still occur.\n *\n * @returns Resolves when synchronization to the server is complete.\n */\n cancel(): Promise {\n const deferred = new Deferred();\n repoOnDisconnectCancel(\n this._repo,\n this._path,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is deleted when the client is disconnected\n * (due to closing the browser, navigating to a new page, or network issues).\n *\n * @returns Resolves when synchronization to the server is complete.\n */\n remove(): Promise {\n validateWritablePath('OnDisconnect.remove', this._path);\n const deferred = new Deferred();\n repoOnDisconnectSet(\n this._repo,\n this._path,\n null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is set to the specified value when the\n * client is disconnected (due to closing the browser, navigating to a new page,\n * or network issues).\n *\n * `set()` is especially useful for implementing \"presence\" systems, where a\n * value should be changed or cleared when a user disconnects so that they\n * appear \"offline\" to other users. See\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information.\n *\n * Note that `onDisconnect` operations are only triggered once. If you want an\n * operation to occur each time a disconnect occurs, you'll need to re-establish\n * the `onDisconnect` operations each time.\n *\n * @param value - The value to be written to this location on disconnect (can\n * be an object, array, string, number, boolean, or null).\n * @returns Resolves when synchronization to the Database is complete.\n */\n set(value: unknown): Promise {\n validateWritablePath('OnDisconnect.set', this._path);\n validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);\n const deferred = new Deferred();\n repoOnDisconnectSet(\n this._repo,\n this._path,\n value,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is set to the specified value and priority\n * when the client is disconnected (due to closing the browser, navigating to a\n * new page, or network issues).\n *\n * @param value - The value to be written to this location on disconnect (can\n * be an object, array, string, number, boolean, or null).\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when synchronization to the Database is complete.\n */\n setWithPriority(\n value: unknown,\n priority: number | string | null\n ): Promise {\n validateWritablePath('OnDisconnect.setWithPriority', this._path);\n validateFirebaseDataArg(\n 'OnDisconnect.setWithPriority',\n value,\n this._path,\n false\n );\n validatePriority('OnDisconnect.setWithPriority', priority, false);\n\n const deferred = new Deferred();\n repoOnDisconnectSetWithPriority(\n this._repo,\n this._path,\n value,\n priority,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Writes multiple values at this location when the client is disconnected (due\n * to closing the browser, navigating to a new page, or network issues).\n *\n * The `values` argument contains multiple property-value pairs that will be\n * written to the Database together. Each child property can either be a simple\n * property (for example, \"name\") or a relative path (for example, \"name/first\")\n * from the current location to the data to update.\n *\n * As opposed to the `set()` method, `update()` can be use to selectively update\n * only the referenced properties at the current location (instead of replacing\n * all the child properties at the current location).\n *\n * @param values - Object containing multiple values.\n * @returns Resolves when synchronization to the Database is complete.\n */\n update(values: object): Promise {\n validateWritablePath('OnDisconnect.update', this._path);\n validateFirebaseMergeDataArg(\n 'OnDisconnect.update',\n values,\n this._path,\n false\n );\n const deferred = new Deferred();\n repoOnDisconnectUpdate(\n this._repo,\n this._path,\n values as Record,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, getModularInstance, Deferred } from '@firebase/util';\n\nimport {\n Repo,\n repoAddEventCallbackForQuery,\n repoGetValue,\n repoRemoveEventCallbackForQuery,\n repoServerTime,\n repoSetWithPriority,\n repoUpdate\n} from '../core/Repo';\nimport { ChildrenNode } from '../core/snap/ChildrenNode';\nimport { Index } from '../core/snap/indexes/Index';\nimport { KEY_INDEX } from '../core/snap/indexes/KeyIndex';\nimport { PathIndex } from '../core/snap/indexes/PathIndex';\nimport { PRIORITY_INDEX } from '../core/snap/indexes/PriorityIndex';\nimport { VALUE_INDEX } from '../core/snap/indexes/ValueIndex';\nimport { Node } from '../core/snap/Node';\nimport { syncPointSetReferenceConstructor } from '../core/SyncPoint';\nimport { syncTreeSetReferenceConstructor } from '../core/SyncTree';\nimport { parseRepoInfo } from '../core/util/libs/parser';\nimport { nextPushId } from '../core/util/NextPushId';\nimport {\n Path,\n pathEquals,\n pathGetBack,\n pathGetFront,\n pathChild,\n pathParent,\n pathToUrlEncodedString,\n pathIsEmpty\n} from '../core/util/Path';\nimport {\n fatal,\n MAX_NAME,\n MIN_NAME,\n ObjectToUniqueKey\n} from '../core/util/util';\nimport {\n isValidPriority,\n validateFirebaseDataArg,\n validateFirebaseMergeDataArg,\n validateKey,\n validatePathString,\n validatePriority,\n validateRootPathString,\n validateUrl,\n validateWritablePath\n} from '../core/util/validation';\nimport { Change } from '../core/view/Change';\nimport { CancelEvent, DataEvent, EventType } from '../core/view/Event';\nimport {\n CallbackContext,\n EventRegistration,\n QueryContext,\n UserCallback\n} from '../core/view/EventRegistration';\nimport {\n QueryParams,\n queryParamsEndAt,\n queryParamsEndBefore,\n queryParamsGetQueryObject,\n queryParamsLimitToFirst,\n queryParamsLimitToLast,\n queryParamsOrderBy,\n queryParamsStartAfter,\n queryParamsStartAt\n} from '../core/view/QueryParams';\n\nimport { Database } from './Database';\nimport { OnDisconnect } from './OnDisconnect';\nimport {\n ListenOptions,\n Query as Query,\n DatabaseReference,\n Unsubscribe,\n ThenableReference\n} from './Reference';\n\n/**\n * @internal\n */\nexport class QueryImpl implements Query, QueryContext {\n /**\n * @hideconstructor\n */\n constructor(\n readonly _repo: Repo,\n readonly _path: Path,\n readonly _queryParams: QueryParams,\n readonly _orderByCalled: boolean\n ) {}\n\n get key(): string | null {\n if (pathIsEmpty(this._path)) {\n return null;\n } else {\n return pathGetBack(this._path);\n }\n }\n\n get ref(): DatabaseReference {\n return new ReferenceImpl(this._repo, this._path);\n }\n\n get _queryIdentifier(): string {\n const obj = queryParamsGetQueryObject(this._queryParams);\n const id = ObjectToUniqueKey(obj);\n return id === '{}' ? 'default' : id;\n }\n\n /**\n * An object representation of the query parameters used by this Query.\n */\n get _queryObject(): object {\n return queryParamsGetQueryObject(this._queryParams);\n }\n\n isEqual(other: QueryImpl | null): boolean {\n other = getModularInstance(other);\n if (!(other instanceof QueryImpl)) {\n return false;\n }\n\n const sameRepo = this._repo === other._repo;\n const samePath = pathEquals(this._path, other._path);\n const sameQueryIdentifier =\n this._queryIdentifier === other._queryIdentifier;\n\n return sameRepo && samePath && sameQueryIdentifier;\n }\n\n toJSON(): string {\n return this.toString();\n }\n\n toString(): string {\n return this._repo.toString() + pathToUrlEncodedString(this._path);\n }\n}\n\n/**\n * Validates that no other order by call has been made\n */\nfunction validateNoPreviousOrderByCall(query: QueryImpl, fnName: string) {\n if (query._orderByCalled === true) {\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\n }\n}\n\n/**\n * Validates start/end values for queries.\n */\nfunction validateQueryEndpoints(params: QueryParams) {\n let startNode = null;\n let endNode = null;\n if (params.hasStart()) {\n startNode = params.getIndexStartValue();\n }\n if (params.hasEnd()) {\n endNode = params.getIndexEndValue();\n }\n\n if (params.getIndex() === KEY_INDEX) {\n const tooManyArgsError =\n 'Query: When ordering by key, you may only pass one argument to ' +\n 'startAt(), endAt(), or equalTo().';\n const wrongArgTypeError =\n 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +\n 'endAt(), endBefore(), or equalTo() must be a string.';\n if (params.hasStart()) {\n const startName = params.getIndexStartName();\n if (startName !== MIN_NAME) {\n throw new Error(tooManyArgsError);\n } else if (typeof startNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n if (params.hasEnd()) {\n const endName = params.getIndexEndName();\n if (endName !== MAX_NAME) {\n throw new Error(tooManyArgsError);\n } else if (typeof endNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n } else if (params.getIndex() === PRIORITY_INDEX) {\n if (\n (startNode != null && !isValidPriority(startNode)) ||\n (endNode != null && !isValidPriority(endNode))\n ) {\n throw new Error(\n 'Query: When ordering by priority, the first argument passed to startAt(), ' +\n 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +\n '(null, a number, or a string).'\n );\n }\n } else {\n assert(\n params.getIndex() instanceof PathIndex ||\n params.getIndex() === VALUE_INDEX,\n 'unknown index type.'\n );\n if (\n (startNode != null && typeof startNode === 'object') ||\n (endNode != null && typeof endNode === 'object')\n ) {\n throw new Error(\n 'Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +\n 'equalTo() cannot be an object.'\n );\n }\n }\n}\n\n/**\n * Validates that limit* has been called with the correct combination of parameters\n */\nfunction validateLimit(params: QueryParams) {\n if (\n params.hasStart() &&\n params.hasEnd() &&\n params.hasLimit() &&\n !params.hasAnchoredLimit()\n ) {\n throw new Error(\n \"Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use \" +\n 'limitToFirst() or limitToLast() instead.'\n );\n }\n}\n/**\n * @internal\n */\nexport class ReferenceImpl extends QueryImpl implements DatabaseReference {\n /** @hideconstructor */\n constructor(repo: Repo, path: Path) {\n super(repo, path, new QueryParams(), false);\n }\n\n get parent(): ReferenceImpl | null {\n const parentPath = pathParent(this._path);\n return parentPath === null\n ? null\n : new ReferenceImpl(this._repo, parentPath);\n }\n\n get root(): ReferenceImpl {\n let ref: ReferenceImpl = this;\n while (ref.parent !== null) {\n ref = ref.parent;\n }\n return ref;\n }\n}\n\n/**\n * A `DataSnapshot` contains data from a Database location.\n *\n * Any time you read data from the Database, you receive the data as a\n * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach\n * with `on()` or `once()`. You can extract the contents of the snapshot as a\n * JavaScript object by calling the `val()` method. Alternatively, you can\n * traverse into the snapshot by calling `child()` to return child snapshots\n * (which you could then call `val()` on).\n *\n * A `DataSnapshot` is an efficiently generated, immutable copy of the data at\n * a Database location. It cannot be modified and will never change (to modify\n * data, you always call the `set()` method on a `Reference` directly).\n */\nexport class DataSnapshot {\n /**\n * @param _node - A SnapshotNode to wrap.\n * @param ref - The location this snapshot came from.\n * @param _index - The iteration order for this snapshot\n * @hideconstructor\n */\n constructor(\n readonly _node: Node,\n /**\n * The location of this DataSnapshot.\n */\n readonly ref: DatabaseReference,\n readonly _index: Index\n ) {}\n\n /**\n * Gets the priority value of the data in this `DataSnapshot`.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}\n * ).\n */\n get priority(): string | number | null {\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\n return this._node.getPriority().val() as string | number | null;\n }\n\n /**\n * The key (last part of the path) of the location of this `DataSnapshot`.\n *\n * The last token in a Database location is considered its key. For example,\n * \"ada\" is the key for the /users/ada/ node. Accessing the key on any\n * `DataSnapshot` will return the key for the location that generated it.\n * However, accessing the key on the root URL of a Database will return\n * `null`.\n */\n get key(): string | null {\n return this.ref.key;\n }\n\n /** Returns the number of child properties of this `DataSnapshot`. */\n get size(): number {\n return this._node.numChildren();\n }\n\n /**\n * Gets another `DataSnapshot` for the location at the specified relative path.\n *\n * Passing a relative path to the `child()` method of a DataSnapshot returns\n * another `DataSnapshot` for the location at the specified relative path. The\n * relative path can either be a simple child name (for example, \"ada\") or a\n * deeper, slash-separated path (for example, \"ada/name/first\"). If the child\n * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`\n * whose value is `null`) is returned.\n *\n * @param path - A relative path to the location of child data.\n */\n child(path: string): DataSnapshot {\n const childPath = new Path(path);\n const childRef = child(this.ref, path);\n return new DataSnapshot(\n this._node.getChild(childPath),\n childRef,\n PRIORITY_INDEX\n );\n }\n /**\n * Returns true if this `DataSnapshot` contains any data. It is slightly more\n * efficient than using `snapshot.val() !== null`.\n */\n exists(): boolean {\n return !this._node.isEmpty();\n }\n\n /**\n * Exports the entire contents of the DataSnapshot as a JavaScript object.\n *\n * The `exportVal()` method is similar to `val()`, except priority information\n * is included (if available), making it suitable for backing up your data.\n *\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\n * Array, string, number, boolean, or `null`).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n exportVal(): any {\n return this._node.val(true);\n }\n\n /**\n * Enumerates the top-level children in the `IteratedDataSnapshot`.\n *\n * Because of the way JavaScript objects work, the ordering of data in the\n * JavaScript object returned by `val()` is not guaranteed to match the\n * ordering on the server nor the ordering of `onChildAdded()` events. That is\n * where `forEach()` comes in handy. It guarantees the children of a\n * `DataSnapshot` will be iterated in their query order.\n *\n * If no explicit `orderBy*()` method is used, results are returned\n * ordered by key (unless priorities are used, in which case, results are\n * returned by priority).\n *\n * @param action - A function that will be called for each child DataSnapshot.\n * The callback can return true to cancel further enumeration.\n * @returns true if enumeration was canceled due to your callback returning\n * true.\n */\n forEach(action: (child: IteratedDataSnapshot) => boolean | void): boolean {\n if (this._node.isLeafNode()) {\n return false;\n }\n\n const childrenNode = this._node as ChildrenNode;\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\n return !!childrenNode.forEachChild(this._index, (key, node) => {\n return action(\n new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX)\n );\n });\n }\n\n /**\n * Returns true if the specified child path has (non-null) data.\n *\n * @param path - A relative path to the location of a potential child.\n * @returns `true` if data exists at the specified child path; else\n * `false`.\n */\n hasChild(path: string): boolean {\n const childPath = new Path(path);\n return !this._node.getChild(childPath).isEmpty();\n }\n\n /**\n * Returns whether or not the `DataSnapshot` has any non-`null` child\n * properties.\n *\n * You can use `hasChildren()` to determine if a `DataSnapshot` has any\n * children. If it does, you can enumerate them using `forEach()`. If it\n * doesn't, then either this snapshot contains a primitive value (which can be\n * retrieved with `val()`) or it is empty (in which case, `val()` will return\n * `null`).\n *\n * @returns true if this snapshot has any children; else false.\n */\n hasChildren(): boolean {\n if (this._node.isLeafNode()) {\n return false;\n } else {\n return !this._node.isEmpty();\n }\n }\n\n /**\n * Returns a JSON-serializable representation of this object.\n */\n toJSON(): object | null {\n return this.exportVal();\n }\n\n /**\n * Extracts a JavaScript value from a `DataSnapshot`.\n *\n * Depending on the data in a `DataSnapshot`, the `val()` method may return a\n * scalar type (string, number, or boolean), an array, or an object. It may\n * also return null, indicating that the `DataSnapshot` is empty (contains no\n * data).\n *\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\n * Array, string, number, boolean, or `null`).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n val(): any {\n return this._node.val();\n }\n}\n\n/**\n * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined.\n */\nexport interface IteratedDataSnapshot extends DataSnapshot {\n key: string; // key of the location of this snapshot.\n}\n\n/**\n *\n * Returns a `Reference` representing the location in the Database\n * corresponding to the provided path. If no path is provided, the `Reference`\n * will point to the root of the Database.\n *\n * @param db - The database instance to obtain a reference for.\n * @param path - Optional path representing the location the returned\n * `Reference` will point. If not provided, the returned `Reference` will\n * point to the root of the Database.\n * @returns If a path is provided, a `Reference`\n * pointing to the provided path. Otherwise, a `Reference` pointing to the\n * root of the Database.\n */\nexport function ref(db: Database, path?: string): DatabaseReference {\n db = getModularInstance(db);\n db._checkNotDeleted('ref');\n return path !== undefined ? child(db._root, path) : db._root;\n}\n\n/**\n * Returns a `Reference` representing the location in the Database\n * corresponding to the provided Firebase URL.\n *\n * An exception is thrown if the URL is not a valid Firebase Database URL or it\n * has a different domain than the current `Database` instance.\n *\n * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored\n * and are not applied to the returned `Reference`.\n *\n * @param db - The database instance to obtain a reference for.\n * @param url - The Firebase URL at which the returned `Reference` will\n * point.\n * @returns A `Reference` pointing to the provided\n * Firebase URL.\n */\nexport function refFromURL(db: Database, url: string): DatabaseReference {\n db = getModularInstance(db);\n db._checkNotDeleted('refFromURL');\n const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\n validateUrl('refFromURL', parsedURL);\n\n const repoInfo = parsedURL.repoInfo;\n if (\n !db._repo.repoInfo_.isCustomHost() &&\n repoInfo.host !== db._repo.repoInfo_.host\n ) {\n fatal(\n 'refFromURL' +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n db._repo.repoInfo_.host +\n ')'\n );\n }\n\n return ref(db, parsedURL.path.toString());\n}\n/**\n * Gets a `Reference` for the location at the specified relative path.\n *\n * The relative path can either be a simple child name (for example, \"ada\") or\n * a deeper slash-separated path (for example, \"ada/name/first\").\n *\n * @param parent - The parent location.\n * @param path - A relative path from this location to the desired child\n * location.\n * @returns The specified child location.\n */\nexport function child(\n parent: DatabaseReference,\n path: string\n): DatabaseReference {\n parent = getModularInstance(parent);\n if (pathGetFront(parent._path) === null) {\n validateRootPathString('child', 'path', path, false);\n } else {\n validatePathString('child', 'path', path, false);\n }\n return new ReferenceImpl(parent._repo, pathChild(parent._path, path));\n}\n\n/**\n * Returns an `OnDisconnect` object - see\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information on how to use it.\n *\n * @param ref - The reference to add OnDisconnect triggers for.\n */\nexport function onDisconnect(ref: DatabaseReference): OnDisconnect {\n ref = getModularInstance(ref) as ReferenceImpl;\n return new OnDisconnect(ref._repo, ref._path);\n}\n\nexport interface ThenableReferenceImpl\n extends ReferenceImpl,\n Pick, 'then' | 'catch'> {\n key: string;\n parent: ReferenceImpl;\n}\n\n/**\n * Generates a new child location using a unique key and returns its\n * `Reference`.\n *\n * This is the most common pattern for adding data to a collection of items.\n *\n * If you provide a value to `push()`, the value is written to the\n * generated location. If you don't pass a value, nothing is written to the\n * database and the child remains empty (but you can use the `Reference`\n * elsewhere).\n *\n * The unique keys generated by `push()` are ordered by the current time, so the\n * resulting list of items is chronologically sorted. The keys are also\n * designed to be unguessable (they contain 72 random bits of entropy).\n *\n * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.\n * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.\n *\n * @param parent - The parent location.\n * @param value - Optional value to be written at the generated location.\n * @returns Combined `Promise` and `Reference`; resolves when write is complete,\n * but can be used immediately as the `Reference` to the child location.\n */\nexport function push(\n parent: DatabaseReference,\n value?: unknown\n): ThenableReference {\n parent = getModularInstance(parent);\n validateWritablePath('push', parent._path);\n validateFirebaseDataArg('push', value, parent._path, true);\n const now = repoServerTime(parent._repo);\n const name = nextPushId(now);\n\n // push() returns a ThennableReference whose promise is fulfilled with a\n // regular Reference. We use child() to create handles to two different\n // references. The first is turned into a ThennableReference below by adding\n // then() and catch() methods and is used as the return value of push(). The\n // second remains a regular Reference and is used as the fulfilled value of\n // the first ThennableReference.\n const thenablePushRef: Partial = child(\n parent,\n name\n ) as ReferenceImpl;\n const pushRef = child(parent, name) as ReferenceImpl;\n\n let promise: Promise;\n if (value != null) {\n promise = set(pushRef, value).then(() => pushRef);\n } else {\n promise = Promise.resolve(pushRef);\n }\n\n thenablePushRef.then = promise.then.bind(promise);\n thenablePushRef.catch = promise.then.bind(promise, undefined);\n return thenablePushRef as ThenableReferenceImpl;\n}\n\n/**\n * Removes the data at this Database location.\n *\n * Any data at child locations will also be deleted.\n *\n * The effect of the remove will be visible immediately and the corresponding\n * event 'value' will be triggered. Synchronization of the remove to the\n * Firebase servers will also be started, and the returned Promise will resolve\n * when complete. If provided, the onComplete callback will be called\n * asynchronously after synchronization has finished.\n *\n * @param ref - The location to remove.\n * @returns Resolves when remove on server is complete.\n */\nexport function remove(ref: DatabaseReference): Promise {\n validateWritablePath('remove', ref._path);\n return set(ref, null);\n}\n\n/**\n * Writes data to this Database location.\n *\n * This will overwrite any data at this location and all child locations.\n *\n * The effect of the write will be visible immediately, and the corresponding\n * events (\"value\", \"child_added\", etc.) will be triggered. Synchronization of\n * the data to the Firebase servers will also be started, and the returned\n * Promise will resolve when complete. If provided, the `onComplete` callback\n * will be called asynchronously after synchronization has finished.\n *\n * Passing `null` for the new value is equivalent to calling `remove()`; namely,\n * all data at this location and all child locations will be deleted.\n *\n * `set()` will remove any priority stored at this location, so if priority is\n * meant to be preserved, you need to use `setWithPriority()` instead.\n *\n * Note that modifying data with `set()` will cancel any pending transactions\n * at that location, so extreme care should be taken if mixing `set()` and\n * `transaction()` to modify the same data.\n *\n * A single `set()` will generate a single \"value\" event at the location where\n * the `set()` was performed.\n *\n * @param ref - The location to write to.\n * @param value - The value to be written (string, number, boolean, object,\n * array, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function set(ref: DatabaseReference, value: unknown): Promise {\n ref = getModularInstance(ref);\n validateWritablePath('set', ref._path);\n validateFirebaseDataArg('set', value, ref._path, false);\n const deferred = new Deferred();\n repoSetWithPriority(\n ref._repo,\n ref._path,\n value,\n /*priority=*/ null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Sets a priority for the data at this Database location.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\n * ).\n *\n * @param ref - The location to write to.\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function setPriority(\n ref: DatabaseReference,\n priority: string | number | null\n): Promise {\n ref = getModularInstance(ref);\n validateWritablePath('setPriority', ref._path);\n validatePriority('setPriority', priority, false);\n const deferred = new Deferred();\n repoSetWithPriority(\n ref._repo,\n pathChild(ref._path, '.priority'),\n priority,\n null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Writes data the Database location. Like `set()` but also specifies the\n * priority for that data.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\n * ).\n *\n * @param ref - The location to write to.\n * @param value - The value to be written (string, number, boolean, object,\n * array, or null).\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function setWithPriority(\n ref: DatabaseReference,\n value: unknown,\n priority: string | number | null\n): Promise {\n validateWritablePath('setWithPriority', ref._path);\n validateFirebaseDataArg('setWithPriority', value, ref._path, false);\n validatePriority('setWithPriority', priority, false);\n if (ref.key === '.length' || ref.key === '.keys') {\n throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';\n }\n\n const deferred = new Deferred();\n repoSetWithPriority(\n ref._repo,\n ref._path,\n value,\n priority,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Writes multiple values to the Database at once.\n *\n * The `values` argument contains multiple property-value pairs that will be\n * written to the Database together. Each child property can either be a simple\n * property (for example, \"name\") or a relative path (for example,\n * \"name/first\") from the current location to the data to update.\n *\n * As opposed to the `set()` method, `update()` can be use to selectively update\n * only the referenced properties at the current location (instead of replacing\n * all the child properties at the current location).\n *\n * The effect of the write will be visible immediately, and the corresponding\n * events ('value', 'child_added', etc.) will be triggered. Synchronization of\n * the data to the Firebase servers will also be started, and the returned\n * Promise will resolve when complete. If provided, the `onComplete` callback\n * will be called asynchronously after synchronization has finished.\n *\n * A single `update()` will generate a single \"value\" event at the location\n * where the `update()` was performed, regardless of how many children were\n * modified.\n *\n * Note that modifying data with `update()` will cancel any pending\n * transactions at that location, so extreme care should be taken if mixing\n * `update()` and `transaction()` to modify the same data.\n *\n * Passing `null` to `update()` will remove the data at this location.\n *\n * See\n * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.\n *\n * @param ref - The location to write to.\n * @param values - Object containing multiple values.\n * @returns Resolves when update on server is complete.\n */\nexport function update(ref: DatabaseReference, values: object): Promise {\n validateFirebaseMergeDataArg('update', values, ref._path, false);\n const deferred = new Deferred();\n repoUpdate(\n ref._repo,\n ref._path,\n values as Record,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Gets the most up-to-date result for this query.\n *\n * @param query - The query to run.\n * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is\n * available, or rejects if the client is unable to return a value (e.g., if the\n * server is unreachable and there is nothing cached).\n */\nexport function get(query: Query): Promise {\n query = getModularInstance(query) as QueryImpl;\n const callbackContext = new CallbackContext(() => {});\n const container = new ValueEventRegistration(callbackContext);\n return repoGetValue(query._repo, query, container).then(node => {\n return new DataSnapshot(\n node,\n new ReferenceImpl(query._repo, query._path),\n query._queryParams.getIndex()\n );\n });\n}\n/**\n * Represents registration for 'value' events.\n */\nexport class ValueEventRegistration implements EventRegistration {\n constructor(private callbackContext: CallbackContext) {}\n\n respondsTo(eventType: string): boolean {\n return eventType === 'value';\n }\n\n createEvent(change: Change, query: QueryContext): DataEvent {\n const index = query._queryParams.getIndex();\n return new DataEvent(\n 'value',\n this,\n new DataSnapshot(\n change.snapshotNode,\n new ReferenceImpl(query._repo, query._path),\n index\n )\n );\n }\n\n getEventRunner(eventData: CancelEvent | DataEvent): () => void {\n if (eventData.getEventType() === 'cancel') {\n return () =>\n this.callbackContext.onCancel((eventData as CancelEvent).error);\n } else {\n return () =>\n this.callbackContext.onValue((eventData as DataEvent).snapshot, null);\n }\n }\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null {\n if (this.callbackContext.hasCancelCallback) {\n return new CancelEvent(this, error, path);\n } else {\n return null;\n }\n }\n\n matches(other: EventRegistration): boolean {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n } else if (!other.callbackContext || !this.callbackContext) {\n // If no callback specified, we consider it to match any callback.\n return true;\n } else {\n return other.callbackContext.matches(this.callbackContext);\n }\n }\n\n hasAnyCallback(): boolean {\n return this.callbackContext !== null;\n }\n}\n\n/**\n * Represents the registration of a child_x event.\n */\nexport class ChildEventRegistration implements EventRegistration {\n constructor(\n private eventType: string,\n private callbackContext: CallbackContext | null\n ) {}\n\n respondsTo(eventType: string): boolean {\n let eventToCheck =\n eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck =\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return this.eventType === eventToCheck;\n }\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null {\n if (this.callbackContext.hasCancelCallback) {\n return new CancelEvent(this, error, path);\n } else {\n return null;\n }\n }\n\n createEvent(change: Change, query: QueryContext): DataEvent {\n assert(change.childName != null, 'Child events should have a childName.');\n const childRef = child(\n new ReferenceImpl(query._repo, query._path),\n change.childName\n );\n const index = query._queryParams.getIndex();\n return new DataEvent(\n change.type as EventType,\n this,\n new DataSnapshot(change.snapshotNode, childRef, index),\n change.prevName\n );\n }\n\n getEventRunner(eventData: CancelEvent | DataEvent): () => void {\n if (eventData.getEventType() === 'cancel') {\n return () =>\n this.callbackContext.onCancel((eventData as CancelEvent).error);\n } else {\n return () =>\n this.callbackContext.onValue(\n (eventData as DataEvent).snapshot,\n (eventData as DataEvent).prevName\n );\n }\n }\n\n matches(other: EventRegistration): boolean {\n if (other instanceof ChildEventRegistration) {\n return (\n this.eventType === other.eventType &&\n (!this.callbackContext ||\n !other.callbackContext ||\n this.callbackContext.matches(other.callbackContext))\n );\n }\n\n return false;\n }\n\n hasAnyCallback(): boolean {\n return !!this.callbackContext;\n }\n}\n\nfunction addEventListener(\n query: Query,\n eventType: EventType,\n callback: UserCallback,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n) {\n let cancelCallback: ((error: Error) => unknown) | undefined;\n if (typeof cancelCallbackOrListenOptions === 'object') {\n cancelCallback = undefined;\n options = cancelCallbackOrListenOptions;\n }\n if (typeof cancelCallbackOrListenOptions === 'function') {\n cancelCallback = cancelCallbackOrListenOptions;\n }\n\n if (options && options.onlyOnce) {\n const userCallback = callback;\n const onceCallback: UserCallback = (dataSnapshot, previousChildName) => {\n repoRemoveEventCallbackForQuery(query._repo, query, container);\n userCallback(dataSnapshot, previousChildName);\n };\n onceCallback.userCallback = callback.userCallback;\n onceCallback.context = callback.context;\n callback = onceCallback;\n }\n\n const callbackContext = new CallbackContext(\n callback,\n cancelCallback || undefined\n );\n const container =\n eventType === 'value'\n ? new ValueEventRegistration(callbackContext)\n : new ChildEventRegistration(eventType, callbackContext);\n repoAddEventCallbackForQuery(query._repo, query, container);\n return () => repoRemoveEventCallbackForQuery(query._repo, query, container);\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'value',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName?: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_added',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_changed',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_moved',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_removed',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\nexport { EventType };\n\n/**\n * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.\n * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from\n * the respective `on*` callbacks.\n *\n * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener\n * will not automatically remove listeners registered on child nodes, `off()`\n * must also be called on any child listeners to remove the callback.\n *\n * If a callback is not specified, all callbacks for the specified eventType\n * will be removed. Similarly, if no eventType is specified, all callbacks\n * for the `Reference` will be removed.\n *\n * Individual listeners can also be removed by invoking their unsubscribe\n * callbacks.\n *\n * @param query - The query that the listener was registered with.\n * @param eventType - One of the following strings: \"value\", \"child_added\",\n * \"child_changed\", \"child_removed\", or \"child_moved.\" If omitted, all callbacks\n * for the `Reference` will be removed.\n * @param callback - The callback function that was passed to `on()` or\n * `undefined` to remove all callbacks.\n */\nexport function off(\n query: Query,\n eventType?: EventType,\n callback?: (\n snapshot: DataSnapshot,\n previousChildName?: string | null\n ) => unknown\n): void {\n let container: EventRegistration | null = null;\n const expCallback = callback ? new CallbackContext(callback) : null;\n if (eventType === 'value') {\n container = new ValueEventRegistration(expCallback);\n } else if (eventType) {\n container = new ChildEventRegistration(eventType, expCallback);\n }\n repoRemoveEventCallbackForQuery(query._repo, query, container);\n}\n\n/** Describes the different query constraints available in this SDK. */\nexport type QueryConstraintType =\n | 'endAt'\n | 'endBefore'\n | 'startAt'\n | 'startAfter'\n | 'limitToFirst'\n | 'limitToLast'\n | 'orderByChild'\n | 'orderByKey'\n | 'orderByPriority'\n | 'orderByValue'\n | 'equalTo';\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Database query. `QueryConstraint`s are created by invoking {@link endAt},\n * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link\n * limitToFirst}, {@link limitToLast}, {@link orderByChild},\n * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,\n * {@link orderByValue} or {@link equalTo} and\n * can then be passed to {@link query} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nexport abstract class QueryConstraint {\n /** The type of this query constraints */\n abstract readonly type: QueryConstraintType;\n\n /**\n * Takes the provided `Query` and returns a copy of the `Query` with this\n * `QueryConstraint` applied.\n */\n abstract _apply(query: QueryImpl): QueryImpl;\n}\n\nclass QueryEndAtConstraint extends QueryConstraint {\n readonly type = 'endAt';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('endAt', this._value, query._path, true);\n const newParams = queryParamsEndAt(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'endAt: Starting point was already set (by another call to endAt, ' +\n 'endBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified ending point.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The ending point is inclusive, so children with exactly the specified value\n * will be included in the query. The optional key argument can be used to\n * further limit the range of the query. If it is specified, then children that\n * have exactly the specified value must also have a key name less than or equal\n * to the specified key.\n *\n * You can read more about `endAt()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to end at. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to end at, among the children with the previously\n * specified priority. This argument is only allowed if ordering by child,\n * value, or priority.\n */\nexport function endAt(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('endAt', 'key', key, true);\n return new QueryEndAtConstraint(value, key);\n}\n\nclass QueryEndBeforeConstraint extends QueryConstraint {\n readonly type = 'endBefore';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('endBefore', this._value, query._path, false);\n const newParams = queryParamsEndBefore(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'endBefore: Starting point was already set (by another call to endAt, ' +\n 'endBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified ending point (exclusive).\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The ending point is exclusive. If only a value is provided, children\n * with a value less than the specified value will be included in the query.\n * If a key is specified, then children must have a value less than or equal\n * to the specified value and a key name less than the specified key.\n *\n * @param value - The value to end before. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to end before, among the children with the\n * previously specified priority. This argument is only allowed if ordering by\n * child, value, or priority.\n */\nexport function endBefore(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('endBefore', 'key', key, true);\n return new QueryEndBeforeConstraint(value, key);\n}\n\nclass QueryStartAtConstraint extends QueryConstraint {\n readonly type = 'startAt';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('startAt', this._value, query._path, true);\n const newParams = queryParamsStartAt(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'startAt: Starting point was already set (by another call to startAt, ' +\n 'startBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified starting point.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The starting point is inclusive, so children with exactly the specified value\n * will be included in the query. The optional key argument can be used to\n * further limit the range of the query. If it is specified, then children that\n * have exactly the specified value must also have a key name greater than or\n * equal to the specified key.\n *\n * You can read more about `startAt()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to start at. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start at. This argument is only allowed if\n * ordering by child, value, or priority.\n */\nexport function startAt(\n value: number | string | boolean | null = null,\n key?: string\n): QueryConstraint {\n validateKey('startAt', 'key', key, true);\n return new QueryStartAtConstraint(value, key);\n}\n\nclass QueryStartAfterConstraint extends QueryConstraint {\n readonly type = 'startAfter';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('startAfter', this._value, query._path, false);\n const newParams = queryParamsStartAfter(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'startAfter: Starting point was already set (by another call to startAt, ' +\n 'startAfter, or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified starting point (exclusive).\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The starting point is exclusive. If only a value is provided, children\n * with a value greater than the specified value will be included in the query.\n * If a key is specified, then children must have a value greater than or equal\n * to the specified value and a a key name greater than the specified key.\n *\n * @param value - The value to start after. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start after. This argument is only allowed if\n * ordering by child, value, or priority.\n */\nexport function startAfter(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('startAfter', 'key', key, true);\n return new QueryStartAfterConstraint(value, key);\n}\n\nclass QueryLimitToFirstConstraint extends QueryConstraint {\n readonly type = 'limitToFirst';\n\n constructor(private readonly _limit: number) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n if (query._queryParams.hasLimit()) {\n throw new Error(\n 'limitToFirst: Limit was already set (by another call to limitToFirst ' +\n 'or limitToLast).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n queryParamsLimitToFirst(query._queryParams, this._limit),\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that if limited to the first specific number\n * of children.\n *\n * The `limitToFirst()` method is used to set a maximum number of children to be\n * synced for a given callback. If we set a limit of 100, we will initially only\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\n * stored in our Database, a `child_added` event will fire for each message.\n * However, if we have over 100 messages, we will only receive a `child_added`\n * event for the first 100 ordered messages. As items change, we will receive\n * `child_removed` events for each item that drops out of the active list so\n * that the total number stays at 100.\n *\n * You can read more about `limitToFirst()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param limit - The maximum number of nodes to include in this query.\n */\nexport function limitToFirst(limit: number): QueryConstraint {\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\n throw new Error('limitToFirst: First argument must be a positive integer.');\n }\n return new QueryLimitToFirstConstraint(limit);\n}\n\nclass QueryLimitToLastConstraint extends QueryConstraint {\n readonly type = 'limitToLast';\n\n constructor(private readonly _limit: number) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n if (query._queryParams.hasLimit()) {\n throw new Error(\n 'limitToLast: Limit was already set (by another call to limitToFirst ' +\n 'or limitToLast).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n queryParamsLimitToLast(query._queryParams, this._limit),\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that is limited to return only the last\n * specified number of children.\n *\n * The `limitToLast()` method is used to set a maximum number of children to be\n * synced for a given callback. If we set a limit of 100, we will initially only\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\n * stored in our Database, a `child_added` event will fire for each message.\n * However, if we have over 100 messages, we will only receive a `child_added`\n * event for the last 100 ordered messages. As items change, we will receive\n * `child_removed` events for each item that drops out of the active list so\n * that the total number stays at 100.\n *\n * You can read more about `limitToLast()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param limit - The maximum number of nodes to include in this query.\n */\nexport function limitToLast(limit: number): QueryConstraint {\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\n throw new Error('limitToLast: First argument must be a positive integer.');\n }\n\n return new QueryLimitToLastConstraint(limit);\n}\n\nclass QueryOrderByChildConstraint extends QueryConstraint {\n readonly type = 'orderByChild';\n\n constructor(private readonly _path: string) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByChild');\n const parsedPath = new Path(this._path);\n if (pathIsEmpty(parsedPath)) {\n throw new Error(\n 'orderByChild: cannot pass in empty path. Use orderByValue() instead.'\n );\n }\n const index = new PathIndex(parsedPath);\n const newParams = queryParamsOrderBy(query._queryParams, index);\n validateQueryEndpoints(newParams);\n\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by the specified child key.\n *\n * Queries can only order by one key at a time. Calling `orderByChild()`\n * multiple times on the same query is an error.\n *\n * Firebase queries allow you to order your data by any child key on the fly.\n * However, if you know in advance what your indexes will be, you can define\n * them via the .indexOn rule in your Security Rules for better performance. See\n * the{@link https://firebase.google.com/docs/database/security/indexing-data}\n * rule for more information.\n *\n * You can read more about `orderByChild()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n *\n * @param path - The path to order by.\n */\nexport function orderByChild(path: string): QueryConstraint {\n if (path === '$key') {\n throw new Error(\n 'orderByChild: \"$key\" is invalid. Use orderByKey() instead.'\n );\n } else if (path === '$priority') {\n throw new Error(\n 'orderByChild: \"$priority\" is invalid. Use orderByPriority() instead.'\n );\n } else if (path === '$value') {\n throw new Error(\n 'orderByChild: \"$value\" is invalid. Use orderByValue() instead.'\n );\n }\n validatePathString('orderByChild', 'path', path, false);\n return new QueryOrderByChildConstraint(path);\n}\n\nclass QueryOrderByKeyConstraint extends QueryConstraint {\n readonly type = 'orderByKey';\n\n _apply(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByKey');\n const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by the key.\n *\n * Sorts the results of a query by their (ascending) key values.\n *\n * You can read more about `orderByKey()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n */\nexport function orderByKey(): QueryConstraint {\n return new QueryOrderByKeyConstraint();\n}\n\nclass QueryOrderByPriorityConstraint extends QueryConstraint {\n readonly type = 'orderByPriority';\n\n _apply(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByPriority');\n const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by priority.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}\n * for alternatives to priority.\n */\nexport function orderByPriority(): QueryConstraint {\n return new QueryOrderByPriorityConstraint();\n}\n\nclass QueryOrderByValueConstraint extends QueryConstraint {\n readonly type = 'orderByValue';\n\n _apply(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByValue');\n const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by value.\n *\n * If the children of a query are all scalar values (string, number, or\n * boolean), you can order the results by their (ascending) values.\n *\n * You can read more about `orderByValue()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n */\nexport function orderByValue(): QueryConstraint {\n return new QueryOrderByValueConstraint();\n}\n\nclass QueryEqualToValueConstraint extends QueryConstraint {\n readonly type = 'equalTo';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('equalTo', this._value, query._path, false);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'equalTo: Starting point was already set (by another call to startAt/startAfter or ' +\n 'equalTo).'\n );\n }\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'equalTo: Ending point was already set (by another call to endAt/endBefore or ' +\n 'equalTo).'\n );\n }\n return new QueryEndAtConstraint(this._value, this._key)._apply(\n new QueryStartAtConstraint(this._value, this._key)._apply(query)\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` that includes children that match the specified\n * value.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The optional key argument can be used to further limit the range of the\n * query. If it is specified, then children that have exactly the specified\n * value must also have exactly the specified key as their key name. This can be\n * used to filter result sets with many matches for the same value.\n *\n * You can read more about `equalTo()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to match for. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start at, among the children with the\n * previously specified priority. This argument is only allowed if ordering by\n * child, value, or priority.\n */\nexport function equalTo(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('equalTo', 'key', key, true);\n return new QueryEqualToValueConstraint(value, key);\n}\n\n/**\n * Creates a new immutable instance of `Query` that is extended to also include\n * additional query constraints.\n *\n * @param query - The Query instance to use as a base for the new constraints.\n * @param queryConstraints - The list of `QueryConstraint`s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query(\n query: Query,\n ...queryConstraints: QueryConstraint[]\n): Query {\n let queryImpl = getModularInstance(query) as QueryImpl;\n for (const constraint of queryConstraints) {\n queryImpl = constraint._apply(queryImpl);\n }\n return queryImpl;\n}\n\n/**\n * Define reference constructor in various modules\n *\n * We are doing this here to avoid several circular\n * dependency issues\n */\nsyncPointSetReferenceConstructor(ReferenceImpl);\nsyncTreeSetReferenceConstructor(ReferenceImpl);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _FirebaseService,\n _getProvider,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\nimport {\n getModularInstance,\n createMockUserToken,\n deepEqual,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\n} from '@firebase/util';\n\nimport { AppCheckTokenProvider } from '../core/AppCheckTokenProvider';\nimport {\n AuthTokenProvider,\n EmulatorTokenProvider,\n FirebaseAuthTokenProvider\n} from '../core/AuthTokenProvider';\nimport { Repo, repoInterrupt, repoResume, repoStart } from '../core/Repo';\nimport { RepoInfo, RepoInfoEmulatorOptions } from '../core/RepoInfo';\nimport { parseRepoInfo } from '../core/util/libs/parser';\nimport { newEmptyPath, pathIsEmpty } from '../core/util/Path';\nimport {\n warn,\n fatal,\n log,\n enableLogging as enableLoggingImpl\n} from '../core/util/util';\nimport { validateUrl } from '../core/util/validation';\nimport { BrowserPollConnection } from '../realtime/BrowserPollConnection';\nimport { TransportManager } from '../realtime/TransportManager';\nimport { WebSocketConnection } from '../realtime/WebSocketConnection';\n\nimport { ReferenceImpl } from './Reference_impl';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n/**\n * This variable is also defined in the firebase Node.js Admin SDK. Before\n * modifying this definition, consult the definition in:\n *\n * https://github.com/firebase/firebase-admin-node\n *\n * and make sure the two are consistent.\n */\nconst FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';\n\n/**\n * Creates and caches `Repo` instances.\n */\nconst repos: {\n [appName: string]: {\n [dbUrl: string]: Repo;\n };\n} = {};\n\n/**\n * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).\n */\nlet useRestClient = false;\n\n/**\n * Update an existing `Repo` in place to point to a new host/port.\n */\nfunction repoManagerApplyEmulatorSettings(\n repo: Repo,\n hostAndPort: string,\n emulatorOptions: RepoInfoEmulatorOptions,\n tokenProvider?: AuthTokenProvider\n): void {\n const portIndex = hostAndPort.lastIndexOf(':');\n const host = hostAndPort.substring(0, portIndex);\n const useSsl = isCloudWorkstation(host);\n repo.repoInfo_ = new RepoInfo(\n hostAndPort,\n /* secure= */ useSsl,\n repo.repoInfo_.namespace,\n repo.repoInfo_.webSocketOnly,\n repo.repoInfo_.nodeAdmin,\n repo.repoInfo_.persistenceKey,\n repo.repoInfo_.includeNamespaceInQueryParams,\n /*isUsingEmulator=*/ true,\n emulatorOptions\n );\n\n if (tokenProvider) {\n repo.authTokenProvider_ = tokenProvider;\n }\n}\n\n/**\n * This function should only ever be called to CREATE a new database instance.\n * @internal\n */\nexport function repoManagerDatabaseFromApp(\n app: FirebaseApp,\n authProvider: Provider,\n appCheckProvider?: Provider,\n url?: string,\n nodeAdmin?: boolean\n): Database {\n let dbUrl: string | undefined = url || app.options.databaseURL;\n if (dbUrl === undefined) {\n if (!app.options.projectId) {\n fatal(\n \"Can't determine Firebase Database URL. Be sure to include \" +\n ' a Project ID when calling firebase.initializeApp().'\n );\n }\n\n log('Using default host for project ', app.options.projectId);\n dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;\n }\n\n let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\n let repoInfo = parsedUrl.repoInfo;\n\n let isEmulator: boolean;\n\n let dbEmulatorHost: string | undefined = undefined;\n if (typeof process !== 'undefined' && process.env) {\n dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];\n }\n\n if (dbEmulatorHost) {\n isEmulator = true;\n dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;\n parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\n repoInfo = parsedUrl.repoInfo;\n } else {\n isEmulator = !parsedUrl.repoInfo.secure;\n }\n\n const authTokenProvider =\n nodeAdmin && isEmulator\n ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)\n : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);\n\n validateUrl('Invalid Firebase Database URL', parsedUrl);\n if (!pathIsEmpty(parsedUrl.path)) {\n fatal(\n 'Database URL must point to the root of a Firebase Database ' +\n '(not including a child path).'\n );\n }\n\n const repo = repoManagerCreateRepo(\n repoInfo,\n app,\n authTokenProvider,\n new AppCheckTokenProvider(app, appCheckProvider)\n );\n return new Database(repo, app);\n}\n\n/**\n * Remove the repo and make sure it is disconnected.\n *\n */\nfunction repoManagerDeleteRepo(repo: Repo, appName: string): void {\n const appRepos = repos[appName];\n // This should never happen...\n if (!appRepos || appRepos[repo.key] !== repo) {\n fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);\n }\n repoInterrupt(repo);\n delete appRepos[repo.key];\n}\n\n/**\n * Ensures a repo doesn't already exist and then creates one using the\n * provided app.\n *\n * @param repoInfo - The metadata about the Repo\n * @returns The Repo object for the specified server / repoName.\n */\nfunction repoManagerCreateRepo(\n repoInfo: RepoInfo,\n app: FirebaseApp,\n authTokenProvider: AuthTokenProvider,\n appCheckProvider: AppCheckTokenProvider\n): Repo {\n let appRepos = repos[app.name];\n\n if (!appRepos) {\n appRepos = {};\n repos[app.name] = appRepos;\n }\n\n let repo = appRepos[repoInfo.toURLString()];\n if (repo) {\n fatal(\n 'Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.'\n );\n }\n repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);\n appRepos[repoInfo.toURLString()] = repo;\n\n return repo;\n}\n\n/**\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\n */\nexport function repoManagerForceRestClient(forceRestClient: boolean): void {\n useRestClient = forceRestClient;\n}\n\n/**\n * Class representing a Firebase Realtime Database.\n */\nexport class Database implements _FirebaseService {\n /** Represents a `Database` instance. */\n readonly 'type' = 'database';\n\n /** Track if the instance has been used (root or repo accessed) */\n _instanceStarted: boolean = false;\n\n /** Backing state for root_ */\n private _rootInternal?: ReferenceImpl;\n\n /** @hideconstructor */\n constructor(\n public _repoInternal: Repo,\n /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */\n readonly app: FirebaseApp\n ) {}\n\n get _repo(): Repo {\n if (!this._instanceStarted) {\n repoStart(\n this._repoInternal,\n this.app.options.appId,\n this.app.options['databaseAuthVariableOverride']\n );\n this._instanceStarted = true;\n }\n return this._repoInternal;\n }\n\n get _root(): ReferenceImpl {\n if (!this._rootInternal) {\n this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());\n }\n return this._rootInternal;\n }\n\n _delete(): Promise {\n if (this._rootInternal !== null) {\n repoManagerDeleteRepo(this._repo, this.app.name);\n this._repoInternal = null;\n this._rootInternal = null;\n }\n return Promise.resolve();\n }\n\n _checkNotDeleted(apiName: string) {\n if (this._rootInternal === null) {\n fatal('Cannot call ' + apiName + ' on a deleted database.');\n }\n }\n}\n\nfunction checkTransportInit() {\n if (TransportManager.IS_TRANSPORT_INITIALIZED) {\n warn(\n 'Transport has already been initialized. Please call this function before calling ref or setting up a listener'\n );\n }\n}\n\n/**\n * Force the use of websockets instead of longPolling.\n */\nexport function forceWebSockets() {\n checkTransportInit();\n BrowserPollConnection.forceDisallow();\n}\n\n/**\n * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.\n */\nexport function forceLongPolling() {\n checkTransportInit();\n WebSocketConnection.forceDisallow();\n BrowserPollConnection.forceAllow();\n}\n\n/**\n * Returns the instance of the Realtime Database SDK that is associated with the provided\n * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if\n * no instance exists or if the existing instance uses a custom database URL.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime\n * Database instance is associated with.\n * @param url - The URL of the Realtime Database instance to connect to. If not\n * provided, the SDK connects to the default instance of the Firebase App.\n * @returns The `Database` instance of the provided app.\n */\nexport function getDatabase(\n app: FirebaseApp = getApp(),\n url?: string\n): Database {\n const db = _getProvider(app, 'database').getImmediate({\n identifier: url\n }) as Database;\n if (!db._instanceStarted) {\n const emulator = getDefaultEmulatorHostnameAndPort('database');\n if (emulator) {\n connectDatabaseEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * Modify the provided instance to communicate with the Realtime Database\n * emulator.\n *\n *

Note: This method must be called before performing any other operation.\n *\n * @param db - The instance to modify.\n * @param host - The emulator host (ex: localhost)\n * @param port - The emulator port (ex: 8080)\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\n */\nexport function connectDatabaseEmulator(\n db: Database,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n db = getModularInstance(db);\n db._checkNotDeleted('useEmulator');\n\n const hostAndPort = `${host}:${port}`;\n const repo = db._repoInternal;\n if (db._instanceStarted) {\n // If the instance has already been started, then silenty fail if this function is called again\n // with the same parameters. If the parameters differ then assert.\n if (\n hostAndPort === db._repoInternal.repoInfo_.host &&\n deepEqual(options, repo.repoInfo_.emulatorOptions)\n ) {\n return;\n }\n fatal(\n 'connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.'\n );\n }\n\n let tokenProvider: EmulatorTokenProvider | undefined = undefined;\n if (repo.repoInfo_.nodeAdmin) {\n if (options.mockUserToken) {\n fatal(\n 'mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the \"firebase\" package instead of \"firebase-admin\".'\n );\n }\n tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);\n } else if (options.mockUserToken) {\n const token =\n typeof options.mockUserToken === 'string'\n ? options.mockUserToken\n : createMockUserToken(options.mockUserToken, db.app.options.projectId);\n tokenProvider = new EmulatorTokenProvider(token);\n }\n\n // Workaround to get cookies in Firebase Studio\n if (isCloudWorkstation(host)) {\n void pingServer(host);\n updateEmulatorBanner('Database', true);\n }\n\n // Modify the repo to apply emulator settings\n repoManagerApplyEmulatorSettings(repo, hostAndPort, options, tokenProvider);\n}\n\n/**\n * Disconnects from the server (all Database operations will be completed\n * offline).\n *\n * The client automatically maintains a persistent connection to the Database\n * server, which will remain active indefinitely and reconnect when\n * disconnected. However, the `goOffline()` and `goOnline()` methods may be used\n * to control the client connection in cases where a persistent connection is\n * undesirable.\n *\n * While offline, the client will no longer receive data updates from the\n * Database. However, all Database operations performed locally will continue to\n * immediately fire events, allowing your application to continue behaving\n * normally. Additionally, each operation performed locally will automatically\n * be queued and retried upon reconnection to the Database server.\n *\n * To reconnect to the Database and begin receiving remote events, see\n * `goOnline()`.\n *\n * @param db - The instance to disconnect.\n */\nexport function goOffline(db: Database): void {\n db = getModularInstance(db);\n db._checkNotDeleted('goOffline');\n repoInterrupt(db._repo);\n}\n\n/**\n * Reconnects to the server and synchronizes the offline Database state\n * with the server state.\n *\n * This method should be used after disabling the active connection with\n * `goOffline()`. Once reconnected, the client will transmit the proper data\n * and fire the appropriate events so that your client \"catches up\"\n * automatically.\n *\n * @param db - The instance to reconnect.\n */\nexport function goOnline(db: Database): void {\n db = getModularInstance(db);\n db._checkNotDeleted('goOnline');\n repoResume(db._repo);\n}\n\n/**\n * Logs debugging information to the console.\n *\n * @param enabled - Enables logging if `true`, disables logging if `false`.\n * @param persistent - Remembers the logging state between page refreshes if\n * `true`.\n */\nexport function enableLogging(enabled: boolean, persistent?: boolean);\n\n/**\n * Logs debugging information to the console.\n *\n * @param logger - A custom logger function to control how things get logged.\n */\nexport function enableLogging(logger: (message: string) => unknown);\n\nexport function enableLogging(\n logger: boolean | ((message: string) => unknown),\n persistent?: boolean\n): void {\n enableLoggingImpl(logger, persistent);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst SERVER_TIMESTAMP = {\n '.sv': 'timestamp'\n};\n\n/**\n * Returns a placeholder value for auto-populating the current timestamp (time\n * since the Unix epoch, in milliseconds) as determined by the Firebase\n * servers.\n */\nexport function serverTimestamp(): object {\n return SERVER_TIMESTAMP;\n}\n\n/**\n * Returns a placeholder value that can be used to atomically increment the\n * current database value by the provided delta.\n *\n * @param delta - the amount to modify the current value atomically.\n * @returns A placeholder value for modifying data atomically server-side.\n */\nexport function increment(delta: number): object {\n return {\n '.sv': {\n 'increment': delta\n }\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance, Deferred } from '@firebase/util';\n\nimport { repoStartTransaction } from '../core/Repo';\nimport { PRIORITY_INDEX } from '../core/snap/indexes/PriorityIndex';\nimport { Node } from '../core/snap/Node';\nimport { validateWritablePath } from '../core/util/validation';\n\nimport { DatabaseReference } from './Reference';\nimport { DataSnapshot, onValue, ReferenceImpl } from './Reference_impl';\n\n/** An options object to configure transactions. */\nexport interface TransactionOptions {\n /**\n * By default, events are raised each time the transaction update function\n * runs. So if it is run multiple times, you may see intermediate states. You\n * can set this to false to suppress these intermediate states and instead\n * wait until the transaction has completed before events are raised.\n */\n readonly applyLocally?: boolean;\n}\n\n/**\n * A type for the resolve value of {@link runTransaction}.\n */\nexport class TransactionResult {\n /** @hideconstructor */\n constructor(\n /** Whether the transaction was successfully committed. */\n readonly committed: boolean,\n /** The resulting data snapshot. */\n readonly snapshot: DataSnapshot\n ) {}\n\n /** Returns a JSON-serializable representation of this object. */\n toJSON(): object {\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n }\n}\n\n/**\n * Atomically modifies the data at this location.\n *\n * Atomically modify the data at this location. Unlike a normal `set()`, which\n * just overwrites the data regardless of its previous value, `runTransaction()` is\n * used to modify the existing value to a new value, ensuring there are no\n * conflicts with other clients writing to the same location at the same time.\n *\n * To accomplish this, you pass `runTransaction()` an update function which is\n * used to transform the current value into a new value. If another client\n * writes to the location before your new value is successfully written, your\n * update function will be called again with the new current value, and the\n * write will be retried. This will happen repeatedly until your write succeeds\n * without conflict or you abort the transaction by not returning a value from\n * your update function.\n *\n * Note: Modifying data with `set()` will cancel any pending transactions at\n * that location, so extreme care should be taken if mixing `set()` and\n * `runTransaction()` to update the same data.\n *\n * Note: When using transactions with Security and Firebase Rules in place, be\n * aware that a client needs `.read` access in addition to `.write` access in\n * order to perform a transaction. This is because the client-side nature of\n * transactions requires the client to read the data in order to transactionally\n * update it.\n *\n * @param ref - The location to atomically modify.\n * @param transactionUpdate - A developer-supplied function which will be passed\n * the current data stored at this location (as a JavaScript object). The\n * function should return the new value it would like written (as a JavaScript\n * object). If `undefined` is returned (i.e. you return with no arguments) the\n * transaction will be aborted and the data at this location will not be\n * modified.\n * @param options - An options object to configure transactions.\n * @returns A `Promise` that can optionally be used instead of the `onComplete`\n * callback to handle success and failure.\n */\nexport function runTransaction(\n ref: DatabaseReference,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n transactionUpdate: (currentData: any) => unknown,\n options?: TransactionOptions\n): Promise {\n ref = getModularInstance(ref);\n\n validateWritablePath('Reference.transaction', ref._path);\n\n if (ref.key === '.length' || ref.key === '.keys') {\n throw (\n 'Reference.transaction failed: ' + ref.key + ' is a read-only object.'\n );\n }\n\n const applyLocally = options?.applyLocally ?? true;\n const deferred = new Deferred();\n\n const promiseComplete = (\n error: Error | null,\n committed: boolean,\n node: Node | null\n ) => {\n let dataSnapshot: DataSnapshot | null = null;\n if (error) {\n deferred.reject(error);\n } else {\n dataSnapshot = new DataSnapshot(\n node,\n new ReferenceImpl(ref._repo, ref._path),\n PRIORITY_INDEX\n );\n deferred.resolve(new TransactionResult(committed, dataSnapshot));\n }\n };\n\n // Add a watch to make sure we get server updates.\n const unwatcher = onValue(ref, () => {});\n\n repoStartTransaction(\n ref._repo,\n ref._path,\n transactionUpdate,\n promiseComplete,\n unwatcher,\n applyLocally\n );\n\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PersistentConnection } from '../core/PersistentConnection';\nimport { RepoInfo } from '../core/RepoInfo';\nimport { Connection } from '../realtime/Connection';\n\nimport { repoManagerForceRestClient } from './Database';\n\nexport const DataConnection = PersistentConnection;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(PersistentConnection.prototype as any).simpleListen = function (\n pathString: string,\n onComplete: (a: unknown) => void\n) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(PersistentConnection.prototype as any).echo = function (\n data: unknown,\n onEcho: (a: unknown) => void\n) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n\n// RealTimeConnection properties that we use in tests.\nexport const RealTimeConnection = Connection;\n\n/**\n * @internal\n */\nexport const hijackHash = function (newHash: () => string) {\n const oldPut = PersistentConnection.prototype.put;\n PersistentConnection.prototype.put = function (\n pathString,\n data,\n onComplete,\n hash\n ) {\n if (hash !== undefined) {\n hash = newHash();\n }\n oldPut.call(this, pathString, data, onComplete, hash);\n };\n return function () {\n PersistentConnection.prototype.put = oldPut;\n };\n};\n\nexport const ConnectionTarget = RepoInfo;\n\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n * @internal\n */\nexport const forceRestClient = function (forceRestClient: boolean) {\n repoManagerForceRestClient(forceRestClient);\n};\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebaseAppCheckInternal,\n AppCheckInternalComponentName\n} from '@firebase/app-check-interop-types';\nimport { FirebaseApp } from '@firebase/app-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n Provider\n} from '@firebase/component';\n\nimport { repoManagerDatabaseFromApp } from '../api/Database';\nimport { Database } from '../api.standalone';\nimport { setSDKVersion } from '../core/version';\n\n/**\n * Used by console to create a database based on the app,\n * passed database URL and a custom auth implementation.\n * @internal\n * @param app - A valid FirebaseApp-like object\n * @param url - A valid Firebase databaseURL\n * @param version - custom version e.g. firebase-admin version\n * @param customAppCheckImpl - custom app check implementation\n * @param customAuthImpl - custom auth implementation\n */\nexport function _initStandalone({\n app,\n url,\n version,\n customAuthImpl,\n customAppCheckImpl,\n nodeAdmin = false\n}: {\n app: FirebaseApp;\n url: string;\n version: string;\n customAuthImpl: FirebaseAuthInternal;\n customAppCheckImpl?: FirebaseAppCheckInternal;\n nodeAdmin?: boolean;\n}): Database {\n setSDKVersion(version);\n\n /**\n * ComponentContainer('database-standalone') is just a placeholder that doesn't perform\n * any actual function.\n */\n const componentContainer = new ComponentContainer('database-standalone');\n const authProvider = new Provider(\n 'auth-internal',\n componentContainer\n );\n let appCheckProvider: Provider;\n if (customAppCheckImpl) {\n appCheckProvider = new Provider(\n 'app-check-internal',\n componentContainer\n );\n appCheckProvider.setComponent(\n new Component(\n 'app-check-internal',\n () => customAppCheckImpl,\n ComponentType.PRIVATE\n )\n );\n }\n authProvider.setComponent(\n new Component('auth-internal', () => customAuthImpl, ComponentType.PRIVATE)\n );\n\n return repoManagerDatabaseFromApp(\n app,\n authProvider,\n appCheckProvider,\n url,\n nodeAdmin\n );\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport Websocket from 'faye-websocket';\n\nimport { setWebSocketImpl } from './realtime/WebSocketConnection';\n\nsetWebSocketImpl(Websocket.Client);\n\n// This entry point should only be consumed by Admin SDK\nexport * from './api.standalone';\n"],"names":["stringify","jsonEval","contains","Logger","stringToByteArray","Sha1","base64","enableLogging","assert","LogLevel","isNodeSdk","deepCopy","app","_isFirebaseServerApp","base64Encode","isMobileCordova","stringLength","Deferred","safeGet","isAdmin","isValidFormat","isEmpty","isReactNative","assertionError","MAX_NODE","setMaxNode","nodeFromJSON","map","setPriorityMaxNode","querystring","referenceConstructor","errorPrefixFxn","getModularInstance","isCloudWorkstation","deepEqual","createMockUserToken","pingServer","updateEmulatorBanner","enableLoggingImpl","ComponentContainer","Provider","Component","Websocket"],"mappings":";;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;AAeG;AAEI,MAAM,gBAAgB,GAAG,GAA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AIA,kBAAQ,CAC7B,oBAAoB,EACpB,kBAAkB,CACnB,CAAC;AACF,QAAA,gBAAgB,CAAC,YAAY,CAC3B,IAAIC,mBAAS,CACX,oBAAoB,EACpB,MAAM,kBAAkB,EAAA,SAAA,6BAEzB,CACF,CAAC;KACH;AACD,IAAA,YAAY,CAAC,YAAY,CACvB,IAAIA,mBAAS,CAAC,eAAe,EAAE,MAAM,cAAc,EAAA,SAAA,6BAAwB,CAC5E,CAAC;AAEF,IAAA,OAAO,0BAA0B,CAC/B,GAAG,EACH,YAAY,EACZ,gBAAgB,EAChB,GAAG,EACH,SAAS,CACV,CAAC;AACJ;;AClGA;;;;;;;;;;;;;;;AAeG;AAMH,gBAAgB,CAACC,6BAAS,CAAC,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@firebase/database/dist/internal.d.ts b/node_modules/@firebase/database/dist/internal.d.ts new file mode 100644 index 0000000..e014588 --- /dev/null +++ b/node_modules/@firebase/database/dist/internal.d.ts @@ -0,0 +1,2991 @@ +/** + * Firebase Realtime Database + * + * @packageDocumentation + */ + +import { AppCheckInternalComponentName } from '@firebase/app-check-interop-types'; +import { AppCheckTokenListener } from '@firebase/app-check-interop-types'; +import { AppCheckTokenResult } from '@firebase/app-check-interop-types'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { FirebaseApp } from '@firebase/app'; +import { FirebaseApp as FirebaseApp_2 } from '@firebase/app-types'; +import { FirebaseAppCheckInternal } from '@firebase/app-check-interop-types'; +import { FirebaseAuthInternal } from '@firebase/auth-interop-types'; +import { FirebaseAuthInternalName } from '@firebase/auth-interop-types'; +import { FirebaseAuthTokenData } from '@firebase/app-types/private'; +import { _FirebaseService } from '@firebase/app'; +import { Provider } from '@firebase/component'; + +/** + * Abstraction around AppCheck's token fetching capabilities. + */ +declare class AppCheckTokenProvider { + private appCheckProvider?; + private appCheck?; + private serverAppAppCheckToken?; + private appName; + constructor(app: FirebaseApp, appCheckProvider?: Provider); + getToken(forceRefresh?: boolean): Promise; + addTokenChangeListener(listener: AppCheckTokenListener): void; + notifyForInvalidToken(): void; +} + +declare interface AuthTokenProvider { + getToken(forceRefresh: boolean): Promise; + addTokenChangeListener(listener: (token: string | null) => void): void; + removeTokenChangeListener(listener: (token: string | null) => void): void; + notifyForInvalidToken(): void; +} + +/** + * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully + * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g. + * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks + * whether a node potentially had children removed due to a filter. + */ +declare class CacheNode { + private node_; + private fullyInitialized_; + private filtered_; + constructor(node_: Node_2, fullyInitialized_: boolean, filtered_: boolean); + /** + * Returns whether this node was fully initialized with either server data or a complete overwrite by the client + */ + isFullyInitialized(): boolean; + /** + * Returns whether this node is potentially missing children due to a filter applied to the node + */ + isFiltered(): boolean; + isCompleteForPath(path: Path): boolean; + isCompleteForChild(key: string): boolean; + getNode(): Node_2; +} + +declare class CancelEvent implements Event_2 { + eventRegistration: EventRegistration; + error: Error; + path: Path; + constructor(eventRegistration: EventRegistration, error: Error, path: Path); + getPath(): Path; + getEventType(): string; + getEventRunner(): () => void; + toString(): string; +} + +declare interface Change { + /** @param type - The event type */ + type: ChangeType; + /** @param snapshotNode - The data */ + snapshotNode: Node_2; + /** @param childName - The name for this child, if it's a child even */ + childName?: string; + /** @param oldSnap - Used for intermediate processing of child changed events */ + oldSnap?: Node_2; + /** * @param prevName - The name for the previous child, if applicable */ + prevName?: string | null; +} + +declare const enum ChangeType { + /** Event type for a child added */ + CHILD_ADDED = "child_added", + /** Event type for a child removed */ + CHILD_REMOVED = "child_removed", + /** Event type for a child changed */ + CHILD_CHANGED = "child_changed", + /** Event type for a child moved */ + CHILD_MOVED = "child_moved", + /** Event type for a value change */ + VALUE = "value" +} + +/** + * Gets a `Reference` for the location at the specified relative path. + * + * The relative path can either be a simple child name (for example, "ada") or + * a deeper slash-separated path (for example, "ada/name/first"). + * + * @param parent - The parent location. + * @param path - A relative path from this location to the desired child + * location. + * @returns The specified child location. + */ +export declare function child(parent: DatabaseReference, path: string): DatabaseReference; + +declare class ChildChangeAccumulator { + private readonly changeMap; + trackChildChange(change: Change): void; + getChanges(): Change[]; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview Implementation of an immutable SortedMap using a Left-leaning + * Red-Black Tree, adapted from the implementation in Mugs + * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen + * (mads379\@gmail.com). + * + * Original paper on Left-leaning Red-Black Trees: + * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf + * + * Invariant 1: No red node has a red child + * Invariant 2: Every leaf path has the same number of black nodes + * Invariant 3: Only the left child can be red (left leaning) + */ +declare type Comparator = (key1: K, key2: K) => number; + +/** + * Since updates to filtered nodes might require nodes to be pulled in from "outside" the node, this interface + * can help to get complete children that can be pulled in. + * A class implementing this interface takes potentially multiple sources (e.g. user writes, server data from + * other views etc.) to try it's best to get a complete child that might be useful in pulling into the view. + * + * @interface + */ +declare interface CompleteChildSource { + getCompleteChild(childKey: string): Node_2 | null; + getChildAfterChild(index: Index, child: NamedNode, reverse: boolean): NamedNode | null; +} + +/** + * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with + * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write + * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write + * to reflect the write added. + */ +declare class CompoundWrite { + writeTree_: ImmutableTree; + constructor(writeTree_: ImmutableTree); + static empty(): CompoundWrite; +} + +/** + * Modify the provided instance to communicate with the Realtime Database + * emulator. + * + *

Note: This method must be called before performing any other operation. + * + * @param db - The instance to modify. + * @param host - The emulator host (ex: localhost) + * @param port - The emulator port (ex: 8080) + * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules + */ +export declare function connectDatabaseEmulator(db: Database, host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions | string; +}): void; + +/** + * Class representing a Firebase Realtime Database. + */ +export declare class Database implements _FirebaseService { + _repoInternal: Repo; + /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */ + readonly app: FirebaseApp; + /** Represents a `Database` instance. */ + readonly 'type' = "database"; + /** Track if the instance has been used (root or repo accessed) */ + _instanceStarted: boolean; + /** Backing state for root_ */ + private _rootInternal?; + /** @hideconstructor */ + constructor(_repoInternal: Repo, + /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */ + app: FirebaseApp); + get _repo(): Repo; + get _root(): _ReferenceImpl; + _delete(): Promise; + _checkNotDeleted(apiName: string): void; +} + +/** + * A `DatabaseReference` represents a specific location in your Database and can be used + * for reading or writing data to that Database location. + * + * You can reference the root or child location in your Database by calling + * `ref()` or `ref("child/path")`. + * + * Writing is done with the `set()` method and reading can be done with the + * `on*()` method. See {@link + * https://firebase.google.com/docs/database/web/read-and-write} + */ +export declare interface DatabaseReference extends Query { + /** + * The last part of the `DatabaseReference`'s path. + * + * For example, `"ada"` is the key for + * `https://.firebaseio.com/users/ada`. + * + * The key of a root `DatabaseReference` is `null`. + */ + readonly key: string | null; + /** + * The parent location of a `DatabaseReference`. + * + * The parent of a root `DatabaseReference` is `null`. + */ + readonly parent: DatabaseReference | null; + /** The root `DatabaseReference` of the Database. */ + readonly root: DatabaseReference; +} + +/** + * A `DataSnapshot` contains data from a Database location. + * + * Any time you read data from the Database, you receive the data as a + * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach + * with `on()` or `once()`. You can extract the contents of the snapshot as a + * JavaScript object by calling the `val()` method. Alternatively, you can + * traverse into the snapshot by calling `child()` to return child snapshots + * (which you could then call `val()` on). + * + * A `DataSnapshot` is an efficiently generated, immutable copy of the data at + * a Database location. It cannot be modified and will never change (to modify + * data, you always call the `set()` method on a `Reference` directly). + */ +export declare class DataSnapshot { + readonly _node: Node_2; + /** + * The location of this DataSnapshot. + */ + readonly ref: DatabaseReference; + readonly _index: Index; + /** + * @param _node - A SnapshotNode to wrap. + * @param ref - The location this snapshot came from. + * @param _index - The iteration order for this snapshot + * @hideconstructor + */ + constructor(_node: Node_2, + /** + * The location of this DataSnapshot. + */ + ref: DatabaseReference, _index: Index); + /** + * Gets the priority value of the data in this `DataSnapshot`. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data} + * ). + */ + get priority(): string | number | null; + /** + * The key (last part of the path) of the location of this `DataSnapshot`. + * + * The last token in a Database location is considered its key. For example, + * "ada" is the key for the /users/ada/ node. Accessing the key on any + * `DataSnapshot` will return the key for the location that generated it. + * However, accessing the key on the root URL of a Database will return + * `null`. + */ + get key(): string | null; + /** Returns the number of child properties of this `DataSnapshot`. */ + get size(): number; + /** + * Gets another `DataSnapshot` for the location at the specified relative path. + * + * Passing a relative path to the `child()` method of a DataSnapshot returns + * another `DataSnapshot` for the location at the specified relative path. The + * relative path can either be a simple child name (for example, "ada") or a + * deeper, slash-separated path (for example, "ada/name/first"). If the child + * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot` + * whose value is `null`) is returned. + * + * @param path - A relative path to the location of child data. + */ + child(path: string): DataSnapshot; + /** + * Returns true if this `DataSnapshot` contains any data. It is slightly more + * efficient than using `snapshot.val() !== null`. + */ + exists(): boolean; + /** + * Exports the entire contents of the DataSnapshot as a JavaScript object. + * + * The `exportVal()` method is similar to `val()`, except priority information + * is included (if available), making it suitable for backing up your data. + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + exportVal(): any; + /** + * Enumerates the top-level children in the `IteratedDataSnapshot`. + * + * Because of the way JavaScript objects work, the ordering of data in the + * JavaScript object returned by `val()` is not guaranteed to match the + * ordering on the server nor the ordering of `onChildAdded()` events. That is + * where `forEach()` comes in handy. It guarantees the children of a + * `DataSnapshot` will be iterated in their query order. + * + * If no explicit `orderBy*()` method is used, results are returned + * ordered by key (unless priorities are used, in which case, results are + * returned by priority). + * + * @param action - A function that will be called for each child DataSnapshot. + * The callback can return true to cancel further enumeration. + * @returns true if enumeration was canceled due to your callback returning + * true. + */ + forEach(action: (child: IteratedDataSnapshot) => boolean | void): boolean; + /** + * Returns true if the specified child path has (non-null) data. + * + * @param path - A relative path to the location of a potential child. + * @returns `true` if data exists at the specified child path; else + * `false`. + */ + hasChild(path: string): boolean; + /** + * Returns whether or not the `DataSnapshot` has any non-`null` child + * properties. + * + * You can use `hasChildren()` to determine if a `DataSnapshot` has any + * children. If it does, you can enumerate them using `forEach()`. If it + * doesn't, then either this snapshot contains a primitive value (which can be + * retrieved with `val()`) or it is empty (in which case, `val()` will return + * `null`). + * + * @returns true if this snapshot has any children; else false. + */ + hasChildren(): boolean; + /** + * Returns a JSON-serializable representation of this object. + */ + toJSON(): object | null; + /** + * Extracts a JavaScript value from a `DataSnapshot`. + * + * Depending on the data in a `DataSnapshot`, the `val()` method may return a + * scalar type (string, number, or boolean), an array, or an object. It may + * also return null, indicating that the `DataSnapshot` is empty (contains no + * data). + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + val(): any; +} +export { EmulatorMockTokenOptions } + +/** + * Logs debugging information to the console. + * + * @param enabled - Enables logging if `true`, disables logging if `false`. + * @param persistent - Remembers the logging state between page refreshes if + * `true`. + */ +export declare function enableLogging(enabled: boolean, persistent?: boolean): any; + +/** + * Logs debugging information to the console. + * + * @param logger - A custom logger function to control how things get logged. + */ +export declare function enableLogging(logger: (message: string) => unknown): any; + +/** + * Creates a `QueryConstraint` with the specified ending point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name less than or equal + * to the specified key. + * + * You can read more about `endAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to end at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end at, among the children with the previously + * specified priority. This argument is only allowed if ordering by child, + * value, or priority. + */ +export declare function endAt(value: number | string | boolean | null, key?: string): QueryConstraint; + +/** + * Creates a `QueryConstraint` with the specified ending point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is exclusive. If only a value is provided, children + * with a value less than the specified value will be included in the query. + * If a key is specified, then children must have a value less than or equal + * to the specified value and a key name less than the specified key. + * + * @param value - The value to end before. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end before, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +export declare function endBefore(value: number | string | boolean | null, key?: string): QueryConstraint; + +/** + * Creates a `QueryConstraint` that includes children that match the specified + * value. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The optional key argument can be used to further limit the range of the + * query. If it is specified, then children that have exactly the specified + * value must also have exactly the specified key as their key name. This can be + * used to filter result sets with many matches for the same value. + * + * You can read more about `equalTo()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to match for. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +export declare function equalTo(value: number | string | boolean | null, key?: string): QueryConstraint; + +/** + * Encapsulates the data needed to raise an event + * @interface + */ +declare interface Event_2 { + getPath(): Path; + getEventType(): string; + getEventRunner(): () => void; + toString(): string; +} + +/** + * An EventGenerator is used to convert "raw" changes (Change) as computed by the + * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges() + * for details. + * + */ +declare class EventGenerator { + query_: QueryContext; + index_: Index; + constructor(query_: QueryContext); +} + +declare interface EventList { + events: Event_2[]; + path: Path; +} + +/** + * The event queue serves a few purposes: + * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more + * events being queued. + * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events, + * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call + * left off, ensuring that the events are still raised synchronously and in order. + * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued + * events are raised synchronously. + * + * NOTE: This can all go away if/when we move to async events. + * + */ +declare class EventQueue { + eventLists_: EventList[]; + /** + * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes. + */ + recursionDepth_: number; +} + +/** + * An EventRegistration is basically an event type ('value', 'child_added', etc.) and a callback + * to be notified of that type of event. + * + * That said, it can also contain a cancel callback to be notified if the event is canceled. And + * currently, this code is organized around the idea that you would register multiple child_ callbacks + * together, as a single EventRegistration. Though currently we don't do that. + */ +declare interface EventRegistration { + /** + * True if this container has a callback to trigger for this event type + */ + respondsTo(eventType: string): boolean; + createEvent(change: Change, query: QueryContext): Event_2; + /** + * Given event data, return a function to trigger the user's callback + */ + getEventRunner(eventData: Event_2): () => void; + createCancelEvent(error: Error, path: Path): CancelEvent | null; + matches(other: EventRegistration): boolean; + /** + * False basically means this is a "dummy" callback container being used as a sentinel + * to remove all callback containers of a particular type. (e.g. if the user does + * ref.off('value') without specifying a specific callback). + * + * (TODO: Rework this, since it's hacky) + * + */ + hasAnyCallback(): boolean; +} + +/** + * One of the following strings: "value", "child_added", "child_changed", + * "child_removed", or "child_moved." + */ +export declare type EventType = 'value' | 'child_added' | 'child_changed' | 'child_moved' | 'child_removed'; + +/** + * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL. + */ +export declare function forceLongPolling(): void; + +/** + * Force the use of websockets instead of longPolling. + */ +export declare function forceWebSockets(): void; + +/** + * Gets the most up-to-date result for this query. + * + * @param query - The query to run. + * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is + * available, or rejects if the client is unable to return a value (e.g., if the + * server is unreachable and there is nothing cached). + */ +export declare function get(query: Query): Promise; + +/** + * Returns the instance of the Realtime Database SDK that is associated with the provided + * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if + * no instance exists or if the existing instance uses a custom database URL. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime + * Database instance is associated with. + * @param url - The URL of the Realtime Database instance to connect to. If not + * provided, the SDK connects to the default instance of the Firebase App. + * @returns The `Database` instance of the provided app. + */ +export declare function getDatabase(app?: FirebaseApp, url?: string): Database; + +/** + * Disconnects from the server (all Database operations will be completed + * offline). + * + * The client automatically maintains a persistent connection to the Database + * server, which will remain active indefinitely and reconnect when + * disconnected. However, the `goOffline()` and `goOnline()` methods may be used + * to control the client connection in cases where a persistent connection is + * undesirable. + * + * While offline, the client will no longer receive data updates from the + * Database. However, all Database operations performed locally will continue to + * immediately fire events, allowing your application to continue behaving + * normally. Additionally, each operation performed locally will automatically + * be queued and retried upon reconnection to the Database server. + * + * To reconnect to the Database and begin receiving remote events, see + * `goOnline()`. + * + * @param db - The instance to disconnect. + */ +export declare function goOffline(db: Database): void; + +/** + * Reconnects to the server and synchronizes the offline Database state + * with the server state. + * + * This method should be used after disabling the active connection with + * `goOffline()`. Once reconnected, the client will transmit the proper data + * and fire the appropriate events so that your client "catches up" + * automatically. + * + * @param db - The instance to reconnect. + */ +export declare function goOnline(db: Database): void; + +/** + * A tree with immutable elements. + */ +declare class ImmutableTree { + readonly value: T | null; + readonly children: SortedMap>; + static fromObject(obj: { + [k: string]: T; + }): ImmutableTree; + constructor(value: T | null, children?: SortedMap>); + /** + * True if the value is empty and there are no children + */ + isEmpty(): boolean; + /** + * Given a path and predicate, return the first node and the path to that node + * where the predicate returns true. + * + * TODO Do a perf test -- If we're creating a bunch of `{path: value:}` + * objects on the way back out, it may be better to pass down a pathSoFar obj. + * + * @param relativePath - The remainder of the path + * @param predicate - The predicate to satisfy to return a node + */ + findRootMostMatchingPathAndValue(relativePath: Path, predicate: (a: T) => boolean): { + path: Path; + value: T; + } | null; + /** + * Find, if it exists, the shortest subpath of the given path that points a defined + * value in the tree + */ + findRootMostValueAndPath(relativePath: Path): { + path: Path; + value: T; + } | null; + /** + * @returns The subtree at the given path + */ + subtree(relativePath: Path): ImmutableTree; + /** + * Sets a value at the specified path. + * + * @param relativePath - Path to set value at. + * @param toSet - Value to set. + * @returns Resulting tree. + */ + set(relativePath: Path, toSet: T | null): ImmutableTree; + /** + * Removes the value at the specified path. + * + * @param relativePath - Path to value to remove. + * @returns Resulting tree. + */ + remove(relativePath: Path): ImmutableTree; + /** + * Gets a value from the tree. + * + * @param relativePath - Path to get value for. + * @returns Value at path, or null. + */ + get(relativePath: Path): T | null; + /** + * Replace the subtree at the specified path with the given new tree. + * + * @param relativePath - Path to replace subtree for. + * @param newTree - New tree. + * @returns Resulting tree. + */ + setTree(relativePath: Path, newTree: ImmutableTree): ImmutableTree; + /** + * Performs a depth first fold on this tree. Transforms a tree into a single + * value, given a function that operates on the path to a node, an optional + * current value, and a map of child names to folded subtrees + */ + fold(fn: (path: Path, value: T, children: { + [k: string]: V; + }) => V): V; + /** + * Recursive helper for public-facing fold() method + */ + private fold_; + /** + * Find the first matching value on the given path. Return the result of applying f to it. + */ + findOnPath(path: Path, f: (path: Path, value: T) => V | null): V | null; + private findOnPath_; + foreachOnPath(path: Path, f: (path: Path, value: T) => void): ImmutableTree; + private foreachOnPath_; + /** + * Calls the given function for each node in the tree that has a value. + * + * @param f - A function to be called with the path from the root of the tree to + * a node, and the value at that node. Called in depth-first order. + */ + foreach(f: (path: Path, value: T) => void): void; + private foreach_; + foreachChild(f: (name: string, value: T) => void): void; +} + +/** + * Returns a placeholder value that can be used to atomically increment the + * current database value by the provided delta. + * + * @param delta - the amount to modify the current value atomically. + * @returns A placeholder value for modifying data atomically server-side. + */ +export declare function increment(delta: number): object; + +declare abstract class Index { + abstract compare(a: NamedNode, b: NamedNode): number; + abstract isDefinedOn(node: Node_2): boolean; + /** + * @returns A standalone comparison function for + * this index + */ + getCompare(): Comparator; + /** + * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different, + * it's possible that the changes are isolated to parts of the snapshot that are not indexed. + * + * + * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode + */ + indexedValueChanged(oldNode: Node_2, newNode: Node_2): boolean; + /** + * @returns a node wrapper that will sort equal to or less than + * any other node wrapper, using this index + */ + minPost(): NamedNode; + /** + * @returns a node wrapper that will sort greater than or equal to + * any other node wrapper, using this index + */ + abstract maxPost(): NamedNode; + abstract makePost(indexValue: unknown, name: string): NamedNode; + /** + * @returns String representation for inclusion in a query spec + */ + abstract toString(): string; +} + +/** + * Used by console to create a database based on the app, + * passed database URL and a custom auth implementation. + * @internal + * @param app - A valid FirebaseApp-like object + * @param url - A valid Firebase databaseURL + * @param version - custom version e.g. firebase-admin version + * @param customAppCheckImpl - custom app check implementation + * @param customAuthImpl - custom auth implementation + */ +export declare function _initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, nodeAdmin }: { + app: FirebaseApp_2; + url: string; + version: string; + customAuthImpl: FirebaseAuthInternal; + customAppCheckImpl?: FirebaseAppCheckInternal; + nodeAdmin?: boolean; +}): Database; + +/** + * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined. + */ +export declare interface IteratedDataSnapshot extends DataSnapshot { + key: string; +} + +/** + * Creates a new `QueryConstraint` that if limited to the first specific number + * of children. + * + * The `limitToFirst()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the first 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToFirst()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +export declare function limitToFirst(limit: number): QueryConstraint; + +/** + * Creates a new `QueryConstraint` that is limited to return only the last + * specified number of children. + * + * The `limitToLast()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the last 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToLast()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +export declare function limitToLast(limit: number): QueryConstraint; + +/** An options objects that can be used to customize a listener. */ +export declare interface ListenOptions { + /** Whether to remove the listener after its first invocation. */ + readonly onlyOnce?: boolean; +} + +declare interface ListenProvider { + startListening(query: QueryContext, tag: number | null, hashFn: () => string, onComplete: (a: string, b?: unknown) => Event_2[]): Event_2[]; + stopListening(a: QueryContext, b: number | null): void; +} + +/** + * Represents an empty node (a leaf node in the Red-Black Tree). + */ +declare class LLRBEmptyNode { + key: K; + value: V; + left: LLRBNode | LLRBEmptyNode; + right: LLRBNode | LLRBEmptyNode; + color: boolean; + /** + * Returns a copy of the current node. + * + * @returns The node copy. + */ + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBEmptyNode; + /** + * Returns a copy of the tree, with the specified key/value added. + * + * @param key - Key to be added. + * @param value - Value to be added. + * @param comparator - Comparator. + * @returns New tree, with item added. + */ + insert(key: K, value: V, comparator: Comparator): LLRBNode; + /** + * Returns a copy of the tree, with the specified key removed. + * + * @param key - The key to remove. + * @param comparator - Comparator. + * @returns New tree, with item removed. + */ + remove(key: K, comparator: Comparator): LLRBEmptyNode; + /** + * @returns The total number of nodes in the tree. + */ + count(): number; + /** + * @returns True if the tree is empty. + */ + isEmpty(): boolean; + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + inorderTraversal(action: (k: K, v: V) => unknown): boolean; + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action: (k: K, v: V) => void): boolean; + minKey(): null; + maxKey(): null; + check_(): number; + /** + * @returns Whether this node is red. + */ + isRed_(): boolean; +} + +/** + * Represents a node in a Left-leaning Red-Black tree. + */ +declare class LLRBNode { + key: K; + value: V; + color: boolean; + left: LLRBNode | LLRBEmptyNode; + right: LLRBNode | LLRBEmptyNode; + /** + * @param key - Key associated with this node. + * @param value - Value associated with this node. + * @param color - Whether this node is red. + * @param left - Left child. + * @param right - Right child. + */ + constructor(key: K, value: V, color: boolean | null, left?: LLRBNode | LLRBEmptyNode | null, right?: LLRBNode | LLRBEmptyNode | null); + static RED: boolean; + static BLACK: boolean; + /** + * Returns a copy of the current node, optionally replacing pieces of it. + * + * @param key - New key for the node, or null. + * @param value - New value for the node, or null. + * @param color - New color for the node, or null. + * @param left - New left child for the node, or null. + * @param right - New right child for the node, or null. + * @returns The node copy. + */ + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBNode; + /** + * @returns The total number of nodes in the tree. + */ + count(): number; + /** + * @returns True if the tree is empty. + */ + isEmpty(): boolean; + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action: (k: K, v: V) => unknown): boolean; + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action: (k: K, v: V) => void): boolean; + /** + * @returns The minimum node in the tree. + */ + private min_; + /** + * @returns The maximum key in the tree. + */ + minKey(): K; + /** + * @returns The maximum key in the tree. + */ + maxKey(): K; + /** + * @param key - Key to insert. + * @param value - Value to insert. + * @param comparator - Comparator. + * @returns New tree, with the key/value added. + */ + insert(key: K, value: V, comparator: Comparator): LLRBNode; + /** + * @returns New tree, with the minimum key removed. + */ + private removeMin_; + /** + * @param key - The key of the item to remove. + * @param comparator - Comparator. + * @returns New tree, with the specified item removed. + */ + remove(key: K, comparator: Comparator): LLRBNode | LLRBEmptyNode; + /** + * @returns Whether this is a RED node. + */ + isRed_(): boolean; + /** + * @returns New tree after performing any needed rotations. + */ + private fixUp_; + /** + * @returns New tree, after moveRedLeft. + */ + private moveRedLeft_; + /** + * @returns New tree, after moveRedRight. + */ + private moveRedRight_; + /** + * @returns New tree, after rotateLeft. + */ + private rotateLeft_; + /** + * @returns New tree, after rotateRight. + */ + private rotateRight_; + /** + * @returns Newt ree, after colorFlip. + */ + private colorFlip_; + /** + * For testing. + * + * @returns True if all is well. + */ + private checkMaxDepth_; + check_(): number; +} + +declare class NamedNode { + name: string; + node: Node_2; + constructor(name: string, node: Node_2); + static Wrap(name: string, node: Node_2): NamedNode; +} + +/** + * Node is an interface defining the common functionality for nodes in + * a DataSnapshot. + * + * @interface + */ +declare interface Node_2 { + /** + * Whether this node is a leaf node. + * @returns Whether this is a leaf node. + */ + isLeafNode(): boolean; + /** + * Gets the priority of the node. + * @returns The priority of the node. + */ + getPriority(): Node_2; + /** + * Returns a duplicate node with the new priority. + * @param newPriorityNode - New priority to set for the node. + * @returns Node with new priority. + */ + updatePriority(newPriorityNode: Node_2): Node_2; + /** + * Returns the specified immediate child, or null if it doesn't exist. + * @param childName - The name of the child to retrieve. + * @returns The retrieved child, or an empty node. + */ + getImmediateChild(childName: string): Node_2; + /** + * Returns a child by path, or null if it doesn't exist. + * @param path - The path of the child to retrieve. + * @returns The retrieved child or an empty node. + */ + getChild(path: Path): Node_2; + /** + * Returns the name of the child immediately prior to the specified childNode, or null. + * @param childName - The name of the child to find the predecessor of. + * @param childNode - The node to find the predecessor of. + * @param index - The index to use to determine the predecessor + * @returns The name of the predecessor child, or null if childNode is the first child. + */ + getPredecessorChildName(childName: string, childNode: Node_2, index: Index): string | null; + /** + * Returns a duplicate node, with the specified immediate child updated. + * Any value in the node will be removed. + * @param childName - The name of the child to update. + * @param newChildNode - The new child node + * @returns The updated node. + */ + updateImmediateChild(childName: string, newChildNode: Node_2): Node_2; + /** + * Returns a duplicate node, with the specified child updated. Any value will + * be removed. + * @param path - The path of the child to update. + * @param newChildNode - The new child node, which may be an empty node + * @returns The updated node. + */ + updateChild(path: Path, newChildNode: Node_2): Node_2; + /** + * True if the immediate child specified exists + */ + hasChild(childName: string): boolean; + /** + * @returns True if this node has no value or children. + */ + isEmpty(): boolean; + /** + * @returns The number of children of this node. + */ + numChildren(): number; + /** + * Calls action for each child. + * @param action - Action to be called for + * each child. It's passed the child name and the child node. + * @returns The first truthy value return by action, or the last falsey one + */ + forEachChild(index: Index, action: (a: string, b: Node_2) => void): unknown; + /** + * @param exportFormat - True for export format (also wire protocol format). + * @returns Value of this node as JSON. + */ + val(exportFormat?: boolean): unknown; + /** + * @returns hash representing the node contents. + */ + hash(): string; + /** + * @param other - Another node + * @returns -1 for less than, 0 for equal, 1 for greater than other + */ + compareTo(other: Node_2): number; + /** + * @returns Whether or not this snapshot equals other + */ + equals(other: Node_2): boolean; + /** + * @returns This node, with the specified index now available + */ + withIndex(indexDefinition: Index): Node_2; + isIndexed(indexDefinition: Index): boolean; +} + +/** + * NodeFilter is used to update nodes and complete children of nodes while applying queries on the fly and keeping + * track of any child changes. This class does not track value changes as value changes depend on more + * than just the node itself. Different kind of queries require different kind of implementations of this interface. + * @interface + */ +declare interface NodeFilter_2 { + /** + * Update a single complete child in the snap. If the child equals the old child in the snap, this is a no-op. + * The method expects an indexed snap. + */ + updateChild(snap: Node_2, key: string, newChild: Node_2, affectedPath: Path, source: CompleteChildSource, optChangeAccumulator: ChildChangeAccumulator | null): Node_2; + /** + * Update a node in full and output any resulting change from this complete update. + */ + updateFullNode(oldSnap: Node_2, newSnap: Node_2, optChangeAccumulator: ChildChangeAccumulator | null): Node_2; + /** + * Update the priority of the root node + */ + updatePriority(oldSnap: Node_2, newPriority: Node_2): Node_2; + /** + * Returns true if children might be filtered due to query criteria + */ + filtersNodes(): boolean; + /** + * Returns the index filter that this filter uses to get a NodeFilter that doesn't filter any children. + */ + getIndexedFilter(): NodeFilter_2; + /** + * Returns the index that this filter uses + */ + getIndex(): Index; +} + +/** + * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener. + * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from + * the respective `on*` callbacks. + * + * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener + * will not automatically remove listeners registered on child nodes, `off()` + * must also be called on any child listeners to remove the callback. + * + * If a callback is not specified, all callbacks for the specified eventType + * will be removed. Similarly, if no eventType is specified, all callbacks + * for the `Reference` will be removed. + * + * Individual listeners can also be removed by invoking their unsubscribe + * callbacks. + * + * @param query - The query that the listener was registered with. + * @param eventType - One of the following strings: "value", "child_added", + * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks + * for the `Reference` will be removed. + * @param callback - The callback function that was passed to `on()` or + * `undefined` to remove all callbacks. + */ +export declare function off(query: Query, eventType?: EventType, callback?: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown): void; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, options: ListenOptions): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; + +/** + * The `onDisconnect` class allows you to write or clear data when your client + * disconnects from the Database server. These updates occur whether your + * client disconnects cleanly or not, so you can rely on them to clean up data + * even if a connection is dropped or a client crashes. + * + * The `onDisconnect` class is most commonly used to manage presence in + * applications where it is useful to detect how many clients are connected and + * when other clients disconnect. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * To avoid problems when a connection is dropped before the requests can be + * transferred to the Database server, these functions should be called before + * writing any data. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time you reconnect. + */ +export declare class OnDisconnect { + private _repo; + private _path; + /** @hideconstructor */ + constructor(_repo: Repo, _path: Path); + /** + * Cancels all previously queued `onDisconnect()` set or update events for this + * location and all children. + * + * If a write has been queued for this location via a `set()` or `update()` at a + * parent location, the write at this location will be canceled, though writes + * to sibling locations will still occur. + * + * @returns Resolves when synchronization to the server is complete. + */ + cancel(): Promise; + /** + * Ensures the data at this location is deleted when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + * + * @returns Resolves when synchronization to the server is complete. + */ + remove(): Promise; + /** + * Ensures the data at this location is set to the specified value when the + * client is disconnected (due to closing the browser, navigating to a new page, + * or network issues). + * + * `set()` is especially useful for implementing "presence" systems, where a + * value should be changed or cleared when a user disconnects so that they + * appear "offline" to other users. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time. + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + set(value: unknown): Promise; + /** + * Ensures the data at this location is set to the specified value and priority + * when the client is disconnected (due to closing the browser, navigating to a + * new page, or network issues). + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + setWithPriority(value: unknown, priority: number | string | null): Promise; + /** + * Writes multiple values at this location when the client is disconnected (due + * to closing the browser, navigating to a new page, or network issues). + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, "name/first") + * from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * @param values - Object containing multiple values. + * @returns Resolves when synchronization to the Database is complete. + */ + update(values: object): Promise; +} + +/** + * Returns an `OnDisconnect` object - see + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information on how to use it. + * + * @param ref - The reference to add OnDisconnect triggers for. + */ +export declare function onDisconnect(ref: DatabaseReference): OnDisconnect; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, options: ListenOptions): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; + +/** + * Creates a new `QueryConstraint` that orders by the specified child key. + * + * Queries can only order by one key at a time. Calling `orderByChild()` + * multiple times on the same query is an error. + * + * Firebase queries allow you to order your data by any child key on the fly. + * However, if you know in advance what your indexes will be, you can define + * them via the .indexOn rule in your Security Rules for better performance. See + * the{@link https://firebase.google.com/docs/database/security/indexing-data} + * rule for more information. + * + * You can read more about `orderByChild()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + * + * @param path - The path to order by. + */ +export declare function orderByChild(path: string): QueryConstraint; + +/** + * Creates a new `QueryConstraint` that orders by the key. + * + * Sorts the results of a query by their (ascending) key values. + * + * You can read more about `orderByKey()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +export declare function orderByKey(): QueryConstraint; + +/** + * Creates a new `QueryConstraint` that orders by priority. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data} + * for alternatives to priority. + */ +export declare function orderByPriority(): QueryConstraint; + +/** + * Creates a new `QueryConstraint` that orders by value. + * + * If the children of a query are all scalar values (string, number, or + * boolean), you can order the results by their (ascending) values. + * + * You can read more about `orderByValue()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +export declare function orderByValue(): QueryConstraint; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a parsed path. It's immutable so that you + * can pass them around to other functions without worrying about them changing + * it. + */ +declare class Path { + pieces_: string[]; + pieceNum_: number; + /** + * @param pathOrString - Path string to parse, or another path, or the raw + * tokens array + */ + constructor(pathOrString: string | string[], pieceNum?: number); + toString(): string; +} + +/** + * Firebase connection. Abstracts wire protocol and handles reconnecting. + * + * NOTE: All JSON objects sent to the realtime connection must have property names enclosed + * in quotes to make sure the closure compiler does not minify them. + */ +declare class PersistentConnection extends ServerActions { + private repoInfo_; + private applicationId_; + private onDataUpdate_; + private onConnectStatus_; + private onServerInfoUpdate_; + private authTokenProvider_; + private appCheckTokenProvider_; + private authOverride_?; + id: number; + private log_; + private interruptReasons_; + private readonly listens; + private outstandingPuts_; + private outstandingGets_; + private outstandingPutCount_; + private outstandingGetCount_; + private onDisconnectRequestQueue_; + private connected_; + private reconnectDelay_; + private maxReconnectDelay_; + private securityDebugCallback_; + lastSessionId: string | null; + private establishConnectionTimer_; + private visible_; + private requestCBHash_; + private requestNumber_; + private realtime_; + private authToken_; + private appCheckToken_; + private forceTokenRefresh_; + private invalidAuthTokenCount_; + private invalidAppCheckTokenCount_; + private firstConnection_; + private lastConnectionAttemptTime_; + private lastConnectionEstablishedTime_; + private static nextPersistentConnectionId_; + /** + * Counter for number of connections created. Mainly used for tagging in the logs + */ + private static nextConnectionId_; + /** + * @param repoInfo_ - Data about the namespace we are connecting to + * @param applicationId_ - The Firebase App ID for this project + * @param onDataUpdate_ - A callback for new data from the server + */ + constructor(repoInfo_: RepoInfo, applicationId_: string, onDataUpdate_: (a: string, b: unknown, c: boolean, d: number | null) => void, onConnectStatus_: (a: boolean) => void, onServerInfoUpdate_: (a: unknown) => void, authTokenProvider_: AuthTokenProvider, appCheckTokenProvider_: AppCheckTokenProvider, authOverride_?: object | null); + protected sendRequest(action: string, body: unknown, onResponse?: (a: unknown) => void): void; + get(query: QueryContext): Promise; + listen(query: QueryContext, currentHashFn: () => string, tag: number | null, onComplete: (a: string, b: unknown) => void): void; + private sendGet_; + private sendListen_; + private static warnOnListenWarnings_; + refreshAuthToken(token: string): void; + private reduceReconnectDelayIfAdminCredential_; + refreshAppCheckToken(token: string | null): void; + /** + * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like + * a auth revoked (the connection is closed). + */ + tryAuth(): void; + /** + * Attempts to authenticate with the given token. If the authentication + * attempt fails, it's triggered like the token was revoked (the connection is + * closed). + */ + tryAppCheck(): void; + /** + * @inheritDoc + */ + unlisten(query: QueryContext, tag: number | null): void; + private sendUnlisten_; + onDisconnectPut(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void): void; + onDisconnectMerge(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void): void; + onDisconnectCancel(pathString: string, onComplete?: (a: string, b: string) => void): void; + private sendOnDisconnect_; + put(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void, hash?: string): void; + merge(pathString: string, data: unknown, onComplete: (a: string, b: string | null) => void, hash?: string): void; + putInternal(action: string, pathString: string, data: unknown, onComplete: (a: string, b: string | null) => void, hash?: string): void; + private sendPut_; + reportStats(stats: { + [k: string]: unknown; + }): void; + private onDataMessage_; + private onDataPush_; + private onReady_; + private scheduleConnect_; + private initConnection_; + private onVisible_; + private onOnline_; + private onRealtimeDisconnect_; + private establishConnection_; + interrupt(reason: string): void; + resume(reason: string): void; + private handleTimestamp_; + private cancelSentTransactions_; + private onListenRevoked_; + private removeListen_; + private onAuthRevoked_; + private onAppCheckRevoked_; + private onSecurityDebugPacket_; + private restoreState_; + /** + * Sends client stats for first connection + */ + private sendConnectStats_; + private shouldReconnect_; +} + +declare class PriorityIndex extends Index { + compare(a: NamedNode, b: NamedNode): number; + isDefinedOn(node: Node_2): boolean; + indexedValueChanged(oldNode: Node_2, newNode: Node_2): boolean; + minPost(): NamedNode; + maxPost(): NamedNode; + makePost(indexValue: unknown, name: string): NamedNode; + /** + * @returns String representation for inclusion in a query spec + */ + toString(): string; +} + +/** + * Generates a new child location using a unique key and returns its + * `Reference`. + * + * This is the most common pattern for adding data to a collection of items. + * + * If you provide a value to `push()`, the value is written to the + * generated location. If you don't pass a value, nothing is written to the + * database and the child remains empty (but you can use the `Reference` + * elsewhere). + * + * The unique keys generated by `push()` are ordered by the current time, so the + * resulting list of items is chronologically sorted. The keys are also + * designed to be unguessable (they contain 72 random bits of entropy). + * + * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}. + * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}. + * + * @param parent - The parent location. + * @param value - Optional value to be written at the generated location. + * @returns Combined `Promise` and `Reference`; resolves when write is complete, + * but can be used immediately as the `Reference` to the child location. + */ +export declare function push(parent: DatabaseReference, value?: unknown): ThenableReference; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` sorts and filters the data at a Database location so only a subset + * of the child data is included. This can be used to order a collection of + * data by some attribute (for example, height of dinosaurs) as well as to + * restrict a large list of items (for example, chat messages) down to a number + * suitable for synchronizing to the client. Queries are created by chaining + * together one or more of the filter methods defined here. + * + * Just as with a `DatabaseReference`, you can receive data from a `Query` by using the + * `on*()` methods. You will only receive events and `DataSnapshot`s for the + * subset of the data that matches your query. + * + * See {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data} + * for more information. + */ +export declare interface Query extends QueryContext { + /** The `DatabaseReference` for the `Query`'s location. */ + readonly ref: DatabaseReference; + /** + * Returns whether or not the current and provided queries represent the same + * location, have the same query parameters, and are from the same instance of + * `FirebaseApp`. + * + * Two `DatabaseReference` objects are equivalent if they represent the same location + * and are from the same instance of `FirebaseApp`. + * + * Two `Query` objects are equivalent if they represent the same location, + * have the same query parameters, and are from the same instance of + * `FirebaseApp`. Equivalent queries share the same sort order, limits, and + * starting and ending points. + * + * @param other - The query to compare against. + * @returns Whether or not the current and provided queries are equivalent. + */ + isEqual(other: Query | null): boolean; + /** + * Returns a JSON-serializable representation of this object. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON(): string; + /** + * Gets the absolute URL for this location. + * + * The `toString()` method returns a URL that is ready to be put into a + * browser, curl command, or a `refFromURL()` call. Since all of those expect + * the URL to be url-encoded, `toString()` returns an encoded URL. + * + * Append '.json' to the returned URL when typed into a browser to download + * JSON-formatted data. If the location is secured (that is, not publicly + * readable), you will get a permission-denied error. + * + * @returns The absolute URL for this location. + */ + toString(): string; +} + +/** + * Creates a new immutable instance of `Query` that is extended to also include + * additional query constraints. + * + * @param query - The Query instance to use as a base for the new constraints. + * @param queryConstraints - The list of `QueryConstraint`s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query; + +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Database query. `QueryConstraint`s are created by invoking {@link endAt}, + * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link + * limitToFirst}, {@link limitToLast}, {@link orderByChild}, + * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} , + * {@link orderByValue} or {@link equalTo} and + * can then be passed to {@link query} to create a new query instance that + * also contains this `QueryConstraint`. + */ +export declare abstract class QueryConstraint { + /** The type of this query constraints */ + abstract readonly type: QueryConstraintType; + /** + * Takes the provided `Query` and returns a copy of the `Query` with this + * `QueryConstraint` applied. + */ + abstract _apply(query: _QueryImpl): _QueryImpl; +} + +/** Describes the different query constraints available in this SDK. */ +export declare type QueryConstraintType = 'endAt' | 'endBefore' | 'startAt' | 'startAfter' | 'limitToFirst' | 'limitToLast' | 'orderByChild' | 'orderByKey' | 'orderByPriority' | 'orderByValue' | 'equalTo'; + +declare interface QueryContext { + readonly _queryIdentifier: string; + readonly _queryObject: object; + readonly _repo: Repo; + readonly _path: Path; + readonly _queryParams: _QueryParams; +} + +/** + * @internal + */ +export declare class _QueryImpl implements Query, QueryContext { + readonly _repo: Repo; + readonly _path: Path; + readonly _queryParams: _QueryParams; + readonly _orderByCalled: boolean; + /** + * @hideconstructor + */ + constructor(_repo: Repo, _path: Path, _queryParams: _QueryParams, _orderByCalled: boolean); + get key(): string | null; + get ref(): DatabaseReference; + get _queryIdentifier(): string; + /** + * An object representation of the query parameters used by this Query. + */ + get _queryObject(): object; + isEqual(other: _QueryImpl | null): boolean; + toJSON(): string; + toString(): string; +} + +/** + * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a + * range to be returned for a particular location. It is assumed that validation of parameters is done at the + * user-facing API level, so it is not done here. + * + * @internal + */ +export declare class _QueryParams { + limitSet_: boolean; + startSet_: boolean; + startNameSet_: boolean; + startAfterSet_: boolean; + endSet_: boolean; + endNameSet_: boolean; + endBeforeSet_: boolean; + limit_: number; + viewFrom_: string; + indexStartValue_: unknown | null; + indexStartName_: string; + indexEndValue_: unknown | null; + indexEndName_: string; + index_: PriorityIndex; + hasStart(): boolean; + /** + * @returns True if it would return from left. + */ + isViewFromLeft(): boolean; + /** + * Only valid to call if hasStart() returns true + */ + getIndexStartValue(): unknown; + /** + * Only valid to call if hasStart() returns true. + * Returns the starting key name for the range defined by these query parameters + */ + getIndexStartName(): string; + hasEnd(): boolean; + /** + * Only valid to call if hasEnd() returns true. + */ + getIndexEndValue(): unknown; + /** + * Only valid to call if hasEnd() returns true. + * Returns the end key name for the range defined by these query parameters + */ + getIndexEndName(): string; + hasLimit(): boolean; + /** + * @returns True if a limit has been set and it has been explicitly anchored + */ + hasAnchoredLimit(): boolean; + /** + * Only valid to call if hasLimit() returns true + */ + getLimit(): number; + getIndex(): Index; + loadsAllData(): boolean; + isDefault(): boolean; + copy(): _QueryParams; +} + +/** + * + * Returns a `Reference` representing the location in the Database + * corresponding to the provided path. If no path is provided, the `Reference` + * will point to the root of the Database. + * + * @param db - The database instance to obtain a reference for. + * @param path - Optional path representing the location the returned + * `Reference` will point. If not provided, the returned `Reference` will + * point to the root of the Database. + * @returns If a path is provided, a `Reference` + * pointing to the provided path. Otherwise, a `Reference` pointing to the + * root of the Database. + */ +export declare function ref(db: Database, path?: string): DatabaseReference; + +/** + * @internal + */ +export declare class _ReferenceImpl extends _QueryImpl implements DatabaseReference { + /** @hideconstructor */ + constructor(repo: Repo, path: Path); + get parent(): _ReferenceImpl | null; + get root(): _ReferenceImpl; +} + +/** + * Returns a `Reference` representing the location in the Database + * corresponding to the provided Firebase URL. + * + * An exception is thrown if the URL is not a valid Firebase Database URL or it + * has a different domain than the current `Database` instance. + * + * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored + * and are not applied to the returned `Reference`. + * + * @param db - The database instance to obtain a reference for. + * @param url - The Firebase URL at which the returned `Reference` will + * point. + * @returns A `Reference` pointing to the provided + * Firebase URL. + */ +export declare function refFromURL(db: Database, url: string): DatabaseReference; + +/** + * Removes the data at this Database location. + * + * Any data at child locations will also be deleted. + * + * The effect of the remove will be visible immediately and the corresponding + * event 'value' will be triggered. Synchronization of the remove to the + * Firebase servers will also be started, and the returned Promise will resolve + * when complete. If provided, the onComplete callback will be called + * asynchronously after synchronization has finished. + * + * @param ref - The location to remove. + * @returns Resolves when remove on server is complete. + */ +export declare function remove(ref: DatabaseReference): Promise; + +/** + * A connection to a single data repository. + */ +declare class Repo { + repoInfo_: RepoInfo; + forceRestClient_: boolean; + authTokenProvider_: AuthTokenProvider; + appCheckProvider_: AppCheckTokenProvider; + /** Key for uniquely identifying this repo, used in RepoManager */ + readonly key: string; + dataUpdateCount: number; + infoSyncTree_: SyncTree; + serverSyncTree_: SyncTree; + stats_: StatsCollection; + statsListener_: StatsListener | null; + eventQueue_: EventQueue; + nextWriteId_: number; + server_: ServerActions; + statsReporter_: StatsReporter; + infoData_: SnapshotHolder; + interceptServerDataCallback_: ((a: string, b: unknown) => void) | null; + /** A list of data pieces and paths to be set when this client disconnects. */ + onDisconnect_: SparseSnapshotTree; + /** Stores queues of outstanding transactions for Firebase locations. */ + transactionQueueTree_: Tree; + persistentConnection_: PersistentConnection | null; + constructor(repoInfo_: RepoInfo, forceRestClient_: boolean, authTokenProvider_: AuthTokenProvider, appCheckProvider_: AppCheckTokenProvider); + /** + * @returns The URL corresponding to the root of this Firebase. + */ + toString(): string; +} + +/** + * A class that holds metadata about a Repo object + */ +declare class RepoInfo { + readonly secure: boolean; + readonly namespace: string; + readonly webSocketOnly: boolean; + readonly nodeAdmin: boolean; + readonly persistenceKey: string; + readonly includeNamespaceInQueryParams: boolean; + readonly isUsingEmulator: boolean; + readonly emulatorOptions: RepoInfoEmulatorOptions | null; + private _host; + private _domain; + internalHost: string; + /** + * @param host - Hostname portion of the url for the repo + * @param secure - Whether or not this repo is accessed over ssl + * @param namespace - The namespace represented by the repo + * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest). + * @param nodeAdmin - Whether this instance uses Admin SDK credentials + * @param persistenceKey - Override the default session persistence storage key + */ + constructor(host: string, secure: boolean, namespace: string, webSocketOnly: boolean, nodeAdmin?: boolean, persistenceKey?: string, includeNamespaceInQueryParams?: boolean, isUsingEmulator?: boolean, emulatorOptions?: RepoInfoEmulatorOptions | null); + isCacheableHost(): boolean; + isCustomHost(): boolean; + get host(): string; + set host(newHost: string); + toString(): string; + toURLString(): string; +} + +declare interface RepoInfoEmulatorOptions { + mockUserToken?: string | EmulatorMockTokenOptions; +} + +/** + * This function should only ever be called to CREATE a new database instance. + * @internal + */ +export declare function _repoManagerDatabaseFromApp(app: FirebaseApp, authProvider: Provider, appCheckProvider?: Provider, url?: string, nodeAdmin?: boolean): Database; + +/** + * Atomically modifies the data at this location. + * + * Atomically modify the data at this location. Unlike a normal `set()`, which + * just overwrites the data regardless of its previous value, `runTransaction()` is + * used to modify the existing value to a new value, ensuring there are no + * conflicts with other clients writing to the same location at the same time. + * + * To accomplish this, you pass `runTransaction()` an update function which is + * used to transform the current value into a new value. If another client + * writes to the location before your new value is successfully written, your + * update function will be called again with the new current value, and the + * write will be retried. This will happen repeatedly until your write succeeds + * without conflict or you abort the transaction by not returning a value from + * your update function. + * + * Note: Modifying data with `set()` will cancel any pending transactions at + * that location, so extreme care should be taken if mixing `set()` and + * `runTransaction()` to update the same data. + * + * Note: When using transactions with Security and Firebase Rules in place, be + * aware that a client needs `.read` access in addition to `.write` access in + * order to perform a transaction. This is because the client-side nature of + * transactions requires the client to read the data in order to transactionally + * update it. + * + * @param ref - The location to atomically modify. + * @param transactionUpdate - A developer-supplied function which will be passed + * the current data stored at this location (as a JavaScript object). The + * function should return the new value it would like written (as a JavaScript + * object). If `undefined` is returned (i.e. you return with no arguments) the + * transaction will be aborted and the data at this location will not be + * modified. + * @param options - An options object to configure transactions. + * @returns A `Promise` that can optionally be used instead of the `onComplete` + * callback to handle success and failure. + */ +export declare function runTransaction(ref: DatabaseReference, transactionUpdate: (currentData: any) => unknown, options?: TransactionOptions): Promise; + +/** + * Interface defining the set of actions that can be performed against the Firebase server + * (basically corresponds to our wire protocol). + * + * @interface + */ +declare abstract class ServerActions { + abstract listen(query: QueryContext, currentHashFn: () => string, tag: number | null, onComplete: (a: string, b: unknown) => void): void; + /** + * Remove a listen. + */ + abstract unlisten(query: QueryContext, tag: number | null): void; + /** + * Get the server value satisfying this query. + */ + abstract get(query: QueryContext): Promise; + put(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void, hash?: string): void; + merge(pathString: string, data: unknown, onComplete: (a: string, b: string | null) => void, hash?: string): void; + /** + * Refreshes the auth token for the current connection. + * @param token - The authentication token + */ + refreshAuthToken(token: string): void; + /** + * Refreshes the app check token for the current connection. + * @param token The app check token + */ + refreshAppCheckToken(token: string): void; + onDisconnectPut(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void): void; + onDisconnectMerge(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void): void; + onDisconnectCancel(pathString: string, onComplete?: (a: string, b: string) => void): void; + reportStats(stats: { + [k: string]: unknown; + }): void; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a placeholder value for auto-populating the current timestamp (time + * since the Unix epoch, in milliseconds) as determined by the Firebase + * servers. + */ +export declare function serverTimestamp(): object; + +/** + * Writes data to this Database location. + * + * This will overwrite any data at this location and all child locations. + * + * The effect of the write will be visible immediately, and the corresponding + * events ("value", "child_added", etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * Passing `null` for the new value is equivalent to calling `remove()`; namely, + * all data at this location and all child locations will be deleted. + * + * `set()` will remove any priority stored at this location, so if priority is + * meant to be preserved, you need to use `setWithPriority()` instead. + * + * Note that modifying data with `set()` will cancel any pending transactions + * at that location, so extreme care should be taken if mixing `set()` and + * `transaction()` to modify the same data. + * + * A single `set()` will generate a single "value" event at the location where + * the `set()` was performed. + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @returns Resolves when write to server is complete. + */ +export declare function set(ref: DatabaseReference, value: unknown): Promise; + +/** + * Sets a priority for the data at this Database location. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +export declare function setPriority(ref: DatabaseReference, priority: string | number | null): Promise; + +/** + * SDK_VERSION should be set before any database instance is created + * @internal + */ +export declare function _setSDKVersion(version: string): void; + +/** + * Writes data the Database location. Like `set()` but also specifies the + * priority for that data. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +export declare function setWithPriority(ref: DatabaseReference, value: unknown, priority: string | number | null): Promise; + +/** + * Mutable object which basically just stores a reference to the "latest" immutable snapshot. + */ +declare class SnapshotHolder { + private rootNode_; + getNode(path: Path): Node_2; + updateSnapshot(path: Path, newSnapshotNode: Node_2): void; +} + +/** + * An immutable sorted map implementation, based on a Left-leaning Red-Black + * tree. + */ +declare class SortedMap { + private comparator_; + private root_; + /** + * Always use the same empty node, to reduce memory. + */ + static EMPTY_NODE: LLRBEmptyNode; + /** + * @param comparator_ - Key comparator. + * @param root_ - Optional root node for the map. + */ + constructor(comparator_: Comparator, root_?: LLRBNode | LLRBEmptyNode); + /** + * Returns a copy of the map, with the specified key/value added or replaced. + * (TODO: We should perhaps rename this method to 'put') + * + * @param key - Key to be added. + * @param value - Value to be added. + * @returns New map, with item added. + */ + insert(key: K, value: V): SortedMap; + /** + * Returns a copy of the map, with the specified key removed. + * + * @param key - The key to remove. + * @returns New map, with item removed. + */ + remove(key: K): SortedMap; + /** + * Returns the value of the node with the given key, or null. + * + * @param key - The key to look up. + * @returns The value of the node with the given key, or null if the + * key doesn't exist. + */ + get(key: K): V | null; + /** + * Returns the key of the item *before* the specified key, or null if key is the first item. + * @param key - The key to find the predecessor of + * @returns The predecessor key. + */ + getPredecessorKey(key: K): K | null; + /** + * @returns True if the map is empty. + */ + isEmpty(): boolean; + /** + * @returns The total number of nodes in the map. + */ + count(): number; + /** + * @returns The minimum key in the map. + */ + minKey(): K | null; + /** + * @returns The maximum key in the map. + */ + maxKey(): K | null; + /** + * Traverses the map in key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action: (k: K, v: V) => unknown): boolean; + /** + * Traverses the map in reverse key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns True if the traversal was aborted. + */ + reverseTraversal(action: (k: K, v: V) => void): boolean; + /** + * Returns an iterator over the SortedMap. + * @returns The iterator. + */ + getIterator(resultGenerator?: (k: K, v: V) => T): SortedMapIterator; + getIteratorFrom(key: K, resultGenerator?: (k: K, v: V) => T): SortedMapIterator; + getReverseIteratorFrom(key: K, resultGenerator?: (k: K, v: V) => T): SortedMapIterator; + getReverseIterator(resultGenerator?: (k: K, v: V) => T): SortedMapIterator; +} + +/** + * An iterator over an LLRBNode. + */ +declare class SortedMapIterator { + private isReverse_; + private resultGenerator_; + private nodeStack_; + /** + * @param node - Node to iterate. + * @param isReverse_ - Whether or not to iterate in reverse + */ + constructor(node: LLRBNode | LLRBEmptyNode, startKey: K | null, comparator: Comparator, isReverse_: boolean, resultGenerator_?: ((k: K, v: V) => T) | null); + getNext(): T; + hasNext(): boolean; + peek(): T; +} + +/** + * Helper class to store a sparse set of snapshots. + */ +declare interface SparseSnapshotTree { + value: Node_2 | null; + readonly children: Map; +} + +/** + * Creates a `QueryConstraint` with the specified starting point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is exclusive. If only a value is provided, children + * with a value greater than the specified value will be included in the query. + * If a key is specified, then children must have a value greater than or equal + * to the specified value and a a key name greater than the specified key. + * + * @param value - The value to start after. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start after. This argument is only allowed if + * ordering by child, value, or priority. + */ +export declare function startAfter(value: number | string | boolean | null, key?: string): QueryConstraint; + +/** + * Creates a `QueryConstraint` with the specified starting point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name greater than or + * equal to the specified key. + * + * You can read more about `startAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to start at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at. This argument is only allowed if + * ordering by child, value, or priority. + */ +export declare function startAt(value?: number | string | boolean | null, key?: string): QueryConstraint; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Tracks a collection of stats. + */ +declare class StatsCollection { + private counters_; + incrementCounter(name: string, amount?: number): void; + get(): { + [k: string]: number; + }; +} + +/** + * Returns the delta from the previous call to get stats. + * + * @param collection_ - The collection to "listen" to. + */ +declare class StatsListener { + private collection_; + private last_; + constructor(collection_: StatsCollection); + get(): { + [k: string]: number; + }; +} + +declare class StatsReporter { + private server_; + private statsListener_; + statsToReport_: { + [k: string]: boolean; + }; + constructor(collection: StatsCollection, server_: ServerActions); + private reportStats_; +} + +/** + * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to + * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes + * and user writes (set, transaction, update). + * + * It's responsible for: + * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed). + * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite, + * applyUserOverwrite, etc.) + */ +declare class SyncPoint { + /** + * The Views being tracked at this location in the tree, stored as a map where the key is a + * queryId and the value is the View for that query. + * + * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case). + */ + readonly views: Map; +} + +/** + * SyncTree is the central class for managing event callback registration, data caching, views + * (query processing), and event generation. There are typically two SyncTree instances for + * each Repo, one for the normal Firebase data, and one for the .info data. + * + * It has a number of responsibilities, including: + * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()). + * - Applying and caching data changes for user set(), transaction(), and update() calls + * (applyUserOverwrite(), applyUserMerge()). + * - Applying and caching data changes for server data changes (applyServerOverwrite(), + * applyServerMerge()). + * - Generating user-facing events for server and user changes (all of the apply* methods + * return the set of events that need to be raised as a result). + * - Maintaining the appropriate set of server listens to ensure we are always subscribed + * to the correct set of paths and queries to satisfy the current set of user event + * callbacks (listens are started/stopped using the provided listenProvider). + * + * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual + * events are returned to the caller rather than raised synchronously. + * + */ +declare class SyncTree { + listenProvider_: ListenProvider; + /** + * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views. + */ + syncPointTree_: ImmutableTree; + /** + * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.). + */ + pendingWriteTree_: WriteTree; + readonly tagToQueryMap: Map; + readonly queryToTagMap: Map; + /** + * @param listenProvider_ - Used by SyncTree to start / stop listening + * to server data. + */ + constructor(listenProvider_: ListenProvider); +} + +/** + * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection. + * @internal + */ +export declare const _TEST_ACCESS_forceRestClient: (forceRestClient: boolean) => void; + +/** + * @internal + */ +export declare const _TEST_ACCESS_hijackHash: (newHash: () => string) => () => void; + +/** + * A `Promise` that can also act as a `DatabaseReference` when returned by + * {@link push}. The reference is available immediately and the `Promise` resolves + * as the write to the backend completes. + */ +export declare interface ThenableReference extends DatabaseReference, Pick, 'then' | 'catch'> { + key: string; + parent: DatabaseReference; +} + +declare interface Transaction { + path: Path; + update: (a: unknown) => unknown; + onComplete: (error: Error | null, committed: boolean, node: Node_2 | null) => void; + status: TransactionStatus; + order: number; + applyLocally: boolean; + retryCount: number; + unwatcher: () => void; + abortReason: string | null; + currentWriteId: number; + currentInputSnapshot: Node_2 | null; + currentOutputSnapshotRaw: Node_2 | null; + currentOutputSnapshotResolved: Node_2 | null; +} + +/** An options object to configure transactions. */ +export declare interface TransactionOptions { + /** + * By default, events are raised each time the transaction update function + * runs. So if it is run multiple times, you may see intermediate states. You + * can set this to false to suppress these intermediate states and instead + * wait until the transaction has completed before events are raised. + */ + readonly applyLocally?: boolean; +} + +/** + * A type for the resolve value of {@link runTransaction}. + */ +export declare class TransactionResult { + /** Whether the transaction was successfully committed. */ + readonly committed: boolean; + /** The resulting data snapshot. */ + readonly snapshot: DataSnapshot; + /** @hideconstructor */ + constructor( + /** Whether the transaction was successfully committed. */ + committed: boolean, + /** The resulting data snapshot. */ + snapshot: DataSnapshot); + /** Returns a JSON-serializable representation of this object. */ + toJSON(): object; +} + +declare const enum TransactionStatus { + RUN = 0, + SENT = 1, + COMPLETED = 2, + SENT_NEEDS_ABORT = 3, + NEEDS_ABORT = 4 +} + +/** + * A light-weight tree, traversable by path. Nodes can have both values and children. + * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty + * children. + */ +declare class Tree { + readonly name: string; + readonly parent: Tree | null; + node: TreeNode; + /** + * @param name - Optional name of the node. + * @param parent - Optional parent node. + * @param node - Optional node to wrap. + */ + constructor(name?: string, parent?: Tree | null, node?: TreeNode); +} + +/** + * Node in a Tree. + */ +declare interface TreeNode { + children: Record>; + childCount: number; + value?: T; +} + +/** A callback that can invoked to remove a listener. */ +export declare type Unsubscribe = () => void; + +/** + * Writes multiple values to the Database at once. + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, + * "name/first") from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * The effect of the write will be visible immediately, and the corresponding + * events ('value', 'child_added', etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * A single `update()` will generate a single "value" event at the location + * where the `update()` was performed, regardless of how many children were + * modified. + * + * Note that modifying data with `update()` will cancel any pending + * transactions at that location, so extreme care should be taken if mixing + * `update()` and `transaction()` to modify the same data. + * + * Passing `null` to `update()` will remove the data at this location. + * + * See + * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}. + * + * @param ref - The location to write to. + * @param values - Object containing multiple values. + * @returns Resolves when update on server is complete. + */ +export declare function update(ref: DatabaseReference, values: object): Promise; + +/** + * A user callback. Callbacks issues from the Legacy SDK maintain references + * to the original user-issued callbacks, which allows equality + * comparison by reference even though this callbacks are wrapped before + * they can be passed to the firebase@exp SDK. + * + * @internal + */ +export declare interface _UserCallback { + (dataSnapshot: DataSnapshot, previousChildName?: string | null): unknown; + userCallback?: unknown; + context?: object | null; +} + +/** + * @internal + */ +export declare const _validatePathString: (fnName: string, argumentName: string, pathString: string, optional: boolean) => void; + +/** + * @internal + */ +export declare const _validateWritablePath: (fnName: string, path: Path) => void; + +/** + * A view represents a specific location and query that has 1 or more event registrations. + * + * It does several things: + * - Maintains the list of event registrations for this location/query. + * - Maintains a cache of the data visible for this location/query. + * - Applies new operations (via applyOperation), updates the cache, and based on the event + * registrations returns the set of events to be raised. + */ +declare class View { + private query_; + processor_: ViewProcessor; + viewCache_: ViewCache; + eventRegistrations_: EventRegistration[]; + eventGenerator_: EventGenerator; + constructor(query_: QueryContext, initialViewCache: ViewCache); + get query(): QueryContext; +} + +/** + * Stores the data we have cached for a view. + * + * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes). + */ +declare interface ViewCache { + readonly eventCache: CacheNode; + readonly serverCache: CacheNode; +} + +declare interface ViewProcessor { + readonly filter: NodeFilter_2; +} + +/** + * Defines a single user-initiated write operation. May be the result of a set(), transaction(), or update() call. In + * the case of a set() or transaction, snap will be non-null. In the case of an update(), children will be non-null. + */ +declare interface WriteRecord { + writeId: number; + path: Path; + snap?: Node_2 | null; + children?: { + [k: string]: Node_2; + } | null; + visible: boolean; +} + +/** + * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them + * with underlying server data (to create "event cache" data). Pending writes are added with addOverwrite() + * and addMerge(), and removed with removeWrite(). + */ +declare interface WriteTree { + /** + * A tree tracking the result of applying all visible writes. This does not include transactions with + * applyLocally=false or writes that are completely shadowed by other writes. + */ + visibleWrites: CompoundWrite; + /** + * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary + * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also + * used by transactions). + */ + allWrites: WriteRecord[]; + lastWriteId: number; +} + +export { } diff --git a/node_modules/@firebase/database/dist/node-esm/index.node.esm.js b/node_modules/@firebase/database/dist/node-esm/index.node.esm.js new file mode 100644 index 0000000..ed287dd --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/index.node.esm.js @@ -0,0 +1,14048 @@ +import Websocket from 'faye-websocket'; +import { stringify, jsonEval, contains, assert, isNodeSdk, stringToByteArray, Sha1, base64, deepCopy, base64Encode, isMobileCordova, stringLength, Deferred, safeGet, isAdmin, isValidFormat, isEmpty, isReactNative, assertionError, map, querystring, errorPrefix, getModularInstance, getDefaultEmulatorHostnameAndPort, deepEqual, createMockUserToken, isCloudWorkstation, pingServer, updateEmulatorBanner } from '@firebase/util'; +import { Logger, LogLevel } from '@firebase/logger'; +import { _isFirebaseServerApp, _getProvider, getApp, SDK_VERSION as SDK_VERSION$1, _registerComponent, registerVersion } from '@firebase/app'; +import { Component, ComponentContainer, Provider } from '@firebase/component'; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const PROTOCOL_VERSION = '5'; +const VERSION_PARAM = 'v'; +const TRANSPORT_SESSION_PARAM = 's'; +const REFERER_PARAM = 'r'; +const FORGE_REF = 'f'; +// Matches console.firebase.google.com, firebase-console-*.corp.google.com and +// firebase.corp.google.com +const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/; +const LAST_SESSION_PARAM = 'ls'; +const APPLICATION_ID_PARAM = 'p'; +const APP_CHECK_TOKEN_PARAM = 'ac'; +const WEBSOCKET = 'websocket'; +const LONG_POLLING = 'long_polling'; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Wraps a DOM Storage object and: + * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types. + * - prefixes names with "firebase:" to avoid collisions with app data. + * + * We automatically (see storage.js) create two such wrappers, one for sessionStorage, + * and one for localStorage. + * + */ +class DOMStorageWrapper { + /** + * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage) + */ + constructor(domStorage_) { + this.domStorage_ = domStorage_; + // Use a prefix to avoid collisions with other stuff saved by the app. + this.prefix_ = 'firebase:'; + } + /** + * @param key - The key to save the value under + * @param value - The value being stored, or null to remove the key. + */ + set(key, value) { + if (value == null) { + this.domStorage_.removeItem(this.prefixedName_(key)); + } + else { + this.domStorage_.setItem(this.prefixedName_(key), stringify(value)); + } + } + /** + * @returns The value that was stored under this key, or null + */ + get(key) { + const storedVal = this.domStorage_.getItem(this.prefixedName_(key)); + if (storedVal == null) { + return null; + } + else { + return jsonEval(storedVal); + } + } + remove(key) { + this.domStorage_.removeItem(this.prefixedName_(key)); + } + prefixedName_(name) { + return this.prefix_ + name; + } + toString() { + return this.domStorage_.toString(); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory storage implementation that matches the API of DOMStorageWrapper + * (TODO: create interface for both to implement). + */ +class MemoryStorage { + constructor() { + this.cache_ = {}; + this.isInMemoryStorage = true; + } + set(key, value) { + if (value == null) { + delete this.cache_[key]; + } + else { + this.cache_[key] = value; + } + } + get(key) { + if (contains(this.cache_, key)) { + return this.cache_[key]; + } + return null; + } + remove(key) { + delete this.cache_[key]; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage. + * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change + * to reflect this type + * + * @param domStorageName - Name of the underlying storage object + * (e.g. 'localStorage' or 'sessionStorage'). + * @returns Turning off type information until a common interface is defined. + */ +const createStoragefor = function (domStorageName) { + try { + // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception, + // so it must be inside the try/catch. + if (typeof window !== 'undefined' && + typeof window[domStorageName] !== 'undefined') { + // Need to test cache. Just because it's here doesn't mean it works + const domStorage = window[domStorageName]; + domStorage.setItem('firebase:sentinel', 'cache'); + domStorage.removeItem('firebase:sentinel'); + return new DOMStorageWrapper(domStorage); + } + } + catch (e) { } + // Failed to create wrapper. Just return in-memory storage. + // TODO: log? + return new MemoryStorage(); +}; +/** A storage object that lasts across sessions */ +const PersistentStorage = createStoragefor('localStorage'); +/** A storage object that only lasts one session */ +const SessionStorage = createStoragefor('sessionStorage'); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const logClient = new Logger('@firebase/database'); +/** + * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called). + */ +const LUIDGenerator = (function () { + let id = 1; + return function () { + return id++; + }; +})(); +/** + * Sha1 hash of the input string + * @param str - The string to hash + * @returns {!string} The resulting hash + */ +const sha1 = function (str) { + const utf8Bytes = stringToByteArray(str); + const sha1 = new Sha1(); + sha1.update(utf8Bytes); + const sha1Bytes = sha1.digest(); + return base64.encodeByteArray(sha1Bytes); +}; +const buildLogMessage_ = function (...varArgs) { + let message = ''; + for (let i = 0; i < varArgs.length; i++) { + const arg = varArgs[i]; + if (Array.isArray(arg) || + (arg && + typeof arg === 'object' && + // eslint-disable-next-line @typescript-eslint/no-explicit-any + typeof arg.length === 'number')) { + message += buildLogMessage_.apply(null, arg); + } + else if (typeof arg === 'object') { + message += stringify(arg); + } + else { + message += arg; + } + message += ' '; + } + return message; +}; +/** + * Use this for all debug messages in Firebase. + */ +let logger = null; +/** + * Flag to check for log availability on first log message + */ +let firstLog_ = true; +/** + * The implementation of Firebase.enableLogging (defined here to break dependencies) + * @param logger_ - A flag to turn on logging, or a custom logger + * @param persistent - Whether or not to persist logging settings across refreshes + */ +const enableLogging$1 = function (logger_, persistent) { + assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently."); + if (logger_ === true) { + logClient.logLevel = LogLevel.VERBOSE; + logger = logClient.log.bind(logClient); + if (persistent) { + SessionStorage.set('logging_enabled', true); + } + } + else if (typeof logger_ === 'function') { + logger = logger_; + } + else { + logger = null; + SessionStorage.remove('logging_enabled'); + } +}; +const log = function (...varArgs) { + if (firstLog_ === true) { + firstLog_ = false; + if (logger === null && SessionStorage.get('logging_enabled') === true) { + enableLogging$1(true); + } + } + if (logger) { + const message = buildLogMessage_.apply(null, varArgs); + logger(message); + } +}; +const logWrapper = function (prefix) { + return function (...varArgs) { + log(prefix, ...varArgs); + }; +}; +const error = function (...varArgs) { + const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs); + logClient.error(message); +}; +const fatal = function (...varArgs) { + const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`; + logClient.error(message); + throw new Error(message); +}; +const warn = function (...varArgs) { + const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs); + logClient.warn(message); +}; +/** + * Logs a warning if the containing page uses https. Called when a call to new Firebase + * does not use https. + */ +const warnIfPageIsSecure = function () { + // Be very careful accessing browser globals. Who knows what may or may not exist. + if (typeof window !== 'undefined' && + window.location && + window.location.protocol && + window.location.protocol.indexOf('https:') !== -1) { + warn('Insecure Firebase access from a secure page. ' + + 'Please use https in calls to new Firebase().'); + } +}; +/** + * Returns true if data is NaN, or +/- Infinity. + */ +const isInvalidJSONNumber = function (data) { + return (typeof data === 'number' && + (data !== data || // NaN + data === Number.POSITIVE_INFINITY || + data === Number.NEGATIVE_INFINITY)); +}; +const executeWhenDOMReady = function (fn) { + if (isNodeSdk() || document.readyState === 'complete') { + fn(); + } + else { + // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which + // fire before onload), but fall back to onload. + let called = false; + const wrappedFn = function () { + if (!document.body) { + setTimeout(wrappedFn, Math.floor(10)); + return; + } + if (!called) { + called = true; + fn(); + } + }; + if (document.addEventListener) { + document.addEventListener('DOMContentLoaded', wrappedFn, false); + // fallback to onload. + window.addEventListener('load', wrappedFn, false); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (document.attachEvent) { + // IE. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + document.attachEvent('onreadystatechange', () => { + if (document.readyState === 'complete') { + wrappedFn(); + } + }); + // fallback to onload. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + window.attachEvent('onload', wrappedFn); + // jQuery has an extra hack for IE that we could employ (based on + // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old. + // I'm hoping we don't need it. + } + } +}; +/** + * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names + */ +const MIN_NAME = '[MIN_NAME]'; +/** + * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names + */ +const MAX_NAME = '[MAX_NAME]'; +/** + * Compares valid Firebase key names, plus min and max name + */ +const nameCompare = function (a, b) { + if (a === b) { + return 0; + } + else if (a === MIN_NAME || b === MAX_NAME) { + return -1; + } + else if (b === MIN_NAME || a === MAX_NAME) { + return 1; + } + else { + const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b); + if (aAsInt !== null) { + if (bAsInt !== null) { + return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt; + } + else { + return -1; + } + } + else if (bAsInt !== null) { + return 1; + } + else { + return a < b ? -1 : 1; + } + } +}; +/** + * @returns {!number} comparison result. + */ +const stringCompare = function (a, b) { + if (a === b) { + return 0; + } + else if (a < b) { + return -1; + } + else { + return 1; + } +}; +const requireKey = function (key, obj) { + if (obj && key in obj) { + return obj[key]; + } + else { + throw new Error('Missing required key (' + key + ') in object: ' + stringify(obj)); + } +}; +const ObjectToUniqueKey = function (obj) { + if (typeof obj !== 'object' || obj === null) { + return stringify(obj); + } + const keys = []; + // eslint-disable-next-line guard-for-in + for (const k in obj) { + keys.push(k); + } + // Export as json, but with the keys sorted. + keys.sort(); + let key = '{'; + for (let i = 0; i < keys.length; i++) { + if (i !== 0) { + key += ','; + } + key += stringify(keys[i]); + key += ':'; + key += ObjectToUniqueKey(obj[keys[i]]); + } + key += '}'; + return key; +}; +/** + * Splits a string into a number of smaller segments of maximum size + * @param str - The string + * @param segsize - The maximum number of chars in the string. + * @returns The string, split into appropriately-sized chunks + */ +const splitStringBySize = function (str, segsize) { + const len = str.length; + if (len <= segsize) { + return [str]; + } + const dataSegs = []; + for (let c = 0; c < len; c += segsize) { + if (c + segsize > len) { + dataSegs.push(str.substring(c, len)); + } + else { + dataSegs.push(str.substring(c, c + segsize)); + } + } + return dataSegs; +}; +/** + * Apply a function to each (key, value) pair in an object or + * apply a function to each (index, value) pair in an array + * @param obj - The object or array to iterate over + * @param fn - The function to apply + */ +function each(obj, fn) { + for (const key in obj) { + if (obj.hasOwnProperty(key)) { + fn(key, obj[key]); + } + } +} +/** + * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License) + * I made one modification at the end and removed the NaN / Infinity + * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments. + * @param v - A double + * + */ +const doubleToIEEE754String = function (v) { + assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL + const ebits = 11, fbits = 52; + const bias = (1 << (ebits - 1)) - 1; + let s, e, f, ln, i; + // Compute sign, exponent, fraction + // Skip NaN / Infinity handling --MJL. + if (v === 0) { + e = 0; + f = 0; + s = 1 / v === -Infinity ? 1 : 0; + } + else { + s = v < 0; + v = Math.abs(v); + if (v >= Math.pow(2, 1 - bias)) { + // Normalized + ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias); + e = ln + bias; + f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits)); + } + else { + // Denormalized + e = 0; + f = Math.round(v / Math.pow(2, 1 - bias - fbits)); + } + } + // Pack sign, exponent, fraction + const bits = []; + for (i = fbits; i; i -= 1) { + bits.push(f % 2 ? 1 : 0); + f = Math.floor(f / 2); + } + for (i = ebits; i; i -= 1) { + bits.push(e % 2 ? 1 : 0); + e = Math.floor(e / 2); + } + bits.push(s ? 1 : 0); + bits.reverse(); + const str = bits.join(''); + // Return the data as a hex string. --MJL + let hexByteString = ''; + for (i = 0; i < 64; i += 8) { + let hexByte = parseInt(str.substr(i, 8), 2).toString(16); + if (hexByte.length === 1) { + hexByte = '0' + hexByte; + } + hexByteString = hexByteString + hexByte; + } + return hexByteString.toLowerCase(); +}; +/** + * Used to detect if we're in a Chrome content script (which executes in an + * isolated environment where long-polling doesn't work). + */ +const isChromeExtensionContentScript = function () { + return !!(typeof window === 'object' && + window['chrome'] && + window['chrome']['extension'] && + !/^chrome/.test(window.location.href)); +}; +/** + * Used to detect if we're in a Windows 8 Store app. + */ +const isWindowsStoreApp = function () { + // Check for the presence of a couple WinRT globals + return typeof Windows === 'object' && typeof Windows.UI === 'object'; +}; +/** + * Converts a server error code to a JavaScript Error + */ +function errorForServerCode(code, query) { + let reason = 'Unknown Error'; + if (code === 'too_big') { + reason = + 'The data requested exceeds the maximum size ' + + 'that can be accessed with a single request.'; + } + else if (code === 'permission_denied') { + reason = "Client doesn't have permission to access the desired data."; + } + else if (code === 'unavailable') { + reason = 'The service is unavailable'; + } + const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error.code = code.toUpperCase(); + return error; +} +/** + * Used to test for integer-looking strings + */ +const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$'); +/** + * For use in keys, the minimum possible 32-bit integer. + */ +const INTEGER_32_MIN = -2147483648; +/** + * For use in keys, the maximum possible 32-bit integer. + */ +const INTEGER_32_MAX = 2147483647; +/** + * If the string contains a 32-bit integer, return it. Else return null. + */ +const tryParseInt = function (str) { + if (INTEGER_REGEXP_.test(str)) { + const intVal = Number(str); + if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) { + return intVal; + } + } + return null; +}; +/** + * Helper to run some code but catch any exceptions and re-throw them later. + * Useful for preventing user callbacks from breaking internal code. + * + * Re-throwing the exception from a setTimeout is a little evil, but it's very + * convenient (we don't have to try to figure out when is a safe point to + * re-throw it), and the behavior seems reasonable: + * + * * If you aren't pausing on exceptions, you get an error in the console with + * the correct stack trace. + * * If you're pausing on all exceptions, the debugger will pause on your + * exception and then again when we rethrow it. + * * If you're only pausing on uncaught exceptions, the debugger will only pause + * on us re-throwing it. + * + * @param fn - The code to guard. + */ +const exceptionGuard = function (fn) { + try { + fn(); + } + catch (e) { + // Re-throw exception when it's safe. + setTimeout(() => { + // It used to be that "throw e" would result in a good console error with + // relevant context, but as of Chrome 39, you just get the firebase.js + // file/line number where we re-throw it, which is useless. So we log + // e.stack explicitly. + const stack = e.stack || ''; + warn('Exception was thrown by user callback.', stack); + throw e; + }, Math.floor(0)); + } +}; +/** + * @returns {boolean} true if we think we're currently being crawled. + */ +const beingCrawled = function () { + const userAgent = (typeof window === 'object' && + window['navigator'] && + window['navigator']['userAgent']) || + ''; + // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we + // believe to support JavaScript/AJAX rendering. + // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website + // would have seen the page" is flaky if we don't treat it as a crawler. + return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0); +}; +/** + * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting. + * + * It is removed with clearTimeout() as normal. + * + * @param fn - Function to run. + * @param time - Milliseconds to wait before running. + * @returns The setTimeout() return value. + */ +const setTimeoutNonBlocking = function (fn, time) { + const timeout = setTimeout(fn, time); + // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API. + if (typeof timeout === 'number' && + // @ts-ignore Is only defined in Deno environments. + typeof Deno !== 'undefined' && + // @ts-ignore Deno and unrefTimer are only defined in Deno environments. + Deno['unrefTimer']) { + // @ts-ignore Deno and unrefTimer are only defined in Deno environments. + Deno.unrefTimer(timeout); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (typeof timeout === 'object' && timeout['unref']) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + timeout['unref'](); + } + return timeout; +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A class that holds metadata about a Repo object + */ +class RepoInfo { + /** + * @param host - Hostname portion of the url for the repo + * @param secure - Whether or not this repo is accessed over ssl + * @param namespace - The namespace represented by the repo + * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest). + * @param nodeAdmin - Whether this instance uses Admin SDK credentials + * @param persistenceKey - Override the default session persistence storage key + */ + constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false, isUsingEmulator = false, emulatorOptions = null) { + this.secure = secure; + this.namespace = namespace; + this.webSocketOnly = webSocketOnly; + this.nodeAdmin = nodeAdmin; + this.persistenceKey = persistenceKey; + this.includeNamespaceInQueryParams = includeNamespaceInQueryParams; + this.isUsingEmulator = isUsingEmulator; + this.emulatorOptions = emulatorOptions; + this._host = host.toLowerCase(); + this._domain = this._host.substr(this._host.indexOf('.') + 1); + this.internalHost = + PersistentStorage.get('host:' + host) || this._host; + } + isCacheableHost() { + return this.internalHost.substr(0, 2) === 's-'; + } + isCustomHost() { + return (this._domain !== 'firebaseio.com' && + this._domain !== 'firebaseio-demo.com'); + } + get host() { + return this._host; + } + set host(newHost) { + if (newHost !== this.internalHost) { + this.internalHost = newHost; + if (this.isCacheableHost()) { + PersistentStorage.set('host:' + this._host, this.internalHost); + } + } + } + toString() { + let str = this.toURLString(); + if (this.persistenceKey) { + str += '<' + this.persistenceKey + '>'; + } + return str; + } + toURLString() { + const protocol = this.secure ? 'https://' : 'http://'; + const query = this.includeNamespaceInQueryParams + ? `?ns=${this.namespace}` + : ''; + return `${protocol}${this.host}/${query}`; + } +} +function repoInfoNeedsQueryParam(repoInfo) { + return (repoInfo.host !== repoInfo.internalHost || + repoInfo.isCustomHost() || + repoInfo.includeNamespaceInQueryParams); +} +/** + * Returns the websocket URL for this repo + * @param repoInfo - RepoInfo object + * @param type - of connection + * @param params - list + * @returns The URL for this repo + */ +function repoInfoConnectionURL(repoInfo, type, params) { + assert(typeof type === 'string', 'typeof type must == string'); + assert(typeof params === 'object', 'typeof params must == object'); + let connURL; + if (type === WEBSOCKET) { + connURL = + (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?'; + } + else if (type === LONG_POLLING) { + connURL = + (repoInfo.secure ? 'https://' : 'http://') + + repoInfo.internalHost + + '/.lp?'; + } + else { + throw new Error('Unknown connection type: ' + type); + } + if (repoInfoNeedsQueryParam(repoInfo)) { + params['ns'] = repoInfo.namespace; + } + const pairs = []; + each(params, (key, value) => { + pairs.push(key + '=' + value); + }); + return connURL + pairs.join('&'); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Tracks a collection of stats. + */ +class StatsCollection { + constructor() { + this.counters_ = {}; + } + incrementCounter(name, amount = 1) { + if (!contains(this.counters_, name)) { + this.counters_[name] = 0; + } + this.counters_[name] += amount; + } + get() { + return deepCopy(this.counters_); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const collections = {}; +const reporters = {}; +function statsManagerGetCollection(repoInfo) { + const hashString = repoInfo.toString(); + if (!collections[hashString]) { + collections[hashString] = new StatsCollection(); + } + return collections[hashString]; +} +function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) { + const hashString = repoInfo.toString(); + if (!reporters[hashString]) { + reporters[hashString] = creatorFunction(); + } + return reporters[hashString]; +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The semver (www.semver.org) version of the SDK. */ +let SDK_VERSION = ''; +/** + * SDK_VERSION should be set before any database instance is created + * @internal + */ +function setSDKVersion(version) { + SDK_VERSION = version; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const WEBSOCKET_MAX_FRAME_SIZE = 16384; +const WEBSOCKET_KEEPALIVE_INTERVAL = 45000; +let WebSocketImpl = null; +if (typeof MozWebSocket !== 'undefined') { + WebSocketImpl = MozWebSocket; +} +else if (typeof WebSocket !== 'undefined') { + WebSocketImpl = WebSocket; +} +function setWebSocketImpl(impl) { + WebSocketImpl = impl; +} +/** + * Create a new websocket connection with the given callbacks. + */ +class WebSocketConnection { + /** + * @param connId identifier for this transport + * @param repoInfo The info for the websocket endpoint. + * @param applicationId The Firebase App ID for this project. + * @param appCheckToken The App Check Token for this client. + * @param authToken The Auth Token for this client. + * @param transportSessionId Optional transportSessionId if this is connecting + * to an existing transport session + * @param lastSessionId Optional lastSessionId if there was a previous + * connection + */ + constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) { + this.connId = connId; + this.applicationId = applicationId; + this.appCheckToken = appCheckToken; + this.authToken = authToken; + this.keepaliveTimer = null; + this.frames = null; + this.totalFrames = 0; + this.bytesSent = 0; + this.bytesReceived = 0; + this.log_ = logWrapper(this.connId); + this.stats_ = statsManagerGetCollection(repoInfo); + this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId); + this.nodeAdmin = repoInfo.nodeAdmin; + } + /** + * @param repoInfo - The info for the websocket endpoint. + * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport + * session + * @param lastSessionId - Optional lastSessionId if there was a previous connection + * @returns connection url + */ + static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) { + const urlParams = {}; + urlParams[VERSION_PARAM] = PROTOCOL_VERSION; + if (!isNodeSdk() && + typeof location !== 'undefined' && + location.hostname && + FORGE_DOMAIN_RE.test(location.hostname)) { + urlParams[REFERER_PARAM] = FORGE_REF; + } + if (transportSessionId) { + urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId; + } + if (lastSessionId) { + urlParams[LAST_SESSION_PARAM] = lastSessionId; + } + if (appCheckToken) { + urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken; + } + if (applicationId) { + urlParams[APPLICATION_ID_PARAM] = applicationId; + } + return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams); + } + /** + * @param onMessage - Callback when messages arrive + * @param onDisconnect - Callback with connection lost. + */ + open(onMessage, onDisconnect) { + this.onDisconnect = onDisconnect; + this.onMessage = onMessage; + this.log_('Websocket connecting to ' + this.connURL); + this.everConnected_ = false; + // Assume failure until proven otherwise. + PersistentStorage.set('previous_websocket_failure', true); + try { + let options; + if (isNodeSdk()) { + const device = this.nodeAdmin ? 'AdminNode' : 'Node'; + // UA Format: Firebase//// + options = { + headers: { + 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`, + 'X-Firebase-GMPID': this.applicationId || '' + } + }; + // If using Node with admin creds, AppCheck-related checks are unnecessary. + // Note that we send the credentials here even if they aren't admin credentials, which is + // not a problem. + // Note that this header is just used to bypass appcheck, and the token should still be sent + // through the websocket connection once it is established. + if (this.authToken) { + options.headers['Authorization'] = `Bearer ${this.authToken}`; + } + if (this.appCheckToken) { + options.headers['X-Firebase-AppCheck'] = this.appCheckToken; + } + // Plumb appropriate http_proxy environment variable into faye-websocket if it exists. + const env = process['env']; + const proxy = this.connURL.indexOf('wss://') === 0 + ? env['HTTPS_PROXY'] || env['https_proxy'] + : env['HTTP_PROXY'] || env['http_proxy']; + if (proxy) { + options['proxy'] = { origin: proxy }; + } + } + this.mySock = new WebSocketImpl(this.connURL, [], options); + } + catch (e) { + this.log_('Error instantiating WebSocket.'); + const error = e.message || e.data; + if (error) { + this.log_(error); + } + this.onClosed_(); + return; + } + this.mySock.onopen = () => { + this.log_('Websocket connected.'); + this.everConnected_ = true; + }; + this.mySock.onclose = () => { + this.log_('Websocket connection was disconnected.'); + this.mySock = null; + this.onClosed_(); + }; + this.mySock.onmessage = m => { + this.handleIncomingFrame(m); + }; + this.mySock.onerror = e => { + this.log_('WebSocket error. Closing connection.'); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const error = e.message || e.data; + if (error) { + this.log_(error); + } + this.onClosed_(); + }; + } + /** + * No-op for websockets, we don't need to do anything once the connection is confirmed as open + */ + start() { } + static forceDisallow() { + WebSocketConnection.forceDisallow_ = true; + } + static isAvailable() { + let isOldAndroid = false; + if (typeof navigator !== 'undefined' && navigator.userAgent) { + const oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/; + const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex); + if (oldAndroidMatch && oldAndroidMatch.length > 1) { + if (parseFloat(oldAndroidMatch[1]) < 4.4) { + isOldAndroid = true; + } + } + } + return (!isOldAndroid && + WebSocketImpl !== null && + !WebSocketConnection.forceDisallow_); + } + /** + * Returns true if we previously failed to connect with this transport. + */ + static previouslyFailed() { + // If our persistent storage is actually only in-memory storage, + // we default to assuming that it previously failed to be safe. + return (PersistentStorage.isInMemoryStorage || + PersistentStorage.get('previous_websocket_failure') === true); + } + markConnectionHealthy() { + PersistentStorage.remove('previous_websocket_failure'); + } + appendFrame_(data) { + this.frames.push(data); + if (this.frames.length === this.totalFrames) { + const fullMess = this.frames.join(''); + this.frames = null; + const jsonMess = jsonEval(fullMess); + //handle the message + this.onMessage(jsonMess); + } + } + /** + * @param frameCount - The number of frames we are expecting from the server + */ + handleNewFrameCount_(frameCount) { + this.totalFrames = frameCount; + this.frames = []; + } + /** + * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1 + * @returns Any remaining data to be process, or null if there is none + */ + extractFrameCount_(data) { + assert(this.frames === null, 'We already have a frame buffer'); + // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced + // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508 + if (data.length <= 6) { + const frameCount = Number(data); + if (!isNaN(frameCount)) { + this.handleNewFrameCount_(frameCount); + return null; + } + } + this.handleNewFrameCount_(1); + return data; + } + /** + * Process a websocket frame that has arrived from the server. + * @param mess - The frame data + */ + handleIncomingFrame(mess) { + if (this.mySock === null) { + return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes. + } + const data = mess['data']; + this.bytesReceived += data.length; + this.stats_.incrementCounter('bytes_received', data.length); + this.resetKeepAlive(); + if (this.frames !== null) { + // we're buffering + this.appendFrame_(data); + } + else { + // try to parse out a frame count, otherwise, assume 1 and process it + const remainingData = this.extractFrameCount_(data); + if (remainingData !== null) { + this.appendFrame_(remainingData); + } + } + } + /** + * Send a message to the server + * @param data - The JSON object to transmit + */ + send(data) { + this.resetKeepAlive(); + const dataStr = stringify(data); + this.bytesSent += dataStr.length; + this.stats_.incrementCounter('bytes_sent', dataStr.length); + //We can only fit a certain amount in each websocket frame, so we need to split this request + //up into multiple pieces if it doesn't fit in one request. + const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE); + //Send the length header + if (dataSegs.length > 1) { + this.sendString_(String(dataSegs.length)); + } + //Send the actual data in segments. + for (let i = 0; i < dataSegs.length; i++) { + this.sendString_(dataSegs[i]); + } + } + shutdown_() { + this.isClosed_ = true; + if (this.keepaliveTimer) { + clearInterval(this.keepaliveTimer); + this.keepaliveTimer = null; + } + if (this.mySock) { + this.mySock.close(); + this.mySock = null; + } + } + onClosed_() { + if (!this.isClosed_) { + this.log_('WebSocket is closing itself'); + this.shutdown_(); + // since this is an internal close, trigger the close listener + if (this.onDisconnect) { + this.onDisconnect(this.everConnected_); + this.onDisconnect = null; + } + } + } + /** + * External-facing close handler. + * Close the websocket and kill the connection. + */ + close() { + if (!this.isClosed_) { + this.log_('WebSocket is being closed'); + this.shutdown_(); + } + } + /** + * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after + * the last activity. + */ + resetKeepAlive() { + clearInterval(this.keepaliveTimer); + this.keepaliveTimer = setInterval(() => { + //If there has been no websocket activity for a while, send a no-op + if (this.mySock) { + this.sendString_('0'); + } + this.resetKeepAlive(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL)); + } + /** + * Send a string over the websocket. + * + * @param str - String to send. + */ + sendString_(str) { + // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send() + // calls for some unknown reason. We treat these as an error and disconnect. + // See https://app.asana.com/0/58926111402292/68021340250410 + try { + this.mySock.send(str); + } + catch (e) { + this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.'); + setTimeout(this.onClosed_.bind(this), 0); + } + } +} +/** + * Number of response before we consider the connection "healthy." + */ +WebSocketConnection.responsesRequiredToBeHealthy = 2; +/** + * Time to wait for the connection te become healthy before giving up. + */ +WebSocketConnection.healthyTimeout = 30000; + +const name = "@firebase/database"; +const version = "1.1.0"; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Abstraction around AppCheck's token fetching capabilities. + */ +class AppCheckTokenProvider { + constructor(app, appCheckProvider) { + this.appCheckProvider = appCheckProvider; + this.appName = app.name; + if (_isFirebaseServerApp(app) && app.settings.appCheckToken) { + this.serverAppAppCheckToken = app.settings.appCheckToken; + } + this.appCheck = appCheckProvider?.getImmediate({ optional: true }); + if (!this.appCheck) { + appCheckProvider?.get().then(appCheck => (this.appCheck = appCheck)); + } + } + getToken(forceRefresh) { + if (this.serverAppAppCheckToken) { + if (forceRefresh) { + throw new Error('Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.'); + } + return Promise.resolve({ token: this.serverAppAppCheckToken }); + } + if (!this.appCheck) { + return new Promise((resolve, reject) => { + // Support delayed initialization of FirebaseAppCheck. This allows our + // customers to initialize the RTDB SDK before initializing Firebase + // AppCheck and ensures that all requests are authenticated if a token + // becomes available before the timeout below expires. + setTimeout(() => { + if (this.appCheck) { + this.getToken(forceRefresh).then(resolve, reject); + } + else { + resolve(null); + } + }, 0); + }); + } + return this.appCheck.getToken(forceRefresh); + } + addTokenChangeListener(listener) { + this.appCheckProvider + ?.get() + .then(appCheck => appCheck.addTokenListener(listener)); + } + notifyForInvalidToken() { + warn(`Provided AppCheck credentials for the app named "${this.appName}" ` + + 'are invalid. This usually indicates your app was not initialized correctly.'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Abstraction around FirebaseApp's token fetching capabilities. + */ +class FirebaseAuthTokenProvider { + constructor(appName_, firebaseOptions_, authProvider_) { + this.appName_ = appName_; + this.firebaseOptions_ = firebaseOptions_; + this.authProvider_ = authProvider_; + this.auth_ = null; + this.auth_ = authProvider_.getImmediate({ optional: true }); + if (!this.auth_) { + authProvider_.onInit(auth => (this.auth_ = auth)); + } + } + getToken(forceRefresh) { + if (!this.auth_) { + return new Promise((resolve, reject) => { + // Support delayed initialization of FirebaseAuth. This allows our + // customers to initialize the RTDB SDK before initializing Firebase + // Auth and ensures that all requests are authenticated if a token + // becomes available before the timeout below expires. + setTimeout(() => { + if (this.auth_) { + this.getToken(forceRefresh).then(resolve, reject); + } + else { + resolve(null); + } + }, 0); + }); + } + return this.auth_.getToken(forceRefresh).catch(error => { + // TODO: Need to figure out all the cases this is raised and whether + // this makes sense. + if (error && error.code === 'auth/token-not-initialized') { + log('Got auth/token-not-initialized error. Treating as null token.'); + return null; + } + else { + return Promise.reject(error); + } + }); + } + addTokenChangeListener(listener) { + // TODO: We might want to wrap the listener and call it with no args to + // avoid a leaky abstraction, but that makes removing the listener harder. + if (this.auth_) { + this.auth_.addAuthTokenListener(listener); + } + else { + this.authProvider_ + .get() + .then(auth => auth.addAuthTokenListener(listener)); + } + } + removeTokenChangeListener(listener) { + this.authProvider_ + .get() + .then(auth => auth.removeAuthTokenListener(listener)); + } + notifyForInvalidToken() { + let errorMessage = 'Provided authentication credentials for the app named "' + + this.appName_ + + '" are invalid. This usually indicates your app was not ' + + 'initialized correctly. '; + if ('credential' in this.firebaseOptions_) { + errorMessage += + 'Make sure the "credential" property provided to initializeApp() ' + + 'is authorized to access the specified "databaseURL" and is from the correct ' + + 'project.'; + } + else if ('serviceAccount' in this.firebaseOptions_) { + errorMessage += + 'Make sure the "serviceAccount" property provided to initializeApp() ' + + 'is authorized to access the specified "databaseURL" and is from the correct ' + + 'project.'; + } + else { + errorMessage += + 'Make sure the "apiKey" and "databaseURL" properties provided to ' + + 'initializeApp() match the values provided for your app at ' + + 'https://console.firebase.google.com/.'; + } + warn(errorMessage); + } +} +/* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */ +class EmulatorTokenProvider { + constructor(accessToken) { + this.accessToken = accessToken; + } + getToken(forceRefresh) { + return Promise.resolve({ + accessToken: this.accessToken + }); + } + addTokenChangeListener(listener) { + // Invoke the listener immediately to match the behavior in Firebase Auth + // (see packages/auth/src/auth.js#L1807) + listener(this.accessToken); + } + removeTokenChangeListener(listener) { } + notifyForInvalidToken() { } +} +/** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */ +EmulatorTokenProvider.OWNER = 'owner'; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This class ensures the packets from the server arrive in order + * This class takes data from the server and ensures it gets passed into the callbacks in order. + */ +class PacketReceiver { + /** + * @param onMessage_ + */ + constructor(onMessage_) { + this.onMessage_ = onMessage_; + this.pendingResponses = []; + this.currentResponseNum = 0; + this.closeAfterResponse = -1; + this.onClose = null; + } + closeAfter(responseNum, callback) { + this.closeAfterResponse = responseNum; + this.onClose = callback; + if (this.closeAfterResponse < this.currentResponseNum) { + this.onClose(); + this.onClose = null; + } + } + /** + * Each message from the server comes with a response number, and an array of data. The responseNumber + * allows us to ensure that we process them in the right order, since we can't be guaranteed that all + * browsers will respond in the same order as the requests we sent + */ + handleResponse(requestNum, data) { + this.pendingResponses[requestNum] = data; + while (this.pendingResponses[this.currentResponseNum]) { + const toProcess = this.pendingResponses[this.currentResponseNum]; + delete this.pendingResponses[this.currentResponseNum]; + for (let i = 0; i < toProcess.length; ++i) { + if (toProcess[i]) { + exceptionGuard(() => { + this.onMessage_(toProcess[i]); + }); + } + } + if (this.currentResponseNum === this.closeAfterResponse) { + if (this.onClose) { + this.onClose(); + this.onClose = null; + } + break; + } + this.currentResponseNum++; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// URL query parameters associated with longpolling +const FIREBASE_LONGPOLL_START_PARAM = 'start'; +const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close'; +const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand'; +const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB'; +const FIREBASE_LONGPOLL_ID_PARAM = 'id'; +const FIREBASE_LONGPOLL_PW_PARAM = 'pw'; +const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser'; +const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb'; +const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg'; +const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts'; +const FIREBASE_LONGPOLL_DATA_PARAM = 'd'; +const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe'; +//Data size constants. +//TODO: Perf: the maximum length actually differs from browser to browser. +// We should check what browser we're on and set accordingly. +const MAX_URL_DATA_SIZE = 1870; +const SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d= +const MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE; +/** + * Keepalive period + * send a fresh request at minimum every 25 seconds. Opera has a maximum request + * length of 30 seconds that we can't exceed. + */ +const KEEPALIVE_REQUEST_INTERVAL = 25000; +/** + * How long to wait before aborting a long-polling connection attempt. + */ +const LP_CONNECT_TIMEOUT = 30000; +/** + * This class manages a single long-polling connection. + */ +class BrowserPollConnection { + /** + * @param connId An identifier for this connection, used for logging + * @param repoInfo The info for the endpoint to send data to. + * @param applicationId The Firebase App ID for this project. + * @param appCheckToken The AppCheck token for this client. + * @param authToken The AuthToken to use for this connection. + * @param transportSessionId Optional transportSessionid if we are + * reconnecting for an existing transport session + * @param lastSessionId Optional lastSessionId if the PersistentConnection has + * already created a connection previously + */ + constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) { + this.connId = connId; + this.repoInfo = repoInfo; + this.applicationId = applicationId; + this.appCheckToken = appCheckToken; + this.authToken = authToken; + this.transportSessionId = transportSessionId; + this.lastSessionId = lastSessionId; + this.bytesSent = 0; + this.bytesReceived = 0; + this.everConnected_ = false; + this.log_ = logWrapper(connId); + this.stats_ = statsManagerGetCollection(repoInfo); + this.urlFn = (params) => { + // Always add the token if we have one. + if (this.appCheckToken) { + params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken; + } + return repoInfoConnectionURL(repoInfo, LONG_POLLING, params); + }; + } + /** + * @param onMessage - Callback when messages arrive + * @param onDisconnect - Callback with connection lost. + */ + open(onMessage, onDisconnect) { + this.curSegmentNum = 0; + this.onDisconnect_ = onDisconnect; + this.myPacketOrderer = new PacketReceiver(onMessage); + this.isClosed_ = false; + this.connectTimeoutTimer_ = setTimeout(() => { + this.log_('Timed out trying to connect.'); + // Make sure we clear the host cache + this.onClosed_(); + this.connectTimeoutTimer_ = null; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(LP_CONNECT_TIMEOUT)); + // Ensure we delay the creation of the iframe until the DOM is loaded. + executeWhenDOMReady(() => { + if (this.isClosed_) { + return; + } + //Set up a callback that gets triggered once a connection is set up. + this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => { + const [command, arg1, arg2, arg3, arg4] = args; + this.incrementIncomingBytes_(args); + if (!this.scriptTagHolder) { + return; // we closed the connection. + } + if (this.connectTimeoutTimer_) { + clearTimeout(this.connectTimeoutTimer_); + this.connectTimeoutTimer_ = null; + } + this.everConnected_ = true; + if (command === FIREBASE_LONGPOLL_START_PARAM) { + this.id = arg1; + this.password = arg2; + } + else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) { + // Don't clear the host cache. We got a response from the server, so we know it's reachable + if (arg1) { + // We aren't expecting any more data (other than what the server's already in the process of sending us + // through our already open polls), so don't send any more. + this.scriptTagHolder.sendNewPolls = false; + // arg1 in this case is the last response number sent by the server. We should try to receive + // all of the responses up to this one before closing + this.myPacketOrderer.closeAfter(arg1, () => { + this.onClosed_(); + }); + } + else { + this.onClosed_(); + } + } + else { + throw new Error('Unrecognized command received: ' + command); + } + }, (...args) => { + const [pN, data] = args; + this.incrementIncomingBytes_(args); + this.myPacketOrderer.handleResponse(pN, data); + }, () => { + this.onClosed_(); + }, this.urlFn); + //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results + //from cache. + const urlParams = {}; + urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't'; + urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000); + if (this.scriptTagHolder.uniqueCallbackIdentifier) { + urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = + this.scriptTagHolder.uniqueCallbackIdentifier; + } + urlParams[VERSION_PARAM] = PROTOCOL_VERSION; + if (this.transportSessionId) { + urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId; + } + if (this.lastSessionId) { + urlParams[LAST_SESSION_PARAM] = this.lastSessionId; + } + if (this.applicationId) { + urlParams[APPLICATION_ID_PARAM] = this.applicationId; + } + if (this.appCheckToken) { + urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken; + } + if (typeof location !== 'undefined' && + location.hostname && + FORGE_DOMAIN_RE.test(location.hostname)) { + urlParams[REFERER_PARAM] = FORGE_REF; + } + const connectURL = this.urlFn(urlParams); + this.log_('Connecting via long-poll to ' + connectURL); + this.scriptTagHolder.addTag(connectURL, () => { + /* do nothing */ + }); + }); + } + /** + * Call this when a handshake has completed successfully and we want to consider the connection established + */ + start() { + this.scriptTagHolder.startLongPoll(this.id, this.password); + this.addDisconnectPingFrame(this.id, this.password); + } + /** + * Forces long polling to be considered as a potential transport + */ + static forceAllow() { + BrowserPollConnection.forceAllow_ = true; + } + /** + * Forces longpolling to not be considered as a potential transport + */ + static forceDisallow() { + BrowserPollConnection.forceDisallow_ = true; + } + // Static method, use string literal so it can be accessed in a generic way + static isAvailable() { + if (isNodeSdk()) { + return false; + } + else if (BrowserPollConnection.forceAllow_) { + return true; + } + else { + // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in + // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08). + return (!BrowserPollConnection.forceDisallow_ && + typeof document !== 'undefined' && + document.createElement != null && + !isChromeExtensionContentScript() && + !isWindowsStoreApp()); + } + } + /** + * No-op for polling + */ + markConnectionHealthy() { } + /** + * Stops polling and cleans up the iframe + */ + shutdown_() { + this.isClosed_ = true; + if (this.scriptTagHolder) { + this.scriptTagHolder.close(); + this.scriptTagHolder = null; + } + //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving. + if (this.myDisconnFrame) { + document.body.removeChild(this.myDisconnFrame); + this.myDisconnFrame = null; + } + if (this.connectTimeoutTimer_) { + clearTimeout(this.connectTimeoutTimer_); + this.connectTimeoutTimer_ = null; + } + } + /** + * Triggered when this transport is closed + */ + onClosed_() { + if (!this.isClosed_) { + this.log_('Longpoll is closing itself'); + this.shutdown_(); + if (this.onDisconnect_) { + this.onDisconnect_(this.everConnected_); + this.onDisconnect_ = null; + } + } + } + /** + * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server + * that we've left. + */ + close() { + if (!this.isClosed_) { + this.log_('Longpoll is being closed.'); + this.shutdown_(); + } + } + /** + * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then + * broken into chunks (since URLs have a small maximum length). + * @param data - The JSON data to transmit. + */ + send(data) { + const dataStr = stringify(data); + this.bytesSent += dataStr.length; + this.stats_.incrementCounter('bytes_sent', dataStr.length); + //first, lets get the base64-encoded data + const base64data = base64Encode(dataStr); + //We can only fit a certain amount in each URL, so we need to split this request + //up into multiple pieces if it doesn't fit in one request. + const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE); + //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number + //of segments so that we can reassemble the packet on the server. + for (let i = 0; i < dataSegs.length; i++) { + this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]); + this.curSegmentNum++; + } + } + /** + * This is how we notify the server that we're leaving. + * We aren't able to send requests with DHTML on a window close event, but we can + * trigger XHR requests in some browsers (everything but Opera basically). + */ + addDisconnectPingFrame(id, pw) { + if (isNodeSdk()) { + return; + } + this.myDisconnFrame = document.createElement('iframe'); + const urlParams = {}; + urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't'; + urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id; + urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw; + this.myDisconnFrame.src = this.urlFn(urlParams); + this.myDisconnFrame.style.display = 'none'; + document.body.appendChild(this.myDisconnFrame); + } + /** + * Used to track the bytes received by this client + */ + incrementIncomingBytes_(args) { + // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in. + const bytesReceived = stringify(args).length; + this.bytesReceived += bytesReceived; + this.stats_.incrementCounter('bytes_received', bytesReceived); + } +} +/********************************************************************************************* + * A wrapper around an iframe that is used as a long-polling script holder. + *********************************************************************************************/ +class FirebaseIFrameScriptHolder { + /** + * @param commandCB - The callback to be called when control commands are received from the server. + * @param onMessageCB - The callback to be triggered when responses arrive from the server. + * @param onDisconnect - The callback to be triggered when this tag holder is closed + * @param urlFn - A function that provides the URL of the endpoint to send data to. + */ + constructor(commandCB, onMessageCB, onDisconnect, urlFn) { + this.onDisconnect = onDisconnect; + this.urlFn = urlFn; + //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause + //problems in some browsers. + this.outstandingRequests = new Set(); + //A queue of the pending segments waiting for transmission to the server. + this.pendingSegs = []; + //A serial number. We use this for two things: + // 1) A way to ensure the browser doesn't cache responses to polls + // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The + // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute + // JSONP code in the order it was added to the iframe. + this.currentSerial = Math.floor(Math.random() * 100000000); + // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still + // incoming data from the server that we're waiting for). + this.sendNewPolls = true; + if (!isNodeSdk()) { + //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the + //iframes where we put the long-polling script tags. We have two callbacks: + // 1) Command Callback - Triggered for control issues, like starting a connection. + // 2) Message Callback - Triggered when new data arrives. + this.uniqueCallbackIdentifier = LUIDGenerator(); + window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB; + window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = + onMessageCB; + //Create an iframe for us to add script tags to. + this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_(); + // Set the iframe's contents. + let script = ''; + // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient + // for ie9, but ie8 needs to do it again in the document itself. + if (this.myIFrame.src && + this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') { + const currentDomain = document.domain; + script = ''; + } + const iframeContents = '' + script + ''; + try { + this.myIFrame.doc.open(); + this.myIFrame.doc.write(iframeContents); + this.myIFrame.doc.close(); + } + catch (e) { + log('frame writing exception'); + if (e.stack) { + log(e.stack); + } + log(e); + } + } + else { + this.commandCB = commandCB; + this.onMessageCB = onMessageCB; + } + } + /** + * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can + * actually use. + */ + static createIFrame_() { + const iframe = document.createElement('iframe'); + iframe.style.display = 'none'; + // This is necessary in order to initialize the document inside the iframe + if (document.body) { + document.body.appendChild(iframe); + try { + // If document.domain has been modified in IE, this will throw an error, and we need to set the + // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute + // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work. + const a = iframe.contentWindow.document; + if (!a) { + // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above. + log('No IE domain setting required'); + } + } + catch (e) { + const domain = document.domain; + iframe.src = + "javascript:void((function(){document.open();document.domain='" + + domain + + "';document.close();})())"; + } + } + else { + // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this + // never gets hit. + throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.'; + } + // Get the document of the iframe in a browser-specific way. + if (iframe.contentDocument) { + iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari + } + else if (iframe.contentWindow) { + iframe.doc = iframe.contentWindow.document; // Internet Explorer + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + else if (iframe.document) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + iframe.doc = iframe.document; //others? + } + return iframe; + } + /** + * Cancel all outstanding queries and remove the frame. + */ + close() { + //Mark this iframe as dead, so no new requests are sent. + this.alive = false; + if (this.myIFrame) { + //We have to actually remove all of the html inside this iframe before removing it from the + //window, or IE will continue loading and executing the script tags we've already added, which + //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this. + this.myIFrame.doc.body.textContent = ''; + setTimeout(() => { + if (this.myIFrame !== null) { + document.body.removeChild(this.myIFrame); + this.myIFrame = null; + } + }, Math.floor(0)); + } + // Protect from being called recursively. + const onDisconnect = this.onDisconnect; + if (onDisconnect) { + this.onDisconnect = null; + onDisconnect(); + } + } + /** + * Actually start the long-polling session by adding the first script tag(s) to the iframe. + * @param id - The ID of this connection + * @param pw - The password for this connection + */ + startLongPoll(id, pw) { + this.myID = id; + this.myPW = pw; + this.alive = true; + //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to. + while (this.newRequest_()) { } + } + /** + * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't + * too many outstanding requests and we are still alive. + * + * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if + * needed. + */ + newRequest_() { + // We keep one outstanding request open all the time to receive data, but if we need to send data + // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically + // close the old request. + if (this.alive && + this.sendNewPolls && + this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) { + //construct our url + this.currentSerial++; + const urlParams = {}; + urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID; + urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW; + urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial; + let theURL = this.urlFn(urlParams); + //Now add as much data as we can. + let curDataString = ''; + let i = 0; + while (this.pendingSegs.length > 0) { + //first, lets see if the next segment will fit. + const nextSeg = this.pendingSegs[0]; + if (nextSeg.d.length + + SEG_HEADER_SIZE + + curDataString.length <= + MAX_URL_DATA_SIZE) { + //great, the segment will fit. Lets append it. + const theSeg = this.pendingSegs.shift(); + curDataString = + curDataString + + '&' + + FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM + + i + + '=' + + theSeg.seg + + '&' + + FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET + + i + + '=' + + theSeg.ts + + '&' + + FIREBASE_LONGPOLL_DATA_PARAM + + i + + '=' + + theSeg.d; + i++; + } + else { + break; + } + } + theURL = theURL + curDataString; + this.addLongPollTag_(theURL, this.currentSerial); + return true; + } + else { + return false; + } + } + /** + * Queue a packet for transmission to the server. + * @param segnum - A sequential id for this packet segment used for reassembly + * @param totalsegs - The total number of segments in this packet + * @param data - The data for this segment. + */ + enqueueSegment(segnum, totalsegs, data) { + //add this to the queue of segments to send. + this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data }); + //send the data immediately if there isn't already data being transmitted, unless + //startLongPoll hasn't been called yet. + if (this.alive) { + this.newRequest_(); + } + } + /** + * Add a script tag for a regular long-poll request. + * @param url - The URL of the script tag. + * @param serial - The serial number of the request. + */ + addLongPollTag_(url, serial) { + //remember that we sent this request. + this.outstandingRequests.add(serial); + const doNewRequest = () => { + this.outstandingRequests.delete(serial); + this.newRequest_(); + }; + // If this request doesn't return on its own accord (by the server sending us some data), we'll + // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open. + const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL)); + const readyStateCB = () => { + // Request completed. Cancel the keepalive. + clearTimeout(keepaliveTimeout); + // Trigger a new request so we can continue receiving data. + doNewRequest(); + }; + this.addTag(url, readyStateCB); + } + /** + * Add an arbitrary script tag to the iframe. + * @param url - The URL for the script tag source. + * @param loadCB - A callback to be triggered once the script has loaded. + */ + addTag(url, loadCB) { + if (isNodeSdk()) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.doNodeLongPoll(url, loadCB); + } + else { + setTimeout(() => { + try { + // if we're already closed, don't add this poll + if (!this.sendNewPolls) { + return; + } + const newScript = this.myIFrame.doc.createElement('script'); + newScript.type = 'text/javascript'; + newScript.async = true; + newScript.src = url; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + newScript.onload = newScript.onreadystatechange = + function () { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const rstate = newScript.readyState; + if (!rstate || rstate === 'loaded' || rstate === 'complete') { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + newScript.onload = newScript.onreadystatechange = null; + if (newScript.parentNode) { + newScript.parentNode.removeChild(newScript); + } + loadCB(); + } + }; + newScript.onerror = () => { + log('Long-poll script failed to load: ' + url); + this.sendNewPolls = false; + this.close(); + }; + this.myIFrame.doc.body.appendChild(newScript); + } + catch (e) { + // TODO: we should make this error visible somehow + } + }, Math.floor(1)); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Currently simplistic, this class manages what transport a Connection should use at various stages of its + * lifecycle. + * + * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if + * they are available. + */ +class TransportManager { + static get ALL_TRANSPORTS() { + return [BrowserPollConnection, WebSocketConnection]; + } + /** + * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after + * TransportManager has already set up transports_ + */ + static get IS_TRANSPORT_INITIALIZED() { + return this.globalTransportInitialized_; + } + /** + * @param repoInfo - Metadata around the namespace we're connecting to + */ + constructor(repoInfo) { + this.initTransports_(repoInfo); + } + initTransports_(repoInfo) { + const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable'](); + let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed(); + if (repoInfo.webSocketOnly) { + if (!isWebSocketsAvailable) { + warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway."); + } + isSkipPollConnection = true; + } + if (isSkipPollConnection) { + this.transports_ = [WebSocketConnection]; + } + else { + const transports = (this.transports_ = []); + for (const transport of TransportManager.ALL_TRANSPORTS) { + if (transport && transport['isAvailable']()) { + transports.push(transport); + } + } + TransportManager.globalTransportInitialized_ = true; + } + } + /** + * @returns The constructor for the initial transport to use + */ + initialTransport() { + if (this.transports_.length > 0) { + return this.transports_[0]; + } + else { + throw new Error('No transports available'); + } + } + /** + * @returns The constructor for the next transport, or null + */ + upgradeTransport() { + if (this.transports_.length > 1) { + return this.transports_[1]; + } + else { + return null; + } + } +} +// Keeps track of whether the TransportManager has already chosen a transport to use +TransportManager.globalTransportInitialized_ = false; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Abort upgrade attempt if it takes longer than 60s. +const UPGRADE_TIMEOUT = 60000; +// For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses. +// If we haven't sent enough requests within 5s, we'll start sending noop ping requests. +const DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000; +// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data) +// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout +// but we've sent/received enough bytes, we don't cancel the connection. +const BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024; +const BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024; +const MESSAGE_TYPE = 't'; +const MESSAGE_DATA = 'd'; +const CONTROL_SHUTDOWN = 's'; +const CONTROL_RESET = 'r'; +const CONTROL_ERROR = 'e'; +const CONTROL_PONG = 'o'; +const SWITCH_ACK = 'a'; +const END_TRANSMISSION = 'n'; +const PING = 'p'; +const SERVER_HELLO = 'h'; +/** + * Creates a new real-time connection to the server using whichever method works + * best in the current browser. + */ +class Connection { + /** + * @param id - an id for this connection + * @param repoInfo_ - the info for the endpoint to connect to + * @param applicationId_ - the Firebase App ID for this project + * @param appCheckToken_ - The App Check Token for this device. + * @param authToken_ - The auth token for this session. + * @param onMessage_ - the callback to be triggered when a server-push message arrives + * @param onReady_ - the callback to be triggered when this connection is ready to send messages. + * @param onDisconnect_ - the callback to be triggered when a connection was lost + * @param onKill_ - the callback to be triggered when this connection has permanently shut down. + * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server + */ + constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) { + this.id = id; + this.repoInfo_ = repoInfo_; + this.applicationId_ = applicationId_; + this.appCheckToken_ = appCheckToken_; + this.authToken_ = authToken_; + this.onMessage_ = onMessage_; + this.onReady_ = onReady_; + this.onDisconnect_ = onDisconnect_; + this.onKill_ = onKill_; + this.lastSessionId = lastSessionId; + this.connectionCount = 0; + this.pendingDataMessages = []; + this.state_ = 0 /* RealtimeState.CONNECTING */; + this.log_ = logWrapper('c:' + this.id + ':'); + this.transportManager_ = new TransportManager(repoInfo_); + this.log_('Connection created'); + this.start_(); + } + /** + * Starts a connection attempt + */ + start_() { + const conn = this.transportManager_.initialTransport(); + this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId); + // For certain transports (WebSockets), we need to send and receive several messages back and forth before we + // can consider the transport healthy. + this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0; + const onMessageReceived = this.connReceiver_(this.conn_); + const onConnectionLost = this.disconnReceiver_(this.conn_); + this.tx_ = this.conn_; + this.rx_ = this.conn_; + this.secondaryConn_ = null; + this.isHealthy_ = false; + /* + * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame. + * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset. + * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should + * still have the context of your originating frame. + */ + setTimeout(() => { + // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it + this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost); + }, Math.floor(0)); + const healthyTimeoutMS = conn['healthyTimeout'] || 0; + if (healthyTimeoutMS > 0) { + this.healthyTimeout_ = setTimeoutNonBlocking(() => { + this.healthyTimeout_ = null; + if (!this.isHealthy_) { + if (this.conn_ && + this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) { + this.log_('Connection exceeded healthy timeout but has received ' + + this.conn_.bytesReceived + + ' bytes. Marking connection healthy.'); + this.isHealthy_ = true; + this.conn_.markConnectionHealthy(); + } + else if (this.conn_ && + this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) { + this.log_('Connection exceeded healthy timeout but has sent ' + + this.conn_.bytesSent + + ' bytes. Leaving connection alive.'); + // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to + // the server. + } + else { + this.log_('Closing unhealthy connection after timeout.'); + this.close(); + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(healthyTimeoutMS)); + } + } + nextTransportId_() { + return 'c:' + this.id + ':' + this.connectionCount++; + } + disconnReceiver_(conn) { + return everConnected => { + if (conn === this.conn_) { + this.onConnectionLost_(everConnected); + } + else if (conn === this.secondaryConn_) { + this.log_('Secondary connection lost.'); + this.onSecondaryConnectionLost_(); + } + else { + this.log_('closing an old connection'); + } + }; + } + connReceiver_(conn) { + return (message) => { + if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) { + if (conn === this.rx_) { + this.onPrimaryMessageReceived_(message); + } + else if (conn === this.secondaryConn_) { + this.onSecondaryMessageReceived_(message); + } + else { + this.log_('message on old connection'); + } + } + }; + } + /** + * @param dataMsg - An arbitrary data message to be sent to the server + */ + sendRequest(dataMsg) { + // wrap in a data message envelope and send it on + const msg = { t: 'd', d: dataMsg }; + this.sendData_(msg); + } + tryCleanupConnection() { + if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) { + this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId); + this.conn_ = this.secondaryConn_; + this.secondaryConn_ = null; + // the server will shutdown the old connection + } + } + onSecondaryControl_(controlData) { + if (MESSAGE_TYPE in controlData) { + const cmd = controlData[MESSAGE_TYPE]; + if (cmd === SWITCH_ACK) { + this.upgradeIfSecondaryHealthy_(); + } + else if (cmd === CONTROL_RESET) { + // Most likely the session wasn't valid. Abandon the switch attempt + this.log_('Got a reset on secondary, closing it'); + this.secondaryConn_.close(); + // If we were already using this connection for something, than we need to fully close + if (this.tx_ === this.secondaryConn_ || + this.rx_ === this.secondaryConn_) { + this.close(); + } + } + else if (cmd === CONTROL_PONG) { + this.log_('got pong on secondary.'); + this.secondaryResponsesRequired_--; + this.upgradeIfSecondaryHealthy_(); + } + } + } + onSecondaryMessageReceived_(parsedData) { + const layer = requireKey('t', parsedData); + const data = requireKey('d', parsedData); + if (layer === 'c') { + this.onSecondaryControl_(data); + } + else if (layer === 'd') { + // got a data message, but we're still second connection. Need to buffer it up + this.pendingDataMessages.push(data); + } + else { + throw new Error('Unknown protocol layer: ' + layer); + } + } + upgradeIfSecondaryHealthy_() { + if (this.secondaryResponsesRequired_ <= 0) { + this.log_('Secondary connection is healthy.'); + this.isHealthy_ = true; + this.secondaryConn_.markConnectionHealthy(); + this.proceedWithUpgrade_(); + } + else { + // Send a ping to make sure the connection is healthy. + this.log_('sending ping on secondary.'); + this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } }); + } + } + proceedWithUpgrade_() { + // tell this connection to consider itself open + this.secondaryConn_.start(); + // send ack + this.log_('sending client ack on secondary'); + this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } }); + // send end packet on primary transport, switch to sending on this one + // can receive on this one, buffer responses until end received on primary transport + this.log_('Ending transmission on primary'); + this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } }); + this.tx_ = this.secondaryConn_; + this.tryCleanupConnection(); + } + onPrimaryMessageReceived_(parsedData) { + // Must refer to parsedData properties in quotes, so closure doesn't touch them. + const layer = requireKey('t', parsedData); + const data = requireKey('d', parsedData); + if (layer === 'c') { + this.onControl_(data); + } + else if (layer === 'd') { + this.onDataMessage_(data); + } + } + onDataMessage_(message) { + this.onPrimaryResponse_(); + // We don't do anything with data messages, just kick them up a level + this.onMessage_(message); + } + onPrimaryResponse_() { + if (!this.isHealthy_) { + this.primaryResponsesRequired_--; + if (this.primaryResponsesRequired_ <= 0) { + this.log_('Primary connection is healthy.'); + this.isHealthy_ = true; + this.conn_.markConnectionHealthy(); + } + } + } + onControl_(controlData) { + const cmd = requireKey(MESSAGE_TYPE, controlData); + if (MESSAGE_DATA in controlData) { + const payload = controlData[MESSAGE_DATA]; + if (cmd === SERVER_HELLO) { + const handshakePayload = { + ...payload + }; + if (this.repoInfo_.isUsingEmulator) { + // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes. + handshakePayload.h = this.repoInfo_.host; + } + this.onHandshake_(handshakePayload); + } + else if (cmd === END_TRANSMISSION) { + this.log_('recvd end transmission on primary'); + this.rx_ = this.secondaryConn_; + for (let i = 0; i < this.pendingDataMessages.length; ++i) { + this.onDataMessage_(this.pendingDataMessages[i]); + } + this.pendingDataMessages = []; + this.tryCleanupConnection(); + } + else if (cmd === CONTROL_SHUTDOWN) { + // This was previously the 'onKill' callback passed to the lower-level connection + // payload in this case is the reason for the shutdown. Generally a human-readable error + this.onConnectionShutdown_(payload); + } + else if (cmd === CONTROL_RESET) { + // payload in this case is the host we should contact + this.onReset_(payload); + } + else if (cmd === CONTROL_ERROR) { + error('Server Error: ' + payload); + } + else if (cmd === CONTROL_PONG) { + this.log_('got pong on primary.'); + this.onPrimaryResponse_(); + this.sendPingOnPrimaryIfNecessary_(); + } + else { + error('Unknown control packet command: ' + cmd); + } + } + } + /** + * @param handshake - The handshake data returned from the server + */ + onHandshake_(handshake) { + const timestamp = handshake.ts; + const version = handshake.v; + const host = handshake.h; + this.sessionId = handshake.s; + this.repoInfo_.host = host; + // if we've already closed the connection, then don't bother trying to progress further + if (this.state_ === 0 /* RealtimeState.CONNECTING */) { + this.conn_.start(); + this.onConnectionEstablished_(this.conn_, timestamp); + if (PROTOCOL_VERSION !== version) { + warn('Protocol version mismatch detected'); + } + // TODO: do we want to upgrade? when? maybe a delay? + this.tryStartUpgrade_(); + } + } + tryStartUpgrade_() { + const conn = this.transportManager_.upgradeTransport(); + if (conn) { + this.startUpgrade_(conn); + } + } + startUpgrade_(conn) { + this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId); + // For certain transports (WebSockets), we need to send and receive several messages back and forth before we + // can consider the transport healthy. + this.secondaryResponsesRequired_ = + conn['responsesRequiredToBeHealthy'] || 0; + const onMessage = this.connReceiver_(this.secondaryConn_); + const onDisconnect = this.disconnReceiver_(this.secondaryConn_); + this.secondaryConn_.open(onMessage, onDisconnect); + // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary. + setTimeoutNonBlocking(() => { + if (this.secondaryConn_) { + this.log_('Timed out trying to upgrade.'); + this.secondaryConn_.close(); + } + }, Math.floor(UPGRADE_TIMEOUT)); + } + onReset_(host) { + this.log_('Reset packet received. New host: ' + host); + this.repoInfo_.host = host; + // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up. + // We don't currently support resets after the connection has already been established + if (this.state_ === 1 /* RealtimeState.CONNECTED */) { + this.close(); + } + else { + // Close whatever connections we have open and start again. + this.closeConnections_(); + this.start_(); + } + } + onConnectionEstablished_(conn, timestamp) { + this.log_('Realtime connection established.'); + this.conn_ = conn; + this.state_ = 1 /* RealtimeState.CONNECTED */; + if (this.onReady_) { + this.onReady_(timestamp, this.sessionId); + this.onReady_ = null; + } + // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy, + // send some pings. + if (this.primaryResponsesRequired_ === 0) { + this.log_('Primary connection is healthy.'); + this.isHealthy_ = true; + } + else { + setTimeoutNonBlocking(() => { + this.sendPingOnPrimaryIfNecessary_(); + }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS)); + } + } + sendPingOnPrimaryIfNecessary_() { + // If the connection isn't considered healthy yet, we'll send a noop ping packet request. + if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) { + this.log_('sending ping on primary.'); + this.sendData_({ t: 'c', d: { t: PING, d: {} } }); + } + } + onSecondaryConnectionLost_() { + const conn = this.secondaryConn_; + this.secondaryConn_ = null; + if (this.tx_ === conn || this.rx_ === conn) { + // we are relying on this connection already in some capacity. Therefore, a failure is real + this.close(); + } + } + /** + * @param everConnected - Whether or not the connection ever reached a server. Used to determine if + * we should flush the host cache + */ + onConnectionLost_(everConnected) { + this.conn_ = null; + // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting + // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess. + if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) { + this.log_('Realtime connection failed.'); + // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away + if (this.repoInfo_.isCacheableHost()) { + PersistentStorage.remove('host:' + this.repoInfo_.host); + // reset the internal host to what we would show the user, i.e. .firebaseio.com + this.repoInfo_.internalHost = this.repoInfo_.host; + } + } + else if (this.state_ === 1 /* RealtimeState.CONNECTED */) { + this.log_('Realtime connection lost.'); + } + this.close(); + } + onConnectionShutdown_(reason) { + this.log_('Connection shutdown command received. Shutting down...'); + if (this.onKill_) { + this.onKill_(reason); + this.onKill_ = null; + } + // We intentionally don't want to fire onDisconnect (kill is a different case), + // so clear the callback. + this.onDisconnect_ = null; + this.close(); + } + sendData_(data) { + if (this.state_ !== 1 /* RealtimeState.CONNECTED */) { + throw 'Connection is not connected'; + } + else { + this.tx_.send(data); + } + } + /** + * Cleans up this connection, calling the appropriate callbacks + */ + close() { + if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) { + this.log_('Closing realtime connection.'); + this.state_ = 2 /* RealtimeState.DISCONNECTED */; + this.closeConnections_(); + if (this.onDisconnect_) { + this.onDisconnect_(); + this.onDisconnect_ = null; + } + } + } + closeConnections_() { + this.log_('Shutting down all connections'); + if (this.conn_) { + this.conn_.close(); + this.conn_ = null; + } + if (this.secondaryConn_) { + this.secondaryConn_.close(); + this.secondaryConn_ = null; + } + if (this.healthyTimeout_) { + clearTimeout(this.healthyTimeout_); + this.healthyTimeout_ = null; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Interface defining the set of actions that can be performed against the Firebase server + * (basically corresponds to our wire protocol). + * + * @interface + */ +class ServerActions { + put(pathString, data, onComplete, hash) { } + merge(pathString, data, onComplete, hash) { } + /** + * Refreshes the auth token for the current connection. + * @param token - The authentication token + */ + refreshAuthToken(token) { } + /** + * Refreshes the app check token for the current connection. + * @param token The app check token + */ + refreshAppCheckToken(token) { } + onDisconnectPut(pathString, data, onComplete) { } + onDisconnectMerge(pathString, data, onComplete) { } + onDisconnectCancel(pathString, onComplete) { } + reportStats(stats) { } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Base class to be used if you want to emit events. Call the constructor with + * the set of allowed event names. + */ +class EventEmitter { + constructor(allowedEvents_) { + this.allowedEvents_ = allowedEvents_; + this.listeners_ = {}; + assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array'); + } + /** + * To be called by derived classes to trigger events. + */ + trigger(eventType, ...varArgs) { + if (Array.isArray(this.listeners_[eventType])) { + // Clone the list, since callbacks could add/remove listeners. + const listeners = [...this.listeners_[eventType]]; + for (let i = 0; i < listeners.length; i++) { + listeners[i].callback.apply(listeners[i].context, varArgs); + } + } + } + on(eventType, callback, context) { + this.validateEventType_(eventType); + this.listeners_[eventType] = this.listeners_[eventType] || []; + this.listeners_[eventType].push({ callback, context }); + const eventData = this.getInitialEvent(eventType); + if (eventData) { + callback.apply(context, eventData); + } + } + off(eventType, callback, context) { + this.validateEventType_(eventType); + const listeners = this.listeners_[eventType] || []; + for (let i = 0; i < listeners.length; i++) { + if (listeners[i].callback === callback && + (!context || context === listeners[i].context)) { + listeners.splice(i, 1); + return; + } + } + } + validateEventType_(eventType) { + assert(this.allowedEvents_.find(et => { + return et === eventType; + }), 'Unknown event: ' + eventType); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Monitors online state (as reported by window.online/offline events). + * + * The expectation is that this could have many false positives (thinks we are online + * when we're not), but no false negatives. So we can safely use it to determine when + * we definitely cannot reach the internet. + */ +class OnlineMonitor extends EventEmitter { + static getInstance() { + return new OnlineMonitor(); + } + constructor() { + super(['online']); + this.online_ = true; + // We've had repeated complaints that Cordova apps can get stuck "offline", e.g. + // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810 + // It would seem that the 'online' event does not always fire consistently. So we disable it + // for Cordova. + if (typeof window !== 'undefined' && + typeof window.addEventListener !== 'undefined' && + !isMobileCordova()) { + window.addEventListener('online', () => { + if (!this.online_) { + this.online_ = true; + this.trigger('online', true); + } + }, false); + window.addEventListener('offline', () => { + if (this.online_) { + this.online_ = false; + this.trigger('online', false); + } + }, false); + } + } + getInitialEvent(eventType) { + assert(eventType === 'online', 'Unknown event type: ' + eventType); + return [this.online_]; + } + currentlyOnline() { + return this.online_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Maximum key depth. */ +const MAX_PATH_DEPTH = 32; +/** Maximum number of (UTF8) bytes in a Firebase path. */ +const MAX_PATH_LENGTH_BYTES = 768; +/** + * An immutable object representing a parsed path. It's immutable so that you + * can pass them around to other functions without worrying about them changing + * it. + */ +class Path { + /** + * @param pathOrString - Path string to parse, or another path, or the raw + * tokens array + */ + constructor(pathOrString, pieceNum) { + if (pieceNum === void 0) { + this.pieces_ = pathOrString.split('/'); + // Remove empty pieces. + let copyTo = 0; + for (let i = 0; i < this.pieces_.length; i++) { + if (this.pieces_[i].length > 0) { + this.pieces_[copyTo] = this.pieces_[i]; + copyTo++; + } + } + this.pieces_.length = copyTo; + this.pieceNum_ = 0; + } + else { + this.pieces_ = pathOrString; + this.pieceNum_ = pieceNum; + } + } + toString() { + let pathString = ''; + for (let i = this.pieceNum_; i < this.pieces_.length; i++) { + if (this.pieces_[i] !== '') { + pathString += '/' + this.pieces_[i]; + } + } + return pathString || '/'; + } +} +function newEmptyPath() { + return new Path(''); +} +function pathGetFront(path) { + if (path.pieceNum_ >= path.pieces_.length) { + return null; + } + return path.pieces_[path.pieceNum_]; +} +/** + * @returns The number of segments in this path + */ +function pathGetLength(path) { + return path.pieces_.length - path.pieceNum_; +} +function pathPopFront(path) { + let pieceNum = path.pieceNum_; + if (pieceNum < path.pieces_.length) { + pieceNum++; + } + return new Path(path.pieces_, pieceNum); +} +function pathGetBack(path) { + if (path.pieceNum_ < path.pieces_.length) { + return path.pieces_[path.pieces_.length - 1]; + } + return null; +} +function pathToUrlEncodedString(path) { + let pathString = ''; + for (let i = path.pieceNum_; i < path.pieces_.length; i++) { + if (path.pieces_[i] !== '') { + pathString += '/' + encodeURIComponent(String(path.pieces_[i])); + } + } + return pathString || '/'; +} +/** + * Shallow copy of the parts of the path. + * + */ +function pathSlice(path, begin = 0) { + return path.pieces_.slice(path.pieceNum_ + begin); +} +function pathParent(path) { + if (path.pieceNum_ >= path.pieces_.length) { + return null; + } + const pieces = []; + for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) { + pieces.push(path.pieces_[i]); + } + return new Path(pieces, 0); +} +function pathChild(path, childPathObj) { + const pieces = []; + for (let i = path.pieceNum_; i < path.pieces_.length; i++) { + pieces.push(path.pieces_[i]); + } + if (childPathObj instanceof Path) { + for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) { + pieces.push(childPathObj.pieces_[i]); + } + } + else { + const childPieces = childPathObj.split('/'); + for (let i = 0; i < childPieces.length; i++) { + if (childPieces[i].length > 0) { + pieces.push(childPieces[i]); + } + } + } + return new Path(pieces, 0); +} +/** + * @returns True if there are no segments in this path + */ +function pathIsEmpty(path) { + return path.pieceNum_ >= path.pieces_.length; +} +/** + * @returns The path from outerPath to innerPath + */ +function newRelativePath(outerPath, innerPath) { + const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath); + if (outer === null) { + return innerPath; + } + else if (outer === inner) { + return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath)); + } + else { + throw new Error('INTERNAL ERROR: innerPath (' + + innerPath + + ') is not within ' + + 'outerPath (' + + outerPath + + ')'); + } +} +/** + * @returns -1, 0, 1 if left is less, equal, or greater than the right. + */ +function pathCompare(left, right) { + const leftKeys = pathSlice(left, 0); + const rightKeys = pathSlice(right, 0); + for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) { + const cmp = nameCompare(leftKeys[i], rightKeys[i]); + if (cmp !== 0) { + return cmp; + } + } + if (leftKeys.length === rightKeys.length) { + return 0; + } + return leftKeys.length < rightKeys.length ? -1 : 1; +} +/** + * @returns true if paths are the same. + */ +function pathEquals(path, other) { + if (pathGetLength(path) !== pathGetLength(other)) { + return false; + } + for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) { + if (path.pieces_[i] !== other.pieces_[j]) { + return false; + } + } + return true; +} +/** + * @returns True if this path is a parent of (or the same as) other + */ +function pathContains(path, other) { + let i = path.pieceNum_; + let j = other.pieceNum_; + if (pathGetLength(path) > pathGetLength(other)) { + return false; + } + while (i < path.pieces_.length) { + if (path.pieces_[i] !== other.pieces_[j]) { + return false; + } + ++i; + ++j; + } + return true; +} +/** + * Dynamic (mutable) path used to count path lengths. + * + * This class is used to efficiently check paths for valid + * length (in UTF8 bytes) and depth (used in path validation). + * + * Throws Error exception if path is ever invalid. + * + * The definition of a path always begins with '/'. + */ +class ValidationPath { + /** + * @param path - Initial Path. + * @param errorPrefix_ - Prefix for any error messages. + */ + constructor(path, errorPrefix_) { + this.errorPrefix_ = errorPrefix_; + this.parts_ = pathSlice(path, 0); + /** Initialize to number of '/' chars needed in path. */ + this.byteLength_ = Math.max(1, this.parts_.length); + for (let i = 0; i < this.parts_.length; i++) { + this.byteLength_ += stringLength(this.parts_[i]); + } + validationPathCheckValid(this); + } +} +function validationPathPush(validationPath, child) { + // Count the needed '/' + if (validationPath.parts_.length > 0) { + validationPath.byteLength_ += 1; + } + validationPath.parts_.push(child); + validationPath.byteLength_ += stringLength(child); + validationPathCheckValid(validationPath); +} +function validationPathPop(validationPath) { + const last = validationPath.parts_.pop(); + validationPath.byteLength_ -= stringLength(last); + // Un-count the previous '/' + if (validationPath.parts_.length > 0) { + validationPath.byteLength_ -= 1; + } +} +function validationPathCheckValid(validationPath) { + if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) { + throw new Error(validationPath.errorPrefix_ + + 'has a key path longer than ' + + MAX_PATH_LENGTH_BYTES + + ' bytes (' + + validationPath.byteLength_ + + ').'); + } + if (validationPath.parts_.length > MAX_PATH_DEPTH) { + throw new Error(validationPath.errorPrefix_ + + 'path specified exceeds the maximum depth that can be written (' + + MAX_PATH_DEPTH + + ') or object contains a cycle ' + + validationPathToErrorString(validationPath)); + } +} +/** + * String for use in error messages - uses '.' notation for path. + */ +function validationPathToErrorString(validationPath) { + if (validationPath.parts_.length === 0) { + return ''; + } + return "in property '" + validationPath.parts_.join('.') + "'"; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class VisibilityMonitor extends EventEmitter { + static getInstance() { + return new VisibilityMonitor(); + } + constructor() { + super(['visible']); + let hidden; + let visibilityChange; + if (typeof document !== 'undefined' && + typeof document.addEventListener !== 'undefined') { + if (typeof document['hidden'] !== 'undefined') { + // Opera 12.10 and Firefox 18 and later support + visibilityChange = 'visibilitychange'; + hidden = 'hidden'; + } + else if (typeof document['mozHidden'] !== 'undefined') { + visibilityChange = 'mozvisibilitychange'; + hidden = 'mozHidden'; + } + else if (typeof document['msHidden'] !== 'undefined') { + visibilityChange = 'msvisibilitychange'; + hidden = 'msHidden'; + } + else if (typeof document['webkitHidden'] !== 'undefined') { + visibilityChange = 'webkitvisibilitychange'; + hidden = 'webkitHidden'; + } + } + // Initially, we always assume we are visible. This ensures that in browsers + // without page visibility support or in cases where we are never visible + // (e.g. chrome extension), we act as if we are visible, i.e. don't delay + // reconnects + this.visible_ = true; + if (visibilityChange) { + document.addEventListener(visibilityChange, () => { + const visible = !document[hidden]; + if (visible !== this.visible_) { + this.visible_ = visible; + this.trigger('visible', visible); + } + }, false); + } + } + getInitialEvent(eventType) { + assert(eventType === 'visible', 'Unknown event type: ' + eventType); + return [this.visible_]; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const RECONNECT_MIN_DELAY = 1000; +const RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858) +const RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server) +const RECONNECT_DELAY_MULTIPLIER = 1.3; +const RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec. +const SERVER_KILL_INTERRUPT_REASON = 'server_kill'; +// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off. +const INVALID_TOKEN_THRESHOLD = 3; +/** + * Firebase connection. Abstracts wire protocol and handles reconnecting. + * + * NOTE: All JSON objects sent to the realtime connection must have property names enclosed + * in quotes to make sure the closure compiler does not minify them. + */ +class PersistentConnection extends ServerActions { + /** + * @param repoInfo_ - Data about the namespace we are connecting to + * @param applicationId_ - The Firebase App ID for this project + * @param onDataUpdate_ - A callback for new data from the server + */ + constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) { + super(); + this.repoInfo_ = repoInfo_; + this.applicationId_ = applicationId_; + this.onDataUpdate_ = onDataUpdate_; + this.onConnectStatus_ = onConnectStatus_; + this.onServerInfoUpdate_ = onServerInfoUpdate_; + this.authTokenProvider_ = authTokenProvider_; + this.appCheckTokenProvider_ = appCheckTokenProvider_; + this.authOverride_ = authOverride_; + // Used for diagnostic logging. + this.id = PersistentConnection.nextPersistentConnectionId_++; + this.log_ = logWrapper('p:' + this.id + ':'); + this.interruptReasons_ = {}; + this.listens = new Map(); + this.outstandingPuts_ = []; + this.outstandingGets_ = []; + this.outstandingPutCount_ = 0; + this.outstandingGetCount_ = 0; + this.onDisconnectRequestQueue_ = []; + this.connected_ = false; + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT; + this.securityDebugCallback_ = null; + this.lastSessionId = null; + this.establishConnectionTimer_ = null; + this.visible_ = false; + // Before we get connected, we keep a queue of pending messages to send. + this.requestCBHash_ = {}; + this.requestNumber_ = 0; + this.realtime_ = null; + this.authToken_ = null; + this.appCheckToken_ = null; + this.forceTokenRefresh_ = false; + this.invalidAuthTokenCount_ = 0; + this.invalidAppCheckTokenCount_ = 0; + this.firstConnection_ = true; + this.lastConnectionAttemptTime_ = null; + this.lastConnectionEstablishedTime_ = null; + if (authOverride_ && !isNodeSdk()) { + throw new Error('Auth override specified in options, but not supported on non Node.js platforms'); + } + VisibilityMonitor.getInstance().on('visible', this.onVisible_, this); + if (repoInfo_.host.indexOf('fblocal') === -1) { + OnlineMonitor.getInstance().on('online', this.onOnline_, this); + } + } + sendRequest(action, body, onResponse) { + const curReqNum = ++this.requestNumber_; + const msg = { r: curReqNum, a: action, b: body }; + this.log_(stringify(msg)); + assert(this.connected_, "sendRequest call when we're not connected not allowed."); + this.realtime_.sendRequest(msg); + if (onResponse) { + this.requestCBHash_[curReqNum] = onResponse; + } + } + get(query) { + this.initConnection_(); + const deferred = new Deferred(); + const request = { + p: query._path.toString(), + q: query._queryObject + }; + const outstandingGet = { + action: 'g', + request, + onComplete: (message) => { + const payload = message['d']; + if (message['s'] === 'ok') { + deferred.resolve(payload); + } + else { + deferred.reject(payload); + } + } + }; + this.outstandingGets_.push(outstandingGet); + this.outstandingGetCount_++; + const index = this.outstandingGets_.length - 1; + if (this.connected_) { + this.sendGet_(index); + } + return deferred.promise; + } + listen(query, currentHashFn, tag, onComplete) { + this.initConnection_(); + const queryId = query._queryIdentifier; + const pathString = query._path.toString(); + this.log_('Listen called for ' + pathString + ' ' + queryId); + if (!this.listens.has(pathString)) { + this.listens.set(pathString, new Map()); + } + assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query'); + assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`); + const listenSpec = { + onComplete, + hashFn: currentHashFn, + query, + tag + }; + this.listens.get(pathString).set(queryId, listenSpec); + if (this.connected_) { + this.sendListen_(listenSpec); + } + } + sendGet_(index) { + const get = this.outstandingGets_[index]; + this.sendRequest('g', get.request, (message) => { + delete this.outstandingGets_[index]; + this.outstandingGetCount_--; + if (this.outstandingGetCount_ === 0) { + this.outstandingGets_ = []; + } + if (get.onComplete) { + get.onComplete(message); + } + }); + } + sendListen_(listenSpec) { + const query = listenSpec.query; + const pathString = query._path.toString(); + const queryId = query._queryIdentifier; + this.log_('Listen on ' + pathString + ' for ' + queryId); + const req = { /*path*/ p: pathString }; + const action = 'q'; + // Only bother to send query if it's non-default. + if (listenSpec.tag) { + req['q'] = query._queryObject; + req['t'] = listenSpec.tag; + } + req[ /*hash*/'h'] = listenSpec.hashFn(); + this.sendRequest(action, req, (message) => { + const payload = message[ /*data*/'d']; + const status = message[ /*status*/'s']; + // print warnings in any case... + PersistentConnection.warnOnListenWarnings_(payload, query); + const currentListenSpec = this.listens.get(pathString) && + this.listens.get(pathString).get(queryId); + // only trigger actions if the listen hasn't been removed and readded + if (currentListenSpec === listenSpec) { + this.log_('listen response', message); + if (status !== 'ok') { + this.removeListen_(pathString, queryId); + } + if (listenSpec.onComplete) { + listenSpec.onComplete(status, payload); + } + } + }); + } + static warnOnListenWarnings_(payload, query) { + if (payload && typeof payload === 'object' && contains(payload, 'w')) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const warnings = safeGet(payload, 'w'); + if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) { + const indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"'; + const indexPath = query._path.toString(); + warn(`Using an unspecified index. Your data will be downloaded and ` + + `filtered on the client. Consider adding ${indexSpec} at ` + + `${indexPath} to your security rules for better performance.`); + } + } + } + refreshAuthToken(token) { + this.authToken_ = token; + this.log_('Auth token refreshed'); + if (this.authToken_) { + this.tryAuth(); + } + else { + //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete + //the credential so we dont become authenticated next time we connect. + if (this.connected_) { + this.sendRequest('unauth', {}, () => { }); + } + } + this.reduceReconnectDelayIfAdminCredential_(token); + } + reduceReconnectDelayIfAdminCredential_(credential) { + // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client). + // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires. + const isFirebaseSecret = credential && credential.length === 40; + if (isFirebaseSecret || isAdmin(credential)) { + this.log_('Admin auth credential detected. Reducing max reconnect time.'); + this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS; + } + } + refreshAppCheckToken(token) { + this.appCheckToken_ = token; + this.log_('App check token refreshed'); + if (this.appCheckToken_) { + this.tryAppCheck(); + } + else { + //If we're connected we want to let the server know to unauthenticate us. + //If we're not connected, simply delete the credential so we dont become + // authenticated next time we connect. + if (this.connected_) { + this.sendRequest('unappeck', {}, () => { }); + } + } + } + /** + * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like + * a auth revoked (the connection is closed). + */ + tryAuth() { + if (this.connected_ && this.authToken_) { + const token = this.authToken_; + const authMethod = isValidFormat(token) ? 'auth' : 'gauth'; + const requestData = { cred: token }; + if (this.authOverride_ === null) { + requestData['noauth'] = true; + } + else if (typeof this.authOverride_ === 'object') { + requestData['authvar'] = this.authOverride_; + } + this.sendRequest(authMethod, requestData, (res) => { + const status = res[ /*status*/'s']; + const data = res[ /*data*/'d'] || 'error'; + if (this.authToken_ === token) { + if (status === 'ok') { + this.invalidAuthTokenCount_ = 0; + } + else { + // Triggers reconnect and force refresh for auth token + this.onAuthRevoked_(status, data); + } + } + }); + } + } + /** + * Attempts to authenticate with the given token. If the authentication + * attempt fails, it's triggered like the token was revoked (the connection is + * closed). + */ + tryAppCheck() { + if (this.connected_ && this.appCheckToken_) { + this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => { + const status = res[ /*status*/'s']; + const data = res[ /*data*/'d'] || 'error'; + if (status === 'ok') { + this.invalidAppCheckTokenCount_ = 0; + } + else { + this.onAppCheckRevoked_(status, data); + } + }); + } + } + /** + * @inheritDoc + */ + unlisten(query, tag) { + const pathString = query._path.toString(); + const queryId = query._queryIdentifier; + this.log_('Unlisten called for ' + pathString + ' ' + queryId); + assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query'); + const listen = this.removeListen_(pathString, queryId); + if (listen && this.connected_) { + this.sendUnlisten_(pathString, queryId, query._queryObject, tag); + } + } + sendUnlisten_(pathString, queryId, queryObj, tag) { + this.log_('Unlisten on ' + pathString + ' for ' + queryId); + const req = { /*path*/ p: pathString }; + const action = 'n'; + // Only bother sending queryId if it's non-default. + if (tag) { + req['q'] = queryObj; + req['t'] = tag; + } + this.sendRequest(action, req); + } + onDisconnectPut(pathString, data, onComplete) { + this.initConnection_(); + if (this.connected_) { + this.sendOnDisconnect_('o', pathString, data, onComplete); + } + else { + this.onDisconnectRequestQueue_.push({ + pathString, + action: 'o', + data, + onComplete + }); + } + } + onDisconnectMerge(pathString, data, onComplete) { + this.initConnection_(); + if (this.connected_) { + this.sendOnDisconnect_('om', pathString, data, onComplete); + } + else { + this.onDisconnectRequestQueue_.push({ + pathString, + action: 'om', + data, + onComplete + }); + } + } + onDisconnectCancel(pathString, onComplete) { + this.initConnection_(); + if (this.connected_) { + this.sendOnDisconnect_('oc', pathString, null, onComplete); + } + else { + this.onDisconnectRequestQueue_.push({ + pathString, + action: 'oc', + data: null, + onComplete + }); + } + } + sendOnDisconnect_(action, pathString, data, onComplete) { + const request = { /*path*/ p: pathString, /*data*/ d: data }; + this.log_('onDisconnect ' + action, request); + this.sendRequest(action, request, (response) => { + if (onComplete) { + setTimeout(() => { + onComplete(response[ /*status*/'s'], response[ /* data */'d']); + }, Math.floor(0)); + } + }); + } + put(pathString, data, onComplete, hash) { + this.putInternal('p', pathString, data, onComplete, hash); + } + merge(pathString, data, onComplete, hash) { + this.putInternal('m', pathString, data, onComplete, hash); + } + putInternal(action, pathString, data, onComplete, hash) { + this.initConnection_(); + const request = { + /*path*/ p: pathString, + /*data*/ d: data + }; + if (hash !== undefined) { + request[ /*hash*/'h'] = hash; + } + // TODO: Only keep track of the most recent put for a given path? + this.outstandingPuts_.push({ + action, + request, + onComplete + }); + this.outstandingPutCount_++; + const index = this.outstandingPuts_.length - 1; + if (this.connected_) { + this.sendPut_(index); + } + else { + this.log_('Buffering put: ' + pathString); + } + } + sendPut_(index) { + const action = this.outstandingPuts_[index].action; + const request = this.outstandingPuts_[index].request; + const onComplete = this.outstandingPuts_[index].onComplete; + this.outstandingPuts_[index].queued = this.connected_; + this.sendRequest(action, request, (message) => { + this.log_(action + ' response', message); + delete this.outstandingPuts_[index]; + this.outstandingPutCount_--; + // Clean up array occasionally. + if (this.outstandingPutCount_ === 0) { + this.outstandingPuts_ = []; + } + if (onComplete) { + onComplete(message[ /*status*/'s'], message[ /* data */'d']); + } + }); + } + reportStats(stats) { + // If we're not connected, we just drop the stats. + if (this.connected_) { + const request = { /*counters*/ c: stats }; + this.log_('reportStats', request); + this.sendRequest(/*stats*/ 's', request, result => { + const status = result[ /*status*/'s']; + if (status !== 'ok') { + const errorReason = result[ /* data */'d']; + this.log_('reportStats', 'Error sending stats: ' + errorReason); + } + }); + } + } + onDataMessage_(message) { + if ('r' in message) { + // this is a response + this.log_('from server: ' + stringify(message)); + const reqNum = message['r']; + const onResponse = this.requestCBHash_[reqNum]; + if (onResponse) { + delete this.requestCBHash_[reqNum]; + onResponse(message[ /*body*/'b']); + } + } + else if ('error' in message) { + throw 'A server-side error has occurred: ' + message['error']; + } + else if ('a' in message) { + // a and b are action and body, respectively + this.onDataPush_(message['a'], message['b']); + } + } + onDataPush_(action, body) { + this.log_('handleServerMessage', action, body); + if (action === 'd') { + this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], + /*isMerge*/ false, body['t']); + } + else if (action === 'm') { + this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], + /*isMerge=*/ true, body['t']); + } + else if (action === 'c') { + this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']); + } + else if (action === 'ac') { + this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']); + } + else if (action === 'apc') { + this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']); + } + else if (action === 'sd') { + this.onSecurityDebugPacket_(body); + } + else { + error('Unrecognized action received from server: ' + + stringify(action) + + '\nAre you using the latest client?'); + } + } + onReady_(timestamp, sessionId) { + this.log_('connection ready'); + this.connected_ = true; + this.lastConnectionEstablishedTime_ = new Date().getTime(); + this.handleTimestamp_(timestamp); + this.lastSessionId = sessionId; + if (this.firstConnection_) { + this.sendConnectStats_(); + } + this.restoreState_(); + this.firstConnection_ = false; + this.onConnectStatus_(true); + } + scheduleConnect_(timeout) { + assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?"); + if (this.establishConnectionTimer_) { + clearTimeout(this.establishConnectionTimer_); + } + // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in + // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests). + this.establishConnectionTimer_ = setTimeout(() => { + this.establishConnectionTimer_ = null; + this.establishConnection_(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }, Math.floor(timeout)); + } + initConnection_() { + if (!this.realtime_ && this.firstConnection_) { + this.scheduleConnect_(0); + } + } + onVisible_(visible) { + // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine. + if (visible && + !this.visible_ && + this.reconnectDelay_ === this.maxReconnectDelay_) { + this.log_('Window became visible. Reducing delay.'); + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + if (!this.realtime_) { + this.scheduleConnect_(0); + } + } + this.visible_ = visible; + } + onOnline_(online) { + if (online) { + this.log_('Browser went online.'); + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + if (!this.realtime_) { + this.scheduleConnect_(0); + } + } + else { + this.log_('Browser went offline. Killing connection.'); + if (this.realtime_) { + this.realtime_.close(); + } + } + } + onRealtimeDisconnect_() { + this.log_('data client disconnected'); + this.connected_ = false; + this.realtime_ = null; + // Since we don't know if our sent transactions succeeded or not, we need to cancel them. + this.cancelSentTransactions_(); + // Clear out the pending requests. + this.requestCBHash_ = {}; + if (this.shouldReconnect_()) { + if (!this.visible_) { + this.log_("Window isn't visible. Delaying reconnect."); + this.reconnectDelay_ = this.maxReconnectDelay_; + this.lastConnectionAttemptTime_ = new Date().getTime(); + } + else if (this.lastConnectionEstablishedTime_) { + // If we've been connected long enough, reset reconnect delay to minimum. + const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_; + if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) { + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + } + this.lastConnectionEstablishedTime_ = null; + } + const timeSinceLastConnectAttempt = Math.max(0, new Date().getTime() - this.lastConnectionAttemptTime_); + let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt); + reconnectDelay = Math.random() * reconnectDelay; + this.log_('Trying to reconnect in ' + reconnectDelay + 'ms'); + this.scheduleConnect_(reconnectDelay); + // Adjust reconnect delay for next time. + this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER); + } + this.onConnectStatus_(false); + } + async establishConnection_() { + if (this.shouldReconnect_()) { + this.log_('Making a connection attempt'); + this.lastConnectionAttemptTime_ = new Date().getTime(); + this.lastConnectionEstablishedTime_ = null; + const onDataMessage = this.onDataMessage_.bind(this); + const onReady = this.onReady_.bind(this); + const onDisconnect = this.onRealtimeDisconnect_.bind(this); + const connId = this.id + ':' + PersistentConnection.nextConnectionId_++; + const lastSessionId = this.lastSessionId; + let canceled = false; + let connection = null; + const closeFn = function () { + if (connection) { + connection.close(); + } + else { + canceled = true; + onDisconnect(); + } + }; + const sendRequestFn = function (msg) { + assert(connection, "sendRequest call when we're not connected not allowed."); + connection.sendRequest(msg); + }; + this.realtime_ = { + close: closeFn, + sendRequest: sendRequestFn + }; + const forceRefresh = this.forceTokenRefresh_; + this.forceTokenRefresh_ = false; + try { + // First fetch auth and app check token, and establish connection after + // fetching the token was successful + const [authToken, appCheckToken] = await Promise.all([ + this.authTokenProvider_.getToken(forceRefresh), + this.appCheckTokenProvider_.getToken(forceRefresh) + ]); + if (!canceled) { + log('getToken() completed. Creating connection.'); + this.authToken_ = authToken && authToken.accessToken; + this.appCheckToken_ = appCheckToken && appCheckToken.token; + connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect, + /* onKill= */ reason => { + warn(reason + ' (' + this.repoInfo_.toString() + ')'); + this.interrupt(SERVER_KILL_INTERRUPT_REASON); + }, lastSessionId); + } + else { + log('getToken() completed but was canceled'); + } + } + catch (error) { + this.log_('Failed to get token: ' + error); + if (!canceled) { + if (this.repoInfo_.nodeAdmin) { + // This may be a critical error for the Admin Node.js SDK, so log a warning. + // But getToken() may also just have temporarily failed, so we still want to + // continue retrying. + warn(error); + } + closeFn(); + } + } + } + } + interrupt(reason) { + log('Interrupting connection for reason: ' + reason); + this.interruptReasons_[reason] = true; + if (this.realtime_) { + this.realtime_.close(); + } + else { + if (this.establishConnectionTimer_) { + clearTimeout(this.establishConnectionTimer_); + this.establishConnectionTimer_ = null; + } + if (this.connected_) { + this.onRealtimeDisconnect_(); + } + } + } + resume(reason) { + log('Resuming connection for reason: ' + reason); + delete this.interruptReasons_[reason]; + if (isEmpty(this.interruptReasons_)) { + this.reconnectDelay_ = RECONNECT_MIN_DELAY; + if (!this.realtime_) { + this.scheduleConnect_(0); + } + } + } + handleTimestamp_(timestamp) { + const delta = timestamp - new Date().getTime(); + this.onServerInfoUpdate_({ serverTimeOffset: delta }); + } + cancelSentTransactions_() { + for (let i = 0; i < this.outstandingPuts_.length; i++) { + const put = this.outstandingPuts_[i]; + if (put && /*hash*/ 'h' in put.request && put.queued) { + if (put.onComplete) { + put.onComplete('disconnect'); + } + delete this.outstandingPuts_[i]; + this.outstandingPutCount_--; + } + } + // Clean up array occasionally. + if (this.outstandingPutCount_ === 0) { + this.outstandingPuts_ = []; + } + } + onListenRevoked_(pathString, query) { + // Remove the listen and manufacture a "permission_denied" error for the failed listen. + let queryId; + if (!query) { + queryId = 'default'; + } + else { + queryId = query.map(q => ObjectToUniqueKey(q)).join('$'); + } + const listen = this.removeListen_(pathString, queryId); + if (listen && listen.onComplete) { + listen.onComplete('permission_denied'); + } + } + removeListen_(pathString, queryId) { + const normalizedPathString = new Path(pathString).toString(); // normalize path. + let listen; + if (this.listens.has(normalizedPathString)) { + const map = this.listens.get(normalizedPathString); + listen = map.get(queryId); + map.delete(queryId); + if (map.size === 0) { + this.listens.delete(normalizedPathString); + } + } + else { + // all listens for this path has already been removed + listen = undefined; + } + return listen; + } + onAuthRevoked_(statusCode, explanation) { + log('Auth token revoked: ' + statusCode + '/' + explanation); + this.authToken_ = null; + this.forceTokenRefresh_ = true; + this.realtime_.close(); + if (statusCode === 'invalid_token' || statusCode === 'permission_denied') { + // We'll wait a couple times before logging the warning / increasing the + // retry period since oauth tokens will report as "invalid" if they're + // just expired. Plus there may be transient issues that resolve themselves. + this.invalidAuthTokenCount_++; + if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) { + // Set a long reconnect delay because recovery is unlikely + this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS; + // Notify the auth token provider that the token is invalid, which will log + // a warning + this.authTokenProvider_.notifyForInvalidToken(); + } + } + } + onAppCheckRevoked_(statusCode, explanation) { + log('App check token revoked: ' + statusCode + '/' + explanation); + this.appCheckToken_ = null; + this.forceTokenRefresh_ = true; + // Note: We don't close the connection as the developer may not have + // enforcement enabled. The backend closes connections with enforcements. + if (statusCode === 'invalid_token' || statusCode === 'permission_denied') { + // We'll wait a couple times before logging the warning / increasing the + // retry period since oauth tokens will report as "invalid" if they're + // just expired. Plus there may be transient issues that resolve themselves. + this.invalidAppCheckTokenCount_++; + if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) { + this.appCheckTokenProvider_.notifyForInvalidToken(); + } + } + } + onSecurityDebugPacket_(body) { + if (this.securityDebugCallback_) { + this.securityDebugCallback_(body); + } + else { + if ('msg' in body) { + console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: ')); + } + } + } + restoreState_() { + //Re-authenticate ourselves if we have a credential stored. + this.tryAuth(); + this.tryAppCheck(); + // Puts depend on having received the corresponding data update from the server before they complete, so we must + // make sure to send listens before puts. + for (const queries of this.listens.values()) { + for (const listenSpec of queries.values()) { + this.sendListen_(listenSpec); + } + } + for (let i = 0; i < this.outstandingPuts_.length; i++) { + if (this.outstandingPuts_[i]) { + this.sendPut_(i); + } + } + while (this.onDisconnectRequestQueue_.length) { + const request = this.onDisconnectRequestQueue_.shift(); + this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete); + } + for (let i = 0; i < this.outstandingGets_.length; i++) { + if (this.outstandingGets_[i]) { + this.sendGet_(i); + } + } + } + /** + * Sends client stats for first connection + */ + sendConnectStats_() { + const stats = {}; + let clientName = 'js'; + if (isNodeSdk()) { + if (this.repoInfo_.nodeAdmin) { + clientName = 'admin_node'; + } + else { + clientName = 'node'; + } + } + stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1; + if (isMobileCordova()) { + stats['framework.cordova'] = 1; + } + else if (isReactNative()) { + stats['framework.reactnative'] = 1; + } + this.reportStats(stats); + } + shouldReconnect_() { + const online = OnlineMonitor.getInstance().currentlyOnline(); + return isEmpty(this.interruptReasons_) && online; + } +} +PersistentConnection.nextPersistentConnectionId_ = 0; +/** + * Counter for number of connections created. Mainly used for tagging in the logs + */ +PersistentConnection.nextConnectionId_ = 0; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class NamedNode { + constructor(name, node) { + this.name = name; + this.node = node; + } + static Wrap(name, node) { + return new NamedNode(name, node); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Index { + /** + * @returns A standalone comparison function for + * this index + */ + getCompare() { + return this.compare.bind(this); + } + /** + * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different, + * it's possible that the changes are isolated to parts of the snapshot that are not indexed. + * + * + * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode + */ + indexedValueChanged(oldNode, newNode) { + const oldWrapped = new NamedNode(MIN_NAME, oldNode); + const newWrapped = new NamedNode(MIN_NAME, newNode); + return this.compare(oldWrapped, newWrapped) !== 0; + } + /** + * @returns a node wrapper that will sort equal to or less than + * any other node wrapper, using this index + */ + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let __EMPTY_NODE; +class KeyIndex extends Index { + static get __EMPTY_NODE() { + return __EMPTY_NODE; + } + static set __EMPTY_NODE(val) { + __EMPTY_NODE = val; + } + compare(a, b) { + return nameCompare(a.name, b.name); + } + isDefinedOn(node) { + // We could probably return true here (since every node has a key), but it's never called + // so just leaving unimplemented for now. + throw assertionError('KeyIndex.isDefinedOn not expected to be called.'); + } + indexedValueChanged(oldNode, newNode) { + return false; // The key for a node never changes. + } + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } + maxPost() { + // TODO: This should really be created once and cached in a static property, but + // NamedNode isn't defined yet, so I can't use it in a static. Bleh. + return new NamedNode(MAX_NAME, __EMPTY_NODE); + } + makePost(indexValue, name) { + assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.'); + // We just use empty node, but it'll never be compared, since our comparator only looks at name. + return new NamedNode(indexValue, __EMPTY_NODE); + } + /** + * @returns String representation for inclusion in a query spec + */ + toString() { + return '.key'; + } +} +const KEY_INDEX = new KeyIndex(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An iterator over an LLRBNode. + */ +class SortedMapIterator { + /** + * @param node - Node to iterate. + * @param isReverse_ - Whether or not to iterate in reverse + */ + constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) { + this.isReverse_ = isReverse_; + this.resultGenerator_ = resultGenerator_; + this.nodeStack_ = []; + let cmp = 1; + while (!node.isEmpty()) { + node = node; + cmp = startKey ? comparator(node.key, startKey) : 1; + // flip the comparison if we're going in reverse + if (isReverse_) { + cmp *= -1; + } + if (cmp < 0) { + // This node is less than our start key. ignore it + if (this.isReverse_) { + node = node.left; + } + else { + node = node.right; + } + } + else if (cmp === 0) { + // This node is exactly equal to our start key. Push it on the stack, but stop iterating; + this.nodeStack_.push(node); + break; + } + else { + // This node is greater than our start key, add it to the stack and move to the next one + this.nodeStack_.push(node); + if (this.isReverse_) { + node = node.right; + } + else { + node = node.left; + } + } + } + } + getNext() { + if (this.nodeStack_.length === 0) { + return null; + } + let node = this.nodeStack_.pop(); + let result; + if (this.resultGenerator_) { + result = this.resultGenerator_(node.key, node.value); + } + else { + result = { key: node.key, value: node.value }; + } + if (this.isReverse_) { + node = node.left; + while (!node.isEmpty()) { + this.nodeStack_.push(node); + node = node.right; + } + } + else { + node = node.right; + while (!node.isEmpty()) { + this.nodeStack_.push(node); + node = node.left; + } + } + return result; + } + hasNext() { + return this.nodeStack_.length > 0; + } + peek() { + if (this.nodeStack_.length === 0) { + return null; + } + const node = this.nodeStack_[this.nodeStack_.length - 1]; + if (this.resultGenerator_) { + return this.resultGenerator_(node.key, node.value); + } + else { + return { key: node.key, value: node.value }; + } + } +} +/** + * Represents a node in a Left-leaning Red-Black tree. + */ +class LLRBNode { + /** + * @param key - Key associated with this node. + * @param value - Value associated with this node. + * @param color - Whether this node is red. + * @param left - Left child. + * @param right - Right child. + */ + constructor(key, value, color, left, right) { + this.key = key; + this.value = value; + this.color = color != null ? color : LLRBNode.RED; + this.left = + left != null ? left : SortedMap.EMPTY_NODE; + this.right = + right != null ? right : SortedMap.EMPTY_NODE; + } + /** + * Returns a copy of the current node, optionally replacing pieces of it. + * + * @param key - New key for the node, or null. + * @param value - New value for the node, or null. + * @param color - New color for the node, or null. + * @param left - New left child for the node, or null. + * @param right - New right child for the node, or null. + * @returns The node copy. + */ + copy(key, value, color, left, right) { + return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right); + } + /** + * @returns The total number of nodes in the tree. + */ + count() { + return this.left.count() + 1 + this.right.count(); + } + /** + * @returns True if the tree is empty. + */ + isEmpty() { + return false; + } + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action) { + return (this.left.inorderTraversal(action) || + !!action(this.key, this.value) || + this.right.inorderTraversal(action)); + } + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action) { + return (this.right.reverseTraversal(action) || + action(this.key, this.value) || + this.left.reverseTraversal(action)); + } + /** + * @returns The minimum node in the tree. + */ + min_() { + if (this.left.isEmpty()) { + return this; + } + else { + return this.left.min_(); + } + } + /** + * @returns The maximum key in the tree. + */ + minKey() { + return this.min_().key; + } + /** + * @returns The maximum key in the tree. + */ + maxKey() { + if (this.right.isEmpty()) { + return this.key; + } + else { + return this.right.maxKey(); + } + } + /** + * @param key - Key to insert. + * @param value - Value to insert. + * @param comparator - Comparator. + * @returns New tree, with the key/value added. + */ + insert(key, value, comparator) { + let n = this; + const cmp = comparator(key, n.key); + if (cmp < 0) { + n = n.copy(null, null, null, n.left.insert(key, value, comparator), null); + } + else if (cmp === 0) { + n = n.copy(null, value, null, null, null); + } + else { + n = n.copy(null, null, null, null, n.right.insert(key, value, comparator)); + } + return n.fixUp_(); + } + /** + * @returns New tree, with the minimum key removed. + */ + removeMin_() { + if (this.left.isEmpty()) { + return SortedMap.EMPTY_NODE; + } + let n = this; + if (!n.left.isRed_() && !n.left.left.isRed_()) { + n = n.moveRedLeft_(); + } + n = n.copy(null, null, null, n.left.removeMin_(), null); + return n.fixUp_(); + } + /** + * @param key - The key of the item to remove. + * @param comparator - Comparator. + * @returns New tree, with the specified item removed. + */ + remove(key, comparator) { + let n, smallest; + n = this; + if (comparator(key, n.key) < 0) { + if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) { + n = n.moveRedLeft_(); + } + n = n.copy(null, null, null, n.left.remove(key, comparator), null); + } + else { + if (n.left.isRed_()) { + n = n.rotateRight_(); + } + if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) { + n = n.moveRedRight_(); + } + if (comparator(key, n.key) === 0) { + if (n.right.isEmpty()) { + return SortedMap.EMPTY_NODE; + } + else { + smallest = n.right.min_(); + n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_()); + } + } + n = n.copy(null, null, null, null, n.right.remove(key, comparator)); + } + return n.fixUp_(); + } + /** + * @returns Whether this is a RED node. + */ + isRed_() { + return this.color; + } + /** + * @returns New tree after performing any needed rotations. + */ + fixUp_() { + let n = this; + if (n.right.isRed_() && !n.left.isRed_()) { + n = n.rotateLeft_(); + } + if (n.left.isRed_() && n.left.left.isRed_()) { + n = n.rotateRight_(); + } + if (n.left.isRed_() && n.right.isRed_()) { + n = n.colorFlip_(); + } + return n; + } + /** + * @returns New tree, after moveRedLeft. + */ + moveRedLeft_() { + let n = this.colorFlip_(); + if (n.right.left.isRed_()) { + n = n.copy(null, null, null, null, n.right.rotateRight_()); + n = n.rotateLeft_(); + n = n.colorFlip_(); + } + return n; + } + /** + * @returns New tree, after moveRedRight. + */ + moveRedRight_() { + let n = this.colorFlip_(); + if (n.left.left.isRed_()) { + n = n.rotateRight_(); + n = n.colorFlip_(); + } + return n; + } + /** + * @returns New tree, after rotateLeft. + */ + rotateLeft_() { + const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, nl, null); + } + /** + * @returns New tree, after rotateRight. + */ + rotateRight_() { + const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, nr); + } + /** + * @returns Newt ree, after colorFlip. + */ + colorFlip_() { + const left = this.left.copy(null, null, !this.left.color, null, null); + const right = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, left, right); + } + /** + * For testing. + * + * @returns True if all is well. + */ + checkMaxDepth_() { + const blackDepth = this.check_(); + return Math.pow(2.0, blackDepth) <= this.count() + 1; + } + check_() { + if (this.isRed_() && this.left.isRed_()) { + throw new Error('Red node has red child(' + this.key + ',' + this.value + ')'); + } + if (this.right.isRed_()) { + throw new Error('Right child of (' + this.key + ',' + this.value + ') is red'); + } + const blackDepth = this.left.check_(); + if (blackDepth !== this.right.check_()) { + throw new Error('Black depths differ'); + } + else { + return blackDepth + (this.isRed_() ? 0 : 1); + } + } +} +LLRBNode.RED = true; +LLRBNode.BLACK = false; +/** + * Represents an empty node (a leaf node in the Red-Black Tree). + */ +class LLRBEmptyNode { + /** + * Returns a copy of the current node. + * + * @returns The node copy. + */ + copy(key, value, color, left, right) { + return this; + } + /** + * Returns a copy of the tree, with the specified key/value added. + * + * @param key - Key to be added. + * @param value - Value to be added. + * @param comparator - Comparator. + * @returns New tree, with item added. + */ + insert(key, value, comparator) { + return new LLRBNode(key, value, null); + } + /** + * Returns a copy of the tree, with the specified key removed. + * + * @param key - The key to remove. + * @param comparator - Comparator. + * @returns New tree, with item removed. + */ + remove(key, comparator) { + return this; + } + /** + * @returns The total number of nodes in the tree. + */ + count() { + return 0; + } + /** + * @returns True if the tree is empty. + */ + isEmpty() { + return true; + } + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + inorderTraversal(action) { + return false; + } + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action) { + return false; + } + minKey() { + return null; + } + maxKey() { + return null; + } + check_() { + return 0; + } + /** + * @returns Whether this node is red. + */ + isRed_() { + return false; + } +} +/** + * An immutable sorted map implementation, based on a Left-leaning Red-Black + * tree. + */ +class SortedMap { + /** + * @param comparator_ - Key comparator. + * @param root_ - Optional root node for the map. + */ + constructor(comparator_, root_ = SortedMap.EMPTY_NODE) { + this.comparator_ = comparator_; + this.root_ = root_; + } + /** + * Returns a copy of the map, with the specified key/value added or replaced. + * (TODO: We should perhaps rename this method to 'put') + * + * @param key - Key to be added. + * @param value - Value to be added. + * @returns New map, with item added. + */ + insert(key, value) { + return new SortedMap(this.comparator_, this.root_ + .insert(key, value, this.comparator_) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + /** + * Returns a copy of the map, with the specified key removed. + * + * @param key - The key to remove. + * @returns New map, with item removed. + */ + remove(key) { + return new SortedMap(this.comparator_, this.root_ + .remove(key, this.comparator_) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + /** + * Returns the value of the node with the given key, or null. + * + * @param key - The key to look up. + * @returns The value of the node with the given key, or null if the + * key doesn't exist. + */ + get(key) { + let cmp; + let node = this.root_; + while (!node.isEmpty()) { + cmp = this.comparator_(key, node.key); + if (cmp === 0) { + return node.value; + } + else if (cmp < 0) { + node = node.left; + } + else if (cmp > 0) { + node = node.right; + } + } + return null; + } + /** + * Returns the key of the item *before* the specified key, or null if key is the first item. + * @param key - The key to find the predecessor of + * @returns The predecessor key. + */ + getPredecessorKey(key) { + let cmp, node = this.root_, rightParent = null; + while (!node.isEmpty()) { + cmp = this.comparator_(key, node.key); + if (cmp === 0) { + if (!node.left.isEmpty()) { + node = node.left; + while (!node.right.isEmpty()) { + node = node.right; + } + return node.key; + } + else if (rightParent) { + return rightParent.key; + } + else { + return null; // first item. + } + } + else if (cmp < 0) { + node = node.left; + } + else if (cmp > 0) { + rightParent = node; + node = node.right; + } + } + throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?'); + } + /** + * @returns True if the map is empty. + */ + isEmpty() { + return this.root_.isEmpty(); + } + /** + * @returns The total number of nodes in the map. + */ + count() { + return this.root_.count(); + } + /** + * @returns The minimum key in the map. + */ + minKey() { + return this.root_.minKey(); + } + /** + * @returns The maximum key in the map. + */ + maxKey() { + return this.root_.maxKey(); + } + /** + * Traverses the map in key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action) { + return this.root_.inorderTraversal(action); + } + /** + * Traverses the map in reverse key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns True if the traversal was aborted. + */ + reverseTraversal(action) { + return this.root_.reverseTraversal(action); + } + /** + * Returns an iterator over the SortedMap. + * @returns The iterator. + */ + getIterator(resultGenerator) { + return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator); + } + getIteratorFrom(key, resultGenerator) { + return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator); + } + getReverseIteratorFrom(key, resultGenerator) { + return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator); + } + getReverseIterator(resultGenerator) { + return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator); + } +} +/** + * Always use the same empty node, to reduce memory. + */ +SortedMap.EMPTY_NODE = new LLRBEmptyNode(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function NAME_ONLY_COMPARATOR(left, right) { + return nameCompare(left.name, right.name); +} +function NAME_COMPARATOR(left, right) { + return nameCompare(left, right); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let MAX_NODE$2; +function setMaxNode$1(val) { + MAX_NODE$2 = val; +} +const priorityHashText = function (priority) { + if (typeof priority === 'number') { + return 'number:' + doubleToIEEE754String(priority); + } + else { + return 'string:' + priority; + } +}; +/** + * Validates that a priority snapshot Node is valid. + */ +const validatePriorityNode = function (priorityNode) { + if (priorityNode.isLeafNode()) { + const val = priorityNode.val(); + assert(typeof val === 'string' || + typeof val === 'number' || + (typeof val === 'object' && contains(val, '.sv')), 'Priority must be a string or number.'); + } + else { + assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.'); + } + // Don't call getPriority() on MAX_NODE to avoid hitting assertion. + assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own."); +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let __childrenNodeConstructor; +/** + * LeafNode is a class for storing leaf nodes in a DataSnapshot. It + * implements Node and stores the value of the node (a string, + * number, or boolean) accessible via getValue(). + */ +class LeafNode { + static set __childrenNodeConstructor(val) { + __childrenNodeConstructor = val; + } + static get __childrenNodeConstructor() { + return __childrenNodeConstructor; + } + /** + * @param value_ - The value to store in this leaf node. The object type is + * possible in the event of a deferred value + * @param priorityNode_ - The priority of this node. + */ + constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) { + this.value_ = value_; + this.priorityNode_ = priorityNode_; + this.lazyHash_ = null; + assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value."); + validatePriorityNode(this.priorityNode_); + } + /** @inheritDoc */ + isLeafNode() { + return true; + } + /** @inheritDoc */ + getPriority() { + return this.priorityNode_; + } + /** @inheritDoc */ + updatePriority(newPriorityNode) { + return new LeafNode(this.value_, newPriorityNode); + } + /** @inheritDoc */ + getImmediateChild(childName) { + // Hack to treat priority as a regular child + if (childName === '.priority') { + return this.priorityNode_; + } + else { + return LeafNode.__childrenNodeConstructor.EMPTY_NODE; + } + } + /** @inheritDoc */ + getChild(path) { + if (pathIsEmpty(path)) { + return this; + } + else if (pathGetFront(path) === '.priority') { + return this.priorityNode_; + } + else { + return LeafNode.__childrenNodeConstructor.EMPTY_NODE; + } + } + hasChild() { + return false; + } + /** @inheritDoc */ + getPredecessorChildName(childName, childNode) { + return null; + } + /** @inheritDoc */ + updateImmediateChild(childName, newChildNode) { + if (childName === '.priority') { + return this.updatePriority(newChildNode); + } + else if (newChildNode.isEmpty() && childName !== '.priority') { + return this; + } + else { + return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_); + } + } + /** @inheritDoc */ + updateChild(path, newChildNode) { + const front = pathGetFront(path); + if (front === null) { + return newChildNode; + } + else if (newChildNode.isEmpty() && front !== '.priority') { + return this; + } + else { + assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path'); + return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode)); + } + } + /** @inheritDoc */ + isEmpty() { + return false; + } + /** @inheritDoc */ + numChildren() { + return 0; + } + /** @inheritDoc */ + forEachChild(index, action) { + return false; + } + val(exportFormat) { + if (exportFormat && !this.getPriority().isEmpty()) { + return { + '.value': this.getValue(), + '.priority': this.getPriority().val() + }; + } + else { + return this.getValue(); + } + } + /** @inheritDoc */ + hash() { + if (this.lazyHash_ === null) { + let toHash = ''; + if (!this.priorityNode_.isEmpty()) { + toHash += + 'priority:' + + priorityHashText(this.priorityNode_.val()) + + ':'; + } + const type = typeof this.value_; + toHash += type + ':'; + if (type === 'number') { + toHash += doubleToIEEE754String(this.value_); + } + else { + toHash += this.value_; + } + this.lazyHash_ = sha1(toHash); + } + return this.lazyHash_; + } + /** + * Returns the value of the leaf node. + * @returns The value of the node. + */ + getValue() { + return this.value_; + } + compareTo(other) { + if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) { + return 1; + } + else if (other instanceof LeafNode.__childrenNodeConstructor) { + return -1; + } + else { + assert(other.isLeafNode(), 'Unknown node type'); + return this.compareToLeafNode_(other); + } + } + /** + * Comparison specifically for two leaf nodes + */ + compareToLeafNode_(otherLeaf) { + const otherLeafType = typeof otherLeaf.value_; + const thisLeafType = typeof this.value_; + const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType); + const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType); + assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType); + assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType); + if (otherIndex === thisIndex) { + // Same type, compare values + if (thisLeafType === 'object') { + // Deferred value nodes are all equal, but we should also never get to this point... + return 0; + } + else { + // Note that this works because true > false, all others are number or string comparisons + if (this.value_ < otherLeaf.value_) { + return -1; + } + else if (this.value_ === otherLeaf.value_) { + return 0; + } + else { + return 1; + } + } + } + else { + return thisIndex - otherIndex; + } + } + withIndex() { + return this; + } + isIndexed() { + return true; + } + equals(other) { + if (other === this) { + return true; + } + else if (other.isLeafNode()) { + const otherLeaf = other; + return (this.value_ === otherLeaf.value_ && + this.priorityNode_.equals(otherLeaf.priorityNode_)); + } + else { + return false; + } + } +} +/** + * The sort order for comparing leaf nodes of different types. If two leaf nodes have + * the same type, the comparison falls back to their value + */ +LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string']; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let nodeFromJSON$1; +let MAX_NODE$1; +function setNodeFromJSON(val) { + nodeFromJSON$1 = val; +} +function setMaxNode(val) { + MAX_NODE$1 = val; +} +class PriorityIndex extends Index { + compare(a, b) { + const aPriority = a.node.getPriority(); + const bPriority = b.node.getPriority(); + const indexCmp = aPriority.compareTo(bPriority); + if (indexCmp === 0) { + return nameCompare(a.name, b.name); + } + else { + return indexCmp; + } + } + isDefinedOn(node) { + return !node.getPriority().isEmpty(); + } + indexedValueChanged(oldNode, newNode) { + return !oldNode.getPriority().equals(newNode.getPriority()); + } + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } + maxPost() { + return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1)); + } + makePost(indexValue, name) { + const priorityNode = nodeFromJSON$1(indexValue); + return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode)); + } + /** + * @returns String representation for inclusion in a query spec + */ + toString() { + return '.priority'; + } +} +const PRIORITY_INDEX = new PriorityIndex(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_2 = Math.log(2); +class Base12Num { + constructor(length) { + const logBase2 = (num) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + parseInt((Math.log(num) / LOG_2), 10); + const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2); + this.count = logBase2(length + 1); + this.current_ = this.count - 1; + const mask = bitMask(this.count); + this.bits_ = (length + 1) & mask; + } + nextBitIsOne() { + //noinspection JSBitwiseOperatorUsage + const result = !(this.bits_ & (0x1 << this.current_)); + this.current_--; + return result; + } +} +/** + * Takes a list of child nodes and constructs a SortedSet using the given comparison + * function + * + * Uses the algorithm described in the paper linked here: + * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458 + * + * @param childList - Unsorted list of children + * @param cmp - The comparison method to be used + * @param keyFn - An optional function to extract K from a node wrapper, if K's + * type is not NamedNode + * @param mapSortFn - An optional override for comparator used by the generated sorted map + */ +const buildChildSet = function (childList, cmp, keyFn, mapSortFn) { + childList.sort(cmp); + const buildBalancedTree = function (low, high) { + const length = high - low; + let namedNode; + let key; + if (length === 0) { + return null; + } + else if (length === 1) { + namedNode = childList[low]; + key = keyFn ? keyFn(namedNode) : namedNode; + return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null); + } + else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const middle = parseInt((length / 2), 10) + low; + const left = buildBalancedTree(low, middle); + const right = buildBalancedTree(middle + 1, high); + namedNode = childList[middle]; + key = keyFn ? keyFn(namedNode) : namedNode; + return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right); + } + }; + const buildFrom12Array = function (base12) { + let node = null; + let root = null; + let index = childList.length; + const buildPennant = function (chunkSize, color) { + const low = index - chunkSize; + const high = index; + index -= chunkSize; + const childTree = buildBalancedTree(low + 1, high); + const namedNode = childList[low]; + const key = keyFn ? keyFn(namedNode) : namedNode; + attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree)); + }; + const attachPennant = function (pennant) { + if (node) { + node.left = pennant; + node = pennant; + } + else { + root = pennant; + node = pennant; + } + }; + for (let i = 0; i < base12.count; ++i) { + const isOne = base12.nextBitIsOne(); + // The number of nodes taken in each slice is 2^(arr.length - (i + 1)) + const chunkSize = Math.pow(2, base12.count - (i + 1)); + if (isOne) { + buildPennant(chunkSize, LLRBNode.BLACK); + } + else { + // current == 2 + buildPennant(chunkSize, LLRBNode.BLACK); + buildPennant(chunkSize, LLRBNode.RED); + } + } + return root; + }; + const base12 = new Base12Num(childList.length); + const root = buildFrom12Array(base12); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return new SortedMap(mapSortFn || cmp, root); +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let _defaultIndexMap; +const fallbackObject = {}; +class IndexMap { + /** + * The default IndexMap for nodes without a priority + */ + static get Default() { + assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded'); + _defaultIndexMap = + _defaultIndexMap || + new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX }); + return _defaultIndexMap; + } + constructor(indexes_, indexSet_) { + this.indexes_ = indexes_; + this.indexSet_ = indexSet_; + } + get(indexKey) { + const sortedMap = safeGet(this.indexes_, indexKey); + if (!sortedMap) { + throw new Error('No index defined for ' + indexKey); + } + if (sortedMap instanceof SortedMap) { + return sortedMap; + } + else { + // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the + // regular child map + return null; + } + } + hasIndex(indexDefinition) { + return contains(this.indexSet_, indexDefinition.toString()); + } + addIndex(indexDefinition, existingChildren) { + assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap."); + const childList = []; + let sawIndexedValue = false; + const iter = existingChildren.getIterator(NamedNode.Wrap); + let next = iter.getNext(); + while (next) { + sawIndexedValue = + sawIndexedValue || indexDefinition.isDefinedOn(next.node); + childList.push(next); + next = iter.getNext(); + } + let newIndex; + if (sawIndexedValue) { + newIndex = buildChildSet(childList, indexDefinition.getCompare()); + } + else { + newIndex = fallbackObject; + } + const indexName = indexDefinition.toString(); + const newIndexSet = { ...this.indexSet_ }; + newIndexSet[indexName] = indexDefinition; + const newIndexes = { ...this.indexes_ }; + newIndexes[indexName] = newIndex; + return new IndexMap(newIndexes, newIndexSet); + } + /** + * Ensure that this node is properly tracked in any indexes that we're maintaining + */ + addToIndexes(namedNode, existingChildren) { + const newIndexes = map(this.indexes_, (indexedChildren, indexName) => { + const index = safeGet(this.indexSet_, indexName); + assert(index, 'Missing index implementation for ' + indexName); + if (indexedChildren === fallbackObject) { + // Check to see if we need to index everything + if (index.isDefinedOn(namedNode.node)) { + // We need to build this index + const childList = []; + const iter = existingChildren.getIterator(NamedNode.Wrap); + let next = iter.getNext(); + while (next) { + if (next.name !== namedNode.name) { + childList.push(next); + } + next = iter.getNext(); + } + childList.push(namedNode); + return buildChildSet(childList, index.getCompare()); + } + else { + // No change, this remains a fallback + return fallbackObject; + } + } + else { + const existingSnap = existingChildren.get(namedNode.name); + let newChildren = indexedChildren; + if (existingSnap) { + newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap)); + } + return newChildren.insert(namedNode, namedNode.node); + } + }); + return new IndexMap(newIndexes, this.indexSet_); + } + /** + * Create a new IndexMap instance with the given value removed + */ + removeFromIndexes(namedNode, existingChildren) { + const newIndexes = map(this.indexes_, (indexedChildren) => { + if (indexedChildren === fallbackObject) { + // This is the fallback. Just return it, nothing to do in this case + return indexedChildren; + } + else { + const existingSnap = existingChildren.get(namedNode.name); + if (existingSnap) { + return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap)); + } + else { + // No record of this child + return indexedChildren; + } + } + }); + return new IndexMap(newIndexes, this.indexSet_); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO: For memory savings, don't store priorityNode_ if it's empty. +let EMPTY_NODE; +/** + * ChildrenNode is a class for storing internal nodes in a DataSnapshot + * (i.e. nodes with children). It implements Node and stores the + * list of children in the children property, sorted by child name. + */ +class ChildrenNode { + static get EMPTY_NODE() { + return (EMPTY_NODE || + (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default))); + } + /** + * @param children_ - List of children of this node.. + * @param priorityNode_ - The priority of this node (as a snapshot node). + */ + constructor(children_, priorityNode_, indexMap_) { + this.children_ = children_; + this.priorityNode_ = priorityNode_; + this.indexMap_ = indexMap_; + this.lazyHash_ = null; + /** + * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use + * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own + * class instead of an empty ChildrenNode. + */ + if (this.priorityNode_) { + validatePriorityNode(this.priorityNode_); + } + if (this.children_.isEmpty()) { + assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority'); + } + } + /** @inheritDoc */ + isLeafNode() { + return false; + } + /** @inheritDoc */ + getPriority() { + return this.priorityNode_ || EMPTY_NODE; + } + /** @inheritDoc */ + updatePriority(newPriorityNode) { + if (this.children_.isEmpty()) { + // Don't allow priorities on empty nodes + return this; + } + else { + return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_); + } + } + /** @inheritDoc */ + getImmediateChild(childName) { + // Hack to treat priority as a regular child + if (childName === '.priority') { + return this.getPriority(); + } + else { + const child = this.children_.get(childName); + return child === null ? EMPTY_NODE : child; + } + } + /** @inheritDoc */ + getChild(path) { + const front = pathGetFront(path); + if (front === null) { + return this; + } + return this.getImmediateChild(front).getChild(pathPopFront(path)); + } + /** @inheritDoc */ + hasChild(childName) { + return this.children_.get(childName) !== null; + } + /** @inheritDoc */ + updateImmediateChild(childName, newChildNode) { + assert(newChildNode, 'We should always be passing snapshot nodes'); + if (childName === '.priority') { + return this.updatePriority(newChildNode); + } + else { + const namedNode = new NamedNode(childName, newChildNode); + let newChildren, newIndexMap; + if (newChildNode.isEmpty()) { + newChildren = this.children_.remove(childName); + newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_); + } + else { + newChildren = this.children_.insert(childName, newChildNode); + newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_); + } + const newPriority = newChildren.isEmpty() + ? EMPTY_NODE + : this.priorityNode_; + return new ChildrenNode(newChildren, newPriority, newIndexMap); + } + } + /** @inheritDoc */ + updateChild(path, newChildNode) { + const front = pathGetFront(path); + if (front === null) { + return newChildNode; + } + else { + assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path'); + const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode); + return this.updateImmediateChild(front, newImmediateChild); + } + } + /** @inheritDoc */ + isEmpty() { + return this.children_.isEmpty(); + } + /** @inheritDoc */ + numChildren() { + return this.children_.count(); + } + /** @inheritDoc */ + val(exportFormat) { + if (this.isEmpty()) { + return null; + } + const obj = {}; + let numKeys = 0, maxKey = 0, allIntegerKeys = true; + this.forEachChild(PRIORITY_INDEX, (key, childNode) => { + obj[key] = childNode.val(exportFormat); + numKeys++; + if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) { + maxKey = Math.max(maxKey, Number(key)); + } + else { + allIntegerKeys = false; + } + }); + if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) { + // convert to array. + const array = []; + // eslint-disable-next-line guard-for-in + for (const key in obj) { + array[key] = obj[key]; + } + return array; + } + else { + if (exportFormat && !this.getPriority().isEmpty()) { + obj['.priority'] = this.getPriority().val(); + } + return obj; + } + } + /** @inheritDoc */ + hash() { + if (this.lazyHash_ === null) { + let toHash = ''; + if (!this.getPriority().isEmpty()) { + toHash += + 'priority:' + + priorityHashText(this.getPriority().val()) + + ':'; + } + this.forEachChild(PRIORITY_INDEX, (key, childNode) => { + const childHash = childNode.hash(); + if (childHash !== '') { + toHash += ':' + key + ':' + childHash; + } + }); + this.lazyHash_ = toHash === '' ? '' : sha1(toHash); + } + return this.lazyHash_; + } + /** @inheritDoc */ + getPredecessorChildName(childName, childNode, index) { + const idx = this.resolveIndex_(index); + if (idx) { + const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode)); + return predecessor ? predecessor.name : null; + } + else { + return this.children_.getPredecessorKey(childName); + } + } + getFirstChildName(indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + const minKey = idx.minKey(); + return minKey && minKey.name; + } + else { + return this.children_.minKey(); + } + } + getFirstChild(indexDefinition) { + const minKey = this.getFirstChildName(indexDefinition); + if (minKey) { + return new NamedNode(minKey, this.children_.get(minKey)); + } + else { + return null; + } + } + /** + * Given an index, return the key name of the largest value we have, according to that index + */ + getLastChildName(indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + const maxKey = idx.maxKey(); + return maxKey && maxKey.name; + } + else { + return this.children_.maxKey(); + } + } + getLastChild(indexDefinition) { + const maxKey = this.getLastChildName(indexDefinition); + if (maxKey) { + return new NamedNode(maxKey, this.children_.get(maxKey)); + } + else { + return null; + } + } + forEachChild(index, action) { + const idx = this.resolveIndex_(index); + if (idx) { + return idx.inorderTraversal(wrappedNode => { + return action(wrappedNode.name, wrappedNode.node); + }); + } + else { + return this.children_.inorderTraversal(action); + } + } + getIterator(indexDefinition) { + return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition); + } + getIteratorFrom(startPost, indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + return idx.getIteratorFrom(startPost, key => key); + } + else { + const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap); + let next = iterator.peek(); + while (next != null && indexDefinition.compare(next, startPost) < 0) { + iterator.getNext(); + next = iterator.peek(); + } + return iterator; + } + } + getReverseIterator(indexDefinition) { + return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition); + } + getReverseIteratorFrom(endPost, indexDefinition) { + const idx = this.resolveIndex_(indexDefinition); + if (idx) { + return idx.getReverseIteratorFrom(endPost, key => { + return key; + }); + } + else { + const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap); + let next = iterator.peek(); + while (next != null && indexDefinition.compare(next, endPost) > 0) { + iterator.getNext(); + next = iterator.peek(); + } + return iterator; + } + } + compareTo(other) { + if (this.isEmpty()) { + if (other.isEmpty()) { + return 0; + } + else { + return -1; + } + } + else if (other.isLeafNode() || other.isEmpty()) { + return 1; + } + else if (other === MAX_NODE) { + return -1; + } + else { + // Must be another node with children. + return 0; + } + } + withIndex(indexDefinition) { + if (indexDefinition === KEY_INDEX || + this.indexMap_.hasIndex(indexDefinition)) { + return this; + } + else { + const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_); + return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap); + } + } + isIndexed(index) { + return index === KEY_INDEX || this.indexMap_.hasIndex(index); + } + equals(other) { + if (other === this) { + return true; + } + else if (other.isLeafNode()) { + return false; + } + else { + const otherChildrenNode = other; + if (!this.getPriority().equals(otherChildrenNode.getPriority())) { + return false; + } + else if (this.children_.count() === otherChildrenNode.children_.count()) { + const thisIter = this.getIterator(PRIORITY_INDEX); + const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX); + let thisCurrent = thisIter.getNext(); + let otherCurrent = otherIter.getNext(); + while (thisCurrent && otherCurrent) { + if (thisCurrent.name !== otherCurrent.name || + !thisCurrent.node.equals(otherCurrent.node)) { + return false; + } + thisCurrent = thisIter.getNext(); + otherCurrent = otherIter.getNext(); + } + return thisCurrent === null && otherCurrent === null; + } + else { + return false; + } + } + } + /** + * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used + * instead. + * + */ + resolveIndex_(indexDefinition) { + if (indexDefinition === KEY_INDEX) { + return null; + } + else { + return this.indexMap_.get(indexDefinition.toString()); + } + } +} +ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/; +class MaxNode extends ChildrenNode { + constructor() { + super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default); + } + compareTo(other) { + if (other === this) { + return 0; + } + else { + return 1; + } + } + equals(other) { + // Not that we every compare it, but MAX_NODE is only ever equal to itself + return other === this; + } + getPriority() { + return this; + } + getImmediateChild(childName) { + return ChildrenNode.EMPTY_NODE; + } + isEmpty() { + return false; + } +} +/** + * Marker that will sort higher than any other snapshot. + */ +const MAX_NODE = new MaxNode(); +Object.defineProperties(NamedNode, { + MIN: { + value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE) + }, + MAX: { + value: new NamedNode(MAX_NAME, MAX_NODE) + } +}); +/** + * Reference Extensions + */ +KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE; +LeafNode.__childrenNodeConstructor = ChildrenNode; +setMaxNode$1(MAX_NODE); +setMaxNode(MAX_NODE); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const USE_HINZE = true; +/** + * Constructs a snapshot node representing the passed JSON and returns it. + * @param json - JSON to create a node for. + * @param priority - Optional priority to use. This will be ignored if the + * passed JSON contains a .priority property. + */ +function nodeFromJSON(json, priority = null) { + if (json === null) { + return ChildrenNode.EMPTY_NODE; + } + if (typeof json === 'object' && '.priority' in json) { + priority = json['.priority']; + } + assert(priority === null || + typeof priority === 'string' || + typeof priority === 'number' || + (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority); + if (typeof json === 'object' && '.value' in json && json['.value'] !== null) { + json = json['.value']; + } + // Valid leaf nodes include non-objects or server-value wrapper objects + if (typeof json !== 'object' || '.sv' in json) { + const jsonLeaf = json; + return new LeafNode(jsonLeaf, nodeFromJSON(priority)); + } + if (!(json instanceof Array) && USE_HINZE) { + const children = []; + let childrenHavePriority = false; + const hinzeJsonObj = json; + each(hinzeJsonObj, (key, child) => { + if (key.substring(0, 1) !== '.') { + // Ignore metadata nodes + const childNode = nodeFromJSON(child); + if (!childNode.isEmpty()) { + childrenHavePriority = + childrenHavePriority || !childNode.getPriority().isEmpty(); + children.push(new NamedNode(key, childNode)); + } + } + }); + if (children.length === 0) { + return ChildrenNode.EMPTY_NODE; + } + const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR); + if (childrenHavePriority) { + const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare()); + return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX })); + } + else { + return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default); + } + } + else { + let node = ChildrenNode.EMPTY_NODE; + each(json, (key, childData) => { + if (contains(json, key)) { + if (key.substring(0, 1) !== '.') { + // ignore metadata nodes. + const childNode = nodeFromJSON(childData); + if (childNode.isLeafNode() || !childNode.isEmpty()) { + node = node.updateImmediateChild(key, childNode); + } + } + } + }); + return node.updatePriority(nodeFromJSON(priority)); + } +} +setNodeFromJSON(nodeFromJSON); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class PathIndex extends Index { + constructor(indexPath_) { + super(); + this.indexPath_ = indexPath_; + assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key"); + } + extractChild(snap) { + return snap.getChild(this.indexPath_); + } + isDefinedOn(node) { + return !node.getChild(this.indexPath_).isEmpty(); + } + compare(a, b) { + const aChild = this.extractChild(a.node); + const bChild = this.extractChild(b.node); + const indexCmp = aChild.compareTo(bChild); + if (indexCmp === 0) { + return nameCompare(a.name, b.name); + } + else { + return indexCmp; + } + } + makePost(indexValue, name) { + const valueNode = nodeFromJSON(indexValue); + const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode); + return new NamedNode(name, node); + } + maxPost() { + const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE); + return new NamedNode(MAX_NAME, node); + } + toString() { + return pathSlice(this.indexPath_, 0).join('/'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ValueIndex extends Index { + compare(a, b) { + const indexCmp = a.node.compareTo(b.node); + if (indexCmp === 0) { + return nameCompare(a.name, b.name); + } + else { + return indexCmp; + } + } + isDefinedOn(node) { + return true; + } + indexedValueChanged(oldNode, newNode) { + return !oldNode.equals(newNode); + } + minPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MIN; + } + maxPost() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return NamedNode.MAX; + } + makePost(indexValue, name) { + const valueNode = nodeFromJSON(indexValue); + return new NamedNode(name, valueNode); + } + /** + * @returns String representation for inclusion in a query spec + */ + toString() { + return '.value'; + } +} +const VALUE_INDEX = new ValueIndex(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function changeValue(snapshotNode) { + return { type: "value" /* ChangeType.VALUE */, snapshotNode }; +} +function changeChildAdded(childName, snapshotNode) { + return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode, childName }; +} +function changeChildRemoved(childName, snapshotNode) { + return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode, childName }; +} +function changeChildChanged(childName, snapshotNode, oldSnap) { + return { + type: "child_changed" /* ChangeType.CHILD_CHANGED */, + snapshotNode, + childName, + oldSnap + }; +} +function changeChildMoved(childName, snapshotNode) { + return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode, childName }; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Doesn't really filter nodes but applies an index to the node and keeps track of any changes + */ +class IndexedFilter { + constructor(index_) { + this.index_ = index_; + } + updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) { + assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated'); + const oldChild = snap.getImmediateChild(key); + // Check if anything actually changed. + if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) { + // There's an edge case where a child can enter or leave the view because affectedPath was set to null. + // In this case, affectedPath will appear null in both the old and new snapshots. So we need + // to avoid treating these cases as "nothing changed." + if (oldChild.isEmpty() === newChild.isEmpty()) { + // Nothing changed. + // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it. + //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.'); + return snap; + } + } + if (optChangeAccumulator != null) { + if (newChild.isEmpty()) { + if (snap.hasChild(key)) { + optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild)); + } + else { + assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node'); + } + } + else if (oldChild.isEmpty()) { + optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild)); + } + else { + optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild)); + } + } + if (snap.isLeafNode() && newChild.isEmpty()) { + return snap; + } + else { + // Make sure the node is indexed + return snap.updateImmediateChild(key, newChild).withIndex(this.index_); + } + } + updateFullNode(oldSnap, newSnap, optChangeAccumulator) { + if (optChangeAccumulator != null) { + if (!oldSnap.isLeafNode()) { + oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => { + if (!newSnap.hasChild(key)) { + optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode)); + } + }); + } + if (!newSnap.isLeafNode()) { + newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => { + if (oldSnap.hasChild(key)) { + const oldChild = oldSnap.getImmediateChild(key); + if (!oldChild.equals(childNode)) { + optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild)); + } + } + else { + optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode)); + } + }); + } + } + return newSnap.withIndex(this.index_); + } + updatePriority(oldSnap, newPriority) { + if (oldSnap.isEmpty()) { + return ChildrenNode.EMPTY_NODE; + } + else { + return oldSnap.updatePriority(newPriority); + } + } + filtersNodes() { + return false; + } + getIndexedFilter() { + return this; + } + getIndex() { + return this.index_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node + */ +class RangedFilter { + constructor(params) { + this.indexedFilter_ = new IndexedFilter(params.getIndex()); + this.index_ = params.getIndex(); + this.startPost_ = RangedFilter.getStartPost_(params); + this.endPost_ = RangedFilter.getEndPost_(params); + this.startIsInclusive_ = !params.startAfterSet_; + this.endIsInclusive_ = !params.endBeforeSet_; + } + getStartPost() { + return this.startPost_; + } + getEndPost() { + return this.endPost_; + } + matches(node) { + const isWithinStart = this.startIsInclusive_ + ? this.index_.compare(this.getStartPost(), node) <= 0 + : this.index_.compare(this.getStartPost(), node) < 0; + const isWithinEnd = this.endIsInclusive_ + ? this.index_.compare(node, this.getEndPost()) <= 0 + : this.index_.compare(node, this.getEndPost()) < 0; + return isWithinStart && isWithinEnd; + } + updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) { + if (!this.matches(new NamedNode(key, newChild))) { + newChild = ChildrenNode.EMPTY_NODE; + } + return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator); + } + updateFullNode(oldSnap, newSnap, optChangeAccumulator) { + if (newSnap.isLeafNode()) { + // Make sure we have a children node with the correct index, not a leaf node; + newSnap = ChildrenNode.EMPTY_NODE; + } + let filtered = newSnap.withIndex(this.index_); + // Don't support priorities on queries + filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE); + const self = this; + newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => { + if (!self.matches(new NamedNode(key, childNode))) { + filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE); + } + }); + return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator); + } + updatePriority(oldSnap, newPriority) { + // Don't support priorities on queries + return oldSnap; + } + filtersNodes() { + return true; + } + getIndexedFilter() { + return this.indexedFilter_; + } + getIndex() { + return this.index_; + } + static getStartPost_(params) { + if (params.hasStart()) { + const startName = params.getIndexStartName(); + return params.getIndex().makePost(params.getIndexStartValue(), startName); + } + else { + return params.getIndex().minPost(); + } + } + static getEndPost_(params) { + if (params.hasEnd()) { + const endName = params.getIndexEndName(); + return params.getIndex().makePost(params.getIndexEndValue(), endName); + } + else { + return params.getIndex().maxPost(); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible + */ +class LimitedFilter { + constructor(params) { + this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node); + this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node); + this.withinStartPost = (node) => { + const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node); + return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0; + }; + this.withinEndPost = (node) => { + const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost()); + return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0; + }; + this.rangedFilter_ = new RangedFilter(params); + this.index_ = params.getIndex(); + this.limit_ = params.getLimit(); + this.reverse_ = !params.isViewFromLeft(); + this.startIsInclusive_ = !params.startAfterSet_; + this.endIsInclusive_ = !params.endBeforeSet_; + } + updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) { + if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) { + newChild = ChildrenNode.EMPTY_NODE; + } + if (snap.getImmediateChild(key).equals(newChild)) { + // No change + return snap; + } + else if (snap.numChildren() < this.limit_) { + return this.rangedFilter_ + .getIndexedFilter() + .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator); + } + else { + return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator); + } + } + updateFullNode(oldSnap, newSnap, optChangeAccumulator) { + let filtered; + if (newSnap.isLeafNode() || newSnap.isEmpty()) { + // Make sure we have a children node with the correct index, not a leaf node; + filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_); + } + else { + if (this.limit_ * 2 < newSnap.numChildren() && + newSnap.isIndexed(this.index_)) { + // Easier to build up a snapshot, since what we're given has more than twice the elements we want + filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_); + // anchor to the startPost, endPost, or last element as appropriate + let iterator; + if (this.reverse_) { + iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_); + } + else { + iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_); + } + let count = 0; + while (iterator.hasNext() && count < this.limit_) { + const next = iterator.getNext(); + if (!this.withinDirectionalStart(next)) { + // if we have not reached the start, skip to the next element + continue; + } + else if (!this.withinDirectionalEnd(next)) { + // if we have reached the end, stop adding elements + break; + } + else { + filtered = filtered.updateImmediateChild(next.name, next.node); + count++; + } + } + } + else { + // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one + filtered = newSnap.withIndex(this.index_); + // Don't support priorities on queries + filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE); + let iterator; + if (this.reverse_) { + iterator = filtered.getReverseIterator(this.index_); + } + else { + iterator = filtered.getIterator(this.index_); + } + let count = 0; + while (iterator.hasNext()) { + const next = iterator.getNext(); + const inRange = count < this.limit_ && + this.withinDirectionalStart(next) && + this.withinDirectionalEnd(next); + if (inRange) { + count++; + } + else { + filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE); + } + } + } + } + return this.rangedFilter_ + .getIndexedFilter() + .updateFullNode(oldSnap, filtered, optChangeAccumulator); + } + updatePriority(oldSnap, newPriority) { + // Don't support priorities on queries + return oldSnap; + } + filtersNodes() { + return true; + } + getIndexedFilter() { + return this.rangedFilter_.getIndexedFilter(); + } + getIndex() { + return this.index_; + } + fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) { + // TODO: rename all cache stuff etc to general snap terminology + let cmp; + if (this.reverse_) { + const indexCmp = this.index_.getCompare(); + cmp = (a, b) => indexCmp(b, a); + } + else { + cmp = this.index_.getCompare(); + } + const oldEventCache = snap; + assert(oldEventCache.numChildren() === this.limit_, ''); + const newChildNamedNode = new NamedNode(childKey, childSnap); + const windowBoundary = this.reverse_ + ? oldEventCache.getFirstChild(this.index_) + : oldEventCache.getLastChild(this.index_); + const inRange = this.rangedFilter_.matches(newChildNamedNode); + if (oldEventCache.hasChild(childKey)) { + const oldChildSnap = oldEventCache.getImmediateChild(childKey); + let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_); + while (nextChild != null && + (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) { + // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't + // been applied to the limited filter yet. Ignore this next child which will be updated later in + // the limited filter... + nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_); + } + const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode); + const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0; + if (remainsInWindow) { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap)); + } + return oldEventCache.updateImmediateChild(childKey, childSnap); + } + else { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap)); + } + const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE); + const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild); + if (nextChildInRange) { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node)); + } + return newEventCache.updateImmediateChild(nextChild.name, nextChild.node); + } + else { + return newEventCache; + } + } + } + else if (childSnap.isEmpty()) { + // we're deleting a node, but it was not in the window, so ignore it + return snap; + } + else if (inRange) { + if (cmp(windowBoundary, newChildNamedNode) >= 0) { + if (changeAccumulator != null) { + changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node)); + changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap)); + } + return oldEventCache + .updateImmediateChild(childKey, childSnap) + .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE); + } + else { + return snap; + } + } + else { + return snap; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a + * range to be returned for a particular location. It is assumed that validation of parameters is done at the + * user-facing API level, so it is not done here. + * + * @internal + */ +class QueryParams { + constructor() { + this.limitSet_ = false; + this.startSet_ = false; + this.startNameSet_ = false; + this.startAfterSet_ = false; // can only be true if startSet_ is true + this.endSet_ = false; + this.endNameSet_ = false; + this.endBeforeSet_ = false; // can only be true if endSet_ is true + this.limit_ = 0; + this.viewFrom_ = ''; + this.indexStartValue_ = null; + this.indexStartName_ = ''; + this.indexEndValue_ = null; + this.indexEndName_ = ''; + this.index_ = PRIORITY_INDEX; + } + hasStart() { + return this.startSet_; + } + /** + * @returns True if it would return from left. + */ + isViewFromLeft() { + if (this.viewFrom_ === '') { + // limit(), rather than limitToFirst or limitToLast was called. + // This means that only one of startSet_ and endSet_ is true. Use them + // to calculate which side of the view to anchor to. If neither is set, + // anchor to the end. + return this.startSet_; + } + else { + return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */; + } + } + /** + * Only valid to call if hasStart() returns true + */ + getIndexStartValue() { + assert(this.startSet_, 'Only valid if start has been set'); + return this.indexStartValue_; + } + /** + * Only valid to call if hasStart() returns true. + * Returns the starting key name for the range defined by these query parameters + */ + getIndexStartName() { + assert(this.startSet_, 'Only valid if start has been set'); + if (this.startNameSet_) { + return this.indexStartName_; + } + else { + return MIN_NAME; + } + } + hasEnd() { + return this.endSet_; + } + /** + * Only valid to call if hasEnd() returns true. + */ + getIndexEndValue() { + assert(this.endSet_, 'Only valid if end has been set'); + return this.indexEndValue_; + } + /** + * Only valid to call if hasEnd() returns true. + * Returns the end key name for the range defined by these query parameters + */ + getIndexEndName() { + assert(this.endSet_, 'Only valid if end has been set'); + if (this.endNameSet_) { + return this.indexEndName_; + } + else { + return MAX_NAME; + } + } + hasLimit() { + return this.limitSet_; + } + /** + * @returns True if a limit has been set and it has been explicitly anchored + */ + hasAnchoredLimit() { + return this.limitSet_ && this.viewFrom_ !== ''; + } + /** + * Only valid to call if hasLimit() returns true + */ + getLimit() { + assert(this.limitSet_, 'Only valid if limit has been set'); + return this.limit_; + } + getIndex() { + return this.index_; + } + loadsAllData() { + return !(this.startSet_ || this.endSet_ || this.limitSet_); + } + isDefault() { + return this.loadsAllData() && this.index_ === PRIORITY_INDEX; + } + copy() { + const copy = new QueryParams(); + copy.limitSet_ = this.limitSet_; + copy.limit_ = this.limit_; + copy.startSet_ = this.startSet_; + copy.startAfterSet_ = this.startAfterSet_; + copy.indexStartValue_ = this.indexStartValue_; + copy.startNameSet_ = this.startNameSet_; + copy.indexStartName_ = this.indexStartName_; + copy.endSet_ = this.endSet_; + copy.endBeforeSet_ = this.endBeforeSet_; + copy.indexEndValue_ = this.indexEndValue_; + copy.endNameSet_ = this.endNameSet_; + copy.indexEndName_ = this.indexEndName_; + copy.index_ = this.index_; + copy.viewFrom_ = this.viewFrom_; + return copy; + } +} +function queryParamsGetNodeFilter(queryParams) { + if (queryParams.loadsAllData()) { + return new IndexedFilter(queryParams.getIndex()); + } + else if (queryParams.hasLimit()) { + return new LimitedFilter(queryParams); + } + else { + return new RangedFilter(queryParams); + } +} +function queryParamsLimitToFirst(queryParams, newLimit) { + const newParams = queryParams.copy(); + newParams.limitSet_ = true; + newParams.limit_ = newLimit; + newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */; + return newParams; +} +function queryParamsLimitToLast(queryParams, newLimit) { + const newParams = queryParams.copy(); + newParams.limitSet_ = true; + newParams.limit_ = newLimit; + newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */; + return newParams; +} +function queryParamsStartAt(queryParams, indexValue, key) { + const newParams = queryParams.copy(); + newParams.startSet_ = true; + if (indexValue === undefined) { + indexValue = null; + } + newParams.indexStartValue_ = indexValue; + if (key != null) { + newParams.startNameSet_ = true; + newParams.indexStartName_ = key; + } + else { + newParams.startNameSet_ = false; + newParams.indexStartName_ = ''; + } + return newParams; +} +function queryParamsStartAfter(queryParams, indexValue, key) { + let params; + if (queryParams.index_ === KEY_INDEX || !!key) { + params = queryParamsStartAt(queryParams, indexValue, key); + } + else { + params = queryParamsStartAt(queryParams, indexValue, MAX_NAME); + } + params.startAfterSet_ = true; + return params; +} +function queryParamsEndAt(queryParams, indexValue, key) { + const newParams = queryParams.copy(); + newParams.endSet_ = true; + if (indexValue === undefined) { + indexValue = null; + } + newParams.indexEndValue_ = indexValue; + if (key !== undefined) { + newParams.endNameSet_ = true; + newParams.indexEndName_ = key; + } + else { + newParams.endNameSet_ = false; + newParams.indexEndName_ = ''; + } + return newParams; +} +function queryParamsEndBefore(queryParams, indexValue, key) { + let params; + if (queryParams.index_ === KEY_INDEX || !!key) { + params = queryParamsEndAt(queryParams, indexValue, key); + } + else { + params = queryParamsEndAt(queryParams, indexValue, MIN_NAME); + } + params.endBeforeSet_ = true; + return params; +} +function queryParamsOrderBy(queryParams, index) { + const newParams = queryParams.copy(); + newParams.index_ = index; + return newParams; +} +/** + * Returns a set of REST query string parameters representing this query. + * + * @returns query string parameters + */ +function queryParamsToRestQueryStringParameters(queryParams) { + const qs = {}; + if (queryParams.isDefault()) { + return qs; + } + let orderBy; + if (queryParams.index_ === PRIORITY_INDEX) { + orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */; + } + else if (queryParams.index_ === VALUE_INDEX) { + orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */; + } + else if (queryParams.index_ === KEY_INDEX) { + orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */; + } + else { + assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!'); + orderBy = queryParams.index_.toString(); + } + qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = stringify(orderBy); + if (queryParams.startSet_) { + const startParam = queryParams.startAfterSet_ + ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */ + : "startAt" /* REST_QUERY_CONSTANTS.START_AT */; + qs[startParam] = stringify(queryParams.indexStartValue_); + if (queryParams.startNameSet_) { + qs[startParam] += ',' + stringify(queryParams.indexStartName_); + } + } + if (queryParams.endSet_) { + const endParam = queryParams.endBeforeSet_ + ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */ + : "endAt" /* REST_QUERY_CONSTANTS.END_AT */; + qs[endParam] = stringify(queryParams.indexEndValue_); + if (queryParams.endNameSet_) { + qs[endParam] += ',' + stringify(queryParams.indexEndName_); + } + } + if (queryParams.limitSet_) { + if (queryParams.isViewFromLeft()) { + qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_; + } + else { + qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_; + } + } + return qs; +} +function queryParamsGetQueryObject(queryParams) { + const obj = {}; + if (queryParams.startSet_) { + obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] = + queryParams.indexStartValue_; + if (queryParams.startNameSet_) { + obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] = + queryParams.indexStartName_; + } + obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] = + !queryParams.startAfterSet_; + } + if (queryParams.endSet_) { + obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_; + if (queryParams.endNameSet_) { + obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_; + } + obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] = + !queryParams.endBeforeSet_; + } + if (queryParams.limitSet_) { + obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_; + let viewFrom = queryParams.viewFrom_; + if (viewFrom === '') { + if (queryParams.isViewFromLeft()) { + viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */; + } + else { + viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */; + } + } + obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom; + } + // For now, priority index is the default, so we only specify if it's some other index + if (queryParams.index_ !== PRIORITY_INDEX) { + obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString(); + } + return obj; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An implementation of ServerActions that communicates with the server via REST requests. + * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full + * persistent connection (using WebSockets or long-polling) + */ +class ReadonlyRestClient extends ServerActions { + reportStats(stats) { + throw new Error('Method not implemented.'); + } + static getListenId_(query, tag) { + if (tag !== undefined) { + return 'tag$' + tag; + } + else { + assert(query._queryParams.isDefault(), "should have a tag if it's not a default query."); + return query._path.toString(); + } + } + /** + * @param repoInfo_ - Data about the namespace we are connecting to + * @param onDataUpdate_ - A callback for new data from the server + */ + constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) { + super(); + this.repoInfo_ = repoInfo_; + this.onDataUpdate_ = onDataUpdate_; + this.authTokenProvider_ = authTokenProvider_; + this.appCheckTokenProvider_ = appCheckTokenProvider_; + /** @private {function(...[*])} */ + this.log_ = logWrapper('p:rest:'); + /** + * We don't actually need to track listens, except to prevent us calling an onComplete for a listen + * that's been removed. :-/ + */ + this.listens_ = {}; + } + /** @inheritDoc */ + listen(query, currentHashFn, tag, onComplete) { + const pathString = query._path.toString(); + this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier); + // Mark this listener so we can tell if it's removed. + const listenId = ReadonlyRestClient.getListenId_(query, tag); + const thisListen = {}; + this.listens_[listenId] = thisListen; + const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams); + this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => { + let data = result; + if (error === 404) { + data = null; + error = null; + } + if (error === null) { + this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag); + } + if (safeGet(this.listens_, listenId) === thisListen) { + let status; + if (!error) { + status = 'ok'; + } + else if (error === 401) { + status = 'permission_denied'; + } + else { + status = 'rest_error:' + error; + } + onComplete(status, null); + } + }); + } + /** @inheritDoc */ + unlisten(query, tag) { + const listenId = ReadonlyRestClient.getListenId_(query, tag); + delete this.listens_[listenId]; + } + get(query) { + const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams); + const pathString = query._path.toString(); + const deferred = new Deferred(); + this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => { + let data = result; + if (error === 404) { + data = null; + error = null; + } + if (error === null) { + this.onDataUpdate_(pathString, data, + /*isMerge=*/ false, + /*tag=*/ null); + deferred.resolve(data); + } + else { + deferred.reject(new Error(data)); + } + }); + return deferred.promise; + } + /** @inheritDoc */ + refreshAuthToken(token) { + // no-op since we just always call getToken. + } + /** + * Performs a REST request to the given path, with the provided query string parameters, + * and any auth credentials we have. + */ + restRequest_(pathString, queryStringParameters = {}, callback) { + queryStringParameters['format'] = 'export'; + return Promise.all([ + this.authTokenProvider_.getToken(/*forceRefresh=*/ false), + this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false) + ]).then(([authToken, appCheckToken]) => { + if (authToken && authToken.accessToken) { + queryStringParameters['auth'] = authToken.accessToken; + } + if (appCheckToken && appCheckToken.token) { + queryStringParameters['ac'] = appCheckToken.token; + } + const url = (this.repoInfo_.secure ? 'https://' : 'http://') + + this.repoInfo_.host + + pathString + + '?' + + 'ns=' + + this.repoInfo_.namespace + + querystring(queryStringParameters); + this.log_('Sending REST request for ' + url); + const xhr = new XMLHttpRequest(); + xhr.onreadystatechange = () => { + if (callback && xhr.readyState === 4) { + this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText); + let res = null; + if (xhr.status >= 200 && xhr.status < 300) { + try { + res = jsonEval(xhr.responseText); + } + catch (e) { + warn('Failed to parse JSON response for ' + + url + + ': ' + + xhr.responseText); + } + callback(null, res); + } + else { + // 401 and 404 are expected. + if (xhr.status !== 401 && xhr.status !== 404) { + warn('Got unsuccessful REST response for ' + + url + + ' Status: ' + + xhr.status); + } + callback(xhr.status); + } + callback = null; + } + }; + xhr.open('GET', url, /*asynchronous=*/ true); + xhr.send(); + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Mutable object which basically just stores a reference to the "latest" immutable snapshot. + */ +class SnapshotHolder { + constructor() { + this.rootNode_ = ChildrenNode.EMPTY_NODE; + } + getNode(path) { + return this.rootNode_.getChild(path); + } + updateSnapshot(path, newSnapshotNode) { + this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newSparseSnapshotTree() { + return { + value: null, + children: new Map() + }; +} +/** + * Stores the given node at the specified path. If there is already a node + * at a shallower path, it merges the new data into that snapshot node. + * + * @param path - Path to look up snapshot for. + * @param data - The new data, or null. + */ +function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) { + if (pathIsEmpty(path)) { + sparseSnapshotTree.value = data; + sparseSnapshotTree.children.clear(); + } + else if (sparseSnapshotTree.value !== null) { + sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data); + } + else { + const childKey = pathGetFront(path); + if (!sparseSnapshotTree.children.has(childKey)) { + sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree()); + } + const child = sparseSnapshotTree.children.get(childKey); + path = pathPopFront(path); + sparseSnapshotTreeRemember(child, path, data); + } +} +/** + * Purge the data at path from the cache. + * + * @param path - Path to look up snapshot for. + * @returns True if this node should now be removed. + */ +function sparseSnapshotTreeForget(sparseSnapshotTree, path) { + if (pathIsEmpty(path)) { + sparseSnapshotTree.value = null; + sparseSnapshotTree.children.clear(); + return true; + } + else { + if (sparseSnapshotTree.value !== null) { + if (sparseSnapshotTree.value.isLeafNode()) { + // We're trying to forget a node that doesn't exist + return false; + } + else { + const value = sparseSnapshotTree.value; + sparseSnapshotTree.value = null; + value.forEachChild(PRIORITY_INDEX, (key, tree) => { + sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree); + }); + return sparseSnapshotTreeForget(sparseSnapshotTree, path); + } + } + else if (sparseSnapshotTree.children.size > 0) { + const childKey = pathGetFront(path); + path = pathPopFront(path); + if (sparseSnapshotTree.children.has(childKey)) { + const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path); + if (safeToRemove) { + sparseSnapshotTree.children.delete(childKey); + } + } + return sparseSnapshotTree.children.size === 0; + } + else { + return true; + } + } +} +/** + * Recursively iterates through all of the stored tree and calls the + * callback on each one. + * + * @param prefixPath - Path to look up node for. + * @param func - The function to invoke for each tree. + */ +function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) { + if (sparseSnapshotTree.value !== null) { + func(prefixPath, sparseSnapshotTree.value); + } + else { + sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => { + const path = new Path(prefixPath.toString() + '/' + key); + sparseSnapshotTreeForEachTree(tree, path, func); + }); + } +} +/** + * Iterates through each immediate child and triggers the callback. + * Only seems to be used in tests. + * + * @param func - The function to invoke for each child. + */ +function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) { + sparseSnapshotTree.children.forEach((tree, key) => { + func(key, tree); + }); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns the delta from the previous call to get stats. + * + * @param collection_ - The collection to "listen" to. + */ +class StatsListener { + constructor(collection_) { + this.collection_ = collection_; + this.last_ = null; + } + get() { + const newStats = this.collection_.get(); + const delta = { ...newStats }; + if (this.last_) { + each(this.last_, (stat, value) => { + delta[stat] = delta[stat] - value; + }); + } + this.last_ = newStats; + return delta; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably +// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10 +// seconds to try to ensure the Firebase connection is established / settled. +const FIRST_STATS_MIN_TIME = 10 * 1000; +const FIRST_STATS_MAX_TIME = 30 * 1000; +// We'll continue to report stats on average every 5 minutes. +const REPORT_STATS_INTERVAL = 5 * 60 * 1000; +class StatsReporter { + constructor(collection, server_) { + this.server_ = server_; + this.statsToReport_ = {}; + this.statsListener_ = new StatsListener(collection); + const timeout = FIRST_STATS_MIN_TIME + + (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random(); + setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout)); + } + reportStats_() { + const stats = this.statsListener_.get(); + const reportedStats = {}; + let haveStatsToReport = false; + each(stats, (stat, value) => { + if (value > 0 && contains(this.statsToReport_, stat)) { + reportedStats[stat] = value; + haveStatsToReport = true; + } + }); + if (haveStatsToReport) { + this.server_.reportStats(reportedStats); + } + // queue our next run. + setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @enum + */ +var OperationType; +(function (OperationType) { + OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE"; + OperationType[OperationType["MERGE"] = 1] = "MERGE"; + OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE"; + OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE"; +})(OperationType || (OperationType = {})); +function newOperationSourceUser() { + return { + fromUser: true, + fromServer: false, + queryId: null, + tagged: false + }; +} +function newOperationSourceServer() { + return { + fromUser: false, + fromServer: true, + queryId: null, + tagged: false + }; +} +function newOperationSourceServerTaggedQuery(queryId) { + return { + fromUser: false, + fromServer: true, + queryId, + tagged: true + }; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class AckUserWrite { + /** + * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap. + */ + constructor( + /** @inheritDoc */ path, + /** @inheritDoc */ affectedTree, + /** @inheritDoc */ revert) { + this.path = path; + this.affectedTree = affectedTree; + this.revert = revert; + /** @inheritDoc */ + this.type = OperationType.ACK_USER_WRITE; + /** @inheritDoc */ + this.source = newOperationSourceUser(); + } + operationForChild(childName) { + if (!pathIsEmpty(this.path)) { + assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.'); + return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert); + } + else if (this.affectedTree.value != null) { + assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.'); + // All child locations are affected as well; just return same operation. + return this; + } + else { + const childTree = this.affectedTree.subtree(new Path(childName)); + return new AckUserWrite(newEmptyPath(), childTree, this.revert); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ListenComplete { + constructor(source, path) { + this.source = source; + this.path = path; + /** @inheritDoc */ + this.type = OperationType.LISTEN_COMPLETE; + } + operationForChild(childName) { + if (pathIsEmpty(this.path)) { + return new ListenComplete(this.source, newEmptyPath()); + } + else { + return new ListenComplete(this.source, pathPopFront(this.path)); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Overwrite { + constructor(source, path, snap) { + this.source = source; + this.path = path; + this.snap = snap; + /** @inheritDoc */ + this.type = OperationType.OVERWRITE; + } + operationForChild(childName) { + if (pathIsEmpty(this.path)) { + return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName)); + } + else { + return new Overwrite(this.source, pathPopFront(this.path), this.snap); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Merge { + constructor( + /** @inheritDoc */ source, + /** @inheritDoc */ path, + /** @inheritDoc */ children) { + this.source = source; + this.path = path; + this.children = children; + /** @inheritDoc */ + this.type = OperationType.MERGE; + } + operationForChild(childName) { + if (pathIsEmpty(this.path)) { + const childTree = this.children.subtree(new Path(childName)); + if (childTree.isEmpty()) { + // This child is unaffected + return null; + } + else if (childTree.value) { + // We have a snapshot for the child in question. This becomes an overwrite of the child. + return new Overwrite(this.source, newEmptyPath(), childTree.value); + } + else { + // This is a merge at a deeper level + return new Merge(this.source, newEmptyPath(), childTree); + } + } + else { + assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation"); + return new Merge(this.source, pathPopFront(this.path), this.children); + } + } + toString() { + return ('Operation(' + + this.path + + ': ' + + this.source.toString() + + ' merge: ' + + this.children.toString() + + ')'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully + * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g. + * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks + * whether a node potentially had children removed due to a filter. + */ +class CacheNode { + constructor(node_, fullyInitialized_, filtered_) { + this.node_ = node_; + this.fullyInitialized_ = fullyInitialized_; + this.filtered_ = filtered_; + } + /** + * Returns whether this node was fully initialized with either server data or a complete overwrite by the client + */ + isFullyInitialized() { + return this.fullyInitialized_; + } + /** + * Returns whether this node is potentially missing children due to a filter applied to the node + */ + isFiltered() { + return this.filtered_; + } + isCompleteForPath(path) { + if (pathIsEmpty(path)) { + return this.isFullyInitialized() && !this.filtered_; + } + const childKey = pathGetFront(path); + return this.isCompleteForChild(childKey); + } + isCompleteForChild(key) { + return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key)); + } + getNode() { + return this.node_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An EventGenerator is used to convert "raw" changes (Change) as computed by the + * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges() + * for details. + * + */ +class EventGenerator { + constructor(query_) { + this.query_ = query_; + this.index_ = this.query_._queryParams.getIndex(); + } +} +/** + * Given a set of raw changes (no moved events and prevName not specified yet), and a set of + * EventRegistrations that should be notified of these changes, generate the actual events to be raised. + * + * Notes: + * - child_moved events will be synthesized at this time for any child_changed events that affect + * our index. + * - prevName will be calculated based on the index ordering. + */ +function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) { + const events = []; + const moves = []; + changes.forEach(change => { + if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ && + eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) { + moves.push(changeChildMoved(change.childName, change.snapshotNode)); + } + }); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache); + eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache); + return events; +} +/** + * Given changes of a single change type, generate the corresponding events. + */ +function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) { + const filteredChanges = changes.filter(change => change.type === eventType); + filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b)); + filteredChanges.forEach(change => { + const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache); + registrations.forEach(registration => { + if (registration.respondsTo(change.type)) { + events.push(registration.createEvent(materializedChange, eventGenerator.query_)); + } + }); + }); +} +function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) { + if (change.type === 'value' || change.type === 'child_removed') { + return change; + } + else { + change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_); + return change; + } +} +function eventGeneratorCompareChanges(eventGenerator, a, b) { + if (a.childName == null || b.childName == null) { + throw assertionError('Should only compare child_ events.'); + } + const aWrapped = new NamedNode(a.childName, a.snapshotNode); + const bWrapped = new NamedNode(b.childName, b.snapshotNode); + return eventGenerator.index_.compare(aWrapped, bWrapped); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newViewCache(eventCache, serverCache) { + return { eventCache, serverCache }; +} +function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) { + return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache); +} +function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) { + return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered)); +} +function viewCacheGetCompleteEventSnap(viewCache) { + return viewCache.eventCache.isFullyInitialized() + ? viewCache.eventCache.getNode() + : null; +} +function viewCacheGetCompleteServerSnap(viewCache) { + return viewCache.serverCache.isFullyInitialized() + ? viewCache.serverCache.getNode() + : null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let emptyChildrenSingleton; +/** + * Singleton empty children collection. + * + */ +const EmptyChildren = () => { + if (!emptyChildrenSingleton) { + emptyChildrenSingleton = new SortedMap(stringCompare); + } + return emptyChildrenSingleton; +}; +/** + * A tree with immutable elements. + */ +class ImmutableTree { + static fromObject(obj) { + let tree = new ImmutableTree(null); + each(obj, (childPath, childSnap) => { + tree = tree.set(new Path(childPath), childSnap); + }); + return tree; + } + constructor(value, children = EmptyChildren()) { + this.value = value; + this.children = children; + } + /** + * True if the value is empty and there are no children + */ + isEmpty() { + return this.value === null && this.children.isEmpty(); + } + /** + * Given a path and predicate, return the first node and the path to that node + * where the predicate returns true. + * + * TODO Do a perf test -- If we're creating a bunch of `{path: value:}` + * objects on the way back out, it may be better to pass down a pathSoFar obj. + * + * @param relativePath - The remainder of the path + * @param predicate - The predicate to satisfy to return a node + */ + findRootMostMatchingPathAndValue(relativePath, predicate) { + if (this.value != null && predicate(this.value)) { + return { path: newEmptyPath(), value: this.value }; + } + else { + if (pathIsEmpty(relativePath)) { + return null; + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front); + if (child !== null) { + const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate); + if (childExistingPathAndValue != null) { + const fullPath = pathChild(new Path(front), childExistingPathAndValue.path); + return { path: fullPath, value: childExistingPathAndValue.value }; + } + else { + return null; + } + } + else { + return null; + } + } + } + } + /** + * Find, if it exists, the shortest subpath of the given path that points a defined + * value in the tree + */ + findRootMostValueAndPath(relativePath) { + return this.findRootMostMatchingPathAndValue(relativePath, () => true); + } + /** + * @returns The subtree at the given path + */ + subtree(relativePath) { + if (pathIsEmpty(relativePath)) { + return this; + } + else { + const front = pathGetFront(relativePath); + const childTree = this.children.get(front); + if (childTree !== null) { + return childTree.subtree(pathPopFront(relativePath)); + } + else { + return new ImmutableTree(null); + } + } + } + /** + * Sets a value at the specified path. + * + * @param relativePath - Path to set value at. + * @param toSet - Value to set. + * @returns Resulting tree. + */ + set(relativePath, toSet) { + if (pathIsEmpty(relativePath)) { + return new ImmutableTree(toSet, this.children); + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front) || new ImmutableTree(null); + const newChild = child.set(pathPopFront(relativePath), toSet); + const newChildren = this.children.insert(front, newChild); + return new ImmutableTree(this.value, newChildren); + } + } + /** + * Removes the value at the specified path. + * + * @param relativePath - Path to value to remove. + * @returns Resulting tree. + */ + remove(relativePath) { + if (pathIsEmpty(relativePath)) { + if (this.children.isEmpty()) { + return new ImmutableTree(null); + } + else { + return new ImmutableTree(null, this.children); + } + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front); + if (child) { + const newChild = child.remove(pathPopFront(relativePath)); + let newChildren; + if (newChild.isEmpty()) { + newChildren = this.children.remove(front); + } + else { + newChildren = this.children.insert(front, newChild); + } + if (this.value === null && newChildren.isEmpty()) { + return new ImmutableTree(null); + } + else { + return new ImmutableTree(this.value, newChildren); + } + } + else { + return this; + } + } + } + /** + * Gets a value from the tree. + * + * @param relativePath - Path to get value for. + * @returns Value at path, or null. + */ + get(relativePath) { + if (pathIsEmpty(relativePath)) { + return this.value; + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front); + if (child) { + return child.get(pathPopFront(relativePath)); + } + else { + return null; + } + } + } + /** + * Replace the subtree at the specified path with the given new tree. + * + * @param relativePath - Path to replace subtree for. + * @param newTree - New tree. + * @returns Resulting tree. + */ + setTree(relativePath, newTree) { + if (pathIsEmpty(relativePath)) { + return newTree; + } + else { + const front = pathGetFront(relativePath); + const child = this.children.get(front) || new ImmutableTree(null); + const newChild = child.setTree(pathPopFront(relativePath), newTree); + let newChildren; + if (newChild.isEmpty()) { + newChildren = this.children.remove(front); + } + else { + newChildren = this.children.insert(front, newChild); + } + return new ImmutableTree(this.value, newChildren); + } + } + /** + * Performs a depth first fold on this tree. Transforms a tree into a single + * value, given a function that operates on the path to a node, an optional + * current value, and a map of child names to folded subtrees + */ + fold(fn) { + return this.fold_(newEmptyPath(), fn); + } + /** + * Recursive helper for public-facing fold() method + */ + fold_(pathSoFar, fn) { + const accum = {}; + this.children.inorderTraversal((childKey, childTree) => { + accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn); + }); + return fn(pathSoFar, this.value, accum); + } + /** + * Find the first matching value on the given path. Return the result of applying f to it. + */ + findOnPath(path, f) { + return this.findOnPath_(path, newEmptyPath(), f); + } + findOnPath_(pathToFollow, pathSoFar, f) { + const result = this.value ? f(pathSoFar, this.value) : false; + if (result) { + return result; + } + else { + if (pathIsEmpty(pathToFollow)) { + return null; + } + else { + const front = pathGetFront(pathToFollow); + const nextChild = this.children.get(front); + if (nextChild) { + return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f); + } + else { + return null; + } + } + } + } + foreachOnPath(path, f) { + return this.foreachOnPath_(path, newEmptyPath(), f); + } + foreachOnPath_(pathToFollow, currentRelativePath, f) { + if (pathIsEmpty(pathToFollow)) { + return this; + } + else { + if (this.value) { + f(currentRelativePath, this.value); + } + const front = pathGetFront(pathToFollow); + const nextChild = this.children.get(front); + if (nextChild) { + return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f); + } + else { + return new ImmutableTree(null); + } + } + } + /** + * Calls the given function for each node in the tree that has a value. + * + * @param f - A function to be called with the path from the root of the tree to + * a node, and the value at that node. Called in depth-first order. + */ + foreach(f) { + this.foreach_(newEmptyPath(), f); + } + foreach_(currentRelativePath, f) { + this.children.inorderTraversal((childName, childTree) => { + childTree.foreach_(pathChild(currentRelativePath, childName), f); + }); + if (this.value) { + f(currentRelativePath, this.value); + } + } + foreachChild(f) { + this.children.inorderTraversal((childName, childTree) => { + if (childTree.value) { + f(childName, childTree.value); + } + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with + * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write + * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write + * to reflect the write added. + */ +class CompoundWrite { + constructor(writeTree_) { + this.writeTree_ = writeTree_; + } + static empty() { + return new CompoundWrite(new ImmutableTree(null)); + } +} +function compoundWriteAddWrite(compoundWrite, path, node) { + if (pathIsEmpty(path)) { + return new CompoundWrite(new ImmutableTree(node)); + } + else { + const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path); + if (rootmost != null) { + const rootMostPath = rootmost.path; + let value = rootmost.value; + const relativePath = newRelativePath(rootMostPath, path); + value = value.updateChild(relativePath, node); + return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value)); + } + else { + const subtree = new ImmutableTree(node); + const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree); + return new CompoundWrite(newWriteTree); + } + } +} +function compoundWriteAddWrites(compoundWrite, path, updates) { + let newWrite = compoundWrite; + each(updates, (childKey, node) => { + newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node); + }); + return newWrite; +} +/** + * Will remove a write at the given path and deeper paths. This will not modify a write at a higher + * location, which must be removed by calling this method with that path. + * + * @param compoundWrite - The CompoundWrite to remove. + * @param path - The path at which a write and all deeper writes should be removed + * @returns The new CompoundWrite with the removed path + */ +function compoundWriteRemoveWrite(compoundWrite, path) { + if (pathIsEmpty(path)) { + return CompoundWrite.empty(); + } + else { + const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null)); + return new CompoundWrite(newWriteTree); + } +} +/** + * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be + * considered "complete". + * + * @param compoundWrite - The CompoundWrite to check. + * @param path - The path to check for + * @returns Whether there is a complete write at that path + */ +function compoundWriteHasCompleteWrite(compoundWrite, path) { + return compoundWriteGetCompleteNode(compoundWrite, path) != null; +} +/** + * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate + * writes from deeper paths, but will return child nodes from a more shallow path. + * + * @param compoundWrite - The CompoundWrite to get the node from. + * @param path - The path to get a complete write + * @returns The node if complete at that path, or null otherwise. + */ +function compoundWriteGetCompleteNode(compoundWrite, path) { + const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path); + if (rootmost != null) { + return compoundWrite.writeTree_ + .get(rootmost.path) + .getChild(newRelativePath(rootmost.path, path)); + } + else { + return null; + } +} +/** + * Returns all children that are guaranteed to be a complete overwrite. + * + * @param compoundWrite - The CompoundWrite to get children from. + * @returns A list of all complete children. + */ +function compoundWriteGetCompleteChildren(compoundWrite) { + const children = []; + const node = compoundWrite.writeTree_.value; + if (node != null) { + // If it's a leaf node, it has no children; so nothing to do. + if (!node.isLeafNode()) { + node.forEachChild(PRIORITY_INDEX, (childName, childNode) => { + children.push(new NamedNode(childName, childNode)); + }); + } + } + else { + compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => { + if (childTree.value != null) { + children.push(new NamedNode(childName, childTree.value)); + } + }); + } + return children; +} +function compoundWriteChildCompoundWrite(compoundWrite, path) { + if (pathIsEmpty(path)) { + return compoundWrite; + } + else { + const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path); + if (shadowingNode != null) { + return new CompoundWrite(new ImmutableTree(shadowingNode)); + } + else { + return new CompoundWrite(compoundWrite.writeTree_.subtree(path)); + } + } +} +/** + * Returns true if this CompoundWrite is empty and therefore does not modify any nodes. + * @returns Whether this CompoundWrite is empty + */ +function compoundWriteIsEmpty(compoundWrite) { + return compoundWrite.writeTree_.isEmpty(); +} +/** + * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the + * node + * @param node - The node to apply this CompoundWrite to + * @returns The node with all writes applied + */ +function compoundWriteApply(compoundWrite, node) { + return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node); +} +function applySubtreeWrite(relativePath, writeTree, node) { + if (writeTree.value != null) { + // Since there a write is always a leaf, we're done here + return node.updateChild(relativePath, writeTree.value); + } + else { + let priorityWrite = null; + writeTree.children.inorderTraversal((childKey, childTree) => { + if (childKey === '.priority') { + // Apply priorities at the end so we don't update priorities for either empty nodes or forget + // to apply priorities to empty nodes that are later filled + assert(childTree.value !== null, 'Priority writes must always be leaf nodes'); + priorityWrite = childTree.value; + } + else { + node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node); + } + }); + // If there was a priority write, we only apply it if the node is not empty + if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) { + node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite); + } + return node; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path. + * + */ +function writeTreeChildWrites(writeTree, path) { + return newWriteTreeRef(path, writeTree); +} +/** + * Record a new overwrite from user code. + * + * @param visible - This is set to false by some transactions. It should be excluded from event caches + */ +function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) { + assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones'); + if (visible === undefined) { + visible = true; + } + writeTree.allWrites.push({ + path, + snap, + writeId, + visible + }); + if (visible) { + writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap); + } + writeTree.lastWriteId = writeId; +} +/** + * Record a new merge from user code. + */ +function writeTreeAddMerge(writeTree, path, changedChildren, writeId) { + assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones'); + writeTree.allWrites.push({ + path, + children: changedChildren, + writeId, + visible: true + }); + writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren); + writeTree.lastWriteId = writeId; +} +function writeTreeGetWrite(writeTree, writeId) { + for (let i = 0; i < writeTree.allWrites.length; i++) { + const record = writeTree.allWrites[i]; + if (record.writeId === writeId) { + return record; + } + } + return null; +} +/** + * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates + * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate. + * + * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise + * events as a result). + */ +function writeTreeRemoveWrite(writeTree, writeId) { + // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied + // out of order. + //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId; + //assert(validClear, "Either we don't have this write, or it's the first one in the queue"); + const idx = writeTree.allWrites.findIndex(s => { + return s.writeId === writeId; + }); + assert(idx >= 0, 'removeWrite called with nonexistent writeId.'); + const writeToRemove = writeTree.allWrites[idx]; + writeTree.allWrites.splice(idx, 1); + let removedWriteWasVisible = writeToRemove.visible; + let removedWriteOverlapsWithOtherWrites = false; + let i = writeTree.allWrites.length - 1; + while (removedWriteWasVisible && i >= 0) { + const currentWrite = writeTree.allWrites[i]; + if (currentWrite.visible) { + if (i >= idx && + writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) { + // The removed write was completely shadowed by a subsequent write. + removedWriteWasVisible = false; + } + else if (pathContains(writeToRemove.path, currentWrite.path)) { + // Either we're covering some writes or they're covering part of us (depending on which came first). + removedWriteOverlapsWithOtherWrites = true; + } + } + i--; + } + if (!removedWriteWasVisible) { + return false; + } + else if (removedWriteOverlapsWithOtherWrites) { + // There's some shadowing going on. Just rebuild the visible writes from scratch. + writeTreeResetTree_(writeTree); + return true; + } + else { + // There's no shadowing. We can safely just remove the write(s) from visibleWrites. + if (writeToRemove.snap) { + writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path); + } + else { + const children = writeToRemove.children; + each(children, (childName) => { + writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName)); + }); + } + return true; + } +} +function writeTreeRecordContainsPath_(writeRecord, path) { + if (writeRecord.snap) { + return pathContains(writeRecord.path, path); + } + else { + for (const childName in writeRecord.children) { + if (writeRecord.children.hasOwnProperty(childName) && + pathContains(pathChild(writeRecord.path, childName), path)) { + return true; + } + } + return false; + } +} +/** + * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots + */ +function writeTreeResetTree_(writeTree) { + writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath()); + if (writeTree.allWrites.length > 0) { + writeTree.lastWriteId = + writeTree.allWrites[writeTree.allWrites.length - 1].writeId; + } + else { + writeTree.lastWriteId = -1; + } +} +/** + * The default filter used when constructing the tree. Keep everything that's visible. + */ +function writeTreeDefaultFilter_(write) { + return write.visible; +} +/** + * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of + * event data at that path. + */ +function writeTreeLayerTree_(writes, filter, treeRoot) { + let compoundWrite = CompoundWrite.empty(); + for (let i = 0; i < writes.length; ++i) { + const write = writes[i]; + // Theory, a later set will either: + // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction + // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction + if (filter(write)) { + const writePath = write.path; + let relativePath; + if (write.snap) { + if (pathContains(treeRoot, writePath)) { + relativePath = newRelativePath(treeRoot, writePath); + compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap); + } + else if (pathContains(writePath, treeRoot)) { + relativePath = newRelativePath(writePath, treeRoot); + compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath)); + } + else ; + } + else if (write.children) { + if (pathContains(treeRoot, writePath)) { + relativePath = newRelativePath(treeRoot, writePath); + compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children); + } + else if (pathContains(writePath, treeRoot)) { + relativePath = newRelativePath(writePath, treeRoot); + if (pathIsEmpty(relativePath)) { + compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children); + } + else { + const child = safeGet(write.children, pathGetFront(relativePath)); + if (child) { + // There exists a child in this node that matches the root path + const deepNode = child.getChild(pathPopFront(relativePath)); + compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode); + } + } + } + else ; + } + else { + throw assertionError('WriteRecord should have .snap or .children'); + } + } + } + return compoundWrite; +} +/** + * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden + * writes), attempt to calculate a complete snapshot for the given path + * + * @param writeIdsToExclude - An optional set to be excluded + * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false + */ +function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) { + if (!writeIdsToExclude && !includeHiddenWrites) { + const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath); + if (shadowingNode != null) { + return shadowingNode; + } + else { + const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + if (compoundWriteIsEmpty(subMerge)) { + return completeServerCache; + } + else if (completeServerCache == null && + !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) { + // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow + return null; + } + else { + const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE; + return compoundWriteApply(subMerge, layeredCache); + } + } + } + else { + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) { + return completeServerCache; + } + else { + // If the server cache is null, and we don't have a complete cache, we need to return null + if (!includeHiddenWrites && + completeServerCache == null && + !compoundWriteHasCompleteWrite(merge, newEmptyPath())) { + return null; + } + else { + const filter = function (write) { + return ((write.visible || includeHiddenWrites) && + (!writeIdsToExclude || + !~writeIdsToExclude.indexOf(write.writeId)) && + (pathContains(write.path, treePath) || + pathContains(treePath, write.path))); + }; + const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath); + const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE; + return compoundWriteApply(mergeAtPath, layeredCache); + } + } + } +} +/** + * With optional, underlying server data, attempt to return a children node of children that we have complete data for. + * Used when creating new views, to pre-fill their complete event children snapshot. + */ +function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) { + let completeChildren = ChildrenNode.EMPTY_NODE; + const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath); + if (topLevelSet) { + if (!topLevelSet.isLeafNode()) { + // we're shadowing everything. Return the children. + topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => { + completeChildren = completeChildren.updateImmediateChild(childName, childSnap); + }); + } + return completeChildren; + } + else if (completeServerChildren) { + // Layer any children we have on top of this + // We know we don't have a top-level set, so just enumerate existing children + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => { + const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode); + completeChildren = completeChildren.updateImmediateChild(childName, node); + }); + // Add any complete children we have from the set + compoundWriteGetCompleteChildren(merge).forEach(namedNode => { + completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node); + }); + return completeChildren; + } + else { + // We don't have anything to layer on top of. Layer on any children we have + // Note that we can return an empty snap if we have a defined delete + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + compoundWriteGetCompleteChildren(merge).forEach(namedNode => { + completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node); + }); + return completeChildren; + } +} +/** + * Given that the underlying server data has updated, determine what, if anything, needs to be + * applied to the event cache. + * + * Possibilities: + * + * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data + * + * 2. Some write is completely shadowing. No events to be raised + * + * 3. Is partially shadowed. Events + * + * Either existingEventSnap or existingServerSnap must exist + */ +function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) { + assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist'); + const path = pathChild(treePath, childPath); + if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) { + // At this point we can probably guarantee that we're in case 2, meaning no events + // May need to check visibility while doing the findRootMostValueAndPath call + return null; + } + else { + // No complete shadowing. We're either partially shadowing or not shadowing at all. + const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path); + if (compoundWriteIsEmpty(childMerge)) { + // We're not shadowing at all. Case 1 + return existingServerSnap.getChild(childPath); + } + else { + // This could be more efficient if the serverNode + updates doesn't change the eventSnap + // However this is tricky to find out, since user updates don't necessary change the server + // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server + // adds nodes, but doesn't change any existing writes. It is therefore not enough to + // only check if the updates change the serverNode. + // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case? + return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath)); + } + } +} +/** + * Returns a complete child for a given server snap after applying all user writes or null if there is no + * complete child for this ChildKey. + */ +function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) { + const path = pathChild(treePath, childKey); + const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path); + if (shadowingNode != null) { + return shadowingNode; + } + else { + if (existingServerSnap.isCompleteForChild(childKey)) { + const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path); + return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey)); + } + else { + return null; + } + } +} +/** + * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at + * a higher path, this will return the child of that write relative to the write and this path. + * Returns null if there is no write at this path. + */ +function writeTreeShadowingWrite(writeTree, path) { + return compoundWriteGetCompleteNode(writeTree.visibleWrites, path); +} +/** + * This method is used when processing child remove events on a query. If we can, we pull in children that were outside + * the window, but may now be in the window. + */ +function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) { + let toIterate; + const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath); + const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath()); + if (shadowingNode != null) { + toIterate = shadowingNode; + } + else if (completeServerData != null) { + toIterate = compoundWriteApply(merge, completeServerData); + } + else { + // no children to iterate on + return []; + } + toIterate = toIterate.withIndex(index); + if (!toIterate.isEmpty() && !toIterate.isLeafNode()) { + const nodes = []; + const cmp = index.getCompare(); + const iter = reverse + ? toIterate.getReverseIteratorFrom(startPost, index) + : toIterate.getIteratorFrom(startPost, index); + let next = iter.getNext(); + while (next && nodes.length < count) { + if (cmp(next, startPost) !== 0) { + nodes.push(next); + } + next = iter.getNext(); + } + return nodes; + } + else { + return []; + } +} +function newWriteTree() { + return { + visibleWrites: CompoundWrite.empty(), + allWrites: [], + lastWriteId: -1 + }; +} +/** + * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used + * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node + * can lead to a more expensive calculation. + * + * @param writeIdsToExclude - Optional writes to exclude. + * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false + */ +function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) { + return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites); +} +/** + * If possible, returns a children node containing all of the complete children we have data for. The returned data is a + * mix of the given server data and write data. + * + */ +function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) { + return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren); +} +/** + * Given that either the underlying server data has updated or the outstanding writes have updated, determine what, + * if anything, needs to be applied to the event cache. + * + * Possibilities: + * + * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data + * + * 2. Some write is completely shadowing. No events to be raised + * + * 3. Is partially shadowed. Events should be raised + * + * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert + * + * + */ +function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) { + return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap); +} +/** + * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at + * a higher path, this will return the child of that write relative to the write and this path. + * Returns null if there is no write at this path. + * + */ +function writeTreeRefShadowingWrite(writeTreeRef, path) { + return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path)); +} +/** + * This method is used when processing child remove events on a query. If we can, we pull in children that were outside + * the window, but may now be in the window + */ +function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) { + return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index); +} +/** + * Returns a complete child for a given server snap after applying all user writes or null if there is no + * complete child for this ChildKey. + */ +function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) { + return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache); +} +/** + * Return a WriteTreeRef for a child. + */ +function writeTreeRefChild(writeTreeRef, childName) { + return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree); +} +function newWriteTreeRef(path, writeTree) { + return { + treePath: path, + writeTree + }; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ChildChangeAccumulator { + constructor() { + this.changeMap = new Map(); + } + trackChildChange(change) { + const type = change.type; + const childKey = change.childName; + assert(type === "child_added" /* ChangeType.CHILD_ADDED */ || + type === "child_changed" /* ChangeType.CHILD_CHANGED */ || + type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking'); + assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.'); + const oldChange = this.changeMap.get(childKey); + if (oldChange) { + const oldType = oldChange.type; + if (type === "child_added" /* ChangeType.CHILD_ADDED */ && + oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) { + this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode)); + } + else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ && + oldType === "child_added" /* ChangeType.CHILD_ADDED */) { + this.changeMap.delete(childKey); + } + else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ && + oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) { + this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap)); + } + else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ && + oldType === "child_added" /* ChangeType.CHILD_ADDED */) { + this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode)); + } + else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ && + oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) { + this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap)); + } + else { + throw assertionError('Illegal combination of changes: ' + + change + + ' occurred after ' + + oldChange); + } + } + else { + this.changeMap.set(childKey, change); + } + } + getChanges() { + return Array.from(this.changeMap.values()); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An implementation of CompleteChildSource that never returns any additional children + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +class NoCompleteChildSource_ { + getCompleteChild(childKey) { + return null; + } + getChildAfterChild(index, child, reverse) { + return null; + } +} +/** + * Singleton instance. + */ +const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_(); +/** + * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or + * old event caches available to calculate complete children. + */ +class WriteTreeCompleteChildSource { + constructor(writes_, viewCache_, optCompleteServerCache_ = null) { + this.writes_ = writes_; + this.viewCache_ = viewCache_; + this.optCompleteServerCache_ = optCompleteServerCache_; + } + getCompleteChild(childKey) { + const node = this.viewCache_.eventCache; + if (node.isCompleteForChild(childKey)) { + return node.getNode().getImmediateChild(childKey); + } + else { + const serverNode = this.optCompleteServerCache_ != null + ? new CacheNode(this.optCompleteServerCache_, true, false) + : this.viewCache_.serverCache; + return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode); + } + } + getChildAfterChild(index, child, reverse) { + const completeServerData = this.optCompleteServerCache_ != null + ? this.optCompleteServerCache_ + : viewCacheGetCompleteServerSnap(this.viewCache_); + const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index); + if (nodes.length === 0) { + return null; + } + else { + return nodes[0]; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newViewProcessor(filter) { + return { filter }; +} +function viewProcessorAssertIndexed(viewProcessor, viewCache) { + assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed'); + assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed'); +} +function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) { + const accumulator = new ChildChangeAccumulator(); + let newViewCache, filterServerNode; + if (operation.type === OperationType.OVERWRITE) { + const overwrite = operation; + if (overwrite.source.fromUser) { + newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator); + } + else { + assert(overwrite.source.fromServer, 'Unknown source.'); + // We filter the node if it's a tagged update or the node has been previously filtered and the + // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered + // again + filterServerNode = + overwrite.source.tagged || + (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path)); + newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator); + } + } + else if (operation.type === OperationType.MERGE) { + const merge = operation; + if (merge.source.fromUser) { + newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator); + } + else { + assert(merge.source.fromServer, 'Unknown source.'); + // We filter the node if it's a tagged update or the node has been previously filtered + filterServerNode = + merge.source.tagged || oldViewCache.serverCache.isFiltered(); + newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator); + } + } + else if (operation.type === OperationType.ACK_USER_WRITE) { + const ackUserWrite = operation; + if (!ackUserWrite.revert) { + newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator); + } + else { + newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator); + } + } + else if (operation.type === OperationType.LISTEN_COMPLETE) { + newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator); + } + else { + throw assertionError('Unknown operation type: ' + operation.type); + } + const changes = accumulator.getChanges(); + viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes); + return { viewCache: newViewCache, changes }; +} +function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) { + const eventSnap = newViewCache.eventCache; + if (eventSnap.isFullyInitialized()) { + const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty(); + const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache); + if (accumulator.length > 0 || + !oldViewCache.eventCache.isFullyInitialized() || + (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) || + !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) { + accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache))); + } + } +} +function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) { + const oldEventSnap = viewCache.eventCache; + if (writeTreeRefShadowingWrite(writesCache, changePath) != null) { + // we have a shadowing write, ignore changes + return viewCache; + } + else { + let newEventCache, serverNode; + if (pathIsEmpty(changePath)) { + // TODO: figure out how this plays with "sliding ack windows" + assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data'); + if (viewCache.serverCache.isFiltered()) { + // We need to special case this, because we need to only apply writes to complete children, or + // we might end up raising events for incomplete children. If the server data is filtered deep + // writes cannot be guaranteed to be complete + const serverCache = viewCacheGetCompleteServerSnap(viewCache); + const completeChildren = serverCache instanceof ChildrenNode + ? serverCache + : ChildrenNode.EMPTY_NODE; + const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren); + newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator); + } + else { + const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache)); + newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator); + } + } + else { + const childKey = pathGetFront(changePath); + if (childKey === '.priority') { + assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components"); + const oldEventNode = oldEventSnap.getNode(); + serverNode = viewCache.serverCache.getNode(); + // we might have overwrites for this priority + const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode); + if (updatedPriority != null) { + newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority); + } + else { + // priority didn't change, keep old node + newEventCache = oldEventSnap.getNode(); + } + } + else { + const childChangePath = pathPopFront(changePath); + // update child + let newEventChild; + if (oldEventSnap.isCompleteForChild(childKey)) { + serverNode = viewCache.serverCache.getNode(); + const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode); + if (eventChildUpdate != null) { + newEventChild = oldEventSnap + .getNode() + .getImmediateChild(childKey) + .updateChild(childChangePath, eventChildUpdate); + } + else { + // Nothing changed, just keep the old child + newEventChild = oldEventSnap.getNode().getImmediateChild(childKey); + } + } + else { + newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache); + } + if (newEventChild != null) { + newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator); + } + else { + // no complete child available or no change + newEventCache = oldEventSnap.getNode(); + } + } + } + return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes()); + } +} +function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) { + const oldServerSnap = oldViewCache.serverCache; + let newServerCache; + const serverFilter = filterServerNode + ? viewProcessor.filter + : viewProcessor.filter.getIndexedFilter(); + if (pathIsEmpty(changePath)) { + newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null); + } + else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) { + // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update + const newServerNode = oldServerSnap + .getNode() + .updateChild(changePath, changedSnap); + newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null); + } + else { + const childKey = pathGetFront(changePath); + if (!oldServerSnap.isCompleteForPath(changePath) && + pathGetLength(changePath) > 1) { + // We don't update incomplete nodes with updates intended for other listeners + return oldViewCache; + } + const childChangePath = pathPopFront(changePath); + const childNode = oldServerSnap.getNode().getImmediateChild(childKey); + const newChildNode = childNode.updateChild(childChangePath, changedSnap); + if (childKey === '.priority') { + newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode); + } + else { + newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null); + } + } + const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes()); + const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache); + return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator); +} +function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) { + const oldEventSnap = oldViewCache.eventCache; + let newViewCache, newEventCache; + const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache); + if (pathIsEmpty(changePath)) { + newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator); + newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes()); + } + else { + const childKey = pathGetFront(changePath); + if (childKey === '.priority') { + newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap); + newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered()); + } + else { + const childChangePath = pathPopFront(changePath); + const oldChild = oldEventSnap.getNode().getImmediateChild(childKey); + let newChild; + if (pathIsEmpty(childChangePath)) { + // Child overwrite, we can replace the child + newChild = changedSnap; + } + else { + const childNode = source.getCompleteChild(childKey); + if (childNode != null) { + if (pathGetBack(childChangePath) === '.priority' && + childNode.getChild(pathParent(childChangePath)).isEmpty()) { + // This is a priority update on an empty node. If this node exists on the server, the + // server will send down the priority in the update, so ignore for now + newChild = childNode; + } + else { + newChild = childNode.updateChild(childChangePath, changedSnap); + } + } + else { + // There is no complete child node available + newChild = ChildrenNode.EMPTY_NODE; + } + } + if (!oldChild.equals(newChild)) { + const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator); + newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes()); + } + else { + newViewCache = oldViewCache; + } + } + } + return newViewCache; +} +function viewProcessorCacheHasChild(viewCache, childKey) { + return viewCache.eventCache.isCompleteForChild(childKey); +} +function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) { + // HACK: In the case of a limit query, there may be some changes that bump things out of the + // window leaving room for new items. It's important we process these changes first, so we + // iterate the changes twice, first processing any that affect items currently in view. + // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server + // and event snap. I'm not sure if this will result in edge cases when a child is in one but + // not the other. + let curViewCache = viewCache; + changedChildren.foreach((relativePath, childNode) => { + const writePath = pathChild(path, relativePath); + if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) { + curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator); + } + }); + changedChildren.foreach((relativePath, childNode) => { + const writePath = pathChild(path, relativePath); + if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) { + curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator); + } + }); + return curViewCache; +} +function viewProcessorApplyMerge(viewProcessor, node, merge) { + merge.foreach((relativePath, childNode) => { + node = node.updateChild(relativePath, childNode); + }); + return node; +} +function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) { + // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and + // wait for the complete data update coming soon. + if (viewCache.serverCache.getNode().isEmpty() && + !viewCache.serverCache.isFullyInitialized()) { + return viewCache; + } + // HACK: In the case of a limit query, there may be some changes that bump things out of the + // window leaving room for new items. It's important we process these changes first, so we + // iterate the changes twice, first processing any that affect items currently in view. + // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server + // and event snap. I'm not sure if this will result in edge cases when a child is in one but + // not the other. + let curViewCache = viewCache; + let viewMergeTree; + if (pathIsEmpty(path)) { + viewMergeTree = changedChildren; + } + else { + viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren); + } + const serverNode = viewCache.serverCache.getNode(); + viewMergeTree.children.inorderTraversal((childKey, childTree) => { + if (serverNode.hasChild(childKey)) { + const serverChild = viewCache.serverCache + .getNode() + .getImmediateChild(childKey); + const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree); + curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator); + } + }); + viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => { + const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) && + childMergeTree.value === null; + if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) { + const serverChild = viewCache.serverCache + .getNode() + .getImmediateChild(childKey); + const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree); + curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator); + } + }); + return curViewCache; +} +function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) { + if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) { + return viewCache; + } + // Only filter server node if it is currently filtered + const filterServerNode = viewCache.serverCache.isFiltered(); + // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update + // now that it won't be shadowed. + const serverCache = viewCache.serverCache; + if (affectedTree.value != null) { + // This is an overwrite. + if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) || + serverCache.isCompleteForPath(ackPath)) { + return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator); + } + else if (pathIsEmpty(ackPath)) { + // This is a goofy edge case where we are acking data at this location but don't have full data. We + // should just re-apply whatever we have in our cache as a merge. + let changedChildren = new ImmutableTree(null); + serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => { + changedChildren = changedChildren.set(new Path(name), node); + }); + return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator); + } + else { + return viewCache; + } + } + else { + // This is a merge. + let changedChildren = new ImmutableTree(null); + affectedTree.foreach((mergePath, value) => { + const serverCachePath = pathChild(ackPath, mergePath); + if (serverCache.isCompleteForPath(serverCachePath)) { + changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath)); + } + }); + return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator); + } +} +function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) { + const oldServerNode = viewCache.serverCache; + const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered()); + return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator); +} +function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) { + let complete; + if (writeTreeRefShadowingWrite(writesCache, path) != null) { + return viewCache; + } + else { + const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache); + const oldEventCache = viewCache.eventCache.getNode(); + let newEventCache; + if (pathIsEmpty(path) || pathGetFront(path) === '.priority') { + let newNode; + if (viewCache.serverCache.isFullyInitialized()) { + newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache)); + } + else { + const serverChildren = viewCache.serverCache.getNode(); + assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node'); + newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren); + } + newNode = newNode; + newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator); + } + else { + const childKey = pathGetFront(path); + let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache); + if (newChild == null && + viewCache.serverCache.isCompleteForChild(childKey)) { + newChild = oldEventCache.getImmediateChild(childKey); + } + if (newChild != null) { + newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator); + } + else if (viewCache.eventCache.getNode().hasChild(childKey)) { + // No complete child available, delete the existing one, if any + newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator); + } + else { + newEventCache = oldEventCache; + } + if (newEventCache.isEmpty() && + viewCache.serverCache.isFullyInitialized()) { + // We might have reverted all child writes. Maybe the old event was a leaf node + complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache)); + if (complete.isLeafNode()) { + newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator); + } + } + } + complete = + viewCache.serverCache.isFullyInitialized() || + writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null; + return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes()); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A view represents a specific location and query that has 1 or more event registrations. + * + * It does several things: + * - Maintains the list of event registrations for this location/query. + * - Maintains a cache of the data visible for this location/query. + * - Applies new operations (via applyOperation), updates the cache, and based on the event + * registrations returns the set of events to be raised. + */ +class View { + constructor(query_, initialViewCache) { + this.query_ = query_; + this.eventRegistrations_ = []; + const params = this.query_._queryParams; + const indexFilter = new IndexedFilter(params.getIndex()); + const filter = queryParamsGetNodeFilter(params); + this.processor_ = newViewProcessor(filter); + const initialServerCache = initialViewCache.serverCache; + const initialEventCache = initialViewCache.eventCache; + // Don't filter server node with other filter than index, wait for tagged listen + const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null); + const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null); + const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes()); + const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes()); + this.viewCache_ = newViewCache(newEventCache, newServerCache); + this.eventGenerator_ = new EventGenerator(this.query_); + } + get query() { + return this.query_; + } +} +function viewGetServerCache(view) { + return view.viewCache_.serverCache.getNode(); +} +function viewGetCompleteNode(view) { + return viewCacheGetCompleteEventSnap(view.viewCache_); +} +function viewGetCompleteServerCache(view, path) { + const cache = viewCacheGetCompleteServerSnap(view.viewCache_); + if (cache) { + // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and + // we need to see if it contains the child we're interested in. + if (view.query._queryParams.loadsAllData() || + (!pathIsEmpty(path) && + !cache.getImmediateChild(pathGetFront(path)).isEmpty())) { + return cache.getChild(path); + } + } + return null; +} +function viewIsEmpty(view) { + return view.eventRegistrations_.length === 0; +} +function viewAddEventRegistration(view, eventRegistration) { + view.eventRegistrations_.push(eventRegistration); +} +/** + * @param eventRegistration - If null, remove all callbacks. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @returns Cancel events, if cancelError was provided. + */ +function viewRemoveEventRegistration(view, eventRegistration, cancelError) { + const cancelEvents = []; + if (cancelError) { + assert(eventRegistration == null, 'A cancel should cancel all event registrations.'); + const path = view.query._path; + view.eventRegistrations_.forEach(registration => { + const maybeEvent = registration.createCancelEvent(cancelError, path); + if (maybeEvent) { + cancelEvents.push(maybeEvent); + } + }); + } + if (eventRegistration) { + let remaining = []; + for (let i = 0; i < view.eventRegistrations_.length; ++i) { + const existing = view.eventRegistrations_[i]; + if (!existing.matches(eventRegistration)) { + remaining.push(existing); + } + else if (eventRegistration.hasAnyCallback()) { + // We're removing just this one + remaining = remaining.concat(view.eventRegistrations_.slice(i + 1)); + break; + } + } + view.eventRegistrations_ = remaining; + } + else { + view.eventRegistrations_ = []; + } + return cancelEvents; +} +/** + * Applies the given Operation, updates our cache, and returns the appropriate events. + */ +function viewApplyOperation(view, operation, writesCache, completeServerCache) { + if (operation.type === OperationType.MERGE && + operation.source.queryId !== null) { + assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges'); + assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache'); + } + const oldViewCache = view.viewCache_; + const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache); + viewProcessorAssertIndexed(view.processor_, result.viewCache); + assert(result.viewCache.serverCache.isFullyInitialized() || + !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back'); + view.viewCache_ = result.viewCache; + return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null); +} +function viewGetInitialEvents(view, registration) { + const eventSnap = view.viewCache_.eventCache; + const initialChanges = []; + if (!eventSnap.getNode().isLeafNode()) { + const eventNode = eventSnap.getNode(); + eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => { + initialChanges.push(changeChildAdded(key, childNode)); + }); + } + if (eventSnap.isFullyInitialized()) { + initialChanges.push(changeValue(eventSnap.getNode())); + } + return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration); +} +function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) { + const registrations = eventRegistration + ? [eventRegistration] + : view.eventRegistrations_; + return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let referenceConstructor$1; +/** + * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to + * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes + * and user writes (set, transaction, update). + * + * It's responsible for: + * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed). + * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite, + * applyUserOverwrite, etc.) + */ +class SyncPoint { + constructor() { + /** + * The Views being tracked at this location in the tree, stored as a map where the key is a + * queryId and the value is the View for that query. + * + * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case). + */ + this.views = new Map(); + } +} +function syncPointSetReferenceConstructor(val) { + assert(!referenceConstructor$1, '__referenceConstructor has already been defined'); + referenceConstructor$1 = val; +} +function syncPointGetReferenceConstructor() { + assert(referenceConstructor$1, 'Reference.ts has not been loaded'); + return referenceConstructor$1; +} +function syncPointIsEmpty(syncPoint) { + return syncPoint.views.size === 0; +} +function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) { + const queryId = operation.source.queryId; + if (queryId !== null) { + const view = syncPoint.views.get(queryId); + assert(view != null, 'SyncTree gave us an op for an invalid query.'); + return viewApplyOperation(view, operation, writesCache, optCompleteServerCache); + } + else { + let events = []; + for (const view of syncPoint.views.values()) { + events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache)); + } + return events; + } +} +/** + * Get a view for the specified query. + * + * @param query - The query to return a view for + * @param writesCache + * @param serverCache + * @param serverCacheComplete + * @returns Events to raise. + */ +function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) { + const queryId = query._queryIdentifier; + const view = syncPoint.views.get(queryId); + if (!view) { + // TODO: make writesCache take flag for complete server node + let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null); + let eventCacheComplete = false; + if (eventCache) { + eventCacheComplete = true; + } + else if (serverCache instanceof ChildrenNode) { + eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache); + eventCacheComplete = false; + } + else { + eventCache = ChildrenNode.EMPTY_NODE; + eventCacheComplete = false; + } + const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false)); + return new View(query, viewCache); + } + return view; +} +/** + * Add an event callback for the specified query. + * + * @param query + * @param eventRegistration + * @param writesCache + * @param serverCache - Complete server cache, if we have it. + * @param serverCacheComplete + * @returns Events to raise. + */ +function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) { + const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete); + if (!syncPoint.views.has(query._queryIdentifier)) { + syncPoint.views.set(query._queryIdentifier, view); + } + // This is guaranteed to exist now, we just created anything that was missing + viewAddEventRegistration(view, eventRegistration); + return viewGetInitialEvents(view, eventRegistration); +} +/** + * Remove event callback(s). Return cancelEvents if a cancelError is specified. + * + * If query is the default query, we'll check all views for the specified eventRegistration. + * If eventRegistration is null, we'll remove all callbacks for the specified view(s). + * + * @param eventRegistration - If null, remove all callbacks. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @returns removed queries and any cancel events + */ +function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) { + const queryId = query._queryIdentifier; + const removed = []; + let cancelEvents = []; + const hadCompleteView = syncPointHasCompleteView(syncPoint); + if (queryId === 'default') { + // When you do ref.off(...), we search all views for the registration to remove. + for (const [viewQueryId, view] of syncPoint.views.entries()) { + cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError)); + if (viewIsEmpty(view)) { + syncPoint.views.delete(viewQueryId); + // We'll deal with complete views later. + if (!view.query._queryParams.loadsAllData()) { + removed.push(view.query); + } + } + } + } + else { + // remove the callback from the specific view. + const view = syncPoint.views.get(queryId); + if (view) { + cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError)); + if (viewIsEmpty(view)) { + syncPoint.views.delete(queryId); + // We'll deal with complete views later. + if (!view.query._queryParams.loadsAllData()) { + removed.push(view.query); + } + } + } + } + if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) { + // We removed our last complete view. + removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path)); + } + return { removed, events: cancelEvents }; +} +function syncPointGetQueryViews(syncPoint) { + const result = []; + for (const view of syncPoint.views.values()) { + if (!view.query._queryParams.loadsAllData()) { + result.push(view); + } + } + return result; +} +/** + * @param path - The path to the desired complete snapshot + * @returns A complete cache, if it exists + */ +function syncPointGetCompleteServerCache(syncPoint, path) { + let serverCache = null; + for (const view of syncPoint.views.values()) { + serverCache = serverCache || viewGetCompleteServerCache(view, path); + } + return serverCache; +} +function syncPointViewForQuery(syncPoint, query) { + const params = query._queryParams; + if (params.loadsAllData()) { + return syncPointGetCompleteView(syncPoint); + } + else { + const queryId = query._queryIdentifier; + return syncPoint.views.get(queryId); + } +} +function syncPointViewExistsForQuery(syncPoint, query) { + return syncPointViewForQuery(syncPoint, query) != null; +} +function syncPointHasCompleteView(syncPoint) { + return syncPointGetCompleteView(syncPoint) != null; +} +function syncPointGetCompleteView(syncPoint) { + for (const view of syncPoint.views.values()) { + if (view.query._queryParams.loadsAllData()) { + return view; + } + } + return null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let referenceConstructor; +function syncTreeSetReferenceConstructor(val) { + assert(!referenceConstructor, '__referenceConstructor has already been defined'); + referenceConstructor = val; +} +function syncTreeGetReferenceConstructor() { + assert(referenceConstructor, 'Reference.ts has not been loaded'); + return referenceConstructor; +} +/** + * Static tracker for next query tag. + */ +let syncTreeNextQueryTag_ = 1; +/** + * SyncTree is the central class for managing event callback registration, data caching, views + * (query processing), and event generation. There are typically two SyncTree instances for + * each Repo, one for the normal Firebase data, and one for the .info data. + * + * It has a number of responsibilities, including: + * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()). + * - Applying and caching data changes for user set(), transaction(), and update() calls + * (applyUserOverwrite(), applyUserMerge()). + * - Applying and caching data changes for server data changes (applyServerOverwrite(), + * applyServerMerge()). + * - Generating user-facing events for server and user changes (all of the apply* methods + * return the set of events that need to be raised as a result). + * - Maintaining the appropriate set of server listens to ensure we are always subscribed + * to the correct set of paths and queries to satisfy the current set of user event + * callbacks (listens are started/stopped using the provided listenProvider). + * + * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual + * events are returned to the caller rather than raised synchronously. + * + */ +class SyncTree { + /** + * @param listenProvider_ - Used by SyncTree to start / stop listening + * to server data. + */ + constructor(listenProvider_) { + this.listenProvider_ = listenProvider_; + /** + * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views. + */ + this.syncPointTree_ = new ImmutableTree(null); + /** + * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.). + */ + this.pendingWriteTree_ = newWriteTree(); + this.tagToQueryMap = new Map(); + this.queryToTagMap = new Map(); + } +} +/** + * Apply the data changes for a user-generated set() or transaction() call. + * + * @returns Events to raise. + */ +function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) { + // Record pending write. + writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible); + if (!visible) { + return []; + } + else { + return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData)); + } +} +/** + * Apply the data from a user-generated update() call + * + * @returns Events to raise. + */ +function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) { + // Record pending merge. + writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId); + const changeTree = ImmutableTree.fromObject(changedChildren); + return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree)); +} +/** + * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge(). + * + * @param revert - True if the given write failed and needs to be reverted + * @returns Events to raise. + */ +function syncTreeAckUserWrite(syncTree, writeId, revert = false) { + const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId); + const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId); + if (!needToReevaluate) { + return []; + } + else { + let affectedTree = new ImmutableTree(null); + if (write.snap != null) { + // overwrite + affectedTree = affectedTree.set(newEmptyPath(), true); + } + else { + each(write.children, (pathString) => { + affectedTree = affectedTree.set(new Path(pathString), true); + }); + } + return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert)); + } +} +/** + * Apply new server data for the specified path.. + * + * @returns Events to raise. + */ +function syncTreeApplyServerOverwrite(syncTree, path, newData) { + return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData)); +} +/** + * Apply new server data to be merged in at the specified path. + * + * @returns Events to raise. + */ +function syncTreeApplyServerMerge(syncTree, path, changedChildren) { + const changeTree = ImmutableTree.fromObject(changedChildren); + return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree)); +} +/** + * Apply a listen complete for a query + * + * @returns Events to raise. + */ +function syncTreeApplyListenComplete(syncTree, path) { + return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path)); +} +/** + * Apply a listen complete for a tagged query + * + * @returns Events to raise. + */ +function syncTreeApplyTaggedListenComplete(syncTree, path, tag) { + const queryKey = syncTreeQueryKeyForTag_(syncTree, tag); + if (queryKey) { + const r = syncTreeParseQueryKey_(queryKey); + const queryPath = r.path, queryId = r.queryId; + const relativePath = newRelativePath(queryPath, path); + const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath); + return syncTreeApplyTaggedOperation_(syncTree, queryPath, op); + } + else { + // We've already removed the query. No big deal, ignore the update + return []; + } +} +/** + * Remove event callback(s). + * + * If query is the default query, we'll check all queries for the specified eventRegistration. + * If eventRegistration is null, we'll remove all callbacks for the specified query/queries. + * + * @param eventRegistration - If null, all callbacks are removed. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no + * deduping needs to take place. This flag allows toggling of that behavior + * @returns Cancel events, if cancelError was provided. + */ +function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) { + // Find the syncPoint first. Then deal with whether or not it has matching listeners + const path = query._path; + const maybeSyncPoint = syncTree.syncPointTree_.get(path); + let cancelEvents = []; + // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without + // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and + // not loadsAllData(). + if (maybeSyncPoint && + (query._queryIdentifier === 'default' || + syncPointViewExistsForQuery(maybeSyncPoint, query))) { + const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError); + if (syncPointIsEmpty(maybeSyncPoint)) { + syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path); + } + const removed = removedAndEvents.removed; + cancelEvents = removedAndEvents.events; + if (!skipListenerDedup) { + /** + * We may have just removed one of many listeners and can short-circuit this whole process + * We may also not have removed a default listener, in which case all of the descendant listeners should already be + * properly set up. + */ + // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of + // queryId === 'default' + const removingDefault = -1 !== + removed.findIndex(query => { + return query._queryParams.loadsAllData(); + }); + const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint)); + if (removingDefault && !covered) { + const subtree = syncTree.syncPointTree_.subtree(path); + // There are potentially child listeners. Determine what if any listens we need to send before executing the + // removal + if (!subtree.isEmpty()) { + // We need to fold over our subtree and collect the listeners to send + const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree); + // Ok, we've collected all the listens we need. Set them up. + for (let i = 0; i < newViews.length; ++i) { + const view = newViews[i], newQuery = view.query; + const listener = syncTreeCreateListenerForView_(syncTree, view); + syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete); + } + } + // Otherwise there's nothing below us, so nothing we need to start listening on + } + // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query + // The above block has us covered in terms of making sure we're set up on listens lower in the tree. + // Also, note that if we have a cancelError, it's already been removed at the provider level. + if (!covered && removed.length > 0 && !cancelError) { + // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one + // default. Otherwise, we need to iterate through and cancel each individual query + if (removingDefault) { + // We don't tag default listeners + const defaultTag = null; + syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag); + } + else { + removed.forEach((queryToRemove) => { + const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove)); + syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove); + }); + } + } + } + // Now, clear all of the tags we're tracking for the removed listens + syncTreeRemoveTags_(syncTree, removed); + } + return cancelEvents; +} +/** + * Apply new server data for the specified tagged query. + * + * @returns Events to raise. + */ +function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) { + const queryKey = syncTreeQueryKeyForTag_(syncTree, tag); + if (queryKey != null) { + const r = syncTreeParseQueryKey_(queryKey); + const queryPath = r.path, queryId = r.queryId; + const relativePath = newRelativePath(queryPath, path); + const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap); + return syncTreeApplyTaggedOperation_(syncTree, queryPath, op); + } + else { + // Query must have been removed already + return []; + } +} +/** + * Apply server data to be merged in for the specified tagged query. + * + * @returns Events to raise. + */ +function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) { + const queryKey = syncTreeQueryKeyForTag_(syncTree, tag); + if (queryKey) { + const r = syncTreeParseQueryKey_(queryKey); + const queryPath = r.path, queryId = r.queryId; + const relativePath = newRelativePath(queryPath, path); + const changeTree = ImmutableTree.fromObject(changedChildren); + const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree); + return syncTreeApplyTaggedOperation_(syncTree, queryPath, op); + } + else { + // We've already removed the query. No big deal, ignore the update + return []; + } +} +/** + * Add an event callback for the specified query. + * + * @returns Events to raise. + */ +function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) { + const path = query._path; + let serverCache = null; + let foundAncestorDefaultView = false; + // Any covering writes will necessarily be at the root, so really all we need to find is the server cache. + // Consider optimizing this once there's a better understanding of what actual behavior will be. + syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => { + const relativePath = newRelativePath(pathToSyncPoint, path); + serverCache = + serverCache || syncPointGetCompleteServerCache(sp, relativePath); + foundAncestorDefaultView = + foundAncestorDefaultView || syncPointHasCompleteView(sp); + }); + let syncPoint = syncTree.syncPointTree_.get(path); + if (!syncPoint) { + syncPoint = new SyncPoint(); + syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint); + } + else { + foundAncestorDefaultView = + foundAncestorDefaultView || syncPointHasCompleteView(syncPoint); + serverCache = + serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + let serverCacheComplete; + if (serverCache != null) { + serverCacheComplete = true; + } + else { + serverCacheComplete = false; + serverCache = ChildrenNode.EMPTY_NODE; + const subtree = syncTree.syncPointTree_.subtree(path); + subtree.foreachChild((childName, childSyncPoint) => { + const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath()); + if (completeCache) { + serverCache = serverCache.updateImmediateChild(childName, completeCache); + } + }); + } + const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query); + if (!viewAlreadyExists && !query._queryParams.loadsAllData()) { + // We need to track a tag for this query + const queryKey = syncTreeMakeQueryKey_(query); + assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag'); + const tag = syncTreeGetNextQueryTag_(); + syncTree.queryToTagMap.set(queryKey, tag); + syncTree.tagToQueryMap.set(tag, queryKey); + } + const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path); + let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete); + if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) { + const view = syncPointViewForQuery(syncPoint, query); + events = events.concat(syncTreeSetupListener_(syncTree, query, view)); + } + return events; +} +/** + * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a + * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always + * have a listener above, and atomic operations would correctly show a jitter of -> + * as the write is applied locally and then acknowledged at the server. + * + * Note: this method will *include* hidden writes from transaction with applyLocally set to false. + * + * @param path - The path to the data we want + * @param writeIdsToExclude - A specific set to be excluded + */ +function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) { + const includeHiddenSets = true; + const writeTree = syncTree.pendingWriteTree_; + const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => { + const relativePath = newRelativePath(pathSoFar, path); + const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath); + if (serverCache) { + return serverCache; + } + }); + return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets); +} +function syncTreeGetServerValue(syncTree, query) { + const path = query._path; + let serverCache = null; + // Any covering writes will necessarily be at the root, so really all we need to find is the server cache. + // Consider optimizing this once there's a better understanding of what actual behavior will be. + syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => { + const relativePath = newRelativePath(pathToSyncPoint, path); + serverCache = + serverCache || syncPointGetCompleteServerCache(sp, relativePath); + }); + let syncPoint = syncTree.syncPointTree_.get(path); + if (!syncPoint) { + syncPoint = new SyncPoint(); + syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint); + } + else { + serverCache = + serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + const serverCacheComplete = serverCache != null; + const serverCacheNode = serverCacheComplete + ? new CacheNode(serverCache, true, false) + : null; + const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path); + const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete); + return viewGetCompleteNode(view); +} +/** + * A helper method that visits all descendant and ancestor SyncPoints, applying the operation. + * + * NOTES: + * - Descendant SyncPoints will be visited first (since we raise events depth-first). + * + * - We call applyOperation() on each SyncPoint passing three things: + * 1. A version of the Operation that has been made relative to the SyncPoint location. + * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location. + * 3. A snapshot Node with cached server data, if we have it. + * + * - We concatenate all of the events returned by each SyncPoint and return the result. + */ +function syncTreeApplyOperationToSyncPoints_(syncTree, operation) { + return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_, + /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath())); +} +/** + * Recursive helper for applyOperationToSyncPoints_ + */ +function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) { + if (pathIsEmpty(operation.path)) { + return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache); + } + else { + const syncPoint = syncPointTree.get(newEmptyPath()); + // If we don't have cached server data, see if we can get it from this SyncPoint. + if (serverCache == null && syncPoint != null) { + serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + let events = []; + const childName = pathGetFront(operation.path); + const childOperation = operation.operationForChild(childName); + const childTree = syncPointTree.children.get(childName); + if (childTree && childOperation) { + const childServerCache = serverCache + ? serverCache.getImmediateChild(childName) + : null; + const childWritesCache = writeTreeRefChild(writesCache, childName); + events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache)); + } + if (syncPoint) { + events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)); + } + return events; + } +} +/** + * Recursive helper for applyOperationToSyncPoints_ + */ +function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) { + const syncPoint = syncPointTree.get(newEmptyPath()); + // If we don't have cached server data, see if we can get it from this SyncPoint. + if (serverCache == null && syncPoint != null) { + serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath()); + } + let events = []; + syncPointTree.children.inorderTraversal((childName, childTree) => { + const childServerCache = serverCache + ? serverCache.getImmediateChild(childName) + : null; + const childWritesCache = writeTreeRefChild(writesCache, childName); + const childOperation = operation.operationForChild(childName); + if (childOperation) { + events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache)); + } + }); + if (syncPoint) { + events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)); + } + return events; +} +function syncTreeCreateListenerForView_(syncTree, view) { + const query = view.query; + const tag = syncTreeTagForQuery(syncTree, query); + return { + hashFn: () => { + const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE; + return cache.hash(); + }, + onComplete: (status) => { + if (status === 'ok') { + if (tag) { + return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag); + } + else { + return syncTreeApplyListenComplete(syncTree, query._path); + } + } + else { + // If a listen failed, kill all of the listeners here, not just the one that triggered the error. + // Note that this may need to be scoped to just this listener if we change permissions on filtered children + const error = errorForServerCode(status, query); + return syncTreeRemoveEventRegistration(syncTree, query, + /*eventRegistration*/ null, error); + } + } + }; +} +/** + * Return the tag associated with the given query. + */ +function syncTreeTagForQuery(syncTree, query) { + const queryKey = syncTreeMakeQueryKey_(query); + return syncTree.queryToTagMap.get(queryKey); +} +/** + * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_. + */ +function syncTreeMakeQueryKey_(query) { + return query._path.toString() + '$' + query._queryIdentifier; +} +/** + * Return the query associated with the given tag, if we have one + */ +function syncTreeQueryKeyForTag_(syncTree, tag) { + return syncTree.tagToQueryMap.get(tag); +} +/** + * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId. + */ +function syncTreeParseQueryKey_(queryKey) { + const splitIndex = queryKey.indexOf('$'); + assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.'); + return { + queryId: queryKey.substr(splitIndex + 1), + path: new Path(queryKey.substr(0, splitIndex)) + }; +} +/** + * A helper method to apply tagged operations + */ +function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) { + const syncPoint = syncTree.syncPointTree_.get(queryPath); + assert(syncPoint, "Missing sync point for query tag that we're tracking"); + const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath); + return syncPointApplyOperation(syncPoint, operation, writesCache, null); +} +/** + * This collapses multiple unfiltered views into a single view, since we only need a single + * listener for them. + */ +function syncTreeCollectDistinctViewsForSubTree_(subtree) { + return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => { + if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) { + const completeView = syncPointGetCompleteView(maybeChildSyncPoint); + return [completeView]; + } + else { + // No complete view here, flatten any deeper listens into an array + let views = []; + if (maybeChildSyncPoint) { + views = syncPointGetQueryViews(maybeChildSyncPoint); + } + each(childMap, (_key, childViews) => { + views = views.concat(childViews); + }); + return views; + } + }); +} +/** + * Normalizes a query to a query we send the server for listening + * + * @returns The normalized query + */ +function syncTreeQueryForListening_(query) { + if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) { + // We treat queries that load all data as default queries + // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits + // from Query + return new (syncTreeGetReferenceConstructor())(query._repo, query._path); + } + else { + return query; + } +} +function syncTreeRemoveTags_(syncTree, queries) { + for (let j = 0; j < queries.length; ++j) { + const removedQuery = queries[j]; + if (!removedQuery._queryParams.loadsAllData()) { + // We should have a tag for this + const removedQueryKey = syncTreeMakeQueryKey_(removedQuery); + const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey); + syncTree.queryToTagMap.delete(removedQueryKey); + syncTree.tagToQueryMap.delete(removedQueryTag); + } + } +} +/** + * Static accessor for query tags. + */ +function syncTreeGetNextQueryTag_() { + return syncTreeNextQueryTag_++; +} +/** + * For a given new listen, manage the de-duplication of outstanding subscriptions. + * + * @returns This method can return events to support synchronous data sources + */ +function syncTreeSetupListener_(syncTree, query, view) { + const path = query._path; + const tag = syncTreeTagForQuery(syncTree, query); + const listener = syncTreeCreateListenerForView_(syncTree, view); + const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete); + const subtree = syncTree.syncPointTree_.subtree(path); + // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we + // may need to shadow other listens as well. + if (tag) { + assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed"); + } + else { + // Shadow everything at or below this location, this is a default listener. + const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => { + if (!pathIsEmpty(relativePath) && + maybeChildSyncPoint && + syncPointHasCompleteView(maybeChildSyncPoint)) { + return [syncPointGetCompleteView(maybeChildSyncPoint).query]; + } + else { + // No default listener here, flatten any deeper queries into an array + let queries = []; + if (maybeChildSyncPoint) { + queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query)); + } + each(childMap, (_key, childQueries) => { + queries = queries.concat(childQueries); + }); + return queries; + } + }); + for (let i = 0; i < queriesToStop.length; ++i) { + const queryToStop = queriesToStop[i]; + syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop)); + } + } + return events; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ExistingValueProvider { + constructor(node_) { + this.node_ = node_; + } + getImmediateChild(childName) { + const child = this.node_.getImmediateChild(childName); + return new ExistingValueProvider(child); + } + node() { + return this.node_; + } +} +class DeferredValueProvider { + constructor(syncTree, path) { + this.syncTree_ = syncTree; + this.path_ = path; + } + getImmediateChild(childName) { + const childPath = pathChild(this.path_, childName); + return new DeferredValueProvider(this.syncTree_, childPath); + } + node() { + return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_); + } +} +/** + * Generate placeholders for deferred values. + */ +const generateWithValues = function (values) { + values = values || {}; + values['timestamp'] = values['timestamp'] || new Date().getTime(); + return values; +}; +/** + * Value to use when firing local events. When writing server values, fire + * local events with an approximate value, otherwise return value as-is. + */ +const resolveDeferredLeafValue = function (value, existingVal, serverValues) { + if (!value || typeof value !== 'object') { + return value; + } + assert('.sv' in value, 'Unexpected leaf node or priority contents'); + if (typeof value['.sv'] === 'string') { + return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues); + } + else if (typeof value['.sv'] === 'object') { + return resolveComplexDeferredValue(value['.sv'], existingVal); + } + else { + assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2)); + } +}; +const resolveScalarDeferredValue = function (op, existing, serverValues) { + switch (op) { + case 'timestamp': + return serverValues['timestamp']; + default: + assert(false, 'Unexpected server value: ' + op); + } +}; +const resolveComplexDeferredValue = function (op, existing, unused) { + if (!op.hasOwnProperty('increment')) { + assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2)); + } + const delta = op['increment']; + if (typeof delta !== 'number') { + assert(false, 'Unexpected increment value: ' + delta); + } + const existingNode = existing.node(); + assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls'); + // Incrementing a non-number sets the value to the incremented amount + if (!existingNode.isLeafNode()) { + return delta; + } + const leaf = existingNode; + const existingVal = leaf.getValue(); + if (typeof existingVal !== 'number') { + return delta; + } + // No need to do over/underflow arithmetic here because JS only handles floats under the covers + return existingVal + delta; +}; +/** + * Recursively replace all deferred values and priorities in the tree with the + * specified generated replacement values. + * @param path - path to which write is relative + * @param node - new data written at path + * @param syncTree - current data + */ +const resolveDeferredValueTree = function (path, node, syncTree, serverValues) { + return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues); +}; +/** + * Recursively replace all deferred values and priorities in the node with the + * specified generated replacement values. If there are no server values in the node, + * it'll be returned as-is. + */ +const resolveDeferredValueSnapshot = function (node, existing, serverValues) { + return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues); +}; +function resolveDeferredValue(node, existingVal, serverValues) { + const rawPri = node.getPriority().val(); + const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues); + let newNode; + if (node.isLeafNode()) { + const leafNode = node; + const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues); + if (value !== leafNode.getValue() || + priority !== leafNode.getPriority().val()) { + return new LeafNode(value, nodeFromJSON(priority)); + } + else { + return node; + } + } + else { + const childrenNode = node; + newNode = childrenNode; + if (priority !== childrenNode.getPriority().val()) { + newNode = newNode.updatePriority(new LeafNode(priority)); + } + childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => { + const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues); + if (newChildNode !== childNode) { + newNode = newNode.updateImmediateChild(childName, newChildNode); + } + }); + return newNode; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A light-weight tree, traversable by path. Nodes can have both values and children. + * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty + * children. + */ +class Tree { + /** + * @param name - Optional name of the node. + * @param parent - Optional parent node. + * @param node - Optional node to wrap. + */ + constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) { + this.name = name; + this.parent = parent; + this.node = node; + } +} +/** + * Returns a sub-Tree for the given path. + * + * @param pathObj - Path to look up. + * @returns Tree for path. + */ +function treeSubTree(tree, pathObj) { + // TODO: Require pathObj to be Path? + let path = pathObj instanceof Path ? pathObj : new Path(pathObj); + let child = tree, next = pathGetFront(path); + while (next !== null) { + const childNode = safeGet(child.node.children, next) || { + children: {}, + childCount: 0 + }; + child = new Tree(next, child, childNode); + path = pathPopFront(path); + next = pathGetFront(path); + } + return child; +} +/** + * Returns the data associated with this tree node. + * + * @returns The data or null if no data exists. + */ +function treeGetValue(tree) { + return tree.node.value; +} +/** + * Sets data to this tree node. + * + * @param value - Value to set. + */ +function treeSetValue(tree, value) { + tree.node.value = value; + treeUpdateParents(tree); +} +/** + * @returns Whether the tree has any children. + */ +function treeHasChildren(tree) { + return tree.node.childCount > 0; +} +/** + * @returns Whether the tree is empty (no value or children). + */ +function treeIsEmpty(tree) { + return treeGetValue(tree) === undefined && !treeHasChildren(tree); +} +/** + * Calls action for each child of this tree node. + * + * @param action - Action to be called for each child. + */ +function treeForEachChild(tree, action) { + each(tree.node.children, (child, childTree) => { + action(new Tree(child, tree, childTree)); + }); +} +/** + * Does a depth-first traversal of this node's descendants, calling action for each one. + * + * @param action - Action to be called for each child. + * @param includeSelf - Whether to call action on this node as well. Defaults to + * false. + * @param childrenFirst - Whether to call action on children before calling it on + * parent. + */ +function treeForEachDescendant(tree, action, includeSelf, childrenFirst) { + if (includeSelf && !childrenFirst) { + action(tree); + } + treeForEachChild(tree, child => { + treeForEachDescendant(child, action, true, childrenFirst); + }); + if (includeSelf && childrenFirst) { + action(tree); + } +} +/** + * Calls action on each ancestor node. + * + * @param action - Action to be called on each parent; return + * true to abort. + * @param includeSelf - Whether to call action on this node as well. + * @returns true if the action callback returned true. + */ +function treeForEachAncestor(tree, action, includeSelf) { + let node = includeSelf ? tree : tree.parent; + while (node !== null) { + if (action(node)) { + return true; + } + node = node.parent; + } + return false; +} +/** + * @returns The path of this tree node, as a Path. + */ +function treeGetPath(tree) { + return new Path(tree.parent === null + ? tree.name + : treeGetPath(tree.parent) + '/' + tree.name); +} +/** + * Adds or removes this child from its parent based on whether it's empty or not. + */ +function treeUpdateParents(tree) { + if (tree.parent !== null) { + treeUpdateChild(tree.parent, tree.name, tree); + } +} +/** + * Adds or removes the passed child to this tree node, depending on whether it's empty. + * + * @param childName - The name of the child to update. + * @param child - The child to update. + */ +function treeUpdateChild(tree, childName, child) { + const childEmpty = treeIsEmpty(child); + const childExists = contains(tree.node.children, childName); + if (childEmpty && childExists) { + delete tree.node.children[childName]; + tree.node.childCount--; + treeUpdateParents(tree); + } + else if (!childEmpty && !childExists) { + tree.node.children[childName] = child.node; + tree.node.childCount++; + treeUpdateParents(tree); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * True for invalid Firebase keys + */ +const INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/; +/** + * True for invalid Firebase paths. + * Allows '/' in paths. + */ +const INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/; +/** + * Maximum number of characters to allow in leaf value + */ +const MAX_LEAF_SIZE_ = 10 * 1024 * 1024; +const isValidKey = function (key) { + return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key)); +}; +const isValidPathString = function (pathString) { + return (typeof pathString === 'string' && + pathString.length !== 0 && + !INVALID_PATH_REGEX_.test(pathString)); +}; +const isValidRootPathString = function (pathString) { + if (pathString) { + // Allow '/.info/' at the beginning. + pathString = pathString.replace(/^\/*\.info(\/|$)/, '/'); + } + return isValidPathString(pathString); +}; +const isValidPriority = function (priority) { + return (priority === null || + typeof priority === 'string' || + (typeof priority === 'number' && !isInvalidJSONNumber(priority)) || + (priority && + typeof priority === 'object' && + // eslint-disable-next-line @typescript-eslint/no-explicit-any + contains(priority, '.sv'))); +}; +/** + * Pre-validate a datum passed as an argument to Firebase function. + */ +const validateFirebaseDataArg = function (fnName, value, path, optional) { + if (optional && value === undefined) { + return; + } + validateFirebaseData(errorPrefix(fnName, 'value'), value, path); +}; +/** + * Validate a data object client-side before sending to server. + */ +const validateFirebaseData = function (errorPrefix, data, path_) { + const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_; + if (data === undefined) { + throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path)); + } + if (typeof data === 'function') { + throw new Error(errorPrefix + + 'contains a function ' + + validationPathToErrorString(path) + + ' with contents = ' + + data.toString()); + } + if (isInvalidJSONNumber(data)) { + throw new Error(errorPrefix + + 'contains ' + + data.toString() + + ' ' + + validationPathToErrorString(path)); + } + // Check max leaf size, but try to avoid the utf8 conversion if we can. + if (typeof data === 'string' && + data.length > MAX_LEAF_SIZE_ / 3 && + stringLength(data) > MAX_LEAF_SIZE_) { + throw new Error(errorPrefix + + 'contains a string greater than ' + + MAX_LEAF_SIZE_ + + ' utf8 bytes ' + + validationPathToErrorString(path) + + " ('" + + data.substring(0, 50) + + "...')"); + } + // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON + // to save extra walking of large objects. + if (data && typeof data === 'object') { + let hasDotValue = false; + let hasActualChild = false; + each(data, (key, value) => { + if (key === '.value') { + hasDotValue = true; + } + else if (key !== '.priority' && key !== '.sv') { + hasActualChild = true; + if (!isValidKey(key)) { + throw new Error(errorPrefix + + ' contains an invalid key (' + + key + + ') ' + + validationPathToErrorString(path) + + '. Keys must be non-empty strings ' + + 'and can\'t contain ".", "#", "$", "/", "[", or "]"'); + } + } + validationPathPush(path, key); + validateFirebaseData(errorPrefix, value, path); + validationPathPop(path); + }); + if (hasDotValue && hasActualChild) { + throw new Error(errorPrefix + + ' contains ".value" child ' + + validationPathToErrorString(path) + + ' in addition to actual children.'); + } + } +}; +/** + * Pre-validate paths passed in the firebase function. + */ +const validateFirebaseMergePaths = function (errorPrefix, mergePaths) { + let i, curPath; + for (i = 0; i < mergePaths.length; i++) { + curPath = mergePaths[i]; + const keys = pathSlice(curPath); + for (let j = 0; j < keys.length; j++) { + if (keys[j] === '.priority' && j === keys.length - 1) ; + else if (!isValidKey(keys[j])) { + throw new Error(errorPrefix + + 'contains an invalid key (' + + keys[j] + + ') in path ' + + curPath.toString() + + '. Keys must be non-empty strings ' + + 'and can\'t contain ".", "#", "$", "/", "[", or "]"'); + } + } + } + // Check that update keys are not descendants of each other. + // We rely on the property that sorting guarantees that ancestors come + // right before descendants. + mergePaths.sort(pathCompare); + let prevPath = null; + for (i = 0; i < mergePaths.length; i++) { + curPath = mergePaths[i]; + if (prevPath !== null && pathContains(prevPath, curPath)) { + throw new Error(errorPrefix + + 'contains a path ' + + prevPath.toString() + + ' that is ancestor of another path ' + + curPath.toString()); + } + prevPath = curPath; + } +}; +/** + * pre-validate an object passed as an argument to firebase function ( + * must be an object - e.g. for firebase.update()). + */ +const validateFirebaseMergeDataArg = function (fnName, data, path, optional) { + if (optional && data === undefined) { + return; + } + const errorPrefix$1 = errorPrefix(fnName, 'values'); + if (!(data && typeof data === 'object') || Array.isArray(data)) { + throw new Error(errorPrefix$1 + ' must be an object containing the children to replace.'); + } + const mergePaths = []; + each(data, (key, value) => { + const curPath = new Path(key); + validateFirebaseData(errorPrefix$1, value, pathChild(path, curPath)); + if (pathGetBack(curPath) === '.priority') { + if (!isValidPriority(value)) { + throw new Error(errorPrefix$1 + + "contains an invalid value for '" + + curPath.toString() + + "', which must be a valid " + + 'Firebase priority (a string, finite number, server value, or null).'); + } + } + mergePaths.push(curPath); + }); + validateFirebaseMergePaths(errorPrefix$1, mergePaths); +}; +const validatePriority = function (fnName, priority, optional) { + if (optional && priority === undefined) { + return; + } + if (isInvalidJSONNumber(priority)) { + throw new Error(errorPrefix(fnName, 'priority') + + 'is ' + + priority.toString() + + ', but must be a valid Firebase priority (a string, finite number, ' + + 'server value, or null).'); + } + // Special case to allow importing data with a .sv. + if (!isValidPriority(priority)) { + throw new Error(errorPrefix(fnName, 'priority') + + 'must be a valid Firebase priority ' + + '(a string, finite number, server value, or null).'); + } +}; +const validateKey = function (fnName, argumentName, key, optional) { + if (optional && key === undefined) { + return; + } + if (!isValidKey(key)) { + throw new Error(errorPrefix(fnName, argumentName) + + 'was an invalid key = "' + + key + + '". Firebase keys must be non-empty strings and ' + + 'can\'t contain ".", "#", "$", "/", "[", or "]").'); + } +}; +/** + * @internal + */ +const validatePathString = function (fnName, argumentName, pathString, optional) { + if (optional && pathString === undefined) { + return; + } + if (!isValidPathString(pathString)) { + throw new Error(errorPrefix(fnName, argumentName) + + 'was an invalid path = "' + + pathString + + '". Paths must be non-empty strings and ' + + 'can\'t contain ".", "#", "$", "[", or "]"'); + } +}; +const validateRootPathString = function (fnName, argumentName, pathString, optional) { + if (pathString) { + // Allow '/.info/' at the beginning. + pathString = pathString.replace(/^\/*\.info(\/|$)/, '/'); + } + validatePathString(fnName, argumentName, pathString, optional); +}; +/** + * @internal + */ +const validateWritablePath = function (fnName, path) { + if (pathGetFront(path) === '.info') { + throw new Error(fnName + " failed = Can't modify data under /.info/"); + } +}; +const validateUrl = function (fnName, parsedUrl) { + // TODO = Validate server better. + const pathString = parsedUrl.path.toString(); + if (!(typeof parsedUrl.repoInfo.host === 'string') || + parsedUrl.repoInfo.host.length === 0 || + (!isValidKey(parsedUrl.repoInfo.namespace) && + parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') || + (pathString.length !== 0 && !isValidRootPathString(pathString))) { + throw new Error(errorPrefix(fnName, 'url') + + 'must be a valid firebase URL and ' + + 'the path can\'t contain ".", "#", "$", "[", or "]".'); + } +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The event queue serves a few purposes: + * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more + * events being queued. + * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events, + * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call + * left off, ensuring that the events are still raised synchronously and in order. + * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued + * events are raised synchronously. + * + * NOTE: This can all go away if/when we move to async events. + * + */ +class EventQueue { + constructor() { + this.eventLists_ = []; + /** + * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes. + */ + this.recursionDepth_ = 0; + } +} +/** + * @param eventDataList - The new events to queue. + */ +function eventQueueQueueEvents(eventQueue, eventDataList) { + // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly. + let currList = null; + for (let i = 0; i < eventDataList.length; i++) { + const data = eventDataList[i]; + const path = data.getPath(); + if (currList !== null && !pathEquals(path, currList.path)) { + eventQueue.eventLists_.push(currList); + currList = null; + } + if (currList === null) { + currList = { events: [], path }; + } + currList.events.push(data); + } + if (currList) { + eventQueue.eventLists_.push(currList); + } +} +/** + * Queues the specified events and synchronously raises all events (including previously queued ones) + * for the specified path. + * + * It is assumed that the new events are all for the specified path. + * + * @param path - The path to raise events for. + * @param eventDataList - The new events to raise. + */ +function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) { + eventQueueQueueEvents(eventQueue, eventDataList); + eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path)); +} +/** + * Queues the specified events and synchronously raises all events (including previously queued ones) for + * locations related to the specified change path (i.e. all ancestors and descendants). + * + * It is assumed that the new events are all related (ancestor or descendant) to the specified path. + * + * @param changedPath - The path to raise events for. + * @param eventDataList - The events to raise + */ +function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) { + eventQueueQueueEvents(eventQueue, eventDataList); + eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) || + pathContains(changedPath, eventPath)); +} +function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) { + eventQueue.recursionDepth_++; + let sentAll = true; + for (let i = 0; i < eventQueue.eventLists_.length; i++) { + const eventList = eventQueue.eventLists_[i]; + if (eventList) { + const eventPath = eventList.path; + if (predicate(eventPath)) { + eventListRaise(eventQueue.eventLists_[i]); + eventQueue.eventLists_[i] = null; + } + else { + sentAll = false; + } + } + } + if (sentAll) { + eventQueue.eventLists_ = []; + } + eventQueue.recursionDepth_--; +} +/** + * Iterates through the list and raises each event + */ +function eventListRaise(eventList) { + for (let i = 0; i < eventList.events.length; i++) { + const eventData = eventList.events[i]; + if (eventData !== null) { + eventList.events[i] = null; + const eventFn = eventData.getEventRunner(); + if (logger) { + log('event: ' + eventData.toString()); + } + exceptionGuard(eventFn); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const INTERRUPT_REASON = 'repo_interrupt'; +/** + * If a transaction does not succeed after 25 retries, we abort it. Among other + * things this ensure that if there's ever a bug causing a mismatch between + * client / server hashes for some data, we won't retry indefinitely. + */ +const MAX_TRANSACTION_RETRIES = 25; +/** + * A connection to a single data repository. + */ +class Repo { + constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) { + this.repoInfo_ = repoInfo_; + this.forceRestClient_ = forceRestClient_; + this.authTokenProvider_ = authTokenProvider_; + this.appCheckProvider_ = appCheckProvider_; + this.dataUpdateCount = 0; + this.statsListener_ = null; + this.eventQueue_ = new EventQueue(); + this.nextWriteId_ = 1; + this.interceptServerDataCallback_ = null; + /** A list of data pieces and paths to be set when this client disconnects. */ + this.onDisconnect_ = newSparseSnapshotTree(); + /** Stores queues of outstanding transactions for Firebase locations. */ + this.transactionQueueTree_ = new Tree(); + // TODO: This should be @private but it's used by test_access.js and internal.js + this.persistentConnection_ = null; + // This key is intentionally not updated if RepoInfo is later changed or replaced + this.key = this.repoInfo_.toURLString(); + } + /** + * @returns The URL corresponding to the root of this Firebase. + */ + toString() { + return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host); + } +} +function repoStart(repo, appId, authOverride) { + repo.stats_ = statsManagerGetCollection(repo.repoInfo_); + if (repo.forceRestClient_ || beingCrawled()) { + repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => { + repoOnDataUpdate(repo, pathString, data, isMerge, tag); + }, repo.authTokenProvider_, repo.appCheckProvider_); + // Minor hack: Fire onConnect immediately, since there's no actual connection. + setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0); + } + else { + // Validate authOverride + if (typeof authOverride !== 'undefined' && authOverride !== null) { + if (typeof authOverride !== 'object') { + throw new Error('Only objects are supported for option databaseAuthVariableOverride'); + } + try { + stringify(authOverride); + } + catch (e) { + throw new Error('Invalid authOverride provided: ' + e); + } + } + repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => { + repoOnDataUpdate(repo, pathString, data, isMerge, tag); + }, (connectStatus) => { + repoOnConnectStatus(repo, connectStatus); + }, (updates) => { + repoOnServerInfoUpdate(repo, updates); + }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride); + repo.server_ = repo.persistentConnection_; + } + repo.authTokenProvider_.addTokenChangeListener(token => { + repo.server_.refreshAuthToken(token); + }); + repo.appCheckProvider_.addTokenChangeListener(result => { + repo.server_.refreshAppCheckToken(result.token); + }); + // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used), + // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created. + repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_)); + // Used for .info. + repo.infoData_ = new SnapshotHolder(); + repo.infoSyncTree_ = new SyncTree({ + startListening: (query, tag, currentHashFn, onComplete) => { + let infoEvents = []; + const node = repo.infoData_.getNode(query._path); + // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events + // on initial data... + if (!node.isEmpty()) { + infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node); + setTimeout(() => { + onComplete('ok'); + }, 0); + } + return infoEvents; + }, + stopListening: () => { } + }); + repoUpdateInfo(repo, 'connected', false); + repo.serverSyncTree_ = new SyncTree({ + startListening: (query, tag, currentHashFn, onComplete) => { + repo.server_.listen(query, currentHashFn, tag, (status, data) => { + const events = onComplete(status, data); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events); + }); + // No synchronous events for network-backed sync trees + return []; + }, + stopListening: (query, tag) => { + repo.server_.unlisten(query, tag); + } + }); +} +/** + * @returns The time in milliseconds, taking the server offset into account if we have one. + */ +function repoServerTime(repo) { + const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset')); + const offset = offsetNode.val() || 0; + return new Date().getTime() + offset; +} +/** + * Generate ServerValues using some variables from the repo object. + */ +function repoGenerateServerValues(repo) { + return generateWithValues({ + timestamp: repoServerTime(repo) + }); +} +/** + * Called by realtime when we get new messages from the server. + */ +function repoOnDataUpdate(repo, pathString, data, isMerge, tag) { + // For testing. + repo.dataUpdateCount++; + const path = new Path(pathString); + data = repo.interceptServerDataCallback_ + ? repo.interceptServerDataCallback_(pathString, data) + : data; + let events = []; + if (tag) { + if (isMerge) { + const taggedChildren = map(data, (raw) => nodeFromJSON(raw)); + events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag); + } + else { + const taggedSnap = nodeFromJSON(data); + events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag); + } + } + else if (isMerge) { + const changedChildren = map(data, (raw) => nodeFromJSON(raw)); + events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren); + } + else { + const snap = nodeFromJSON(data); + events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap); + } + let affectedPath = path; + if (events.length > 0) { + // Since we have a listener outstanding for each transaction, receiving any events + // is a proxy for some change having occurred. + affectedPath = repoRerunTransactions(repo, path); + } + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events); +} +function repoOnConnectStatus(repo, connectStatus) { + repoUpdateInfo(repo, 'connected', connectStatus); + if (connectStatus === false) { + repoRunOnDisconnectEvents(repo); + } +} +function repoOnServerInfoUpdate(repo, updates) { + each(updates, (key, value) => { + repoUpdateInfo(repo, key, value); + }); +} +function repoUpdateInfo(repo, pathString, value) { + const path = new Path('/.info/' + pathString); + const newNode = nodeFromJSON(value); + repo.infoData_.updateSnapshot(path, newNode); + const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); +} +function repoGetNextWriteId(repo) { + return repo.nextWriteId_++; +} +/** + * The purpose of `getValue` is to return the latest known value + * satisfying `query`. + * + * This method will first check for in-memory cached values + * belonging to active listeners. If they are found, such values + * are considered to be the most up-to-date. + * + * If the client is not connected, this method will wait until the + * repo has established a connection and then request the value for `query`. + * If the client is not able to retrieve the query result for another reason, + * it reports an error. + * + * @param query - The query to surface a value for. + */ +function repoGetValue(repo, query, eventRegistration) { + // Only active queries are cached. There is no persisted cache. + const cached = syncTreeGetServerValue(repo.serverSyncTree_, query); + if (cached != null) { + return Promise.resolve(cached); + } + return repo.server_.get(query).then(payload => { + const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex()); + /** + * Below we simulate the actions of an `onlyOnce` `onValue()` event where: + * Add an event registration, + * Update data at the path, + * Raise any events, + * Cleanup the SyncTree + */ + syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true); + let events; + if (query._queryParams.loadsAllData()) { + events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node); + } + else { + const tag = syncTreeTagForQuery(repo.serverSyncTree_, query); + events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag); + } + /* + * We need to raise events in the scenario where `get()` is called at a parent path, and + * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting + * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree + * and its corresponding serverCache, including the child location where `onValue` is called. Then, + * `onValue` will receive the event from the server, but look at the syncTree and see that the data received + * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired. + * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and + * ensure the corresponding child events will get fired. + */ + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events); + syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true); + return node; + }, err => { + repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err); + return Promise.reject(new Error(err)); + }); +} +function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) { + repoLog(repo, 'set', { + path: path.toString(), + value: newVal, + priority: newPriority + }); + // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or + // (b) store unresolved paths on JSON parse + const serverValues = repoGenerateServerValues(repo); + const newNodeUnresolved = nodeFromJSON(newVal, newPriority); + const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path); + const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues); + const writeId = repoGetNextWriteId(repo); + const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true); + eventQueueQueueEvents(repo.eventQueue_, events); + repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => { + const success = status === 'ok'; + if (!success) { + warn('set at ' + path + ' failed: ' + status); + } + const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents); + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); + const affectedPath = repoAbortTransactions(repo, path); + repoRerunTransactions(repo, affectedPath); + // We queued the events above, so just flush the queue here + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []); +} +function repoUpdate(repo, path, childrenToMerge, onComplete) { + repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge }); + // Start with our existing data and merge each child into it. + let empty = true; + const serverValues = repoGenerateServerValues(repo); + const changedChildren = {}; + each(childrenToMerge, (changedKey, changedValue) => { + empty = false; + changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues); + }); + if (!empty) { + const writeId = repoGetNextWriteId(repo); + const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId); + eventQueueQueueEvents(repo.eventQueue_, events); + repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => { + const success = status === 'ok'; + if (!success) { + warn('update at ' + path + ' failed: ' + status); + } + const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success); + const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path; + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents); + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); + each(childrenToMerge, (changedPath) => { + const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath)); + repoRerunTransactions(repo, affectedPath); + }); + // We queued the events above, so just flush the queue here + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []); + } + else { + log("update() called with empty data. Don't do anything."); + repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined); + } +} +/** + * Applies all of the changes stored up in the onDisconnect_ tree. + */ +function repoRunOnDisconnectEvents(repo) { + repoLog(repo, 'onDisconnectEvents'); + const serverValues = repoGenerateServerValues(repo); + const resolvedOnDisconnectTree = newSparseSnapshotTree(); + sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => { + const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues); + sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved); + }); + let events = []; + sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => { + events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap)); + const affectedPath = repoAbortTransactions(repo, path); + repoRerunTransactions(repo, affectedPath); + }); + repo.onDisconnect_ = newSparseSnapshotTree(); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events); +} +function repoOnDisconnectCancel(repo, path, onComplete) { + repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => { + if (status === 'ok') { + sparseSnapshotTreeForget(repo.onDisconnect_, path); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoOnDisconnectSet(repo, path, value, onComplete) { + const newNode = nodeFromJSON(value); + repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => { + if (status === 'ok') { + sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) { + const newNode = nodeFromJSON(value, priority); + repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => { + if (status === 'ok') { + sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) { + if (isEmpty(childrenToMerge)) { + log("onDisconnect().update() called with empty data. Don't do anything."); + repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined); + return; + } + repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => { + if (status === 'ok') { + each(childrenToMerge, (childName, childNode) => { + const newChildNode = nodeFromJSON(childNode); + sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode); + }); + } + repoCallOnCompleteCallback(repo, onComplete, status, errorReason); + }); +} +function repoAddEventCallbackForQuery(repo, query, eventRegistration) { + let events; + if (pathGetFront(query._path) === '.info') { + events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration); + } + else { + events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration); + } + eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events); +} +function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) { + // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof + // a little bit by handling the return values anyways. + let events; + if (pathGetFront(query._path) === '.info') { + events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration); + } + else { + events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration); + } + eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events); +} +function repoInterrupt(repo) { + if (repo.persistentConnection_) { + repo.persistentConnection_.interrupt(INTERRUPT_REASON); + } +} +function repoResume(repo) { + if (repo.persistentConnection_) { + repo.persistentConnection_.resume(INTERRUPT_REASON); + } +} +function repoLog(repo, ...varArgs) { + let prefix = ''; + if (repo.persistentConnection_) { + prefix = repo.persistentConnection_.id + ':'; + } + log(prefix, ...varArgs); +} +function repoCallOnCompleteCallback(repo, callback, status, errorReason) { + if (callback) { + exceptionGuard(() => { + if (status === 'ok') { + callback(null); + } + else { + const code = (status || 'error').toUpperCase(); + let message = code; + if (errorReason) { + message += ': ' + errorReason; + } + const error = new Error(message); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error.code = code; + callback(error); + } + }); + } +} +/** + * Creates a new transaction, adds it to the transactions we're tracking, and + * sends it to the server if possible. + * + * @param path - Path at which to do transaction. + * @param transactionUpdate - Update callback. + * @param onComplete - Completion callback. + * @param unwatcher - Function that will be called when the transaction no longer + * need data updates for `path`. + * @param applyLocally - Whether or not to make intermediate results visible + */ +function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) { + repoLog(repo, 'transaction on ' + path); + // Initialize transaction. + const transaction = { + path, + update: transactionUpdate, + onComplete, + // One of TransactionStatus enums. + status: null, + // Used when combining transactions at different locations to figure out + // which one goes first. + order: LUIDGenerator(), + // Whether to raise local events for this transaction. + applyLocally, + // Count of how many times we've retried the transaction. + retryCount: 0, + // Function to call to clean up our .on() listener. + unwatcher, + // Stores why a transaction was aborted. + abortReason: null, + currentWriteId: null, + currentInputSnapshot: null, + currentOutputSnapshotRaw: null, + currentOutputSnapshotResolved: null + }; + // Run transaction initially. + const currentState = repoGetLatestState(repo, path, undefined); + transaction.currentInputSnapshot = currentState; + const newVal = transaction.update(currentState.val()); + if (newVal === undefined) { + // Abort transaction. + transaction.unwatcher(); + transaction.currentOutputSnapshotRaw = null; + transaction.currentOutputSnapshotResolved = null; + if (transaction.onComplete) { + transaction.onComplete(null, false, transaction.currentInputSnapshot); + } + } + else { + validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path); + // Mark as run and add to our queue. + transaction.status = 0 /* TransactionStatus.RUN */; + const queueNode = treeSubTree(repo.transactionQueueTree_, path); + const nodeQueue = treeGetValue(queueNode) || []; + nodeQueue.push(transaction); + treeSetValue(queueNode, nodeQueue); + // Update visibleData and raise events + // Note: We intentionally raise events after updating all of our + // transaction state, since the user could start new transactions from the + // event callbacks. + let priorityForNode; + if (typeof newVal === 'object' && + newVal !== null && + contains(newVal, '.priority')) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + priorityForNode = safeGet(newVal, '.priority'); + assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' + + 'Priority must be a valid string, finite number, server value, or null.'); + } + else { + const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) || + ChildrenNode.EMPTY_NODE; + priorityForNode = currentNode.getPriority().val(); + } + const serverValues = repoGenerateServerValues(repo); + const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode); + const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues); + transaction.currentOutputSnapshotRaw = newNodeUnresolved; + transaction.currentOutputSnapshotResolved = newNode; + transaction.currentWriteId = repoGetNextWriteId(repo); + const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); + repoSendReadyTransactions(repo, repo.transactionQueueTree_); + } +} +/** + * @param excludeSets - A specific set to exclude + */ +function repoGetLatestState(repo, path, excludeSets) { + return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) || + ChildrenNode.EMPTY_NODE); +} +/** + * Sends any already-run transactions that aren't waiting for outstanding + * transactions to complete. + * + * Externally it's called with no arguments, but it calls itself recursively + * with a particular transactionQueueTree node to recurse through the tree. + * + * @param node - transactionQueueTree node to start at. + */ +function repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) { + // Before recursing, make sure any completed transactions are removed. + if (!node) { + repoPruneCompletedTransactionsBelowNode(repo, node); + } + if (treeGetValue(node)) { + const queue = repoBuildTransactionQueue(repo, node); + assert(queue.length > 0, 'Sending zero length transaction queue'); + const allRun = queue.every((transaction) => transaction.status === 0 /* TransactionStatus.RUN */); + // If they're all run (and not sent), we can send them. Else, we must wait. + if (allRun) { + repoSendTransactionQueue(repo, treeGetPath(node), queue); + } + } + else if (treeHasChildren(node)) { + treeForEachChild(node, childNode => { + repoSendReadyTransactions(repo, childNode); + }); + } +} +/** + * Given a list of run transactions, send them to the server and then handle + * the result (success or failure). + * + * @param path - The location of the queue. + * @param queue - Queue of transactions under the specified location. + */ +function repoSendTransactionQueue(repo, path, queue) { + // Mark transactions as sent and increment retry count! + const setsToIgnore = queue.map(txn => { + return txn.currentWriteId; + }); + const latestState = repoGetLatestState(repo, path, setsToIgnore); + let snapToSend = latestState; + const latestHash = latestState.hash(); + for (let i = 0; i < queue.length; i++) { + const txn = queue[i]; + assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.'); + txn.status = 1 /* TransactionStatus.SENT */; + txn.retryCount++; + const relativePath = newRelativePath(path, txn.path); + // If we've gotten to this point, the output snapshot must be defined. + snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw); + } + const dataToSend = snapToSend.val(true); + const pathToSend = path; + // Send the put. + repo.server_.put(pathToSend.toString(), dataToSend, (status) => { + repoLog(repo, 'transaction put response', { + path: pathToSend.toString(), + status + }); + let events = []; + if (status === 'ok') { + // Queue up the callbacks and fire them after cleaning up all of our + // transaction state, since the callback could trigger more + // transactions or sets. + const callbacks = []; + for (let i = 0; i < queue.length; i++) { + queue[i].status = 2 /* TransactionStatus.COMPLETED */; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId)); + if (queue[i].onComplete) { + // We never unset the output snapshot, and given that this + // transaction is complete, it should be set + callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved)); + } + queue[i].unwatcher(); + } + // Now remove the completed transactions. + repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path)); + // There may be pending transactions that we can now send. + repoSendReadyTransactions(repo, repo.transactionQueueTree_); + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); + // Finally, trigger onComplete callbacks. + for (let i = 0; i < callbacks.length; i++) { + exceptionGuard(callbacks[i]); + } + } + else { + // transactions are no longer sent. Update their status appropriately. + if (status === 'datastale') { + for (let i = 0; i < queue.length; i++) { + if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) { + queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */; + } + else { + queue[i].status = 0 /* TransactionStatus.RUN */; + } + } + } + else { + warn('transaction at ' + pathToSend.toString() + ' failed: ' + status); + for (let i = 0; i < queue.length; i++) { + queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */; + queue[i].abortReason = status; + } + } + repoRerunTransactions(repo, path); + } + }, latestHash); +} +/** + * Finds all transactions dependent on the data at changedPath and reruns them. + * + * Should be called any time cached data changes. + * + * Return the highest path that was affected by rerunning transactions. This + * is the path at which events need to be raised for. + * + * @param changedPath - The path in mergedData that changed. + * @returns The rootmost path that was affected by rerunning transactions. + */ +function repoRerunTransactions(repo, changedPath) { + const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath); + const path = treeGetPath(rootMostTransactionNode); + const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode); + repoRerunTransactionQueue(repo, queue, path); + return path; +} +/** + * Does all the work of rerunning transactions (as well as cleans up aborted + * transactions and whatnot). + * + * @param queue - The queue of transactions to run. + * @param path - The path the queue is for. + */ +function repoRerunTransactionQueue(repo, queue, path) { + if (queue.length === 0) { + return; // Nothing to do! + } + // Queue up the callbacks and fire them after cleaning up all of our + // transaction state, since the callback could trigger more transactions or + // sets. + const callbacks = []; + let events = []; + // Ignore all of the sets we're going to re-run. + const txnsToRerun = queue.filter(q => { + return q.status === 0 /* TransactionStatus.RUN */; + }); + const setsToIgnore = txnsToRerun.map(q => { + return q.currentWriteId; + }); + for (let i = 0; i < queue.length; i++) { + const transaction = queue[i]; + const relativePath = newRelativePath(path, transaction.path); + let abortTransaction = false, abortReason; + assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.'); + if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) { + abortTransaction = true; + abortReason = transaction.abortReason; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true)); + } + else if (transaction.status === 0 /* TransactionStatus.RUN */) { + if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) { + abortTransaction = true; + abortReason = 'maxretry'; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true)); + } + else { + // This code reruns a transaction + const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore); + transaction.currentInputSnapshot = currentNode; + const newData = queue[i].update(currentNode.val()); + if (newData !== undefined) { + validateFirebaseData('transaction failed: Data returned ', newData, transaction.path); + let newDataNode = nodeFromJSON(newData); + const hasExplicitPriority = typeof newData === 'object' && + newData != null && + contains(newData, '.priority'); + if (!hasExplicitPriority) { + // Keep the old priority if there wasn't a priority explicitly specified. + newDataNode = newDataNode.updatePriority(currentNode.getPriority()); + } + const oldWriteId = transaction.currentWriteId; + const serverValues = repoGenerateServerValues(repo); + const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues); + transaction.currentOutputSnapshotRaw = newDataNode; + transaction.currentOutputSnapshotResolved = newNodeResolved; + transaction.currentWriteId = repoGetNextWriteId(repo); + // Mutates setsToIgnore in place + setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1); + events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally)); + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true)); + } + else { + abortTransaction = true; + abortReason = 'nodata'; + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true)); + } + } + } + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events); + events = []; + if (abortTransaction) { + // Abort. + queue[i].status = 2 /* TransactionStatus.COMPLETED */; + // Removing a listener can trigger pruning which can muck with + // mergedData/visibleData (as it prunes data). So defer the unwatcher + // until we're done. + (function (unwatcher) { + setTimeout(unwatcher, Math.floor(0)); + })(queue[i].unwatcher); + if (queue[i].onComplete) { + if (abortReason === 'nodata') { + callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot)); + } + else { + callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null)); + } + } + } + } + // Clean up completed transactions. + repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_); + // Now fire callbacks, now that we're in a good, known state. + for (let i = 0; i < callbacks.length; i++) { + exceptionGuard(callbacks[i]); + } + // Try to send the transaction result to the server. + repoSendReadyTransactions(repo, repo.transactionQueueTree_); +} +/** + * Returns the rootmost ancestor node of the specified path that has a pending + * transaction on it, or just returns the node for the given path if there are + * no pending transactions on any ancestor. + * + * @param path - The location to start at. + * @returns The rootmost node with a transaction. + */ +function repoGetAncestorTransactionNode(repo, path) { + let front; + // Start at the root and walk deeper into the tree towards path until we + // find a node with pending transactions. + let transactionNode = repo.transactionQueueTree_; + front = pathGetFront(path); + while (front !== null && treeGetValue(transactionNode) === undefined) { + transactionNode = treeSubTree(transactionNode, front); + path = pathPopFront(path); + front = pathGetFront(path); + } + return transactionNode; +} +/** + * Builds the queue of all transactions at or below the specified + * transactionNode. + * + * @param transactionNode + * @returns The generated queue. + */ +function repoBuildTransactionQueue(repo, transactionNode) { + // Walk any child transaction queues and aggregate them into a single queue. + const transactionQueue = []; + repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue); + // Sort them by the order the transactions were created. + transactionQueue.sort((a, b) => a.order - b.order); + return transactionQueue; +} +function repoAggregateTransactionQueuesForNode(repo, node, queue) { + const nodeQueue = treeGetValue(node); + if (nodeQueue) { + for (let i = 0; i < nodeQueue.length; i++) { + queue.push(nodeQueue[i]); + } + } + treeForEachChild(node, child => { + repoAggregateTransactionQueuesForNode(repo, child, queue); + }); +} +/** + * Remove COMPLETED transactions at or below this node in the transactionQueueTree_. + */ +function repoPruneCompletedTransactionsBelowNode(repo, node) { + const queue = treeGetValue(node); + if (queue) { + let to = 0; + for (let from = 0; from < queue.length; from++) { + if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) { + queue[to] = queue[from]; + to++; + } + } + queue.length = to; + treeSetValue(node, queue.length > 0 ? queue : undefined); + } + treeForEachChild(node, childNode => { + repoPruneCompletedTransactionsBelowNode(repo, childNode); + }); +} +/** + * Aborts all transactions on ancestors or descendants of the specified path. + * Called when doing a set() or update() since we consider them incompatible + * with transactions. + * + * @param path - Path for which we want to abort related transactions. + */ +function repoAbortTransactions(repo, path) { + const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path)); + const transactionNode = treeSubTree(repo.transactionQueueTree_, path); + treeForEachAncestor(transactionNode, (node) => { + repoAbortTransactionsOnNode(repo, node); + }); + repoAbortTransactionsOnNode(repo, transactionNode); + treeForEachDescendant(transactionNode, (node) => { + repoAbortTransactionsOnNode(repo, node); + }); + return affectedPath; +} +/** + * Abort transactions stored in this transaction queue node. + * + * @param node - Node to abort transactions for. + */ +function repoAbortTransactionsOnNode(repo, node) { + const queue = treeGetValue(node); + if (queue) { + // Queue up the callbacks and fire them after cleaning up all of our + // transaction state, since the callback could trigger more transactions + // or sets. + const callbacks = []; + // Go through queue. Any already-sent transactions must be marked for + // abort, while the unsent ones can be immediately aborted and removed. + let events = []; + let lastSent = -1; + for (let i = 0; i < queue.length; i++) { + if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ; + else if (queue[i].status === 1 /* TransactionStatus.SENT */) { + assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.'); + lastSent = i; + // Mark transaction for abort when it comes back. + queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */; + queue[i].abortReason = 'set'; + } + else { + assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort'); + // We can abort it immediately. + queue[i].unwatcher(); + events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true)); + if (queue[i].onComplete) { + callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null)); + } + } + } + if (lastSent === -1) { + // We're not waiting for any sent transactions. We can clear the queue. + treeSetValue(node, undefined); + } + else { + // Remove the transactions we aborted. + queue.length = lastSent + 1; + } + // Now fire the callbacks. + eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events); + for (let i = 0; i < callbacks.length; i++) { + exceptionGuard(callbacks[i]); + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function decodePath(pathString) { + let pathStringDecoded = ''; + const pieces = pathString.split('/'); + for (let i = 0; i < pieces.length; i++) { + if (pieces[i].length > 0) { + let piece = pieces[i]; + try { + piece = decodeURIComponent(piece.replace(/\+/g, ' ')); + } + catch (e) { } + pathStringDecoded += '/' + piece; + } + } + return pathStringDecoded; +} +/** + * @returns key value hash + */ +function decodeQuery(queryString) { + const results = {}; + if (queryString.charAt(0) === '?') { + queryString = queryString.substring(1); + } + for (const segment of queryString.split('&')) { + if (segment.length === 0) { + continue; + } + const kv = segment.split('='); + if (kv.length === 2) { + results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]); + } + else { + warn(`Invalid query segment '${segment}' in query '${queryString}'`); + } + } + return results; +} +const parseRepoInfo = function (dataURL, nodeAdmin) { + const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace; + if (parsedUrl.domain === 'firebase.com') { + fatal(parsedUrl.host + + ' is no longer supported. ' + + 'Please use .firebaseio.com instead'); + } + // Catch common error of uninitialized namespace value. + if ((!namespace || namespace === 'undefined') && + parsedUrl.domain !== 'localhost') { + fatal('Cannot parse Firebase url. Please use https://.firebaseio.com'); + } + if (!parsedUrl.secure) { + warnIfPageIsSecure(); + } + const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss'; + return { + repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin, + /*persistenceKey=*/ '', + /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain), + path: new Path(parsedUrl.pathString) + }; +}; +const parseDatabaseURL = function (dataURL) { + // Default to empty strings in the event of a malformed string. + let host = '', domain = '', subdomain = '', pathString = '', namespace = ''; + // Always default to SSL, unless otherwise specified. + let secure = true, scheme = 'https', port = 443; + // Don't do any validation here. The caller is responsible for validating the result of parsing. + if (typeof dataURL === 'string') { + // Parse scheme. + let colonInd = dataURL.indexOf('//'); + if (colonInd >= 0) { + scheme = dataURL.substring(0, colonInd - 1); + dataURL = dataURL.substring(colonInd + 2); + } + // Parse host, path, and query string. + let slashInd = dataURL.indexOf('/'); + if (slashInd === -1) { + slashInd = dataURL.length; + } + let questionMarkInd = dataURL.indexOf('?'); + if (questionMarkInd === -1) { + questionMarkInd = dataURL.length; + } + host = dataURL.substring(0, Math.min(slashInd, questionMarkInd)); + if (slashInd < questionMarkInd) { + // For pathString, questionMarkInd will always come after slashInd + pathString = decodePath(dataURL.substring(slashInd, questionMarkInd)); + } + const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd))); + // If we have a port, use scheme for determining if it's secure. + colonInd = host.indexOf(':'); + if (colonInd >= 0) { + secure = scheme === 'https' || scheme === 'wss'; + port = parseInt(host.substring(colonInd + 1), 10); + } + else { + colonInd = host.length; + } + const hostWithoutPort = host.slice(0, colonInd); + if (hostWithoutPort.toLowerCase() === 'localhost') { + domain = 'localhost'; + } + else if (hostWithoutPort.split('.').length <= 2) { + domain = hostWithoutPort; + } + else { + // Interpret the subdomain of a 3 or more component URL as the namespace name. + const dotInd = host.indexOf('.'); + subdomain = host.substring(0, dotInd).toLowerCase(); + domain = host.substring(dotInd + 1); + // Normalize namespaces to lowercase to share storage / connection. + namespace = subdomain; + } + // Always treat the value of the `ns` as the namespace name if it is present. + if ('ns' in queryParams) { + namespace = queryParams['ns']; + } + } + return { + host, + port, + domain, + subdomain, + secure, + scheme, + pathString, + namespace + }; +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Modeled after base64 web-safe chars, but ordered by ASCII. +const PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'; +/** + * Fancy ID generator that creates 20-character string identifiers with the + * following properties: + * + * 1. They're based on timestamp so that they sort *after* any existing ids. + * 2. They contain 72-bits of random data after the timestamp so that IDs won't + * collide with other clients' IDs. + * 3. They sort *lexicographically* (so the timestamp is converted to characters + * that will sort properly). + * 4. They're monotonically increasing. Even if you generate more than one in + * the same timestamp, the latter ones will sort after the former ones. We do + * this by using the previous random bits but "incrementing" them by 1 (only + * in the case of a timestamp collision). + */ +const nextPushId = (function () { + // Timestamp of last push, used to prevent local collisions if you push twice + // in one ms. + let lastPushTime = 0; + // We generate 72-bits of randomness which get turned into 12 characters and + // appended to the timestamp to prevent collisions with other clients. We + // store the last characters we generated because in the event of a collision, + // we'll use those same characters except "incremented" by one. + const lastRandChars = []; + return function (now) { + const duplicateTime = now === lastPushTime; + lastPushTime = now; + let i; + const timeStampChars = new Array(8); + for (i = 7; i >= 0; i--) { + timeStampChars[i] = PUSH_CHARS.charAt(now % 64); + // NOTE: Can't use << here because javascript will convert to int and lose + // the upper bits. + now = Math.floor(now / 64); + } + assert(now === 0, 'Cannot push at time == 0'); + let id = timeStampChars.join(''); + if (!duplicateTime) { + for (i = 0; i < 12; i++) { + lastRandChars[i] = Math.floor(Math.random() * 64); + } + } + else { + // If the timestamp hasn't changed since last push, use the same random + // number, except incremented by 1. + for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) { + lastRandChars[i] = 0; + } + lastRandChars[i]++; + } + for (i = 0; i < 12; i++) { + id += PUSH_CHARS.charAt(lastRandChars[i]); + } + assert(id.length === 20, 'nextPushId: Length should be 20.'); + return id; + }; +})(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Encapsulates the data needed to raise an event + */ +class DataEvent { + /** + * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed + * @param eventRegistration - The function to call to with the event data. User provided + * @param snapshot - The data backing the event + * @param prevName - Optional, the name of the previous child for child_* events. + */ + constructor(eventType, eventRegistration, snapshot, prevName) { + this.eventType = eventType; + this.eventRegistration = eventRegistration; + this.snapshot = snapshot; + this.prevName = prevName; + } + getPath() { + const ref = this.snapshot.ref; + if (this.eventType === 'value') { + return ref._path; + } + else { + return ref.parent._path; + } + } + getEventType() { + return this.eventType; + } + getEventRunner() { + return this.eventRegistration.getEventRunner(this); + } + toString() { + return (this.getPath().toString() + + ':' + + this.eventType + + ':' + + stringify(this.snapshot.exportVal())); + } +} +class CancelEvent { + constructor(eventRegistration, error, path) { + this.eventRegistration = eventRegistration; + this.error = error; + this.path = path; + } + getPath() { + return this.path; + } + getEventType() { + return 'cancel'; + } + getEventRunner() { + return this.eventRegistration.getEventRunner(this); + } + toString() { + return this.path.toString() + ':cancel'; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A wrapper class that converts events from the database@exp SDK to the legacy + * Database SDK. Events are not converted directly as event registration relies + * on reference comparison of the original user callback (see `matches()`) and + * relies on equality of the legacy SDK's `context` object. + */ +class CallbackContext { + constructor(snapshotCallback, cancelCallback) { + this.snapshotCallback = snapshotCallback; + this.cancelCallback = cancelCallback; + } + onValue(expDataSnapshot, previousChildName) { + this.snapshotCallback.call(null, expDataSnapshot, previousChildName); + } + onCancel(error) { + assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback'); + return this.cancelCallback.call(null, error); + } + get hasCancelCallback() { + return !!this.cancelCallback; + } + matches(other) { + return (this.snapshotCallback === other.snapshotCallback || + (this.snapshotCallback.userCallback !== undefined && + this.snapshotCallback.userCallback === + other.snapshotCallback.userCallback && + this.snapshotCallback.context === other.snapshotCallback.context)); + } +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The `onDisconnect` class allows you to write or clear data when your client + * disconnects from the Database server. These updates occur whether your + * client disconnects cleanly or not, so you can rely on them to clean up data + * even if a connection is dropped or a client crashes. + * + * The `onDisconnect` class is most commonly used to manage presence in + * applications where it is useful to detect how many clients are connected and + * when other clients disconnect. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * To avoid problems when a connection is dropped before the requests can be + * transferred to the Database server, these functions should be called before + * writing any data. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time you reconnect. + */ +class OnDisconnect { + /** @hideconstructor */ + constructor(_repo, _path) { + this._repo = _repo; + this._path = _path; + } + /** + * Cancels all previously queued `onDisconnect()` set or update events for this + * location and all children. + * + * If a write has been queued for this location via a `set()` or `update()` at a + * parent location, the write at this location will be canceled, though writes + * to sibling locations will still occur. + * + * @returns Resolves when synchronization to the server is complete. + */ + cancel() { + const deferred = new Deferred(); + repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Ensures the data at this location is deleted when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + * + * @returns Resolves when synchronization to the server is complete. + */ + remove() { + validateWritablePath('OnDisconnect.remove', this._path); + const deferred = new Deferred(); + repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Ensures the data at this location is set to the specified value when the + * client is disconnected (due to closing the browser, navigating to a new page, + * or network issues). + * + * `set()` is especially useful for implementing "presence" systems, where a + * value should be changed or cleared when a user disconnects so that they + * appear "offline" to other users. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time. + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + set(value) { + validateWritablePath('OnDisconnect.set', this._path); + validateFirebaseDataArg('OnDisconnect.set', value, this._path, false); + const deferred = new Deferred(); + repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Ensures the data at this location is set to the specified value and priority + * when the client is disconnected (due to closing the browser, navigating to a + * new page, or network issues). + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + setWithPriority(value, priority) { + validateWritablePath('OnDisconnect.setWithPriority', this._path); + validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false); + validatePriority('OnDisconnect.setWithPriority', priority, false); + const deferred = new Deferred(); + repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { })); + return deferred.promise; + } + /** + * Writes multiple values at this location when the client is disconnected (due + * to closing the browser, navigating to a new page, or network issues). + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, "name/first") + * from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * @param values - Object containing multiple values. + * @returns Resolves when synchronization to the Database is complete. + */ + update(values) { + validateWritablePath('OnDisconnect.update', this._path); + validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false); + const deferred = new Deferred(); + repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { })); + return deferred.promise; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ +class QueryImpl { + /** + * @hideconstructor + */ + constructor(_repo, _path, _queryParams, _orderByCalled) { + this._repo = _repo; + this._path = _path; + this._queryParams = _queryParams; + this._orderByCalled = _orderByCalled; + } + get key() { + if (pathIsEmpty(this._path)) { + return null; + } + else { + return pathGetBack(this._path); + } + } + get ref() { + return new ReferenceImpl(this._repo, this._path); + } + get _queryIdentifier() { + const obj = queryParamsGetQueryObject(this._queryParams); + const id = ObjectToUniqueKey(obj); + return id === '{}' ? 'default' : id; + } + /** + * An object representation of the query parameters used by this Query. + */ + get _queryObject() { + return queryParamsGetQueryObject(this._queryParams); + } + isEqual(other) { + other = getModularInstance(other); + if (!(other instanceof QueryImpl)) { + return false; + } + const sameRepo = this._repo === other._repo; + const samePath = pathEquals(this._path, other._path); + const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier; + return sameRepo && samePath && sameQueryIdentifier; + } + toJSON() { + return this.toString(); + } + toString() { + return this._repo.toString() + pathToUrlEncodedString(this._path); + } +} +/** + * Validates that no other order by call has been made + */ +function validateNoPreviousOrderByCall(query, fnName) { + if (query._orderByCalled === true) { + throw new Error(fnName + ": You can't combine multiple orderBy calls."); + } +} +/** + * Validates start/end values for queries. + */ +function validateQueryEndpoints(params) { + let startNode = null; + let endNode = null; + if (params.hasStart()) { + startNode = params.getIndexStartValue(); + } + if (params.hasEnd()) { + endNode = params.getIndexEndValue(); + } + if (params.getIndex() === KEY_INDEX) { + const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' + + 'startAt(), endAt(), or equalTo().'; + const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' + + 'endAt(), endBefore(), or equalTo() must be a string.'; + if (params.hasStart()) { + const startName = params.getIndexStartName(); + if (startName !== MIN_NAME) { + throw new Error(tooManyArgsError); + } + else if (typeof startNode !== 'string') { + throw new Error(wrongArgTypeError); + } + } + if (params.hasEnd()) { + const endName = params.getIndexEndName(); + if (endName !== MAX_NAME) { + throw new Error(tooManyArgsError); + } + else if (typeof endNode !== 'string') { + throw new Error(wrongArgTypeError); + } + } + } + else if (params.getIndex() === PRIORITY_INDEX) { + if ((startNode != null && !isValidPriority(startNode)) || + (endNode != null && !isValidPriority(endNode))) { + throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' + + 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' + + '(null, a number, or a string).'); + } + } + else { + assert(params.getIndex() instanceof PathIndex || + params.getIndex() === VALUE_INDEX, 'unknown index type.'); + if ((startNode != null && typeof startNode === 'object') || + (endNode != null && typeof endNode === 'object')) { + throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' + + 'equalTo() cannot be an object.'); + } + } +} +/** + * Validates that limit* has been called with the correct combination of parameters + */ +function validateLimit(params) { + if (params.hasStart() && + params.hasEnd() && + params.hasLimit() && + !params.hasAnchoredLimit()) { + throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " + + 'limitToFirst() or limitToLast() instead.'); + } +} +/** + * @internal + */ +class ReferenceImpl extends QueryImpl { + /** @hideconstructor */ + constructor(repo, path) { + super(repo, path, new QueryParams(), false); + } + get parent() { + const parentPath = pathParent(this._path); + return parentPath === null + ? null + : new ReferenceImpl(this._repo, parentPath); + } + get root() { + let ref = this; + while (ref.parent !== null) { + ref = ref.parent; + } + return ref; + } +} +/** + * A `DataSnapshot` contains data from a Database location. + * + * Any time you read data from the Database, you receive the data as a + * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach + * with `on()` or `once()`. You can extract the contents of the snapshot as a + * JavaScript object by calling the `val()` method. Alternatively, you can + * traverse into the snapshot by calling `child()` to return child snapshots + * (which you could then call `val()` on). + * + * A `DataSnapshot` is an efficiently generated, immutable copy of the data at + * a Database location. It cannot be modified and will never change (to modify + * data, you always call the `set()` method on a `Reference` directly). + */ +class DataSnapshot { + /** + * @param _node - A SnapshotNode to wrap. + * @param ref - The location this snapshot came from. + * @param _index - The iteration order for this snapshot + * @hideconstructor + */ + constructor(_node, + /** + * The location of this DataSnapshot. + */ + ref, _index) { + this._node = _node; + this.ref = ref; + this._index = _index; + } + /** + * Gets the priority value of the data in this `DataSnapshot`. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data} + * ). + */ + get priority() { + // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY) + return this._node.getPriority().val(); + } + /** + * The key (last part of the path) of the location of this `DataSnapshot`. + * + * The last token in a Database location is considered its key. For example, + * "ada" is the key for the /users/ada/ node. Accessing the key on any + * `DataSnapshot` will return the key for the location that generated it. + * However, accessing the key on the root URL of a Database will return + * `null`. + */ + get key() { + return this.ref.key; + } + /** Returns the number of child properties of this `DataSnapshot`. */ + get size() { + return this._node.numChildren(); + } + /** + * Gets another `DataSnapshot` for the location at the specified relative path. + * + * Passing a relative path to the `child()` method of a DataSnapshot returns + * another `DataSnapshot` for the location at the specified relative path. The + * relative path can either be a simple child name (for example, "ada") or a + * deeper, slash-separated path (for example, "ada/name/first"). If the child + * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot` + * whose value is `null`) is returned. + * + * @param path - A relative path to the location of child data. + */ + child(path) { + const childPath = new Path(path); + const childRef = child(this.ref, path); + return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX); + } + /** + * Returns true if this `DataSnapshot` contains any data. It is slightly more + * efficient than using `snapshot.val() !== null`. + */ + exists() { + return !this._node.isEmpty(); + } + /** + * Exports the entire contents of the DataSnapshot as a JavaScript object. + * + * The `exportVal()` method is similar to `val()`, except priority information + * is included (if available), making it suitable for backing up your data. + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + exportVal() { + return this._node.val(true); + } + /** + * Enumerates the top-level children in the `IteratedDataSnapshot`. + * + * Because of the way JavaScript objects work, the ordering of data in the + * JavaScript object returned by `val()` is not guaranteed to match the + * ordering on the server nor the ordering of `onChildAdded()` events. That is + * where `forEach()` comes in handy. It guarantees the children of a + * `DataSnapshot` will be iterated in their query order. + * + * If no explicit `orderBy*()` method is used, results are returned + * ordered by key (unless priorities are used, in which case, results are + * returned by priority). + * + * @param action - A function that will be called for each child DataSnapshot. + * The callback can return true to cancel further enumeration. + * @returns true if enumeration was canceled due to your callback returning + * true. + */ + forEach(action) { + if (this._node.isLeafNode()) { + return false; + } + const childrenNode = this._node; + // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type... + return !!childrenNode.forEachChild(this._index, (key, node) => { + return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX)); + }); + } + /** + * Returns true if the specified child path has (non-null) data. + * + * @param path - A relative path to the location of a potential child. + * @returns `true` if data exists at the specified child path; else + * `false`. + */ + hasChild(path) { + const childPath = new Path(path); + return !this._node.getChild(childPath).isEmpty(); + } + /** + * Returns whether or not the `DataSnapshot` has any non-`null` child + * properties. + * + * You can use `hasChildren()` to determine if a `DataSnapshot` has any + * children. If it does, you can enumerate them using `forEach()`. If it + * doesn't, then either this snapshot contains a primitive value (which can be + * retrieved with `val()`) or it is empty (in which case, `val()` will return + * `null`). + * + * @returns true if this snapshot has any children; else false. + */ + hasChildren() { + if (this._node.isLeafNode()) { + return false; + } + else { + return !this._node.isEmpty(); + } + } + /** + * Returns a JSON-serializable representation of this object. + */ + toJSON() { + return this.exportVal(); + } + /** + * Extracts a JavaScript value from a `DataSnapshot`. + * + * Depending on the data in a `DataSnapshot`, the `val()` method may return a + * scalar type (string, number, or boolean), an array, or an object. It may + * also return null, indicating that the `DataSnapshot` is empty (contains no + * data). + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + val() { + return this._node.val(); + } +} +/** + * + * Returns a `Reference` representing the location in the Database + * corresponding to the provided path. If no path is provided, the `Reference` + * will point to the root of the Database. + * + * @param db - The database instance to obtain a reference for. + * @param path - Optional path representing the location the returned + * `Reference` will point. If not provided, the returned `Reference` will + * point to the root of the Database. + * @returns If a path is provided, a `Reference` + * pointing to the provided path. Otherwise, a `Reference` pointing to the + * root of the Database. + */ +function ref(db, path) { + db = getModularInstance(db); + db._checkNotDeleted('ref'); + return path !== undefined ? child(db._root, path) : db._root; +} +/** + * Returns a `Reference` representing the location in the Database + * corresponding to the provided Firebase URL. + * + * An exception is thrown if the URL is not a valid Firebase Database URL or it + * has a different domain than the current `Database` instance. + * + * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored + * and are not applied to the returned `Reference`. + * + * @param db - The database instance to obtain a reference for. + * @param url - The Firebase URL at which the returned `Reference` will + * point. + * @returns A `Reference` pointing to the provided + * Firebase URL. + */ +function refFromURL(db, url) { + db = getModularInstance(db); + db._checkNotDeleted('refFromURL'); + const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin); + validateUrl('refFromURL', parsedURL); + const repoInfo = parsedURL.repoInfo; + if (!db._repo.repoInfo_.isCustomHost() && + repoInfo.host !== db._repo.repoInfo_.host) { + fatal('refFromURL' + + ': Host name does not match the current database: ' + + '(found ' + + repoInfo.host + + ' but expected ' + + db._repo.repoInfo_.host + + ')'); + } + return ref(db, parsedURL.path.toString()); +} +/** + * Gets a `Reference` for the location at the specified relative path. + * + * The relative path can either be a simple child name (for example, "ada") or + * a deeper slash-separated path (for example, "ada/name/first"). + * + * @param parent - The parent location. + * @param path - A relative path from this location to the desired child + * location. + * @returns The specified child location. + */ +function child(parent, path) { + parent = getModularInstance(parent); + if (pathGetFront(parent._path) === null) { + validateRootPathString('child', 'path', path, false); + } + else { + validatePathString('child', 'path', path, false); + } + return new ReferenceImpl(parent._repo, pathChild(parent._path, path)); +} +/** + * Returns an `OnDisconnect` object - see + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information on how to use it. + * + * @param ref - The reference to add OnDisconnect triggers for. + */ +function onDisconnect(ref) { + ref = getModularInstance(ref); + return new OnDisconnect(ref._repo, ref._path); +} +/** + * Generates a new child location using a unique key and returns its + * `Reference`. + * + * This is the most common pattern for adding data to a collection of items. + * + * If you provide a value to `push()`, the value is written to the + * generated location. If you don't pass a value, nothing is written to the + * database and the child remains empty (but you can use the `Reference` + * elsewhere). + * + * The unique keys generated by `push()` are ordered by the current time, so the + * resulting list of items is chronologically sorted. The keys are also + * designed to be unguessable (they contain 72 random bits of entropy). + * + * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}. + * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}. + * + * @param parent - The parent location. + * @param value - Optional value to be written at the generated location. + * @returns Combined `Promise` and `Reference`; resolves when write is complete, + * but can be used immediately as the `Reference` to the child location. + */ +function push(parent, value) { + parent = getModularInstance(parent); + validateWritablePath('push', parent._path); + validateFirebaseDataArg('push', value, parent._path, true); + const now = repoServerTime(parent._repo); + const name = nextPushId(now); + // push() returns a ThennableReference whose promise is fulfilled with a + // regular Reference. We use child() to create handles to two different + // references. The first is turned into a ThennableReference below by adding + // then() and catch() methods and is used as the return value of push(). The + // second remains a regular Reference and is used as the fulfilled value of + // the first ThennableReference. + const thenablePushRef = child(parent, name); + const pushRef = child(parent, name); + let promise; + if (value != null) { + promise = set(pushRef, value).then(() => pushRef); + } + else { + promise = Promise.resolve(pushRef); + } + thenablePushRef.then = promise.then.bind(promise); + thenablePushRef.catch = promise.then.bind(promise, undefined); + return thenablePushRef; +} +/** + * Removes the data at this Database location. + * + * Any data at child locations will also be deleted. + * + * The effect of the remove will be visible immediately and the corresponding + * event 'value' will be triggered. Synchronization of the remove to the + * Firebase servers will also be started, and the returned Promise will resolve + * when complete. If provided, the onComplete callback will be called + * asynchronously after synchronization has finished. + * + * @param ref - The location to remove. + * @returns Resolves when remove on server is complete. + */ +function remove(ref) { + validateWritablePath('remove', ref._path); + return set(ref, null); +} +/** + * Writes data to this Database location. + * + * This will overwrite any data at this location and all child locations. + * + * The effect of the write will be visible immediately, and the corresponding + * events ("value", "child_added", etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * Passing `null` for the new value is equivalent to calling `remove()`; namely, + * all data at this location and all child locations will be deleted. + * + * `set()` will remove any priority stored at this location, so if priority is + * meant to be preserved, you need to use `setWithPriority()` instead. + * + * Note that modifying data with `set()` will cancel any pending transactions + * at that location, so extreme care should be taken if mixing `set()` and + * `transaction()` to modify the same data. + * + * A single `set()` will generate a single "value" event at the location where + * the `set()` was performed. + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @returns Resolves when write to server is complete. + */ +function set(ref, value) { + ref = getModularInstance(ref); + validateWritablePath('set', ref._path); + validateFirebaseDataArg('set', value, ref._path, false); + const deferred = new Deferred(); + repoSetWithPriority(ref._repo, ref._path, value, + /*priority=*/ null, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Sets a priority for the data at this Database location. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +function setPriority(ref, priority) { + ref = getModularInstance(ref); + validateWritablePath('setPriority', ref._path); + validatePriority('setPriority', priority, false); + const deferred = new Deferred(); + repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Writes data the Database location. Like `set()` but also specifies the + * priority for that data. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +function setWithPriority(ref, value, priority) { + validateWritablePath('setWithPriority', ref._path); + validateFirebaseDataArg('setWithPriority', value, ref._path, false); + validatePriority('setWithPriority', priority, false); + if (ref.key === '.length' || ref.key === '.keys') { + throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.'; + } + const deferred = new Deferred(); + repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Writes multiple values to the Database at once. + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, + * "name/first") from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * The effect of the write will be visible immediately, and the corresponding + * events ('value', 'child_added', etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * A single `update()` will generate a single "value" event at the location + * where the `update()` was performed, regardless of how many children were + * modified. + * + * Note that modifying data with `update()` will cancel any pending + * transactions at that location, so extreme care should be taken if mixing + * `update()` and `transaction()` to modify the same data. + * + * Passing `null` to `update()` will remove the data at this location. + * + * See + * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}. + * + * @param ref - The location to write to. + * @param values - Object containing multiple values. + * @returns Resolves when update on server is complete. + */ +function update(ref, values) { + validateFirebaseMergeDataArg('update', values, ref._path, false); + const deferred = new Deferred(); + repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { })); + return deferred.promise; +} +/** + * Gets the most up-to-date result for this query. + * + * @param query - The query to run. + * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is + * available, or rejects if the client is unable to return a value (e.g., if the + * server is unreachable and there is nothing cached). + */ +function get(query) { + query = getModularInstance(query); + const callbackContext = new CallbackContext(() => { }); + const container = new ValueEventRegistration(callbackContext); + return repoGetValue(query._repo, query, container).then(node => { + return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex()); + }); +} +/** + * Represents registration for 'value' events. + */ +class ValueEventRegistration { + constructor(callbackContext) { + this.callbackContext = callbackContext; + } + respondsTo(eventType) { + return eventType === 'value'; + } + createEvent(change, query) { + const index = query._queryParams.getIndex(); + return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index)); + } + getEventRunner(eventData) { + if (eventData.getEventType() === 'cancel') { + return () => this.callbackContext.onCancel(eventData.error); + } + else { + return () => this.callbackContext.onValue(eventData.snapshot, null); + } + } + createCancelEvent(error, path) { + if (this.callbackContext.hasCancelCallback) { + return new CancelEvent(this, error, path); + } + else { + return null; + } + } + matches(other) { + if (!(other instanceof ValueEventRegistration)) { + return false; + } + else if (!other.callbackContext || !this.callbackContext) { + // If no callback specified, we consider it to match any callback. + return true; + } + else { + return other.callbackContext.matches(this.callbackContext); + } + } + hasAnyCallback() { + return this.callbackContext !== null; + } +} +/** + * Represents the registration of a child_x event. + */ +class ChildEventRegistration { + constructor(eventType, callbackContext) { + this.eventType = eventType; + this.callbackContext = callbackContext; + } + respondsTo(eventType) { + let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType; + eventToCheck = + eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck; + return this.eventType === eventToCheck; + } + createCancelEvent(error, path) { + if (this.callbackContext.hasCancelCallback) { + return new CancelEvent(this, error, path); + } + else { + return null; + } + } + createEvent(change, query) { + assert(change.childName != null, 'Child events should have a childName.'); + const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName); + const index = query._queryParams.getIndex(); + return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName); + } + getEventRunner(eventData) { + if (eventData.getEventType() === 'cancel') { + return () => this.callbackContext.onCancel(eventData.error); + } + else { + return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName); + } + } + matches(other) { + if (other instanceof ChildEventRegistration) { + return (this.eventType === other.eventType && + (!this.callbackContext || + !other.callbackContext || + this.callbackContext.matches(other.callbackContext))); + } + return false; + } + hasAnyCallback() { + return !!this.callbackContext; + } +} +function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) { + let cancelCallback; + if (typeof cancelCallbackOrListenOptions === 'object') { + cancelCallback = undefined; + options = cancelCallbackOrListenOptions; + } + if (typeof cancelCallbackOrListenOptions === 'function') { + cancelCallback = cancelCallbackOrListenOptions; + } + if (options && options.onlyOnce) { + const userCallback = callback; + const onceCallback = (dataSnapshot, previousChildName) => { + repoRemoveEventCallbackForQuery(query._repo, query, container); + userCallback(dataSnapshot, previousChildName); + }; + onceCallback.userCallback = callback.userCallback; + onceCallback.context = callback.context; + callback = onceCallback; + } + const callbackContext = new CallbackContext(callback, cancelCallback || undefined); + const container = eventType === 'value' + ? new ValueEventRegistration(callbackContext) + : new ChildEventRegistration(eventType, callbackContext); + repoAddEventCallbackForQuery(query._repo, query, container); + return () => repoRemoveEventCallbackForQuery(query._repo, query, container); +} +function onValue(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options); +} +function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options); +} +function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options); +} +function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options); +} +function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) { + return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options); +} +/** + * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener. + * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from + * the respective `on*` callbacks. + * + * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener + * will not automatically remove listeners registered on child nodes, `off()` + * must also be called on any child listeners to remove the callback. + * + * If a callback is not specified, all callbacks for the specified eventType + * will be removed. Similarly, if no eventType is specified, all callbacks + * for the `Reference` will be removed. + * + * Individual listeners can also be removed by invoking their unsubscribe + * callbacks. + * + * @param query - The query that the listener was registered with. + * @param eventType - One of the following strings: "value", "child_added", + * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks + * for the `Reference` will be removed. + * @param callback - The callback function that was passed to `on()` or + * `undefined` to remove all callbacks. + */ +function off(query, eventType, callback) { + let container = null; + const expCallback = callback ? new CallbackContext(callback) : null; + if (eventType === 'value') { + container = new ValueEventRegistration(expCallback); + } + else if (eventType) { + container = new ChildEventRegistration(eventType, expCallback); + } + repoRemoveEventCallbackForQuery(query._repo, query, container); +} +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Database query. `QueryConstraint`s are created by invoking {@link endAt}, + * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link + * limitToFirst}, {@link limitToLast}, {@link orderByChild}, + * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} , + * {@link orderByValue} or {@link equalTo} and + * can then be passed to {@link query} to create a new query instance that + * also contains this `QueryConstraint`. + */ +class QueryConstraint { +} +class QueryEndAtConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'endAt'; + } + _apply(query) { + validateFirebaseDataArg('endAt', this._value, query._path, true); + const newParams = queryParamsEndAt(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasEnd()) { + throw new Error('endAt: Starting point was already set (by another call to endAt, ' + + 'endBefore or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified ending point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name less than or equal + * to the specified key. + * + * You can read more about `endAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to end at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end at, among the children with the previously + * specified priority. This argument is only allowed if ordering by child, + * value, or priority. + */ +function endAt(value, key) { + validateKey('endAt', 'key', key, true); + return new QueryEndAtConstraint(value, key); +} +class QueryEndBeforeConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'endBefore'; + } + _apply(query) { + validateFirebaseDataArg('endBefore', this._value, query._path, false); + const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasEnd()) { + throw new Error('endBefore: Starting point was already set (by another call to endAt, ' + + 'endBefore or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified ending point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is exclusive. If only a value is provided, children + * with a value less than the specified value will be included in the query. + * If a key is specified, then children must have a value less than or equal + * to the specified value and a key name less than the specified key. + * + * @param value - The value to end before. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end before, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +function endBefore(value, key) { + validateKey('endBefore', 'key', key, true); + return new QueryEndBeforeConstraint(value, key); +} +class QueryStartAtConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'startAt'; + } + _apply(query) { + validateFirebaseDataArg('startAt', this._value, query._path, true); + const newParams = queryParamsStartAt(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasStart()) { + throw new Error('startAt: Starting point was already set (by another call to startAt, ' + + 'startBefore or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified starting point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name greater than or + * equal to the specified key. + * + * You can read more about `startAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to start at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at. This argument is only allowed if + * ordering by child, value, or priority. + */ +function startAt(value = null, key) { + validateKey('startAt', 'key', key, true); + return new QueryStartAtConstraint(value, key); +} +class QueryStartAfterConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'startAfter'; + } + _apply(query) { + validateFirebaseDataArg('startAfter', this._value, query._path, false); + const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key); + validateLimit(newParams); + validateQueryEndpoints(newParams); + if (query._queryParams.hasStart()) { + throw new Error('startAfter: Starting point was already set (by another call to startAt, ' + + 'startAfter, or equalTo).'); + } + return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled); + } +} +/** + * Creates a `QueryConstraint` with the specified starting point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is exclusive. If only a value is provided, children + * with a value greater than the specified value will be included in the query. + * If a key is specified, then children must have a value greater than or equal + * to the specified value and a a key name greater than the specified key. + * + * @param value - The value to start after. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start after. This argument is only allowed if + * ordering by child, value, or priority. + */ +function startAfter(value, key) { + validateKey('startAfter', 'key', key, true); + return new QueryStartAfterConstraint(value, key); +} +class QueryLimitToFirstConstraint extends QueryConstraint { + constructor(_limit) { + super(); + this._limit = _limit; + this.type = 'limitToFirst'; + } + _apply(query) { + if (query._queryParams.hasLimit()) { + throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' + + 'or limitToLast).'); + } + return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled); + } +} +/** + * Creates a new `QueryConstraint` that if limited to the first specific number + * of children. + * + * The `limitToFirst()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the first 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToFirst()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +function limitToFirst(limit) { + if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) { + throw new Error('limitToFirst: First argument must be a positive integer.'); + } + return new QueryLimitToFirstConstraint(limit); +} +class QueryLimitToLastConstraint extends QueryConstraint { + constructor(_limit) { + super(); + this._limit = _limit; + this.type = 'limitToLast'; + } + _apply(query) { + if (query._queryParams.hasLimit()) { + throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' + + 'or limitToLast).'); + } + return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled); + } +} +/** + * Creates a new `QueryConstraint` that is limited to return only the last + * specified number of children. + * + * The `limitToLast()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the last 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToLast()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +function limitToLast(limit) { + if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) { + throw new Error('limitToLast: First argument must be a positive integer.'); + } + return new QueryLimitToLastConstraint(limit); +} +class QueryOrderByChildConstraint extends QueryConstraint { + constructor(_path) { + super(); + this._path = _path; + this.type = 'orderByChild'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByChild'); + const parsedPath = new Path(this._path); + if (pathIsEmpty(parsedPath)) { + throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.'); + } + const index = new PathIndex(parsedPath); + const newParams = queryParamsOrderBy(query._queryParams, index); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by the specified child key. + * + * Queries can only order by one key at a time. Calling `orderByChild()` + * multiple times on the same query is an error. + * + * Firebase queries allow you to order your data by any child key on the fly. + * However, if you know in advance what your indexes will be, you can define + * them via the .indexOn rule in your Security Rules for better performance. See + * the{@link https://firebase.google.com/docs/database/security/indexing-data} + * rule for more information. + * + * You can read more about `orderByChild()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + * + * @param path - The path to order by. + */ +function orderByChild(path) { + if (path === '$key') { + throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.'); + } + else if (path === '$priority') { + throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.'); + } + else if (path === '$value') { + throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.'); + } + validatePathString('orderByChild', 'path', path, false); + return new QueryOrderByChildConstraint(path); +} +class QueryOrderByKeyConstraint extends QueryConstraint { + constructor() { + super(...arguments); + this.type = 'orderByKey'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByKey'); + const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by the key. + * + * Sorts the results of a query by their (ascending) key values. + * + * You can read more about `orderByKey()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +function orderByKey() { + return new QueryOrderByKeyConstraint(); +} +class QueryOrderByPriorityConstraint extends QueryConstraint { + constructor() { + super(...arguments); + this.type = 'orderByPriority'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByPriority'); + const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by priority. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data} + * for alternatives to priority. + */ +function orderByPriority() { + return new QueryOrderByPriorityConstraint(); +} +class QueryOrderByValueConstraint extends QueryConstraint { + constructor() { + super(...arguments); + this.type = 'orderByValue'; + } + _apply(query) { + validateNoPreviousOrderByCall(query, 'orderByValue'); + const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX); + validateQueryEndpoints(newParams); + return new QueryImpl(query._repo, query._path, newParams, + /*orderByCalled=*/ true); + } +} +/** + * Creates a new `QueryConstraint` that orders by value. + * + * If the children of a query are all scalar values (string, number, or + * boolean), you can order the results by their (ascending) values. + * + * You can read more about `orderByValue()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +function orderByValue() { + return new QueryOrderByValueConstraint(); +} +class QueryEqualToValueConstraint extends QueryConstraint { + constructor(_value, _key) { + super(); + this._value = _value; + this._key = _key; + this.type = 'equalTo'; + } + _apply(query) { + validateFirebaseDataArg('equalTo', this._value, query._path, false); + if (query._queryParams.hasStart()) { + throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' + + 'equalTo).'); + } + if (query._queryParams.hasEnd()) { + throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' + + 'equalTo).'); + } + return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query)); + } +} +/** + * Creates a `QueryConstraint` that includes children that match the specified + * value. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The optional key argument can be used to further limit the range of the + * query. If it is specified, then children that have exactly the specified + * value must also have exactly the specified key as their key name. This can be + * used to filter result sets with many matches for the same value. + * + * You can read more about `equalTo()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to match for. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +function equalTo(value, key) { + validateKey('equalTo', 'key', key, true); + return new QueryEqualToValueConstraint(value, key); +} +/** + * Creates a new immutable instance of `Query` that is extended to also include + * additional query constraints. + * + * @param query - The Query instance to use as a base for the new constraints. + * @param queryConstraints - The list of `QueryConstraint`s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +function query(query, ...queryConstraints) { + let queryImpl = getModularInstance(query); + for (const constraint of queryConstraints) { + queryImpl = constraint._apply(queryImpl); + } + return queryImpl; +} +/** + * Define reference constructor in various modules + * + * We are doing this here to avoid several circular + * dependency issues + */ +syncPointSetReferenceConstructor(ReferenceImpl); +syncTreeSetReferenceConstructor(ReferenceImpl); + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This variable is also defined in the firebase Node.js Admin SDK. Before + * modifying this definition, consult the definition in: + * + * https://github.com/firebase/firebase-admin-node + * + * and make sure the two are consistent. + */ +const FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST'; +/** + * Creates and caches `Repo` instances. + */ +const repos = {}; +/** + * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes). + */ +let useRestClient = false; +/** + * Update an existing `Repo` in place to point to a new host/port. + */ +function repoManagerApplyEmulatorSettings(repo, hostAndPort, emulatorOptions, tokenProvider) { + const portIndex = hostAndPort.lastIndexOf(':'); + const host = hostAndPort.substring(0, portIndex); + const useSsl = isCloudWorkstation(host); + repo.repoInfo_ = new RepoInfo(hostAndPort, + /* secure= */ useSsl, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams, + /*isUsingEmulator=*/ true, emulatorOptions); + if (tokenProvider) { + repo.authTokenProvider_ = tokenProvider; + } +} +/** + * This function should only ever be called to CREATE a new database instance. + * @internal + */ +function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) { + let dbUrl = url || app.options.databaseURL; + if (dbUrl === undefined) { + if (!app.options.projectId) { + fatal("Can't determine Firebase Database URL. Be sure to include " + + ' a Project ID when calling firebase.initializeApp().'); + } + log('Using default host for project ', app.options.projectId); + dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`; + } + let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin); + let repoInfo = parsedUrl.repoInfo; + let isEmulator; + let dbEmulatorHost = undefined; + if (typeof process !== 'undefined' && process.env) { + dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR]; + } + if (dbEmulatorHost) { + isEmulator = true; + dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`; + parsedUrl = parseRepoInfo(dbUrl, nodeAdmin); + repoInfo = parsedUrl.repoInfo; + } + else { + isEmulator = !parsedUrl.repoInfo.secure; + } + const authTokenProvider = nodeAdmin && isEmulator + ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER) + : new FirebaseAuthTokenProvider(app.name, app.options, authProvider); + validateUrl('Invalid Firebase Database URL', parsedUrl); + if (!pathIsEmpty(parsedUrl.path)) { + fatal('Database URL must point to the root of a Firebase Database ' + + '(not including a child path).'); + } + const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app, appCheckProvider)); + return new Database(repo, app); +} +/** + * Remove the repo and make sure it is disconnected. + * + */ +function repoManagerDeleteRepo(repo, appName) { + const appRepos = repos[appName]; + // This should never happen... + if (!appRepos || appRepos[repo.key] !== repo) { + fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`); + } + repoInterrupt(repo); + delete appRepos[repo.key]; +} +/** + * Ensures a repo doesn't already exist and then creates one using the + * provided app. + * + * @param repoInfo - The metadata about the Repo + * @returns The Repo object for the specified server / repoName. + */ +function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) { + let appRepos = repos[app.name]; + if (!appRepos) { + appRepos = {}; + repos[app.name] = appRepos; + } + let repo = appRepos[repoInfo.toURLString()]; + if (repo) { + fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.'); + } + repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider); + appRepos[repoInfo.toURLString()] = repo; + return repo; +} +/** + * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos. + */ +function repoManagerForceRestClient(forceRestClient) { + useRestClient = forceRestClient; +} +/** + * Class representing a Firebase Realtime Database. + */ +class Database { + /** @hideconstructor */ + constructor(_repoInternal, + /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */ + app) { + this._repoInternal = _repoInternal; + this.app = app; + /** Represents a `Database` instance. */ + this['type'] = 'database'; + /** Track if the instance has been used (root or repo accessed) */ + this._instanceStarted = false; + } + get _repo() { + if (!this._instanceStarted) { + repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']); + this._instanceStarted = true; + } + return this._repoInternal; + } + get _root() { + if (!this._rootInternal) { + this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath()); + } + return this._rootInternal; + } + _delete() { + if (this._rootInternal !== null) { + repoManagerDeleteRepo(this._repo, this.app.name); + this._repoInternal = null; + this._rootInternal = null; + } + return Promise.resolve(); + } + _checkNotDeleted(apiName) { + if (this._rootInternal === null) { + fatal('Cannot call ' + apiName + ' on a deleted database.'); + } + } +} +function checkTransportInit() { + if (TransportManager.IS_TRANSPORT_INITIALIZED) { + warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener'); + } +} +/** + * Force the use of websockets instead of longPolling. + */ +function forceWebSockets() { + checkTransportInit(); + BrowserPollConnection.forceDisallow(); +} +/** + * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL. + */ +function forceLongPolling() { + checkTransportInit(); + WebSocketConnection.forceDisallow(); + BrowserPollConnection.forceAllow(); +} +/** + * Returns the instance of the Realtime Database SDK that is associated with the provided + * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if + * no instance exists or if the existing instance uses a custom database URL. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime + * Database instance is associated with. + * @param url - The URL of the Realtime Database instance to connect to. If not + * provided, the SDK connects to the default instance of the Firebase App. + * @returns The `Database` instance of the provided app. + */ +function getDatabase(app = getApp(), url) { + const db = _getProvider(app, 'database').getImmediate({ + identifier: url + }); + if (!db._instanceStarted) { + const emulator = getDefaultEmulatorHostnameAndPort('database'); + if (emulator) { + connectDatabaseEmulator(db, ...emulator); + } + } + return db; +} +/** + * Modify the provided instance to communicate with the Realtime Database + * emulator. + * + *

Note: This method must be called before performing any other operation. + * + * @param db - The instance to modify. + * @param host - The emulator host (ex: localhost) + * @param port - The emulator port (ex: 8080) + * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules + */ +function connectDatabaseEmulator(db, host, port, options = {}) { + db = getModularInstance(db); + db._checkNotDeleted('useEmulator'); + const hostAndPort = `${host}:${port}`; + const repo = db._repoInternal; + if (db._instanceStarted) { + // If the instance has already been started, then silenty fail if this function is called again + // with the same parameters. If the parameters differ then assert. + if (hostAndPort === db._repoInternal.repoInfo_.host && + deepEqual(options, repo.repoInfo_.emulatorOptions)) { + return; + } + fatal('connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.'); + } + let tokenProvider = undefined; + if (repo.repoInfo_.nodeAdmin) { + if (options.mockUserToken) { + fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'); + } + tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER); + } + else if (options.mockUserToken) { + const token = typeof options.mockUserToken === 'string' + ? options.mockUserToken + : createMockUserToken(options.mockUserToken, db.app.options.projectId); + tokenProvider = new EmulatorTokenProvider(token); + } + // Workaround to get cookies in Firebase Studio + if (isCloudWorkstation(host)) { + void pingServer(host); + updateEmulatorBanner('Database', true); + } + // Modify the repo to apply emulator settings + repoManagerApplyEmulatorSettings(repo, hostAndPort, options, tokenProvider); +} +/** + * Disconnects from the server (all Database operations will be completed + * offline). + * + * The client automatically maintains a persistent connection to the Database + * server, which will remain active indefinitely and reconnect when + * disconnected. However, the `goOffline()` and `goOnline()` methods may be used + * to control the client connection in cases where a persistent connection is + * undesirable. + * + * While offline, the client will no longer receive data updates from the + * Database. However, all Database operations performed locally will continue to + * immediately fire events, allowing your application to continue behaving + * normally. Additionally, each operation performed locally will automatically + * be queued and retried upon reconnection to the Database server. + * + * To reconnect to the Database and begin receiving remote events, see + * `goOnline()`. + * + * @param db - The instance to disconnect. + */ +function goOffline(db) { + db = getModularInstance(db); + db._checkNotDeleted('goOffline'); + repoInterrupt(db._repo); +} +/** + * Reconnects to the server and synchronizes the offline Database state + * with the server state. + * + * This method should be used after disabling the active connection with + * `goOffline()`. Once reconnected, the client will transmit the proper data + * and fire the appropriate events so that your client "catches up" + * automatically. + * + * @param db - The instance to reconnect. + */ +function goOnline(db) { + db = getModularInstance(db); + db._checkNotDeleted('goOnline'); + repoResume(db._repo); +} +function enableLogging(logger, persistent) { + enableLogging$1(logger, persistent); +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function registerDatabase(variant) { + setSDKVersion(SDK_VERSION$1); + _registerComponent(new Component('database', (container, { instanceIdentifier: url }) => { + const app = container.getProvider('app').getImmediate(); + const authProvider = container.getProvider('auth-internal'); + const appCheckProvider = container.getProvider('app-check-internal'); + return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url); + }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true)); + registerVersion(name, version, variant); + // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation + registerVersion(name, version, 'esm2020'); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const SERVER_TIMESTAMP = { + '.sv': 'timestamp' +}; +/** + * Returns a placeholder value for auto-populating the current timestamp (time + * since the Unix epoch, in milliseconds) as determined by the Firebase + * servers. + */ +function serverTimestamp() { + return SERVER_TIMESTAMP; +} +/** + * Returns a placeholder value that can be used to atomically increment the + * current database value by the provided delta. + * + * @param delta - the amount to modify the current value atomically. + * @returns A placeholder value for modifying data atomically server-side. + */ +function increment(delta) { + return { + '.sv': { + 'increment': delta + } + }; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A type for the resolve value of {@link runTransaction}. + */ +class TransactionResult { + /** @hideconstructor */ + constructor( + /** Whether the transaction was successfully committed. */ + committed, + /** The resulting data snapshot. */ + snapshot) { + this.committed = committed; + this.snapshot = snapshot; + } + /** Returns a JSON-serializable representation of this object. */ + toJSON() { + return { committed: this.committed, snapshot: this.snapshot.toJSON() }; + } +} +/** + * Atomically modifies the data at this location. + * + * Atomically modify the data at this location. Unlike a normal `set()`, which + * just overwrites the data regardless of its previous value, `runTransaction()` is + * used to modify the existing value to a new value, ensuring there are no + * conflicts with other clients writing to the same location at the same time. + * + * To accomplish this, you pass `runTransaction()` an update function which is + * used to transform the current value into a new value. If another client + * writes to the location before your new value is successfully written, your + * update function will be called again with the new current value, and the + * write will be retried. This will happen repeatedly until your write succeeds + * without conflict or you abort the transaction by not returning a value from + * your update function. + * + * Note: Modifying data with `set()` will cancel any pending transactions at + * that location, so extreme care should be taken if mixing `set()` and + * `runTransaction()` to update the same data. + * + * Note: When using transactions with Security and Firebase Rules in place, be + * aware that a client needs `.read` access in addition to `.write` access in + * order to perform a transaction. This is because the client-side nature of + * transactions requires the client to read the data in order to transactionally + * update it. + * + * @param ref - The location to atomically modify. + * @param transactionUpdate - A developer-supplied function which will be passed + * the current data stored at this location (as a JavaScript object). The + * function should return the new value it would like written (as a JavaScript + * object). If `undefined` is returned (i.e. you return with no arguments) the + * transaction will be aborted and the data at this location will not be + * modified. + * @param options - An options object to configure transactions. + * @returns A `Promise` that can optionally be used instead of the `onComplete` + * callback to handle success and failure. + */ +function runTransaction(ref, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +transactionUpdate, options) { + ref = getModularInstance(ref); + validateWritablePath('Reference.transaction', ref._path); + if (ref.key === '.length' || ref.key === '.keys') { + throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.'); + } + const applyLocally = options?.applyLocally ?? true; + const deferred = new Deferred(); + const promiseComplete = (error, committed, node) => { + let dataSnapshot = null; + if (error) { + deferred.reject(error); + } + else { + dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX); + deferred.resolve(new TransactionResult(committed, dataSnapshot)); + } + }; + // Add a watch to make sure we get server updates. + const unwatcher = onValue(ref, () => { }); + repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally); + return deferred.promise; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +PersistentConnection; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +PersistentConnection.prototype.simpleListen = function (pathString, onComplete) { + this.sendRequest('q', { p: pathString }, onComplete); +}; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +PersistentConnection.prototype.echo = function (data, onEcho) { + this.sendRequest('echo', { d: data }, onEcho); +}; +// RealTimeConnection properties that we use in tests. +Connection; +/** + * @internal + */ +const hijackHash = function (newHash) { + const oldPut = PersistentConnection.prototype.put; + PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) { + if (hash !== undefined) { + hash = newHash(); + } + oldPut.call(this, pathString, data, onComplete, hash); + }; + return function () { + PersistentConnection.prototype.put = oldPut; + }; +}; +RepoInfo; +/** + * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection. + * @internal + */ +const forceRestClient = function (forceRestClient) { + repoManagerForceRestClient(forceRestClient); +}; + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Used by console to create a database based on the app, + * passed database URL and a custom auth implementation. + * @internal + * @param app - A valid FirebaseApp-like object + * @param url - A valid Firebase databaseURL + * @param version - custom version e.g. firebase-admin version + * @param customAppCheckImpl - custom app check implementation + * @param customAuthImpl - custom auth implementation + */ +function _initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, nodeAdmin = false }) { + setSDKVersion(version); + /** + * ComponentContainer('database-standalone') is just a placeholder that doesn't perform + * any actual function. + */ + const componentContainer = new ComponentContainer('database-standalone'); + const authProvider = new Provider('auth-internal', componentContainer); + let appCheckProvider; + if (customAppCheckImpl) { + appCheckProvider = new Provider('app-check-internal', componentContainer); + appCheckProvider.setComponent(new Component('app-check-internal', () => customAppCheckImpl, "PRIVATE" /* ComponentType.PRIVATE */)); + } + authProvider.setComponent(new Component('auth-internal', () => customAuthImpl, "PRIVATE" /* ComponentType.PRIVATE */)); + return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin); +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +setWebSocketImpl(Websocket.Client); +registerDatabase('node'); + +export { DataSnapshot, Database, OnDisconnect, QueryConstraint, TransactionResult, QueryImpl as _QueryImpl, QueryParams as _QueryParams, ReferenceImpl as _ReferenceImpl, forceRestClient as _TEST_ACCESS_forceRestClient, hijackHash as _TEST_ACCESS_hijackHash, _initStandalone, repoManagerDatabaseFromApp as _repoManagerDatabaseFromApp, setSDKVersion as _setSDKVersion, validatePathString as _validatePathString, validateWritablePath as _validateWritablePath, child, connectDatabaseEmulator, enableLogging, endAt, endBefore, equalTo, forceLongPolling, forceWebSockets, get, getDatabase, goOffline, goOnline, increment, limitToFirst, limitToLast, off, onChildAdded, onChildChanged, onChildMoved, onChildRemoved, onDisconnect, onValue, orderByChild, orderByKey, orderByPriority, orderByValue, push, query, ref, refFromURL, remove, runTransaction, serverTimestamp, set, setPriority, setWithPriority, startAfter, startAt, update }; +//# sourceMappingURL=index.node.esm.js.map diff --git a/node_modules/@firebase/database/dist/node-esm/index.node.esm.js.map b/node_modules/@firebase/database/dist/node-esm/index.node.esm.js.map new file mode 100644 index 0000000..dd4956d --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/index.node.esm.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.node.esm.js","sources":["../../src/realtime/Constants.ts","../../src/core/storage/DOMStorageWrapper.ts","../../src/core/storage/MemoryStorage.ts","../../src/core/storage/storage.ts","../../src/core/util/util.ts","../../src/core/RepoInfo.ts","../../src/core/stats/StatsCollection.ts","../../src/core/stats/StatsManager.ts","../../src/core/version.ts","../../src/realtime/WebSocketConnection.ts","../../src/core/AppCheckTokenProvider.ts","../../src/core/AuthTokenProvider.ts","../../src/realtime/polling/PacketReceiver.ts","../../src/realtime/BrowserPollConnection.ts","../../src/realtime/TransportManager.ts","../../src/realtime/Connection.ts","../../src/core/ServerActions.ts","../../src/core/util/EventEmitter.ts","../../src/core/util/OnlineMonitor.ts","../../src/core/util/Path.ts","../../src/core/util/VisibilityMonitor.ts","../../src/core/PersistentConnection.ts","../../src/core/snap/Node.ts","../../src/core/snap/indexes/Index.ts","../../src/core/snap/indexes/KeyIndex.ts","../../src/core/util/SortedMap.ts","../../src/core/snap/comparators.ts","../../src/core/snap/snap.ts","../../src/core/snap/LeafNode.ts","../../src/core/snap/indexes/PriorityIndex.ts","../../src/core/snap/childSet.ts","../../src/core/snap/IndexMap.ts","../../src/core/snap/ChildrenNode.ts","../../src/core/snap/nodeFromJSON.ts","../../src/core/snap/indexes/PathIndex.ts","../../src/core/snap/indexes/ValueIndex.ts","../../src/core/view/Change.ts","../../src/core/view/filter/IndexedFilter.ts","../../src/core/view/filter/RangedFilter.ts","../../src/core/view/filter/LimitedFilter.ts","../../src/core/view/QueryParams.ts","../../src/core/ReadonlyRestClient.ts","../../src/core/SnapshotHolder.ts","../../src/core/SparseSnapshotTree.ts","../../src/core/stats/StatsListener.ts","../../src/core/stats/StatsReporter.ts","../../src/core/operation/Operation.ts","../../src/core/operation/AckUserWrite.ts","../../src/core/operation/ListenComplete.ts","../../src/core/operation/Overwrite.ts","../../src/core/operation/Merge.ts","../../src/core/view/CacheNode.ts","../../src/core/view/EventGenerator.ts","../../src/core/view/ViewCache.ts","../../src/core/util/ImmutableTree.ts","../../src/core/CompoundWrite.ts","../../src/core/WriteTree.ts","../../src/core/view/ChildChangeAccumulator.ts","../../src/core/view/CompleteChildSource.ts","../../src/core/view/ViewProcessor.ts","../../src/core/view/View.ts","../../src/core/SyncPoint.ts","../../src/core/SyncTree.ts","../../src/core/util/ServerValues.ts","../../src/core/util/Tree.ts","../../src/core/util/validation.ts","../../src/core/view/EventQueue.ts","../../src/core/Repo.ts","../../src/core/util/libs/parser.ts","../../src/core/util/NextPushId.ts","../../src/core/view/Event.ts","../../src/core/view/EventRegistration.ts","../../src/api/OnDisconnect.ts","../../src/api/Reference_impl.ts","../../src/api/Database.ts","../../src/register.ts","../../src/api/ServerValue.ts","../../src/api/Transaction.ts","../../src/api/test_access.ts","../../src/internal/index.ts","../../src/index.node.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const PROTOCOL_VERSION = '5';\n\nexport const VERSION_PARAM = 'v';\n\nexport const TRANSPORT_SESSION_PARAM = 's';\n\nexport const REFERER_PARAM = 'r';\n\nexport const FORGE_REF = 'f';\n\n// Matches console.firebase.google.com, firebase-console-*.corp.google.com and\n// firebase.corp.google.com\nexport const FORGE_DOMAIN_RE =\n /(console\\.firebase|firebase-console-\\w+\\.corp|firebase\\.corp)\\.google\\.com/;\n\nexport const LAST_SESSION_PARAM = 'ls';\n\nexport const APPLICATION_ID_PARAM = 'p';\n\nexport const APP_CHECK_TOKEN_PARAM = 'ac';\n\nexport const WEBSOCKET = 'websocket';\n\nexport const LONG_POLLING = 'long_polling';\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { jsonEval, stringify } from '@firebase/util';\n\n/**\n * Wraps a DOM Storage object and:\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\n *\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\n * and one for localStorage.\n *\n */\nexport class DOMStorageWrapper {\n // Use a prefix to avoid collisions with other stuff saved by the app.\n private prefix_ = 'firebase:';\n\n /**\n * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)\n */\n constructor(private domStorage_: Storage) {}\n\n /**\n * @param key - The key to save the value under\n * @param value - The value being stored, or null to remove the key.\n */\n set(key: string, value: unknown | null) {\n if (value == null) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n } else {\n this.domStorage_.setItem(this.prefixedName_(key), stringify(value));\n }\n }\n\n /**\n * @returns The value that was stored under this key, or null\n */\n get(key: string): unknown {\n const storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n if (storedVal == null) {\n return null;\n } else {\n return jsonEval(storedVal);\n }\n }\n\n remove(key: string) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n\n isInMemoryStorage: boolean;\n\n prefixedName_(name: string): string {\n return this.prefix_ + name;\n }\n\n toString(): string {\n return this.domStorage_.toString();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains } from '@firebase/util';\n\n/**\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\n * (TODO: create interface for both to implement).\n */\nexport class MemoryStorage {\n private cache_: { [k: string]: unknown } = {};\n\n set(key: string, value: unknown | null) {\n if (value == null) {\n delete this.cache_[key];\n } else {\n this.cache_[key] = value;\n }\n }\n\n get(key: string): unknown {\n if (contains(this.cache_, key)) {\n return this.cache_[key];\n }\n return null;\n }\n\n remove(key: string) {\n delete this.cache_[key];\n }\n\n isInMemoryStorage = true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DOMStorageWrapper } from './DOMStorageWrapper';\nimport { MemoryStorage } from './MemoryStorage';\n\ndeclare const window: Window;\n\n/**\n * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\n * to reflect this type\n *\n * @param domStorageName - Name of the underlying storage object\n * (e.g. 'localStorage' or 'sessionStorage').\n * @returns Turning off type information until a common interface is defined.\n */\nconst createStoragefor = function (\n domStorageName: string\n): DOMStorageWrapper | MemoryStorage {\n try {\n // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\n // so it must be inside the try/catch.\n if (\n typeof window !== 'undefined' &&\n typeof window[domStorageName] !== 'undefined'\n ) {\n // Need to test cache. Just because it's here doesn't mean it works\n const domStorage = window[domStorageName];\n domStorage.setItem('firebase:sentinel', 'cache');\n domStorage.removeItem('firebase:sentinel');\n return new DOMStorageWrapper(domStorage);\n }\n } catch (e) {}\n\n // Failed to create wrapper. Just return in-memory storage.\n // TODO: log?\n return new MemoryStorage();\n};\n\n/** A storage object that lasts across sessions */\nexport const PersistentStorage = createStoragefor('localStorage');\n\n/** A storage object that only lasts one session */\nexport const SessionStorage = createStoragefor('sessionStorage');\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel } from '@firebase/logger';\nimport {\n assert,\n base64,\n Sha1,\n stringToByteArray,\n stringify,\n isNodeSdk\n} from '@firebase/util';\n\nimport { SessionStorage } from '../storage/storage';\nimport { QueryContext } from '../view/EventRegistration';\n\ndeclare const window: Window;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ndeclare const Windows: any;\n\nconst logClient = new Logger('@firebase/database');\n\n/**\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\n */\nexport const LUIDGenerator: () => number = (function () {\n let id = 1;\n return function () {\n return id++;\n };\n})();\n\n/**\n * Sha1 hash of the input string\n * @param str - The string to hash\n * @returns {!string} The resulting hash\n */\nexport const sha1 = function (str: string): string {\n const utf8Bytes = stringToByteArray(str);\n const sha1 = new Sha1();\n sha1.update(utf8Bytes);\n const sha1Bytes = sha1.digest();\n return base64.encodeByteArray(sha1Bytes);\n};\n\nconst buildLogMessage_ = function (...varArgs: unknown[]): string {\n let message = '';\n for (let i = 0; i < varArgs.length; i++) {\n const arg = varArgs[i];\n if (\n Array.isArray(arg) ||\n (arg &&\n typeof arg === 'object' &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (arg as any).length === 'number')\n ) {\n message += buildLogMessage_.apply(null, arg);\n } else if (typeof arg === 'object') {\n message += stringify(arg);\n } else {\n message += arg;\n }\n message += ' ';\n }\n\n return message;\n};\n\n/**\n * Use this for all debug messages in Firebase.\n */\nexport let logger: ((a: string) => void) | null = null;\n\n/**\n * Flag to check for log availability on first log message\n */\nlet firstLog_ = true;\n\n/**\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\n * @param logger_ - A flag to turn on logging, or a custom logger\n * @param persistent - Whether or not to persist logging settings across refreshes\n */\nexport const enableLogging = function (\n logger_?: boolean | ((a: string) => void) | null,\n persistent?: boolean\n) {\n assert(\n !persistent || logger_ === true || logger_ === false,\n \"Can't turn on custom loggers persistently.\"\n );\n if (logger_ === true) {\n logClient.logLevel = LogLevel.VERBOSE;\n logger = logClient.log.bind(logClient);\n if (persistent) {\n SessionStorage.set('logging_enabled', true);\n }\n } else if (typeof logger_ === 'function') {\n logger = logger_;\n } else {\n logger = null;\n SessionStorage.remove('logging_enabled');\n }\n};\n\nexport const log = function (...varArgs: unknown[]) {\n if (firstLog_ === true) {\n firstLog_ = false;\n if (logger === null && SessionStorage.get('logging_enabled') === true) {\n enableLogging(true);\n }\n }\n\n if (logger) {\n const message = buildLogMessage_.apply(null, varArgs);\n logger(message);\n }\n};\n\nexport const logWrapper = function (\n prefix: string\n): (...varArgs: unknown[]) => void {\n return function (...varArgs: unknown[]) {\n log(prefix, ...varArgs);\n };\n};\n\nexport const error = function (...varArgs: string[]) {\n const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);\n logClient.error(message);\n};\n\nexport const fatal = function (...varArgs: string[]) {\n const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;\n logClient.error(message);\n throw new Error(message);\n};\n\nexport const warn = function (...varArgs: unknown[]) {\n const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);\n logClient.warn(message);\n};\n\n/**\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\n * does not use https.\n */\nexport const warnIfPageIsSecure = function () {\n // Be very careful accessing browser globals. Who knows what may or may not exist.\n if (\n typeof window !== 'undefined' &&\n window.location &&\n window.location.protocol &&\n window.location.protocol.indexOf('https:') !== -1\n ) {\n warn(\n 'Insecure Firebase access from a secure page. ' +\n 'Please use https in calls to new Firebase().'\n );\n }\n};\n\nexport const warnAboutUnsupportedMethod = function (methodName: string) {\n warn(\n methodName +\n ' is unsupported and will likely change soon. ' +\n 'Please do not use.'\n );\n};\n\n/**\n * Returns true if data is NaN, or +/- Infinity.\n */\nexport const isInvalidJSONNumber = function (data: unknown): boolean {\n return (\n typeof data === 'number' &&\n (data !== data || // NaN\n data === Number.POSITIVE_INFINITY ||\n data === Number.NEGATIVE_INFINITY)\n );\n};\n\nexport const executeWhenDOMReady = function (fn: () => void) {\n if (isNodeSdk() || document.readyState === 'complete') {\n fn();\n } else {\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\n // fire before onload), but fall back to onload.\n\n let called = false;\n const wrappedFn = function () {\n if (!document.body) {\n setTimeout(wrappedFn, Math.floor(10));\n return;\n }\n\n if (!called) {\n called = true;\n fn();\n }\n };\n\n if (document.addEventListener) {\n document.addEventListener('DOMContentLoaded', wrappedFn, false);\n // fallback to onload.\n window.addEventListener('load', wrappedFn, false);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else if ((document as any).attachEvent) {\n // IE.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (document as any).attachEvent('onreadystatechange', () => {\n if (document.readyState === 'complete') {\n wrappedFn();\n }\n });\n // fallback to onload.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (window as any).attachEvent('onload', wrappedFn);\n\n // jQuery has an extra hack for IE that we could employ (based on\n // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\n // I'm hoping we don't need it.\n }\n }\n};\n\n/**\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\n */\nexport const MIN_NAME = '[MIN_NAME]';\n\n/**\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\n */\nexport const MAX_NAME = '[MAX_NAME]';\n\n/**\n * Compares valid Firebase key names, plus min and max name\n */\nexport const nameCompare = function (a: string, b: string): number {\n if (a === b) {\n return 0;\n } else if (a === MIN_NAME || b === MAX_NAME) {\n return -1;\n } else if (b === MIN_NAME || a === MAX_NAME) {\n return 1;\n } else {\n const aAsInt = tryParseInt(a),\n bAsInt = tryParseInt(b);\n\n if (aAsInt !== null) {\n if (bAsInt !== null) {\n return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;\n } else {\n return -1;\n }\n } else if (bAsInt !== null) {\n return 1;\n } else {\n return a < b ? -1 : 1;\n }\n }\n};\n\n/**\n * @returns {!number} comparison result.\n */\nexport const stringCompare = function (a: string, b: string): number {\n if (a === b) {\n return 0;\n } else if (a < b) {\n return -1;\n } else {\n return 1;\n }\n};\n\nexport const requireKey = function (\n key: string,\n obj: { [k: string]: unknown }\n): unknown {\n if (obj && key in obj) {\n return obj[key];\n } else {\n throw new Error(\n 'Missing required key (' + key + ') in object: ' + stringify(obj)\n );\n }\n};\n\nexport const ObjectToUniqueKey = function (obj: unknown): string {\n if (typeof obj !== 'object' || obj === null) {\n return stringify(obj);\n }\n\n const keys = [];\n // eslint-disable-next-line guard-for-in\n for (const k in obj) {\n keys.push(k);\n }\n\n // Export as json, but with the keys sorted.\n keys.sort();\n let key = '{';\n for (let i = 0; i < keys.length; i++) {\n if (i !== 0) {\n key += ',';\n }\n key += stringify(keys[i]);\n key += ':';\n key += ObjectToUniqueKey(obj[keys[i]]);\n }\n\n key += '}';\n return key;\n};\n\n/**\n * Splits a string into a number of smaller segments of maximum size\n * @param str - The string\n * @param segsize - The maximum number of chars in the string.\n * @returns The string, split into appropriately-sized chunks\n */\nexport const splitStringBySize = function (\n str: string,\n segsize: number\n): string[] {\n const len = str.length;\n\n if (len <= segsize) {\n return [str];\n }\n\n const dataSegs = [];\n for (let c = 0; c < len; c += segsize) {\n if (c + segsize > len) {\n dataSegs.push(str.substring(c, len));\n } else {\n dataSegs.push(str.substring(c, c + segsize));\n }\n }\n return dataSegs;\n};\n\n/**\n * Apply a function to each (key, value) pair in an object or\n * apply a function to each (index, value) pair in an array\n * @param obj - The object or array to iterate over\n * @param fn - The function to apply\n */\nexport function each(obj: object, fn: (k: string, v: unknown) => void) {\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n fn(key, obj[key]);\n }\n }\n}\n\n/**\n * Like goog.bind, but doesn't bother to create a closure if opt_context is null/undefined.\n * @param callback - Callback function.\n * @param context - Optional context to bind to.\n *\n */\nexport const bindCallback = function (\n callback: (a: unknown) => void,\n context?: object | null\n): (a: unknown) => void {\n return context ? callback.bind(context) : callback;\n};\n\n/**\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\n * I made one modification at the end and removed the NaN / Infinity\n * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.\n * @param v - A double\n *\n */\nexport const doubleToIEEE754String = function (v: number): string {\n assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\n\n const ebits = 11,\n fbits = 52;\n const bias = (1 << (ebits - 1)) - 1;\n let s, e, f, ln, i;\n\n // Compute sign, exponent, fraction\n // Skip NaN / Infinity handling --MJL.\n if (v === 0) {\n e = 0;\n f = 0;\n s = 1 / v === -Infinity ? 1 : 0;\n } else {\n s = v < 0;\n v = Math.abs(v);\n\n if (v >= Math.pow(2, 1 - bias)) {\n // Normalized\n ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\n e = ln + bias;\n f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\n } else {\n // Denormalized\n e = 0;\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\n }\n }\n\n // Pack sign, exponent, fraction\n const bits = [];\n for (i = fbits; i; i -= 1) {\n bits.push(f % 2 ? 1 : 0);\n f = Math.floor(f / 2);\n }\n for (i = ebits; i; i -= 1) {\n bits.push(e % 2 ? 1 : 0);\n e = Math.floor(e / 2);\n }\n bits.push(s ? 1 : 0);\n bits.reverse();\n const str = bits.join('');\n\n // Return the data as a hex string. --MJL\n let hexByteString = '';\n for (i = 0; i < 64; i += 8) {\n let hexByte = parseInt(str.substr(i, 8), 2).toString(16);\n if (hexByte.length === 1) {\n hexByte = '0' + hexByte;\n }\n hexByteString = hexByteString + hexByte;\n }\n return hexByteString.toLowerCase();\n};\n\n/**\n * Used to detect if we're in a Chrome content script (which executes in an\n * isolated environment where long-polling doesn't work).\n */\nexport const isChromeExtensionContentScript = function (): boolean {\n return !!(\n typeof window === 'object' &&\n window['chrome'] &&\n window['chrome']['extension'] &&\n !/^chrome/.test(window.location.href)\n );\n};\n\n/**\n * Used to detect if we're in a Windows 8 Store app.\n */\nexport const isWindowsStoreApp = function (): boolean {\n // Check for the presence of a couple WinRT globals\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\n};\n\n/**\n * Converts a server error code to a JavaScript Error\n */\nexport function errorForServerCode(code: string, query: QueryContext): Error {\n let reason = 'Unknown Error';\n if (code === 'too_big') {\n reason =\n 'The data requested exceeds the maximum size ' +\n 'that can be accessed with a single request.';\n } else if (code === 'permission_denied') {\n reason = \"Client doesn't have permission to access the desired data.\";\n } else if (code === 'unavailable') {\n reason = 'The service is unavailable';\n }\n\n const error = new Error(\n code + ' at ' + query._path.toString() + ': ' + reason\n );\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (error as any).code = code.toUpperCase();\n return error;\n}\n\n/**\n * Used to test for integer-looking strings\n */\nexport const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\\\d{1,10}$');\n\n/**\n * For use in keys, the minimum possible 32-bit integer.\n */\nexport const INTEGER_32_MIN = -2147483648;\n\n/**\n * For use in keys, the maximum possible 32-bit integer.\n */\nexport const INTEGER_32_MAX = 2147483647;\n\n/**\n * If the string contains a 32-bit integer, return it. Else return null.\n */\nexport const tryParseInt = function (str: string): number | null {\n if (INTEGER_REGEXP_.test(str)) {\n const intVal = Number(str);\n if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {\n return intVal;\n }\n }\n return null;\n};\n\n/**\n * Helper to run some code but catch any exceptions and re-throw them later.\n * Useful for preventing user callbacks from breaking internal code.\n *\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\n * convenient (we don't have to try to figure out when is a safe point to\n * re-throw it), and the behavior seems reasonable:\n *\n * * If you aren't pausing on exceptions, you get an error in the console with\n * the correct stack trace.\n * * If you're pausing on all exceptions, the debugger will pause on your\n * exception and then again when we rethrow it.\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\n * on us re-throwing it.\n *\n * @param fn - The code to guard.\n */\nexport const exceptionGuard = function (fn: () => void) {\n try {\n fn();\n } catch (e) {\n // Re-throw exception when it's safe.\n setTimeout(() => {\n // It used to be that \"throw e\" would result in a good console error with\n // relevant context, but as of Chrome 39, you just get the firebase.js\n // file/line number where we re-throw it, which is useless. So we log\n // e.stack explicitly.\n const stack = e.stack || '';\n warn('Exception was thrown by user callback.', stack);\n throw e;\n }, Math.floor(0));\n }\n};\n\n/**\n * Helper function to safely call opt_callback with the specified arguments. It:\n * 1. Turns into a no-op if opt_callback is null or undefined.\n * 2. Wraps the call inside exceptionGuard to prevent exceptions from breaking our state.\n *\n * @param callback - Optional onComplete callback.\n * @param varArgs - Arbitrary args to be passed to opt_onComplete\n */\nexport const callUserCallback = function (\n // eslint-disable-next-line @typescript-eslint/ban-types\n callback?: Function | null,\n ...varArgs: unknown[]\n) {\n if (typeof callback === 'function') {\n exceptionGuard(() => {\n callback(...varArgs);\n });\n }\n};\n\n/**\n * @returns {boolean} true if we think we're currently being crawled.\n */\nexport const beingCrawled = function (): boolean {\n const userAgent =\n (typeof window === 'object' &&\n window['navigator'] &&\n window['navigator']['userAgent']) ||\n '';\n\n // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we\n // believe to support JavaScript/AJAX rendering.\n // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\n // would have seen the page\" is flaky if we don't treat it as a crawler.\n return (\n userAgent.search(\n /googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i\n ) >= 0\n );\n};\n\n/**\n * Export a property of an object using a getter function.\n */\nexport const exportPropGetter = function (\n object: object,\n name: string,\n fnGet: () => unknown\n) {\n Object.defineProperty(object, name, { get: fnGet });\n};\n\n/**\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\n *\n * It is removed with clearTimeout() as normal.\n *\n * @param fn - Function to run.\n * @param time - Milliseconds to wait before running.\n * @returns The setTimeout() return value.\n */\nexport const setTimeoutNonBlocking = function (\n fn: () => void,\n time: number\n): number | object {\n const timeout: number | object = setTimeout(fn, time);\n // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.\n if (\n typeof timeout === 'number' &&\n // @ts-ignore Is only defined in Deno environments.\n typeof Deno !== 'undefined' &&\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\n Deno['unrefTimer']\n ) {\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\n Deno.unrefTimer(timeout);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else if (typeof timeout === 'object' && (timeout as any)['unref']) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (timeout as any)['unref']();\n }\n\n return timeout;\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, EmulatorMockTokenOptions } from '@firebase/util';\n\nimport { LONG_POLLING, WEBSOCKET } from '../realtime/Constants';\n\nimport { PersistentStorage } from './storage/storage';\nimport { each } from './util/util';\n\nexport interface RepoInfoEmulatorOptions {\n mockUserToken?: string | EmulatorMockTokenOptions;\n}\n\n/**\n * A class that holds metadata about a Repo object\n */\nexport class RepoInfo {\n private _host: string;\n private _domain: string;\n internalHost: string;\n\n /**\n * @param host - Hostname portion of the url for the repo\n * @param secure - Whether or not this repo is accessed over ssl\n * @param namespace - The namespace represented by the repo\n * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).\n * @param nodeAdmin - Whether this instance uses Admin SDK credentials\n * @param persistenceKey - Override the default session persistence storage key\n */\n constructor(\n host: string,\n public readonly secure: boolean,\n public readonly namespace: string,\n public readonly webSocketOnly: boolean,\n public readonly nodeAdmin: boolean = false,\n public readonly persistenceKey: string = '',\n public readonly includeNamespaceInQueryParams: boolean = false,\n public readonly isUsingEmulator: boolean = false,\n public readonly emulatorOptions: RepoInfoEmulatorOptions | null = null\n ) {\n this._host = host.toLowerCase();\n this._domain = this._host.substr(this._host.indexOf('.') + 1);\n this.internalHost =\n (PersistentStorage.get('host:' + host) as string) || this._host;\n }\n\n isCacheableHost(): boolean {\n return this.internalHost.substr(0, 2) === 's-';\n }\n\n isCustomHost() {\n return (\n this._domain !== 'firebaseio.com' &&\n this._domain !== 'firebaseio-demo.com'\n );\n }\n\n get host() {\n return this._host;\n }\n\n set host(newHost: string) {\n if (newHost !== this.internalHost) {\n this.internalHost = newHost;\n if (this.isCacheableHost()) {\n PersistentStorage.set('host:' + this._host, this.internalHost);\n }\n }\n }\n\n toString(): string {\n let str = this.toURLString();\n if (this.persistenceKey) {\n str += '<' + this.persistenceKey + '>';\n }\n return str;\n }\n\n toURLString(): string {\n const protocol = this.secure ? 'https://' : 'http://';\n const query = this.includeNamespaceInQueryParams\n ? `?ns=${this.namespace}`\n : '';\n return `${protocol}${this.host}/${query}`;\n }\n}\n\nfunction repoInfoNeedsQueryParam(repoInfo: RepoInfo): boolean {\n return (\n repoInfo.host !== repoInfo.internalHost ||\n repoInfo.isCustomHost() ||\n repoInfo.includeNamespaceInQueryParams\n );\n}\n\n/**\n * Returns the websocket URL for this repo\n * @param repoInfo - RepoInfo object\n * @param type - of connection\n * @param params - list\n * @returns The URL for this repo\n */\nexport function repoInfoConnectionURL(\n repoInfo: RepoInfo,\n type: string,\n params: { [k: string]: string }\n): string {\n assert(typeof type === 'string', 'typeof type must == string');\n assert(typeof params === 'object', 'typeof params must == object');\n\n let connURL: string;\n if (type === WEBSOCKET) {\n connURL =\n (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';\n } else if (type === LONG_POLLING) {\n connURL =\n (repoInfo.secure ? 'https://' : 'http://') +\n repoInfo.internalHost +\n '/.lp?';\n } else {\n throw new Error('Unknown connection type: ' + type);\n }\n if (repoInfoNeedsQueryParam(repoInfo)) {\n params['ns'] = repoInfo.namespace;\n }\n\n const pairs: string[] = [];\n\n each(params, (key: string, value: string) => {\n pairs.push(key + '=' + value);\n });\n\n return connURL + pairs.join('&');\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { deepCopy, contains } from '@firebase/util';\n\n/**\n * Tracks a collection of stats.\n */\nexport class StatsCollection {\n private counters_: { [k: string]: number } = {};\n\n incrementCounter(name: string, amount: number = 1) {\n if (!contains(this.counters_, name)) {\n this.counters_[name] = 0;\n }\n\n this.counters_[name] += amount;\n }\n\n get() {\n return deepCopy(this.counters_);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../RepoInfo';\n\nimport { StatsCollection } from './StatsCollection';\n\nconst collections: { [k: string]: StatsCollection } = {};\nconst reporters: { [k: string]: unknown } = {};\n\nexport function statsManagerGetCollection(repoInfo: RepoInfo): StatsCollection {\n const hashString = repoInfo.toString();\n\n if (!collections[hashString]) {\n collections[hashString] = new StatsCollection();\n }\n\n return collections[hashString];\n}\n\nexport function statsManagerGetOrCreateReporter(\n repoInfo: RepoInfo,\n creatorFunction: () => T\n): T {\n const hashString = repoInfo.toString();\n\n if (!reporters[hashString]) {\n reporters[hashString] = creatorFunction();\n }\n\n return reporters[hashString] as T;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nexport let SDK_VERSION = '';\n\n/**\n * SDK_VERSION should be set before any database instance is created\n * @internal\n */\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, isNodeSdk, jsonEval, stringify } from '@firebase/util';\n\nimport { RepoInfo, repoInfoConnectionURL } from '../core/RepoInfo';\nimport { StatsCollection } from '../core/stats/StatsCollection';\nimport { statsManagerGetCollection } from '../core/stats/StatsManager';\nimport { PersistentStorage } from '../core/storage/storage';\nimport { logWrapper, splitStringBySize } from '../core/util/util';\nimport { SDK_VERSION } from '../core/version';\n\nimport {\n APPLICATION_ID_PARAM,\n APP_CHECK_TOKEN_PARAM,\n FORGE_DOMAIN_RE,\n FORGE_REF,\n LAST_SESSION_PARAM,\n PROTOCOL_VERSION,\n REFERER_PARAM,\n TRANSPORT_SESSION_PARAM,\n VERSION_PARAM,\n WEBSOCKET\n} from './Constants';\nimport { Transport } from './Transport';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ndeclare const MozWebSocket: any;\n\nconst WEBSOCKET_MAX_FRAME_SIZE = 16384;\nconst WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\n\nlet WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n} else if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\n\nexport function setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\n\n/**\n * Create a new websocket connection with the given callbacks.\n */\nexport class WebSocketConnection implements Transport {\n keepaliveTimer: number | null = null;\n frames: string[] | null = null;\n totalFrames = 0;\n bytesSent = 0;\n bytesReceived = 0;\n connURL: string;\n onDisconnect: (a?: boolean) => void;\n onMessage: (msg: {}) => void;\n mySock: WebSocket | null;\n private log_: (...a: unknown[]) => void;\n private stats_: StatsCollection;\n private everConnected_: boolean;\n private isClosed_: boolean;\n private nodeAdmin: boolean;\n\n /**\n * @param connId identifier for this transport\n * @param repoInfo The info for the websocket endpoint.\n * @param applicationId The Firebase App ID for this project.\n * @param appCheckToken The App Check Token for this client.\n * @param authToken The Auth Token for this client.\n * @param transportSessionId Optional transportSessionId if this is connecting\n * to an existing transport session\n * @param lastSessionId Optional lastSessionId if there was a previous\n * connection\n */\n constructor(\n public connId: string,\n repoInfo: RepoInfo,\n private applicationId?: string,\n private appCheckToken?: string,\n private authToken?: string,\n transportSessionId?: string,\n lastSessionId?: string\n ) {\n this.log_ = logWrapper(this.connId);\n this.stats_ = statsManagerGetCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(\n repoInfo,\n transportSessionId,\n lastSessionId,\n appCheckToken,\n applicationId\n );\n this.nodeAdmin = repoInfo.nodeAdmin;\n }\n\n /**\n * @param repoInfo - The info for the websocket endpoint.\n * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param lastSessionId - Optional lastSessionId if there was a previous connection\n * @returns connection url\n */\n private static connectionURL_(\n repoInfo: RepoInfo,\n transportSessionId?: string,\n lastSessionId?: string,\n appCheckToken?: string,\n applicationId?: string\n ): string {\n const urlParams: { [k: string]: string } = {};\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\n\n if (\n !isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.hostname &&\n FORGE_DOMAIN_RE.test(location.hostname)\n ) {\n urlParams[REFERER_PARAM] = FORGE_REF;\n }\n if (transportSessionId) {\n urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[LAST_SESSION_PARAM] = lastSessionId;\n }\n if (appCheckToken) {\n urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;\n }\n if (applicationId) {\n urlParams[APPLICATION_ID_PARAM] = applicationId;\n }\n\n return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);\n }\n\n /**\n * @param onMessage - Callback when messages arrive\n * @param onDisconnect - Callback with connection lost.\n */\n open(onMessage: (msg: {}) => void, onDisconnect: (a?: boolean) => void) {\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n\n this.log_('Websocket connecting to ' + this.connURL);\n\n this.everConnected_ = false;\n // Assume failure until proven otherwise.\n PersistentStorage.set('previous_websocket_failure', true);\n\n try {\n let options: { [k: string]: object };\n if (isNodeSdk()) {\n const device = this.nodeAdmin ? 'AdminNode' : 'Node';\n // UA Format: Firebase////\n options = {\n headers: {\n 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,\n 'X-Firebase-GMPID': this.applicationId || ''\n }\n };\n\n // If using Node with admin creds, AppCheck-related checks are unnecessary.\n // Note that we send the credentials here even if they aren't admin credentials, which is\n // not a problem.\n // Note that this header is just used to bypass appcheck, and the token should still be sent\n // through the websocket connection once it is established.\n if (this.authToken) {\n options.headers['Authorization'] = `Bearer ${this.authToken}`;\n }\n if (this.appCheckToken) {\n options.headers['X-Firebase-AppCheck'] = this.appCheckToken;\n }\n\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n const env = process['env'];\n const proxy =\n this.connURL.indexOf('wss://') === 0\n ? env['HTTPS_PROXY'] || env['https_proxy']\n : env['HTTP_PROXY'] || env['http_proxy'];\n\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n }\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n } catch (e) {\n this.log_('Error instantiating WebSocket.');\n const error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n return;\n }\n\n this.mySock.onopen = () => {\n this.log_('Websocket connected.');\n this.everConnected_ = true;\n };\n\n this.mySock.onclose = () => {\n this.log_('Websocket connection was disconnected.');\n this.mySock = null;\n this.onClosed_();\n };\n\n this.mySock.onmessage = m => {\n this.handleIncomingFrame(m as {});\n };\n\n this.mySock.onerror = e => {\n this.log_('WebSocket error. Closing connection.');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const error = (e as any).message || (e as any).data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n };\n }\n\n /**\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n */\n start() {}\n\n static forceDisallow_: boolean;\n\n static forceDisallow() {\n WebSocketConnection.forceDisallow_ = true;\n }\n\n static isAvailable(): boolean {\n let isOldAndroid = false;\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n const oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n isOldAndroid = true;\n }\n }\n }\n\n return (\n !isOldAndroid &&\n WebSocketImpl !== null &&\n !WebSocketConnection.forceDisallow_\n );\n }\n\n /**\n * Number of response before we consider the connection \"healthy.\"\n */\n static responsesRequiredToBeHealthy = 2;\n\n /**\n * Time to wait for the connection te become healthy before giving up.\n */\n static healthyTimeout = 30000;\n\n /**\n * Returns true if we previously failed to connect with this transport.\n */\n static previouslyFailed(): boolean {\n // If our persistent storage is actually only in-memory storage,\n // we default to assuming that it previously failed to be safe.\n return (\n PersistentStorage.isInMemoryStorage ||\n PersistentStorage.get('previous_websocket_failure') === true\n );\n }\n\n markConnectionHealthy() {\n PersistentStorage.remove('previous_websocket_failure');\n }\n\n private appendFrame_(data: string) {\n this.frames.push(data);\n if (this.frames.length === this.totalFrames) {\n const fullMess = this.frames.join('');\n this.frames = null;\n const jsonMess = jsonEval(fullMess) as object;\n\n //handle the message\n this.onMessage(jsonMess);\n }\n }\n\n /**\n * @param frameCount - The number of frames we are expecting from the server\n */\n private handleNewFrameCount_(frameCount: number) {\n this.totalFrames = frameCount;\n this.frames = [];\n }\n\n /**\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\n * @returns Any remaining data to be process, or null if there is none\n */\n private extractFrameCount_(data: string): string | null {\n assert(this.frames === null, 'We already have a frame buffer');\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\n if (data.length <= 6) {\n const frameCount = Number(data);\n if (!isNaN(frameCount)) {\n this.handleNewFrameCount_(frameCount);\n return null;\n }\n }\n this.handleNewFrameCount_(1);\n return data;\n }\n\n /**\n * Process a websocket frame that has arrived from the server.\n * @param mess - The frame data\n */\n handleIncomingFrame(mess: { [k: string]: unknown }) {\n if (this.mySock === null) {\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n }\n const data = mess['data'] as string;\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n\n this.resetKeepAlive();\n\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n } else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n const remainingData = this.extractFrameCount_(data);\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n }\n\n /**\n * Send a message to the server\n * @param data - The JSON object to transmit\n */\n send(data: {}) {\n this.resetKeepAlive();\n\n const dataStr = stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n\n //We can only fit a certain amount in each websocket frame, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n\n const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n\n //Send the length header\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n }\n\n //Send the actual data in segments.\n for (let i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n }\n\n private shutdown_() {\n this.isClosed_ = true;\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n }\n\n private onClosed_() {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_();\n\n // since this is an internal close, trigger the close listener\n if (this.onDisconnect) {\n this.onDisconnect(this.everConnected_);\n this.onDisconnect = null;\n }\n }\n }\n\n /**\n * External-facing close handler.\n * Close the websocket and kill the connection.\n */\n close() {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n }\n\n /**\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\n * the last activity.\n */\n resetKeepAlive() {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(() => {\n //If there has been no websocket activity for a while, send a no-op\n if (this.mySock) {\n this.sendString_('0');\n }\n this.resetKeepAlive();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL)) as any;\n }\n\n /**\n * Send a string over the websocket.\n *\n * @param str - String to send.\n */\n private sendString_(str: string) {\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n // calls for some unknown reason. We treat these as an error and disconnect.\n // See https://app.asana.com/0/58926111402292/68021340250410\n try {\n this.mySock.send(str);\n } catch (e) {\n this.log_(\n 'Exception thrown from WebSocket.send():',\n e.message || e.data,\n 'Closing connection.'\n );\n setTimeout(this.onClosed_.bind(this), 0);\n }\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _isFirebaseServerApp } from '@firebase/app'; // eslint-disable-line import/no-extraneous-dependencies\nimport {\n AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { warn } from './util/util';\n\n/**\n * Abstraction around AppCheck's token fetching capabilities.\n */\nexport class AppCheckTokenProvider {\n private appCheck?: FirebaseAppCheckInternal;\n private serverAppAppCheckToken?: string;\n private appName: string;\n constructor(\n app: FirebaseApp,\n private appCheckProvider?: Provider\n ) {\n this.appName = app.name;\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n this.appCheck = appCheckProvider?.getImmediate({ optional: true });\n if (!this.appCheck) {\n appCheckProvider?.get().then(appCheck => (this.appCheck = appCheck));\n }\n }\n\n getToken(forceRefresh?: boolean): Promise {\n if (this.serverAppAppCheckToken) {\n if (forceRefresh) {\n throw new Error(\n 'Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.'\n );\n }\n return Promise.resolve({ token: this.serverAppAppCheckToken });\n }\n if (!this.appCheck) {\n return new Promise((resolve, reject) => {\n // Support delayed initialization of FirebaseAppCheck. This allows our\n // customers to initialize the RTDB SDK before initializing Firebase\n // AppCheck and ensures that all requests are authenticated if a token\n // becomes available before the timeout below expires.\n setTimeout(() => {\n if (this.appCheck) {\n this.getToken(forceRefresh).then(resolve, reject);\n } else {\n resolve(null);\n }\n }, 0);\n });\n }\n return this.appCheck.getToken(forceRefresh);\n }\n\n addTokenChangeListener(listener: AppCheckTokenListener) {\n this.appCheckProvider\n ?.get()\n .then(appCheck => appCheck.addTokenListener(listener));\n }\n\n notifyForInvalidToken(): void {\n warn(\n `Provided AppCheck credentials for the app named \"${this.appName}\" ` +\n 'are invalid. This usually indicates your app was not initialized correctly.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseAuthTokenData } from '@firebase/app-types/private';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { log, warn } from './util/util';\n\nexport interface AuthTokenProvider {\n getToken(forceRefresh: boolean): Promise;\n addTokenChangeListener(listener: (token: string | null) => void): void;\n removeTokenChangeListener(listener: (token: string | null) => void): void;\n notifyForInvalidToken(): void;\n}\n\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nexport class FirebaseAuthTokenProvider implements AuthTokenProvider {\n private auth_: FirebaseAuthInternal | null = null;\n\n constructor(\n private appName_: string,\n private firebaseOptions_: object,\n private authProvider_: Provider\n ) {\n this.auth_ = authProvider_.getImmediate({ optional: true });\n if (!this.auth_) {\n authProvider_.onInit(auth => (this.auth_ = auth));\n }\n }\n\n getToken(forceRefresh: boolean): Promise {\n if (!this.auth_) {\n return new Promise((resolve, reject) => {\n // Support delayed initialization of FirebaseAuth. This allows our\n // customers to initialize the RTDB SDK before initializing Firebase\n // Auth and ensures that all requests are authenticated if a token\n // becomes available before the timeout below expires.\n setTimeout(() => {\n if (this.auth_) {\n this.getToken(forceRefresh).then(resolve, reject);\n } else {\n resolve(null);\n }\n }, 0);\n });\n }\n\n return this.auth_.getToken(forceRefresh).catch(error => {\n // TODO: Need to figure out all the cases this is raised and whether\n // this makes sense.\n if (error && error.code === 'auth/token-not-initialized') {\n log('Got auth/token-not-initialized error. Treating as null token.');\n return null;\n } else {\n return Promise.reject(error);\n }\n });\n }\n\n addTokenChangeListener(listener: (token: string | null) => void): void {\n // TODO: We might want to wrap the listener and call it with no args to\n // avoid a leaky abstraction, but that makes removing the listener harder.\n if (this.auth_) {\n this.auth_.addAuthTokenListener(listener);\n } else {\n this.authProvider_\n .get()\n .then(auth => auth.addAuthTokenListener(listener));\n }\n }\n\n removeTokenChangeListener(listener: (token: string | null) => void): void {\n this.authProvider_\n .get()\n .then(auth => auth.removeAuthTokenListener(listener));\n }\n\n notifyForInvalidToken(): void {\n let errorMessage =\n 'Provided authentication credentials for the app named \"' +\n this.appName_ +\n '\" are invalid. This usually indicates your app was not ' +\n 'initialized correctly. ';\n if ('credential' in this.firebaseOptions_) {\n errorMessage +=\n 'Make sure the \"credential\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n } else if ('serviceAccount' in this.firebaseOptions_) {\n errorMessage +=\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n } else {\n errorMessage +=\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\n 'initializeApp() match the values provided for your app at ' +\n 'https://console.firebase.google.com/.';\n }\n warn(errorMessage);\n }\n}\n\n/* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */\nexport class EmulatorTokenProvider implements AuthTokenProvider {\n /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */\n static OWNER = 'owner';\n\n constructor(private accessToken: string) {}\n\n getToken(forceRefresh: boolean): Promise {\n return Promise.resolve({\n accessToken: this.accessToken\n });\n }\n\n addTokenChangeListener(listener: (token: string | null) => void): void {\n // Invoke the listener immediately to match the behavior in Firebase Auth\n // (see packages/auth/src/auth.js#L1807)\n listener(this.accessToken);\n }\n\n removeTokenChangeListener(listener: (token: string | null) => void): void {}\n\n notifyForInvalidToken(): void {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { exceptionGuard } from '../../core/util/util';\n\n/**\n * This class ensures the packets from the server arrive in order\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\n */\nexport class PacketReceiver {\n pendingResponses: unknown[] = [];\n currentResponseNum = 0;\n closeAfterResponse = -1;\n onClose: (() => void) | null = null;\n\n /**\n * @param onMessage_\n */\n constructor(private onMessage_: (a: {}) => void) {}\n\n closeAfter(responseNum: number, callback: () => void) {\n this.closeAfterResponse = responseNum;\n this.onClose = callback;\n if (this.closeAfterResponse < this.currentResponseNum) {\n this.onClose();\n this.onClose = null;\n }\n }\n\n /**\n * Each message from the server comes with a response number, and an array of data. The responseNumber\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\n * browsers will respond in the same order as the requests we sent\n */\n handleResponse(requestNum: number, data: unknown[]) {\n this.pendingResponses[requestNum] = data;\n while (this.pendingResponses[this.currentResponseNum]) {\n const toProcess = this.pendingResponses[\n this.currentResponseNum\n ] as unknown[];\n delete this.pendingResponses[this.currentResponseNum];\n for (let i = 0; i < toProcess.length; ++i) {\n if (toProcess[i]) {\n exceptionGuard(() => {\n this.onMessage_(toProcess[i]);\n });\n }\n }\n if (this.currentResponseNum === this.closeAfterResponse) {\n if (this.onClose) {\n this.onClose();\n this.onClose = null;\n }\n break;\n }\n this.currentResponseNum++;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Encode, isNodeSdk, stringify } from '@firebase/util';\n\nimport { RepoInfo, repoInfoConnectionURL } from '../core/RepoInfo';\nimport { StatsCollection } from '../core/stats/StatsCollection';\nimport { statsManagerGetCollection } from '../core/stats/StatsManager';\nimport {\n executeWhenDOMReady,\n isChromeExtensionContentScript,\n isWindowsStoreApp,\n log,\n logWrapper,\n LUIDGenerator,\n splitStringBySize\n} from '../core/util/util';\n\nimport {\n APP_CHECK_TOKEN_PARAM,\n APPLICATION_ID_PARAM,\n FORGE_DOMAIN_RE,\n FORGE_REF,\n LAST_SESSION_PARAM,\n LONG_POLLING,\n PROTOCOL_VERSION,\n REFERER_PARAM,\n TRANSPORT_SESSION_PARAM,\n VERSION_PARAM\n} from './Constants';\nimport { PacketReceiver } from './polling/PacketReceiver';\nimport { Transport } from './Transport';\n\n// URL query parameters associated with longpolling\nexport const FIREBASE_LONGPOLL_START_PARAM = 'start';\nexport const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\nexport const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\nexport const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\nexport const FIREBASE_LONGPOLL_ID_PARAM = 'id';\nexport const FIREBASE_LONGPOLL_PW_PARAM = 'pw';\nexport const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\nexport const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\nexport const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\nexport const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\nexport const FIREBASE_LONGPOLL_DATA_PARAM = 'd';\nexport const FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = 'disconn';\nexport const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\n\n//Data size constants.\n//TODO: Perf: the maximum length actually differs from browser to browser.\n// We should check what browser we're on and set accordingly.\nconst MAX_URL_DATA_SIZE = 1870;\nconst SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\nconst MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\n\n/**\n * Keepalive period\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\n * length of 30 seconds that we can't exceed.\n */\nconst KEEPALIVE_REQUEST_INTERVAL = 25000;\n\n/**\n * How long to wait before aborting a long-polling connection attempt.\n */\nconst LP_CONNECT_TIMEOUT = 30000;\n\n/**\n * This class manages a single long-polling connection.\n */\nexport class BrowserPollConnection implements Transport {\n bytesSent = 0;\n bytesReceived = 0;\n urlFn: (params: object) => string;\n scriptTagHolder: FirebaseIFrameScriptHolder;\n myDisconnFrame: HTMLIFrameElement;\n curSegmentNum: number;\n myPacketOrderer: PacketReceiver;\n id: string;\n password: string;\n private log_: (...a: unknown[]) => void;\n private stats_: StatsCollection;\n private everConnected_ = false;\n private isClosed_: boolean;\n private connectTimeoutTimer_: number | null;\n private onDisconnect_: ((a?: boolean) => void) | null;\n\n /**\n * @param connId An identifier for this connection, used for logging\n * @param repoInfo The info for the endpoint to send data to.\n * @param applicationId The Firebase App ID for this project.\n * @param appCheckToken The AppCheck token for this client.\n * @param authToken The AuthToken to use for this connection.\n * @param transportSessionId Optional transportSessionid if we are\n * reconnecting for an existing transport session\n * @param lastSessionId Optional lastSessionId if the PersistentConnection has\n * already created a connection previously\n */\n constructor(\n public connId: string,\n public repoInfo: RepoInfo,\n private applicationId?: string,\n private appCheckToken?: string,\n private authToken?: string,\n public transportSessionId?: string,\n public lastSessionId?: string\n ) {\n this.log_ = logWrapper(connId);\n this.stats_ = statsManagerGetCollection(repoInfo);\n this.urlFn = (params: { [k: string]: string }) => {\n // Always add the token if we have one.\n if (this.appCheckToken) {\n params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\n }\n return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);\n };\n }\n\n /**\n * @param onMessage - Callback when messages arrive\n * @param onDisconnect - Callback with connection lost.\n */\n open(onMessage: (msg: {}) => void, onDisconnect: (a?: boolean) => void) {\n this.curSegmentNum = 0;\n this.onDisconnect_ = onDisconnect;\n this.myPacketOrderer = new PacketReceiver(onMessage);\n this.isClosed_ = false;\n\n this.connectTimeoutTimer_ = setTimeout(() => {\n this.log_('Timed out trying to connect.');\n // Make sure we clear the host cache\n this.onClosed_();\n this.connectTimeoutTimer_ = null;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(LP_CONNECT_TIMEOUT)) as any;\n\n // Ensure we delay the creation of the iframe until the DOM is loaded.\n executeWhenDOMReady(() => {\n if (this.isClosed_) {\n return;\n }\n\n //Set up a callback that gets triggered once a connection is set up.\n this.scriptTagHolder = new FirebaseIFrameScriptHolder(\n (...args) => {\n const [command, arg1, arg2, arg3, arg4] = args;\n this.incrementIncomingBytes_(args);\n if (!this.scriptTagHolder) {\n return; // we closed the connection.\n }\n\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n this.everConnected_ = true;\n if (command === FIREBASE_LONGPOLL_START_PARAM) {\n this.id = arg1 as string;\n this.password = arg2 as string;\n } else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {\n // Don't clear the host cache. We got a response from the server, so we know it's reachable\n if (arg1) {\n // We aren't expecting any more data (other than what the server's already in the process of sending us\n // through our already open polls), so don't send any more.\n this.scriptTagHolder.sendNewPolls = false;\n\n // arg1 in this case is the last response number sent by the server. We should try to receive\n // all of the responses up to this one before closing\n this.myPacketOrderer.closeAfter(arg1 as number, () => {\n this.onClosed_();\n });\n } else {\n this.onClosed_();\n }\n } else {\n throw new Error('Unrecognized command received: ' + command);\n }\n },\n (...args) => {\n const [pN, data] = args;\n this.incrementIncomingBytes_(args);\n this.myPacketOrderer.handleResponse(pN as number, data as unknown[]);\n },\n () => {\n this.onClosed_();\n },\n this.urlFn\n );\n\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\n //from cache.\n const urlParams: { [k: string]: string | number } = {};\n urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(\n Math.random() * 100000000\n );\n if (this.scriptTagHolder.uniqueCallbackIdentifier) {\n urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =\n this.scriptTagHolder.uniqueCallbackIdentifier;\n }\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\n if (this.transportSessionId) {\n urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;\n }\n if (this.lastSessionId) {\n urlParams[LAST_SESSION_PARAM] = this.lastSessionId;\n }\n if (this.applicationId) {\n urlParams[APPLICATION_ID_PARAM] = this.applicationId;\n }\n if (this.appCheckToken) {\n urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\n }\n if (\n typeof location !== 'undefined' &&\n location.hostname &&\n FORGE_DOMAIN_RE.test(location.hostname)\n ) {\n urlParams[REFERER_PARAM] = FORGE_REF;\n }\n const connectURL = this.urlFn(urlParams);\n this.log_('Connecting via long-poll to ' + connectURL);\n this.scriptTagHolder.addTag(connectURL, () => {\n /* do nothing */\n });\n });\n }\n\n /**\n * Call this when a handshake has completed successfully and we want to consider the connection established\n */\n start() {\n this.scriptTagHolder.startLongPoll(this.id, this.password);\n this.addDisconnectPingFrame(this.id, this.password);\n }\n\n static forceAllow_: boolean;\n\n /**\n * Forces long polling to be considered as a potential transport\n */\n static forceAllow() {\n BrowserPollConnection.forceAllow_ = true;\n }\n\n static forceDisallow_: boolean;\n\n /**\n * Forces longpolling to not be considered as a potential transport\n */\n static forceDisallow() {\n BrowserPollConnection.forceDisallow_ = true;\n }\n\n // Static method, use string literal so it can be accessed in a generic way\n static isAvailable() {\n if (isNodeSdk()) {\n return false;\n } else if (BrowserPollConnection.forceAllow_) {\n return true;\n } else {\n // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\n // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\n return (\n !BrowserPollConnection.forceDisallow_ &&\n typeof document !== 'undefined' &&\n document.createElement != null &&\n !isChromeExtensionContentScript() &&\n !isWindowsStoreApp()\n );\n }\n }\n\n /**\n * No-op for polling\n */\n markConnectionHealthy() {}\n\n /**\n * Stops polling and cleans up the iframe\n */\n private shutdown_() {\n this.isClosed_ = true;\n\n if (this.scriptTagHolder) {\n this.scriptTagHolder.close();\n this.scriptTagHolder = null;\n }\n\n //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\n if (this.myDisconnFrame) {\n document.body.removeChild(this.myDisconnFrame);\n this.myDisconnFrame = null;\n }\n\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n }\n\n /**\n * Triggered when this transport is closed\n */\n private onClosed_() {\n if (!this.isClosed_) {\n this.log_('Longpoll is closing itself');\n this.shutdown_();\n\n if (this.onDisconnect_) {\n this.onDisconnect_(this.everConnected_);\n this.onDisconnect_ = null;\n }\n }\n }\n\n /**\n * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\n * that we've left.\n */\n close() {\n if (!this.isClosed_) {\n this.log_('Longpoll is being closed.');\n this.shutdown_();\n }\n }\n\n /**\n * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\n * broken into chunks (since URLs have a small maximum length).\n * @param data - The JSON data to transmit.\n */\n send(data: {}) {\n const dataStr = stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n\n //first, lets get the base64-encoded data\n const base64data = base64Encode(dataStr);\n\n //We can only fit a certain amount in each URL, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\n\n //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\n //of segments so that we can reassemble the packet on the server.\n for (let i = 0; i < dataSegs.length; i++) {\n this.scriptTagHolder.enqueueSegment(\n this.curSegmentNum,\n dataSegs.length,\n dataSegs[i]\n );\n this.curSegmentNum++;\n }\n }\n\n /**\n * This is how we notify the server that we're leaving.\n * We aren't able to send requests with DHTML on a window close event, but we can\n * trigger XHR requests in some browsers (everything but Opera basically).\n */\n addDisconnectPingFrame(id: string, pw: string) {\n if (isNodeSdk()) {\n return;\n }\n this.myDisconnFrame = document.createElement('iframe');\n const urlParams: { [k: string]: string } = {};\n urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;\n this.myDisconnFrame.src = this.urlFn(urlParams);\n this.myDisconnFrame.style.display = 'none';\n\n document.body.appendChild(this.myDisconnFrame);\n }\n\n /**\n * Used to track the bytes received by this client\n */\n private incrementIncomingBytes_(args: unknown) {\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\n const bytesReceived = stringify(args).length;\n this.bytesReceived += bytesReceived;\n this.stats_.incrementCounter('bytes_received', bytesReceived);\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport interface IFrameElement extends HTMLIFrameElement {\n doc: Document;\n}\n\n/*********************************************************************************************\n * A wrapper around an iframe that is used as a long-polling script holder.\n *********************************************************************************************/\nexport class FirebaseIFrameScriptHolder {\n //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\n //problems in some browsers.\n outstandingRequests = new Set();\n\n //A queue of the pending segments waiting for transmission to the server.\n pendingSegs: Array<{ seg: number; ts: number; d: unknown }> = [];\n\n //A serial number. We use this for two things:\n // 1) A way to ensure the browser doesn't cache responses to polls\n // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\n // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\n // JSONP code in the order it was added to the iframe.\n currentSerial = Math.floor(Math.random() * 100000000);\n\n // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\n // incoming data from the server that we're waiting for).\n sendNewPolls = true;\n\n uniqueCallbackIdentifier: number;\n myIFrame: IFrameElement;\n alive: boolean;\n myID: string;\n myPW: string;\n commandCB: (command: string, ...args: unknown[]) => void;\n onMessageCB: (...args: unknown[]) => void;\n\n /**\n * @param commandCB - The callback to be called when control commands are received from the server.\n * @param onMessageCB - The callback to be triggered when responses arrive from the server.\n * @param onDisconnect - The callback to be triggered when this tag holder is closed\n * @param urlFn - A function that provides the URL of the endpoint to send data to.\n */\n constructor(\n commandCB: (command: string, ...args: unknown[]) => void,\n onMessageCB: (...args: unknown[]) => void,\n public onDisconnect: () => void,\n public urlFn: (a: object) => string\n ) {\n if (!isNodeSdk()) {\n //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\n //iframes where we put the long-polling script tags. We have two callbacks:\n // 1) Command Callback - Triggered for control issues, like starting a connection.\n // 2) Message Callback - Triggered when new data arrives.\n this.uniqueCallbackIdentifier = LUIDGenerator();\n window[\n FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier\n ] = commandCB;\n window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =\n onMessageCB;\n\n //Create an iframe for us to add script tags to.\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\n\n // Set the iframe's contents.\n let script = '';\n // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\n // for ie9, but ie8 needs to do it again in the document itself.\n if (\n this.myIFrame.src &&\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:'\n ) {\n const currentDomain = document.domain;\n script = '';\n }\n const iframeContents = '' + script + '';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n } catch (e) {\n log('frame writing exception');\n if (e.stack) {\n log(e.stack);\n }\n log(e);\n }\n } else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n\n /**\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\n * actually use.\n */\n private static createIFrame_(): IFrameElement {\n const iframe = document.createElement('iframe') as IFrameElement;\n iframe.style.display = 'none';\n\n // This is necessary in order to initialize the document inside the iframe\n if (document.body) {\n document.body.appendChild(iframe);\n try {\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n const a = iframe.contentWindow.document;\n if (!a) {\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n log('No IE domain setting required');\n }\n } catch (e) {\n const domain = document.domain;\n iframe.src =\n \"javascript:void((function(){document.open();document.domain='\" +\n domain +\n \"';document.close();})())\";\n }\n } else {\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n // never gets hit.\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n }\n\n // Get the document of the iframe in a browser-specific way.\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n } else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else if ((iframe as any).document) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n iframe.doc = (iframe as any).document; //others?\n }\n\n return iframe;\n }\n\n /**\n * Cancel all outstanding queries and remove the frame.\n */\n close() {\n //Mark this iframe as dead, so no new requests are sent.\n this.alive = false;\n\n if (this.myIFrame) {\n //We have to actually remove all of the html inside this iframe before removing it from the\n //window, or IE will continue loading and executing the script tags we've already added, which\n //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.\n this.myIFrame.doc.body.textContent = '';\n setTimeout(() => {\n if (this.myIFrame !== null) {\n document.body.removeChild(this.myIFrame);\n this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n\n // Protect from being called recursively.\n const onDisconnect = this.onDisconnect;\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\n }\n\n /**\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\n * @param id - The ID of this connection\n * @param pw - The password for this connection\n */\n startLongPoll(id: string, pw: string) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true;\n\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n while (this.newRequest_()) {}\n }\n\n /**\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\n * too many outstanding requests and we are still alive.\n *\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\n * needed.\n */\n private newRequest_() {\n // We keep one outstanding request open all the time to receive data, but if we need to send data\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\n // close the old request.\n if (\n this.alive &&\n this.sendNewPolls &&\n this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)\n ) {\n //construct our url\n this.currentSerial++;\n const urlParams: { [k: string]: string | number } = {};\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n let theURL = this.urlFn(urlParams);\n //Now add as much data as we can.\n let curDataString = '';\n let i = 0;\n\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n const nextSeg = this.pendingSegs[0];\n if (\n (nextSeg.d as unknown[]).length +\n SEG_HEADER_SIZE +\n curDataString.length <=\n MAX_URL_DATA_SIZE\n ) {\n //great, the segment will fit. Lets append it.\n const theSeg = this.pendingSegs.shift();\n curDataString =\n curDataString +\n '&' +\n FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n i +\n '=' +\n theSeg.seg +\n '&' +\n FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n i +\n '=' +\n theSeg.ts +\n '&' +\n FIREBASE_LONGPOLL_DATA_PARAM +\n i +\n '=' +\n theSeg.d;\n i++;\n } else {\n break;\n }\n }\n\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Queue a packet for transmission to the server.\n * @param segnum - A sequential id for this packet segment used for reassembly\n * @param totalsegs - The total number of segments in this packet\n * @param data - The data for this segment.\n */\n enqueueSegment(segnum: number, totalsegs: number, data: unknown) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n\n //send the data immediately if there isn't already data being transmitted, unless\n //startLongPoll hasn't been called yet.\n if (this.alive) {\n this.newRequest_();\n }\n }\n\n /**\n * Add a script tag for a regular long-poll request.\n * @param url - The URL of the script tag.\n * @param serial - The serial number of the request.\n */\n private addLongPollTag_(url: string, serial: number) {\n //remember that we sent this request.\n this.outstandingRequests.add(serial);\n\n const doNewRequest = () => {\n this.outstandingRequests.delete(serial);\n this.newRequest_();\n };\n\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n const keepaliveTimeout = setTimeout(\n doNewRequest,\n Math.floor(KEEPALIVE_REQUEST_INTERVAL)\n );\n\n const readyStateCB = () => {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout);\n\n // Trigger a new request so we can continue receiving data.\n doNewRequest();\n };\n\n this.addTag(url, readyStateCB);\n }\n\n /**\n * Add an arbitrary script tag to the iframe.\n * @param url - The URL for the script tag source.\n * @param loadCB - A callback to be triggered once the script has loaded.\n */\n addTag(url: string, loadCB: () => void) {\n if (isNodeSdk()) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any).doNodeLongPoll(url, loadCB);\n } else {\n setTimeout(() => {\n try {\n // if we're already closed, don't add this poll\n if (!this.sendNewPolls) {\n return;\n }\n const newScript = this.myIFrame.doc.createElement('script');\n newScript.type = 'text/javascript';\n newScript.async = true;\n newScript.src = url;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n newScript.onload = (newScript as any).onreadystatechange =\n function () {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const rstate = (newScript as any).readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n newScript.onload = (newScript as any).onreadystatechange = null;\n if (newScript.parentNode) {\n newScript.parentNode.removeChild(newScript);\n }\n loadCB();\n }\n };\n newScript.onerror = () => {\n log('Long-poll script failed to load: ' + url);\n this.sendNewPolls = false;\n this.close();\n };\n this.myIFrame.doc.body.appendChild(newScript);\n } catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../core/RepoInfo';\nimport { warn } from '../core/util/util';\n\nimport { BrowserPollConnection } from './BrowserPollConnection';\nimport { TransportConstructor } from './Transport';\nimport { WebSocketConnection } from './WebSocketConnection';\n\n/**\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\n * lifecycle.\n *\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\n * they are available.\n */\nexport class TransportManager {\n private transports_: TransportConstructor[];\n\n // Keeps track of whether the TransportManager has already chosen a transport to use\n static globalTransportInitialized_ = false;\n\n static get ALL_TRANSPORTS() {\n return [BrowserPollConnection, WebSocketConnection];\n }\n\n /**\n * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after\n * TransportManager has already set up transports_\n */\n static get IS_TRANSPORT_INITIALIZED() {\n return this.globalTransportInitialized_;\n }\n\n /**\n * @param repoInfo - Metadata around the namespace we're connecting to\n */\n constructor(repoInfo: RepoInfo) {\n this.initTransports_(repoInfo);\n }\n\n private initTransports_(repoInfo: RepoInfo) {\n const isWebSocketsAvailable: boolean =\n WebSocketConnection && WebSocketConnection['isAvailable']();\n let isSkipPollConnection =\n isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();\n\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable) {\n warn(\n \"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\"\n );\n }\n\n isSkipPollConnection = true;\n }\n\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection];\n } else {\n const transports = (this.transports_ = [] as TransportConstructor[]);\n for (const transport of TransportManager.ALL_TRANSPORTS) {\n if (transport && transport['isAvailable']()) {\n transports.push(transport);\n }\n }\n TransportManager.globalTransportInitialized_ = true;\n }\n }\n\n /**\n * @returns The constructor for the initial transport to use\n */\n initialTransport(): TransportConstructor {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n } else {\n throw new Error('No transports available');\n }\n }\n\n /**\n * @returns The constructor for the next transport, or null\n */\n upgradeTransport(): TransportConstructor | null {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n } else {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../core/RepoInfo';\nimport { PersistentStorage } from '../core/storage/storage';\nimport { Indexable } from '../core/util/misc';\nimport {\n error,\n logWrapper,\n requireKey,\n setTimeoutNonBlocking,\n warn\n} from '../core/util/util';\n\nimport { PROTOCOL_VERSION } from './Constants';\nimport { Transport, TransportConstructor } from './Transport';\nimport { TransportManager } from './TransportManager';\n\n// Abort upgrade attempt if it takes longer than 60s.\nconst UPGRADE_TIMEOUT = 60000;\n\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\nconst DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\n\n// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\n// but we've sent/received enough bytes, we don't cancel the connection.\nconst BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\nconst BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\n\nconst enum RealtimeState {\n CONNECTING,\n CONNECTED,\n DISCONNECTED\n}\n\nconst MESSAGE_TYPE = 't';\nconst MESSAGE_DATA = 'd';\nconst CONTROL_SHUTDOWN = 's';\nconst CONTROL_RESET = 'r';\nconst CONTROL_ERROR = 'e';\nconst CONTROL_PONG = 'o';\nconst SWITCH_ACK = 'a';\nconst END_TRANSMISSION = 'n';\nconst PING = 'p';\n\nconst SERVER_HELLO = 'h';\n\n/**\n * Creates a new real-time connection to the server using whichever method works\n * best in the current browser.\n */\nexport class Connection {\n connectionCount = 0;\n pendingDataMessages: unknown[] = [];\n sessionId: string;\n\n private conn_: Transport;\n private healthyTimeout_: number;\n private isHealthy_: boolean;\n private log_: (...args: unknown[]) => void;\n private primaryResponsesRequired_: number;\n private rx_: Transport;\n private secondaryConn_: Transport;\n private secondaryResponsesRequired_: number;\n private state_ = RealtimeState.CONNECTING;\n private transportManager_: TransportManager;\n private tx_: Transport;\n\n /**\n * @param id - an id for this connection\n * @param repoInfo_ - the info for the endpoint to connect to\n * @param applicationId_ - the Firebase App ID for this project\n * @param appCheckToken_ - The App Check Token for this device.\n * @param authToken_ - The auth token for this session.\n * @param onMessage_ - the callback to be triggered when a server-push message arrives\n * @param onReady_ - the callback to be triggered when this connection is ready to send messages.\n * @param onDisconnect_ - the callback to be triggered when a connection was lost\n * @param onKill_ - the callback to be triggered when this connection has permanently shut down.\n * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\n */\n constructor(\n public id: string,\n private repoInfo_: RepoInfo,\n private applicationId_: string | undefined,\n private appCheckToken_: string | undefined,\n private authToken_: string | undefined,\n private onMessage_: (a: {}) => void,\n private onReady_: (a: number, b: string) => void,\n private onDisconnect_: () => void,\n private onKill_: (a: string) => void,\n public lastSessionId?: string\n ) {\n this.log_ = logWrapper('c:' + this.id + ':');\n this.transportManager_ = new TransportManager(repoInfo_);\n this.log_('Connection created');\n this.start_();\n }\n\n /**\n * Starts a connection attempt\n */\n private start_(): void {\n const conn = this.transportManager_.initialTransport();\n this.conn_ = new conn(\n this.nextTransportId_(),\n this.repoInfo_,\n this.applicationId_,\n this.appCheckToken_,\n this.authToken_,\n null,\n this.lastSessionId\n );\n\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\n\n const onMessageReceived = this.connReceiver_(this.conn_);\n const onConnectionLost = this.disconnReceiver_(this.conn_);\n this.tx_ = this.conn_;\n this.rx_ = this.conn_;\n this.secondaryConn_ = null;\n this.isHealthy_ = false;\n\n /*\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\n * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\n * still have the context of your originating frame.\n */\n setTimeout(() => {\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\n this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);\n }, Math.floor(0));\n\n const healthyTimeoutMS = conn['healthyTimeout'] || 0;\n if (healthyTimeoutMS > 0) {\n this.healthyTimeout_ = setTimeoutNonBlocking(() => {\n this.healthyTimeout_ = null;\n if (!this.isHealthy_) {\n if (\n this.conn_ &&\n this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE\n ) {\n this.log_(\n 'Connection exceeded healthy timeout but has received ' +\n this.conn_.bytesReceived +\n ' bytes. Marking connection healthy.'\n );\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n } else if (\n this.conn_ &&\n this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE\n ) {\n this.log_(\n 'Connection exceeded healthy timeout but has sent ' +\n this.conn_.bytesSent +\n ' bytes. Leaving connection alive.'\n );\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\n // the server.\n } else {\n this.log_('Closing unhealthy connection after timeout.');\n this.close();\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(healthyTimeoutMS)) as any;\n }\n }\n\n private nextTransportId_(): string {\n return 'c:' + this.id + ':' + this.connectionCount++;\n }\n\n private disconnReceiver_(conn) {\n return everConnected => {\n if (conn === this.conn_) {\n this.onConnectionLost_(everConnected);\n } else if (conn === this.secondaryConn_) {\n this.log_('Secondary connection lost.');\n this.onSecondaryConnectionLost_();\n } else {\n this.log_('closing an old connection');\n }\n };\n }\n\n private connReceiver_(conn: Transport) {\n return (message: Indexable) => {\n if (this.state_ !== RealtimeState.DISCONNECTED) {\n if (conn === this.rx_) {\n this.onPrimaryMessageReceived_(message);\n } else if (conn === this.secondaryConn_) {\n this.onSecondaryMessageReceived_(message);\n } else {\n this.log_('message on old connection');\n }\n }\n };\n }\n\n /**\n * @param dataMsg - An arbitrary data message to be sent to the server\n */\n sendRequest(dataMsg: object) {\n // wrap in a data message envelope and send it on\n const msg = { t: 'd', d: dataMsg };\n this.sendData_(msg);\n }\n\n tryCleanupConnection() {\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\n this.log_(\n 'cleaning up and promoting a connection: ' + this.secondaryConn_.connId\n );\n this.conn_ = this.secondaryConn_;\n this.secondaryConn_ = null;\n // the server will shutdown the old connection\n }\n }\n\n private onSecondaryControl_(controlData: { [k: string]: unknown }) {\n if (MESSAGE_TYPE in controlData) {\n const cmd = controlData[MESSAGE_TYPE] as string;\n if (cmd === SWITCH_ACK) {\n this.upgradeIfSecondaryHealthy_();\n } else if (cmd === CONTROL_RESET) {\n // Most likely the session wasn't valid. Abandon the switch attempt\n this.log_('Got a reset on secondary, closing it');\n this.secondaryConn_.close();\n // If we were already using this connection for something, than we need to fully close\n if (\n this.tx_ === this.secondaryConn_ ||\n this.rx_ === this.secondaryConn_\n ) {\n this.close();\n }\n } else if (cmd === CONTROL_PONG) {\n this.log_('got pong on secondary.');\n this.secondaryResponsesRequired_--;\n this.upgradeIfSecondaryHealthy_();\n }\n }\n }\n\n private onSecondaryMessageReceived_(parsedData: Indexable) {\n const layer: string = requireKey('t', parsedData) as string;\n const data: unknown = requireKey('d', parsedData);\n if (layer === 'c') {\n this.onSecondaryControl_(data as Indexable);\n } else if (layer === 'd') {\n // got a data message, but we're still second connection. Need to buffer it up\n this.pendingDataMessages.push(data);\n } else {\n throw new Error('Unknown protocol layer: ' + layer);\n }\n }\n\n private upgradeIfSecondaryHealthy_() {\n if (this.secondaryResponsesRequired_ <= 0) {\n this.log_('Secondary connection is healthy.');\n this.isHealthy_ = true;\n this.secondaryConn_.markConnectionHealthy();\n this.proceedWithUpgrade_();\n } else {\n // Send a ping to make sure the connection is healthy.\n this.log_('sending ping on secondary.');\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\n }\n }\n\n private proceedWithUpgrade_() {\n // tell this connection to consider itself open\n this.secondaryConn_.start();\n // send ack\n this.log_('sending client ack on secondary');\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\n\n // send end packet on primary transport, switch to sending on this one\n // can receive on this one, buffer responses until end received on primary transport\n this.log_('Ending transmission on primary');\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\n this.tx_ = this.secondaryConn_;\n\n this.tryCleanupConnection();\n }\n\n private onPrimaryMessageReceived_(parsedData: { [k: string]: unknown }) {\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\n const layer: string = requireKey('t', parsedData) as string;\n const data: unknown = requireKey('d', parsedData);\n if (layer === 'c') {\n this.onControl_(data as { [k: string]: unknown });\n } else if (layer === 'd') {\n this.onDataMessage_(data);\n }\n }\n\n private onDataMessage_(message: unknown) {\n this.onPrimaryResponse_();\n\n // We don't do anything with data messages, just kick them up a level\n this.onMessage_(message);\n }\n\n private onPrimaryResponse_() {\n if (!this.isHealthy_) {\n this.primaryResponsesRequired_--;\n if (this.primaryResponsesRequired_ <= 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n }\n }\n }\n\n private onControl_(controlData: { [k: string]: unknown }) {\n const cmd: string = requireKey(MESSAGE_TYPE, controlData) as string;\n if (MESSAGE_DATA in controlData) {\n const payload = controlData[MESSAGE_DATA];\n if (cmd === SERVER_HELLO) {\n const handshakePayload = {\n ...(payload as {\n ts: number;\n v: string;\n h: string;\n s: string;\n })\n };\n if (this.repoInfo_.isUsingEmulator) {\n // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes.\n handshakePayload.h = this.repoInfo_.host;\n }\n this.onHandshake_(handshakePayload);\n } else if (cmd === END_TRANSMISSION) {\n this.log_('recvd end transmission on primary');\n this.rx_ = this.secondaryConn_;\n for (let i = 0; i < this.pendingDataMessages.length; ++i) {\n this.onDataMessage_(this.pendingDataMessages[i]);\n }\n this.pendingDataMessages = [];\n this.tryCleanupConnection();\n } else if (cmd === CONTROL_SHUTDOWN) {\n // This was previously the 'onKill' callback passed to the lower-level connection\n // payload in this case is the reason for the shutdown. Generally a human-readable error\n this.onConnectionShutdown_(payload as string);\n } else if (cmd === CONTROL_RESET) {\n // payload in this case is the host we should contact\n this.onReset_(payload as string);\n } else if (cmd === CONTROL_ERROR) {\n error('Server Error: ' + payload);\n } else if (cmd === CONTROL_PONG) {\n this.log_('got pong on primary.');\n this.onPrimaryResponse_();\n this.sendPingOnPrimaryIfNecessary_();\n } else {\n error('Unknown control packet command: ' + cmd);\n }\n }\n }\n\n /**\n * @param handshake - The handshake data returned from the server\n */\n private onHandshake_(handshake: {\n ts: number;\n v: string;\n h: string;\n s: string;\n }): void {\n const timestamp = handshake.ts;\n const version = handshake.v;\n const host = handshake.h;\n this.sessionId = handshake.s;\n this.repoInfo_.host = host;\n // if we've already closed the connection, then don't bother trying to progress further\n if (this.state_ === RealtimeState.CONNECTING) {\n this.conn_.start();\n this.onConnectionEstablished_(this.conn_, timestamp);\n if (PROTOCOL_VERSION !== version) {\n warn('Protocol version mismatch detected');\n }\n // TODO: do we want to upgrade? when? maybe a delay?\n this.tryStartUpgrade_();\n }\n }\n\n private tryStartUpgrade_() {\n const conn = this.transportManager_.upgradeTransport();\n if (conn) {\n this.startUpgrade_(conn);\n }\n }\n\n private startUpgrade_(conn: TransportConstructor) {\n this.secondaryConn_ = new conn(\n this.nextTransportId_(),\n this.repoInfo_,\n this.applicationId_,\n this.appCheckToken_,\n this.authToken_,\n this.sessionId\n );\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.secondaryResponsesRequired_ =\n conn['responsesRequiredToBeHealthy'] || 0;\n\n const onMessage = this.connReceiver_(this.secondaryConn_);\n const onDisconnect = this.disconnReceiver_(this.secondaryConn_);\n this.secondaryConn_.open(onMessage, onDisconnect);\n\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\n setTimeoutNonBlocking(() => {\n if (this.secondaryConn_) {\n this.log_('Timed out trying to upgrade.');\n this.secondaryConn_.close();\n }\n }, Math.floor(UPGRADE_TIMEOUT));\n }\n\n private onReset_(host: string) {\n this.log_('Reset packet received. New host: ' + host);\n this.repoInfo_.host = host;\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\n // We don't currently support resets after the connection has already been established\n if (this.state_ === RealtimeState.CONNECTED) {\n this.close();\n } else {\n // Close whatever connections we have open and start again.\n this.closeConnections_();\n this.start_();\n }\n }\n\n private onConnectionEstablished_(conn: Transport, timestamp: number) {\n this.log_('Realtime connection established.');\n this.conn_ = conn;\n this.state_ = RealtimeState.CONNECTED;\n\n if (this.onReady_) {\n this.onReady_(timestamp, this.sessionId);\n this.onReady_ = null;\n }\n\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\n // send some pings.\n if (this.primaryResponsesRequired_ === 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n } else {\n setTimeoutNonBlocking(() => {\n this.sendPingOnPrimaryIfNecessary_();\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\n }\n }\n\n private sendPingOnPrimaryIfNecessary_() {\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\n if (!this.isHealthy_ && this.state_ === RealtimeState.CONNECTED) {\n this.log_('sending ping on primary.');\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\n }\n }\n\n private onSecondaryConnectionLost_() {\n const conn = this.secondaryConn_;\n this.secondaryConn_ = null;\n if (this.tx_ === conn || this.rx_ === conn) {\n // we are relying on this connection already in some capacity. Therefore, a failure is real\n this.close();\n }\n }\n\n /**\n * @param everConnected - Whether or not the connection ever reached a server. Used to determine if\n * we should flush the host cache\n */\n private onConnectionLost_(everConnected: boolean) {\n this.conn_ = null;\n\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\n if (!everConnected && this.state_ === RealtimeState.CONNECTING) {\n this.log_('Realtime connection failed.');\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\n if (this.repoInfo_.isCacheableHost()) {\n PersistentStorage.remove('host:' + this.repoInfo_.host);\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\n this.repoInfo_.internalHost = this.repoInfo_.host;\n }\n } else if (this.state_ === RealtimeState.CONNECTED) {\n this.log_('Realtime connection lost.');\n }\n\n this.close();\n }\n\n private onConnectionShutdown_(reason: string) {\n this.log_('Connection shutdown command received. Shutting down...');\n\n if (this.onKill_) {\n this.onKill_(reason);\n this.onKill_ = null;\n }\n\n // We intentionally don't want to fire onDisconnect (kill is a different case),\n // so clear the callback.\n this.onDisconnect_ = null;\n\n this.close();\n }\n\n private sendData_(data: object) {\n if (this.state_ !== RealtimeState.CONNECTED) {\n throw 'Connection is not connected';\n } else {\n this.tx_.send(data);\n }\n }\n\n /**\n * Cleans up this connection, calling the appropriate callbacks\n */\n close() {\n if (this.state_ !== RealtimeState.DISCONNECTED) {\n this.log_('Closing realtime connection.');\n this.state_ = RealtimeState.DISCONNECTED;\n\n this.closeConnections_();\n\n if (this.onDisconnect_) {\n this.onDisconnect_();\n this.onDisconnect_ = null;\n }\n }\n }\n\n private closeConnections_() {\n this.log_('Shutting down all connections');\n if (this.conn_) {\n this.conn_.close();\n this.conn_ = null;\n }\n\n if (this.secondaryConn_) {\n this.secondaryConn_.close();\n this.secondaryConn_ = null;\n }\n\n if (this.healthyTimeout_) {\n clearTimeout(this.healthyTimeout_);\n this.healthyTimeout_ = null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QueryContext } from './view/EventRegistration';\n\n/**\n * Interface defining the set of actions that can be performed against the Firebase server\n * (basically corresponds to our wire protocol).\n *\n * @interface\n */\nexport abstract class ServerActions {\n abstract listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ): void;\n\n /**\n * Remove a listen.\n */\n abstract unlisten(query: QueryContext, tag: number | null): void;\n\n /**\n * Get the server value satisfying this query.\n */\n abstract get(query: QueryContext): Promise;\n\n put(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void,\n hash?: string\n ) {}\n\n merge(\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {}\n\n /**\n * Refreshes the auth token for the current connection.\n * @param token - The authentication token\n */\n refreshAuthToken(token: string) {}\n\n /**\n * Refreshes the app check token for the current connection.\n * @param token The app check token\n */\n refreshAppCheckToken(token: string) {}\n\n onDisconnectPut(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n onDisconnectMerge(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n onDisconnectCancel(\n pathString: string,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n reportStats(stats: { [k: string]: unknown }) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\n/**\n * Base class to be used if you want to emit events. Call the constructor with\n * the set of allowed event names.\n */\nexport abstract class EventEmitter {\n private listeners_: {\n [eventType: string]: Array<{\n callback(...args: unknown[]): void;\n context: unknown;\n }>;\n } = {};\n\n constructor(private allowedEvents_: string[]) {\n assert(\n Array.isArray(allowedEvents_) && allowedEvents_.length > 0,\n 'Requires a non-empty array'\n );\n }\n\n /**\n * To be overridden by derived classes in order to fire an initial event when\n * somebody subscribes for data.\n *\n * @returns {Array.<*>} Array of parameters to trigger initial event with.\n */\n abstract getInitialEvent(eventType: string): unknown[];\n\n /**\n * To be called by derived classes to trigger events.\n */\n protected trigger(eventType: string, ...varArgs: unknown[]) {\n if (Array.isArray(this.listeners_[eventType])) {\n // Clone the list, since callbacks could add/remove listeners.\n const listeners = [...this.listeners_[eventType]];\n\n for (let i = 0; i < listeners.length; i++) {\n listeners[i].callback.apply(listeners[i].context, varArgs);\n }\n }\n }\n\n on(eventType: string, callback: (a: unknown) => void, context: unknown) {\n this.validateEventType_(eventType);\n this.listeners_[eventType] = this.listeners_[eventType] || [];\n this.listeners_[eventType].push({ callback, context });\n\n const eventData = this.getInitialEvent(eventType);\n if (eventData) {\n callback.apply(context, eventData);\n }\n }\n\n off(eventType: string, callback: (a: unknown) => void, context: unknown) {\n this.validateEventType_(eventType);\n const listeners = this.listeners_[eventType] || [];\n for (let i = 0; i < listeners.length; i++) {\n if (\n listeners[i].callback === callback &&\n (!context || context === listeners[i].context)\n ) {\n listeners.splice(i, 1);\n return;\n }\n }\n }\n\n private validateEventType_(eventType: string) {\n assert(\n this.allowedEvents_.find(et => {\n return et === eventType;\n }),\n 'Unknown event: ' + eventType\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, isMobileCordova } from '@firebase/util';\n\nimport { EventEmitter } from './EventEmitter';\n\n/**\n * Monitors online state (as reported by window.online/offline events).\n *\n * The expectation is that this could have many false positives (thinks we are online\n * when we're not), but no false negatives. So we can safely use it to determine when\n * we definitely cannot reach the internet.\n */\nexport class OnlineMonitor extends EventEmitter {\n private online_ = true;\n\n static getInstance() {\n return new OnlineMonitor();\n }\n\n constructor() {\n super(['online']);\n\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\n // It would seem that the 'online' event does not always fire consistently. So we disable it\n // for Cordova.\n if (\n typeof window !== 'undefined' &&\n typeof window.addEventListener !== 'undefined' &&\n !isMobileCordova()\n ) {\n window.addEventListener(\n 'online',\n () => {\n if (!this.online_) {\n this.online_ = true;\n this.trigger('online', true);\n }\n },\n false\n );\n\n window.addEventListener(\n 'offline',\n () => {\n if (this.online_) {\n this.online_ = false;\n this.trigger('online', false);\n }\n },\n false\n );\n }\n }\n\n getInitialEvent(eventType: string): boolean[] {\n assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n }\n\n currentlyOnline(): boolean {\n return this.online_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { stringLength } from '@firebase/util';\n\nimport { nameCompare } from './util';\n\n/** Maximum key depth. */\nconst MAX_PATH_DEPTH = 32;\n\n/** Maximum number of (UTF8) bytes in a Firebase path. */\nconst MAX_PATH_LENGTH_BYTES = 768;\n\n/**\n * An immutable object representing a parsed path. It's immutable so that you\n * can pass them around to other functions without worrying about them changing\n * it.\n */\n\nexport class Path {\n pieces_: string[];\n pieceNum_: number;\n\n /**\n * @param pathOrString - Path string to parse, or another path, or the raw\n * tokens array\n */\n constructor(pathOrString: string | string[], pieceNum?: number) {\n if (pieceNum === void 0) {\n this.pieces_ = (pathOrString as string).split('/');\n\n // Remove empty pieces.\n let copyTo = 0;\n for (let i = 0; i < this.pieces_.length; i++) {\n if (this.pieces_[i].length > 0) {\n this.pieces_[copyTo] = this.pieces_[i];\n copyTo++;\n }\n }\n this.pieces_.length = copyTo;\n\n this.pieceNum_ = 0;\n } else {\n this.pieces_ = pathOrString as string[];\n this.pieceNum_ = pieceNum;\n }\n }\n\n toString(): string {\n let pathString = '';\n for (let i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '') {\n pathString += '/' + this.pieces_[i];\n }\n }\n\n return pathString || '/';\n }\n}\n\nexport function newEmptyPath(): Path {\n return new Path('');\n}\n\nexport function pathGetFront(path: Path): string | null {\n if (path.pieceNum_ >= path.pieces_.length) {\n return null;\n }\n\n return path.pieces_[path.pieceNum_];\n}\n\n/**\n * @returns The number of segments in this path\n */\nexport function pathGetLength(path: Path): number {\n return path.pieces_.length - path.pieceNum_;\n}\n\nexport function pathPopFront(path: Path): Path {\n let pieceNum = path.pieceNum_;\n if (pieceNum < path.pieces_.length) {\n pieceNum++;\n }\n return new Path(path.pieces_, pieceNum);\n}\n\nexport function pathGetBack(path: Path): string | null {\n if (path.pieceNum_ < path.pieces_.length) {\n return path.pieces_[path.pieces_.length - 1];\n }\n\n return null;\n}\n\nexport function pathToUrlEncodedString(path: Path): string {\n let pathString = '';\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\n if (path.pieces_[i] !== '') {\n pathString += '/' + encodeURIComponent(String(path.pieces_[i]));\n }\n }\n\n return pathString || '/';\n}\n\n/**\n * Shallow copy of the parts of the path.\n *\n */\nexport function pathSlice(path: Path, begin: number = 0): string[] {\n return path.pieces_.slice(path.pieceNum_ + begin);\n}\n\nexport function pathParent(path: Path): Path | null {\n if (path.pieceNum_ >= path.pieces_.length) {\n return null;\n }\n\n const pieces = [];\n for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {\n pieces.push(path.pieces_[i]);\n }\n\n return new Path(pieces, 0);\n}\n\nexport function pathChild(path: Path, childPathObj: string | Path): Path {\n const pieces = [];\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\n pieces.push(path.pieces_[i]);\n }\n\n if (childPathObj instanceof Path) {\n for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\n pieces.push(childPathObj.pieces_[i]);\n }\n } else {\n const childPieces = childPathObj.split('/');\n for (let i = 0; i < childPieces.length; i++) {\n if (childPieces[i].length > 0) {\n pieces.push(childPieces[i]);\n }\n }\n }\n\n return new Path(pieces, 0);\n}\n\n/**\n * @returns True if there are no segments in this path\n */\nexport function pathIsEmpty(path: Path): boolean {\n return path.pieceNum_ >= path.pieces_.length;\n}\n\n/**\n * @returns The path from outerPath to innerPath\n */\nexport function newRelativePath(outerPath: Path, innerPath: Path): Path {\n const outer = pathGetFront(outerPath),\n inner = pathGetFront(innerPath);\n if (outer === null) {\n return innerPath;\n } else if (outer === inner) {\n return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));\n } else {\n throw new Error(\n 'INTERNAL ERROR: innerPath (' +\n innerPath +\n ') is not within ' +\n 'outerPath (' +\n outerPath +\n ')'\n );\n }\n}\n\n/**\n * @returns -1, 0, 1 if left is less, equal, or greater than the right.\n */\nexport function pathCompare(left: Path, right: Path): number {\n const leftKeys = pathSlice(left, 0);\n const rightKeys = pathSlice(right, 0);\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\n const cmp = nameCompare(leftKeys[i], rightKeys[i]);\n if (cmp !== 0) {\n return cmp;\n }\n }\n if (leftKeys.length === rightKeys.length) {\n return 0;\n }\n return leftKeys.length < rightKeys.length ? -1 : 1;\n}\n\n/**\n * @returns true if paths are the same.\n */\nexport function pathEquals(path: Path, other: Path): boolean {\n if (pathGetLength(path) !== pathGetLength(other)) {\n return false;\n }\n\n for (\n let i = path.pieceNum_, j = other.pieceNum_;\n i <= path.pieces_.length;\n i++, j++\n ) {\n if (path.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * @returns True if this path is a parent of (or the same as) other\n */\nexport function pathContains(path: Path, other: Path): boolean {\n let i = path.pieceNum_;\n let j = other.pieceNum_;\n if (pathGetLength(path) > pathGetLength(other)) {\n return false;\n }\n while (i < path.pieces_.length) {\n if (path.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n ++i;\n ++j;\n }\n return true;\n}\n\n/**\n * Dynamic (mutable) path used to count path lengths.\n *\n * This class is used to efficiently check paths for valid\n * length (in UTF8 bytes) and depth (used in path validation).\n *\n * Throws Error exception if path is ever invalid.\n *\n * The definition of a path always begins with '/'.\n */\nexport class ValidationPath {\n parts_: string[];\n /** Initialize to number of '/' chars needed in path. */\n byteLength_: number;\n\n /**\n * @param path - Initial Path.\n * @param errorPrefix_ - Prefix for any error messages.\n */\n constructor(path: Path, public errorPrefix_: string) {\n this.parts_ = pathSlice(path, 0);\n /** Initialize to number of '/' chars needed in path. */\n this.byteLength_ = Math.max(1, this.parts_.length);\n\n for (let i = 0; i < this.parts_.length; i++) {\n this.byteLength_ += stringLength(this.parts_[i]);\n }\n validationPathCheckValid(this);\n }\n}\n\nexport function validationPathPush(\n validationPath: ValidationPath,\n child: string\n): void {\n // Count the needed '/'\n if (validationPath.parts_.length > 0) {\n validationPath.byteLength_ += 1;\n }\n validationPath.parts_.push(child);\n validationPath.byteLength_ += stringLength(child);\n validationPathCheckValid(validationPath);\n}\n\nexport function validationPathPop(validationPath: ValidationPath): void {\n const last = validationPath.parts_.pop();\n validationPath.byteLength_ -= stringLength(last);\n // Un-count the previous '/'\n if (validationPath.parts_.length > 0) {\n validationPath.byteLength_ -= 1;\n }\n}\n\nfunction validationPathCheckValid(validationPath: ValidationPath): void {\n if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {\n throw new Error(\n validationPath.errorPrefix_ +\n 'has a key path longer than ' +\n MAX_PATH_LENGTH_BYTES +\n ' bytes (' +\n validationPath.byteLength_ +\n ').'\n );\n }\n if (validationPath.parts_.length > MAX_PATH_DEPTH) {\n throw new Error(\n validationPath.errorPrefix_ +\n 'path specified exceeds the maximum depth that can be written (' +\n MAX_PATH_DEPTH +\n ') or object contains a cycle ' +\n validationPathToErrorString(validationPath)\n );\n }\n}\n\n/**\n * String for use in error messages - uses '.' notation for path.\n */\nexport function validationPathToErrorString(\n validationPath: ValidationPath\n): string {\n if (validationPath.parts_.length === 0) {\n return '';\n }\n return \"in property '\" + validationPath.parts_.join('.') + \"'\";\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { EventEmitter } from './EventEmitter';\n\ndeclare const document: Document;\n\nexport class VisibilityMonitor extends EventEmitter {\n private visible_: boolean;\n\n static getInstance() {\n return new VisibilityMonitor();\n }\n\n constructor() {\n super(['visible']);\n let hidden: string;\n let visibilityChange: string;\n if (\n typeof document !== 'undefined' &&\n typeof document.addEventListener !== 'undefined'\n ) {\n if (typeof document['hidden'] !== 'undefined') {\n // Opera 12.10 and Firefox 18 and later support\n visibilityChange = 'visibilitychange';\n hidden = 'hidden';\n } else if (typeof document['mozHidden'] !== 'undefined') {\n visibilityChange = 'mozvisibilitychange';\n hidden = 'mozHidden';\n } else if (typeof document['msHidden'] !== 'undefined') {\n visibilityChange = 'msvisibilitychange';\n hidden = 'msHidden';\n } else if (typeof document['webkitHidden'] !== 'undefined') {\n visibilityChange = 'webkitvisibilitychange';\n hidden = 'webkitHidden';\n }\n }\n\n // Initially, we always assume we are visible. This ensures that in browsers\n // without page visibility support or in cases where we are never visible\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n // reconnects\n this.visible_ = true;\n\n if (visibilityChange) {\n document.addEventListener(\n visibilityChange,\n () => {\n const visible = !document[hidden];\n if (visible !== this.visible_) {\n this.visible_ = visible;\n this.trigger('visible', visible);\n }\n },\n false\n );\n }\n }\n\n getInitialEvent(eventType: string): boolean[] {\n assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n contains,\n Deferred,\n isEmpty,\n isMobileCordova,\n isNodeSdk,\n isReactNative,\n isValidFormat,\n safeGet,\n stringify,\n isAdmin\n} from '@firebase/util';\n\nimport { Connection } from '../realtime/Connection';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { OnlineMonitor } from './util/OnlineMonitor';\nimport { Path } from './util/Path';\nimport { error, log, logWrapper, warn, ObjectToUniqueKey } from './util/util';\nimport { VisibilityMonitor } from './util/VisibilityMonitor';\nimport { SDK_VERSION } from './version';\nimport { QueryContext } from './view/EventRegistration';\n\nconst RECONNECT_MIN_DELAY = 1000;\nconst RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\nconst RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\nconst RECONNECT_DELAY_MULTIPLIER = 1.3;\nconst RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\nconst SERVER_KILL_INTERRUPT_REASON = 'server_kill';\n\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\nconst INVALID_TOKEN_THRESHOLD = 3;\n\ninterface ListenSpec {\n onComplete(s: string, p?: unknown): void;\n\n hashFn(): string;\n\n query: QueryContext;\n tag: number | null;\n}\n\ninterface OnDisconnectRequest {\n pathString: string;\n action: string;\n data: unknown;\n onComplete?: (a: string, b: string) => void;\n}\n\ninterface OutstandingPut {\n action: string;\n request: object;\n queued?: boolean;\n onComplete: (a: string, b?: string) => void;\n}\n\ninterface OutstandingGet {\n request: object;\n onComplete: (response: { [k: string]: unknown }) => void;\n}\n\n/**\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\n *\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\n * in quotes to make sure the closure compiler does not minify them.\n */\nexport class PersistentConnection extends ServerActions {\n // Used for diagnostic logging.\n id = PersistentConnection.nextPersistentConnectionId_++;\n private log_ = logWrapper('p:' + this.id + ':');\n\n private interruptReasons_: { [reason: string]: boolean } = {};\n private readonly listens: Map<\n /* path */ string,\n Map\n > = new Map();\n private outstandingPuts_: OutstandingPut[] = [];\n private outstandingGets_: OutstandingGet[] = [];\n private outstandingPutCount_ = 0;\n private outstandingGetCount_ = 0;\n private onDisconnectRequestQueue_: OnDisconnectRequest[] = [];\n private connected_ = false;\n private reconnectDelay_ = RECONNECT_MIN_DELAY;\n private maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\n private securityDebugCallback_: ((a: object) => void) | null = null;\n lastSessionId: string | null = null;\n\n private establishConnectionTimer_: number | null = null;\n\n private visible_: boolean = false;\n\n // Before we get connected, we keep a queue of pending messages to send.\n private requestCBHash_: { [k: number]: (a: unknown) => void } = {};\n private requestNumber_ = 0;\n\n private realtime_: {\n sendRequest(a: object): void;\n close(): void;\n } | null = null;\n\n private authToken_: string | null = null;\n private appCheckToken_: string | null = null;\n private forceTokenRefresh_ = false;\n private invalidAuthTokenCount_ = 0;\n private invalidAppCheckTokenCount_ = 0;\n\n private firstConnection_ = true;\n private lastConnectionAttemptTime_: number | null = null;\n private lastConnectionEstablishedTime_: number | null = null;\n\n private static nextPersistentConnectionId_ = 0;\n\n /**\n * Counter for number of connections created. Mainly used for tagging in the logs\n */\n private static nextConnectionId_ = 0;\n\n /**\n * @param repoInfo_ - Data about the namespace we are connecting to\n * @param applicationId_ - The Firebase App ID for this project\n * @param onDataUpdate_ - A callback for new data from the server\n */\n constructor(\n private repoInfo_: RepoInfo,\n private applicationId_: string,\n private onDataUpdate_: (\n a: string,\n b: unknown,\n c: boolean,\n d: number | null\n ) => void,\n private onConnectStatus_: (a: boolean) => void,\n private onServerInfoUpdate_: (a: unknown) => void,\n private authTokenProvider_: AuthTokenProvider,\n private appCheckTokenProvider_: AppCheckTokenProvider,\n private authOverride_?: object | null\n ) {\n super();\n\n if (authOverride_ && !isNodeSdk()) {\n throw new Error(\n 'Auth override specified in options, but not supported on non Node.js platforms'\n );\n }\n\n VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);\n\n if (repoInfo_.host.indexOf('fblocal') === -1) {\n OnlineMonitor.getInstance().on('online', this.onOnline_, this);\n }\n }\n\n protected sendRequest(\n action: string,\n body: unknown,\n onResponse?: (a: unknown) => void\n ) {\n const curReqNum = ++this.requestNumber_;\n\n const msg = { r: curReqNum, a: action, b: body };\n this.log_(stringify(msg));\n assert(\n this.connected_,\n \"sendRequest call when we're not connected not allowed.\"\n );\n this.realtime_.sendRequest(msg);\n if (onResponse) {\n this.requestCBHash_[curReqNum] = onResponse;\n }\n }\n\n get(query: QueryContext): Promise {\n this.initConnection_();\n\n const deferred = new Deferred();\n const request = {\n p: query._path.toString(),\n q: query._queryObject\n };\n const outstandingGet = {\n action: 'g',\n request,\n onComplete: (message: { [k: string]: unknown }) => {\n const payload = message['d'] as string;\n if (message['s'] === 'ok') {\n deferred.resolve(payload);\n } else {\n deferred.reject(payload);\n }\n }\n };\n this.outstandingGets_.push(outstandingGet);\n this.outstandingGetCount_++;\n const index = this.outstandingGets_.length - 1;\n\n if (this.connected_) {\n this.sendGet_(index);\n }\n\n return deferred.promise;\n }\n\n listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ) {\n this.initConnection_();\n\n const queryId = query._queryIdentifier;\n const pathString = query._path.toString();\n this.log_('Listen called for ' + pathString + ' ' + queryId);\n if (!this.listens.has(pathString)) {\n this.listens.set(pathString, new Map());\n }\n assert(\n query._queryParams.isDefault() || !query._queryParams.loadsAllData(),\n 'listen() called for non-default but complete query'\n );\n assert(\n !this.listens.get(pathString)!.has(queryId),\n `listen() called twice for same path/queryId.`\n );\n const listenSpec: ListenSpec = {\n onComplete,\n hashFn: currentHashFn,\n query,\n tag\n };\n this.listens.get(pathString)!.set(queryId, listenSpec);\n\n if (this.connected_) {\n this.sendListen_(listenSpec);\n }\n }\n\n private sendGet_(index: number) {\n const get = this.outstandingGets_[index];\n this.sendRequest('g', get.request, (message: { [k: string]: unknown }) => {\n delete this.outstandingGets_[index];\n this.outstandingGetCount_--;\n if (this.outstandingGetCount_ === 0) {\n this.outstandingGets_ = [];\n }\n if (get.onComplete) {\n get.onComplete(message);\n }\n });\n }\n\n private sendListen_(listenSpec: ListenSpec) {\n const query = listenSpec.query;\n const pathString = query._path.toString();\n const queryId = query._queryIdentifier;\n this.log_('Listen on ' + pathString + ' for ' + queryId);\n const req: { [k: string]: unknown } = { /*path*/ p: pathString };\n\n const action = 'q';\n\n // Only bother to send query if it's non-default.\n if (listenSpec.tag) {\n req['q'] = query._queryObject;\n req['t'] = listenSpec.tag;\n }\n\n req[/*hash*/ 'h'] = listenSpec.hashFn();\n\n this.sendRequest(action, req, (message: { [k: string]: unknown }) => {\n const payload: unknown = message[/*data*/ 'd'];\n const status = message[/*status*/ 's'] as string;\n\n // print warnings in any case...\n PersistentConnection.warnOnListenWarnings_(payload, query);\n\n const currentListenSpec =\n this.listens.get(pathString) &&\n this.listens.get(pathString)!.get(queryId);\n // only trigger actions if the listen hasn't been removed and readded\n if (currentListenSpec === listenSpec) {\n this.log_('listen response', message);\n\n if (status !== 'ok') {\n this.removeListen_(pathString, queryId);\n }\n\n if (listenSpec.onComplete) {\n listenSpec.onComplete(status, payload);\n }\n }\n });\n }\n\n private static warnOnListenWarnings_(payload: unknown, query: QueryContext) {\n if (payload && typeof payload === 'object' && contains(payload, 'w')) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const warnings = safeGet(payload as any, 'w');\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\n const indexSpec =\n '\".indexOn\": \"' + query._queryParams.getIndex().toString() + '\"';\n const indexPath = query._path.toString();\n warn(\n `Using an unspecified index. Your data will be downloaded and ` +\n `filtered on the client. Consider adding ${indexSpec} at ` +\n `${indexPath} to your security rules for better performance.`\n );\n }\n }\n }\n\n refreshAuthToken(token: string) {\n this.authToken_ = token;\n this.log_('Auth token refreshed');\n if (this.authToken_) {\n this.tryAuth();\n } else {\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\n //the credential so we dont become authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unauth', {}, () => {});\n }\n }\n\n this.reduceReconnectDelayIfAdminCredential_(token);\n }\n\n private reduceReconnectDelayIfAdminCredential_(credential: string) {\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\n const isFirebaseSecret = credential && credential.length === 40;\n if (isFirebaseSecret || isAdmin(credential)) {\n this.log_(\n 'Admin auth credential detected. Reducing max reconnect time.'\n );\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n }\n }\n\n refreshAppCheckToken(token: string | null) {\n this.appCheckToken_ = token;\n this.log_('App check token refreshed');\n if (this.appCheckToken_) {\n this.tryAppCheck();\n } else {\n //If we're connected we want to let the server know to unauthenticate us.\n //If we're not connected, simply delete the credential so we dont become\n // authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unappeck', {}, () => {});\n }\n }\n }\n\n /**\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\n * a auth revoked (the connection is closed).\n */\n tryAuth() {\n if (this.connected_ && this.authToken_) {\n const token = this.authToken_;\n const authMethod = isValidFormat(token) ? 'auth' : 'gauth';\n const requestData: { [k: string]: unknown } = { cred: token };\n if (this.authOverride_ === null) {\n requestData['noauth'] = true;\n } else if (typeof this.authOverride_ === 'object') {\n requestData['authvar'] = this.authOverride_;\n }\n this.sendRequest(\n authMethod,\n requestData,\n (res: { [k: string]: unknown }) => {\n const status = res[/*status*/ 's'] as string;\n const data = (res[/*data*/ 'd'] as string) || 'error';\n\n if (this.authToken_ === token) {\n if (status === 'ok') {\n this.invalidAuthTokenCount_ = 0;\n } else {\n // Triggers reconnect and force refresh for auth token\n this.onAuthRevoked_(status, data);\n }\n }\n }\n );\n }\n }\n\n /**\n * Attempts to authenticate with the given token. If the authentication\n * attempt fails, it's triggered like the token was revoked (the connection is\n * closed).\n */\n tryAppCheck() {\n if (this.connected_ && this.appCheckToken_) {\n this.sendRequest(\n 'appcheck',\n { 'token': this.appCheckToken_ },\n (res: { [k: string]: unknown }) => {\n const status = res[/*status*/ 's'] as string;\n const data = (res[/*data*/ 'd'] as string) || 'error';\n if (status === 'ok') {\n this.invalidAppCheckTokenCount_ = 0;\n } else {\n this.onAppCheckRevoked_(status, data);\n }\n }\n );\n }\n }\n\n /**\n * @inheritDoc\n */\n unlisten(query: QueryContext, tag: number | null) {\n const pathString = query._path.toString();\n const queryId = query._queryIdentifier;\n\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\n\n assert(\n query._queryParams.isDefault() || !query._queryParams.loadsAllData(),\n 'unlisten() called for non-default but complete query'\n );\n const listen = this.removeListen_(pathString, queryId);\n if (listen && this.connected_) {\n this.sendUnlisten_(pathString, queryId, query._queryObject, tag);\n }\n }\n\n private sendUnlisten_(\n pathString: string,\n queryId: string,\n queryObj: object,\n tag: number | null\n ) {\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\n\n const req: { [k: string]: unknown } = { /*path*/ p: pathString };\n const action = 'n';\n // Only bother sending queryId if it's non-default.\n if (tag) {\n req['q'] = queryObj;\n req['t'] = tag;\n }\n\n this.sendRequest(action, req);\n }\n\n onDisconnectPut(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\n\n if (this.connected_) {\n this.sendOnDisconnect_('o', pathString, data, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'o',\n data,\n onComplete\n });\n }\n }\n\n onDisconnectMerge(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\n\n if (this.connected_) {\n this.sendOnDisconnect_('om', pathString, data, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'om',\n data,\n onComplete\n });\n }\n }\n\n onDisconnectCancel(\n pathString: string,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\n\n if (this.connected_) {\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'oc',\n data: null,\n onComplete\n });\n }\n }\n\n private sendOnDisconnect_(\n action: string,\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string) => void\n ) {\n const request = { /*path*/ p: pathString, /*data*/ d: data };\n this.log_('onDisconnect ' + action, request);\n this.sendRequest(action, request, (response: { [k: string]: unknown }) => {\n if (onComplete) {\n setTimeout(() => {\n onComplete(\n response[/*status*/ 's'] as string,\n response[/* data */ 'd'] as string\n );\n }, Math.floor(0));\n }\n });\n }\n\n put(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void,\n hash?: string\n ) {\n this.putInternal('p', pathString, data, onComplete, hash);\n }\n\n merge(\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {\n this.putInternal('m', pathString, data, onComplete, hash);\n }\n\n putInternal(\n action: string,\n pathString: string,\n data: unknown,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {\n this.initConnection_();\n\n const request: { [k: string]: unknown } = {\n /*path*/ p: pathString,\n /*data*/ d: data\n };\n\n if (hash !== undefined) {\n request[/*hash*/ 'h'] = hash;\n }\n\n // TODO: Only keep track of the most recent put for a given path?\n this.outstandingPuts_.push({\n action,\n request,\n onComplete\n });\n\n this.outstandingPutCount_++;\n const index = this.outstandingPuts_.length - 1;\n\n if (this.connected_) {\n this.sendPut_(index);\n } else {\n this.log_('Buffering put: ' + pathString);\n }\n }\n\n private sendPut_(index: number) {\n const action = this.outstandingPuts_[index].action;\n const request = this.outstandingPuts_[index].request;\n const onComplete = this.outstandingPuts_[index].onComplete;\n this.outstandingPuts_[index].queued = this.connected_;\n\n this.sendRequest(action, request, (message: { [k: string]: unknown }) => {\n this.log_(action + ' response', message);\n\n delete this.outstandingPuts_[index];\n this.outstandingPutCount_--;\n\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0) {\n this.outstandingPuts_ = [];\n }\n\n if (onComplete) {\n onComplete(\n message[/*status*/ 's'] as string,\n message[/* data */ 'd'] as string\n );\n }\n });\n }\n\n reportStats(stats: { [k: string]: unknown }) {\n // If we're not connected, we just drop the stats.\n if (this.connected_) {\n const request = { /*counters*/ c: stats };\n this.log_('reportStats', request);\n\n this.sendRequest(/*stats*/ 's', request, result => {\n const status = result[/*status*/ 's'];\n if (status !== 'ok') {\n const errorReason = result[/* data */ 'd'];\n this.log_('reportStats', 'Error sending stats: ' + errorReason);\n }\n });\n }\n }\n\n private onDataMessage_(message: { [k: string]: unknown }) {\n if ('r' in message) {\n // this is a response\n this.log_('from server: ' + stringify(message));\n const reqNum = message['r'] as string;\n const onResponse = this.requestCBHash_[reqNum];\n if (onResponse) {\n delete this.requestCBHash_[reqNum];\n onResponse(message[/*body*/ 'b']);\n }\n } else if ('error' in message) {\n throw 'A server-side error has occurred: ' + message['error'];\n } else if ('a' in message) {\n // a and b are action and body, respectively\n this.onDataPush_(message['a'] as string, message['b'] as {});\n }\n }\n\n private onDataPush_(action: string, body: { [k: string]: unknown }) {\n this.log_('handleServerMessage', action, body);\n if (action === 'd') {\n this.onDataUpdate_(\n body[/*path*/ 'p'] as string,\n body[/*data*/ 'd'],\n /*isMerge*/ false,\n body['t'] as number\n );\n } else if (action === 'm') {\n this.onDataUpdate_(\n body[/*path*/ 'p'] as string,\n body[/*data*/ 'd'],\n /*isMerge=*/ true,\n body['t'] as number\n );\n } else if (action === 'c') {\n this.onListenRevoked_(\n body[/*path*/ 'p'] as string,\n body[/*query*/ 'q'] as unknown[]\n );\n } else if (action === 'ac') {\n this.onAuthRevoked_(\n body[/*status code*/ 's'] as string,\n body[/* explanation */ 'd'] as string\n );\n } else if (action === 'apc') {\n this.onAppCheckRevoked_(\n body[/*status code*/ 's'] as string,\n body[/* explanation */ 'd'] as string\n );\n } else if (action === 'sd') {\n this.onSecurityDebugPacket_(body);\n } else {\n error(\n 'Unrecognized action received from server: ' +\n stringify(action) +\n '\\nAre you using the latest client?'\n );\n }\n }\n\n private onReady_(timestamp: number, sessionId: string) {\n this.log_('connection ready');\n this.connected_ = true;\n this.lastConnectionEstablishedTime_ = new Date().getTime();\n this.handleTimestamp_(timestamp);\n this.lastSessionId = sessionId;\n if (this.firstConnection_) {\n this.sendConnectStats_();\n }\n this.restoreState_();\n this.firstConnection_ = false;\n this.onConnectStatus_(true);\n }\n\n private scheduleConnect_(timeout: number) {\n assert(\n !this.realtime_,\n \"Scheduling a connect when we're already connected/ing?\"\n );\n\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n }\n\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\n\n this.establishConnectionTimer_ = setTimeout(() => {\n this.establishConnectionTimer_ = null;\n this.establishConnection_();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(timeout)) as any;\n }\n\n private initConnection_() {\n if (!this.realtime_ && this.firstConnection_) {\n this.scheduleConnect_(0);\n }\n }\n\n private onVisible_(visible: boolean) {\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\n if (\n visible &&\n !this.visible_ &&\n this.reconnectDelay_ === this.maxReconnectDelay_\n ) {\n this.log_('Window became visible. Reducing delay.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n this.visible_ = visible;\n }\n\n private onOnline_(online: boolean) {\n if (online) {\n this.log_('Browser went online.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n } else {\n this.log_('Browser went offline. Killing connection.');\n if (this.realtime_) {\n this.realtime_.close();\n }\n }\n }\n\n private onRealtimeDisconnect_() {\n this.log_('data client disconnected');\n this.connected_ = false;\n this.realtime_ = null;\n\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\n this.cancelSentTransactions_();\n\n // Clear out the pending requests.\n this.requestCBHash_ = {};\n\n if (this.shouldReconnect_()) {\n if (!this.visible_) {\n this.log_(\"Window isn't visible. Delaying reconnect.\");\n this.reconnectDelay_ = this.maxReconnectDelay_;\n this.lastConnectionAttemptTime_ = new Date().getTime();\n } else if (this.lastConnectionEstablishedTime_) {\n // If we've been connected long enough, reset reconnect delay to minimum.\n const timeSinceLastConnectSucceeded =\n new Date().getTime() - this.lastConnectionEstablishedTime_;\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n }\n this.lastConnectionEstablishedTime_ = null;\n }\n\n const timeSinceLastConnectAttempt = Math.max(\n 0,\n new Date().getTime() - this.lastConnectionAttemptTime_\n );\n let reconnectDelay = Math.max(\n 0,\n this.reconnectDelay_ - timeSinceLastConnectAttempt\n );\n reconnectDelay = Math.random() * reconnectDelay;\n\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\n this.scheduleConnect_(reconnectDelay);\n\n // Adjust reconnect delay for next time.\n this.reconnectDelay_ = Math.min(\n this.maxReconnectDelay_,\n this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER\n );\n }\n this.onConnectStatus_(false);\n }\n\n private async establishConnection_() {\n if (this.shouldReconnect_()) {\n this.log_('Making a connection attempt');\n this.lastConnectionAttemptTime_ = new Date().getTime();\n this.lastConnectionEstablishedTime_ = null;\n const onDataMessage = this.onDataMessage_.bind(this);\n const onReady = this.onReady_.bind(this);\n const onDisconnect = this.onRealtimeDisconnect_.bind(this);\n const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;\n const lastSessionId = this.lastSessionId;\n let canceled = false;\n let connection: Connection | null = null;\n const closeFn = function () {\n if (connection) {\n connection.close();\n } else {\n canceled = true;\n onDisconnect();\n }\n };\n const sendRequestFn = function (msg: object) {\n assert(\n connection,\n \"sendRequest call when we're not connected not allowed.\"\n );\n connection.sendRequest(msg);\n };\n\n this.realtime_ = {\n close: closeFn,\n sendRequest: sendRequestFn\n };\n\n const forceRefresh = this.forceTokenRefresh_;\n this.forceTokenRefresh_ = false;\n\n try {\n // First fetch auth and app check token, and establish connection after\n // fetching the token was successful\n const [authToken, appCheckToken] = await Promise.all([\n this.authTokenProvider_.getToken(forceRefresh),\n this.appCheckTokenProvider_.getToken(forceRefresh)\n ]);\n\n if (!canceled) {\n log('getToken() completed. Creating connection.');\n this.authToken_ = authToken && authToken.accessToken;\n this.appCheckToken_ = appCheckToken && appCheckToken.token;\n connection = new Connection(\n connId,\n this.repoInfo_,\n this.applicationId_,\n this.appCheckToken_,\n this.authToken_,\n onDataMessage,\n onReady,\n onDisconnect,\n /* onKill= */ reason => {\n warn(reason + ' (' + this.repoInfo_.toString() + ')');\n this.interrupt(SERVER_KILL_INTERRUPT_REASON);\n },\n lastSessionId\n );\n } else {\n log('getToken() completed but was canceled');\n }\n } catch (error) {\n this.log_('Failed to get token: ' + error);\n if (!canceled) {\n if (this.repoInfo_.nodeAdmin) {\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\n // But getToken() may also just have temporarily failed, so we still want to\n // continue retrying.\n warn(error);\n }\n closeFn();\n }\n }\n }\n }\n\n interrupt(reason: string) {\n log('Interrupting connection for reason: ' + reason);\n this.interruptReasons_[reason] = true;\n if (this.realtime_) {\n this.realtime_.close();\n } else {\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n this.establishConnectionTimer_ = null;\n }\n if (this.connected_) {\n this.onRealtimeDisconnect_();\n }\n }\n }\n\n resume(reason: string) {\n log('Resuming connection for reason: ' + reason);\n delete this.interruptReasons_[reason];\n if (isEmpty(this.interruptReasons_)) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n }\n\n private handleTimestamp_(timestamp: number) {\n const delta = timestamp - new Date().getTime();\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\n }\n\n private cancelSentTransactions_() {\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\n const put = this.outstandingPuts_[i];\n if (put && /*hash*/ 'h' in put.request && put.queued) {\n if (put.onComplete) {\n put.onComplete('disconnect');\n }\n\n delete this.outstandingPuts_[i];\n this.outstandingPutCount_--;\n }\n }\n\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0) {\n this.outstandingPuts_ = [];\n }\n }\n\n private onListenRevoked_(pathString: string, query?: unknown[]) {\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\n let queryId;\n if (!query) {\n queryId = 'default';\n } else {\n queryId = query.map(q => ObjectToUniqueKey(q)).join('$');\n }\n const listen = this.removeListen_(pathString, queryId);\n if (listen && listen.onComplete) {\n listen.onComplete('permission_denied');\n }\n }\n\n private removeListen_(pathString: string, queryId: string): ListenSpec {\n const normalizedPathString = new Path(pathString).toString(); // normalize path.\n let listen;\n if (this.listens.has(normalizedPathString)) {\n const map = this.listens.get(normalizedPathString)!;\n listen = map.get(queryId);\n map.delete(queryId);\n if (map.size === 0) {\n this.listens.delete(normalizedPathString);\n }\n } else {\n // all listens for this path has already been removed\n listen = undefined;\n }\n return listen;\n }\n\n private onAuthRevoked_(statusCode: string, explanation: string) {\n log('Auth token revoked: ' + statusCode + '/' + explanation);\n this.authToken_ = null;\n this.forceTokenRefresh_ = true;\n this.realtime_.close();\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAuthTokenCount_++;\n if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\n // Set a long reconnect delay because recovery is unlikely\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n\n // Notify the auth token provider that the token is invalid, which will log\n // a warning\n this.authTokenProvider_.notifyForInvalidToken();\n }\n }\n }\n\n private onAppCheckRevoked_(statusCode: string, explanation: string) {\n log('App check token revoked: ' + statusCode + '/' + explanation);\n this.appCheckToken_ = null;\n this.forceTokenRefresh_ = true;\n // Note: We don't close the connection as the developer may not have\n // enforcement enabled. The backend closes connections with enforcements.\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAppCheckTokenCount_++;\n if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\n this.appCheckTokenProvider_.notifyForInvalidToken();\n }\n }\n }\n\n private onSecurityDebugPacket_(body: { [k: string]: unknown }) {\n if (this.securityDebugCallback_) {\n this.securityDebugCallback_(body);\n } else {\n if ('msg' in body) {\n console.log(\n 'FIREBASE: ' + (body['msg'] as string).replace('\\n', '\\nFIREBASE: ')\n );\n }\n }\n }\n\n private restoreState_() {\n //Re-authenticate ourselves if we have a credential stored.\n this.tryAuth();\n this.tryAppCheck();\n\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\n // make sure to send listens before puts.\n for (const queries of this.listens.values()) {\n for (const listenSpec of queries.values()) {\n this.sendListen_(listenSpec);\n }\n }\n\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\n if (this.outstandingPuts_[i]) {\n this.sendPut_(i);\n }\n }\n\n while (this.onDisconnectRequestQueue_.length) {\n const request = this.onDisconnectRequestQueue_.shift();\n this.sendOnDisconnect_(\n request.action,\n request.pathString,\n request.data,\n request.onComplete\n );\n }\n\n for (let i = 0; i < this.outstandingGets_.length; i++) {\n if (this.outstandingGets_[i]) {\n this.sendGet_(i);\n }\n }\n }\n\n /**\n * Sends client stats for first connection\n */\n private sendConnectStats_() {\n const stats: { [k: string]: number } = {};\n\n let clientName = 'js';\n if (isNodeSdk()) {\n if (this.repoInfo_.nodeAdmin) {\n clientName = 'admin_node';\n } else {\n clientName = 'node';\n }\n }\n\n stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\\./g, '-')] = 1;\n\n if (isMobileCordova()) {\n stats['framework.cordova'] = 1;\n } else if (isReactNative()) {\n stats['framework.reactnative'] = 1;\n }\n this.reportStats(stats);\n }\n\n private shouldReconnect_(): boolean {\n const online = OnlineMonitor.getInstance().currentlyOnline();\n return isEmpty(this.interruptReasons_) && online;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Path } from '../util/Path';\n\nimport { Index } from './indexes/Index';\n\n/**\n * Node is an interface defining the common functionality for nodes in\n * a DataSnapshot.\n *\n * @interface\n */\nexport interface Node {\n /**\n * Whether this node is a leaf node.\n * @returns Whether this is a leaf node.\n */\n isLeafNode(): boolean;\n\n /**\n * Gets the priority of the node.\n * @returns The priority of the node.\n */\n getPriority(): Node;\n\n /**\n * Returns a duplicate node with the new priority.\n * @param newPriorityNode - New priority to set for the node.\n * @returns Node with new priority.\n */\n updatePriority(newPriorityNode: Node): Node;\n\n /**\n * Returns the specified immediate child, or null if it doesn't exist.\n * @param childName - The name of the child to retrieve.\n * @returns The retrieved child, or an empty node.\n */\n getImmediateChild(childName: string): Node;\n\n /**\n * Returns a child by path, or null if it doesn't exist.\n * @param path - The path of the child to retrieve.\n * @returns The retrieved child or an empty node.\n */\n getChild(path: Path): Node;\n\n /**\n * Returns the name of the child immediately prior to the specified childNode, or null.\n * @param childName - The name of the child to find the predecessor of.\n * @param childNode - The node to find the predecessor of.\n * @param index - The index to use to determine the predecessor\n * @returns The name of the predecessor child, or null if childNode is the first child.\n */\n getPredecessorChildName(\n childName: string,\n childNode: Node,\n index: Index\n ): string | null;\n\n /**\n * Returns a duplicate node, with the specified immediate child updated.\n * Any value in the node will be removed.\n * @param childName - The name of the child to update.\n * @param newChildNode - The new child node\n * @returns The updated node.\n */\n updateImmediateChild(childName: string, newChildNode: Node): Node;\n\n /**\n * Returns a duplicate node, with the specified child updated. Any value will\n * be removed.\n * @param path - The path of the child to update.\n * @param newChildNode - The new child node, which may be an empty node\n * @returns The updated node.\n */\n updateChild(path: Path, newChildNode: Node): Node;\n\n /**\n * True if the immediate child specified exists\n */\n hasChild(childName: string): boolean;\n\n /**\n * @returns True if this node has no value or children.\n */\n isEmpty(): boolean;\n\n /**\n * @returns The number of children of this node.\n */\n numChildren(): number;\n\n /**\n * Calls action for each child.\n * @param action - Action to be called for\n * each child. It's passed the child name and the child node.\n * @returns The first truthy value return by action, or the last falsey one\n */\n forEachChild(index: Index, action: (a: string, b: Node) => void): unknown;\n\n /**\n * @param exportFormat - True for export format (also wire protocol format).\n * @returns Value of this node as JSON.\n */\n val(exportFormat?: boolean): unknown;\n\n /**\n * @returns hash representing the node contents.\n */\n hash(): string;\n\n /**\n * @param other - Another node\n * @returns -1 for less than, 0 for equal, 1 for greater than other\n */\n compareTo(other: Node): number;\n\n /**\n * @returns Whether or not this snapshot equals other\n */\n equals(other: Node): boolean;\n\n /**\n * @returns This node, with the specified index now available\n */\n withIndex(indexDefinition: Index): Node;\n\n isIndexed(indexDefinition: Index): boolean;\n}\n\nexport class NamedNode {\n constructor(public name: string, public node: Node) {}\n\n static Wrap(name: string, node: Node) {\n return new NamedNode(name, node);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Comparator } from '../../util/SortedMap';\nimport { MIN_NAME } from '../../util/util';\nimport { Node, NamedNode } from '../Node';\n\nexport abstract class Index {\n abstract compare(a: NamedNode, b: NamedNode): number;\n\n abstract isDefinedOn(node: Node): boolean;\n\n /**\n * @returns A standalone comparison function for\n * this index\n */\n getCompare(): Comparator {\n return this.compare.bind(this);\n }\n\n /**\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\n *\n *\n * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode\n */\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n const oldWrapped = new NamedNode(MIN_NAME, oldNode);\n const newWrapped = new NamedNode(MIN_NAME, newNode);\n return this.compare(oldWrapped, newWrapped) !== 0;\n }\n\n /**\n * @returns a node wrapper that will sort equal to or less than\n * any other node wrapper, using this index\n */\n minPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n\n /**\n * @returns a node wrapper that will sort greater than or equal to\n * any other node wrapper, using this index\n */\n abstract maxPost(): NamedNode;\n\n abstract makePost(indexValue: unknown, name: string): NamedNode;\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n abstract toString(): string;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport { nameCompare, MAX_NAME } from '../../util/util';\nimport { ChildrenNode } from '../ChildrenNode';\nimport { Node, NamedNode } from '../Node';\n\nimport { Index } from './Index';\n\nlet __EMPTY_NODE: ChildrenNode;\n\nexport class KeyIndex extends Index {\n static get __EMPTY_NODE() {\n return __EMPTY_NODE;\n }\n\n static set __EMPTY_NODE(val) {\n __EMPTY_NODE = val;\n }\n compare(a: NamedNode, b: NamedNode): number {\n return nameCompare(a.name, b.name);\n }\n isDefinedOn(node: Node): boolean {\n // We could probably return true here (since every node has a key), but it's never called\n // so just leaving unimplemented for now.\n throw assertionError('KeyIndex.isDefinedOn not expected to be called.');\n }\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return false; // The key for a node never changes.\n }\n minPost() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n maxPost(): NamedNode {\n // TODO: This should really be created once and cached in a static property, but\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\n return new NamedNode(MAX_NAME, __EMPTY_NODE);\n }\n\n makePost(indexValue: string, name: string): NamedNode {\n assert(\n typeof indexValue === 'string',\n 'KeyIndex indexValue must always be a string.'\n );\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\n return new NamedNode(indexValue, __EMPTY_NODE);\n }\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString(): string {\n return '.key';\n }\n}\n\nexport const KEY_INDEX = new KeyIndex();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Implementation of an immutable SortedMap using a Left-leaning\n * Red-Black Tree, adapted from the implementation in Mugs\n * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen\n * (mads379\\@gmail.com).\n *\n * Original paper on Left-leaning Red-Black Trees:\n * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf\n *\n * Invariant 1: No red node has a red child\n * Invariant 2: Every leaf path has the same number of black nodes\n * Invariant 3: Only the left child can be red (left leaning)\n */\n\n// TODO: There are some improvements I'd like to make to improve memory / perf:\n// * Create two prototypes, LLRedNode and LLBlackNode, instead of storing a\n// color property in every node.\n// TODO: It would also be good (and possibly necessary) to create a base\n// interface for LLRBNode and LLRBEmptyNode.\n\nexport type Comparator = (key1: K, key2: K) => number;\n\n/**\n * An iterator over an LLRBNode.\n */\nexport class SortedMapIterator {\n private nodeStack_: Array | LLRBEmptyNode> = [];\n\n /**\n * @param node - Node to iterate.\n * @param isReverse_ - Whether or not to iterate in reverse\n */\n constructor(\n node: LLRBNode | LLRBEmptyNode,\n startKey: K | null,\n comparator: Comparator,\n private isReverse_: boolean,\n private resultGenerator_: ((k: K, v: V) => T) | null = null\n ) {\n let cmp = 1;\n while (!node.isEmpty()) {\n node = node as LLRBNode;\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse_) {\n cmp *= -1;\n }\n\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse_) {\n node = node.left;\n } else {\n node = node.right;\n }\n } else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\n this.nodeStack_.push(node);\n break;\n } else {\n // This node is greater than our start key, add it to the stack and move to the next one\n this.nodeStack_.push(node);\n if (this.isReverse_) {\n node = node.right;\n } else {\n node = node.left;\n }\n }\n }\n }\n\n getNext(): T {\n if (this.nodeStack_.length === 0) {\n return null;\n }\n\n let node = this.nodeStack_.pop();\n let result: T;\n if (this.resultGenerator_) {\n result = this.resultGenerator_(node.key, node.value);\n } else {\n result = { key: node.key, value: node.value } as unknown as T;\n }\n\n if (this.isReverse_) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.right;\n }\n } else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.left;\n }\n }\n\n return result;\n }\n\n hasNext(): boolean {\n return this.nodeStack_.length > 0;\n }\n\n peek(): T {\n if (this.nodeStack_.length === 0) {\n return null;\n }\n\n const node = this.nodeStack_[this.nodeStack_.length - 1];\n if (this.resultGenerator_) {\n return this.resultGenerator_(node.key, node.value);\n } else {\n return { key: node.key, value: node.value } as unknown as T;\n }\n }\n}\n\n/**\n * Represents a node in a Left-leaning Red-Black tree.\n */\nexport class LLRBNode {\n color: boolean;\n left: LLRBNode | LLRBEmptyNode;\n right: LLRBNode | LLRBEmptyNode;\n\n /**\n * @param key - Key associated with this node.\n * @param value - Value associated with this node.\n * @param color - Whether this node is red.\n * @param left - Left child.\n * @param right - Right child.\n */\n constructor(\n public key: K,\n public value: V,\n color: boolean | null,\n left?: LLRBNode | LLRBEmptyNode | null,\n right?: LLRBNode | LLRBEmptyNode | null\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left =\n left != null ? left : (SortedMap.EMPTY_NODE as LLRBEmptyNode);\n this.right =\n right != null ? right : (SortedMap.EMPTY_NODE as LLRBEmptyNode);\n }\n\n static RED = true;\n static BLACK = false;\n\n /**\n * Returns a copy of the current node, optionally replacing pieces of it.\n *\n * @param key - New key for the node, or null.\n * @param value - New value for the node, or null.\n * @param color - New color for the node, or null.\n * @param left - New left child for the node, or null.\n * @param right - New right child for the node, or null.\n * @returns The node copy.\n */\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBNode {\n return new LLRBNode(\n key != null ? key : this.key,\n value != null ? value : this.value,\n color != null ? color : this.color,\n left != null ? left : this.left,\n right != null ? right : this.right\n );\n }\n\n /**\n * @returns The total number of nodes in the tree.\n */\n count(): number {\n return this.left.count() + 1 + this.right.count();\n }\n\n /**\n * @returns True if the tree is empty.\n */\n isEmpty(): boolean {\n return false;\n }\n\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n inorderTraversal(action: (k: K, v: V) => unknown): boolean {\n return (\n this.left.inorderTraversal(action) ||\n !!action(this.key, this.value) ||\n this.right.inorderTraversal(action)\n );\n }\n\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n reverseTraversal(action: (k: K, v: V) => void): boolean {\n return (\n this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action)\n );\n }\n\n /**\n * @returns The minimum node in the tree.\n */\n private min_(): LLRBNode {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode).min_();\n }\n }\n\n /**\n * @returns The maximum key in the tree.\n */\n minKey(): K {\n return this.min_().key;\n }\n\n /**\n * @returns The maximum key in the tree.\n */\n maxKey(): K {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\n }\n\n /**\n * @param key - Key to insert.\n * @param value - Value to insert.\n * @param comparator - Comparator.\n * @returns New tree, with the key/value added.\n */\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n let n: LLRBNode = this;\n const cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n } else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n } else {\n n = n.copy(\n null,\n null,\n null,\n null,\n n.right.insert(key, value, comparator)\n );\n }\n return n.fixUp_();\n }\n\n /**\n * @returns New tree, with the minimum key removed.\n */\n private removeMin_(): LLRBNode | LLRBEmptyNode {\n if (this.left.isEmpty()) {\n return SortedMap.EMPTY_NODE as LLRBEmptyNode;\n }\n let n: LLRBNode = this;\n if (!n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, (n.left as LLRBNode).removeMin_(), null);\n return n.fixUp_();\n }\n\n /**\n * @param key - The key of the item to remove.\n * @param comparator - Comparator.\n * @returns New tree, with the specified item removed.\n */\n remove(\n key: K,\n comparator: Comparator\n ): LLRBNode | LLRBEmptyNode {\n let n, smallest;\n n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n } else {\n if (n.left.isRed_()) {\n n = n.rotateRight_();\n }\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\n n = n.moveRedRight_();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return SortedMap.EMPTY_NODE as LLRBEmptyNode;\n } else {\n smallest = (n.right as LLRBNode).min_();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode).removeMin_()\n );\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp_();\n }\n\n /**\n * @returns Whether this is a RED node.\n */\n isRed_(): boolean {\n return this.color;\n }\n\n /**\n * @returns New tree after performing any needed rotations.\n */\n private fixUp_(): LLRBNode {\n let n: LLRBNode = this;\n if (n.right.isRed_() && !n.left.isRed_()) {\n n = n.rotateLeft_();\n }\n if (n.left.isRed_() && n.left.left.isRed_()) {\n n = n.rotateRight_();\n }\n if (n.left.isRed_() && n.right.isRed_()) {\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @returns New tree, after moveRedLeft.\n */\n private moveRedLeft_(): LLRBNode {\n let n = this.colorFlip_();\n if (n.right.left.isRed_()) {\n n = n.copy(\n null,\n null,\n null,\n null,\n (n.right as LLRBNode).rotateRight_()\n );\n n = n.rotateLeft_();\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @returns New tree, after moveRedRight.\n */\n private moveRedRight_(): LLRBNode {\n let n = this.colorFlip_();\n if (n.left.left.isRed_()) {\n n = n.rotateRight_();\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @returns New tree, after rotateLeft.\n */\n private rotateLeft_(): LLRBNode {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null) as LLRBNode;\n }\n\n /**\n * @returns New tree, after rotateRight.\n */\n private rotateRight_(): LLRBNode {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr) as LLRBNode;\n }\n\n /**\n * @returns Newt ree, after colorFlip.\n */\n private colorFlip_(): LLRBNode {\n const left = this.left.copy(null, null, !this.left.color, null, null);\n const right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n }\n\n /**\n * For testing.\n *\n * @returns True if all is well.\n */\n private checkMaxDepth_(): boolean {\n const blackDepth = this.check_();\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\n }\n\n check_(): number {\n if (this.isRed_() && this.left.isRed_()) {\n throw new Error(\n 'Red node has red child(' + this.key + ',' + this.value + ')'\n );\n }\n if (this.right.isRed_()) {\n throw new Error(\n 'Right child of (' + this.key + ',' + this.value + ') is red'\n );\n }\n const blackDepth = this.left.check_();\n if (blackDepth !== this.right.check_()) {\n throw new Error('Black depths differ');\n } else {\n return blackDepth + (this.isRed_() ? 0 : 1);\n }\n }\n}\n\n/**\n * Represents an empty node (a leaf node in the Red-Black Tree).\n */\nexport class LLRBEmptyNode {\n key: K;\n value: V;\n left: LLRBNode | LLRBEmptyNode;\n right: LLRBNode | LLRBEmptyNode;\n color: boolean;\n\n /**\n * Returns a copy of the current node.\n *\n * @returns The node copy.\n */\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBEmptyNode {\n return this;\n }\n\n /**\n * Returns a copy of the tree, with the specified key/value added.\n *\n * @param key - Key to be added.\n * @param value - Value to be added.\n * @param comparator - Comparator.\n * @returns New tree, with item added.\n */\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n return new LLRBNode(key, value, null);\n }\n\n /**\n * Returns a copy of the tree, with the specified key removed.\n *\n * @param key - The key to remove.\n * @param comparator - Comparator.\n * @returns New tree, with item removed.\n */\n remove(key: K, comparator: Comparator): LLRBEmptyNode {\n return this;\n }\n\n /**\n * @returns The total number of nodes in the tree.\n */\n count(): number {\n return 0;\n }\n\n /**\n * @returns True if the tree is empty.\n */\n isEmpty(): boolean {\n return true;\n }\n\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n inorderTraversal(action: (k: K, v: V) => unknown): boolean {\n return false;\n }\n\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n reverseTraversal(action: (k: K, v: V) => void): boolean {\n return false;\n }\n\n minKey(): null {\n return null;\n }\n\n maxKey(): null {\n return null;\n }\n\n check_(): number {\n return 0;\n }\n\n /**\n * @returns Whether this node is red.\n */\n isRed_() {\n return false;\n }\n}\n\n/**\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\n * tree.\n */\nexport class SortedMap {\n /**\n * Always use the same empty node, to reduce memory.\n */\n static EMPTY_NODE = new LLRBEmptyNode();\n\n /**\n * @param comparator_ - Key comparator.\n * @param root_ - Optional root node for the map.\n */\n constructor(\n private comparator_: Comparator,\n private root_:\n | LLRBNode\n | LLRBEmptyNode = SortedMap.EMPTY_NODE as LLRBEmptyNode\n ) {}\n\n /**\n * Returns a copy of the map, with the specified key/value added or replaced.\n * (TODO: We should perhaps rename this method to 'put')\n *\n * @param key - Key to be added.\n * @param value - Value to be added.\n * @returns New map, with item added.\n */\n insert(key: K, value: V): SortedMap {\n return new SortedMap(\n this.comparator_,\n this.root_\n .insert(key, value, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n /**\n * Returns a copy of the map, with the specified key removed.\n *\n * @param key - The key to remove.\n * @returns New map, with item removed.\n */\n remove(key: K): SortedMap {\n return new SortedMap(\n this.comparator_,\n this.root_\n .remove(key, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n /**\n * Returns the value of the node with the given key, or null.\n *\n * @param key - The key to look up.\n * @returns The value of the node with the given key, or null if the\n * key doesn't exist.\n */\n get(key: K): V | null {\n let cmp;\n let node = this.root_;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n return node.value;\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n }\n\n /**\n * Returns the key of the item *before* the specified key, or null if key is the first item.\n * @param key - The key to find the predecessor of\n * @returns The predecessor key.\n */\n getPredecessorKey(key: K): K | null {\n let cmp,\n node = this.root_,\n rightParent = null;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n if (!node.left.isEmpty()) {\n node = node.left;\n while (!node.right.isEmpty()) {\n node = node.right;\n }\n return node.key;\n } else if (rightParent) {\n return rightParent.key;\n } else {\n return null; // first item.\n }\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n\n throw new Error(\n 'Attempted to find predecessor key for a nonexistent key. What gives?'\n );\n }\n\n /**\n * @returns True if the map is empty.\n */\n isEmpty(): boolean {\n return this.root_.isEmpty();\n }\n\n /**\n * @returns The total number of nodes in the map.\n */\n count(): number {\n return this.root_.count();\n }\n\n /**\n * @returns The minimum key in the map.\n */\n minKey(): K | null {\n return this.root_.minKey();\n }\n\n /**\n * @returns The maximum key in the map.\n */\n maxKey(): K | null {\n return this.root_.maxKey();\n }\n\n /**\n * Traverses the map in key order and calls the specified action function\n * for each key/value pair.\n *\n * @param action - Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @returns The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n inorderTraversal(action: (k: K, v: V) => unknown): boolean {\n return this.root_.inorderTraversal(action);\n }\n\n /**\n * Traverses the map in reverse key order and calls the specified action function\n * for each key/value pair.\n *\n * @param action - Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @returns True if the traversal was aborted.\n */\n reverseTraversal(action: (k: K, v: V) => void): boolean {\n return this.root_.reverseTraversal(action);\n }\n\n /**\n * Returns an iterator over the SortedMap.\n * @returns The iterator.\n */\n getIterator(\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n null,\n this.comparator_,\n false,\n resultGenerator\n );\n }\n\n getIteratorFrom(\n key: K,\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n key,\n this.comparator_,\n false,\n resultGenerator\n );\n }\n\n getReverseIteratorFrom(\n key: K,\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n key,\n this.comparator_,\n true,\n resultGenerator\n );\n }\n\n getReverseIterator(\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n null,\n this.comparator_,\n true,\n resultGenerator\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare } from '../util/util';\n\nimport { NamedNode } from './Node';\n\nexport function NAME_ONLY_COMPARATOR(left: NamedNode, right: NamedNode) {\n return nameCompare(left.name, right.name);\n}\n\nexport function NAME_COMPARATOR(left: string, right: string) {\n return nameCompare(left, right);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, contains } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport { doubleToIEEE754String } from '../util/util';\n\nimport { Node } from './Node';\n\nlet MAX_NODE: Node;\n\nexport function setMaxNode(val: Node) {\n MAX_NODE = val;\n}\n\nexport const priorityHashText = function (priority: string | number): string {\n if (typeof priority === 'number') {\n return 'number:' + doubleToIEEE754String(priority);\n } else {\n return 'string:' + priority;\n }\n};\n\n/**\n * Validates that a priority snapshot Node is valid.\n */\nexport const validatePriorityNode = function (priorityNode: Node) {\n if (priorityNode.isLeafNode()) {\n const val = priorityNode.val();\n assert(\n typeof val === 'string' ||\n typeof val === 'number' ||\n (typeof val === 'object' && contains(val as Indexable, '.sv')),\n 'Priority must be a string or number.'\n );\n } else {\n assert(\n priorityNode === MAX_NODE || priorityNode.isEmpty(),\n 'priority of unexpected type.'\n );\n }\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\n assert(\n priorityNode === MAX_NODE || priorityNode.getPriority().isEmpty(),\n \"Priority nodes can't have a priority of their own.\"\n );\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport {\n Path,\n pathGetFront,\n pathGetLength,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\nimport { doubleToIEEE754String, sha1 } from '../util/util';\n\nimport { ChildrenNodeConstructor } from './ChildrenNode';\nimport { Index } from './indexes/Index';\nimport { Node } from './Node';\nimport { priorityHashText, validatePriorityNode } from './snap';\n\nlet __childrenNodeConstructor: ChildrenNodeConstructor;\n\n/**\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\n * implements Node and stores the value of the node (a string,\n * number, or boolean) accessible via getValue().\n */\nexport class LeafNode implements Node {\n static set __childrenNodeConstructor(val: ChildrenNodeConstructor) {\n __childrenNodeConstructor = val;\n }\n\n static get __childrenNodeConstructor() {\n return __childrenNodeConstructor;\n }\n\n /**\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\n * the same type, the comparison falls back to their value\n */\n static VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n\n private lazyHash_: string | null = null;\n\n /**\n * @param value_ - The value to store in this leaf node. The object type is\n * possible in the event of a deferred value\n * @param priorityNode_ - The priority of this node.\n */\n constructor(\n private readonly value_: string | number | boolean | Indexable,\n private priorityNode_: Node = LeafNode.__childrenNodeConstructor.EMPTY_NODE\n ) {\n assert(\n this.value_ !== undefined && this.value_ !== null,\n \"LeafNode shouldn't be created with null/undefined value.\"\n );\n\n validatePriorityNode(this.priorityNode_);\n }\n\n /** @inheritDoc */\n isLeafNode(): boolean {\n return true;\n }\n\n /** @inheritDoc */\n getPriority(): Node {\n return this.priorityNode_;\n }\n\n /** @inheritDoc */\n updatePriority(newPriorityNode: Node): Node {\n return new LeafNode(this.value_, newPriorityNode);\n }\n\n /** @inheritDoc */\n getImmediateChild(childName: string): Node {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.priorityNode_;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n }\n\n /** @inheritDoc */\n getChild(path: Path): Node {\n if (pathIsEmpty(path)) {\n return this;\n } else if (pathGetFront(path) === '.priority') {\n return this.priorityNode_;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n }\n hasChild(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n getPredecessorChildName(childName: string, childNode: Node): null {\n return null;\n }\n\n /** @inheritDoc */\n updateImmediateChild(childName: string, newChildNode: Node): Node {\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n } else if (newChildNode.isEmpty() && childName !== '.priority') {\n return this;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(\n childName,\n newChildNode\n ).updatePriority(this.priorityNode_);\n }\n }\n\n /** @inheritDoc */\n updateChild(path: Path, newChildNode: Node): Node {\n const front = pathGetFront(path);\n if (front === null) {\n return newChildNode;\n } else if (newChildNode.isEmpty() && front !== '.priority') {\n return this;\n } else {\n assert(\n front !== '.priority' || pathGetLength(path) === 1,\n '.priority must be the last token in a path'\n );\n\n return this.updateImmediateChild(\n front,\n LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(\n pathPopFront(path),\n newChildNode\n )\n );\n }\n }\n\n /** @inheritDoc */\n isEmpty(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n numChildren(): number {\n return 0;\n }\n\n /** @inheritDoc */\n forEachChild(index: Index, action: (s: string, n: Node) => void): boolean {\n return false;\n }\n val(exportFormat?: boolean): {} {\n if (exportFormat && !this.getPriority().isEmpty()) {\n return {\n '.value': this.getValue(),\n '.priority': this.getPriority().val()\n };\n } else {\n return this.getValue();\n }\n }\n\n /** @inheritDoc */\n hash(): string {\n if (this.lazyHash_ === null) {\n let toHash = '';\n if (!this.priorityNode_.isEmpty()) {\n toHash +=\n 'priority:' +\n priorityHashText(this.priorityNode_.val() as number | string) +\n ':';\n }\n\n const type = typeof this.value_;\n toHash += type + ':';\n if (type === 'number') {\n toHash += doubleToIEEE754String(this.value_ as number);\n } else {\n toHash += this.value_;\n }\n this.lazyHash_ = sha1(toHash);\n }\n return this.lazyHash_;\n }\n\n /**\n * Returns the value of the leaf node.\n * @returns The value of the node.\n */\n getValue(): Indexable | string | number | boolean {\n return this.value_;\n }\n compareTo(other: Node): number {\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\n return 1;\n } else if (other instanceof LeafNode.__childrenNodeConstructor) {\n return -1;\n } else {\n assert(other.isLeafNode(), 'Unknown node type');\n return this.compareToLeafNode_(other as LeafNode);\n }\n }\n\n /**\n * Comparison specifically for two leaf nodes\n */\n private compareToLeafNode_(otherLeaf: LeafNode): number {\n const otherLeafType = typeof otherLeaf.value_;\n const thisLeafType = typeof this.value_;\n const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\n const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\n assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\n assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\n if (otherIndex === thisIndex) {\n // Same type, compare values\n if (thisLeafType === 'object') {\n // Deferred value nodes are all equal, but we should also never get to this point...\n return 0;\n } else {\n // Note that this works because true > false, all others are number or string comparisons\n if (this.value_ < otherLeaf.value_) {\n return -1;\n } else if (this.value_ === otherLeaf.value_) {\n return 0;\n } else {\n return 1;\n }\n }\n } else {\n return thisIndex - otherIndex;\n }\n }\n withIndex(): Node {\n return this;\n }\n isIndexed(): boolean {\n return true;\n }\n equals(other: Node): boolean {\n if (other === this) {\n return true;\n } else if (other.isLeafNode()) {\n const otherLeaf = other as LeafNode;\n return (\n this.value_ === otherLeaf.value_ &&\n this.priorityNode_.equals(otherLeaf.priorityNode_)\n );\n } else {\n return false;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare, MAX_NAME } from '../../util/util';\nimport { LeafNode } from '../LeafNode';\nimport { NamedNode, Node } from '../Node';\n\nimport { Index } from './Index';\n\nlet nodeFromJSON: (a: unknown) => Node;\nlet MAX_NODE: Node;\n\nexport function setNodeFromJSON(val: (a: unknown) => Node) {\n nodeFromJSON = val;\n}\n\nexport function setMaxNode(val: Node) {\n MAX_NODE = val;\n}\n\nexport class PriorityIndex extends Index {\n compare(a: NamedNode, b: NamedNode): number {\n const aPriority = a.node.getPriority();\n const bPriority = b.node.getPriority();\n const indexCmp = aPriority.compareTo(bPriority);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n isDefinedOn(node: Node): boolean {\n return !node.getPriority().isEmpty();\n }\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return !oldNode.getPriority().equals(newNode.getPriority());\n }\n minPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n maxPost(): NamedNode {\n return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE));\n }\n\n makePost(indexValue: unknown, name: string): NamedNode {\n const priorityNode = nodeFromJSON(indexValue);\n return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));\n }\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString(): string {\n return '.priority';\n }\n}\n\nexport const PRIORITY_INDEX = new PriorityIndex();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LLRBNode, SortedMap } from '../util/SortedMap';\n\nimport { NamedNode } from './Node';\n\nconst LOG_2 = Math.log(2);\n\nclass Base12Num {\n count: number;\n private current_: number;\n private bits_: number;\n\n constructor(length: number) {\n const logBase2 = (num: number) =>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parseInt((Math.log(num) / LOG_2) as any, 10);\n const bitMask = (bits: number) => parseInt(Array(bits + 1).join('1'), 2);\n this.count = logBase2(length + 1);\n this.current_ = this.count - 1;\n const mask = bitMask(this.count);\n this.bits_ = (length + 1) & mask;\n }\n\n nextBitIsOne(): boolean {\n //noinspection JSBitwiseOperatorUsage\n const result = !(this.bits_ & (0x1 << this.current_));\n this.current_--;\n return result;\n }\n}\n\n/**\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\n * function\n *\n * Uses the algorithm described in the paper linked here:\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\n *\n * @param childList - Unsorted list of children\n * @param cmp - The comparison method to be used\n * @param keyFn - An optional function to extract K from a node wrapper, if K's\n * type is not NamedNode\n * @param mapSortFn - An optional override for comparator used by the generated sorted map\n */\nexport const buildChildSet = function (\n childList: NamedNode[],\n cmp: (a: NamedNode, b: NamedNode) => number,\n keyFn?: (a: NamedNode) => K,\n mapSortFn?: (a: K, b: K) => number\n): SortedMap {\n childList.sort(cmp);\n\n const buildBalancedTree = function (\n low: number,\n high: number\n ): LLRBNode | null {\n const length = high - low;\n let namedNode: NamedNode;\n let key: K;\n if (length === 0) {\n return null;\n } else if (length === 1) {\n namedNode = childList[low];\n key = keyFn ? keyFn(namedNode) : (namedNode as unknown as K);\n return new LLRBNode(\n key,\n namedNode.node as unknown as V,\n LLRBNode.BLACK,\n null,\n null\n );\n } else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const middle = parseInt((length / 2) as any, 10) + low;\n const left = buildBalancedTree(low, middle);\n const right = buildBalancedTree(middle + 1, high);\n namedNode = childList[middle];\n key = keyFn ? keyFn(namedNode) : (namedNode as unknown as K);\n return new LLRBNode(\n key,\n namedNode.node as unknown as V,\n LLRBNode.BLACK,\n left,\n right\n );\n }\n };\n\n const buildFrom12Array = function (base12: Base12Num): LLRBNode {\n let node: LLRBNode = null;\n let root = null;\n let index = childList.length;\n\n const buildPennant = function (chunkSize: number, color: boolean) {\n const low = index - chunkSize;\n const high = index;\n index -= chunkSize;\n const childTree = buildBalancedTree(low + 1, high);\n const namedNode = childList[low];\n const key: K = keyFn ? keyFn(namedNode) : (namedNode as unknown as K);\n attachPennant(\n new LLRBNode(\n key,\n namedNode.node as unknown as V,\n color,\n null,\n childTree\n )\n );\n };\n\n const attachPennant = function (pennant: LLRBNode) {\n if (node) {\n node.left = pennant;\n node = pennant;\n } else {\n root = pennant;\n node = pennant;\n }\n };\n\n for (let i = 0; i < base12.count; ++i) {\n const isOne = base12.nextBitIsOne();\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\n const chunkSize = Math.pow(2, base12.count - (i + 1));\n if (isOne) {\n buildPennant(chunkSize, LLRBNode.BLACK);\n } else {\n // current == 2\n buildPennant(chunkSize, LLRBNode.BLACK);\n buildPennant(chunkSize, LLRBNode.RED);\n }\n }\n return root;\n };\n\n const base12 = new Base12Num(childList.length);\n const root = buildFrom12Array(base12);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new SortedMap(mapSortFn || (cmp as any), root);\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, contains, map, safeGet } from '@firebase/util';\n\nimport { SortedMap } from '../util/SortedMap';\n\nimport { buildChildSet } from './childSet';\nimport { Index } from './indexes/Index';\nimport { KEY_INDEX } from './indexes/KeyIndex';\nimport { PRIORITY_INDEX } from './indexes/PriorityIndex';\nimport { NamedNode, Node } from './Node';\n\nlet _defaultIndexMap: IndexMap;\n\nconst fallbackObject = {};\n\nexport class IndexMap {\n /**\n * The default IndexMap for nodes without a priority\n */\n static get Default(): IndexMap {\n assert(\n fallbackObject && PRIORITY_INDEX,\n 'ChildrenNode.ts has not been loaded'\n );\n _defaultIndexMap =\n _defaultIndexMap ||\n new IndexMap(\n { '.priority': fallbackObject },\n { '.priority': PRIORITY_INDEX }\n );\n return _defaultIndexMap;\n }\n\n constructor(\n private indexes_: {\n [k: string]: SortedMap | /*FallbackType*/ object;\n },\n private indexSet_: { [k: string]: Index }\n ) {}\n\n get(indexKey: string): SortedMap | null {\n const sortedMap = safeGet(this.indexes_, indexKey);\n if (!sortedMap) {\n throw new Error('No index defined for ' + indexKey);\n }\n\n if (sortedMap instanceof SortedMap) {\n return sortedMap;\n } else {\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\n // regular child map\n return null;\n }\n }\n\n hasIndex(indexDefinition: Index): boolean {\n return contains(this.indexSet_, indexDefinition.toString());\n }\n\n addIndex(\n indexDefinition: Index,\n existingChildren: SortedMap\n ): IndexMap {\n assert(\n indexDefinition !== KEY_INDEX,\n \"KeyIndex always exists and isn't meant to be added to the IndexMap.\"\n );\n const childList = [];\n let sawIndexedValue = false;\n const iter = existingChildren.getIterator(NamedNode.Wrap);\n let next = iter.getNext();\n while (next) {\n sawIndexedValue =\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\n childList.push(next);\n next = iter.getNext();\n }\n let newIndex;\n if (sawIndexedValue) {\n newIndex = buildChildSet(childList, indexDefinition.getCompare());\n } else {\n newIndex = fallbackObject;\n }\n const indexName = indexDefinition.toString();\n const newIndexSet = { ...this.indexSet_ };\n newIndexSet[indexName] = indexDefinition;\n const newIndexes = { ...this.indexes_ };\n newIndexes[indexName] = newIndex;\n return new IndexMap(newIndexes, newIndexSet);\n }\n\n /**\n * Ensure that this node is properly tracked in any indexes that we're maintaining\n */\n addToIndexes(\n namedNode: NamedNode,\n existingChildren: SortedMap\n ): IndexMap {\n const newIndexes = map(\n this.indexes_,\n (indexedChildren: SortedMap, indexName: string) => {\n const index = safeGet(this.indexSet_, indexName);\n assert(index, 'Missing index implementation for ' + indexName);\n if (indexedChildren === fallbackObject) {\n // Check to see if we need to index everything\n if (index.isDefinedOn(namedNode.node)) {\n // We need to build this index\n const childList = [];\n const iter = existingChildren.getIterator(NamedNode.Wrap);\n let next = iter.getNext();\n while (next) {\n if (next.name !== namedNode.name) {\n childList.push(next);\n }\n next = iter.getNext();\n }\n childList.push(namedNode);\n return buildChildSet(childList, index.getCompare());\n } else {\n // No change, this remains a fallback\n return fallbackObject;\n }\n } else {\n const existingSnap = existingChildren.get(namedNode.name);\n let newChildren = indexedChildren;\n if (existingSnap) {\n newChildren = newChildren.remove(\n new NamedNode(namedNode.name, existingSnap)\n );\n }\n return newChildren.insert(namedNode, namedNode.node);\n }\n }\n );\n return new IndexMap(newIndexes, this.indexSet_);\n }\n\n /**\n * Create a new IndexMap instance with the given value removed\n */\n removeFromIndexes(\n namedNode: NamedNode,\n existingChildren: SortedMap\n ): IndexMap {\n const newIndexes = map(\n this.indexes_,\n (indexedChildren: SortedMap) => {\n if (indexedChildren === fallbackObject) {\n // This is the fallback. Just return it, nothing to do in this case\n return indexedChildren;\n } else {\n const existingSnap = existingChildren.get(namedNode.name);\n if (existingSnap) {\n return indexedChildren.remove(\n new NamedNode(namedNode.name, existingSnap)\n );\n } else {\n // No record of this child\n return indexedChildren;\n }\n }\n }\n );\n return new IndexMap(newIndexes, this.indexSet_);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Path, pathGetFront, pathGetLength, pathPopFront } from '../util/Path';\nimport { SortedMap, SortedMapIterator } from '../util/SortedMap';\nimport { MAX_NAME, MIN_NAME, sha1 } from '../util/util';\n\nimport { NAME_COMPARATOR } from './comparators';\nimport { Index } from './indexes/Index';\nimport { KEY_INDEX, KeyIndex } from './indexes/KeyIndex';\nimport {\n PRIORITY_INDEX,\n setMaxNode as setPriorityMaxNode\n} from './indexes/PriorityIndex';\nimport { IndexMap } from './IndexMap';\nimport { LeafNode } from './LeafNode';\nimport { NamedNode, Node } from './Node';\nimport { priorityHashText, setMaxNode, validatePriorityNode } from './snap';\n\nexport interface ChildrenNodeConstructor {\n new (\n children_: SortedMap,\n priorityNode_: Node | null,\n indexMap_: IndexMap\n ): ChildrenNode;\n EMPTY_NODE: ChildrenNode;\n}\n\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\n\nlet EMPTY_NODE: ChildrenNode;\n\n/**\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\n * (i.e. nodes with children). It implements Node and stores the\n * list of children in the children property, sorted by child name.\n */\nexport class ChildrenNode implements Node {\n private lazyHash_: string | null = null;\n\n static get EMPTY_NODE(): ChildrenNode {\n return (\n EMPTY_NODE ||\n (EMPTY_NODE = new ChildrenNode(\n new SortedMap(NAME_COMPARATOR),\n null,\n IndexMap.Default\n ))\n );\n }\n\n /**\n * @param children_ - List of children of this node..\n * @param priorityNode_ - The priority of this node (as a snapshot node).\n */\n constructor(\n private readonly children_: SortedMap,\n private readonly priorityNode_: Node | null,\n private indexMap_: IndexMap\n ) {\n /**\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\n * class instead of an empty ChildrenNode.\n */\n if (this.priorityNode_) {\n validatePriorityNode(this.priorityNode_);\n }\n\n if (this.children_.isEmpty()) {\n assert(\n !this.priorityNode_ || this.priorityNode_.isEmpty(),\n 'An empty node cannot have a priority'\n );\n }\n }\n\n /** @inheritDoc */\n isLeafNode(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n getPriority(): Node {\n return this.priorityNode_ || EMPTY_NODE;\n }\n\n /** @inheritDoc */\n updatePriority(newPriorityNode: Node): Node {\n if (this.children_.isEmpty()) {\n // Don't allow priorities on empty nodes\n return this;\n } else {\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\n }\n }\n\n /** @inheritDoc */\n getImmediateChild(childName: string): Node {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.getPriority();\n } else {\n const child = this.children_.get(childName);\n return child === null ? EMPTY_NODE : child;\n }\n }\n\n /** @inheritDoc */\n getChild(path: Path): Node {\n const front = pathGetFront(path);\n if (front === null) {\n return this;\n }\n\n return this.getImmediateChild(front).getChild(pathPopFront(path));\n }\n\n /** @inheritDoc */\n hasChild(childName: string): boolean {\n return this.children_.get(childName) !== null;\n }\n\n /** @inheritDoc */\n updateImmediateChild(childName: string, newChildNode: Node): Node {\n assert(newChildNode, 'We should always be passing snapshot nodes');\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n } else {\n const namedNode = new NamedNode(childName, newChildNode);\n let newChildren, newIndexMap;\n if (newChildNode.isEmpty()) {\n newChildren = this.children_.remove(childName);\n newIndexMap = this.indexMap_.removeFromIndexes(\n namedNode,\n this.children_\n );\n } else {\n newChildren = this.children_.insert(childName, newChildNode);\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\n }\n\n const newPriority = newChildren.isEmpty()\n ? EMPTY_NODE\n : this.priorityNode_;\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\n }\n }\n\n /** @inheritDoc */\n updateChild(path: Path, newChildNode: Node): Node {\n const front = pathGetFront(path);\n if (front === null) {\n return newChildNode;\n } else {\n assert(\n pathGetFront(path) !== '.priority' || pathGetLength(path) === 1,\n '.priority must be the last token in a path'\n );\n const newImmediateChild = this.getImmediateChild(front).updateChild(\n pathPopFront(path),\n newChildNode\n );\n return this.updateImmediateChild(front, newImmediateChild);\n }\n }\n\n /** @inheritDoc */\n isEmpty(): boolean {\n return this.children_.isEmpty();\n }\n\n /** @inheritDoc */\n numChildren(): number {\n return this.children_.count();\n }\n\n private static INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\n\n /** @inheritDoc */\n val(exportFormat?: boolean): object {\n if (this.isEmpty()) {\n return null;\n }\n\n const obj: { [k: string]: unknown } = {};\n let numKeys = 0,\n maxKey = 0,\n allIntegerKeys = true;\n this.forEachChild(PRIORITY_INDEX, (key: string, childNode: Node) => {\n obj[key] = childNode.val(exportFormat);\n\n numKeys++;\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\n maxKey = Math.max(maxKey, Number(key));\n } else {\n allIntegerKeys = false;\n }\n });\n\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\n // convert to array.\n const array: unknown[] = [];\n // eslint-disable-next-line guard-for-in\n for (const key in obj) {\n array[key as unknown as number] = obj[key];\n }\n\n return array;\n } else {\n if (exportFormat && !this.getPriority().isEmpty()) {\n obj['.priority'] = this.getPriority().val();\n }\n return obj;\n }\n }\n\n /** @inheritDoc */\n hash(): string {\n if (this.lazyHash_ === null) {\n let toHash = '';\n if (!this.getPriority().isEmpty()) {\n toHash +=\n 'priority:' +\n priorityHashText(this.getPriority().val() as string | number) +\n ':';\n }\n\n this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n const childHash = childNode.hash();\n if (childHash !== '') {\n toHash += ':' + key + ':' + childHash;\n }\n });\n\n this.lazyHash_ = toHash === '' ? '' : sha1(toHash);\n }\n return this.lazyHash_;\n }\n\n /** @inheritDoc */\n getPredecessorChildName(\n childName: string,\n childNode: Node,\n index: Index\n ): string {\n const idx = this.resolveIndex_(index);\n if (idx) {\n const predecessor = idx.getPredecessorKey(\n new NamedNode(childName, childNode)\n );\n return predecessor ? predecessor.name : null;\n } else {\n return this.children_.getPredecessorKey(childName);\n }\n }\n\n getFirstChildName(indexDefinition: Index): string | null {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n const minKey = idx.minKey();\n return minKey && minKey.name;\n } else {\n return this.children_.minKey();\n }\n }\n\n getFirstChild(indexDefinition: Index): NamedNode | null {\n const minKey = this.getFirstChildName(indexDefinition);\n if (minKey) {\n return new NamedNode(minKey, this.children_.get(minKey));\n } else {\n return null;\n }\n }\n\n /**\n * Given an index, return the key name of the largest value we have, according to that index\n */\n getLastChildName(indexDefinition: Index): string | null {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n const maxKey = idx.maxKey();\n return maxKey && maxKey.name;\n } else {\n return this.children_.maxKey();\n }\n }\n\n getLastChild(indexDefinition: Index): NamedNode | null {\n const maxKey = this.getLastChildName(indexDefinition);\n if (maxKey) {\n return new NamedNode(maxKey, this.children_.get(maxKey));\n } else {\n return null;\n }\n }\n forEachChild(\n index: Index,\n action: (key: string, node: Node) => boolean | void\n ): boolean {\n const idx = this.resolveIndex_(index);\n if (idx) {\n return idx.inorderTraversal(wrappedNode => {\n return action(wrappedNode.name, wrappedNode.node);\n });\n } else {\n return this.children_.inorderTraversal(action);\n }\n }\n\n getIterator(\n indexDefinition: Index\n ): SortedMapIterator {\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\n }\n\n getIteratorFrom(\n startPost: NamedNode,\n indexDefinition: Index\n ): SortedMapIterator {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getIteratorFrom(startPost, key => key);\n } else {\n const iterator = this.children_.getIteratorFrom(\n startPost.name,\n NamedNode.Wrap\n );\n let next = iterator.peek();\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n }\n\n getReverseIterator(\n indexDefinition: Index\n ): SortedMapIterator {\n return this.getReverseIteratorFrom(\n indexDefinition.maxPost(),\n indexDefinition\n );\n }\n\n getReverseIteratorFrom(\n endPost: NamedNode,\n indexDefinition: Index\n ): SortedMapIterator {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getReverseIteratorFrom(endPost, key => {\n return key;\n });\n } else {\n const iterator = this.children_.getReverseIteratorFrom(\n endPost.name,\n NamedNode.Wrap\n );\n let next = iterator.peek();\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n }\n compareTo(other: ChildrenNode): number {\n if (this.isEmpty()) {\n if (other.isEmpty()) {\n return 0;\n } else {\n return -1;\n }\n } else if (other.isLeafNode() || other.isEmpty()) {\n return 1;\n } else if (other === MAX_NODE) {\n return -1;\n } else {\n // Must be another node with children.\n return 0;\n }\n }\n withIndex(indexDefinition: Index): Node {\n if (\n indexDefinition === KEY_INDEX ||\n this.indexMap_.hasIndex(indexDefinition)\n ) {\n return this;\n } else {\n const newIndexMap = this.indexMap_.addIndex(\n indexDefinition,\n this.children_\n );\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\n }\n }\n isIndexed(index: Index): boolean {\n return index === KEY_INDEX || this.indexMap_.hasIndex(index);\n }\n equals(other: Node): boolean {\n if (other === this) {\n return true;\n } else if (other.isLeafNode()) {\n return false;\n } else {\n const otherChildrenNode = other as ChildrenNode;\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\n return false;\n } else if (\n this.children_.count() === otherChildrenNode.children_.count()\n ) {\n const thisIter = this.getIterator(PRIORITY_INDEX);\n const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);\n let thisCurrent = thisIter.getNext();\n let otherCurrent = otherIter.getNext();\n while (thisCurrent && otherCurrent) {\n if (\n thisCurrent.name !== otherCurrent.name ||\n !thisCurrent.node.equals(otherCurrent.node)\n ) {\n return false;\n }\n thisCurrent = thisIter.getNext();\n otherCurrent = otherIter.getNext();\n }\n return thisCurrent === null && otherCurrent === null;\n } else {\n return false;\n }\n }\n }\n\n /**\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\n * instead.\n *\n */\n private resolveIndex_(\n indexDefinition: Index\n ): SortedMap | null {\n if (indexDefinition === KEY_INDEX) {\n return null;\n } else {\n return this.indexMap_.get(indexDefinition.toString());\n }\n }\n}\n\nexport class MaxNode extends ChildrenNode {\n constructor() {\n super(\n new SortedMap(NAME_COMPARATOR),\n ChildrenNode.EMPTY_NODE,\n IndexMap.Default\n );\n }\n\n compareTo(other: Node): number {\n if (other === this) {\n return 0;\n } else {\n return 1;\n }\n }\n\n equals(other: Node): boolean {\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\n return other === this;\n }\n\n getPriority(): MaxNode {\n return this;\n }\n\n getImmediateChild(childName: string): ChildrenNode {\n return ChildrenNode.EMPTY_NODE;\n }\n\n isEmpty(): boolean {\n return false;\n }\n}\n\n/**\n * Marker that will sort higher than any other snapshot.\n */\nexport const MAX_NODE = new MaxNode();\n\n/**\n * Document NamedNode extensions\n */\ndeclare module './Node' {\n interface NamedNode {\n MIN: NamedNode;\n MAX: NamedNode;\n }\n}\n\nObject.defineProperties(NamedNode, {\n MIN: {\n value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)\n },\n MAX: {\n value: new NamedNode(MAX_NAME, MAX_NODE)\n }\n});\n\n/**\n * Reference Extensions\n */\nKeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\nLeafNode.__childrenNodeConstructor = ChildrenNode;\nsetMaxNode(MAX_NODE);\nsetPriorityMaxNode(MAX_NODE);\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains, assert } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport { SortedMap } from '../util/SortedMap';\nimport { each } from '../util/util';\n\nimport { ChildrenNode } from './ChildrenNode';\nimport { buildChildSet } from './childSet';\nimport { NAME_COMPARATOR, NAME_ONLY_COMPARATOR } from './comparators';\nimport { PRIORITY_INDEX, setNodeFromJSON } from './indexes/PriorityIndex';\nimport { IndexMap } from './IndexMap';\nimport { LeafNode } from './LeafNode';\nimport { NamedNode, Node } from './Node';\n\nconst USE_HINZE = true;\n\n/**\n * Constructs a snapshot node representing the passed JSON and returns it.\n * @param json - JSON to create a node for.\n * @param priority - Optional priority to use. This will be ignored if the\n * passed JSON contains a .priority property.\n */\nexport function nodeFromJSON(\n json: unknown | null,\n priority: unknown = null\n): Node {\n if (json === null) {\n return ChildrenNode.EMPTY_NODE;\n }\n\n if (typeof json === 'object' && '.priority' in json) {\n priority = json['.priority'];\n }\n\n assert(\n priority === null ||\n typeof priority === 'string' ||\n typeof priority === 'number' ||\n (typeof priority === 'object' && '.sv' in (priority as object)),\n 'Invalid priority type found: ' + typeof priority\n );\n\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\n json = json['.value'];\n }\n\n // Valid leaf nodes include non-objects or server-value wrapper objects\n if (typeof json !== 'object' || '.sv' in json) {\n const jsonLeaf = json as string | number | boolean | Indexable;\n return new LeafNode(jsonLeaf, nodeFromJSON(priority));\n }\n\n if (!(json instanceof Array) && USE_HINZE) {\n const children: NamedNode[] = [];\n let childrenHavePriority = false;\n const hinzeJsonObj = json;\n each(hinzeJsonObj, (key, child) => {\n if (key.substring(0, 1) !== '.') {\n // Ignore metadata nodes\n const childNode = nodeFromJSON(child);\n if (!childNode.isEmpty()) {\n childrenHavePriority =\n childrenHavePriority || !childNode.getPriority().isEmpty();\n children.push(new NamedNode(key, childNode));\n }\n }\n });\n\n if (children.length === 0) {\n return ChildrenNode.EMPTY_NODE;\n }\n\n const childSet = buildChildSet(\n children,\n NAME_ONLY_COMPARATOR,\n namedNode => namedNode.name,\n NAME_COMPARATOR\n ) as SortedMap;\n if (childrenHavePriority) {\n const sortedChildSet = buildChildSet(\n children,\n PRIORITY_INDEX.getCompare()\n );\n return new ChildrenNode(\n childSet,\n nodeFromJSON(priority),\n new IndexMap(\n { '.priority': sortedChildSet },\n { '.priority': PRIORITY_INDEX }\n )\n );\n } else {\n return new ChildrenNode(\n childSet,\n nodeFromJSON(priority),\n IndexMap.Default\n );\n }\n } else {\n let node: Node = ChildrenNode.EMPTY_NODE;\n each(json, (key: string, childData: unknown) => {\n if (contains(json as object, key)) {\n if (key.substring(0, 1) !== '.') {\n // ignore metadata nodes.\n const childNode = nodeFromJSON(childData);\n if (childNode.isLeafNode() || !childNode.isEmpty()) {\n node = node.updateImmediateChild(key, childNode);\n }\n }\n }\n });\n\n return node.updatePriority(nodeFromJSON(priority));\n }\n}\n\nsetNodeFromJSON(nodeFromJSON);\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Path, pathGetFront, pathIsEmpty, pathSlice } from '../../util/Path';\nimport { MAX_NAME, nameCompare } from '../../util/util';\nimport { ChildrenNode, MAX_NODE } from '../ChildrenNode';\nimport { NamedNode, Node } from '../Node';\nimport { nodeFromJSON } from '../nodeFromJSON';\n\nimport { Index } from './Index';\n\nexport class PathIndex extends Index {\n constructor(private indexPath_: Path) {\n super();\n\n assert(\n !pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority',\n \"Can't create PathIndex with empty path or .priority key\"\n );\n }\n\n protected extractChild(snap: Node): Node {\n return snap.getChild(this.indexPath_);\n }\n isDefinedOn(node: Node): boolean {\n return !node.getChild(this.indexPath_).isEmpty();\n }\n compare(a: NamedNode, b: NamedNode): number {\n const aChild = this.extractChild(a.node);\n const bChild = this.extractChild(b.node);\n const indexCmp = aChild.compareTo(bChild);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n makePost(indexValue: object, name: string): NamedNode {\n const valueNode = nodeFromJSON(indexValue);\n const node = ChildrenNode.EMPTY_NODE.updateChild(\n this.indexPath_,\n valueNode\n );\n return new NamedNode(name, node);\n }\n maxPost(): NamedNode {\n const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);\n return new NamedNode(MAX_NAME, node);\n }\n toString(): string {\n return pathSlice(this.indexPath_, 0).join('/');\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare } from '../../util/util';\nimport { NamedNode, Node } from '../Node';\nimport { nodeFromJSON } from '../nodeFromJSON';\n\nimport { Index } from './Index';\n\nexport class ValueIndex extends Index {\n compare(a: NamedNode, b: NamedNode): number {\n const indexCmp = a.node.compareTo(b.node);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n isDefinedOn(node: Node): boolean {\n return true;\n }\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return !oldNode.equals(newNode);\n }\n minPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n maxPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MAX;\n }\n\n makePost(indexValue: object, name: string): NamedNode {\n const valueNode = nodeFromJSON(indexValue);\n return new NamedNode(name, valueNode);\n }\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n toString(): string {\n return '.value';\n }\n}\n\nexport const VALUE_INDEX = new ValueIndex();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\n\nexport const enum ChangeType {\n /** Event type for a child added */\n CHILD_ADDED = 'child_added',\n /** Event type for a child removed */\n CHILD_REMOVED = 'child_removed',\n /** Event type for a child changed */\n CHILD_CHANGED = 'child_changed',\n /** Event type for a child moved */\n CHILD_MOVED = 'child_moved',\n /** Event type for a value change */\n VALUE = 'value'\n}\n\nexport interface Change {\n /** @param type - The event type */\n type: ChangeType;\n /** @param snapshotNode - The data */\n snapshotNode: Node;\n /** @param childName - The name for this child, if it's a child even */\n childName?: string;\n /** @param oldSnap - Used for intermediate processing of child changed events */\n oldSnap?: Node;\n /** * @param prevName - The name for the previous child, if applicable */\n prevName?: string | null;\n}\n\nexport function changeValue(snapshotNode: Node): Change {\n return { type: ChangeType.VALUE, snapshotNode };\n}\n\nexport function changeChildAdded(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_ADDED, snapshotNode, childName };\n}\n\nexport function changeChildRemoved(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_REMOVED, snapshotNode, childName };\n}\n\nexport function changeChildChanged(\n childName: string,\n snapshotNode: Node,\n oldSnap: Node\n): Change {\n return {\n type: ChangeType.CHILD_CHANGED,\n snapshotNode,\n childName,\n oldSnap\n };\n}\n\nexport function changeChildMoved(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_MOVED, snapshotNode, childName };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { PRIORITY_INDEX } from '../../snap/indexes/PriorityIndex';\nimport { Node } from '../../snap/Node';\nimport { Path } from '../../util/Path';\nimport {\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from '../Change';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\n\nimport { NodeFilter } from './NodeFilter';\n\n/**\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\n */\nexport class IndexedFilter implements NodeFilter {\n constructor(private readonly index_: Index) {}\n\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n assert(\n snap.isIndexed(this.index_),\n 'A node must be indexed if only a child is updated'\n );\n const oldChild = snap.getImmediateChild(key);\n // Check if anything actually changed.\n if (\n oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))\n ) {\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\n // to avoid treating these cases as \"nothing changed.\"\n if (oldChild.isEmpty() === newChild.isEmpty()) {\n // Nothing changed.\n\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\n return snap;\n }\n }\n\n if (optChangeAccumulator != null) {\n if (newChild.isEmpty()) {\n if (snap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(\n changeChildRemoved(key, oldChild)\n );\n } else {\n assert(\n snap.isLeafNode(),\n 'A child remove without an old child only makes sense on a leaf node'\n );\n }\n } else if (oldChild.isEmpty()) {\n optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));\n } else {\n optChangeAccumulator.trackChildChange(\n changeChildChanged(key, newChild, oldChild)\n );\n }\n }\n if (snap.isLeafNode() && newChild.isEmpty()) {\n return snap;\n } else {\n // Make sure the node is indexed\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\n }\n }\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (optChangeAccumulator != null) {\n if (!oldSnap.isLeafNode()) {\n oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (!newSnap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(\n changeChildRemoved(key, childNode)\n );\n }\n });\n }\n if (!newSnap.isLeafNode()) {\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (oldSnap.hasChild(key)) {\n const oldChild = oldSnap.getImmediateChild(key);\n if (!oldChild.equals(childNode)) {\n optChangeAccumulator.trackChildChange(\n changeChildChanged(key, childNode, oldChild)\n );\n }\n } else {\n optChangeAccumulator.trackChildChange(\n changeChildAdded(key, childNode)\n );\n }\n });\n }\n }\n return newSnap.withIndex(this.index_);\n }\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n if (oldSnap.isEmpty()) {\n return ChildrenNode.EMPTY_NODE;\n } else {\n return oldSnap.updatePriority(newPriority);\n }\n }\n filtersNodes(): boolean {\n return false;\n }\n getIndexedFilter(): IndexedFilter {\n return this;\n }\n getIndex(): Index {\n return this.index_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NamedNode, Node } from '../../../core/snap/Node';\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { PRIORITY_INDEX } from '../../snap/indexes/PriorityIndex';\nimport { Path } from '../../util/Path';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\nimport { QueryParams } from '../QueryParams';\n\nimport { IndexedFilter } from './IndexedFilter';\nimport { NodeFilter } from './NodeFilter';\n\n/**\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n */\nexport class RangedFilter implements NodeFilter {\n private indexedFilter_: IndexedFilter;\n\n private index_: Index;\n\n private startPost_: NamedNode;\n\n private endPost_: NamedNode;\n\n private startIsInclusive_: boolean;\n\n private endIsInclusive_: boolean;\n\n constructor(params: QueryParams) {\n this.indexedFilter_ = new IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n this.startIsInclusive_ = !params.startAfterSet_;\n this.endIsInclusive_ = !params.endBeforeSet_;\n }\n\n getStartPost(): NamedNode {\n return this.startPost_;\n }\n\n getEndPost(): NamedNode {\n return this.endPost_;\n }\n\n matches(node: NamedNode): boolean {\n const isWithinStart = this.startIsInclusive_\n ? this.index_.compare(this.getStartPost(), node) <= 0\n : this.index_.compare(this.getStartPost(), node) < 0;\n const isWithinEnd = this.endIsInclusive_\n ? this.index_.compare(node, this.getEndPost()) <= 0\n : this.index_.compare(node, this.getEndPost()) < 0;\n return isWithinStart && isWithinEnd;\n }\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (!this.matches(new NamedNode(key, newChild))) {\n newChild = ChildrenNode.EMPTY_NODE;\n }\n return this.indexedFilter_.updateChild(\n snap,\n key,\n newChild,\n affectedPath,\n source,\n optChangeAccumulator\n );\n }\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode.EMPTY_NODE;\n }\n let filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\n const self = this;\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n if (!self.matches(new NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(\n oldSnap,\n filtered,\n optChangeAccumulator\n );\n }\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n // Don't support priorities on queries\n return oldSnap;\n }\n filtersNodes(): boolean {\n return true;\n }\n getIndexedFilter(): IndexedFilter {\n return this.indexedFilter_;\n }\n getIndex(): Index {\n return this.index_;\n }\n\n private static getStartPost_(params: QueryParams): NamedNode {\n if (params.hasStart()) {\n const startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n } else {\n return params.getIndex().minPost();\n }\n }\n\n private static getEndPost_(params: QueryParams): NamedNode {\n if (params.hasEnd()) {\n const endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n } else {\n return params.getIndex().maxPost();\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { NamedNode, Node } from '../../snap/Node';\nimport { Path } from '../../util/Path';\nimport {\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from '../Change';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\nimport { QueryParams } from '../QueryParams';\n\nimport { IndexedFilter } from './IndexedFilter';\nimport { NodeFilter } from './NodeFilter';\nimport { RangedFilter } from './RangedFilter';\n\n/**\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n */\nexport class LimitedFilter implements NodeFilter {\n private readonly rangedFilter_: RangedFilter;\n\n private readonly index_: Index;\n\n private readonly limit_: number;\n\n private readonly reverse_: boolean;\n\n private readonly startIsInclusive_: boolean;\n\n private readonly endIsInclusive_: boolean;\n\n constructor(params: QueryParams) {\n this.rangedFilter_ = new RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n this.startIsInclusive_ = !params.startAfterSet_;\n this.endIsInclusive_ = !params.endBeforeSet_;\n }\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {\n newChild = ChildrenNode.EMPTY_NODE;\n }\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n } else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_\n .getIndexedFilter()\n .updateChild(\n snap,\n key,\n newChild,\n affectedPath,\n source,\n optChangeAccumulator\n );\n } else {\n return this.fullLimitUpdateChild_(\n snap,\n key,\n newChild,\n source,\n optChangeAccumulator\n );\n }\n }\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n let filtered;\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n } else {\n if (\n this.limit_ * 2 < newSnap.numChildren() &&\n newSnap.isIndexed(this.index_)\n ) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n // anchor to the startPost, endPost, or last element as appropriate\n let iterator;\n if (this.reverse_) {\n iterator = (newSnap as ChildrenNode).getReverseIteratorFrom(\n this.rangedFilter_.getEndPost(),\n this.index_\n );\n } else {\n iterator = (newSnap as ChildrenNode).getIteratorFrom(\n this.rangedFilter_.getStartPost(),\n this.index_\n );\n }\n let count = 0;\n while (iterator.hasNext() && count < this.limit_) {\n const next = iterator.getNext();\n if (!this.withinDirectionalStart(next)) {\n // if we have not reached the start, skip to the next element\n continue;\n } else if (!this.withinDirectionalEnd(next)) {\n // if we have reached the end, stop adding elements\n break;\n } else {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\n }\n }\n } else {\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(\n ChildrenNode.EMPTY_NODE\n ) as ChildrenNode;\n\n let iterator;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n } else {\n iterator = filtered.getIterator(this.index_);\n }\n\n let count = 0;\n while (iterator.hasNext()) {\n const next = iterator.getNext();\n const inRange =\n count < this.limit_ &&\n this.withinDirectionalStart(next) &&\n this.withinDirectionalEnd(next);\n if (inRange) {\n count++;\n } else {\n filtered = filtered.updateImmediateChild(\n next.name,\n ChildrenNode.EMPTY_NODE\n );\n }\n }\n }\n }\n return this.rangedFilter_\n .getIndexedFilter()\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n }\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n // Don't support priorities on queries\n return oldSnap;\n }\n filtersNodes(): boolean {\n return true;\n }\n getIndexedFilter(): IndexedFilter {\n return this.rangedFilter_.getIndexedFilter();\n }\n getIndex(): Index {\n return this.index_;\n }\n\n private fullLimitUpdateChild_(\n snap: Node,\n childKey: string,\n childSnap: Node,\n source: CompleteChildSource,\n changeAccumulator: ChildChangeAccumulator | null\n ): Node {\n // TODO: rename all cache stuff etc to general snap terminology\n let cmp;\n if (this.reverse_) {\n const indexCmp = this.index_.getCompare();\n cmp = (a: NamedNode, b: NamedNode) => indexCmp(b, a);\n } else {\n cmp = this.index_.getCompare();\n }\n const oldEventCache = snap as ChildrenNode;\n assert(oldEventCache.numChildren() === this.limit_, '');\n const newChildNamedNode = new NamedNode(childKey, childSnap);\n const windowBoundary = this.reverse_\n ? oldEventCache.getFirstChild(this.index_)\n : (oldEventCache.getLastChild(this.index_) as NamedNode);\n const inRange = this.rangedFilter_.matches(newChildNamedNode);\n if (oldEventCache.hasChild(childKey)) {\n const oldChildSnap = oldEventCache.getImmediateChild(childKey);\n let nextChild = source.getChildAfterChild(\n this.index_,\n windowBoundary,\n this.reverse_\n );\n while (\n nextChild != null &&\n (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))\n ) {\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\n // the limited filter...\n nextChild = source.getChildAfterChild(\n this.index_,\n nextChild,\n this.reverse_\n );\n }\n const compareNext =\n nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n const remainsInWindow =\n inRange && !childSnap.isEmpty() && compareNext >= 0;\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildChanged(childKey, childSnap, oldChildSnap)\n );\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n } else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildRemoved(childKey, oldChildSnap)\n );\n }\n const newEventCache = oldEventCache.updateImmediateChild(\n childKey,\n ChildrenNode.EMPTY_NODE\n );\n const nextChildInRange =\n nextChild != null && this.rangedFilter_.matches(nextChild);\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildAdded(nextChild.name, nextChild.node)\n );\n }\n return newEventCache.updateImmediateChild(\n nextChild.name,\n nextChild.node\n );\n } else {\n return newEventCache;\n }\n }\n } else if (childSnap.isEmpty()) {\n // we're deleting a node, but it was not in the window, so ignore it\n return snap;\n } else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildRemoved(windowBoundary.name, windowBoundary.node)\n );\n changeAccumulator.trackChildChange(\n changeChildAdded(childKey, childSnap)\n );\n }\n return oldEventCache\n .updateImmediateChild(childKey, childSnap)\n .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);\n } else {\n return snap;\n }\n } else {\n return snap;\n }\n }\n\n private withinDirectionalStart = (node: NamedNode) =>\n this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);\n\n private withinDirectionalEnd = (node: NamedNode) =>\n this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);\n\n private withinStartPost = (node: NamedNode) => {\n const compareRes = this.index_.compare(\n this.rangedFilter_.getStartPost(),\n node\n );\n return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;\n };\n\n private withinEndPost = (node: NamedNode) => {\n const compareRes = this.index_.compare(\n node,\n this.rangedFilter_.getEndPost()\n );\n return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, stringify } from '@firebase/util';\n\nimport { Index } from '../snap/indexes/Index';\nimport { KEY_INDEX } from '../snap/indexes/KeyIndex';\nimport { PathIndex } from '../snap/indexes/PathIndex';\nimport { PRIORITY_INDEX, PriorityIndex } from '../snap/indexes/PriorityIndex';\nimport { VALUE_INDEX } from '../snap/indexes/ValueIndex';\nimport { MAX_NAME, MIN_NAME } from '../util/util';\n\nimport { IndexedFilter } from './filter/IndexedFilter';\nimport { LimitedFilter } from './filter/LimitedFilter';\nimport { NodeFilter } from './filter/NodeFilter';\nimport { RangedFilter } from './filter/RangedFilter';\n\n/**\n * Wire Protocol Constants\n */\nconst enum WIRE_PROTOCOL_CONSTANTS {\n INDEX_START_VALUE = 'sp',\n INDEX_START_NAME = 'sn',\n INDEX_START_IS_INCLUSIVE = 'sin',\n INDEX_END_VALUE = 'ep',\n INDEX_END_NAME = 'en',\n INDEX_END_IS_INCLUSIVE = 'ein',\n LIMIT = 'l',\n VIEW_FROM = 'vf',\n VIEW_FROM_LEFT = 'l',\n VIEW_FROM_RIGHT = 'r',\n INDEX = 'i'\n}\n\n/**\n * REST Query Constants\n */\nconst enum REST_QUERY_CONSTANTS {\n ORDER_BY = 'orderBy',\n PRIORITY_INDEX = '$priority',\n VALUE_INDEX = '$value',\n KEY_INDEX = '$key',\n START_AFTER = 'startAfter',\n START_AT = 'startAt',\n END_AT = 'endAt',\n END_BEFORE = 'endBefore',\n LIMIT_TO_FIRST = 'limitToFirst',\n LIMIT_TO_LAST = 'limitToLast'\n}\n\n/**\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\n * user-facing API level, so it is not done here.\n *\n * @internal\n */\nexport class QueryParams {\n limitSet_ = false;\n startSet_ = false;\n startNameSet_ = false;\n startAfterSet_ = false; // can only be true if startSet_ is true\n endSet_ = false;\n endNameSet_ = false;\n endBeforeSet_ = false; // can only be true if endSet_ is true\n limit_ = 0;\n viewFrom_ = '';\n indexStartValue_: unknown | null = null;\n indexStartName_ = '';\n indexEndValue_: unknown | null = null;\n indexEndName_ = '';\n index_: PriorityIndex = PRIORITY_INDEX;\n\n hasStart(): boolean {\n return this.startSet_;\n }\n\n /**\n * @returns True if it would return from left.\n */\n isViewFromLeft(): boolean {\n if (this.viewFrom_ === '') {\n // limit(), rather than limitToFirst or limitToLast was called.\n // This means that only one of startSet_ and endSet_ is true. Use them\n // to calculate which side of the view to anchor to. If neither is set,\n // anchor to the end.\n return this.startSet_;\n } else {\n return this.viewFrom_ === WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n }\n }\n\n /**\n * Only valid to call if hasStart() returns true\n */\n getIndexStartValue(): unknown {\n assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n }\n\n /**\n * Only valid to call if hasStart() returns true.\n * Returns the starting key name for the range defined by these query parameters\n */\n getIndexStartName(): string {\n assert(this.startSet_, 'Only valid if start has been set');\n if (this.startNameSet_) {\n return this.indexStartName_;\n } else {\n return MIN_NAME;\n }\n }\n\n hasEnd(): boolean {\n return this.endSet_;\n }\n\n /**\n * Only valid to call if hasEnd() returns true.\n */\n getIndexEndValue(): unknown {\n assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n }\n\n /**\n * Only valid to call if hasEnd() returns true.\n * Returns the end key name for the range defined by these query parameters\n */\n getIndexEndName(): string {\n assert(this.endSet_, 'Only valid if end has been set');\n if (this.endNameSet_) {\n return this.indexEndName_;\n } else {\n return MAX_NAME;\n }\n }\n\n hasLimit(): boolean {\n return this.limitSet_;\n }\n\n /**\n * @returns True if a limit has been set and it has been explicitly anchored\n */\n hasAnchoredLimit(): boolean {\n return this.limitSet_ && this.viewFrom_ !== '';\n }\n\n /**\n * Only valid to call if hasLimit() returns true\n */\n getLimit(): number {\n assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n }\n\n getIndex(): Index {\n return this.index_;\n }\n\n loadsAllData(): boolean {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n }\n\n isDefault(): boolean {\n return this.loadsAllData() && this.index_ === PRIORITY_INDEX;\n }\n\n copy(): QueryParams {\n const copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.startAfterSet_ = this.startAfterSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.endBeforeSet_ = this.endBeforeSet_;\n copy.indexEndValue_ = this.indexEndValue_;\n copy.endNameSet_ = this.endNameSet_;\n copy.indexEndName_ = this.indexEndName_;\n copy.index_ = this.index_;\n copy.viewFrom_ = this.viewFrom_;\n return copy;\n }\n}\n\nexport function queryParamsGetNodeFilter(queryParams: QueryParams): NodeFilter {\n if (queryParams.loadsAllData()) {\n return new IndexedFilter(queryParams.getIndex());\n } else if (queryParams.hasLimit()) {\n return new LimitedFilter(queryParams);\n } else {\n return new RangedFilter(queryParams);\n }\n}\n\nexport function queryParamsLimit(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n}\n\nexport function queryParamsLimitToFirst(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n return newParams;\n}\n\nexport function queryParamsLimitToLast(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n return newParams;\n}\n\nexport function queryParamsStartAt(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.startSet_ = true;\n if (indexValue === undefined) {\n indexValue = null;\n }\n newParams.indexStartValue_ = indexValue;\n if (key != null) {\n newParams.startNameSet_ = true;\n newParams.indexStartName_ = key;\n } else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n return newParams;\n}\n\nexport function queryParamsStartAfter(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n let params: QueryParams;\n if (queryParams.index_ === KEY_INDEX || !!key) {\n params = queryParamsStartAt(queryParams, indexValue, key);\n } else {\n params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);\n }\n params.startAfterSet_ = true;\n return params;\n}\n\nexport function queryParamsEndAt(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.endSet_ = true;\n if (indexValue === undefined) {\n indexValue = null;\n }\n newParams.indexEndValue_ = indexValue;\n if (key !== undefined) {\n newParams.endNameSet_ = true;\n newParams.indexEndName_ = key;\n } else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n return newParams;\n}\n\nexport function queryParamsEndBefore(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n let params: QueryParams;\n if (queryParams.index_ === KEY_INDEX || !!key) {\n params = queryParamsEndAt(queryParams, indexValue, key);\n } else {\n params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);\n }\n params.endBeforeSet_ = true;\n return params;\n}\n\nexport function queryParamsOrderBy(\n queryParams: QueryParams,\n index: Index\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.index_ = index;\n return newParams;\n}\n\n/**\n * Returns a set of REST query string parameters representing this query.\n *\n * @returns query string parameters\n */\nexport function queryParamsToRestQueryStringParameters(\n queryParams: QueryParams\n): Record {\n const qs: Record = {};\n\n if (queryParams.isDefault()) {\n return qs;\n }\n\n let orderBy;\n if (queryParams.index_ === PRIORITY_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.PRIORITY_INDEX;\n } else if (queryParams.index_ === VALUE_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.VALUE_INDEX;\n } else if (queryParams.index_ === KEY_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.KEY_INDEX;\n } else {\n assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');\n orderBy = queryParams.index_.toString();\n }\n qs[REST_QUERY_CONSTANTS.ORDER_BY] = stringify(orderBy);\n\n if (queryParams.startSet_) {\n const startParam = queryParams.startAfterSet_\n ? REST_QUERY_CONSTANTS.START_AFTER\n : REST_QUERY_CONSTANTS.START_AT;\n qs[startParam] = stringify(queryParams.indexStartValue_);\n if (queryParams.startNameSet_) {\n qs[startParam] += ',' + stringify(queryParams.indexStartName_);\n }\n }\n\n if (queryParams.endSet_) {\n const endParam = queryParams.endBeforeSet_\n ? REST_QUERY_CONSTANTS.END_BEFORE\n : REST_QUERY_CONSTANTS.END_AT;\n qs[endParam] = stringify(queryParams.indexEndValue_);\n if (queryParams.endNameSet_) {\n qs[endParam] += ',' + stringify(queryParams.indexEndName_);\n }\n }\n\n if (queryParams.limitSet_) {\n if (queryParams.isViewFromLeft()) {\n qs[REST_QUERY_CONSTANTS.LIMIT_TO_FIRST] = queryParams.limit_;\n } else {\n qs[REST_QUERY_CONSTANTS.LIMIT_TO_LAST] = queryParams.limit_;\n }\n }\n\n return qs;\n}\n\nexport function queryParamsGetQueryObject(\n queryParams: QueryParams\n): Record {\n const obj: Record = {};\n if (queryParams.startSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] =\n queryParams.indexStartValue_;\n if (queryParams.startNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] =\n queryParams.indexStartName_;\n }\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE] =\n !queryParams.startAfterSet_;\n }\n if (queryParams.endSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = queryParams.indexEndValue_;\n if (queryParams.endNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = queryParams.indexEndName_;\n }\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE] =\n !queryParams.endBeforeSet_;\n }\n if (queryParams.limitSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = queryParams.limit_;\n let viewFrom = queryParams.viewFrom_;\n if (viewFrom === '') {\n if (queryParams.isViewFromLeft()) {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n } else {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n }\n }\n obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom;\n }\n // For now, priority index is the default, so we only specify if it's some other index\n if (queryParams.index_ !== PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = queryParams.index_.toString();\n }\n return obj;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n jsonEval,\n safeGet,\n querystring,\n Deferred\n} from '@firebase/util';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { logWrapper, warn } from './util/util';\nimport { QueryContext } from './view/EventRegistration';\nimport { queryParamsToRestQueryStringParameters } from './view/QueryParams';\n\n/**\n * An implementation of ServerActions that communicates with the server via REST requests.\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\n * persistent connection (using WebSockets or long-polling)\n */\nexport class ReadonlyRestClient extends ServerActions {\n reportStats(stats: { [k: string]: unknown }): void {\n throw new Error('Method not implemented.');\n }\n\n /** @private {function(...[*])} */\n private log_: (...args: unknown[]) => void = logWrapper('p:rest:');\n\n /**\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\n * that's been removed. :-/\n */\n private listens_: { [k: string]: object } = {};\n\n static getListenId_(query: QueryContext, tag?: number | null): string {\n if (tag !== undefined) {\n return 'tag$' + tag;\n } else {\n assert(\n query._queryParams.isDefault(),\n \"should have a tag if it's not a default query.\"\n );\n return query._path.toString();\n }\n }\n\n /**\n * @param repoInfo_ - Data about the namespace we are connecting to\n * @param onDataUpdate_ - A callback for new data from the server\n */\n constructor(\n private repoInfo_: RepoInfo,\n private onDataUpdate_: (\n a: string,\n b: unknown,\n c: boolean,\n d: number | null\n ) => void,\n private authTokenProvider_: AuthTokenProvider,\n private appCheckTokenProvider_: AppCheckTokenProvider\n ) {\n super();\n }\n\n /** @inheritDoc */\n listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ) {\n const pathString = query._path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);\n\n // Mark this listener so we can tell if it's removed.\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\n const thisListen = {};\n this.listens_[listenId] = thisListen;\n\n const queryStringParameters = queryParamsToRestQueryStringParameters(\n query._queryParams\n );\n\n this.restRequest_(\n pathString + '.json',\n queryStringParameters,\n (error, result) => {\n let data = result;\n\n if (error === 404) {\n data = null;\n error = null;\n }\n\n if (error === null) {\n this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n }\n\n if (safeGet(this.listens_, listenId) === thisListen) {\n let status;\n if (!error) {\n status = 'ok';\n } else if (error === 401) {\n status = 'permission_denied';\n } else {\n status = 'rest_error:' + error;\n }\n\n onComplete(status, null);\n }\n }\n );\n }\n\n /** @inheritDoc */\n unlisten(query: QueryContext, tag: number | null) {\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n }\n\n get(query: QueryContext): Promise {\n const queryStringParameters = queryParamsToRestQueryStringParameters(\n query._queryParams\n );\n\n const pathString = query._path.toString();\n\n const deferred = new Deferred();\n\n this.restRequest_(\n pathString + '.json',\n queryStringParameters,\n (error, result) => {\n let data = result;\n\n if (error === 404) {\n data = null;\n error = null;\n }\n\n if (error === null) {\n this.onDataUpdate_(\n pathString,\n data,\n /*isMerge=*/ false,\n /*tag=*/ null\n );\n deferred.resolve(data as string);\n } else {\n deferred.reject(new Error(data as string));\n }\n }\n );\n return deferred.promise;\n }\n\n /** @inheritDoc */\n refreshAuthToken(token: string) {\n // no-op since we just always call getToken.\n }\n\n /**\n * Performs a REST request to the given path, with the provided query string parameters,\n * and any auth credentials we have.\n */\n private restRequest_(\n pathString: string,\n queryStringParameters: { [k: string]: string | number } = {},\n callback: ((a: number | null, b?: unknown) => void) | null\n ) {\n queryStringParameters['format'] = 'export';\n\n return Promise.all([\n this.authTokenProvider_.getToken(/*forceRefresh=*/ false),\n this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)\n ]).then(([authToken, appCheckToken]) => {\n if (authToken && authToken.accessToken) {\n queryStringParameters['auth'] = authToken.accessToken;\n }\n if (appCheckToken && appCheckToken.token) {\n queryStringParameters['ac'] = appCheckToken.token;\n }\n\n const url =\n (this.repoInfo_.secure ? 'https://' : 'http://') +\n this.repoInfo_.host +\n pathString +\n '?' +\n 'ns=' +\n this.repoInfo_.namespace +\n querystring(queryStringParameters);\n\n this.log_('Sending REST request for ' + url);\n const xhr = new XMLHttpRequest();\n xhr.onreadystatechange = () => {\n if (callback && xhr.readyState === 4) {\n this.log_(\n 'REST Response for ' + url + ' received. status:',\n xhr.status,\n 'response:',\n xhr.responseText\n );\n let res = null;\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = jsonEval(xhr.responseText);\n } catch (e) {\n warn(\n 'Failed to parse JSON response for ' +\n url +\n ': ' +\n xhr.responseText\n );\n }\n callback(null, res);\n } else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n warn(\n 'Got unsuccessful REST response for ' +\n url +\n ' Status: ' +\n xhr.status\n );\n }\n callback(xhr.status);\n }\n callback = null;\n }\n };\n\n xhr.open('GET', url, /*asynchronous=*/ true);\n xhr.send();\n });\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { Path } from './util/Path';\n\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n */\nexport class SnapshotHolder {\n private rootNode_: Node = ChildrenNode.EMPTY_NODE;\n\n getNode(path: Path): Node {\n return this.rootNode_.getChild(path);\n }\n\n updateSnapshot(path: Path, newSnapshotNode: Node) {\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { Node } from './snap/Node';\nimport { Path, pathGetFront, pathIsEmpty, pathPopFront } from './util/Path';\n\n/**\n * Helper class to store a sparse set of snapshots.\n */\nexport interface SparseSnapshotTree {\n value: Node | null;\n readonly children: Map;\n}\n\nexport function newSparseSnapshotTree(): SparseSnapshotTree {\n return {\n value: null,\n children: new Map()\n };\n}\n\n/**\n * Gets the node stored at the given path if one exists.\n * Only seems to be used in tests.\n *\n * @param path - Path to look up snapshot for.\n * @returns The retrieved node, or null.\n */\nexport function sparseSnapshotTreeFind(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path\n): Node | null {\n if (sparseSnapshotTree.value != null) {\n return sparseSnapshotTree.value.getChild(path);\n } else if (!pathIsEmpty(path) && sparseSnapshotTree.children.size > 0) {\n const childKey = pathGetFront(path);\n path = pathPopFront(path);\n if (sparseSnapshotTree.children.has(childKey)) {\n const childTree = sparseSnapshotTree.children.get(childKey);\n return sparseSnapshotTreeFind(childTree, path);\n } else {\n return null;\n }\n } else {\n return null;\n }\n}\n\n/**\n * Stores the given node at the specified path. If there is already a node\n * at a shallower path, it merges the new data into that snapshot node.\n *\n * @param path - Path to look up snapshot for.\n * @param data - The new data, or null.\n */\nexport function sparseSnapshotTreeRemember(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path,\n data: Node\n): void {\n if (pathIsEmpty(path)) {\n sparseSnapshotTree.value = data;\n sparseSnapshotTree.children.clear();\n } else if (sparseSnapshotTree.value !== null) {\n sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);\n } else {\n const childKey = pathGetFront(path);\n if (!sparseSnapshotTree.children.has(childKey)) {\n sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());\n }\n\n const child = sparseSnapshotTree.children.get(childKey);\n path = pathPopFront(path);\n sparseSnapshotTreeRemember(child, path, data);\n }\n}\n\n/**\n * Purge the data at path from the cache.\n *\n * @param path - Path to look up snapshot for.\n * @returns True if this node should now be removed.\n */\nexport function sparseSnapshotTreeForget(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path\n): boolean {\n if (pathIsEmpty(path)) {\n sparseSnapshotTree.value = null;\n sparseSnapshotTree.children.clear();\n return true;\n } else {\n if (sparseSnapshotTree.value !== null) {\n if (sparseSnapshotTree.value.isLeafNode()) {\n // We're trying to forget a node that doesn't exist\n return false;\n } else {\n const value = sparseSnapshotTree.value;\n sparseSnapshotTree.value = null;\n\n value.forEachChild(PRIORITY_INDEX, (key, tree) => {\n sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);\n });\n\n return sparseSnapshotTreeForget(sparseSnapshotTree, path);\n }\n } else if (sparseSnapshotTree.children.size > 0) {\n const childKey = pathGetFront(path);\n path = pathPopFront(path);\n if (sparseSnapshotTree.children.has(childKey)) {\n const safeToRemove = sparseSnapshotTreeForget(\n sparseSnapshotTree.children.get(childKey),\n path\n );\n if (safeToRemove) {\n sparseSnapshotTree.children.delete(childKey);\n }\n }\n\n return sparseSnapshotTree.children.size === 0;\n } else {\n return true;\n }\n }\n}\n\n/**\n * Recursively iterates through all of the stored tree and calls the\n * callback on each one.\n *\n * @param prefixPath - Path to look up node for.\n * @param func - The function to invoke for each tree.\n */\nexport function sparseSnapshotTreeForEachTree(\n sparseSnapshotTree: SparseSnapshotTree,\n prefixPath: Path,\n func: (a: Path, b: Node) => unknown\n): void {\n if (sparseSnapshotTree.value !== null) {\n func(prefixPath, sparseSnapshotTree.value);\n } else {\n sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {\n const path = new Path(prefixPath.toString() + '/' + key);\n sparseSnapshotTreeForEachTree(tree, path, func);\n });\n }\n}\n\n/**\n * Iterates through each immediate child and triggers the callback.\n * Only seems to be used in tests.\n *\n * @param func - The function to invoke for each child.\n */\nexport function sparseSnapshotTreeForEachChild(\n sparseSnapshotTree: SparseSnapshotTree,\n func: (a: string, b: SparseSnapshotTree) => void\n): void {\n sparseSnapshotTree.children.forEach((tree, key) => {\n func(key, tree);\n });\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { each } from '../util/util';\n\nimport { StatsCollection } from './StatsCollection';\n\n/**\n * Returns the delta from the previous call to get stats.\n *\n * @param collection_ - The collection to \"listen\" to.\n */\nexport class StatsListener {\n private last_: { [k: string]: number } | null = null;\n\n constructor(private collection_: StatsCollection) {}\n\n get(): { [k: string]: number } {\n const newStats = this.collection_.get();\n\n const delta = { ...newStats };\n if (this.last_) {\n each(this.last_, (stat: string, value: number) => {\n delta[stat] = delta[stat] - value;\n });\n }\n this.last_ = newStats;\n\n return delta;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains } from '@firebase/util';\n\nimport { ServerActions } from '../ServerActions';\nimport { setTimeoutNonBlocking, each } from '../util/util';\n\nimport { StatsCollection } from './StatsCollection';\nimport { StatsListener } from './StatsListener';\n\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\n// seconds to try to ensure the Firebase connection is established / settled.\nconst FIRST_STATS_MIN_TIME = 10 * 1000;\nconst FIRST_STATS_MAX_TIME = 30 * 1000;\n\n// We'll continue to report stats on average every 5 minutes.\nconst REPORT_STATS_INTERVAL = 5 * 60 * 1000;\n\nexport class StatsReporter {\n private statsListener_: StatsListener;\n statsToReport_: { [k: string]: boolean } = {};\n\n constructor(collection: StatsCollection, private server_: ServerActions) {\n this.statsListener_ = new StatsListener(collection);\n\n const timeout =\n FIRST_STATS_MIN_TIME +\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n }\n\n private reportStats_() {\n const stats = this.statsListener_.get();\n const reportedStats: typeof stats = {};\n let haveStatsToReport = false;\n\n each(stats, (stat: string, value: number) => {\n if (value > 0 && contains(this.statsToReport_, stat)) {\n reportedStats[stat] = value;\n haveStatsToReport = true;\n }\n });\n\n if (haveStatsToReport) {\n this.server_.reportStats(reportedStats);\n }\n\n // queue our next run.\n setTimeoutNonBlocking(\n this.reportStats_.bind(this),\n Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL)\n );\n }\n}\n\nexport function statsReporterIncludeStat(\n reporter: StatsReporter,\n stat: string\n) {\n reporter.statsToReport_[stat] = true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Path } from '../util/Path';\n\n/**\n *\n * @enum\n */\nexport enum OperationType {\n OVERWRITE,\n MERGE,\n ACK_USER_WRITE,\n LISTEN_COMPLETE\n}\n\n/**\n * @interface\n */\nexport interface Operation {\n source: OperationSource;\n\n type: OperationType;\n\n path: Path;\n\n operationForChild(childName: string): Operation | null;\n}\n\nexport interface OperationSource {\n fromUser: boolean;\n fromServer: boolean;\n queryId: string | null;\n tagged: boolean;\n}\n\nexport function newOperationSourceUser(): OperationSource {\n return {\n fromUser: true,\n fromServer: false,\n queryId: null,\n tagged: false\n };\n}\n\nexport function newOperationSourceServer(): OperationSource {\n return {\n fromUser: false,\n fromServer: true,\n queryId: null,\n tagged: false\n };\n}\n\nexport function newOperationSourceServerTaggedQuery(\n queryId: string\n): OperationSource {\n return {\n fromUser: false,\n fromServer: true,\n queryId,\n tagged: true\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\n\nimport { newOperationSourceUser, Operation, OperationType } from './Operation';\n\nexport class AckUserWrite implements Operation {\n /** @inheritDoc */\n type = OperationType.ACK_USER_WRITE;\n\n /** @inheritDoc */\n source = newOperationSourceUser();\n\n /**\n * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.\n */\n constructor(\n /** @inheritDoc */ public path: Path,\n /** @inheritDoc */ public affectedTree: ImmutableTree,\n /** @inheritDoc */ public revert: boolean\n ) {}\n operationForChild(childName: string): AckUserWrite {\n if (!pathIsEmpty(this.path)) {\n assert(\n pathGetFront(this.path) === childName,\n 'operationForChild called for unrelated child.'\n );\n return new AckUserWrite(\n pathPopFront(this.path),\n this.affectedTree,\n this.revert\n );\n } else if (this.affectedTree.value != null) {\n assert(\n this.affectedTree.children.isEmpty(),\n 'affectedTree should not have overlapping affected paths.'\n );\n // All child locations are affected as well; just return same operation.\n return this;\n } else {\n const childTree = this.affectedTree.subtree(new Path(childName));\n return new AckUserWrite(newEmptyPath(), childTree, this.revert);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { newEmptyPath, Path, pathIsEmpty, pathPopFront } from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './Operation';\n\nexport class ListenComplete implements Operation {\n /** @inheritDoc */\n type = OperationType.LISTEN_COMPLETE;\n\n constructor(public source: OperationSource, public path: Path) {}\n\n operationForChild(childName: string): ListenComplete {\n if (pathIsEmpty(this.path)) {\n return new ListenComplete(this.source, newEmptyPath());\n } else {\n return new ListenComplete(this.source, pathPopFront(this.path));\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\nimport { newEmptyPath, Path, pathIsEmpty, pathPopFront } from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './Operation';\n\nexport class Overwrite implements Operation {\n /** @inheritDoc */\n type = OperationType.OVERWRITE;\n\n constructor(\n public source: OperationSource,\n public path: Path,\n public snap: Node\n ) {}\n\n operationForChild(childName: string): Overwrite {\n if (pathIsEmpty(this.path)) {\n return new Overwrite(\n this.source,\n newEmptyPath(),\n this.snap.getImmediateChild(childName)\n );\n } else {\n return new Overwrite(this.source, pathPopFront(this.path), this.snap);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Node } from '../snap/Node';\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './Operation';\nimport { Overwrite } from './Overwrite';\n\nexport class Merge implements Operation {\n /** @inheritDoc */\n type = OperationType.MERGE;\n\n constructor(\n /** @inheritDoc */ public source: OperationSource,\n /** @inheritDoc */ public path: Path,\n /** @inheritDoc */ public children: ImmutableTree\n ) {}\n operationForChild(childName: string): Operation {\n if (pathIsEmpty(this.path)) {\n const childTree = this.children.subtree(new Path(childName));\n if (childTree.isEmpty()) {\n // This child is unaffected\n return null;\n } else if (childTree.value) {\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\n return new Overwrite(this.source, newEmptyPath(), childTree.value);\n } else {\n // This is a merge at a deeper level\n return new Merge(this.source, newEmptyPath(), childTree);\n }\n } else {\n assert(\n pathGetFront(this.path) === childName,\n \"Can't get a merge for a child not on the path of the operation\"\n );\n return new Merge(this.source, pathPopFront(this.path), this.children);\n }\n }\n toString(): string {\n return (\n 'Operation(' +\n this.path +\n ': ' +\n this.source.toString() +\n ' merge: ' +\n this.children.toString() +\n ')'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\nimport { Path, pathGetFront, pathIsEmpty } from '../util/Path';\n\n/**\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\n * whether a node potentially had children removed due to a filter.\n */\nexport class CacheNode {\n constructor(\n private node_: Node,\n private fullyInitialized_: boolean,\n private filtered_: boolean\n ) {}\n\n /**\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\n */\n isFullyInitialized(): boolean {\n return this.fullyInitialized_;\n }\n\n /**\n * Returns whether this node is potentially missing children due to a filter applied to the node\n */\n isFiltered(): boolean {\n return this.filtered_;\n }\n\n isCompleteForPath(path: Path): boolean {\n if (pathIsEmpty(path)) {\n return this.isFullyInitialized() && !this.filtered_;\n }\n\n const childKey = pathGetFront(path);\n return this.isCompleteForChild(childKey);\n }\n\n isCompleteForChild(key: string): boolean {\n return (\n (this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key)\n );\n }\n\n getNode(): Node {\n return this.node_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assertionError } from '@firebase/util';\n\nimport { Index } from '../snap/indexes/Index';\nimport { NamedNode, Node } from '../snap/Node';\n\nimport { Change, ChangeType, changeChildMoved } from './Change';\nimport { Event } from './Event';\nimport { EventRegistration, QueryContext } from './EventRegistration';\n\n/**\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\n * for details.\n *\n */\nexport class EventGenerator {\n index_: Index;\n\n constructor(public query_: QueryContext) {\n this.index_ = this.query_._queryParams.getIndex();\n }\n}\n\n/**\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\n *\n * Notes:\n * - child_moved events will be synthesized at this time for any child_changed events that affect\n * our index.\n * - prevName will be calculated based on the index ordering.\n */\nexport function eventGeneratorGenerateEventsForChanges(\n eventGenerator: EventGenerator,\n changes: Change[],\n eventCache: Node,\n eventRegistrations: EventRegistration[]\n): Event[] {\n const events: Event[] = [];\n const moves: Change[] = [];\n\n changes.forEach(change => {\n if (\n change.type === ChangeType.CHILD_CHANGED &&\n eventGenerator.index_.indexedValueChanged(\n change.oldSnap as Node,\n change.snapshotNode\n )\n ) {\n moves.push(changeChildMoved(change.childName, change.snapshotNode));\n }\n });\n\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_REMOVED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_ADDED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_MOVED,\n moves,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_CHANGED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.VALUE,\n changes,\n eventRegistrations,\n eventCache\n );\n\n return events;\n}\n\n/**\n * Given changes of a single change type, generate the corresponding events.\n */\nfunction eventGeneratorGenerateEventsForType(\n eventGenerator: EventGenerator,\n events: Event[],\n eventType: string,\n changes: Change[],\n registrations: EventRegistration[],\n eventCache: Node\n) {\n const filteredChanges = changes.filter(change => change.type === eventType);\n\n filteredChanges.sort((a, b) =>\n eventGeneratorCompareChanges(eventGenerator, a, b)\n );\n filteredChanges.forEach(change => {\n const materializedChange = eventGeneratorMaterializeSingleChange(\n eventGenerator,\n change,\n eventCache\n );\n registrations.forEach(registration => {\n if (registration.respondsTo(change.type)) {\n events.push(\n registration.createEvent(materializedChange, eventGenerator.query_)\n );\n }\n });\n });\n}\n\nfunction eventGeneratorMaterializeSingleChange(\n eventGenerator: EventGenerator,\n change: Change,\n eventCache: Node\n): Change {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n } else {\n change.prevName = eventCache.getPredecessorChildName(\n change.childName,\n change.snapshotNode,\n eventGenerator.index_\n );\n return change;\n }\n}\n\nfunction eventGeneratorCompareChanges(\n eventGenerator: EventGenerator,\n a: Change,\n b: Change\n) {\n if (a.childName == null || b.childName == null) {\n throw assertionError('Should only compare child_ events.');\n }\n const aWrapped = new NamedNode(a.childName, a.snapshotNode);\n const bWrapped = new NamedNode(b.childName, b.snapshotNode);\n return eventGenerator.index_.compare(aWrapped, bWrapped);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\n\nimport { CacheNode } from './CacheNode';\n\n/**\n * Stores the data we have cached for a view.\n *\n * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes).\n */\nexport interface ViewCache {\n readonly eventCache: CacheNode;\n readonly serverCache: CacheNode;\n}\n\nexport function newViewCache(\n eventCache: CacheNode,\n serverCache: CacheNode\n): ViewCache {\n return { eventCache, serverCache };\n}\n\nexport function viewCacheUpdateEventSnap(\n viewCache: ViewCache,\n eventSnap: Node,\n complete: boolean,\n filtered: boolean\n): ViewCache {\n return newViewCache(\n new CacheNode(eventSnap, complete, filtered),\n viewCache.serverCache\n );\n}\n\nexport function viewCacheUpdateServerSnap(\n viewCache: ViewCache,\n serverSnap: Node,\n complete: boolean,\n filtered: boolean\n): ViewCache {\n return newViewCache(\n viewCache.eventCache,\n new CacheNode(serverSnap, complete, filtered)\n );\n}\n\nexport function viewCacheGetCompleteEventSnap(\n viewCache: ViewCache\n): Node | null {\n return viewCache.eventCache.isFullyInitialized()\n ? viewCache.eventCache.getNode()\n : null;\n}\n\nexport function viewCacheGetCompleteServerSnap(\n viewCache: ViewCache\n): Node | null {\n return viewCache.serverCache.isFullyInitialized()\n ? viewCache.serverCache.getNode()\n : null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n newEmptyPath,\n Path,\n pathChild,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from './Path';\nimport { SortedMap } from './SortedMap';\nimport { each, stringCompare } from './util';\n\nlet emptyChildrenSingleton: SortedMap>;\n\n/**\n * Singleton empty children collection.\n *\n */\nconst EmptyChildren = (): SortedMap> => {\n if (!emptyChildrenSingleton) {\n emptyChildrenSingleton = new SortedMap>(\n stringCompare\n );\n }\n return emptyChildrenSingleton;\n};\n\n/**\n * A tree with immutable elements.\n */\nexport class ImmutableTree {\n static fromObject(obj: { [k: string]: T }): ImmutableTree {\n let tree: ImmutableTree = new ImmutableTree(null);\n each(obj, (childPath: string, childSnap: T) => {\n tree = tree.set(new Path(childPath), childSnap);\n });\n return tree;\n }\n\n constructor(\n public readonly value: T | null,\n public readonly children: SortedMap<\n string,\n ImmutableTree\n > = EmptyChildren()\n ) {}\n\n /**\n * True if the value is empty and there are no children\n */\n isEmpty(): boolean {\n return this.value === null && this.children.isEmpty();\n }\n\n /**\n * Given a path and predicate, return the first node and the path to that node\n * where the predicate returns true.\n *\n * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`\n * objects on the way back out, it may be better to pass down a pathSoFar obj.\n *\n * @param relativePath - The remainder of the path\n * @param predicate - The predicate to satisfy to return a node\n */\n findRootMostMatchingPathAndValue(\n relativePath: Path,\n predicate: (a: T) => boolean\n ): { path: Path; value: T } | null {\n if (this.value != null && predicate(this.value)) {\n return { path: newEmptyPath(), value: this.value };\n } else {\n if (pathIsEmpty(relativePath)) {\n return null;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child !== null) {\n const childExistingPathAndValue =\n child.findRootMostMatchingPathAndValue(\n pathPopFront(relativePath),\n predicate\n );\n if (childExistingPathAndValue != null) {\n const fullPath = pathChild(\n new Path(front),\n childExistingPathAndValue.path\n );\n return { path: fullPath, value: childExistingPathAndValue.value };\n } else {\n return null;\n }\n } else {\n return null;\n }\n }\n }\n }\n\n /**\n * Find, if it exists, the shortest subpath of the given path that points a defined\n * value in the tree\n */\n findRootMostValueAndPath(\n relativePath: Path\n ): { path: Path; value: T } | null {\n return this.findRootMostMatchingPathAndValue(relativePath, () => true);\n }\n\n /**\n * @returns The subtree at the given path\n */\n subtree(relativePath: Path): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n return this;\n } else {\n const front = pathGetFront(relativePath);\n const childTree = this.children.get(front);\n if (childTree !== null) {\n return childTree.subtree(pathPopFront(relativePath));\n } else {\n return new ImmutableTree(null);\n }\n }\n }\n\n /**\n * Sets a value at the specified path.\n *\n * @param relativePath - Path to set value at.\n * @param toSet - Value to set.\n * @returns Resulting tree.\n */\n set(relativePath: Path, toSet: T | null): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n return new ImmutableTree(toSet, this.children);\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front) || new ImmutableTree(null);\n const newChild = child.set(pathPopFront(relativePath), toSet);\n const newChildren = this.children.insert(front, newChild);\n return new ImmutableTree(this.value, newChildren);\n }\n }\n\n /**\n * Removes the value at the specified path.\n *\n * @param relativePath - Path to value to remove.\n * @returns Resulting tree.\n */\n remove(relativePath: Path): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n if (this.children.isEmpty()) {\n return new ImmutableTree(null);\n } else {\n return new ImmutableTree(null, this.children);\n }\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child) {\n const newChild = child.remove(pathPopFront(relativePath));\n let newChildren;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n } else {\n newChildren = this.children.insert(front, newChild);\n }\n if (this.value === null && newChildren.isEmpty()) {\n return new ImmutableTree(null);\n } else {\n return new ImmutableTree(this.value, newChildren);\n }\n } else {\n return this;\n }\n }\n }\n\n /**\n * Gets a value from the tree.\n *\n * @param relativePath - Path to get value for.\n * @returns Value at path, or null.\n */\n get(relativePath: Path): T | null {\n if (pathIsEmpty(relativePath)) {\n return this.value;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child) {\n return child.get(pathPopFront(relativePath));\n } else {\n return null;\n }\n }\n }\n\n /**\n * Replace the subtree at the specified path with the given new tree.\n *\n * @param relativePath - Path to replace subtree for.\n * @param newTree - New tree.\n * @returns Resulting tree.\n */\n setTree(relativePath: Path, newTree: ImmutableTree): ImmutableTree {\n if (pathIsEmpty(relativePath)) {\n return newTree;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front) || new ImmutableTree(null);\n const newChild = child.setTree(pathPopFront(relativePath), newTree);\n let newChildren;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n } else {\n newChildren = this.children.insert(front, newChild);\n }\n return new ImmutableTree(this.value, newChildren);\n }\n }\n\n /**\n * Performs a depth first fold on this tree. Transforms a tree into a single\n * value, given a function that operates on the path to a node, an optional\n * current value, and a map of child names to folded subtrees\n */\n fold(fn: (path: Path, value: T, children: { [k: string]: V }) => V): V {\n return this.fold_(newEmptyPath(), fn);\n }\n\n /**\n * Recursive helper for public-facing fold() method\n */\n private fold_(\n pathSoFar: Path,\n fn: (path: Path, value: T | null, children: { [k: string]: V }) => V\n ): V {\n const accum: { [k: string]: V } = {};\n this.children.inorderTraversal(\n (childKey: string, childTree: ImmutableTree) => {\n accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);\n }\n );\n return fn(pathSoFar, this.value, accum);\n }\n\n /**\n * Find the first matching value on the given path. Return the result of applying f to it.\n */\n findOnPath(path: Path, f: (path: Path, value: T) => V | null): V | null {\n return this.findOnPath_(path, newEmptyPath(), f);\n }\n\n private findOnPath_(\n pathToFollow: Path,\n pathSoFar: Path,\n f: (path: Path, value: T) => V | null\n ): V | null {\n const result = this.value ? f(pathSoFar, this.value) : false;\n if (result) {\n return result;\n } else {\n if (pathIsEmpty(pathToFollow)) {\n return null;\n } else {\n const front = pathGetFront(pathToFollow)!;\n const nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.findOnPath_(\n pathPopFront(pathToFollow),\n pathChild(pathSoFar, front),\n f\n );\n } else {\n return null;\n }\n }\n }\n }\n\n foreachOnPath(\n path: Path,\n f: (path: Path, value: T) => void\n ): ImmutableTree {\n return this.foreachOnPath_(path, newEmptyPath(), f);\n }\n\n private foreachOnPath_(\n pathToFollow: Path,\n currentRelativePath: Path,\n f: (path: Path, value: T) => void\n ): ImmutableTree {\n if (pathIsEmpty(pathToFollow)) {\n return this;\n } else {\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n const front = pathGetFront(pathToFollow);\n const nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.foreachOnPath_(\n pathPopFront(pathToFollow),\n pathChild(currentRelativePath, front),\n f\n );\n } else {\n return new ImmutableTree(null);\n }\n }\n }\n\n /**\n * Calls the given function for each node in the tree that has a value.\n *\n * @param f - A function to be called with the path from the root of the tree to\n * a node, and the value at that node. Called in depth-first order.\n */\n foreach(f: (path: Path, value: T) => void) {\n this.foreach_(newEmptyPath(), f);\n }\n\n private foreach_(\n currentRelativePath: Path,\n f: (path: Path, value: T) => void\n ) {\n this.children.inorderTraversal((childName, childTree) => {\n childTree.foreach_(pathChild(currentRelativePath, childName), f);\n });\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n }\n\n foreachChild(f: (name: string, value: T) => void) {\n this.children.inorderTraversal(\n (childName: string, childTree: ImmutableTree) => {\n if (childTree.value) {\n f(childName, childTree.value);\n }\n }\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { NamedNode, Node } from './snap/Node';\nimport { ImmutableTree } from './util/ImmutableTree';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathIsEmpty\n} from './util/Path';\nimport { each } from './util/util';\n\n/**\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\n * to reflect the write added.\n */\nexport class CompoundWrite {\n constructor(public writeTree_: ImmutableTree) {}\n\n static empty(): CompoundWrite {\n return new CompoundWrite(new ImmutableTree(null));\n }\n}\n\nexport function compoundWriteAddWrite(\n compoundWrite: CompoundWrite,\n path: Path,\n node: Node\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return new CompoundWrite(new ImmutableTree(node));\n } else {\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n const rootMostPath = rootmost.path;\n let value = rootmost.value;\n const relativePath = newRelativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(\n compoundWrite.writeTree_.set(rootMostPath, value)\n );\n } else {\n const subtree = new ImmutableTree(node);\n const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n}\n\nexport function compoundWriteAddWrites(\n compoundWrite: CompoundWrite,\n path: Path,\n updates: { [name: string]: Node }\n): CompoundWrite {\n let newWrite = compoundWrite;\n each(updates, (childKey: string, node: Node) => {\n newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);\n });\n return newWrite;\n}\n\n/**\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param compoundWrite - The CompoundWrite to remove.\n * @param path - The path at which a write and all deeper writes should be removed\n * @returns The new CompoundWrite with the removed path\n */\nexport function compoundWriteRemoveWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return CompoundWrite.empty();\n } else {\n const newWriteTree = compoundWrite.writeTree_.setTree(\n path,\n new ImmutableTree(null)\n );\n return new CompoundWrite(newWriteTree);\n }\n}\n\n/**\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\n * considered \"complete\".\n *\n * @param compoundWrite - The CompoundWrite to check.\n * @param path - The path to check for\n * @returns Whether there is a complete write at that path\n */\nexport function compoundWriteHasCompleteWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): boolean {\n return compoundWriteGetCompleteNode(compoundWrite, path) != null;\n}\n\n/**\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\n * writes from deeper paths, but will return child nodes from a more shallow path.\n *\n * @param compoundWrite - The CompoundWrite to get the node from.\n * @param path - The path to get a complete write\n * @returns The node if complete at that path, or null otherwise.\n */\nexport function compoundWriteGetCompleteNode(\n compoundWrite: CompoundWrite,\n path: Path\n): Node | null {\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return compoundWrite.writeTree_\n .get(rootmost.path)\n .getChild(newRelativePath(rootmost.path, path));\n } else {\n return null;\n }\n}\n\n/**\n * Returns all children that are guaranteed to be a complete overwrite.\n *\n * @param compoundWrite - The CompoundWrite to get children from.\n * @returns A list of all complete children.\n */\nexport function compoundWriteGetCompleteChildren(\n compoundWrite: CompoundWrite\n): NamedNode[] {\n const children: NamedNode[] = [];\n const node = compoundWrite.writeTree_.value;\n if (node != null) {\n // If it's a leaf node, it has no children; so nothing to do.\n if (!node.isLeafNode()) {\n (node as ChildrenNode).forEachChild(\n PRIORITY_INDEX,\n (childName, childNode) => {\n children.push(new NamedNode(childName, childNode));\n }\n );\n }\n } else {\n compoundWrite.writeTree_.children.inorderTraversal(\n (childName, childTree) => {\n if (childTree.value != null) {\n children.push(new NamedNode(childName, childTree.value));\n }\n }\n );\n }\n return children;\n}\n\nexport function compoundWriteChildCompoundWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return compoundWrite;\n } else {\n const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree(shadowingNode));\n } else {\n return new CompoundWrite(compoundWrite.writeTree_.subtree(path));\n }\n }\n}\n\n/**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @returns Whether this CompoundWrite is empty\n */\nexport function compoundWriteIsEmpty(compoundWrite: CompoundWrite): boolean {\n return compoundWrite.writeTree_.isEmpty();\n}\n\n/**\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\n * node\n * @param node - The node to apply this CompoundWrite to\n * @returns The node with all writes applied\n */\nexport function compoundWriteApply(\n compoundWrite: CompoundWrite,\n node: Node\n): Node {\n return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);\n}\n\nfunction applySubtreeWrite(\n relativePath: Path,\n writeTree: ImmutableTree,\n node: Node\n): Node {\n if (writeTree.value != null) {\n // Since there a write is always a leaf, we're done here\n return node.updateChild(relativePath, writeTree.value);\n } else {\n let priorityWrite = null;\n writeTree.children.inorderTraversal((childKey, childTree) => {\n if (childKey === '.priority') {\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\n // to apply priorities to empty nodes that are later filled\n assert(\n childTree.value !== null,\n 'Priority writes must always be leaf nodes'\n );\n priorityWrite = childTree.value;\n } else {\n node = applySubtreeWrite(\n pathChild(relativePath, childKey),\n childTree,\n node\n );\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {\n node = node.updateChild(\n pathChild(relativePath, '.priority'),\n priorityWrite\n );\n }\n return node;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError, safeGet } from '@firebase/util';\n\nimport {\n CompoundWrite,\n compoundWriteAddWrite,\n compoundWriteAddWrites,\n compoundWriteApply,\n compoundWriteChildCompoundWrite,\n compoundWriteGetCompleteChildren,\n compoundWriteGetCompleteNode,\n compoundWriteHasCompleteWrite,\n compoundWriteIsEmpty,\n compoundWriteRemoveWrite\n} from './CompoundWrite';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Index } from './snap/indexes/Index';\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { NamedNode, Node } from './snap/Node';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathContains,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from './util/Path';\nimport { each } from './util/util';\nimport { CacheNode } from './view/CacheNode';\n\n/**\n * Defines a single user-initiated write operation. May be the result of a set(), transaction(), or update() call. In\n * the case of a set() or transaction, snap will be non-null. In the case of an update(), children will be non-null.\n */\nexport interface WriteRecord {\n writeId: number;\n path: Path;\n snap?: Node | null;\n children?: { [k: string]: Node } | null;\n visible: boolean;\n}\n\n/**\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n */\nexport function writeTreeChildWrites(\n writeTree: WriteTree,\n path: Path\n): WriteTreeRef {\n return newWriteTreeRef(path, writeTree);\n}\n\n/**\n * Record a new overwrite from user code.\n *\n * @param visible - This is set to false by some transactions. It should be excluded from event caches\n */\nexport function writeTreeAddOverwrite(\n writeTree: WriteTree,\n path: Path,\n snap: Node,\n writeId: number,\n visible?: boolean\n) {\n assert(\n writeId > writeTree.lastWriteId,\n 'Stacking an older write on top of newer ones'\n );\n if (visible === undefined) {\n visible = true;\n }\n writeTree.allWrites.push({\n path,\n snap,\n writeId,\n visible\n });\n\n if (visible) {\n writeTree.visibleWrites = compoundWriteAddWrite(\n writeTree.visibleWrites,\n path,\n snap\n );\n }\n writeTree.lastWriteId = writeId;\n}\n\n/**\n * Record a new merge from user code.\n */\nexport function writeTreeAddMerge(\n writeTree: WriteTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n writeId: number\n) {\n assert(\n writeId > writeTree.lastWriteId,\n 'Stacking an older merge on top of newer ones'\n );\n writeTree.allWrites.push({\n path,\n children: changedChildren,\n writeId,\n visible: true\n });\n\n writeTree.visibleWrites = compoundWriteAddWrites(\n writeTree.visibleWrites,\n path,\n changedChildren\n );\n writeTree.lastWriteId = writeId;\n}\n\nexport function writeTreeGetWrite(\n writeTree: WriteTree,\n writeId: number\n): WriteRecord | null {\n for (let i = 0; i < writeTree.allWrites.length; i++) {\n const record = writeTree.allWrites[i];\n if (record.writeId === writeId) {\n return record;\n }\n }\n return null;\n}\n\n/**\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\n *\n * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\nexport function writeTreeRemoveWrite(\n writeTree: WriteTree,\n writeId: number\n): boolean {\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\n // out of order.\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\n\n const idx = writeTree.allWrites.findIndex(s => {\n return s.writeId === writeId;\n });\n assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n const writeToRemove = writeTree.allWrites[idx];\n writeTree.allWrites.splice(idx, 1);\n\n let removedWriteWasVisible = writeToRemove.visible;\n let removedWriteOverlapsWithOtherWrites = false;\n\n let i = writeTree.allWrites.length - 1;\n\n while (removedWriteWasVisible && i >= 0) {\n const currentWrite = writeTree.allWrites[i];\n if (currentWrite.visible) {\n if (\n i >= idx &&\n writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)\n ) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\n } else if (pathContains(writeToRemove.path, currentWrite.path)) {\n // Either we're covering some writes or they're covering part of us (depending on which came first).\n removedWriteOverlapsWithOtherWrites = true;\n }\n }\n i--;\n }\n\n if (!removedWriteWasVisible) {\n return false;\n } else if (removedWriteOverlapsWithOtherWrites) {\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\n writeTreeResetTree_(writeTree);\n return true;\n } else {\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\n if (writeToRemove.snap) {\n writeTree.visibleWrites = compoundWriteRemoveWrite(\n writeTree.visibleWrites,\n writeToRemove.path\n );\n } else {\n const children = writeToRemove.children;\n each(children, (childName: string) => {\n writeTree.visibleWrites = compoundWriteRemoveWrite(\n writeTree.visibleWrites,\n pathChild(writeToRemove.path, childName)\n );\n });\n }\n return true;\n }\n}\n\nfunction writeTreeRecordContainsPath_(\n writeRecord: WriteRecord,\n path: Path\n): boolean {\n if (writeRecord.snap) {\n return pathContains(writeRecord.path, path);\n } else {\n for (const childName in writeRecord.children) {\n if (\n writeRecord.children.hasOwnProperty(childName) &&\n pathContains(pathChild(writeRecord.path, childName), path)\n ) {\n return true;\n }\n }\n return false;\n }\n}\n\n/**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\n */\nfunction writeTreeResetTree_(writeTree: WriteTree) {\n writeTree.visibleWrites = writeTreeLayerTree_(\n writeTree.allWrites,\n writeTreeDefaultFilter_,\n newEmptyPath()\n );\n if (writeTree.allWrites.length > 0) {\n writeTree.lastWriteId =\n writeTree.allWrites[writeTree.allWrites.length - 1].writeId;\n } else {\n writeTree.lastWriteId = -1;\n }\n}\n\n/**\n * The default filter used when constructing the tree. Keep everything that's visible.\n */\nfunction writeTreeDefaultFilter_(write: WriteRecord) {\n return write.visible;\n}\n\n/**\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\n * event data at that path.\n */\nfunction writeTreeLayerTree_(\n writes: WriteRecord[],\n filter: (w: WriteRecord) => boolean,\n treeRoot: Path\n): CompoundWrite {\n let compoundWrite = CompoundWrite.empty();\n for (let i = 0; i < writes.length; ++i) {\n const write = writes[i];\n // Theory, a later set will either:\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\n if (filter(write)) {\n const writePath = write.path;\n let relativePath: Path;\n if (write.snap) {\n if (pathContains(treeRoot, writePath)) {\n relativePath = newRelativePath(treeRoot, writePath);\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n relativePath,\n write.snap\n );\n } else if (pathContains(writePath, treeRoot)) {\n relativePath = newRelativePath(writePath, treeRoot);\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n newEmptyPath(),\n write.snap.getChild(relativePath)\n );\n } else {\n // There is no overlap between root path and write path, ignore write\n }\n } else if (write.children) {\n if (pathContains(treeRoot, writePath)) {\n relativePath = newRelativePath(treeRoot, writePath);\n compoundWrite = compoundWriteAddWrites(\n compoundWrite,\n relativePath,\n write.children\n );\n } else if (pathContains(writePath, treeRoot)) {\n relativePath = newRelativePath(writePath, treeRoot);\n if (pathIsEmpty(relativePath)) {\n compoundWrite = compoundWriteAddWrites(\n compoundWrite,\n newEmptyPath(),\n write.children\n );\n } else {\n const child = safeGet(write.children, pathGetFront(relativePath));\n if (child) {\n // There exists a child in this node that matches the root path\n const deepNode = child.getChild(pathPopFront(relativePath));\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n newEmptyPath(),\n deepNode\n );\n }\n }\n } else {\n // There is no overlap between root path and write path, ignore write\n }\n } else {\n throw assertionError('WriteRecord should have .snap or .children');\n }\n }\n }\n return compoundWrite;\n}\n\n/**\n * Return a complete snapshot for the given path if there's visible write data at that path, else null.\n * No server data is considered.\n *\n */\nexport function writeTreeGetCompleteWriteData(\n writeTree: WriteTree,\n path: Path\n): Node | null {\n return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\n}\n\n/**\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\n * writes), attempt to calculate a complete snapshot for the given path\n *\n * @param writeIdsToExclude - An optional set to be excluded\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\n */\nexport function writeTreeCalcCompleteEventCache(\n writeTree: WriteTree,\n treePath: Path,\n completeServerCache: Node | null,\n writeIdsToExclude?: number[],\n includeHiddenWrites?: boolean\n): Node | null {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n const shadowingNode = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n treePath\n );\n if (shadowingNode != null) {\n return shadowingNode;\n } else {\n const subMerge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n if (compoundWriteIsEmpty(subMerge)) {\n return completeServerCache;\n } else if (\n completeServerCache == null &&\n !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())\n ) {\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n return null;\n } else {\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\n return compoundWriteApply(subMerge, layeredCache);\n }\n }\n } else {\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {\n return completeServerCache;\n } else {\n // If the server cache is null, and we don't have a complete cache, we need to return null\n if (\n !includeHiddenWrites &&\n completeServerCache == null &&\n !compoundWriteHasCompleteWrite(merge, newEmptyPath())\n ) {\n return null;\n } else {\n const filter = function (write: WriteRecord) {\n return (\n (write.visible || includeHiddenWrites) &&\n (!writeIdsToExclude ||\n !~writeIdsToExclude.indexOf(write.writeId)) &&\n (pathContains(write.path, treePath) ||\n pathContains(treePath, write.path))\n );\n };\n const mergeAtPath = writeTreeLayerTree_(\n writeTree.allWrites,\n filter,\n treePath\n );\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\n return compoundWriteApply(mergeAtPath, layeredCache);\n }\n }\n }\n}\n\n/**\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\n * Used when creating new views, to pre-fill their complete event children snapshot.\n */\nexport function writeTreeCalcCompleteEventChildren(\n writeTree: WriteTree,\n treePath: Path,\n completeServerChildren: ChildrenNode | null\n) {\n let completeChildren = ChildrenNode.EMPTY_NODE as Node;\n const topLevelSet = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n treePath\n );\n if (topLevelSet) {\n if (!topLevelSet.isLeafNode()) {\n // we're shadowing everything. Return the children.\n topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {\n completeChildren = completeChildren.updateImmediateChild(\n childName,\n childSnap\n );\n });\n }\n return completeChildren;\n } else if (completeServerChildren) {\n // Layer any children we have on top of this\n // We know we don't have a top-level set, so just enumerate existing children\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n completeServerChildren.forEachChild(\n PRIORITY_INDEX,\n (childName, childNode) => {\n const node = compoundWriteApply(\n compoundWriteChildCompoundWrite(merge, new Path(childName)),\n childNode\n );\n completeChildren = completeChildren.updateImmediateChild(\n childName,\n node\n );\n }\n );\n // Add any complete children we have from the set\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\n completeChildren = completeChildren.updateImmediateChild(\n namedNode.name,\n namedNode.node\n );\n });\n return completeChildren;\n } else {\n // We don't have anything to layer on top of. Layer on any children we have\n // Note that we can return an empty snap if we have a defined delete\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\n completeChildren = completeChildren.updateImmediateChild(\n namedNode.name,\n namedNode.node\n );\n });\n return completeChildren;\n }\n}\n\n/**\n * Given that the underlying server data has updated, determine what, if anything, needs to be\n * applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events\n *\n * Either existingEventSnap or existingServerSnap must exist\n */\nexport function writeTreeCalcEventCacheAfterServerOverwrite(\n writeTree: WriteTree,\n treePath: Path,\n childPath: Path,\n existingEventSnap: Node | null,\n existingServerSnap: Node | null\n): Node | null {\n assert(\n existingEventSnap || existingServerSnap,\n 'Either existingEventSnap or existingServerSnap must exist'\n );\n const path = pathChild(treePath, childPath);\n if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {\n // At this point we can probably guarantee that we're in case 2, meaning no events\n // May need to check visibility while doing the findRootMostValueAndPath call\n return null;\n } else {\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\n const childMerge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n path\n );\n if (compoundWriteIsEmpty(childMerge)) {\n // We're not shadowing at all. Case 1\n return existingServerSnap.getChild(childPath);\n } else {\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\n // However this is tricky to find out, since user updates don't necessary change the server\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\n // only check if the updates change the serverNode.\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\n return compoundWriteApply(\n childMerge,\n existingServerSnap.getChild(childPath)\n );\n }\n }\n}\n\n/**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n */\nexport function writeTreeCalcCompleteChild(\n writeTree: WriteTree,\n treePath: Path,\n childKey: string,\n existingServerSnap: CacheNode\n): Node | null {\n const path = pathChild(treePath, childKey);\n const shadowingNode = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n path\n );\n if (shadowingNode != null) {\n return shadowingNode;\n } else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n const childMerge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n path\n );\n return compoundWriteApply(\n childMerge,\n existingServerSnap.getNode().getImmediateChild(childKey)\n );\n } else {\n return null;\n }\n }\n}\n\n/**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n */\nexport function writeTreeShadowingWrite(\n writeTree: WriteTree,\n path: Path\n): Node | null {\n return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\n}\n\n/**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window.\n */\nexport function writeTreeCalcIndexedSlice(\n writeTree: WriteTree,\n treePath: Path,\n completeServerData: Node | null,\n startPost: NamedNode,\n count: number,\n reverse: boolean,\n index: Index\n): NamedNode[] {\n let toIterate: Node;\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n } else if (completeServerData != null) {\n toIterate = compoundWriteApply(merge, completeServerData);\n } else {\n // no children to iterate on\n return [];\n }\n toIterate = toIterate.withIndex(index);\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n const nodes = [];\n const cmp = index.getCompare();\n const iter = reverse\n ? (toIterate as ChildrenNode).getReverseIteratorFrom(startPost, index)\n : (toIterate as ChildrenNode).getIteratorFrom(startPost, index);\n let next = iter.getNext();\n while (next && nodes.length < count) {\n if (cmp(next, startPost) !== 0) {\n nodes.push(next);\n }\n next = iter.getNext();\n }\n return nodes;\n } else {\n return [];\n }\n}\n\nexport function newWriteTree(): WriteTree {\n return {\n visibleWrites: CompoundWrite.empty(),\n allWrites: [],\n lastWriteId: -1\n };\n}\n\n/**\n * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them\n * with underlying server data (to create \"event cache\" data). Pending writes are added with addOverwrite()\n * and addMerge(), and removed with removeWrite().\n */\nexport interface WriteTree {\n /**\n * A tree tracking the result of applying all visible writes. This does not include transactions with\n * applyLocally=false or writes that are completely shadowed by other writes.\n */\n visibleWrites: CompoundWrite;\n\n /**\n * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary\n * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also\n * used by transactions).\n */\n allWrites: WriteRecord[];\n\n lastWriteId: number;\n}\n\n/**\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\n * can lead to a more expensive calculation.\n *\n * @param writeIdsToExclude - Optional writes to exclude.\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\n */\nexport function writeTreeRefCalcCompleteEventCache(\n writeTreeRef: WriteTreeRef,\n completeServerCache: Node | null,\n writeIdsToExclude?: number[],\n includeHiddenWrites?: boolean\n): Node | null {\n return writeTreeCalcCompleteEventCache(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n completeServerCache,\n writeIdsToExclude,\n includeHiddenWrites\n );\n}\n\n/**\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\n * mix of the given server data and write data.\n *\n */\nexport function writeTreeRefCalcCompleteEventChildren(\n writeTreeRef: WriteTreeRef,\n completeServerChildren: ChildrenNode | null\n): ChildrenNode {\n return writeTreeCalcCompleteEventChildren(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n completeServerChildren\n ) as ChildrenNode;\n}\n\n/**\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\n * if anything, needs to be applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events should be raised\n *\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\n *\n *\n */\nexport function writeTreeRefCalcEventCacheAfterServerOverwrite(\n writeTreeRef: WriteTreeRef,\n path: Path,\n existingEventSnap: Node | null,\n existingServerSnap: Node | null\n): Node | null {\n return writeTreeCalcEventCacheAfterServerOverwrite(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n path,\n existingEventSnap,\n existingServerSnap\n );\n}\n\n/**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n */\nexport function writeTreeRefShadowingWrite(\n writeTreeRef: WriteTreeRef,\n path: Path\n): Node | null {\n return writeTreeShadowingWrite(\n writeTreeRef.writeTree,\n pathChild(writeTreeRef.treePath, path)\n );\n}\n\n/**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window\n */\nexport function writeTreeRefCalcIndexedSlice(\n writeTreeRef: WriteTreeRef,\n completeServerData: Node | null,\n startPost: NamedNode,\n count: number,\n reverse: boolean,\n index: Index\n): NamedNode[] {\n return writeTreeCalcIndexedSlice(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n completeServerData,\n startPost,\n count,\n reverse,\n index\n );\n}\n\n/**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n */\nexport function writeTreeRefCalcCompleteChild(\n writeTreeRef: WriteTreeRef,\n childKey: string,\n existingServerCache: CacheNode\n): Node | null {\n return writeTreeCalcCompleteChild(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n childKey,\n existingServerCache\n );\n}\n\n/**\n * Return a WriteTreeRef for a child.\n */\nexport function writeTreeRefChild(\n writeTreeRef: WriteTreeRef,\n childName: string\n): WriteTreeRef {\n return newWriteTreeRef(\n pathChild(writeTreeRef.treePath, childName),\n writeTreeRef.writeTree\n );\n}\n\nexport function newWriteTreeRef(\n path: Path,\n writeTree: WriteTree\n): WriteTreeRef {\n return {\n treePath: path,\n writeTree\n };\n}\n\n/**\n * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods\n * just proxy to the underlying WriteTree.\n *\n */\nexport interface WriteTreeRef {\n /**\n * The path to this particular write tree ref. Used for calling methods on writeTree_ while exposing a simpler\n * interface to callers.\n */\n readonly treePath: Path;\n\n /**\n * * A reference to the actual tree of write data. All methods are pass-through to the tree, but with the appropriate\n * path prefixed.\n *\n * This lets us make cheap references to points in the tree for sync points without having to copy and maintain all of\n * the data.\n */\n readonly writeTree: WriteTree;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport {\n Change,\n ChangeType,\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from './Change';\n\nexport class ChildChangeAccumulator {\n private readonly changeMap: Map = new Map();\n\n trackChildChange(change: Change) {\n const type = change.type;\n const childKey = change.childName!;\n assert(\n type === ChangeType.CHILD_ADDED ||\n type === ChangeType.CHILD_CHANGED ||\n type === ChangeType.CHILD_REMOVED,\n 'Only child changes supported for tracking'\n );\n assert(\n childKey !== '.priority',\n 'Only non-priority child changes can be tracked.'\n );\n const oldChange = this.changeMap.get(childKey);\n if (oldChange) {\n const oldType = oldChange.type;\n if (\n type === ChangeType.CHILD_ADDED &&\n oldType === ChangeType.CHILD_REMOVED\n ) {\n this.changeMap.set(\n childKey,\n changeChildChanged(\n childKey,\n change.snapshotNode,\n oldChange.snapshotNode\n )\n );\n } else if (\n type === ChangeType.CHILD_REMOVED &&\n oldType === ChangeType.CHILD_ADDED\n ) {\n this.changeMap.delete(childKey);\n } else if (\n type === ChangeType.CHILD_REMOVED &&\n oldType === ChangeType.CHILD_CHANGED\n ) {\n this.changeMap.set(\n childKey,\n changeChildRemoved(childKey, oldChange.oldSnap)\n );\n } else if (\n type === ChangeType.CHILD_CHANGED &&\n oldType === ChangeType.CHILD_ADDED\n ) {\n this.changeMap.set(\n childKey,\n changeChildAdded(childKey, change.snapshotNode)\n );\n } else if (\n type === ChangeType.CHILD_CHANGED &&\n oldType === ChangeType.CHILD_CHANGED\n ) {\n this.changeMap.set(\n childKey,\n changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap)\n );\n } else {\n throw assertionError(\n 'Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange\n );\n }\n } else {\n this.changeMap.set(childKey, change);\n }\n }\n\n getChanges(): Change[] {\n return Array.from(this.changeMap.values());\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Index } from '../snap/indexes/Index';\nimport { NamedNode, Node } from '../snap/Node';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteChild,\n writeTreeRefCalcIndexedSlice\n} from '../WriteTree';\n\nimport { CacheNode } from './CacheNode';\nimport { ViewCache, viewCacheGetCompleteServerSnap } from './ViewCache';\n\n/**\n * Since updates to filtered nodes might require nodes to be pulled in from \"outside\" the node, this interface\n * can help to get complete children that can be pulled in.\n * A class implementing this interface takes potentially multiple sources (e.g. user writes, server data from\n * other views etc.) to try it's best to get a complete child that might be useful in pulling into the view.\n *\n * @interface\n */\nexport interface CompleteChildSource {\n getCompleteChild(childKey: string): Node | null;\n\n getChildAfterChild(\n index: Index,\n child: NamedNode,\n reverse: boolean\n ): NamedNode | null;\n}\n\n/**\n * An implementation of CompleteChildSource that never returns any additional children\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class NoCompleteChildSource_ implements CompleteChildSource {\n getCompleteChild(childKey?: string): Node | null {\n return null;\n }\n getChildAfterChild(\n index?: Index,\n child?: NamedNode,\n reverse?: boolean\n ): NamedNode | null {\n return null;\n }\n}\n\n/**\n * Singleton instance.\n */\nexport const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n\n/**\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\n * old event caches available to calculate complete children.\n */\nexport class WriteTreeCompleteChildSource implements CompleteChildSource {\n constructor(\n private writes_: WriteTreeRef,\n private viewCache_: ViewCache,\n private optCompleteServerCache_: Node | null = null\n ) {}\n getCompleteChild(childKey: string): Node | null {\n const node = this.viewCache_.eventCache;\n if (node.isCompleteForChild(childKey)) {\n return node.getNode().getImmediateChild(childKey);\n } else {\n const serverNode =\n this.optCompleteServerCache_ != null\n ? new CacheNode(this.optCompleteServerCache_, true, false)\n : this.viewCache_.serverCache;\n return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);\n }\n }\n getChildAfterChild(\n index: Index,\n child: NamedNode,\n reverse: boolean\n ): NamedNode | null {\n const completeServerData =\n this.optCompleteServerCache_ != null\n ? this.optCompleteServerCache_\n : viewCacheGetCompleteServerSnap(this.viewCache_);\n const nodes = writeTreeRefCalcIndexedSlice(\n this.writes_,\n completeServerData,\n child,\n 1,\n reverse,\n index\n );\n if (nodes.length === 0) {\n return null;\n } else {\n return nodes[0];\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport { AckUserWrite } from '../operation/AckUserWrite';\nimport { Merge } from '../operation/Merge';\nimport { Operation, OperationType } from '../operation/Operation';\nimport { Overwrite } from '../operation/Overwrite';\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { KEY_INDEX } from '../snap/indexes/KeyIndex';\nimport { Node } from '../snap/Node';\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathChild,\n pathGetBack,\n pathGetFront,\n pathGetLength,\n pathIsEmpty,\n pathParent,\n pathPopFront\n} from '../util/Path';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteChild,\n writeTreeRefCalcCompleteEventCache,\n writeTreeRefCalcCompleteEventChildren,\n writeTreeRefCalcEventCacheAfterServerOverwrite,\n writeTreeRefShadowingWrite\n} from '../WriteTree';\n\nimport { Change, changeValue } from './Change';\nimport { ChildChangeAccumulator } from './ChildChangeAccumulator';\nimport {\n CompleteChildSource,\n NO_COMPLETE_CHILD_SOURCE,\n WriteTreeCompleteChildSource\n} from './CompleteChildSource';\nimport { NodeFilter } from './filter/NodeFilter';\nimport {\n ViewCache,\n viewCacheGetCompleteEventSnap,\n viewCacheGetCompleteServerSnap,\n viewCacheUpdateEventSnap,\n viewCacheUpdateServerSnap\n} from './ViewCache';\n\nexport interface ProcessorResult {\n readonly viewCache: ViewCache;\n readonly changes: Change[];\n}\n\nexport interface ViewProcessor {\n readonly filter: NodeFilter;\n}\n\nexport function newViewProcessor(filter: NodeFilter): ViewProcessor {\n return { filter };\n}\n\nexport function viewProcessorAssertIndexed(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache\n): void {\n assert(\n viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()),\n 'Event snap not indexed'\n );\n assert(\n viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()),\n 'Server snap not indexed'\n );\n}\n\nexport function viewProcessorApplyOperation(\n viewProcessor: ViewProcessor,\n oldViewCache: ViewCache,\n operation: Operation,\n writesCache: WriteTreeRef,\n completeCache: Node | null\n): ProcessorResult {\n const accumulator = new ChildChangeAccumulator();\n let newViewCache, filterServerNode;\n if (operation.type === OperationType.OVERWRITE) {\n const overwrite = operation as Overwrite;\n if (overwrite.source.fromUser) {\n newViewCache = viewProcessorApplyUserOverwrite(\n viewProcessor,\n oldViewCache,\n overwrite.path,\n overwrite.snap,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n assert(overwrite.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered and the\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\n // again\n filterServerNode =\n overwrite.source.tagged ||\n (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));\n newViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\n oldViewCache,\n overwrite.path,\n overwrite.snap,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n } else if (operation.type === OperationType.MERGE) {\n const merge = operation as Merge;\n if (merge.source.fromUser) {\n newViewCache = viewProcessorApplyUserMerge(\n viewProcessor,\n oldViewCache,\n merge.path,\n merge.children,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n assert(merge.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered\n filterServerNode =\n merge.source.tagged || oldViewCache.serverCache.isFiltered();\n newViewCache = viewProcessorApplyServerMerge(\n viewProcessor,\n oldViewCache,\n merge.path,\n merge.children,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n } else if (operation.type === OperationType.ACK_USER_WRITE) {\n const ackUserWrite = operation as AckUserWrite;\n if (!ackUserWrite.revert) {\n newViewCache = viewProcessorAckUserWrite(\n viewProcessor,\n oldViewCache,\n ackUserWrite.path,\n ackUserWrite.affectedTree,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n newViewCache = viewProcessorRevertUserWrite(\n viewProcessor,\n oldViewCache,\n ackUserWrite.path,\n writesCache,\n completeCache,\n accumulator\n );\n }\n } else if (operation.type === OperationType.LISTEN_COMPLETE) {\n newViewCache = viewProcessorListenComplete(\n viewProcessor,\n oldViewCache,\n operation.path,\n writesCache,\n accumulator\n );\n } else {\n throw assertionError('Unknown operation type: ' + operation.type);\n }\n const changes = accumulator.getChanges();\n viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);\n return { viewCache: newViewCache, changes };\n}\n\nfunction viewProcessorMaybeAddValueEvent(\n oldViewCache: ViewCache,\n newViewCache: ViewCache,\n accumulator: Change[]\n): void {\n const eventSnap = newViewCache.eventCache;\n if (eventSnap.isFullyInitialized()) {\n const isLeafOrEmpty =\n eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);\n if (\n accumulator.length > 0 ||\n !oldViewCache.eventCache.isFullyInitialized() ||\n (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||\n !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())\n ) {\n accumulator.push(\n changeValue(viewCacheGetCompleteEventSnap(newViewCache))\n );\n }\n }\n}\n\nfunction viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n changePath: Path,\n writesCache: WriteTreeRef,\n source: CompleteChildSource,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldEventSnap = viewCache.eventCache;\n if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n } else {\n let newEventCache, serverNode;\n if (pathIsEmpty(changePath)) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n assert(\n viewCache.serverCache.isFullyInitialized(),\n 'If change path is empty, we must have complete server data'\n );\n if (viewCache.serverCache.isFiltered()) {\n // We need to special case this, because we need to only apply writes to complete children, or\n // we might end up raising events for incomplete children. If the server data is filtered deep\n // writes cannot be guaranteed to be complete\n const serverCache = viewCacheGetCompleteServerSnap(viewCache);\n const completeChildren =\n serverCache instanceof ChildrenNode\n ? serverCache\n : ChildrenNode.EMPTY_NODE;\n const completeEventChildren = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n completeChildren\n );\n newEventCache = viewProcessor.filter.updateFullNode(\n viewCache.eventCache.getNode(),\n completeEventChildren,\n accumulator\n );\n } else {\n const completeNode = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n newEventCache = viewProcessor.filter.updateFullNode(\n viewCache.eventCache.getNode(),\n completeNode,\n accumulator\n );\n }\n } else {\n const childKey = pathGetFront(changePath);\n if (childKey === '.priority') {\n assert(\n pathGetLength(changePath) === 1,\n \"Can't have a priority with additional path components\"\n );\n const oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.serverCache.getNode();\n // we might have overwrites for this priority\n const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(\n writesCache,\n changePath,\n oldEventNode,\n serverNode\n );\n if (updatedPriority != null) {\n newEventCache = viewProcessor.filter.updatePriority(\n oldEventNode,\n updatedPriority\n );\n } else {\n // priority didn't change, keep old node\n newEventCache = oldEventSnap.getNode();\n }\n } else {\n const childChangePath = pathPopFront(changePath);\n // update child\n let newEventChild;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.serverCache.getNode();\n const eventChildUpdate =\n writeTreeRefCalcEventCacheAfterServerOverwrite(\n writesCache,\n changePath,\n oldEventSnap.getNode(),\n serverNode\n );\n if (eventChildUpdate != null) {\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey)\n .updateChild(childChangePath, eventChildUpdate);\n } else {\n // Nothing changed, just keep the old child\n newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);\n }\n } else {\n newEventChild = writeTreeRefCalcCompleteChild(\n writesCache,\n childKey,\n viewCache.serverCache\n );\n }\n if (newEventChild != null) {\n newEventCache = viewProcessor.filter.updateChild(\n oldEventSnap.getNode(),\n childKey,\n newEventChild,\n childChangePath,\n source,\n accumulator\n );\n } else {\n // no complete child available or no change\n newEventCache = oldEventSnap.getNode();\n }\n }\n }\n return viewCacheUpdateEventSnap(\n viewCache,\n newEventCache,\n oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath),\n viewProcessor.filter.filtersNodes()\n );\n }\n}\n\nfunction viewProcessorApplyServerOverwrite(\n viewProcessor: ViewProcessor,\n oldViewCache: ViewCache,\n changePath: Path,\n changedSnap: Node,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n filterServerNode: boolean,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldServerSnap = oldViewCache.serverCache;\n let newServerCache;\n const serverFilter = filterServerNode\n ? viewProcessor.filter\n : viewProcessor.filter.getIndexedFilter();\n if (pathIsEmpty(changePath)) {\n newServerCache = serverFilter.updateFullNode(\n oldServerSnap.getNode(),\n changedSnap,\n null\n );\n } else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\n const newServerNode = oldServerSnap\n .getNode()\n .updateChild(changePath, changedSnap);\n newServerCache = serverFilter.updateFullNode(\n oldServerSnap.getNode(),\n newServerNode,\n null\n );\n } else {\n const childKey = pathGetFront(changePath);\n if (\n !oldServerSnap.isCompleteForPath(changePath) &&\n pathGetLength(changePath) > 1\n ) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n const childChangePath = pathPopFront(changePath);\n const childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n const newChildNode = childNode.updateChild(childChangePath, changedSnap);\n if (childKey === '.priority') {\n newServerCache = serverFilter.updatePriority(\n oldServerSnap.getNode(),\n newChildNode\n );\n } else {\n newServerCache = serverFilter.updateChild(\n oldServerSnap.getNode(),\n childKey,\n newChildNode,\n childChangePath,\n NO_COMPLETE_CHILD_SOURCE,\n null\n );\n }\n }\n const newViewCache = viewCacheUpdateServerSnap(\n oldViewCache,\n newServerCache,\n oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath),\n serverFilter.filtersNodes()\n );\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n newViewCache,\n completeCache\n );\n return viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor,\n newViewCache,\n changePath,\n writesCache,\n source,\n accumulator\n );\n}\n\nfunction viewProcessorApplyUserOverwrite(\n viewProcessor: ViewProcessor,\n oldViewCache: ViewCache,\n changePath: Path,\n changedSnap: Node,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldEventSnap = oldViewCache.eventCache;\n let newViewCache, newEventCache;\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n oldViewCache,\n completeCache\n );\n if (pathIsEmpty(changePath)) {\n newEventCache = viewProcessor.filter.updateFullNode(\n oldViewCache.eventCache.getNode(),\n changedSnap,\n accumulator\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventCache,\n true,\n viewProcessor.filter.filtersNodes()\n );\n } else {\n const childKey = pathGetFront(changePath);\n if (childKey === '.priority') {\n newEventCache = viewProcessor.filter.updatePriority(\n oldViewCache.eventCache.getNode(),\n changedSnap\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventCache,\n oldEventSnap.isFullyInitialized(),\n oldEventSnap.isFiltered()\n );\n } else {\n const childChangePath = pathPopFront(changePath);\n const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n let newChild;\n if (pathIsEmpty(childChangePath)) {\n // Child overwrite, we can replace the child\n newChild = changedSnap;\n } else {\n const childNode = source.getCompleteChild(childKey);\n if (childNode != null) {\n if (\n pathGetBack(childChangePath) === '.priority' &&\n childNode.getChild(pathParent(childChangePath)).isEmpty()\n ) {\n // This is a priority update on an empty node. If this node exists on the server, the\n // server will send down the priority in the update, so ignore for now\n newChild = childNode;\n } else {\n newChild = childNode.updateChild(childChangePath, changedSnap);\n }\n } else {\n // There is no complete child node available\n newChild = ChildrenNode.EMPTY_NODE;\n }\n }\n if (!oldChild.equals(newChild)) {\n const newEventSnap = viewProcessor.filter.updateChild(\n oldEventSnap.getNode(),\n childKey,\n newChild,\n childChangePath,\n source,\n accumulator\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventSnap,\n oldEventSnap.isFullyInitialized(),\n viewProcessor.filter.filtersNodes()\n );\n } else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n}\n\nfunction viewProcessorCacheHasChild(\n viewCache: ViewCache,\n childKey: string\n): boolean {\n return viewCache.eventCache.isCompleteForChild(childKey);\n}\n\nfunction viewProcessorApplyUserMerge(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n changedChildren: ImmutableTree,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n let curViewCache = viewCache;\n changedChildren.foreach((relativePath, childNode) => {\n const writePath = pathChild(path, relativePath);\n if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\n curViewCache = viewProcessorApplyUserOverwrite(\n viewProcessor,\n curViewCache,\n writePath,\n childNode,\n writesCache,\n serverCache,\n accumulator\n );\n }\n });\n\n changedChildren.foreach((relativePath, childNode) => {\n const writePath = pathChild(path, relativePath);\n if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\n curViewCache = viewProcessorApplyUserOverwrite(\n viewProcessor,\n curViewCache,\n writePath,\n childNode,\n writesCache,\n serverCache,\n accumulator\n );\n }\n });\n\n return curViewCache;\n}\n\nfunction viewProcessorApplyMerge(\n viewProcessor: ViewProcessor,\n node: Node,\n merge: ImmutableTree\n): Node {\n merge.foreach((relativePath, childNode) => {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n}\n\nfunction viewProcessorApplyServerMerge(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n changedChildren: ImmutableTree,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n filterServerNode: boolean,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\n // wait for the complete data update coming soon.\n if (\n viewCache.serverCache.getNode().isEmpty() &&\n !viewCache.serverCache.isFullyInitialized()\n ) {\n return viewCache;\n }\n\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n let curViewCache = viewCache;\n let viewMergeTree: ImmutableTree;\n if (pathIsEmpty(path)) {\n viewMergeTree = changedChildren;\n } else {\n viewMergeTree = new ImmutableTree(null).setTree(\n path,\n changedChildren\n );\n }\n const serverNode = viewCache.serverCache.getNode();\n viewMergeTree.children.inorderTraversal((childKey, childTree) => {\n if (serverNode.hasChild(childKey)) {\n const serverChild = viewCache.serverCache\n .getNode()\n .getImmediateChild(childKey);\n const newChild = viewProcessorApplyMerge(\n viewProcessor,\n serverChild,\n childTree\n );\n curViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\n curViewCache,\n new Path(childKey),\n newChild,\n writesCache,\n serverCache,\n filterServerNode,\n accumulator\n );\n }\n });\n viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {\n const isUnknownDeepMerge =\n !viewCache.serverCache.isCompleteForChild(childKey) &&\n childMergeTree.value === null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n const serverChild = viewCache.serverCache\n .getNode()\n .getImmediateChild(childKey);\n const newChild = viewProcessorApplyMerge(\n viewProcessor,\n serverChild,\n childMergeTree\n );\n curViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\n curViewCache,\n new Path(childKey),\n newChild,\n writesCache,\n serverCache,\n filterServerNode,\n accumulator\n );\n }\n });\n\n return curViewCache;\n}\n\nfunction viewProcessorAckUserWrite(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n ackPath: Path,\n affectedTree: ImmutableTree,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {\n return viewCache;\n }\n\n // Only filter server node if it is currently filtered\n const filterServerNode = viewCache.serverCache.isFiltered();\n\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\n // now that it won't be shadowed.\n const serverCache = viewCache.serverCache;\n if (affectedTree.value != null) {\n // This is an overwrite.\n if (\n (pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)\n ) {\n return viewProcessorApplyServerOverwrite(\n viewProcessor,\n viewCache,\n ackPath,\n serverCache.getNode().getChild(ackPath),\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n } else if (pathIsEmpty(ackPath)) {\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\n // should just re-apply whatever we have in our cache as a merge.\n let changedChildren = new ImmutableTree(null);\n serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {\n changedChildren = changedChildren.set(new Path(name), node);\n });\n return viewProcessorApplyServerMerge(\n viewProcessor,\n viewCache,\n ackPath,\n changedChildren,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n } else {\n return viewCache;\n }\n } else {\n // This is a merge.\n let changedChildren = new ImmutableTree(null);\n affectedTree.foreach((mergePath, value) => {\n const serverCachePath = pathChild(ackPath, mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren = changedChildren.set(\n mergePath,\n serverCache.getNode().getChild(serverCachePath)\n );\n }\n });\n return viewProcessorApplyServerMerge(\n viewProcessor,\n viewCache,\n ackPath,\n changedChildren,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n}\n\nfunction viewProcessorListenComplete(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n writesCache: WriteTreeRef,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldServerNode = viewCache.serverCache;\n const newViewCache = viewCacheUpdateServerSnap(\n viewCache,\n oldServerNode.getNode(),\n oldServerNode.isFullyInitialized() || pathIsEmpty(path),\n oldServerNode.isFiltered()\n );\n return viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor,\n newViewCache,\n path,\n writesCache,\n NO_COMPLETE_CHILD_SOURCE,\n accumulator\n );\n}\n\nfunction viewProcessorRevertUserWrite(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n writesCache: WriteTreeRef,\n completeServerCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n let complete;\n if (writeTreeRefShadowingWrite(writesCache, path) != null) {\n return viewCache;\n } else {\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n viewCache,\n completeServerCache\n );\n const oldEventCache = viewCache.eventCache.getNode();\n let newEventCache;\n if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {\n let newNode;\n if (viewCache.serverCache.isFullyInitialized()) {\n newNode = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n } else {\n const serverChildren = viewCache.serverCache.getNode();\n assert(\n serverChildren instanceof ChildrenNode,\n 'serverChildren would be complete if leaf node'\n );\n newNode = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n serverChildren as ChildrenNode\n );\n }\n newNode = newNode as Node;\n newEventCache = viewProcessor.filter.updateFullNode(\n oldEventCache,\n newNode,\n accumulator\n );\n } else {\n const childKey = pathGetFront(path);\n let newChild = writeTreeRefCalcCompleteChild(\n writesCache,\n childKey,\n viewCache.serverCache\n );\n if (\n newChild == null &&\n viewCache.serverCache.isCompleteForChild(childKey)\n ) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = viewProcessor.filter.updateChild(\n oldEventCache,\n childKey,\n newChild,\n pathPopFront(path),\n source,\n accumulator\n );\n } else if (viewCache.eventCache.getNode().hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = viewProcessor.filter.updateChild(\n oldEventCache,\n childKey,\n ChildrenNode.EMPTY_NODE,\n pathPopFront(path),\n source,\n accumulator\n );\n } else {\n newEventCache = oldEventCache;\n }\n if (\n newEventCache.isEmpty() &&\n viewCache.serverCache.isFullyInitialized()\n ) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n if (complete.isLeafNode()) {\n newEventCache = viewProcessor.filter.updateFullNode(\n newEventCache,\n complete,\n accumulator\n );\n }\n }\n }\n complete =\n viewCache.serverCache.isFullyInitialized() ||\n writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;\n return viewCacheUpdateEventSnap(\n viewCache,\n newEventCache,\n complete,\n viewProcessor.filter.filtersNodes()\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Operation, OperationType } from '../operation/Operation';\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { PRIORITY_INDEX } from '../snap/indexes/PriorityIndex';\nimport { Node } from '../snap/Node';\nimport { Path, pathGetFront, pathIsEmpty } from '../util/Path';\nimport { WriteTreeRef } from '../WriteTree';\n\nimport { CacheNode } from './CacheNode';\nimport { Change, changeChildAdded, changeValue } from './Change';\nimport { CancelEvent, Event } from './Event';\nimport {\n EventGenerator,\n eventGeneratorGenerateEventsForChanges\n} from './EventGenerator';\nimport { EventRegistration, QueryContext } from './EventRegistration';\nimport { IndexedFilter } from './filter/IndexedFilter';\nimport { queryParamsGetNodeFilter } from './QueryParams';\nimport {\n newViewCache,\n ViewCache,\n viewCacheGetCompleteEventSnap,\n viewCacheGetCompleteServerSnap\n} from './ViewCache';\nimport {\n newViewProcessor,\n ViewProcessor,\n viewProcessorApplyOperation,\n viewProcessorAssertIndexed\n} from './ViewProcessor';\n\n/**\n * A view represents a specific location and query that has 1 or more event registrations.\n *\n * It does several things:\n * - Maintains the list of event registrations for this location/query.\n * - Maintains a cache of the data visible for this location/query.\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\n * registrations returns the set of events to be raised.\n */\nexport class View {\n processor_: ViewProcessor;\n viewCache_: ViewCache;\n eventRegistrations_: EventRegistration[] = [];\n eventGenerator_: EventGenerator;\n\n constructor(private query_: QueryContext, initialViewCache: ViewCache) {\n const params = this.query_._queryParams;\n\n const indexFilter = new IndexedFilter(params.getIndex());\n const filter = queryParamsGetNodeFilter(params);\n\n this.processor_ = newViewProcessor(filter);\n\n const initialServerCache = initialViewCache.serverCache;\n const initialEventCache = initialViewCache.eventCache;\n\n // Don't filter server node with other filter than index, wait for tagged listen\n const serverSnap = indexFilter.updateFullNode(\n ChildrenNode.EMPTY_NODE,\n initialServerCache.getNode(),\n null\n );\n const eventSnap = filter.updateFullNode(\n ChildrenNode.EMPTY_NODE,\n initialEventCache.getNode(),\n null\n );\n const newServerCache = new CacheNode(\n serverSnap,\n initialServerCache.isFullyInitialized(),\n indexFilter.filtersNodes()\n );\n const newEventCache = new CacheNode(\n eventSnap,\n initialEventCache.isFullyInitialized(),\n filter.filtersNodes()\n );\n\n this.viewCache_ = newViewCache(newEventCache, newServerCache);\n this.eventGenerator_ = new EventGenerator(this.query_);\n }\n\n get query(): QueryContext {\n return this.query_;\n }\n}\n\nexport function viewGetServerCache(view: View): Node | null {\n return view.viewCache_.serverCache.getNode();\n}\n\nexport function viewGetCompleteNode(view: View): Node | null {\n return viewCacheGetCompleteEventSnap(view.viewCache_);\n}\n\nexport function viewGetCompleteServerCache(\n view: View,\n path: Path\n): Node | null {\n const cache = viewCacheGetCompleteServerSnap(view.viewCache_);\n if (cache) {\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\n // we need to see if it contains the child we're interested in.\n if (\n view.query._queryParams.loadsAllData() ||\n (!pathIsEmpty(path) &&\n !cache.getImmediateChild(pathGetFront(path)).isEmpty())\n ) {\n return cache.getChild(path);\n }\n }\n return null;\n}\n\nexport function viewIsEmpty(view: View): boolean {\n return view.eventRegistrations_.length === 0;\n}\n\nexport function viewAddEventRegistration(\n view: View,\n eventRegistration: EventRegistration\n) {\n view.eventRegistrations_.push(eventRegistration);\n}\n\n/**\n * @param eventRegistration - If null, remove all callbacks.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @returns Cancel events, if cancelError was provided.\n */\nexport function viewRemoveEventRegistration(\n view: View,\n eventRegistration: EventRegistration | null,\n cancelError?: Error\n): Event[] {\n const cancelEvents: CancelEvent[] = [];\n if (cancelError) {\n assert(\n eventRegistration == null,\n 'A cancel should cancel all event registrations.'\n );\n const path = view.query._path;\n view.eventRegistrations_.forEach(registration => {\n const maybeEvent = registration.createCancelEvent(cancelError, path);\n if (maybeEvent) {\n cancelEvents.push(maybeEvent);\n }\n });\n }\n\n if (eventRegistration) {\n let remaining = [];\n for (let i = 0; i < view.eventRegistrations_.length; ++i) {\n const existing = view.eventRegistrations_[i];\n if (!existing.matches(eventRegistration)) {\n remaining.push(existing);\n } else if (eventRegistration.hasAnyCallback()) {\n // We're removing just this one\n remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));\n break;\n }\n }\n view.eventRegistrations_ = remaining;\n } else {\n view.eventRegistrations_ = [];\n }\n return cancelEvents;\n}\n\n/**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n */\nexport function viewApplyOperation(\n view: View,\n operation: Operation,\n writesCache: WriteTreeRef,\n completeServerCache: Node | null\n): Event[] {\n if (\n operation.type === OperationType.MERGE &&\n operation.source.queryId !== null\n ) {\n assert(\n viewCacheGetCompleteServerSnap(view.viewCache_),\n 'We should always have a full cache before handling merges'\n );\n assert(\n viewCacheGetCompleteEventSnap(view.viewCache_),\n 'Missing event cache, even though we have a server cache'\n );\n }\n\n const oldViewCache = view.viewCache_;\n const result = viewProcessorApplyOperation(\n view.processor_,\n oldViewCache,\n operation,\n writesCache,\n completeServerCache\n );\n viewProcessorAssertIndexed(view.processor_, result.viewCache);\n\n assert(\n result.viewCache.serverCache.isFullyInitialized() ||\n !oldViewCache.serverCache.isFullyInitialized(),\n 'Once a server snap is complete, it should never go back'\n );\n\n view.viewCache_ = result.viewCache;\n\n return viewGenerateEventsForChanges_(\n view,\n result.changes,\n result.viewCache.eventCache.getNode(),\n null\n );\n}\n\nexport function viewGetInitialEvents(\n view: View,\n registration: EventRegistration\n): Event[] {\n const eventSnap = view.viewCache_.eventCache;\n const initialChanges: Change[] = [];\n if (!eventSnap.getNode().isLeafNode()) {\n const eventNode = eventSnap.getNode() as ChildrenNode;\n eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n initialChanges.push(changeChildAdded(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(changeValue(eventSnap.getNode()));\n }\n return viewGenerateEventsForChanges_(\n view,\n initialChanges,\n eventSnap.getNode(),\n registration\n );\n}\n\nfunction viewGenerateEventsForChanges_(\n view: View,\n changes: Change[],\n eventCache: Node,\n eventRegistration?: EventRegistration\n): Event[] {\n const registrations = eventRegistration\n ? [eventRegistration]\n : view.eventRegistrations_;\n return eventGeneratorGenerateEventsForChanges(\n view.eventGenerator_,\n changes,\n eventCache,\n registrations\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ReferenceConstructor } from '../api/Reference';\n\nimport { Operation } from './operation/Operation';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { Path } from './util/Path';\nimport { CacheNode } from './view/CacheNode';\nimport { Event } from './view/Event';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\nimport {\n View,\n viewAddEventRegistration,\n viewApplyOperation,\n viewGetCompleteServerCache,\n viewGetInitialEvents,\n viewIsEmpty,\n viewRemoveEventRegistration\n} from './view/View';\nimport { newViewCache } from './view/ViewCache';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteEventCache,\n writeTreeRefCalcCompleteEventChildren\n} from './WriteTree';\n\nlet referenceConstructor: ReferenceConstructor;\n\n/**\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\n * and user writes (set, transaction, update).\n *\n * It's responsible for:\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\n * applyUserOverwrite, etc.)\n */\nexport class SyncPoint {\n /**\n * The Views being tracked at this location in the tree, stored as a map where the key is a\n * queryId and the value is the View for that query.\n *\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\n */\n readonly views: Map = new Map();\n}\n\nexport function syncPointSetReferenceConstructor(\n val: ReferenceConstructor\n): void {\n assert(\n !referenceConstructor,\n '__referenceConstructor has already been defined'\n );\n referenceConstructor = val;\n}\n\nfunction syncPointGetReferenceConstructor(): ReferenceConstructor {\n assert(referenceConstructor, 'Reference.ts has not been loaded');\n return referenceConstructor;\n}\n\nexport function syncPointIsEmpty(syncPoint: SyncPoint): boolean {\n return syncPoint.views.size === 0;\n}\n\nexport function syncPointApplyOperation(\n syncPoint: SyncPoint,\n operation: Operation,\n writesCache: WriteTreeRef,\n optCompleteServerCache: Node | null\n): Event[] {\n const queryId = operation.source.queryId;\n if (queryId !== null) {\n const view = syncPoint.views.get(queryId);\n assert(view != null, 'SyncTree gave us an op for an invalid query.');\n return viewApplyOperation(\n view,\n operation,\n writesCache,\n optCompleteServerCache\n );\n } else {\n let events: Event[] = [];\n\n for (const view of syncPoint.views.values()) {\n events = events.concat(\n viewApplyOperation(view, operation, writesCache, optCompleteServerCache)\n );\n }\n\n return events;\n }\n}\n\n/**\n * Get a view for the specified query.\n *\n * @param query - The query to return a view for\n * @param writesCache\n * @param serverCache\n * @param serverCacheComplete\n * @returns Events to raise.\n */\nexport function syncPointGetView(\n syncPoint: SyncPoint,\n query: QueryContext,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n serverCacheComplete: boolean\n): View {\n const queryId = query._queryIdentifier;\n const view = syncPoint.views.get(queryId);\n if (!view) {\n // TODO: make writesCache take flag for complete server node\n let eventCache = writeTreeRefCalcCompleteEventCache(\n writesCache,\n serverCacheComplete ? serverCache : null\n );\n let eventCacheComplete = false;\n if (eventCache) {\n eventCacheComplete = true;\n } else if (serverCache instanceof ChildrenNode) {\n eventCache = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n serverCache\n );\n eventCacheComplete = false;\n } else {\n eventCache = ChildrenNode.EMPTY_NODE;\n eventCacheComplete = false;\n }\n const viewCache = newViewCache(\n new CacheNode(eventCache, eventCacheComplete, false),\n new CacheNode(serverCache, serverCacheComplete, false)\n );\n return new View(query, viewCache);\n }\n return view;\n}\n\n/**\n * Add an event callback for the specified query.\n *\n * @param query\n * @param eventRegistration\n * @param writesCache\n * @param serverCache - Complete server cache, if we have it.\n * @param serverCacheComplete\n * @returns Events to raise.\n */\nexport function syncPointAddEventRegistration(\n syncPoint: SyncPoint,\n query: QueryContext,\n eventRegistration: EventRegistration,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n serverCacheComplete: boolean\n): Event[] {\n const view = syncPointGetView(\n syncPoint,\n query,\n writesCache,\n serverCache,\n serverCacheComplete\n );\n if (!syncPoint.views.has(query._queryIdentifier)) {\n syncPoint.views.set(query._queryIdentifier, view);\n }\n // This is guaranteed to exist now, we just created anything that was missing\n viewAddEventRegistration(view, eventRegistration);\n return viewGetInitialEvents(view, eventRegistration);\n}\n\n/**\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\n *\n * If query is the default query, we'll check all views for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\n *\n * @param eventRegistration - If null, remove all callbacks.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @returns removed queries and any cancel events\n */\nexport function syncPointRemoveEventRegistration(\n syncPoint: SyncPoint,\n query: QueryContext,\n eventRegistration: EventRegistration | null,\n cancelError?: Error\n): { removed: QueryContext[]; events: Event[] } {\n const queryId = query._queryIdentifier;\n const removed: QueryContext[] = [];\n let cancelEvents: Event[] = [];\n const hadCompleteView = syncPointHasCompleteView(syncPoint);\n if (queryId === 'default') {\n // When you do ref.off(...), we search all views for the registration to remove.\n for (const [viewQueryId, view] of syncPoint.views.entries()) {\n cancelEvents = cancelEvents.concat(\n viewRemoveEventRegistration(view, eventRegistration, cancelError)\n );\n if (viewIsEmpty(view)) {\n syncPoint.views.delete(viewQueryId);\n\n // We'll deal with complete views later.\n if (!view.query._queryParams.loadsAllData()) {\n removed.push(view.query);\n }\n }\n }\n } else {\n // remove the callback from the specific view.\n const view = syncPoint.views.get(queryId);\n if (view) {\n cancelEvents = cancelEvents.concat(\n viewRemoveEventRegistration(view, eventRegistration, cancelError)\n );\n if (viewIsEmpty(view)) {\n syncPoint.views.delete(queryId);\n\n // We'll deal with complete views later.\n if (!view.query._queryParams.loadsAllData()) {\n removed.push(view.query);\n }\n }\n }\n }\n\n if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {\n // We removed our last complete view.\n removed.push(\n new (syncPointGetReferenceConstructor())(query._repo, query._path)\n );\n }\n\n return { removed, events: cancelEvents };\n}\n\nexport function syncPointGetQueryViews(syncPoint: SyncPoint): View[] {\n const result = [];\n for (const view of syncPoint.views.values()) {\n if (!view.query._queryParams.loadsAllData()) {\n result.push(view);\n }\n }\n return result;\n}\n\n/**\n * @param path - The path to the desired complete snapshot\n * @returns A complete cache, if it exists\n */\nexport function syncPointGetCompleteServerCache(\n syncPoint: SyncPoint,\n path: Path\n): Node | null {\n let serverCache: Node | null = null;\n for (const view of syncPoint.views.values()) {\n serverCache = serverCache || viewGetCompleteServerCache(view, path);\n }\n return serverCache;\n}\n\nexport function syncPointViewForQuery(\n syncPoint: SyncPoint,\n query: QueryContext\n): View | null {\n const params = query._queryParams;\n if (params.loadsAllData()) {\n return syncPointGetCompleteView(syncPoint);\n } else {\n const queryId = query._queryIdentifier;\n return syncPoint.views.get(queryId);\n }\n}\n\nexport function syncPointViewExistsForQuery(\n syncPoint: SyncPoint,\n query: QueryContext\n): boolean {\n return syncPointViewForQuery(syncPoint, query) != null;\n}\n\nexport function syncPointHasCompleteView(syncPoint: SyncPoint): boolean {\n return syncPointGetCompleteView(syncPoint) != null;\n}\n\nexport function syncPointGetCompleteView(syncPoint: SyncPoint): View | null {\n for (const view of syncPoint.views.values()) {\n if (view.query._queryParams.loadsAllData()) {\n return view;\n }\n }\n return null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ReferenceConstructor } from '../api/Reference';\n\nimport { AckUserWrite } from './operation/AckUserWrite';\nimport { ListenComplete } from './operation/ListenComplete';\nimport { Merge } from './operation/Merge';\nimport {\n newOperationSourceServer,\n newOperationSourceServerTaggedQuery,\n newOperationSourceUser,\n Operation\n} from './operation/Operation';\nimport { Overwrite } from './operation/Overwrite';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport {\n SyncPoint,\n syncPointAddEventRegistration,\n syncPointApplyOperation,\n syncPointGetCompleteServerCache,\n syncPointGetCompleteView,\n syncPointGetQueryViews,\n syncPointGetView,\n syncPointHasCompleteView,\n syncPointIsEmpty,\n syncPointRemoveEventRegistration,\n syncPointViewExistsForQuery,\n syncPointViewForQuery\n} from './SyncPoint';\nimport { ImmutableTree } from './util/ImmutableTree';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathGetFront,\n pathIsEmpty\n} from './util/Path';\nimport { each, errorForServerCode } from './util/util';\nimport { CacheNode } from './view/CacheNode';\nimport { Event } from './view/Event';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\nimport { View, viewGetCompleteNode, viewGetServerCache } from './view/View';\nimport {\n newWriteTree,\n WriteTree,\n writeTreeAddMerge,\n writeTreeAddOverwrite,\n writeTreeCalcCompleteEventCache,\n writeTreeChildWrites,\n writeTreeGetWrite,\n WriteTreeRef,\n writeTreeRefChild,\n writeTreeRemoveWrite\n} from './WriteTree';\n\nlet referenceConstructor: ReferenceConstructor;\n\nexport function syncTreeSetReferenceConstructor(\n val: ReferenceConstructor\n): void {\n assert(\n !referenceConstructor,\n '__referenceConstructor has already been defined'\n );\n referenceConstructor = val;\n}\n\nfunction syncTreeGetReferenceConstructor(): ReferenceConstructor {\n assert(referenceConstructor, 'Reference.ts has not been loaded');\n return referenceConstructor;\n}\n\nexport interface ListenProvider {\n startListening(\n query: QueryContext,\n tag: number | null,\n hashFn: () => string,\n onComplete: (a: string, b?: unknown) => Event[]\n ): Event[];\n\n stopListening(a: QueryContext, b: number | null): void;\n}\n\n/**\n * Static tracker for next query tag.\n */\nlet syncTreeNextQueryTag_ = 1;\n\nexport function resetSyncTreeTag() {\n syncTreeNextQueryTag_ = 1;\n}\n\n/**\n * SyncTree is the central class for managing event callback registration, data caching, views\n * (query processing), and event generation. There are typically two SyncTree instances for\n * each Repo, one for the normal Firebase data, and one for the .info data.\n *\n * It has a number of responsibilities, including:\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\n * - Applying and caching data changes for user set(), transaction(), and update() calls\n * (applyUserOverwrite(), applyUserMerge()).\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\n * applyServerMerge()).\n * - Generating user-facing events for server and user changes (all of the apply* methods\n * return the set of events that need to be raised as a result).\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\n * to the correct set of paths and queries to satisfy the current set of user event\n * callbacks (listens are started/stopped using the provided listenProvider).\n *\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\n * events are returned to the caller rather than raised synchronously.\n *\n */\nexport class SyncTree {\n /**\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\n */\n syncPointTree_: ImmutableTree = new ImmutableTree(null);\n\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n */\n pendingWriteTree_: WriteTree = newWriteTree();\n\n readonly tagToQueryMap: Map = new Map();\n readonly queryToTagMap: Map = new Map();\n\n /**\n * @param listenProvider_ - Used by SyncTree to start / stop listening\n * to server data.\n */\n constructor(public listenProvider_: ListenProvider) {}\n}\n\n/**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyUserOverwrite(\n syncTree: SyncTree,\n path: Path,\n newData: Node,\n writeId: number,\n visible?: boolean\n): Event[] {\n // Record pending write.\n writeTreeAddOverwrite(\n syncTree.pendingWriteTree_,\n path,\n newData,\n writeId,\n visible\n );\n\n if (!visible) {\n return [];\n } else {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Overwrite(newOperationSourceUser(), path, newData)\n );\n }\n}\n\n/**\n * Apply the data from a user-generated update() call\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyUserMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n writeId: number\n): Event[] {\n // Record pending merge.\n writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);\n\n const changeTree = ImmutableTree.fromObject(changedChildren);\n\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Merge(newOperationSourceUser(), path, changeTree)\n );\n}\n\n/**\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\n *\n * @param revert - True if the given write failed and needs to be reverted\n * @returns Events to raise.\n */\nexport function syncTreeAckUserWrite(\n syncTree: SyncTree,\n writeId: number,\n revert: boolean = false\n) {\n const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);\n const needToReevaluate = writeTreeRemoveWrite(\n syncTree.pendingWriteTree_,\n writeId\n );\n if (!needToReevaluate) {\n return [];\n } else {\n let affectedTree = new ImmutableTree(null);\n if (write.snap != null) {\n // overwrite\n affectedTree = affectedTree.set(newEmptyPath(), true);\n } else {\n each(write.children, (pathString: string) => {\n affectedTree = affectedTree.set(new Path(pathString), true);\n });\n }\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new AckUserWrite(write.path, affectedTree, revert)\n );\n }\n}\n\n/**\n * Apply new server data for the specified path..\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyServerOverwrite(\n syncTree: SyncTree,\n path: Path,\n newData: Node\n): Event[] {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Overwrite(newOperationSourceServer(), path, newData)\n );\n}\n\n/**\n * Apply new server data to be merged in at the specified path.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyServerMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node }\n): Event[] {\n const changeTree = ImmutableTree.fromObject(changedChildren);\n\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Merge(newOperationSourceServer(), path, changeTree)\n );\n}\n\n/**\n * Apply a listen complete for a query\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyListenComplete(\n syncTree: SyncTree,\n path: Path\n): Event[] {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new ListenComplete(newOperationSourceServer(), path)\n );\n}\n\n/**\n * Apply a listen complete for a tagged query\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedListenComplete(\n syncTree: SyncTree,\n path: Path,\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const op = new ListenComplete(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath\n );\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n } else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n}\n\n/**\n * Remove event callback(s).\n *\n * If query is the default query, we'll check all queries for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\n *\n * @param eventRegistration - If null, all callbacks are removed.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no\n * deduping needs to take place. This flag allows toggling of that behavior\n * @returns Cancel events, if cancelError was provided.\n */\nexport function syncTreeRemoveEventRegistration(\n syncTree: SyncTree,\n query: QueryContext,\n eventRegistration: EventRegistration | null,\n cancelError?: Error,\n skipListenerDedup = false\n): Event[] {\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\n const path = query._path;\n const maybeSyncPoint = syncTree.syncPointTree_.get(path);\n let cancelEvents: Event[] = [];\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\n // not loadsAllData().\n if (\n maybeSyncPoint &&\n (query._queryIdentifier === 'default' ||\n syncPointViewExistsForQuery(maybeSyncPoint, query))\n ) {\n const removedAndEvents = syncPointRemoveEventRegistration(\n maybeSyncPoint,\n query,\n eventRegistration,\n cancelError\n );\n if (syncPointIsEmpty(maybeSyncPoint)) {\n syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);\n }\n\n const removed = removedAndEvents.removed;\n cancelEvents = removedAndEvents.events;\n\n if (!skipListenerDedup) {\n /**\n * We may have just removed one of many listeners and can short-circuit this whole process\n * We may also not have removed a default listener, in which case all of the descendant listeners should already be\n * properly set up.\n */\n\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\n // queryId === 'default'\n const removingDefault =\n -1 !==\n removed.findIndex(query => {\n return query._queryParams.loadsAllData();\n });\n const covered = syncTree.syncPointTree_.findOnPath(\n path,\n (relativePath, parentSyncPoint) =>\n syncPointHasCompleteView(parentSyncPoint)\n );\n\n if (removingDefault && !covered) {\n const subtree = syncTree.syncPointTree_.subtree(path);\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\n // removal\n if (!subtree.isEmpty()) {\n // We need to fold over our subtree and collect the listeners to send\n const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);\n\n // Ok, we've collected all the listens we need. Set them up.\n for (let i = 0; i < newViews.length; ++i) {\n const view = newViews[i],\n newQuery = view.query;\n const listener = syncTreeCreateListenerForView_(syncTree, view);\n syncTree.listenProvider_.startListening(\n syncTreeQueryForListening_(newQuery),\n syncTreeTagForQuery(syncTree, newQuery),\n listener.hashFn,\n listener.onComplete\n );\n }\n }\n // Otherwise there's nothing below us, so nothing we need to start listening on\n }\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\n if (!covered && removed.length > 0 && !cancelError) {\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\n // default. Otherwise, we need to iterate through and cancel each individual query\n if (removingDefault) {\n // We don't tag default listeners\n const defaultTag: number | null = null;\n syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(query),\n defaultTag\n );\n } else {\n removed.forEach((queryToRemove: QueryContext) => {\n const tagToRemove = syncTree.queryToTagMap.get(\n syncTreeMakeQueryKey_(queryToRemove)\n );\n syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(queryToRemove),\n tagToRemove\n );\n });\n }\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n syncTreeRemoveTags_(syncTree, removed);\n } else {\n // No-op, this listener must've been already removed\n }\n return cancelEvents;\n}\n\n/**\n * Apply new server data for the specified tagged query.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedQueryOverwrite(\n syncTree: SyncTree,\n path: Path,\n snap: Node,\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey != null) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const op = new Overwrite(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath,\n snap\n );\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n } else {\n // Query must have been removed already\n return [];\n }\n}\n\n/**\n * Apply server data to be merged in for the specified tagged query.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedQueryMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const changeTree = ImmutableTree.fromObject(changedChildren);\n const op = new Merge(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath,\n changeTree\n );\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n } else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n}\n\n/**\n * Add an event callback for the specified query.\n *\n * @returns Events to raise.\n */\nexport function syncTreeAddEventRegistration(\n syncTree: SyncTree,\n query: QueryContext,\n eventRegistration: EventRegistration,\n skipSetupListener = false\n): Event[] {\n const path = query._path;\n\n let serverCache: Node | null = null;\n let foundAncestorDefaultView = false;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\n const relativePath = newRelativePath(pathToSyncPoint, path);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPointHasCompleteView(sp);\n });\n let syncPoint = syncTree.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint();\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\n } else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n\n let serverCacheComplete;\n if (serverCache != null) {\n serverCacheComplete = true;\n } else {\n serverCacheComplete = false;\n serverCache = ChildrenNode.EMPTY_NODE;\n const subtree = syncTree.syncPointTree_.subtree(path);\n subtree.foreachChild((childName, childSyncPoint) => {\n const completeCache = syncPointGetCompleteServerCache(\n childSyncPoint,\n newEmptyPath()\n );\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(\n childName,\n completeCache\n );\n }\n });\n }\n\n const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);\n if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {\n // We need to track a tag for this query\n const queryKey = syncTreeMakeQueryKey_(query);\n assert(\n !syncTree.queryToTagMap.has(queryKey),\n 'View does not exist, but we have a tag'\n );\n const tag = syncTreeGetNextQueryTag_();\n syncTree.queryToTagMap.set(queryKey, tag);\n syncTree.tagToQueryMap.set(tag, queryKey);\n }\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);\n let events = syncPointAddEventRegistration(\n syncPoint,\n query,\n eventRegistration,\n writesCache,\n serverCache,\n serverCacheComplete\n );\n if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {\n const view = syncPointViewForQuery(syncPoint, query);\n events = events.concat(syncTreeSetupListener_(syncTree, query, view));\n }\n return events;\n}\n\n/**\n * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a\n * listener above it, we will get a false \"null\". This shouldn't be a problem because transactions will always\n * have a listener above, and atomic operations would correctly show a jitter of ->\n * as the write is applied locally and then acknowledged at the server.\n *\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\n *\n * @param path - The path to the data we want\n * @param writeIdsToExclude - A specific set to be excluded\n */\nexport function syncTreeCalcCompleteEventCache(\n syncTree: SyncTree,\n path: Path,\n writeIdsToExclude?: number[]\n): Node {\n const includeHiddenSets = true;\n const writeTree = syncTree.pendingWriteTree_;\n const serverCache = syncTree.syncPointTree_.findOnPath(\n path,\n (pathSoFar, syncPoint) => {\n const relativePath = newRelativePath(pathSoFar, path);\n const serverCache = syncPointGetCompleteServerCache(\n syncPoint,\n relativePath\n );\n if (serverCache) {\n return serverCache;\n }\n }\n );\n return writeTreeCalcCompleteEventCache(\n writeTree,\n path,\n serverCache,\n writeIdsToExclude,\n includeHiddenSets\n );\n}\n\nexport function syncTreeGetServerValue(\n syncTree: SyncTree,\n query: QueryContext\n): Node | null {\n const path = query._path;\n let serverCache: Node | null = null;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\n const relativePath = newRelativePath(pathToSyncPoint, path);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\n });\n let syncPoint = syncTree.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint();\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\n } else {\n serverCache =\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n const serverCacheComplete = serverCache != null;\n const serverCacheNode: CacheNode | null = serverCacheComplete\n ? new CacheNode(serverCache, true, false)\n : null;\n const writesCache: WriteTreeRef | null = writeTreeChildWrites(\n syncTree.pendingWriteTree_,\n query._path\n );\n const view: View = syncPointGetView(\n syncPoint,\n query,\n writesCache,\n serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE,\n serverCacheComplete\n );\n return viewGetCompleteNode(view);\n}\n\n/**\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\n *\n * NOTES:\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\n *\n * - We call applyOperation() on each SyncPoint passing three things:\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\n * 3. A snapshot Node with cached server data, if we have it.\n *\n * - We concatenate all of the events returned by each SyncPoint and return the result.\n */\nfunction syncTreeApplyOperationToSyncPoints_(\n syncTree: SyncTree,\n operation: Operation\n): Event[] {\n return syncTreeApplyOperationHelper_(\n operation,\n syncTree.syncPointTree_,\n /*serverCache=*/ null,\n writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath())\n );\n}\n\n/**\n * Recursive helper for applyOperationToSyncPoints_\n */\nfunction syncTreeApplyOperationHelper_(\n operation: Operation,\n syncPointTree: ImmutableTree,\n serverCache: Node | null,\n writesCache: WriteTreeRef\n): Event[] {\n if (pathIsEmpty(operation.path)) {\n return syncTreeApplyOperationDescendantsHelper_(\n operation,\n syncPointTree,\n serverCache,\n writesCache\n );\n } else {\n const syncPoint = syncPointTree.get(newEmptyPath());\n\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n\n let events: Event[] = [];\n const childName = pathGetFront(operation.path);\n const childOperation = operation.operationForChild(childName);\n const childTree = syncPointTree.children.get(childName);\n if (childTree && childOperation) {\n const childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n const childWritesCache = writeTreeRefChild(writesCache, childName);\n events = events.concat(\n syncTreeApplyOperationHelper_(\n childOperation,\n childTree,\n childServerCache,\n childWritesCache\n )\n );\n }\n\n if (syncPoint) {\n events = events.concat(\n syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)\n );\n }\n\n return events;\n }\n}\n\n/**\n * Recursive helper for applyOperationToSyncPoints_\n */\nfunction syncTreeApplyOperationDescendantsHelper_(\n operation: Operation,\n syncPointTree: ImmutableTree,\n serverCache: Node | null,\n writesCache: WriteTreeRef\n): Event[] {\n const syncPoint = syncPointTree.get(newEmptyPath());\n\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n\n let events: Event[] = [];\n syncPointTree.children.inorderTraversal((childName, childTree) => {\n const childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n const childWritesCache = writeTreeRefChild(writesCache, childName);\n const childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(\n syncTreeApplyOperationDescendantsHelper_(\n childOperation,\n childTree,\n childServerCache,\n childWritesCache\n )\n );\n }\n });\n\n if (syncPoint) {\n events = events.concat(\n syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)\n );\n }\n\n return events;\n}\n\nfunction syncTreeCreateListenerForView_(\n syncTree: SyncTree,\n view: View\n): { hashFn(): string; onComplete(a: string, b?: unknown): Event[] } {\n const query = view.query;\n const tag = syncTreeTagForQuery(syncTree, query);\n\n return {\n hashFn: () => {\n const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: (status: string): Event[] => {\n if (status === 'ok') {\n if (tag) {\n return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);\n } else {\n return syncTreeApplyListenComplete(syncTree, query._path);\n }\n } else {\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\n const error = errorForServerCode(status, query);\n return syncTreeRemoveEventRegistration(\n syncTree,\n query,\n /*eventRegistration*/ null,\n error\n );\n }\n }\n };\n}\n\n/**\n * Return the tag associated with the given query.\n */\nexport function syncTreeTagForQuery(\n syncTree: SyncTree,\n query: QueryContext\n): number | null {\n const queryKey = syncTreeMakeQueryKey_(query);\n return syncTree.queryToTagMap.get(queryKey);\n}\n\n/**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n */\nfunction syncTreeMakeQueryKey_(query: QueryContext): string {\n return query._path.toString() + '$' + query._queryIdentifier;\n}\n\n/**\n * Return the query associated with the given tag, if we have one\n */\nfunction syncTreeQueryKeyForTag_(\n syncTree: SyncTree,\n tag: number\n): string | null {\n return syncTree.tagToQueryMap.get(tag);\n}\n\n/**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n */\nfunction syncTreeParseQueryKey_(queryKey: string): {\n queryId: string;\n path: Path;\n} {\n const splitIndex = queryKey.indexOf('$');\n assert(\n splitIndex !== -1 && splitIndex < queryKey.length - 1,\n 'Bad queryKey.'\n );\n return {\n queryId: queryKey.substr(splitIndex + 1),\n path: new Path(queryKey.substr(0, splitIndex))\n };\n}\n\n/**\n * A helper method to apply tagged operations\n */\nfunction syncTreeApplyTaggedOperation_(\n syncTree: SyncTree,\n queryPath: Path,\n operation: Operation\n): Event[] {\n const syncPoint = syncTree.syncPointTree_.get(queryPath);\n assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n const writesCache = writeTreeChildWrites(\n syncTree.pendingWriteTree_,\n queryPath\n );\n return syncPointApplyOperation(syncPoint, operation, writesCache, null);\n}\n\n/**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n */\nfunction syncTreeCollectDistinctViewsForSubTree_(\n subtree: ImmutableTree\n): View[] {\n return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {\n if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {\n const completeView = syncPointGetCompleteView(maybeChildSyncPoint);\n return [completeView];\n } else {\n // No complete view here, flatten any deeper listens into an array\n let views: View[] = [];\n if (maybeChildSyncPoint) {\n views = syncPointGetQueryViews(maybeChildSyncPoint);\n }\n each(childMap, (_key: string, childViews: View[]) => {\n views = views.concat(childViews);\n });\n return views;\n }\n });\n}\n\n/**\n * Normalizes a query to a query we send the server for listening\n *\n * @returns The normalized query\n */\nfunction syncTreeQueryForListening_(query: QueryContext): QueryContext {\n if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {\n // We treat queries that load all data as default queries\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n // from Query\n return new (syncTreeGetReferenceConstructor())(query._repo, query._path);\n } else {\n return query;\n }\n}\n\nfunction syncTreeRemoveTags_(syncTree: SyncTree, queries: QueryContext[]) {\n for (let j = 0; j < queries.length; ++j) {\n const removedQuery = queries[j];\n if (!removedQuery._queryParams.loadsAllData()) {\n // We should have a tag for this\n const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);\n const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);\n syncTree.queryToTagMap.delete(removedQueryKey);\n syncTree.tagToQueryMap.delete(removedQueryTag);\n }\n }\n}\n\n/**\n * Static accessor for query tags.\n */\nfunction syncTreeGetNextQueryTag_(): number {\n return syncTreeNextQueryTag_++;\n}\n\n/**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @returns This method can return events to support synchronous data sources\n */\nfunction syncTreeSetupListener_(\n syncTree: SyncTree,\n query: QueryContext,\n view: View\n): Event[] {\n const path = query._path;\n const tag = syncTreeTagForQuery(syncTree, query);\n const listener = syncTreeCreateListenerForView_(syncTree, view);\n\n const events = syncTree.listenProvider_.startListening(\n syncTreeQueryForListening_(query),\n tag,\n listener.hashFn,\n listener.onComplete\n );\n\n const subtree = syncTree.syncPointTree_.subtree(path);\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\n // may need to shadow other listens as well.\n if (tag) {\n assert(\n !syncPointHasCompleteView(subtree.value),\n \"If we're adding a query, it shouldn't be shadowed\"\n );\n } else {\n // Shadow everything at or below this location, this is a default listener.\n const queriesToStop = subtree.fold(\n (relativePath, maybeChildSyncPoint, childMap) => {\n if (\n !pathIsEmpty(relativePath) &&\n maybeChildSyncPoint &&\n syncPointHasCompleteView(maybeChildSyncPoint)\n ) {\n return [syncPointGetCompleteView(maybeChildSyncPoint).query];\n } else {\n // No default listener here, flatten any deeper queries into an array\n let queries: QueryContext[] = [];\n if (maybeChildSyncPoint) {\n queries = queries.concat(\n syncPointGetQueryViews(maybeChildSyncPoint).map(\n view => view.query\n )\n );\n }\n each(childMap, (_key: string, childQueries: QueryContext[]) => {\n queries = queries.concat(childQueries);\n });\n return queries;\n }\n }\n );\n for (let i = 0; i < queriesToStop.length; ++i) {\n const queryToStop = queriesToStop[i];\n syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(queryToStop),\n syncTreeTagForQuery(syncTree, queryToStop)\n );\n }\n }\n return events;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { PRIORITY_INDEX } from '../snap/indexes/PriorityIndex';\nimport { LeafNode } from '../snap/LeafNode';\nimport { Node } from '../snap/Node';\nimport { nodeFromJSON } from '../snap/nodeFromJSON';\nimport { SyncTree, syncTreeCalcCompleteEventCache } from '../SyncTree';\n\nimport { Indexable } from './misc';\nimport { Path, pathChild } from './Path';\n\n/* It's critical for performance that we do not calculate actual values from a SyncTree\n * unless and until the value is needed. Because we expose both a SyncTree and Node\n * version of deferred value resolution, we ned a wrapper class that will let us share\n * code.\n *\n * @see https://github.com/firebase/firebase-js-sdk/issues/2487\n */\ninterface ValueProvider {\n getImmediateChild(childName: string): ValueProvider;\n node(): Node;\n}\n\nclass ExistingValueProvider implements ValueProvider {\n constructor(readonly node_: Node) {}\n\n getImmediateChild(childName: string): ValueProvider {\n const child = this.node_.getImmediateChild(childName);\n return new ExistingValueProvider(child);\n }\n\n node(): Node {\n return this.node_;\n }\n}\n\nclass DeferredValueProvider implements ValueProvider {\n private syncTree_: SyncTree;\n private path_: Path;\n\n constructor(syncTree: SyncTree, path: Path) {\n this.syncTree_ = syncTree;\n this.path_ = path;\n }\n\n getImmediateChild(childName: string): ValueProvider {\n const childPath = pathChild(this.path_, childName);\n return new DeferredValueProvider(this.syncTree_, childPath);\n }\n\n node(): Node {\n return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);\n }\n}\n\n/**\n * Generate placeholders for deferred values.\n */\nexport const generateWithValues = function (\n values: {\n [k: string]: unknown;\n } | null\n): { [k: string]: unknown } {\n values = values || {};\n values['timestamp'] = values['timestamp'] || new Date().getTime();\n return values;\n};\n\n/**\n * Value to use when firing local events. When writing server values, fire\n * local events with an approximate value, otherwise return value as-is.\n */\nexport const resolveDeferredLeafValue = function (\n value: { [k: string]: unknown } | string | number | boolean,\n existingVal: ValueProvider,\n serverValues: { [k: string]: unknown }\n): string | number | boolean {\n if (!value || typeof value !== 'object') {\n return value as string | number | boolean;\n }\n assert('.sv' in value, 'Unexpected leaf node or priority contents');\n\n if (typeof value['.sv'] === 'string') {\n return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);\n } else if (typeof value['.sv'] === 'object') {\n return resolveComplexDeferredValue(value['.sv'], existingVal, serverValues);\n } else {\n assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));\n }\n};\n\nconst resolveScalarDeferredValue = function (\n op: string,\n existing: ValueProvider,\n serverValues: { [k: string]: unknown }\n): string | number | boolean {\n switch (op) {\n case 'timestamp':\n return serverValues['timestamp'] as string | number | boolean;\n default:\n assert(false, 'Unexpected server value: ' + op);\n }\n};\n\nconst resolveComplexDeferredValue = function (\n op: object,\n existing: ValueProvider,\n unused: { [k: string]: unknown }\n): string | number | boolean {\n if (!op.hasOwnProperty('increment')) {\n assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));\n }\n const delta = op['increment'];\n if (typeof delta !== 'number') {\n assert(false, 'Unexpected increment value: ' + delta);\n }\n\n const existingNode = existing.node();\n assert(\n existingNode !== null && typeof existingNode !== 'undefined',\n 'Expected ChildrenNode.EMPTY_NODE for nulls'\n );\n\n // Incrementing a non-number sets the value to the incremented amount\n if (!existingNode.isLeafNode()) {\n return delta;\n }\n\n const leaf = existingNode as LeafNode;\n const existingVal = leaf.getValue();\n if (typeof existingVal !== 'number') {\n return delta;\n }\n\n // No need to do over/underflow arithmetic here because JS only handles floats under the covers\n return existingVal + delta;\n};\n\n/**\n * Recursively replace all deferred values and priorities in the tree with the\n * specified generated replacement values.\n * @param path - path to which write is relative\n * @param node - new data written at path\n * @param syncTree - current data\n */\nexport const resolveDeferredValueTree = function (\n path: Path,\n node: Node,\n syncTree: SyncTree,\n serverValues: Indexable\n): Node {\n return resolveDeferredValue(\n node,\n new DeferredValueProvider(syncTree, path),\n serverValues\n );\n};\n\n/**\n * Recursively replace all deferred values and priorities in the node with the\n * specified generated replacement values. If there are no server values in the node,\n * it'll be returned as-is.\n */\nexport const resolveDeferredValueSnapshot = function (\n node: Node,\n existing: Node,\n serverValues: Indexable\n): Node {\n return resolveDeferredValue(\n node,\n new ExistingValueProvider(existing),\n serverValues\n );\n};\n\nfunction resolveDeferredValue(\n node: Node,\n existingVal: ValueProvider,\n serverValues: Indexable\n): Node {\n const rawPri = node.getPriority().val() as\n | Indexable\n | boolean\n | null\n | number\n | string;\n const priority = resolveDeferredLeafValue(\n rawPri,\n existingVal.getImmediateChild('.priority'),\n serverValues\n );\n let newNode: Node;\n\n if (node.isLeafNode()) {\n const leafNode = node as LeafNode;\n const value = resolveDeferredLeafValue(\n leafNode.getValue(),\n existingVal,\n serverValues\n );\n if (\n value !== leafNode.getValue() ||\n priority !== leafNode.getPriority().val()\n ) {\n return new LeafNode(value, nodeFromJSON(priority));\n } else {\n return node;\n }\n } else {\n const childrenNode = node as ChildrenNode;\n newNode = childrenNode;\n if (priority !== childrenNode.getPriority().val()) {\n newNode = newNode.updatePriority(new LeafNode(priority));\n }\n childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\n const newChildNode = resolveDeferredValue(\n childNode,\n existingVal.getImmediateChild(childName),\n serverValues\n );\n if (newChildNode !== childNode) {\n newNode = newNode.updateImmediateChild(childName, newChildNode);\n }\n });\n return newNode;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains, safeGet } from '@firebase/util';\n\nimport { Path, pathGetFront, pathPopFront } from './Path';\nimport { each } from './util';\n\n/**\n * Node in a Tree.\n */\nexport interface TreeNode {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n children: Record>;\n childCount: number;\n value?: T;\n}\n\n/**\n * A light-weight tree, traversable by path. Nodes can have both values and children.\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\n * children.\n */\nexport class Tree {\n /**\n * @param name - Optional name of the node.\n * @param parent - Optional parent node.\n * @param node - Optional node to wrap.\n */\n constructor(\n readonly name: string = '',\n readonly parent: Tree | null = null,\n public node: TreeNode = { children: {}, childCount: 0 }\n ) {}\n}\n\n/**\n * Returns a sub-Tree for the given path.\n *\n * @param pathObj - Path to look up.\n * @returns Tree for path.\n */\nexport function treeSubTree(tree: Tree, pathObj: string | Path): Tree {\n // TODO: Require pathObj to be Path?\n let path = pathObj instanceof Path ? pathObj : new Path(pathObj);\n let child = tree,\n next = pathGetFront(path);\n while (next !== null) {\n const childNode = safeGet(child.node.children, next) || {\n children: {},\n childCount: 0\n };\n child = new Tree(next, child, childNode);\n path = pathPopFront(path);\n next = pathGetFront(path);\n }\n\n return child;\n}\n\n/**\n * Returns the data associated with this tree node.\n *\n * @returns The data or null if no data exists.\n */\nexport function treeGetValue(tree: Tree): T | undefined {\n return tree.node.value;\n}\n\n/**\n * Sets data to this tree node.\n *\n * @param value - Value to set.\n */\nexport function treeSetValue(tree: Tree, value: T | undefined): void {\n tree.node.value = value;\n treeUpdateParents(tree);\n}\n\n/**\n * @returns Whether the tree has any children.\n */\nexport function treeHasChildren(tree: Tree): boolean {\n return tree.node.childCount > 0;\n}\n\n/**\n * @returns Whether the tree is empty (no value or children).\n */\nexport function treeIsEmpty(tree: Tree): boolean {\n return treeGetValue(tree) === undefined && !treeHasChildren(tree);\n}\n\n/**\n * Calls action for each child of this tree node.\n *\n * @param action - Action to be called for each child.\n */\nexport function treeForEachChild(\n tree: Tree,\n action: (tree: Tree) => void\n): void {\n each(tree.node.children, (child: string, childTree: TreeNode) => {\n action(new Tree(child, tree, childTree));\n });\n}\n\n/**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param action - Action to be called for each child.\n * @param includeSelf - Whether to call action on this node as well. Defaults to\n * false.\n * @param childrenFirst - Whether to call action on children before calling it on\n * parent.\n */\nexport function treeForEachDescendant(\n tree: Tree,\n action: (tree: Tree) => void,\n includeSelf?: boolean,\n childrenFirst?: boolean\n): void {\n if (includeSelf && !childrenFirst) {\n action(tree);\n }\n\n treeForEachChild(tree, child => {\n treeForEachDescendant(child, action, true, childrenFirst);\n });\n\n if (includeSelf && childrenFirst) {\n action(tree);\n }\n}\n\n/**\n * Calls action on each ancestor node.\n *\n * @param action - Action to be called on each parent; return\n * true to abort.\n * @param includeSelf - Whether to call action on this node as well.\n * @returns true if the action callback returned true.\n */\nexport function treeForEachAncestor(\n tree: Tree,\n action: (tree: Tree) => unknown,\n includeSelf?: boolean\n): boolean {\n let node = includeSelf ? tree : tree.parent;\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n node = node.parent;\n }\n return false;\n}\n\n/**\n * Does a depth-first traversal of this node's descendants. When a descendant with a value\n * is found, action is called on it and traversal does not continue inside the node.\n * Action is *not* called on this node.\n *\n * @param action - Action to be called for each child.\n */\nexport function treeForEachImmediateDescendantWithValue(\n tree: Tree,\n action: (tree: Tree) => void\n): void {\n treeForEachChild(tree, child => {\n if (treeGetValue(child) !== undefined) {\n action(child);\n } else {\n treeForEachImmediateDescendantWithValue(child, action);\n }\n });\n}\n\n/**\n * @returns The path of this tree node, as a Path.\n */\nexport function treeGetPath(tree: Tree) {\n return new Path(\n tree.parent === null\n ? tree.name\n : treeGetPath(tree.parent) + '/' + tree.name\n );\n}\n\n/**\n * Adds or removes this child from its parent based on whether it's empty or not.\n */\nfunction treeUpdateParents(tree: Tree) {\n if (tree.parent !== null) {\n treeUpdateChild(tree.parent, tree.name, tree);\n }\n}\n\n/**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param childName - The name of the child to update.\n * @param child - The child to update.\n */\nfunction treeUpdateChild(tree: Tree, childName: string, child: Tree) {\n const childEmpty = treeIsEmpty(child);\n const childExists = contains(tree.node.children, childName);\n if (childEmpty && childExists) {\n delete tree.node.children[childName];\n tree.node.childCount--;\n treeUpdateParents(tree);\n } else if (!childEmpty && !childExists) {\n tree.node.children[childName] = child.node;\n tree.node.childCount++;\n treeUpdateParents(tree);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n contains,\n errorPrefix as errorPrefixFxn,\n safeGet,\n stringLength\n} from '@firebase/util';\n\nimport { RepoInfo } from '../RepoInfo';\n\nimport {\n Path,\n pathChild,\n pathCompare,\n pathContains,\n pathGetBack,\n pathGetFront,\n pathSlice,\n ValidationPath,\n validationPathPop,\n validationPathPush,\n validationPathToErrorString\n} from './Path';\nimport { each, isInvalidJSONNumber } from './util';\n\n/**\n * True for invalid Firebase keys\n */\nexport const INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\n\n/**\n * True for invalid Firebase paths.\n * Allows '/' in paths.\n */\nexport const INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\n\n/**\n * Maximum number of characters to allow in leaf value\n */\nexport const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\n\nexport const isValidKey = function (key: unknown): boolean {\n return (\n typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key)\n );\n};\n\nexport const isValidPathString = function (pathString: string): boolean {\n return (\n typeof pathString === 'string' &&\n pathString.length !== 0 &&\n !INVALID_PATH_REGEX_.test(pathString)\n );\n};\n\nexport const isValidRootPathString = function (pathString: string): boolean {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n\n return isValidPathString(pathString);\n};\n\nexport const isValidPriority = function (priority: unknown): boolean {\n return (\n priority === null ||\n typeof priority === 'string' ||\n (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||\n (priority &&\n typeof priority === 'object' &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n contains(priority as any, '.sv'))\n );\n};\n\n/**\n * Pre-validate a datum passed as an argument to Firebase function.\n */\nexport const validateFirebaseDataArg = function (\n fnName: string,\n value: unknown,\n path: Path,\n optional: boolean\n) {\n if (optional && value === undefined) {\n return;\n }\n\n validateFirebaseData(errorPrefixFxn(fnName, 'value'), value, path);\n};\n\n/**\n * Validate a data object client-side before sending to server.\n */\nexport const validateFirebaseData = function (\n errorPrefix: string,\n data: unknown,\n path_: Path | ValidationPath\n) {\n const path =\n path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;\n\n if (data === undefined) {\n throw new Error(\n errorPrefix + 'contains undefined ' + validationPathToErrorString(path)\n );\n }\n if (typeof data === 'function') {\n throw new Error(\n errorPrefix +\n 'contains a function ' +\n validationPathToErrorString(path) +\n ' with contents = ' +\n data.toString()\n );\n }\n if (isInvalidJSONNumber(data)) {\n throw new Error(\n errorPrefix +\n 'contains ' +\n data.toString() +\n ' ' +\n validationPathToErrorString(path)\n );\n }\n\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\n if (\n typeof data === 'string' &&\n data.length > MAX_LEAF_SIZE_ / 3 &&\n stringLength(data) > MAX_LEAF_SIZE_\n ) {\n throw new Error(\n errorPrefix +\n 'contains a string greater than ' +\n MAX_LEAF_SIZE_ +\n ' utf8 bytes ' +\n validationPathToErrorString(path) +\n \" ('\" +\n data.substring(0, 50) +\n \"...')\"\n );\n }\n\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\n // to save extra walking of large objects.\n if (data && typeof data === 'object') {\n let hasDotValue = false;\n let hasActualChild = false;\n each(data, (key: string, value: unknown) => {\n if (key === '.value') {\n hasDotValue = true;\n } else if (key !== '.priority' && key !== '.sv') {\n hasActualChild = true;\n if (!isValidKey(key)) {\n throw new Error(\n errorPrefix +\n ' contains an invalid key (' +\n key +\n ') ' +\n validationPathToErrorString(path) +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"'\n );\n }\n }\n\n validationPathPush(path, key);\n validateFirebaseData(errorPrefix, value, path);\n validationPathPop(path);\n });\n\n if (hasDotValue && hasActualChild) {\n throw new Error(\n errorPrefix +\n ' contains \".value\" child ' +\n validationPathToErrorString(path) +\n ' in addition to actual children.'\n );\n }\n }\n};\n\n/**\n * Pre-validate paths passed in the firebase function.\n */\nexport const validateFirebaseMergePaths = function (\n errorPrefix: string,\n mergePaths: Path[]\n) {\n let i, curPath: Path;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n const keys = pathSlice(curPath);\n for (let j = 0; j < keys.length; j++) {\n if (keys[j] === '.priority' && j === keys.length - 1) {\n // .priority is OK\n } else if (!isValidKey(keys[j])) {\n throw new Error(\n errorPrefix +\n 'contains an invalid key (' +\n keys[j] +\n ') in path ' +\n curPath.toString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"'\n );\n }\n }\n }\n\n // Check that update keys are not descendants of each other.\n // We rely on the property that sorting guarantees that ancestors come\n // right before descendants.\n mergePaths.sort(pathCompare);\n let prevPath: Path | null = null;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n if (prevPath !== null && pathContains(prevPath, curPath)) {\n throw new Error(\n errorPrefix +\n 'contains a path ' +\n prevPath.toString() +\n ' that is ancestor of another path ' +\n curPath.toString()\n );\n }\n prevPath = curPath;\n }\n};\n\n/**\n * pre-validate an object passed as an argument to firebase function (\n * must be an object - e.g. for firebase.update()).\n */\nexport const validateFirebaseMergeDataArg = function (\n fnName: string,\n data: unknown,\n path: Path,\n optional: boolean\n) {\n if (optional && data === undefined) {\n return;\n }\n\n const errorPrefix = errorPrefixFxn(fnName, 'values');\n\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\n throw new Error(\n errorPrefix + ' must be an object containing the children to replace.'\n );\n }\n\n const mergePaths: Path[] = [];\n each(data, (key: string, value: unknown) => {\n const curPath = new Path(key);\n validateFirebaseData(errorPrefix, value, pathChild(path, curPath));\n if (pathGetBack(curPath) === '.priority') {\n if (!isValidPriority(value)) {\n throw new Error(\n errorPrefix +\n \"contains an invalid value for '\" +\n curPath.toString() +\n \"', which must be a valid \" +\n 'Firebase priority (a string, finite number, server value, or null).'\n );\n }\n }\n mergePaths.push(curPath);\n });\n validateFirebaseMergePaths(errorPrefix, mergePaths);\n};\n\nexport const validatePriority = function (\n fnName: string,\n priority: unknown,\n optional: boolean\n) {\n if (optional && priority === undefined) {\n return;\n }\n if (isInvalidJSONNumber(priority)) {\n throw new Error(\n errorPrefixFxn(fnName, 'priority') +\n 'is ' +\n priority.toString() +\n ', but must be a valid Firebase priority (a string, finite number, ' +\n 'server value, or null).'\n );\n }\n // Special case to allow importing data with a .sv.\n if (!isValidPriority(priority)) {\n throw new Error(\n errorPrefixFxn(fnName, 'priority') +\n 'must be a valid Firebase priority ' +\n '(a string, finite number, server value, or null).'\n );\n }\n};\n\nexport const validateKey = function (\n fnName: string,\n argumentName: string,\n key: string,\n optional: boolean\n) {\n if (optional && key === undefined) {\n return;\n }\n if (!isValidKey(key)) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'was an invalid key = \"' +\n key +\n '\". Firebase keys must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").'\n );\n }\n};\n\n/**\n * @internal\n */\nexport const validatePathString = function (\n fnName: string,\n argumentName: string,\n pathString: string,\n optional: boolean\n) {\n if (optional && pathString === undefined) {\n return;\n }\n\n if (!isValidPathString(pathString)) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'was an invalid path = \"' +\n pathString +\n '\". Paths must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"'\n );\n }\n};\n\nexport const validateRootPathString = function (\n fnName: string,\n argumentName: string,\n pathString: string,\n optional: boolean\n) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n\n validatePathString(fnName, argumentName, pathString, optional);\n};\n\n/**\n * @internal\n */\nexport const validateWritablePath = function (fnName: string, path: Path) {\n if (pathGetFront(path) === '.info') {\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\n }\n};\n\nexport const validateUrl = function (\n fnName: string,\n parsedUrl: { repoInfo: RepoInfo; path: Path }\n) {\n // TODO = Validate server better.\n const pathString = parsedUrl.path.toString();\n if (\n !(typeof parsedUrl.repoInfo.host === 'string') ||\n parsedUrl.repoInfo.host.length === 0 ||\n (!isValidKey(parsedUrl.repoInfo.namespace) &&\n parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||\n (pathString.length !== 0 && !isValidRootPathString(pathString))\n ) {\n throw new Error(\n errorPrefixFxn(fnName, 'url') +\n 'must be a valid firebase URL and ' +\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".'\n );\n }\n};\n\nexport const validateString = function (\n fnName: string,\n argumentName: string,\n string: unknown,\n optional: boolean\n) {\n if (optional && string === undefined) {\n return;\n }\n if (!(typeof string === 'string')) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) + 'must be a valid string.'\n );\n }\n};\n\nexport const validateObject = function (\n fnName: string,\n argumentName: string,\n obj: unknown,\n optional: boolean\n) {\n if (optional && obj === undefined) {\n return;\n }\n if (!(obj && typeof obj === 'object') || obj === null) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) + 'must be a valid object.'\n );\n }\n};\n\nexport const validateObjectContainsKey = function (\n fnName: string,\n argumentName: string,\n obj: unknown,\n key: string,\n optional: boolean,\n optType?: string\n) {\n const objectContainsKey =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj && typeof obj === 'object' && contains(obj as any, key);\n\n if (!objectContainsKey) {\n if (optional) {\n return;\n } else {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'must contain the key \"' +\n key +\n '\"'\n );\n }\n }\n\n if (optType) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const val = safeGet(obj as any, key);\n if (\n (optType === 'number' && !(typeof val === 'number')) ||\n (optType === 'string' && !(typeof val === 'string')) ||\n (optType === 'boolean' && !(typeof val === 'boolean')) ||\n (optType === 'function' && !(typeof val === 'function')) ||\n (optType === 'object' && !(typeof val === 'object') && val)\n ) {\n if (optional) {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'contains invalid value for key \"' +\n key +\n '\" (must be of type \"' +\n optType +\n '\")'\n );\n } else {\n throw new Error(\n errorPrefixFxn(fnName, argumentName) +\n 'must contain the key \"' +\n key +\n '\" with type \"' +\n optType +\n '\"'\n );\n }\n }\n }\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Path, pathContains, pathEquals } from '../util/Path';\nimport { exceptionGuard, log, logger } from '../util/util';\n\nimport { Event } from './Event';\n\n/**\n * The event queue serves a few purposes:\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\n * events being queued.\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\n * left off, ensuring that the events are still raised synchronously and in order.\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\n * events are raised synchronously.\n *\n * NOTE: This can all go away if/when we move to async events.\n *\n */\nexport class EventQueue {\n eventLists_: EventList[] = [];\n\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n */\n recursionDepth_ = 0;\n}\n\n/**\n * @param eventDataList - The new events to queue.\n */\nexport function eventQueueQueueEvents(\n eventQueue: EventQueue,\n eventDataList: Event[]\n) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n let currList: EventList | null = null;\n for (let i = 0; i < eventDataList.length; i++) {\n const data = eventDataList[i];\n const path = data.getPath();\n if (currList !== null && !pathEquals(path, currList.path)) {\n eventQueue.eventLists_.push(currList);\n currList = null;\n }\n\n if (currList === null) {\n currList = { events: [], path };\n }\n\n currList.events.push(data);\n }\n if (currList) {\n eventQueue.eventLists_.push(currList);\n }\n}\n\n/**\n * Queues the specified events and synchronously raises all events (including previously queued ones)\n * for the specified path.\n *\n * It is assumed that the new events are all for the specified path.\n *\n * @param path - The path to raise events for.\n * @param eventDataList - The new events to raise.\n */\nexport function eventQueueRaiseEventsAtPath(\n eventQueue: EventQueue,\n path: Path,\n eventDataList: Event[]\n) {\n eventQueueQueueEvents(eventQueue, eventDataList);\n eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath =>\n pathEquals(eventPath, path)\n );\n}\n\n/**\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\n * locations related to the specified change path (i.e. all ancestors and descendants).\n *\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\n *\n * @param changedPath - The path to raise events for.\n * @param eventDataList - The events to raise\n */\nexport function eventQueueRaiseEventsForChangedPath(\n eventQueue: EventQueue,\n changedPath: Path,\n eventDataList: Event[]\n) {\n eventQueueQueueEvents(eventQueue, eventDataList);\n eventQueueRaiseQueuedEventsMatchingPredicate(\n eventQueue,\n eventPath =>\n pathContains(eventPath, changedPath) ||\n pathContains(changedPath, eventPath)\n );\n}\n\nfunction eventQueueRaiseQueuedEventsMatchingPredicate(\n eventQueue: EventQueue,\n predicate: (path: Path) => boolean\n) {\n eventQueue.recursionDepth_++;\n\n let sentAll = true;\n for (let i = 0; i < eventQueue.eventLists_.length; i++) {\n const eventList = eventQueue.eventLists_[i];\n if (eventList) {\n const eventPath = eventList.path;\n if (predicate(eventPath)) {\n eventListRaise(eventQueue.eventLists_[i]);\n eventQueue.eventLists_[i] = null;\n } else {\n sentAll = false;\n }\n }\n }\n\n if (sentAll) {\n eventQueue.eventLists_ = [];\n }\n\n eventQueue.recursionDepth_--;\n}\n\ninterface EventList {\n events: Event[];\n path: Path;\n}\n\n/**\n * Iterates through the list and raises each event\n */\nfunction eventListRaise(eventList: EventList) {\n for (let i = 0; i < eventList.events.length; i++) {\n const eventData = eventList.events[i];\n if (eventData !== null) {\n eventList.events[i] = null;\n const eventFn = eventData.getEventRunner();\n if (logger) {\n log('event: ' + eventData.toString());\n }\n exceptionGuard(eventFn);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n contains,\n isEmpty,\n map,\n safeGet,\n stringify\n} from '@firebase/util';\n\nimport { ValueEventRegistration } from '../api/Reference_impl';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { PersistentConnection } from './PersistentConnection';\nimport { ReadonlyRestClient } from './ReadonlyRestClient';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { nodeFromJSON } from './snap/nodeFromJSON';\nimport { SnapshotHolder } from './SnapshotHolder';\nimport {\n newSparseSnapshotTree,\n SparseSnapshotTree,\n sparseSnapshotTreeForEachTree,\n sparseSnapshotTreeForget,\n sparseSnapshotTreeRemember\n} from './SparseSnapshotTree';\nimport { StatsCollection } from './stats/StatsCollection';\nimport { StatsListener } from './stats/StatsListener';\nimport {\n statsManagerGetCollection,\n statsManagerGetOrCreateReporter\n} from './stats/StatsManager';\nimport { StatsReporter, statsReporterIncludeStat } from './stats/StatsReporter';\nimport {\n SyncTree,\n syncTreeAckUserWrite,\n syncTreeAddEventRegistration,\n syncTreeApplyServerMerge,\n syncTreeApplyServerOverwrite,\n syncTreeApplyTaggedQueryMerge,\n syncTreeApplyTaggedQueryOverwrite,\n syncTreeApplyUserMerge,\n syncTreeApplyUserOverwrite,\n syncTreeCalcCompleteEventCache,\n syncTreeGetServerValue,\n syncTreeRemoveEventRegistration,\n syncTreeTagForQuery\n} from './SyncTree';\nimport { Indexable } from './util/misc';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathGetFront,\n pathPopFront\n} from './util/Path';\nimport {\n generateWithValues,\n resolveDeferredValueSnapshot,\n resolveDeferredValueTree\n} from './util/ServerValues';\nimport {\n Tree,\n treeForEachAncestor,\n treeForEachChild,\n treeForEachDescendant,\n treeGetPath,\n treeGetValue,\n treeHasChildren,\n treeSetValue,\n treeSubTree\n} from './util/Tree';\nimport {\n beingCrawled,\n each,\n exceptionGuard,\n log,\n LUIDGenerator,\n warn\n} from './util/util';\nimport { isValidPriority, validateFirebaseData } from './util/validation';\nimport { Event } from './view/Event';\nimport {\n EventQueue,\n eventQueueQueueEvents,\n eventQueueRaiseEventsAtPath,\n eventQueueRaiseEventsForChangedPath\n} from './view/EventQueue';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\n\nconst INTERRUPT_REASON = 'repo_interrupt';\n\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other\n * things this ensure that if there's ever a bug causing a mismatch between\n * client / server hashes for some data, we won't retry indefinitely.\n */\nconst MAX_TRANSACTION_RETRIES = 25;\n\nconst enum TransactionStatus {\n // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the\n // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to\n // mismatched hash.\n RUN,\n\n // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted\n // or rejected yet).\n SENT,\n\n // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be\n // removed when we get a chance to prune completed ones.\n COMPLETED,\n\n // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made).\n // If it comes back as unsuccessful, we'll abort it.\n SENT_NEEDS_ABORT,\n\n // Temporary state used to mark transactions that need to be aborted.\n NEEDS_ABORT\n}\n\ninterface Transaction {\n path: Path;\n update: (a: unknown) => unknown;\n onComplete: (\n error: Error | null,\n committed: boolean,\n node: Node | null\n ) => void;\n status: TransactionStatus;\n order: number;\n applyLocally: boolean;\n retryCount: number;\n unwatcher: () => void;\n abortReason: string | null;\n currentWriteId: number;\n currentInputSnapshot: Node | null;\n currentOutputSnapshotRaw: Node | null;\n currentOutputSnapshotResolved: Node | null;\n}\n\n/**\n * A connection to a single data repository.\n */\nexport class Repo {\n /** Key for uniquely identifying this repo, used in RepoManager */\n readonly key: string;\n\n dataUpdateCount = 0;\n infoSyncTree_: SyncTree;\n serverSyncTree_: SyncTree;\n\n stats_: StatsCollection;\n statsListener_: StatsListener | null = null;\n eventQueue_ = new EventQueue();\n nextWriteId_ = 1;\n server_: ServerActions;\n statsReporter_: StatsReporter;\n infoData_: SnapshotHolder;\n interceptServerDataCallback_: ((a: string, b: unknown) => void) | null = null;\n\n /** A list of data pieces and paths to be set when this client disconnects. */\n onDisconnect_: SparseSnapshotTree = newSparseSnapshotTree();\n\n /** Stores queues of outstanding transactions for Firebase locations. */\n transactionQueueTree_ = new Tree();\n\n // TODO: This should be @private but it's used by test_access.js and internal.js\n persistentConnection_: PersistentConnection | null = null;\n\n constructor(\n public repoInfo_: RepoInfo,\n public forceRestClient_: boolean,\n public authTokenProvider_: AuthTokenProvider,\n public appCheckProvider_: AppCheckTokenProvider\n ) {\n // This key is intentionally not updated if RepoInfo is later changed or replaced\n this.key = this.repoInfo_.toURLString();\n }\n\n /**\n * @returns The URL corresponding to the root of this Firebase.\n */\n toString(): string {\n return (\n (this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host\n );\n }\n}\n\nexport function repoStart(\n repo: Repo,\n appId: string,\n authOverride?: object\n): void {\n repo.stats_ = statsManagerGetCollection(repo.repoInfo_);\n\n if (repo.forceRestClient_ || beingCrawled()) {\n repo.server_ = new ReadonlyRestClient(\n repo.repoInfo_,\n (\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n ) => {\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\n },\n repo.authTokenProvider_,\n repo.appCheckProvider_\n );\n\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\n setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);\n } else {\n // Validate authOverride\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\n if (typeof authOverride !== 'object') {\n throw new Error(\n 'Only objects are supported for option databaseAuthVariableOverride'\n );\n }\n try {\n stringify(authOverride);\n } catch (e) {\n throw new Error('Invalid authOverride provided: ' + e);\n }\n }\n\n repo.persistentConnection_ = new PersistentConnection(\n repo.repoInfo_,\n appId,\n (\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n ) => {\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\n },\n (connectStatus: boolean) => {\n repoOnConnectStatus(repo, connectStatus);\n },\n (updates: object) => {\n repoOnServerInfoUpdate(repo, updates);\n },\n repo.authTokenProvider_,\n repo.appCheckProvider_,\n authOverride\n );\n\n repo.server_ = repo.persistentConnection_;\n }\n\n repo.authTokenProvider_.addTokenChangeListener(token => {\n repo.server_.refreshAuthToken(token);\n });\n\n repo.appCheckProvider_.addTokenChangeListener(result => {\n repo.server_.refreshAppCheckToken(result.token);\n });\n\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\n repo.statsReporter_ = statsManagerGetOrCreateReporter(\n repo.repoInfo_,\n () => new StatsReporter(repo.stats_, repo.server_)\n );\n\n // Used for .info.\n repo.infoData_ = new SnapshotHolder();\n repo.infoSyncTree_ = new SyncTree({\n startListening: (query, tag, currentHashFn, onComplete) => {\n let infoEvents: Event[] = [];\n const node = repo.infoData_.getNode(query._path);\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\n // on initial data...\n if (!node.isEmpty()) {\n infoEvents = syncTreeApplyServerOverwrite(\n repo.infoSyncTree_,\n query._path,\n node\n );\n setTimeout(() => {\n onComplete('ok');\n }, 0);\n }\n return infoEvents;\n },\n stopListening: () => {}\n });\n repoUpdateInfo(repo, 'connected', false);\n\n repo.serverSyncTree_ = new SyncTree({\n startListening: (query, tag, currentHashFn, onComplete) => {\n repo.server_.listen(query, currentHashFn, tag, (status, data) => {\n const events = onComplete(status, data);\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n query._path,\n events\n );\n });\n // No synchronous events for network-backed sync trees\n return [];\n },\n stopListening: (query, tag) => {\n repo.server_.unlisten(query, tag);\n }\n });\n}\n\n/**\n * @returns The time in milliseconds, taking the server offset into account if we have one.\n */\nexport function repoServerTime(repo: Repo): number {\n const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));\n const offset = (offsetNode.val() as number) || 0;\n return new Date().getTime() + offset;\n}\n\n/**\n * Generate ServerValues using some variables from the repo object.\n */\nexport function repoGenerateServerValues(repo: Repo): Indexable {\n return generateWithValues({\n timestamp: repoServerTime(repo)\n });\n}\n\n/**\n * Called by realtime when we get new messages from the server.\n */\nfunction repoOnDataUpdate(\n repo: Repo,\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n): void {\n // For testing.\n repo.dataUpdateCount++;\n const path = new Path(pathString);\n data = repo.interceptServerDataCallback_\n ? repo.interceptServerDataCallback_(pathString, data)\n : data;\n let events = [];\n if (tag) {\n if (isMerge) {\n const taggedChildren = map(\n data as { [k: string]: unknown },\n (raw: unknown) => nodeFromJSON(raw)\n );\n events = syncTreeApplyTaggedQueryMerge(\n repo.serverSyncTree_,\n path,\n taggedChildren,\n tag\n );\n } else {\n const taggedSnap = nodeFromJSON(data);\n events = syncTreeApplyTaggedQueryOverwrite(\n repo.serverSyncTree_,\n path,\n taggedSnap,\n tag\n );\n }\n } else if (isMerge) {\n const changedChildren = map(\n data as { [k: string]: unknown },\n (raw: unknown) => nodeFromJSON(raw)\n );\n events = syncTreeApplyServerMerge(\n repo.serverSyncTree_,\n path,\n changedChildren\n );\n } else {\n const snap = nodeFromJSON(data);\n events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);\n }\n let affectedPath = path;\n if (events.length > 0) {\n // Since we have a listener outstanding for each transaction, receiving any events\n // is a proxy for some change having occurred.\n affectedPath = repoRerunTransactions(repo, path);\n }\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);\n}\n\n// TODO: This should be @private but it's used by test_access.js and internal.js\nexport function repoInterceptServerData(\n repo: Repo,\n callback: ((a: string, b: unknown) => unknown) | null\n): void {\n repo.interceptServerDataCallback_ = callback;\n}\n\nfunction repoOnConnectStatus(repo: Repo, connectStatus: boolean): void {\n repoUpdateInfo(repo, 'connected', connectStatus);\n if (connectStatus === false) {\n repoRunOnDisconnectEvents(repo);\n }\n}\n\nfunction repoOnServerInfoUpdate(repo: Repo, updates: object): void {\n each(updates, (key: string, value: unknown) => {\n repoUpdateInfo(repo, key, value);\n });\n}\n\nfunction repoUpdateInfo(repo: Repo, pathString: string, value: unknown): void {\n const path = new Path('/.info/' + pathString);\n const newNode = nodeFromJSON(value);\n repo.infoData_.updateSnapshot(path, newNode);\n const events = syncTreeApplyServerOverwrite(\n repo.infoSyncTree_,\n path,\n newNode\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n}\n\nfunction repoGetNextWriteId(repo: Repo): number {\n return repo.nextWriteId_++;\n}\n\n/**\n * The purpose of `getValue` is to return the latest known value\n * satisfying `query`.\n *\n * This method will first check for in-memory cached values\n * belonging to active listeners. If they are found, such values\n * are considered to be the most up-to-date.\n *\n * If the client is not connected, this method will wait until the\n * repo has established a connection and then request the value for `query`.\n * If the client is not able to retrieve the query result for another reason,\n * it reports an error.\n *\n * @param query - The query to surface a value for.\n */\nexport function repoGetValue(\n repo: Repo,\n query: QueryContext,\n eventRegistration: ValueEventRegistration\n): Promise {\n // Only active queries are cached. There is no persisted cache.\n const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);\n if (cached != null) {\n return Promise.resolve(cached);\n }\n return repo.server_.get(query).then(\n payload => {\n const node = nodeFromJSON(payload).withIndex(\n query._queryParams.getIndex()\n );\n /**\n * Below we simulate the actions of an `onlyOnce` `onValue()` event where:\n * Add an event registration,\n * Update data at the path,\n * Raise any events,\n * Cleanup the SyncTree\n */\n syncTreeAddEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration,\n true\n );\n let events: Event[];\n if (query._queryParams.loadsAllData()) {\n events = syncTreeApplyServerOverwrite(\n repo.serverSyncTree_,\n query._path,\n node\n );\n } else {\n const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);\n events = syncTreeApplyTaggedQueryOverwrite(\n repo.serverSyncTree_,\n query._path,\n node,\n tag\n );\n }\n /*\n * We need to raise events in the scenario where `get()` is called at a parent path, and\n * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting\n * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree\n * and its corresponding serverCache, including the child location where `onValue` is called. Then,\n * `onValue` will receive the event from the server, but look at the syncTree and see that the data received\n * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.\n * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and\n * ensure the corresponding child events will get fired.\n */\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n query._path,\n events\n );\n syncTreeRemoveEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration,\n null,\n true\n );\n return node;\n },\n err => {\n repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);\n return Promise.reject(new Error(err as string));\n }\n );\n}\n\nexport function repoSetWithPriority(\n repo: Repo,\n path: Path,\n newVal: unknown,\n newPriority: number | string | null,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repoLog(repo, 'set', {\n path: path.toString(),\n value: newVal,\n priority: newPriority\n });\n\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\n // (b) store unresolved paths on JSON parse\n const serverValues = repoGenerateServerValues(repo);\n const newNodeUnresolved = nodeFromJSON(newVal, newPriority);\n const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);\n const newNode = resolveDeferredValueSnapshot(\n newNodeUnresolved,\n existing,\n serverValues\n );\n\n const writeId = repoGetNextWriteId(repo);\n const events = syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n path,\n newNode,\n writeId,\n true\n );\n eventQueueQueueEvents(repo.eventQueue_, events);\n repo.server_.put(\n path.toString(),\n newNodeUnresolved.val(/*export=*/ true),\n (status, errorReason) => {\n const success = status === 'ok';\n if (!success) {\n warn('set at ' + path + ' failed: ' + status);\n }\n\n const clearEvents = syncTreeAckUserWrite(\n repo.serverSyncTree_,\n writeId,\n !success\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n const affectedPath = repoAbortTransactions(repo, path);\n repoRerunTransactions(repo, affectedPath);\n // We queued the events above, so just flush the queue here\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);\n}\n\nexport function repoUpdate(\n repo: Repo,\n path: Path,\n childrenToMerge: { [k: string]: unknown },\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });\n\n // Start with our existing data and merge each child into it.\n let empty = true;\n const serverValues = repoGenerateServerValues(repo);\n const changedChildren: { [k: string]: Node } = {};\n each(childrenToMerge, (changedKey: string, changedValue: unknown) => {\n empty = false;\n changedChildren[changedKey] = resolveDeferredValueTree(\n pathChild(path, changedKey),\n nodeFromJSON(changedValue),\n repo.serverSyncTree_,\n serverValues\n );\n });\n\n if (!empty) {\n const writeId = repoGetNextWriteId(repo);\n const events = syncTreeApplyUserMerge(\n repo.serverSyncTree_,\n path,\n changedChildren,\n writeId\n );\n eventQueueQueueEvents(repo.eventQueue_, events);\n repo.server_.merge(\n path.toString(),\n childrenToMerge,\n (status, errorReason) => {\n const success = status === 'ok';\n if (!success) {\n warn('update at ' + path + ' failed: ' + status);\n }\n\n const clearEvents = syncTreeAckUserWrite(\n repo.serverSyncTree_,\n writeId,\n !success\n );\n const affectedPath =\n clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n affectedPath,\n clearEvents\n );\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n\n each(childrenToMerge, (changedPath: string) => {\n const affectedPath = repoAbortTransactions(\n repo,\n pathChild(path, changedPath)\n );\n repoRerunTransactions(repo, affectedPath);\n });\n\n // We queued the events above, so just flush the queue here\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);\n } else {\n log(\"update() called with empty data. Don't do anything.\");\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\n }\n}\n\n/**\n * Applies all of the changes stored up in the onDisconnect_ tree.\n */\nfunction repoRunOnDisconnectEvents(repo: Repo): void {\n repoLog(repo, 'onDisconnectEvents');\n\n const serverValues = repoGenerateServerValues(repo);\n const resolvedOnDisconnectTree = newSparseSnapshotTree();\n sparseSnapshotTreeForEachTree(\n repo.onDisconnect_,\n newEmptyPath(),\n (path, node) => {\n const resolved = resolveDeferredValueTree(\n path,\n node,\n repo.serverSyncTree_,\n serverValues\n );\n sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);\n }\n );\n let events: Event[] = [];\n\n sparseSnapshotTreeForEachTree(\n resolvedOnDisconnectTree,\n newEmptyPath(),\n (path, snap) => {\n events = events.concat(\n syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap)\n );\n const affectedPath = repoAbortTransactions(repo, path);\n repoRerunTransactions(repo, affectedPath);\n }\n );\n\n repo.onDisconnect_ = newSparseSnapshotTree();\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);\n}\n\nexport function repoOnDisconnectCancel(\n repo: Repo,\n path: Path,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeForget(repo.onDisconnect_, path);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n });\n}\n\nexport function repoOnDisconnectSet(\n repo: Repo,\n path: Path,\n value: unknown,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n const newNode = nodeFromJSON(value);\n repo.server_.onDisconnectPut(\n path.toString(),\n newNode.val(/*export=*/ true),\n (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoOnDisconnectSetWithPriority(\n repo: Repo,\n path: Path,\n value: unknown,\n priority: unknown,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n const newNode = nodeFromJSON(value, priority);\n repo.server_.onDisconnectPut(\n path.toString(),\n newNode.val(/*export=*/ true),\n (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoOnDisconnectUpdate(\n repo: Repo,\n path: Path,\n childrenToMerge: { [k: string]: unknown },\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n if (isEmpty(childrenToMerge)) {\n log(\"onDisconnect().update() called with empty data. Don't do anything.\");\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\n return;\n }\n\n repo.server_.onDisconnectMerge(\n path.toString(),\n childrenToMerge,\n (status, errorReason) => {\n if (status === 'ok') {\n each(childrenToMerge, (childName: string, childNode: unknown) => {\n const newChildNode = nodeFromJSON(childNode);\n sparseSnapshotTreeRemember(\n repo.onDisconnect_,\n pathChild(path, childName),\n newChildNode\n );\n });\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoAddEventCallbackForQuery(\n repo: Repo,\n query: QueryContext,\n eventRegistration: EventRegistration\n): void {\n let events;\n if (pathGetFront(query._path) === '.info') {\n events = syncTreeAddEventRegistration(\n repo.infoSyncTree_,\n query,\n eventRegistration\n );\n } else {\n events = syncTreeAddEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration\n );\n }\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\n}\n\nexport function repoRemoveEventCallbackForQuery(\n repo: Repo,\n query: QueryContext,\n eventRegistration: EventRegistration\n): void {\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\n // a little bit by handling the return values anyways.\n let events;\n if (pathGetFront(query._path) === '.info') {\n events = syncTreeRemoveEventRegistration(\n repo.infoSyncTree_,\n query,\n eventRegistration\n );\n } else {\n events = syncTreeRemoveEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration\n );\n }\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\n}\n\nexport function repoInterrupt(repo: Repo): void {\n if (repo.persistentConnection_) {\n repo.persistentConnection_.interrupt(INTERRUPT_REASON);\n }\n}\n\nexport function repoResume(repo: Repo): void {\n if (repo.persistentConnection_) {\n repo.persistentConnection_.resume(INTERRUPT_REASON);\n }\n}\n\nexport function repoStats(repo: Repo, showDelta: boolean = false): void {\n if (typeof console === 'undefined') {\n return;\n }\n\n let stats: { [k: string]: unknown };\n if (showDelta) {\n if (!repo.statsListener_) {\n repo.statsListener_ = new StatsListener(repo.stats_);\n }\n stats = repo.statsListener_.get();\n } else {\n stats = repo.stats_.get();\n }\n\n const longestName = Object.keys(stats).reduce(\n (previousValue, currentValue) =>\n Math.max(currentValue.length, previousValue),\n 0\n );\n\n each(stats, (stat: string, value: unknown) => {\n let paddedStat = stat;\n // pad stat names to be the same length (plus 2 extra spaces).\n for (let i = stat.length; i < longestName + 2; i++) {\n paddedStat += ' ';\n }\n console.log(paddedStat + value);\n });\n}\n\nexport function repoStatsIncrementCounter(repo: Repo, metric: string): void {\n repo.stats_.incrementCounter(metric);\n statsReporterIncludeStat(repo.statsReporter_, metric);\n}\n\nfunction repoLog(repo: Repo, ...varArgs: unknown[]): void {\n let prefix = '';\n if (repo.persistentConnection_) {\n prefix = repo.persistentConnection_.id + ':';\n }\n log(prefix, ...varArgs);\n}\n\nexport function repoCallOnCompleteCallback(\n repo: Repo,\n callback: ((status: Error | null, errorReason?: string) => void) | null,\n status: string,\n errorReason?: string | null\n): void {\n if (callback) {\n exceptionGuard(() => {\n if (status === 'ok') {\n callback(null);\n } else {\n const code = (status || 'error').toUpperCase();\n let message = code;\n if (errorReason) {\n message += ': ' + errorReason;\n }\n\n const error = new Error(message);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (error as any).code = code;\n callback(error);\n }\n });\n }\n}\n\n/**\n * Creates a new transaction, adds it to the transactions we're tracking, and\n * sends it to the server if possible.\n *\n * @param path - Path at which to do transaction.\n * @param transactionUpdate - Update callback.\n * @param onComplete - Completion callback.\n * @param unwatcher - Function that will be called when the transaction no longer\n * need data updates for `path`.\n * @param applyLocally - Whether or not to make intermediate results visible\n */\nexport function repoStartTransaction(\n repo: Repo,\n path: Path,\n transactionUpdate: (a: unknown) => unknown,\n onComplete: ((error: Error, committed: boolean, node: Node) => void) | null,\n unwatcher: () => void,\n applyLocally: boolean\n): void {\n repoLog(repo, 'transaction on ' + path);\n\n // Initialize transaction.\n const transaction: Transaction = {\n path,\n update: transactionUpdate,\n onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out\n // which one goes first.\n order: LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n };\n\n // Run transaction initially.\n const currentState = repoGetLatestState(repo, path, undefined);\n transaction.currentInputSnapshot = currentState;\n const newVal = transaction.update(currentState.val());\n if (newVal === undefined) {\n // Abort transaction.\n transaction.unwatcher();\n transaction.currentOutputSnapshotRaw = null;\n transaction.currentOutputSnapshotResolved = null;\n if (transaction.onComplete) {\n transaction.onComplete(null, false, transaction.currentInputSnapshot);\n }\n } else {\n validateFirebaseData(\n 'transaction failed: Data returned ',\n newVal,\n transaction.path\n );\n\n // Mark as run and add to our queue.\n transaction.status = TransactionStatus.RUN;\n const queueNode = treeSubTree(repo.transactionQueueTree_, path);\n const nodeQueue = treeGetValue(queueNode) || [];\n nodeQueue.push(transaction);\n\n treeSetValue(queueNode, nodeQueue);\n\n // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our\n // transaction state, since the user could start new transactions from the\n // event callbacks.\n let priorityForNode;\n if (\n typeof newVal === 'object' &&\n newVal !== null &&\n contains(newVal, '.priority')\n ) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n priorityForNode = safeGet(newVal as any, '.priority');\n assert(\n isValidPriority(priorityForNode),\n 'Invalid priority returned by transaction. ' +\n 'Priority must be a valid string, finite number, server value, or null.'\n );\n } else {\n const currentNode =\n syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||\n ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n\n const serverValues = repoGenerateServerValues(repo);\n const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);\n const newNode = resolveDeferredValueSnapshot(\n newNodeUnresolved,\n currentState,\n serverValues\n );\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = repoGetNextWriteId(repo);\n\n const events = syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n path,\n newNode,\n transaction.currentWriteId,\n transaction.applyLocally\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n }\n}\n\n/**\n * @param excludeSets - A specific set to exclude\n */\nfunction repoGetLatestState(\n repo: Repo,\n path: Path,\n excludeSets?: number[]\n): Node {\n return (\n syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||\n ChildrenNode.EMPTY_NODE\n );\n}\n\n/**\n * Sends any already-run transactions that aren't waiting for outstanding\n * transactions to complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively\n * with a particular transactionQueueTree node to recurse through the tree.\n *\n * @param node - transactionQueueTree node to start at.\n */\nfunction repoSendReadyTransactions(\n repo: Repo,\n node: Tree = repo.transactionQueueTree_\n): void {\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n repoPruneCompletedTransactionsBelowNode(repo, node);\n }\n\n if (treeGetValue(node)) {\n const queue = repoBuildTransactionQueue(repo, node);\n assert(queue.length > 0, 'Sending zero length transaction queue');\n\n const allRun = queue.every(\n (transaction: Transaction) => transaction.status === TransactionStatus.RUN\n );\n\n // If they're all run (and not sent), we can send them. Else, we must wait.\n if (allRun) {\n repoSendTransactionQueue(repo, treeGetPath(node), queue);\n }\n } else if (treeHasChildren(node)) {\n treeForEachChild(node, childNode => {\n repoSendReadyTransactions(repo, childNode);\n });\n }\n}\n\n/**\n * Given a list of run transactions, send them to the server and then handle\n * the result (success or failure).\n *\n * @param path - The location of the queue.\n * @param queue - Queue of transactions under the specified location.\n */\nfunction repoSendTransactionQueue(\n repo: Repo,\n path: Path,\n queue: Transaction[]\n): void {\n // Mark transactions as sent and increment retry count!\n const setsToIgnore = queue.map(txn => {\n return txn.currentWriteId;\n });\n const latestState = repoGetLatestState(repo, path, setsToIgnore);\n let snapToSend = latestState;\n const latestHash = latestState.hash();\n for (let i = 0; i < queue.length; i++) {\n const txn = queue[i];\n assert(\n txn.status === TransactionStatus.RUN,\n 'tryToSendTransactionQueue_: items in queue should all be run.'\n );\n txn.status = TransactionStatus.SENT;\n txn.retryCount++;\n const relativePath = newRelativePath(path, txn.path);\n // If we've gotten to this point, the output snapshot must be defined.\n snapToSend = snapToSend.updateChild(\n relativePath /** @type {!Node} */,\n txn.currentOutputSnapshotRaw\n );\n }\n\n const dataToSend = snapToSend.val(true);\n const pathToSend = path;\n\n // Send the put.\n repo.server_.put(\n pathToSend.toString(),\n dataToSend,\n (status: string) => {\n repoLog(repo, 'transaction put response', {\n path: pathToSend.toString(),\n status\n });\n\n let events: Event[] = [];\n if (status === 'ok') {\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more\n // transactions or sets.\n const callbacks = [];\n for (let i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.COMPLETED;\n events = events.concat(\n syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId)\n );\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this\n // transaction is complete, it should be set\n callbacks.push(() =>\n queue[i].onComplete(\n null,\n true,\n queue[i].currentOutputSnapshotResolved\n )\n );\n }\n queue[i].unwatcher();\n }\n\n // Now remove the completed transactions.\n repoPruneCompletedTransactionsBelowNode(\n repo,\n treeSubTree(repo.transactionQueueTree_, path)\n );\n // There may be pending transactions that we can now send.\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n\n // Finally, trigger onComplete callbacks.\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n } else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (let i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n } else {\n queue[i].status = TransactionStatus.RUN;\n }\n }\n } else {\n warn(\n 'transaction at ' + pathToSend.toString() + ' failed: ' + status\n );\n for (let i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n queue[i].abortReason = status;\n }\n }\n\n repoRerunTransactions(repo, path);\n }\n },\n latestHash\n );\n}\n\n/**\n * Finds all transactions dependent on the data at changedPath and reruns them.\n *\n * Should be called any time cached data changes.\n *\n * Return the highest path that was affected by rerunning transactions. This\n * is the path at which events need to be raised for.\n *\n * @param changedPath - The path in mergedData that changed.\n * @returns The rootmost path that was affected by rerunning transactions.\n */\nfunction repoRerunTransactions(repo: Repo, changedPath: Path): Path {\n const rootMostTransactionNode = repoGetAncestorTransactionNode(\n repo,\n changedPath\n );\n const path = treeGetPath(rootMostTransactionNode);\n\n const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);\n repoRerunTransactionQueue(repo, queue, path);\n\n return path;\n}\n\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted\n * transactions and whatnot).\n *\n * @param queue - The queue of transactions to run.\n * @param path - The path the queue is for.\n */\nfunction repoRerunTransactionQueue(\n repo: Repo,\n queue: Transaction[],\n path: Path\n): void {\n if (queue.length === 0) {\n return; // Nothing to do!\n }\n\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more transactions or\n // sets.\n const callbacks = [];\n let events: Event[] = [];\n // Ignore all of the sets we're going to re-run.\n const txnsToRerun = queue.filter(q => {\n return q.status === TransactionStatus.RUN;\n });\n const setsToIgnore = txnsToRerun.map(q => {\n return q.currentWriteId;\n });\n for (let i = 0; i < queue.length; i++) {\n const transaction = queue[i];\n const relativePath = newRelativePath(path, transaction.path);\n let abortTransaction = false,\n abortReason;\n assert(\n relativePath !== null,\n 'rerunTransactionsUnderNode_: relativePath should not be null.'\n );\n\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n } else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n } else {\n // This code reruns a transaction\n const currentNode = repoGetLatestState(\n repo,\n transaction.path,\n setsToIgnore\n );\n transaction.currentInputSnapshot = currentNode;\n const newData = queue[i].update(currentNode.val());\n if (newData !== undefined) {\n validateFirebaseData(\n 'transaction failed: Data returned ',\n newData,\n transaction.path\n );\n let newDataNode = nodeFromJSON(newData);\n const hasExplicitPriority =\n typeof newData === 'object' &&\n newData != null &&\n contains(newData, '.priority');\n if (!hasExplicitPriority) {\n // Keep the old priority if there wasn't a priority explicitly specified.\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n }\n\n const oldWriteId = transaction.currentWriteId;\n const serverValues = repoGenerateServerValues(repo);\n const newNodeResolved = resolveDeferredValueSnapshot(\n newDataNode,\n currentNode,\n serverValues\n );\n\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = repoGetNextWriteId(repo);\n // Mutates setsToIgnore in place\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(\n syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n transaction.path,\n newNodeResolved,\n transaction.currentWriteId,\n transaction.applyLocally\n )\n );\n events = events.concat(\n syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true)\n );\n } else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n }\n }\n }\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n events = [];\n if (abortTransaction) {\n // Abort.\n queue[i].status = TransactionStatus.COMPLETED;\n\n // Removing a listener can trigger pruning which can muck with\n // mergedData/visibleData (as it prunes data). So defer the unwatcher\n // until we're done.\n (function (unwatcher) {\n setTimeout(unwatcher, Math.floor(0));\n })(queue[i].unwatcher);\n\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n callbacks.push(() =>\n queue[i].onComplete(null, false, queue[i].currentInputSnapshot)\n );\n } else {\n callbacks.push(() =>\n queue[i].onComplete(new Error(abortReason), false, null)\n );\n }\n }\n }\n }\n\n // Clean up completed transactions.\n repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);\n\n // Now fire callbacks, now that we're in a good, known state.\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n\n // Try to send the transaction result to the server.\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n}\n\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending\n * transaction on it, or just returns the node for the given path if there are\n * no pending transactions on any ancestor.\n *\n * @param path - The location to start at.\n * @returns The rootmost node with a transaction.\n */\nfunction repoGetAncestorTransactionNode(\n repo: Repo,\n path: Path\n): Tree {\n let front;\n\n // Start at the root and walk deeper into the tree towards path until we\n // find a node with pending transactions.\n let transactionNode = repo.transactionQueueTree_;\n front = pathGetFront(path);\n while (front !== null && treeGetValue(transactionNode) === undefined) {\n transactionNode = treeSubTree(transactionNode, front);\n path = pathPopFront(path);\n front = pathGetFront(path);\n }\n\n return transactionNode;\n}\n\n/**\n * Builds the queue of all transactions at or below the specified\n * transactionNode.\n *\n * @param transactionNode\n * @returns The generated queue.\n */\nfunction repoBuildTransactionQueue(\n repo: Repo,\n transactionNode: Tree\n): Transaction[] {\n // Walk any child transaction queues and aggregate them into a single queue.\n const transactionQueue: Transaction[] = [];\n repoAggregateTransactionQueuesForNode(\n repo,\n transactionNode,\n transactionQueue\n );\n\n // Sort them by the order the transactions were created.\n transactionQueue.sort((a, b) => a.order - b.order);\n\n return transactionQueue;\n}\n\nfunction repoAggregateTransactionQueuesForNode(\n repo: Repo,\n node: Tree,\n queue: Transaction[]\n): void {\n const nodeQueue = treeGetValue(node);\n if (nodeQueue) {\n for (let i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n\n treeForEachChild(node, child => {\n repoAggregateTransactionQueuesForNode(repo, child, queue);\n });\n}\n\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n */\nfunction repoPruneCompletedTransactionsBelowNode(\n repo: Repo,\n node: Tree\n): void {\n const queue = treeGetValue(node);\n if (queue) {\n let to = 0;\n for (let from = 0; from < queue.length; from++) {\n if (queue[from].status !== TransactionStatus.COMPLETED) {\n queue[to] = queue[from];\n to++;\n }\n }\n queue.length = to;\n treeSetValue(node, queue.length > 0 ? queue : undefined);\n }\n\n treeForEachChild(node, childNode => {\n repoPruneCompletedTransactionsBelowNode(repo, childNode);\n });\n}\n\n/**\n * Aborts all transactions on ancestors or descendants of the specified path.\n * Called when doing a set() or update() since we consider them incompatible\n * with transactions.\n *\n * @param path - Path for which we want to abort related transactions.\n */\nfunction repoAbortTransactions(repo: Repo, path: Path): Path {\n const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));\n\n const transactionNode = treeSubTree(repo.transactionQueueTree_, path);\n\n treeForEachAncestor(transactionNode, (node: Tree) => {\n repoAbortTransactionsOnNode(repo, node);\n });\n\n repoAbortTransactionsOnNode(repo, transactionNode);\n\n treeForEachDescendant(transactionNode, (node: Tree) => {\n repoAbortTransactionsOnNode(repo, node);\n });\n\n return affectedPath;\n}\n\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param node - Node to abort transactions for.\n */\nfunction repoAbortTransactionsOnNode(\n repo: Repo,\n node: Tree\n): void {\n const queue = treeGetValue(node);\n if (queue) {\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more transactions\n // or sets.\n const callbacks = [];\n\n // Go through queue. Any already-sent transactions must be marked for\n // abort, while the unsent ones can be immediately aborted and removed.\n let events: Event[] = [];\n let lastSent = -1;\n for (let i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n // Already marked. No action needed.\n } else if (queue[i].status === TransactionStatus.SENT) {\n assert(\n lastSent === i - 1,\n 'All SENT items should be at beginning of queue.'\n );\n lastSent = i;\n // Mark transaction for abort when it comes back.\n queue[i].status = TransactionStatus.SENT_NEEDS_ABORT;\n queue[i].abortReason = 'set';\n } else {\n assert(\n queue[i].status === TransactionStatus.RUN,\n 'Unexpected transaction status in abort'\n );\n // We can abort it immediately.\n queue[i].unwatcher();\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n queue[i].currentWriteId,\n true\n )\n );\n if (queue[i].onComplete) {\n callbacks.push(\n queue[i].onComplete.bind(null, new Error('set'), false, null)\n );\n }\n }\n }\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n treeSetValue(node, undefined);\n } else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n\n // Now fire the callbacks.\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n treeGetPath(node),\n events\n );\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../../RepoInfo';\nimport { Path } from '../Path';\nimport { warnIfPageIsSecure, warn, fatal } from '../util';\n\nfunction decodePath(pathString: string): string {\n let pathStringDecoded = '';\n const pieces = pathString.split('/');\n for (let i = 0; i < pieces.length; i++) {\n if (pieces[i].length > 0) {\n let piece = pieces[i];\n try {\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\n } catch (e) {}\n pathStringDecoded += '/' + piece;\n }\n }\n return pathStringDecoded;\n}\n\n/**\n * @returns key value hash\n */\nfunction decodeQuery(queryString: string): { [key: string]: string } {\n const results = {};\n if (queryString.charAt(0) === '?') {\n queryString = queryString.substring(1);\n }\n for (const segment of queryString.split('&')) {\n if (segment.length === 0) {\n continue;\n }\n const kv = segment.split('=');\n if (kv.length === 2) {\n results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\n } else {\n warn(`Invalid query segment '${segment}' in query '${queryString}'`);\n }\n }\n return results;\n}\n\nexport const parseRepoInfo = function (\n dataURL: string,\n nodeAdmin: boolean\n): { repoInfo: RepoInfo; path: Path } {\n const parsedUrl = parseDatabaseURL(dataURL),\n namespace = parsedUrl.namespace;\n\n if (parsedUrl.domain === 'firebase.com') {\n fatal(\n parsedUrl.host +\n ' is no longer supported. ' +\n 'Please use .firebaseio.com instead'\n );\n }\n\n // Catch common error of uninitialized namespace value.\n if (\n (!namespace || namespace === 'undefined') &&\n parsedUrl.domain !== 'localhost'\n ) {\n fatal(\n 'Cannot parse Firebase url. Please use https://.firebaseio.com'\n );\n }\n\n if (!parsedUrl.secure) {\n warnIfPageIsSecure();\n }\n\n const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\n\n return {\n repoInfo: new RepoInfo(\n parsedUrl.host,\n parsedUrl.secure,\n namespace,\n webSocketOnly,\n nodeAdmin,\n /*persistenceKey=*/ '',\n /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain\n ),\n path: new Path(parsedUrl.pathString)\n };\n};\n\nexport const parseDatabaseURL = function (dataURL: string): {\n host: string;\n port: number;\n domain: string;\n subdomain: string;\n secure: boolean;\n scheme: string;\n pathString: string;\n namespace: string;\n} {\n // Default to empty strings in the event of a malformed string.\n let host = '',\n domain = '',\n subdomain = '',\n pathString = '',\n namespace = '';\n\n // Always default to SSL, unless otherwise specified.\n let secure = true,\n scheme = 'https',\n port = 443;\n\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\n if (typeof dataURL === 'string') {\n // Parse scheme.\n let colonInd = dataURL.indexOf('//');\n if (colonInd >= 0) {\n scheme = dataURL.substring(0, colonInd - 1);\n dataURL = dataURL.substring(colonInd + 2);\n }\n\n // Parse host, path, and query string.\n let slashInd = dataURL.indexOf('/');\n if (slashInd === -1) {\n slashInd = dataURL.length;\n }\n let questionMarkInd = dataURL.indexOf('?');\n if (questionMarkInd === -1) {\n questionMarkInd = dataURL.length;\n }\n host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));\n if (slashInd < questionMarkInd) {\n // For pathString, questionMarkInd will always come after slashInd\n pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));\n }\n const queryParams = decodeQuery(\n dataURL.substring(Math.min(dataURL.length, questionMarkInd))\n );\n\n // If we have a port, use scheme for determining if it's secure.\n colonInd = host.indexOf(':');\n if (colonInd >= 0) {\n secure = scheme === 'https' || scheme === 'wss';\n port = parseInt(host.substring(colonInd + 1), 10);\n } else {\n colonInd = host.length;\n }\n\n const hostWithoutPort = host.slice(0, colonInd);\n if (hostWithoutPort.toLowerCase() === 'localhost') {\n domain = 'localhost';\n } else if (hostWithoutPort.split('.').length <= 2) {\n domain = hostWithoutPort;\n } else {\n // Interpret the subdomain of a 3 or more component URL as the namespace name.\n const dotInd = host.indexOf('.');\n subdomain = host.substring(0, dotInd).toLowerCase();\n domain = host.substring(dotInd + 1);\n // Normalize namespaces to lowercase to share storage / connection.\n namespace = subdomain;\n }\n // Always treat the value of the `ns` as the namespace name if it is present.\n if ('ns' in queryParams) {\n namespace = queryParams['ns'];\n }\n }\n\n return {\n host,\n port,\n domain,\n subdomain,\n secure,\n scheme,\n pathString,\n namespace\n };\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport {\n tryParseInt,\n MAX_NAME,\n MIN_NAME,\n INTEGER_32_MIN,\n INTEGER_32_MAX\n} from '../util/util';\n\n// Modeled after base64 web-safe chars, but ordered by ASCII.\nconst PUSH_CHARS =\n '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n\nconst MIN_PUSH_CHAR = '-';\n\nconst MAX_PUSH_CHAR = 'z';\n\nconst MAX_KEY_LEN = 786;\n\n/**\n * Fancy ID generator that creates 20-character string identifiers with the\n * following properties:\n *\n * 1. They're based on timestamp so that they sort *after* any existing ids.\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\n * collide with other clients' IDs.\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\n * that will sort properly).\n * 4. They're monotonically increasing. Even if you generate more than one in\n * the same timestamp, the latter ones will sort after the former ones. We do\n * this by using the previous random bits but \"incrementing\" them by 1 (only\n * in the case of a timestamp collision).\n */\nexport const nextPushId = (function () {\n // Timestamp of last push, used to prevent local collisions if you push twice\n // in one ms.\n let lastPushTime = 0;\n\n // We generate 72-bits of randomness which get turned into 12 characters and\n // appended to the timestamp to prevent collisions with other clients. We\n // store the last characters we generated because in the event of a collision,\n // we'll use those same characters except \"incremented\" by one.\n const lastRandChars: number[] = [];\n\n return function (now: number) {\n const duplicateTime = now === lastPushTime;\n lastPushTime = now;\n\n let i;\n const timeStampChars = new Array(8);\n for (i = 7; i >= 0; i--) {\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\n // NOTE: Can't use << here because javascript will convert to int and lose\n // the upper bits.\n now = Math.floor(now / 64);\n }\n assert(now === 0, 'Cannot push at time == 0');\n\n let id = timeStampChars.join('');\n\n if (!duplicateTime) {\n for (i = 0; i < 12; i++) {\n lastRandChars[i] = Math.floor(Math.random() * 64);\n }\n } else {\n // If the timestamp hasn't changed since last push, use the same random\n // number, except incremented by 1.\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\n lastRandChars[i] = 0;\n }\n lastRandChars[i]++;\n }\n for (i = 0; i < 12; i++) {\n id += PUSH_CHARS.charAt(lastRandChars[i]);\n }\n assert(id.length === 20, 'nextPushId: Length should be 20.');\n\n return id;\n };\n})();\n\nexport const successor = function (key: string) {\n if (key === '' + INTEGER_32_MAX) {\n // See https://firebase.google.com/docs/database/web/lists-of-data#data-order\n return MIN_PUSH_CHAR;\n }\n const keyAsInt: number = tryParseInt(key);\n if (keyAsInt != null) {\n return '' + (keyAsInt + 1);\n }\n const next = new Array(key.length);\n\n for (let i = 0; i < next.length; i++) {\n next[i] = key.charAt(i);\n }\n\n if (next.length < MAX_KEY_LEN) {\n next.push(MIN_PUSH_CHAR);\n return next.join('');\n }\n\n let i = next.length - 1;\n\n while (i >= 0 && next[i] === MAX_PUSH_CHAR) {\n i--;\n }\n\n // `successor` was called on the largest possible key, so return the\n // MAX_NAME, which sorts larger than all keys.\n if (i === -1) {\n return MAX_NAME;\n }\n\n const source = next[i];\n const sourcePlusOne = PUSH_CHARS.charAt(PUSH_CHARS.indexOf(source) + 1);\n next[i] = sourcePlusOne;\n\n return next.slice(0, i + 1).join('');\n};\n\n// `key` is assumed to be non-empty.\nexport const predecessor = function (key: string) {\n if (key === '' + INTEGER_32_MIN) {\n return MIN_NAME;\n }\n const keyAsInt: number = tryParseInt(key);\n if (keyAsInt != null) {\n return '' + (keyAsInt - 1);\n }\n const next = new Array(key.length);\n for (let i = 0; i < next.length; i++) {\n next[i] = key.charAt(i);\n }\n // If `key` ends in `MIN_PUSH_CHAR`, the largest key lexicographically\n // smaller than `key`, is `key[0:key.length - 1]`. The next key smaller\n // than that, `predecessor(predecessor(key))`, is\n //\n // `key[0:key.length - 2] + (key[key.length - 1] - 1) + \\\n // { MAX_PUSH_CHAR repeated MAX_KEY_LEN - (key.length - 1) times }\n //\n // analogous to increment/decrement for base-10 integers.\n //\n // This works because lexicographic comparison works character-by-character,\n // using length as a tie-breaker if one key is a prefix of the other.\n if (next[next.length - 1] === MIN_PUSH_CHAR) {\n if (next.length === 1) {\n // See https://firebase.google.com/docs/database/web/lists-of-data#orderbykey\n return '' + INTEGER_32_MAX;\n }\n delete next[next.length - 1];\n return next.join('');\n }\n // Replace the last character with it's immediate predecessor, and\n // fill the suffix of the key with MAX_PUSH_CHAR. This is the\n // lexicographically largest possible key smaller than `key`.\n next[next.length - 1] = PUSH_CHARS.charAt(\n PUSH_CHARS.indexOf(next[next.length - 1]) - 1\n );\n return next.join('') + MAX_PUSH_CHAR.repeat(MAX_KEY_LEN - next.length);\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { stringify } from '@firebase/util';\n\nimport { DataSnapshot as ExpDataSnapshot } from '../../api/Reference_impl';\nimport { Path } from '../util/Path';\n\nimport { EventRegistration } from './EventRegistration';\n\n/**\n * Encapsulates the data needed to raise an event\n * @interface\n */\nexport interface Event {\n getPath(): Path;\n\n getEventType(): string;\n\n getEventRunner(): () => void;\n\n toString(): string;\n}\n\n/**\n * One of the following strings: \"value\", \"child_added\", \"child_changed\",\n * \"child_removed\", or \"child_moved.\"\n */\nexport type EventType =\n | 'value'\n | 'child_added'\n | 'child_changed'\n | 'child_moved'\n | 'child_removed';\n\n/**\n * Encapsulates the data needed to raise an event\n */\nexport class DataEvent implements Event {\n /**\n * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed\n * @param eventRegistration - The function to call to with the event data. User provided\n * @param snapshot - The data backing the event\n * @param prevName - Optional, the name of the previous child for child_* events.\n */\n constructor(\n public eventType: EventType,\n public eventRegistration: EventRegistration,\n public snapshot: ExpDataSnapshot,\n public prevName?: string | null\n ) {}\n getPath(): Path {\n const ref = this.snapshot.ref;\n if (this.eventType === 'value') {\n return ref._path;\n } else {\n return ref.parent._path;\n }\n }\n getEventType(): string {\n return this.eventType;\n }\n getEventRunner(): () => void {\n return this.eventRegistration.getEventRunner(this);\n }\n toString(): string {\n return (\n this.getPath().toString() +\n ':' +\n this.eventType +\n ':' +\n stringify(this.snapshot.exportVal())\n );\n }\n}\n\nexport class CancelEvent implements Event {\n constructor(\n public eventRegistration: EventRegistration,\n public error: Error,\n public path: Path\n ) {}\n getPath(): Path {\n return this.path;\n }\n getEventType(): string {\n return 'cancel';\n }\n getEventRunner(): () => void {\n return this.eventRegistration.getEventRunner(this);\n }\n toString(): string {\n return this.path.toString() + ':cancel';\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { DataSnapshot } from '../../api/Reference_impl';\nimport { Repo } from '../Repo';\nimport { Path } from '../util/Path';\n\nimport { Change } from './Change';\nimport { CancelEvent, Event } from './Event';\nimport { QueryParams } from './QueryParams';\n\n/**\n * A user callback. Callbacks issues from the Legacy SDK maintain references\n * to the original user-issued callbacks, which allows equality\n * comparison by reference even though this callbacks are wrapped before\n * they can be passed to the firebase@exp SDK.\n *\n * @internal\n */\nexport interface UserCallback {\n (dataSnapshot: DataSnapshot, previousChildName?: string | null): unknown;\n userCallback?: unknown;\n context?: object | null;\n}\n\n/**\n * A wrapper class that converts events from the database@exp SDK to the legacy\n * Database SDK. Events are not converted directly as event registration relies\n * on reference comparison of the original user callback (see `matches()`) and\n * relies on equality of the legacy SDK's `context` object.\n */\nexport class CallbackContext {\n constructor(\n private readonly snapshotCallback: UserCallback,\n private readonly cancelCallback?: (error: Error) => unknown\n ) {}\n\n onValue(\n expDataSnapshot: DataSnapshot,\n previousChildName?: string | null\n ): void {\n this.snapshotCallback.call(null, expDataSnapshot, previousChildName);\n }\n\n onCancel(error: Error): void {\n assert(\n this.hasCancelCallback,\n 'Raising a cancel event on a listener with no cancel callback'\n );\n return this.cancelCallback.call(null, error);\n }\n\n get hasCancelCallback(): boolean {\n return !!this.cancelCallback;\n }\n\n matches(other: CallbackContext): boolean {\n return (\n this.snapshotCallback === other.snapshotCallback ||\n (this.snapshotCallback.userCallback !== undefined &&\n this.snapshotCallback.userCallback ===\n other.snapshotCallback.userCallback &&\n this.snapshotCallback.context === other.snapshotCallback.context)\n );\n }\n}\n\nexport interface QueryContext {\n readonly _queryIdentifier: string;\n readonly _queryObject: object;\n readonly _repo: Repo;\n readonly _path: Path;\n readonly _queryParams: QueryParams;\n}\n\n/**\n * An EventRegistration is basically an event type ('value', 'child_added', etc.) and a callback\n * to be notified of that type of event.\n *\n * That said, it can also contain a cancel callback to be notified if the event is canceled. And\n * currently, this code is organized around the idea that you would register multiple child_ callbacks\n * together, as a single EventRegistration. Though currently we don't do that.\n */\nexport interface EventRegistration {\n /**\n * True if this container has a callback to trigger for this event type\n */\n respondsTo(eventType: string): boolean;\n\n createEvent(change: Change, query: QueryContext): Event;\n\n /**\n * Given event data, return a function to trigger the user's callback\n */\n getEventRunner(eventData: Event): () => void;\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null;\n\n matches(other: EventRegistration): boolean;\n\n /**\n * False basically means this is a \"dummy\" callback container being used as a sentinel\n * to remove all callback containers of a particular type. (e.g. if the user does\n * ref.off('value') without specifying a specific callback).\n *\n * (TODO: Rework this, since it's hacky)\n *\n */\n hasAnyCallback(): boolean;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from '@firebase/util';\n\nimport {\n Repo,\n repoOnDisconnectCancel,\n repoOnDisconnectSet,\n repoOnDisconnectSetWithPriority,\n repoOnDisconnectUpdate\n} from '../core/Repo';\nimport { Path } from '../core/util/Path';\nimport {\n validateFirebaseDataArg,\n validateFirebaseMergeDataArg,\n validatePriority,\n validateWritablePath\n} from '../core/util/validation';\n\n/**\n * The `onDisconnect` class allows you to write or clear data when your client\n * disconnects from the Database server. These updates occur whether your\n * client disconnects cleanly or not, so you can rely on them to clean up data\n * even if a connection is dropped or a client crashes.\n *\n * The `onDisconnect` class is most commonly used to manage presence in\n * applications where it is useful to detect how many clients are connected and\n * when other clients disconnect. See\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information.\n *\n * To avoid problems when a connection is dropped before the requests can be\n * transferred to the Database server, these functions should be called before\n * writing any data.\n *\n * Note that `onDisconnect` operations are only triggered once. If you want an\n * operation to occur each time a disconnect occurs, you'll need to re-establish\n * the `onDisconnect` operations each time you reconnect.\n */\nexport class OnDisconnect {\n /** @hideconstructor */\n constructor(private _repo: Repo, private _path: Path) {}\n\n /**\n * Cancels all previously queued `onDisconnect()` set or update events for this\n * location and all children.\n *\n * If a write has been queued for this location via a `set()` or `update()` at a\n * parent location, the write at this location will be canceled, though writes\n * to sibling locations will still occur.\n *\n * @returns Resolves when synchronization to the server is complete.\n */\n cancel(): Promise {\n const deferred = new Deferred();\n repoOnDisconnectCancel(\n this._repo,\n this._path,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is deleted when the client is disconnected\n * (due to closing the browser, navigating to a new page, or network issues).\n *\n * @returns Resolves when synchronization to the server is complete.\n */\n remove(): Promise {\n validateWritablePath('OnDisconnect.remove', this._path);\n const deferred = new Deferred();\n repoOnDisconnectSet(\n this._repo,\n this._path,\n null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is set to the specified value when the\n * client is disconnected (due to closing the browser, navigating to a new page,\n * or network issues).\n *\n * `set()` is especially useful for implementing \"presence\" systems, where a\n * value should be changed or cleared when a user disconnects so that they\n * appear \"offline\" to other users. See\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information.\n *\n * Note that `onDisconnect` operations are only triggered once. If you want an\n * operation to occur each time a disconnect occurs, you'll need to re-establish\n * the `onDisconnect` operations each time.\n *\n * @param value - The value to be written to this location on disconnect (can\n * be an object, array, string, number, boolean, or null).\n * @returns Resolves when synchronization to the Database is complete.\n */\n set(value: unknown): Promise {\n validateWritablePath('OnDisconnect.set', this._path);\n validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);\n const deferred = new Deferred();\n repoOnDisconnectSet(\n this._repo,\n this._path,\n value,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is set to the specified value and priority\n * when the client is disconnected (due to closing the browser, navigating to a\n * new page, or network issues).\n *\n * @param value - The value to be written to this location on disconnect (can\n * be an object, array, string, number, boolean, or null).\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when synchronization to the Database is complete.\n */\n setWithPriority(\n value: unknown,\n priority: number | string | null\n ): Promise {\n validateWritablePath('OnDisconnect.setWithPriority', this._path);\n validateFirebaseDataArg(\n 'OnDisconnect.setWithPriority',\n value,\n this._path,\n false\n );\n validatePriority('OnDisconnect.setWithPriority', priority, false);\n\n const deferred = new Deferred();\n repoOnDisconnectSetWithPriority(\n this._repo,\n this._path,\n value,\n priority,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Writes multiple values at this location when the client is disconnected (due\n * to closing the browser, navigating to a new page, or network issues).\n *\n * The `values` argument contains multiple property-value pairs that will be\n * written to the Database together. Each child property can either be a simple\n * property (for example, \"name\") or a relative path (for example, \"name/first\")\n * from the current location to the data to update.\n *\n * As opposed to the `set()` method, `update()` can be use to selectively update\n * only the referenced properties at the current location (instead of replacing\n * all the child properties at the current location).\n *\n * @param values - Object containing multiple values.\n * @returns Resolves when synchronization to the Database is complete.\n */\n update(values: object): Promise {\n validateWritablePath('OnDisconnect.update', this._path);\n validateFirebaseMergeDataArg(\n 'OnDisconnect.update',\n values,\n this._path,\n false\n );\n const deferred = new Deferred();\n repoOnDisconnectUpdate(\n this._repo,\n this._path,\n values as Record,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, getModularInstance, Deferred } from '@firebase/util';\n\nimport {\n Repo,\n repoAddEventCallbackForQuery,\n repoGetValue,\n repoRemoveEventCallbackForQuery,\n repoServerTime,\n repoSetWithPriority,\n repoUpdate\n} from '../core/Repo';\nimport { ChildrenNode } from '../core/snap/ChildrenNode';\nimport { Index } from '../core/snap/indexes/Index';\nimport { KEY_INDEX } from '../core/snap/indexes/KeyIndex';\nimport { PathIndex } from '../core/snap/indexes/PathIndex';\nimport { PRIORITY_INDEX } from '../core/snap/indexes/PriorityIndex';\nimport { VALUE_INDEX } from '../core/snap/indexes/ValueIndex';\nimport { Node } from '../core/snap/Node';\nimport { syncPointSetReferenceConstructor } from '../core/SyncPoint';\nimport { syncTreeSetReferenceConstructor } from '../core/SyncTree';\nimport { parseRepoInfo } from '../core/util/libs/parser';\nimport { nextPushId } from '../core/util/NextPushId';\nimport {\n Path,\n pathEquals,\n pathGetBack,\n pathGetFront,\n pathChild,\n pathParent,\n pathToUrlEncodedString,\n pathIsEmpty\n} from '../core/util/Path';\nimport {\n fatal,\n MAX_NAME,\n MIN_NAME,\n ObjectToUniqueKey\n} from '../core/util/util';\nimport {\n isValidPriority,\n validateFirebaseDataArg,\n validateFirebaseMergeDataArg,\n validateKey,\n validatePathString,\n validatePriority,\n validateRootPathString,\n validateUrl,\n validateWritablePath\n} from '../core/util/validation';\nimport { Change } from '../core/view/Change';\nimport { CancelEvent, DataEvent, EventType } from '../core/view/Event';\nimport {\n CallbackContext,\n EventRegistration,\n QueryContext,\n UserCallback\n} from '../core/view/EventRegistration';\nimport {\n QueryParams,\n queryParamsEndAt,\n queryParamsEndBefore,\n queryParamsGetQueryObject,\n queryParamsLimitToFirst,\n queryParamsLimitToLast,\n queryParamsOrderBy,\n queryParamsStartAfter,\n queryParamsStartAt\n} from '../core/view/QueryParams';\n\nimport { Database } from './Database';\nimport { OnDisconnect } from './OnDisconnect';\nimport {\n ListenOptions,\n Query as Query,\n DatabaseReference,\n Unsubscribe,\n ThenableReference\n} from './Reference';\n\n/**\n * @internal\n */\nexport class QueryImpl implements Query, QueryContext {\n /**\n * @hideconstructor\n */\n constructor(\n readonly _repo: Repo,\n readonly _path: Path,\n readonly _queryParams: QueryParams,\n readonly _orderByCalled: boolean\n ) {}\n\n get key(): string | null {\n if (pathIsEmpty(this._path)) {\n return null;\n } else {\n return pathGetBack(this._path);\n }\n }\n\n get ref(): DatabaseReference {\n return new ReferenceImpl(this._repo, this._path);\n }\n\n get _queryIdentifier(): string {\n const obj = queryParamsGetQueryObject(this._queryParams);\n const id = ObjectToUniqueKey(obj);\n return id === '{}' ? 'default' : id;\n }\n\n /**\n * An object representation of the query parameters used by this Query.\n */\n get _queryObject(): object {\n return queryParamsGetQueryObject(this._queryParams);\n }\n\n isEqual(other: QueryImpl | null): boolean {\n other = getModularInstance(other);\n if (!(other instanceof QueryImpl)) {\n return false;\n }\n\n const sameRepo = this._repo === other._repo;\n const samePath = pathEquals(this._path, other._path);\n const sameQueryIdentifier =\n this._queryIdentifier === other._queryIdentifier;\n\n return sameRepo && samePath && sameQueryIdentifier;\n }\n\n toJSON(): string {\n return this.toString();\n }\n\n toString(): string {\n return this._repo.toString() + pathToUrlEncodedString(this._path);\n }\n}\n\n/**\n * Validates that no other order by call has been made\n */\nfunction validateNoPreviousOrderByCall(query: QueryImpl, fnName: string) {\n if (query._orderByCalled === true) {\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\n }\n}\n\n/**\n * Validates start/end values for queries.\n */\nfunction validateQueryEndpoints(params: QueryParams) {\n let startNode = null;\n let endNode = null;\n if (params.hasStart()) {\n startNode = params.getIndexStartValue();\n }\n if (params.hasEnd()) {\n endNode = params.getIndexEndValue();\n }\n\n if (params.getIndex() === KEY_INDEX) {\n const tooManyArgsError =\n 'Query: When ordering by key, you may only pass one argument to ' +\n 'startAt(), endAt(), or equalTo().';\n const wrongArgTypeError =\n 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +\n 'endAt(), endBefore(), or equalTo() must be a string.';\n if (params.hasStart()) {\n const startName = params.getIndexStartName();\n if (startName !== MIN_NAME) {\n throw new Error(tooManyArgsError);\n } else if (typeof startNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n if (params.hasEnd()) {\n const endName = params.getIndexEndName();\n if (endName !== MAX_NAME) {\n throw new Error(tooManyArgsError);\n } else if (typeof endNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n } else if (params.getIndex() === PRIORITY_INDEX) {\n if (\n (startNode != null && !isValidPriority(startNode)) ||\n (endNode != null && !isValidPriority(endNode))\n ) {\n throw new Error(\n 'Query: When ordering by priority, the first argument passed to startAt(), ' +\n 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +\n '(null, a number, or a string).'\n );\n }\n } else {\n assert(\n params.getIndex() instanceof PathIndex ||\n params.getIndex() === VALUE_INDEX,\n 'unknown index type.'\n );\n if (\n (startNode != null && typeof startNode === 'object') ||\n (endNode != null && typeof endNode === 'object')\n ) {\n throw new Error(\n 'Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +\n 'equalTo() cannot be an object.'\n );\n }\n }\n}\n\n/**\n * Validates that limit* has been called with the correct combination of parameters\n */\nfunction validateLimit(params: QueryParams) {\n if (\n params.hasStart() &&\n params.hasEnd() &&\n params.hasLimit() &&\n !params.hasAnchoredLimit()\n ) {\n throw new Error(\n \"Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use \" +\n 'limitToFirst() or limitToLast() instead.'\n );\n }\n}\n/**\n * @internal\n */\nexport class ReferenceImpl extends QueryImpl implements DatabaseReference {\n /** @hideconstructor */\n constructor(repo: Repo, path: Path) {\n super(repo, path, new QueryParams(), false);\n }\n\n get parent(): ReferenceImpl | null {\n const parentPath = pathParent(this._path);\n return parentPath === null\n ? null\n : new ReferenceImpl(this._repo, parentPath);\n }\n\n get root(): ReferenceImpl {\n let ref: ReferenceImpl = this;\n while (ref.parent !== null) {\n ref = ref.parent;\n }\n return ref;\n }\n}\n\n/**\n * A `DataSnapshot` contains data from a Database location.\n *\n * Any time you read data from the Database, you receive the data as a\n * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach\n * with `on()` or `once()`. You can extract the contents of the snapshot as a\n * JavaScript object by calling the `val()` method. Alternatively, you can\n * traverse into the snapshot by calling `child()` to return child snapshots\n * (which you could then call `val()` on).\n *\n * A `DataSnapshot` is an efficiently generated, immutable copy of the data at\n * a Database location. It cannot be modified and will never change (to modify\n * data, you always call the `set()` method on a `Reference` directly).\n */\nexport class DataSnapshot {\n /**\n * @param _node - A SnapshotNode to wrap.\n * @param ref - The location this snapshot came from.\n * @param _index - The iteration order for this snapshot\n * @hideconstructor\n */\n constructor(\n readonly _node: Node,\n /**\n * The location of this DataSnapshot.\n */\n readonly ref: DatabaseReference,\n readonly _index: Index\n ) {}\n\n /**\n * Gets the priority value of the data in this `DataSnapshot`.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}\n * ).\n */\n get priority(): string | number | null {\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\n return this._node.getPriority().val() as string | number | null;\n }\n\n /**\n * The key (last part of the path) of the location of this `DataSnapshot`.\n *\n * The last token in a Database location is considered its key. For example,\n * \"ada\" is the key for the /users/ada/ node. Accessing the key on any\n * `DataSnapshot` will return the key for the location that generated it.\n * However, accessing the key on the root URL of a Database will return\n * `null`.\n */\n get key(): string | null {\n return this.ref.key;\n }\n\n /** Returns the number of child properties of this `DataSnapshot`. */\n get size(): number {\n return this._node.numChildren();\n }\n\n /**\n * Gets another `DataSnapshot` for the location at the specified relative path.\n *\n * Passing a relative path to the `child()` method of a DataSnapshot returns\n * another `DataSnapshot` for the location at the specified relative path. The\n * relative path can either be a simple child name (for example, \"ada\") or a\n * deeper, slash-separated path (for example, \"ada/name/first\"). If the child\n * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`\n * whose value is `null`) is returned.\n *\n * @param path - A relative path to the location of child data.\n */\n child(path: string): DataSnapshot {\n const childPath = new Path(path);\n const childRef = child(this.ref, path);\n return new DataSnapshot(\n this._node.getChild(childPath),\n childRef,\n PRIORITY_INDEX\n );\n }\n /**\n * Returns true if this `DataSnapshot` contains any data. It is slightly more\n * efficient than using `snapshot.val() !== null`.\n */\n exists(): boolean {\n return !this._node.isEmpty();\n }\n\n /**\n * Exports the entire contents of the DataSnapshot as a JavaScript object.\n *\n * The `exportVal()` method is similar to `val()`, except priority information\n * is included (if available), making it suitable for backing up your data.\n *\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\n * Array, string, number, boolean, or `null`).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n exportVal(): any {\n return this._node.val(true);\n }\n\n /**\n * Enumerates the top-level children in the `IteratedDataSnapshot`.\n *\n * Because of the way JavaScript objects work, the ordering of data in the\n * JavaScript object returned by `val()` is not guaranteed to match the\n * ordering on the server nor the ordering of `onChildAdded()` events. That is\n * where `forEach()` comes in handy. It guarantees the children of a\n * `DataSnapshot` will be iterated in their query order.\n *\n * If no explicit `orderBy*()` method is used, results are returned\n * ordered by key (unless priorities are used, in which case, results are\n * returned by priority).\n *\n * @param action - A function that will be called for each child DataSnapshot.\n * The callback can return true to cancel further enumeration.\n * @returns true if enumeration was canceled due to your callback returning\n * true.\n */\n forEach(action: (child: IteratedDataSnapshot) => boolean | void): boolean {\n if (this._node.isLeafNode()) {\n return false;\n }\n\n const childrenNode = this._node as ChildrenNode;\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\n return !!childrenNode.forEachChild(this._index, (key, node) => {\n return action(\n new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX)\n );\n });\n }\n\n /**\n * Returns true if the specified child path has (non-null) data.\n *\n * @param path - A relative path to the location of a potential child.\n * @returns `true` if data exists at the specified child path; else\n * `false`.\n */\n hasChild(path: string): boolean {\n const childPath = new Path(path);\n return !this._node.getChild(childPath).isEmpty();\n }\n\n /**\n * Returns whether or not the `DataSnapshot` has any non-`null` child\n * properties.\n *\n * You can use `hasChildren()` to determine if a `DataSnapshot` has any\n * children. If it does, you can enumerate them using `forEach()`. If it\n * doesn't, then either this snapshot contains a primitive value (which can be\n * retrieved with `val()`) or it is empty (in which case, `val()` will return\n * `null`).\n *\n * @returns true if this snapshot has any children; else false.\n */\n hasChildren(): boolean {\n if (this._node.isLeafNode()) {\n return false;\n } else {\n return !this._node.isEmpty();\n }\n }\n\n /**\n * Returns a JSON-serializable representation of this object.\n */\n toJSON(): object | null {\n return this.exportVal();\n }\n\n /**\n * Extracts a JavaScript value from a `DataSnapshot`.\n *\n * Depending on the data in a `DataSnapshot`, the `val()` method may return a\n * scalar type (string, number, or boolean), an array, or an object. It may\n * also return null, indicating that the `DataSnapshot` is empty (contains no\n * data).\n *\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\n * Array, string, number, boolean, or `null`).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n val(): any {\n return this._node.val();\n }\n}\n\n/**\n * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined.\n */\nexport interface IteratedDataSnapshot extends DataSnapshot {\n key: string; // key of the location of this snapshot.\n}\n\n/**\n *\n * Returns a `Reference` representing the location in the Database\n * corresponding to the provided path. If no path is provided, the `Reference`\n * will point to the root of the Database.\n *\n * @param db - The database instance to obtain a reference for.\n * @param path - Optional path representing the location the returned\n * `Reference` will point. If not provided, the returned `Reference` will\n * point to the root of the Database.\n * @returns If a path is provided, a `Reference`\n * pointing to the provided path. Otherwise, a `Reference` pointing to the\n * root of the Database.\n */\nexport function ref(db: Database, path?: string): DatabaseReference {\n db = getModularInstance(db);\n db._checkNotDeleted('ref');\n return path !== undefined ? child(db._root, path) : db._root;\n}\n\n/**\n * Returns a `Reference` representing the location in the Database\n * corresponding to the provided Firebase URL.\n *\n * An exception is thrown if the URL is not a valid Firebase Database URL or it\n * has a different domain than the current `Database` instance.\n *\n * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored\n * and are not applied to the returned `Reference`.\n *\n * @param db - The database instance to obtain a reference for.\n * @param url - The Firebase URL at which the returned `Reference` will\n * point.\n * @returns A `Reference` pointing to the provided\n * Firebase URL.\n */\nexport function refFromURL(db: Database, url: string): DatabaseReference {\n db = getModularInstance(db);\n db._checkNotDeleted('refFromURL');\n const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\n validateUrl('refFromURL', parsedURL);\n\n const repoInfo = parsedURL.repoInfo;\n if (\n !db._repo.repoInfo_.isCustomHost() &&\n repoInfo.host !== db._repo.repoInfo_.host\n ) {\n fatal(\n 'refFromURL' +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n db._repo.repoInfo_.host +\n ')'\n );\n }\n\n return ref(db, parsedURL.path.toString());\n}\n/**\n * Gets a `Reference` for the location at the specified relative path.\n *\n * The relative path can either be a simple child name (for example, \"ada\") or\n * a deeper slash-separated path (for example, \"ada/name/first\").\n *\n * @param parent - The parent location.\n * @param path - A relative path from this location to the desired child\n * location.\n * @returns The specified child location.\n */\nexport function child(\n parent: DatabaseReference,\n path: string\n): DatabaseReference {\n parent = getModularInstance(parent);\n if (pathGetFront(parent._path) === null) {\n validateRootPathString('child', 'path', path, false);\n } else {\n validatePathString('child', 'path', path, false);\n }\n return new ReferenceImpl(parent._repo, pathChild(parent._path, path));\n}\n\n/**\n * Returns an `OnDisconnect` object - see\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information on how to use it.\n *\n * @param ref - The reference to add OnDisconnect triggers for.\n */\nexport function onDisconnect(ref: DatabaseReference): OnDisconnect {\n ref = getModularInstance(ref) as ReferenceImpl;\n return new OnDisconnect(ref._repo, ref._path);\n}\n\nexport interface ThenableReferenceImpl\n extends ReferenceImpl,\n Pick, 'then' | 'catch'> {\n key: string;\n parent: ReferenceImpl;\n}\n\n/**\n * Generates a new child location using a unique key and returns its\n * `Reference`.\n *\n * This is the most common pattern for adding data to a collection of items.\n *\n * If you provide a value to `push()`, the value is written to the\n * generated location. If you don't pass a value, nothing is written to the\n * database and the child remains empty (but you can use the `Reference`\n * elsewhere).\n *\n * The unique keys generated by `push()` are ordered by the current time, so the\n * resulting list of items is chronologically sorted. The keys are also\n * designed to be unguessable (they contain 72 random bits of entropy).\n *\n * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.\n * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.\n *\n * @param parent - The parent location.\n * @param value - Optional value to be written at the generated location.\n * @returns Combined `Promise` and `Reference`; resolves when write is complete,\n * but can be used immediately as the `Reference` to the child location.\n */\nexport function push(\n parent: DatabaseReference,\n value?: unknown\n): ThenableReference {\n parent = getModularInstance(parent);\n validateWritablePath('push', parent._path);\n validateFirebaseDataArg('push', value, parent._path, true);\n const now = repoServerTime(parent._repo);\n const name = nextPushId(now);\n\n // push() returns a ThennableReference whose promise is fulfilled with a\n // regular Reference. We use child() to create handles to two different\n // references. The first is turned into a ThennableReference below by adding\n // then() and catch() methods and is used as the return value of push(). The\n // second remains a regular Reference and is used as the fulfilled value of\n // the first ThennableReference.\n const thenablePushRef: Partial = child(\n parent,\n name\n ) as ReferenceImpl;\n const pushRef = child(parent, name) as ReferenceImpl;\n\n let promise: Promise;\n if (value != null) {\n promise = set(pushRef, value).then(() => pushRef);\n } else {\n promise = Promise.resolve(pushRef);\n }\n\n thenablePushRef.then = promise.then.bind(promise);\n thenablePushRef.catch = promise.then.bind(promise, undefined);\n return thenablePushRef as ThenableReferenceImpl;\n}\n\n/**\n * Removes the data at this Database location.\n *\n * Any data at child locations will also be deleted.\n *\n * The effect of the remove will be visible immediately and the corresponding\n * event 'value' will be triggered. Synchronization of the remove to the\n * Firebase servers will also be started, and the returned Promise will resolve\n * when complete. If provided, the onComplete callback will be called\n * asynchronously after synchronization has finished.\n *\n * @param ref - The location to remove.\n * @returns Resolves when remove on server is complete.\n */\nexport function remove(ref: DatabaseReference): Promise {\n validateWritablePath('remove', ref._path);\n return set(ref, null);\n}\n\n/**\n * Writes data to this Database location.\n *\n * This will overwrite any data at this location and all child locations.\n *\n * The effect of the write will be visible immediately, and the corresponding\n * events (\"value\", \"child_added\", etc.) will be triggered. Synchronization of\n * the data to the Firebase servers will also be started, and the returned\n * Promise will resolve when complete. If provided, the `onComplete` callback\n * will be called asynchronously after synchronization has finished.\n *\n * Passing `null` for the new value is equivalent to calling `remove()`; namely,\n * all data at this location and all child locations will be deleted.\n *\n * `set()` will remove any priority stored at this location, so if priority is\n * meant to be preserved, you need to use `setWithPriority()` instead.\n *\n * Note that modifying data with `set()` will cancel any pending transactions\n * at that location, so extreme care should be taken if mixing `set()` and\n * `transaction()` to modify the same data.\n *\n * A single `set()` will generate a single \"value\" event at the location where\n * the `set()` was performed.\n *\n * @param ref - The location to write to.\n * @param value - The value to be written (string, number, boolean, object,\n * array, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function set(ref: DatabaseReference, value: unknown): Promise {\n ref = getModularInstance(ref);\n validateWritablePath('set', ref._path);\n validateFirebaseDataArg('set', value, ref._path, false);\n const deferred = new Deferred();\n repoSetWithPriority(\n ref._repo,\n ref._path,\n value,\n /*priority=*/ null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Sets a priority for the data at this Database location.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\n * ).\n *\n * @param ref - The location to write to.\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function setPriority(\n ref: DatabaseReference,\n priority: string | number | null\n): Promise {\n ref = getModularInstance(ref);\n validateWritablePath('setPriority', ref._path);\n validatePriority('setPriority', priority, false);\n const deferred = new Deferred();\n repoSetWithPriority(\n ref._repo,\n pathChild(ref._path, '.priority'),\n priority,\n null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Writes data the Database location. Like `set()` but also specifies the\n * priority for that data.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\n * ).\n *\n * @param ref - The location to write to.\n * @param value - The value to be written (string, number, boolean, object,\n * array, or null).\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function setWithPriority(\n ref: DatabaseReference,\n value: unknown,\n priority: string | number | null\n): Promise {\n validateWritablePath('setWithPriority', ref._path);\n validateFirebaseDataArg('setWithPriority', value, ref._path, false);\n validatePriority('setWithPriority', priority, false);\n if (ref.key === '.length' || ref.key === '.keys') {\n throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';\n }\n\n const deferred = new Deferred();\n repoSetWithPriority(\n ref._repo,\n ref._path,\n value,\n priority,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Writes multiple values to the Database at once.\n *\n * The `values` argument contains multiple property-value pairs that will be\n * written to the Database together. Each child property can either be a simple\n * property (for example, \"name\") or a relative path (for example,\n * \"name/first\") from the current location to the data to update.\n *\n * As opposed to the `set()` method, `update()` can be use to selectively update\n * only the referenced properties at the current location (instead of replacing\n * all the child properties at the current location).\n *\n * The effect of the write will be visible immediately, and the corresponding\n * events ('value', 'child_added', etc.) will be triggered. Synchronization of\n * the data to the Firebase servers will also be started, and the returned\n * Promise will resolve when complete. If provided, the `onComplete` callback\n * will be called asynchronously after synchronization has finished.\n *\n * A single `update()` will generate a single \"value\" event at the location\n * where the `update()` was performed, regardless of how many children were\n * modified.\n *\n * Note that modifying data with `update()` will cancel any pending\n * transactions at that location, so extreme care should be taken if mixing\n * `update()` and `transaction()` to modify the same data.\n *\n * Passing `null` to `update()` will remove the data at this location.\n *\n * See\n * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.\n *\n * @param ref - The location to write to.\n * @param values - Object containing multiple values.\n * @returns Resolves when update on server is complete.\n */\nexport function update(ref: DatabaseReference, values: object): Promise {\n validateFirebaseMergeDataArg('update', values, ref._path, false);\n const deferred = new Deferred();\n repoUpdate(\n ref._repo,\n ref._path,\n values as Record,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Gets the most up-to-date result for this query.\n *\n * @param query - The query to run.\n * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is\n * available, or rejects if the client is unable to return a value (e.g., if the\n * server is unreachable and there is nothing cached).\n */\nexport function get(query: Query): Promise {\n query = getModularInstance(query) as QueryImpl;\n const callbackContext = new CallbackContext(() => {});\n const container = new ValueEventRegistration(callbackContext);\n return repoGetValue(query._repo, query, container).then(node => {\n return new DataSnapshot(\n node,\n new ReferenceImpl(query._repo, query._path),\n query._queryParams.getIndex()\n );\n });\n}\n/**\n * Represents registration for 'value' events.\n */\nexport class ValueEventRegistration implements EventRegistration {\n constructor(private callbackContext: CallbackContext) {}\n\n respondsTo(eventType: string): boolean {\n return eventType === 'value';\n }\n\n createEvent(change: Change, query: QueryContext): DataEvent {\n const index = query._queryParams.getIndex();\n return new DataEvent(\n 'value',\n this,\n new DataSnapshot(\n change.snapshotNode,\n new ReferenceImpl(query._repo, query._path),\n index\n )\n );\n }\n\n getEventRunner(eventData: CancelEvent | DataEvent): () => void {\n if (eventData.getEventType() === 'cancel') {\n return () =>\n this.callbackContext.onCancel((eventData as CancelEvent).error);\n } else {\n return () =>\n this.callbackContext.onValue((eventData as DataEvent).snapshot, null);\n }\n }\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null {\n if (this.callbackContext.hasCancelCallback) {\n return new CancelEvent(this, error, path);\n } else {\n return null;\n }\n }\n\n matches(other: EventRegistration): boolean {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n } else if (!other.callbackContext || !this.callbackContext) {\n // If no callback specified, we consider it to match any callback.\n return true;\n } else {\n return other.callbackContext.matches(this.callbackContext);\n }\n }\n\n hasAnyCallback(): boolean {\n return this.callbackContext !== null;\n }\n}\n\n/**\n * Represents the registration of a child_x event.\n */\nexport class ChildEventRegistration implements EventRegistration {\n constructor(\n private eventType: string,\n private callbackContext: CallbackContext | null\n ) {}\n\n respondsTo(eventType: string): boolean {\n let eventToCheck =\n eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck =\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return this.eventType === eventToCheck;\n }\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null {\n if (this.callbackContext.hasCancelCallback) {\n return new CancelEvent(this, error, path);\n } else {\n return null;\n }\n }\n\n createEvent(change: Change, query: QueryContext): DataEvent {\n assert(change.childName != null, 'Child events should have a childName.');\n const childRef = child(\n new ReferenceImpl(query._repo, query._path),\n change.childName\n );\n const index = query._queryParams.getIndex();\n return new DataEvent(\n change.type as EventType,\n this,\n new DataSnapshot(change.snapshotNode, childRef, index),\n change.prevName\n );\n }\n\n getEventRunner(eventData: CancelEvent | DataEvent): () => void {\n if (eventData.getEventType() === 'cancel') {\n return () =>\n this.callbackContext.onCancel((eventData as CancelEvent).error);\n } else {\n return () =>\n this.callbackContext.onValue(\n (eventData as DataEvent).snapshot,\n (eventData as DataEvent).prevName\n );\n }\n }\n\n matches(other: EventRegistration): boolean {\n if (other instanceof ChildEventRegistration) {\n return (\n this.eventType === other.eventType &&\n (!this.callbackContext ||\n !other.callbackContext ||\n this.callbackContext.matches(other.callbackContext))\n );\n }\n\n return false;\n }\n\n hasAnyCallback(): boolean {\n return !!this.callbackContext;\n }\n}\n\nfunction addEventListener(\n query: Query,\n eventType: EventType,\n callback: UserCallback,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n) {\n let cancelCallback: ((error: Error) => unknown) | undefined;\n if (typeof cancelCallbackOrListenOptions === 'object') {\n cancelCallback = undefined;\n options = cancelCallbackOrListenOptions;\n }\n if (typeof cancelCallbackOrListenOptions === 'function') {\n cancelCallback = cancelCallbackOrListenOptions;\n }\n\n if (options && options.onlyOnce) {\n const userCallback = callback;\n const onceCallback: UserCallback = (dataSnapshot, previousChildName) => {\n repoRemoveEventCallbackForQuery(query._repo, query, container);\n userCallback(dataSnapshot, previousChildName);\n };\n onceCallback.userCallback = callback.userCallback;\n onceCallback.context = callback.context;\n callback = onceCallback;\n }\n\n const callbackContext = new CallbackContext(\n callback,\n cancelCallback || undefined\n );\n const container =\n eventType === 'value'\n ? new ValueEventRegistration(callbackContext)\n : new ChildEventRegistration(eventType, callbackContext);\n repoAddEventCallbackForQuery(query._repo, query, container);\n return () => repoRemoveEventCallbackForQuery(query._repo, query, container);\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'value',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName?: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_added',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_changed',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_moved',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_removed',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\nexport { EventType };\n\n/**\n * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.\n * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from\n * the respective `on*` callbacks.\n *\n * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener\n * will not automatically remove listeners registered on child nodes, `off()`\n * must also be called on any child listeners to remove the callback.\n *\n * If a callback is not specified, all callbacks for the specified eventType\n * will be removed. Similarly, if no eventType is specified, all callbacks\n * for the `Reference` will be removed.\n *\n * Individual listeners can also be removed by invoking their unsubscribe\n * callbacks.\n *\n * @param query - The query that the listener was registered with.\n * @param eventType - One of the following strings: \"value\", \"child_added\",\n * \"child_changed\", \"child_removed\", or \"child_moved.\" If omitted, all callbacks\n * for the `Reference` will be removed.\n * @param callback - The callback function that was passed to `on()` or\n * `undefined` to remove all callbacks.\n */\nexport function off(\n query: Query,\n eventType?: EventType,\n callback?: (\n snapshot: DataSnapshot,\n previousChildName?: string | null\n ) => unknown\n): void {\n let container: EventRegistration | null = null;\n const expCallback = callback ? new CallbackContext(callback) : null;\n if (eventType === 'value') {\n container = new ValueEventRegistration(expCallback);\n } else if (eventType) {\n container = new ChildEventRegistration(eventType, expCallback);\n }\n repoRemoveEventCallbackForQuery(query._repo, query, container);\n}\n\n/** Describes the different query constraints available in this SDK. */\nexport type QueryConstraintType =\n | 'endAt'\n | 'endBefore'\n | 'startAt'\n | 'startAfter'\n | 'limitToFirst'\n | 'limitToLast'\n | 'orderByChild'\n | 'orderByKey'\n | 'orderByPriority'\n | 'orderByValue'\n | 'equalTo';\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Database query. `QueryConstraint`s are created by invoking {@link endAt},\n * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link\n * limitToFirst}, {@link limitToLast}, {@link orderByChild},\n * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,\n * {@link orderByValue} or {@link equalTo} and\n * can then be passed to {@link query} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nexport abstract class QueryConstraint {\n /** The type of this query constraints */\n abstract readonly type: QueryConstraintType;\n\n /**\n * Takes the provided `Query` and returns a copy of the `Query` with this\n * `QueryConstraint` applied.\n */\n abstract _apply(query: QueryImpl): QueryImpl;\n}\n\nclass QueryEndAtConstraint extends QueryConstraint {\n readonly type = 'endAt';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('endAt', this._value, query._path, true);\n const newParams = queryParamsEndAt(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'endAt: Starting point was already set (by another call to endAt, ' +\n 'endBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified ending point.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The ending point is inclusive, so children with exactly the specified value\n * will be included in the query. The optional key argument can be used to\n * further limit the range of the query. If it is specified, then children that\n * have exactly the specified value must also have a key name less than or equal\n * to the specified key.\n *\n * You can read more about `endAt()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to end at. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to end at, among the children with the previously\n * specified priority. This argument is only allowed if ordering by child,\n * value, or priority.\n */\nexport function endAt(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('endAt', 'key', key, true);\n return new QueryEndAtConstraint(value, key);\n}\n\nclass QueryEndBeforeConstraint extends QueryConstraint {\n readonly type = 'endBefore';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('endBefore', this._value, query._path, false);\n const newParams = queryParamsEndBefore(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'endBefore: Starting point was already set (by another call to endAt, ' +\n 'endBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified ending point (exclusive).\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The ending point is exclusive. If only a value is provided, children\n * with a value less than the specified value will be included in the query.\n * If a key is specified, then children must have a value less than or equal\n * to the specified value and a key name less than the specified key.\n *\n * @param value - The value to end before. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to end before, among the children with the\n * previously specified priority. This argument is only allowed if ordering by\n * child, value, or priority.\n */\nexport function endBefore(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('endBefore', 'key', key, true);\n return new QueryEndBeforeConstraint(value, key);\n}\n\nclass QueryStartAtConstraint extends QueryConstraint {\n readonly type = 'startAt';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('startAt', this._value, query._path, true);\n const newParams = queryParamsStartAt(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'startAt: Starting point was already set (by another call to startAt, ' +\n 'startBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified starting point.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The starting point is inclusive, so children with exactly the specified value\n * will be included in the query. The optional key argument can be used to\n * further limit the range of the query. If it is specified, then children that\n * have exactly the specified value must also have a key name greater than or\n * equal to the specified key.\n *\n * You can read more about `startAt()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to start at. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start at. This argument is only allowed if\n * ordering by child, value, or priority.\n */\nexport function startAt(\n value: number | string | boolean | null = null,\n key?: string\n): QueryConstraint {\n validateKey('startAt', 'key', key, true);\n return new QueryStartAtConstraint(value, key);\n}\n\nclass QueryStartAfterConstraint extends QueryConstraint {\n readonly type = 'startAfter';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('startAfter', this._value, query._path, false);\n const newParams = queryParamsStartAfter(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'startAfter: Starting point was already set (by another call to startAt, ' +\n 'startAfter, or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified starting point (exclusive).\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The starting point is exclusive. If only a value is provided, children\n * with a value greater than the specified value will be included in the query.\n * If a key is specified, then children must have a value greater than or equal\n * to the specified value and a a key name greater than the specified key.\n *\n * @param value - The value to start after. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start after. This argument is only allowed if\n * ordering by child, value, or priority.\n */\nexport function startAfter(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('startAfter', 'key', key, true);\n return new QueryStartAfterConstraint(value, key);\n}\n\nclass QueryLimitToFirstConstraint extends QueryConstraint {\n readonly type = 'limitToFirst';\n\n constructor(private readonly _limit: number) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n if (query._queryParams.hasLimit()) {\n throw new Error(\n 'limitToFirst: Limit was already set (by another call to limitToFirst ' +\n 'or limitToLast).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n queryParamsLimitToFirst(query._queryParams, this._limit),\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that if limited to the first specific number\n * of children.\n *\n * The `limitToFirst()` method is used to set a maximum number of children to be\n * synced for a given callback. If we set a limit of 100, we will initially only\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\n * stored in our Database, a `child_added` event will fire for each message.\n * However, if we have over 100 messages, we will only receive a `child_added`\n * event for the first 100 ordered messages. As items change, we will receive\n * `child_removed` events for each item that drops out of the active list so\n * that the total number stays at 100.\n *\n * You can read more about `limitToFirst()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param limit - The maximum number of nodes to include in this query.\n */\nexport function limitToFirst(limit: number): QueryConstraint {\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\n throw new Error('limitToFirst: First argument must be a positive integer.');\n }\n return new QueryLimitToFirstConstraint(limit);\n}\n\nclass QueryLimitToLastConstraint extends QueryConstraint {\n readonly type = 'limitToLast';\n\n constructor(private readonly _limit: number) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n if (query._queryParams.hasLimit()) {\n throw new Error(\n 'limitToLast: Limit was already set (by another call to limitToFirst ' +\n 'or limitToLast).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n queryParamsLimitToLast(query._queryParams, this._limit),\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that is limited to return only the last\n * specified number of children.\n *\n * The `limitToLast()` method is used to set a maximum number of children to be\n * synced for a given callback. If we set a limit of 100, we will initially only\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\n * stored in our Database, a `child_added` event will fire for each message.\n * However, if we have over 100 messages, we will only receive a `child_added`\n * event for the last 100 ordered messages. As items change, we will receive\n * `child_removed` events for each item that drops out of the active list so\n * that the total number stays at 100.\n *\n * You can read more about `limitToLast()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param limit - The maximum number of nodes to include in this query.\n */\nexport function limitToLast(limit: number): QueryConstraint {\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\n throw new Error('limitToLast: First argument must be a positive integer.');\n }\n\n return new QueryLimitToLastConstraint(limit);\n}\n\nclass QueryOrderByChildConstraint extends QueryConstraint {\n readonly type = 'orderByChild';\n\n constructor(private readonly _path: string) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByChild');\n const parsedPath = new Path(this._path);\n if (pathIsEmpty(parsedPath)) {\n throw new Error(\n 'orderByChild: cannot pass in empty path. Use orderByValue() instead.'\n );\n }\n const index = new PathIndex(parsedPath);\n const newParams = queryParamsOrderBy(query._queryParams, index);\n validateQueryEndpoints(newParams);\n\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by the specified child key.\n *\n * Queries can only order by one key at a time. Calling `orderByChild()`\n * multiple times on the same query is an error.\n *\n * Firebase queries allow you to order your data by any child key on the fly.\n * However, if you know in advance what your indexes will be, you can define\n * them via the .indexOn rule in your Security Rules for better performance. See\n * the{@link https://firebase.google.com/docs/database/security/indexing-data}\n * rule for more information.\n *\n * You can read more about `orderByChild()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n *\n * @param path - The path to order by.\n */\nexport function orderByChild(path: string): QueryConstraint {\n if (path === '$key') {\n throw new Error(\n 'orderByChild: \"$key\" is invalid. Use orderByKey() instead.'\n );\n } else if (path === '$priority') {\n throw new Error(\n 'orderByChild: \"$priority\" is invalid. Use orderByPriority() instead.'\n );\n } else if (path === '$value') {\n throw new Error(\n 'orderByChild: \"$value\" is invalid. Use orderByValue() instead.'\n );\n }\n validatePathString('orderByChild', 'path', path, false);\n return new QueryOrderByChildConstraint(path);\n}\n\nclass QueryOrderByKeyConstraint extends QueryConstraint {\n readonly type = 'orderByKey';\n\n _apply(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByKey');\n const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by the key.\n *\n * Sorts the results of a query by their (ascending) key values.\n *\n * You can read more about `orderByKey()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n */\nexport function orderByKey(): QueryConstraint {\n return new QueryOrderByKeyConstraint();\n}\n\nclass QueryOrderByPriorityConstraint extends QueryConstraint {\n readonly type = 'orderByPriority';\n\n _apply(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByPriority');\n const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by priority.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}\n * for alternatives to priority.\n */\nexport function orderByPriority(): QueryConstraint {\n return new QueryOrderByPriorityConstraint();\n}\n\nclass QueryOrderByValueConstraint extends QueryConstraint {\n readonly type = 'orderByValue';\n\n _apply(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByValue');\n const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by value.\n *\n * If the children of a query are all scalar values (string, number, or\n * boolean), you can order the results by their (ascending) values.\n *\n * You can read more about `orderByValue()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n */\nexport function orderByValue(): QueryConstraint {\n return new QueryOrderByValueConstraint();\n}\n\nclass QueryEqualToValueConstraint extends QueryConstraint {\n readonly type = 'equalTo';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('equalTo', this._value, query._path, false);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'equalTo: Starting point was already set (by another call to startAt/startAfter or ' +\n 'equalTo).'\n );\n }\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'equalTo: Ending point was already set (by another call to endAt/endBefore or ' +\n 'equalTo).'\n );\n }\n return new QueryEndAtConstraint(this._value, this._key)._apply(\n new QueryStartAtConstraint(this._value, this._key)._apply(query)\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` that includes children that match the specified\n * value.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The optional key argument can be used to further limit the range of the\n * query. If it is specified, then children that have exactly the specified\n * value must also have exactly the specified key as their key name. This can be\n * used to filter result sets with many matches for the same value.\n *\n * You can read more about `equalTo()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to match for. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start at, among the children with the\n * previously specified priority. This argument is only allowed if ordering by\n * child, value, or priority.\n */\nexport function equalTo(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('equalTo', 'key', key, true);\n return new QueryEqualToValueConstraint(value, key);\n}\n\n/**\n * Creates a new immutable instance of `Query` that is extended to also include\n * additional query constraints.\n *\n * @param query - The Query instance to use as a base for the new constraints.\n * @param queryConstraints - The list of `QueryConstraint`s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query(\n query: Query,\n ...queryConstraints: QueryConstraint[]\n): Query {\n let queryImpl = getModularInstance(query) as QueryImpl;\n for (const constraint of queryConstraints) {\n queryImpl = constraint._apply(queryImpl);\n }\n return queryImpl;\n}\n\n/**\n * Define reference constructor in various modules\n *\n * We are doing this here to avoid several circular\n * dependency issues\n */\nsyncPointSetReferenceConstructor(ReferenceImpl);\nsyncTreeSetReferenceConstructor(ReferenceImpl);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _FirebaseService,\n _getProvider,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\nimport {\n getModularInstance,\n createMockUserToken,\n deepEqual,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\n} from '@firebase/util';\n\nimport { AppCheckTokenProvider } from '../core/AppCheckTokenProvider';\nimport {\n AuthTokenProvider,\n EmulatorTokenProvider,\n FirebaseAuthTokenProvider\n} from '../core/AuthTokenProvider';\nimport { Repo, repoInterrupt, repoResume, repoStart } from '../core/Repo';\nimport { RepoInfo, RepoInfoEmulatorOptions } from '../core/RepoInfo';\nimport { parseRepoInfo } from '../core/util/libs/parser';\nimport { newEmptyPath, pathIsEmpty } from '../core/util/Path';\nimport {\n warn,\n fatal,\n log,\n enableLogging as enableLoggingImpl\n} from '../core/util/util';\nimport { validateUrl } from '../core/util/validation';\nimport { BrowserPollConnection } from '../realtime/BrowserPollConnection';\nimport { TransportManager } from '../realtime/TransportManager';\nimport { WebSocketConnection } from '../realtime/WebSocketConnection';\n\nimport { ReferenceImpl } from './Reference_impl';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n/**\n * This variable is also defined in the firebase Node.js Admin SDK. Before\n * modifying this definition, consult the definition in:\n *\n * https://github.com/firebase/firebase-admin-node\n *\n * and make sure the two are consistent.\n */\nconst FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';\n\n/**\n * Creates and caches `Repo` instances.\n */\nconst repos: {\n [appName: string]: {\n [dbUrl: string]: Repo;\n };\n} = {};\n\n/**\n * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).\n */\nlet useRestClient = false;\n\n/**\n * Update an existing `Repo` in place to point to a new host/port.\n */\nfunction repoManagerApplyEmulatorSettings(\n repo: Repo,\n hostAndPort: string,\n emulatorOptions: RepoInfoEmulatorOptions,\n tokenProvider?: AuthTokenProvider\n): void {\n const portIndex = hostAndPort.lastIndexOf(':');\n const host = hostAndPort.substring(0, portIndex);\n const useSsl = isCloudWorkstation(host);\n repo.repoInfo_ = new RepoInfo(\n hostAndPort,\n /* secure= */ useSsl,\n repo.repoInfo_.namespace,\n repo.repoInfo_.webSocketOnly,\n repo.repoInfo_.nodeAdmin,\n repo.repoInfo_.persistenceKey,\n repo.repoInfo_.includeNamespaceInQueryParams,\n /*isUsingEmulator=*/ true,\n emulatorOptions\n );\n\n if (tokenProvider) {\n repo.authTokenProvider_ = tokenProvider;\n }\n}\n\n/**\n * This function should only ever be called to CREATE a new database instance.\n * @internal\n */\nexport function repoManagerDatabaseFromApp(\n app: FirebaseApp,\n authProvider: Provider,\n appCheckProvider?: Provider,\n url?: string,\n nodeAdmin?: boolean\n): Database {\n let dbUrl: string | undefined = url || app.options.databaseURL;\n if (dbUrl === undefined) {\n if (!app.options.projectId) {\n fatal(\n \"Can't determine Firebase Database URL. Be sure to include \" +\n ' a Project ID when calling firebase.initializeApp().'\n );\n }\n\n log('Using default host for project ', app.options.projectId);\n dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;\n }\n\n let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\n let repoInfo = parsedUrl.repoInfo;\n\n let isEmulator: boolean;\n\n let dbEmulatorHost: string | undefined = undefined;\n if (typeof process !== 'undefined' && process.env) {\n dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];\n }\n\n if (dbEmulatorHost) {\n isEmulator = true;\n dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;\n parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\n repoInfo = parsedUrl.repoInfo;\n } else {\n isEmulator = !parsedUrl.repoInfo.secure;\n }\n\n const authTokenProvider =\n nodeAdmin && isEmulator\n ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)\n : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);\n\n validateUrl('Invalid Firebase Database URL', parsedUrl);\n if (!pathIsEmpty(parsedUrl.path)) {\n fatal(\n 'Database URL must point to the root of a Firebase Database ' +\n '(not including a child path).'\n );\n }\n\n const repo = repoManagerCreateRepo(\n repoInfo,\n app,\n authTokenProvider,\n new AppCheckTokenProvider(app, appCheckProvider)\n );\n return new Database(repo, app);\n}\n\n/**\n * Remove the repo and make sure it is disconnected.\n *\n */\nfunction repoManagerDeleteRepo(repo: Repo, appName: string): void {\n const appRepos = repos[appName];\n // This should never happen...\n if (!appRepos || appRepos[repo.key] !== repo) {\n fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);\n }\n repoInterrupt(repo);\n delete appRepos[repo.key];\n}\n\n/**\n * Ensures a repo doesn't already exist and then creates one using the\n * provided app.\n *\n * @param repoInfo - The metadata about the Repo\n * @returns The Repo object for the specified server / repoName.\n */\nfunction repoManagerCreateRepo(\n repoInfo: RepoInfo,\n app: FirebaseApp,\n authTokenProvider: AuthTokenProvider,\n appCheckProvider: AppCheckTokenProvider\n): Repo {\n let appRepos = repos[app.name];\n\n if (!appRepos) {\n appRepos = {};\n repos[app.name] = appRepos;\n }\n\n let repo = appRepos[repoInfo.toURLString()];\n if (repo) {\n fatal(\n 'Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.'\n );\n }\n repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);\n appRepos[repoInfo.toURLString()] = repo;\n\n return repo;\n}\n\n/**\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\n */\nexport function repoManagerForceRestClient(forceRestClient: boolean): void {\n useRestClient = forceRestClient;\n}\n\n/**\n * Class representing a Firebase Realtime Database.\n */\nexport class Database implements _FirebaseService {\n /** Represents a `Database` instance. */\n readonly 'type' = 'database';\n\n /** Track if the instance has been used (root or repo accessed) */\n _instanceStarted: boolean = false;\n\n /** Backing state for root_ */\n private _rootInternal?: ReferenceImpl;\n\n /** @hideconstructor */\n constructor(\n public _repoInternal: Repo,\n /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */\n readonly app: FirebaseApp\n ) {}\n\n get _repo(): Repo {\n if (!this._instanceStarted) {\n repoStart(\n this._repoInternal,\n this.app.options.appId,\n this.app.options['databaseAuthVariableOverride']\n );\n this._instanceStarted = true;\n }\n return this._repoInternal;\n }\n\n get _root(): ReferenceImpl {\n if (!this._rootInternal) {\n this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());\n }\n return this._rootInternal;\n }\n\n _delete(): Promise {\n if (this._rootInternal !== null) {\n repoManagerDeleteRepo(this._repo, this.app.name);\n this._repoInternal = null;\n this._rootInternal = null;\n }\n return Promise.resolve();\n }\n\n _checkNotDeleted(apiName: string) {\n if (this._rootInternal === null) {\n fatal('Cannot call ' + apiName + ' on a deleted database.');\n }\n }\n}\n\nfunction checkTransportInit() {\n if (TransportManager.IS_TRANSPORT_INITIALIZED) {\n warn(\n 'Transport has already been initialized. Please call this function before calling ref or setting up a listener'\n );\n }\n}\n\n/**\n * Force the use of websockets instead of longPolling.\n */\nexport function forceWebSockets() {\n checkTransportInit();\n BrowserPollConnection.forceDisallow();\n}\n\n/**\n * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.\n */\nexport function forceLongPolling() {\n checkTransportInit();\n WebSocketConnection.forceDisallow();\n BrowserPollConnection.forceAllow();\n}\n\n/**\n * Returns the instance of the Realtime Database SDK that is associated with the provided\n * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if\n * no instance exists or if the existing instance uses a custom database URL.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime\n * Database instance is associated with.\n * @param url - The URL of the Realtime Database instance to connect to. If not\n * provided, the SDK connects to the default instance of the Firebase App.\n * @returns The `Database` instance of the provided app.\n */\nexport function getDatabase(\n app: FirebaseApp = getApp(),\n url?: string\n): Database {\n const db = _getProvider(app, 'database').getImmediate({\n identifier: url\n }) as Database;\n if (!db._instanceStarted) {\n const emulator = getDefaultEmulatorHostnameAndPort('database');\n if (emulator) {\n connectDatabaseEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * Modify the provided instance to communicate with the Realtime Database\n * emulator.\n *\n *

Note: This method must be called before performing any other operation.\n *\n * @param db - The instance to modify.\n * @param host - The emulator host (ex: localhost)\n * @param port - The emulator port (ex: 8080)\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\n */\nexport function connectDatabaseEmulator(\n db: Database,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n db = getModularInstance(db);\n db._checkNotDeleted('useEmulator');\n\n const hostAndPort = `${host}:${port}`;\n const repo = db._repoInternal;\n if (db._instanceStarted) {\n // If the instance has already been started, then silenty fail if this function is called again\n // with the same parameters. If the parameters differ then assert.\n if (\n hostAndPort === db._repoInternal.repoInfo_.host &&\n deepEqual(options, repo.repoInfo_.emulatorOptions)\n ) {\n return;\n }\n fatal(\n 'connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.'\n );\n }\n\n let tokenProvider: EmulatorTokenProvider | undefined = undefined;\n if (repo.repoInfo_.nodeAdmin) {\n if (options.mockUserToken) {\n fatal(\n 'mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the \"firebase\" package instead of \"firebase-admin\".'\n );\n }\n tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);\n } else if (options.mockUserToken) {\n const token =\n typeof options.mockUserToken === 'string'\n ? options.mockUserToken\n : createMockUserToken(options.mockUserToken, db.app.options.projectId);\n tokenProvider = new EmulatorTokenProvider(token);\n }\n\n // Workaround to get cookies in Firebase Studio\n if (isCloudWorkstation(host)) {\n void pingServer(host);\n updateEmulatorBanner('Database', true);\n }\n\n // Modify the repo to apply emulator settings\n repoManagerApplyEmulatorSettings(repo, hostAndPort, options, tokenProvider);\n}\n\n/**\n * Disconnects from the server (all Database operations will be completed\n * offline).\n *\n * The client automatically maintains a persistent connection to the Database\n * server, which will remain active indefinitely and reconnect when\n * disconnected. However, the `goOffline()` and `goOnline()` methods may be used\n * to control the client connection in cases where a persistent connection is\n * undesirable.\n *\n * While offline, the client will no longer receive data updates from the\n * Database. However, all Database operations performed locally will continue to\n * immediately fire events, allowing your application to continue behaving\n * normally. Additionally, each operation performed locally will automatically\n * be queued and retried upon reconnection to the Database server.\n *\n * To reconnect to the Database and begin receiving remote events, see\n * `goOnline()`.\n *\n * @param db - The instance to disconnect.\n */\nexport function goOffline(db: Database): void {\n db = getModularInstance(db);\n db._checkNotDeleted('goOffline');\n repoInterrupt(db._repo);\n}\n\n/**\n * Reconnects to the server and synchronizes the offline Database state\n * with the server state.\n *\n * This method should be used after disabling the active connection with\n * `goOffline()`. Once reconnected, the client will transmit the proper data\n * and fire the appropriate events so that your client \"catches up\"\n * automatically.\n *\n * @param db - The instance to reconnect.\n */\nexport function goOnline(db: Database): void {\n db = getModularInstance(db);\n db._checkNotDeleted('goOnline');\n repoResume(db._repo);\n}\n\n/**\n * Logs debugging information to the console.\n *\n * @param enabled - Enables logging if `true`, disables logging if `false`.\n * @param persistent - Remembers the logging state between page refreshes if\n * `true`.\n */\nexport function enableLogging(enabled: boolean, persistent?: boolean);\n\n/**\n * Logs debugging information to the console.\n *\n * @param logger - A custom logger function to control how things get logged.\n */\nexport function enableLogging(logger: (message: string) => unknown);\n\nexport function enableLogging(\n logger: boolean | ((message: string) => unknown),\n persistent?: boolean\n): void {\n enableLoggingImpl(logger, persistent);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { name, version } from '../package.json';\nimport { setSDKVersion } from '../src/core/version';\n\nimport { repoManagerDatabaseFromApp } from './api/Database';\n\nexport function registerDatabase(variant?: string): void {\n setSDKVersion(SDK_VERSION);\n _registerComponent(\n new Component(\n 'database',\n (container, { instanceIdentifier: url }) => {\n const app = container.getProvider('app').getImmediate()!;\n const authProvider = container.getProvider('auth-internal');\n const appCheckProvider = container.getProvider('app-check-internal');\n return repoManagerDatabaseFromApp(\n app,\n authProvider,\n appCheckProvider,\n url\n );\n },\n ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n registerVersion(name, version, variant);\n // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst SERVER_TIMESTAMP = {\n '.sv': 'timestamp'\n};\n\n/**\n * Returns a placeholder value for auto-populating the current timestamp (time\n * since the Unix epoch, in milliseconds) as determined by the Firebase\n * servers.\n */\nexport function serverTimestamp(): object {\n return SERVER_TIMESTAMP;\n}\n\n/**\n * Returns a placeholder value that can be used to atomically increment the\n * current database value by the provided delta.\n *\n * @param delta - the amount to modify the current value atomically.\n * @returns A placeholder value for modifying data atomically server-side.\n */\nexport function increment(delta: number): object {\n return {\n '.sv': {\n 'increment': delta\n }\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance, Deferred } from '@firebase/util';\n\nimport { repoStartTransaction } from '../core/Repo';\nimport { PRIORITY_INDEX } from '../core/snap/indexes/PriorityIndex';\nimport { Node } from '../core/snap/Node';\nimport { validateWritablePath } from '../core/util/validation';\n\nimport { DatabaseReference } from './Reference';\nimport { DataSnapshot, onValue, ReferenceImpl } from './Reference_impl';\n\n/** An options object to configure transactions. */\nexport interface TransactionOptions {\n /**\n * By default, events are raised each time the transaction update function\n * runs. So if it is run multiple times, you may see intermediate states. You\n * can set this to false to suppress these intermediate states and instead\n * wait until the transaction has completed before events are raised.\n */\n readonly applyLocally?: boolean;\n}\n\n/**\n * A type for the resolve value of {@link runTransaction}.\n */\nexport class TransactionResult {\n /** @hideconstructor */\n constructor(\n /** Whether the transaction was successfully committed. */\n readonly committed: boolean,\n /** The resulting data snapshot. */\n readonly snapshot: DataSnapshot\n ) {}\n\n /** Returns a JSON-serializable representation of this object. */\n toJSON(): object {\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n }\n}\n\n/**\n * Atomically modifies the data at this location.\n *\n * Atomically modify the data at this location. Unlike a normal `set()`, which\n * just overwrites the data regardless of its previous value, `runTransaction()` is\n * used to modify the existing value to a new value, ensuring there are no\n * conflicts with other clients writing to the same location at the same time.\n *\n * To accomplish this, you pass `runTransaction()` an update function which is\n * used to transform the current value into a new value. If another client\n * writes to the location before your new value is successfully written, your\n * update function will be called again with the new current value, and the\n * write will be retried. This will happen repeatedly until your write succeeds\n * without conflict or you abort the transaction by not returning a value from\n * your update function.\n *\n * Note: Modifying data with `set()` will cancel any pending transactions at\n * that location, so extreme care should be taken if mixing `set()` and\n * `runTransaction()` to update the same data.\n *\n * Note: When using transactions with Security and Firebase Rules in place, be\n * aware that a client needs `.read` access in addition to `.write` access in\n * order to perform a transaction. This is because the client-side nature of\n * transactions requires the client to read the data in order to transactionally\n * update it.\n *\n * @param ref - The location to atomically modify.\n * @param transactionUpdate - A developer-supplied function which will be passed\n * the current data stored at this location (as a JavaScript object). The\n * function should return the new value it would like written (as a JavaScript\n * object). If `undefined` is returned (i.e. you return with no arguments) the\n * transaction will be aborted and the data at this location will not be\n * modified.\n * @param options - An options object to configure transactions.\n * @returns A `Promise` that can optionally be used instead of the `onComplete`\n * callback to handle success and failure.\n */\nexport function runTransaction(\n ref: DatabaseReference,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n transactionUpdate: (currentData: any) => unknown,\n options?: TransactionOptions\n): Promise {\n ref = getModularInstance(ref);\n\n validateWritablePath('Reference.transaction', ref._path);\n\n if (ref.key === '.length' || ref.key === '.keys') {\n throw (\n 'Reference.transaction failed: ' + ref.key + ' is a read-only object.'\n );\n }\n\n const applyLocally = options?.applyLocally ?? true;\n const deferred = new Deferred();\n\n const promiseComplete = (\n error: Error | null,\n committed: boolean,\n node: Node | null\n ) => {\n let dataSnapshot: DataSnapshot | null = null;\n if (error) {\n deferred.reject(error);\n } else {\n dataSnapshot = new DataSnapshot(\n node,\n new ReferenceImpl(ref._repo, ref._path),\n PRIORITY_INDEX\n );\n deferred.resolve(new TransactionResult(committed, dataSnapshot));\n }\n };\n\n // Add a watch to make sure we get server updates.\n const unwatcher = onValue(ref, () => {});\n\n repoStartTransaction(\n ref._repo,\n ref._path,\n transactionUpdate,\n promiseComplete,\n unwatcher,\n applyLocally\n );\n\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PersistentConnection } from '../core/PersistentConnection';\nimport { RepoInfo } from '../core/RepoInfo';\nimport { Connection } from '../realtime/Connection';\n\nimport { repoManagerForceRestClient } from './Database';\n\nexport const DataConnection = PersistentConnection;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(PersistentConnection.prototype as any).simpleListen = function (\n pathString: string,\n onComplete: (a: unknown) => void\n) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(PersistentConnection.prototype as any).echo = function (\n data: unknown,\n onEcho: (a: unknown) => void\n) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n\n// RealTimeConnection properties that we use in tests.\nexport const RealTimeConnection = Connection;\n\n/**\n * @internal\n */\nexport const hijackHash = function (newHash: () => string) {\n const oldPut = PersistentConnection.prototype.put;\n PersistentConnection.prototype.put = function (\n pathString,\n data,\n onComplete,\n hash\n ) {\n if (hash !== undefined) {\n hash = newHash();\n }\n oldPut.call(this, pathString, data, onComplete, hash);\n };\n return function () {\n PersistentConnection.prototype.put = oldPut;\n };\n};\n\nexport const ConnectionTarget = RepoInfo;\n\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n * @internal\n */\nexport const forceRestClient = function (forceRestClient: boolean) {\n repoManagerForceRestClient(forceRestClient);\n};\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebaseAppCheckInternal,\n AppCheckInternalComponentName\n} from '@firebase/app-check-interop-types';\nimport { FirebaseApp } from '@firebase/app-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n Provider\n} from '@firebase/component';\n\nimport { repoManagerDatabaseFromApp } from '../api/Database';\nimport { Database } from '../api.standalone';\nimport { setSDKVersion } from '../core/version';\n\n/**\n * Used by console to create a database based on the app,\n * passed database URL and a custom auth implementation.\n * @internal\n * @param app - A valid FirebaseApp-like object\n * @param url - A valid Firebase databaseURL\n * @param version - custom version e.g. firebase-admin version\n * @param customAppCheckImpl - custom app check implementation\n * @param customAuthImpl - custom auth implementation\n */\nexport function _initStandalone({\n app,\n url,\n version,\n customAuthImpl,\n customAppCheckImpl,\n nodeAdmin = false\n}: {\n app: FirebaseApp;\n url: string;\n version: string;\n customAuthImpl: FirebaseAuthInternal;\n customAppCheckImpl?: FirebaseAppCheckInternal;\n nodeAdmin?: boolean;\n}): Database {\n setSDKVersion(version);\n\n /**\n * ComponentContainer('database-standalone') is just a placeholder that doesn't perform\n * any actual function.\n */\n const componentContainer = new ComponentContainer('database-standalone');\n const authProvider = new Provider(\n 'auth-internal',\n componentContainer\n );\n let appCheckProvider: Provider;\n if (customAppCheckImpl) {\n appCheckProvider = new Provider(\n 'app-check-internal',\n componentContainer\n );\n appCheckProvider.setComponent(\n new Component(\n 'app-check-internal',\n () => customAppCheckImpl,\n ComponentType.PRIVATE\n )\n );\n }\n authProvider.setComponent(\n new Component('auth-internal', () => customAuthImpl, ComponentType.PRIVATE)\n );\n\n return repoManagerDatabaseFromApp(\n app,\n authProvider,\n appCheckProvider,\n url,\n nodeAdmin\n );\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Use default import to import a cjs library, so we can provide a esm entrypoint for Nodejs.\n// We can't use named import here because otherwise you will get the following error:\n// \"SyntaxError: Named export 'Client' not found. The requested module 'faye-websocket' is a CommonJS module\".\n// We can change back to using named imports once the lib provides an esm build, however they are not planning to.\n// see https://github.com/faye/faye-websocket-node/issues/82\nimport Websocket from 'faye-websocket';\n\nimport { setWebSocketImpl } from '../src/realtime/WebSocketConnection';\n\nimport { registerDatabase } from './register';\n\nsetWebSocketImpl(Websocket.Client);\n\nexport * from './api';\n\nregisterDatabase('node');\n"],"names":["enableLogging","MAX_NODE","setMaxNode","nodeFromJSON","setPriorityMaxNode","referenceConstructor","errorPrefixFxn","errorPrefix","enableLoggingImpl","SDK_VERSION"],"mappings":";;;;;;AAAA;;;;;;;;;;;;;;;AAeG;AAEI,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAE7B,MAAM,aAAa,GAAG,GAAG,CAAC;AAE1B,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAEpC,MAAM,aAAa,GAAG,GAAG,CAAC;AAE1B,MAAM,SAAS,GAAG,GAAG,CAAC;AAE7B;AACA;AACO,MAAM,eAAe,GAC1B,4EAA4E,CAAC;AAExE,MAAM,kBAAkB,GAAG,IAAI,CAAC;AAEhC,MAAM,oBAAoB,GAAG,GAAG,CAAC;AAEjC,MAAM,qBAAqB,GAAG,IAAI,CAAC;AAEnC,MAAM,SAAS,GAAG,WAAW,CAAC;AAE9B,MAAM,YAAY,GAAG,cAAc;;ACxC1C;;;;;;;;;;;;;;;AAeG;AAIH;;;;;;;;AAQG;MACU,iBAAiB,CAAA;AAI5B;;AAEG;AACH,IAAA,WAAA,CAAoB,WAAoB,EAAA;QAApB,IAAW,CAAA,WAAA,GAAX,WAAW,CAAS;;QALhC,IAAO,CAAA,OAAA,GAAG,WAAW,CAAC;KAKc;AAE5C;;;AAGG;IACH,GAAG,CAAC,GAAW,EAAE,KAAqB,EAAA;AACpC,QAAA,IAAI,KAAK,IAAI,IAAI,EAAE;AACjB,YAAA,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,aAAa,CAAC,G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ACnB,CAAC;AACF,IAAA,IAAI,gBAAyD,CAAC;IAC9D,IAAI,kBAAkB,EAAE;QACtB,gBAAgB,GAAG,IAAI,QAAQ,CAC7B,oBAAoB,EACpB,kBAAkB,CACnB,CAAC;AACF,QAAA,gBAAgB,CAAC,YAAY,CAC3B,IAAI,SAAS,CACX,oBAAoB,EACpB,MAAM,kBAAkB,EAAA,SAAA,6BAEzB,CACF,CAAC;KACH;AACD,IAAA,YAAY,CAAC,YAAY,CACvB,IAAI,SAAS,CAAC,eAAe,EAAE,MAAM,cAAc,EAAA,SAAA,6BAAwB,CAC5E,CAAC;AAEF,IAAA,OAAO,0BAA0B,CAC/B,GAAG,EACH,YAAY,EACZ,gBAAgB,EAChB,GAAG,EACH,SAAS,CACV,CAAC;AACJ;;AClGA;;;;;;;;;;;;;;;AAeG;AAaH,gBAAgB,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;AAInC,gBAAgB,CAAC,MAAM,CAAC;;;;"} \ No newline at end of file diff --git a/node_modules/@firebase/database/dist/node-esm/package.json b/node_modules/@firebase/database/dist/node-esm/package.json new file mode 100644 index 0000000..7c34deb --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/package.json @@ -0,0 +1 @@ +{"type":"module"} \ No newline at end of file diff --git a/node_modules/@firebase/database/dist/node-esm/src/api.d.ts b/node_modules/@firebase/database/dist/node-esm/src/api.d.ts new file mode 100644 index 0000000..26bc1ee --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/api.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './api.standalone'; +export { getDatabase } from './api/Database'; diff --git a/node_modules/@firebase/database/dist/node-esm/src/api.standalone.d.ts b/node_modules/@firebase/database/dist/node-esm/src/api.standalone.d.ts new file mode 100644 index 0000000..1c65ab6 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/api.standalone.d.ts @@ -0,0 +1,30 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { Database, EmulatorMockTokenOptions, enableLogging, goOffline, goOnline, forceWebSockets, forceLongPolling, connectDatabaseEmulator } from './api/Database'; +export { Query, DatabaseReference, ListenOptions, Unsubscribe, ThenableReference } from './api/Reference'; +export { OnDisconnect } from './api/OnDisconnect'; +export { DataSnapshot, EventType, IteratedDataSnapshot, QueryConstraint, QueryConstraintType, endAt, endBefore, equalTo, get, limitToFirst, limitToLast, off, onChildAdded, onChildChanged, onChildMoved, onChildRemoved, onDisconnect, onValue, orderByChild, orderByKey, orderByPriority, orderByValue, push, query, ref, refFromURL, remove, set, setPriority, setWithPriority, startAfter, startAt, update, child } from './api/Reference_impl'; +export { increment, serverTimestamp } from './api/ServerValue'; +export { runTransaction, TransactionOptions, TransactionResult } from './api/Transaction'; +export { setSDKVersion as _setSDKVersion } from './core/version'; +export { ReferenceImpl as _ReferenceImpl, QueryImpl as _QueryImpl } from './api/Reference_impl'; +export { repoManagerDatabaseFromApp as _repoManagerDatabaseFromApp } from './api/Database'; +export { validatePathString as _validatePathString, validateWritablePath as _validateWritablePath } from './core/util/validation'; +export { UserCallback as _UserCallback } from './core/view/EventRegistration'; +export { QueryParams as _QueryParams } from './core/view/QueryParams'; +export { hijackHash as _TEST_ACCESS_hijackHash, forceRestClient as _TEST_ACCESS_forceRestClient } from './api/test_access'; +export * from './internal/index'; diff --git a/node_modules/@firebase/database/dist/node-esm/src/api/Database.d.ts b/node_modules/@firebase/database/dist/node-esm/src/api/Database.d.ts new file mode 100644 index 0000000..9a79baf --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/api/Database.d.ts @@ -0,0 +1,137 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { _FirebaseService, FirebaseApp } from '@firebase/app'; +import { AppCheckInternalComponentName } from '@firebase/app-check-interop-types'; +import { FirebaseAuthInternalName } from '@firebase/auth-interop-types'; +import { Provider } from '@firebase/component'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { Repo } from '../core/Repo'; +import { ReferenceImpl } from './Reference_impl'; +export { EmulatorMockTokenOptions } from '@firebase/util'; +/** + * This function should only ever be called to CREATE a new database instance. + * @internal + */ +export declare function repoManagerDatabaseFromApp(app: FirebaseApp, authProvider: Provider, appCheckProvider?: Provider, url?: string, nodeAdmin?: boolean): Database; +/** + * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos. + */ +export declare function repoManagerForceRestClient(forceRestClient: boolean): void; +/** + * Class representing a Firebase Realtime Database. + */ +export declare class Database implements _FirebaseService { + _repoInternal: Repo; + /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */ + readonly app: FirebaseApp; + /** Represents a `Database` instance. */ + readonly 'type' = "database"; + /** Track if the instance has been used (root or repo accessed) */ + _instanceStarted: boolean; + /** Backing state for root_ */ + private _rootInternal?; + /** @hideconstructor */ + constructor(_repoInternal: Repo, + /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */ + app: FirebaseApp); + get _repo(): Repo; + get _root(): ReferenceImpl; + _delete(): Promise; + _checkNotDeleted(apiName: string): void; +} +/** + * Force the use of websockets instead of longPolling. + */ +export declare function forceWebSockets(): void; +/** + * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL. + */ +export declare function forceLongPolling(): void; +/** + * Returns the instance of the Realtime Database SDK that is associated with the provided + * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if + * no instance exists or if the existing instance uses a custom database URL. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime + * Database instance is associated with. + * @param url - The URL of the Realtime Database instance to connect to. If not + * provided, the SDK connects to the default instance of the Firebase App. + * @returns The `Database` instance of the provided app. + */ +export declare function getDatabase(app?: FirebaseApp, url?: string): Database; +/** + * Modify the provided instance to communicate with the Realtime Database + * emulator. + * + *

Note: This method must be called before performing any other operation. + * + * @param db - The instance to modify. + * @param host - The emulator host (ex: localhost) + * @param port - The emulator port (ex: 8080) + * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules + */ +export declare function connectDatabaseEmulator(db: Database, host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions | string; +}): void; +/** + * Disconnects from the server (all Database operations will be completed + * offline). + * + * The client automatically maintains a persistent connection to the Database + * server, which will remain active indefinitely and reconnect when + * disconnected. However, the `goOffline()` and `goOnline()` methods may be used + * to control the client connection in cases where a persistent connection is + * undesirable. + * + * While offline, the client will no longer receive data updates from the + * Database. However, all Database operations performed locally will continue to + * immediately fire events, allowing your application to continue behaving + * normally. Additionally, each operation performed locally will automatically + * be queued and retried upon reconnection to the Database server. + * + * To reconnect to the Database and begin receiving remote events, see + * `goOnline()`. + * + * @param db - The instance to disconnect. + */ +export declare function goOffline(db: Database): void; +/** + * Reconnects to the server and synchronizes the offline Database state + * with the server state. + * + * This method should be used after disabling the active connection with + * `goOffline()`. Once reconnected, the client will transmit the proper data + * and fire the appropriate events so that your client "catches up" + * automatically. + * + * @param db - The instance to reconnect. + */ +export declare function goOnline(db: Database): void; +/** + * Logs debugging information to the console. + * + * @param enabled - Enables logging if `true`, disables logging if `false`. + * @param persistent - Remembers the logging state between page refreshes if + * `true`. + */ +export declare function enableLogging(enabled: boolean, persistent?: boolean): any; +/** + * Logs debugging information to the console. + * + * @param logger - A custom logger function to control how things get logged. + */ +export declare function enableLogging(logger: (message: string) => unknown): any; diff --git a/node_modules/@firebase/database/dist/node-esm/src/api/OnDisconnect.d.ts b/node_modules/@firebase/database/dist/node-esm/src/api/OnDisconnect.d.ts new file mode 100644 index 0000000..bbae779 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/api/OnDisconnect.d.ts @@ -0,0 +1,110 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Repo } from '../core/Repo'; +import { Path } from '../core/util/Path'; +/** + * The `onDisconnect` class allows you to write or clear data when your client + * disconnects from the Database server. These updates occur whether your + * client disconnects cleanly or not, so you can rely on them to clean up data + * even if a connection is dropped or a client crashes. + * + * The `onDisconnect` class is most commonly used to manage presence in + * applications where it is useful to detect how many clients are connected and + * when other clients disconnect. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * To avoid problems when a connection is dropped before the requests can be + * transferred to the Database server, these functions should be called before + * writing any data. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time you reconnect. + */ +export declare class OnDisconnect { + private _repo; + private _path; + /** @hideconstructor */ + constructor(_repo: Repo, _path: Path); + /** + * Cancels all previously queued `onDisconnect()` set or update events for this + * location and all children. + * + * If a write has been queued for this location via a `set()` or `update()` at a + * parent location, the write at this location will be canceled, though writes + * to sibling locations will still occur. + * + * @returns Resolves when synchronization to the server is complete. + */ + cancel(): Promise; + /** + * Ensures the data at this location is deleted when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + * + * @returns Resolves when synchronization to the server is complete. + */ + remove(): Promise; + /** + * Ensures the data at this location is set to the specified value when the + * client is disconnected (due to closing the browser, navigating to a new page, + * or network issues). + * + * `set()` is especially useful for implementing "presence" systems, where a + * value should be changed or cleared when a user disconnects so that they + * appear "offline" to other users. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time. + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + set(value: unknown): Promise; + /** + * Ensures the data at this location is set to the specified value and priority + * when the client is disconnected (due to closing the browser, navigating to a + * new page, or network issues). + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + setWithPriority(value: unknown, priority: number | string | null): Promise; + /** + * Writes multiple values at this location when the client is disconnected (due + * to closing the browser, navigating to a new page, or network issues). + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, "name/first") + * from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * @param values - Object containing multiple values. + * @returns Resolves when synchronization to the Database is complete. + */ + update(values: object): Promise; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/api/Reference.d.ts b/node_modules/@firebase/database/dist/node-esm/src/api/Reference.d.ts new file mode 100644 index 0000000..0d9e054 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/api/Reference.d.ts @@ -0,0 +1,124 @@ +import { Repo } from '../core/Repo'; +import { Path } from '../core/util/Path'; +import { QueryContext } from '../core/view/EventRegistration'; +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` sorts and filters the data at a Database location so only a subset + * of the child data is included. This can be used to order a collection of + * data by some attribute (for example, height of dinosaurs) as well as to + * restrict a large list of items (for example, chat messages) down to a number + * suitable for synchronizing to the client. Queries are created by chaining + * together one or more of the filter methods defined here. + * + * Just as with a `DatabaseReference`, you can receive data from a `Query` by using the + * `on*()` methods. You will only receive events and `DataSnapshot`s for the + * subset of the data that matches your query. + * + * See {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data} + * for more information. + */ +export interface Query extends QueryContext { + /** The `DatabaseReference` for the `Query`'s location. */ + readonly ref: DatabaseReference; + /** + * Returns whether or not the current and provided queries represent the same + * location, have the same query parameters, and are from the same instance of + * `FirebaseApp`. + * + * Two `DatabaseReference` objects are equivalent if they represent the same location + * and are from the same instance of `FirebaseApp`. + * + * Two `Query` objects are equivalent if they represent the same location, + * have the same query parameters, and are from the same instance of + * `FirebaseApp`. Equivalent queries share the same sort order, limits, and + * starting and ending points. + * + * @param other - The query to compare against. + * @returns Whether or not the current and provided queries are equivalent. + */ + isEqual(other: Query | null): boolean; + /** + * Returns a JSON-serializable representation of this object. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON(): string; + /** + * Gets the absolute URL for this location. + * + * The `toString()` method returns a URL that is ready to be put into a + * browser, curl command, or a `refFromURL()` call. Since all of those expect + * the URL to be url-encoded, `toString()` returns an encoded URL. + * + * Append '.json' to the returned URL when typed into a browser to download + * JSON-formatted data. If the location is secured (that is, not publicly + * readable), you will get a permission-denied error. + * + * @returns The absolute URL for this location. + */ + toString(): string; +} +/** + * A `DatabaseReference` represents a specific location in your Database and can be used + * for reading or writing data to that Database location. + * + * You can reference the root or child location in your Database by calling + * `ref()` or `ref("child/path")`. + * + * Writing is done with the `set()` method and reading can be done with the + * `on*()` method. See {@link + * https://firebase.google.com/docs/database/web/read-and-write} + */ +export interface DatabaseReference extends Query { + /** + * The last part of the `DatabaseReference`'s path. + * + * For example, `"ada"` is the key for + * `https://.firebaseio.com/users/ada`. + * + * The key of a root `DatabaseReference` is `null`. + */ + readonly key: string | null; + /** + * The parent location of a `DatabaseReference`. + * + * The parent of a root `DatabaseReference` is `null`. + */ + readonly parent: DatabaseReference | null; + /** The root `DatabaseReference` of the Database. */ + readonly root: DatabaseReference; +} +/** + * A `Promise` that can also act as a `DatabaseReference` when returned by + * {@link push}. The reference is available immediately and the `Promise` resolves + * as the write to the backend completes. + */ +export interface ThenableReference extends DatabaseReference, Pick, 'then' | 'catch'> { + key: string; + parent: DatabaseReference; +} +/** A callback that can invoked to remove a listener. */ +export type Unsubscribe = () => void; +/** An options objects that can be used to customize a listener. */ +export interface ListenOptions { + /** Whether to remove the listener after its first invocation. */ + readonly onlyOnce?: boolean; +} +export interface ReferenceConstructor { + new (repo: Repo, path: Path): DatabaseReference; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/api/Reference_impl.d.ts b/node_modules/@firebase/database/dist/node-esm/src/api/Reference_impl.d.ts new file mode 100644 index 0000000..873e00e --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/api/Reference_impl.d.ts @@ -0,0 +1,1100 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Repo } from '../core/Repo'; +import { Index } from '../core/snap/indexes/Index'; +import { Node } from '../core/snap/Node'; +import { Path } from '../core/util/Path'; +import { Change } from '../core/view/Change'; +import { CancelEvent, DataEvent, EventType } from '../core/view/Event'; +import { CallbackContext, EventRegistration, QueryContext } from '../core/view/EventRegistration'; +import { QueryParams } from '../core/view/QueryParams'; +import { Database } from './Database'; +import { OnDisconnect } from './OnDisconnect'; +import { ListenOptions, Query as Query, DatabaseReference, Unsubscribe, ThenableReference } from './Reference'; +/** + * @internal + */ +export declare class QueryImpl implements Query, QueryContext { + readonly _repo: Repo; + readonly _path: Path; + readonly _queryParams: QueryParams; + readonly _orderByCalled: boolean; + /** + * @hideconstructor + */ + constructor(_repo: Repo, _path: Path, _queryParams: QueryParams, _orderByCalled: boolean); + get key(): string | null; + get ref(): DatabaseReference; + get _queryIdentifier(): string; + /** + * An object representation of the query parameters used by this Query. + */ + get _queryObject(): object; + isEqual(other: QueryImpl | null): boolean; + toJSON(): string; + toString(): string; +} +/** + * @internal + */ +export declare class ReferenceImpl extends QueryImpl implements DatabaseReference { + /** @hideconstructor */ + constructor(repo: Repo, path: Path); + get parent(): ReferenceImpl | null; + get root(): ReferenceImpl; +} +/** + * A `DataSnapshot` contains data from a Database location. + * + * Any time you read data from the Database, you receive the data as a + * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach + * with `on()` or `once()`. You can extract the contents of the snapshot as a + * JavaScript object by calling the `val()` method. Alternatively, you can + * traverse into the snapshot by calling `child()` to return child snapshots + * (which you could then call `val()` on). + * + * A `DataSnapshot` is an efficiently generated, immutable copy of the data at + * a Database location. It cannot be modified and will never change (to modify + * data, you always call the `set()` method on a `Reference` directly). + */ +export declare class DataSnapshot { + readonly _node: Node; + /** + * The location of this DataSnapshot. + */ + readonly ref: DatabaseReference; + readonly _index: Index; + /** + * @param _node - A SnapshotNode to wrap. + * @param ref - The location this snapshot came from. + * @param _index - The iteration order for this snapshot + * @hideconstructor + */ + constructor(_node: Node, + /** + * The location of this DataSnapshot. + */ + ref: DatabaseReference, _index: Index); + /** + * Gets the priority value of the data in this `DataSnapshot`. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data} + * ). + */ + get priority(): string | number | null; + /** + * The key (last part of the path) of the location of this `DataSnapshot`. + * + * The last token in a Database location is considered its key. For example, + * "ada" is the key for the /users/ada/ node. Accessing the key on any + * `DataSnapshot` will return the key for the location that generated it. + * However, accessing the key on the root URL of a Database will return + * `null`. + */ + get key(): string | null; + /** Returns the number of child properties of this `DataSnapshot`. */ + get size(): number; + /** + * Gets another `DataSnapshot` for the location at the specified relative path. + * + * Passing a relative path to the `child()` method of a DataSnapshot returns + * another `DataSnapshot` for the location at the specified relative path. The + * relative path can either be a simple child name (for example, "ada") or a + * deeper, slash-separated path (for example, "ada/name/first"). If the child + * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot` + * whose value is `null`) is returned. + * + * @param path - A relative path to the location of child data. + */ + child(path: string): DataSnapshot; + /** + * Returns true if this `DataSnapshot` contains any data. It is slightly more + * efficient than using `snapshot.val() !== null`. + */ + exists(): boolean; + /** + * Exports the entire contents of the DataSnapshot as a JavaScript object. + * + * The `exportVal()` method is similar to `val()`, except priority information + * is included (if available), making it suitable for backing up your data. + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + exportVal(): any; + /** + * Enumerates the top-level children in the `IteratedDataSnapshot`. + * + * Because of the way JavaScript objects work, the ordering of data in the + * JavaScript object returned by `val()` is not guaranteed to match the + * ordering on the server nor the ordering of `onChildAdded()` events. That is + * where `forEach()` comes in handy. It guarantees the children of a + * `DataSnapshot` will be iterated in their query order. + * + * If no explicit `orderBy*()` method is used, results are returned + * ordered by key (unless priorities are used, in which case, results are + * returned by priority). + * + * @param action - A function that will be called for each child DataSnapshot. + * The callback can return true to cancel further enumeration. + * @returns true if enumeration was canceled due to your callback returning + * true. + */ + forEach(action: (child: IteratedDataSnapshot) => boolean | void): boolean; + /** + * Returns true if the specified child path has (non-null) data. + * + * @param path - A relative path to the location of a potential child. + * @returns `true` if data exists at the specified child path; else + * `false`. + */ + hasChild(path: string): boolean; + /** + * Returns whether or not the `DataSnapshot` has any non-`null` child + * properties. + * + * You can use `hasChildren()` to determine if a `DataSnapshot` has any + * children. If it does, you can enumerate them using `forEach()`. If it + * doesn't, then either this snapshot contains a primitive value (which can be + * retrieved with `val()`) or it is empty (in which case, `val()` will return + * `null`). + * + * @returns true if this snapshot has any children; else false. + */ + hasChildren(): boolean; + /** + * Returns a JSON-serializable representation of this object. + */ + toJSON(): object | null; + /** + * Extracts a JavaScript value from a `DataSnapshot`. + * + * Depending on the data in a `DataSnapshot`, the `val()` method may return a + * scalar type (string, number, or boolean), an array, or an object. It may + * also return null, indicating that the `DataSnapshot` is empty (contains no + * data). + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + val(): any; +} +/** + * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined. + */ +export interface IteratedDataSnapshot extends DataSnapshot { + key: string; +} +/** + * + * Returns a `Reference` representing the location in the Database + * corresponding to the provided path. If no path is provided, the `Reference` + * will point to the root of the Database. + * + * @param db - The database instance to obtain a reference for. + * @param path - Optional path representing the location the returned + * `Reference` will point. If not provided, the returned `Reference` will + * point to the root of the Database. + * @returns If a path is provided, a `Reference` + * pointing to the provided path. Otherwise, a `Reference` pointing to the + * root of the Database. + */ +export declare function ref(db: Database, path?: string): DatabaseReference; +/** + * Returns a `Reference` representing the location in the Database + * corresponding to the provided Firebase URL. + * + * An exception is thrown if the URL is not a valid Firebase Database URL or it + * has a different domain than the current `Database` instance. + * + * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored + * and are not applied to the returned `Reference`. + * + * @param db - The database instance to obtain a reference for. + * @param url - The Firebase URL at which the returned `Reference` will + * point. + * @returns A `Reference` pointing to the provided + * Firebase URL. + */ +export declare function refFromURL(db: Database, url: string): DatabaseReference; +/** + * Gets a `Reference` for the location at the specified relative path. + * + * The relative path can either be a simple child name (for example, "ada") or + * a deeper slash-separated path (for example, "ada/name/first"). + * + * @param parent - The parent location. + * @param path - A relative path from this location to the desired child + * location. + * @returns The specified child location. + */ +export declare function child(parent: DatabaseReference, path: string): DatabaseReference; +/** + * Returns an `OnDisconnect` object - see + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information on how to use it. + * + * @param ref - The reference to add OnDisconnect triggers for. + */ +export declare function onDisconnect(ref: DatabaseReference): OnDisconnect; +export interface ThenableReferenceImpl extends ReferenceImpl, Pick, 'then' | 'catch'> { + key: string; + parent: ReferenceImpl; +} +/** + * Generates a new child location using a unique key and returns its + * `Reference`. + * + * This is the most common pattern for adding data to a collection of items. + * + * If you provide a value to `push()`, the value is written to the + * generated location. If you don't pass a value, nothing is written to the + * database and the child remains empty (but you can use the `Reference` + * elsewhere). + * + * The unique keys generated by `push()` are ordered by the current time, so the + * resulting list of items is chronologically sorted. The keys are also + * designed to be unguessable (they contain 72 random bits of entropy). + * + * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}. + * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}. + * + * @param parent - The parent location. + * @param value - Optional value to be written at the generated location. + * @returns Combined `Promise` and `Reference`; resolves when write is complete, + * but can be used immediately as the `Reference` to the child location. + */ +export declare function push(parent: DatabaseReference, value?: unknown): ThenableReference; +/** + * Removes the data at this Database location. + * + * Any data at child locations will also be deleted. + * + * The effect of the remove will be visible immediately and the corresponding + * event 'value' will be triggered. Synchronization of the remove to the + * Firebase servers will also be started, and the returned Promise will resolve + * when complete. If provided, the onComplete callback will be called + * asynchronously after synchronization has finished. + * + * @param ref - The location to remove. + * @returns Resolves when remove on server is complete. + */ +export declare function remove(ref: DatabaseReference): Promise; +/** + * Writes data to this Database location. + * + * This will overwrite any data at this location and all child locations. + * + * The effect of the write will be visible immediately, and the corresponding + * events ("value", "child_added", etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * Passing `null` for the new value is equivalent to calling `remove()`; namely, + * all data at this location and all child locations will be deleted. + * + * `set()` will remove any priority stored at this location, so if priority is + * meant to be preserved, you need to use `setWithPriority()` instead. + * + * Note that modifying data with `set()` will cancel any pending transactions + * at that location, so extreme care should be taken if mixing `set()` and + * `transaction()` to modify the same data. + * + * A single `set()` will generate a single "value" event at the location where + * the `set()` was performed. + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @returns Resolves when write to server is complete. + */ +export declare function set(ref: DatabaseReference, value: unknown): Promise; +/** + * Sets a priority for the data at this Database location. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +export declare function setPriority(ref: DatabaseReference, priority: string | number | null): Promise; +/** + * Writes data the Database location. Like `set()` but also specifies the + * priority for that data. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +export declare function setWithPriority(ref: DatabaseReference, value: unknown, priority: string | number | null): Promise; +/** + * Writes multiple values to the Database at once. + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, + * "name/first") from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * The effect of the write will be visible immediately, and the corresponding + * events ('value', 'child_added', etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * A single `update()` will generate a single "value" event at the location + * where the `update()` was performed, regardless of how many children were + * modified. + * + * Note that modifying data with `update()` will cancel any pending + * transactions at that location, so extreme care should be taken if mixing + * `update()` and `transaction()` to modify the same data. + * + * Passing `null` to `update()` will remove the data at this location. + * + * See + * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}. + * + * @param ref - The location to write to. + * @param values - Object containing multiple values. + * @returns Resolves when update on server is complete. + */ +export declare function update(ref: DatabaseReference, values: object): Promise; +/** + * Gets the most up-to-date result for this query. + * + * @param query - The query to run. + * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is + * available, or rejects if the client is unable to return a value (e.g., if the + * server is unreachable and there is nothing cached). + */ +export declare function get(query: Query): Promise; +/** + * Represents registration for 'value' events. + */ +export declare class ValueEventRegistration implements EventRegistration { + private callbackContext; + constructor(callbackContext: CallbackContext); + respondsTo(eventType: string): boolean; + createEvent(change: Change, query: QueryContext): DataEvent; + getEventRunner(eventData: CancelEvent | DataEvent): () => void; + createCancelEvent(error: Error, path: Path): CancelEvent | null; + matches(other: EventRegistration): boolean; + hasAnyCallback(): boolean; +} +/** + * Represents the registration of a child_x event. + */ +export declare class ChildEventRegistration implements EventRegistration { + private eventType; + private callbackContext; + constructor(eventType: string, callbackContext: CallbackContext | null); + respondsTo(eventType: string): boolean; + createCancelEvent(error: Error, path: Path): CancelEvent | null; + createEvent(change: Change, query: QueryContext): DataEvent; + getEventRunner(eventData: CancelEvent | DataEvent): () => void; + matches(other: EventRegistration): boolean; + hasAnyCallback(): boolean; +} +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; +export { EventType }; +/** + * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener. + * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from + * the respective `on*` callbacks. + * + * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener + * will not automatically remove listeners registered on child nodes, `off()` + * must also be called on any child listeners to remove the callback. + * + * If a callback is not specified, all callbacks for the specified eventType + * will be removed. Similarly, if no eventType is specified, all callbacks + * for the `Reference` will be removed. + * + * Individual listeners can also be removed by invoking their unsubscribe + * callbacks. + * + * @param query - The query that the listener was registered with. + * @param eventType - One of the following strings: "value", "child_added", + * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks + * for the `Reference` will be removed. + * @param callback - The callback function that was passed to `on()` or + * `undefined` to remove all callbacks. + */ +export declare function off(query: Query, eventType?: EventType, callback?: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown): void; +/** Describes the different query constraints available in this SDK. */ +export type QueryConstraintType = 'endAt' | 'endBefore' | 'startAt' | 'startAfter' | 'limitToFirst' | 'limitToLast' | 'orderByChild' | 'orderByKey' | 'orderByPriority' | 'orderByValue' | 'equalTo'; +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Database query. `QueryConstraint`s are created by invoking {@link endAt}, + * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link + * limitToFirst}, {@link limitToLast}, {@link orderByChild}, + * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} , + * {@link orderByValue} or {@link equalTo} and + * can then be passed to {@link query} to create a new query instance that + * also contains this `QueryConstraint`. + */ +export declare abstract class QueryConstraint { + /** The type of this query constraints */ + abstract readonly type: QueryConstraintType; + /** + * Takes the provided `Query` and returns a copy of the `Query` with this + * `QueryConstraint` applied. + */ + abstract _apply(query: QueryImpl): QueryImpl; +} +/** + * Creates a `QueryConstraint` with the specified ending point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name less than or equal + * to the specified key. + * + * You can read more about `endAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to end at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end at, among the children with the previously + * specified priority. This argument is only allowed if ordering by child, + * value, or priority. + */ +export declare function endAt(value: number | string | boolean | null, key?: string): QueryConstraint; +/** + * Creates a `QueryConstraint` with the specified ending point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is exclusive. If only a value is provided, children + * with a value less than the specified value will be included in the query. + * If a key is specified, then children must have a value less than or equal + * to the specified value and a key name less than the specified key. + * + * @param value - The value to end before. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end before, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +export declare function endBefore(value: number | string | boolean | null, key?: string): QueryConstraint; +/** + * Creates a `QueryConstraint` with the specified starting point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name greater than or + * equal to the specified key. + * + * You can read more about `startAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to start at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at. This argument is only allowed if + * ordering by child, value, or priority. + */ +export declare function startAt(value?: number | string | boolean | null, key?: string): QueryConstraint; +/** + * Creates a `QueryConstraint` with the specified starting point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is exclusive. If only a value is provided, children + * with a value greater than the specified value will be included in the query. + * If a key is specified, then children must have a value greater than or equal + * to the specified value and a a key name greater than the specified key. + * + * @param value - The value to start after. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start after. This argument is only allowed if + * ordering by child, value, or priority. + */ +export declare function startAfter(value: number | string | boolean | null, key?: string): QueryConstraint; +/** + * Creates a new `QueryConstraint` that if limited to the first specific number + * of children. + * + * The `limitToFirst()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the first 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToFirst()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +export declare function limitToFirst(limit: number): QueryConstraint; +/** + * Creates a new `QueryConstraint` that is limited to return only the last + * specified number of children. + * + * The `limitToLast()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the last 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToLast()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +export declare function limitToLast(limit: number): QueryConstraint; +/** + * Creates a new `QueryConstraint` that orders by the specified child key. + * + * Queries can only order by one key at a time. Calling `orderByChild()` + * multiple times on the same query is an error. + * + * Firebase queries allow you to order your data by any child key on the fly. + * However, if you know in advance what your indexes will be, you can define + * them via the .indexOn rule in your Security Rules for better performance. See + * the{@link https://firebase.google.com/docs/database/security/indexing-data} + * rule for more information. + * + * You can read more about `orderByChild()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + * + * @param path - The path to order by. + */ +export declare function orderByChild(path: string): QueryConstraint; +/** + * Creates a new `QueryConstraint` that orders by the key. + * + * Sorts the results of a query by their (ascending) key values. + * + * You can read more about `orderByKey()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +export declare function orderByKey(): QueryConstraint; +/** + * Creates a new `QueryConstraint` that orders by priority. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data} + * for alternatives to priority. + */ +export declare function orderByPriority(): QueryConstraint; +/** + * Creates a new `QueryConstraint` that orders by value. + * + * If the children of a query are all scalar values (string, number, or + * boolean), you can order the results by their (ascending) values. + * + * You can read more about `orderByValue()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +export declare function orderByValue(): QueryConstraint; +/** + * Creates a `QueryConstraint` that includes children that match the specified + * value. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The optional key argument can be used to further limit the range of the + * query. If it is specified, then children that have exactly the specified + * value must also have exactly the specified key as their key name. This can be + * used to filter result sets with many matches for the same value. + * + * You can read more about `equalTo()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to match for. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +export declare function equalTo(value: number | string | boolean | null, key?: string): QueryConstraint; +/** + * Creates a new immutable instance of `Query` that is extended to also include + * additional query constraints. + * + * @param query - The Query instance to use as a base for the new constraints. + * @param queryConstraints - The list of `QueryConstraint`s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query; diff --git a/node_modules/@firebase/database/dist/node-esm/src/api/ServerValue.d.ts b/node_modules/@firebase/database/dist/node-esm/src/api/ServerValue.d.ts new file mode 100644 index 0000000..d1a9a4b --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/api/ServerValue.d.ts @@ -0,0 +1,30 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a placeholder value for auto-populating the current timestamp (time + * since the Unix epoch, in milliseconds) as determined by the Firebase + * servers. + */ +export declare function serverTimestamp(): object; +/** + * Returns a placeholder value that can be used to atomically increment the + * current database value by the provided delta. + * + * @param delta - the amount to modify the current value atomically. + * @returns A placeholder value for modifying data atomically server-side. + */ +export declare function increment(delta: number): object; diff --git a/node_modules/@firebase/database/dist/node-esm/src/api/Transaction.d.ts b/node_modules/@firebase/database/dist/node-esm/src/api/Transaction.d.ts new file mode 100644 index 0000000..bd69015 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/api/Transaction.d.ts @@ -0,0 +1,83 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseReference } from './Reference'; +import { DataSnapshot } from './Reference_impl'; +/** An options object to configure transactions. */ +export interface TransactionOptions { + /** + * By default, events are raised each time the transaction update function + * runs. So if it is run multiple times, you may see intermediate states. You + * can set this to false to suppress these intermediate states and instead + * wait until the transaction has completed before events are raised. + */ + readonly applyLocally?: boolean; +} +/** + * A type for the resolve value of {@link runTransaction}. + */ +export declare class TransactionResult { + /** Whether the transaction was successfully committed. */ + readonly committed: boolean; + /** The resulting data snapshot. */ + readonly snapshot: DataSnapshot; + /** @hideconstructor */ + constructor( + /** Whether the transaction was successfully committed. */ + committed: boolean, + /** The resulting data snapshot. */ + snapshot: DataSnapshot); + /** Returns a JSON-serializable representation of this object. */ + toJSON(): object; +} +/** + * Atomically modifies the data at this location. + * + * Atomically modify the data at this location. Unlike a normal `set()`, which + * just overwrites the data regardless of its previous value, `runTransaction()` is + * used to modify the existing value to a new value, ensuring there are no + * conflicts with other clients writing to the same location at the same time. + * + * To accomplish this, you pass `runTransaction()` an update function which is + * used to transform the current value into a new value. If another client + * writes to the location before your new value is successfully written, your + * update function will be called again with the new current value, and the + * write will be retried. This will happen repeatedly until your write succeeds + * without conflict or you abort the transaction by not returning a value from + * your update function. + * + * Note: Modifying data with `set()` will cancel any pending transactions at + * that location, so extreme care should be taken if mixing `set()` and + * `runTransaction()` to update the same data. + * + * Note: When using transactions with Security and Firebase Rules in place, be + * aware that a client needs `.read` access in addition to `.write` access in + * order to perform a transaction. This is because the client-side nature of + * transactions requires the client to read the data in order to transactionally + * update it. + * + * @param ref - The location to atomically modify. + * @param transactionUpdate - A developer-supplied function which will be passed + * the current data stored at this location (as a JavaScript object). The + * function should return the new value it would like written (as a JavaScript + * object). If `undefined` is returned (i.e. you return with no arguments) the + * transaction will be aborted and the data at this location will not be + * modified. + * @param options - An options object to configure transactions. + * @returns A `Promise` that can optionally be used instead of the `onComplete` + * callback to handle success and failure. + */ +export declare function runTransaction(ref: DatabaseReference, transactionUpdate: (currentData: any) => unknown, options?: TransactionOptions): Promise; diff --git a/node_modules/@firebase/database/dist/node-esm/src/api/test_access.d.ts b/node_modules/@firebase/database/dist/node-esm/src/api/test_access.d.ts new file mode 100644 index 0000000..839feaa --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/api/test_access.d.ts @@ -0,0 +1,31 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { PersistentConnection } from '../core/PersistentConnection'; +import { RepoInfo } from '../core/RepoInfo'; +import { Connection } from '../realtime/Connection'; +export declare const DataConnection: typeof PersistentConnection; +export declare const RealTimeConnection: typeof Connection; +/** + * @internal + */ +export declare const hijackHash: (newHash: () => string) => () => void; +export declare const ConnectionTarget: typeof RepoInfo; +/** + * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection. + * @internal + */ +export declare const forceRestClient: (forceRestClient: boolean) => void; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/AppCheckTokenProvider.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/AppCheckTokenProvider.d.ts new file mode 100644 index 0000000..5262dd5 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/AppCheckTokenProvider.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app'; +import { AppCheckInternalComponentName, AppCheckTokenListener, AppCheckTokenResult } from '@firebase/app-check-interop-types'; +import { Provider } from '@firebase/component'; +/** + * Abstraction around AppCheck's token fetching capabilities. + */ +export declare class AppCheckTokenProvider { + private appCheckProvider?; + private appCheck?; + private serverAppAppCheckToken?; + private appName; + constructor(app: FirebaseApp, appCheckProvider?: Provider); + getToken(forceRefresh?: boolean): Promise; + addTokenChangeListener(listener: AppCheckTokenListener): void; + notifyForInvalidToken(): void; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/AuthTokenProvider.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/AuthTokenProvider.d.ts new file mode 100644 index 0000000..5cc81e6 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/AuthTokenProvider.d.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseAuthTokenData } from '@firebase/app-types/private'; +import { FirebaseAuthInternalName } from '@firebase/auth-interop-types'; +import { Provider } from '@firebase/component'; +export interface AuthTokenProvider { + getToken(forceRefresh: boolean): Promise; + addTokenChangeListener(listener: (token: string | null) => void): void; + removeTokenChangeListener(listener: (token: string | null) => void): void; + notifyForInvalidToken(): void; +} +/** + * Abstraction around FirebaseApp's token fetching capabilities. + */ +export declare class FirebaseAuthTokenProvider implements AuthTokenProvider { + private appName_; + private firebaseOptions_; + private authProvider_; + private auth_; + constructor(appName_: string, firebaseOptions_: object, authProvider_: Provider); + getToken(forceRefresh: boolean): Promise; + addTokenChangeListener(listener: (token: string | null) => void): void; + removeTokenChangeListener(listener: (token: string | null) => void): void; + notifyForInvalidToken(): void; +} +export declare class EmulatorTokenProvider implements AuthTokenProvider { + private accessToken; + /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */ + static OWNER: string; + constructor(accessToken: string); + getToken(forceRefresh: boolean): Promise; + addTokenChangeListener(listener: (token: string | null) => void): void; + removeTokenChangeListener(listener: (token: string | null) => void): void; + notifyForInvalidToken(): void; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/CompoundWrite.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/CompoundWrite.d.ts new file mode 100644 index 0000000..0af422b --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/CompoundWrite.d.ts @@ -0,0 +1,81 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NamedNode, Node } from './snap/Node'; +import { ImmutableTree } from './util/ImmutableTree'; +import { Path } from './util/Path'; +/** + * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with + * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write + * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write + * to reflect the write added. + */ +export declare class CompoundWrite { + writeTree_: ImmutableTree; + constructor(writeTree_: ImmutableTree); + static empty(): CompoundWrite; +} +export declare function compoundWriteAddWrite(compoundWrite: CompoundWrite, path: Path, node: Node): CompoundWrite; +export declare function compoundWriteAddWrites(compoundWrite: CompoundWrite, path: Path, updates: { + [name: string]: Node; +}): CompoundWrite; +/** + * Will remove a write at the given path and deeper paths. This will not modify a write at a higher + * location, which must be removed by calling this method with that path. + * + * @param compoundWrite - The CompoundWrite to remove. + * @param path - The path at which a write and all deeper writes should be removed + * @returns The new CompoundWrite with the removed path + */ +export declare function compoundWriteRemoveWrite(compoundWrite: CompoundWrite, path: Path): CompoundWrite; +/** + * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be + * considered "complete". + * + * @param compoundWrite - The CompoundWrite to check. + * @param path - The path to check for + * @returns Whether there is a complete write at that path + */ +export declare function compoundWriteHasCompleteWrite(compoundWrite: CompoundWrite, path: Path): boolean; +/** + * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate + * writes from deeper paths, but will return child nodes from a more shallow path. + * + * @param compoundWrite - The CompoundWrite to get the node from. + * @param path - The path to get a complete write + * @returns The node if complete at that path, or null otherwise. + */ +export declare function compoundWriteGetCompleteNode(compoundWrite: CompoundWrite, path: Path): Node | null; +/** + * Returns all children that are guaranteed to be a complete overwrite. + * + * @param compoundWrite - The CompoundWrite to get children from. + * @returns A list of all complete children. + */ +export declare function compoundWriteGetCompleteChildren(compoundWrite: CompoundWrite): NamedNode[]; +export declare function compoundWriteChildCompoundWrite(compoundWrite: CompoundWrite, path: Path): CompoundWrite; +/** + * Returns true if this CompoundWrite is empty and therefore does not modify any nodes. + * @returns Whether this CompoundWrite is empty + */ +export declare function compoundWriteIsEmpty(compoundWrite: CompoundWrite): boolean; +/** + * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the + * node + * @param node - The node to apply this CompoundWrite to + * @returns The node with all writes applied + */ +export declare function compoundWriteApply(compoundWrite: CompoundWrite, node: Node): Node; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/PersistentConnection.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/PersistentConnection.d.ts new file mode 100644 index 0000000..1868d90 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/PersistentConnection.d.ts @@ -0,0 +1,135 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AppCheckTokenProvider } from './AppCheckTokenProvider'; +import { AuthTokenProvider } from './AuthTokenProvider'; +import { RepoInfo } from './RepoInfo'; +import { ServerActions } from './ServerActions'; +import { QueryContext } from './view/EventRegistration'; +/** + * Firebase connection. Abstracts wire protocol and handles reconnecting. + * + * NOTE: All JSON objects sent to the realtime connection must have property names enclosed + * in quotes to make sure the closure compiler does not minify them. + */ +export declare class PersistentConnection extends ServerActions { + private repoInfo_; + private applicationId_; + private onDataUpdate_; + private onConnectStatus_; + private onServerInfoUpdate_; + private authTokenProvider_; + private appCheckTokenProvider_; + private authOverride_?; + id: number; + private log_; + private interruptReasons_; + private readonly listens; + private outstandingPuts_; + private outstandingGets_; + private outstandingPutCount_; + private outstandingGetCount_; + private onDisconnectRequestQueue_; + private connected_; + private reconnectDelay_; + private maxReconnectDelay_; + private securityDebugCallback_; + lastSessionId: string | null; + private establishConnectionTimer_; + private visible_; + private requestCBHash_; + private requestNumber_; + private realtime_; + private authToken_; + private appCheckToken_; + private forceTokenRefresh_; + private invalidAuthTokenCount_; + private invalidAppCheckTokenCount_; + private firstConnection_; + private lastConnectionAttemptTime_; + private lastConnectionEstablishedTime_; + private static nextPersistentConnectionId_; + /** + * Counter for number of connections created. Mainly used for tagging in the logs + */ + private static nextConnectionId_; + /** + * @param repoInfo_ - Data about the namespace we are connecting to + * @param applicationId_ - The Firebase App ID for this project + * @param onDataUpdate_ - A callback for new data from the server + */ + constructor(repoInfo_: RepoInfo, applicationId_: string, onDataUpdate_: (a: string, b: unknown, c: boolean, d: number | null) => void, onConnectStatus_: (a: boolean) => void, onServerInfoUpdate_: (a: unknown) => void, authTokenProvider_: AuthTokenProvider, appCheckTokenProvider_: AppCheckTokenProvider, authOverride_?: object | null); + protected sendRequest(action: string, body: unknown, onResponse?: (a: unknown) => void): void; + get(query: QueryContext): Promise; + listen(query: QueryContext, currentHashFn: () => string, tag: number | null, onComplete: (a: string, b: unknown) => void): void; + private sendGet_; + private sendListen_; + private static warnOnListenWarnings_; + refreshAuthToken(token: string): void; + private reduceReconnectDelayIfAdminCredential_; + refreshAppCheckToken(token: string | null): void; + /** + * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like + * a auth revoked (the connection is closed). + */ + tryAuth(): void; + /** + * Attempts to authenticate with the given token. If the authentication + * attempt fails, it's triggered like the token was revoked (the connection is + * closed). + */ + tryAppCheck(): void; + /** + * @inheritDoc + */ + unlisten(query: QueryContext, tag: number | null): void; + private sendUnlisten_; + onDisconnectPut(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void): void; + onDisconnectMerge(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void): void; + onDisconnectCancel(pathString: string, onComplete?: (a: string, b: string) => void): void; + private sendOnDisconnect_; + put(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void, hash?: string): void; + merge(pathString: string, data: unknown, onComplete: (a: string, b: string | null) => void, hash?: string): void; + putInternal(action: string, pathString: string, data: unknown, onComplete: (a: string, b: string | null) => void, hash?: string): void; + private sendPut_; + reportStats(stats: { + [k: string]: unknown; + }): void; + private onDataMessage_; + private onDataPush_; + private onReady_; + private scheduleConnect_; + private initConnection_; + private onVisible_; + private onOnline_; + private onRealtimeDisconnect_; + private establishConnection_; + interrupt(reason: string): void; + resume(reason: string): void; + private handleTimestamp_; + private cancelSentTransactions_; + private onListenRevoked_; + private removeListen_; + private onAuthRevoked_; + private onAppCheckRevoked_; + private onSecurityDebugPacket_; + private restoreState_; + /** + * Sends client stats for first connection + */ + private sendConnectStats_; + private shouldReconnect_; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/ReadonlyRestClient.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/ReadonlyRestClient.d.ts new file mode 100644 index 0000000..28c1710 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/ReadonlyRestClient.d.ts @@ -0,0 +1,60 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AppCheckTokenProvider } from './AppCheckTokenProvider'; +import { AuthTokenProvider } from './AuthTokenProvider'; +import { RepoInfo } from './RepoInfo'; +import { ServerActions } from './ServerActions'; +import { QueryContext } from './view/EventRegistration'; +/** + * An implementation of ServerActions that communicates with the server via REST requests. + * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full + * persistent connection (using WebSockets or long-polling) + */ +export declare class ReadonlyRestClient extends ServerActions { + private repoInfo_; + private onDataUpdate_; + private authTokenProvider_; + private appCheckTokenProvider_; + reportStats(stats: { + [k: string]: unknown; + }): void; + /** @private {function(...[*])} */ + private log_; + /** + * We don't actually need to track listens, except to prevent us calling an onComplete for a listen + * that's been removed. :-/ + */ + private listens_; + static getListenId_(query: QueryContext, tag?: number | null): string; + /** + * @param repoInfo_ - Data about the namespace we are connecting to + * @param onDataUpdate_ - A callback for new data from the server + */ + constructor(repoInfo_: RepoInfo, onDataUpdate_: (a: string, b: unknown, c: boolean, d: number | null) => void, authTokenProvider_: AuthTokenProvider, appCheckTokenProvider_: AppCheckTokenProvider); + /** @inheritDoc */ + listen(query: QueryContext, currentHashFn: () => string, tag: number | null, onComplete: (a: string, b: unknown) => void): void; + /** @inheritDoc */ + unlisten(query: QueryContext, tag: number | null): void; + get(query: QueryContext): Promise; + /** @inheritDoc */ + refreshAuthToken(token: string): void; + /** + * Performs a REST request to the given path, with the provided query string parameters, + * and any auth credentials we have. + */ + private restRequest_; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/Repo.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/Repo.d.ts new file mode 100644 index 0000000..6861109 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/Repo.d.ts @@ -0,0 +1,144 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ValueEventRegistration } from '../api/Reference_impl'; +import { AppCheckTokenProvider } from './AppCheckTokenProvider'; +import { AuthTokenProvider } from './AuthTokenProvider'; +import { PersistentConnection } from './PersistentConnection'; +import { RepoInfo } from './RepoInfo'; +import { ServerActions } from './ServerActions'; +import { Node } from './snap/Node'; +import { SnapshotHolder } from './SnapshotHolder'; +import { SparseSnapshotTree } from './SparseSnapshotTree'; +import { StatsCollection } from './stats/StatsCollection'; +import { StatsListener } from './stats/StatsListener'; +import { StatsReporter } from './stats/StatsReporter'; +import { SyncTree } from './SyncTree'; +import { Indexable } from './util/misc'; +import { Path } from './util/Path'; +import { Tree } from './util/Tree'; +import { EventQueue } from './view/EventQueue'; +import { EventRegistration, QueryContext } from './view/EventRegistration'; +declare const enum TransactionStatus { + RUN = 0, + SENT = 1, + COMPLETED = 2, + SENT_NEEDS_ABORT = 3, + NEEDS_ABORT = 4 +} +interface Transaction { + path: Path; + update: (a: unknown) => unknown; + onComplete: (error: Error | null, committed: boolean, node: Node | null) => void; + status: TransactionStatus; + order: number; + applyLocally: boolean; + retryCount: number; + unwatcher: () => void; + abortReason: string | null; + currentWriteId: number; + currentInputSnapshot: Node | null; + currentOutputSnapshotRaw: Node | null; + currentOutputSnapshotResolved: Node | null; +} +/** + * A connection to a single data repository. + */ +export declare class Repo { + repoInfo_: RepoInfo; + forceRestClient_: boolean; + authTokenProvider_: AuthTokenProvider; + appCheckProvider_: AppCheckTokenProvider; + /** Key for uniquely identifying this repo, used in RepoManager */ + readonly key: string; + dataUpdateCount: number; + infoSyncTree_: SyncTree; + serverSyncTree_: SyncTree; + stats_: StatsCollection; + statsListener_: StatsListener | null; + eventQueue_: EventQueue; + nextWriteId_: number; + server_: ServerActions; + statsReporter_: StatsReporter; + infoData_: SnapshotHolder; + interceptServerDataCallback_: ((a: string, b: unknown) => void) | null; + /** A list of data pieces and paths to be set when this client disconnects. */ + onDisconnect_: SparseSnapshotTree; + /** Stores queues of outstanding transactions for Firebase locations. */ + transactionQueueTree_: Tree; + persistentConnection_: PersistentConnection | null; + constructor(repoInfo_: RepoInfo, forceRestClient_: boolean, authTokenProvider_: AuthTokenProvider, appCheckProvider_: AppCheckTokenProvider); + /** + * @returns The URL corresponding to the root of this Firebase. + */ + toString(): string; +} +export declare function repoStart(repo: Repo, appId: string, authOverride?: object): void; +/** + * @returns The time in milliseconds, taking the server offset into account if we have one. + */ +export declare function repoServerTime(repo: Repo): number; +/** + * Generate ServerValues using some variables from the repo object. + */ +export declare function repoGenerateServerValues(repo: Repo): Indexable; +export declare function repoInterceptServerData(repo: Repo, callback: ((a: string, b: unknown) => unknown) | null): void; +/** + * The purpose of `getValue` is to return the latest known value + * satisfying `query`. + * + * This method will first check for in-memory cached values + * belonging to active listeners. If they are found, such values + * are considered to be the most up-to-date. + * + * If the client is not connected, this method will wait until the + * repo has established a connection and then request the value for `query`. + * If the client is not able to retrieve the query result for another reason, + * it reports an error. + * + * @param query - The query to surface a value for. + */ +export declare function repoGetValue(repo: Repo, query: QueryContext, eventRegistration: ValueEventRegistration): Promise; +export declare function repoSetWithPriority(repo: Repo, path: Path, newVal: unknown, newPriority: number | string | null, onComplete: ((status: Error | null, errorReason?: string) => void) | null): void; +export declare function repoUpdate(repo: Repo, path: Path, childrenToMerge: { + [k: string]: unknown; +}, onComplete: ((status: Error | null, errorReason?: string) => void) | null): void; +export declare function repoOnDisconnectCancel(repo: Repo, path: Path, onComplete: ((status: Error | null, errorReason?: string) => void) | null): void; +export declare function repoOnDisconnectSet(repo: Repo, path: Path, value: unknown, onComplete: ((status: Error | null, errorReason?: string) => void) | null): void; +export declare function repoOnDisconnectSetWithPriority(repo: Repo, path: Path, value: unknown, priority: unknown, onComplete: ((status: Error | null, errorReason?: string) => void) | null): void; +export declare function repoOnDisconnectUpdate(repo: Repo, path: Path, childrenToMerge: { + [k: string]: unknown; +}, onComplete: ((status: Error | null, errorReason?: string) => void) | null): void; +export declare function repoAddEventCallbackForQuery(repo: Repo, query: QueryContext, eventRegistration: EventRegistration): void; +export declare function repoRemoveEventCallbackForQuery(repo: Repo, query: QueryContext, eventRegistration: EventRegistration): void; +export declare function repoInterrupt(repo: Repo): void; +export declare function repoResume(repo: Repo): void; +export declare function repoStats(repo: Repo, showDelta?: boolean): void; +export declare function repoStatsIncrementCounter(repo: Repo, metric: string): void; +export declare function repoCallOnCompleteCallback(repo: Repo, callback: ((status: Error | null, errorReason?: string) => void) | null, status: string, errorReason?: string | null): void; +/** + * Creates a new transaction, adds it to the transactions we're tracking, and + * sends it to the server if possible. + * + * @param path - Path at which to do transaction. + * @param transactionUpdate - Update callback. + * @param onComplete - Completion callback. + * @param unwatcher - Function that will be called when the transaction no longer + * need data updates for `path`. + * @param applyLocally - Whether or not to make intermediate results visible + */ +export declare function repoStartTransaction(repo: Repo, path: Path, transactionUpdate: (a: unknown) => unknown, onComplete: ((error: Error, committed: boolean, node: Node) => void) | null, unwatcher: () => void, applyLocally: boolean): void; +export {}; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/RepoInfo.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/RepoInfo.d.ts new file mode 100644 index 0000000..4604e86 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/RepoInfo.d.ts @@ -0,0 +1,61 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { EmulatorMockTokenOptions } from '@firebase/util'; +export interface RepoInfoEmulatorOptions { + mockUserToken?: string | EmulatorMockTokenOptions; +} +/** + * A class that holds metadata about a Repo object + */ +export declare class RepoInfo { + readonly secure: boolean; + readonly namespace: string; + readonly webSocketOnly: boolean; + readonly nodeAdmin: boolean; + readonly persistenceKey: string; + readonly includeNamespaceInQueryParams: boolean; + readonly isUsingEmulator: boolean; + readonly emulatorOptions: RepoInfoEmulatorOptions | null; + private _host; + private _domain; + internalHost: string; + /** + * @param host - Hostname portion of the url for the repo + * @param secure - Whether or not this repo is accessed over ssl + * @param namespace - The namespace represented by the repo + * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest). + * @param nodeAdmin - Whether this instance uses Admin SDK credentials + * @param persistenceKey - Override the default session persistence storage key + */ + constructor(host: string, secure: boolean, namespace: string, webSocketOnly: boolean, nodeAdmin?: boolean, persistenceKey?: string, includeNamespaceInQueryParams?: boolean, isUsingEmulator?: boolean, emulatorOptions?: RepoInfoEmulatorOptions | null); + isCacheableHost(): boolean; + isCustomHost(): boolean; + get host(): string; + set host(newHost: string); + toString(): string; + toURLString(): string; +} +/** + * Returns the websocket URL for this repo + * @param repoInfo - RepoInfo object + * @param type - of connection + * @param params - list + * @returns The URL for this repo + */ +export declare function repoInfoConnectionURL(repoInfo: RepoInfo, type: string, params: { + [k: string]: string; +}): string; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/ServerActions.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/ServerActions.d.ts new file mode 100644 index 0000000..9f13a86 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/ServerActions.d.ts @@ -0,0 +1,52 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { QueryContext } from './view/EventRegistration'; +/** + * Interface defining the set of actions that can be performed against the Firebase server + * (basically corresponds to our wire protocol). + * + * @interface + */ +export declare abstract class ServerActions { + abstract listen(query: QueryContext, currentHashFn: () => string, tag: number | null, onComplete: (a: string, b: unknown) => void): void; + /** + * Remove a listen. + */ + abstract unlisten(query: QueryContext, tag: number | null): void; + /** + * Get the server value satisfying this query. + */ + abstract get(query: QueryContext): Promise; + put(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void, hash?: string): void; + merge(pathString: string, data: unknown, onComplete: (a: string, b: string | null) => void, hash?: string): void; + /** + * Refreshes the auth token for the current connection. + * @param token - The authentication token + */ + refreshAuthToken(token: string): void; + /** + * Refreshes the app check token for the current connection. + * @param token The app check token + */ + refreshAppCheckToken(token: string): void; + onDisconnectPut(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void): void; + onDisconnectMerge(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void): void; + onDisconnectCancel(pathString: string, onComplete?: (a: string, b: string) => void): void; + reportStats(stats: { + [k: string]: unknown; + }): void; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/SnapshotHolder.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/SnapshotHolder.d.ts new file mode 100644 index 0000000..cdd8456 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/SnapshotHolder.d.ts @@ -0,0 +1,26 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Node } from './snap/Node'; +import { Path } from './util/Path'; +/** + * Mutable object which basically just stores a reference to the "latest" immutable snapshot. + */ +export declare class SnapshotHolder { + private rootNode_; + getNode(path: Path): Node; + updateSnapshot(path: Path, newSnapshotNode: Node): void; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/SparseSnapshotTree.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/SparseSnapshotTree.d.ts new file mode 100644 index 0000000..ddd382e --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/SparseSnapshotTree.d.ts @@ -0,0 +1,64 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Node } from './snap/Node'; +import { Path } from './util/Path'; +/** + * Helper class to store a sparse set of snapshots. + */ +export interface SparseSnapshotTree { + value: Node | null; + readonly children: Map; +} +export declare function newSparseSnapshotTree(): SparseSnapshotTree; +/** + * Gets the node stored at the given path if one exists. + * Only seems to be used in tests. + * + * @param path - Path to look up snapshot for. + * @returns The retrieved node, or null. + */ +export declare function sparseSnapshotTreeFind(sparseSnapshotTree: SparseSnapshotTree, path: Path): Node | null; +/** + * Stores the given node at the specified path. If there is already a node + * at a shallower path, it merges the new data into that snapshot node. + * + * @param path - Path to look up snapshot for. + * @param data - The new data, or null. + */ +export declare function sparseSnapshotTreeRemember(sparseSnapshotTree: SparseSnapshotTree, path: Path, data: Node): void; +/** + * Purge the data at path from the cache. + * + * @param path - Path to look up snapshot for. + * @returns True if this node should now be removed. + */ +export declare function sparseSnapshotTreeForget(sparseSnapshotTree: SparseSnapshotTree, path: Path): boolean; +/** + * Recursively iterates through all of the stored tree and calls the + * callback on each one. + * + * @param prefixPath - Path to look up node for. + * @param func - The function to invoke for each tree. + */ +export declare function sparseSnapshotTreeForEachTree(sparseSnapshotTree: SparseSnapshotTree, prefixPath: Path, func: (a: Path, b: Node) => unknown): void; +/** + * Iterates through each immediate child and triggers the callback. + * Only seems to be used in tests. + * + * @param func - The function to invoke for each child. + */ +export declare function sparseSnapshotTreeForEachChild(sparseSnapshotTree: SparseSnapshotTree, func: (a: string, b: SparseSnapshotTree) => void): void; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/SyncPoint.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/SyncPoint.d.ts new file mode 100644 index 0000000..b6b4daf --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/SyncPoint.d.ts @@ -0,0 +1,91 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ReferenceConstructor } from '../api/Reference'; +import { Operation } from './operation/Operation'; +import { Node } from './snap/Node'; +import { Path } from './util/Path'; +import { Event } from './view/Event'; +import { EventRegistration, QueryContext } from './view/EventRegistration'; +import { View } from './view/View'; +import { WriteTreeRef } from './WriteTree'; +/** + * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to + * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes + * and user writes (set, transaction, update). + * + * It's responsible for: + * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed). + * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite, + * applyUserOverwrite, etc.) + */ +export declare class SyncPoint { + /** + * The Views being tracked at this location in the tree, stored as a map where the key is a + * queryId and the value is the View for that query. + * + * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case). + */ + readonly views: Map; +} +export declare function syncPointSetReferenceConstructor(val: ReferenceConstructor): void; +export declare function syncPointIsEmpty(syncPoint: SyncPoint): boolean; +export declare function syncPointApplyOperation(syncPoint: SyncPoint, operation: Operation, writesCache: WriteTreeRef, optCompleteServerCache: Node | null): Event[]; +/** + * Get a view for the specified query. + * + * @param query - The query to return a view for + * @param writesCache + * @param serverCache + * @param serverCacheComplete + * @returns Events to raise. + */ +export declare function syncPointGetView(syncPoint: SyncPoint, query: QueryContext, writesCache: WriteTreeRef, serverCache: Node | null, serverCacheComplete: boolean): View; +/** + * Add an event callback for the specified query. + * + * @param query + * @param eventRegistration + * @param writesCache + * @param serverCache - Complete server cache, if we have it. + * @param serverCacheComplete + * @returns Events to raise. + */ +export declare function syncPointAddEventRegistration(syncPoint: SyncPoint, query: QueryContext, eventRegistration: EventRegistration, writesCache: WriteTreeRef, serverCache: Node | null, serverCacheComplete: boolean): Event[]; +/** + * Remove event callback(s). Return cancelEvents if a cancelError is specified. + * + * If query is the default query, we'll check all views for the specified eventRegistration. + * If eventRegistration is null, we'll remove all callbacks for the specified view(s). + * + * @param eventRegistration - If null, remove all callbacks. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @returns removed queries and any cancel events + */ +export declare function syncPointRemoveEventRegistration(syncPoint: SyncPoint, query: QueryContext, eventRegistration: EventRegistration | null, cancelError?: Error): { + removed: QueryContext[]; + events: Event[]; +}; +export declare function syncPointGetQueryViews(syncPoint: SyncPoint): View[]; +/** + * @param path - The path to the desired complete snapshot + * @returns A complete cache, if it exists + */ +export declare function syncPointGetCompleteServerCache(syncPoint: SyncPoint, path: Path): Node | null; +export declare function syncPointViewForQuery(syncPoint: SyncPoint, query: QueryContext): View | null; +export declare function syncPointViewExistsForQuery(syncPoint: SyncPoint, query: QueryContext): boolean; +export declare function syncPointHasCompleteView(syncPoint: SyncPoint): boolean; +export declare function syncPointGetCompleteView(syncPoint: SyncPoint): View | null; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/SyncTree.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/SyncTree.d.ts new file mode 100644 index 0000000..7025a3d --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/SyncTree.d.ts @@ -0,0 +1,166 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ReferenceConstructor } from '../api/Reference'; +import { Node } from './snap/Node'; +import { SyncPoint } from './SyncPoint'; +import { ImmutableTree } from './util/ImmutableTree'; +import { Path } from './util/Path'; +import { Event } from './view/Event'; +import { EventRegistration, QueryContext } from './view/EventRegistration'; +import { WriteTree } from './WriteTree'; +export declare function syncTreeSetReferenceConstructor(val: ReferenceConstructor): void; +export interface ListenProvider { + startListening(query: QueryContext, tag: number | null, hashFn: () => string, onComplete: (a: string, b?: unknown) => Event[]): Event[]; + stopListening(a: QueryContext, b: number | null): void; +} +export declare function resetSyncTreeTag(): void; +/** + * SyncTree is the central class for managing event callback registration, data caching, views + * (query processing), and event generation. There are typically two SyncTree instances for + * each Repo, one for the normal Firebase data, and one for the .info data. + * + * It has a number of responsibilities, including: + * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()). + * - Applying and caching data changes for user set(), transaction(), and update() calls + * (applyUserOverwrite(), applyUserMerge()). + * - Applying and caching data changes for server data changes (applyServerOverwrite(), + * applyServerMerge()). + * - Generating user-facing events for server and user changes (all of the apply* methods + * return the set of events that need to be raised as a result). + * - Maintaining the appropriate set of server listens to ensure we are always subscribed + * to the correct set of paths and queries to satisfy the current set of user event + * callbacks (listens are started/stopped using the provided listenProvider). + * + * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual + * events are returned to the caller rather than raised synchronously. + * + */ +export declare class SyncTree { + listenProvider_: ListenProvider; + /** + * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views. + */ + syncPointTree_: ImmutableTree; + /** + * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.). + */ + pendingWriteTree_: WriteTree; + readonly tagToQueryMap: Map; + readonly queryToTagMap: Map; + /** + * @param listenProvider_ - Used by SyncTree to start / stop listening + * to server data. + */ + constructor(listenProvider_: ListenProvider); +} +/** + * Apply the data changes for a user-generated set() or transaction() call. + * + * @returns Events to raise. + */ +export declare function syncTreeApplyUserOverwrite(syncTree: SyncTree, path: Path, newData: Node, writeId: number, visible?: boolean): Event[]; +/** + * Apply the data from a user-generated update() call + * + * @returns Events to raise. + */ +export declare function syncTreeApplyUserMerge(syncTree: SyncTree, path: Path, changedChildren: { + [k: string]: Node; +}, writeId: number): Event[]; +/** + * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge(). + * + * @param revert - True if the given write failed and needs to be reverted + * @returns Events to raise. + */ +export declare function syncTreeAckUserWrite(syncTree: SyncTree, writeId: number, revert?: boolean): Event[]; +/** + * Apply new server data for the specified path.. + * + * @returns Events to raise. + */ +export declare function syncTreeApplyServerOverwrite(syncTree: SyncTree, path: Path, newData: Node): Event[]; +/** + * Apply new server data to be merged in at the specified path. + * + * @returns Events to raise. + */ +export declare function syncTreeApplyServerMerge(syncTree: SyncTree, path: Path, changedChildren: { + [k: string]: Node; +}): Event[]; +/** + * Apply a listen complete for a query + * + * @returns Events to raise. + */ +export declare function syncTreeApplyListenComplete(syncTree: SyncTree, path: Path): Event[]; +/** + * Apply a listen complete for a tagged query + * + * @returns Events to raise. + */ +export declare function syncTreeApplyTaggedListenComplete(syncTree: SyncTree, path: Path, tag: number): Event[]; +/** + * Remove event callback(s). + * + * If query is the default query, we'll check all queries for the specified eventRegistration. + * If eventRegistration is null, we'll remove all callbacks for the specified query/queries. + * + * @param eventRegistration - If null, all callbacks are removed. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no + * deduping needs to take place. This flag allows toggling of that behavior + * @returns Cancel events, if cancelError was provided. + */ +export declare function syncTreeRemoveEventRegistration(syncTree: SyncTree, query: QueryContext, eventRegistration: EventRegistration | null, cancelError?: Error, skipListenerDedup?: boolean): Event[]; +/** + * Apply new server data for the specified tagged query. + * + * @returns Events to raise. + */ +export declare function syncTreeApplyTaggedQueryOverwrite(syncTree: SyncTree, path: Path, snap: Node, tag: number): Event[]; +/** + * Apply server data to be merged in for the specified tagged query. + * + * @returns Events to raise. + */ +export declare function syncTreeApplyTaggedQueryMerge(syncTree: SyncTree, path: Path, changedChildren: { + [k: string]: Node; +}, tag: number): Event[]; +/** + * Add an event callback for the specified query. + * + * @returns Events to raise. + */ +export declare function syncTreeAddEventRegistration(syncTree: SyncTree, query: QueryContext, eventRegistration: EventRegistration, skipSetupListener?: boolean): Event[]; +/** + * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a + * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always + * have a listener above, and atomic operations would correctly show a jitter of -> + * as the write is applied locally and then acknowledged at the server. + * + * Note: this method will *include* hidden writes from transaction with applyLocally set to false. + * + * @param path - The path to the data we want + * @param writeIdsToExclude - A specific set to be excluded + */ +export declare function syncTreeCalcCompleteEventCache(syncTree: SyncTree, path: Path, writeIdsToExclude?: number[]): Node; +export declare function syncTreeGetServerValue(syncTree: SyncTree, query: QueryContext): Node | null; +/** + * Return the tag associated with the given query. + */ +export declare function syncTreeTagForQuery(syncTree: SyncTree, query: QueryContext): number | null; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/WriteTree.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/WriteTree.d.ts new file mode 100644 index 0000000..8b03daa --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/WriteTree.d.ts @@ -0,0 +1,205 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CompoundWrite } from './CompoundWrite'; +import { ChildrenNode } from './snap/ChildrenNode'; +import { Index } from './snap/indexes/Index'; +import { NamedNode, Node } from './snap/Node'; +import { Path } from './util/Path'; +import { CacheNode } from './view/CacheNode'; +/** + * Defines a single user-initiated write operation. May be the result of a set(), transaction(), or update() call. In + * the case of a set() or transaction, snap will be non-null. In the case of an update(), children will be non-null. + */ +export interface WriteRecord { + writeId: number; + path: Path; + snap?: Node | null; + children?: { + [k: string]: Node; + } | null; + visible: boolean; +} +/** + * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path. + * + */ +export declare function writeTreeChildWrites(writeTree: WriteTree, path: Path): WriteTreeRef; +/** + * Record a new overwrite from user code. + * + * @param visible - This is set to false by some transactions. It should be excluded from event caches + */ +export declare function writeTreeAddOverwrite(writeTree: WriteTree, path: Path, snap: Node, writeId: number, visible?: boolean): void; +/** + * Record a new merge from user code. + */ +export declare function writeTreeAddMerge(writeTree: WriteTree, path: Path, changedChildren: { + [k: string]: Node; +}, writeId: number): void; +export declare function writeTreeGetWrite(writeTree: WriteTree, writeId: number): WriteRecord | null; +/** + * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates + * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate. + * + * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise + * events as a result). + */ +export declare function writeTreeRemoveWrite(writeTree: WriteTree, writeId: number): boolean; +/** + * Return a complete snapshot for the given path if there's visible write data at that path, else null. + * No server data is considered. + * + */ +export declare function writeTreeGetCompleteWriteData(writeTree: WriteTree, path: Path): Node | null; +/** + * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden + * writes), attempt to calculate a complete snapshot for the given path + * + * @param writeIdsToExclude - An optional set to be excluded + * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false + */ +export declare function writeTreeCalcCompleteEventCache(writeTree: WriteTree, treePath: Path, completeServerCache: Node | null, writeIdsToExclude?: number[], includeHiddenWrites?: boolean): Node | null; +/** + * With optional, underlying server data, attempt to return a children node of children that we have complete data for. + * Used when creating new views, to pre-fill their complete event children snapshot. + */ +export declare function writeTreeCalcCompleteEventChildren(writeTree: WriteTree, treePath: Path, completeServerChildren: ChildrenNode | null): Node; +/** + * Given that the underlying server data has updated, determine what, if anything, needs to be + * applied to the event cache. + * + * Possibilities: + * + * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data + * + * 2. Some write is completely shadowing. No events to be raised + * + * 3. Is partially shadowed. Events + * + * Either existingEventSnap or existingServerSnap must exist + */ +export declare function writeTreeCalcEventCacheAfterServerOverwrite(writeTree: WriteTree, treePath: Path, childPath: Path, existingEventSnap: Node | null, existingServerSnap: Node | null): Node | null; +/** + * Returns a complete child for a given server snap after applying all user writes or null if there is no + * complete child for this ChildKey. + */ +export declare function writeTreeCalcCompleteChild(writeTree: WriteTree, treePath: Path, childKey: string, existingServerSnap: CacheNode): Node | null; +/** + * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at + * a higher path, this will return the child of that write relative to the write and this path. + * Returns null if there is no write at this path. + */ +export declare function writeTreeShadowingWrite(writeTree: WriteTree, path: Path): Node | null; +/** + * This method is used when processing child remove events on a query. If we can, we pull in children that were outside + * the window, but may now be in the window. + */ +export declare function writeTreeCalcIndexedSlice(writeTree: WriteTree, treePath: Path, completeServerData: Node | null, startPost: NamedNode, count: number, reverse: boolean, index: Index): NamedNode[]; +export declare function newWriteTree(): WriteTree; +/** + * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them + * with underlying server data (to create "event cache" data). Pending writes are added with addOverwrite() + * and addMerge(), and removed with removeWrite(). + */ +export interface WriteTree { + /** + * A tree tracking the result of applying all visible writes. This does not include transactions with + * applyLocally=false or writes that are completely shadowed by other writes. + */ + visibleWrites: CompoundWrite; + /** + * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary + * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also + * used by transactions). + */ + allWrites: WriteRecord[]; + lastWriteId: number; +} +/** + * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used + * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node + * can lead to a more expensive calculation. + * + * @param writeIdsToExclude - Optional writes to exclude. + * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false + */ +export declare function writeTreeRefCalcCompleteEventCache(writeTreeRef: WriteTreeRef, completeServerCache: Node | null, writeIdsToExclude?: number[], includeHiddenWrites?: boolean): Node | null; +/** + * If possible, returns a children node containing all of the complete children we have data for. The returned data is a + * mix of the given server data and write data. + * + */ +export declare function writeTreeRefCalcCompleteEventChildren(writeTreeRef: WriteTreeRef, completeServerChildren: ChildrenNode | null): ChildrenNode; +/** + * Given that either the underlying server data has updated or the outstanding writes have updated, determine what, + * if anything, needs to be applied to the event cache. + * + * Possibilities: + * + * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data + * + * 2. Some write is completely shadowing. No events to be raised + * + * 3. Is partially shadowed. Events should be raised + * + * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert + * + * + */ +export declare function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef: WriteTreeRef, path: Path, existingEventSnap: Node | null, existingServerSnap: Node | null): Node | null; +/** + * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at + * a higher path, this will return the child of that write relative to the write and this path. + * Returns null if there is no write at this path. + * + */ +export declare function writeTreeRefShadowingWrite(writeTreeRef: WriteTreeRef, path: Path): Node | null; +/** + * This method is used when processing child remove events on a query. If we can, we pull in children that were outside + * the window, but may now be in the window + */ +export declare function writeTreeRefCalcIndexedSlice(writeTreeRef: WriteTreeRef, completeServerData: Node | null, startPost: NamedNode, count: number, reverse: boolean, index: Index): NamedNode[]; +/** + * Returns a complete child for a given server snap after applying all user writes or null if there is no + * complete child for this ChildKey. + */ +export declare function writeTreeRefCalcCompleteChild(writeTreeRef: WriteTreeRef, childKey: string, existingServerCache: CacheNode): Node | null; +/** + * Return a WriteTreeRef for a child. + */ +export declare function writeTreeRefChild(writeTreeRef: WriteTreeRef, childName: string): WriteTreeRef; +export declare function newWriteTreeRef(path: Path, writeTree: WriteTree): WriteTreeRef; +/** + * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods + * just proxy to the underlying WriteTree. + * + */ +export interface WriteTreeRef { + /** + * The path to this particular write tree ref. Used for calling methods on writeTree_ while exposing a simpler + * interface to callers. + */ + readonly treePath: Path; + /** + * * A reference to the actual tree of write data. All methods are pass-through to the tree, but with the appropriate + * path prefixed. + * + * This lets us make cheap references to points in the tree for sync points without having to copy and maintain all of + * the data. + */ + readonly writeTree: WriteTree; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/operation/AckUserWrite.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/operation/AckUserWrite.d.ts new file mode 100644 index 0000000..a0cef5f --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/operation/AckUserWrite.d.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ImmutableTree } from '../util/ImmutableTree'; +import { Path } from '../util/Path'; +import { Operation, OperationType } from './Operation'; +export declare class AckUserWrite implements Operation { + /** @inheritDoc */ path: Path; + /** @inheritDoc */ affectedTree: ImmutableTree; + /** @inheritDoc */ revert: boolean; + /** @inheritDoc */ + type: OperationType; + /** @inheritDoc */ + source: import("./Operation").OperationSource; + /** + * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap. + */ + constructor( + /** @inheritDoc */ path: Path, + /** @inheritDoc */ affectedTree: ImmutableTree, + /** @inheritDoc */ revert: boolean); + operationForChild(childName: string): AckUserWrite; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/operation/ListenComplete.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/operation/ListenComplete.d.ts new file mode 100644 index 0000000..87157a2 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/operation/ListenComplete.d.ts @@ -0,0 +1,26 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Path } from '../util/Path'; +import { Operation, OperationSource, OperationType } from './Operation'; +export declare class ListenComplete implements Operation { + source: OperationSource; + path: Path; + /** @inheritDoc */ + type: OperationType; + constructor(source: OperationSource, path: Path); + operationForChild(childName: string): ListenComplete; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/operation/Merge.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/operation/Merge.d.ts new file mode 100644 index 0000000..3fbfbef --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/operation/Merge.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Node } from '../snap/Node'; +import { ImmutableTree } from '../util/ImmutableTree'; +import { Path } from '../util/Path'; +import { Operation, OperationSource, OperationType } from './Operation'; +export declare class Merge implements Operation { + /** @inheritDoc */ source: OperationSource; + /** @inheritDoc */ path: Path; + /** @inheritDoc */ children: ImmutableTree; + /** @inheritDoc */ + type: OperationType; + constructor( + /** @inheritDoc */ source: OperationSource, + /** @inheritDoc */ path: Path, + /** @inheritDoc */ children: ImmutableTree); + operationForChild(childName: string): Operation; + toString(): string; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/operation/Operation.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/operation/Operation.d.ts new file mode 100644 index 0000000..4e0bc44 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/operation/Operation.d.ts @@ -0,0 +1,45 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Path } from '../util/Path'; +/** + * + * @enum + */ +export declare enum OperationType { + OVERWRITE = 0, + MERGE = 1, + ACK_USER_WRITE = 2, + LISTEN_COMPLETE = 3 +} +/** + * @interface + */ +export interface Operation { + source: OperationSource; + type: OperationType; + path: Path; + operationForChild(childName: string): Operation | null; +} +export interface OperationSource { + fromUser: boolean; + fromServer: boolean; + queryId: string | null; + tagged: boolean; +} +export declare function newOperationSourceUser(): OperationSource; +export declare function newOperationSourceServer(): OperationSource; +export declare function newOperationSourceServerTaggedQuery(queryId: string): OperationSource; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/operation/Overwrite.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/operation/Overwrite.d.ts new file mode 100644 index 0000000..2494845 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/operation/Overwrite.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Node } from '../snap/Node'; +import { Path } from '../util/Path'; +import { Operation, OperationSource, OperationType } from './Operation'; +export declare class Overwrite implements Operation { + source: OperationSource; + path: Path; + snap: Node; + /** @inheritDoc */ + type: OperationType; + constructor(source: OperationSource, path: Path, snap: Node); + operationForChild(childName: string): Overwrite; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/snap/ChildrenNode.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/snap/ChildrenNode.d.ts new file mode 100644 index 0000000..0cc0519 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/snap/ChildrenNode.d.ts @@ -0,0 +1,112 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Path } from '../util/Path'; +import { SortedMap, SortedMapIterator } from '../util/SortedMap'; +import { Index } from './indexes/Index'; +import { IndexMap } from './IndexMap'; +import { NamedNode, Node } from './Node'; +export interface ChildrenNodeConstructor { + new (children_: SortedMap, priorityNode_: Node | null, indexMap_: IndexMap): ChildrenNode; + EMPTY_NODE: ChildrenNode; +} +/** + * ChildrenNode is a class for storing internal nodes in a DataSnapshot + * (i.e. nodes with children). It implements Node and stores the + * list of children in the children property, sorted by child name. + */ +export declare class ChildrenNode implements Node { + private readonly children_; + private readonly priorityNode_; + private indexMap_; + private lazyHash_; + static get EMPTY_NODE(): ChildrenNode; + /** + * @param children_ - List of children of this node.. + * @param priorityNode_ - The priority of this node (as a snapshot node). + */ + constructor(children_: SortedMap, priorityNode_: Node | null, indexMap_: IndexMap); + /** @inheritDoc */ + isLeafNode(): boolean; + /** @inheritDoc */ + getPriority(): Node; + /** @inheritDoc */ + updatePriority(newPriorityNode: Node): Node; + /** @inheritDoc */ + getImmediateChild(childName: string): Node; + /** @inheritDoc */ + getChild(path: Path): Node; + /** @inheritDoc */ + hasChild(childName: string): boolean; + /** @inheritDoc */ + updateImmediateChild(childName: string, newChildNode: Node): Node; + /** @inheritDoc */ + updateChild(path: Path, newChildNode: Node): Node; + /** @inheritDoc */ + isEmpty(): boolean; + /** @inheritDoc */ + numChildren(): number; + private static INTEGER_REGEXP_; + /** @inheritDoc */ + val(exportFormat?: boolean): object; + /** @inheritDoc */ + hash(): string; + /** @inheritDoc */ + getPredecessorChildName(childName: string, childNode: Node, index: Index): string; + getFirstChildName(indexDefinition: Index): string | null; + getFirstChild(indexDefinition: Index): NamedNode | null; + /** + * Given an index, return the key name of the largest value we have, according to that index + */ + getLastChildName(indexDefinition: Index): string | null; + getLastChild(indexDefinition: Index): NamedNode | null; + forEachChild(index: Index, action: (key: string, node: Node) => boolean | void): boolean; + getIterator(indexDefinition: Index): SortedMapIterator; + getIteratorFrom(startPost: NamedNode, indexDefinition: Index): SortedMapIterator; + getReverseIterator(indexDefinition: Index): SortedMapIterator; + getReverseIteratorFrom(endPost: NamedNode, indexDefinition: Index): SortedMapIterator; + compareTo(other: ChildrenNode): number; + withIndex(indexDefinition: Index): Node; + isIndexed(index: Index): boolean; + equals(other: Node): boolean; + /** + * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used + * instead. + * + */ + private resolveIndex_; +} +export declare class MaxNode extends ChildrenNode { + constructor(); + compareTo(other: Node): number; + equals(other: Node): boolean; + getPriority(): MaxNode; + getImmediateChild(childName: string): ChildrenNode; + isEmpty(): boolean; +} +/** + * Marker that will sort higher than any other snapshot. + */ +export declare const MAX_NODE: MaxNode; +/** + * Document NamedNode extensions + */ +declare module './Node' { + interface NamedNode { + MIN: NamedNode; + MAX: NamedNode; + } +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/snap/IndexMap.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/snap/IndexMap.d.ts new file mode 100644 index 0000000..42e64ee --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/snap/IndexMap.d.ts @@ -0,0 +1,43 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SortedMap } from '../util/SortedMap'; +import { Index } from './indexes/Index'; +import { NamedNode, Node } from './Node'; +export declare class IndexMap { + private indexes_; + private indexSet_; + /** + * The default IndexMap for nodes without a priority + */ + static get Default(): IndexMap; + constructor(indexes_: { + [k: string]: SortedMap | /*FallbackType*/ object; + }, indexSet_: { + [k: string]: Index; + }); + get(indexKey: string): SortedMap | null; + hasIndex(indexDefinition: Index): boolean; + addIndex(indexDefinition: Index, existingChildren: SortedMap): IndexMap; + /** + * Ensure that this node is properly tracked in any indexes that we're maintaining + */ + addToIndexes(namedNode: NamedNode, existingChildren: SortedMap): IndexMap; + /** + * Create a new IndexMap instance with the given value removed + */ + removeFromIndexes(namedNode: NamedNode, existingChildren: SortedMap): IndexMap; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/snap/LeafNode.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/snap/LeafNode.d.ts new file mode 100644 index 0000000..6eecc9d --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/snap/LeafNode.d.ts @@ -0,0 +1,83 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Indexable } from '../util/misc'; +import { Path } from '../util/Path'; +import { ChildrenNodeConstructor } from './ChildrenNode'; +import { Index } from './indexes/Index'; +import { Node } from './Node'; +/** + * LeafNode is a class for storing leaf nodes in a DataSnapshot. It + * implements Node and stores the value of the node (a string, + * number, or boolean) accessible via getValue(). + */ +export declare class LeafNode implements Node { + private readonly value_; + private priorityNode_; + static set __childrenNodeConstructor(val: ChildrenNodeConstructor); + static get __childrenNodeConstructor(): ChildrenNodeConstructor; + /** + * The sort order for comparing leaf nodes of different types. If two leaf nodes have + * the same type, the comparison falls back to their value + */ + static VALUE_TYPE_ORDER: string[]; + private lazyHash_; + /** + * @param value_ - The value to store in this leaf node. The object type is + * possible in the event of a deferred value + * @param priorityNode_ - The priority of this node. + */ + constructor(value_: string | number | boolean | Indexable, priorityNode_?: Node); + /** @inheritDoc */ + isLeafNode(): boolean; + /** @inheritDoc */ + getPriority(): Node; + /** @inheritDoc */ + updatePriority(newPriorityNode: Node): Node; + /** @inheritDoc */ + getImmediateChild(childName: string): Node; + /** @inheritDoc */ + getChild(path: Path): Node; + hasChild(): boolean; + /** @inheritDoc */ + getPredecessorChildName(childName: string, childNode: Node): null; + /** @inheritDoc */ + updateImmediateChild(childName: string, newChildNode: Node): Node; + /** @inheritDoc */ + updateChild(path: Path, newChildNode: Node): Node; + /** @inheritDoc */ + isEmpty(): boolean; + /** @inheritDoc */ + numChildren(): number; + /** @inheritDoc */ + forEachChild(index: Index, action: (s: string, n: Node) => void): boolean; + val(exportFormat?: boolean): {}; + /** @inheritDoc */ + hash(): string; + /** + * Returns the value of the leaf node. + * @returns The value of the node. + */ + getValue(): Indexable | string | number | boolean; + compareTo(other: Node): number; + /** + * Comparison specifically for two leaf nodes + */ + private compareToLeafNode_; + withIndex(): Node; + isIndexed(): boolean; + equals(other: Node): boolean; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/snap/Node.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/snap/Node.d.ts new file mode 100644 index 0000000..99d379c --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/snap/Node.d.ts @@ -0,0 +1,126 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Path } from '../util/Path'; +import { Index } from './indexes/Index'; +/** + * Node is an interface defining the common functionality for nodes in + * a DataSnapshot. + * + * @interface + */ +export interface Node { + /** + * Whether this node is a leaf node. + * @returns Whether this is a leaf node. + */ + isLeafNode(): boolean; + /** + * Gets the priority of the node. + * @returns The priority of the node. + */ + getPriority(): Node; + /** + * Returns a duplicate node with the new priority. + * @param newPriorityNode - New priority to set for the node. + * @returns Node with new priority. + */ + updatePriority(newPriorityNode: Node): Node; + /** + * Returns the specified immediate child, or null if it doesn't exist. + * @param childName - The name of the child to retrieve. + * @returns The retrieved child, or an empty node. + */ + getImmediateChild(childName: string): Node; + /** + * Returns a child by path, or null if it doesn't exist. + * @param path - The path of the child to retrieve. + * @returns The retrieved child or an empty node. + */ + getChild(path: Path): Node; + /** + * Returns the name of the child immediately prior to the specified childNode, or null. + * @param childName - The name of the child to find the predecessor of. + * @param childNode - The node to find the predecessor of. + * @param index - The index to use to determine the predecessor + * @returns The name of the predecessor child, or null if childNode is the first child. + */ + getPredecessorChildName(childName: string, childNode: Node, index: Index): string | null; + /** + * Returns a duplicate node, with the specified immediate child updated. + * Any value in the node will be removed. + * @param childName - The name of the child to update. + * @param newChildNode - The new child node + * @returns The updated node. + */ + updateImmediateChild(childName: string, newChildNode: Node): Node; + /** + * Returns a duplicate node, with the specified child updated. Any value will + * be removed. + * @param path - The path of the child to update. + * @param newChildNode - The new child node, which may be an empty node + * @returns The updated node. + */ + updateChild(path: Path, newChildNode: Node): Node; + /** + * True if the immediate child specified exists + */ + hasChild(childName: string): boolean; + /** + * @returns True if this node has no value or children. + */ + isEmpty(): boolean; + /** + * @returns The number of children of this node. + */ + numChildren(): number; + /** + * Calls action for each child. + * @param action - Action to be called for + * each child. It's passed the child name and the child node. + * @returns The first truthy value return by action, or the last falsey one + */ + forEachChild(index: Index, action: (a: string, b: Node) => void): unknown; + /** + * @param exportFormat - True for export format (also wire protocol format). + * @returns Value of this node as JSON. + */ + val(exportFormat?: boolean): unknown; + /** + * @returns hash representing the node contents. + */ + hash(): string; + /** + * @param other - Another node + * @returns -1 for less than, 0 for equal, 1 for greater than other + */ + compareTo(other: Node): number; + /** + * @returns Whether or not this snapshot equals other + */ + equals(other: Node): boolean; + /** + * @returns This node, with the specified index now available + */ + withIndex(indexDefinition: Index): Node; + isIndexed(indexDefinition: Index): boolean; +} +export declare class NamedNode { + name: string; + node: Node; + constructor(name: string, node: Node); + static Wrap(name: string, node: Node): NamedNode; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/snap/childSet.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/snap/childSet.d.ts new file mode 100644 index 0000000..42ce33a --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/snap/childSet.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SortedMap } from '../util/SortedMap'; +import { NamedNode } from './Node'; +/** + * Takes a list of child nodes and constructs a SortedSet using the given comparison + * function + * + * Uses the algorithm described in the paper linked here: + * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458 + * + * @param childList - Unsorted list of children + * @param cmp - The comparison method to be used + * @param keyFn - An optional function to extract K from a node wrapper, if K's + * type is not NamedNode + * @param mapSortFn - An optional override for comparator used by the generated sorted map + */ +export declare const buildChildSet: (childList: NamedNode[], cmp: (a: NamedNode, b: NamedNode) => number, keyFn?: (a: NamedNode) => K, mapSortFn?: (a: K, b: K) => number) => SortedMap; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/snap/comparators.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/snap/comparators.d.ts new file mode 100644 index 0000000..a39e3aa --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/snap/comparators.d.ts @@ -0,0 +1,19 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NamedNode } from './Node'; +export declare function NAME_ONLY_COMPARATOR(left: NamedNode, right: NamedNode): number; +export declare function NAME_COMPARATOR(left: string, right: string): number; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/snap/indexes/Index.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/snap/indexes/Index.d.ts new file mode 100644 index 0000000..04c1fa9 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/snap/indexes/Index.d.ts @@ -0,0 +1,50 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Comparator } from '../../util/SortedMap'; +import { Node, NamedNode } from '../Node'; +export declare abstract class Index { + abstract compare(a: NamedNode, b: NamedNode): number; + abstract isDefinedOn(node: Node): boolean; + /** + * @returns A standalone comparison function for + * this index + */ + getCompare(): Comparator; + /** + * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different, + * it's possible that the changes are isolated to parts of the snapshot that are not indexed. + * + * + * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode + */ + indexedValueChanged(oldNode: Node, newNode: Node): boolean; + /** + * @returns a node wrapper that will sort equal to or less than + * any other node wrapper, using this index + */ + minPost(): NamedNode; + /** + * @returns a node wrapper that will sort greater than or equal to + * any other node wrapper, using this index + */ + abstract maxPost(): NamedNode; + abstract makePost(indexValue: unknown, name: string): NamedNode; + /** + * @returns String representation for inclusion in a query spec + */ + abstract toString(): string; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/snap/indexes/KeyIndex.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/snap/indexes/KeyIndex.d.ts new file mode 100644 index 0000000..dc4c04f --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/snap/indexes/KeyIndex.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ChildrenNode } from '../ChildrenNode'; +import { Node, NamedNode } from '../Node'; +import { Index } from './Index'; +export declare class KeyIndex extends Index { + static get __EMPTY_NODE(): ChildrenNode; + static set __EMPTY_NODE(val: ChildrenNode); + compare(a: NamedNode, b: NamedNode): number; + isDefinedOn(node: Node): boolean; + indexedValueChanged(oldNode: Node, newNode: Node): boolean; + minPost(): any; + maxPost(): NamedNode; + makePost(indexValue: string, name: string): NamedNode; + /** + * @returns String representation for inclusion in a query spec + */ + toString(): string; +} +export declare const KEY_INDEX: KeyIndex; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/snap/indexes/PathIndex.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/snap/indexes/PathIndex.d.ts new file mode 100644 index 0000000..65af086 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/snap/indexes/PathIndex.d.ts @@ -0,0 +1,29 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Path } from '../../util/Path'; +import { NamedNode, Node } from '../Node'; +import { Index } from './Index'; +export declare class PathIndex extends Index { + private indexPath_; + constructor(indexPath_: Path); + protected extractChild(snap: Node): Node; + isDefinedOn(node: Node): boolean; + compare(a: NamedNode, b: NamedNode): number; + makePost(indexValue: object, name: string): NamedNode; + maxPost(): NamedNode; + toString(): string; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/snap/indexes/PriorityIndex.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/snap/indexes/PriorityIndex.d.ts new file mode 100644 index 0000000..910d780 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/snap/indexes/PriorityIndex.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NamedNode, Node } from '../Node'; +import { Index } from './Index'; +export declare function setNodeFromJSON(val: (a: unknown) => Node): void; +export declare function setMaxNode(val: Node): void; +export declare class PriorityIndex extends Index { + compare(a: NamedNode, b: NamedNode): number; + isDefinedOn(node: Node): boolean; + indexedValueChanged(oldNode: Node, newNode: Node): boolean; + minPost(): NamedNode; + maxPost(): NamedNode; + makePost(indexValue: unknown, name: string): NamedNode; + /** + * @returns String representation for inclusion in a query spec + */ + toString(): string; +} +export declare const PRIORITY_INDEX: PriorityIndex; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/snap/indexes/ValueIndex.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/snap/indexes/ValueIndex.d.ts new file mode 100644 index 0000000..6b801a9 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/snap/indexes/ValueIndex.d.ts @@ -0,0 +1,31 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NamedNode, Node } from '../Node'; +import { Index } from './Index'; +export declare class ValueIndex extends Index { + compare(a: NamedNode, b: NamedNode): number; + isDefinedOn(node: Node): boolean; + indexedValueChanged(oldNode: Node, newNode: Node): boolean; + minPost(): NamedNode; + maxPost(): NamedNode; + makePost(indexValue: object, name: string): NamedNode; + /** + * @returns String representation for inclusion in a query spec + */ + toString(): string; +} +export declare const VALUE_INDEX: ValueIndex; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/snap/nodeFromJSON.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/snap/nodeFromJSON.d.ts new file mode 100644 index 0000000..a20804b --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/snap/nodeFromJSON.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Node } from './Node'; +/** + * Constructs a snapshot node representing the passed JSON and returns it. + * @param json - JSON to create a node for. + * @param priority - Optional priority to use. This will be ignored if the + * passed JSON contains a .priority property. + */ +export declare function nodeFromJSON(json: unknown | null, priority?: unknown): Node; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/snap/snap.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/snap/snap.d.ts new file mode 100644 index 0000000..579a2ed --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/snap/snap.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Node } from './Node'; +export declare function setMaxNode(val: Node): void; +export declare const priorityHashText: (priority: string | number) => string; +/** + * Validates that a priority snapshot Node is valid. + */ +export declare const validatePriorityNode: (priorityNode: Node) => void; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/stats/StatsCollection.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/stats/StatsCollection.d.ts new file mode 100644 index 0000000..0179d61 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/stats/StatsCollection.d.ts @@ -0,0 +1,26 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Tracks a collection of stats. + */ +export declare class StatsCollection { + private counters_; + incrementCounter(name: string, amount?: number): void; + get(): { + [k: string]: number; + }; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/stats/StatsListener.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/stats/StatsListener.d.ts new file mode 100644 index 0000000..cf6d906 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/stats/StatsListener.d.ts @@ -0,0 +1,30 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { StatsCollection } from './StatsCollection'; +/** + * Returns the delta from the previous call to get stats. + * + * @param collection_ - The collection to "listen" to. + */ +export declare class StatsListener { + private collection_; + private last_; + constructor(collection_: StatsCollection); + get(): { + [k: string]: number; + }; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/stats/StatsManager.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/stats/StatsManager.d.ts new file mode 100644 index 0000000..7c02ab4 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/stats/StatsManager.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { RepoInfo } from '../RepoInfo'; +import { StatsCollection } from './StatsCollection'; +export declare function statsManagerGetCollection(repoInfo: RepoInfo): StatsCollection; +export declare function statsManagerGetOrCreateReporter(repoInfo: RepoInfo, creatorFunction: () => T): T; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/stats/StatsReporter.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/stats/StatsReporter.d.ts new file mode 100644 index 0000000..402b43b --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/stats/StatsReporter.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ServerActions } from '../ServerActions'; +import { StatsCollection } from './StatsCollection'; +export declare class StatsReporter { + private server_; + private statsListener_; + statsToReport_: { + [k: string]: boolean; + }; + constructor(collection: StatsCollection, server_: ServerActions); + private reportStats_; +} +export declare function statsReporterIncludeStat(reporter: StatsReporter, stat: string): void; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/storage/DOMStorageWrapper.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/storage/DOMStorageWrapper.d.ts new file mode 100644 index 0000000..662d8f5 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/storage/DOMStorageWrapper.d.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Wraps a DOM Storage object and: + * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types. + * - prefixes names with "firebase:" to avoid collisions with app data. + * + * We automatically (see storage.js) create two such wrappers, one for sessionStorage, + * and one for localStorage. + * + */ +export declare class DOMStorageWrapper { + private domStorage_; + private prefix_; + /** + * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage) + */ + constructor(domStorage_: Storage); + /** + * @param key - The key to save the value under + * @param value - The value being stored, or null to remove the key. + */ + set(key: string, value: unknown | null): void; + /** + * @returns The value that was stored under this key, or null + */ + get(key: string): unknown; + remove(key: string): void; + isInMemoryStorage: boolean; + prefixedName_(name: string): string; + toString(): string; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/storage/MemoryStorage.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/storage/MemoryStorage.d.ts new file mode 100644 index 0000000..08dd04e --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/storage/MemoryStorage.d.ts @@ -0,0 +1,27 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory storage implementation that matches the API of DOMStorageWrapper + * (TODO: create interface for both to implement). + */ +export declare class MemoryStorage { + private cache_; + set(key: string, value: unknown | null): void; + get(key: string): unknown; + remove(key: string): void; + isInMemoryStorage: boolean; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/storage/storage.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/storage/storage.d.ts new file mode 100644 index 0000000..52b3579 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/storage/storage.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DOMStorageWrapper } from './DOMStorageWrapper'; +import { MemoryStorage } from './MemoryStorage'; +/** A storage object that lasts across sessions */ +export declare const PersistentStorage: DOMStorageWrapper | MemoryStorage; +/** A storage object that only lasts one session */ +export declare const SessionStorage: DOMStorageWrapper | MemoryStorage; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/util/EventEmitter.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/util/EventEmitter.d.ts new file mode 100644 index 0000000..0fd09f9 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/util/EventEmitter.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Base class to be used if you want to emit events. Call the constructor with + * the set of allowed event names. + */ +export declare abstract class EventEmitter { + private allowedEvents_; + private listeners_; + constructor(allowedEvents_: string[]); + /** + * To be overridden by derived classes in order to fire an initial event when + * somebody subscribes for data. + * + * @returns {Array.<*>} Array of parameters to trigger initial event with. + */ + abstract getInitialEvent(eventType: string): unknown[]; + /** + * To be called by derived classes to trigger events. + */ + protected trigger(eventType: string, ...varArgs: unknown[]): void; + on(eventType: string, callback: (a: unknown) => void, context: unknown): void; + off(eventType: string, callback: (a: unknown) => void, context: unknown): void; + private validateEventType_; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/util/ImmutableTree.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/util/ImmutableTree.d.ts new file mode 100644 index 0000000..8a85ce6 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/util/ImmutableTree.d.ts @@ -0,0 +1,117 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Path } from './Path'; +import { SortedMap } from './SortedMap'; +/** + * A tree with immutable elements. + */ +export declare class ImmutableTree { + readonly value: T | null; + readonly children: SortedMap>; + static fromObject(obj: { + [k: string]: T; + }): ImmutableTree; + constructor(value: T | null, children?: SortedMap>); + /** + * True if the value is empty and there are no children + */ + isEmpty(): boolean; + /** + * Given a path and predicate, return the first node and the path to that node + * where the predicate returns true. + * + * TODO Do a perf test -- If we're creating a bunch of `{path: value:}` + * objects on the way back out, it may be better to pass down a pathSoFar obj. + * + * @param relativePath - The remainder of the path + * @param predicate - The predicate to satisfy to return a node + */ + findRootMostMatchingPathAndValue(relativePath: Path, predicate: (a: T) => boolean): { + path: Path; + value: T; + } | null; + /** + * Find, if it exists, the shortest subpath of the given path that points a defined + * value in the tree + */ + findRootMostValueAndPath(relativePath: Path): { + path: Path; + value: T; + } | null; + /** + * @returns The subtree at the given path + */ + subtree(relativePath: Path): ImmutableTree; + /** + * Sets a value at the specified path. + * + * @param relativePath - Path to set value at. + * @param toSet - Value to set. + * @returns Resulting tree. + */ + set(relativePath: Path, toSet: T | null): ImmutableTree; + /** + * Removes the value at the specified path. + * + * @param relativePath - Path to value to remove. + * @returns Resulting tree. + */ + remove(relativePath: Path): ImmutableTree; + /** + * Gets a value from the tree. + * + * @param relativePath - Path to get value for. + * @returns Value at path, or null. + */ + get(relativePath: Path): T | null; + /** + * Replace the subtree at the specified path with the given new tree. + * + * @param relativePath - Path to replace subtree for. + * @param newTree - New tree. + * @returns Resulting tree. + */ + setTree(relativePath: Path, newTree: ImmutableTree): ImmutableTree; + /** + * Performs a depth first fold on this tree. Transforms a tree into a single + * value, given a function that operates on the path to a node, an optional + * current value, and a map of child names to folded subtrees + */ + fold(fn: (path: Path, value: T, children: { + [k: string]: V; + }) => V): V; + /** + * Recursive helper for public-facing fold() method + */ + private fold_; + /** + * Find the first matching value on the given path. Return the result of applying f to it. + */ + findOnPath(path: Path, f: (path: Path, value: T) => V | null): V | null; + private findOnPath_; + foreachOnPath(path: Path, f: (path: Path, value: T) => void): ImmutableTree; + private foreachOnPath_; + /** + * Calls the given function for each node in the tree that has a value. + * + * @param f - A function to be called with the path from the root of the tree to + * a node, and the value at that node. Called in depth-first order. + */ + foreach(f: (path: Path, value: T) => void): void; + private foreach_; + foreachChild(f: (name: string, value: T) => void): void; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/util/NextPushId.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/util/NextPushId.d.ts new file mode 100644 index 0000000..9ad8425 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/util/NextPushId.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Fancy ID generator that creates 20-character string identifiers with the + * following properties: + * + * 1. They're based on timestamp so that they sort *after* any existing ids. + * 2. They contain 72-bits of random data after the timestamp so that IDs won't + * collide with other clients' IDs. + * 3. They sort *lexicographically* (so the timestamp is converted to characters + * that will sort properly). + * 4. They're monotonically increasing. Even if you generate more than one in + * the same timestamp, the latter ones will sort after the former ones. We do + * this by using the previous random bits but "incrementing" them by 1 (only + * in the case of a timestamp collision). + */ +export declare const nextPushId: (now: number) => string; +export declare const successor: (key: string) => string; +export declare const predecessor: (key: string) => string; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/util/OnlineMonitor.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/util/OnlineMonitor.d.ts new file mode 100644 index 0000000..bed347b --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/util/OnlineMonitor.d.ts @@ -0,0 +1,31 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { EventEmitter } from './EventEmitter'; +/** + * Monitors online state (as reported by window.online/offline events). + * + * The expectation is that this could have many false positives (thinks we are online + * when we're not), but no false negatives. So we can safely use it to determine when + * we definitely cannot reach the internet. + */ +export declare class OnlineMonitor extends EventEmitter { + private online_; + static getInstance(): OnlineMonitor; + constructor(); + getInitialEvent(eventType: string): boolean[]; + currentlyOnline(): boolean; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/util/Path.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/util/Path.d.ts new file mode 100644 index 0000000..2f73b36 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/util/Path.d.ts @@ -0,0 +1,94 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a parsed path. It's immutable so that you + * can pass them around to other functions without worrying about them changing + * it. + */ +export declare class Path { + pieces_: string[]; + pieceNum_: number; + /** + * @param pathOrString - Path string to parse, or another path, or the raw + * tokens array + */ + constructor(pathOrString: string | string[], pieceNum?: number); + toString(): string; +} +export declare function newEmptyPath(): Path; +export declare function pathGetFront(path: Path): string | null; +/** + * @returns The number of segments in this path + */ +export declare function pathGetLength(path: Path): number; +export declare function pathPopFront(path: Path): Path; +export declare function pathGetBack(path: Path): string | null; +export declare function pathToUrlEncodedString(path: Path): string; +/** + * Shallow copy of the parts of the path. + * + */ +export declare function pathSlice(path: Path, begin?: number): string[]; +export declare function pathParent(path: Path): Path | null; +export declare function pathChild(path: Path, childPathObj: string | Path): Path; +/** + * @returns True if there are no segments in this path + */ +export declare function pathIsEmpty(path: Path): boolean; +/** + * @returns The path from outerPath to innerPath + */ +export declare function newRelativePath(outerPath: Path, innerPath: Path): Path; +/** + * @returns -1, 0, 1 if left is less, equal, or greater than the right. + */ +export declare function pathCompare(left: Path, right: Path): number; +/** + * @returns true if paths are the same. + */ +export declare function pathEquals(path: Path, other: Path): boolean; +/** + * @returns True if this path is a parent of (or the same as) other + */ +export declare function pathContains(path: Path, other: Path): boolean; +/** + * Dynamic (mutable) path used to count path lengths. + * + * This class is used to efficiently check paths for valid + * length (in UTF8 bytes) and depth (used in path validation). + * + * Throws Error exception if path is ever invalid. + * + * The definition of a path always begins with '/'. + */ +export declare class ValidationPath { + errorPrefix_: string; + parts_: string[]; + /** Initialize to number of '/' chars needed in path. */ + byteLength_: number; + /** + * @param path - Initial Path. + * @param errorPrefix_ - Prefix for any error messages. + */ + constructor(path: Path, errorPrefix_: string); +} +export declare function validationPathPush(validationPath: ValidationPath, child: string): void; +export declare function validationPathPop(validationPath: ValidationPath): void; +/** + * String for use in error messages - uses '.' notation for path. + */ +export declare function validationPathToErrorString(validationPath: ValidationPath): string; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/util/ServerValues.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/util/ServerValues.d.ts new file mode 100644 index 0000000..916cf14 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/util/ServerValues.d.ts @@ -0,0 +1,56 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Node } from '../snap/Node'; +import { SyncTree } from '../SyncTree'; +import { Indexable } from './misc'; +import { Path } from './Path'; +interface ValueProvider { + getImmediateChild(childName: string): ValueProvider; + node(): Node; +} +/** + * Generate placeholders for deferred values. + */ +export declare const generateWithValues: (values: { + [k: string]: unknown; +} | null) => { + [k: string]: unknown; +}; +/** + * Value to use when firing local events. When writing server values, fire + * local events with an approximate value, otherwise return value as-is. + */ +export declare const resolveDeferredLeafValue: (value: { + [k: string]: unknown; +} | string | number | boolean, existingVal: ValueProvider, serverValues: { + [k: string]: unknown; +}) => string | number | boolean; +/** + * Recursively replace all deferred values and priorities in the tree with the + * specified generated replacement values. + * @param path - path to which write is relative + * @param node - new data written at path + * @param syncTree - current data + */ +export declare const resolveDeferredValueTree: (path: Path, node: Node, syncTree: SyncTree, serverValues: Indexable) => Node; +/** + * Recursively replace all deferred values and priorities in the node with the + * specified generated replacement values. If there are no server values in the node, + * it'll be returned as-is. + */ +export declare const resolveDeferredValueSnapshot: (node: Node, existing: Node, serverValues: Indexable) => Node; +export {}; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/util/SortedMap.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/util/SortedMap.d.ts new file mode 100644 index 0000000..09d3aa6 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/util/SortedMap.d.ts @@ -0,0 +1,324 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview Implementation of an immutable SortedMap using a Left-leaning + * Red-Black Tree, adapted from the implementation in Mugs + * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen + * (mads379\@gmail.com). + * + * Original paper on Left-leaning Red-Black Trees: + * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf + * + * Invariant 1: No red node has a red child + * Invariant 2: Every leaf path has the same number of black nodes + * Invariant 3: Only the left child can be red (left leaning) + */ +export type Comparator = (key1: K, key2: K) => number; +/** + * An iterator over an LLRBNode. + */ +export declare class SortedMapIterator { + private isReverse_; + private resultGenerator_; + private nodeStack_; + /** + * @param node - Node to iterate. + * @param isReverse_ - Whether or not to iterate in reverse + */ + constructor(node: LLRBNode | LLRBEmptyNode, startKey: K | null, comparator: Comparator, isReverse_: boolean, resultGenerator_?: ((k: K, v: V) => T) | null); + getNext(): T; + hasNext(): boolean; + peek(): T; +} +/** + * Represents a node in a Left-leaning Red-Black tree. + */ +export declare class LLRBNode { + key: K; + value: V; + color: boolean; + left: LLRBNode | LLRBEmptyNode; + right: LLRBNode | LLRBEmptyNode; + /** + * @param key - Key associated with this node. + * @param value - Value associated with this node. + * @param color - Whether this node is red. + * @param left - Left child. + * @param right - Right child. + */ + constructor(key: K, value: V, color: boolean | null, left?: LLRBNode | LLRBEmptyNode | null, right?: LLRBNode | LLRBEmptyNode | null); + static RED: boolean; + static BLACK: boolean; + /** + * Returns a copy of the current node, optionally replacing pieces of it. + * + * @param key - New key for the node, or null. + * @param value - New value for the node, or null. + * @param color - New color for the node, or null. + * @param left - New left child for the node, or null. + * @param right - New right child for the node, or null. + * @returns The node copy. + */ + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBNode; + /** + * @returns The total number of nodes in the tree. + */ + count(): number; + /** + * @returns True if the tree is empty. + */ + isEmpty(): boolean; + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action: (k: K, v: V) => unknown): boolean; + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action: (k: K, v: V) => void): boolean; + /** + * @returns The minimum node in the tree. + */ + private min_; + /** + * @returns The maximum key in the tree. + */ + minKey(): K; + /** + * @returns The maximum key in the tree. + */ + maxKey(): K; + /** + * @param key - Key to insert. + * @param value - Value to insert. + * @param comparator - Comparator. + * @returns New tree, with the key/value added. + */ + insert(key: K, value: V, comparator: Comparator): LLRBNode; + /** + * @returns New tree, with the minimum key removed. + */ + private removeMin_; + /** + * @param key - The key of the item to remove. + * @param comparator - Comparator. + * @returns New tree, with the specified item removed. + */ + remove(key: K, comparator: Comparator): LLRBNode | LLRBEmptyNode; + /** + * @returns Whether this is a RED node. + */ + isRed_(): boolean; + /** + * @returns New tree after performing any needed rotations. + */ + private fixUp_; + /** + * @returns New tree, after moveRedLeft. + */ + private moveRedLeft_; + /** + * @returns New tree, after moveRedRight. + */ + private moveRedRight_; + /** + * @returns New tree, after rotateLeft. + */ + private rotateLeft_; + /** + * @returns New tree, after rotateRight. + */ + private rotateRight_; + /** + * @returns Newt ree, after colorFlip. + */ + private colorFlip_; + /** + * For testing. + * + * @returns True if all is well. + */ + private checkMaxDepth_; + check_(): number; +} +/** + * Represents an empty node (a leaf node in the Red-Black Tree). + */ +export declare class LLRBEmptyNode { + key: K; + value: V; + left: LLRBNode | LLRBEmptyNode; + right: LLRBNode | LLRBEmptyNode; + color: boolean; + /** + * Returns a copy of the current node. + * + * @returns The node copy. + */ + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBEmptyNode; + /** + * Returns a copy of the tree, with the specified key/value added. + * + * @param key - Key to be added. + * @param value - Value to be added. + * @param comparator - Comparator. + * @returns New tree, with item added. + */ + insert(key: K, value: V, comparator: Comparator): LLRBNode; + /** + * Returns a copy of the tree, with the specified key removed. + * + * @param key - The key to remove. + * @param comparator - Comparator. + * @returns New tree, with item removed. + */ + remove(key: K, comparator: Comparator): LLRBEmptyNode; + /** + * @returns The total number of nodes in the tree. + */ + count(): number; + /** + * @returns True if the tree is empty. + */ + isEmpty(): boolean; + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + inorderTraversal(action: (k: K, v: V) => unknown): boolean; + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action: (k: K, v: V) => void): boolean; + minKey(): null; + maxKey(): null; + check_(): number; + /** + * @returns Whether this node is red. + */ + isRed_(): boolean; +} +/** + * An immutable sorted map implementation, based on a Left-leaning Red-Black + * tree. + */ +export declare class SortedMap { + private comparator_; + private root_; + /** + * Always use the same empty node, to reduce memory. + */ + static EMPTY_NODE: LLRBEmptyNode; + /** + * @param comparator_ - Key comparator. + * @param root_ - Optional root node for the map. + */ + constructor(comparator_: Comparator, root_?: LLRBNode | LLRBEmptyNode); + /** + * Returns a copy of the map, with the specified key/value added or replaced. + * (TODO: We should perhaps rename this method to 'put') + * + * @param key - Key to be added. + * @param value - Value to be added. + * @returns New map, with item added. + */ + insert(key: K, value: V): SortedMap; + /** + * Returns a copy of the map, with the specified key removed. + * + * @param key - The key to remove. + * @returns New map, with item removed. + */ + remove(key: K): SortedMap; + /** + * Returns the value of the node with the given key, or null. + * + * @param key - The key to look up. + * @returns The value of the node with the given key, or null if the + * key doesn't exist. + */ + get(key: K): V | null; + /** + * Returns the key of the item *before* the specified key, or null if key is the first item. + * @param key - The key to find the predecessor of + * @returns The predecessor key. + */ + getPredecessorKey(key: K): K | null; + /** + * @returns True if the map is empty. + */ + isEmpty(): boolean; + /** + * @returns The total number of nodes in the map. + */ + count(): number; + /** + * @returns The minimum key in the map. + */ + minKey(): K | null; + /** + * @returns The maximum key in the map. + */ + maxKey(): K | null; + /** + * Traverses the map in key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action: (k: K, v: V) => unknown): boolean; + /** + * Traverses the map in reverse key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns True if the traversal was aborted. + */ + reverseTraversal(action: (k: K, v: V) => void): boolean; + /** + * Returns an iterator over the SortedMap. + * @returns The iterator. + */ + getIterator(resultGenerator?: (k: K, v: V) => T): SortedMapIterator; + getIteratorFrom(key: K, resultGenerator?: (k: K, v: V) => T): SortedMapIterator; + getReverseIteratorFrom(key: K, resultGenerator?: (k: K, v: V) => T): SortedMapIterator; + getReverseIterator(resultGenerator?: (k: K, v: V) => T): SortedMapIterator; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/util/Tree.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/util/Tree.d.ts new file mode 100644 index 0000000..3bcdc27 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/util/Tree.d.ts @@ -0,0 +1,105 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Path } from './Path'; +/** + * Node in a Tree. + */ +export interface TreeNode { + children: Record>; + childCount: number; + value?: T; +} +/** + * A light-weight tree, traversable by path. Nodes can have both values and children. + * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty + * children. + */ +export declare class Tree { + readonly name: string; + readonly parent: Tree | null; + node: TreeNode; + /** + * @param name - Optional name of the node. + * @param parent - Optional parent node. + * @param node - Optional node to wrap. + */ + constructor(name?: string, parent?: Tree | null, node?: TreeNode); +} +/** + * Returns a sub-Tree for the given path. + * + * @param pathObj - Path to look up. + * @returns Tree for path. + */ +export declare function treeSubTree(tree: Tree, pathObj: string | Path): Tree; +/** + * Returns the data associated with this tree node. + * + * @returns The data or null if no data exists. + */ +export declare function treeGetValue(tree: Tree): T | undefined; +/** + * Sets data to this tree node. + * + * @param value - Value to set. + */ +export declare function treeSetValue(tree: Tree, value: T | undefined): void; +/** + * @returns Whether the tree has any children. + */ +export declare function treeHasChildren(tree: Tree): boolean; +/** + * @returns Whether the tree is empty (no value or children). + */ +export declare function treeIsEmpty(tree: Tree): boolean; +/** + * Calls action for each child of this tree node. + * + * @param action - Action to be called for each child. + */ +export declare function treeForEachChild(tree: Tree, action: (tree: Tree) => void): void; +/** + * Does a depth-first traversal of this node's descendants, calling action for each one. + * + * @param action - Action to be called for each child. + * @param includeSelf - Whether to call action on this node as well. Defaults to + * false. + * @param childrenFirst - Whether to call action on children before calling it on + * parent. + */ +export declare function treeForEachDescendant(tree: Tree, action: (tree: Tree) => void, includeSelf?: boolean, childrenFirst?: boolean): void; +/** + * Calls action on each ancestor node. + * + * @param action - Action to be called on each parent; return + * true to abort. + * @param includeSelf - Whether to call action on this node as well. + * @returns true if the action callback returned true. + */ +export declare function treeForEachAncestor(tree: Tree, action: (tree: Tree) => unknown, includeSelf?: boolean): boolean; +/** + * Does a depth-first traversal of this node's descendants. When a descendant with a value + * is found, action is called on it and traversal does not continue inside the node. + * Action is *not* called on this node. + * + * @param action - Action to be called for each child. + */ +export declare function treeForEachImmediateDescendantWithValue(tree: Tree, action: (tree: Tree) => void): void; +/** + * @returns The path of this tree node, as a Path. + */ +export declare function treeGetPath(tree: Tree): any; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/util/VisibilityMonitor.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/util/VisibilityMonitor.d.ts new file mode 100644 index 0000000..e9e306f --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/util/VisibilityMonitor.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { EventEmitter } from './EventEmitter'; +export declare class VisibilityMonitor extends EventEmitter { + private visible_; + static getInstance(): VisibilityMonitor; + constructor(); + getInitialEvent(eventType: string): boolean[]; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/util/libs/parser.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/util/libs/parser.d.ts new file mode 100644 index 0000000..9f1d58c --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/util/libs/parser.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { RepoInfo } from '../../RepoInfo'; +import { Path } from '../Path'; +export declare const parseRepoInfo: (dataURL: string, nodeAdmin: boolean) => { + repoInfo: RepoInfo; + path: Path; +}; +export declare const parseDatabaseURL: (dataURL: string) => { + host: string; + port: number; + domain: string; + subdomain: string; + secure: boolean; + scheme: string; + pathString: string; + namespace: string; +}; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/util/misc.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/util/misc.d.ts new file mode 100644 index 0000000..abfa94c --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/util/misc.d.ts @@ -0,0 +1,19 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface Indexable { + [key: string]: unknown; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/util/util.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/util/util.d.ts new file mode 100644 index 0000000..35c32d8 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/util/util.d.ts @@ -0,0 +1,176 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { QueryContext } from '../view/EventRegistration'; +/** + * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called). + */ +export declare const LUIDGenerator: () => number; +/** + * Sha1 hash of the input string + * @param str - The string to hash + * @returns {!string} The resulting hash + */ +export declare const sha1: (str: string) => string; +/** + * Use this for all debug messages in Firebase. + */ +export declare let logger: ((a: string) => void) | null; +/** + * The implementation of Firebase.enableLogging (defined here to break dependencies) + * @param logger_ - A flag to turn on logging, or a custom logger + * @param persistent - Whether or not to persist logging settings across refreshes + */ +export declare const enableLogging: (logger_?: boolean | ((a: string) => void) | null, persistent?: boolean) => void; +export declare const log: (...varArgs: unknown[]) => void; +export declare const logWrapper: (prefix: string) => (...varArgs: unknown[]) => void; +export declare const error: (...varArgs: string[]) => void; +export declare const fatal: (...varArgs: string[]) => never; +export declare const warn: (...varArgs: unknown[]) => void; +/** + * Logs a warning if the containing page uses https. Called when a call to new Firebase + * does not use https. + */ +export declare const warnIfPageIsSecure: () => void; +export declare const warnAboutUnsupportedMethod: (methodName: string) => void; +/** + * Returns true if data is NaN, or +/- Infinity. + */ +export declare const isInvalidJSONNumber: (data: unknown) => boolean; +export declare const executeWhenDOMReady: (fn: () => void) => void; +/** + * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names + */ +export declare const MIN_NAME = "[MIN_NAME]"; +/** + * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names + */ +export declare const MAX_NAME = "[MAX_NAME]"; +/** + * Compares valid Firebase key names, plus min and max name + */ +export declare const nameCompare: (a: string, b: string) => number; +/** + * @returns {!number} comparison result. + */ +export declare const stringCompare: (a: string, b: string) => number; +export declare const requireKey: (key: string, obj: { + [k: string]: unknown; +}) => unknown; +export declare const ObjectToUniqueKey: (obj: unknown) => string; +/** + * Splits a string into a number of smaller segments of maximum size + * @param str - The string + * @param segsize - The maximum number of chars in the string. + * @returns The string, split into appropriately-sized chunks + */ +export declare const splitStringBySize: (str: string, segsize: number) => string[]; +/** + * Apply a function to each (key, value) pair in an object or + * apply a function to each (index, value) pair in an array + * @param obj - The object or array to iterate over + * @param fn - The function to apply + */ +export declare function each(obj: object, fn: (k: string, v: unknown) => void): void; +/** + * Like goog.bind, but doesn't bother to create a closure if opt_context is null/undefined. + * @param callback - Callback function. + * @param context - Optional context to bind to. + * + */ +export declare const bindCallback: (callback: (a: unknown) => void, context?: object | null) => (a: unknown) => void; +/** + * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License) + * I made one modification at the end and removed the NaN / Infinity + * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments. + * @param v - A double + * + */ +export declare const doubleToIEEE754String: (v: number) => string; +/** + * Used to detect if we're in a Chrome content script (which executes in an + * isolated environment where long-polling doesn't work). + */ +export declare const isChromeExtensionContentScript: () => boolean; +/** + * Used to detect if we're in a Windows 8 Store app. + */ +export declare const isWindowsStoreApp: () => boolean; +/** + * Converts a server error code to a JavaScript Error + */ +export declare function errorForServerCode(code: string, query: QueryContext): Error; +/** + * Used to test for integer-looking strings + */ +export declare const INTEGER_REGEXP_: RegExp; +/** + * For use in keys, the minimum possible 32-bit integer. + */ +export declare const INTEGER_32_MIN = -2147483648; +/** + * For use in keys, the maximum possible 32-bit integer. + */ +export declare const INTEGER_32_MAX = 2147483647; +/** + * If the string contains a 32-bit integer, return it. Else return null. + */ +export declare const tryParseInt: (str: string) => number | null; +/** + * Helper to run some code but catch any exceptions and re-throw them later. + * Useful for preventing user callbacks from breaking internal code. + * + * Re-throwing the exception from a setTimeout is a little evil, but it's very + * convenient (we don't have to try to figure out when is a safe point to + * re-throw it), and the behavior seems reasonable: + * + * * If you aren't pausing on exceptions, you get an error in the console with + * the correct stack trace. + * * If you're pausing on all exceptions, the debugger will pause on your + * exception and then again when we rethrow it. + * * If you're only pausing on uncaught exceptions, the debugger will only pause + * on us re-throwing it. + * + * @param fn - The code to guard. + */ +export declare const exceptionGuard: (fn: () => void) => void; +/** + * Helper function to safely call opt_callback with the specified arguments. It: + * 1. Turns into a no-op if opt_callback is null or undefined. + * 2. Wraps the call inside exceptionGuard to prevent exceptions from breaking our state. + * + * @param callback - Optional onComplete callback. + * @param varArgs - Arbitrary args to be passed to opt_onComplete + */ +export declare const callUserCallback: (callback?: Function | null, ...varArgs: unknown[]) => void; +/** + * @returns {boolean} true if we think we're currently being crawled. + */ +export declare const beingCrawled: () => boolean; +/** + * Export a property of an object using a getter function. + */ +export declare const exportPropGetter: (object: object, name: string, fnGet: () => unknown) => void; +/** + * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting. + * + * It is removed with clearTimeout() as normal. + * + * @param fn - Function to run. + * @param time - Milliseconds to wait before running. + * @returns The setTimeout() return value. + */ +export declare const setTimeoutNonBlocking: (fn: () => void, time: number) => number | object; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/util/validation.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/util/validation.d.ts new file mode 100644 index 0000000..dc216b8 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/util/validation.d.ts @@ -0,0 +1,70 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { RepoInfo } from '../RepoInfo'; +import { Path, ValidationPath } from './Path'; +/** + * True for invalid Firebase keys + */ +export declare const INVALID_KEY_REGEX_: RegExp; +/** + * True for invalid Firebase paths. + * Allows '/' in paths. + */ +export declare const INVALID_PATH_REGEX_: RegExp; +/** + * Maximum number of characters to allow in leaf value + */ +export declare const MAX_LEAF_SIZE_: number; +export declare const isValidKey: (key: unknown) => boolean; +export declare const isValidPathString: (pathString: string) => boolean; +export declare const isValidRootPathString: (pathString: string) => boolean; +export declare const isValidPriority: (priority: unknown) => boolean; +/** + * Pre-validate a datum passed as an argument to Firebase function. + */ +export declare const validateFirebaseDataArg: (fnName: string, value: unknown, path: Path, optional: boolean) => void; +/** + * Validate a data object client-side before sending to server. + */ +export declare const validateFirebaseData: (errorPrefix: string, data: unknown, path_: Path | ValidationPath) => void; +/** + * Pre-validate paths passed in the firebase function. + */ +export declare const validateFirebaseMergePaths: (errorPrefix: string, mergePaths: Path[]) => void; +/** + * pre-validate an object passed as an argument to firebase function ( + * must be an object - e.g. for firebase.update()). + */ +export declare const validateFirebaseMergeDataArg: (fnName: string, data: unknown, path: Path, optional: boolean) => void; +export declare const validatePriority: (fnName: string, priority: unknown, optional: boolean) => void; +export declare const validateKey: (fnName: string, argumentName: string, key: string, optional: boolean) => void; +/** + * @internal + */ +export declare const validatePathString: (fnName: string, argumentName: string, pathString: string, optional: boolean) => void; +export declare const validateRootPathString: (fnName: string, argumentName: string, pathString: string, optional: boolean) => void; +/** + * @internal + */ +export declare const validateWritablePath: (fnName: string, path: Path) => void; +export declare const validateUrl: (fnName: string, parsedUrl: { + repoInfo: RepoInfo; + path: Path; +}) => void; +export declare const validateString: (fnName: string, argumentName: string, string: unknown, optional: boolean) => void; +export declare const validateObject: (fnName: string, argumentName: string, obj: unknown, optional: boolean) => void; +export declare const validateObjectContainsKey: (fnName: string, argumentName: string, obj: unknown, key: string, optional: boolean, optType?: string) => void; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/version.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/version.d.ts new file mode 100644 index 0000000..d6ea395 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/version.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The semver (www.semver.org) version of the SDK. */ +export declare let SDK_VERSION: string; +/** + * SDK_VERSION should be set before any database instance is created + * @internal + */ +export declare function setSDKVersion(version: string): void; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/view/CacheNode.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/view/CacheNode.d.ts new file mode 100644 index 0000000..da38015 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/view/CacheNode.d.ts @@ -0,0 +1,41 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Node } from '../snap/Node'; +import { Path } from '../util/Path'; +/** + * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully + * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g. + * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks + * whether a node potentially had children removed due to a filter. + */ +export declare class CacheNode { + private node_; + private fullyInitialized_; + private filtered_; + constructor(node_: Node, fullyInitialized_: boolean, filtered_: boolean); + /** + * Returns whether this node was fully initialized with either server data or a complete overwrite by the client + */ + isFullyInitialized(): boolean; + /** + * Returns whether this node is potentially missing children due to a filter applied to the node + */ + isFiltered(): boolean; + isCompleteForPath(path: Path): boolean; + isCompleteForChild(key: string): boolean; + getNode(): Node; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/view/Change.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/view/Change.d.ts new file mode 100644 index 0000000..985eee0 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/view/Change.d.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Node } from '../snap/Node'; +export declare const enum ChangeType { + /** Event type for a child added */ + CHILD_ADDED = "child_added", + /** Event type for a child removed */ + CHILD_REMOVED = "child_removed", + /** Event type for a child changed */ + CHILD_CHANGED = "child_changed", + /** Event type for a child moved */ + CHILD_MOVED = "child_moved", + /** Event type for a value change */ + VALUE = "value" +} +export interface Change { + /** @param type - The event type */ + type: ChangeType; + /** @param snapshotNode - The data */ + snapshotNode: Node; + /** @param childName - The name for this child, if it's a child even */ + childName?: string; + /** @param oldSnap - Used for intermediate processing of child changed events */ + oldSnap?: Node; + /** * @param prevName - The name for the previous child, if applicable */ + prevName?: string | null; +} +export declare function changeValue(snapshotNode: Node): Change; +export declare function changeChildAdded(childName: string, snapshotNode: Node): Change; +export declare function changeChildRemoved(childName: string, snapshotNode: Node): Change; +export declare function changeChildChanged(childName: string, snapshotNode: Node, oldSnap: Node): Change; +export declare function changeChildMoved(childName: string, snapshotNode: Node): Change; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/view/ChildChangeAccumulator.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/view/ChildChangeAccumulator.d.ts new file mode 100644 index 0000000..473ab16 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/view/ChildChangeAccumulator.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Change } from './Change'; +export declare class ChildChangeAccumulator { + private readonly changeMap; + trackChildChange(change: Change): void; + getChanges(): Change[]; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/view/CompleteChildSource.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/view/CompleteChildSource.d.ts new file mode 100644 index 0000000..fcc774c --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/view/CompleteChildSource.d.ts @@ -0,0 +1,55 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Index } from '../snap/indexes/Index'; +import { NamedNode, Node } from '../snap/Node'; +import { WriteTreeRef } from '../WriteTree'; +import { ViewCache } from './ViewCache'; +/** + * Since updates to filtered nodes might require nodes to be pulled in from "outside" the node, this interface + * can help to get complete children that can be pulled in. + * A class implementing this interface takes potentially multiple sources (e.g. user writes, server data from + * other views etc.) to try it's best to get a complete child that might be useful in pulling into the view. + * + * @interface + */ +export interface CompleteChildSource { + getCompleteChild(childKey: string): Node | null; + getChildAfterChild(index: Index, child: NamedNode, reverse: boolean): NamedNode | null; +} +/** + * An implementation of CompleteChildSource that never returns any additional children + */ +export declare class NoCompleteChildSource_ implements CompleteChildSource { + getCompleteChild(childKey?: string): Node | null; + getChildAfterChild(index?: Index, child?: NamedNode, reverse?: boolean): NamedNode | null; +} +/** + * Singleton instance. + */ +export declare const NO_COMPLETE_CHILD_SOURCE: NoCompleteChildSource_; +/** + * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or + * old event caches available to calculate complete children. + */ +export declare class WriteTreeCompleteChildSource implements CompleteChildSource { + private writes_; + private viewCache_; + private optCompleteServerCache_; + constructor(writes_: WriteTreeRef, viewCache_: ViewCache, optCompleteServerCache_?: Node | null); + getCompleteChild(childKey: string): Node | null; + getChildAfterChild(index: Index, child: NamedNode, reverse: boolean): NamedNode | null; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/view/Event.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/view/Event.d.ts new file mode 100644 index 0000000..69e326a --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/view/Event.d.ts @@ -0,0 +1,64 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DataSnapshot as ExpDataSnapshot } from '../../api/Reference_impl'; +import { Path } from '../util/Path'; +import { EventRegistration } from './EventRegistration'; +/** + * Encapsulates the data needed to raise an event + * @interface + */ +export interface Event { + getPath(): Path; + getEventType(): string; + getEventRunner(): () => void; + toString(): string; +} +/** + * One of the following strings: "value", "child_added", "child_changed", + * "child_removed", or "child_moved." + */ +export type EventType = 'value' | 'child_added' | 'child_changed' | 'child_moved' | 'child_removed'; +/** + * Encapsulates the data needed to raise an event + */ +export declare class DataEvent implements Event { + eventType: EventType; + eventRegistration: EventRegistration; + snapshot: ExpDataSnapshot; + prevName?: string | null; + /** + * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed + * @param eventRegistration - The function to call to with the event data. User provided + * @param snapshot - The data backing the event + * @param prevName - Optional, the name of the previous child for child_* events. + */ + constructor(eventType: EventType, eventRegistration: EventRegistration, snapshot: ExpDataSnapshot, prevName?: string | null); + getPath(): Path; + getEventType(): string; + getEventRunner(): () => void; + toString(): string; +} +export declare class CancelEvent implements Event { + eventRegistration: EventRegistration; + error: Error; + path: Path; + constructor(eventRegistration: EventRegistration, error: Error, path: Path); + getPath(): Path; + getEventType(): string; + getEventRunner(): () => void; + toString(): string; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/view/EventGenerator.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/view/EventGenerator.d.ts new file mode 100644 index 0000000..bc916b8 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/view/EventGenerator.d.ts @@ -0,0 +1,42 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Index } from '../snap/indexes/Index'; +import { Node } from '../snap/Node'; +import { Change } from './Change'; +import { Event } from './Event'; +import { EventRegistration, QueryContext } from './EventRegistration'; +/** + * An EventGenerator is used to convert "raw" changes (Change) as computed by the + * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges() + * for details. + * + */ +export declare class EventGenerator { + query_: QueryContext; + index_: Index; + constructor(query_: QueryContext); +} +/** + * Given a set of raw changes (no moved events and prevName not specified yet), and a set of + * EventRegistrations that should be notified of these changes, generate the actual events to be raised. + * + * Notes: + * - child_moved events will be synthesized at this time for any child_changed events that affect + * our index. + * - prevName will be calculated based on the index ordering. + */ +export declare function eventGeneratorGenerateEventsForChanges(eventGenerator: EventGenerator, changes: Change[], eventCache: Node, eventRegistrations: EventRegistration[]): Event[]; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/view/EventQueue.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/view/EventQueue.d.ts new file mode 100644 index 0000000..63ea6f4 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/view/EventQueue.d.ts @@ -0,0 +1,67 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Path } from '../util/Path'; +import { Event } from './Event'; +/** + * The event queue serves a few purposes: + * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more + * events being queued. + * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events, + * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call + * left off, ensuring that the events are still raised synchronously and in order. + * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued + * events are raised synchronously. + * + * NOTE: This can all go away if/when we move to async events. + * + */ +export declare class EventQueue { + eventLists_: EventList[]; + /** + * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes. + */ + recursionDepth_: number; +} +/** + * @param eventDataList - The new events to queue. + */ +export declare function eventQueueQueueEvents(eventQueue: EventQueue, eventDataList: Event[]): void; +/** + * Queues the specified events and synchronously raises all events (including previously queued ones) + * for the specified path. + * + * It is assumed that the new events are all for the specified path. + * + * @param path - The path to raise events for. + * @param eventDataList - The new events to raise. + */ +export declare function eventQueueRaiseEventsAtPath(eventQueue: EventQueue, path: Path, eventDataList: Event[]): void; +/** + * Queues the specified events and synchronously raises all events (including previously queued ones) for + * locations related to the specified change path (i.e. all ancestors and descendants). + * + * It is assumed that the new events are all related (ancestor or descendant) to the specified path. + * + * @param changedPath - The path to raise events for. + * @param eventDataList - The events to raise + */ +export declare function eventQueueRaiseEventsForChangedPath(eventQueue: EventQueue, changedPath: Path, eventDataList: Event[]): void; +interface EventList { + events: Event[]; + path: Path; +} +export {}; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/view/EventRegistration.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/view/EventRegistration.d.ts new file mode 100644 index 0000000..4425097 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/view/EventRegistration.d.ts @@ -0,0 +1,87 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DataSnapshot } from '../../api/Reference_impl'; +import { Repo } from '../Repo'; +import { Path } from '../util/Path'; +import { Change } from './Change'; +import { CancelEvent, Event } from './Event'; +import { QueryParams } from './QueryParams'; +/** + * A user callback. Callbacks issues from the Legacy SDK maintain references + * to the original user-issued callbacks, which allows equality + * comparison by reference even though this callbacks are wrapped before + * they can be passed to the firebase@exp SDK. + * + * @internal + */ +export interface UserCallback { + (dataSnapshot: DataSnapshot, previousChildName?: string | null): unknown; + userCallback?: unknown; + context?: object | null; +} +/** + * A wrapper class that converts events from the database@exp SDK to the legacy + * Database SDK. Events are not converted directly as event registration relies + * on reference comparison of the original user callback (see `matches()`) and + * relies on equality of the legacy SDK's `context` object. + */ +export declare class CallbackContext { + private readonly snapshotCallback; + private readonly cancelCallback?; + constructor(snapshotCallback: UserCallback, cancelCallback?: (error: Error) => unknown); + onValue(expDataSnapshot: DataSnapshot, previousChildName?: string | null): void; + onCancel(error: Error): void; + get hasCancelCallback(): boolean; + matches(other: CallbackContext): boolean; +} +export interface QueryContext { + readonly _queryIdentifier: string; + readonly _queryObject: object; + readonly _repo: Repo; + readonly _path: Path; + readonly _queryParams: QueryParams; +} +/** + * An EventRegistration is basically an event type ('value', 'child_added', etc.) and a callback + * to be notified of that type of event. + * + * That said, it can also contain a cancel callback to be notified if the event is canceled. And + * currently, this code is organized around the idea that you would register multiple child_ callbacks + * together, as a single EventRegistration. Though currently we don't do that. + */ +export interface EventRegistration { + /** + * True if this container has a callback to trigger for this event type + */ + respondsTo(eventType: string): boolean; + createEvent(change: Change, query: QueryContext): Event; + /** + * Given event data, return a function to trigger the user's callback + */ + getEventRunner(eventData: Event): () => void; + createCancelEvent(error: Error, path: Path): CancelEvent | null; + matches(other: EventRegistration): boolean; + /** + * False basically means this is a "dummy" callback container being used as a sentinel + * to remove all callback containers of a particular type. (e.g. if the user does + * ref.off('value') without specifying a specific callback). + * + * (TODO: Rework this, since it's hacky) + * + */ + hasAnyCallback(): boolean; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/view/QueryParams.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/view/QueryParams.d.ts new file mode 100644 index 0000000..47870f7 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/view/QueryParams.d.ts @@ -0,0 +1,95 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Index } from '../snap/indexes/Index'; +import { PriorityIndex } from '../snap/indexes/PriorityIndex'; +import { NodeFilter } from './filter/NodeFilter'; +/** + * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a + * range to be returned for a particular location. It is assumed that validation of parameters is done at the + * user-facing API level, so it is not done here. + * + * @internal + */ +export declare class QueryParams { + limitSet_: boolean; + startSet_: boolean; + startNameSet_: boolean; + startAfterSet_: boolean; + endSet_: boolean; + endNameSet_: boolean; + endBeforeSet_: boolean; + limit_: number; + viewFrom_: string; + indexStartValue_: unknown | null; + indexStartName_: string; + indexEndValue_: unknown | null; + indexEndName_: string; + index_: PriorityIndex; + hasStart(): boolean; + /** + * @returns True if it would return from left. + */ + isViewFromLeft(): boolean; + /** + * Only valid to call if hasStart() returns true + */ + getIndexStartValue(): unknown; + /** + * Only valid to call if hasStart() returns true. + * Returns the starting key name for the range defined by these query parameters + */ + getIndexStartName(): string; + hasEnd(): boolean; + /** + * Only valid to call if hasEnd() returns true. + */ + getIndexEndValue(): unknown; + /** + * Only valid to call if hasEnd() returns true. + * Returns the end key name for the range defined by these query parameters + */ + getIndexEndName(): string; + hasLimit(): boolean; + /** + * @returns True if a limit has been set and it has been explicitly anchored + */ + hasAnchoredLimit(): boolean; + /** + * Only valid to call if hasLimit() returns true + */ + getLimit(): number; + getIndex(): Index; + loadsAllData(): boolean; + isDefault(): boolean; + copy(): QueryParams; +} +export declare function queryParamsGetNodeFilter(queryParams: QueryParams): NodeFilter; +export declare function queryParamsLimit(queryParams: QueryParams, newLimit: number): QueryParams; +export declare function queryParamsLimitToFirst(queryParams: QueryParams, newLimit: number): QueryParams; +export declare function queryParamsLimitToLast(queryParams: QueryParams, newLimit: number): QueryParams; +export declare function queryParamsStartAt(queryParams: QueryParams, indexValue: unknown, key?: string | null): QueryParams; +export declare function queryParamsStartAfter(queryParams: QueryParams, indexValue: unknown, key?: string | null): QueryParams; +export declare function queryParamsEndAt(queryParams: QueryParams, indexValue: unknown, key?: string | null): QueryParams; +export declare function queryParamsEndBefore(queryParams: QueryParams, indexValue: unknown, key?: string | null): QueryParams; +export declare function queryParamsOrderBy(queryParams: QueryParams, index: Index): QueryParams; +/** + * Returns a set of REST query string parameters representing this query. + * + * @returns query string parameters + */ +export declare function queryParamsToRestQueryStringParameters(queryParams: QueryParams): Record; +export declare function queryParamsGetQueryObject(queryParams: QueryParams): Record; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/view/View.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/view/View.d.ts new file mode 100644 index 0000000..a872658 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/view/View.d.ts @@ -0,0 +1,59 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Operation } from '../operation/Operation'; +import { Node } from '../snap/Node'; +import { Path } from '../util/Path'; +import { WriteTreeRef } from '../WriteTree'; +import { Event } from './Event'; +import { EventGenerator } from './EventGenerator'; +import { EventRegistration, QueryContext } from './EventRegistration'; +import { ViewCache } from './ViewCache'; +import { ViewProcessor } from './ViewProcessor'; +/** + * A view represents a specific location and query that has 1 or more event registrations. + * + * It does several things: + * - Maintains the list of event registrations for this location/query. + * - Maintains a cache of the data visible for this location/query. + * - Applies new operations (via applyOperation), updates the cache, and based on the event + * registrations returns the set of events to be raised. + */ +export declare class View { + private query_; + processor_: ViewProcessor; + viewCache_: ViewCache; + eventRegistrations_: EventRegistration[]; + eventGenerator_: EventGenerator; + constructor(query_: QueryContext, initialViewCache: ViewCache); + get query(): QueryContext; +} +export declare function viewGetServerCache(view: View): Node | null; +export declare function viewGetCompleteNode(view: View): Node | null; +export declare function viewGetCompleteServerCache(view: View, path: Path): Node | null; +export declare function viewIsEmpty(view: View): boolean; +export declare function viewAddEventRegistration(view: View, eventRegistration: EventRegistration): void; +/** + * @param eventRegistration - If null, remove all callbacks. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @returns Cancel events, if cancelError was provided. + */ +export declare function viewRemoveEventRegistration(view: View, eventRegistration: EventRegistration | null, cancelError?: Error): Event[]; +/** + * Applies the given Operation, updates our cache, and returns the appropriate events. + */ +export declare function viewApplyOperation(view: View, operation: Operation, writesCache: WriteTreeRef, completeServerCache: Node | null): Event[]; +export declare function viewGetInitialEvents(view: View, registration: EventRegistration): Event[]; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/view/ViewCache.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/view/ViewCache.d.ts new file mode 100644 index 0000000..089749d --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/view/ViewCache.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Node } from '../snap/Node'; +import { CacheNode } from './CacheNode'; +/** + * Stores the data we have cached for a view. + * + * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes). + */ +export interface ViewCache { + readonly eventCache: CacheNode; + readonly serverCache: CacheNode; +} +export declare function newViewCache(eventCache: CacheNode, serverCache: CacheNode): ViewCache; +export declare function viewCacheUpdateEventSnap(viewCache: ViewCache, eventSnap: Node, complete: boolean, filtered: boolean): ViewCache; +export declare function viewCacheUpdateServerSnap(viewCache: ViewCache, serverSnap: Node, complete: boolean, filtered: boolean): ViewCache; +export declare function viewCacheGetCompleteEventSnap(viewCache: ViewCache): Node | null; +export declare function viewCacheGetCompleteServerSnap(viewCache: ViewCache): Node | null; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/view/ViewProcessor.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/view/ViewProcessor.d.ts new file mode 100644 index 0000000..9baa237 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/view/ViewProcessor.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Operation } from '../operation/Operation'; +import { Node } from '../snap/Node'; +import { WriteTreeRef } from '../WriteTree'; +import { Change } from './Change'; +import { NodeFilter } from './filter/NodeFilter'; +import { ViewCache } from './ViewCache'; +export interface ProcessorResult { + readonly viewCache: ViewCache; + readonly changes: Change[]; +} +export interface ViewProcessor { + readonly filter: NodeFilter; +} +export declare function newViewProcessor(filter: NodeFilter): ViewProcessor; +export declare function viewProcessorAssertIndexed(viewProcessor: ViewProcessor, viewCache: ViewCache): void; +export declare function viewProcessorApplyOperation(viewProcessor: ViewProcessor, oldViewCache: ViewCache, operation: Operation, writesCache: WriteTreeRef, completeCache: Node | null): ProcessorResult; diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/view/filter/IndexedFilter.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/view/filter/IndexedFilter.d.ts new file mode 100644 index 0000000..07584dd --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/view/filter/IndexedFilter.d.ts @@ -0,0 +1,35 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Index } from '../../snap/indexes/Index'; +import { Node } from '../../snap/Node'; +import { Path } from '../../util/Path'; +import { ChildChangeAccumulator } from '../ChildChangeAccumulator'; +import { CompleteChildSource } from '../CompleteChildSource'; +import { NodeFilter } from './NodeFilter'; +/** + * Doesn't really filter nodes but applies an index to the node and keeps track of any changes + */ +export declare class IndexedFilter implements NodeFilter { + private readonly index_; + constructor(index_: Index); + updateChild(snap: Node, key: string, newChild: Node, affectedPath: Path, source: CompleteChildSource, optChangeAccumulator: ChildChangeAccumulator | null): Node; + updateFullNode(oldSnap: Node, newSnap: Node, optChangeAccumulator: ChildChangeAccumulator | null): Node; + updatePriority(oldSnap: Node, newPriority: Node): Node; + filtersNodes(): boolean; + getIndexedFilter(): IndexedFilter; + getIndex(): Index; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/view/filter/LimitedFilter.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/view/filter/LimitedFilter.d.ts new file mode 100644 index 0000000..cb2da45 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/view/filter/LimitedFilter.d.ts @@ -0,0 +1,47 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Index } from '../../snap/indexes/Index'; +import { Node } from '../../snap/Node'; +import { Path } from '../../util/Path'; +import { ChildChangeAccumulator } from '../ChildChangeAccumulator'; +import { CompleteChildSource } from '../CompleteChildSource'; +import { QueryParams } from '../QueryParams'; +import { IndexedFilter } from './IndexedFilter'; +import { NodeFilter } from './NodeFilter'; +/** + * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible + */ +export declare class LimitedFilter implements NodeFilter { + private readonly rangedFilter_; + private readonly index_; + private readonly limit_; + private readonly reverse_; + private readonly startIsInclusive_; + private readonly endIsInclusive_; + constructor(params: QueryParams); + updateChild(snap: Node, key: string, newChild: Node, affectedPath: Path, source: CompleteChildSource, optChangeAccumulator: ChildChangeAccumulator | null): Node; + updateFullNode(oldSnap: Node, newSnap: Node, optChangeAccumulator: ChildChangeAccumulator | null): Node; + updatePriority(oldSnap: Node, newPriority: Node): Node; + filtersNodes(): boolean; + getIndexedFilter(): IndexedFilter; + getIndex(): Index; + private fullLimitUpdateChild_; + private withinDirectionalStart; + private withinDirectionalEnd; + private withinStartPost; + private withinEndPost; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/view/filter/NodeFilter.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/view/filter/NodeFilter.d.ts new file mode 100644 index 0000000..b1fafb2 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/view/filter/NodeFilter.d.ts @@ -0,0 +1,54 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Index } from '../../snap/indexes/Index'; +import { Node } from '../../snap/Node'; +import { Path } from '../../util/Path'; +import { ChildChangeAccumulator } from '../ChildChangeAccumulator'; +import { CompleteChildSource } from '../CompleteChildSource'; +/** + * NodeFilter is used to update nodes and complete children of nodes while applying queries on the fly and keeping + * track of any child changes. This class does not track value changes as value changes depend on more + * than just the node itself. Different kind of queries require different kind of implementations of this interface. + * @interface + */ +export interface NodeFilter { + /** + * Update a single complete child in the snap. If the child equals the old child in the snap, this is a no-op. + * The method expects an indexed snap. + */ + updateChild(snap: Node, key: string, newChild: Node, affectedPath: Path, source: CompleteChildSource, optChangeAccumulator: ChildChangeAccumulator | null): Node; + /** + * Update a node in full and output any resulting change from this complete update. + */ + updateFullNode(oldSnap: Node, newSnap: Node, optChangeAccumulator: ChildChangeAccumulator | null): Node; + /** + * Update the priority of the root node + */ + updatePriority(oldSnap: Node, newPriority: Node): Node; + /** + * Returns true if children might be filtered due to query criteria + */ + filtersNodes(): boolean; + /** + * Returns the index filter that this filter uses to get a NodeFilter that doesn't filter any children. + */ + getIndexedFilter(): NodeFilter; + /** + * Returns the index that this filter uses + */ + getIndex(): Index; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/core/view/filter/RangedFilter.d.ts b/node_modules/@firebase/database/dist/node-esm/src/core/view/filter/RangedFilter.d.ts new file mode 100644 index 0000000..bef847a --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/core/view/filter/RangedFilter.d.ts @@ -0,0 +1,47 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NamedNode, Node } from '../../../core/snap/Node'; +import { Index } from '../../snap/indexes/Index'; +import { Path } from '../../util/Path'; +import { ChildChangeAccumulator } from '../ChildChangeAccumulator'; +import { CompleteChildSource } from '../CompleteChildSource'; +import { QueryParams } from '../QueryParams'; +import { IndexedFilter } from './IndexedFilter'; +import { NodeFilter } from './NodeFilter'; +/** + * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node + */ +export declare class RangedFilter implements NodeFilter { + private indexedFilter_; + private index_; + private startPost_; + private endPost_; + private startIsInclusive_; + private endIsInclusive_; + constructor(params: QueryParams); + getStartPost(): NamedNode; + getEndPost(): NamedNode; + matches(node: NamedNode): boolean; + updateChild(snap: Node, key: string, newChild: Node, affectedPath: Path, source: CompleteChildSource, optChangeAccumulator: ChildChangeAccumulator | null): Node; + updateFullNode(oldSnap: Node, newSnap: Node, optChangeAccumulator: ChildChangeAccumulator | null): Node; + updatePriority(oldSnap: Node, newPriority: Node): Node; + filtersNodes(): boolean; + getIndexedFilter(): IndexedFilter; + getIndex(): Index; + private static getStartPost_; + private static getEndPost_; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/index.d.ts b/node_modules/@firebase/database/dist/node-esm/src/index.d.ts new file mode 100644 index 0000000..8990721 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/index.d.ts @@ -0,0 +1,28 @@ +/** + * Firebase Realtime Database + * + * @packageDocumentation + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Database } from './api/Database'; +export * from './api'; +declare module '@firebase/component' { + interface NameServiceMapping { + 'database': Database; + } +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/index.node.d.ts b/node_modules/@firebase/database/dist/node-esm/src/index.node.d.ts new file mode 100644 index 0000000..952da59 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/index.node.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './api'; diff --git a/node_modules/@firebase/database/dist/node-esm/src/index.standalone.d.ts b/node_modules/@firebase/database/dist/node-esm/src/index.standalone.d.ts new file mode 100644 index 0000000..c852b29 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/index.standalone.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './api.standalone'; diff --git a/node_modules/@firebase/database/dist/node-esm/src/internal/index.d.ts b/node_modules/@firebase/database/dist/node-esm/src/internal/index.d.ts new file mode 100644 index 0000000..77b7558 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/internal/index.d.ts @@ -0,0 +1,38 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseAppCheckInternal } from '@firebase/app-check-interop-types'; +import { FirebaseApp } from '@firebase/app-types'; +import { FirebaseAuthInternal } from '@firebase/auth-interop-types'; +import { Database } from '../api.standalone'; +/** + * Used by console to create a database based on the app, + * passed database URL and a custom auth implementation. + * @internal + * @param app - A valid FirebaseApp-like object + * @param url - A valid Firebase databaseURL + * @param version - custom version e.g. firebase-admin version + * @param customAppCheckImpl - custom app check implementation + * @param customAuthImpl - custom auth implementation + */ +export declare function _initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, nodeAdmin }: { + app: FirebaseApp; + url: string; + version: string; + customAuthImpl: FirebaseAuthInternal; + customAppCheckImpl?: FirebaseAppCheckInternal; + nodeAdmin?: boolean; +}): Database; diff --git a/node_modules/@firebase/database/dist/node-esm/src/realtime/BrowserPollConnection.d.ts b/node_modules/@firebase/database/dist/node-esm/src/realtime/BrowserPollConnection.d.ts new file mode 100644 index 0000000..b99fd6e --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/realtime/BrowserPollConnection.d.ts @@ -0,0 +1,198 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { RepoInfo } from '../core/RepoInfo'; +import { PacketReceiver } from './polling/PacketReceiver'; +import { Transport } from './Transport'; +export declare const FIREBASE_LONGPOLL_START_PARAM = "start"; +export declare const FIREBASE_LONGPOLL_CLOSE_COMMAND = "close"; +export declare const FIREBASE_LONGPOLL_COMMAND_CB_NAME = "pLPCommand"; +export declare const FIREBASE_LONGPOLL_DATA_CB_NAME = "pRTLPCB"; +export declare const FIREBASE_LONGPOLL_ID_PARAM = "id"; +export declare const FIREBASE_LONGPOLL_PW_PARAM = "pw"; +export declare const FIREBASE_LONGPOLL_SERIAL_PARAM = "ser"; +export declare const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = "cb"; +export declare const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = "seg"; +export declare const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = "ts"; +export declare const FIREBASE_LONGPOLL_DATA_PARAM = "d"; +export declare const FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = "disconn"; +export declare const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = "dframe"; +/** + * This class manages a single long-polling connection. + */ +export declare class BrowserPollConnection implements Transport { + connId: string; + repoInfo: RepoInfo; + private applicationId?; + private appCheckToken?; + private authToken?; + transportSessionId?: string; + lastSessionId?: string; + bytesSent: number; + bytesReceived: number; + urlFn: (params: object) => string; + scriptTagHolder: FirebaseIFrameScriptHolder; + myDisconnFrame: HTMLIFrameElement; + curSegmentNum: number; + myPacketOrderer: PacketReceiver; + id: string; + password: string; + private log_; + private stats_; + private everConnected_; + private isClosed_; + private connectTimeoutTimer_; + private onDisconnect_; + /** + * @param connId An identifier for this connection, used for logging + * @param repoInfo The info for the endpoint to send data to. + * @param applicationId The Firebase App ID for this project. + * @param appCheckToken The AppCheck token for this client. + * @param authToken The AuthToken to use for this connection. + * @param transportSessionId Optional transportSessionid if we are + * reconnecting for an existing transport session + * @param lastSessionId Optional lastSessionId if the PersistentConnection has + * already created a connection previously + */ + constructor(connId: string, repoInfo: RepoInfo, applicationId?: string, appCheckToken?: string, authToken?: string, transportSessionId?: string, lastSessionId?: string); + /** + * @param onMessage - Callback when messages arrive + * @param onDisconnect - Callback with connection lost. + */ + open(onMessage: (msg: {}) => void, onDisconnect: (a?: boolean) => void): void; + /** + * Call this when a handshake has completed successfully and we want to consider the connection established + */ + start(): void; + static forceAllow_: boolean; + /** + * Forces long polling to be considered as a potential transport + */ + static forceAllow(): void; + static forceDisallow_: boolean; + /** + * Forces longpolling to not be considered as a potential transport + */ + static forceDisallow(): void; + static isAvailable(): boolean; + /** + * No-op for polling + */ + markConnectionHealthy(): void; + /** + * Stops polling and cleans up the iframe + */ + private shutdown_; + /** + * Triggered when this transport is closed + */ + private onClosed_; + /** + * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server + * that we've left. + */ + close(): void; + /** + * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then + * broken into chunks (since URLs have a small maximum length). + * @param data - The JSON data to transmit. + */ + send(data: {}): void; + /** + * This is how we notify the server that we're leaving. + * We aren't able to send requests with DHTML on a window close event, but we can + * trigger XHR requests in some browsers (everything but Opera basically). + */ + addDisconnectPingFrame(id: string, pw: string): void; + /** + * Used to track the bytes received by this client + */ + private incrementIncomingBytes_; +} +export interface IFrameElement extends HTMLIFrameElement { + doc: Document; +} +/********************************************************************************************* + * A wrapper around an iframe that is used as a long-polling script holder. + *********************************************************************************************/ +export declare class FirebaseIFrameScriptHolder { + onDisconnect: () => void; + urlFn: (a: object) => string; + outstandingRequests: Set; + pendingSegs: Array<{ + seg: number; + ts: number; + d: unknown; + }>; + currentSerial: number; + sendNewPolls: boolean; + uniqueCallbackIdentifier: number; + myIFrame: IFrameElement; + alive: boolean; + myID: string; + myPW: string; + commandCB: (command: string, ...args: unknown[]) => void; + onMessageCB: (...args: unknown[]) => void; + /** + * @param commandCB - The callback to be called when control commands are received from the server. + * @param onMessageCB - The callback to be triggered when responses arrive from the server. + * @param onDisconnect - The callback to be triggered when this tag holder is closed + * @param urlFn - A function that provides the URL of the endpoint to send data to. + */ + constructor(commandCB: (command: string, ...args: unknown[]) => void, onMessageCB: (...args: unknown[]) => void, onDisconnect: () => void, urlFn: (a: object) => string); + /** + * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can + * actually use. + */ + private static createIFrame_; + /** + * Cancel all outstanding queries and remove the frame. + */ + close(): void; + /** + * Actually start the long-polling session by adding the first script tag(s) to the iframe. + * @param id - The ID of this connection + * @param pw - The password for this connection + */ + startLongPoll(id: string, pw: string): void; + /** + * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't + * too many outstanding requests and we are still alive. + * + * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if + * needed. + */ + private newRequest_; + /** + * Queue a packet for transmission to the server. + * @param segnum - A sequential id for this packet segment used for reassembly + * @param totalsegs - The total number of segments in this packet + * @param data - The data for this segment. + */ + enqueueSegment(segnum: number, totalsegs: number, data: unknown): void; + /** + * Add a script tag for a regular long-poll request. + * @param url - The URL of the script tag. + * @param serial - The serial number of the request. + */ + private addLongPollTag_; + /** + * Add an arbitrary script tag to the iframe. + * @param url - The URL for the script tag source. + * @param loadCB - A callback to be triggered once the script has loaded. + */ + addTag(url: string, loadCB: () => void): void; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/realtime/Connection.d.ts b/node_modules/@firebase/database/dist/node-esm/src/realtime/Connection.d.ts new file mode 100644 index 0000000..e20e244 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/realtime/Connection.d.ts @@ -0,0 +1,102 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { RepoInfo } from '../core/RepoInfo'; +/** + * Creates a new real-time connection to the server using whichever method works + * best in the current browser. + */ +export declare class Connection { + id: string; + private repoInfo_; + private applicationId_; + private appCheckToken_; + private authToken_; + private onMessage_; + private onReady_; + private onDisconnect_; + private onKill_; + lastSessionId?: string; + connectionCount: number; + pendingDataMessages: unknown[]; + sessionId: string; + private conn_; + private healthyTimeout_; + private isHealthy_; + private log_; + private primaryResponsesRequired_; + private rx_; + private secondaryConn_; + private secondaryResponsesRequired_; + private state_; + private transportManager_; + private tx_; + /** + * @param id - an id for this connection + * @param repoInfo_ - the info for the endpoint to connect to + * @param applicationId_ - the Firebase App ID for this project + * @param appCheckToken_ - The App Check Token for this device. + * @param authToken_ - The auth token for this session. + * @param onMessage_ - the callback to be triggered when a server-push message arrives + * @param onReady_ - the callback to be triggered when this connection is ready to send messages. + * @param onDisconnect_ - the callback to be triggered when a connection was lost + * @param onKill_ - the callback to be triggered when this connection has permanently shut down. + * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server + */ + constructor(id: string, repoInfo_: RepoInfo, applicationId_: string | undefined, appCheckToken_: string | undefined, authToken_: string | undefined, onMessage_: (a: {}) => void, onReady_: (a: number, b: string) => void, onDisconnect_: () => void, onKill_: (a: string) => void, lastSessionId?: string); + /** + * Starts a connection attempt + */ + private start_; + private nextTransportId_; + private disconnReceiver_; + private connReceiver_; + /** + * @param dataMsg - An arbitrary data message to be sent to the server + */ + sendRequest(dataMsg: object): void; + tryCleanupConnection(): void; + private onSecondaryControl_; + private onSecondaryMessageReceived_; + private upgradeIfSecondaryHealthy_; + private proceedWithUpgrade_; + private onPrimaryMessageReceived_; + private onDataMessage_; + private onPrimaryResponse_; + private onControl_; + /** + * @param handshake - The handshake data returned from the server + */ + private onHandshake_; + private tryStartUpgrade_; + private startUpgrade_; + private onReset_; + private onConnectionEstablished_; + private sendPingOnPrimaryIfNecessary_; + private onSecondaryConnectionLost_; + /** + * @param everConnected - Whether or not the connection ever reached a server. Used to determine if + * we should flush the host cache + */ + private onConnectionLost_; + private onConnectionShutdown_; + private sendData_; + /** + * Cleans up this connection, calling the appropriate callbacks + */ + close(): void; + private closeConnections_; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/realtime/Constants.d.ts b/node_modules/@firebase/database/dist/node-esm/src/realtime/Constants.d.ts new file mode 100644 index 0000000..4ff77ff --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/realtime/Constants.d.ts @@ -0,0 +1,27 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const PROTOCOL_VERSION = "5"; +export declare const VERSION_PARAM = "v"; +export declare const TRANSPORT_SESSION_PARAM = "s"; +export declare const REFERER_PARAM = "r"; +export declare const FORGE_REF = "f"; +export declare const FORGE_DOMAIN_RE: RegExp; +export declare const LAST_SESSION_PARAM = "ls"; +export declare const APPLICATION_ID_PARAM = "p"; +export declare const APP_CHECK_TOKEN_PARAM = "ac"; +export declare const WEBSOCKET = "websocket"; +export declare const LONG_POLLING = "long_polling"; diff --git a/node_modules/@firebase/database/dist/node-esm/src/realtime/Transport.d.ts b/node_modules/@firebase/database/dist/node-esm/src/realtime/Transport.d.ts new file mode 100644 index 0000000..d66429e --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/realtime/Transport.d.ts @@ -0,0 +1,58 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { RepoInfo } from '../core/RepoInfo'; +export interface TransportConstructor { + new (connId: string, repoInfo: RepoInfo, applicationId?: string, appCheckToken?: string, authToken?: string, transportSessionId?: string, lastSessionId?: string): Transport; + isAvailable: () => boolean; + responsesRequiredToBeHealthy?: number; + healthyTimeout?: number; +} +export declare abstract class Transport { + /** + * Bytes received since connection started. + */ + abstract bytesReceived: number; + /** + * Bytes sent since connection started. + */ + abstract bytesSent: number; + /** + * An identifier for this connection, used for logging + */ + abstract connId: string; + /** + * @param connId - An identifier for this connection, used for logging + * @param repoInfo - The info for the endpoint to send data to. + * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport session + * @param lastSessionId - Optional lastSessionId if there was a previous connection + * @interface + */ + constructor(connId: string, repoInfo: RepoInfo, transportSessionId?: string, lastSessionId?: string); + /** + * @param onMessage - Callback when messages arrive + * @param onDisconnect - Callback with connection lost. + */ + abstract open(onMessage: (a: {}) => void, onDisconnect: (a?: boolean) => void): void; + abstract start(): void; + abstract close(): void; + /** + * @param data - The JSON data to transmit + */ + abstract send(data: {}): void; + abstract markConnectionHealthy(): void; + abstract markConnectionHealthy(): void; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/realtime/TransportManager.d.ts b/node_modules/@firebase/database/dist/node-esm/src/realtime/TransportManager.d.ts new file mode 100644 index 0000000..4f2ef51 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/realtime/TransportManager.d.ts @@ -0,0 +1,50 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { RepoInfo } from '../core/RepoInfo'; +import { BrowserPollConnection } from './BrowserPollConnection'; +import { TransportConstructor } from './Transport'; +import { WebSocketConnection } from './WebSocketConnection'; +/** + * Currently simplistic, this class manages what transport a Connection should use at various stages of its + * lifecycle. + * + * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if + * they are available. + */ +export declare class TransportManager { + private transports_; + static globalTransportInitialized_: boolean; + static get ALL_TRANSPORTS(): (typeof BrowserPollConnection | typeof WebSocketConnection)[]; + /** + * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after + * TransportManager has already set up transports_ + */ + static get IS_TRANSPORT_INITIALIZED(): boolean; + /** + * @param repoInfo - Metadata around the namespace we're connecting to + */ + constructor(repoInfo: RepoInfo); + private initTransports_; + /** + * @returns The constructor for the initial transport to use + */ + initialTransport(): TransportConstructor; + /** + * @returns The constructor for the next transport, or null + */ + upgradeTransport(): TransportConstructor | null; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/realtime/WebSocketConnection.d.ts b/node_modules/@firebase/database/dist/node-esm/src/realtime/WebSocketConnection.d.ts new file mode 100644 index 0000000..f427bb5 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/realtime/WebSocketConnection.d.ts @@ -0,0 +1,127 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { RepoInfo } from '../core/RepoInfo'; +import { Transport } from './Transport'; +export declare function setWebSocketImpl(impl: any): void; +/** + * Create a new websocket connection with the given callbacks. + */ +export declare class WebSocketConnection implements Transport { + connId: string; + private applicationId?; + private appCheckToken?; + private authToken?; + keepaliveTimer: number | null; + frames: string[] | null; + totalFrames: number; + bytesSent: number; + bytesReceived: number; + connURL: string; + onDisconnect: (a?: boolean) => void; + onMessage: (msg: {}) => void; + mySock: WebSocket | null; + private log_; + private stats_; + private everConnected_; + private isClosed_; + private nodeAdmin; + /** + * @param connId identifier for this transport + * @param repoInfo The info for the websocket endpoint. + * @param applicationId The Firebase App ID for this project. + * @param appCheckToken The App Check Token for this client. + * @param authToken The Auth Token for this client. + * @param transportSessionId Optional transportSessionId if this is connecting + * to an existing transport session + * @param lastSessionId Optional lastSessionId if there was a previous + * connection + */ + constructor(connId: string, repoInfo: RepoInfo, applicationId?: string, appCheckToken?: string, authToken?: string, transportSessionId?: string, lastSessionId?: string); + /** + * @param repoInfo - The info for the websocket endpoint. + * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport + * session + * @param lastSessionId - Optional lastSessionId if there was a previous connection + * @returns connection url + */ + private static connectionURL_; + /** + * @param onMessage - Callback when messages arrive + * @param onDisconnect - Callback with connection lost. + */ + open(onMessage: (msg: {}) => void, onDisconnect: (a?: boolean) => void): void; + /** + * No-op for websockets, we don't need to do anything once the connection is confirmed as open + */ + start(): void; + static forceDisallow_: boolean; + static forceDisallow(): void; + static isAvailable(): boolean; + /** + * Number of response before we consider the connection "healthy." + */ + static responsesRequiredToBeHealthy: number; + /** + * Time to wait for the connection te become healthy before giving up. + */ + static healthyTimeout: number; + /** + * Returns true if we previously failed to connect with this transport. + */ + static previouslyFailed(): boolean; + markConnectionHealthy(): void; + private appendFrame_; + /** + * @param frameCount - The number of frames we are expecting from the server + */ + private handleNewFrameCount_; + /** + * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1 + * @returns Any remaining data to be process, or null if there is none + */ + private extractFrameCount_; + /** + * Process a websocket frame that has arrived from the server. + * @param mess - The frame data + */ + handleIncomingFrame(mess: { + [k: string]: unknown; + }): void; + /** + * Send a message to the server + * @param data - The JSON object to transmit + */ + send(data: {}): void; + private shutdown_; + private onClosed_; + /** + * External-facing close handler. + * Close the websocket and kill the connection. + */ + close(): void; + /** + * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after + * the last activity. + */ + resetKeepAlive(): void; + /** + * Send a string over the websocket. + * + * @param str - String to send. + */ + private sendString_; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/realtime/polling/PacketReceiver.d.ts b/node_modules/@firebase/database/dist/node-esm/src/realtime/polling/PacketReceiver.d.ts new file mode 100644 index 0000000..78be316 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/realtime/polling/PacketReceiver.d.ts @@ -0,0 +1,38 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This class ensures the packets from the server arrive in order + * This class takes data from the server and ensures it gets passed into the callbacks in order. + */ +export declare class PacketReceiver { + private onMessage_; + pendingResponses: unknown[]; + currentResponseNum: number; + closeAfterResponse: number; + onClose: (() => void) | null; + /** + * @param onMessage_ + */ + constructor(onMessage_: (a: {}) => void); + closeAfter(responseNum: number, callback: () => void): void; + /** + * Each message from the server comes with a response number, and an array of data. The responseNumber + * allows us to ensure that we process them in the right order, since we can't be guaranteed that all + * browsers will respond in the same order as the requests we sent + */ + handleResponse(requestNum: number, data: unknown[]): void; +} diff --git a/node_modules/@firebase/database/dist/node-esm/src/register.d.ts b/node_modules/@firebase/database/dist/node-esm/src/register.d.ts new file mode 100644 index 0000000..4461564 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/src/register.d.ts @@ -0,0 +1 @@ +export declare function registerDatabase(variant?: string): void; diff --git a/node_modules/@firebase/database/dist/node-esm/test/helpers/EventAccumulator.d.ts b/node_modules/@firebase/database/dist/node-esm/test/helpers/EventAccumulator.d.ts new file mode 100644 index 0000000..c80b734 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/test/helpers/EventAccumulator.d.ts @@ -0,0 +1,35 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const EventAccumulatorFactory: { + waitsForCount: (maxCount: any) => EventAccumulator; + waitsForExactCount: (maxCount: any) => EventAccumulator; +}; +export declare class EventAccumulator { + condition: Function; + eventData: any[]; + promise: any; + resolve: any; + reject: any; + private onResetFxn; + private onEventFxn; + constructor(condition: Function); + addEvent(eventData?: any): void; + reset(condition?: Function): void; + onEvent(cb: Function): void; + onReset(cb: Function): void; + _testCondition(): any; +} diff --git a/node_modules/@firebase/database/dist/node-esm/test/helpers/syncpoint-util.d.ts b/node_modules/@firebase/database/dist/node-esm/test/helpers/syncpoint-util.d.ts new file mode 100644 index 0000000..c02a122 --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/test/helpers/syncpoint-util.d.ts @@ -0,0 +1,29 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app'; +import { ListenProvider } from '../../src/core/SyncTree'; +import { Path } from '../../src/core/util/Path'; +export declare class SyncPointTestParser { + app: FirebaseApp; + listens_: any; + listenProvider_: ListenProvider; + private syncTree_; + constructor(); + getTestPath(optBasePath: string | string[], path?: string): Path; + private testRunner; + defineTest(spec: any): void; +} diff --git a/node_modules/@firebase/database/dist/node-esm/test/helpers/util.d.ts b/node_modules/@firebase/database/dist/node-esm/test/helpers/util.d.ts new file mode 100644 index 0000000..1ddcdcd --- /dev/null +++ b/node_modules/@firebase/database/dist/node-esm/test/helpers/util.d.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Database, DatabaseReference } from '../../src'; +import { Path } from '../../src/core/util/Path'; +import { EventAccumulator } from './EventAccumulator'; +export declare const TEST_PROJECT: any; +export declare const EMULATOR_PORT: string; +export declare const USE_EMULATOR: boolean; +export declare function getFreshRepo(path: Path): DatabaseReference; +export declare const DATABASE_ADDRESS: any; +export declare const DATABASE_URL: any; +export declare function testRepoInfo(url: any): import("../../src/core/RepoInfo").RepoInfo; +export declare function repoInfoForConnectionTest(): import("../../src/core/RepoInfo").RepoInfo; +export declare function shuffle(arr: any, randFn?: () => number): void; +export declare function waitFor(waitTimeInMS: number): Promise; +export declare function getUniqueRef(db: Database): DatabaseReference; +export declare function getRWRefs(db: Database): { + readerRef: DatabaseReference; + writerRef: DatabaseReference; +}; +export declare function writeAndValidate(writerRef: DatabaseReference, readerRef: DatabaseReference, toWrite: unknown, ec: EventAccumulator): Promise; +export declare function waitUntil(cb: () => boolean, maxRetries?: number): Promise; diff --git a/node_modules/@firebase/database/dist/private.d.ts b/node_modules/@firebase/database/dist/private.d.ts new file mode 100644 index 0000000..030719c --- /dev/null +++ b/node_modules/@firebase/database/dist/private.d.ts @@ -0,0 +1,2853 @@ +/** + * Firebase Realtime Database + * + * @packageDocumentation + */ + +import { AppCheckInternalComponentName } from '@firebase/app-check-interop-types'; +import { AppCheckTokenListener } from '@firebase/app-check-interop-types'; +import { AppCheckTokenResult } from '@firebase/app-check-interop-types'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { FirebaseApp } from '@firebase/app'; +import { FirebaseApp as FirebaseApp_2 } from '@firebase/app-types'; +import { FirebaseAppCheckInternal } from '@firebase/app-check-interop-types'; +import { FirebaseAuthInternal } from '@firebase/auth-interop-types'; +import { FirebaseAuthInternalName } from '@firebase/auth-interop-types'; +import { FirebaseAuthTokenData } from '@firebase/app-types/private'; +import { Provider } from '@firebase/component'; + +/** + * Abstraction around AppCheck's token fetching capabilities. + */ +declare class AppCheckTokenProvider { + private appCheckProvider?; + private appCheck?; + private serverAppAppCheckToken?; + private appName; + constructor(app: FirebaseApp, appCheckProvider?: Provider); + getToken(forceRefresh?: boolean): Promise; + addTokenChangeListener(listener: AppCheckTokenListener): void; + notifyForInvalidToken(): void; +} + +declare interface AuthTokenProvider { + getToken(forceRefresh: boolean): Promise; + addTokenChangeListener(listener: (token: string | null) => void): void; + removeTokenChangeListener(listener: (token: string | null) => void): void; + notifyForInvalidToken(): void; +} + +/** + * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully + * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g. + * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks + * whether a node potentially had children removed due to a filter. + */ +declare class CacheNode { + private node_; + private fullyInitialized_; + private filtered_; + constructor(node_: Node_2, fullyInitialized_: boolean, filtered_: boolean); + /** + * Returns whether this node was fully initialized with either server data or a complete overwrite by the client + */ + isFullyInitialized(): boolean; + /** + * Returns whether this node is potentially missing children due to a filter applied to the node + */ + isFiltered(): boolean; + isCompleteForPath(path: Path): boolean; + isCompleteForChild(key: string): boolean; + getNode(): Node_2; +} + +declare class CancelEvent implements Event_2 { + eventRegistration: EventRegistration; + error: Error; + path: Path; + constructor(eventRegistration: EventRegistration, error: Error, path: Path); + getPath(): Path; + getEventType(): string; + getEventRunner(): () => void; + toString(): string; +} + +declare interface Change { + /** @param type - The event type */ + type: ChangeType; + /** @param snapshotNode - The data */ + snapshotNode: Node_2; + /** @param childName - The name for this child, if it's a child even */ + childName?: string; + /** @param oldSnap - Used for intermediate processing of child changed events */ + oldSnap?: Node_2; + /** * @param prevName - The name for the previous child, if applicable */ + prevName?: string | null; +} + +declare const enum ChangeType { + /** Event type for a child added */ + CHILD_ADDED = "child_added", + /** Event type for a child removed */ + CHILD_REMOVED = "child_removed", + /** Event type for a child changed */ + CHILD_CHANGED = "child_changed", + /** Event type for a child moved */ + CHILD_MOVED = "child_moved", + /** Event type for a value change */ + VALUE = "value" +} + +/** + * Gets a `Reference` for the location at the specified relative path. + * + * The relative path can either be a simple child name (for example, "ada") or + * a deeper slash-separated path (for example, "ada/name/first"). + * + * @param parent - The parent location. + * @param path - A relative path from this location to the desired child + * location. + * @returns The specified child location. + */ +export declare function child(parent: DatabaseReference, path: string): DatabaseReference; + +declare class ChildChangeAccumulator { + private readonly changeMap; + trackChildChange(change: Change): void; + getChanges(): Change[]; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview Implementation of an immutable SortedMap using a Left-leaning + * Red-Black Tree, adapted from the implementation in Mugs + * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen + * (mads379\@gmail.com). + * + * Original paper on Left-leaning Red-Black Trees: + * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf + * + * Invariant 1: No red node has a red child + * Invariant 2: Every leaf path has the same number of black nodes + * Invariant 3: Only the left child can be red (left leaning) + */ +declare type Comparator = (key1: K, key2: K) => number; + +/** + * Since updates to filtered nodes might require nodes to be pulled in from "outside" the node, this interface + * can help to get complete children that can be pulled in. + * A class implementing this interface takes potentially multiple sources (e.g. user writes, server data from + * other views etc.) to try it's best to get a complete child that might be useful in pulling into the view. + * + * @interface + */ +declare interface CompleteChildSource { + getCompleteChild(childKey: string): Node_2 | null; + getChildAfterChild(index: Index, child: NamedNode, reverse: boolean): NamedNode | null; +} + +/** + * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with + * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write + * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write + * to reflect the write added. + */ +declare class CompoundWrite { + writeTree_: ImmutableTree; + constructor(writeTree_: ImmutableTree); + static empty(): CompoundWrite; +} + +/** + * Modify the provided instance to communicate with the Realtime Database + * emulator. + * + *

Note: This method must be called before performing any other operation. + * + * @param db - The instance to modify. + * @param host - The emulator host (ex: localhost) + * @param port - The emulator port (ex: 8080) + * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules + */ +export declare function connectDatabaseEmulator(db: Database, host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions | string; +}): void; + +/** + * Class representing a Firebase Realtime Database. + */ +export declare class Database implements _FirebaseService { + _repoInternal: Repo; + /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */ + readonly app: FirebaseApp; + /** Represents a `Database` instance. */ + readonly 'type' = "database"; + /** Track if the instance has been used (root or repo accessed) */ + _instanceStarted: boolean; + /** Backing state for root_ */ + private _rootInternal?; + /** @hideconstructor */ + constructor(_repoInternal: Repo, + /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */ + app: FirebaseApp); + get _repo(): Repo; + get _root(): _ReferenceImpl; + _delete(): Promise; + _checkNotDeleted(apiName: string): void; +} + +/** + * A `DatabaseReference` represents a specific location in your Database and can be used + * for reading or writing data to that Database location. + * + * You can reference the root or child location in your Database by calling + * `ref()` or `ref("child/path")`. + * + * Writing is done with the `set()` method and reading can be done with the + * `on*()` method. See {@link + * https://firebase.google.com/docs/database/web/read-and-write} + */ +export declare interface DatabaseReference extends Query { + /** + * The last part of the `DatabaseReference`'s path. + * + * For example, `"ada"` is the key for + * `https://.firebaseio.com/users/ada`. + * + * The key of a root `DatabaseReference` is `null`. + */ + readonly key: string | null; + /** + * The parent location of a `DatabaseReference`. + * + * The parent of a root `DatabaseReference` is `null`. + */ + readonly parent: DatabaseReference | null; + /** The root `DatabaseReference` of the Database. */ + readonly root: DatabaseReference; +} + +/** + * A `DataSnapshot` contains data from a Database location. + * + * Any time you read data from the Database, you receive the data as a + * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach + * with `on()` or `once()`. You can extract the contents of the snapshot as a + * JavaScript object by calling the `val()` method. Alternatively, you can + * traverse into the snapshot by calling `child()` to return child snapshots + * (which you could then call `val()` on). + * + * A `DataSnapshot` is an efficiently generated, immutable copy of the data at + * a Database location. It cannot be modified and will never change (to modify + * data, you always call the `set()` method on a `Reference` directly). + */ +export declare class DataSnapshot { + readonly _node: Node_2; + /** + * The location of this DataSnapshot. + */ + readonly ref: DatabaseReference; + readonly _index: Index; + /** + * @param _node - A SnapshotNode to wrap. + * @param ref - The location this snapshot came from. + * @param _index - The iteration order for this snapshot + * @hideconstructor + */ + constructor(_node: Node_2, + /** + * The location of this DataSnapshot. + */ + ref: DatabaseReference, _index: Index); + /** + * Gets the priority value of the data in this `DataSnapshot`. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data} + * ). + */ + get priority(): string | number | null; + /** + * The key (last part of the path) of the location of this `DataSnapshot`. + * + * The last token in a Database location is considered its key. For example, + * "ada" is the key for the /users/ada/ node. Accessing the key on any + * `DataSnapshot` will return the key for the location that generated it. + * However, accessing the key on the root URL of a Database will return + * `null`. + */ + get key(): string | null; + /** Returns the number of child properties of this `DataSnapshot`. */ + get size(): number; + /** + * Gets another `DataSnapshot` for the location at the specified relative path. + * + * Passing a relative path to the `child()` method of a DataSnapshot returns + * another `DataSnapshot` for the location at the specified relative path. The + * relative path can either be a simple child name (for example, "ada") or a + * deeper, slash-separated path (for example, "ada/name/first"). If the child + * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot` + * whose value is `null`) is returned. + * + * @param path - A relative path to the location of child data. + */ + child(path: string): DataSnapshot; + /** + * Returns true if this `DataSnapshot` contains any data. It is slightly more + * efficient than using `snapshot.val() !== null`. + */ + exists(): boolean; + /** + * Exports the entire contents of the DataSnapshot as a JavaScript object. + * + * The `exportVal()` method is similar to `val()`, except priority information + * is included (if available), making it suitable for backing up your data. + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + exportVal(): any; + /** + * Enumerates the top-level children in the `IteratedDataSnapshot`. + * + * Because of the way JavaScript objects work, the ordering of data in the + * JavaScript object returned by `val()` is not guaranteed to match the + * ordering on the server nor the ordering of `onChildAdded()` events. That is + * where `forEach()` comes in handy. It guarantees the children of a + * `DataSnapshot` will be iterated in their query order. + * + * If no explicit `orderBy*()` method is used, results are returned + * ordered by key (unless priorities are used, in which case, results are + * returned by priority). + * + * @param action - A function that will be called for each child DataSnapshot. + * The callback can return true to cancel further enumeration. + * @returns true if enumeration was canceled due to your callback returning + * true. + */ + forEach(action: (child: IteratedDataSnapshot) => boolean | void): boolean; + /** + * Returns true if the specified child path has (non-null) data. + * + * @param path - A relative path to the location of a potential child. + * @returns `true` if data exists at the specified child path; else + * `false`. + */ + hasChild(path: string): boolean; + /** + * Returns whether or not the `DataSnapshot` has any non-`null` child + * properties. + * + * You can use `hasChildren()` to determine if a `DataSnapshot` has any + * children. If it does, you can enumerate them using `forEach()`. If it + * doesn't, then either this snapshot contains a primitive value (which can be + * retrieved with `val()`) or it is empty (in which case, `val()` will return + * `null`). + * + * @returns true if this snapshot has any children; else false. + */ + hasChildren(): boolean; + /** + * Returns a JSON-serializable representation of this object. + */ + toJSON(): object | null; + /** + * Extracts a JavaScript value from a `DataSnapshot`. + * + * Depending on the data in a `DataSnapshot`, the `val()` method may return a + * scalar type (string, number, or boolean), an array, or an object. It may + * also return null, indicating that the `DataSnapshot` is empty (contains no + * data). + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + val(): any; +} +export { EmulatorMockTokenOptions } + +/** + * Logs debugging information to the console. + * + * @param enabled - Enables logging if `true`, disables logging if `false`. + * @param persistent - Remembers the logging state between page refreshes if + * `true`. + */ +export declare function enableLogging(enabled: boolean, persistent?: boolean): any; + +/** + * Logs debugging information to the console. + * + * @param logger - A custom logger function to control how things get logged. + */ +export declare function enableLogging(logger: (message: string) => unknown): any; + +/** + * Creates a `QueryConstraint` with the specified ending point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name less than or equal + * to the specified key. + * + * You can read more about `endAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to end at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end at, among the children with the previously + * specified priority. This argument is only allowed if ordering by child, + * value, or priority. + */ +export declare function endAt(value: number | string | boolean | null, key?: string): QueryConstraint; + +/** + * Creates a `QueryConstraint` with the specified ending point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is exclusive. If only a value is provided, children + * with a value less than the specified value will be included in the query. + * If a key is specified, then children must have a value less than or equal + * to the specified value and a key name less than the specified key. + * + * @param value - The value to end before. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end before, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +export declare function endBefore(value: number | string | boolean | null, key?: string): QueryConstraint; + +/** + * Creates a `QueryConstraint` that includes children that match the specified + * value. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The optional key argument can be used to further limit the range of the + * query. If it is specified, then children that have exactly the specified + * value must also have exactly the specified key as their key name. This can be + * used to filter result sets with many matches for the same value. + * + * You can read more about `equalTo()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to match for. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +export declare function equalTo(value: number | string | boolean | null, key?: string): QueryConstraint; + +/** + * Encapsulates the data needed to raise an event + * @interface + */ +declare interface Event_2 { + getPath(): Path; + getEventType(): string; + getEventRunner(): () => void; + toString(): string; +} + +/** + * An EventGenerator is used to convert "raw" changes (Change) as computed by the + * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges() + * for details. + * + */ +declare class EventGenerator { + query_: QueryContext; + index_: Index; + constructor(query_: QueryContext); +} + +declare interface EventList { + events: Event_2[]; + path: Path; +} + +/** + * The event queue serves a few purposes: + * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more + * events being queued. + * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events, + * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call + * left off, ensuring that the events are still raised synchronously and in order. + * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued + * events are raised synchronously. + * + * NOTE: This can all go away if/when we move to async events. + * + */ +declare class EventQueue { + eventLists_: EventList[]; + /** + * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes. + */ + recursionDepth_: number; +} + +/** + * An EventRegistration is basically an event type ('value', 'child_added', etc.) and a callback + * to be notified of that type of event. + * + * That said, it can also contain a cancel callback to be notified if the event is canceled. And + * currently, this code is organized around the idea that you would register multiple child_ callbacks + * together, as a single EventRegistration. Though currently we don't do that. + */ +declare interface EventRegistration { + /** + * True if this container has a callback to trigger for this event type + */ + respondsTo(eventType: string): boolean; + createEvent(change: Change, query: QueryContext): Event_2; + /** + * Given event data, return a function to trigger the user's callback + */ + getEventRunner(eventData: Event_2): () => void; + createCancelEvent(error: Error, path: Path): CancelEvent | null; + matches(other: EventRegistration): boolean; + /** + * False basically means this is a "dummy" callback container being used as a sentinel + * to remove all callback containers of a particular type. (e.g. if the user does + * ref.off('value') without specifying a specific callback). + * + * (TODO: Rework this, since it's hacky) + * + */ + hasAnyCallback(): boolean; +} + +/** + * One of the following strings: "value", "child_added", "child_changed", + * "child_removed", or "child_moved." + */ +export declare type EventType = 'value' | 'child_added' | 'child_changed' | 'child_moved' | 'child_removed'; + +/* Excluded from this release type: _FirebaseService */ + +/** + * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL. + */ +export declare function forceLongPolling(): void; + +/** + * Force the use of websockets instead of longPolling. + */ +export declare function forceWebSockets(): void; + +/** + * Gets the most up-to-date result for this query. + * + * @param query - The query to run. + * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is + * available, or rejects if the client is unable to return a value (e.g., if the + * server is unreachable and there is nothing cached). + */ +export declare function get(query: Query): Promise; + +/** + * Returns the instance of the Realtime Database SDK that is associated with the provided + * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if + * no instance exists or if the existing instance uses a custom database URL. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime + * Database instance is associated with. + * @param url - The URL of the Realtime Database instance to connect to. If not + * provided, the SDK connects to the default instance of the Firebase App. + * @returns The `Database` instance of the provided app. + */ +export declare function getDatabase(app?: FirebaseApp, url?: string): Database; + +/** + * Disconnects from the server (all Database operations will be completed + * offline). + * + * The client automatically maintains a persistent connection to the Database + * server, which will remain active indefinitely and reconnect when + * disconnected. However, the `goOffline()` and `goOnline()` methods may be used + * to control the client connection in cases where a persistent connection is + * undesirable. + * + * While offline, the client will no longer receive data updates from the + * Database. However, all Database operations performed locally will continue to + * immediately fire events, allowing your application to continue behaving + * normally. Additionally, each operation performed locally will automatically + * be queued and retried upon reconnection to the Database server. + * + * To reconnect to the Database and begin receiving remote events, see + * `goOnline()`. + * + * @param db - The instance to disconnect. + */ +export declare function goOffline(db: Database): void; + +/** + * Reconnects to the server and synchronizes the offline Database state + * with the server state. + * + * This method should be used after disabling the active connection with + * `goOffline()`. Once reconnected, the client will transmit the proper data + * and fire the appropriate events so that your client "catches up" + * automatically. + * + * @param db - The instance to reconnect. + */ +export declare function goOnline(db: Database): void; + +/** + * A tree with immutable elements. + */ +declare class ImmutableTree { + readonly value: T | null; + readonly children: SortedMap>; + static fromObject(obj: { + [k: string]: T; + }): ImmutableTree; + constructor(value: T | null, children?: SortedMap>); + /** + * True if the value is empty and there are no children + */ + isEmpty(): boolean; + /** + * Given a path and predicate, return the first node and the path to that node + * where the predicate returns true. + * + * TODO Do a perf test -- If we're creating a bunch of `{path: value:}` + * objects on the way back out, it may be better to pass down a pathSoFar obj. + * + * @param relativePath - The remainder of the path + * @param predicate - The predicate to satisfy to return a node + */ + findRootMostMatchingPathAndValue(relativePath: Path, predicate: (a: T) => boolean): { + path: Path; + value: T; + } | null; + /** + * Find, if it exists, the shortest subpath of the given path that points a defined + * value in the tree + */ + findRootMostValueAndPath(relativePath: Path): { + path: Path; + value: T; + } | null; + /** + * @returns The subtree at the given path + */ + subtree(relativePath: Path): ImmutableTree; + /** + * Sets a value at the specified path. + * + * @param relativePath - Path to set value at. + * @param toSet - Value to set. + * @returns Resulting tree. + */ + set(relativePath: Path, toSet: T | null): ImmutableTree; + /** + * Removes the value at the specified path. + * + * @param relativePath - Path to value to remove. + * @returns Resulting tree. + */ + remove(relativePath: Path): ImmutableTree; + /** + * Gets a value from the tree. + * + * @param relativePath - Path to get value for. + * @returns Value at path, or null. + */ + get(relativePath: Path): T | null; + /** + * Replace the subtree at the specified path with the given new tree. + * + * @param relativePath - Path to replace subtree for. + * @param newTree - New tree. + * @returns Resulting tree. + */ + setTree(relativePath: Path, newTree: ImmutableTree): ImmutableTree; + /** + * Performs a depth first fold on this tree. Transforms a tree into a single + * value, given a function that operates on the path to a node, an optional + * current value, and a map of child names to folded subtrees + */ + fold(fn: (path: Path, value: T, children: { + [k: string]: V; + }) => V): V; + /** + * Recursive helper for public-facing fold() method + */ + private fold_; + /** + * Find the first matching value on the given path. Return the result of applying f to it. + */ + findOnPath(path: Path, f: (path: Path, value: T) => V | null): V | null; + private findOnPath_; + foreachOnPath(path: Path, f: (path: Path, value: T) => void): ImmutableTree; + private foreachOnPath_; + /** + * Calls the given function for each node in the tree that has a value. + * + * @param f - A function to be called with the path from the root of the tree to + * a node, and the value at that node. Called in depth-first order. + */ + foreach(f: (path: Path, value: T) => void): void; + private foreach_; + foreachChild(f: (name: string, value: T) => void): void; +} + +/** + * Returns a placeholder value that can be used to atomically increment the + * current database value by the provided delta. + * + * @param delta - the amount to modify the current value atomically. + * @returns A placeholder value for modifying data atomically server-side. + */ +export declare function increment(delta: number): object; + +declare abstract class Index { + abstract compare(a: NamedNode, b: NamedNode): number; + abstract isDefinedOn(node: Node_2): boolean; + /** + * @returns A standalone comparison function for + * this index + */ + getCompare(): Comparator; + /** + * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different, + * it's possible that the changes are isolated to parts of the snapshot that are not indexed. + * + * + * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode + */ + indexedValueChanged(oldNode: Node_2, newNode: Node_2): boolean; + /** + * @returns a node wrapper that will sort equal to or less than + * any other node wrapper, using this index + */ + minPost(): NamedNode; + /** + * @returns a node wrapper that will sort greater than or equal to + * any other node wrapper, using this index + */ + abstract maxPost(): NamedNode; + abstract makePost(indexValue: unknown, name: string): NamedNode; + /** + * @returns String representation for inclusion in a query spec + */ + abstract toString(): string; +} + +/* Excluded from this release type: _initStandalone */ + +/** + * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined. + */ +export declare interface IteratedDataSnapshot extends DataSnapshot { + key: string; +} + +/** + * Creates a new `QueryConstraint` that if limited to the first specific number + * of children. + * + * The `limitToFirst()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the first 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToFirst()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +export declare function limitToFirst(limit: number): QueryConstraint; + +/** + * Creates a new `QueryConstraint` that is limited to return only the last + * specified number of children. + * + * The `limitToLast()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the last 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToLast()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +export declare function limitToLast(limit: number): QueryConstraint; + +/** An options objects that can be used to customize a listener. */ +export declare interface ListenOptions { + /** Whether to remove the listener after its first invocation. */ + readonly onlyOnce?: boolean; +} + +declare interface ListenProvider { + startListening(query: QueryContext, tag: number | null, hashFn: () => string, onComplete: (a: string, b?: unknown) => Event_2[]): Event_2[]; + stopListening(a: QueryContext, b: number | null): void; +} + +/** + * Represents an empty node (a leaf node in the Red-Black Tree). + */ +declare class LLRBEmptyNode { + key: K; + value: V; + left: LLRBNode | LLRBEmptyNode; + right: LLRBNode | LLRBEmptyNode; + color: boolean; + /** + * Returns a copy of the current node. + * + * @returns The node copy. + */ + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBEmptyNode; + /** + * Returns a copy of the tree, with the specified key/value added. + * + * @param key - Key to be added. + * @param value - Value to be added. + * @param comparator - Comparator. + * @returns New tree, with item added. + */ + insert(key: K, value: V, comparator: Comparator): LLRBNode; + /** + * Returns a copy of the tree, with the specified key removed. + * + * @param key - The key to remove. + * @param comparator - Comparator. + * @returns New tree, with item removed. + */ + remove(key: K, comparator: Comparator): LLRBEmptyNode; + /** + * @returns The total number of nodes in the tree. + */ + count(): number; + /** + * @returns True if the tree is empty. + */ + isEmpty(): boolean; + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + inorderTraversal(action: (k: K, v: V) => unknown): boolean; + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action: (k: K, v: V) => void): boolean; + minKey(): null; + maxKey(): null; + check_(): number; + /** + * @returns Whether this node is red. + */ + isRed_(): boolean; +} + +/** + * Represents a node in a Left-leaning Red-Black tree. + */ +declare class LLRBNode { + key: K; + value: V; + color: boolean; + left: LLRBNode | LLRBEmptyNode; + right: LLRBNode | LLRBEmptyNode; + /** + * @param key - Key associated with this node. + * @param value - Value associated with this node. + * @param color - Whether this node is red. + * @param left - Left child. + * @param right - Right child. + */ + constructor(key: K, value: V, color: boolean | null, left?: LLRBNode | LLRBEmptyNode | null, right?: LLRBNode | LLRBEmptyNode | null); + static RED: boolean; + static BLACK: boolean; + /** + * Returns a copy of the current node, optionally replacing pieces of it. + * + * @param key - New key for the node, or null. + * @param value - New value for the node, or null. + * @param color - New color for the node, or null. + * @param left - New left child for the node, or null. + * @param right - New right child for the node, or null. + * @returns The node copy. + */ + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBNode; + /** + * @returns The total number of nodes in the tree. + */ + count(): number; + /** + * @returns True if the tree is empty. + */ + isEmpty(): boolean; + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action: (k: K, v: V) => unknown): boolean; + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action: (k: K, v: V) => void): boolean; + /** + * @returns The minimum node in the tree. + */ + private min_; + /** + * @returns The maximum key in the tree. + */ + minKey(): K; + /** + * @returns The maximum key in the tree. + */ + maxKey(): K; + /** + * @param key - Key to insert. + * @param value - Value to insert. + * @param comparator - Comparator. + * @returns New tree, with the key/value added. + */ + insert(key: K, value: V, comparator: Comparator): LLRBNode; + /** + * @returns New tree, with the minimum key removed. + */ + private removeMin_; + /** + * @param key - The key of the item to remove. + * @param comparator - Comparator. + * @returns New tree, with the specified item removed. + */ + remove(key: K, comparator: Comparator): LLRBNode | LLRBEmptyNode; + /** + * @returns Whether this is a RED node. + */ + isRed_(): boolean; + /** + * @returns New tree after performing any needed rotations. + */ + private fixUp_; + /** + * @returns New tree, after moveRedLeft. + */ + private moveRedLeft_; + /** + * @returns New tree, after moveRedRight. + */ + private moveRedRight_; + /** + * @returns New tree, after rotateLeft. + */ + private rotateLeft_; + /** + * @returns New tree, after rotateRight. + */ + private rotateRight_; + /** + * @returns Newt ree, after colorFlip. + */ + private colorFlip_; + /** + * For testing. + * + * @returns True if all is well. + */ + private checkMaxDepth_; + check_(): number; +} + +declare class NamedNode { + name: string; + node: Node_2; + constructor(name: string, node: Node_2); + static Wrap(name: string, node: Node_2): NamedNode; +} + +/** + * Node is an interface defining the common functionality for nodes in + * a DataSnapshot. + * + * @interface + */ +declare interface Node_2 { + /** + * Whether this node is a leaf node. + * @returns Whether this is a leaf node. + */ + isLeafNode(): boolean; + /** + * Gets the priority of the node. + * @returns The priority of the node. + */ + getPriority(): Node_2; + /** + * Returns a duplicate node with the new priority. + * @param newPriorityNode - New priority to set for the node. + * @returns Node with new priority. + */ + updatePriority(newPriorityNode: Node_2): Node_2; + /** + * Returns the specified immediate child, or null if it doesn't exist. + * @param childName - The name of the child to retrieve. + * @returns The retrieved child, or an empty node. + */ + getImmediateChild(childName: string): Node_2; + /** + * Returns a child by path, or null if it doesn't exist. + * @param path - The path of the child to retrieve. + * @returns The retrieved child or an empty node. + */ + getChild(path: Path): Node_2; + /** + * Returns the name of the child immediately prior to the specified childNode, or null. + * @param childName - The name of the child to find the predecessor of. + * @param childNode - The node to find the predecessor of. + * @param index - The index to use to determine the predecessor + * @returns The name of the predecessor child, or null if childNode is the first child. + */ + getPredecessorChildName(childName: string, childNode: Node_2, index: Index): string | null; + /** + * Returns a duplicate node, with the specified immediate child updated. + * Any value in the node will be removed. + * @param childName - The name of the child to update. + * @param newChildNode - The new child node + * @returns The updated node. + */ + updateImmediateChild(childName: string, newChildNode: Node_2): Node_2; + /** + * Returns a duplicate node, with the specified child updated. Any value will + * be removed. + * @param path - The path of the child to update. + * @param newChildNode - The new child node, which may be an empty node + * @returns The updated node. + */ + updateChild(path: Path, newChildNode: Node_2): Node_2; + /** + * True if the immediate child specified exists + */ + hasChild(childName: string): boolean; + /** + * @returns True if this node has no value or children. + */ + isEmpty(): boolean; + /** + * @returns The number of children of this node. + */ + numChildren(): number; + /** + * Calls action for each child. + * @param action - Action to be called for + * each child. It's passed the child name and the child node. + * @returns The first truthy value return by action, or the last falsey one + */ + forEachChild(index: Index, action: (a: string, b: Node_2) => void): unknown; + /** + * @param exportFormat - True for export format (also wire protocol format). + * @returns Value of this node as JSON. + */ + val(exportFormat?: boolean): unknown; + /** + * @returns hash representing the node contents. + */ + hash(): string; + /** + * @param other - Another node + * @returns -1 for less than, 0 for equal, 1 for greater than other + */ + compareTo(other: Node_2): number; + /** + * @returns Whether or not this snapshot equals other + */ + equals(other: Node_2): boolean; + /** + * @returns This node, with the specified index now available + */ + withIndex(indexDefinition: Index): Node_2; + isIndexed(indexDefinition: Index): boolean; +} + +/** + * NodeFilter is used to update nodes and complete children of nodes while applying queries on the fly and keeping + * track of any child changes. This class does not track value changes as value changes depend on more + * than just the node itself. Different kind of queries require different kind of implementations of this interface. + * @interface + */ +declare interface NodeFilter_2 { + /** + * Update a single complete child in the snap. If the child equals the old child in the snap, this is a no-op. + * The method expects an indexed snap. + */ + updateChild(snap: Node_2, key: string, newChild: Node_2, affectedPath: Path, source: CompleteChildSource, optChangeAccumulator: ChildChangeAccumulator | null): Node_2; + /** + * Update a node in full and output any resulting change from this complete update. + */ + updateFullNode(oldSnap: Node_2, newSnap: Node_2, optChangeAccumulator: ChildChangeAccumulator | null): Node_2; + /** + * Update the priority of the root node + */ + updatePriority(oldSnap: Node_2, newPriority: Node_2): Node_2; + /** + * Returns true if children might be filtered due to query criteria + */ + filtersNodes(): boolean; + /** + * Returns the index filter that this filter uses to get a NodeFilter that doesn't filter any children. + */ + getIndexedFilter(): NodeFilter_2; + /** + * Returns the index that this filter uses + */ + getIndex(): Index; +} + +/** + * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener. + * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from + * the respective `on*` callbacks. + * + * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener + * will not automatically remove listeners registered on child nodes, `off()` + * must also be called on any child listeners to remove the callback. + * + * If a callback is not specified, all callbacks for the specified eventType + * will be removed. Similarly, if no eventType is specified, all callbacks + * for the `Reference` will be removed. + * + * Individual listeners can also be removed by invoking their unsubscribe + * callbacks. + * + * @param query - The query that the listener was registered with. + * @param eventType - One of the following strings: "value", "child_added", + * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks + * for the `Reference` will be removed. + * @param callback - The callback function that was passed to `on()` or + * `undefined` to remove all callbacks. + */ +export declare function off(query: Query, eventType?: EventType, callback?: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown): void; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, options: ListenOptions): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; + +/** + * The `onDisconnect` class allows you to write or clear data when your client + * disconnects from the Database server. These updates occur whether your + * client disconnects cleanly or not, so you can rely on them to clean up data + * even if a connection is dropped or a client crashes. + * + * The `onDisconnect` class is most commonly used to manage presence in + * applications where it is useful to detect how many clients are connected and + * when other clients disconnect. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * To avoid problems when a connection is dropped before the requests can be + * transferred to the Database server, these functions should be called before + * writing any data. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time you reconnect. + */ +export declare class OnDisconnect { + private _repo; + private _path; + /** @hideconstructor */ + constructor(_repo: Repo, _path: Path); + /** + * Cancels all previously queued `onDisconnect()` set or update events for this + * location and all children. + * + * If a write has been queued for this location via a `set()` or `update()` at a + * parent location, the write at this location will be canceled, though writes + * to sibling locations will still occur. + * + * @returns Resolves when synchronization to the server is complete. + */ + cancel(): Promise; + /** + * Ensures the data at this location is deleted when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + * + * @returns Resolves when synchronization to the server is complete. + */ + remove(): Promise; + /** + * Ensures the data at this location is set to the specified value when the + * client is disconnected (due to closing the browser, navigating to a new page, + * or network issues). + * + * `set()` is especially useful for implementing "presence" systems, where a + * value should be changed or cleared when a user disconnects so that they + * appear "offline" to other users. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time. + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + set(value: unknown): Promise; + /** + * Ensures the data at this location is set to the specified value and priority + * when the client is disconnected (due to closing the browser, navigating to a + * new page, or network issues). + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + setWithPriority(value: unknown, priority: number | string | null): Promise; + /** + * Writes multiple values at this location when the client is disconnected (due + * to closing the browser, navigating to a new page, or network issues). + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, "name/first") + * from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * @param values - Object containing multiple values. + * @returns Resolves when synchronization to the Database is complete. + */ + update(values: object): Promise; +} + +/** + * Returns an `OnDisconnect` object - see + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information on how to use it. + * + * @param ref - The reference to add OnDisconnect triggers for. + */ +export declare function onDisconnect(ref: DatabaseReference): OnDisconnect; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, options: ListenOptions): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; + +/** + * Creates a new `QueryConstraint` that orders by the specified child key. + * + * Queries can only order by one key at a time. Calling `orderByChild()` + * multiple times on the same query is an error. + * + * Firebase queries allow you to order your data by any child key on the fly. + * However, if you know in advance what your indexes will be, you can define + * them via the .indexOn rule in your Security Rules for better performance. See + * the{@link https://firebase.google.com/docs/database/security/indexing-data} + * rule for more information. + * + * You can read more about `orderByChild()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + * + * @param path - The path to order by. + */ +export declare function orderByChild(path: string): QueryConstraint; + +/** + * Creates a new `QueryConstraint` that orders by the key. + * + * Sorts the results of a query by their (ascending) key values. + * + * You can read more about `orderByKey()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +export declare function orderByKey(): QueryConstraint; + +/** + * Creates a new `QueryConstraint` that orders by priority. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data} + * for alternatives to priority. + */ +export declare function orderByPriority(): QueryConstraint; + +/** + * Creates a new `QueryConstraint` that orders by value. + * + * If the children of a query are all scalar values (string, number, or + * boolean), you can order the results by their (ascending) values. + * + * You can read more about `orderByValue()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +export declare function orderByValue(): QueryConstraint; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a parsed path. It's immutable so that you + * can pass them around to other functions without worrying about them changing + * it. + */ +declare class Path { + pieces_: string[]; + pieceNum_: number; + /** + * @param pathOrString - Path string to parse, or another path, or the raw + * tokens array + */ + constructor(pathOrString: string | string[], pieceNum?: number); + toString(): string; +} + +/** + * Firebase connection. Abstracts wire protocol and handles reconnecting. + * + * NOTE: All JSON objects sent to the realtime connection must have property names enclosed + * in quotes to make sure the closure compiler does not minify them. + */ +declare class PersistentConnection extends ServerActions { + private repoInfo_; + private applicationId_; + private onDataUpdate_; + private onConnectStatus_; + private onServerInfoUpdate_; + private authTokenProvider_; + private appCheckTokenProvider_; + private authOverride_?; + id: number; + private log_; + private interruptReasons_; + private readonly listens; + private outstandingPuts_; + private outstandingGets_; + private outstandingPutCount_; + private outstandingGetCount_; + private onDisconnectRequestQueue_; + private connected_; + private reconnectDelay_; + private maxReconnectDelay_; + private securityDebugCallback_; + lastSessionId: string | null; + private establishConnectionTimer_; + private visible_; + private requestCBHash_; + private requestNumber_; + private realtime_; + private authToken_; + private appCheckToken_; + private forceTokenRefresh_; + private invalidAuthTokenCount_; + private invalidAppCheckTokenCount_; + private firstConnection_; + private lastConnectionAttemptTime_; + private lastConnectionEstablishedTime_; + private static nextPersistentConnectionId_; + /** + * Counter for number of connections created. Mainly used for tagging in the logs + */ + private static nextConnectionId_; + /** + * @param repoInfo_ - Data about the namespace we are connecting to + * @param applicationId_ - The Firebase App ID for this project + * @param onDataUpdate_ - A callback for new data from the server + */ + constructor(repoInfo_: RepoInfo, applicationId_: string, onDataUpdate_: (a: string, b: unknown, c: boolean, d: number | null) => void, onConnectStatus_: (a: boolean) => void, onServerInfoUpdate_: (a: unknown) => void, authTokenProvider_: AuthTokenProvider, appCheckTokenProvider_: AppCheckTokenProvider, authOverride_?: object | null); + protected sendRequest(action: string, body: unknown, onResponse?: (a: unknown) => void): void; + get(query: QueryContext): Promise; + listen(query: QueryContext, currentHashFn: () => string, tag: number | null, onComplete: (a: string, b: unknown) => void): void; + private sendGet_; + private sendListen_; + private static warnOnListenWarnings_; + refreshAuthToken(token: string): void; + private reduceReconnectDelayIfAdminCredential_; + refreshAppCheckToken(token: string | null): void; + /** + * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like + * a auth revoked (the connection is closed). + */ + tryAuth(): void; + /** + * Attempts to authenticate with the given token. If the authentication + * attempt fails, it's triggered like the token was revoked (the connection is + * closed). + */ + tryAppCheck(): void; + /** + * @inheritDoc + */ + unlisten(query: QueryContext, tag: number | null): void; + private sendUnlisten_; + onDisconnectPut(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void): void; + onDisconnectMerge(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void): void; + onDisconnectCancel(pathString: string, onComplete?: (a: string, b: string) => void): void; + private sendOnDisconnect_; + put(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void, hash?: string): void; + merge(pathString: string, data: unknown, onComplete: (a: string, b: string | null) => void, hash?: string): void; + putInternal(action: string, pathString: string, data: unknown, onComplete: (a: string, b: string | null) => void, hash?: string): void; + private sendPut_; + reportStats(stats: { + [k: string]: unknown; + }): void; + private onDataMessage_; + private onDataPush_; + private onReady_; + private scheduleConnect_; + private initConnection_; + private onVisible_; + private onOnline_; + private onRealtimeDisconnect_; + private establishConnection_; + interrupt(reason: string): void; + resume(reason: string): void; + private handleTimestamp_; + private cancelSentTransactions_; + private onListenRevoked_; + private removeListen_; + private onAuthRevoked_; + private onAppCheckRevoked_; + private onSecurityDebugPacket_; + private restoreState_; + /** + * Sends client stats for first connection + */ + private sendConnectStats_; + private shouldReconnect_; +} + +declare class PriorityIndex extends Index { + compare(a: NamedNode, b: NamedNode): number; + isDefinedOn(node: Node_2): boolean; + indexedValueChanged(oldNode: Node_2, newNode: Node_2): boolean; + minPost(): NamedNode; + maxPost(): NamedNode; + makePost(indexValue: unknown, name: string): NamedNode; + /** + * @returns String representation for inclusion in a query spec + */ + toString(): string; +} + +/** + * Generates a new child location using a unique key and returns its + * `Reference`. + * + * This is the most common pattern for adding data to a collection of items. + * + * If you provide a value to `push()`, the value is written to the + * generated location. If you don't pass a value, nothing is written to the + * database and the child remains empty (but you can use the `Reference` + * elsewhere). + * + * The unique keys generated by `push()` are ordered by the current time, so the + * resulting list of items is chronologically sorted. The keys are also + * designed to be unguessable (they contain 72 random bits of entropy). + * + * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}. + * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}. + * + * @param parent - The parent location. + * @param value - Optional value to be written at the generated location. + * @returns Combined `Promise` and `Reference`; resolves when write is complete, + * but can be used immediately as the `Reference` to the child location. + */ +export declare function push(parent: DatabaseReference, value?: unknown): ThenableReference; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` sorts and filters the data at a Database location so only a subset + * of the child data is included. This can be used to order a collection of + * data by some attribute (for example, height of dinosaurs) as well as to + * restrict a large list of items (for example, chat messages) down to a number + * suitable for synchronizing to the client. Queries are created by chaining + * together one or more of the filter methods defined here. + * + * Just as with a `DatabaseReference`, you can receive data from a `Query` by using the + * `on*()` methods. You will only receive events and `DataSnapshot`s for the + * subset of the data that matches your query. + * + * See {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data} + * for more information. + */ +export declare interface Query extends QueryContext { + /** The `DatabaseReference` for the `Query`'s location. */ + readonly ref: DatabaseReference; + /** + * Returns whether or not the current and provided queries represent the same + * location, have the same query parameters, and are from the same instance of + * `FirebaseApp`. + * + * Two `DatabaseReference` objects are equivalent if they represent the same location + * and are from the same instance of `FirebaseApp`. + * + * Two `Query` objects are equivalent if they represent the same location, + * have the same query parameters, and are from the same instance of + * `FirebaseApp`. Equivalent queries share the same sort order, limits, and + * starting and ending points. + * + * @param other - The query to compare against. + * @returns Whether or not the current and provided queries are equivalent. + */ + isEqual(other: Query | null): boolean; + /** + * Returns a JSON-serializable representation of this object. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON(): string; + /** + * Gets the absolute URL for this location. + * + * The `toString()` method returns a URL that is ready to be put into a + * browser, curl command, or a `refFromURL()` call. Since all of those expect + * the URL to be url-encoded, `toString()` returns an encoded URL. + * + * Append '.json' to the returned URL when typed into a browser to download + * JSON-formatted data. If the location is secured (that is, not publicly + * readable), you will get a permission-denied error. + * + * @returns The absolute URL for this location. + */ + toString(): string; +} + +/** + * Creates a new immutable instance of `Query` that is extended to also include + * additional query constraints. + * + * @param query - The Query instance to use as a base for the new constraints. + * @param queryConstraints - The list of `QueryConstraint`s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query; + +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Database query. `QueryConstraint`s are created by invoking {@link endAt}, + * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link + * limitToFirst}, {@link limitToLast}, {@link orderByChild}, + * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} , + * {@link orderByValue} or {@link equalTo} and + * can then be passed to {@link query} to create a new query instance that + * also contains this `QueryConstraint`. + */ +export declare abstract class QueryConstraint { + /** The type of this query constraints */ + abstract readonly type: QueryConstraintType; + /** + * Takes the provided `Query` and returns a copy of the `Query` with this + * `QueryConstraint` applied. + */ + abstract _apply(query: _QueryImpl): _QueryImpl; +} + +/** Describes the different query constraints available in this SDK. */ +export declare type QueryConstraintType = 'endAt' | 'endBefore' | 'startAt' | 'startAfter' | 'limitToFirst' | 'limitToLast' | 'orderByChild' | 'orderByKey' | 'orderByPriority' | 'orderByValue' | 'equalTo'; + +declare interface QueryContext { + readonly _queryIdentifier: string; + readonly _queryObject: object; + readonly _repo: Repo; + readonly _path: Path; + readonly _queryParams: _QueryParams; +} + +/* Excluded from this release type: _QueryImpl */ + +/* Excluded from this release type: _QueryParams */ + +/** + * + * Returns a `Reference` representing the location in the Database + * corresponding to the provided path. If no path is provided, the `Reference` + * will point to the root of the Database. + * + * @param db - The database instance to obtain a reference for. + * @param path - Optional path representing the location the returned + * `Reference` will point. If not provided, the returned `Reference` will + * point to the root of the Database. + * @returns If a path is provided, a `Reference` + * pointing to the provided path. Otherwise, a `Reference` pointing to the + * root of the Database. + */ +export declare function ref(db: Database, path?: string): DatabaseReference; + +/* Excluded from this release type: _ReferenceImpl */ + +/** + * Returns a `Reference` representing the location in the Database + * corresponding to the provided Firebase URL. + * + * An exception is thrown if the URL is not a valid Firebase Database URL or it + * has a different domain than the current `Database` instance. + * + * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored + * and are not applied to the returned `Reference`. + * + * @param db - The database instance to obtain a reference for. + * @param url - The Firebase URL at which the returned `Reference` will + * point. + * @returns A `Reference` pointing to the provided + * Firebase URL. + */ +export declare function refFromURL(db: Database, url: string): DatabaseReference; + +/** + * Removes the data at this Database location. + * + * Any data at child locations will also be deleted. + * + * The effect of the remove will be visible immediately and the corresponding + * event 'value' will be triggered. Synchronization of the remove to the + * Firebase servers will also be started, and the returned Promise will resolve + * when complete. If provided, the onComplete callback will be called + * asynchronously after synchronization has finished. + * + * @param ref - The location to remove. + * @returns Resolves when remove on server is complete. + */ +export declare function remove(ref: DatabaseReference): Promise; + +/** + * A connection to a single data repository. + */ +declare class Repo { + repoInfo_: RepoInfo; + forceRestClient_: boolean; + authTokenProvider_: AuthTokenProvider; + appCheckProvider_: AppCheckTokenProvider; + /** Key for uniquely identifying this repo, used in RepoManager */ + readonly key: string; + dataUpdateCount: number; + infoSyncTree_: SyncTree; + serverSyncTree_: SyncTree; + stats_: StatsCollection; + statsListener_: StatsListener | null; + eventQueue_: EventQueue; + nextWriteId_: number; + server_: ServerActions; + statsReporter_: StatsReporter; + infoData_: SnapshotHolder; + interceptServerDataCallback_: ((a: string, b: unknown) => void) | null; + /** A list of data pieces and paths to be set when this client disconnects. */ + onDisconnect_: SparseSnapshotTree; + /** Stores queues of outstanding transactions for Firebase locations. */ + transactionQueueTree_: Tree; + persistentConnection_: PersistentConnection | null; + constructor(repoInfo_: RepoInfo, forceRestClient_: boolean, authTokenProvider_: AuthTokenProvider, appCheckProvider_: AppCheckTokenProvider); + /** + * @returns The URL corresponding to the root of this Firebase. + */ + toString(): string; +} + +/** + * A class that holds metadata about a Repo object + */ +declare class RepoInfo { + readonly secure: boolean; + readonly namespace: string; + readonly webSocketOnly: boolean; + readonly nodeAdmin: boolean; + readonly persistenceKey: string; + readonly includeNamespaceInQueryParams: boolean; + readonly isUsingEmulator: boolean; + readonly emulatorOptions: RepoInfoEmulatorOptions | null; + private _host; + private _domain; + internalHost: string; + /** + * @param host - Hostname portion of the url for the repo + * @param secure - Whether or not this repo is accessed over ssl + * @param namespace - The namespace represented by the repo + * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest). + * @param nodeAdmin - Whether this instance uses Admin SDK credentials + * @param persistenceKey - Override the default session persistence storage key + */ + constructor(host: string, secure: boolean, namespace: string, webSocketOnly: boolean, nodeAdmin?: boolean, persistenceKey?: string, includeNamespaceInQueryParams?: boolean, isUsingEmulator?: boolean, emulatorOptions?: RepoInfoEmulatorOptions | null); + isCacheableHost(): boolean; + isCustomHost(): boolean; + get host(): string; + set host(newHost: string); + toString(): string; + toURLString(): string; +} + +declare interface RepoInfoEmulatorOptions { + mockUserToken?: string | EmulatorMockTokenOptions; +} + +/* Excluded from this release type: _repoManagerDatabaseFromApp */ + +/** + * Atomically modifies the data at this location. + * + * Atomically modify the data at this location. Unlike a normal `set()`, which + * just overwrites the data regardless of its previous value, `runTransaction()` is + * used to modify the existing value to a new value, ensuring there are no + * conflicts with other clients writing to the same location at the same time. + * + * To accomplish this, you pass `runTransaction()` an update function which is + * used to transform the current value into a new value. If another client + * writes to the location before your new value is successfully written, your + * update function will be called again with the new current value, and the + * write will be retried. This will happen repeatedly until your write succeeds + * without conflict or you abort the transaction by not returning a value from + * your update function. + * + * Note: Modifying data with `set()` will cancel any pending transactions at + * that location, so extreme care should be taken if mixing `set()` and + * `runTransaction()` to update the same data. + * + * Note: When using transactions with Security and Firebase Rules in place, be + * aware that a client needs `.read` access in addition to `.write` access in + * order to perform a transaction. This is because the client-side nature of + * transactions requires the client to read the data in order to transactionally + * update it. + * + * @param ref - The location to atomically modify. + * @param transactionUpdate - A developer-supplied function which will be passed + * the current data stored at this location (as a JavaScript object). The + * function should return the new value it would like written (as a JavaScript + * object). If `undefined` is returned (i.e. you return with no arguments) the + * transaction will be aborted and the data at this location will not be + * modified. + * @param options - An options object to configure transactions. + * @returns A `Promise` that can optionally be used instead of the `onComplete` + * callback to handle success and failure. + */ +export declare function runTransaction(ref: DatabaseReference, transactionUpdate: (currentData: any) => unknown, options?: TransactionOptions): Promise; + +/** + * Interface defining the set of actions that can be performed against the Firebase server + * (basically corresponds to our wire protocol). + * + * @interface + */ +declare abstract class ServerActions { + abstract listen(query: QueryContext, currentHashFn: () => string, tag: number | null, onComplete: (a: string, b: unknown) => void): void; + /** + * Remove a listen. + */ + abstract unlisten(query: QueryContext, tag: number | null): void; + /** + * Get the server value satisfying this query. + */ + abstract get(query: QueryContext): Promise; + put(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void, hash?: string): void; + merge(pathString: string, data: unknown, onComplete: (a: string, b: string | null) => void, hash?: string): void; + /** + * Refreshes the auth token for the current connection. + * @param token - The authentication token + */ + refreshAuthToken(token: string): void; + /** + * Refreshes the app check token for the current connection. + * @param token The app check token + */ + refreshAppCheckToken(token: string): void; + onDisconnectPut(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void): void; + onDisconnectMerge(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void): void; + onDisconnectCancel(pathString: string, onComplete?: (a: string, b: string) => void): void; + reportStats(stats: { + [k: string]: unknown; + }): void; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a placeholder value for auto-populating the current timestamp (time + * since the Unix epoch, in milliseconds) as determined by the Firebase + * servers. + */ +export declare function serverTimestamp(): object; + +/** + * Writes data to this Database location. + * + * This will overwrite any data at this location and all child locations. + * + * The effect of the write will be visible immediately, and the corresponding + * events ("value", "child_added", etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * Passing `null` for the new value is equivalent to calling `remove()`; namely, + * all data at this location and all child locations will be deleted. + * + * `set()` will remove any priority stored at this location, so if priority is + * meant to be preserved, you need to use `setWithPriority()` instead. + * + * Note that modifying data with `set()` will cancel any pending transactions + * at that location, so extreme care should be taken if mixing `set()` and + * `transaction()` to modify the same data. + * + * A single `set()` will generate a single "value" event at the location where + * the `set()` was performed. + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @returns Resolves when write to server is complete. + */ +export declare function set(ref: DatabaseReference, value: unknown): Promise; + +/** + * Sets a priority for the data at this Database location. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +export declare function setPriority(ref: DatabaseReference, priority: string | number | null): Promise; + +/* Excluded from this release type: _setSDKVersion */ + +/** + * Writes data the Database location. Like `set()` but also specifies the + * priority for that data. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +export declare function setWithPriority(ref: DatabaseReference, value: unknown, priority: string | number | null): Promise; + +/** + * Mutable object which basically just stores a reference to the "latest" immutable snapshot. + */ +declare class SnapshotHolder { + private rootNode_; + getNode(path: Path): Node_2; + updateSnapshot(path: Path, newSnapshotNode: Node_2): void; +} + +/** + * An immutable sorted map implementation, based on a Left-leaning Red-Black + * tree. + */ +declare class SortedMap { + private comparator_; + private root_; + /** + * Always use the same empty node, to reduce memory. + */ + static EMPTY_NODE: LLRBEmptyNode; + /** + * @param comparator_ - Key comparator. + * @param root_ - Optional root node for the map. + */ + constructor(comparator_: Comparator, root_?: LLRBNode | LLRBEmptyNode); + /** + * Returns a copy of the map, with the specified key/value added or replaced. + * (TODO: We should perhaps rename this method to 'put') + * + * @param key - Key to be added. + * @param value - Value to be added. + * @returns New map, with item added. + */ + insert(key: K, value: V): SortedMap; + /** + * Returns a copy of the map, with the specified key removed. + * + * @param key - The key to remove. + * @returns New map, with item removed. + */ + remove(key: K): SortedMap; + /** + * Returns the value of the node with the given key, or null. + * + * @param key - The key to look up. + * @returns The value of the node with the given key, or null if the + * key doesn't exist. + */ + get(key: K): V | null; + /** + * Returns the key of the item *before* the specified key, or null if key is the first item. + * @param key - The key to find the predecessor of + * @returns The predecessor key. + */ + getPredecessorKey(key: K): K | null; + /** + * @returns True if the map is empty. + */ + isEmpty(): boolean; + /** + * @returns The total number of nodes in the map. + */ + count(): number; + /** + * @returns The minimum key in the map. + */ + minKey(): K | null; + /** + * @returns The maximum key in the map. + */ + maxKey(): K | null; + /** + * Traverses the map in key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action: (k: K, v: V) => unknown): boolean; + /** + * Traverses the map in reverse key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns True if the traversal was aborted. + */ + reverseTraversal(action: (k: K, v: V) => void): boolean; + /** + * Returns an iterator over the SortedMap. + * @returns The iterator. + */ + getIterator(resultGenerator?: (k: K, v: V) => T): SortedMapIterator; + getIteratorFrom(key: K, resultGenerator?: (k: K, v: V) => T): SortedMapIterator; + getReverseIteratorFrom(key: K, resultGenerator?: (k: K, v: V) => T): SortedMapIterator; + getReverseIterator(resultGenerator?: (k: K, v: V) => T): SortedMapIterator; +} + +/** + * An iterator over an LLRBNode. + */ +declare class SortedMapIterator { + private isReverse_; + private resultGenerator_; + private nodeStack_; + /** + * @param node - Node to iterate. + * @param isReverse_ - Whether or not to iterate in reverse + */ + constructor(node: LLRBNode | LLRBEmptyNode, startKey: K | null, comparator: Comparator, isReverse_: boolean, resultGenerator_?: ((k: K, v: V) => T) | null); + getNext(): T; + hasNext(): boolean; + peek(): T; +} + +/** + * Helper class to store a sparse set of snapshots. + */ +declare interface SparseSnapshotTree { + value: Node_2 | null; + readonly children: Map; +} + +/** + * Creates a `QueryConstraint` with the specified starting point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is exclusive. If only a value is provided, children + * with a value greater than the specified value will be included in the query. + * If a key is specified, then children must have a value greater than or equal + * to the specified value and a a key name greater than the specified key. + * + * @param value - The value to start after. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start after. This argument is only allowed if + * ordering by child, value, or priority. + */ +export declare function startAfter(value: number | string | boolean | null, key?: string): QueryConstraint; + +/** + * Creates a `QueryConstraint` with the specified starting point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name greater than or + * equal to the specified key. + * + * You can read more about `startAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to start at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at. This argument is only allowed if + * ordering by child, value, or priority. + */ +export declare function startAt(value?: number | string | boolean | null, key?: string): QueryConstraint; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Tracks a collection of stats. + */ +declare class StatsCollection { + private counters_; + incrementCounter(name: string, amount?: number): void; + get(): { + [k: string]: number; + }; +} + +/** + * Returns the delta from the previous call to get stats. + * + * @param collection_ - The collection to "listen" to. + */ +declare class StatsListener { + private collection_; + private last_; + constructor(collection_: StatsCollection); + get(): { + [k: string]: number; + }; +} + +declare class StatsReporter { + private server_; + private statsListener_; + statsToReport_: { + [k: string]: boolean; + }; + constructor(collection: StatsCollection, server_: ServerActions); + private reportStats_; +} + +/** + * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to + * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes + * and user writes (set, transaction, update). + * + * It's responsible for: + * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed). + * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite, + * applyUserOverwrite, etc.) + */ +declare class SyncPoint { + /** + * The Views being tracked at this location in the tree, stored as a map where the key is a + * queryId and the value is the View for that query. + * + * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case). + */ + readonly views: Map; +} + +/** + * SyncTree is the central class for managing event callback registration, data caching, views + * (query processing), and event generation. There are typically two SyncTree instances for + * each Repo, one for the normal Firebase data, and one for the .info data. + * + * It has a number of responsibilities, including: + * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()). + * - Applying and caching data changes for user set(), transaction(), and update() calls + * (applyUserOverwrite(), applyUserMerge()). + * - Applying and caching data changes for server data changes (applyServerOverwrite(), + * applyServerMerge()). + * - Generating user-facing events for server and user changes (all of the apply* methods + * return the set of events that need to be raised as a result). + * - Maintaining the appropriate set of server listens to ensure we are always subscribed + * to the correct set of paths and queries to satisfy the current set of user event + * callbacks (listens are started/stopped using the provided listenProvider). + * + * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual + * events are returned to the caller rather than raised synchronously. + * + */ +declare class SyncTree { + listenProvider_: ListenProvider; + /** + * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views. + */ + syncPointTree_: ImmutableTree; + /** + * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.). + */ + pendingWriteTree_: WriteTree; + readonly tagToQueryMap: Map; + readonly queryToTagMap: Map; + /** + * @param listenProvider_ - Used by SyncTree to start / stop listening + * to server data. + */ + constructor(listenProvider_: ListenProvider); +} + +/* Excluded from this release type: _TEST_ACCESS_forceRestClient */ + +/* Excluded from this release type: _TEST_ACCESS_hijackHash */ + +/** + * A `Promise` that can also act as a `DatabaseReference` when returned by + * {@link push}. The reference is available immediately and the `Promise` resolves + * as the write to the backend completes. + */ +export declare interface ThenableReference extends DatabaseReference, Pick, 'then' | 'catch'> { + key: string; + parent: DatabaseReference; +} + +declare interface Transaction { + path: Path; + update: (a: unknown) => unknown; + onComplete: (error: Error | null, committed: boolean, node: Node_2 | null) => void; + status: TransactionStatus; + order: number; + applyLocally: boolean; + retryCount: number; + unwatcher: () => void; + abortReason: string | null; + currentWriteId: number; + currentInputSnapshot: Node_2 | null; + currentOutputSnapshotRaw: Node_2 | null; + currentOutputSnapshotResolved: Node_2 | null; +} + +/** An options object to configure transactions. */ +export declare interface TransactionOptions { + /** + * By default, events are raised each time the transaction update function + * runs. So if it is run multiple times, you may see intermediate states. You + * can set this to false to suppress these intermediate states and instead + * wait until the transaction has completed before events are raised. + */ + readonly applyLocally?: boolean; +} + +/** + * A type for the resolve value of {@link runTransaction}. + */ +export declare class TransactionResult { + /** Whether the transaction was successfully committed. */ + readonly committed: boolean; + /** The resulting data snapshot. */ + readonly snapshot: DataSnapshot; + /** @hideconstructor */ + constructor( + /** Whether the transaction was successfully committed. */ + committed: boolean, + /** The resulting data snapshot. */ + snapshot: DataSnapshot); + /** Returns a JSON-serializable representation of this object. */ + toJSON(): object; +} + +declare const enum TransactionStatus { + RUN = 0, + SENT = 1, + COMPLETED = 2, + SENT_NEEDS_ABORT = 3, + NEEDS_ABORT = 4 +} + +/** + * A light-weight tree, traversable by path. Nodes can have both values and children. + * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty + * children. + */ +declare class Tree { + readonly name: string; + readonly parent: Tree | null; + node: TreeNode; + /** + * @param name - Optional name of the node. + * @param parent - Optional parent node. + * @param node - Optional node to wrap. + */ + constructor(name?: string, parent?: Tree | null, node?: TreeNode); +} + +/** + * Node in a Tree. + */ +declare interface TreeNode { + children: Record>; + childCount: number; + value?: T; +} + +/** A callback that can invoked to remove a listener. */ +export declare type Unsubscribe = () => void; + +/** + * Writes multiple values to the Database at once. + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, + * "name/first") from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * The effect of the write will be visible immediately, and the corresponding + * events ('value', 'child_added', etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * A single `update()` will generate a single "value" event at the location + * where the `update()` was performed, regardless of how many children were + * modified. + * + * Note that modifying data with `update()` will cancel any pending + * transactions at that location, so extreme care should be taken if mixing + * `update()` and `transaction()` to modify the same data. + * + * Passing `null` to `update()` will remove the data at this location. + * + * See + * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}. + * + * @param ref - The location to write to. + * @param values - Object containing multiple values. + * @returns Resolves when update on server is complete. + */ +export declare function update(ref: DatabaseReference, values: object): Promise; + +/* Excluded from this release type: _UserCallback */ + +/* Excluded from this release type: _validatePathString */ + +/* Excluded from this release type: _validateWritablePath */ + +/** + * A view represents a specific location and query that has 1 or more event registrations. + * + * It does several things: + * - Maintains the list of event registrations for this location/query. + * - Maintains a cache of the data visible for this location/query. + * - Applies new operations (via applyOperation), updates the cache, and based on the event + * registrations returns the set of events to be raised. + */ +declare class View { + private query_; + processor_: ViewProcessor; + viewCache_: ViewCache; + eventRegistrations_: EventRegistration[]; + eventGenerator_: EventGenerator; + constructor(query_: QueryContext, initialViewCache: ViewCache); + get query(): QueryContext; +} + +/** + * Stores the data we have cached for a view. + * + * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes). + */ +declare interface ViewCache { + readonly eventCache: CacheNode; + readonly serverCache: CacheNode; +} + +declare interface ViewProcessor { + readonly filter: NodeFilter_2; +} + +/** + * Defines a single user-initiated write operation. May be the result of a set(), transaction(), or update() call. In + * the case of a set() or transaction, snap will be non-null. In the case of an update(), children will be non-null. + */ +declare interface WriteRecord { + writeId: number; + path: Path; + snap?: Node_2 | null; + children?: { + [k: string]: Node_2; + } | null; + visible: boolean; +} + +/** + * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them + * with underlying server data (to create "event cache" data). Pending writes are added with addOverwrite() + * and addMerge(), and removed with removeWrite(). + */ +declare interface WriteTree { + /** + * A tree tracking the result of applying all visible writes. This does not include transactions with + * applyLocally=false or writes that are completely shadowed by other writes. + */ + visibleWrites: CompoundWrite; + /** + * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary + * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also + * used by transactions). + */ + allWrites: WriteRecord[]; + lastWriteId: number; +} + +export { } diff --git a/node_modules/@firebase/database/dist/public.d.ts b/node_modules/@firebase/database/dist/public.d.ts new file mode 100644 index 0000000..543dc01 --- /dev/null +++ b/node_modules/@firebase/database/dist/public.d.ts @@ -0,0 +1,1405 @@ +/** + * Firebase Realtime Database + * + * @packageDocumentation + */ +import { FirebaseApp } from '@firebase/app'; +import { EmulatorMockTokenOptions } from '@firebase/util'; + +/** + * Gets a `Reference` for the location at the specified relative path. + * + * The relative path can either be a simple child name (for example, "ada") or + * a deeper slash-separated path (for example, "ada/name/first"). + * + * @param parent - The parent location. + * @param path - A relative path from this location to the desired child + * location. + * @returns The specified child location. + */ +export declare function child(parent: DatabaseReference, path: string): DatabaseReference; +/** + * Modify the provided instance to communicate with the Realtime Database + * emulator. + * + *

Note: This method must be called before performing any other operation. + * + * @param db - The instance to modify. + * @param host - The emulator host (ex: localhost) + * @param port - The emulator port (ex: 8080) + * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules + */ +export declare function connectDatabaseEmulator(db: Database, host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions | string; +}): void; +/** + * Class representing a Firebase Realtime Database. + */ +export declare class Database { + /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */ + readonly app: FirebaseApp; + /** Represents a `Database` instance. */ + readonly 'type' = "database"; + private constructor(); +} +/** + * A `DatabaseReference` represents a specific location in your Database and can be used + * for reading or writing data to that Database location. + * + * You can reference the root or child location in your Database by calling + * `ref()` or `ref("child/path")`. + * + * Writing is done with the `set()` method and reading can be done with the + * `on*()` method. See {@link + * https://firebase.google.com/docs/database/web/read-and-write} + */ +export declare interface DatabaseReference extends Query { + /** + * The last part of the `DatabaseReference`'s path. + * + * For example, `"ada"` is the key for + * `https://.firebaseio.com/users/ada`. + * + * The key of a root `DatabaseReference` is `null`. + */ + readonly key: string | null; + /** + * The parent location of a `DatabaseReference`. + * + * The parent of a root `DatabaseReference` is `null`. + */ + readonly parent: DatabaseReference | null; + /** The root `DatabaseReference` of the Database. */ + readonly root: DatabaseReference; +} +/** + * A `DataSnapshot` contains data from a Database location. + * + * Any time you read data from the Database, you receive the data as a + * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach + * with `on()` or `once()`. You can extract the contents of the snapshot as a + * JavaScript object by calling the `val()` method. Alternatively, you can + * traverse into the snapshot by calling `child()` to return child snapshots + * (which you could then call `val()` on). + * + * A `DataSnapshot` is an efficiently generated, immutable copy of the data at + * a Database location. It cannot be modified and will never change (to modify + * data, you always call the `set()` method on a `Reference` directly). + */ +export declare class DataSnapshot { + /** + * The location of this DataSnapshot. + */ + readonly ref: DatabaseReference; + private constructor(); + /** + * Gets the priority value of the data in this `DataSnapshot`. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data} + * ). + */ + get priority(): string | number | null; + /** + * The key (last part of the path) of the location of this `DataSnapshot`. + * + * The last token in a Database location is considered its key. For example, + * "ada" is the key for the /users/ada/ node. Accessing the key on any + * `DataSnapshot` will return the key for the location that generated it. + * However, accessing the key on the root URL of a Database will return + * `null`. + */ + get key(): string | null; + /** Returns the number of child properties of this `DataSnapshot`. */ + get size(): number; + /** + * Gets another `DataSnapshot` for the location at the specified relative path. + * + * Passing a relative path to the `child()` method of a DataSnapshot returns + * another `DataSnapshot` for the location at the specified relative path. The + * relative path can either be a simple child name (for example, "ada") or a + * deeper, slash-separated path (for example, "ada/name/first"). If the child + * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot` + * whose value is `null`) is returned. + * + * @param path - A relative path to the location of child data. + */ + child(path: string): DataSnapshot; + /** + * Returns true if this `DataSnapshot` contains any data. It is slightly more + * efficient than using `snapshot.val() !== null`. + */ + exists(): boolean; + /** + * Exports the entire contents of the DataSnapshot as a JavaScript object. + * + * The `exportVal()` method is similar to `val()`, except priority information + * is included (if available), making it suitable for backing up your data. + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + exportVal(): any; + /** + * Enumerates the top-level children in the `IteratedDataSnapshot`. + * + * Because of the way JavaScript objects work, the ordering of data in the + * JavaScript object returned by `val()` is not guaranteed to match the + * ordering on the server nor the ordering of `onChildAdded()` events. That is + * where `forEach()` comes in handy. It guarantees the children of a + * `DataSnapshot` will be iterated in their query order. + * + * If no explicit `orderBy*()` method is used, results are returned + * ordered by key (unless priorities are used, in which case, results are + * returned by priority). + * + * @param action - A function that will be called for each child DataSnapshot. + * The callback can return true to cancel further enumeration. + * @returns true if enumeration was canceled due to your callback returning + * true. + */ + forEach(action: (child: IteratedDataSnapshot) => boolean | void): boolean; + /** + * Returns true if the specified child path has (non-null) data. + * + * @param path - A relative path to the location of a potential child. + * @returns `true` if data exists at the specified child path; else + * `false`. + */ + hasChild(path: string): boolean; + /** + * Returns whether or not the `DataSnapshot` has any non-`null` child + * properties. + * + * You can use `hasChildren()` to determine if a `DataSnapshot` has any + * children. If it does, you can enumerate them using `forEach()`. If it + * doesn't, then either this snapshot contains a primitive value (which can be + * retrieved with `val()`) or it is empty (in which case, `val()` will return + * `null`). + * + * @returns true if this snapshot has any children; else false. + */ + hasChildren(): boolean; + /** + * Returns a JSON-serializable representation of this object. + */ + toJSON(): object | null; + /** + * Extracts a JavaScript value from a `DataSnapshot`. + * + * Depending on the data in a `DataSnapshot`, the `val()` method may return a + * scalar type (string, number, or boolean), an array, or an object. It may + * also return null, indicating that the `DataSnapshot` is empty (contains no + * data). + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + val(): any; +} +export { EmulatorMockTokenOptions }; +/** + * Logs debugging information to the console. + * + * @param enabled - Enables logging if `true`, disables logging if `false`. + * @param persistent - Remembers the logging state between page refreshes if + * `true`. + */ +export declare function enableLogging(enabled: boolean, persistent?: boolean): any; +/** + * Logs debugging information to the console. + * + * @param logger - A custom logger function to control how things get logged. + */ +export declare function enableLogging(logger: (message: string) => unknown): any; +/** + * Creates a `QueryConstraint` with the specified ending point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name less than or equal + * to the specified key. + * + * You can read more about `endAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to end at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end at, among the children with the previously + * specified priority. This argument is only allowed if ordering by child, + * value, or priority. + */ +export declare function endAt(value: number | string | boolean | null, key?: string): QueryConstraint; +/** + * Creates a `QueryConstraint` with the specified ending point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is exclusive. If only a value is provided, children + * with a value less than the specified value will be included in the query. + * If a key is specified, then children must have a value less than or equal + * to the specified value and a key name less than the specified key. + * + * @param value - The value to end before. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end before, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +export declare function endBefore(value: number | string | boolean | null, key?: string): QueryConstraint; +/** + * Creates a `QueryConstraint` that includes children that match the specified + * value. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The optional key argument can be used to further limit the range of the + * query. If it is specified, then children that have exactly the specified + * value must also have exactly the specified key as their key name. This can be + * used to filter result sets with many matches for the same value. + * + * You can read more about `equalTo()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to match for. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +export declare function equalTo(value: number | string | boolean | null, key?: string): QueryConstraint; +/** + * One of the following strings: "value", "child_added", "child_changed", + * "child_removed", or "child_moved." + */ +export declare type EventType = 'value' | 'child_added' | 'child_changed' | 'child_moved' | 'child_removed'; +/* Excluded from this release type: _FirebaseService */ +/** + * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL. + */ +export declare function forceLongPolling(): void; +/** + * Force the use of websockets instead of longPolling. + */ +export declare function forceWebSockets(): void; +/** + * Gets the most up-to-date result for this query. + * + * @param query - The query to run. + * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is + * available, or rejects if the client is unable to return a value (e.g., if the + * server is unreachable and there is nothing cached). + */ +export declare function get(query: Query): Promise; +/** + * Returns the instance of the Realtime Database SDK that is associated with the provided + * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if + * no instance exists or if the existing instance uses a custom database URL. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime + * Database instance is associated with. + * @param url - The URL of the Realtime Database instance to connect to. If not + * provided, the SDK connects to the default instance of the Firebase App. + * @returns The `Database` instance of the provided app. + */ +export declare function getDatabase(app?: FirebaseApp, url?: string): Database; +/** + * Disconnects from the server (all Database operations will be completed + * offline). + * + * The client automatically maintains a persistent connection to the Database + * server, which will remain active indefinitely and reconnect when + * disconnected. However, the `goOffline()` and `goOnline()` methods may be used + * to control the client connection in cases where a persistent connection is + * undesirable. + * + * While offline, the client will no longer receive data updates from the + * Database. However, all Database operations performed locally will continue to + * immediately fire events, allowing your application to continue behaving + * normally. Additionally, each operation performed locally will automatically + * be queued and retried upon reconnection to the Database server. + * + * To reconnect to the Database and begin receiving remote events, see + * `goOnline()`. + * + * @param db - The instance to disconnect. + */ +export declare function goOffline(db: Database): void; +/** + * Reconnects to the server and synchronizes the offline Database state + * with the server state. + * + * This method should be used after disabling the active connection with + * `goOffline()`. Once reconnected, the client will transmit the proper data + * and fire the appropriate events so that your client "catches up" + * automatically. + * + * @param db - The instance to reconnect. + */ +export declare function goOnline(db: Database): void; +/** + * Returns a placeholder value that can be used to atomically increment the + * current database value by the provided delta. + * + * @param delta - the amount to modify the current value atomically. + * @returns A placeholder value for modifying data atomically server-side. + */ +export declare function increment(delta: number): object; +/* Excluded from this release type: _initStandalone */ +/** + * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined. + */ +export declare interface IteratedDataSnapshot extends DataSnapshot { + key: string; +} +/** + * Creates a new `QueryConstraint` that if limited to the first specific number + * of children. + * + * The `limitToFirst()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the first 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToFirst()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +export declare function limitToFirst(limit: number): QueryConstraint; +/** + * Creates a new `QueryConstraint` that is limited to return only the last + * specified number of children. + * + * The `limitToLast()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the last 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToLast()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +export declare function limitToLast(limit: number): QueryConstraint; +/** An options objects that can be used to customize a listener. */ +export declare interface ListenOptions { + /** Whether to remove the listener after its first invocation. */ + readonly onlyOnce?: boolean; +} +/** + * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener. + * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from + * the respective `on*` callbacks. + * + * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener + * will not automatically remove listeners registered on child nodes, `off()` + * must also be called on any child listeners to remove the callback. + * + * If a callback is not specified, all callbacks for the specified eventType + * will be removed. Similarly, if no eventType is specified, all callbacks + * for the `Reference` will be removed. + * + * Individual listeners can also be removed by invoking their unsubscribe + * callbacks. + * + * @param query - The query that the listener was registered with. + * @param eventType - One of the following strings: "value", "child_added", + * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks + * for the `Reference` will be removed. + * @param callback - The callback function that was passed to `on()` or + * `undefined` to remove all callbacks. + */ +export declare function off(query: Query, eventType?: EventType, callback?: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown): void; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; +/** + * The `onDisconnect` class allows you to write or clear data when your client + * disconnects from the Database server. These updates occur whether your + * client disconnects cleanly or not, so you can rely on them to clean up data + * even if a connection is dropped or a client crashes. + * + * The `onDisconnect` class is most commonly used to manage presence in + * applications where it is useful to detect how many clients are connected and + * when other clients disconnect. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * To avoid problems when a connection is dropped before the requests can be + * transferred to the Database server, these functions should be called before + * writing any data. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time you reconnect. + */ +export declare class OnDisconnect { + private constructor(); + /** + * Cancels all previously queued `onDisconnect()` set or update events for this + * location and all children. + * + * If a write has been queued for this location via a `set()` or `update()` at a + * parent location, the write at this location will be canceled, though writes + * to sibling locations will still occur. + * + * @returns Resolves when synchronization to the server is complete. + */ + cancel(): Promise; + /** + * Ensures the data at this location is deleted when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + * + * @returns Resolves when synchronization to the server is complete. + */ + remove(): Promise; + /** + * Ensures the data at this location is set to the specified value when the + * client is disconnected (due to closing the browser, navigating to a new page, + * or network issues). + * + * `set()` is especially useful for implementing "presence" systems, where a + * value should be changed or cleared when a user disconnects so that they + * appear "offline" to other users. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time. + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + set(value: unknown): Promise; + /** + * Ensures the data at this location is set to the specified value and priority + * when the client is disconnected (due to closing the browser, navigating to a + * new page, or network issues). + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + setWithPriority(value: unknown, priority: number | string | null): Promise; + /** + * Writes multiple values at this location when the client is disconnected (due + * to closing the browser, navigating to a new page, or network issues). + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, "name/first") + * from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * @param values - Object containing multiple values. + * @returns Resolves when synchronization to the Database is complete. + */ + update(values: object): Promise; +} +/** + * Returns an `OnDisconnect` object - see + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information on how to use it. + * + * @param ref - The reference to add OnDisconnect triggers for. + */ +export declare function onDisconnect(ref: DatabaseReference): OnDisconnect; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; +/** + * Creates a new `QueryConstraint` that orders by the specified child key. + * + * Queries can only order by one key at a time. Calling `orderByChild()` + * multiple times on the same query is an error. + * + * Firebase queries allow you to order your data by any child key on the fly. + * However, if you know in advance what your indexes will be, you can define + * them via the .indexOn rule in your Security Rules for better performance. See + * the{@link https://firebase.google.com/docs/database/security/indexing-data} + * rule for more information. + * + * You can read more about `orderByChild()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + * + * @param path - The path to order by. + */ +export declare function orderByChild(path: string): QueryConstraint; +/** + * Creates a new `QueryConstraint` that orders by the key. + * + * Sorts the results of a query by their (ascending) key values. + * + * You can read more about `orderByKey()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +export declare function orderByKey(): QueryConstraint; +/** + * Creates a new `QueryConstraint` that orders by priority. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data} + * for alternatives to priority. + */ +export declare function orderByPriority(): QueryConstraint; +/** + * Creates a new `QueryConstraint` that orders by value. + * + * If the children of a query are all scalar values (string, number, or + * boolean), you can order the results by their (ascending) values. + * + * You can read more about `orderByValue()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +export declare function orderByValue(): QueryConstraint; +/** + * Generates a new child location using a unique key and returns its + * `Reference`. + * + * This is the most common pattern for adding data to a collection of items. + * + * If you provide a value to `push()`, the value is written to the + * generated location. If you don't pass a value, nothing is written to the + * database and the child remains empty (but you can use the `Reference` + * elsewhere). + * + * The unique keys generated by `push()` are ordered by the current time, so the + * resulting list of items is chronologically sorted. The keys are also + * designed to be unguessable (they contain 72 random bits of entropy). + * + * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}. + * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}. + * + * @param parent - The parent location. + * @param value - Optional value to be written at the generated location. + * @returns Combined `Promise` and `Reference`; resolves when write is complete, + * but can be used immediately as the `Reference` to the child location. + */ +export declare function push(parent: DatabaseReference, value?: unknown): ThenableReference; +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` sorts and filters the data at a Database location so only a subset + * of the child data is included. This can be used to order a collection of + * data by some attribute (for example, height of dinosaurs) as well as to + * restrict a large list of items (for example, chat messages) down to a number + * suitable for synchronizing to the client. Queries are created by chaining + * together one or more of the filter methods defined here. + * + * Just as with a `DatabaseReference`, you can receive data from a `Query` by using the + * `on*()` methods. You will only receive events and `DataSnapshot`s for the + * subset of the data that matches your query. + * + * See {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data} + * for more information. + */ +export declare interface Query { + /** The `DatabaseReference` for the `Query`'s location. */ + readonly ref: DatabaseReference; + /** + * Returns whether or not the current and provided queries represent the same + * location, have the same query parameters, and are from the same instance of + * `FirebaseApp`. + * + * Two `DatabaseReference` objects are equivalent if they represent the same location + * and are from the same instance of `FirebaseApp`. + * + * Two `Query` objects are equivalent if they represent the same location, + * have the same query parameters, and are from the same instance of + * `FirebaseApp`. Equivalent queries share the same sort order, limits, and + * starting and ending points. + * + * @param other - The query to compare against. + * @returns Whether or not the current and provided queries are equivalent. + */ + isEqual(other: Query | null): boolean; + /** + * Returns a JSON-serializable representation of this object. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON(): string; + /** + * Gets the absolute URL for this location. + * + * The `toString()` method returns a URL that is ready to be put into a + * browser, curl command, or a `refFromURL()` call. Since all of those expect + * the URL to be url-encoded, `toString()` returns an encoded URL. + * + * Append '.json' to the returned URL when typed into a browser to download + * JSON-formatted data. If the location is secured (that is, not publicly + * readable), you will get a permission-denied error. + * + * @returns The absolute URL for this location. + */ + toString(): string; +} +/** + * Creates a new immutable instance of `Query` that is extended to also include + * additional query constraints. + * + * @param query - The Query instance to use as a base for the new constraints. + * @param queryConstraints - The list of `QueryConstraint`s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query; +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Database query. `QueryConstraint`s are created by invoking {@link endAt}, + * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link + * limitToFirst}, {@link limitToLast}, {@link orderByChild}, + * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} , + * {@link orderByValue} or {@link equalTo} and + * can then be passed to {@link query} to create a new query instance that + * also contains this `QueryConstraint`. + */ +export declare abstract class QueryConstraint { + /** The type of this query constraints */ + abstract readonly type: QueryConstraintType; +} +/** Describes the different query constraints available in this SDK. */ +export declare type QueryConstraintType = 'endAt' | 'endBefore' | 'startAt' | 'startAfter' | 'limitToFirst' | 'limitToLast' | 'orderByChild' | 'orderByKey' | 'orderByPriority' | 'orderByValue' | 'equalTo'; +/* Excluded from this release type: _QueryImpl */ +/* Excluded from this release type: _QueryParams */ +/** + * + * Returns a `Reference` representing the location in the Database + * corresponding to the provided path. If no path is provided, the `Reference` + * will point to the root of the Database. + * + * @param db - The database instance to obtain a reference for. + * @param path - Optional path representing the location the returned + * `Reference` will point. If not provided, the returned `Reference` will + * point to the root of the Database. + * @returns If a path is provided, a `Reference` + * pointing to the provided path. Otherwise, a `Reference` pointing to the + * root of the Database. + */ +export declare function ref(db: Database, path?: string): DatabaseReference; +/* Excluded from this release type: _ReferenceImpl */ +/** + * Returns a `Reference` representing the location in the Database + * corresponding to the provided Firebase URL. + * + * An exception is thrown if the URL is not a valid Firebase Database URL or it + * has a different domain than the current `Database` instance. + * + * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored + * and are not applied to the returned `Reference`. + * + * @param db - The database instance to obtain a reference for. + * @param url - The Firebase URL at which the returned `Reference` will + * point. + * @returns A `Reference` pointing to the provided + * Firebase URL. + */ +export declare function refFromURL(db: Database, url: string): DatabaseReference; +/** + * Removes the data at this Database location. + * + * Any data at child locations will also be deleted. + * + * The effect of the remove will be visible immediately and the corresponding + * event 'value' will be triggered. Synchronization of the remove to the + * Firebase servers will also be started, and the returned Promise will resolve + * when complete. If provided, the onComplete callback will be called + * asynchronously after synchronization has finished. + * + * @param ref - The location to remove. + * @returns Resolves when remove on server is complete. + */ +export declare function remove(ref: DatabaseReference): Promise; +/* Excluded from this release type: _repoManagerDatabaseFromApp */ +/** + * Atomically modifies the data at this location. + * + * Atomically modify the data at this location. Unlike a normal `set()`, which + * just overwrites the data regardless of its previous value, `runTransaction()` is + * used to modify the existing value to a new value, ensuring there are no + * conflicts with other clients writing to the same location at the same time. + * + * To accomplish this, you pass `runTransaction()` an update function which is + * used to transform the current value into a new value. If another client + * writes to the location before your new value is successfully written, your + * update function will be called again with the new current value, and the + * write will be retried. This will happen repeatedly until your write succeeds + * without conflict or you abort the transaction by not returning a value from + * your update function. + * + * Note: Modifying data with `set()` will cancel any pending transactions at + * that location, so extreme care should be taken if mixing `set()` and + * `runTransaction()` to update the same data. + * + * Note: When using transactions with Security and Firebase Rules in place, be + * aware that a client needs `.read` access in addition to `.write` access in + * order to perform a transaction. This is because the client-side nature of + * transactions requires the client to read the data in order to transactionally + * update it. + * + * @param ref - The location to atomically modify. + * @param transactionUpdate - A developer-supplied function which will be passed + * the current data stored at this location (as a JavaScript object). The + * function should return the new value it would like written (as a JavaScript + * object). If `undefined` is returned (i.e. you return with no arguments) the + * transaction will be aborted and the data at this location will not be + * modified. + * @param options - An options object to configure transactions. + * @returns A `Promise` that can optionally be used instead of the `onComplete` + * callback to handle success and failure. + */ +export declare function runTransaction(ref: DatabaseReference, transactionUpdate: (currentData: any) => unknown, options?: TransactionOptions): Promise; +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a placeholder value for auto-populating the current timestamp (time + * since the Unix epoch, in milliseconds) as determined by the Firebase + * servers. + */ +export declare function serverTimestamp(): object; +/** + * Writes data to this Database location. + * + * This will overwrite any data at this location and all child locations. + * + * The effect of the write will be visible immediately, and the corresponding + * events ("value", "child_added", etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * Passing `null` for the new value is equivalent to calling `remove()`; namely, + * all data at this location and all child locations will be deleted. + * + * `set()` will remove any priority stored at this location, so if priority is + * meant to be preserved, you need to use `setWithPriority()` instead. + * + * Note that modifying data with `set()` will cancel any pending transactions + * at that location, so extreme care should be taken if mixing `set()` and + * `transaction()` to modify the same data. + * + * A single `set()` will generate a single "value" event at the location where + * the `set()` was performed. + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @returns Resolves when write to server is complete. + */ +export declare function set(ref: DatabaseReference, value: unknown): Promise; +/** + * Sets a priority for the data at this Database location. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +export declare function setPriority(ref: DatabaseReference, priority: string | number | null): Promise; +/* Excluded from this release type: _setSDKVersion */ +/** + * Writes data the Database location. Like `set()` but also specifies the + * priority for that data. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +export declare function setWithPriority(ref: DatabaseReference, value: unknown, priority: string | number | null): Promise; +/** + * Creates a `QueryConstraint` with the specified starting point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is exclusive. If only a value is provided, children + * with a value greater than the specified value will be included in the query. + * If a key is specified, then children must have a value greater than or equal + * to the specified value and a a key name greater than the specified key. + * + * @param value - The value to start after. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start after. This argument is only allowed if + * ordering by child, value, or priority. + */ +export declare function startAfter(value: number | string | boolean | null, key?: string): QueryConstraint; +/** + * Creates a `QueryConstraint` with the specified starting point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name greater than or + * equal to the specified key. + * + * You can read more about `startAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to start at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at. This argument is only allowed if + * ordering by child, value, or priority. + */ +export declare function startAt(value?: number | string | boolean | null, key?: string): QueryConstraint; +/* Excluded from this release type: _TEST_ACCESS_forceRestClient */ +/* Excluded from this release type: _TEST_ACCESS_hijackHash */ +/** + * A `Promise` that can also act as a `DatabaseReference` when returned by + * {@link push}. The reference is available immediately and the `Promise` resolves + * as the write to the backend completes. + */ +export declare interface ThenableReference extends DatabaseReference, Pick, 'then' | 'catch'> { + key: string; + parent: DatabaseReference; +} +/** An options object to configure transactions. */ +export declare interface TransactionOptions { + /** + * By default, events are raised each time the transaction update function + * runs. So if it is run multiple times, you may see intermediate states. You + * can set this to false to suppress these intermediate states and instead + * wait until the transaction has completed before events are raised. + */ + readonly applyLocally?: boolean; +} +/** + * A type for the resolve value of {@link runTransaction}. + */ +export declare class TransactionResult { + /** Whether the transaction was successfully committed. */ + readonly committed: boolean; + /** The resulting data snapshot. */ + readonly snapshot: DataSnapshot; + private constructor(); + /** Returns a JSON-serializable representation of this object. */ + toJSON(): object; +} +/** A callback that can invoked to remove a listener. */ +export declare type Unsubscribe = () => void; +/** + * Writes multiple values to the Database at once. + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, + * "name/first") from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * The effect of the write will be visible immediately, and the corresponding + * events ('value', 'child_added', etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * A single `update()` will generate a single "value" event at the location + * where the `update()` was performed, regardless of how many children were + * modified. + * + * Note that modifying data with `update()` will cancel any pending + * transactions at that location, so extreme care should be taken if mixing + * `update()` and `transaction()` to modify the same data. + * + * Passing `null` to `update()` will remove the data at this location. + * + * See + * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}. + * + * @param ref - The location to write to. + * @param values - Object containing multiple values. + * @returns Resolves when update on server is complete. + */ +export declare function update(ref: DatabaseReference, values: object): Promise; +export {}; diff --git a/node_modules/@firebase/database/dist/src/api.d.ts b/node_modules/@firebase/database/dist/src/api.d.ts new file mode 100644 index 0000000..26bc1ee --- /dev/null +++ b/node_modules/@firebase/database/dist/src/api.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './api.standalone'; +export { getDatabase } from './api/Database'; diff --git a/node_modules/@firebase/database/dist/src/api.standalone.d.ts b/node_modules/@firebase/database/dist/src/api.standalone.d.ts new file mode 100644 index 0000000..1c65ab6 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/api.standalone.d.ts @@ -0,0 +1,30 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { Database, EmulatorMockTokenOptions, enableLogging, goOffline, goOnline, forceWebSockets, forceLongPolling, connectDatabaseEmulator } from './api/Database'; +export { Query, DatabaseReference, ListenOptions, Unsubscribe, ThenableReference } from './api/Reference'; +export { OnDisconnect } from './api/OnDisconnect'; +export { DataSnapshot, EventType, IteratedDataSnapshot, QueryConstraint, QueryConstraintType, endAt, endBefore, equalTo, get, limitToFirst, limitToLast, off, onChildAdded, onChildChanged, onChildMoved, onChildRemoved, onDisconnect, onValue, orderByChild, orderByKey, orderByPriority, orderByValue, push, query, ref, refFromURL, remove, set, setPriority, setWithPriority, startAfter, startAt, update, child } from './api/Reference_impl'; +export { increment, serverTimestamp } from './api/ServerValue'; +export { runTransaction, TransactionOptions, TransactionResult } from './api/Transaction'; +export { setSDKVersion as _setSDKVersion } from './core/version'; +export { ReferenceImpl as _ReferenceImpl, QueryImpl as _QueryImpl } from './api/Reference_impl'; +export { repoManagerDatabaseFromApp as _repoManagerDatabaseFromApp } from './api/Database'; +export { validatePathString as _validatePathString, validateWritablePath as _validateWritablePath } from './core/util/validation'; +export { UserCallback as _UserCallback } from './core/view/EventRegistration'; +export { QueryParams as _QueryParams } from './core/view/QueryParams'; +export { hijackHash as _TEST_ACCESS_hijackHash, forceRestClient as _TEST_ACCESS_forceRestClient } from './api/test_access'; +export * from './internal/index'; diff --git a/node_modules/@firebase/database/dist/src/api/Database.d.ts b/node_modules/@firebase/database/dist/src/api/Database.d.ts new file mode 100644 index 0000000..9a79baf --- /dev/null +++ b/node_modules/@firebase/database/dist/src/api/Database.d.ts @@ -0,0 +1,137 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { _FirebaseService, FirebaseApp } from '@firebase/app'; +import { AppCheckInternalComponentName } from '@firebase/app-check-interop-types'; +import { FirebaseAuthInternalName } from '@firebase/auth-interop-types'; +import { Provider } from '@firebase/component'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { Repo } from '../core/Repo'; +import { ReferenceImpl } from './Reference_impl'; +export { EmulatorMockTokenOptions } from '@firebase/util'; +/** + * This function should only ever be called to CREATE a new database instance. + * @internal + */ +export declare function repoManagerDatabaseFromApp(app: FirebaseApp, authProvider: Provider, appCheckProvider?: Provider, url?: string, nodeAdmin?: boolean): Database; +/** + * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos. + */ +export declare function repoManagerForceRestClient(forceRestClient: boolean): void; +/** + * Class representing a Firebase Realtime Database. + */ +export declare class Database implements _FirebaseService { + _repoInternal: Repo; + /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */ + readonly app: FirebaseApp; + /** Represents a `Database` instance. */ + readonly 'type' = "database"; + /** Track if the instance has been used (root or repo accessed) */ + _instanceStarted: boolean; + /** Backing state for root_ */ + private _rootInternal?; + /** @hideconstructor */ + constructor(_repoInternal: Repo, + /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */ + app: FirebaseApp); + get _repo(): Repo; + get _root(): ReferenceImpl; + _delete(): Promise; + _checkNotDeleted(apiName: string): void; +} +/** + * Force the use of websockets instead of longPolling. + */ +export declare function forceWebSockets(): void; +/** + * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL. + */ +export declare function forceLongPolling(): void; +/** + * Returns the instance of the Realtime Database SDK that is associated with the provided + * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if + * no instance exists or if the existing instance uses a custom database URL. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime + * Database instance is associated with. + * @param url - The URL of the Realtime Database instance to connect to. If not + * provided, the SDK connects to the default instance of the Firebase App. + * @returns The `Database` instance of the provided app. + */ +export declare function getDatabase(app?: FirebaseApp, url?: string): Database; +/** + * Modify the provided instance to communicate with the Realtime Database + * emulator. + * + *

Note: This method must be called before performing any other operation. + * + * @param db - The instance to modify. + * @param host - The emulator host (ex: localhost) + * @param port - The emulator port (ex: 8080) + * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules + */ +export declare function connectDatabaseEmulator(db: Database, host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions | string; +}): void; +/** + * Disconnects from the server (all Database operations will be completed + * offline). + * + * The client automatically maintains a persistent connection to the Database + * server, which will remain active indefinitely and reconnect when + * disconnected. However, the `goOffline()` and `goOnline()` methods may be used + * to control the client connection in cases where a persistent connection is + * undesirable. + * + * While offline, the client will no longer receive data updates from the + * Database. However, all Database operations performed locally will continue to + * immediately fire events, allowing your application to continue behaving + * normally. Additionally, each operation performed locally will automatically + * be queued and retried upon reconnection to the Database server. + * + * To reconnect to the Database and begin receiving remote events, see + * `goOnline()`. + * + * @param db - The instance to disconnect. + */ +export declare function goOffline(db: Database): void; +/** + * Reconnects to the server and synchronizes the offline Database state + * with the server state. + * + * This method should be used after disabling the active connection with + * `goOffline()`. Once reconnected, the client will transmit the proper data + * and fire the appropriate events so that your client "catches up" + * automatically. + * + * @param db - The instance to reconnect. + */ +export declare function goOnline(db: Database): void; +/** + * Logs debugging information to the console. + * + * @param enabled - Enables logging if `true`, disables logging if `false`. + * @param persistent - Remembers the logging state between page refreshes if + * `true`. + */ +export declare function enableLogging(enabled: boolean, persistent?: boolean): any; +/** + * Logs debugging information to the console. + * + * @param logger - A custom logger function to control how things get logged. + */ +export declare function enableLogging(logger: (message: string) => unknown): any; diff --git a/node_modules/@firebase/database/dist/src/api/OnDisconnect.d.ts b/node_modules/@firebase/database/dist/src/api/OnDisconnect.d.ts new file mode 100644 index 0000000..bbae779 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/api/OnDisconnect.d.ts @@ -0,0 +1,110 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Repo } from '../core/Repo'; +import { Path } from '../core/util/Path'; +/** + * The `onDisconnect` class allows you to write or clear data when your client + * disconnects from the Database server. These updates occur whether your + * client disconnects cleanly or not, so you can rely on them to clean up data + * even if a connection is dropped or a client crashes. + * + * The `onDisconnect` class is most commonly used to manage presence in + * applications where it is useful to detect how many clients are connected and + * when other clients disconnect. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * To avoid problems when a connection is dropped before the requests can be + * transferred to the Database server, these functions should be called before + * writing any data. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time you reconnect. + */ +export declare class OnDisconnect { + private _repo; + private _path; + /** @hideconstructor */ + constructor(_repo: Repo, _path: Path); + /** + * Cancels all previously queued `onDisconnect()` set or update events for this + * location and all children. + * + * If a write has been queued for this location via a `set()` or `update()` at a + * parent location, the write at this location will be canceled, though writes + * to sibling locations will still occur. + * + * @returns Resolves when synchronization to the server is complete. + */ + cancel(): Promise; + /** + * Ensures the data at this location is deleted when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + * + * @returns Resolves when synchronization to the server is complete. + */ + remove(): Promise; + /** + * Ensures the data at this location is set to the specified value when the + * client is disconnected (due to closing the browser, navigating to a new page, + * or network issues). + * + * `set()` is especially useful for implementing "presence" systems, where a + * value should be changed or cleared when a user disconnects so that they + * appear "offline" to other users. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time. + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + set(value: unknown): Promise; + /** + * Ensures the data at this location is set to the specified value and priority + * when the client is disconnected (due to closing the browser, navigating to a + * new page, or network issues). + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + setWithPriority(value: unknown, priority: number | string | null): Promise; + /** + * Writes multiple values at this location when the client is disconnected (due + * to closing the browser, navigating to a new page, or network issues). + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, "name/first") + * from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * @param values - Object containing multiple values. + * @returns Resolves when synchronization to the Database is complete. + */ + update(values: object): Promise; +} diff --git a/node_modules/@firebase/database/dist/src/api/Reference.d.ts b/node_modules/@firebase/database/dist/src/api/Reference.d.ts new file mode 100644 index 0000000..0d9e054 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/api/Reference.d.ts @@ -0,0 +1,124 @@ +import { Repo } from '../core/Repo'; +import { Path } from '../core/util/Path'; +import { QueryContext } from '../core/view/EventRegistration'; +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` sorts and filters the data at a Database location so only a subset + * of the child data is included. This can be used to order a collection of + * data by some attribute (for example, height of dinosaurs) as well as to + * restrict a large list of items (for example, chat messages) down to a number + * suitable for synchronizing to the client. Queries are created by chaining + * together one or more of the filter methods defined here. + * + * Just as with a `DatabaseReference`, you can receive data from a `Query` by using the + * `on*()` methods. You will only receive events and `DataSnapshot`s for the + * subset of the data that matches your query. + * + * See {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data} + * for more information. + */ +export interface Query extends QueryContext { + /** The `DatabaseReference` for the `Query`'s location. */ + readonly ref: DatabaseReference; + /** + * Returns whether or not the current and provided queries represent the same + * location, have the same query parameters, and are from the same instance of + * `FirebaseApp`. + * + * Two `DatabaseReference` objects are equivalent if they represent the same location + * and are from the same instance of `FirebaseApp`. + * + * Two `Query` objects are equivalent if they represent the same location, + * have the same query parameters, and are from the same instance of + * `FirebaseApp`. Equivalent queries share the same sort order, limits, and + * starting and ending points. + * + * @param other - The query to compare against. + * @returns Whether or not the current and provided queries are equivalent. + */ + isEqual(other: Query | null): boolean; + /** + * Returns a JSON-serializable representation of this object. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON(): string; + /** + * Gets the absolute URL for this location. + * + * The `toString()` method returns a URL that is ready to be put into a + * browser, curl command, or a `refFromURL()` call. Since all of those expect + * the URL to be url-encoded, `toString()` returns an encoded URL. + * + * Append '.json' to the returned URL when typed into a browser to download + * JSON-formatted data. If the location is secured (that is, not publicly + * readable), you will get a permission-denied error. + * + * @returns The absolute URL for this location. + */ + toString(): string; +} +/** + * A `DatabaseReference` represents a specific location in your Database and can be used + * for reading or writing data to that Database location. + * + * You can reference the root or child location in your Database by calling + * `ref()` or `ref("child/path")`. + * + * Writing is done with the `set()` method and reading can be done with the + * `on*()` method. See {@link + * https://firebase.google.com/docs/database/web/read-and-write} + */ +export interface DatabaseReference extends Query { + /** + * The last part of the `DatabaseReference`'s path. + * + * For example, `"ada"` is the key for + * `https://.firebaseio.com/users/ada`. + * + * The key of a root `DatabaseReference` is `null`. + */ + readonly key: string | null; + /** + * The parent location of a `DatabaseReference`. + * + * The parent of a root `DatabaseReference` is `null`. + */ + readonly parent: DatabaseReference | null; + /** The root `DatabaseReference` of the Database. */ + readonly root: DatabaseReference; +} +/** + * A `Promise` that can also act as a `DatabaseReference` when returned by + * {@link push}. The reference is available immediately and the `Promise` resolves + * as the write to the backend completes. + */ +export interface ThenableReference extends DatabaseReference, Pick, 'then' | 'catch'> { + key: string; + parent: DatabaseReference; +} +/** A callback that can invoked to remove a listener. */ +export type Unsubscribe = () => void; +/** An options objects that can be used to customize a listener. */ +export interface ListenOptions { + /** Whether to remove the listener after its first invocation. */ + readonly onlyOnce?: boolean; +} +export interface ReferenceConstructor { + new (repo: Repo, path: Path): DatabaseReference; +} diff --git a/node_modules/@firebase/database/dist/src/api/Reference_impl.d.ts b/node_modules/@firebase/database/dist/src/api/Reference_impl.d.ts new file mode 100644 index 0000000..873e00e --- /dev/null +++ b/node_modules/@firebase/database/dist/src/api/Reference_impl.d.ts @@ -0,0 +1,1100 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Repo } from '../core/Repo'; +import { Index } from '../core/snap/indexes/Index'; +import { Node } from '../core/snap/Node'; +import { Path } from '../core/util/Path'; +import { Change } from '../core/view/Change'; +import { CancelEvent, DataEvent, EventType } from '../core/view/Event'; +import { CallbackContext, EventRegistration, QueryContext } from '../core/view/EventRegistration'; +import { QueryParams } from '../core/view/QueryParams'; +import { Database } from './Database'; +import { OnDisconnect } from './OnDisconnect'; +import { ListenOptions, Query as Query, DatabaseReference, Unsubscribe, ThenableReference } from './Reference'; +/** + * @internal + */ +export declare class QueryImpl implements Query, QueryContext { + readonly _repo: Repo; + readonly _path: Path; + readonly _queryParams: QueryParams; + readonly _orderByCalled: boolean; + /** + * @hideconstructor + */ + constructor(_repo: Repo, _path: Path, _queryParams: QueryParams, _orderByCalled: boolean); + get key(): string | null; + get ref(): DatabaseReference; + get _queryIdentifier(): string; + /** + * An object representation of the query parameters used by this Query. + */ + get _queryObject(): object; + isEqual(other: QueryImpl | null): boolean; + toJSON(): string; + toString(): string; +} +/** + * @internal + */ +export declare class ReferenceImpl extends QueryImpl implements DatabaseReference { + /** @hideconstructor */ + constructor(repo: Repo, path: Path); + get parent(): ReferenceImpl | null; + get root(): ReferenceImpl; +} +/** + * A `DataSnapshot` contains data from a Database location. + * + * Any time you read data from the Database, you receive the data as a + * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach + * with `on()` or `once()`. You can extract the contents of the snapshot as a + * JavaScript object by calling the `val()` method. Alternatively, you can + * traverse into the snapshot by calling `child()` to return child snapshots + * (which you could then call `val()` on). + * + * A `DataSnapshot` is an efficiently generated, immutable copy of the data at + * a Database location. It cannot be modified and will never change (to modify + * data, you always call the `set()` method on a `Reference` directly). + */ +export declare class DataSnapshot { + readonly _node: Node; + /** + * The location of this DataSnapshot. + */ + readonly ref: DatabaseReference; + readonly _index: Index; + /** + * @param _node - A SnapshotNode to wrap. + * @param ref - The location this snapshot came from. + * @param _index - The iteration order for this snapshot + * @hideconstructor + */ + constructor(_node: Node, + /** + * The location of this DataSnapshot. + */ + ref: DatabaseReference, _index: Index); + /** + * Gets the priority value of the data in this `DataSnapshot`. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data} + * ). + */ + get priority(): string | number | null; + /** + * The key (last part of the path) of the location of this `DataSnapshot`. + * + * The last token in a Database location is considered its key. For example, + * "ada" is the key for the /users/ada/ node. Accessing the key on any + * `DataSnapshot` will return the key for the location that generated it. + * However, accessing the key on the root URL of a Database will return + * `null`. + */ + get key(): string | null; + /** Returns the number of child properties of this `DataSnapshot`. */ + get size(): number; + /** + * Gets another `DataSnapshot` for the location at the specified relative path. + * + * Passing a relative path to the `child()` method of a DataSnapshot returns + * another `DataSnapshot` for the location at the specified relative path. The + * relative path can either be a simple child name (for example, "ada") or a + * deeper, slash-separated path (for example, "ada/name/first"). If the child + * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot` + * whose value is `null`) is returned. + * + * @param path - A relative path to the location of child data. + */ + child(path: string): DataSnapshot; + /** + * Returns true if this `DataSnapshot` contains any data. It is slightly more + * efficient than using `snapshot.val() !== null`. + */ + exists(): boolean; + /** + * Exports the entire contents of the DataSnapshot as a JavaScript object. + * + * The `exportVal()` method is similar to `val()`, except priority information + * is included (if available), making it suitable for backing up your data. + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + exportVal(): any; + /** + * Enumerates the top-level children in the `IteratedDataSnapshot`. + * + * Because of the way JavaScript objects work, the ordering of data in the + * JavaScript object returned by `val()` is not guaranteed to match the + * ordering on the server nor the ordering of `onChildAdded()` events. That is + * where `forEach()` comes in handy. It guarantees the children of a + * `DataSnapshot` will be iterated in their query order. + * + * If no explicit `orderBy*()` method is used, results are returned + * ordered by key (unless priorities are used, in which case, results are + * returned by priority). + * + * @param action - A function that will be called for each child DataSnapshot. + * The callback can return true to cancel further enumeration. + * @returns true if enumeration was canceled due to your callback returning + * true. + */ + forEach(action: (child: IteratedDataSnapshot) => boolean | void): boolean; + /** + * Returns true if the specified child path has (non-null) data. + * + * @param path - A relative path to the location of a potential child. + * @returns `true` if data exists at the specified child path; else + * `false`. + */ + hasChild(path: string): boolean; + /** + * Returns whether or not the `DataSnapshot` has any non-`null` child + * properties. + * + * You can use `hasChildren()` to determine if a `DataSnapshot` has any + * children. If it does, you can enumerate them using `forEach()`. If it + * doesn't, then either this snapshot contains a primitive value (which can be + * retrieved with `val()`) or it is empty (in which case, `val()` will return + * `null`). + * + * @returns true if this snapshot has any children; else false. + */ + hasChildren(): boolean; + /** + * Returns a JSON-serializable representation of this object. + */ + toJSON(): object | null; + /** + * Extracts a JavaScript value from a `DataSnapshot`. + * + * Depending on the data in a `DataSnapshot`, the `val()` method may return a + * scalar type (string, number, or boolean), an array, or an object. It may + * also return null, indicating that the `DataSnapshot` is empty (contains no + * data). + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + val(): any; +} +/** + * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined. + */ +export interface IteratedDataSnapshot extends DataSnapshot { + key: string; +} +/** + * + * Returns a `Reference` representing the location in the Database + * corresponding to the provided path. If no path is provided, the `Reference` + * will point to the root of the Database. + * + * @param db - The database instance to obtain a reference for. + * @param path - Optional path representing the location the returned + * `Reference` will point. If not provided, the returned `Reference` will + * point to the root of the Database. + * @returns If a path is provided, a `Reference` + * pointing to the provided path. Otherwise, a `Reference` pointing to the + * root of the Database. + */ +export declare function ref(db: Database, path?: string): DatabaseReference; +/** + * Returns a `Reference` representing the location in the Database + * corresponding to the provided Firebase URL. + * + * An exception is thrown if the URL is not a valid Firebase Database URL or it + * has a different domain than the current `Database` instance. + * + * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored + * and are not applied to the returned `Reference`. + * + * @param db - The database instance to obtain a reference for. + * @param url - The Firebase URL at which the returned `Reference` will + * point. + * @returns A `Reference` pointing to the provided + * Firebase URL. + */ +export declare function refFromURL(db: Database, url: string): DatabaseReference; +/** + * Gets a `Reference` for the location at the specified relative path. + * + * The relative path can either be a simple child name (for example, "ada") or + * a deeper slash-separated path (for example, "ada/name/first"). + * + * @param parent - The parent location. + * @param path - A relative path from this location to the desired child + * location. + * @returns The specified child location. + */ +export declare function child(parent: DatabaseReference, path: string): DatabaseReference; +/** + * Returns an `OnDisconnect` object - see + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information on how to use it. + * + * @param ref - The reference to add OnDisconnect triggers for. + */ +export declare function onDisconnect(ref: DatabaseReference): OnDisconnect; +export interface ThenableReferenceImpl extends ReferenceImpl, Pick, 'then' | 'catch'> { + key: string; + parent: ReferenceImpl; +} +/** + * Generates a new child location using a unique key and returns its + * `Reference`. + * + * This is the most common pattern for adding data to a collection of items. + * + * If you provide a value to `push()`, the value is written to the + * generated location. If you don't pass a value, nothing is written to the + * database and the child remains empty (but you can use the `Reference` + * elsewhere). + * + * The unique keys generated by `push()` are ordered by the current time, so the + * resulting list of items is chronologically sorted. The keys are also + * designed to be unguessable (they contain 72 random bits of entropy). + * + * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}. + * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}. + * + * @param parent - The parent location. + * @param value - Optional value to be written at the generated location. + * @returns Combined `Promise` and `Reference`; resolves when write is complete, + * but can be used immediately as the `Reference` to the child location. + */ +export declare function push(parent: DatabaseReference, value?: unknown): ThenableReference; +/** + * Removes the data at this Database location. + * + * Any data at child locations will also be deleted. + * + * The effect of the remove will be visible immediately and the corresponding + * event 'value' will be triggered. Synchronization of the remove to the + * Firebase servers will also be started, and the returned Promise will resolve + * when complete. If provided, the onComplete callback will be called + * asynchronously after synchronization has finished. + * + * @param ref - The location to remove. + * @returns Resolves when remove on server is complete. + */ +export declare function remove(ref: DatabaseReference): Promise; +/** + * Writes data to this Database location. + * + * This will overwrite any data at this location and all child locations. + * + * The effect of the write will be visible immediately, and the corresponding + * events ("value", "child_added", etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * Passing `null` for the new value is equivalent to calling `remove()`; namely, + * all data at this location and all child locations will be deleted. + * + * `set()` will remove any priority stored at this location, so if priority is + * meant to be preserved, you need to use `setWithPriority()` instead. + * + * Note that modifying data with `set()` will cancel any pending transactions + * at that location, so extreme care should be taken if mixing `set()` and + * `transaction()` to modify the same data. + * + * A single `set()` will generate a single "value" event at the location where + * the `set()` was performed. + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @returns Resolves when write to server is complete. + */ +export declare function set(ref: DatabaseReference, value: unknown): Promise; +/** + * Sets a priority for the data at this Database location. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +export declare function setPriority(ref: DatabaseReference, priority: string | number | null): Promise; +/** + * Writes data the Database location. Like `set()` but also specifies the + * priority for that data. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +export declare function setWithPriority(ref: DatabaseReference, value: unknown, priority: string | number | null): Promise; +/** + * Writes multiple values to the Database at once. + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, + * "name/first") from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * The effect of the write will be visible immediately, and the corresponding + * events ('value', 'child_added', etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * A single `update()` will generate a single "value" event at the location + * where the `update()` was performed, regardless of how many children were + * modified. + * + * Note that modifying data with `update()` will cancel any pending + * transactions at that location, so extreme care should be taken if mixing + * `update()` and `transaction()` to modify the same data. + * + * Passing `null` to `update()` will remove the data at this location. + * + * See + * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}. + * + * @param ref - The location to write to. + * @param values - Object containing multiple values. + * @returns Resolves when update on server is complete. + */ +export declare function update(ref: DatabaseReference, values: object): Promise; +/** + * Gets the most up-to-date result for this query. + * + * @param query - The query to run. + * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is + * available, or rejects if the client is unable to return a value (e.g., if the + * server is unreachable and there is nothing cached). + */ +export declare function get(query: Query): Promise; +/** + * Represents registration for 'value' events. + */ +export declare class ValueEventRegistration implements EventRegistration { + private callbackContext; + constructor(callbackContext: CallbackContext); + respondsTo(eventType: string): boolean; + createEvent(change: Change, query: QueryContext): DataEvent; + getEventRunner(eventData: CancelEvent | DataEvent): () => void; + createCancelEvent(error: Error, path: Path): CancelEvent | null; + matches(other: EventRegistration): boolean; + hasAnyCallback(): boolean; +} +/** + * Represents the registration of a child_x event. + */ +export declare class ChildEventRegistration implements EventRegistration { + private eventType; + private callbackContext; + constructor(eventType: string, callbackContext: CallbackContext | null); + respondsTo(eventType: string): boolean; + createCancelEvent(error: Error, path: Path): CancelEvent | null; + createEvent(change: Change, query: QueryContext): DataEvent; + getEventRunner(eventData: CancelEvent | DataEvent): () => void; + matches(other: EventRegistration): boolean; + hasAnyCallback(): boolean; +} +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, options: ListenOptions): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe; +export { EventType }; +/** + * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener. + * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from + * the respective `on*` callbacks. + * + * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener + * will not automatically remove listeners registered on child nodes, `off()` + * must also be called on any child listeners to remove the callback. + * + * If a callback is not specified, all callbacks for the specified eventType + * will be removed. Similarly, if no eventType is specified, all callbacks + * for the `Reference` will be removed. + * + * Individual listeners can also be removed by invoking their unsubscribe + * callbacks. + * + * @param query - The query that the listener was registered with. + * @param eventType - One of the following strings: "value", "child_added", + * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks + * for the `Reference` will be removed. + * @param callback - The callback function that was passed to `on()` or + * `undefined` to remove all callbacks. + */ +export declare function off(query: Query, eventType?: EventType, callback?: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown): void; +/** Describes the different query constraints available in this SDK. */ +export type QueryConstraintType = 'endAt' | 'endBefore' | 'startAt' | 'startAfter' | 'limitToFirst' | 'limitToLast' | 'orderByChild' | 'orderByKey' | 'orderByPriority' | 'orderByValue' | 'equalTo'; +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Database query. `QueryConstraint`s are created by invoking {@link endAt}, + * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link + * limitToFirst}, {@link limitToLast}, {@link orderByChild}, + * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} , + * {@link orderByValue} or {@link equalTo} and + * can then be passed to {@link query} to create a new query instance that + * also contains this `QueryConstraint`. + */ +export declare abstract class QueryConstraint { + /** The type of this query constraints */ + abstract readonly type: QueryConstraintType; + /** + * Takes the provided `Query` and returns a copy of the `Query` with this + * `QueryConstraint` applied. + */ + abstract _apply(query: QueryImpl): QueryImpl; +} +/** + * Creates a `QueryConstraint` with the specified ending point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name less than or equal + * to the specified key. + * + * You can read more about `endAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to end at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end at, among the children with the previously + * specified priority. This argument is only allowed if ordering by child, + * value, or priority. + */ +export declare function endAt(value: number | string | boolean | null, key?: string): QueryConstraint; +/** + * Creates a `QueryConstraint` with the specified ending point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is exclusive. If only a value is provided, children + * with a value less than the specified value will be included in the query. + * If a key is specified, then children must have a value less than or equal + * to the specified value and a key name less than the specified key. + * + * @param value - The value to end before. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end before, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +export declare function endBefore(value: number | string | boolean | null, key?: string): QueryConstraint; +/** + * Creates a `QueryConstraint` with the specified starting point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name greater than or + * equal to the specified key. + * + * You can read more about `startAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to start at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at. This argument is only allowed if + * ordering by child, value, or priority. + */ +export declare function startAt(value?: number | string | boolean | null, key?: string): QueryConstraint; +/** + * Creates a `QueryConstraint` with the specified starting point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is exclusive. If only a value is provided, children + * with a value greater than the specified value will be included in the query. + * If a key is specified, then children must have a value greater than or equal + * to the specified value and a a key name greater than the specified key. + * + * @param value - The value to start after. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start after. This argument is only allowed if + * ordering by child, value, or priority. + */ +export declare function startAfter(value: number | string | boolean | null, key?: string): QueryConstraint; +/** + * Creates a new `QueryConstraint` that if limited to the first specific number + * of children. + * + * The `limitToFirst()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the first 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToFirst()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +export declare function limitToFirst(limit: number): QueryConstraint; +/** + * Creates a new `QueryConstraint` that is limited to return only the last + * specified number of children. + * + * The `limitToLast()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the last 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToLast()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +export declare function limitToLast(limit: number): QueryConstraint; +/** + * Creates a new `QueryConstraint` that orders by the specified child key. + * + * Queries can only order by one key at a time. Calling `orderByChild()` + * multiple times on the same query is an error. + * + * Firebase queries allow you to order your data by any child key on the fly. + * However, if you know in advance what your indexes will be, you can define + * them via the .indexOn rule in your Security Rules for better performance. See + * the{@link https://firebase.google.com/docs/database/security/indexing-data} + * rule for more information. + * + * You can read more about `orderByChild()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + * + * @param path - The path to order by. + */ +export declare function orderByChild(path: string): QueryConstraint; +/** + * Creates a new `QueryConstraint` that orders by the key. + * + * Sorts the results of a query by their (ascending) key values. + * + * You can read more about `orderByKey()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +export declare function orderByKey(): QueryConstraint; +/** + * Creates a new `QueryConstraint` that orders by priority. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data} + * for alternatives to priority. + */ +export declare function orderByPriority(): QueryConstraint; +/** + * Creates a new `QueryConstraint` that orders by value. + * + * If the children of a query are all scalar values (string, number, or + * boolean), you can order the results by their (ascending) values. + * + * You can read more about `orderByValue()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +export declare function orderByValue(): QueryConstraint; +/** + * Creates a `QueryConstraint` that includes children that match the specified + * value. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The optional key argument can be used to further limit the range of the + * query. If it is specified, then children that have exactly the specified + * value must also have exactly the specified key as their key name. This can be + * used to filter result sets with many matches for the same value. + * + * You can read more about `equalTo()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to match for. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +export declare function equalTo(value: number | string | boolean | null, key?: string): QueryConstraint; +/** + * Creates a new immutable instance of `Query` that is extended to also include + * additional query constraints. + * + * @param query - The Query instance to use as a base for the new constraints. + * @param queryConstraints - The list of `QueryConstraint`s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query; diff --git a/node_modules/@firebase/database/dist/src/api/ServerValue.d.ts b/node_modules/@firebase/database/dist/src/api/ServerValue.d.ts new file mode 100644 index 0000000..d1a9a4b --- /dev/null +++ b/node_modules/@firebase/database/dist/src/api/ServerValue.d.ts @@ -0,0 +1,30 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a placeholder value for auto-populating the current timestamp (time + * since the Unix epoch, in milliseconds) as determined by the Firebase + * servers. + */ +export declare function serverTimestamp(): object; +/** + * Returns a placeholder value that can be used to atomically increment the + * current database value by the provided delta. + * + * @param delta - the amount to modify the current value atomically. + * @returns A placeholder value for modifying data atomically server-side. + */ +export declare function increment(delta: number): object; diff --git a/node_modules/@firebase/database/dist/src/api/Transaction.d.ts b/node_modules/@firebase/database/dist/src/api/Transaction.d.ts new file mode 100644 index 0000000..bd69015 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/api/Transaction.d.ts @@ -0,0 +1,83 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseReference } from './Reference'; +import { DataSnapshot } from './Reference_impl'; +/** An options object to configure transactions. */ +export interface TransactionOptions { + /** + * By default, events are raised each time the transaction update function + * runs. So if it is run multiple times, you may see intermediate states. You + * can set this to false to suppress these intermediate states and instead + * wait until the transaction has completed before events are raised. + */ + readonly applyLocally?: boolean; +} +/** + * A type for the resolve value of {@link runTransaction}. + */ +export declare class TransactionResult { + /** Whether the transaction was successfully committed. */ + readonly committed: boolean; + /** The resulting data snapshot. */ + readonly snapshot: DataSnapshot; + /** @hideconstructor */ + constructor( + /** Whether the transaction was successfully committed. */ + committed: boolean, + /** The resulting data snapshot. */ + snapshot: DataSnapshot); + /** Returns a JSON-serializable representation of this object. */ + toJSON(): object; +} +/** + * Atomically modifies the data at this location. + * + * Atomically modify the data at this location. Unlike a normal `set()`, which + * just overwrites the data regardless of its previous value, `runTransaction()` is + * used to modify the existing value to a new value, ensuring there are no + * conflicts with other clients writing to the same location at the same time. + * + * To accomplish this, you pass `runTransaction()` an update function which is + * used to transform the current value into a new value. If another client + * writes to the location before your new value is successfully written, your + * update function will be called again with the new current value, and the + * write will be retried. This will happen repeatedly until your write succeeds + * without conflict or you abort the transaction by not returning a value from + * your update function. + * + * Note: Modifying data with `set()` will cancel any pending transactions at + * that location, so extreme care should be taken if mixing `set()` and + * `runTransaction()` to update the same data. + * + * Note: When using transactions with Security and Firebase Rules in place, be + * aware that a client needs `.read` access in addition to `.write` access in + * order to perform a transaction. This is because the client-side nature of + * transactions requires the client to read the data in order to transactionally + * update it. + * + * @param ref - The location to atomically modify. + * @param transactionUpdate - A developer-supplied function which will be passed + * the current data stored at this location (as a JavaScript object). The + * function should return the new value it would like written (as a JavaScript + * object). If `undefined` is returned (i.e. you return with no arguments) the + * transaction will be aborted and the data at this location will not be + * modified. + * @param options - An options object to configure transactions. + * @returns A `Promise` that can optionally be used instead of the `onComplete` + * callback to handle success and failure. + */ +export declare function runTransaction(ref: DatabaseReference, transactionUpdate: (currentData: any) => unknown, options?: TransactionOptions): Promise; diff --git a/node_modules/@firebase/database/dist/src/api/test_access.d.ts b/node_modules/@firebase/database/dist/src/api/test_access.d.ts new file mode 100644 index 0000000..839feaa --- /dev/null +++ b/node_modules/@firebase/database/dist/src/api/test_access.d.ts @@ -0,0 +1,31 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { PersistentConnection } from '../core/PersistentConnection'; +import { RepoInfo } from '../core/RepoInfo'; +import { Connection } from '../realtime/Connection'; +export declare const DataConnection: typeof PersistentConnection; +export declare const RealTimeConnection: typeof Connection; +/** + * @internal + */ +export declare const hijackHash: (newHash: () => string) => () => void; +export declare const ConnectionTarget: typeof RepoInfo; +/** + * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection. + * @internal + */ +export declare const forceRestClient: (forceRestClient: boolean) => void; diff --git a/node_modules/@firebase/database/dist/src/core/AppCheckTokenProvider.d.ts b/node_modules/@firebase/database/dist/src/core/AppCheckTokenProvider.d.ts new file mode 100644 index 0000000..5262dd5 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/AppCheckTokenProvider.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app'; +import { AppCheckInternalComponentName, AppCheckTokenListener, AppCheckTokenResult } from '@firebase/app-check-interop-types'; +import { Provider } from '@firebase/component'; +/** + * Abstraction around AppCheck's token fetching capabilities. + */ +export declare class AppCheckTokenProvider { + private appCheckProvider?; + private appCheck?; + private serverAppAppCheckToken?; + private appName; + constructor(app: FirebaseApp, appCheckProvider?: Provider); + getToken(forceRefresh?: boolean): Promise; + addTokenChangeListener(listener: AppCheckTokenListener): void; + notifyForInvalidToken(): void; +} diff --git a/node_modules/@firebase/database/dist/src/core/AuthTokenProvider.d.ts b/node_modules/@firebase/database/dist/src/core/AuthTokenProvider.d.ts new file mode 100644 index 0000000..5cc81e6 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/AuthTokenProvider.d.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseAuthTokenData } from '@firebase/app-types/private'; +import { FirebaseAuthInternalName } from '@firebase/auth-interop-types'; +import { Provider } from '@firebase/component'; +export interface AuthTokenProvider { + getToken(forceRefresh: boolean): Promise; + addTokenChangeListener(listener: (token: string | null) => void): void; + removeTokenChangeListener(listener: (token: string | null) => void): void; + notifyForInvalidToken(): void; +} +/** + * Abstraction around FirebaseApp's token fetching capabilities. + */ +export declare class FirebaseAuthTokenProvider implements AuthTokenProvider { + private appName_; + private firebaseOptions_; + private authProvider_; + private auth_; + constructor(appName_: string, firebaseOptions_: object, authProvider_: Provider); + getToken(forceRefresh: boolean): Promise; + addTokenChangeListener(listener: (token: string | null) => void): void; + removeTokenChangeListener(listener: (token: string | null) => void): void; + notifyForInvalidToken(): void; +} +export declare class EmulatorTokenProvider implements AuthTokenProvider { + private accessToken; + /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */ + static OWNER: string; + constructor(accessToken: string); + getToken(forceRefresh: boolean): Promise; + addTokenChangeListener(listener: (token: string | null) => void): void; + removeTokenChangeListener(listener: (token: string | null) => void): void; + notifyForInvalidToken(): void; +} diff --git a/node_modules/@firebase/database/dist/src/core/CompoundWrite.d.ts b/node_modules/@firebase/database/dist/src/core/CompoundWrite.d.ts new file mode 100644 index 0000000..0af422b --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/CompoundWrite.d.ts @@ -0,0 +1,81 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NamedNode, Node } from './snap/Node'; +import { ImmutableTree } from './util/ImmutableTree'; +import { Path } from './util/Path'; +/** + * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with + * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write + * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write + * to reflect the write added. + */ +export declare class CompoundWrite { + writeTree_: ImmutableTree; + constructor(writeTree_: ImmutableTree); + static empty(): CompoundWrite; +} +export declare function compoundWriteAddWrite(compoundWrite: CompoundWrite, path: Path, node: Node): CompoundWrite; +export declare function compoundWriteAddWrites(compoundWrite: CompoundWrite, path: Path, updates: { + [name: string]: Node; +}): CompoundWrite; +/** + * Will remove a write at the given path and deeper paths. This will not modify a write at a higher + * location, which must be removed by calling this method with that path. + * + * @param compoundWrite - The CompoundWrite to remove. + * @param path - The path at which a write and all deeper writes should be removed + * @returns The new CompoundWrite with the removed path + */ +export declare function compoundWriteRemoveWrite(compoundWrite: CompoundWrite, path: Path): CompoundWrite; +/** + * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be + * considered "complete". + * + * @param compoundWrite - The CompoundWrite to check. + * @param path - The path to check for + * @returns Whether there is a complete write at that path + */ +export declare function compoundWriteHasCompleteWrite(compoundWrite: CompoundWrite, path: Path): boolean; +/** + * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate + * writes from deeper paths, but will return child nodes from a more shallow path. + * + * @param compoundWrite - The CompoundWrite to get the node from. + * @param path - The path to get a complete write + * @returns The node if complete at that path, or null otherwise. + */ +export declare function compoundWriteGetCompleteNode(compoundWrite: CompoundWrite, path: Path): Node | null; +/** + * Returns all children that are guaranteed to be a complete overwrite. + * + * @param compoundWrite - The CompoundWrite to get children from. + * @returns A list of all complete children. + */ +export declare function compoundWriteGetCompleteChildren(compoundWrite: CompoundWrite): NamedNode[]; +export declare function compoundWriteChildCompoundWrite(compoundWrite: CompoundWrite, path: Path): CompoundWrite; +/** + * Returns true if this CompoundWrite is empty and therefore does not modify any nodes. + * @returns Whether this CompoundWrite is empty + */ +export declare function compoundWriteIsEmpty(compoundWrite: CompoundWrite): boolean; +/** + * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the + * node + * @param node - The node to apply this CompoundWrite to + * @returns The node with all writes applied + */ +export declare function compoundWriteApply(compoundWrite: CompoundWrite, node: Node): Node; diff --git a/node_modules/@firebase/database/dist/src/core/PersistentConnection.d.ts b/node_modules/@firebase/database/dist/src/core/PersistentConnection.d.ts new file mode 100644 index 0000000..1868d90 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/PersistentConnection.d.ts @@ -0,0 +1,135 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AppCheckTokenProvider } from './AppCheckTokenProvider'; +import { AuthTokenProvider } from './AuthTokenProvider'; +import { RepoInfo } from './RepoInfo'; +import { ServerActions } from './ServerActions'; +import { QueryContext } from './view/EventRegistration'; +/** + * Firebase connection. Abstracts wire protocol and handles reconnecting. + * + * NOTE: All JSON objects sent to the realtime connection must have property names enclosed + * in quotes to make sure the closure compiler does not minify them. + */ +export declare class PersistentConnection extends ServerActions { + private repoInfo_; + private applicationId_; + private onDataUpdate_; + private onConnectStatus_; + private onServerInfoUpdate_; + private authTokenProvider_; + private appCheckTokenProvider_; + private authOverride_?; + id: number; + private log_; + private interruptReasons_; + private readonly listens; + private outstandingPuts_; + private outstandingGets_; + private outstandingPutCount_; + private outstandingGetCount_; + private onDisconnectRequestQueue_; + private connected_; + private reconnectDelay_; + private maxReconnectDelay_; + private securityDebugCallback_; + lastSessionId: string | null; + private establishConnectionTimer_; + private visible_; + private requestCBHash_; + private requestNumber_; + private realtime_; + private authToken_; + private appCheckToken_; + private forceTokenRefresh_; + private invalidAuthTokenCount_; + private invalidAppCheckTokenCount_; + private firstConnection_; + private lastConnectionAttemptTime_; + private lastConnectionEstablishedTime_; + private static nextPersistentConnectionId_; + /** + * Counter for number of connections created. Mainly used for tagging in the logs + */ + private static nextConnectionId_; + /** + * @param repoInfo_ - Data about the namespace we are connecting to + * @param applicationId_ - The Firebase App ID for this project + * @param onDataUpdate_ - A callback for new data from the server + */ + constructor(repoInfo_: RepoInfo, applicationId_: string, onDataUpdate_: (a: string, b: unknown, c: boolean, d: number | null) => void, onConnectStatus_: (a: boolean) => void, onServerInfoUpdate_: (a: unknown) => void, authTokenProvider_: AuthTokenProvider, appCheckTokenProvider_: AppCheckTokenProvider, authOverride_?: object | null); + protected sendRequest(action: string, body: unknown, onResponse?: (a: unknown) => void): void; + get(query: QueryContext): Promise; + listen(query: QueryContext, currentHashFn: () => string, tag: number | null, onComplete: (a: string, b: unknown) => void): void; + private sendGet_; + private sendListen_; + private static warnOnListenWarnings_; + refreshAuthToken(token: string): void; + private reduceReconnectDelayIfAdminCredential_; + refreshAppCheckToken(token: string | null): void; + /** + * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like + * a auth revoked (the connection is closed). + */ + tryAuth(): void; + /** + * Attempts to authenticate with the given token. If the authentication + * attempt fails, it's triggered like the token was revoked (the connection is + * closed). + */ + tryAppCheck(): void; + /** + * @inheritDoc + */ + unlisten(query: QueryContext, tag: number | null): void; + private sendUnlisten_; + onDisconnectPut(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void): void; + onDisconnectMerge(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void): void; + onDisconnectCancel(pathString: string, onComplete?: (a: string, b: string) => void): void; + private sendOnDisconnect_; + put(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void, hash?: string): void; + merge(pathString: string, data: unknown, onComplete: (a: string, b: string | null) => void, hash?: string): void; + putInternal(action: string, pathString: string, data: unknown, onComplete: (a: string, b: string | null) => void, hash?: string): void; + private sendPut_; + reportStats(stats: { + [k: string]: unknown; + }): void; + private onDataMessage_; + private onDataPush_; + private onReady_; + private scheduleConnect_; + private initConnection_; + private onVisible_; + private onOnline_; + private onRealtimeDisconnect_; + private establishConnection_; + interrupt(reason: string): void; + resume(reason: string): void; + private handleTimestamp_; + private cancelSentTransactions_; + private onListenRevoked_; + private removeListen_; + private onAuthRevoked_; + private onAppCheckRevoked_; + private onSecurityDebugPacket_; + private restoreState_; + /** + * Sends client stats for first connection + */ + private sendConnectStats_; + private shouldReconnect_; +} diff --git a/node_modules/@firebase/database/dist/src/core/ReadonlyRestClient.d.ts b/node_modules/@firebase/database/dist/src/core/ReadonlyRestClient.d.ts new file mode 100644 index 0000000..28c1710 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/ReadonlyRestClient.d.ts @@ -0,0 +1,60 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AppCheckTokenProvider } from './AppCheckTokenProvider'; +import { AuthTokenProvider } from './AuthTokenProvider'; +import { RepoInfo } from './RepoInfo'; +import { ServerActions } from './ServerActions'; +import { QueryContext } from './view/EventRegistration'; +/** + * An implementation of ServerActions that communicates with the server via REST requests. + * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full + * persistent connection (using WebSockets or long-polling) + */ +export declare class ReadonlyRestClient extends ServerActions { + private repoInfo_; + private onDataUpdate_; + private authTokenProvider_; + private appCheckTokenProvider_; + reportStats(stats: { + [k: string]: unknown; + }): void; + /** @private {function(...[*])} */ + private log_; + /** + * We don't actually need to track listens, except to prevent us calling an onComplete for a listen + * that's been removed. :-/ + */ + private listens_; + static getListenId_(query: QueryContext, tag?: number | null): string; + /** + * @param repoInfo_ - Data about the namespace we are connecting to + * @param onDataUpdate_ - A callback for new data from the server + */ + constructor(repoInfo_: RepoInfo, onDataUpdate_: (a: string, b: unknown, c: boolean, d: number | null) => void, authTokenProvider_: AuthTokenProvider, appCheckTokenProvider_: AppCheckTokenProvider); + /** @inheritDoc */ + listen(query: QueryContext, currentHashFn: () => string, tag: number | null, onComplete: (a: string, b: unknown) => void): void; + /** @inheritDoc */ + unlisten(query: QueryContext, tag: number | null): void; + get(query: QueryContext): Promise; + /** @inheritDoc */ + refreshAuthToken(token: string): void; + /** + * Performs a REST request to the given path, with the provided query string parameters, + * and any auth credentials we have. + */ + private restRequest_; +} diff --git a/node_modules/@firebase/database/dist/src/core/Repo.d.ts b/node_modules/@firebase/database/dist/src/core/Repo.d.ts new file mode 100644 index 0000000..6861109 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/Repo.d.ts @@ -0,0 +1,144 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ValueEventRegistration } from '../api/Reference_impl'; +import { AppCheckTokenProvider } from './AppCheckTokenProvider'; +import { AuthTokenProvider } from './AuthTokenProvider'; +import { PersistentConnection } from './PersistentConnection'; +import { RepoInfo } from './RepoInfo'; +import { ServerActions } from './ServerActions'; +import { Node } from './snap/Node'; +import { SnapshotHolder } from './SnapshotHolder'; +import { SparseSnapshotTree } from './SparseSnapshotTree'; +import { StatsCollection } from './stats/StatsCollection'; +import { StatsListener } from './stats/StatsListener'; +import { StatsReporter } from './stats/StatsReporter'; +import { SyncTree } from './SyncTree'; +import { Indexable } from './util/misc'; +import { Path } from './util/Path'; +import { Tree } from './util/Tree'; +import { EventQueue } from './view/EventQueue'; +import { EventRegistration, QueryContext } from './view/EventRegistration'; +declare const enum TransactionStatus { + RUN = 0, + SENT = 1, + COMPLETED = 2, + SENT_NEEDS_ABORT = 3, + NEEDS_ABORT = 4 +} +interface Transaction { + path: Path; + update: (a: unknown) => unknown; + onComplete: (error: Error | null, committed: boolean, node: Node | null) => void; + status: TransactionStatus; + order: number; + applyLocally: boolean; + retryCount: number; + unwatcher: () => void; + abortReason: string | null; + currentWriteId: number; + currentInputSnapshot: Node | null; + currentOutputSnapshotRaw: Node | null; + currentOutputSnapshotResolved: Node | null; +} +/** + * A connection to a single data repository. + */ +export declare class Repo { + repoInfo_: RepoInfo; + forceRestClient_: boolean; + authTokenProvider_: AuthTokenProvider; + appCheckProvider_: AppCheckTokenProvider; + /** Key for uniquely identifying this repo, used in RepoManager */ + readonly key: string; + dataUpdateCount: number; + infoSyncTree_: SyncTree; + serverSyncTree_: SyncTree; + stats_: StatsCollection; + statsListener_: StatsListener | null; + eventQueue_: EventQueue; + nextWriteId_: number; + server_: ServerActions; + statsReporter_: StatsReporter; + infoData_: SnapshotHolder; + interceptServerDataCallback_: ((a: string, b: unknown) => void) | null; + /** A list of data pieces and paths to be set when this client disconnects. */ + onDisconnect_: SparseSnapshotTree; + /** Stores queues of outstanding transactions for Firebase locations. */ + transactionQueueTree_: Tree; + persistentConnection_: PersistentConnection | null; + constructor(repoInfo_: RepoInfo, forceRestClient_: boolean, authTokenProvider_: AuthTokenProvider, appCheckProvider_: AppCheckTokenProvider); + /** + * @returns The URL corresponding to the root of this Firebase. + */ + toString(): string; +} +export declare function repoStart(repo: Repo, appId: string, authOverride?: object): void; +/** + * @returns The time in milliseconds, taking the server offset into account if we have one. + */ +export declare function repoServerTime(repo: Repo): number; +/** + * Generate ServerValues using some variables from the repo object. + */ +export declare function repoGenerateServerValues(repo: Repo): Indexable; +export declare function repoInterceptServerData(repo: Repo, callback: ((a: string, b: unknown) => unknown) | null): void; +/** + * The purpose of `getValue` is to return the latest known value + * satisfying `query`. + * + * This method will first check for in-memory cached values + * belonging to active listeners. If they are found, such values + * are considered to be the most up-to-date. + * + * If the client is not connected, this method will wait until the + * repo has established a connection and then request the value for `query`. + * If the client is not able to retrieve the query result for another reason, + * it reports an error. + * + * @param query - The query to surface a value for. + */ +export declare function repoGetValue(repo: Repo, query: QueryContext, eventRegistration: ValueEventRegistration): Promise; +export declare function repoSetWithPriority(repo: Repo, path: Path, newVal: unknown, newPriority: number | string | null, onComplete: ((status: Error | null, errorReason?: string) => void) | null): void; +export declare function repoUpdate(repo: Repo, path: Path, childrenToMerge: { + [k: string]: unknown; +}, onComplete: ((status: Error | null, errorReason?: string) => void) | null): void; +export declare function repoOnDisconnectCancel(repo: Repo, path: Path, onComplete: ((status: Error | null, errorReason?: string) => void) | null): void; +export declare function repoOnDisconnectSet(repo: Repo, path: Path, value: unknown, onComplete: ((status: Error | null, errorReason?: string) => void) | null): void; +export declare function repoOnDisconnectSetWithPriority(repo: Repo, path: Path, value: unknown, priority: unknown, onComplete: ((status: Error | null, errorReason?: string) => void) | null): void; +export declare function repoOnDisconnectUpdate(repo: Repo, path: Path, childrenToMerge: { + [k: string]: unknown; +}, onComplete: ((status: Error | null, errorReason?: string) => void) | null): void; +export declare function repoAddEventCallbackForQuery(repo: Repo, query: QueryContext, eventRegistration: EventRegistration): void; +export declare function repoRemoveEventCallbackForQuery(repo: Repo, query: QueryContext, eventRegistration: EventRegistration): void; +export declare function repoInterrupt(repo: Repo): void; +export declare function repoResume(repo: Repo): void; +export declare function repoStats(repo: Repo, showDelta?: boolean): void; +export declare function repoStatsIncrementCounter(repo: Repo, metric: string): void; +export declare function repoCallOnCompleteCallback(repo: Repo, callback: ((status: Error | null, errorReason?: string) => void) | null, status: string, errorReason?: string | null): void; +/** + * Creates a new transaction, adds it to the transactions we're tracking, and + * sends it to the server if possible. + * + * @param path - Path at which to do transaction. + * @param transactionUpdate - Update callback. + * @param onComplete - Completion callback. + * @param unwatcher - Function that will be called when the transaction no longer + * need data updates for `path`. + * @param applyLocally - Whether or not to make intermediate results visible + */ +export declare function repoStartTransaction(repo: Repo, path: Path, transactionUpdate: (a: unknown) => unknown, onComplete: ((error: Error, committed: boolean, node: Node) => void) | null, unwatcher: () => void, applyLocally: boolean): void; +export {}; diff --git a/node_modules/@firebase/database/dist/src/core/RepoInfo.d.ts b/node_modules/@firebase/database/dist/src/core/RepoInfo.d.ts new file mode 100644 index 0000000..4604e86 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/RepoInfo.d.ts @@ -0,0 +1,61 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { EmulatorMockTokenOptions } from '@firebase/util'; +export interface RepoInfoEmulatorOptions { + mockUserToken?: string | EmulatorMockTokenOptions; +} +/** + * A class that holds metadata about a Repo object + */ +export declare class RepoInfo { + readonly secure: boolean; + readonly namespace: string; + readonly webSocketOnly: boolean; + readonly nodeAdmin: boolean; + readonly persistenceKey: string; + readonly includeNamespaceInQueryParams: boolean; + readonly isUsingEmulator: boolean; + readonly emulatorOptions: RepoInfoEmulatorOptions | null; + private _host; + private _domain; + internalHost: string; + /** + * @param host - Hostname portion of the url for the repo + * @param secure - Whether or not this repo is accessed over ssl + * @param namespace - The namespace represented by the repo + * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest). + * @param nodeAdmin - Whether this instance uses Admin SDK credentials + * @param persistenceKey - Override the default session persistence storage key + */ + constructor(host: string, secure: boolean, namespace: string, webSocketOnly: boolean, nodeAdmin?: boolean, persistenceKey?: string, includeNamespaceInQueryParams?: boolean, isUsingEmulator?: boolean, emulatorOptions?: RepoInfoEmulatorOptions | null); + isCacheableHost(): boolean; + isCustomHost(): boolean; + get host(): string; + set host(newHost: string); + toString(): string; + toURLString(): string; +} +/** + * Returns the websocket URL for this repo + * @param repoInfo - RepoInfo object + * @param type - of connection + * @param params - list + * @returns The URL for this repo + */ +export declare function repoInfoConnectionURL(repoInfo: RepoInfo, type: string, params: { + [k: string]: string; +}): string; diff --git a/node_modules/@firebase/database/dist/src/core/ServerActions.d.ts b/node_modules/@firebase/database/dist/src/core/ServerActions.d.ts new file mode 100644 index 0000000..9f13a86 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/ServerActions.d.ts @@ -0,0 +1,52 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { QueryContext } from './view/EventRegistration'; +/** + * Interface defining the set of actions that can be performed against the Firebase server + * (basically corresponds to our wire protocol). + * + * @interface + */ +export declare abstract class ServerActions { + abstract listen(query: QueryContext, currentHashFn: () => string, tag: number | null, onComplete: (a: string, b: unknown) => void): void; + /** + * Remove a listen. + */ + abstract unlisten(query: QueryContext, tag: number | null): void; + /** + * Get the server value satisfying this query. + */ + abstract get(query: QueryContext): Promise; + put(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void, hash?: string): void; + merge(pathString: string, data: unknown, onComplete: (a: string, b: string | null) => void, hash?: string): void; + /** + * Refreshes the auth token for the current connection. + * @param token - The authentication token + */ + refreshAuthToken(token: string): void; + /** + * Refreshes the app check token for the current connection. + * @param token The app check token + */ + refreshAppCheckToken(token: string): void; + onDisconnectPut(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void): void; + onDisconnectMerge(pathString: string, data: unknown, onComplete?: (a: string, b: string) => void): void; + onDisconnectCancel(pathString: string, onComplete?: (a: string, b: string) => void): void; + reportStats(stats: { + [k: string]: unknown; + }): void; +} diff --git a/node_modules/@firebase/database/dist/src/core/SnapshotHolder.d.ts b/node_modules/@firebase/database/dist/src/core/SnapshotHolder.d.ts new file mode 100644 index 0000000..cdd8456 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/SnapshotHolder.d.ts @@ -0,0 +1,26 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Node } from './snap/Node'; +import { Path } from './util/Path'; +/** + * Mutable object which basically just stores a reference to the "latest" immutable snapshot. + */ +export declare class SnapshotHolder { + private rootNode_; + getNode(path: Path): Node; + updateSnapshot(path: Path, newSnapshotNode: Node): void; +} diff --git a/node_modules/@firebase/database/dist/src/core/SparseSnapshotTree.d.ts b/node_modules/@firebase/database/dist/src/core/SparseSnapshotTree.d.ts new file mode 100644 index 0000000..ddd382e --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/SparseSnapshotTree.d.ts @@ -0,0 +1,64 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Node } from './snap/Node'; +import { Path } from './util/Path'; +/** + * Helper class to store a sparse set of snapshots. + */ +export interface SparseSnapshotTree { + value: Node | null; + readonly children: Map; +} +export declare function newSparseSnapshotTree(): SparseSnapshotTree; +/** + * Gets the node stored at the given path if one exists. + * Only seems to be used in tests. + * + * @param path - Path to look up snapshot for. + * @returns The retrieved node, or null. + */ +export declare function sparseSnapshotTreeFind(sparseSnapshotTree: SparseSnapshotTree, path: Path): Node | null; +/** + * Stores the given node at the specified path. If there is already a node + * at a shallower path, it merges the new data into that snapshot node. + * + * @param path - Path to look up snapshot for. + * @param data - The new data, or null. + */ +export declare function sparseSnapshotTreeRemember(sparseSnapshotTree: SparseSnapshotTree, path: Path, data: Node): void; +/** + * Purge the data at path from the cache. + * + * @param path - Path to look up snapshot for. + * @returns True if this node should now be removed. + */ +export declare function sparseSnapshotTreeForget(sparseSnapshotTree: SparseSnapshotTree, path: Path): boolean; +/** + * Recursively iterates through all of the stored tree and calls the + * callback on each one. + * + * @param prefixPath - Path to look up node for. + * @param func - The function to invoke for each tree. + */ +export declare function sparseSnapshotTreeForEachTree(sparseSnapshotTree: SparseSnapshotTree, prefixPath: Path, func: (a: Path, b: Node) => unknown): void; +/** + * Iterates through each immediate child and triggers the callback. + * Only seems to be used in tests. + * + * @param func - The function to invoke for each child. + */ +export declare function sparseSnapshotTreeForEachChild(sparseSnapshotTree: SparseSnapshotTree, func: (a: string, b: SparseSnapshotTree) => void): void; diff --git a/node_modules/@firebase/database/dist/src/core/SyncPoint.d.ts b/node_modules/@firebase/database/dist/src/core/SyncPoint.d.ts new file mode 100644 index 0000000..b6b4daf --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/SyncPoint.d.ts @@ -0,0 +1,91 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ReferenceConstructor } from '../api/Reference'; +import { Operation } from './operation/Operation'; +import { Node } from './snap/Node'; +import { Path } from './util/Path'; +import { Event } from './view/Event'; +import { EventRegistration, QueryContext } from './view/EventRegistration'; +import { View } from './view/View'; +import { WriteTreeRef } from './WriteTree'; +/** + * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to + * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes + * and user writes (set, transaction, update). + * + * It's responsible for: + * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed). + * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite, + * applyUserOverwrite, etc.) + */ +export declare class SyncPoint { + /** + * The Views being tracked at this location in the tree, stored as a map where the key is a + * queryId and the value is the View for that query. + * + * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case). + */ + readonly views: Map; +} +export declare function syncPointSetReferenceConstructor(val: ReferenceConstructor): void; +export declare function syncPointIsEmpty(syncPoint: SyncPoint): boolean; +export declare function syncPointApplyOperation(syncPoint: SyncPoint, operation: Operation, writesCache: WriteTreeRef, optCompleteServerCache: Node | null): Event[]; +/** + * Get a view for the specified query. + * + * @param query - The query to return a view for + * @param writesCache + * @param serverCache + * @param serverCacheComplete + * @returns Events to raise. + */ +export declare function syncPointGetView(syncPoint: SyncPoint, query: QueryContext, writesCache: WriteTreeRef, serverCache: Node | null, serverCacheComplete: boolean): View; +/** + * Add an event callback for the specified query. + * + * @param query + * @param eventRegistration + * @param writesCache + * @param serverCache - Complete server cache, if we have it. + * @param serverCacheComplete + * @returns Events to raise. + */ +export declare function syncPointAddEventRegistration(syncPoint: SyncPoint, query: QueryContext, eventRegistration: EventRegistration, writesCache: WriteTreeRef, serverCache: Node | null, serverCacheComplete: boolean): Event[]; +/** + * Remove event callback(s). Return cancelEvents if a cancelError is specified. + * + * If query is the default query, we'll check all views for the specified eventRegistration. + * If eventRegistration is null, we'll remove all callbacks for the specified view(s). + * + * @param eventRegistration - If null, remove all callbacks. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @returns removed queries and any cancel events + */ +export declare function syncPointRemoveEventRegistration(syncPoint: SyncPoint, query: QueryContext, eventRegistration: EventRegistration | null, cancelError?: Error): { + removed: QueryContext[]; + events: Event[]; +}; +export declare function syncPointGetQueryViews(syncPoint: SyncPoint): View[]; +/** + * @param path - The path to the desired complete snapshot + * @returns A complete cache, if it exists + */ +export declare function syncPointGetCompleteServerCache(syncPoint: SyncPoint, path: Path): Node | null; +export declare function syncPointViewForQuery(syncPoint: SyncPoint, query: QueryContext): View | null; +export declare function syncPointViewExistsForQuery(syncPoint: SyncPoint, query: QueryContext): boolean; +export declare function syncPointHasCompleteView(syncPoint: SyncPoint): boolean; +export declare function syncPointGetCompleteView(syncPoint: SyncPoint): View | null; diff --git a/node_modules/@firebase/database/dist/src/core/SyncTree.d.ts b/node_modules/@firebase/database/dist/src/core/SyncTree.d.ts new file mode 100644 index 0000000..7025a3d --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/SyncTree.d.ts @@ -0,0 +1,166 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ReferenceConstructor } from '../api/Reference'; +import { Node } from './snap/Node'; +import { SyncPoint } from './SyncPoint'; +import { ImmutableTree } from './util/ImmutableTree'; +import { Path } from './util/Path'; +import { Event } from './view/Event'; +import { EventRegistration, QueryContext } from './view/EventRegistration'; +import { WriteTree } from './WriteTree'; +export declare function syncTreeSetReferenceConstructor(val: ReferenceConstructor): void; +export interface ListenProvider { + startListening(query: QueryContext, tag: number | null, hashFn: () => string, onComplete: (a: string, b?: unknown) => Event[]): Event[]; + stopListening(a: QueryContext, b: number | null): void; +} +export declare function resetSyncTreeTag(): void; +/** + * SyncTree is the central class for managing event callback registration, data caching, views + * (query processing), and event generation. There are typically two SyncTree instances for + * each Repo, one for the normal Firebase data, and one for the .info data. + * + * It has a number of responsibilities, including: + * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()). + * - Applying and caching data changes for user set(), transaction(), and update() calls + * (applyUserOverwrite(), applyUserMerge()). + * - Applying and caching data changes for server data changes (applyServerOverwrite(), + * applyServerMerge()). + * - Generating user-facing events for server and user changes (all of the apply* methods + * return the set of events that need to be raised as a result). + * - Maintaining the appropriate set of server listens to ensure we are always subscribed + * to the correct set of paths and queries to satisfy the current set of user event + * callbacks (listens are started/stopped using the provided listenProvider). + * + * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual + * events are returned to the caller rather than raised synchronously. + * + */ +export declare class SyncTree { + listenProvider_: ListenProvider; + /** + * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views. + */ + syncPointTree_: ImmutableTree; + /** + * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.). + */ + pendingWriteTree_: WriteTree; + readonly tagToQueryMap: Map; + readonly queryToTagMap: Map; + /** + * @param listenProvider_ - Used by SyncTree to start / stop listening + * to server data. + */ + constructor(listenProvider_: ListenProvider); +} +/** + * Apply the data changes for a user-generated set() or transaction() call. + * + * @returns Events to raise. + */ +export declare function syncTreeApplyUserOverwrite(syncTree: SyncTree, path: Path, newData: Node, writeId: number, visible?: boolean): Event[]; +/** + * Apply the data from a user-generated update() call + * + * @returns Events to raise. + */ +export declare function syncTreeApplyUserMerge(syncTree: SyncTree, path: Path, changedChildren: { + [k: string]: Node; +}, writeId: number): Event[]; +/** + * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge(). + * + * @param revert - True if the given write failed and needs to be reverted + * @returns Events to raise. + */ +export declare function syncTreeAckUserWrite(syncTree: SyncTree, writeId: number, revert?: boolean): Event[]; +/** + * Apply new server data for the specified path.. + * + * @returns Events to raise. + */ +export declare function syncTreeApplyServerOverwrite(syncTree: SyncTree, path: Path, newData: Node): Event[]; +/** + * Apply new server data to be merged in at the specified path. + * + * @returns Events to raise. + */ +export declare function syncTreeApplyServerMerge(syncTree: SyncTree, path: Path, changedChildren: { + [k: string]: Node; +}): Event[]; +/** + * Apply a listen complete for a query + * + * @returns Events to raise. + */ +export declare function syncTreeApplyListenComplete(syncTree: SyncTree, path: Path): Event[]; +/** + * Apply a listen complete for a tagged query + * + * @returns Events to raise. + */ +export declare function syncTreeApplyTaggedListenComplete(syncTree: SyncTree, path: Path, tag: number): Event[]; +/** + * Remove event callback(s). + * + * If query is the default query, we'll check all queries for the specified eventRegistration. + * If eventRegistration is null, we'll remove all callbacks for the specified query/queries. + * + * @param eventRegistration - If null, all callbacks are removed. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no + * deduping needs to take place. This flag allows toggling of that behavior + * @returns Cancel events, if cancelError was provided. + */ +export declare function syncTreeRemoveEventRegistration(syncTree: SyncTree, query: QueryContext, eventRegistration: EventRegistration | null, cancelError?: Error, skipListenerDedup?: boolean): Event[]; +/** + * Apply new server data for the specified tagged query. + * + * @returns Events to raise. + */ +export declare function syncTreeApplyTaggedQueryOverwrite(syncTree: SyncTree, path: Path, snap: Node, tag: number): Event[]; +/** + * Apply server data to be merged in for the specified tagged query. + * + * @returns Events to raise. + */ +export declare function syncTreeApplyTaggedQueryMerge(syncTree: SyncTree, path: Path, changedChildren: { + [k: string]: Node; +}, tag: number): Event[]; +/** + * Add an event callback for the specified query. + * + * @returns Events to raise. + */ +export declare function syncTreeAddEventRegistration(syncTree: SyncTree, query: QueryContext, eventRegistration: EventRegistration, skipSetupListener?: boolean): Event[]; +/** + * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a + * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always + * have a listener above, and atomic operations would correctly show a jitter of -> + * as the write is applied locally and then acknowledged at the server. + * + * Note: this method will *include* hidden writes from transaction with applyLocally set to false. + * + * @param path - The path to the data we want + * @param writeIdsToExclude - A specific set to be excluded + */ +export declare function syncTreeCalcCompleteEventCache(syncTree: SyncTree, path: Path, writeIdsToExclude?: number[]): Node; +export declare function syncTreeGetServerValue(syncTree: SyncTree, query: QueryContext): Node | null; +/** + * Return the tag associated with the given query. + */ +export declare function syncTreeTagForQuery(syncTree: SyncTree, query: QueryContext): number | null; diff --git a/node_modules/@firebase/database/dist/src/core/WriteTree.d.ts b/node_modules/@firebase/database/dist/src/core/WriteTree.d.ts new file mode 100644 index 0000000..8b03daa --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/WriteTree.d.ts @@ -0,0 +1,205 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CompoundWrite } from './CompoundWrite'; +import { ChildrenNode } from './snap/ChildrenNode'; +import { Index } from './snap/indexes/Index'; +import { NamedNode, Node } from './snap/Node'; +import { Path } from './util/Path'; +import { CacheNode } from './view/CacheNode'; +/** + * Defines a single user-initiated write operation. May be the result of a set(), transaction(), or update() call. In + * the case of a set() or transaction, snap will be non-null. In the case of an update(), children will be non-null. + */ +export interface WriteRecord { + writeId: number; + path: Path; + snap?: Node | null; + children?: { + [k: string]: Node; + } | null; + visible: boolean; +} +/** + * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path. + * + */ +export declare function writeTreeChildWrites(writeTree: WriteTree, path: Path): WriteTreeRef; +/** + * Record a new overwrite from user code. + * + * @param visible - This is set to false by some transactions. It should be excluded from event caches + */ +export declare function writeTreeAddOverwrite(writeTree: WriteTree, path: Path, snap: Node, writeId: number, visible?: boolean): void; +/** + * Record a new merge from user code. + */ +export declare function writeTreeAddMerge(writeTree: WriteTree, path: Path, changedChildren: { + [k: string]: Node; +}, writeId: number): void; +export declare function writeTreeGetWrite(writeTree: WriteTree, writeId: number): WriteRecord | null; +/** + * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates + * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate. + * + * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise + * events as a result). + */ +export declare function writeTreeRemoveWrite(writeTree: WriteTree, writeId: number): boolean; +/** + * Return a complete snapshot for the given path if there's visible write data at that path, else null. + * No server data is considered. + * + */ +export declare function writeTreeGetCompleteWriteData(writeTree: WriteTree, path: Path): Node | null; +/** + * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden + * writes), attempt to calculate a complete snapshot for the given path + * + * @param writeIdsToExclude - An optional set to be excluded + * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false + */ +export declare function writeTreeCalcCompleteEventCache(writeTree: WriteTree, treePath: Path, completeServerCache: Node | null, writeIdsToExclude?: number[], includeHiddenWrites?: boolean): Node | null; +/** + * With optional, underlying server data, attempt to return a children node of children that we have complete data for. + * Used when creating new views, to pre-fill their complete event children snapshot. + */ +export declare function writeTreeCalcCompleteEventChildren(writeTree: WriteTree, treePath: Path, completeServerChildren: ChildrenNode | null): Node; +/** + * Given that the underlying server data has updated, determine what, if anything, needs to be + * applied to the event cache. + * + * Possibilities: + * + * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data + * + * 2. Some write is completely shadowing. No events to be raised + * + * 3. Is partially shadowed. Events + * + * Either existingEventSnap or existingServerSnap must exist + */ +export declare function writeTreeCalcEventCacheAfterServerOverwrite(writeTree: WriteTree, treePath: Path, childPath: Path, existingEventSnap: Node | null, existingServerSnap: Node | null): Node | null; +/** + * Returns a complete child for a given server snap after applying all user writes or null if there is no + * complete child for this ChildKey. + */ +export declare function writeTreeCalcCompleteChild(writeTree: WriteTree, treePath: Path, childKey: string, existingServerSnap: CacheNode): Node | null; +/** + * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at + * a higher path, this will return the child of that write relative to the write and this path. + * Returns null if there is no write at this path. + */ +export declare function writeTreeShadowingWrite(writeTree: WriteTree, path: Path): Node | null; +/** + * This method is used when processing child remove events on a query. If we can, we pull in children that were outside + * the window, but may now be in the window. + */ +export declare function writeTreeCalcIndexedSlice(writeTree: WriteTree, treePath: Path, completeServerData: Node | null, startPost: NamedNode, count: number, reverse: boolean, index: Index): NamedNode[]; +export declare function newWriteTree(): WriteTree; +/** + * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them + * with underlying server data (to create "event cache" data). Pending writes are added with addOverwrite() + * and addMerge(), and removed with removeWrite(). + */ +export interface WriteTree { + /** + * A tree tracking the result of applying all visible writes. This does not include transactions with + * applyLocally=false or writes that are completely shadowed by other writes. + */ + visibleWrites: CompoundWrite; + /** + * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary + * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also + * used by transactions). + */ + allWrites: WriteRecord[]; + lastWriteId: number; +} +/** + * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used + * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node + * can lead to a more expensive calculation. + * + * @param writeIdsToExclude - Optional writes to exclude. + * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false + */ +export declare function writeTreeRefCalcCompleteEventCache(writeTreeRef: WriteTreeRef, completeServerCache: Node | null, writeIdsToExclude?: number[], includeHiddenWrites?: boolean): Node | null; +/** + * If possible, returns a children node containing all of the complete children we have data for. The returned data is a + * mix of the given server data and write data. + * + */ +export declare function writeTreeRefCalcCompleteEventChildren(writeTreeRef: WriteTreeRef, completeServerChildren: ChildrenNode | null): ChildrenNode; +/** + * Given that either the underlying server data has updated or the outstanding writes have updated, determine what, + * if anything, needs to be applied to the event cache. + * + * Possibilities: + * + * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data + * + * 2. Some write is completely shadowing. No events to be raised + * + * 3. Is partially shadowed. Events should be raised + * + * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert + * + * + */ +export declare function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef: WriteTreeRef, path: Path, existingEventSnap: Node | null, existingServerSnap: Node | null): Node | null; +/** + * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at + * a higher path, this will return the child of that write relative to the write and this path. + * Returns null if there is no write at this path. + * + */ +export declare function writeTreeRefShadowingWrite(writeTreeRef: WriteTreeRef, path: Path): Node | null; +/** + * This method is used when processing child remove events on a query. If we can, we pull in children that were outside + * the window, but may now be in the window + */ +export declare function writeTreeRefCalcIndexedSlice(writeTreeRef: WriteTreeRef, completeServerData: Node | null, startPost: NamedNode, count: number, reverse: boolean, index: Index): NamedNode[]; +/** + * Returns a complete child for a given server snap after applying all user writes or null if there is no + * complete child for this ChildKey. + */ +export declare function writeTreeRefCalcCompleteChild(writeTreeRef: WriteTreeRef, childKey: string, existingServerCache: CacheNode): Node | null; +/** + * Return a WriteTreeRef for a child. + */ +export declare function writeTreeRefChild(writeTreeRef: WriteTreeRef, childName: string): WriteTreeRef; +export declare function newWriteTreeRef(path: Path, writeTree: WriteTree): WriteTreeRef; +/** + * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods + * just proxy to the underlying WriteTree. + * + */ +export interface WriteTreeRef { + /** + * The path to this particular write tree ref. Used for calling methods on writeTree_ while exposing a simpler + * interface to callers. + */ + readonly treePath: Path; + /** + * * A reference to the actual tree of write data. All methods are pass-through to the tree, but with the appropriate + * path prefixed. + * + * This lets us make cheap references to points in the tree for sync points without having to copy and maintain all of + * the data. + */ + readonly writeTree: WriteTree; +} diff --git a/node_modules/@firebase/database/dist/src/core/operation/AckUserWrite.d.ts b/node_modules/@firebase/database/dist/src/core/operation/AckUserWrite.d.ts new file mode 100644 index 0000000..a0cef5f --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/operation/AckUserWrite.d.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ImmutableTree } from '../util/ImmutableTree'; +import { Path } from '../util/Path'; +import { Operation, OperationType } from './Operation'; +export declare class AckUserWrite implements Operation { + /** @inheritDoc */ path: Path; + /** @inheritDoc */ affectedTree: ImmutableTree; + /** @inheritDoc */ revert: boolean; + /** @inheritDoc */ + type: OperationType; + /** @inheritDoc */ + source: import("./Operation").OperationSource; + /** + * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap. + */ + constructor( + /** @inheritDoc */ path: Path, + /** @inheritDoc */ affectedTree: ImmutableTree, + /** @inheritDoc */ revert: boolean); + operationForChild(childName: string): AckUserWrite; +} diff --git a/node_modules/@firebase/database/dist/src/core/operation/ListenComplete.d.ts b/node_modules/@firebase/database/dist/src/core/operation/ListenComplete.d.ts new file mode 100644 index 0000000..87157a2 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/operation/ListenComplete.d.ts @@ -0,0 +1,26 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Path } from '../util/Path'; +import { Operation, OperationSource, OperationType } from './Operation'; +export declare class ListenComplete implements Operation { + source: OperationSource; + path: Path; + /** @inheritDoc */ + type: OperationType; + constructor(source: OperationSource, path: Path); + operationForChild(childName: string): ListenComplete; +} diff --git a/node_modules/@firebase/database/dist/src/core/operation/Merge.d.ts b/node_modules/@firebase/database/dist/src/core/operation/Merge.d.ts new file mode 100644 index 0000000..3fbfbef --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/operation/Merge.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Node } from '../snap/Node'; +import { ImmutableTree } from '../util/ImmutableTree'; +import { Path } from '../util/Path'; +import { Operation, OperationSource, OperationType } from './Operation'; +export declare class Merge implements Operation { + /** @inheritDoc */ source: OperationSource; + /** @inheritDoc */ path: Path; + /** @inheritDoc */ children: ImmutableTree; + /** @inheritDoc */ + type: OperationType; + constructor( + /** @inheritDoc */ source: OperationSource, + /** @inheritDoc */ path: Path, + /** @inheritDoc */ children: ImmutableTree); + operationForChild(childName: string): Operation; + toString(): string; +} diff --git a/node_modules/@firebase/database/dist/src/core/operation/Operation.d.ts b/node_modules/@firebase/database/dist/src/core/operation/Operation.d.ts new file mode 100644 index 0000000..4e0bc44 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/operation/Operation.d.ts @@ -0,0 +1,45 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Path } from '../util/Path'; +/** + * + * @enum + */ +export declare enum OperationType { + OVERWRITE = 0, + MERGE = 1, + ACK_USER_WRITE = 2, + LISTEN_COMPLETE = 3 +} +/** + * @interface + */ +export interface Operation { + source: OperationSource; + type: OperationType; + path: Path; + operationForChild(childName: string): Operation | null; +} +export interface OperationSource { + fromUser: boolean; + fromServer: boolean; + queryId: string | null; + tagged: boolean; +} +export declare function newOperationSourceUser(): OperationSource; +export declare function newOperationSourceServer(): OperationSource; +export declare function newOperationSourceServerTaggedQuery(queryId: string): OperationSource; diff --git a/node_modules/@firebase/database/dist/src/core/operation/Overwrite.d.ts b/node_modules/@firebase/database/dist/src/core/operation/Overwrite.d.ts new file mode 100644 index 0000000..2494845 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/operation/Overwrite.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Node } from '../snap/Node'; +import { Path } from '../util/Path'; +import { Operation, OperationSource, OperationType } from './Operation'; +export declare class Overwrite implements Operation { + source: OperationSource; + path: Path; + snap: Node; + /** @inheritDoc */ + type: OperationType; + constructor(source: OperationSource, path: Path, snap: Node); + operationForChild(childName: string): Overwrite; +} diff --git a/node_modules/@firebase/database/dist/src/core/snap/ChildrenNode.d.ts b/node_modules/@firebase/database/dist/src/core/snap/ChildrenNode.d.ts new file mode 100644 index 0000000..0cc0519 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/snap/ChildrenNode.d.ts @@ -0,0 +1,112 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Path } from '../util/Path'; +import { SortedMap, SortedMapIterator } from '../util/SortedMap'; +import { Index } from './indexes/Index'; +import { IndexMap } from './IndexMap'; +import { NamedNode, Node } from './Node'; +export interface ChildrenNodeConstructor { + new (children_: SortedMap, priorityNode_: Node | null, indexMap_: IndexMap): ChildrenNode; + EMPTY_NODE: ChildrenNode; +} +/** + * ChildrenNode is a class for storing internal nodes in a DataSnapshot + * (i.e. nodes with children). It implements Node and stores the + * list of children in the children property, sorted by child name. + */ +export declare class ChildrenNode implements Node { + private readonly children_; + private readonly priorityNode_; + private indexMap_; + private lazyHash_; + static get EMPTY_NODE(): ChildrenNode; + /** + * @param children_ - List of children of this node.. + * @param priorityNode_ - The priority of this node (as a snapshot node). + */ + constructor(children_: SortedMap, priorityNode_: Node | null, indexMap_: IndexMap); + /** @inheritDoc */ + isLeafNode(): boolean; + /** @inheritDoc */ + getPriority(): Node; + /** @inheritDoc */ + updatePriority(newPriorityNode: Node): Node; + /** @inheritDoc */ + getImmediateChild(childName: string): Node; + /** @inheritDoc */ + getChild(path: Path): Node; + /** @inheritDoc */ + hasChild(childName: string): boolean; + /** @inheritDoc */ + updateImmediateChild(childName: string, newChildNode: Node): Node; + /** @inheritDoc */ + updateChild(path: Path, newChildNode: Node): Node; + /** @inheritDoc */ + isEmpty(): boolean; + /** @inheritDoc */ + numChildren(): number; + private static INTEGER_REGEXP_; + /** @inheritDoc */ + val(exportFormat?: boolean): object; + /** @inheritDoc */ + hash(): string; + /** @inheritDoc */ + getPredecessorChildName(childName: string, childNode: Node, index: Index): string; + getFirstChildName(indexDefinition: Index): string | null; + getFirstChild(indexDefinition: Index): NamedNode | null; + /** + * Given an index, return the key name of the largest value we have, according to that index + */ + getLastChildName(indexDefinition: Index): string | null; + getLastChild(indexDefinition: Index): NamedNode | null; + forEachChild(index: Index, action: (key: string, node: Node) => boolean | void): boolean; + getIterator(indexDefinition: Index): SortedMapIterator; + getIteratorFrom(startPost: NamedNode, indexDefinition: Index): SortedMapIterator; + getReverseIterator(indexDefinition: Index): SortedMapIterator; + getReverseIteratorFrom(endPost: NamedNode, indexDefinition: Index): SortedMapIterator; + compareTo(other: ChildrenNode): number; + withIndex(indexDefinition: Index): Node; + isIndexed(index: Index): boolean; + equals(other: Node): boolean; + /** + * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used + * instead. + * + */ + private resolveIndex_; +} +export declare class MaxNode extends ChildrenNode { + constructor(); + compareTo(other: Node): number; + equals(other: Node): boolean; + getPriority(): MaxNode; + getImmediateChild(childName: string): ChildrenNode; + isEmpty(): boolean; +} +/** + * Marker that will sort higher than any other snapshot. + */ +export declare const MAX_NODE: MaxNode; +/** + * Document NamedNode extensions + */ +declare module './Node' { + interface NamedNode { + MIN: NamedNode; + MAX: NamedNode; + } +} diff --git a/node_modules/@firebase/database/dist/src/core/snap/IndexMap.d.ts b/node_modules/@firebase/database/dist/src/core/snap/IndexMap.d.ts new file mode 100644 index 0000000..42e64ee --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/snap/IndexMap.d.ts @@ -0,0 +1,43 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SortedMap } from '../util/SortedMap'; +import { Index } from './indexes/Index'; +import { NamedNode, Node } from './Node'; +export declare class IndexMap { + private indexes_; + private indexSet_; + /** + * The default IndexMap for nodes without a priority + */ + static get Default(): IndexMap; + constructor(indexes_: { + [k: string]: SortedMap | /*FallbackType*/ object; + }, indexSet_: { + [k: string]: Index; + }); + get(indexKey: string): SortedMap | null; + hasIndex(indexDefinition: Index): boolean; + addIndex(indexDefinition: Index, existingChildren: SortedMap): IndexMap; + /** + * Ensure that this node is properly tracked in any indexes that we're maintaining + */ + addToIndexes(namedNode: NamedNode, existingChildren: SortedMap): IndexMap; + /** + * Create a new IndexMap instance with the given value removed + */ + removeFromIndexes(namedNode: NamedNode, existingChildren: SortedMap): IndexMap; +} diff --git a/node_modules/@firebase/database/dist/src/core/snap/LeafNode.d.ts b/node_modules/@firebase/database/dist/src/core/snap/LeafNode.d.ts new file mode 100644 index 0000000..6eecc9d --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/snap/LeafNode.d.ts @@ -0,0 +1,83 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Indexable } from '../util/misc'; +import { Path } from '../util/Path'; +import { ChildrenNodeConstructor } from './ChildrenNode'; +import { Index } from './indexes/Index'; +import { Node } from './Node'; +/** + * LeafNode is a class for storing leaf nodes in a DataSnapshot. It + * implements Node and stores the value of the node (a string, + * number, or boolean) accessible via getValue(). + */ +export declare class LeafNode implements Node { + private readonly value_; + private priorityNode_; + static set __childrenNodeConstructor(val: ChildrenNodeConstructor); + static get __childrenNodeConstructor(): ChildrenNodeConstructor; + /** + * The sort order for comparing leaf nodes of different types. If two leaf nodes have + * the same type, the comparison falls back to their value + */ + static VALUE_TYPE_ORDER: string[]; + private lazyHash_; + /** + * @param value_ - The value to store in this leaf node. The object type is + * possible in the event of a deferred value + * @param priorityNode_ - The priority of this node. + */ + constructor(value_: string | number | boolean | Indexable, priorityNode_?: Node); + /** @inheritDoc */ + isLeafNode(): boolean; + /** @inheritDoc */ + getPriority(): Node; + /** @inheritDoc */ + updatePriority(newPriorityNode: Node): Node; + /** @inheritDoc */ + getImmediateChild(childName: string): Node; + /** @inheritDoc */ + getChild(path: Path): Node; + hasChild(): boolean; + /** @inheritDoc */ + getPredecessorChildName(childName: string, childNode: Node): null; + /** @inheritDoc */ + updateImmediateChild(childName: string, newChildNode: Node): Node; + /** @inheritDoc */ + updateChild(path: Path, newChildNode: Node): Node; + /** @inheritDoc */ + isEmpty(): boolean; + /** @inheritDoc */ + numChildren(): number; + /** @inheritDoc */ + forEachChild(index: Index, action: (s: string, n: Node) => void): boolean; + val(exportFormat?: boolean): {}; + /** @inheritDoc */ + hash(): string; + /** + * Returns the value of the leaf node. + * @returns The value of the node. + */ + getValue(): Indexable | string | number | boolean; + compareTo(other: Node): number; + /** + * Comparison specifically for two leaf nodes + */ + private compareToLeafNode_; + withIndex(): Node; + isIndexed(): boolean; + equals(other: Node): boolean; +} diff --git a/node_modules/@firebase/database/dist/src/core/snap/Node.d.ts b/node_modules/@firebase/database/dist/src/core/snap/Node.d.ts new file mode 100644 index 0000000..99d379c --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/snap/Node.d.ts @@ -0,0 +1,126 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Path } from '../util/Path'; +import { Index } from './indexes/Index'; +/** + * Node is an interface defining the common functionality for nodes in + * a DataSnapshot. + * + * @interface + */ +export interface Node { + /** + * Whether this node is a leaf node. + * @returns Whether this is a leaf node. + */ + isLeafNode(): boolean; + /** + * Gets the priority of the node. + * @returns The priority of the node. + */ + getPriority(): Node; + /** + * Returns a duplicate node with the new priority. + * @param newPriorityNode - New priority to set for the node. + * @returns Node with new priority. + */ + updatePriority(newPriorityNode: Node): Node; + /** + * Returns the specified immediate child, or null if it doesn't exist. + * @param childName - The name of the child to retrieve. + * @returns The retrieved child, or an empty node. + */ + getImmediateChild(childName: string): Node; + /** + * Returns a child by path, or null if it doesn't exist. + * @param path - The path of the child to retrieve. + * @returns The retrieved child or an empty node. + */ + getChild(path: Path): Node; + /** + * Returns the name of the child immediately prior to the specified childNode, or null. + * @param childName - The name of the child to find the predecessor of. + * @param childNode - The node to find the predecessor of. + * @param index - The index to use to determine the predecessor + * @returns The name of the predecessor child, or null if childNode is the first child. + */ + getPredecessorChildName(childName: string, childNode: Node, index: Index): string | null; + /** + * Returns a duplicate node, with the specified immediate child updated. + * Any value in the node will be removed. + * @param childName - The name of the child to update. + * @param newChildNode - The new child node + * @returns The updated node. + */ + updateImmediateChild(childName: string, newChildNode: Node): Node; + /** + * Returns a duplicate node, with the specified child updated. Any value will + * be removed. + * @param path - The path of the child to update. + * @param newChildNode - The new child node, which may be an empty node + * @returns The updated node. + */ + updateChild(path: Path, newChildNode: Node): Node; + /** + * True if the immediate child specified exists + */ + hasChild(childName: string): boolean; + /** + * @returns True if this node has no value or children. + */ + isEmpty(): boolean; + /** + * @returns The number of children of this node. + */ + numChildren(): number; + /** + * Calls action for each child. + * @param action - Action to be called for + * each child. It's passed the child name and the child node. + * @returns The first truthy value return by action, or the last falsey one + */ + forEachChild(index: Index, action: (a: string, b: Node) => void): unknown; + /** + * @param exportFormat - True for export format (also wire protocol format). + * @returns Value of this node as JSON. + */ + val(exportFormat?: boolean): unknown; + /** + * @returns hash representing the node contents. + */ + hash(): string; + /** + * @param other - Another node + * @returns -1 for less than, 0 for equal, 1 for greater than other + */ + compareTo(other: Node): number; + /** + * @returns Whether or not this snapshot equals other + */ + equals(other: Node): boolean; + /** + * @returns This node, with the specified index now available + */ + withIndex(indexDefinition: Index): Node; + isIndexed(indexDefinition: Index): boolean; +} +export declare class NamedNode { + name: string; + node: Node; + constructor(name: string, node: Node); + static Wrap(name: string, node: Node): NamedNode; +} diff --git a/node_modules/@firebase/database/dist/src/core/snap/childSet.d.ts b/node_modules/@firebase/database/dist/src/core/snap/childSet.d.ts new file mode 100644 index 0000000..42ce33a --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/snap/childSet.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SortedMap } from '../util/SortedMap'; +import { NamedNode } from './Node'; +/** + * Takes a list of child nodes and constructs a SortedSet using the given comparison + * function + * + * Uses the algorithm described in the paper linked here: + * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458 + * + * @param childList - Unsorted list of children + * @param cmp - The comparison method to be used + * @param keyFn - An optional function to extract K from a node wrapper, if K's + * type is not NamedNode + * @param mapSortFn - An optional override for comparator used by the generated sorted map + */ +export declare const buildChildSet: (childList: NamedNode[], cmp: (a: NamedNode, b: NamedNode) => number, keyFn?: (a: NamedNode) => K, mapSortFn?: (a: K, b: K) => number) => SortedMap; diff --git a/node_modules/@firebase/database/dist/src/core/snap/comparators.d.ts b/node_modules/@firebase/database/dist/src/core/snap/comparators.d.ts new file mode 100644 index 0000000..a39e3aa --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/snap/comparators.d.ts @@ -0,0 +1,19 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NamedNode } from './Node'; +export declare function NAME_ONLY_COMPARATOR(left: NamedNode, right: NamedNode): number; +export declare function NAME_COMPARATOR(left: string, right: string): number; diff --git a/node_modules/@firebase/database/dist/src/core/snap/indexes/Index.d.ts b/node_modules/@firebase/database/dist/src/core/snap/indexes/Index.d.ts new file mode 100644 index 0000000..04c1fa9 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/snap/indexes/Index.d.ts @@ -0,0 +1,50 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Comparator } from '../../util/SortedMap'; +import { Node, NamedNode } from '../Node'; +export declare abstract class Index { + abstract compare(a: NamedNode, b: NamedNode): number; + abstract isDefinedOn(node: Node): boolean; + /** + * @returns A standalone comparison function for + * this index + */ + getCompare(): Comparator; + /** + * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different, + * it's possible that the changes are isolated to parts of the snapshot that are not indexed. + * + * + * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode + */ + indexedValueChanged(oldNode: Node, newNode: Node): boolean; + /** + * @returns a node wrapper that will sort equal to or less than + * any other node wrapper, using this index + */ + minPost(): NamedNode; + /** + * @returns a node wrapper that will sort greater than or equal to + * any other node wrapper, using this index + */ + abstract maxPost(): NamedNode; + abstract makePost(indexValue: unknown, name: string): NamedNode; + /** + * @returns String representation for inclusion in a query spec + */ + abstract toString(): string; +} diff --git a/node_modules/@firebase/database/dist/src/core/snap/indexes/KeyIndex.d.ts b/node_modules/@firebase/database/dist/src/core/snap/indexes/KeyIndex.d.ts new file mode 100644 index 0000000..dc4c04f --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/snap/indexes/KeyIndex.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ChildrenNode } from '../ChildrenNode'; +import { Node, NamedNode } from '../Node'; +import { Index } from './Index'; +export declare class KeyIndex extends Index { + static get __EMPTY_NODE(): ChildrenNode; + static set __EMPTY_NODE(val: ChildrenNode); + compare(a: NamedNode, b: NamedNode): number; + isDefinedOn(node: Node): boolean; + indexedValueChanged(oldNode: Node, newNode: Node): boolean; + minPost(): any; + maxPost(): NamedNode; + makePost(indexValue: string, name: string): NamedNode; + /** + * @returns String representation for inclusion in a query spec + */ + toString(): string; +} +export declare const KEY_INDEX: KeyIndex; diff --git a/node_modules/@firebase/database/dist/src/core/snap/indexes/PathIndex.d.ts b/node_modules/@firebase/database/dist/src/core/snap/indexes/PathIndex.d.ts new file mode 100644 index 0000000..65af086 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/snap/indexes/PathIndex.d.ts @@ -0,0 +1,29 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Path } from '../../util/Path'; +import { NamedNode, Node } from '../Node'; +import { Index } from './Index'; +export declare class PathIndex extends Index { + private indexPath_; + constructor(indexPath_: Path); + protected extractChild(snap: Node): Node; + isDefinedOn(node: Node): boolean; + compare(a: NamedNode, b: NamedNode): number; + makePost(indexValue: object, name: string): NamedNode; + maxPost(): NamedNode; + toString(): string; +} diff --git a/node_modules/@firebase/database/dist/src/core/snap/indexes/PriorityIndex.d.ts b/node_modules/@firebase/database/dist/src/core/snap/indexes/PriorityIndex.d.ts new file mode 100644 index 0000000..910d780 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/snap/indexes/PriorityIndex.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NamedNode, Node } from '../Node'; +import { Index } from './Index'; +export declare function setNodeFromJSON(val: (a: unknown) => Node): void; +export declare function setMaxNode(val: Node): void; +export declare class PriorityIndex extends Index { + compare(a: NamedNode, b: NamedNode): number; + isDefinedOn(node: Node): boolean; + indexedValueChanged(oldNode: Node, newNode: Node): boolean; + minPost(): NamedNode; + maxPost(): NamedNode; + makePost(indexValue: unknown, name: string): NamedNode; + /** + * @returns String representation for inclusion in a query spec + */ + toString(): string; +} +export declare const PRIORITY_INDEX: PriorityIndex; diff --git a/node_modules/@firebase/database/dist/src/core/snap/indexes/ValueIndex.d.ts b/node_modules/@firebase/database/dist/src/core/snap/indexes/ValueIndex.d.ts new file mode 100644 index 0000000..6b801a9 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/snap/indexes/ValueIndex.d.ts @@ -0,0 +1,31 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NamedNode, Node } from '../Node'; +import { Index } from './Index'; +export declare class ValueIndex extends Index { + compare(a: NamedNode, b: NamedNode): number; + isDefinedOn(node: Node): boolean; + indexedValueChanged(oldNode: Node, newNode: Node): boolean; + minPost(): NamedNode; + maxPost(): NamedNode; + makePost(indexValue: object, name: string): NamedNode; + /** + * @returns String representation for inclusion in a query spec + */ + toString(): string; +} +export declare const VALUE_INDEX: ValueIndex; diff --git a/node_modules/@firebase/database/dist/src/core/snap/nodeFromJSON.d.ts b/node_modules/@firebase/database/dist/src/core/snap/nodeFromJSON.d.ts new file mode 100644 index 0000000..a20804b --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/snap/nodeFromJSON.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Node } from './Node'; +/** + * Constructs a snapshot node representing the passed JSON and returns it. + * @param json - JSON to create a node for. + * @param priority - Optional priority to use. This will be ignored if the + * passed JSON contains a .priority property. + */ +export declare function nodeFromJSON(json: unknown | null, priority?: unknown): Node; diff --git a/node_modules/@firebase/database/dist/src/core/snap/snap.d.ts b/node_modules/@firebase/database/dist/src/core/snap/snap.d.ts new file mode 100644 index 0000000..579a2ed --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/snap/snap.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Node } from './Node'; +export declare function setMaxNode(val: Node): void; +export declare const priorityHashText: (priority: string | number) => string; +/** + * Validates that a priority snapshot Node is valid. + */ +export declare const validatePriorityNode: (priorityNode: Node) => void; diff --git a/node_modules/@firebase/database/dist/src/core/stats/StatsCollection.d.ts b/node_modules/@firebase/database/dist/src/core/stats/StatsCollection.d.ts new file mode 100644 index 0000000..0179d61 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/stats/StatsCollection.d.ts @@ -0,0 +1,26 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Tracks a collection of stats. + */ +export declare class StatsCollection { + private counters_; + incrementCounter(name: string, amount?: number): void; + get(): { + [k: string]: number; + }; +} diff --git a/node_modules/@firebase/database/dist/src/core/stats/StatsListener.d.ts b/node_modules/@firebase/database/dist/src/core/stats/StatsListener.d.ts new file mode 100644 index 0000000..cf6d906 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/stats/StatsListener.d.ts @@ -0,0 +1,30 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { StatsCollection } from './StatsCollection'; +/** + * Returns the delta from the previous call to get stats. + * + * @param collection_ - The collection to "listen" to. + */ +export declare class StatsListener { + private collection_; + private last_; + constructor(collection_: StatsCollection); + get(): { + [k: string]: number; + }; +} diff --git a/node_modules/@firebase/database/dist/src/core/stats/StatsManager.d.ts b/node_modules/@firebase/database/dist/src/core/stats/StatsManager.d.ts new file mode 100644 index 0000000..7c02ab4 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/stats/StatsManager.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { RepoInfo } from '../RepoInfo'; +import { StatsCollection } from './StatsCollection'; +export declare function statsManagerGetCollection(repoInfo: RepoInfo): StatsCollection; +export declare function statsManagerGetOrCreateReporter(repoInfo: RepoInfo, creatorFunction: () => T): T; diff --git a/node_modules/@firebase/database/dist/src/core/stats/StatsReporter.d.ts b/node_modules/@firebase/database/dist/src/core/stats/StatsReporter.d.ts new file mode 100644 index 0000000..402b43b --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/stats/StatsReporter.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ServerActions } from '../ServerActions'; +import { StatsCollection } from './StatsCollection'; +export declare class StatsReporter { + private server_; + private statsListener_; + statsToReport_: { + [k: string]: boolean; + }; + constructor(collection: StatsCollection, server_: ServerActions); + private reportStats_; +} +export declare function statsReporterIncludeStat(reporter: StatsReporter, stat: string): void; diff --git a/node_modules/@firebase/database/dist/src/core/storage/DOMStorageWrapper.d.ts b/node_modules/@firebase/database/dist/src/core/storage/DOMStorageWrapper.d.ts new file mode 100644 index 0000000..662d8f5 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/storage/DOMStorageWrapper.d.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Wraps a DOM Storage object and: + * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types. + * - prefixes names with "firebase:" to avoid collisions with app data. + * + * We automatically (see storage.js) create two such wrappers, one for sessionStorage, + * and one for localStorage. + * + */ +export declare class DOMStorageWrapper { + private domStorage_; + private prefix_; + /** + * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage) + */ + constructor(domStorage_: Storage); + /** + * @param key - The key to save the value under + * @param value - The value being stored, or null to remove the key. + */ + set(key: string, value: unknown | null): void; + /** + * @returns The value that was stored under this key, or null + */ + get(key: string): unknown; + remove(key: string): void; + isInMemoryStorage: boolean; + prefixedName_(name: string): string; + toString(): string; +} diff --git a/node_modules/@firebase/database/dist/src/core/storage/MemoryStorage.d.ts b/node_modules/@firebase/database/dist/src/core/storage/MemoryStorage.d.ts new file mode 100644 index 0000000..08dd04e --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/storage/MemoryStorage.d.ts @@ -0,0 +1,27 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory storage implementation that matches the API of DOMStorageWrapper + * (TODO: create interface for both to implement). + */ +export declare class MemoryStorage { + private cache_; + set(key: string, value: unknown | null): void; + get(key: string): unknown; + remove(key: string): void; + isInMemoryStorage: boolean; +} diff --git a/node_modules/@firebase/database/dist/src/core/storage/storage.d.ts b/node_modules/@firebase/database/dist/src/core/storage/storage.d.ts new file mode 100644 index 0000000..52b3579 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/storage/storage.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DOMStorageWrapper } from './DOMStorageWrapper'; +import { MemoryStorage } from './MemoryStorage'; +/** A storage object that lasts across sessions */ +export declare const PersistentStorage: DOMStorageWrapper | MemoryStorage; +/** A storage object that only lasts one session */ +export declare const SessionStorage: DOMStorageWrapper | MemoryStorage; diff --git a/node_modules/@firebase/database/dist/src/core/util/EventEmitter.d.ts b/node_modules/@firebase/database/dist/src/core/util/EventEmitter.d.ts new file mode 100644 index 0000000..0fd09f9 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/util/EventEmitter.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Base class to be used if you want to emit events. Call the constructor with + * the set of allowed event names. + */ +export declare abstract class EventEmitter { + private allowedEvents_; + private listeners_; + constructor(allowedEvents_: string[]); + /** + * To be overridden by derived classes in order to fire an initial event when + * somebody subscribes for data. + * + * @returns {Array.<*>} Array of parameters to trigger initial event with. + */ + abstract getInitialEvent(eventType: string): unknown[]; + /** + * To be called by derived classes to trigger events. + */ + protected trigger(eventType: string, ...varArgs: unknown[]): void; + on(eventType: string, callback: (a: unknown) => void, context: unknown): void; + off(eventType: string, callback: (a: unknown) => void, context: unknown): void; + private validateEventType_; +} diff --git a/node_modules/@firebase/database/dist/src/core/util/ImmutableTree.d.ts b/node_modules/@firebase/database/dist/src/core/util/ImmutableTree.d.ts new file mode 100644 index 0000000..8a85ce6 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/util/ImmutableTree.d.ts @@ -0,0 +1,117 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Path } from './Path'; +import { SortedMap } from './SortedMap'; +/** + * A tree with immutable elements. + */ +export declare class ImmutableTree { + readonly value: T | null; + readonly children: SortedMap>; + static fromObject(obj: { + [k: string]: T; + }): ImmutableTree; + constructor(value: T | null, children?: SortedMap>); + /** + * True if the value is empty and there are no children + */ + isEmpty(): boolean; + /** + * Given a path and predicate, return the first node and the path to that node + * where the predicate returns true. + * + * TODO Do a perf test -- If we're creating a bunch of `{path: value:}` + * objects on the way back out, it may be better to pass down a pathSoFar obj. + * + * @param relativePath - The remainder of the path + * @param predicate - The predicate to satisfy to return a node + */ + findRootMostMatchingPathAndValue(relativePath: Path, predicate: (a: T) => boolean): { + path: Path; + value: T; + } | null; + /** + * Find, if it exists, the shortest subpath of the given path that points a defined + * value in the tree + */ + findRootMostValueAndPath(relativePath: Path): { + path: Path; + value: T; + } | null; + /** + * @returns The subtree at the given path + */ + subtree(relativePath: Path): ImmutableTree; + /** + * Sets a value at the specified path. + * + * @param relativePath - Path to set value at. + * @param toSet - Value to set. + * @returns Resulting tree. + */ + set(relativePath: Path, toSet: T | null): ImmutableTree; + /** + * Removes the value at the specified path. + * + * @param relativePath - Path to value to remove. + * @returns Resulting tree. + */ + remove(relativePath: Path): ImmutableTree; + /** + * Gets a value from the tree. + * + * @param relativePath - Path to get value for. + * @returns Value at path, or null. + */ + get(relativePath: Path): T | null; + /** + * Replace the subtree at the specified path with the given new tree. + * + * @param relativePath - Path to replace subtree for. + * @param newTree - New tree. + * @returns Resulting tree. + */ + setTree(relativePath: Path, newTree: ImmutableTree): ImmutableTree; + /** + * Performs a depth first fold on this tree. Transforms a tree into a single + * value, given a function that operates on the path to a node, an optional + * current value, and a map of child names to folded subtrees + */ + fold(fn: (path: Path, value: T, children: { + [k: string]: V; + }) => V): V; + /** + * Recursive helper for public-facing fold() method + */ + private fold_; + /** + * Find the first matching value on the given path. Return the result of applying f to it. + */ + findOnPath(path: Path, f: (path: Path, value: T) => V | null): V | null; + private findOnPath_; + foreachOnPath(path: Path, f: (path: Path, value: T) => void): ImmutableTree; + private foreachOnPath_; + /** + * Calls the given function for each node in the tree that has a value. + * + * @param f - A function to be called with the path from the root of the tree to + * a node, and the value at that node. Called in depth-first order. + */ + foreach(f: (path: Path, value: T) => void): void; + private foreach_; + foreachChild(f: (name: string, value: T) => void): void; +} diff --git a/node_modules/@firebase/database/dist/src/core/util/NextPushId.d.ts b/node_modules/@firebase/database/dist/src/core/util/NextPushId.d.ts new file mode 100644 index 0000000..9ad8425 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/util/NextPushId.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Fancy ID generator that creates 20-character string identifiers with the + * following properties: + * + * 1. They're based on timestamp so that they sort *after* any existing ids. + * 2. They contain 72-bits of random data after the timestamp so that IDs won't + * collide with other clients' IDs. + * 3. They sort *lexicographically* (so the timestamp is converted to characters + * that will sort properly). + * 4. They're monotonically increasing. Even if you generate more than one in + * the same timestamp, the latter ones will sort after the former ones. We do + * this by using the previous random bits but "incrementing" them by 1 (only + * in the case of a timestamp collision). + */ +export declare const nextPushId: (now: number) => string; +export declare const successor: (key: string) => string; +export declare const predecessor: (key: string) => string; diff --git a/node_modules/@firebase/database/dist/src/core/util/OnlineMonitor.d.ts b/node_modules/@firebase/database/dist/src/core/util/OnlineMonitor.d.ts new file mode 100644 index 0000000..bed347b --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/util/OnlineMonitor.d.ts @@ -0,0 +1,31 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { EventEmitter } from './EventEmitter'; +/** + * Monitors online state (as reported by window.online/offline events). + * + * The expectation is that this could have many false positives (thinks we are online + * when we're not), but no false negatives. So we can safely use it to determine when + * we definitely cannot reach the internet. + */ +export declare class OnlineMonitor extends EventEmitter { + private online_; + static getInstance(): OnlineMonitor; + constructor(); + getInitialEvent(eventType: string): boolean[]; + currentlyOnline(): boolean; +} diff --git a/node_modules/@firebase/database/dist/src/core/util/Path.d.ts b/node_modules/@firebase/database/dist/src/core/util/Path.d.ts new file mode 100644 index 0000000..2f73b36 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/util/Path.d.ts @@ -0,0 +1,94 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a parsed path. It's immutable so that you + * can pass them around to other functions without worrying about them changing + * it. + */ +export declare class Path { + pieces_: string[]; + pieceNum_: number; + /** + * @param pathOrString - Path string to parse, or another path, or the raw + * tokens array + */ + constructor(pathOrString: string | string[], pieceNum?: number); + toString(): string; +} +export declare function newEmptyPath(): Path; +export declare function pathGetFront(path: Path): string | null; +/** + * @returns The number of segments in this path + */ +export declare function pathGetLength(path: Path): number; +export declare function pathPopFront(path: Path): Path; +export declare function pathGetBack(path: Path): string | null; +export declare function pathToUrlEncodedString(path: Path): string; +/** + * Shallow copy of the parts of the path. + * + */ +export declare function pathSlice(path: Path, begin?: number): string[]; +export declare function pathParent(path: Path): Path | null; +export declare function pathChild(path: Path, childPathObj: string | Path): Path; +/** + * @returns True if there are no segments in this path + */ +export declare function pathIsEmpty(path: Path): boolean; +/** + * @returns The path from outerPath to innerPath + */ +export declare function newRelativePath(outerPath: Path, innerPath: Path): Path; +/** + * @returns -1, 0, 1 if left is less, equal, or greater than the right. + */ +export declare function pathCompare(left: Path, right: Path): number; +/** + * @returns true if paths are the same. + */ +export declare function pathEquals(path: Path, other: Path): boolean; +/** + * @returns True if this path is a parent of (or the same as) other + */ +export declare function pathContains(path: Path, other: Path): boolean; +/** + * Dynamic (mutable) path used to count path lengths. + * + * This class is used to efficiently check paths for valid + * length (in UTF8 bytes) and depth (used in path validation). + * + * Throws Error exception if path is ever invalid. + * + * The definition of a path always begins with '/'. + */ +export declare class ValidationPath { + errorPrefix_: string; + parts_: string[]; + /** Initialize to number of '/' chars needed in path. */ + byteLength_: number; + /** + * @param path - Initial Path. + * @param errorPrefix_ - Prefix for any error messages. + */ + constructor(path: Path, errorPrefix_: string); +} +export declare function validationPathPush(validationPath: ValidationPath, child: string): void; +export declare function validationPathPop(validationPath: ValidationPath): void; +/** + * String for use in error messages - uses '.' notation for path. + */ +export declare function validationPathToErrorString(validationPath: ValidationPath): string; diff --git a/node_modules/@firebase/database/dist/src/core/util/ServerValues.d.ts b/node_modules/@firebase/database/dist/src/core/util/ServerValues.d.ts new file mode 100644 index 0000000..916cf14 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/util/ServerValues.d.ts @@ -0,0 +1,56 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Node } from '../snap/Node'; +import { SyncTree } from '../SyncTree'; +import { Indexable } from './misc'; +import { Path } from './Path'; +interface ValueProvider { + getImmediateChild(childName: string): ValueProvider; + node(): Node; +} +/** + * Generate placeholders for deferred values. + */ +export declare const generateWithValues: (values: { + [k: string]: unknown; +} | null) => { + [k: string]: unknown; +}; +/** + * Value to use when firing local events. When writing server values, fire + * local events with an approximate value, otherwise return value as-is. + */ +export declare const resolveDeferredLeafValue: (value: { + [k: string]: unknown; +} | string | number | boolean, existingVal: ValueProvider, serverValues: { + [k: string]: unknown; +}) => string | number | boolean; +/** + * Recursively replace all deferred values and priorities in the tree with the + * specified generated replacement values. + * @param path - path to which write is relative + * @param node - new data written at path + * @param syncTree - current data + */ +export declare const resolveDeferredValueTree: (path: Path, node: Node, syncTree: SyncTree, serverValues: Indexable) => Node; +/** + * Recursively replace all deferred values and priorities in the node with the + * specified generated replacement values. If there are no server values in the node, + * it'll be returned as-is. + */ +export declare const resolveDeferredValueSnapshot: (node: Node, existing: Node, serverValues: Indexable) => Node; +export {}; diff --git a/node_modules/@firebase/database/dist/src/core/util/SortedMap.d.ts b/node_modules/@firebase/database/dist/src/core/util/SortedMap.d.ts new file mode 100644 index 0000000..09d3aa6 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/util/SortedMap.d.ts @@ -0,0 +1,324 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview Implementation of an immutable SortedMap using a Left-leaning + * Red-Black Tree, adapted from the implementation in Mugs + * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen + * (mads379\@gmail.com). + * + * Original paper on Left-leaning Red-Black Trees: + * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf + * + * Invariant 1: No red node has a red child + * Invariant 2: Every leaf path has the same number of black nodes + * Invariant 3: Only the left child can be red (left leaning) + */ +export type Comparator = (key1: K, key2: K) => number; +/** + * An iterator over an LLRBNode. + */ +export declare class SortedMapIterator { + private isReverse_; + private resultGenerator_; + private nodeStack_; + /** + * @param node - Node to iterate. + * @param isReverse_ - Whether or not to iterate in reverse + */ + constructor(node: LLRBNode | LLRBEmptyNode, startKey: K | null, comparator: Comparator, isReverse_: boolean, resultGenerator_?: ((k: K, v: V) => T) | null); + getNext(): T; + hasNext(): boolean; + peek(): T; +} +/** + * Represents a node in a Left-leaning Red-Black tree. + */ +export declare class LLRBNode { + key: K; + value: V; + color: boolean; + left: LLRBNode | LLRBEmptyNode; + right: LLRBNode | LLRBEmptyNode; + /** + * @param key - Key associated with this node. + * @param value - Value associated with this node. + * @param color - Whether this node is red. + * @param left - Left child. + * @param right - Right child. + */ + constructor(key: K, value: V, color: boolean | null, left?: LLRBNode | LLRBEmptyNode | null, right?: LLRBNode | LLRBEmptyNode | null); + static RED: boolean; + static BLACK: boolean; + /** + * Returns a copy of the current node, optionally replacing pieces of it. + * + * @param key - New key for the node, or null. + * @param value - New value for the node, or null. + * @param color - New color for the node, or null. + * @param left - New left child for the node, or null. + * @param right - New right child for the node, or null. + * @returns The node copy. + */ + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBNode; + /** + * @returns The total number of nodes in the tree. + */ + count(): number; + /** + * @returns True if the tree is empty. + */ + isEmpty(): boolean; + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action: (k: K, v: V) => unknown): boolean; + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action: (k: K, v: V) => void): boolean; + /** + * @returns The minimum node in the tree. + */ + private min_; + /** + * @returns The maximum key in the tree. + */ + minKey(): K; + /** + * @returns The maximum key in the tree. + */ + maxKey(): K; + /** + * @param key - Key to insert. + * @param value - Value to insert. + * @param comparator - Comparator. + * @returns New tree, with the key/value added. + */ + insert(key: K, value: V, comparator: Comparator): LLRBNode; + /** + * @returns New tree, with the minimum key removed. + */ + private removeMin_; + /** + * @param key - The key of the item to remove. + * @param comparator - Comparator. + * @returns New tree, with the specified item removed. + */ + remove(key: K, comparator: Comparator): LLRBNode | LLRBEmptyNode; + /** + * @returns Whether this is a RED node. + */ + isRed_(): boolean; + /** + * @returns New tree after performing any needed rotations. + */ + private fixUp_; + /** + * @returns New tree, after moveRedLeft. + */ + private moveRedLeft_; + /** + * @returns New tree, after moveRedRight. + */ + private moveRedRight_; + /** + * @returns New tree, after rotateLeft. + */ + private rotateLeft_; + /** + * @returns New tree, after rotateRight. + */ + private rotateRight_; + /** + * @returns Newt ree, after colorFlip. + */ + private colorFlip_; + /** + * For testing. + * + * @returns True if all is well. + */ + private checkMaxDepth_; + check_(): number; +} +/** + * Represents an empty node (a leaf node in the Red-Black Tree). + */ +export declare class LLRBEmptyNode { + key: K; + value: V; + left: LLRBNode | LLRBEmptyNode; + right: LLRBNode | LLRBEmptyNode; + color: boolean; + /** + * Returns a copy of the current node. + * + * @returns The node copy. + */ + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBEmptyNode; + /** + * Returns a copy of the tree, with the specified key/value added. + * + * @param key - Key to be added. + * @param value - Value to be added. + * @param comparator - Comparator. + * @returns New tree, with item added. + */ + insert(key: K, value: V, comparator: Comparator): LLRBNode; + /** + * Returns a copy of the tree, with the specified key removed. + * + * @param key - The key to remove. + * @param comparator - Comparator. + * @returns New tree, with item removed. + */ + remove(key: K, comparator: Comparator): LLRBEmptyNode; + /** + * @returns The total number of nodes in the tree. + */ + count(): number; + /** + * @returns True if the tree is empty. + */ + isEmpty(): boolean; + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + inorderTraversal(action: (k: K, v: V) => unknown): boolean; + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action: (k: K, v: V) => void): boolean; + minKey(): null; + maxKey(): null; + check_(): number; + /** + * @returns Whether this node is red. + */ + isRed_(): boolean; +} +/** + * An immutable sorted map implementation, based on a Left-leaning Red-Black + * tree. + */ +export declare class SortedMap { + private comparator_; + private root_; + /** + * Always use the same empty node, to reduce memory. + */ + static EMPTY_NODE: LLRBEmptyNode; + /** + * @param comparator_ - Key comparator. + * @param root_ - Optional root node for the map. + */ + constructor(comparator_: Comparator, root_?: LLRBNode | LLRBEmptyNode); + /** + * Returns a copy of the map, with the specified key/value added or replaced. + * (TODO: We should perhaps rename this method to 'put') + * + * @param key - Key to be added. + * @param value - Value to be added. + * @returns New map, with item added. + */ + insert(key: K, value: V): SortedMap; + /** + * Returns a copy of the map, with the specified key removed. + * + * @param key - The key to remove. + * @returns New map, with item removed. + */ + remove(key: K): SortedMap; + /** + * Returns the value of the node with the given key, or null. + * + * @param key - The key to look up. + * @returns The value of the node with the given key, or null if the + * key doesn't exist. + */ + get(key: K): V | null; + /** + * Returns the key of the item *before* the specified key, or null if key is the first item. + * @param key - The key to find the predecessor of + * @returns The predecessor key. + */ + getPredecessorKey(key: K): K | null; + /** + * @returns True if the map is empty. + */ + isEmpty(): boolean; + /** + * @returns The total number of nodes in the map. + */ + count(): number; + /** + * @returns The minimum key in the map. + */ + minKey(): K | null; + /** + * @returns The maximum key in the map. + */ + maxKey(): K | null; + /** + * Traverses the map in key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action: (k: K, v: V) => unknown): boolean; + /** + * Traverses the map in reverse key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns True if the traversal was aborted. + */ + reverseTraversal(action: (k: K, v: V) => void): boolean; + /** + * Returns an iterator over the SortedMap. + * @returns The iterator. + */ + getIterator(resultGenerator?: (k: K, v: V) => T): SortedMapIterator; + getIteratorFrom(key: K, resultGenerator?: (k: K, v: V) => T): SortedMapIterator; + getReverseIteratorFrom(key: K, resultGenerator?: (k: K, v: V) => T): SortedMapIterator; + getReverseIterator(resultGenerator?: (k: K, v: V) => T): SortedMapIterator; +} diff --git a/node_modules/@firebase/database/dist/src/core/util/Tree.d.ts b/node_modules/@firebase/database/dist/src/core/util/Tree.d.ts new file mode 100644 index 0000000..3bcdc27 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/util/Tree.d.ts @@ -0,0 +1,105 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Path } from './Path'; +/** + * Node in a Tree. + */ +export interface TreeNode { + children: Record>; + childCount: number; + value?: T; +} +/** + * A light-weight tree, traversable by path. Nodes can have both values and children. + * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty + * children. + */ +export declare class Tree { + readonly name: string; + readonly parent: Tree | null; + node: TreeNode; + /** + * @param name - Optional name of the node. + * @param parent - Optional parent node. + * @param node - Optional node to wrap. + */ + constructor(name?: string, parent?: Tree | null, node?: TreeNode); +} +/** + * Returns a sub-Tree for the given path. + * + * @param pathObj - Path to look up. + * @returns Tree for path. + */ +export declare function treeSubTree(tree: Tree, pathObj: string | Path): Tree; +/** + * Returns the data associated with this tree node. + * + * @returns The data or null if no data exists. + */ +export declare function treeGetValue(tree: Tree): T | undefined; +/** + * Sets data to this tree node. + * + * @param value - Value to set. + */ +export declare function treeSetValue(tree: Tree, value: T | undefined): void; +/** + * @returns Whether the tree has any children. + */ +export declare function treeHasChildren(tree: Tree): boolean; +/** + * @returns Whether the tree is empty (no value or children). + */ +export declare function treeIsEmpty(tree: Tree): boolean; +/** + * Calls action for each child of this tree node. + * + * @param action - Action to be called for each child. + */ +export declare function treeForEachChild(tree: Tree, action: (tree: Tree) => void): void; +/** + * Does a depth-first traversal of this node's descendants, calling action for each one. + * + * @param action - Action to be called for each child. + * @param includeSelf - Whether to call action on this node as well. Defaults to + * false. + * @param childrenFirst - Whether to call action on children before calling it on + * parent. + */ +export declare function treeForEachDescendant(tree: Tree, action: (tree: Tree) => void, includeSelf?: boolean, childrenFirst?: boolean): void; +/** + * Calls action on each ancestor node. + * + * @param action - Action to be called on each parent; return + * true to abort. + * @param includeSelf - Whether to call action on this node as well. + * @returns true if the action callback returned true. + */ +export declare function treeForEachAncestor(tree: Tree, action: (tree: Tree) => unknown, includeSelf?: boolean): boolean; +/** + * Does a depth-first traversal of this node's descendants. When a descendant with a value + * is found, action is called on it and traversal does not continue inside the node. + * Action is *not* called on this node. + * + * @param action - Action to be called for each child. + */ +export declare function treeForEachImmediateDescendantWithValue(tree: Tree, action: (tree: Tree) => void): void; +/** + * @returns The path of this tree node, as a Path. + */ +export declare function treeGetPath(tree: Tree): any; diff --git a/node_modules/@firebase/database/dist/src/core/util/VisibilityMonitor.d.ts b/node_modules/@firebase/database/dist/src/core/util/VisibilityMonitor.d.ts new file mode 100644 index 0000000..e9e306f --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/util/VisibilityMonitor.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { EventEmitter } from './EventEmitter'; +export declare class VisibilityMonitor extends EventEmitter { + private visible_; + static getInstance(): VisibilityMonitor; + constructor(); + getInitialEvent(eventType: string): boolean[]; +} diff --git a/node_modules/@firebase/database/dist/src/core/util/libs/parser.d.ts b/node_modules/@firebase/database/dist/src/core/util/libs/parser.d.ts new file mode 100644 index 0000000..9f1d58c --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/util/libs/parser.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { RepoInfo } from '../../RepoInfo'; +import { Path } from '../Path'; +export declare const parseRepoInfo: (dataURL: string, nodeAdmin: boolean) => { + repoInfo: RepoInfo; + path: Path; +}; +export declare const parseDatabaseURL: (dataURL: string) => { + host: string; + port: number; + domain: string; + subdomain: string; + secure: boolean; + scheme: string; + pathString: string; + namespace: string; +}; diff --git a/node_modules/@firebase/database/dist/src/core/util/misc.d.ts b/node_modules/@firebase/database/dist/src/core/util/misc.d.ts new file mode 100644 index 0000000..abfa94c --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/util/misc.d.ts @@ -0,0 +1,19 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface Indexable { + [key: string]: unknown; +} diff --git a/node_modules/@firebase/database/dist/src/core/util/util.d.ts b/node_modules/@firebase/database/dist/src/core/util/util.d.ts new file mode 100644 index 0000000..35c32d8 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/util/util.d.ts @@ -0,0 +1,176 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { QueryContext } from '../view/EventRegistration'; +/** + * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called). + */ +export declare const LUIDGenerator: () => number; +/** + * Sha1 hash of the input string + * @param str - The string to hash + * @returns {!string} The resulting hash + */ +export declare const sha1: (str: string) => string; +/** + * Use this for all debug messages in Firebase. + */ +export declare let logger: ((a: string) => void) | null; +/** + * The implementation of Firebase.enableLogging (defined here to break dependencies) + * @param logger_ - A flag to turn on logging, or a custom logger + * @param persistent - Whether or not to persist logging settings across refreshes + */ +export declare const enableLogging: (logger_?: boolean | ((a: string) => void) | null, persistent?: boolean) => void; +export declare const log: (...varArgs: unknown[]) => void; +export declare const logWrapper: (prefix: string) => (...varArgs: unknown[]) => void; +export declare const error: (...varArgs: string[]) => void; +export declare const fatal: (...varArgs: string[]) => never; +export declare const warn: (...varArgs: unknown[]) => void; +/** + * Logs a warning if the containing page uses https. Called when a call to new Firebase + * does not use https. + */ +export declare const warnIfPageIsSecure: () => void; +export declare const warnAboutUnsupportedMethod: (methodName: string) => void; +/** + * Returns true if data is NaN, or +/- Infinity. + */ +export declare const isInvalidJSONNumber: (data: unknown) => boolean; +export declare const executeWhenDOMReady: (fn: () => void) => void; +/** + * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names + */ +export declare const MIN_NAME = "[MIN_NAME]"; +/** + * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names + */ +export declare const MAX_NAME = "[MAX_NAME]"; +/** + * Compares valid Firebase key names, plus min and max name + */ +export declare const nameCompare: (a: string, b: string) => number; +/** + * @returns {!number} comparison result. + */ +export declare const stringCompare: (a: string, b: string) => number; +export declare const requireKey: (key: string, obj: { + [k: string]: unknown; +}) => unknown; +export declare const ObjectToUniqueKey: (obj: unknown) => string; +/** + * Splits a string into a number of smaller segments of maximum size + * @param str - The string + * @param segsize - The maximum number of chars in the string. + * @returns The string, split into appropriately-sized chunks + */ +export declare const splitStringBySize: (str: string, segsize: number) => string[]; +/** + * Apply a function to each (key, value) pair in an object or + * apply a function to each (index, value) pair in an array + * @param obj - The object or array to iterate over + * @param fn - The function to apply + */ +export declare function each(obj: object, fn: (k: string, v: unknown) => void): void; +/** + * Like goog.bind, but doesn't bother to create a closure if opt_context is null/undefined. + * @param callback - Callback function. + * @param context - Optional context to bind to. + * + */ +export declare const bindCallback: (callback: (a: unknown) => void, context?: object | null) => (a: unknown) => void; +/** + * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License) + * I made one modification at the end and removed the NaN / Infinity + * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments. + * @param v - A double + * + */ +export declare const doubleToIEEE754String: (v: number) => string; +/** + * Used to detect if we're in a Chrome content script (which executes in an + * isolated environment where long-polling doesn't work). + */ +export declare const isChromeExtensionContentScript: () => boolean; +/** + * Used to detect if we're in a Windows 8 Store app. + */ +export declare const isWindowsStoreApp: () => boolean; +/** + * Converts a server error code to a JavaScript Error + */ +export declare function errorForServerCode(code: string, query: QueryContext): Error; +/** + * Used to test for integer-looking strings + */ +export declare const INTEGER_REGEXP_: RegExp; +/** + * For use in keys, the minimum possible 32-bit integer. + */ +export declare const INTEGER_32_MIN = -2147483648; +/** + * For use in keys, the maximum possible 32-bit integer. + */ +export declare const INTEGER_32_MAX = 2147483647; +/** + * If the string contains a 32-bit integer, return it. Else return null. + */ +export declare const tryParseInt: (str: string) => number | null; +/** + * Helper to run some code but catch any exceptions and re-throw them later. + * Useful for preventing user callbacks from breaking internal code. + * + * Re-throwing the exception from a setTimeout is a little evil, but it's very + * convenient (we don't have to try to figure out when is a safe point to + * re-throw it), and the behavior seems reasonable: + * + * * If you aren't pausing on exceptions, you get an error in the console with + * the correct stack trace. + * * If you're pausing on all exceptions, the debugger will pause on your + * exception and then again when we rethrow it. + * * If you're only pausing on uncaught exceptions, the debugger will only pause + * on us re-throwing it. + * + * @param fn - The code to guard. + */ +export declare const exceptionGuard: (fn: () => void) => void; +/** + * Helper function to safely call opt_callback with the specified arguments. It: + * 1. Turns into a no-op if opt_callback is null or undefined. + * 2. Wraps the call inside exceptionGuard to prevent exceptions from breaking our state. + * + * @param callback - Optional onComplete callback. + * @param varArgs - Arbitrary args to be passed to opt_onComplete + */ +export declare const callUserCallback: (callback?: Function | null, ...varArgs: unknown[]) => void; +/** + * @returns {boolean} true if we think we're currently being crawled. + */ +export declare const beingCrawled: () => boolean; +/** + * Export a property of an object using a getter function. + */ +export declare const exportPropGetter: (object: object, name: string, fnGet: () => unknown) => void; +/** + * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting. + * + * It is removed with clearTimeout() as normal. + * + * @param fn - Function to run. + * @param time - Milliseconds to wait before running. + * @returns The setTimeout() return value. + */ +export declare const setTimeoutNonBlocking: (fn: () => void, time: number) => number | object; diff --git a/node_modules/@firebase/database/dist/src/core/util/validation.d.ts b/node_modules/@firebase/database/dist/src/core/util/validation.d.ts new file mode 100644 index 0000000..dc216b8 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/util/validation.d.ts @@ -0,0 +1,70 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { RepoInfo } from '../RepoInfo'; +import { Path, ValidationPath } from './Path'; +/** + * True for invalid Firebase keys + */ +export declare const INVALID_KEY_REGEX_: RegExp; +/** + * True for invalid Firebase paths. + * Allows '/' in paths. + */ +export declare const INVALID_PATH_REGEX_: RegExp; +/** + * Maximum number of characters to allow in leaf value + */ +export declare const MAX_LEAF_SIZE_: number; +export declare const isValidKey: (key: unknown) => boolean; +export declare const isValidPathString: (pathString: string) => boolean; +export declare const isValidRootPathString: (pathString: string) => boolean; +export declare const isValidPriority: (priority: unknown) => boolean; +/** + * Pre-validate a datum passed as an argument to Firebase function. + */ +export declare const validateFirebaseDataArg: (fnName: string, value: unknown, path: Path, optional: boolean) => void; +/** + * Validate a data object client-side before sending to server. + */ +export declare const validateFirebaseData: (errorPrefix: string, data: unknown, path_: Path | ValidationPath) => void; +/** + * Pre-validate paths passed in the firebase function. + */ +export declare const validateFirebaseMergePaths: (errorPrefix: string, mergePaths: Path[]) => void; +/** + * pre-validate an object passed as an argument to firebase function ( + * must be an object - e.g. for firebase.update()). + */ +export declare const validateFirebaseMergeDataArg: (fnName: string, data: unknown, path: Path, optional: boolean) => void; +export declare const validatePriority: (fnName: string, priority: unknown, optional: boolean) => void; +export declare const validateKey: (fnName: string, argumentName: string, key: string, optional: boolean) => void; +/** + * @internal + */ +export declare const validatePathString: (fnName: string, argumentName: string, pathString: string, optional: boolean) => void; +export declare const validateRootPathString: (fnName: string, argumentName: string, pathString: string, optional: boolean) => void; +/** + * @internal + */ +export declare const validateWritablePath: (fnName: string, path: Path) => void; +export declare const validateUrl: (fnName: string, parsedUrl: { + repoInfo: RepoInfo; + path: Path; +}) => void; +export declare const validateString: (fnName: string, argumentName: string, string: unknown, optional: boolean) => void; +export declare const validateObject: (fnName: string, argumentName: string, obj: unknown, optional: boolean) => void; +export declare const validateObjectContainsKey: (fnName: string, argumentName: string, obj: unknown, key: string, optional: boolean, optType?: string) => void; diff --git a/node_modules/@firebase/database/dist/src/core/version.d.ts b/node_modules/@firebase/database/dist/src/core/version.d.ts new file mode 100644 index 0000000..d6ea395 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/version.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The semver (www.semver.org) version of the SDK. */ +export declare let SDK_VERSION: string; +/** + * SDK_VERSION should be set before any database instance is created + * @internal + */ +export declare function setSDKVersion(version: string): void; diff --git a/node_modules/@firebase/database/dist/src/core/view/CacheNode.d.ts b/node_modules/@firebase/database/dist/src/core/view/CacheNode.d.ts new file mode 100644 index 0000000..da38015 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/view/CacheNode.d.ts @@ -0,0 +1,41 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Node } from '../snap/Node'; +import { Path } from '../util/Path'; +/** + * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully + * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g. + * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks + * whether a node potentially had children removed due to a filter. + */ +export declare class CacheNode { + private node_; + private fullyInitialized_; + private filtered_; + constructor(node_: Node, fullyInitialized_: boolean, filtered_: boolean); + /** + * Returns whether this node was fully initialized with either server data or a complete overwrite by the client + */ + isFullyInitialized(): boolean; + /** + * Returns whether this node is potentially missing children due to a filter applied to the node + */ + isFiltered(): boolean; + isCompleteForPath(path: Path): boolean; + isCompleteForChild(key: string): boolean; + getNode(): Node; +} diff --git a/node_modules/@firebase/database/dist/src/core/view/Change.d.ts b/node_modules/@firebase/database/dist/src/core/view/Change.d.ts new file mode 100644 index 0000000..985eee0 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/view/Change.d.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Node } from '../snap/Node'; +export declare const enum ChangeType { + /** Event type for a child added */ + CHILD_ADDED = "child_added", + /** Event type for a child removed */ + CHILD_REMOVED = "child_removed", + /** Event type for a child changed */ + CHILD_CHANGED = "child_changed", + /** Event type for a child moved */ + CHILD_MOVED = "child_moved", + /** Event type for a value change */ + VALUE = "value" +} +export interface Change { + /** @param type - The event type */ + type: ChangeType; + /** @param snapshotNode - The data */ + snapshotNode: Node; + /** @param childName - The name for this child, if it's a child even */ + childName?: string; + /** @param oldSnap - Used for intermediate processing of child changed events */ + oldSnap?: Node; + /** * @param prevName - The name for the previous child, if applicable */ + prevName?: string | null; +} +export declare function changeValue(snapshotNode: Node): Change; +export declare function changeChildAdded(childName: string, snapshotNode: Node): Change; +export declare function changeChildRemoved(childName: string, snapshotNode: Node): Change; +export declare function changeChildChanged(childName: string, snapshotNode: Node, oldSnap: Node): Change; +export declare function changeChildMoved(childName: string, snapshotNode: Node): Change; diff --git a/node_modules/@firebase/database/dist/src/core/view/ChildChangeAccumulator.d.ts b/node_modules/@firebase/database/dist/src/core/view/ChildChangeAccumulator.d.ts new file mode 100644 index 0000000..473ab16 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/view/ChildChangeAccumulator.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Change } from './Change'; +export declare class ChildChangeAccumulator { + private readonly changeMap; + trackChildChange(change: Change): void; + getChanges(): Change[]; +} diff --git a/node_modules/@firebase/database/dist/src/core/view/CompleteChildSource.d.ts b/node_modules/@firebase/database/dist/src/core/view/CompleteChildSource.d.ts new file mode 100644 index 0000000..fcc774c --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/view/CompleteChildSource.d.ts @@ -0,0 +1,55 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Index } from '../snap/indexes/Index'; +import { NamedNode, Node } from '../snap/Node'; +import { WriteTreeRef } from '../WriteTree'; +import { ViewCache } from './ViewCache'; +/** + * Since updates to filtered nodes might require nodes to be pulled in from "outside" the node, this interface + * can help to get complete children that can be pulled in. + * A class implementing this interface takes potentially multiple sources (e.g. user writes, server data from + * other views etc.) to try it's best to get a complete child that might be useful in pulling into the view. + * + * @interface + */ +export interface CompleteChildSource { + getCompleteChild(childKey: string): Node | null; + getChildAfterChild(index: Index, child: NamedNode, reverse: boolean): NamedNode | null; +} +/** + * An implementation of CompleteChildSource that never returns any additional children + */ +export declare class NoCompleteChildSource_ implements CompleteChildSource { + getCompleteChild(childKey?: string): Node | null; + getChildAfterChild(index?: Index, child?: NamedNode, reverse?: boolean): NamedNode | null; +} +/** + * Singleton instance. + */ +export declare const NO_COMPLETE_CHILD_SOURCE: NoCompleteChildSource_; +/** + * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or + * old event caches available to calculate complete children. + */ +export declare class WriteTreeCompleteChildSource implements CompleteChildSource { + private writes_; + private viewCache_; + private optCompleteServerCache_; + constructor(writes_: WriteTreeRef, viewCache_: ViewCache, optCompleteServerCache_?: Node | null); + getCompleteChild(childKey: string): Node | null; + getChildAfterChild(index: Index, child: NamedNode, reverse: boolean): NamedNode | null; +} diff --git a/node_modules/@firebase/database/dist/src/core/view/Event.d.ts b/node_modules/@firebase/database/dist/src/core/view/Event.d.ts new file mode 100644 index 0000000..69e326a --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/view/Event.d.ts @@ -0,0 +1,64 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DataSnapshot as ExpDataSnapshot } from '../../api/Reference_impl'; +import { Path } from '../util/Path'; +import { EventRegistration } from './EventRegistration'; +/** + * Encapsulates the data needed to raise an event + * @interface + */ +export interface Event { + getPath(): Path; + getEventType(): string; + getEventRunner(): () => void; + toString(): string; +} +/** + * One of the following strings: "value", "child_added", "child_changed", + * "child_removed", or "child_moved." + */ +export type EventType = 'value' | 'child_added' | 'child_changed' | 'child_moved' | 'child_removed'; +/** + * Encapsulates the data needed to raise an event + */ +export declare class DataEvent implements Event { + eventType: EventType; + eventRegistration: EventRegistration; + snapshot: ExpDataSnapshot; + prevName?: string | null; + /** + * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed + * @param eventRegistration - The function to call to with the event data. User provided + * @param snapshot - The data backing the event + * @param prevName - Optional, the name of the previous child for child_* events. + */ + constructor(eventType: EventType, eventRegistration: EventRegistration, snapshot: ExpDataSnapshot, prevName?: string | null); + getPath(): Path; + getEventType(): string; + getEventRunner(): () => void; + toString(): string; +} +export declare class CancelEvent implements Event { + eventRegistration: EventRegistration; + error: Error; + path: Path; + constructor(eventRegistration: EventRegistration, error: Error, path: Path); + getPath(): Path; + getEventType(): string; + getEventRunner(): () => void; + toString(): string; +} diff --git a/node_modules/@firebase/database/dist/src/core/view/EventGenerator.d.ts b/node_modules/@firebase/database/dist/src/core/view/EventGenerator.d.ts new file mode 100644 index 0000000..bc916b8 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/view/EventGenerator.d.ts @@ -0,0 +1,42 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Index } from '../snap/indexes/Index'; +import { Node } from '../snap/Node'; +import { Change } from './Change'; +import { Event } from './Event'; +import { EventRegistration, QueryContext } from './EventRegistration'; +/** + * An EventGenerator is used to convert "raw" changes (Change) as computed by the + * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges() + * for details. + * + */ +export declare class EventGenerator { + query_: QueryContext; + index_: Index; + constructor(query_: QueryContext); +} +/** + * Given a set of raw changes (no moved events and prevName not specified yet), and a set of + * EventRegistrations that should be notified of these changes, generate the actual events to be raised. + * + * Notes: + * - child_moved events will be synthesized at this time for any child_changed events that affect + * our index. + * - prevName will be calculated based on the index ordering. + */ +export declare function eventGeneratorGenerateEventsForChanges(eventGenerator: EventGenerator, changes: Change[], eventCache: Node, eventRegistrations: EventRegistration[]): Event[]; diff --git a/node_modules/@firebase/database/dist/src/core/view/EventQueue.d.ts b/node_modules/@firebase/database/dist/src/core/view/EventQueue.d.ts new file mode 100644 index 0000000..63ea6f4 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/view/EventQueue.d.ts @@ -0,0 +1,67 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Path } from '../util/Path'; +import { Event } from './Event'; +/** + * The event queue serves a few purposes: + * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more + * events being queued. + * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events, + * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call + * left off, ensuring that the events are still raised synchronously and in order. + * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued + * events are raised synchronously. + * + * NOTE: This can all go away if/when we move to async events. + * + */ +export declare class EventQueue { + eventLists_: EventList[]; + /** + * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes. + */ + recursionDepth_: number; +} +/** + * @param eventDataList - The new events to queue. + */ +export declare function eventQueueQueueEvents(eventQueue: EventQueue, eventDataList: Event[]): void; +/** + * Queues the specified events and synchronously raises all events (including previously queued ones) + * for the specified path. + * + * It is assumed that the new events are all for the specified path. + * + * @param path - The path to raise events for. + * @param eventDataList - The new events to raise. + */ +export declare function eventQueueRaiseEventsAtPath(eventQueue: EventQueue, path: Path, eventDataList: Event[]): void; +/** + * Queues the specified events and synchronously raises all events (including previously queued ones) for + * locations related to the specified change path (i.e. all ancestors and descendants). + * + * It is assumed that the new events are all related (ancestor or descendant) to the specified path. + * + * @param changedPath - The path to raise events for. + * @param eventDataList - The events to raise + */ +export declare function eventQueueRaiseEventsForChangedPath(eventQueue: EventQueue, changedPath: Path, eventDataList: Event[]): void; +interface EventList { + events: Event[]; + path: Path; +} +export {}; diff --git a/node_modules/@firebase/database/dist/src/core/view/EventRegistration.d.ts b/node_modules/@firebase/database/dist/src/core/view/EventRegistration.d.ts new file mode 100644 index 0000000..4425097 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/view/EventRegistration.d.ts @@ -0,0 +1,87 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DataSnapshot } from '../../api/Reference_impl'; +import { Repo } from '../Repo'; +import { Path } from '../util/Path'; +import { Change } from './Change'; +import { CancelEvent, Event } from './Event'; +import { QueryParams } from './QueryParams'; +/** + * A user callback. Callbacks issues from the Legacy SDK maintain references + * to the original user-issued callbacks, which allows equality + * comparison by reference even though this callbacks are wrapped before + * they can be passed to the firebase@exp SDK. + * + * @internal + */ +export interface UserCallback { + (dataSnapshot: DataSnapshot, previousChildName?: string | null): unknown; + userCallback?: unknown; + context?: object | null; +} +/** + * A wrapper class that converts events from the database@exp SDK to the legacy + * Database SDK. Events are not converted directly as event registration relies + * on reference comparison of the original user callback (see `matches()`) and + * relies on equality of the legacy SDK's `context` object. + */ +export declare class CallbackContext { + private readonly snapshotCallback; + private readonly cancelCallback?; + constructor(snapshotCallback: UserCallback, cancelCallback?: (error: Error) => unknown); + onValue(expDataSnapshot: DataSnapshot, previousChildName?: string | null): void; + onCancel(error: Error): void; + get hasCancelCallback(): boolean; + matches(other: CallbackContext): boolean; +} +export interface QueryContext { + readonly _queryIdentifier: string; + readonly _queryObject: object; + readonly _repo: Repo; + readonly _path: Path; + readonly _queryParams: QueryParams; +} +/** + * An EventRegistration is basically an event type ('value', 'child_added', etc.) and a callback + * to be notified of that type of event. + * + * That said, it can also contain a cancel callback to be notified if the event is canceled. And + * currently, this code is organized around the idea that you would register multiple child_ callbacks + * together, as a single EventRegistration. Though currently we don't do that. + */ +export interface EventRegistration { + /** + * True if this container has a callback to trigger for this event type + */ + respondsTo(eventType: string): boolean; + createEvent(change: Change, query: QueryContext): Event; + /** + * Given event data, return a function to trigger the user's callback + */ + getEventRunner(eventData: Event): () => void; + createCancelEvent(error: Error, path: Path): CancelEvent | null; + matches(other: EventRegistration): boolean; + /** + * False basically means this is a "dummy" callback container being used as a sentinel + * to remove all callback containers of a particular type. (e.g. if the user does + * ref.off('value') without specifying a specific callback). + * + * (TODO: Rework this, since it's hacky) + * + */ + hasAnyCallback(): boolean; +} diff --git a/node_modules/@firebase/database/dist/src/core/view/QueryParams.d.ts b/node_modules/@firebase/database/dist/src/core/view/QueryParams.d.ts new file mode 100644 index 0000000..47870f7 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/view/QueryParams.d.ts @@ -0,0 +1,95 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Index } from '../snap/indexes/Index'; +import { PriorityIndex } from '../snap/indexes/PriorityIndex'; +import { NodeFilter } from './filter/NodeFilter'; +/** + * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a + * range to be returned for a particular location. It is assumed that validation of parameters is done at the + * user-facing API level, so it is not done here. + * + * @internal + */ +export declare class QueryParams { + limitSet_: boolean; + startSet_: boolean; + startNameSet_: boolean; + startAfterSet_: boolean; + endSet_: boolean; + endNameSet_: boolean; + endBeforeSet_: boolean; + limit_: number; + viewFrom_: string; + indexStartValue_: unknown | null; + indexStartName_: string; + indexEndValue_: unknown | null; + indexEndName_: string; + index_: PriorityIndex; + hasStart(): boolean; + /** + * @returns True if it would return from left. + */ + isViewFromLeft(): boolean; + /** + * Only valid to call if hasStart() returns true + */ + getIndexStartValue(): unknown; + /** + * Only valid to call if hasStart() returns true. + * Returns the starting key name for the range defined by these query parameters + */ + getIndexStartName(): string; + hasEnd(): boolean; + /** + * Only valid to call if hasEnd() returns true. + */ + getIndexEndValue(): unknown; + /** + * Only valid to call if hasEnd() returns true. + * Returns the end key name for the range defined by these query parameters + */ + getIndexEndName(): string; + hasLimit(): boolean; + /** + * @returns True if a limit has been set and it has been explicitly anchored + */ + hasAnchoredLimit(): boolean; + /** + * Only valid to call if hasLimit() returns true + */ + getLimit(): number; + getIndex(): Index; + loadsAllData(): boolean; + isDefault(): boolean; + copy(): QueryParams; +} +export declare function queryParamsGetNodeFilter(queryParams: QueryParams): NodeFilter; +export declare function queryParamsLimit(queryParams: QueryParams, newLimit: number): QueryParams; +export declare function queryParamsLimitToFirst(queryParams: QueryParams, newLimit: number): QueryParams; +export declare function queryParamsLimitToLast(queryParams: QueryParams, newLimit: number): QueryParams; +export declare function queryParamsStartAt(queryParams: QueryParams, indexValue: unknown, key?: string | null): QueryParams; +export declare function queryParamsStartAfter(queryParams: QueryParams, indexValue: unknown, key?: string | null): QueryParams; +export declare function queryParamsEndAt(queryParams: QueryParams, indexValue: unknown, key?: string | null): QueryParams; +export declare function queryParamsEndBefore(queryParams: QueryParams, indexValue: unknown, key?: string | null): QueryParams; +export declare function queryParamsOrderBy(queryParams: QueryParams, index: Index): QueryParams; +/** + * Returns a set of REST query string parameters representing this query. + * + * @returns query string parameters + */ +export declare function queryParamsToRestQueryStringParameters(queryParams: QueryParams): Record; +export declare function queryParamsGetQueryObject(queryParams: QueryParams): Record; diff --git a/node_modules/@firebase/database/dist/src/core/view/View.d.ts b/node_modules/@firebase/database/dist/src/core/view/View.d.ts new file mode 100644 index 0000000..a872658 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/view/View.d.ts @@ -0,0 +1,59 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Operation } from '../operation/Operation'; +import { Node } from '../snap/Node'; +import { Path } from '../util/Path'; +import { WriteTreeRef } from '../WriteTree'; +import { Event } from './Event'; +import { EventGenerator } from './EventGenerator'; +import { EventRegistration, QueryContext } from './EventRegistration'; +import { ViewCache } from './ViewCache'; +import { ViewProcessor } from './ViewProcessor'; +/** + * A view represents a specific location and query that has 1 or more event registrations. + * + * It does several things: + * - Maintains the list of event registrations for this location/query. + * - Maintains a cache of the data visible for this location/query. + * - Applies new operations (via applyOperation), updates the cache, and based on the event + * registrations returns the set of events to be raised. + */ +export declare class View { + private query_; + processor_: ViewProcessor; + viewCache_: ViewCache; + eventRegistrations_: EventRegistration[]; + eventGenerator_: EventGenerator; + constructor(query_: QueryContext, initialViewCache: ViewCache); + get query(): QueryContext; +} +export declare function viewGetServerCache(view: View): Node | null; +export declare function viewGetCompleteNode(view: View): Node | null; +export declare function viewGetCompleteServerCache(view: View, path: Path): Node | null; +export declare function viewIsEmpty(view: View): boolean; +export declare function viewAddEventRegistration(view: View, eventRegistration: EventRegistration): void; +/** + * @param eventRegistration - If null, remove all callbacks. + * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned. + * @returns Cancel events, if cancelError was provided. + */ +export declare function viewRemoveEventRegistration(view: View, eventRegistration: EventRegistration | null, cancelError?: Error): Event[]; +/** + * Applies the given Operation, updates our cache, and returns the appropriate events. + */ +export declare function viewApplyOperation(view: View, operation: Operation, writesCache: WriteTreeRef, completeServerCache: Node | null): Event[]; +export declare function viewGetInitialEvents(view: View, registration: EventRegistration): Event[]; diff --git a/node_modules/@firebase/database/dist/src/core/view/ViewCache.d.ts b/node_modules/@firebase/database/dist/src/core/view/ViewCache.d.ts new file mode 100644 index 0000000..089749d --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/view/ViewCache.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Node } from '../snap/Node'; +import { CacheNode } from './CacheNode'; +/** + * Stores the data we have cached for a view. + * + * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes). + */ +export interface ViewCache { + readonly eventCache: CacheNode; + readonly serverCache: CacheNode; +} +export declare function newViewCache(eventCache: CacheNode, serverCache: CacheNode): ViewCache; +export declare function viewCacheUpdateEventSnap(viewCache: ViewCache, eventSnap: Node, complete: boolean, filtered: boolean): ViewCache; +export declare function viewCacheUpdateServerSnap(viewCache: ViewCache, serverSnap: Node, complete: boolean, filtered: boolean): ViewCache; +export declare function viewCacheGetCompleteEventSnap(viewCache: ViewCache): Node | null; +export declare function viewCacheGetCompleteServerSnap(viewCache: ViewCache): Node | null; diff --git a/node_modules/@firebase/database/dist/src/core/view/ViewProcessor.d.ts b/node_modules/@firebase/database/dist/src/core/view/ViewProcessor.d.ts new file mode 100644 index 0000000..9baa237 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/view/ViewProcessor.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Operation } from '../operation/Operation'; +import { Node } from '../snap/Node'; +import { WriteTreeRef } from '../WriteTree'; +import { Change } from './Change'; +import { NodeFilter } from './filter/NodeFilter'; +import { ViewCache } from './ViewCache'; +export interface ProcessorResult { + readonly viewCache: ViewCache; + readonly changes: Change[]; +} +export interface ViewProcessor { + readonly filter: NodeFilter; +} +export declare function newViewProcessor(filter: NodeFilter): ViewProcessor; +export declare function viewProcessorAssertIndexed(viewProcessor: ViewProcessor, viewCache: ViewCache): void; +export declare function viewProcessorApplyOperation(viewProcessor: ViewProcessor, oldViewCache: ViewCache, operation: Operation, writesCache: WriteTreeRef, completeCache: Node | null): ProcessorResult; diff --git a/node_modules/@firebase/database/dist/src/core/view/filter/IndexedFilter.d.ts b/node_modules/@firebase/database/dist/src/core/view/filter/IndexedFilter.d.ts new file mode 100644 index 0000000..07584dd --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/view/filter/IndexedFilter.d.ts @@ -0,0 +1,35 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Index } from '../../snap/indexes/Index'; +import { Node } from '../../snap/Node'; +import { Path } from '../../util/Path'; +import { ChildChangeAccumulator } from '../ChildChangeAccumulator'; +import { CompleteChildSource } from '../CompleteChildSource'; +import { NodeFilter } from './NodeFilter'; +/** + * Doesn't really filter nodes but applies an index to the node and keeps track of any changes + */ +export declare class IndexedFilter implements NodeFilter { + private readonly index_; + constructor(index_: Index); + updateChild(snap: Node, key: string, newChild: Node, affectedPath: Path, source: CompleteChildSource, optChangeAccumulator: ChildChangeAccumulator | null): Node; + updateFullNode(oldSnap: Node, newSnap: Node, optChangeAccumulator: ChildChangeAccumulator | null): Node; + updatePriority(oldSnap: Node, newPriority: Node): Node; + filtersNodes(): boolean; + getIndexedFilter(): IndexedFilter; + getIndex(): Index; +} diff --git a/node_modules/@firebase/database/dist/src/core/view/filter/LimitedFilter.d.ts b/node_modules/@firebase/database/dist/src/core/view/filter/LimitedFilter.d.ts new file mode 100644 index 0000000..cb2da45 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/view/filter/LimitedFilter.d.ts @@ -0,0 +1,47 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Index } from '../../snap/indexes/Index'; +import { Node } from '../../snap/Node'; +import { Path } from '../../util/Path'; +import { ChildChangeAccumulator } from '../ChildChangeAccumulator'; +import { CompleteChildSource } from '../CompleteChildSource'; +import { QueryParams } from '../QueryParams'; +import { IndexedFilter } from './IndexedFilter'; +import { NodeFilter } from './NodeFilter'; +/** + * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible + */ +export declare class LimitedFilter implements NodeFilter { + private readonly rangedFilter_; + private readonly index_; + private readonly limit_; + private readonly reverse_; + private readonly startIsInclusive_; + private readonly endIsInclusive_; + constructor(params: QueryParams); + updateChild(snap: Node, key: string, newChild: Node, affectedPath: Path, source: CompleteChildSource, optChangeAccumulator: ChildChangeAccumulator | null): Node; + updateFullNode(oldSnap: Node, newSnap: Node, optChangeAccumulator: ChildChangeAccumulator | null): Node; + updatePriority(oldSnap: Node, newPriority: Node): Node; + filtersNodes(): boolean; + getIndexedFilter(): IndexedFilter; + getIndex(): Index; + private fullLimitUpdateChild_; + private withinDirectionalStart; + private withinDirectionalEnd; + private withinStartPost; + private withinEndPost; +} diff --git a/node_modules/@firebase/database/dist/src/core/view/filter/NodeFilter.d.ts b/node_modules/@firebase/database/dist/src/core/view/filter/NodeFilter.d.ts new file mode 100644 index 0000000..b1fafb2 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/view/filter/NodeFilter.d.ts @@ -0,0 +1,54 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Index } from '../../snap/indexes/Index'; +import { Node } from '../../snap/Node'; +import { Path } from '../../util/Path'; +import { ChildChangeAccumulator } from '../ChildChangeAccumulator'; +import { CompleteChildSource } from '../CompleteChildSource'; +/** + * NodeFilter is used to update nodes and complete children of nodes while applying queries on the fly and keeping + * track of any child changes. This class does not track value changes as value changes depend on more + * than just the node itself. Different kind of queries require different kind of implementations of this interface. + * @interface + */ +export interface NodeFilter { + /** + * Update a single complete child in the snap. If the child equals the old child in the snap, this is a no-op. + * The method expects an indexed snap. + */ + updateChild(snap: Node, key: string, newChild: Node, affectedPath: Path, source: CompleteChildSource, optChangeAccumulator: ChildChangeAccumulator | null): Node; + /** + * Update a node in full and output any resulting change from this complete update. + */ + updateFullNode(oldSnap: Node, newSnap: Node, optChangeAccumulator: ChildChangeAccumulator | null): Node; + /** + * Update the priority of the root node + */ + updatePriority(oldSnap: Node, newPriority: Node): Node; + /** + * Returns true if children might be filtered due to query criteria + */ + filtersNodes(): boolean; + /** + * Returns the index filter that this filter uses to get a NodeFilter that doesn't filter any children. + */ + getIndexedFilter(): NodeFilter; + /** + * Returns the index that this filter uses + */ + getIndex(): Index; +} diff --git a/node_modules/@firebase/database/dist/src/core/view/filter/RangedFilter.d.ts b/node_modules/@firebase/database/dist/src/core/view/filter/RangedFilter.d.ts new file mode 100644 index 0000000..bef847a --- /dev/null +++ b/node_modules/@firebase/database/dist/src/core/view/filter/RangedFilter.d.ts @@ -0,0 +1,47 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NamedNode, Node } from '../../../core/snap/Node'; +import { Index } from '../../snap/indexes/Index'; +import { Path } from '../../util/Path'; +import { ChildChangeAccumulator } from '../ChildChangeAccumulator'; +import { CompleteChildSource } from '../CompleteChildSource'; +import { QueryParams } from '../QueryParams'; +import { IndexedFilter } from './IndexedFilter'; +import { NodeFilter } from './NodeFilter'; +/** + * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node + */ +export declare class RangedFilter implements NodeFilter { + private indexedFilter_; + private index_; + private startPost_; + private endPost_; + private startIsInclusive_; + private endIsInclusive_; + constructor(params: QueryParams); + getStartPost(): NamedNode; + getEndPost(): NamedNode; + matches(node: NamedNode): boolean; + updateChild(snap: Node, key: string, newChild: Node, affectedPath: Path, source: CompleteChildSource, optChangeAccumulator: ChildChangeAccumulator | null): Node; + updateFullNode(oldSnap: Node, newSnap: Node, optChangeAccumulator: ChildChangeAccumulator | null): Node; + updatePriority(oldSnap: Node, newPriority: Node): Node; + filtersNodes(): boolean; + getIndexedFilter(): IndexedFilter; + getIndex(): Index; + private static getStartPost_; + private static getEndPost_; +} diff --git a/node_modules/@firebase/database/dist/src/index.d.ts b/node_modules/@firebase/database/dist/src/index.d.ts new file mode 100644 index 0000000..8990721 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/index.d.ts @@ -0,0 +1,28 @@ +/** + * Firebase Realtime Database + * + * @packageDocumentation + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Database } from './api/Database'; +export * from './api'; +declare module '@firebase/component' { + interface NameServiceMapping { + 'database': Database; + } +} diff --git a/node_modules/@firebase/database/dist/src/index.node.d.ts b/node_modules/@firebase/database/dist/src/index.node.d.ts new file mode 100644 index 0000000..952da59 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/index.node.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './api'; diff --git a/node_modules/@firebase/database/dist/src/index.standalone.d.ts b/node_modules/@firebase/database/dist/src/index.standalone.d.ts new file mode 100644 index 0000000..c852b29 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/index.standalone.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './api.standalone'; diff --git a/node_modules/@firebase/database/dist/src/internal/index.d.ts b/node_modules/@firebase/database/dist/src/internal/index.d.ts new file mode 100644 index 0000000..77b7558 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/internal/index.d.ts @@ -0,0 +1,38 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseAppCheckInternal } from '@firebase/app-check-interop-types'; +import { FirebaseApp } from '@firebase/app-types'; +import { FirebaseAuthInternal } from '@firebase/auth-interop-types'; +import { Database } from '../api.standalone'; +/** + * Used by console to create a database based on the app, + * passed database URL and a custom auth implementation. + * @internal + * @param app - A valid FirebaseApp-like object + * @param url - A valid Firebase databaseURL + * @param version - custom version e.g. firebase-admin version + * @param customAppCheckImpl - custom app check implementation + * @param customAuthImpl - custom auth implementation + */ +export declare function _initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, nodeAdmin }: { + app: FirebaseApp; + url: string; + version: string; + customAuthImpl: FirebaseAuthInternal; + customAppCheckImpl?: FirebaseAppCheckInternal; + nodeAdmin?: boolean; +}): Database; diff --git a/node_modules/@firebase/database/dist/src/realtime/BrowserPollConnection.d.ts b/node_modules/@firebase/database/dist/src/realtime/BrowserPollConnection.d.ts new file mode 100644 index 0000000..b99fd6e --- /dev/null +++ b/node_modules/@firebase/database/dist/src/realtime/BrowserPollConnection.d.ts @@ -0,0 +1,198 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { RepoInfo } from '../core/RepoInfo'; +import { PacketReceiver } from './polling/PacketReceiver'; +import { Transport } from './Transport'; +export declare const FIREBASE_LONGPOLL_START_PARAM = "start"; +export declare const FIREBASE_LONGPOLL_CLOSE_COMMAND = "close"; +export declare const FIREBASE_LONGPOLL_COMMAND_CB_NAME = "pLPCommand"; +export declare const FIREBASE_LONGPOLL_DATA_CB_NAME = "pRTLPCB"; +export declare const FIREBASE_LONGPOLL_ID_PARAM = "id"; +export declare const FIREBASE_LONGPOLL_PW_PARAM = "pw"; +export declare const FIREBASE_LONGPOLL_SERIAL_PARAM = "ser"; +export declare const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = "cb"; +export declare const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = "seg"; +export declare const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = "ts"; +export declare const FIREBASE_LONGPOLL_DATA_PARAM = "d"; +export declare const FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = "disconn"; +export declare const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = "dframe"; +/** + * This class manages a single long-polling connection. + */ +export declare class BrowserPollConnection implements Transport { + connId: string; + repoInfo: RepoInfo; + private applicationId?; + private appCheckToken?; + private authToken?; + transportSessionId?: string; + lastSessionId?: string; + bytesSent: number; + bytesReceived: number; + urlFn: (params: object) => string; + scriptTagHolder: FirebaseIFrameScriptHolder; + myDisconnFrame: HTMLIFrameElement; + curSegmentNum: number; + myPacketOrderer: PacketReceiver; + id: string; + password: string; + private log_; + private stats_; + private everConnected_; + private isClosed_; + private connectTimeoutTimer_; + private onDisconnect_; + /** + * @param connId An identifier for this connection, used for logging + * @param repoInfo The info for the endpoint to send data to. + * @param applicationId The Firebase App ID for this project. + * @param appCheckToken The AppCheck token for this client. + * @param authToken The AuthToken to use for this connection. + * @param transportSessionId Optional transportSessionid if we are + * reconnecting for an existing transport session + * @param lastSessionId Optional lastSessionId if the PersistentConnection has + * already created a connection previously + */ + constructor(connId: string, repoInfo: RepoInfo, applicationId?: string, appCheckToken?: string, authToken?: string, transportSessionId?: string, lastSessionId?: string); + /** + * @param onMessage - Callback when messages arrive + * @param onDisconnect - Callback with connection lost. + */ + open(onMessage: (msg: {}) => void, onDisconnect: (a?: boolean) => void): void; + /** + * Call this when a handshake has completed successfully and we want to consider the connection established + */ + start(): void; + static forceAllow_: boolean; + /** + * Forces long polling to be considered as a potential transport + */ + static forceAllow(): void; + static forceDisallow_: boolean; + /** + * Forces longpolling to not be considered as a potential transport + */ + static forceDisallow(): void; + static isAvailable(): boolean; + /** + * No-op for polling + */ + markConnectionHealthy(): void; + /** + * Stops polling and cleans up the iframe + */ + private shutdown_; + /** + * Triggered when this transport is closed + */ + private onClosed_; + /** + * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server + * that we've left. + */ + close(): void; + /** + * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then + * broken into chunks (since URLs have a small maximum length). + * @param data - The JSON data to transmit. + */ + send(data: {}): void; + /** + * This is how we notify the server that we're leaving. + * We aren't able to send requests with DHTML on a window close event, but we can + * trigger XHR requests in some browsers (everything but Opera basically). + */ + addDisconnectPingFrame(id: string, pw: string): void; + /** + * Used to track the bytes received by this client + */ + private incrementIncomingBytes_; +} +export interface IFrameElement extends HTMLIFrameElement { + doc: Document; +} +/********************************************************************************************* + * A wrapper around an iframe that is used as a long-polling script holder. + *********************************************************************************************/ +export declare class FirebaseIFrameScriptHolder { + onDisconnect: () => void; + urlFn: (a: object) => string; + outstandingRequests: Set; + pendingSegs: Array<{ + seg: number; + ts: number; + d: unknown; + }>; + currentSerial: number; + sendNewPolls: boolean; + uniqueCallbackIdentifier: number; + myIFrame: IFrameElement; + alive: boolean; + myID: string; + myPW: string; + commandCB: (command: string, ...args: unknown[]) => void; + onMessageCB: (...args: unknown[]) => void; + /** + * @param commandCB - The callback to be called when control commands are received from the server. + * @param onMessageCB - The callback to be triggered when responses arrive from the server. + * @param onDisconnect - The callback to be triggered when this tag holder is closed + * @param urlFn - A function that provides the URL of the endpoint to send data to. + */ + constructor(commandCB: (command: string, ...args: unknown[]) => void, onMessageCB: (...args: unknown[]) => void, onDisconnect: () => void, urlFn: (a: object) => string); + /** + * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can + * actually use. + */ + private static createIFrame_; + /** + * Cancel all outstanding queries and remove the frame. + */ + close(): void; + /** + * Actually start the long-polling session by adding the first script tag(s) to the iframe. + * @param id - The ID of this connection + * @param pw - The password for this connection + */ + startLongPoll(id: string, pw: string): void; + /** + * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't + * too many outstanding requests and we are still alive. + * + * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if + * needed. + */ + private newRequest_; + /** + * Queue a packet for transmission to the server. + * @param segnum - A sequential id for this packet segment used for reassembly + * @param totalsegs - The total number of segments in this packet + * @param data - The data for this segment. + */ + enqueueSegment(segnum: number, totalsegs: number, data: unknown): void; + /** + * Add a script tag for a regular long-poll request. + * @param url - The URL of the script tag. + * @param serial - The serial number of the request. + */ + private addLongPollTag_; + /** + * Add an arbitrary script tag to the iframe. + * @param url - The URL for the script tag source. + * @param loadCB - A callback to be triggered once the script has loaded. + */ + addTag(url: string, loadCB: () => void): void; +} diff --git a/node_modules/@firebase/database/dist/src/realtime/Connection.d.ts b/node_modules/@firebase/database/dist/src/realtime/Connection.d.ts new file mode 100644 index 0000000..e20e244 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/realtime/Connection.d.ts @@ -0,0 +1,102 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { RepoInfo } from '../core/RepoInfo'; +/** + * Creates a new real-time connection to the server using whichever method works + * best in the current browser. + */ +export declare class Connection { + id: string; + private repoInfo_; + private applicationId_; + private appCheckToken_; + private authToken_; + private onMessage_; + private onReady_; + private onDisconnect_; + private onKill_; + lastSessionId?: string; + connectionCount: number; + pendingDataMessages: unknown[]; + sessionId: string; + private conn_; + private healthyTimeout_; + private isHealthy_; + private log_; + private primaryResponsesRequired_; + private rx_; + private secondaryConn_; + private secondaryResponsesRequired_; + private state_; + private transportManager_; + private tx_; + /** + * @param id - an id for this connection + * @param repoInfo_ - the info for the endpoint to connect to + * @param applicationId_ - the Firebase App ID for this project + * @param appCheckToken_ - The App Check Token for this device. + * @param authToken_ - The auth token for this session. + * @param onMessage_ - the callback to be triggered when a server-push message arrives + * @param onReady_ - the callback to be triggered when this connection is ready to send messages. + * @param onDisconnect_ - the callback to be triggered when a connection was lost + * @param onKill_ - the callback to be triggered when this connection has permanently shut down. + * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server + */ + constructor(id: string, repoInfo_: RepoInfo, applicationId_: string | undefined, appCheckToken_: string | undefined, authToken_: string | undefined, onMessage_: (a: {}) => void, onReady_: (a: number, b: string) => void, onDisconnect_: () => void, onKill_: (a: string) => void, lastSessionId?: string); + /** + * Starts a connection attempt + */ + private start_; + private nextTransportId_; + private disconnReceiver_; + private connReceiver_; + /** + * @param dataMsg - An arbitrary data message to be sent to the server + */ + sendRequest(dataMsg: object): void; + tryCleanupConnection(): void; + private onSecondaryControl_; + private onSecondaryMessageReceived_; + private upgradeIfSecondaryHealthy_; + private proceedWithUpgrade_; + private onPrimaryMessageReceived_; + private onDataMessage_; + private onPrimaryResponse_; + private onControl_; + /** + * @param handshake - The handshake data returned from the server + */ + private onHandshake_; + private tryStartUpgrade_; + private startUpgrade_; + private onReset_; + private onConnectionEstablished_; + private sendPingOnPrimaryIfNecessary_; + private onSecondaryConnectionLost_; + /** + * @param everConnected - Whether or not the connection ever reached a server. Used to determine if + * we should flush the host cache + */ + private onConnectionLost_; + private onConnectionShutdown_; + private sendData_; + /** + * Cleans up this connection, calling the appropriate callbacks + */ + close(): void; + private closeConnections_; +} diff --git a/node_modules/@firebase/database/dist/src/realtime/Constants.d.ts b/node_modules/@firebase/database/dist/src/realtime/Constants.d.ts new file mode 100644 index 0000000..4ff77ff --- /dev/null +++ b/node_modules/@firebase/database/dist/src/realtime/Constants.d.ts @@ -0,0 +1,27 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const PROTOCOL_VERSION = "5"; +export declare const VERSION_PARAM = "v"; +export declare const TRANSPORT_SESSION_PARAM = "s"; +export declare const REFERER_PARAM = "r"; +export declare const FORGE_REF = "f"; +export declare const FORGE_DOMAIN_RE: RegExp; +export declare const LAST_SESSION_PARAM = "ls"; +export declare const APPLICATION_ID_PARAM = "p"; +export declare const APP_CHECK_TOKEN_PARAM = "ac"; +export declare const WEBSOCKET = "websocket"; +export declare const LONG_POLLING = "long_polling"; diff --git a/node_modules/@firebase/database/dist/src/realtime/Transport.d.ts b/node_modules/@firebase/database/dist/src/realtime/Transport.d.ts new file mode 100644 index 0000000..d66429e --- /dev/null +++ b/node_modules/@firebase/database/dist/src/realtime/Transport.d.ts @@ -0,0 +1,58 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { RepoInfo } from '../core/RepoInfo'; +export interface TransportConstructor { + new (connId: string, repoInfo: RepoInfo, applicationId?: string, appCheckToken?: string, authToken?: string, transportSessionId?: string, lastSessionId?: string): Transport; + isAvailable: () => boolean; + responsesRequiredToBeHealthy?: number; + healthyTimeout?: number; +} +export declare abstract class Transport { + /** + * Bytes received since connection started. + */ + abstract bytesReceived: number; + /** + * Bytes sent since connection started. + */ + abstract bytesSent: number; + /** + * An identifier for this connection, used for logging + */ + abstract connId: string; + /** + * @param connId - An identifier for this connection, used for logging + * @param repoInfo - The info for the endpoint to send data to. + * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport session + * @param lastSessionId - Optional lastSessionId if there was a previous connection + * @interface + */ + constructor(connId: string, repoInfo: RepoInfo, transportSessionId?: string, lastSessionId?: string); + /** + * @param onMessage - Callback when messages arrive + * @param onDisconnect - Callback with connection lost. + */ + abstract open(onMessage: (a: {}) => void, onDisconnect: (a?: boolean) => void): void; + abstract start(): void; + abstract close(): void; + /** + * @param data - The JSON data to transmit + */ + abstract send(data: {}): void; + abstract markConnectionHealthy(): void; + abstract markConnectionHealthy(): void; +} diff --git a/node_modules/@firebase/database/dist/src/realtime/TransportManager.d.ts b/node_modules/@firebase/database/dist/src/realtime/TransportManager.d.ts new file mode 100644 index 0000000..4f2ef51 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/realtime/TransportManager.d.ts @@ -0,0 +1,50 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { RepoInfo } from '../core/RepoInfo'; +import { BrowserPollConnection } from './BrowserPollConnection'; +import { TransportConstructor } from './Transport'; +import { WebSocketConnection } from './WebSocketConnection'; +/** + * Currently simplistic, this class manages what transport a Connection should use at various stages of its + * lifecycle. + * + * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if + * they are available. + */ +export declare class TransportManager { + private transports_; + static globalTransportInitialized_: boolean; + static get ALL_TRANSPORTS(): (typeof BrowserPollConnection | typeof WebSocketConnection)[]; + /** + * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after + * TransportManager has already set up transports_ + */ + static get IS_TRANSPORT_INITIALIZED(): boolean; + /** + * @param repoInfo - Metadata around the namespace we're connecting to + */ + constructor(repoInfo: RepoInfo); + private initTransports_; + /** + * @returns The constructor for the initial transport to use + */ + initialTransport(): TransportConstructor; + /** + * @returns The constructor for the next transport, or null + */ + upgradeTransport(): TransportConstructor | null; +} diff --git a/node_modules/@firebase/database/dist/src/realtime/WebSocketConnection.d.ts b/node_modules/@firebase/database/dist/src/realtime/WebSocketConnection.d.ts new file mode 100644 index 0000000..f427bb5 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/realtime/WebSocketConnection.d.ts @@ -0,0 +1,127 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { RepoInfo } from '../core/RepoInfo'; +import { Transport } from './Transport'; +export declare function setWebSocketImpl(impl: any): void; +/** + * Create a new websocket connection with the given callbacks. + */ +export declare class WebSocketConnection implements Transport { + connId: string; + private applicationId?; + private appCheckToken?; + private authToken?; + keepaliveTimer: number | null; + frames: string[] | null; + totalFrames: number; + bytesSent: number; + bytesReceived: number; + connURL: string; + onDisconnect: (a?: boolean) => void; + onMessage: (msg: {}) => void; + mySock: WebSocket | null; + private log_; + private stats_; + private everConnected_; + private isClosed_; + private nodeAdmin; + /** + * @param connId identifier for this transport + * @param repoInfo The info for the websocket endpoint. + * @param applicationId The Firebase App ID for this project. + * @param appCheckToken The App Check Token for this client. + * @param authToken The Auth Token for this client. + * @param transportSessionId Optional transportSessionId if this is connecting + * to an existing transport session + * @param lastSessionId Optional lastSessionId if there was a previous + * connection + */ + constructor(connId: string, repoInfo: RepoInfo, applicationId?: string, appCheckToken?: string, authToken?: string, transportSessionId?: string, lastSessionId?: string); + /** + * @param repoInfo - The info for the websocket endpoint. + * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport + * session + * @param lastSessionId - Optional lastSessionId if there was a previous connection + * @returns connection url + */ + private static connectionURL_; + /** + * @param onMessage - Callback when messages arrive + * @param onDisconnect - Callback with connection lost. + */ + open(onMessage: (msg: {}) => void, onDisconnect: (a?: boolean) => void): void; + /** + * No-op for websockets, we don't need to do anything once the connection is confirmed as open + */ + start(): void; + static forceDisallow_: boolean; + static forceDisallow(): void; + static isAvailable(): boolean; + /** + * Number of response before we consider the connection "healthy." + */ + static responsesRequiredToBeHealthy: number; + /** + * Time to wait for the connection te become healthy before giving up. + */ + static healthyTimeout: number; + /** + * Returns true if we previously failed to connect with this transport. + */ + static previouslyFailed(): boolean; + markConnectionHealthy(): void; + private appendFrame_; + /** + * @param frameCount - The number of frames we are expecting from the server + */ + private handleNewFrameCount_; + /** + * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1 + * @returns Any remaining data to be process, or null if there is none + */ + private extractFrameCount_; + /** + * Process a websocket frame that has arrived from the server. + * @param mess - The frame data + */ + handleIncomingFrame(mess: { + [k: string]: unknown; + }): void; + /** + * Send a message to the server + * @param data - The JSON object to transmit + */ + send(data: {}): void; + private shutdown_; + private onClosed_; + /** + * External-facing close handler. + * Close the websocket and kill the connection. + */ + close(): void; + /** + * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after + * the last activity. + */ + resetKeepAlive(): void; + /** + * Send a string over the websocket. + * + * @param str - String to send. + */ + private sendString_; +} diff --git a/node_modules/@firebase/database/dist/src/realtime/polling/PacketReceiver.d.ts b/node_modules/@firebase/database/dist/src/realtime/polling/PacketReceiver.d.ts new file mode 100644 index 0000000..78be316 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/realtime/polling/PacketReceiver.d.ts @@ -0,0 +1,38 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This class ensures the packets from the server arrive in order + * This class takes data from the server and ensures it gets passed into the callbacks in order. + */ +export declare class PacketReceiver { + private onMessage_; + pendingResponses: unknown[]; + currentResponseNum: number; + closeAfterResponse: number; + onClose: (() => void) | null; + /** + * @param onMessage_ + */ + constructor(onMessage_: (a: {}) => void); + closeAfter(responseNum: number, callback: () => void): void; + /** + * Each message from the server comes with a response number, and an array of data. The responseNumber + * allows us to ensure that we process them in the right order, since we can't be guaranteed that all + * browsers will respond in the same order as the requests we sent + */ + handleResponse(requestNum: number, data: unknown[]): void; +} diff --git a/node_modules/@firebase/database/dist/src/register.d.ts b/node_modules/@firebase/database/dist/src/register.d.ts new file mode 100644 index 0000000..4461564 --- /dev/null +++ b/node_modules/@firebase/database/dist/src/register.d.ts @@ -0,0 +1 @@ +export declare function registerDatabase(variant?: string): void; diff --git a/node_modules/@firebase/database/dist/src/tsdoc-metadata.json b/node_modules/@firebase/database/dist/src/tsdoc-metadata.json new file mode 100644 index 0000000..6af1f6a --- /dev/null +++ b/node_modules/@firebase/database/dist/src/tsdoc-metadata.json @@ -0,0 +1,11 @@ +// This file is read by tools that parse documentation comments conforming to the TSDoc standard. +// It should be published with your NPM package. It should not be tracked by Git. +{ + "tsdocVersion": "0.12", + "toolPackages": [ + { + "packageName": "@microsoft/api-extractor", + "packageVersion": "0.1.2" + } + ] +} diff --git a/node_modules/@firebase/database/dist/test/helpers/EventAccumulator.d.ts b/node_modules/@firebase/database/dist/test/helpers/EventAccumulator.d.ts new file mode 100644 index 0000000..c80b734 --- /dev/null +++ b/node_modules/@firebase/database/dist/test/helpers/EventAccumulator.d.ts @@ -0,0 +1,35 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const EventAccumulatorFactory: { + waitsForCount: (maxCount: any) => EventAccumulator; + waitsForExactCount: (maxCount: any) => EventAccumulator; +}; +export declare class EventAccumulator { + condition: Function; + eventData: any[]; + promise: any; + resolve: any; + reject: any; + private onResetFxn; + private onEventFxn; + constructor(condition: Function); + addEvent(eventData?: any): void; + reset(condition?: Function): void; + onEvent(cb: Function): void; + onReset(cb: Function): void; + _testCondition(): any; +} diff --git a/node_modules/@firebase/database/dist/test/helpers/syncpoint-util.d.ts b/node_modules/@firebase/database/dist/test/helpers/syncpoint-util.d.ts new file mode 100644 index 0000000..c02a122 --- /dev/null +++ b/node_modules/@firebase/database/dist/test/helpers/syncpoint-util.d.ts @@ -0,0 +1,29 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app'; +import { ListenProvider } from '../../src/core/SyncTree'; +import { Path } from '../../src/core/util/Path'; +export declare class SyncPointTestParser { + app: FirebaseApp; + listens_: any; + listenProvider_: ListenProvider; + private syncTree_; + constructor(); + getTestPath(optBasePath: string | string[], path?: string): Path; + private testRunner; + defineTest(spec: any): void; +} diff --git a/node_modules/@firebase/database/dist/test/helpers/util.d.ts b/node_modules/@firebase/database/dist/test/helpers/util.d.ts new file mode 100644 index 0000000..1ddcdcd --- /dev/null +++ b/node_modules/@firebase/database/dist/test/helpers/util.d.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Database, DatabaseReference } from '../../src'; +import { Path } from '../../src/core/util/Path'; +import { EventAccumulator } from './EventAccumulator'; +export declare const TEST_PROJECT: any; +export declare const EMULATOR_PORT: string; +export declare const USE_EMULATOR: boolean; +export declare function getFreshRepo(path: Path): DatabaseReference; +export declare const DATABASE_ADDRESS: any; +export declare const DATABASE_URL: any; +export declare function testRepoInfo(url: any): import("../../src/core/RepoInfo").RepoInfo; +export declare function repoInfoForConnectionTest(): import("../../src/core/RepoInfo").RepoInfo; +export declare function shuffle(arr: any, randFn?: () => number): void; +export declare function waitFor(waitTimeInMS: number): Promise; +export declare function getUniqueRef(db: Database): DatabaseReference; +export declare function getRWRefs(db: Database): { + readerRef: DatabaseReference; + writerRef: DatabaseReference; +}; +export declare function writeAndValidate(writerRef: DatabaseReference, readerRef: DatabaseReference, toWrite: unknown, ec: EventAccumulator): Promise; +export declare function waitUntil(cb: () => boolean, maxRetries?: number): Promise; diff --git a/node_modules/@firebase/database/package.json b/node_modules/@firebase/database/package.json new file mode 100644 index 0000000..bcd9084 --- /dev/null +++ b/node_modules/@firebase/database/package.json @@ -0,0 +1,83 @@ +{ + "name": "@firebase/database", + "version": "1.1.0", + "description": "", + "author": "Firebase (https://firebase.google.com/)", + "main": "dist/index.node.cjs.js", + "browser": "dist/index.esm.js", + "module": "dist/index.esm.js", + "standalone": "dist/index.standalone.js", + "exports": { + ".": { + "types": "./dist/public.d.ts", + "node": { + "import": "./dist/node-esm/index.node.esm.js", + "require": "./dist/index.node.cjs.js" + }, + "standalone": "./dist/index.standalone.js", + "browser": { + "require": "./dist/index.cjs.js", + "import": "./dist/index.esm.js" + }, + "default": "./dist/index.esm.js" + }, + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "scripts": { + "lint": "eslint -c .eslintrc.js '**/*.ts' --ignore-path '../../.gitignore'", + "lint:fix": "eslint --fix -c .eslintrc.js '**/*.ts' --ignore-path '../../.gitignore'", + "prettier": "prettier --write '*.js' '*.ts' '@(src|test)/**/*.ts'", + "build": "rollup -c rollup.config.js && yarn api-report", + "build:deps": "lerna run --scope @firebase/'{app,database}' --include-dependencies build", + "dev": "rollup -c -w", + "test": "run-p --npm-path npm lint test:emulator", + "test:ci": "node ../../scripts/run_tests_in_ci.js -s test:emulator", + "test:all": "run-p --npm-path npm lint test:browser test:node", + "test:browser": "karma start", + "test:node": "TS_NODE_FILES=true TS_NODE_CACHE=NO TS_NODE_COMPILER_OPTIONS='{\"module\":\"commonjs\"}' nyc --reporter lcovonly -- mocha 'test/{,!(browser)/**/}*.test.ts' --file src/index.node.ts --config ../../config/mocharc.node.js", + "test:emulator": "ts-node --compiler-options='{\"module\":\"commonjs\"}' ../../scripts/emulator-testing/database-test-runner.ts", + "trusted-type-check": "tsec -p tsconfig.json --noEmit", + "api-report": "TS_NODE_COMPILER_OPTIONS='{\"module\":\"commonjs\"}' ts-node ../../repo-scripts/prune-dts/extract-public-api.ts --package database --packageRoot . --typescriptDts ./dist/src/index.d.ts --rollupDts ./dist/private.d.ts --untrimmedRollupDts ./dist/internal.d.ts --publicDts ./dist/public.d.ts && yarn api-report:api-json", + "api-report:api-json": "rm -rf temp && api-extractor run --local --verbose", + "doc": "api-documenter markdown --input temp --output docs", + "typings:public": "node ../../scripts/build/use_typings.js ./dist/public.d.ts" + }, + "license": "Apache-2.0", + "peerDependencies": {}, + "dependencies": { + "@firebase/logger": "0.5.0", + "@firebase/util": "1.13.0", + "@firebase/component": "0.7.0", + "@firebase/app-check-interop-types": "0.3.3", + "@firebase/auth-interop-types": "0.2.4", + "faye-websocket": "0.11.4", + "tslib": "^2.1.0" + }, + "devDependencies": { + "@firebase/app": "0.14.0", + "rollup": "2.79.2", + "rollup-plugin-typescript2": "0.36.0", + "typescript": "5.5.4" + }, + "repository": { + "directory": "packages/database", + "type": "git", + "url": "git+https://github.com/firebase/firebase-js-sdk.git" + }, + "bugs": { + "url": "https://github.com/firebase/firebase-js-sdk/issues" + }, + "typings": "./dist/public.d.ts", + "nyc": { + "extension": [ + ".ts" + ], + "reportDir": "./coverage/node" + }, + "engines": { + "node": ">=20.0.0" + } +} diff --git a/node_modules/@firebase/logger/README.md b/node_modules/@firebase/logger/README.md new file mode 100644 index 0000000..69c1642 --- /dev/null +++ b/node_modules/@firebase/logger/README.md @@ -0,0 +1,40 @@ +# @firebase/logger + +This package serves as the base of all logging in the JS SDK. Any logging that +is intended to be visible to Firebase end developers should go through this +module. + +## Basic Usage + +Firebase components should import the `Logger` class and instantiate a new +instance by passing a component name (e.g. `@firebase/`) to the +constructor. + +_e.g._ + +```typescript +import { Logger } from '@firebase/logger'; + +const logClient = new Logger(`@firebase/`); +``` + +Each `Logger` instance supports 5 log functions each to be used in a specific +instance: + +- `debug`: Internal logs; use this to allow developers to send us their debug + logs for us to be able to diagnose an issue. +- `log`: Use to inform your user about things they may need to know. +- `info`: Use if you have to inform the user about something that they need to + take a concrete action on. Once they take that action, the log should go away. +- `warn`: Use when a product feature may stop functioning correctly; unexpected + scenario. +- `error`: Only use when user App would stop functioning correctly - super rare! + +## Log Format + +Each log will be formatted in the following manner: + +```typescript +`[${new Date()}] ${COMPONENT_NAME}: ${...args}` +``` + diff --git a/node_modules/@firebase/logger/dist/esm/index.d.ts b/node_modules/@firebase/logger/dist/esm/index.d.ts new file mode 100644 index 0000000..35f2155 --- /dev/null +++ b/node_modules/@firebase/logger/dist/esm/index.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { setLogLevel, Logger, LogLevel, LogHandler, setUserLogHandler, LogCallback, LogLevelString, LogOptions } from './src/logger'; diff --git a/node_modules/@firebase/logger/dist/esm/index.esm.js b/node_modules/@firebase/logger/dist/esm/index.esm.js new file mode 100644 index 0000000..078e952 --- /dev/null +++ b/node_modules/@firebase/logger/dist/esm/index.esm.js @@ -0,0 +1,219 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A container for all of the Logger instances + */ +const instances = []; +/** + * The JS SDK supports 5 log levels and also allows a user the ability to + * silence the logs altogether. + * + * The order is a follows: + * DEBUG < VERBOSE < INFO < WARN < ERROR + * + * All of the log types above the current log level will be captured (i.e. if + * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and + * `VERBOSE` logs will not) + */ +var LogLevel; +(function (LogLevel) { + LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG"; + LogLevel[LogLevel["VERBOSE"] = 1] = "VERBOSE"; + LogLevel[LogLevel["INFO"] = 2] = "INFO"; + LogLevel[LogLevel["WARN"] = 3] = "WARN"; + LogLevel[LogLevel["ERROR"] = 4] = "ERROR"; + LogLevel[LogLevel["SILENT"] = 5] = "SILENT"; +})(LogLevel || (LogLevel = {})); +const levelStringToEnum = { + 'debug': LogLevel.DEBUG, + 'verbose': LogLevel.VERBOSE, + 'info': LogLevel.INFO, + 'warn': LogLevel.WARN, + 'error': LogLevel.ERROR, + 'silent': LogLevel.SILENT +}; +/** + * The default log level + */ +const defaultLogLevel = LogLevel.INFO; +/** + * By default, `console.debug` is not displayed in the developer console (in + * chrome). To avoid forcing users to have to opt-in to these logs twice + * (i.e. once for firebase, and once in the console), we are sending `DEBUG` + * logs to the `console.log` function. + */ +const ConsoleMethod = { + [LogLevel.DEBUG]: 'log', + [LogLevel.VERBOSE]: 'log', + [LogLevel.INFO]: 'info', + [LogLevel.WARN]: 'warn', + [LogLevel.ERROR]: 'error' +}; +/** + * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR + * messages on to their corresponding console counterparts (if the log method + * is supported by the current log level) + */ +const defaultLogHandler = (instance, logType, ...args) => { + if (logType < instance.logLevel) { + return; + } + const now = new Date().toISOString(); + const method = ConsoleMethod[logType]; + if (method) { + console[method](`[${now}] ${instance.name}:`, ...args); + } + else { + throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`); + } +}; +class Logger { + /** + * Gives you an instance of a Logger to capture messages according to + * Firebase's logging scheme. + * + * @param name The name that the logs will be associated with + */ + constructor(name) { + this.name = name; + /** + * The log level of the given Logger instance. + */ + this._logLevel = defaultLogLevel; + /** + * The main (internal) log handler for the Logger instance. + * Can be set to a new function in internal package code but not by user. + */ + this._logHandler = defaultLogHandler; + /** + * The optional, additional, user-defined log handler for the Logger instance. + */ + this._userLogHandler = null; + /** + * Capture the current instance for later use + */ + instances.push(this); + } + get logLevel() { + return this._logLevel; + } + set logLevel(val) { + if (!(val in LogLevel)) { + throw new TypeError(`Invalid value "${val}" assigned to \`logLevel\``); + } + this._logLevel = val; + } + // Workaround for setter/getter having to be the same type. + setLogLevel(val) { + this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val; + } + get logHandler() { + return this._logHandler; + } + set logHandler(val) { + if (typeof val !== 'function') { + throw new TypeError('Value assigned to `logHandler` must be a function'); + } + this._logHandler = val; + } + get userLogHandler() { + return this._userLogHandler; + } + set userLogHandler(val) { + this._userLogHandler = val; + } + /** + * The functions below are all based on the `console` interface + */ + debug(...args) { + this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args); + this._logHandler(this, LogLevel.DEBUG, ...args); + } + log(...args) { + this._userLogHandler && + this._userLogHandler(this, LogLevel.VERBOSE, ...args); + this._logHandler(this, LogLevel.VERBOSE, ...args); + } + info(...args) { + this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args); + this._logHandler(this, LogLevel.INFO, ...args); + } + warn(...args) { + this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args); + this._logHandler(this, LogLevel.WARN, ...args); + } + error(...args) { + this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args); + this._logHandler(this, LogLevel.ERROR, ...args); + } +} +function setLogLevel(level) { + instances.forEach(inst => { + inst.setLogLevel(level); + }); +} +function setUserLogHandler(logCallback, options) { + for (const instance of instances) { + let customLogLevel = null; + if (options && options.level) { + customLogLevel = levelStringToEnum[options.level]; + } + if (logCallback === null) { + instance.userLogHandler = null; + } + else { + instance.userLogHandler = (instance, level, ...args) => { + const message = args + .map(arg => { + if (arg == null) { + return null; + } + else if (typeof arg === 'string') { + return arg; + } + else if (typeof arg === 'number' || typeof arg === 'boolean') { + return arg.toString(); + } + else if (arg instanceof Error) { + return arg.message; + } + else { + try { + return JSON.stringify(arg); + } + catch (ignored) { + return null; + } + } + }) + .filter(arg => arg) + .join(' '); + if (level >= (customLogLevel ?? instance.logLevel)) { + logCallback({ + level: LogLevel[level].toLowerCase(), + message, + args, + type: instance.name + }); + } + }; + } + } +} + +export { LogLevel, Logger, setLogLevel, setUserLogHandler }; +//# sourceMappingURL=index.esm.js.map diff --git a/node_modules/@firebase/logger/dist/esm/index.esm.js.map b/node_modules/@firebase/logger/dist/esm/index.esm.js.map new file mode 100644 index 0000000..cac2e41 --- /dev/null +++ b/node_modules/@firebase/logger/dist/esm/index.esm.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.esm.js","sources":["../../src/logger.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type LogLevelString =\n | 'debug'\n | 'verbose'\n | 'info'\n | 'warn'\n | 'error'\n | 'silent';\n\nexport interface LogOptions {\n level: LogLevelString;\n}\n\nexport type LogCallback = (callbackParams: LogCallbackParams) => void;\n\nexport interface LogCallbackParams {\n level: LogLevelString;\n message: string;\n args: unknown[];\n type: string;\n}\n\n/**\n * A container for all of the Logger instances\n */\nexport const instances: Logger[] = [];\n\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nexport enum LogLevel {\n DEBUG,\n VERBOSE,\n INFO,\n WARN,\n ERROR,\n SILENT\n}\n\nconst levelStringToEnum: { [key in LogLevelString]: LogLevel } = {\n 'debug': LogLevel.DEBUG,\n 'verbose': LogLevel.VERBOSE,\n 'info': LogLevel.INFO,\n 'warn': LogLevel.WARN,\n 'error': LogLevel.ERROR,\n 'silent': LogLevel.SILENT\n};\n\n/**\n * The default log level\n */\nconst defaultLogLevel: LogLevel = LogLevel.INFO;\n\n/**\n * We allow users the ability to pass their own log handler. We will pass the\n * type of log, the current log level, and any other arguments passed (i.e. the\n * messages that the user wants to log) to this function.\n */\nexport type LogHandler = (\n loggerInstance: Logger,\n logType: LogLevel,\n ...args: unknown[]\n) => void;\n\n/**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\nconst ConsoleMethod = {\n [LogLevel.DEBUG]: 'log',\n [LogLevel.VERBOSE]: 'log',\n [LogLevel.INFO]: 'info',\n [LogLevel.WARN]: 'warn',\n [LogLevel.ERROR]: 'error'\n};\n\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nconst defaultLogHandler: LogHandler = (instance, logType, ...args): void => {\n if (logType < instance.logLevel) {\n return;\n }\n const now = new Date().toISOString();\n const method = ConsoleMethod[logType as keyof typeof ConsoleMethod];\n if (method) {\n console[method as 'log' | 'info' | 'warn' | 'error'](\n `[${now}] ${instance.name}:`,\n ...args\n );\n } else {\n throw new Error(\n `Attempted to log a message with an invalid logType (value: ${logType})`\n );\n }\n};\n\nexport class Logger {\n /**\n * Gives you an instance of a Logger to capture messages according to\n * Firebase's logging scheme.\n *\n * @param name The name that the logs will be associated with\n */\n constructor(public name: string) {\n /**\n * Capture the current instance for later use\n */\n instances.push(this);\n }\n\n /**\n * The log level of the given Logger instance.\n */\n private _logLevel = defaultLogLevel;\n\n get logLevel(): LogLevel {\n return this._logLevel;\n }\n\n set logLevel(val: LogLevel) {\n if (!(val in LogLevel)) {\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\n }\n this._logLevel = val;\n }\n\n // Workaround for setter/getter having to be the same type.\n setLogLevel(val: LogLevel | LogLevelString): void {\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\n }\n\n /**\n * The main (internal) log handler for the Logger instance.\n * Can be set to a new function in internal package code but not by user.\n */\n private _logHandler: LogHandler = defaultLogHandler;\n get logHandler(): LogHandler {\n return this._logHandler;\n }\n set logHandler(val: LogHandler) {\n if (typeof val !== 'function') {\n throw new TypeError('Value assigned to `logHandler` must be a function');\n }\n this._logHandler = val;\n }\n\n /**\n * The optional, additional, user-defined log handler for the Logger instance.\n */\n private _userLogHandler: LogHandler | null = null;\n get userLogHandler(): LogHandler | null {\n return this._userLogHandler;\n }\n set userLogHandler(val: LogHandler | null) {\n this._userLogHandler = val;\n }\n\n /**\n * The functions below are all based on the `console` interface\n */\n\n debug(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\n this._logHandler(this, LogLevel.DEBUG, ...args);\n }\n log(...args: unknown[]): void {\n this._userLogHandler &&\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\n this._logHandler(this, LogLevel.VERBOSE, ...args);\n }\n info(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\n this._logHandler(this, LogLevel.INFO, ...args);\n }\n warn(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\n this._logHandler(this, LogLevel.WARN, ...args);\n }\n error(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\n this._logHandler(this, LogLevel.ERROR, ...args);\n }\n}\n\nexport function setLogLevel(level: LogLevelString | LogLevel): void {\n instances.forEach(inst => {\n inst.setLogLevel(level);\n });\n}\n\nexport function setUserLogHandler(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n for (const instance of instances) {\n let customLogLevel: LogLevel | null = null;\n if (options && options.level) {\n customLogLevel = levelStringToEnum[options.level];\n }\n if (logCallback === null) {\n instance.userLogHandler = null;\n } else {\n instance.userLogHandler = (\n instance: Logger,\n level: LogLevel,\n ...args: unknown[]\n ) => {\n const message = args\n .map(arg => {\n if (arg == null) {\n return null;\n } else if (typeof arg === 'string') {\n return arg;\n } else if (typeof arg === 'number' || typeof arg === 'boolean') {\n return arg.toString();\n } else if (arg instanceof Error) {\n return arg.message;\n } else {\n try {\n return JSON.stringify(arg);\n } catch (ignored) {\n return null;\n }\n }\n })\n .filter(arg => arg)\n .join(' ');\n if (level >= (customLogLevel ?? instance.logLevel)) {\n logCallback({\n level: LogLevel[level].toLowerCase() as LogLevelString,\n message,\n args,\n type: instance.name\n });\n }\n };\n }\n }\n}\n"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;AAeG;AAuBH;;AAEG;AACI,MAAM,SAAS,GAAa,EAAE,CAAC;AAEtC;;;;;;;;;;AAUG;IACS,SAOX;AAPD,CAAA,UAAY,QAAQ,EAAA;AAClB,IAAA,QAAA,CAAA,QAAA,CAAA,OAAA,CAAA,GAAA,CAAA,CAAA,GAAA,OAAK,CAAA;AACL,IAAA,QAAA,CAAA,QAAA,CAAA,SAAA,CAAA,GAAA,CAAA,CAAA,GAAA,SAAO,CAAA;AACP,IAAA,QAAA,CAAA,QAAA,CAAA,MAAA,CAAA,GAAA,CAAA,CAAA,GAAA,MAAI,CAAA;AACJ,IAAA,QAAA,CAAA,QAAA,CAAA,MAAA,CAAA,GAAA,CAAA,CAAA,GAAA,MAAI,CAAA;AACJ,IAAA,QAAA,CAAA,QAAA,CAAA,OAAA,CAAA,GAAA,CAAA,CAAA,GAAA,OAAK,CAAA;AACL,IAAA,QAAA,CAAA,QAAA,CAAA,QAAA,CAAA,GAAA,CAAA,CAAA,GAAA,QAAM,CAAA;AACR,CAAC,EAPW,QAAQ,KAAR,QAAQ,GAOnB,EAAA,CAAA,CAAA,CAAA;AAED,MAAM,iBAAiB,GAA0C;IAC/D,OAAO,EAAE,QAAQ,CAAC,KAAK;IACvB,SAAS,EAAE,QAAQ,CAAC,OAAO;IAC3B,MAAM,EAAE,QAAQ,CAAC,IAAI;IACrB,MAAM,EAAE,QAAQ,CAAC,IAAI;IACrB,OAAO,EAAE,QAAQ,CAAC,KA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;gBACb,IAAI,KAAK,KAAK,cAAc,IAAI,QAAQ,CAAC,QAAQ,CAAC,EAAE;AAClD,oBAAA,WAAW,CAAC;AACV,wBAAA,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,CAAC,WAAW,EAAoB;wBACtD,OAAO;wBACP,IAAI;wBACJ,IAAI,EAAE,QAAQ,CAAC,IAAI;AACpB,qBAAA,CAAC,CAAC;iBACJ;AACH,aAAC,CAAC;SACH;KACF;AACH;;;;"} \ No newline at end of file diff --git a/node_modules/@firebase/logger/dist/esm/package.json b/node_modules/@firebase/logger/dist/esm/package.json new file mode 100644 index 0000000..7c34deb --- /dev/null +++ b/node_modules/@firebase/logger/dist/esm/package.json @@ -0,0 +1 @@ +{"type":"module"} \ No newline at end of file diff --git a/node_modules/@firebase/logger/dist/esm/src/logger.d.ts b/node_modules/@firebase/logger/dist/esm/src/logger.d.ts new file mode 100644 index 0000000..a2df808 --- /dev/null +++ b/node_modules/@firebase/logger/dist/esm/src/logger.d.ts @@ -0,0 +1,96 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export type LogLevelString = 'debug' | 'verbose' | 'info' | 'warn' | 'error' | 'silent'; +export interface LogOptions { + level: LogLevelString; +} +export type LogCallback = (callbackParams: LogCallbackParams) => void; +export interface LogCallbackParams { + level: LogLevelString; + message: string; + args: unknown[]; + type: string; +} +/** + * A container for all of the Logger instances + */ +export declare const instances: Logger[]; +/** + * The JS SDK supports 5 log levels and also allows a user the ability to + * silence the logs altogether. + * + * The order is a follows: + * DEBUG < VERBOSE < INFO < WARN < ERROR + * + * All of the log types above the current log level will be captured (i.e. if + * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and + * `VERBOSE` logs will not) + */ +export declare enum LogLevel { + DEBUG = 0, + VERBOSE = 1, + INFO = 2, + WARN = 3, + ERROR = 4, + SILENT = 5 +} +/** + * We allow users the ability to pass their own log handler. We will pass the + * type of log, the current log level, and any other arguments passed (i.e. the + * messages that the user wants to log) to this function. + */ +export type LogHandler = (loggerInstance: Logger, logType: LogLevel, ...args: unknown[]) => void; +export declare class Logger { + name: string; + /** + * Gives you an instance of a Logger to capture messages according to + * Firebase's logging scheme. + * + * @param name The name that the logs will be associated with + */ + constructor(name: string); + /** + * The log level of the given Logger instance. + */ + private _logLevel; + get logLevel(): LogLevel; + set logLevel(val: LogLevel); + setLogLevel(val: LogLevel | LogLevelString): void; + /** + * The main (internal) log handler for the Logger instance. + * Can be set to a new function in internal package code but not by user. + */ + private _logHandler; + get logHandler(): LogHandler; + set logHandler(val: LogHandler); + /** + * The optional, additional, user-defined log handler for the Logger instance. + */ + private _userLogHandler; + get userLogHandler(): LogHandler | null; + set userLogHandler(val: LogHandler | null); + /** + * The functions below are all based on the `console` interface + */ + debug(...args: unknown[]): void; + log(...args: unknown[]): void; + info(...args: unknown[]): void; + warn(...args: unknown[]): void; + error(...args: unknown[]): void; +} +export declare function setLogLevel(level: LogLevelString | LogLevel): void; +export declare function setUserLogHandler(logCallback: LogCallback | null, options?: LogOptions): void; diff --git a/node_modules/@firebase/logger/dist/esm/test/custom-logger.test.d.ts b/node_modules/@firebase/logger/dist/esm/test/custom-logger.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/node_modules/@firebase/logger/dist/esm/test/custom-logger.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/logger/dist/esm/test/logger.test.d.ts b/node_modules/@firebase/logger/dist/esm/test/logger.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/node_modules/@firebase/logger/dist/esm/test/logger.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/logger/dist/index.cjs.js b/node_modules/@firebase/logger/dist/index.cjs.js new file mode 100644 index 0000000..30dbcd2 --- /dev/null +++ b/node_modules/@firebase/logger/dist/index.cjs.js @@ -0,0 +1,225 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A container for all of the Logger instances + */ +const instances = []; +/** + * The JS SDK supports 5 log levels and also allows a user the ability to + * silence the logs altogether. + * + * The order is a follows: + * DEBUG < VERBOSE < INFO < WARN < ERROR + * + * All of the log types above the current log level will be captured (i.e. if + * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and + * `VERBOSE` logs will not) + */ +exports.LogLevel = void 0; +(function (LogLevel) { + LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG"; + LogLevel[LogLevel["VERBOSE"] = 1] = "VERBOSE"; + LogLevel[LogLevel["INFO"] = 2] = "INFO"; + LogLevel[LogLevel["WARN"] = 3] = "WARN"; + LogLevel[LogLevel["ERROR"] = 4] = "ERROR"; + LogLevel[LogLevel["SILENT"] = 5] = "SILENT"; +})(exports.LogLevel || (exports.LogLevel = {})); +const levelStringToEnum = { + 'debug': exports.LogLevel.DEBUG, + 'verbose': exports.LogLevel.VERBOSE, + 'info': exports.LogLevel.INFO, + 'warn': exports.LogLevel.WARN, + 'error': exports.LogLevel.ERROR, + 'silent': exports.LogLevel.SILENT +}; +/** + * The default log level + */ +const defaultLogLevel = exports.LogLevel.INFO; +/** + * By default, `console.debug` is not displayed in the developer console (in + * chrome). To avoid forcing users to have to opt-in to these logs twice + * (i.e. once for firebase, and once in the console), we are sending `DEBUG` + * logs to the `console.log` function. + */ +const ConsoleMethod = { + [exports.LogLevel.DEBUG]: 'log', + [exports.LogLevel.VERBOSE]: 'log', + [exports.LogLevel.INFO]: 'info', + [exports.LogLevel.WARN]: 'warn', + [exports.LogLevel.ERROR]: 'error' +}; +/** + * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR + * messages on to their corresponding console counterparts (if the log method + * is supported by the current log level) + */ +const defaultLogHandler = (instance, logType, ...args) => { + if (logType < instance.logLevel) { + return; + } + const now = new Date().toISOString(); + const method = ConsoleMethod[logType]; + if (method) { + console[method](`[${now}] ${instance.name}:`, ...args); + } + else { + throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`); + } +}; +class Logger { + /** + * Gives you an instance of a Logger to capture messages according to + * Firebase's logging scheme. + * + * @param name The name that the logs will be associated with + */ + constructor(name) { + this.name = name; + /** + * The log level of the given Logger instance. + */ + this._logLevel = defaultLogLevel; + /** + * The main (internal) log handler for the Logger instance. + * Can be set to a new function in internal package code but not by user. + */ + this._logHandler = defaultLogHandler; + /** + * The optional, additional, user-defined log handler for the Logger instance. + */ + this._userLogHandler = null; + /** + * Capture the current instance for later use + */ + instances.push(this); + } + get logLevel() { + return this._logLevel; + } + set logLevel(val) { + if (!(val in exports.LogLevel)) { + throw new TypeError(`Invalid value "${val}" assigned to \`logLevel\``); + } + this._logLevel = val; + } + // Workaround for setter/getter having to be the same type. + setLogLevel(val) { + this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val; + } + get logHandler() { + return this._logHandler; + } + set logHandler(val) { + if (typeof val !== 'function') { + throw new TypeError('Value assigned to `logHandler` must be a function'); + } + this._logHandler = val; + } + get userLogHandler() { + return this._userLogHandler; + } + set userLogHandler(val) { + this._userLogHandler = val; + } + /** + * The functions below are all based on the `console` interface + */ + debug(...args) { + this._userLogHandler && this._userLogHandler(this, exports.LogLevel.DEBUG, ...args); + this._logHandler(this, exports.LogLevel.DEBUG, ...args); + } + log(...args) { + this._userLogHandler && + this._userLogHandler(this, exports.LogLevel.VERBOSE, ...args); + this._logHandler(this, exports.LogLevel.VERBOSE, ...args); + } + info(...args) { + this._userLogHandler && this._userLogHandler(this, exports.LogLevel.INFO, ...args); + this._logHandler(this, exports.LogLevel.INFO, ...args); + } + warn(...args) { + this._userLogHandler && this._userLogHandler(this, exports.LogLevel.WARN, ...args); + this._logHandler(this, exports.LogLevel.WARN, ...args); + } + error(...args) { + this._userLogHandler && this._userLogHandler(this, exports.LogLevel.ERROR, ...args); + this._logHandler(this, exports.LogLevel.ERROR, ...args); + } +} +function setLogLevel(level) { + instances.forEach(inst => { + inst.setLogLevel(level); + }); +} +function setUserLogHandler(logCallback, options) { + for (const instance of instances) { + let customLogLevel = null; + if (options && options.level) { + customLogLevel = levelStringToEnum[options.level]; + } + if (logCallback === null) { + instance.userLogHandler = null; + } + else { + instance.userLogHandler = (instance, level, ...args) => { + const message = args + .map(arg => { + if (arg == null) { + return null; + } + else if (typeof arg === 'string') { + return arg; + } + else if (typeof arg === 'number' || typeof arg === 'boolean') { + return arg.toString(); + } + else if (arg instanceof Error) { + return arg.message; + } + else { + try { + return JSON.stringify(arg); + } + catch (ignored) { + return null; + } + } + }) + .filter(arg => arg) + .join(' '); + if (level >= (customLogLevel ?? instance.logLevel)) { + logCallback({ + level: exports.LogLevel[level].toLowerCase(), + message, + args, + type: instance.name + }); + } + }; + } + } +} + +exports.Logger = Logger; +exports.setLogLevel = setLogLevel; +exports.setUserLogHandler = setUserLogHandler; +//# sourceMappingURL=index.cjs.js.map diff --git a/node_modules/@firebase/logger/dist/index.cjs.js.map b/node_modules/@firebase/logger/dist/index.cjs.js.map new file mode 100644 index 0000000..c94b470 --- /dev/null +++ b/node_modules/@firebase/logger/dist/index.cjs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.cjs.js","sources":["../src/logger.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type LogLevelString =\n | 'debug'\n | 'verbose'\n | 'info'\n | 'warn'\n | 'error'\n | 'silent';\n\nexport interface LogOptions {\n level: LogLevelString;\n}\n\nexport type LogCallback = (callbackParams: LogCallbackParams) => void;\n\nexport interface LogCallbackParams {\n level: LogLevelString;\n message: string;\n args: unknown[];\n type: string;\n}\n\n/**\n * A container for all of the Logger instances\n */\nexport const instances: Logger[] = [];\n\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nexport enum LogLevel {\n DEBUG,\n VERBOSE,\n INFO,\n WARN,\n ERROR,\n SILENT\n}\n\nconst levelStringToEnum: { [key in LogLevelString]: LogLevel } = {\n 'debug': LogLevel.DEBUG,\n 'verbose': LogLevel.VERBOSE,\n 'info': LogLevel.INFO,\n 'warn': LogLevel.WARN,\n 'error': LogLevel.ERROR,\n 'silent': LogLevel.SILENT\n};\n\n/**\n * The default log level\n */\nconst defaultLogLevel: LogLevel = LogLevel.INFO;\n\n/**\n * We allow users the ability to pass their own log handler. We will pass the\n * type of log, the current log level, and any other arguments passed (i.e. the\n * messages that the user wants to log) to this function.\n */\nexport type LogHandler = (\n loggerInstance: Logger,\n logType: LogLevel,\n ...args: unknown[]\n) => void;\n\n/**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\nconst ConsoleMethod = {\n [LogLevel.DEBUG]: 'log',\n [LogLevel.VERBOSE]: 'log',\n [LogLevel.INFO]: 'info',\n [LogLevel.WARN]: 'warn',\n [LogLevel.ERROR]: 'error'\n};\n\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nconst defaultLogHandler: LogHandler = (instance, logType, ...args): void => {\n if (logType < instance.logLevel) {\n return;\n }\n const now = new Date().toISOString();\n const method = ConsoleMethod[logType as keyof typeof ConsoleMethod];\n if (method) {\n console[method as 'log' | 'info' | 'warn' | 'error'](\n `[${now}] ${instance.name}:`,\n ...args\n );\n } else {\n throw new Error(\n `Attempted to log a message with an invalid logType (value: ${logType})`\n );\n }\n};\n\nexport class Logger {\n /**\n * Gives you an instance of a Logger to capture messages according to\n * Firebase's logging scheme.\n *\n * @param name The name that the logs will be associated with\n */\n constructor(public name: string) {\n /**\n * Capture the current instance for later use\n */\n instances.push(this);\n }\n\n /**\n * The log level of the given Logger instance.\n */\n private _logLevel = defaultLogLevel;\n\n get logLevel(): LogLevel {\n return this._logLevel;\n }\n\n set logLevel(val: LogLevel) {\n if (!(val in LogLevel)) {\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\n }\n this._logLevel = val;\n }\n\n // Workaround for setter/getter having to be the same type.\n setLogLevel(val: LogLevel | LogLevelString): void {\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\n }\n\n /**\n * The main (internal) log handler for the Logger instance.\n * Can be set to a new function in internal package code but not by user.\n */\n private _logHandler: LogHandler = defaultLogHandler;\n get logHandler(): LogHandler {\n return this._logHandler;\n }\n set logHandler(val: LogHandler) {\n if (typeof val !== 'function') {\n throw new TypeError('Value assigned to `logHandler` must be a function');\n }\n this._logHandler = val;\n }\n\n /**\n * The optional, additional, user-defined log handler for the Logger instance.\n */\n private _userLogHandler: LogHandler | null = null;\n get userLogHandler(): LogHandler | null {\n return this._userLogHandler;\n }\n set userLogHandler(val: LogHandler | null) {\n this._userLogHandler = val;\n }\n\n /**\n * The functions below are all based on the `console` interface\n */\n\n debug(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\n this._logHandler(this, LogLevel.DEBUG, ...args);\n }\n log(...args: unknown[]): void {\n this._userLogHandler &&\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\n this._logHandler(this, LogLevel.VERBOSE, ...args);\n }\n info(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\n this._logHandler(this, LogLevel.INFO, ...args);\n }\n warn(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\n this._logHandler(this, LogLevel.WARN, ...args);\n }\n error(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\n this._logHandler(this, LogLevel.ERROR, ...args);\n }\n}\n\nexport function setLogLevel(level: LogLevelString | LogLevel): void {\n instances.forEach(inst => {\n inst.setLogLevel(level);\n });\n}\n\nexport function setUserLogHandler(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n for (const instance of instances) {\n let customLogLevel: LogLevel | null = null;\n if (options && options.level) {\n customLogLevel = levelStringToEnum[options.level];\n }\n if (logCallback === null) {\n instance.userLogHandler = null;\n } else {\n instance.userLogHandler = (\n instance: Logger,\n level: LogLevel,\n ...args: unknown[]\n ) => {\n const message = args\n .map(arg => {\n if (arg == null) {\n return null;\n } else if (typeof arg === 'string') {\n return arg;\n } else if (typeof arg === 'number' || typeof arg === 'boolean') {\n return arg.toString();\n } else if (arg instanceof Error) {\n return arg.message;\n } else {\n try {\n return JSON.stringify(arg);\n } catch (ignored) {\n return null;\n }\n }\n })\n .filter(arg => arg)\n .join(' ');\n if (level >= (customLogLevel ?? instance.logLevel)) {\n logCallback({\n level: LogLevel[level].toLowerCase() as LogLevelString,\n message,\n args,\n type: instance.name\n });\n }\n };\n }\n }\n}\n"],"names":["LogLevel"],"mappings":";;;;AAAA;;;;;;;;;;;;;;;AAeG;AAuBH;;AAEG;AACI,MAAM,SAAS,GAAa,EAAE,CAAC;AAEtC;;;;;;;;;;AAUG;AACSA,0BAOX;AAPD,CAAA,UAAY,QAAQ,EAAA;AAClB,IAAA,QAAA,CAAA,QAAA,CAAA,OAAA,CAAA,GAAA,CAAA,CAAA,GAAA,OAAK,CAAA;AACL,IAAA,QAAA,CAAA,QAAA,CAAA,SAAA,CAAA,GAAA,CAAA,CAAA,GAAA,SAAO,CAAA;AACP,IAAA,QAAA,CAAA,QAAA,CAAA,MAAA,CAAA,GAAA,CAAA,CAAA,GAAA,MAAI,CAAA;AACJ,IAAA,QAAA,CAAA,QAAA,CAAA,MAAA,CAAA,GAAA,CAAA,CAAA,GAAA,MAAI,CAAA;AACJ,IAAA,QAAA,CAAA,QAAA,CAAA,OAAA,CAAA,GAAA,CAAA,CAAA,GAAA,OAAK,CAAA;AACL,IAAA,QAAA,CAAA,QAAA,CAAA,QAAA,CAAA,GAAA,CAAA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ACvB;AAAM,yBAAA,IAAI,GAAG,YAAY,KAAK,EAAE;wBAC/B,OAAO,GAAG,CAAC,OAAO,CAAC;qBACpB;yBAAM;AACL,wBAAA,IAAI;AACF,4BAAA,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;yBAC5B;wBAAC,OAAO,OAAO,EAAE;AAChB,4BAAA,OAAO,IAAI,CAAC;yBACb;qBACF;AACH,iBAAC,CAAC;AACD,qBAAA,MAAM,CAAC,GAAG,IAAI,GAAG,CAAC;qBAClB,IAAI,CAAC,GAAG,CAAC,CAAC;gBACb,IAAI,KAAK,KAAK,cAAc,IAAI,QAAQ,CAAC,QAAQ,CAAC,EAAE;AAClD,oBAAA,WAAW,CAAC;AACV,wBAAA,KAAK,EAAEA,gBAAQ,CAAC,KAAK,CAAC,CAAC,WAAW,EAAoB;wBACtD,OAAO;wBACP,IAAI;wBACJ,IAAI,EAAE,QAAQ,CAAC,IAAI;AACpB,qBAAA,CAAC,CAAC;iBACJ;AACH,aAAC,CAAC;SACH;KACF;AACH;;;;;;"} \ No newline at end of file diff --git a/node_modules/@firebase/logger/dist/index.d.ts b/node_modules/@firebase/logger/dist/index.d.ts new file mode 100644 index 0000000..35f2155 --- /dev/null +++ b/node_modules/@firebase/logger/dist/index.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { setLogLevel, Logger, LogLevel, LogHandler, setUserLogHandler, LogCallback, LogLevelString, LogOptions } from './src/logger'; diff --git a/node_modules/@firebase/logger/dist/src/logger.d.ts b/node_modules/@firebase/logger/dist/src/logger.d.ts new file mode 100644 index 0000000..a2df808 --- /dev/null +++ b/node_modules/@firebase/logger/dist/src/logger.d.ts @@ -0,0 +1,96 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export type LogLevelString = 'debug' | 'verbose' | 'info' | 'warn' | 'error' | 'silent'; +export interface LogOptions { + level: LogLevelString; +} +export type LogCallback = (callbackParams: LogCallbackParams) => void; +export interface LogCallbackParams { + level: LogLevelString; + message: string; + args: unknown[]; + type: string; +} +/** + * A container for all of the Logger instances + */ +export declare const instances: Logger[]; +/** + * The JS SDK supports 5 log levels and also allows a user the ability to + * silence the logs altogether. + * + * The order is a follows: + * DEBUG < VERBOSE < INFO < WARN < ERROR + * + * All of the log types above the current log level will be captured (i.e. if + * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and + * `VERBOSE` logs will not) + */ +export declare enum LogLevel { + DEBUG = 0, + VERBOSE = 1, + INFO = 2, + WARN = 3, + ERROR = 4, + SILENT = 5 +} +/** + * We allow users the ability to pass their own log handler. We will pass the + * type of log, the current log level, and any other arguments passed (i.e. the + * messages that the user wants to log) to this function. + */ +export type LogHandler = (loggerInstance: Logger, logType: LogLevel, ...args: unknown[]) => void; +export declare class Logger { + name: string; + /** + * Gives you an instance of a Logger to capture messages according to + * Firebase's logging scheme. + * + * @param name The name that the logs will be associated with + */ + constructor(name: string); + /** + * The log level of the given Logger instance. + */ + private _logLevel; + get logLevel(): LogLevel; + set logLevel(val: LogLevel); + setLogLevel(val: LogLevel | LogLevelString): void; + /** + * The main (internal) log handler for the Logger instance. + * Can be set to a new function in internal package code but not by user. + */ + private _logHandler; + get logHandler(): LogHandler; + set logHandler(val: LogHandler); + /** + * The optional, additional, user-defined log handler for the Logger instance. + */ + private _userLogHandler; + get userLogHandler(): LogHandler | null; + set userLogHandler(val: LogHandler | null); + /** + * The functions below are all based on the `console` interface + */ + debug(...args: unknown[]): void; + log(...args: unknown[]): void; + info(...args: unknown[]): void; + warn(...args: unknown[]): void; + error(...args: unknown[]): void; +} +export declare function setLogLevel(level: LogLevelString | LogLevel): void; +export declare function setUserLogHandler(logCallback: LogCallback | null, options?: LogOptions): void; diff --git a/node_modules/@firebase/logger/dist/test/custom-logger.test.d.ts b/node_modules/@firebase/logger/dist/test/custom-logger.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/node_modules/@firebase/logger/dist/test/custom-logger.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/logger/dist/test/logger.test.d.ts b/node_modules/@firebase/logger/dist/test/logger.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/node_modules/@firebase/logger/dist/test/logger.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/logger/package.json b/node_modules/@firebase/logger/package.json new file mode 100644 index 0000000..f44fa21 --- /dev/null +++ b/node_modules/@firebase/logger/package.json @@ -0,0 +1,60 @@ +{ + "name": "@firebase/logger", + "version": "0.5.0", + "description": "A logger package for use in the Firebase JS SDK", + "author": "Firebase (https://firebase.google.com/)", + "main": "dist/index.cjs.js", + "module": "dist/esm/index.esm.js", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "require": "./dist/index.cjs.js", + "default": "./dist/esm/index.esm.js" + }, + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "scripts": { + "lint": "eslint -c .eslintrc.js '**/*.ts' --ignore-path '../../.gitignore'", + "lint:fix": "eslint --fix -c .eslintrc.js '**/*.ts' --ignore-path '../../.gitignore'", + "build": "rollup -c", + "build:deps": "lerna run --scope @firebase/logger --include-dependencies build", + "dev": "rollup -c -w", + "test": "run-p --npm-path npm lint test:all", + "test:ci": "node ../../scripts/run_tests_in_ci.js -s test:all", + "test:all": "run-p --npm-path npm test:browser test:node", + "test:browser": "karma start", + "test:browser:debug": "karma start --browsers Chrome --auto-watch", + "test:node": "TS_NODE_COMPILER_OPTIONS='{\"module\":\"commonjs\"}' nyc --reporter lcovonly -- mocha test/**/*.test.* --config ../../config/mocharc.node.js", + "trusted-type-check": "tsec -p tsconfig.json --noEmit" + }, + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + }, + "devDependencies": { + "rollup": "2.79.2", + "rollup-plugin-typescript2": "0.36.0", + "typescript": "5.5.4" + }, + "repository": { + "directory": "packages/logger", + "type": "git", + "url": "git+https://github.com/firebase/firebase-js-sdk.git" + }, + "bugs": { + "url": "https://github.com/firebase/firebase-js-sdk/issues" + }, + "typings": "dist/index.d.ts", + "nyc": { + "extension": [ + ".ts" + ], + "reportDir": "./coverage/node" + }, + "engines": { + "node": ">=20.0.0" + } +} diff --git a/node_modules/@firebase/util/README.md b/node_modules/@firebase/util/README.md new file mode 100644 index 0000000..b79aeb6 --- /dev/null +++ b/node_modules/@firebase/util/README.md @@ -0,0 +1,25 @@ +# @firebase/util + +_NOTE: This is specifically tailored for Firebase JS SDK usage, if you are not a +member of the Firebase team, please avoid using this package_ + +This is a wrapper of some Webchannel Features for the Firebase JS SDK. + +## Usage + +**ES Modules** + +```javascript +import { Deferred } from '@firebase/util'; + +// Do stuff with Deferred or any of the other Utils you import +``` + +**CommonJS Modules** + +```javascript +const utils = require('@firebase/util'); + +// Do stuff with any of the re-exported `utils` +``` + diff --git a/node_modules/@firebase/util/dist/index.cjs.js b/node_modules/@firebase/util/dist/index.cjs.js new file mode 100644 index 0000000..6fa505b --- /dev/null +++ b/node_modules/@firebase/util/dist/index.cjs.js @@ -0,0 +1,2392 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var postinstall = require('./postinstall.js'); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time. + */ +const CONSTANTS = { + /** + * @define {boolean} Whether this is the client Node.js SDK. + */ + NODE_CLIENT: false, + /** + * @define {boolean} Whether this is the Admin Node.js SDK. + */ + NODE_ADMIN: false, + /** + * Firebase SDK Version + */ + SDK_VERSION: '${JSCORE_VERSION}' +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Throws an error if the provided assertion is falsy + */ +const assert = function (assertion, message) { + if (!assertion) { + throw assertionError(message); + } +}; +/** + * Returns an Error object suitable for throwing. + */ +const assertionError = function (message) { + return new Error('Firebase Database (' + + CONSTANTS.SDK_VERSION + + ') INTERNAL ASSERT FAILED: ' + + message); +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const stringToByteArray$1 = function (str) { + // TODO(user): Use native implementations if/when available + const out = []; + let p = 0; + for (let i = 0; i < str.length; i++) { + let c = str.charCodeAt(i); + if (c < 128) { + out[p++] = c; + } + else if (c < 2048) { + out[p++] = (c >> 6) | 192; + out[p++] = (c & 63) | 128; + } + else if ((c & 0xfc00) === 0xd800 && + i + 1 < str.length && + (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { + // Surrogate Pair + c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff); + out[p++] = (c >> 18) | 240; + out[p++] = ((c >> 12) & 63) | 128; + out[p++] = ((c >> 6) & 63) | 128; + out[p++] = (c & 63) | 128; + } + else { + out[p++] = (c >> 12) | 224; + out[p++] = ((c >> 6) & 63) | 128; + out[p++] = (c & 63) | 128; + } + } + return out; +}; +/** + * Turns an array of numbers into the string given by the concatenation of the + * characters to which the numbers correspond. + * @param bytes Array of numbers representing characters. + * @return Stringification of the array. + */ +const byteArrayToString = function (bytes) { + // TODO(user): Use native implementations if/when available + const out = []; + let pos = 0, c = 0; + while (pos < bytes.length) { + const c1 = bytes[pos++]; + if (c1 < 128) { + out[c++] = String.fromCharCode(c1); + } + else if (c1 > 191 && c1 < 224) { + const c2 = bytes[pos++]; + out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63)); + } + else if (c1 > 239 && c1 < 365) { + // Surrogate Pair + const c2 = bytes[pos++]; + const c3 = bytes[pos++]; + const c4 = bytes[pos++]; + const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) - + 0x10000; + out[c++] = String.fromCharCode(0xd800 + (u >> 10)); + out[c++] = String.fromCharCode(0xdc00 + (u & 1023)); + } + else { + const c2 = bytes[pos++]; + const c3 = bytes[pos++]; + out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); + } + } + return out.join(''); +}; +// We define it as an object literal instead of a class because a class compiled down to es5 can't +// be treeshaked. https://github.com/rollup/rollup/issues/1691 +// Static lookup maps, lazily populated by init_() +// TODO(dlarocque): Define this as a class, since we no longer target ES5. +const base64 = { + /** + * Maps bytes to characters. + */ + byteToCharMap_: null, + /** + * Maps characters to bytes. + */ + charToByteMap_: null, + /** + * Maps bytes to websafe characters. + * @private + */ + byteToCharMapWebSafe_: null, + /** + * Maps websafe characters to bytes. + * @private + */ + charToByteMapWebSafe_: null, + /** + * Our default alphabet, shared between + * ENCODED_VALS and ENCODED_VALS_WEBSAFE + */ + ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789', + /** + * Our default alphabet. Value 64 (=) is special; it means "nothing." + */ + get ENCODED_VALS() { + return this.ENCODED_VALS_BASE + '+/='; + }, + /** + * Our websafe alphabet. + */ + get ENCODED_VALS_WEBSAFE() { + return this.ENCODED_VALS_BASE + '-_.'; + }, + /** + * Whether this browser supports the atob and btoa functions. This extension + * started at Mozilla but is now implemented by many browsers. We use the + * ASSUME_* variables to avoid pulling in the full useragent detection library + * but still allowing the standard per-browser compilations. + * + */ + HAS_NATIVE_SUPPORT: typeof atob === 'function', + /** + * Base64-encode an array of bytes. + * + * @param input An array of bytes (numbers with + * value in [0, 255]) to encode. + * @param webSafe Boolean indicating we should use the + * alternative alphabet. + * @return The base64 encoded string. + */ + encodeByteArray(input, webSafe) { + if (!Array.isArray(input)) { + throw Error('encodeByteArray takes an array as a parameter'); + } + this.init_(); + const byteToCharMap = webSafe + ? this.byteToCharMapWebSafe_ + : this.byteToCharMap_; + const output = []; + for (let i = 0; i < input.length; i += 3) { + const byte1 = input[i]; + const haveByte2 = i + 1 < input.length; + const byte2 = haveByte2 ? input[i + 1] : 0; + const haveByte3 = i + 2 < input.length; + const byte3 = haveByte3 ? input[i + 2] : 0; + const outByte1 = byte1 >> 2; + const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4); + let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6); + let outByte4 = byte3 & 0x3f; + if (!haveByte3) { + outByte4 = 64; + if (!haveByte2) { + outByte3 = 64; + } + } + output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]); + } + return output.join(''); + }, + /** + * Base64-encode a string. + * + * @param input A string to encode. + * @param webSafe If true, we should use the + * alternative alphabet. + * @return The base64 encoded string. + */ + encodeString(input, webSafe) { + // Shortcut for Mozilla browsers that implement + // a native base64 encoder in the form of "btoa/atob" + if (this.HAS_NATIVE_SUPPORT && !webSafe) { + return btoa(input); + } + return this.encodeByteArray(stringToByteArray$1(input), webSafe); + }, + /** + * Base64-decode a string. + * + * @param input to decode. + * @param webSafe True if we should use the + * alternative alphabet. + * @return string representing the decoded value. + */ + decodeString(input, webSafe) { + // Shortcut for Mozilla browsers that implement + // a native base64 encoder in the form of "btoa/atob" + if (this.HAS_NATIVE_SUPPORT && !webSafe) { + return atob(input); + } + return byteArrayToString(this.decodeStringToByteArray(input, webSafe)); + }, + /** + * Base64-decode a string. + * + * In base-64 decoding, groups of four characters are converted into three + * bytes. If the encoder did not apply padding, the input length may not + * be a multiple of 4. + * + * In this case, the last group will have fewer than 4 characters, and + * padding will be inferred. If the group has one or two characters, it decodes + * to one byte. If the group has three characters, it decodes to two bytes. + * + * @param input Input to decode. + * @param webSafe True if we should use the web-safe alphabet. + * @return bytes representing the decoded value. + */ + decodeStringToByteArray(input, webSafe) { + this.init_(); + const charToByteMap = webSafe + ? this.charToByteMapWebSafe_ + : this.charToByteMap_; + const output = []; + for (let i = 0; i < input.length;) { + const byte1 = charToByteMap[input.charAt(i++)]; + const haveByte2 = i < input.length; + const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0; + ++i; + const haveByte3 = i < input.length; + const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64; + ++i; + const haveByte4 = i < input.length; + const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64; + ++i; + if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) { + throw new DecodeBase64StringError(); + } + const outByte1 = (byte1 << 2) | (byte2 >> 4); + output.push(outByte1); + if (byte3 !== 64) { + const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2); + output.push(outByte2); + if (byte4 !== 64) { + const outByte3 = ((byte3 << 6) & 0xc0) | byte4; + output.push(outByte3); + } + } + } + return output; + }, + /** + * Lazy static initialization function. Called before + * accessing any of the static map variables. + * @private + */ + init_() { + if (!this.byteToCharMap_) { + this.byteToCharMap_ = {}; + this.charToByteMap_ = {}; + this.byteToCharMapWebSafe_ = {}; + this.charToByteMapWebSafe_ = {}; + // We want quick mappings back and forth, so we precompute two maps. + for (let i = 0; i < this.ENCODED_VALS.length; i++) { + this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i); + this.charToByteMap_[this.byteToCharMap_[i]] = i; + this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i); + this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i; + // Be forgiving when decoding and correctly decode both encodings. + if (i >= this.ENCODED_VALS_BASE.length) { + this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i; + this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i; + } + } + } + } +}; +/** + * An error encountered while decoding base64 string. + */ +class DecodeBase64StringError extends Error { + constructor() { + super(...arguments); + this.name = 'DecodeBase64StringError'; + } +} +/** + * URL-safe base64 encoding + */ +const base64Encode = function (str) { + const utf8Bytes = stringToByteArray$1(str); + return base64.encodeByteArray(utf8Bytes, true); +}; +/** + * URL-safe base64 encoding (without "." padding in the end). + * e.g. Used in JSON Web Token (JWT) parts. + */ +const base64urlEncodeWithoutPadding = function (str) { + // Use base64url encoding and remove padding in the end (dot characters). + return base64Encode(str).replace(/\./g, ''); +}; +/** + * URL-safe base64 decoding + * + * NOTE: DO NOT use the global atob() function - it does NOT support the + * base64Url variant encoding. + * + * @param str To be decoded + * @return Decoded result, if possible + */ +const base64Decode = function (str) { + try { + return base64.decodeString(str, true); + } + catch (e) { + console.error('base64Decode failed: ', e); + } + return null; +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Do a deep-copy of basic JavaScript Objects or Arrays. + */ +function deepCopy(value) { + return deepExtend(undefined, value); +} +/** + * Copy properties from source to target (recursively allows extension + * of Objects and Arrays). Scalar values in the target are over-written. + * If target is undefined, an object of the appropriate type will be created + * (and returned). + * + * We recursively copy all child properties of plain Objects in the source- so + * that namespace- like dictionaries are merged. + * + * Note that the target can be a function, in which case the properties in + * the source Object are copied onto it as static properties of the Function. + * + * Note: we don't merge __proto__ to prevent prototype pollution + */ +function deepExtend(target, source) { + if (!(source instanceof Object)) { + return source; + } + switch (source.constructor) { + case Date: + // Treat Dates like scalars; if the target date object had any child + // properties - they will be lost! + const dateValue = source; + return new Date(dateValue.getTime()); + case Object: + if (target === undefined) { + target = {}; + } + break; + case Array: + // Always copy the array source and overwrite the target. + target = []; + break; + default: + // Not a plain Object - treat it as a scalar. + return source; + } + for (const prop in source) { + // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202 + if (!source.hasOwnProperty(prop) || !isValidKey(prop)) { + continue; + } + target[prop] = deepExtend(target[prop], source[prop]); + } + return target; +} +function isValidKey(key) { + return key !== '__proto__'; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Polyfill for `globalThis` object. + * @returns the `globalThis` object for the given environment. + * @public + */ +function getGlobal() { + if (typeof self !== 'undefined') { + return self; + } + if (typeof window !== 'undefined') { + return window; + } + if (typeof global !== 'undefined') { + return global; + } + throw new Error('Unable to locate global object.'); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__; +/** + * Attempt to read defaults from a JSON string provided to + * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in + * process(.)env(.)__FIREBASE_DEFAULTS_PATH__ + * The dots are in parens because certain compilers (Vite?) cannot + * handle seeing that variable in comments. + * See https://github.com/firebase/firebase-js-sdk/issues/6838 + */ +const getDefaultsFromEnvVariable = () => { + if (typeof process === 'undefined' || typeof process.env === 'undefined') { + return; + } + const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__; + if (defaultsJsonString) { + return JSON.parse(defaultsJsonString); + } +}; +const getDefaultsFromCookie = () => { + if (typeof document === 'undefined') { + return; + } + let match; + try { + match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/); + } + catch (e) { + // Some environments such as Angular Universal SSR have a + // `document` object but error on accessing `document.cookie`. + return; + } + const decoded = match && base64Decode(match[1]); + return decoded && JSON.parse(decoded); +}; +/** + * Get the __FIREBASE_DEFAULTS__ object. It checks in order: + * (1) if such an object exists as a property of `globalThis` + * (2) if such an object was provided on a shell environment variable + * (3) if such an object exists in a cookie + * @public + */ +const getDefaults = () => { + try { + return (postinstall.getDefaultsFromPostinstall() || + getDefaultsFromGlobal() || + getDefaultsFromEnvVariable() || + getDefaultsFromCookie()); + } + catch (e) { + /** + * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due + * to any environment case we have not accounted for. Log to + * info instead of swallowing so we can find these unknown cases + * and add paths for them if needed. + */ + console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`); + return; + } +}; +/** + * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object + * for the given product. + * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available + * @public + */ +const getDefaultEmulatorHost = (productName) => getDefaults()?.emulatorHosts?.[productName]; +/** + * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object + * for the given product. + * @returns a pair of hostname and port like `["::1", 4000]` if available + * @public + */ +const getDefaultEmulatorHostnameAndPort = (productName) => { + const host = getDefaultEmulatorHost(productName); + if (!host) { + return undefined; + } + const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons. + if (separatorIndex <= 0 || separatorIndex + 1 === host.length) { + throw new Error(`Invalid host ${host} with no separate hostname and port!`); + } + // eslint-disable-next-line no-restricted-globals + const port = parseInt(host.substring(separatorIndex + 1), 10); + if (host[0] === '[') { + // Bracket-quoted `[ipv6addr]:port` => return "ipv6addr" (without brackets). + return [host.substring(1, separatorIndex - 1), port]; + } + else { + return [host.substring(0, separatorIndex), port]; + } +}; +/** + * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object. + * @public + */ +const getDefaultAppConfig = () => getDefaults()?.config; +/** + * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties + * prefixed by "_") + * @public + */ +const getExperimentalSetting = (name) => getDefaults()?.[`_${name}`]; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Deferred { + constructor() { + this.reject = () => { }; + this.resolve = () => { }; + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } + /** + * Our API internals are not promisified and cannot because our callback APIs have subtle expectations around + * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback + * and returns a node-style callback which will resolve or reject the Deferred's promise. + */ + wrapCallback(callback) { + return (error, value) => { + if (error) { + this.reject(error); + } + else { + this.resolve(value); + } + if (typeof callback === 'function') { + // Attaching noop handler just in case developer wasn't expecting + // promises + this.promise.catch(() => { }); + // Some of our callbacks don't expect a value and our own tests + // assert that the parameter length is 1 + if (callback.length === 1) { + callback(error); + } + else { + callback(error, value); + } + } + }; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Checks whether host is a cloud workstation or not. + * @public + */ +function isCloudWorkstation(url) { + // `isCloudWorkstation` is called without protocol in certain connect*Emulator functions + // In HTTP request builders, it's called with the protocol. + // If called with protocol prefix, it's a valid URL, so we extract the hostname + // If called without, we assume the string is the hostname. + try { + const host = url.startsWith('http://') || url.startsWith('https://') + ? new URL(url).hostname + : url; + return host.endsWith('.cloudworkstations.dev'); + } + catch { + return false; + } +} +/** + * Makes a fetch request to the given server. + * Mostly used for forwarding cookies in Firebase Studio. + * @public + */ +async function pingServer(endpoint) { + const result = await fetch(endpoint, { + credentials: 'include' + }); + return result.ok; +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function createMockUserToken(token, projectId) { + if (token.uid) { + throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.'); + } + // Unsecured JWTs use "none" as the algorithm. + const header = { + alg: 'none', + type: 'JWT' + }; + const project = projectId || 'demo-project'; + const iat = token.iat || 0; + const sub = token.sub || token.user_id; + if (!sub) { + throw new Error("mockUserToken must contain 'sub' or 'user_id' field!"); + } + const payload = { + // Set all required fields to decent defaults + iss: `https://securetoken.google.com/${project}`, + aud: project, + iat, + exp: iat + 3600, + auth_time: iat, + sub, + user_id: sub, + firebase: { + sign_in_provider: 'custom', + identities: {} + }, + // Override with user options + ...token + }; + // Unsecured JWTs use the empty string as a signature. + const signature = ''; + return [ + base64urlEncodeWithoutPadding(JSON.stringify(header)), + base64urlEncodeWithoutPadding(JSON.stringify(payload)), + signature + ].join('.'); +} +const emulatorStatus = {}; +// Checks whether any products are running on an emulator +function getEmulatorSummary() { + const summary = { + prod: [], + emulator: [] + }; + for (const key of Object.keys(emulatorStatus)) { + if (emulatorStatus[key]) { + summary.emulator.push(key); + } + else { + summary.prod.push(key); + } + } + return summary; +} +function getOrCreateEl(id) { + let parentDiv = document.getElementById(id); + let created = false; + if (!parentDiv) { + parentDiv = document.createElement('div'); + parentDiv.setAttribute('id', id); + created = true; + } + return { created, element: parentDiv }; +} +let previouslyDismissed = false; +/** + * Updates Emulator Banner. Primarily used for Firebase Studio + * @param name + * @param isRunningEmulator + * @public + */ +function updateEmulatorBanner(name, isRunningEmulator) { + if (typeof window === 'undefined' || + typeof document === 'undefined' || + !isCloudWorkstation(window.location.host) || + emulatorStatus[name] === isRunningEmulator || + emulatorStatus[name] || // If already set to use emulator, can't go back to prod. + previouslyDismissed) { + return; + } + emulatorStatus[name] = isRunningEmulator; + function prefixedId(id) { + return `__firebase__banner__${id}`; + } + const bannerId = '__firebase__banner'; + const summary = getEmulatorSummary(); + const showError = summary.prod.length > 0; + function tearDown() { + const element = document.getElementById(bannerId); + if (element) { + element.remove(); + } + } + function setupBannerStyles(bannerEl) { + bannerEl.style.display = 'flex'; + bannerEl.style.background = '#7faaf0'; + bannerEl.style.position = 'fixed'; + bannerEl.style.bottom = '5px'; + bannerEl.style.left = '5px'; + bannerEl.style.padding = '.5em'; + bannerEl.style.borderRadius = '5px'; + bannerEl.style.alignItems = 'center'; + } + function setupIconStyles(prependIcon, iconId) { + prependIcon.setAttribute('width', '24'); + prependIcon.setAttribute('id', iconId); + prependIcon.setAttribute('height', '24'); + prependIcon.setAttribute('viewBox', '0 0 24 24'); + prependIcon.setAttribute('fill', 'none'); + prependIcon.style.marginLeft = '-6px'; + } + function setupCloseBtn() { + const closeBtn = document.createElement('span'); + closeBtn.style.cursor = 'pointer'; + closeBtn.style.marginLeft = '16px'; + closeBtn.style.fontSize = '24px'; + closeBtn.innerHTML = ' ×'; + closeBtn.onclick = () => { + previouslyDismissed = true; + tearDown(); + }; + return closeBtn; + } + function setupLinkStyles(learnMoreLink, learnMoreId) { + learnMoreLink.setAttribute('id', learnMoreId); + learnMoreLink.innerText = 'Learn more'; + learnMoreLink.href = + 'https://firebase.google.com/docs/studio/preview-apps#preview-backend'; + learnMoreLink.setAttribute('target', '__blank'); + learnMoreLink.style.paddingLeft = '5px'; + learnMoreLink.style.textDecoration = 'underline'; + } + function setupDom() { + const banner = getOrCreateEl(bannerId); + const firebaseTextId = prefixedId('text'); + const firebaseText = document.getElementById(firebaseTextId) || document.createElement('span'); + const learnMoreId = prefixedId('learnmore'); + const learnMoreLink = document.getElementById(learnMoreId) || + document.createElement('a'); + const prependIconId = prefixedId('preprendIcon'); + const prependIcon = document.getElementById(prependIconId) || + document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + if (banner.created) { + // update styles + const bannerEl = banner.element; + setupBannerStyles(bannerEl); + setupLinkStyles(learnMoreLink, learnMoreId); + const closeBtn = setupCloseBtn(); + setupIconStyles(prependIcon, prependIconId); + bannerEl.append(prependIcon, firebaseText, learnMoreLink, closeBtn); + document.body.appendChild(bannerEl); + } + if (showError) { + firebaseText.innerText = `Preview backend disconnected.`; + prependIcon.innerHTML = ` + + + + + + +`; + } + else { + prependIcon.innerHTML = ` + + + + + + +`; + firebaseText.innerText = 'Preview backend running in this workspace.'; + } + firebaseText.setAttribute('id', firebaseTextId); + } + if (document.readyState === 'loading') { + window.addEventListener('DOMContentLoaded', setupDom); + } + else { + setupDom(); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns navigator.userAgent string or '' if it's not defined. + * @return user agent string + */ +function getUA() { + if (typeof navigator !== 'undefined' && + typeof navigator['userAgent'] === 'string') { + return navigator['userAgent']; + } + else { + return ''; + } +} +/** + * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device. + * + * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap + * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally + * wait for a callback. + */ +function isMobileCordova() { + return (typeof window !== 'undefined' && + // @ts-ignore Setting up an broadly applicable index signature for Window + // just to deal with this case would probably be a bad idea. + !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) && + /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())); +} +/** + * Detect Node.js. + * + * @return true if Node.js environment is detected or specified. + */ +// Node detection logic from: https://github.com/iliakan/detect-node/ +function isNode() { + const forceEnvironment = getDefaults()?.forceEnvironment; + if (forceEnvironment === 'node') { + return true; + } + else if (forceEnvironment === 'browser') { + return false; + } + try { + return (Object.prototype.toString.call(global.process) === '[object process]'); + } + catch (e) { + return false; + } +} +/** + * Detect Browser Environment. + * Note: This will return true for certain test frameworks that are incompletely + * mimicking a browser, and should not lead to assuming all browser APIs are + * available. + */ +function isBrowser() { + return typeof window !== 'undefined' || isWebWorker(); +} +/** + * Detect Web Worker context. + */ +function isWebWorker() { + return (typeof WorkerGlobalScope !== 'undefined' && + typeof self !== 'undefined' && + self instanceof WorkerGlobalScope); +} +/** + * Detect Cloudflare Worker context. + */ +function isCloudflareWorker() { + return (typeof navigator !== 'undefined' && + navigator.userAgent === 'Cloudflare-Workers'); +} +function isBrowserExtension() { + const runtime = typeof chrome === 'object' + ? chrome.runtime + : typeof browser === 'object' + ? browser.runtime + : undefined; + return typeof runtime === 'object' && runtime.id !== undefined; +} +/** + * Detect React Native. + * + * @return true if ReactNative environment is detected. + */ +function isReactNative() { + return (typeof navigator === 'object' && navigator['product'] === 'ReactNative'); +} +/** Detects Electron apps. */ +function isElectron() { + return getUA().indexOf('Electron/') >= 0; +} +/** Detects Internet Explorer. */ +function isIE() { + const ua = getUA(); + return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0; +} +/** Detects Universal Windows Platform apps. */ +function isUWP() { + return getUA().indexOf('MSAppHost/') >= 0; +} +/** + * Detect whether the current SDK build is the Node version. + * + * @return true if it's the Node SDK build. + */ +function isNodeSdk() { + return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true; +} +/** Returns true if we are running in Safari. */ +function isSafari() { + return (!isNode() && + !!navigator.userAgent && + navigator.userAgent.includes('Safari') && + !navigator.userAgent.includes('Chrome')); +} +/** Returns true if we are running in Safari or WebKit */ +function isSafariOrWebkit() { + return (!isNode() && + !!navigator.userAgent && + (navigator.userAgent.includes('Safari') || + navigator.userAgent.includes('WebKit')) && + !navigator.userAgent.includes('Chrome')); +} +/** + * This method checks if indexedDB is supported by current browser/service worker context + * @return true if indexedDB is supported by current browser/service worker context + */ +function isIndexedDBAvailable() { + try { + return typeof indexedDB === 'object'; + } + catch (e) { + return false; + } +} +/** + * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject + * if errors occur during the database open operation. + * + * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox + * private browsing) + */ +function validateIndexedDBOpenable() { + return new Promise((resolve, reject) => { + try { + let preExist = true; + const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module'; + const request = self.indexedDB.open(DB_CHECK_NAME); + request.onsuccess = () => { + request.result.close(); + // delete database only when it doesn't pre-exist + if (!preExist) { + self.indexedDB.deleteDatabase(DB_CHECK_NAME); + } + resolve(true); + }; + request.onupgradeneeded = () => { + preExist = false; + }; + request.onerror = () => { + reject(request.error?.message || ''); + }; + } + catch (error) { + reject(error); + } + }); +} +/** + * + * This method checks whether cookie is enabled within current browser + * @return true if cookie is enabled within current browser + */ +function areCookiesEnabled() { + if (typeof navigator === 'undefined' || !navigator.cookieEnabled) { + return false; + } + return true; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview Standardized Firebase Error. + * + * Usage: + * + * // TypeScript string literals for type-safe codes + * type Err = + * 'unknown' | + * 'object-not-found' + * ; + * + * // Closure enum for type-safe error codes + * // at-enum {string} + * var Err = { + * UNKNOWN: 'unknown', + * OBJECT_NOT_FOUND: 'object-not-found', + * } + * + * let errors: Map = { + * 'generic-error': "Unknown error", + * 'file-not-found': "Could not find file: {$file}", + * }; + * + * // Type-safe function - must pass a valid error code as param. + * let error = new ErrorFactory('service', 'Service', errors); + * + * ... + * throw error.create(Err.GENERIC); + * ... + * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName}); + * ... + * // Service: Could not file file: foo.txt (service/file-not-found). + * + * catch (e) { + * assert(e.message === "Could not find file: foo.txt."); + * if ((e as FirebaseError)?.code === 'service/file-not-found') { + * console.log("Could not read file: " + e['file']); + * } + * } + */ +const ERROR_NAME = 'FirebaseError'; +// Based on code from: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types +class FirebaseError extends Error { + constructor( + /** The error code for this error. */ + code, message, + /** Custom data for this error. */ + customData) { + super(message); + this.code = code; + this.customData = customData; + /** The custom name for all FirebaseErrors. */ + this.name = ERROR_NAME; + // Fix For ES5 + // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work + // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget + // which we can now use since we no longer target ES5. + Object.setPrototypeOf(this, FirebaseError.prototype); + // Maintains proper stack trace for where our error was thrown. + // Only available on V8. + if (Error.captureStackTrace) { + Error.captureStackTrace(this, ErrorFactory.prototype.create); + } + } +} +class ErrorFactory { + constructor(service, serviceName, errors) { + this.service = service; + this.serviceName = serviceName; + this.errors = errors; + } + create(code, ...data) { + const customData = data[0] || {}; + const fullCode = `${this.service}/${code}`; + const template = this.errors[code]; + const message = template ? replaceTemplate(template, customData) : 'Error'; + // Service Name: Error message (service/code). + const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`; + const error = new FirebaseError(fullCode, fullMessage, customData); + return error; + } +} +function replaceTemplate(template, data) { + return template.replace(PATTERN, (_, key) => { + const value = data[key]; + return value != null ? String(value) : `<${key}?>`; + }); +} +const PATTERN = /\{\$([^}]+)}/g; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Evaluates a JSON string into a javascript object. + * + * @param {string} str A string containing JSON. + * @return {*} The javascript object representing the specified JSON. + */ +function jsonEval(str) { + return JSON.parse(str); +} +/** + * Returns JSON representing a javascript object. + * @param {*} data JavaScript object to be stringified. + * @return {string} The JSON contents of the object. + */ +function stringify(data) { + return JSON.stringify(data); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Decodes a Firebase auth. token into constituent parts. + * + * Notes: + * - May return with invalid / incomplete claims if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +const decode = function (token) { + let header = {}, claims = {}, data = {}, signature = ''; + try { + const parts = token.split('.'); + header = jsonEval(base64Decode(parts[0]) || ''); + claims = jsonEval(base64Decode(parts[1]) || ''); + signature = parts[2]; + data = claims['d'] || {}; + delete claims['d']; + } + catch (e) { } + return { + header, + claims, + data, + signature + }; +}; +/** + * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the + * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +const isValidTimestamp = function (token) { + const claims = decode(token).claims; + const now = Math.floor(new Date().getTime() / 1000); + let validSince = 0, validUntil = 0; + if (typeof claims === 'object') { + if (claims.hasOwnProperty('nbf')) { + validSince = claims['nbf']; + } + else if (claims.hasOwnProperty('iat')) { + validSince = claims['iat']; + } + if (claims.hasOwnProperty('exp')) { + validUntil = claims['exp']; + } + else { + // token will expire after 24h by default + validUntil = validSince + 86400; + } + } + return (!!now && + !!validSince && + !!validUntil && + now >= validSince && + now <= validUntil); +}; +/** + * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise. + * + * Notes: + * - May return null if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +const issuedAtTime = function (token) { + const claims = decode(token).claims; + if (typeof claims === 'object' && claims.hasOwnProperty('iat')) { + return claims['iat']; + } + return null; +}; +/** + * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +const isValidFormat = function (token) { + const decoded = decode(token), claims = decoded.claims; + return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat'); +}; +/** + * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +const isAdmin = function (token) { + const claims = decode(token).claims; + return typeof claims === 'object' && claims['admin'] === true; +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function contains(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +function safeGet(obj, key) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + return obj[key]; + } + else { + return undefined; + } +} +function isEmpty(obj) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + return false; + } + } + return true; +} +function map(obj, fn, contextObj) { + const res = {}; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + res[key] = fn.call(contextObj, obj[key], key, obj); + } + } + return res; +} +/** + * Deep equal two objects. Support Arrays and Objects. + */ +function deepEqual(a, b) { + if (a === b) { + return true; + } + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + for (const k of aKeys) { + if (!bKeys.includes(k)) { + return false; + } + const aProp = a[k]; + const bProp = b[k]; + if (isObject(aProp) && isObject(bProp)) { + if (!deepEqual(aProp, bProp)) { + return false; + } + } + else if (aProp !== bProp) { + return false; + } + } + for (const k of bKeys) { + if (!aKeys.includes(k)) { + return false; + } + } + return true; +} +function isObject(thing) { + return thing !== null && typeof thing === 'object'; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Rejects if the given promise doesn't resolve in timeInMS milliseconds. + * @internal + */ +function promiseWithTimeout(promise, timeInMS = 2000) { + const deferredPromise = new Deferred(); + setTimeout(() => deferredPromise.reject('timeout!'), timeInMS); + promise.then(deferredPromise.resolve, deferredPromise.reject); + return deferredPromise.promise; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a + * params object (e.g. {arg: 'val', arg2: 'val2'}) + * Note: You must prepend it with ? when adding it to a URL. + */ +function querystring(querystringParams) { + const params = []; + for (const [key, value] of Object.entries(querystringParams)) { + if (Array.isArray(value)) { + value.forEach(arrayVal => { + params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal)); + }); + } + else { + params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); + } + } + return params.length ? '&' + params.join('&') : ''; +} +/** + * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object + * (e.g. {arg: 'val', arg2: 'val2'}) + */ +function querystringDecode(querystring) { + const obj = {}; + const tokens = querystring.replace(/^\?/, '').split('&'); + tokens.forEach(token => { + if (token) { + const [key, value] = token.split('='); + obj[decodeURIComponent(key)] = decodeURIComponent(value); + } + }); + return obj; +} +/** + * Extract the query string part of a URL, including the leading question mark (if present). + */ +function extractQuerystring(url) { + const queryStart = url.indexOf('?'); + if (!queryStart) { + return ''; + } + const fragmentStart = url.indexOf('#', queryStart); + return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview SHA-1 cryptographic hash. + * Variable names follow the notation in FIPS PUB 180-3: + * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf. + * + * Usage: + * var sha1 = new sha1(); + * sha1.update(bytes); + * var hash = sha1.digest(); + * + * Performance: + * Chrome 23: ~400 Mbit/s + * Firefox 16: ~250 Mbit/s + * + */ +/** + * SHA-1 cryptographic hash constructor. + * + * The properties declared here are discussed in the above algorithm document. + * @constructor + * @final + * @struct + */ +class Sha1 { + constructor() { + /** + * Holds the previous values of accumulated variables a-e in the compress_ + * function. + * @private + */ + this.chain_ = []; + /** + * A buffer holding the partially computed hash result. + * @private + */ + this.buf_ = []; + /** + * An array of 80 bytes, each a part of the message to be hashed. Referred to + * as the message schedule in the docs. + * @private + */ + this.W_ = []; + /** + * Contains data needed to pad messages less than 64 bytes. + * @private + */ + this.pad_ = []; + /** + * @private {number} + */ + this.inbuf_ = 0; + /** + * @private {number} + */ + this.total_ = 0; + this.blockSize = 512 / 8; + this.pad_[0] = 128; + for (let i = 1; i < this.blockSize; ++i) { + this.pad_[i] = 0; + } + this.reset(); + } + reset() { + this.chain_[0] = 0x67452301; + this.chain_[1] = 0xefcdab89; + this.chain_[2] = 0x98badcfe; + this.chain_[3] = 0x10325476; + this.chain_[4] = 0xc3d2e1f0; + this.inbuf_ = 0; + this.total_ = 0; + } + /** + * Internal compress helper function. + * @param buf Block to compress. + * @param offset Offset of the block in the buffer. + * @private + */ + compress_(buf, offset) { + if (!offset) { + offset = 0; + } + const W = this.W_; + // get 16 big endian words + if (typeof buf === 'string') { + for (let i = 0; i < 16; i++) { + // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS + // have a bug that turns the post-increment ++ operator into pre-increment + // during JIT compilation. We have code that depends heavily on SHA-1 for + // correctness and which is affected by this bug, so I've removed all uses + // of post-increment ++ in which the result value is used. We can revert + // this change once the Safari bug + // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and + // most clients have been updated. + W[i] = + (buf.charCodeAt(offset) << 24) | + (buf.charCodeAt(offset + 1) << 16) | + (buf.charCodeAt(offset + 2) << 8) | + buf.charCodeAt(offset + 3); + offset += 4; + } + } + else { + for (let i = 0; i < 16; i++) { + W[i] = + (buf[offset] << 24) | + (buf[offset + 1] << 16) | + (buf[offset + 2] << 8) | + buf[offset + 3]; + offset += 4; + } + } + // expand to 80 words + for (let i = 16; i < 80; i++) { + const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff; + } + let a = this.chain_[0]; + let b = this.chain_[1]; + let c = this.chain_[2]; + let d = this.chain_[3]; + let e = this.chain_[4]; + let f, k; + // TODO(user): Try to unroll this loop to speed up the computation. + for (let i = 0; i < 80; i++) { + if (i < 40) { + if (i < 20) { + f = d ^ (b & (c ^ d)); + k = 0x5a827999; + } + else { + f = b ^ c ^ d; + k = 0x6ed9eba1; + } + } + else { + if (i < 60) { + f = (b & c) | (d & (b | c)); + k = 0x8f1bbcdc; + } + else { + f = b ^ c ^ d; + k = 0xca62c1d6; + } + } + const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff; + e = d; + d = c; + c = ((b << 30) | (b >>> 2)) & 0xffffffff; + b = a; + a = t; + } + this.chain_[0] = (this.chain_[0] + a) & 0xffffffff; + this.chain_[1] = (this.chain_[1] + b) & 0xffffffff; + this.chain_[2] = (this.chain_[2] + c) & 0xffffffff; + this.chain_[3] = (this.chain_[3] + d) & 0xffffffff; + this.chain_[4] = (this.chain_[4] + e) & 0xffffffff; + } + update(bytes, length) { + // TODO(johnlenz): tighten the function signature and remove this check + if (bytes == null) { + return; + } + if (length === undefined) { + length = bytes.length; + } + const lengthMinusBlock = length - this.blockSize; + let n = 0; + // Using local instead of member variables gives ~5% speedup on Firefox 16. + const buf = this.buf_; + let inbuf = this.inbuf_; + // The outer while loop should execute at most twice. + while (n < length) { + // When we have no data in the block to top up, we can directly process the + // input buffer (assuming it contains sufficient data). This gives ~25% + // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that + // the data is provided in large chunks (or in multiples of 64 bytes). + if (inbuf === 0) { + while (n <= lengthMinusBlock) { + this.compress_(bytes, n); + n += this.blockSize; + } + } + if (typeof bytes === 'string') { + while (n < length) { + buf[inbuf] = bytes.charCodeAt(n); + ++inbuf; + ++n; + if (inbuf === this.blockSize) { + this.compress_(buf); + inbuf = 0; + // Jump to the outer loop so we use the full-block optimization. + break; + } + } + } + else { + while (n < length) { + buf[inbuf] = bytes[n]; + ++inbuf; + ++n; + if (inbuf === this.blockSize) { + this.compress_(buf); + inbuf = 0; + // Jump to the outer loop so we use the full-block optimization. + break; + } + } + } + } + this.inbuf_ = inbuf; + this.total_ += length; + } + /** @override */ + digest() { + const digest = []; + let totalBits = this.total_ * 8; + // Add pad 0x80 0x00*. + if (this.inbuf_ < 56) { + this.update(this.pad_, 56 - this.inbuf_); + } + else { + this.update(this.pad_, this.blockSize - (this.inbuf_ - 56)); + } + // Add # bits. + for (let i = this.blockSize - 1; i >= 56; i--) { + this.buf_[i] = totalBits & 255; + totalBits /= 256; // Don't use bit-shifting here! + } + this.compress_(this.buf_); + let n = 0; + for (let i = 0; i < 5; i++) { + for (let j = 24; j >= 0; j -= 8) { + digest[n] = (this.chain_[i] >> j) & 255; + ++n; + } + } + return digest; + } +} + +/** + * Helper to make a Subscribe function (just like Promise helps make a + * Thenable). + * + * @param executor Function which can make calls to a single Observer + * as a proxy. + * @param onNoObservers Callback when count of Observers goes to zero. + */ +function createSubscribe(executor, onNoObservers) { + const proxy = new ObserverProxy(executor, onNoObservers); + return proxy.subscribe.bind(proxy); +} +/** + * Implement fan-out for any number of Observers attached via a subscribe + * function. + */ +class ObserverProxy { + /** + * @param executor Function which can make calls to a single Observer + * as a proxy. + * @param onNoObservers Callback when count of Observers goes to zero. + */ + constructor(executor, onNoObservers) { + this.observers = []; + this.unsubscribes = []; + this.observerCount = 0; + // Micro-task scheduling by calling task.then(). + this.task = Promise.resolve(); + this.finalized = false; + this.onNoObservers = onNoObservers; + // Call the executor asynchronously so subscribers that are called + // synchronously after the creation of the subscribe function + // can still receive the very first value generated in the executor. + this.task + .then(() => { + executor(this); + }) + .catch(e => { + this.error(e); + }); + } + next(value) { + this.forEachObserver((observer) => { + observer.next(value); + }); + } + error(error) { + this.forEachObserver((observer) => { + observer.error(error); + }); + this.close(error); + } + complete() { + this.forEachObserver((observer) => { + observer.complete(); + }); + this.close(); + } + /** + * Subscribe function that can be used to add an Observer to the fan-out list. + * + * - We require that no event is sent to a subscriber synchronously to their + * call to subscribe(). + */ + subscribe(nextOrObserver, error, complete) { + let observer; + if (nextOrObserver === undefined && + error === undefined && + complete === undefined) { + throw new Error('Missing Observer.'); + } + // Assemble an Observer object when passed as callback functions. + if (implementsAnyMethods(nextOrObserver, [ + 'next', + 'error', + 'complete' + ])) { + observer = nextOrObserver; + } + else { + observer = { + next: nextOrObserver, + error, + complete + }; + } + if (observer.next === undefined) { + observer.next = noop; + } + if (observer.error === undefined) { + observer.error = noop; + } + if (observer.complete === undefined) { + observer.complete = noop; + } + const unsub = this.unsubscribeOne.bind(this, this.observers.length); + // Attempt to subscribe to a terminated Observable - we + // just respond to the Observer with the final error or complete + // event. + if (this.finalized) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.task.then(() => { + try { + if (this.finalError) { + observer.error(this.finalError); + } + else { + observer.complete(); + } + } + catch (e) { + // nothing + } + return; + }); + } + this.observers.push(observer); + return unsub; + } + // Unsubscribe is synchronous - we guarantee that no events are sent to + // any unsubscribed Observer. + unsubscribeOne(i) { + if (this.observers === undefined || this.observers[i] === undefined) { + return; + } + delete this.observers[i]; + this.observerCount -= 1; + if (this.observerCount === 0 && this.onNoObservers !== undefined) { + this.onNoObservers(this); + } + } + forEachObserver(fn) { + if (this.finalized) { + // Already closed by previous event....just eat the additional values. + return; + } + // Since sendOne calls asynchronously - there is no chance that + // this.observers will become undefined. + for (let i = 0; i < this.observers.length; i++) { + this.sendOne(i, fn); + } + } + // Call the Observer via one of it's callback function. We are careful to + // confirm that the observe has not been unsubscribed since this asynchronous + // function had been queued. + sendOne(i, fn) { + // Execute the callback asynchronously + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.task.then(() => { + if (this.observers !== undefined && this.observers[i] !== undefined) { + try { + fn(this.observers[i]); + } + catch (e) { + // Ignore exceptions raised in Observers or missing methods of an + // Observer. + // Log error to console. b/31404806 + if (typeof console !== 'undefined' && console.error) { + console.error(e); + } + } + } + }); + } + close(err) { + if (this.finalized) { + return; + } + this.finalized = true; + if (err !== undefined) { + this.finalError = err; + } + // Proxy is no longer needed - garbage collect references + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.task.then(() => { + this.observers = undefined; + this.onNoObservers = undefined; + }); + } +} +/** Turn synchronous function into one called asynchronously. */ +// eslint-disable-next-line @typescript-eslint/ban-types +function async(fn, onError) { + return (...args) => { + Promise.resolve(true) + .then(() => { + fn(...args); + }) + .catch((error) => { + if (onError) { + onError(error); + } + }); + }; +} +/** + * Return true if the object passed in implements any of the named methods. + */ +function implementsAnyMethods(obj, methods) { + if (typeof obj !== 'object' || obj === null) { + return false; + } + for (const method of methods) { + if (method in obj && typeof obj[method] === 'function') { + return true; + } + } + return false; +} +function noop() { + // do nothing +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Check to make sure the appropriate number of arguments are provided for a public function. + * Throws an error if it fails. + * + * @param fnName The function name + * @param minCount The minimum number of arguments to allow for the function call + * @param maxCount The maximum number of argument to allow for the function call + * @param argCount The actual number of arguments provided. + */ +const validateArgCount = function (fnName, minCount, maxCount, argCount) { + let argError; + if (argCount < minCount) { + argError = 'at least ' + minCount; + } + else if (argCount > maxCount) { + argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount; + } + if (argError) { + const error = fnName + + ' failed: Was called with ' + + argCount + + (argCount === 1 ? ' argument.' : ' arguments.') + + ' Expects ' + + argError + + '.'; + throw new Error(error); + } +}; +/** + * Generates a string to prefix an error message about failed argument validation + * + * @param fnName The function name + * @param argName The name of the argument + * @return The prefix to add to the error thrown for validation. + */ +function errorPrefix(fnName, argName) { + return `${fnName} failed: ${argName} argument `; +} +/** + * @param fnName + * @param argumentNumber + * @param namespace + * @param optional + */ +function validateNamespace(fnName, namespace, optional) { + if (optional && !namespace) { + return; + } + if (typeof namespace !== 'string') { + //TODO: I should do more validation here. We only allow certain chars in namespaces. + throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.'); + } +} +function validateCallback(fnName, argumentName, +// eslint-disable-next-line @typescript-eslint/ban-types +callback, optional) { + if (optional && !callback) { + return; + } + if (typeof callback !== 'function') { + throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.'); + } +} +function validateContextObject(fnName, argumentName, context, optional) { + if (optional && !context) { + return; + } + if (typeof context !== 'object' || context === null) { + throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they +// automatically replaced '\r\n' with '\n', and they didn't handle surrogate pairs, +// so it's been modified. +// Note that not all Unicode characters appear as single characters in JavaScript strings. +// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters +// use 2 characters in JavaScript. All 4-byte UTF-8 characters begin with a first +// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate +// pair). +// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3 +/** + * @param {string} str + * @return {Array} + */ +const stringToByteArray = function (str) { + const out = []; + let p = 0; + for (let i = 0; i < str.length; i++) { + let c = str.charCodeAt(i); + // Is this the lead surrogate in a surrogate pair? + if (c >= 0xd800 && c <= 0xdbff) { + const high = c - 0xd800; // the high 10 bits. + i++; + assert(i < str.length, 'Surrogate pair missing trail surrogate.'); + const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits. + c = 0x10000 + (high << 10) + low; + } + if (c < 128) { + out[p++] = c; + } + else if (c < 2048) { + out[p++] = (c >> 6) | 192; + out[p++] = (c & 63) | 128; + } + else if (c < 65536) { + out[p++] = (c >> 12) | 224; + out[p++] = ((c >> 6) & 63) | 128; + out[p++] = (c & 63) | 128; + } + else { + out[p++] = (c >> 18) | 240; + out[p++] = ((c >> 12) & 63) | 128; + out[p++] = ((c >> 6) & 63) | 128; + out[p++] = (c & 63) | 128; + } + } + return out; +}; +/** + * Calculate length without actually converting; useful for doing cheaper validation. + * @param {string} str + * @return {number} + */ +const stringLength = function (str) { + let p = 0; + for (let i = 0; i < str.length; i++) { + const c = str.charCodeAt(i); + if (c < 128) { + p++; + } + else if (c < 2048) { + p += 2; + } + else if (c >= 0xd800 && c <= 0xdbff) { + // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent. + p += 4; + i++; // skip trail surrogate. + } + else { + p += 3; + } + } + return p; +}; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The amount of milliseconds to exponentially increase. + */ +const DEFAULT_INTERVAL_MILLIS = 1000; +/** + * The factor to backoff by. + * Should be a number greater than 1. + */ +const DEFAULT_BACKOFF_FACTOR = 2; +/** + * The maximum milliseconds to increase to. + * + *

Visible for testing + */ +const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android. +/** + * The percentage of backoff time to randomize by. + * See + * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic + * for context. + * + *

Visible for testing + */ +const RANDOM_FACTOR = 0.5; +/** + * Based on the backoff method from + * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js. + * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around. + */ +function calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) { + // Calculates an exponentially increasing value. + // Deviation: calculates value from count and a constant interval, so we only need to save value + // and count to restore state. + const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount); + // A random "fuzz" to avoid waves of retries. + // Deviation: randomFactor is required. + const randomWait = Math.round( + // A fraction of the backoff value to add/subtract. + // Deviation: changes multiplication order to improve readability. + RANDOM_FACTOR * + currBaseValue * + // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines + // if we add or subtract. + (Math.random() - 0.5) * + 2); + // Limits backoff to max to avoid effectively permanent backoff. + return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provide English ordinal letters after a number + */ +function ordinal(i) { + if (!Number.isFinite(i)) { + return `${i}`; + } + return i + indicator(i); +} +function indicator(i) { + i = Math.abs(i); + const cent = i % 100; + if (cent >= 10 && cent <= 20) { + return 'th'; + } + const dec = i % 10; + if (dec === 1) { + return 'st'; + } + if (dec === 2) { + return 'nd'; + } + if (dec === 3) { + return 'rd'; + } + return 'th'; +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function getModularInstance(service) { + if (service && service._delegate) { + return service._delegate; + } + else { + return service; + } +} + +exports.CONSTANTS = CONSTANTS; +exports.DecodeBase64StringError = DecodeBase64StringError; +exports.Deferred = Deferred; +exports.ErrorFactory = ErrorFactory; +exports.FirebaseError = FirebaseError; +exports.MAX_VALUE_MILLIS = MAX_VALUE_MILLIS; +exports.RANDOM_FACTOR = RANDOM_FACTOR; +exports.Sha1 = Sha1; +exports.areCookiesEnabled = areCookiesEnabled; +exports.assert = assert; +exports.assertionError = assertionError; +exports.async = async; +exports.base64 = base64; +exports.base64Decode = base64Decode; +exports.base64Encode = base64Encode; +exports.base64urlEncodeWithoutPadding = base64urlEncodeWithoutPadding; +exports.calculateBackoffMillis = calculateBackoffMillis; +exports.contains = contains; +exports.createMockUserToken = createMockUserToken; +exports.createSubscribe = createSubscribe; +exports.decode = decode; +exports.deepCopy = deepCopy; +exports.deepEqual = deepEqual; +exports.deepExtend = deepExtend; +exports.errorPrefix = errorPrefix; +exports.extractQuerystring = extractQuerystring; +exports.getDefaultAppConfig = getDefaultAppConfig; +exports.getDefaultEmulatorHost = getDefaultEmulatorHost; +exports.getDefaultEmulatorHostnameAndPort = getDefaultEmulatorHostnameAndPort; +exports.getDefaults = getDefaults; +exports.getExperimentalSetting = getExperimentalSetting; +exports.getGlobal = getGlobal; +exports.getModularInstance = getModularInstance; +exports.getUA = getUA; +exports.isAdmin = isAdmin; +exports.isBrowser = isBrowser; +exports.isBrowserExtension = isBrowserExtension; +exports.isCloudWorkstation = isCloudWorkstation; +exports.isCloudflareWorker = isCloudflareWorker; +exports.isElectron = isElectron; +exports.isEmpty = isEmpty; +exports.isIE = isIE; +exports.isIndexedDBAvailable = isIndexedDBAvailable; +exports.isMobileCordova = isMobileCordova; +exports.isNode = isNode; +exports.isNodeSdk = isNodeSdk; +exports.isReactNative = isReactNative; +exports.isSafari = isSafari; +exports.isSafariOrWebkit = isSafariOrWebkit; +exports.isUWP = isUWP; +exports.isValidFormat = isValidFormat; +exports.isValidTimestamp = isValidTimestamp; +exports.isWebWorker = isWebWorker; +exports.issuedAtTime = issuedAtTime; +exports.jsonEval = jsonEval; +exports.map = map; +exports.ordinal = ordinal; +exports.pingServer = pingServer; +exports.promiseWithTimeout = promiseWithTimeout; +exports.querystring = querystring; +exports.querystringDecode = querystringDecode; +exports.safeGet = safeGet; +exports.stringLength = stringLength; +exports.stringToByteArray = stringToByteArray; +exports.stringify = stringify; +exports.updateEmulatorBanner = updateEmulatorBanner; +exports.validateArgCount = validateArgCount; +exports.validateCallback = validateCallback; +exports.validateContextObject = validateContextObject; +exports.validateIndexedDBOpenable = validateIndexedDBOpenable; +exports.validateNamespace = validateNamespace; +//# sourceMappingURL=index.cjs.js.map diff --git a/node_modules/@firebase/util/dist/index.cjs.js.map b/node_modules/@firebase/util/dist/index.cjs.js.map new file mode 100644 index 0000000..fea08d8 --- /dev/null +++ b/node_modules/@firebase/util/dist/index.cjs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.cjs.js","sources":["../src/constants.ts","../src/assert.ts","../src/crypt.ts","../src/deepCopy.ts","../src/global.ts","../src/defaults.ts","../src/deferred.ts","../src/url.ts","../src/emulator.ts","../src/environment.ts","../src/errors.ts","../src/json.ts","../src/jwt.ts","../src/obj.ts","../src/promise.ts","../src/query.ts","../src/sha1.ts","../src/subscribe.ts","../src/validation.ts","../src/utf8.ts","../src/exponential_backoff.ts","../src/formatters.ts","../src/compat.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\n */\n\nexport const CONSTANTS = {\n /**\n * @define {boolean} Whether this is the client Node.js SDK.\n */\n NODE_CLIENT: false,\n /**\n * @define {boolean} Whether this is the Admin Node.js SDK.\n */\n NODE_ADMIN: false,\n\n /**\n * Firebase SDK Version\n */\n SDK_VERSION: '${JSCORE_VERSION}'\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSTANTS } from './constants';\n\n/**\n * Throws an error if the provided assertion is falsy\n */\nexport const assert = function (assertion: unknown, message: string): void {\n if (!assertion) {\n throw assertionError(message);\n }\n};\n\n/**\n * Returns an Error object suitable for throwing.\n */\nexport const assertionError = function (message: string): Error {\n return new Error(\n 'Firebase Database (' +\n CONSTANTS.SDK_VERSION +\n ') INTERNAL ASSERT FAILED: ' +\n message\n );\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst stringToByteArray = function (str: string): number[] {\n // TODO(user): Use native implementations if/when available\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (\n (c & 0xfc00) === 0xd800 &&\n i + 1 < str.length &&\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00\n ) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param bytes Array of numbers representing characters.\n * @return Stringification of the array.\n */\nconst byteArrayToString = function (bytes: number[]): string {\n // TODO(user): Use native implementations if/when available\n const out: string[] = [];\n let pos = 0,\n c = 0;\n while (pos < bytes.length) {\n const c1 = bytes[pos++];\n if (c1 < 128) {\n out[c++] = String.fromCharCode(c1);\n } else if (c1 > 191 && c1 < 224) {\n const c2 = bytes[pos++];\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n } else if (c1 > 239 && c1 < 365) {\n // Surrogate Pair\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n const c4 = bytes[pos++];\n const u =\n (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n 0x10000;\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n } else {\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n out[c++] = String.fromCharCode(\n ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)\n );\n }\n }\n return out.join('');\n};\n\ninterface Base64 {\n byteToCharMap_: { [key: number]: string } | null;\n charToByteMap_: { [key: string]: number } | null;\n byteToCharMapWebSafe_: { [key: number]: string } | null;\n charToByteMapWebSafe_: { [key: string]: number } | null;\n ENCODED_VALS_BASE: string;\n readonly ENCODED_VALS: string;\n readonly ENCODED_VALS_WEBSAFE: string;\n HAS_NATIVE_SUPPORT: boolean;\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string;\n encodeString(input: string, webSafe?: boolean): string;\n decodeString(input: string, webSafe: boolean): string;\n decodeStringToByteArray(input: string, webSafe: boolean): number[];\n init_(): void;\n}\n\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\n// Static lookup maps, lazily populated by init_()\n// TODO(dlarocque): Define this as a class, since we no longer target ES5.\nexport const base64: Base64 = {\n /**\n * Maps bytes to characters.\n */\n byteToCharMap_: null,\n\n /**\n * Maps characters to bytes.\n */\n charToByteMap_: null,\n\n /**\n * Maps bytes to websafe characters.\n * @private\n */\n byteToCharMapWebSafe_: null,\n\n /**\n * Maps websafe characters to bytes.\n * @private\n */\n charToByteMapWebSafe_: null,\n\n /**\n * Our default alphabet, shared between\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n */\n ENCODED_VALS_BASE:\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n\n /**\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n */\n get ENCODED_VALS() {\n return this.ENCODED_VALS_BASE + '+/=';\n },\n\n /**\n * Our websafe alphabet.\n */\n get ENCODED_VALS_WEBSAFE() {\n return this.ENCODED_VALS_BASE + '-_.';\n },\n\n /**\n * Whether this browser supports the atob and btoa functions. This extension\n * started at Mozilla but is now implemented by many browsers. We use the\n * ASSUME_* variables to avoid pulling in the full useragent detection library\n * but still allowing the standard per-browser compilations.\n *\n */\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\n\n /**\n * Base64-encode an array of bytes.\n *\n * @param input An array of bytes (numbers with\n * value in [0, 255]) to encode.\n * @param webSafe Boolean indicating we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string {\n if (!Array.isArray(input)) {\n throw Error('encodeByteArray takes an array as a parameter');\n }\n\n this.init_();\n\n const byteToCharMap = webSafe\n ? this.byteToCharMapWebSafe_!\n : this.byteToCharMap_!;\n\n const output = [];\n\n for (let i = 0; i < input.length; i += 3) {\n const byte1 = input[i];\n const haveByte2 = i + 1 < input.length;\n const byte2 = haveByte2 ? input[i + 1] : 0;\n const haveByte3 = i + 2 < input.length;\n const byte3 = haveByte3 ? input[i + 2] : 0;\n\n const outByte1 = byte1 >> 2;\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n let outByte4 = byte3 & 0x3f;\n\n if (!haveByte3) {\n outByte4 = 64;\n\n if (!haveByte2) {\n outByte3 = 64;\n }\n }\n\n output.push(\n byteToCharMap[outByte1],\n byteToCharMap[outByte2],\n byteToCharMap[outByte3],\n byteToCharMap[outByte4]\n );\n }\n\n return output.join('');\n },\n\n /**\n * Base64-encode a string.\n *\n * @param input A string to encode.\n * @param webSafe If true, we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeString(input: string, webSafe?: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return btoa(input);\n }\n return this.encodeByteArray(stringToByteArray(input), webSafe);\n },\n\n /**\n * Base64-decode a string.\n *\n * @param input to decode.\n * @param webSafe True if we should use the\n * alternative alphabet.\n * @return string representing the decoded value.\n */\n decodeString(input: string, webSafe: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return atob(input);\n }\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\n },\n\n /**\n * Base64-decode a string.\n *\n * In base-64 decoding, groups of four characters are converted into three\n * bytes. If the encoder did not apply padding, the input length may not\n * be a multiple of 4.\n *\n * In this case, the last group will have fewer than 4 characters, and\n * padding will be inferred. If the group has one or two characters, it decodes\n * to one byte. If the group has three characters, it decodes to two bytes.\n *\n * @param input Input to decode.\n * @param webSafe True if we should use the web-safe alphabet.\n * @return bytes representing the decoded value.\n */\n decodeStringToByteArray(input: string, webSafe: boolean): number[] {\n this.init_();\n\n const charToByteMap = webSafe\n ? this.charToByteMapWebSafe_!\n : this.charToByteMap_!;\n\n const output: number[] = [];\n\n for (let i = 0; i < input.length; ) {\n const byte1 = charToByteMap[input.charAt(i++)];\n\n const haveByte2 = i < input.length;\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n ++i;\n\n const haveByte3 = i < input.length;\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n const haveByte4 = i < input.length;\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n throw new DecodeBase64StringError();\n }\n\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\n output.push(outByte1);\n\n if (byte3 !== 64) {\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n output.push(outByte2);\n\n if (byte4 !== 64) {\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n output.push(outByte3);\n }\n }\n }\n\n return output;\n },\n\n /**\n * Lazy static initialization function. Called before\n * accessing any of the static map variables.\n * @private\n */\n init_() {\n if (!this.byteToCharMap_) {\n this.byteToCharMap_ = {};\n this.charToByteMap_ = {};\n this.byteToCharMapWebSafe_ = {};\n this.charToByteMapWebSafe_ = {};\n\n // We want quick mappings back and forth, so we precompute two maps.\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n\n // Be forgiving when decoding and correctly decode both encodings.\n if (i >= this.ENCODED_VALS_BASE.length) {\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n }\n }\n }\n }\n};\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class DecodeBase64StringError extends Error {\n readonly name = 'DecodeBase64StringError';\n}\n\n/**\n * URL-safe base64 encoding\n */\nexport const base64Encode = function (str: string): string {\n const utf8Bytes = stringToByteArray(str);\n return base64.encodeByteArray(utf8Bytes, true);\n};\n\n/**\n * URL-safe base64 encoding (without \".\" padding in the end).\n * e.g. Used in JSON Web Token (JWT) parts.\n */\nexport const base64urlEncodeWithoutPadding = function (str: string): string {\n // Use base64url encoding and remove padding in the end (dot characters).\n return base64Encode(str).replace(/\\./g, '');\n};\n\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param str To be decoded\n * @return Decoded result, if possible\n */\nexport const base64Decode = function (str: string): string | null {\n try {\n return base64.decodeString(str, true);\n } catch (e) {\n console.error('base64Decode failed: ', e);\n }\n return null;\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Do a deep-copy of basic JavaScript Objects or Arrays.\n */\nexport function deepCopy(value: T): T {\n return deepExtend(undefined, value) as T;\n}\n\n/**\n * Copy properties from source to target (recursively allows extension\n * of Objects and Arrays). Scalar values in the target are over-written.\n * If target is undefined, an object of the appropriate type will be created\n * (and returned).\n *\n * We recursively copy all child properties of plain Objects in the source- so\n * that namespace- like dictionaries are merged.\n *\n * Note that the target can be a function, in which case the properties in\n * the source Object are copied onto it as static properties of the Function.\n *\n * Note: we don't merge __proto__ to prevent prototype pollution\n */\nexport function deepExtend(target: unknown, source: unknown): unknown {\n if (!(source instanceof Object)) {\n return source;\n }\n\n switch (source.constructor) {\n case Date:\n // Treat Dates like scalars; if the target date object had any child\n // properties - they will be lost!\n const dateValue = source as Date;\n return new Date(dateValue.getTime());\n\n case Object:\n if (target === undefined) {\n target = {};\n }\n break;\n case Array:\n // Always copy the array source and overwrite the target.\n target = [];\n break;\n\n default:\n // Not a plain Object - treat it as a scalar.\n return source;\n }\n\n for (const prop in source) {\n // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202\n if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {\n continue;\n }\n (target as Record)[prop] = deepExtend(\n (target as Record)[prop],\n (source as Record)[prop]\n );\n }\n\n return target;\n}\n\nfunction isValidKey(key: string): boolean {\n return key !== '__proto__';\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Polyfill for `globalThis` object.\n * @returns the `globalThis` object for the given environment.\n * @public\n */\nexport function getGlobal(): typeof globalThis {\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('Unable to locate global object.');\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Decode } from './crypt';\nimport { getGlobal } from './global';\nimport { getDefaultsFromPostinstall } from './postinstall';\n\n/**\n * Keys for experimental properties on the `FirebaseDefaults` object.\n * @public\n */\nexport type ExperimentalKey = 'authTokenSyncURL' | 'authIdTokenMaxAge';\n\n/**\n * An object that can be injected into the environment as __FIREBASE_DEFAULTS__,\n * either as a property of globalThis, a shell environment variable, or a\n * cookie.\n *\n * This object can be used to automatically configure and initialize\n * a Firebase app as well as any emulators.\n *\n * @public\n */\nexport interface FirebaseDefaults {\n config?: Record;\n emulatorHosts?: Record;\n _authTokenSyncURL?: string;\n _authIdTokenMaxAge?: number;\n /**\n * Override Firebase's runtime environment detection and\n * force the SDK to act as if it were in the specified environment.\n */\n forceEnvironment?: 'browser' | 'node';\n [key: string]: unknown;\n}\n\ndeclare global {\n // Need `var` for this to work.\n // eslint-disable-next-line no-var\n var __FIREBASE_DEFAULTS__: FirebaseDefaults | undefined;\n}\n\nconst getDefaultsFromGlobal = (): FirebaseDefaults | undefined =>\n getGlobal().__FIREBASE_DEFAULTS__;\n\n/**\n * Attempt to read defaults from a JSON string provided to\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\n * The dots are in parens because certain compilers (Vite?) cannot\n * handle seeing that variable in comments.\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\n */\nconst getDefaultsFromEnvVariable = (): FirebaseDefaults | undefined => {\n if (typeof process === 'undefined' || typeof process.env === 'undefined') {\n return;\n }\n const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\n if (defaultsJsonString) {\n return JSON.parse(defaultsJsonString);\n }\n};\n\nconst getDefaultsFromCookie = (): FirebaseDefaults | undefined => {\n if (typeof document === 'undefined') {\n return;\n }\n let match;\n try {\n match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\n } catch (e) {\n // Some environments such as Angular Universal SSR have a\n // `document` object but error on accessing `document.cookie`.\n return;\n }\n const decoded = match && base64Decode(match[1]);\n return decoded && JSON.parse(decoded);\n};\n\n/**\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\n * (1) if such an object exists as a property of `globalThis`\n * (2) if such an object was provided on a shell environment variable\n * (3) if such an object exists in a cookie\n * @public\n */\nexport const getDefaults = (): FirebaseDefaults | undefined => {\n try {\n return (\n getDefaultsFromPostinstall() ||\n getDefaultsFromGlobal() ||\n getDefaultsFromEnvVariable() ||\n getDefaultsFromCookie()\n );\n } catch (e) {\n /**\n * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\n * to any environment case we have not accounted for. Log to\n * info instead of swallowing so we can find these unknown cases\n * and add paths for them if needed.\n */\n console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\n return;\n }\n};\n\n/**\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\n * @public\n */\nexport const getDefaultEmulatorHost = (\n productName: string\n): string | undefined => getDefaults()?.emulatorHosts?.[productName];\n\n/**\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\n * @public\n */\nexport const getDefaultEmulatorHostnameAndPort = (\n productName: string\n): [hostname: string, port: number] | undefined => {\n const host = getDefaultEmulatorHost(productName);\n if (!host) {\n return undefined;\n }\n const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\n if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\n throw new Error(`Invalid host ${host} with no separate hostname and port!`);\n }\n // eslint-disable-next-line no-restricted-globals\n const port = parseInt(host.substring(separatorIndex + 1), 10);\n if (host[0] === '[') {\n // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\n return [host.substring(1, separatorIndex - 1), port];\n } else {\n return [host.substring(0, separatorIndex), port];\n }\n};\n\n/**\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\n * @public\n */\nexport const getDefaultAppConfig = (): Record | undefined =>\n getDefaults()?.config;\n\n/**\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\n * prefixed by \"_\")\n * @public\n */\nexport const getExperimentalSetting = (\n name: T\n): FirebaseDefaults[`_${T}`] =>\n getDefaults()?.[`_${name}`] as FirebaseDefaults[`_${T}`];\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred {\n promise: Promise;\n reject: (value?: unknown) => void = () => {};\n resolve: (value?: unknown) => void = () => {};\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve as (value?: unknown) => void;\n this.reject = reject as (value?: unknown) => void;\n });\n }\n\n /**\n * Our API internals are not promisified and cannot because our callback APIs have subtle expectations around\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\n */\n wrapCallback(\n callback?: (error?: unknown, value?: unknown) => void\n ): (error: unknown, value?: unknown) => void {\n return (error, value?) => {\n if (error) {\n this.reject(error);\n } else {\n this.resolve(value);\n }\n if (typeof callback === 'function') {\n // Attaching noop handler just in case developer wasn't expecting\n // promises\n this.promise.catch(() => {});\n\n // Some of our callbacks don't expect a value and our own tests\n // assert that the parameter length is 1\n if (callback.length === 1) {\n callback(error);\n } else {\n callback(error, value);\n }\n }\n };\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Checks whether host is a cloud workstation or not.\n * @public\n */\nexport function isCloudWorkstation(url: string): boolean {\n // `isCloudWorkstation` is called without protocol in certain connect*Emulator functions\n // In HTTP request builders, it's called with the protocol.\n // If called with protocol prefix, it's a valid URL, so we extract the hostname\n // If called without, we assume the string is the hostname.\n try {\n const host =\n url.startsWith('http://') || url.startsWith('https://')\n ? new URL(url).hostname\n : url;\n return host.endsWith('.cloudworkstations.dev');\n } catch {\n return false;\n }\n}\n\n/**\n * Makes a fetch request to the given server.\n * Mostly used for forwarding cookies in Firebase Studio.\n * @public\n */\nexport async function pingServer(endpoint: string): Promise {\n const result = await fetch(endpoint, {\n credentials: 'include'\n });\n return result.ok;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64urlEncodeWithoutPadding } from './crypt';\nimport { isCloudWorkstation } from './url';\n\n// Firebase Auth tokens contain snake_case claims following the JWT standard / convention.\n/* eslint-disable camelcase */\n\nexport type FirebaseSignInProvider =\n | 'custom'\n | 'email'\n | 'password'\n | 'phone'\n | 'anonymous'\n | 'google.com'\n | 'facebook.com'\n | 'github.com'\n | 'twitter.com'\n | 'microsoft.com'\n | 'apple.com';\n\ninterface FirebaseIdToken {\n // Always set to https://securetoken.google.com/PROJECT_ID\n iss: string;\n\n // Always set to PROJECT_ID\n aud: string;\n\n // The user's unique ID\n sub: string;\n\n // The token issue time, in seconds since epoch\n iat: number;\n\n // The token expiry time, normally 'iat' + 3600\n exp: number;\n\n // The user's unique ID. Must be equal to 'sub'\n user_id: string;\n\n // The time the user authenticated, normally 'iat'\n auth_time: number;\n\n // The sign in provider, only set when the provider is 'anonymous'\n provider_id?: 'anonymous';\n\n // The user's primary email\n email?: string;\n\n // The user's email verification status\n email_verified?: boolean;\n\n // The user's primary phone number\n phone_number?: string;\n\n // The user's display name\n name?: string;\n\n // The user's profile photo URL\n picture?: string;\n\n // Information on all identities linked to this user\n firebase: {\n // The primary sign-in provider\n sign_in_provider: FirebaseSignInProvider;\n\n // A map of providers to the user's list of unique identifiers from\n // each provider\n identities?: { [provider in FirebaseSignInProvider]?: string[] };\n };\n\n // Custom claims set by the developer\n [claim: string]: unknown;\n\n uid?: never; // Try to catch a common mistake of \"uid\" (should be \"sub\" instead).\n}\n\nexport type EmulatorMockTokenOptions = ({ user_id: string } | { sub: string }) &\n Partial;\n\nexport function createMockUserToken(\n token: EmulatorMockTokenOptions,\n projectId?: string\n): string {\n if (token.uid) {\n throw new Error(\n 'The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.'\n );\n }\n // Unsecured JWTs use \"none\" as the algorithm.\n const header = {\n alg: 'none',\n type: 'JWT'\n };\n\n const project = projectId || 'demo-project';\n const iat = token.iat || 0;\n const sub = token.sub || token.user_id;\n if (!sub) {\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\n }\n\n const payload: FirebaseIdToken = {\n // Set all required fields to decent defaults\n iss: `https://securetoken.google.com/${project}`,\n aud: project,\n iat,\n exp: iat + 3600,\n auth_time: iat,\n sub,\n user_id: sub,\n firebase: {\n sign_in_provider: 'custom',\n identities: {}\n },\n\n // Override with user options\n ...token\n };\n\n // Unsecured JWTs use the empty string as a signature.\n const signature = '';\n return [\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\n signature\n ].join('.');\n}\n\ninterface EmulatorStatusMap {\n [name: string]: boolean;\n}\nconst emulatorStatus: EmulatorStatusMap = {};\n\ninterface EmulatorSummary {\n prod: string[];\n emulator: string[];\n}\n\n// Checks whether any products are running on an emulator\nfunction getEmulatorSummary(): EmulatorSummary {\n const summary: EmulatorSummary = {\n prod: [],\n emulator: []\n };\n for (const key of Object.keys(emulatorStatus)) {\n if (emulatorStatus[key]) {\n summary.emulator.push(key);\n } else {\n summary.prod.push(key);\n }\n }\n return summary;\n}\n\nfunction getOrCreateEl(id: string): { created: boolean; element: HTMLElement } {\n let parentDiv = document.getElementById(id);\n let created = false;\n if (!parentDiv) {\n parentDiv = document.createElement('div');\n parentDiv.setAttribute('id', id);\n created = true;\n }\n return { created, element: parentDiv };\n}\n\nlet previouslyDismissed = false;\n/**\n * Updates Emulator Banner. Primarily used for Firebase Studio\n * @param name\n * @param isRunningEmulator\n * @public\n */\nexport function updateEmulatorBanner(\n name: string,\n isRunningEmulator: boolean\n): void {\n if (\n typeof window === 'undefined' ||\n typeof document === 'undefined' ||\n !isCloudWorkstation(window.location.host) ||\n emulatorStatus[name] === isRunningEmulator ||\n emulatorStatus[name] || // If already set to use emulator, can't go back to prod.\n previouslyDismissed\n ) {\n return;\n }\n\n emulatorStatus[name] = isRunningEmulator;\n\n function prefixedId(id: string): string {\n return `__firebase__banner__${id}`;\n }\n const bannerId = '__firebase__banner';\n const summary = getEmulatorSummary();\n const showError = summary.prod.length > 0;\n\n function tearDown(): void {\n const element = document.getElementById(bannerId);\n if (element) {\n element.remove();\n }\n }\n\n function setupBannerStyles(bannerEl: HTMLElement): void {\n bannerEl.style.display = 'flex';\n bannerEl.style.background = '#7faaf0';\n bannerEl.style.position = 'fixed';\n bannerEl.style.bottom = '5px';\n bannerEl.style.left = '5px';\n bannerEl.style.padding = '.5em';\n bannerEl.style.borderRadius = '5px';\n bannerEl.style.alignItems = 'center';\n }\n\n function setupIconStyles(prependIcon: SVGElement, iconId: string): void {\n prependIcon.setAttribute('width', '24');\n prependIcon.setAttribute('id', iconId);\n prependIcon.setAttribute('height', '24');\n prependIcon.setAttribute('viewBox', '0 0 24 24');\n prependIcon.setAttribute('fill', 'none');\n prependIcon.style.marginLeft = '-6px';\n }\n\n function setupCloseBtn(): HTMLSpanElement {\n const closeBtn = document.createElement('span');\n closeBtn.style.cursor = 'pointer';\n closeBtn.style.marginLeft = '16px';\n closeBtn.style.fontSize = '24px';\n closeBtn.innerHTML = ' ×';\n closeBtn.onclick = () => {\n previouslyDismissed = true;\n tearDown();\n };\n return closeBtn;\n }\n\n function setupLinkStyles(\n learnMoreLink: HTMLAnchorElement,\n learnMoreId: string\n ): void {\n learnMoreLink.setAttribute('id', learnMoreId);\n learnMoreLink.innerText = 'Learn more';\n learnMoreLink.href =\n 'https://firebase.google.com/docs/studio/preview-apps#preview-backend';\n learnMoreLink.setAttribute('target', '__blank');\n learnMoreLink.style.paddingLeft = '5px';\n learnMoreLink.style.textDecoration = 'underline';\n }\n\n function setupDom(): void {\n const banner = getOrCreateEl(bannerId);\n const firebaseTextId = prefixedId('text');\n const firebaseText: HTMLSpanElement =\n document.getElementById(firebaseTextId) || document.createElement('span');\n const learnMoreId = prefixedId('learnmore');\n const learnMoreLink: HTMLAnchorElement =\n (document.getElementById(learnMoreId) as HTMLAnchorElement) ||\n document.createElement('a');\n const prependIconId = prefixedId('preprendIcon');\n const prependIcon: SVGElement =\n (document.getElementById(\n prependIconId\n ) as HTMLOrSVGElement as SVGElement) ||\n document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n if (banner.created) {\n // update styles\n const bannerEl = banner.element;\n setupBannerStyles(bannerEl);\n setupLinkStyles(learnMoreLink, learnMoreId);\n const closeBtn = setupCloseBtn();\n setupIconStyles(prependIcon, prependIconId);\n bannerEl.append(prependIcon, firebaseText, learnMoreLink, closeBtn);\n document.body.appendChild(bannerEl);\n }\n\n if (showError) {\n firebaseText.innerText = `Preview backend disconnected.`;\n prependIcon.innerHTML = `\n\n\n\n\n\n\n`;\n } else {\n prependIcon.innerHTML = `\n\n\n\n\n\n\n`;\n firebaseText.innerText = 'Preview backend running in this workspace.';\n }\n firebaseText.setAttribute('id', firebaseTextId);\n }\n if (document.readyState === 'loading') {\n window.addEventListener('DOMContentLoaded', setupDom);\n } else {\n setupDom();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSTANTS } from './constants';\nimport { getDefaults } from './defaults';\n\n/**\n * Type placeholder for `WorkerGlobalScope` from `webworker`\n */\ndeclare class WorkerGlobalScope {}\n\n/**\n * Returns navigator.userAgent string or '' if it's not defined.\n * @return user agent string\n */\nexport function getUA(): string {\n if (\n typeof navigator !== 'undefined' &&\n typeof navigator['userAgent'] === 'string'\n ) {\n return navigator['userAgent'];\n } else {\n return '';\n }\n}\n\n/**\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\n *\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\n * wait for a callback.\n */\nexport function isMobileCordova(): boolean {\n return (\n typeof window !== 'undefined' &&\n // @ts-ignore Setting up an broadly applicable index signature for Window\n // just to deal with this case would probably be a bad idea.\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())\n );\n}\n\n/**\n * Detect Node.js.\n *\n * @return true if Node.js environment is detected or specified.\n */\n// Node detection logic from: https://github.com/iliakan/detect-node/\nexport function isNode(): boolean {\n const forceEnvironment = getDefaults()?.forceEnvironment;\n if (forceEnvironment === 'node') {\n return true;\n } else if (forceEnvironment === 'browser') {\n return false;\n }\n\n try {\n return (\n Object.prototype.toString.call(global.process) === '[object process]'\n );\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Detect Browser Environment.\n * Note: This will return true for certain test frameworks that are incompletely\n * mimicking a browser, and should not lead to assuming all browser APIs are\n * available.\n */\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined' || isWebWorker();\n}\n\n/**\n * Detect Web Worker context.\n */\nexport function isWebWorker(): boolean {\n return (\n typeof WorkerGlobalScope !== 'undefined' &&\n typeof self !== 'undefined' &&\n self instanceof WorkerGlobalScope\n );\n}\n\n/**\n * Detect Cloudflare Worker context.\n */\nexport function isCloudflareWorker(): boolean {\n return (\n typeof navigator !== 'undefined' &&\n navigator.userAgent === 'Cloudflare-Workers'\n );\n}\n\n/**\n * Detect browser extensions (Chrome and Firefox at least).\n */\ninterface BrowserRuntime {\n id?: unknown;\n}\ndeclare const chrome: { runtime?: BrowserRuntime };\ndeclare const browser: { runtime?: BrowserRuntime };\nexport function isBrowserExtension(): boolean {\n const runtime =\n typeof chrome === 'object'\n ? chrome.runtime\n : typeof browser === 'object'\n ? browser.runtime\n : undefined;\n return typeof runtime === 'object' && runtime.id !== undefined;\n}\n\n/**\n * Detect React Native.\n *\n * @return true if ReactNative environment is detected.\n */\nexport function isReactNative(): boolean {\n return (\n typeof navigator === 'object' && navigator['product'] === 'ReactNative'\n );\n}\n\n/** Detects Electron apps. */\nexport function isElectron(): boolean {\n return getUA().indexOf('Electron/') >= 0;\n}\n\n/** Detects Internet Explorer. */\nexport function isIE(): boolean {\n const ua = getUA();\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\n}\n\n/** Detects Universal Windows Platform apps. */\nexport function isUWP(): boolean {\n return getUA().indexOf('MSAppHost/') >= 0;\n}\n\n/**\n * Detect whether the current SDK build is the Node version.\n *\n * @return true if it's the Node SDK build.\n */\nexport function isNodeSdk(): boolean {\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\n}\n\n/** Returns true if we are running in Safari. */\nexport function isSafari(): boolean {\n return (\n !isNode() &&\n !!navigator.userAgent &&\n navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome')\n );\n}\n\n/** Returns true if we are running in Safari or WebKit */\nexport function isSafariOrWebkit(): boolean {\n return (\n !isNode() &&\n !!navigator.userAgent &&\n (navigator.userAgent.includes('Safari') ||\n navigator.userAgent.includes('WebKit')) &&\n !navigator.userAgent.includes('Chrome')\n );\n}\n\n/**\n * This method checks if indexedDB is supported by current browser/service worker context\n * @return true if indexedDB is supported by current browser/service worker context\n */\nexport function isIndexedDBAvailable(): boolean {\n try {\n return typeof indexedDB === 'object';\n } catch (e) {\n return false;\n }\n}\n\n/**\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\n * if errors occur during the database open operation.\n *\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\n * private browsing)\n */\nexport function validateIndexedDBOpenable(): Promise {\n return new Promise((resolve, reject) => {\n try {\n let preExist: boolean = true;\n const DB_CHECK_NAME =\n 'validate-browser-context-for-indexeddb-analytics-module';\n const request = self.indexedDB.open(DB_CHECK_NAME);\n request.onsuccess = () => {\n request.result.close();\n // delete database only when it doesn't pre-exist\n if (!preExist) {\n self.indexedDB.deleteDatabase(DB_CHECK_NAME);\n }\n resolve(true);\n };\n request.onupgradeneeded = () => {\n preExist = false;\n };\n\n request.onerror = () => {\n reject(request.error?.message || '');\n };\n } catch (error) {\n reject(error);\n }\n });\n}\n\n/**\n *\n * This method checks whether cookie is enabled within current browser\n * @return true if cookie is enabled within current browser\n */\nexport function areCookiesEnabled(): boolean {\n if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\n return false;\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n * // TypeScript string literals for type-safe codes\n * type Err =\n * 'unknown' |\n * 'object-not-found'\n * ;\n *\n * // Closure enum for type-safe error codes\n * // at-enum {string}\n * var Err = {\n * UNKNOWN: 'unknown',\n * OBJECT_NOT_FOUND: 'object-not-found',\n * }\n *\n * let errors: Map = {\n * 'generic-error': \"Unknown error\",\n * 'file-not-found': \"Could not find file: {$file}\",\n * };\n *\n * // Type-safe function - must pass a valid error code as param.\n * let error = new ErrorFactory('service', 'Service', errors);\n *\n * ...\n * throw error.create(Err.GENERIC);\n * ...\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n * ...\n * // Service: Could not file file: foo.txt (service/file-not-found).\n *\n * catch (e) {\n * assert(e.message === \"Could not find file: foo.txt.\");\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\n * console.log(\"Could not read file: \" + e['file']);\n * }\n * }\n */\n\nexport type ErrorMap = {\n readonly [K in ErrorCode]: string;\n};\n\nconst ERROR_NAME = 'FirebaseError';\n\nexport interface StringLike {\n toString(): string;\n}\n\nexport interface ErrorData {\n [key: string]: unknown;\n}\n\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nexport class FirebaseError extends Error {\n /** The custom name for all FirebaseErrors. */\n readonly name: string = ERROR_NAME;\n\n constructor(\n /** The error code for this error. */\n readonly code: string,\n message: string,\n /** Custom data for this error. */\n public customData?: Record\n ) {\n super(message);\n\n // Fix For ES5\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget\n // which we can now use since we no longer target ES5.\n Object.setPrototypeOf(this, FirebaseError.prototype);\n\n // Maintains proper stack trace for where our error was thrown.\n // Only available on V8.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\n }\n }\n}\n\nexport class ErrorFactory<\n ErrorCode extends string,\n ErrorParams extends { readonly [K in ErrorCode]?: ErrorData } = {}\n> {\n constructor(\n private readonly service: string,\n private readonly serviceName: string,\n private readonly errors: ErrorMap\n ) {}\n\n create(\n code: K,\n ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []\n ): FirebaseError {\n const customData = (data[0] as ErrorData) || {};\n const fullCode = `${this.service}/${code}`;\n const template = this.errors[code];\n\n const message = template ? replaceTemplate(template, customData) : 'Error';\n // Service Name: Error message (service/code).\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n\n const error = new FirebaseError(fullCode, fullMessage, customData);\n\n return error;\n }\n}\n\nfunction replaceTemplate(template: string, data: ErrorData): string {\n return template.replace(PATTERN, (_, key) => {\n const value = data[key];\n return value != null ? String(value) : `<${key}?>`;\n });\n}\n\nconst PATTERN = /\\{\\$([^}]+)}/g;\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Evaluates a JSON string into a javascript object.\n *\n * @param {string} str A string containing JSON.\n * @return {*} The javascript object representing the specified JSON.\n */\nexport function jsonEval(str: string): unknown {\n return JSON.parse(str);\n}\n\n/**\n * Returns JSON representing a javascript object.\n * @param {*} data JavaScript object to be stringified.\n * @return {string} The JSON contents of the object.\n */\nexport function stringify(data: unknown): string {\n return JSON.stringify(data);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Decode } from './crypt';\nimport { jsonEval } from './json';\n\ninterface Claims {\n [key: string]: {};\n}\n\ninterface DecodedToken {\n header: object;\n claims: Claims;\n data: object;\n signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token into constituent parts.\n *\n * Notes:\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const decode = function (token: string): DecodedToken {\n let header = {},\n claims: Claims = {},\n data = {},\n signature = '';\n\n try {\n const parts = token.split('.');\n header = jsonEval(base64Decode(parts[0]) || '') as object;\n claims = jsonEval(base64Decode(parts[1]) || '') as Claims;\n signature = parts[2];\n data = claims['d'] || {};\n delete claims['d'];\n } catch (e) {}\n\n return {\n header,\n claims,\n data,\n signature\n };\n};\n\ninterface DecodedToken {\n header: object;\n claims: Claims;\n data: object;\n signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidTimestamp = function (token: string): boolean {\n const claims: Claims = decode(token).claims;\n const now: number = Math.floor(new Date().getTime() / 1000);\n let validSince: number = 0,\n validUntil: number = 0;\n\n if (typeof claims === 'object') {\n if (claims.hasOwnProperty('nbf')) {\n validSince = claims['nbf'] as number;\n } else if (claims.hasOwnProperty('iat')) {\n validSince = claims['iat'] as number;\n }\n\n if (claims.hasOwnProperty('exp')) {\n validUntil = claims['exp'] as number;\n } else {\n // token will expire after 24h by default\n validUntil = validSince + 86400;\n }\n }\n\n return (\n !!now &&\n !!validSince &&\n !!validUntil &&\n now >= validSince &&\n now <= validUntil\n );\n};\n\n/**\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\n *\n * Notes:\n * - May return null if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const issuedAtTime = function (token: string): number | null {\n const claims: Claims = decode(token).claims;\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\n return claims['iat'] as number;\n }\n return null;\n};\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidFormat = function (token: string): boolean {\n const decoded = decode(token),\n claims = decoded.claims;\n\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\n};\n\n/**\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isAdmin = function (token: string): boolean {\n const claims: Claims = decode(token).claims;\n return typeof claims === 'object' && claims['admin'] === true;\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function contains(obj: T, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function safeGet(\n obj: T,\n key: K\n): T[K] | undefined {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return obj[key];\n } else {\n return undefined;\n }\n}\n\nexport function isEmpty(obj: object): obj is {} {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\n\nexport function map(\n obj: { [key in K]: V },\n fn: (value: V, key: K, obj: { [key in K]: V }) => U,\n contextObj?: unknown\n): { [key in K]: U } {\n const res: Partial<{ [key in K]: U }> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n res[key] = fn.call(contextObj, obj[key], key, obj);\n }\n }\n return res as { [key in K]: U };\n}\n\n/**\n * Deep equal two objects. Support Arrays and Objects.\n */\nexport function deepEqual(a: object, b: object): boolean {\n if (a === b) {\n return true;\n }\n\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n for (const k of aKeys) {\n if (!bKeys.includes(k)) {\n return false;\n }\n\n const aProp = (a as Record)[k];\n const bProp = (b as Record)[k];\n if (isObject(aProp) && isObject(bProp)) {\n if (!deepEqual(aProp, bProp)) {\n return false;\n }\n } else if (aProp !== bProp) {\n return false;\n }\n }\n\n for (const k of bKeys) {\n if (!aKeys.includes(k)) {\n return false;\n }\n }\n return true;\n}\n\nfunction isObject(thing: unknown): thing is object {\n return thing !== null && typeof thing === 'object';\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from './deferred';\n\n/**\n * Rejects if the given promise doesn't resolve in timeInMS milliseconds.\n * @internal\n */\nexport function promiseWithTimeout(\n promise: Promise,\n timeInMS = 2000\n): Promise {\n const deferredPromise = new Deferred();\n setTimeout(() => deferredPromise.reject('timeout!'), timeInMS);\n promise.then(deferredPromise.resolve, deferredPromise.reject);\n return deferredPromise.promise;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\n * params object (e.g. {arg: 'val', arg2: 'val2'})\n * Note: You must prepend it with ? when adding it to a URL.\n */\nexport function querystring(querystringParams: {\n [key: string]: string | number;\n}): string {\n const params = [];\n for (const [key, value] of Object.entries(querystringParams)) {\n if (Array.isArray(value)) {\n value.forEach(arrayVal => {\n params.push(\n encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal)\n );\n });\n } else {\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n }\n }\n return params.length ? '&' + params.join('&') : '';\n}\n\n/**\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\n * (e.g. {arg: 'val', arg2: 'val2'})\n */\nexport function querystringDecode(querystring: string): Record {\n const obj: Record = {};\n const tokens = querystring.replace(/^\\?/, '').split('&');\n\n tokens.forEach(token => {\n if (token) {\n const [key, value] = token.split('=');\n obj[decodeURIComponent(key)] = decodeURIComponent(value);\n }\n });\n return obj;\n}\n\n/**\n * Extract the query string part of a URL, including the leading question mark (if present).\n */\nexport function extractQuerystring(url: string): string {\n const queryStart = url.indexOf('?');\n if (!queryStart) {\n return '';\n }\n const fragmentStart = url.indexOf('#', queryStart);\n return url.substring(\n queryStart,\n fragmentStart > 0 ? fragmentStart : undefined\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview SHA-1 cryptographic hash.\n * Variable names follow the notation in FIPS PUB 180-3:\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\n *\n * Usage:\n * var sha1 = new sha1();\n * sha1.update(bytes);\n * var hash = sha1.digest();\n *\n * Performance:\n * Chrome 23: ~400 Mbit/s\n * Firefox 16: ~250 Mbit/s\n *\n */\n\n/**\n * SHA-1 cryptographic hash constructor.\n *\n * The properties declared here are discussed in the above algorithm document.\n * @constructor\n * @final\n * @struct\n */\nexport class Sha1 {\n /**\n * Holds the previous values of accumulated variables a-e in the compress_\n * function.\n * @private\n */\n private chain_: number[] = [];\n\n /**\n * A buffer holding the partially computed hash result.\n * @private\n */\n private buf_: number[] = [];\n\n /**\n * An array of 80 bytes, each a part of the message to be hashed. Referred to\n * as the message schedule in the docs.\n * @private\n */\n private W_: number[] = [];\n\n /**\n * Contains data needed to pad messages less than 64 bytes.\n * @private\n */\n private pad_: number[] = [];\n\n /**\n * @private {number}\n */\n private inbuf_: number = 0;\n\n /**\n * @private {number}\n */\n private total_: number = 0;\n\n blockSize: number;\n\n constructor() {\n this.blockSize = 512 / 8;\n\n this.pad_[0] = 128;\n for (let i = 1; i < this.blockSize; ++i) {\n this.pad_[i] = 0;\n }\n\n this.reset();\n }\n\n reset(): void {\n this.chain_[0] = 0x67452301;\n this.chain_[1] = 0xefcdab89;\n this.chain_[2] = 0x98badcfe;\n this.chain_[3] = 0x10325476;\n this.chain_[4] = 0xc3d2e1f0;\n\n this.inbuf_ = 0;\n this.total_ = 0;\n }\n\n /**\n * Internal compress helper function.\n * @param buf Block to compress.\n * @param offset Offset of the block in the buffer.\n * @private\n */\n compress_(buf: number[] | Uint8Array | string, offset?: number): void {\n if (!offset) {\n offset = 0;\n }\n\n const W = this.W_;\n\n // get 16 big endian words\n if (typeof buf === 'string') {\n for (let i = 0; i < 16; i++) {\n // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\n // have a bug that turns the post-increment ++ operator into pre-increment\n // during JIT compilation. We have code that depends heavily on SHA-1 for\n // correctness and which is affected by this bug, so I've removed all uses\n // of post-increment ++ in which the result value is used. We can revert\n // this change once the Safari bug\n // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\n // most clients have been updated.\n W[i] =\n (buf.charCodeAt(offset) << 24) |\n (buf.charCodeAt(offset + 1) << 16) |\n (buf.charCodeAt(offset + 2) << 8) |\n buf.charCodeAt(offset + 3);\n offset += 4;\n }\n } else {\n for (let i = 0; i < 16; i++) {\n W[i] =\n (buf[offset] << 24) |\n (buf[offset + 1] << 16) |\n (buf[offset + 2] << 8) |\n buf[offset + 3];\n offset += 4;\n }\n }\n\n // expand to 80 words\n for (let i = 16; i < 80; i++) {\n const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\n W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\n }\n\n let a = this.chain_[0];\n let b = this.chain_[1];\n let c = this.chain_[2];\n let d = this.chain_[3];\n let e = this.chain_[4];\n let f, k;\n\n // TODO(user): Try to unroll this loop to speed up the computation.\n for (let i = 0; i < 80; i++) {\n if (i < 40) {\n if (i < 20) {\n f = d ^ (b & (c ^ d));\n k = 0x5a827999;\n } else {\n f = b ^ c ^ d;\n k = 0x6ed9eba1;\n }\n } else {\n if (i < 60) {\n f = (b & c) | (d & (b | c));\n k = 0x8f1bbcdc;\n } else {\n f = b ^ c ^ d;\n k = 0xca62c1d6;\n }\n }\n\n const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\n e = d;\n d = c;\n c = ((b << 30) | (b >>> 2)) & 0xffffffff;\n b = a;\n a = t;\n }\n\n this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\n this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\n this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\n this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\n this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\n }\n\n update(bytes?: number[] | Uint8Array | string, length?: number): void {\n // TODO(johnlenz): tighten the function signature and remove this check\n if (bytes == null) {\n return;\n }\n\n if (length === undefined) {\n length = bytes.length;\n }\n\n const lengthMinusBlock = length - this.blockSize;\n let n = 0;\n // Using local instead of member variables gives ~5% speedup on Firefox 16.\n const buf = this.buf_;\n let inbuf = this.inbuf_;\n\n // The outer while loop should execute at most twice.\n while (n < length) {\n // When we have no data in the block to top up, we can directly process the\n // input buffer (assuming it contains sufficient data). This gives ~25%\n // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\n // the data is provided in large chunks (or in multiples of 64 bytes).\n if (inbuf === 0) {\n while (n <= lengthMinusBlock) {\n this.compress_(bytes, n);\n n += this.blockSize;\n }\n }\n\n if (typeof bytes === 'string') {\n while (n < length) {\n buf[inbuf] = bytes.charCodeAt(n);\n ++inbuf;\n ++n;\n if (inbuf === this.blockSize) {\n this.compress_(buf);\n inbuf = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n } else {\n while (n < length) {\n buf[inbuf] = bytes[n];\n ++inbuf;\n ++n;\n if (inbuf === this.blockSize) {\n this.compress_(buf);\n inbuf = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n }\n }\n\n this.inbuf_ = inbuf;\n this.total_ += length;\n }\n\n /** @override */\n digest(): number[] {\n const digest: number[] = [];\n let totalBits = this.total_ * 8;\n\n // Add pad 0x80 0x00*.\n if (this.inbuf_ < 56) {\n this.update(this.pad_, 56 - this.inbuf_);\n } else {\n this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\n }\n\n // Add # bits.\n for (let i = this.blockSize - 1; i >= 56; i--) {\n this.buf_[i] = totalBits & 255;\n totalBits /= 256; // Don't use bit-shifting here!\n }\n\n this.compress_(this.buf_);\n\n let n = 0;\n for (let i = 0; i < 5; i++) {\n for (let j = 24; j >= 0; j -= 8) {\n digest[n] = (this.chain_[i] >> j) & 255;\n ++n;\n }\n }\n return digest;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport type NextFn = (value: T) => void;\nexport type ErrorFn = (error: Error) => void;\nexport type CompleteFn = () => void;\n\nexport interface Observer {\n // Called once for each value in a stream of values.\n next: NextFn;\n\n // A stream terminates by a single call to EITHER error() or complete().\n error: ErrorFn;\n\n // No events will be sent to next() once complete() is called.\n complete: CompleteFn;\n}\n\nexport type PartialObserver = Partial>;\n\n// TODO: Support also Unsubscribe.unsubscribe?\nexport type Unsubscribe = () => void;\n\n/**\n * The Subscribe interface has two forms - passing the inline function\n * callbacks, or a object interface with callback properties.\n */\nexport interface Subscribe {\n (next?: NextFn, error?: ErrorFn, complete?: CompleteFn): Unsubscribe;\n (observer: PartialObserver): Unsubscribe;\n}\n\nexport interface Observable {\n // Subscribe method\n subscribe: Subscribe;\n}\n\nexport type Executor = (observer: Observer) => void;\n\n/**\n * Helper to make a Subscribe function (just like Promise helps make a\n * Thenable).\n *\n * @param executor Function which can make calls to a single Observer\n * as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\nexport function createSubscribe(\n executor: Executor,\n onNoObservers?: Executor\n): Subscribe {\n const proxy = new ObserverProxy(executor, onNoObservers);\n return proxy.subscribe.bind(proxy);\n}\n\n/**\n * Implement fan-out for any number of Observers attached via a subscribe\n * function.\n */\nclass ObserverProxy implements Observer {\n private observers: Array> | undefined = [];\n private unsubscribes: Unsubscribe[] = [];\n private onNoObservers: Executor | undefined;\n private observerCount = 0;\n // Micro-task scheduling by calling task.then().\n private task = Promise.resolve();\n private finalized = false;\n private finalError?: Error;\n\n /**\n * @param executor Function which can make calls to a single Observer\n * as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\n constructor(executor: Executor, onNoObservers?: Executor) {\n this.onNoObservers = onNoObservers;\n // Call the executor asynchronously so subscribers that are called\n // synchronously after the creation of the subscribe function\n // can still receive the very first value generated in the executor.\n this.task\n .then(() => {\n executor(this);\n })\n .catch(e => {\n this.error(e);\n });\n }\n\n next(value: T): void {\n this.forEachObserver((observer: Observer) => {\n observer.next(value);\n });\n }\n\n error(error: Error): void {\n this.forEachObserver((observer: Observer) => {\n observer.error(error);\n });\n this.close(error);\n }\n\n complete(): void {\n this.forEachObserver((observer: Observer) => {\n observer.complete();\n });\n this.close();\n }\n\n /**\n * Subscribe function that can be used to add an Observer to the fan-out list.\n *\n * - We require that no event is sent to a subscriber synchronously to their\n * call to subscribe().\n */\n subscribe(\n nextOrObserver?: NextFn | PartialObserver,\n error?: ErrorFn,\n complete?: CompleteFn\n ): Unsubscribe {\n let observer: Observer;\n\n if (\n nextOrObserver === undefined &&\n error === undefined &&\n complete === undefined\n ) {\n throw new Error('Missing Observer.');\n }\n\n // Assemble an Observer object when passed as callback functions.\n if (\n implementsAnyMethods(nextOrObserver as { [key: string]: unknown }, [\n 'next',\n 'error',\n 'complete'\n ])\n ) {\n observer = nextOrObserver as Observer;\n } else {\n observer = {\n next: nextOrObserver as NextFn,\n error,\n complete\n } as Observer;\n }\n\n if (observer.next === undefined) {\n observer.next = noop as NextFn;\n }\n if (observer.error === undefined) {\n observer.error = noop as ErrorFn;\n }\n if (observer.complete === undefined) {\n observer.complete = noop as CompleteFn;\n }\n\n const unsub = this.unsubscribeOne.bind(this, this.observers!.length);\n\n // Attempt to subscribe to a terminated Observable - we\n // just respond to the Observer with the final error or complete\n // event.\n if (this.finalized) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n try {\n if (this.finalError) {\n observer.error(this.finalError);\n } else {\n observer.complete();\n }\n } catch (e) {\n // nothing\n }\n return;\n });\n }\n\n this.observers!.push(observer as Observer);\n\n return unsub;\n }\n\n // Unsubscribe is synchronous - we guarantee that no events are sent to\n // any unsubscribed Observer.\n private unsubscribeOne(i: number): void {\n if (this.observers === undefined || this.observers[i] === undefined) {\n return;\n }\n\n delete this.observers[i];\n\n this.observerCount -= 1;\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\n this.onNoObservers(this);\n }\n }\n\n private forEachObserver(fn: (observer: Observer) => void): void {\n if (this.finalized) {\n // Already closed by previous event....just eat the additional values.\n return;\n }\n\n // Since sendOne calls asynchronously - there is no chance that\n // this.observers will become undefined.\n for (let i = 0; i < this.observers!.length; i++) {\n this.sendOne(i, fn);\n }\n }\n\n // Call the Observer via one of it's callback function. We are careful to\n // confirm that the observe has not been unsubscribed since this asynchronous\n // function had been queued.\n private sendOne(i: number, fn: (observer: Observer) => void): void {\n // Execute the callback asynchronously\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n if (this.observers !== undefined && this.observers[i] !== undefined) {\n try {\n fn(this.observers[i]);\n } catch (e) {\n // Ignore exceptions raised in Observers or missing methods of an\n // Observer.\n // Log error to console. b/31404806\n if (typeof console !== 'undefined' && console.error) {\n console.error(e);\n }\n }\n }\n });\n }\n\n private close(err?: Error): void {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n if (err !== undefined) {\n this.finalError = err;\n }\n // Proxy is no longer needed - garbage collect references\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n this.observers = undefined;\n this.onNoObservers = undefined;\n });\n }\n}\n\n/** Turn synchronous function into one called asynchronously. */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function async(fn: Function, onError?: ErrorFn): Function {\n return (...args: unknown[]) => {\n Promise.resolve(true)\n .then(() => {\n fn(...args);\n })\n .catch((error: Error) => {\n if (onError) {\n onError(error);\n }\n });\n };\n}\n\n/**\n * Return true if the object passed in implements any of the named methods.\n */\nfunction implementsAnyMethods(\n obj: { [key: string]: unknown },\n methods: string[]\n): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n for (const method of methods) {\n if (method in obj && typeof obj[method] === 'function') {\n return true;\n }\n }\n\n return false;\n}\n\nfunction noop(): void {\n // do nothing\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Check to make sure the appropriate number of arguments are provided for a public function.\n * Throws an error if it fails.\n *\n * @param fnName The function name\n * @param minCount The minimum number of arguments to allow for the function call\n * @param maxCount The maximum number of argument to allow for the function call\n * @param argCount The actual number of arguments provided.\n */\nexport const validateArgCount = function (\n fnName: string,\n minCount: number,\n maxCount: number,\n argCount: number\n): void {\n let argError;\n if (argCount < minCount) {\n argError = 'at least ' + minCount;\n } else if (argCount > maxCount) {\n argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\n }\n if (argError) {\n const error =\n fnName +\n ' failed: Was called with ' +\n argCount +\n (argCount === 1 ? ' argument.' : ' arguments.') +\n ' Expects ' +\n argError +\n '.';\n throw new Error(error);\n }\n};\n\n/**\n * Generates a string to prefix an error message about failed argument validation\n *\n * @param fnName The function name\n * @param argName The name of the argument\n * @return The prefix to add to the error thrown for validation.\n */\nexport function errorPrefix(fnName: string, argName: string): string {\n return `${fnName} failed: ${argName} argument `;\n}\n\n/**\n * @param fnName\n * @param argumentNumber\n * @param namespace\n * @param optional\n */\nexport function validateNamespace(\n fnName: string,\n namespace: string,\n optional: boolean\n): void {\n if (optional && !namespace) {\n return;\n }\n if (typeof namespace !== 'string') {\n //TODO: I should do more validation here. We only allow certain chars in namespaces.\n throw new Error(\n errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.'\n );\n }\n}\n\nexport function validateCallback(\n fnName: string,\n argumentName: string,\n // eslint-disable-next-line @typescript-eslint/ban-types\n callback: Function,\n optional: boolean\n): void {\n if (optional && !callback) {\n return;\n }\n if (typeof callback !== 'function') {\n throw new Error(\n errorPrefix(fnName, argumentName) + 'must be a valid function.'\n );\n }\n}\n\nexport function validateContextObject(\n fnName: string,\n argumentName: string,\n context: unknown,\n optional: boolean\n): void {\n if (optional && !context) {\n return;\n }\n if (typeof context !== 'object' || context === null) {\n throw new Error(\n errorPrefix(fnName, argumentName) + 'must be a valid context object.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from './assert';\n\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\n// so it's been modified.\n\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\n// use 2 characters in JavaScript. All 4-byte UTF-8 characters begin with a first\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\n// pair).\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\n\n/**\n * @param {string} str\n * @return {Array}\n */\nexport const stringToByteArray = function (str: string): number[] {\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n\n // Is this the lead surrogate in a surrogate pair?\n if (c >= 0xd800 && c <= 0xdbff) {\n const high = c - 0xd800; // the high 10 bits.\n i++;\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\n const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\n c = 0x10000 + (high << 10) + low;\n }\n\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (c < 65536) {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Calculate length without actually converting; useful for doing cheaper validation.\n * @param {string} str\n * @return {number}\n */\nexport const stringLength = function (str: string): number {\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n const c = str.charCodeAt(i);\n if (c < 128) {\n p++;\n } else if (c < 2048) {\n p += 2;\n } else if (c >= 0xd800 && c <= 0xdbff) {\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\n p += 4;\n i++; // skip trail surrogate.\n } else {\n p += 3;\n }\n }\n return p;\n};\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The amount of milliseconds to exponentially increase.\n */\nconst DEFAULT_INTERVAL_MILLIS = 1000;\n\n/**\n * The factor to backoff by.\n * Should be a number greater than 1.\n */\nconst DEFAULT_BACKOFF_FACTOR = 2;\n\n/**\n * The maximum milliseconds to increase to.\n *\n *

Visible for testing\n */\nexport const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\n\n/**\n * The percentage of backoff time to randomize by.\n * See\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\n * for context.\n *\n *

Visible for testing\n */\nexport const RANDOM_FACTOR = 0.5;\n\n/**\n * Based on the backoff method from\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\n */\nexport function calculateBackoffMillis(\n backoffCount: number,\n intervalMillis: number = DEFAULT_INTERVAL_MILLIS,\n backoffFactor: number = DEFAULT_BACKOFF_FACTOR\n): number {\n // Calculates an exponentially increasing value.\n // Deviation: calculates value from count and a constant interval, so we only need to save value\n // and count to restore state.\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\n\n // A random \"fuzz\" to avoid waves of retries.\n // Deviation: randomFactor is required.\n const randomWait = Math.round(\n // A fraction of the backoff value to add/subtract.\n // Deviation: changes multiplication order to improve readability.\n RANDOM_FACTOR *\n currBaseValue *\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\n // if we add or subtract.\n (Math.random() - 0.5) *\n 2\n );\n\n // Limits backoff to max to avoid effectively permanent backoff.\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Provide English ordinal letters after a number\n */\nexport function ordinal(i: number): string {\n if (!Number.isFinite(i)) {\n return `${i}`;\n }\n return i + indicator(i);\n}\n\nfunction indicator(i: number): string {\n i = Math.abs(i);\n const cent = i % 100;\n if (cent >= 10 && cent <= 20) {\n return 'th';\n }\n const dec = i % 10;\n if (dec === 1) {\n return 'st';\n }\n if (dec === 2) {\n return 'nd';\n }\n if (dec === 3) {\n return 'rd';\n }\n return 'th';\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Compat {\n _delegate: T;\n}\n\nexport function getModularInstance(\n service: Compat | ExpService\n): ExpService {\n if (service && (service as Compat)._delegate) {\n return (service as Compat)._delegate;\n } else {\n return service as ExpService;\n }\n}\n"],"names":["stringToByteArray","getDefaultsFromPostinstall"],"mappings":";;;;;;AAAA,CAAA,CAAA;;;;;;;;;;;;;;;AAeG,CAAA,CAAA;AAEH,CAAA,CAAA;;AAEG,CAAA,CAA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,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAA8B,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAS;CACjD,CAAA,CAAA,CAAA;CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AACL,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAO,OAAqB;CAC7B,CAAA,CAAA,CAAA;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@firebase/util/dist/index.d.ts b/node_modules/@firebase/util/dist/index.d.ts new file mode 100644 index 0000000..2c31ac9 --- /dev/null +++ b/node_modules/@firebase/util/dist/index.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './src/assert'; +export * from './src/crypt'; +export * from './src/constants'; +export * from './src/deepCopy'; +export * from './src/defaults'; +export * from './src/deferred'; +export * from './src/emulator'; +export * from './src/environment'; +export * from './src/errors'; +export * from './src/json'; +export * from './src/jwt'; +export * from './src/obj'; +export * from './src/promise'; +export * from './src/query'; +export * from './src/sha1'; +export * from './src/subscribe'; +export * from './src/validation'; +export * from './src/utf8'; +export * from './src/exponential_backoff'; +export * from './src/formatters'; +export * from './src/compat'; +export * from './src/global'; +export * from './src/url'; diff --git a/node_modules/@firebase/util/dist/index.esm.js b/node_modules/@firebase/util/dist/index.esm.js new file mode 100644 index 0000000..b18b956 --- /dev/null +++ b/node_modules/@firebase/util/dist/index.esm.js @@ -0,0 +1,2318 @@ +import { getDefaultsFromPostinstall } from './postinstall.mjs'; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time. + */ +const CONSTANTS = { + /** + * @define {boolean} Whether this is the client Node.js SDK. + */ + NODE_CLIENT: false, + /** + * @define {boolean} Whether this is the Admin Node.js SDK. + */ + NODE_ADMIN: false, + /** + * Firebase SDK Version + */ + SDK_VERSION: '${JSCORE_VERSION}' +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Throws an error if the provided assertion is falsy + */ +const assert = function (assertion, message) { + if (!assertion) { + throw assertionError(message); + } +}; +/** + * Returns an Error object suitable for throwing. + */ +const assertionError = function (message) { + return new Error('Firebase Database (' + + CONSTANTS.SDK_VERSION + + ') INTERNAL ASSERT FAILED: ' + + message); +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const stringToByteArray$1 = function (str) { + // TODO(user): Use native implementations if/when available + const out = []; + let p = 0; + for (let i = 0; i < str.length; i++) { + let c = str.charCodeAt(i); + if (c < 128) { + out[p++] = c; + } + else if (c < 2048) { + out[p++] = (c >> 6) | 192; + out[p++] = (c & 63) | 128; + } + else if ((c & 0xfc00) === 0xd800 && + i + 1 < str.length && + (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { + // Surrogate Pair + c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff); + out[p++] = (c >> 18) | 240; + out[p++] = ((c >> 12) & 63) | 128; + out[p++] = ((c >> 6) & 63) | 128; + out[p++] = (c & 63) | 128; + } + else { + out[p++] = (c >> 12) | 224; + out[p++] = ((c >> 6) & 63) | 128; + out[p++] = (c & 63) | 128; + } + } + return out; +}; +/** + * Turns an array of numbers into the string given by the concatenation of the + * characters to which the numbers correspond. + * @param bytes Array of numbers representing characters. + * @return Stringification of the array. + */ +const byteArrayToString = function (bytes) { + // TODO(user): Use native implementations if/when available + const out = []; + let pos = 0, c = 0; + while (pos < bytes.length) { + const c1 = bytes[pos++]; + if (c1 < 128) { + out[c++] = String.fromCharCode(c1); + } + else if (c1 > 191 && c1 < 224) { + const c2 = bytes[pos++]; + out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63)); + } + else if (c1 > 239 && c1 < 365) { + // Surrogate Pair + const c2 = bytes[pos++]; + const c3 = bytes[pos++]; + const c4 = bytes[pos++]; + const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) - + 0x10000; + out[c++] = String.fromCharCode(0xd800 + (u >> 10)); + out[c++] = String.fromCharCode(0xdc00 + (u & 1023)); + } + else { + const c2 = bytes[pos++]; + const c3 = bytes[pos++]; + out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); + } + } + return out.join(''); +}; +// We define it as an object literal instead of a class because a class compiled down to es5 can't +// be treeshaked. https://github.com/rollup/rollup/issues/1691 +// Static lookup maps, lazily populated by init_() +// TODO(dlarocque): Define this as a class, since we no longer target ES5. +const base64 = { + /** + * Maps bytes to characters. + */ + byteToCharMap_: null, + /** + * Maps characters to bytes. + */ + charToByteMap_: null, + /** + * Maps bytes to websafe characters. + * @private + */ + byteToCharMapWebSafe_: null, + /** + * Maps websafe characters to bytes. + * @private + */ + charToByteMapWebSafe_: null, + /** + * Our default alphabet, shared between + * ENCODED_VALS and ENCODED_VALS_WEBSAFE + */ + ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789', + /** + * Our default alphabet. Value 64 (=) is special; it means "nothing." + */ + get ENCODED_VALS() { + return this.ENCODED_VALS_BASE + '+/='; + }, + /** + * Our websafe alphabet. + */ + get ENCODED_VALS_WEBSAFE() { + return this.ENCODED_VALS_BASE + '-_.'; + }, + /** + * Whether this browser supports the atob and btoa functions. This extension + * started at Mozilla but is now implemented by many browsers. We use the + * ASSUME_* variables to avoid pulling in the full useragent detection library + * but still allowing the standard per-browser compilations. + * + */ + HAS_NATIVE_SUPPORT: typeof atob === 'function', + /** + * Base64-encode an array of bytes. + * + * @param input An array of bytes (numbers with + * value in [0, 255]) to encode. + * @param webSafe Boolean indicating we should use the + * alternative alphabet. + * @return The base64 encoded string. + */ + encodeByteArray(input, webSafe) { + if (!Array.isArray(input)) { + throw Error('encodeByteArray takes an array as a parameter'); + } + this.init_(); + const byteToCharMap = webSafe + ? this.byteToCharMapWebSafe_ + : this.byteToCharMap_; + const output = []; + for (let i = 0; i < input.length; i += 3) { + const byte1 = input[i]; + const haveByte2 = i + 1 < input.length; + const byte2 = haveByte2 ? input[i + 1] : 0; + const haveByte3 = i + 2 < input.length; + const byte3 = haveByte3 ? input[i + 2] : 0; + const outByte1 = byte1 >> 2; + const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4); + let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6); + let outByte4 = byte3 & 0x3f; + if (!haveByte3) { + outByte4 = 64; + if (!haveByte2) { + outByte3 = 64; + } + } + output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]); + } + return output.join(''); + }, + /** + * Base64-encode a string. + * + * @param input A string to encode. + * @param webSafe If true, we should use the + * alternative alphabet. + * @return The base64 encoded string. + */ + encodeString(input, webSafe) { + // Shortcut for Mozilla browsers that implement + // a native base64 encoder in the form of "btoa/atob" + if (this.HAS_NATIVE_SUPPORT && !webSafe) { + return btoa(input); + } + return this.encodeByteArray(stringToByteArray$1(input), webSafe); + }, + /** + * Base64-decode a string. + * + * @param input to decode. + * @param webSafe True if we should use the + * alternative alphabet. + * @return string representing the decoded value. + */ + decodeString(input, webSafe) { + // Shortcut for Mozilla browsers that implement + // a native base64 encoder in the form of "btoa/atob" + if (this.HAS_NATIVE_SUPPORT && !webSafe) { + return atob(input); + } + return byteArrayToString(this.decodeStringToByteArray(input, webSafe)); + }, + /** + * Base64-decode a string. + * + * In base-64 decoding, groups of four characters are converted into three + * bytes. If the encoder did not apply padding, the input length may not + * be a multiple of 4. + * + * In this case, the last group will have fewer than 4 characters, and + * padding will be inferred. If the group has one or two characters, it decodes + * to one byte. If the group has three characters, it decodes to two bytes. + * + * @param input Input to decode. + * @param webSafe True if we should use the web-safe alphabet. + * @return bytes representing the decoded value. + */ + decodeStringToByteArray(input, webSafe) { + this.init_(); + const charToByteMap = webSafe + ? this.charToByteMapWebSafe_ + : this.charToByteMap_; + const output = []; + for (let i = 0; i < input.length;) { + const byte1 = charToByteMap[input.charAt(i++)]; + const haveByte2 = i < input.length; + const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0; + ++i; + const haveByte3 = i < input.length; + const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64; + ++i; + const haveByte4 = i < input.length; + const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64; + ++i; + if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) { + throw new DecodeBase64StringError(); + } + const outByte1 = (byte1 << 2) | (byte2 >> 4); + output.push(outByte1); + if (byte3 !== 64) { + const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2); + output.push(outByte2); + if (byte4 !== 64) { + const outByte3 = ((byte3 << 6) & 0xc0) | byte4; + output.push(outByte3); + } + } + } + return output; + }, + /** + * Lazy static initialization function. Called before + * accessing any of the static map variables. + * @private + */ + init_() { + if (!this.byteToCharMap_) { + this.byteToCharMap_ = {}; + this.charToByteMap_ = {}; + this.byteToCharMapWebSafe_ = {}; + this.charToByteMapWebSafe_ = {}; + // We want quick mappings back and forth, so we precompute two maps. + for (let i = 0; i < this.ENCODED_VALS.length; i++) { + this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i); + this.charToByteMap_[this.byteToCharMap_[i]] = i; + this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i); + this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i; + // Be forgiving when decoding and correctly decode both encodings. + if (i >= this.ENCODED_VALS_BASE.length) { + this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i; + this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i; + } + } + } + } +}; +/** + * An error encountered while decoding base64 string. + */ +class DecodeBase64StringError extends Error { + constructor() { + super(...arguments); + this.name = 'DecodeBase64StringError'; + } +} +/** + * URL-safe base64 encoding + */ +const base64Encode = function (str) { + const utf8Bytes = stringToByteArray$1(str); + return base64.encodeByteArray(utf8Bytes, true); +}; +/** + * URL-safe base64 encoding (without "." padding in the end). + * e.g. Used in JSON Web Token (JWT) parts. + */ +const base64urlEncodeWithoutPadding = function (str) { + // Use base64url encoding and remove padding in the end (dot characters). + return base64Encode(str).replace(/\./g, ''); +}; +/** + * URL-safe base64 decoding + * + * NOTE: DO NOT use the global atob() function - it does NOT support the + * base64Url variant encoding. + * + * @param str To be decoded + * @return Decoded result, if possible + */ +const base64Decode = function (str) { + try { + return base64.decodeString(str, true); + } + catch (e) { + console.error('base64Decode failed: ', e); + } + return null; +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Do a deep-copy of basic JavaScript Objects or Arrays. + */ +function deepCopy(value) { + return deepExtend(undefined, value); +} +/** + * Copy properties from source to target (recursively allows extension + * of Objects and Arrays). Scalar values in the target are over-written. + * If target is undefined, an object of the appropriate type will be created + * (and returned). + * + * We recursively copy all child properties of plain Objects in the source- so + * that namespace- like dictionaries are merged. + * + * Note that the target can be a function, in which case the properties in + * the source Object are copied onto it as static properties of the Function. + * + * Note: we don't merge __proto__ to prevent prototype pollution + */ +function deepExtend(target, source) { + if (!(source instanceof Object)) { + return source; + } + switch (source.constructor) { + case Date: + // Treat Dates like scalars; if the target date object had any child + // properties - they will be lost! + const dateValue = source; + return new Date(dateValue.getTime()); + case Object: + if (target === undefined) { + target = {}; + } + break; + case Array: + // Always copy the array source and overwrite the target. + target = []; + break; + default: + // Not a plain Object - treat it as a scalar. + return source; + } + for (const prop in source) { + // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202 + if (!source.hasOwnProperty(prop) || !isValidKey(prop)) { + continue; + } + target[prop] = deepExtend(target[prop], source[prop]); + } + return target; +} +function isValidKey(key) { + return key !== '__proto__'; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Polyfill for `globalThis` object. + * @returns the `globalThis` object for the given environment. + * @public + */ +function getGlobal() { + if (typeof self !== 'undefined') { + return self; + } + if (typeof window !== 'undefined') { + return window; + } + if (typeof global !== 'undefined') { + return global; + } + throw new Error('Unable to locate global object.'); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__; +/** + * Attempt to read defaults from a JSON string provided to + * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in + * process(.)env(.)__FIREBASE_DEFAULTS_PATH__ + * The dots are in parens because certain compilers (Vite?) cannot + * handle seeing that variable in comments. + * See https://github.com/firebase/firebase-js-sdk/issues/6838 + */ +const getDefaultsFromEnvVariable = () => { + if (typeof process === 'undefined' || typeof process.env === 'undefined') { + return; + } + const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__; + if (defaultsJsonString) { + return JSON.parse(defaultsJsonString); + } +}; +const getDefaultsFromCookie = () => { + if (typeof document === 'undefined') { + return; + } + let match; + try { + match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/); + } + catch (e) { + // Some environments such as Angular Universal SSR have a + // `document` object but error on accessing `document.cookie`. + return; + } + const decoded = match && base64Decode(match[1]); + return decoded && JSON.parse(decoded); +}; +/** + * Get the __FIREBASE_DEFAULTS__ object. It checks in order: + * (1) if such an object exists as a property of `globalThis` + * (2) if such an object was provided on a shell environment variable + * (3) if such an object exists in a cookie + * @public + */ +const getDefaults = () => { + try { + return (getDefaultsFromPostinstall() || + getDefaultsFromGlobal() || + getDefaultsFromEnvVariable() || + getDefaultsFromCookie()); + } + catch (e) { + /** + * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due + * to any environment case we have not accounted for. Log to + * info instead of swallowing so we can find these unknown cases + * and add paths for them if needed. + */ + console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`); + return; + } +}; +/** + * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object + * for the given product. + * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available + * @public + */ +const getDefaultEmulatorHost = (productName) => getDefaults()?.emulatorHosts?.[productName]; +/** + * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object + * for the given product. + * @returns a pair of hostname and port like `["::1", 4000]` if available + * @public + */ +const getDefaultEmulatorHostnameAndPort = (productName) => { + const host = getDefaultEmulatorHost(productName); + if (!host) { + return undefined; + } + const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons. + if (separatorIndex <= 0 || separatorIndex + 1 === host.length) { + throw new Error(`Invalid host ${host} with no separate hostname and port!`); + } + // eslint-disable-next-line no-restricted-globals + const port = parseInt(host.substring(separatorIndex + 1), 10); + if (host[0] === '[') { + // Bracket-quoted `[ipv6addr]:port` => return "ipv6addr" (without brackets). + return [host.substring(1, separatorIndex - 1), port]; + } + else { + return [host.substring(0, separatorIndex), port]; + } +}; +/** + * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object. + * @public + */ +const getDefaultAppConfig = () => getDefaults()?.config; +/** + * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties + * prefixed by "_") + * @public + */ +const getExperimentalSetting = (name) => getDefaults()?.[`_${name}`]; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Deferred { + constructor() { + this.reject = () => { }; + this.resolve = () => { }; + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } + /** + * Our API internals are not promisified and cannot because our callback APIs have subtle expectations around + * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback + * and returns a node-style callback which will resolve or reject the Deferred's promise. + */ + wrapCallback(callback) { + return (error, value) => { + if (error) { + this.reject(error); + } + else { + this.resolve(value); + } + if (typeof callback === 'function') { + // Attaching noop handler just in case developer wasn't expecting + // promises + this.promise.catch(() => { }); + // Some of our callbacks don't expect a value and our own tests + // assert that the parameter length is 1 + if (callback.length === 1) { + callback(error); + } + else { + callback(error, value); + } + } + }; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Checks whether host is a cloud workstation or not. + * @public + */ +function isCloudWorkstation(url) { + // `isCloudWorkstation` is called without protocol in certain connect*Emulator functions + // In HTTP request builders, it's called with the protocol. + // If called with protocol prefix, it's a valid URL, so we extract the hostname + // If called without, we assume the string is the hostname. + try { + const host = url.startsWith('http://') || url.startsWith('https://') + ? new URL(url).hostname + : url; + return host.endsWith('.cloudworkstations.dev'); + } + catch { + return false; + } +} +/** + * Makes a fetch request to the given server. + * Mostly used for forwarding cookies in Firebase Studio. + * @public + */ +async function pingServer(endpoint) { + const result = await fetch(endpoint, { + credentials: 'include' + }); + return result.ok; +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function createMockUserToken(token, projectId) { + if (token.uid) { + throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.'); + } + // Unsecured JWTs use "none" as the algorithm. + const header = { + alg: 'none', + type: 'JWT' + }; + const project = projectId || 'demo-project'; + const iat = token.iat || 0; + const sub = token.sub || token.user_id; + if (!sub) { + throw new Error("mockUserToken must contain 'sub' or 'user_id' field!"); + } + const payload = { + // Set all required fields to decent defaults + iss: `https://securetoken.google.com/${project}`, + aud: project, + iat, + exp: iat + 3600, + auth_time: iat, + sub, + user_id: sub, + firebase: { + sign_in_provider: 'custom', + identities: {} + }, + // Override with user options + ...token + }; + // Unsecured JWTs use the empty string as a signature. + const signature = ''; + return [ + base64urlEncodeWithoutPadding(JSON.stringify(header)), + base64urlEncodeWithoutPadding(JSON.stringify(payload)), + signature + ].join('.'); +} +const emulatorStatus = {}; +// Checks whether any products are running on an emulator +function getEmulatorSummary() { + const summary = { + prod: [], + emulator: [] + }; + for (const key of Object.keys(emulatorStatus)) { + if (emulatorStatus[key]) { + summary.emulator.push(key); + } + else { + summary.prod.push(key); + } + } + return summary; +} +function getOrCreateEl(id) { + let parentDiv = document.getElementById(id); + let created = false; + if (!parentDiv) { + parentDiv = document.createElement('div'); + parentDiv.setAttribute('id', id); + created = true; + } + return { created, element: parentDiv }; +} +let previouslyDismissed = false; +/** + * Updates Emulator Banner. Primarily used for Firebase Studio + * @param name + * @param isRunningEmulator + * @public + */ +function updateEmulatorBanner(name, isRunningEmulator) { + if (typeof window === 'undefined' || + typeof document === 'undefined' || + !isCloudWorkstation(window.location.host) || + emulatorStatus[name] === isRunningEmulator || + emulatorStatus[name] || // If already set to use emulator, can't go back to prod. + previouslyDismissed) { + return; + } + emulatorStatus[name] = isRunningEmulator; + function prefixedId(id) { + return `__firebase__banner__${id}`; + } + const bannerId = '__firebase__banner'; + const summary = getEmulatorSummary(); + const showError = summary.prod.length > 0; + function tearDown() { + const element = document.getElementById(bannerId); + if (element) { + element.remove(); + } + } + function setupBannerStyles(bannerEl) { + bannerEl.style.display = 'flex'; + bannerEl.style.background = '#7faaf0'; + bannerEl.style.position = 'fixed'; + bannerEl.style.bottom = '5px'; + bannerEl.style.left = '5px'; + bannerEl.style.padding = '.5em'; + bannerEl.style.borderRadius = '5px'; + bannerEl.style.alignItems = 'center'; + } + function setupIconStyles(prependIcon, iconId) { + prependIcon.setAttribute('width', '24'); + prependIcon.setAttribute('id', iconId); + prependIcon.setAttribute('height', '24'); + prependIcon.setAttribute('viewBox', '0 0 24 24'); + prependIcon.setAttribute('fill', 'none'); + prependIcon.style.marginLeft = '-6px'; + } + function setupCloseBtn() { + const closeBtn = document.createElement('span'); + closeBtn.style.cursor = 'pointer'; + closeBtn.style.marginLeft = '16px'; + closeBtn.style.fontSize = '24px'; + closeBtn.innerHTML = ' ×'; + closeBtn.onclick = () => { + previouslyDismissed = true; + tearDown(); + }; + return closeBtn; + } + function setupLinkStyles(learnMoreLink, learnMoreId) { + learnMoreLink.setAttribute('id', learnMoreId); + learnMoreLink.innerText = 'Learn more'; + learnMoreLink.href = + 'https://firebase.google.com/docs/studio/preview-apps#preview-backend'; + learnMoreLink.setAttribute('target', '__blank'); + learnMoreLink.style.paddingLeft = '5px'; + learnMoreLink.style.textDecoration = 'underline'; + } + function setupDom() { + const banner = getOrCreateEl(bannerId); + const firebaseTextId = prefixedId('text'); + const firebaseText = document.getElementById(firebaseTextId) || document.createElement('span'); + const learnMoreId = prefixedId('learnmore'); + const learnMoreLink = document.getElementById(learnMoreId) || + document.createElement('a'); + const prependIconId = prefixedId('preprendIcon'); + const prependIcon = document.getElementById(prependIconId) || + document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + if (banner.created) { + // update styles + const bannerEl = banner.element; + setupBannerStyles(bannerEl); + setupLinkStyles(learnMoreLink, learnMoreId); + const closeBtn = setupCloseBtn(); + setupIconStyles(prependIcon, prependIconId); + bannerEl.append(prependIcon, firebaseText, learnMoreLink, closeBtn); + document.body.appendChild(bannerEl); + } + if (showError) { + firebaseText.innerText = `Preview backend disconnected.`; + prependIcon.innerHTML = ` + + + + + + +`; + } + else { + prependIcon.innerHTML = ` + + + + + + +`; + firebaseText.innerText = 'Preview backend running in this workspace.'; + } + firebaseText.setAttribute('id', firebaseTextId); + } + if (document.readyState === 'loading') { + window.addEventListener('DOMContentLoaded', setupDom); + } + else { + setupDom(); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns navigator.userAgent string or '' if it's not defined. + * @return user agent string + */ +function getUA() { + if (typeof navigator !== 'undefined' && + typeof navigator['userAgent'] === 'string') { + return navigator['userAgent']; + } + else { + return ''; + } +} +/** + * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device. + * + * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap + * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally + * wait for a callback. + */ +function isMobileCordova() { + return (typeof window !== 'undefined' && + // @ts-ignore Setting up an broadly applicable index signature for Window + // just to deal with this case would probably be a bad idea. + !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) && + /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())); +} +/** + * Detect Node.js. + * + * @return true if Node.js environment is detected or specified. + */ +// Node detection logic from: https://github.com/iliakan/detect-node/ +function isNode() { + const forceEnvironment = getDefaults()?.forceEnvironment; + if (forceEnvironment === 'node') { + return true; + } + else if (forceEnvironment === 'browser') { + return false; + } + try { + return (Object.prototype.toString.call(global.process) === '[object process]'); + } + catch (e) { + return false; + } +} +/** + * Detect Browser Environment. + * Note: This will return true for certain test frameworks that are incompletely + * mimicking a browser, and should not lead to assuming all browser APIs are + * available. + */ +function isBrowser() { + return typeof window !== 'undefined' || isWebWorker(); +} +/** + * Detect Web Worker context. + */ +function isWebWorker() { + return (typeof WorkerGlobalScope !== 'undefined' && + typeof self !== 'undefined' && + self instanceof WorkerGlobalScope); +} +/** + * Detect Cloudflare Worker context. + */ +function isCloudflareWorker() { + return (typeof navigator !== 'undefined' && + navigator.userAgent === 'Cloudflare-Workers'); +} +function isBrowserExtension() { + const runtime = typeof chrome === 'object' + ? chrome.runtime + : typeof browser === 'object' + ? browser.runtime + : undefined; + return typeof runtime === 'object' && runtime.id !== undefined; +} +/** + * Detect React Native. + * + * @return true if ReactNative environment is detected. + */ +function isReactNative() { + return (typeof navigator === 'object' && navigator['product'] === 'ReactNative'); +} +/** Detects Electron apps. */ +function isElectron() { + return getUA().indexOf('Electron/') >= 0; +} +/** Detects Internet Explorer. */ +function isIE() { + const ua = getUA(); + return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0; +} +/** Detects Universal Windows Platform apps. */ +function isUWP() { + return getUA().indexOf('MSAppHost/') >= 0; +} +/** + * Detect whether the current SDK build is the Node version. + * + * @return true if it's the Node SDK build. + */ +function isNodeSdk() { + return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true; +} +/** Returns true if we are running in Safari. */ +function isSafari() { + return (!isNode() && + !!navigator.userAgent && + navigator.userAgent.includes('Safari') && + !navigator.userAgent.includes('Chrome')); +} +/** Returns true if we are running in Safari or WebKit */ +function isSafariOrWebkit() { + return (!isNode() && + !!navigator.userAgent && + (navigator.userAgent.includes('Safari') || + navigator.userAgent.includes('WebKit')) && + !navigator.userAgent.includes('Chrome')); +} +/** + * This method checks if indexedDB is supported by current browser/service worker context + * @return true if indexedDB is supported by current browser/service worker context + */ +function isIndexedDBAvailable() { + try { + return typeof indexedDB === 'object'; + } + catch (e) { + return false; + } +} +/** + * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject + * if errors occur during the database open operation. + * + * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox + * private browsing) + */ +function validateIndexedDBOpenable() { + return new Promise((resolve, reject) => { + try { + let preExist = true; + const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module'; + const request = self.indexedDB.open(DB_CHECK_NAME); + request.onsuccess = () => { + request.result.close(); + // delete database only when it doesn't pre-exist + if (!preExist) { + self.indexedDB.deleteDatabase(DB_CHECK_NAME); + } + resolve(true); + }; + request.onupgradeneeded = () => { + preExist = false; + }; + request.onerror = () => { + reject(request.error?.message || ''); + }; + } + catch (error) { + reject(error); + } + }); +} +/** + * + * This method checks whether cookie is enabled within current browser + * @return true if cookie is enabled within current browser + */ +function areCookiesEnabled() { + if (typeof navigator === 'undefined' || !navigator.cookieEnabled) { + return false; + } + return true; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview Standardized Firebase Error. + * + * Usage: + * + * // TypeScript string literals for type-safe codes + * type Err = + * 'unknown' | + * 'object-not-found' + * ; + * + * // Closure enum for type-safe error codes + * // at-enum {string} + * var Err = { + * UNKNOWN: 'unknown', + * OBJECT_NOT_FOUND: 'object-not-found', + * } + * + * let errors: Map = { + * 'generic-error': "Unknown error", + * 'file-not-found': "Could not find file: {$file}", + * }; + * + * // Type-safe function - must pass a valid error code as param. + * let error = new ErrorFactory('service', 'Service', errors); + * + * ... + * throw error.create(Err.GENERIC); + * ... + * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName}); + * ... + * // Service: Could not file file: foo.txt (service/file-not-found). + * + * catch (e) { + * assert(e.message === "Could not find file: foo.txt."); + * if ((e as FirebaseError)?.code === 'service/file-not-found') { + * console.log("Could not read file: " + e['file']); + * } + * } + */ +const ERROR_NAME = 'FirebaseError'; +// Based on code from: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types +class FirebaseError extends Error { + constructor( + /** The error code for this error. */ + code, message, + /** Custom data for this error. */ + customData) { + super(message); + this.code = code; + this.customData = customData; + /** The custom name for all FirebaseErrors. */ + this.name = ERROR_NAME; + // Fix For ES5 + // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work + // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget + // which we can now use since we no longer target ES5. + Object.setPrototypeOf(this, FirebaseError.prototype); + // Maintains proper stack trace for where our error was thrown. + // Only available on V8. + if (Error.captureStackTrace) { + Error.captureStackTrace(this, ErrorFactory.prototype.create); + } + } +} +class ErrorFactory { + constructor(service, serviceName, errors) { + this.service = service; + this.serviceName = serviceName; + this.errors = errors; + } + create(code, ...data) { + const customData = data[0] || {}; + const fullCode = `${this.service}/${code}`; + const template = this.errors[code]; + const message = template ? replaceTemplate(template, customData) : 'Error'; + // Service Name: Error message (service/code). + const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`; + const error = new FirebaseError(fullCode, fullMessage, customData); + return error; + } +} +function replaceTemplate(template, data) { + return template.replace(PATTERN, (_, key) => { + const value = data[key]; + return value != null ? String(value) : `<${key}?>`; + }); +} +const PATTERN = /\{\$([^}]+)}/g; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Evaluates a JSON string into a javascript object. + * + * @param {string} str A string containing JSON. + * @return {*} The javascript object representing the specified JSON. + */ +function jsonEval(str) { + return JSON.parse(str); +} +/** + * Returns JSON representing a javascript object. + * @param {*} data JavaScript object to be stringified. + * @return {string} The JSON contents of the object. + */ +function stringify(data) { + return JSON.stringify(data); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Decodes a Firebase auth. token into constituent parts. + * + * Notes: + * - May return with invalid / incomplete claims if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +const decode = function (token) { + let header = {}, claims = {}, data = {}, signature = ''; + try { + const parts = token.split('.'); + header = jsonEval(base64Decode(parts[0]) || ''); + claims = jsonEval(base64Decode(parts[1]) || ''); + signature = parts[2]; + data = claims['d'] || {}; + delete claims['d']; + } + catch (e) { } + return { + header, + claims, + data, + signature + }; +}; +/** + * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the + * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +const isValidTimestamp = function (token) { + const claims = decode(token).claims; + const now = Math.floor(new Date().getTime() / 1000); + let validSince = 0, validUntil = 0; + if (typeof claims === 'object') { + if (claims.hasOwnProperty('nbf')) { + validSince = claims['nbf']; + } + else if (claims.hasOwnProperty('iat')) { + validSince = claims['iat']; + } + if (claims.hasOwnProperty('exp')) { + validUntil = claims['exp']; + } + else { + // token will expire after 24h by default + validUntil = validSince + 86400; + } + } + return (!!now && + !!validSince && + !!validUntil && + now >= validSince && + now <= validUntil); +}; +/** + * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise. + * + * Notes: + * - May return null if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +const issuedAtTime = function (token) { + const claims = decode(token).claims; + if (typeof claims === 'object' && claims.hasOwnProperty('iat')) { + return claims['iat']; + } + return null; +}; +/** + * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +const isValidFormat = function (token) { + const decoded = decode(token), claims = decoded.claims; + return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat'); +}; +/** + * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +const isAdmin = function (token) { + const claims = decode(token).claims; + return typeof claims === 'object' && claims['admin'] === true; +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function contains(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +function safeGet(obj, key) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + return obj[key]; + } + else { + return undefined; + } +} +function isEmpty(obj) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + return false; + } + } + return true; +} +function map(obj, fn, contextObj) { + const res = {}; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + res[key] = fn.call(contextObj, obj[key], key, obj); + } + } + return res; +} +/** + * Deep equal two objects. Support Arrays and Objects. + */ +function deepEqual(a, b) { + if (a === b) { + return true; + } + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + for (const k of aKeys) { + if (!bKeys.includes(k)) { + return false; + } + const aProp = a[k]; + const bProp = b[k]; + if (isObject(aProp) && isObject(bProp)) { + if (!deepEqual(aProp, bProp)) { + return false; + } + } + else if (aProp !== bProp) { + return false; + } + } + for (const k of bKeys) { + if (!aKeys.includes(k)) { + return false; + } + } + return true; +} +function isObject(thing) { + return thing !== null && typeof thing === 'object'; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Rejects if the given promise doesn't resolve in timeInMS milliseconds. + * @internal + */ +function promiseWithTimeout(promise, timeInMS = 2000) { + const deferredPromise = new Deferred(); + setTimeout(() => deferredPromise.reject('timeout!'), timeInMS); + promise.then(deferredPromise.resolve, deferredPromise.reject); + return deferredPromise.promise; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a + * params object (e.g. {arg: 'val', arg2: 'val2'}) + * Note: You must prepend it with ? when adding it to a URL. + */ +function querystring(querystringParams) { + const params = []; + for (const [key, value] of Object.entries(querystringParams)) { + if (Array.isArray(value)) { + value.forEach(arrayVal => { + params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal)); + }); + } + else { + params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); + } + } + return params.length ? '&' + params.join('&') : ''; +} +/** + * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object + * (e.g. {arg: 'val', arg2: 'val2'}) + */ +function querystringDecode(querystring) { + const obj = {}; + const tokens = querystring.replace(/^\?/, '').split('&'); + tokens.forEach(token => { + if (token) { + const [key, value] = token.split('='); + obj[decodeURIComponent(key)] = decodeURIComponent(value); + } + }); + return obj; +} +/** + * Extract the query string part of a URL, including the leading question mark (if present). + */ +function extractQuerystring(url) { + const queryStart = url.indexOf('?'); + if (!queryStart) { + return ''; + } + const fragmentStart = url.indexOf('#', queryStart); + return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview SHA-1 cryptographic hash. + * Variable names follow the notation in FIPS PUB 180-3: + * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf. + * + * Usage: + * var sha1 = new sha1(); + * sha1.update(bytes); + * var hash = sha1.digest(); + * + * Performance: + * Chrome 23: ~400 Mbit/s + * Firefox 16: ~250 Mbit/s + * + */ +/** + * SHA-1 cryptographic hash constructor. + * + * The properties declared here are discussed in the above algorithm document. + * @constructor + * @final + * @struct + */ +class Sha1 { + constructor() { + /** + * Holds the previous values of accumulated variables a-e in the compress_ + * function. + * @private + */ + this.chain_ = []; + /** + * A buffer holding the partially computed hash result. + * @private + */ + this.buf_ = []; + /** + * An array of 80 bytes, each a part of the message to be hashed. Referred to + * as the message schedule in the docs. + * @private + */ + this.W_ = []; + /** + * Contains data needed to pad messages less than 64 bytes. + * @private + */ + this.pad_ = []; + /** + * @private {number} + */ + this.inbuf_ = 0; + /** + * @private {number} + */ + this.total_ = 0; + this.blockSize = 512 / 8; + this.pad_[0] = 128; + for (let i = 1; i < this.blockSize; ++i) { + this.pad_[i] = 0; + } + this.reset(); + } + reset() { + this.chain_[0] = 0x67452301; + this.chain_[1] = 0xefcdab89; + this.chain_[2] = 0x98badcfe; + this.chain_[3] = 0x10325476; + this.chain_[4] = 0xc3d2e1f0; + this.inbuf_ = 0; + this.total_ = 0; + } + /** + * Internal compress helper function. + * @param buf Block to compress. + * @param offset Offset of the block in the buffer. + * @private + */ + compress_(buf, offset) { + if (!offset) { + offset = 0; + } + const W = this.W_; + // get 16 big endian words + if (typeof buf === 'string') { + for (let i = 0; i < 16; i++) { + // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS + // have a bug that turns the post-increment ++ operator into pre-increment + // during JIT compilation. We have code that depends heavily on SHA-1 for + // correctness and which is affected by this bug, so I've removed all uses + // of post-increment ++ in which the result value is used. We can revert + // this change once the Safari bug + // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and + // most clients have been updated. + W[i] = + (buf.charCodeAt(offset) << 24) | + (buf.charCodeAt(offset + 1) << 16) | + (buf.charCodeAt(offset + 2) << 8) | + buf.charCodeAt(offset + 3); + offset += 4; + } + } + else { + for (let i = 0; i < 16; i++) { + W[i] = + (buf[offset] << 24) | + (buf[offset + 1] << 16) | + (buf[offset + 2] << 8) | + buf[offset + 3]; + offset += 4; + } + } + // expand to 80 words + for (let i = 16; i < 80; i++) { + const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff; + } + let a = this.chain_[0]; + let b = this.chain_[1]; + let c = this.chain_[2]; + let d = this.chain_[3]; + let e = this.chain_[4]; + let f, k; + // TODO(user): Try to unroll this loop to speed up the computation. + for (let i = 0; i < 80; i++) { + if (i < 40) { + if (i < 20) { + f = d ^ (b & (c ^ d)); + k = 0x5a827999; + } + else { + f = b ^ c ^ d; + k = 0x6ed9eba1; + } + } + else { + if (i < 60) { + f = (b & c) | (d & (b | c)); + k = 0x8f1bbcdc; + } + else { + f = b ^ c ^ d; + k = 0xca62c1d6; + } + } + const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff; + e = d; + d = c; + c = ((b << 30) | (b >>> 2)) & 0xffffffff; + b = a; + a = t; + } + this.chain_[0] = (this.chain_[0] + a) & 0xffffffff; + this.chain_[1] = (this.chain_[1] + b) & 0xffffffff; + this.chain_[2] = (this.chain_[2] + c) & 0xffffffff; + this.chain_[3] = (this.chain_[3] + d) & 0xffffffff; + this.chain_[4] = (this.chain_[4] + e) & 0xffffffff; + } + update(bytes, length) { + // TODO(johnlenz): tighten the function signature and remove this check + if (bytes == null) { + return; + } + if (length === undefined) { + length = bytes.length; + } + const lengthMinusBlock = length - this.blockSize; + let n = 0; + // Using local instead of member variables gives ~5% speedup on Firefox 16. + const buf = this.buf_; + let inbuf = this.inbuf_; + // The outer while loop should execute at most twice. + while (n < length) { + // When we have no data in the block to top up, we can directly process the + // input buffer (assuming it contains sufficient data). This gives ~25% + // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that + // the data is provided in large chunks (or in multiples of 64 bytes). + if (inbuf === 0) { + while (n <= lengthMinusBlock) { + this.compress_(bytes, n); + n += this.blockSize; + } + } + if (typeof bytes === 'string') { + while (n < length) { + buf[inbuf] = bytes.charCodeAt(n); + ++inbuf; + ++n; + if (inbuf === this.blockSize) { + this.compress_(buf); + inbuf = 0; + // Jump to the outer loop so we use the full-block optimization. + break; + } + } + } + else { + while (n < length) { + buf[inbuf] = bytes[n]; + ++inbuf; + ++n; + if (inbuf === this.blockSize) { + this.compress_(buf); + inbuf = 0; + // Jump to the outer loop so we use the full-block optimization. + break; + } + } + } + } + this.inbuf_ = inbuf; + this.total_ += length; + } + /** @override */ + digest() { + const digest = []; + let totalBits = this.total_ * 8; + // Add pad 0x80 0x00*. + if (this.inbuf_ < 56) { + this.update(this.pad_, 56 - this.inbuf_); + } + else { + this.update(this.pad_, this.blockSize - (this.inbuf_ - 56)); + } + // Add # bits. + for (let i = this.blockSize - 1; i >= 56; i--) { + this.buf_[i] = totalBits & 255; + totalBits /= 256; // Don't use bit-shifting here! + } + this.compress_(this.buf_); + let n = 0; + for (let i = 0; i < 5; i++) { + for (let j = 24; j >= 0; j -= 8) { + digest[n] = (this.chain_[i] >> j) & 255; + ++n; + } + } + return digest; + } +} + +/** + * Helper to make a Subscribe function (just like Promise helps make a + * Thenable). + * + * @param executor Function which can make calls to a single Observer + * as a proxy. + * @param onNoObservers Callback when count of Observers goes to zero. + */ +function createSubscribe(executor, onNoObservers) { + const proxy = new ObserverProxy(executor, onNoObservers); + return proxy.subscribe.bind(proxy); +} +/** + * Implement fan-out for any number of Observers attached via a subscribe + * function. + */ +class ObserverProxy { + /** + * @param executor Function which can make calls to a single Observer + * as a proxy. + * @param onNoObservers Callback when count of Observers goes to zero. + */ + constructor(executor, onNoObservers) { + this.observers = []; + this.unsubscribes = []; + this.observerCount = 0; + // Micro-task scheduling by calling task.then(). + this.task = Promise.resolve(); + this.finalized = false; + this.onNoObservers = onNoObservers; + // Call the executor asynchronously so subscribers that are called + // synchronously after the creation of the subscribe function + // can still receive the very first value generated in the executor. + this.task + .then(() => { + executor(this); + }) + .catch(e => { + this.error(e); + }); + } + next(value) { + this.forEachObserver((observer) => { + observer.next(value); + }); + } + error(error) { + this.forEachObserver((observer) => { + observer.error(error); + }); + this.close(error); + } + complete() { + this.forEachObserver((observer) => { + observer.complete(); + }); + this.close(); + } + /** + * Subscribe function that can be used to add an Observer to the fan-out list. + * + * - We require that no event is sent to a subscriber synchronously to their + * call to subscribe(). + */ + subscribe(nextOrObserver, error, complete) { + let observer; + if (nextOrObserver === undefined && + error === undefined && + complete === undefined) { + throw new Error('Missing Observer.'); + } + // Assemble an Observer object when passed as callback functions. + if (implementsAnyMethods(nextOrObserver, [ + 'next', + 'error', + 'complete' + ])) { + observer = nextOrObserver; + } + else { + observer = { + next: nextOrObserver, + error, + complete + }; + } + if (observer.next === undefined) { + observer.next = noop; + } + if (observer.error === undefined) { + observer.error = noop; + } + if (observer.complete === undefined) { + observer.complete = noop; + } + const unsub = this.unsubscribeOne.bind(this, this.observers.length); + // Attempt to subscribe to a terminated Observable - we + // just respond to the Observer with the final error or complete + // event. + if (this.finalized) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.task.then(() => { + try { + if (this.finalError) { + observer.error(this.finalError); + } + else { + observer.complete(); + } + } + catch (e) { + // nothing + } + return; + }); + } + this.observers.push(observer); + return unsub; + } + // Unsubscribe is synchronous - we guarantee that no events are sent to + // any unsubscribed Observer. + unsubscribeOne(i) { + if (this.observers === undefined || this.observers[i] === undefined) { + return; + } + delete this.observers[i]; + this.observerCount -= 1; + if (this.observerCount === 0 && this.onNoObservers !== undefined) { + this.onNoObservers(this); + } + } + forEachObserver(fn) { + if (this.finalized) { + // Already closed by previous event....just eat the additional values. + return; + } + // Since sendOne calls asynchronously - there is no chance that + // this.observers will become undefined. + for (let i = 0; i < this.observers.length; i++) { + this.sendOne(i, fn); + } + } + // Call the Observer via one of it's callback function. We are careful to + // confirm that the observe has not been unsubscribed since this asynchronous + // function had been queued. + sendOne(i, fn) { + // Execute the callback asynchronously + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.task.then(() => { + if (this.observers !== undefined && this.observers[i] !== undefined) { + try { + fn(this.observers[i]); + } + catch (e) { + // Ignore exceptions raised in Observers or missing methods of an + // Observer. + // Log error to console. b/31404806 + if (typeof console !== 'undefined' && console.error) { + console.error(e); + } + } + } + }); + } + close(err) { + if (this.finalized) { + return; + } + this.finalized = true; + if (err !== undefined) { + this.finalError = err; + } + // Proxy is no longer needed - garbage collect references + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.task.then(() => { + this.observers = undefined; + this.onNoObservers = undefined; + }); + } +} +/** Turn synchronous function into one called asynchronously. */ +// eslint-disable-next-line @typescript-eslint/ban-types +function async(fn, onError) { + return (...args) => { + Promise.resolve(true) + .then(() => { + fn(...args); + }) + .catch((error) => { + if (onError) { + onError(error); + } + }); + }; +} +/** + * Return true if the object passed in implements any of the named methods. + */ +function implementsAnyMethods(obj, methods) { + if (typeof obj !== 'object' || obj === null) { + return false; + } + for (const method of methods) { + if (method in obj && typeof obj[method] === 'function') { + return true; + } + } + return false; +} +function noop() { + // do nothing +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Check to make sure the appropriate number of arguments are provided for a public function. + * Throws an error if it fails. + * + * @param fnName The function name + * @param minCount The minimum number of arguments to allow for the function call + * @param maxCount The maximum number of argument to allow for the function call + * @param argCount The actual number of arguments provided. + */ +const validateArgCount = function (fnName, minCount, maxCount, argCount) { + let argError; + if (argCount < minCount) { + argError = 'at least ' + minCount; + } + else if (argCount > maxCount) { + argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount; + } + if (argError) { + const error = fnName + + ' failed: Was called with ' + + argCount + + (argCount === 1 ? ' argument.' : ' arguments.') + + ' Expects ' + + argError + + '.'; + throw new Error(error); + } +}; +/** + * Generates a string to prefix an error message about failed argument validation + * + * @param fnName The function name + * @param argName The name of the argument + * @return The prefix to add to the error thrown for validation. + */ +function errorPrefix(fnName, argName) { + return `${fnName} failed: ${argName} argument `; +} +/** + * @param fnName + * @param argumentNumber + * @param namespace + * @param optional + */ +function validateNamespace(fnName, namespace, optional) { + if (optional && !namespace) { + return; + } + if (typeof namespace !== 'string') { + //TODO: I should do more validation here. We only allow certain chars in namespaces. + throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.'); + } +} +function validateCallback(fnName, argumentName, +// eslint-disable-next-line @typescript-eslint/ban-types +callback, optional) { + if (optional && !callback) { + return; + } + if (typeof callback !== 'function') { + throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.'); + } +} +function validateContextObject(fnName, argumentName, context, optional) { + if (optional && !context) { + return; + } + if (typeof context !== 'object' || context === null) { + throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they +// automatically replaced '\r\n' with '\n', and they didn't handle surrogate pairs, +// so it's been modified. +// Note that not all Unicode characters appear as single characters in JavaScript strings. +// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters +// use 2 characters in JavaScript. All 4-byte UTF-8 characters begin with a first +// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate +// pair). +// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3 +/** + * @param {string} str + * @return {Array} + */ +const stringToByteArray = function (str) { + const out = []; + let p = 0; + for (let i = 0; i < str.length; i++) { + let c = str.charCodeAt(i); + // Is this the lead surrogate in a surrogate pair? + if (c >= 0xd800 && c <= 0xdbff) { + const high = c - 0xd800; // the high 10 bits. + i++; + assert(i < str.length, 'Surrogate pair missing trail surrogate.'); + const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits. + c = 0x10000 + (high << 10) + low; + } + if (c < 128) { + out[p++] = c; + } + else if (c < 2048) { + out[p++] = (c >> 6) | 192; + out[p++] = (c & 63) | 128; + } + else if (c < 65536) { + out[p++] = (c >> 12) | 224; + out[p++] = ((c >> 6) & 63) | 128; + out[p++] = (c & 63) | 128; + } + else { + out[p++] = (c >> 18) | 240; + out[p++] = ((c >> 12) & 63) | 128; + out[p++] = ((c >> 6) & 63) | 128; + out[p++] = (c & 63) | 128; + } + } + return out; +}; +/** + * Calculate length without actually converting; useful for doing cheaper validation. + * @param {string} str + * @return {number} + */ +const stringLength = function (str) { + let p = 0; + for (let i = 0; i < str.length; i++) { + const c = str.charCodeAt(i); + if (c < 128) { + p++; + } + else if (c < 2048) { + p += 2; + } + else if (c >= 0xd800 && c <= 0xdbff) { + // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent. + p += 4; + i++; // skip trail surrogate. + } + else { + p += 3; + } + } + return p; +}; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The amount of milliseconds to exponentially increase. + */ +const DEFAULT_INTERVAL_MILLIS = 1000; +/** + * The factor to backoff by. + * Should be a number greater than 1. + */ +const DEFAULT_BACKOFF_FACTOR = 2; +/** + * The maximum milliseconds to increase to. + * + *

Visible for testing + */ +const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android. +/** + * The percentage of backoff time to randomize by. + * See + * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic + * for context. + * + *

Visible for testing + */ +const RANDOM_FACTOR = 0.5; +/** + * Based on the backoff method from + * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js. + * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around. + */ +function calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) { + // Calculates an exponentially increasing value. + // Deviation: calculates value from count and a constant interval, so we only need to save value + // and count to restore state. + const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount); + // A random "fuzz" to avoid waves of retries. + // Deviation: randomFactor is required. + const randomWait = Math.round( + // A fraction of the backoff value to add/subtract. + // Deviation: changes multiplication order to improve readability. + RANDOM_FACTOR * + currBaseValue * + // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines + // if we add or subtract. + (Math.random() - 0.5) * + 2); + // Limits backoff to max to avoid effectively permanent backoff. + return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provide English ordinal letters after a number + */ +function ordinal(i) { + if (!Number.isFinite(i)) { + return `${i}`; + } + return i + indicator(i); +} +function indicator(i) { + i = Math.abs(i); + const cent = i % 100; + if (cent >= 10 && cent <= 20) { + return 'th'; + } + const dec = i % 10; + if (dec === 1) { + return 'st'; + } + if (dec === 2) { + return 'nd'; + } + if (dec === 3) { + return 'rd'; + } + return 'th'; +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function getModularInstance(service) { + if (service && service._delegate) { + return service._delegate; + } + else { + return service; + } +} + +export { CONSTANTS, DecodeBase64StringError, Deferred, ErrorFactory, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getDefaultAppConfig, getDefaultEmulatorHost, getDefaultEmulatorHostnameAndPort, getDefaults, getExperimentalSetting, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isCloudWorkstation, isCloudflareWorker, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isSafariOrWebkit, isUWP, isValidFormat, isValidTimestamp, isWebWorker, issuedAtTime, jsonEval, map, ordinal, pingServer, promiseWithTimeout, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, updateEmulatorBanner, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace }; +//# sourceMappingURL=index.esm.js.map diff --git a/node_modules/@firebase/util/dist/index.esm.js.map b/node_modules/@firebase/util/dist/index.esm.js.map new file mode 100644 index 0000000..dadc2f5 --- /dev/null +++ b/node_modules/@firebase/util/dist/index.esm.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.esm.js","sources":["../src/constants.ts","../src/assert.ts","../src/crypt.ts","../src/deepCopy.ts","../src/global.ts","../src/defaults.ts","../src/deferred.ts","../src/url.ts","../src/emulator.ts","../src/environment.ts","../src/errors.ts","../src/json.ts","../src/jwt.ts","../src/obj.ts","../src/promise.ts","../src/query.ts","../src/sha1.ts","../src/subscribe.ts","../src/validation.ts","../src/utf8.ts","../src/exponential_backoff.ts","../src/formatters.ts","../src/compat.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\n */\n\nexport const CONSTANTS = {\n /**\n * @define {boolean} Whether this is the client Node.js SDK.\n */\n NODE_CLIENT: false,\n /**\n * @define {boolean} Whether this is the Admin Node.js SDK.\n */\n NODE_ADMIN: false,\n\n /**\n * Firebase SDK Version\n */\n SDK_VERSION: '${JSCORE_VERSION}'\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSTANTS } from './constants';\n\n/**\n * Throws an error if the provided assertion is falsy\n */\nexport const assert = function (assertion: unknown, message: string): void {\n if (!assertion) {\n throw assertionError(message);\n }\n};\n\n/**\n * Returns an Error object suitable for throwing.\n */\nexport const assertionError = function (message: string): Error {\n return new Error(\n 'Firebase Database (' +\n CONSTANTS.SDK_VERSION +\n ') INTERNAL ASSERT FAILED: ' +\n message\n );\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst stringToByteArray = function (str: string): number[] {\n // TODO(user): Use native implementations if/when available\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (\n (c & 0xfc00) === 0xd800 &&\n i + 1 < str.length &&\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00\n ) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param bytes Array of numbers representing characters.\n * @return Stringification of the array.\n */\nconst byteArrayToString = function (bytes: number[]): string {\n // TODO(user): Use native implementations if/when available\n const out: string[] = [];\n let pos = 0,\n c = 0;\n while (pos < bytes.length) {\n const c1 = bytes[pos++];\n if (c1 < 128) {\n out[c++] = String.fromCharCode(c1);\n } else if (c1 > 191 && c1 < 224) {\n const c2 = bytes[pos++];\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n } else if (c1 > 239 && c1 < 365) {\n // Surrogate Pair\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n const c4 = bytes[pos++];\n const u =\n (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n 0x10000;\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n } else {\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n out[c++] = String.fromCharCode(\n ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)\n );\n }\n }\n return out.join('');\n};\n\ninterface Base64 {\n byteToCharMap_: { [key: number]: string } | null;\n charToByteMap_: { [key: string]: number } | null;\n byteToCharMapWebSafe_: { [key: number]: string } | null;\n charToByteMapWebSafe_: { [key: string]: number } | null;\n ENCODED_VALS_BASE: string;\n readonly ENCODED_VALS: string;\n readonly ENCODED_VALS_WEBSAFE: string;\n HAS_NATIVE_SUPPORT: boolean;\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string;\n encodeString(input: string, webSafe?: boolean): string;\n decodeString(input: string, webSafe: boolean): string;\n decodeStringToByteArray(input: string, webSafe: boolean): number[];\n init_(): void;\n}\n\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\n// Static lookup maps, lazily populated by init_()\n// TODO(dlarocque): Define this as a class, since we no longer target ES5.\nexport const base64: Base64 = {\n /**\n * Maps bytes to characters.\n */\n byteToCharMap_: null,\n\n /**\n * Maps characters to bytes.\n */\n charToByteMap_: null,\n\n /**\n * Maps bytes to websafe characters.\n * @private\n */\n byteToCharMapWebSafe_: null,\n\n /**\n * Maps websafe characters to bytes.\n * @private\n */\n charToByteMapWebSafe_: null,\n\n /**\n * Our default alphabet, shared between\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n */\n ENCODED_VALS_BASE:\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n\n /**\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n */\n get ENCODED_VALS() {\n return this.ENCODED_VALS_BASE + '+/=';\n },\n\n /**\n * Our websafe alphabet.\n */\n get ENCODED_VALS_WEBSAFE() {\n return this.ENCODED_VALS_BASE + '-_.';\n },\n\n /**\n * Whether this browser supports the atob and btoa functions. This extension\n * started at Mozilla but is now implemented by many browsers. We use the\n * ASSUME_* variables to avoid pulling in the full useragent detection library\n * but still allowing the standard per-browser compilations.\n *\n */\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\n\n /**\n * Base64-encode an array of bytes.\n *\n * @param input An array of bytes (numbers with\n * value in [0, 255]) to encode.\n * @param webSafe Boolean indicating we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string {\n if (!Array.isArray(input)) {\n throw Error('encodeByteArray takes an array as a parameter');\n }\n\n this.init_();\n\n const byteToCharMap = webSafe\n ? this.byteToCharMapWebSafe_!\n : this.byteToCharMap_!;\n\n const output = [];\n\n for (let i = 0; i < input.length; i += 3) {\n const byte1 = input[i];\n const haveByte2 = i + 1 < input.length;\n const byte2 = haveByte2 ? input[i + 1] : 0;\n const haveByte3 = i + 2 < input.length;\n const byte3 = haveByte3 ? input[i + 2] : 0;\n\n const outByte1 = byte1 >> 2;\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n let outByte4 = byte3 & 0x3f;\n\n if (!haveByte3) {\n outByte4 = 64;\n\n if (!haveByte2) {\n outByte3 = 64;\n }\n }\n\n output.push(\n byteToCharMap[outByte1],\n byteToCharMap[outByte2],\n byteToCharMap[outByte3],\n byteToCharMap[outByte4]\n );\n }\n\n return output.join('');\n },\n\n /**\n * Base64-encode a string.\n *\n * @param input A string to encode.\n * @param webSafe If true, we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeString(input: string, webSafe?: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return btoa(input);\n }\n return this.encodeByteArray(stringToByteArray(input), webSafe);\n },\n\n /**\n * Base64-decode a string.\n *\n * @param input to decode.\n * @param webSafe True if we should use the\n * alternative alphabet.\n * @return string representing the decoded value.\n */\n decodeString(input: string, webSafe: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return atob(input);\n }\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\n },\n\n /**\n * Base64-decode a string.\n *\n * In base-64 decoding, groups of four characters are converted into three\n * bytes. If the encoder did not apply padding, the input length may not\n * be a multiple of 4.\n *\n * In this case, the last group will have fewer than 4 characters, and\n * padding will be inferred. If the group has one or two characters, it decodes\n * to one byte. If the group has three characters, it decodes to two bytes.\n *\n * @param input Input to decode.\n * @param webSafe True if we should use the web-safe alphabet.\n * @return bytes representing the decoded value.\n */\n decodeStringToByteArray(input: string, webSafe: boolean): number[] {\n this.init_();\n\n const charToByteMap = webSafe\n ? this.charToByteMapWebSafe_!\n : this.charToByteMap_!;\n\n const output: number[] = [];\n\n for (let i = 0; i < input.length; ) {\n const byte1 = charToByteMap[input.charAt(i++)];\n\n const haveByte2 = i < input.length;\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n ++i;\n\n const haveByte3 = i < input.length;\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n const haveByte4 = i < input.length;\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n throw new DecodeBase64StringError();\n }\n\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\n output.push(outByte1);\n\n if (byte3 !== 64) {\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n output.push(outByte2);\n\n if (byte4 !== 64) {\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n output.push(outByte3);\n }\n }\n }\n\n return output;\n },\n\n /**\n * Lazy static initialization function. Called before\n * accessing any of the static map variables.\n * @private\n */\n init_() {\n if (!this.byteToCharMap_) {\n this.byteToCharMap_ = {};\n this.charToByteMap_ = {};\n this.byteToCharMapWebSafe_ = {};\n this.charToByteMapWebSafe_ = {};\n\n // We want quick mappings back and forth, so we precompute two maps.\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n\n // Be forgiving when decoding and correctly decode both encodings.\n if (i >= this.ENCODED_VALS_BASE.length) {\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n }\n }\n }\n }\n};\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class DecodeBase64StringError extends Error {\n readonly name = 'DecodeBase64StringError';\n}\n\n/**\n * URL-safe base64 encoding\n */\nexport const base64Encode = function (str: string): string {\n const utf8Bytes = stringToByteArray(str);\n return base64.encodeByteArray(utf8Bytes, true);\n};\n\n/**\n * URL-safe base64 encoding (without \".\" padding in the end).\n * e.g. Used in JSON Web Token (JWT) parts.\n */\nexport const base64urlEncodeWithoutPadding = function (str: string): string {\n // Use base64url encoding and remove padding in the end (dot characters).\n return base64Encode(str).replace(/\\./g, '');\n};\n\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param str To be decoded\n * @return Decoded result, if possible\n */\nexport const base64Decode = function (str: string): string | null {\n try {\n return base64.decodeString(str, true);\n } catch (e) {\n console.error('base64Decode failed: ', e);\n }\n return null;\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Do a deep-copy of basic JavaScript Objects or Arrays.\n */\nexport function deepCopy(value: T): T {\n return deepExtend(undefined, value) as T;\n}\n\n/**\n * Copy properties from source to target (recursively allows extension\n * of Objects and Arrays). Scalar values in the target are over-written.\n * If target is undefined, an object of the appropriate type will be created\n * (and returned).\n *\n * We recursively copy all child properties of plain Objects in the source- so\n * that namespace- like dictionaries are merged.\n *\n * Note that the target can be a function, in which case the properties in\n * the source Object are copied onto it as static properties of the Function.\n *\n * Note: we don't merge __proto__ to prevent prototype pollution\n */\nexport function deepExtend(target: unknown, source: unknown): unknown {\n if (!(source instanceof Object)) {\n return source;\n }\n\n switch (source.constructor) {\n case Date:\n // Treat Dates like scalars; if the target date object had any child\n // properties - they will be lost!\n const dateValue = source as Date;\n return new Date(dateValue.getTime());\n\n case Object:\n if (target === undefined) {\n target = {};\n }\n break;\n case Array:\n // Always copy the array source and overwrite the target.\n target = [];\n break;\n\n default:\n // Not a plain Object - treat it as a scalar.\n return source;\n }\n\n for (const prop in source) {\n // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202\n if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {\n continue;\n }\n (target as Record)[prop] = deepExtend(\n (target as Record)[prop],\n (source as Record)[prop]\n );\n }\n\n return target;\n}\n\nfunction isValidKey(key: string): boolean {\n return key !== '__proto__';\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Polyfill for `globalThis` object.\n * @returns the `globalThis` object for the given environment.\n * @public\n */\nexport function getGlobal(): typeof globalThis {\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('Unable to locate global object.');\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Decode } from './crypt';\nimport { getGlobal } from './global';\nimport { getDefaultsFromPostinstall } from './postinstall';\n\n/**\n * Keys for experimental properties on the `FirebaseDefaults` object.\n * @public\n */\nexport type ExperimentalKey = 'authTokenSyncURL' | 'authIdTokenMaxAge';\n\n/**\n * An object that can be injected into the environment as __FIREBASE_DEFAULTS__,\n * either as a property of globalThis, a shell environment variable, or a\n * cookie.\n *\n * This object can be used to automatically configure and initialize\n * a Firebase app as well as any emulators.\n *\n * @public\n */\nexport interface FirebaseDefaults {\n config?: Record;\n emulatorHosts?: Record;\n _authTokenSyncURL?: string;\n _authIdTokenMaxAge?: number;\n /**\n * Override Firebase's runtime environment detection and\n * force the SDK to act as if it were in the specified environment.\n */\n forceEnvironment?: 'browser' | 'node';\n [key: string]: unknown;\n}\n\ndeclare global {\n // Need `var` for this to work.\n // eslint-disable-next-line no-var\n var __FIREBASE_DEFAULTS__: FirebaseDefaults | undefined;\n}\n\nconst getDefaultsFromGlobal = (): FirebaseDefaults | undefined =>\n getGlobal().__FIREBASE_DEFAULTS__;\n\n/**\n * Attempt to read defaults from a JSON string provided to\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\n * The dots are in parens because certain compilers (Vite?) cannot\n * handle seeing that variable in comments.\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\n */\nconst getDefaultsFromEnvVariable = (): FirebaseDefaults | undefined => {\n if (typeof process === 'undefined' || typeof process.env === 'undefined') {\n return;\n }\n const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\n if (defaultsJsonString) {\n return JSON.parse(defaultsJsonString);\n }\n};\n\nconst getDefaultsFromCookie = (): FirebaseDefaults | undefined => {\n if (typeof document === 'undefined') {\n return;\n }\n let match;\n try {\n match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\n } catch (e) {\n // Some environments such as Angular Universal SSR have a\n // `document` object but error on accessing `document.cookie`.\n return;\n }\n const decoded = match && base64Decode(match[1]);\n return decoded && JSON.parse(decoded);\n};\n\n/**\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\n * (1) if such an object exists as a property of `globalThis`\n * (2) if such an object was provided on a shell environment variable\n * (3) if such an object exists in a cookie\n * @public\n */\nexport const getDefaults = (): FirebaseDefaults | undefined => {\n try {\n return (\n getDefaultsFromPostinstall() ||\n getDefaultsFromGlobal() ||\n getDefaultsFromEnvVariable() ||\n getDefaultsFromCookie()\n );\n } catch (e) {\n /**\n * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\n * to any environment case we have not accounted for. Log to\n * info instead of swallowing so we can find these unknown cases\n * and add paths for them if needed.\n */\n console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\n return;\n }\n};\n\n/**\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\n * @public\n */\nexport const getDefaultEmulatorHost = (\n productName: string\n): string | undefined => getDefaults()?.emulatorHosts?.[productName];\n\n/**\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\n * @public\n */\nexport const getDefaultEmulatorHostnameAndPort = (\n productName: string\n): [hostname: string, port: number] | undefined => {\n const host = getDefaultEmulatorHost(productName);\n if (!host) {\n return undefined;\n }\n const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\n if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\n throw new Error(`Invalid host ${host} with no separate hostname and port!`);\n }\n // eslint-disable-next-line no-restricted-globals\n const port = parseInt(host.substring(separatorIndex + 1), 10);\n if (host[0] === '[') {\n // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\n return [host.substring(1, separatorIndex - 1), port];\n } else {\n return [host.substring(0, separatorIndex), port];\n }\n};\n\n/**\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\n * @public\n */\nexport const getDefaultAppConfig = (): Record | undefined =>\n getDefaults()?.config;\n\n/**\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\n * prefixed by \"_\")\n * @public\n */\nexport const getExperimentalSetting = (\n name: T\n): FirebaseDefaults[`_${T}`] =>\n getDefaults()?.[`_${name}`] as FirebaseDefaults[`_${T}`];\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred {\n promise: Promise;\n reject: (value?: unknown) => void = () => {};\n resolve: (value?: unknown) => void = () => {};\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve as (value?: unknown) => void;\n this.reject = reject as (value?: unknown) => void;\n });\n }\n\n /**\n * Our API internals are not promisified and cannot because our callback APIs have subtle expectations around\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\n */\n wrapCallback(\n callback?: (error?: unknown, value?: unknown) => void\n ): (error: unknown, value?: unknown) => void {\n return (error, value?) => {\n if (error) {\n this.reject(error);\n } else {\n this.resolve(value);\n }\n if (typeof callback === 'function') {\n // Attaching noop handler just in case developer wasn't expecting\n // promises\n this.promise.catch(() => {});\n\n // Some of our callbacks don't expect a value and our own tests\n // assert that the parameter length is 1\n if (callback.length === 1) {\n callback(error);\n } else {\n callback(error, value);\n }\n }\n };\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Checks whether host is a cloud workstation or not.\n * @public\n */\nexport function isCloudWorkstation(url: string): boolean {\n // `isCloudWorkstation` is called without protocol in certain connect*Emulator functions\n // In HTTP request builders, it's called with the protocol.\n // If called with protocol prefix, it's a valid URL, so we extract the hostname\n // If called without, we assume the string is the hostname.\n try {\n const host =\n url.startsWith('http://') || url.startsWith('https://')\n ? new URL(url).hostname\n : url;\n return host.endsWith('.cloudworkstations.dev');\n } catch {\n return false;\n }\n}\n\n/**\n * Makes a fetch request to the given server.\n * Mostly used for forwarding cookies in Firebase Studio.\n * @public\n */\nexport async function pingServer(endpoint: string): Promise {\n const result = await fetch(endpoint, {\n credentials: 'include'\n });\n return result.ok;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64urlEncodeWithoutPadding } from './crypt';\nimport { isCloudWorkstation } from './url';\n\n// Firebase Auth tokens contain snake_case claims following the JWT standard / convention.\n/* eslint-disable camelcase */\n\nexport type FirebaseSignInProvider =\n | 'custom'\n | 'email'\n | 'password'\n | 'phone'\n | 'anonymous'\n | 'google.com'\n | 'facebook.com'\n | 'github.com'\n | 'twitter.com'\n | 'microsoft.com'\n | 'apple.com';\n\ninterface FirebaseIdToken {\n // Always set to https://securetoken.google.com/PROJECT_ID\n iss: string;\n\n // Always set to PROJECT_ID\n aud: string;\n\n // The user's unique ID\n sub: string;\n\n // The token issue time, in seconds since epoch\n iat: number;\n\n // The token expiry time, normally 'iat' + 3600\n exp: number;\n\n // The user's unique ID. Must be equal to 'sub'\n user_id: string;\n\n // The time the user authenticated, normally 'iat'\n auth_time: number;\n\n // The sign in provider, only set when the provider is 'anonymous'\n provider_id?: 'anonymous';\n\n // The user's primary email\n email?: string;\n\n // The user's email verification status\n email_verified?: boolean;\n\n // The user's primary phone number\n phone_number?: string;\n\n // The user's display name\n name?: string;\n\n // The user's profile photo URL\n picture?: string;\n\n // Information on all identities linked to this user\n firebase: {\n // The primary sign-in provider\n sign_in_provider: FirebaseSignInProvider;\n\n // A map of providers to the user's list of unique identifiers from\n // each provider\n identities?: { [provider in FirebaseSignInProvider]?: string[] };\n };\n\n // Custom claims set by the developer\n [claim: string]: unknown;\n\n uid?: never; // Try to catch a common mistake of \"uid\" (should be \"sub\" instead).\n}\n\nexport type EmulatorMockTokenOptions = ({ user_id: string } | { sub: string }) &\n Partial;\n\nexport function createMockUserToken(\n token: EmulatorMockTokenOptions,\n projectId?: string\n): string {\n if (token.uid) {\n throw new Error(\n 'The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.'\n );\n }\n // Unsecured JWTs use \"none\" as the algorithm.\n const header = {\n alg: 'none',\n type: 'JWT'\n };\n\n const project = projectId || 'demo-project';\n const iat = token.iat || 0;\n const sub = token.sub || token.user_id;\n if (!sub) {\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\n }\n\n const payload: FirebaseIdToken = {\n // Set all required fields to decent defaults\n iss: `https://securetoken.google.com/${project}`,\n aud: project,\n iat,\n exp: iat + 3600,\n auth_time: iat,\n sub,\n user_id: sub,\n firebase: {\n sign_in_provider: 'custom',\n identities: {}\n },\n\n // Override with user options\n ...token\n };\n\n // Unsecured JWTs use the empty string as a signature.\n const signature = '';\n return [\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\n signature\n ].join('.');\n}\n\ninterface EmulatorStatusMap {\n [name: string]: boolean;\n}\nconst emulatorStatus: EmulatorStatusMap = {};\n\ninterface EmulatorSummary {\n prod: string[];\n emulator: string[];\n}\n\n// Checks whether any products are running on an emulator\nfunction getEmulatorSummary(): EmulatorSummary {\n const summary: EmulatorSummary = {\n prod: [],\n emulator: []\n };\n for (const key of Object.keys(emulatorStatus)) {\n if (emulatorStatus[key]) {\n summary.emulator.push(key);\n } else {\n summary.prod.push(key);\n }\n }\n return summary;\n}\n\nfunction getOrCreateEl(id: string): { created: boolean; element: HTMLElement } {\n let parentDiv = document.getElementById(id);\n let created = false;\n if (!parentDiv) {\n parentDiv = document.createElement('div');\n parentDiv.setAttribute('id', id);\n created = true;\n }\n return { created, element: parentDiv };\n}\n\nlet previouslyDismissed = false;\n/**\n * Updates Emulator Banner. Primarily used for Firebase Studio\n * @param name\n * @param isRunningEmulator\n * @public\n */\nexport function updateEmulatorBanner(\n name: string,\n isRunningEmulator: boolean\n): void {\n if (\n typeof window === 'undefined' ||\n typeof document === 'undefined' ||\n !isCloudWorkstation(window.location.host) ||\n emulatorStatus[name] === isRunningEmulator ||\n emulatorStatus[name] || // If already set to use emulator, can't go back to prod.\n previouslyDismissed\n ) {\n return;\n }\n\n emulatorStatus[name] = isRunningEmulator;\n\n function prefixedId(id: string): string {\n return `__firebase__banner__${id}`;\n }\n const bannerId = '__firebase__banner';\n const summary = getEmulatorSummary();\n const showError = summary.prod.length > 0;\n\n function tearDown(): void {\n const element = document.getElementById(bannerId);\n if (element) {\n element.remove();\n }\n }\n\n function setupBannerStyles(bannerEl: HTMLElement): void {\n bannerEl.style.display = 'flex';\n bannerEl.style.background = '#7faaf0';\n bannerEl.style.position = 'fixed';\n bannerEl.style.bottom = '5px';\n bannerEl.style.left = '5px';\n bannerEl.style.padding = '.5em';\n bannerEl.style.borderRadius = '5px';\n bannerEl.style.alignItems = 'center';\n }\n\n function setupIconStyles(prependIcon: SVGElement, iconId: string): void {\n prependIcon.setAttribute('width', '24');\n prependIcon.setAttribute('id', iconId);\n prependIcon.setAttribute('height', '24');\n prependIcon.setAttribute('viewBox', '0 0 24 24');\n prependIcon.setAttribute('fill', 'none');\n prependIcon.style.marginLeft = '-6px';\n }\n\n function setupCloseBtn(): HTMLSpanElement {\n const closeBtn = document.createElement('span');\n closeBtn.style.cursor = 'pointer';\n closeBtn.style.marginLeft = '16px';\n closeBtn.style.fontSize = '24px';\n closeBtn.innerHTML = ' ×';\n closeBtn.onclick = () => {\n previouslyDismissed = true;\n tearDown();\n };\n return closeBtn;\n }\n\n function setupLinkStyles(\n learnMoreLink: HTMLAnchorElement,\n learnMoreId: string\n ): void {\n learnMoreLink.setAttribute('id', learnMoreId);\n learnMoreLink.innerText = 'Learn more';\n learnMoreLink.href =\n 'https://firebase.google.com/docs/studio/preview-apps#preview-backend';\n learnMoreLink.setAttribute('target', '__blank');\n learnMoreLink.style.paddingLeft = '5px';\n learnMoreLink.style.textDecoration = 'underline';\n }\n\n function setupDom(): void {\n const banner = getOrCreateEl(bannerId);\n const firebaseTextId = prefixedId('text');\n const firebaseText: HTMLSpanElement =\n document.getElementById(firebaseTextId) || document.createElement('span');\n const learnMoreId = prefixedId('learnmore');\n const learnMoreLink: HTMLAnchorElement =\n (document.getElementById(learnMoreId) as HTMLAnchorElement) ||\n document.createElement('a');\n const prependIconId = prefixedId('preprendIcon');\n const prependIcon: SVGElement =\n (document.getElementById(\n prependIconId\n ) as HTMLOrSVGElement as SVGElement) ||\n document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n if (banner.created) {\n // update styles\n const bannerEl = banner.element;\n setupBannerStyles(bannerEl);\n setupLinkStyles(learnMoreLink, learnMoreId);\n const closeBtn = setupCloseBtn();\n setupIconStyles(prependIcon, prependIconId);\n bannerEl.append(prependIcon, firebaseText, learnMoreLink, closeBtn);\n document.body.appendChild(bannerEl);\n }\n\n if (showError) {\n firebaseText.innerText = `Preview backend disconnected.`;\n prependIcon.innerHTML = `\n\n\n\n\n\n\n`;\n } else {\n prependIcon.innerHTML = `\n\n\n\n\n\n\n`;\n firebaseText.innerText = 'Preview backend running in this workspace.';\n }\n firebaseText.setAttribute('id', firebaseTextId);\n }\n if (document.readyState === 'loading') {\n window.addEventListener('DOMContentLoaded', setupDom);\n } else {\n setupDom();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSTANTS } from './constants';\nimport { getDefaults } from './defaults';\n\n/**\n * Type placeholder for `WorkerGlobalScope` from `webworker`\n */\ndeclare class WorkerGlobalScope {}\n\n/**\n * Returns navigator.userAgent string or '' if it's not defined.\n * @return user agent string\n */\nexport function getUA(): string {\n if (\n typeof navigator !== 'undefined' &&\n typeof navigator['userAgent'] === 'string'\n ) {\n return navigator['userAgent'];\n } else {\n return '';\n }\n}\n\n/**\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\n *\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\n * wait for a callback.\n */\nexport function isMobileCordova(): boolean {\n return (\n typeof window !== 'undefined' &&\n // @ts-ignore Setting up an broadly applicable index signature for Window\n // just to deal with this case would probably be a bad idea.\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())\n );\n}\n\n/**\n * Detect Node.js.\n *\n * @return true if Node.js environment is detected or specified.\n */\n// Node detection logic from: https://github.com/iliakan/detect-node/\nexport function isNode(): boolean {\n const forceEnvironment = getDefaults()?.forceEnvironment;\n if (forceEnvironment === 'node') {\n return true;\n } else if (forceEnvironment === 'browser') {\n return false;\n }\n\n try {\n return (\n Object.prototype.toString.call(global.process) === '[object process]'\n );\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Detect Browser Environment.\n * Note: This will return true for certain test frameworks that are incompletely\n * mimicking a browser, and should not lead to assuming all browser APIs are\n * available.\n */\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined' || isWebWorker();\n}\n\n/**\n * Detect Web Worker context.\n */\nexport function isWebWorker(): boolean {\n return (\n typeof WorkerGlobalScope !== 'undefined' &&\n typeof self !== 'undefined' &&\n self instanceof WorkerGlobalScope\n );\n}\n\n/**\n * Detect Cloudflare Worker context.\n */\nexport function isCloudflareWorker(): boolean {\n return (\n typeof navigator !== 'undefined' &&\n navigator.userAgent === 'Cloudflare-Workers'\n );\n}\n\n/**\n * Detect browser extensions (Chrome and Firefox at least).\n */\ninterface BrowserRuntime {\n id?: unknown;\n}\ndeclare const chrome: { runtime?: BrowserRuntime };\ndeclare const browser: { runtime?: BrowserRuntime };\nexport function isBrowserExtension(): boolean {\n const runtime =\n typeof chrome === 'object'\n ? chrome.runtime\n : typeof browser === 'object'\n ? browser.runtime\n : undefined;\n return typeof runtime === 'object' && runtime.id !== undefined;\n}\n\n/**\n * Detect React Native.\n *\n * @return true if ReactNative environment is detected.\n */\nexport function isReactNative(): boolean {\n return (\n typeof navigator === 'object' && navigator['product'] === 'ReactNative'\n );\n}\n\n/** Detects Electron apps. */\nexport function isElectron(): boolean {\n return getUA().indexOf('Electron/') >= 0;\n}\n\n/** Detects Internet Explorer. */\nexport function isIE(): boolean {\n const ua = getUA();\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\n}\n\n/** Detects Universal Windows Platform apps. */\nexport function isUWP(): boolean {\n return getUA().indexOf('MSAppHost/') >= 0;\n}\n\n/**\n * Detect whether the current SDK build is the Node version.\n *\n * @return true if it's the Node SDK build.\n */\nexport function isNodeSdk(): boolean {\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\n}\n\n/** Returns true if we are running in Safari. */\nexport function isSafari(): boolean {\n return (\n !isNode() &&\n !!navigator.userAgent &&\n navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome')\n );\n}\n\n/** Returns true if we are running in Safari or WebKit */\nexport function isSafariOrWebkit(): boolean {\n return (\n !isNode() &&\n !!navigator.userAgent &&\n (navigator.userAgent.includes('Safari') ||\n navigator.userAgent.includes('WebKit')) &&\n !navigator.userAgent.includes('Chrome')\n );\n}\n\n/**\n * This method checks if indexedDB is supported by current browser/service worker context\n * @return true if indexedDB is supported by current browser/service worker context\n */\nexport function isIndexedDBAvailable(): boolean {\n try {\n return typeof indexedDB === 'object';\n } catch (e) {\n return false;\n }\n}\n\n/**\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\n * if errors occur during the database open operation.\n *\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\n * private browsing)\n */\nexport function validateIndexedDBOpenable(): Promise {\n return new Promise((resolve, reject) => {\n try {\n let preExist: boolean = true;\n const DB_CHECK_NAME =\n 'validate-browser-context-for-indexeddb-analytics-module';\n const request = self.indexedDB.open(DB_CHECK_NAME);\n request.onsuccess = () => {\n request.result.close();\n // delete database only when it doesn't pre-exist\n if (!preExist) {\n self.indexedDB.deleteDatabase(DB_CHECK_NAME);\n }\n resolve(true);\n };\n request.onupgradeneeded = () => {\n preExist = false;\n };\n\n request.onerror = () => {\n reject(request.error?.message || '');\n };\n } catch (error) {\n reject(error);\n }\n });\n}\n\n/**\n *\n * This method checks whether cookie is enabled within current browser\n * @return true if cookie is enabled within current browser\n */\nexport function areCookiesEnabled(): boolean {\n if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\n return false;\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n * // TypeScript string literals for type-safe codes\n * type Err =\n * 'unknown' |\n * 'object-not-found'\n * ;\n *\n * // Closure enum for type-safe error codes\n * // at-enum {string}\n * var Err = {\n * UNKNOWN: 'unknown',\n * OBJECT_NOT_FOUND: 'object-not-found',\n * }\n *\n * let errors: Map = {\n * 'generic-error': \"Unknown error\",\n * 'file-not-found': \"Could not find file: {$file}\",\n * };\n *\n * // Type-safe function - must pass a valid error code as param.\n * let error = new ErrorFactory('service', 'Service', errors);\n *\n * ...\n * throw error.create(Err.GENERIC);\n * ...\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n * ...\n * // Service: Could not file file: foo.txt (service/file-not-found).\n *\n * catch (e) {\n * assert(e.message === \"Could not find file: foo.txt.\");\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\n * console.log(\"Could not read file: \" + e['file']);\n * }\n * }\n */\n\nexport type ErrorMap = {\n readonly [K in ErrorCode]: string;\n};\n\nconst ERROR_NAME = 'FirebaseError';\n\nexport interface StringLike {\n toString(): string;\n}\n\nexport interface ErrorData {\n [key: string]: unknown;\n}\n\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nexport class FirebaseError extends Error {\n /** The custom name for all FirebaseErrors. */\n readonly name: string = ERROR_NAME;\n\n constructor(\n /** The error code for this error. */\n readonly code: string,\n message: string,\n /** Custom data for this error. */\n public customData?: Record\n ) {\n super(message);\n\n // Fix For ES5\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget\n // which we can now use since we no longer target ES5.\n Object.setPrototypeOf(this, FirebaseError.prototype);\n\n // Maintains proper stack trace for where our error was thrown.\n // Only available on V8.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\n }\n }\n}\n\nexport class ErrorFactory<\n ErrorCode extends string,\n ErrorParams extends { readonly [K in ErrorCode]?: ErrorData } = {}\n> {\n constructor(\n private readonly service: string,\n private readonly serviceName: string,\n private readonly errors: ErrorMap\n ) {}\n\n create(\n code: K,\n ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []\n ): FirebaseError {\n const customData = (data[0] as ErrorData) || {};\n const fullCode = `${this.service}/${code}`;\n const template = this.errors[code];\n\n const message = template ? replaceTemplate(template, customData) : 'Error';\n // Service Name: Error message (service/code).\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n\n const error = new FirebaseError(fullCode, fullMessage, customData);\n\n return error;\n }\n}\n\nfunction replaceTemplate(template: string, data: ErrorData): string {\n return template.replace(PATTERN, (_, key) => {\n const value = data[key];\n return value != null ? String(value) : `<${key}?>`;\n });\n}\n\nconst PATTERN = /\\{\\$([^}]+)}/g;\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Evaluates a JSON string into a javascript object.\n *\n * @param {string} str A string containing JSON.\n * @return {*} The javascript object representing the specified JSON.\n */\nexport function jsonEval(str: string): unknown {\n return JSON.parse(str);\n}\n\n/**\n * Returns JSON representing a javascript object.\n * @param {*} data JavaScript object to be stringified.\n * @return {string} The JSON contents of the object.\n */\nexport function stringify(data: unknown): string {\n return JSON.stringify(data);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Decode } from './crypt';\nimport { jsonEval } from './json';\n\ninterface Claims {\n [key: string]: {};\n}\n\ninterface DecodedToken {\n header: object;\n claims: Claims;\n data: object;\n signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token into constituent parts.\n *\n * Notes:\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const decode = function (token: string): DecodedToken {\n let header = {},\n claims: Claims = {},\n data = {},\n signature = '';\n\n try {\n const parts = token.split('.');\n header = jsonEval(base64Decode(parts[0]) || '') as object;\n claims = jsonEval(base64Decode(parts[1]) || '') as Claims;\n signature = parts[2];\n data = claims['d'] || {};\n delete claims['d'];\n } catch (e) {}\n\n return {\n header,\n claims,\n data,\n signature\n };\n};\n\ninterface DecodedToken {\n header: object;\n claims: Claims;\n data: object;\n signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidTimestamp = function (token: string): boolean {\n const claims: Claims = decode(token).claims;\n const now: number = Math.floor(new Date().getTime() / 1000);\n let validSince: number = 0,\n validUntil: number = 0;\n\n if (typeof claims === 'object') {\n if (claims.hasOwnProperty('nbf')) {\n validSince = claims['nbf'] as number;\n } else if (claims.hasOwnProperty('iat')) {\n validSince = claims['iat'] as number;\n }\n\n if (claims.hasOwnProperty('exp')) {\n validUntil = claims['exp'] as number;\n } else {\n // token will expire after 24h by default\n validUntil = validSince + 86400;\n }\n }\n\n return (\n !!now &&\n !!validSince &&\n !!validUntil &&\n now >= validSince &&\n now <= validUntil\n );\n};\n\n/**\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\n *\n * Notes:\n * - May return null if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const issuedAtTime = function (token: string): number | null {\n const claims: Claims = decode(token).claims;\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\n return claims['iat'] as number;\n }\n return null;\n};\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidFormat = function (token: string): boolean {\n const decoded = decode(token),\n claims = decoded.claims;\n\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\n};\n\n/**\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isAdmin = function (token: string): boolean {\n const claims: Claims = decode(token).claims;\n return typeof claims === 'object' && claims['admin'] === true;\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function contains(obj: T, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function safeGet(\n obj: T,\n key: K\n): T[K] | undefined {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return obj[key];\n } else {\n return undefined;\n }\n}\n\nexport function isEmpty(obj: object): obj is {} {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\n\nexport function map(\n obj: { [key in K]: V },\n fn: (value: V, key: K, obj: { [key in K]: V }) => U,\n contextObj?: unknown\n): { [key in K]: U } {\n const res: Partial<{ [key in K]: U }> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n res[key] = fn.call(contextObj, obj[key], key, obj);\n }\n }\n return res as { [key in K]: U };\n}\n\n/**\n * Deep equal two objects. Support Arrays and Objects.\n */\nexport function deepEqual(a: object, b: object): boolean {\n if (a === b) {\n return true;\n }\n\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n for (const k of aKeys) {\n if (!bKeys.includes(k)) {\n return false;\n }\n\n const aProp = (a as Record)[k];\n const bProp = (b as Record)[k];\n if (isObject(aProp) && isObject(bProp)) {\n if (!deepEqual(aProp, bProp)) {\n return false;\n }\n } else if (aProp !== bProp) {\n return false;\n }\n }\n\n for (const k of bKeys) {\n if (!aKeys.includes(k)) {\n return false;\n }\n }\n return true;\n}\n\nfunction isObject(thing: unknown): thing is object {\n return thing !== null && typeof thing === 'object';\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from './deferred';\n\n/**\n * Rejects if the given promise doesn't resolve in timeInMS milliseconds.\n * @internal\n */\nexport function promiseWithTimeout(\n promise: Promise,\n timeInMS = 2000\n): Promise {\n const deferredPromise = new Deferred();\n setTimeout(() => deferredPromise.reject('timeout!'), timeInMS);\n promise.then(deferredPromise.resolve, deferredPromise.reject);\n return deferredPromise.promise;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\n * params object (e.g. {arg: 'val', arg2: 'val2'})\n * Note: You must prepend it with ? when adding it to a URL.\n */\nexport function querystring(querystringParams: {\n [key: string]: string | number;\n}): string {\n const params = [];\n for (const [key, value] of Object.entries(querystringParams)) {\n if (Array.isArray(value)) {\n value.forEach(arrayVal => {\n params.push(\n encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal)\n );\n });\n } else {\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n }\n }\n return params.length ? '&' + params.join('&') : '';\n}\n\n/**\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\n * (e.g. {arg: 'val', arg2: 'val2'})\n */\nexport function querystringDecode(querystring: string): Record {\n const obj: Record = {};\n const tokens = querystring.replace(/^\\?/, '').split('&');\n\n tokens.forEach(token => {\n if (token) {\n const [key, value] = token.split('=');\n obj[decodeURIComponent(key)] = decodeURIComponent(value);\n }\n });\n return obj;\n}\n\n/**\n * Extract the query string part of a URL, including the leading question mark (if present).\n */\nexport function extractQuerystring(url: string): string {\n const queryStart = url.indexOf('?');\n if (!queryStart) {\n return '';\n }\n const fragmentStart = url.indexOf('#', queryStart);\n return url.substring(\n queryStart,\n fragmentStart > 0 ? fragmentStart : undefined\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview SHA-1 cryptographic hash.\n * Variable names follow the notation in FIPS PUB 180-3:\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\n *\n * Usage:\n * var sha1 = new sha1();\n * sha1.update(bytes);\n * var hash = sha1.digest();\n *\n * Performance:\n * Chrome 23: ~400 Mbit/s\n * Firefox 16: ~250 Mbit/s\n *\n */\n\n/**\n * SHA-1 cryptographic hash constructor.\n *\n * The properties declared here are discussed in the above algorithm document.\n * @constructor\n * @final\n * @struct\n */\nexport class Sha1 {\n /**\n * Holds the previous values of accumulated variables a-e in the compress_\n * function.\n * @private\n */\n private chain_: number[] = [];\n\n /**\n * A buffer holding the partially computed hash result.\n * @private\n */\n private buf_: number[] = [];\n\n /**\n * An array of 80 bytes, each a part of the message to be hashed. Referred to\n * as the message schedule in the docs.\n * @private\n */\n private W_: number[] = [];\n\n /**\n * Contains data needed to pad messages less than 64 bytes.\n * @private\n */\n private pad_: number[] = [];\n\n /**\n * @private {number}\n */\n private inbuf_: number = 0;\n\n /**\n * @private {number}\n */\n private total_: number = 0;\n\n blockSize: number;\n\n constructor() {\n this.blockSize = 512 / 8;\n\n this.pad_[0] = 128;\n for (let i = 1; i < this.blockSize; ++i) {\n this.pad_[i] = 0;\n }\n\n this.reset();\n }\n\n reset(): void {\n this.chain_[0] = 0x67452301;\n this.chain_[1] = 0xefcdab89;\n this.chain_[2] = 0x98badcfe;\n this.chain_[3] = 0x10325476;\n this.chain_[4] = 0xc3d2e1f0;\n\n this.inbuf_ = 0;\n this.total_ = 0;\n }\n\n /**\n * Internal compress helper function.\n * @param buf Block to compress.\n * @param offset Offset of the block in the buffer.\n * @private\n */\n compress_(buf: number[] | Uint8Array | string, offset?: number): void {\n if (!offset) {\n offset = 0;\n }\n\n const W = this.W_;\n\n // get 16 big endian words\n if (typeof buf === 'string') {\n for (let i = 0; i < 16; i++) {\n // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\n // have a bug that turns the post-increment ++ operator into pre-increment\n // during JIT compilation. We have code that depends heavily on SHA-1 for\n // correctness and which is affected by this bug, so I've removed all uses\n // of post-increment ++ in which the result value is used. We can revert\n // this change once the Safari bug\n // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\n // most clients have been updated.\n W[i] =\n (buf.charCodeAt(offset) << 24) |\n (buf.charCodeAt(offset + 1) << 16) |\n (buf.charCodeAt(offset + 2) << 8) |\n buf.charCodeAt(offset + 3);\n offset += 4;\n }\n } else {\n for (let i = 0; i < 16; i++) {\n W[i] =\n (buf[offset] << 24) |\n (buf[offset + 1] << 16) |\n (buf[offset + 2] << 8) |\n buf[offset + 3];\n offset += 4;\n }\n }\n\n // expand to 80 words\n for (let i = 16; i < 80; i++) {\n const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\n W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\n }\n\n let a = this.chain_[0];\n let b = this.chain_[1];\n let c = this.chain_[2];\n let d = this.chain_[3];\n let e = this.chain_[4];\n let f, k;\n\n // TODO(user): Try to unroll this loop to speed up the computation.\n for (let i = 0; i < 80; i++) {\n if (i < 40) {\n if (i < 20) {\n f = d ^ (b & (c ^ d));\n k = 0x5a827999;\n } else {\n f = b ^ c ^ d;\n k = 0x6ed9eba1;\n }\n } else {\n if (i < 60) {\n f = (b & c) | (d & (b | c));\n k = 0x8f1bbcdc;\n } else {\n f = b ^ c ^ d;\n k = 0xca62c1d6;\n }\n }\n\n const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\n e = d;\n d = c;\n c = ((b << 30) | (b >>> 2)) & 0xffffffff;\n b = a;\n a = t;\n }\n\n this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\n this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\n this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\n this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\n this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\n }\n\n update(bytes?: number[] | Uint8Array | string, length?: number): void {\n // TODO(johnlenz): tighten the function signature and remove this check\n if (bytes == null) {\n return;\n }\n\n if (length === undefined) {\n length = bytes.length;\n }\n\n const lengthMinusBlock = length - this.blockSize;\n let n = 0;\n // Using local instead of member variables gives ~5% speedup on Firefox 16.\n const buf = this.buf_;\n let inbuf = this.inbuf_;\n\n // The outer while loop should execute at most twice.\n while (n < length) {\n // When we have no data in the block to top up, we can directly process the\n // input buffer (assuming it contains sufficient data). This gives ~25%\n // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\n // the data is provided in large chunks (or in multiples of 64 bytes).\n if (inbuf === 0) {\n while (n <= lengthMinusBlock) {\n this.compress_(bytes, n);\n n += this.blockSize;\n }\n }\n\n if (typeof bytes === 'string') {\n while (n < length) {\n buf[inbuf] = bytes.charCodeAt(n);\n ++inbuf;\n ++n;\n if (inbuf === this.blockSize) {\n this.compress_(buf);\n inbuf = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n } else {\n while (n < length) {\n buf[inbuf] = bytes[n];\n ++inbuf;\n ++n;\n if (inbuf === this.blockSize) {\n this.compress_(buf);\n inbuf = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n }\n }\n\n this.inbuf_ = inbuf;\n this.total_ += length;\n }\n\n /** @override */\n digest(): number[] {\n const digest: number[] = [];\n let totalBits = this.total_ * 8;\n\n // Add pad 0x80 0x00*.\n if (this.inbuf_ < 56) {\n this.update(this.pad_, 56 - this.inbuf_);\n } else {\n this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\n }\n\n // Add # bits.\n for (let i = this.blockSize - 1; i >= 56; i--) {\n this.buf_[i] = totalBits & 255;\n totalBits /= 256; // Don't use bit-shifting here!\n }\n\n this.compress_(this.buf_);\n\n let n = 0;\n for (let i = 0; i < 5; i++) {\n for (let j = 24; j >= 0; j -= 8) {\n digest[n] = (this.chain_[i] >> j) & 255;\n ++n;\n }\n }\n return digest;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport type NextFn = (value: T) => void;\nexport type ErrorFn = (error: Error) => void;\nexport type CompleteFn = () => void;\n\nexport interface Observer {\n // Called once for each value in a stream of values.\n next: NextFn;\n\n // A stream terminates by a single call to EITHER error() or complete().\n error: ErrorFn;\n\n // No events will be sent to next() once complete() is called.\n complete: CompleteFn;\n}\n\nexport type PartialObserver = Partial>;\n\n// TODO: Support also Unsubscribe.unsubscribe?\nexport type Unsubscribe = () => void;\n\n/**\n * The Subscribe interface has two forms - passing the inline function\n * callbacks, or a object interface with callback properties.\n */\nexport interface Subscribe {\n (next?: NextFn, error?: ErrorFn, complete?: CompleteFn): Unsubscribe;\n (observer: PartialObserver): Unsubscribe;\n}\n\nexport interface Observable {\n // Subscribe method\n subscribe: Subscribe;\n}\n\nexport type Executor = (observer: Observer) => void;\n\n/**\n * Helper to make a Subscribe function (just like Promise helps make a\n * Thenable).\n *\n * @param executor Function which can make calls to a single Observer\n * as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\nexport function createSubscribe(\n executor: Executor,\n onNoObservers?: Executor\n): Subscribe {\n const proxy = new ObserverProxy(executor, onNoObservers);\n return proxy.subscribe.bind(proxy);\n}\n\n/**\n * Implement fan-out for any number of Observers attached via a subscribe\n * function.\n */\nclass ObserverProxy implements Observer {\n private observers: Array> | undefined = [];\n private unsubscribes: Unsubscribe[] = [];\n private onNoObservers: Executor | undefined;\n private observerCount = 0;\n // Micro-task scheduling by calling task.then().\n private task = Promise.resolve();\n private finalized = false;\n private finalError?: Error;\n\n /**\n * @param executor Function which can make calls to a single Observer\n * as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\n constructor(executor: Executor, onNoObservers?: Executor) {\n this.onNoObservers = onNoObservers;\n // Call the executor asynchronously so subscribers that are called\n // synchronously after the creation of the subscribe function\n // can still receive the very first value generated in the executor.\n this.task\n .then(() => {\n executor(this);\n })\n .catch(e => {\n this.error(e);\n });\n }\n\n next(value: T): void {\n this.forEachObserver((observer: Observer) => {\n observer.next(value);\n });\n }\n\n error(error: Error): void {\n this.forEachObserver((observer: Observer) => {\n observer.error(error);\n });\n this.close(error);\n }\n\n complete(): void {\n this.forEachObserver((observer: Observer) => {\n observer.complete();\n });\n this.close();\n }\n\n /**\n * Subscribe function that can be used to add an Observer to the fan-out list.\n *\n * - We require that no event is sent to a subscriber synchronously to their\n * call to subscribe().\n */\n subscribe(\n nextOrObserver?: NextFn | PartialObserver,\n error?: ErrorFn,\n complete?: CompleteFn\n ): Unsubscribe {\n let observer: Observer;\n\n if (\n nextOrObserver === undefined &&\n error === undefined &&\n complete === undefined\n ) {\n throw new Error('Missing Observer.');\n }\n\n // Assemble an Observer object when passed as callback functions.\n if (\n implementsAnyMethods(nextOrObserver as { [key: string]: unknown }, [\n 'next',\n 'error',\n 'complete'\n ])\n ) {\n observer = nextOrObserver as Observer;\n } else {\n observer = {\n next: nextOrObserver as NextFn,\n error,\n complete\n } as Observer;\n }\n\n if (observer.next === undefined) {\n observer.next = noop as NextFn;\n }\n if (observer.error === undefined) {\n observer.error = noop as ErrorFn;\n }\n if (observer.complete === undefined) {\n observer.complete = noop as CompleteFn;\n }\n\n const unsub = this.unsubscribeOne.bind(this, this.observers!.length);\n\n // Attempt to subscribe to a terminated Observable - we\n // just respond to the Observer with the final error or complete\n // event.\n if (this.finalized) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n try {\n if (this.finalError) {\n observer.error(this.finalError);\n } else {\n observer.complete();\n }\n } catch (e) {\n // nothing\n }\n return;\n });\n }\n\n this.observers!.push(observer as Observer);\n\n return unsub;\n }\n\n // Unsubscribe is synchronous - we guarantee that no events are sent to\n // any unsubscribed Observer.\n private unsubscribeOne(i: number): void {\n if (this.observers === undefined || this.observers[i] === undefined) {\n return;\n }\n\n delete this.observers[i];\n\n this.observerCount -= 1;\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\n this.onNoObservers(this);\n }\n }\n\n private forEachObserver(fn: (observer: Observer) => void): void {\n if (this.finalized) {\n // Already closed by previous event....just eat the additional values.\n return;\n }\n\n // Since sendOne calls asynchronously - there is no chance that\n // this.observers will become undefined.\n for (let i = 0; i < this.observers!.length; i++) {\n this.sendOne(i, fn);\n }\n }\n\n // Call the Observer via one of it's callback function. We are careful to\n // confirm that the observe has not been unsubscribed since this asynchronous\n // function had been queued.\n private sendOne(i: number, fn: (observer: Observer) => void): void {\n // Execute the callback asynchronously\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n if (this.observers !== undefined && this.observers[i] !== undefined) {\n try {\n fn(this.observers[i]);\n } catch (e) {\n // Ignore exceptions raised in Observers or missing methods of an\n // Observer.\n // Log error to console. b/31404806\n if (typeof console !== 'undefined' && console.error) {\n console.error(e);\n }\n }\n }\n });\n }\n\n private close(err?: Error): void {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n if (err !== undefined) {\n this.finalError = err;\n }\n // Proxy is no longer needed - garbage collect references\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n this.observers = undefined;\n this.onNoObservers = undefined;\n });\n }\n}\n\n/** Turn synchronous function into one called asynchronously. */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function async(fn: Function, onError?: ErrorFn): Function {\n return (...args: unknown[]) => {\n Promise.resolve(true)\n .then(() => {\n fn(...args);\n })\n .catch((error: Error) => {\n if (onError) {\n onError(error);\n }\n });\n };\n}\n\n/**\n * Return true if the object passed in implements any of the named methods.\n */\nfunction implementsAnyMethods(\n obj: { [key: string]: unknown },\n methods: string[]\n): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n for (const method of methods) {\n if (method in obj && typeof obj[method] === 'function') {\n return true;\n }\n }\n\n return false;\n}\n\nfunction noop(): void {\n // do nothing\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Check to make sure the appropriate number of arguments are provided for a public function.\n * Throws an error if it fails.\n *\n * @param fnName The function name\n * @param minCount The minimum number of arguments to allow for the function call\n * @param maxCount The maximum number of argument to allow for the function call\n * @param argCount The actual number of arguments provided.\n */\nexport const validateArgCount = function (\n fnName: string,\n minCount: number,\n maxCount: number,\n argCount: number\n): void {\n let argError;\n if (argCount < minCount) {\n argError = 'at least ' + minCount;\n } else if (argCount > maxCount) {\n argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\n }\n if (argError) {\n const error =\n fnName +\n ' failed: Was called with ' +\n argCount +\n (argCount === 1 ? ' argument.' : ' arguments.') +\n ' Expects ' +\n argError +\n '.';\n throw new Error(error);\n }\n};\n\n/**\n * Generates a string to prefix an error message about failed argument validation\n *\n * @param fnName The function name\n * @param argName The name of the argument\n * @return The prefix to add to the error thrown for validation.\n */\nexport function errorPrefix(fnName: string, argName: string): string {\n return `${fnName} failed: ${argName} argument `;\n}\n\n/**\n * @param fnName\n * @param argumentNumber\n * @param namespace\n * @param optional\n */\nexport function validateNamespace(\n fnName: string,\n namespace: string,\n optional: boolean\n): void {\n if (optional && !namespace) {\n return;\n }\n if (typeof namespace !== 'string') {\n //TODO: I should do more validation here. We only allow certain chars in namespaces.\n throw new Error(\n errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.'\n );\n }\n}\n\nexport function validateCallback(\n fnName: string,\n argumentName: string,\n // eslint-disable-next-line @typescript-eslint/ban-types\n callback: Function,\n optional: boolean\n): void {\n if (optional && !callback) {\n return;\n }\n if (typeof callback !== 'function') {\n throw new Error(\n errorPrefix(fnName, argumentName) + 'must be a valid function.'\n );\n }\n}\n\nexport function validateContextObject(\n fnName: string,\n argumentName: string,\n context: unknown,\n optional: boolean\n): void {\n if (optional && !context) {\n return;\n }\n if (typeof context !== 'object' || context === null) {\n throw new Error(\n errorPrefix(fnName, argumentName) + 'must be a valid context object.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from './assert';\n\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\n// so it's been modified.\n\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\n// use 2 characters in JavaScript. All 4-byte UTF-8 characters begin with a first\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\n// pair).\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\n\n/**\n * @param {string} str\n * @return {Array}\n */\nexport const stringToByteArray = function (str: string): number[] {\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n\n // Is this the lead surrogate in a surrogate pair?\n if (c >= 0xd800 && c <= 0xdbff) {\n const high = c - 0xd800; // the high 10 bits.\n i++;\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\n const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\n c = 0x10000 + (high << 10) + low;\n }\n\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (c < 65536) {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Calculate length without actually converting; useful for doing cheaper validation.\n * @param {string} str\n * @return {number}\n */\nexport const stringLength = function (str: string): number {\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n const c = str.charCodeAt(i);\n if (c < 128) {\n p++;\n } else if (c < 2048) {\n p += 2;\n } else if (c >= 0xd800 && c <= 0xdbff) {\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\n p += 4;\n i++; // skip trail surrogate.\n } else {\n p += 3;\n }\n }\n return p;\n};\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The amount of milliseconds to exponentially increase.\n */\nconst DEFAULT_INTERVAL_MILLIS = 1000;\n\n/**\n * The factor to backoff by.\n * Should be a number greater than 1.\n */\nconst DEFAULT_BACKOFF_FACTOR = 2;\n\n/**\n * The maximum milliseconds to increase to.\n *\n *

Visible for testing\n */\nexport const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\n\n/**\n * The percentage of backoff time to randomize by.\n * See\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\n * for context.\n *\n *

Visible for testing\n */\nexport const RANDOM_FACTOR = 0.5;\n\n/**\n * Based on the backoff method from\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\n */\nexport function calculateBackoffMillis(\n backoffCount: number,\n intervalMillis: number = DEFAULT_INTERVAL_MILLIS,\n backoffFactor: number = DEFAULT_BACKOFF_FACTOR\n): number {\n // Calculates an exponentially increasing value.\n // Deviation: calculates value from count and a constant interval, so we only need to save value\n // and count to restore state.\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\n\n // A random \"fuzz\" to avoid waves of retries.\n // Deviation: randomFactor is required.\n const randomWait = Math.round(\n // A fraction of the backoff value to add/subtract.\n // Deviation: changes multiplication order to improve readability.\n RANDOM_FACTOR *\n currBaseValue *\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\n // if we add or subtract.\n (Math.random() - 0.5) *\n 2\n );\n\n // Limits backoff to max to avoid effectively permanent backoff.\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Provide English ordinal letters after a number\n */\nexport function ordinal(i: number): string {\n if (!Number.isFinite(i)) {\n return `${i}`;\n }\n return i + indicator(i);\n}\n\nfunction indicator(i: number): string {\n i = Math.abs(i);\n const cent = i % 100;\n if (cent >= 10 && cent <= 20) {\n return 'th';\n }\n const dec = i % 10;\n if (dec === 1) {\n return 'st';\n }\n if (dec === 2) {\n return 'nd';\n }\n if (dec === 3) {\n return 'rd';\n }\n return 'th';\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Compat {\n _delegate: T;\n}\n\nexport function getModularInstance(\n service: Compat | ExpService\n): ExpService {\n if (service && (service as Compat)._delegate) {\n return (service as Compat)._delegate;\n } else {\n return service as ExpService;\n }\n}\n"],"names":["stringToByteArray"],"mappings":";;AAAA,CAAA,CAAA;;;;;;;;;;;;;;;AAeG,CAAA,CAAA;AAEH,CAAA,CAAA;;AAEG,CAAA,CAAA;AAEU,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,SAAS,CAAG,CAAA,CAAA;AACvB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;;AAEG,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AACH,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAW,EAAE,CAAK,CAAA,CAAA,CAAA,CAAA;AAClB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;;AAEG,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AACH,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CA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new file mode 100644 index 0000000..5c6790a --- /dev/null +++ b/node_modules/@firebase/util/dist/index.node.cjs.js @@ -0,0 +1,2411 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var postinstall = require('./postinstall.js'); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time. + */ +const CONSTANTS = { + /** + * @define {boolean} Whether this is the client Node.js SDK. + */ + NODE_CLIENT: false, + /** + * @define {boolean} Whether this is the Admin Node.js SDK. + */ + NODE_ADMIN: false, + /** + * Firebase SDK Version + */ + SDK_VERSION: '${JSCORE_VERSION}' +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Throws an error if the provided assertion is falsy + */ +const assert = function (assertion, message) { + if (!assertion) { + throw assertionError(message); + } +}; +/** + * Returns an Error object suitable for throwing. + */ +const assertionError = function (message) { + return new Error('Firebase Database (' + + CONSTANTS.SDK_VERSION + + ') INTERNAL ASSERT FAILED: ' + + message); +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const stringToByteArray$1 = function (str) { + // TODO(user): Use native implementations if/when available + const out = []; + let p = 0; + for (let i = 0; i < str.length; i++) { + let c = str.charCodeAt(i); + if (c < 128) { + out[p++] = c; + } + else if (c < 2048) { + out[p++] = (c >> 6) | 192; + out[p++] = (c & 63) | 128; + } + else if ((c & 0xfc00) === 0xd800 && + i + 1 < str.length && + (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { + // Surrogate Pair + c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff); + out[p++] = (c >> 18) | 240; + out[p++] = ((c >> 12) & 63) | 128; + out[p++] = ((c >> 6) & 63) | 128; + out[p++] = (c & 63) | 128; + } + else { + out[p++] = (c >> 12) | 224; + out[p++] = ((c >> 6) & 63) | 128; + out[p++] = (c & 63) | 128; + } + } + return out; +}; +/** + * Turns an array of numbers into the string given by the concatenation of the + * characters to which the numbers correspond. + * @param bytes Array of numbers representing characters. + * @return Stringification of the array. + */ +const byteArrayToString = function (bytes) { + // TODO(user): Use native implementations if/when available + const out = []; + let pos = 0, c = 0; + while (pos < bytes.length) { + const c1 = bytes[pos++]; + if (c1 < 128) { + out[c++] = String.fromCharCode(c1); + } + else if (c1 > 191 && c1 < 224) { + const c2 = bytes[pos++]; + out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63)); + } + else if (c1 > 239 && c1 < 365) { + // Surrogate Pair + const c2 = bytes[pos++]; + const c3 = bytes[pos++]; + const c4 = bytes[pos++]; + const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) - + 0x10000; + out[c++] = String.fromCharCode(0xd800 + (u >> 10)); + out[c++] = String.fromCharCode(0xdc00 + (u & 1023)); + } + else { + const c2 = bytes[pos++]; + const c3 = bytes[pos++]; + out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); + } + } + return out.join(''); +}; +// We define it as an object literal instead of a class because a class compiled down to es5 can't +// be treeshaked. https://github.com/rollup/rollup/issues/1691 +// Static lookup maps, lazily populated by init_() +// TODO(dlarocque): Define this as a class, since we no longer target ES5. +const base64 = { + /** + * Maps bytes to characters. + */ + byteToCharMap_: null, + /** + * Maps characters to bytes. + */ + charToByteMap_: null, + /** + * Maps bytes to websafe characters. + * @private + */ + byteToCharMapWebSafe_: null, + /** + * Maps websafe characters to bytes. + * @private + */ + charToByteMapWebSafe_: null, + /** + * Our default alphabet, shared between + * ENCODED_VALS and ENCODED_VALS_WEBSAFE + */ + ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789', + /** + * Our default alphabet. Value 64 (=) is special; it means "nothing." + */ + get ENCODED_VALS() { + return this.ENCODED_VALS_BASE + '+/='; + }, + /** + * Our websafe alphabet. + */ + get ENCODED_VALS_WEBSAFE() { + return this.ENCODED_VALS_BASE + '-_.'; + }, + /** + * Whether this browser supports the atob and btoa functions. This extension + * started at Mozilla but is now implemented by many browsers. We use the + * ASSUME_* variables to avoid pulling in the full useragent detection library + * but still allowing the standard per-browser compilations. + * + */ + HAS_NATIVE_SUPPORT: typeof atob === 'function', + /** + * Base64-encode an array of bytes. + * + * @param input An array of bytes (numbers with + * value in [0, 255]) to encode. + * @param webSafe Boolean indicating we should use the + * alternative alphabet. + * @return The base64 encoded string. + */ + encodeByteArray(input, webSafe) { + if (!Array.isArray(input)) { + throw Error('encodeByteArray takes an array as a parameter'); + } + this.init_(); + const byteToCharMap = webSafe + ? this.byteToCharMapWebSafe_ + : this.byteToCharMap_; + const output = []; + for (let i = 0; i < input.length; i += 3) { + const byte1 = input[i]; + const haveByte2 = i + 1 < input.length; + const byte2 = haveByte2 ? input[i + 1] : 0; + const haveByte3 = i + 2 < input.length; + const byte3 = haveByte3 ? input[i + 2] : 0; + const outByte1 = byte1 >> 2; + const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4); + let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6); + let outByte4 = byte3 & 0x3f; + if (!haveByte3) { + outByte4 = 64; + if (!haveByte2) { + outByte3 = 64; + } + } + output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]); + } + return output.join(''); + }, + /** + * Base64-encode a string. + * + * @param input A string to encode. + * @param webSafe If true, we should use the + * alternative alphabet. + * @return The base64 encoded string. + */ + encodeString(input, webSafe) { + // Shortcut for Mozilla browsers that implement + // a native base64 encoder in the form of "btoa/atob" + if (this.HAS_NATIVE_SUPPORT && !webSafe) { + return btoa(input); + } + return this.encodeByteArray(stringToByteArray$1(input), webSafe); + }, + /** + * Base64-decode a string. + * + * @param input to decode. + * @param webSafe True if we should use the + * alternative alphabet. + * @return string representing the decoded value. + */ + decodeString(input, webSafe) { + // Shortcut for Mozilla browsers that implement + // a native base64 encoder in the form of "btoa/atob" + if (this.HAS_NATIVE_SUPPORT && !webSafe) { + return atob(input); + } + return byteArrayToString(this.decodeStringToByteArray(input, webSafe)); + }, + /** + * Base64-decode a string. + * + * In base-64 decoding, groups of four characters are converted into three + * bytes. If the encoder did not apply padding, the input length may not + * be a multiple of 4. + * + * In this case, the last group will have fewer than 4 characters, and + * padding will be inferred. If the group has one or two characters, it decodes + * to one byte. If the group has three characters, it decodes to two bytes. + * + * @param input Input to decode. + * @param webSafe True if we should use the web-safe alphabet. + * @return bytes representing the decoded value. + */ + decodeStringToByteArray(input, webSafe) { + this.init_(); + const charToByteMap = webSafe + ? this.charToByteMapWebSafe_ + : this.charToByteMap_; + const output = []; + for (let i = 0; i < input.length;) { + const byte1 = charToByteMap[input.charAt(i++)]; + const haveByte2 = i < input.length; + const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0; + ++i; + const haveByte3 = i < input.length; + const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64; + ++i; + const haveByte4 = i < input.length; + const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64; + ++i; + if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) { + throw new DecodeBase64StringError(); + } + const outByte1 = (byte1 << 2) | (byte2 >> 4); + output.push(outByte1); + if (byte3 !== 64) { + const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2); + output.push(outByte2); + if (byte4 !== 64) { + const outByte3 = ((byte3 << 6) & 0xc0) | byte4; + output.push(outByte3); + } + } + } + return output; + }, + /** + * Lazy static initialization function. Called before + * accessing any of the static map variables. + * @private + */ + init_() { + if (!this.byteToCharMap_) { + this.byteToCharMap_ = {}; + this.charToByteMap_ = {}; + this.byteToCharMapWebSafe_ = {}; + this.charToByteMapWebSafe_ = {}; + // We want quick mappings back and forth, so we precompute two maps. + for (let i = 0; i < this.ENCODED_VALS.length; i++) { + this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i); + this.charToByteMap_[this.byteToCharMap_[i]] = i; + this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i); + this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i; + // Be forgiving when decoding and correctly decode both encodings. + if (i >= this.ENCODED_VALS_BASE.length) { + this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i; + this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i; + } + } + } + } +}; +/** + * An error encountered while decoding base64 string. + */ +class DecodeBase64StringError extends Error { + constructor() { + super(...arguments); + this.name = 'DecodeBase64StringError'; + } +} +/** + * URL-safe base64 encoding + */ +const base64Encode = function (str) { + const utf8Bytes = stringToByteArray$1(str); + return base64.encodeByteArray(utf8Bytes, true); +}; +/** + * URL-safe base64 encoding (without "." padding in the end). + * e.g. Used in JSON Web Token (JWT) parts. + */ +const base64urlEncodeWithoutPadding = function (str) { + // Use base64url encoding and remove padding in the end (dot characters). + return base64Encode(str).replace(/\./g, ''); +}; +/** + * URL-safe base64 decoding + * + * NOTE: DO NOT use the global atob() function - it does NOT support the + * base64Url variant encoding. + * + * @param str To be decoded + * @return Decoded result, if possible + */ +const base64Decode = function (str) { + try { + return base64.decodeString(str, true); + } + catch (e) { + console.error('base64Decode failed: ', e); + } + return null; +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Do a deep-copy of basic JavaScript Objects or Arrays. + */ +function deepCopy(value) { + return deepExtend(undefined, value); +} +/** + * Copy properties from source to target (recursively allows extension + * of Objects and Arrays). Scalar values in the target are over-written. + * If target is undefined, an object of the appropriate type will be created + * (and returned). + * + * We recursively copy all child properties of plain Objects in the source- so + * that namespace- like dictionaries are merged. + * + * Note that the target can be a function, in which case the properties in + * the source Object are copied onto it as static properties of the Function. + * + * Note: we don't merge __proto__ to prevent prototype pollution + */ +function deepExtend(target, source) { + if (!(source instanceof Object)) { + return source; + } + switch (source.constructor) { + case Date: + // Treat Dates like scalars; if the target date object had any child + // properties - they will be lost! + const dateValue = source; + return new Date(dateValue.getTime()); + case Object: + if (target === undefined) { + target = {}; + } + break; + case Array: + // Always copy the array source and overwrite the target. + target = []; + break; + default: + // Not a plain Object - treat it as a scalar. + return source; + } + for (const prop in source) { + // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202 + if (!source.hasOwnProperty(prop) || !isValidKey(prop)) { + continue; + } + target[prop] = deepExtend(target[prop], source[prop]); + } + return target; +} +function isValidKey(key) { + return key !== '__proto__'; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Polyfill for `globalThis` object. + * @returns the `globalThis` object for the given environment. + * @public + */ +function getGlobal() { + if (typeof self !== 'undefined') { + return self; + } + if (typeof window !== 'undefined') { + return window; + } + if (typeof global !== 'undefined') { + return global; + } + throw new Error('Unable to locate global object.'); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__; +/** + * Attempt to read defaults from a JSON string provided to + * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in + * process(.)env(.)__FIREBASE_DEFAULTS_PATH__ + * The dots are in parens because certain compilers (Vite?) cannot + * handle seeing that variable in comments. + * See https://github.com/firebase/firebase-js-sdk/issues/6838 + */ +const getDefaultsFromEnvVariable = () => { + if (typeof process === 'undefined' || typeof process.env === 'undefined') { + return; + } + const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__; + if (defaultsJsonString) { + return JSON.parse(defaultsJsonString); + } +}; +const getDefaultsFromCookie = () => { + if (typeof document === 'undefined') { + return; + } + let match; + try { + match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/); + } + catch (e) { + // Some environments such as Angular Universal SSR have a + // `document` object but error on accessing `document.cookie`. + return; + } + const decoded = match && base64Decode(match[1]); + return decoded && JSON.parse(decoded); +}; +/** + * Get the __FIREBASE_DEFAULTS__ object. It checks in order: + * (1) if such an object exists as a property of `globalThis` + * (2) if such an object was provided on a shell environment variable + * (3) if such an object exists in a cookie + * @public + */ +const getDefaults = () => { + try { + return (postinstall.getDefaultsFromPostinstall() || + getDefaultsFromGlobal() || + getDefaultsFromEnvVariable() || + getDefaultsFromCookie()); + } + catch (e) { + /** + * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due + * to any environment case we have not accounted for. Log to + * info instead of swallowing so we can find these unknown cases + * and add paths for them if needed. + */ + console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`); + return; + } +}; +/** + * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object + * for the given product. + * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available + * @public + */ +const getDefaultEmulatorHost = (productName) => getDefaults()?.emulatorHosts?.[productName]; +/** + * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object + * for the given product. + * @returns a pair of hostname and port like `["::1", 4000]` if available + * @public + */ +const getDefaultEmulatorHostnameAndPort = (productName) => { + const host = getDefaultEmulatorHost(productName); + if (!host) { + return undefined; + } + const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons. + if (separatorIndex <= 0 || separatorIndex + 1 === host.length) { + throw new Error(`Invalid host ${host} with no separate hostname and port!`); + } + // eslint-disable-next-line no-restricted-globals + const port = parseInt(host.substring(separatorIndex + 1), 10); + if (host[0] === '[') { + // Bracket-quoted `[ipv6addr]:port` => return "ipv6addr" (without brackets). + return [host.substring(1, separatorIndex - 1), port]; + } + else { + return [host.substring(0, separatorIndex), port]; + } +}; +/** + * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object. + * @public + */ +const getDefaultAppConfig = () => getDefaults()?.config; +/** + * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties + * prefixed by "_") + * @public + */ +const getExperimentalSetting = (name) => getDefaults()?.[`_${name}`]; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Deferred { + constructor() { + this.reject = () => { }; + this.resolve = () => { }; + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } + /** + * Our API internals are not promisified and cannot because our callback APIs have subtle expectations around + * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback + * and returns a node-style callback which will resolve or reject the Deferred's promise. + */ + wrapCallback(callback) { + return (error, value) => { + if (error) { + this.reject(error); + } + else { + this.resolve(value); + } + if (typeof callback === 'function') { + // Attaching noop handler just in case developer wasn't expecting + // promises + this.promise.catch(() => { }); + // Some of our callbacks don't expect a value and our own tests + // assert that the parameter length is 1 + if (callback.length === 1) { + callback(error); + } + else { + callback(error, value); + } + } + }; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Checks whether host is a cloud workstation or not. + * @public + */ +function isCloudWorkstation(url) { + // `isCloudWorkstation` is called without protocol in certain connect*Emulator functions + // In HTTP request builders, it's called with the protocol. + // If called with protocol prefix, it's a valid URL, so we extract the hostname + // If called without, we assume the string is the hostname. + try { + const host = url.startsWith('http://') || url.startsWith('https://') + ? new URL(url).hostname + : url; + return host.endsWith('.cloudworkstations.dev'); + } + catch { + return false; + } +} +/** + * Makes a fetch request to the given server. + * Mostly used for forwarding cookies in Firebase Studio. + * @public + */ +async function pingServer(endpoint) { + const result = await fetch(endpoint, { + credentials: 'include' + }); + return result.ok; +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function createMockUserToken(token, projectId) { + if (token.uid) { + throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.'); + } + // Unsecured JWTs use "none" as the algorithm. + const header = { + alg: 'none', + type: 'JWT' + }; + const project = projectId || 'demo-project'; + const iat = token.iat || 0; + const sub = token.sub || token.user_id; + if (!sub) { + throw new Error("mockUserToken must contain 'sub' or 'user_id' field!"); + } + const payload = { + // Set all required fields to decent defaults + iss: `https://securetoken.google.com/${project}`, + aud: project, + iat, + exp: iat + 3600, + auth_time: iat, + sub, + user_id: sub, + firebase: { + sign_in_provider: 'custom', + identities: {} + }, + // Override with user options + ...token + }; + // Unsecured JWTs use the empty string as a signature. + const signature = ''; + return [ + base64urlEncodeWithoutPadding(JSON.stringify(header)), + base64urlEncodeWithoutPadding(JSON.stringify(payload)), + signature + ].join('.'); +} +const emulatorStatus = {}; +// Checks whether any products are running on an emulator +function getEmulatorSummary() { + const summary = { + prod: [], + emulator: [] + }; + for (const key of Object.keys(emulatorStatus)) { + if (emulatorStatus[key]) { + summary.emulator.push(key); + } + else { + summary.prod.push(key); + } + } + return summary; +} +function getOrCreateEl(id) { + let parentDiv = document.getElementById(id); + let created = false; + if (!parentDiv) { + parentDiv = document.createElement('div'); + parentDiv.setAttribute('id', id); + created = true; + } + return { created, element: parentDiv }; +} +let previouslyDismissed = false; +/** + * Updates Emulator Banner. Primarily used for Firebase Studio + * @param name + * @param isRunningEmulator + * @public + */ +function updateEmulatorBanner(name, isRunningEmulator) { + if (typeof window === 'undefined' || + typeof document === 'undefined' || + !isCloudWorkstation(window.location.host) || + emulatorStatus[name] === isRunningEmulator || + emulatorStatus[name] || // If already set to use emulator, can't go back to prod. + previouslyDismissed) { + return; + } + emulatorStatus[name] = isRunningEmulator; + function prefixedId(id) { + return `__firebase__banner__${id}`; + } + const bannerId = '__firebase__banner'; + const summary = getEmulatorSummary(); + const showError = summary.prod.length > 0; + function tearDown() { + const element = document.getElementById(bannerId); + if (element) { + element.remove(); + } + } + function setupBannerStyles(bannerEl) { + bannerEl.style.display = 'flex'; + bannerEl.style.background = '#7faaf0'; + bannerEl.style.position = 'fixed'; + bannerEl.style.bottom = '5px'; + bannerEl.style.left = '5px'; + bannerEl.style.padding = '.5em'; + bannerEl.style.borderRadius = '5px'; + bannerEl.style.alignItems = 'center'; + } + function setupIconStyles(prependIcon, iconId) { + prependIcon.setAttribute('width', '24'); + prependIcon.setAttribute('id', iconId); + prependIcon.setAttribute('height', '24'); + prependIcon.setAttribute('viewBox', '0 0 24 24'); + prependIcon.setAttribute('fill', 'none'); + prependIcon.style.marginLeft = '-6px'; + } + function setupCloseBtn() { + const closeBtn = document.createElement('span'); + closeBtn.style.cursor = 'pointer'; + closeBtn.style.marginLeft = '16px'; + closeBtn.style.fontSize = '24px'; + closeBtn.innerHTML = ' ×'; + closeBtn.onclick = () => { + previouslyDismissed = true; + tearDown(); + }; + return closeBtn; + } + function setupLinkStyles(learnMoreLink, learnMoreId) { + learnMoreLink.setAttribute('id', learnMoreId); + learnMoreLink.innerText = 'Learn more'; + learnMoreLink.href = + 'https://firebase.google.com/docs/studio/preview-apps#preview-backend'; + learnMoreLink.setAttribute('target', '__blank'); + learnMoreLink.style.paddingLeft = '5px'; + learnMoreLink.style.textDecoration = 'underline'; + } + function setupDom() { + const banner = getOrCreateEl(bannerId); + const firebaseTextId = prefixedId('text'); + const firebaseText = document.getElementById(firebaseTextId) || document.createElement('span'); + const learnMoreId = prefixedId('learnmore'); + const learnMoreLink = document.getElementById(learnMoreId) || + document.createElement('a'); + const prependIconId = prefixedId('preprendIcon'); + const prependIcon = document.getElementById(prependIconId) || + document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + if (banner.created) { + // update styles + const bannerEl = banner.element; + setupBannerStyles(bannerEl); + setupLinkStyles(learnMoreLink, learnMoreId); + const closeBtn = setupCloseBtn(); + setupIconStyles(prependIcon, prependIconId); + bannerEl.append(prependIcon, firebaseText, learnMoreLink, closeBtn); + document.body.appendChild(bannerEl); + } + if (showError) { + firebaseText.innerText = `Preview backend disconnected.`; + prependIcon.innerHTML = ` + + + + + + +`; + } + else { + prependIcon.innerHTML = ` + + + + + + +`; + firebaseText.innerText = 'Preview backend running in this workspace.'; + } + firebaseText.setAttribute('id', firebaseTextId); + } + if (document.readyState === 'loading') { + window.addEventListener('DOMContentLoaded', setupDom); + } + else { + setupDom(); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns navigator.userAgent string or '' if it's not defined. + * @return user agent string + */ +function getUA() { + if (typeof navigator !== 'undefined' && + typeof navigator['userAgent'] === 'string') { + return navigator['userAgent']; + } + else { + return ''; + } +} +/** + * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device. + * + * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap + * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally + * wait for a callback. + */ +function isMobileCordova() { + return (typeof window !== 'undefined' && + // @ts-ignore Setting up an broadly applicable index signature for Window + // just to deal with this case would probably be a bad idea. + !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) && + /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())); +} +/** + * Detect Node.js. + * + * @return true if Node.js environment is detected or specified. + */ +// Node detection logic from: https://github.com/iliakan/detect-node/ +function isNode() { + const forceEnvironment = getDefaults()?.forceEnvironment; + if (forceEnvironment === 'node') { + return true; + } + else if (forceEnvironment === 'browser') { + return false; + } + try { + return (Object.prototype.toString.call(global.process) === '[object process]'); + } + catch (e) { + return false; + } +} +/** + * Detect Browser Environment. + * Note: This will return true for certain test frameworks that are incompletely + * mimicking a browser, and should not lead to assuming all browser APIs are + * available. + */ +function isBrowser() { + return typeof window !== 'undefined' || isWebWorker(); +} +/** + * Detect Web Worker context. + */ +function isWebWorker() { + return (typeof WorkerGlobalScope !== 'undefined' && + typeof self !== 'undefined' && + self instanceof WorkerGlobalScope); +} +/** + * Detect Cloudflare Worker context. + */ +function isCloudflareWorker() { + return (typeof navigator !== 'undefined' && + navigator.userAgent === 'Cloudflare-Workers'); +} +function isBrowserExtension() { + const runtime = typeof chrome === 'object' + ? chrome.runtime + : typeof browser === 'object' + ? browser.runtime + : undefined; + return typeof runtime === 'object' && runtime.id !== undefined; +} +/** + * Detect React Native. + * + * @return true if ReactNative environment is detected. + */ +function isReactNative() { + return (typeof navigator === 'object' && navigator['product'] === 'ReactNative'); +} +/** Detects Electron apps. */ +function isElectron() { + return getUA().indexOf('Electron/') >= 0; +} +/** Detects Internet Explorer. */ +function isIE() { + const ua = getUA(); + return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0; +} +/** Detects Universal Windows Platform apps. */ +function isUWP() { + return getUA().indexOf('MSAppHost/') >= 0; +} +/** + * Detect whether the current SDK build is the Node version. + * + * @return true if it's the Node SDK build. + */ +function isNodeSdk() { + return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true; +} +/** Returns true if we are running in Safari. */ +function isSafari() { + return (!isNode() && + !!navigator.userAgent && + navigator.userAgent.includes('Safari') && + !navigator.userAgent.includes('Chrome')); +} +/** Returns true if we are running in Safari or WebKit */ +function isSafariOrWebkit() { + return (!isNode() && + !!navigator.userAgent && + (navigator.userAgent.includes('Safari') || + navigator.userAgent.includes('WebKit')) && + !navigator.userAgent.includes('Chrome')); +} +/** + * This method checks if indexedDB is supported by current browser/service worker context + * @return true if indexedDB is supported by current browser/service worker context + */ +function isIndexedDBAvailable() { + try { + return typeof indexedDB === 'object'; + } + catch (e) { + return false; + } +} +/** + * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject + * if errors occur during the database open operation. + * + * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox + * private browsing) + */ +function validateIndexedDBOpenable() { + return new Promise((resolve, reject) => { + try { + let preExist = true; + const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module'; + const request = self.indexedDB.open(DB_CHECK_NAME); + request.onsuccess = () => { + request.result.close(); + // delete database only when it doesn't pre-exist + if (!preExist) { + self.indexedDB.deleteDatabase(DB_CHECK_NAME); + } + resolve(true); + }; + request.onupgradeneeded = () => { + preExist = false; + }; + request.onerror = () => { + reject(request.error?.message || ''); + }; + } + catch (error) { + reject(error); + } + }); +} +/** + * + * This method checks whether cookie is enabled within current browser + * @return true if cookie is enabled within current browser + */ +function areCookiesEnabled() { + if (typeof navigator === 'undefined' || !navigator.cookieEnabled) { + return false; + } + return true; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview Standardized Firebase Error. + * + * Usage: + * + * // TypeScript string literals for type-safe codes + * type Err = + * 'unknown' | + * 'object-not-found' + * ; + * + * // Closure enum for type-safe error codes + * // at-enum {string} + * var Err = { + * UNKNOWN: 'unknown', + * OBJECT_NOT_FOUND: 'object-not-found', + * } + * + * let errors: Map = { + * 'generic-error': "Unknown error", + * 'file-not-found': "Could not find file: {$file}", + * }; + * + * // Type-safe function - must pass a valid error code as param. + * let error = new ErrorFactory('service', 'Service', errors); + * + * ... + * throw error.create(Err.GENERIC); + * ... + * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName}); + * ... + * // Service: Could not file file: foo.txt (service/file-not-found). + * + * catch (e) { + * assert(e.message === "Could not find file: foo.txt."); + * if ((e as FirebaseError)?.code === 'service/file-not-found') { + * console.log("Could not read file: " + e['file']); + * } + * } + */ +const ERROR_NAME = 'FirebaseError'; +// Based on code from: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types +class FirebaseError extends Error { + constructor( + /** The error code for this error. */ + code, message, + /** Custom data for this error. */ + customData) { + super(message); + this.code = code; + this.customData = customData; + /** The custom name for all FirebaseErrors. */ + this.name = ERROR_NAME; + // Fix For ES5 + // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work + // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget + // which we can now use since we no longer target ES5. + Object.setPrototypeOf(this, FirebaseError.prototype); + // Maintains proper stack trace for where our error was thrown. + // Only available on V8. + if (Error.captureStackTrace) { + Error.captureStackTrace(this, ErrorFactory.prototype.create); + } + } +} +class ErrorFactory { + constructor(service, serviceName, errors) { + this.service = service; + this.serviceName = serviceName; + this.errors = errors; + } + create(code, ...data) { + const customData = data[0] || {}; + const fullCode = `${this.service}/${code}`; + const template = this.errors[code]; + const message = template ? replaceTemplate(template, customData) : 'Error'; + // Service Name: Error message (service/code). + const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`; + const error = new FirebaseError(fullCode, fullMessage, customData); + return error; + } +} +function replaceTemplate(template, data) { + return template.replace(PATTERN, (_, key) => { + const value = data[key]; + return value != null ? String(value) : `<${key}?>`; + }); +} +const PATTERN = /\{\$([^}]+)}/g; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Evaluates a JSON string into a javascript object. + * + * @param {string} str A string containing JSON. + * @return {*} The javascript object representing the specified JSON. + */ +function jsonEval(str) { + return JSON.parse(str); +} +/** + * Returns JSON representing a javascript object. + * @param {*} data JavaScript object to be stringified. + * @return {string} The JSON contents of the object. + */ +function stringify(data) { + return JSON.stringify(data); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Decodes a Firebase auth. token into constituent parts. + * + * Notes: + * - May return with invalid / incomplete claims if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +const decode = function (token) { + let header = {}, claims = {}, data = {}, signature = ''; + try { + const parts = token.split('.'); + header = jsonEval(base64Decode(parts[0]) || ''); + claims = jsonEval(base64Decode(parts[1]) || ''); + signature = parts[2]; + data = claims['d'] || {}; + delete claims['d']; + } + catch (e) { } + return { + header, + claims, + data, + signature + }; +}; +/** + * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the + * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +const isValidTimestamp = function (token) { + const claims = decode(token).claims; + const now = Math.floor(new Date().getTime() / 1000); + let validSince = 0, validUntil = 0; + if (typeof claims === 'object') { + if (claims.hasOwnProperty('nbf')) { + validSince = claims['nbf']; + } + else if (claims.hasOwnProperty('iat')) { + validSince = claims['iat']; + } + if (claims.hasOwnProperty('exp')) { + validUntil = claims['exp']; + } + else { + // token will expire after 24h by default + validUntil = validSince + 86400; + } + } + return (!!now && + !!validSince && + !!validUntil && + now >= validSince && + now <= validUntil); +}; +/** + * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise. + * + * Notes: + * - May return null if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +const issuedAtTime = function (token) { + const claims = decode(token).claims; + if (typeof claims === 'object' && claims.hasOwnProperty('iat')) { + return claims['iat']; + } + return null; +}; +/** + * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +const isValidFormat = function (token) { + const decoded = decode(token), claims = decoded.claims; + return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat'); +}; +/** + * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +const isAdmin = function (token) { + const claims = decode(token).claims; + return typeof claims === 'object' && claims['admin'] === true; +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function contains(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +function safeGet(obj, key) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + return obj[key]; + } + else { + return undefined; + } +} +function isEmpty(obj) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + return false; + } + } + return true; +} +function map(obj, fn, contextObj) { + const res = {}; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + res[key] = fn.call(contextObj, obj[key], key, obj); + } + } + return res; +} +/** + * Deep equal two objects. Support Arrays and Objects. + */ +function deepEqual(a, b) { + if (a === b) { + return true; + } + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + for (const k of aKeys) { + if (!bKeys.includes(k)) { + return false; + } + const aProp = a[k]; + const bProp = b[k]; + if (isObject(aProp) && isObject(bProp)) { + if (!deepEqual(aProp, bProp)) { + return false; + } + } + else if (aProp !== bProp) { + return false; + } + } + for (const k of bKeys) { + if (!aKeys.includes(k)) { + return false; + } + } + return true; +} +function isObject(thing) { + return thing !== null && typeof thing === 'object'; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Rejects if the given promise doesn't resolve in timeInMS milliseconds. + * @internal + */ +function promiseWithTimeout(promise, timeInMS = 2000) { + const deferredPromise = new Deferred(); + setTimeout(() => deferredPromise.reject('timeout!'), timeInMS); + promise.then(deferredPromise.resolve, deferredPromise.reject); + return deferredPromise.promise; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a + * params object (e.g. {arg: 'val', arg2: 'val2'}) + * Note: You must prepend it with ? when adding it to a URL. + */ +function querystring(querystringParams) { + const params = []; + for (const [key, value] of Object.entries(querystringParams)) { + if (Array.isArray(value)) { + value.forEach(arrayVal => { + params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal)); + }); + } + else { + params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); + } + } + return params.length ? '&' + params.join('&') : ''; +} +/** + * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object + * (e.g. {arg: 'val', arg2: 'val2'}) + */ +function querystringDecode(querystring) { + const obj = {}; + const tokens = querystring.replace(/^\?/, '').split('&'); + tokens.forEach(token => { + if (token) { + const [key, value] = token.split('='); + obj[decodeURIComponent(key)] = decodeURIComponent(value); + } + }); + return obj; +} +/** + * Extract the query string part of a URL, including the leading question mark (if present). + */ +function extractQuerystring(url) { + const queryStart = url.indexOf('?'); + if (!queryStart) { + return ''; + } + const fragmentStart = url.indexOf('#', queryStart); + return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview SHA-1 cryptographic hash. + * Variable names follow the notation in FIPS PUB 180-3: + * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf. + * + * Usage: + * var sha1 = new sha1(); + * sha1.update(bytes); + * var hash = sha1.digest(); + * + * Performance: + * Chrome 23: ~400 Mbit/s + * Firefox 16: ~250 Mbit/s + * + */ +/** + * SHA-1 cryptographic hash constructor. + * + * The properties declared here are discussed in the above algorithm document. + * @constructor + * @final + * @struct + */ +class Sha1 { + constructor() { + /** + * Holds the previous values of accumulated variables a-e in the compress_ + * function. + * @private + */ + this.chain_ = []; + /** + * A buffer holding the partially computed hash result. + * @private + */ + this.buf_ = []; + /** + * An array of 80 bytes, each a part of the message to be hashed. Referred to + * as the message schedule in the docs. + * @private + */ + this.W_ = []; + /** + * Contains data needed to pad messages less than 64 bytes. + * @private + */ + this.pad_ = []; + /** + * @private {number} + */ + this.inbuf_ = 0; + /** + * @private {number} + */ + this.total_ = 0; + this.blockSize = 512 / 8; + this.pad_[0] = 128; + for (let i = 1; i < this.blockSize; ++i) { + this.pad_[i] = 0; + } + this.reset(); + } + reset() { + this.chain_[0] = 0x67452301; + this.chain_[1] = 0xefcdab89; + this.chain_[2] = 0x98badcfe; + this.chain_[3] = 0x10325476; + this.chain_[4] = 0xc3d2e1f0; + this.inbuf_ = 0; + this.total_ = 0; + } + /** + * Internal compress helper function. + * @param buf Block to compress. + * @param offset Offset of the block in the buffer. + * @private + */ + compress_(buf, offset) { + if (!offset) { + offset = 0; + } + const W = this.W_; + // get 16 big endian words + if (typeof buf === 'string') { + for (let i = 0; i < 16; i++) { + // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS + // have a bug that turns the post-increment ++ operator into pre-increment + // during JIT compilation. We have code that depends heavily on SHA-1 for + // correctness and which is affected by this bug, so I've removed all uses + // of post-increment ++ in which the result value is used. We can revert + // this change once the Safari bug + // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and + // most clients have been updated. + W[i] = + (buf.charCodeAt(offset) << 24) | + (buf.charCodeAt(offset + 1) << 16) | + (buf.charCodeAt(offset + 2) << 8) | + buf.charCodeAt(offset + 3); + offset += 4; + } + } + else { + for (let i = 0; i < 16; i++) { + W[i] = + (buf[offset] << 24) | + (buf[offset + 1] << 16) | + (buf[offset + 2] << 8) | + buf[offset + 3]; + offset += 4; + } + } + // expand to 80 words + for (let i = 16; i < 80; i++) { + const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff; + } + let a = this.chain_[0]; + let b = this.chain_[1]; + let c = this.chain_[2]; + let d = this.chain_[3]; + let e = this.chain_[4]; + let f, k; + // TODO(user): Try to unroll this loop to speed up the computation. + for (let i = 0; i < 80; i++) { + if (i < 40) { + if (i < 20) { + f = d ^ (b & (c ^ d)); + k = 0x5a827999; + } + else { + f = b ^ c ^ d; + k = 0x6ed9eba1; + } + } + else { + if (i < 60) { + f = (b & c) | (d & (b | c)); + k = 0x8f1bbcdc; + } + else { + f = b ^ c ^ d; + k = 0xca62c1d6; + } + } + const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff; + e = d; + d = c; + c = ((b << 30) | (b >>> 2)) & 0xffffffff; + b = a; + a = t; + } + this.chain_[0] = (this.chain_[0] + a) & 0xffffffff; + this.chain_[1] = (this.chain_[1] + b) & 0xffffffff; + this.chain_[2] = (this.chain_[2] + c) & 0xffffffff; + this.chain_[3] = (this.chain_[3] + d) & 0xffffffff; + this.chain_[4] = (this.chain_[4] + e) & 0xffffffff; + } + update(bytes, length) { + // TODO(johnlenz): tighten the function signature and remove this check + if (bytes == null) { + return; + } + if (length === undefined) { + length = bytes.length; + } + const lengthMinusBlock = length - this.blockSize; + let n = 0; + // Using local instead of member variables gives ~5% speedup on Firefox 16. + const buf = this.buf_; + let inbuf = this.inbuf_; + // The outer while loop should execute at most twice. + while (n < length) { + // When we have no data in the block to top up, we can directly process the + // input buffer (assuming it contains sufficient data). This gives ~25% + // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that + // the data is provided in large chunks (or in multiples of 64 bytes). + if (inbuf === 0) { + while (n <= lengthMinusBlock) { + this.compress_(bytes, n); + n += this.blockSize; + } + } + if (typeof bytes === 'string') { + while (n < length) { + buf[inbuf] = bytes.charCodeAt(n); + ++inbuf; + ++n; + if (inbuf === this.blockSize) { + this.compress_(buf); + inbuf = 0; + // Jump to the outer loop so we use the full-block optimization. + break; + } + } + } + else { + while (n < length) { + buf[inbuf] = bytes[n]; + ++inbuf; + ++n; + if (inbuf === this.blockSize) { + this.compress_(buf); + inbuf = 0; + // Jump to the outer loop so we use the full-block optimization. + break; + } + } + } + } + this.inbuf_ = inbuf; + this.total_ += length; + } + /** @override */ + digest() { + const digest = []; + let totalBits = this.total_ * 8; + // Add pad 0x80 0x00*. + if (this.inbuf_ < 56) { + this.update(this.pad_, 56 - this.inbuf_); + } + else { + this.update(this.pad_, this.blockSize - (this.inbuf_ - 56)); + } + // Add # bits. + for (let i = this.blockSize - 1; i >= 56; i--) { + this.buf_[i] = totalBits & 255; + totalBits /= 256; // Don't use bit-shifting here! + } + this.compress_(this.buf_); + let n = 0; + for (let i = 0; i < 5; i++) { + for (let j = 24; j >= 0; j -= 8) { + digest[n] = (this.chain_[i] >> j) & 255; + ++n; + } + } + return digest; + } +} + +/** + * Helper to make a Subscribe function (just like Promise helps make a + * Thenable). + * + * @param executor Function which can make calls to a single Observer + * as a proxy. + * @param onNoObservers Callback when count of Observers goes to zero. + */ +function createSubscribe(executor, onNoObservers) { + const proxy = new ObserverProxy(executor, onNoObservers); + return proxy.subscribe.bind(proxy); +} +/** + * Implement fan-out for any number of Observers attached via a subscribe + * function. + */ +class ObserverProxy { + /** + * @param executor Function which can make calls to a single Observer + * as a proxy. + * @param onNoObservers Callback when count of Observers goes to zero. + */ + constructor(executor, onNoObservers) { + this.observers = []; + this.unsubscribes = []; + this.observerCount = 0; + // Micro-task scheduling by calling task.then(). + this.task = Promise.resolve(); + this.finalized = false; + this.onNoObservers = onNoObservers; + // Call the executor asynchronously so subscribers that are called + // synchronously after the creation of the subscribe function + // can still receive the very first value generated in the executor. + this.task + .then(() => { + executor(this); + }) + .catch(e => { + this.error(e); + }); + } + next(value) { + this.forEachObserver((observer) => { + observer.next(value); + }); + } + error(error) { + this.forEachObserver((observer) => { + observer.error(error); + }); + this.close(error); + } + complete() { + this.forEachObserver((observer) => { + observer.complete(); + }); + this.close(); + } + /** + * Subscribe function that can be used to add an Observer to the fan-out list. + * + * - We require that no event is sent to a subscriber synchronously to their + * call to subscribe(). + */ + subscribe(nextOrObserver, error, complete) { + let observer; + if (nextOrObserver === undefined && + error === undefined && + complete === undefined) { + throw new Error('Missing Observer.'); + } + // Assemble an Observer object when passed as callback functions. + if (implementsAnyMethods(nextOrObserver, [ + 'next', + 'error', + 'complete' + ])) { + observer = nextOrObserver; + } + else { + observer = { + next: nextOrObserver, + error, + complete + }; + } + if (observer.next === undefined) { + observer.next = noop; + } + if (observer.error === undefined) { + observer.error = noop; + } + if (observer.complete === undefined) { + observer.complete = noop; + } + const unsub = this.unsubscribeOne.bind(this, this.observers.length); + // Attempt to subscribe to a terminated Observable - we + // just respond to the Observer with the final error or complete + // event. + if (this.finalized) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.task.then(() => { + try { + if (this.finalError) { + observer.error(this.finalError); + } + else { + observer.complete(); + } + } + catch (e) { + // nothing + } + return; + }); + } + this.observers.push(observer); + return unsub; + } + // Unsubscribe is synchronous - we guarantee that no events are sent to + // any unsubscribed Observer. + unsubscribeOne(i) { + if (this.observers === undefined || this.observers[i] === undefined) { + return; + } + delete this.observers[i]; + this.observerCount -= 1; + if (this.observerCount === 0 && this.onNoObservers !== undefined) { + this.onNoObservers(this); + } + } + forEachObserver(fn) { + if (this.finalized) { + // Already closed by previous event....just eat the additional values. + return; + } + // Since sendOne calls asynchronously - there is no chance that + // this.observers will become undefined. + for (let i = 0; i < this.observers.length; i++) { + this.sendOne(i, fn); + } + } + // Call the Observer via one of it's callback function. We are careful to + // confirm that the observe has not been unsubscribed since this asynchronous + // function had been queued. + sendOne(i, fn) { + // Execute the callback asynchronously + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.task.then(() => { + if (this.observers !== undefined && this.observers[i] !== undefined) { + try { + fn(this.observers[i]); + } + catch (e) { + // Ignore exceptions raised in Observers or missing methods of an + // Observer. + // Log error to console. b/31404806 + if (typeof console !== 'undefined' && console.error) { + console.error(e); + } + } + } + }); + } + close(err) { + if (this.finalized) { + return; + } + this.finalized = true; + if (err !== undefined) { + this.finalError = err; + } + // Proxy is no longer needed - garbage collect references + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.task.then(() => { + this.observers = undefined; + this.onNoObservers = undefined; + }); + } +} +/** Turn synchronous function into one called asynchronously. */ +// eslint-disable-next-line @typescript-eslint/ban-types +function async(fn, onError) { + return (...args) => { + Promise.resolve(true) + .then(() => { + fn(...args); + }) + .catch((error) => { + if (onError) { + onError(error); + } + }); + }; +} +/** + * Return true if the object passed in implements any of the named methods. + */ +function implementsAnyMethods(obj, methods) { + if (typeof obj !== 'object' || obj === null) { + return false; + } + for (const method of methods) { + if (method in obj && typeof obj[method] === 'function') { + return true; + } + } + return false; +} +function noop() { + // do nothing +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Check to make sure the appropriate number of arguments are provided for a public function. + * Throws an error if it fails. + * + * @param fnName The function name + * @param minCount The minimum number of arguments to allow for the function call + * @param maxCount The maximum number of argument to allow for the function call + * @param argCount The actual number of arguments provided. + */ +const validateArgCount = function (fnName, minCount, maxCount, argCount) { + let argError; + if (argCount < minCount) { + argError = 'at least ' + minCount; + } + else if (argCount > maxCount) { + argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount; + } + if (argError) { + const error = fnName + + ' failed: Was called with ' + + argCount + + (argCount === 1 ? ' argument.' : ' arguments.') + + ' Expects ' + + argError + + '.'; + throw new Error(error); + } +}; +/** + * Generates a string to prefix an error message about failed argument validation + * + * @param fnName The function name + * @param argName The name of the argument + * @return The prefix to add to the error thrown for validation. + */ +function errorPrefix(fnName, argName) { + return `${fnName} failed: ${argName} argument `; +} +/** + * @param fnName + * @param argumentNumber + * @param namespace + * @param optional + */ +function validateNamespace(fnName, namespace, optional) { + if (optional && !namespace) { + return; + } + if (typeof namespace !== 'string') { + //TODO: I should do more validation here. We only allow certain chars in namespaces. + throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.'); + } +} +function validateCallback(fnName, argumentName, +// eslint-disable-next-line @typescript-eslint/ban-types +callback, optional) { + if (optional && !callback) { + return; + } + if (typeof callback !== 'function') { + throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.'); + } +} +function validateContextObject(fnName, argumentName, context, optional) { + if (optional && !context) { + return; + } + if (typeof context !== 'object' || context === null) { + throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they +// automatically replaced '\r\n' with '\n', and they didn't handle surrogate pairs, +// so it's been modified. +// Note that not all Unicode characters appear as single characters in JavaScript strings. +// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters +// use 2 characters in JavaScript. All 4-byte UTF-8 characters begin with a first +// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate +// pair). +// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3 +/** + * @param {string} str + * @return {Array} + */ +const stringToByteArray = function (str) { + const out = []; + let p = 0; + for (let i = 0; i < str.length; i++) { + let c = str.charCodeAt(i); + // Is this the lead surrogate in a surrogate pair? + if (c >= 0xd800 && c <= 0xdbff) { + const high = c - 0xd800; // the high 10 bits. + i++; + assert(i < str.length, 'Surrogate pair missing trail surrogate.'); + const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits. + c = 0x10000 + (high << 10) + low; + } + if (c < 128) { + out[p++] = c; + } + else if (c < 2048) { + out[p++] = (c >> 6) | 192; + out[p++] = (c & 63) | 128; + } + else if (c < 65536) { + out[p++] = (c >> 12) | 224; + out[p++] = ((c >> 6) & 63) | 128; + out[p++] = (c & 63) | 128; + } + else { + out[p++] = (c >> 18) | 240; + out[p++] = ((c >> 12) & 63) | 128; + out[p++] = ((c >> 6) & 63) | 128; + out[p++] = (c & 63) | 128; + } + } + return out; +}; +/** + * Calculate length without actually converting; useful for doing cheaper validation. + * @param {string} str + * @return {number} + */ +const stringLength = function (str) { + let p = 0; + for (let i = 0; i < str.length; i++) { + const c = str.charCodeAt(i); + if (c < 128) { + p++; + } + else if (c < 2048) { + p += 2; + } + else if (c >= 0xd800 && c <= 0xdbff) { + // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent. + p += 4; + i++; // skip trail surrogate. + } + else { + p += 3; + } + } + return p; +}; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The amount of milliseconds to exponentially increase. + */ +const DEFAULT_INTERVAL_MILLIS = 1000; +/** + * The factor to backoff by. + * Should be a number greater than 1. + */ +const DEFAULT_BACKOFF_FACTOR = 2; +/** + * The maximum milliseconds to increase to. + * + *

Visible for testing + */ +const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android. +/** + * The percentage of backoff time to randomize by. + * See + * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic + * for context. + * + *

Visible for testing + */ +const RANDOM_FACTOR = 0.5; +/** + * Based on the backoff method from + * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js. + * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around. + */ +function calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) { + // Calculates an exponentially increasing value. + // Deviation: calculates value from count and a constant interval, so we only need to save value + // and count to restore state. + const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount); + // A random "fuzz" to avoid waves of retries. + // Deviation: randomFactor is required. + const randomWait = Math.round( + // A fraction of the backoff value to add/subtract. + // Deviation: changes multiplication order to improve readability. + RANDOM_FACTOR * + currBaseValue * + // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines + // if we add or subtract. + (Math.random() - 0.5) * + 2); + // Limits backoff to max to avoid effectively permanent backoff. + return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provide English ordinal letters after a number + */ +function ordinal(i) { + if (!Number.isFinite(i)) { + return `${i}`; + } + return i + indicator(i); +} +function indicator(i) { + i = Math.abs(i); + const cent = i % 100; + if (cent >= 10 && cent <= 20) { + return 'th'; + } + const dec = i % 10; + if (dec === 1) { + return 'st'; + } + if (dec === 2) { + return 'nd'; + } + if (dec === 3) { + return 'rd'; + } + return 'th'; +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function getModularInstance(service) { + if (service && service._delegate) { + return service._delegate; + } + else { + return service; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Overriding the constant (we should be the only ones doing this) +CONSTANTS.NODE_CLIENT = true; + +exports.CONSTANTS = CONSTANTS; +exports.DecodeBase64StringError = DecodeBase64StringError; +exports.Deferred = Deferred; +exports.ErrorFactory = ErrorFactory; +exports.FirebaseError = FirebaseError; +exports.MAX_VALUE_MILLIS = MAX_VALUE_MILLIS; +exports.RANDOM_FACTOR = RANDOM_FACTOR; +exports.Sha1 = Sha1; +exports.areCookiesEnabled = areCookiesEnabled; +exports.assert = assert; +exports.assertionError = assertionError; +exports.async = async; +exports.base64 = base64; +exports.base64Decode = base64Decode; +exports.base64Encode = base64Encode; +exports.base64urlEncodeWithoutPadding = base64urlEncodeWithoutPadding; +exports.calculateBackoffMillis = calculateBackoffMillis; +exports.contains = contains; +exports.createMockUserToken = createMockUserToken; +exports.createSubscribe = createSubscribe; +exports.decode = decode; +exports.deepCopy = deepCopy; +exports.deepEqual = deepEqual; +exports.deepExtend = deepExtend; +exports.errorPrefix = errorPrefix; +exports.extractQuerystring = extractQuerystring; +exports.getDefaultAppConfig = getDefaultAppConfig; +exports.getDefaultEmulatorHost = getDefaultEmulatorHost; +exports.getDefaultEmulatorHostnameAndPort = getDefaultEmulatorHostnameAndPort; +exports.getDefaults = getDefaults; +exports.getExperimentalSetting = getExperimentalSetting; +exports.getGlobal = getGlobal; +exports.getModularInstance = getModularInstance; +exports.getUA = getUA; +exports.isAdmin = isAdmin; +exports.isBrowser = isBrowser; +exports.isBrowserExtension = isBrowserExtension; +exports.isCloudWorkstation = isCloudWorkstation; +exports.isCloudflareWorker = isCloudflareWorker; +exports.isElectron = isElectron; +exports.isEmpty = isEmpty; +exports.isIE = isIE; +exports.isIndexedDBAvailable = isIndexedDBAvailable; +exports.isMobileCordova = isMobileCordova; +exports.isNode = isNode; +exports.isNodeSdk = isNodeSdk; +exports.isReactNative = isReactNative; +exports.isSafari = isSafari; +exports.isSafariOrWebkit = isSafariOrWebkit; +exports.isUWP = isUWP; +exports.isValidFormat = isValidFormat; +exports.isValidTimestamp = isValidTimestamp; +exports.isWebWorker = isWebWorker; +exports.issuedAtTime = issuedAtTime; +exports.jsonEval = jsonEval; +exports.map = map; +exports.ordinal = ordinal; +exports.pingServer = pingServer; +exports.promiseWithTimeout = promiseWithTimeout; +exports.querystring = querystring; +exports.querystringDecode = querystringDecode; +exports.safeGet = safeGet; +exports.stringLength = stringLength; +exports.stringToByteArray = stringToByteArray; +exports.stringify = stringify; +exports.updateEmulatorBanner = updateEmulatorBanner; +exports.validateArgCount = validateArgCount; +exports.validateCallback = validateCallback; +exports.validateContextObject = validateContextObject; +exports.validateIndexedDBOpenable = validateIndexedDBOpenable; +exports.validateNamespace = validateNamespace; +//# sourceMappingURL=index.node.cjs.js.map diff --git a/node_modules/@firebase/util/dist/index.node.cjs.js.map b/node_modules/@firebase/util/dist/index.node.cjs.js.map new file mode 100644 index 0000000..16f0121 --- /dev/null +++ b/node_modules/@firebase/util/dist/index.node.cjs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.node.cjs.js","sources":["../src/constants.ts","../src/assert.ts","../src/crypt.ts","../src/deepCopy.ts","../src/global.ts","../src/defaults.ts","../src/deferred.ts","../src/url.ts","../src/emulator.ts","../src/environment.ts","../src/errors.ts","../src/json.ts","../src/jwt.ts","../src/obj.ts","../src/promise.ts","../src/query.ts","../src/sha1.ts","../src/subscribe.ts","../src/validation.ts","../src/utf8.ts","../src/exponential_backoff.ts","../src/formatters.ts","../src/compat.ts","../index.node.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\n */\n\nexport const CONSTANTS = {\n /**\n * @define {boolean} Whether this is the client Node.js SDK.\n */\n NODE_CLIENT: false,\n /**\n * @define {boolean} Whether this is the Admin Node.js SDK.\n */\n NODE_ADMIN: false,\n\n /**\n * Firebase SDK Version\n */\n SDK_VERSION: '${JSCORE_VERSION}'\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSTANTS } from './constants';\n\n/**\n * Throws an error if the provided assertion is falsy\n */\nexport const assert = function (assertion: unknown, message: string): void {\n if (!assertion) {\n throw assertionError(message);\n }\n};\n\n/**\n * Returns an Error object suitable for throwing.\n */\nexport const assertionError = function (message: string): Error {\n return new Error(\n 'Firebase Database (' +\n CONSTANTS.SDK_VERSION +\n ') INTERNAL ASSERT FAILED: ' +\n message\n );\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst stringToByteArray = function (str: string): number[] {\n // TODO(user): Use native implementations if/when available\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (\n (c & 0xfc00) === 0xd800 &&\n i + 1 < str.length &&\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00\n ) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param bytes Array of numbers representing characters.\n * @return Stringification of the array.\n */\nconst byteArrayToString = function (bytes: number[]): string {\n // TODO(user): Use native implementations if/when available\n const out: string[] = [];\n let pos = 0,\n c = 0;\n while (pos < bytes.length) {\n const c1 = bytes[pos++];\n if (c1 < 128) {\n out[c++] = String.fromCharCode(c1);\n } else if (c1 > 191 && c1 < 224) {\n const c2 = bytes[pos++];\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n } else if (c1 > 239 && c1 < 365) {\n // Surrogate Pair\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n const c4 = bytes[pos++];\n const u =\n (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n 0x10000;\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n } else {\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n out[c++] = String.fromCharCode(\n ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)\n );\n }\n }\n return out.join('');\n};\n\ninterface Base64 {\n byteToCharMap_: { [key: number]: string } | null;\n charToByteMap_: { [key: string]: number } | null;\n byteToCharMapWebSafe_: { [key: number]: string } | null;\n charToByteMapWebSafe_: { [key: string]: number } | null;\n ENCODED_VALS_BASE: string;\n readonly ENCODED_VALS: string;\n readonly ENCODED_VALS_WEBSAFE: string;\n HAS_NATIVE_SUPPORT: boolean;\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string;\n encodeString(input: string, webSafe?: boolean): string;\n decodeString(input: string, webSafe: boolean): string;\n decodeStringToByteArray(input: string, webSafe: boolean): number[];\n init_(): void;\n}\n\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\n// Static lookup maps, lazily populated by init_()\n// TODO(dlarocque): Define this as a class, since we no longer target ES5.\nexport const base64: Base64 = {\n /**\n * Maps bytes to characters.\n */\n byteToCharMap_: null,\n\n /**\n * Maps characters to bytes.\n */\n charToByteMap_: null,\n\n /**\n * Maps bytes to websafe characters.\n * @private\n */\n byteToCharMapWebSafe_: null,\n\n /**\n * Maps websafe characters to bytes.\n * @private\n */\n charToByteMapWebSafe_: null,\n\n /**\n * Our default alphabet, shared between\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n */\n ENCODED_VALS_BASE:\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n\n /**\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n */\n get ENCODED_VALS() {\n return this.ENCODED_VALS_BASE + '+/=';\n },\n\n /**\n * Our websafe alphabet.\n */\n get ENCODED_VALS_WEBSAFE() {\n return this.ENCODED_VALS_BASE + '-_.';\n },\n\n /**\n * Whether this browser supports the atob and btoa functions. This extension\n * started at Mozilla but is now implemented by many browsers. We use the\n * ASSUME_* variables to avoid pulling in the full useragent detection library\n * but still allowing the standard per-browser compilations.\n *\n */\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\n\n /**\n * Base64-encode an array of bytes.\n *\n * @param input An array of bytes (numbers with\n * value in [0, 255]) to encode.\n * @param webSafe Boolean indicating we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string {\n if (!Array.isArray(input)) {\n throw Error('encodeByteArray takes an array as a parameter');\n }\n\n this.init_();\n\n const byteToCharMap = webSafe\n ? this.byteToCharMapWebSafe_!\n : this.byteToCharMap_!;\n\n const output = [];\n\n for (let i = 0; i < input.length; i += 3) {\n const byte1 = input[i];\n const haveByte2 = i + 1 < input.length;\n const byte2 = haveByte2 ? input[i + 1] : 0;\n const haveByte3 = i + 2 < input.length;\n const byte3 = haveByte3 ? input[i + 2] : 0;\n\n const outByte1 = byte1 >> 2;\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n let outByte4 = byte3 & 0x3f;\n\n if (!haveByte3) {\n outByte4 = 64;\n\n if (!haveByte2) {\n outByte3 = 64;\n }\n }\n\n output.push(\n byteToCharMap[outByte1],\n byteToCharMap[outByte2],\n byteToCharMap[outByte3],\n byteToCharMap[outByte4]\n );\n }\n\n return output.join('');\n },\n\n /**\n * Base64-encode a string.\n *\n * @param input A string to encode.\n * @param webSafe If true, we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeString(input: string, webSafe?: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return btoa(input);\n }\n return this.encodeByteArray(stringToByteArray(input), webSafe);\n },\n\n /**\n * Base64-decode a string.\n *\n * @param input to decode.\n * @param webSafe True if we should use the\n * alternative alphabet.\n * @return string representing the decoded value.\n */\n decodeString(input: string, webSafe: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return atob(input);\n }\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\n },\n\n /**\n * Base64-decode a string.\n *\n * In base-64 decoding, groups of four characters are converted into three\n * bytes. If the encoder did not apply padding, the input length may not\n * be a multiple of 4.\n *\n * In this case, the last group will have fewer than 4 characters, and\n * padding will be inferred. If the group has one or two characters, it decodes\n * to one byte. If the group has three characters, it decodes to two bytes.\n *\n * @param input Input to decode.\n * @param webSafe True if we should use the web-safe alphabet.\n * @return bytes representing the decoded value.\n */\n decodeStringToByteArray(input: string, webSafe: boolean): number[] {\n this.init_();\n\n const charToByteMap = webSafe\n ? this.charToByteMapWebSafe_!\n : this.charToByteMap_!;\n\n const output: number[] = [];\n\n for (let i = 0; i < input.length; ) {\n const byte1 = charToByteMap[input.charAt(i++)];\n\n const haveByte2 = i < input.length;\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n ++i;\n\n const haveByte3 = i < input.length;\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n const haveByte4 = i < input.length;\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n throw new DecodeBase64StringError();\n }\n\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\n output.push(outByte1);\n\n if (byte3 !== 64) {\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n output.push(outByte2);\n\n if (byte4 !== 64) {\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n output.push(outByte3);\n }\n }\n }\n\n return output;\n },\n\n /**\n * Lazy static initialization function. Called before\n * accessing any of the static map variables.\n * @private\n */\n init_() {\n if (!this.byteToCharMap_) {\n this.byteToCharMap_ = {};\n this.charToByteMap_ = {};\n this.byteToCharMapWebSafe_ = {};\n this.charToByteMapWebSafe_ = {};\n\n // We want quick mappings back and forth, so we precompute two maps.\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n\n // Be forgiving when decoding and correctly decode both encodings.\n if (i >= this.ENCODED_VALS_BASE.length) {\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n }\n }\n }\n }\n};\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class DecodeBase64StringError extends Error {\n readonly name = 'DecodeBase64StringError';\n}\n\n/**\n * URL-safe base64 encoding\n */\nexport const base64Encode = function (str: string): string {\n const utf8Bytes = stringToByteArray(str);\n return base64.encodeByteArray(utf8Bytes, true);\n};\n\n/**\n * URL-safe base64 encoding (without \".\" padding in the end).\n * e.g. Used in JSON Web Token (JWT) parts.\n */\nexport const base64urlEncodeWithoutPadding = function (str: string): string {\n // Use base64url encoding and remove padding in the end (dot characters).\n return base64Encode(str).replace(/\\./g, '');\n};\n\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param str To be decoded\n * @return Decoded result, if possible\n */\nexport const base64Decode = function (str: string): string | null {\n try {\n return base64.decodeString(str, true);\n } catch (e) {\n console.error('base64Decode failed: ', e);\n }\n return null;\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Do a deep-copy of basic JavaScript Objects or Arrays.\n */\nexport function deepCopy(value: T): T {\n return deepExtend(undefined, value) as T;\n}\n\n/**\n * Copy properties from source to target (recursively allows extension\n * of Objects and Arrays). Scalar values in the target are over-written.\n * If target is undefined, an object of the appropriate type will be created\n * (and returned).\n *\n * We recursively copy all child properties of plain Objects in the source- so\n * that namespace- like dictionaries are merged.\n *\n * Note that the target can be a function, in which case the properties in\n * the source Object are copied onto it as static properties of the Function.\n *\n * Note: we don't merge __proto__ to prevent prototype pollution\n */\nexport function deepExtend(target: unknown, source: unknown): unknown {\n if (!(source instanceof Object)) {\n return source;\n }\n\n switch (source.constructor) {\n case Date:\n // Treat Dates like scalars; if the target date object had any child\n // properties - they will be lost!\n const dateValue = source as Date;\n return new Date(dateValue.getTime());\n\n case Object:\n if (target === undefined) {\n target = {};\n }\n break;\n case Array:\n // Always copy the array source and overwrite the target.\n target = [];\n break;\n\n default:\n // Not a plain Object - treat it as a scalar.\n return source;\n }\n\n for (const prop in source) {\n // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202\n if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {\n continue;\n }\n (target as Record)[prop] = deepExtend(\n (target as Record)[prop],\n (source as Record)[prop]\n );\n }\n\n return target;\n}\n\nfunction isValidKey(key: string): boolean {\n return key !== '__proto__';\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Polyfill for `globalThis` object.\n * @returns the `globalThis` object for the given environment.\n * @public\n */\nexport function getGlobal(): typeof globalThis {\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('Unable to locate global object.');\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Decode } from './crypt';\nimport { getGlobal } from './global';\nimport { getDefaultsFromPostinstall } from './postinstall';\n\n/**\n * Keys for experimental properties on the `FirebaseDefaults` object.\n * @public\n */\nexport type ExperimentalKey = 'authTokenSyncURL' | 'authIdTokenMaxAge';\n\n/**\n * An object that can be injected into the environment as __FIREBASE_DEFAULTS__,\n * either as a property of globalThis, a shell environment variable, or a\n * cookie.\n *\n * This object can be used to automatically configure and initialize\n * a Firebase app as well as any emulators.\n *\n * @public\n */\nexport interface FirebaseDefaults {\n config?: Record;\n emulatorHosts?: Record;\n _authTokenSyncURL?: string;\n _authIdTokenMaxAge?: number;\n /**\n * Override Firebase's runtime environment detection and\n * force the SDK to act as if it were in the specified environment.\n */\n forceEnvironment?: 'browser' | 'node';\n [key: string]: unknown;\n}\n\ndeclare global {\n // Need `var` for this to work.\n // eslint-disable-next-line no-var\n var __FIREBASE_DEFAULTS__: FirebaseDefaults | undefined;\n}\n\nconst getDefaultsFromGlobal = (): FirebaseDefaults | undefined =>\n getGlobal().__FIREBASE_DEFAULTS__;\n\n/**\n * Attempt to read defaults from a JSON string provided to\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\n * The dots are in parens because certain compilers (Vite?) cannot\n * handle seeing that variable in comments.\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\n */\nconst getDefaultsFromEnvVariable = (): FirebaseDefaults | undefined => {\n if (typeof process === 'undefined' || typeof process.env === 'undefined') {\n return;\n }\n const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\n if (defaultsJsonString) {\n return JSON.parse(defaultsJsonString);\n }\n};\n\nconst getDefaultsFromCookie = (): FirebaseDefaults | undefined => {\n if (typeof document === 'undefined') {\n return;\n }\n let match;\n try {\n match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\n } catch (e) {\n // Some environments such as Angular Universal SSR have a\n // `document` object but error on accessing `document.cookie`.\n return;\n }\n const decoded = match && base64Decode(match[1]);\n return decoded && JSON.parse(decoded);\n};\n\n/**\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\n * (1) if such an object exists as a property of `globalThis`\n * (2) if such an object was provided on a shell environment variable\n * (3) if such an object exists in a cookie\n * @public\n */\nexport const getDefaults = (): FirebaseDefaults | undefined => {\n try {\n return (\n getDefaultsFromPostinstall() ||\n getDefaultsFromGlobal() ||\n getDefaultsFromEnvVariable() ||\n getDefaultsFromCookie()\n );\n } catch (e) {\n /**\n * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\n * to any environment case we have not accounted for. Log to\n * info instead of swallowing so we can find these unknown cases\n * and add paths for them if needed.\n */\n console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\n return;\n }\n};\n\n/**\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\n * @public\n */\nexport const getDefaultEmulatorHost = (\n productName: string\n): string | undefined => getDefaults()?.emulatorHosts?.[productName];\n\n/**\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\n * @public\n */\nexport const getDefaultEmulatorHostnameAndPort = (\n productName: string\n): [hostname: string, port: number] | undefined => {\n const host = getDefaultEmulatorHost(productName);\n if (!host) {\n return undefined;\n }\n const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\n if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\n throw new Error(`Invalid host ${host} with no separate hostname and port!`);\n }\n // eslint-disable-next-line no-restricted-globals\n const port = parseInt(host.substring(separatorIndex + 1), 10);\n if (host[0] === '[') {\n // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\n return [host.substring(1, separatorIndex - 1), port];\n } else {\n return [host.substring(0, separatorIndex), port];\n }\n};\n\n/**\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\n * @public\n */\nexport const getDefaultAppConfig = (): Record | undefined =>\n getDefaults()?.config;\n\n/**\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\n * prefixed by \"_\")\n * @public\n */\nexport const getExperimentalSetting = (\n name: T\n): FirebaseDefaults[`_${T}`] =>\n getDefaults()?.[`_${name}`] as FirebaseDefaults[`_${T}`];\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred {\n promise: Promise;\n reject: (value?: unknown) => void = () => {};\n resolve: (value?: unknown) => void = () => {};\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve as (value?: unknown) => void;\n this.reject = reject as (value?: unknown) => void;\n });\n }\n\n /**\n * Our API internals are not promisified and cannot because our callback APIs have subtle expectations around\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\n */\n wrapCallback(\n callback?: (error?: unknown, value?: unknown) => void\n ): (error: unknown, value?: unknown) => void {\n return (error, value?) => {\n if (error) {\n this.reject(error);\n } else {\n this.resolve(value);\n }\n if (typeof callback === 'function') {\n // Attaching noop handler just in case developer wasn't expecting\n // promises\n this.promise.catch(() => {});\n\n // Some of our callbacks don't expect a value and our own tests\n // assert that the parameter length is 1\n if (callback.length === 1) {\n callback(error);\n } else {\n callback(error, value);\n }\n }\n };\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Checks whether host is a cloud workstation or not.\n * @public\n */\nexport function isCloudWorkstation(url: string): boolean {\n // `isCloudWorkstation` is called without protocol in certain connect*Emulator functions\n // In HTTP request builders, it's called with the protocol.\n // If called with protocol prefix, it's a valid URL, so we extract the hostname\n // If called without, we assume the string is the hostname.\n try {\n const host =\n url.startsWith('http://') || url.startsWith('https://')\n ? new URL(url).hostname\n : url;\n return host.endsWith('.cloudworkstations.dev');\n } catch {\n return false;\n }\n}\n\n/**\n * Makes a fetch request to the given server.\n * Mostly used for forwarding cookies in Firebase Studio.\n * @public\n */\nexport async function pingServer(endpoint: string): Promise {\n const result = await fetch(endpoint, {\n credentials: 'include'\n });\n return result.ok;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64urlEncodeWithoutPadding } from './crypt';\nimport { isCloudWorkstation } from './url';\n\n// Firebase Auth tokens contain snake_case claims following the JWT standard / convention.\n/* eslint-disable camelcase */\n\nexport type FirebaseSignInProvider =\n | 'custom'\n | 'email'\n | 'password'\n | 'phone'\n | 'anonymous'\n | 'google.com'\n | 'facebook.com'\n | 'github.com'\n | 'twitter.com'\n | 'microsoft.com'\n | 'apple.com';\n\ninterface FirebaseIdToken {\n // Always set to https://securetoken.google.com/PROJECT_ID\n iss: string;\n\n // Always set to PROJECT_ID\n aud: string;\n\n // The user's unique ID\n sub: string;\n\n // The token issue time, in seconds since epoch\n iat: number;\n\n // The token expiry time, normally 'iat' + 3600\n exp: number;\n\n // The user's unique ID. Must be equal to 'sub'\n user_id: string;\n\n // The time the user authenticated, normally 'iat'\n auth_time: number;\n\n // The sign in provider, only set when the provider is 'anonymous'\n provider_id?: 'anonymous';\n\n // The user's primary email\n email?: string;\n\n // The user's email verification status\n email_verified?: boolean;\n\n // The user's primary phone number\n phone_number?: string;\n\n // The user's display name\n name?: string;\n\n // The user's profile photo URL\n picture?: string;\n\n // Information on all identities linked to this user\n firebase: {\n // The primary sign-in provider\n sign_in_provider: FirebaseSignInProvider;\n\n // A map of providers to the user's list of unique identifiers from\n // each provider\n identities?: { [provider in FirebaseSignInProvider]?: string[] };\n };\n\n // Custom claims set by the developer\n [claim: string]: unknown;\n\n uid?: never; // Try to catch a common mistake of \"uid\" (should be \"sub\" instead).\n}\n\nexport type EmulatorMockTokenOptions = ({ user_id: string } | { sub: string }) &\n Partial;\n\nexport function createMockUserToken(\n token: EmulatorMockTokenOptions,\n projectId?: string\n): string {\n if (token.uid) {\n throw new Error(\n 'The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.'\n );\n }\n // Unsecured JWTs use \"none\" as the algorithm.\n const header = {\n alg: 'none',\n type: 'JWT'\n };\n\n const project = projectId || 'demo-project';\n const iat = token.iat || 0;\n const sub = token.sub || token.user_id;\n if (!sub) {\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\n }\n\n const payload: FirebaseIdToken = {\n // Set all required fields to decent defaults\n iss: `https://securetoken.google.com/${project}`,\n aud: project,\n iat,\n exp: iat + 3600,\n auth_time: iat,\n sub,\n user_id: sub,\n firebase: {\n sign_in_provider: 'custom',\n identities: {}\n },\n\n // Override with user options\n ...token\n };\n\n // Unsecured JWTs use the empty string as a signature.\n const signature = '';\n return [\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\n signature\n ].join('.');\n}\n\ninterface EmulatorStatusMap {\n [name: string]: boolean;\n}\nconst emulatorStatus: EmulatorStatusMap = {};\n\ninterface EmulatorSummary {\n prod: string[];\n emulator: string[];\n}\n\n// Checks whether any products are running on an emulator\nfunction getEmulatorSummary(): EmulatorSummary {\n const summary: EmulatorSummary = {\n prod: [],\n emulator: []\n };\n for (const key of Object.keys(emulatorStatus)) {\n if (emulatorStatus[key]) {\n summary.emulator.push(key);\n } else {\n summary.prod.push(key);\n }\n }\n return summary;\n}\n\nfunction getOrCreateEl(id: string): { created: boolean; element: HTMLElement } {\n let parentDiv = document.getElementById(id);\n let created = false;\n if (!parentDiv) {\n parentDiv = document.createElement('div');\n parentDiv.setAttribute('id', id);\n created = true;\n }\n return { created, element: parentDiv };\n}\n\nlet previouslyDismissed = false;\n/**\n * Updates Emulator Banner. Primarily used for Firebase Studio\n * @param name\n * @param isRunningEmulator\n * @public\n */\nexport function updateEmulatorBanner(\n name: string,\n isRunningEmulator: boolean\n): void {\n if (\n typeof window === 'undefined' ||\n typeof document === 'undefined' ||\n !isCloudWorkstation(window.location.host) ||\n emulatorStatus[name] === isRunningEmulator ||\n emulatorStatus[name] || // If already set to use emulator, can't go back to prod.\n previouslyDismissed\n ) {\n return;\n }\n\n emulatorStatus[name] = isRunningEmulator;\n\n function prefixedId(id: string): string {\n return `__firebase__banner__${id}`;\n }\n const bannerId = '__firebase__banner';\n const summary = getEmulatorSummary();\n const showError = summary.prod.length > 0;\n\n function tearDown(): void {\n const element = document.getElementById(bannerId);\n if (element) {\n element.remove();\n }\n }\n\n function setupBannerStyles(bannerEl: HTMLElement): void {\n bannerEl.style.display = 'flex';\n bannerEl.style.background = '#7faaf0';\n bannerEl.style.position = 'fixed';\n bannerEl.style.bottom = '5px';\n bannerEl.style.left = '5px';\n bannerEl.style.padding = '.5em';\n bannerEl.style.borderRadius = '5px';\n bannerEl.style.alignItems = 'center';\n }\n\n function setupIconStyles(prependIcon: SVGElement, iconId: string): void {\n prependIcon.setAttribute('width', '24');\n prependIcon.setAttribute('id', iconId);\n prependIcon.setAttribute('height', '24');\n prependIcon.setAttribute('viewBox', '0 0 24 24');\n prependIcon.setAttribute('fill', 'none');\n prependIcon.style.marginLeft = '-6px';\n }\n\n function setupCloseBtn(): HTMLSpanElement {\n const closeBtn = document.createElement('span');\n closeBtn.style.cursor = 'pointer';\n closeBtn.style.marginLeft = '16px';\n closeBtn.style.fontSize = '24px';\n closeBtn.innerHTML = ' ×';\n closeBtn.onclick = () => {\n previouslyDismissed = true;\n tearDown();\n };\n return closeBtn;\n }\n\n function setupLinkStyles(\n learnMoreLink: HTMLAnchorElement,\n learnMoreId: string\n ): void {\n learnMoreLink.setAttribute('id', learnMoreId);\n learnMoreLink.innerText = 'Learn more';\n learnMoreLink.href =\n 'https://firebase.google.com/docs/studio/preview-apps#preview-backend';\n learnMoreLink.setAttribute('target', '__blank');\n learnMoreLink.style.paddingLeft = '5px';\n learnMoreLink.style.textDecoration = 'underline';\n }\n\n function setupDom(): void {\n const banner = getOrCreateEl(bannerId);\n const firebaseTextId = prefixedId('text');\n const firebaseText: HTMLSpanElement =\n document.getElementById(firebaseTextId) || document.createElement('span');\n const learnMoreId = prefixedId('learnmore');\n const learnMoreLink: HTMLAnchorElement =\n (document.getElementById(learnMoreId) as HTMLAnchorElement) ||\n document.createElement('a');\n const prependIconId = prefixedId('preprendIcon');\n const prependIcon: SVGElement =\n (document.getElementById(\n prependIconId\n ) as HTMLOrSVGElement as SVGElement) ||\n document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n if (banner.created) {\n // update styles\n const bannerEl = banner.element;\n setupBannerStyles(bannerEl);\n setupLinkStyles(learnMoreLink, learnMoreId);\n const closeBtn = setupCloseBtn();\n setupIconStyles(prependIcon, prependIconId);\n bannerEl.append(prependIcon, firebaseText, learnMoreLink, closeBtn);\n document.body.appendChild(bannerEl);\n }\n\n if (showError) {\n firebaseText.innerText = `Preview backend disconnected.`;\n prependIcon.innerHTML = `\n\n\n\n\n\n\n`;\n } else {\n prependIcon.innerHTML = `\n\n\n\n\n\n\n`;\n firebaseText.innerText = 'Preview backend running in this workspace.';\n }\n firebaseText.setAttribute('id', firebaseTextId);\n }\n if (document.readyState === 'loading') {\n window.addEventListener('DOMContentLoaded', setupDom);\n } else {\n setupDom();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSTANTS } from './constants';\nimport { getDefaults } from './defaults';\n\n/**\n * Type placeholder for `WorkerGlobalScope` from `webworker`\n */\ndeclare class WorkerGlobalScope {}\n\n/**\n * Returns navigator.userAgent string or '' if it's not defined.\n * @return user agent string\n */\nexport function getUA(): string {\n if (\n typeof navigator !== 'undefined' &&\n typeof navigator['userAgent'] === 'string'\n ) {\n return navigator['userAgent'];\n } else {\n return '';\n }\n}\n\n/**\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\n *\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\n * wait for a callback.\n */\nexport function isMobileCordova(): boolean {\n return (\n typeof window !== 'undefined' &&\n // @ts-ignore Setting up an broadly applicable index signature for Window\n // just to deal with this case would probably be a bad idea.\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())\n );\n}\n\n/**\n * Detect Node.js.\n *\n * @return true if Node.js environment is detected or specified.\n */\n// Node detection logic from: https://github.com/iliakan/detect-node/\nexport function isNode(): boolean {\n const forceEnvironment = getDefaults()?.forceEnvironment;\n if (forceEnvironment === 'node') {\n return true;\n } else if (forceEnvironment === 'browser') {\n return false;\n }\n\n try {\n return (\n Object.prototype.toString.call(global.process) === '[object process]'\n );\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Detect Browser Environment.\n * Note: This will return true for certain test frameworks that are incompletely\n * mimicking a browser, and should not lead to assuming all browser APIs are\n * available.\n */\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined' || isWebWorker();\n}\n\n/**\n * Detect Web Worker context.\n */\nexport function isWebWorker(): boolean {\n return (\n typeof WorkerGlobalScope !== 'undefined' &&\n typeof self !== 'undefined' &&\n self instanceof WorkerGlobalScope\n );\n}\n\n/**\n * Detect Cloudflare Worker context.\n */\nexport function isCloudflareWorker(): boolean {\n return (\n typeof navigator !== 'undefined' &&\n navigator.userAgent === 'Cloudflare-Workers'\n );\n}\n\n/**\n * Detect browser extensions (Chrome and Firefox at least).\n */\ninterface BrowserRuntime {\n id?: unknown;\n}\ndeclare const chrome: { runtime?: BrowserRuntime };\ndeclare const browser: { runtime?: BrowserRuntime };\nexport function isBrowserExtension(): boolean {\n const runtime =\n typeof chrome === 'object'\n ? chrome.runtime\n : typeof browser === 'object'\n ? browser.runtime\n : undefined;\n return typeof runtime === 'object' && runtime.id !== undefined;\n}\n\n/**\n * Detect React Native.\n *\n * @return true if ReactNative environment is detected.\n */\nexport function isReactNative(): boolean {\n return (\n typeof navigator === 'object' && navigator['product'] === 'ReactNative'\n );\n}\n\n/** Detects Electron apps. */\nexport function isElectron(): boolean {\n return getUA().indexOf('Electron/') >= 0;\n}\n\n/** Detects Internet Explorer. */\nexport function isIE(): boolean {\n const ua = getUA();\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\n}\n\n/** Detects Universal Windows Platform apps. */\nexport function isUWP(): boolean {\n return getUA().indexOf('MSAppHost/') >= 0;\n}\n\n/**\n * Detect whether the current SDK build is the Node version.\n *\n * @return true if it's the Node SDK build.\n */\nexport function isNodeSdk(): boolean {\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\n}\n\n/** Returns true if we are running in Safari. */\nexport function isSafari(): boolean {\n return (\n !isNode() &&\n !!navigator.userAgent &&\n navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome')\n );\n}\n\n/** Returns true if we are running in Safari or WebKit */\nexport function isSafariOrWebkit(): boolean {\n return (\n !isNode() &&\n !!navigator.userAgent &&\n (navigator.userAgent.includes('Safari') ||\n navigator.userAgent.includes('WebKit')) &&\n !navigator.userAgent.includes('Chrome')\n );\n}\n\n/**\n * This method checks if indexedDB is supported by current browser/service worker context\n * @return true if indexedDB is supported by current browser/service worker context\n */\nexport function isIndexedDBAvailable(): boolean {\n try {\n return typeof indexedDB === 'object';\n } catch (e) {\n return false;\n }\n}\n\n/**\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\n * if errors occur during the database open operation.\n *\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\n * private browsing)\n */\nexport function validateIndexedDBOpenable(): Promise {\n return new Promise((resolve, reject) => {\n try {\n let preExist: boolean = true;\n const DB_CHECK_NAME =\n 'validate-browser-context-for-indexeddb-analytics-module';\n const request = self.indexedDB.open(DB_CHECK_NAME);\n request.onsuccess = () => {\n request.result.close();\n // delete database only when it doesn't pre-exist\n if (!preExist) {\n self.indexedDB.deleteDatabase(DB_CHECK_NAME);\n }\n resolve(true);\n };\n request.onupgradeneeded = () => {\n preExist = false;\n };\n\n request.onerror = () => {\n reject(request.error?.message || '');\n };\n } catch (error) {\n reject(error);\n }\n });\n}\n\n/**\n *\n * This method checks whether cookie is enabled within current browser\n * @return true if cookie is enabled within current browser\n */\nexport function areCookiesEnabled(): boolean {\n if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\n return false;\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n * // TypeScript string literals for type-safe codes\n * type Err =\n * 'unknown' |\n * 'object-not-found'\n * ;\n *\n * // Closure enum for type-safe error codes\n * // at-enum {string}\n * var Err = {\n * UNKNOWN: 'unknown',\n * OBJECT_NOT_FOUND: 'object-not-found',\n * }\n *\n * let errors: Map = {\n * 'generic-error': \"Unknown error\",\n * 'file-not-found': \"Could not find file: {$file}\",\n * };\n *\n * // Type-safe function - must pass a valid error code as param.\n * let error = new ErrorFactory('service', 'Service', errors);\n *\n * ...\n * throw error.create(Err.GENERIC);\n * ...\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n * ...\n * // Service: Could not file file: foo.txt (service/file-not-found).\n *\n * catch (e) {\n * assert(e.message === \"Could not find file: foo.txt.\");\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\n * console.log(\"Could not read file: \" + e['file']);\n * }\n * }\n */\n\nexport type ErrorMap = {\n readonly [K in ErrorCode]: string;\n};\n\nconst ERROR_NAME = 'FirebaseError';\n\nexport interface StringLike {\n toString(): string;\n}\n\nexport interface ErrorData {\n [key: string]: unknown;\n}\n\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nexport class FirebaseError extends Error {\n /** The custom name for all FirebaseErrors. */\n readonly name: string = ERROR_NAME;\n\n constructor(\n /** The error code for this error. */\n readonly code: string,\n message: string,\n /** Custom data for this error. */\n public customData?: Record\n ) {\n super(message);\n\n // Fix For ES5\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget\n // which we can now use since we no longer target ES5.\n Object.setPrototypeOf(this, FirebaseError.prototype);\n\n // Maintains proper stack trace for where our error was thrown.\n // Only available on V8.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\n }\n }\n}\n\nexport class ErrorFactory<\n ErrorCode extends string,\n ErrorParams extends { readonly [K in ErrorCode]?: ErrorData } = {}\n> {\n constructor(\n private readonly service: string,\n private readonly serviceName: string,\n private readonly errors: ErrorMap\n ) {}\n\n create(\n code: K,\n ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []\n ): FirebaseError {\n const customData = (data[0] as ErrorData) || {};\n const fullCode = `${this.service}/${code}`;\n const template = this.errors[code];\n\n const message = template ? replaceTemplate(template, customData) : 'Error';\n // Service Name: Error message (service/code).\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n\n const error = new FirebaseError(fullCode, fullMessage, customData);\n\n return error;\n }\n}\n\nfunction replaceTemplate(template: string, data: ErrorData): string {\n return template.replace(PATTERN, (_, key) => {\n const value = data[key];\n return value != null ? String(value) : `<${key}?>`;\n });\n}\n\nconst PATTERN = /\\{\\$([^}]+)}/g;\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Evaluates a JSON string into a javascript object.\n *\n * @param {string} str A string containing JSON.\n * @return {*} The javascript object representing the specified JSON.\n */\nexport function jsonEval(str: string): unknown {\n return JSON.parse(str);\n}\n\n/**\n * Returns JSON representing a javascript object.\n * @param {*} data JavaScript object to be stringified.\n * @return {string} The JSON contents of the object.\n */\nexport function stringify(data: unknown): string {\n return JSON.stringify(data);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Decode } from './crypt';\nimport { jsonEval } from './json';\n\ninterface Claims {\n [key: string]: {};\n}\n\ninterface DecodedToken {\n header: object;\n claims: Claims;\n data: object;\n signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token into constituent parts.\n *\n * Notes:\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const decode = function (token: string): DecodedToken {\n let header = {},\n claims: Claims = {},\n data = {},\n signature = '';\n\n try {\n const parts = token.split('.');\n header = jsonEval(base64Decode(parts[0]) || '') as object;\n claims = jsonEval(base64Decode(parts[1]) || '') as Claims;\n signature = parts[2];\n data = claims['d'] || {};\n delete claims['d'];\n } catch (e) {}\n\n return {\n header,\n claims,\n data,\n signature\n };\n};\n\ninterface DecodedToken {\n header: object;\n claims: Claims;\n data: object;\n signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidTimestamp = function (token: string): boolean {\n const claims: Claims = decode(token).claims;\n const now: number = Math.floor(new Date().getTime() / 1000);\n let validSince: number = 0,\n validUntil: number = 0;\n\n if (typeof claims === 'object') {\n if (claims.hasOwnProperty('nbf')) {\n validSince = claims['nbf'] as number;\n } else if (claims.hasOwnProperty('iat')) {\n validSince = claims['iat'] as number;\n }\n\n if (claims.hasOwnProperty('exp')) {\n validUntil = claims['exp'] as number;\n } else {\n // token will expire after 24h by default\n validUntil = validSince + 86400;\n }\n }\n\n return (\n !!now &&\n !!validSince &&\n !!validUntil &&\n now >= validSince &&\n now <= validUntil\n );\n};\n\n/**\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\n *\n * Notes:\n * - May return null if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const issuedAtTime = function (token: string): number | null {\n const claims: Claims = decode(token).claims;\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\n return claims['iat'] as number;\n }\n return null;\n};\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidFormat = function (token: string): boolean {\n const decoded = decode(token),\n claims = decoded.claims;\n\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\n};\n\n/**\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isAdmin = function (token: string): boolean {\n const claims: Claims = decode(token).claims;\n return typeof claims === 'object' && claims['admin'] === true;\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function contains(obj: T, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function safeGet(\n obj: T,\n key: K\n): T[K] | undefined {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return obj[key];\n } else {\n return undefined;\n }\n}\n\nexport function isEmpty(obj: object): obj is {} {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\n\nexport function map(\n obj: { [key in K]: V },\n fn: (value: V, key: K, obj: { [key in K]: V }) => U,\n contextObj?: unknown\n): { [key in K]: U } {\n const res: Partial<{ [key in K]: U }> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n res[key] = fn.call(contextObj, obj[key], key, obj);\n }\n }\n return res as { [key in K]: U };\n}\n\n/**\n * Deep equal two objects. Support Arrays and Objects.\n */\nexport function deepEqual(a: object, b: object): boolean {\n if (a === b) {\n return true;\n }\n\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n for (const k of aKeys) {\n if (!bKeys.includes(k)) {\n return false;\n }\n\n const aProp = (a as Record)[k];\n const bProp = (b as Record)[k];\n if (isObject(aProp) && isObject(bProp)) {\n if (!deepEqual(aProp, bProp)) {\n return false;\n }\n } else if (aProp !== bProp) {\n return false;\n }\n }\n\n for (const k of bKeys) {\n if (!aKeys.includes(k)) {\n return false;\n }\n }\n return true;\n}\n\nfunction isObject(thing: unknown): thing is object {\n return thing !== null && typeof thing === 'object';\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from './deferred';\n\n/**\n * Rejects if the given promise doesn't resolve in timeInMS milliseconds.\n * @internal\n */\nexport function promiseWithTimeout(\n promise: Promise,\n timeInMS = 2000\n): Promise {\n const deferredPromise = new Deferred();\n setTimeout(() => deferredPromise.reject('timeout!'), timeInMS);\n promise.then(deferredPromise.resolve, deferredPromise.reject);\n return deferredPromise.promise;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\n * params object (e.g. {arg: 'val', arg2: 'val2'})\n * Note: You must prepend it with ? when adding it to a URL.\n */\nexport function querystring(querystringParams: {\n [key: string]: string | number;\n}): string {\n const params = [];\n for (const [key, value] of Object.entries(querystringParams)) {\n if (Array.isArray(value)) {\n value.forEach(arrayVal => {\n params.push(\n encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal)\n );\n });\n } else {\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n }\n }\n return params.length ? '&' + params.join('&') : '';\n}\n\n/**\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\n * (e.g. {arg: 'val', arg2: 'val2'})\n */\nexport function querystringDecode(querystring: string): Record {\n const obj: Record = {};\n const tokens = querystring.replace(/^\\?/, '').split('&');\n\n tokens.forEach(token => {\n if (token) {\n const [key, value] = token.split('=');\n obj[decodeURIComponent(key)] = decodeURIComponent(value);\n }\n });\n return obj;\n}\n\n/**\n * Extract the query string part of a URL, including the leading question mark (if present).\n */\nexport function extractQuerystring(url: string): string {\n const queryStart = url.indexOf('?');\n if (!queryStart) {\n return '';\n }\n const fragmentStart = url.indexOf('#', queryStart);\n return url.substring(\n queryStart,\n fragmentStart > 0 ? fragmentStart : undefined\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview SHA-1 cryptographic hash.\n * Variable names follow the notation in FIPS PUB 180-3:\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\n *\n * Usage:\n * var sha1 = new sha1();\n * sha1.update(bytes);\n * var hash = sha1.digest();\n *\n * Performance:\n * Chrome 23: ~400 Mbit/s\n * Firefox 16: ~250 Mbit/s\n *\n */\n\n/**\n * SHA-1 cryptographic hash constructor.\n *\n * The properties declared here are discussed in the above algorithm document.\n * @constructor\n * @final\n * @struct\n */\nexport class Sha1 {\n /**\n * Holds the previous values of accumulated variables a-e in the compress_\n * function.\n * @private\n */\n private chain_: number[] = [];\n\n /**\n * A buffer holding the partially computed hash result.\n * @private\n */\n private buf_: number[] = [];\n\n /**\n * An array of 80 bytes, each a part of the message to be hashed. Referred to\n * as the message schedule in the docs.\n * @private\n */\n private W_: number[] = [];\n\n /**\n * Contains data needed to pad messages less than 64 bytes.\n * @private\n */\n private pad_: number[] = [];\n\n /**\n * @private {number}\n */\n private inbuf_: number = 0;\n\n /**\n * @private {number}\n */\n private total_: number = 0;\n\n blockSize: number;\n\n constructor() {\n this.blockSize = 512 / 8;\n\n this.pad_[0] = 128;\n for (let i = 1; i < this.blockSize; ++i) {\n this.pad_[i] = 0;\n }\n\n this.reset();\n }\n\n reset(): void {\n this.chain_[0] = 0x67452301;\n this.chain_[1] = 0xefcdab89;\n this.chain_[2] = 0x98badcfe;\n this.chain_[3] = 0x10325476;\n this.chain_[4] = 0xc3d2e1f0;\n\n this.inbuf_ = 0;\n this.total_ = 0;\n }\n\n /**\n * Internal compress helper function.\n * @param buf Block to compress.\n * @param offset Offset of the block in the buffer.\n * @private\n */\n compress_(buf: number[] | Uint8Array | string, offset?: number): void {\n if (!offset) {\n offset = 0;\n }\n\n const W = this.W_;\n\n // get 16 big endian words\n if (typeof buf === 'string') {\n for (let i = 0; i < 16; i++) {\n // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\n // have a bug that turns the post-increment ++ operator into pre-increment\n // during JIT compilation. We have code that depends heavily on SHA-1 for\n // correctness and which is affected by this bug, so I've removed all uses\n // of post-increment ++ in which the result value is used. We can revert\n // this change once the Safari bug\n // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\n // most clients have been updated.\n W[i] =\n (buf.charCodeAt(offset) << 24) |\n (buf.charCodeAt(offset + 1) << 16) |\n (buf.charCodeAt(offset + 2) << 8) |\n buf.charCodeAt(offset + 3);\n offset += 4;\n }\n } else {\n for (let i = 0; i < 16; i++) {\n W[i] =\n (buf[offset] << 24) |\n (buf[offset + 1] << 16) |\n (buf[offset + 2] << 8) |\n buf[offset + 3];\n offset += 4;\n }\n }\n\n // expand to 80 words\n for (let i = 16; i < 80; i++) {\n const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\n W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\n }\n\n let a = this.chain_[0];\n let b = this.chain_[1];\n let c = this.chain_[2];\n let d = this.chain_[3];\n let e = this.chain_[4];\n let f, k;\n\n // TODO(user): Try to unroll this loop to speed up the computation.\n for (let i = 0; i < 80; i++) {\n if (i < 40) {\n if (i < 20) {\n f = d ^ (b & (c ^ d));\n k = 0x5a827999;\n } else {\n f = b ^ c ^ d;\n k = 0x6ed9eba1;\n }\n } else {\n if (i < 60) {\n f = (b & c) | (d & (b | c));\n k = 0x8f1bbcdc;\n } else {\n f = b ^ c ^ d;\n k = 0xca62c1d6;\n }\n }\n\n const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\n e = d;\n d = c;\n c = ((b << 30) | (b >>> 2)) & 0xffffffff;\n b = a;\n a = t;\n }\n\n this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\n this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\n this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\n this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\n this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\n }\n\n update(bytes?: number[] | Uint8Array | string, length?: number): void {\n // TODO(johnlenz): tighten the function signature and remove this check\n if (bytes == null) {\n return;\n }\n\n if (length === undefined) {\n length = bytes.length;\n }\n\n const lengthMinusBlock = length - this.blockSize;\n let n = 0;\n // Using local instead of member variables gives ~5% speedup on Firefox 16.\n const buf = this.buf_;\n let inbuf = this.inbuf_;\n\n // The outer while loop should execute at most twice.\n while (n < length) {\n // When we have no data in the block to top up, we can directly process the\n // input buffer (assuming it contains sufficient data). This gives ~25%\n // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\n // the data is provided in large chunks (or in multiples of 64 bytes).\n if (inbuf === 0) {\n while (n <= lengthMinusBlock) {\n this.compress_(bytes, n);\n n += this.blockSize;\n }\n }\n\n if (typeof bytes === 'string') {\n while (n < length) {\n buf[inbuf] = bytes.charCodeAt(n);\n ++inbuf;\n ++n;\n if (inbuf === this.blockSize) {\n this.compress_(buf);\n inbuf = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n } else {\n while (n < length) {\n buf[inbuf] = bytes[n];\n ++inbuf;\n ++n;\n if (inbuf === this.blockSize) {\n this.compress_(buf);\n inbuf = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n }\n }\n\n this.inbuf_ = inbuf;\n this.total_ += length;\n }\n\n /** @override */\n digest(): number[] {\n const digest: number[] = [];\n let totalBits = this.total_ * 8;\n\n // Add pad 0x80 0x00*.\n if (this.inbuf_ < 56) {\n this.update(this.pad_, 56 - this.inbuf_);\n } else {\n this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\n }\n\n // Add # bits.\n for (let i = this.blockSize - 1; i >= 56; i--) {\n this.buf_[i] = totalBits & 255;\n totalBits /= 256; // Don't use bit-shifting here!\n }\n\n this.compress_(this.buf_);\n\n let n = 0;\n for (let i = 0; i < 5; i++) {\n for (let j = 24; j >= 0; j -= 8) {\n digest[n] = (this.chain_[i] >> j) & 255;\n ++n;\n }\n }\n return digest;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport type NextFn = (value: T) => void;\nexport type ErrorFn = (error: Error) => void;\nexport type CompleteFn = () => void;\n\nexport interface Observer {\n // Called once for each value in a stream of values.\n next: NextFn;\n\n // A stream terminates by a single call to EITHER error() or complete().\n error: ErrorFn;\n\n // No events will be sent to next() once complete() is called.\n complete: CompleteFn;\n}\n\nexport type PartialObserver = Partial>;\n\n// TODO: Support also Unsubscribe.unsubscribe?\nexport type Unsubscribe = () => void;\n\n/**\n * The Subscribe interface has two forms - passing the inline function\n * callbacks, or a object interface with callback properties.\n */\nexport interface Subscribe {\n (next?: NextFn, error?: ErrorFn, complete?: CompleteFn): Unsubscribe;\n (observer: PartialObserver): Unsubscribe;\n}\n\nexport interface Observable {\n // Subscribe method\n subscribe: Subscribe;\n}\n\nexport type Executor = (observer: Observer) => void;\n\n/**\n * Helper to make a Subscribe function (just like Promise helps make a\n * Thenable).\n *\n * @param executor Function which can make calls to a single Observer\n * as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\nexport function createSubscribe(\n executor: Executor,\n onNoObservers?: Executor\n): Subscribe {\n const proxy = new ObserverProxy(executor, onNoObservers);\n return proxy.subscribe.bind(proxy);\n}\n\n/**\n * Implement fan-out for any number of Observers attached via a subscribe\n * function.\n */\nclass ObserverProxy implements Observer {\n private observers: Array> | undefined = [];\n private unsubscribes: Unsubscribe[] = [];\n private onNoObservers: Executor | undefined;\n private observerCount = 0;\n // Micro-task scheduling by calling task.then().\n private task = Promise.resolve();\n private finalized = false;\n private finalError?: Error;\n\n /**\n * @param executor Function which can make calls to a single Observer\n * as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\n constructor(executor: Executor, onNoObservers?: Executor) {\n this.onNoObservers = onNoObservers;\n // Call the executor asynchronously so subscribers that are called\n // synchronously after the creation of the subscribe function\n // can still receive the very first value generated in the executor.\n this.task\n .then(() => {\n executor(this);\n })\n .catch(e => {\n this.error(e);\n });\n }\n\n next(value: T): void {\n this.forEachObserver((observer: Observer) => {\n observer.next(value);\n });\n }\n\n error(error: Error): void {\n this.forEachObserver((observer: Observer) => {\n observer.error(error);\n });\n this.close(error);\n }\n\n complete(): void {\n this.forEachObserver((observer: Observer) => {\n observer.complete();\n });\n this.close();\n }\n\n /**\n * Subscribe function that can be used to add an Observer to the fan-out list.\n *\n * - We require that no event is sent to a subscriber synchronously to their\n * call to subscribe().\n */\n subscribe(\n nextOrObserver?: NextFn | PartialObserver,\n error?: ErrorFn,\n complete?: CompleteFn\n ): Unsubscribe {\n let observer: Observer;\n\n if (\n nextOrObserver === undefined &&\n error === undefined &&\n complete === undefined\n ) {\n throw new Error('Missing Observer.');\n }\n\n // Assemble an Observer object when passed as callback functions.\n if (\n implementsAnyMethods(nextOrObserver as { [key: string]: unknown }, [\n 'next',\n 'error',\n 'complete'\n ])\n ) {\n observer = nextOrObserver as Observer;\n } else {\n observer = {\n next: nextOrObserver as NextFn,\n error,\n complete\n } as Observer;\n }\n\n if (observer.next === undefined) {\n observer.next = noop as NextFn;\n }\n if (observer.error === undefined) {\n observer.error = noop as ErrorFn;\n }\n if (observer.complete === undefined) {\n observer.complete = noop as CompleteFn;\n }\n\n const unsub = this.unsubscribeOne.bind(this, this.observers!.length);\n\n // Attempt to subscribe to a terminated Observable - we\n // just respond to the Observer with the final error or complete\n // event.\n if (this.finalized) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n try {\n if (this.finalError) {\n observer.error(this.finalError);\n } else {\n observer.complete();\n }\n } catch (e) {\n // nothing\n }\n return;\n });\n }\n\n this.observers!.push(observer as Observer);\n\n return unsub;\n }\n\n // Unsubscribe is synchronous - we guarantee that no events are sent to\n // any unsubscribed Observer.\n private unsubscribeOne(i: number): void {\n if (this.observers === undefined || this.observers[i] === undefined) {\n return;\n }\n\n delete this.observers[i];\n\n this.observerCount -= 1;\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\n this.onNoObservers(this);\n }\n }\n\n private forEachObserver(fn: (observer: Observer) => void): void {\n if (this.finalized) {\n // Already closed by previous event....just eat the additional values.\n return;\n }\n\n // Since sendOne calls asynchronously - there is no chance that\n // this.observers will become undefined.\n for (let i = 0; i < this.observers!.length; i++) {\n this.sendOne(i, fn);\n }\n }\n\n // Call the Observer via one of it's callback function. We are careful to\n // confirm that the observe has not been unsubscribed since this asynchronous\n // function had been queued.\n private sendOne(i: number, fn: (observer: Observer) => void): void {\n // Execute the callback asynchronously\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n if (this.observers !== undefined && this.observers[i] !== undefined) {\n try {\n fn(this.observers[i]);\n } catch (e) {\n // Ignore exceptions raised in Observers or missing methods of an\n // Observer.\n // Log error to console. b/31404806\n if (typeof console !== 'undefined' && console.error) {\n console.error(e);\n }\n }\n }\n });\n }\n\n private close(err?: Error): void {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n if (err !== undefined) {\n this.finalError = err;\n }\n // Proxy is no longer needed - garbage collect references\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n this.observers = undefined;\n this.onNoObservers = undefined;\n });\n }\n}\n\n/** Turn synchronous function into one called asynchronously. */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function async(fn: Function, onError?: ErrorFn): Function {\n return (...args: unknown[]) => {\n Promise.resolve(true)\n .then(() => {\n fn(...args);\n })\n .catch((error: Error) => {\n if (onError) {\n onError(error);\n }\n });\n };\n}\n\n/**\n * Return true if the object passed in implements any of the named methods.\n */\nfunction implementsAnyMethods(\n obj: { [key: string]: unknown },\n methods: string[]\n): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n for (const method of methods) {\n if (method in obj && typeof obj[method] === 'function') {\n return true;\n }\n }\n\n return false;\n}\n\nfunction noop(): void {\n // do nothing\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Check to make sure the appropriate number of arguments are provided for a public function.\n * Throws an error if it fails.\n *\n * @param fnName The function name\n * @param minCount The minimum number of arguments to allow for the function call\n * @param maxCount The maximum number of argument to allow for the function call\n * @param argCount The actual number of arguments provided.\n */\nexport const validateArgCount = function (\n fnName: string,\n minCount: number,\n maxCount: number,\n argCount: number\n): void {\n let argError;\n if (argCount < minCount) {\n argError = 'at least ' + minCount;\n } else if (argCount > maxCount) {\n argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\n }\n if (argError) {\n const error =\n fnName +\n ' failed: Was called with ' +\n argCount +\n (argCount === 1 ? ' argument.' : ' arguments.') +\n ' Expects ' +\n argError +\n '.';\n throw new Error(error);\n }\n};\n\n/**\n * Generates a string to prefix an error message about failed argument validation\n *\n * @param fnName The function name\n * @param argName The name of the argument\n * @return The prefix to add to the error thrown for validation.\n */\nexport function errorPrefix(fnName: string, argName: string): string {\n return `${fnName} failed: ${argName} argument `;\n}\n\n/**\n * @param fnName\n * @param argumentNumber\n * @param namespace\n * @param optional\n */\nexport function validateNamespace(\n fnName: string,\n namespace: string,\n optional: boolean\n): void {\n if (optional && !namespace) {\n return;\n }\n if (typeof namespace !== 'string') {\n //TODO: I should do more validation here. We only allow certain chars in namespaces.\n throw new Error(\n errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.'\n );\n }\n}\n\nexport function validateCallback(\n fnName: string,\n argumentName: string,\n // eslint-disable-next-line @typescript-eslint/ban-types\n callback: Function,\n optional: boolean\n): void {\n if (optional && !callback) {\n return;\n }\n if (typeof callback !== 'function') {\n throw new Error(\n errorPrefix(fnName, argumentName) + 'must be a valid function.'\n );\n }\n}\n\nexport function validateContextObject(\n fnName: string,\n argumentName: string,\n context: unknown,\n optional: boolean\n): void {\n if (optional && !context) {\n return;\n }\n if (typeof context !== 'object' || context === null) {\n throw new Error(\n errorPrefix(fnName, argumentName) + 'must be a valid context object.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from './assert';\n\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\n// so it's been modified.\n\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\n// use 2 characters in JavaScript. All 4-byte UTF-8 characters begin with a first\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\n// pair).\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\n\n/**\n * @param {string} str\n * @return {Array}\n */\nexport const stringToByteArray = function (str: string): number[] {\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n\n // Is this the lead surrogate in a surrogate pair?\n if (c >= 0xd800 && c <= 0xdbff) {\n const high = c - 0xd800; // the high 10 bits.\n i++;\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\n const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\n c = 0x10000 + (high << 10) + low;\n }\n\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (c < 65536) {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Calculate length without actually converting; useful for doing cheaper validation.\n * @param {string} str\n * @return {number}\n */\nexport const stringLength = function (str: string): number {\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n const c = str.charCodeAt(i);\n if (c < 128) {\n p++;\n } else if (c < 2048) {\n p += 2;\n } else if (c >= 0xd800 && c <= 0xdbff) {\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\n p += 4;\n i++; // skip trail surrogate.\n } else {\n p += 3;\n }\n }\n return p;\n};\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The amount of milliseconds to exponentially increase.\n */\nconst DEFAULT_INTERVAL_MILLIS = 1000;\n\n/**\n * The factor to backoff by.\n * Should be a number greater than 1.\n */\nconst DEFAULT_BACKOFF_FACTOR = 2;\n\n/**\n * The maximum milliseconds to increase to.\n *\n *

Visible for testing\n */\nexport const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\n\n/**\n * The percentage of backoff time to randomize by.\n * See\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\n * for context.\n *\n *

Visible for testing\n */\nexport const RANDOM_FACTOR = 0.5;\n\n/**\n * Based on the backoff method from\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\n */\nexport function calculateBackoffMillis(\n backoffCount: number,\n intervalMillis: number = DEFAULT_INTERVAL_MILLIS,\n backoffFactor: number = DEFAULT_BACKOFF_FACTOR\n): number {\n // Calculates an exponentially increasing value.\n // Deviation: calculates value from count and a constant interval, so we only need to save value\n // and count to restore state.\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\n\n // A random \"fuzz\" to avoid waves of retries.\n // Deviation: randomFactor is required.\n const randomWait = Math.round(\n // A fraction of the backoff value to add/subtract.\n // Deviation: changes multiplication order to improve readability.\n RANDOM_FACTOR *\n currBaseValue *\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\n // if we add or subtract.\n (Math.random() - 0.5) *\n 2\n );\n\n // Limits backoff to max to avoid effectively permanent backoff.\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Provide English ordinal letters after a number\n */\nexport function ordinal(i: number): string {\n if (!Number.isFinite(i)) {\n return `${i}`;\n }\n return i + indicator(i);\n}\n\nfunction indicator(i: number): string {\n i = Math.abs(i);\n const cent = i % 100;\n if (cent >= 10 && cent <= 20) {\n return 'th';\n }\n const dec = i % 10;\n if (dec === 1) {\n return 'st';\n }\n if (dec === 2) {\n return 'nd';\n }\n if (dec === 3) {\n return 'rd';\n }\n return 'th';\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Compat {\n _delegate: T;\n}\n\nexport function getModularInstance(\n service: Compat | ExpService\n): ExpService {\n if (service && (service as Compat)._delegate) {\n return (service as Compat)._delegate;\n } else {\n return service as ExpService;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSTANTS } from './src/constants';\n\n// Overriding the constant (we should be the only ones doing this)\nCONSTANTS.NODE_CLIENT = true;\n\nexport * from './src/assert';\nexport * from './src/crypt';\nexport * from './src/constants';\nexport * from './src/deepCopy';\nexport * from './src/defaults';\nexport * from './src/deferred';\nexport * from './src/emulator';\nexport * from './src/environment';\nexport * from './src/errors';\nexport * from './src/json';\nexport * from './src/jwt';\nexport * from './src/obj';\nexport * from './src/promise';\nexport * from './src/query';\nexport * from './src/sha1';\nexport * from './src/subscribe';\nexport * from './src/validation';\nexport * from './src/utf8';\nexport * from './src/exponential_backoff';\nexport * from './src/formatters';\nexport * from './src/compat';\nexport * from './src/global';\nexport * from './src/url';\n"],"names":["stringToByteArray","getDefaultsFromPostinstall"],"mappings":";;;;;;AAAA,CAAA,CAAA;;;;;;;;;;;;;;;AAeG,CAAA,CAAA;AAEH,CAAA,CAAA;;AAEG,CAAA,CAAA;AAEU,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,SAAS,CAAG,CAAA,CAAA;AACvB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;;AAEG,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AACH,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAW,EAAE,CAAK,CAAA,CAAA,CAAA,CAAA;AAClB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;;AAEG,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AACH,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAU,EAAE,CAAK,CAAA,CAAA,CAAA,CAAA;AAEjB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;;AAEG,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AACH,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAW,EAAE,CAAmB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;;;AClClC,CAAA,CAAA;;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CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAC,CAAW,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAG,CAAI,CAAA,CAAA,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@firebase/util/dist/index.node.d.ts b/node_modules/@firebase/util/dist/index.node.d.ts new file mode 100644 index 0000000..2c31ac9 --- /dev/null +++ b/node_modules/@firebase/util/dist/index.node.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './src/assert'; +export * from './src/crypt'; +export * from './src/constants'; +export * from './src/deepCopy'; +export * from './src/defaults'; +export * from './src/deferred'; +export * from './src/emulator'; +export * from './src/environment'; +export * from './src/errors'; +export * from './src/json'; +export * from './src/jwt'; +export * from './src/obj'; +export * from './src/promise'; +export * from './src/query'; +export * from './src/sha1'; +export * from './src/subscribe'; +export * from './src/validation'; +export * from './src/utf8'; +export * from './src/exponential_backoff'; +export * from './src/formatters'; +export * from './src/compat'; +export * from './src/global'; +export * from './src/url'; diff --git a/node_modules/@firebase/util/dist/node-esm/index.d.ts b/node_modules/@firebase/util/dist/node-esm/index.d.ts new file mode 100644 index 0000000..2c31ac9 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/index.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './src/assert'; +export * from './src/crypt'; +export * from './src/constants'; +export * from './src/deepCopy'; +export * from './src/defaults'; +export * from './src/deferred'; +export * from './src/emulator'; +export * from './src/environment'; +export * from './src/errors'; +export * from './src/json'; +export * from './src/jwt'; +export * from './src/obj'; +export * from './src/promise'; +export * from './src/query'; +export * from './src/sha1'; +export * from './src/subscribe'; +export * from './src/validation'; +export * from './src/utf8'; +export * from './src/exponential_backoff'; +export * from './src/formatters'; +export * from './src/compat'; +export * from './src/global'; +export * from './src/url'; diff --git a/node_modules/@firebase/util/dist/node-esm/index.node.d.ts b/node_modules/@firebase/util/dist/node-esm/index.node.d.ts new file mode 100644 index 0000000..2c31ac9 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/index.node.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './src/assert'; +export * from './src/crypt'; +export * from './src/constants'; +export * from './src/deepCopy'; +export * from './src/defaults'; +export * from './src/deferred'; +export * from './src/emulator'; +export * from './src/environment'; +export * from './src/errors'; +export * from './src/json'; +export * from './src/jwt'; +export * from './src/obj'; +export * from './src/promise'; +export * from './src/query'; +export * from './src/sha1'; +export * from './src/subscribe'; +export * from './src/validation'; +export * from './src/utf8'; +export * from './src/exponential_backoff'; +export * from './src/formatters'; +export * from './src/compat'; +export * from './src/global'; +export * from './src/url'; diff --git a/node_modules/@firebase/util/dist/node-esm/index.node.esm.js b/node_modules/@firebase/util/dist/node-esm/index.node.esm.js new file mode 100644 index 0000000..0c74c06 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/index.node.esm.js @@ -0,0 +1,2337 @@ +import { getDefaultsFromPostinstall } from '../postinstall.mjs'; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time. + */ +const CONSTANTS = { + /** + * @define {boolean} Whether this is the client Node.js SDK. + */ + NODE_CLIENT: false, + /** + * @define {boolean} Whether this is the Admin Node.js SDK. + */ + NODE_ADMIN: false, + /** + * Firebase SDK Version + */ + SDK_VERSION: '${JSCORE_VERSION}' +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Throws an error if the provided assertion is falsy + */ +const assert = function (assertion, message) { + if (!assertion) { + throw assertionError(message); + } +}; +/** + * Returns an Error object suitable for throwing. + */ +const assertionError = function (message) { + return new Error('Firebase Database (' + + CONSTANTS.SDK_VERSION + + ') INTERNAL ASSERT FAILED: ' + + message); +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const stringToByteArray$1 = function (str) { + // TODO(user): Use native implementations if/when available + const out = []; + let p = 0; + for (let i = 0; i < str.length; i++) { + let c = str.charCodeAt(i); + if (c < 128) { + out[p++] = c; + } + else if (c < 2048) { + out[p++] = (c >> 6) | 192; + out[p++] = (c & 63) | 128; + } + else if ((c & 0xfc00) === 0xd800 && + i + 1 < str.length && + (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { + // Surrogate Pair + c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff); + out[p++] = (c >> 18) | 240; + out[p++] = ((c >> 12) & 63) | 128; + out[p++] = ((c >> 6) & 63) | 128; + out[p++] = (c & 63) | 128; + } + else { + out[p++] = (c >> 12) | 224; + out[p++] = ((c >> 6) & 63) | 128; + out[p++] = (c & 63) | 128; + } + } + return out; +}; +/** + * Turns an array of numbers into the string given by the concatenation of the + * characters to which the numbers correspond. + * @param bytes Array of numbers representing characters. + * @return Stringification of the array. + */ +const byteArrayToString = function (bytes) { + // TODO(user): Use native implementations if/when available + const out = []; + let pos = 0, c = 0; + while (pos < bytes.length) { + const c1 = bytes[pos++]; + if (c1 < 128) { + out[c++] = String.fromCharCode(c1); + } + else if (c1 > 191 && c1 < 224) { + const c2 = bytes[pos++]; + out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63)); + } + else if (c1 > 239 && c1 < 365) { + // Surrogate Pair + const c2 = bytes[pos++]; + const c3 = bytes[pos++]; + const c4 = bytes[pos++]; + const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) - + 0x10000; + out[c++] = String.fromCharCode(0xd800 + (u >> 10)); + out[c++] = String.fromCharCode(0xdc00 + (u & 1023)); + } + else { + const c2 = bytes[pos++]; + const c3 = bytes[pos++]; + out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); + } + } + return out.join(''); +}; +// We define it as an object literal instead of a class because a class compiled down to es5 can't +// be treeshaked. https://github.com/rollup/rollup/issues/1691 +// Static lookup maps, lazily populated by init_() +// TODO(dlarocque): Define this as a class, since we no longer target ES5. +const base64 = { + /** + * Maps bytes to characters. + */ + byteToCharMap_: null, + /** + * Maps characters to bytes. + */ + charToByteMap_: null, + /** + * Maps bytes to websafe characters. + * @private + */ + byteToCharMapWebSafe_: null, + /** + * Maps websafe characters to bytes. + * @private + */ + charToByteMapWebSafe_: null, + /** + * Our default alphabet, shared between + * ENCODED_VALS and ENCODED_VALS_WEBSAFE + */ + ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789', + /** + * Our default alphabet. Value 64 (=) is special; it means "nothing." + */ + get ENCODED_VALS() { + return this.ENCODED_VALS_BASE + '+/='; + }, + /** + * Our websafe alphabet. + */ + get ENCODED_VALS_WEBSAFE() { + return this.ENCODED_VALS_BASE + '-_.'; + }, + /** + * Whether this browser supports the atob and btoa functions. This extension + * started at Mozilla but is now implemented by many browsers. We use the + * ASSUME_* variables to avoid pulling in the full useragent detection library + * but still allowing the standard per-browser compilations. + * + */ + HAS_NATIVE_SUPPORT: typeof atob === 'function', + /** + * Base64-encode an array of bytes. + * + * @param input An array of bytes (numbers with + * value in [0, 255]) to encode. + * @param webSafe Boolean indicating we should use the + * alternative alphabet. + * @return The base64 encoded string. + */ + encodeByteArray(input, webSafe) { + if (!Array.isArray(input)) { + throw Error('encodeByteArray takes an array as a parameter'); + } + this.init_(); + const byteToCharMap = webSafe + ? this.byteToCharMapWebSafe_ + : this.byteToCharMap_; + const output = []; + for (let i = 0; i < input.length; i += 3) { + const byte1 = input[i]; + const haveByte2 = i + 1 < input.length; + const byte2 = haveByte2 ? input[i + 1] : 0; + const haveByte3 = i + 2 < input.length; + const byte3 = haveByte3 ? input[i + 2] : 0; + const outByte1 = byte1 >> 2; + const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4); + let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6); + let outByte4 = byte3 & 0x3f; + if (!haveByte3) { + outByte4 = 64; + if (!haveByte2) { + outByte3 = 64; + } + } + output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]); + } + return output.join(''); + }, + /** + * Base64-encode a string. + * + * @param input A string to encode. + * @param webSafe If true, we should use the + * alternative alphabet. + * @return The base64 encoded string. + */ + encodeString(input, webSafe) { + // Shortcut for Mozilla browsers that implement + // a native base64 encoder in the form of "btoa/atob" + if (this.HAS_NATIVE_SUPPORT && !webSafe) { + return btoa(input); + } + return this.encodeByteArray(stringToByteArray$1(input), webSafe); + }, + /** + * Base64-decode a string. + * + * @param input to decode. + * @param webSafe True if we should use the + * alternative alphabet. + * @return string representing the decoded value. + */ + decodeString(input, webSafe) { + // Shortcut for Mozilla browsers that implement + // a native base64 encoder in the form of "btoa/atob" + if (this.HAS_NATIVE_SUPPORT && !webSafe) { + return atob(input); + } + return byteArrayToString(this.decodeStringToByteArray(input, webSafe)); + }, + /** + * Base64-decode a string. + * + * In base-64 decoding, groups of four characters are converted into three + * bytes. If the encoder did not apply padding, the input length may not + * be a multiple of 4. + * + * In this case, the last group will have fewer than 4 characters, and + * padding will be inferred. If the group has one or two characters, it decodes + * to one byte. If the group has three characters, it decodes to two bytes. + * + * @param input Input to decode. + * @param webSafe True if we should use the web-safe alphabet. + * @return bytes representing the decoded value. + */ + decodeStringToByteArray(input, webSafe) { + this.init_(); + const charToByteMap = webSafe + ? this.charToByteMapWebSafe_ + : this.charToByteMap_; + const output = []; + for (let i = 0; i < input.length;) { + const byte1 = charToByteMap[input.charAt(i++)]; + const haveByte2 = i < input.length; + const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0; + ++i; + const haveByte3 = i < input.length; + const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64; + ++i; + const haveByte4 = i < input.length; + const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64; + ++i; + if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) { + throw new DecodeBase64StringError(); + } + const outByte1 = (byte1 << 2) | (byte2 >> 4); + output.push(outByte1); + if (byte3 !== 64) { + const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2); + output.push(outByte2); + if (byte4 !== 64) { + const outByte3 = ((byte3 << 6) & 0xc0) | byte4; + output.push(outByte3); + } + } + } + return output; + }, + /** + * Lazy static initialization function. Called before + * accessing any of the static map variables. + * @private + */ + init_() { + if (!this.byteToCharMap_) { + this.byteToCharMap_ = {}; + this.charToByteMap_ = {}; + this.byteToCharMapWebSafe_ = {}; + this.charToByteMapWebSafe_ = {}; + // We want quick mappings back and forth, so we precompute two maps. + for (let i = 0; i < this.ENCODED_VALS.length; i++) { + this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i); + this.charToByteMap_[this.byteToCharMap_[i]] = i; + this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i); + this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i; + // Be forgiving when decoding and correctly decode both encodings. + if (i >= this.ENCODED_VALS_BASE.length) { + this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i; + this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i; + } + } + } + } +}; +/** + * An error encountered while decoding base64 string. + */ +class DecodeBase64StringError extends Error { + constructor() { + super(...arguments); + this.name = 'DecodeBase64StringError'; + } +} +/** + * URL-safe base64 encoding + */ +const base64Encode = function (str) { + const utf8Bytes = stringToByteArray$1(str); + return base64.encodeByteArray(utf8Bytes, true); +}; +/** + * URL-safe base64 encoding (without "." padding in the end). + * e.g. Used in JSON Web Token (JWT) parts. + */ +const base64urlEncodeWithoutPadding = function (str) { + // Use base64url encoding and remove padding in the end (dot characters). + return base64Encode(str).replace(/\./g, ''); +}; +/** + * URL-safe base64 decoding + * + * NOTE: DO NOT use the global atob() function - it does NOT support the + * base64Url variant encoding. + * + * @param str To be decoded + * @return Decoded result, if possible + */ +const base64Decode = function (str) { + try { + return base64.decodeString(str, true); + } + catch (e) { + console.error('base64Decode failed: ', e); + } + return null; +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Do a deep-copy of basic JavaScript Objects or Arrays. + */ +function deepCopy(value) { + return deepExtend(undefined, value); +} +/** + * Copy properties from source to target (recursively allows extension + * of Objects and Arrays). Scalar values in the target are over-written. + * If target is undefined, an object of the appropriate type will be created + * (and returned). + * + * We recursively copy all child properties of plain Objects in the source- so + * that namespace- like dictionaries are merged. + * + * Note that the target can be a function, in which case the properties in + * the source Object are copied onto it as static properties of the Function. + * + * Note: we don't merge __proto__ to prevent prototype pollution + */ +function deepExtend(target, source) { + if (!(source instanceof Object)) { + return source; + } + switch (source.constructor) { + case Date: + // Treat Dates like scalars; if the target date object had any child + // properties - they will be lost! + const dateValue = source; + return new Date(dateValue.getTime()); + case Object: + if (target === undefined) { + target = {}; + } + break; + case Array: + // Always copy the array source and overwrite the target. + target = []; + break; + default: + // Not a plain Object - treat it as a scalar. + return source; + } + for (const prop in source) { + // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202 + if (!source.hasOwnProperty(prop) || !isValidKey(prop)) { + continue; + } + target[prop] = deepExtend(target[prop], source[prop]); + } + return target; +} +function isValidKey(key) { + return key !== '__proto__'; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Polyfill for `globalThis` object. + * @returns the `globalThis` object for the given environment. + * @public + */ +function getGlobal() { + if (typeof self !== 'undefined') { + return self; + } + if (typeof window !== 'undefined') { + return window; + } + if (typeof global !== 'undefined') { + return global; + } + throw new Error('Unable to locate global object.'); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__; +/** + * Attempt to read defaults from a JSON string provided to + * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in + * process(.)env(.)__FIREBASE_DEFAULTS_PATH__ + * The dots are in parens because certain compilers (Vite?) cannot + * handle seeing that variable in comments. + * See https://github.com/firebase/firebase-js-sdk/issues/6838 + */ +const getDefaultsFromEnvVariable = () => { + if (typeof process === 'undefined' || typeof process.env === 'undefined') { + return; + } + const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__; + if (defaultsJsonString) { + return JSON.parse(defaultsJsonString); + } +}; +const getDefaultsFromCookie = () => { + if (typeof document === 'undefined') { + return; + } + let match; + try { + match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/); + } + catch (e) { + // Some environments such as Angular Universal SSR have a + // `document` object but error on accessing `document.cookie`. + return; + } + const decoded = match && base64Decode(match[1]); + return decoded && JSON.parse(decoded); +}; +/** + * Get the __FIREBASE_DEFAULTS__ object. It checks in order: + * (1) if such an object exists as a property of `globalThis` + * (2) if such an object was provided on a shell environment variable + * (3) if such an object exists in a cookie + * @public + */ +const getDefaults = () => { + try { + return (getDefaultsFromPostinstall() || + getDefaultsFromGlobal() || + getDefaultsFromEnvVariable() || + getDefaultsFromCookie()); + } + catch (e) { + /** + * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due + * to any environment case we have not accounted for. Log to + * info instead of swallowing so we can find these unknown cases + * and add paths for them if needed. + */ + console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`); + return; + } +}; +/** + * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object + * for the given product. + * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available + * @public + */ +const getDefaultEmulatorHost = (productName) => getDefaults()?.emulatorHosts?.[productName]; +/** + * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object + * for the given product. + * @returns a pair of hostname and port like `["::1", 4000]` if available + * @public + */ +const getDefaultEmulatorHostnameAndPort = (productName) => { + const host = getDefaultEmulatorHost(productName); + if (!host) { + return undefined; + } + const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons. + if (separatorIndex <= 0 || separatorIndex + 1 === host.length) { + throw new Error(`Invalid host ${host} with no separate hostname and port!`); + } + // eslint-disable-next-line no-restricted-globals + const port = parseInt(host.substring(separatorIndex + 1), 10); + if (host[0] === '[') { + // Bracket-quoted `[ipv6addr]:port` => return "ipv6addr" (without brackets). + return [host.substring(1, separatorIndex - 1), port]; + } + else { + return [host.substring(0, separatorIndex), port]; + } +}; +/** + * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object. + * @public + */ +const getDefaultAppConfig = () => getDefaults()?.config; +/** + * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties + * prefixed by "_") + * @public + */ +const getExperimentalSetting = (name) => getDefaults()?.[`_${name}`]; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Deferred { + constructor() { + this.reject = () => { }; + this.resolve = () => { }; + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } + /** + * Our API internals are not promisified and cannot because our callback APIs have subtle expectations around + * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback + * and returns a node-style callback which will resolve or reject the Deferred's promise. + */ + wrapCallback(callback) { + return (error, value) => { + if (error) { + this.reject(error); + } + else { + this.resolve(value); + } + if (typeof callback === 'function') { + // Attaching noop handler just in case developer wasn't expecting + // promises + this.promise.catch(() => { }); + // Some of our callbacks don't expect a value and our own tests + // assert that the parameter length is 1 + if (callback.length === 1) { + callback(error); + } + else { + callback(error, value); + } + } + }; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Checks whether host is a cloud workstation or not. + * @public + */ +function isCloudWorkstation(url) { + // `isCloudWorkstation` is called without protocol in certain connect*Emulator functions + // In HTTP request builders, it's called with the protocol. + // If called with protocol prefix, it's a valid URL, so we extract the hostname + // If called without, we assume the string is the hostname. + try { + const host = url.startsWith('http://') || url.startsWith('https://') + ? new URL(url).hostname + : url; + return host.endsWith('.cloudworkstations.dev'); + } + catch { + return false; + } +} +/** + * Makes a fetch request to the given server. + * Mostly used for forwarding cookies in Firebase Studio. + * @public + */ +async function pingServer(endpoint) { + const result = await fetch(endpoint, { + credentials: 'include' + }); + return result.ok; +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function createMockUserToken(token, projectId) { + if (token.uid) { + throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.'); + } + // Unsecured JWTs use "none" as the algorithm. + const header = { + alg: 'none', + type: 'JWT' + }; + const project = projectId || 'demo-project'; + const iat = token.iat || 0; + const sub = token.sub || token.user_id; + if (!sub) { + throw new Error("mockUserToken must contain 'sub' or 'user_id' field!"); + } + const payload = { + // Set all required fields to decent defaults + iss: `https://securetoken.google.com/${project}`, + aud: project, + iat, + exp: iat + 3600, + auth_time: iat, + sub, + user_id: sub, + firebase: { + sign_in_provider: 'custom', + identities: {} + }, + // Override with user options + ...token + }; + // Unsecured JWTs use the empty string as a signature. + const signature = ''; + return [ + base64urlEncodeWithoutPadding(JSON.stringify(header)), + base64urlEncodeWithoutPadding(JSON.stringify(payload)), + signature + ].join('.'); +} +const emulatorStatus = {}; +// Checks whether any products are running on an emulator +function getEmulatorSummary() { + const summary = { + prod: [], + emulator: [] + }; + for (const key of Object.keys(emulatorStatus)) { + if (emulatorStatus[key]) { + summary.emulator.push(key); + } + else { + summary.prod.push(key); + } + } + return summary; +} +function getOrCreateEl(id) { + let parentDiv = document.getElementById(id); + let created = false; + if (!parentDiv) { + parentDiv = document.createElement('div'); + parentDiv.setAttribute('id', id); + created = true; + } + return { created, element: parentDiv }; +} +let previouslyDismissed = false; +/** + * Updates Emulator Banner. Primarily used for Firebase Studio + * @param name + * @param isRunningEmulator + * @public + */ +function updateEmulatorBanner(name, isRunningEmulator) { + if (typeof window === 'undefined' || + typeof document === 'undefined' || + !isCloudWorkstation(window.location.host) || + emulatorStatus[name] === isRunningEmulator || + emulatorStatus[name] || // If already set to use emulator, can't go back to prod. + previouslyDismissed) { + return; + } + emulatorStatus[name] = isRunningEmulator; + function prefixedId(id) { + return `__firebase__banner__${id}`; + } + const bannerId = '__firebase__banner'; + const summary = getEmulatorSummary(); + const showError = summary.prod.length > 0; + function tearDown() { + const element = document.getElementById(bannerId); + if (element) { + element.remove(); + } + } + function setupBannerStyles(bannerEl) { + bannerEl.style.display = 'flex'; + bannerEl.style.background = '#7faaf0'; + bannerEl.style.position = 'fixed'; + bannerEl.style.bottom = '5px'; + bannerEl.style.left = '5px'; + bannerEl.style.padding = '.5em'; + bannerEl.style.borderRadius = '5px'; + bannerEl.style.alignItems = 'center'; + } + function setupIconStyles(prependIcon, iconId) { + prependIcon.setAttribute('width', '24'); + prependIcon.setAttribute('id', iconId); + prependIcon.setAttribute('height', '24'); + prependIcon.setAttribute('viewBox', '0 0 24 24'); + prependIcon.setAttribute('fill', 'none'); + prependIcon.style.marginLeft = '-6px'; + } + function setupCloseBtn() { + const closeBtn = document.createElement('span'); + closeBtn.style.cursor = 'pointer'; + closeBtn.style.marginLeft = '16px'; + closeBtn.style.fontSize = '24px'; + closeBtn.innerHTML = ' ×'; + closeBtn.onclick = () => { + previouslyDismissed = true; + tearDown(); + }; + return closeBtn; + } + function setupLinkStyles(learnMoreLink, learnMoreId) { + learnMoreLink.setAttribute('id', learnMoreId); + learnMoreLink.innerText = 'Learn more'; + learnMoreLink.href = + 'https://firebase.google.com/docs/studio/preview-apps#preview-backend'; + learnMoreLink.setAttribute('target', '__blank'); + learnMoreLink.style.paddingLeft = '5px'; + learnMoreLink.style.textDecoration = 'underline'; + } + function setupDom() { + const banner = getOrCreateEl(bannerId); + const firebaseTextId = prefixedId('text'); + const firebaseText = document.getElementById(firebaseTextId) || document.createElement('span'); + const learnMoreId = prefixedId('learnmore'); + const learnMoreLink = document.getElementById(learnMoreId) || + document.createElement('a'); + const prependIconId = prefixedId('preprendIcon'); + const prependIcon = document.getElementById(prependIconId) || + document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + if (banner.created) { + // update styles + const bannerEl = banner.element; + setupBannerStyles(bannerEl); + setupLinkStyles(learnMoreLink, learnMoreId); + const closeBtn = setupCloseBtn(); + setupIconStyles(prependIcon, prependIconId); + bannerEl.append(prependIcon, firebaseText, learnMoreLink, closeBtn); + document.body.appendChild(bannerEl); + } + if (showError) { + firebaseText.innerText = `Preview backend disconnected.`; + prependIcon.innerHTML = ` + + + + + + +`; + } + else { + prependIcon.innerHTML = ` + + + + + + +`; + firebaseText.innerText = 'Preview backend running in this workspace.'; + } + firebaseText.setAttribute('id', firebaseTextId); + } + if (document.readyState === 'loading') { + window.addEventListener('DOMContentLoaded', setupDom); + } + else { + setupDom(); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns navigator.userAgent string or '' if it's not defined. + * @return user agent string + */ +function getUA() { + if (typeof navigator !== 'undefined' && + typeof navigator['userAgent'] === 'string') { + return navigator['userAgent']; + } + else { + return ''; + } +} +/** + * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device. + * + * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap + * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally + * wait for a callback. + */ +function isMobileCordova() { + return (typeof window !== 'undefined' && + // @ts-ignore Setting up an broadly applicable index signature for Window + // just to deal with this case would probably be a bad idea. + !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) && + /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())); +} +/** + * Detect Node.js. + * + * @return true if Node.js environment is detected or specified. + */ +// Node detection logic from: https://github.com/iliakan/detect-node/ +function isNode() { + const forceEnvironment = getDefaults()?.forceEnvironment; + if (forceEnvironment === 'node') { + return true; + } + else if (forceEnvironment === 'browser') { + return false; + } + try { + return (Object.prototype.toString.call(global.process) === '[object process]'); + } + catch (e) { + return false; + } +} +/** + * Detect Browser Environment. + * Note: This will return true for certain test frameworks that are incompletely + * mimicking a browser, and should not lead to assuming all browser APIs are + * available. + */ +function isBrowser() { + return typeof window !== 'undefined' || isWebWorker(); +} +/** + * Detect Web Worker context. + */ +function isWebWorker() { + return (typeof WorkerGlobalScope !== 'undefined' && + typeof self !== 'undefined' && + self instanceof WorkerGlobalScope); +} +/** + * Detect Cloudflare Worker context. + */ +function isCloudflareWorker() { + return (typeof navigator !== 'undefined' && + navigator.userAgent === 'Cloudflare-Workers'); +} +function isBrowserExtension() { + const runtime = typeof chrome === 'object' + ? chrome.runtime + : typeof browser === 'object' + ? browser.runtime + : undefined; + return typeof runtime === 'object' && runtime.id !== undefined; +} +/** + * Detect React Native. + * + * @return true if ReactNative environment is detected. + */ +function isReactNative() { + return (typeof navigator === 'object' && navigator['product'] === 'ReactNative'); +} +/** Detects Electron apps. */ +function isElectron() { + return getUA().indexOf('Electron/') >= 0; +} +/** Detects Internet Explorer. */ +function isIE() { + const ua = getUA(); + return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0; +} +/** Detects Universal Windows Platform apps. */ +function isUWP() { + return getUA().indexOf('MSAppHost/') >= 0; +} +/** + * Detect whether the current SDK build is the Node version. + * + * @return true if it's the Node SDK build. + */ +function isNodeSdk() { + return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true; +} +/** Returns true if we are running in Safari. */ +function isSafari() { + return (!isNode() && + !!navigator.userAgent && + navigator.userAgent.includes('Safari') && + !navigator.userAgent.includes('Chrome')); +} +/** Returns true if we are running in Safari or WebKit */ +function isSafariOrWebkit() { + return (!isNode() && + !!navigator.userAgent && + (navigator.userAgent.includes('Safari') || + navigator.userAgent.includes('WebKit')) && + !navigator.userAgent.includes('Chrome')); +} +/** + * This method checks if indexedDB is supported by current browser/service worker context + * @return true if indexedDB is supported by current browser/service worker context + */ +function isIndexedDBAvailable() { + try { + return typeof indexedDB === 'object'; + } + catch (e) { + return false; + } +} +/** + * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject + * if errors occur during the database open operation. + * + * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox + * private browsing) + */ +function validateIndexedDBOpenable() { + return new Promise((resolve, reject) => { + try { + let preExist = true; + const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module'; + const request = self.indexedDB.open(DB_CHECK_NAME); + request.onsuccess = () => { + request.result.close(); + // delete database only when it doesn't pre-exist + if (!preExist) { + self.indexedDB.deleteDatabase(DB_CHECK_NAME); + } + resolve(true); + }; + request.onupgradeneeded = () => { + preExist = false; + }; + request.onerror = () => { + reject(request.error?.message || ''); + }; + } + catch (error) { + reject(error); + } + }); +} +/** + * + * This method checks whether cookie is enabled within current browser + * @return true if cookie is enabled within current browser + */ +function areCookiesEnabled() { + if (typeof navigator === 'undefined' || !navigator.cookieEnabled) { + return false; + } + return true; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview Standardized Firebase Error. + * + * Usage: + * + * // TypeScript string literals for type-safe codes + * type Err = + * 'unknown' | + * 'object-not-found' + * ; + * + * // Closure enum for type-safe error codes + * // at-enum {string} + * var Err = { + * UNKNOWN: 'unknown', + * OBJECT_NOT_FOUND: 'object-not-found', + * } + * + * let errors: Map = { + * 'generic-error': "Unknown error", + * 'file-not-found': "Could not find file: {$file}", + * }; + * + * // Type-safe function - must pass a valid error code as param. + * let error = new ErrorFactory('service', 'Service', errors); + * + * ... + * throw error.create(Err.GENERIC); + * ... + * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName}); + * ... + * // Service: Could not file file: foo.txt (service/file-not-found). + * + * catch (e) { + * assert(e.message === "Could not find file: foo.txt."); + * if ((e as FirebaseError)?.code === 'service/file-not-found') { + * console.log("Could not read file: " + e['file']); + * } + * } + */ +const ERROR_NAME = 'FirebaseError'; +// Based on code from: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types +class FirebaseError extends Error { + constructor( + /** The error code for this error. */ + code, message, + /** Custom data for this error. */ + customData) { + super(message); + this.code = code; + this.customData = customData; + /** The custom name for all FirebaseErrors. */ + this.name = ERROR_NAME; + // Fix For ES5 + // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work + // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget + // which we can now use since we no longer target ES5. + Object.setPrototypeOf(this, FirebaseError.prototype); + // Maintains proper stack trace for where our error was thrown. + // Only available on V8. + if (Error.captureStackTrace) { + Error.captureStackTrace(this, ErrorFactory.prototype.create); + } + } +} +class ErrorFactory { + constructor(service, serviceName, errors) { + this.service = service; + this.serviceName = serviceName; + this.errors = errors; + } + create(code, ...data) { + const customData = data[0] || {}; + const fullCode = `${this.service}/${code}`; + const template = this.errors[code]; + const message = template ? replaceTemplate(template, customData) : 'Error'; + // Service Name: Error message (service/code). + const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`; + const error = new FirebaseError(fullCode, fullMessage, customData); + return error; + } +} +function replaceTemplate(template, data) { + return template.replace(PATTERN, (_, key) => { + const value = data[key]; + return value != null ? String(value) : `<${key}?>`; + }); +} +const PATTERN = /\{\$([^}]+)}/g; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Evaluates a JSON string into a javascript object. + * + * @param {string} str A string containing JSON. + * @return {*} The javascript object representing the specified JSON. + */ +function jsonEval(str) { + return JSON.parse(str); +} +/** + * Returns JSON representing a javascript object. + * @param {*} data JavaScript object to be stringified. + * @return {string} The JSON contents of the object. + */ +function stringify(data) { + return JSON.stringify(data); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Decodes a Firebase auth. token into constituent parts. + * + * Notes: + * - May return with invalid / incomplete claims if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +const decode = function (token) { + let header = {}, claims = {}, data = {}, signature = ''; + try { + const parts = token.split('.'); + header = jsonEval(base64Decode(parts[0]) || ''); + claims = jsonEval(base64Decode(parts[1]) || ''); + signature = parts[2]; + data = claims['d'] || {}; + delete claims['d']; + } + catch (e) { } + return { + header, + claims, + data, + signature + }; +}; +/** + * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the + * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +const isValidTimestamp = function (token) { + const claims = decode(token).claims; + const now = Math.floor(new Date().getTime() / 1000); + let validSince = 0, validUntil = 0; + if (typeof claims === 'object') { + if (claims.hasOwnProperty('nbf')) { + validSince = claims['nbf']; + } + else if (claims.hasOwnProperty('iat')) { + validSince = claims['iat']; + } + if (claims.hasOwnProperty('exp')) { + validUntil = claims['exp']; + } + else { + // token will expire after 24h by default + validUntil = validSince + 86400; + } + } + return (!!now && + !!validSince && + !!validUntil && + now >= validSince && + now <= validUntil); +}; +/** + * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise. + * + * Notes: + * - May return null if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +const issuedAtTime = function (token) { + const claims = decode(token).claims; + if (typeof claims === 'object' && claims.hasOwnProperty('iat')) { + return claims['iat']; + } + return null; +}; +/** + * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +const isValidFormat = function (token) { + const decoded = decode(token), claims = decoded.claims; + return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat'); +}; +/** + * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +const isAdmin = function (token) { + const claims = decode(token).claims; + return typeof claims === 'object' && claims['admin'] === true; +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function contains(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +function safeGet(obj, key) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + return obj[key]; + } + else { + return undefined; + } +} +function isEmpty(obj) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + return false; + } + } + return true; +} +function map(obj, fn, contextObj) { + const res = {}; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + res[key] = fn.call(contextObj, obj[key], key, obj); + } + } + return res; +} +/** + * Deep equal two objects. Support Arrays and Objects. + */ +function deepEqual(a, b) { + if (a === b) { + return true; + } + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + for (const k of aKeys) { + if (!bKeys.includes(k)) { + return false; + } + const aProp = a[k]; + const bProp = b[k]; + if (isObject(aProp) && isObject(bProp)) { + if (!deepEqual(aProp, bProp)) { + return false; + } + } + else if (aProp !== bProp) { + return false; + } + } + for (const k of bKeys) { + if (!aKeys.includes(k)) { + return false; + } + } + return true; +} +function isObject(thing) { + return thing !== null && typeof thing === 'object'; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Rejects if the given promise doesn't resolve in timeInMS milliseconds. + * @internal + */ +function promiseWithTimeout(promise, timeInMS = 2000) { + const deferredPromise = new Deferred(); + setTimeout(() => deferredPromise.reject('timeout!'), timeInMS); + promise.then(deferredPromise.resolve, deferredPromise.reject); + return deferredPromise.promise; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a + * params object (e.g. {arg: 'val', arg2: 'val2'}) + * Note: You must prepend it with ? when adding it to a URL. + */ +function querystring(querystringParams) { + const params = []; + for (const [key, value] of Object.entries(querystringParams)) { + if (Array.isArray(value)) { + value.forEach(arrayVal => { + params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal)); + }); + } + else { + params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); + } + } + return params.length ? '&' + params.join('&') : ''; +} +/** + * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object + * (e.g. {arg: 'val', arg2: 'val2'}) + */ +function querystringDecode(querystring) { + const obj = {}; + const tokens = querystring.replace(/^\?/, '').split('&'); + tokens.forEach(token => { + if (token) { + const [key, value] = token.split('='); + obj[decodeURIComponent(key)] = decodeURIComponent(value); + } + }); + return obj; +} +/** + * Extract the query string part of a URL, including the leading question mark (if present). + */ +function extractQuerystring(url) { + const queryStart = url.indexOf('?'); + if (!queryStart) { + return ''; + } + const fragmentStart = url.indexOf('#', queryStart); + return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview SHA-1 cryptographic hash. + * Variable names follow the notation in FIPS PUB 180-3: + * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf. + * + * Usage: + * var sha1 = new sha1(); + * sha1.update(bytes); + * var hash = sha1.digest(); + * + * Performance: + * Chrome 23: ~400 Mbit/s + * Firefox 16: ~250 Mbit/s + * + */ +/** + * SHA-1 cryptographic hash constructor. + * + * The properties declared here are discussed in the above algorithm document. + * @constructor + * @final + * @struct + */ +class Sha1 { + constructor() { + /** + * Holds the previous values of accumulated variables a-e in the compress_ + * function. + * @private + */ + this.chain_ = []; + /** + * A buffer holding the partially computed hash result. + * @private + */ + this.buf_ = []; + /** + * An array of 80 bytes, each a part of the message to be hashed. Referred to + * as the message schedule in the docs. + * @private + */ + this.W_ = []; + /** + * Contains data needed to pad messages less than 64 bytes. + * @private + */ + this.pad_ = []; + /** + * @private {number} + */ + this.inbuf_ = 0; + /** + * @private {number} + */ + this.total_ = 0; + this.blockSize = 512 / 8; + this.pad_[0] = 128; + for (let i = 1; i < this.blockSize; ++i) { + this.pad_[i] = 0; + } + this.reset(); + } + reset() { + this.chain_[0] = 0x67452301; + this.chain_[1] = 0xefcdab89; + this.chain_[2] = 0x98badcfe; + this.chain_[3] = 0x10325476; + this.chain_[4] = 0xc3d2e1f0; + this.inbuf_ = 0; + this.total_ = 0; + } + /** + * Internal compress helper function. + * @param buf Block to compress. + * @param offset Offset of the block in the buffer. + * @private + */ + compress_(buf, offset) { + if (!offset) { + offset = 0; + } + const W = this.W_; + // get 16 big endian words + if (typeof buf === 'string') { + for (let i = 0; i < 16; i++) { + // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS + // have a bug that turns the post-increment ++ operator into pre-increment + // during JIT compilation. We have code that depends heavily on SHA-1 for + // correctness and which is affected by this bug, so I've removed all uses + // of post-increment ++ in which the result value is used. We can revert + // this change once the Safari bug + // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and + // most clients have been updated. + W[i] = + (buf.charCodeAt(offset) << 24) | + (buf.charCodeAt(offset + 1) << 16) | + (buf.charCodeAt(offset + 2) << 8) | + buf.charCodeAt(offset + 3); + offset += 4; + } + } + else { + for (let i = 0; i < 16; i++) { + W[i] = + (buf[offset] << 24) | + (buf[offset + 1] << 16) | + (buf[offset + 2] << 8) | + buf[offset + 3]; + offset += 4; + } + } + // expand to 80 words + for (let i = 16; i < 80; i++) { + const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff; + } + let a = this.chain_[0]; + let b = this.chain_[1]; + let c = this.chain_[2]; + let d = this.chain_[3]; + let e = this.chain_[4]; + let f, k; + // TODO(user): Try to unroll this loop to speed up the computation. + for (let i = 0; i < 80; i++) { + if (i < 40) { + if (i < 20) { + f = d ^ (b & (c ^ d)); + k = 0x5a827999; + } + else { + f = b ^ c ^ d; + k = 0x6ed9eba1; + } + } + else { + if (i < 60) { + f = (b & c) | (d & (b | c)); + k = 0x8f1bbcdc; + } + else { + f = b ^ c ^ d; + k = 0xca62c1d6; + } + } + const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff; + e = d; + d = c; + c = ((b << 30) | (b >>> 2)) & 0xffffffff; + b = a; + a = t; + } + this.chain_[0] = (this.chain_[0] + a) & 0xffffffff; + this.chain_[1] = (this.chain_[1] + b) & 0xffffffff; + this.chain_[2] = (this.chain_[2] + c) & 0xffffffff; + this.chain_[3] = (this.chain_[3] + d) & 0xffffffff; + this.chain_[4] = (this.chain_[4] + e) & 0xffffffff; + } + update(bytes, length) { + // TODO(johnlenz): tighten the function signature and remove this check + if (bytes == null) { + return; + } + if (length === undefined) { + length = bytes.length; + } + const lengthMinusBlock = length - this.blockSize; + let n = 0; + // Using local instead of member variables gives ~5% speedup on Firefox 16. + const buf = this.buf_; + let inbuf = this.inbuf_; + // The outer while loop should execute at most twice. + while (n < length) { + // When we have no data in the block to top up, we can directly process the + // input buffer (assuming it contains sufficient data). This gives ~25% + // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that + // the data is provided in large chunks (or in multiples of 64 bytes). + if (inbuf === 0) { + while (n <= lengthMinusBlock) { + this.compress_(bytes, n); + n += this.blockSize; + } + } + if (typeof bytes === 'string') { + while (n < length) { + buf[inbuf] = bytes.charCodeAt(n); + ++inbuf; + ++n; + if (inbuf === this.blockSize) { + this.compress_(buf); + inbuf = 0; + // Jump to the outer loop so we use the full-block optimization. + break; + } + } + } + else { + while (n < length) { + buf[inbuf] = bytes[n]; + ++inbuf; + ++n; + if (inbuf === this.blockSize) { + this.compress_(buf); + inbuf = 0; + // Jump to the outer loop so we use the full-block optimization. + break; + } + } + } + } + this.inbuf_ = inbuf; + this.total_ += length; + } + /** @override */ + digest() { + const digest = []; + let totalBits = this.total_ * 8; + // Add pad 0x80 0x00*. + if (this.inbuf_ < 56) { + this.update(this.pad_, 56 - this.inbuf_); + } + else { + this.update(this.pad_, this.blockSize - (this.inbuf_ - 56)); + } + // Add # bits. + for (let i = this.blockSize - 1; i >= 56; i--) { + this.buf_[i] = totalBits & 255; + totalBits /= 256; // Don't use bit-shifting here! + } + this.compress_(this.buf_); + let n = 0; + for (let i = 0; i < 5; i++) { + for (let j = 24; j >= 0; j -= 8) { + digest[n] = (this.chain_[i] >> j) & 255; + ++n; + } + } + return digest; + } +} + +/** + * Helper to make a Subscribe function (just like Promise helps make a + * Thenable). + * + * @param executor Function which can make calls to a single Observer + * as a proxy. + * @param onNoObservers Callback when count of Observers goes to zero. + */ +function createSubscribe(executor, onNoObservers) { + const proxy = new ObserverProxy(executor, onNoObservers); + return proxy.subscribe.bind(proxy); +} +/** + * Implement fan-out for any number of Observers attached via a subscribe + * function. + */ +class ObserverProxy { + /** + * @param executor Function which can make calls to a single Observer + * as a proxy. + * @param onNoObservers Callback when count of Observers goes to zero. + */ + constructor(executor, onNoObservers) { + this.observers = []; + this.unsubscribes = []; + this.observerCount = 0; + // Micro-task scheduling by calling task.then(). + this.task = Promise.resolve(); + this.finalized = false; + this.onNoObservers = onNoObservers; + // Call the executor asynchronously so subscribers that are called + // synchronously after the creation of the subscribe function + // can still receive the very first value generated in the executor. + this.task + .then(() => { + executor(this); + }) + .catch(e => { + this.error(e); + }); + } + next(value) { + this.forEachObserver((observer) => { + observer.next(value); + }); + } + error(error) { + this.forEachObserver((observer) => { + observer.error(error); + }); + this.close(error); + } + complete() { + this.forEachObserver((observer) => { + observer.complete(); + }); + this.close(); + } + /** + * Subscribe function that can be used to add an Observer to the fan-out list. + * + * - We require that no event is sent to a subscriber synchronously to their + * call to subscribe(). + */ + subscribe(nextOrObserver, error, complete) { + let observer; + if (nextOrObserver === undefined && + error === undefined && + complete === undefined) { + throw new Error('Missing Observer.'); + } + // Assemble an Observer object when passed as callback functions. + if (implementsAnyMethods(nextOrObserver, [ + 'next', + 'error', + 'complete' + ])) { + observer = nextOrObserver; + } + else { + observer = { + next: nextOrObserver, + error, + complete + }; + } + if (observer.next === undefined) { + observer.next = noop; + } + if (observer.error === undefined) { + observer.error = noop; + } + if (observer.complete === undefined) { + observer.complete = noop; + } + const unsub = this.unsubscribeOne.bind(this, this.observers.length); + // Attempt to subscribe to a terminated Observable - we + // just respond to the Observer with the final error or complete + // event. + if (this.finalized) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.task.then(() => { + try { + if (this.finalError) { + observer.error(this.finalError); + } + else { + observer.complete(); + } + } + catch (e) { + // nothing + } + return; + }); + } + this.observers.push(observer); + return unsub; + } + // Unsubscribe is synchronous - we guarantee that no events are sent to + // any unsubscribed Observer. + unsubscribeOne(i) { + if (this.observers === undefined || this.observers[i] === undefined) { + return; + } + delete this.observers[i]; + this.observerCount -= 1; + if (this.observerCount === 0 && this.onNoObservers !== undefined) { + this.onNoObservers(this); + } + } + forEachObserver(fn) { + if (this.finalized) { + // Already closed by previous event....just eat the additional values. + return; + } + // Since sendOne calls asynchronously - there is no chance that + // this.observers will become undefined. + for (let i = 0; i < this.observers.length; i++) { + this.sendOne(i, fn); + } + } + // Call the Observer via one of it's callback function. We are careful to + // confirm that the observe has not been unsubscribed since this asynchronous + // function had been queued. + sendOne(i, fn) { + // Execute the callback asynchronously + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.task.then(() => { + if (this.observers !== undefined && this.observers[i] !== undefined) { + try { + fn(this.observers[i]); + } + catch (e) { + // Ignore exceptions raised in Observers or missing methods of an + // Observer. + // Log error to console. b/31404806 + if (typeof console !== 'undefined' && console.error) { + console.error(e); + } + } + } + }); + } + close(err) { + if (this.finalized) { + return; + } + this.finalized = true; + if (err !== undefined) { + this.finalError = err; + } + // Proxy is no longer needed - garbage collect references + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.task.then(() => { + this.observers = undefined; + this.onNoObservers = undefined; + }); + } +} +/** Turn synchronous function into one called asynchronously. */ +// eslint-disable-next-line @typescript-eslint/ban-types +function async(fn, onError) { + return (...args) => { + Promise.resolve(true) + .then(() => { + fn(...args); + }) + .catch((error) => { + if (onError) { + onError(error); + } + }); + }; +} +/** + * Return true if the object passed in implements any of the named methods. + */ +function implementsAnyMethods(obj, methods) { + if (typeof obj !== 'object' || obj === null) { + return false; + } + for (const method of methods) { + if (method in obj && typeof obj[method] === 'function') { + return true; + } + } + return false; +} +function noop() { + // do nothing +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Check to make sure the appropriate number of arguments are provided for a public function. + * Throws an error if it fails. + * + * @param fnName The function name + * @param minCount The minimum number of arguments to allow for the function call + * @param maxCount The maximum number of argument to allow for the function call + * @param argCount The actual number of arguments provided. + */ +const validateArgCount = function (fnName, minCount, maxCount, argCount) { + let argError; + if (argCount < minCount) { + argError = 'at least ' + minCount; + } + else if (argCount > maxCount) { + argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount; + } + if (argError) { + const error = fnName + + ' failed: Was called with ' + + argCount + + (argCount === 1 ? ' argument.' : ' arguments.') + + ' Expects ' + + argError + + '.'; + throw new Error(error); + } +}; +/** + * Generates a string to prefix an error message about failed argument validation + * + * @param fnName The function name + * @param argName The name of the argument + * @return The prefix to add to the error thrown for validation. + */ +function errorPrefix(fnName, argName) { + return `${fnName} failed: ${argName} argument `; +} +/** + * @param fnName + * @param argumentNumber + * @param namespace + * @param optional + */ +function validateNamespace(fnName, namespace, optional) { + if (optional && !namespace) { + return; + } + if (typeof namespace !== 'string') { + //TODO: I should do more validation here. We only allow certain chars in namespaces. + throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.'); + } +} +function validateCallback(fnName, argumentName, +// eslint-disable-next-line @typescript-eslint/ban-types +callback, optional) { + if (optional && !callback) { + return; + } + if (typeof callback !== 'function') { + throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.'); + } +} +function validateContextObject(fnName, argumentName, context, optional) { + if (optional && !context) { + return; + } + if (typeof context !== 'object' || context === null) { + throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they +// automatically replaced '\r\n' with '\n', and they didn't handle surrogate pairs, +// so it's been modified. +// Note that not all Unicode characters appear as single characters in JavaScript strings. +// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters +// use 2 characters in JavaScript. All 4-byte UTF-8 characters begin with a first +// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate +// pair). +// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3 +/** + * @param {string} str + * @return {Array} + */ +const stringToByteArray = function (str) { + const out = []; + let p = 0; + for (let i = 0; i < str.length; i++) { + let c = str.charCodeAt(i); + // Is this the lead surrogate in a surrogate pair? + if (c >= 0xd800 && c <= 0xdbff) { + const high = c - 0xd800; // the high 10 bits. + i++; + assert(i < str.length, 'Surrogate pair missing trail surrogate.'); + const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits. + c = 0x10000 + (high << 10) + low; + } + if (c < 128) { + out[p++] = c; + } + else if (c < 2048) { + out[p++] = (c >> 6) | 192; + out[p++] = (c & 63) | 128; + } + else if (c < 65536) { + out[p++] = (c >> 12) | 224; + out[p++] = ((c >> 6) & 63) | 128; + out[p++] = (c & 63) | 128; + } + else { + out[p++] = (c >> 18) | 240; + out[p++] = ((c >> 12) & 63) | 128; + out[p++] = ((c >> 6) & 63) | 128; + out[p++] = (c & 63) | 128; + } + } + return out; +}; +/** + * Calculate length without actually converting; useful for doing cheaper validation. + * @param {string} str + * @return {number} + */ +const stringLength = function (str) { + let p = 0; + for (let i = 0; i < str.length; i++) { + const c = str.charCodeAt(i); + if (c < 128) { + p++; + } + else if (c < 2048) { + p += 2; + } + else if (c >= 0xd800 && c <= 0xdbff) { + // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent. + p += 4; + i++; // skip trail surrogate. + } + else { + p += 3; + } + } + return p; +}; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The amount of milliseconds to exponentially increase. + */ +const DEFAULT_INTERVAL_MILLIS = 1000; +/** + * The factor to backoff by. + * Should be a number greater than 1. + */ +const DEFAULT_BACKOFF_FACTOR = 2; +/** + * The maximum milliseconds to increase to. + * + *

Visible for testing + */ +const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android. +/** + * The percentage of backoff time to randomize by. + * See + * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic + * for context. + * + *

Visible for testing + */ +const RANDOM_FACTOR = 0.5; +/** + * Based on the backoff method from + * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js. + * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around. + */ +function calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) { + // Calculates an exponentially increasing value. + // Deviation: calculates value from count and a constant interval, so we only need to save value + // and count to restore state. + const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount); + // A random "fuzz" to avoid waves of retries. + // Deviation: randomFactor is required. + const randomWait = Math.round( + // A fraction of the backoff value to add/subtract. + // Deviation: changes multiplication order to improve readability. + RANDOM_FACTOR * + currBaseValue * + // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines + // if we add or subtract. + (Math.random() - 0.5) * + 2); + // Limits backoff to max to avoid effectively permanent backoff. + return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provide English ordinal letters after a number + */ +function ordinal(i) { + if (!Number.isFinite(i)) { + return `${i}`; + } + return i + indicator(i); +} +function indicator(i) { + i = Math.abs(i); + const cent = i % 100; + if (cent >= 10 && cent <= 20) { + return 'th'; + } + const dec = i % 10; + if (dec === 1) { + return 'st'; + } + if (dec === 2) { + return 'nd'; + } + if (dec === 3) { + return 'rd'; + } + return 'th'; +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function getModularInstance(service) { + if (service && service._delegate) { + return service._delegate; + } + else { + return service; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Overriding the constant (we should be the only ones doing this) +CONSTANTS.NODE_CLIENT = true; + +export { CONSTANTS, DecodeBase64StringError, Deferred, ErrorFactory, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getDefaultAppConfig, getDefaultEmulatorHost, getDefaultEmulatorHostnameAndPort, getDefaults, getExperimentalSetting, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isCloudWorkstation, isCloudflareWorker, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isSafariOrWebkit, isUWP, isValidFormat, isValidTimestamp, isWebWorker, issuedAtTime, jsonEval, map, ordinal, pingServer, promiseWithTimeout, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, updateEmulatorBanner, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace }; +//# sourceMappingURL=index.node.esm.js.map diff --git a/node_modules/@firebase/util/dist/node-esm/index.node.esm.js.map b/node_modules/@firebase/util/dist/node-esm/index.node.esm.js.map new file mode 100644 index 0000000..ffe1ab3 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/index.node.esm.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.node.esm.js","sources":["../../src/constants.ts","../../src/assert.ts","../../src/crypt.ts","../../src/deepCopy.ts","../../src/global.ts","../../src/defaults.ts","../../src/deferred.ts","../../src/url.ts","../../src/emulator.ts","../../src/environment.ts","../../src/errors.ts","../../src/json.ts","../../src/jwt.ts","../../src/obj.ts","../../src/promise.ts","../../src/query.ts","../../src/sha1.ts","../../src/subscribe.ts","../../src/validation.ts","../../src/utf8.ts","../../src/exponential_backoff.ts","../../src/formatters.ts","../../src/compat.ts","../../index.node.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\n */\n\nexport const CONSTANTS = {\n /**\n * @define {boolean} Whether this is the client Node.js SDK.\n */\n NODE_CLIENT: false,\n /**\n * @define {boolean} Whether this is the Admin Node.js SDK.\n */\n NODE_ADMIN: false,\n\n /**\n * Firebase SDK Version\n */\n SDK_VERSION: '${JSCORE_VERSION}'\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSTANTS } from './constants';\n\n/**\n * Throws an error if the provided assertion is falsy\n */\nexport const assert = function (assertion: unknown, message: string): void {\n if (!assertion) {\n throw assertionError(message);\n }\n};\n\n/**\n * Returns an Error object suitable for throwing.\n */\nexport const assertionError = function (message: string): Error {\n return new Error(\n 'Firebase Database (' +\n CONSTANTS.SDK_VERSION +\n ') INTERNAL ASSERT FAILED: ' +\n message\n );\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst stringToByteArray = function (str: string): number[] {\n // TODO(user): Use native implementations if/when available\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (\n (c & 0xfc00) === 0xd800 &&\n i + 1 < str.length &&\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00\n ) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param bytes Array of numbers representing characters.\n * @return Stringification of the array.\n */\nconst byteArrayToString = function (bytes: number[]): string {\n // TODO(user): Use native implementations if/when available\n const out: string[] = [];\n let pos = 0,\n c = 0;\n while (pos < bytes.length) {\n const c1 = bytes[pos++];\n if (c1 < 128) {\n out[c++] = String.fromCharCode(c1);\n } else if (c1 > 191 && c1 < 224) {\n const c2 = bytes[pos++];\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n } else if (c1 > 239 && c1 < 365) {\n // Surrogate Pair\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n const c4 = bytes[pos++];\n const u =\n (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n 0x10000;\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n } else {\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n out[c++] = String.fromCharCode(\n ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)\n );\n }\n }\n return out.join('');\n};\n\ninterface Base64 {\n byteToCharMap_: { [key: number]: string } | null;\n charToByteMap_: { [key: string]: number } | null;\n byteToCharMapWebSafe_: { [key: number]: string } | null;\n charToByteMapWebSafe_: { [key: string]: number } | null;\n ENCODED_VALS_BASE: string;\n readonly ENCODED_VALS: string;\n readonly ENCODED_VALS_WEBSAFE: string;\n HAS_NATIVE_SUPPORT: boolean;\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string;\n encodeString(input: string, webSafe?: boolean): string;\n decodeString(input: string, webSafe: boolean): string;\n decodeStringToByteArray(input: string, webSafe: boolean): number[];\n init_(): void;\n}\n\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\n// Static lookup maps, lazily populated by init_()\n// TODO(dlarocque): Define this as a class, since we no longer target ES5.\nexport const base64: Base64 = {\n /**\n * Maps bytes to characters.\n */\n byteToCharMap_: null,\n\n /**\n * Maps characters to bytes.\n */\n charToByteMap_: null,\n\n /**\n * Maps bytes to websafe characters.\n * @private\n */\n byteToCharMapWebSafe_: null,\n\n /**\n * Maps websafe characters to bytes.\n * @private\n */\n charToByteMapWebSafe_: null,\n\n /**\n * Our default alphabet, shared between\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n */\n ENCODED_VALS_BASE:\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n\n /**\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n */\n get ENCODED_VALS() {\n return this.ENCODED_VALS_BASE + '+/=';\n },\n\n /**\n * Our websafe alphabet.\n */\n get ENCODED_VALS_WEBSAFE() {\n return this.ENCODED_VALS_BASE + '-_.';\n },\n\n /**\n * Whether this browser supports the atob and btoa functions. This extension\n * started at Mozilla but is now implemented by many browsers. We use the\n * ASSUME_* variables to avoid pulling in the full useragent detection library\n * but still allowing the standard per-browser compilations.\n *\n */\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\n\n /**\n * Base64-encode an array of bytes.\n *\n * @param input An array of bytes (numbers with\n * value in [0, 255]) to encode.\n * @param webSafe Boolean indicating we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string {\n if (!Array.isArray(input)) {\n throw Error('encodeByteArray takes an array as a parameter');\n }\n\n this.init_();\n\n const byteToCharMap = webSafe\n ? this.byteToCharMapWebSafe_!\n : this.byteToCharMap_!;\n\n const output = [];\n\n for (let i = 0; i < input.length; i += 3) {\n const byte1 = input[i];\n const haveByte2 = i + 1 < input.length;\n const byte2 = haveByte2 ? input[i + 1] : 0;\n const haveByte3 = i + 2 < input.length;\n const byte3 = haveByte3 ? input[i + 2] : 0;\n\n const outByte1 = byte1 >> 2;\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n let outByte4 = byte3 & 0x3f;\n\n if (!haveByte3) {\n outByte4 = 64;\n\n if (!haveByte2) {\n outByte3 = 64;\n }\n }\n\n output.push(\n byteToCharMap[outByte1],\n byteToCharMap[outByte2],\n byteToCharMap[outByte3],\n byteToCharMap[outByte4]\n );\n }\n\n return output.join('');\n },\n\n /**\n * Base64-encode a string.\n *\n * @param input A string to encode.\n * @param webSafe If true, we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeString(input: string, webSafe?: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return btoa(input);\n }\n return this.encodeByteArray(stringToByteArray(input), webSafe);\n },\n\n /**\n * Base64-decode a string.\n *\n * @param input to decode.\n * @param webSafe True if we should use the\n * alternative alphabet.\n * @return string representing the decoded value.\n */\n decodeString(input: string, webSafe: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return atob(input);\n }\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\n },\n\n /**\n * Base64-decode a string.\n *\n * In base-64 decoding, groups of four characters are converted into three\n * bytes. If the encoder did not apply padding, the input length may not\n * be a multiple of 4.\n *\n * In this case, the last group will have fewer than 4 characters, and\n * padding will be inferred. If the group has one or two characters, it decodes\n * to one byte. If the group has three characters, it decodes to two bytes.\n *\n * @param input Input to decode.\n * @param webSafe True if we should use the web-safe alphabet.\n * @return bytes representing the decoded value.\n */\n decodeStringToByteArray(input: string, webSafe: boolean): number[] {\n this.init_();\n\n const charToByteMap = webSafe\n ? this.charToByteMapWebSafe_!\n : this.charToByteMap_!;\n\n const output: number[] = [];\n\n for (let i = 0; i < input.length; ) {\n const byte1 = charToByteMap[input.charAt(i++)];\n\n const haveByte2 = i < input.length;\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n ++i;\n\n const haveByte3 = i < input.length;\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n const haveByte4 = i < input.length;\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n throw new DecodeBase64StringError();\n }\n\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\n output.push(outByte1);\n\n if (byte3 !== 64) {\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n output.push(outByte2);\n\n if (byte4 !== 64) {\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n output.push(outByte3);\n }\n }\n }\n\n return output;\n },\n\n /**\n * Lazy static initialization function. Called before\n * accessing any of the static map variables.\n * @private\n */\n init_() {\n if (!this.byteToCharMap_) {\n this.byteToCharMap_ = {};\n this.charToByteMap_ = {};\n this.byteToCharMapWebSafe_ = {};\n this.charToByteMapWebSafe_ = {};\n\n // We want quick mappings back and forth, so we precompute two maps.\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n\n // Be forgiving when decoding and correctly decode both encodings.\n if (i >= this.ENCODED_VALS_BASE.length) {\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n }\n }\n }\n }\n};\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class DecodeBase64StringError extends Error {\n readonly name = 'DecodeBase64StringError';\n}\n\n/**\n * URL-safe base64 encoding\n */\nexport const base64Encode = function (str: string): string {\n const utf8Bytes = stringToByteArray(str);\n return base64.encodeByteArray(utf8Bytes, true);\n};\n\n/**\n * URL-safe base64 encoding (without \".\" padding in the end).\n * e.g. Used in JSON Web Token (JWT) parts.\n */\nexport const base64urlEncodeWithoutPadding = function (str: string): string {\n // Use base64url encoding and remove padding in the end (dot characters).\n return base64Encode(str).replace(/\\./g, '');\n};\n\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param str To be decoded\n * @return Decoded result, if possible\n */\nexport const base64Decode = function (str: string): string | null {\n try {\n return base64.decodeString(str, true);\n } catch (e) {\n console.error('base64Decode failed: ', e);\n }\n return null;\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Do a deep-copy of basic JavaScript Objects or Arrays.\n */\nexport function deepCopy(value: T): T {\n return deepExtend(undefined, value) as T;\n}\n\n/**\n * Copy properties from source to target (recursively allows extension\n * of Objects and Arrays). Scalar values in the target are over-written.\n * If target is undefined, an object of the appropriate type will be created\n * (and returned).\n *\n * We recursively copy all child properties of plain Objects in the source- so\n * that namespace- like dictionaries are merged.\n *\n * Note that the target can be a function, in which case the properties in\n * the source Object are copied onto it as static properties of the Function.\n *\n * Note: we don't merge __proto__ to prevent prototype pollution\n */\nexport function deepExtend(target: unknown, source: unknown): unknown {\n if (!(source instanceof Object)) {\n return source;\n }\n\n switch (source.constructor) {\n case Date:\n // Treat Dates like scalars; if the target date object had any child\n // properties - they will be lost!\n const dateValue = source as Date;\n return new Date(dateValue.getTime());\n\n case Object:\n if (target === undefined) {\n target = {};\n }\n break;\n case Array:\n // Always copy the array source and overwrite the target.\n target = [];\n break;\n\n default:\n // Not a plain Object - treat it as a scalar.\n return source;\n }\n\n for (const prop in source) {\n // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202\n if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {\n continue;\n }\n (target as Record)[prop] = deepExtend(\n (target as Record)[prop],\n (source as Record)[prop]\n );\n }\n\n return target;\n}\n\nfunction isValidKey(key: string): boolean {\n return key !== '__proto__';\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Polyfill for `globalThis` object.\n * @returns the `globalThis` object for the given environment.\n * @public\n */\nexport function getGlobal(): typeof globalThis {\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('Unable to locate global object.');\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Decode } from './crypt';\nimport { getGlobal } from './global';\nimport { getDefaultsFromPostinstall } from './postinstall';\n\n/**\n * Keys for experimental properties on the `FirebaseDefaults` object.\n * @public\n */\nexport type ExperimentalKey = 'authTokenSyncURL' | 'authIdTokenMaxAge';\n\n/**\n * An object that can be injected into the environment as __FIREBASE_DEFAULTS__,\n * either as a property of globalThis, a shell environment variable, or a\n * cookie.\n *\n * This object can be used to automatically configure and initialize\n * a Firebase app as well as any emulators.\n *\n * @public\n */\nexport interface FirebaseDefaults {\n config?: Record;\n emulatorHosts?: Record;\n _authTokenSyncURL?: string;\n _authIdTokenMaxAge?: number;\n /**\n * Override Firebase's runtime environment detection and\n * force the SDK to act as if it were in the specified environment.\n */\n forceEnvironment?: 'browser' | 'node';\n [key: string]: unknown;\n}\n\ndeclare global {\n // Need `var` for this to work.\n // eslint-disable-next-line no-var\n var __FIREBASE_DEFAULTS__: FirebaseDefaults | undefined;\n}\n\nconst getDefaultsFromGlobal = (): FirebaseDefaults | undefined =>\n getGlobal().__FIREBASE_DEFAULTS__;\n\n/**\n * Attempt to read defaults from a JSON string provided to\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\n * The dots are in parens because certain compilers (Vite?) cannot\n * handle seeing that variable in comments.\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\n */\nconst getDefaultsFromEnvVariable = (): FirebaseDefaults | undefined => {\n if (typeof process === 'undefined' || typeof process.env === 'undefined') {\n return;\n }\n const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\n if (defaultsJsonString) {\n return JSON.parse(defaultsJsonString);\n }\n};\n\nconst getDefaultsFromCookie = (): FirebaseDefaults | undefined => {\n if (typeof document === 'undefined') {\n return;\n }\n let match;\n try {\n match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\n } catch (e) {\n // Some environments such as Angular Universal SSR have a\n // `document` object but error on accessing `document.cookie`.\n return;\n }\n const decoded = match && base64Decode(match[1]);\n return decoded && JSON.parse(decoded);\n};\n\n/**\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\n * (1) if such an object exists as a property of `globalThis`\n * (2) if such an object was provided on a shell environment variable\n * (3) if such an object exists in a cookie\n * @public\n */\nexport const getDefaults = (): FirebaseDefaults | undefined => {\n try {\n return (\n getDefaultsFromPostinstall() ||\n getDefaultsFromGlobal() ||\n getDefaultsFromEnvVariable() ||\n getDefaultsFromCookie()\n );\n } catch (e) {\n /**\n * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\n * to any environment case we have not accounted for. Log to\n * info instead of swallowing so we can find these unknown cases\n * and add paths for them if needed.\n */\n console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\n return;\n }\n};\n\n/**\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\n * @public\n */\nexport const getDefaultEmulatorHost = (\n productName: string\n): string | undefined => getDefaults()?.emulatorHosts?.[productName];\n\n/**\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\n * @public\n */\nexport const getDefaultEmulatorHostnameAndPort = (\n productName: string\n): [hostname: string, port: number] | undefined => {\n const host = getDefaultEmulatorHost(productName);\n if (!host) {\n return undefined;\n }\n const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\n if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\n throw new Error(`Invalid host ${host} with no separate hostname and port!`);\n }\n // eslint-disable-next-line no-restricted-globals\n const port = parseInt(host.substring(separatorIndex + 1), 10);\n if (host[0] === '[') {\n // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\n return [host.substring(1, separatorIndex - 1), port];\n } else {\n return [host.substring(0, separatorIndex), port];\n }\n};\n\n/**\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\n * @public\n */\nexport const getDefaultAppConfig = (): Record | undefined =>\n getDefaults()?.config;\n\n/**\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\n * prefixed by \"_\")\n * @public\n */\nexport const getExperimentalSetting = (\n name: T\n): FirebaseDefaults[`_${T}`] =>\n getDefaults()?.[`_${name}`] as FirebaseDefaults[`_${T}`];\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred {\n promise: Promise;\n reject: (value?: unknown) => void = () => {};\n resolve: (value?: unknown) => void = () => {};\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve as (value?: unknown) => void;\n this.reject = reject as (value?: unknown) => void;\n });\n }\n\n /**\n * Our API internals are not promisified and cannot because our callback APIs have subtle expectations around\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\n */\n wrapCallback(\n callback?: (error?: unknown, value?: unknown) => void\n ): (error: unknown, value?: unknown) => void {\n return (error, value?) => {\n if (error) {\n this.reject(error);\n } else {\n this.resolve(value);\n }\n if (typeof callback === 'function') {\n // Attaching noop handler just in case developer wasn't expecting\n // promises\n this.promise.catch(() => {});\n\n // Some of our callbacks don't expect a value and our own tests\n // assert that the parameter length is 1\n if (callback.length === 1) {\n callback(error);\n } else {\n callback(error, value);\n }\n }\n };\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Checks whether host is a cloud workstation or not.\n * @public\n */\nexport function isCloudWorkstation(url: string): boolean {\n // `isCloudWorkstation` is called without protocol in certain connect*Emulator functions\n // In HTTP request builders, it's called with the protocol.\n // If called with protocol prefix, it's a valid URL, so we extract the hostname\n // If called without, we assume the string is the hostname.\n try {\n const host =\n url.startsWith('http://') || url.startsWith('https://')\n ? new URL(url).hostname\n : url;\n return host.endsWith('.cloudworkstations.dev');\n } catch {\n return false;\n }\n}\n\n/**\n * Makes a fetch request to the given server.\n * Mostly used for forwarding cookies in Firebase Studio.\n * @public\n */\nexport async function pingServer(endpoint: string): Promise {\n const result = await fetch(endpoint, {\n credentials: 'include'\n });\n return result.ok;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64urlEncodeWithoutPadding } from './crypt';\nimport { isCloudWorkstation } from './url';\n\n// Firebase Auth tokens contain snake_case claims following the JWT standard / convention.\n/* eslint-disable camelcase */\n\nexport type FirebaseSignInProvider =\n | 'custom'\n | 'email'\n | 'password'\n | 'phone'\n | 'anonymous'\n | 'google.com'\n | 'facebook.com'\n | 'github.com'\n | 'twitter.com'\n | 'microsoft.com'\n | 'apple.com';\n\ninterface FirebaseIdToken {\n // Always set to https://securetoken.google.com/PROJECT_ID\n iss: string;\n\n // Always set to PROJECT_ID\n aud: string;\n\n // The user's unique ID\n sub: string;\n\n // The token issue time, in seconds since epoch\n iat: number;\n\n // The token expiry time, normally 'iat' + 3600\n exp: number;\n\n // The user's unique ID. Must be equal to 'sub'\n user_id: string;\n\n // The time the user authenticated, normally 'iat'\n auth_time: number;\n\n // The sign in provider, only set when the provider is 'anonymous'\n provider_id?: 'anonymous';\n\n // The user's primary email\n email?: string;\n\n // The user's email verification status\n email_verified?: boolean;\n\n // The user's primary phone number\n phone_number?: string;\n\n // The user's display name\n name?: string;\n\n // The user's profile photo URL\n picture?: string;\n\n // Information on all identities linked to this user\n firebase: {\n // The primary sign-in provider\n sign_in_provider: FirebaseSignInProvider;\n\n // A map of providers to the user's list of unique identifiers from\n // each provider\n identities?: { [provider in FirebaseSignInProvider]?: string[] };\n };\n\n // Custom claims set by the developer\n [claim: string]: unknown;\n\n uid?: never; // Try to catch a common mistake of \"uid\" (should be \"sub\" instead).\n}\n\nexport type EmulatorMockTokenOptions = ({ user_id: string } | { sub: string }) &\n Partial;\n\nexport function createMockUserToken(\n token: EmulatorMockTokenOptions,\n projectId?: string\n): string {\n if (token.uid) {\n throw new Error(\n 'The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.'\n );\n }\n // Unsecured JWTs use \"none\" as the algorithm.\n const header = {\n alg: 'none',\n type: 'JWT'\n };\n\n const project = projectId || 'demo-project';\n const iat = token.iat || 0;\n const sub = token.sub || token.user_id;\n if (!sub) {\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\n }\n\n const payload: FirebaseIdToken = {\n // Set all required fields to decent defaults\n iss: `https://securetoken.google.com/${project}`,\n aud: project,\n iat,\n exp: iat + 3600,\n auth_time: iat,\n sub,\n user_id: sub,\n firebase: {\n sign_in_provider: 'custom',\n identities: {}\n },\n\n // Override with user options\n ...token\n };\n\n // Unsecured JWTs use the empty string as a signature.\n const signature = '';\n return [\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\n signature\n ].join('.');\n}\n\ninterface EmulatorStatusMap {\n [name: string]: boolean;\n}\nconst emulatorStatus: EmulatorStatusMap = {};\n\ninterface EmulatorSummary {\n prod: string[];\n emulator: string[];\n}\n\n// Checks whether any products are running on an emulator\nfunction getEmulatorSummary(): EmulatorSummary {\n const summary: EmulatorSummary = {\n prod: [],\n emulator: []\n };\n for (const key of Object.keys(emulatorStatus)) {\n if (emulatorStatus[key]) {\n summary.emulator.push(key);\n } else {\n summary.prod.push(key);\n }\n }\n return summary;\n}\n\nfunction getOrCreateEl(id: string): { created: boolean; element: HTMLElement } {\n let parentDiv = document.getElementById(id);\n let created = false;\n if (!parentDiv) {\n parentDiv = document.createElement('div');\n parentDiv.setAttribute('id', id);\n created = true;\n }\n return { created, element: parentDiv };\n}\n\nlet previouslyDismissed = false;\n/**\n * Updates Emulator Banner. Primarily used for Firebase Studio\n * @param name\n * @param isRunningEmulator\n * @public\n */\nexport function updateEmulatorBanner(\n name: string,\n isRunningEmulator: boolean\n): void {\n if (\n typeof window === 'undefined' ||\n typeof document === 'undefined' ||\n !isCloudWorkstation(window.location.host) ||\n emulatorStatus[name] === isRunningEmulator ||\n emulatorStatus[name] || // If already set to use emulator, can't go back to prod.\n previouslyDismissed\n ) {\n return;\n }\n\n emulatorStatus[name] = isRunningEmulator;\n\n function prefixedId(id: string): string {\n return `__firebase__banner__${id}`;\n }\n const bannerId = '__firebase__banner';\n const summary = getEmulatorSummary();\n const showError = summary.prod.length > 0;\n\n function tearDown(): void {\n const element = document.getElementById(bannerId);\n if (element) {\n element.remove();\n }\n }\n\n function setupBannerStyles(bannerEl: HTMLElement): void {\n bannerEl.style.display = 'flex';\n bannerEl.style.background = '#7faaf0';\n bannerEl.style.position = 'fixed';\n bannerEl.style.bottom = '5px';\n bannerEl.style.left = '5px';\n bannerEl.style.padding = '.5em';\n bannerEl.style.borderRadius = '5px';\n bannerEl.style.alignItems = 'center';\n }\n\n function setupIconStyles(prependIcon: SVGElement, iconId: string): void {\n prependIcon.setAttribute('width', '24');\n prependIcon.setAttribute('id', iconId);\n prependIcon.setAttribute('height', '24');\n prependIcon.setAttribute('viewBox', '0 0 24 24');\n prependIcon.setAttribute('fill', 'none');\n prependIcon.style.marginLeft = '-6px';\n }\n\n function setupCloseBtn(): HTMLSpanElement {\n const closeBtn = document.createElement('span');\n closeBtn.style.cursor = 'pointer';\n closeBtn.style.marginLeft = '16px';\n closeBtn.style.fontSize = '24px';\n closeBtn.innerHTML = ' ×';\n closeBtn.onclick = () => {\n previouslyDismissed = true;\n tearDown();\n };\n return closeBtn;\n }\n\n function setupLinkStyles(\n learnMoreLink: HTMLAnchorElement,\n learnMoreId: string\n ): void {\n learnMoreLink.setAttribute('id', learnMoreId);\n learnMoreLink.innerText = 'Learn more';\n learnMoreLink.href =\n 'https://firebase.google.com/docs/studio/preview-apps#preview-backend';\n learnMoreLink.setAttribute('target', '__blank');\n learnMoreLink.style.paddingLeft = '5px';\n learnMoreLink.style.textDecoration = 'underline';\n }\n\n function setupDom(): void {\n const banner = getOrCreateEl(bannerId);\n const firebaseTextId = prefixedId('text');\n const firebaseText: HTMLSpanElement =\n document.getElementById(firebaseTextId) || document.createElement('span');\n const learnMoreId = prefixedId('learnmore');\n const learnMoreLink: HTMLAnchorElement =\n (document.getElementById(learnMoreId) as HTMLAnchorElement) ||\n document.createElement('a');\n const prependIconId = prefixedId('preprendIcon');\n const prependIcon: SVGElement =\n (document.getElementById(\n prependIconId\n ) as HTMLOrSVGElement as SVGElement) ||\n document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n if (banner.created) {\n // update styles\n const bannerEl = banner.element;\n setupBannerStyles(bannerEl);\n setupLinkStyles(learnMoreLink, learnMoreId);\n const closeBtn = setupCloseBtn();\n setupIconStyles(prependIcon, prependIconId);\n bannerEl.append(prependIcon, firebaseText, learnMoreLink, closeBtn);\n document.body.appendChild(bannerEl);\n }\n\n if (showError) {\n firebaseText.innerText = `Preview backend disconnected.`;\n prependIcon.innerHTML = `\n\n\n\n\n\n\n`;\n } else {\n prependIcon.innerHTML = `\n\n\n\n\n\n\n`;\n firebaseText.innerText = 'Preview backend running in this workspace.';\n }\n firebaseText.setAttribute('id', firebaseTextId);\n }\n if (document.readyState === 'loading') {\n window.addEventListener('DOMContentLoaded', setupDom);\n } else {\n setupDom();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSTANTS } from './constants';\nimport { getDefaults } from './defaults';\n\n/**\n * Type placeholder for `WorkerGlobalScope` from `webworker`\n */\ndeclare class WorkerGlobalScope {}\n\n/**\n * Returns navigator.userAgent string or '' if it's not defined.\n * @return user agent string\n */\nexport function getUA(): string {\n if (\n typeof navigator !== 'undefined' &&\n typeof navigator['userAgent'] === 'string'\n ) {\n return navigator['userAgent'];\n } else {\n return '';\n }\n}\n\n/**\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\n *\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\n * wait for a callback.\n */\nexport function isMobileCordova(): boolean {\n return (\n typeof window !== 'undefined' &&\n // @ts-ignore Setting up an broadly applicable index signature for Window\n // just to deal with this case would probably be a bad idea.\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())\n );\n}\n\n/**\n * Detect Node.js.\n *\n * @return true if Node.js environment is detected or specified.\n */\n// Node detection logic from: https://github.com/iliakan/detect-node/\nexport function isNode(): boolean {\n const forceEnvironment = getDefaults()?.forceEnvironment;\n if (forceEnvironment === 'node') {\n return true;\n } else if (forceEnvironment === 'browser') {\n return false;\n }\n\n try {\n return (\n Object.prototype.toString.call(global.process) === '[object process]'\n );\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Detect Browser Environment.\n * Note: This will return true for certain test frameworks that are incompletely\n * mimicking a browser, and should not lead to assuming all browser APIs are\n * available.\n */\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined' || isWebWorker();\n}\n\n/**\n * Detect Web Worker context.\n */\nexport function isWebWorker(): boolean {\n return (\n typeof WorkerGlobalScope !== 'undefined' &&\n typeof self !== 'undefined' &&\n self instanceof WorkerGlobalScope\n );\n}\n\n/**\n * Detect Cloudflare Worker context.\n */\nexport function isCloudflareWorker(): boolean {\n return (\n typeof navigator !== 'undefined' &&\n navigator.userAgent === 'Cloudflare-Workers'\n );\n}\n\n/**\n * Detect browser extensions (Chrome and Firefox at least).\n */\ninterface BrowserRuntime {\n id?: unknown;\n}\ndeclare const chrome: { runtime?: BrowserRuntime };\ndeclare const browser: { runtime?: BrowserRuntime };\nexport function isBrowserExtension(): boolean {\n const runtime =\n typeof chrome === 'object'\n ? chrome.runtime\n : typeof browser === 'object'\n ? browser.runtime\n : undefined;\n return typeof runtime === 'object' && runtime.id !== undefined;\n}\n\n/**\n * Detect React Native.\n *\n * @return true if ReactNative environment is detected.\n */\nexport function isReactNative(): boolean {\n return (\n typeof navigator === 'object' && navigator['product'] === 'ReactNative'\n );\n}\n\n/** Detects Electron apps. */\nexport function isElectron(): boolean {\n return getUA().indexOf('Electron/') >= 0;\n}\n\n/** Detects Internet Explorer. */\nexport function isIE(): boolean {\n const ua = getUA();\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\n}\n\n/** Detects Universal Windows Platform apps. */\nexport function isUWP(): boolean {\n return getUA().indexOf('MSAppHost/') >= 0;\n}\n\n/**\n * Detect whether the current SDK build is the Node version.\n *\n * @return true if it's the Node SDK build.\n */\nexport function isNodeSdk(): boolean {\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\n}\n\n/** Returns true if we are running in Safari. */\nexport function isSafari(): boolean {\n return (\n !isNode() &&\n !!navigator.userAgent &&\n navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome')\n );\n}\n\n/** Returns true if we are running in Safari or WebKit */\nexport function isSafariOrWebkit(): boolean {\n return (\n !isNode() &&\n !!navigator.userAgent &&\n (navigator.userAgent.includes('Safari') ||\n navigator.userAgent.includes('WebKit')) &&\n !navigator.userAgent.includes('Chrome')\n );\n}\n\n/**\n * This method checks if indexedDB is supported by current browser/service worker context\n * @return true if indexedDB is supported by current browser/service worker context\n */\nexport function isIndexedDBAvailable(): boolean {\n try {\n return typeof indexedDB === 'object';\n } catch (e) {\n return false;\n }\n}\n\n/**\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\n * if errors occur during the database open operation.\n *\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\n * private browsing)\n */\nexport function validateIndexedDBOpenable(): Promise {\n return new Promise((resolve, reject) => {\n try {\n let preExist: boolean = true;\n const DB_CHECK_NAME =\n 'validate-browser-context-for-indexeddb-analytics-module';\n const request = self.indexedDB.open(DB_CHECK_NAME);\n request.onsuccess = () => {\n request.result.close();\n // delete database only when it doesn't pre-exist\n if (!preExist) {\n self.indexedDB.deleteDatabase(DB_CHECK_NAME);\n }\n resolve(true);\n };\n request.onupgradeneeded = () => {\n preExist = false;\n };\n\n request.onerror = () => {\n reject(request.error?.message || '');\n };\n } catch (error) {\n reject(error);\n }\n });\n}\n\n/**\n *\n * This method checks whether cookie is enabled within current browser\n * @return true if cookie is enabled within current browser\n */\nexport function areCookiesEnabled(): boolean {\n if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\n return false;\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n * // TypeScript string literals for type-safe codes\n * type Err =\n * 'unknown' |\n * 'object-not-found'\n * ;\n *\n * // Closure enum for type-safe error codes\n * // at-enum {string}\n * var Err = {\n * UNKNOWN: 'unknown',\n * OBJECT_NOT_FOUND: 'object-not-found',\n * }\n *\n * let errors: Map = {\n * 'generic-error': \"Unknown error\",\n * 'file-not-found': \"Could not find file: {$file}\",\n * };\n *\n * // Type-safe function - must pass a valid error code as param.\n * let error = new ErrorFactory('service', 'Service', errors);\n *\n * ...\n * throw error.create(Err.GENERIC);\n * ...\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n * ...\n * // Service: Could not file file: foo.txt (service/file-not-found).\n *\n * catch (e) {\n * assert(e.message === \"Could not find file: foo.txt.\");\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\n * console.log(\"Could not read file: \" + e['file']);\n * }\n * }\n */\n\nexport type ErrorMap = {\n readonly [K in ErrorCode]: string;\n};\n\nconst ERROR_NAME = 'FirebaseError';\n\nexport interface StringLike {\n toString(): string;\n}\n\nexport interface ErrorData {\n [key: string]: unknown;\n}\n\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nexport class FirebaseError extends Error {\n /** The custom name for all FirebaseErrors. */\n readonly name: string = ERROR_NAME;\n\n constructor(\n /** The error code for this error. */\n readonly code: string,\n message: string,\n /** Custom data for this error. */\n public customData?: Record\n ) {\n super(message);\n\n // Fix For ES5\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget\n // which we can now use since we no longer target ES5.\n Object.setPrototypeOf(this, FirebaseError.prototype);\n\n // Maintains proper stack trace for where our error was thrown.\n // Only available on V8.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\n }\n }\n}\n\nexport class ErrorFactory<\n ErrorCode extends string,\n ErrorParams extends { readonly [K in ErrorCode]?: ErrorData } = {}\n> {\n constructor(\n private readonly service: string,\n private readonly serviceName: string,\n private readonly errors: ErrorMap\n ) {}\n\n create(\n code: K,\n ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []\n ): FirebaseError {\n const customData = (data[0] as ErrorData) || {};\n const fullCode = `${this.service}/${code}`;\n const template = this.errors[code];\n\n const message = template ? replaceTemplate(template, customData) : 'Error';\n // Service Name: Error message (service/code).\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n\n const error = new FirebaseError(fullCode, fullMessage, customData);\n\n return error;\n }\n}\n\nfunction replaceTemplate(template: string, data: ErrorData): string {\n return template.replace(PATTERN, (_, key) => {\n const value = data[key];\n return value != null ? String(value) : `<${key}?>`;\n });\n}\n\nconst PATTERN = /\\{\\$([^}]+)}/g;\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Evaluates a JSON string into a javascript object.\n *\n * @param {string} str A string containing JSON.\n * @return {*} The javascript object representing the specified JSON.\n */\nexport function jsonEval(str: string): unknown {\n return JSON.parse(str);\n}\n\n/**\n * Returns JSON representing a javascript object.\n * @param {*} data JavaScript object to be stringified.\n * @return {string} The JSON contents of the object.\n */\nexport function stringify(data: unknown): string {\n return JSON.stringify(data);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Decode } from './crypt';\nimport { jsonEval } from './json';\n\ninterface Claims {\n [key: string]: {};\n}\n\ninterface DecodedToken {\n header: object;\n claims: Claims;\n data: object;\n signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token into constituent parts.\n *\n * Notes:\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const decode = function (token: string): DecodedToken {\n let header = {},\n claims: Claims = {},\n data = {},\n signature = '';\n\n try {\n const parts = token.split('.');\n header = jsonEval(base64Decode(parts[0]) || '') as object;\n claims = jsonEval(base64Decode(parts[1]) || '') as Claims;\n signature = parts[2];\n data = claims['d'] || {};\n delete claims['d'];\n } catch (e) {}\n\n return {\n header,\n claims,\n data,\n signature\n };\n};\n\ninterface DecodedToken {\n header: object;\n claims: Claims;\n data: object;\n signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidTimestamp = function (token: string): boolean {\n const claims: Claims = decode(token).claims;\n const now: number = Math.floor(new Date().getTime() / 1000);\n let validSince: number = 0,\n validUntil: number = 0;\n\n if (typeof claims === 'object') {\n if (claims.hasOwnProperty('nbf')) {\n validSince = claims['nbf'] as number;\n } else if (claims.hasOwnProperty('iat')) {\n validSince = claims['iat'] as number;\n }\n\n if (claims.hasOwnProperty('exp')) {\n validUntil = claims['exp'] as number;\n } else {\n // token will expire after 24h by default\n validUntil = validSince + 86400;\n }\n }\n\n return (\n !!now &&\n !!validSince &&\n !!validUntil &&\n now >= validSince &&\n now <= validUntil\n );\n};\n\n/**\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\n *\n * Notes:\n * - May return null if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const issuedAtTime = function (token: string): number | null {\n const claims: Claims = decode(token).claims;\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\n return claims['iat'] as number;\n }\n return null;\n};\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidFormat = function (token: string): boolean {\n const decoded = decode(token),\n claims = decoded.claims;\n\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\n};\n\n/**\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isAdmin = function (token: string): boolean {\n const claims: Claims = decode(token).claims;\n return typeof claims === 'object' && claims['admin'] === true;\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function contains(obj: T, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function safeGet(\n obj: T,\n key: K\n): T[K] | undefined {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return obj[key];\n } else {\n return undefined;\n }\n}\n\nexport function isEmpty(obj: object): obj is {} {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\n\nexport function map(\n obj: { [key in K]: V },\n fn: (value: V, key: K, obj: { [key in K]: V }) => U,\n contextObj?: unknown\n): { [key in K]: U } {\n const res: Partial<{ [key in K]: U }> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n res[key] = fn.call(contextObj, obj[key], key, obj);\n }\n }\n return res as { [key in K]: U };\n}\n\n/**\n * Deep equal two objects. Support Arrays and Objects.\n */\nexport function deepEqual(a: object, b: object): boolean {\n if (a === b) {\n return true;\n }\n\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n for (const k of aKeys) {\n if (!bKeys.includes(k)) {\n return false;\n }\n\n const aProp = (a as Record)[k];\n const bProp = (b as Record)[k];\n if (isObject(aProp) && isObject(bProp)) {\n if (!deepEqual(aProp, bProp)) {\n return false;\n }\n } else if (aProp !== bProp) {\n return false;\n }\n }\n\n for (const k of bKeys) {\n if (!aKeys.includes(k)) {\n return false;\n }\n }\n return true;\n}\n\nfunction isObject(thing: unknown): thing is object {\n return thing !== null && typeof thing === 'object';\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from './deferred';\n\n/**\n * Rejects if the given promise doesn't resolve in timeInMS milliseconds.\n * @internal\n */\nexport function promiseWithTimeout(\n promise: Promise,\n timeInMS = 2000\n): Promise {\n const deferredPromise = new Deferred();\n setTimeout(() => deferredPromise.reject('timeout!'), timeInMS);\n promise.then(deferredPromise.resolve, deferredPromise.reject);\n return deferredPromise.promise;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\n * params object (e.g. {arg: 'val', arg2: 'val2'})\n * Note: You must prepend it with ? when adding it to a URL.\n */\nexport function querystring(querystringParams: {\n [key: string]: string | number;\n}): string {\n const params = [];\n for (const [key, value] of Object.entries(querystringParams)) {\n if (Array.isArray(value)) {\n value.forEach(arrayVal => {\n params.push(\n encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal)\n );\n });\n } else {\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n }\n }\n return params.length ? '&' + params.join('&') : '';\n}\n\n/**\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\n * (e.g. {arg: 'val', arg2: 'val2'})\n */\nexport function querystringDecode(querystring: string): Record {\n const obj: Record = {};\n const tokens = querystring.replace(/^\\?/, '').split('&');\n\n tokens.forEach(token => {\n if (token) {\n const [key, value] = token.split('=');\n obj[decodeURIComponent(key)] = decodeURIComponent(value);\n }\n });\n return obj;\n}\n\n/**\n * Extract the query string part of a URL, including the leading question mark (if present).\n */\nexport function extractQuerystring(url: string): string {\n const queryStart = url.indexOf('?');\n if (!queryStart) {\n return '';\n }\n const fragmentStart = url.indexOf('#', queryStart);\n return url.substring(\n queryStart,\n fragmentStart > 0 ? fragmentStart : undefined\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview SHA-1 cryptographic hash.\n * Variable names follow the notation in FIPS PUB 180-3:\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\n *\n * Usage:\n * var sha1 = new sha1();\n * sha1.update(bytes);\n * var hash = sha1.digest();\n *\n * Performance:\n * Chrome 23: ~400 Mbit/s\n * Firefox 16: ~250 Mbit/s\n *\n */\n\n/**\n * SHA-1 cryptographic hash constructor.\n *\n * The properties declared here are discussed in the above algorithm document.\n * @constructor\n * @final\n * @struct\n */\nexport class Sha1 {\n /**\n * Holds the previous values of accumulated variables a-e in the compress_\n * function.\n * @private\n */\n private chain_: number[] = [];\n\n /**\n * A buffer holding the partially computed hash result.\n * @private\n */\n private buf_: number[] = [];\n\n /**\n * An array of 80 bytes, each a part of the message to be hashed. Referred to\n * as the message schedule in the docs.\n * @private\n */\n private W_: number[] = [];\n\n /**\n * Contains data needed to pad messages less than 64 bytes.\n * @private\n */\n private pad_: number[] = [];\n\n /**\n * @private {number}\n */\n private inbuf_: number = 0;\n\n /**\n * @private {number}\n */\n private total_: number = 0;\n\n blockSize: number;\n\n constructor() {\n this.blockSize = 512 / 8;\n\n this.pad_[0] = 128;\n for (let i = 1; i < this.blockSize; ++i) {\n this.pad_[i] = 0;\n }\n\n this.reset();\n }\n\n reset(): void {\n this.chain_[0] = 0x67452301;\n this.chain_[1] = 0xefcdab89;\n this.chain_[2] = 0x98badcfe;\n this.chain_[3] = 0x10325476;\n this.chain_[4] = 0xc3d2e1f0;\n\n this.inbuf_ = 0;\n this.total_ = 0;\n }\n\n /**\n * Internal compress helper function.\n * @param buf Block to compress.\n * @param offset Offset of the block in the buffer.\n * @private\n */\n compress_(buf: number[] | Uint8Array | string, offset?: number): void {\n if (!offset) {\n offset = 0;\n }\n\n const W = this.W_;\n\n // get 16 big endian words\n if (typeof buf === 'string') {\n for (let i = 0; i < 16; i++) {\n // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\n // have a bug that turns the post-increment ++ operator into pre-increment\n // during JIT compilation. We have code that depends heavily on SHA-1 for\n // correctness and which is affected by this bug, so I've removed all uses\n // of post-increment ++ in which the result value is used. We can revert\n // this change once the Safari bug\n // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\n // most clients have been updated.\n W[i] =\n (buf.charCodeAt(offset) << 24) |\n (buf.charCodeAt(offset + 1) << 16) |\n (buf.charCodeAt(offset + 2) << 8) |\n buf.charCodeAt(offset + 3);\n offset += 4;\n }\n } else {\n for (let i = 0; i < 16; i++) {\n W[i] =\n (buf[offset] << 24) |\n (buf[offset + 1] << 16) |\n (buf[offset + 2] << 8) |\n buf[offset + 3];\n offset += 4;\n }\n }\n\n // expand to 80 words\n for (let i = 16; i < 80; i++) {\n const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\n W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\n }\n\n let a = this.chain_[0];\n let b = this.chain_[1];\n let c = this.chain_[2];\n let d = this.chain_[3];\n let e = this.chain_[4];\n let f, k;\n\n // TODO(user): Try to unroll this loop to speed up the computation.\n for (let i = 0; i < 80; i++) {\n if (i < 40) {\n if (i < 20) {\n f = d ^ (b & (c ^ d));\n k = 0x5a827999;\n } else {\n f = b ^ c ^ d;\n k = 0x6ed9eba1;\n }\n } else {\n if (i < 60) {\n f = (b & c) | (d & (b | c));\n k = 0x8f1bbcdc;\n } else {\n f = b ^ c ^ d;\n k = 0xca62c1d6;\n }\n }\n\n const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\n e = d;\n d = c;\n c = ((b << 30) | (b >>> 2)) & 0xffffffff;\n b = a;\n a = t;\n }\n\n this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\n this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\n this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\n this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\n this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\n }\n\n update(bytes?: number[] | Uint8Array | string, length?: number): void {\n // TODO(johnlenz): tighten the function signature and remove this check\n if (bytes == null) {\n return;\n }\n\n if (length === undefined) {\n length = bytes.length;\n }\n\n const lengthMinusBlock = length - this.blockSize;\n let n = 0;\n // Using local instead of member variables gives ~5% speedup on Firefox 16.\n const buf = this.buf_;\n let inbuf = this.inbuf_;\n\n // The outer while loop should execute at most twice.\n while (n < length) {\n // When we have no data in the block to top up, we can directly process the\n // input buffer (assuming it contains sufficient data). This gives ~25%\n // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\n // the data is provided in large chunks (or in multiples of 64 bytes).\n if (inbuf === 0) {\n while (n <= lengthMinusBlock) {\n this.compress_(bytes, n);\n n += this.blockSize;\n }\n }\n\n if (typeof bytes === 'string') {\n while (n < length) {\n buf[inbuf] = bytes.charCodeAt(n);\n ++inbuf;\n ++n;\n if (inbuf === this.blockSize) {\n this.compress_(buf);\n inbuf = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n } else {\n while (n < length) {\n buf[inbuf] = bytes[n];\n ++inbuf;\n ++n;\n if (inbuf === this.blockSize) {\n this.compress_(buf);\n inbuf = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n }\n }\n\n this.inbuf_ = inbuf;\n this.total_ += length;\n }\n\n /** @override */\n digest(): number[] {\n const digest: number[] = [];\n let totalBits = this.total_ * 8;\n\n // Add pad 0x80 0x00*.\n if (this.inbuf_ < 56) {\n this.update(this.pad_, 56 - this.inbuf_);\n } else {\n this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\n }\n\n // Add # bits.\n for (let i = this.blockSize - 1; i >= 56; i--) {\n this.buf_[i] = totalBits & 255;\n totalBits /= 256; // Don't use bit-shifting here!\n }\n\n this.compress_(this.buf_);\n\n let n = 0;\n for (let i = 0; i < 5; i++) {\n for (let j = 24; j >= 0; j -= 8) {\n digest[n] = (this.chain_[i] >> j) & 255;\n ++n;\n }\n }\n return digest;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport type NextFn = (value: T) => void;\nexport type ErrorFn = (error: Error) => void;\nexport type CompleteFn = () => void;\n\nexport interface Observer {\n // Called once for each value in a stream of values.\n next: NextFn;\n\n // A stream terminates by a single call to EITHER error() or complete().\n error: ErrorFn;\n\n // No events will be sent to next() once complete() is called.\n complete: CompleteFn;\n}\n\nexport type PartialObserver = Partial>;\n\n// TODO: Support also Unsubscribe.unsubscribe?\nexport type Unsubscribe = () => void;\n\n/**\n * The Subscribe interface has two forms - passing the inline function\n * callbacks, or a object interface with callback properties.\n */\nexport interface Subscribe {\n (next?: NextFn, error?: ErrorFn, complete?: CompleteFn): Unsubscribe;\n (observer: PartialObserver): Unsubscribe;\n}\n\nexport interface Observable {\n // Subscribe method\n subscribe: Subscribe;\n}\n\nexport type Executor = (observer: Observer) => void;\n\n/**\n * Helper to make a Subscribe function (just like Promise helps make a\n * Thenable).\n *\n * @param executor Function which can make calls to a single Observer\n * as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\nexport function createSubscribe(\n executor: Executor,\n onNoObservers?: Executor\n): Subscribe {\n const proxy = new ObserverProxy(executor, onNoObservers);\n return proxy.subscribe.bind(proxy);\n}\n\n/**\n * Implement fan-out for any number of Observers attached via a subscribe\n * function.\n */\nclass ObserverProxy implements Observer {\n private observers: Array> | undefined = [];\n private unsubscribes: Unsubscribe[] = [];\n private onNoObservers: Executor | undefined;\n private observerCount = 0;\n // Micro-task scheduling by calling task.then().\n private task = Promise.resolve();\n private finalized = false;\n private finalError?: Error;\n\n /**\n * @param executor Function which can make calls to a single Observer\n * as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\n constructor(executor: Executor, onNoObservers?: Executor) {\n this.onNoObservers = onNoObservers;\n // Call the executor asynchronously so subscribers that are called\n // synchronously after the creation of the subscribe function\n // can still receive the very first value generated in the executor.\n this.task\n .then(() => {\n executor(this);\n })\n .catch(e => {\n this.error(e);\n });\n }\n\n next(value: T): void {\n this.forEachObserver((observer: Observer) => {\n observer.next(value);\n });\n }\n\n error(error: Error): void {\n this.forEachObserver((observer: Observer) => {\n observer.error(error);\n });\n this.close(error);\n }\n\n complete(): void {\n this.forEachObserver((observer: Observer) => {\n observer.complete();\n });\n this.close();\n }\n\n /**\n * Subscribe function that can be used to add an Observer to the fan-out list.\n *\n * - We require that no event is sent to a subscriber synchronously to their\n * call to subscribe().\n */\n subscribe(\n nextOrObserver?: NextFn | PartialObserver,\n error?: ErrorFn,\n complete?: CompleteFn\n ): Unsubscribe {\n let observer: Observer;\n\n if (\n nextOrObserver === undefined &&\n error === undefined &&\n complete === undefined\n ) {\n throw new Error('Missing Observer.');\n }\n\n // Assemble an Observer object when passed as callback functions.\n if (\n implementsAnyMethods(nextOrObserver as { [key: string]: unknown }, [\n 'next',\n 'error',\n 'complete'\n ])\n ) {\n observer = nextOrObserver as Observer;\n } else {\n observer = {\n next: nextOrObserver as NextFn,\n error,\n complete\n } as Observer;\n }\n\n if (observer.next === undefined) {\n observer.next = noop as NextFn;\n }\n if (observer.error === undefined) {\n observer.error = noop as ErrorFn;\n }\n if (observer.complete === undefined) {\n observer.complete = noop as CompleteFn;\n }\n\n const unsub = this.unsubscribeOne.bind(this, this.observers!.length);\n\n // Attempt to subscribe to a terminated Observable - we\n // just respond to the Observer with the final error or complete\n // event.\n if (this.finalized) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n try {\n if (this.finalError) {\n observer.error(this.finalError);\n } else {\n observer.complete();\n }\n } catch (e) {\n // nothing\n }\n return;\n });\n }\n\n this.observers!.push(observer as Observer);\n\n return unsub;\n }\n\n // Unsubscribe is synchronous - we guarantee that no events are sent to\n // any unsubscribed Observer.\n private unsubscribeOne(i: number): void {\n if (this.observers === undefined || this.observers[i] === undefined) {\n return;\n }\n\n delete this.observers[i];\n\n this.observerCount -= 1;\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\n this.onNoObservers(this);\n }\n }\n\n private forEachObserver(fn: (observer: Observer) => void): void {\n if (this.finalized) {\n // Already closed by previous event....just eat the additional values.\n return;\n }\n\n // Since sendOne calls asynchronously - there is no chance that\n // this.observers will become undefined.\n for (let i = 0; i < this.observers!.length; i++) {\n this.sendOne(i, fn);\n }\n }\n\n // Call the Observer via one of it's callback function. We are careful to\n // confirm that the observe has not been unsubscribed since this asynchronous\n // function had been queued.\n private sendOne(i: number, fn: (observer: Observer) => void): void {\n // Execute the callback asynchronously\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n if (this.observers !== undefined && this.observers[i] !== undefined) {\n try {\n fn(this.observers[i]);\n } catch (e) {\n // Ignore exceptions raised in Observers or missing methods of an\n // Observer.\n // Log error to console. b/31404806\n if (typeof console !== 'undefined' && console.error) {\n console.error(e);\n }\n }\n }\n });\n }\n\n private close(err?: Error): void {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n if (err !== undefined) {\n this.finalError = err;\n }\n // Proxy is no longer needed - garbage collect references\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n this.observers = undefined;\n this.onNoObservers = undefined;\n });\n }\n}\n\n/** Turn synchronous function into one called asynchronously. */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function async(fn: Function, onError?: ErrorFn): Function {\n return (...args: unknown[]) => {\n Promise.resolve(true)\n .then(() => {\n fn(...args);\n })\n .catch((error: Error) => {\n if (onError) {\n onError(error);\n }\n });\n };\n}\n\n/**\n * Return true if the object passed in implements any of the named methods.\n */\nfunction implementsAnyMethods(\n obj: { [key: string]: unknown },\n methods: string[]\n): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n for (const method of methods) {\n if (method in obj && typeof obj[method] === 'function') {\n return true;\n }\n }\n\n return false;\n}\n\nfunction noop(): void {\n // do nothing\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Check to make sure the appropriate number of arguments are provided for a public function.\n * Throws an error if it fails.\n *\n * @param fnName The function name\n * @param minCount The minimum number of arguments to allow for the function call\n * @param maxCount The maximum number of argument to allow for the function call\n * @param argCount The actual number of arguments provided.\n */\nexport const validateArgCount = function (\n fnName: string,\n minCount: number,\n maxCount: number,\n argCount: number\n): void {\n let argError;\n if (argCount < minCount) {\n argError = 'at least ' + minCount;\n } else if (argCount > maxCount) {\n argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\n }\n if (argError) {\n const error =\n fnName +\n ' failed: Was called with ' +\n argCount +\n (argCount === 1 ? ' argument.' : ' arguments.') +\n ' Expects ' +\n argError +\n '.';\n throw new Error(error);\n }\n};\n\n/**\n * Generates a string to prefix an error message about failed argument validation\n *\n * @param fnName The function name\n * @param argName The name of the argument\n * @return The prefix to add to the error thrown for validation.\n */\nexport function errorPrefix(fnName: string, argName: string): string {\n return `${fnName} failed: ${argName} argument `;\n}\n\n/**\n * @param fnName\n * @param argumentNumber\n * @param namespace\n * @param optional\n */\nexport function validateNamespace(\n fnName: string,\n namespace: string,\n optional: boolean\n): void {\n if (optional && !namespace) {\n return;\n }\n if (typeof namespace !== 'string') {\n //TODO: I should do more validation here. We only allow certain chars in namespaces.\n throw new Error(\n errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.'\n );\n }\n}\n\nexport function validateCallback(\n fnName: string,\n argumentName: string,\n // eslint-disable-next-line @typescript-eslint/ban-types\n callback: Function,\n optional: boolean\n): void {\n if (optional && !callback) {\n return;\n }\n if (typeof callback !== 'function') {\n throw new Error(\n errorPrefix(fnName, argumentName) + 'must be a valid function.'\n );\n }\n}\n\nexport function validateContextObject(\n fnName: string,\n argumentName: string,\n context: unknown,\n optional: boolean\n): void {\n if (optional && !context) {\n return;\n }\n if (typeof context !== 'object' || context === null) {\n throw new Error(\n errorPrefix(fnName, argumentName) + 'must be a valid context object.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from './assert';\n\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\n// so it's been modified.\n\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\n// use 2 characters in JavaScript. All 4-byte UTF-8 characters begin with a first\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\n// pair).\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\n\n/**\n * @param {string} str\n * @return {Array}\n */\nexport const stringToByteArray = function (str: string): number[] {\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n\n // Is this the lead surrogate in a surrogate pair?\n if (c >= 0xd800 && c <= 0xdbff) {\n const high = c - 0xd800; // the high 10 bits.\n i++;\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\n const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\n c = 0x10000 + (high << 10) + low;\n }\n\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (c < 65536) {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Calculate length without actually converting; useful for doing cheaper validation.\n * @param {string} str\n * @return {number}\n */\nexport const stringLength = function (str: string): number {\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n const c = str.charCodeAt(i);\n if (c < 128) {\n p++;\n } else if (c < 2048) {\n p += 2;\n } else if (c >= 0xd800 && c <= 0xdbff) {\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\n p += 4;\n i++; // skip trail surrogate.\n } else {\n p += 3;\n }\n }\n return p;\n};\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The amount of milliseconds to exponentially increase.\n */\nconst DEFAULT_INTERVAL_MILLIS = 1000;\n\n/**\n * The factor to backoff by.\n * Should be a number greater than 1.\n */\nconst DEFAULT_BACKOFF_FACTOR = 2;\n\n/**\n * The maximum milliseconds to increase to.\n *\n *

Visible for testing\n */\nexport const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\n\n/**\n * The percentage of backoff time to randomize by.\n * See\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\n * for context.\n *\n *

Visible for testing\n */\nexport const RANDOM_FACTOR = 0.5;\n\n/**\n * Based on the backoff method from\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\n */\nexport function calculateBackoffMillis(\n backoffCount: number,\n intervalMillis: number = DEFAULT_INTERVAL_MILLIS,\n backoffFactor: number = DEFAULT_BACKOFF_FACTOR\n): number {\n // Calculates an exponentially increasing value.\n // Deviation: calculates value from count and a constant interval, so we only need to save value\n // and count to restore state.\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\n\n // A random \"fuzz\" to avoid waves of retries.\n // Deviation: randomFactor is required.\n const randomWait = Math.round(\n // A fraction of the backoff value to add/subtract.\n // Deviation: changes multiplication order to improve readability.\n RANDOM_FACTOR *\n currBaseValue *\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\n // if we add or subtract.\n (Math.random() - 0.5) *\n 2\n );\n\n // Limits backoff to max to avoid effectively permanent backoff.\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Provide English ordinal letters after a number\n */\nexport function ordinal(i: number): string {\n if (!Number.isFinite(i)) {\n return `${i}`;\n }\n return i + indicator(i);\n}\n\nfunction indicator(i: number): string {\n i = Math.abs(i);\n const cent = i % 100;\n if (cent >= 10 && cent <= 20) {\n return 'th';\n }\n const dec = i % 10;\n if (dec === 1) {\n return 'st';\n }\n if (dec === 2) {\n return 'nd';\n }\n if (dec === 3) {\n return 'rd';\n }\n return 'th';\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Compat {\n _delegate: T;\n}\n\nexport function getModularInstance(\n service: Compat | ExpService\n): ExpService {\n if (service && (service as Compat)._delegate) {\n return (service as Compat)._delegate;\n } else {\n return service as ExpService;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSTANTS } from './src/constants';\n\n// Overriding the constant (we should be the only ones doing this)\nCONSTANTS.NODE_CLIENT = true;\n\nexport * from './src/assert';\nexport * from './src/crypt';\nexport * from './src/constants';\nexport * from './src/deepCopy';\nexport * from './src/defaults';\nexport * from './src/deferred';\nexport * from './src/emulator';\nexport * from './src/environment';\nexport * from './src/errors';\nexport * from './src/json';\nexport * from './src/jwt';\nexport * from './src/obj';\nexport * from './src/promise';\nexport * from './src/query';\nexport * from './src/sha1';\nexport * from './src/subscribe';\nexport * from './src/validation';\nexport * from './src/utf8';\nexport * from './src/exponential_backoff';\nexport * from './src/formatters';\nexport * from './src/compat';\nexport * from './src/global';\nexport * from './src/url';\n"],"names":["stringToByteArray"],"mappings":";;AAAA,CAAA,CAAA;;;;;;;;;;;;;;;AAeG,CAAA,CAAA;AAEH,CAAA,CAAA;;AAEG,CAAA,CAAA;AAEU,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,SAAS,CAAG,CAAA,CAAA;AACvB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;;AAEG,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AACH,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAW,EAAE,CAAK,CAAA,CAAA,CAAA,CAAA;AAClB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;;AAEG,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AACH,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CA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AA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AACA,CAAS,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAC,CAAW,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAG,CAAI,CAAA,CAAA,CAAA;;"} \ No newline at end of file diff --git a/node_modules/@firebase/util/dist/node-esm/package.json b/node_modules/@firebase/util/dist/node-esm/package.json new file mode 100644 index 0000000..7c34deb --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/package.json @@ -0,0 +1 @@ +{"type":"module"} \ No newline at end of file diff --git a/node_modules/@firebase/util/dist/node-esm/src/assert.d.ts b/node_modules/@firebase/util/dist/node-esm/src/assert.d.ts new file mode 100644 index 0000000..cabf52a --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/assert.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Throws an error if the provided assertion is falsy + */ +export declare const assert: (assertion: unknown, message: string) => void; +/** + * Returns an Error object suitable for throwing. + */ +export declare const assertionError: (message: string) => Error; diff --git a/node_modules/@firebase/util/dist/node-esm/src/compat.d.ts b/node_modules/@firebase/util/dist/node-esm/src/compat.d.ts new file mode 100644 index 0000000..2d15505 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/compat.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface Compat { + _delegate: T; +} +export declare function getModularInstance(service: Compat | ExpService): ExpService; diff --git a/node_modules/@firebase/util/dist/node-esm/src/constants.d.ts b/node_modules/@firebase/util/dist/node-esm/src/constants.d.ts new file mode 100644 index 0000000..9904c9b --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/constants.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time. + */ +export declare const CONSTANTS: { + /** + * @define {boolean} Whether this is the client Node.js SDK. + */ + NODE_CLIENT: boolean; + /** + * @define {boolean} Whether this is the Admin Node.js SDK. + */ + NODE_ADMIN: boolean; + /** + * Firebase SDK Version + */ + SDK_VERSION: string; +}; diff --git a/node_modules/@firebase/util/dist/node-esm/src/crypt.d.ts b/node_modules/@firebase/util/dist/node-esm/src/crypt.d.ts new file mode 100644 index 0000000..1f8335a --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/crypt.d.ts @@ -0,0 +1,66 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +interface Base64 { + byteToCharMap_: { + [key: number]: string; + } | null; + charToByteMap_: { + [key: string]: number; + } | null; + byteToCharMapWebSafe_: { + [key: number]: string; + } | null; + charToByteMapWebSafe_: { + [key: string]: number; + } | null; + ENCODED_VALS_BASE: string; + readonly ENCODED_VALS: string; + readonly ENCODED_VALS_WEBSAFE: string; + HAS_NATIVE_SUPPORT: boolean; + encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string; + encodeString(input: string, webSafe?: boolean): string; + decodeString(input: string, webSafe: boolean): string; + decodeStringToByteArray(input: string, webSafe: boolean): number[]; + init_(): void; +} +export declare const base64: Base64; +/** + * An error encountered while decoding base64 string. + */ +export declare class DecodeBase64StringError extends Error { + readonly name = "DecodeBase64StringError"; +} +/** + * URL-safe base64 encoding + */ +export declare const base64Encode: (str: string) => string; +/** + * URL-safe base64 encoding (without "." padding in the end). + * e.g. Used in JSON Web Token (JWT) parts. + */ +export declare const base64urlEncodeWithoutPadding: (str: string) => string; +/** + * URL-safe base64 decoding + * + * NOTE: DO NOT use the global atob() function - it does NOT support the + * base64Url variant encoding. + * + * @param str To be decoded + * @return Decoded result, if possible + */ +export declare const base64Decode: (str: string) => string | null; +export {}; diff --git a/node_modules/@firebase/util/dist/node-esm/src/deepCopy.d.ts b/node_modules/@firebase/util/dist/node-esm/src/deepCopy.d.ts new file mode 100644 index 0000000..063ced0 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/deepCopy.d.ts @@ -0,0 +1,35 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Do a deep-copy of basic JavaScript Objects or Arrays. + */ +export declare function deepCopy(value: T): T; +/** + * Copy properties from source to target (recursively allows extension + * of Objects and Arrays). Scalar values in the target are over-written. + * If target is undefined, an object of the appropriate type will be created + * (and returned). + * + * We recursively copy all child properties of plain Objects in the source- so + * that namespace- like dictionaries are merged. + * + * Note that the target can be a function, in which case the properties in + * the source Object are copied onto it as static properties of the Function. + * + * Note: we don't merge __proto__ to prevent prototype pollution + */ +export declare function deepExtend(target: unknown, source: unknown): unknown; diff --git a/node_modules/@firebase/util/dist/node-esm/src/defaults.d.ts b/node_modules/@firebase/util/dist/node-esm/src/defaults.d.ts new file mode 100644 index 0000000..d6f32bf --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/defaults.d.ts @@ -0,0 +1,79 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Keys for experimental properties on the `FirebaseDefaults` object. + * @public + */ +export type ExperimentalKey = 'authTokenSyncURL' | 'authIdTokenMaxAge'; +/** + * An object that can be injected into the environment as __FIREBASE_DEFAULTS__, + * either as a property of globalThis, a shell environment variable, or a + * cookie. + * + * This object can be used to automatically configure and initialize + * a Firebase app as well as any emulators. + * + * @public + */ +export interface FirebaseDefaults { + config?: Record; + emulatorHosts?: Record; + _authTokenSyncURL?: string; + _authIdTokenMaxAge?: number; + /** + * Override Firebase's runtime environment detection and + * force the SDK to act as if it were in the specified environment. + */ + forceEnvironment?: 'browser' | 'node'; + [key: string]: unknown; +} +declare global { + var __FIREBASE_DEFAULTS__: FirebaseDefaults | undefined; +} +/** + * Get the __FIREBASE_DEFAULTS__ object. It checks in order: + * (1) if such an object exists as a property of `globalThis` + * (2) if such an object was provided on a shell environment variable + * (3) if such an object exists in a cookie + * @public + */ +export declare const getDefaults: () => FirebaseDefaults | undefined; +/** + * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object + * for the given product. + * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available + * @public + */ +export declare const getDefaultEmulatorHost: (productName: string) => string | undefined; +/** + * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object + * for the given product. + * @returns a pair of hostname and port like `["::1", 4000]` if available + * @public + */ +export declare const getDefaultEmulatorHostnameAndPort: (productName: string) => [hostname: string, port: number] | undefined; +/** + * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object. + * @public + */ +export declare const getDefaultAppConfig: () => Record | undefined; +/** + * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties + * prefixed by "_") + * @public + */ +export declare const getExperimentalSetting: (name: T) => FirebaseDefaults[`_${T}`]; diff --git a/node_modules/@firebase/util/dist/node-esm/src/deferred.d.ts b/node_modules/@firebase/util/dist/node-esm/src/deferred.d.ts new file mode 100644 index 0000000..d6c37b8 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/deferred.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare class Deferred { + promise: Promise; + reject: (value?: unknown) => void; + resolve: (value?: unknown) => void; + constructor(); + /** + * Our API internals are not promisified and cannot because our callback APIs have subtle expectations around + * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback + * and returns a node-style callback which will resolve or reject the Deferred's promise. + */ + wrapCallback(callback?: (error?: unknown, value?: unknown) => void): (error: unknown, value?: unknown) => void; +} diff --git a/node_modules/@firebase/util/dist/node-esm/src/emulator.d.ts b/node_modules/@firebase/util/dist/node-esm/src/emulator.d.ts new file mode 100644 index 0000000..782d0a5 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/emulator.d.ts @@ -0,0 +1,54 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export type FirebaseSignInProvider = 'custom' | 'email' | 'password' | 'phone' | 'anonymous' | 'google.com' | 'facebook.com' | 'github.com' | 'twitter.com' | 'microsoft.com' | 'apple.com'; +interface FirebaseIdToken { + iss: string; + aud: string; + sub: string; + iat: number; + exp: number; + user_id: string; + auth_time: number; + provider_id?: 'anonymous'; + email?: string; + email_verified?: boolean; + phone_number?: string; + name?: string; + picture?: string; + firebase: { + sign_in_provider: FirebaseSignInProvider; + identities?: { + [provider in FirebaseSignInProvider]?: string[]; + }; + }; + [claim: string]: unknown; + uid?: never; +} +export type EmulatorMockTokenOptions = ({ + user_id: string; +} | { + sub: string; +}) & Partial; +export declare function createMockUserToken(token: EmulatorMockTokenOptions, projectId?: string): string; +/** + * Updates Emulator Banner. Primarily used for Firebase Studio + * @param name + * @param isRunningEmulator + * @public + */ +export declare function updateEmulatorBanner(name: string, isRunningEmulator: boolean): void; +export {}; diff --git a/node_modules/@firebase/util/dist/node-esm/src/environment.d.ts b/node_modules/@firebase/util/dist/node-esm/src/environment.d.ts new file mode 100644 index 0000000..71a53df --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/environment.d.ts @@ -0,0 +1,92 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns navigator.userAgent string or '' if it's not defined. + * @return user agent string + */ +export declare function getUA(): string; +/** + * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device. + * + * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap + * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally + * wait for a callback. + */ +export declare function isMobileCordova(): boolean; +/** + * Detect Node.js. + * + * @return true if Node.js environment is detected or specified. + */ +export declare function isNode(): boolean; +/** + * Detect Browser Environment. + * Note: This will return true for certain test frameworks that are incompletely + * mimicking a browser, and should not lead to assuming all browser APIs are + * available. + */ +export declare function isBrowser(): boolean; +/** + * Detect Web Worker context. + */ +export declare function isWebWorker(): boolean; +/** + * Detect Cloudflare Worker context. + */ +export declare function isCloudflareWorker(): boolean; +export declare function isBrowserExtension(): boolean; +/** + * Detect React Native. + * + * @return true if ReactNative environment is detected. + */ +export declare function isReactNative(): boolean; +/** Detects Electron apps. */ +export declare function isElectron(): boolean; +/** Detects Internet Explorer. */ +export declare function isIE(): boolean; +/** Detects Universal Windows Platform apps. */ +export declare function isUWP(): boolean; +/** + * Detect whether the current SDK build is the Node version. + * + * @return true if it's the Node SDK build. + */ +export declare function isNodeSdk(): boolean; +/** Returns true if we are running in Safari. */ +export declare function isSafari(): boolean; +/** Returns true if we are running in Safari or WebKit */ +export declare function isSafariOrWebkit(): boolean; +/** + * This method checks if indexedDB is supported by current browser/service worker context + * @return true if indexedDB is supported by current browser/service worker context + */ +export declare function isIndexedDBAvailable(): boolean; +/** + * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject + * if errors occur during the database open operation. + * + * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox + * private browsing) + */ +export declare function validateIndexedDBOpenable(): Promise; +/** + * + * This method checks whether cookie is enabled within current browser + * @return true if cookie is enabled within current browser + */ +export declare function areCookiesEnabled(): boolean; diff --git a/node_modules/@firebase/util/dist/node-esm/src/errors.d.ts b/node_modules/@firebase/util/dist/node-esm/src/errors.d.ts new file mode 100644 index 0000000..fa9afa0 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/errors.d.ts @@ -0,0 +1,87 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview Standardized Firebase Error. + * + * Usage: + * + * // TypeScript string literals for type-safe codes + * type Err = + * 'unknown' | + * 'object-not-found' + * ; + * + * // Closure enum for type-safe error codes + * // at-enum {string} + * var Err = { + * UNKNOWN: 'unknown', + * OBJECT_NOT_FOUND: 'object-not-found', + * } + * + * let errors: Map = { + * 'generic-error': "Unknown error", + * 'file-not-found': "Could not find file: {$file}", + * }; + * + * // Type-safe function - must pass a valid error code as param. + * let error = new ErrorFactory('service', 'Service', errors); + * + * ... + * throw error.create(Err.GENERIC); + * ... + * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName}); + * ... + * // Service: Could not file file: foo.txt (service/file-not-found). + * + * catch (e) { + * assert(e.message === "Could not find file: foo.txt."); + * if ((e as FirebaseError)?.code === 'service/file-not-found') { + * console.log("Could not read file: " + e['file']); + * } + * } + */ +export type ErrorMap = { + readonly [K in ErrorCode]: string; +}; +export interface StringLike { + toString(): string; +} +export interface ErrorData { + [key: string]: unknown; +} +export declare class FirebaseError extends Error { + /** The error code for this error. */ + readonly code: string; + /** Custom data for this error. */ + customData?: Record | undefined; + /** The custom name for all FirebaseErrors. */ + readonly name: string; + constructor( + /** The error code for this error. */ + code: string, message: string, + /** Custom data for this error. */ + customData?: Record | undefined); +} +export declare class ErrorFactory { + private readonly service; + private readonly serviceName; + private readonly errors; + constructor(service: string, serviceName: string, errors: ErrorMap); + create(code: K, ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []): FirebaseError; +} diff --git a/node_modules/@firebase/util/dist/node-esm/src/exponential_backoff.d.ts b/node_modules/@firebase/util/dist/node-esm/src/exponential_backoff.d.ts new file mode 100644 index 0000000..f475721 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/exponential_backoff.d.ts @@ -0,0 +1,37 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The maximum milliseconds to increase to. + * + *

Visible for testing + */ +export declare const MAX_VALUE_MILLIS: number; +/** + * The percentage of backoff time to randomize by. + * See + * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic + * for context. + * + *

Visible for testing + */ +export declare const RANDOM_FACTOR = 0.5; +/** + * Based on the backoff method from + * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js. + * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around. + */ +export declare function calculateBackoffMillis(backoffCount: number, intervalMillis?: number, backoffFactor?: number): number; diff --git a/node_modules/@firebase/util/dist/node-esm/src/formatters.d.ts b/node_modules/@firebase/util/dist/node-esm/src/formatters.d.ts new file mode 100644 index 0000000..f9d372e --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/formatters.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provide English ordinal letters after a number + */ +export declare function ordinal(i: number): string; diff --git a/node_modules/@firebase/util/dist/node-esm/src/global.d.ts b/node_modules/@firebase/util/dist/node-esm/src/global.d.ts new file mode 100644 index 0000000..7e5e687 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/global.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Polyfill for `globalThis` object. + * @returns the `globalThis` object for the given environment. + * @public + */ +export declare function getGlobal(): typeof globalThis; diff --git a/node_modules/@firebase/util/dist/node-esm/src/json.d.ts b/node_modules/@firebase/util/dist/node-esm/src/json.d.ts new file mode 100644 index 0000000..b1de286 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/json.d.ts @@ -0,0 +1,29 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Evaluates a JSON string into a javascript object. + * + * @param {string} str A string containing JSON. + * @return {*} The javascript object representing the specified JSON. + */ +export declare function jsonEval(str: string): unknown; +/** + * Returns JSON representing a javascript object. + * @param {*} data JavaScript object to be stringified. + * @return {string} The JSON contents of the object. + */ +export declare function stringify(data: unknown): string; diff --git a/node_modules/@firebase/util/dist/node-esm/src/jwt.d.ts b/node_modules/@firebase/util/dist/node-esm/src/jwt.d.ts new file mode 100644 index 0000000..4a1d809 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/jwt.d.ts @@ -0,0 +1,73 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +interface Claims { + [key: string]: {}; +} +interface DecodedToken { + header: object; + claims: Claims; + data: object; + signature: string; +} +/** + * Decodes a Firebase auth. token into constituent parts. + * + * Notes: + * - May return with invalid / incomplete claims if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +export declare const decode: (token: string) => DecodedToken; +interface DecodedToken { + header: object; + claims: Claims; + data: object; + signature: string; +} +/** + * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the + * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +export declare const isValidTimestamp: (token: string) => boolean; +/** + * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise. + * + * Notes: + * - May return null if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +export declare const issuedAtTime: (token: string) => number | null; +/** + * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +export declare const isValidFormat: (token: string) => boolean; +/** + * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +export declare const isAdmin: (token: string) => boolean; +export {}; diff --git a/node_modules/@firebase/util/dist/node-esm/src/obj.d.ts b/node_modules/@firebase/util/dist/node-esm/src/obj.d.ts new file mode 100644 index 0000000..e29bb4c --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/obj.d.ts @@ -0,0 +1,30 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare function contains(obj: T, key: string): boolean; +export declare function safeGet(obj: T, key: K): T[K] | undefined; +export declare function isEmpty(obj: object): obj is {}; +export declare function map(obj: { + [key in K]: V; +}, fn: (value: V, key: K, obj: { + [key in K]: V; +}) => U, contextObj?: unknown): { + [key in K]: U; +}; +/** + * Deep equal two objects. Support Arrays and Objects. + */ +export declare function deepEqual(a: object, b: object): boolean; diff --git a/node_modules/@firebase/util/dist/node-esm/src/postinstall.d.ts b/node_modules/@firebase/util/dist/node-esm/src/postinstall.d.ts new file mode 100644 index 0000000..c623b76 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/postinstall.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import type { FirebaseDefaults } from './defaults'; +export declare const getDefaultsFromPostinstall: () => FirebaseDefaults | undefined; diff --git a/node_modules/@firebase/util/dist/node-esm/src/promise.d.ts b/node_modules/@firebase/util/dist/node-esm/src/promise.d.ts new file mode 100644 index 0000000..3738ab7 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/promise.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Rejects if the given promise doesn't resolve in timeInMS milliseconds. + * @internal + */ +export declare function promiseWithTimeout(promise: Promise, timeInMS?: number): Promise; diff --git a/node_modules/@firebase/util/dist/node-esm/src/query.d.ts b/node_modules/@firebase/util/dist/node-esm/src/query.d.ts new file mode 100644 index 0000000..1c67596 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/query.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a + * params object (e.g. {arg: 'val', arg2: 'val2'}) + * Note: You must prepend it with ? when adding it to a URL. + */ +export declare function querystring(querystringParams: { + [key: string]: string | number; +}): string; +/** + * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object + * (e.g. {arg: 'val', arg2: 'val2'}) + */ +export declare function querystringDecode(querystring: string): Record; +/** + * Extract the query string part of a URL, including the leading question mark (if present). + */ +export declare function extractQuerystring(url: string): string; diff --git a/node_modules/@firebase/util/dist/node-esm/src/sha1.d.ts b/node_modules/@firebase/util/dist/node-esm/src/sha1.d.ts new file mode 100644 index 0000000..2320491 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/sha1.d.ts @@ -0,0 +1,84 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview SHA-1 cryptographic hash. + * Variable names follow the notation in FIPS PUB 180-3: + * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf. + * + * Usage: + * var sha1 = new sha1(); + * sha1.update(bytes); + * var hash = sha1.digest(); + * + * Performance: + * Chrome 23: ~400 Mbit/s + * Firefox 16: ~250 Mbit/s + * + */ +/** + * SHA-1 cryptographic hash constructor. + * + * The properties declared here are discussed in the above algorithm document. + * @constructor + * @final + * @struct + */ +export declare class Sha1 { + /** + * Holds the previous values of accumulated variables a-e in the compress_ + * function. + * @private + */ + private chain_; + /** + * A buffer holding the partially computed hash result. + * @private + */ + private buf_; + /** + * An array of 80 bytes, each a part of the message to be hashed. Referred to + * as the message schedule in the docs. + * @private + */ + private W_; + /** + * Contains data needed to pad messages less than 64 bytes. + * @private + */ + private pad_; + /** + * @private {number} + */ + private inbuf_; + /** + * @private {number} + */ + private total_; + blockSize: number; + constructor(); + reset(): void; + /** + * Internal compress helper function. + * @param buf Block to compress. + * @param offset Offset of the block in the buffer. + * @private + */ + compress_(buf: number[] | Uint8Array | string, offset?: number): void; + update(bytes?: number[] | Uint8Array | string, length?: number): void; + /** @override */ + digest(): number[]; +} diff --git a/node_modules/@firebase/util/dist/node-esm/src/subscribe.d.ts b/node_modules/@firebase/util/dist/node-esm/src/subscribe.d.ts new file mode 100644 index 0000000..f01d5e5 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/subscribe.d.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export type NextFn = (value: T) => void; +export type ErrorFn = (error: Error) => void; +export type CompleteFn = () => void; +export interface Observer { + next: NextFn; + error: ErrorFn; + complete: CompleteFn; +} +export type PartialObserver = Partial>; +export type Unsubscribe = () => void; +/** + * The Subscribe interface has two forms - passing the inline function + * callbacks, or a object interface with callback properties. + */ +export interface Subscribe { + (next?: NextFn, error?: ErrorFn, complete?: CompleteFn): Unsubscribe; + (observer: PartialObserver): Unsubscribe; +} +export interface Observable { + subscribe: Subscribe; +} +export type Executor = (observer: Observer) => void; +/** + * Helper to make a Subscribe function (just like Promise helps make a + * Thenable). + * + * @param executor Function which can make calls to a single Observer + * as a proxy. + * @param onNoObservers Callback when count of Observers goes to zero. + */ +export declare function createSubscribe(executor: Executor, onNoObservers?: Executor): Subscribe; +/** Turn synchronous function into one called asynchronously. */ +export declare function async(fn: Function, onError?: ErrorFn): Function; diff --git a/node_modules/@firebase/util/dist/node-esm/src/url.d.ts b/node_modules/@firebase/util/dist/node-esm/src/url.d.ts new file mode 100644 index 0000000..c999848 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/url.d.ts @@ -0,0 +1,27 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Checks whether host is a cloud workstation or not. + * @public + */ +export declare function isCloudWorkstation(url: string): boolean; +/** + * Makes a fetch request to the given server. + * Mostly used for forwarding cookies in Firebase Studio. + * @public + */ +export declare function pingServer(endpoint: string): Promise; diff --git a/node_modules/@firebase/util/dist/node-esm/src/utf8.d.ts b/node_modules/@firebase/util/dist/node-esm/src/utf8.d.ts new file mode 100644 index 0000000..1883306 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/utf8.d.ts @@ -0,0 +1,27 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @param {string} str + * @return {Array} + */ +export declare const stringToByteArray: (str: string) => number[]; +/** + * Calculate length without actually converting; useful for doing cheaper validation. + * @param {string} str + * @return {number} + */ +export declare const stringLength: (str: string) => number; diff --git a/node_modules/@firebase/util/dist/node-esm/src/validation.d.ts b/node_modules/@firebase/util/dist/node-esm/src/validation.d.ts new file mode 100644 index 0000000..f8c00b9 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/src/validation.d.ts @@ -0,0 +1,43 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Check to make sure the appropriate number of arguments are provided for a public function. + * Throws an error if it fails. + * + * @param fnName The function name + * @param minCount The minimum number of arguments to allow for the function call + * @param maxCount The maximum number of argument to allow for the function call + * @param argCount The actual number of arguments provided. + */ +export declare const validateArgCount: (fnName: string, minCount: number, maxCount: number, argCount: number) => void; +/** + * Generates a string to prefix an error message about failed argument validation + * + * @param fnName The function name + * @param argName The name of the argument + * @return The prefix to add to the error thrown for validation. + */ +export declare function errorPrefix(fnName: string, argName: string): string; +/** + * @param fnName + * @param argumentNumber + * @param namespace + * @param optional + */ +export declare function validateNamespace(fnName: string, namespace: string, optional: boolean): void; +export declare function validateCallback(fnName: string, argumentName: string, callback: Function, optional: boolean): void; +export declare function validateContextObject(fnName: string, argumentName: string, context: unknown, optional: boolean): void; diff --git a/node_modules/@firebase/util/dist/node-esm/test/base64.test.d.ts b/node_modules/@firebase/util/dist/node-esm/test/base64.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/test/base64.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/@firebase/util/dist/node-esm/test/compat.test.d.ts b/node_modules/@firebase/util/dist/node-esm/test/compat.test.d.ts new file mode 100644 index 0000000..daa6d5d --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/test/compat.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/util/dist/node-esm/test/deepCopy.test.d.ts b/node_modules/@firebase/util/dist/node-esm/test/deepCopy.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/test/deepCopy.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/@firebase/util/dist/node-esm/test/defaults.test.d.ts b/node_modules/@firebase/util/dist/node-esm/test/defaults.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/test/defaults.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/@firebase/util/dist/node-esm/test/emulator.test.d.ts b/node_modules/@firebase/util/dist/node-esm/test/emulator.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/test/emulator.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/@firebase/util/dist/node-esm/test/environments.test.d.ts b/node_modules/@firebase/util/dist/node-esm/test/environments.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/test/environments.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/util/dist/node-esm/test/errors.test.d.ts b/node_modules/@firebase/util/dist/node-esm/test/errors.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/test/errors.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/@firebase/util/dist/node-esm/test/exponential_backoff.test.d.ts b/node_modules/@firebase/util/dist/node-esm/test/exponential_backoff.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/test/exponential_backoff.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/util/dist/node-esm/test/object.test.d.ts b/node_modules/@firebase/util/dist/node-esm/test/object.test.d.ts new file mode 100644 index 0000000..daa6d5d --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/test/object.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/util/dist/node-esm/test/subscribe.test.d.ts b/node_modules/@firebase/util/dist/node-esm/test/subscribe.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/node_modules/@firebase/util/dist/node-esm/test/subscribe.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/util/dist/postinstall.js b/node_modules/@firebase/util/dist/postinstall.js new file mode 100644 index 0000000..8bee84b --- /dev/null +++ b/node_modules/@firebase/util/dist/postinstall.js @@ -0,0 +1,3 @@ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.getDefaultsFromPostinstall = () => (undefined); \ No newline at end of file diff --git a/node_modules/@firebase/util/dist/postinstall.mjs b/node_modules/@firebase/util/dist/postinstall.mjs new file mode 100644 index 0000000..0c02b08 --- /dev/null +++ b/node_modules/@firebase/util/dist/postinstall.mjs @@ -0,0 +1,2 @@ +const getDefaultsFromPostinstall = () => (undefined); +export { getDefaultsFromPostinstall }; \ No newline at end of file diff --git a/node_modules/@firebase/util/dist/src/assert.d.ts b/node_modules/@firebase/util/dist/src/assert.d.ts new file mode 100644 index 0000000..cabf52a --- /dev/null +++ b/node_modules/@firebase/util/dist/src/assert.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Throws an error if the provided assertion is falsy + */ +export declare const assert: (assertion: unknown, message: string) => void; +/** + * Returns an Error object suitable for throwing. + */ +export declare const assertionError: (message: string) => Error; diff --git a/node_modules/@firebase/util/dist/src/compat.d.ts b/node_modules/@firebase/util/dist/src/compat.d.ts new file mode 100644 index 0000000..2d15505 --- /dev/null +++ b/node_modules/@firebase/util/dist/src/compat.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface Compat { + _delegate: T; +} +export declare function getModularInstance(service: Compat | ExpService): ExpService; diff --git a/node_modules/@firebase/util/dist/src/constants.d.ts b/node_modules/@firebase/util/dist/src/constants.d.ts new file mode 100644 index 0000000..9904c9b --- /dev/null +++ b/node_modules/@firebase/util/dist/src/constants.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time. + */ +export declare const CONSTANTS: { + /** + * @define {boolean} Whether this is the client Node.js SDK. + */ + NODE_CLIENT: boolean; + /** + * @define {boolean} Whether this is the Admin Node.js SDK. + */ + NODE_ADMIN: boolean; + /** + * Firebase SDK Version + */ + SDK_VERSION: string; +}; diff --git a/node_modules/@firebase/util/dist/src/crypt.d.ts b/node_modules/@firebase/util/dist/src/crypt.d.ts new file mode 100644 index 0000000..1f8335a --- /dev/null +++ b/node_modules/@firebase/util/dist/src/crypt.d.ts @@ -0,0 +1,66 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +interface Base64 { + byteToCharMap_: { + [key: number]: string; + } | null; + charToByteMap_: { + [key: string]: number; + } | null; + byteToCharMapWebSafe_: { + [key: number]: string; + } | null; + charToByteMapWebSafe_: { + [key: string]: number; + } | null; + ENCODED_VALS_BASE: string; + readonly ENCODED_VALS: string; + readonly ENCODED_VALS_WEBSAFE: string; + HAS_NATIVE_SUPPORT: boolean; + encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string; + encodeString(input: string, webSafe?: boolean): string; + decodeString(input: string, webSafe: boolean): string; + decodeStringToByteArray(input: string, webSafe: boolean): number[]; + init_(): void; +} +export declare const base64: Base64; +/** + * An error encountered while decoding base64 string. + */ +export declare class DecodeBase64StringError extends Error { + readonly name = "DecodeBase64StringError"; +} +/** + * URL-safe base64 encoding + */ +export declare const base64Encode: (str: string) => string; +/** + * URL-safe base64 encoding (without "." padding in the end). + * e.g. Used in JSON Web Token (JWT) parts. + */ +export declare const base64urlEncodeWithoutPadding: (str: string) => string; +/** + * URL-safe base64 decoding + * + * NOTE: DO NOT use the global atob() function - it does NOT support the + * base64Url variant encoding. + * + * @param str To be decoded + * @return Decoded result, if possible + */ +export declare const base64Decode: (str: string) => string | null; +export {}; diff --git a/node_modules/@firebase/util/dist/src/deepCopy.d.ts b/node_modules/@firebase/util/dist/src/deepCopy.d.ts new file mode 100644 index 0000000..063ced0 --- /dev/null +++ b/node_modules/@firebase/util/dist/src/deepCopy.d.ts @@ -0,0 +1,35 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Do a deep-copy of basic JavaScript Objects or Arrays. + */ +export declare function deepCopy(value: T): T; +/** + * Copy properties from source to target (recursively allows extension + * of Objects and Arrays). Scalar values in the target are over-written. + * If target is undefined, an object of the appropriate type will be created + * (and returned). + * + * We recursively copy all child properties of plain Objects in the source- so + * that namespace- like dictionaries are merged. + * + * Note that the target can be a function, in which case the properties in + * the source Object are copied onto it as static properties of the Function. + * + * Note: we don't merge __proto__ to prevent prototype pollution + */ +export declare function deepExtend(target: unknown, source: unknown): unknown; diff --git a/node_modules/@firebase/util/dist/src/defaults.d.ts b/node_modules/@firebase/util/dist/src/defaults.d.ts new file mode 100644 index 0000000..d6f32bf --- /dev/null +++ b/node_modules/@firebase/util/dist/src/defaults.d.ts @@ -0,0 +1,79 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Keys for experimental properties on the `FirebaseDefaults` object. + * @public + */ +export type ExperimentalKey = 'authTokenSyncURL' | 'authIdTokenMaxAge'; +/** + * An object that can be injected into the environment as __FIREBASE_DEFAULTS__, + * either as a property of globalThis, a shell environment variable, or a + * cookie. + * + * This object can be used to automatically configure and initialize + * a Firebase app as well as any emulators. + * + * @public + */ +export interface FirebaseDefaults { + config?: Record; + emulatorHosts?: Record; + _authTokenSyncURL?: string; + _authIdTokenMaxAge?: number; + /** + * Override Firebase's runtime environment detection and + * force the SDK to act as if it were in the specified environment. + */ + forceEnvironment?: 'browser' | 'node'; + [key: string]: unknown; +} +declare global { + var __FIREBASE_DEFAULTS__: FirebaseDefaults | undefined; +} +/** + * Get the __FIREBASE_DEFAULTS__ object. It checks in order: + * (1) if such an object exists as a property of `globalThis` + * (2) if such an object was provided on a shell environment variable + * (3) if such an object exists in a cookie + * @public + */ +export declare const getDefaults: () => FirebaseDefaults | undefined; +/** + * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object + * for the given product. + * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available + * @public + */ +export declare const getDefaultEmulatorHost: (productName: string) => string | undefined; +/** + * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object + * for the given product. + * @returns a pair of hostname and port like `["::1", 4000]` if available + * @public + */ +export declare const getDefaultEmulatorHostnameAndPort: (productName: string) => [hostname: string, port: number] | undefined; +/** + * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object. + * @public + */ +export declare const getDefaultAppConfig: () => Record | undefined; +/** + * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties + * prefixed by "_") + * @public + */ +export declare const getExperimentalSetting: (name: T) => FirebaseDefaults[`_${T}`]; diff --git a/node_modules/@firebase/util/dist/src/deferred.d.ts b/node_modules/@firebase/util/dist/src/deferred.d.ts new file mode 100644 index 0000000..d6c37b8 --- /dev/null +++ b/node_modules/@firebase/util/dist/src/deferred.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare class Deferred { + promise: Promise; + reject: (value?: unknown) => void; + resolve: (value?: unknown) => void; + constructor(); + /** + * Our API internals are not promisified and cannot because our callback APIs have subtle expectations around + * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback + * and returns a node-style callback which will resolve or reject the Deferred's promise. + */ + wrapCallback(callback?: (error?: unknown, value?: unknown) => void): (error: unknown, value?: unknown) => void; +} diff --git a/node_modules/@firebase/util/dist/src/emulator.d.ts b/node_modules/@firebase/util/dist/src/emulator.d.ts new file mode 100644 index 0000000..782d0a5 --- /dev/null +++ b/node_modules/@firebase/util/dist/src/emulator.d.ts @@ -0,0 +1,54 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export type FirebaseSignInProvider = 'custom' | 'email' | 'password' | 'phone' | 'anonymous' | 'google.com' | 'facebook.com' | 'github.com' | 'twitter.com' | 'microsoft.com' | 'apple.com'; +interface FirebaseIdToken { + iss: string; + aud: string; + sub: string; + iat: number; + exp: number; + user_id: string; + auth_time: number; + provider_id?: 'anonymous'; + email?: string; + email_verified?: boolean; + phone_number?: string; + name?: string; + picture?: string; + firebase: { + sign_in_provider: FirebaseSignInProvider; + identities?: { + [provider in FirebaseSignInProvider]?: string[]; + }; + }; + [claim: string]: unknown; + uid?: never; +} +export type EmulatorMockTokenOptions = ({ + user_id: string; +} | { + sub: string; +}) & Partial; +export declare function createMockUserToken(token: EmulatorMockTokenOptions, projectId?: string): string; +/** + * Updates Emulator Banner. Primarily used for Firebase Studio + * @param name + * @param isRunningEmulator + * @public + */ +export declare function updateEmulatorBanner(name: string, isRunningEmulator: boolean): void; +export {}; diff --git a/node_modules/@firebase/util/dist/src/environment.d.ts b/node_modules/@firebase/util/dist/src/environment.d.ts new file mode 100644 index 0000000..71a53df --- /dev/null +++ b/node_modules/@firebase/util/dist/src/environment.d.ts @@ -0,0 +1,92 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns navigator.userAgent string or '' if it's not defined. + * @return user agent string + */ +export declare function getUA(): string; +/** + * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device. + * + * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap + * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally + * wait for a callback. + */ +export declare function isMobileCordova(): boolean; +/** + * Detect Node.js. + * + * @return true if Node.js environment is detected or specified. + */ +export declare function isNode(): boolean; +/** + * Detect Browser Environment. + * Note: This will return true for certain test frameworks that are incompletely + * mimicking a browser, and should not lead to assuming all browser APIs are + * available. + */ +export declare function isBrowser(): boolean; +/** + * Detect Web Worker context. + */ +export declare function isWebWorker(): boolean; +/** + * Detect Cloudflare Worker context. + */ +export declare function isCloudflareWorker(): boolean; +export declare function isBrowserExtension(): boolean; +/** + * Detect React Native. + * + * @return true if ReactNative environment is detected. + */ +export declare function isReactNative(): boolean; +/** Detects Electron apps. */ +export declare function isElectron(): boolean; +/** Detects Internet Explorer. */ +export declare function isIE(): boolean; +/** Detects Universal Windows Platform apps. */ +export declare function isUWP(): boolean; +/** + * Detect whether the current SDK build is the Node version. + * + * @return true if it's the Node SDK build. + */ +export declare function isNodeSdk(): boolean; +/** Returns true if we are running in Safari. */ +export declare function isSafari(): boolean; +/** Returns true if we are running in Safari or WebKit */ +export declare function isSafariOrWebkit(): boolean; +/** + * This method checks if indexedDB is supported by current browser/service worker context + * @return true if indexedDB is supported by current browser/service worker context + */ +export declare function isIndexedDBAvailable(): boolean; +/** + * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject + * if errors occur during the database open operation. + * + * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox + * private browsing) + */ +export declare function validateIndexedDBOpenable(): Promise; +/** + * + * This method checks whether cookie is enabled within current browser + * @return true if cookie is enabled within current browser + */ +export declare function areCookiesEnabled(): boolean; diff --git a/node_modules/@firebase/util/dist/src/errors.d.ts b/node_modules/@firebase/util/dist/src/errors.d.ts new file mode 100644 index 0000000..fa9afa0 --- /dev/null +++ b/node_modules/@firebase/util/dist/src/errors.d.ts @@ -0,0 +1,87 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview Standardized Firebase Error. + * + * Usage: + * + * // TypeScript string literals for type-safe codes + * type Err = + * 'unknown' | + * 'object-not-found' + * ; + * + * // Closure enum for type-safe error codes + * // at-enum {string} + * var Err = { + * UNKNOWN: 'unknown', + * OBJECT_NOT_FOUND: 'object-not-found', + * } + * + * let errors: Map = { + * 'generic-error': "Unknown error", + * 'file-not-found': "Could not find file: {$file}", + * }; + * + * // Type-safe function - must pass a valid error code as param. + * let error = new ErrorFactory('service', 'Service', errors); + * + * ... + * throw error.create(Err.GENERIC); + * ... + * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName}); + * ... + * // Service: Could not file file: foo.txt (service/file-not-found). + * + * catch (e) { + * assert(e.message === "Could not find file: foo.txt."); + * if ((e as FirebaseError)?.code === 'service/file-not-found') { + * console.log("Could not read file: " + e['file']); + * } + * } + */ +export type ErrorMap = { + readonly [K in ErrorCode]: string; +}; +export interface StringLike { + toString(): string; +} +export interface ErrorData { + [key: string]: unknown; +} +export declare class FirebaseError extends Error { + /** The error code for this error. */ + readonly code: string; + /** Custom data for this error. */ + customData?: Record | undefined; + /** The custom name for all FirebaseErrors. */ + readonly name: string; + constructor( + /** The error code for this error. */ + code: string, message: string, + /** Custom data for this error. */ + customData?: Record | undefined); +} +export declare class ErrorFactory { + private readonly service; + private readonly serviceName; + private readonly errors; + constructor(service: string, serviceName: string, errors: ErrorMap); + create(code: K, ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []): FirebaseError; +} diff --git a/node_modules/@firebase/util/dist/src/exponential_backoff.d.ts b/node_modules/@firebase/util/dist/src/exponential_backoff.d.ts new file mode 100644 index 0000000..f475721 --- /dev/null +++ b/node_modules/@firebase/util/dist/src/exponential_backoff.d.ts @@ -0,0 +1,37 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The maximum milliseconds to increase to. + * + *

Visible for testing + */ +export declare const MAX_VALUE_MILLIS: number; +/** + * The percentage of backoff time to randomize by. + * See + * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic + * for context. + * + *

Visible for testing + */ +export declare const RANDOM_FACTOR = 0.5; +/** + * Based on the backoff method from + * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js. + * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around. + */ +export declare function calculateBackoffMillis(backoffCount: number, intervalMillis?: number, backoffFactor?: number): number; diff --git a/node_modules/@firebase/util/dist/src/formatters.d.ts b/node_modules/@firebase/util/dist/src/formatters.d.ts new file mode 100644 index 0000000..f9d372e --- /dev/null +++ b/node_modules/@firebase/util/dist/src/formatters.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provide English ordinal letters after a number + */ +export declare function ordinal(i: number): string; diff --git a/node_modules/@firebase/util/dist/src/global.d.ts b/node_modules/@firebase/util/dist/src/global.d.ts new file mode 100644 index 0000000..7e5e687 --- /dev/null +++ b/node_modules/@firebase/util/dist/src/global.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Polyfill for `globalThis` object. + * @returns the `globalThis` object for the given environment. + * @public + */ +export declare function getGlobal(): typeof globalThis; diff --git a/node_modules/@firebase/util/dist/src/json.d.ts b/node_modules/@firebase/util/dist/src/json.d.ts new file mode 100644 index 0000000..b1de286 --- /dev/null +++ b/node_modules/@firebase/util/dist/src/json.d.ts @@ -0,0 +1,29 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Evaluates a JSON string into a javascript object. + * + * @param {string} str A string containing JSON. + * @return {*} The javascript object representing the specified JSON. + */ +export declare function jsonEval(str: string): unknown; +/** + * Returns JSON representing a javascript object. + * @param {*} data JavaScript object to be stringified. + * @return {string} The JSON contents of the object. + */ +export declare function stringify(data: unknown): string; diff --git a/node_modules/@firebase/util/dist/src/jwt.d.ts b/node_modules/@firebase/util/dist/src/jwt.d.ts new file mode 100644 index 0000000..4a1d809 --- /dev/null +++ b/node_modules/@firebase/util/dist/src/jwt.d.ts @@ -0,0 +1,73 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +interface Claims { + [key: string]: {}; +} +interface DecodedToken { + header: object; + claims: Claims; + data: object; + signature: string; +} +/** + * Decodes a Firebase auth. token into constituent parts. + * + * Notes: + * - May return with invalid / incomplete claims if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +export declare const decode: (token: string) => DecodedToken; +interface DecodedToken { + header: object; + claims: Claims; + data: object; + signature: string; +} +/** + * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the + * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +export declare const isValidTimestamp: (token: string) => boolean; +/** + * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise. + * + * Notes: + * - May return null if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +export declare const issuedAtTime: (token: string) => number | null; +/** + * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +export declare const isValidFormat: (token: string) => boolean; +/** + * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +export declare const isAdmin: (token: string) => boolean; +export {}; diff --git a/node_modules/@firebase/util/dist/src/obj.d.ts b/node_modules/@firebase/util/dist/src/obj.d.ts new file mode 100644 index 0000000..e29bb4c --- /dev/null +++ b/node_modules/@firebase/util/dist/src/obj.d.ts @@ -0,0 +1,30 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare function contains(obj: T, key: string): boolean; +export declare function safeGet(obj: T, key: K): T[K] | undefined; +export declare function isEmpty(obj: object): obj is {}; +export declare function map(obj: { + [key in K]: V; +}, fn: (value: V, key: K, obj: { + [key in K]: V; +}) => U, contextObj?: unknown): { + [key in K]: U; +}; +/** + * Deep equal two objects. Support Arrays and Objects. + */ +export declare function deepEqual(a: object, b: object): boolean; diff --git a/node_modules/@firebase/util/dist/src/postinstall.d.ts b/node_modules/@firebase/util/dist/src/postinstall.d.ts new file mode 100644 index 0000000..c623b76 --- /dev/null +++ b/node_modules/@firebase/util/dist/src/postinstall.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import type { FirebaseDefaults } from './defaults'; +export declare const getDefaultsFromPostinstall: () => FirebaseDefaults | undefined; diff --git a/node_modules/@firebase/util/dist/src/promise.d.ts b/node_modules/@firebase/util/dist/src/promise.d.ts new file mode 100644 index 0000000..3738ab7 --- /dev/null +++ b/node_modules/@firebase/util/dist/src/promise.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Rejects if the given promise doesn't resolve in timeInMS milliseconds. + * @internal + */ +export declare function promiseWithTimeout(promise: Promise, timeInMS?: number): Promise; diff --git a/node_modules/@firebase/util/dist/src/query.d.ts b/node_modules/@firebase/util/dist/src/query.d.ts new file mode 100644 index 0000000..1c67596 --- /dev/null +++ b/node_modules/@firebase/util/dist/src/query.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a + * params object (e.g. {arg: 'val', arg2: 'val2'}) + * Note: You must prepend it with ? when adding it to a URL. + */ +export declare function querystring(querystringParams: { + [key: string]: string | number; +}): string; +/** + * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object + * (e.g. {arg: 'val', arg2: 'val2'}) + */ +export declare function querystringDecode(querystring: string): Record; +/** + * Extract the query string part of a URL, including the leading question mark (if present). + */ +export declare function extractQuerystring(url: string): string; diff --git a/node_modules/@firebase/util/dist/src/sha1.d.ts b/node_modules/@firebase/util/dist/src/sha1.d.ts new file mode 100644 index 0000000..2320491 --- /dev/null +++ b/node_modules/@firebase/util/dist/src/sha1.d.ts @@ -0,0 +1,84 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview SHA-1 cryptographic hash. + * Variable names follow the notation in FIPS PUB 180-3: + * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf. + * + * Usage: + * var sha1 = new sha1(); + * sha1.update(bytes); + * var hash = sha1.digest(); + * + * Performance: + * Chrome 23: ~400 Mbit/s + * Firefox 16: ~250 Mbit/s + * + */ +/** + * SHA-1 cryptographic hash constructor. + * + * The properties declared here are discussed in the above algorithm document. + * @constructor + * @final + * @struct + */ +export declare class Sha1 { + /** + * Holds the previous values of accumulated variables a-e in the compress_ + * function. + * @private + */ + private chain_; + /** + * A buffer holding the partially computed hash result. + * @private + */ + private buf_; + /** + * An array of 80 bytes, each a part of the message to be hashed. Referred to + * as the message schedule in the docs. + * @private + */ + private W_; + /** + * Contains data needed to pad messages less than 64 bytes. + * @private + */ + private pad_; + /** + * @private {number} + */ + private inbuf_; + /** + * @private {number} + */ + private total_; + blockSize: number; + constructor(); + reset(): void; + /** + * Internal compress helper function. + * @param buf Block to compress. + * @param offset Offset of the block in the buffer. + * @private + */ + compress_(buf: number[] | Uint8Array | string, offset?: number): void; + update(bytes?: number[] | Uint8Array | string, length?: number): void; + /** @override */ + digest(): number[]; +} diff --git a/node_modules/@firebase/util/dist/src/subscribe.d.ts b/node_modules/@firebase/util/dist/src/subscribe.d.ts new file mode 100644 index 0000000..f01d5e5 --- /dev/null +++ b/node_modules/@firebase/util/dist/src/subscribe.d.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export type NextFn = (value: T) => void; +export type ErrorFn = (error: Error) => void; +export type CompleteFn = () => void; +export interface Observer { + next: NextFn; + error: ErrorFn; + complete: CompleteFn; +} +export type PartialObserver = Partial>; +export type Unsubscribe = () => void; +/** + * The Subscribe interface has two forms - passing the inline function + * callbacks, or a object interface with callback properties. + */ +export interface Subscribe { + (next?: NextFn, error?: ErrorFn, complete?: CompleteFn): Unsubscribe; + (observer: PartialObserver): Unsubscribe; +} +export interface Observable { + subscribe: Subscribe; +} +export type Executor = (observer: Observer) => void; +/** + * Helper to make a Subscribe function (just like Promise helps make a + * Thenable). + * + * @param executor Function which can make calls to a single Observer + * as a proxy. + * @param onNoObservers Callback when count of Observers goes to zero. + */ +export declare function createSubscribe(executor: Executor, onNoObservers?: Executor): Subscribe; +/** Turn synchronous function into one called asynchronously. */ +export declare function async(fn: Function, onError?: ErrorFn): Function; diff --git a/node_modules/@firebase/util/dist/src/url.d.ts b/node_modules/@firebase/util/dist/src/url.d.ts new file mode 100644 index 0000000..c999848 --- /dev/null +++ b/node_modules/@firebase/util/dist/src/url.d.ts @@ -0,0 +1,27 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Checks whether host is a cloud workstation or not. + * @public + */ +export declare function isCloudWorkstation(url: string): boolean; +/** + * Makes a fetch request to the given server. + * Mostly used for forwarding cookies in Firebase Studio. + * @public + */ +export declare function pingServer(endpoint: string): Promise; diff --git a/node_modules/@firebase/util/dist/src/utf8.d.ts b/node_modules/@firebase/util/dist/src/utf8.d.ts new file mode 100644 index 0000000..1883306 --- /dev/null +++ b/node_modules/@firebase/util/dist/src/utf8.d.ts @@ -0,0 +1,27 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @param {string} str + * @return {Array} + */ +export declare const stringToByteArray: (str: string) => number[]; +/** + * Calculate length without actually converting; useful for doing cheaper validation. + * @param {string} str + * @return {number} + */ +export declare const stringLength: (str: string) => number; diff --git a/node_modules/@firebase/util/dist/src/validation.d.ts b/node_modules/@firebase/util/dist/src/validation.d.ts new file mode 100644 index 0000000..f8c00b9 --- /dev/null +++ b/node_modules/@firebase/util/dist/src/validation.d.ts @@ -0,0 +1,43 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Check to make sure the appropriate number of arguments are provided for a public function. + * Throws an error if it fails. + * + * @param fnName The function name + * @param minCount The minimum number of arguments to allow for the function call + * @param maxCount The maximum number of argument to allow for the function call + * @param argCount The actual number of arguments provided. + */ +export declare const validateArgCount: (fnName: string, minCount: number, maxCount: number, argCount: number) => void; +/** + * Generates a string to prefix an error message about failed argument validation + * + * @param fnName The function name + * @param argName The name of the argument + * @return The prefix to add to the error thrown for validation. + */ +export declare function errorPrefix(fnName: string, argName: string): string; +/** + * @param fnName + * @param argumentNumber + * @param namespace + * @param optional + */ +export declare function validateNamespace(fnName: string, namespace: string, optional: boolean): void; +export declare function validateCallback(fnName: string, argumentName: string, callback: Function, optional: boolean): void; +export declare function validateContextObject(fnName: string, argumentName: string, context: unknown, optional: boolean): void; diff --git a/node_modules/@firebase/util/dist/test/base64.test.d.ts b/node_modules/@firebase/util/dist/test/base64.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/@firebase/util/dist/test/base64.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/@firebase/util/dist/test/compat.test.d.ts b/node_modules/@firebase/util/dist/test/compat.test.d.ts new file mode 100644 index 0000000..daa6d5d --- /dev/null +++ b/node_modules/@firebase/util/dist/test/compat.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/util/dist/test/deepCopy.test.d.ts b/node_modules/@firebase/util/dist/test/deepCopy.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/@firebase/util/dist/test/deepCopy.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/@firebase/util/dist/test/defaults.test.d.ts b/node_modules/@firebase/util/dist/test/defaults.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/@firebase/util/dist/test/defaults.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/@firebase/util/dist/test/emulator.test.d.ts b/node_modules/@firebase/util/dist/test/emulator.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/@firebase/util/dist/test/emulator.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/@firebase/util/dist/test/environments.test.d.ts b/node_modules/@firebase/util/dist/test/environments.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/node_modules/@firebase/util/dist/test/environments.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/util/dist/test/errors.test.d.ts b/node_modules/@firebase/util/dist/test/errors.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/@firebase/util/dist/test/errors.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/@firebase/util/dist/test/exponential_backoff.test.d.ts b/node_modules/@firebase/util/dist/test/exponential_backoff.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/node_modules/@firebase/util/dist/test/exponential_backoff.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/util/dist/test/object.test.d.ts b/node_modules/@firebase/util/dist/test/object.test.d.ts new file mode 100644 index 0000000..daa6d5d --- /dev/null +++ b/node_modules/@firebase/util/dist/test/object.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/util/dist/test/subscribe.test.d.ts b/node_modules/@firebase/util/dist/test/subscribe.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/node_modules/@firebase/util/dist/test/subscribe.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/@firebase/util/dist/tsdoc-metadata.json b/node_modules/@firebase/util/dist/tsdoc-metadata.json new file mode 100644 index 0000000..6af1f6a --- /dev/null +++ b/node_modules/@firebase/util/dist/tsdoc-metadata.json @@ -0,0 +1,11 @@ +// This file is read by tools that parse documentation comments conforming to the TSDoc standard. +// It should be published with your NPM package. It should not be tracked by Git. +{ + "tsdocVersion": "0.12", + "toolPackages": [ + { + "packageName": "@microsoft/api-extractor", + "packageVersion": "0.1.2" + } + ] +} diff --git a/node_modules/@firebase/util/dist/util-public.d.ts b/node_modules/@firebase/util/dist/util-public.d.ts new file mode 100644 index 0000000..0ea2b87 --- /dev/null +++ b/node_modules/@firebase/util/dist/util-public.d.ts @@ -0,0 +1,1002 @@ + +/** + * + * This method checks whether cookie is enabled within current browser + * @return true if cookie is enabled within current browser + */ +export declare function areCookiesEnabled(): boolean; + +/** + * Throws an error if the provided assertion is falsy + */ +export declare const assert: (assertion: unknown, message: string) => void; + +/** + * Returns an Error object suitable for throwing. + */ +export declare const assertionError: (message: string) => Error; + +/** Turn synchronous function into one called asynchronously. */ +export declare function async(fn: Function, onError?: ErrorFn): Function; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare interface Base64 { + byteToCharMap_: { + [key: number]: string; + } | null; + charToByteMap_: { + [key: string]: number; + } | null; + byteToCharMapWebSafe_: { + [key: number]: string; + } | null; + charToByteMapWebSafe_: { + [key: string]: number; + } | null; + ENCODED_VALS_BASE: string; + readonly ENCODED_VALS: string; + readonly ENCODED_VALS_WEBSAFE: string; + HAS_NATIVE_SUPPORT: boolean; + encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string; + encodeString(input: string, webSafe?: boolean): string; + decodeString(input: string, webSafe: boolean): string; + decodeStringToByteArray(input: string, webSafe: boolean): number[]; + init_(): void; +} + +export declare const base64: Base64; + +/** + * URL-safe base64 decoding + * + * NOTE: DO NOT use the global atob() function - it does NOT support the + * base64Url variant encoding. + * + * @param str To be decoded + * @return Decoded result, if possible + */ +export declare const base64Decode: (str: string) => string | null; + +/** + * URL-safe base64 encoding + */ +export declare const base64Encode: (str: string) => string; + +/** + * URL-safe base64 encoding (without "." padding in the end). + * e.g. Used in JSON Web Token (JWT) parts. + */ +export declare const base64urlEncodeWithoutPadding: (str: string) => string; + +/** + * Based on the backoff method from + * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js. + * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around. + */ +export declare function calculateBackoffMillis(backoffCount: number, intervalMillis?: number, backoffFactor?: number): number; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare interface Claims { + [key: string]: {}; +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare interface Compat { + _delegate: T; +} + +export declare type CompleteFn = () => void; + +/** + * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time. + */ +export declare const CONSTANTS: { + /** + * @define {boolean} Whether this is the client Node.js SDK. + */ + NODE_CLIENT: boolean; + /** + * @define {boolean} Whether this is the Admin Node.js SDK. + */ + NODE_ADMIN: boolean; + /** + * Firebase SDK Version + */ + SDK_VERSION: string; +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare function contains(obj: T, key: string): boolean; + +export declare function createMockUserToken(token: EmulatorMockTokenOptions, projectId?: string): string; + +/** + * Helper to make a Subscribe function (just like Promise helps make a + * Thenable). + * + * @param executor Function which can make calls to a single Observer + * as a proxy. + * @param onNoObservers Callback when count of Observers goes to zero. + */ +export declare function createSubscribe(executor: Executor, onNoObservers?: Executor): Subscribe; + +/** + * Decodes a Firebase auth. token into constituent parts. + * + * Notes: + * - May return with invalid / incomplete claims if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +export declare const decode: (token: string) => DecodedToken; + +/** + * An error encountered while decoding base64 string. + */ +export declare class DecodeBase64StringError extends Error { + readonly name = "DecodeBase64StringError"; +} + +declare interface DecodedToken { + header: object; + claims: Claims; + data: object; + signature: string; +} + +declare interface DecodedToken { + header: object; + claims: Claims; + data: object; + signature: string; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Do a deep-copy of basic JavaScript Objects or Arrays. + */ +export declare function deepCopy(value: T): T; + +/** + * Deep equal two objects. Support Arrays and Objects. + */ +export declare function deepEqual(a: object, b: object): boolean; + +/** + * Copy properties from source to target (recursively allows extension + * of Objects and Arrays). Scalar values in the target are over-written. + * If target is undefined, an object of the appropriate type will be created + * (and returned). + * + * We recursively copy all child properties of plain Objects in the source- so + * that namespace- like dictionaries are merged. + * + * Note that the target can be a function, in which case the properties in + * the source Object are copied onto it as static properties of the Function. + * + * Note: we don't merge __proto__ to prevent prototype pollution + */ +export declare function deepExtend(target: unknown, source: unknown): unknown; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare class Deferred { + promise: Promise; + reject: (value?: unknown) => void; + resolve: (value?: unknown) => void; + constructor(); + /** + * Our API internals are not promisified and cannot because our callback APIs have subtle expectations around + * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback + * and returns a node-style callback which will resolve or reject the Deferred's promise. + */ + wrapCallback(callback?: (error?: unknown, value?: unknown) => void): (error: unknown, value?: unknown) => void; +} + +export declare type EmulatorMockTokenOptions = ({ + user_id: string; +} | { + sub: string; +}) & Partial; + +export declare interface ErrorData { + [key: string]: unknown; +} + +export declare class ErrorFactory { + private readonly service; + private readonly serviceName; + private readonly errors; + constructor(service: string, serviceName: string, errors: ErrorMap); + create(code: K, ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []): FirebaseError; +} + +export declare type ErrorFn = (error: Error) => void; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview Standardized Firebase Error. + * + * Usage: + * + * // TypeScript string literals for type-safe codes + * type Err = + * 'unknown' | + * 'object-not-found' + * ; + * + * // Closure enum for type-safe error codes + * // at-enum {string} + * var Err = { + * UNKNOWN: 'unknown', + * OBJECT_NOT_FOUND: 'object-not-found', + * } + * + * let errors: Map = { + * 'generic-error': "Unknown error", + * 'file-not-found': "Could not find file: {$file}", + * }; + * + * // Type-safe function - must pass a valid error code as param. + * let error = new ErrorFactory('service', 'Service', errors); + * + * ... + * throw error.create(Err.GENERIC); + * ... + * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName}); + * ... + * // Service: Could not file file: foo.txt (service/file-not-found). + * + * catch (e) { + * assert(e.message === "Could not find file: foo.txt."); + * if ((e as FirebaseError)?.code === 'service/file-not-found') { + * console.log("Could not read file: " + e['file']); + * } + * } + */ +export declare type ErrorMap = { + readonly [K in ErrorCode]: string; +}; + +/** + * Generates a string to prefix an error message about failed argument validation + * + * @param fnName The function name + * @param argName The name of the argument + * @return The prefix to add to the error thrown for validation. + */ +export declare function errorPrefix(fnName: string, argName: string): string; + +export declare type Executor = (observer: Observer) => void; + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Keys for experimental properties on the `FirebaseDefaults` object. + * @public + */ +export declare type ExperimentalKey = 'authTokenSyncURL' | 'authIdTokenMaxAge'; + +/** + * Extract the query string part of a URL, including the leading question mark (if present). + */ +export declare function extractQuerystring(url: string): string; + +/** + * An object that can be injected into the environment as __FIREBASE_DEFAULTS__, + * either as a property of globalThis, a shell environment variable, or a + * cookie. + * + * This object can be used to automatically configure and initialize + * a Firebase app as well as any emulators. + * + * @public + */ +export declare interface FirebaseDefaults { + config?: Record; + emulatorHosts?: Record; + _authTokenSyncURL?: string; + _authIdTokenMaxAge?: number; + /** + * Override Firebase's runtime environment detection and + * force the SDK to act as if it were in the specified environment. + */ + forceEnvironment?: 'browser' | 'node'; + [key: string]: unknown; +} + +export declare class FirebaseError extends Error { + /** The error code for this error. */ + readonly code: string; + /** Custom data for this error. */ + customData?: Record | undefined; + /** The custom name for all FirebaseErrors. */ + readonly name: string; + constructor( + /** The error code for this error. */ + code: string, message: string, + /** Custom data for this error. */ + customData?: Record | undefined); +} + +declare interface FirebaseIdToken { + iss: string; + aud: string; + sub: string; + iat: number; + exp: number; + user_id: string; + auth_time: number; + provider_id?: 'anonymous'; + email?: string; + email_verified?: boolean; + phone_number?: string; + name?: string; + picture?: string; + firebase: { + sign_in_provider: FirebaseSignInProvider; + identities?: { + [provider in FirebaseSignInProvider]?: string[]; + }; + }; + [claim: string]: unknown; + uid?: never; +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare type FirebaseSignInProvider = 'custom' | 'email' | 'password' | 'phone' | 'anonymous' | 'google.com' | 'facebook.com' | 'github.com' | 'twitter.com' | 'microsoft.com' | 'apple.com'; + +/** + * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object. + * @public + */ +export declare const getDefaultAppConfig: () => Record | undefined; + +/** + * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object + * for the given product. + * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available + * @public + */ +export declare const getDefaultEmulatorHost: (productName: string) => string | undefined; + +/** + * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object + * for the given product. + * @returns a pair of hostname and port like `["::1", 4000]` if available + * @public + */ +export declare const getDefaultEmulatorHostnameAndPort: (productName: string) => [hostname: string, port: number] | undefined; + +/** + * Get the __FIREBASE_DEFAULTS__ object. It checks in order: + * (1) if such an object exists as a property of `globalThis` + * (2) if such an object was provided on a shell environment variable + * (3) if such an object exists in a cookie + * @public + */ +export declare const getDefaults: () => FirebaseDefaults | undefined; + +/** + * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties + * prefixed by "_") + * @public + */ +export declare const getExperimentalSetting: (name: T) => FirebaseDefaults[`_${T}`]; + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Polyfill for `globalThis` object. + * @returns the `globalThis` object for the given environment. + * @public + */ +export declare function getGlobal(): typeof globalThis; + +export declare function getModularInstance(service: Compat | ExpService): ExpService; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns navigator.userAgent string or '' if it's not defined. + * @return user agent string + */ +export declare function getUA(): string; + +/** + * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +export declare const isAdmin: (token: string) => boolean; + +/** + * Detect Browser Environment. + * Note: This will return true for certain test frameworks that are incompletely + * mimicking a browser, and should not lead to assuming all browser APIs are + * available. + */ +export declare function isBrowser(): boolean; + +export declare function isBrowserExtension(): boolean; + +/** + * Detect Cloudflare Worker context. + */ +export declare function isCloudflareWorker(): boolean; + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Checks whether host is a cloud workstation or not. + * @public + */ +export declare function isCloudWorkstation(url: string): boolean; + +/** Detects Electron apps. */ +export declare function isElectron(): boolean; + +export declare function isEmpty(obj: object): obj is {}; + +/** Detects Internet Explorer. */ +export declare function isIE(): boolean; + +/** + * This method checks if indexedDB is supported by current browser/service worker context + * @return true if indexedDB is supported by current browser/service worker context + */ +export declare function isIndexedDBAvailable(): boolean; + +/** + * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device. + * + * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap + * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally + * wait for a callback. + */ +export declare function isMobileCordova(): boolean; + +/** + * Detect Node.js. + * + * @return true if Node.js environment is detected or specified. + */ +export declare function isNode(): boolean; + +/** + * Detect whether the current SDK build is the Node version. + * + * @return true if it's the Node SDK build. + */ +export declare function isNodeSdk(): boolean; + +/** + * Detect React Native. + * + * @return true if ReactNative environment is detected. + */ +export declare function isReactNative(): boolean; + +/** Returns true if we are running in Safari. */ +export declare function isSafari(): boolean; + +/** Returns true if we are running in Safari or WebKit */ +export declare function isSafariOrWebkit(): boolean; + +/** + * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise. + * + * Notes: + * - May return null if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +export declare const issuedAtTime: (token: string) => number | null; + +/** Detects Universal Windows Platform apps. */ +export declare function isUWP(): boolean; + +/** + * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +export declare const isValidFormat: (token: string) => boolean; + +/** + * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the + * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +export declare const isValidTimestamp: (token: string) => boolean; + +/** + * Detect Web Worker context. + */ +export declare function isWebWorker(): boolean; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Evaluates a JSON string into a javascript object. + * + * @param {string} str A string containing JSON. + * @return {*} The javascript object representing the specified JSON. + */ +export declare function jsonEval(str: string): unknown; + +export declare function map(obj: { + [key in K]: V; +}, fn: (value: V, key: K, obj: { + [key in K]: V; +}) => U, contextObj?: unknown): { + [key in K]: U; +}; + +/** + * The maximum milliseconds to increase to. + * + *

Visible for testing + */ +export declare const MAX_VALUE_MILLIS: number; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare type NextFn = (value: T) => void; + +export declare interface Observable { + subscribe: Subscribe; +} + +export declare interface Observer { + next: NextFn; + error: ErrorFn; + complete: CompleteFn; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provide English ordinal letters after a number + */ +export declare function ordinal(i: number): string; + +export declare type PartialObserver = Partial>; + +/** + * Makes a fetch request to the given server. + * Mostly used for forwarding cookies in Firebase Studio. + * @public + */ +export declare function pingServer(endpoint: string): Promise; + +/* Excluded from this release type: promiseWithTimeout */ + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a + * params object (e.g. {arg: 'val', arg2: 'val2'}) + * Note: You must prepend it with ? when adding it to a URL. + */ +export declare function querystring(querystringParams: { + [key: string]: string | number; +}): string; + +/** + * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object + * (e.g. {arg: 'val', arg2: 'val2'}) + */ +export declare function querystringDecode(querystring: string): Record; + +/** + * The percentage of backoff time to randomize by. + * See + * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic + * for context. + * + *

Visible for testing + */ +export declare const RANDOM_FACTOR = 0.5; + +export declare function safeGet(obj: T, key: K): T[K] | undefined; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview SHA-1 cryptographic hash. + * Variable names follow the notation in FIPS PUB 180-3: + * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf. + * + * Usage: + * var sha1 = new sha1(); + * sha1.update(bytes); + * var hash = sha1.digest(); + * + * Performance: + * Chrome 23: ~400 Mbit/s + * Firefox 16: ~250 Mbit/s + * + */ +/** + * SHA-1 cryptographic hash constructor. + * + * The properties declared here are discussed in the above algorithm document. + * @constructor + * @final + * @struct + */ +export declare class Sha1 { + /** + * Holds the previous values of accumulated variables a-e in the compress_ + * function. + * @private + */ + private chain_; + /** + * A buffer holding the partially computed hash result. + * @private + */ + private buf_; + /** + * An array of 80 bytes, each a part of the message to be hashed. Referred to + * as the message schedule in the docs. + * @private + */ + private W_; + /** + * Contains data needed to pad messages less than 64 bytes. + * @private + */ + private pad_; + /** + * @private {number} + */ + private inbuf_; + /** + * @private {number} + */ + private total_; + blockSize: number; + constructor(); + reset(): void; + /** + * Internal compress helper function. + * @param buf Block to compress. + * @param offset Offset of the block in the buffer. + * @private + */ + compress_(buf: number[] | Uint8Array | string, offset?: number): void; + update(bytes?: number[] | Uint8Array | string, length?: number): void; + /** @override */ + digest(): number[]; +} + +/** + * Returns JSON representing a javascript object. + * @param {*} data JavaScript object to be stringified. + * @return {string} The JSON contents of the object. + */ +export declare function stringify(data: unknown): string; + +/** + * Calculate length without actually converting; useful for doing cheaper validation. + * @param {string} str + * @return {number} + */ +export declare const stringLength: (str: string) => number; + +export declare interface StringLike { + toString(): string; +} + +/** + * @param {string} str + * @return {Array} + */ +export declare const stringToByteArray: (str: string) => number[]; + +/** + * The Subscribe interface has two forms - passing the inline function + * callbacks, or a object interface with callback properties. + */ +export declare interface Subscribe { + (next?: NextFn, error?: ErrorFn, complete?: CompleteFn): Unsubscribe; + (observer: PartialObserver): Unsubscribe; +} + +export declare type Unsubscribe = () => void; + +/** + * Updates Emulator Banner. Primarily used for Firebase Studio + * @param name + * @param isRunningEmulator + * @public + */ +export declare function updateEmulatorBanner(name: string, isRunningEmulator: boolean): void; + +/** + * Check to make sure the appropriate number of arguments are provided for a public function. + * Throws an error if it fails. + * + * @param fnName The function name + * @param minCount The minimum number of arguments to allow for the function call + * @param maxCount The maximum number of argument to allow for the function call + * @param argCount The actual number of arguments provided. + */ +export declare const validateArgCount: (fnName: string, minCount: number, maxCount: number, argCount: number) => void; + +export declare function validateCallback(fnName: string, argumentName: string, callback: Function, optional: boolean): void; + +export declare function validateContextObject(fnName: string, argumentName: string, context: unknown, optional: boolean): void; + +/** + * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject + * if errors occur during the database open operation. + * + * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox + * private browsing) + */ +export declare function validateIndexedDBOpenable(): Promise; + +/** + * @param fnName + * @param argumentNumber + * @param namespace + * @param optional + */ +export declare function validateNamespace(fnName: string, namespace: string, optional: boolean): void; + +export { } diff --git a/node_modules/@firebase/util/dist/util.d.ts b/node_modules/@firebase/util/dist/util.d.ts new file mode 100644 index 0000000..fe6af73 --- /dev/null +++ b/node_modules/@firebase/util/dist/util.d.ts @@ -0,0 +1,1022 @@ + +/** + * + * This method checks whether cookie is enabled within current browser + * @return true if cookie is enabled within current browser + */ +export declare function areCookiesEnabled(): boolean; + +/** + * Throws an error if the provided assertion is falsy + */ +export declare const assert: (assertion: unknown, message: string) => void; + +/** + * Returns an Error object suitable for throwing. + */ +export declare const assertionError: (message: string) => Error; + +/** Turn synchronous function into one called asynchronously. */ +export declare function async(fn: Function, onError?: ErrorFn): Function; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare interface Base64 { + byteToCharMap_: { + [key: number]: string; + } | null; + charToByteMap_: { + [key: string]: number; + } | null; + byteToCharMapWebSafe_: { + [key: number]: string; + } | null; + charToByteMapWebSafe_: { + [key: string]: number; + } | null; + ENCODED_VALS_BASE: string; + readonly ENCODED_VALS: string; + readonly ENCODED_VALS_WEBSAFE: string; + HAS_NATIVE_SUPPORT: boolean; + encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string; + encodeString(input: string, webSafe?: boolean): string; + decodeString(input: string, webSafe: boolean): string; + decodeStringToByteArray(input: string, webSafe: boolean): number[]; + init_(): void; +} + +export declare const base64: Base64; + +/** + * URL-safe base64 decoding + * + * NOTE: DO NOT use the global atob() function - it does NOT support the + * base64Url variant encoding. + * + * @param str To be decoded + * @return Decoded result, if possible + */ +export declare const base64Decode: (str: string) => string | null; + +/** + * URL-safe base64 encoding + */ +export declare const base64Encode: (str: string) => string; + +/** + * URL-safe base64 encoding (without "." padding in the end). + * e.g. Used in JSON Web Token (JWT) parts. + */ +export declare const base64urlEncodeWithoutPadding: (str: string) => string; + +/** + * Based on the backoff method from + * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js. + * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around. + */ +export declare function calculateBackoffMillis(backoffCount: number, intervalMillis?: number, backoffFactor?: number): number; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare interface Claims { + [key: string]: {}; +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare interface Compat { + _delegate: T; +} + +export declare type CompleteFn = () => void; + +/** + * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time. + */ +export declare const CONSTANTS: { + /** + * @define {boolean} Whether this is the client Node.js SDK. + */ + NODE_CLIENT: boolean; + /** + * @define {boolean} Whether this is the Admin Node.js SDK. + */ + NODE_ADMIN: boolean; + /** + * Firebase SDK Version + */ + SDK_VERSION: string; +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare function contains(obj: T, key: string): boolean; + +export declare function createMockUserToken(token: EmulatorMockTokenOptions, projectId?: string): string; + +/** + * Helper to make a Subscribe function (just like Promise helps make a + * Thenable). + * + * @param executor Function which can make calls to a single Observer + * as a proxy. + * @param onNoObservers Callback when count of Observers goes to zero. + */ +export declare function createSubscribe(executor: Executor, onNoObservers?: Executor): Subscribe; + +/** + * Decodes a Firebase auth. token into constituent parts. + * + * Notes: + * - May return with invalid / incomplete claims if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +export declare const decode: (token: string) => DecodedToken; + +/** + * An error encountered while decoding base64 string. + */ +export declare class DecodeBase64StringError extends Error { + readonly name = "DecodeBase64StringError"; +} + +declare interface DecodedToken { + header: object; + claims: Claims; + data: object; + signature: string; +} + +declare interface DecodedToken { + header: object; + claims: Claims; + data: object; + signature: string; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Do a deep-copy of basic JavaScript Objects or Arrays. + */ +export declare function deepCopy(value: T): T; + +/** + * Deep equal two objects. Support Arrays and Objects. + */ +export declare function deepEqual(a: object, b: object): boolean; + +/** + * Copy properties from source to target (recursively allows extension + * of Objects and Arrays). Scalar values in the target are over-written. + * If target is undefined, an object of the appropriate type will be created + * (and returned). + * + * We recursively copy all child properties of plain Objects in the source- so + * that namespace- like dictionaries are merged. + * + * Note that the target can be a function, in which case the properties in + * the source Object are copied onto it as static properties of the Function. + * + * Note: we don't merge __proto__ to prevent prototype pollution + */ +export declare function deepExtend(target: unknown, source: unknown): unknown; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare class Deferred { + promise: Promise; + reject: (value?: unknown) => void; + resolve: (value?: unknown) => void; + constructor(); + /** + * Our API internals are not promisified and cannot because our callback APIs have subtle expectations around + * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback + * and returns a node-style callback which will resolve or reject the Deferred's promise. + */ + wrapCallback(callback?: (error?: unknown, value?: unknown) => void): (error: unknown, value?: unknown) => void; +} + +export declare type EmulatorMockTokenOptions = ({ + user_id: string; +} | { + sub: string; +}) & Partial; + +export declare interface ErrorData { + [key: string]: unknown; +} + +export declare class ErrorFactory { + private readonly service; + private readonly serviceName; + private readonly errors; + constructor(service: string, serviceName: string, errors: ErrorMap); + create(code: K, ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []): FirebaseError; +} + +export declare type ErrorFn = (error: Error) => void; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview Standardized Firebase Error. + * + * Usage: + * + * // TypeScript string literals for type-safe codes + * type Err = + * 'unknown' | + * 'object-not-found' + * ; + * + * // Closure enum for type-safe error codes + * // at-enum {string} + * var Err = { + * UNKNOWN: 'unknown', + * OBJECT_NOT_FOUND: 'object-not-found', + * } + * + * let errors: Map = { + * 'generic-error': "Unknown error", + * 'file-not-found': "Could not find file: {$file}", + * }; + * + * // Type-safe function - must pass a valid error code as param. + * let error = new ErrorFactory('service', 'Service', errors); + * + * ... + * throw error.create(Err.GENERIC); + * ... + * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName}); + * ... + * // Service: Could not file file: foo.txt (service/file-not-found). + * + * catch (e) { + * assert(e.message === "Could not find file: foo.txt."); + * if ((e as FirebaseError)?.code === 'service/file-not-found') { + * console.log("Could not read file: " + e['file']); + * } + * } + */ +export declare type ErrorMap = { + readonly [K in ErrorCode]: string; +}; + +/** + * Generates a string to prefix an error message about failed argument validation + * + * @param fnName The function name + * @param argName The name of the argument + * @return The prefix to add to the error thrown for validation. + */ +export declare function errorPrefix(fnName: string, argName: string): string; + +export declare type Executor = (observer: Observer) => void; + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Keys for experimental properties on the `FirebaseDefaults` object. + * @public + */ +export declare type ExperimentalKey = 'authTokenSyncURL' | 'authIdTokenMaxAge'; + +/** + * Extract the query string part of a URL, including the leading question mark (if present). + */ +export declare function extractQuerystring(url: string): string; + +/** + * An object that can be injected into the environment as __FIREBASE_DEFAULTS__, + * either as a property of globalThis, a shell environment variable, or a + * cookie. + * + * This object can be used to automatically configure and initialize + * a Firebase app as well as any emulators. + * + * @public + */ +export declare interface FirebaseDefaults { + config?: Record; + emulatorHosts?: Record; + _authTokenSyncURL?: string; + _authIdTokenMaxAge?: number; + /** + * Override Firebase's runtime environment detection and + * force the SDK to act as if it were in the specified environment. + */ + forceEnvironment?: 'browser' | 'node'; + [key: string]: unknown; +} + +export declare class FirebaseError extends Error { + /** The error code for this error. */ + readonly code: string; + /** Custom data for this error. */ + customData?: Record | undefined; + /** The custom name for all FirebaseErrors. */ + readonly name: string; + constructor( + /** The error code for this error. */ + code: string, message: string, + /** Custom data for this error. */ + customData?: Record | undefined); +} + +declare interface FirebaseIdToken { + iss: string; + aud: string; + sub: string; + iat: number; + exp: number; + user_id: string; + auth_time: number; + provider_id?: 'anonymous'; + email?: string; + email_verified?: boolean; + phone_number?: string; + name?: string; + picture?: string; + firebase: { + sign_in_provider: FirebaseSignInProvider; + identities?: { + [provider in FirebaseSignInProvider]?: string[]; + }; + }; + [claim: string]: unknown; + uid?: never; +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare type FirebaseSignInProvider = 'custom' | 'email' | 'password' | 'phone' | 'anonymous' | 'google.com' | 'facebook.com' | 'github.com' | 'twitter.com' | 'microsoft.com' | 'apple.com'; + +/** + * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object. + * @public + */ +export declare const getDefaultAppConfig: () => Record | undefined; + +/** + * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object + * for the given product. + * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available + * @public + */ +export declare const getDefaultEmulatorHost: (productName: string) => string | undefined; + +/** + * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object + * for the given product. + * @returns a pair of hostname and port like `["::1", 4000]` if available + * @public + */ +export declare const getDefaultEmulatorHostnameAndPort: (productName: string) => [hostname: string, port: number] | undefined; + +/** + * Get the __FIREBASE_DEFAULTS__ object. It checks in order: + * (1) if such an object exists as a property of `globalThis` + * (2) if such an object was provided on a shell environment variable + * (3) if such an object exists in a cookie + * @public + */ +export declare const getDefaults: () => FirebaseDefaults | undefined; + +/** + * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties + * prefixed by "_") + * @public + */ +export declare const getExperimentalSetting: (name: T) => FirebaseDefaults[`_${T}`]; + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Polyfill for `globalThis` object. + * @returns the `globalThis` object for the given environment. + * @public + */ +export declare function getGlobal(): typeof globalThis; + +export declare function getModularInstance(service: Compat | ExpService): ExpService; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns navigator.userAgent string or '' if it's not defined. + * @return user agent string + */ +export declare function getUA(): string; + +/** + * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +export declare const isAdmin: (token: string) => boolean; + +/** + * Detect Browser Environment. + * Note: This will return true for certain test frameworks that are incompletely + * mimicking a browser, and should not lead to assuming all browser APIs are + * available. + */ +export declare function isBrowser(): boolean; + +export declare function isBrowserExtension(): boolean; + +/** + * Detect Cloudflare Worker context. + */ +export declare function isCloudflareWorker(): boolean; + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Checks whether host is a cloud workstation or not. + * @public + */ +export declare function isCloudWorkstation(url: string): boolean; + +/** Detects Electron apps. */ +export declare function isElectron(): boolean; + +export declare function isEmpty(obj: object): obj is {}; + +/** Detects Internet Explorer. */ +export declare function isIE(): boolean; + +/** + * This method checks if indexedDB is supported by current browser/service worker context + * @return true if indexedDB is supported by current browser/service worker context + */ +export declare function isIndexedDBAvailable(): boolean; + +/** + * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device. + * + * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap + * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally + * wait for a callback. + */ +export declare function isMobileCordova(): boolean; + +/** + * Detect Node.js. + * + * @return true if Node.js environment is detected or specified. + */ +export declare function isNode(): boolean; + +/** + * Detect whether the current SDK build is the Node version. + * + * @return true if it's the Node SDK build. + */ +export declare function isNodeSdk(): boolean; + +/** + * Detect React Native. + * + * @return true if ReactNative environment is detected. + */ +export declare function isReactNative(): boolean; + +/** Returns true if we are running in Safari. */ +export declare function isSafari(): boolean; + +/** Returns true if we are running in Safari or WebKit */ +export declare function isSafariOrWebkit(): boolean; + +/** + * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise. + * + * Notes: + * - May return null if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +export declare const issuedAtTime: (token: string) => number | null; + +/** Detects Universal Windows Platform apps. */ +export declare function isUWP(): boolean; + +/** + * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +export declare const isValidFormat: (token: string) => boolean; + +/** + * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the + * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims. + * + * Notes: + * - May return a false negative if there's no native base64 decoding support. + * - Doesn't check if the token is actually valid. + */ +export declare const isValidTimestamp: (token: string) => boolean; + +/** + * Detect Web Worker context. + */ +export declare function isWebWorker(): boolean; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Evaluates a JSON string into a javascript object. + * + * @param {string} str A string containing JSON. + * @return {*} The javascript object representing the specified JSON. + */ +export declare function jsonEval(str: string): unknown; + +export declare function map(obj: { + [key in K]: V; +}, fn: (value: V, key: K, obj: { + [key in K]: V; +}) => U, contextObj?: unknown): { + [key in K]: U; +}; + +/** + * The maximum milliseconds to increase to. + * + *

Visible for testing + */ +export declare const MAX_VALUE_MILLIS: number; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare type NextFn = (value: T) => void; + +export declare interface Observable { + subscribe: Subscribe; +} + +export declare interface Observer { + next: NextFn; + error: ErrorFn; + complete: CompleteFn; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provide English ordinal letters after a number + */ +export declare function ordinal(i: number): string; + +export declare type PartialObserver = Partial>; + +/** + * Makes a fetch request to the given server. + * Mostly used for forwarding cookies in Firebase Studio. + * @public + */ +export declare function pingServer(endpoint: string): Promise; + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Rejects if the given promise doesn't resolve in timeInMS milliseconds. + * @internal + */ +export declare function promiseWithTimeout(promise: Promise, timeInMS?: number): Promise; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a + * params object (e.g. {arg: 'val', arg2: 'val2'}) + * Note: You must prepend it with ? when adding it to a URL. + */ +export declare function querystring(querystringParams: { + [key: string]: string | number; +}): string; + +/** + * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object + * (e.g. {arg: 'val', arg2: 'val2'}) + */ +export declare function querystringDecode(querystring: string): Record; + +/** + * The percentage of backoff time to randomize by. + * See + * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic + * for context. + * + *

For a DocumentSnapshot that points to a non-existing document, any data + * access will return 'undefined'. You can use the + * [exists]{@link DocumentSnapshot#exists} property to explicitly verify a + * document's existence. + * + * @class DocumentSnapshot + */ +export declare class DocumentSnapshot implements firestore.DocumentSnapshot { + /** + * @internal + * @private + **/ + readonly _fieldsProto?: ApiMapValue | undefined; + private _ref; + private _serializer; + private _readTime; + private _createTime; + private _updateTime; + /** + * @private + * @internal + * + * @param ref The reference to the document. + * @param _fieldsProto The fields of the Firestore `Document` Protobuf backing + * this document (or undefined if the document does not exist). + * @param readTime The time when this snapshot was read (or undefined if + * the document exists only locally). + * @param createTime The time when the document was created (or undefined if + * the document does not exist). + * @param updateTime The time when the document was last updated (or undefined + * if the document does not exist). + */ + constructor(ref: DocumentReference, + /** + * @internal + * @private + **/ + _fieldsProto?: ApiMapValue | undefined, readTime?: Timestamp, createTime?: Timestamp, updateTime?: Timestamp); + /** + * Creates a DocumentSnapshot from an object. + * + * @private + * @internal + * @param ref The reference to the document. + * @param obj The object to store in the DocumentSnapshot. + * @return The created DocumentSnapshot. + */ + static fromObject(ref: DocumentReference, obj: firestore.DocumentData): DocumentSnapshot; + /** + * Creates a DocumentSnapshot from an UpdateMap. + * + * This methods expands the top-level field paths in a JavaScript map and + * turns { foo.bar : foobar } into { foo { bar : foobar }} + * + * @private + * @internal + * @param ref The reference to the document. + * @param data The field/value map to expand. + * @return The created DocumentSnapshot. + */ + static fromUpdateMap(ref: firestore.DocumentReference, data: UpdateMap): DocumentSnapshot; + /** + * True if the document exists. + * + * @type {boolean} + * @name DocumentSnapshot#exists + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then((documentSnapshot) => { + * if (documentSnapshot.exists) { + * console.log(`Data: ${JSON.stringify(documentSnapshot.data())}`); + * } + * }); + * ``` + */ + get exists(): boolean; + /** + * A [DocumentReference]{@link DocumentReference} for the document + * stored in this snapshot. + * + * @type {DocumentReference} + * @name DocumentSnapshot#ref + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then((documentSnapshot) => { + * if (documentSnapshot.exists) { + * console.log(`Found document at '${documentSnapshot.ref.path}'`); + * } + * }); + * ``` + */ + get ref(): DocumentReference; + /** + * The ID of the document for which this DocumentSnapshot contains data. + * + * @type {string} + * @name DocumentSnapshot#id + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then((documentSnapshot) => { + * if (documentSnapshot.exists) { + * console.log(`Document found with name '${documentSnapshot.id}'`); + * } + * }); + * ``` + */ + get id(): string; + /** + * The time the document was created. Undefined for documents that don't + * exist. + * + * @type {Timestamp|undefined} + * @name DocumentSnapshot#createTime + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(documentSnapshot => { + * if (documentSnapshot.exists) { + * let createTime = documentSnapshot.createTime; + * console.log(`Document created at '${createTime.toDate()}'`); + * } + * }); + * ``` + */ + get createTime(): Timestamp | undefined; + /** + * The time the document was last updated (at the time the snapshot was + * generated). Undefined for documents that don't exist. + * + * @type {Timestamp|undefined} + * @name DocumentSnapshot#updateTime + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(documentSnapshot => { + * if (documentSnapshot.exists) { + * let updateTime = documentSnapshot.updateTime; + * console.log(`Document updated at '${updateTime.toDate()}'`); + * } + * }); + * ``` + */ + get updateTime(): Timestamp | undefined; + /** + * The time this snapshot was read. + * + * @type {Timestamp} + * @name DocumentSnapshot#readTime + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(documentSnapshot => { + * let readTime = documentSnapshot.readTime; + * console.log(`Document read at '${readTime.toDate()}'`); + * }); + * ``` + */ + get readTime(): Timestamp; + /** + * Retrieves all fields in the document as an object. Returns 'undefined' if + * the document doesn't exist. + * + * @returns {T|undefined} An object containing all fields in the document or + * 'undefined' if the document doesn't exist. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(documentSnapshot => { + * let data = documentSnapshot.data(); + * console.log(`Retrieved data: ${JSON.stringify(data)}`); + * }); + * ``` + */ + data(): AppModelType | undefined; + /** + * Retrieves the field specified by `field`. + * + * @param {string|FieldPath} field The field path + * (e.g. 'foo' or 'foo.bar') to a specific field. + * @returns {*} The data at the specified field location or undefined if no + * such field exists. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({ a: { b: 'c' }}).then(() => { + * return documentRef.get(); + * }).then(documentSnapshot => { + * let field = documentSnapshot.get('a.b'); + * console.log(`Retrieved field value: ${field}`); + * }); + * ``` + */ + get(field: string | FieldPath): any; + /** + * Retrieves the field specified by 'fieldPath' in its Protobuf JS + * representation. + * + * @private + * @internal + * @param field The path (e.g. 'foo' or 'foo.bar') to a specific field. + * @returns The Protobuf-encoded data at the specified field location or + * undefined if no such field exists. + */ + protoField(field: string | FieldPath): api.IValue | undefined; + /** + * Convert a document snapshot to the Firestore 'Write' proto. + * + * @private + * @internal + */ + toWriteProto(): api.IWrite; + /** + * Convert a document snapshot to the Firestore 'Document' proto. + * + * @private + * @internal + */ + toDocumentProto(): api.IDocument; + /** + * Returns true if the document's data and path in this `DocumentSnapshot` is + * equal to the provided value. + * + * @param {*} other The value to compare against. + * @return {boolean} true if this `DocumentSnapshot` is equal to the provided + * value. + */ + isEqual(other: firestore.DocumentSnapshot): boolean; +} +/** + * A QueryDocumentSnapshot contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with [data()]{@link QueryDocumentSnapshot#data} + * or [get()]{@link DocumentSnapshot#get} to get a specific field. + * + * A QueryDocumentSnapshot offers the same API surface as a + * {@link DocumentSnapshot}. Since query results contain only existing + * documents, the [exists]{@link DocumentSnapshot#exists} property will + * always be true and [data()]{@link QueryDocumentSnapshot#data} will never + * return 'undefined'. + * + * @class QueryDocumentSnapshot + * @extends DocumentSnapshot + */ +export declare class QueryDocumentSnapshot extends DocumentSnapshot implements firestore.QueryDocumentSnapshot { + /** + * The time the document was created. + * + * @type {Timestamp} + * @name QueryDocumentSnapshot#createTime + * @readonly + * @override + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.get().forEach(snapshot => { + * console.log(`Document created at '${snapshot.createTime.toDate()}'`); + * }); + * ``` + */ + get createTime(): Timestamp; + /** + * The time the document was last updated (at the time the snapshot was + * generated). + * + * @type {Timestamp} + * @name QueryDocumentSnapshot#updateTime + * @readonly + * @override + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.get().forEach(snapshot => { + * console.log(`Document updated at '${snapshot.updateTime.toDate()}'`); + * }); + * ``` + */ + get updateTime(): Timestamp; + /** + * Retrieves all fields in the document as an object. + * + * @override + * + * @returns {T} An object containing all fields in the document. + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.get().forEach(documentSnapshot => { + * let data = documentSnapshot.data(); + * console.log(`Retrieved data: ${JSON.stringify(data)}`); + * }); + * ``` + */ + data(): AppModelType; +} +/** + * A Firestore Document Mask contains the field paths affected by an update. + * + * @class + * @private + * @internal + */ +export declare class DocumentMask { + private _sortedPaths; + /** + * @private + * @internal + * @private + * + * @param fieldPaths The field paths in this mask. + */ + constructor(fieldPaths: FieldPath[]); + /** + * Creates a document mask with the field paths of a document. + * + * @private + * @internal + * @param data A map with fields to modify. Only the keys are used to extract + * the document mask. + */ + static fromUpdateMap(data: UpdateMap): DocumentMask; + /** + * Creates a document mask from an array of field paths. + * + * @private + * @internal + * @param fieldMask A list of field paths. + */ + static fromFieldMask(fieldMask: Array): DocumentMask; + /** + * Creates a document mask with the field names of a document. + * + * @private + * @internal + * @param data An object with fields to modify. Only the keys are used to + * extract the document mask. + */ + static fromObject(data: firestore.DocumentData): DocumentMask; + /** + * Returns true if this document mask contains no fields. + * + * @private + * @internal + * @return {boolean} Whether this document mask is empty. + */ + get isEmpty(): boolean; + /** + * Removes the specified values from a sorted field path array. + * + * @private + * @internal + * @param input A sorted array of FieldPaths. + * @param values An array of FieldPaths to remove. + */ + private static removeFromSortedArray; + /** + * Removes the field path specified in 'fieldPaths' from this document mask. + * + * @private + * @internal + * @param fieldPaths An array of FieldPaths. + */ + removeFields(fieldPaths: FieldPath[]): void; + /** + * Returns whether this document mask contains 'fieldPath'. + * + * @private + * @internal + * @param fieldPath The field path to test. + * @return Whether this document mask contains 'fieldPath'. + */ + contains(fieldPath: FieldPath): boolean; + /** + * Removes all properties from 'data' that are not contained in this document + * mask. + * + * @private + * @internal + * @param data An object to filter. + * @return A shallow copy of the object filtered by this document mask. + */ + applyTo(data: firestore.DocumentData): firestore.DocumentData; + /** + * Converts a document mask to the Firestore 'DocumentMask' Proto. + * + * @private + * @internal + * @returns A Firestore 'DocumentMask' Proto. + */ + toProto(): api.IDocumentMask; +} +/** + * A Firestore Document Transform. + * + * A DocumentTransform contains pending server-side transforms and their + * corresponding field paths. + * + * @private + * @internal + * @class + */ +export declare class DocumentTransform { + private readonly ref; + private readonly transforms; + /** + * @private + * @internal + * @private + * + * @param ref The DocumentReference for this transform. + * @param transforms A Map of FieldPaths to FieldTransforms. + */ + constructor(ref: DocumentReference, transforms: Map); + /** + * Generates a DocumentTransform from a JavaScript object. + * + * @private + * @internal + * @param ref The `DocumentReference` to use for the DocumentTransform. + * @param obj The object to extract the transformations from. + * @returns The Document Transform. + */ + static fromObject(ref: firestore.DocumentReference, obj: firestore.DocumentData): DocumentTransform; + /** + * Generates a DocumentTransform from an Update Map. + * + * @private + * @internal + * @param ref The `DocumentReference` to use for the DocumentTransform. + * @param data The update data to extract the transformations from. + * @returns The Document Transform. + */ + static fromUpdateMap(ref: firestore.DocumentReference, data: UpdateMap): DocumentTransform; + /** + * Whether this DocumentTransform contains any actionable transformations. + * + * @private + * @internal + */ + get isEmpty(): boolean; + /** + * Returns the array of fields in this DocumentTransform. + * + * @private + * @internal + */ + get fields(): FieldPath[]; + /** + * Validates the user provided field values in this document transform. + * @private + * @internal + */ + validate(): void; + /** + * Converts a document transform to the Firestore 'FieldTransform' Proto. + * + * @private + * @internal + * @param serializer The Firestore serializer + * @returns A list of Firestore 'FieldTransform' Protos + */ + toProto(serializer: Serializer): api.DocumentTransform.IFieldTransform[]; +} +/** + * A Firestore Precondition encapsulates options for database writes. + * + * @private + * @internal + * @class + */ +export declare class Precondition { + private _exists?; + private _lastUpdateTime?; + /** + * @private + * @internal + * @private + * + * @param options.exists - Whether the referenced document should exist in + * Firestore, + * @param options.lastUpdateTime - The last update time of the referenced + * document in Firestore. + * @param options + */ + constructor(options?: { + exists?: boolean; + lastUpdateTime?: firestore.Timestamp; + }); + /** + * Generates the Protobuf `Preconditon` object for this precondition. + * + * @private + * @internal + * @returns The `Preconditon` Protobuf object or 'null' if there are no + * preconditions. + */ + toProto(): api.IPrecondition | null; + /** + * Whether this DocumentTransform contains any enforcement. + * + * @private + * @internal + */ + get isEmpty(): boolean; +} diff --git a/node_modules/@google-cloud/firestore/build/src/document.js b/node_modules/@google-cloud/firestore/build/src/document.js new file mode 100644 index 0000000..5f5478c --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/document.js @@ -0,0 +1,936 @@ +"use strict"; +/*! + * Copyright 2019 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Precondition = exports.DocumentTransform = exports.DocumentMask = exports.QueryDocumentSnapshot = exports.DocumentSnapshot = exports.DocumentSnapshotBuilder = void 0; +const deepEqual = require("fast-deep-equal"); +const assert = require("assert"); +const field_value_1 = require("./field-value"); +const path_1 = require("./path"); +const document_reference_1 = require("./reference/document-reference"); +const types_1 = require("./types"); +const util_1 = require("./util"); +/** + * Returns a builder for DocumentSnapshot and QueryDocumentSnapshot instances. + * Invoke `.build()' to assemble the final snapshot. + * + * @private + * @internal + */ +class DocumentSnapshotBuilder { + // We include the DocumentReference in the constructor in order to allow the + // DocumentSnapshotBuilder to be typed with when + // it is constructed. + constructor(ref) { + this.ref = ref; + } + /** + * Builds the DocumentSnapshot. + * + * @private + * @internal + * @returns Returns either a QueryDocumentSnapshot (if `fieldsProto` was + * provided) or a DocumentSnapshot. + */ + build() { + assert((this.fieldsProto !== undefined) === (this.createTime !== undefined), 'Create time should be set iff document exists.'); + assert((this.fieldsProto !== undefined) === (this.updateTime !== undefined), 'Update time should be set iff document exists.'); + return this.fieldsProto + ? new QueryDocumentSnapshot(this.ref, this.fieldsProto, this.readTime, this.createTime, this.updateTime) + : new DocumentSnapshot(this.ref, undefined, this.readTime); + } +} +exports.DocumentSnapshotBuilder = DocumentSnapshotBuilder; +/** + * A DocumentSnapshot is an immutable representation for a document in a + * Firestore database. The data can be extracted with + * [data()]{@link DocumentSnapshot#data} or + * [get(fieldPath)]{@link DocumentSnapshot#get} to get a + * specific field. + * + *

For a DocumentSnapshot that points to a non-existing document, any data + * access will return 'undefined'. You can use the + * [exists]{@link DocumentSnapshot#exists} property to explicitly verify a + * document's existence. + * + * @class DocumentSnapshot + */ +class DocumentSnapshot { + /** + * @private + * @internal + * + * @param ref The reference to the document. + * @param _fieldsProto The fields of the Firestore `Document` Protobuf backing + * this document (or undefined if the document does not exist). + * @param readTime The time when this snapshot was read (or undefined if + * the document exists only locally). + * @param createTime The time when the document was created (or undefined if + * the document does not exist). + * @param updateTime The time when the document was last updated (or undefined + * if the document does not exist). + */ + constructor(ref, + /** + * @internal + * @private + **/ + _fieldsProto, readTime, createTime, updateTime) { + this._fieldsProto = _fieldsProto; + this._ref = ref; + this._serializer = ref.firestore._serializer; + this._readTime = readTime; + this._createTime = createTime; + this._updateTime = updateTime; + } + /** + * Creates a DocumentSnapshot from an object. + * + * @private + * @internal + * @param ref The reference to the document. + * @param obj The object to store in the DocumentSnapshot. + * @return The created DocumentSnapshot. + */ + static fromObject(ref, obj) { + const serializer = ref.firestore._serializer; + return new DocumentSnapshot(ref, serializer.encodeFields(obj)); + } + /** + * Creates a DocumentSnapshot from an UpdateMap. + * + * This methods expands the top-level field paths in a JavaScript map and + * turns { foo.bar : foobar } into { foo { bar : foobar }} + * + * @private + * @internal + * @param ref The reference to the document. + * @param data The field/value map to expand. + * @return The created DocumentSnapshot. + */ + static fromUpdateMap(ref, data) { + const serializer = ref + .firestore._serializer; + /** + * Merges 'value' at the field path specified by the path array into + * 'target'. + */ + function merge(target, value, path, pos) { + const key = path[pos]; + const isLast = pos === path.length - 1; + if (target[key] === undefined) { + if (isLast) { + if (value instanceof field_value_1.FieldTransform) { + // If there is already data at this path, we need to retain it. + // Otherwise, we don't include it in the DocumentSnapshot. + return !(0, util_1.isEmpty)(target) ? target : null; + } + // The merge is done. + const leafNode = serializer.encodeValue(value); + if (leafNode) { + target[key] = leafNode; + } + return target; + } + else { + // We need to expand the target object. + const childNode = { + mapValue: { + fields: {}, + }, + }; + const nestedValue = merge(childNode.mapValue.fields, value, path, pos + 1); + if (nestedValue) { + childNode.mapValue.fields = nestedValue; + target[key] = childNode; + return target; + } + else { + return !(0, util_1.isEmpty)(target) ? target : null; + } + } + } + else { + assert(!isLast, "Can't merge current value into a nested object"); + target[key].mapValue.fields = merge(target[key].mapValue.fields, value, path, pos + 1); + return target; + } + } + const res = {}; + for (const [key, value] of data) { + const path = key.toArray(); + merge(res, value, path, 0); + } + return new DocumentSnapshot(ref, res); + } + /** + * True if the document exists. + * + * @type {boolean} + * @name DocumentSnapshot#exists + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then((documentSnapshot) => { + * if (documentSnapshot.exists) { + * console.log(`Data: ${JSON.stringify(documentSnapshot.data())}`); + * } + * }); + * ``` + */ + get exists() { + return this._fieldsProto !== undefined; + } + /** + * A [DocumentReference]{@link DocumentReference} for the document + * stored in this snapshot. + * + * @type {DocumentReference} + * @name DocumentSnapshot#ref + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then((documentSnapshot) => { + * if (documentSnapshot.exists) { + * console.log(`Found document at '${documentSnapshot.ref.path}'`); + * } + * }); + * ``` + */ + get ref() { + return this._ref; + } + /** + * The ID of the document for which this DocumentSnapshot contains data. + * + * @type {string} + * @name DocumentSnapshot#id + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then((documentSnapshot) => { + * if (documentSnapshot.exists) { + * console.log(`Document found with name '${documentSnapshot.id}'`); + * } + * }); + * ``` + */ + get id() { + return this._ref.id; + } + /** + * The time the document was created. Undefined for documents that don't + * exist. + * + * @type {Timestamp|undefined} + * @name DocumentSnapshot#createTime + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(documentSnapshot => { + * if (documentSnapshot.exists) { + * let createTime = documentSnapshot.createTime; + * console.log(`Document created at '${createTime.toDate()}'`); + * } + * }); + * ``` + */ + get createTime() { + return this._createTime; + } + /** + * The time the document was last updated (at the time the snapshot was + * generated). Undefined for documents that don't exist. + * + * @type {Timestamp|undefined} + * @name DocumentSnapshot#updateTime + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(documentSnapshot => { + * if (documentSnapshot.exists) { + * let updateTime = documentSnapshot.updateTime; + * console.log(`Document updated at '${updateTime.toDate()}'`); + * } + * }); + * ``` + */ + get updateTime() { + return this._updateTime; + } + /** + * The time this snapshot was read. + * + * @type {Timestamp} + * @name DocumentSnapshot#readTime + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(documentSnapshot => { + * let readTime = documentSnapshot.readTime; + * console.log(`Document read at '${readTime.toDate()}'`); + * }); + * ``` + */ + get readTime() { + if (this._readTime === undefined) { + throw new Error("Called 'readTime' on a local document"); + } + return this._readTime; + } + /** + * Retrieves all fields in the document as an object. Returns 'undefined' if + * the document doesn't exist. + * + * @returns {T|undefined} An object containing all fields in the document or + * 'undefined' if the document doesn't exist. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(documentSnapshot => { + * let data = documentSnapshot.data(); + * console.log(`Retrieved data: ${JSON.stringify(data)}`); + * }); + * ``` + */ + data() { + const fields = this._fieldsProto; + if (fields === undefined) { + return undefined; + } + // We only want to use the converter and create a new QueryDocumentSnapshot + // if a converter has been provided. + if (this.ref._converter !== (0, types_1.defaultConverter)()) { + const untypedReference = new document_reference_1.DocumentReference(this.ref.firestore, this.ref._path); + return this.ref._converter.fromFirestore(new QueryDocumentSnapshot(untypedReference, this._fieldsProto, this.readTime, this.createTime, this.updateTime)); + } + else { + const obj = {}; + for (const prop of Object.keys(fields)) { + obj[prop] = this._serializer.decodeValue(fields[prop]); + } + return obj; + } + } + /** + * Retrieves the field specified by `field`. + * + * @param {string|FieldPath} field The field path + * (e.g. 'foo' or 'foo.bar') to a specific field. + * @returns {*} The data at the specified field location or undefined if no + * such field exists. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({ a: { b: 'c' }}).then(() => { + * return documentRef.get(); + * }).then(documentSnapshot => { + * let field = documentSnapshot.get('a.b'); + * console.log(`Retrieved field value: ${field}`); + * }); + * ``` + */ + // We deliberately use `any` in the external API to not impose type-checking + // on end users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(field) { + (0, path_1.validateFieldPath)('field', field); + const protoField = this.protoField(field); + if (protoField === undefined) { + return undefined; + } + return this._serializer.decodeValue(protoField); + } + /** + * Retrieves the field specified by 'fieldPath' in its Protobuf JS + * representation. + * + * @private + * @internal + * @param field The path (e.g. 'foo' or 'foo.bar') to a specific field. + * @returns The Protobuf-encoded data at the specified field location or + * undefined if no such field exists. + */ + protoField(field) { + let fields = this._fieldsProto; + if (fields === undefined) { + return undefined; + } + const components = path_1.FieldPath.fromArgument(field).toArray(); + while (components.length > 1) { + fields = fields[components.shift()]; + if (!fields || !fields.mapValue) { + return undefined; + } + fields = fields.mapValue.fields; + } + return fields[components[0]]; + } + /** + * Convert a document snapshot to the Firestore 'Write' proto. + * + * @private + * @internal + */ + toWriteProto() { + return { + update: { + name: this._ref.formattedName, + fields: this._fieldsProto, + }, + }; + } + /** + * Convert a document snapshot to the Firestore 'Document' proto. + * + * @private + * @internal + */ + toDocumentProto() { + var _a, _b; + return { + name: this._ref.formattedName, + createTime: (_a = this.createTime) === null || _a === void 0 ? void 0 : _a.toProto().timestampValue, + updateTime: (_b = this.updateTime) === null || _b === void 0 ? void 0 : _b.toProto().timestampValue, + fields: this._fieldsProto, + }; + } + /** + * Returns true if the document's data and path in this `DocumentSnapshot` is + * equal to the provided value. + * + * @param {*} other The value to compare against. + * @return {boolean} true if this `DocumentSnapshot` is equal to the provided + * value. + */ + isEqual(other) { + // Since the read time is different on every document read, we explicitly + // ignore all document metadata in this comparison. + return (this === other || + (other instanceof DocumentSnapshot && + this._ref.isEqual(other._ref) && + deepEqual(this._fieldsProto, other._fieldsProto))); + } +} +exports.DocumentSnapshot = DocumentSnapshot; +/** + * A QueryDocumentSnapshot contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with [data()]{@link QueryDocumentSnapshot#data} + * or [get()]{@link DocumentSnapshot#get} to get a specific field. + * + * A QueryDocumentSnapshot offers the same API surface as a + * {@link DocumentSnapshot}. Since query results contain only existing + * documents, the [exists]{@link DocumentSnapshot#exists} property will + * always be true and [data()]{@link QueryDocumentSnapshot#data} will never + * return 'undefined'. + * + * @class QueryDocumentSnapshot + * @extends DocumentSnapshot + */ +class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * The time the document was created. + * + * @type {Timestamp} + * @name QueryDocumentSnapshot#createTime + * @readonly + * @override + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.get().forEach(snapshot => { + * console.log(`Document created at '${snapshot.createTime.toDate()}'`); + * }); + * ``` + */ + get createTime() { + return super.createTime; + } + /** + * The time the document was last updated (at the time the snapshot was + * generated). + * + * @type {Timestamp} + * @name QueryDocumentSnapshot#updateTime + * @readonly + * @override + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.get().forEach(snapshot => { + * console.log(`Document updated at '${snapshot.updateTime.toDate()}'`); + * }); + * ``` + */ + get updateTime() { + return super.updateTime; + } + /** + * Retrieves all fields in the document as an object. + * + * @override + * + * @returns {T} An object containing all fields in the document. + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.get().forEach(documentSnapshot => { + * let data = documentSnapshot.data(); + * console.log(`Retrieved data: ${JSON.stringify(data)}`); + * }); + * ``` + */ + data() { + const data = super.data(); + if (!data) { + throw new Error('The data in a QueryDocumentSnapshot should always exist.'); + } + return data; + } +} +exports.QueryDocumentSnapshot = QueryDocumentSnapshot; +/** + * A Firestore Document Mask contains the field paths affected by an update. + * + * @class + * @private + * @internal + */ +class DocumentMask { + /** + * @private + * @internal + * @private + * + * @param fieldPaths The field paths in this mask. + */ + constructor(fieldPaths) { + this._sortedPaths = fieldPaths; + this._sortedPaths.sort((a, b) => a.compareTo(b)); + } + /** + * Creates a document mask with the field paths of a document. + * + * @private + * @internal + * @param data A map with fields to modify. Only the keys are used to extract + * the document mask. + */ + static fromUpdateMap(data) { + const fieldPaths = []; + data.forEach((value, key) => { + if (!(value instanceof field_value_1.FieldTransform) || value.includeInDocumentMask) { + fieldPaths.push(path_1.FieldPath.fromArgument(key)); + } + }); + return new DocumentMask(fieldPaths); + } + /** + * Creates a document mask from an array of field paths. + * + * @private + * @internal + * @param fieldMask A list of field paths. + */ + static fromFieldMask(fieldMask) { + const fieldPaths = []; + for (const fieldPath of fieldMask) { + fieldPaths.push(path_1.FieldPath.fromArgument(fieldPath)); + } + return new DocumentMask(fieldPaths); + } + /** + * Creates a document mask with the field names of a document. + * + * @private + * @internal + * @param data An object with fields to modify. Only the keys are used to + * extract the document mask. + */ + static fromObject(data) { + const fieldPaths = []; + function extractFieldPaths(currentData, currentPath) { + let isEmpty = true; + for (const key of Object.keys(currentData)) { + isEmpty = false; + // We don't split on dots since fromObject is called with + // DocumentData. + const childSegment = new path_1.FieldPath(key); + const childPath = currentPath + ? currentPath.append(childSegment) + : childSegment; + const value = currentData[key]; + if (value instanceof field_value_1.FieldTransform) { + if (value.includeInDocumentMask) { + fieldPaths.push(childPath); + } + } + else if ((0, util_1.isPlainObject)(value)) { + extractFieldPaths(value, childPath); + } + else if (value !== undefined) { + // If the value is undefined it can never participate in the document + // mask. With `ignoreUndefinedProperties` set to false, + // `validateDocumentData` will reject an undefined value before even + // computing the document mask. + fieldPaths.push(childPath); + } + } + // Add a field path for an explicitly updated empty map. + if (currentPath && isEmpty) { + fieldPaths.push(currentPath); + } + } + extractFieldPaths(data); + return new DocumentMask(fieldPaths); + } + /** + * Returns true if this document mask contains no fields. + * + * @private + * @internal + * @return {boolean} Whether this document mask is empty. + */ + get isEmpty() { + return this._sortedPaths.length === 0; + } + /** + * Removes the specified values from a sorted field path array. + * + * @private + * @internal + * @param input A sorted array of FieldPaths. + * @param values An array of FieldPaths to remove. + */ + static removeFromSortedArray(input, values) { + for (let i = 0; i < input.length;) { + let removed = false; + for (const fieldPath of values) { + if (input[i].isEqual(fieldPath)) { + input.splice(i, 1); + removed = true; + break; + } + } + if (!removed) { + ++i; + } + } + } + /** + * Removes the field path specified in 'fieldPaths' from this document mask. + * + * @private + * @internal + * @param fieldPaths An array of FieldPaths. + */ + removeFields(fieldPaths) { + DocumentMask.removeFromSortedArray(this._sortedPaths, fieldPaths); + } + /** + * Returns whether this document mask contains 'fieldPath'. + * + * @private + * @internal + * @param fieldPath The field path to test. + * @return Whether this document mask contains 'fieldPath'. + */ + contains(fieldPath) { + for (const sortedPath of this._sortedPaths) { + const cmp = sortedPath.compareTo(fieldPath); + if (cmp === 0) { + return true; + } + else if (cmp > 0) { + return false; + } + } + return false; + } + /** + * Removes all properties from 'data' that are not contained in this document + * mask. + * + * @private + * @internal + * @param data An object to filter. + * @return A shallow copy of the object filtered by this document mask. + */ + applyTo(data) { + /*! + * Applies this DocumentMask to 'data' and computes the list of field paths + * that were specified in the mask but are not present in 'data'. + */ + const applyDocumentMask = data => { + const remainingPaths = this._sortedPaths.slice(0); + const processObject = (currentData, currentPath) => { + let result = null; + Object.keys(currentData).forEach(key => { + const childPath = currentPath + ? currentPath.append(key) + : new path_1.FieldPath(key); + if (this.contains(childPath)) { + DocumentMask.removeFromSortedArray(remainingPaths, [childPath]); + result = result || {}; + result[key] = currentData[key]; + } + else if ((0, util_1.isObject)(currentData[key])) { + const childObject = processObject(currentData[key], childPath); + if (childObject) { + result = result || {}; + result[key] = childObject; + } + } + }); + return result; + }; + // processObject() returns 'null' if the DocumentMask is empty. + const filteredData = processObject(data) || {}; + return { + filteredData, + remainingPaths, + }; + }; + const result = applyDocumentMask(data); + if (result.remainingPaths.length !== 0) { + throw new Error(`Input data is missing for field "${result.remainingPaths[0]}".`); + } + return result.filteredData; + } + /** + * Converts a document mask to the Firestore 'DocumentMask' Proto. + * + * @private + * @internal + * @returns A Firestore 'DocumentMask' Proto. + */ + toProto() { + if (this.isEmpty) { + return {}; + } + const encodedPaths = []; + for (const fieldPath of this._sortedPaths) { + encodedPaths.push(fieldPath.formattedName); + } + return { + fieldPaths: encodedPaths, + }; + } +} +exports.DocumentMask = DocumentMask; +/** + * A Firestore Document Transform. + * + * A DocumentTransform contains pending server-side transforms and their + * corresponding field paths. + * + * @private + * @internal + * @class + */ +class DocumentTransform { + /** + * @private + * @internal + * @private + * + * @param ref The DocumentReference for this transform. + * @param transforms A Map of FieldPaths to FieldTransforms. + */ + constructor(ref, transforms) { + this.ref = ref; + this.transforms = transforms; + } + /** + * Generates a DocumentTransform from a JavaScript object. + * + * @private + * @internal + * @param ref The `DocumentReference` to use for the DocumentTransform. + * @param obj The object to extract the transformations from. + * @returns The Document Transform. + */ + static fromObject(ref, obj) { + const updateMap = new Map(); + for (const prop of Object.keys(obj)) { + updateMap.set(new path_1.FieldPath(prop), obj[prop]); + } + return DocumentTransform.fromUpdateMap(ref, updateMap); + } + /** + * Generates a DocumentTransform from an Update Map. + * + * @private + * @internal + * @param ref The `DocumentReference` to use for the DocumentTransform. + * @param data The update data to extract the transformations from. + * @returns The Document Transform. + */ + static fromUpdateMap(ref, data) { + const transforms = new Map(); + function encode_(val, path, allowTransforms) { + if (val instanceof field_value_1.FieldTransform && val.includeInDocumentTransform) { + if (allowTransforms) { + transforms.set(path, val); + } + else { + throw new Error(`${val.methodName}() is not supported inside of array values.`); + } + } + else if (Array.isArray(val)) { + for (let i = 0; i < val.length; ++i) { + // We need to verify that no array value contains a document transform + encode_(val[i], path.append(String(i)), false); + } + } + else if ((0, util_1.isPlainObject)(val)) { + for (const prop of Object.keys(val)) { + encode_(val[prop], path.append(new path_1.FieldPath(prop)), allowTransforms); + } + } + } + data.forEach((value, key) => { + encode_(value, path_1.FieldPath.fromArgument(key), true); + }); + return new DocumentTransform(ref, transforms); + } + /** + * Whether this DocumentTransform contains any actionable transformations. + * + * @private + * @internal + */ + get isEmpty() { + return this.transforms.size === 0; + } + /** + * Returns the array of fields in this DocumentTransform. + * + * @private + * @internal + */ + get fields() { + return Array.from(this.transforms.keys()); + } + /** + * Validates the user provided field values in this document transform. + * @private + * @internal + */ + validate() { + const allowUndefined = !!this.ref.firestore._settings.ignoreUndefinedProperties; + this.transforms.forEach(transform => transform.validate(allowUndefined)); + } + /** + * Converts a document transform to the Firestore 'FieldTransform' Proto. + * + * @private + * @internal + * @param serializer The Firestore serializer + * @returns A list of Firestore 'FieldTransform' Protos + */ + toProto(serializer) { + return Array.from(this.transforms, ([path, transform]) => transform.toProto(serializer, path)); + } +} +exports.DocumentTransform = DocumentTransform; +/** + * A Firestore Precondition encapsulates options for database writes. + * + * @private + * @internal + * @class + */ +class Precondition { + /** + * @private + * @internal + * @private + * + * @param options.exists - Whether the referenced document should exist in + * Firestore, + * @param options.lastUpdateTime - The last update time of the referenced + * document in Firestore. + * @param options + */ + constructor(options) { + if (options !== undefined) { + this._exists = options.exists; + this._lastUpdateTime = options.lastUpdateTime; + } + } + /** + * Generates the Protobuf `Preconditon` object for this precondition. + * + * @private + * @internal + * @returns The `Preconditon` Protobuf object or 'null' if there are no + * preconditions. + */ + toProto() { + if (this.isEmpty) { + return null; + } + const proto = {}; + if (this._lastUpdateTime !== undefined) { + proto.updateTime = this._lastUpdateTime.toProto().timestampValue; + } + else { + proto.exists = this._exists; + } + return proto; + } + /** + * Whether this DocumentTransform contains any enforcement. + * + * @private + * @internal + */ + get isEmpty() { + return this._exists === undefined && !this._lastUpdateTime; + } +} +exports.Precondition = Precondition; +//# sourceMappingURL=document.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/field-value.d.ts b/node_modules/@google-cloud/firestore/build/src/field-value.d.ts new file mode 100644 index 0000000..10a40f0 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/field-value.d.ts @@ -0,0 +1,289 @@ +/*! + * Copyright 2018 Google Inc. 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. + */ +import * as firestore from '@google-cloud/firestore'; +import * as proto from '../protos/firestore_v1_proto_api'; +import { FieldPath } from './path'; +import { Serializer } from './serializer'; +import api = proto.google.firestore.v1; +/** + * Represent a vector type in Firestore documents. + * Create an instance with {@link FieldValue.vector}. + * + * @class VectorValue + */ +export declare class VectorValue implements firestore.VectorValue { + private readonly _values; + /** + * @private + * @internal + */ + constructor(values: number[] | undefined); + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray(): number[]; + /** + * @private + * @internal + */ + _toProto(serializer: Serializer): api.IValue; + /** + * @private + * @internal + */ + static _fromProto(valueArray: api.IValue): VectorValue; + /** + * Returns `true` if the two VectorValue has the same raw number arrays, returns `false` otherwise. + */ + isEqual(other: VectorValue): boolean; +} +/** + * Sentinel values that can be used when writing documents with set(), create() + * or update(). + * + * @class FieldValue + */ +export declare class FieldValue implements firestore.FieldValue { + /** @private */ + constructor(); + /** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ + static vector(values?: number[]): VectorValue; + /** + * Returns a sentinel for use with update() or set() with {merge:true} to mark + * a field for deletion. + * + * @returns {FieldValue} The sentinel value to use in your objects. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * let data = { a: 'b', c: 'd' }; + * + * documentRef.set(data).then(() => { + * return documentRef.update({a: Firestore.FieldValue.delete()}); + * }).then(() => { + * // Document now only contains { c: 'd' } + * }); + * ``` + */ + static delete(): FieldValue; + /** + * Returns a sentinel used with set(), create() or update() to include a + * server-generated timestamp in the written data. + * + * @return {FieldValue} The FieldValue sentinel for use in a call to set(), + * create() or update(). + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({ + * time: Firestore.FieldValue.serverTimestamp() + * }).then(() => { + * return documentRef.get(); + * }).then(doc => { + * console.log(`Server time set to ${doc.get('time')}`); + * }); + * ``` + */ + static serverTimestamp(): FieldValue; + /** + * Returns a special value that can be used with set(), create() or update() + * that tells the server to increment the the field's current value by the + * given value. + * + * If either current field value or the operand uses floating point + * precision, both values will be interpreted as floating point numbers and + * all arithmetic will follow IEEE 754 semantics. Otherwise, integer + * precision is kept and the result is capped between -2^63 and 2^63-1. + * + * If the current field value is not of type 'number', or if the field does + * not yet exist, the transformation will set the field to the given value. + * + * @param {number} n The value to increment by. + * @return {FieldValue} The FieldValue sentinel for use in a call to set(), + * create() or update(). + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.update( + * 'counter', Firestore.FieldValue.increment(1) + * ).then(() => { + * return documentRef.get(); + * }).then(doc => { + * // doc.get('counter') was incremented + * }); + * ``` + */ + static increment(n: number): FieldValue; + /** + * Returns a special value that can be used with set(), create() or update() + * that tells the server to union the given elements with any array value that + * already exists on the server. Each specified element that doesn't already + * exist in the array will be added to the end. If the field being modified is + * not already an array it will be overwritten with an array containing + * exactly the specified elements. + * + * @param {...*} elements The elements to union into the array. + * @return {FieldValue} The FieldValue sentinel for use in a call to set(), + * create() or update(). + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.update( + * 'array', Firestore.FieldValue.arrayUnion('foo') + * ).then(() => { + * return documentRef.get(); + * }).then(doc => { + * // doc.get('array') contains field 'foo' + * }); + * ``` + */ + static arrayUnion(...elements: unknown[]): FieldValue; + /** + * Returns a special value that can be used with set(), create() or update() + * that tells the server to remove the given elements from any array value + * that already exists on the server. All instances of each element specified + * will be removed from the array. If the field being modified is not already + * an array it will be overwritten with an empty array. + * + * @param {...*} elements The elements to remove from the array. + * @return {FieldValue} The FieldValue sentinel for use in a call to set(), + * create() or update(). + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.update( + * 'array', Firestore.FieldValue.arrayRemove('foo') + * ).then(() => { + * return documentRef.get(); + * }).then(doc => { + * // doc.get('array') no longer contains field 'foo' + * }); + * ``` + */ + static arrayRemove(...elements: unknown[]): FieldValue; + /** + * Returns true if this `FieldValue` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @return {boolean} true if this `FieldValue` is equal to the provided value. + * + * @example + * ``` + * let fieldValues = [ + * Firestore.FieldValue.increment(-1.0), + * Firestore.FieldValue.increment(-1), + * Firestore.FieldValue.increment(-0.0), + * Firestore.FieldValue.increment(-0), + * Firestore.FieldValue.increment(0), + * Firestore.FieldValue.increment(0.0), + * Firestore.FieldValue.increment(1), + * Firestore.FieldValue.increment(1.0) + * ]; + * + * let equal = 0; + * for (let i = 0; i < fieldValues.length; ++i) { + * for (let j = i + 1; j < fieldValues.length; ++j) { + * if (fieldValues[i].isEqual(fieldValues[j])) { + * ++equal; + * } + * } + * } + * console.log(`Found ${equal} equalities.`); + * ``` + */ + isEqual(other: firestore.FieldValue): boolean; +} +/** + * An internal interface shared by all field transforms. + * + * A 'FieldTransform` subclass should implement '.includeInDocumentMask', + * '.includeInDocumentTransform' and 'toProto' (if '.includeInDocumentTransform' + * is 'true'). + * + * @private + * @internal + * @abstract + */ +export declare abstract class FieldTransform extends FieldValue { + /** Whether this FieldTransform should be included in the document mask. */ + abstract get includeInDocumentMask(): boolean; + /** + * Whether this FieldTransform should be included in the list of document + * transforms. + */ + abstract get includeInDocumentTransform(): boolean; + /** The method name used to obtain the field transform. */ + abstract get methodName(): string; + /** + * Performs input validation on the values of this field transform. + * + * @param allowUndefined Whether to allow nested properties that are `undefined`. + */ + abstract validate(allowUndefined: boolean): void; + /*** + * The proto representation for this field transform. + * + * @param serializer The Firestore serializer. + * @param fieldPath The field path to apply this transformation to. + * @return The 'FieldTransform' proto message. + */ + abstract toProto(serializer: Serializer, fieldPath: FieldPath): api.DocumentTransform.IFieldTransform; +} +/** + * A transform that deletes a field from a Firestore document. + * + * @private + * @internal + */ +export declare class DeleteTransform extends FieldTransform { + /** + * Sentinel value for a field delete. + * @private + * @internal + */ + static DELETE_SENTINEL: DeleteTransform; + private constructor(); + /** + * Deletes are included in document masks. + * @private + * @internal + */ + get includeInDocumentMask(): true; + /** + * Deletes are are omitted from document transforms. + * @private + * @internal + */ + get includeInDocumentTransform(): false; + get methodName(): string; + validate(): void; + toProto(): never; +} diff --git a/node_modules/@google-cloud/firestore/build/src/field-value.js b/node_modules/@google-cloud/firestore/build/src/field-value.js new file mode 100644 index 0000000..764151f --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/field-value.js @@ -0,0 +1,523 @@ +"use strict"; +/*! + * Copyright 2018 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DeleteTransform = exports.FieldTransform = exports.FieldValue = exports.VectorValue = void 0; +const deepEqual = require("fast-deep-equal"); +const serializer_1 = require("./serializer"); +const util_1 = require("./util"); +const validate_1 = require("./validate"); +/** + * Represent a vector type in Firestore documents. + * Create an instance with {@link FieldValue.vector}. + * + * @class VectorValue + */ +class VectorValue { + /** + * @private + * @internal + */ + constructor(values) { + // Making a copy of the parameter. + this._values = (values || []).map(n => n); + } + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray() { + return this._values.map(n => n); + } + /** + * @private + * @internal + */ + _toProto(serializer) { + return serializer.encodeVector(this._values); + } + /** + * @private + * @internal + */ + static _fromProto(valueArray) { + var _a, _b; + const values = (_b = (_a = valueArray.arrayValue) === null || _a === void 0 ? void 0 : _a.values) === null || _b === void 0 ? void 0 : _b.map(v => { + return v.doubleValue; + }); + return new VectorValue(values); + } + /** + * Returns `true` if the two VectorValue has the same raw number arrays, returns `false` otherwise. + */ + isEqual(other) { + return (0, util_1.isPrimitiveArrayEqual)(this._values, other._values); + } +} +exports.VectorValue = VectorValue; +/** + * Sentinel values that can be used when writing documents with set(), create() + * or update(). + * + * @class FieldValue + */ +class FieldValue { + /** @private */ + constructor() { } + /** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ + static vector(values) { + return new VectorValue(values); + } + /** + * Returns a sentinel for use with update() or set() with {merge:true} to mark + * a field for deletion. + * + * @returns {FieldValue} The sentinel value to use in your objects. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * let data = { a: 'b', c: 'd' }; + * + * documentRef.set(data).then(() => { + * return documentRef.update({a: Firestore.FieldValue.delete()}); + * }).then(() => { + * // Document now only contains { c: 'd' } + * }); + * ``` + */ + static delete() { + return DeleteTransform.DELETE_SENTINEL; + } + /** + * Returns a sentinel used with set(), create() or update() to include a + * server-generated timestamp in the written data. + * + * @return {FieldValue} The FieldValue sentinel for use in a call to set(), + * create() or update(). + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({ + * time: Firestore.FieldValue.serverTimestamp() + * }).then(() => { + * return documentRef.get(); + * }).then(doc => { + * console.log(`Server time set to ${doc.get('time')}`); + * }); + * ``` + */ + static serverTimestamp() { + return ServerTimestampTransform.SERVER_TIMESTAMP_SENTINEL; + } + /** + * Returns a special value that can be used with set(), create() or update() + * that tells the server to increment the the field's current value by the + * given value. + * + * If either current field value or the operand uses floating point + * precision, both values will be interpreted as floating point numbers and + * all arithmetic will follow IEEE 754 semantics. Otherwise, integer + * precision is kept and the result is capped between -2^63 and 2^63-1. + * + * If the current field value is not of type 'number', or if the field does + * not yet exist, the transformation will set the field to the given value. + * + * @param {number} n The value to increment by. + * @return {FieldValue} The FieldValue sentinel for use in a call to set(), + * create() or update(). + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.update( + * 'counter', Firestore.FieldValue.increment(1) + * ).then(() => { + * return documentRef.get(); + * }).then(doc => { + * // doc.get('counter') was incremented + * }); + * ``` + */ + static increment(n) { + // eslint-disable-next-line prefer-rest-params + (0, validate_1.validateMinNumberOfArguments)('FieldValue.increment', arguments, 1); + return new NumericIncrementTransform(n); + } + /** + * Returns a special value that can be used with set(), create() or update() + * that tells the server to union the given elements with any array value that + * already exists on the server. Each specified element that doesn't already + * exist in the array will be added to the end. If the field being modified is + * not already an array it will be overwritten with an array containing + * exactly the specified elements. + * + * @param {...*} elements The elements to union into the array. + * @return {FieldValue} The FieldValue sentinel for use in a call to set(), + * create() or update(). + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.update( + * 'array', Firestore.FieldValue.arrayUnion('foo') + * ).then(() => { + * return documentRef.get(); + * }).then(doc => { + * // doc.get('array') contains field 'foo' + * }); + * ``` + */ + static arrayUnion(...elements) { + (0, validate_1.validateMinNumberOfArguments)('FieldValue.arrayUnion', elements, 1); + return new ArrayUnionTransform(elements); + } + /** + * Returns a special value that can be used with set(), create() or update() + * that tells the server to remove the given elements from any array value + * that already exists on the server. All instances of each element specified + * will be removed from the array. If the field being modified is not already + * an array it will be overwritten with an empty array. + * + * @param {...*} elements The elements to remove from the array. + * @return {FieldValue} The FieldValue sentinel for use in a call to set(), + * create() or update(). + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.update( + * 'array', Firestore.FieldValue.arrayRemove('foo') + * ).then(() => { + * return documentRef.get(); + * }).then(doc => { + * // doc.get('array') no longer contains field 'foo' + * }); + * ``` + */ + static arrayRemove(...elements) { + (0, validate_1.validateMinNumberOfArguments)('FieldValue.arrayRemove', elements, 1); + return new ArrayRemoveTransform(elements); + } + /** + * Returns true if this `FieldValue` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @return {boolean} true if this `FieldValue` is equal to the provided value. + * + * @example + * ``` + * let fieldValues = [ + * Firestore.FieldValue.increment(-1.0), + * Firestore.FieldValue.increment(-1), + * Firestore.FieldValue.increment(-0.0), + * Firestore.FieldValue.increment(-0), + * Firestore.FieldValue.increment(0), + * Firestore.FieldValue.increment(0.0), + * Firestore.FieldValue.increment(1), + * Firestore.FieldValue.increment(1.0) + * ]; + * + * let equal = 0; + * for (let i = 0; i < fieldValues.length; ++i) { + * for (let j = i + 1; j < fieldValues.length; ++j) { + * if (fieldValues[i].isEqual(fieldValues[j])) { + * ++equal; + * } + * } + * } + * console.log(`Found ${equal} equalities.`); + * ``` + */ + isEqual(other) { + return this === other; + } +} +exports.FieldValue = FieldValue; +/** + * An internal interface shared by all field transforms. + * + * A 'FieldTransform` subclass should implement '.includeInDocumentMask', + * '.includeInDocumentTransform' and 'toProto' (if '.includeInDocumentTransform' + * is 'true'). + * + * @private + * @internal + * @abstract + */ +class FieldTransform extends FieldValue { +} +exports.FieldTransform = FieldTransform; +/** + * A transform that deletes a field from a Firestore document. + * + * @private + * @internal + */ +class DeleteTransform extends FieldTransform { + constructor() { + super(); + } + /** + * Deletes are included in document masks. + * @private + * @internal + */ + get includeInDocumentMask() { + return true; + } + /** + * Deletes are are omitted from document transforms. + * @private + * @internal + */ + get includeInDocumentTransform() { + return false; + } + get methodName() { + return 'FieldValue.delete'; + } + validate() { } + toProto() { + throw new Error('FieldValue.delete() should not be included in a FieldTransform'); + } +} +exports.DeleteTransform = DeleteTransform; +/** + * Sentinel value for a field delete. + * @private + * @internal + */ +DeleteTransform.DELETE_SENTINEL = new DeleteTransform(); +/** + * A transform that sets a field to the Firestore server time. + * + * @private + * @internal + */ +class ServerTimestampTransform extends FieldTransform { + constructor() { + super(); + } + /** + * Server timestamps are omitted from document masks. + * + * @private + * @internal + */ + get includeInDocumentMask() { + return false; + } + /** + * Server timestamps are included in document transforms. + * + * @private + * @internal + */ + get includeInDocumentTransform() { + return true; + } + get methodName() { + return 'FieldValue.serverTimestamp'; + } + validate() { } + toProto(serializer, fieldPath) { + return { + fieldPath: fieldPath.formattedName, + setToServerValue: 'REQUEST_TIME', + }; + } +} +/** + * Sentinel value for a server timestamp. + * + * @private + * @internal + */ +ServerTimestampTransform.SERVER_TIMESTAMP_SENTINEL = new ServerTimestampTransform(); +/** + * Increments a field value on the backend. + * + * @private + * @internal + */ +class NumericIncrementTransform extends FieldTransform { + constructor(operand) { + super(); + this.operand = operand; + } + /** + * Numeric transforms are omitted from document masks. + * + * @private + * @internal + */ + get includeInDocumentMask() { + return false; + } + /** + * Numeric transforms are included in document transforms. + * + * @private + * @internal + */ + get includeInDocumentTransform() { + return true; + } + get methodName() { + return 'FieldValue.increment'; + } + validate() { + (0, validate_1.validateNumber)('FieldValue.increment()', this.operand); + } + toProto(serializer, fieldPath) { + const encodedOperand = serializer.encodeValue(this.operand); + return { fieldPath: fieldPath.formattedName, increment: encodedOperand }; + } + isEqual(other) { + return (this === other || + (other instanceof NumericIncrementTransform && + this.operand === other.operand)); + } +} +/** + * Transforms an array value via a union operation. + * + * @private + * @internal + */ +class ArrayUnionTransform extends FieldTransform { + constructor(elements) { + super(); + this.elements = elements; + } + /** + * Array transforms are omitted from document masks. + * @private + * @internal + */ + get includeInDocumentMask() { + return false; + } + /** + * Array transforms are included in document transforms. + * @private + * @internal + */ + get includeInDocumentTransform() { + return true; + } + get methodName() { + return 'FieldValue.arrayUnion'; + } + validate(allowUndefined) { + for (let i = 0; i < this.elements.length; ++i) { + validateArrayElement(i, this.elements[i], allowUndefined); + } + } + toProto(serializer, fieldPath) { + const encodedElements = serializer.encodeValue(this.elements).arrayValue; + return { + fieldPath: fieldPath.formattedName, + appendMissingElements: encodedElements, + }; + } + isEqual(other) { + return (this === other || + (other instanceof ArrayUnionTransform && + deepEqual(this.elements, other.elements))); + } +} +/** + * Transforms an array value via a remove operation. + * + * @private + * @internal + */ +class ArrayRemoveTransform extends FieldTransform { + constructor(elements) { + super(); + this.elements = elements; + } + /** + * Array transforms are omitted from document masks. + * @private + * @internal + */ + get includeInDocumentMask() { + return false; + } + /** + * Array transforms are included in document transforms. + * @private + * @internal + */ + get includeInDocumentTransform() { + return true; + } + get methodName() { + return 'FieldValue.arrayRemove'; + } + validate(allowUndefined) { + for (let i = 0; i < this.elements.length; ++i) { + validateArrayElement(i, this.elements[i], allowUndefined); + } + } + toProto(serializer, fieldPath) { + const encodedElements = serializer.encodeValue(this.elements).arrayValue; + return { + fieldPath: fieldPath.formattedName, + removeAllFromArray: encodedElements, + }; + } + isEqual(other) { + return (this === other || + (other instanceof ArrayRemoveTransform && + deepEqual(this.elements, other.elements))); + } +} +/** + * Validates that `value` can be used as an element inside of an array. Certain + * field values (such as ServerTimestamps) are rejected. Nested arrays are also + * rejected. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The value to validate. + * @param allowUndefined Whether to allow nested properties that are `undefined`. + */ +function validateArrayElement(arg, value, allowUndefined) { + if (Array.isArray(value)) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, 'array element')} Nested arrays are not supported.`); + } + (0, serializer_1.validateUserInput)(arg, value, 'array element', + /*path=*/ { allowDeletes: 'none', allowTransforms: false, allowUndefined }, + /*path=*/ undefined, + /*level=*/ 0, + /*inArray=*/ true); +} +//# sourceMappingURL=field-value.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/filter.d.ts b/node_modules/@google-cloud/firestore/build/src/filter.d.ts new file mode 100644 index 0000000..e44129a --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/filter.d.ts @@ -0,0 +1,184 @@ +/*! + * Copyright 2023 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. + */ +import * as firestore from '@google-cloud/firestore'; +/** + * A `Filter` represents a restriction on one or more field values and can + * be used to refine the results of a {@link Query}. + * `Filters`s are created by invoking {@link Filter#where}, {@link Filter#or}, + * or {@link Filter#and} and can then be passed to {@link Query#where} + * to create a new {@link Query} instance that also contains this `Filter`. + */ +export declare abstract class Filter { + /** + * Creates and returns a new [Filter]{@link Filter}, which can be + * applied to [Query.where()]{@link Query#where}, [Filter.or()]{@link Filter#or}, + * or [Filter.and()]{@link Filter#and}. When applied to a [Query]{@link Query} + * it requires that documents must contain the specified field and that its value should + * satisfy the relation constraint provided. + * + * @param {string|FieldPath} fieldPath The name of a property value to compare. + * @param {string} opStr A comparison operation in the form of a string. + * Acceptable operator strings are "<", "<=", "==", "!=", ">=", ">", "array-contains", + * "in", "not-in", and "array-contains-any". + * @param {*} value The value to which to compare the field for inclusion in + * a query. + * @returns {Filter} The created Filter. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.where(Filter.where('foo', '==', 'bar')).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + static where(fieldPath: string | firestore.FieldPath, opStr: firestore.WhereFilterOp, value: unknown): Filter; + /** + * Creates and returns a new [Filter]{@link Filter} that is a + * disjunction of the given {@link Filter}s. A disjunction filter includes + * a document if it satisfies any of the given {@link Filter}s. + * + * The returned Filter can be applied to [Query.where()]{@link Query#where}, + * [Filter.or()]{@link Filter#or}, or [Filter.and()]{@link Filter#and}. When + * applied to a [Query]{@link Query} it requires that documents must satisfy + * one of the provided {@link Filter}s. + * + * @param {...Filter} filters Optional. The {@link Filter}s + * for OR operation. These must be created with calls to {@link Filter#where}, + * {@link Filter#or}, or {@link Filter#and}. + * @returns {Filter} The created {@link Filter}. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * // doc.foo == 'bar' || doc.baz > 0 + * let orFilter = Filter.or(Filter.where('foo', '==', 'bar'), Filter.where('baz', '>', 0)); + * + * collectionRef.where(orFilter).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + static or(...filters: Filter[]): Filter; + /** + * Creates and returns a new [Filter]{@link Filter} that is a + * conjunction of the given {@link Filter}s. A conjunction filter includes + * a document if it satisfies all of the given {@link Filter}s. + * + * The returned Filter can be applied to [Query.where()]{@link Query#where}, + * [Filter.or()]{@link Filter#or}, or [Filter.and()]{@link Filter#and}. When + * applied to a [Query]{@link Query} it requires that documents must satisfy + * one of the provided {@link Filter}s. + * + * @param {...Filter} filters Optional. The {@link Filter}s + * for AND operation. These must be created with calls to {@link Filter#where}, + * {@link Filter#or}, or {@link Filter#and}. + * @returns {Filter} The created {@link Filter}. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * // doc.foo == 'bar' && doc.baz > 0 + * let andFilter = Filter.and(Filter.where('foo', '==', 'bar'), Filter.where('baz', '>', 0)); + * + * collectionRef.where(andFilter).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + static and(...filters: Filter[]): Filter; +} +/** + * A `UnaryFilter` represents a restriction on one field value and can + * be used to refine the results of a {@link Query}. + * `UnaryFilter`s are created by invoking {@link Filter#where} and can then + * be passed to {@link Query#where} to create a new {@link Query} instance + * that also contains this `UnaryFilter`. + * + * @private + * @internal + */ +export declare class UnaryFilter extends Filter { + private field; + private operator; + private value; + /** + @private + @internal + */ + constructor(field: string | firestore.FieldPath, operator: firestore.WhereFilterOp, value: unknown); + /** + @private + @internal + */ + _getField(): string | firestore.FieldPath; + /** + @private + @internal + */ + _getOperator(): firestore.WhereFilterOp; + /** + @private + @internal + */ + _getValue(): unknown; +} +/** + * A `CompositeFilter` is used to narrow the set of documents returned + * by a Firestore query by performing the logical OR or AND of multiple + * {@link Filters}s. `CompositeFilters`s are created by invoking {@link Filter#or} + * or {@link Filter#and} and can then be passed to {@link Query#where} + * to create a new query instance that also contains the `CompositeFilter`. + * + * @private + * @internal + */ +export declare class CompositeFilter extends Filter { + private filters; + private operator; + /** + @private + @internal + */ + constructor(filters: Filter[], operator: CompositeOperator); + /** + @private + @internal + */ + _getFilters(): Filter[]; + /** + @private + @internal + */ + _getOperator(): CompositeOperator; +} +/** + * Composition operator of a `CompositeFilter`. This operator specifies the + * behavior of the `CompositeFilter`. + * + * @private + * @internal + */ +export type CompositeOperator = 'AND' | 'OR'; diff --git a/node_modules/@google-cloud/firestore/build/src/filter.js b/node_modules/@google-cloud/firestore/build/src/filter.js new file mode 100644 index 0000000..f7df2a0 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/filter.js @@ -0,0 +1,202 @@ +"use strict"; +/*! + * Copyright 2023 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CompositeFilter = exports.UnaryFilter = exports.Filter = void 0; +/** + * A `Filter` represents a restriction on one or more field values and can + * be used to refine the results of a {@link Query}. + * `Filters`s are created by invoking {@link Filter#where}, {@link Filter#or}, + * or {@link Filter#and} and can then be passed to {@link Query#where} + * to create a new {@link Query} instance that also contains this `Filter`. + */ +class Filter { + /** + * Creates and returns a new [Filter]{@link Filter}, which can be + * applied to [Query.where()]{@link Query#where}, [Filter.or()]{@link Filter#or}, + * or [Filter.and()]{@link Filter#and}. When applied to a [Query]{@link Query} + * it requires that documents must contain the specified field and that its value should + * satisfy the relation constraint provided. + * + * @param {string|FieldPath} fieldPath The name of a property value to compare. + * @param {string} opStr A comparison operation in the form of a string. + * Acceptable operator strings are "<", "<=", "==", "!=", ">=", ">", "array-contains", + * "in", "not-in", and "array-contains-any". + * @param {*} value The value to which to compare the field for inclusion in + * a query. + * @returns {Filter} The created Filter. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.where(Filter.where('foo', '==', 'bar')).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + static where(fieldPath, opStr, value) { + return new UnaryFilter(fieldPath, opStr, value); + } + /** + * Creates and returns a new [Filter]{@link Filter} that is a + * disjunction of the given {@link Filter}s. A disjunction filter includes + * a document if it satisfies any of the given {@link Filter}s. + * + * The returned Filter can be applied to [Query.where()]{@link Query#where}, + * [Filter.or()]{@link Filter#or}, or [Filter.and()]{@link Filter#and}. When + * applied to a [Query]{@link Query} it requires that documents must satisfy + * one of the provided {@link Filter}s. + * + * @param {...Filter} filters Optional. The {@link Filter}s + * for OR operation. These must be created with calls to {@link Filter#where}, + * {@link Filter#or}, or {@link Filter#and}. + * @returns {Filter} The created {@link Filter}. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * // doc.foo == 'bar' || doc.baz > 0 + * let orFilter = Filter.or(Filter.where('foo', '==', 'bar'), Filter.where('baz', '>', 0)); + * + * collectionRef.where(orFilter).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + static or(...filters) { + return new CompositeFilter(filters, 'OR'); + } + /** + * Creates and returns a new [Filter]{@link Filter} that is a + * conjunction of the given {@link Filter}s. A conjunction filter includes + * a document if it satisfies all of the given {@link Filter}s. + * + * The returned Filter can be applied to [Query.where()]{@link Query#where}, + * [Filter.or()]{@link Filter#or}, or [Filter.and()]{@link Filter#and}. When + * applied to a [Query]{@link Query} it requires that documents must satisfy + * one of the provided {@link Filter}s. + * + * @param {...Filter} filters Optional. The {@link Filter}s + * for AND operation. These must be created with calls to {@link Filter#where}, + * {@link Filter#or}, or {@link Filter#and}. + * @returns {Filter} The created {@link Filter}. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * // doc.foo == 'bar' && doc.baz > 0 + * let andFilter = Filter.and(Filter.where('foo', '==', 'bar'), Filter.where('baz', '>', 0)); + * + * collectionRef.where(andFilter).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + static and(...filters) { + return new CompositeFilter(filters, 'AND'); + } +} +exports.Filter = Filter; +/** + * A `UnaryFilter` represents a restriction on one field value and can + * be used to refine the results of a {@link Query}. + * `UnaryFilter`s are created by invoking {@link Filter#where} and can then + * be passed to {@link Query#where} to create a new {@link Query} instance + * that also contains this `UnaryFilter`. + * + * @private + * @internal + */ +class UnaryFilter extends Filter { + /** + @private + @internal + */ + constructor(field, operator, value) { + super(); + this.field = field; + this.operator = operator; + this.value = value; + } + /** + @private + @internal + */ + _getField() { + return this.field; + } + /** + @private + @internal + */ + _getOperator() { + return this.operator; + } + /** + @private + @internal + */ + _getValue() { + return this.value; + } +} +exports.UnaryFilter = UnaryFilter; +/** + * A `CompositeFilter` is used to narrow the set of documents returned + * by a Firestore query by performing the logical OR or AND of multiple + * {@link Filters}s. `CompositeFilters`s are created by invoking {@link Filter#or} + * or {@link Filter#and} and can then be passed to {@link Query#where} + * to create a new query instance that also contains the `CompositeFilter`. + * + * @private + * @internal + */ +class CompositeFilter extends Filter { + /** + @private + @internal + */ + constructor(filters, operator) { + super(); + this.filters = filters; + this.operator = operator; + } + /** + @private + @internal + */ + _getFilters() { + return this.filters; + } + /** + @private + @internal + */ + _getOperator() { + return this.operator; + } +} +exports.CompositeFilter = CompositeFilter; +//# sourceMappingURL=filter.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/geo-point.d.ts b/node_modules/@google-cloud/firestore/build/src/geo-point.d.ts new file mode 100644 index 0000000..469c236 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/geo-point.d.ts @@ -0,0 +1,83 @@ +/*! + * Copyright 2018 Google Inc. 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. + */ +import * as firestore from '@google-cloud/firestore'; +import { google } from '../protos/firestore_v1_proto_api'; +import { Serializable } from './serializer'; +import api = google.firestore.v1; +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as a latitude/longitude pair. + * + * @class + */ +export declare class GeoPoint implements Serializable, firestore.GeoPoint { + private readonly _latitude; + private readonly _longitude; + /** + * Creates a [GeoPoint]{@link GeoPoint}. + * + * @param {number} latitude The latitude as a number between -90 and 90. + * @param {number} longitude The longitude as a number between -180 and 180. + * + * @example + * ``` + * let data = { + * google: new Firestore.GeoPoint(37.422, 122.084) + * }; + * + * firestore.doc('col/doc').set(data).then(() => { + * console.log(`Location is ${data.google.latitude}, ` + + * `${data.google.longitude}`); + * }); + * ``` + */ + constructor(latitude: number, longitude: number); + /** + * The latitude as a number between -90 and 90. + * + * @type {number} + * @name GeoPoint#latitude + * @readonly + */ + get latitude(): number; + /** + * The longitude as a number between -180 and 180. + * + * @type {number} + * @name GeoPoint#longitude + * @readonly + */ + get longitude(): number; + /** + * Returns true if this `GeoPoint` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @return {boolean} true if this `GeoPoint` is equal to the provided value. + */ + isEqual(other: firestore.GeoPoint): boolean; + /** + * Converts the GeoPoint to a google.type.LatLng proto. + * @private + * @internal + */ + toProto(): api.IValue; + /** + * Converts a google.type.LatLng proto to its GeoPoint representation. + * @private + * @internal + */ + static fromProto(proto: google.type.ILatLng): GeoPoint; +} diff --git a/node_modules/@google-cloud/firestore/build/src/geo-point.js b/node_modules/@google-cloud/firestore/build/src/geo-point.js new file mode 100644 index 0000000..d50ea65 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/geo-point.js @@ -0,0 +1,106 @@ +"use strict"; +/*! + * Copyright 2018 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GeoPoint = void 0; +const validate_1 = require("./validate"); +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as a latitude/longitude pair. + * + * @class + */ +class GeoPoint { + /** + * Creates a [GeoPoint]{@link GeoPoint}. + * + * @param {number} latitude The latitude as a number between -90 and 90. + * @param {number} longitude The longitude as a number between -180 and 180. + * + * @example + * ``` + * let data = { + * google: new Firestore.GeoPoint(37.422, 122.084) + * }; + * + * firestore.doc('col/doc').set(data).then(() => { + * console.log(`Location is ${data.google.latitude}, ` + + * `${data.google.longitude}`); + * }); + * ``` + */ + constructor(latitude, longitude) { + (0, validate_1.validateNumber)('latitude', latitude, { minValue: -90, maxValue: 90 }); + (0, validate_1.validateNumber)('longitude', longitude, { minValue: -180, maxValue: 180 }); + this._latitude = latitude; + this._longitude = longitude; + } + /** + * The latitude as a number between -90 and 90. + * + * @type {number} + * @name GeoPoint#latitude + * @readonly + */ + get latitude() { + return this._latitude; + } + /** + * The longitude as a number between -180 and 180. + * + * @type {number} + * @name GeoPoint#longitude + * @readonly + */ + get longitude() { + return this._longitude; + } + /** + * Returns true if this `GeoPoint` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @return {boolean} true if this `GeoPoint` is equal to the provided value. + */ + isEqual(other) { + return (this === other || + (other instanceof GeoPoint && + this.latitude === other.latitude && + this.longitude === other.longitude)); + } + /** + * Converts the GeoPoint to a google.type.LatLng proto. + * @private + * @internal + */ + toProto() { + return { + geoPointValue: { + latitude: this.latitude, + longitude: this.longitude, + }, + }; + } + /** + * Converts a google.type.LatLng proto to its GeoPoint representation. + * @private + * @internal + */ + static fromProto(proto) { + return new GeoPoint(proto.latitude || 0, proto.longitude || 0); + } +} +exports.GeoPoint = GeoPoint; +//# sourceMappingURL=geo-point.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/index.d.ts b/node_modules/@google-cloud/firestore/build/src/index.d.ts new file mode 100644 index 0000000..726a994 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/index.d.ts @@ -0,0 +1,990 @@ +/*! + * Copyright 2017 Google Inc. 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. + */ +import * as firestore from '@google-cloud/firestore'; +import { Duplex } from 'stream'; +import { google } from '../protos/firestore_v1_proto_api'; +import { BulkWriter } from './bulk-writer'; +import { BundleBuilder } from './bundle'; +import { DocumentSnapshot, QueryDocumentSnapshot } from './document'; +import { CollectionReference } from './reference/collection-reference'; +import { DocumentReference } from './reference/document-reference'; +import { Serializer } from './serializer'; +import { Transaction } from './transaction'; +import { FirestoreStreamingMethod, FirestoreUnaryMethod } from './types'; +import { WriteBatch } from './write-batch'; +import api = google.firestore.v1; +import { CollectionGroup } from './collection-group'; +import { TraceUtil } from './telemetry/trace-util'; +export { CollectionReference } from './reference/collection-reference'; +export { DocumentReference } from './reference/document-reference'; +export { QuerySnapshot } from './reference/query-snapshot'; +export { Query } from './reference/query'; +export type { AggregateQuery } from './reference/aggregate-query'; +export type { AggregateQuerySnapshot } from './reference/aggregate-query-snapshot'; +export type { VectorQuery } from './reference/vector-query'; +export type { VectorQuerySnapshot } from './reference/vector-query-snapshot'; +export type { VectorQueryOptions } from './reference/vector-query-options'; +export { BulkWriter } from './bulk-writer'; +export type { BulkWriterError } from './bulk-writer'; +export type { BundleBuilder } from './bundle'; +export { DocumentSnapshot, QueryDocumentSnapshot } from './document'; +export { FieldValue, VectorValue } from './field-value'; +export { Filter } from './filter'; +export { WriteBatch, WriteResult } from './write-batch'; +export { Transaction } from './transaction'; +export { Timestamp } from './timestamp'; +export { DocumentChange } from './document-change'; +export type { DocumentChangeType } from './document-change'; +export { FieldPath } from './path'; +export { GeoPoint } from './geo-point'; +export { CollectionGroup }; +export { QueryPartition } from './query-partition'; +export { setLogFunction } from './logger'; +export { Aggregate, AggregateField } from './aggregate'; +export type { AggregateFieldType, AggregateSpec, AggregateType, } from './aggregate'; +export type { PlanSummary, ExecutionStats, ExplainMetrics, ExplainResults, } from './query-profile'; +/** + * The maximum number of times to retry idempotent requests. + * @private + */ +export declare const MAX_REQUEST_RETRIES = 5; +/** + * The maximum number of times to attempt a transaction before failing. + * @private + */ +export declare const DEFAULT_MAX_TRANSACTION_ATTEMPTS = 5; +/*! + * The default number of idle GRPC channel to keep. + */ +export declare const DEFAULT_MAX_IDLE_CHANNELS = 1; +/** + * Document data (e.g. for use with + * [set()]{@link DocumentReference#set}) consisting of fields mapped + * to values. + * + * @typedef {Object.} DocumentData + */ +/** + * Converter used by [withConverter()]{@link Query#withConverter} to transform + * user objects of type `AppModelType` into Firestore data of type + * `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when storing + * and retrieving objects from Firestore. + * + * @example + * ``` + * class Post { + * constructor(readonly title: string, readonly author: string) {} + * + * toString(): string { + * return this.title + ', by ' + this.author; + * } + * } + * + * const postConverter = { + * toFirestore(post: Post): FirebaseFirestore.DocumentData { + * return {title: post.title, author: post.author}; + * }, + * fromFirestore( + * snapshot: FirebaseFirestore.QueryDocumentSnapshot + * ): Post { + * const data = snapshot.data(); + * return new Post(data.title, data.author); + * } + * }; + * + * const postSnap = await Firestore() + * .collection('posts') + * .withConverter(postConverter) + * .doc().get(); + * const post = postSnap.data(); + * if (post !== undefined) { + * post.title; // string + * post.toString(); // Should be defined + * post.someNonExistentProperty; // TS error + * } + * + * ``` + * @property {Function} toFirestore Called by the Firestore SDK to convert a + * custom model object of type `AppModelType` into a plain Javascript object + * (suitable for writing directly to the Firestore database). + * @property {Function} fromFirestore Called by the Firestore SDK to convert + * Firestore data into an object of type `AppModelType`. + * @typedef {Object} FirestoreDataConverter + */ +/** + * Update data (for use with [update]{@link DocumentReference#update}) + * that contains paths mapped to values. Fields that contain dots + * reference nested fields within the document. + * + * You can update a top-level field in your document by using the field name + * as a key (e.g. `foo`). The provided value completely replaces the contents + * for this field. + * + * You can also update a nested field directly by using its field path as a key + * (e.g. `foo.bar`). This nested field update replaces the contents at `bar` + * but does not modify other data under `foo`. + * + * @example + * ``` + * const documentRef = firestore.doc('coll/doc'); + * documentRef.set({a1: {a2: 'val'}, b1: {b2: 'val'}, c1: {c2: 'val'}}); + * documentRef.update({ + * b1: {b3: 'val'}, + * 'c1.c3': 'val', + * }); + * // Value is {a1: {a2: 'val'}, b1: {b3: 'val'}, c1: {c2: 'val', c3: 'val'}} + * + * ``` + * @typedef {Object.} UpdateData + */ +/** + * An options object that configures conditional behavior of + * [update()]{@link DocumentReference#update} and + * [delete()]{@link DocumentReference#delete} calls in + * [DocumentReference]{@link DocumentReference}, + * [WriteBatch]{@link WriteBatch}, [BulkWriter]{@link BulkWriter}, and + * [Transaction]{@link Transaction}. Using Preconditions, these calls + * can be restricted to only apply to documents that match the specified + * conditions. + * + * @example + * ``` + * const documentRef = firestore.doc('coll/doc'); + * + * documentRef.get().then(snapshot => { + * const updateTime = snapshot.updateTime; + * + * console.log(`Deleting document at update time: ${updateTime.toDate()}`); + * return documentRef.delete({ lastUpdateTime: updateTime }); + * }); + * + * ``` + * @property {Timestamp} lastUpdateTime The update time to enforce. If set, + * enforces that the document was last updated at lastUpdateTime. Fails the + * operation if the document was last updated at a different time. + * @property {boolean} exists If set, enforces that the target document must + * or must not exist. + * @typedef {Object} Precondition + */ +/** + * An options object that configures the behavior of + * [set()]{@link DocumentReference#set} calls in + * [DocumentReference]{@link DocumentReference}, + * [WriteBatch]{@link WriteBatch}, and + * [Transaction]{@link Transaction}. These calls can be + * configured to perform granular merges instead of overwriting the target + * documents in their entirety by providing a SetOptions object with + * { merge : true }. + * + * @property {boolean} merge Changes the behavior of a set() call to only + * replace the values specified in its data argument. Fields omitted from the + * set() call remain untouched. + * @property {Array<(string|FieldPath)>} mergeFields Changes the behavior of + * set() calls to only replace the specified field paths. Any field path that is + * not specified is ignored and remains untouched. + * It is an error to pass a SetOptions object to a set() call that is missing a + * value for any of the fields specified here. + * @typedef {Object} SetOptions + */ +/** + * An options object that can be used to configure the behavior of + * [getAll()]{@link Firestore#getAll} calls. By providing a `fieldMask`, these + * calls can be configured to only return a subset of fields. + * + * @property {Array<(string|FieldPath)>} fieldMask Specifies the set of fields + * to return and reduces the amount of data transmitted by the backend. + * Adding a field mask does not filter results. Documents do not need to + * contain values for all the fields in the mask to be part of the result set. + * @typedef {Object} ReadOptions + */ +/** + * An options object to configure throttling on BulkWriter. + * + * Whether to disable or configure throttling. By default, throttling is + * enabled. `throttling` can be set to either a boolean or a config object. + * Setting it to `true` will use default values. You can override the defaults + * by setting it to `false` to disable throttling, or by setting the config + * values to enable throttling with the provided values. + * + * @property {boolean|Object} throttling Whether to disable or enable + * throttling. Throttling is enabled by default, if the field is set to `true` + * or if any custom throttling options are provided. `{ initialOpsPerSecond: + * number }` sets the initial maximum number of operations per second allowed by + * the throttler. If `initialOpsPerSecond` is not set, the default is 500 + * operations per second. `{ maxOpsPerSecond: number }` sets the maximum number + * of operations per second allowed by the throttler. If `maxOpsPerSecond` is + * not set, no maximum is enforced. + * @typedef {Object} BulkWriterOptions + */ +/** + * An error thrown when a BulkWriter operation fails. + * + * The error used by {@link BulkWriter~shouldRetryCallback} set in + * {@link BulkWriter#onWriteError}. + * + * @property {GrpcStatus} code The status code of the error. + * @property {string} message The error message of the error. + * @property {DocumentReference} documentRef The document reference the + * operation was performed on. + * @property {'create' | 'set' | 'update' | 'delete'} operationType The type + * of operation performed. + * @property {number} failedAttempts How many times this operation has been + * attempted unsuccessfully. + * @typedef {Error} BulkWriterError + */ +/** + * Status codes returned by GRPC operations. + * + * @see https://github.com/grpc/grpc/blob/master/doc/statuscodes.md + * + * @enum {number} + * @typedef {Object} GrpcStatus + */ +/** + * The Firestore client represents a Firestore Database and is the entry point + * for all Firestore operations. + * + * @see [Firestore Documentation]{@link https://firebase.google.com/docs/firestore/} + * + * @class + * + * @example Install the client library with npm: + * ``` + * npm install --save @google-cloud/firestore + * + * ``` + * @example Import the client library + * ``` + * var Firestore = require('@google-cloud/firestore'); + * + * ``` + * @example Create a client that uses Application Default Credentials (ADC): + * ``` + * var firestore = new Firestore(); + * + * ``` + * @example Create a client with explicit credentials: + * ``` + * var firestore = new Firestore({ projectId: + * 'your-project-id', keyFilename: '/path/to/keyfile.json' + * }); + * + * ``` + * @example include:samples/quickstart.js + * region_tag:firestore_quickstart + * Full quickstart example: + */ +export declare class Firestore implements firestore.Firestore { + /** + * A client pool to distribute requests over multiple GAPIC clients in order + * to work around a connection limit of 100 concurrent requests per client. + * @private + * @internal + */ + private _clientPool; + /** + * Preloaded instance of google-gax (full module, with gRPC support). + */ + private _gax?; + /** + * Preloaded instance of google-gax HTTP fallback implementation (no gRPC). + */ + private _gaxFallback?; + /** + * The configuration options for the GAPIC client. + * @private + * @internal + */ + _settings: firestore.Settings; + /** + * Settings for the exponential backoff used by the streaming endpoints. + * @private + * @internal + */ + private _backoffSettings; + /** + * Whether the initialization settings can still be changed by invoking + * `settings()`. + * @private + * @internal + */ + private _settingsFrozen; + /** + * The serializer to use for the Protobuf transformation. + * @private + * @internal + */ + _serializer: Serializer | null; + /** + * The OpenTelemetry tracing utility object. + * @private + * @internal + */ + _traceUtil: TraceUtil; + /** + * The project ID for this client. + * + * The project ID is auto-detected during the first request unless a project + * ID is passed to the constructor (or provided via `.settings()`). + * @private + * @internal + */ + private _projectId; + /** + * The database ID provided via `.settings()`. + * + * @private + * @internal + */ + private _databaseId; + /** + * Count of listeners that have been registered on the client. + * + * The client can only be terminated when there are no pending writes or + * registered listeners. + * @private + * @internal + */ + private registeredListenersCount; + /** + * A lazy-loaded BulkWriter instance to be used with recursiveDelete() if no + * BulkWriter instance is provided. + * + * @private + * @internal + */ + private _bulkWriter; + /** + * Lazy-load the Firestore's default BulkWriter. + * + * @private + * @internal + */ + private getBulkWriter; + /** + * Number of pending operations on the client. + * + * The client can only be terminated when there are no pending writes or + * registered listeners. + * @private + * @internal + */ + private bulkWritersCount; + /** + * @param {Object=} settings [Configuration object](#/docs). + * @param {string=} settings.projectId The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check the + * environment variable GCLOUD_PROJECT for your project ID. Can be omitted in + * environments that support + * {@link https://cloud.google.com/docs/authentication Application Default + * Credentials} + * @param {string=} settings.keyFilename Local file containing the Service + * Account credentials as downloaded from the Google Developers Console. Can + * be omitted in environments that support + * {@link https://cloud.google.com/docs/authentication Application Default + * Credentials}. To configure Firestore with custom credentials, use + * `settings.credentials` and provide the `client_email` and `private_key` of + * your service account. + * @param {{client_email:string=, private_key:string=}=} settings.credentials + * The `client_email` and `private_key` properties of the service account + * to use with your Firestore project. Can be omitted in environments that + * support {@link https://cloud.google.com/docs/authentication Application + * Default Credentials}. If your credentials are stored in a JSON file, you + * can specify a `keyFilename` instead. + * @param {string=} settings.host The host to connect to. + * @param {boolean=} settings.ssl Whether to use SSL when connecting. + * @param {number=} settings.maxIdleChannels The maximum number of idle GRPC + * channels to keep. A smaller number of idle channels reduces memory usage + * but increases request latency for clients with fluctuating request rates. + * If set to 0, shuts down all GRPC channels when the client becomes idle. + * Defaults to 1. + * @param {boolean=} settings.ignoreUndefinedProperties Whether to skip nested + * properties that are set to `undefined` during object serialization. If set + * to `true`, these properties are skipped and not written to Firestore. If + * set `false` or omitted, the SDK throws an exception when it encounters + * properties of type `undefined`. + * @param {boolean=} settings.preferRest Whether to force the use of HTTP/1.1 REST + * transport until a method that requires gRPC is called. When a method requires gRPC, + * this Firestore client will load dependent gRPC libraries and then use gRPC transport + * for communication from that point forward. Currently the only operation + * that requires gRPC is creating a snapshot listener with the method + * `DocumentReference.onSnapshot()`, `CollectionReference.onSnapshot()`, or + * `Query.onSnapshot()`. If specified, this setting value will take precedent over the + * environment variable `FIRESTORE_PREFER_REST`. If not specified, the + * SDK will use the value specified in the environment variable `FIRESTORE_PREFER_REST`. + * Valid values of `FIRESTORE_PREFER_REST` are `true` ('1') or `false` (`0`). Values are + * not case-sensitive. Any other value for the environment variable will be ignored and + * a warning will be logged to the console. + */ + constructor(settings?: firestore.Settings); + /** + * Specifies custom settings to be used to configure the `Firestore` + * instance. Can only be invoked once and before any other Firestore method. + * + * If settings are provided via both `settings()` and the `Firestore` + * constructor, both settings objects are merged and any settings provided via + * `settings()` take precedence. + * + * @param {object} settings The settings to use for all Firestore operations. + */ + settings(settings: firestore.Settings): void; + private validateAndApplySettings; + private newTraceUtilInstance; + /** + * Returns the Project ID for this Firestore instance. Validates that + * `initializeIfNeeded()` was called before. + * + * @private + * @internal + */ + get projectId(): string; + /** + * Returns the Database ID for this Firestore instance. + */ + get databaseId(): string; + /** + * Returns the root path of the database. Validates that + * `initializeIfNeeded()` was called before. + * + * @private + * @internal + */ + get formattedName(): string; + /** + * Gets a [DocumentReference]{@link DocumentReference} instance that + * refers to the document at the specified path. + * + * @param {string} documentPath A slash-separated path to a document. + * @returns {DocumentReference} The + * [DocumentReference]{@link DocumentReference} instance. + * + * @example + * ``` + * let documentRef = firestore.doc('collection/document'); + * console.log(`Path of document is ${documentRef.path}`); + * ``` + */ + doc(documentPath: string): DocumentReference; + /** + * Gets a [CollectionReference]{@link CollectionReference} instance + * that refers to the collection at the specified path. + * + * @param {string} collectionPath A slash-separated path to a collection. + * @returns {CollectionReference} The + * [CollectionReference]{@link CollectionReference} instance. + * + * @example + * ``` + * let collectionRef = firestore.collection('collection'); + * + * // Add a document with an auto-generated ID. + * collectionRef.add({foo: 'bar'}).then((documentRef) => { + * console.log(`Added document at ${documentRef.path})`); + * }); + * ``` + */ + collection(collectionPath: string): CollectionReference; + /** + * Creates and returns a new Query that includes all documents in the + * database that are contained in a collection or subcollection with the + * given collectionId. + * + * @param {string} collectionId Identifies the collections to query over. + * Every collection or subcollection with this ID as the last segment of its + * path will be included. Cannot contain a slash. + * @returns {CollectionGroup} The created CollectionGroup. + * + * @example + * ``` + * let docA = firestore.doc('mygroup/docA').set({foo: 'bar'}); + * let docB = firestore.doc('abc/def/mygroup/docB').set({foo: 'bar'}); + * + * Promise.all([docA, docB]).then(() => { + * let query = firestore.collectionGroup('mygroup'); + * query = query.where('foo', '==', 'bar'); + * return query.get().then(snapshot => { + * console.log(`Found ${snapshot.size} documents.`); + * }); + * }); + * ``` + */ + collectionGroup(collectionId: string): CollectionGroup; + /** + * Creates a [WriteBatch]{@link WriteBatch}, used for performing + * multiple writes as a single atomic operation. + * + * @returns {WriteBatch} A WriteBatch that operates on this Firestore + * client. + * + * @example + * ``` + * let writeBatch = firestore.batch(); + * + * // Add two documents in an atomic batch. + * let data = { foo: 'bar' }; + * writeBatch.set(firestore.doc('col/doc1'), data); + * writeBatch.set(firestore.doc('col/doc2'), data); + * + * writeBatch.commit().then(res => { + * console.log('Successfully executed batch.'); + * }); + * ``` + */ + batch(): WriteBatch; + /** + * Creates a [BulkWriter]{@link BulkWriter}, used for performing + * multiple writes in parallel. Gradually ramps up writes as specified + * by the 500/50/5 rule. + * + * If you pass [BulkWriterOptions]{@link BulkWriterOptions}, you can + * configure the throttling rates for the created BulkWriter. + * + * @see [500/50/5 Documentation]{@link https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic} + * + * @param {BulkWriterOptions=} options BulkWriter options. + * @returns {BulkWriter} A BulkWriter that operates on this Firestore + * client. + * + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * + * bulkWriter.create(firestore.doc('col/doc1'), {foo: 'bar'}) + * .then(res => { + * console.log(`Added document at ${res.writeTime}`); + * }); + * bulkWriter.update(firestore.doc('col/doc2'), {foo: 'bar'}) + * .then(res => { + * console.log(`Updated document at ${res.writeTime}`); + * }); + * bulkWriter.delete(firestore.doc('col/doc3')) + * .then(res => { + * console.log(`Deleted document at ${res.writeTime}`); + * }); + * await bulkWriter.close().then(() => { + * console.log('Executed all writes'); + * }); + * ``` + */ + bulkWriter(options?: firestore.BulkWriterOptions): BulkWriter; + /** + * Creates a [DocumentSnapshot]{@link DocumentSnapshot} or a + * [QueryDocumentSnapshot]{@link QueryDocumentSnapshot} from a + * `firestore.v1.Document` proto (or from a resource name for missing + * documents). + * + * This API is used by Google Cloud Functions and can be called with both + * 'Proto3 JSON' and 'Protobuf JS' encoded data. + * + * @private + * @param documentOrName The Firestore 'Document' proto or the resource name + * of a missing document. + * @param readTime A 'Timestamp' proto indicating the time this document was + * read. + * @param encoding One of 'json' or 'protobufJS'. Applies to both the + * 'document' Proto and 'readTime'. Defaults to 'protobufJS'. + * @returns A QueryDocumentSnapshot for existing documents, otherwise a + * DocumentSnapshot. + */ + snapshot_(documentName: string, readTime?: google.protobuf.ITimestamp, encoding?: 'protobufJS'): DocumentSnapshot; + /** @private */ + snapshot_(documentName: string, readTime: string, encoding: 'json'): DocumentSnapshot; + /** @private */ + snapshot_(document: api.IDocument, readTime: google.protobuf.ITimestamp, encoding?: 'protobufJS'): QueryDocumentSnapshot; + /** @private */ + snapshot_(document: { + [k: string]: unknown; + }, readTime: string, encoding: 'json'): QueryDocumentSnapshot; + /** + * Creates a new `BundleBuilder` instance to package selected Firestore data into + * a bundle. + * + * @param bundleId. The id of the bundle. When loaded on clients, client SDKs use this id + * and the timestamp associated with the built bundle to tell if it has been loaded already. + * If not specified, a random identifier will be used. + */ + bundle(name?: string): BundleBuilder; + /** + * Function executed by {@link Firestore#runTransaction} within the transaction + * context. + * + * @callback Firestore~updateFunction + * @template T + * @param {Transaction} transaction The transaction object for this + * transaction. + * @returns {Promise} The promise returned at the end of the transaction. + * This promise will be returned by {@link Firestore#runTransaction} if the + * transaction completed successfully. + */ + /** + * Options object for {@link Firestore#runTransaction} to configure a + * read-only transaction. + * + * @param {true} readOnly Set to true to indicate a read-only transaction. + * @param {Timestamp=} readTime If specified, documents are read at the given + * time. This may not be more than 60 seconds in the past from when the + * request is processed by the server. + * @typedef {Object} Firestore~ReadOnlyTransactionOptions + */ + /** + * Options object for {@link Firestore#runTransaction} to configure a + * read-write transaction. + * + * @param {false=} readOnly Set to false or omit to indicate a read-write + * transaction. + * @param {number=} maxAttempts The maximum number of attempts for this + * transaction. Defaults to 5. + * @typedef {Object} Firestore~ReadWriteTransactionOptions + */ + /** + * Executes the given updateFunction and commits the changes applied within + * the transaction. + * + * You can use the transaction object passed to 'updateFunction' to read and + * modify Firestore documents under lock. You have to perform all reads before + * before you perform any write. + * + * Transactions can be performed as read-only or read-write transactions. By + * default, transactions are executed in read-write mode. + * + * A read-write transaction obtains a pessimistic lock on all documents that + * are read during the transaction. These locks block other transactions, + * batched writes, and other non-transactional writes from changing that + * document. Any writes in a read-write transactions are committed once + * 'updateFunction' resolves, which also releases all locks. + * + * If a read-write transaction fails with contention, the transaction is + * retried up to five times. The `updateFunction` is invoked once for each + * attempt. + * + * Read-only transactions do not lock documents. They can be used to read + * documents at a consistent snapshot in time, which may be up to 60 seconds + * in the past. Read-only transactions are not retried. + * + * Transactions time out after 60 seconds if no documents are read. + * Transactions that are not committed within than 270 seconds are also + * aborted. Any remaining locks are released when a transaction times out. + * + * @template T + * @param {Firestore~updateFunction} updateFunction The user function to + * execute within the transaction context. + * @param { + * Firestore~ReadWriteTransactionOptions|Firestore~ReadOnlyTransactionOptions= + * } transactionOptions Transaction options. + * @returns {Promise} If the transaction completed successfully or was + * explicitly aborted (by the updateFunction returning a failed Promise), the + * Promise returned by the updateFunction will be returned here. Else if the + * transaction failed, a rejected Promise with the corresponding failure + * error will be returned. + * + * @example + * ``` + * let counterTransaction = firestore.runTransaction(transaction => { + * let documentRef = firestore.doc('col/doc'); + * return transaction.get(documentRef).then(doc => { + * if (doc.exists) { + * let count = doc.get('count') || 0; + * if (count > 10) { + * return Promise.reject('Reached maximum count'); + * } + * transaction.update(documentRef, { count: ++count }); + * return Promise.resolve(count); + * } + * + * transaction.create(documentRef, { count: 1 }); + * return Promise.resolve(1); + * }); + * }); + * + * counterTransaction.then(res => { + * console.log(`Count updated to ${res}`); + * }); + * ``` + */ + runTransaction(updateFunction: (transaction: Transaction) => Promise, transactionOptions?: firestore.ReadWriteTransactionOptions | firestore.ReadOnlyTransactionOptions): Promise; + /** + * Fetches the root collections that are associated with this Firestore + * database. + * + * @returns {Promise.>} A Promise that resolves + * with an array of CollectionReferences. + * + * @example + * ``` + * firestore.listCollections().then(collections => { + * for (let collection of collections) { + * console.log(`Found collection with id: ${collection.id}`); + * } + * }); + * ``` + */ + listCollections(): Promise; + /** + * Retrieves multiple documents from Firestore. + * + * The first argument is required and must be of type `DocumentReference` + * followed by any additional `DocumentReference` documents. If used, the + * optional `ReadOptions` must be the last argument. + * + * @param {...DocumentReference|ReadOptions} documentRefsOrReadOptions The + * `DocumentReferences` to receive, followed by an optional field mask. + * @returns {Promise>} A Promise that + * contains an array with the resulting document snapshots. + * + * @example + * ``` + * let docRef1 = firestore.doc('col/doc1'); + * let docRef2 = firestore.doc('col/doc2'); + * + * firestore.getAll(docRef1, docRef2, { fieldMask: ['user'] }).then(docs => { + * console.log(`First document: ${JSON.stringify(docs[0])}`); + * console.log(`Second document: ${JSON.stringify(docs[1])}`); + * }); + * ``` + */ + getAll(...documentRefsOrReadOptions: Array | firestore.ReadOptions>): Promise>>; + /** + * Registers a listener on this client, incrementing the listener count. This + * is used to verify that all listeners are unsubscribed when terminate() is + * called. + * + * @private + * @internal + */ + registerListener(): void; + /** + * Unregisters a listener on this client, decrementing the listener count. + * This is used to verify that all listeners are unsubscribed when terminate() + * is called. + * + * @private + * @internal + */ + unregisterListener(): void; + /** + * Increments the number of open BulkWriter instances. This is used to verify + * that all pending operations are complete when terminate() is called. + * + * @private + * @internal + */ + _incrementBulkWritersCount(): void; + /** + * Decrements the number of open BulkWriter instances. This is used to verify + * that all pending operations are complete when terminate() is called. + * + * @private + * @internal + */ + _decrementBulkWritersCount(): void; + /** + * Recursively deletes all documents and subcollections at and under the + * specified level. + * + * If any delete fails, the promise is rejected with an error message + * containing the number of failed deletes and the stack trace of the last + * failed delete. The provided reference is deleted regardless of whether + * all deletes succeeded. + * + * `recursiveDelete()` uses a BulkWriter instance with default settings to + * perform the deletes. To customize throttling rates or add success/error + * callbacks, pass in a custom BulkWriter instance. + * + * @param ref The reference of a document or collection to delete. + * @param bulkWriter A custom BulkWriter instance used to perform the + * deletes. + * @return A promise that resolves when all deletes have been performed. + * The promise is rejected if any of the deletes fail. + * + * @example + * ``` + * // Recursively delete a reference and log the references of failures. + * const bulkWriter = firestore.bulkWriter(); + * bulkWriter + * .onWriteError((error) => { + * if ( + * error.failedAttempts < MAX_RETRY_ATTEMPTS + * ) { + * return true; + * } else { + * console.log('Failed write at document: ', error.documentRef.path); + * return false; + * } + * }); + * await firestore.recursiveDelete(docRef, bulkWriter); + * ``` + */ + recursiveDelete(ref: firestore.CollectionReference | firestore.DocumentReference, bulkWriter?: BulkWriter): Promise; + /** + * This overload is not private in order to test the query resumption with + * startAfter() once the RecursiveDelete instance has MAX_PENDING_OPS pending. + * + * @private + * @internal + */ + _recursiveDelete(ref: firestore.CollectionReference | firestore.DocumentReference, maxPendingOps: number, minPendingOps: number, bulkWriter?: BulkWriter): Promise; + /** + * Terminates the Firestore client and closes all open streams. + * + * @return A Promise that resolves when the client is terminated. + */ + terminate(): Promise; + /** + * Returns the Project ID to serve as the JSON representation of this + * Firestore instance. + * + * @return An object that contains the project ID (or `undefined` if not yet + * available). + */ + toJSON(): object; + /** + * Initializes the client if it is not already initialized. All methods in the + * SDK can be used after this method completes. + * + * @private + * @internal + * @param requestTag A unique client-assigned identifier that caused this + * initialization. + * @return A Promise that resolves when the client is initialized. + */ + initializeIfNeeded(requestTag: string): Promise; + /** + * Returns GAX call options that set the cloud resource header. + * @private + * @internal + */ + private createCallOptions; + /** + * A function returning a Promise that can be retried. + * + * @private + * @internal + * @callback retryFunction + * @returns {Promise} A Promise indicating the function's success. + */ + /** + * Helper method that retries failed Promises. + * + * If 'delayMs' is specified, waits 'delayMs' between invocations. Otherwise, + * schedules the first attempt immediately, and then waits 100 milliseconds + * for further attempts. + * + * @private + * @internal + * @param methodName Name of the Veneer API endpoint that takes a request + * and GAX options. + * @param requestTag A unique client-assigned identifier for this request. + * @param func Method returning a Promise than can be retried. + * @returns A Promise with the function's result if successful within + * `attemptsRemaining`. Otherwise, returns the last rejected Promise. + */ + private _retry; + /** + * Waits for the provided stream to become active and returns a paused but + * healthy stream. If an error occurs before the first byte is read, the + * method rejects the returned Promise. + * + * @private + * @internal + * @param backendStream The Node stream to monitor. + * @param lifetime A Promise that resolves when the stream receives an 'end', + * 'close' or 'finish' message. + * @param requestTag A unique client-assigned identifier for this request. + * @param request If specified, the request that should be written to the + * stream after opening. + * @returns A guaranteed healthy stream that should be used instead of + * `backendStream`. + */ + private _initializeStream; + /** + * A funnel for all non-streaming API requests, assigning a project ID where + * necessary within the request options. + * + * @private + * @internal + * @param methodName Name of the Veneer API endpoint that takes a request + * and GAX options. + * @param request The Protobuf request to send. + * @param requestTag A unique client-assigned identifier for this request. + * @param retryCodes If provided, a custom list of retry codes. If not + * provided, retry is based on the behavior as defined in the ServiceConfig. + * @returns A Promise with the request result. + */ + request(methodName: FirestoreUnaryMethod, request: Req, requestTag: string, retryCodes?: number[]): Promise; + /** + * A funnel for streaming API requests, assigning a project ID where necessary + * within the request options. + * + * The stream is returned in paused state and needs to be resumed once all + * listeners are attached. + * + * @private + * @internal + * @param methodName Name of the streaming Veneer API endpoint that + * takes a request and GAX options. + * @param bidrectional Whether the request is bidirectional (true) or + * unidirectional (false_ + * @param request The Protobuf request to send. + * @param requestTag A unique client-assigned identifier for this request. + * @returns A Promise with the resulting read-only stream. + */ + requestStream(methodName: FirestoreStreamingMethod, bidrectional: boolean, request: {}, requestTag: string): Promise; +} +/** + * A logging function that takes a single string. + * + * @callback Firestore~logFunction + * @param {string} Log message + */ +/** + * The default export of the `@google-cloud/firestore` package is the + * {@link Firestore} class. + * + * See {@link Firestore} and {@link ClientConfig} for client methods and + * configuration options. + * + * @module {Firestore} @google-cloud/firestore + * @alias nodejs-firestore + * + * @example Install the client library with npm: + * ``` + * npm install --save @google-cloud/firestore + * + * ``` + * @example Import the client library + * ``` + * var Firestore = require('@google-cloud/firestore'); + * + * ``` + * @example Create a client that uses Application Default Credentials (ADC): + * ``` + * var firestore = new Firestore(); + * + * ``` + * @example Create a client with explicit credentials: + * ``` + * var firestore = new Firestore({ projectId: + * 'your-project-id', keyFilename: '/path/to/keyfile.json' + * }); + * + * ``` + * @example include:samples/quickstart.js + * region_tag:firestore_quickstart + * Full quickstart example: + */ +export default Firestore; diff --git a/node_modules/@google-cloud/firestore/build/src/index.js b/node_modules/@google-cloud/firestore/build/src/index.js new file mode 100644 index 0000000..71998cc --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/index.js @@ -0,0 +1,1555 @@ +"use strict"; +/*! + * Copyright 2017 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Firestore = exports.DEFAULT_MAX_IDLE_CHANNELS = exports.DEFAULT_MAX_TRANSACTION_ATTEMPTS = exports.MAX_REQUEST_RETRIES = exports.AggregateField = exports.Aggregate = exports.setLogFunction = exports.QueryPartition = exports.CollectionGroup = exports.GeoPoint = exports.FieldPath = exports.DocumentChange = exports.Timestamp = exports.Transaction = exports.WriteResult = exports.WriteBatch = exports.Filter = exports.VectorValue = exports.FieldValue = exports.QueryDocumentSnapshot = exports.DocumentSnapshot = exports.BulkWriter = exports.Query = exports.QuerySnapshot = exports.DocumentReference = exports.CollectionReference = void 0; +const stream_1 = require("stream"); +const url_1 = require("url"); +const backoff_1 = require("./backoff"); +const bulk_writer_1 = require("./bulk-writer"); +const bundle_1 = require("./bundle"); +const convert_1 = require("./convert"); +const document_reader_1 = require("./document-reader"); +const document_1 = require("./document"); +const logger_1 = require("./logger"); +const path_1 = require("./path"); +const pool_1 = require("./pool"); +const collection_reference_1 = require("./reference/collection-reference"); +const document_reference_1 = require("./reference/document-reference"); +const serializer_1 = require("./serializer"); +const timestamp_1 = require("./timestamp"); +const transaction_1 = require("./transaction"); +const util_1 = require("./util"); +const validate_1 = require("./validate"); +const write_batch_1 = require("./write-batch"); +const firestore_client_config_json_1 = require("./v1/firestore_client_config.json"); +const serviceConfig = firestore_client_config_json_1.interfaces['google.firestore.v1.Firestore']; +const collection_group_1 = require("./collection-group"); +Object.defineProperty(exports, "CollectionGroup", { enumerable: true, get: function () { return collection_group_1.CollectionGroup; } }); +const recursive_delete_1 = require("./recursive-delete"); +const trace_util_1 = require("./telemetry/trace-util"); +const disabled_trace_util_1 = require("./telemetry/disabled-trace-util"); +const enabled_trace_util_1 = require("./telemetry/enabled-trace-util"); +var collection_reference_2 = require("./reference/collection-reference"); +Object.defineProperty(exports, "CollectionReference", { enumerable: true, get: function () { return collection_reference_2.CollectionReference; } }); +var document_reference_2 = require("./reference/document-reference"); +Object.defineProperty(exports, "DocumentReference", { enumerable: true, get: function () { return document_reference_2.DocumentReference; } }); +var query_snapshot_1 = require("./reference/query-snapshot"); +Object.defineProperty(exports, "QuerySnapshot", { enumerable: true, get: function () { return query_snapshot_1.QuerySnapshot; } }); +var query_1 = require("./reference/query"); +Object.defineProperty(exports, "Query", { enumerable: true, get: function () { return query_1.Query; } }); +var bulk_writer_2 = require("./bulk-writer"); +Object.defineProperty(exports, "BulkWriter", { enumerable: true, get: function () { return bulk_writer_2.BulkWriter; } }); +var document_2 = require("./document"); +Object.defineProperty(exports, "DocumentSnapshot", { enumerable: true, get: function () { return document_2.DocumentSnapshot; } }); +Object.defineProperty(exports, "QueryDocumentSnapshot", { enumerable: true, get: function () { return document_2.QueryDocumentSnapshot; } }); +var field_value_1 = require("./field-value"); +Object.defineProperty(exports, "FieldValue", { enumerable: true, get: function () { return field_value_1.FieldValue; } }); +Object.defineProperty(exports, "VectorValue", { enumerable: true, get: function () { return field_value_1.VectorValue; } }); +var filter_1 = require("./filter"); +Object.defineProperty(exports, "Filter", { enumerable: true, get: function () { return filter_1.Filter; } }); +var write_batch_2 = require("./write-batch"); +Object.defineProperty(exports, "WriteBatch", { enumerable: true, get: function () { return write_batch_2.WriteBatch; } }); +Object.defineProperty(exports, "WriteResult", { enumerable: true, get: function () { return write_batch_2.WriteResult; } }); +var transaction_2 = require("./transaction"); +Object.defineProperty(exports, "Transaction", { enumerable: true, get: function () { return transaction_2.Transaction; } }); +var timestamp_2 = require("./timestamp"); +Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function () { return timestamp_2.Timestamp; } }); +var document_change_1 = require("./document-change"); +Object.defineProperty(exports, "DocumentChange", { enumerable: true, get: function () { return document_change_1.DocumentChange; } }); +var path_2 = require("./path"); +Object.defineProperty(exports, "FieldPath", { enumerable: true, get: function () { return path_2.FieldPath; } }); +var geo_point_1 = require("./geo-point"); +Object.defineProperty(exports, "GeoPoint", { enumerable: true, get: function () { return geo_point_1.GeoPoint; } }); +var query_partition_1 = require("./query-partition"); +Object.defineProperty(exports, "QueryPartition", { enumerable: true, get: function () { return query_partition_1.QueryPartition; } }); +var logger_2 = require("./logger"); +Object.defineProperty(exports, "setLogFunction", { enumerable: true, get: function () { return logger_2.setLogFunction; } }); +var aggregate_1 = require("./aggregate"); +Object.defineProperty(exports, "Aggregate", { enumerable: true, get: function () { return aggregate_1.Aggregate; } }); +Object.defineProperty(exports, "AggregateField", { enumerable: true, get: function () { return aggregate_1.AggregateField; } }); +const libVersion = require('../../package.json').version; +(0, logger_1.setLibVersion)(libVersion); +/*! + * DO NOT REMOVE THE FOLLOWING NAMESPACE DEFINITIONS + */ +/** + * @namespace google.protobuf + */ +/** + * @namespace google.rpc + */ +/** + * @namespace google.longrunning + */ +/** + * @namespace google.firestore.v1 + */ +/** + * @namespace google.firestore.v1beta1 + */ +/** + * @namespace google.firestore.admin.v1 + */ +/*! + * HTTP header for the resource prefix to improve routing and project isolation + * by the backend. + */ +const CLOUD_RESOURCE_HEADER = 'google-cloud-resource-prefix'; +/** + * The maximum number of times to retry idempotent requests. + * @private + */ +exports.MAX_REQUEST_RETRIES = 5; +/** + * The maximum number of times to attempt a transaction before failing. + * @private + */ +exports.DEFAULT_MAX_TRANSACTION_ATTEMPTS = 5; +/*! + * The default number of idle GRPC channel to keep. + */ +exports.DEFAULT_MAX_IDLE_CHANNELS = 1; +/*! + * The maximum number of concurrent requests supported by a single GRPC channel, + * as enforced by Google's Frontend. If the SDK issues more than 100 concurrent + * operations, we need to use more than one GAPIC client since these clients + * multiplex all requests over a single channel. + */ +const MAX_CONCURRENT_REQUESTS_PER_CLIENT = 100; +/** + * Document data (e.g. for use with + * [set()]{@link DocumentReference#set}) consisting of fields mapped + * to values. + * + * @typedef {Object.} DocumentData + */ +/** + * Converter used by [withConverter()]{@link Query#withConverter} to transform + * user objects of type `AppModelType` into Firestore data of type + * `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when storing + * and retrieving objects from Firestore. + * + * @example + * ``` + * class Post { + * constructor(readonly title: string, readonly author: string) {} + * + * toString(): string { + * return this.title + ', by ' + this.author; + * } + * } + * + * const postConverter = { + * toFirestore(post: Post): FirebaseFirestore.DocumentData { + * return {title: post.title, author: post.author}; + * }, + * fromFirestore( + * snapshot: FirebaseFirestore.QueryDocumentSnapshot + * ): Post { + * const data = snapshot.data(); + * return new Post(data.title, data.author); + * } + * }; + * + * const postSnap = await Firestore() + * .collection('posts') + * .withConverter(postConverter) + * .doc().get(); + * const post = postSnap.data(); + * if (post !== undefined) { + * post.title; // string + * post.toString(); // Should be defined + * post.someNonExistentProperty; // TS error + * } + * + * ``` + * @property {Function} toFirestore Called by the Firestore SDK to convert a + * custom model object of type `AppModelType` into a plain Javascript object + * (suitable for writing directly to the Firestore database). + * @property {Function} fromFirestore Called by the Firestore SDK to convert + * Firestore data into an object of type `AppModelType`. + * @typedef {Object} FirestoreDataConverter + */ +/** + * Update data (for use with [update]{@link DocumentReference#update}) + * that contains paths mapped to values. Fields that contain dots + * reference nested fields within the document. + * + * You can update a top-level field in your document by using the field name + * as a key (e.g. `foo`). The provided value completely replaces the contents + * for this field. + * + * You can also update a nested field directly by using its field path as a key + * (e.g. `foo.bar`). This nested field update replaces the contents at `bar` + * but does not modify other data under `foo`. + * + * @example + * ``` + * const documentRef = firestore.doc('coll/doc'); + * documentRef.set({a1: {a2: 'val'}, b1: {b2: 'val'}, c1: {c2: 'val'}}); + * documentRef.update({ + * b1: {b3: 'val'}, + * 'c1.c3': 'val', + * }); + * // Value is {a1: {a2: 'val'}, b1: {b3: 'val'}, c1: {c2: 'val', c3: 'val'}} + * + * ``` + * @typedef {Object.} UpdateData + */ +/** + * An options object that configures conditional behavior of + * [update()]{@link DocumentReference#update} and + * [delete()]{@link DocumentReference#delete} calls in + * [DocumentReference]{@link DocumentReference}, + * [WriteBatch]{@link WriteBatch}, [BulkWriter]{@link BulkWriter}, and + * [Transaction]{@link Transaction}. Using Preconditions, these calls + * can be restricted to only apply to documents that match the specified + * conditions. + * + * @example + * ``` + * const documentRef = firestore.doc('coll/doc'); + * + * documentRef.get().then(snapshot => { + * const updateTime = snapshot.updateTime; + * + * console.log(`Deleting document at update time: ${updateTime.toDate()}`); + * return documentRef.delete({ lastUpdateTime: updateTime }); + * }); + * + * ``` + * @property {Timestamp} lastUpdateTime The update time to enforce. If set, + * enforces that the document was last updated at lastUpdateTime. Fails the + * operation if the document was last updated at a different time. + * @property {boolean} exists If set, enforces that the target document must + * or must not exist. + * @typedef {Object} Precondition + */ +/** + * An options object that configures the behavior of + * [set()]{@link DocumentReference#set} calls in + * [DocumentReference]{@link DocumentReference}, + * [WriteBatch]{@link WriteBatch}, and + * [Transaction]{@link Transaction}. These calls can be + * configured to perform granular merges instead of overwriting the target + * documents in their entirety by providing a SetOptions object with + * { merge : true }. + * + * @property {boolean} merge Changes the behavior of a set() call to only + * replace the values specified in its data argument. Fields omitted from the + * set() call remain untouched. + * @property {Array<(string|FieldPath)>} mergeFields Changes the behavior of + * set() calls to only replace the specified field paths. Any field path that is + * not specified is ignored and remains untouched. + * It is an error to pass a SetOptions object to a set() call that is missing a + * value for any of the fields specified here. + * @typedef {Object} SetOptions + */ +/** + * An options object that can be used to configure the behavior of + * [getAll()]{@link Firestore#getAll} calls. By providing a `fieldMask`, these + * calls can be configured to only return a subset of fields. + * + * @property {Array<(string|FieldPath)>} fieldMask Specifies the set of fields + * to return and reduces the amount of data transmitted by the backend. + * Adding a field mask does not filter results. Documents do not need to + * contain values for all the fields in the mask to be part of the result set. + * @typedef {Object} ReadOptions + */ +/** + * An options object to configure throttling on BulkWriter. + * + * Whether to disable or configure throttling. By default, throttling is + * enabled. `throttling` can be set to either a boolean or a config object. + * Setting it to `true` will use default values. You can override the defaults + * by setting it to `false` to disable throttling, or by setting the config + * values to enable throttling with the provided values. + * + * @property {boolean|Object} throttling Whether to disable or enable + * throttling. Throttling is enabled by default, if the field is set to `true` + * or if any custom throttling options are provided. `{ initialOpsPerSecond: + * number }` sets the initial maximum number of operations per second allowed by + * the throttler. If `initialOpsPerSecond` is not set, the default is 500 + * operations per second. `{ maxOpsPerSecond: number }` sets the maximum number + * of operations per second allowed by the throttler. If `maxOpsPerSecond` is + * not set, no maximum is enforced. + * @typedef {Object} BulkWriterOptions + */ +/** + * An error thrown when a BulkWriter operation fails. + * + * The error used by {@link BulkWriter~shouldRetryCallback} set in + * {@link BulkWriter#onWriteError}. + * + * @property {GrpcStatus} code The status code of the error. + * @property {string} message The error message of the error. + * @property {DocumentReference} documentRef The document reference the + * operation was performed on. + * @property {'create' | 'set' | 'update' | 'delete'} operationType The type + * of operation performed. + * @property {number} failedAttempts How many times this operation has been + * attempted unsuccessfully. + * @typedef {Error} BulkWriterError + */ +/** + * Status codes returned by GRPC operations. + * + * @see https://github.com/grpc/grpc/blob/master/doc/statuscodes.md + * + * @enum {number} + * @typedef {Object} GrpcStatus + */ +/** + * The Firestore client represents a Firestore Database and is the entry point + * for all Firestore operations. + * + * @see [Firestore Documentation]{@link https://firebase.google.com/docs/firestore/} + * + * @class + * + * @example Install the client library with npm: + * ``` + * npm install --save @google-cloud/firestore + * + * ``` + * @example Import the client library + * ``` + * var Firestore = require('@google-cloud/firestore'); + * + * ``` + * @example Create a client that uses Application Default Credentials (ADC): + * ``` + * var firestore = new Firestore(); + * + * ``` + * @example Create a client with explicit credentials: + * ``` + * var firestore = new Firestore({ projectId: + * 'your-project-id', keyFilename: '/path/to/keyfile.json' + * }); + * + * ``` + * @example include:samples/quickstart.js + * region_tag:firestore_quickstart + * Full quickstart example: + */ +class Firestore { + /** + * Lazy-load the Firestore's default BulkWriter. + * + * @private + * @internal + */ + getBulkWriter() { + if (!this._bulkWriter) { + this._bulkWriter = this.bulkWriter(); + } + return this._bulkWriter; + } + /** + * @param {Object=} settings [Configuration object](#/docs). + * @param {string=} settings.projectId The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check the + * environment variable GCLOUD_PROJECT for your project ID. Can be omitted in + * environments that support + * {@link https://cloud.google.com/docs/authentication Application Default + * Credentials} + * @param {string=} settings.keyFilename Local file containing the Service + * Account credentials as downloaded from the Google Developers Console. Can + * be omitted in environments that support + * {@link https://cloud.google.com/docs/authentication Application Default + * Credentials}. To configure Firestore with custom credentials, use + * `settings.credentials` and provide the `client_email` and `private_key` of + * your service account. + * @param {{client_email:string=, private_key:string=}=} settings.credentials + * The `client_email` and `private_key` properties of the service account + * to use with your Firestore project. Can be omitted in environments that + * support {@link https://cloud.google.com/docs/authentication Application + * Default Credentials}. If your credentials are stored in a JSON file, you + * can specify a `keyFilename` instead. + * @param {string=} settings.host The host to connect to. + * @param {boolean=} settings.ssl Whether to use SSL when connecting. + * @param {number=} settings.maxIdleChannels The maximum number of idle GRPC + * channels to keep. A smaller number of idle channels reduces memory usage + * but increases request latency for clients with fluctuating request rates. + * If set to 0, shuts down all GRPC channels when the client becomes idle. + * Defaults to 1. + * @param {boolean=} settings.ignoreUndefinedProperties Whether to skip nested + * properties that are set to `undefined` during object serialization. If set + * to `true`, these properties are skipped and not written to Firestore. If + * set `false` or omitted, the SDK throws an exception when it encounters + * properties of type `undefined`. + * @param {boolean=} settings.preferRest Whether to force the use of HTTP/1.1 REST + * transport until a method that requires gRPC is called. When a method requires gRPC, + * this Firestore client will load dependent gRPC libraries and then use gRPC transport + * for communication from that point forward. Currently the only operation + * that requires gRPC is creating a snapshot listener with the method + * `DocumentReference.onSnapshot()`, `CollectionReference.onSnapshot()`, or + * `Query.onSnapshot()`. If specified, this setting value will take precedent over the + * environment variable `FIRESTORE_PREFER_REST`. If not specified, the + * SDK will use the value specified in the environment variable `FIRESTORE_PREFER_REST`. + * Valid values of `FIRESTORE_PREFER_REST` are `true` ('1') or `false` (`0`). Values are + * not case-sensitive. Any other value for the environment variable will be ignored and + * a warning will be logged to the console. + */ + constructor(settings) { + /** + * The configuration options for the GAPIC client. + * @private + * @internal + */ + this._settings = {}; + /** + * Whether the initialization settings can still be changed by invoking + * `settings()`. + * @private + * @internal + */ + this._settingsFrozen = false; + /** + * The serializer to use for the Protobuf transformation. + * @private + * @internal + */ + this._serializer = null; + /** + * The project ID for this client. + * + * The project ID is auto-detected during the first request unless a project + * ID is passed to the constructor (or provided via `.settings()`). + * @private + * @internal + */ + this._projectId = undefined; + /** + * The database ID provided via `.settings()`. + * + * @private + * @internal + */ + this._databaseId = undefined; + /** + * Count of listeners that have been registered on the client. + * + * The client can only be terminated when there are no pending writes or + * registered listeners. + * @private + * @internal + */ + this.registeredListenersCount = 0; + /** + * Number of pending operations on the client. + * + * The client can only be terminated when there are no pending writes or + * registered listeners. + * @private + * @internal + */ + this.bulkWritersCount = 0; + const libraryHeader = { + libName: 'gccl', + libVersion, + }; + if (settings && settings.firebaseVersion) { + libraryHeader.libVersion += ' fire/' + settings.firebaseVersion; + } + if (settings && settings.firebaseAdminVersion) { + libraryHeader.libVersion += + ' fire-admin/' + settings.firebaseAdminVersion; + } + this.validateAndApplySettings({ ...settings, ...libraryHeader }); + this._traceUtil = this.newTraceUtilInstance(this._settings); + const retryConfig = serviceConfig.retry_params.default; + this._backoffSettings = { + initialDelayMs: retryConfig.initial_retry_delay_millis, + maxDelayMs: retryConfig.max_retry_delay_millis, + backoffFactor: retryConfig.retry_delay_multiplier, + }; + const maxIdleChannels = this._settings.maxIdleChannels === undefined + ? exports.DEFAULT_MAX_IDLE_CHANNELS + : this._settings.maxIdleChannels; + this._clientPool = new pool_1.ClientPool(MAX_CONCURRENT_REQUESTS_PER_CLIENT, maxIdleChannels, + /* clientFactory= */ (requiresGrpc) => { + var _a; + let client; + // Use the rest fallback if enabled and if the method does not require GRPC + const useFallback = !this._settings.preferRest || requiresGrpc ? false : 'rest'; + let gax; + if (useFallback) { + if (!this._gaxFallback) { + gax = this._gaxFallback = require('google-gax/build/src/fallback'); + } + else { + gax = this._gaxFallback; + } + } + else { + if (!this._gax) { + gax = this._gax = require('google-gax'); + } + else { + gax = this._gax; + } + } + if (this._settings.ssl === false) { + const grpcModule = (_a = this._settings.grpc) !== null && _a !== void 0 ? _a : require('google-gax').grpc; + const sslCreds = grpcModule.credentials.createInsecure(); + const settings = { + sslCreds, + ...this._settings, + fallback: useFallback, + }; + // Since `ssl === false`, if we're using the GAX fallback then + // also set the `protocol` option for GAX fallback to force http + if (useFallback) { + settings.protocol = 'http'; + } + client = new module.exports.v1(settings, gax); + } + else { + client = new module.exports.v1({ + ...this._settings, + fallback: useFallback, + }, gax); + } + (0, logger_1.logger)('clientFactory', null, 'Initialized Firestore GAPIC Client (useFallback: %s)', useFallback); + return client; + }, + /* clientDestructor= */ client => client.close()); + (0, logger_1.logger)('Firestore', null, 'Initialized Firestore'); + } + /** + * Specifies custom settings to be used to configure the `Firestore` + * instance. Can only be invoked once and before any other Firestore method. + * + * If settings are provided via both `settings()` and the `Firestore` + * constructor, both settings objects are merged and any settings provided via + * `settings()` take precedence. + * + * @param {object} settings The settings to use for all Firestore operations. + */ + settings(settings) { + (0, validate_1.validateObject)('settings', settings); + (0, validate_1.validateString)('settings.projectId', settings.projectId, { optional: true }); + (0, validate_1.validateString)('settings.databaseId', settings.databaseId, { + optional: true, + }); + if (this._settingsFrozen) { + throw new Error('Firestore has already been initialized. You can only call ' + + 'settings() once, and only before calling any other methods on a ' + + 'Firestore object.'); + } + const mergedSettings = { ...this._settings, ...settings }; + this.validateAndApplySettings(mergedSettings); + this._traceUtil = this.newTraceUtilInstance(this._settings); + this._settingsFrozen = true; + } + validateAndApplySettings(settings) { + var _a; + if (settings.projectId !== undefined) { + (0, validate_1.validateString)('settings.projectId', settings.projectId); + this._projectId = settings.projectId; + } + if (settings.databaseId !== undefined) { + (0, validate_1.validateString)('settings.databaseId', settings.databaseId); + this._databaseId = settings.databaseId; + } + let url = null; + // If preferRest is not specified in settings, but is set as environment variable, + // then use the environment variable value. + const preferRestEnvValue = (0, util_1.tryGetPreferRestEnvironmentVariable)(); + if (settings.preferRest === undefined && preferRestEnvValue !== undefined) { + settings = { + ...settings, + preferRest: preferRestEnvValue, + }; + } + // If the environment variable is set, it should always take precedence + // over any user passed in settings. + if (process.env.FIRESTORE_EMULATOR_HOST) { + (0, validate_1.validateHost)('FIRESTORE_EMULATOR_HOST', process.env.FIRESTORE_EMULATOR_HOST); + settings = { + ...settings, + host: process.env.FIRESTORE_EMULATOR_HOST, + ssl: false, + }; + url = new url_1.URL(`http://${settings.host}`); + } + else if (settings.host !== undefined) { + (0, validate_1.validateHost)('settings.host', settings.host); + url = new url_1.URL(`http://${settings.host}`); + } + // Only store the host if a valid value was provided in `host`. + if (url !== null) { + if ((settings.servicePath !== undefined && + settings.servicePath !== url.hostname) || + (settings.apiEndpoint !== undefined && + settings.apiEndpoint !== url.hostname)) { + // eslint-disable-next-line no-console + console.warn(`The provided host (${url.hostname}) in "settings" does not ` + + `match the existing host (${(_a = settings.servicePath) !== null && _a !== void 0 ? _a : settings.apiEndpoint}). Using the provided host.`); + } + settings.servicePath = url.hostname; + if (url.port !== '' && settings.port === undefined) { + settings.port = Number(url.port); + } + // We need to remove the `host` and `apiEndpoint` setting, in case a user + // calls `settings()`, which will compare the the provided `host` to the + // existing hostname stored on `servicePath`. + delete settings.host; + delete settings.apiEndpoint; + } + if (settings.ssl !== undefined) { + (0, validate_1.validateBoolean)('settings.ssl', settings.ssl); + } + if (settings.maxIdleChannels !== undefined) { + (0, validate_1.validateInteger)('settings.maxIdleChannels', settings.maxIdleChannels, { + minValue: 0, + }); + } + this._settings = settings; + this._settings.toJSON = function () { + const temp = Object.assign({}, this); + if (temp.credentials) { + temp.credentials = { private_key: '***', client_email: '***' }; + } + return temp; + }; + this._serializer = new serializer_1.Serializer(this); + } + newTraceUtilInstance(settings) { + let createEnabledInstance = true; + // The environment variable can override options to enable/disable telemetry collection. + if ('FIRESTORE_ENABLE_TRACING' in process.env) { + const enableTracingEnvVar = process.env.FIRESTORE_ENABLE_TRACING.toLowerCase(); + if (enableTracingEnvVar === 'on' || enableTracingEnvVar === 'true') { + createEnabledInstance = true; + } + if (enableTracingEnvVar === 'off' || enableTracingEnvVar === 'false') { + createEnabledInstance = false; + } + } + if (createEnabledInstance) { + return new enabled_trace_util_1.EnabledTraceUtil(settings); + } + else { + return new disabled_trace_util_1.DisabledTraceUtil(); + } + } + /** + * Returns the Project ID for this Firestore instance. Validates that + * `initializeIfNeeded()` was called before. + * + * @private + * @internal + */ + get projectId() { + if (this._projectId === undefined) { + throw new Error('INTERNAL ERROR: Client is not yet ready to issue requests.'); + } + return this._projectId; + } + /** + * Returns the Database ID for this Firestore instance. + */ + get databaseId() { + return this._databaseId || path_1.DEFAULT_DATABASE_ID; + } + /** + * Returns the root path of the database. Validates that + * `initializeIfNeeded()` was called before. + * + * @private + * @internal + */ + get formattedName() { + return `projects/${this.projectId}/databases/${this.databaseId}`; + } + /** + * Gets a [DocumentReference]{@link DocumentReference} instance that + * refers to the document at the specified path. + * + * @param {string} documentPath A slash-separated path to a document. + * @returns {DocumentReference} The + * [DocumentReference]{@link DocumentReference} instance. + * + * @example + * ``` + * let documentRef = firestore.doc('collection/document'); + * console.log(`Path of document is ${documentRef.path}`); + * ``` + */ + doc(documentPath) { + (0, path_1.validateResourcePath)('documentPath', documentPath); + const path = path_1.ResourcePath.EMPTY.append(documentPath); + if (!path.isDocument) { + throw new Error(`Value for argument "documentPath" must point to a document, but was "${documentPath}". Your path does not contain an even number of components.`); + } + return new document_reference_1.DocumentReference(this, path); + } + /** + * Gets a [CollectionReference]{@link CollectionReference} instance + * that refers to the collection at the specified path. + * + * @param {string} collectionPath A slash-separated path to a collection. + * @returns {CollectionReference} The + * [CollectionReference]{@link CollectionReference} instance. + * + * @example + * ``` + * let collectionRef = firestore.collection('collection'); + * + * // Add a document with an auto-generated ID. + * collectionRef.add({foo: 'bar'}).then((documentRef) => { + * console.log(`Added document at ${documentRef.path})`); + * }); + * ``` + */ + collection(collectionPath) { + (0, path_1.validateResourcePath)('collectionPath', collectionPath); + const path = path_1.ResourcePath.EMPTY.append(collectionPath); + if (!path.isCollection) { + throw new Error(`Value for argument "collectionPath" must point to a collection, but was "${collectionPath}". Your path does not contain an odd number of components.`); + } + return new collection_reference_1.CollectionReference(this, path); + } + /** + * Creates and returns a new Query that includes all documents in the + * database that are contained in a collection or subcollection with the + * given collectionId. + * + * @param {string} collectionId Identifies the collections to query over. + * Every collection or subcollection with this ID as the last segment of its + * path will be included. Cannot contain a slash. + * @returns {CollectionGroup} The created CollectionGroup. + * + * @example + * ``` + * let docA = firestore.doc('mygroup/docA').set({foo: 'bar'}); + * let docB = firestore.doc('abc/def/mygroup/docB').set({foo: 'bar'}); + * + * Promise.all([docA, docB]).then(() => { + * let query = firestore.collectionGroup('mygroup'); + * query = query.where('foo', '==', 'bar'); + * return query.get().then(snapshot => { + * console.log(`Found ${snapshot.size} documents.`); + * }); + * }); + * ``` + */ + collectionGroup(collectionId) { + if (collectionId.indexOf('/') !== -1) { + throw new Error(`Invalid collectionId '${collectionId}'. Collection IDs must not contain '/'.`); + } + return new collection_group_1.CollectionGroup(this, collectionId, /* converter= */ undefined); + } + /** + * Creates a [WriteBatch]{@link WriteBatch}, used for performing + * multiple writes as a single atomic operation. + * + * @returns {WriteBatch} A WriteBatch that operates on this Firestore + * client. + * + * @example + * ``` + * let writeBatch = firestore.batch(); + * + * // Add two documents in an atomic batch. + * let data = { foo: 'bar' }; + * writeBatch.set(firestore.doc('col/doc1'), data); + * writeBatch.set(firestore.doc('col/doc2'), data); + * + * writeBatch.commit().then(res => { + * console.log('Successfully executed batch.'); + * }); + * ``` + */ + batch() { + return new write_batch_1.WriteBatch(this); + } + /** + * Creates a [BulkWriter]{@link BulkWriter}, used for performing + * multiple writes in parallel. Gradually ramps up writes as specified + * by the 500/50/5 rule. + * + * If you pass [BulkWriterOptions]{@link BulkWriterOptions}, you can + * configure the throttling rates for the created BulkWriter. + * + * @see [500/50/5 Documentation]{@link https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic} + * + * @param {BulkWriterOptions=} options BulkWriter options. + * @returns {BulkWriter} A BulkWriter that operates on this Firestore + * client. + * + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * + * bulkWriter.create(firestore.doc('col/doc1'), {foo: 'bar'}) + * .then(res => { + * console.log(`Added document at ${res.writeTime}`); + * }); + * bulkWriter.update(firestore.doc('col/doc2'), {foo: 'bar'}) + * .then(res => { + * console.log(`Updated document at ${res.writeTime}`); + * }); + * bulkWriter.delete(firestore.doc('col/doc3')) + * .then(res => { + * console.log(`Deleted document at ${res.writeTime}`); + * }); + * await bulkWriter.close().then(() => { + * console.log('Executed all writes'); + * }); + * ``` + */ + bulkWriter(options) { + return new bulk_writer_1.BulkWriter(this, options); + } + /** @private */ + snapshot_(documentOrName, readTime, encoding) { + // TODO: Assert that Firestore Project ID is valid. + let convertTimestamp; + let convertFields; + if (encoding === undefined || encoding === 'protobufJS') { + convertTimestamp = data => data; + convertFields = data => data; + } + else if (encoding === 'json') { + // Google Cloud Functions calls us with Proto3 JSON format data, which we + // must convert to Protobuf JS. + convertTimestamp = convert_1.timestampFromJson; + convertFields = convert_1.fieldsFromJson; + } + else { + throw new Error('Unsupported encoding format. Expected "json" or "protobufJS", ' + + `but was "${encoding}".`); + } + let ref; + let document; + if (typeof documentOrName === 'string') { + ref = new document_reference_1.DocumentReference(this, path_1.QualifiedResourcePath.fromSlashSeparatedString(documentOrName)); + document = new document_1.DocumentSnapshotBuilder(ref); + } + else { + ref = new document_reference_1.DocumentReference(this, path_1.QualifiedResourcePath.fromSlashSeparatedString(documentOrName.name)); + document = new document_1.DocumentSnapshotBuilder(ref); + document.fieldsProto = documentOrName.fields + ? convertFields(documentOrName.fields) + : {}; + document.createTime = timestamp_1.Timestamp.fromProto(convertTimestamp(documentOrName.createTime, 'documentOrName.createTime')); + document.updateTime = timestamp_1.Timestamp.fromProto(convertTimestamp(documentOrName.updateTime, 'documentOrName.updateTime')); + } + if (readTime) { + document.readTime = timestamp_1.Timestamp.fromProto(convertTimestamp(readTime, 'readTime')); + } + return document.build(); + } + /** + * Creates a new `BundleBuilder` instance to package selected Firestore data into + * a bundle. + * + * @param bundleId. The id of the bundle. When loaded on clients, client SDKs use this id + * and the timestamp associated with the built bundle to tell if it has been loaded already. + * If not specified, a random identifier will be used. + */ + bundle(name) { + return new bundle_1.BundleBuilder(name || (0, util_1.autoId)()); + } + /** + * Function executed by {@link Firestore#runTransaction} within the transaction + * context. + * + * @callback Firestore~updateFunction + * @template T + * @param {Transaction} transaction The transaction object for this + * transaction. + * @returns {Promise} The promise returned at the end of the transaction. + * This promise will be returned by {@link Firestore#runTransaction} if the + * transaction completed successfully. + */ + /** + * Options object for {@link Firestore#runTransaction} to configure a + * read-only transaction. + * + * @param {true} readOnly Set to true to indicate a read-only transaction. + * @param {Timestamp=} readTime If specified, documents are read at the given + * time. This may not be more than 60 seconds in the past from when the + * request is processed by the server. + * @typedef {Object} Firestore~ReadOnlyTransactionOptions + */ + /** + * Options object for {@link Firestore#runTransaction} to configure a + * read-write transaction. + * + * @param {false=} readOnly Set to false or omit to indicate a read-write + * transaction. + * @param {number=} maxAttempts The maximum number of attempts for this + * transaction. Defaults to 5. + * @typedef {Object} Firestore~ReadWriteTransactionOptions + */ + /** + * Executes the given updateFunction and commits the changes applied within + * the transaction. + * + * You can use the transaction object passed to 'updateFunction' to read and + * modify Firestore documents under lock. You have to perform all reads before + * before you perform any write. + * + * Transactions can be performed as read-only or read-write transactions. By + * default, transactions are executed in read-write mode. + * + * A read-write transaction obtains a pessimistic lock on all documents that + * are read during the transaction. These locks block other transactions, + * batched writes, and other non-transactional writes from changing that + * document. Any writes in a read-write transactions are committed once + * 'updateFunction' resolves, which also releases all locks. + * + * If a read-write transaction fails with contention, the transaction is + * retried up to five times. The `updateFunction` is invoked once for each + * attempt. + * + * Read-only transactions do not lock documents. They can be used to read + * documents at a consistent snapshot in time, which may be up to 60 seconds + * in the past. Read-only transactions are not retried. + * + * Transactions time out after 60 seconds if no documents are read. + * Transactions that are not committed within than 270 seconds are also + * aborted. Any remaining locks are released when a transaction times out. + * + * @template T + * @param {Firestore~updateFunction} updateFunction The user function to + * execute within the transaction context. + * @param { + * Firestore~ReadWriteTransactionOptions|Firestore~ReadOnlyTransactionOptions= + * } transactionOptions Transaction options. + * @returns {Promise} If the transaction completed successfully or was + * explicitly aborted (by the updateFunction returning a failed Promise), the + * Promise returned by the updateFunction will be returned here. Else if the + * transaction failed, a rejected Promise with the corresponding failure + * error will be returned. + * + * @example + * ``` + * let counterTransaction = firestore.runTransaction(transaction => { + * let documentRef = firestore.doc('col/doc'); + * return transaction.get(documentRef).then(doc => { + * if (doc.exists) { + * let count = doc.get('count') || 0; + * if (count > 10) { + * return Promise.reject('Reached maximum count'); + * } + * transaction.update(documentRef, { count: ++count }); + * return Promise.resolve(count); + * } + * + * transaction.create(documentRef, { count: 1 }); + * return Promise.resolve(1); + * }); + * }); + * + * counterTransaction.then(res => { + * console.log(`Count updated to ${res}`); + * }); + * ``` + */ + runTransaction(updateFunction, transactionOptions) { + (0, validate_1.validateFunction)('updateFunction', updateFunction); + const tag = (0, util_1.requestTag)(); + if (transactionOptions) { + (0, validate_1.validateObject)('transactionOptions', transactionOptions); + (0, validate_1.validateBoolean)('transactionOptions.readOnly', transactionOptions.readOnly, { optional: true }); + if (transactionOptions.readOnly) { + (0, validate_1.validateTimestamp)('transactionOptions.readTime', transactionOptions.readTime, { optional: true }); + } + else { + (0, validate_1.validateInteger)('transactionOptions.maxAttempts', transactionOptions.maxAttempts, { optional: true, minValue: 1 }); + } + } + const transaction = new transaction_1.Transaction(this, tag, transactionOptions); + return this.initializeIfNeeded(tag).then(() => transaction.runTransaction(updateFunction)); + } + /** + * Fetches the root collections that are associated with this Firestore + * database. + * + * @returns {Promise.>} A Promise that resolves + * with an array of CollectionReferences. + * + * @example + * ``` + * firestore.listCollections().then(collections => { + * for (let collection of collections) { + * console.log(`Found collection with id: ${collection.id}`); + * } + * }); + * ``` + */ + listCollections() { + const rootDocument = new document_reference_1.DocumentReference(this, path_1.ResourcePath.EMPTY); + return rootDocument.listCollections(); + } + /** + * Retrieves multiple documents from Firestore. + * + * The first argument is required and must be of type `DocumentReference` + * followed by any additional `DocumentReference` documents. If used, the + * optional `ReadOptions` must be the last argument. + * + * @param {...DocumentReference|ReadOptions} documentRefsOrReadOptions The + * `DocumentReferences` to receive, followed by an optional field mask. + * @returns {Promise>} A Promise that + * contains an array with the resulting document snapshots. + * + * @example + * ``` + * let docRef1 = firestore.doc('col/doc1'); + * let docRef2 = firestore.doc('col/doc2'); + * + * firestore.getAll(docRef1, docRef2, { fieldMask: ['user'] }).then(docs => { + * console.log(`First document: ${JSON.stringify(docs[0])}`); + * console.log(`Second document: ${JSON.stringify(docs[1])}`); + * }); + * ``` + */ + getAll(...documentRefsOrReadOptions) { + return this._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_BATCH_GET_DOCUMENTS, () => { + (0, validate_1.validateMinNumberOfArguments)('Firestore.getAll', documentRefsOrReadOptions, 1); + const { documents, fieldMask } = (0, transaction_1.parseGetAllArguments)(documentRefsOrReadOptions); + this._traceUtil.currentSpan().setAttributes({ + [trace_util_1.ATTRIBUTE_KEY_IS_TRANSACTIONAL]: false, + [trace_util_1.ATTRIBUTE_KEY_DOC_COUNT]: documents.length, + }); + const tag = (0, util_1.requestTag)(); + // Capture the error stack to preserve stack tracing across async calls. + const stack = Error().stack; + return this.initializeIfNeeded(tag) + .then(() => { + const reader = new document_reader_1.DocumentReader(this, documents, fieldMask); + return reader.get(tag); + }) + .catch(err => { + throw (0, util_1.wrapError)(err, stack); + }); + }); + } + /** + * Registers a listener on this client, incrementing the listener count. This + * is used to verify that all listeners are unsubscribed when terminate() is + * called. + * + * @private + * @internal + */ + registerListener() { + this.registeredListenersCount += 1; + } + /** + * Unregisters a listener on this client, decrementing the listener count. + * This is used to verify that all listeners are unsubscribed when terminate() + * is called. + * + * @private + * @internal + */ + unregisterListener() { + this.registeredListenersCount -= 1; + } + /** + * Increments the number of open BulkWriter instances. This is used to verify + * that all pending operations are complete when terminate() is called. + * + * @private + * @internal + */ + _incrementBulkWritersCount() { + this.bulkWritersCount += 1; + } + /** + * Decrements the number of open BulkWriter instances. This is used to verify + * that all pending operations are complete when terminate() is called. + * + * @private + * @internal + */ + _decrementBulkWritersCount() { + this.bulkWritersCount -= 1; + } + /** + * Recursively deletes all documents and subcollections at and under the + * specified level. + * + * If any delete fails, the promise is rejected with an error message + * containing the number of failed deletes and the stack trace of the last + * failed delete. The provided reference is deleted regardless of whether + * all deletes succeeded. + * + * `recursiveDelete()` uses a BulkWriter instance with default settings to + * perform the deletes. To customize throttling rates or add success/error + * callbacks, pass in a custom BulkWriter instance. + * + * @param ref The reference of a document or collection to delete. + * @param bulkWriter A custom BulkWriter instance used to perform the + * deletes. + * @return A promise that resolves when all deletes have been performed. + * The promise is rejected if any of the deletes fail. + * + * @example + * ``` + * // Recursively delete a reference and log the references of failures. + * const bulkWriter = firestore.bulkWriter(); + * bulkWriter + * .onWriteError((error) => { + * if ( + * error.failedAttempts < MAX_RETRY_ATTEMPTS + * ) { + * return true; + * } else { + * console.log('Failed write at document: ', error.documentRef.path); + * return false; + * } + * }); + * await firestore.recursiveDelete(docRef, bulkWriter); + * ``` + */ + recursiveDelete(ref, bulkWriter) { + return this._recursiveDelete(ref, recursive_delete_1.RECURSIVE_DELETE_MAX_PENDING_OPS, recursive_delete_1.RECURSIVE_DELETE_MIN_PENDING_OPS, bulkWriter); + } + /** + * This overload is not private in order to test the query resumption with + * startAfter() once the RecursiveDelete instance has MAX_PENDING_OPS pending. + * + * @private + * @internal + */ + // Visible for testing + _recursiveDelete(ref, maxPendingOps, minPendingOps, bulkWriter) { + const writer = bulkWriter !== null && bulkWriter !== void 0 ? bulkWriter : this.getBulkWriter(); + const deleter = new recursive_delete_1.RecursiveDelete(this, writer, ref, maxPendingOps, minPendingOps); + return deleter.run(); + } + /** + * Terminates the Firestore client and closes all open streams. + * + * @return A Promise that resolves when the client is terminated. + */ + async terminate() { + if (this._bulkWriter) { + await this._bulkWriter.close(); + this._bulkWriter = undefined; + } + if (this.registeredListenersCount > 0 || this.bulkWritersCount > 0) { + return Promise.reject('All onSnapshot() listeners must be unsubscribed, and all BulkWriter ' + + 'instances must be closed before terminating the client. ' + + `There are ${this.registeredListenersCount} active listeners and ` + + `${this.bulkWritersCount} open BulkWriter instances.`); + } + return this._clientPool.terminate(); + } + /** + * Returns the Project ID to serve as the JSON representation of this + * Firestore instance. + * + * @return An object that contains the project ID (or `undefined` if not yet + * available). + */ + toJSON() { + return { projectId: this._projectId }; + } + /** + * Initializes the client if it is not already initialized. All methods in the + * SDK can be used after this method completes. + * + * @private + * @internal + * @param requestTag A unique client-assigned identifier that caused this + * initialization. + * @return A Promise that resolves when the client is initialized. + */ + async initializeIfNeeded(requestTag) { + this._settingsFrozen = true; + if (this._settings.ssl === false) { + // If SSL is false, we assume that we are talking to the emulator. We + // provide an Authorization header by default so that the connection is + // recognized as admin in Firestore Emulator. (If for some reason we're + // not connecting to the emulator, then this will result in denials with + // invalid token, rather than behave like clients not logged in. The user + // can then provide their own Authorization header, which will take + // precedence). + this._settings.customHeaders = { + Authorization: 'Bearer owner', + ...this._settings.customHeaders, + }; + } + if (this._projectId === undefined) { + try { + this._projectId = await this._clientPool.run(requestTag, + /* requiresGrpc= */ false, gapicClient => gapicClient.getProjectId()); + (0, logger_1.logger)('Firestore.initializeIfNeeded', null, 'Detected project ID: %s', this._projectId); + // If the project ID was undefined when the TraceUtil was set up, we + // need to record it. + this._traceUtil.recordProjectId(this.projectId); + } + catch (err) { + (0, logger_1.logger)('Firestore.initializeIfNeeded', null, 'Failed to detect project ID: %s', err); + return Promise.reject(err); + } + } + } + /** + * Returns GAX call options that set the cloud resource header. + * @private + * @internal + */ + createCallOptions(methodName, retryCodes) { + var _a; + const callOptions = { + otherArgs: { + headers: { + [CLOUD_RESOURCE_HEADER]: this.formattedName, + ...this._settings.customHeaders, + ...(_a = this._settings[methodName]) === null || _a === void 0 ? void 0 : _a.customHeaders, + }, + }, + }; + if (retryCodes) { + const retryParams = (0, util_1.getRetryParams)(methodName); + callOptions.retry = + new (require('google-gax/build/src/fallback').RetryOptions)(retryCodes, retryParams); + } + return callOptions; + } + /** + * A function returning a Promise that can be retried. + * + * @private + * @internal + * @callback retryFunction + * @returns {Promise} A Promise indicating the function's success. + */ + /** + * Helper method that retries failed Promises. + * + * If 'delayMs' is specified, waits 'delayMs' between invocations. Otherwise, + * schedules the first attempt immediately, and then waits 100 milliseconds + * for further attempts. + * + * @private + * @internal + * @param methodName Name of the Veneer API endpoint that takes a request + * and GAX options. + * @param requestTag A unique client-assigned identifier for this request. + * @param func Method returning a Promise than can be retried. + * @returns A Promise with the function's result if successful within + * `attemptsRemaining`. Otherwise, returns the last rejected Promise. + */ + async _retry(methodName, requestTag, func) { + const backoff = new backoff_1.ExponentialBackoff(); + let lastError = undefined; + for (let attempt = 0; attempt < exports.MAX_REQUEST_RETRIES; ++attempt) { + if (lastError) { + (0, logger_1.logger)('Firestore._retry', requestTag, 'Retrying request that failed with error:', lastError); + } + try { + await backoff.backoffAndWait(); + return await func(); + } + catch (err) { + lastError = err; + if ((0, util_1.isPermanentRpcError)(err, methodName)) { + break; + } + } + } + (0, logger_1.logger)('Firestore._retry', requestTag, 'Request failed with error:', lastError); + return Promise.reject(lastError); + } + /** + * Waits for the provided stream to become active and returns a paused but + * healthy stream. If an error occurs before the first byte is read, the + * method rejects the returned Promise. + * + * @private + * @internal + * @param backendStream The Node stream to monitor. + * @param lifetime A Promise that resolves when the stream receives an 'end', + * 'close' or 'finish' message. + * @param requestTag A unique client-assigned identifier for this request. + * @param request If specified, the request that should be written to the + * stream after opening. + * @returns A guaranteed healthy stream that should be used instead of + * `backendStream`. + */ + _initializeStream(backendStream, lifetime, requestTag, request) { + const resultStream = new stream_1.PassThrough({ objectMode: true }); + resultStream.pause(); + /** + * Whether we have resolved the Promise and returned the stream to the + * caller. + */ + let streamInitialized = false; + return new Promise((resolve, reject) => { + function streamReady() { + if (!streamInitialized) { + streamInitialized = true; + (0, logger_1.logger)('Firestore._initializeStream', requestTag, 'Stream ready'); + resolve(resultStream); + } + } + function streamEnded() { + (0, logger_1.logger)('Firestore._initializeStream', requestTag, 'Received stream end'); + resultStream.unpipe(backendStream); + resolve(resultStream); + lifetime.resolve(); + } + function streamFailed(err) { + if (!streamInitialized) { + // If we receive an error before we were able to receive any data, + // reject this stream. + (0, logger_1.logger)('Firestore._initializeStream', requestTag, 'Received initial error:', err); + reject(err); + } + else { + (0, logger_1.logger)('Firestore._initializeStream', requestTag, 'Received stream error:', err); + // We execute the forwarding of the 'error' event via setImmediate() as + // V8 guarantees that the Promise chain returned from this method + // is resolved before any code executed via setImmediate(). This + // allows the caller to attach an error handler. + setImmediate(() => { + resultStream.emit('error', err); + }); + } + } + backendStream.on('data', () => streamReady()); + backendStream.on('error', err => streamFailed(err)); + backendStream.on('end', () => streamEnded()); + backendStream.on('close', () => streamEnded()); + backendStream.on('finish', () => streamEnded()); + backendStream.pipe(resultStream); + if (request) { + (0, logger_1.logger)('Firestore._initializeStream', requestTag, 'Sending request: %j', request); + backendStream.write(request, 'utf-8', err => { + if (err) { + streamFailed(err); + } + else { + (0, logger_1.logger)('Firestore._initializeStream', requestTag, 'Marking stream as healthy'); + streamReady(); + } + }); + } + }); + } + /** + * A funnel for all non-streaming API requests, assigning a project ID where + * necessary within the request options. + * + * @private + * @internal + * @param methodName Name of the Veneer API endpoint that takes a request + * and GAX options. + * @param request The Protobuf request to send. + * @param requestTag A unique client-assigned identifier for this request. + * @param retryCodes If provided, a custom list of retry codes. If not + * provided, retry is based on the behavior as defined in the ServiceConfig. + * @returns A Promise with the request result. + */ + request(methodName, request, requestTag, retryCodes) { + const callOptions = this.createCallOptions(methodName, retryCodes); + return this._clientPool.run(requestTag, + /* requiresGrpc= */ false, async (gapicClient) => { + try { + (0, logger_1.logger)('Firestore.request', requestTag, 'Sending request: %j', request); + const [result] = await gapicClient[methodName](request, callOptions); + (0, logger_1.logger)('Firestore.request', requestTag, 'Received response: %j', result); + return result; + } + catch (err) { + (0, logger_1.logger)('Firestore.request', requestTag, 'Received error:', err); + return Promise.reject(err); + } + }); + } + /** + * A funnel for streaming API requests, assigning a project ID where necessary + * within the request options. + * + * The stream is returned in paused state and needs to be resumed once all + * listeners are attached. + * + * @private + * @internal + * @param methodName Name of the streaming Veneer API endpoint that + * takes a request and GAX options. + * @param bidrectional Whether the request is bidirectional (true) or + * unidirectional (false_ + * @param request The Protobuf request to send. + * @param requestTag A unique client-assigned identifier for this request. + * @returns A Promise with the resulting read-only stream. + */ + requestStream(methodName, bidrectional, request, requestTag) { + const callOptions = this.createCallOptions(methodName); + const bidirectional = methodName === 'listen'; + let numResponses = 0; + const NUM_RESPONSES_PER_TRACE_EVENT = 100; + return this._retry(methodName, requestTag, () => { + const result = new util_1.Deferred(); + this._clientPool.run(requestTag, bidrectional, async (gapicClient) => { + (0, logger_1.logger)('Firestore.requestStream', requestTag, 'Sending request: %j', request); + this._traceUtil + .currentSpan() + .addEvent(`Firestore.${methodName}: Start`); + try { + const stream = bidirectional + ? gapicClient[methodName](callOptions) + : gapicClient[methodName](request, callOptions); + const logStream = new stream_1.Transform({ + objectMode: true, + transform: (chunk, encoding, callback) => { + (0, logger_1.logger)('Firestore.requestStream', requestTag, 'Received response: %j', chunk); + numResponses++; + if (numResponses === 1) { + this._traceUtil + .currentSpan() + .addEvent(`Firestore.${methodName}: First response received`); + } + else if (numResponses % NUM_RESPONSES_PER_TRACE_EVENT === 0) { + this._traceUtil + .currentSpan() + .addEvent(`Firestore.${methodName}: Received ${numResponses} responses`); + } + callback(); + }, + }); + stream.pipe(logStream); + const lifetime = new util_1.Deferred(); + const resultStream = await this._initializeStream(stream, lifetime, requestTag, bidirectional ? request : undefined); + resultStream.on('end', () => { + stream.end(); + this._traceUtil + .currentSpan() + .addEvent(`Firestore.${methodName}: Completed`, { + [trace_util_1.ATTRIBUTE_KEY_NUM_RESPONSES]: numResponses, + }); + }); + result.resolve(resultStream); + // While we return the stream to the callee early, we don't want to + // release the GAPIC client until the callee has finished processing the + // stream. + return lifetime.promise; + } + catch (e) { + result.reject(e); + } + }); + return result.promise; + }); + } +} +exports.Firestore = Firestore; +/** + * A logging function that takes a single string. + * + * @callback Firestore~logFunction + * @param {string} Log message + */ +// tslint:disable-next-line:no-default-export +/** + * The default export of the `@google-cloud/firestore` package is the + * {@link Firestore} class. + * + * See {@link Firestore} and {@link ClientConfig} for client methods and + * configuration options. + * + * @module {Firestore} @google-cloud/firestore + * @alias nodejs-firestore + * + * @example Install the client library with npm: + * ``` + * npm install --save @google-cloud/firestore + * + * ``` + * @example Import the client library + * ``` + * var Firestore = require('@google-cloud/firestore'); + * + * ``` + * @example Create a client that uses Application Default Credentials (ADC): + * ``` + * var firestore = new Firestore(); + * + * ``` + * @example Create a client with explicit credentials: + * ``` + * var firestore = new Firestore({ projectId: + * 'your-project-id', keyFilename: '/path/to/keyfile.json' + * }); + * + * ``` + * @example include:samples/quickstart.js + * region_tag:firestore_quickstart + * Full quickstart example: + */ +// tslint:disable-next-line:no-default-export +exports.default = Firestore; +// Horrible hack to ensure backwards compatibility with <= 17.0, which allows +// users to call the default constructor via +// `const Fs = require(`@google-cloud/firestore`); new Fs()`; +const existingExports = module.exports; +module.exports = Firestore; +module.exports = Object.assign(module.exports, existingExports); +/** + * {@link v1beta1} factory function. + * + * @private + * @internal + * @name Firestore.v1beta1 + * @type {function} + */ +Object.defineProperty(module.exports, 'v1beta1', { + // The v1beta1 module is very large. To avoid pulling it in from static + // scope, we lazy-load the module. + get: () => require('./v1beta1'), +}); +/** + * {@link v1} factory function. + * + * @private + * @internal + * @name Firestore.v1 + * @type {function} + */ +Object.defineProperty(module.exports, 'v1', { + // The v1 module is very large. To avoid pulling it in from static + // scope, we lazy-load the module. + get: () => require('./v1'), +}); +/** + * {@link Status} factory function. + * + * @private + * @internal + * @name Firestore.GrpcStatus + * @type {function} + */ +Object.defineProperty(module.exports, 'GrpcStatus', { + // The gax module is very large. To avoid pulling it in from static + // scope, we lazy-load the module. + get: () => require('google-gax').Status, +}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/logger.d.ts b/node_modules/@google-cloud/firestore/build/src/logger.d.ts new file mode 100644 index 0000000..6f50968 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/logger.d.ts @@ -0,0 +1,37 @@ +/*! + * Copyright 2018 Google Inc. 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. + */ +/** + * Log function to use for debug output. By default, we don't perform any + * logging. + * + * @private + * @internal + */ +export declare function logger(methodName: string, requestTag: string | null, logMessage: string, ...additionalArgs: unknown[]): void; +/** + * Sets or disables the log function for all active Firestore instances. + * + * @param logger A log function that takes a message (such as `console.log`) or + * `null` to turn off logging. + */ +export declare function setLogFunction(logger: ((msg: string) => void) | null): void; +/** + * Sets the library version to be used in log messages. + * + * @private + * @internal + */ +export declare function setLibVersion(version: string): void; diff --git a/node_modules/@google-cloud/firestore/build/src/logger.js b/node_modules/@google-cloud/firestore/build/src/logger.js new file mode 100644 index 0000000..b831fb3 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/logger.js @@ -0,0 +1,63 @@ +"use strict"; +/*! + * Copyright 2018 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.logger = logger; +exports.setLogFunction = setLogFunction; +exports.setLibVersion = setLibVersion; +const util = require("util"); +const validate_1 = require("./validate"); +/*! The Firestore library version */ +let libVersion; +/*! The external function used to emit logs. */ +let logFunction = null; +/** + * Log function to use for debug output. By default, we don't perform any + * logging. + * + * @private + * @internal + */ +function logger(methodName, requestTag, logMessage, ...additionalArgs) { + requestTag = requestTag || '#####'; + if (logFunction) { + const formattedMessage = util.format(logMessage, ...additionalArgs); + const time = new Date().toISOString(); + logFunction(`Firestore (${libVersion}) ${time} ${requestTag} [${methodName}]: ` + + formattedMessage); + } +} +/** + * Sets or disables the log function for all active Firestore instances. + * + * @param logger A log function that takes a message (such as `console.log`) or + * `null` to turn off logging. + */ +function setLogFunction(logger) { + if (logger !== null) + (0, validate_1.validateFunction)('logger', logger); + logFunction = logger; +} +/** + * Sets the library version to be used in log messages. + * + * @private + * @internal + */ +function setLibVersion(version) { + libVersion = version; +} +//# sourceMappingURL=logger.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/map-type.d.ts b/node_modules/@google-cloud/firestore/build/src/map-type.d.ts new file mode 100644 index 0000000..cf518a3 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/map-type.d.ts @@ -0,0 +1,18 @@ +/*! + * Copyright 2024 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. + */ +export declare const RESERVED_MAP_KEY = "__type__"; +export declare const RESERVED_MAP_KEY_VECTOR_VALUE = "__vector__"; +export declare const VECTOR_MAP_VECTORS_KEY = "value"; diff --git a/node_modules/@google-cloud/firestore/build/src/map-type.js b/node_modules/@google-cloud/firestore/build/src/map-type.js new file mode 100644 index 0000000..9e6d27d --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/map-type.js @@ -0,0 +1,22 @@ +"use strict"; +/*! + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.VECTOR_MAP_VECTORS_KEY = exports.RESERVED_MAP_KEY_VECTOR_VALUE = exports.RESERVED_MAP_KEY = void 0; +exports.RESERVED_MAP_KEY = '__type__'; +exports.RESERVED_MAP_KEY_VECTOR_VALUE = '__vector__'; +exports.VECTOR_MAP_VECTORS_KEY = 'value'; +//# sourceMappingURL=map-type.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/order.d.ts b/node_modules/@google-cloud/firestore/build/src/order.d.ts new file mode 100644 index 0000000..2da8af9 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/order.d.ts @@ -0,0 +1,38 @@ +/*! + * Copyright 2017 Google Inc. 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. + */ +import { google } from '../protos/firestore_v1_proto_api'; +import api = google.firestore.v1; +/*! + * @private + * @internal + */ +export declare function primitiveComparator(left: string | boolean | number, right: string | boolean | number): number; +/*! + * @private + * @internal + */ +export declare function compareArrays(left: api.IValue[], right: api.IValue[]): number; +/*! + * Compare strings in UTF-8 encoded byte order + * @private + * @internal + */ +export declare function compareUtf8Strings(left: string, right: string): number; +/*! + * @private + * @internal + */ +export declare function compare(left: api.IValue, right: api.IValue): number; diff --git a/node_modules/@google-cloud/firestore/build/src/order.js b/node_modules/@google-cloud/firestore/build/src/order.js new file mode 100644 index 0000000..27a5632 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/order.js @@ -0,0 +1,326 @@ +"use strict"; +/*! + * Copyright 2017 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.primitiveComparator = primitiveComparator; +exports.compareArrays = compareArrays; +exports.compareUtf8Strings = compareUtf8Strings; +exports.compare = compare; +const convert_1 = require("./convert"); +const path_1 = require("./path"); +/*! + * The type order as defined by the backend. + */ +var TypeOrder; +(function (TypeOrder) { + TypeOrder[TypeOrder["NULL"] = 0] = "NULL"; + TypeOrder[TypeOrder["BOOLEAN"] = 1] = "BOOLEAN"; + TypeOrder[TypeOrder["NUMBER"] = 2] = "NUMBER"; + TypeOrder[TypeOrder["TIMESTAMP"] = 3] = "TIMESTAMP"; + TypeOrder[TypeOrder["STRING"] = 4] = "STRING"; + TypeOrder[TypeOrder["BLOB"] = 5] = "BLOB"; + TypeOrder[TypeOrder["REF"] = 6] = "REF"; + TypeOrder[TypeOrder["GEO_POINT"] = 7] = "GEO_POINT"; + TypeOrder[TypeOrder["ARRAY"] = 8] = "ARRAY"; + TypeOrder[TypeOrder["VECTOR"] = 9] = "VECTOR"; + TypeOrder[TypeOrder["OBJECT"] = 10] = "OBJECT"; +})(TypeOrder || (TypeOrder = {})); +/*! + * @private + * @internal + */ +function typeOrder(val) { + const valueType = (0, convert_1.detectValueType)(val); + switch (valueType) { + case 'nullValue': + return TypeOrder.NULL; + case 'integerValue': + return TypeOrder.NUMBER; + case 'doubleValue': + return TypeOrder.NUMBER; + case 'stringValue': + return TypeOrder.STRING; + case 'booleanValue': + return TypeOrder.BOOLEAN; + case 'arrayValue': + return TypeOrder.ARRAY; + case 'timestampValue': + return TypeOrder.TIMESTAMP; + case 'geoPointValue': + return TypeOrder.GEO_POINT; + case 'bytesValue': + return TypeOrder.BLOB; + case 'referenceValue': + return TypeOrder.REF; + case 'mapValue': + return TypeOrder.OBJECT; + case 'vectorValue': + return TypeOrder.VECTOR; + default: + throw new Error('Unexpected value type: ' + valueType); + } +} +/*! + * @private + * @internal + */ +function primitiveComparator(left, right) { + if (left < right) { + return -1; + } + if (left > right) { + return 1; + } + return 0; +} +/*! + * Utility function to compare doubles (using Firestore semantics for NaN). + * @private + * @internal + */ +function compareNumbers(left, right) { + if (left < right) { + return -1; + } + if (left > right) { + return 1; + } + if (left === right) { + return 0; + } + // one or both are NaN. + if (isNaN(left)) { + return isNaN(right) ? 0 : -1; + } + return 1; +} +/*! + * @private + * @internal + */ +function compareNumberProtos(left, right) { + let leftValue, rightValue; + if (left.integerValue !== undefined) { + leftValue = Number(left.integerValue); + } + else { + leftValue = Number(left.doubleValue); + } + if (right.integerValue !== undefined) { + rightValue = Number(right.integerValue); + } + else { + rightValue = Number(right.doubleValue); + } + return compareNumbers(leftValue, rightValue); +} +/*! + * @private + * @internal + */ +function compareTimestamps(left, right) { + const seconds = primitiveComparator(left.seconds || 0, right.seconds || 0); + if (seconds !== 0) { + return seconds; + } + return primitiveComparator(left.nanos || 0, right.nanos || 0); +} +/*! + * @private + * @internal + */ +function compareBlobs(left, right) { + if (!(left instanceof Buffer) || !(right instanceof Buffer)) { + throw new Error('Blobs can only be compared if they are Buffers.'); + } + return Buffer.compare(left, right); +} +/*! + * @private + * @internal + */ +function compareReferenceProtos(left, right) { + const leftPath = path_1.QualifiedResourcePath.fromSlashSeparatedString(left.referenceValue); + const rightPath = path_1.QualifiedResourcePath.fromSlashSeparatedString(right.referenceValue); + return leftPath.compareTo(rightPath); +} +/*! + * @private + * @internal + */ +function compareGeoPoints(left, right) { + return (primitiveComparator(left.latitude || 0, right.latitude || 0) || + primitiveComparator(left.longitude || 0, right.longitude || 0)); +} +/*! + * @private + * @internal + */ +function compareArrays(left, right) { + for (let i = 0; i < left.length && i < right.length; i++) { + const valueComparison = compare(left[i], right[i]); + if (valueComparison !== 0) { + return valueComparison; + } + } + // If all the values matched so far, just check the length. + return primitiveComparator(left.length, right.length); +} +/*! + * @private + * @internal + */ +function compareObjects(left, right) { + // This requires iterating over the keys in the object in order and doing a + // deep comparison. + const leftKeys = Object.keys(left); + const rightKeys = Object.keys(right); + leftKeys.sort(); + rightKeys.sort(); + for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) { + const keyComparison = compareUtf8Strings(leftKeys[i], rightKeys[i]); + if (keyComparison !== 0) { + return keyComparison; + } + const key = leftKeys[i]; + const valueComparison = compare(left[key], right[key]); + if (valueComparison !== 0) { + return valueComparison; + } + } + // If all the keys matched so far, just check the length. + return primitiveComparator(leftKeys.length, rightKeys.length); +} +/*! + * @private + * @internal + */ +function compareVectors(left, right) { + var _a, _b, _c, _d, _e, _f; + // The vector is a map, but only vector value is compared. + const leftArray = (_c = (_b = (_a = left === null || left === void 0 ? void 0 : left['value']) === null || _a === void 0 ? void 0 : _a.arrayValue) === null || _b === void 0 ? void 0 : _b.values) !== null && _c !== void 0 ? _c : []; + const rightArray = (_f = (_e = (_d = right === null || right === void 0 ? void 0 : right['value']) === null || _d === void 0 ? void 0 : _d.arrayValue) === null || _e === void 0 ? void 0 : _e.values) !== null && _f !== void 0 ? _f : []; + const lengthCompare = primitiveComparator(leftArray.length, rightArray.length); + if (lengthCompare !== 0) { + return lengthCompare; + } + return compareArrays(leftArray, rightArray); +} +/*! + * Compare strings in UTF-8 encoded byte order + * @private + * @internal + */ +function compareUtf8Strings(left, right) { + // Find the first differing character (a.k.a. "UTF-16 code unit") in the two strings and, + // if found, use that character to determine the relative ordering of the two strings as a + // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by + // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8 + // and UTF-16 happen to represent Unicode code points. + // + // After finding the first pair of differing characters, there are two cases: + // + // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or + // both are surrogates from a surrogate pair (that collectively represent code points greater + // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the + // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is + // sufficient. + // + // Case 2: One character is a surrogate and the other is not. In this case the surrogate- + // containing string is always ordered after the non-surrogate. This is because surrogates are + // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations + // and are lexicographically greater than the 1, 2, or 3-byte representations of code points + // less than or equal to 0xFFFF. + // + // An example of why Case 2 is required is comparing the following two Unicode code points: + // + // |-----------------------|------------|---------------------|-----------------| + // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding | + // |-----------------------|------------|---------------------|-----------------| + // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD | + // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 | + // |-----------------------|------------|---------------------|-----------------| + // + // A lexicographical comparison of the UTF-8 encodings of these code points would order + // "Replacement Character" _before_ "Grinning Face" because 0xEF is less than 0xF0. However, a + // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously + // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out, + // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate + // pair with those that do not. + const length = Math.min(left.length, right.length); + for (let i = 0; i < length; i++) { + const leftChar = left.charAt(i); + const rightChar = right.charAt(i); + if (leftChar !== rightChar) { + return isSurrogate(leftChar) === isSurrogate(rightChar) + ? primitiveComparator(leftChar, rightChar) + : isSurrogate(leftChar) + ? 1 + : -1; + } + } + // Use the lengths of the strings to determine the overall comparison result since either the + // strings were equal or one is a prefix of the other. + return primitiveComparator(left.length, right.length); +} +const MIN_SURROGATE = 0xd800; +const MAX_SURROGATE = 0xdfff; +function isSurrogate(s) { + const c = s.charCodeAt(0); + return c >= MIN_SURROGATE && c <= MAX_SURROGATE; +} +/*! + * @private + * @internal + */ +function compare(left, right) { + // First compare the types. + const leftType = typeOrder(left); + const rightType = typeOrder(right); + const typeComparison = primitiveComparator(leftType, rightType); + if (typeComparison !== 0) { + return typeComparison; + } + // So they are the same type. + switch (leftType) { + case TypeOrder.NULL: + // Nulls are all equal. + return 0; + case TypeOrder.BOOLEAN: + return primitiveComparator(left.booleanValue, right.booleanValue); + case TypeOrder.STRING: + return compareUtf8Strings(left.stringValue, right.stringValue); + case TypeOrder.NUMBER: + return compareNumberProtos(left, right); + case TypeOrder.TIMESTAMP: + return compareTimestamps(left.timestampValue, right.timestampValue); + case TypeOrder.BLOB: + return compareBlobs(left.bytesValue, right.bytesValue); + case TypeOrder.REF: + return compareReferenceProtos(left, right); + case TypeOrder.GEO_POINT: + return compareGeoPoints(left.geoPointValue, right.geoPointValue); + case TypeOrder.ARRAY: + return compareArrays(left.arrayValue.values || [], right.arrayValue.values || []); + case TypeOrder.OBJECT: + return compareObjects(left.mapValue.fields || {}, right.mapValue.fields || {}); + case TypeOrder.VECTOR: + return compareVectors(left.mapValue.fields || {}, right.mapValue.fields || {}); + default: + throw new Error(`Encountered unknown type order: ${leftType}`); + } +} +//# sourceMappingURL=order.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/path.d.ts b/node_modules/@google-cloud/firestore/build/src/path.d.ts new file mode 100644 index 0000000..3a21b71 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/path.d.ts @@ -0,0 +1,416 @@ +/*! + * Copyright 2017 Google Inc. 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. + */ +import * as firestore from '@google-cloud/firestore'; +import { google } from '../protos/firestore_v1_proto_api'; +import api = google.firestore.v1; +/*! + * The default database ID for this Firestore client. We do not yet expose the + * ability to use different databases. + */ +export declare const DEFAULT_DATABASE_ID = "(default)"; +/** + * An abstract class representing a Firestore path. + * + * Subclasses have to implement `split()` and `canonicalString()`. + * + * @private + * @internal + * @class + */ +declare abstract class Path { + protected readonly segments: string[]; + /** + * Creates a new Path with the given segments. + * + * @private + * @internal + * @private + * @param segments Sequence of parts of a path. + */ + constructor(segments: string[]); + /** + * Returns the number of segments of this field path. + * + * @private + * @internal + */ + get size(): number; + abstract construct(segments: string[] | string): T; + abstract split(relativePath: string): string[]; + /** + * Create a child path beneath the current level. + * + * @private + * @internal + * @param relativePath Relative path to append to the current path. + * @returns The new path. + */ + append(relativePath: Path | string): T; + /** + * Returns the path of the parent node. + * + * @private + * @internal + * @returns The new path or null if we are already at the root. + */ + parent(): T | null; + /** + * Checks whether the current path is a prefix of the specified path. + * + * @private + * @internal + * @param other The path to check against. + * @returns 'true' iff the current path is a prefix match with 'other'. + */ + isPrefixOf(other: Path): boolean; + /** + * Compare the current path against another Path object. + * + * Compare the current path against another Path object. Paths are compared segment by segment, + * prioritizing numeric IDs (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + * + * @private + * @internal + * @param other The path to compare to. + * @returns -1 if current < other, 1 if current > other, 0 if equal + */ + compareTo(other: Path): number; + private compareSegments; + private isNumericId; + private extractNumericId; + private compareNumbers; + /** + * Returns a copy of the underlying segments. + * + * @private + * @internal + * @returns A copy of the segments that make up this path. + */ + toArray(): string[]; + /** + * Pops the last segment from this `Path` and returns a newly constructed + * `Path`. + * + * @private + * @internal + * @returns The newly created Path. + */ + popLast(): T; + /** + * Returns true if this `Path` is equal to the provided value. + * + * @private + * @internal + * @param other The value to compare against. + * @return true if this `Path` is equal to the provided value. + */ + isEqual(other: Path): boolean; +} +/** + * A slash-separated path for navigating resources within the current Firestore + * instance. + * + * @private + * @internal + */ +export declare class ResourcePath extends Path { + /** + * A default instance pointing to the root collection. + * @private + * @internal + */ + static EMPTY: ResourcePath; + /** + * Constructs a ResourcePath. + * + * @private + * @internal + * @param segments Sequence of names of the parts of the path. + */ + constructor(...segments: string[]); + /** + * Indicates whether this path points to a document. + * @private + * @internal + */ + get isDocument(): boolean; + /** + * Indicates whether this path points to a collection. + * @private + * @internal + */ + get isCollection(): boolean; + /** + * The last component of the path. + * @private + * @internal + */ + get id(): string | null; + /** + * Returns the location of this path relative to the root of the project's + * database. + * @private + * @internal + */ + get relativeName(): string; + /** + * Constructs a new instance of ResourcePath. + * + * @private + * @internal + * @param segments Sequence of parts of the path. + * @returns The newly created ResourcePath. + */ + construct(segments: string[]): ResourcePath; + /** + * Splits a string into path segments, using slashes as separators. + * + * @private + * @internal + * @param relativePath The path to split. + * @returns The split path segments. + */ + split(relativePath: string): string[]; + /** + * Converts this path to a fully qualified ResourcePath. + * + * @private + * @internal + * @param projectId The project ID of the current Firestore project. + * @return A fully-qualified resource path pointing to the same element. + */ + toQualifiedResourcePath(projectId: string, databaseId: string): QualifiedResourcePath; +} +/** + * A slash-separated path that includes a project and database ID for referring + * to resources in any Firestore project. + * + * @private + * @internal + */ +export declare class QualifiedResourcePath extends ResourcePath { + /** + * The project ID of this path. + */ + readonly projectId: string; + /** + * The database ID of this path. + */ + readonly databaseId: string; + /** + * Constructs a Firestore Resource Path. + * + * @private + * @internal + * @param projectId The Firestore project id. + * @param databaseId The Firestore database id. + * @param segments Sequence of names of the parts of the path. + */ + constructor(projectId: string, databaseId: string, ...segments: string[]); + /** + * String representation of the path relative to the database root. + * @private + * @internal + */ + get relativeName(): string; + /** + * Creates a resource path from an absolute Firestore path. + * + * @private + * @internal + * @param absolutePath A string representation of a Resource Path. + * @returns The new ResourcePath. + */ + static fromSlashSeparatedString(absolutePath: string): QualifiedResourcePath; + /** + * Create a child path beneath the current level. + * + * @private + * @internal + * @param relativePath Relative path to append to the current path. + * @returns The new path. + */ + append(relativePath: ResourcePath | string): QualifiedResourcePath; + /** + * Create a child path beneath the current level. + * + * @private + * @internal + * @returns The new path. + */ + parent(): QualifiedResourcePath | null; + /** + * String representation of a ResourcePath as expected by the API. + * + * @private + * @internal + * @returns The representation as expected by the API. + */ + get formattedName(): string; + /** + * Constructs a new instance of ResourcePath. We need this instead of using + * the normal constructor because polymorphic 'this' doesn't work on static + * methods. + * + * @private + * @internal + * @param segments Sequence of names of the parts of the path. + * @returns The newly created QualifiedResourcePath. + */ + construct(segments: string[]): QualifiedResourcePath; + /** + * Convenience method to match the ResourcePath API. This method always + * returns the current instance. + * + * @private + * @internal + */ + toQualifiedResourcePath(): QualifiedResourcePath; + /** + * Compare the current path against another ResourcePath object. + * + * @private + * @internal + * @param other The path to compare to. + * @returns -1 if current < other, 1 if current > other, 0 if equal + */ + compareTo(other: ResourcePath): number; + /** + * Converts this ResourcePath to the Firestore Proto representation. + * @private + * @internal + */ + toProto(): api.IValue; +} +/** + * Validates that the given string can be used as a relative or absolute + * resource path. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param resourcePath The path to validate. + * @throws if the string can't be used as a resource path. + */ +export declare function validateResourcePath(arg: string | number, resourcePath: string): void; +/** + * A dot-separated path for navigating sub-objects (e.g. nested maps) within a document. + * + * @class + */ +export declare class FieldPath extends Path implements firestore.FieldPath { + /** + * A special sentinel value to refer to the ID of a document. + * + * @private + * @internal + */ + private static _DOCUMENT_ID; + /** + * Constructs a Firestore Field Path. + * + * @param {...string} segments Sequence of field names that form this path. + * + * @example + * ``` + * let query = firestore.collection('col'); + * let fieldPath = new FieldPath('f.o.o', 'bar'); + * + * query.where(fieldPath, '==', 42).get().then(snapshot => { + * snapshot.forEach(document => { + * console.log(`Document contains {'f.o.o' : {'bar' : 42}}`); + * }); + * }); + * ``` + */ + constructor(...segments: string[]); + /** + * A special FieldPath value to refer to the ID of a document. It can be used + * in queries to sort or filter by the document ID. + * + * @returns {FieldPath} + */ + static documentId(): FieldPath; + /** + * Turns a field path argument into a [FieldPath]{@link FieldPath}. + * Supports FieldPaths as input (which are passed through) and dot-separated + * strings. + * + * @private + * @internal + * @param {string|FieldPath} fieldPath The FieldPath to create. + * @returns {FieldPath} A field path representation. + */ + static fromArgument(fieldPath: string | firestore.FieldPath): FieldPath; + /** + * String representation of a FieldPath as expected by the API. + * + * @private + * @internal + * @override + * @returns {string} The representation as expected by the API. + */ + get formattedName(): string; + /** + * Returns a string representation of this path. + * + * @private + * @internal + * @returns A string representing this path. + */ + toString(): string; + /** + * Splits a string into path segments, using dots as separators. + * + * @private + * @internal + * @override + * @param {string} fieldPath The path to split. + * @returns {Array.} - The split path segments. + */ + split(fieldPath: string): string[]; + /** + * Constructs a new instance of FieldPath. We need this instead of using + * the normal constructor because polymorphic 'this' doesn't work on static + * methods. + * + * @private + * @internal + * @override + * @param segments Sequence of field names. + * @returns The newly created FieldPath. + */ + construct(segments: string[]): FieldPath; + /** + * Returns true if this `FieldPath` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @return {boolean} true if this `FieldPath` is equal to the provided value. + */ + isEqual(other: FieldPath): boolean; +} +/** + * Validates that the provided value can be used as a field path argument. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param fieldPath The value to verify. + * @throws if the string can't be used as a field path. + */ +export declare function validateFieldPath(arg: string | number, fieldPath: unknown): asserts fieldPath is string | FieldPath; +export {}; diff --git a/node_modules/@google-cloud/firestore/build/src/path.js b/node_modules/@google-cloud/firestore/build/src/path.js new file mode 100644 index 0000000..4097e03 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/path.js @@ -0,0 +1,656 @@ +"use strict"; +/*! + * Copyright 2017 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FieldPath = exports.QualifiedResourcePath = exports.ResourcePath = exports.DEFAULT_DATABASE_ID = void 0; +exports.validateResourcePath = validateResourcePath; +exports.validateFieldPath = validateFieldPath; +const order_1 = require("./order"); +const util_1 = require("./util"); +const validate_1 = require("./validate"); +/*! + * The default database ID for this Firestore client. We do not yet expose the + * ability to use different databases. + */ +exports.DEFAULT_DATABASE_ID = '(default)'; +/*! + * A regular expression to verify an absolute Resource Path in Firestore. It + * extracts the project ID, the database name and the relative resource path + * if available. + * + * @type {RegExp} + */ +const RESOURCE_PATH_RE = +// Note: [\s\S] matches all characters including newlines. +/^projects\/([^/]*)\/databases\/([^/]*)(?:\/documents\/)?([\s\S]*)$/; +/*! + * A regular expression to verify whether a field name can be passed to the + * backend without escaping. + * + * @type {RegExp} + */ +const UNESCAPED_FIELD_NAME_RE = /^[_a-zA-Z][_a-zA-Z0-9]*$/; +/*! + * A regular expression to verify field paths that are passed to the API as + * strings. Field paths that do not match this expression have to be provided + * as a [FieldPath]{@link FieldPath} object. + * + * @type {RegExp} + */ +const FIELD_PATH_RE = /^[^*~/[\]]+$/; +/** + * An abstract class representing a Firestore path. + * + * Subclasses have to implement `split()` and `canonicalString()`. + * + * @private + * @internal + * @class + */ +class Path { + /** + * Creates a new Path with the given segments. + * + * @private + * @internal + * @private + * @param segments Sequence of parts of a path. + */ + constructor(segments) { + this.segments = segments; + } + /** + * Returns the number of segments of this field path. + * + * @private + * @internal + */ + get size() { + return this.segments.length; + } + /** + * Create a child path beneath the current level. + * + * @private + * @internal + * @param relativePath Relative path to append to the current path. + * @returns The new path. + */ + append(relativePath) { + if (relativePath instanceof Path) { + return this.construct(this.segments.concat(relativePath.segments)); + } + return this.construct(this.segments.concat(this.split(relativePath))); + } + /** + * Returns the path of the parent node. + * + * @private + * @internal + * @returns The new path or null if we are already at the root. + */ + parent() { + if (this.segments.length === 0) { + return null; + } + return this.construct(this.segments.slice(0, this.segments.length - 1)); + } + /** + * Checks whether the current path is a prefix of the specified path. + * + * @private + * @internal + * @param other The path to check against. + * @returns 'true' iff the current path is a prefix match with 'other'. + */ + isPrefixOf(other) { + if (other.segments.length < this.segments.length) { + return false; + } + for (let i = 0; i < this.segments.length; i++) { + if (this.segments[i] !== other.segments[i]) { + return false; + } + } + return true; + } + /** + * Compare the current path against another Path object. + * + * Compare the current path against another Path object. Paths are compared segment by segment, + * prioritizing numeric IDs (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + * + * @private + * @internal + * @param other The path to compare to. + * @returns -1 if current < other, 1 if current > other, 0 if equal + */ + compareTo(other) { + const len = Math.min(this.segments.length, other.segments.length); + for (let i = 0; i < len; i++) { + const comparison = this.compareSegments(this.segments[i], other.segments[i]); + if (comparison !== 0) { + return comparison; + } + } + return (0, order_1.primitiveComparator)(this.segments.length, other.segments.length); + } + compareSegments(lhs, rhs) { + const isLhsNumeric = this.isNumericId(lhs); + const isRhsNumeric = this.isNumericId(rhs); + if (isLhsNumeric && !isRhsNumeric) { + // Only lhs is numeric + return -1; + } + else if (!isLhsNumeric && isRhsNumeric) { + // Only rhs is numeric + return 1; + } + else if (isLhsNumeric && isRhsNumeric) { + // both numeric + return this.compareNumbers(this.extractNumericId(lhs), this.extractNumericId(rhs)); + } + else { + // both non-numeric + return (0, order_1.compareUtf8Strings)(lhs, rhs); + } + } + // Checks if a segment is a numeric ID (starts with "__id" and ends with "__"). + isNumericId(segment) { + return segment.startsWith('__id') && segment.endsWith('__'); + } + // Extracts the long number from a numeric ID segment. + extractNumericId(segment) { + return BigInt(segment.substring(4, segment.length - 2)); + } + compareNumbers(lhs, rhs) { + if (lhs < rhs) { + return -1; + } + else if (lhs > rhs) { + return 1; + } + else { + return 0; + } + } + /** + * Returns a copy of the underlying segments. + * + * @private + * @internal + * @returns A copy of the segments that make up this path. + */ + toArray() { + return this.segments.slice(); + } + /** + * Pops the last segment from this `Path` and returns a newly constructed + * `Path`. + * + * @private + * @internal + * @returns The newly created Path. + */ + popLast() { + this.segments.pop(); + return this.construct(this.segments); + } + /** + * Returns true if this `Path` is equal to the provided value. + * + * @private + * @internal + * @param other The value to compare against. + * @return true if this `Path` is equal to the provided value. + */ + isEqual(other) { + return this === other || this.compareTo(other) === 0; + } +} +/** + * A slash-separated path for navigating resources within the current Firestore + * instance. + * + * @private + * @internal + */ +class ResourcePath extends Path { + /** + * Constructs a ResourcePath. + * + * @private + * @internal + * @param segments Sequence of names of the parts of the path. + */ + constructor(...segments) { + super(segments); + } + /** + * Indicates whether this path points to a document. + * @private + * @internal + */ + get isDocument() { + return this.segments.length > 0 && this.segments.length % 2 === 0; + } + /** + * Indicates whether this path points to a collection. + * @private + * @internal + */ + get isCollection() { + return this.segments.length % 2 === 1; + } + /** + * The last component of the path. + * @private + * @internal + */ + get id() { + if (this.segments.length > 0) { + return this.segments[this.segments.length - 1]; + } + return null; + } + /** + * Returns the location of this path relative to the root of the project's + * database. + * @private + * @internal + */ + get relativeName() { + return this.segments.join('/'); + } + /** + * Constructs a new instance of ResourcePath. + * + * @private + * @internal + * @param segments Sequence of parts of the path. + * @returns The newly created ResourcePath. + */ + construct(segments) { + return new ResourcePath(...segments); + } + /** + * Splits a string into path segments, using slashes as separators. + * + * @private + * @internal + * @param relativePath The path to split. + * @returns The split path segments. + */ + split(relativePath) { + // We may have an empty segment at the beginning or end if they had a + // leading or trailing slash (which we allow). + return relativePath.split('/').filter(segment => segment.length > 0); + } + /** + * Converts this path to a fully qualified ResourcePath. + * + * @private + * @internal + * @param projectId The project ID of the current Firestore project. + * @return A fully-qualified resource path pointing to the same element. + */ + toQualifiedResourcePath(projectId, databaseId) { + return new QualifiedResourcePath(projectId, databaseId, ...this.segments); + } +} +exports.ResourcePath = ResourcePath; +/** + * A default instance pointing to the root collection. + * @private + * @internal + */ +ResourcePath.EMPTY = new ResourcePath(); +/** + * A slash-separated path that includes a project and database ID for referring + * to resources in any Firestore project. + * + * @private + * @internal + */ +class QualifiedResourcePath extends ResourcePath { + /** + * Constructs a Firestore Resource Path. + * + * @private + * @internal + * @param projectId The Firestore project id. + * @param databaseId The Firestore database id. + * @param segments Sequence of names of the parts of the path. + */ + constructor(projectId, databaseId, ...segments) { + super(...segments); + this.projectId = projectId; + this.databaseId = databaseId; + } + /** + * String representation of the path relative to the database root. + * @private + * @internal + */ + get relativeName() { + return this.segments.join('/'); + } + /** + * Creates a resource path from an absolute Firestore path. + * + * @private + * @internal + * @param absolutePath A string representation of a Resource Path. + * @returns The new ResourcePath. + */ + static fromSlashSeparatedString(absolutePath) { + const elements = RESOURCE_PATH_RE.exec(absolutePath); + if (elements) { + const project = elements[1]; + const database = elements[2]; + const path = elements[3]; + return new QualifiedResourcePath(project, database).append(path); + } + throw new Error(`Resource name '${absolutePath}' is not valid.`); + } + /** + * Create a child path beneath the current level. + * + * @private + * @internal + * @param relativePath Relative path to append to the current path. + * @returns The new path. + */ + append(relativePath) { + // `super.append()` calls `QualifiedResourcePath.construct()` when invoked + // from here and returns a QualifiedResourcePath. + return super.append(relativePath); + } + /** + * Create a child path beneath the current level. + * + * @private + * @internal + * @returns The new path. + */ + parent() { + return super.parent(); + } + /** + * String representation of a ResourcePath as expected by the API. + * + * @private + * @internal + * @returns The representation as expected by the API. + */ + get formattedName() { + const components = [ + 'projects', + this.projectId, + 'databases', + this.databaseId, + 'documents', + ...this.segments, + ]; + return components.join('/'); + } + /** + * Constructs a new instance of ResourcePath. We need this instead of using + * the normal constructor because polymorphic 'this' doesn't work on static + * methods. + * + * @private + * @internal + * @param segments Sequence of names of the parts of the path. + * @returns The newly created QualifiedResourcePath. + */ + construct(segments) { + return new QualifiedResourcePath(this.projectId, this.databaseId, ...segments); + } + /** + * Convenience method to match the ResourcePath API. This method always + * returns the current instance. + * + * @private + * @internal + */ + toQualifiedResourcePath() { + return this; + } + /** + * Compare the current path against another ResourcePath object. + * + * @private + * @internal + * @param other The path to compare to. + * @returns -1 if current < other, 1 if current > other, 0 if equal + */ + compareTo(other) { + if (other instanceof QualifiedResourcePath) { + if (this.projectId < other.projectId) { + return -1; + } + if (this.projectId > other.projectId) { + return 1; + } + if (this.databaseId < other.databaseId) { + return -1; + } + if (this.databaseId > other.databaseId) { + return 1; + } + } + return super.compareTo(other); + } + /** + * Converts this ResourcePath to the Firestore Proto representation. + * @private + * @internal + */ + toProto() { + return { + referenceValue: this.formattedName, + }; + } +} +exports.QualifiedResourcePath = QualifiedResourcePath; +/** + * Validates that the given string can be used as a relative or absolute + * resource path. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param resourcePath The path to validate. + * @throws if the string can't be used as a resource path. + */ +function validateResourcePath(arg, resourcePath) { + if (typeof resourcePath !== 'string' || resourcePath === '') { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, 'resource path')} Path must be a non-empty string.`); + } + if (resourcePath.indexOf('//') >= 0) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, 'resource path')} Paths must not contain //.`); + } +} +/** + * A dot-separated path for navigating sub-objects (e.g. nested maps) within a document. + * + * @class + */ +class FieldPath extends Path { + /** + * Constructs a Firestore Field Path. + * + * @param {...string} segments Sequence of field names that form this path. + * + * @example + * ``` + * let query = firestore.collection('col'); + * let fieldPath = new FieldPath('f.o.o', 'bar'); + * + * query.where(fieldPath, '==', 42).get().then(snapshot => { + * snapshot.forEach(document => { + * console.log(`Document contains {'f.o.o' : {'bar' : 42}}`); + * }); + * }); + * ``` + */ + constructor(...segments) { + if (Array.isArray(segments[0])) { + throw new Error('The FieldPath constructor no longer supports an array as its first argument. ' + + 'Please unpack your array and call FieldPath() with individual arguments.'); + } + (0, validate_1.validateMinNumberOfArguments)('FieldPath', segments, 1); + for (let i = 0; i < segments.length; ++i) { + (0, validate_1.validateString)(i, segments[i]); + if (segments[i].length === 0) { + throw new Error(`Element at index ${i} should not be an empty string.`); + } + } + super(segments); + } + /** + * A special FieldPath value to refer to the ID of a document. It can be used + * in queries to sort or filter by the document ID. + * + * @returns {FieldPath} + */ + static documentId() { + return FieldPath._DOCUMENT_ID; + } + /** + * Turns a field path argument into a [FieldPath]{@link FieldPath}. + * Supports FieldPaths as input (which are passed through) and dot-separated + * strings. + * + * @private + * @internal + * @param {string|FieldPath} fieldPath The FieldPath to create. + * @returns {FieldPath} A field path representation. + */ + static fromArgument(fieldPath) { + // validateFieldPath() is used in all public API entry points to validate + // that fromArgument() is only called with a Field Path or a string. + return fieldPath instanceof FieldPath + ? fieldPath + : new FieldPath(...fieldPath.split('.')); + } + /** + * String representation of a FieldPath as expected by the API. + * + * @private + * @internal + * @override + * @returns {string} The representation as expected by the API. + */ + get formattedName() { + return this.segments + .map(str => { + return UNESCAPED_FIELD_NAME_RE.test(str) + ? str + : '`' + str.replace(/\\/g, '\\\\').replace(/`/g, '\\`') + '`'; + }) + .join('.'); + } + /** + * Returns a string representation of this path. + * + * @private + * @internal + * @returns A string representing this path. + */ + toString() { + return this.formattedName; + } + /** + * Splits a string into path segments, using dots as separators. + * + * @private + * @internal + * @override + * @param {string} fieldPath The path to split. + * @returns {Array.} - The split path segments. + */ + split(fieldPath) { + return fieldPath.split('.'); + } + /** + * Constructs a new instance of FieldPath. We need this instead of using + * the normal constructor because polymorphic 'this' doesn't work on static + * methods. + * + * @private + * @internal + * @override + * @param segments Sequence of field names. + * @returns The newly created FieldPath. + */ + construct(segments) { + return new FieldPath(...segments); + } + /** + * Returns true if this `FieldPath` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @return {boolean} true if this `FieldPath` is equal to the provided value. + */ + isEqual(other) { + return super.isEqual(other); + } +} +exports.FieldPath = FieldPath; +/** + * A special sentinel value to refer to the ID of a document. + * + * @private + * @internal + */ +FieldPath._DOCUMENT_ID = new FieldPath('__name__'); +/** + * Validates that the provided value can be used as a field path argument. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param fieldPath The value to verify. + * @throws if the string can't be used as a field path. + */ +function validateFieldPath(arg, fieldPath) { + if (fieldPath instanceof FieldPath) { + return; + } + if (fieldPath === undefined) { + throw new Error((0, validate_1.invalidArgumentMessage)(arg, 'field path') + ' The path cannot be omitted.'); + } + if ((0, util_1.isObject)(fieldPath) && fieldPath.constructor.name === 'FieldPath') { + throw new Error((0, validate_1.customObjectMessage)(arg, fieldPath)); + } + if (typeof fieldPath !== 'string') { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, 'field path')} Paths can only be specified as strings or via a FieldPath object.`); + } + if (fieldPath.indexOf('..') >= 0) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, 'field path')} Paths must not contain ".." in them.`); + } + if (fieldPath.startsWith('.') || fieldPath.endsWith('.')) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, 'field path')} Paths must not start or end with ".".`); + } + if (!FIELD_PATH_RE.test(fieldPath)) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, 'field path')} Paths can't be empty and must not contain + "*~/[]".`); + } +} +//# sourceMappingURL=path.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/pool.d.ts b/node_modules/@google-cloud/firestore/build/src/pool.d.ts new file mode 100644 index 0000000..5190677 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/pool.d.ts @@ -0,0 +1,144 @@ +/*! + * Copyright 2018 Google Inc. 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. + */ +export declare const CLIENT_TERMINATED_ERROR_MSG = "The client has already been terminated"; +/** + * An auto-resizing pool that distributes concurrent operations over multiple + * clients of type `T`. + * + * ClientPool is used within Firestore to manage a pool of GAPIC clients and + * automatically initializes multiple clients if we issue more than 100 + * concurrent operations. + * + * @private + * @internal + */ +export declare class ClientPool { + private readonly concurrentOperationLimit; + private readonly maxIdleClients; + private readonly clientFactory; + private readonly clientDestructor; + private grpcEnabled; + /** + * Stores each active clients and how many operations it has outstanding. + */ + private readonly activeClients; + /** + * A set of clients that have seen RST_STREAM errors (see + * https://github.com/googleapis/nodejs-firestore/issues/1023) and should + * no longer be used. + */ + private readonly failedClients; + /** + * A mapping from "client" objects to their corresponding IDs. These IDs have + * no semantic meaning but are used for logging to enable tracing the events + * of a particular client over time (such as creating, acquiring, and + * releasing). + */ + private readonly clientIdByClient; + /** + * An object that can be specified to `logger()` to lazily calculate a long + * log message that includes all client IDs of active and pending clients. + */ + private readonly lazyLogStringForAllClientIds; + /** + * Whether the Firestore instance has been terminated. Once terminated, the + * ClientPool can longer schedule new operations. + */ + private terminated; + /** + * Deferred promise that is resolved when there are no active operations on + * the client pool after terminate() has been called. + */ + private readonly terminateDeferred; + /** + * A unique identifier for this object, for inclusion in log messages. + */ + private readonly instanceId; + /** + * @param concurrentOperationLimit The number of operations that each client + * can handle. + * @param maxIdleClients The maximum number of idle clients to keep before + * garbage collecting. + * @param clientFactory A factory function called as needed when new clients + * are required. + * @param clientDestructor A cleanup function that is called when a client is + * disposed of. + */ + constructor(concurrentOperationLimit: number, maxIdleClients: number, clientFactory: (requiresGrpc: boolean) => T, clientDestructor?: (client: T) => Promise); + /** + * Returns an already existing client if it has less than the maximum number + * of concurrent operations or initializes and returns a new client. + * + * @private + * @internal + */ + private acquire; + /** + * Reduces the number of operations for the provided client, potentially + * removing it from the pool of active clients. + * @private + * @internal + */ + private release; + /** + * Given the current operation counts, determines if the given client should + * be garbage collected. + * @private + * @internal + */ + private shouldGarbageCollectClient; + /** + * The number of currently registered clients. + * + * @return Number of currently registered clients. + * @private + * @internal + */ + get size(): number; + /** + * The number of currently active operations. + * + * @return Number of currently active operations. + * @private + * @internal + */ + get opCount(): number; + /** + * The currently active clients. + * + * @return The currently active clients. + * @private + * @internal + */ + get _activeClients(): Map; + /** + * Runs the provided operation in this pool. This function may create an + * additional client if all existing clients already operate at the concurrent + * operation limit. + * + * @param requestTag A unique client-assigned identifier for this operation. + * @param op A callback function that returns a Promise. The client T will + * be returned to the pool when callback finishes. + * @return A Promise that resolves with the result of `op`. + * @private + * @internal + */ + run(requestTag: string, requiresGrpc: boolean, op: (client: T) => Promise): Promise; + terminate(): Promise; +} diff --git a/node_modules/@google-cloud/firestore/build/src/pool.js b/node_modules/@google-cloud/firestore/build/src/pool.js new file mode 100644 index 0000000..f372dde --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/pool.js @@ -0,0 +1,379 @@ +"use strict"; +/*! + * Copyright 2018 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ClientPool = exports.CLIENT_TERMINATED_ERROR_MSG = void 0; +const assert = require("assert"); +const logger_1 = require("./logger"); +const util_1 = require("./util"); +exports.CLIENT_TERMINATED_ERROR_MSG = 'The client has already been terminated'; +/** + * An auto-resizing pool that distributes concurrent operations over multiple + * clients of type `T`. + * + * ClientPool is used within Firestore to manage a pool of GAPIC clients and + * automatically initializes multiple clients if we issue more than 100 + * concurrent operations. + * + * @private + * @internal + */ +class ClientPool { + /** + * @param concurrentOperationLimit The number of operations that each client + * can handle. + * @param maxIdleClients The maximum number of idle clients to keep before + * garbage collecting. + * @param clientFactory A factory function called as needed when new clients + * are required. + * @param clientDestructor A cleanup function that is called when a client is + * disposed of. + */ + constructor(concurrentOperationLimit, maxIdleClients, clientFactory, clientDestructor = () => Promise.resolve()) { + this.concurrentOperationLimit = concurrentOperationLimit; + this.maxIdleClients = maxIdleClients; + this.clientFactory = clientFactory; + this.clientDestructor = clientDestructor; + this.grpcEnabled = false; + /** + * Stores each active clients and how many operations it has outstanding. + */ + this.activeClients = new Map(); + /** + * A set of clients that have seen RST_STREAM errors (see + * https://github.com/googleapis/nodejs-firestore/issues/1023) and should + * no longer be used. + */ + this.failedClients = new Set(); + /** + * A mapping from "client" objects to their corresponding IDs. These IDs have + * no semantic meaning but are used for logging to enable tracing the events + * of a particular client over time (such as creating, acquiring, and + * releasing). + */ + this.clientIdByClient = new WeakMap(); + /** + * Whether the Firestore instance has been terminated. Once terminated, the + * ClientPool can longer schedule new operations. + */ + this.terminated = false; + /** + * Deferred promise that is resolved when there are no active operations on + * the client pool after terminate() has been called. + */ + this.terminateDeferred = new util_1.Deferred(); + /** + * A unique identifier for this object, for inclusion in log messages. + */ + this.instanceId = 'cpl' + (0, util_1.requestTag)(); + this.lazyLogStringForAllClientIds = new LazyLogStringForAllClientIds({ + activeClients: this.activeClients, + failedClients: this.failedClients, + clientIdByClient: this.clientIdByClient, + }); + } + /** + * Returns an already existing client if it has less than the maximum number + * of concurrent operations or initializes and returns a new client. + * + * @private + * @internal + */ + acquire(requestTag, requiresGrpc) { + let selectedClient = null; + let selectedClientRequestCount = -1; + // Transition to grpc when we see the first operation that requires grpc. + this.grpcEnabled = this.grpcEnabled || requiresGrpc; + // Require a grpc client for this operation if we have transitioned to grpc. + requiresGrpc = requiresGrpc || this.grpcEnabled; + for (const [client, metadata] of this.activeClients) { + // Use the "most-full" client that can still accommodate the request + // in order to maximize the number of idle clients as operations start to + // complete. + if (!this.failedClients.has(client) && + metadata.activeRequestCount > selectedClientRequestCount && + metadata.activeRequestCount < this.concurrentOperationLimit && + (metadata.grpcEnabled || !requiresGrpc)) { + selectedClient = client; + selectedClientRequestCount = metadata.activeRequestCount; + } + } + if (selectedClient) { + const selectedClientId = this.clientIdByClient.get(selectedClient); + (0, logger_1.logger)(`ClientPool[${this.instanceId}].acquire`, requestTag, 'Re-using existing client [%s] with %s remaining operations', selectedClientId, this.concurrentOperationLimit - selectedClientRequestCount); + } + else { + const newClientId = 'cli' + (0, util_1.requestTag)(); + (0, logger_1.logger)(`ClientPool[${this.instanceId}].acquire`, requestTag, 'Creating a new client [%s] (requiresGrpc: %s)', newClientId, requiresGrpc); + selectedClient = this.clientFactory(requiresGrpc); + this.clientIdByClient.set(selectedClient, newClientId); + selectedClientRequestCount = 0; + assert(!this.activeClients.has(selectedClient), 'The provided client factory returned an existing instance'); + } + this.activeClients.set(selectedClient, { + grpcEnabled: requiresGrpc, + activeRequestCount: selectedClientRequestCount + 1, + }); + return selectedClient; + } + /** + * Reduces the number of operations for the provided client, potentially + * removing it from the pool of active clients. + * @private + * @internal + */ + async release(requestTag, client) { + const clientId = this.clientIdByClient.get(client); + const metadata = this.activeClients.get(client); + assert(metadata && metadata.activeRequestCount > 0, 'No active requests'); + this.activeClients.set(client, { + grpcEnabled: metadata.grpcEnabled, + activeRequestCount: metadata.activeRequestCount - 1, + }); + if (this.terminated && this.opCount === 0) { + this.terminateDeferred.resolve(); + } + const gcDetermination = this.shouldGarbageCollectClient(client); + (0, logger_1.logger)(`ClientPool[${this.instanceId}].release`, requestTag, 'Releasing client [%s] (gc=%s)', clientId, gcDetermination); + if (!gcDetermination.shouldGarbageCollectClient) { + return; + } + (0, logger_1.logger)(`ClientPool[${this.instanceId}].release`, requestTag, 'Garbage collecting client [%s] (%s)', clientId, this.lazyLogStringForAllClientIds); + const activeClientDeleted = this.activeClients.delete(client); + this.failedClients.delete(client); + await this.clientDestructor(client); + (0, logger_1.logger)(`ClientPool[${this.instanceId}].release`, requestTag, 'Garbage collected client [%s] activeClientDeleted=%s (%s)', clientId, activeClientDeleted, this.lazyLogStringForAllClientIds); + } + /** + * Given the current operation counts, determines if the given client should + * be garbage collected. + * @private + * @internal + */ + shouldGarbageCollectClient(client) { + const clientMetadata = this.activeClients.get(client); + if (clientMetadata.activeRequestCount !== 0) { + // Don't garbage collect clients that have active requests. + return new ClientHasActiveRequests({ + shouldGarbageCollectClient: false, + clientActiveRequestCount: clientMetadata.activeRequestCount, + }); + } + if (this.grpcEnabled !== clientMetadata.grpcEnabled) { + // We are transitioning to GRPC. Garbage collect REST clients. + return new PoolIsTransitioningToGrpc({ + shouldGarbageCollectClient: true, + clientActiveRequestCount: clientMetadata.activeRequestCount, + poolGrpcEnabled: this.grpcEnabled, + clientGrpcEnabled: clientMetadata.grpcEnabled, + }); + } + // Idle clients that have received RST_STREAM errors are always garbage + // collected. + if (this.failedClients.has(client)) { + return new ClientIsFailed({ + shouldGarbageCollectClient: true, + clientActiveRequestCount: clientMetadata.activeRequestCount, + }); + } + // Otherwise, only garbage collect if we have too much idle capacity (e.g. + // more than 100 idle capacity with default settings). + let idleCapacityCount = 0; + for (const [, metadata] of this.activeClients) { + idleCapacityCount += + this.concurrentOperationLimit - metadata.activeRequestCount; + } + const maxIdleCapacityCount = this.maxIdleClients * this.concurrentOperationLimit; + return new IdleCapacity({ + shouldGarbageCollectClient: idleCapacityCount > maxIdleCapacityCount, + clientActiveRequestCount: clientMetadata.activeRequestCount, + idleCapacityCount: idleCapacityCount, + maxIdleCapacityCount: maxIdleCapacityCount, + maxIdleClients: this.maxIdleClients, + concurrentOperationLimit: this.concurrentOperationLimit, + }); + } + /** + * The number of currently registered clients. + * + * @return Number of currently registered clients. + * @private + * @internal + */ + // Visible for testing. + get size() { + return this.activeClients.size; + } + /** + * The number of currently active operations. + * + * @return Number of currently active operations. + * @private + * @internal + */ + // Visible for testing. + get opCount() { + let activeOperationCount = 0; + this.activeClients.forEach(metadata => (activeOperationCount += metadata.activeRequestCount)); + return activeOperationCount; + } + /** + * The currently active clients. + * + * @return The currently active clients. + * @private + * @internal + */ + // Visible for testing. + get _activeClients() { + return this.activeClients; + } + /** + * Runs the provided operation in this pool. This function may create an + * additional client if all existing clients already operate at the concurrent + * operation limit. + * + * @param requestTag A unique client-assigned identifier for this operation. + * @param op A callback function that returns a Promise. The client T will + * be returned to the pool when callback finishes. + * @return A Promise that resolves with the result of `op`. + * @private + * @internal + */ + run(requestTag, requiresGrpc, op) { + if (this.terminated) { + return Promise.reject(new Error(exports.CLIENT_TERMINATED_ERROR_MSG)); + } + const client = this.acquire(requestTag, requiresGrpc); + return op(client) + .catch(async (err) => { + var _a; + if ((_a = err.message) === null || _a === void 0 ? void 0 : _a.match(/RST_STREAM/)) { + // Once a client has seen a RST_STREAM error, the GRPC channel can + // no longer be used. We mark the client as failed, which ensures that + // we open a new GRPC channel for the next request. + this.failedClients.add(client); + } + await this.release(requestTag, client); + return Promise.reject(err); + }) + .then(async (res) => { + await this.release(requestTag, client); + return res; + }); + } + async terminate() { + this.terminated = true; + // Wait for all pending operations to complete before terminating. + if (this.opCount > 0) { + (0, logger_1.logger)(`ClientPool[${this.instanceId}].terminate`, + /* requestTag= */ null, 'Waiting for %s pending operations to complete before terminating (%s)', this.opCount, this.lazyLogStringForAllClientIds); + await this.terminateDeferred.promise; + } + (0, logger_1.logger)(`ClientPool[${this.instanceId}].terminate`, + /* requestTag= */ null, 'Closing all active clients (%s)', this.lazyLogStringForAllClientIds); + for (const [client] of this.activeClients) { + this.activeClients.delete(client); + await this.clientDestructor(client); + } + } +} +exports.ClientPool = ClientPool; +/** + * Helper class that, when logged as a direct argument of `logger()`, will + * lazily evaluate to a long string that contains all IDs of both active and + * failed clients. + */ +class LazyLogStringForAllClientIds { + constructor(config) { + this.activeClients = config.activeClients; + this.failedClients = config.failedClients; + this.clientIdByClient = config.clientIdByClient; + } + toString() { + const activeClientsDescription = Array.from(this.activeClients.entries()) + .map(([client, metadata]) => `${this.clientIdByClient.get(client)}=${metadata.activeRequestCount}`) + .sort() + .join(', '); + const failedClientsDescription = Array.from(this.failedClients) + .map(client => `${this.clientIdByClient.get(client)}`) + .sort() + .join(', '); + return (`${this.activeClients.size} active clients: {` + + activeClientsDescription + + '}, ' + + `${this.failedClients.size} failed clients: {` + + failedClientsDescription + + '}'); + } +} +/** + * Minimum data to be included in the objects returned from + * ClientPool.shouldGarbageCollectClient(). + */ +class BaseShouldGarbageCollectClientResult { + /** + * Return a terse, one-line string representation. This makes it easy to + * grep through log output to find the logged values. + */ + toString() { + const propertyStrings = []; + for (const propertyName of Object.getOwnPropertyNames(this)) { + const propertyValue = this[propertyName]; + propertyStrings.push(`${propertyName}=${propertyValue}`); + } + return '{' + propertyStrings.join(', ') + '}'; + } +} +class ClientHasActiveRequests extends BaseShouldGarbageCollectClientResult { + constructor(args) { + super(); + this.name = 'ClientHasActiveRequests'; + this.shouldGarbageCollectClient = args.shouldGarbageCollectClient; + this.clientActiveRequestCount = args.clientActiveRequestCount; + } +} +class PoolIsTransitioningToGrpc extends BaseShouldGarbageCollectClientResult { + constructor(args) { + super(); + this.name = 'PoolIsTransitioningToGrpc'; + this.shouldGarbageCollectClient = args.shouldGarbageCollectClient; + this.clientActiveRequestCount = args.clientActiveRequestCount; + this.poolGrpcEnabled = args.poolGrpcEnabled; + this.clientGrpcEnabled = args.clientGrpcEnabled; + } +} +class ClientIsFailed extends BaseShouldGarbageCollectClientResult { + constructor(args) { + super(); + this.name = 'ClientIsFailed'; + this.shouldGarbageCollectClient = args.shouldGarbageCollectClient; + this.clientActiveRequestCount = args.clientActiveRequestCount; + } +} +class IdleCapacity extends BaseShouldGarbageCollectClientResult { + constructor(args) { + super(); + this.name = 'IdleCapacity'; + this.shouldGarbageCollectClient = args.shouldGarbageCollectClient; + this.clientActiveRequestCount = args.clientActiveRequestCount; + this.idleCapacityCount = args.idleCapacityCount; + this.maxIdleCapacityCount = args.maxIdleCapacityCount; + this.maxIdleClients = args.maxIdleClients; + this.concurrentOperationLimit = args.concurrentOperationLimit; + } +} +//# sourceMappingURL=pool.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/query-partition.d.ts b/node_modules/@google-cloud/firestore/build/src/query-partition.d.ts new file mode 100644 index 0000000..d197747 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/query-partition.d.ts @@ -0,0 +1,96 @@ +import * as firestore from '@google-cloud/firestore'; +import * as protos from '../protos/firestore_v1_proto_api'; +import { Query } from './reference/query'; +import { Firestore } from './index'; +import api = protos.google.firestore.v1; +/** + * A split point that can be used in a query as a starting and/or end point for + * the query results. The cursors returned by {@link #startAt} and {@link + * #endBefore} can only be used in a query that matches the constraint of query + * that produced this partition. + * + * @class QueryPartition + */ +export declare class QueryPartition implements firestore.QueryPartition { + private readonly _firestore; + private readonly _collectionId; + private readonly _converter; + private readonly _startAt; + private readonly _endBefore; + private readonly _serializer; + private _memoizedStartAt; + private _memoizedEndBefore; + /** @private */ + constructor(_firestore: Firestore, _collectionId: string, _converter: firestore.FirestoreDataConverter, _startAt: api.IValue[] | undefined, _endBefore: api.IValue[] | undefined); + /** + * The cursor that defines the first result for this partition or `undefined` + * if this is the first partition. The cursor value must be + * destructured when passed to `startAt()` (for example with + * `query.startAt(...queryPartition.startAt)`). + * + * @example + * ``` + * const query = firestore.collectionGroup('collectionId'); + * for await (const partition of query.getPartitions(42)) { + * let partitionedQuery = query.orderBy(FieldPath.documentId()); + * if (partition.startAt) { + * partitionedQuery = partitionedQuery.startAt(...partition.startAt); + * } + * if (partition.endBefore) { + * partitionedQuery = partitionedQuery.endBefore(...partition.endBefore); + * } + * const querySnapshot = await partitionedQuery.get(); + * console.log(`Partition contained ${querySnapshot.length} documents`); + * } + * + * ``` + * @type {Array<*>} + * @return {Array<*>} A cursor value that can be used with {@link + * Query#startAt} or `undefined` if this is the first partition. + */ + get startAt(): unknown[] | undefined; + /** + * The cursor that defines the first result after this partition or + * `undefined` if this is the last partition. The cursor value must be + * destructured when passed to `endBefore()` (for example with + * `query.endBefore(...queryPartition.endBefore)`). + * + * @example + * ``` + * const query = firestore.collectionGroup('collectionId'); + * for await (const partition of query.getPartitions(42)) { + * let partitionedQuery = query.orderBy(FieldPath.documentId()); + * if (partition.startAt) { + * partitionedQuery = partitionedQuery.startAt(...partition.startAt); + * } + * if (partition.endBefore) { + * partitionedQuery = partitionedQuery.endBefore(...partition.endBefore); + * } + * const querySnapshot = await partitionedQuery.get(); + * console.log(`Partition contained ${querySnapshot.length} documents`); + * } + * + * ``` + * @type {Array<*>} + * @return {Array<*>} A cursor value that can be used with {@link + * Query#endBefore} or `undefined` if this is the last partition. + */ + get endBefore(): unknown[] | undefined; + /** + * Returns a query that only encapsulates the documents for this partition. + * + * @example + * ``` + * const query = firestore.collectionGroup('collectionId'); + * for await (const partition of query.getPartitions(42)) { + * const partitionedQuery = partition.toQuery(); + * const querySnapshot = await partitionedQuery.get(); + * console.log(`Partition contained ${querySnapshot.length} documents`); + * } + * + * ``` + * @return {Query} A query partitioned by a {@link Query#startAt} and + * {@link Query#endBefore} cursor. + */ + toQuery(): Query; +} diff --git a/node_modules/@google-cloud/firestore/build/src/query-partition.js b/node_modules/@google-cloud/firestore/build/src/query-partition.js new file mode 100644 index 0000000..21086f9 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/query-partition.js @@ -0,0 +1,144 @@ +"use strict"; +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.QueryPartition = void 0; +const field_order_1 = require("./reference/field-order"); +const query_1 = require("./reference/query"); +const query_options_1 = require("./reference/query-options"); +const path_1 = require("./path"); +const serializer_1 = require("./serializer"); +/** + * A split point that can be used in a query as a starting and/or end point for + * the query results. The cursors returned by {@link #startAt} and {@link + * #endBefore} can only be used in a query that matches the constraint of query + * that produced this partition. + * + * @class QueryPartition + */ +class QueryPartition { + /** @private */ + constructor(_firestore, _collectionId, _converter, _startAt, _endBefore) { + this._firestore = _firestore; + this._collectionId = _collectionId; + this._converter = _converter; + this._startAt = _startAt; + this._endBefore = _endBefore; + this._serializer = new serializer_1.Serializer(_firestore); + } + /** + * The cursor that defines the first result for this partition or `undefined` + * if this is the first partition. The cursor value must be + * destructured when passed to `startAt()` (for example with + * `query.startAt(...queryPartition.startAt)`). + * + * @example + * ``` + * const query = firestore.collectionGroup('collectionId'); + * for await (const partition of query.getPartitions(42)) { + * let partitionedQuery = query.orderBy(FieldPath.documentId()); + * if (partition.startAt) { + * partitionedQuery = partitionedQuery.startAt(...partition.startAt); + * } + * if (partition.endBefore) { + * partitionedQuery = partitionedQuery.endBefore(...partition.endBefore); + * } + * const querySnapshot = await partitionedQuery.get(); + * console.log(`Partition contained ${querySnapshot.length} documents`); + * } + * + * ``` + * @type {Array<*>} + * @return {Array<*>} A cursor value that can be used with {@link + * Query#startAt} or `undefined` if this is the first partition. + */ + get startAt() { + if (this._startAt && !this._memoizedStartAt) { + this._memoizedStartAt = this._startAt.map(v => this._serializer.decodeValue(v)); + } + return this._memoizedStartAt; + } + /** + * The cursor that defines the first result after this partition or + * `undefined` if this is the last partition. The cursor value must be + * destructured when passed to `endBefore()` (for example with + * `query.endBefore(...queryPartition.endBefore)`). + * + * @example + * ``` + * const query = firestore.collectionGroup('collectionId'); + * for await (const partition of query.getPartitions(42)) { + * let partitionedQuery = query.orderBy(FieldPath.documentId()); + * if (partition.startAt) { + * partitionedQuery = partitionedQuery.startAt(...partition.startAt); + * } + * if (partition.endBefore) { + * partitionedQuery = partitionedQuery.endBefore(...partition.endBefore); + * } + * const querySnapshot = await partitionedQuery.get(); + * console.log(`Partition contained ${querySnapshot.length} documents`); + * } + * + * ``` + * @type {Array<*>} + * @return {Array<*>} A cursor value that can be used with {@link + * Query#endBefore} or `undefined` if this is the last partition. + */ + get endBefore() { + if (this._endBefore && !this._memoizedEndBefore) { + this._memoizedEndBefore = this._endBefore.map(v => this._serializer.decodeValue(v)); + } + return this._memoizedEndBefore; + } + /** + * Returns a query that only encapsulates the documents for this partition. + * + * @example + * ``` + * const query = firestore.collectionGroup('collectionId'); + * for await (const partition of query.getPartitions(42)) { + * const partitionedQuery = partition.toQuery(); + * const querySnapshot = await partitionedQuery.get(); + * console.log(`Partition contained ${querySnapshot.length} documents`); + * } + * + * ``` + * @return {Query} A query partitioned by a {@link Query#startAt} and + * {@link Query#endBefore} cursor. + */ + toQuery() { + // Since the api.Value to JavaScript type conversion can be lossy (unless + // `useBigInt` is used), we pass the original protobuf representation to the + // created query. + let queryOptions = query_options_1.QueryOptions.forCollectionGroupQuery(this._collectionId, this._converter); + queryOptions = queryOptions.with({ + fieldOrders: [new field_order_1.FieldOrder(path_1.FieldPath.documentId())], + }); + if (this._startAt !== undefined) { + queryOptions = queryOptions.with({ + startAt: { before: true, values: this._startAt }, + }); + } + if (this._endBefore !== undefined) { + queryOptions = queryOptions.with({ + endAt: { before: true, values: this._endBefore }, + }); + } + return new query_1.Query(this._firestore, queryOptions); + } +} +exports.QueryPartition = QueryPartition; +//# sourceMappingURL=query-partition.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/query-profile.d.ts b/node_modules/@google-cloud/firestore/build/src/query-profile.d.ts new file mode 100644 index 0000000..7ac1642 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/query-profile.d.ts @@ -0,0 +1,94 @@ +/*! + * Copyright 2024 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. + */ +import * as firestore from '@google-cloud/firestore'; +import { google } from '../protos/firestore_v1_proto_api'; +import { Serializer } from './serializer'; +import IPlanSummary = google.firestore.v1.IPlanSummary; +import IExecutionStats = google.firestore.v1.IExecutionStats; +import IExplainMetrics = google.firestore.v1.IExplainMetrics; +/** + * PlanSummary contains information about the planning stage of a query. + * + * @class PlanSummary + */ +export declare class PlanSummary implements firestore.PlanSummary { + readonly indexesUsed: Record[]; + /** + * @private + * @internal + */ + constructor(indexesUsed: Record[]); + /** + * @private + * @internal + */ + static _fromProto(plan: IPlanSummary | null | undefined, serializer: Serializer): PlanSummary; +} +/** + * ExecutionStats contains information about the execution of a query. + * + * @class ExecutionStats + */ +export declare class ExecutionStats implements firestore.ExecutionStats { + readonly resultsReturned: number; + readonly executionDuration: firestore.Duration; + readonly readOperations: number; + readonly debugStats: Record; + /** + * @private + * @internal + */ + constructor(resultsReturned: number, executionDuration: firestore.Duration, readOperations: number, debugStats: Record); + /** + * @private + * @internal + */ + static _fromProto(stats: IExecutionStats | null | undefined, serializer: Serializer): ExecutionStats | null; +} +/** + * ExplainMetrics contains information about planning and execution of a query. + * + * @class ExplainMetrics + */ +export declare class ExplainMetrics implements firestore.ExplainMetrics { + readonly planSummary: PlanSummary; + readonly executionStats: ExecutionStats | null; + /** + * @private + * @internal + */ + constructor(planSummary: PlanSummary, executionStats: ExecutionStats | null); + /** + * @private + * @internal + */ + static _fromProto(metrics: IExplainMetrics, serializer: Serializer): ExplainMetrics; +} +/** + * ExplainResults contains information about planning, execution, and results + * of a query. + * + * @class ExplainResults + */ +export declare class ExplainResults implements firestore.ExplainResults { + readonly metrics: ExplainMetrics; + readonly snapshot: T | null; + /** + * @private + * @internal + */ + constructor(metrics: ExplainMetrics, snapshot: T | null); +} diff --git a/node_modules/@google-cloud/firestore/build/src/query-profile.js b/node_modules/@google-cloud/firestore/build/src/query-profile.js new file mode 100644 index 0000000..da7a9ef --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/query-profile.js @@ -0,0 +1,119 @@ +"use strict"; +/*! + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ExplainResults = exports.ExplainMetrics = exports.ExecutionStats = exports.PlanSummary = void 0; +/** + * PlanSummary contains information about the planning stage of a query. + * + * @class PlanSummary + */ +class PlanSummary { + /** + * @private + * @internal + */ + constructor(indexesUsed) { + this.indexesUsed = indexesUsed; + } + /** + * @private + * @internal + */ + static _fromProto(plan, serializer) { + const indexes = []; + if (plan && plan.indexesUsed) { + for (const index of plan.indexesUsed) { + indexes.push(serializer.decodeGoogleProtobufStruct(index)); + } + } + return new PlanSummary(indexes); + } +} +exports.PlanSummary = PlanSummary; +/** + * ExecutionStats contains information about the execution of a query. + * + * @class ExecutionStats + */ +class ExecutionStats { + /** + * @private + * @internal + */ + constructor(resultsReturned, executionDuration, readOperations, debugStats) { + this.resultsReturned = resultsReturned; + this.executionDuration = executionDuration; + this.readOperations = readOperations; + this.debugStats = debugStats; + } + /** + * @private + * @internal + */ + static _fromProto(stats, serializer) { + var _a, _b; + if (stats) { + return new ExecutionStats(Number(stats.resultsReturned), { + seconds: Number((_a = stats.executionDuration) === null || _a === void 0 ? void 0 : _a.seconds), + nanoseconds: Number((_b = stats.executionDuration) === null || _b === void 0 ? void 0 : _b.nanos), + }, Number(stats.readOperations), serializer.decodeGoogleProtobufStruct(stats.debugStats)); + } + return null; + } +} +exports.ExecutionStats = ExecutionStats; +/** + * ExplainMetrics contains information about planning and execution of a query. + * + * @class ExplainMetrics + */ +class ExplainMetrics { + /** + * @private + * @internal + */ + constructor(planSummary, executionStats) { + this.planSummary = planSummary; + this.executionStats = executionStats; + } + /** + * @private + * @internal + */ + static _fromProto(metrics, serializer) { + return new ExplainMetrics(PlanSummary._fromProto(metrics.planSummary, serializer), ExecutionStats._fromProto(metrics.executionStats, serializer)); + } +} +exports.ExplainMetrics = ExplainMetrics; +/** + * ExplainResults contains information about planning, execution, and results + * of a query. + * + * @class ExplainResults + */ +class ExplainResults { + /** + * @private + * @internal + */ + constructor(metrics, snapshot) { + this.metrics = metrics; + this.snapshot = snapshot; + } +} +exports.ExplainResults = ExplainResults; +//# sourceMappingURL=query-profile.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/rate-limiter.d.ts b/node_modules/@google-cloud/firestore/build/src/rate-limiter.d.ts new file mode 100644 index 0000000..e6c59e3 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/rate-limiter.d.ts @@ -0,0 +1,75 @@ +/** + * A helper that uses the Token Bucket algorithm to rate limit the number of + * operations that can be made in a second. + * + * Before a given request containing a number of operations can proceed, + * RateLimiter determines doing so stays under the provided rate limits. It can + * also determine how much time is required before a request can be made. + * + * RateLimiter can also implement a gradually increasing rate limit. This is + * used to enforce the 500/50/5 rule + * (https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic). + * + * @private + * @internal + */ +export declare class RateLimiter { + private readonly initialCapacity; + private readonly multiplier; + private readonly multiplierMillis; + readonly maximumCapacity: number; + private readonly startTimeMillis; + availableTokens: number; + lastRefillTimeMillis: number; + previousCapacity: number; + /** + * @param initialCapacity Initial maximum number of operations per second. + * @param multiplier Rate by which to increase the capacity. + * @param multiplierMillis How often the capacity should increase in + * milliseconds. + * @param maximumCapacity Maximum number of allowed operations per second. + * The number of tokens added per second will never exceed this number. + * @param startTimeMillis The starting time in epoch milliseconds that the + * rate limit is based on. Used for testing the limiter. + */ + constructor(initialCapacity: number, multiplier: number, multiplierMillis: number, maximumCapacity: number, startTimeMillis?: number); + /** + * Tries to make the number of operations. Returns true if the request + * succeeded and false otherwise. + * + * @param requestTimeMillis The time used to calculate the number of available + * tokens. Used for testing the limiter. + * @private + * @internal + */ + tryMakeRequest(numOperations: number, requestTimeMillis?: number): boolean; + /** + * Returns the number of ms needed to make a request with the provided number + * of operations. Returns 0 if the request can be made with the existing + * capacity. Returns -1 if the request is not possible with the current + * capacity. + * + * @param requestTimeMillis The time used to calculate the number of available + * tokens. Used for testing the limiter. + * @private + * @internal + */ + getNextRequestDelayMs(numOperations: number, requestTimeMillis?: number): number; + /** + * Refills the number of available tokens based on how much time has elapsed + * since the last time the tokens were refilled. + * + * @param requestTimeMillis The time used to calculate the number of available + * tokens. Used for testing the limiter. + * @private + * @internal + */ + private refillTokens; + /** + * Calculates the maximum capacity based on the provided date. + * + * @private + * @internal + */ + calculateCapacity(requestTimeMillis: number): number; +} diff --git a/node_modules/@google-cloud/firestore/build/src/rate-limiter.js b/node_modules/@google-cloud/firestore/build/src/rate-limiter.js new file mode 100644 index 0000000..64cdac8 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/rate-limiter.js @@ -0,0 +1,139 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RateLimiter = void 0; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const assert = require("assert"); +const logger_1 = require("./logger"); +/** + * A helper that uses the Token Bucket algorithm to rate limit the number of + * operations that can be made in a second. + * + * Before a given request containing a number of operations can proceed, + * RateLimiter determines doing so stays under the provided rate limits. It can + * also determine how much time is required before a request can be made. + * + * RateLimiter can also implement a gradually increasing rate limit. This is + * used to enforce the 500/50/5 rule + * (https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic). + * + * @private + * @internal + */ +class RateLimiter { + /** + * @param initialCapacity Initial maximum number of operations per second. + * @param multiplier Rate by which to increase the capacity. + * @param multiplierMillis How often the capacity should increase in + * milliseconds. + * @param maximumCapacity Maximum number of allowed operations per second. + * The number of tokens added per second will never exceed this number. + * @param startTimeMillis The starting time in epoch milliseconds that the + * rate limit is based on. Used for testing the limiter. + */ + constructor(initialCapacity, multiplier, multiplierMillis, maximumCapacity, startTimeMillis = Date.now()) { + this.initialCapacity = initialCapacity; + this.multiplier = multiplier; + this.multiplierMillis = multiplierMillis; + this.maximumCapacity = maximumCapacity; + this.startTimeMillis = startTimeMillis; + this.availableTokens = initialCapacity; + this.lastRefillTimeMillis = startTimeMillis; + this.previousCapacity = initialCapacity; + } + /** + * Tries to make the number of operations. Returns true if the request + * succeeded and false otherwise. + * + * @param requestTimeMillis The time used to calculate the number of available + * tokens. Used for testing the limiter. + * @private + * @internal + */ + tryMakeRequest(numOperations, requestTimeMillis = Date.now()) { + this.refillTokens(requestTimeMillis); + if (numOperations <= this.availableTokens) { + this.availableTokens -= numOperations; + return true; + } + return false; + } + /** + * Returns the number of ms needed to make a request with the provided number + * of operations. Returns 0 if the request can be made with the existing + * capacity. Returns -1 if the request is not possible with the current + * capacity. + * + * @param requestTimeMillis The time used to calculate the number of available + * tokens. Used for testing the limiter. + * @private + * @internal + */ + getNextRequestDelayMs(numOperations, requestTimeMillis = Date.now()) { + this.refillTokens(requestTimeMillis); + if (numOperations < this.availableTokens) { + return 0; + } + const capacity = this.calculateCapacity(requestTimeMillis); + if (capacity < numOperations) { + return -1; + } + const requiredTokens = numOperations - this.availableTokens; + return Math.ceil((requiredTokens * 1000) / capacity); + } + /** + * Refills the number of available tokens based on how much time has elapsed + * since the last time the tokens were refilled. + * + * @param requestTimeMillis The time used to calculate the number of available + * tokens. Used for testing the limiter. + * @private + * @internal + */ + refillTokens(requestTimeMillis) { + if (requestTimeMillis >= this.lastRefillTimeMillis) { + const elapsedTime = requestTimeMillis - this.lastRefillTimeMillis; + const capacity = this.calculateCapacity(requestTimeMillis); + const tokensToAdd = Math.floor((elapsedTime * capacity) / 1000); + if (tokensToAdd > 0) { + this.availableTokens = Math.min(capacity, this.availableTokens + tokensToAdd); + this.lastRefillTimeMillis = requestTimeMillis; + } + } + else { + throw new Error('Request time should not be before the last token refill time.'); + } + } + /** + * Calculates the maximum capacity based on the provided date. + * + * @private + * @internal + */ + // Visible for testing. + calculateCapacity(requestTimeMillis) { + assert(requestTimeMillis >= this.startTimeMillis, 'startTime cannot be after currentTime'); + const millisElapsed = requestTimeMillis - this.startTimeMillis; + const operationsPerSecond = Math.min(Math.floor(Math.pow(this.multiplier, Math.floor(millisElapsed / this.multiplierMillis)) * this.initialCapacity), this.maximumCapacity); + if (operationsPerSecond !== this.previousCapacity) { + (0, logger_1.logger)('RateLimiter.calculateCapacity', null, `New request capacity: ${operationsPerSecond} operations per second.`); + } + this.previousCapacity = operationsPerSecond; + return operationsPerSecond; + } +} +exports.RateLimiter = RateLimiter; +//# sourceMappingURL=rate-limiter.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/recursive-delete.d.ts b/node_modules/@google-cloud/firestore/build/src/recursive-delete.d.ts new file mode 100644 index 0000000..8ec38cf --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/recursive-delete.d.ts @@ -0,0 +1,166 @@ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as firestore from '@google-cloud/firestore'; +import Firestore, { BulkWriter } from '.'; +/*! + * Datastore allowed numeric IDs where Firestore only allows strings. Numeric + * IDs are exposed to Firestore as __idNUM__, so this is the lowest possible + * negative numeric value expressed in that format. + * + * This constant is used to specify startAt/endAt values when querying for all + * descendants in a single collection. + */ +export declare const REFERENCE_NAME_MIN_ID = "__id-9223372036854775808__"; +/*! + * The query limit used for recursive deletes when fetching all descendants of + * the specified reference to delete. This is done to prevent the query stream + * from streaming documents faster than Firestore can delete. + */ +export declare const RECURSIVE_DELETE_MAX_PENDING_OPS = 5000; +/*! + * The number of pending BulkWriter operations at which RecursiveDelete + * starts the next limit query to fetch descendants. By starting the query + * while there are pending operations, Firestore can improve BulkWriter + * throughput. This helps prevent BulkWriter from idling while Firestore + * fetches the next query. + */ +export declare const RECURSIVE_DELETE_MIN_PENDING_OPS = 1000; +/** + * Class used to store state required for running a recursive delete operation. + * Each recursive delete call should use a new instance of the class. + * @private + * @internal + */ +export declare class RecursiveDelete { + private readonly firestore; + private readonly writer; + private readonly ref; + private readonly maxLimit; + private readonly minLimit; + /** + * The number of deletes that failed with a permanent error. + * @private + * @internal + */ + private errorCount; + /** + * The most recently thrown error. Used to populate the developer-facing + * error message when the recursive delete operation completes. + * @private + * @internal + */ + private lastError; + /** + * Whether there are still documents to delete that still need to be fetched. + * @private + * @internal + */ + private documentsPending; + /** + * Whether run() has been called. + * @private + * @internal + */ + private started; + /** + * Query limit to use when fetching all descendants. + * @private + * @internal + */ + private readonly maxPendingOps; + /** + * The number of pending BulkWriter operations at which RecursiveDelete + * starts the next limit query to fetch descendants. + * @private + * @internal + */ + private readonly minPendingOps; + /** + * A deferred promise that resolves when the recursive delete operation + * is completed. + * @private + * @internal + */ + private readonly completionDeferred; + /** + * Whether a query stream is currently in progress. Only one stream can be + * run at a time. + * @private + * @internal + */ + private streamInProgress; + /** + * The last document snapshot returned by the stream. Used to set the + * startAfter() field in the subsequent stream. + * @private + * @internal + */ + private lastDocumentSnap; + /** + * The number of pending BulkWriter operations. Used to determine when the + * next query can be run. + * @private + * @internal + */ + private pendingOpsCount; + private errorStack; + /** + * + * @param firestore The Firestore instance to use. + * @param writer The BulkWriter instance to use for delete operations. + * @param ref The document or collection reference to recursively delete. + * @param maxLimit The query limit to use when fetching descendants + * @param minLimit The number of pending BulkWriter operations at which + * RecursiveDelete starts the next limit query to fetch descendants. + */ + constructor(firestore: Firestore, writer: BulkWriter, ref: firestore.CollectionReference | firestore.DocumentReference, maxLimit: number, minLimit: number); + /** + * Recursively deletes the reference provided in the class constructor. + * Returns a promise that resolves when all descendants have been deleted, or + * if an error occurs. + */ + run(): Promise; + /** + * Creates a query stream and attaches event handlers to it. + * @private + * @internal + */ + private setupStream; + /** + * Retrieves all descendant documents nested under the provided reference. + * @param ref The reference to fetch all descendants for. + * @private + * @internal + * @return {Stream} Stream of descendant documents. + */ + private getAllDescendants; + /** + * Called when all descendants of the provided reference have been streamed + * or if a permanent error occurs during the stream. Deletes the developer + * provided reference and wraps any errors that occurred. + * @private + * @internal + */ + private onQueryEnd; + /** + * Deletes the provided reference and starts the next stream if conditions + * are met. + * @private + * @internal + */ + private deleteRef; + private incrementErrorCount; +} diff --git a/node_modules/@google-cloud/firestore/build/src/recursive-delete.js b/node_modules/@google-cloud/firestore/build/src/recursive-delete.js new file mode 100644 index 0000000..78f0f59 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/recursive-delete.js @@ -0,0 +1,251 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RecursiveDelete = exports.RECURSIVE_DELETE_MIN_PENDING_OPS = exports.RECURSIVE_DELETE_MAX_PENDING_OPS = exports.REFERENCE_NAME_MIN_ID = void 0; +const assert = require("assert"); +const _1 = require("."); +const util_1 = require("./util"); +const query_options_1 = require("./reference/query-options"); +/*! + * Datastore allowed numeric IDs where Firestore only allows strings. Numeric + * IDs are exposed to Firestore as __idNUM__, so this is the lowest possible + * negative numeric value expressed in that format. + * + * This constant is used to specify startAt/endAt values when querying for all + * descendants in a single collection. + */ +exports.REFERENCE_NAME_MIN_ID = '__id-9223372036854775808__'; +/*! + * The query limit used for recursive deletes when fetching all descendants of + * the specified reference to delete. This is done to prevent the query stream + * from streaming documents faster than Firestore can delete. + */ +// Visible for testing. +exports.RECURSIVE_DELETE_MAX_PENDING_OPS = 5000; +/*! + * The number of pending BulkWriter operations at which RecursiveDelete + * starts the next limit query to fetch descendants. By starting the query + * while there are pending operations, Firestore can improve BulkWriter + * throughput. This helps prevent BulkWriter from idling while Firestore + * fetches the next query. + */ +exports.RECURSIVE_DELETE_MIN_PENDING_OPS = 1000; +/** + * Class used to store state required for running a recursive delete operation. + * Each recursive delete call should use a new instance of the class. + * @private + * @internal + */ +class RecursiveDelete { + /** + * + * @param firestore The Firestore instance to use. + * @param writer The BulkWriter instance to use for delete operations. + * @param ref The document or collection reference to recursively delete. + * @param maxLimit The query limit to use when fetching descendants + * @param minLimit The number of pending BulkWriter operations at which + * RecursiveDelete starts the next limit query to fetch descendants. + */ + constructor(firestore, writer, ref, maxLimit, minLimit) { + this.firestore = firestore; + this.writer = writer; + this.ref = ref; + this.maxLimit = maxLimit; + this.minLimit = minLimit; + /** + * The number of deletes that failed with a permanent error. + * @private + * @internal + */ + this.errorCount = 0; + /** + * Whether there are still documents to delete that still need to be fetched. + * @private + * @internal + */ + this.documentsPending = true; + /** + * Whether run() has been called. + * @private + * @internal + */ + this.started = false; + /** + * A deferred promise that resolves when the recursive delete operation + * is completed. + * @private + * @internal + */ + this.completionDeferred = new util_1.Deferred(); + /** + * Whether a query stream is currently in progress. Only one stream can be + * run at a time. + * @private + * @internal + */ + this.streamInProgress = false; + /** + * The number of pending BulkWriter operations. Used to determine when the + * next query can be run. + * @private + * @internal + */ + this.pendingOpsCount = 0; + this.errorStack = ''; + this.maxPendingOps = maxLimit; + this.minPendingOps = minLimit; + } + /** + * Recursively deletes the reference provided in the class constructor. + * Returns a promise that resolves when all descendants have been deleted, or + * if an error occurs. + */ + run() { + assert(!this.started, 'RecursiveDelete.run() should only be called once.'); + // Capture the error stack to preserve stack tracing across async calls. + this.errorStack = Error().stack; + this.writer._verifyNotClosed(); + this.setupStream(); + return this.completionDeferred.promise; + } + /** + * Creates a query stream and attaches event handlers to it. + * @private + * @internal + */ + setupStream() { + const stream = this.getAllDescendants(this.ref instanceof _1.CollectionReference + ? this.ref + : this.ref); + this.streamInProgress = true; + let streamedDocsCount = 0; + stream + .on('error', err => { + err.code = 14 /* StatusCode.UNAVAILABLE */; + err.stack = 'Failed to fetch children documents: ' + err.stack; + this.lastError = err; + this.onQueryEnd(); + }) + .on('data', (snap) => { + streamedDocsCount++; + this.lastDocumentSnap = snap; + this.deleteRef(snap.ref); + }) + .on('end', () => { + this.streamInProgress = false; + // If there are fewer than the number of documents specified in the + // limit() field, we know that the query is complete. + if (streamedDocsCount < this.minPendingOps) { + this.onQueryEnd(); + } + else if (this.pendingOpsCount === 0) { + this.setupStream(); + } + }); + } + /** + * Retrieves all descendant documents nested under the provided reference. + * @param ref The reference to fetch all descendants for. + * @private + * @internal + * @return {Stream} Stream of descendant documents. + */ + getAllDescendants(ref) { + // The parent is the closest ancestor document to the location we're + // deleting. If we are deleting a document, the parent is the path of that + // document. If we are deleting a collection, the parent is the path of the + // document containing that collection (or the database root, if it is a + // root collection). + let parentPath = ref._resourcePath; + if (ref instanceof _1.CollectionReference) { + parentPath = parentPath.popLast(); + } + const collectionId = ref instanceof _1.CollectionReference + ? ref.id + : ref.parent.id; + let query = new _1.Query(this.firestore, query_options_1.QueryOptions.forKindlessAllDescendants(parentPath, collectionId, + /* requireConsistency= */ false)); + // Query for names only to fetch empty snapshots. + query = query.select(_1.FieldPath.documentId()).limit(this.maxPendingOps); + if (ref instanceof _1.CollectionReference) { + // To find all descendants of a collection reference, we need to use a + // composite filter that captures all documents that start with the + // collection prefix. The MIN_KEY constant represents the minimum key in + // this collection, and a null byte + the MIN_KEY represents the minimum + // key is the next possible collection. + const nullChar = String.fromCharCode(0); + const startAt = collectionId + '/' + exports.REFERENCE_NAME_MIN_ID; + const endAt = collectionId + nullChar + '/' + exports.REFERENCE_NAME_MIN_ID; + query = query + .where(_1.FieldPath.documentId(), '>=', startAt) + .where(_1.FieldPath.documentId(), '<', endAt); + } + if (this.lastDocumentSnap) { + query = query.startAfter(this.lastDocumentSnap); + } + return query.stream(); + } + /** + * Called when all descendants of the provided reference have been streamed + * or if a permanent error occurs during the stream. Deletes the developer + * provided reference and wraps any errors that occurred. + * @private + * @internal + */ + onQueryEnd() { + this.documentsPending = false; + if (this.ref instanceof _1.DocumentReference) { + this.writer.delete(this.ref).catch(err => this.incrementErrorCount(err)); + } + this.writer.flush().then(async () => { + var _a; + if (this.lastError === undefined) { + this.completionDeferred.resolve(); + } + else { + let error = new (require('google-gax/build/src/fallback').GoogleError)(`${this.errorCount} ` + + `${this.errorCount !== 1 ? 'deletes' : 'delete'} ` + + 'failed. The last delete failed with: '); + if (this.lastError.code !== undefined) { + error.code = this.lastError.code; + } + error = (0, util_1.wrapError)(error, this.errorStack); + // Wrap the BulkWriter error last to provide the full stack trace. + this.completionDeferred.reject(this.lastError.stack + ? (0, util_1.wrapError)(error, (_a = this.lastError.stack) !== null && _a !== void 0 ? _a : '') + : error); + } + }); + } + /** + * Deletes the provided reference and starts the next stream if conditions + * are met. + * @private + * @internal + */ + deleteRef(docRef) { + this.pendingOpsCount++; + this.writer + .delete(docRef) + .catch(err => { + this.incrementErrorCount(err); + }) + .then(() => { + this.pendingOpsCount--; + // We wait until the previous stream has ended in order to sure the + // startAfter document is correct. Starting the next stream while + // there are pending operations allows Firestore to maximize + // BulkWriter throughput. + if (this.documentsPending && + !this.streamInProgress && + this.pendingOpsCount < this.minPendingOps) { + this.setupStream(); + } + }); + } + incrementErrorCount(err) { + this.errorCount++; + this.lastError = err; + } +} +exports.RecursiveDelete = RecursiveDelete; +//# sourceMappingURL=recursive-delete.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/reference/aggregate-query-snapshot.d.ts b/node_modules/@google-cloud/firestore/build/src/reference/aggregate-query-snapshot.d.ts new file mode 100644 index 0000000..6390438 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/aggregate-query-snapshot.d.ts @@ -0,0 +1,63 @@ +/** + * Copyright 2024 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. + */ +import * as firestore from '@google-cloud/firestore'; +import { Timestamp } from '../timestamp'; +import { AggregateQuery } from './aggregate-query'; +/** + * The results of executing an aggregation query. + */ +export declare class AggregateQuerySnapshot implements firestore.AggregateQuerySnapshot { + private readonly _query; + private readonly _readTime; + private readonly _data; + /** + * @internal + * + * @param _query The query that was executed to produce this result. + * @param _readTime The time this snapshot was read. + * @param _data The results of the aggregations performed over the underlying + * query. + */ + constructor(_query: AggregateQuery, _readTime: Timestamp, _data: firestore.AggregateSpecData); + /** The query that was executed to produce this result. */ + get query(): AggregateQuery; + /** The time this snapshot was read. */ + get readTime(): Timestamp; + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the + * values will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): firestore.AggregateSpecData; + /** + * Compares this object with the given object for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they + * have the same data and their underlying queries compare "equal" using + * `AggregateQuery.isEqual()`. + * + * @param other The object to compare to this object for equality. + * @return `true` if this object is "equal" to the given object, as + * defined above, or `false` otherwise. + */ + isEqual(other: firestore.AggregateQuerySnapshot): boolean; +} diff --git a/node_modules/@google-cloud/firestore/build/src/reference/aggregate-query-snapshot.js b/node_modules/@google-cloud/firestore/build/src/reference/aggregate-query-snapshot.js new file mode 100644 index 0000000..e2ea019 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/aggregate-query-snapshot.js @@ -0,0 +1,87 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AggregateQuerySnapshot = void 0; +const deepEqual = require("fast-deep-equal"); +/** + * The results of executing an aggregation query. + */ +class AggregateQuerySnapshot { + /** + * @internal + * + * @param _query The query that was executed to produce this result. + * @param _readTime The time this snapshot was read. + * @param _data The results of the aggregations performed over the underlying + * query. + */ + constructor(_query, _readTime, _data) { + this._query = _query; + this._readTime = _readTime; + this._data = _data; + } + /** The query that was executed to produce this result. */ + get query() { + return this._query; + } + /** The time this snapshot was read. */ + get readTime() { + return this._readTime; + } + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the + * values will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data() { + return this._data; + } + /** + * Compares this object with the given object for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they + * have the same data and their underlying queries compare "equal" using + * `AggregateQuery.isEqual()`. + * + * @param other The object to compare to this object for equality. + * @return `true` if this object is "equal" to the given object, as + * defined above, or `false` otherwise. + */ + isEqual(other) { + if (this === other) { + return true; + } + if (!(other instanceof AggregateQuerySnapshot)) { + return false; + } + // Since the read time is different on every read, we explicitly ignore all + // document metadata in this comparison, just like + // `DocumentSnapshot.isEqual()` does. + if (!this.query.isEqual(other.query)) { + return false; + } + return deepEqual(this._data, other._data); + } +} +exports.AggregateQuerySnapshot = AggregateQuerySnapshot; +//# sourceMappingURL=aggregate-query-snapshot.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/reference/aggregate-query.d.ts b/node_modules/@google-cloud/firestore/build/src/reference/aggregate-query.d.ts new file mode 100644 index 0000000..0459dde --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/aggregate-query.d.ts @@ -0,0 +1,119 @@ +/** + * Copyright 2024 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. + */ +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; +import * as firestore from '@google-cloud/firestore'; +import { AggregateSpec } from '../aggregate'; +import { Timestamp } from '../timestamp'; +import { ExplainResults } from '../query-profile'; +import { AggregateQuerySnapshot } from './aggregate-query-snapshot'; +import { Query } from './query'; +import { Readable } from 'stream'; +import { QueryResponse, QuerySnapshotResponse } from './types'; +/** + * A query that calculates aggregations over an underlying query. + */ +export declare class AggregateQuery implements firestore.AggregateQuery { + private readonly _query; + private readonly _aggregates; + private readonly clientAliasToServerAliasMap; + private readonly serverAliasToClientAliasMap; + /** + * @internal + * @param _query The query whose aggregations will be calculated by this + * object. + * @param _aggregates The aggregations that will be performed by this query. + */ + constructor(_query: Query, _aggregates: AggregateSpecType); + /** The query whose aggregations will be calculated by this object. */ + get query(): Query; + /** + * Executes this query. + * + * @return A promise that will be resolved with the results of the query. + */ + get(): Promise>; + /** + * Internal get() method that accepts an optional transaction options and + * returns a snapshot with transaction and explain metadata. + * + * @private + * @internal + * @param transactionOrReadTime A transaction ID, options to start a new + * transaction, or timestamp to use as read time. + */ + _get(transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions): Promise>>; + /** + * Internal get() method that accepts an optional transaction id, and returns + * transaction metadata. + * + * @private + * @internal + * @param transactionOrReadTime A transaction ID, options to start a new + * transaction, or timestamp to use as read time. + */ + _getResponse(transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, explainOptions?: firestore.ExplainOptions): Promise>>; + /** + * Internal streaming method that accepts an optional transaction ID. + * + * BEWARE: If `transactionOrReadTime` is `ITransactionOptions`, then the first + * response in the stream will be a transaction response. + * + * @private + * @internal + * @param transactionOrReadTime A transaction ID, options to start a new + * transaction, or timestamp to use as read time. + * @param explainOptions Options to use for explaining the query (if any). + * @returns A stream of document results optionally preceded by a transaction response. + */ + _stream(transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, explainOptions?: firestore.ExplainOptions): Readable; + /** + * Internal method to decode values within result. + * @private + */ + private decodeResult; + /** + * Internal method for serializing a query to its RunAggregationQuery proto + * representation with an optional transaction id. + * + * @private + * @internal + * @returns Serialized JSON for the query. + */ + toProto(transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, explainOptions?: firestore.ExplainOptions): api.IRunAggregationQueryRequest; + /** + * Compares this object with the given object for equality. + * + * This object is considered "equal" to the other object if and only if + * `other` performs the same aggregations as this `AggregateQuery` and + * the underlying Query of `other` compares equal to that of this object + * using `Query.isEqual()`. + * + * @param other The object to compare to this object for equality. + * @return `true` if this object is "equal" to the given object, as + * defined above, or `false` otherwise. + */ + isEqual(other: firestore.AggregateQuery): boolean; + /** + * Plans and optionally executes this query. Returns a Promise that will be + * resolved with the planner information, statistics from the query + * execution (if any), and the query results (if any). + * + * @return A Promise that will be resolved with the planner information, + * statistics from the query execution (if any), and the query results (if any). + */ + explain(options?: firestore.ExplainOptions): Promise>>; +} diff --git a/node_modules/@google-cloud/firestore/build/src/reference/aggregate-query.js b/node_modules/@google-cloud/firestore/build/src/reference/aggregate-query.js new file mode 100644 index 0000000..f7944ee --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/aggregate-query.js @@ -0,0 +1,291 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AggregateQuery = void 0; +const assert = require("assert"); +const deepEqual = require("fast-deep-equal"); +const aggregate_1 = require("../aggregate"); +const timestamp_1 = require("../timestamp"); +const util_1 = require("../util"); +const query_profile_1 = require("../query-profile"); +const logger_1 = require("../logger"); +const aggregate_query_snapshot_1 = require("./aggregate-query-snapshot"); +const stream_1 = require("stream"); +const trace_util_1 = require("../telemetry/trace-util"); +/** + * A query that calculates aggregations over an underlying query. + */ +class AggregateQuery { + /** + * @internal + * @param _query The query whose aggregations will be calculated by this + * object. + * @param _aggregates The aggregations that will be performed by this query. + */ + constructor( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _query, _aggregates) { + this._query = _query; + this._aggregates = _aggregates; + this.clientAliasToServerAliasMap = {}; + this.serverAliasToClientAliasMap = {}; + // Client-side aliases may be too long and exceed the 1500-byte string size limit. + // Such long strings do not need to be transferred over the wire either. + // The client maps the user's alias to a short form alias and send that to the server. + let aggregationNum = 0; + for (const clientAlias in this._aggregates) { + if (Object.prototype.hasOwnProperty.call(this._aggregates, clientAlias)) { + const serverAlias = `aggregate_${aggregationNum++}`; + this.clientAliasToServerAliasMap[clientAlias] = serverAlias; + this.serverAliasToClientAliasMap[serverAlias] = clientAlias; + } + } + } + /** The query whose aggregations will be calculated by this object. */ + get query() { + return this._query; + } + /** + * Executes this query. + * + * @return A promise that will be resolved with the results of the query. + */ + async get() { + return this._query._firestore._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_AGGREGATION_QUERY_GET, async () => { + const { result } = await this._get(); + return result; + }); + } + /** + * Internal get() method that accepts an optional transaction options and + * returns a snapshot with transaction and explain metadata. + * + * @private + * @internal + * @param transactionOrReadTime A transaction ID, options to start a new + * transaction, or timestamp to use as read time. + */ + async _get(transactionOrReadTime) { + const response = await this._getResponse(transactionOrReadTime); + if (!response.result) { + throw new Error('No AggregateQuery results'); + } + return response; + } + /** + * Internal get() method that accepts an optional transaction id, and returns + * transaction metadata. + * + * @private + * @internal + * @param transactionOrReadTime A transaction ID, options to start a new + * transaction, or timestamp to use as read time. + */ + _getResponse(transactionOrReadTime, explainOptions) { + // Capture the error stack to preserve stack tracing across async calls. + const stack = Error().stack; + return new Promise((resolve, reject) => { + const output = {}; + const stream = this._stream(transactionOrReadTime, explainOptions); + stream.on('error', err => { + reject((0, util_1.wrapError)(err, stack)); + }); + stream.on('data', (data) => { + if (data.transaction) { + output.transaction = data.transaction; + } + if (data.explainMetrics) { + output.explainMetrics = data.explainMetrics; + } + if (data.result) { + output.result = data.result; + } + }); + stream.on('end', () => { + stream.destroy(); + resolve(output); + }); + }); + } + /** + * Internal streaming method that accepts an optional transaction ID. + * + * BEWARE: If `transactionOrReadTime` is `ITransactionOptions`, then the first + * response in the stream will be a transaction response. + * + * @private + * @internal + * @param transactionOrReadTime A transaction ID, options to start a new + * transaction, or timestamp to use as read time. + * @param explainOptions Options to use for explaining the query (if any). + * @returns A stream of document results optionally preceded by a transaction response. + */ + _stream(transactionOrReadTime, explainOptions) { + const tag = (0, util_1.requestTag)(); + const firestore = this._query.firestore; + const stream = new stream_1.Transform({ + objectMode: true, + transform: (proto, enc, callback) => { + var _a; + const output = {}; + // Proto comes with zero-length buffer by default + if ((_a = proto.transaction) === null || _a === void 0 ? void 0 : _a.length) { + output.transaction = proto.transaction; + } + if (proto.explainMetrics) { + output.explainMetrics = query_profile_1.ExplainMetrics._fromProto(proto.explainMetrics, firestore._serializer); + } + if (proto.result) { + const readTime = timestamp_1.Timestamp.fromProto(proto.readTime); + const data = this.decodeResult(proto.result); + output.result = new aggregate_query_snapshot_1.AggregateQuerySnapshot(this, readTime, data); + } + callback(undefined, output); + }, + }); + firestore + .initializeIfNeeded(tag) + .then(async () => { + // `toProto()` might throw an exception. We rely on the behavior of an + // async function to convert this exception into the rejected Promise we + // catch below. + const request = this.toProto(transactionOrReadTime, explainOptions); + const backendStream = await firestore.requestStream('runAggregationQuery', + /* bidirectional= */ false, request, tag); + stream.on('close', () => { + backendStream.resume(); + backendStream.end(); + }); + backendStream.on('error', err => { + // TODO(group-by) When group-by queries are supported for aggregates + // consider implementing retries if the stream is making progress + // receiving results for groups. See the use of lastReceivedDocument + // in the retry strategy for runQuery. + // Also note that explain queries should not be retried. + backendStream.unpipe(stream); + (0, logger_1.logger)('AggregateQuery._stream', tag, 'AggregateQuery failed with stream error:', err); + this._query._firestore._traceUtil + .currentSpan() + .addEvent(`${trace_util_1.SPAN_NAME_RUN_AGGREGATION_QUERY}: Error.`, { + 'error.message': err.message, + }); + stream.destroy(err); + }); + backendStream.resume(); + backendStream.pipe(stream); + }) + .catch(e => stream.destroy(e)); + return stream; + } + /** + * Internal method to decode values within result. + * @private + */ + decodeResult(proto) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const data = {}; + const fields = proto.aggregateFields; + if (fields) { + const serializer = this._query.firestore._serializer; + for (const prop of Object.keys(fields)) { + const alias = this.serverAliasToClientAliasMap[prop]; + assert(alias !== null && alias !== undefined, `'${prop}' not present in server-client alias mapping.`); + if (this._aggregates[alias] === undefined) { + throw new Error(`Unexpected alias [${prop}] in result aggregate result`); + } + data[alias] = serializer.decodeValue(fields[prop]); + } + } + return data; + } + /** + * Internal method for serializing a query to its RunAggregationQuery proto + * representation with an optional transaction id. + * + * @private + * @internal + * @returns Serialized JSON for the query. + */ + toProto(transactionOrReadTime, explainOptions) { + const queryProto = this._query.toProto(); + const runQueryRequest = { + parent: queryProto.parent, + structuredAggregationQuery: { + structuredQuery: queryProto.structuredQuery, + aggregations: (0, util_1.mapToArray)(this._aggregates, (aggregate, clientAlias) => { + const serverAlias = this.clientAliasToServerAliasMap[clientAlias]; + assert(serverAlias !== null && serverAlias !== undefined, `'${clientAlias}' not present in client-server alias mapping.`); + return new aggregate_1.Aggregate(serverAlias, aggregate.aggregateType, aggregate._field).toProto(); + }), + }, + }; + if (transactionOrReadTime instanceof Uint8Array) { + runQueryRequest.transaction = transactionOrReadTime; + } + else if (transactionOrReadTime instanceof timestamp_1.Timestamp) { + runQueryRequest.readTime = transactionOrReadTime.toProto().timestampValue; + } + else if (transactionOrReadTime) { + runQueryRequest.newTransaction = transactionOrReadTime; + } + if (explainOptions) { + runQueryRequest.explainOptions = explainOptions; + } + return runQueryRequest; + } + /** + * Compares this object with the given object for equality. + * + * This object is considered "equal" to the other object if and only if + * `other` performs the same aggregations as this `AggregateQuery` and + * the underlying Query of `other` compares equal to that of this object + * using `Query.isEqual()`. + * + * @param other The object to compare to this object for equality. + * @return `true` if this object is "equal" to the given object, as + * defined above, or `false` otherwise. + */ + isEqual(other) { + if (this === other) { + return true; + } + if (!(other instanceof AggregateQuery)) { + return false; + } + if (!this.query.isEqual(other.query)) { + return false; + } + return deepEqual(this._aggregates, other._aggregates); + } + /** + * Plans and optionally executes this query. Returns a Promise that will be + * resolved with the planner information, statistics from the query + * execution (if any), and the query results (if any). + * + * @return A Promise that will be resolved with the planner information, + * statistics from the query execution (if any), and the query results (if any). + */ + async explain(options) { + const { result, explainMetrics } = await this._getResponse(undefined, options || {}); + if (!explainMetrics) { + throw new Error('No explain results'); + } + return new query_profile_1.ExplainResults(explainMetrics, result || null); + } +} +exports.AggregateQuery = AggregateQuery; +//# sourceMappingURL=aggregate-query.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/reference/collection-reference.d.ts b/node_modules/@google-cloud/firestore/build/src/reference/collection-reference.d.ts new file mode 100644 index 0000000..66e2a07 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/collection-reference.d.ts @@ -0,0 +1,150 @@ +/** + * Copyright 2024 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. + */ +import * as firestore from '@google-cloud/firestore'; +import { ResourcePath } from '../path'; +import { Query } from './query'; +import Firestore from '../index'; +import { DocumentReference } from './document-reference'; +/** + * A CollectionReference object can be used for adding documents, getting + * document references, and querying for documents (using the methods + * inherited from [Query]{@link Query}). + * + * @class CollectionReference + * @extends Query + */ +export declare class CollectionReference extends Query implements firestore.CollectionReference { + /** + * @private + * + * @param firestore The Firestore Database client. + * @param path The Path of this collection. + */ + constructor(firestore: Firestore, path: ResourcePath, converter?: firestore.FirestoreDataConverter); + /** + * Returns a resource path for this collection. + * @private + * @internal + */ + get _resourcePath(): ResourcePath; + /** + * The last path element of the referenced collection. + * + * @type {string} + * @name CollectionReference#id + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col/doc/subcollection'); + * console.log(`ID of the subcollection: ${collectionRef.id}`); + * ``` + */ + get id(): string; + /** + * A reference to the containing Document if this is a subcollection, else + * null. + * + * @type {DocumentReference|null} + * @name CollectionReference#parent + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col/doc/subcollection'); + * let documentRef = collectionRef.parent; + * console.log(`Parent name: ${documentRef.path}`); + * ``` + */ + get parent(): DocumentReference | null; + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + * + * @type {string} + * @name CollectionReference#path + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col/doc/subcollection'); + * console.log(`Path of the subcollection: ${collectionRef.path}`); + * ``` + */ + get path(): string; + /** + * Retrieves the list of documents in this collection. + * + * The document references returned may include references to "missing + * documents", i.e. document locations that have no document present but + * which contain subcollections with documents. Attempting to read such a + * document reference (e.g. via `.get()` or `.onSnapshot()`) will return a + * `DocumentSnapshot` whose `.exists` property is false. + * + * @return {Promise} The list of documents in this + * collection. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * return collectionRef.listDocuments().then(documentRefs => { + * return firestore.getAll(...documentRefs); + * }).then(documentSnapshots => { + * for (let documentSnapshot of documentSnapshots) { + * if (documentSnapshot.exists) { + * console.log(`Found document with data: ${documentSnapshot.id}`); + * } else { + * console.log(`Found missing document: ${documentSnapshot.id}`); + * } + * } + * }); + * ``` + */ + listDocuments(): Promise>>; + doc(): DocumentReference; + doc(documentPath: string): DocumentReference; + /** + * Add a new document to this collection with the specified data, assigning + * it a document ID automatically. + * + * @param {DocumentData} data An Object containing the data for the new + * document. + * @throws {Error} If the provided input is not a valid Firestore document. + * @returns {Promise.} A Promise resolved with a + * [DocumentReference]{@link DocumentReference} pointing to the + * newly created document. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * collectionRef.add({foo: 'bar'}).then(documentReference => { + * console.log(`Added document with name: ${documentReference.id}`); + * }); + * ``` + */ + add(data: firestore.WithFieldValue): Promise>; + /** + * Returns true if this `CollectionReference` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @return {boolean} true if this `CollectionReference` is equal to the + * provided value. + */ + isEqual(other: firestore.CollectionReference): boolean; + withConverter(converter: null): CollectionReference; + withConverter(converter: firestore.FirestoreDataConverter): CollectionReference; +} diff --git a/node_modules/@google-cloud/firestore/build/src/reference/collection-reference.js b/node_modules/@google-cloud/firestore/build/src/reference/collection-reference.js new file mode 100644 index 0000000..c94f79a --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/collection-reference.js @@ -0,0 +1,287 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CollectionReference = void 0; +const path_1 = require("../path"); +const util_1 = require("../util"); +const write_batch_1 = require("../write-batch"); +const types_1 = require("../types"); +const query_1 = require("./query"); +const document_reference_1 = require("./document-reference"); +const query_options_1 = require("./query-options"); +const trace_util_1 = require("../telemetry/trace-util"); +/** + * A CollectionReference object can be used for adding documents, getting + * document references, and querying for documents (using the methods + * inherited from [Query]{@link Query}). + * + * @class CollectionReference + * @extends Query + */ +class CollectionReference extends query_1.Query { + /** + * @private + * + * @param firestore The Firestore Database client. + * @param path The Path of this collection. + */ + constructor(firestore, path, converter) { + super(firestore, query_options_1.QueryOptions.forCollectionQuery(path, converter)); + } + /** + * Returns a resource path for this collection. + * @private + * @internal + */ + get _resourcePath() { + return this._queryOptions.parentPath.append(this._queryOptions.collectionId); + } + /** + * The last path element of the referenced collection. + * + * @type {string} + * @name CollectionReference#id + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col/doc/subcollection'); + * console.log(`ID of the subcollection: ${collectionRef.id}`); + * ``` + */ + get id() { + return this._queryOptions.collectionId; + } + /** + * A reference to the containing Document if this is a subcollection, else + * null. + * + * @type {DocumentReference|null} + * @name CollectionReference#parent + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col/doc/subcollection'); + * let documentRef = collectionRef.parent; + * console.log(`Parent name: ${documentRef.path}`); + * ``` + */ + get parent() { + if (this._queryOptions.parentPath.isDocument) { + return new document_reference_1.DocumentReference(this.firestore, this._queryOptions.parentPath); + } + return null; + } + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + * + * @type {string} + * @name CollectionReference#path + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col/doc/subcollection'); + * console.log(`Path of the subcollection: ${collectionRef.path}`); + * ``` + */ + get path() { + return this._resourcePath.relativeName; + } + /** + * Retrieves the list of documents in this collection. + * + * The document references returned may include references to "missing + * documents", i.e. document locations that have no document present but + * which contain subcollections with documents. Attempting to read such a + * document reference (e.g. via `.get()` or `.onSnapshot()`) will return a + * `DocumentSnapshot` whose `.exists` property is false. + * + * @return {Promise} The list of documents in this + * collection. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * return collectionRef.listDocuments().then(documentRefs => { + * return firestore.getAll(...documentRefs); + * }).then(documentSnapshots => { + * for (let documentSnapshot of documentSnapshots) { + * if (documentSnapshot.exists) { + * console.log(`Found document with data: ${documentSnapshot.id}`); + * } else { + * console.log(`Found missing document: ${documentSnapshot.id}`); + * } + * } + * }); + * ``` + */ + listDocuments() { + return this._firestore._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_COL_REF_LIST_DOCUMENTS, () => { + const tag = (0, util_1.requestTag)(); + return this.firestore.initializeIfNeeded(tag).then(() => { + const parentPath = this._queryOptions.parentPath.toQualifiedResourcePath(this.firestore.projectId, this.firestore.databaseId); + const request = { + parent: parentPath.formattedName, + collectionId: this.id, + showMissing: true, + mask: { fieldPaths: [] }, + }; + return this.firestore + .request('listDocuments', request, tag) + .then(documents => { + // Note that the backend already orders these documents by name, + // so we do not need to manually sort them. + return documents.map(doc => { + const path = path_1.QualifiedResourcePath.fromSlashSeparatedString(doc.name); + return this.doc(path.id); + }); + }); + }); + }); + } + /** + * Gets a [DocumentReference]{@link DocumentReference} instance that + * refers to the document at the specified path. If no path is specified, an + * automatically-generated unique ID will be used for the returned + * DocumentReference. + * + * @param {string=} documentPath A slash-separated path to a document. + * @returns {DocumentReference} The `DocumentReference` + * instance. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * let documentRefWithName = collectionRef.doc('doc'); + * let documentRefWithAutoId = collectionRef.doc(); + * console.log(`Reference with name: ${documentRefWithName.path}`); + * console.log(`Reference with auto-id: ${documentRefWithAutoId.path}`); + * ``` + */ + doc(documentPath) { + if (arguments.length === 0) { + documentPath = (0, util_1.autoId)(); + } + else { + (0, path_1.validateResourcePath)('documentPath', documentPath); + } + const path = this._resourcePath.append(documentPath); + if (!path.isDocument) { + throw new Error(`Value for argument "documentPath" must point to a document, but was "${documentPath}". Your path does not contain an even number of components.`); + } + return new document_reference_1.DocumentReference(this.firestore, path, this._queryOptions.converter); + } + /** + * Add a new document to this collection with the specified data, assigning + * it a document ID automatically. + * + * @param {DocumentData} data An Object containing the data for the new + * document. + * @throws {Error} If the provided input is not a valid Firestore document. + * @returns {Promise.} A Promise resolved with a + * [DocumentReference]{@link DocumentReference} pointing to the + * newly created document. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * collectionRef.add({foo: 'bar'}).then(documentReference => { + * console.log(`Added document with name: ${documentReference.id}`); + * }); + * ``` + */ + add(data) { + return this._firestore._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_COL_REF_ADD, () => { + const firestoreData = this._queryOptions.converter.toFirestore(data); + (0, write_batch_1.validateDocumentData)('data', firestoreData, + /*allowDeletes=*/ false, this._allowUndefined); + const documentRef = this.doc(); + return documentRef.create(data).then(() => documentRef); + }); + } + /** + * Returns true if this `CollectionReference` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @return {boolean} true if this `CollectionReference` is equal to the + * provided value. + */ + isEqual(other) { + return (this === other || + (other instanceof CollectionReference && super.isEqual(other))); + } + /** + * Applies a custom data converter to this CollectionReference, allowing you + * to use your own custom model objects with Firestore. When you call add() on + * the returned CollectionReference instance, the provided converter will + * convert between Firestore data of type `NewDbModelType` and your custom + * type `NewAppModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * Passing in `null` as the converter parameter removes the current + * converter. + * + * @example + * ``` + * class Post { + * constructor(readonly title: string, readonly author: string) {} + * + * toString(): string { + * return this.title + ', by ' + this.author; + * } + * } + * + * const postConverter = { + * toFirestore(post: Post): FirebaseFirestore.DocumentData { + * return {title: post.title, author: post.author}; + * }, + * fromFirestore( + * snapshot: FirebaseFirestore.QueryDocumentSnapshot + * ): Post { + * const data = snapshot.data(); + * return new Post(data.title, data.author); + * } + * }; + * + * const postSnap = await Firestore() + * .collection('posts') + * .withConverter(postConverter) + * .doc().get(); + * const post = postSnap.data(); + * if (post !== undefined) { + * post.title; // string + * post.toString(); // Should be defined + * post.someNonExistentProperty; // TS error + * } + * + * ``` + * @param {FirestoreDataConverter | null} converter Converts objects to and + * from Firestore. Passing in `null` removes the current converter. + * @return A CollectionReference that uses the provided converter. + */ + withConverter(converter) { + return new CollectionReference(this.firestore, this._resourcePath, converter !== null && converter !== void 0 ? converter : (0, types_1.defaultConverter)()); + } +} +exports.CollectionReference = CollectionReference; +//# sourceMappingURL=collection-reference.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/reference/composite-filter-internal.d.ts b/node_modules/@google-cloud/firestore/build/src/reference/composite-filter-internal.d.ts new file mode 100644 index 0000000..b73d67d --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/composite-filter-internal.d.ts @@ -0,0 +1,30 @@ +/** + * Copyright 2024 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. + */ +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; +import { FilterInternal } from './filter-internal'; +import { FieldFilterInternal } from './field-filter-internal'; +export declare class CompositeFilterInternal extends FilterInternal { + private filters; + private operator; + constructor(filters: FilterInternal[], operator: api.StructuredQuery.CompositeFilter.Operator); + private memoizedFlattenedFilters; + getFilters(): FilterInternal[]; + isConjunction(): boolean; + getFlattenedFilters(): FieldFilterInternal[]; + toProto(): api.StructuredQuery.IFilter; + isEqual(other: FilterInternal): boolean; +} diff --git a/node_modules/@google-cloud/firestore/build/src/reference/composite-filter-internal.js b/node_modules/@google-cloud/firestore/build/src/reference/composite-filter-internal.js new file mode 100644 index 0000000..a16566a --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/composite-filter-internal.js @@ -0,0 +1,67 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CompositeFilterInternal = void 0; +const filter_internal_1 = require("./filter-internal"); +class CompositeFilterInternal extends filter_internal_1.FilterInternal { + constructor(filters, operator) { + super(); + this.filters = filters; + this.operator = operator; + // Memoized list of all field filters that can be found by traversing the tree of filters + // contained in this composite filter. + this.memoizedFlattenedFilters = null; + } + getFilters() { + return this.filters; + } + isConjunction() { + return this.operator === 'AND'; + } + getFlattenedFilters() { + if (this.memoizedFlattenedFilters !== null) { + return this.memoizedFlattenedFilters; + } + this.memoizedFlattenedFilters = this.filters.reduce((allFilters, subfilter) => allFilters.concat(subfilter.getFlattenedFilters()), []); + return this.memoizedFlattenedFilters; + } + toProto() { + if (this.filters.length === 1) { + return this.filters[0].toProto(); + } + const proto = { + compositeFilter: { + op: this.operator, + filters: this.filters.map(filter => filter.toProto()), + }, + }; + return proto; + } + isEqual(other) { + if (other instanceof CompositeFilterInternal) { + const otherFilters = other.getFilters(); + return (this.operator === other.operator && + this.getFilters().length === other.getFilters().length && + this.getFilters().every((filter, index) => filter.isEqual(otherFilters[index]))); + } + else { + return false; + } + } +} +exports.CompositeFilterInternal = CompositeFilterInternal; +//# sourceMappingURL=composite-filter-internal.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/reference/constants.d.ts b/node_modules/@google-cloud/firestore/build/src/reference/constants.d.ts new file mode 100644 index 0000000..81e1925 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/constants.d.ts @@ -0,0 +1,39 @@ +/** + * Copyright 2024 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. + */ +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; +/** + * The direction of a `Query.orderBy()` clause is specified as 'desc' or 'asc' + * (descending or ascending). + * + * @private + * @internal + */ +export declare const directionOperators: { + [k: string]: api.StructuredQuery.Direction; +}; +/** + * Filter conditions in a `Query.where()` clause are specified using the + * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', 'not-in', + * and 'array-contains-any'. + * + * @private + * @internal + */ +export declare const comparisonOperators: { + [k: string]: api.StructuredQuery.FieldFilter.Operator; +}; +export declare const NOOP_MESSAGE: unique symbol; diff --git a/node_modules/@google-cloud/firestore/build/src/reference/constants.js b/node_modules/@google-cloud/firestore/build/src/reference/constants.js new file mode 100644 index 0000000..0259ef4 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/constants.js @@ -0,0 +1,51 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NOOP_MESSAGE = exports.comparisonOperators = exports.directionOperators = void 0; +/** + * The direction of a `Query.orderBy()` clause is specified as 'desc' or 'asc' + * (descending or ascending). + * + * @private + * @internal + */ +exports.directionOperators = { + asc: 'ASCENDING', + desc: 'DESCENDING', +}; +/** + * Filter conditions in a `Query.where()` clause are specified using the + * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', 'not-in', + * and 'array-contains-any'. + * + * @private + * @internal + */ +exports.comparisonOperators = { + '<': 'LESS_THAN', + '<=': 'LESS_THAN_OR_EQUAL', + '==': 'EQUAL', + '!=': 'NOT_EQUAL', + '>': 'GREATER_THAN', + '>=': 'GREATER_THAN_OR_EQUAL', + 'array-contains': 'ARRAY_CONTAINS', + in: 'IN', + 'not-in': 'NOT_IN', + 'array-contains-any': 'ARRAY_CONTAINS_ANY', +}; +exports.NOOP_MESSAGE = Symbol('a noop message'); +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/reference/document-reference.d.ts b/node_modules/@google-cloud/firestore/build/src/reference/document-reference.d.ts new file mode 100644 index 0000000..b22d02e --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/document-reference.d.ts @@ -0,0 +1,332 @@ +/** + * Copyright 2024 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. + */ +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; +import * as firestore from '@google-cloud/firestore'; +import Firestore, { DocumentSnapshot, WriteResult } from '../index'; +import { ResourcePath } from '../path'; +import { Serializable } from '../serializer'; +import { CollectionReference } from './collection-reference'; +/** + * A DocumentReference refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. A DocumentReference can + * also be used to create a + * [CollectionReference]{@link CollectionReference} to a + * subcollection. + * + * @class DocumentReference + */ +export declare class DocumentReference implements Serializable, firestore.DocumentReference { + private readonly _firestore; + /** + * @private + * @internal + **/ + readonly _path: ResourcePath; + /** + * @internal + * @private + **/ + readonly _converter: firestore.FirestoreDataConverter; + /** + * @private + * @internal + * @param _firestore The Firestore Database client. + * @param _path The Path of this reference. + * @param _converter The converter to use when serializing data. + */ + constructor(_firestore: Firestore, + /** + * @private + * @internal + **/ + _path: ResourcePath, + /** + * @internal + * @private + **/ + _converter?: firestore.FirestoreDataConverter); + /** + * The string representation of the DocumentReference's location. + * @private + * @internal + * @type {string} + * @name DocumentReference#formattedName + */ + get formattedName(): string; + /** + * The [Firestore]{@link Firestore} instance for the Firestore + * database (useful for performing transactions, etc.). + * + * @type {Firestore} + * @name DocumentReference#firestore + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.add({foo: 'bar'}).then(documentReference => { + * let firestore = documentReference.firestore; + * console.log(`Root location for document is ${firestore.formattedName}`); + * }); + * ``` + */ + get firestore(): Firestore; + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + * + * @type {string} + * @name DocumentReference#path + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.add({foo: 'bar'}).then(documentReference => { + * console.log(`Added document at '${documentReference.path}'`); + * }); + * ``` + */ + get path(): string; + /** + * The last path element of the referenced document. + * + * @type {string} + * @name DocumentReference#id + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.add({foo: 'bar'}).then(documentReference => { + * console.log(`Added document with name '${documentReference.id}'`); + * }); + * ``` + */ + get id(): string; + /** + * Returns a resource path for this document. + * @private + * @internal + */ + get _resourcePath(): ResourcePath; + /** + * A reference to the collection to which this DocumentReference belongs. + * + * @name DocumentReference#parent + * @type {CollectionReference} + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * let collectionRef = documentRef.parent; + * + * collectionRef.where('foo', '==', 'bar').get().then(results => { + * console.log(`Found ${results.size} matches in parent collection`); + * }): + * ``` + */ + get parent(): CollectionReference; + /** + * Reads the document referred to by this DocumentReference. + * + * @returns {Promise.} A Promise resolved with a + * DocumentSnapshot for the retrieved document on success. For missing + * documents, DocumentSnapshot.exists will be false. If the get() fails for + * other reasons, the Promise will be rejected. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(documentSnapshot => { + * if (documentSnapshot.exists) { + * console.log('Document retrieved successfully.'); + * } + * }); + * ``` + */ + get(): Promise>; + /** + * Gets a [CollectionReference]{@link CollectionReference} instance + * that refers to the collection at the specified path. + * + * @param {string} collectionPath A slash-separated path to a collection. + * @returns {CollectionReference} A reference to the new + * subcollection. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * let subcollection = documentRef.collection('subcollection'); + * console.log(`Path to subcollection: ${subcollection.path}`); + * ``` + */ + collection(collectionPath: string): CollectionReference; + /** + * Fetches the subcollections that are direct children of this document. + * + * @returns {Promise.>} A Promise that resolves + * with an array of CollectionReferences. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.listCollections().then(collections => { + * for (let collection of collections) { + * console.log(`Found subcollection with id: ${collection.id}`); + * } + * }); + * ``` + */ + listCollections(): Promise>; + /** + * Create a document with the provided object values. This will fail the write + * if a document exists at its location. + * + * @param {DocumentData} data An object that contains the fields and data to + * serialize as the document. + * @throws {Error} If the provided input is not a valid Firestore document or if the document already exists. + * @returns {Promise.} A Promise that resolves with the + * write time of this create. + * + * @example + * ``` + * let documentRef = firestore.collection('col').doc(); + * + * documentRef.create({foo: 'bar'}).then((res) => { + * console.log(`Document created at ${res.updateTime}`); + * }).catch((err) => { + * console.log(`Failed to create document: ${err}`); + * }); + * ``` + */ + create(data: firestore.WithFieldValue): Promise; + /** + * Deletes the document referred to by this `DocumentReference`. + * + * A delete for a non-existing document is treated as a success (unless + * lastUptimeTime is provided). + * + * @param {Precondition=} precondition A precondition to enforce for this + * delete. + * @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the + * document was last updated at lastUpdateTime. Fails the delete if the + * document was last updated at a different time. + * @param {boolean=} precondition.exists If set, enforces that the target + * document must or must not exist. + * @returns {Promise.} A Promise that resolves with the + * delete time. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.delete().then(() => { + * console.log('Document successfully deleted.'); + * }); + * ``` + */ + delete(precondition?: firestore.Precondition): Promise; + set(data: firestore.PartialWithFieldValue, options: firestore.SetOptions): Promise; + set(data: firestore.WithFieldValue): Promise; + /** + * Updates fields in the document referred to by this DocumentReference. + * If the document doesn't yet exist, the update fails and the returned + * Promise will be rejected. + * + * The update() method accepts either an object with field paths encoded as + * keys and field values encoded as values, or a variable number of arguments + * that alternate between field paths and field values. + * + * A Precondition restricting this update can be specified as the last + * argument. + * + * @param {UpdateData|string|FieldPath} dataOrField An object containing the + * fields and values with which to update the document or the path of the + * first field to update. + * @param { + * ...(*|string|FieldPath|Precondition)} preconditionOrValues An alternating + * list of field paths and values to update or a Precondition to restrict + * this update. + * @throws {Error} If the provided input is not valid Firestore data. + * @returns {Promise.} A Promise that resolves once the + * data has been successfully written to the backend. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.update({foo: 'bar'}).then(res => { + * console.log(`Document updated at ${res.updateTime}`); + * }); + * ``` + */ + update(dataOrField: firestore.UpdateData | string | firestore.FieldPath, ...preconditionOrValues: Array): Promise; + /** + * Attaches a listener for DocumentSnapshot events. + * + * @param {documentSnapshotCallback} onNext A callback to be called every + * time a new `DocumentSnapshot` is available. + * @param {errorCallback=} onError A callback to be called if the listen fails + * or is cancelled. No further callbacks will occur. If unset, errors will be + * logged to the console. + * + * @returns {function()} An unsubscribe function that can be called to cancel + * the snapshot listener. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * let unsubscribe = documentRef.onSnapshot(documentSnapshot => { + * if (documentSnapshot.exists) { + * console.log(documentSnapshot.data()); + * } + * }, err => { + * console.log(`Encountered error: ${err}`); + * }); + * + * // Remove this listener. + * unsubscribe(); + * ``` + */ + onSnapshot(onNext: (snapshot: firestore.DocumentSnapshot) => void, onError?: (error: Error) => void): () => void; + /** + * Returns true if this `DocumentReference` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @return {boolean} true if this `DocumentReference` is equal to the provided + * value. + */ + isEqual(other: firestore.DocumentReference): boolean; + /** + * Converts this DocumentReference to the Firestore Proto representation. + * + * @private + * @internal + */ + toProto(): api.IValue; + withConverter(converter: null): DocumentReference; + withConverter(converter: firestore.FirestoreDataConverter): DocumentReference; +} diff --git a/node_modules/@google-cloud/firestore/build/src/reference/document-reference.js b/node_modules/@google-cloud/firestore/build/src/reference/document-reference.js new file mode 100644 index 0000000..5115c11 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/document-reference.js @@ -0,0 +1,521 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DocumentReference = void 0; +const index_1 = require("../index"); +const path_1 = require("../path"); +const types_1 = require("../types"); +const collection_reference_1 = require("./collection-reference"); +const util_1 = require("../util"); +const validate_1 = require("../validate"); +const document_1 = require("../document"); +const trace_util_1 = require("../telemetry/trace-util"); +/** + * A DocumentReference refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. A DocumentReference can + * also be used to create a + * [CollectionReference]{@link CollectionReference} to a + * subcollection. + * + * @class DocumentReference + */ +class DocumentReference { + /** + * @private + * @internal + * @param _firestore The Firestore Database client. + * @param _path The Path of this reference. + * @param _converter The converter to use when serializing data. + */ + constructor(_firestore, + /** + * @private + * @internal + **/ + _path, + /** + * @internal + * @private + **/ + _converter = (0, types_1.defaultConverter)()) { + this._firestore = _firestore; + this._path = _path; + this._converter = _converter; + } + /** + * The string representation of the DocumentReference's location. + * @private + * @internal + * @type {string} + * @name DocumentReference#formattedName + */ + get formattedName() { + const projectId = this.firestore.projectId; + const databaseId = this.firestore.databaseId; + return this._path.toQualifiedResourcePath(projectId, databaseId) + .formattedName; + } + /** + * The [Firestore]{@link Firestore} instance for the Firestore + * database (useful for performing transactions, etc.). + * + * @type {Firestore} + * @name DocumentReference#firestore + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.add({foo: 'bar'}).then(documentReference => { + * let firestore = documentReference.firestore; + * console.log(`Root location for document is ${firestore.formattedName}`); + * }); + * ``` + */ + get firestore() { + return this._firestore; + } + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + * + * @type {string} + * @name DocumentReference#path + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.add({foo: 'bar'}).then(documentReference => { + * console.log(`Added document at '${documentReference.path}'`); + * }); + * ``` + */ + get path() { + return this._path.relativeName; + } + /** + * The last path element of the referenced document. + * + * @type {string} + * @name DocumentReference#id + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.add({foo: 'bar'}).then(documentReference => { + * console.log(`Added document with name '${documentReference.id}'`); + * }); + * ``` + */ + get id() { + return this._path.id; + } + /** + * Returns a resource path for this document. + * @private + * @internal + */ + get _resourcePath() { + return this._path; + } + /** + * A reference to the collection to which this DocumentReference belongs. + * + * @name DocumentReference#parent + * @type {CollectionReference} + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * let collectionRef = documentRef.parent; + * + * collectionRef.where('foo', '==', 'bar').get().then(results => { + * console.log(`Found ${results.size} matches in parent collection`); + * }): + * ``` + */ + get parent() { + return new collection_reference_1.CollectionReference(this._firestore, this._path.parent(), this._converter); + } + /** + * Reads the document referred to by this DocumentReference. + * + * @returns {Promise.} A Promise resolved with a + * DocumentSnapshot for the retrieved document on success. For missing + * documents, DocumentSnapshot.exists will be false. If the get() fails for + * other reasons, the Promise will be rejected. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(documentSnapshot => { + * if (documentSnapshot.exists) { + * console.log('Document retrieved successfully.'); + * } + * }); + * ``` + */ + get() { + return this._firestore._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_DOC_REF_GET, () => { + return this._firestore.getAll(this).then(([result]) => result); + }); + } + /** + * Gets a [CollectionReference]{@link CollectionReference} instance + * that refers to the collection at the specified path. + * + * @param {string} collectionPath A slash-separated path to a collection. + * @returns {CollectionReference} A reference to the new + * subcollection. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * let subcollection = documentRef.collection('subcollection'); + * console.log(`Path to subcollection: ${subcollection.path}`); + * ``` + */ + collection(collectionPath) { + (0, path_1.validateResourcePath)('collectionPath', collectionPath); + const path = this._path.append(collectionPath); + if (!path.isCollection) { + throw new Error(`Value for argument "collectionPath" must point to a collection, but was "${collectionPath}". Your path does not contain an odd number of components.`); + } + return new collection_reference_1.CollectionReference(this._firestore, path); + } + /** + * Fetches the subcollections that are direct children of this document. + * + * @returns {Promise.>} A Promise that resolves + * with an array of CollectionReferences. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.listCollections().then(collections => { + * for (let collection of collections) { + * console.log(`Found subcollection with id: ${collection.id}`); + * } + * }); + * ``` + */ + listCollections() { + return this._firestore._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_DOC_REF_LIST_COLLECTIONS, () => { + const tag = (0, util_1.requestTag)(); + return this.firestore.initializeIfNeeded(tag).then(() => { + const request = { + parent: this.formattedName, + }; + return this._firestore + .request('listCollectionIds', request, tag) + .then(collectionIds => { + const collections = []; + // We can just sort this list using the default comparator since it + // will only contain collection ids. + collectionIds.sort(); + for (const collectionId of collectionIds) { + collections.push(this.collection(collectionId)); + } + return collections; + }); + }); + }); + } + /** + * Create a document with the provided object values. This will fail the write + * if a document exists at its location. + * + * @param {DocumentData} data An object that contains the fields and data to + * serialize as the document. + * @throws {Error} If the provided input is not a valid Firestore document or if the document already exists. + * @returns {Promise.} A Promise that resolves with the + * write time of this create. + * + * @example + * ``` + * let documentRef = firestore.collection('col').doc(); + * + * documentRef.create({foo: 'bar'}).then((res) => { + * console.log(`Document created at ${res.updateTime}`); + * }).catch((err) => { + * console.log(`Failed to create document: ${err}`); + * }); + * ``` + */ + create(data) { + return this._firestore._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_DOC_REF_CREATE, () => { + const writeBatch = new index_1.WriteBatch(this._firestore); + return writeBatch + .create(this, data) + .commit() + .then(([writeResult]) => writeResult); + }); + } + /** + * Deletes the document referred to by this `DocumentReference`. + * + * A delete for a non-existing document is treated as a success (unless + * lastUptimeTime is provided). + * + * @param {Precondition=} precondition A precondition to enforce for this + * delete. + * @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the + * document was last updated at lastUpdateTime. Fails the delete if the + * document was last updated at a different time. + * @param {boolean=} precondition.exists If set, enforces that the target + * document must or must not exist. + * @returns {Promise.} A Promise that resolves with the + * delete time. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.delete().then(() => { + * console.log('Document successfully deleted.'); + * }); + * ``` + */ + delete(precondition) { + return this._firestore._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_DOC_REF_DELETE, () => { + const writeBatch = new index_1.WriteBatch(this._firestore); + return writeBatch + .delete(this, precondition) + .commit() + .then(([writeResult]) => writeResult); + }); + } + /** + * Writes to the document referred to by this DocumentReference. If the + * document does not yet exist, it will be created. If you pass + * [SetOptions]{@link SetOptions}, the provided data can be merged into an + * existing document. + * + * @param {T|Partial} data A map of the fields and values for + * the document. + * @param {SetOptions=} options An object to configure the set behavior. + * @param {boolean=} options.merge If true, set() merges the values specified + * in its data argument. Fields omitted from this set() call remain untouched. + * If your input sets any field to an empty map, all nested fields are + * overwritten. + * @param {Array.=} options.mergeFields If provided, + * set() only replaces the specified field paths. Any field path that is not + * specified is ignored and remains untouched. If your input sets any field to + * an empty map, all nested fields are overwritten. + * @throws {Error} If the provided input is not a valid Firestore document. + * @returns {Promise.} A Promise that resolves with the + * write time of this set. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({foo: 'bar'}).then(res => { + * console.log(`Document written at ${res.updateTime}`); + * }); + * ``` + */ + set(data, options) { + return this._firestore._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_DOC_REF_SET, () => { + let writeBatch = new index_1.WriteBatch(this._firestore); + if (options) { + writeBatch = writeBatch.set(this, data, options); + } + else { + writeBatch = writeBatch.set(this, data); + } + return writeBatch.commit().then(([writeResult]) => writeResult); + }); + } + /** + * Updates fields in the document referred to by this DocumentReference. + * If the document doesn't yet exist, the update fails and the returned + * Promise will be rejected. + * + * The update() method accepts either an object with field paths encoded as + * keys and field values encoded as values, or a variable number of arguments + * that alternate between field paths and field values. + * + * A Precondition restricting this update can be specified as the last + * argument. + * + * @param {UpdateData|string|FieldPath} dataOrField An object containing the + * fields and values with which to update the document or the path of the + * first field to update. + * @param { + * ...(*|string|FieldPath|Precondition)} preconditionOrValues An alternating + * list of field paths and values to update or a Precondition to restrict + * this update. + * @throws {Error} If the provided input is not valid Firestore data. + * @returns {Promise.} A Promise that resolves once the + * data has been successfully written to the backend. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.update({foo: 'bar'}).then(res => { + * console.log(`Document updated at ${res.updateTime}`); + * }); + * ``` + */ + update(dataOrField, ...preconditionOrValues) { + return this._firestore._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_DOC_REF_UPDATE, () => { + // eslint-disable-next-line prefer-rest-params + (0, validate_1.validateMinNumberOfArguments)('DocumentReference.update', arguments, 1); + const writeBatch = new index_1.WriteBatch(this._firestore); + return writeBatch + .update(this, dataOrField, ...preconditionOrValues) + .commit() + .then(([writeResult]) => writeResult); + }); + } + /** + * Attaches a listener for DocumentSnapshot events. + * + * @param {documentSnapshotCallback} onNext A callback to be called every + * time a new `DocumentSnapshot` is available. + * @param {errorCallback=} onError A callback to be called if the listen fails + * or is cancelled. No further callbacks will occur. If unset, errors will be + * logged to the console. + * + * @returns {function()} An unsubscribe function that can be called to cancel + * the snapshot listener. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * let unsubscribe = documentRef.onSnapshot(documentSnapshot => { + * if (documentSnapshot.exists) { + * console.log(documentSnapshot.data()); + * } + * }, err => { + * console.log(`Encountered error: ${err}`); + * }); + * + * // Remove this listener. + * unsubscribe(); + * ``` + */ + onSnapshot(onNext, onError) { + (0, validate_1.validateFunction)('onNext', onNext); + (0, validate_1.validateFunction)('onError', onError, { optional: true }); + const watch = new (require('../watch').DocumentWatch)(this.firestore, this); + return watch.onSnapshot((readTime, size, docs) => { + for (const document of docs()) { + if (document.ref.path === this.path) { + onNext(document); + return; + } + } + // The document is missing. + const ref = new DocumentReference(this._firestore, this._path, this._converter); + const document = new document_1.DocumentSnapshotBuilder(ref); + document.readTime = readTime; + onNext(document.build()); + }, onError || console.error); + } + /** + * Returns true if this `DocumentReference` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @return {boolean} true if this `DocumentReference` is equal to the provided + * value. + */ + isEqual(other) { + return (this === other || + (other instanceof DocumentReference && + this._firestore === other._firestore && + this._path.isEqual(other._path) && + this._converter === other._converter)); + } + /** + * Converts this DocumentReference to the Firestore Proto representation. + * + * @private + * @internal + */ + toProto() { + return { referenceValue: this.formattedName }; + } + /** + * Applies a custom data converter to this DocumentReference, allowing you to + * use your own custom model objects with Firestore. When you call set(), + * get(), etc. on the returned DocumentReference instance, the provided + * converter will convert between Firestore data of type `NewDbModelType` and + * your custom type `NewAppModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * Passing in `null` as the converter parameter removes the current + * converter. + * + * @example + * ``` + * class Post { + * constructor(readonly title: string, readonly author: string) {} + * + * toString(): string { + * return this.title + ', by ' + this.author; + * } + * } + * + * const postConverter = { + * toFirestore(post: Post): FirebaseFirestore.DocumentData { + * return {title: post.title, author: post.author}; + * }, + * fromFirestore( + * snapshot: FirebaseFirestore.QueryDocumentSnapshot + * ): Post { + * const data = snapshot.data(); + * return new Post(data.title, data.author); + * } + * }; + * + * const postSnap = await Firestore() + * .collection('posts') + * .withConverter(postConverter) + * .doc().get(); + * const post = postSnap.data(); + * if (post !== undefined) { + * post.title; // string + * post.toString(); // Should be defined + * post.someNonExistentProperty; // TS error + * } + * + * ``` + * @param {FirestoreDataConverter | null} converter Converts objects to and + * from Firestore. Passing in `null` removes the current converter. + * @return A DocumentReference that uses the provided converter. + */ + withConverter(converter) { + return new DocumentReference(this.firestore, this._path, converter !== null && converter !== void 0 ? converter : (0, types_1.defaultConverter)()); + } +} +exports.DocumentReference = DocumentReference; +//# sourceMappingURL=document-reference.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/reference/field-filter-internal.d.ts b/node_modules/@google-cloud/firestore/build/src/reference/field-filter-internal.d.ts new file mode 100644 index 0000000..b411bbc --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/field-filter-internal.d.ts @@ -0,0 +1,58 @@ +/** + * Copyright 2024 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. + */ +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; +import { FilterInternal } from './filter-internal'; +import { Serializer } from '../serializer'; +import { FieldPath } from '../path'; +/** + * A field constraint for a Query where clause. + * + * @private + * @internal + * @class + */ +export declare class FieldFilterInternal extends FilterInternal { + private readonly serializer; + readonly field: FieldPath; + private readonly op; + private readonly value; + getFlattenedFilters(): FieldFilterInternal[]; + getFilters(): FilterInternal[]; + /** + * @param serializer The Firestore serializer + * @param field The path of the property value to compare. + * @param op A comparison operation. + * @param value The value to which to compare the field for inclusion in a + * query. + */ + constructor(serializer: Serializer, field: FieldPath, op: api.StructuredQuery.FieldFilter.Operator, value: unknown); + /** + * Returns whether this FieldFilter uses an equals comparison. + * + * @private + * @internal + */ + isInequalityFilter(): boolean; + /** + * Generates the proto representation for this field filter. + * + * @private + * @internal + */ + toProto(): api.StructuredQuery.IFilter; + isEqual(other: FilterInternal): boolean; +} diff --git a/node_modules/@google-cloud/firestore/build/src/reference/field-filter-internal.js b/node_modules/@google-cloud/firestore/build/src/reference/field-filter-internal.js new file mode 100644 index 0000000..00d9769 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/field-filter-internal.js @@ -0,0 +1,113 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FieldFilterInternal = void 0; +const deepEqual = require("fast-deep-equal"); +const filter_internal_1 = require("./filter-internal"); +/** + * A field constraint for a Query where clause. + * + * @private + * @internal + * @class + */ +class FieldFilterInternal extends filter_internal_1.FilterInternal { + getFlattenedFilters() { + return [this]; + } + getFilters() { + return [this]; + } + /** + * @param serializer The Firestore serializer + * @param field The path of the property value to compare. + * @param op A comparison operation. + * @param value The value to which to compare the field for inclusion in a + * query. + */ + constructor(serializer, field, op, value) { + super(); + this.serializer = serializer; + this.field = field; + this.op = op; + this.value = value; + } + /** + * Returns whether this FieldFilter uses an equals comparison. + * + * @private + * @internal + */ + isInequalityFilter() { + switch (this.op) { + case 'GREATER_THAN': + case 'GREATER_THAN_OR_EQUAL': + case 'LESS_THAN': + case 'LESS_THAN_OR_EQUAL': + case 'NOT_EQUAL': + case 'NOT_IN': + return true; + default: + return false; + } + } + /** + * Generates the proto representation for this field filter. + * + * @private + * @internal + */ + toProto() { + if (typeof this.value === 'number' && isNaN(this.value)) { + return { + unaryFilter: { + field: { + fieldPath: this.field.formattedName, + }, + op: this.op === 'EQUAL' ? 'IS_NAN' : 'IS_NOT_NAN', + }, + }; + } + if (this.value === null) { + return { + unaryFilter: { + field: { + fieldPath: this.field.formattedName, + }, + op: this.op === 'EQUAL' ? 'IS_NULL' : 'IS_NOT_NULL', + }, + }; + } + return { + fieldFilter: { + field: { + fieldPath: this.field.formattedName, + }, + op: this.op, + value: this.serializer.encodeValue(this.value), + }, + }; + } + isEqual(other) { + return (other instanceof FieldFilterInternal && + this.field.isEqual(other.field) && + this.op === other.op && + deepEqual(this.value, other.value)); + } +} +exports.FieldFilterInternal = FieldFilterInternal; +//# sourceMappingURL=field-filter-internal.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/reference/field-order.d.ts b/node_modules/@google-cloud/firestore/build/src/reference/field-order.d.ts new file mode 100644 index 0000000..2473c0a --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/field-order.d.ts @@ -0,0 +1,42 @@ +/** + * Copyright 2024 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. + */ +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; +import { FieldPath } from '../path'; +/** + * A Query order-by field. + * + * @private + * @internal + * @class + */ +export declare class FieldOrder { + readonly field: FieldPath; + readonly direction: api.StructuredQuery.Direction; + /** + * @param field The name of a document field (member) on which to order query + * results. + * @param direction One of 'ASCENDING' (default) or 'DESCENDING' to + * set the ordering direction to ascending or descending, respectively. + */ + constructor(field: FieldPath, direction?: api.StructuredQuery.Direction); + /** + * Generates the proto representation for this field order. + * @private + * @internal + */ + toProto(): api.StructuredQuery.IOrder; +} diff --git a/node_modules/@google-cloud/firestore/build/src/reference/field-order.js b/node_modules/@google-cloud/firestore/build/src/reference/field-order.js new file mode 100644 index 0000000..77077dd --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/field-order.js @@ -0,0 +1,52 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FieldOrder = void 0; +/** + * A Query order-by field. + * + * @private + * @internal + * @class + */ +class FieldOrder { + /** + * @param field The name of a document field (member) on which to order query + * results. + * @param direction One of 'ASCENDING' (default) or 'DESCENDING' to + * set the ordering direction to ascending or descending, respectively. + */ + constructor(field, direction = 'ASCENDING') { + this.field = field; + this.direction = direction; + } + /** + * Generates the proto representation for this field order. + * @private + * @internal + */ + toProto() { + return { + field: { + fieldPath: this.field.formattedName, + }, + direction: this.direction, + }; + } +} +exports.FieldOrder = FieldOrder; +//# sourceMappingURL=field-order.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/reference/filter-internal.d.ts b/node_modules/@google-cloud/firestore/build/src/reference/filter-internal.d.ts new file mode 100644 index 0000000..4eb16f3 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/filter-internal.d.ts @@ -0,0 +1,26 @@ +/** + * Copyright 2024 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. + */ +import { Filter } from '../filter'; +import { FieldFilterInternal } from './field-filter-internal'; +export declare abstract class FilterInternal { + /** Returns a list of all field filters that are contained within this filter */ + abstract getFlattenedFilters(): FieldFilterInternal[]; + /** Returns a list of all filters that are contained within this filter */ + abstract getFilters(): FilterInternal[]; + /** Returns the proto representation of this filter */ + abstract toProto(): Filter; + abstract isEqual(other: FilterInternal): boolean; +} diff --git a/node_modules/@google-cloud/firestore/build/src/reference/filter-internal.js b/node_modules/@google-cloud/firestore/build/src/reference/filter-internal.js new file mode 100644 index 0000000..34cd8e9 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/filter-internal.js @@ -0,0 +1,22 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FilterInternal = void 0; +class FilterInternal { +} +exports.FilterInternal = FilterInternal; +//# sourceMappingURL=filter-internal.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/reference/helpers.d.ts b/node_modules/@google-cloud/firestore/build/src/reference/helpers.d.ts new file mode 100644 index 0000000..4410c33 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/helpers.d.ts @@ -0,0 +1,68 @@ +/** + * Copyright 2024 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. + */ +import * as firestore from '@google-cloud/firestore'; +import { DocumentReference } from './document-reference'; +/** + * Validates the input string as a field order direction. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param op Order direction to validate. + * @throws when the direction is invalid + * @return a validated input value, which may be different from the provided + * value. + */ +export declare function validateQueryOrder(arg: string, op: unknown): firestore.OrderByDirection | undefined; +/** + * Validates the input string as a field comparison operator. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param op Field comparison operator to validate. + * @param fieldValue Value that is used in the filter. + * @throws when the comparison operation is invalid + * @return a validated input value, which may be different from the provided + * value. + */ +export declare function validateQueryOperator(arg: string | number, op: unknown, fieldValue: unknown): firestore.WhereFilterOp; +/** + * Validates that 'value' is a DocumentReference. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The argument to validate. + * @return the DocumentReference if valid + */ +export declare function validateDocumentReference(arg: string | number, value: firestore.DocumentReference): DocumentReference; +/** + * Validates that 'value' can be used as a query value. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The argument to validate. + * @param allowUndefined Whether to allow nested properties that are `undefined`. + */ +export declare function validateQueryValue(arg: string | number, value: unknown, allowUndefined: boolean): void; +/** + * Returns the first non-undefined value or `undefined` if no such value exists. + * @private + * @internal + */ +export declare function coalesce(...values: Array): T | undefined; diff --git a/node_modules/@google-cloud/firestore/build/src/reference/helpers.js b/node_modules/@google-cloud/firestore/build/src/reference/helpers.js new file mode 100644 index 0000000..2dabe43 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/helpers.js @@ -0,0 +1,112 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateQueryOrder = validateQueryOrder; +exports.validateQueryOperator = validateQueryOperator; +exports.validateDocumentReference = validateDocumentReference; +exports.validateQueryValue = validateQueryValue; +exports.coalesce = coalesce; +const validate_1 = require("../validate"); +const serializer_1 = require("../serializer"); +const document_reference_1 = require("./document-reference"); +const constants_1 = require("./constants"); +/** + * Validates the input string as a field order direction. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param op Order direction to validate. + * @throws when the direction is invalid + * @return a validated input value, which may be different from the provided + * value. + */ +function validateQueryOrder(arg, op) { + // For backwards compatibility, we support both lower and uppercase values. + op = typeof op === 'string' ? op.toLowerCase() : op; + (0, validate_1.validateEnumValue)(arg, op, Object.keys(constants_1.directionOperators), { optional: true }); + return op; +} +/** + * Validates the input string as a field comparison operator. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param op Field comparison operator to validate. + * @param fieldValue Value that is used in the filter. + * @throws when the comparison operation is invalid + * @return a validated input value, which may be different from the provided + * value. + */ +function validateQueryOperator(arg, op, fieldValue) { + // For backwards compatibility, we support both `=` and `==` for "equals". + if (op === '=') { + op = '=='; + } + (0, validate_1.validateEnumValue)(arg, op, Object.keys(constants_1.comparisonOperators)); + if (typeof fieldValue === 'number' && + isNaN(fieldValue) && + op !== '==' && + op !== '!=') { + throw new Error("Invalid query. You can only perform '==' and '!=' comparisons on NaN."); + } + if (fieldValue === null && op !== '==' && op !== '!=') { + throw new Error("Invalid query. You can only perform '==' and '!=' comparisons on Null."); + } + return op; +} +/** + * Validates that 'value' is a DocumentReference. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The argument to validate. + * @return the DocumentReference if valid + */ +function validateDocumentReference(arg, value) { + if (!(value instanceof document_reference_1.DocumentReference)) { + throw new Error((0, validate_1.invalidArgumentMessage)(arg, 'DocumentReference')); + } + return value; +} +/** + * Validates that 'value' can be used as a query value. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The argument to validate. + * @param allowUndefined Whether to allow nested properties that are `undefined`. + */ +function validateQueryValue(arg, value, allowUndefined) { + (0, serializer_1.validateUserInput)(arg, value, 'query constraint', { + allowDeletes: 'none', + allowTransforms: false, + allowUndefined, + }); +} +/** + * Returns the first non-undefined value or `undefined` if no such value exists. + * @private + * @internal + */ +function coalesce(...values) { + return values.find(value => value !== undefined); +} +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/reference/query-options.d.ts b/node_modules/@google-cloud/firestore/build/src/reference/query-options.d.ts new file mode 100644 index 0000000..1030b49 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/query-options.d.ts @@ -0,0 +1,76 @@ +/** + * Copyright 2024 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. + */ +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; +import * as firestore from '@google-cloud/firestore'; +import { ResourcePath } from '../path'; +import { FilterInternal } from './filter-internal'; +import { FieldOrder } from './field-order'; +import { LimitType, QueryCursor } from './types'; +/** + * Internal class representing custom Query options. + * + * These options are immutable. Modified options can be created using `with()`. + * @private + * @internal + */ +export declare class QueryOptions { + readonly parentPath: ResourcePath; + readonly collectionId: string; + readonly converter: firestore.FirestoreDataConverter; + readonly allDescendants: boolean; + readonly filters: FilterInternal[]; + readonly fieldOrders: FieldOrder[]; + readonly startAt?: QueryCursor | undefined; + readonly endAt?: QueryCursor | undefined; + readonly limit?: number | undefined; + readonly limitType?: LimitType | undefined; + readonly offset?: number | undefined; + readonly projection?: api.StructuredQuery.IProjection | undefined; + readonly kindless: boolean; + readonly requireConsistency: boolean; + constructor(parentPath: ResourcePath, collectionId: string, converter: firestore.FirestoreDataConverter, allDescendants: boolean, filters: FilterInternal[], fieldOrders: FieldOrder[], startAt?: QueryCursor | undefined, endAt?: QueryCursor | undefined, limit?: number | undefined, limitType?: LimitType | undefined, offset?: number | undefined, projection?: api.StructuredQuery.IProjection | undefined, kindless?: boolean, requireConsistency?: boolean); + /** + * Returns query options for a collection group query. + * @private + * @internal + */ + static forCollectionGroupQuery(collectionId: string, converter?: firestore.FirestoreDataConverter): QueryOptions; + /** + * Returns query options for a single-collection query. + * @private + * @internal + */ + static forCollectionQuery(collectionRef: ResourcePath, converter?: firestore.FirestoreDataConverter): QueryOptions; + /** + * Returns query options for a query that fetches all descendants under the + * specified reference. + * + * @private + * @internal + */ + static forKindlessAllDescendants(parent: ResourcePath, id: string, requireConsistency?: boolean): QueryOptions; + /** + * Returns the union of the current and the provided options. + * @private + * @internal + */ + with(settings: Partial, 'converter'>>): QueryOptions; + withConverter(converter: firestore.FirestoreDataConverter): QueryOptions; + hasFieldOrders(): boolean; + isEqual(other: QueryOptions): boolean; + private filtersEqual; +} diff --git a/node_modules/@google-cloud/firestore/build/src/reference/query-options.js b/node_modules/@google-cloud/firestore/build/src/reference/query-options.js new file mode 100644 index 0000000..90ab15f --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/query-options.js @@ -0,0 +1,141 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.QueryOptions = void 0; +const deepEqual = require("fast-deep-equal"); +const path_1 = require("../path"); +const types_1 = require("../types"); +const helpers_1 = require("./helpers"); +/** + * Internal class representing custom Query options. + * + * These options are immutable. Modified options can be created using `with()`. + * @private + * @internal + */ +class QueryOptions { + constructor(parentPath, collectionId, converter, allDescendants, filters, fieldOrders, startAt, endAt, limit, limitType, offset, projection, + // Whether to select all documents under `parentPath`. By default, only + // collections that match `collectionId` are selected. + kindless = false, + // Whether to require consistent documents when restarting the query. By + // default, restarting the query uses the readTime offset of the original + // query to provide consistent results. + requireConsistency = true) { + this.parentPath = parentPath; + this.collectionId = collectionId; + this.converter = converter; + this.allDescendants = allDescendants; + this.filters = filters; + this.fieldOrders = fieldOrders; + this.startAt = startAt; + this.endAt = endAt; + this.limit = limit; + this.limitType = limitType; + this.offset = offset; + this.projection = projection; + this.kindless = kindless; + this.requireConsistency = requireConsistency; + } + /** + * Returns query options for a collection group query. + * @private + * @internal + */ + static forCollectionGroupQuery(collectionId, converter = (0, types_1.defaultConverter)()) { + return new QueryOptions( + /*parentPath=*/ path_1.ResourcePath.EMPTY, collectionId, converter, + /*allDescendants=*/ true, + /*fieldFilters=*/ [], + /*fieldOrders=*/ []); + } + /** + * Returns query options for a single-collection query. + * @private + * @internal + */ + static forCollectionQuery(collectionRef, converter = (0, types_1.defaultConverter)()) { + return new QueryOptions(collectionRef.parent(), collectionRef.id, converter, + /*allDescendants=*/ false, + /*fieldFilters=*/ [], + /*fieldOrders=*/ []); + } + /** + * Returns query options for a query that fetches all descendants under the + * specified reference. + * + * @private + * @internal + */ + static forKindlessAllDescendants(parent, id, requireConsistency = true) { + let options = new QueryOptions(parent, id, (0, types_1.defaultConverter)(), + /*allDescendants=*/ true, + /*fieldFilters=*/ [], + /*fieldOrders=*/ []); + options = options.with({ + kindless: true, + requireConsistency, + }); + return options; + } + /** + * Returns the union of the current and the provided options. + * @private + * @internal + */ + with(settings) { + return new QueryOptions((0, helpers_1.coalesce)(settings.parentPath, this.parentPath), (0, helpers_1.coalesce)(settings.collectionId, this.collectionId), this.converter, (0, helpers_1.coalesce)(settings.allDescendants, this.allDescendants), (0, helpers_1.coalesce)(settings.filters, this.filters), (0, helpers_1.coalesce)(settings.fieldOrders, this.fieldOrders), (0, helpers_1.coalesce)(settings.startAt, this.startAt), (0, helpers_1.coalesce)(settings.endAt, this.endAt), (0, helpers_1.coalesce)(settings.limit, this.limit), (0, helpers_1.coalesce)(settings.limitType, this.limitType), (0, helpers_1.coalesce)(settings.offset, this.offset), (0, helpers_1.coalesce)(settings.projection, this.projection), (0, helpers_1.coalesce)(settings.kindless, this.kindless), (0, helpers_1.coalesce)(settings.requireConsistency, this.requireConsistency)); + } + withConverter(converter) { + return new QueryOptions(this.parentPath, this.collectionId, converter, this.allDescendants, this.filters, this.fieldOrders, this.startAt, this.endAt, this.limit, this.limitType, this.offset, this.projection); + } + hasFieldOrders() { + return this.fieldOrders.length > 0; + } + isEqual(other) { + if (this === other) { + return true; + } + return (other instanceof QueryOptions && + this.parentPath.isEqual(other.parentPath) && + this.filtersEqual(other.filters) && + this.collectionId === other.collectionId && + this.converter === other.converter && + this.allDescendants === other.allDescendants && + this.limit === other.limit && + this.offset === other.offset && + deepEqual(this.fieldOrders, other.fieldOrders) && + deepEqual(this.startAt, other.startAt) && + deepEqual(this.endAt, other.endAt) && + deepEqual(this.projection, other.projection) && + this.kindless === other.kindless && + this.requireConsistency === other.requireConsistency); + } + filtersEqual(other) { + if (this.filters.length !== other.length) { + return false; + } + for (let i = 0; i < other.length; i++) { + if (!this.filters[i].isEqual(other[i])) { + return false; + } + } + return true; + } +} +exports.QueryOptions = QueryOptions; +//# sourceMappingURL=query-options.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/reference/query-snapshot.d.ts b/node_modules/@google-cloud/firestore/build/src/reference/query-snapshot.d.ts new file mode 100644 index 0000000..09ab7a1 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/query-snapshot.d.ts @@ -0,0 +1,199 @@ +/** + * Copyright 2024 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. + */ +import * as firestore from '@google-cloud/firestore'; +import { QueryDocumentSnapshot } from '../document'; +import { DocumentChange } from '../document-change'; +import { Timestamp } from '../timestamp'; +import { Query } from './query'; +/** + * A QuerySnapshot contains zero or more + * [QueryDocumentSnapshot]{@link QueryDocumentSnapshot} objects + * representing the results of a query. The documents can be accessed as an + * array via the [documents]{@link QuerySnapshot#documents} property + * or enumerated using the [forEach]{@link QuerySnapshot#forEach} + * method. The number of documents can be determined via the + * [empty]{@link QuerySnapshot#empty} and + * [size]{@link QuerySnapshot#size} properties. + * + * @class QuerySnapshot + */ +export declare class QuerySnapshot implements firestore.QuerySnapshot { + private readonly _query; + private readonly _readTime; + private readonly _size; + private _materializedDocs; + private _materializedChanges; + private _docs; + private _changes; + /** + * @private + * + * @param _query The originating query. + * @param _readTime The time when this query snapshot was obtained. + * @param _size The number of documents in the result set. + * @param docs A callback returning a sorted array of documents matching + * this query + * @param changes A callback returning a sorted array of document change + * events for this snapshot. + */ + constructor(_query: Query, _readTime: Timestamp, _size: number, docs: () => Array>, changes: () => Array>); + /** + * The query on which you called get() or onSnapshot() in order to get this + * QuerySnapshot. + * + * @type {Query} + * @name QuerySnapshot#query + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.limit(10).get().then(querySnapshot => { + * console.log(`Returned first batch of results`); + * let query = querySnapshot.query; + * return query.offset(10).get(); + * }).then(() => { + * console.log(`Returned second batch of results`); + * }); + * ``` + */ + get query(): Query; + /** + * An array of all the documents in this QuerySnapshot. + * + * @type {Array.} + * @name QuerySnapshot#docs + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.get().then(querySnapshot => { + * let docs = querySnapshot.docs; + * for (let doc of docs) { + * console.log(`Document found at path: ${doc.ref.path}`); + * } + * }); + * ``` + */ + get docs(): Array>; + /** + * True if there are no documents in the QuerySnapshot. + * + * @type {boolean} + * @name QuerySnapshot#empty + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.get().then(querySnapshot => { + * if (querySnapshot.empty) { + * console.log('No documents found.'); + * } + * }); + * ``` + */ + get empty(): boolean; + /** + * The number of documents in the QuerySnapshot. + * + * @type {number} + * @name QuerySnapshot#size + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.get().then(querySnapshot => { + * console.log(`Found ${querySnapshot.size} documents.`); + * }); + * ``` + */ + get size(): number; + /** + * The time this query snapshot was obtained. + * + * @type {Timestamp} + * @name QuerySnapshot#readTime + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.get().then((querySnapshot) => { + * let readTime = querySnapshot.readTime; + * console.log(`Query results returned at '${readTime.toDate()}'`); + * }); + * ``` + */ + get readTime(): Timestamp; + /** + * Returns an array of the documents changes since the last snapshot. If + * this is the first snapshot, all documents will be in the list as added + * changes. + * + * @return {Array.} + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.onSnapshot(querySnapshot => { + * let changes = querySnapshot.docChanges(); + * for (let change of changes) { + * console.log(`A document was ${change.type}.`); + * } + * }); + * ``` + */ + docChanges(): Array>; + /** + * Enumerates all of the documents in the QuerySnapshot. This is a convenience + * method for running the same callback on each {@link QueryDocumentSnapshot} + * that is returned. + * + * @param {function} callback A callback to be called with a + * [QueryDocumentSnapshot]{@link QueryDocumentSnapshot} for each document in + * the snapshot. + * @param {*=} thisArg The `this` binding for the callback.. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Document found at path: ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + forEach(callback: (result: firestore.QueryDocumentSnapshot) => void, thisArg?: unknown): void; + /** + * Returns true if the document data in this `QuerySnapshot` is equal to the + * provided value. + * + * @param {*} other The value to compare against. + * @return {boolean} true if this `QuerySnapshot` is equal to the provided + * value. + */ + isEqual(other: firestore.QuerySnapshot): boolean; +} diff --git a/node_modules/@google-cloud/firestore/build/src/reference/query-snapshot.js b/node_modules/@google-cloud/firestore/build/src/reference/query-snapshot.js new file mode 100644 index 0000000..96d41e8 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/query-snapshot.js @@ -0,0 +1,254 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.QuerySnapshot = void 0; +const validate_1 = require("../validate"); +const util_1 = require("../util"); +/** + * A QuerySnapshot contains zero or more + * [QueryDocumentSnapshot]{@link QueryDocumentSnapshot} objects + * representing the results of a query. The documents can be accessed as an + * array via the [documents]{@link QuerySnapshot#documents} property + * or enumerated using the [forEach]{@link QuerySnapshot#forEach} + * method. The number of documents can be determined via the + * [empty]{@link QuerySnapshot#empty} and + * [size]{@link QuerySnapshot#size} properties. + * + * @class QuerySnapshot + */ +class QuerySnapshot { + /** + * @private + * + * @param _query The originating query. + * @param _readTime The time when this query snapshot was obtained. + * @param _size The number of documents in the result set. + * @param docs A callback returning a sorted array of documents matching + * this query + * @param changes A callback returning a sorted array of document change + * events for this snapshot. + */ + constructor(_query, _readTime, _size, docs, changes) { + this._query = _query; + this._readTime = _readTime; + this._size = _size; + this._materializedDocs = null; + this._materializedChanges = null; + this._docs = null; + this._changes = null; + this._docs = docs; + this._changes = changes; + } + /** + * The query on which you called get() or onSnapshot() in order to get this + * QuerySnapshot. + * + * @type {Query} + * @name QuerySnapshot#query + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.limit(10).get().then(querySnapshot => { + * console.log(`Returned first batch of results`); + * let query = querySnapshot.query; + * return query.offset(10).get(); + * }).then(() => { + * console.log(`Returned second batch of results`); + * }); + * ``` + */ + get query() { + return this._query; + } + /** + * An array of all the documents in this QuerySnapshot. + * + * @type {Array.} + * @name QuerySnapshot#docs + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.get().then(querySnapshot => { + * let docs = querySnapshot.docs; + * for (let doc of docs) { + * console.log(`Document found at path: ${doc.ref.path}`); + * } + * }); + * ``` + */ + get docs() { + if (this._materializedDocs) { + return this._materializedDocs; + } + this._materializedDocs = this._docs(); + this._docs = null; + return this._materializedDocs; + } + /** + * True if there are no documents in the QuerySnapshot. + * + * @type {boolean} + * @name QuerySnapshot#empty + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.get().then(querySnapshot => { + * if (querySnapshot.empty) { + * console.log('No documents found.'); + * } + * }); + * ``` + */ + get empty() { + return this._size === 0; + } + /** + * The number of documents in the QuerySnapshot. + * + * @type {number} + * @name QuerySnapshot#size + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.get().then(querySnapshot => { + * console.log(`Found ${querySnapshot.size} documents.`); + * }); + * ``` + */ + get size() { + return this._size; + } + /** + * The time this query snapshot was obtained. + * + * @type {Timestamp} + * @name QuerySnapshot#readTime + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.get().then((querySnapshot) => { + * let readTime = querySnapshot.readTime; + * console.log(`Query results returned at '${readTime.toDate()}'`); + * }); + * ``` + */ + get readTime() { + return this._readTime; + } + /** + * Returns an array of the documents changes since the last snapshot. If + * this is the first snapshot, all documents will be in the list as added + * changes. + * + * @return {Array.} + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.onSnapshot(querySnapshot => { + * let changes = querySnapshot.docChanges(); + * for (let change of changes) { + * console.log(`A document was ${change.type}.`); + * } + * }); + * ``` + */ + docChanges() { + if (this._materializedChanges) { + return this._materializedChanges; + } + this._materializedChanges = this._changes(); + this._changes = null; + return this._materializedChanges; + } + /** + * Enumerates all of the documents in the QuerySnapshot. This is a convenience + * method for running the same callback on each {@link QueryDocumentSnapshot} + * that is returned. + * + * @param {function} callback A callback to be called with a + * [QueryDocumentSnapshot]{@link QueryDocumentSnapshot} for each document in + * the snapshot. + * @param {*=} thisArg The `this` binding for the callback.. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Document found at path: ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + forEach(callback, thisArg) { + (0, validate_1.validateFunction)('callback', callback); + for (const doc of this.docs) { + callback.call(thisArg, doc); + } + } + /** + * Returns true if the document data in this `QuerySnapshot` is equal to the + * provided value. + * + * @param {*} other The value to compare against. + * @return {boolean} true if this `QuerySnapshot` is equal to the provided + * value. + */ + isEqual(other) { + // Since the read time is different on every query read, we explicitly + // ignore all metadata in this comparison. + if (this === other) { + return true; + } + if (!(other instanceof QuerySnapshot)) { + return false; + } + if (this._size !== other._size) { + return false; + } + if (!this._query.isEqual(other._query)) { + return false; + } + if (this._materializedDocs && !this._materializedChanges) { + // If we have only materialized the documents, we compare them first. + return ((0, util_1.isArrayEqual)(this.docs, other.docs) && + (0, util_1.isArrayEqual)(this.docChanges(), other.docChanges())); + } + // Otherwise, we compare the changes first as we expect there to be fewer. + return ((0, util_1.isArrayEqual)(this.docChanges(), other.docChanges()) && + (0, util_1.isArrayEqual)(this.docs, other.docs)); + } +} +exports.QuerySnapshot = QuerySnapshot; +//# sourceMappingURL=query-snapshot.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/reference/query-util.d.ts b/node_modules/@google-cloud/firestore/build/src/reference/query-util.d.ts new file mode 100644 index 0000000..cfbc121 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/query-util.d.ts @@ -0,0 +1,46 @@ +/** + * Copyright 2024 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. + */ +import * as firestore from '@google-cloud/firestore'; +import { GoogleError } from 'google-gax'; +import { Serializer } from '../serializer'; +import { Timestamp } from '../timestamp'; +import { VectorQuery } from './vector-query'; +import { Query } from './query'; +import Firestore from '../index'; +import { QueryOptions } from './query-options'; +import { QueryResponse } from './types'; +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; +export declare class QueryUtil | VectorQuery> { + /** @private */ + readonly _firestore: Firestore; + /** @private */ + readonly _queryOptions: QueryOptions; + /** @private */ + readonly _serializer: Serializer; + constructor( + /** @private */ + _firestore: Firestore, + /** @private */ + _queryOptions: QueryOptions, + /** @private */ + _serializer: Serializer); + _getResponse(query: Template, transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, retryWithCursor?: boolean, explainOptions?: firestore.ExplainOptions): Promise>>; + _isPermanentRpcError(err: GoogleError, methodName: string): boolean; + _hasRetryTimedOut(methodName: string, startTime: number): boolean; + stream(query: Template): NodeJS.ReadableStream; + _stream(query: Template, transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, retryWithCursor?: boolean, explainOptions?: firestore.ExplainOptions): NodeJS.ReadableStream; +} diff --git a/node_modules/@google-cloud/firestore/build/src/reference/query-util.js b/node_modules/@google-cloud/firestore/build/src/reference/query-util.js new file mode 100644 index 0000000..cda568b --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/query-util.js @@ -0,0 +1,286 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.QueryUtil = void 0; +const stream_1 = require("stream"); +const timestamp_1 = require("../timestamp"); +const document_1 = require("../document"); +const util_1 = require("../util"); +const document_change_1 = require("../document-change"); +const query_profile_1 = require("../query-profile"); +const logger_1 = require("../logger"); +const vector_query_1 = require("./vector-query"); +const types_1 = require("./types"); +const constants_1 = require("./constants"); +const trace_util_1 = require("../telemetry/trace-util"); +class QueryUtil { + constructor( + /** @private */ + _firestore, + /** @private */ + _queryOptions, + /** @private */ + _serializer) { + this._firestore = _firestore; + this._queryOptions = _queryOptions; + this._serializer = _serializer; + } + _getResponse(query, transactionOrReadTime, retryWithCursor = true, explainOptions) { + // Capture the error stack to preserve stack tracing across async calls. + const stack = Error().stack; + return new Promise((resolve, reject) => { + const docs = []; + const output = {}; + this._stream(query, transactionOrReadTime, retryWithCursor, explainOptions) + .on('error', err => { + reject((0, util_1.wrapError)(err, stack)); + }) + .on('data', (data) => { + if (data.transaction) { + output.transaction = data.transaction; + } + if (data.readTime) { + output.readTime = data.readTime; + } + if (data.explainMetrics) { + output.explainMetrics = data.explainMetrics; + } + if (data.document) { + docs.push(data.document); + } + }) + .on('end', () => { + if (this._queryOptions.limitType === types_1.LimitType.Last) { + // The results for limitToLast queries need to be flipped since + // we reversed the ordering constraints before sending the query + // to the backend. + docs.reverse(); + } + // Only return a snapshot when we have a readTime + // explain queries with analyze !== true will return no documents and no read time + const result = output.readTime + ? query._createSnapshot(output.readTime, docs.length, () => docs, () => { + const changes = []; + for (let i = 0; i < docs.length; ++i) { + changes.push(new document_change_1.DocumentChange('added', docs[i], -1, i)); + } + return changes; + }) + : undefined; + resolve({ + transaction: output.transaction, + explainMetrics: output.explainMetrics, + result, + }); + }); + }); + } + // This method exists solely to enable unit tests to mock it. + _isPermanentRpcError(err, methodName) { + return (0, util_1.isPermanentRpcError)(err, methodName); + } + _hasRetryTimedOut(methodName, startTime) { + const totalTimeout = (0, util_1.getTotalTimeout)(methodName); + if (totalTimeout === 0) { + return false; + } + return Date.now() - startTime >= totalTimeout; + } + stream(query) { + if (this._queryOptions.limitType === types_1.LimitType.Last) { + throw new Error('Query results for queries that include limitToLast() ' + + 'constraints cannot be streamed. Use Query.get() instead.'); + } + const responseStream = this._stream(query); + const transform = new stream_1.Transform({ + objectMode: true, + transform(chunk, encoding, callback) { + callback(undefined, chunk.document); + }, + }); + responseStream.pipe(transform); + responseStream.on('error', e => transform.destroy(e)); + return transform; + } + _stream(query, transactionOrReadTime, retryWithCursor = true, explainOptions) { + const tag = (0, util_1.requestTag)(); + const startTime = Date.now(); + const isExplain = explainOptions !== undefined; + const methodName = 'runQuery'; + let numDocumentsReceived = 0; + let lastReceivedDocument = null; + let backendStream; + const stream = new stream_1.Transform({ + objectMode: true, + transform: (proto, enc, callback) => { + var _a; + if (proto === constants_1.NOOP_MESSAGE) { + callback(undefined); + return; + } + const output = {}; + // Proto comes with zero-length buffer by default + if ((_a = proto.transaction) === null || _a === void 0 ? void 0 : _a.length) { + output.transaction = proto.transaction; + } + if (proto.readTime) { + output.readTime = timestamp_1.Timestamp.fromProto(proto.readTime); + } + if (proto.document) { + const document = this._firestore.snapshot_(proto.document, proto.readTime); + const finalDoc = new document_1.DocumentSnapshotBuilder(document.ref.withConverter(this._queryOptions.converter)); + // Recreate the QueryDocumentSnapshot with the DocumentReference + // containing the original converter. + finalDoc.fieldsProto = document._fieldsProto; + finalDoc.readTime = document.readTime; + finalDoc.createTime = document.createTime; + finalDoc.updateTime = document.updateTime; + lastReceivedDocument = finalDoc.build(); + output.document = lastReceivedDocument; + } + if (proto.explainMetrics) { + output.explainMetrics = query_profile_1.ExplainMetrics._fromProto(proto.explainMetrics, this._serializer); + } + ++numDocumentsReceived; + callback(undefined, output); + if (proto.done) { + (0, logger_1.logger)('QueryUtil._stream', tag, 'Trigger Logical Termination.'); + this._firestore._traceUtil + .currentSpan() + .addEvent(`Firestore.${methodName}: Received RunQueryResponse.Done.`); + backendStream.unpipe(stream); + backendStream.resume(); + backendStream.end(); + stream.end(); + } + }, + }); + this._firestore + .initializeIfNeeded(tag) + .then(async () => { + // `toProto()` might throw an exception. We rely on the behavior of an + // async function to convert this exception into the rejected Promise we + // catch below. + let request = query.toProto(transactionOrReadTime, explainOptions); + let isRetryRequestWithCursor = false; + let streamActive; + do { + streamActive = new util_1.Deferred(); + this._firestore._traceUtil + .currentSpan() + .addEvent(trace_util_1.SPAN_NAME_RUN_QUERY, { + [trace_util_1.ATTRIBUTE_KEY_IS_TRANSACTIONAL]: !!request.transaction, + [trace_util_1.ATTRIBUTE_KEY_IS_RETRY_WITH_CURSOR]: isRetryRequestWithCursor, + }); + backendStream = await this._firestore.requestStream(methodName, + /* bidirectional= */ false, request, tag); + backendStream.on('error', err => { + backendStream.unpipe(stream); + // If a non-transactional query failed, attempt to restart. + // Transactional queries are retried via the transaction runner. + // Explain queries are not retried with a cursor. That would produce + // incorrect/partial profiling results. + if (!isExplain && + !transactionOrReadTime && + !this._isPermanentRpcError(err, methodName)) { + (0, logger_1.logger)('QueryUtil._stream', tag, 'Query failed with retryable stream error:', err); + this._firestore._traceUtil + .currentSpan() + .addEvent(`${trace_util_1.SPAN_NAME_RUN_QUERY}: Retryable Error.`, { + 'error.message': err.message, + }); + // Enqueue a "no-op" write into the stream and wait for it to be + // read by the downstream consumer. This ensures that all enqueued + // results in the stream are consumed, which will give us an accurate + // value for `lastReceivedDocument`. + stream.write(constants_1.NOOP_MESSAGE, () => { + if (this._hasRetryTimedOut(methodName, startTime)) { + (0, logger_1.logger)('QueryUtil._stream', tag, 'Query failed with retryable stream error but the total retry timeout has exceeded.'); + stream.destroy(err); + streamActive.resolve(/* active= */ false); + } + else if (lastReceivedDocument && retryWithCursor) { + if (query instanceof vector_query_1.VectorQuery) { + throw new Error('Unimplemented: Vector query does not support cursors yet.'); + } + (0, logger_1.logger)('Query._stream', tag, 'Query failed with retryable stream error and progress was made receiving ' + + 'documents, so the stream is being retried.'); + isRetryRequestWithCursor = true; + // Restart the query but use the last document we received as + // the query cursor. Note that we do not use backoff here. The + // call to `requestStream()` will backoff should the restart + // fail before delivering any results. + let newQuery; + if (!this._queryOptions.limit) { + newQuery = query; + } + else { + const newLimit = this._queryOptions.limit - numDocumentsReceived; + if (this._queryOptions.limitType === undefined || + this._queryOptions.limitType === types_1.LimitType.First) { + newQuery = query.limit(newLimit); + } + else { + newQuery = query.limitToLast(newLimit); + } + } + if (this._queryOptions.requireConsistency) { + request = newQuery + .startAfter(lastReceivedDocument) + .toProto(lastReceivedDocument.readTime); + } + else { + request = newQuery + .startAfter(lastReceivedDocument) + .toProto(); + } + // Set lastReceivedDocument to null before each retry attempt to ensure the retry makes progress + lastReceivedDocument = null; + streamActive.resolve(/* active= */ true); + } + else { + (0, logger_1.logger)('QueryUtil._stream', tag, `Query failed with retryable stream error however either retryWithCursor="${retryWithCursor}", or ` + + 'no progress was made receiving documents, so the stream is being closed.'); + stream.destroy(err); + streamActive.resolve(/* active= */ false); + } + }); + } + else { + (0, logger_1.logger)('QueryUtil._stream', tag, 'Query failed with stream error:', err); + this._firestore._traceUtil + .currentSpan() + .addEvent(`${trace_util_1.SPAN_NAME_RUN_QUERY}: Error.`, { + 'error.message': err.message, + }); + stream.destroy(err); + streamActive.resolve(/* active= */ false); + } + }); + backendStream.on('end', () => { + streamActive.resolve(/* active= */ false); + }); + backendStream.resume(); + backendStream.pipe(stream); + } while (await streamActive.promise); + }) + .catch(e => stream.destroy(e)); + return stream; + } +} +exports.QueryUtil = QueryUtil; +//# sourceMappingURL=query-util.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/reference/query.d.ts b/node_modules/@google-cloud/firestore/build/src/reference/query.d.ts new file mode 100644 index 0000000..26edb22 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/query.d.ts @@ -0,0 +1,742 @@ +/** + * Copyright 2024 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. + */ +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; +import * as firestore from '@google-cloud/firestore'; +import { GoogleError } from 'google-gax'; +import { QueryUtil } from './query-util'; +import { Firestore, DocumentChange, DocumentSnapshot, FieldPath, Filter, QueryDocumentSnapshot, Timestamp } from '../index'; +import { QueryOptions } from './query-options'; +import { FieldOrder } from './field-order'; +import { FilterInternal } from './filter-internal'; +import { FieldFilterInternal } from './field-filter-internal'; +import { VectorQueryOptions } from './vector-query-options'; +import { QuerySnapshot } from './query-snapshot'; +import { Serializer } from '../serializer'; +import { ExplainResults } from '../query-profile'; +import { CompositeFilter, UnaryFilter } from '../filter'; +import { QueryResponse, QuerySnapshotResponse } from './types'; +import { AggregateQuery } from './aggregate-query'; +import { VectorQuery } from './vector-query'; +/** + * A Query refers to a query which you can read or stream from. You can also + * construct refined Query objects by adding filters and ordering. + * + * @class Query + */ +export declare class Query implements firestore.Query { + /** + * @internal + * @private + **/ + readonly _firestore: Firestore; + /** + * @internal + * @private + **/ + readonly _queryOptions: QueryOptions; + /** + * @internal + * @private + **/ + readonly _serializer: Serializer; + /** + * @internal + * @private + **/ + protected readonly _allowUndefined: boolean; + /** + * @internal + * @private + **/ + readonly _queryUtil: QueryUtil>; + /** + * @internal + * @private + * + * @param _firestore The Firestore Database client. + * @param _queryOptions Options that define the query. + */ + constructor( + /** + * @internal + * @private + **/ + _firestore: Firestore, + /** + * @internal + * @private + **/ + _queryOptions: QueryOptions); + /** + * Extracts field values from the DocumentSnapshot based on the provided + * field order. + * + * @private + * @internal + * @param documentSnapshot The document to extract the fields from. + * @param fieldOrders The field order that defines what fields we should + * extract. + * @return {Array.<*>} The field values to use. + */ + static _extractFieldValues(documentSnapshot: DocumentSnapshot, fieldOrders: FieldOrder[]): unknown[]; + /** + * The [Firestore]{@link Firestore} instance for the Firestore + * database (useful for performing transactions, etc.). + * + * @type {Firestore} + * @name Query#firestore + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.add({foo: 'bar'}).then(documentReference => { + * let firestore = documentReference.firestore; + * console.log(`Root location for document is ${firestore.formattedName}`); + * }); + * ``` + */ + get firestore(): Firestore; + /** + * Creates and returns a new [Query]{@link Query} with the additional filter + * that documents must contain the specified field and that its value should + * satisfy the relation constraint provided. + * + * This function returns a new (immutable) instance of the Query (rather than + * modify the existing instance) to impose the filter. + * + * @param {string|FieldPath} fieldPath The name of a property value to compare. + * @param {string} opStr A comparison operation in the form of a string. + * Acceptable operator strings are "<", "<=", "==", "!=", ">=", ">", "array-contains", + * "in", "not-in", and "array-contains-any". + * @param {*} value The value to which to compare the field for inclusion in + * a query. + * @returns {Query} The created Query. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.where('foo', '==', 'bar').get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + where(fieldPath: string | FieldPath, opStr: firestore.WhereFilterOp, value: unknown): Query; + /** + * Creates and returns a new [Query]{@link Query} with the additional filter + * that documents should satisfy the relation constraint(s) provided. + * + * This function returns a new (immutable) instance of the Query (rather than + * modify the existing instance) to impose the filter. + * + * @param {Filter} filter A unary or composite filter to apply to the Query. + * @returns {Query} The created Query. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.where(Filter.and(Filter.where('foo', '==', 'bar'), Filter.where('foo', '!=', 'baz'))).get() + * .then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + where(filter: Filter): Query; + /** + * @internal + * @private + */ + _parseFilter(filter: Filter): FilterInternal; + /** + * @internal + * @private + */ + _parseFieldFilter(fieldFilterData: UnaryFilter): FieldFilterInternal; + /** + * @internal + * @private + */ + _parseCompositeFilter(compositeFilterData: CompositeFilter): FilterInternal; + /** + * Creates and returns a new [Query]{@link Query} instance that applies a + * field mask to the result and returns only the specified subset of fields. + * You can specify a list of field paths to return, or use an empty list to + * only return the references of matching documents. + * + * Queries that contain field masks cannot be listened to via `onSnapshot()` + * listeners. + * + * This function returns a new (immutable) instance of the Query (rather than + * modify the existing instance) to impose the field mask. + * + * @param {...(string|FieldPath)} fieldPaths The field paths to return. + * @returns {Query} The created Query. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * let documentRef = collectionRef.doc('doc'); + * + * return documentRef.set({x:10, y:5}).then(() => { + * return collectionRef.where('x', '>', 5).select('y').get(); + * }).then((res) => { + * console.log(`y is ${res.docs[0].get('y')}.`); + * }); + * ``` + */ + select(...fieldPaths: Array): Query; + /** + * Creates and returns a new [Query]{@link Query} that's additionally sorted + * by the specified field, optionally in descending order instead of + * ascending. + * + * This function returns a new (immutable) instance of the Query (rather than + * modify the existing instance) to impose the field mask. + * + * @param {string|FieldPath} fieldPath The field to sort by. + * @param {string=} directionStr Optional direction to sort by ('asc' or + * 'desc'). If not specified, order will be ascending. + * @returns {Query} The created Query. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '>', 42); + * + * query.orderBy('foo', 'desc').get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + orderBy(fieldPath: string | firestore.FieldPath, directionStr?: firestore.OrderByDirection): Query; + /** + * Creates and returns a new [Query]{@link Query} that only returns the + * first matching documents. + * + * This function returns a new (immutable) instance of the Query (rather than + * modify the existing instance) to impose the limit. + * + * @param {number} limit The maximum number of items to return. + * @returns {Query} The created Query. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '>', 42); + * + * query.limit(1).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + limit(limit: number): Query; + /** + * Creates and returns a new [Query]{@link Query} that only returns the + * last matching documents. + * + * You must specify at least one orderBy clause for limitToLast queries, + * otherwise an exception will be thrown during execution. + * + * Results for limitToLast queries cannot be streamed via the `stream()` API. + * + * @param limit The maximum number of items to return. + * @return The created Query. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '>', 42); + * + * query.limitToLast(1).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Last matching document is ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + limitToLast(limit: number): Query; + /** + * Specifies the offset of the returned results. + * + * This function returns a new (immutable) instance of the + * [Query]{@link Query} (rather than modify the existing instance) + * to impose the offset. + * + * @param {number} offset The offset to apply to the Query results + * @returns {Query} The created Query. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '>', 42); + * + * query.limit(10).offset(20).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + offset(offset: number): Query; + /** + * Returns a query that counts the documents in the result set of this + * query. + * + * The returned query, when executed, counts the documents in the result set + * of this query without actually downloading the documents. + * + * Using the returned query to count the documents is efficient because only + * the final count, not the documents' data, is downloaded. The returned + * query can count the documents in cases where the result set is + * prohibitively large to download entirely (thousands of documents). + * + * @return a query that counts the documents in the result set of this + * query. The count can be retrieved from `snapshot.data().count`, where + * `snapshot` is the `AggregateQuerySnapshot` resulting from running the + * returned query. + */ + count(): AggregateQuery<{ + count: firestore.AggregateField; + }, AppModelType, DbModelType>; + /** + * Returns a query that can perform the given aggregations. + * + * The returned query, when executed, calculates the specified aggregations + * over the documents in the result set of this query without actually + * downloading the documents. + * + * Using the returned query to perform aggregations is efficient because only + * the final aggregation values, not the documents' data, is downloaded. The + * returned query can perform aggregations of the documents count the + * documents in cases where the result set is prohibitively large to download + * entirely (thousands of documents). + * + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateQuery = col.aggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const aggregateSnapshot = await aggregateQuery.get(); + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ + aggregate(aggregateSpec: T): AggregateQuery; + /** + * Returns a query that can perform vector distance (similarity) search with given parameters. + * + * The returned query, when executed, performs a distance (similarity) search on the specified + * `vectorField` against the given `queryVector` and returns the top documents that are closest + * to the `queryVector`. + * + * Only documents whose `vectorField` field is a {@link VectorValue} of the same dimension as `queryVector` + * participate in the query, all other documents are ignored. + * + * @example + * ``` + * // Returns the closest 10 documents whose Euclidean distance from their 'embedding' fields are closed to [41, 42]. + * const vectorQuery = col.findNearest('embedding', [41, 42], {limit: 10, distanceMeasure: 'EUCLIDEAN'}); + * + * const querySnapshot = await vectorQuery.get(); + * querySnapshot.forEach(...); + * ``` + * + * @param vectorField - A string or {@link FieldPath} specifying the vector field to search on. + * @param queryVector - The {@link VectorValue} used to measure the distance from `vectorField` values in the documents. + * @param options - Options control the vector query. `limit` specifies the upper bound of documents to return, must + * be a positive integer with a maximum value of 1000. `distanceMeasure` specifies what type of distance is calculated + * when performing the query. + * + * @deprecated Use the new {@link findNearest} implementation + * accepting a single `options` param. + */ + findNearest(vectorField: string | firestore.FieldPath, queryVector: firestore.VectorValue | Array, options: { + limit: number; + distanceMeasure: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT'; + }): VectorQuery; + /** + * Returns a query that can perform vector distance (similarity) search with given parameters. + * + * The returned query, when executed, performs a distance (similarity) search on the specified + * `vectorField` against the given `queryVector` and returns the top documents that are closest + * to the `queryVector`. + * + * Only documents whose `vectorField` field is a {@link VectorValue} of the same dimension as `queryVector` + * participate in the query, all other documents are ignored. + * + * @example + * ``` + * // Returns the closest 10 documents whose Euclidean distance from their 'embedding' fields are closed to [41, 42]. + * const vectorQuery = col.findNearest({ + * vectorField: 'embedding', + * queryVector: [41, 42], + * limit: 10, + * distanceMeasure: 'EUCLIDEAN', + * distanceResultField: 'distance', + * distanceThreshold: 0.125 + * }); + * + * const querySnapshot = await aggregateQuery.get(); + * querySnapshot.forEach(...); + * ``` + * @param options - An argument specifying the behavior of the {@link VectorQuery} returned by this function. + * See {@link VectorQueryOptions}. + */ + findNearest(options: VectorQueryOptions): VectorQuery; + _findNearest(options: VectorQueryOptions): VectorQuery; + /** + * Returns true if this `Query` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @return {boolean} true if this `Query` is equal to the provided value. + */ + isEqual(other: firestore.Query): boolean; + /** + * Returns the sorted array of inequality filter fields used in this query. + * + * @return An array of inequality filter fields sorted lexicographically by FieldPath. + */ + private getInequalityFilterFields; + /** + * Computes the backend ordering semantics for DocumentSnapshot cursors. + * + * @private + * @internal + * @param cursorValuesOrDocumentSnapshot The snapshot of the document or the + * set of field values to use as the boundary. + * @returns The implicit ordering semantics. + */ + private createImplicitOrderBy; + /** + * Builds a Firestore 'Position' proto message. + * + * @private + * @internal + * @param {Array.} fieldOrders The field orders to use for this + * cursor. + * @param {Array.} cursorValuesOrDocumentSnapshot The + * snapshot of the document or the set of field values to use as the boundary. + * @param before Whether the query boundary lies just before or after the + * provided data. + * @returns {Object} The proto message. + */ + private createCursor; + /** + * Validates that a value used with FieldValue.documentId() is either a + * string or a DocumentReference that is part of the query`s result set. + * Throws a validation error or returns a DocumentReference that can + * directly be used in the Query. + * + * @param val The value to validate. + * @throws If the value cannot be used for this query. + * @return If valid, returns a DocumentReference that can be used with the + * query. + * @private + * @internal + */ + private validateReference; + /** + * Creates and returns a new [Query]{@link Query} that starts at the provided + * set of field values relative to the order of the query. The order of the + * provided values must match the order of the order by clauses of the query. + * + * @param {...*|DocumentSnapshot} fieldValuesOrDocumentSnapshot The snapshot + * of the document the query results should start at or the field values to + * start this query at, in order of the query's order by. + * @returns {Query} A query with the new starting point. + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.orderBy('foo').startAt(42).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + startAt(...fieldValuesOrDocumentSnapshot: Array): Query; + /** + * Creates and returns a new [Query]{@link Query} that starts after the + * provided set of field values relative to the order of the query. The order + * of the provided values must match the order of the order by clauses of the + * query. + * + * @param {...*|DocumentSnapshot} fieldValuesOrDocumentSnapshot The snapshot + * of the document the query results should start after or the field values to + * start this query after, in order of the query's order by. + * @returns {Query} A query with the new starting point. + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.orderBy('foo').startAfter(42).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + startAfter(...fieldValuesOrDocumentSnapshot: Array): Query; + /** + * Creates and returns a new [Query]{@link Query} that ends before the set of + * field values relative to the order of the query. The order of the provided + * values must match the order of the order by clauses of the query. + * + * @param {...*|DocumentSnapshot} fieldValuesOrDocumentSnapshot The snapshot + * of the document the query results should end before or the field values to + * end this query before, in order of the query's order by. + * @returns {Query} A query with the new ending point. + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.orderBy('foo').endBefore(42).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + endBefore(...fieldValuesOrDocumentSnapshot: Array): Query; + /** + * Creates and returns a new [Query]{@link Query} that ends at the provided + * set of field values relative to the order of the query. The order of the + * provided values must match the order of the order by clauses of the query. + * + * @param {...*|DocumentSnapshot} fieldValuesOrDocumentSnapshot The snapshot + * of the document the query results should end at or the field values to end + * this query at, in order of the query's order by. + * @returns {Query} A query with the new ending point. + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.orderBy('foo').endAt(42).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + endAt(...fieldValuesOrDocumentSnapshot: Array): Query; + /** + * Executes the query and returns the results as a + * [QuerySnapshot]{@link QuerySnapshot}. + * + * @returns {Promise.} A Promise that resolves with the results + * of the Query. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + get(): Promise>; + /** + * Plans and optionally executes this query. Returns a Promise that will be + * resolved with the planner information, statistics from the query execution (if any), + * and the query results (if any). + * + * @return A Promise that will be resolved with the planner information, statistics + * from the query execution (if any), and the query results (if any). + */ + explain(options?: firestore.ExplainOptions): Promise>>; + /** + * Internal get() method that accepts an optional transaction options, and + * returns a query snapshot with transaction and explain metadata. + * + * @private + * @internal + * @param transactionOrReadTime A transaction ID, options to start a new + * transaction, or timestamp to use as read time. + */ + _get(transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions): Promise>>; + _getResponse(transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, explainOptions?: firestore.ExplainOptions): Promise>>; + /** + * Executes the query and streams the results as + * [QueryDocumentSnapshots]{@link QueryDocumentSnapshot}. + * + * @returns {Stream.} A stream of + * QueryDocumentSnapshots. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * let count = 0; + * + * query.stream().on('data', (documentSnapshot) => { + * console.log(`Found document with name '${documentSnapshot.id}'`); + * ++count; + * }).on('end', () => { + * console.log(`Total count is ${count}`); + * }); + * ``` + */ + stream(): NodeJS.ReadableStream; + /** + * Executes the query and streams the results as the following object: + * {document?: DocumentSnapshot, metrics?: ExplainMetrics} + * + * The stream surfaces documents one at a time as they are received from the + * server, and at the end, it will surface the metrics associated with + * executing the query. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * let count = 0; + * + * query.explainStream({analyze: true}).on('data', (data) => { + * if (data.document) { + * // Use data.document which is a DocumentSnapshot instance. + * console.log(`Found document with name '${data.document.id}'`); + * ++count; + * } + * if (data.metrics) { + * // Use data.metrics which is an ExplainMetrics instance. + * } + * }).on('end', () => { + * console.log(`Received ${count} documents.`); + * }); + * ``` + */ + explainStream(explainOptions?: firestore.ExplainOptions): NodeJS.ReadableStream; + /** + * Converts a QueryCursor to its proto representation. + * + * @param cursor The original cursor value + * @private + * @internal + */ + private toCursor; + /** + * Internal method for serializing a query to its RunQuery proto + * representation with an optional transaction id or read time. + * + * @param transactionOrReadTime A transaction ID, options to start a new + * transaction, or timestamp to use as read time. + * @param explainOptions Options to use for explaining the query (if any). + * @private + * @internal + * @returns Serialized JSON for the query. + */ + toProto(transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, explainOptions?: firestore.ExplainOptions): api.IRunQueryRequest; + /** + * Converts current Query to an IBundledQuery. + * + * @private + * @internal + */ + _toBundledQuery(): protos.firestore.IBundledQuery; + private toStructuredQuery; + /** + * @internal + * @private + * This method exists solely to maintain backward compatability. + */ + _isPermanentRpcError(err: GoogleError, methodName: string): boolean; + /** + * @internal + * @private + * This method exists solely to maintain backward compatability. + */ + _hasRetryTimedOut(methodName: string, startTime: number): boolean; + /** + * Internal streaming method that accepts an optional transaction ID. + * + * BEWARE: If `transactionOrReadTime` is `ITransactionOptions`, then the first + * response in the stream will be a transaction response. + * + * @param transactionOrReadTime A transaction ID, options to start a new + * transaction, or timestamp to use as read time. + * @param explainOptions Options to use for explaining the query (if any). + * @private + * @internal + * @returns A stream of document results, optionally preceded by a transaction response. + */ + _stream(transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, explainOptions?: firestore.ExplainOptions): NodeJS.ReadableStream; + /** + * Attaches a listener for QuerySnapshot events. + * + * @param {querySnapshotCallback} onNext A callback to be called every time + * a new [QuerySnapshot]{@link QuerySnapshot} is available. + * @param {errorCallback=} onError A callback to be called if the listen + * fails or is cancelled. No further callbacks will occur. + * + * @returns {function()} An unsubscribe function that can be called to cancel + * the snapshot listener. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * let unsubscribe = query.onSnapshot(querySnapshot => { + * console.log(`Received query snapshot of size ${querySnapshot.size}`); + * }, err => { + * console.log(`Encountered error: ${err}`); + * }); + * + * // Remove this listener. + * unsubscribe(); + * ``` + */ + onSnapshot(onNext: (snapshot: QuerySnapshot) => void, onError?: (error: Error) => void): () => void; + /** + * Returns a function that can be used to sort QueryDocumentSnapshots + * according to the sort criteria of this query. + * + * @private + * @internal + */ + comparator(): (s1: QueryDocumentSnapshot, s2: QueryDocumentSnapshot) => number; + withConverter(converter: null): Query; + withConverter(converter: firestore.FirestoreDataConverter): Query; + /** + * Construct the resulting snapshot for this query with given documents. + * + * @private + * @internal + */ + _createSnapshot(readTime: Timestamp, size: number, docs: () => Array>, changes: () => Array>): QuerySnapshot; +} diff --git a/node_modules/@google-cloud/firestore/build/src/reference/query.js b/node_modules/@google-cloud/firestore/build/src/reference/query.js new file mode 100644 index 0000000..c177c8a --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/query.js @@ -0,0 +1,1152 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Query = void 0; +const stream_1 = require("stream"); +const query_util_1 = require("./query-util"); +const index_1 = require("../index"); +const field_order_1 = require("./field-order"); +const field_filter_internal_1 = require("./field-filter-internal"); +const composite_filter_internal_1 = require("./composite-filter-internal"); +const constants_1 = require("./constants"); +const document_reference_1 = require("./document-reference"); +const query_snapshot_1 = require("./query-snapshot"); +const serializer_1 = require("../serializer"); +const query_profile_1 = require("../query-profile"); +const filter_1 = require("../filter"); +const path_1 = require("../path"); +const helpers_1 = require("./helpers"); +const validate_1 = require("../validate"); +const types_1 = require("./types"); +const aggregate_query_1 = require("./aggregate-query"); +const vector_query_1 = require("./vector-query"); +const order_1 = require("../order"); +const types_2 = require("../types"); +const trace_util_1 = require("../telemetry/trace-util"); +/** + * A Query refers to a query which you can read or stream from. You can also + * construct refined Query objects by adding filters and ordering. + * + * @class Query + */ +class Query { + /** + * @internal + * @private + * + * @param _firestore The Firestore Database client. + * @param _queryOptions Options that define the query. + */ + constructor( + /** + * @internal + * @private + **/ + _firestore, + /** + * @internal + * @private + **/ + _queryOptions) { + this._firestore = _firestore; + this._queryOptions = _queryOptions; + this._serializer = new serializer_1.Serializer(_firestore); + this._allowUndefined = + !!this._firestore._settings.ignoreUndefinedProperties; + this._queryUtil = new query_util_1.QueryUtil(_firestore, _queryOptions, this._serializer); + } + /** + * Extracts field values from the DocumentSnapshot based on the provided + * field order. + * + * @private + * @internal + * @param documentSnapshot The document to extract the fields from. + * @param fieldOrders The field order that defines what fields we should + * extract. + * @return {Array.<*>} The field values to use. + */ + static _extractFieldValues(documentSnapshot, fieldOrders) { + const fieldValues = []; + for (const fieldOrder of fieldOrders) { + if (index_1.FieldPath.documentId().isEqual(fieldOrder.field)) { + fieldValues.push(documentSnapshot.ref); + } + else { + const fieldValue = documentSnapshot.get(fieldOrder.field); + if (fieldValue === undefined) { + throw new Error(`Field "${fieldOrder.field}" is missing in the provided DocumentSnapshot. ` + + 'Please provide a document that contains values for all specified ' + + 'orderBy() and where() constraints.'); + } + else { + fieldValues.push(fieldValue); + } + } + } + return fieldValues; + } + /** + * The [Firestore]{@link Firestore} instance for the Firestore + * database (useful for performing transactions, etc.). + * + * @type {Firestore} + * @name Query#firestore + * @readonly + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.add({foo: 'bar'}).then(documentReference => { + * let firestore = documentReference.firestore; + * console.log(`Root location for document is ${firestore.formattedName}`); + * }); + * ``` + */ + get firestore() { + return this._firestore; + } + where(fieldPathOrFilter, opStr, value) { + let filter; + if (fieldPathOrFilter instanceof index_1.Filter) { + filter = fieldPathOrFilter; + } + else { + filter = index_1.Filter.where(fieldPathOrFilter, opStr, value); + } + if (this._queryOptions.startAt || this._queryOptions.endAt) { + throw new Error('Cannot specify a where() filter after calling startAt(), ' + + 'startAfter(), endBefore() or endAt().'); + } + const parsedFilter = this._parseFilter(filter); + if (parsedFilter.getFilters().length === 0) { + // Return the existing query if not adding any more filters (e.g. an empty composite filter). + return this; + } + const options = this._queryOptions.with({ + filters: this._queryOptions.filters.concat(parsedFilter), + }); + return new Query(this._firestore, options); + } + /** + * @internal + * @private + */ + _parseFilter(filter) { + if (filter instanceof filter_1.UnaryFilter) { + return this._parseFieldFilter(filter); + } + return this._parseCompositeFilter(filter); + } + /** + * @internal + * @private + */ + _parseFieldFilter(fieldFilterData) { + let value = fieldFilterData._getValue(); + let operator = fieldFilterData._getOperator(); + const fieldPath = fieldFilterData._getField(); + (0, path_1.validateFieldPath)('fieldPath', fieldPath); + operator = (0, helpers_1.validateQueryOperator)('opStr', operator, value); + (0, helpers_1.validateQueryValue)('value', value, this._allowUndefined); + const path = index_1.FieldPath.fromArgument(fieldPath); + if (index_1.FieldPath.documentId().isEqual(path)) { + if (operator === 'array-contains' || operator === 'array-contains-any') { + throw new Error(`Invalid Query. You can't perform '${operator}' ` + + 'queries on FieldPath.documentId().'); + } + else if (operator === 'in' || operator === 'not-in') { + if (!Array.isArray(value) || value.length === 0) { + throw new Error(`Invalid Query. A non-empty array is required for '${operator}' filters.`); + } + value = value.map(el => this.validateReference(el)); + } + else { + value = this.validateReference(value); + } + } + return new field_filter_internal_1.FieldFilterInternal(this._serializer, path, constants_1.comparisonOperators[operator], value); + } + /** + * @internal + * @private + */ + _parseCompositeFilter(compositeFilterData) { + const parsedFilters = compositeFilterData + ._getFilters() + .map(filter => this._parseFilter(filter)) + .filter(parsedFilter => parsedFilter.getFilters().length > 0); + // For composite filters containing 1 filter, return the only filter. + // For example: AND(FieldFilter1) == FieldFilter1 + if (parsedFilters.length === 1) { + return parsedFilters[0]; + } + return new composite_filter_internal_1.CompositeFilterInternal(parsedFilters, compositeFilterData._getOperator() === 'AND' ? 'AND' : 'OR'); + } + /** + * Creates and returns a new [Query]{@link Query} instance that applies a + * field mask to the result and returns only the specified subset of fields. + * You can specify a list of field paths to return, or use an empty list to + * only return the references of matching documents. + * + * Queries that contain field masks cannot be listened to via `onSnapshot()` + * listeners. + * + * This function returns a new (immutable) instance of the Query (rather than + * modify the existing instance) to impose the field mask. + * + * @param {...(string|FieldPath)} fieldPaths The field paths to return. + * @returns {Query} The created Query. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * let documentRef = collectionRef.doc('doc'); + * + * return documentRef.set({x:10, y:5}).then(() => { + * return collectionRef.where('x', '>', 5).select('y').get(); + * }).then((res) => { + * console.log(`y is ${res.docs[0].get('y')}.`); + * }); + * ``` + */ + select(...fieldPaths) { + const fields = []; + if (fieldPaths.length === 0) { + fields.push({ fieldPath: index_1.FieldPath.documentId().formattedName }); + } + else { + for (let i = 0; i < fieldPaths.length; ++i) { + (0, path_1.validateFieldPath)(i, fieldPaths[i]); + fields.push({ + fieldPath: index_1.FieldPath.fromArgument(fieldPaths[i]).formattedName, + }); + } + } + // By specifying a field mask, the query result no longer conforms to type + // `T`. We there return `Query`; + const options = this._queryOptions.with({ + projection: { fields }, + }); + return new Query(this._firestore, options); + } + /** + * Creates and returns a new [Query]{@link Query} that's additionally sorted + * by the specified field, optionally in descending order instead of + * ascending. + * + * This function returns a new (immutable) instance of the Query (rather than + * modify the existing instance) to impose the field mask. + * + * @param {string|FieldPath} fieldPath The field to sort by. + * @param {string=} directionStr Optional direction to sort by ('asc' or + * 'desc'). If not specified, order will be ascending. + * @returns {Query} The created Query. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '>', 42); + * + * query.orderBy('foo', 'desc').get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + orderBy(fieldPath, directionStr) { + (0, path_1.validateFieldPath)('fieldPath', fieldPath); + directionStr = (0, helpers_1.validateQueryOrder)('directionStr', directionStr); + if (this._queryOptions.startAt || this._queryOptions.endAt) { + throw new Error('Cannot specify an orderBy() constraint after calling ' + + 'startAt(), startAfter(), endBefore() or endAt().'); + } + const newOrder = new field_order_1.FieldOrder(index_1.FieldPath.fromArgument(fieldPath), constants_1.directionOperators[directionStr || 'asc']); + const options = this._queryOptions.with({ + fieldOrders: this._queryOptions.fieldOrders.concat(newOrder), + }); + return new Query(this._firestore, options); + } + /** + * Creates and returns a new [Query]{@link Query} that only returns the + * first matching documents. + * + * This function returns a new (immutable) instance of the Query (rather than + * modify the existing instance) to impose the limit. + * + * @param {number} limit The maximum number of items to return. + * @returns {Query} The created Query. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '>', 42); + * + * query.limit(1).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + limit(limit) { + (0, validate_1.validateInteger)('limit', limit); + const options = this._queryOptions.with({ + limit, + limitType: types_1.LimitType.First, + }); + return new Query(this._firestore, options); + } + /** + * Creates and returns a new [Query]{@link Query} that only returns the + * last matching documents. + * + * You must specify at least one orderBy clause for limitToLast queries, + * otherwise an exception will be thrown during execution. + * + * Results for limitToLast queries cannot be streamed via the `stream()` API. + * + * @param limit The maximum number of items to return. + * @return The created Query. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '>', 42); + * + * query.limitToLast(1).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Last matching document is ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + limitToLast(limit) { + (0, validate_1.validateInteger)('limitToLast', limit); + const options = this._queryOptions.with({ limit, limitType: types_1.LimitType.Last }); + return new Query(this._firestore, options); + } + /** + * Specifies the offset of the returned results. + * + * This function returns a new (immutable) instance of the + * [Query]{@link Query} (rather than modify the existing instance) + * to impose the offset. + * + * @param {number} offset The offset to apply to the Query results + * @returns {Query} The created Query. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '>', 42); + * + * query.limit(10).offset(20).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + offset(offset) { + (0, validate_1.validateInteger)('offset', offset); + const options = this._queryOptions.with({ offset }); + return new Query(this._firestore, options); + } + /** + * Returns a query that counts the documents in the result set of this + * query. + * + * The returned query, when executed, counts the documents in the result set + * of this query without actually downloading the documents. + * + * Using the returned query to count the documents is efficient because only + * the final count, not the documents' data, is downloaded. The returned + * query can count the documents in cases where the result set is + * prohibitively large to download entirely (thousands of documents). + * + * @return a query that counts the documents in the result set of this + * query. The count can be retrieved from `snapshot.data().count`, where + * `snapshot` is the `AggregateQuerySnapshot` resulting from running the + * returned query. + */ + count() { + return this.aggregate({ + count: index_1.AggregateField.count(), + }); + } + /** + * Returns a query that can perform the given aggregations. + * + * The returned query, when executed, calculates the specified aggregations + * over the documents in the result set of this query without actually + * downloading the documents. + * + * Using the returned query to perform aggregations is efficient because only + * the final aggregation values, not the documents' data, is downloaded. The + * returned query can perform aggregations of the documents count the + * documents in cases where the result set is prohibitively large to download + * entirely (thousands of documents). + * + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateQuery = col.aggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const aggregateSnapshot = await aggregateQuery.get(); + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ + aggregate(aggregateSpec) { + return new aggregate_query_1.AggregateQuery(this, aggregateSpec); + } + findNearest(vectorFieldOrOptions, queryVector, options) { + if (typeof vectorFieldOrOptions === 'string' || + vectorFieldOrOptions instanceof index_1.FieldPath) { + const vqOptions = { + distanceMeasure: options.distanceMeasure, + limit: options.limit, + queryVector: queryVector, + vectorField: vectorFieldOrOptions, + }; + return this._findNearest(vqOptions); + } + else { + return this._findNearest(vectorFieldOrOptions); + } + } + _findNearest(options) { + (0, path_1.validateFieldPath)('vectorField', options.vectorField); + if (options.limit <= 0) { + throw (0, validate_1.invalidArgumentMessage)('limit', 'positive limit number'); + } + if ((Array.isArray(options.queryVector) + ? options.queryVector.length + : options.queryVector.toArray().length) === 0) { + throw (0, validate_1.invalidArgumentMessage)('queryVector', 'vector size must be larger than 0'); + } + return new vector_query_1.VectorQuery(this, options); + } + /** + * Returns true if this `Query` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @return {boolean} true if this `Query` is equal to the provided value. + */ + isEqual(other) { + if (this === other) { + return true; + } + return (other instanceof Query && this._queryOptions.isEqual(other._queryOptions)); + } + /** + * Returns the sorted array of inequality filter fields used in this query. + * + * @return An array of inequality filter fields sorted lexicographically by FieldPath. + */ + getInequalityFilterFields() { + const inequalityFields = []; + for (const filter of this._queryOptions.filters) { + for (const subFilter of filter.getFlattenedFilters()) { + if (subFilter.isInequalityFilter()) { + inequalityFields.push(subFilter.field); + } + } + } + return inequalityFields.sort((a, b) => a.compareTo(b)); + } + /** + * Computes the backend ordering semantics for DocumentSnapshot cursors. + * + * @private + * @internal + * @param cursorValuesOrDocumentSnapshot The snapshot of the document or the + * set of field values to use as the boundary. + * @returns The implicit ordering semantics. + */ + createImplicitOrderBy(cursorValuesOrDocumentSnapshot) { + // Add an implicit orderBy if the only cursor value is a DocumentSnapshot. + if (cursorValuesOrDocumentSnapshot.length !== 1 || + !(cursorValuesOrDocumentSnapshot[0] instanceof index_1.DocumentSnapshot)) { + return this._queryOptions.fieldOrders; + } + const fieldOrders = this._queryOptions.fieldOrders.slice(); + const fieldsNormalized = new Set([ + ...fieldOrders.map(item => item.field.toString()), + ]); + /** The order of the implicit ordering always matches the last explicit order by. */ + const lastDirection = fieldOrders.length === 0 + ? constants_1.directionOperators.ASC + : fieldOrders[fieldOrders.length - 1].direction; + /** + * Any inequality fields not explicitly ordered should be implicitly ordered in a + * lexicographical order. When there are multiple inequality filters on the same field, the + * field should be added only once. + * Note: getInequalityFilterFields function sorts the key field before + * other fields. However, we want the key field to be sorted last. + */ + const inequalityFields = this.getInequalityFilterFields(); + for (const field of inequalityFields) { + if (!fieldsNormalized.has(field.toString()) && + !field.isEqual(index_1.FieldPath.documentId())) { + fieldOrders.push(new field_order_1.FieldOrder(field, lastDirection)); + fieldsNormalized.add(field.toString()); + } + } + // Add the document key field to the last if it is not explicitly ordered. + if (!fieldsNormalized.has(index_1.FieldPath.documentId().toString())) { + fieldOrders.push(new field_order_1.FieldOrder(index_1.FieldPath.documentId(), lastDirection)); + } + return fieldOrders; + } + /** + * Builds a Firestore 'Position' proto message. + * + * @private + * @internal + * @param {Array.} fieldOrders The field orders to use for this + * cursor. + * @param {Array.} cursorValuesOrDocumentSnapshot The + * snapshot of the document or the set of field values to use as the boundary. + * @param before Whether the query boundary lies just before or after the + * provided data. + * @returns {Object} The proto message. + */ + createCursor(fieldOrders, cursorValuesOrDocumentSnapshot, before) { + let fieldValues; + if (cursorValuesOrDocumentSnapshot.length === 1 && + cursorValuesOrDocumentSnapshot[0] instanceof index_1.DocumentSnapshot) { + fieldValues = Query._extractFieldValues(cursorValuesOrDocumentSnapshot[0], fieldOrders); + } + else { + fieldValues = cursorValuesOrDocumentSnapshot; + } + if (fieldValues.length > fieldOrders.length) { + throw new Error('Too many cursor values specified. The specified ' + + 'values must match the orderBy() constraints of the query.'); + } + const options = { values: [], before }; + for (let i = 0; i < fieldValues.length; ++i) { + let fieldValue = fieldValues[i]; + if (index_1.FieldPath.documentId().isEqual(fieldOrders[i].field)) { + fieldValue = this.validateReference(fieldValue); + } + (0, helpers_1.validateQueryValue)(i, fieldValue, this._allowUndefined); + options.values.push(this._serializer.encodeValue(fieldValue)); + } + return options; + } + /** + * Validates that a value used with FieldValue.documentId() is either a + * string or a DocumentReference that is part of the query`s result set. + * Throws a validation error or returns a DocumentReference that can + * directly be used in the Query. + * + * @param val The value to validate. + * @throws If the value cannot be used for this query. + * @return If valid, returns a DocumentReference that can be used with the + * query. + * @private + * @internal + */ + validateReference(val) { + const basePath = this._queryOptions.allDescendants + ? this._queryOptions.parentPath + : this._queryOptions.parentPath.append(this._queryOptions.collectionId); + let reference; + if (typeof val === 'string') { + const path = basePath.append(val); + if (this._queryOptions.allDescendants) { + if (!path.isDocument) { + throw new Error('When querying a collection group and ordering by ' + + 'FieldPath.documentId(), the corresponding value must result in ' + + `a valid document path, but '${val}' is not because it ` + + 'contains an odd number of segments.'); + } + } + else if (val.indexOf('/') !== -1) { + throw new Error('When querying a collection and ordering by FieldPath.documentId(), ' + + `the corresponding value must be a plain document ID, but '${val}' ` + + 'contains a slash.'); + } + reference = new document_reference_1.DocumentReference(this._firestore, basePath.append(val), this._queryOptions.converter); + } + else if (val instanceof document_reference_1.DocumentReference) { + reference = val; + if (!basePath.isPrefixOf(reference._path)) { + throw new Error(`"${reference.path}" is not part of the query result set and ` + + 'cannot be used as a query boundary.'); + } + } + else { + throw new Error('The corresponding value for FieldPath.documentId() must be a ' + + `string or a DocumentReference, but was "${val}".`); + } + if (!this._queryOptions.allDescendants && + reference._path.parent().compareTo(basePath) !== 0) { + throw new Error('Only a direct child can be used as a query boundary. ' + + `Found: "${reference.path}".`); + } + return reference; + } + /** + * Creates and returns a new [Query]{@link Query} that starts at the provided + * set of field values relative to the order of the query. The order of the + * provided values must match the order of the order by clauses of the query. + * + * @param {...*|DocumentSnapshot} fieldValuesOrDocumentSnapshot The snapshot + * of the document the query results should start at or the field values to + * start this query at, in order of the query's order by. + * @returns {Query} A query with the new starting point. + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.orderBy('foo').startAt(42).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + startAt(...fieldValuesOrDocumentSnapshot) { + (0, validate_1.validateMinNumberOfArguments)('Query.startAt', fieldValuesOrDocumentSnapshot, 1); + const fieldOrders = this.createImplicitOrderBy(fieldValuesOrDocumentSnapshot); + const startAt = this.createCursor(fieldOrders, fieldValuesOrDocumentSnapshot, true); + const options = this._queryOptions.with({ fieldOrders, startAt }); + return new Query(this._firestore, options); + } + /** + * Creates and returns a new [Query]{@link Query} that starts after the + * provided set of field values relative to the order of the query. The order + * of the provided values must match the order of the order by clauses of the + * query. + * + * @param {...*|DocumentSnapshot} fieldValuesOrDocumentSnapshot The snapshot + * of the document the query results should start after or the field values to + * start this query after, in order of the query's order by. + * @returns {Query} A query with the new starting point. + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.orderBy('foo').startAfter(42).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + startAfter(...fieldValuesOrDocumentSnapshot) { + (0, validate_1.validateMinNumberOfArguments)('Query.startAfter', fieldValuesOrDocumentSnapshot, 1); + const fieldOrders = this.createImplicitOrderBy(fieldValuesOrDocumentSnapshot); + const startAt = this.createCursor(fieldOrders, fieldValuesOrDocumentSnapshot, false); + const options = this._queryOptions.with({ fieldOrders, startAt }); + return new Query(this._firestore, options); + } + /** + * Creates and returns a new [Query]{@link Query} that ends before the set of + * field values relative to the order of the query. The order of the provided + * values must match the order of the order by clauses of the query. + * + * @param {...*|DocumentSnapshot} fieldValuesOrDocumentSnapshot The snapshot + * of the document the query results should end before or the field values to + * end this query before, in order of the query's order by. + * @returns {Query} A query with the new ending point. + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.orderBy('foo').endBefore(42).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + endBefore(...fieldValuesOrDocumentSnapshot) { + (0, validate_1.validateMinNumberOfArguments)('Query.endBefore', fieldValuesOrDocumentSnapshot, 1); + const fieldOrders = this.createImplicitOrderBy(fieldValuesOrDocumentSnapshot); + const endAt = this.createCursor(fieldOrders, fieldValuesOrDocumentSnapshot, true); + const options = this._queryOptions.with({ fieldOrders, endAt }); + return new Query(this._firestore, options); + } + /** + * Creates and returns a new [Query]{@link Query} that ends at the provided + * set of field values relative to the order of the query. The order of the + * provided values must match the order of the order by clauses of the query. + * + * @param {...*|DocumentSnapshot} fieldValuesOrDocumentSnapshot The snapshot + * of the document the query results should end at or the field values to end + * this query at, in order of the query's order by. + * @returns {Query} A query with the new ending point. + * + * @example + * ``` + * let query = firestore.collection('col'); + * + * query.orderBy('foo').endAt(42).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + endAt(...fieldValuesOrDocumentSnapshot) { + (0, validate_1.validateMinNumberOfArguments)('Query.endAt', fieldValuesOrDocumentSnapshot, 1); + const fieldOrders = this.createImplicitOrderBy(fieldValuesOrDocumentSnapshot); + const endAt = this.createCursor(fieldOrders, fieldValuesOrDocumentSnapshot, false); + const options = this._queryOptions.with({ fieldOrders, endAt }); + return new Query(this._firestore, options); + } + /** + * Executes the query and returns the results as a + * [QuerySnapshot]{@link QuerySnapshot}. + * + * @returns {Promise.} A Promise that resolves with the results + * of the Query. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + async get() { + return this._firestore._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_QUERY_GET, async () => { + const { result } = await this._get(); + return result; + }); + } + /** + * Plans and optionally executes this query. Returns a Promise that will be + * resolved with the planner information, statistics from the query execution (if any), + * and the query results (if any). + * + * @return A Promise that will be resolved with the planner information, statistics + * from the query execution (if any), and the query results (if any). + */ + async explain(options) { + if (options === undefined) { + options = {}; + } + const { result, explainMetrics } = await this._getResponse(undefined, options); + if (!explainMetrics) { + throw new Error('No explain results'); + } + return new query_profile_1.ExplainResults(explainMetrics, result || null); + } + /** + * Internal get() method that accepts an optional transaction options, and + * returns a query snapshot with transaction and explain metadata. + * + * @private + * @internal + * @param transactionOrReadTime A transaction ID, options to start a new + * transaction, or timestamp to use as read time. + */ + async _get(transactionOrReadTime) { + const result = await this._getResponse(transactionOrReadTime); + if (!result.result) { + throw new Error('No QuerySnapshot result'); + } + return result; + } + _getResponse(transactionOrReadTime, explainOptions) { + return this._queryUtil._getResponse(this, transactionOrReadTime, true, explainOptions); + } + /** + * Executes the query and streams the results as + * [QueryDocumentSnapshots]{@link QueryDocumentSnapshot}. + * + * @returns {Stream.} A stream of + * QueryDocumentSnapshots. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * let count = 0; + * + * query.stream().on('data', (documentSnapshot) => { + * console.log(`Found document with name '${documentSnapshot.id}'`); + * ++count; + * }).on('end', () => { + * console.log(`Total count is ${count}`); + * }); + * ``` + */ + stream() { + return this._queryUtil.stream(this); + } + /** + * Executes the query and streams the results as the following object: + * {document?: DocumentSnapshot, metrics?: ExplainMetrics} + * + * The stream surfaces documents one at a time as they are received from the + * server, and at the end, it will surface the metrics associated with + * executing the query. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * let count = 0; + * + * query.explainStream({analyze: true}).on('data', (data) => { + * if (data.document) { + * // Use data.document which is a DocumentSnapshot instance. + * console.log(`Found document with name '${data.document.id}'`); + * ++count; + * } + * if (data.metrics) { + * // Use data.metrics which is an ExplainMetrics instance. + * } + * }).on('end', () => { + * console.log(`Received ${count} documents.`); + * }); + * ``` + */ + explainStream(explainOptions) { + if (explainOptions === undefined) { + explainOptions = {}; + } + if (this._queryOptions.limitType === types_1.LimitType.Last) { + throw new Error('Query results for queries that include limitToLast() ' + + 'constraints cannot be streamed. Use Query.explain() instead.'); + } + const responseStream = this._stream(undefined, explainOptions); + const transform = new stream_1.Transform({ + objectMode: true, + transform(chunk, encoding, callback) { + if (chunk.document || chunk.explainMetrics) { + callback(undefined, { + document: chunk.document, + metrics: chunk.explainMetrics, + }); + } + }, + }); + responseStream.pipe(transform); + responseStream.on('error', e => transform.destroy(e)); + return transform; + } + /** + * Converts a QueryCursor to its proto representation. + * + * @param cursor The original cursor value + * @private + * @internal + */ + toCursor(cursor) { + if (cursor) { + return cursor.before + ? { before: true, values: cursor.values } + : { values: cursor.values }; + } + return undefined; + } + /** + * Internal method for serializing a query to its RunQuery proto + * representation with an optional transaction id or read time. + * + * @param transactionOrReadTime A transaction ID, options to start a new + * transaction, or timestamp to use as read time. + * @param explainOptions Options to use for explaining the query (if any). + * @private + * @internal + * @returns Serialized JSON for the query. + */ + toProto(transactionOrReadTime, explainOptions) { + const projectId = this.firestore.projectId; + const databaseId = this.firestore.databaseId; + const parentPath = this._queryOptions.parentPath.toQualifiedResourcePath(projectId, databaseId); + const structuredQuery = this.toStructuredQuery(); + // For limitToLast queries, the structured query has to be translated to a version with + // reversed ordered, and flipped startAt/endAt to work properly. + if (this._queryOptions.limitType === types_1.LimitType.Last) { + if (!this._queryOptions.hasFieldOrders()) { + throw new Error('limitToLast() queries require specifying at least one orderBy() clause.'); + } + structuredQuery.orderBy = this._queryOptions.fieldOrders.map(order => { + // Flip the orderBy directions since we want the last results + const dir = order.direction === 'DESCENDING' ? 'ASCENDING' : 'DESCENDING'; + return new field_order_1.FieldOrder(order.field, dir).toProto(); + }); + // Swap the cursors to match the now-flipped query ordering. + structuredQuery.startAt = this._queryOptions.endAt + ? this.toCursor({ + values: this._queryOptions.endAt.values, + before: !this._queryOptions.endAt.before, + }) + : undefined; + structuredQuery.endAt = this._queryOptions.startAt + ? this.toCursor({ + values: this._queryOptions.startAt.values, + before: !this._queryOptions.startAt.before, + }) + : undefined; + } + const runQueryRequest = { + parent: parentPath.formattedName, + structuredQuery, + }; + if (transactionOrReadTime instanceof Uint8Array) { + runQueryRequest.transaction = transactionOrReadTime; + } + else if (transactionOrReadTime instanceof index_1.Timestamp) { + runQueryRequest.readTime = transactionOrReadTime.toProto().timestampValue; + } + else if (transactionOrReadTime) { + runQueryRequest.newTransaction = transactionOrReadTime; + } + if (explainOptions) { + runQueryRequest.explainOptions = explainOptions; + } + return runQueryRequest; + } + /** + * Converts current Query to an IBundledQuery. + * + * @private + * @internal + */ + _toBundledQuery() { + const projectId = this.firestore.projectId; + const databaseId = this.firestore.databaseId; + const parentPath = this._queryOptions.parentPath.toQualifiedResourcePath(projectId, databaseId); + const structuredQuery = this.toStructuredQuery(); + const bundledQuery = { + parent: parentPath.formattedName, + structuredQuery, + }; + if (this._queryOptions.limitType === types_1.LimitType.First) { + bundledQuery.limitType = 'FIRST'; + } + else if (this._queryOptions.limitType === types_1.LimitType.Last) { + bundledQuery.limitType = 'LAST'; + } + return bundledQuery; + } + toStructuredQuery() { + const structuredQuery = { + from: [{}], + }; + if (this._queryOptions.allDescendants) { + structuredQuery.from[0].allDescendants = true; + } + // Kindless queries select all descendant documents, so we remove the + // collectionId field. + if (!this._queryOptions.kindless) { + structuredQuery.from[0].collectionId = this._queryOptions.collectionId; + } + if (this._queryOptions.filters.length >= 1) { + structuredQuery.where = new composite_filter_internal_1.CompositeFilterInternal(this._queryOptions.filters, 'AND').toProto(); + } + if (this._queryOptions.hasFieldOrders()) { + structuredQuery.orderBy = this._queryOptions.fieldOrders.map(o => o.toProto()); + } + structuredQuery.startAt = this.toCursor(this._queryOptions.startAt); + structuredQuery.endAt = this.toCursor(this._queryOptions.endAt); + if (this._queryOptions.limit) { + structuredQuery.limit = { value: this._queryOptions.limit }; + } + structuredQuery.offset = this._queryOptions.offset; + structuredQuery.select = this._queryOptions.projection; + return structuredQuery; + } + /** + * @internal + * @private + * This method exists solely to maintain backward compatability. + */ + _isPermanentRpcError(err, methodName) { + return this._queryUtil._isPermanentRpcError(err, methodName); + } + /** + * @internal + * @private + * This method exists solely to maintain backward compatability. + */ + _hasRetryTimedOut(methodName, startTime) { + return this._queryUtil._hasRetryTimedOut(methodName, startTime); + } + /** + * Internal streaming method that accepts an optional transaction ID. + * + * BEWARE: If `transactionOrReadTime` is `ITransactionOptions`, then the first + * response in the stream will be a transaction response. + * + * @param transactionOrReadTime A transaction ID, options to start a new + * transaction, or timestamp to use as read time. + * @param explainOptions Options to use for explaining the query (if any). + * @private + * @internal + * @returns A stream of document results, optionally preceded by a transaction response. + */ + _stream(transactionOrReadTime, explainOptions) { + return this._queryUtil._stream(this, transactionOrReadTime, true, explainOptions); + } + /** + * Attaches a listener for QuerySnapshot events. + * + * @param {querySnapshotCallback} onNext A callback to be called every time + * a new [QuerySnapshot]{@link QuerySnapshot} is available. + * @param {errorCallback=} onError A callback to be called if the listen + * fails or is cancelled. No further callbacks will occur. + * + * @returns {function()} An unsubscribe function that can be called to cancel + * the snapshot listener. + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * let unsubscribe = query.onSnapshot(querySnapshot => { + * console.log(`Received query snapshot of size ${querySnapshot.size}`); + * }, err => { + * console.log(`Encountered error: ${err}`); + * }); + * + * // Remove this listener. + * unsubscribe(); + * ``` + */ + onSnapshot(onNext, onError) { + (0, validate_1.validateFunction)('onNext', onNext); + (0, validate_1.validateFunction)('onError', onError, { optional: true }); + const watch = new (require('../watch').QueryWatch)(this.firestore, this, this._queryOptions.converter); + return watch.onSnapshot((readTime, size, docs, changes) => { + onNext(new query_snapshot_1.QuerySnapshot(this, readTime, size, docs, changes)); + }, onError || console.error); + } + /** + * Returns a function that can be used to sort QueryDocumentSnapshots + * according to the sort criteria of this query. + * + * @private + * @internal + */ + comparator() { + return (doc1, doc2) => { + // Add implicit sorting by name, using the last specified direction. + const lastDirection = this._queryOptions.hasFieldOrders() + ? this._queryOptions.fieldOrders[this._queryOptions.fieldOrders.length - 1].direction + : 'ASCENDING'; + const orderBys = this._queryOptions.fieldOrders.concat(new field_order_1.FieldOrder(index_1.FieldPath.documentId(), lastDirection)); + for (const orderBy of orderBys) { + let comp; + if (index_1.FieldPath.documentId().isEqual(orderBy.field)) { + comp = doc1.ref._path.compareTo(doc2.ref._path); + } + else { + const v1 = doc1.protoField(orderBy.field); + const v2 = doc2.protoField(orderBy.field); + if (v1 === undefined || v2 === undefined) { + throw new Error('Trying to compare documents on fields that ' + + "don't exist. Please include the fields you are ordering on " + + 'in your select() call.'); + } + comp = (0, order_1.compare)(v1, v2); + } + if (comp !== 0) { + const direction = orderBy.direction === 'ASCENDING' ? 1 : -1; + return direction * comp; + } + } + return 0; + }; + } + /** + * Applies a custom data converter to this Query, allowing you to use your + * own custom model objects with Firestore. When you call get() on the + * returned Query, the provided converter will convert between Firestore + * data of type `NewDbModelType` and your custom type `NewAppModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * Passing in `null` as the converter parameter removes the current + * converter. + * + * @example + * ``` + * class Post { + * constructor(readonly title: string, readonly author: string) {} + * + * toString(): string { + * return this.title + ', by ' + this.author; + * } + * } + * + * const postConverter = { + * toFirestore(post: Post): FirebaseFirestore.DocumentData { + * return {title: post.title, author: post.author}; + * }, + * fromFirestore( + * snapshot: FirebaseFirestore.QueryDocumentSnapshot + * ): Post { + * const data = snapshot.data(); + * return new Post(data.title, data.author); + * } + * }; + * + * const postSnap = await Firestore() + * .collection('posts') + * .withConverter(postConverter) + * .doc().get(); + * const post = postSnap.data(); + * if (post !== undefined) { + * post.title; // string + * post.toString(); // Should be defined + * post.someNonExistentProperty; // TS error + * } + * + * ``` + * @param {FirestoreDataConverter | null} converter Converts objects to and + * from Firestore. Passing in `null` removes the current converter. + * @return A Query that uses the provided converter. + */ + withConverter(converter) { + return new Query(this.firestore, this._queryOptions.withConverter(converter !== null && converter !== void 0 ? converter : (0, types_2.defaultConverter)())); + } + /** + * Construct the resulting snapshot for this query with given documents. + * + * @private + * @internal + */ + _createSnapshot(readTime, size, docs, changes) { + return new query_snapshot_1.QuerySnapshot(this, readTime, size, docs, changes); + } +} +exports.Query = Query; +//# sourceMappingURL=query.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/reference/types.d.ts b/node_modules/@google-cloud/firestore/build/src/reference/types.d.ts new file mode 100644 index 0000000..e144d5e --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/types.d.ts @@ -0,0 +1,66 @@ +/** + * Copyright 2024 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. + */ +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; +import { Timestamp } from '../timestamp'; +import { ExplainMetrics } from '../query-profile'; +import { QueryDocumentSnapshot } from '../document'; +import * as firestore from '@google-cloud/firestore'; +export interface QueryStreamElement { + transaction?: Uint8Array; + readTime?: Timestamp; + explainMetrics?: ExplainMetrics; + document?: QueryDocumentSnapshot; +} +export interface QueryResponse { + transaction?: Uint8Array; + explainMetrics?: ExplainMetrics; + result?: TSnapshot; +} +export interface QuerySnapshotResponse extends QueryResponse { + result: TSnapshot; +} +/** Internal representation of a query cursor before serialization. */ +export interface QueryCursor { + before: boolean; + values: api.IValue[]; +} +/*! + * Denotes whether a provided limit is applied to the beginning or the end of + * the result set. + */ +export declare enum LimitType { + First = 0, + Last = 1 +} +/** + * onSnapshot() callback that receives a QuerySnapshot. + * + * @callback querySnapshotCallback + * @param {QuerySnapshot} snapshot A query snapshot. + */ +/** + * onSnapshot() callback that receives a DocumentSnapshot. + * + * @callback documentSnapshotCallback + * @param {DocumentSnapshot} snapshot A document snapshot. + */ +/** + * onSnapshot() callback that receives an error. + * + * @callback errorCallback + * @param {Error} err An error from a listen. + */ diff --git a/node_modules/@google-cloud/firestore/build/src/reference/types.js b/node_modules/@google-cloud/firestore/build/src/reference/types.js new file mode 100644 index 0000000..c2132d8 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/types.js @@ -0,0 +1,46 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LimitType = void 0; +/*! + * Denotes whether a provided limit is applied to the beginning or the end of + * the result set. + */ +var LimitType; +(function (LimitType) { + LimitType[LimitType["First"] = 0] = "First"; + LimitType[LimitType["Last"] = 1] = "Last"; +})(LimitType || (exports.LimitType = LimitType = {})); +/** + * onSnapshot() callback that receives a QuerySnapshot. + * + * @callback querySnapshotCallback + * @param {QuerySnapshot} snapshot A query snapshot. + */ +/** + * onSnapshot() callback that receives a DocumentSnapshot. + * + * @callback documentSnapshotCallback + * @param {DocumentSnapshot} snapshot A document snapshot. + */ +/** + * onSnapshot() callback that receives an error. + * + * @callback errorCallback + * @param {Error} err An error from a listen. + */ +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/reference/vector-query-options.d.ts b/node_modules/@google-cloud/firestore/build/src/reference/vector-query-options.d.ts new file mode 100644 index 0000000..f8eebb7 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/vector-query-options.d.ts @@ -0,0 +1,54 @@ +/** + * Copyright 2024 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. + */ +import * as firestore from '@google-cloud/firestore'; +/** + * Specifies the behavior of the {@link VectorQuery} generated by a call to {@link Query.findNearest}. + */ +export interface VectorQueryOptions { + /** + * A string or {@link FieldPath} specifying the vector field to search on. + */ + vectorField: string | firestore.FieldPath; + /** + * The {@link VectorValue} used to measure the distance from `vectorField` values in the documents. + */ + queryVector: firestore.VectorValue | Array; + /** + * Specifies the upper bound of documents to return, must be a positive integer with a maximum value of 1000. + */ + limit: number; + /** + * Specifies what type of distance is calculated when performing the query. + */ + distanceMeasure: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT'; + /** + * Optionally specifies the name of a field that will be set on each returned DocumentSnapshot, + * which will contain the computed distance for the document. + */ + distanceResultField?: string | firestore.FieldPath; + /** + * Specifies a threshold for which no less similar documents will be returned. The behavior + * of the specified `distanceMeasure` will affect the meaning of the distance threshold. + * + * - For `distanceMeasure: "EUCLIDEAN"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE euclidean_distance <= distanceThreshold + * - For `distanceMeasure: "COSINE"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE cosine_distance <= distanceThreshold + * - For `distanceMeasure: "DOT_PRODUCT"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE dot_product_distance >= distanceThreshold + */ + distanceThreshold?: number; +} diff --git a/node_modules/@google-cloud/firestore/build/src/reference/vector-query-options.js b/node_modules/@google-cloud/firestore/build/src/reference/vector-query-options.js new file mode 100644 index 0000000..74e6f62 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/vector-query-options.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=vector-query-options.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/reference/vector-query-snapshot.d.ts b/node_modules/@google-cloud/firestore/build/src/reference/vector-query-snapshot.d.ts new file mode 100644 index 0000000..6f0e9d6 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/vector-query-snapshot.d.ts @@ -0,0 +1,191 @@ +/** + * Copyright 2024 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. + */ +import * as firestore from '@google-cloud/firestore'; +import { QueryDocumentSnapshot } from '../document'; +import { DocumentChange } from '../document-change'; +import { Timestamp } from '../timestamp'; +import { VectorQuery } from './vector-query'; +/** + * A `VectorQuerySnapshot` contains zero or more `QueryDocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +export declare class VectorQuerySnapshot implements firestore.VectorQuerySnapshot { + private readonly _query; + private readonly _readTime; + private readonly _size; + private _materializedDocs; + private _materializedChanges; + private _docs; + private _changes; + /** + * @private + * @internal + * + * @param _query - The originating query. + * @param _readTime - The time when this query snapshot was obtained. + * @param _size - The number of documents in the result set. + * @param docs - A callback returning a sorted array of documents matching + * this query + * @param changes - A callback returning a sorted array of document change + * events for this snapshot. + */ + constructor(_query: VectorQuery, _readTime: Timestamp, _size: number, docs: () => Array>, changes: () => Array>); + /** + * The `VectorQuery` on which you called get() in order to get this + * `VectorQuerySnapshot`. + * + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}) + * .get().then(querySnapshot => { + * console.log(`Returned first batch of results`); + * let query = querySnapshot.query; + * return query.offset(10).get(); + * }).then(() => { + * console.log(`Returned second batch of results`); + * }); + * ``` + */ + get query(): VectorQuery; + /** + * An array of all the documents in this `VectorQuerySnapshot`. + * + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col') + * .findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}); + * + * query.get().then(querySnapshot => { + * let docs = querySnapshot.docs; + * for (let doc of docs) { + * console.log(`Document found at path: ${doc.ref.path}`); + * } + * }); + * ``` + */ + get docs(): Array>; + /** + * `true` if there are no documents in the `VectorQuerySnapshot`. + * + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col') + * .findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}); + * + * query.get().then(querySnapshot => { + * if (querySnapshot.empty) { + * console.log('No documents found.'); + * } + * }); + * ``` + */ + get empty(): boolean; + /** + * The number of documents in the `VectorQuerySnapshot`. + * + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col') + * .findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}); + * + * query.get().then(querySnapshot => { + * console.log(`Found ${querySnapshot.size} documents.`); + * }); + * ``` + */ + get size(): number; + /** + * The time this `VectorQuerySnapshot` was obtained. + * + * @example + * ``` + * let query = firestore.collection('col') + * .findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}); + * + * query.get().then((querySnapshot) => { + * let readTime = querySnapshot.readTime; + * console.log(`Query results returned at '${readTime.toDate()}'`); + * }); + * ``` + */ + get readTime(): Timestamp; + /** + * Returns an array of the documents changes since the last snapshot. If + * this is the first snapshot, all documents will be in the list as added + * changes. + * + * @returns An array of the documents changes since the last snapshot. + * + * @example + * ``` + * let query = firestore.collection('col') + * .findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}); + * + * query.get().then(querySnapshot => { + * let changes = querySnapshot.docChanges(); + * for (let change of changes) { + * console.log(`A document was ${change.type}.`); + * } + * }); + * ``` + */ + docChanges(): Array>; + /** + * Enumerates all of the documents in the `VectorQuerySnapshot`. This is a convenience + * method for running the same callback on each {@link QueryDocumentSnapshot} + * that is returned. + * + * @param callback - A callback to be called with a + * {@link QueryDocumentSnapshot} for each document in + * the snapshot. + * @param thisArg - The `this` binding for the callback.. + * + * @example + * ``` + * let query = firestore.collection('col') + * .findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}); + * + * query.get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Document found at path: ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + forEach(callback: (result: firestore.QueryDocumentSnapshot) => void, thisArg?: unknown): void; + /** + * Returns true if the document data in this `VectorQuerySnapshot` is equal to the + * provided value. + * + * @param other - The value to compare against. + * @returns true if this `VectorQuerySnapshot` is equal to the provided + * value. + */ + isEqual(other: firestore.VectorQuerySnapshot): boolean; +} diff --git a/node_modules/@google-cloud/firestore/build/src/reference/vector-query-snapshot.js b/node_modules/@google-cloud/firestore/build/src/reference/vector-query-snapshot.js new file mode 100644 index 0000000..9091758 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/vector-query-snapshot.js @@ -0,0 +1,246 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.VectorQuerySnapshot = void 0; +const validate_1 = require("../validate"); +const util_1 = require("../util"); +/** + * A `VectorQuerySnapshot` contains zero or more `QueryDocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +class VectorQuerySnapshot { + /** + * @private + * @internal + * + * @param _query - The originating query. + * @param _readTime - The time when this query snapshot was obtained. + * @param _size - The number of documents in the result set. + * @param docs - A callback returning a sorted array of documents matching + * this query + * @param changes - A callback returning a sorted array of document change + * events for this snapshot. + */ + constructor(_query, _readTime, _size, docs, changes) { + this._query = _query; + this._readTime = _readTime; + this._size = _size; + this._materializedDocs = null; + this._materializedChanges = null; + this._docs = null; + this._changes = null; + this._docs = docs; + this._changes = changes; + } + /** + * The `VectorQuery` on which you called get() in order to get this + * `VectorQuerySnapshot`. + * + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * query.findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}) + * .get().then(querySnapshot => { + * console.log(`Returned first batch of results`); + * let query = querySnapshot.query; + * return query.offset(10).get(); + * }).then(() => { + * console.log(`Returned second batch of results`); + * }); + * ``` + */ + get query() { + return this._query; + } + /** + * An array of all the documents in this `VectorQuerySnapshot`. + * + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col') + * .findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}); + * + * query.get().then(querySnapshot => { + * let docs = querySnapshot.docs; + * for (let doc of docs) { + * console.log(`Document found at path: ${doc.ref.path}`); + * } + * }); + * ``` + */ + get docs() { + if (this._materializedDocs) { + return this._materializedDocs; + } + this._materializedDocs = this._docs(); + this._docs = null; + return this._materializedDocs; + } + /** + * `true` if there are no documents in the `VectorQuerySnapshot`. + * + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col') + * .findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}); + * + * query.get().then(querySnapshot => { + * if (querySnapshot.empty) { + * console.log('No documents found.'); + * } + * }); + * ``` + */ + get empty() { + return this._size === 0; + } + /** + * The number of documents in the `VectorQuerySnapshot`. + * + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col') + * .findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}); + * + * query.get().then(querySnapshot => { + * console.log(`Found ${querySnapshot.size} documents.`); + * }); + * ``` + */ + get size() { + return this._size; + } + /** + * The time this `VectorQuerySnapshot` was obtained. + * + * @example + * ``` + * let query = firestore.collection('col') + * .findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}); + * + * query.get().then((querySnapshot) => { + * let readTime = querySnapshot.readTime; + * console.log(`Query results returned at '${readTime.toDate()}'`); + * }); + * ``` + */ + get readTime() { + return this._readTime; + } + /** + * Returns an array of the documents changes since the last snapshot. If + * this is the first snapshot, all documents will be in the list as added + * changes. + * + * @returns An array of the documents changes since the last snapshot. + * + * @example + * ``` + * let query = firestore.collection('col') + * .findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}); + * + * query.get().then(querySnapshot => { + * let changes = querySnapshot.docChanges(); + * for (let change of changes) { + * console.log(`A document was ${change.type}.`); + * } + * }); + * ``` + */ + docChanges() { + if (this._materializedChanges) { + return this._materializedChanges; + } + this._materializedChanges = this._changes(); + this._changes = null; + return this._materializedChanges; + } + /** + * Enumerates all of the documents in the `VectorQuerySnapshot`. This is a convenience + * method for running the same callback on each {@link QueryDocumentSnapshot} + * that is returned. + * + * @param callback - A callback to be called with a + * {@link QueryDocumentSnapshot} for each document in + * the snapshot. + * @param thisArg - The `this` binding for the callback.. + * + * @example + * ``` + * let query = firestore.collection('col') + * .findNearest("embedding", [0, 0], {limit: 10, distanceMeasure: "EUCLIDEAN"}); + * + * query.get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Document found at path: ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + forEach(callback, thisArg) { + (0, validate_1.validateFunction)('callback', callback); + for (const doc of this.docs) { + callback.call(thisArg, doc); + } + } + /** + * Returns true if the document data in this `VectorQuerySnapshot` is equal to the + * provided value. + * + * @param other - The value to compare against. + * @returns true if this `VectorQuerySnapshot` is equal to the provided + * value. + */ + isEqual(other) { + // Since the read time is different on every query read, we explicitly + // ignore all metadata in this comparison. + if (this === other) { + return true; + } + if (!(other instanceof VectorQuerySnapshot)) { + return false; + } + if (this._size !== other._size) { + return false; + } + if (!this._query.isEqual(other._query)) { + return false; + } + if (this._materializedDocs && !this._materializedChanges) { + // If we have only materialized the documents, we compare them first. + return ((0, util_1.isArrayEqual)(this.docs, other.docs) && + (0, util_1.isArrayEqual)(this.docChanges(), other.docChanges())); + } + // Otherwise, we compare the changes first as we expect there to be fewer. + return ((0, util_1.isArrayEqual)(this.docChanges(), other.docChanges()) && + (0, util_1.isArrayEqual)(this.docs, other.docs)); + } +} +exports.VectorQuerySnapshot = VectorQuerySnapshot; +//# sourceMappingURL=vector-query-snapshot.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/reference/vector-query.d.ts b/node_modules/@google-cloud/firestore/build/src/reference/vector-query.d.ts new file mode 100644 index 0000000..5330494 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/vector-query.d.ts @@ -0,0 +1,127 @@ +/** + * Copyright 2024 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. + */ +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; +import * as firestore from '@google-cloud/firestore'; +import { Timestamp } from '../timestamp'; +import { QueryDocumentSnapshot } from '../document'; +import { DocumentChange } from '../document-change'; +import { QueryUtil } from './query-util'; +import { Query } from './query'; +import { VectorQueryOptions } from './vector-query-options'; +import { VectorQuerySnapshot } from './vector-query-snapshot'; +import { ExplainResults } from '../query-profile'; +import { QueryResponse } from './types'; +/** + * A query that finds the documents whose vector fields are closest to a certain query vector. + * Create an instance of `VectorQuery` with {@link Query.findNearest}. + */ +export declare class VectorQuery implements firestore.VectorQuery { + private readonly _query; + private readonly _options; + /** + * @internal + * @private + **/ + readonly _queryUtil: QueryUtil>; + /** + * @private + * @internal + */ + constructor(_query: Query, _options: VectorQueryOptions); + /** The query whose results participants in the vector search. Filtering + * performed by the query will apply before the vector search. + **/ + get query(): Query; + /** + * @private + * @internal + */ + private get _rawVectorField(); + /** + * @private + * @internal + */ + private get _rawDistanceResultField(); + /** + * @private + * @internal + */ + private get _rawQueryVector(); + /** + * Plans and optionally executes this vector search query. Returns a Promise that will be + * resolved with the planner information, statistics from the query execution (if any), + * and the query results (if any). + * + * @return A Promise that will be resolved with the planner information, statistics + * from the query execution (if any), and the query results (if any). + */ + explain(options?: firestore.ExplainOptions): Promise>>; + /** + * Executes this vector search query. + * + * @returns A promise that will be resolved with the results of the query. + */ + get(): Promise>; + _getResponse(explainOptions?: firestore.ExplainOptions): Promise>>; + /** + * Internal streaming method that accepts an optional transaction ID. + * + * @param transactionId - A transaction ID. + * @private + * @internal + * @returns A stream of document results. + */ + _stream(transactionId?: Uint8Array): NodeJS.ReadableStream; + /** + * Internal method for serializing a query to its proto + * representation with an optional transaction id. + * + * @private + * @internal + * @returns Serialized JSON for the query. + */ + toProto(transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, explainOptions?: firestore.ExplainOptions): api.IRunQueryRequest; + /** + * Construct the resulting vector snapshot for this query with given documents. + * + * @private + * @internal + */ + _createSnapshot(readTime: Timestamp, size: number, docs: () => Array>, changes: () => Array>): VectorQuerySnapshot; + /** + * Construct a new vector query whose result will start after To support stream(). + * This now throws an exception because cursors are not supported from the backend for vector queries yet. + * + * @private + * @internal + * @returns Serialized JSON for the query. + */ + startAfter(...fieldValuesOrDocumentSnapshot: Array): VectorQuery; + /** + * Compares this object with the given object for equality. + * + * This object is considered "equal" to the other object if and only if + * `other` performs the same vector distance search as this `VectorQuery` and + * the underlying Query of `other` compares equal to that of this object + * using `Query.isEqual()`. + * + * @param other - The object to compare to this object for equality. + * @returns `true` if this object is "equal" to the given object, as + * defined above, or `false` otherwise. + */ + isEqual(other: firestore.VectorQuery): boolean; +} diff --git a/node_modules/@google-cloud/firestore/build/src/reference/vector-query.js b/node_modules/@google-cloud/firestore/build/src/reference/vector-query.js new file mode 100644 index 0000000..1c8ffc5 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/reference/vector-query.js @@ -0,0 +1,210 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.VectorQuery = void 0; +const field_value_1 = require("../field-value"); +const path_1 = require("../path"); +const util_1 = require("../util"); +const query_util_1 = require("./query-util"); +const vector_query_snapshot_1 = require("./vector-query-snapshot"); +const query_profile_1 = require("../query-profile"); +/** + * A query that finds the documents whose vector fields are closest to a certain query vector. + * Create an instance of `VectorQuery` with {@link Query.findNearest}. + */ +class VectorQuery { + /** + * @private + * @internal + */ + constructor(_query, _options) { + this._query = _query; + this._options = _options; + this._queryUtil = new query_util_1.QueryUtil(_query._firestore, _query._queryOptions, _query._serializer); + } + /** The query whose results participants in the vector search. Filtering + * performed by the query will apply before the vector search. + **/ + get query() { + return this._query; + } + /** + * @private + * @internal + */ + get _rawVectorField() { + return typeof this._options.vectorField === 'string' + ? this._options.vectorField + : this._options.vectorField.toString(); + } + /** + * @private + * @internal + */ + get _rawDistanceResultField() { + if (typeof this._options.distanceResultField === 'undefined') + return; + return typeof this._options.distanceResultField === 'string' + ? this._options.distanceResultField + : this._options.distanceResultField.toString(); + } + /** + * @private + * @internal + */ + get _rawQueryVector() { + return Array.isArray(this._options.queryVector) + ? this._options.queryVector + : this._options.queryVector.toArray(); + } + /** + * Plans and optionally executes this vector search query. Returns a Promise that will be + * resolved with the planner information, statistics from the query execution (if any), + * and the query results (if any). + * + * @return A Promise that will be resolved with the planner information, statistics + * from the query execution (if any), and the query results (if any). + */ + async explain(options) { + if (options === undefined) { + options = {}; + } + const { result, explainMetrics } = await this._getResponse(options); + if (!explainMetrics) { + throw new Error('No explain results'); + } + return new query_profile_1.ExplainResults(explainMetrics, result || null); + } + /** + * Executes this vector search query. + * + * @returns A promise that will be resolved with the results of the query. + */ + async get() { + const { result } = await this._getResponse(); + if (!result) { + throw new Error('No VectorQuerySnapshot result'); + } + return result; + } + _getResponse(explainOptions) { + return this._queryUtil._getResponse(this, + /*transactionOrReadTime*/ undefined, + // VectorQuery cannot be retried with cursors as they do not support cursors yet. + /*retryWithCursor*/ false, explainOptions); + } + /** + * Internal streaming method that accepts an optional transaction ID. + * + * @param transactionId - A transaction ID. + * @private + * @internal + * @returns A stream of document results. + */ + _stream(transactionId) { + return this._queryUtil._stream(this, transactionId, + /*retryWithCursor*/ false); + } + /** + * Internal method for serializing a query to its proto + * representation with an optional transaction id. + * + * @private + * @internal + * @returns Serialized JSON for the query. + */ + toProto(transactionOrReadTime, explainOptions) { + var _a, _b, _c; + const queryProto = this._query.toProto(transactionOrReadTime); + const queryVector = Array.isArray(this._options.queryVector) + ? new field_value_1.VectorValue(this._options.queryVector) + : this._options.queryVector; + queryProto.structuredQuery.findNearest = { + limit: { value: this._options.limit }, + distanceMeasure: this._options.distanceMeasure, + vectorField: { + fieldPath: path_1.FieldPath.fromArgument(this._options.vectorField) + .formattedName, + }, + queryVector: queryVector._toProto(this._query._serializer), + distanceResultField: ((_a = this._options) === null || _a === void 0 ? void 0 : _a.distanceResultField) + ? path_1.FieldPath.fromArgument(this._options.distanceResultField) + .formattedName + : undefined, + distanceThreshold: ((_b = this._options) === null || _b === void 0 ? void 0 : _b.distanceThreshold) + ? { value: (_c = this._options) === null || _c === void 0 ? void 0 : _c.distanceThreshold } + : undefined, + }; + if (explainOptions) { + queryProto.explainOptions = explainOptions; + } + return queryProto; + } + /** + * Construct the resulting vector snapshot for this query with given documents. + * + * @private + * @internal + */ + _createSnapshot(readTime, size, docs, changes) { + return new vector_query_snapshot_1.VectorQuerySnapshot(this, readTime, size, docs, changes); + } + /** + * Construct a new vector query whose result will start after To support stream(). + * This now throws an exception because cursors are not supported from the backend for vector queries yet. + * + * @private + * @internal + * @returns Serialized JSON for the query. + */ + startAfter( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + ...fieldValuesOrDocumentSnapshot) { + throw new Error('Unimplemented: Vector query does not support cursors yet.'); + } + /** + * Compares this object with the given object for equality. + * + * This object is considered "equal" to the other object if and only if + * `other` performs the same vector distance search as this `VectorQuery` and + * the underlying Query of `other` compares equal to that of this object + * using `Query.isEqual()`. + * + * @param other - The object to compare to this object for equality. + * @returns `true` if this object is "equal" to the given object, as + * defined above, or `false` otherwise. + */ + isEqual(other) { + if (this === other) { + return true; + } + if (!(other instanceof VectorQuery)) { + return false; + } + if (!this.query.isEqual(other.query)) { + return false; + } + return (this._rawVectorField === other._rawVectorField && + (0, util_1.isPrimitiveArrayEqual)(this._rawQueryVector, other._rawQueryVector) && + this._options.limit === other._options.limit && + this._options.distanceMeasure === other._options.distanceMeasure && + this._options.distanceThreshold === other._options.distanceThreshold && + this._rawDistanceResultField === other._rawDistanceResultField); + } +} +exports.VectorQuery = VectorQuery; +//# sourceMappingURL=vector-query.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/serializer.d.ts b/node_modules/@google-cloud/firestore/build/src/serializer.d.ts new file mode 100644 index 0000000..ff48a2f --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/serializer.d.ts @@ -0,0 +1,117 @@ +/*! + * Copyright 2019 Google Inc. 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. + */ +import { DocumentData } from '@google-cloud/firestore'; +import * as proto from '../protos/firestore_v1_proto_api'; +import { Firestore } from './index'; +import { FieldPath } from './path'; +import { ApiMapValue, ValidationOptions } from './types'; +import api = proto.google.firestore.v1; +/** + * An interface for Firestore types that can be serialized to Protobuf. + * + * @private + * @internal + */ +export interface Serializable { + toProto(): api.IValue; +} +/** + * Serializer that is used to convert between JavaScript types and their + * Firestore Protobuf representation. + * + * @private + * @internal + */ +export declare class Serializer { + private allowUndefined; + private createReference; + private createInteger; + constructor(firestore: Firestore); + /** + * Encodes a JavaScript object into the Firestore 'Fields' representation. + * + * @private + * @internal + * @param obj The object to encode. + * @returns The Firestore 'Fields' representation + */ + encodeFields(obj: DocumentData): ApiMapValue; + /** + * Encodes a JavaScript value into the Firestore 'Value' representation. + * + * @private + * @internal + * @param val The object to encode + * @returns The Firestore Proto or null if we are deleting a field. + */ + encodeValue(val: unknown): api.IValue | null; + /** + * @private + */ + encodeVector(rawVector: number[]): api.IValue; + /** + * Decodes a single Firestore 'Value' Protobuf. + * + * @private + * @internal + * @param proto A Firestore 'Value' Protobuf. + * @returns The converted JS type. + */ + decodeValue(proto: api.IValue): unknown; + /** + * Decodes a google.protobuf.Value + * + * @private + * @internal + * @param proto A Google Protobuf 'Value'. + * @returns The converted JS type. + */ + decodeGoogleProtobufValue(proto: proto.google.protobuf.IValue): unknown; + /** + * Decodes a google.protobuf.ListValue + * + * @private + * @internal + * @param proto A Google Protobuf 'ListValue'. + * @returns The converted JS type. + */ + decodeGoogleProtobufList(proto: proto.google.protobuf.IListValue | null | undefined): unknown[]; + /** + * Decodes a google.protobuf.Struct + * + * @private + * @internal + * @param proto A Google Protobuf 'Struct'. + * @returns The converted JS type. + */ + decodeGoogleProtobufStruct(proto: proto.google.protobuf.IStruct | null | undefined): Record; +} +/** + * Validates a JavaScript value for usage as a Firestore value. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value JavaScript value to validate. + * @param desc A description of the expected type. + * @param path The field path to validate. + * @param options Validation options + * @param level The current depth of the traversal. This is used to decide + * whether undefined values or deletes are allowed. + * @param inArray Whether we are inside an array. + * @throws when the object is invalid. + */ +export declare function validateUserInput(arg: string | number, value: unknown, desc: string, options: ValidationOptions, path?: FieldPath, level?: number, inArray?: boolean): void; diff --git a/node_modules/@google-cloud/firestore/build/src/serializer.js b/node_modules/@google-cloud/firestore/build/src/serializer.js new file mode 100644 index 0000000..d35bf7f --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/serializer.js @@ -0,0 +1,456 @@ +"use strict"; +/*! + * Copyright 2019 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Serializer = void 0; +exports.validateUserInput = validateUserInput; +const field_value_1 = require("./field-value"); +const convert_1 = require("./convert"); +const geo_point_1 = require("./geo-point"); +const index_1 = require("./index"); +const path_1 = require("./path"); +const timestamp_1 = require("./timestamp"); +const util_1 = require("./util"); +const validate_1 = require("./validate"); +const map_type_1 = require("./map-type"); +/** + * The maximum depth of a Firestore object. + * + * @private + * @internal + */ +const MAX_DEPTH = 20; +/** + * Serializer that is used to convert between JavaScript types and their + * Firestore Protobuf representation. + * + * @private + * @internal + */ +class Serializer { + constructor(firestore) { + // Instead of storing the `firestore` object, we store just a reference to + // its `.doc()` method. This avoid a circular reference, which breaks + // JSON.stringify(). + this.createReference = path => firestore.doc(path); + this.createInteger = n => firestore._settings.useBigInt ? BigInt(n) : Number(n); + this.allowUndefined = !!firestore._settings.ignoreUndefinedProperties; + } + /** + * Encodes a JavaScript object into the Firestore 'Fields' representation. + * + * @private + * @internal + * @param obj The object to encode. + * @returns The Firestore 'Fields' representation + */ + encodeFields(obj) { + const fields = {}; + for (const prop of Object.keys(obj)) { + const val = this.encodeValue(obj[prop]); + if (val) { + fields[prop] = val; + } + } + return fields; + } + /** + * Encodes a JavaScript value into the Firestore 'Value' representation. + * + * @private + * @internal + * @param val The object to encode + * @returns The Firestore Proto or null if we are deleting a field. + */ + encodeValue(val) { + if (val instanceof field_value_1.FieldTransform) { + return null; + } + if (typeof val === 'string') { + return { + stringValue: val, + }; + } + if (typeof val === 'boolean') { + return { + booleanValue: val, + }; + } + if (typeof val === 'number') { + const isNegativeZero = val === 0 && 1 / val === 1 / -0; + if (Number.isSafeInteger(val) && !isNegativeZero) { + return { + integerValue: val, + }; + } + else { + return { + doubleValue: val, + }; + } + } + if (typeof val === 'bigint') { + return { + integerValue: val.toString(), + }; + } + if (val instanceof Date) { + const timestamp = timestamp_1.Timestamp.fromDate(val); + return { + timestampValue: { + seconds: timestamp.seconds, + nanos: timestamp.nanoseconds, + }, + }; + } + if (isMomentJsType(val)) { + const timestamp = timestamp_1.Timestamp.fromDate(val.toDate()); + return { + timestampValue: { + seconds: timestamp.seconds, + nanos: timestamp.nanoseconds, + }, + }; + } + if (val === null) { + return { + nullValue: 'NULL_VALUE', + }; + } + if (val instanceof Buffer || val instanceof Uint8Array) { + return { + bytesValue: val, + }; + } + if (val instanceof field_value_1.VectorValue) { + return val._toProto(this); + } + if ((0, util_1.isObject)(val)) { + const toProto = val['toProto']; + if (typeof toProto === 'function') { + return toProto.bind(val)(); + } + } + if (Array.isArray(val)) { + const array = { + arrayValue: {}, + }; + if (val.length > 0) { + array.arrayValue.values = []; + for (let i = 0; i < val.length; ++i) { + const enc = this.encodeValue(val[i]); + if (enc) { + array.arrayValue.values.push(enc); + } + } + } + return array; + } + if (typeof val === 'object' && (0, util_1.isPlainObject)(val)) { + const map = { + mapValue: {}, + }; + // If we encounter an empty object, we always need to send it to make sure + // the server creates a map entry. + if (!(0, util_1.isEmpty)(val)) { + map.mapValue.fields = this.encodeFields(val); + if ((0, util_1.isEmpty)(map.mapValue.fields)) { + return null; + } + } + return map; + } + if (val === undefined && this.allowUndefined) { + return null; + } + throw new Error(`Cannot encode value: ${val}`); + } + /** + * @private + */ + encodeVector(rawVector) { + // A Firestore Vector is a map with reserved key/value pairs. + return { + mapValue: { + fields: { + [map_type_1.RESERVED_MAP_KEY]: { + stringValue: map_type_1.RESERVED_MAP_KEY_VECTOR_VALUE, + }, + [map_type_1.VECTOR_MAP_VECTORS_KEY]: { + arrayValue: { + values: rawVector.map(value => { + return { + doubleValue: value, + }; + }), + }, + }, + }, + }, + }; + } + /** + * Decodes a single Firestore 'Value' Protobuf. + * + * @private + * @internal + * @param proto A Firestore 'Value' Protobuf. + * @returns The converted JS type. + */ + decodeValue(proto) { + const valueType = (0, convert_1.detectValueType)(proto); + switch (valueType) { + case 'stringValue': { + return proto.stringValue; + } + case 'booleanValue': { + return proto.booleanValue; + } + case 'integerValue': { + return this.createInteger(proto.integerValue); + } + case 'doubleValue': { + return proto.doubleValue; + } + case 'timestampValue': { + return timestamp_1.Timestamp.fromProto(proto.timestampValue); + } + case 'referenceValue': { + const resourcePath = path_1.QualifiedResourcePath.fromSlashSeparatedString(proto.referenceValue); + return this.createReference(resourcePath.relativeName); + } + case 'arrayValue': { + const array = []; + if (Array.isArray(proto.arrayValue.values)) { + for (const value of proto.arrayValue.values) { + array.push(this.decodeValue(value)); + } + } + return array; + } + case 'nullValue': { + return null; + } + case 'mapValue': { + const fields = proto.mapValue.fields; + if (fields) { + const obj = {}; + for (const prop of Object.keys(fields)) { + obj[prop] = this.decodeValue(fields[prop]); + } + return obj; + } + else { + return {}; + } + } + case 'vectorValue': { + const fields = proto.mapValue.fields; + return field_value_1.VectorValue._fromProto(fields[map_type_1.VECTOR_MAP_VECTORS_KEY]); + } + case 'geoPointValue': { + return geo_point_1.GeoPoint.fromProto(proto.geoPointValue); + } + case 'bytesValue': { + return proto.bytesValue; + } + default: { + throw new Error('Cannot decode type from Firestore Value: ' + JSON.stringify(proto)); + } + } + } + /** + * Decodes a google.protobuf.Value + * + * @private + * @internal + * @param proto A Google Protobuf 'Value'. + * @returns The converted JS type. + */ + decodeGoogleProtobufValue(proto) { + switch ((0, convert_1.detectGoogleProtobufValueType)(proto)) { + case 'nullValue': { + return null; + } + case 'numberValue': { + return proto.numberValue; + } + case 'stringValue': { + return proto.stringValue; + } + case 'boolValue': { + return proto.boolValue; + } + case 'listValue': { + return this.decodeGoogleProtobufList(proto.listValue); + } + case 'structValue': { + return this.decodeGoogleProtobufStruct(proto.structValue); + } + default: { + throw new Error('Cannot decode type from google.protobuf.Value: ' + + JSON.stringify(proto)); + } + } + } + /** + * Decodes a google.protobuf.ListValue + * + * @private + * @internal + * @param proto A Google Protobuf 'ListValue'. + * @returns The converted JS type. + */ + decodeGoogleProtobufList(proto) { + const result = []; + if (proto && proto.values && Array.isArray(proto.values)) { + for (const value of proto.values) { + result.push(this.decodeGoogleProtobufValue(value)); + } + } + return result; + } + /** + * Decodes a google.protobuf.Struct + * + * @private + * @internal + * @param proto A Google Protobuf 'Struct'. + * @returns The converted JS type. + */ + decodeGoogleProtobufStruct(proto) { + const result = {}; + if (proto && proto.fields) { + for (const prop of Object.keys(proto.fields)) { + result[prop] = this.decodeGoogleProtobufValue(proto.fields[prop]); + } + } + return result; + } +} +exports.Serializer = Serializer; +/** + * Validates a JavaScript value for usage as a Firestore value. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value JavaScript value to validate. + * @param desc A description of the expected type. + * @param path The field path to validate. + * @param options Validation options + * @param level The current depth of the traversal. This is used to decide + * whether undefined values or deletes are allowed. + * @param inArray Whether we are inside an array. + * @throws when the object is invalid. + */ +function validateUserInput(arg, value, desc, options, path, level, inArray) { + if (path && path.size - 1 > MAX_DEPTH) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, desc)} Input object is deeper than ${MAX_DEPTH} levels or contains a cycle.`); + } + level = level || 0; + inArray = inArray || false; + const fieldPathMessage = path ? ` (found in field "${path}")` : ''; + if (Array.isArray(value)) { + for (let i = 0; i < value.length; ++i) { + validateUserInput(arg, value[i], desc, options, path ? path.append(String(i)) : new path_1.FieldPath(String(i)), level + 1, + /* inArray= */ true); + } + } + else if ((0, util_1.isPlainObject)(value)) { + for (const prop of Object.keys(value)) { + validateUserInput(arg, value[prop], desc, options, path ? path.append(new path_1.FieldPath(prop)) : new path_1.FieldPath(prop), level + 1, inArray); + } + } + else if (value === undefined) { + if (options.allowUndefined && level === 0) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, desc)} "undefined" values are only ignored inside of objects.`); + } + else if (!options.allowUndefined) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, desc)} Cannot use "undefined" as a Firestore value${fieldPathMessage}. ` + + 'If you want to ignore undefined values, enable `ignoreUndefinedProperties`.'); + } + } + else if (value instanceof field_value_1.VectorValue) { + // OK + } + else if (value instanceof field_value_1.DeleteTransform) { + if (inArray) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, desc)} ${value.methodName}() cannot be used inside of an array${fieldPathMessage}.`); + } + else if (options.allowDeletes === 'none') { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, desc)} ${value.methodName}() must appear at the top-level and can only be used in update() ` + + `or set() with {merge:true}${fieldPathMessage}.`); + } + else if (options.allowDeletes === 'root') { + if (level === 0) { + // Ok (update() with UpdateData). + } + else if (level === 1 && (path === null || path === void 0 ? void 0 : path.size) === 1) { + // Ok (update with varargs). + } + else { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, desc)} ${value.methodName}() must appear at the top-level and can only be used in update() ` + + `or set() with {merge:true}${fieldPathMessage}.`); + } + } + } + else if (value instanceof field_value_1.FieldTransform) { + if (inArray) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, desc)} ${value.methodName}() cannot be used inside of an array${fieldPathMessage}.`); + } + else if (!options.allowTransforms) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, desc)} ${value.methodName}() can only be used in set(), create() or update()${fieldPathMessage}.`); + } + } + else if (value instanceof path_1.FieldPath) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, desc)} Cannot use object of type "FieldPath" as a Firestore value${fieldPathMessage}.`); + } + else if (value instanceof index_1.DocumentReference) { + // Ok. + } + else if (value instanceof geo_point_1.GeoPoint) { + // Ok. + } + else if (value instanceof timestamp_1.Timestamp || value instanceof Date) { + // Ok. + } + else if (isMomentJsType(value)) { + // Ok. + } + else if (value instanceof Buffer || value instanceof Uint8Array) { + // Ok. + } + else if (value === null) { + // Ok. + } + else if (typeof value === 'object') { + throw new Error((0, validate_1.customObjectMessage)(arg, value, path)); + } +} +/** + * Returns true if value is a MomentJs date object. + * @private + * @internal + */ +function isMomentJsType(value) { + return (typeof value === 'object' && + value !== null && + value.constructor && + value.constructor.name === 'Moment' && + typeof value.toDate === 'function'); +} +//# sourceMappingURL=serializer.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/status-code.d.ts b/node_modules/@google-cloud/firestore/build/src/status-code.d.ts new file mode 100644 index 0000000..059ced9 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/status-code.d.ts @@ -0,0 +1,38 @@ +/** + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Internal copy of GRPC status code. Copied to prevent loading of google-gax + * at SDK startup. + */ +export declare const enum StatusCode { + OK = 0, + CANCELLED = 1, + UNKNOWN = 2, + INVALID_ARGUMENT = 3, + DEADLINE_EXCEEDED = 4, + NOT_FOUND = 5, + ALREADY_EXISTS = 6, + PERMISSION_DENIED = 7, + RESOURCE_EXHAUSTED = 8, + FAILED_PRECONDITION = 9, + ABORTED = 10, + OUT_OF_RANGE = 11, + UNIMPLEMENTED = 12, + INTERNAL = 13, + UNAVAILABLE = 14, + DATA_LOSS = 15, + UNAUTHENTICATED = 16 +} diff --git a/node_modules/@google-cloud/firestore/build/src/status-code.js b/node_modules/@google-cloud/firestore/build/src/status-code.js new file mode 100644 index 0000000..7dc9e6b --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/status-code.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=status-code.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/telemetry/disabled-trace-util.d.ts b/node_modules/@google-cloud/firestore/build/src/telemetry/disabled-trace-util.d.ts new file mode 100644 index 0000000..4c74366 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/telemetry/disabled-trace-util.d.ts @@ -0,0 +1,27 @@ +/** + * Copyright 2024 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. + */ +import { Attributes, TraceUtil } from './trace-util'; +import { Span } from './span'; +/** + * @private + * @internal + */ +export declare class DisabledTraceUtil implements TraceUtil { + startSpan(name: string): Span; + startActiveSpan unknown>(name: string, fn: F, attributes?: Attributes): ReturnType; + currentSpan(): Span; + recordProjectId(projectId: string): void; +} diff --git a/node_modules/@google-cloud/firestore/build/src/telemetry/disabled-trace-util.js b/node_modules/@google-cloud/firestore/build/src/telemetry/disabled-trace-util.js new file mode 100644 index 0000000..d11917f --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/telemetry/disabled-trace-util.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DisabledTraceUtil = void 0; +const span_1 = require("./span"); +/** + * @private + * @internal + */ +class DisabledTraceUtil { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + startSpan(name) { + return new span_1.Span(); + } + startActiveSpan( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + name, fn, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + attributes) { + const emptySpan = new span_1.Span(); + return fn(emptySpan); + } + currentSpan() { + return new span_1.Span(); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + recordProjectId(projectId) { } +} +exports.DisabledTraceUtil = DisabledTraceUtil; +//# sourceMappingURL=disabled-trace-util.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/telemetry/enabled-trace-util.d.ts b/node_modules/@google-cloud/firestore/build/src/telemetry/enabled-trace-util.d.ts new file mode 100644 index 0000000..88246b1 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/telemetry/enabled-trace-util.d.ts @@ -0,0 +1,36 @@ +/** + * Copyright 2024 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. + */ +import { Settings } from '@google-cloud/firestore'; +import { Span as OpenTelemetrySpan, TracerProvider } from '@opentelemetry/api'; +import { Span } from './span'; +import { Attributes, TraceUtil } from './trace-util'; +/** + * @private + * @internal + */ +export declare class EnabledTraceUtil implements TraceUtil { + private tracer; + private settingsAttributes; + tracerProvider: TracerProvider; + constructor(settings: Settings); + recordProjectId(projectId: string): void; + private millisToSecondString; + private endSpan; + startActiveSpan unknown>(name: string, fn: F, attributes?: Attributes): ReturnType; + startSpan(name: string): Span; + currentSpan(): Span; + addCommonAttributes(otelSpan: OpenTelemetrySpan): void; +} diff --git a/node_modules/@google-cloud/firestore/build/src/telemetry/enabled-trace-util.js b/node_modules/@google-cloud/firestore/build/src/telemetry/enabled-trace-util.js new file mode 100644 index 0000000..2f43c98 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/telemetry/enabled-trace-util.js @@ -0,0 +1,148 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EnabledTraceUtil = void 0; +const api_1 = require("@opentelemetry/api"); +const span_1 = require("./span"); +const trace_util_1 = require("./trace-util"); +const firestore_client_config_json_1 = require("../v1/firestore_client_config.json"); +const v1_1 = require("../v1"); +const path_1 = require("../path"); +const index_1 = require("../index"); +const serviceConfig = firestore_client_config_json_1.interfaces['google.firestore.v1.Firestore']; +/** + * @private + * @internal + */ +class EnabledTraceUtil { + constructor(settings) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r; + let provider = (_a = settings.openTelemetry) === null || _a === void 0 ? void 0 : _a.tracerProvider; + // If a TracerProvider has not been given to us, we try to use the global one. + if (!provider) { + const { trace } = require('@opentelemetry/api'); + provider = trace.getTracerProvider(); + } + // At this point provider is guaranteed to be defined because + // `trace.getTracerProvider()` does not return null or undefined. + this.tracerProvider = provider; + const libVersion = require('../../../package.json').version; + const libName = require('../../../package.json').name; + try { + this.tracer = this.tracerProvider.getTracer(libName, libVersion); + } + catch (e) { + throw new Error("The object provided for 'tracerProvider' does not conform to the TracerProvider interface."); + } + this.settingsAttributes = {}; + this.settingsAttributes['otel.scope.name'] = libName; + this.settingsAttributes['otel.scope.version'] = libVersion; + if (settings.projectId) { + this.settingsAttributes[`${trace_util_1.ATTRIBUTE_SETTINGS_PREFIX}.project_id`] = + settings.projectId; + } + this.settingsAttributes[`${trace_util_1.ATTRIBUTE_SETTINGS_PREFIX}.database_id`] = + settings.databaseId || path_1.DEFAULT_DATABASE_ID; + const host = (_c = (_b = settings.servicePath) !== null && _b !== void 0 ? _b : settings.host) !== null && _c !== void 0 ? _c : 'firestore.googleapis.com'; + const port = (_d = settings.port) !== null && _d !== void 0 ? _d : v1_1.FirestoreClient.port; + this.settingsAttributes[`${trace_util_1.ATTRIBUTE_SETTINGS_PREFIX}.host`] = + `${host}:${port}`; + if (settings.preferRest !== undefined) { + this.settingsAttributes[`${trace_util_1.ATTRIBUTE_SETTINGS_PREFIX}.prefer_REST`] = + settings.preferRest; + } + this.settingsAttributes[`${trace_util_1.ATTRIBUTE_SETTINGS_PREFIX}.max_idle_channels`] = + (_e = settings.maxIdleChannels) !== null && _e !== void 0 ? _e : index_1.DEFAULT_MAX_IDLE_CHANNELS; + const defaultRetrySettings = serviceConfig.retry_params.default; + const customRetrySettings = (_j = (_h = (_g = (_f = settings.clientConfig) === null || _f === void 0 ? void 0 : _f.interfaces) === null || _g === void 0 ? void 0 : _g['google.firestore.v1.Firestore']) === null || _h === void 0 ? void 0 : _h['retry_params']) === null || _j === void 0 ? void 0 : _j['default']; + this.settingsAttributes[`${trace_util_1.ATTRIBUTE_SETTINGS_PREFIX}.initial_retry_delay`] = this.millisToSecondString((_k = customRetrySettings === null || customRetrySettings === void 0 ? void 0 : customRetrySettings.initial_retry_delay_millis) !== null && _k !== void 0 ? _k : defaultRetrySettings.initial_retry_delay_millis); + this.settingsAttributes[`${trace_util_1.ATTRIBUTE_SETTINGS_PREFIX}.initial_rpc_timeout`] = this.millisToSecondString((_l = customRetrySettings === null || customRetrySettings === void 0 ? void 0 : customRetrySettings.initial_rpc_timeout_millis) !== null && _l !== void 0 ? _l : defaultRetrySettings.initial_rpc_timeout_millis); + this.settingsAttributes[`${trace_util_1.ATTRIBUTE_SETTINGS_PREFIX}.total_timeout`] = + this.millisToSecondString((_m = customRetrySettings === null || customRetrySettings === void 0 ? void 0 : customRetrySettings.total_timeout_millis) !== null && _m !== void 0 ? _m : defaultRetrySettings.total_timeout_millis); + this.settingsAttributes[`${trace_util_1.ATTRIBUTE_SETTINGS_PREFIX}.max_retry_delay`] = + this.millisToSecondString((_o = customRetrySettings === null || customRetrySettings === void 0 ? void 0 : customRetrySettings.max_retry_delay_millis) !== null && _o !== void 0 ? _o : defaultRetrySettings.max_retry_delay_millis); + this.settingsAttributes[`${trace_util_1.ATTRIBUTE_SETTINGS_PREFIX}.max_rpc_timeout`] = + this.millisToSecondString((_p = customRetrySettings === null || customRetrySettings === void 0 ? void 0 : customRetrySettings.max_rpc_timeout_millis) !== null && _p !== void 0 ? _p : defaultRetrySettings.max_rpc_timeout_millis); + this.settingsAttributes[`${trace_util_1.ATTRIBUTE_SETTINGS_PREFIX}.retry_delay_multiplier`] = + (_q = customRetrySettings === null || customRetrySettings === void 0 ? void 0 : customRetrySettings.retry_delay_multiplier.toString()) !== null && _q !== void 0 ? _q : defaultRetrySettings.retry_delay_multiplier.toString(); + this.settingsAttributes[`${trace_util_1.ATTRIBUTE_SETTINGS_PREFIX}.rpc_timeout_multiplier`] = + (_r = customRetrySettings === null || customRetrySettings === void 0 ? void 0 : customRetrySettings.rpc_timeout_multiplier.toString()) !== null && _r !== void 0 ? _r : defaultRetrySettings.rpc_timeout_multiplier.toString(); + } + recordProjectId(projectId) { + this.settingsAttributes[`${trace_util_1.ATTRIBUTE_SETTINGS_PREFIX}.project_id`] = + projectId; + this.currentSpan().setAttributes(this.settingsAttributes); + } + millisToSecondString(millis) { + return `${millis / 1000}s`; + } + endSpan(otelSpan, error) { + otelSpan.setStatus({ + code: api_1.SpanStatusCode.ERROR, + message: error.message, + }); + otelSpan.recordException(error); + otelSpan.end(); + } + startActiveSpan(name, fn, attributes) { + return this.tracer.startActiveSpan(name, { + attributes: attributes, + }, (otelSpan) => { + this.addCommonAttributes(otelSpan); + // Note that if `fn` returns a `Promise`, we want the otelSpan to end + // after the `Promise` has resolved, NOT after the `fn` has returned. + // Therefore, we should not use a `finally` clause to end the otelSpan. + try { + let result = fn(new span_1.Span(otelSpan)); + if (result instanceof Promise) { + result = result + .then(value => { + otelSpan.end(); + return value; + }) + .catch(error => { + this.endSpan(otelSpan, error); + // Returns a Promise.reject the same as the underlying function. + return Promise.reject(error); + }); + } + else { + otelSpan.end(); + } + return result; + } + catch (error) { + this.endSpan(otelSpan, error); + // Re-throw the exception to maintain normal error handling. + throw error; + } + }); + } + startSpan(name) { + const otelSpan = this.tracer.startSpan(name, undefined, api_1.context.active()); + this.addCommonAttributes(otelSpan); + return new span_1.Span(otelSpan); + } + currentSpan() { + return new span_1.Span(api_1.trace.getActiveSpan()); + } + addCommonAttributes(otelSpan) { + otelSpan.setAttributes(this.settingsAttributes); + } +} +exports.EnabledTraceUtil = EnabledTraceUtil; +//# sourceMappingURL=enabled-trace-util.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/telemetry/span.d.ts b/node_modules/@google-cloud/firestore/build/src/telemetry/span.d.ts new file mode 100644 index 0000000..7654370 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/telemetry/span.d.ts @@ -0,0 +1,28 @@ +/** + * Copyright 2024 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. + */ +import { Span as OpenTelemetrySpan } from '@opentelemetry/api'; +import { Attributes } from './trace-util'; +/** + * @private + * @internal + */ +export declare class Span { + private span?; + constructor(span?: OpenTelemetrySpan | undefined); + end(): void; + addEvent(name: string, attributes?: Attributes): this; + setAttributes(attributes: Attributes): this; +} diff --git a/node_modules/@google-cloud/firestore/build/src/telemetry/span.js b/node_modules/@google-cloud/firestore/build/src/telemetry/span.js new file mode 100644 index 0000000..f461044 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/telemetry/span.js @@ -0,0 +1,43 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Span = void 0; +/** + * @private + * @internal + */ +class Span { + constructor(span) { + this.span = span; + } + end() { + var _a; + (_a = this.span) === null || _a === void 0 ? void 0 : _a.end(); + } + addEvent(name, attributes) { + var _a; + this.span = (_a = this.span) === null || _a === void 0 ? void 0 : _a.addEvent(name, attributes); + return this; + } + setAttributes(attributes) { + var _a; + this.span = (_a = this.span) === null || _a === void 0 ? void 0 : _a.setAttributes(attributes); + return this; + } +} +exports.Span = Span; +//# sourceMappingURL=span.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/telemetry/trace-util.d.ts b/node_modules/@google-cloud/firestore/build/src/telemetry/trace-util.d.ts new file mode 100644 index 0000000..28a469b --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/telemetry/trace-util.d.ts @@ -0,0 +1,74 @@ +/** + * Copyright 2024 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. + */ +import { Span } from './span'; +/** + * @private + * @internal + */ +export interface Attributes { + [attributeKey: string]: AttributeValue | undefined; +} +/** + * @private + * @internal + */ +export declare type AttributeValue = string | number | boolean | Array | Array | Array; +/** + * Span names for instrumented operations. + */ +export declare const SERVICE = "google.firestore.v1.Firestore/"; +export declare const SPAN_NAME_BATCH_GET_DOCUMENTS = "BatchGetDocuments"; +export declare const SPAN_NAME_RUN_QUERY = "RunQuery"; +export declare const SPAN_NAME_RUN_AGGREGATION_QUERY = "RunAggregationQuery"; +export declare const SPAN_NAME_DOC_REF_CREATE = "DocumentReference.Create"; +export declare const SPAN_NAME_DOC_REF_SET = "DocumentReference.Set"; +export declare const SPAN_NAME_DOC_REF_UPDATE = "DocumentReference.Update"; +export declare const SPAN_NAME_DOC_REF_DELETE = "DocumentReference.Delete"; +export declare const SPAN_NAME_DOC_REF_GET = "DocumentReference.Get"; +export declare const SPAN_NAME_DOC_REF_LIST_COLLECTIONS = "DocumentReference.ListCollections"; +export declare const SPAN_NAME_COL_REF_ADD = "CollectionReference.Add"; +export declare const SPAN_NAME_COL_REF_LIST_DOCUMENTS = "CollectionReference.ListDocuments"; +export declare const SPAN_NAME_QUERY_GET = "Query.Get"; +export declare const SPAN_NAME_AGGREGATION_QUERY_GET = "AggregationQuery.Get"; +export declare const SPAN_NAME_TRANSACTION_RUN = "Transaction.Run"; +export declare const SPAN_NAME_TRANSACTION_GET_QUERY = "Transaction.Get.Query"; +export declare const SPAN_NAME_TRANSACTION_GET_AGGREGATION_QUERY = "Transaction.Get.AggregationQuery"; +export declare const SPAN_NAME_TRANSACTION_GET_DOCUMENT = "Transaction.Get.Document"; +export declare const SPAN_NAME_TRANSACTION_GET_DOCUMENTS = "Transaction.Get.Documents"; +export declare const SPAN_NAME_TRANSACTION_ROLLBACK = "Transaction.Rollback"; +export declare const SPAN_NAME_TRANSACTION_COMMIT = "Transaction.Commit"; +export declare const SPAN_NAME_BATCH_COMMIT = "Batch.Commit"; +export declare const SPAN_NAME_PARTITION_QUERY = "PartitionQuery"; +export declare const SPAN_NAME_BULK_WRITER_COMMIT = "BulkWriter.Commit"; +export declare const ATTRIBUTE_SERVICE_PREFIX = "gcp.firestore"; +export declare const ATTRIBUTE_SETTINGS_PREFIX = "gcp.firestore.settings"; +export declare const ATTRIBUTE_KEY_DOC_COUNT = "doc_count"; +export declare const ATTRIBUTE_KEY_IS_TRANSACTIONAL = "transactional"; +export declare const ATTRIBUTE_KEY_NUM_RESPONSES = "response_count"; +export declare const ATTRIBUTE_KEY_IS_RETRY_WITH_CURSOR = "retry_query_with_cursor"; +export declare const ATTRIBUTE_KEY_TRANSACTION_TYPE = "transaction_type"; +export declare const ATTRIBUTE_KEY_ATTEMPTS_ALLOWED = "attempts_allowed"; +export declare const ATTRIBUTE_KEY_ATTEMPTS_REMAINING = "attempts_remaining"; +/** + * @private + * @internal + */ +export interface TraceUtil { + startActiveSpan unknown>(name: string, fn: F, attributes?: Attributes): ReturnType; + startSpan(name: string): Span; + currentSpan(): Span; + recordProjectId(projectId: string): void; +} diff --git a/node_modules/@google-cloud/firestore/build/src/telemetry/trace-util.js b/node_modules/@google-cloud/firestore/build/src/telemetry/trace-util.js new file mode 100644 index 0000000..c1a07f6 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/telemetry/trace-util.js @@ -0,0 +1,55 @@ +"use strict"; +/** + * Copyright 2024 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ATTRIBUTE_KEY_ATTEMPTS_REMAINING = exports.ATTRIBUTE_KEY_ATTEMPTS_ALLOWED = exports.ATTRIBUTE_KEY_TRANSACTION_TYPE = exports.ATTRIBUTE_KEY_IS_RETRY_WITH_CURSOR = exports.ATTRIBUTE_KEY_NUM_RESPONSES = exports.ATTRIBUTE_KEY_IS_TRANSACTIONAL = exports.ATTRIBUTE_KEY_DOC_COUNT = exports.ATTRIBUTE_SETTINGS_PREFIX = exports.ATTRIBUTE_SERVICE_PREFIX = exports.SPAN_NAME_BULK_WRITER_COMMIT = exports.SPAN_NAME_PARTITION_QUERY = exports.SPAN_NAME_BATCH_COMMIT = exports.SPAN_NAME_TRANSACTION_COMMIT = exports.SPAN_NAME_TRANSACTION_ROLLBACK = exports.SPAN_NAME_TRANSACTION_GET_DOCUMENTS = exports.SPAN_NAME_TRANSACTION_GET_DOCUMENT = exports.SPAN_NAME_TRANSACTION_GET_AGGREGATION_QUERY = exports.SPAN_NAME_TRANSACTION_GET_QUERY = exports.SPAN_NAME_TRANSACTION_RUN = exports.SPAN_NAME_AGGREGATION_QUERY_GET = exports.SPAN_NAME_QUERY_GET = exports.SPAN_NAME_COL_REF_LIST_DOCUMENTS = exports.SPAN_NAME_COL_REF_ADD = exports.SPAN_NAME_DOC_REF_LIST_COLLECTIONS = exports.SPAN_NAME_DOC_REF_GET = exports.SPAN_NAME_DOC_REF_DELETE = exports.SPAN_NAME_DOC_REF_UPDATE = exports.SPAN_NAME_DOC_REF_SET = exports.SPAN_NAME_DOC_REF_CREATE = exports.SPAN_NAME_RUN_AGGREGATION_QUERY = exports.SPAN_NAME_RUN_QUERY = exports.SPAN_NAME_BATCH_GET_DOCUMENTS = exports.SERVICE = void 0; +/** + * Span names for instrumented operations. + */ +exports.SERVICE = 'google.firestore.v1.Firestore/'; +exports.SPAN_NAME_BATCH_GET_DOCUMENTS = 'BatchGetDocuments'; +exports.SPAN_NAME_RUN_QUERY = 'RunQuery'; +exports.SPAN_NAME_RUN_AGGREGATION_QUERY = 'RunAggregationQuery'; +exports.SPAN_NAME_DOC_REF_CREATE = 'DocumentReference.Create'; +exports.SPAN_NAME_DOC_REF_SET = 'DocumentReference.Set'; +exports.SPAN_NAME_DOC_REF_UPDATE = 'DocumentReference.Update'; +exports.SPAN_NAME_DOC_REF_DELETE = 'DocumentReference.Delete'; +exports.SPAN_NAME_DOC_REF_GET = 'DocumentReference.Get'; +exports.SPAN_NAME_DOC_REF_LIST_COLLECTIONS = 'DocumentReference.ListCollections'; +exports.SPAN_NAME_COL_REF_ADD = 'CollectionReference.Add'; +exports.SPAN_NAME_COL_REF_LIST_DOCUMENTS = 'CollectionReference.ListDocuments'; +exports.SPAN_NAME_QUERY_GET = 'Query.Get'; +exports.SPAN_NAME_AGGREGATION_QUERY_GET = 'AggregationQuery.Get'; +exports.SPAN_NAME_TRANSACTION_RUN = 'Transaction.Run'; +exports.SPAN_NAME_TRANSACTION_GET_QUERY = 'Transaction.Get.Query'; +exports.SPAN_NAME_TRANSACTION_GET_AGGREGATION_QUERY = 'Transaction.Get.AggregationQuery'; +exports.SPAN_NAME_TRANSACTION_GET_DOCUMENT = 'Transaction.Get.Document'; +exports.SPAN_NAME_TRANSACTION_GET_DOCUMENTS = 'Transaction.Get.Documents'; +exports.SPAN_NAME_TRANSACTION_ROLLBACK = 'Transaction.Rollback'; +exports.SPAN_NAME_TRANSACTION_COMMIT = 'Transaction.Commit'; +exports.SPAN_NAME_BATCH_COMMIT = 'Batch.Commit'; +exports.SPAN_NAME_PARTITION_QUERY = 'PartitionQuery'; +exports.SPAN_NAME_BULK_WRITER_COMMIT = 'BulkWriter.Commit'; +exports.ATTRIBUTE_SERVICE_PREFIX = 'gcp.firestore'; +exports.ATTRIBUTE_SETTINGS_PREFIX = `${exports.ATTRIBUTE_SERVICE_PREFIX}.settings`; +exports.ATTRIBUTE_KEY_DOC_COUNT = 'doc_count'; +exports.ATTRIBUTE_KEY_IS_TRANSACTIONAL = 'transactional'; +exports.ATTRIBUTE_KEY_NUM_RESPONSES = 'response_count'; +exports.ATTRIBUTE_KEY_IS_RETRY_WITH_CURSOR = 'retry_query_with_cursor'; +exports.ATTRIBUTE_KEY_TRANSACTION_TYPE = 'transaction_type'; +exports.ATTRIBUTE_KEY_ATTEMPTS_ALLOWED = 'attempts_allowed'; +exports.ATTRIBUTE_KEY_ATTEMPTS_REMAINING = 'attempts_remaining'; +//# sourceMappingURL=trace-util.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/timestamp.d.ts b/node_modules/@google-cloud/firestore/build/src/timestamp.d.ts new file mode 100644 index 0000000..99c8510 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/timestamp.d.ts @@ -0,0 +1,206 @@ +/*! + * Copyright 2018 Google Inc. 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. + */ +import * as firestore from '@google-cloud/firestore'; +import { google } from '../protos/firestore_v1_proto_api'; +import api = google.firestore.v1; +/** + * A Timestamp represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian + * Calendar which extends the Gregorian calendar backwards to year one. It is + * encoded assuming all minutes are 60 seconds long, i.e. leap seconds are + * "smeared" so that no leap second table is needed for interpretation. Range is + * from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. + * + * @see https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto + */ +export declare class Timestamp implements firestore.Timestamp { + private readonly _seconds; + private readonly _nanoseconds; + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({ updateTime:Firestore.Timestamp.now() }); + * + * ``` + * @return {Timestamp} A new `Timestamp` representing the current date. + */ + static now(): Timestamp; + /** + * Creates a new timestamp from the given date. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * let date = Date.parse('01 Jan 2000 00:00:00 GMT'); + * documentRef.set({ startTime:Firestore.Timestamp.fromDate(date) }); + * + * ``` + * @param {Date} date The date to initialize the `Timestamp` from. + * @return {Timestamp} A new `Timestamp` representing the same point in time + * as the given date. + */ + static fromDate(date: Date): Timestamp; + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({ startTime:Firestore.Timestamp.fromMillis(42) }); + * + * ``` + * @param {number} milliseconds Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @return {Timestamp} A new `Timestamp` representing the same point in time + * as the given number of milliseconds. + */ + static fromMillis(milliseconds: number): Timestamp; + /** + * Generates a `Timestamp` object from a Timestamp proto. + * + * @private + * @internal + * @param {Object} timestamp The `Timestamp` Protobuf object. + */ + static fromProto(timestamp: google.protobuf.ITimestamp): Timestamp; + /** + * Creates a new timestamp. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({ startTime:new Firestore.Timestamp(42, 0) }); + * + * ``` + * @param {number} seconds The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param {number} nanoseconds The non-negative fractions of a second at + * nanosecond resolution. Negative second values with fractions must still + * have non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor(seconds: number, nanoseconds: number); + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(snap => { + * let updated = snap.updateTime; + * console.log(`Updated at ${updated.seconds}s ${updated.nanoseconds}ns`); + * }); + * + * ``` + * @type {number} + */ + get seconds(): number; + /** + * The non-negative fractions of a second at nanosecond resolution. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(snap => { + * let updated = snap.updateTime; + * console.log(`Updated at ${updated.seconds}s ${updated.nanoseconds}ns`); + * }); + * + * ``` + * @type {number} + */ + get nanoseconds(): number; + /** + * Returns a new `Date` corresponding to this timestamp. This may lose + * precision. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(snap => { + * console.log(`Document updated at: ${snap.updateTime.toDate()}`); + * }); + * + * ``` + * @return {Date} JavaScript `Date` object representing the same point in time + * as this `Timestamp`, with millisecond precision. + */ + toDate(): Date; + /** + * Returns the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(snap => { + * let startTime = snap.get('startTime'); + * let endTime = snap.get('endTime'); + * console.log(`Duration: ${endTime - startTime}`); + * }); + * + * ``` + * @return {number} The point in time corresponding to this timestamp, + * represented as the number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + */ + toMillis(): number; + /** + * Returns 'true' if this `Timestamp` is equal to the provided one. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(snap => { + * if (snap.createTime.isEqual(snap.updateTime)) { + * console.log('Document is in its initial state.'); + * } + * }); + * + * ``` + * @param {any} other The `Timestamp` to compare against. + * @return {boolean} 'true' if this `Timestamp` is equal to the provided one. + */ + isEqual(other: firestore.Timestamp): boolean; + /** + * Generates the Protobuf `Timestamp` object for this timestamp. + * + * @private + * @internal + * @returns {Object} The `Timestamp` Protobuf object. + */ + toProto(): api.IValue; + /** + * Converts this object to a primitive `string`, which allows `Timestamp` objects to be compared + * using the `>`, `<=`, `>=` and `>` operators. + * + * @return {string} a string encoding of this object. + */ + valueOf(): string; +} diff --git a/node_modules/@google-cloud/firestore/build/src/timestamp.js b/node_modules/@google-cloud/firestore/build/src/timestamp.js new file mode 100644 index 0000000..9f4aa92 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/timestamp.js @@ -0,0 +1,284 @@ +"use strict"; +/*! + * Copyright 2018 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Timestamp = void 0; +const validate_1 = require("./validate"); +/*! + * Number of nanoseconds in a millisecond. + * + * @type {number} + */ +const MS_TO_NANOS = 1000000; +/*! + * The minimum legal value for the "seconds" property of a Timestamp object. + * + * This value corresponds to 0001-01-01T00:00:00Z. + * + * @type {number} + */ +const MIN_SECONDS = -62135596800; +/*! + * The maximum legal value for the "seconds" property of a Timestamp object. + * + * This value corresponds to 9999-12-31T23:59:59.999999999Z. + * + * @type {number} + */ +const MAX_SECONDS = 253402300799; +/** + * A Timestamp represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian + * Calendar which extends the Gregorian calendar backwards to year one. It is + * encoded assuming all minutes are 60 seconds long, i.e. leap seconds are + * "smeared" so that no leap second table is needed for interpretation. Range is + * from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. + * + * @see https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto + */ +class Timestamp { + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({ updateTime:Firestore.Timestamp.now() }); + * + * ``` + * @return {Timestamp} A new `Timestamp` representing the current date. + */ + static now() { + return Timestamp.fromMillis(Date.now()); + } + /** + * Creates a new timestamp from the given date. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * let date = Date.parse('01 Jan 2000 00:00:00 GMT'); + * documentRef.set({ startTime:Firestore.Timestamp.fromDate(date) }); + * + * ``` + * @param {Date} date The date to initialize the `Timestamp` from. + * @return {Timestamp} A new `Timestamp` representing the same point in time + * as the given date. + */ + static fromDate(date) { + return Timestamp.fromMillis(date.getTime()); + } + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({ startTime:Firestore.Timestamp.fromMillis(42) }); + * + * ``` + * @param {number} milliseconds Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @return {Timestamp} A new `Timestamp` representing the same point in time + * as the given number of milliseconds. + */ + static fromMillis(milliseconds) { + const seconds = Math.floor(milliseconds / 1000); + const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS); + return new Timestamp(seconds, nanos); + } + /** + * Generates a `Timestamp` object from a Timestamp proto. + * + * @private + * @internal + * @param {Object} timestamp The `Timestamp` Protobuf object. + */ + static fromProto(timestamp) { + return new Timestamp(Number(timestamp.seconds || 0), timestamp.nanos || 0); + } + /** + * Creates a new timestamp. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({ startTime:new Firestore.Timestamp(42, 0) }); + * + * ``` + * @param {number} seconds The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param {number} nanoseconds The non-negative fractions of a second at + * nanosecond resolution. Negative second values with fractions must still + * have non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor(seconds, nanoseconds) { + (0, validate_1.validateInteger)('seconds', seconds, { + minValue: MIN_SECONDS, + maxValue: MAX_SECONDS, + }); + (0, validate_1.validateInteger)('nanoseconds', nanoseconds, { + minValue: 0, + maxValue: 999999999, + }); + this._seconds = seconds; + this._nanoseconds = nanoseconds; + } + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(snap => { + * let updated = snap.updateTime; + * console.log(`Updated at ${updated.seconds}s ${updated.nanoseconds}ns`); + * }); + * + * ``` + * @type {number} + */ + get seconds() { + return this._seconds; + } + /** + * The non-negative fractions of a second at nanosecond resolution. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(snap => { + * let updated = snap.updateTime; + * console.log(`Updated at ${updated.seconds}s ${updated.nanoseconds}ns`); + * }); + * + * ``` + * @type {number} + */ + get nanoseconds() { + return this._nanoseconds; + } + /** + * Returns a new `Date` corresponding to this timestamp. This may lose + * precision. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(snap => { + * console.log(`Document updated at: ${snap.updateTime.toDate()}`); + * }); + * + * ``` + * @return {Date} JavaScript `Date` object representing the same point in time + * as this `Timestamp`, with millisecond precision. + */ + toDate() { + return new Date(this._seconds * 1000 + Math.round(this._nanoseconds / MS_TO_NANOS)); + } + /** + * Returns the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(snap => { + * let startTime = snap.get('startTime'); + * let endTime = snap.get('endTime'); + * console.log(`Duration: ${endTime - startTime}`); + * }); + * + * ``` + * @return {number} The point in time corresponding to this timestamp, + * represented as the number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + */ + toMillis() { + return this._seconds * 1000 + Math.floor(this._nanoseconds / MS_TO_NANOS); + } + /** + * Returns 'true' if this `Timestamp` is equal to the provided one. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(snap => { + * if (snap.createTime.isEqual(snap.updateTime)) { + * console.log('Document is in its initial state.'); + * } + * }); + * + * ``` + * @param {any} other The `Timestamp` to compare against. + * @return {boolean} 'true' if this `Timestamp` is equal to the provided one. + */ + isEqual(other) { + return (this === other || + (other instanceof Timestamp && + this._seconds === other.seconds && + this._nanoseconds === other.nanoseconds)); + } + /** + * Generates the Protobuf `Timestamp` object for this timestamp. + * + * @private + * @internal + * @returns {Object} The `Timestamp` Protobuf object. + */ + toProto() { + const timestamp = {}; + if (this.seconds) { + timestamp.seconds = this.seconds.toString(); + } + if (this.nanoseconds) { + timestamp.nanos = this.nanoseconds; + } + return { timestampValue: timestamp }; + } + /** + * Converts this object to a primitive `string`, which allows `Timestamp` objects to be compared + * using the `>`, `<=`, `>=` and `>` operators. + * + * @return {string} a string encoding of this object. + */ + valueOf() { + // This method returns a string of the form . where is + // translated to have a non-negative value and both and are left-padded + // with zeroes to be a consistent length. Strings with this format then have a lexicographical + // ordering that matches the expected ordering. The translation is done to avoid + // having a leading negative sign (i.e. a leading '-' character) in its string representation, + // which would affect its lexicographical ordering. + const adjustedSeconds = this.seconds - MIN_SECONDS; + // Note: Up to 12 decimal digits are required to represent all valid 'seconds' values. + const formattedSeconds = String(adjustedSeconds).padStart(12, '0'); + const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0'); + return formattedSeconds + '.' + formattedNanoseconds; + } +} +exports.Timestamp = Timestamp; +//# sourceMappingURL=timestamp.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/transaction.d.ts b/node_modules/@google-cloud/firestore/build/src/transaction.d.ts new file mode 100644 index 0000000..6661adf --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/transaction.d.ts @@ -0,0 +1,262 @@ +/*! + * Copyright 2017 Google Inc. 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. + */ +import * as firestore from '@google-cloud/firestore'; +import { DocumentSnapshot } from './document'; +import { Firestore } from './index'; +import { FieldPath } from './path'; +import { AggregateQuerySnapshot } from './reference/aggregate-query-snapshot'; +import { DocumentReference } from './reference/document-reference'; +import { QuerySnapshot } from './reference/query-snapshot'; +/** + * A reference to a transaction. + * + * The Transaction object passed to a transaction's updateFunction provides + * the methods to read and write data within the transaction context. See + * [runTransaction()]{@link Firestore#runTransaction}. + * + * @class Transaction + */ +export declare class Transaction implements firestore.Transaction { + private readonly _firestore; + private readonly _maxAttempts; + private readonly _requestTag; + /** Optional, could be set only if transaction is read only */ + private readonly _readOnlyReadTime; + /** `undefined` if transaction is read only */ + private readonly _writeBatch; + /** `undefined` if transaction is read only */ + private readonly _backoff; + /** + * Promise that resolves to the transaction ID of the current attempt. + * It is lazily initialised upon the first read. Upon retry, it is reset and + * `_prevTransactionId` is set + */ + private _transactionIdPromise?; + private _prevTransactionId?; + /** + * @private + * + * @param firestore The Firestore Database client. + * @param requestTag A unique client-assigned identifier for the scope of + * this transaction. + * @param transactionOptions The user-defined options for this transaction. + */ + constructor(firestore: Firestore, requestTag: string, transactionOptions?: firestore.ReadWriteTransactionOptions | firestore.ReadOnlyTransactionOptions); + /** + * Retrieves a query result. Holds a pessimistic lock on all returned + * documents. + * + * @param {Query} query A query to execute. + * @return {Promise} A QuerySnapshot for the retrieved data. + */ + get(query: firestore.Query): Promise>; + /** + * Reads the document referenced by the provided `DocumentReference.` + * Holds a pessimistic lock on the returned document. + * + * @param {DocumentReference} documentRef A reference to the document to be read. + * @return {Promise} A DocumentSnapshot for the read data. + */ + get(documentRef: firestore.DocumentReference): Promise>; + /** + * Retrieves an aggregate query result. Holds a pessimistic lock on all + * documents that were matched by the underlying query. + * + * @param aggregateQuery An aggregate query to execute. + * @return An AggregateQuerySnapshot for the retrieved data. + */ + get(aggregateQuery: firestore.AggregateQuery): Promise>; + /** + * Retrieves multiple documents from Firestore. Holds a pessimistic lock on + * all returned documents. + * + * The first argument is required and must be of type `DocumentReference` + * followed by any additional `DocumentReference` documents. If used, the + * optional `ReadOptions` must be the last argument. + * + * @param {...DocumentReference|ReadOptions} documentRefsOrReadOptions The + * `DocumentReferences` to receive, followed by an optional field mask. + * @returns {Promise>} A Promise that + * contains an array with the resulting document snapshots. + * + * @example + * ``` + * let firstDoc = firestore.doc('col/doc1'); + * let secondDoc = firestore.doc('col/doc2'); + * let resultDoc = firestore.doc('col/doc3'); + * + * firestore.runTransaction(transaction => { + * return transaction.getAll(firstDoc, secondDoc).then(docs => { + * transaction.set(resultDoc, { + * sum: docs[0].get('count') + docs[1].get('count') + * }); + * }); + * }); + * ``` + */ + getAll(...documentRefsOrReadOptions: Array | firestore.ReadOptions>): Promise>>; + /** + * Create the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. The operation will + * fail the transaction if a document exists at the specified location. + * + * @param {DocumentReference} documentRef A reference to the document to be + * created. + * @param {DocumentData} data The object data to serialize as the document. + * @returns {Transaction} This Transaction instance. Used for + * chaining method calls. + * + * @example + * ``` + * firestore.runTransaction(transaction => { + * let documentRef = firestore.doc('col/doc'); + * return transaction.get(documentRef).then(doc => { + * if (!doc.exists) { + * transaction.create(documentRef, { foo: 'bar' }); + * } + * }); + * }); + * ``` + */ + create(documentRef: firestore.DocumentReference, data: firestore.WithFieldValue): Transaction; + set(documentRef: firestore.DocumentReference, data: firestore.PartialWithFieldValue, options: firestore.SetOptions): Transaction; + set(documentRef: firestore.DocumentReference, data: firestore.WithFieldValue): Transaction; + /** + * Updates fields in the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. The update will + * fail if applied to a document that does not exist. + * + * The update() method accepts either an object with field paths encoded as + * keys and field values encoded as values, or a variable number of arguments + * that alternate between field paths and field values. Nested fields can be + * updated by providing dot-separated field path strings or by providing + * FieldPath objects. + * + * A Precondition restricting this update can be specified as the last + * argument. + * + * @param {DocumentReference} documentRef A reference to the document to be + * updated. + * @param {UpdateData|string|FieldPath} dataOrField An object + * containing the fields and values with which to update the document + * or the path of the first field to update. + * @param { + * ...(Precondition|*|string|FieldPath)} preconditionOrValues - + * An alternating list of field paths and values to update or a Precondition + * to to enforce on this update. + * @throws {Error} If the provided input is not valid Firestore data. + * @returns {Transaction} This Transaction instance. Used for + * chaining method calls. + * + * @example + * ``` + * firestore.runTransaction(transaction => { + * let documentRef = firestore.doc('col/doc'); + * return transaction.get(documentRef).then(doc => { + * if (doc.exists) { + * transaction.update(documentRef, { count: doc.get('count') + 1 }); + * } else { + * transaction.create(documentRef, { count: 1 }); + * } + * }); + * }); + * ``` + */ + update(documentRef: firestore.DocumentReference, dataOrField: firestore.UpdateData | string | firestore.FieldPath, ...preconditionOrValues: Array): Transaction; + /** + * Deletes the document referred to by the provided [DocumentReference] + * {@link DocumentReference}. + * + * @param {DocumentReference} documentRef A reference to the document to be + * deleted. + * @param {Precondition=} precondition A precondition to enforce for this + * delete. + * @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the + * document was last updated at lastUpdateTime. Fails the transaction if the + * document doesn't exist or was last updated at a different time. + * @param {boolean=} precondition.exists If set, enforces that the target + * document must or must not exist. + * @returns {Transaction} This Transaction instance. Used for + * chaining method calls. + * + * @example + * ``` + * firestore.runTransaction(transaction => { + * let documentRef = firestore.doc('col/doc'); + * transaction.delete(documentRef); + * return Promise.resolve(); + * }); + * ``` + */ + delete(documentRef: DocumentReference, precondition?: firestore.Precondition): this; + /** + * Commits all queued-up changes in this transaction and releases all locks. + * + * @private + * @internal + */ + commit(): Promise; + /** + * Releases all locks and rolls back this transaction. The rollback process + * is completed asynchronously and this function resolves before the operation + * is completed. + * + * @private + * @internal + */ + rollback(): Promise; + /** + * Executes `updateFunction()` and commits the transaction with retry. + * + * @private + * @internal + * @param updateFunction The user function to execute within the transaction + * context. + */ + runTransaction(updateFunction: (transaction: Transaction) => Promise): Promise; + /** + * Make single attempt to execute `updateFunction()` and commit the + * transaction. Will rollback upon error. + * + * @private + * @internal + * @param updateFunction The user function to execute within the transaction + * context. + */ + runTransactionOnce(updateFunction: (transaction: Transaction) => Promise): Promise; + /** + * Given a function that performs a read operation, ensures that the first one + * is provided with new transaction options and all subsequent ones are queued + * upon the resulting transaction ID. + */ + private withLazyStartedTransaction; + private getSingleFn; + private getBatchFn; + private getQueryFn; +} +/** + * Parses the arguments for the `getAll()` call supported by both the Firestore + * and Transaction class. + * + * @private + * @internal + * @param documentRefsOrReadOptions An array of document references followed by + * an optional ReadOptions object. + */ +export declare function parseGetAllArguments(documentRefsOrReadOptions: Array | firestore.ReadOptions>): { + documents: Array>; + fieldMask: FieldPath[] | undefined; +}; diff --git a/node_modules/@google-cloud/firestore/build/src/transaction.js b/node_modules/@google-cloud/firestore/build/src/transaction.js new file mode 100644 index 0000000..d21a46c --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/transaction.js @@ -0,0 +1,619 @@ +"use strict"; +/*! + * Copyright 2017 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Transaction = void 0; +exports.parseGetAllArguments = parseGetAllArguments; +const backoff_1 = require("./backoff"); +const index_1 = require("./index"); +const logger_1 = require("./logger"); +const path_1 = require("./path"); +const aggregate_query_1 = require("./reference/aggregate-query"); +const document_reference_1 = require("./reference/document-reference"); +const query_1 = require("./reference/query"); +const helpers_1 = require("./reference/helpers"); +const util_1 = require("./util"); +const validate_1 = require("./validate"); +const document_reader_1 = require("./document-reader"); +const trace_util_1 = require("./telemetry/trace-util"); +/*! + * Error message for transactional reads that were executed after performing + * writes. + */ +const READ_AFTER_WRITE_ERROR_MSG = 'Firestore transactions require all reads to be executed before all writes.'; +const READ_ONLY_WRITE_ERROR_MSG = 'Firestore read-only transactions cannot execute writes.'; +/** + * A reference to a transaction. + * + * The Transaction object passed to a transaction's updateFunction provides + * the methods to read and write data within the transaction context. See + * [runTransaction()]{@link Firestore#runTransaction}. + * + * @class Transaction + */ +class Transaction { + /** + * @private + * + * @param firestore The Firestore Database client. + * @param requestTag A unique client-assigned identifier for the scope of + * this transaction. + * @param transactionOptions The user-defined options for this transaction. + */ + constructor(firestore, requestTag, transactionOptions) { + this._maxAttempts = index_1.DEFAULT_MAX_TRANSACTION_ATTEMPTS; + this._firestore = firestore; + this._requestTag = requestTag; + if (transactionOptions === null || transactionOptions === void 0 ? void 0 : transactionOptions.readOnly) { + // Avoid initialising write batch and backoff unnecessarily for read-only transactions + this._maxAttempts = 1; + this._readOnlyReadTime = transactionOptions.readTime; + } + else { + this._maxAttempts = + (transactionOptions === null || transactionOptions === void 0 ? void 0 : transactionOptions.maxAttempts) || index_1.DEFAULT_MAX_TRANSACTION_ATTEMPTS; + this._writeBatch = firestore.batch(); + this._backoff = new backoff_1.ExponentialBackoff(); + } + } + /** + * Retrieve a document or a query result from the database. Holds a + * pessimistic lock on all returned documents. + * + * @param {DocumentReference|Query} refOrQuery The document or query to + * return. + * @returns {Promise} A Promise that resolves with a DocumentSnapshot or + * QuerySnapshot for the returned documents. + * + * @example + * ``` + * firestore.runTransaction(transaction => { + * let documentRef = firestore.doc('col/doc'); + * return transaction.get(documentRef).then(doc => { + * if (doc.exists) { + * transaction.update(documentRef, { count: doc.get('count') + 1 }); + * } else { + * transaction.create(documentRef, { count: 1 }); + * } + * }); + * }); + * ``` + */ + get(refOrQuery) { + if (this._writeBatch && !this._writeBatch.isEmpty) { + throw new Error(READ_AFTER_WRITE_ERROR_MSG); + } + if (refOrQuery instanceof document_reference_1.DocumentReference) { + return this._firestore._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_TRANSACTION_GET_DOCUMENT, () => { + return this.withLazyStartedTransaction(refOrQuery, this.getSingleFn); + }); + } + if (refOrQuery instanceof query_1.Query || refOrQuery instanceof aggregate_query_1.AggregateQuery) { + return this._firestore._traceUtil.startActiveSpan(refOrQuery instanceof query_1.Query + ? trace_util_1.SPAN_NAME_TRANSACTION_GET_QUERY + : trace_util_1.SPAN_NAME_TRANSACTION_GET_AGGREGATION_QUERY, () => { + return this.withLazyStartedTransaction(refOrQuery, this.getQueryFn); + }); + } + throw new Error('Value for argument "refOrQuery" must be a DocumentReference, Query, or AggregateQuery.'); + } + /** + * Retrieves multiple documents from Firestore. Holds a pessimistic lock on + * all returned documents. + * + * The first argument is required and must be of type `DocumentReference` + * followed by any additional `DocumentReference` documents. If used, the + * optional `ReadOptions` must be the last argument. + * + * @param {...DocumentReference|ReadOptions} documentRefsOrReadOptions The + * `DocumentReferences` to receive, followed by an optional field mask. + * @returns {Promise>} A Promise that + * contains an array with the resulting document snapshots. + * + * @example + * ``` + * let firstDoc = firestore.doc('col/doc1'); + * let secondDoc = firestore.doc('col/doc2'); + * let resultDoc = firestore.doc('col/doc3'); + * + * firestore.runTransaction(transaction => { + * return transaction.getAll(firstDoc, secondDoc).then(docs => { + * transaction.set(resultDoc, { + * sum: docs[0].get('count') + docs[1].get('count') + * }); + * }); + * }); + * ``` + */ + getAll(...documentRefsOrReadOptions) { + if (this._writeBatch && !this._writeBatch.isEmpty) { + throw new Error(READ_AFTER_WRITE_ERROR_MSG); + } + (0, validate_1.validateMinNumberOfArguments)('Transaction.getAll', documentRefsOrReadOptions, 1); + return this.withLazyStartedTransaction(parseGetAllArguments(documentRefsOrReadOptions), this.getBatchFn); + } + /** + * Create the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. The operation will + * fail the transaction if a document exists at the specified location. + * + * @param {DocumentReference} documentRef A reference to the document to be + * created. + * @param {DocumentData} data The object data to serialize as the document. + * @returns {Transaction} This Transaction instance. Used for + * chaining method calls. + * + * @example + * ``` + * firestore.runTransaction(transaction => { + * let documentRef = firestore.doc('col/doc'); + * return transaction.get(documentRef).then(doc => { + * if (!doc.exists) { + * transaction.create(documentRef, { foo: 'bar' }); + * } + * }); + * }); + * ``` + */ + create(documentRef, data) { + if (!this._writeBatch) { + throw new Error(READ_ONLY_WRITE_ERROR_MSG); + } + this._writeBatch.create(documentRef, data); + return this; + } + /** + * Writes to the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. If the document + * does not exist yet, it will be created. If you pass + * [SetOptions]{@link SetOptions}, the provided data can be merged into the + * existing document. + * + * @param {DocumentReference} documentRef A reference to the document to be + * set. + * @param {T|Partial} data The object to serialize as the document. + * @param {SetOptions=} options An object to configure the set behavior. + * @param {boolean=} options.merge - If true, set() merges the values + * specified in its data argument. Fields omitted from this set() call remain + * untouched. If your input sets any field to an empty map, all nested fields + * are overwritten. + * @param {Array.=} options.mergeFields - If provided, + * set() only replaces the specified field paths. Any field path that is not + * specified is ignored and remains untouched. If your input sets any field to + * an empty map, all nested fields are overwritten. + * @throws {Error} If the provided input is not a valid Firestore document. + * @returns {Transaction} This Transaction instance. Used for + * chaining method calls. + * + * @example + * ``` + * firestore.runTransaction(transaction => { + * let documentRef = firestore.doc('col/doc'); + * transaction.set(documentRef, { foo: 'bar' }); + * return Promise.resolve(); + * }); + * ``` + */ + set(documentRef, data, options) { + if (!this._writeBatch) { + throw new Error(READ_ONLY_WRITE_ERROR_MSG); + } + if (options) { + this._writeBatch.set(documentRef, data, options); + } + else { + this._writeBatch.set(documentRef, data); + } + return this; + } + /** + * Updates fields in the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. The update will + * fail if applied to a document that does not exist. + * + * The update() method accepts either an object with field paths encoded as + * keys and field values encoded as values, or a variable number of arguments + * that alternate between field paths and field values. Nested fields can be + * updated by providing dot-separated field path strings or by providing + * FieldPath objects. + * + * A Precondition restricting this update can be specified as the last + * argument. + * + * @param {DocumentReference} documentRef A reference to the document to be + * updated. + * @param {UpdateData|string|FieldPath} dataOrField An object + * containing the fields and values with which to update the document + * or the path of the first field to update. + * @param { + * ...(Precondition|*|string|FieldPath)} preconditionOrValues - + * An alternating list of field paths and values to update or a Precondition + * to to enforce on this update. + * @throws {Error} If the provided input is not valid Firestore data. + * @returns {Transaction} This Transaction instance. Used for + * chaining method calls. + * + * @example + * ``` + * firestore.runTransaction(transaction => { + * let documentRef = firestore.doc('col/doc'); + * return transaction.get(documentRef).then(doc => { + * if (doc.exists) { + * transaction.update(documentRef, { count: doc.get('count') + 1 }); + * } else { + * transaction.create(documentRef, { count: 1 }); + * } + * }); + * }); + * ``` + */ + update(documentRef, dataOrField, ...preconditionOrValues) { + if (!this._writeBatch) { + throw new Error(READ_ONLY_WRITE_ERROR_MSG); + } + // eslint-disable-next-line prefer-rest-params + (0, validate_1.validateMinNumberOfArguments)('Transaction.update', arguments, 2); + this._writeBatch.update(documentRef, dataOrField, ...preconditionOrValues); + return this; + } + /** + * Deletes the document referred to by the provided [DocumentReference] + * {@link DocumentReference}. + * + * @param {DocumentReference} documentRef A reference to the document to be + * deleted. + * @param {Precondition=} precondition A precondition to enforce for this + * delete. + * @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the + * document was last updated at lastUpdateTime. Fails the transaction if the + * document doesn't exist or was last updated at a different time. + * @param {boolean=} precondition.exists If set, enforces that the target + * document must or must not exist. + * @returns {Transaction} This Transaction instance. Used for + * chaining method calls. + * + * @example + * ``` + * firestore.runTransaction(transaction => { + * let documentRef = firestore.doc('col/doc'); + * transaction.delete(documentRef); + * return Promise.resolve(); + * }); + * ``` + */ + delete( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + documentRef, precondition) { + if (!this._writeBatch) { + throw new Error(READ_ONLY_WRITE_ERROR_MSG); + } + this._writeBatch.delete(documentRef, precondition); + return this; + } + /** + * Commits all queued-up changes in this transaction and releases all locks. + * + * @private + * @internal + */ + async commit() { + var _a; + return this._firestore._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_TRANSACTION_COMMIT, async () => { + if (!this._writeBatch) { + throw new Error(READ_ONLY_WRITE_ERROR_MSG); + } + // If we have not performed any reads in this particular attempt + // then the writes will be atomically committed without a transaction ID + let transactionId; + if (this._transactionIdPromise) { + transactionId = await this._transactionIdPromise; + } + else if (this._writeBatch.isEmpty) { + // If we have not started a transaction (no reads) and we have no writes + // then the commit is a no-op (success) + return; + } + await this._writeBatch._commit({ + transactionId, + requestTag: this._requestTag, + }); + this._transactionIdPromise = undefined; + this._prevTransactionId = transactionId; + }, { + [trace_util_1.ATTRIBUTE_KEY_IS_TRANSACTIONAL]: true, + [trace_util_1.ATTRIBUTE_KEY_DOC_COUNT]: (_a = this._writeBatch) === null || _a === void 0 ? void 0 : _a._opCount, + }); + } + /** + * Releases all locks and rolls back this transaction. The rollback process + * is completed asynchronously and this function resolves before the operation + * is completed. + * + * @private + * @internal + */ + async rollback() { + return this._firestore._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_TRANSACTION_ROLLBACK, async () => { + // No need to roll back if we have not lazily started the transaction + // or if we are read only + if (!this._transactionIdPromise || !this._writeBatch) { + return; + } + let transactionId; + try { + transactionId = await this._transactionIdPromise; + } + catch (_a) { + // This means the initial read operation rejected + // and we do not have a transaction ID to roll back + this._transactionIdPromise = undefined; + return; + } + const request = { + database: this._firestore.formattedName, + transaction: transactionId, + }; + this._transactionIdPromise = undefined; + this._prevTransactionId = transactionId; + // We don't need to wait for rollback to completed before continuing. + // If there are any locks held, then rollback will eventually release them. + // Rollback can be done concurrently thereby reducing latency caused by + // otherwise blocking. + this._firestore + .request('rollback', request, this._requestTag) + .catch(err => { + (0, logger_1.logger)('Firestore.runTransaction', this._requestTag, 'Best effort to rollback failed with error:', err); + }); + }); + } + /** + * Executes `updateFunction()` and commits the transaction with retry. + * + * @private + * @internal + * @param updateFunction The user function to execute within the transaction + * context. + */ + async runTransaction(updateFunction) { + return this._firestore._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_TRANSACTION_RUN, async (span) => { + // No backoff is set for readonly transactions (i.e. attempts == 1) + if (!this._writeBatch) { + return this.runTransactionOnce(updateFunction); + } + let lastError = undefined; + for (let attempt = 0; attempt < this._maxAttempts; ++attempt) { + span.setAttributes({ + [trace_util_1.ATTRIBUTE_KEY_TRANSACTION_TYPE]: this._writeBatch + ? 'READ_WRITE' + : 'READ_ONLY', + [trace_util_1.ATTRIBUTE_KEY_ATTEMPTS_ALLOWED]: this._maxAttempts, + [trace_util_1.ATTRIBUTE_KEY_ATTEMPTS_REMAINING]: this._maxAttempts - attempt - 1, + }); + try { + if (lastError) { + (0, logger_1.logger)('Firestore.runTransaction', this._requestTag, 'Retrying transaction after error:', lastError); + span.addEvent('Initiate transaction retry'); + } + this._writeBatch._reset(); + await maybeBackoff(this._backoff, lastError); + return await this.runTransactionOnce(updateFunction); + } + catch (err) { + lastError = err; + if (!isRetryableTransactionError(err)) { + break; + } + } + } + (0, logger_1.logger)('Firestore.runTransaction', this._requestTag, 'Transaction not eligible for retry, returning error: %s', lastError); + return Promise.reject(lastError); + }); + } + /** + * Make single attempt to execute `updateFunction()` and commit the + * transaction. Will rollback upon error. + * + * @private + * @internal + * @param updateFunction The user function to execute within the transaction + * context. + */ + async runTransactionOnce(updateFunction) { + try { + const promise = updateFunction(this); + if (!(promise instanceof Promise)) { + throw new Error('You must return a Promise in your transaction()-callback.'); + } + const result = await promise; + if (this._writeBatch) { + await this.commit(); + } + return result; + } + catch (err) { + (0, logger_1.logger)('Firestore.runTransaction', this._requestTag, 'Rolling back transaction after callback error:', err); + await this.rollback(); + return Promise.reject(err); + } + } + /** + * Given a function that performs a read operation, ensures that the first one + * is provided with new transaction options and all subsequent ones are queued + * upon the resulting transaction ID. + */ + withLazyStartedTransaction(param, resultFn) { + if (this._transactionIdPromise) { + // Simply queue this subsequent read operation after the first read + // operation has resolved and we don't expect a transaction ID in the + // response because we are not starting a new transaction + return this._transactionIdPromise + .then(opts => resultFn.call(this, param, opts)) + .then(r => r.result); + } + else { + if (this._readOnlyReadTime) { + // We do not start a transaction for read-only transactions + // do not set _prevTransactionId + return resultFn + .call(this, param, this._readOnlyReadTime) + .then(r => r.result); + } + else { + // This is the first read of the transaction so we create the appropriate + // options for lazily starting the transaction inside this first read op + const opts = {}; + if (this._writeBatch) { + opts.readWrite = this._prevTransactionId + ? { retryTransaction: this._prevTransactionId } + : {}; + } + else { + opts.readOnly = {}; + } + const resultPromise = resultFn.call(this, param, opts); + // Ensure the _transactionIdPromise is set synchronously so that + // subsequent operations will not race to start another transaction + this._transactionIdPromise = resultPromise.then(r => { + if (!r.transaction) { + // Illegal state + // The read operation was provided with new transaction options but did not return a transaction ID + // Rejecting here will cause all queued reads to reject + throw new Error('Transaction ID was missing from server response'); + } + return r.transaction; + }); + return resultPromise.then(r => r.result); + } + } + } + async getSingleFn(document, opts) { + const documentReader = new document_reader_1.DocumentReader(this._firestore, [document], undefined, opts); + const { transaction, result: [result], } = await documentReader._get(this._requestTag); + return { transaction, result }; + } + async getBatchFn({ documents, fieldMask, }, opts) { + return this._firestore._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_TRANSACTION_GET_DOCUMENTS, async () => { + const documentReader = new document_reader_1.DocumentReader(this._firestore, documents, fieldMask, opts); + return documentReader._get(this._requestTag); + }); + } + async getQueryFn(query, opts) { + return query._get(opts); + } +} +exports.Transaction = Transaction; +/** + * Parses the arguments for the `getAll()` call supported by both the Firestore + * and Transaction class. + * + * @private + * @internal + * @param documentRefsOrReadOptions An array of document references followed by + * an optional ReadOptions object. + */ +function parseGetAllArguments(documentRefsOrReadOptions) { + let documents; + let readOptions = undefined; + if (Array.isArray(documentRefsOrReadOptions[0])) { + throw new Error('getAll() no longer accepts an array as its first argument. ' + + 'Please unpack your array and call getAll() with individual arguments.'); + } + if (documentRefsOrReadOptions.length > 0 && + (0, util_1.isPlainObject)(documentRefsOrReadOptions[documentRefsOrReadOptions.length - 1])) { + readOptions = documentRefsOrReadOptions.pop(); + documents = documentRefsOrReadOptions; + } + else { + documents = documentRefsOrReadOptions; + } + for (let i = 0; i < documents.length; ++i) { + (0, helpers_1.validateDocumentReference)(i, documents[i]); + } + validateReadOptions('options', readOptions, { optional: true }); + const fieldMask = readOptions && readOptions.fieldMask + ? readOptions.fieldMask.map(fieldPath => path_1.FieldPath.fromArgument(fieldPath)) + : undefined; + return { fieldMask, documents }; +} +/** + * Validates the use of 'options' as ReadOptions and enforces that 'fieldMask' + * is an array of strings or field paths. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the ReadOptions can be omitted. + */ +function validateReadOptions(arg, value, options) { + if (!(0, validate_1.validateOptional)(value, options)) { + if (!(0, util_1.isObject)(value)) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, 'read option')} Input is not an object.'`); + } + const options = value; + if (options.fieldMask !== undefined) { + if (!Array.isArray(options.fieldMask)) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, 'read option')} "fieldMask" is not an array.`); + } + for (let i = 0; i < options.fieldMask.length; ++i) { + try { + (0, path_1.validateFieldPath)(i, options.fieldMask[i]); + } + catch (err) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, 'read option')} "fieldMask" is not valid: ${err.message}`); + } + } + } + } +} +function isRetryableTransactionError(error) { + if (error.code !== undefined) { + // This list is based on https://github.com/firebase/firebase-js-sdk/blob/master/packages/firestore/src/core/transaction_runner.ts#L112 + switch (error.code) { + case 10 /* StatusCode.ABORTED */: + case 1 /* StatusCode.CANCELLED */: + case 2 /* StatusCode.UNKNOWN */: + case 4 /* StatusCode.DEADLINE_EXCEEDED */: + case 13 /* StatusCode.INTERNAL */: + case 14 /* StatusCode.UNAVAILABLE */: + case 16 /* StatusCode.UNAUTHENTICATED */: + case 8 /* StatusCode.RESOURCE_EXHAUSTED */: + return true; + case 3 /* StatusCode.INVALID_ARGUMENT */: + // The Firestore backend uses "INVALID_ARGUMENT" for transactions + // IDs that have expired. While INVALID_ARGUMENT is generally not + // retryable, we retry this specific case. + return !!error.message.match(/transaction has expired/); + default: + return false; + } + } + return false; +} +/** + * Delays further operations based on the provided error. + * + * @private + * @internal + * @return A Promise that resolves after the delay expired. + */ +async function maybeBackoff(backoff, error) { + if ((error === null || error === void 0 ? void 0 : error.code) === 8 /* StatusCode.RESOURCE_EXHAUSTED */) { + backoff.resetToMax(); + } + await backoff.backoffAndWait(); +} +//# sourceMappingURL=transaction.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/types.d.ts b/node_modules/@google-cloud/firestore/build/src/types.d.ts new file mode 100644 index 0000000..7c837b3 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/types.d.ts @@ -0,0 +1,89 @@ +/*! + * Copyright 2018 Google Inc. 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. + */ +import { FirestoreDataConverter, DocumentData } from '@google-cloud/firestore'; +import { CallOptions } from 'google-gax'; +import { Duplex } from 'stream'; +import { google } from '../protos/firestore_v1_proto_api'; +import { FieldPath } from './path'; +import api = google.firestore.v1; +/** + * A map in the format of the Proto API + */ +export interface ApiMapValue { + [k: string]: google.firestore.v1.IValue; +} +/** + * The subset of methods we use from FirestoreClient. + * + * We don't depend on the actual Gapic client to avoid loading the GAX stack at + * module initialization time. + */ +export interface GapicClient { + getProjectId(): Promise; + beginTransaction(request: api.IBeginTransactionRequest, options?: CallOptions): Promise<[api.IBeginTransactionResponse, unknown, unknown]>; + commit(request: api.ICommitRequest, options?: CallOptions): Promise<[api.ICommitResponse, unknown, unknown]>; + batchWrite(request: api.IBatchWriteRequest, options?: CallOptions): Promise<[api.IBatchWriteResponse, unknown, unknown]>; + rollback(request: api.IRollbackRequest, options?: CallOptions): Promise<[google.protobuf.IEmpty, unknown, unknown]>; + batchGetDocuments(request?: api.IBatchGetDocumentsRequest, options?: CallOptions): Duplex; + runQuery(request?: api.IRunQueryRequest, options?: CallOptions): Duplex; + runAggregationQuery(request?: api.IRunAggregationQueryRequest, options?: CallOptions): Duplex; + listDocuments(request: api.IListDocumentsRequest, options?: CallOptions): Promise<[api.IDocument[], unknown, unknown]>; + listCollectionIds(request: api.IListCollectionIdsRequest, options?: CallOptions): Promise<[string[], unknown, unknown]>; + listen(options?: CallOptions): Duplex; + partitionQueryStream(request?: api.IPartitionQueryRequest, options?: CallOptions): Duplex; + close(): Promise; +} +/** Request/response methods used in the Firestore SDK. */ +export type FirestoreUnaryMethod = 'listDocuments' | 'listCollectionIds' | 'rollback' | 'beginTransaction' | 'commit' | 'batchWrite'; +/** Streaming methods used in the Firestore SDK. */ +export type FirestoreStreamingMethod = 'listen' | 'partitionQueryStream' | 'runQuery' | 'runAggregationQuery' | 'batchGetDocuments'; +/** Type signature for the unary methods in the GAPIC layer. */ +export type UnaryMethod = (request: Req, callOptions: CallOptions) => Promise<[Resp, unknown, unknown]>; +export type RBTree = any; +/** + * A default converter to use when none is provided. + * @private + * @internal + */ +export declare function defaultConverter(): FirestoreDataConverter; +/** + * Update data that has been resolved to a mapping of FieldPaths to values. + */ +export type UpdateMap = Map; +/** + * Internal user data validation options. + * @private + * @internal + */ +export interface ValidationOptions { + /** At what level field deletes are supported. */ + allowDeletes: 'none' | 'root' | 'all'; + /** Whether server transforms are supported. */ + allowTransforms: boolean; + /** + * Whether undefined values are allowed. Undefined values cannot appear at + * the root. + */ + allowUndefined: boolean; +} +/** + * A Firestore Proto value in ProtoJs format. + * @private + * @internal + */ +export interface ProtobufJsValue extends api.IValue { + valueType?: string; +} diff --git a/node_modules/@google-cloud/firestore/build/src/types.js b/node_modules/@google-cloud/firestore/build/src/types.js new file mode 100644 index 0000000..2639da8 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/types.js @@ -0,0 +1,44 @@ +"use strict"; +/*! + * Copyright 2018 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultConverter = defaultConverter; +/** + * A default converter to use when none is provided. + * + * By declaring the converter as a variable instead of creating the object + * inside defaultConverter(), object equality when comparing default converters + * is preserved. + * @private + * @internal + */ +const defaultConverterObj = { + toFirestore(modelObject) { + return modelObject; + }, + fromFirestore(snapshot) { + return snapshot.data(); + }, +}; +/** + * A default converter to use when none is provided. + * @private + * @internal + */ +function defaultConverter() { + return defaultConverterObj; +} +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/util.d.ts b/node_modules/@google-cloud/firestore/build/src/util.d.ts new file mode 100644 index 0000000..021104b --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/util.d.ts @@ -0,0 +1,178 @@ +/*! + * Copyright 2018 Google Inc. 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. + */ +import { DocumentData } from '@google-cloud/firestore'; +import type { GoogleError } from 'google-gax'; +import type { BackoffSettings } from 'google-gax/build/src/gax'; +import Dict = NodeJS.Dict; +/** + * A Promise implementation that supports deferred resolution. + * @private + * @internal + */ +export declare class Deferred { + promise: Promise; + resolve: (value: R | Promise) => void; + reject: (reason: Error) => void; + constructor(); +} +/** + * Generate a unique client-side identifier. + * + * Used for the creation of new documents. + * + * @private + * @internal + * @returns {string} A unique 20-character wide identifier. + */ +export declare function autoId(): string; +/** + * Generate a short and semi-random client-side identifier. + * + * Used for the creation of request tags. + * + * @private + * @internal + * @returns {string} A random 5-character wide identifier. + */ +export declare function requestTag(): string; +/** + * Determines whether `value` is a JavaScript object. + * + * @private + * @internal + */ +export declare function isObject(value: unknown): value is { + [k: string]: unknown; +}; +/** + * Verifies that 'obj' is a plain JavaScript object that can be encoded as a + * 'Map' in Firestore. + * + * @private + * @internal + * @param input The argument to verify. + * @returns 'true' if the input can be a treated as a plain object. + */ +export declare function isPlainObject(input: unknown): input is DocumentData; +/** + * Returns whether `value` has no custom properties. + * + * @private + * @internal + */ +export declare function isEmpty(value: {}): boolean; +/** + * Determines whether `value` is a JavaScript function. + * + * @private + * @internal + */ +export declare function isFunction(value: unknown): boolean; +/** + * Determines whether the provided error is considered permanent for the given + * RPC. + * + * @private + * @internal + */ +export declare function isPermanentRpcError(err: GoogleError, methodName: string): boolean; +/** + * Returns the list of retryable error codes specified in the service + * configuration. + * @private + * @internal + */ +export declare function getRetryCodes(methodName: string): number[]; +/** + * Gets the total timeout in milliseconds from the retry settings in + * the service config for the given RPC. If the total timeout is not + * set, then `0` is returned. + * + * @private + * @internal + */ +export declare function getTotalTimeout(methodName: string): number; +/** + * Returns the backoff setting from the service configuration. + * @private + * @internal + */ +export declare function getRetryParams(methodName: string): BackoffSettings; +/** + * Returns a promise with a void return type. The returned promise swallows all + * errors and never throws. + * + * This is primarily used to wait for a promise to complete when the result of + * the promise will be discarded. + * + * @private + * @internal + */ +export declare function silencePromise(promise: Promise): Promise; +/** + * Wraps the provided error in a new error that includes the provided stack. + * + * Used to preserve stack traces across async calls. + * @private + * @internal + */ +export declare function wrapError(err: Error, stack: string): Error; +/** + * Parses the value of the environment variable FIRESTORE_PREFER_REST, and + * returns a value indicating if the environment variable enables or disables + * preferRest. + * + * This function will warn to the console if the environment variable is set + * to an unsupported value. + * + * @return `true` if the environment variable enables `preferRest`, + * `false` if the environment variable disables `preferRest`, or `undefined` + * if the environment variable is not set or is set to an unsupported value. + * + * @internal + * @private + */ +export declare function tryGetPreferRestEnvironmentVariable(): boolean | undefined; +/** + * Returns an array of values that are calculated by performing the given `fn` + * on all keys in the given `obj` dictionary. + * + * @private + * @internal + */ +export declare function mapToArray(obj: Dict, fn: (element: V, key: string, obj: Dict) => R): R[]; +/** + * Verifies equality for an array of objects using the `isEqual` interface. + * + * @private + * @internal + * @param left Array of objects supporting `isEqual`. + * @param right Array of objects supporting `isEqual`. + * @return True if arrays are equal. + */ +export declare function isArrayEqual boolean; +}>(left: T[], right: T[]): boolean; +/** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ +export declare function isPrimitiveArrayEqual(left: T[], right: T[]): boolean; diff --git a/node_modules/@google-cloud/firestore/build/src/util.js b/node_modules/@google-cloud/firestore/build/src/util.js new file mode 100644 index 0000000..8550666 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/util.js @@ -0,0 +1,305 @@ +"use strict"; +/*! + * Copyright 2018 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Deferred = void 0; +exports.autoId = autoId; +exports.requestTag = requestTag; +exports.isObject = isObject; +exports.isPlainObject = isPlainObject; +exports.isEmpty = isEmpty; +exports.isFunction = isFunction; +exports.isPermanentRpcError = isPermanentRpcError; +exports.getRetryCodes = getRetryCodes; +exports.getTotalTimeout = getTotalTimeout; +exports.getRetryParams = getRetryParams; +exports.silencePromise = silencePromise; +exports.wrapError = wrapError; +exports.tryGetPreferRestEnvironmentVariable = tryGetPreferRestEnvironmentVariable; +exports.mapToArray = mapToArray; +exports.isArrayEqual = isArrayEqual; +exports.isPrimitiveArrayEqual = isPrimitiveArrayEqual; +const crypto_1 = require("crypto"); +const gapicConfig = require("./v1/firestore_client_config.json"); +/** + * A Promise implementation that supports deferred resolution. + * @private + * @internal + */ +class Deferred { + constructor() { + this.resolve = () => { }; + this.reject = () => { }; + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } +} +exports.Deferred = Deferred; +/** + * Generate a unique client-side identifier. + * + * Used for the creation of new documents. + * + * @private + * @internal + * @returns {string} A unique 20-character wide identifier. + */ +function autoId() { + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + let autoId = ''; + while (autoId.length < 20) { + const bytes = (0, crypto_1.randomBytes)(40); + bytes.forEach(b => { + // Length of `chars` is 62. We only take bytes between 0 and 62*4-1 + // (both inclusive). The value is then evenly mapped to indices of `char` + // via a modulo operation. + const maxValue = 62 * 4 - 1; + if (autoId.length < 20 && b <= maxValue) { + autoId += chars.charAt(b % 62); + } + }); + } + return autoId; +} +/** + * Generate a short and semi-random client-side identifier. + * + * Used for the creation of request tags. + * + * @private + * @internal + * @returns {string} A random 5-character wide identifier. + */ +function requestTag() { + return autoId().substr(0, 5); +} +/** + * Determines whether `value` is a JavaScript object. + * + * @private + * @internal + */ +function isObject(value) { + return Object.prototype.toString.call(value) === '[object Object]'; +} +/** + * Verifies that 'obj' is a plain JavaScript object that can be encoded as a + * 'Map' in Firestore. + * + * @private + * @internal + * @param input The argument to verify. + * @returns 'true' if the input can be a treated as a plain object. + */ +function isPlainObject(input) { + return (isObject(input) && + (Object.getPrototypeOf(input) === Object.prototype || + Object.getPrototypeOf(input) === null || + input.constructor.name === 'Object')); +} +/** + * Returns whether `value` has no custom properties. + * + * @private + * @internal + */ +function isEmpty(value) { + return Object.keys(value).length === 0; +} +/** + * Determines whether `value` is a JavaScript function. + * + * @private + * @internal + */ +function isFunction(value) { + return typeof value === 'function'; +} +/** + * Determines whether the provided error is considered permanent for the given + * RPC. + * + * @private + * @internal + */ +function isPermanentRpcError(err, methodName) { + if (err.code !== undefined) { + const retryCodes = getRetryCodes(methodName); + return retryCodes.indexOf(err.code) === -1; + } + else { + return false; + } +} +let serviceConfig; +/** + * Lazy-loads the service config when first accessed. + * @private + * @internal + **/ +function getServiceConfig(methodName) { + if (!serviceConfig) { + serviceConfig = require('google-gax/build/src/fallback').constructSettings('google.firestore.v1.Firestore', gapicConfig, {}, require('google-gax/build/src/status').Status); + } + return serviceConfig[methodName]; +} +/** + * Returns the list of retryable error codes specified in the service + * configuration. + * @private + * @internal + */ +function getRetryCodes(methodName) { + var _a, _b, _c; + return (_c = (_b = (_a = getServiceConfig(methodName)) === null || _a === void 0 ? void 0 : _a.retry) === null || _b === void 0 ? void 0 : _b.retryCodes) !== null && _c !== void 0 ? _c : []; +} +/** + * Gets the total timeout in milliseconds from the retry settings in + * the service config for the given RPC. If the total timeout is not + * set, then `0` is returned. + * + * @private + * @internal + */ +function getTotalTimeout(methodName) { + var _a, _b, _c, _d; + return ((_d = (_c = (_b = (_a = getServiceConfig(methodName)) === null || _a === void 0 ? void 0 : _a.retry) === null || _b === void 0 ? void 0 : _b.backoffSettings) === null || _c === void 0 ? void 0 : _c.totalTimeoutMillis) !== null && _d !== void 0 ? _d : 0); +} +/** + * Returns the backoff setting from the service configuration. + * @private + * @internal + */ +function getRetryParams(methodName) { + var _a, _b, _c; + return ((_c = (_b = (_a = getServiceConfig(methodName)) === null || _a === void 0 ? void 0 : _a.retry) === null || _b === void 0 ? void 0 : _b.backoffSettings) !== null && _c !== void 0 ? _c : require('google-gax/build/src/fallback').createDefaultBackoffSettings()); +} +/** + * Returns a promise with a void return type. The returned promise swallows all + * errors and never throws. + * + * This is primarily used to wait for a promise to complete when the result of + * the promise will be discarded. + * + * @private + * @internal + */ +function silencePromise(promise) { + return promise.then(() => { }, () => { }); +} +/** + * Wraps the provided error in a new error that includes the provided stack. + * + * Used to preserve stack traces across async calls. + * @private + * @internal + */ +function wrapError(err, stack) { + err.stack += '\nCaused by: ' + stack; + return err; +} +/** + * Parses the value of the environment variable FIRESTORE_PREFER_REST, and + * returns a value indicating if the environment variable enables or disables + * preferRest. + * + * This function will warn to the console if the environment variable is set + * to an unsupported value. + * + * @return `true` if the environment variable enables `preferRest`, + * `false` if the environment variable disables `preferRest`, or `undefined` + * if the environment variable is not set or is set to an unsupported value. + * + * @internal + * @private + */ +function tryGetPreferRestEnvironmentVariable() { + var _a; + const rawValue = (_a = process.env.FIRESTORE_PREFER_REST) === null || _a === void 0 ? void 0 : _a.trim().toLowerCase(); + if (rawValue === undefined) { + return undefined; + } + else if (rawValue === '1' || rawValue === 'true') { + return true; + } + else if (rawValue === '0' || rawValue === 'false') { + return false; + } + else { + // eslint-disable-next-line no-console + console.warn(`An unsupported value was specified for the environment variable FIRESTORE_PREFER_REST. Value ${rawValue} is unsupported.`); + return undefined; + } +} +/** + * Returns an array of values that are calculated by performing the given `fn` + * on all keys in the given `obj` dictionary. + * + * @private + * @internal + */ +function mapToArray(obj, fn) { + const result = []; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + result.push(fn(obj[key], key, obj)); + } + } + return result; +} +/** + * Verifies equality for an array of objects using the `isEqual` interface. + * + * @private + * @internal + * @param left Array of objects supporting `isEqual`. + * @param right Array of objects supporting `isEqual`. + * @return True if arrays are equal. + */ +function isArrayEqual(left, right) { + if (left.length !== right.length) { + return false; + } + for (let i = 0; i < left.length; ++i) { + if (!left[i].isEqual(right[i])) { + return false; + } + } + return true; +} +/** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ +function isPrimitiveArrayEqual(left, right) { + if (left.length !== right.length) { + return false; + } + for (let i = 0; i < left.length; ++i) { + if (left[i] !== right[i]) { + return false; + } + } + return true; +} +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/v1/firestore_admin_client.d.ts b/node_modules/@google-cloud/firestore/build/src/v1/firestore_admin_client.d.ts new file mode 100644 index 0000000..4ddf8fe --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/v1/firestore_admin_client.d.ts @@ -0,0 +1,1625 @@ +import type * as gax from 'google-gax'; +import type { Callback, CallOptions, Descriptors, ClientOptions, LROperation, PaginationCallback, LocationsClient, LocationProtos } from 'google-gax'; +import { Transform } from 'stream'; +import * as protos from '../../protos/firestore_admin_v1_proto_api'; +/** + * The Cloud Firestore Admin API. + * + * This API provides several administrative services for Cloud Firestore. + * + * Project, Database, Namespace, Collection, Collection Group, and Document are + * used as defined in the Google Cloud Firestore API. + * + * Operation: An Operation represents work being performed in the background. + * + * The index service manages Cloud Firestore indexes. + * + * Index creation is performed asynchronously. + * An Operation resource is created for each such asynchronous operation. + * The state of the operation (including any errors encountered) + * may be queried via the Operation resource. + * + * The Operations collection provides a record of actions performed for the + * specified Project (including any Operations in progress). Operations are not + * created directly but through calls on other collections or resources. + * + * An Operation that is done may be deleted so that it is no longer listed as + * part of the Operation collection. Operations are garbage collected after + * 30 days. By default, ListOperations will only return in progress and failed + * operations. To list completed operation, issue a ListOperations request with + * the filter `done: true`. + * + * Operations are created by service `FirestoreAdmin`, but are accessed via + * service `google.longrunning.Operations`. + * @class + * @memberof v1 + */ +export declare class FirestoreAdminClient { + private _terminated; + private _opts; + private _providedCustomServicePath; + private _gaxModule; + private _gaxGrpc; + private _protos; + private _defaults; + private _universeDomain; + private _servicePath; + auth: gax.GoogleAuth; + descriptors: Descriptors; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: { + [name: string]: Function; + }; + locationsClient: LocationsClient; + pathTemplates: { + [name: string]: gax.PathTemplate; + }; + operationsClient: gax.OperationsClient; + firestoreAdminStub?: Promise<{ + [name: string]: Function; + }>; + /** + * Construct an instance of FirestoreAdminClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param {string} [options.apiEndpoint] - The domain name of the + * API remote host. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new FirestoreAdminClient({fallback: true}, gax); + * ``` + */ + constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback); + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize(): Promise<{ + [name: string]: Function; + }>; + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath(): string; + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint(): string; + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint(): string; + get universeDomain(): string; + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port(): number; + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes(): string[]; + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Gets a composite index. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Index|Index}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.get_index.js + * region_tag:firestore_v1_generated_FirestoreAdmin_GetIndex_async + */ + getIndex(request?: protos.google.firestore.admin.v1.IGetIndexRequest, options?: CallOptions): Promise<[ + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | undefined, + {} | undefined + ]>; + getIndex(request: protos.google.firestore.admin.v1.IGetIndexRequest, options: CallOptions, callback: Callback): void; + getIndex(request: protos.google.firestore.admin.v1.IGetIndexRequest, callback: Callback): void; + /** + * Deletes a composite index. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.delete_index.js + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteIndex_async + */ + deleteIndex(request?: protos.google.firestore.admin.v1.IDeleteIndexRequest, options?: CallOptions): Promise<[ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest | undefined, + {} | undefined + ]>; + deleteIndex(request: protos.google.firestore.admin.v1.IDeleteIndexRequest, options: CallOptions, callback: Callback): void; + deleteIndex(request: protos.google.firestore.admin.v1.IDeleteIndexRequest, callback: Callback): void; + /** + * Gets the metadata and configuration for a Field. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Field|Field}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.get_field.js + * region_tag:firestore_v1_generated_FirestoreAdmin_GetField_async + */ + getField(request?: protos.google.firestore.admin.v1.IGetFieldRequest, options?: CallOptions): Promise<[ + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | undefined, + {} | undefined + ]>; + getField(request: protos.google.firestore.admin.v1.IGetFieldRequest, options: CallOptions, callback: Callback): void; + getField(request: protos.google.firestore.admin.v1.IGetFieldRequest, callback: Callback): void; + /** + * Gets information about a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Database|Database}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.get_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_GetDatabase_async + */ + getDatabase(request?: protos.google.firestore.admin.v1.IGetDatabaseRequest, options?: CallOptions): Promise<[ + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest | undefined, + {} | undefined + ]>; + getDatabase(request: protos.google.firestore.admin.v1.IGetDatabaseRequest, options: CallOptions, callback: Callback): void; + getDatabase(request: protos.google.firestore.admin.v1.IGetDatabaseRequest, callback: Callback): void; + /** + * List all the databases in the project. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}` + * @param {boolean} request.showDeleted + * If true, also returns deleted resources. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListDatabasesResponse|ListDatabasesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.list_databases.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ListDatabases_async + */ + listDatabases(request?: protos.google.firestore.admin.v1.IListDatabasesRequest, options?: CallOptions): Promise<[ + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest | undefined, + {} | undefined + ]>; + listDatabases(request: protos.google.firestore.admin.v1.IListDatabasesRequest, options: CallOptions, callback: Callback): void; + listDatabases(request: protos.google.firestore.admin.v1.IListDatabasesRequest, callback: Callback): void; + /** + * Gets information about a backup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the backup to fetch. + * + * Format is `projects/{project}/locations/{location}/backups/{backup}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Backup|Backup}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.get_backup.js + * region_tag:firestore_v1_generated_FirestoreAdmin_GetBackup_async + */ + getBackup(request?: protos.google.firestore.admin.v1.IGetBackupRequest, options?: CallOptions): Promise<[ + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | undefined, + {} | undefined + ]>; + getBackup(request: protos.google.firestore.admin.v1.IGetBackupRequest, options: CallOptions, callback: Callback): void; + getBackup(request: protos.google.firestore.admin.v1.IGetBackupRequest, callback: Callback): void; + /** + * Lists all the backups. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The location to list backups from. + * + * Format is `projects/{project}/locations/{location}`. + * Use `{location} = '-'` to list backups from all locations for the given + * project. This allows listing backups from a single location or from all + * locations. + * @param {string} request.filter + * An expression that filters the list of returned backups. + * + * A filter expression consists of a field name, a comparison operator, and a + * value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the {@link protos.google.firestore.admin.v1.Backup|Backup} are + * eligible for filtering: + * + * * `database_uid` (supports `=` only) + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListBackupsResponse|ListBackupsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.list_backups.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ListBackups_async + */ + listBackups(request?: protos.google.firestore.admin.v1.IListBackupsRequest, options?: CallOptions): Promise<[ + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | undefined, + {} | undefined + ]>; + listBackups(request: protos.google.firestore.admin.v1.IListBackupsRequest, options: CallOptions, callback: Callback): void; + listBackups(request: protos.google.firestore.admin.v1.IListBackupsRequest, callback: Callback): void; + /** + * Deletes a backup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the backup to delete. + * + * format is `projects/{project}/locations/{location}/backups/{backup}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.delete_backup.js + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteBackup_async + */ + deleteBackup(request?: protos.google.firestore.admin.v1.IDeleteBackupRequest, options?: CallOptions): Promise<[ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | undefined, + {} | undefined + ]>; + deleteBackup(request: protos.google.firestore.admin.v1.IDeleteBackupRequest, options: CallOptions, callback: Callback): void; + deleteBackup(request: protos.google.firestore.admin.v1.IDeleteBackupRequest, callback: Callback): void; + /** + * Creates a backup schedule on a database. + * At most two backup schedules can be configured on a database, one daily + * backup schedule and one weekly backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent database. + * + * Format `projects/{project}/databases/{database}` + * @param {google.firestore.admin.v1.BackupSchedule} request.backupSchedule + * Required. The backup schedule to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.create_backup_schedule.js + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateBackupSchedule_async + */ + createBackupSchedule(request?: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, options?: CallOptions): Promise<[ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.ICreateBackupScheduleRequest | undefined, + {} | undefined + ]>; + createBackupSchedule(request: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, options: CallOptions, callback: Callback): void; + createBackupSchedule(request: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, callback: Callback): void; + /** + * Gets information about a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the backup schedule. + * + * Format + * `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.get_backup_schedule.js + * region_tag:firestore_v1_generated_FirestoreAdmin_GetBackupSchedule_async + */ + getBackupSchedule(request?: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, options?: CallOptions): Promise<[ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IGetBackupScheduleRequest | undefined, + {} | undefined + ]>; + getBackupSchedule(request: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, options: CallOptions, callback: Callback): void; + getBackupSchedule(request: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, callback: Callback): void; + /** + * List backup schedules. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent database. + * + * Format is `projects/{project}/databases/{database}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListBackupSchedulesResponse|ListBackupSchedulesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.list_backup_schedules.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ListBackupSchedules_async + */ + listBackupSchedules(request?: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, options?: CallOptions): Promise<[ + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + protos.google.firestore.admin.v1.IListBackupSchedulesRequest | undefined, + {} | undefined + ]>; + listBackupSchedules(request: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, options: CallOptions, callback: Callback): void; + listBackupSchedules(request: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, callback: Callback): void; + /** + * Updates a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.admin.v1.BackupSchedule} request.backupSchedule + * Required. The backup schedule to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The list of fields to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.update_backup_schedule.js + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateBackupSchedule_async + */ + updateBackupSchedule(request?: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, options?: CallOptions): Promise<[ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest | undefined, + {} | undefined + ]>; + updateBackupSchedule(request: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, options: CallOptions, callback: Callback): void; + updateBackupSchedule(request: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, callback: Callback): void; + /** + * Deletes a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the backup schedule. + * + * Format + * `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.delete_backup_schedule.js + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteBackupSchedule_async + */ + deleteBackupSchedule(request?: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, options?: CallOptions): Promise<[ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest | undefined, + {} | undefined + ]>; + deleteBackupSchedule(request: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, options: CallOptions, callback: Callback): void; + deleteBackupSchedule(request: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, callback: Callback): void; + /** + * Creates a composite index. This returns a + * {@link protos.google.longrunning.Operation|google.longrunning.Operation} which may be + * used to track the status of the creation. The metadata for the operation + * will be the type + * {@link protos.google.firestore.admin.v1.IndexOperationMetadata|IndexOperationMetadata}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {google.firestore.admin.v1.Index} request.index + * Required. The composite index to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.create_index.js + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateIndex_async + */ + createIndex(request?: protos.google.firestore.admin.v1.ICreateIndexRequest, options?: CallOptions): Promise<[ + LROperation, + protos.google.longrunning.IOperation | undefined, + {} | undefined + ]>; + createIndex(request: protos.google.firestore.admin.v1.ICreateIndexRequest, options: CallOptions, callback: Callback, protos.google.longrunning.IOperation | null | undefined, {} | null | undefined>): void; + createIndex(request: protos.google.firestore.admin.v1.ICreateIndexRequest, callback: Callback, protos.google.longrunning.IOperation | null | undefined, {} | null | undefined>): void; + /** + * Check the status of the long running operation returned by `createIndex()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.create_index.js + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateIndex_async + */ + checkCreateIndexProgress(name: string): Promise>; + /** + * Updates a field configuration. Currently, field updates apply only to + * single field index configuration. However, calls to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.UpdateField|FirestoreAdmin.UpdateField} + * should provide a field mask to avoid changing any configuration that the + * caller isn't aware of. The field mask should be specified as: `{ paths: + * "index_config" }`. + * + * This call returns a + * {@link protos.google.longrunning.Operation|google.longrunning.Operation} which may be + * used to track the status of the field update. The metadata for the + * operation will be the type + * {@link protos.google.firestore.admin.v1.FieldOperationMetadata|FieldOperationMetadata}. + * + * To configure the default field settings for the database, use + * the special `Field` with resource name: + * `projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/*`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.admin.v1.Field} request.field + * Required. The field to be updated. + * @param {google.protobuf.FieldMask} request.updateMask + * A mask, relative to the field. If specified, only configuration specified + * by this field_mask will be updated in the field. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.update_field.js + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateField_async + */ + updateField(request?: protos.google.firestore.admin.v1.IUpdateFieldRequest, options?: CallOptions): Promise<[ + LROperation, + protos.google.longrunning.IOperation | undefined, + {} | undefined + ]>; + updateField(request: protos.google.firestore.admin.v1.IUpdateFieldRequest, options: CallOptions, callback: Callback, protos.google.longrunning.IOperation | null | undefined, {} | null | undefined>): void; + updateField(request: protos.google.firestore.admin.v1.IUpdateFieldRequest, callback: Callback, protos.google.longrunning.IOperation | null | undefined, {} | null | undefined>): void; + /** + * Check the status of the long running operation returned by `updateField()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.update_field.js + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateField_async + */ + checkUpdateFieldProgress(name: string): Promise>; + /** + * Exports a copy of all or a subset of documents from Google Cloud Firestore + * to another storage system, such as Google Cloud Storage. Recent updates to + * documents may not be reflected in the export. The export occurs in the + * background and its progress can be monitored and managed via the + * Operation resource that is created. The output of an export may only be + * used once the associated operation is done. If an export operation is + * cancelled before completion it may leave partial data behind in Google + * Cloud Storage. + * + * For more details on export behavior and output format, refer to: + * https://cloud.google.com/firestore/docs/manage-data/export-import + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Database to export. Should be of the form: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.collectionIds + * Which collection IDs to export. Unspecified means all collections. Each + * collection ID in this list must be unique. + * @param {string} request.outputUriPrefix + * The output URI. Currently only supports Google Cloud Storage URIs of the + * form: `gs://BUCKET_NAME[/NAMESPACE_PATH]`, where `BUCKET_NAME` is the name + * of the Google Cloud Storage bucket and `NAMESPACE_PATH` is an optional + * Google Cloud Storage namespace path. When + * choosing a name, be sure to consider Google Cloud Storage naming + * guidelines: https://cloud.google.com/storage/docs/naming. + * If the URI is a bucket (without a namespace path), a prefix will be + * generated based on the start time. + * @param {string[]} request.namespaceIds + * An empty list represents all namespaces. This is the preferred + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to include them. Each namespace in this list must be unique. + * @param {google.protobuf.Timestamp} request.snapshotTime + * The timestamp that corresponds to the version of the database to be + * exported. The timestamp must be in the past, rounded to the minute and not + * older than + * {@link protos.google.firestore.admin.v1.Database.earliest_version_time|earliestVersionTime}. + * If specified, then the exported documents will represent a consistent view + * of the database at the provided time. Otherwise, there are no guarantees + * about the consistency of the exported documents. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.export_documents.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ExportDocuments_async + */ + exportDocuments(request?: protos.google.firestore.admin.v1.IExportDocumentsRequest, options?: CallOptions): Promise<[ + LROperation, + protos.google.longrunning.IOperation | undefined, + {} | undefined + ]>; + exportDocuments(request: protos.google.firestore.admin.v1.IExportDocumentsRequest, options: CallOptions, callback: Callback, protos.google.longrunning.IOperation | null | undefined, {} | null | undefined>): void; + exportDocuments(request: protos.google.firestore.admin.v1.IExportDocumentsRequest, callback: Callback, protos.google.longrunning.IOperation | null | undefined, {} | null | undefined>): void; + /** + * Check the status of the long running operation returned by `exportDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.export_documents.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ExportDocuments_async + */ + checkExportDocumentsProgress(name: string): Promise>; + /** + * Imports documents into Google Cloud Firestore. Existing documents with the + * same name are overwritten. The import occurs in the background and its + * progress can be monitored and managed via the Operation resource that is + * created. If an ImportDocuments operation is cancelled, it is possible + * that a subset of the data has already been imported to Cloud Firestore. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Database to import into. Should be of the form: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.collectionIds + * Which collection IDs to import. Unspecified means all collections included + * in the import. Each collection ID in this list must be unique. + * @param {string} request.inputUriPrefix + * Location of the exported files. + * This must match the output_uri_prefix of an ExportDocumentsResponse from + * an export that has completed successfully. + * See: + * {@link protos.google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix|google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix}. + * @param {string[]} request.namespaceIds + * An empty list represents all namespaces. This is the preferred + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to include them. Each namespace in this list must be unique. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.import_documents.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ImportDocuments_async + */ + importDocuments(request?: protos.google.firestore.admin.v1.IImportDocumentsRequest, options?: CallOptions): Promise<[ + LROperation, + protos.google.longrunning.IOperation | undefined, + {} | undefined + ]>; + importDocuments(request: protos.google.firestore.admin.v1.IImportDocumentsRequest, options: CallOptions, callback: Callback, protos.google.longrunning.IOperation | null | undefined, {} | null | undefined>): void; + importDocuments(request: protos.google.firestore.admin.v1.IImportDocumentsRequest, callback: Callback, protos.google.longrunning.IOperation | null | undefined, {} | null | undefined>): void; + /** + * Check the status of the long running operation returned by `importDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.import_documents.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ImportDocuments_async + */ + checkImportDocumentsProgress(name: string): Promise>; + /** + * Bulk deletes a subset of documents from Google Cloud Firestore. + * Documents created or updated after the underlying system starts to process + * the request will not be deleted. The bulk delete occurs in the background + * and its progress can be monitored and managed via the Operation resource + * that is created. + * + * For more details on bulk delete behavior, refer to: + * https://cloud.google.com/firestore/docs/manage-data/bulk-delete + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Database to operate. Should be of the form: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} [request.collectionIds] + * Optional. IDs of the collection groups to delete. Unspecified means all + * collection groups. + * + * Each collection group in this list must be unique. + * @param {string[]} [request.namespaceIds] + * Optional. Namespaces to delete. + * + * An empty list means all namespaces. This is the recommended + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to delete from them. + * + * Each namespace in this list must be unique. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.bulk_delete_documents.js + * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async + */ + bulkDeleteDocuments(request?: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, options?: CallOptions): Promise<[ + LROperation, + protos.google.longrunning.IOperation | undefined, + {} | undefined + ]>; + bulkDeleteDocuments(request: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, options: CallOptions, callback: Callback, protos.google.longrunning.IOperation | null | undefined, {} | null | undefined>): void; + bulkDeleteDocuments(request: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, callback: Callback, protos.google.longrunning.IOperation | null | undefined, {} | null | undefined>): void; + /** + * Check the status of the long running operation returned by `bulkDeleteDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.bulk_delete_documents.js + * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async + */ + checkBulkDeleteDocumentsProgress(name: string): Promise>; + /** + * Create a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}` + * @param {google.firestore.admin.v1.Database} request.database + * Required. The Database to create. + * @param {string} request.databaseId + * Required. The ID to use for the database, which will become the final + * component of the database's resource name. + * + * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ + * with first character a letter and the last a letter or a number. Must not + * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + * + * "(default)" database ID is also valid. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.create_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateDatabase_async + */ + createDatabase(request?: protos.google.firestore.admin.v1.ICreateDatabaseRequest, options?: CallOptions): Promise<[ + LROperation, + protos.google.longrunning.IOperation | undefined, + {} | undefined + ]>; + createDatabase(request: protos.google.firestore.admin.v1.ICreateDatabaseRequest, options: CallOptions, callback: Callback, protos.google.longrunning.IOperation | null | undefined, {} | null | undefined>): void; + createDatabase(request: protos.google.firestore.admin.v1.ICreateDatabaseRequest, callback: Callback, protos.google.longrunning.IOperation | null | undefined, {} | null | undefined>): void; + /** + * Check the status of the long running operation returned by `createDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.create_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateDatabase_async + */ + checkCreateDatabaseProgress(name: string): Promise>; + /** + * Updates a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.admin.v1.Database} request.database + * Required. The database to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The list of fields to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.update_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async + */ + updateDatabase(request?: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, options?: CallOptions): Promise<[ + LROperation, + protos.google.longrunning.IOperation | undefined, + {} | undefined + ]>; + updateDatabase(request: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, options: CallOptions, callback: Callback, protos.google.longrunning.IOperation | null | undefined, {} | null | undefined>): void; + updateDatabase(request: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, callback: Callback, protos.google.longrunning.IOperation | null | undefined, {} | null | undefined>): void; + /** + * Check the status of the long running operation returned by `updateDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.update_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async + */ + checkUpdateDatabaseProgress(name: string): Promise>; + /** + * Deletes a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}` + * @param {string} request.etag + * The current etag of the Database. + * If an etag is provided and does not match the current etag of the database, + * deletion will be blocked and a FAILED_PRECONDITION error will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.delete_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteDatabase_async + */ + deleteDatabase(request?: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, options?: CallOptions): Promise<[ + LROperation, + protos.google.longrunning.IOperation | undefined, + {} | undefined + ]>; + deleteDatabase(request: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, options: CallOptions, callback: Callback, protos.google.longrunning.IOperation | null | undefined, {} | null | undefined>): void; + deleteDatabase(request: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, callback: Callback, protos.google.longrunning.IOperation | null | undefined, {} | null | undefined>): void; + /** + * Check the status of the long running operation returned by `deleteDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.delete_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteDatabase_async + */ + checkDeleteDatabaseProgress(name: string): Promise>; + /** + * Creates a new database by restoring from an existing backup. + * + * The new database must be in the same cloud region or multi-region location + * as the existing backup. This behaves similar to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.CreateDatabase|FirestoreAdmin.CreateDatabase} + * except instead of creating a new empty database, a new database is created + * with the database type, index configuration, and documents from an existing + * backup. + * + * The {@link protos.google.longrunning.Operation|long-running operation} can be used to + * track the progress of the restore, with the Operation's + * {@link protos.google.longrunning.Operation.metadata|metadata} field type being the + * {@link protos.google.firestore.admin.v1.RestoreDatabaseMetadata|RestoreDatabaseMetadata}. + * The {@link protos.google.longrunning.Operation.response|response} type is the + * {@link protos.google.firestore.admin.v1.Database|Database} if the restore was + * successful. The new database is not readable or writeable until the LRO has + * completed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project to restore the database in. Format is + * `projects/{project_id}`. + * @param {string} request.databaseId + * Required. The ID to use for the database, which will become the final + * component of the database's resource name. This database ID must not be + * associated with an existing database. + * + * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ + * with first character a letter and the last a letter or a number. Must not + * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + * + * "(default)" database ID is also valid. + * @param {string} request.backup + * Required. Backup to restore from. Must be from the same project as the + * parent. + * + * The restored database will be created in the same location as the source + * backup. + * + * Format is: `projects/{project_id}/locations/{location}/backups/{backup}` + * @param {google.firestore.admin.v1.Database.EncryptionConfig} [request.encryptionConfig] + * Optional. Encryption configuration for the restored database. + * + * If this field is not specified, the restored database will use + * the same encryption configuration as the backup, namely + * {@link protos.google.firestore.admin.v1.Database.EncryptionConfig.use_source_encryption|use_source_encryption}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.restore_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_RestoreDatabase_async + */ + restoreDatabase(request?: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, options?: CallOptions): Promise<[ + LROperation, + protos.google.longrunning.IOperation | undefined, + {} | undefined + ]>; + restoreDatabase(request: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, options: CallOptions, callback: Callback, protos.google.longrunning.IOperation | null | undefined, {} | null | undefined>): void; + restoreDatabase(request: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, callback: Callback, protos.google.longrunning.IOperation | null | undefined, {} | null | undefined>): void; + /** + * Check the status of the long running operation returned by `restoreDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.restore_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_RestoreDatabase_async + */ + checkRestoreDatabaseProgress(name: string): Promise>; + /** + * Lists composite indexes. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.admin.v1.Index|Index}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listIndexesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listIndexes(request?: protos.google.firestore.admin.v1.IListIndexesRequest, options?: CallOptions): Promise<[ + protos.google.firestore.admin.v1.IIndex[], + protos.google.firestore.admin.v1.IListIndexesRequest | null, + protos.google.firestore.admin.v1.IListIndexesResponse + ]>; + listIndexes(request: protos.google.firestore.admin.v1.IListIndexesRequest, options: CallOptions, callback: PaginationCallback): void; + listIndexes(request: protos.google.firestore.admin.v1.IListIndexesRequest, callback: PaginationCallback): void; + /** + * Equivalent to `listIndexes`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.admin.v1.Index|Index} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listIndexesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listIndexesStream(request?: protos.google.firestore.admin.v1.IListIndexesRequest, options?: CallOptions): Transform; + /** + * Equivalent to `listIndexes`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.admin.v1.Index|Index}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.list_indexes.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ListIndexes_async + */ + listIndexesAsync(request?: protos.google.firestore.admin.v1.IListIndexesRequest, options?: CallOptions): AsyncIterable; + /** + * Lists the field configuration and metadata for this database. + * + * Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with the filter set to `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.admin.v1.Field|Field}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listFieldsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listFields(request?: protos.google.firestore.admin.v1.IListFieldsRequest, options?: CallOptions): Promise<[ + protos.google.firestore.admin.v1.IField[], + protos.google.firestore.admin.v1.IListFieldsRequest | null, + protos.google.firestore.admin.v1.IListFieldsResponse + ]>; + listFields(request: protos.google.firestore.admin.v1.IListFieldsRequest, options: CallOptions, callback: PaginationCallback): void; + listFields(request: protos.google.firestore.admin.v1.IListFieldsRequest, callback: PaginationCallback): void; + /** + * Equivalent to `listFields`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.admin.v1.Field|Field} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listFieldsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listFieldsStream(request?: protos.google.firestore.admin.v1.IListFieldsRequest, options?: CallOptions): Transform; + /** + * Equivalent to `listFields`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.admin.v1.Field|Field}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.list_fields.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ListFields_async + */ + listFieldsAsync(request?: protos.google.firestore.admin.v1.IListFieldsRequest, options?: CallOptions): AsyncIterable; + /** + * Gets information about a location. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Resource name for the location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html | CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.cloud.location.Location | Location}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * ``` + * const [response] = await client.getLocation(request); + * ``` + */ + getLocation(request: LocationProtos.google.cloud.location.IGetLocationRequest, options?: gax.CallOptions | Callback, callback?: Callback): Promise; + /** + * Lists information about the supported locations for this service. Returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource that owns the locations collection, if applicable. + * @param {string} request.filter + * The standard list filter. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link google.cloud.location.Location | Location}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * ``` + * const iterable = client.listLocationsAsync(request); + * for await (const response of iterable) { + * // process response + * } + * ``` + */ + listLocationsAsync(request: LocationProtos.google.cloud.location.IListLocationsRequest, options?: CallOptions): AsyncIterable; + /** + * Gets the latest state of a long-running operation. Clients can use this + * method to poll the operation result at intervals as recommended by the API + * service. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} + * for the details. + * @param {function(?Error, ?Object)=} callback + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing + * {@link google.longrunning.Operation | google.longrunning.Operation}. + * @return {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * {@link google.longrunning.Operation | google.longrunning.Operation}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * const name = ''; + * const [response] = await client.getOperation({name}); + * // doThingsWith(response) + * ``` + */ + getOperation(request: protos.google.longrunning.GetOperationRequest, optionsOrCallback?: gax.CallOptions | Callback, callback?: Callback): Promise<[protos.google.longrunning.Operation]>; + /** + * Lists operations that match the specified filter in the request. If the + * server doesn't support this method, it returns `UNIMPLEMENTED`. Returns an iterable object. + * + * For-await-of syntax is used with the iterable to recursively get response element on-demand. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation collection. + * @param {string} request.filter - The standard list filter. + * @param {number=} request.pageSize - + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} for the + * details. + * @returns {Object} + * An iterable Object that conforms to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | iteration protocols}. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * for await (const response of client.listOperationsAsync(request)); + * // doThingsWith(response) + * ``` + */ + listOperationsAsync(request: protos.google.longrunning.ListOperationsRequest, options?: gax.CallOptions): AsyncIterable; + /** + * Starts asynchronous cancellation on a long-running operation. The server + * makes a best effort to cancel the operation, but success is not + * guaranteed. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. Clients can use + * {@link Operations.GetOperation} or + * other methods to check whether the cancellation succeeded or whether the + * operation completed despite cancellation. On successful cancellation, + * the operation is not deleted; instead, it becomes an operation with + * an {@link Operation.error} value with a {@link google.rpc.Status.code} of + * 1, corresponding to `Code.CANCELLED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be cancelled. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} for the + * details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @return {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * await client.cancelOperation({name: ''}); + * ``` + */ + cancelOperation(request: protos.google.longrunning.CancelOperationRequest, optionsOrCallback?: gax.CallOptions | Callback, callback?: Callback): Promise; + /** + * Deletes a long-running operation. This method indicates that the client is + * no longer interested in the operation result. It does not cancel the + * operation. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be deleted. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} + * for the details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @return {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * await client.deleteOperation({name: ''}); + * ``` + */ + deleteOperation(request: protos.google.longrunning.DeleteOperationRequest, optionsOrCallback?: gax.CallOptions | Callback, callback?: Callback): Promise; + /** + * Return a fully-qualified backup resource name string. + * + * @param {string} project + * @param {string} location + * @param {string} backup + * @returns {string} Resource name string. + */ + backupPath(project: string, location: string, backup: string): string; + /** + * Parse the project from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the project. + */ + matchProjectFromBackupName(backupName: string): string | number; + /** + * Parse the location from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the location. + */ + matchLocationFromBackupName(backupName: string): string | number; + /** + * Parse the backup from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the backup. + */ + matchBackupFromBackupName(backupName: string): string | number; + /** + * Return a fully-qualified backupSchedule resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} backup_schedule + * @returns {string} Resource name string. + */ + backupSchedulePath(project: string, database: string, backupSchedule: string): string; + /** + * Parse the project from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the project. + */ + matchProjectFromBackupScheduleName(backupScheduleName: string): string | number; + /** + * Parse the database from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromBackupScheduleName(backupScheduleName: string): string | number; + /** + * Parse the backup_schedule from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the backup_schedule. + */ + matchBackupScheduleFromBackupScheduleName(backupScheduleName: string): string | number; + /** + * Return a fully-qualified collectionGroup resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} collection + * @returns {string} Resource name string. + */ + collectionGroupPath(project: string, database: string, collection: string): string; + /** + * Parse the project from CollectionGroup resource. + * + * @param {string} collectionGroupName + * A fully-qualified path representing CollectionGroup resource. + * @returns {string} A string representing the project. + */ + matchProjectFromCollectionGroupName(collectionGroupName: string): string | number; + /** + * Parse the database from CollectionGroup resource. + * + * @param {string} collectionGroupName + * A fully-qualified path representing CollectionGroup resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromCollectionGroupName(collectionGroupName: string): string | number; + /** + * Parse the collection from CollectionGroup resource. + * + * @param {string} collectionGroupName + * A fully-qualified path representing CollectionGroup resource. + * @returns {string} A string representing the collection. + */ + matchCollectionFromCollectionGroupName(collectionGroupName: string): string | number; + /** + * Return a fully-qualified database resource name string. + * + * @param {string} project + * @param {string} database + * @returns {string} Resource name string. + */ + databasePath(project: string, database: string): string; + /** + * Parse the project from Database resource. + * + * @param {string} databaseName + * A fully-qualified path representing Database resource. + * @returns {string} A string representing the project. + */ + matchProjectFromDatabaseName(databaseName: string): string | number; + /** + * Parse the database from Database resource. + * + * @param {string} databaseName + * A fully-qualified path representing Database resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromDatabaseName(databaseName: string): string | number; + /** + * Return a fully-qualified field resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} collection + * @param {string} field + * @returns {string} Resource name string. + */ + fieldPath(project: string, database: string, collection: string, field: string): string; + /** + * Parse the project from Field resource. + * + * @param {string} fieldName + * A fully-qualified path representing Field resource. + * @returns {string} A string representing the project. + */ + matchProjectFromFieldName(fieldName: string): string | number; + /** + * Parse the database from Field resource. + * + * @param {string} fieldName + * A fully-qualified path representing Field resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromFieldName(fieldName: string): string | number; + /** + * Parse the collection from Field resource. + * + * @param {string} fieldName + * A fully-qualified path representing Field resource. + * @returns {string} A string representing the collection. + */ + matchCollectionFromFieldName(fieldName: string): string | number; + /** + * Parse the field from Field resource. + * + * @param {string} fieldName + * A fully-qualified path representing Field resource. + * @returns {string} A string representing the field. + */ + matchFieldFromFieldName(fieldName: string): string | number; + /** + * Return a fully-qualified index resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} collection + * @param {string} index + * @returns {string} Resource name string. + */ + indexPath(project: string, database: string, collection: string, index: string): string; + /** + * Parse the project from Index resource. + * + * @param {string} indexName + * A fully-qualified path representing Index resource. + * @returns {string} A string representing the project. + */ + matchProjectFromIndexName(indexName: string): string | number; + /** + * Parse the database from Index resource. + * + * @param {string} indexName + * A fully-qualified path representing Index resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromIndexName(indexName: string): string | number; + /** + * Parse the collection from Index resource. + * + * @param {string} indexName + * A fully-qualified path representing Index resource. + * @returns {string} A string representing the collection. + */ + matchCollectionFromIndexName(indexName: string): string | number; + /** + * Parse the index from Index resource. + * + * @param {string} indexName + * A fully-qualified path representing Index resource. + * @returns {string} A string representing the index. + */ + matchIndexFromIndexName(indexName: string): string | number; + /** + * Return a fully-qualified location resource name string. + * + * @param {string} project + * @param {string} location + * @returns {string} Resource name string. + */ + locationPath(project: string, location: string): string; + /** + * Parse the project from Location resource. + * + * @param {string} locationName + * A fully-qualified path representing Location resource. + * @returns {string} A string representing the project. + */ + matchProjectFromLocationName(locationName: string): string | number; + /** + * Parse the location from Location resource. + * + * @param {string} locationName + * A fully-qualified path representing Location resource. + * @returns {string} A string representing the location. + */ + matchLocationFromLocationName(locationName: string): string | number; + /** + * Return a fully-qualified project resource name string. + * + * @param {string} project + * @returns {string} Resource name string. + */ + projectPath(project: string): string; + /** + * Parse the project from Project resource. + * + * @param {string} projectName + * A fully-qualified path representing Project resource. + * @returns {string} A string representing the project. + */ + matchProjectFromProjectName(projectName: string): string | number; + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise; +} diff --git a/node_modules/@google-cloud/firestore/build/src/v1/firestore_admin_client.js b/node_modules/@google-cloud/firestore/build/src/v1/firestore_admin_client.js new file mode 100644 index 0000000..bb4b429 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/v1/firestore_admin_client.js @@ -0,0 +1,1833 @@ +"use strict"; +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirestoreAdminClient = void 0; +const jsonProtos = require("../../protos/admin_v1.json"); +/** + * Client JSON configuration object, loaded from + * `src/v1/firestore_admin_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +const gapicConfig = require("./firestore_admin_client_config.json"); +const version = require('../../../package.json').version; +/** + * The Cloud Firestore Admin API. + * + * This API provides several administrative services for Cloud Firestore. + * + * Project, Database, Namespace, Collection, Collection Group, and Document are + * used as defined in the Google Cloud Firestore API. + * + * Operation: An Operation represents work being performed in the background. + * + * The index service manages Cloud Firestore indexes. + * + * Index creation is performed asynchronously. + * An Operation resource is created for each such asynchronous operation. + * The state of the operation (including any errors encountered) + * may be queried via the Operation resource. + * + * The Operations collection provides a record of actions performed for the + * specified Project (including any Operations in progress). Operations are not + * created directly but through calls on other collections or resources. + * + * An Operation that is done may be deleted so that it is no longer listed as + * part of the Operation collection. Operations are garbage collected after + * 30 days. By default, ListOperations will only return in progress and failed + * operations. To list completed operation, issue a ListOperations request with + * the filter `done: true`. + * + * Operations are created by service `FirestoreAdmin`, but are accessed via + * service `google.longrunning.Operations`. + * @class + * @memberof v1 + */ +class FirestoreAdminClient { + /** + * Construct an instance of FirestoreAdminClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param {string} [options.apiEndpoint] - The domain name of the + * API remote host. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new FirestoreAdminClient({fallback: true}, gax); + * ``` + */ + constructor(opts, gaxInstance) { + var _a, _b, _c, _d, _e; + this._terminated = false; + this.descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + // Ensure that options include all the required fields. + const staticMembers = this.constructor; + if ((opts === null || opts === void 0 ? void 0 : opts.universe_domain) && + (opts === null || opts === void 0 ? void 0 : opts.universeDomain) && + (opts === null || opts === void 0 ? void 0 : opts.universe_domain) !== (opts === null || opts === void 0 ? void 0 : opts.universeDomain)) { + throw new Error('Please set either universe_domain or universeDomain, but not both.'); + } + const universeDomainEnvVar = typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + (_c = (_b = (_a = opts === null || opts === void 0 ? void 0 : opts.universeDomain) !== null && _a !== void 0 ? _a : opts === null || opts === void 0 ? void 0 : opts.universe_domain) !== null && _b !== void 0 ? _b : universeDomainEnvVar) !== null && _c !== void 0 ? _c : 'googleapis.com'; + this._servicePath = 'firestore.' + this._universeDomain; + const servicePath = (opts === null || opts === void 0 ? void 0 : opts.servicePath) || (opts === null || opts === void 0 ? void 0 : opts.apiEndpoint) || this._servicePath; + this._providedCustomServicePath = !!((opts === null || opts === void 0 ? void 0 : opts.servicePath) || (opts === null || opts === void 0 ? void 0 : opts.apiEndpoint)); + const port = (opts === null || opts === void 0 ? void 0 : opts.port) || staticMembers.port; + const clientConfig = (_d = opts === null || opts === void 0 ? void 0 : opts.clientConfig) !== null && _d !== void 0 ? _d : {}; + const fallback = (_e = opts === null || opts === void 0 ? void 0 : opts.fallback) !== null && _e !== void 0 ? _e : (typeof window !== 'undefined' && typeof (window === null || window === void 0 ? void 0 : window.fetch) === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); + // Request numeric enum values if REST transport is used. + opts.numericEnums = true; + // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. + if (servicePath !== this._servicePath && !('scopes' in opts)) { + opts['scopes'] = staticMembers.scopes; + } + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax'); + } + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + // Save options to use in initialize() method. + this._opts = opts; + // Save the auth object to the client, for use by other methods. + this.auth = this._gaxGrpc.auth; + // Set useJWTAccessWithScope on the auth object. + this.auth.useJWTAccessWithScope = true; + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + this.locationsClient = new this._gaxModule.LocationsClient(this._gaxGrpc, opts); + // Determine the client header string. + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } + else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } + else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + // This API contains "path templates"; forward-slash-separated + // identifiers to uniquely identify resources within the API. + // Create useful helper objects for these. + this.pathTemplates = { + backupPathTemplate: new this._gaxModule.PathTemplate('projects/{project}/locations/{location}/backups/{backup}'), + backupSchedulePathTemplate: new this._gaxModule.PathTemplate('projects/{project}/databases/{database}/backupSchedules/{backup_schedule}'), + collectionGroupPathTemplate: new this._gaxModule.PathTemplate('projects/{project}/databases/{database}/collectionGroups/{collection}'), + databasePathTemplate: new this._gaxModule.PathTemplate('projects/{project}/databases/{database}'), + fieldPathTemplate: new this._gaxModule.PathTemplate('projects/{project}/databases/{database}/collectionGroups/{collection}/fields/{field}'), + indexPathTemplate: new this._gaxModule.PathTemplate('projects/{project}/databases/{database}/collectionGroups/{collection}/indexes/{index}'), + locationPathTemplate: new this._gaxModule.PathTemplate('projects/{project}/locations/{location}'), + projectPathTemplate: new this._gaxModule.PathTemplate('projects/{project}'), + }; + // Some of the methods on this service return "paged" results, + // (e.g. 50 results at a time, with tokens to get subsequent + // pages). Denote the keys used for pagination and results. + this.descriptors.page = { + listIndexes: new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'indexes'), + listFields: new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'fields'), + }; + const protoFilesRoot = this._gaxModule.protobuf.Root.fromJSON(jsonProtos); + // This API contains "long-running operations", which return a + // an Operation object that allows for tracking of the operation, + // rather than holding a request open. + const lroOptions = { + auth: this.auth, + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, + }; + if (opts.fallback) { + lroOptions.protoJson = protoFilesRoot; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.CancelOperation', + post: '/v1/{name=projects/*/databases/*/operations/*}:cancel', + body: '*', + }, + { + selector: 'google.longrunning.Operations.DeleteOperation', + delete: '/v1/{name=projects/*/databases/*/operations/*}', + }, + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v1/{name=projects/*/databases/*/operations/*}', + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v1/{name=projects/*/databases/*}/operations', + }, + ]; + } + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); + const createIndexResponse = protoFilesRoot.lookup('.google.firestore.admin.v1.Index'); + const createIndexMetadata = protoFilesRoot.lookup('.google.firestore.admin.v1.IndexOperationMetadata'); + const updateFieldResponse = protoFilesRoot.lookup('.google.firestore.admin.v1.Field'); + const updateFieldMetadata = protoFilesRoot.lookup('.google.firestore.admin.v1.FieldOperationMetadata'); + const exportDocumentsResponse = protoFilesRoot.lookup('.google.firestore.admin.v1.ExportDocumentsResponse'); + const exportDocumentsMetadata = protoFilesRoot.lookup('.google.firestore.admin.v1.ExportDocumentsMetadata'); + const importDocumentsResponse = protoFilesRoot.lookup('.google.protobuf.Empty'); + const importDocumentsMetadata = protoFilesRoot.lookup('.google.firestore.admin.v1.ImportDocumentsMetadata'); + const bulkDeleteDocumentsResponse = protoFilesRoot.lookup('.google.firestore.admin.v1.BulkDeleteDocumentsResponse'); + const bulkDeleteDocumentsMetadata = protoFilesRoot.lookup('.google.firestore.admin.v1.BulkDeleteDocumentsMetadata'); + const createDatabaseResponse = protoFilesRoot.lookup('.google.firestore.admin.v1.Database'); + const createDatabaseMetadata = protoFilesRoot.lookup('.google.firestore.admin.v1.CreateDatabaseMetadata'); + const updateDatabaseResponse = protoFilesRoot.lookup('.google.firestore.admin.v1.Database'); + const updateDatabaseMetadata = protoFilesRoot.lookup('.google.firestore.admin.v1.UpdateDatabaseMetadata'); + const deleteDatabaseResponse = protoFilesRoot.lookup('.google.firestore.admin.v1.Database'); + const deleteDatabaseMetadata = protoFilesRoot.lookup('.google.firestore.admin.v1.DeleteDatabaseMetadata'); + const restoreDatabaseResponse = protoFilesRoot.lookup('.google.firestore.admin.v1.Database'); + const restoreDatabaseMetadata = protoFilesRoot.lookup('.google.firestore.admin.v1.RestoreDatabaseMetadata'); + this.descriptors.longrunning = { + createIndex: new this._gaxModule.LongrunningDescriptor(this.operationsClient, createIndexResponse.decode.bind(createIndexResponse), createIndexMetadata.decode.bind(createIndexMetadata)), + updateField: new this._gaxModule.LongrunningDescriptor(this.operationsClient, updateFieldResponse.decode.bind(updateFieldResponse), updateFieldMetadata.decode.bind(updateFieldMetadata)), + exportDocuments: new this._gaxModule.LongrunningDescriptor(this.operationsClient, exportDocumentsResponse.decode.bind(exportDocumentsResponse), exportDocumentsMetadata.decode.bind(exportDocumentsMetadata)), + importDocuments: new this._gaxModule.LongrunningDescriptor(this.operationsClient, importDocumentsResponse.decode.bind(importDocumentsResponse), importDocumentsMetadata.decode.bind(importDocumentsMetadata)), + bulkDeleteDocuments: new this._gaxModule.LongrunningDescriptor(this.operationsClient, bulkDeleteDocumentsResponse.decode.bind(bulkDeleteDocumentsResponse), bulkDeleteDocumentsMetadata.decode.bind(bulkDeleteDocumentsMetadata)), + createDatabase: new this._gaxModule.LongrunningDescriptor(this.operationsClient, createDatabaseResponse.decode.bind(createDatabaseResponse), createDatabaseMetadata.decode.bind(createDatabaseMetadata)), + updateDatabase: new this._gaxModule.LongrunningDescriptor(this.operationsClient, updateDatabaseResponse.decode.bind(updateDatabaseResponse), updateDatabaseMetadata.decode.bind(updateDatabaseMetadata)), + deleteDatabase: new this._gaxModule.LongrunningDescriptor(this.operationsClient, deleteDatabaseResponse.decode.bind(deleteDatabaseResponse), deleteDatabaseMetadata.decode.bind(deleteDatabaseMetadata)), + restoreDatabase: new this._gaxModule.LongrunningDescriptor(this.operationsClient, restoreDatabaseResponse.decode.bind(restoreDatabaseResponse), restoreDatabaseMetadata.decode.bind(restoreDatabaseMetadata)), + }; + // Put together the default options sent with requests. + this._defaults = this._gaxGrpc.constructSettings('google.firestore.admin.v1.FirestoreAdmin', gapicConfig, opts.clientConfig || {}, { 'x-goog-api-client': clientHeader.join(' ') }); + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.firestoreAdminStub) { + return this.firestoreAdminStub; + } + // Put together the "service stub" for + // google.firestore.admin.v1.FirestoreAdmin. + this.firestoreAdminStub = this._gaxGrpc.createStub(this._opts.fallback + ? this._protos.lookupService('google.firestore.admin.v1.FirestoreAdmin') + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._protos.google.firestore.admin.v1.FirestoreAdmin, this._opts, this._providedCustomServicePath); + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const firestoreAdminStubMethods = [ + 'createIndex', + 'listIndexes', + 'getIndex', + 'deleteIndex', + 'getField', + 'updateField', + 'listFields', + 'exportDocuments', + 'importDocuments', + 'bulkDeleteDocuments', + 'createDatabase', + 'getDatabase', + 'listDatabases', + 'updateDatabase', + 'deleteDatabase', + 'getBackup', + 'listBackups', + 'deleteBackup', + 'restoreDatabase', + 'createBackupSchedule', + 'getBackupSchedule', + 'listBackupSchedules', + 'updateBackupSchedule', + 'deleteBackupSchedule', + ]; + for (const methodName of firestoreAdminStubMethods) { + const callPromise = this.firestoreAdminStub.then(stub => (...args) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, (err) => () => { + throw err; + }); + const descriptor = this.descriptors.page[methodName] || + this.descriptors.longrunning[methodName] || + undefined; + const apiCall = this._gaxModule.createApiCall(callPromise, this._defaults[methodName], descriptor, this._opts.fallback); + this.innerApiCalls[methodName] = apiCall; + } + return this.firestoreAdminStub; + } + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath() { + if (typeof process === 'object' && + typeof process.emitWarning === 'function') { + process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'firestore.googleapis.com'; + } + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint() { + if (typeof process === 'object' && + typeof process.emitWarning === 'function') { + process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'firestore.googleapis.com'; + } + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + get universeDomain() { + return this._universeDomain; + } + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/datastore', + ]; + } + /** + * Return the project ID used by this class. + * @returns {Promise} A promise that resolves to string containing the project ID. + */ + getProjectId(callback) { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + getIndex(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: (_a = request.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.getIndex(request, options, callback); + } + deleteIndex(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: (_a = request.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.deleteIndex(request, options, callback); + } + getField(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: (_a = request.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.getField(request, options, callback); + } + getDatabase(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: (_a = request.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.getDatabase(request, options, callback); + } + listDatabases(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.listDatabases(request, options, callback); + } + getBackup(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: (_a = request.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.getBackup(request, options, callback); + } + listBackups(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.listBackups(request, options, callback); + } + deleteBackup(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: (_a = request.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.deleteBackup(request, options, callback); + } + createBackupSchedule(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.createBackupSchedule(request, options, callback); + } + getBackupSchedule(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: (_a = request.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.getBackupSchedule(request, options, callback); + } + listBackupSchedules(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.listBackupSchedules(request, options, callback); + } + updateBackupSchedule(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'backup_schedule.name': (_a = request.backupSchedule.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.updateBackupSchedule(request, options, callback); + } + deleteBackupSchedule(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: (_a = request.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.deleteBackupSchedule(request, options, callback); + } + createIndex(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.createIndex(request, options, callback); + } + /** + * Check the status of the long running operation returned by `createIndex()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.create_index.js + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateIndex_async + */ + async checkCreateIndexProgress(name) { + const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({ name }); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.createIndex, this._gaxModule.createDefaultBackoffSettings()); + return decodeOperation; + } + updateField(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'field.name': (_a = request.field.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.updateField(request, options, callback); + } + /** + * Check the status of the long running operation returned by `updateField()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.update_field.js + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateField_async + */ + async checkUpdateFieldProgress(name) { + const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({ name }); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.updateField, this._gaxModule.createDefaultBackoffSettings()); + return decodeOperation; + } + exportDocuments(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: (_a = request.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.exportDocuments(request, options, callback); + } + /** + * Check the status of the long running operation returned by `exportDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.export_documents.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ExportDocuments_async + */ + async checkExportDocumentsProgress(name) { + const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({ name }); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.exportDocuments, this._gaxModule.createDefaultBackoffSettings()); + return decodeOperation; + } + importDocuments(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: (_a = request.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.importDocuments(request, options, callback); + } + /** + * Check the status of the long running operation returned by `importDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.import_documents.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ImportDocuments_async + */ + async checkImportDocumentsProgress(name) { + const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({ name }); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.importDocuments, this._gaxModule.createDefaultBackoffSettings()); + return decodeOperation; + } + bulkDeleteDocuments(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: (_a = request.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.bulkDeleteDocuments(request, options, callback); + } + /** + * Check the status of the long running operation returned by `bulkDeleteDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.bulk_delete_documents.js + * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async + */ + async checkBulkDeleteDocumentsProgress(name) { + const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({ name }); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.bulkDeleteDocuments, this._gaxModule.createDefaultBackoffSettings()); + return decodeOperation; + } + createDatabase(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.createDatabase(request, options, callback); + } + /** + * Check the status of the long running operation returned by `createDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.create_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateDatabase_async + */ + async checkCreateDatabaseProgress(name) { + const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({ name }); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.createDatabase, this._gaxModule.createDefaultBackoffSettings()); + return decodeOperation; + } + updateDatabase(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'database.name': (_a = request.database.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.updateDatabase(request, options, callback); + } + /** + * Check the status of the long running operation returned by `updateDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.update_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async + */ + async checkUpdateDatabaseProgress(name) { + const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({ name }); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.updateDatabase, this._gaxModule.createDefaultBackoffSettings()); + return decodeOperation; + } + deleteDatabase(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: (_a = request.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.deleteDatabase(request, options, callback); + } + /** + * Check the status of the long running operation returned by `deleteDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.delete_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteDatabase_async + */ + async checkDeleteDatabaseProgress(name) { + const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({ name }); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.deleteDatabase, this._gaxModule.createDefaultBackoffSettings()); + return decodeOperation; + } + restoreDatabase(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.restoreDatabase(request, options, callback); + } + /** + * Check the status of the long running operation returned by `restoreDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.restore_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_RestoreDatabase_async + */ + async checkRestoreDatabaseProgress(name) { + const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({ name }); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.restoreDatabase, this._gaxModule.createDefaultBackoffSettings()); + return decodeOperation; + } + listIndexes(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.listIndexes(request, options, callback); + } + /** + * Equivalent to `listIndexes`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.admin.v1.Index|Index} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listIndexesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listIndexesStream(request, options) { + var _a; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + const defaultCallSettings = this._defaults['listIndexes']; + const callSettings = defaultCallSettings.merge(options); + this.initialize(); + return this.descriptors.page.listIndexes.createStream(this.innerApiCalls.listIndexes, request, callSettings); + } + /** + * Equivalent to `listIndexes`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.admin.v1.Index|Index}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.list_indexes.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ListIndexes_async + */ + listIndexesAsync(request, options) { + var _a; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + const defaultCallSettings = this._defaults['listIndexes']; + const callSettings = defaultCallSettings.merge(options); + this.initialize(); + return this.descriptors.page.listIndexes.asyncIterate(this.innerApiCalls['listIndexes'], request, callSettings); + } + listFields(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.listFields(request, options, callback); + } + /** + * Equivalent to `listFields`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.admin.v1.Field|Field} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listFieldsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listFieldsStream(request, options) { + var _a; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + const defaultCallSettings = this._defaults['listFields']; + const callSettings = defaultCallSettings.merge(options); + this.initialize(); + return this.descriptors.page.listFields.createStream(this.innerApiCalls.listFields, request, callSettings); + } + /** + * Equivalent to `listFields`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.admin.v1.Field|Field}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.list_fields.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ListFields_async + */ + listFieldsAsync(request, options) { + var _a; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + const defaultCallSettings = this._defaults['listFields']; + const callSettings = defaultCallSettings.merge(options); + this.initialize(); + return this.descriptors.page.listFields.asyncIterate(this.innerApiCalls['listFields'], request, callSettings); + } + /** + * Gets information about a location. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Resource name for the location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html | CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.cloud.location.Location | Location}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * ``` + * const [response] = await client.getLocation(request); + * ``` + */ + getLocation(request, options, callback) { + return this.locationsClient.getLocation(request, options, callback); + } + /** + * Lists information about the supported locations for this service. Returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource that owns the locations collection, if applicable. + * @param {string} request.filter + * The standard list filter. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link google.cloud.location.Location | Location}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * ``` + * const iterable = client.listLocationsAsync(request); + * for await (const response of iterable) { + * // process response + * } + * ``` + */ + listLocationsAsync(request, options) { + return this.locationsClient.listLocationsAsync(request, options); + } + /** + * Gets the latest state of a long-running operation. Clients can use this + * method to poll the operation result at intervals as recommended by the API + * service. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} + * for the details. + * @param {function(?Error, ?Object)=} callback + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing + * {@link google.longrunning.Operation | google.longrunning.Operation}. + * @return {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * {@link google.longrunning.Operation | google.longrunning.Operation}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * const name = ''; + * const [response] = await client.getOperation({name}); + * // doThingsWith(response) + * ``` + */ + getOperation(request, optionsOrCallback, callback) { + var _a; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: (_a = request.name) !== null && _a !== void 0 ? _a : '', + }); + return this.operationsClient.getOperation(request, options, callback); + } + /** + * Lists operations that match the specified filter in the request. If the + * server doesn't support this method, it returns `UNIMPLEMENTED`. Returns an iterable object. + * + * For-await-of syntax is used with the iterable to recursively get response element on-demand. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation collection. + * @param {string} request.filter - The standard list filter. + * @param {number=} request.pageSize - + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} for the + * details. + * @returns {Object} + * An iterable Object that conforms to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | iteration protocols}. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * for await (const response of client.listOperationsAsync(request)); + * // doThingsWith(response) + * ``` + */ + listOperationsAsync(request, options) { + var _a; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: (_a = request.name) !== null && _a !== void 0 ? _a : '', + }); + return this.operationsClient.listOperationsAsync(request, options); + } + /** + * Starts asynchronous cancellation on a long-running operation. The server + * makes a best effort to cancel the operation, but success is not + * guaranteed. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. Clients can use + * {@link Operations.GetOperation} or + * other methods to check whether the cancellation succeeded or whether the + * operation completed despite cancellation. On successful cancellation, + * the operation is not deleted; instead, it becomes an operation with + * an {@link Operation.error} value with a {@link google.rpc.Status.code} of + * 1, corresponding to `Code.CANCELLED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be cancelled. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} for the + * details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @return {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * await client.cancelOperation({name: ''}); + * ``` + */ + cancelOperation(request, optionsOrCallback, callback) { + var _a; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: (_a = request.name) !== null && _a !== void 0 ? _a : '', + }); + return this.operationsClient.cancelOperation(request, options, callback); + } + /** + * Deletes a long-running operation. This method indicates that the client is + * no longer interested in the operation result. It does not cancel the + * operation. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be deleted. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} + * for the details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @return {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * await client.deleteOperation({name: ''}); + * ``` + */ + deleteOperation(request, optionsOrCallback, callback) { + var _a; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: (_a = request.name) !== null && _a !== void 0 ? _a : '', + }); + return this.operationsClient.deleteOperation(request, options, callback); + } + // -------------------- + // -- Path templates -- + // -------------------- + /** + * Return a fully-qualified backup resource name string. + * + * @param {string} project + * @param {string} location + * @param {string} backup + * @returns {string} Resource name string. + */ + backupPath(project, location, backup) { + return this.pathTemplates.backupPathTemplate.render({ + project: project, + location: location, + backup: backup, + }); + } + /** + * Parse the project from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the project. + */ + matchProjectFromBackupName(backupName) { + return this.pathTemplates.backupPathTemplate.match(backupName).project; + } + /** + * Parse the location from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the location. + */ + matchLocationFromBackupName(backupName) { + return this.pathTemplates.backupPathTemplate.match(backupName).location; + } + /** + * Parse the backup from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the backup. + */ + matchBackupFromBackupName(backupName) { + return this.pathTemplates.backupPathTemplate.match(backupName).backup; + } + /** + * Return a fully-qualified backupSchedule resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} backup_schedule + * @returns {string} Resource name string. + */ + backupSchedulePath(project, database, backupSchedule) { + return this.pathTemplates.backupSchedulePathTemplate.render({ + project: project, + database: database, + backup_schedule: backupSchedule, + }); + } + /** + * Parse the project from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the project. + */ + matchProjectFromBackupScheduleName(backupScheduleName) { + return this.pathTemplates.backupSchedulePathTemplate.match(backupScheduleName).project; + } + /** + * Parse the database from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromBackupScheduleName(backupScheduleName) { + return this.pathTemplates.backupSchedulePathTemplate.match(backupScheduleName).database; + } + /** + * Parse the backup_schedule from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the backup_schedule. + */ + matchBackupScheduleFromBackupScheduleName(backupScheduleName) { + return this.pathTemplates.backupSchedulePathTemplate.match(backupScheduleName).backup_schedule; + } + /** + * Return a fully-qualified collectionGroup resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} collection + * @returns {string} Resource name string. + */ + collectionGroupPath(project, database, collection) { + return this.pathTemplates.collectionGroupPathTemplate.render({ + project: project, + database: database, + collection: collection, + }); + } + /** + * Parse the project from CollectionGroup resource. + * + * @param {string} collectionGroupName + * A fully-qualified path representing CollectionGroup resource. + * @returns {string} A string representing the project. + */ + matchProjectFromCollectionGroupName(collectionGroupName) { + return this.pathTemplates.collectionGroupPathTemplate.match(collectionGroupName).project; + } + /** + * Parse the database from CollectionGroup resource. + * + * @param {string} collectionGroupName + * A fully-qualified path representing CollectionGroup resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromCollectionGroupName(collectionGroupName) { + return this.pathTemplates.collectionGroupPathTemplate.match(collectionGroupName).database; + } + /** + * Parse the collection from CollectionGroup resource. + * + * @param {string} collectionGroupName + * A fully-qualified path representing CollectionGroup resource. + * @returns {string} A string representing the collection. + */ + matchCollectionFromCollectionGroupName(collectionGroupName) { + return this.pathTemplates.collectionGroupPathTemplate.match(collectionGroupName).collection; + } + /** + * Return a fully-qualified database resource name string. + * + * @param {string} project + * @param {string} database + * @returns {string} Resource name string. + */ + databasePath(project, database) { + return this.pathTemplates.databasePathTemplate.render({ + project: project, + database: database, + }); + } + /** + * Parse the project from Database resource. + * + * @param {string} databaseName + * A fully-qualified path representing Database resource. + * @returns {string} A string representing the project. + */ + matchProjectFromDatabaseName(databaseName) { + return this.pathTemplates.databasePathTemplate.match(databaseName).project; + } + /** + * Parse the database from Database resource. + * + * @param {string} databaseName + * A fully-qualified path representing Database resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromDatabaseName(databaseName) { + return this.pathTemplates.databasePathTemplate.match(databaseName).database; + } + /** + * Return a fully-qualified field resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} collection + * @param {string} field + * @returns {string} Resource name string. + */ + fieldPath(project, database, collection, field) { + return this.pathTemplates.fieldPathTemplate.render({ + project: project, + database: database, + collection: collection, + field: field, + }); + } + /** + * Parse the project from Field resource. + * + * @param {string} fieldName + * A fully-qualified path representing Field resource. + * @returns {string} A string representing the project. + */ + matchProjectFromFieldName(fieldName) { + return this.pathTemplates.fieldPathTemplate.match(fieldName).project; + } + /** + * Parse the database from Field resource. + * + * @param {string} fieldName + * A fully-qualified path representing Field resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromFieldName(fieldName) { + return this.pathTemplates.fieldPathTemplate.match(fieldName).database; + } + /** + * Parse the collection from Field resource. + * + * @param {string} fieldName + * A fully-qualified path representing Field resource. + * @returns {string} A string representing the collection. + */ + matchCollectionFromFieldName(fieldName) { + return this.pathTemplates.fieldPathTemplate.match(fieldName).collection; + } + /** + * Parse the field from Field resource. + * + * @param {string} fieldName + * A fully-qualified path representing Field resource. + * @returns {string} A string representing the field. + */ + matchFieldFromFieldName(fieldName) { + return this.pathTemplates.fieldPathTemplate.match(fieldName).field; + } + /** + * Return a fully-qualified index resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} collection + * @param {string} index + * @returns {string} Resource name string. + */ + indexPath(project, database, collection, index) { + return this.pathTemplates.indexPathTemplate.render({ + project: project, + database: database, + collection: collection, + index: index, + }); + } + /** + * Parse the project from Index resource. + * + * @param {string} indexName + * A fully-qualified path representing Index resource. + * @returns {string} A string representing the project. + */ + matchProjectFromIndexName(indexName) { + return this.pathTemplates.indexPathTemplate.match(indexName).project; + } + /** + * Parse the database from Index resource. + * + * @param {string} indexName + * A fully-qualified path representing Index resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromIndexName(indexName) { + return this.pathTemplates.indexPathTemplate.match(indexName).database; + } + /** + * Parse the collection from Index resource. + * + * @param {string} indexName + * A fully-qualified path representing Index resource. + * @returns {string} A string representing the collection. + */ + matchCollectionFromIndexName(indexName) { + return this.pathTemplates.indexPathTemplate.match(indexName).collection; + } + /** + * Parse the index from Index resource. + * + * @param {string} indexName + * A fully-qualified path representing Index resource. + * @returns {string} A string representing the index. + */ + matchIndexFromIndexName(indexName) { + return this.pathTemplates.indexPathTemplate.match(indexName).index; + } + /** + * Return a fully-qualified location resource name string. + * + * @param {string} project + * @param {string} location + * @returns {string} Resource name string. + */ + locationPath(project, location) { + return this.pathTemplates.locationPathTemplate.render({ + project: project, + location: location, + }); + } + /** + * Parse the project from Location resource. + * + * @param {string} locationName + * A fully-qualified path representing Location resource. + * @returns {string} A string representing the project. + */ + matchProjectFromLocationName(locationName) { + return this.pathTemplates.locationPathTemplate.match(locationName).project; + } + /** + * Parse the location from Location resource. + * + * @param {string} locationName + * A fully-qualified path representing Location resource. + * @returns {string} A string representing the location. + */ + matchLocationFromLocationName(locationName) { + return this.pathTemplates.locationPathTemplate.match(locationName).location; + } + /** + * Return a fully-qualified project resource name string. + * + * @param {string} project + * @returns {string} Resource name string. + */ + projectPath(project) { + return this.pathTemplates.projectPathTemplate.render({ + project: project, + }); + } + /** + * Parse the project from Project resource. + * + * @param {string} projectName + * A fully-qualified path representing Project resource. + * @returns {string} A string representing the project. + */ + matchProjectFromProjectName(projectName) { + return this.pathTemplates.projectPathTemplate.match(projectName).project; + } + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close() { + if (this.firestoreAdminStub && !this._terminated) { + return this.firestoreAdminStub.then(stub => { + this._terminated = true; + stub.close(); + this.locationsClient.close(); + this.operationsClient.close(); + }); + } + return Promise.resolve(); + } +} +exports.FirestoreAdminClient = FirestoreAdminClient; +//# sourceMappingURL=firestore_admin_client.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/v1/firestore_admin_client_config.json b/node_modules/@google-cloud/firestore/build/src/v1/firestore_admin_client_config.json new file mode 100644 index 0000000..874c4b6 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/v1/firestore_admin_client_config.json @@ -0,0 +1,139 @@ +{ + "interfaces": { + "google.firestore.admin.v1.FirestoreAdmin": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ], + "deadline_exceeded_internal_unavailable": [ + "DEADLINE_EXCEEDED", + "INTERNAL", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "CreateIndex": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListIndexes": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_internal_unavailable", + "retry_params_name": "default" + }, + "GetIndex": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_internal_unavailable", + "retry_params_name": "default" + }, + "DeleteIndex": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_internal_unavailable", + "retry_params_name": "default" + }, + "GetField": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_internal_unavailable", + "retry_params_name": "default" + }, + "UpdateField": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListFields": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_internal_unavailable", + "retry_params_name": "default" + }, + "ExportDocuments": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ImportDocuments": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "BulkDeleteDocuments": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "CreateDatabase": { + "timeout_millis": 120000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetDatabase": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListDatabases": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "UpdateDatabase": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "DeleteDatabase": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetBackup": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListBackups": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "DeleteBackup": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "RestoreDatabase": { + "timeout_millis": 120000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "CreateBackupSchedule": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetBackupSchedule": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListBackupSchedules": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "UpdateBackupSchedule": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "DeleteBackupSchedule": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/node_modules/@google-cloud/firestore/build/src/v1/firestore_admin_proto_list.json b/node_modules/@google-cloud/firestore/build/src/v1/firestore_admin_proto_list.json new file mode 100644 index 0000000..eaf3273 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/v1/firestore_admin_proto_list.json @@ -0,0 +1,10 @@ +[ + "../../protos/google/firestore/admin/v1/backup.proto", + "../../protos/google/firestore/admin/v1/database.proto", + "../../protos/google/firestore/admin/v1/field.proto", + "../../protos/google/firestore/admin/v1/firestore_admin.proto", + "../../protos/google/firestore/admin/v1/index.proto", + "../../protos/google/firestore/admin/v1/location.proto", + "../../protos/google/firestore/admin/v1/operation.proto", + "../../protos/google/firestore/admin/v1/schedule.proto" +] diff --git a/node_modules/@google-cloud/firestore/build/src/v1/firestore_client.d.ts b/node_modules/@google-cloud/firestore/build/src/v1/firestore_client.d.ts new file mode 100644 index 0000000..ff07404 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/v1/firestore_client.d.ts @@ -0,0 +1,1156 @@ +import type * as gax from 'google-gax'; +import type { Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, LocationsClient, LocationProtos } from 'google-gax'; +import { Transform } from 'stream'; +import * as protos from '../../protos/firestore_v1_proto_api'; +/** + * The Cloud Firestore service. + * + * Cloud Firestore is a fast, fully managed, serverless, cloud-native NoSQL + * document database that simplifies storing, syncing, and querying data for + * your mobile, web, and IoT apps at global scale. Its client libraries provide + * live synchronization and offline support, while its security features and + * integrations with Firebase and Google Cloud Platform accelerate building + * truly serverless apps. + * @class + * @memberof v1 + */ +export declare class FirestoreClient { + private _terminated; + private _opts; + private _providedCustomServicePath; + private _gaxModule; + private _gaxGrpc; + private _protos; + private _defaults; + private _universeDomain; + private _servicePath; + private _stubFailed; + auth: gax.GoogleAuth; + descriptors: Descriptors; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: { + [name: string]: Function; + }; + locationsClient: LocationsClient; + firestoreStub?: Promise<{ + [name: string]: Function; + }>; + /** + * Construct an instance of FirestoreClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param {string} [options.apiEndpoint] - The domain name of the + * API remote host. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new FirestoreClient({fallback: true}, gax); + * ``` + */ + constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback); + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize(): Promise<{ + [name: string]: Function; + }>; + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath(): string; + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint(): string; + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint(): string; + get universeDomain(): string; + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port(): number; + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes(): string[]; + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Gets a single document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Document to get. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * @param {google.firestore.v1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If the document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Reads the document in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads the version of the document at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.get_document.js + * region_tag:firestore_v1_generated_Firestore_GetDocument_async + */ + getDocument(request?: protos.google.firestore.v1.IGetDocumentRequest, options?: CallOptions): Promise<[ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | undefined, + {} | undefined + ]>; + getDocument(request: protos.google.firestore.v1.IGetDocumentRequest, options: CallOptions, callback: Callback): void; + getDocument(request: protos.google.firestore.v1.IGetDocumentRequest, callback: Callback): void; + /** + * Updates or inserts a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.v1.Document} request.document + * Required. The updated document. + * Creates the document if it does not already exist. + * @param {google.firestore.v1.DocumentMask} request.updateMask + * The fields to update. + * None of the field paths in the mask may contain a reserved name. + * + * If the document exists on the server and has fields not referenced in the + * mask, they are left unchanged. + * Fields referenced in the mask, but not present in the input document, are + * deleted from the document on the server. + * @param {google.firestore.v1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If the document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {google.firestore.v1.Precondition} request.currentDocument + * An optional precondition on the document. + * The request will fail if this is set and not met by the target document. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.update_document.js + * region_tag:firestore_v1_generated_Firestore_UpdateDocument_async + */ + updateDocument(request?: protos.google.firestore.v1.IUpdateDocumentRequest, options?: CallOptions): Promise<[ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | undefined, + {} | undefined + ]>; + updateDocument(request: protos.google.firestore.v1.IUpdateDocumentRequest, options: CallOptions, callback: Callback): void; + updateDocument(request: protos.google.firestore.v1.IUpdateDocumentRequest, callback: Callback): void; + /** + * Deletes a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Document to delete. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * @param {google.firestore.v1.Precondition} request.currentDocument + * An optional precondition on the document. + * The request will fail if this is set and not met by the target document. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.delete_document.js + * region_tag:firestore_v1_generated_Firestore_DeleteDocument_async + */ + deleteDocument(request?: protos.google.firestore.v1.IDeleteDocumentRequest, options?: CallOptions): Promise<[ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | undefined, + {} | undefined + ]>; + deleteDocument(request: protos.google.firestore.v1.IDeleteDocumentRequest, options: CallOptions, callback: Callback): void; + deleteDocument(request: protos.google.firestore.v1.IDeleteDocumentRequest, callback: Callback): void; + /** + * Starts a new transaction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {google.firestore.v1.TransactionOptions} request.options + * The options for the transaction. + * Defaults to a read-write transaction. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.BeginTransactionResponse|BeginTransactionResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.begin_transaction.js + * region_tag:firestore_v1_generated_Firestore_BeginTransaction_async + */ + beginTransaction(request?: protos.google.firestore.v1.IBeginTransactionRequest, options?: CallOptions): Promise<[ + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest | undefined, + {} | undefined + ]>; + beginTransaction(request: protos.google.firestore.v1.IBeginTransactionRequest, options: CallOptions, callback: Callback): void; + beginTransaction(request: protos.google.firestore.v1.IBeginTransactionRequest, callback: Callback): void; + /** + * Commits a transaction, while optionally updating documents. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {number[]} request.writes + * The writes to apply. + * + * Always executed atomically and in order. + * @param {Buffer} request.transaction + * If set, applies all writes in this transaction, and commits it. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.CommitResponse|CommitResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.commit.js + * region_tag:firestore_v1_generated_Firestore_Commit_async + */ + commit(request?: protos.google.firestore.v1.ICommitRequest, options?: CallOptions): Promise<[ + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | undefined, + {} | undefined + ]>; + commit(request: protos.google.firestore.v1.ICommitRequest, options: CallOptions, callback: Callback): void; + commit(request: protos.google.firestore.v1.ICommitRequest, callback: Callback): void; + /** + * Rolls back a transaction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {Buffer} request.transaction + * Required. The transaction to roll back. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.rollback.js + * region_tag:firestore_v1_generated_Firestore_Rollback_async + */ + rollback(request?: protos.google.firestore.v1.IRollbackRequest, options?: CallOptions): Promise<[ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | undefined, + {} | undefined + ]>; + rollback(request: protos.google.firestore.v1.IRollbackRequest, options: CallOptions, callback: Callback): void; + rollback(request: protos.google.firestore.v1.IRollbackRequest, callback: Callback): void; + /** + * Applies a batch of write operations. + * + * The BatchWrite method does not apply the write operations atomically + * and can apply them out of order. Method does not allow more than one write + * per document. Each write succeeds or fails independently. See the + * {@link protos.google.firestore.v1.BatchWriteResponse|BatchWriteResponse} for the + * success status of each write. + * + * If you require an atomically applied set of writes, use + * {@link protos.google.firestore.v1.Firestore.Commit|Commit} instead. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {number[]} request.writes + * The writes to apply. + * + * Method does not apply writes atomically and does not guarantee ordering. + * Each write succeeds or fails independently. You cannot write to the same + * document more than once per request. + * @param {number[]} request.labels + * Labels associated with this batch write. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.BatchWriteResponse|BatchWriteResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.batch_write.js + * region_tag:firestore_v1_generated_Firestore_BatchWrite_async + */ + batchWrite(request?: protos.google.firestore.v1.IBatchWriteRequest, options?: CallOptions): Promise<[ + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | undefined, + {} | undefined + ]>; + batchWrite(request: protos.google.firestore.v1.IBatchWriteRequest, options: CallOptions, callback: Callback): void; + batchWrite(request: protos.google.firestore.v1.IBatchWriteRequest, callback: Callback): void; + /** + * Creates a new document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource. For example: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: + * `chatrooms`. + * @param {string} request.documentId + * The client-assigned document ID to use for this document. + * + * Optional. If not specified, an ID will be assigned by the service. + * @param {google.firestore.v1.Document} request.document + * Required. The document to create. `name` must not be set. + * @param {google.firestore.v1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If the document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.create_document.js + * region_tag:firestore_v1_generated_Firestore_CreateDocument_async + */ + createDocument(request?: protos.google.firestore.v1.ICreateDocumentRequest, options?: CallOptions): Promise<[ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | undefined, + {} | undefined + ]>; + createDocument(request: protos.google.firestore.v1.ICreateDocumentRequest, options: CallOptions, callback: Callback): void; + createDocument(request: protos.google.firestore.v1.ICreateDocumentRequest, callback: Callback): void; + /** + * Gets multiple documents. + * + * Documents returned by this method are not guaranteed to be returned in the + * same order that they were requested. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.documents + * The names of the documents to retrieve. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * The request will fail if any of the document is not a child resource of the + * given `database`. Duplicate names will be elided. + * @param {google.firestore.v1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field will + * not be returned in the response. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * Starts a new transaction and reads the documents. + * Defaults to a read-only transaction. + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.BatchGetDocumentsResponse|BatchGetDocumentsResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.batch_get_documents.js + * region_tag:firestore_v1_generated_Firestore_BatchGetDocuments_async + */ + batchGetDocuments(request?: protos.google.firestore.v1.IBatchGetDocumentsRequest, options?: CallOptions): gax.CancellableStream; + /** + * Runs a query. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * @param {Buffer} request.transaction + * Run the query within an already active transaction. + * + * The value here is the opaque transaction ID to execute the query in. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * Starts a new transaction and reads the documents. + * Defaults to a read-only transaction. + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {google.firestore.v1.ExplainOptions} [request.explainOptions] + * Optional. Explain options for the query. If set, additional query + * statistics will be returned. If not, only query results will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.RunQueryResponse|RunQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.run_query.js + * region_tag:firestore_v1_generated_Firestore_RunQuery_async + */ + runQuery(request?: protos.google.firestore.v1.IRunQueryRequest, options?: CallOptions): gax.CancellableStream; + /** + * Runs an aggregation query. + * + * Rather than producing {@link protos.google.firestore.v1.Document|Document} results like + * {@link protos.google.firestore.v1.Firestore.RunQuery|Firestore.RunQuery}, this API + * allows running an aggregation to produce a series of + * {@link protos.google.firestore.v1.AggregationResult|AggregationResult} server-side. + * + * High-Level Example: + * + * ``` + * -- Return the number of documents in table given a filter. + * SELECT COUNT(*) FROM ( SELECT * FROM k where a = true ); + * ``` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {google.firestore.v1.StructuredAggregationQuery} request.structuredAggregationQuery + * An aggregation query. + * @param {Buffer} request.transaction + * Run the aggregation within an already active transaction. + * + * The value here is the opaque transaction ID to execute the query in. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * Starts a new transaction as part of the query, defaulting to read-only. + * + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Executes the query at the given timestamp. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {google.firestore.v1.ExplainOptions} [request.explainOptions] + * Optional. Explain options for the query. If set, additional query + * statistics will be returned. If not, only query results will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.RunAggregationQueryResponse|RunAggregationQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.run_aggregation_query.js + * region_tag:firestore_v1_generated_Firestore_RunAggregationQuery_async + */ + runAggregationQuery(request?: protos.google.firestore.v1.IRunAggregationQueryRequest, options?: CallOptions): gax.CancellableStream; + /** + * Streams batches of document updates and deletes, in order. This method is + * only available via gRPC or WebChannel (not REST). + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1.WriteRequest|WriteRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1.WriteResponse|WriteResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.write.js + * region_tag:firestore_v1_generated_Firestore_Write_async + */ + write(options?: CallOptions): gax.CancellableStream; + /** + * Listens to changes. This method is only available via gRPC or WebChannel + * (not REST). + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1.ListenRequest|ListenRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1.ListenResponse|ListenResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.listen.js + * region_tag:firestore_v1_generated_Firestore_Listen_async + */ + listen(options?: CallOptions): gax.CancellableStream; + /** + * Lists documents. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} [request.collectionId] + * Optional. The collection ID, relative to `parent`, to list. + * + * For example: `chatrooms` or `messages`. + * + * This is optional, and when not provided, Firestore will list documents + * from all collections under the provided `parent`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` response. + * + * Provide this to retrieve the subsequent page. When paginating, all other + * parameters (with the exception of `page_size`) must match the values set + * in the request that generated the page token. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * Optional. The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Perform the read as part of an already active transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Perform the read at the provided time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {boolean} request.showMissing + * If the list should show missing documents. + * + * A document is missing if it does not exist, but there are sub-documents + * nested underneath it. When true, such missing documents will be returned + * with a key but will not have fields, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.v1.Document|Document}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDocuments(request?: protos.google.firestore.v1.IListDocumentsRequest, options?: CallOptions): Promise<[ + protos.google.firestore.v1.IDocument[], + protos.google.firestore.v1.IListDocumentsRequest | null, + protos.google.firestore.v1.IListDocumentsResponse + ]>; + listDocuments(request: protos.google.firestore.v1.IListDocumentsRequest, options: CallOptions, callback: PaginationCallback): void; + listDocuments(request: protos.google.firestore.v1.IListDocumentsRequest, callback: PaginationCallback): void; + /** + * Equivalent to `listDocuments`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} [request.collectionId] + * Optional. The collection ID, relative to `parent`, to list. + * + * For example: `chatrooms` or `messages`. + * + * This is optional, and when not provided, Firestore will list documents + * from all collections under the provided `parent`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` response. + * + * Provide this to retrieve the subsequent page. When paginating, all other + * parameters (with the exception of `page_size`) must match the values set + * in the request that generated the page token. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * Optional. The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Perform the read as part of an already active transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Perform the read at the provided time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {boolean} request.showMissing + * If the list should show missing documents. + * + * A document is missing if it does not exist, but there are sub-documents + * nested underneath it. When true, such missing documents will be returned + * with a key but will not have fields, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1.Document|Document} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDocumentsStream(request?: protos.google.firestore.v1.IListDocumentsRequest, options?: CallOptions): Transform; + /** + * Equivalent to `listDocuments`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} [request.collectionId] + * Optional. The collection ID, relative to `parent`, to list. + * + * For example: `chatrooms` or `messages`. + * + * This is optional, and when not provided, Firestore will list documents + * from all collections under the provided `parent`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` response. + * + * Provide this to retrieve the subsequent page. When paginating, all other + * parameters (with the exception of `page_size`) must match the values set + * in the request that generated the page token. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * Optional. The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Perform the read as part of an already active transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Perform the read at the provided time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {boolean} request.showMissing + * If the list should show missing documents. + * + * A document is missing if it does not exist, but there are sub-documents + * nested underneath it. When true, such missing documents will be returned + * with a key but will not have fields, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1.Document|Document}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.list_documents.js + * region_tag:firestore_v1_generated_Firestore_ListDocuments_async + */ + listDocumentsAsync(request?: protos.google.firestore.v1.IListDocumentsRequest, options?: CallOptions): AsyncIterable; + /** + * Partitions a query by returning partition cursors that can be used to run + * the query in parallel. The returned partition cursors are split points that + * can be used by RunQuery as starting/end points for the query results. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.v1.Cursor|Cursor}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + partitionQuery(request?: protos.google.firestore.v1.IPartitionQueryRequest, options?: CallOptions): Promise<[ + protos.google.firestore.v1.ICursor[], + protos.google.firestore.v1.IPartitionQueryRequest | null, + protos.google.firestore.v1.IPartitionQueryResponse + ]>; + partitionQuery(request: protos.google.firestore.v1.IPartitionQueryRequest, options: CallOptions, callback: PaginationCallback): void; + partitionQuery(request: protos.google.firestore.v1.IPartitionQueryRequest, callback: PaginationCallback): void; + /** + * Equivalent to `partitionQuery`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1.Cursor|Cursor} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + partitionQueryStream(request?: protos.google.firestore.v1.IPartitionQueryRequest, options?: CallOptions): Transform; + /** + * Equivalent to `partitionQuery`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1.Cursor|Cursor}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.partition_query.js + * region_tag:firestore_v1_generated_Firestore_PartitionQuery_async + */ + partitionQueryAsync(request?: protos.google.firestore.v1.IPartitionQueryRequest, options?: CallOptions): AsyncIterable; + /** + * Lists all the collection IDs underneath a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of string. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listCollectionIds(request?: protos.google.firestore.v1.IListCollectionIdsRequest, options?: CallOptions): Promise<[ + string[], + protos.google.firestore.v1.IListCollectionIdsRequest | null, + protos.google.firestore.v1.IListCollectionIdsResponse + ]>; + listCollectionIds(request: protos.google.firestore.v1.IListCollectionIdsRequest, options: CallOptions, callback: PaginationCallback): void; + listCollectionIds(request: protos.google.firestore.v1.IListCollectionIdsRequest, callback: PaginationCallback): void; + /** + * Equivalent to `listCollectionIds`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing string on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listCollectionIdsStream(request?: protos.google.firestore.v1.IListCollectionIdsRequest, options?: CallOptions): Transform; + /** + * Equivalent to `listCollectionIds`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * string. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.list_collection_ids.js + * region_tag:firestore_v1_generated_Firestore_ListCollectionIds_async + */ + listCollectionIdsAsync(request?: protos.google.firestore.v1.IListCollectionIdsRequest, options?: CallOptions): AsyncIterable; + /** + * Gets information about a location. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Resource name for the location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html | CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.cloud.location.Location | Location}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * ``` + * const [response] = await client.getLocation(request); + * ``` + */ + getLocation(request: LocationProtos.google.cloud.location.IGetLocationRequest, options?: gax.CallOptions | Callback, callback?: Callback): Promise; + /** + * Lists information about the supported locations for this service. Returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource that owns the locations collection, if applicable. + * @param {string} request.filter + * The standard list filter. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link google.cloud.location.Location | Location}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * ``` + * const iterable = client.listLocationsAsync(request); + * for await (const response of iterable) { + * // process response + * } + * ``` + */ + listLocationsAsync(request: LocationProtos.google.cloud.location.IListLocationsRequest, options?: CallOptions): AsyncIterable; + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise; +} diff --git a/node_modules/@google-cloud/firestore/build/src/v1/firestore_client.js b/node_modules/@google-cloud/firestore/build/src/v1/firestore_client.js new file mode 100644 index 0000000..8379c5d --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/v1/firestore_client.js @@ -0,0 +1,1271 @@ +"use strict"; +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirestoreClient = void 0; +const stream_1 = require("stream"); +const jsonProtos = require("../../protos/v1.json"); +const logger_1 = require("../logger"); +/** + * Client JSON configuration object, loaded from + * `src/v1/firestore_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +const gapicConfig = require("./firestore_client_config.json"); +const version = require('../../../package.json').version; +/** + * The Cloud Firestore service. + * + * Cloud Firestore is a fast, fully managed, serverless, cloud-native NoSQL + * document database that simplifies storing, syncing, and querying data for + * your mobile, web, and IoT apps at global scale. Its client libraries provide + * live synchronization and offline support, while its security features and + * integrations with Firebase and Google Cloud Platform accelerate building + * truly serverless apps. + * @class + * @memberof v1 + */ +class FirestoreClient { + /** + * Construct an instance of FirestoreClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param {string} [options.apiEndpoint] - The domain name of the + * API remote host. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new FirestoreClient({fallback: true}, gax); + * ``` + */ + constructor(opts, gaxInstance) { + var _a, _b, _c, _d, _e; + this._terminated = false; + this._stubFailed = false; + this.descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + // Ensure that options include all the required fields. + const staticMembers = this.constructor; + if ((opts === null || opts === void 0 ? void 0 : opts.universe_domain) && + (opts === null || opts === void 0 ? void 0 : opts.universeDomain) && + (opts === null || opts === void 0 ? void 0 : opts.universe_domain) !== (opts === null || opts === void 0 ? void 0 : opts.universeDomain)) { + throw new Error('Please set either universe_domain or universeDomain, but not both.'); + } + const universeDomainEnvVar = typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + (_c = (_b = (_a = opts === null || opts === void 0 ? void 0 : opts.universeDomain) !== null && _a !== void 0 ? _a : opts === null || opts === void 0 ? void 0 : opts.universe_domain) !== null && _b !== void 0 ? _b : universeDomainEnvVar) !== null && _c !== void 0 ? _c : 'googleapis.com'; + this._servicePath = 'firestore.' + this._universeDomain; + const servicePath = (opts === null || opts === void 0 ? void 0 : opts.servicePath) || (opts === null || opts === void 0 ? void 0 : opts.apiEndpoint) || this._servicePath; + this._providedCustomServicePath = !!((opts === null || opts === void 0 ? void 0 : opts.servicePath) || (opts === null || opts === void 0 ? void 0 : opts.apiEndpoint)); + const port = (opts === null || opts === void 0 ? void 0 : opts.port) || staticMembers.port; + const clientConfig = (_d = opts === null || opts === void 0 ? void 0 : opts.clientConfig) !== null && _d !== void 0 ? _d : {}; + const fallback = (_e = opts === null || opts === void 0 ? void 0 : opts.fallback) !== null && _e !== void 0 ? _e : (typeof window !== 'undefined' && typeof (window === null || window === void 0 ? void 0 : window.fetch) === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); + // Request numeric enum values if REST transport is used. + opts.numericEnums = true; + // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. + if (servicePath !== this._servicePath && !('scopes' in opts)) { + opts['scopes'] = staticMembers.scopes; + } + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax'); + } + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + // Save options to use in initialize() method. + this._opts = opts; + // Save the auth object to the client, for use by other methods. + this.auth = this._gaxGrpc.auth; + // Set useJWTAccessWithScope on the auth object. + this.auth.useJWTAccessWithScope = true; + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + this.locationsClient = new this._gaxModule.LocationsClient(this._gaxGrpc, opts); + // Determine the client header string. + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } + else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } + else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + // Some of the methods on this service return "paged" results, + // (e.g. 50 results at a time, with tokens to get subsequent + // pages). Denote the keys used for pagination and results. + this.descriptors.page = { + listDocuments: new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'documents'), + partitionQuery: new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'partitions'), + listCollectionIds: new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'collectionIds'), + }; + // Some of the methods on this service provide streaming responses. + // Provide descriptors for these. + this.descriptors.stream = { + batchGetDocuments: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), + runQuery: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), + runAggregationQuery: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), + write: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), + listen: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), + }; + // Put together the default options sent with requests. + this._defaults = this._gaxGrpc.constructSettings('google.firestore.v1.Firestore', gapicConfig, opts.clientConfig || {}, { 'x-goog-api-client': clientHeader.join(' ') }); + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.firestoreStub && !this._stubFailed) { + return this.firestoreStub; + } + // Reset _stubFailed because we are re-attempting create + this._stubFailed = false; + // Put together the "service stub" for + // google.firestore.v1.Firestore. + this.firestoreStub = this._gaxGrpc.createStub(this._opts.fallback + ? this._protos.lookupService('google.firestore.v1.Firestore') + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._protos.google.firestore.v1.Firestore, this._opts, this._providedCustomServicePath); + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const firestoreStubMethods = [ + 'getDocument', + 'listDocuments', + 'updateDocument', + 'deleteDocument', + 'batchGetDocuments', + 'beginTransaction', + 'commit', + 'rollback', + 'runQuery', + 'runAggregationQuery', + 'partitionQuery', + 'write', + 'listen', + 'listCollectionIds', + 'batchWrite', + 'createDocument', + ]; + for (const methodName of firestoreStubMethods) { + const callPromise = this.firestoreStub.then(stub => { + return (...args) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new stream_1.PassThrough({ objectMode: true }); + setImmediate(() => { + stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.')); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }; + }, (err) => { + this._stubFailed = true; + (0, logger_1.logger)('initialize', null, 'Failed to create the gax client stub.', err); + return () => { + throw err; + }; + }); + const descriptor = this.descriptors.page[methodName] || + this.descriptors.stream[methodName] || + undefined; + const apiCall = this._gaxModule.createApiCall(callPromise, this._defaults[methodName], descriptor, this._opts.fallback); + this.innerApiCalls[methodName] = apiCall; + } + return this.firestoreStub; + } + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath() { + if (typeof process === 'object' && + typeof process.emitWarning === 'function') { + process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'firestore.googleapis.com'; + } + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint() { + if (typeof process === 'object' && + typeof process.emitWarning === 'function') { + process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'firestore.googleapis.com'; + } + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + get universeDomain() { + return this._universeDomain; + } + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/datastore', + ]; + } + /** + * Return the project ID used by this class. + * @returns {Promise} A promise that resolves to string containing the project ID. + */ + getProjectId(callback) { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + getDocument(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: (_a = request.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.getDocument(request, options, callback); + } + updateDocument(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'document.name': (_a = request.document.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.updateDocument(request, options, callback); + } + deleteDocument(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: (_a = request.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.deleteDocument(request, options, callback); + } + beginTransaction(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: (_a = request.database) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.beginTransaction(request, options, callback); + } + commit(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: (_a = request.database) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.commit(request, options, callback); + } + rollback(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: (_a = request.database) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.rollback(request, options, callback); + } + batchWrite(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: (_a = request.database) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.batchWrite(request, options, callback); + } + createDocument(request, optionsOrCallback, callback) { + var _a, _b; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + collection_id: (_b = request.collectionId) !== null && _b !== void 0 ? _b : '', + }); + this.initialize(); + return this.innerApiCalls.createDocument(request, options, callback); + } + /** + * Gets multiple documents. + * + * Documents returned by this method are not guaranteed to be returned in the + * same order that they were requested. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.documents + * The names of the documents to retrieve. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * The request will fail if any of the document is not a child resource of the + * given `database`. Duplicate names will be elided. + * @param {google.firestore.v1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field will + * not be returned in the response. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * Starts a new transaction and reads the documents. + * Defaults to a read-only transaction. + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.BatchGetDocumentsResponse|BatchGetDocumentsResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.batch_get_documents.js + * region_tag:firestore_v1_generated_Firestore_BatchGetDocuments_async + */ + batchGetDocuments(request, options) { + var _a; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: (_a = request.database) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.batchGetDocuments(request, options); + } + /** + * Runs a query. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * @param {Buffer} request.transaction + * Run the query within an already active transaction. + * + * The value here is the opaque transaction ID to execute the query in. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * Starts a new transaction and reads the documents. + * Defaults to a read-only transaction. + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {google.firestore.v1.ExplainOptions} [request.explainOptions] + * Optional. Explain options for the query. If set, additional query + * statistics will be returned. If not, only query results will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.RunQueryResponse|RunQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.run_query.js + * region_tag:firestore_v1_generated_Firestore_RunQuery_async + */ + runQuery(request, options) { + var _a; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.runQuery(request, options); + } + /** + * Runs an aggregation query. + * + * Rather than producing {@link protos.google.firestore.v1.Document|Document} results like + * {@link protos.google.firestore.v1.Firestore.RunQuery|Firestore.RunQuery}, this API + * allows running an aggregation to produce a series of + * {@link protos.google.firestore.v1.AggregationResult|AggregationResult} server-side. + * + * High-Level Example: + * + * ``` + * -- Return the number of documents in table given a filter. + * SELECT COUNT(*) FROM ( SELECT * FROM k where a = true ); + * ``` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {google.firestore.v1.StructuredAggregationQuery} request.structuredAggregationQuery + * An aggregation query. + * @param {Buffer} request.transaction + * Run the aggregation within an already active transaction. + * + * The value here is the opaque transaction ID to execute the query in. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * Starts a new transaction as part of the query, defaulting to read-only. + * + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Executes the query at the given timestamp. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {google.firestore.v1.ExplainOptions} [request.explainOptions] + * Optional. Explain options for the query. If set, additional query + * statistics will be returned. If not, only query results will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.RunAggregationQueryResponse|RunAggregationQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.run_aggregation_query.js + * region_tag:firestore_v1_generated_Firestore_RunAggregationQuery_async + */ + runAggregationQuery(request, options) { + var _a; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.runAggregationQuery(request, options); + } + /** + * Streams batches of document updates and deletes, in order. This method is + * only available via gRPC or WebChannel (not REST). + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1.WriteRequest|WriteRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1.WriteResponse|WriteResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.write.js + * region_tag:firestore_v1_generated_Firestore_Write_async + */ + write(options) { + this.initialize(); + return this.innerApiCalls.write(null, options); + } + /** + * Listens to changes. This method is only available via gRPC or WebChannel + * (not REST). + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1.ListenRequest|ListenRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1.ListenResponse|ListenResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.listen.js + * region_tag:firestore_v1_generated_Firestore_Listen_async + */ + listen(options) { + this.initialize(); + return this.innerApiCalls.listen(null, options); + } + listDocuments(request, optionsOrCallback, callback) { + var _a, _b; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + collection_id: (_b = request.collectionId) !== null && _b !== void 0 ? _b : '', + }); + this.initialize(); + return this.innerApiCalls.listDocuments(request, options, callback); + } + /** + * Equivalent to `listDocuments`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} [request.collectionId] + * Optional. The collection ID, relative to `parent`, to list. + * + * For example: `chatrooms` or `messages`. + * + * This is optional, and when not provided, Firestore will list documents + * from all collections under the provided `parent`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` response. + * + * Provide this to retrieve the subsequent page. When paginating, all other + * parameters (with the exception of `page_size`) must match the values set + * in the request that generated the page token. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * Optional. The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Perform the read as part of an already active transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Perform the read at the provided time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {boolean} request.showMissing + * If the list should show missing documents. + * + * A document is missing if it does not exist, but there are sub-documents + * nested underneath it. When true, such missing documents will be returned + * with a key but will not have fields, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1.Document|Document} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDocumentsStream(request, options) { + var _a, _b; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + collection_id: (_b = request.collectionId) !== null && _b !== void 0 ? _b : '', + }); + const defaultCallSettings = this._defaults['listDocuments']; + const callSettings = defaultCallSettings.merge(options); + this.initialize(); + return this.descriptors.page.listDocuments.createStream(this.innerApiCalls.listDocuments, request, callSettings); + } + /** + * Equivalent to `listDocuments`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} [request.collectionId] + * Optional. The collection ID, relative to `parent`, to list. + * + * For example: `chatrooms` or `messages`. + * + * This is optional, and when not provided, Firestore will list documents + * from all collections under the provided `parent`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` response. + * + * Provide this to retrieve the subsequent page. When paginating, all other + * parameters (with the exception of `page_size`) must match the values set + * in the request that generated the page token. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * Optional. The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Perform the read as part of an already active transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Perform the read at the provided time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {boolean} request.showMissing + * If the list should show missing documents. + * + * A document is missing if it does not exist, but there are sub-documents + * nested underneath it. When true, such missing documents will be returned + * with a key but will not have fields, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1.Document|Document}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.list_documents.js + * region_tag:firestore_v1_generated_Firestore_ListDocuments_async + */ + listDocumentsAsync(request, options) { + var _a, _b; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + collection_id: (_b = request.collectionId) !== null && _b !== void 0 ? _b : '', + }); + const defaultCallSettings = this._defaults['listDocuments']; + const callSettings = defaultCallSettings.merge(options); + this.initialize(); + return this.descriptors.page.listDocuments.asyncIterate(this.innerApiCalls['listDocuments'], request, callSettings); + } + partitionQuery(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.partitionQuery(request, options, callback); + } + /** + * Equivalent to `partitionQuery`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1.Cursor|Cursor} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + partitionQueryStream(request, options) { + var _a; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + const defaultCallSettings = this._defaults['partitionQuery']; + const callSettings = defaultCallSettings.merge(options); + this.initialize(); + return this.descriptors.page.partitionQuery.createStream(this.innerApiCalls.partitionQuery, request, callSettings); + } + /** + * Equivalent to `partitionQuery`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1.Cursor|Cursor}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.partition_query.js + * region_tag:firestore_v1_generated_Firestore_PartitionQuery_async + */ + partitionQueryAsync(request, options) { + var _a; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + const defaultCallSettings = this._defaults['partitionQuery']; + const callSettings = defaultCallSettings.merge(options); + this.initialize(); + return this.descriptors.page.partitionQuery.asyncIterate(this.innerApiCalls['partitionQuery'], request, callSettings); + } + listCollectionIds(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.listCollectionIds(request, options, callback); + } + /** + * Equivalent to `listCollectionIds`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing string on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listCollectionIdsStream(request, options) { + var _a; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + const defaultCallSettings = this._defaults['listCollectionIds']; + const callSettings = defaultCallSettings.merge(options); + this.initialize(); + return this.descriptors.page.listCollectionIds.createStream(this.innerApiCalls.listCollectionIds, request, callSettings); + } + /** + * Equivalent to `listCollectionIds`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * string. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.list_collection_ids.js + * region_tag:firestore_v1_generated_Firestore_ListCollectionIds_async + */ + listCollectionIdsAsync(request, options) { + var _a; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + const defaultCallSettings = this._defaults['listCollectionIds']; + const callSettings = defaultCallSettings.merge(options); + this.initialize(); + return this.descriptors.page.listCollectionIds.asyncIterate(this.innerApiCalls['listCollectionIds'], request, callSettings); + } + /** + * Gets information about a location. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Resource name for the location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html | CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.cloud.location.Location | Location}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * ``` + * const [response] = await client.getLocation(request); + * ``` + */ + getLocation(request, options, callback) { + return this.locationsClient.getLocation(request, options, callback); + } + /** + * Lists information about the supported locations for this service. Returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource that owns the locations collection, if applicable. + * @param {string} request.filter + * The standard list filter. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link google.cloud.location.Location | Location}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * ``` + * const iterable = client.listLocationsAsync(request); + * for await (const response of iterable) { + * // process response + * } + * ``` + */ + listLocationsAsync(request, options) { + return this.locationsClient.listLocationsAsync(request, options); + } + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close() { + if (this.firestoreStub && !this._terminated) { + return this.firestoreStub.then(stub => { + this._terminated = true; + stub.close(); + this.locationsClient.close(); + }); + } + return Promise.resolve(); + } +} +exports.FirestoreClient = FirestoreClient; +//# sourceMappingURL=firestore_client.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/v1/firestore_client_config.json b/node_modules/@google-cloud/firestore/build/src/v1/firestore_client_config.json new file mode 100644 index 0000000..75487fc --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/v1/firestore_client_config.json @@ -0,0 +1,121 @@ +{ + "interfaces": { + "google.firestore.v1.Firestore": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ], + "deadline_exceeded_resource_exhausted_internal_unavailable": [ + "DEADLINE_EXCEEDED", + "RESOURCE_EXHAUSTED", + "INTERNAL", + "UNAVAILABLE" + ], + "resource_exhausted_unavailable": [ + "RESOURCE_EXHAUSTED", + "UNAVAILABLE" + ], + "resource_exhausted_aborted_unavailable": [ + "RESOURCE_EXHAUSTED", + "ABORTED", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "GetDocument": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "ListDocuments": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "UpdateDocument": { + "timeout_millis": 60000, + "retry_codes_name": "resource_exhausted_unavailable", + "retry_params_name": "default" + }, + "DeleteDocument": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "BatchGetDocuments": { + "timeout_millis": 300000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "BeginTransaction": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "Commit": { + "timeout_millis": 60000, + "retry_codes_name": "resource_exhausted_unavailable", + "retry_params_name": "default" + }, + "Rollback": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "RunQuery": { + "timeout_millis": 300000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "RunAggregationQuery": { + "timeout_millis": 300000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "PartitionQuery": { + "timeout_millis": 300000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "Write": { + "timeout_millis": 86400000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "Listen": { + "timeout_millis": 86400000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "ListCollectionIds": { + "timeout_millis": 60000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, + "BatchWrite": { + "timeout_millis": 60000, + "retry_codes_name": "resource_exhausted_aborted_unavailable", + "retry_params_name": "default" + }, + "CreateDocument": { + "timeout_millis": 60000, + "retry_codes_name": "resource_exhausted_unavailable", + "retry_params_name": "default" + } + } + } + } +} diff --git a/node_modules/@google-cloud/firestore/build/src/v1/firestore_proto_list.json b/node_modules/@google-cloud/firestore/build/src/v1/firestore_proto_list.json new file mode 100644 index 0000000..318c636 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/v1/firestore_proto_list.json @@ -0,0 +1,10 @@ +[ + "../../protos/google/firestore/v1/aggregation_result.proto", + "../../protos/google/firestore/v1/bloom_filter.proto", + "../../protos/google/firestore/v1/common.proto", + "../../protos/google/firestore/v1/document.proto", + "../../protos/google/firestore/v1/firestore.proto", + "../../protos/google/firestore/v1/query.proto", + "../../protos/google/firestore/v1/query_profile.proto", + "../../protos/google/firestore/v1/write.proto" +] diff --git a/node_modules/@google-cloud/firestore/build/src/v1/gapic_metadata.json b/node_modules/@google-cloud/firestore/build/src/v1/gapic_metadata.json new file mode 100644 index 0000000..4fce001 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/v1/gapic_metadata.json @@ -0,0 +1,170 @@ +{ + "schema": "1.0", + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "typescript", + "protoPackage": "google.firestore.v1", + "libraryPackage": "@google-cloud/firestore", + "services": { + "Firestore": { + "clients": { + "grpc": { + "libraryClient": "FirestoreClient", + "rpcs": { + "GetDocument": { + "methods": [ + "getDocument" + ] + }, + "UpdateDocument": { + "methods": [ + "updateDocument" + ] + }, + "DeleteDocument": { + "methods": [ + "deleteDocument" + ] + }, + "BeginTransaction": { + "methods": [ + "beginTransaction" + ] + }, + "Commit": { + "methods": [ + "commit" + ] + }, + "Rollback": { + "methods": [ + "rollback" + ] + }, + "BatchWrite": { + "methods": [ + "batchWrite" + ] + }, + "CreateDocument": { + "methods": [ + "createDocument" + ] + }, + "BatchGetDocuments": { + "methods": [ + "batchGetDocuments" + ] + }, + "RunQuery": { + "methods": [ + "runQuery" + ] + }, + "RunAggregationQuery": { + "methods": [ + "runAggregationQuery" + ] + }, + "Write": { + "methods": [ + "write" + ] + }, + "Listen": { + "methods": [ + "listen" + ] + }, + "ListDocuments": { + "methods": [ + "listDocuments", + "listDocumentsStream", + "listDocumentsAsync" + ] + }, + "PartitionQuery": { + "methods": [ + "partitionQuery", + "partitionQueryStream", + "partitionQueryAsync" + ] + }, + "ListCollectionIds": { + "methods": [ + "listCollectionIds", + "listCollectionIdsStream", + "listCollectionIdsAsync" + ] + } + } + }, + "grpc-fallback": { + "libraryClient": "FirestoreClient", + "rpcs": { + "GetDocument": { + "methods": [ + "getDocument" + ] + }, + "UpdateDocument": { + "methods": [ + "updateDocument" + ] + }, + "DeleteDocument": { + "methods": [ + "deleteDocument" + ] + }, + "BeginTransaction": { + "methods": [ + "beginTransaction" + ] + }, + "Commit": { + "methods": [ + "commit" + ] + }, + "Rollback": { + "methods": [ + "rollback" + ] + }, + "BatchWrite": { + "methods": [ + "batchWrite" + ] + }, + "CreateDocument": { + "methods": [ + "createDocument" + ] + }, + "ListDocuments": { + "methods": [ + "listDocuments", + "listDocumentsStream", + "listDocumentsAsync" + ] + }, + "PartitionQuery": { + "methods": [ + "partitionQuery", + "partitionQueryStream", + "partitionQueryAsync" + ] + }, + "ListCollectionIds": { + "methods": [ + "listCollectionIds", + "listCollectionIdsStream", + "listCollectionIdsAsync" + ] + } + } + } + } + } + } +} diff --git a/node_modules/@google-cloud/firestore/build/src/v1/index.d.ts b/node_modules/@google-cloud/firestore/build/src/v1/index.d.ts new file mode 100644 index 0000000..5b127e7 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/v1/index.d.ts @@ -0,0 +1,3 @@ +import { FirestoreAdminClient } from './firestore_admin_client'; +import { FirestoreClient } from './firestore_client'; +export { FirestoreClient, FirestoreAdminClient }; diff --git a/node_modules/@google-cloud/firestore/build/src/v1/index.js b/node_modules/@google-cloud/firestore/build/src/v1/index.js new file mode 100644 index 0000000..dcb7449 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/v1/index.js @@ -0,0 +1,25 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirestoreAdminClient = exports.FirestoreClient = void 0; +const firestore_admin_client_1 = require("./firestore_admin_client"); +Object.defineProperty(exports, "FirestoreAdminClient", { enumerable: true, get: function () { return firestore_admin_client_1.FirestoreAdminClient; } }); +const firestore_client_1 = require("./firestore_client"); +Object.defineProperty(exports, "FirestoreClient", { enumerable: true, get: function () { return firestore_client_1.FirestoreClient; } }); +// Doing something really horrible for reverse compatibility with original JavaScript exports +const existingExports = module.exports; +module.exports = firestore_client_1.FirestoreClient; +module.exports = Object.assign(module.exports, existingExports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_client.d.ts b/node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_client.d.ts new file mode 100644 index 0000000..ffc88f0 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_client.d.ts @@ -0,0 +1,930 @@ +import type * as gax from 'google-gax'; +import type { Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback } from 'google-gax'; +import { Transform } from 'stream'; +import * as protos from '../../protos/firestore_v1beta1_proto_api'; +/** + * The Cloud Firestore service. + * + * Cloud Firestore is a fast, fully managed, serverless, cloud-native NoSQL + * document database that simplifies storing, syncing, and querying data for + * your mobile, web, and IoT apps at global scale. Its client libraries provide + * live synchronization and offline support, while its security features and + * integrations with Firebase and Google Cloud Platform (GCP) accelerate + * building truly serverless apps. + * @class + * @deprecated Use v1/firestore_client instead. + * @memberof v1beta1 + */ +export declare class FirestoreClient { + private _terminated; + private _opts; + private _providedCustomServicePath; + private _gaxModule; + private _gaxGrpc; + private _protos; + private _defaults; + private _universeDomain; + private _servicePath; + auth: gax.GoogleAuth; + descriptors: Descriptors; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: { + [name: string]: Function; + }; + firestoreStub?: Promise<{ + [name: string]: Function; + }>; + /** + * Construct an instance of FirestoreClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param {string} [options.apiEndpoint] - The domain name of the + * API remote host. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new FirestoreClient({fallback: true}, gax); + * ``` + */ + constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback); + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize(): Promise<{ + [name: string]: Function; + }>; + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath(): string; + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint(): string; + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint(): string; + get universeDomain(): string; + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port(): number; + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes(): string[]; + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Gets a single document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Document to get. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If the document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Reads the document in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads the version of the document at the given time. + * This may not be older than 270 seconds. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.get_document.js + * region_tag:firestore_v1beta1_generated_Firestore_GetDocument_async + */ + getDocument(request?: protos.google.firestore.v1beta1.IGetDocumentRequest, options?: CallOptions): Promise<[ + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IGetDocumentRequest | undefined, + {} | undefined + ]>; + getDocument(request: protos.google.firestore.v1beta1.IGetDocumentRequest, options: CallOptions, callback: Callback): void; + getDocument(request: protos.google.firestore.v1beta1.IGetDocumentRequest, callback: Callback): void; + /** + * Updates or inserts a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.v1beta1.Document} request.document + * Required. The updated document. + * Creates the document if it does not already exist. + * @param {google.firestore.v1beta1.DocumentMask} request.updateMask + * The fields to update. + * None of the field paths in the mask may contain a reserved name. + * + * If the document exists on the server and has fields not referenced in the + * mask, they are left unchanged. + * Fields referenced in the mask, but not present in the input document, are + * deleted from the document on the server. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If the document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {google.firestore.v1beta1.Precondition} request.currentDocument + * An optional precondition on the document. + * The request will fail if this is set and not met by the target document. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.update_document.js + * region_tag:firestore_v1beta1_generated_Firestore_UpdateDocument_async + */ + updateDocument(request?: protos.google.firestore.v1beta1.IUpdateDocumentRequest, options?: CallOptions): Promise<[ + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IUpdateDocumentRequest | undefined, + {} | undefined + ]>; + updateDocument(request: protos.google.firestore.v1beta1.IUpdateDocumentRequest, options: CallOptions, callback: Callback): void; + updateDocument(request: protos.google.firestore.v1beta1.IUpdateDocumentRequest, callback: Callback): void; + /** + * Deletes a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Document to delete. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * @param {google.firestore.v1beta1.Precondition} request.currentDocument + * An optional precondition on the document. + * The request will fail if this is set and not met by the target document. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.delete_document.js + * region_tag:firestore_v1beta1_generated_Firestore_DeleteDocument_async + */ + deleteDocument(request?: protos.google.firestore.v1beta1.IDeleteDocumentRequest, options?: CallOptions): Promise<[ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IDeleteDocumentRequest | undefined, + {} | undefined + ]>; + deleteDocument(request: protos.google.firestore.v1beta1.IDeleteDocumentRequest, options: CallOptions, callback: Callback): void; + deleteDocument(request: protos.google.firestore.v1beta1.IDeleteDocumentRequest, callback: Callback): void; + /** + * Starts a new transaction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {google.firestore.v1beta1.TransactionOptions} request.options + * The options for the transaction. + * Defaults to a read-write transaction. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.BeginTransactionResponse|BeginTransactionResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.begin_transaction.js + * region_tag:firestore_v1beta1_generated_Firestore_BeginTransaction_async + */ + beginTransaction(request?: protos.google.firestore.v1beta1.IBeginTransactionRequest, options?: CallOptions): Promise<[ + protos.google.firestore.v1beta1.IBeginTransactionResponse, + protos.google.firestore.v1beta1.IBeginTransactionRequest | undefined, + {} | undefined + ]>; + beginTransaction(request: protos.google.firestore.v1beta1.IBeginTransactionRequest, options: CallOptions, callback: Callback): void; + beginTransaction(request: protos.google.firestore.v1beta1.IBeginTransactionRequest, callback: Callback): void; + /** + * Commits a transaction, while optionally updating documents. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {number[]} request.writes + * The writes to apply. + * + * Always executed atomically and in order. + * @param {Buffer} request.transaction + * If set, applies all writes in this transaction, and commits it. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.CommitResponse|CommitResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.commit.js + * region_tag:firestore_v1beta1_generated_Firestore_Commit_async + */ + commit(request?: protos.google.firestore.v1beta1.ICommitRequest, options?: CallOptions): Promise<[ + protos.google.firestore.v1beta1.ICommitResponse, + protos.google.firestore.v1beta1.ICommitRequest | undefined, + {} | undefined + ]>; + commit(request: protos.google.firestore.v1beta1.ICommitRequest, options: CallOptions, callback: Callback): void; + commit(request: protos.google.firestore.v1beta1.ICommitRequest, callback: Callback): void; + /** + * Rolls back a transaction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {Buffer} request.transaction + * Required. The transaction to roll back. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.rollback.js + * region_tag:firestore_v1beta1_generated_Firestore_Rollback_async + */ + rollback(request?: protos.google.firestore.v1beta1.IRollbackRequest, options?: CallOptions): Promise<[ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IRollbackRequest | undefined, + {} | undefined + ]>; + rollback(request: protos.google.firestore.v1beta1.IRollbackRequest, options: CallOptions, callback: Callback): void; + rollback(request: protos.google.firestore.v1beta1.IRollbackRequest, callback: Callback): void; + /** + * Applies a batch of write operations. + * + * The BatchWrite method does not apply the write operations atomically + * and can apply them out of order. Method does not allow more than one write + * per document. Each write succeeds or fails independently. See the + * {@link protos.google.firestore.v1beta1.BatchWriteResponse|BatchWriteResponse} for the success status of each write. + * + * If you require an atomically applied set of writes, use + * {@link protos.google.firestore.v1beta1.Firestore.Commit|Commit} instead. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {number[]} request.writes + * The writes to apply. + * + * Method does not apply writes atomically and does not guarantee ordering. + * Each write succeeds or fails independently. You cannot write to the same + * document more than once per request. + * @param {number[]} request.labels + * Labels associated with this batch write. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.BatchWriteResponse|BatchWriteResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.batch_write.js + * region_tag:firestore_v1beta1_generated_Firestore_BatchWrite_async + */ + batchWrite(request?: protos.google.firestore.v1beta1.IBatchWriteRequest, options?: CallOptions): Promise<[ + protos.google.firestore.v1beta1.IBatchWriteResponse, + protos.google.firestore.v1beta1.IBatchWriteRequest | undefined, + {} | undefined + ]>; + batchWrite(request: protos.google.firestore.v1beta1.IBatchWriteRequest, options: CallOptions, callback: Callback): void; + batchWrite(request: protos.google.firestore.v1beta1.IBatchWriteRequest, callback: Callback): void; + /** + * Creates a new document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource. For example: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms`. + * @param {string} request.documentId + * The client-assigned document ID to use for this document. + * + * Optional. If not specified, an ID will be assigned by the service. + * @param {google.firestore.v1beta1.Document} request.document + * Required. The document to create. `name` must not be set. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If the document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.create_document.js + * region_tag:firestore_v1beta1_generated_Firestore_CreateDocument_async + */ + createDocument(request?: protos.google.firestore.v1beta1.ICreateDocumentRequest, options?: CallOptions): Promise<[ + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.ICreateDocumentRequest | undefined, + {} | undefined + ]>; + createDocument(request: protos.google.firestore.v1beta1.ICreateDocumentRequest, options: CallOptions, callback: Callback): void; + createDocument(request: protos.google.firestore.v1beta1.ICreateDocumentRequest, callback: Callback): void; + /** + * Gets multiple documents. + * + * Documents returned by this method are not guaranteed to be returned in the + * same order that they were requested. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.documents + * The names of the documents to retrieve. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * The request will fail if any of the document is not a child resource of the + * given `database`. Duplicate names will be elided. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field will + * not be returned in the response. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.firestore.v1beta1.TransactionOptions} request.newTransaction + * Starts a new transaction and reads the documents. + * Defaults to a read-only transaction. + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1beta1.BatchGetDocumentsResponse|BatchGetDocumentsResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.batch_get_documents.js + * region_tag:firestore_v1beta1_generated_Firestore_BatchGetDocuments_async + */ + batchGetDocuments(request?: protos.google.firestore.v1beta1.IBatchGetDocumentsRequest, options?: CallOptions): gax.CancellableStream; + /** + * Runs a query. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {google.firestore.v1beta1.StructuredQuery} request.structuredQuery + * A structured query. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.firestore.v1beta1.TransactionOptions} request.newTransaction + * Starts a new transaction and reads the documents. + * Defaults to a read-only transaction. + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1beta1.RunQueryResponse|RunQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.run_query.js + * region_tag:firestore_v1beta1_generated_Firestore_RunQuery_async + */ + runQuery(request?: protos.google.firestore.v1beta1.IRunQueryRequest, options?: CallOptions): gax.CancellableStream; + /** + * Streams batches of document updates and deletes, in order. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1beta1.WriteRequest|WriteRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1beta1.WriteResponse|WriteResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.write.js + * region_tag:firestore_v1beta1_generated_Firestore_Write_async + */ + write(options?: CallOptions): gax.CancellableStream; + /** + * Listens to changes. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1beta1.ListenRequest|ListenRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1beta1.ListenResponse|ListenResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.listen.js + * region_tag:firestore_v1beta1_generated_Firestore_Listen_async + */ + listen(options?: CallOptions): gax.CancellableStream; + /** + * Lists documents. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` + * or `messages`. + * @param {number} request.pageSize + * The maximum number of documents to return. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous List request, if any. + * @param {string} request.orderBy + * The order to sort results by. For example: `priority desc, name`. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {boolean} request.showMissing + * If the list should show missing documents. A missing document is a + * document that does not exist but has sub-documents. These documents will + * be returned with a key but will not have fields, {@link protos.google.firestore.v1beta1.Document.create_time|Document.create_time}, + * or {@link protos.google.firestore.v1beta1.Document.update_time|Document.update_time} set. + * + * Requests with `show_missing` may not specify `where` or + * `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.v1beta1.Document|Document}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDocuments(request?: protos.google.firestore.v1beta1.IListDocumentsRequest, options?: CallOptions): Promise<[ + protos.google.firestore.v1beta1.IDocument[], + protos.google.firestore.v1beta1.IListDocumentsRequest | null, + protos.google.firestore.v1beta1.IListDocumentsResponse + ]>; + listDocuments(request: protos.google.firestore.v1beta1.IListDocumentsRequest, options: CallOptions, callback: PaginationCallback): void; + listDocuments(request: protos.google.firestore.v1beta1.IListDocumentsRequest, callback: PaginationCallback): void; + /** + * Equivalent to `listDocuments`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` + * or `messages`. + * @param {number} request.pageSize + * The maximum number of documents to return. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous List request, if any. + * @param {string} request.orderBy + * The order to sort results by. For example: `priority desc, name`. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {boolean} request.showMissing + * If the list should show missing documents. A missing document is a + * document that does not exist but has sub-documents. These documents will + * be returned with a key but will not have fields, {@link protos.google.firestore.v1beta1.Document.create_time|Document.create_time}, + * or {@link protos.google.firestore.v1beta1.Document.update_time|Document.update_time} set. + * + * Requests with `show_missing` may not specify `where` or + * `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1beta1.Document|Document} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDocumentsStream(request?: protos.google.firestore.v1beta1.IListDocumentsRequest, options?: CallOptions): Transform; + /** + * Equivalent to `listDocuments`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` + * or `messages`. + * @param {number} request.pageSize + * The maximum number of documents to return. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous List request, if any. + * @param {string} request.orderBy + * The order to sort results by. For example: `priority desc, name`. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {boolean} request.showMissing + * If the list should show missing documents. A missing document is a + * document that does not exist but has sub-documents. These documents will + * be returned with a key but will not have fields, {@link protos.google.firestore.v1beta1.Document.create_time|Document.create_time}, + * or {@link protos.google.firestore.v1beta1.Document.update_time|Document.update_time} set. + * + * Requests with `show_missing` may not specify `where` or + * `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1beta1.Document|Document}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.list_documents.js + * region_tag:firestore_v1beta1_generated_Firestore_ListDocuments_async + */ + listDocumentsAsync(request?: protos.google.firestore.v1beta1.IListDocumentsRequest, options?: CallOptions): AsyncIterable; + /** + * Partitions a query by returning partition cursors that can be used to run + * the query in parallel. The returned partition cursors are split points that + * can be used by RunQuery as starting/end points for the query results. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1beta1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.v1beta1.Cursor|Cursor}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + partitionQuery(request?: protos.google.firestore.v1beta1.IPartitionQueryRequest, options?: CallOptions): Promise<[ + protos.google.firestore.v1beta1.ICursor[], + protos.google.firestore.v1beta1.IPartitionQueryRequest | null, + protos.google.firestore.v1beta1.IPartitionQueryResponse + ]>; + partitionQuery(request: protos.google.firestore.v1beta1.IPartitionQueryRequest, options: CallOptions, callback: PaginationCallback): void; + partitionQuery(request: protos.google.firestore.v1beta1.IPartitionQueryRequest, callback: PaginationCallback): void; + /** + * Equivalent to `partitionQuery`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1beta1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1beta1.Cursor|Cursor} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + partitionQueryStream(request?: protos.google.firestore.v1beta1.IPartitionQueryRequest, options?: CallOptions): Transform; + /** + * Equivalent to `partitionQuery`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1beta1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1beta1.Cursor|Cursor}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.partition_query.js + * region_tag:firestore_v1beta1_generated_Firestore_PartitionQuery_async + */ + partitionQueryAsync(request?: protos.google.firestore.v1beta1.IPartitionQueryRequest, options?: CallOptions): AsyncIterable; + /** + * Lists all the collection IDs underneath a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1beta1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of string. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listCollectionIds(request?: protos.google.firestore.v1beta1.IListCollectionIdsRequest, options?: CallOptions): Promise<[ + string[], + protos.google.firestore.v1beta1.IListCollectionIdsRequest | null, + protos.google.firestore.v1beta1.IListCollectionIdsResponse + ]>; + listCollectionIds(request: protos.google.firestore.v1beta1.IListCollectionIdsRequest, options: CallOptions, callback: PaginationCallback): void; + listCollectionIds(request: protos.google.firestore.v1beta1.IListCollectionIdsRequest, callback: PaginationCallback): void; + /** + * Equivalent to `listCollectionIds`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1beta1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing string on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listCollectionIdsStream(request?: protos.google.firestore.v1beta1.IListCollectionIdsRequest, options?: CallOptions): Transform; + /** + * Equivalent to `listCollectionIds`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1beta1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * string. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.list_collection_ids.js + * region_tag:firestore_v1beta1_generated_Firestore_ListCollectionIds_async + */ + listCollectionIdsAsync(request?: protos.google.firestore.v1beta1.IListCollectionIdsRequest, options?: CallOptions): AsyncIterable; + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise; +} diff --git a/node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_client.js b/node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_client.js new file mode 100644 index 0000000..0978e95 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_client.js @@ -0,0 +1,1057 @@ +"use strict"; +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirestoreClient = void 0; +const stream_1 = require("stream"); +const jsonProtos = require("../../protos/v1beta1.json"); +/** + * Client JSON configuration object, loaded from + * `src/v1beta1/firestore_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +const gapicConfig = require("./firestore_client_config.json"); +// tslint:disable deprecation +const version = require('../../../package.json').version; +/** + * The Cloud Firestore service. + * + * Cloud Firestore is a fast, fully managed, serverless, cloud-native NoSQL + * document database that simplifies storing, syncing, and querying data for + * your mobile, web, and IoT apps at global scale. Its client libraries provide + * live synchronization and offline support, while its security features and + * integrations with Firebase and Google Cloud Platform (GCP) accelerate + * building truly serverless apps. + * @class + * @deprecated Use v1/firestore_client instead. + * @memberof v1beta1 + */ +class FirestoreClient { + /** + * Construct an instance of FirestoreClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param {string} [options.apiEndpoint] - The domain name of the + * API remote host. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new FirestoreClient({fallback: true}, gax); + * ``` + */ + constructor(opts, gaxInstance) { + var _a, _b, _c, _d, _e; + this._terminated = false; + this.descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + // Ensure that options include all the required fields. + const staticMembers = this.constructor; + if ((opts === null || opts === void 0 ? void 0 : opts.universe_domain) && + (opts === null || opts === void 0 ? void 0 : opts.universeDomain) && + (opts === null || opts === void 0 ? void 0 : opts.universe_domain) !== (opts === null || opts === void 0 ? void 0 : opts.universeDomain)) { + throw new Error('Please set either universe_domain or universeDomain, but not both.'); + } + const universeDomainEnvVar = typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + (_c = (_b = (_a = opts === null || opts === void 0 ? void 0 : opts.universeDomain) !== null && _a !== void 0 ? _a : opts === null || opts === void 0 ? void 0 : opts.universe_domain) !== null && _b !== void 0 ? _b : universeDomainEnvVar) !== null && _c !== void 0 ? _c : 'googleapis.com'; + this._servicePath = 'firestore.' + this._universeDomain; + const servicePath = (opts === null || opts === void 0 ? void 0 : opts.servicePath) || (opts === null || opts === void 0 ? void 0 : opts.apiEndpoint) || this._servicePath; + this._providedCustomServicePath = !!((opts === null || opts === void 0 ? void 0 : opts.servicePath) || (opts === null || opts === void 0 ? void 0 : opts.apiEndpoint)); + const port = (opts === null || opts === void 0 ? void 0 : opts.port) || staticMembers.port; + const clientConfig = (_d = opts === null || opts === void 0 ? void 0 : opts.clientConfig) !== null && _d !== void 0 ? _d : {}; + const fallback = (_e = opts === null || opts === void 0 ? void 0 : opts.fallback) !== null && _e !== void 0 ? _e : (typeof window !== 'undefined' && typeof (window === null || window === void 0 ? void 0 : window.fetch) === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); + // Request numeric enum values if REST transport is used. + opts.numericEnums = true; + // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. + if (servicePath !== this._servicePath && !('scopes' in opts)) { + opts['scopes'] = staticMembers.scopes; + } + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax'); + } + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + // Save options to use in initialize() method. + this._opts = opts; + // Save the auth object to the client, for use by other methods. + this.auth = this._gaxGrpc.auth; + // Set useJWTAccessWithScope on the auth object. + this.auth.useJWTAccessWithScope = true; + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + // Determine the client header string. + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } + else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } + else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + // Some of the methods on this service return "paged" results, + // (e.g. 50 results at a time, with tokens to get subsequent + // pages). Denote the keys used for pagination and results. + this.descriptors.page = { + listDocuments: new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'documents'), + partitionQuery: new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'partitions'), + listCollectionIds: new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'collectionIds'), + }; + // Some of the methods on this service provide streaming responses. + // Provide descriptors for these. + this.descriptors.stream = { + batchGetDocuments: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), + runQuery: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), + write: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), + listen: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), + }; + // Put together the default options sent with requests. + this._defaults = this._gaxGrpc.constructSettings('google.firestore.v1beta1.Firestore', gapicConfig, opts.clientConfig || {}, { 'x-goog-api-client': clientHeader.join(' ') }); + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.firestoreStub) { + return this.firestoreStub; + } + // Put together the "service stub" for + // google.firestore.v1beta1.Firestore. + this.firestoreStub = this._gaxGrpc.createStub(this._opts.fallback + ? this._protos.lookupService('google.firestore.v1beta1.Firestore') + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._protos.google.firestore.v1beta1.Firestore, this._opts, this._providedCustomServicePath); + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const firestoreStubMethods = [ + 'getDocument', + 'listDocuments', + 'updateDocument', + 'deleteDocument', + 'batchGetDocuments', + 'beginTransaction', + 'commit', + 'rollback', + 'runQuery', + 'partitionQuery', + 'write', + 'listen', + 'listCollectionIds', + 'batchWrite', + 'createDocument', + ]; + for (const methodName of firestoreStubMethods) { + const callPromise = this.firestoreStub.then(stub => (...args) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new stream_1.PassThrough({ objectMode: true }); + setImmediate(() => { + stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.')); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, (err) => () => { + throw err; + }); + const descriptor = this.descriptors.page[methodName] || + this.descriptors.stream[methodName] || + undefined; + const apiCall = this._gaxModule.createApiCall(callPromise, this._defaults[methodName], descriptor, this._opts.fallback); + this.innerApiCalls[methodName] = apiCall; + } + return this.firestoreStub; + } + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath() { + if (typeof process === 'object' && + typeof process.emitWarning === 'function') { + process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'firestore.googleapis.com'; + } + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint() { + if (typeof process === 'object' && + typeof process.emitWarning === 'function') { + process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'firestore.googleapis.com'; + } + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + get universeDomain() { + return this._universeDomain; + } + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/datastore', + ]; + } + /** + * Return the project ID used by this class. + * @returns {Promise} A promise that resolves to string containing the project ID. + */ + getProjectId(callback) { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + getDocument(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: (_a = request.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.getDocument(request, options, callback); + } + updateDocument(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'document.name': (_a = request.document.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.updateDocument(request, options, callback); + } + deleteDocument(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: (_a = request.name) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.deleteDocument(request, options, callback); + } + beginTransaction(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: (_a = request.database) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.beginTransaction(request, options, callback); + } + commit(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: (_a = request.database) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.commit(request, options, callback); + } + rollback(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: (_a = request.database) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.rollback(request, options, callback); + } + batchWrite(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: (_a = request.database) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.batchWrite(request, options, callback); + } + createDocument(request, optionsOrCallback, callback) { + var _a, _b; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + collection_id: (_b = request.collectionId) !== null && _b !== void 0 ? _b : '', + }); + this.initialize(); + return this.innerApiCalls.createDocument(request, options, callback); + } + /** + * Gets multiple documents. + * + * Documents returned by this method are not guaranteed to be returned in the + * same order that they were requested. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.documents + * The names of the documents to retrieve. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * The request will fail if any of the document is not a child resource of the + * given `database`. Duplicate names will be elided. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field will + * not be returned in the response. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.firestore.v1beta1.TransactionOptions} request.newTransaction + * Starts a new transaction and reads the documents. + * Defaults to a read-only transaction. + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1beta1.BatchGetDocumentsResponse|BatchGetDocumentsResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.batch_get_documents.js + * region_tag:firestore_v1beta1_generated_Firestore_BatchGetDocuments_async + */ + batchGetDocuments(request, options) { + var _a; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: (_a = request.database) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.batchGetDocuments(request, options); + } + /** + * Runs a query. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {google.firestore.v1beta1.StructuredQuery} request.structuredQuery + * A structured query. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.firestore.v1beta1.TransactionOptions} request.newTransaction + * Starts a new transaction and reads the documents. + * Defaults to a read-only transaction. + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1beta1.RunQueryResponse|RunQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.run_query.js + * region_tag:firestore_v1beta1_generated_Firestore_RunQuery_async + */ + runQuery(request, options) { + var _a; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.runQuery(request, options); + } + /** + * Streams batches of document updates and deletes, in order. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1beta1.WriteRequest|WriteRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1beta1.WriteResponse|WriteResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.write.js + * region_tag:firestore_v1beta1_generated_Firestore_Write_async + */ + write(options) { + this.initialize(); + return this.innerApiCalls.write(null, options); + } + /** + * Listens to changes. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1beta1.ListenRequest|ListenRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1beta1.ListenResponse|ListenResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.listen.js + * region_tag:firestore_v1beta1_generated_Firestore_Listen_async + */ + listen(options) { + this.initialize(); + return this.innerApiCalls.listen(null, options); + } + listDocuments(request, optionsOrCallback, callback) { + var _a, _b; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + collection_id: (_b = request.collectionId) !== null && _b !== void 0 ? _b : '', + }); + this.initialize(); + return this.innerApiCalls.listDocuments(request, options, callback); + } + /** + * Equivalent to `listDocuments`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` + * or `messages`. + * @param {number} request.pageSize + * The maximum number of documents to return. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous List request, if any. + * @param {string} request.orderBy + * The order to sort results by. For example: `priority desc, name`. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {boolean} request.showMissing + * If the list should show missing documents. A missing document is a + * document that does not exist but has sub-documents. These documents will + * be returned with a key but will not have fields, {@link protos.google.firestore.v1beta1.Document.create_time|Document.create_time}, + * or {@link protos.google.firestore.v1beta1.Document.update_time|Document.update_time} set. + * + * Requests with `show_missing` may not specify `where` or + * `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1beta1.Document|Document} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDocumentsStream(request, options) { + var _a, _b; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + collection_id: (_b = request.collectionId) !== null && _b !== void 0 ? _b : '', + }); + const defaultCallSettings = this._defaults['listDocuments']; + const callSettings = defaultCallSettings.merge(options); + this.initialize(); + return this.descriptors.page.listDocuments.createStream(this.innerApiCalls.listDocuments, request, callSettings); + } + /** + * Equivalent to `listDocuments`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` + * or `messages`. + * @param {number} request.pageSize + * The maximum number of documents to return. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous List request, if any. + * @param {string} request.orderBy + * The order to sort results by. For example: `priority desc, name`. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {boolean} request.showMissing + * If the list should show missing documents. A missing document is a + * document that does not exist but has sub-documents. These documents will + * be returned with a key but will not have fields, {@link protos.google.firestore.v1beta1.Document.create_time|Document.create_time}, + * or {@link protos.google.firestore.v1beta1.Document.update_time|Document.update_time} set. + * + * Requests with `show_missing` may not specify `where` or + * `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1beta1.Document|Document}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.list_documents.js + * region_tag:firestore_v1beta1_generated_Firestore_ListDocuments_async + */ + listDocumentsAsync(request, options) { + var _a, _b; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + collection_id: (_b = request.collectionId) !== null && _b !== void 0 ? _b : '', + }); + const defaultCallSettings = this._defaults['listDocuments']; + const callSettings = defaultCallSettings.merge(options); + this.initialize(); + return this.descriptors.page.listDocuments.asyncIterate(this.innerApiCalls['listDocuments'], request, callSettings); + } + partitionQuery(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.partitionQuery(request, options, callback); + } + /** + * Equivalent to `partitionQuery`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1beta1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1beta1.Cursor|Cursor} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + partitionQueryStream(request, options) { + var _a; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + const defaultCallSettings = this._defaults['partitionQuery']; + const callSettings = defaultCallSettings.merge(options); + this.initialize(); + return this.descriptors.page.partitionQuery.createStream(this.innerApiCalls.partitionQuery, request, callSettings); + } + /** + * Equivalent to `partitionQuery`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1beta1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1beta1.Cursor|Cursor}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.partition_query.js + * region_tag:firestore_v1beta1_generated_Firestore_PartitionQuery_async + */ + partitionQueryAsync(request, options) { + var _a; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + const defaultCallSettings = this._defaults['partitionQuery']; + const callSettings = defaultCallSettings.merge(options); + this.initialize(); + return this.descriptors.page.partitionQuery.asyncIterate(this.innerApiCalls['partitionQuery'], request, callSettings); + } + listCollectionIds(request, optionsOrCallback, callback) { + var _a; + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + this.initialize(); + return this.innerApiCalls.listCollectionIds(request, options, callback); + } + /** + * Equivalent to `listCollectionIds`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1beta1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing string on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listCollectionIdsStream(request, options) { + var _a; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + const defaultCallSettings = this._defaults['listCollectionIds']; + const callSettings = defaultCallSettings.merge(options); + this.initialize(); + return this.descriptors.page.listCollectionIds.createStream(this.innerApiCalls.listCollectionIds, request, callSettings); + } + /** + * Equivalent to `listCollectionIds`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1beta1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * string. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.list_collection_ids.js + * region_tag:firestore_v1beta1_generated_Firestore_ListCollectionIds_async + */ + listCollectionIdsAsync(request, options) { + var _a; + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: (_a = request.parent) !== null && _a !== void 0 ? _a : '', + }); + const defaultCallSettings = this._defaults['listCollectionIds']; + const callSettings = defaultCallSettings.merge(options); + this.initialize(); + return this.descriptors.page.listCollectionIds.asyncIterate(this.innerApiCalls['listCollectionIds'], request, callSettings); + } + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close() { + if (this.firestoreStub && !this._terminated) { + return this.firestoreStub.then(stub => { + this._terminated = true; + stub.close(); + }); + } + return Promise.resolve(); + } +} +exports.FirestoreClient = FirestoreClient; +//# sourceMappingURL=firestore_client.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_client_config.json b/node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_client_config.json new file mode 100644 index 0000000..b0366d6 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_client_config.json @@ -0,0 +1,99 @@ +{ + "interfaces": { + "google.firestore.v1beta1.Firestore": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "GetDocument": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "ListDocuments": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "UpdateDocument": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "DeleteDocument": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "BatchGetDocuments": { + "timeout_millis": 300000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "BeginTransaction": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "Commit": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "Rollback": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "RunQuery": { + "timeout_millis": 300000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "PartitionQuery": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "Write": { + "timeout_millis": 86400000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "Listen": { + "timeout_millis": 86400000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "ListCollectionIds": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "BatchWrite": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "CreateDocument": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_proto_list.json b/node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_proto_list.json new file mode 100644 index 0000000..735b795 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_proto_list.json @@ -0,0 +1,8 @@ +[ + "../../protos/google/firestore/v1beta1/common.proto", + "../../protos/google/firestore/v1beta1/document.proto", + "../../protos/google/firestore/v1beta1/firestore.proto", + "../../protos/google/firestore/v1beta1/query.proto", + "../../protos/google/firestore/v1beta1/undeliverable_first_gen_event.proto", + "../../protos/google/firestore/v1beta1/write.proto" +] diff --git a/node_modules/@google-cloud/firestore/build/src/v1beta1/gapic_metadata.json b/node_modules/@google-cloud/firestore/build/src/v1beta1/gapic_metadata.json new file mode 100644 index 0000000..90ed69d --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/v1beta1/gapic_metadata.json @@ -0,0 +1,165 @@ +{ + "schema": "1.0", + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "typescript", + "protoPackage": "google.firestore.v1beta1", + "libraryPackage": "@google-cloud/firestore", + "services": { + "Firestore": { + "clients": { + "grpc": { + "libraryClient": "FirestoreClient", + "rpcs": { + "GetDocument": { + "methods": [ + "getDocument" + ] + }, + "UpdateDocument": { + "methods": [ + "updateDocument" + ] + }, + "DeleteDocument": { + "methods": [ + "deleteDocument" + ] + }, + "BeginTransaction": { + "methods": [ + "beginTransaction" + ] + }, + "Commit": { + "methods": [ + "commit" + ] + }, + "Rollback": { + "methods": [ + "rollback" + ] + }, + "BatchWrite": { + "methods": [ + "batchWrite" + ] + }, + "CreateDocument": { + "methods": [ + "createDocument" + ] + }, + "BatchGetDocuments": { + "methods": [ + "batchGetDocuments" + ] + }, + "RunQuery": { + "methods": [ + "runQuery" + ] + }, + "Write": { + "methods": [ + "write" + ] + }, + "Listen": { + "methods": [ + "listen" + ] + }, + "ListDocuments": { + "methods": [ + "listDocuments", + "listDocumentsStream", + "listDocumentsAsync" + ] + }, + "PartitionQuery": { + "methods": [ + "partitionQuery", + "partitionQueryStream", + "partitionQueryAsync" + ] + }, + "ListCollectionIds": { + "methods": [ + "listCollectionIds", + "listCollectionIdsStream", + "listCollectionIdsAsync" + ] + } + } + }, + "grpc-fallback": { + "libraryClient": "FirestoreClient", + "rpcs": { + "GetDocument": { + "methods": [ + "getDocument" + ] + }, + "UpdateDocument": { + "methods": [ + "updateDocument" + ] + }, + "DeleteDocument": { + "methods": [ + "deleteDocument" + ] + }, + "BeginTransaction": { + "methods": [ + "beginTransaction" + ] + }, + "Commit": { + "methods": [ + "commit" + ] + }, + "Rollback": { + "methods": [ + "rollback" + ] + }, + "BatchWrite": { + "methods": [ + "batchWrite" + ] + }, + "CreateDocument": { + "methods": [ + "createDocument" + ] + }, + "ListDocuments": { + "methods": [ + "listDocuments", + "listDocumentsStream", + "listDocumentsAsync" + ] + }, + "PartitionQuery": { + "methods": [ + "partitionQuery", + "partitionQueryStream", + "partitionQueryAsync" + ] + }, + "ListCollectionIds": { + "methods": [ + "listCollectionIds", + "listCollectionIdsStream", + "listCollectionIdsAsync" + ] + } + } + } + } + } + } +} diff --git a/node_modules/@google-cloud/firestore/build/src/v1beta1/index.d.ts b/node_modules/@google-cloud/firestore/build/src/v1beta1/index.d.ts new file mode 100644 index 0000000..aea3d26 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/v1beta1/index.d.ts @@ -0,0 +1,2 @@ +import { FirestoreClient } from './firestore_client'; +export { FirestoreClient }; diff --git a/node_modules/@google-cloud/firestore/build/src/v1beta1/index.js b/node_modules/@google-cloud/firestore/build/src/v1beta1/index.js new file mode 100644 index 0000000..2114733 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/v1beta1/index.js @@ -0,0 +1,28 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirestoreClient = void 0; +// tslint:disable deprecation +const firestore_client_1 = require("./firestore_client"); +Object.defineProperty(exports, "FirestoreClient", { enumerable: true, get: function () { return firestore_client_1.FirestoreClient; } }); +// Doing something really horrible for reverse compatibility with original JavaScript exports +const existingExports = module.exports; +module.exports = firestore_client_1.FirestoreClient; +module.exports = Object.assign(module.exports, existingExports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/validate.d.ts b/node_modules/@google-cloud/firestore/build/src/validate.d.ts new file mode 100644 index 0000000..c4ae32c --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/validate.d.ts @@ -0,0 +1,178 @@ +/*! + * Copyright 2017 Google Inc. 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. + */ +import { FieldPath } from './path'; +/** + * Options to allow argument omission. + * + * @private + * @internal + */ +export interface RequiredArgumentOptions { + optional?: boolean; +} +/** + * Options to limit the range of numbers. + * + * @private + * @internal + */ +export interface NumericRangeOptions { + minValue?: number; + maxValue?: number; +} +/** + * Generates an error message to use with custom objects that cannot be + * serialized. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The value that failed serialization. + * @param path The field path that the object is assigned to. + */ +export declare function customObjectMessage(arg: string | number, value: unknown, path?: FieldPath): string; +/** + * Validates that 'value' is a function. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the function can be omitted. + */ +export declare function validateFunction(arg: string | number, value: unknown, options?: RequiredArgumentOptions): void; +/** + * Validates that 'value' is an object. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the object can be omitted. + */ +export declare function validateObject(arg: string | number, value: unknown, options?: RequiredArgumentOptions): void; +/** + * Validates that 'value' is a string. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the string can be omitted. + */ +export declare function validateString(arg: string | number, value: unknown, options?: RequiredArgumentOptions): void; +/** + * Validates that 'value' is a host. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the host can be omitted. + */ +export declare function validateHost(arg: string | number, value: unknown, options?: RequiredArgumentOptions): void; +/** + * Validates that 'value' is a boolean. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the boolean can be omitted. + */ +export declare function validateBoolean(arg: string | number, value: unknown, options?: RequiredArgumentOptions): void; +/** + * Validates that 'value' is a number. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the number can be omitted. + */ +export declare function validateNumber(arg: string | number, value: unknown, options?: RequiredArgumentOptions & NumericRangeOptions): void; +/** + * Validates that 'value' is a integer. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the integer can be omitted. + */ +export declare function validateInteger(arg: string | number, value: unknown, options?: RequiredArgumentOptions & NumericRangeOptions): void; +/** + * Validates that 'value' is a Timestamp. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the Timestamp can be omitted. + */ +export declare function validateTimestamp(arg: string | number, value: unknown, options?: RequiredArgumentOptions): void; +/** + * Generates an error message to use with invalid arguments. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param expectedType The expected input type. + */ +export declare function invalidArgumentMessage(arg: string | number, expectedType: string): string; +/** + * Enforces the 'options.optional' constraint for 'value'. + * + * @private + * @internal + * @param value The input to validate. + * @param options Whether the function can be omitted. + * @return Whether the object is omitted and is allowed to be omitted. + */ +export declare function validateOptional(value: unknown, options?: RequiredArgumentOptions): boolean; +/** + * Verifies that 'args' has at least 'minSize' elements. + * + * @private + * @internal + * @param funcName The function name to use in the error message. + * @param args The array (or array-like structure) to verify. + * @param minSize The minimum number of elements to enforce. + * @throws if the expectation is not met. + */ +export declare function validateMinNumberOfArguments(funcName: string, args: IArguments | unknown[], minSize: number): void; +/** + * Verifies that 'args' has at most 'maxSize' elements. + * + * @private + * @internal + * @param funcName The function name to use in the error message. + * @param args The array (or array-like structure) to verify. + * @param maxSize The maximum number of elements to enforce. + * @throws if the expectation is not met. + */ +export declare function validateMaxNumberOfArguments(funcName: string, args: IArguments, maxSize: number): void; +/** + * Validates that the provided named option equals one of the expected values. + * + * @param arg The argument name or argument index (for varargs methods).). + * @param value The input to validate. + * @param allowedValues A list of expected values. + * @param options Whether the input can be omitted. + * @private + * @internal + */ +export declare function validateEnumValue(arg: string | number, value: unknown, allowedValues: string[], options?: RequiredArgumentOptions): void; diff --git a/node_modules/@google-cloud/firestore/build/src/validate.js b/node_modules/@google-cloud/firestore/build/src/validate.js new file mode 100644 index 0000000..7a9420f --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/validate.js @@ -0,0 +1,331 @@ +"use strict"; +/*! + * Copyright 2017 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.customObjectMessage = customObjectMessage; +exports.validateFunction = validateFunction; +exports.validateObject = validateObject; +exports.validateString = validateString; +exports.validateHost = validateHost; +exports.validateBoolean = validateBoolean; +exports.validateNumber = validateNumber; +exports.validateInteger = validateInteger; +exports.validateTimestamp = validateTimestamp; +exports.invalidArgumentMessage = invalidArgumentMessage; +exports.validateOptional = validateOptional; +exports.validateMinNumberOfArguments = validateMinNumberOfArguments; +exports.validateMaxNumberOfArguments = validateMaxNumberOfArguments; +exports.validateEnumValue = validateEnumValue; +const url_1 = require("url"); +const util_1 = require("./util"); +const timestamp_1 = require("./timestamp"); +/** + * Generates an error message to use with custom objects that cannot be + * serialized. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The value that failed serialization. + * @param path The field path that the object is assigned to. + */ +function customObjectMessage(arg, value, path) { + const fieldPathMessage = path ? ` (found in field "${path}")` : ''; + if ((0, util_1.isObject)(value)) { + // We use the base class name as the type name as the sentinel classes + // returned by the public FieldValue API are subclasses of FieldValue. By + // using the base name, we reduce the number of special cases below. + const typeName = value.constructor.name; + switch (typeName) { + case 'DocumentReference': + case 'FieldPath': + case 'FieldValue': + case 'GeoPoint': + case 'Timestamp': + return (`${invalidArgumentMessage(arg, 'Firestore document')} Detected an object of type "${typeName}" that doesn't match the ` + + `expected instance${fieldPathMessage}. Please ensure that the ` + + 'Firestore types you are using are from the same NPM package.)'); + case 'Object': + return `${invalidArgumentMessage(arg, 'Firestore document')} Invalid use of type "${typeof value}" as a Firestore argument${fieldPathMessage}.`; + default: + return (`${invalidArgumentMessage(arg, 'Firestore document')} Couldn't serialize object of type "${typeName}"${fieldPathMessage}. Firestore doesn't support JavaScript ` + + 'objects with custom prototypes (i.e. objects that were created ' + + 'via the "new" operator).'); + } + } + else { + return `${invalidArgumentMessage(arg, 'Firestore document')} Input is not a plain JavaScript object${fieldPathMessage}.`; + } +} +/** + * Validates that 'value' is a function. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the function can be omitted. + */ +function validateFunction(arg, value, options) { + if (!validateOptional(value, options)) { + if (!(0, util_1.isFunction)(value)) { + throw new Error(invalidArgumentMessage(arg, 'function')); + } + } +} +/** + * Validates that 'value' is an object. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the object can be omitted. + */ +function validateObject(arg, value, options) { + if (!validateOptional(value, options)) { + if (!(0, util_1.isObject)(value)) { + throw new Error(invalidArgumentMessage(arg, 'object')); + } + } +} +/** + * Validates that 'value' is a string. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the string can be omitted. + */ +function validateString(arg, value, options) { + if (!validateOptional(value, options)) { + if (typeof value !== 'string') { + throw new Error(invalidArgumentMessage(arg, 'string')); + } + } +} +/** + * Validates that 'value' is a host. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the host can be omitted. + */ +function validateHost(arg, value, options) { + if (!validateOptional(value, options)) { + validateString(arg, value); + const urlString = `http://${value}/`; + let parsed; + try { + parsed = new url_1.URL(urlString); + } + catch (e) { + throw new Error(invalidArgumentMessage(arg, 'host')); + } + if (parsed.search !== '' || + parsed.pathname !== '/' || + parsed.username !== '') { + throw new Error(invalidArgumentMessage(arg, 'host')); + } + } +} +/** + * Validates that 'value' is a boolean. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the boolean can be omitted. + */ +function validateBoolean(arg, value, options) { + if (!validateOptional(value, options)) { + if (typeof value !== 'boolean') { + throw new Error(invalidArgumentMessage(arg, 'boolean')); + } + } +} +/** + * Validates that 'value' is a number. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the number can be omitted. + */ +function validateNumber(arg, value, options) { + const min = options !== undefined && options.minValue !== undefined + ? options.minValue + : -Infinity; + const max = options !== undefined && options.maxValue !== undefined + ? options.maxValue + : Infinity; + if (!validateOptional(value, options)) { + if (typeof value !== 'number' || isNaN(value)) { + throw new Error(invalidArgumentMessage(arg, 'number')); + } + else if (value < min || value > max) { + throw new Error(`${formatArgumentName(arg)} must be within [${min}, ${max}] inclusive, but was: ${value}`); + } + } +} +/** + * Validates that 'value' is a integer. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the integer can be omitted. + */ +function validateInteger(arg, value, options) { + const min = options !== undefined && options.minValue !== undefined + ? options.minValue + : -Infinity; + const max = options !== undefined && options.maxValue !== undefined + ? options.maxValue + : Infinity; + if (!validateOptional(value, options)) { + if (typeof value !== 'number' || isNaN(value) || value % 1 !== 0) { + throw new Error(invalidArgumentMessage(arg, 'integer')); + } + else if (value < min || value > max) { + throw new Error(`${formatArgumentName(arg)} must be within [${min}, ${max}] inclusive, but was: ${value}`); + } + } +} +/** + * Validates that 'value' is a Timestamp. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + * @param options Options that specify whether the Timestamp can be omitted. + */ +function validateTimestamp(arg, value, options) { + if (!validateOptional(value, options)) { + if (!(value instanceof timestamp_1.Timestamp)) { + throw new Error(invalidArgumentMessage(arg, 'Timestamp')); + } + } +} +/** + * Generates an error message to use with invalid arguments. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param expectedType The expected input type. + */ +function invalidArgumentMessage(arg, expectedType) { + return `${formatArgumentName(arg)} is not a valid ${expectedType}.`; +} +/** + * Enforces the 'options.optional' constraint for 'value'. + * + * @private + * @internal + * @param value The input to validate. + * @param options Whether the function can be omitted. + * @return Whether the object is omitted and is allowed to be omitted. + */ +function validateOptional(value, options) { + return (value === undefined && options !== undefined && options.optional === true); +} +/** + * Formats the given word as plural conditionally given the preceding number. + * + * @private + * @internal + * @param num The number to use for formatting. + * @param str The string to format. + */ +function formatPlural(num, str) { + return `${num} ${str}` + (num === 1 ? '' : 's'); +} +/** + * Creates a descriptive name for the provided argument name or index. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @return Either the argument name or its index description. + */ +function formatArgumentName(arg) { + return typeof arg === 'string' + ? `Value for argument "${arg}"` + : `Element at index ${arg}`; +} +/** + * Verifies that 'args' has at least 'minSize' elements. + * + * @private + * @internal + * @param funcName The function name to use in the error message. + * @param args The array (or array-like structure) to verify. + * @param minSize The minimum number of elements to enforce. + * @throws if the expectation is not met. + */ +function validateMinNumberOfArguments(funcName, args, minSize) { + if (args.length < minSize) { + throw new Error(`Function "${funcName}()" requires at least ` + + `${formatPlural(minSize, 'argument')}.`); + } +} +/** + * Verifies that 'args' has at most 'maxSize' elements. + * + * @private + * @internal + * @param funcName The function name to use in the error message. + * @param args The array (or array-like structure) to verify. + * @param maxSize The maximum number of elements to enforce. + * @throws if the expectation is not met. + */ +function validateMaxNumberOfArguments(funcName, args, maxSize) { + if (args.length > maxSize) { + throw new Error(`Function "${funcName}()" accepts at most ` + + `${formatPlural(maxSize, 'argument')}.`); + } +} +/** + * Validates that the provided named option equals one of the expected values. + * + * @param arg The argument name or argument index (for varargs methods).). + * @param value The input to validate. + * @param allowedValues A list of expected values. + * @param options Whether the input can be omitted. + * @private + * @internal + */ +function validateEnumValue(arg, value, allowedValues, options) { + if (!validateOptional(value, options)) { + const expectedDescription = []; + for (const allowed of allowedValues) { + if (allowed === value) { + return; + } + expectedDescription.push(allowed); + } + throw new Error(`${formatArgumentName(arg)} is invalid. Acceptable values are: ${expectedDescription.join(', ')}`); + } +} +//# sourceMappingURL=validate.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/watch.d.ts b/node_modules/@google-cloud/firestore/build/src/watch.d.ts new file mode 100644 index 0000000..cb4276e --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/watch.d.ts @@ -0,0 +1,310 @@ +/*! + * Copyright 2017 Google Inc. 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. + */ +import * as firestore from '@google-cloud/firestore'; +import { google } from '../protos/firestore_v1_proto_api'; +import { QueryDocumentSnapshot } from './document'; +import { DocumentChange } from './document-change'; +import { DocumentReference, Firestore, Query } from './index'; +import { Timestamp } from './timestamp'; +import api = google.firestore.v1; +/*! + * Idle timeout used to detect Watch streams that stall (see + * https://github.com/googleapis/nodejs-firestore/issues/1057, b/156308554). + * Under normal load, the Watch backend will send a TARGET_CHANGE message + * roughly every 30 seconds. As discussed with the backend team, we reset the + * Watch stream if we do not receive any message within 120 seconds. + */ +export declare const WATCH_IDLE_TIMEOUT_MS: number; +/** + * @private + * @internal + * @callback docsCallback + * @returns {Array.} An ordered list of documents. + */ +/** + * @private + * @internal + * @callback changeCallback + * @returns {Array.} An ordered list of document + * changes. + */ +/** + * onSnapshot() callback that receives the updated query state. + * + * @private + * @internal + * @callback watchSnapshotCallback + * + * @param {Timestamp} readTime The time at which this snapshot was obtained. + * @param {number} size The number of documents in the result set. + * @param {docsCallback} docs A callback that returns the ordered list of + * documents stored in this snapshot. + * @param {changeCallback} changes A callback that returns the list of + * changed documents since the last snapshot delivered for this watch. + */ +type DocumentComparator = (l: QueryDocumentSnapshot, r: QueryDocumentSnapshot) => number; +/** + * Watch provides listen functionality and exposes the 'onSnapshot' observer. It + * can be used with a valid Firestore Listen target. + * + * @class + * @private + * @internal + */ +declare abstract class Watch { + readonly _converter: firestore.FirestoreDataConverter; + protected readonly firestore: Firestore; + private readonly backoff; + private readonly requestTag; + /** + * Indicates whether we are interested in data from the stream. Set to false in the + * 'unsubscribe()' callback. + * @private + * @internal + */ + private isActive; + /** + * The current stream to the backend. + * @private + * @internal + */ + private currentStream; + /** + * The server assigns and updates the resume token. + * @private + * @internal + */ + private resumeToken; + /** + * A map of document names to QueryDocumentSnapshots for the last sent snapshot. + * @private + * @internal + */ + private docMap; + /** + * The accumulated map of document changes (keyed by document name) for the + * current snapshot. + * @private + * @internal + */ + private changeMap; + /** + * The current state of the query results. * + * @private + * @internal + */ + private current; + /** + * The sorted tree of QueryDocumentSnapshots as sent in the last snapshot. + * We only look at the keys. + * @private + * @internal + */ + private docTree; + /** + * We need this to track whether we've pushed an initial set of changes, + * since we should push those even when there are no changes, if there + * aren't docs. + * @private + * @internal + */ + private hasPushed; + /** + * The handler used to restart the Watch stream if it has been idle for more + * than WATCH_IDLE_TIMEOUT_MS. + */ + private idleTimeoutHandle?; + private onNext; + private onError; + /** + * @private + * @internal + * + * @param firestore The Firestore Database client. + */ + constructor(firestore: Firestore, _converter?: firestore.FirestoreDataConverter); + /** Returns a 'Target' proto denoting the target to listen on. */ + protected abstract getTarget(resumeToken?: Uint8Array): api.ITarget; + /** + * Returns a comparator for QueryDocumentSnapshots that is used to order the + * document snapshots returned by this watch. + */ + protected abstract getComparator(): DocumentComparator; + /** + * Starts a watch and attaches a listener for document change events. + * + * @private + * @internal + * @param onNext A callback to be called every time a new snapshot is + * available. + * @param onError A callback to be called if the listen fails or is cancelled. + * No further callbacks will occur. + * + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + */ + onSnapshot(onNext: (readTime: Timestamp, size: number, docs: () => Array>, changes: () => Array>) => void, onError: (error: Error) => void): () => void; + /** + * Returns the current count of all documents, including the changes from + * the current changeMap. + * @private + * @internal + */ + private currentSize; + /** + * Splits up document changes into removals, additions, and updates. + * @private + * @internal + */ + private extractCurrentChanges; + /** + * Helper to clear the docs on RESET or filter mismatch. + * @private + * @internal + */ + private resetDocs; + /** + * Closes the stream and calls onError() if the stream is still active. + * @private + * @internal + */ + private closeStream; + /** + * Re-opens the stream unless the specified error is considered permanent. + * Clears the change map. + * @private + * @internal + */ + private maybeReopenStream; + /** + * Cancels the current idle timeout and reschedules a new timer. + * + * @private + * @internal + */ + private resetIdleTimeout; + /** + * Helper to restart the outgoing stream to the backend. + * @private + * @internal + */ + private resetStream; + /** + * Initializes a new stream to the backend with backoff. + * @private + * @internal + */ + private initStream; + /** + * Handles 'data' events and closes the stream if the response type is + * invalid. + * @private + * @internal + */ + private onData; + /** + * Checks if the current target id is included in the list of target ids. + * If no targetIds are provided, returns true. + * @private + * @internal + */ + private affectsTarget; + /** + * Assembles a new snapshot from the current set of changes and invokes the + * user's callback. Clears the current changes on completion. + * @private + * @internal + */ + private pushSnapshot; + /** + * Applies a document delete to the document tree and the document map. + * Returns the corresponding DocumentChange event. + * @private + * @internal + */ + private deleteDoc; + /** + * Applies a document add to the document tree and the document map. Returns + * the corresponding DocumentChange event. + * @private + * @internal + */ + private addDoc; + /** + * Applies a document modification to the document tree and the document map. + * Returns the DocumentChange event for successful modifications. + * @private + * @internal + */ + private modifyDoc; + /** + * Applies the mutations in changeMap to both the document tree and the + * document lookup map. Modified docMap in-place and returns the updated + * state. + * @private + * @internal + */ + private computeSnapshot; + /** + * Determines whether a watch error is considered permanent and should not be + * retried. Errors that don't provide a GRPC error code are always considered + * transient in this context. + * + * @private + * @internal + * @param error An error object. + * @return Whether the error is permanent. + */ + private isPermanentWatchError; + /** + * Determines whether we need to initiate a longer backoff due to system + * overload. + * + * @private + * @internal + * @param error A GRPC Error object that exposes an error code. + * @return Whether we need to back off our retries. + */ + private isResourceExhaustedError; + /** Closes the stream and clears all timeouts. */ + private shutdown; +} +/** + * Creates a new Watch instance to listen on DocumentReferences. + * + * @private + * @internal + */ +export declare class DocumentWatch extends Watch { + private readonly ref; + constructor(firestore: Firestore, ref: DocumentReference); + getComparator(): DocumentComparator; + getTarget(resumeToken?: Uint8Array): google.firestore.v1.ITarget; +} +/** + * Creates a new Watch instance to listen on Queries. + * + * @private + * @internal + */ +export declare class QueryWatch extends Watch { + private readonly query; + private comparator; + constructor(firestore: Firestore, query: Query, converter?: firestore.FirestoreDataConverter); + getComparator(): DocumentComparator; + getTarget(resumeToken?: Uint8Array): google.firestore.v1.ITarget; +} +export {}; diff --git a/node_modules/@google-cloud/firestore/build/src/watch.js b/node_modules/@google-cloud/firestore/build/src/watch.js new file mode 100644 index 0000000..897a081 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/watch.js @@ -0,0 +1,668 @@ +"use strict"; +/*! + * Copyright 2017 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.QueryWatch = exports.DocumentWatch = exports.WATCH_IDLE_TIMEOUT_MS = void 0; +const assert = require("assert"); +const rbtree = require("functional-red-black-tree"); +const google_gax_1 = require("google-gax"); +const backoff_1 = require("./backoff"); +const document_1 = require("./document"); +const document_change_1 = require("./document-change"); +const logger_1 = require("./logger"); +const path_1 = require("./path"); +const timestamp_1 = require("./timestamp"); +const types_1 = require("./types"); +const util_1 = require("./util"); +/*! + * Target ID used by watch. Watch uses a fixed target id since we only support + * one target per stream. + * @type {number} + */ +const WATCH_TARGET_ID = 0x1; +/*! + * Idle timeout used to detect Watch streams that stall (see + * https://github.com/googleapis/nodejs-firestore/issues/1057, b/156308554). + * Under normal load, the Watch backend will send a TARGET_CHANGE message + * roughly every 30 seconds. As discussed with the backend team, we reset the + * Watch stream if we do not receive any message within 120 seconds. + */ +exports.WATCH_IDLE_TIMEOUT_MS = 120 * 1000; +/*! + * Sentinel value for a document remove. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const REMOVED = {}; +/*! + * The change type for document change events. + */ +// tslint:disable-next-line:variable-name +const ChangeType = { + added: 'added', + modified: 'modified', + removed: 'removed', +}; +/*! + * The comparator used for document watches (which should always get called with + * the same document). + */ +const DOCUMENT_WATCH_COMPARATOR = (doc1, doc2) => { + assert(doc1 === doc2, 'Document watches only support one document.'); + return 0; +}; +const EMPTY_FUNCTION = () => { }; +/** + * Watch provides listen functionality and exposes the 'onSnapshot' observer. It + * can be used with a valid Firestore Listen target. + * + * @class + * @private + * @internal + */ +class Watch { + /** + * @private + * @internal + * + * @param firestore The Firestore Database client. + */ + constructor(firestore, _converter = (0, types_1.defaultConverter)()) { + this._converter = _converter; + /** + * Indicates whether we are interested in data from the stream. Set to false in the + * 'unsubscribe()' callback. + * @private + * @internal + */ + this.isActive = true; + /** + * The current stream to the backend. + * @private + * @internal + */ + this.currentStream = null; + /** + * The server assigns and updates the resume token. + * @private + * @internal + */ + this.resumeToken = undefined; + /** + * A map of document names to QueryDocumentSnapshots for the last sent snapshot. + * @private + * @internal + */ + this.docMap = new Map(); + /** + * The accumulated map of document changes (keyed by document name) for the + * current snapshot. + * @private + * @internal + */ + this.changeMap = new Map(); + /** + * The current state of the query results. * + * @private + * @internal + */ + this.current = false; + /** + * We need this to track whether we've pushed an initial set of changes, + * since we should push those even when there are no changes, if there + * aren't docs. + * @private + * @internal + */ + this.hasPushed = false; + this.firestore = firestore; + this.backoff = new backoff_1.ExponentialBackoff(); + this.requestTag = (0, util_1.requestTag)(); + this.onNext = EMPTY_FUNCTION; + this.onError = EMPTY_FUNCTION; + } + /** + * Starts a watch and attaches a listener for document change events. + * + * @private + * @internal + * @param onNext A callback to be called every time a new snapshot is + * available. + * @param onError A callback to be called if the listen fails or is cancelled. + * No further callbacks will occur. + * + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + */ + onSnapshot(onNext, onError) { + assert(this.onNext === EMPTY_FUNCTION, 'onNext should not already be defined.'); + assert(this.onError === EMPTY_FUNCTION, 'onError should not already be defined.'); + assert(this.docTree === undefined, 'docTree should not already be defined.'); + this.onNext = onNext; + this.onError = onError; + this.docTree = rbtree(this.getComparator()); + this.initStream(); + const unsubscribe = () => { + (0, logger_1.logger)('Watch.onSnapshot', this.requestTag, 'Unsubscribe called'); + // Prevent further callbacks. + this.onNext = () => { }; + this.onError = () => { }; + this.shutdown(); + }; + this.firestore.registerListener(); + return unsubscribe; + } + /** + * Returns the current count of all documents, including the changes from + * the current changeMap. + * @private + * @internal + */ + currentSize() { + const changes = this.extractCurrentChanges(timestamp_1.Timestamp.now()); + return this.docMap.size + changes.adds.length - changes.deletes.length; + } + /** + * Splits up document changes into removals, additions, and updates. + * @private + * @internal + */ + extractCurrentChanges(readTime) { + const deletes = []; + const adds = []; + const updates = []; + this.changeMap.forEach((value, name) => { + if (value === REMOVED) { + if (this.docMap.has(name)) { + deletes.push(name); + } + } + else if (this.docMap.has(name)) { + value.readTime = readTime; + updates.push(value.build()); + } + else { + value.readTime = readTime; + adds.push(value.build()); + } + }); + return { deletes, adds, updates }; + } + /** + * Helper to clear the docs on RESET or filter mismatch. + * @private + * @internal + */ + resetDocs() { + (0, logger_1.logger)('Watch.resetDocs', this.requestTag, 'Resetting documents'); + this.changeMap.clear(); + this.resumeToken = undefined; + this.docTree.forEach((snapshot) => { + // Mark each document as deleted. If documents are not deleted, they + // will be send again by the server. + this.changeMap.set(snapshot.ref.path, REMOVED); + }); + this.current = false; + } + /** + * Closes the stream and calls onError() if the stream is still active. + * @private + * @internal + */ + closeStream(err) { + if (this.isActive) { + (0, logger_1.logger)('Watch.closeStream', this.requestTag, 'Invoking onError: ', err); + this.onError(err); + } + this.shutdown(); + } + /** + * Re-opens the stream unless the specified error is considered permanent. + * Clears the change map. + * @private + * @internal + */ + maybeReopenStream(err) { + if (this.isActive && !this.isPermanentWatchError(err)) { + (0, logger_1.logger)('Watch.maybeReopenStream', this.requestTag, 'Stream ended, re-opening after retryable error:', err); + this.changeMap.clear(); + if (this.isResourceExhaustedError(err)) { + this.backoff.resetToMax(); + } + this.initStream(); + } + else { + this.closeStream(err); + } + } + /** + * Cancels the current idle timeout and reschedules a new timer. + * + * @private + * @internal + */ + resetIdleTimeout() { + if (this.idleTimeoutHandle) { + clearTimeout(this.idleTimeoutHandle); + } + this.idleTimeoutHandle = (0, backoff_1.delayExecution)(() => { + var _a; + (0, logger_1.logger)('Watch.resetIdleTimeout', this.requestTag, 'Resetting stream after idle timeout'); + (_a = this.currentStream) === null || _a === void 0 ? void 0 : _a.end(); + this.currentStream = null; + const error = new google_gax_1.GoogleError('Watch stream idle timeout'); + error.code = google_gax_1.Status.UNKNOWN; + this.maybeReopenStream(error); + }, exports.WATCH_IDLE_TIMEOUT_MS); + } + /** + * Helper to restart the outgoing stream to the backend. + * @private + * @internal + */ + resetStream() { + (0, logger_1.logger)('Watch.resetStream', this.requestTag, 'Restarting stream'); + if (this.currentStream) { + this.currentStream.end(); + this.currentStream = null; + } + this.initStream(); + } + /** + * Initializes a new stream to the backend with backoff. + * @private + * @internal + */ + initStream() { + this.backoff + .backoffAndWait() + .then(async () => { + if (!this.isActive) { + (0, logger_1.logger)('Watch.initStream', this.requestTag, 'Not initializing inactive stream'); + return; + } + await this.firestore.initializeIfNeeded(this.requestTag); + const request = {}; + request.database = this.firestore.formattedName; + request.addTarget = this.getTarget(this.resumeToken); + // Note that we need to call the internal _listen API to pass additional + // header values in readWriteStream. + return this.firestore + .requestStream('listen', + /* bidirectional= */ true, request, this.requestTag) + .then(backendStream => { + if (!this.isActive) { + (0, logger_1.logger)('Watch.initStream', this.requestTag, 'Closing inactive stream'); + backendStream.emit('end'); + backendStream.on('error', () => { + // Note that emitting 'end' above does not prevent the Duplex + // from receiving potential errors from the backend. Since the + // stream is no longer active (`isActive` is false), we + // swallow / ignore any errors it may receive. + }); + return; + } + (0, logger_1.logger)('Watch.initStream', this.requestTag, 'Opened new stream'); + this.currentStream = backendStream; + this.resetIdleTimeout(); + this.currentStream.on('data', (proto) => { + this.resetIdleTimeout(); + this.onData(proto); + }) + .on('error', err => { + if (this.currentStream === backendStream) { + this.currentStream = null; + this.maybeReopenStream(err); + } + }) + .on('end', () => { + if (this.currentStream === backendStream) { + this.currentStream = null; + const err = new google_gax_1.GoogleError('Stream ended unexpectedly'); + err.code = google_gax_1.Status.UNKNOWN; + this.maybeReopenStream(err); + } + }); + this.currentStream.resume(); + }); + }) + .catch(err => { + this.closeStream(err); + }); + } + /** + * Handles 'data' events and closes the stream if the response type is + * invalid. + * @private + * @internal + */ + onData(proto) { + if (proto.targetChange) { + (0, logger_1.logger)('Watch.onData', this.requestTag, 'Processing target change'); + const change = proto.targetChange; + const noTargetIds = !change.targetIds || change.targetIds.length === 0; + if (change.targetChangeType === 'NO_CHANGE') { + if (noTargetIds && change.readTime && this.current) { + // This means everything is up-to-date, so emit the current + // set of docs as a snapshot, if there were changes. + this.pushSnapshot(timestamp_1.Timestamp.fromProto(change.readTime), change.resumeToken); + } + } + else if (change.targetChangeType === 'ADD') { + if (WATCH_TARGET_ID !== change.targetIds[0]) { + this.closeStream(Error('Unexpected target ID sent by server')); + } + } + else if (change.targetChangeType === 'REMOVE') { + let code = google_gax_1.Status.INTERNAL; + let message = 'internal error'; + if (change.cause) { + code = change.cause.code; + message = change.cause.message; + } + // @todo: Surface a .code property on the exception. + this.closeStream(new Error('Error ' + code + ': ' + message)); + } + else if (change.targetChangeType === 'RESET') { + // Whatever changes have happened so far no longer matter. + this.resetDocs(); + } + else if (change.targetChangeType === 'CURRENT') { + this.current = true; + } + else { + this.closeStream(new Error('Unknown target change type: ' + JSON.stringify(change))); + } + if (change.resumeToken && + this.affectsTarget(change.targetIds, WATCH_TARGET_ID)) { + this.backoff.reset(); + } + } + else if (proto.documentChange) { + (0, logger_1.logger)('Watch.onData', this.requestTag, 'Processing change event'); + // No other targetIds can show up here, but we still need to see + // if the targetId was in the added list or removed list. + const targetIds = proto.documentChange.targetIds || []; + const removedTargetIds = proto.documentChange.removedTargetIds || []; + let changed = false; + let removed = false; + for (let i = 0; i < targetIds.length; i++) { + if (targetIds[i] === WATCH_TARGET_ID) { + changed = true; + } + } + for (let i = 0; i < removedTargetIds.length; i++) { + if (removedTargetIds[i] === WATCH_TARGET_ID) { + removed = true; + } + } + const document = proto.documentChange.document; + const name = document.name; + const relativeName = path_1.QualifiedResourcePath.fromSlashSeparatedString(name).relativeName; + if (changed) { + (0, logger_1.logger)('Watch.onData', this.requestTag, 'Received document change'); + const ref = this.firestore.doc(relativeName); + const snapshot = new document_1.DocumentSnapshotBuilder(ref.withConverter(this._converter)); + snapshot.fieldsProto = document.fields || {}; + snapshot.createTime = timestamp_1.Timestamp.fromProto(document.createTime); + snapshot.updateTime = timestamp_1.Timestamp.fromProto(document.updateTime); + this.changeMap.set(relativeName, snapshot); + } + else if (removed) { + (0, logger_1.logger)('Watch.onData', this.requestTag, 'Received document remove'); + this.changeMap.set(relativeName, REMOVED); + } + } + else if (proto.documentDelete || proto.documentRemove) { + (0, logger_1.logger)('Watch.onData', this.requestTag, 'Processing remove event'); + const name = (proto.documentDelete || proto.documentRemove).document; + const relativeName = path_1.QualifiedResourcePath.fromSlashSeparatedString(name).relativeName; + this.changeMap.set(relativeName, REMOVED); + } + else if (proto.filter) { + (0, logger_1.logger)('Watch.onData', this.requestTag, 'Processing filter update'); + if (proto.filter.count !== this.currentSize()) { + // We need to remove all the current results. + this.resetDocs(); + // The filter didn't match, so re-issue the query. + this.resetStream(); + } + } + else { + this.closeStream(new Error('Unknown listen response type: ' + JSON.stringify(proto))); + } + } + /** + * Checks if the current target id is included in the list of target ids. + * If no targetIds are provided, returns true. + * @private + * @internal + */ + affectsTarget(targetIds, currentId) { + if (targetIds === undefined || targetIds.length === 0) { + return true; + } + for (const targetId of targetIds) { + if (targetId === currentId) { + return true; + } + } + return false; + } + /** + * Assembles a new snapshot from the current set of changes and invokes the + * user's callback. Clears the current changes on completion. + * @private + * @internal + */ + pushSnapshot(readTime, nextResumeToken) { + const appliedChanges = this.computeSnapshot(readTime); + if (!this.hasPushed || appliedChanges.length > 0) { + (0, logger_1.logger)('Watch.pushSnapshot', this.requestTag, 'Sending snapshot with %d changes and %d documents', String(appliedChanges.length), this.docTree.length); + // We pass the current set of changes, even if `docTree` is modified later. + const currentTree = this.docTree; + this.onNext(readTime, currentTree.length, () => currentTree.keys, () => appliedChanges); + this.hasPushed = true; + } + this.changeMap.clear(); + this.resumeToken = nextResumeToken; + } + /** + * Applies a document delete to the document tree and the document map. + * Returns the corresponding DocumentChange event. + * @private + * @internal + */ + deleteDoc(name) { + assert(this.docMap.has(name), 'Document to delete does not exist'); + const oldDocument = this.docMap.get(name); + const existing = this.docTree.find(oldDocument); + const oldIndex = existing.index; + this.docTree = existing.remove(); + this.docMap.delete(name); + return new document_change_1.DocumentChange(ChangeType.removed, oldDocument, oldIndex, -1); + } + /** + * Applies a document add to the document tree and the document map. Returns + * the corresponding DocumentChange event. + * @private + * @internal + */ + addDoc(newDocument) { + const name = newDocument.ref.path; + assert(!this.docMap.has(name), 'Document to add already exists'); + this.docTree = this.docTree.insert(newDocument, null); + const newIndex = this.docTree.find(newDocument).index; + this.docMap.set(name, newDocument); + return new document_change_1.DocumentChange(ChangeType.added, newDocument, -1, newIndex); + } + /** + * Applies a document modification to the document tree and the document map. + * Returns the DocumentChange event for successful modifications. + * @private + * @internal + */ + modifyDoc(newDocument) { + const name = newDocument.ref.path; + assert(this.docMap.has(name), 'Document to modify does not exist'); + const oldDocument = this.docMap.get(name); + if (!oldDocument.updateTime.isEqual(newDocument.updateTime)) { + const removeChange = this.deleteDoc(name); + const addChange = this.addDoc(newDocument); + return new document_change_1.DocumentChange(ChangeType.modified, newDocument, removeChange.oldIndex, addChange.newIndex); + } + return null; + } + /** + * Applies the mutations in changeMap to both the document tree and the + * document lookup map. Modified docMap in-place and returns the updated + * state. + * @private + * @internal + */ + computeSnapshot(readTime) { + const changeSet = this.extractCurrentChanges(readTime); + const appliedChanges = []; + // Process the sorted changes in the order that is expected by our clients + // (removals, additions, and then modifications). We also need to sort the + // individual changes to assure that oldIndex/newIndex keep incrementing. + changeSet.deletes.sort((name1, name2) => { + // Deletes are sorted based on the order of the existing document. + return this.getComparator()(this.docMap.get(name1), this.docMap.get(name2)); + }); + changeSet.deletes.forEach(name => { + const change = this.deleteDoc(name); + appliedChanges.push(change); + }); + changeSet.adds.sort(this.getComparator()); + changeSet.adds.forEach(snapshot => { + const change = this.addDoc(snapshot); + appliedChanges.push(change); + }); + changeSet.updates.sort(this.getComparator()); + changeSet.updates.forEach(snapshot => { + const change = this.modifyDoc(snapshot); + if (change) { + appliedChanges.push(change); + } + }); + assert(this.docTree.length === this.docMap.size, 'The update document ' + + 'tree and document map should have the same number of entries.'); + return appliedChanges; + } + /** + * Determines whether a watch error is considered permanent and should not be + * retried. Errors that don't provide a GRPC error code are always considered + * transient in this context. + * + * @private + * @internal + * @param error An error object. + * @return Whether the error is permanent. + */ + isPermanentWatchError(error) { + if (error.code === undefined) { + (0, logger_1.logger)('Watch.isPermanentError', this.requestTag, 'Unable to determine error code: ', error); + return false; + } + switch (error.code) { + case google_gax_1.Status.ABORTED: + case google_gax_1.Status.CANCELLED: + case google_gax_1.Status.UNKNOWN: + case google_gax_1.Status.DEADLINE_EXCEEDED: + case google_gax_1.Status.RESOURCE_EXHAUSTED: + case google_gax_1.Status.INTERNAL: + case google_gax_1.Status.UNAVAILABLE: + case google_gax_1.Status.UNAUTHENTICATED: + return false; + default: + return true; + } + } + /** + * Determines whether we need to initiate a longer backoff due to system + * overload. + * + * @private + * @internal + * @param error A GRPC Error object that exposes an error code. + * @return Whether we need to back off our retries. + */ + isResourceExhaustedError(error) { + return error.code === google_gax_1.Status.RESOURCE_EXHAUSTED; + } + /** Closes the stream and clears all timeouts. */ + shutdown() { + var _a; + if (this.isActive) { + this.isActive = false; + if (this.idleTimeoutHandle) { + clearTimeout(this.idleTimeoutHandle); + this.idleTimeoutHandle = undefined; + } + this.firestore.unregisterListener(); + } + (_a = this.currentStream) === null || _a === void 0 ? void 0 : _a.end(); + this.currentStream = null; + } +} +/** + * Creates a new Watch instance to listen on DocumentReferences. + * + * @private + * @internal + */ +class DocumentWatch extends Watch { + constructor(firestore, ref) { + super(firestore, ref._converter); + this.ref = ref; + } + getComparator() { + return DOCUMENT_WATCH_COMPARATOR; + } + getTarget(resumeToken) { + const formattedName = this.ref.formattedName; + return { + documents: { + documents: [formattedName], + }, + targetId: WATCH_TARGET_ID, + resumeToken, + }; + } +} +exports.DocumentWatch = DocumentWatch; +/** + * Creates a new Watch instance to listen on Queries. + * + * @private + * @internal + */ +class QueryWatch extends Watch { + constructor(firestore, query, converter) { + super(firestore, converter); + this.query = query; + this.comparator = query.comparator(); + } + getComparator() { + return this.query.comparator(); + } + getTarget(resumeToken) { + const query = this.query.toProto(); + return { query, targetId: WATCH_TARGET_ID, resumeToken }; + } +} +exports.QueryWatch = QueryWatch; +//# sourceMappingURL=watch.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/write-batch.d.ts b/node_modules/@google-cloud/firestore/build/src/write-batch.d.ts new file mode 100644 index 0000000..c8fdda3 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/write-batch.d.ts @@ -0,0 +1,287 @@ +/*! + * Copyright 2019 Google Inc. 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. + */ +import * as firestore from '@google-cloud/firestore'; +import { google } from '../protos/firestore_v1_proto_api'; +import { Firestore } from './index'; +import { FieldPath } from './path'; +import { Timestamp } from './timestamp'; +import { FirestoreUnaryMethod } from './types'; +import { RequiredArgumentOptions } from './validate'; +import api = google.firestore.v1; +/** + * A WriteResult wraps the write time set by the Firestore servers on sets(), + * updates(), and creates(). + * + * @class WriteResult + */ +export declare class WriteResult implements firestore.WriteResult { + private readonly _writeTime; + /** + * @private + * + * @param _writeTime The time of the corresponding document write. + */ + constructor(_writeTime: Timestamp); + /** + * The write time as set by the Firestore servers. + * + * @type {Timestamp} + * @name WriteResult#writeTime + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({foo: 'bar'}).then(writeResult => { + * console.log(`Document written at: ${writeResult.writeTime.toDate()}`); + * }); + * ``` + */ + get writeTime(): Timestamp; + /** + * Returns true if this `WriteResult` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @return true if this `WriteResult` is equal to the provided value. + */ + isEqual(other: firestore.WriteResult): boolean; +} +/** + * A lazily-evaluated write that allows us to detect the Project ID before + * serializing the request. + * @private + * @internal + */ +export type PendingWriteOp = () => api.IWrite; +/** + * A Firestore WriteBatch that can be used to atomically commit multiple write + * operations at once. + * + * @class WriteBatch + */ +export declare class WriteBatch implements firestore.WriteBatch { + protected readonly _firestore: Firestore; + private readonly _serializer; + private readonly _allowUndefined; + /** + * An array of document paths and the corresponding write operations that are + * executed as part of the commit. The resulting `api.IWrite` will be sent to + * the backend. + * + * @private + * @internal + */ + private readonly _ops; + private _committed; + /** + * The number of writes in this batch. + * @private + * @internal + */ + get _opCount(): number; + /** @private */ + constructor(firestore: Firestore); + /** + * Checks if this write batch has any pending operations. + * + * @private + * @internal + */ + get isEmpty(): boolean; + /** + * Throws an error if this batch has already been committed. + * + * @private + * @internal + */ + private verifyNotCommitted; + /** + * Create a document with the provided object values. This will fail the batch + * if a document exists at its location. + * + * @param {DocumentReference} documentRef A reference to the document to be + * created. + * @param {T} data The object to serialize as the document. + * @throws {Error} If the provided input is not a valid Firestore document. + * @returns {WriteBatch} This WriteBatch instance. Used for chaining + * method calls. + * + * @example + * ``` + * let writeBatch = firestore.batch(); + * let documentRef = firestore.collection('col').doc(); + * + * writeBatch.create(documentRef, {foo: 'bar'}); + * + * writeBatch.commit().then(() => { + * console.log('Successfully executed batch.'); + * }); + * ``` + */ + create(documentRef: firestore.DocumentReference, data: firestore.WithFieldValue): WriteBatch; + /** + * Deletes a document from the database. + * + * @param {DocumentReference} documentRef A reference to the document to be + * deleted. + * @param {Precondition=} precondition A precondition to enforce for this + * delete. + * @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the + * document was last updated at lastUpdateTime. Fails the batch if the + * document doesn't exist or was last updated at a different time. + * @param {boolean= } precondition.exists If set to true, enforces that the target + * document must or must not exist. + * @returns {WriteBatch} This WriteBatch instance. Used for chaining + * method calls. + * + * @example + * ``` + * let writeBatch = firestore.batch(); + * let documentRef = firestore.doc('col/doc'); + * + * writeBatch.delete(documentRef); + * + * writeBatch.commit().then(() => { + * console.log('Successfully executed batch.'); + * }); + * ``` + */ + delete(documentRef: firestore.DocumentReference, precondition?: firestore.Precondition): WriteBatch; + set(documentRef: firestore.DocumentReference, data: firestore.PartialWithFieldValue, options: firestore.SetOptions): WriteBatch; + set(documentRef: firestore.DocumentReference, data: firestore.WithFieldValue): WriteBatch; + /** + * Update fields of the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. If the document + * doesn't yet exist, the update fails and the entire batch will be rejected. + * + * The update() method accepts either an object with field paths encoded as + * keys and field values encoded as values, or a variable number of arguments + * that alternate between field paths and field values. Nested fields can be + * updated by providing dot-separated field path strings or by providing + * FieldPath objects. + * + * A Precondition restricting this update can be specified as the last + * argument. + * + * @param {DocumentReference} documentRef A reference to the document to be + * updated. + * @param {UpdateData|string|FieldPath} dataOrField An object + * containing the fields and values with which to update the document + * or the path of the first field to update. + * @param { + * ...(Precondition|*|string|FieldPath)} preconditionOrValues - + * An alternating list of field paths and values to update or a Precondition + * to restrict this update. + * @throws {Error} If the provided input is not valid Firestore data. + * @returns {WriteBatch} This WriteBatch instance. Used for chaining + * method calls. + * + * @example + * ``` + * let writeBatch = firestore.batch(); + * let documentRef = firestore.doc('col/doc'); + * + * writeBatch.update(documentRef, {foo: 'bar'}); + * + * writeBatch.commit().then(() => { + * console.log('Successfully executed batch.'); + * }); + * ``` + */ + update(documentRef: firestore.DocumentReference, dataOrField: firestore.UpdateData | string | firestore.FieldPath, ...preconditionOrValues: Array<{ + lastUpdateTime?: firestore.Timestamp; + } | unknown | string | firestore.FieldPath>): WriteBatch; + /** + * Atomically commits all pending operations to the database and verifies all + * preconditions. Fails the entire write if any precondition is not met. + * + * @returns {Promise.>} A Promise that resolves + * when this batch completes. + * + * @example + * ``` + * let writeBatch = firestore.batch(); + * let documentRef = firestore.doc('col/doc'); + * + * writeBatch.set(documentRef, {foo: 'bar'}); + * + * writeBatch.commit().then(() => { + * console.log('Successfully executed batch.'); + * }); + * ``` + */ + commit(): Promise; + /** + * Commit method that takes an optional transaction ID. + * + * @private + * @internal + * @param commitOptions Options to use for this commit. + * @param commitOptions.transactionId The transaction ID of this commit. + * @param commitOptions.requestTag A unique client-assigned identifier for + * this request. + * @returns A Promise that resolves when this batch completes. + */ + _commit(commitOptions?: { + transactionId?: Uint8Array; + requestTag?: string; + retryCodes?: number[]; + methodName?: FirestoreUnaryMethod; + }): Promise; + /** + * Resets the WriteBatch and dequeues all pending operations. + * @private + * @internal + */ + _reset(): void; +} +/** + * Validates the use of 'value' as SetOptions and enforces that 'merge' is a + * boolean. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The object to validate. + * @param options Optional validation options specifying whether the value can + * be omitted. + * @throws if the input is not a valid SetOptions object. + */ +export declare function validateSetOptions(arg: string | number, value: unknown, options?: RequiredArgumentOptions): void; +/** + * Validates a JavaScript object for usage as a Firestore document. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param obj JavaScript object to validate. + * @param allowDeletes Whether to allow FieldValue.delete() sentinels. + * @param allowUndefined Whether to allow nested properties that are `undefined`. + * @throws when the object is invalid. + */ +export declare function validateDocumentData(arg: string | number, obj: unknown, allowDeletes: boolean, allowUndefined: boolean): void; +/** + * Validates that a value can be used as field value during an update. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param val The value to verify. + * @param allowUndefined Whether to allow nested properties that are `undefined`. + * @param path The path to show in the error message. + */ +export declare function validateFieldValue(arg: string | number, val: unknown, allowUndefined: boolean, path?: FieldPath): void; diff --git a/node_modules/@google-cloud/firestore/build/src/write-batch.js b/node_modules/@google-cloud/firestore/build/src/write-batch.js new file mode 100644 index 0000000..4785e1a --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/write-batch.js @@ -0,0 +1,668 @@ +"use strict"; +/*! + * Copyright 2019 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WriteBatch = exports.WriteResult = void 0; +exports.validateSetOptions = validateSetOptions; +exports.validateDocumentData = validateDocumentData; +exports.validateFieldValue = validateFieldValue; +const document_1 = require("./document"); +const logger_1 = require("./logger"); +const path_1 = require("./path"); +const helpers_1 = require("./reference/helpers"); +const serializer_1 = require("./serializer"); +const timestamp_1 = require("./timestamp"); +const util_1 = require("./util"); +const validate_1 = require("./validate"); +const trace_util_1 = require("./telemetry/trace-util"); +/** + * A WriteResult wraps the write time set by the Firestore servers on sets(), + * updates(), and creates(). + * + * @class WriteResult + */ +class WriteResult { + /** + * @private + * + * @param _writeTime The time of the corresponding document write. + */ + constructor(_writeTime) { + this._writeTime = _writeTime; + } + /** + * The write time as set by the Firestore servers. + * + * @type {Timestamp} + * @name WriteResult#writeTime + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({foo: 'bar'}).then(writeResult => { + * console.log(`Document written at: ${writeResult.writeTime.toDate()}`); + * }); + * ``` + */ + get writeTime() { + return this._writeTime; + } + /** + * Returns true if this `WriteResult` is equal to the provided value. + * + * @param {*} other The value to compare against. + * @return true if this `WriteResult` is equal to the provided value. + */ + isEqual(other) { + return (this === other || + (other instanceof WriteResult && + this._writeTime.isEqual(other._writeTime))); + } +} +exports.WriteResult = WriteResult; +/** + * A Firestore WriteBatch that can be used to atomically commit multiple write + * operations at once. + * + * @class WriteBatch + */ +class WriteBatch { + /** + * The number of writes in this batch. + * @private + * @internal + */ + get _opCount() { + return this._ops.length; + } + /** @private */ + constructor(firestore) { + /** + * An array of document paths and the corresponding write operations that are + * executed as part of the commit. The resulting `api.IWrite` will be sent to + * the backend. + * + * @private + * @internal + */ + this._ops = []; + this._committed = false; + this._firestore = firestore; + this._serializer = new serializer_1.Serializer(firestore); + this._allowUndefined = !!firestore._settings.ignoreUndefinedProperties; + } + /** + * Checks if this write batch has any pending operations. + * + * @private + * @internal + */ + get isEmpty() { + return this._ops.length === 0; + } + /** + * Throws an error if this batch has already been committed. + * + * @private + * @internal + */ + verifyNotCommitted() { + if (this._committed) { + throw new Error('Cannot modify a WriteBatch that has been committed.'); + } + } + /** + * Create a document with the provided object values. This will fail the batch + * if a document exists at its location. + * + * @param {DocumentReference} documentRef A reference to the document to be + * created. + * @param {T} data The object to serialize as the document. + * @throws {Error} If the provided input is not a valid Firestore document. + * @returns {WriteBatch} This WriteBatch instance. Used for chaining + * method calls. + * + * @example + * ``` + * let writeBatch = firestore.batch(); + * let documentRef = firestore.collection('col').doc(); + * + * writeBatch.create(documentRef, {foo: 'bar'}); + * + * writeBatch.commit().then(() => { + * console.log('Successfully executed batch.'); + * }); + * ``` + */ + create(documentRef, data) { + const ref = (0, helpers_1.validateDocumentReference)('documentRef', documentRef); + const firestoreData = ref._converter.toFirestore(data); + validateDocumentData('data', firestoreData, + /* allowDeletes= */ false, this._allowUndefined); + this.verifyNotCommitted(); + const transform = document_1.DocumentTransform.fromObject(ref, firestoreData); + transform.validate(); + const precondition = new document_1.Precondition({ exists: false }); + const op = () => { + const document = document_1.DocumentSnapshot.fromObject(ref, firestoreData); + const write = document.toWriteProto(); + if (!transform.isEmpty) { + write.updateTransforms = transform.toProto(this._serializer); + } + write.currentDocument = precondition.toProto(); + return write; + }; + this._ops.push({ docPath: documentRef.path, op }); + return this; + } + /** + * Deletes a document from the database. + * + * @param {DocumentReference} documentRef A reference to the document to be + * deleted. + * @param {Precondition=} precondition A precondition to enforce for this + * delete. + * @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the + * document was last updated at lastUpdateTime. Fails the batch if the + * document doesn't exist or was last updated at a different time. + * @param {boolean= } precondition.exists If set to true, enforces that the target + * document must or must not exist. + * @returns {WriteBatch} This WriteBatch instance. Used for chaining + * method calls. + * + * @example + * ``` + * let writeBatch = firestore.batch(); + * let documentRef = firestore.doc('col/doc'); + * + * writeBatch.delete(documentRef); + * + * writeBatch.commit().then(() => { + * console.log('Successfully executed batch.'); + * }); + * ``` + */ + delete( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + documentRef, precondition) { + const ref = (0, helpers_1.validateDocumentReference)('documentRef', documentRef); + validateDeletePrecondition('precondition', precondition, { optional: true }); + this.verifyNotCommitted(); + const conditions = new document_1.Precondition(precondition); + const op = () => { + const write = { delete: ref.formattedName }; + if (!conditions.isEmpty) { + write.currentDocument = conditions.toProto(); + } + return write; + }; + this._ops.push({ docPath: documentRef.path, op }); + return this; + } + /** + * Write to the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. If the document does not + * exist yet, it will be created. If you pass [SetOptions]{@link SetOptions}, + * the provided data can be merged into the existing document. + * + * @param {DocumentReference} documentRef A reference to the document to be + * set. + * @param {T|Partial} data The object to serialize as the document. + * @param {SetOptions=} options An object to configure the set behavior. + * @param {boolean=} options.merge - If true, set() merges the values + * specified in its data argument. Fields omitted from this set() call + * remain untouched. If your input sets any field to an empty map, all nested + * fields are overwritten. + * @param {Array.=} options.mergeFields - If provided, + * set() only replaces the specified field paths. Any field path that is no + * specified is ignored and remains untouched. If your input sets any field to + * an empty map, all nested fields are overwritten. + * @throws {Error} If the provided input is not a valid Firestore document. + * @returns {WriteBatch} This WriteBatch instance. Used for chaining + * method calls. + * + * @example + * ``` + * let writeBatch = firestore.batch(); + * let documentRef = firestore.doc('col/doc'); + * + * writeBatch.set(documentRef, {foo: 'bar'}); + * + * writeBatch.commit().then(() => { + * console.log('Successfully executed batch.'); + * }); + * ``` + */ + set(documentRef, data, options) { + validateSetOptions('options', options, { optional: true }); + const mergeLeaves = options && 'merge' in options && options.merge; + const mergePaths = options && 'mergeFields' in options; + const ref = (0, helpers_1.validateDocumentReference)('documentRef', documentRef); + let firestoreData; + if (mergeLeaves || mergePaths) { + firestoreData = ref._converter.toFirestore(data, options); + } + else { + firestoreData = ref._converter.toFirestore(data); + } + validateDocumentData('data', firestoreData, + /* allowDeletes= */ !!(mergePaths || mergeLeaves), this._allowUndefined); + this.verifyNotCommitted(); + let documentMask; + if (mergePaths) { + documentMask = document_1.DocumentMask.fromFieldMask(options.mergeFields); + firestoreData = documentMask.applyTo(firestoreData); + } + const transform = document_1.DocumentTransform.fromObject(ref, firestoreData); + transform.validate(); + const op = () => { + const document = document_1.DocumentSnapshot.fromObject(ref, firestoreData); + if (mergePaths) { + documentMask.removeFields(transform.fields); + } + else if (mergeLeaves) { + documentMask = document_1.DocumentMask.fromObject(firestoreData); + } + const write = document.toWriteProto(); + if (!transform.isEmpty) { + write.updateTransforms = transform.toProto(this._serializer); + } + if (mergePaths || mergeLeaves) { + write.updateMask = documentMask.toProto(); + } + return write; + }; + this._ops.push({ docPath: documentRef.path, op }); + return this; + } + /** + * Update fields of the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. If the document + * doesn't yet exist, the update fails and the entire batch will be rejected. + * + * The update() method accepts either an object with field paths encoded as + * keys and field values encoded as values, or a variable number of arguments + * that alternate between field paths and field values. Nested fields can be + * updated by providing dot-separated field path strings or by providing + * FieldPath objects. + * + * A Precondition restricting this update can be specified as the last + * argument. + * + * @param {DocumentReference} documentRef A reference to the document to be + * updated. + * @param {UpdateData|string|FieldPath} dataOrField An object + * containing the fields and values with which to update the document + * or the path of the first field to update. + * @param { + * ...(Precondition|*|string|FieldPath)} preconditionOrValues - + * An alternating list of field paths and values to update or a Precondition + * to restrict this update. + * @throws {Error} If the provided input is not valid Firestore data. + * @returns {WriteBatch} This WriteBatch instance. Used for chaining + * method calls. + * + * @example + * ``` + * let writeBatch = firestore.batch(); + * let documentRef = firestore.doc('col/doc'); + * + * writeBatch.update(documentRef, {foo: 'bar'}); + * + * writeBatch.commit().then(() => { + * console.log('Successfully executed batch.'); + * }); + * ``` + */ + update(documentRef, dataOrField, ...preconditionOrValues) { + // eslint-disable-next-line prefer-rest-params + (0, validate_1.validateMinNumberOfArguments)('WriteBatch.update', arguments, 2); + (0, helpers_1.validateDocumentReference)('documentRef', documentRef); + this.verifyNotCommitted(); + const updateMap = new Map(); + let precondition = new document_1.Precondition({ exists: true }); + const argumentError = 'Update() requires either a single JavaScript ' + + 'object or an alternating list of field/value pairs that can be ' + + 'followed by an optional precondition.'; + const usesVarargs = typeof dataOrField === 'string' || dataOrField instanceof path_1.FieldPath; + if (usesVarargs) { + const argumentOffset = 1; // Respect 'documentRef' in the error message + const fieldOrValues = [dataOrField, ...preconditionOrValues]; + try { + for (let i = 0; i < fieldOrValues.length; i += 2) { + if (i === fieldOrValues.length - 1) { + const maybePrecondition = fieldOrValues[i]; + validateUpdatePrecondition(i + argumentOffset, maybePrecondition); + precondition = new document_1.Precondition(maybePrecondition); + } + else { + const maybeFieldPath = fieldOrValues[i]; + (0, path_1.validateFieldPath)(i + argumentOffset, maybeFieldPath); + // Unlike the `validateMinNumberOfArguments` invocation above, this + // validation can be triggered both from `WriteBatch.update()` and + // `DocumentReference.update()`. Hence, we don't use the fully + // qualified API name in the error message. + (0, validate_1.validateMinNumberOfArguments)('update', fieldOrValues, i + 1); + const fieldPath = path_1.FieldPath.fromArgument(maybeFieldPath); + validateFieldValue(i + argumentOffset, fieldOrValues[i + 1], this._allowUndefined, fieldPath); + updateMap.set(fieldPath, fieldOrValues[i + 1]); + } + } + } + catch (err) { + (0, logger_1.logger)('WriteBatch.update', null, 'Varargs validation failed:', err); + // We catch the validation error here and re-throw to provide a better + // error message. + throw new Error(`${argumentError} ${err.message}`); + } + } + else { + try { + validateUpdateMap('dataOrField', dataOrField, this._allowUndefined); + // eslint-disable-next-line prefer-rest-params + (0, validate_1.validateMaxNumberOfArguments)('update', arguments, 3); + Object.entries(dataOrField).forEach(([key, value]) => { + // Skip `undefined` values (can be hit if `ignoreUndefinedProperties` + // is set) + if (value !== undefined) { + (0, path_1.validateFieldPath)(key, key); + updateMap.set(path_1.FieldPath.fromArgument(key), value); + } + }); + if (preconditionOrValues.length > 0) { + validateUpdatePrecondition('preconditionOrValues', preconditionOrValues[0]); + precondition = new document_1.Precondition(preconditionOrValues[0]); + } + } + catch (err) { + (0, logger_1.logger)('WriteBatch.update', null, 'Non-varargs validation failed:', err); + // We catch the validation error here and prefix the error with a custom + // message to describe the usage of update() better. + throw new Error(`${argumentError} ${err.message}`); + } + } + validateNoConflictingFields('dataOrField', updateMap); + const transform = document_1.DocumentTransform.fromUpdateMap(documentRef, updateMap); + transform.validate(); + const documentMask = document_1.DocumentMask.fromUpdateMap(updateMap); + const op = () => { + const document = document_1.DocumentSnapshot.fromUpdateMap(documentRef, updateMap); + const write = document.toWriteProto(); + write.updateMask = documentMask.toProto(); + if (!transform.isEmpty) { + write.updateTransforms = transform.toProto(this._serializer); + } + write.currentDocument = precondition.toProto(); + return write; + }; + this._ops.push({ docPath: documentRef.path, op }); + return this; + } + /** + * Atomically commits all pending operations to the database and verifies all + * preconditions. Fails the entire write if any precondition is not met. + * + * @returns {Promise.>} A Promise that resolves + * when this batch completes. + * + * @example + * ``` + * let writeBatch = firestore.batch(); + * let documentRef = firestore.doc('col/doc'); + * + * writeBatch.set(documentRef, {foo: 'bar'}); + * + * writeBatch.commit().then(() => { + * console.log('Successfully executed batch.'); + * }); + * ``` + */ + commit() { + return this._firestore._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_BATCH_COMMIT, async () => { + // Capture the error stack to preserve stack tracing across async calls. + const stack = Error().stack; + // Commits should also be retried when they fail with status code ABORTED. + const retryCodes = [10 /* StatusCode.ABORTED */, ...(0, util_1.getRetryCodes)('commit')]; + return this._commit({ retryCodes }) + .then(response => { + return (response.writeResults || []).map(writeResult => new WriteResult(timestamp_1.Timestamp.fromProto(writeResult.updateTime || response.commitTime))); + }) + .catch(err => { + throw (0, util_1.wrapError)(err, stack); + }); + }, { + [trace_util_1.ATTRIBUTE_KEY_IS_TRANSACTIONAL]: false, + [trace_util_1.ATTRIBUTE_KEY_DOC_COUNT]: this._opCount, + }); + } + /** + * Commit method that takes an optional transaction ID. + * + * @private + * @internal + * @param commitOptions Options to use for this commit. + * @param commitOptions.transactionId The transaction ID of this commit. + * @param commitOptions.requestTag A unique client-assigned identifier for + * this request. + * @returns A Promise that resolves when this batch completes. + */ + async _commit(commitOptions) { + var _a; + // Note: We don't call `verifyNotCommitted()` to allow for retries. + this._committed = true; + const tag = (_a = commitOptions === null || commitOptions === void 0 ? void 0 : commitOptions.requestTag) !== null && _a !== void 0 ? _a : (0, util_1.requestTag)(); + await this._firestore.initializeIfNeeded(tag); + // Note that the request may not always be of type ICommitRequest. This is + // just here to ensure type safety. + const request = { + database: this._firestore.formattedName, + writes: this._ops.map(op => op.op()), + }; + if (commitOptions === null || commitOptions === void 0 ? void 0 : commitOptions.transactionId) { + request.transaction = commitOptions.transactionId; + } + (0, logger_1.logger)('WriteBatch.commit', tag, 'Sending %d writes', request.writes.length); + return this._firestore.request((commitOptions === null || commitOptions === void 0 ? void 0 : commitOptions.methodName) || 'commit', request, tag, commitOptions === null || commitOptions === void 0 ? void 0 : commitOptions.retryCodes); + } + /** + * Resets the WriteBatch and dequeues all pending operations. + * @private + * @internal + */ + _reset() { + this._ops.splice(0); + this._committed = false; + } +} +exports.WriteBatch = WriteBatch; +/** + * Validates the use of 'value' as a Precondition and enforces that 'exists' + * and 'lastUpdateTime' use valid types. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The object to validate + * @param options Options describing other things for this function to validate. + */ +function validatePrecondition(arg, value, options) { + if (typeof value !== 'object' || value === null) { + throw new Error('Input is not an object.'); + } + const precondition = value; + let conditions = 0; + if (precondition.exists !== undefined) { + ++conditions; + if (typeof precondition.exists !== 'boolean') { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, 'precondition')} "exists" is not a boolean.'`); + } + if ((options === null || options === void 0 ? void 0 : options.allowedExistsValues) && + options.allowedExistsValues.indexOf(precondition.exists) < 0) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, 'precondition')} ` + + `"exists" is not allowed to have the value ${precondition.exists} ` + + `(allowed values: ${options.allowedExistsValues.join(', ')})`); + } + } + if (precondition.lastUpdateTime !== undefined) { + ++conditions; + if (!(precondition.lastUpdateTime instanceof timestamp_1.Timestamp)) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, 'precondition')} "lastUpdateTime" is not a Firestore Timestamp.`); + } + } + if (conditions > 1) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, 'precondition')} Input specifies more than one precondition.`); + } +} +/** + * Validates the use of 'value' as an update Precondition. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The object to validate. + * @param options Optional validation options specifying whether the value can + * be omitted. + */ +function validateUpdatePrecondition(arg, value, options) { + if (!(0, validate_1.validateOptional)(value, options)) { + validatePrecondition(arg, value, { allowedExistsValues: [true] }); + } +} +/** + * Validates the use of 'value' as a delete Precondition. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The object to validate. + * @param options Optional validation options specifying whether the value can + * be omitted. + */ +function validateDeletePrecondition(arg, value, options) { + if (!(0, validate_1.validateOptional)(value, options)) { + validatePrecondition(arg, value); + } +} +/** + * Validates the use of 'value' as SetOptions and enforces that 'merge' is a + * boolean. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The object to validate. + * @param options Optional validation options specifying whether the value can + * be omitted. + * @throws if the input is not a valid SetOptions object. + */ +function validateSetOptions(arg, value, options) { + if (!(0, validate_1.validateOptional)(value, options)) { + if (!(0, util_1.isObject)(value)) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, 'set() options argument')} Input is not an object.`); + } + const setOptions = value; + if ('mergeFields' in setOptions) { + for (let i = 0; i < setOptions.mergeFields.length; ++i) { + try { + (0, path_1.validateFieldPath)(i, setOptions.mergeFields[i]); + } + catch (err) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, 'set() options argument')} "mergeFields" is not valid: ${err.message}`); + } + } + } + if ('merge' in setOptions && 'mergeFields' in setOptions) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, 'set() options argument')} You cannot specify both "merge" and "mergeFields".`); + } + } +} +/** + * Validates a JavaScript object for usage as a Firestore document. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param obj JavaScript object to validate. + * @param allowDeletes Whether to allow FieldValue.delete() sentinels. + * @param allowUndefined Whether to allow nested properties that are `undefined`. + * @throws when the object is invalid. + */ +function validateDocumentData(arg, obj, allowDeletes, allowUndefined) { + if (!(0, util_1.isPlainObject)(obj)) { + throw new Error((0, validate_1.customObjectMessage)(arg, obj)); + } + (0, serializer_1.validateUserInput)(arg, obj, 'Firestore document', { + allowDeletes: allowDeletes ? 'all' : 'none', + allowTransforms: true, + allowUndefined, + }); +} +/** + * Validates that a value can be used as field value during an update. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param val The value to verify. + * @param allowUndefined Whether to allow nested properties that are `undefined`. + * @param path The path to show in the error message. + */ +function validateFieldValue(arg, val, allowUndefined, path) { + (0, serializer_1.validateUserInput)(arg, val, 'Firestore value', { allowDeletes: 'root', allowTransforms: true, allowUndefined }, path); +} +/** + * Validates that the update data does not contain any ambiguous field + * definitions (such as 'a.b' and 'a'). + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param data An update map with field/value pairs. + */ +function validateNoConflictingFields(arg, data) { + const fields = []; + data.forEach((value, key) => { + fields.push(key); + }); + fields.sort((left, right) => left.compareTo(right)); + for (let i = 1; i < fields.length; ++i) { + if (fields[i - 1].isPrefixOf(fields[i])) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, 'update map')} Field "${fields[i - 1]}" was specified multiple times.`); + } + } +} +/** + * Validates that a JavaScript object is a map of field paths to field values. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param obj JavaScript object to validate. + * @param allowUndefined Whether to allow nested properties that are `undefined`. + * @throws when the object is invalid. + */ +function validateUpdateMap(arg, obj, allowUndefined) { + if (!(0, util_1.isPlainObject)(obj)) { + throw new Error((0, validate_1.customObjectMessage)(arg, obj)); + } + if (Object.keys(obj).length === 0) { + throw new Error('At least one field must be updated.'); + } + validateFieldValue(arg, obj, allowUndefined); +} +//# sourceMappingURL=write-batch.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/package.json b/node_modules/@google-cloud/firestore/package.json new file mode 100644 index 0000000..3e8f8bc --- /dev/null +++ b/node_modules/@google-cloud/firestore/package.json @@ -0,0 +1,115 @@ +{ + "name": "@google-cloud/firestore", + "description": "Firestore Client Library for Node.js", + "version": "7.11.6", + "license": "Apache-2.0", + "author": "Google Inc.", + "engines": { + "node": ">=14.0.0" + }, + "repository": "googleapis/nodejs-firestore", + "main": "./build/src/index.js", + "types": "./types/firestore.d.ts", + "files": [ + "build/protos", + "build/src", + "!build/src/**/*.map", + "types" + ], + "keywords": [ + "google apis client", + "google api client", + "google apis", + "google api", + "google", + "google cloud platform", + "google cloud", + "cloud", + "firestore" + ], + "scripts": { + "precloud-rad": "npm run compile", + "cloud-rad": "NO_UPLOAD=1 npx @google-cloud/cloud-rad", + "preapi-report": "npm run compile", + "api-report": "node scripts/api-report.js", + "predocs": "npm run compile", + "docs": "jsdoc -c .jsdoc.js", + "system-test:rest": "FIRESTORE_PREFER_REST=true mocha build/system-test --timeout 1200000", + "system-test:named-db:rest": "FIRESTORE_NAMED_DATABASE=test-db FIRESTORE_PREFER_REST=true mocha build/system-test --timeout 1200000", + "system-test:grpc": "mocha build/system-test --timeout 1200000", + "system-test:named-db:grpc": "FIRESTORE_NAMED_DATABASE=test-db mocha build/system-test --timeout 1200000", + "system-test:emulator:rest": "FIRESTORE_EMULATOR_HOST=localhost:8080 FIRESTORE_PREFER_REST=true mocha build/system-test --timeout 1200000", + "system-test:named-db:emulator:rest": "FIRESTORE_NAMED_DATABASE=test-db FIRESTORE_EMULATOR_HOST=localhost:8080 FIRESTORE_PREFER_REST=true mocha build/system-test --timeout 1200000", + "system-test:emulator:grpc": "FIRESTORE_EMULATOR_HOST=localhost:8080 mocha build/system-test --timeout 1200000", + "system-test:named-db:emulator:grpc": "FIRESTORE_NAMED_DATABASE=test-db FIRESTORE_EMULATOR_HOST=localhost:8080 mocha build/system-test --timeout 1200000", + "system-test": "npm run system-test:grpc && npm run system-test:rest && npm run system-test:named-db:grpc && npm run system-test:named-db:rest", + "system-test:emulator": "npm run system-test:emulator:grpc && npm run system-test:emulator:rest && npm run system-test:named-db:emulator:grpc && npm run system-test:named-db:emulator:rest", + "presystem-test": "npm run compile", + "samples-test": "npm link && cd samples/ && npm link ../ && npm test && cd ../", + "conformance": "mocha build/conformance", + "preconformance": "npm run compile", + "test-only": "c8 mocha build/test", + "pretest-only": "npm run compile", + "test": "npm run test-only && npm run conformance", + "lint": "gts check", + "clean": "gts clean", + "compile": "tsc -p .", + "postcompile": "node scripts/init-directories.js && cp -r dev/protos build && cp dev/src/v1beta1/*.json build/src/v1beta1/ && cp dev/src/v1/*.json build/src/v1/ && cp dev/conformance/test-definition.proto build/conformance && cp dev/conformance/conformance-tests/*.json build/conformance/conformance-tests && minifyProtoJson", + "fix": "gts fix", + "prepare": "npm run compile", + "docs-test": "linkinator docs", + "predocs-test": "npm run docs", + "prelint": "cd samples; npm link ../; npm install", + "precompile": "gts clean" + }, + "dependencies": { + "@opentelemetry/api": "^1.3.0", + "fast-deep-equal": "^3.1.1", + "functional-red-black-tree": "^1.0.1", + "google-gax": "^4.3.3", + "protobufjs": "^7.2.6" + }, + "devDependencies": { + "@google-cloud/promisify": "legacy-14", + "@google-cloud/trace-agent": "^8.0.0", + "@googleapis/cloudtrace": "^1.1.2", + "@google-cloud/cloud-rad": "^0.4.0", + "@google-cloud/opentelemetry-cloud-trace-exporter": "^2.0.0", + "@opentelemetry/context-async-hooks": "^1.24.1", + "@opentelemetry/sdk-trace-node": "^1.24.1", + "@types/assert": "^1.4.0", + "@types/chai": "^4.2.7", + "@types/chai-as-promised": "^7.1.2", + "@types/duplexify": "^3.5.0", + "@types/extend": "^3.0.0", + "@types/mocha": "^9.0.0", + "@types/node": "^22.0.0", + "@types/sinon": "^17.0.0", + "@types/through2": "^2.0.34", + "c8": "^9.0.0", + "chai": "^4.1.2", + "chai-as-promised": "^7.1.1", + "codecov": "^3.6.1", + "duplexify": "^4.0.0", + "execa": "^5.1.1", + "extend": "^3.0.2", + "fs-extra": "10.1.0", + "gapic-tools": "^0.4.0", + "gts": "^5.0.1", + "jsdoc": "^4.0.0", + "jsdoc-fresh": "^3.0.0", + "jsdoc-region-tag": "^3.0.0", + "length-prefixed-json-stream": "^1.0.1", + "linkinator": "^3.0.0", + "mkdirp": "^3.0.0", + "mocha": "^9.2.2", + "protobufjs-cli": "^1.1.2", + "proxyquire": "^2.1.3", + "nise": "6.0.0", + "sinon": "^18.0.0", + "path-to-regexp": "^6.0.0", + "through2": "^4.0.0", + "ts-node": "^10.0.0", + "typescript": "^5.2.2" + } +} diff --git a/node_modules/@google-cloud/firestore/types/firestore.d.ts b/node_modules/@google-cloud/firestore/types/firestore.d.ts new file mode 100644 index 0000000..cfff47c --- /dev/null +++ b/node_modules/@google-cloud/firestore/types/firestore.d.ts @@ -0,0 +1,3302 @@ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// We deliberately use `any` in the external API to not impose type-checking +// on end users. +/* eslint-disable @typescript-eslint/no-explicit-any */ + +// Declare a global (ambient) namespace +// (used when not using import statement, but just script include). + +declare namespace FirebaseFirestore { + /** Alias for `any` but used where a Firestore field value would be provided. */ + export type DocumentFieldValue = any; + + /** + * Document data (for use with `DocumentReference.set()`) consists of fields + * mapped to values. + */ + export type DocumentData = {[field: string]: DocumentFieldValue}; + + /** + * Similar to Typescript's `Partial`, but allows nested fields to be + * omitted and FieldValues to be passed in as property values. + */ + export type PartialWithFieldValue = + | Partial + | (T extends Primitive + ? T + : T extends {} + ? {[K in keyof T]?: PartialWithFieldValue | FieldValue} + : never); + + /** + * Allows FieldValues to be passed in as a property value while maintaining + * type safety. + */ + export type WithFieldValue = + | T + | (T extends Primitive + ? T + : T extends {} + ? {[K in keyof T]: WithFieldValue | FieldValue} + : never); + + /** + * Update data (for use with [update]{@link DocumentReference#update}) + * that contains paths mapped to values. Fields that contain dots reference + * nested fields within the document. FieldValues can be passed in + * as property values. + * + * You can update a top-level field in your document by using the field name + * as a key (e.g. `foo`). The provided value completely replaces the contents + * for this field. + * + * You can also update a nested field directly by using its field path as a + * key (e.g. `foo.bar`). This nested field update replaces the contents at + * `bar` but does not modify other data under `foo`. + */ + export type UpdateData = T extends Primitive + ? T + : T extends {} + ? {[K in keyof T]?: UpdateData | FieldValue} & NestedUpdateFields + : Partial; + + /** Primitive types. */ + export type Primitive = string | number | boolean | undefined | null; + + /** + * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, + * 'bar.qux': T2}). Intersect them together to make a single map containing + * all possible keys that are all marked as optional + */ + export type NestedUpdateFields> = + UnionToIntersection< + { + [K in keyof T & string]: ChildUpdateFields; + }[keyof T & string] // Also include the generated prefix-string keys. + >; + + /** + * Helper for calculating the nested fields for a given type T1. This is needed + * to distribute union types such as `undefined | {...}` (happens for optional + * props) or `{a: A} | {b: B}`. + * + * In this use case, `V` is used to distribute the union types of `T[K]` on + * `Record`, since `T[K]` is evaluated as an expression and not distributed. + * + * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types + */ + export type ChildUpdateFields = + // Only allow nesting for map values + V extends Record + ? // Recurse into the map and add the prefix in front of each key + // (e.g. Prefix 'bar.' to create: 'bar.baz' and 'bar.qux'. + AddPrefixToKeys> + : // UpdateData is always a map of values. + never; + + /** + * Returns a new map where every key is prefixed with the outer key appended + * to a dot. + */ + export type AddPrefixToKeys< + Prefix extends string, + T extends Record, + > = + // Remap K => Prefix.K. See https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#key-remapping-via-as + {[K in keyof T & string as `${Prefix}.${K}`]+?: T[K]}; + + /** + * Given a union type `U = T1 | T2 | ...`, returns an intersected type + * `(T1 & T2 & ...)`. + * + * Uses distributive conditional types and inference from conditional types. + * This works because multiple candidates for the same type variable in + * contra-variant positions causes an intersection type to be inferred. + * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types + * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type + */ + export type UnionToIntersection = ( + U extends unknown ? (k: U) => void : never + ) extends (k: infer I) => void + ? I + : never; + + /** + * Sets or disables the log function for all active Firestore instances. + * + * @param logger A log function that takes a message (such as `console.log`) or + * `null` to turn off logging. + */ + function setLogFunction(logger: ((msg: string) => void) | null): void; + + /** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties + * used for memoization, properties of types not supported by Firestore (such + * as `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In + * this context, this type is referred to as the "DbModel" and would be an + * object suitable for persisting into Firestore. For convenience, + * applications can implement `FirestoreDataConverter` and register the + * converter with Firestore objects, such as `DocumentReference` or `Query`, + * to automatically convert `AppModel` to `DbModel` when storing into + * Firestore, and convert `DbModel` to `AppModel` when retrieving from + * Firestore. + * + * @example + * + * Simple Example + * + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot) { + * return snapshot.data().value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = db.doc('values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await documentRef.set(42); + * const snapshot1 = await documentRef.get(); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await documentRef.update({ value: 999 }); + * const snapshot2 = await documentRef.get(); + * assertEqual(snapshot2.data(), 999); + * } + * + * Advanced Example + * + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot): Post { + * const data = snapshot.data() as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = db.doc('posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `DocumentReference.set()` is type + * // checked by the TypeScript compiler to be compatible with `Post`. Since + * // the `data` argument is typed as `WithFieldValue` rather than just + * // `Post`, this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `FieldValue.arrayRemove()`, `FieldValue.delete()`, and + * // `FieldValue.serverTimestamp()`. + * await documentRef.set({ + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: FieldValue.serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument + * // to `DocumentReference.set()` is _not_ compatible with + * // `WithFieldValue`. This type checking prevents the caller from + * // specifying objects with incorrect properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await documentRef.set(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `DocumentReference.get()` the + * // `DocumentSnapshot` object's `data()` method returns a `Post`, rather + * // than a generic object, which would have been returned if the + * // `DocumentReference` did _not_ have a `FirestoreDataConverter` + * // attached to it. + * const snapshot1: DocumentSnapshot = await documentRef.get(); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `DocumentReference.update()` is type + * // checked by the TypeScript compiler to be compatible with + * // `PostDbModel`. Note that unlike `DocumentReference.set()`, whose + * // `data` argument must be compatible with `Post`, the `data` argument + * // to `update()` must be compatible with `PostDbModel`. Similar to + * // `set()`, since the `data` argument is typed as + * // `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `FieldValue.arrayRemove()`, + * // `FieldValue.delete()`, and `FieldValue.serverTimestamp()`. + * await documentRef.update({ + * 'aut.firstName': 'NewFirstName', + * lut: FieldValue.serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument + * // to `DocumentReference.update()` is _not_ compatible with + * // `WithFieldValue`. This type checking prevents the caller + * // from specifying objects with incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not + * // assignable to parameter of type WithFieldValue" + * await documentRef.update({ title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await documentRef.get(); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + */ + export interface FirestoreDataConverter< + AppModelType, + DbModelType extends DocumentData = DocumentData, + > { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain Javascript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. + * + * To use set() with `merge` and `mergeFields`, + * toFirestore() must be defined with `Partial`. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such + * as `FieldValue.delete()` to be used as property values. + */ + toFirestore( + modelObject: WithFieldValue + ): WithFieldValue; + + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain Javascript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. + * + * To use set() with `merge` and `mergeFields`, + * toFirestore() must be defined with `Partial`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as `FieldValue.delete()` to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore( + modelObject: PartialWithFieldValue, + options: SetOptions + ): PartialWithFieldValue; + + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data()`. + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use + * a type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + */ + fromFirestore(snapshot: QueryDocumentSnapshot): AppModelType; + } + + /** + * Settings used to directly configure a `Firestore` instance. + */ + export interface Settings { + /** + * The project ID from the Google Developer's Console, e.g. + * 'grape-spaceship-123'. We will also check the environment variable + * GCLOUD_PROJECT for your project ID. Can be omitted in environments that + * support {@link https://cloud.google.com/docs/authentication Application + * Default Credentials} + */ + projectId?: string; + + /** + * The database name. If omitted, the default database will be used. + */ + databaseId?: string; + + /** The hostname to connect to. */ + host?: string; + + /** The port to connect to. */ + port?: number; + + /** + * Local file containing the Service Account credentials as downloaded from + * the Google Developers Console. Can be omitted in environments that + * support {@link https://cloud.google.com/docs/authentication Application + * Default Credentials}. To configure Firestore with custom credentials, use + * the `credentials` property to provide the `client_email` and + * `private_key` of your service account. + */ + keyFilename?: string; + + /** + * The 'client_email' and 'private_key' properties of the service account + * to use with your Firestore project. Can be omitted in environments that + * support {@link https://cloud.google.com/docs/authentication Application + * Default Credentials}. If your credentials are stored in a JSON file, you + * can specify a `keyFilename` instead. + */ + credentials?: {client_email?: string; private_key?: string}; + + /** Whether to use SSL when connecting. */ + ssl?: boolean; + + /** + * The maximum number of idle GRPC channels to keep. A smaller number of idle + * channels reduces memory usage but increases request latency for clients + * with fluctuating request rates. If set to 0, shuts down all GRPC channels + * when the client becomes idle. Defaults to 1. + */ + maxIdleChannels?: number; + + /** + * Whether to use `BigInt` for integer types when deserializing Firestore + * Documents. Regardless of magnitude, all integer values are returned as + * `BigInt` to match the precision of the Firestore backend. Floating point + * numbers continue to use JavaScript's `number` type. + */ + useBigInt?: boolean; + + /** + * Whether to skip nested properties that are set to `undefined` during + * object serialization. If set to `true`, these properties are skipped + * and not written to Firestore. If set `false` or omitted, the SDK throws + * an exception when it encounters properties of type `undefined`. + */ + ignoreUndefinedProperties?: boolean; + + /** + * Whether to force the use of HTTP/1.1 REST transport until a method that requires gRPC + * is called. When a method requires gRPC, this Firestore client will load dependent gRPC + * libraries and then use gRPC transport for communication from that point forward. + * Currently the only operation that requires gRPC is creating a snapshot listener with + * the method `DocumentReference.onSnapshot()`, `CollectionReference.onSnapshot()`, + * or `Query.onSnapshot()`. + */ + preferRest?: boolean; + + /** + * Settings related to telemetry collection by this client. + * @beta + */ + openTelemetry?: FirestoreOpenTelemetryOptions; + + [key: string]: any; // Accept other properties, such as GRPC settings. + } + + /** + * Options to configure telemetry collection. + * This is a 'beta' interface and may change in backwards incompatible ways. + * @beta + */ + export interface FirestoreOpenTelemetryOptions { + /** + * The OpenTelemetry TracerProvider instance that the SDK should use to + * create trace spans. If not provided, the SDK will use the Global TracerProvider. + * + * Even if a Global TracerProvider has been registered, users can still + * disable this client's span creation by passing in a "no-op" tracer provider + * here, or by setting the `FIRESTORE_ENABLE_TRACING` environment variable to `OFF` or `FALSE`. + */ + tracerProvider?: any; + } + + /** Options to configure a read-only transaction. */ + export interface ReadOnlyTransactionOptions { + /** Set to true to indicate a read-only transaction. */ + readOnly: true; + /** + * If specified, documents are read at the given time. This may not be more + * than 60 seconds in the past from when the request is processed by the + * server. + */ + readTime?: Timestamp; + } + + /** Options to configure a read-write transaction. */ + export interface ReadWriteTransactionOptions { + /** Set to false or omit to indicate a read-write transaction. */ + readOnly?: false; + /** + * The maximum number of attempts for this transaction. Defaults to 5. + */ + maxAttempts?: number; + } + + /** + * `Firestore` represents a Firestore Database and is the entry point for all + * Firestore operations. + */ + export class Firestore { + /** + * @param settings Configuration object. See [Firestore Documentation] + * {@link https://firebase.google.com/docs/firestore/} + */ + public constructor(settings?: Settings); + + /** + * Specifies custom settings to be used to configure the `Firestore` + * instance. Can only be invoked once and before any other Firestore + * method. + * + * If settings are provided via both `settings()` and the `Firestore` + * constructor, both settings objects are merged and any settings provided + * via `settings()` take precedence. + * + * @param {object} settings The settings to use for all Firestore + * operations. + */ + settings(settings: Settings): void; + + /** + * Returns the Database ID for this Firestore instance. + */ + get databaseId(): string; + + /** + * Gets a `CollectionReference` instance that refers to the collection at + * the specified path. + * + * @param collectionPath A slash-separated path to a collection. + * @return The `CollectionReference` instance. + */ + collection(collectionPath: string): CollectionReference; + + /** + * Gets a `DocumentReference` instance that refers to the document at the + * specified path. + * + * @param documentPath A slash-separated path to a document. + * @return The `DocumentReference` instance. + */ + doc(documentPath: string): DocumentReference; + + /** + * Creates and returns a new Query that includes all documents in the + * database that are contained in a collection or subcollection with the + * given collectionId. + * + * @param collectionId Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @return The created `CollectionGroup`. + */ + collectionGroup(collectionId: string): CollectionGroup; + + /** + * Retrieves multiple documents from Firestore. + * + * The first argument is required and must be of type `DocumentReference` + * followed by any additional `DocumentReference` documents. If used, the + * optional `ReadOptions` must be the last argument. + * + * @param {Array.} documentRefsOrReadOptions + * The `DocumentReferences` to receive, followed by an optional field + * mask. + * @return A Promise that resolves with an array of resulting document + * snapshots. + */ + getAll( + ...documentRefsOrReadOptions: Array + ): Promise>; + + /** + * Recursively deletes all documents and subcollections at and under the + * specified level. + * + * If any delete fails, the promise is rejected with an error message + * containing the number of failed deletes and the stack trace of the last + * failed delete. The provided reference is deleted regardless of whether + * all deletes succeeded. + * + * `recursiveDelete()` uses a BulkWriter instance with default settings to + * perform the deletes. To customize throttling rates or add success/error + * callbacks, pass in a custom BulkWriter instance. + * + * @param ref The reference of a document or collection to delete. + * @param bulkWriter A custom BulkWriter instance used to perform the + * deletes. + * @return A promise that resolves when all deletes have been performed. + * The promise is rejected if any of the deletes fail. + * + * @example + * // Recursively delete a reference and log the references of failures. + * const bulkWriter = firestore.bulkWriter(); + * bulkWriter + * .onWriteError((error) => { + * if ( + * error.failedAttempts < MAX_RETRY_ATTEMPTS + * ) { + * return true; + * } else { + * console.log('Failed write at document: ', error.documentRef.path); + * return false; + * } + * }); + * await firestore.recursiveDelete(docRef, bulkWriter); + */ + recursiveDelete( + ref: CollectionReference | DocumentReference, + bulkWriter?: BulkWriter + ): Promise; + + /** + * Terminates the Firestore client and closes all open streams. + * + * @return A Promise that resolves when the client is terminated. + */ + terminate(): Promise; + + /** + * Fetches the root collections that are associated with this Firestore + * database. + * + * @returns A Promise that resolves with an array of CollectionReferences. + */ + listCollections(): Promise>; + + /** + * Executes the given updateFunction and commits the changes applied within + * the transaction. + * + * You can use the transaction object passed to 'updateFunction' to read and + * modify Firestore documents under lock. You have to perform all reads + * before you perform any write. + * + * Transactions can be performed as read-only or read-write transactions. By + * default, transactions are executed in read-write mode. + * + * A read-write transaction obtains a pessimistic lock on all documents that + * are read during the transaction. These locks block other transactions, + * batched writes, and other non-transactional writes from changing that + * document. Any writes in a read-write transactions are committed once + * 'updateFunction' resolves, which also releases all locks. + * + * If a read-write transaction fails with contention, the transaction is + * retried up to five times. The `updateFunction` is invoked once for each + * attempt. + * + * Read-only transactions do not lock documents. They can be used to read + * documents at a consistent snapshot in time, which may be up to 60 seconds + * in the past. Read-only transactions are not retried. + * + * Transactions time out after 60 seconds if no documents are read. + * Transactions that are not committed within than 270 seconds are also + * aborted. Any remaining locks are released when a transaction times out. + * + * @param updateFunction The function to execute within the transaction + * context. + * @param transactionOptions Transaction options. + * @return If the transaction completed successfully or was explicitly + * aborted (by the updateFunction returning a failed Promise), the Promise + * returned by the updateFunction will be returned here. Else if the + * transaction failed, a rejected Promise with the corresponding failure + * error will be returned. + */ + runTransaction( + updateFunction: (transaction: Transaction) => Promise, + transactionOptions?: + | ReadWriteTransactionOptions + | ReadOnlyTransactionOptions + ): Promise; + + /** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. + */ + batch(): WriteBatch; + + /** + * Creates a [BulkWriter]{@link BulkWriter}, used for performing + * multiple writes in parallel. Gradually ramps up writes as specified + * by the 500/50/5 rule. + * + * @see https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic + * + * @param options An options object used to configure the throttling + * behavior for the underlying BulkWriter. + */ + bulkWriter(options?: BulkWriterOptions): BulkWriter; + + /** + * Creates a new `BundleBuilder` instance to package selected Firestore data into + * a bundle. + * + * @param bundleId The ID of the bundle. When loaded on clients, client SDKs use this ID + * and the timestamp associated with the bundle to tell if it has been loaded already. + * If not specified, a random identifier will be used. + * + * + * @example + * const bundle = firestore.bundle('data-bundle'); + * const docSnapshot = await firestore.doc('abc/123').get(); + * const querySnapshot = await firestore.collection('coll').get(); + * + * const bundleBuffer = bundle.add(docSnapshot); // Add a document + * .add('coll-query', querySnapshot) // Add a named query. + * .build() + * // Save `bundleBuffer` to CDN or stream it to clients. + */ + bundle(bundleId?: string): BundleBuilder; + } + + /** + * An immutable object representing a geo point in Firestore. The geo point + * is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ + export class GeoPoint { + /** + * Creates a new immutable GeoPoint object with the provided latitude and + * longitude values. + * @param latitude The latitude as number between -90 and 90. + * @param longitude The longitude as number between -180 and 180. + */ + constructor(latitude: number, longitude: number); + + readonly latitude: number; + readonly longitude: number; + + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other The `GeoPoint` to compare against. + * @return true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other: GeoPoint): boolean; + } + + /** + * A reference to a transaction. + * The `Transaction` object passed to a transaction's updateFunction provides + * the methods to read and write data within the transaction context. See + * `Firestore.runTransaction()`. + */ + export class Transaction { + private constructor(); + + /** + * Retrieves a query result. Holds a pessimistic lock on all returned + * documents. + * + * @param query A query to execute. + * @return A QuerySnapshot for the retrieved data. + */ + get( + query: Query + ): Promise>; + + /** + * Reads the document referenced by the provided `DocumentReference.` + * Holds a pessimistic lock on the returned document. + * + * @param documentRef A reference to the document to be read. + * @return A DocumentSnapshot for the read data. + */ + get( + documentRef: DocumentReference + ): Promise>; + + /** + * Retrieves an aggregate query result. Holds a pessimistic lock on all + * documents that were matched by the underlying query. + * + * @param aggregateQuery An aggregate query to execute. + * @return An AggregateQuerySnapshot for the retrieved data. + */ + get< + AppModelType, + DbModelType extends DocumentData, + AggregateSpecType extends AggregateSpec, + >( + aggregateQuery: AggregateQuery< + AggregateSpecType, + AppModelType, + DbModelType + > + ): Promise< + AggregateQuerySnapshot + >; + + /** + * Retrieves multiple documents from Firestore. Holds a pessimistic lock on + * all returned documents. + * + * The first argument is required and must be of type `DocumentReference` + * followed by any additional `DocumentReference` documents. If used, the + * optional `ReadOptions` must be the last argument. + * + * @param {Array.} documentRefsOrReadOptions + * The `DocumentReferences` to receive, followed by an optional field + * mask. + * @return A Promise that resolves with an array of resulting document + * snapshots. + */ + getAll( + ...documentRefsOrReadOptions: Array< + DocumentReference | ReadOptions + > + ): Promise>>; + + /** + * Create the document referred to by the provided `DocumentReference`. + * The operation will fail the transaction if a document exists at the + * specified location. + * + * @param documentRef A reference to the document to be create. + * @param data The object data to serialize as the document. + * @throws Error If the provided input is not a valid Firestore document. + * @return This `Transaction` instance. Used for chaining method calls. + */ + create( + documentRef: DocumentReference, + data: WithFieldValue + ): Transaction; + + /** + * Writes to the document referred to by the provided `DocumentReference`. + * If the document does not exist yet, it will be created. If you pass + * `SetOptions`, the provided data can be merged into the existing document. + * + * @param documentRef A reference to the document to be set. + * @param data An object of the fields and values for the document. + * @param options An object to configure the set behavior. + * @param options.merge - If true, set() merges the values specified in its + * data argument. Fields omitted from this set() call remain untouched. If + * your input sets any field to an empty map, all nested fields are + * overwritten. + * @param options.mergeFields - If provided, set() only replaces the + * specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @throws Error If the provided input is not a valid Firestore document. + * @return This `Transaction` instance. Used for chaining method calls. + */ + set( + documentRef: DocumentReference, + data: PartialWithFieldValue, + options: SetOptions + ): Transaction; + set( + documentRef: DocumentReference, + data: WithFieldValue + ): Transaction; + + /** + * Updates fields in the document referred to by the provided + * `DocumentReference`. The update will fail if applied to a document that + * does not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings. + * + * @param documentRef A reference to the document to be updated. + * @param data An object containing the fields and values with which to + * update the document. + * @param precondition A Precondition to enforce on this update. + * @throws Error If the provided input is not valid Firestore data. + * @return This `Transaction` instance. Used for chaining method calls. + */ + update( + documentRef: DocumentReference, + data: UpdateData, + precondition?: Precondition + ): Transaction; + + /** + * Updates fields in the document referred to by the provided + * `DocumentReference`. The update will fail if applied to a document that + * does not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing FieldPath objects. + * + * A `Precondition` restricting this update can be specified as the last + * argument. + * + * @param documentRef A reference to the document to be updated. + * @param field The first field to update. + * @param value The first value + * @param fieldsOrPrecondition An alternating list of field paths and values + * to update, optionally followed by a `Precondition` to enforce on this + * update. + * @throws Error If the provided input is not valid Firestore data. + * @return This `Transaction` instance. Used for chaining method calls. + */ + update( + documentRef: DocumentReference, + field: string | FieldPath, + value: any, + ...fieldsOrPrecondition: any[] + ): Transaction; + + /** + * Deletes the document referred to by the provided `DocumentReference`. + * + * @param documentRef A reference to the document to be deleted. + * @param precondition A Precondition to enforce for this delete. + * @return This `Transaction` instance. Used for chaining method calls. + */ + delete( + documentRef: DocumentReference, + precondition?: Precondition + ): Transaction; + } + + /** + * A Firestore BulkWriter than can be used to perform a large number of writes + * in parallel. Writes to the same document will be executed sequentially. + * + * @class + */ + export class BulkWriter { + private constructor(); + + /** + * Create a document with the provided data. This single operation will fail + * if a document exists at its location. + * + * @param documentRef A reference to the document to be + * created. + * @param data The object to serialize as the document. + * @throws Error If the provided input is not a valid Firestore document. + * @returns A promise that resolves with the result of the write. If the + * write fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + */ + create( + documentRef: DocumentReference, + data: WithFieldValue + ): Promise; + + /** + * Delete a document from the database. + * + * @param documentRef A reference to the document to be + * deleted. + * @param precondition A precondition to enforce for this + * delete. + * @param precondition.lastUpdateTime If set, enforces that the + * document was last updated at lastUpdateTime. Fails the batch if the + * document doesn't exist or was last updated at a different time. + * @param precondition.exists If set, enforces that the target document + * must or must not exist. + * @returns A promise that resolves with the result of the delete. If the + * delete fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + */ + delete( + documentRef: DocumentReference, + precondition?: Precondition + ): Promise; + + /** + * Write to the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. If the document does not + * exist yet, it will be created. If you pass + * [SetOptions]{@link SetOptions}., the provided data can be merged into the + * existing document. + * + * @param documentRef A reference to the document to be + * set. + * @param data The object to serialize as the document. + * @param options An object to configure the set behavior. + * @param options.merge - If true, set() merges the values specified in its + * data argument. Fields omitted from this set() call remain untouched. If + * your input sets any field to an empty map, all nested fields are + * overwritten. + * @param options.mergeFields - If provided, set() only replaces the + * specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @throws Error If the provided input is not a valid Firestore document. + * @returns A promise that resolves with the result of the write. If the + * write fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + */ + set( + documentRef: DocumentReference, + data: PartialWithFieldValue, + options: SetOptions + ): Promise; + set( + documentRef: DocumentReference, + data: WithFieldValue + ): Promise; + + /** + * Update fields of the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. If the document doesn't yet + * exist, the update fails and the entire batch will be rejected. + * + * The update() method accepts either an object with field paths encoded as + * keys and field values encoded as values, or a variable number of + * arguments that alternate between field paths and field values. Nested + * fields can be updated by providing dot-separated field path strings or by + * providing FieldPath objects. + * + * + * A Precondition restricting this update can be specified as the last + * argument. + * + * @param documentRef A reference to the document to be updated. + * @param data An object containing the fields and values with which to + * update the document. + * @param precondition A Precondition to enforce on this update. + * @throws Error If the provided input is not valid Firestore data. + * @returns A promise that resolves with the result of the write. If the + * write fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + */ + update( + documentRef: DocumentReference, + data: UpdateData, + precondition?: Precondition + ): Promise; + + /** + * Update fields of the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. If the document doesn't yet + * exist, the update fails and the entire batch will be rejected. + * + * The update() method accepts either an object with field paths encoded as + * keys and field values encoded as values, or a variable number of + * arguments that alternate between field paths and field values. Nested + * fields can be updated by providing dot-separated field path strings or by + * providing FieldPath objects. + * + * + * A Precondition restricting this update can be specified as the last + * argument. + * + * @param documentRef A reference to the document to be updated. + * @param field The first field to update. + * @param value The first value + * @param fieldsOrPrecondition An alternating list of field paths and values + * to update, optionally followed a `Precondition` to enforce on this + * update. + * @throws Error If the provided input is not valid Firestore data; + * @returns A promise that resolves with the result of the write. If the + * write fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + */ + update( + documentRef: DocumentReference, + field: string | FieldPath, + value: any, + ...fieldsOrPrecondition: any[] + ): Promise; + + /** + * Attaches a listener that is run every time a BulkWriter operation + * successfully completes. + * + * @param callback A callback to be called every time a BulkWriter operation + * successfully completes. + */ + onWriteResult( + callback: ( + documentRef: DocumentReference, + result: WriteResult + ) => void + ): void; + + /** + * Attaches an error handler listener that is run every time a BulkWriter + * operation fails. + * + * BulkWriter has a default error handler that retries UNAVAILABLE and + * ABORTED errors up to a maximum of 10 failed attempts. When an error + * handler is specified, the default error handler will be overwritten. + * + * @param shouldRetryCallback A callback to be called every time a BulkWriter + * operation fails. Returning `true` will retry the operation. Returning + * `false` will stop the retry loop. + */ + onWriteError( + shouldRetryCallback: (error: BulkWriterError) => boolean + ): void; + + /** + * Commits all writes that have been enqueued up to this point in parallel. + * + * Returns a Promise that resolves when all currently queued operations have + * been committed. The Promise will never be rejected since the results for + * each individual operation are conveyed via their individual Promises. + * + * The Promise resolves immediately if there are no pending writes. + * Otherwise, the Promise waits for all previously issued writes, but it + * does not wait for writes that were added after the method is called. If + * you want to wait for additional writes, call `flush()` again. + * + * @return A promise that resolves when all enqueued writes + * up to this point have been committed. + */ + flush(): Promise; + + /** + * Commits all enqueued writes and marks the BulkWriter instance as closed. + * + * After calling `close()`, calling any method will throw an error. Any + * retries scheduled as part of an `onWriteError()` handler will be run + * before the `close()` promise resolves. + * + * Returns a Promise that resolves when all writes have been committed. The + * Promise will never be rejected. Calling this method will send all + * requests. The promise resolves immediately if there are no pending + * writes. + * + * @return A promise that resolves when all enqueued writes + * up to this point have been committed. + */ + close(): Promise; + } + + /** + * An options object to configure throttling on BulkWriter. + */ + export interface BulkWriterOptions { + /** + * Whether to disable or configure throttling. By default, throttling is + * enabled. This field can be set to either a boolean or a config + * object. Setting it to `true` will use default values. You can override + * the defaults by setting it to `false` to disable throttling, or by + * setting the config values to enable throttling with the provided values. + * + * @see https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic + * + * @param initialOpsPerSecond The initial maximum number of operations per + * second allowed by the throttler. If this field is not set, the default + * is 500 operations per second. + * @param maxOpsPerSecond The maximum number of operations per second + * allowed by the throttler. If this field is set, the throttler's allowed + * operations per second does not ramp up past the specified operations per + * second. + */ + readonly throttling?: + | boolean + | {initialOpsPerSecond?: number; maxOpsPerSecond?: number}; + } + + /** + * The error thrown when a BulkWriter operation fails. + */ + export class BulkWriterError extends Error { + /** The status code of the error. */ + readonly code: GrpcStatus; + + /** The error message of the error. */ + readonly message: string; + + /** The document reference the operation was performed on. */ + readonly documentRef: DocumentReference; + + /** The type of operation performed. */ + readonly operationType: 'create' | 'set' | 'update' | 'delete'; + + /** How many times this operation has been attempted unsuccessfully. */ + readonly failedAttempts: number; + } + + /** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling `Firestore.batch()`. It + * provides methods for adding writes to the write batch. None of the + * writes will be committed (or visible locally) until `WriteBatch.commit()` + * is called. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + */ + export class WriteBatch { + private constructor(); + + /** + * Create the document referred to by the provided `DocumentReference`. The + * operation will fail the batch if a document exists at the specified + * location. + * + * @param documentRef A reference to the document to be created. + * @param data The object data to serialize as the document. + * @throws Error If the provided input is not a valid Firestore document. + * @return This `WriteBatch` instance. Used for chaining method calls. + */ + create( + documentRef: DocumentReference, + data: WithFieldValue + ): WriteBatch; + + /** + * Write to the document referred to by the provided `DocumentReference`. + * If the document does not exist yet, it will be created. If you pass + * `SetOptions`, the provided data can be merged into the existing document. + * + * @param documentRef A reference to the document to be set. + * @param data An object of the fields and values for the document. + * @param options An object to configure the set behavior. + * @param options.merge - If true, set() merges the values specified in its + * data argument. Fields omitted from this set() call remain untouched. If + * your input sets any field to an empty map, all nested fields are + * overwritten. + * @param options.mergeFields - If provided, set() only replaces the + * specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @throws Error If the provided input is not a valid Firestore document. + * @return This `WriteBatch` instance. Used for chaining method calls. + */ + set( + documentRef: DocumentReference, + data: PartialWithFieldValue, + options: SetOptions + ): WriteBatch; + set( + documentRef: DocumentReference, + data: WithFieldValue + ): WriteBatch; + + /** + * Update fields of the document referred to by the provided + * `DocumentReference`. If the document doesn't yet exist, the update fails + * and the entire batch will be rejected. + * + * Nested fields can be updated by providing dot-separated field path + * strings. + * + * @param documentRef A reference to the document to be updated. + * @param data An object containing the fields and values with which to + * update the document. + * @param precondition A Precondition to enforce on this update. + * @throws Error If the provided input is not valid Firestore data. + * @return This `WriteBatch` instance. Used for chaining method calls. + */ + update( + documentRef: DocumentReference, + data: UpdateData, + precondition?: Precondition + ): WriteBatch; + + /** + * Updates fields in the document referred to by the provided + * `DocumentReference`. The update will fail if applied to a document that + * does not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing FieldPath objects. + * + * A `Precondition` restricting this update can be specified as the last + * argument. + * + * @param documentRef A reference to the document to be updated. + * @param field The first field to update. + * @param value The first value + * @param fieldsOrPrecondition An alternating list of field paths and values + * to update, optionally followed a `Precondition` to enforce on this + * update. + * @throws Error If the provided input is not valid Firestore data. + * @return This `WriteBatch` instance. Used for chaining method calls. + */ + update( + documentRef: DocumentReference, + field: string | FieldPath, + value: any, + ...fieldsOrPrecondition: any[] + ): WriteBatch; + + /** + * Deletes the document referred to by the provided `DocumentReference`. + * + * @param documentRef A reference to the document to be deleted. + * @param precondition A Precondition to enforce for this delete. + * @return This `WriteBatch` instance. Used for chaining method calls. + */ + delete( + documentRef: DocumentReference, + precondition?: Precondition + ): WriteBatch; + + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * @return A Promise resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit. + */ + commit(): Promise; + } + + /** + * An options object that configures conditional behavior of `update()` and + * `delete()` calls in `DocumentReference`, `WriteBatch`, and `Transaction`. + * Using Preconditions, these calls can be restricted to only apply to + * documents that match the specified restrictions. + */ + export interface Precondition { + /** + * If set, the last update time to enforce. + */ + readonly lastUpdateTime?: Timestamp; + + /** + * If set, enforces that the target document must or must not exist. + */ + readonly exists?: boolean; + } + + /** + * An options object that configures the behavior of `set()` calls in + * `DocumentReference`, `WriteBatch` and `Transaction`. These calls can be + * configured to perform granular merges instead of overwriting the target + * documents in their entirety. + * + * @param merge Changes the behavior of a set() call to only replace the + * values specified in its data argument. Fields omitted from the set() call + * remain untouched. If your input sets any field to an empty map, all nested + * fields are overwritten. + * + * @param mergeFields Changes the behavior of set() calls to only replace + * the specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + */ + export type SetOptions = + | { + readonly merge?: boolean; + } + | { + readonly mergeFields?: Array; + }; + + /** + * An options object that can be used to configure the behavior of `getAll()` + * calls. By providing a `fieldMask`, these calls can be configured to only + * return a subset of fields. + */ + export interface ReadOptions { + /** + * Specifies the set of fields to return and reduces the amount of data + * transmitted by the backend. + * + * Adding a field mask does not filter results. Documents do not need to + * contain values for all the fields in the mask to be part of the result + * set. + */ + readonly fieldMask?: (string | FieldPath)[]; + } + + /** + * A WriteResult wraps the write time set by the Firestore servers on `sets()`, + * `updates()`, and `creates()`. + */ + export class WriteResult { + private constructor(); + + /** + * The write time as set by the Firestore servers. + */ + readonly writeTime: Timestamp; + + /** + * Returns true if this `WriteResult` is equal to the provided one. + * + * @param other The `WriteResult` to compare against. + * @return true if this `WriteResult` is equal to the provided one. + */ + isEqual(other: WriteResult): boolean; + } + + /** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. A `DocumentReference` can + * also be used to create a `CollectionReference` to a subcollection. + */ + export class DocumentReference< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + private constructor(); + + /** The identifier of the document within its collection. */ + readonly id: string; + + /** + * The `Firestore` for the Firestore database (useful for performing + * transactions, etc.). + */ + readonly firestore: Firestore; + + /** + * A reference to the Collection to which this DocumentReference belongs. + */ + readonly parent: CollectionReference; + + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + readonly path: string; + + /** + * Gets a `CollectionReference` instance that refers to the collection at + * the specified path. + * + * @param collectionPath A slash-separated path to a collection. + * @return The `CollectionReference` instance. + */ + collection(collectionPath: string): CollectionReference; + + /** + * Fetches the subcollections that are direct children of this document. + * + * @returns A Promise that resolves with an array of CollectionReferences. + */ + listCollections(): Promise>; + + /** + * Creates a document referred to by this `DocumentReference` with the + * provided object values. The write fails if the document already exists + * + * @param data The object data to serialize as the document. + * @throws {Error} If the provided input is not a valid Firestore document or if the document already exists. + * @return A Promise resolved with the write time of this create. + */ + create(data: WithFieldValue): Promise; + + /** + * Writes to the document referred to by this `DocumentReference`. If the + * document does not yet exist, it will be created. If you pass + * `SetOptions`, the provided data can be merged into an existing document. + * + * @param data A map of the fields and values for the document. + * @param options An object to configure the set behavior. + * @param options.merge - If true, set() merges the values specified in its + * data argument. Fields omitted from this set() call remain untouched. If + * your input sets any field to an empty map, all nested fields are + * overwritten. + * @param options.mergeFields - If provided, set() only replaces the + * specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @throws Error If the provided input is not a valid Firestore document. + * @return A Promise resolved with the write time of this set. + */ + set( + data: PartialWithFieldValue, + options: SetOptions + ): Promise; + set(data: WithFieldValue): Promise; + + /** + * Updates fields in the document referred to by this `DocumentReference`. + * The update will fail if applied to a document that does not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings. + * + * @param data An object containing the fields and values with which to + * update the document. + * @param precondition A Precondition to enforce on this update. + * @throws Error If the provided input is not valid Firestore data. + * @return A Promise resolved with the write time of this update. + */ + update( + data: UpdateData, + precondition?: Precondition + ): Promise; + + /** + * Updates fields in the document referred to by this `DocumentReference`. + * The update will fail if applied to a document that does not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing FieldPath objects. + * + * A `Precondition` restricting this update can be specified as the last + * argument. + * + * @param field The first field to update. + * @param value The first value. + * @param moreFieldsOrPrecondition An alternating list of field paths and + * values to update, optionally followed by a `Precondition` to enforce on + * this update. + * @throws Error If the provided input is not valid Firestore data. + * @return A Promise resolved with the write time of this update. + */ + update( + field: string | FieldPath, + value: any, + ...moreFieldsOrPrecondition: any[] + ): Promise; + + /** + * Deletes the document referred to by this `DocumentReference`. + * + * @param precondition A Precondition to enforce for this delete. + * @return A Promise resolved with the write time of this delete. + */ + delete(precondition?: Precondition): Promise; + + /** + * Reads the document referred to by this `DocumentReference`. + * + * @return A Promise resolved with a DocumentSnapshot containing the + * current document contents. + */ + get(): Promise>; + + /** + * Attaches a listener for DocumentSnapshot events. + * + * @param onNext A callback to be called every time a new `DocumentSnapshot` + * is available. + * @param onError A callback to be called if the listen fails or is + * cancelled. No further callbacks will occur. + * @return An unsubscribe function that can be called to cancel + * the snapshot listener. + */ + onSnapshot( + onNext: (snapshot: DocumentSnapshot) => void, + onError?: (error: Error) => void + ): () => void; + + /** + * Returns true if this `DocumentReference` is equal to the provided one. + * + * @param other The `DocumentReference` to compare against. + * @return true if this `DocumentReference` is equal to the provided one. + */ + isEqual(other: DocumentReference): boolean; + + /** + * Applies a custom data converter to this DocumentReference, allowing you + * to use your own custom model objects with Firestore. When you call + * set(), get(), etc. on the returned DocumentReference instance, the + * provided converter will convert between Firestore data of type + * `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter Converts objects to and from Firestore. Passing in + * `null` removes the current converter. + * @return A DocumentReference that uses the provided converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends DocumentData = DocumentData, + >( + converter: FirestoreDataConverter + ): DocumentReference; + withConverter(converter: null): DocumentReference; + } + + /** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists` property to + * explicitly verify a document's existence. + */ + export class DocumentSnapshot< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + protected constructor(); + + /** True if the document exists. */ + readonly exists: boolean; + + /** A `DocumentReference` to the document location. */ + readonly ref: DocumentReference; + + /** + * The ID of the document for which this `DocumentSnapshot` contains data. + */ + readonly id: string; + + /** + * The time the document was created. Not set for documents that don't + * exist. + */ + readonly createTime?: Timestamp; + + /** + * The time the document was last updated (at the time the snapshot was + * generated). Not set for documents that don't exist. + */ + readonly updateTime?: Timestamp; + + /** + * The time this snapshot was read. + */ + readonly readTime: Timestamp; + + /** + * Retrieves all fields in the document as an Object. Returns 'undefined' if + * the document doesn't exist. + * + * @return An Object containing all fields in the document. + */ + data(): AppModelType | undefined; + + /** + * Retrieves the field specified by `fieldPath`. + * + * @param fieldPath The path (e.g. 'foo' or 'foo.bar') to a specific field. + * @return The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath): any; + + /** + * Returns true if the document's data and path in this `DocumentSnapshot` + * is equal to the provided one. + * + * @param other The `DocumentSnapshot` to compare against. + * @return true if this `DocumentSnapshot` is equal to the provided one. + */ + isEqual(other: DocumentSnapshot): boolean; + } + + /** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ + export class QueryDocumentSnapshot< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > extends DocumentSnapshot { + private constructor(); + + /** + * The time the document was created. + */ + readonly createTime: Timestamp; + + /** + * The time the document was last updated (at the time the snapshot was + * generated). + */ + readonly updateTime: Timestamp; + + /** + * Retrieves all fields in the document as an Object. + * + * @override + * @return An Object containing all fields in the document. + */ + data(): AppModelType; + } + + /** + * The direction of a `Query.orderBy()` clause is specified as 'desc' or 'asc' + * (descending or ascending). + */ + export type OrderByDirection = 'desc' | 'asc'; + + /** + * Filter conditions in a `Query.where()` clause are specified using the + * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', 'not-in', + * and 'array-contains-any'. + */ + export type WhereFilterOp = + | '<' + | '<=' + | '==' + | '!=' + | '>=' + | '>' + | 'array-contains' + | 'in' + | 'not-in' + | 'array-contains-any'; + + /** + * A `Query` refers to a Query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ + export class Query< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + protected constructor(); + + /** + * The `Firestore` for the Firestore database (useful for performing + * transactions, etc.). + */ + readonly firestore: Firestore; + + /** + * Creates and returns a new Query with the additional filter that documents + * must contain the specified field and that its value should satisfy the + * relation constraint provided. + * + * This function returns a new (immutable) instance of the Query (rather + * than modify the existing instance) to impose the filter. + * + * @param fieldPath The path to compare + * @param opStr The operation string (e.g "<", "<=", "==", ">", ">="). + * @param value The value for comparison + * @return The created Query. + */ + where( + fieldPath: string | FieldPath, + opStr: WhereFilterOp, + value: any + ): Query; + + /** + * Creates and returns a new [Query]{@link Query} with the additional filter + * that documents should satisfy the relation constraint provided. Documents + * must contain the field specified in the filter. + * + * This function returns a new (immutable) instance of the Query (rather than + * modify the existing instance) to impose the filter. + * + * @param {Filter} filter A filter to apply to the Query. + * @returns {Query} The created Query. + */ + where(filter: Filter): Query; + + /** + * Creates and returns a new Query that's additionally sorted by the + * specified field, optionally in descending order instead of ascending. + * + * This function returns a new (immutable) instance of the Query (rather + * than modify the existing instance) to impose the order. + * + * @param fieldPath The field to sort by. + * @param directionStr Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @return The created Query. + */ + orderBy( + fieldPath: string | FieldPath, + directionStr?: OrderByDirection + ): Query; + + /** + * Creates and returns a new Query that only returns the first matching + * documents. + * + * This function returns a new (immutable) instance of the Query (rather + * than modify the existing instance) to impose the limit. + * + * @param limit The maximum number of items to return. + * @return The created Query. + */ + limit(limit: number): Query; + + /** + * Creates and returns a new Query that only returns the last matching + * documents. + * + * You must specify at least one orderBy clause for limitToLast queries, + * otherwise an exception will be thrown during execution. + * + * Results for limitToLast queries cannot be streamed via the `stream()` + * API. + * + * @param limit The maximum number of items to return. + * @return The created Query. + */ + limitToLast(limit: number): Query; + + /** + * Specifies the offset of the returned results. + * + * This function returns a new (immutable) instance of the Query (rather + * than modify the existing instance) to impose the offset. + * + * @param offset The offset to apply to the Query results. + * @return The created Query. + */ + offset(offset: number): Query; + + /** + * Creates and returns a new Query instance that applies a field mask to + * the result and returns only the specified subset of fields. You can + * specify a list of field paths to return, or use an empty list to only + * return the references of matching documents. + * + * Queries that contain field masks cannot be listened to via `onSnapshot()` + * listeners. + * + * This function returns a new (immutable) instance of the Query (rather + * than modify the existing instance) to impose the field mask. + * + * @param field The field paths to return. + * @return The created Query. + */ + select(...field: (string | FieldPath)[]): Query; + + /** + * Creates and returns a new Query that starts at the provided document + * (inclusive). The starting position is relative to the order of the query. + * The document must contain all of the fields provided in the orderBy of + * this query. + * + * @param snapshot The snapshot of the document to start after. + * @return The created Query. + */ + startAt( + snapshot: DocumentSnapshot + ): Query; + + /** + * Creates and returns a new Query that starts at the provided fields + * relative to the order of the query. The order of the field values + * must match the order of the order by clauses of the query. + * + * @param fieldValues The field values to start this query at, in order + * of the query's order by. + * @return The created Query. + */ + startAt(...fieldValues: any[]): Query; + + /** + * Creates and returns a new Query that starts after the provided document + * (exclusive). The starting position is relative to the order of the query. + * The document must contain all of the fields provided in the orderBy of + * this query. + * + * @param snapshot The snapshot of the document to start after. + * @return The created Query. + */ + startAfter( + snapshot: DocumentSnapshot + ): Query; + + /** + * Creates and returns a new Query that starts after the provided fields + * relative to the order of the query. The order of the field values + * must match the order of the order by clauses of the query. + * + * @param fieldValues The field values to start this query after, in order + * of the query's order by. + * @return The created Query. + */ + startAfter(...fieldValues: any[]): Query; + + /** + * Creates and returns a new Query that ends before the provided document + * (exclusive). The end position is relative to the order of the query. The + * document must contain all of the fields provided in the orderBy of this + * query. + * + * @param snapshot The snapshot of the document to end before. + * @return The created Query. + */ + endBefore( + snapshot: DocumentSnapshot + ): Query; + + /** + * Creates and returns a new Query that ends before the provided fields + * relative to the order of the query. The order of the field values + * must match the order of the order by clauses of the query. + * + * @param fieldValues The field values to end this query before, in order + * of the query's order by. + * @return The created Query. + */ + endBefore(...fieldValues: any[]): Query; + + /** + * Creates and returns a new Query that ends at the provided document + * (inclusive). The end position is relative to the order of the query. The + * document must contain all of the fields provided in the orderBy of this + * query. + * + * @param snapshot The snapshot of the document to end at. + * @return The created Query. + */ + endAt( + snapshot: DocumentSnapshot + ): Query; + + /** + * Creates and returns a new Query that ends at the provided fields + * relative to the order of the query. The order of the field values + * must match the order of the order by clauses of the query. + * + * @param fieldValues The field values to end this query at, in order + * of the query's order by. + * @return The created Query. + */ + endAt(...fieldValues: any[]): Query; + + /** + * Executes the query and returns the results as a `QuerySnapshot`. + * + * @return A Promise that will be resolved with the results of the Query. + */ + get(): Promise>; + + /** + * Plans and optionally executes this query. Returns a Promise that will be + * resolved with the planner information, statistics from the query execution (if any), + * and the query results (if any). + * + * @return A Promise that will be resolved with the planner information, statistics + * from the query execution (if any), and the query results (if any). + */ + explain( + options?: ExplainOptions + ): Promise>>; + + /** + * Executes the query and returns the results as Node Stream. + * + * @return A stream of QueryDocumentSnapshot. + */ + stream(): NodeJS.ReadableStream; + + /** + * Plans and optionally executes this query, and streams the results as Node Stream + * of `{document?: DocumentSnapshot, metrics?: ExplainMetrics}` objects. + * + * The stream surfaces documents one at a time as they are received from the + * server, and at the end, it will surface the metrics associated with + * executing the query (if any). + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * let count = 0; + * + * query.explainStream({analyze: true}).on('data', (data) => { + * if (data.document) { + * // Use data.document which is a DocumentSnapshot instance. + * console.log(`Found document with name '${data.document.id}'`); + * ++count; + * } + * if (data.metrics) { + * // Use data.metrics which is an ExplainMetrics instance. + * } + * }).on('end', () => { + * console.log(`Received ${count} documents.`); + * }); + * ``` + * + * @return A stream of `{document?: DocumentSnapshot, metrics?: ExplainMetrics}` + * objects. + */ + explainStream(options?: ExplainOptions): NodeJS.ReadableStream; + + /** + * Attaches a listener for `QuerySnapshot `events. + * + * @param onNext A callback to be called every time a new `QuerySnapshot` + * is available. + * @param onError A callback to be called if the listen fails or is + * cancelled. No further callbacks will occur. + * @return An unsubscribe function that can be called to cancel + * the snapshot listener. + */ + onSnapshot( + onNext: (snapshot: QuerySnapshot) => void, + onError?: (error: Error) => void + ): () => void; + + /** + * Returns a query that counts the documents in the result set of this + * query. + * + * The returned query, when executed, counts the documents in the result set + * of this query without actually downloading the documents. + * + * Using the returned query to count the documents is efficient because only + * the final count, not the documents' data, is downloaded. The returned + * query can count the documents in cases where the result set is + * prohibitively large to download entirely (thousands of documents). + * + * @return a query that counts the documents in the result set of this + * query. The count can be retrieved from `snapshot.data().count`, where + * `snapshot` is the `AggregateQuerySnapshot` resulting from running the + * returned query. + */ + count(): AggregateQuery< + {count: AggregateField}, + AppModelType, + DbModelType + >; + + /** + * Returns a query that can perform the given aggregations. + * + * The returned query, when executed, calculates the specified aggregations + * over the documents in the result set of this query without actually + * downloading the documents. + * + * Using the returned query to perform aggregations is efficient because only + * the final aggregation values, not the documents' data, is downloaded. The + * returned query can perform aggregations of the documents in cases where + * the result set is prohibitively large to download entirely (thousands of + * documents). + * + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateQuery = col.aggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const aggregateSnapshot = await aggregateQuery.get(); + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ + aggregate( + aggregateSpec: T + ): AggregateQuery; + + /** + * Returns a query that can perform vector distance (similarity) search with given parameters. + * + * The returned query, when executed, performs a distance (similarity) search on the specified + * `vectorField` against the given `queryVector` and returns the top documents that are closest + * to the `queryVector`. + * + * Only documents whose `vectorField` field is a {@link VectorValue} of the same dimension as `queryVector` + * participate in the query, all other documents are ignored. + * + * @example + * ``` + * // Returns the closest 10 documents whose Euclidean distance from their 'embedding' fields are closed to [41, 42]. + * const vectorQuery = col.findNearest('embedding', [41, 42], {limit: 10, distanceMeasure: 'EUCLIDEAN'}); + * + * const querySnapshot = await aggregateQuery.get(); + * querySnapshot.forEach(...); + * ``` + * + * @param vectorField - A string or {@link FieldPath} specifying the vector field to search on. + * @param queryVector - The {@link VectorValue} used to measure the distance from `vectorField` values in the documents. + * @param options - Options control the vector query. `limit` specifies the upper bound of documents to return, must + * be a positive integer with a maximum value of 1000. `distanceMeasure` specifies what type of distance is calculated + * when performing the query. + * + * @deprecated Use the new {@link findNearest} implementation + * accepting a single `options` param. + */ + findNearest( + vectorField: string | FieldPath, + queryVector: VectorValue | Array, + options: { + limit: number; + distanceMeasure: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT'; + } + ): VectorQuery; + + /** + * Returns a query that can perform vector distance (similarity) search with given parameters. + * + * The returned query, when executed, performs a distance (similarity) search on the specified + * `vectorField` against the given `queryVector` and returns the top documents that are closest + * to the `queryVector`. + * + * Only documents whose `vectorField` field is a {@link VectorValue} of the same dimension as `queryVector` + * participate in the query, all other documents are ignored. + * + * @example + * ``` + * // Returns the closest 10 documents whose Euclidean distance from their 'embedding' fields are closed to [41, 42]. + * const vectorQuery = col.findNearest({ + * vectorField: 'embedding', + * queryVector: [41, 42], + * limit: 10, + * distanceMeasure: 'EUCLIDEAN', + * distanceResultField: 'distance', + * distanceThreshold: 0.125 + * }); + * + * const querySnapshot = await aggregateQuery.get(); + * querySnapshot.forEach(...); + * ``` + * @param options - An argument specifying the behavior of the {@link VectorQuery} returned by this function. + * See {@link VectorQueryOptions}. + */ + findNearest( + options: VectorQueryOptions + ): VectorQuery; + + /** + * Returns true if this `Query` is equal to the provided one. + * + * @param other The `Query` to compare against. + * @return true if this `Query` is equal to the provided one. + */ + isEqual(other: Query): boolean; + + /** + * Applies a custom data converter to this Query, allowing you to use your + * own custom model objects with Firestore. When you call get() on the + * returned Query, the provided converter will convert between Firestore + * data of type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter Converts objects to and from Firestore. Passing in + * `null` removes the current converter. + * @return A Query that uses the provided converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends DocumentData = DocumentData, + >( + converter: FirestoreDataConverter + ): Query; + withConverter(converter: null): Query; + } + + /** + * A `QuerySnapshot` contains zero or more `QueryDocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ + export class QuerySnapshot< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + private constructor(); + + /** + * The query on which you called `get` or `onSnapshot` in order to get this + * `QuerySnapshot`. + */ + readonly query: Query; + + /** An array of all the documents in the QuerySnapshot. */ + readonly docs: Array>; + + /** The number of documents in the QuerySnapshot. */ + readonly size: number; + + /** True if there are no documents in the QuerySnapshot. */ + readonly empty: boolean; + + /** The time this query snapshot was obtained. */ + readonly readTime: Timestamp; + + /** + * Returns an array of the documents changes since the last snapshot. If + * this is the first snapshot, all documents will be in the list as added + * changes. + */ + docChanges(): DocumentChange[]; + + /** + * Enumerates all of the documents in the QuerySnapshot. + * + * @param callback A callback to be called with a `DocumentSnapshot` for + * each document in the snapshot. + * @param thisArg The `this` binding for the callback. + */ + forEach( + callback: ( + result: QueryDocumentSnapshot + ) => void, + thisArg?: any + ): void; + + /** + * Returns true if the document data in this `QuerySnapshot` is equal to the + * provided one. + * + * @param other The `QuerySnapshot` to compare against. + * @return true if this `QuerySnapshot` is equal to the provided one. + */ + isEqual(other: QuerySnapshot): boolean; + } + + /** + * A `VectorQuerySnapshot` contains zero or more `QueryDocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ + export class VectorQuerySnapshot< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + private constructor(); + + /** + * The query on which you called `get` in order to get this + * `VectorQuerySnapshot`. + */ + readonly query: VectorQuery; + + /** An array of all the documents in the QuerySnapshot. */ + readonly docs: Array>; + + /** The number of documents in the QuerySnapshot. */ + readonly size: number; + + /** True if there are no documents in the QuerySnapshot. */ + readonly empty: boolean; + + /** The time this query snapshot was obtained. */ + readonly readTime: Timestamp; + + /** + * Returns an array of the documents changes since the last snapshot. If + * this is the first snapshot, all documents will be in the list as added + * changes. + */ + docChanges(): DocumentChange[]; + + /** + * Enumerates all of the documents in the QuerySnapshot. + * + * @param callback A callback to be called with a `DocumentSnapshot` for + * each document in the snapshot. + * @param thisArg The `this` binding for the callback. + */ + forEach( + callback: ( + result: QueryDocumentSnapshot + ) => void, + thisArg?: any + ): void; + + /** + * Returns true if the document data in this `VectorQuerySnapshot` is equal to the + * provided one. + * + * @param other The `VectorQuerySnapshot` to compare against. + * @return true if this `VectorQuerySnapshot` is equal to the provided one. + */ + isEqual(other: VectorQuerySnapshot): boolean; + } + + /** + * The type of `DocumentChange` may be 'added', 'removed', or 'modified'. + */ + export type DocumentChangeType = 'added' | 'removed' | 'modified'; + + /** + * A `DocumentChange` represents a change to the documents matching a query. + * It contains the document affected and the type of change that occurred. + */ + export interface DocumentChange< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + /** The type of change ('added', 'modified', or 'removed'). */ + readonly type: DocumentChangeType; + + /** The document affected by this change. */ + readonly doc: QueryDocumentSnapshot; + + /** + * The index of the changed document in the result set immediately prior to + * this DocumentChange (i.e. supposing that all prior DocumentChange objects + * have been applied). Is -1 for 'added' events. + */ + readonly oldIndex: number; + + /** + * The index of the changed document in the result set immediately after + * this DocumentChange (i.e. supposing that all prior DocumentChange + * objects and the current DocumentChange object have been applied). + * Is -1 for 'removed' events. + */ + readonly newIndex: number; + + /** + * Returns true if the data in this `DocumentChange` is equal to the + * provided one. + * + * @param other The `DocumentChange` to compare against. + * @return true if this `DocumentChange` is equal to the provided one. + */ + isEqual(other: DocumentChange): boolean; + } + + /** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using the methods + * inherited from `Query`). + */ + export class CollectionReference< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > extends Query { + private constructor(); + + /** The identifier of the collection. */ + readonly id: string; + + /** + * A reference to the containing Document if this is a subcollection, else + * null. + */ + readonly parent: DocumentReference | null; + + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + readonly path: string; + + /** + * Retrieves the list of documents in this collection. + * + * The document references returned may include references to "missing + * documents", i.e. document locations that have no document present but + * which contain subcollections with documents. Attempting to read such a + * document reference (e.g. via `.get()` or `.onSnapshot()`) will return a + * `DocumentSnapshot` whose `.exists` property is false. + * + * @return {Promise} The list of documents in this + * collection. + */ + listDocuments(): Promise< + Array> + >; + + /** + * Get a `DocumentReference` for a randomly-named document within this + * collection. An automatically-generated unique ID will be used as the + * document ID. + * + * @return The `DocumentReference` instance. + */ + doc(): DocumentReference; + + /** + * Get a `DocumentReference` for the document within the collection at the + * specified path. + * + * @param documentPath A slash-separated path to a document. + * @return The `DocumentReference` instance. + */ + doc(documentPath: string): DocumentReference; + + /** + * Add a new document to this collection with the specified data, assigning + * it a document ID automatically. + * + * @param data An Object containing the data for the new document. + * @throws Error If the provided input is not a valid Firestore document. + * @return A Promise resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ + add( + data: WithFieldValue + ): Promise>; + + /** + * Returns true if this `CollectionReference` is equal to the provided one. + * + * @param other The `CollectionReference` to compare against. + * @return true if this `CollectionReference` is equal to the provided one. + */ + isEqual(other: CollectionReference): boolean; + + /** + * Applies a custom data converter to this CollectionReference, allowing you + * to use your own custom model objects with Firestore. When you call add() + * on the returned CollectionReference instance, the provided converter will + * convert between Firestore data of type `NewDbModelType` and your custom + * type `NewAppModelType`. + * + * @param converter Converts objects to and from Firestore. Passing in + * `null` removes the current converter. + * @return A CollectionReference that uses the provided converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends DocumentData = DocumentData, + >( + converter: FirestoreDataConverter + ): CollectionReference; + withConverter(converter: null): CollectionReference; + } + + /** + * A `CollectionGroup` refers to all documents that are contained in a + * collection or subcollection with a specific collection ID. + */ + export class CollectionGroup< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > extends Query { + private constructor(); + + /** + * Partitions a query by returning partition cursors that can be used to run + * the query in parallel. The returned cursors are split points that can be + * used as starting and end points for individual query invocations. + * + * @param desiredPartitionCount The desired maximum number of partition + * points. The number must be strictly positive. The actual number of + * partitions returned may be fewer. + * @return An AsyncIterable of `QueryPartition`s. + */ + getPartitions( + desiredPartitionCount: number + ): AsyncIterable>; + + /** + * Applies a custom data converter to this `CollectionGroup`, allowing you + * to use your own custom model objects with Firestore. When you call get() + * on the returned `CollectionGroup`, the provided converter will convert + * between Firestore data of type `NewDbModelType` and your custom type + * `NewAppModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * @example + * class Post { + * constructor(readonly title: string, readonly author: string) {} + * + * toString(): string { + * return this.title + ', by ' + this.author; + * } + * } + * + * const postConverter = { + * toFirestore(post: Post): FirebaseFirestore.DocumentData { + * return {title: post.title, author: post.author}; + * }, + * fromFirestore( + * snapshot: FirebaseFirestore.QueryDocumentSnapshot + * ): Post { + * const data = snapshot.data(); + * return new Post(data.title, data.author); + * } + * }; + * + * const querySnapshot = await Firestore() + * .collectionGroup('posts') + * .withConverter(postConverter) + * .get(); + * for (const doc of querySnapshot.docs) { + * const post = doc.data(); + * post.title; // string + * post.toString(); // Should be defined + * post.someNonExistentProperty; // TS error + * } + * + * @param converter Converts objects to and from Firestore. Passing in + * `null` removes the current converter. + * @return A `CollectionGroup` that uses the provided converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends DocumentData = DocumentData, + >( + converter: FirestoreDataConverter + ): CollectionGroup; + withConverter(converter: null): CollectionGroup; + } + + /** + * A split point that can be used in a query as a starting and/or end point for + * the query results. The cursors returned by {@link #startAt} and {@link + * #endBefore} can only be used in a query that matches the constraint of query + * that produced this partition. + */ + export class QueryPartition< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + private constructor(); + + /** + * The cursor that defines the first result for this partition or + * `undefined` if this is the first partition. The cursor value must be + * destructured when passed to `startAt()` (for example with + * `query.startAt(...queryPartition.startAt)`). + * + * @return Cursor values that can be used with {@link Query#startAt} or + * `undefined` if this is the first partition. + */ + get startAt(): unknown[] | undefined; + + /** + * The cursor that defines the first result after this partition or + * `undefined` if this is the last partition. The cursor value must be + * destructured when passed to `endBefore()` (for example with + * `query.endBefore(...queryPartition.endBefore)`). + * + * @return Cursor values that can be used with {@link Query#endBefore} or + * `undefined` if this is the last partition. + */ + get endBefore(): unknown[] | undefined; + + /** + * Returns a query that only returns the documents for this partition. + * + * @return A query partitioned by a {@link Query#startAt} and {@link + * Query#endBefore} cursor. + */ + toQuery(): Query; + } + + /** + * Union type representing the aggregate type to be performed. + */ + export type AggregateType = 'count' | 'avg' | 'sum'; + + /** + * The union of all `AggregateField` types that are supported by Firestore. + */ + export type AggregateFieldType = + | ReturnType + | ReturnType + | ReturnType; + + /** + * Represents an aggregation that can be performed by Firestore. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + export class AggregateField { + private constructor(); + + /** A type string to uniquely identify instances of this class. */ + readonly type = 'AggregateField'; + + /** The kind of aggregation performed by this AggregateField. */ + public readonly aggregateType: AggregateType; + + /** + * Compares this object with the given object for equality. + * + * This object is considered "equal" to the other object if and only if + * `other` performs the same kind of aggregation on the same field (if any). + * + * @param other The object to compare to this object for equality. + * @return `true` if this object is "equal" to the given object, as + * defined above, or `false` otherwise. + */ + isEqual(other: AggregateField): boolean; + + /** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ + static count(): AggregateField; + + /** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ + static average(field: string | FieldPath): AggregateField; + + /** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ + static sum(field: string | FieldPath): AggregateField; + } + + /** + * A type whose property values are all `AggregateField` objects. + */ + export interface AggregateSpec { + [field: string]: AggregateFieldType; + } + + /** + * A type whose keys are taken from an `AggregateSpec`, and whose values are + * the result of the aggregation performed by the corresponding + * `AggregateField` from the input `AggregateSpec`. + */ + export type AggregateSpecData = { + [P in keyof T]: T[P] extends AggregateField ? U : never; + }; + + /** + * A query that calculates aggregations over an underlying query. + */ + export class AggregateQuery< + AggregateSpecType extends AggregateSpec, + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + private constructor(); + + /** The query whose aggregations will be calculated by this object. */ + readonly query: Query; + + /** + * Executes this query. + * + * @return A promise that will be resolved with the results of the query. + */ + get(): Promise< + AggregateQuerySnapshot + >; + + /** + * Plans and optionally executes this query. Returns a Promise that will be + * resolved with the planner information, statistics from the query execution (if any), + * and the query results (if any). + * + * @return A Promise that will be resolved with the planner information, statistics + * from the query execution (if any), and the query results (if any). + */ + explain( + options?: ExplainOptions + ): Promise< + ExplainResults< + AggregateQuerySnapshot + > + >; + + /** + * Compares this object with the given object for equality. + * + * This object is considered "equal" to the other object if and only if + * `other` performs the same aggregations as this `AggregateQuery` and + * the underlying Query of `other` compares equal to that of this object + * using `Query.isEqual()`. + * + * @param other The object to compare to this object for equality. + * @return `true` if this object is "equal" to the given object, as + * defined above, or `false` otherwise. + */ + isEqual( + other: AggregateQuery + ): boolean; + } + + /** + * The results of executing an aggregation query. + */ + export class AggregateQuerySnapshot< + AggregateSpecType extends AggregateSpec, + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + private constructor(); + + /** The query that was executed to produce this result. */ + readonly query: AggregateQuery< + AggregateSpecType, + AppModelType, + DbModelType + >; + + /** The time this snapshot was read. */ + readonly readTime: Timestamp; + + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the + * values will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): AggregateSpecData; + + /** + * Compares this object with the given object for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they + * have the same data and their underlying queries compare "equal" using + * `AggregateQuery.isEqual()`. + * + * @param other The object to compare to this object for equality. + * @return `true` if this object is "equal" to the given object, as + * defined above, or `false` otherwise. + */ + isEqual( + other: AggregateQuerySnapshot< + AggregateSpecType, + AppModelType, + DbModelType + > + ): boolean; + } + + /** + * A query that finds the document whose vector fields are closest to a certain vector. + */ + export class VectorQuery< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + private constructor(); + + /** The query whose results participants in the distance search. */ + readonly query: Query; + + /** + * Executes this query. + * + * @return A promise that will be resolved with the results of the query. + */ + get(): Promise>; + + /** + * Compares this object with the given object for equality. + * + * This object is considered "equal" to the other object if and only if + * `other` performs the same vector distance search as this `VectorQuery` and + * the underlying Query of `other` compares equal to that of this object + * using `Query.isEqual()`. + * + * @param other The object to compare to this object for equality. + * @return `true` if this object is "equal" to the given object, as + * defined above, or `false` otherwise. + */ + isEqual(other: VectorQuery): boolean; + } + + /** + * Represent a vector type in Firestore documents. + */ + export class VectorValue { + private constructor(values: number[] | undefined); + + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray(): number[]; + + /** + * Returns true if the two `VectorValue` has the same raw number arrays, returns false otherwise. + */ + isEqual(other: VectorValue): boolean; + } + + /** + * Sentinel values that can be used when writing document fields with set(), + * create() or update(). + */ + export class FieldValue { + private constructor(); + + /** + * Returns a sentinel used with set(), create() or update() to include a + * server-generated timestamp in the written data. + * + * @return The FieldValue sentinel for use in a call to set(), create() or + * update(). + */ + static serverTimestamp(): FieldValue; + + /** + * Returns a sentinel for use with update() or set() with {merge:true} to + * mark a field for deletion. + * + * @return The FieldValue sentinel for use in a call to set() or update(). + */ + static delete(): FieldValue; + + /** + * Returns a special value that can be used with set(), create() or update() + * that tells the server to increment the field's current value by the given + * value. + * + * If either current field value or the operand uses floating point + * precision, both values will be interpreted as floating point numbers and + * all arithmetic will follow IEEE 754 semantics. Otherwise, integer + * precision is kept and the result is capped between -2^63 and 2^63-1. + * + * If the current field value is not of type 'number', or if the field does + * not yet exist, the transformation will set the field to the given value. + * + * @param n The value to increment by. + * @return The FieldValue sentinel for use in a call to set(), create() or + * update(). + */ + static increment(n: number): FieldValue; + + /** + * Returns a special value that can be used with set(), create() or update() + * that tells the server to union the given elements with any array value + * that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements The elements to union into the array. + * @return The FieldValue sentinel for use in a call to set(), create() or + * update(). + */ + static arrayUnion(...elements: any[]): FieldValue; + + /** + * Returns a special value that can be used with set(), create() or update() + * that tells the server to remove the given elements from any array value + * that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is + * not already an array it will be overwritten with an empty array. + * + * @param elements The elements to remove from the array. + * @return The FieldValue sentinel for use in a call to set(), create() or + * update(). + */ + static arrayRemove(...elements: any[]): FieldValue; + + /** + * @return A new `VectorValue` constructed with a copy of the given array of number. + */ + static vector(values?: number[]): VectorValue; + + /** + * Returns true if this `FieldValue` is equal to the provided one. + * + * @param other The `FieldValue` to compare against. + * @return true if this `FieldValue` is equal to the provided one. + */ + isEqual(other: FieldValue): boolean; + } + + /** + * A FieldPath refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + */ + export class FieldPath { + /** + * Creates a FieldPath from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames A list of field names. + */ + constructor(...fieldNames: string[]); + + /** + * Returns a special sentinel FieldPath to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ + static documentId(): FieldPath; + + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other The `FieldPath` to compare against. + * @return true if this `FieldPath` is equal to the provided one. + */ + isEqual(other: FieldPath): boolean; + } + + /** + * A Timestamp represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian + * Calendar which extends the Gregorian calendar backwards to year one. It is + * encoded assuming all minutes are 60 seconds long, i.e. leap seconds are + * "smeared" so that no leap second table is needed for interpretation. Range + * is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. + * + * @see https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto + */ + export class Timestamp { + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @return A new `Timestamp` representing the current date. + */ + static now(): Timestamp; + + /** + * Creates a new timestamp from the given date. + * + * @param date The date to initialize the `Timestamp` from. + * @return A new `Timestamp` representing the same point in time as the + * given date. + */ + static fromDate(date: Date): Timestamp; + + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @return A new `Timestamp` representing the same point in time as the + * given number of milliseconds. + */ + static fromMillis(milliseconds: number): Timestamp; + + /** + * Creates a new timestamp. + * + * @param seconds The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be from + * 0 to 999,999,999 inclusive. + */ + constructor(seconds: number, nanoseconds: number); + + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + readonly seconds: number; + + /** The non-negative fractions of a second at nanosecond resolution. */ + readonly nanoseconds: number; + + /** + * Returns a new `Date` corresponding to this timestamp. This may lose + * precision. + * + * @return JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate(): Date; + + /** + * Returns the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + * + * @return The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis(): number; + + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other The `Timestamp` to compare against. + * @return 'true' if this `Timestamp` is equal to the provided one. + */ + isEqual(other: Timestamp): boolean; + + /** + * Converts this object to a primitive `string`, which allows `Timestamp` objects to be compared + * using the `>`, `<=`, `>=` and `>` operators. + * + * @return a string encoding of this object. + */ + valueOf(): string; + } + + /** + * Builds a Firestore data bundle with results from the given document and query snapshots. + */ + export class BundleBuilder { + /** The ID of this bundle. */ + readonly bundleId: string; + + /** + * Adds a Firestore `DocumentSnapshot` to the bundle. Both the documents data and the document + * read time will be included in the bundle. + * + * @param documentSnapshot A `DocumentSnapshot` to add. + * @returns This instance. + */ + add( + documentSnapshot: DocumentSnapshot + ): BundleBuilder; + + /** + * Adds a Firestore `QuerySnapshot` to the bundle. Both the documents in the query results and + * the query read time will be included in the bundle. + * + * @param queryName The name of the query to add. + * @param querySnapshot A `QuerySnapshot` to add to the bundle. + * @returns This instance. + */ + add( + queryName: string, + querySnapshot: QuerySnapshot + ): BundleBuilder; + + /** + * Builds the bundle and returns the result as a `Buffer` instance. + */ + build(): Buffer; + } + + /** + * The v1beta1 Veneer client. This client provides access to to the underlying + * Firestore v1beta1 RPCs. + * @deprecated Use v1 instead. + */ + export const v1beta1: { + FirestoreClient: typeof import('./v1beta1/firestore_client').FirestoreClient; + }; + + /** + * The v1 Veneer clients. These clients provide access to the Firestore Admin + * API and the underlying Firestore v1 RPCs. + */ + export const v1: { + FirestoreClient: typeof import('./v1/firestore_client').FirestoreClient; + FirestoreAdminClient: typeof import('./v1/firestore_admin_client').FirestoreAdminClient; + }; + + /** + * Status codes returned by Firestore's gRPC calls. + */ + export enum GrpcStatus { + OK = 0, + CANCELLED = 1, + UNKNOWN = 2, + INVALID_ARGUMENT = 3, + DEADLINE_EXCEEDED = 4, + NOT_FOUND = 5, + ALREADY_EXISTS = 6, + PERMISSION_DENIED = 7, + RESOURCE_EXHAUSTED = 8, + FAILED_PRECONDITION = 9, + ABORTED = 10, + OUT_OF_RANGE = 11, + UNIMPLEMENTED = 12, + INTERNAL = 13, + UNAVAILABLE = 14, + DATA_LOSS = 15, + UNAUTHENTICATED = 16, + } + + /** + * A `Filter` represents a restriction on one or more field values and can + * be used to refine the results of a {@link Query}. + * `Filters`s are created by invoking {@link Filter#where}, {@link Filter#or}, + * or {@link Filter#and} and can then be passed to {@link Query#where} + * to create a new {@link Query} instance that also contains this `Filter`. + */ + export abstract class Filter { + /** + * Creates and returns a new [Filter]{@link Filter}, which can be + * applied to [Query.where()]{@link Query#where}, [Filter.or()]{@link Filter#or}, + * or [Filter.and()]{@link Filter#and}. When applied to a [Query]{@link Query} + * it requires that documents must contain the specified field and that its value should + * satisfy the relation constraint provided. + * + * Returns a new Filter that can be used to constrain the value of a Document property. + * + * @param {string|FieldPath} fieldPath The name of a property value to compare. + * @param {string} opStr A comparison operation in the form of a string + * (e.g., "<"). + * @param {*} value The value to which to compare the field for inclusion in + * a query. + * @returns {Filter} The created Filter. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * collectionRef.where(Filter.where('foo', '==', 'bar')).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + static where( + fieldPath: string | FieldPath, + opStr: WhereFilterOp, + value: unknown + ): Filter; + + /** + * Creates and returns a new [Filter]{@link Filter} that is a + * disjunction of the given {@link Filter}s. A disjunction filter includes + * a document if it satisfies any of the given {@link Filter}s. + * + * The returned Filter can be applied to [Query.where()]{@link Query#where}, + * [Filter.or()]{@link Filter#or}, or [Filter.and()]{@link Filter#and}. When + * applied to a [Query]{@link Query} it requires that documents must satisfy + * one of the provided {@link Filter}s. + * + * @param {...Filter} filters Optional. The {@link Filter}s + * for OR operation. These must be created with calls to {@link Filter#where}, + * {@link Filter#or}, or {@link Filter#and}. + * @returns {Filter} The created {@link Filter}. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * // doc.foo == 'bar' || doc.baz > 0 + * let orFilter = Filter.or(Filter.where('foo', '==', 'bar'), Filter.where('baz', '>', 0)); + * + * collectionRef.where(orFilter).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + static or(...filters: Filter[]): Filter; + + /** + * Creates and returns a new [Filter]{@link Filter} that is a + * conjunction of the given {@link Filter}s. A conjunction filter includes + * a document if it satisfies all of the given {@link Filter}s. + * + * The returned Filter can be applied to [Query.where()]{@link Query#where}, + * [Filter.or()]{@link Filter#or}, or [Filter.and()]{@link Filter#and}. When + * applied to a [Query]{@link Query} it requires that documents must satisfy + * one of the provided {@link Filter}s. + * + * @param {...Filter} filters Optional. The {@link Filter}s + * for OR operation. These must be created with calls to {@link Filter#where}, + * {@link Filter#or}, or {@link Filter#and}. + * @returns {Filter} The created {@link Filter}. + * + * @example + * ``` + * let collectionRef = firestore.collection('col'); + * + * // doc.foo == 'bar' && doc.baz > 0 + * let orFilter = Filter.and(Filter.where('foo', '==', 'bar'), Filter.where('baz', '>', 0)); + * + * collectionRef.where(orFilter).get().then(querySnapshot => { + * querySnapshot.forEach(documentSnapshot => { + * console.log(`Found document at ${documentSnapshot.ref.path}`); + * }); + * }); + * ``` + */ + static and(...filters: Filter[]): Filter; + } + + type Duration = { + /** Signed seconds of the span of time. */ + seconds: number; + + /** + * Signed fractions of a second at nanosecond resolution of the span + * of time. Durations less than one second are represented with a 0 + * `seconds` field and a positive or negative `nanos` field. For durations + * of one second or more, a non-zero value for the `nanos` field must be + * of the same sign as the `seconds` field. Must be from -999,999,999 + * to +999,999,999 inclusive. + */ + nanoseconds: number; + }; + + /** Options used to configure explain queries. */ + export interface ExplainOptions { + /** + * Whether analyzing the query is enabled. If true, the query will be + * executed and execution statistics will be returned as part of the + * [ExplainResults]{@link ExplainResults}. + */ + readonly analyze?: boolean; + } + + /** + * PlanSummary contains information about the planning stage of a query. + */ + export interface PlanSummary { + /** + * Information about the indexes that were used to serve the query. + * This should be inspected or logged, because the contents are intended to be + * human-readable. Contents are subject to change, and it is advised to not + * program against this object. + */ + readonly indexesUsed: Record[]; + } + + /** ExecutionStats contains information about the execution of a query. */ + export interface ExecutionStats { + /** The number of query results. */ + readonly resultsReturned: number; + + /** The total execution time of the query. */ + readonly executionDuration: Duration; + + /** The number of read operations that occurred when executing the query. */ + readonly readOperations: number; + + /** + * Contains additional statistics related to the query execution. + * This should be inspected or logged, because the contents are intended to be + * human-readable. Contents are subject to change, and it is advised to not + * program against this object. + */ + readonly debugStats: Record; + } + + /** + * ExplainMetrics contains information about planning and execution of a query. + */ + export interface ExplainMetrics { + /** + * Information about the query plan. + */ + readonly planSummary: PlanSummary; + + /** + * Information about the execution of the query, or null if the query was + * not executed. + */ + readonly executionStats: ExecutionStats | null; + } + + /** + * ExplainResults contains information about planning, execution, and results + * of a query. + */ + export interface ExplainResults { + /** + * Information about planning and execution of the query. + */ + readonly metrics: ExplainMetrics; + + /** + * The snapshot that contains the results of executing the query, or null + * if the query was not executed. + */ + readonly snapshot: T | null; + } + + /** + * Specifies the behavior of the {@link VectorQuery} generated by a call to {@link Query.findNearest}. + */ + export interface VectorQueryOptions { + /** + * A string or {@link FieldPath} specifying the vector field to search on. + */ + vectorField: string | FieldPath; + + /** + * The {@link VectorValue} used to measure the distance from `vectorField` values in the documents. + */ + queryVector: VectorValue | Array; + + /** + * Specifies the upper bound of documents to return, must be a positive integer with a maximum value of 1000. + */ + limit: number; + + /** + * Specifies what type of distance is calculated when performing the query. + */ + distanceMeasure: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT'; + + /** + * Optionally specifies the name of a field that will be set on each returned DocumentSnapshot, + * which will contain the computed distance for the document. + */ + distanceResultField?: string | FieldPath; + + /** + * Specifies a threshold for which no less similar documents will be returned. The behavior + * of the specified `distanceMeasure` will affect the meaning of the distance threshold. + * + * - For `distanceMeasure: "EUCLIDEAN"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE euclidean_distance <= distanceThreshold + * - For `distanceMeasure: "COSINE"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE cosine_distance <= distanceThreshold + * - For `distanceMeasure: "DOT_PRODUCT"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE dot_product_distance >= distanceThreshold + */ + distanceThreshold?: number; + } +} + +declare module '@google-cloud/firestore' { + export = FirebaseFirestore; +} diff --git a/node_modules/@google-cloud/firestore/types/protos/firestore_admin_v1_proto_api.d.ts b/node_modules/@google-cloud/firestore/types/protos/firestore_admin_v1_proto_api.d.ts new file mode 100644 index 0000000..4240ac5 --- /dev/null +++ b/node_modules/@google-cloud/firestore/types/protos/firestore_admin_v1_proto_api.d.ts @@ -0,0 +1,9761 @@ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as $protobuf from "protobufjs"; +/** Namespace google. */ +export namespace google { + + /** Namespace firestore. */ + namespace firestore { + + /** Namespace admin. */ + namespace admin { + + /** Namespace v1. */ + namespace v1 { + + /** Properties of a Backup. */ + interface IBackup { + + /** Backup name */ + name?: (string|null); + + /** Backup database */ + database?: (string|null); + + /** Backup databaseUid */ + databaseUid?: (string|null); + + /** Backup snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + + /** Backup expireTime */ + expireTime?: (google.protobuf.ITimestamp|null); + + /** Backup stats */ + stats?: (google.firestore.admin.v1.Backup.IStats|null); + + /** Backup state */ + state?: (google.firestore.admin.v1.Backup.State|null); + } + + /** Represents a Backup. */ + class Backup implements IBackup { + + /** + * Constructs a new Backup. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBackup); + + /** Backup name. */ + public name: string; + + /** Backup database. */ + public database: string; + + /** Backup databaseUid. */ + public databaseUid: string; + + /** Backup snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** Backup expireTime. */ + public expireTime?: (google.protobuf.ITimestamp|null); + + /** Backup stats. */ + public stats?: (google.firestore.admin.v1.Backup.IStats|null); + + /** Backup state. */ + public state: google.firestore.admin.v1.Backup.State; + + /** + * Creates a Backup message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Backup + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Backup; + + /** + * Creates a plain object from a Backup message. Also converts values to other types if specified. + * @param message Backup + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Backup, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Backup to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Backup + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Backup { + + /** Properties of a Stats. */ + interface IStats { + + /** Stats sizeBytes */ + sizeBytes?: (number|string|null); + + /** Stats documentCount */ + documentCount?: (number|string|null); + + /** Stats indexCount */ + indexCount?: (number|string|null); + } + + /** Represents a Stats. */ + class Stats implements IStats { + + /** + * Constructs a new Stats. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Backup.IStats); + + /** Stats sizeBytes. */ + public sizeBytes: (number|string); + + /** Stats documentCount. */ + public documentCount: (number|string); + + /** Stats indexCount. */ + public indexCount: (number|string); + + /** + * Creates a Stats message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Stats + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Backup.Stats; + + /** + * Creates a plain object from a Stats message. Also converts values to other types if specified. + * @param message Stats + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Backup.Stats, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Stats to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Stats + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** State enum. */ + type State = + "STATE_UNSPECIFIED"| "CREATING"| "READY"| "NOT_AVAILABLE"; + } + + /** Properties of a Database. */ + interface IDatabase { + + /** Database name */ + name?: (string|null); + + /** Database uid */ + uid?: (string|null); + + /** Database createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** Database updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** Database deleteTime */ + deleteTime?: (google.protobuf.ITimestamp|null); + + /** Database locationId */ + locationId?: (string|null); + + /** Database type */ + type?: (google.firestore.admin.v1.Database.DatabaseType|null); + + /** Database concurrencyMode */ + concurrencyMode?: (google.firestore.admin.v1.Database.ConcurrencyMode|null); + + /** Database versionRetentionPeriod */ + versionRetentionPeriod?: (google.protobuf.IDuration|null); + + /** Database earliestVersionTime */ + earliestVersionTime?: (google.protobuf.ITimestamp|null); + + /** Database pointInTimeRecoveryEnablement */ + pointInTimeRecoveryEnablement?: (google.firestore.admin.v1.Database.PointInTimeRecoveryEnablement|null); + + /** Database appEngineIntegrationMode */ + appEngineIntegrationMode?: (google.firestore.admin.v1.Database.AppEngineIntegrationMode|null); + + /** Database keyPrefix */ + keyPrefix?: (string|null); + + /** Database deleteProtectionState */ + deleteProtectionState?: (google.firestore.admin.v1.Database.DeleteProtectionState|null); + + /** Database cmekConfig */ + cmekConfig?: (google.firestore.admin.v1.Database.ICmekConfig|null); + + /** Database previousId */ + previousId?: (string|null); + + /** Database sourceInfo */ + sourceInfo?: (google.firestore.admin.v1.Database.ISourceInfo|null); + + /** Database etag */ + etag?: (string|null); + } + + /** Represents a Database. */ + class Database implements IDatabase { + + /** + * Constructs a new Database. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDatabase); + + /** Database name. */ + public name: string; + + /** Database uid. */ + public uid: string; + + /** Database createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** Database updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** Database deleteTime. */ + public deleteTime?: (google.protobuf.ITimestamp|null); + + /** Database locationId. */ + public locationId: string; + + /** Database type. */ + public type: google.firestore.admin.v1.Database.DatabaseType; + + /** Database concurrencyMode. */ + public concurrencyMode: google.firestore.admin.v1.Database.ConcurrencyMode; + + /** Database versionRetentionPeriod. */ + public versionRetentionPeriod?: (google.protobuf.IDuration|null); + + /** Database earliestVersionTime. */ + public earliestVersionTime?: (google.protobuf.ITimestamp|null); + + /** Database pointInTimeRecoveryEnablement. */ + public pointInTimeRecoveryEnablement: google.firestore.admin.v1.Database.PointInTimeRecoveryEnablement; + + /** Database appEngineIntegrationMode. */ + public appEngineIntegrationMode: google.firestore.admin.v1.Database.AppEngineIntegrationMode; + + /** Database keyPrefix. */ + public keyPrefix: string; + + /** Database deleteProtectionState. */ + public deleteProtectionState: google.firestore.admin.v1.Database.DeleteProtectionState; + + /** Database cmekConfig. */ + public cmekConfig?: (google.firestore.admin.v1.Database.ICmekConfig|null); + + /** Database previousId. */ + public previousId: string; + + /** Database sourceInfo. */ + public sourceInfo?: (google.firestore.admin.v1.Database.ISourceInfo|null); + + /** Database etag. */ + public etag: string; + + /** + * Creates a Database message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Database + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database; + + /** + * Creates a plain object from a Database message. Also converts values to other types if specified. + * @param message Database + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Database to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Database + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Database { + + /** DatabaseType enum. */ + type DatabaseType = + "DATABASE_TYPE_UNSPECIFIED"| "FIRESTORE_NATIVE"| "DATASTORE_MODE"; + + /** ConcurrencyMode enum. */ + type ConcurrencyMode = + "CONCURRENCY_MODE_UNSPECIFIED"| "OPTIMISTIC"| "PESSIMISTIC"| "OPTIMISTIC_WITH_ENTITY_GROUPS"; + + /** PointInTimeRecoveryEnablement enum. */ + type PointInTimeRecoveryEnablement = + "POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED"| "POINT_IN_TIME_RECOVERY_ENABLED"| "POINT_IN_TIME_RECOVERY_DISABLED"; + + /** AppEngineIntegrationMode enum. */ + type AppEngineIntegrationMode = + "APP_ENGINE_INTEGRATION_MODE_UNSPECIFIED"| "ENABLED"| "DISABLED"; + + /** DeleteProtectionState enum. */ + type DeleteProtectionState = + "DELETE_PROTECTION_STATE_UNSPECIFIED"| "DELETE_PROTECTION_DISABLED"| "DELETE_PROTECTION_ENABLED"; + + /** Properties of a CmekConfig. */ + interface ICmekConfig { + + /** CmekConfig kmsKeyName */ + kmsKeyName?: (string|null); + + /** CmekConfig activeKeyVersion */ + activeKeyVersion?: (string[]|null); + } + + /** Represents a CmekConfig. */ + class CmekConfig implements ICmekConfig { + + /** + * Constructs a new CmekConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.ICmekConfig); + + /** CmekConfig kmsKeyName. */ + public kmsKeyName: string; + + /** CmekConfig activeKeyVersion. */ + public activeKeyVersion: string[]; + + /** + * Creates a CmekConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CmekConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.CmekConfig; + + /** + * Creates a plain object from a CmekConfig message. Also converts values to other types if specified. + * @param message CmekConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.CmekConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CmekConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CmekConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a SourceInfo. */ + interface ISourceInfo { + + /** SourceInfo backup */ + backup?: (google.firestore.admin.v1.Database.SourceInfo.IBackupSource|null); + + /** SourceInfo operation */ + operation?: (string|null); + } + + /** Represents a SourceInfo. */ + class SourceInfo implements ISourceInfo { + + /** + * Constructs a new SourceInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.ISourceInfo); + + /** SourceInfo backup. */ + public backup?: (google.firestore.admin.v1.Database.SourceInfo.IBackupSource|null); + + /** SourceInfo operation. */ + public operation: string; + + /** SourceInfo source. */ + public source?: "backup"; + + /** + * Creates a SourceInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceInfo + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.SourceInfo; + + /** + * Creates a plain object from a SourceInfo message. Also converts values to other types if specified. + * @param message SourceInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.SourceInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace SourceInfo { + + /** Properties of a BackupSource. */ + interface IBackupSource { + + /** BackupSource backup */ + backup?: (string|null); + } + + /** Represents a BackupSource. */ + class BackupSource implements IBackupSource { + + /** + * Constructs a new BackupSource. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.SourceInfo.IBackupSource); + + /** BackupSource backup. */ + public backup: string; + + /** + * Creates a BackupSource message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BackupSource + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.SourceInfo.BackupSource; + + /** + * Creates a plain object from a BackupSource message. Also converts values to other types if specified. + * @param message BackupSource + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.SourceInfo.BackupSource, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BackupSource to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BackupSource + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an EncryptionConfig. */ + interface IEncryptionConfig { + + /** EncryptionConfig googleDefaultEncryption */ + googleDefaultEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.IGoogleDefaultEncryptionOptions|null); + + /** EncryptionConfig useSourceEncryption */ + useSourceEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.ISourceEncryptionOptions|null); + + /** EncryptionConfig customerManagedEncryption */ + customerManagedEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.ICustomerManagedEncryptionOptions|null); + } + + /** Represents an EncryptionConfig. */ + class EncryptionConfig implements IEncryptionConfig { + + /** + * Constructs a new EncryptionConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.IEncryptionConfig); + + /** EncryptionConfig googleDefaultEncryption. */ + public googleDefaultEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.IGoogleDefaultEncryptionOptions|null); + + /** EncryptionConfig useSourceEncryption. */ + public useSourceEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.ISourceEncryptionOptions|null); + + /** EncryptionConfig customerManagedEncryption. */ + public customerManagedEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.ICustomerManagedEncryptionOptions|null); + + /** EncryptionConfig encryptionType. */ + public encryptionType?: ("googleDefaultEncryption"|"useSourceEncryption"|"customerManagedEncryption"); + + /** + * Creates an EncryptionConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EncryptionConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.EncryptionConfig; + + /** + * Creates a plain object from an EncryptionConfig message. Also converts values to other types if specified. + * @param message EncryptionConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.EncryptionConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EncryptionConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EncryptionConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace EncryptionConfig { + + /** Properties of a GoogleDefaultEncryptionOptions. */ + interface IGoogleDefaultEncryptionOptions { + } + + /** Represents a GoogleDefaultEncryptionOptions. */ + class GoogleDefaultEncryptionOptions implements IGoogleDefaultEncryptionOptions { + + /** + * Constructs a new GoogleDefaultEncryptionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.EncryptionConfig.IGoogleDefaultEncryptionOptions); + + /** + * Creates a GoogleDefaultEncryptionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GoogleDefaultEncryptionOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.EncryptionConfig.GoogleDefaultEncryptionOptions; + + /** + * Creates a plain object from a GoogleDefaultEncryptionOptions message. Also converts values to other types if specified. + * @param message GoogleDefaultEncryptionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.EncryptionConfig.GoogleDefaultEncryptionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GoogleDefaultEncryptionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GoogleDefaultEncryptionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a SourceEncryptionOptions. */ + interface ISourceEncryptionOptions { + } + + /** Represents a SourceEncryptionOptions. */ + class SourceEncryptionOptions implements ISourceEncryptionOptions { + + /** + * Constructs a new SourceEncryptionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.EncryptionConfig.ISourceEncryptionOptions); + + /** + * Creates a SourceEncryptionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceEncryptionOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.EncryptionConfig.SourceEncryptionOptions; + + /** + * Creates a plain object from a SourceEncryptionOptions message. Also converts values to other types if specified. + * @param message SourceEncryptionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.EncryptionConfig.SourceEncryptionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceEncryptionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceEncryptionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CustomerManagedEncryptionOptions. */ + interface ICustomerManagedEncryptionOptions { + + /** CustomerManagedEncryptionOptions kmsKeyName */ + kmsKeyName?: (string|null); + } + + /** Represents a CustomerManagedEncryptionOptions. */ + class CustomerManagedEncryptionOptions implements ICustomerManagedEncryptionOptions { + + /** + * Constructs a new CustomerManagedEncryptionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.EncryptionConfig.ICustomerManagedEncryptionOptions); + + /** CustomerManagedEncryptionOptions kmsKeyName. */ + public kmsKeyName: string; + + /** + * Creates a CustomerManagedEncryptionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomerManagedEncryptionOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.EncryptionConfig.CustomerManagedEncryptionOptions; + + /** + * Creates a plain object from a CustomerManagedEncryptionOptions message. Also converts values to other types if specified. + * @param message CustomerManagedEncryptionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.EncryptionConfig.CustomerManagedEncryptionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomerManagedEncryptionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CustomerManagedEncryptionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + + /** Properties of a Field. */ + interface IField { + + /** Field name */ + name?: (string|null); + + /** Field indexConfig */ + indexConfig?: (google.firestore.admin.v1.Field.IIndexConfig|null); + + /** Field ttlConfig */ + ttlConfig?: (google.firestore.admin.v1.Field.ITtlConfig|null); + } + + /** Represents a Field. */ + class Field implements IField { + + /** + * Constructs a new Field. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IField); + + /** Field name. */ + public name: string; + + /** Field indexConfig. */ + public indexConfig?: (google.firestore.admin.v1.Field.IIndexConfig|null); + + /** Field ttlConfig. */ + public ttlConfig?: (google.firestore.admin.v1.Field.ITtlConfig|null); + + /** + * Creates a Field message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Field + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Field; + + /** + * Creates a plain object from a Field message. Also converts values to other types if specified. + * @param message Field + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Field, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Field to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Field + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Field { + + /** Properties of an IndexConfig. */ + interface IIndexConfig { + + /** IndexConfig indexes */ + indexes?: (google.firestore.admin.v1.IIndex[]|null); + + /** IndexConfig usesAncestorConfig */ + usesAncestorConfig?: (boolean|null); + + /** IndexConfig ancestorField */ + ancestorField?: (string|null); + + /** IndexConfig reverting */ + reverting?: (boolean|null); + } + + /** Represents an IndexConfig. */ + class IndexConfig implements IIndexConfig { + + /** + * Constructs a new IndexConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Field.IIndexConfig); + + /** IndexConfig indexes. */ + public indexes: google.firestore.admin.v1.IIndex[]; + + /** IndexConfig usesAncestorConfig. */ + public usesAncestorConfig: boolean; + + /** IndexConfig ancestorField. */ + public ancestorField: string; + + /** IndexConfig reverting. */ + public reverting: boolean; + + /** + * Creates an IndexConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IndexConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Field.IndexConfig; + + /** + * Creates a plain object from an IndexConfig message. Also converts values to other types if specified. + * @param message IndexConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Field.IndexConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IndexConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IndexConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a TtlConfig. */ + interface ITtlConfig { + + /** TtlConfig state */ + state?: (google.firestore.admin.v1.Field.TtlConfig.State|null); + } + + /** Represents a TtlConfig. */ + class TtlConfig implements ITtlConfig { + + /** + * Constructs a new TtlConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Field.ITtlConfig); + + /** TtlConfig state. */ + public state: google.firestore.admin.v1.Field.TtlConfig.State; + + /** + * Creates a TtlConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TtlConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Field.TtlConfig; + + /** + * Creates a plain object from a TtlConfig message. Also converts values to other types if specified. + * @param message TtlConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Field.TtlConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TtlConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TtlConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TtlConfig { + + /** State enum. */ + type State = + "STATE_UNSPECIFIED"| "CREATING"| "ACTIVE"| "NEEDS_REPAIR"; + } + } + + /** Properties of an Index. */ + interface IIndex { + + /** Index name */ + name?: (string|null); + + /** Index queryScope */ + queryScope?: (google.firestore.admin.v1.Index.QueryScope|null); + + /** Index apiScope */ + apiScope?: (google.firestore.admin.v1.Index.ApiScope|null); + + /** Index fields */ + fields?: (google.firestore.admin.v1.Index.IIndexField[]|null); + + /** Index state */ + state?: (google.firestore.admin.v1.Index.State|null); + } + + /** Represents an Index. */ + class Index implements IIndex { + + /** + * Constructs a new Index. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IIndex); + + /** Index name. */ + public name: string; + + /** Index queryScope. */ + public queryScope: google.firestore.admin.v1.Index.QueryScope; + + /** Index apiScope. */ + public apiScope: google.firestore.admin.v1.Index.ApiScope; + + /** Index fields. */ + public fields: google.firestore.admin.v1.Index.IIndexField[]; + + /** Index state. */ + public state: google.firestore.admin.v1.Index.State; + + /** + * Creates an Index message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Index + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index; + + /** + * Creates a plain object from an Index message. Also converts values to other types if specified. + * @param message Index + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Index, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Index to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Index + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Index { + + /** QueryScope enum. */ + type QueryScope = + "QUERY_SCOPE_UNSPECIFIED"| "COLLECTION"| "COLLECTION_GROUP"| "COLLECTION_RECURSIVE"; + + /** ApiScope enum. */ + type ApiScope = + "ANY_API"| "DATASTORE_MODE_API"; + + /** Properties of an IndexField. */ + interface IIndexField { + + /** IndexField fieldPath */ + fieldPath?: (string|null); + + /** IndexField order */ + order?: (google.firestore.admin.v1.Index.IndexField.Order|null); + + /** IndexField arrayConfig */ + arrayConfig?: (google.firestore.admin.v1.Index.IndexField.ArrayConfig|null); + + /** IndexField vectorConfig */ + vectorConfig?: (google.firestore.admin.v1.Index.IndexField.IVectorConfig|null); + } + + /** Represents an IndexField. */ + class IndexField implements IIndexField { + + /** + * Constructs a new IndexField. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Index.IIndexField); + + /** IndexField fieldPath. */ + public fieldPath: string; + + /** IndexField order. */ + public order?: (google.firestore.admin.v1.Index.IndexField.Order|null); + + /** IndexField arrayConfig. */ + public arrayConfig?: (google.firestore.admin.v1.Index.IndexField.ArrayConfig|null); + + /** IndexField vectorConfig. */ + public vectorConfig?: (google.firestore.admin.v1.Index.IndexField.IVectorConfig|null); + + /** IndexField valueMode. */ + public valueMode?: ("order"|"arrayConfig"|"vectorConfig"); + + /** + * Creates an IndexField message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IndexField + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index.IndexField; + + /** + * Creates a plain object from an IndexField message. Also converts values to other types if specified. + * @param message IndexField + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Index.IndexField, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IndexField to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IndexField + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace IndexField { + + /** Order enum. */ + type Order = + "ORDER_UNSPECIFIED"| "ASCENDING"| "DESCENDING"; + + /** ArrayConfig enum. */ + type ArrayConfig = + "ARRAY_CONFIG_UNSPECIFIED"| "CONTAINS"; + + /** Properties of a VectorConfig. */ + interface IVectorConfig { + + /** VectorConfig dimension */ + dimension?: (number|null); + + /** VectorConfig flat */ + flat?: (google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex|null); + } + + /** Represents a VectorConfig. */ + class VectorConfig implements IVectorConfig { + + /** + * Constructs a new VectorConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Index.IndexField.IVectorConfig); + + /** VectorConfig dimension. */ + public dimension: number; + + /** VectorConfig flat. */ + public flat?: (google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex|null); + + /** VectorConfig type. */ + public type?: "flat"; + + /** + * Creates a VectorConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns VectorConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index.IndexField.VectorConfig; + + /** + * Creates a plain object from a VectorConfig message. Also converts values to other types if specified. + * @param message VectorConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Index.IndexField.VectorConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this VectorConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for VectorConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace VectorConfig { + + /** Properties of a FlatIndex. */ + interface IFlatIndex { + } + + /** Represents a FlatIndex. */ + class FlatIndex implements IFlatIndex { + + /** + * Constructs a new FlatIndex. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex); + + /** + * Creates a FlatIndex message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FlatIndex + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex; + + /** + * Creates a plain object from a FlatIndex message. Also converts values to other types if specified. + * @param message FlatIndex + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FlatIndex to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FlatIndex + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + + /** State enum. */ + type State = + "STATE_UNSPECIFIED"| "CREATING"| "READY"| "NEEDS_REPAIR"; + } + + /** Represents a FirestoreAdmin */ + class FirestoreAdmin extends $protobuf.rpc.Service { + + /** + * Constructs a new FirestoreAdmin service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls CreateIndex. + * @param request CreateIndexRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public createIndex(request: google.firestore.admin.v1.ICreateIndexRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CreateIndexCallback): void; + + /** + * Calls CreateIndex. + * @param request CreateIndexRequest message or plain object + * @returns Promise + */ + public createIndex(request: google.firestore.admin.v1.ICreateIndexRequest): Promise; + + /** + * Calls ListIndexes. + * @param request ListIndexesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListIndexesResponse + */ + public listIndexes(request: google.firestore.admin.v1.IListIndexesRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListIndexesCallback): void; + + /** + * Calls ListIndexes. + * @param request ListIndexesRequest message or plain object + * @returns Promise + */ + public listIndexes(request: google.firestore.admin.v1.IListIndexesRequest): Promise; + + /** + * Calls GetIndex. + * @param request GetIndexRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Index + */ + public getIndex(request: google.firestore.admin.v1.IGetIndexRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetIndexCallback): void; + + /** + * Calls GetIndex. + * @param request GetIndexRequest message or plain object + * @returns Promise + */ + public getIndex(request: google.firestore.admin.v1.IGetIndexRequest): Promise; + + /** + * Calls DeleteIndex. + * @param request DeleteIndexRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteIndex(request: google.firestore.admin.v1.IDeleteIndexRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteIndexCallback): void; + + /** + * Calls DeleteIndex. + * @param request DeleteIndexRequest message or plain object + * @returns Promise + */ + public deleteIndex(request: google.firestore.admin.v1.IDeleteIndexRequest): Promise; + + /** + * Calls GetField. + * @param request GetFieldRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Field + */ + public getField(request: google.firestore.admin.v1.IGetFieldRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetFieldCallback): void; + + /** + * Calls GetField. + * @param request GetFieldRequest message or plain object + * @returns Promise + */ + public getField(request: google.firestore.admin.v1.IGetFieldRequest): Promise; + + /** + * Calls UpdateField. + * @param request UpdateFieldRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public updateField(request: google.firestore.admin.v1.IUpdateFieldRequest, callback: google.firestore.admin.v1.FirestoreAdmin.UpdateFieldCallback): void; + + /** + * Calls UpdateField. + * @param request UpdateFieldRequest message or plain object + * @returns Promise + */ + public updateField(request: google.firestore.admin.v1.IUpdateFieldRequest): Promise; + + /** + * Calls ListFields. + * @param request ListFieldsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListFieldsResponse + */ + public listFields(request: google.firestore.admin.v1.IListFieldsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListFieldsCallback): void; + + /** + * Calls ListFields. + * @param request ListFieldsRequest message or plain object + * @returns Promise + */ + public listFields(request: google.firestore.admin.v1.IListFieldsRequest): Promise; + + /** + * Calls ExportDocuments. + * @param request ExportDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public exportDocuments(request: google.firestore.admin.v1.IExportDocumentsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ExportDocumentsCallback): void; + + /** + * Calls ExportDocuments. + * @param request ExportDocumentsRequest message or plain object + * @returns Promise + */ + public exportDocuments(request: google.firestore.admin.v1.IExportDocumentsRequest): Promise; + + /** + * Calls ImportDocuments. + * @param request ImportDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public importDocuments(request: google.firestore.admin.v1.IImportDocumentsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ImportDocumentsCallback): void; + + /** + * Calls ImportDocuments. + * @param request ImportDocumentsRequest message or plain object + * @returns Promise + */ + public importDocuments(request: google.firestore.admin.v1.IImportDocumentsRequest): Promise; + + /** + * Calls BulkDeleteDocuments. + * @param request BulkDeleteDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public bulkDeleteDocuments(request: google.firestore.admin.v1.IBulkDeleteDocumentsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.BulkDeleteDocumentsCallback): void; + + /** + * Calls BulkDeleteDocuments. + * @param request BulkDeleteDocumentsRequest message or plain object + * @returns Promise + */ + public bulkDeleteDocuments(request: google.firestore.admin.v1.IBulkDeleteDocumentsRequest): Promise; + + /** + * Calls CreateDatabase. + * @param request CreateDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public createDatabase(request: google.firestore.admin.v1.ICreateDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CreateDatabaseCallback): void; + + /** + * Calls CreateDatabase. + * @param request CreateDatabaseRequest message or plain object + * @returns Promise + */ + public createDatabase(request: google.firestore.admin.v1.ICreateDatabaseRequest): Promise; + + /** + * Calls GetDatabase. + * @param request GetDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Database + */ + public getDatabase(request: google.firestore.admin.v1.IGetDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetDatabaseCallback): void; + + /** + * Calls GetDatabase. + * @param request GetDatabaseRequest message or plain object + * @returns Promise + */ + public getDatabase(request: google.firestore.admin.v1.IGetDatabaseRequest): Promise; + + /** + * Calls ListDatabases. + * @param request ListDatabasesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListDatabasesResponse + */ + public listDatabases(request: google.firestore.admin.v1.IListDatabasesRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListDatabasesCallback): void; + + /** + * Calls ListDatabases. + * @param request ListDatabasesRequest message or plain object + * @returns Promise + */ + public listDatabases(request: google.firestore.admin.v1.IListDatabasesRequest): Promise; + + /** + * Calls UpdateDatabase. + * @param request UpdateDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public updateDatabase(request: google.firestore.admin.v1.IUpdateDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.UpdateDatabaseCallback): void; + + /** + * Calls UpdateDatabase. + * @param request UpdateDatabaseRequest message or plain object + * @returns Promise + */ + public updateDatabase(request: google.firestore.admin.v1.IUpdateDatabaseRequest): Promise; + + /** + * Calls DeleteDatabase. + * @param request DeleteDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public deleteDatabase(request: google.firestore.admin.v1.IDeleteDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteDatabaseCallback): void; + + /** + * Calls DeleteDatabase. + * @param request DeleteDatabaseRequest message or plain object + * @returns Promise + */ + public deleteDatabase(request: google.firestore.admin.v1.IDeleteDatabaseRequest): Promise; + + /** + * Calls GetBackup. + * @param request GetBackupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Backup + */ + public getBackup(request: google.firestore.admin.v1.IGetBackupRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetBackupCallback): void; + + /** + * Calls GetBackup. + * @param request GetBackupRequest message or plain object + * @returns Promise + */ + public getBackup(request: google.firestore.admin.v1.IGetBackupRequest): Promise; + + /** + * Calls ListBackups. + * @param request ListBackupsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListBackupsResponse + */ + public listBackups(request: google.firestore.admin.v1.IListBackupsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListBackupsCallback): void; + + /** + * Calls ListBackups. + * @param request ListBackupsRequest message or plain object + * @returns Promise + */ + public listBackups(request: google.firestore.admin.v1.IListBackupsRequest): Promise; + + /** + * Calls DeleteBackup. + * @param request DeleteBackupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteBackup(request: google.firestore.admin.v1.IDeleteBackupRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteBackupCallback): void; + + /** + * Calls DeleteBackup. + * @param request DeleteBackupRequest message or plain object + * @returns Promise + */ + public deleteBackup(request: google.firestore.admin.v1.IDeleteBackupRequest): Promise; + + /** + * Calls RestoreDatabase. + * @param request RestoreDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public restoreDatabase(request: google.firestore.admin.v1.IRestoreDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.RestoreDatabaseCallback): void; + + /** + * Calls RestoreDatabase. + * @param request RestoreDatabaseRequest message or plain object + * @returns Promise + */ + public restoreDatabase(request: google.firestore.admin.v1.IRestoreDatabaseRequest): Promise; + + /** + * Calls CreateBackupSchedule. + * @param request CreateBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BackupSchedule + */ + public createBackupSchedule(request: google.firestore.admin.v1.ICreateBackupScheduleRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CreateBackupScheduleCallback): void; + + /** + * Calls CreateBackupSchedule. + * @param request CreateBackupScheduleRequest message or plain object + * @returns Promise + */ + public createBackupSchedule(request: google.firestore.admin.v1.ICreateBackupScheduleRequest): Promise; + + /** + * Calls GetBackupSchedule. + * @param request GetBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BackupSchedule + */ + public getBackupSchedule(request: google.firestore.admin.v1.IGetBackupScheduleRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetBackupScheduleCallback): void; + + /** + * Calls GetBackupSchedule. + * @param request GetBackupScheduleRequest message or plain object + * @returns Promise + */ + public getBackupSchedule(request: google.firestore.admin.v1.IGetBackupScheduleRequest): Promise; + + /** + * Calls ListBackupSchedules. + * @param request ListBackupSchedulesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListBackupSchedulesResponse + */ + public listBackupSchedules(request: google.firestore.admin.v1.IListBackupSchedulesRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListBackupSchedulesCallback): void; + + /** + * Calls ListBackupSchedules. + * @param request ListBackupSchedulesRequest message or plain object + * @returns Promise + */ + public listBackupSchedules(request: google.firestore.admin.v1.IListBackupSchedulesRequest): Promise; + + /** + * Calls UpdateBackupSchedule. + * @param request UpdateBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BackupSchedule + */ + public updateBackupSchedule(request: google.firestore.admin.v1.IUpdateBackupScheduleRequest, callback: google.firestore.admin.v1.FirestoreAdmin.UpdateBackupScheduleCallback): void; + + /** + * Calls UpdateBackupSchedule. + * @param request UpdateBackupScheduleRequest message or plain object + * @returns Promise + */ + public updateBackupSchedule(request: google.firestore.admin.v1.IUpdateBackupScheduleRequest): Promise; + + /** + * Calls DeleteBackupSchedule. + * @param request DeleteBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteBackupSchedule(request: google.firestore.admin.v1.IDeleteBackupScheduleRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteBackupScheduleCallback): void; + + /** + * Calls DeleteBackupSchedule. + * @param request DeleteBackupScheduleRequest message or plain object + * @returns Promise + */ + public deleteBackupSchedule(request: google.firestore.admin.v1.IDeleteBackupScheduleRequest): Promise; + } + + namespace FirestoreAdmin { + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createIndex}. + * @param error Error, if any + * @param [response] Operation + */ + type CreateIndexCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listIndexes}. + * @param error Error, if any + * @param [response] ListIndexesResponse + */ + type ListIndexesCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListIndexesResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getIndex}. + * @param error Error, if any + * @param [response] Index + */ + type GetIndexCallback = (error: (Error|null), response?: google.firestore.admin.v1.Index) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteIndex}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteIndexCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getField}. + * @param error Error, if any + * @param [response] Field + */ + type GetFieldCallback = (error: (Error|null), response?: google.firestore.admin.v1.Field) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#updateField}. + * @param error Error, if any + * @param [response] Operation + */ + type UpdateFieldCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listFields}. + * @param error Error, if any + * @param [response] ListFieldsResponse + */ + type ListFieldsCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListFieldsResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#exportDocuments}. + * @param error Error, if any + * @param [response] Operation + */ + type ExportDocumentsCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#importDocuments}. + * @param error Error, if any + * @param [response] Operation + */ + type ImportDocumentsCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#bulkDeleteDocuments}. + * @param error Error, if any + * @param [response] Operation + */ + type BulkDeleteDocumentsCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type CreateDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getDatabase}. + * @param error Error, if any + * @param [response] Database + */ + type GetDatabaseCallback = (error: (Error|null), response?: google.firestore.admin.v1.Database) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listDatabases}. + * @param error Error, if any + * @param [response] ListDatabasesResponse + */ + type ListDatabasesCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListDatabasesResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#updateDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type UpdateDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type DeleteDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getBackup}. + * @param error Error, if any + * @param [response] Backup + */ + type GetBackupCallback = (error: (Error|null), response?: google.firestore.admin.v1.Backup) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listBackups}. + * @param error Error, if any + * @param [response] ListBackupsResponse + */ + type ListBackupsCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListBackupsResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteBackup}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteBackupCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#restoreDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type RestoreDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createBackupSchedule}. + * @param error Error, if any + * @param [response] BackupSchedule + */ + type CreateBackupScheduleCallback = (error: (Error|null), response?: google.firestore.admin.v1.BackupSchedule) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getBackupSchedule}. + * @param error Error, if any + * @param [response] BackupSchedule + */ + type GetBackupScheduleCallback = (error: (Error|null), response?: google.firestore.admin.v1.BackupSchedule) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listBackupSchedules}. + * @param error Error, if any + * @param [response] ListBackupSchedulesResponse + */ + type ListBackupSchedulesCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListBackupSchedulesResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#updateBackupSchedule}. + * @param error Error, if any + * @param [response] BackupSchedule + */ + type UpdateBackupScheduleCallback = (error: (Error|null), response?: google.firestore.admin.v1.BackupSchedule) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteBackupSchedule}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteBackupScheduleCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + } + + /** Properties of a ListDatabasesRequest. */ + interface IListDatabasesRequest { + + /** ListDatabasesRequest parent */ + parent?: (string|null); + + /** ListDatabasesRequest showDeleted */ + showDeleted?: (boolean|null); + } + + /** Represents a ListDatabasesRequest. */ + class ListDatabasesRequest implements IListDatabasesRequest { + + /** + * Constructs a new ListDatabasesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListDatabasesRequest); + + /** ListDatabasesRequest parent. */ + public parent: string; + + /** ListDatabasesRequest showDeleted. */ + public showDeleted: boolean; + + /** + * Creates a ListDatabasesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDatabasesRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListDatabasesRequest; + + /** + * Creates a plain object from a ListDatabasesRequest message. Also converts values to other types if specified. + * @param message ListDatabasesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListDatabasesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDatabasesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDatabasesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDatabaseRequest. */ + interface ICreateDatabaseRequest { + + /** CreateDatabaseRequest parent */ + parent?: (string|null); + + /** CreateDatabaseRequest database */ + database?: (google.firestore.admin.v1.IDatabase|null); + + /** CreateDatabaseRequest databaseId */ + databaseId?: (string|null); + } + + /** Represents a CreateDatabaseRequest. */ + class CreateDatabaseRequest implements ICreateDatabaseRequest { + + /** + * Constructs a new CreateDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateDatabaseRequest); + + /** CreateDatabaseRequest parent. */ + public parent: string; + + /** CreateDatabaseRequest database. */ + public database?: (google.firestore.admin.v1.IDatabase|null); + + /** CreateDatabaseRequest databaseId. */ + public databaseId: string; + + /** + * Creates a CreateDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateDatabaseRequest; + + /** + * Creates a plain object from a CreateDatabaseRequest message. Also converts values to other types if specified. + * @param message CreateDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDatabaseMetadata. */ + interface ICreateDatabaseMetadata { + } + + /** Represents a CreateDatabaseMetadata. */ + class CreateDatabaseMetadata implements ICreateDatabaseMetadata { + + /** + * Constructs a new CreateDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateDatabaseMetadata); + + /** + * Creates a CreateDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateDatabaseMetadata; + + /** + * Creates a plain object from a CreateDatabaseMetadata message. Also converts values to other types if specified. + * @param message CreateDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDatabasesResponse. */ + interface IListDatabasesResponse { + + /** ListDatabasesResponse databases */ + databases?: (google.firestore.admin.v1.IDatabase[]|null); + + /** ListDatabasesResponse unreachable */ + unreachable?: (string[]|null); + } + + /** Represents a ListDatabasesResponse. */ + class ListDatabasesResponse implements IListDatabasesResponse { + + /** + * Constructs a new ListDatabasesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListDatabasesResponse); + + /** ListDatabasesResponse databases. */ + public databases: google.firestore.admin.v1.IDatabase[]; + + /** ListDatabasesResponse unreachable. */ + public unreachable: string[]; + + /** + * Creates a ListDatabasesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDatabasesResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListDatabasesResponse; + + /** + * Creates a plain object from a ListDatabasesResponse message. Also converts values to other types if specified. + * @param message ListDatabasesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListDatabasesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDatabasesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDatabasesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetDatabaseRequest. */ + interface IGetDatabaseRequest { + + /** GetDatabaseRequest name */ + name?: (string|null); + } + + /** Represents a GetDatabaseRequest. */ + class GetDatabaseRequest implements IGetDatabaseRequest { + + /** + * Constructs a new GetDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetDatabaseRequest); + + /** GetDatabaseRequest name. */ + public name: string; + + /** + * Creates a GetDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetDatabaseRequest; + + /** + * Creates a plain object from a GetDatabaseRequest message. Also converts values to other types if specified. + * @param message GetDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDatabaseRequest. */ + interface IUpdateDatabaseRequest { + + /** UpdateDatabaseRequest database */ + database?: (google.firestore.admin.v1.IDatabase|null); + + /** UpdateDatabaseRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateDatabaseRequest. */ + class UpdateDatabaseRequest implements IUpdateDatabaseRequest { + + /** + * Constructs a new UpdateDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateDatabaseRequest); + + /** UpdateDatabaseRequest database. */ + public database?: (google.firestore.admin.v1.IDatabase|null); + + /** UpdateDatabaseRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates an UpdateDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateDatabaseRequest; + + /** + * Creates a plain object from an UpdateDatabaseRequest message. Also converts values to other types if specified. + * @param message UpdateDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDatabaseMetadata. */ + interface IUpdateDatabaseMetadata { + } + + /** Represents an UpdateDatabaseMetadata. */ + class UpdateDatabaseMetadata implements IUpdateDatabaseMetadata { + + /** + * Constructs a new UpdateDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateDatabaseMetadata); + + /** + * Creates an UpdateDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateDatabaseMetadata; + + /** + * Creates a plain object from an UpdateDatabaseMetadata message. Also converts values to other types if specified. + * @param message UpdateDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDatabaseRequest. */ + interface IDeleteDatabaseRequest { + + /** DeleteDatabaseRequest name */ + name?: (string|null); + + /** DeleteDatabaseRequest etag */ + etag?: (string|null); + } + + /** Represents a DeleteDatabaseRequest. */ + class DeleteDatabaseRequest implements IDeleteDatabaseRequest { + + /** + * Constructs a new DeleteDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteDatabaseRequest); + + /** DeleteDatabaseRequest name. */ + public name: string; + + /** DeleteDatabaseRequest etag. */ + public etag: string; + + /** + * Creates a DeleteDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteDatabaseRequest; + + /** + * Creates a plain object from a DeleteDatabaseRequest message. Also converts values to other types if specified. + * @param message DeleteDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDatabaseMetadata. */ + interface IDeleteDatabaseMetadata { + } + + /** Represents a DeleteDatabaseMetadata. */ + class DeleteDatabaseMetadata implements IDeleteDatabaseMetadata { + + /** + * Constructs a new DeleteDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteDatabaseMetadata); + + /** + * Creates a DeleteDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteDatabaseMetadata; + + /** + * Creates a plain object from a DeleteDatabaseMetadata message. Also converts values to other types if specified. + * @param message DeleteDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateBackupScheduleRequest. */ + interface ICreateBackupScheduleRequest { + + /** CreateBackupScheduleRequest parent */ + parent?: (string|null); + + /** CreateBackupScheduleRequest backupSchedule */ + backupSchedule?: (google.firestore.admin.v1.IBackupSchedule|null); + } + + /** Represents a CreateBackupScheduleRequest. */ + class CreateBackupScheduleRequest implements ICreateBackupScheduleRequest { + + /** + * Constructs a new CreateBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateBackupScheduleRequest); + + /** CreateBackupScheduleRequest parent. */ + public parent: string; + + /** CreateBackupScheduleRequest backupSchedule. */ + public backupSchedule?: (google.firestore.admin.v1.IBackupSchedule|null); + + /** + * Creates a CreateBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateBackupScheduleRequest; + + /** + * Creates a plain object from a CreateBackupScheduleRequest message. Also converts values to other types if specified. + * @param message CreateBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetBackupScheduleRequest. */ + interface IGetBackupScheduleRequest { + + /** GetBackupScheduleRequest name */ + name?: (string|null); + } + + /** Represents a GetBackupScheduleRequest. */ + class GetBackupScheduleRequest implements IGetBackupScheduleRequest { + + /** + * Constructs a new GetBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetBackupScheduleRequest); + + /** GetBackupScheduleRequest name. */ + public name: string; + + /** + * Creates a GetBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetBackupScheduleRequest; + + /** + * Creates a plain object from a GetBackupScheduleRequest message. Also converts values to other types if specified. + * @param message GetBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateBackupScheduleRequest. */ + interface IUpdateBackupScheduleRequest { + + /** UpdateBackupScheduleRequest backupSchedule */ + backupSchedule?: (google.firestore.admin.v1.IBackupSchedule|null); + + /** UpdateBackupScheduleRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateBackupScheduleRequest. */ + class UpdateBackupScheduleRequest implements IUpdateBackupScheduleRequest { + + /** + * Constructs a new UpdateBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateBackupScheduleRequest); + + /** UpdateBackupScheduleRequest backupSchedule. */ + public backupSchedule?: (google.firestore.admin.v1.IBackupSchedule|null); + + /** UpdateBackupScheduleRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates an UpdateBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateBackupScheduleRequest; + + /** + * Creates a plain object from an UpdateBackupScheduleRequest message. Also converts values to other types if specified. + * @param message UpdateBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupSchedulesRequest. */ + interface IListBackupSchedulesRequest { + + /** ListBackupSchedulesRequest parent */ + parent?: (string|null); + } + + /** Represents a ListBackupSchedulesRequest. */ + class ListBackupSchedulesRequest implements IListBackupSchedulesRequest { + + /** + * Constructs a new ListBackupSchedulesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListBackupSchedulesRequest); + + /** ListBackupSchedulesRequest parent. */ + public parent: string; + + /** + * Creates a ListBackupSchedulesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupSchedulesRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListBackupSchedulesRequest; + + /** + * Creates a plain object from a ListBackupSchedulesRequest message. Also converts values to other types if specified. + * @param message ListBackupSchedulesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListBackupSchedulesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupSchedulesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupSchedulesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupSchedulesResponse. */ + interface IListBackupSchedulesResponse { + + /** ListBackupSchedulesResponse backupSchedules */ + backupSchedules?: (google.firestore.admin.v1.IBackupSchedule[]|null); + } + + /** Represents a ListBackupSchedulesResponse. */ + class ListBackupSchedulesResponse implements IListBackupSchedulesResponse { + + /** + * Constructs a new ListBackupSchedulesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListBackupSchedulesResponse); + + /** ListBackupSchedulesResponse backupSchedules. */ + public backupSchedules: google.firestore.admin.v1.IBackupSchedule[]; + + /** + * Creates a ListBackupSchedulesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupSchedulesResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListBackupSchedulesResponse; + + /** + * Creates a plain object from a ListBackupSchedulesResponse message. Also converts values to other types if specified. + * @param message ListBackupSchedulesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListBackupSchedulesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupSchedulesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupSchedulesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteBackupScheduleRequest. */ + interface IDeleteBackupScheduleRequest { + + /** DeleteBackupScheduleRequest name */ + name?: (string|null); + } + + /** Represents a DeleteBackupScheduleRequest. */ + class DeleteBackupScheduleRequest implements IDeleteBackupScheduleRequest { + + /** + * Constructs a new DeleteBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteBackupScheduleRequest); + + /** DeleteBackupScheduleRequest name. */ + public name: string; + + /** + * Creates a DeleteBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteBackupScheduleRequest; + + /** + * Creates a plain object from a DeleteBackupScheduleRequest message. Also converts values to other types if specified. + * @param message DeleteBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateIndexRequest. */ + interface ICreateIndexRequest { + + /** CreateIndexRequest parent */ + parent?: (string|null); + + /** CreateIndexRequest index */ + index?: (google.firestore.admin.v1.IIndex|null); + } + + /** Represents a CreateIndexRequest. */ + class CreateIndexRequest implements ICreateIndexRequest { + + /** + * Constructs a new CreateIndexRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateIndexRequest); + + /** CreateIndexRequest parent. */ + public parent: string; + + /** CreateIndexRequest index. */ + public index?: (google.firestore.admin.v1.IIndex|null); + + /** + * Creates a CreateIndexRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateIndexRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateIndexRequest; + + /** + * Creates a plain object from a CreateIndexRequest message. Also converts values to other types if specified. + * @param message CreateIndexRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateIndexRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateIndexRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateIndexRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListIndexesRequest. */ + interface IListIndexesRequest { + + /** ListIndexesRequest parent */ + parent?: (string|null); + + /** ListIndexesRequest filter */ + filter?: (string|null); + + /** ListIndexesRequest pageSize */ + pageSize?: (number|null); + + /** ListIndexesRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListIndexesRequest. */ + class ListIndexesRequest implements IListIndexesRequest { + + /** + * Constructs a new ListIndexesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListIndexesRequest); + + /** ListIndexesRequest parent. */ + public parent: string; + + /** ListIndexesRequest filter. */ + public filter: string; + + /** ListIndexesRequest pageSize. */ + public pageSize: number; + + /** ListIndexesRequest pageToken. */ + public pageToken: string; + + /** + * Creates a ListIndexesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListIndexesRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListIndexesRequest; + + /** + * Creates a plain object from a ListIndexesRequest message. Also converts values to other types if specified. + * @param message ListIndexesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListIndexesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListIndexesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListIndexesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListIndexesResponse. */ + interface IListIndexesResponse { + + /** ListIndexesResponse indexes */ + indexes?: (google.firestore.admin.v1.IIndex[]|null); + + /** ListIndexesResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListIndexesResponse. */ + class ListIndexesResponse implements IListIndexesResponse { + + /** + * Constructs a new ListIndexesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListIndexesResponse); + + /** ListIndexesResponse indexes. */ + public indexes: google.firestore.admin.v1.IIndex[]; + + /** ListIndexesResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListIndexesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListIndexesResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListIndexesResponse; + + /** + * Creates a plain object from a ListIndexesResponse message. Also converts values to other types if specified. + * @param message ListIndexesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListIndexesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListIndexesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListIndexesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetIndexRequest. */ + interface IGetIndexRequest { + + /** GetIndexRequest name */ + name?: (string|null); + } + + /** Represents a GetIndexRequest. */ + class GetIndexRequest implements IGetIndexRequest { + + /** + * Constructs a new GetIndexRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetIndexRequest); + + /** GetIndexRequest name. */ + public name: string; + + /** + * Creates a GetIndexRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetIndexRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetIndexRequest; + + /** + * Creates a plain object from a GetIndexRequest message. Also converts values to other types if specified. + * @param message GetIndexRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetIndexRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetIndexRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetIndexRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteIndexRequest. */ + interface IDeleteIndexRequest { + + /** DeleteIndexRequest name */ + name?: (string|null); + } + + /** Represents a DeleteIndexRequest. */ + class DeleteIndexRequest implements IDeleteIndexRequest { + + /** + * Constructs a new DeleteIndexRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteIndexRequest); + + /** DeleteIndexRequest name. */ + public name: string; + + /** + * Creates a DeleteIndexRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteIndexRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteIndexRequest; + + /** + * Creates a plain object from a DeleteIndexRequest message. Also converts values to other types if specified. + * @param message DeleteIndexRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteIndexRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteIndexRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteIndexRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateFieldRequest. */ + interface IUpdateFieldRequest { + + /** UpdateFieldRequest field */ + field?: (google.firestore.admin.v1.IField|null); + + /** UpdateFieldRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateFieldRequest. */ + class UpdateFieldRequest implements IUpdateFieldRequest { + + /** + * Constructs a new UpdateFieldRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateFieldRequest); + + /** UpdateFieldRequest field. */ + public field?: (google.firestore.admin.v1.IField|null); + + /** UpdateFieldRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates an UpdateFieldRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateFieldRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateFieldRequest; + + /** + * Creates a plain object from an UpdateFieldRequest message. Also converts values to other types if specified. + * @param message UpdateFieldRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateFieldRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateFieldRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateFieldRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetFieldRequest. */ + interface IGetFieldRequest { + + /** GetFieldRequest name */ + name?: (string|null); + } + + /** Represents a GetFieldRequest. */ + class GetFieldRequest implements IGetFieldRequest { + + /** + * Constructs a new GetFieldRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetFieldRequest); + + /** GetFieldRequest name. */ + public name: string; + + /** + * Creates a GetFieldRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetFieldRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetFieldRequest; + + /** + * Creates a plain object from a GetFieldRequest message. Also converts values to other types if specified. + * @param message GetFieldRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetFieldRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetFieldRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetFieldRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListFieldsRequest. */ + interface IListFieldsRequest { + + /** ListFieldsRequest parent */ + parent?: (string|null); + + /** ListFieldsRequest filter */ + filter?: (string|null); + + /** ListFieldsRequest pageSize */ + pageSize?: (number|null); + + /** ListFieldsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListFieldsRequest. */ + class ListFieldsRequest implements IListFieldsRequest { + + /** + * Constructs a new ListFieldsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListFieldsRequest); + + /** ListFieldsRequest parent. */ + public parent: string; + + /** ListFieldsRequest filter. */ + public filter: string; + + /** ListFieldsRequest pageSize. */ + public pageSize: number; + + /** ListFieldsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a ListFieldsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListFieldsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListFieldsRequest; + + /** + * Creates a plain object from a ListFieldsRequest message. Also converts values to other types if specified. + * @param message ListFieldsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListFieldsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListFieldsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListFieldsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListFieldsResponse. */ + interface IListFieldsResponse { + + /** ListFieldsResponse fields */ + fields?: (google.firestore.admin.v1.IField[]|null); + + /** ListFieldsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListFieldsResponse. */ + class ListFieldsResponse implements IListFieldsResponse { + + /** + * Constructs a new ListFieldsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListFieldsResponse); + + /** ListFieldsResponse fields. */ + public fields: google.firestore.admin.v1.IField[]; + + /** ListFieldsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListFieldsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListFieldsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListFieldsResponse; + + /** + * Creates a plain object from a ListFieldsResponse message. Also converts values to other types if specified. + * @param message ListFieldsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListFieldsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListFieldsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListFieldsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExportDocumentsRequest. */ + interface IExportDocumentsRequest { + + /** ExportDocumentsRequest name */ + name?: (string|null); + + /** ExportDocumentsRequest collectionIds */ + collectionIds?: (string[]|null); + + /** ExportDocumentsRequest outputUriPrefix */ + outputUriPrefix?: (string|null); + + /** ExportDocumentsRequest namespaceIds */ + namespaceIds?: (string[]|null); + + /** ExportDocumentsRequest snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an ExportDocumentsRequest. */ + class ExportDocumentsRequest implements IExportDocumentsRequest { + + /** + * Constructs a new ExportDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IExportDocumentsRequest); + + /** ExportDocumentsRequest name. */ + public name: string; + + /** ExportDocumentsRequest collectionIds. */ + public collectionIds: string[]; + + /** ExportDocumentsRequest outputUriPrefix. */ + public outputUriPrefix: string; + + /** ExportDocumentsRequest namespaceIds. */ + public namespaceIds: string[]; + + /** ExportDocumentsRequest snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates an ExportDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExportDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ExportDocumentsRequest; + + /** + * Creates a plain object from an ExportDocumentsRequest message. Also converts values to other types if specified. + * @param message ExportDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ExportDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExportDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExportDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ImportDocumentsRequest. */ + interface IImportDocumentsRequest { + + /** ImportDocumentsRequest name */ + name?: (string|null); + + /** ImportDocumentsRequest collectionIds */ + collectionIds?: (string[]|null); + + /** ImportDocumentsRequest inputUriPrefix */ + inputUriPrefix?: (string|null); + + /** ImportDocumentsRequest namespaceIds */ + namespaceIds?: (string[]|null); + } + + /** Represents an ImportDocumentsRequest. */ + class ImportDocumentsRequest implements IImportDocumentsRequest { + + /** + * Constructs a new ImportDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IImportDocumentsRequest); + + /** ImportDocumentsRequest name. */ + public name: string; + + /** ImportDocumentsRequest collectionIds. */ + public collectionIds: string[]; + + /** ImportDocumentsRequest inputUriPrefix. */ + public inputUriPrefix: string; + + /** ImportDocumentsRequest namespaceIds. */ + public namespaceIds: string[]; + + /** + * Creates an ImportDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ImportDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ImportDocumentsRequest; + + /** + * Creates a plain object from an ImportDocumentsRequest message. Also converts values to other types if specified. + * @param message ImportDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ImportDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ImportDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ImportDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BulkDeleteDocumentsRequest. */ + interface IBulkDeleteDocumentsRequest { + + /** BulkDeleteDocumentsRequest name */ + name?: (string|null); + + /** BulkDeleteDocumentsRequest collectionIds */ + collectionIds?: (string[]|null); + + /** BulkDeleteDocumentsRequest namespaceIds */ + namespaceIds?: (string[]|null); + } + + /** Represents a BulkDeleteDocumentsRequest. */ + class BulkDeleteDocumentsRequest implements IBulkDeleteDocumentsRequest { + + /** + * Constructs a new BulkDeleteDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBulkDeleteDocumentsRequest); + + /** BulkDeleteDocumentsRequest name. */ + public name: string; + + /** BulkDeleteDocumentsRequest collectionIds. */ + public collectionIds: string[]; + + /** BulkDeleteDocumentsRequest namespaceIds. */ + public namespaceIds: string[]; + + /** + * Creates a BulkDeleteDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BulkDeleteDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BulkDeleteDocumentsRequest; + + /** + * Creates a plain object from a BulkDeleteDocumentsRequest message. Also converts values to other types if specified. + * @param message BulkDeleteDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.BulkDeleteDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BulkDeleteDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BulkDeleteDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BulkDeleteDocumentsResponse. */ + interface IBulkDeleteDocumentsResponse { + } + + /** Represents a BulkDeleteDocumentsResponse. */ + class BulkDeleteDocumentsResponse implements IBulkDeleteDocumentsResponse { + + /** + * Constructs a new BulkDeleteDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBulkDeleteDocumentsResponse); + + /** + * Creates a BulkDeleteDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BulkDeleteDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BulkDeleteDocumentsResponse; + + /** + * Creates a plain object from a BulkDeleteDocumentsResponse message. Also converts values to other types if specified. + * @param message BulkDeleteDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.BulkDeleteDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BulkDeleteDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BulkDeleteDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetBackupRequest. */ + interface IGetBackupRequest { + + /** GetBackupRequest name */ + name?: (string|null); + } + + /** Represents a GetBackupRequest. */ + class GetBackupRequest implements IGetBackupRequest { + + /** + * Constructs a new GetBackupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetBackupRequest); + + /** GetBackupRequest name. */ + public name: string; + + /** + * Creates a GetBackupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetBackupRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetBackupRequest; + + /** + * Creates a plain object from a GetBackupRequest message. Also converts values to other types if specified. + * @param message GetBackupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetBackupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetBackupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetBackupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupsRequest. */ + interface IListBackupsRequest { + + /** ListBackupsRequest parent */ + parent?: (string|null); + + /** ListBackupsRequest filter */ + filter?: (string|null); + } + + /** Represents a ListBackupsRequest. */ + class ListBackupsRequest implements IListBackupsRequest { + + /** + * Constructs a new ListBackupsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListBackupsRequest); + + /** ListBackupsRequest parent. */ + public parent: string; + + /** ListBackupsRequest filter. */ + public filter: string; + + /** + * Creates a ListBackupsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListBackupsRequest; + + /** + * Creates a plain object from a ListBackupsRequest message. Also converts values to other types if specified. + * @param message ListBackupsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListBackupsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupsResponse. */ + interface IListBackupsResponse { + + /** ListBackupsResponse backups */ + backups?: (google.firestore.admin.v1.IBackup[]|null); + + /** ListBackupsResponse unreachable */ + unreachable?: (string[]|null); + } + + /** Represents a ListBackupsResponse. */ + class ListBackupsResponse implements IListBackupsResponse { + + /** + * Constructs a new ListBackupsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListBackupsResponse); + + /** ListBackupsResponse backups. */ + public backups: google.firestore.admin.v1.IBackup[]; + + /** ListBackupsResponse unreachable. */ + public unreachable: string[]; + + /** + * Creates a ListBackupsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListBackupsResponse; + + /** + * Creates a plain object from a ListBackupsResponse message. Also converts values to other types if specified. + * @param message ListBackupsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListBackupsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteBackupRequest. */ + interface IDeleteBackupRequest { + + /** DeleteBackupRequest name */ + name?: (string|null); + } + + /** Represents a DeleteBackupRequest. */ + class DeleteBackupRequest implements IDeleteBackupRequest { + + /** + * Constructs a new DeleteBackupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteBackupRequest); + + /** DeleteBackupRequest name. */ + public name: string; + + /** + * Creates a DeleteBackupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteBackupRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteBackupRequest; + + /** + * Creates a plain object from a DeleteBackupRequest message. Also converts values to other types if specified. + * @param message DeleteBackupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteBackupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteBackupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteBackupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RestoreDatabaseRequest. */ + interface IRestoreDatabaseRequest { + + /** RestoreDatabaseRequest parent */ + parent?: (string|null); + + /** RestoreDatabaseRequest databaseId */ + databaseId?: (string|null); + + /** RestoreDatabaseRequest backup */ + backup?: (string|null); + + /** RestoreDatabaseRequest encryptionConfig */ + encryptionConfig?: (google.firestore.admin.v1.Database.IEncryptionConfig|null); + } + + /** Represents a RestoreDatabaseRequest. */ + class RestoreDatabaseRequest implements IRestoreDatabaseRequest { + + /** + * Constructs a new RestoreDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IRestoreDatabaseRequest); + + /** RestoreDatabaseRequest parent. */ + public parent: string; + + /** RestoreDatabaseRequest databaseId. */ + public databaseId: string; + + /** RestoreDatabaseRequest backup. */ + public backup: string; + + /** RestoreDatabaseRequest encryptionConfig. */ + public encryptionConfig?: (google.firestore.admin.v1.Database.IEncryptionConfig|null); + + /** + * Creates a RestoreDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RestoreDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.RestoreDatabaseRequest; + + /** + * Creates a plain object from a RestoreDatabaseRequest message. Also converts values to other types if specified. + * @param message RestoreDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.RestoreDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RestoreDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RestoreDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an IndexOperationMetadata. */ + interface IIndexOperationMetadata { + + /** IndexOperationMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** IndexOperationMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** IndexOperationMetadata index */ + index?: (string|null); + + /** IndexOperationMetadata state */ + state?: (google.firestore.admin.v1.OperationState|null); + + /** IndexOperationMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** IndexOperationMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + } + + /** Represents an IndexOperationMetadata. */ + class IndexOperationMetadata implements IIndexOperationMetadata { + + /** + * Constructs a new IndexOperationMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IIndexOperationMetadata); + + /** IndexOperationMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** IndexOperationMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** IndexOperationMetadata index. */ + public index: string; + + /** IndexOperationMetadata state. */ + public state: google.firestore.admin.v1.OperationState; + + /** IndexOperationMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** IndexOperationMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** + * Creates an IndexOperationMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IndexOperationMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.IndexOperationMetadata; + + /** + * Creates a plain object from an IndexOperationMetadata message. Also converts values to other types if specified. + * @param message IndexOperationMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.IndexOperationMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IndexOperationMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IndexOperationMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldOperationMetadata. */ + interface IFieldOperationMetadata { + + /** FieldOperationMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** FieldOperationMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** FieldOperationMetadata field */ + field?: (string|null); + + /** FieldOperationMetadata indexConfigDeltas */ + indexConfigDeltas?: (google.firestore.admin.v1.FieldOperationMetadata.IIndexConfigDelta[]|null); + + /** FieldOperationMetadata state */ + state?: (google.firestore.admin.v1.OperationState|null); + + /** FieldOperationMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** FieldOperationMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** FieldOperationMetadata ttlConfigDelta */ + ttlConfigDelta?: (google.firestore.admin.v1.FieldOperationMetadata.ITtlConfigDelta|null); + } + + /** Represents a FieldOperationMetadata. */ + class FieldOperationMetadata implements IFieldOperationMetadata { + + /** + * Constructs a new FieldOperationMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IFieldOperationMetadata); + + /** FieldOperationMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** FieldOperationMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** FieldOperationMetadata field. */ + public field: string; + + /** FieldOperationMetadata indexConfigDeltas. */ + public indexConfigDeltas: google.firestore.admin.v1.FieldOperationMetadata.IIndexConfigDelta[]; + + /** FieldOperationMetadata state. */ + public state: google.firestore.admin.v1.OperationState; + + /** FieldOperationMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** FieldOperationMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** FieldOperationMetadata ttlConfigDelta. */ + public ttlConfigDelta?: (google.firestore.admin.v1.FieldOperationMetadata.ITtlConfigDelta|null); + + /** + * Creates a FieldOperationMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOperationMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.FieldOperationMetadata; + + /** + * Creates a plain object from a FieldOperationMetadata message. Also converts values to other types if specified. + * @param message FieldOperationMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.FieldOperationMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldOperationMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldOperationMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldOperationMetadata { + + /** Properties of an IndexConfigDelta. */ + interface IIndexConfigDelta { + + /** IndexConfigDelta changeType */ + changeType?: (google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta.ChangeType|null); + + /** IndexConfigDelta index */ + index?: (google.firestore.admin.v1.IIndex|null); + } + + /** Represents an IndexConfigDelta. */ + class IndexConfigDelta implements IIndexConfigDelta { + + /** + * Constructs a new IndexConfigDelta. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.FieldOperationMetadata.IIndexConfigDelta); + + /** IndexConfigDelta changeType. */ + public changeType: google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta.ChangeType; + + /** IndexConfigDelta index. */ + public index?: (google.firestore.admin.v1.IIndex|null); + + /** + * Creates an IndexConfigDelta message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IndexConfigDelta + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta; + + /** + * Creates a plain object from an IndexConfigDelta message. Also converts values to other types if specified. + * @param message IndexConfigDelta + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IndexConfigDelta to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IndexConfigDelta + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace IndexConfigDelta { + + /** ChangeType enum. */ + type ChangeType = + "CHANGE_TYPE_UNSPECIFIED"| "ADD"| "REMOVE"; + } + + /** Properties of a TtlConfigDelta. */ + interface ITtlConfigDelta { + + /** TtlConfigDelta changeType */ + changeType?: (google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta.ChangeType|null); + } + + /** Represents a TtlConfigDelta. */ + class TtlConfigDelta implements ITtlConfigDelta { + + /** + * Constructs a new TtlConfigDelta. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.FieldOperationMetadata.ITtlConfigDelta); + + /** TtlConfigDelta changeType. */ + public changeType: google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta.ChangeType; + + /** + * Creates a TtlConfigDelta message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TtlConfigDelta + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta; + + /** + * Creates a plain object from a TtlConfigDelta message. Also converts values to other types if specified. + * @param message TtlConfigDelta + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TtlConfigDelta to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TtlConfigDelta + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TtlConfigDelta { + + /** ChangeType enum. */ + type ChangeType = + "CHANGE_TYPE_UNSPECIFIED"| "ADD"| "REMOVE"; + } + } + + /** Properties of an ExportDocumentsMetadata. */ + interface IExportDocumentsMetadata { + + /** ExportDocumentsMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** ExportDocumentsMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** ExportDocumentsMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** ExportDocumentsMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** ExportDocumentsMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** ExportDocumentsMetadata collectionIds */ + collectionIds?: (string[]|null); + + /** ExportDocumentsMetadata outputUriPrefix */ + outputUriPrefix?: (string|null); + + /** ExportDocumentsMetadata namespaceIds */ + namespaceIds?: (string[]|null); + + /** ExportDocumentsMetadata snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an ExportDocumentsMetadata. */ + class ExportDocumentsMetadata implements IExportDocumentsMetadata { + + /** + * Constructs a new ExportDocumentsMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IExportDocumentsMetadata); + + /** ExportDocumentsMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** ExportDocumentsMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** ExportDocumentsMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** ExportDocumentsMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** ExportDocumentsMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** ExportDocumentsMetadata collectionIds. */ + public collectionIds: string[]; + + /** ExportDocumentsMetadata outputUriPrefix. */ + public outputUriPrefix: string; + + /** ExportDocumentsMetadata namespaceIds. */ + public namespaceIds: string[]; + + /** ExportDocumentsMetadata snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates an ExportDocumentsMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExportDocumentsMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ExportDocumentsMetadata; + + /** + * Creates a plain object from an ExportDocumentsMetadata message. Also converts values to other types if specified. + * @param message ExportDocumentsMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ExportDocumentsMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExportDocumentsMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExportDocumentsMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ImportDocumentsMetadata. */ + interface IImportDocumentsMetadata { + + /** ImportDocumentsMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** ImportDocumentsMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** ImportDocumentsMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** ImportDocumentsMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** ImportDocumentsMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** ImportDocumentsMetadata collectionIds */ + collectionIds?: (string[]|null); + + /** ImportDocumentsMetadata inputUriPrefix */ + inputUriPrefix?: (string|null); + + /** ImportDocumentsMetadata namespaceIds */ + namespaceIds?: (string[]|null); + } + + /** Represents an ImportDocumentsMetadata. */ + class ImportDocumentsMetadata implements IImportDocumentsMetadata { + + /** + * Constructs a new ImportDocumentsMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IImportDocumentsMetadata); + + /** ImportDocumentsMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** ImportDocumentsMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** ImportDocumentsMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** ImportDocumentsMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** ImportDocumentsMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** ImportDocumentsMetadata collectionIds. */ + public collectionIds: string[]; + + /** ImportDocumentsMetadata inputUriPrefix. */ + public inputUriPrefix: string; + + /** ImportDocumentsMetadata namespaceIds. */ + public namespaceIds: string[]; + + /** + * Creates an ImportDocumentsMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ImportDocumentsMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ImportDocumentsMetadata; + + /** + * Creates a plain object from an ImportDocumentsMetadata message. Also converts values to other types if specified. + * @param message ImportDocumentsMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ImportDocumentsMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ImportDocumentsMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ImportDocumentsMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BulkDeleteDocumentsMetadata. */ + interface IBulkDeleteDocumentsMetadata { + + /** BulkDeleteDocumentsMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** BulkDeleteDocumentsMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata collectionIds */ + collectionIds?: (string[]|null); + + /** BulkDeleteDocumentsMetadata namespaceIds */ + namespaceIds?: (string[]|null); + + /** BulkDeleteDocumentsMetadata snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BulkDeleteDocumentsMetadata. */ + class BulkDeleteDocumentsMetadata implements IBulkDeleteDocumentsMetadata { + + /** + * Constructs a new BulkDeleteDocumentsMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBulkDeleteDocumentsMetadata); + + /** BulkDeleteDocumentsMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** BulkDeleteDocumentsMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata collectionIds. */ + public collectionIds: string[]; + + /** BulkDeleteDocumentsMetadata namespaceIds. */ + public namespaceIds: string[]; + + /** BulkDeleteDocumentsMetadata snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a BulkDeleteDocumentsMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BulkDeleteDocumentsMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BulkDeleteDocumentsMetadata; + + /** + * Creates a plain object from a BulkDeleteDocumentsMetadata message. Also converts values to other types if specified. + * @param message BulkDeleteDocumentsMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.BulkDeleteDocumentsMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BulkDeleteDocumentsMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BulkDeleteDocumentsMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExportDocumentsResponse. */ + interface IExportDocumentsResponse { + + /** ExportDocumentsResponse outputUriPrefix */ + outputUriPrefix?: (string|null); + } + + /** Represents an ExportDocumentsResponse. */ + class ExportDocumentsResponse implements IExportDocumentsResponse { + + /** + * Constructs a new ExportDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IExportDocumentsResponse); + + /** ExportDocumentsResponse outputUriPrefix. */ + public outputUriPrefix: string; + + /** + * Creates an ExportDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExportDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ExportDocumentsResponse; + + /** + * Creates a plain object from an ExportDocumentsResponse message. Also converts values to other types if specified. + * @param message ExportDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ExportDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExportDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExportDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RestoreDatabaseMetadata. */ + interface IRestoreDatabaseMetadata { + + /** RestoreDatabaseMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** RestoreDatabaseMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** RestoreDatabaseMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** RestoreDatabaseMetadata database */ + database?: (string|null); + + /** RestoreDatabaseMetadata backup */ + backup?: (string|null); + + /** RestoreDatabaseMetadata progressPercentage */ + progressPercentage?: (google.firestore.admin.v1.IProgress|null); + } + + /** Represents a RestoreDatabaseMetadata. */ + class RestoreDatabaseMetadata implements IRestoreDatabaseMetadata { + + /** + * Constructs a new RestoreDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IRestoreDatabaseMetadata); + + /** RestoreDatabaseMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** RestoreDatabaseMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** RestoreDatabaseMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** RestoreDatabaseMetadata database. */ + public database: string; + + /** RestoreDatabaseMetadata backup. */ + public backup: string; + + /** RestoreDatabaseMetadata progressPercentage. */ + public progressPercentage?: (google.firestore.admin.v1.IProgress|null); + + /** + * Creates a RestoreDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RestoreDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.RestoreDatabaseMetadata; + + /** + * Creates a plain object from a RestoreDatabaseMetadata message. Also converts values to other types if specified. + * @param message RestoreDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.RestoreDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RestoreDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RestoreDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Progress. */ + interface IProgress { + + /** Progress estimatedWork */ + estimatedWork?: (number|string|null); + + /** Progress completedWork */ + completedWork?: (number|string|null); + } + + /** Represents a Progress. */ + class Progress implements IProgress { + + /** + * Constructs a new Progress. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IProgress); + + /** Progress estimatedWork. */ + public estimatedWork: (number|string); + + /** Progress completedWork. */ + public completedWork: (number|string); + + /** + * Creates a Progress message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Progress + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Progress; + + /** + * Creates a plain object from a Progress message. Also converts values to other types if specified. + * @param message Progress + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Progress, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Progress to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Progress + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** OperationState enum. */ + type OperationState = + "OPERATION_STATE_UNSPECIFIED"| "INITIALIZING"| "PROCESSING"| "CANCELLING"| "FINALIZING"| "SUCCESSFUL"| "FAILED"| "CANCELLED"; + + /** Properties of a BackupSchedule. */ + interface IBackupSchedule { + + /** BackupSchedule name */ + name?: (string|null); + + /** BackupSchedule createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** BackupSchedule updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** BackupSchedule retention */ + retention?: (google.protobuf.IDuration|null); + + /** BackupSchedule dailyRecurrence */ + dailyRecurrence?: (google.firestore.admin.v1.IDailyRecurrence|null); + + /** BackupSchedule weeklyRecurrence */ + weeklyRecurrence?: (google.firestore.admin.v1.IWeeklyRecurrence|null); + } + + /** Represents a BackupSchedule. */ + class BackupSchedule implements IBackupSchedule { + + /** + * Constructs a new BackupSchedule. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBackupSchedule); + + /** BackupSchedule name. */ + public name: string; + + /** BackupSchedule createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** BackupSchedule updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** BackupSchedule retention. */ + public retention?: (google.protobuf.IDuration|null); + + /** BackupSchedule dailyRecurrence. */ + public dailyRecurrence?: (google.firestore.admin.v1.IDailyRecurrence|null); + + /** BackupSchedule weeklyRecurrence. */ + public weeklyRecurrence?: (google.firestore.admin.v1.IWeeklyRecurrence|null); + + /** BackupSchedule recurrence. */ + public recurrence?: ("dailyRecurrence"|"weeklyRecurrence"); + + /** + * Creates a BackupSchedule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BackupSchedule + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BackupSchedule; + + /** + * Creates a plain object from a BackupSchedule message. Also converts values to other types if specified. + * @param message BackupSchedule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.BackupSchedule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BackupSchedule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BackupSchedule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DailyRecurrence. */ + interface IDailyRecurrence { + } + + /** Represents a DailyRecurrence. */ + class DailyRecurrence implements IDailyRecurrence { + + /** + * Constructs a new DailyRecurrence. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDailyRecurrence); + + /** + * Creates a DailyRecurrence message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DailyRecurrence + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DailyRecurrence; + + /** + * Creates a plain object from a DailyRecurrence message. Also converts values to other types if specified. + * @param message DailyRecurrence + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DailyRecurrence, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DailyRecurrence to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DailyRecurrence + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WeeklyRecurrence. */ + interface IWeeklyRecurrence { + + /** WeeklyRecurrence day */ + day?: (google.type.DayOfWeek|null); + } + + /** Represents a WeeklyRecurrence. */ + class WeeklyRecurrence implements IWeeklyRecurrence { + + /** + * Constructs a new WeeklyRecurrence. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IWeeklyRecurrence); + + /** WeeklyRecurrence day. */ + public day: google.type.DayOfWeek; + + /** + * Creates a WeeklyRecurrence message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WeeklyRecurrence + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.WeeklyRecurrence; + + /** + * Creates a plain object from a WeeklyRecurrence message. Also converts values to other types if specified. + * @param message WeeklyRecurrence + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.WeeklyRecurrence, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WeeklyRecurrence to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WeeklyRecurrence + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a LocationMetadata. */ + interface ILocationMetadata { + } + + /** Represents a LocationMetadata. */ + class LocationMetadata implements ILocationMetadata { + + /** + * Constructs a new LocationMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ILocationMetadata); + + /** + * Creates a LocationMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LocationMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.LocationMetadata; + + /** + * Creates a plain object from a LocationMetadata message. Also converts values to other types if specified. + * @param message LocationMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.LocationMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LocationMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LocationMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + } + + /** Namespace api. */ + namespace api { + + /** FieldBehavior enum. */ + type FieldBehavior = + "FIELD_BEHAVIOR_UNSPECIFIED"| "OPTIONAL"| "REQUIRED"| "OUTPUT_ONLY"| "INPUT_ONLY"| "IMMUTABLE"| "UNORDERED_LIST"| "NON_EMPTY_DEFAULT"| "IDENTIFIER"; + + /** Properties of a ResourceDescriptor. */ + interface IResourceDescriptor { + + /** ResourceDescriptor type */ + type?: (string|null); + + /** ResourceDescriptor pattern */ + pattern?: (string[]|null); + + /** ResourceDescriptor nameField */ + nameField?: (string|null); + + /** ResourceDescriptor history */ + history?: (google.api.ResourceDescriptor.History|null); + + /** ResourceDescriptor plural */ + plural?: (string|null); + + /** ResourceDescriptor singular */ + singular?: (string|null); + + /** ResourceDescriptor style */ + style?: (google.api.ResourceDescriptor.Style[]|null); + } + + /** Represents a ResourceDescriptor. */ + class ResourceDescriptor implements IResourceDescriptor { + + /** + * Constructs a new ResourceDescriptor. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceDescriptor); + + /** ResourceDescriptor type. */ + public type: string; + + /** ResourceDescriptor pattern. */ + public pattern: string[]; + + /** ResourceDescriptor nameField. */ + public nameField: string; + + /** ResourceDescriptor history. */ + public history: google.api.ResourceDescriptor.History; + + /** ResourceDescriptor plural. */ + public plural: string; + + /** ResourceDescriptor singular. */ + public singular: string; + + /** ResourceDescriptor style. */ + public style: google.api.ResourceDescriptor.Style[]; + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceDescriptor + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @param message ResourceDescriptor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceDescriptor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceDescriptor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ResourceDescriptor { + + /** History enum. */ + type History = + "HISTORY_UNSPECIFIED"| "ORIGINALLY_SINGLE_PATTERN"| "FUTURE_MULTI_PATTERN"; + + /** Style enum. */ + type Style = + "STYLE_UNSPECIFIED"| "DECLARATIVE_FRIENDLY"; + } + + /** Properties of a ResourceReference. */ + interface IResourceReference { + + /** ResourceReference type */ + type?: (string|null); + + /** ResourceReference childType */ + childType?: (string|null); + } + + /** Represents a ResourceReference. */ + class ResourceReference implements IResourceReference { + + /** + * Constructs a new ResourceReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceReference); + + /** ResourceReference type. */ + public type: string; + + /** ResourceReference childType. */ + public childType: string; + + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceReference + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; + + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @param message ResourceReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Http. */ + interface IHttp { + + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); + + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); + } + + /** Represents a Http. */ + class Http implements IHttp { + + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); + + /** Http rules. */ + public rules: google.api.IHttpRule[]; + + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Http + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a HttpRule. */ + interface IHttpRule { + + /** HttpRule selector */ + selector?: (string|null); + + /** HttpRule get */ + get?: (string|null); + + /** HttpRule put */ + put?: (string|null); + + /** HttpRule post */ + post?: (string|null); + + /** HttpRule delete */ + "delete"?: (string|null); + + /** HttpRule patch */ + patch?: (string|null); + + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body */ + body?: (string|null); + + /** HttpRule responseBody */ + responseBody?: (string|null); + + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); + } + + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { + + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); + + /** HttpRule selector. */ + public selector: string; + + /** HttpRule get. */ + public get?: (string|null); + + /** HttpRule put. */ + public put?: (string|null); + + /** HttpRule post. */ + public post?: (string|null); + + /** HttpRule delete. */ + public delete?: (string|null); + + /** HttpRule patch. */ + public patch?: (string|null); + + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body. */ + public body: string; + + /** HttpRule responseBody. */ + public responseBody: string; + + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; + + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for HttpRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { + + /** CustomHttpPattern kind */ + kind?: (string|null); + + /** CustomHttpPattern path */ + path?: (string|null); + } + + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { + + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); + + /** CustomHttpPattern kind. */ + public kind: string; + + /** CustomHttpPattern path. */ + public path: string; + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CustomHttpPattern + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommonLanguageSettings. */ + interface ICommonLanguageSettings { + + /** CommonLanguageSettings referenceDocsUri */ + referenceDocsUri?: (string|null); + + /** CommonLanguageSettings destinations */ + destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + } + + /** Represents a CommonLanguageSettings. */ + class CommonLanguageSettings implements ICommonLanguageSettings { + + /** + * Constructs a new CommonLanguageSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICommonLanguageSettings); + + /** CommonLanguageSettings referenceDocsUri. */ + public referenceDocsUri: string; + + /** CommonLanguageSettings destinations. */ + public destinations: google.api.ClientLibraryDestination[]; + + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommonLanguageSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CommonLanguageSettings; + + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @param message CommonLanguageSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CommonLanguageSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommonLanguageSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommonLanguageSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ClientLibrarySettings. */ + interface IClientLibrarySettings { + + /** ClientLibrarySettings version */ + version?: (string|null); + + /** ClientLibrarySettings launchStage */ + launchStage?: (google.api.LaunchStage|null); + + /** ClientLibrarySettings restNumericEnums */ + restNumericEnums?: (boolean|null); + + /** ClientLibrarySettings javaSettings */ + javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings */ + cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings */ + phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings */ + pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings */ + nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings */ + dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings */ + rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings */ + goSettings?: (google.api.IGoSettings|null); + } + + /** Represents a ClientLibrarySettings. */ + class ClientLibrarySettings implements IClientLibrarySettings { + + /** + * Constructs a new ClientLibrarySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IClientLibrarySettings); + + /** ClientLibrarySettings version. */ + public version: string; + + /** ClientLibrarySettings launchStage. */ + public launchStage: google.api.LaunchStage; + + /** ClientLibrarySettings restNumericEnums. */ + public restNumericEnums: boolean; + + /** ClientLibrarySettings javaSettings. */ + public javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings. */ + public cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings. */ + public phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings. */ + public pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings. */ + public nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings. */ + public dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings. */ + public rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings. */ + public goSettings?: (google.api.IGoSettings|null); + + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ClientLibrarySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.ClientLibrarySettings; + + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @param message ClientLibrarySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ClientLibrarySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ClientLibrarySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ClientLibrarySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Publishing. */ + interface IPublishing { + + /** Publishing methodSettings */ + methodSettings?: (google.api.IMethodSettings[]|null); + + /** Publishing newIssueUri */ + newIssueUri?: (string|null); + + /** Publishing documentationUri */ + documentationUri?: (string|null); + + /** Publishing apiShortName */ + apiShortName?: (string|null); + + /** Publishing githubLabel */ + githubLabel?: (string|null); + + /** Publishing codeownerGithubTeams */ + codeownerGithubTeams?: (string[]|null); + + /** Publishing docTagPrefix */ + docTagPrefix?: (string|null); + + /** Publishing organization */ + organization?: (google.api.ClientLibraryOrganization|null); + + /** Publishing librarySettings */ + librarySettings?: (google.api.IClientLibrarySettings[]|null); + + /** Publishing protoReferenceDocumentationUri */ + protoReferenceDocumentationUri?: (string|null); + + /** Publishing restReferenceDocumentationUri */ + restReferenceDocumentationUri?: (string|null); + } + + /** Represents a Publishing. */ + class Publishing implements IPublishing { + + /** + * Constructs a new Publishing. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPublishing); + + /** Publishing methodSettings. */ + public methodSettings: google.api.IMethodSettings[]; + + /** Publishing newIssueUri. */ + public newIssueUri: string; + + /** Publishing documentationUri. */ + public documentationUri: string; + + /** Publishing apiShortName. */ + public apiShortName: string; + + /** Publishing githubLabel. */ + public githubLabel: string; + + /** Publishing codeownerGithubTeams. */ + public codeownerGithubTeams: string[]; + + /** Publishing docTagPrefix. */ + public docTagPrefix: string; + + /** Publishing organization. */ + public organization: google.api.ClientLibraryOrganization; + + /** Publishing librarySettings. */ + public librarySettings: google.api.IClientLibrarySettings[]; + + /** Publishing protoReferenceDocumentationUri. */ + public protoReferenceDocumentationUri: string; + + /** Publishing restReferenceDocumentationUri. */ + public restReferenceDocumentationUri: string; + + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Publishing + */ + public static fromObject(object: { [k: string]: any }): google.api.Publishing; + + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @param message Publishing + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Publishing, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Publishing to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Publishing + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a JavaSettings. */ + interface IJavaSettings { + + /** JavaSettings libraryPackage */ + libraryPackage?: (string|null); + + /** JavaSettings serviceClassNames */ + serviceClassNames?: ({ [k: string]: string }|null); + + /** JavaSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a JavaSettings. */ + class JavaSettings implements IJavaSettings { + + /** + * Constructs a new JavaSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IJavaSettings); + + /** JavaSettings libraryPackage. */ + public libraryPackage: string; + + /** JavaSettings serviceClassNames. */ + public serviceClassNames: { [k: string]: string }; + + /** JavaSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns JavaSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.JavaSettings; + + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @param message JavaSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.JavaSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this JavaSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for JavaSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CppSettings. */ + interface ICppSettings { + + /** CppSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a CppSettings. */ + class CppSettings implements ICppSettings { + + /** + * Constructs a new CppSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICppSettings); + + /** CppSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CppSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CppSettings; + + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @param message CppSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CppSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CppSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CppSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PhpSettings. */ + interface IPhpSettings { + + /** PhpSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a PhpSettings. */ + class PhpSettings implements IPhpSettings { + + /** + * Constructs a new PhpSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPhpSettings); + + /** PhpSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PhpSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PhpSettings; + + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @param message PhpSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PhpSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PhpSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PhpSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PythonSettings. */ + interface IPythonSettings { + + /** PythonSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + } + + /** Represents a PythonSettings. */ + class PythonSettings implements IPythonSettings { + + /** + * Constructs a new PythonSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPythonSettings); + + /** PythonSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PythonSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings; + + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @param message PythonSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PythonSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PythonSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace PythonSettings { + + /** Properties of an ExperimentalFeatures. */ + interface IExperimentalFeatures { + + /** ExperimentalFeatures restAsyncIoEnabled */ + restAsyncIoEnabled?: (boolean|null); + + /** ExperimentalFeatures protobufPythonicTypesEnabled */ + protobufPythonicTypesEnabled?: (boolean|null); + } + + /** Represents an ExperimentalFeatures. */ + class ExperimentalFeatures implements IExperimentalFeatures { + + /** + * Constructs a new ExperimentalFeatures. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.PythonSettings.IExperimentalFeatures); + + /** ExperimentalFeatures restAsyncIoEnabled. */ + public restAsyncIoEnabled: boolean; + + /** ExperimentalFeatures protobufPythonicTypesEnabled. */ + public protobufPythonicTypesEnabled: boolean; + + /** + * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExperimentalFeatures + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. + * @param message ExperimentalFeatures + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings.ExperimentalFeatures, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExperimentalFeatures to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExperimentalFeatures + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a NodeSettings. */ + interface INodeSettings { + + /** NodeSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a NodeSettings. */ + class NodeSettings implements INodeSettings { + + /** + * Constructs a new NodeSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.INodeSettings); + + /** NodeSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NodeSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.NodeSettings; + + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @param message NodeSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.NodeSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NodeSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NodeSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DotnetSettings. */ + interface IDotnetSettings { + + /** DotnetSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + + /** DotnetSettings renamedResources */ + renamedResources?: ({ [k: string]: string }|null); + + /** DotnetSettings ignoredResources */ + ignoredResources?: (string[]|null); + + /** DotnetSettings forcedNamespaceAliases */ + forcedNamespaceAliases?: (string[]|null); + + /** DotnetSettings handwrittenSignatures */ + handwrittenSignatures?: (string[]|null); + } + + /** Represents a DotnetSettings. */ + class DotnetSettings implements IDotnetSettings { + + /** + * Constructs a new DotnetSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IDotnetSettings); + + /** DotnetSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** DotnetSettings renamedResources. */ + public renamedResources: { [k: string]: string }; + + /** DotnetSettings ignoredResources. */ + public ignoredResources: string[]; + + /** DotnetSettings forcedNamespaceAliases. */ + public forcedNamespaceAliases: string[]; + + /** DotnetSettings handwrittenSignatures. */ + public handwrittenSignatures: string[]; + + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DotnetSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.DotnetSettings; + + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @param message DotnetSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.DotnetSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DotnetSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DotnetSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RubySettings. */ + interface IRubySettings { + + /** RubySettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a RubySettings. */ + class RubySettings implements IRubySettings { + + /** + * Constructs a new RubySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRubySettings); + + /** RubySettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RubySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.RubySettings; + + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @param message RubySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RubySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RubySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RubySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GoSettings. */ + interface IGoSettings { + + /** GoSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + } + + /** Represents a GoSettings. */ + class GoSettings implements IGoSettings { + + /** + * Constructs a new GoSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IGoSettings); + + /** GoSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GoSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.GoSettings; + + /** + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @param message GoSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.GoSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GoSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GoSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodSettings. */ + interface IMethodSettings { + + /** MethodSettings selector */ + selector?: (string|null); + + /** MethodSettings longRunning */ + longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields */ + autoPopulatedFields?: (string[]|null); + } + + /** Represents a MethodSettings. */ + class MethodSettings implements IMethodSettings { + + /** + * Constructs a new MethodSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IMethodSettings); + + /** MethodSettings selector. */ + public selector: string; + + /** MethodSettings longRunning. */ + public longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields. */ + public autoPopulatedFields: string[]; + + /** + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings; + + /** + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @param message MethodSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodSettings { + + /** Properties of a LongRunning. */ + interface ILongRunning { + + /** LongRunning initialPollDelay */ + initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier */ + pollDelayMultiplier?: (number|null); + + /** LongRunning maxPollDelay */ + maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout */ + totalPollTimeout?: (google.protobuf.IDuration|null); + } + + /** Represents a LongRunning. */ + class LongRunning implements ILongRunning { + + /** + * Constructs a new LongRunning. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.MethodSettings.ILongRunning); + + /** LongRunning initialPollDelay. */ + public initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier. */ + public pollDelayMultiplier: number; + + /** LongRunning maxPollDelay. */ + public maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout. */ + public totalPollTimeout?: (google.protobuf.IDuration|null); + + /** + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LongRunning + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings.LongRunning; + + /** + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @param message LongRunning + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings.LongRunning, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LongRunning to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LongRunning + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** ClientLibraryOrganization enum. */ + type ClientLibraryOrganization = + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"| "CLOUD"| "ADS"| "PHOTOS"| "STREET_VIEW"| "SHOPPING"| "GEO"| "GENERATIVE_AI"; + + /** ClientLibraryDestination enum. */ + type ClientLibraryDestination = + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"| "GITHUB"| "PACKAGE_MANAGER"; + + /** Properties of a SelectiveGapicGeneration. */ + interface ISelectiveGapicGeneration { + + /** SelectiveGapicGeneration methods */ + methods?: (string[]|null); + + /** SelectiveGapicGeneration generateOmittedAsInternal */ + generateOmittedAsInternal?: (boolean|null); + } + + /** Represents a SelectiveGapicGeneration. */ + class SelectiveGapicGeneration implements ISelectiveGapicGeneration { + + /** + * Constructs a new SelectiveGapicGeneration. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ISelectiveGapicGeneration); + + /** SelectiveGapicGeneration methods. */ + public methods: string[]; + + /** SelectiveGapicGeneration generateOmittedAsInternal. */ + public generateOmittedAsInternal: boolean; + + /** + * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SelectiveGapicGeneration + */ + public static fromObject(object: { [k: string]: any }): google.api.SelectiveGapicGeneration; + + /** + * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. + * @param message SelectiveGapicGeneration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.SelectiveGapicGeneration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SelectiveGapicGeneration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SelectiveGapicGeneration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** LaunchStage enum. */ + type LaunchStage = + "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; + } + + /** Namespace protobuf. */ + namespace protobuf { + + /** Properties of a FileDescriptorSet. */ + interface IFileDescriptorSet { + + /** FileDescriptorSet file */ + file?: (google.protobuf.IFileDescriptorProto[]|null); + } + + /** Represents a FileDescriptorSet. */ + class FileDescriptorSet implements IFileDescriptorSet { + + /** + * Constructs a new FileDescriptorSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorSet); + + /** FileDescriptorSet file. */ + public file: google.protobuf.IFileDescriptorProto[]; + + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; + + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @param message FileDescriptorSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Edition enum. */ + type Edition = + "EDITION_UNKNOWN"| "EDITION_PROTO2"| "EDITION_PROTO3"| "EDITION_2023"| "EDITION_2024"| "EDITION_1_TEST_ONLY"| "EDITION_2_TEST_ONLY"| "EDITION_99997_TEST_ONLY"| "EDITION_99998_TEST_ONLY"| "EDITION_99999_TEST_ONLY"| "EDITION_MAX"; + + /** Properties of a FileDescriptorProto. */ + interface IFileDescriptorProto { + + /** FileDescriptorProto name */ + name?: (string|null); + + /** FileDescriptorProto package */ + "package"?: (string|null); + + /** FileDescriptorProto dependency */ + dependency?: (string[]|null); + + /** FileDescriptorProto publicDependency */ + publicDependency?: (number[]|null); + + /** FileDescriptorProto weakDependency */ + weakDependency?: (number[]|null); + + /** FileDescriptorProto messageType */ + messageType?: (google.protobuf.IDescriptorProto[]|null); + + /** FileDescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** FileDescriptorProto service */ + service?: (google.protobuf.IServiceDescriptorProto[]|null); + + /** FileDescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** FileDescriptorProto options */ + options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo */ + sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax */ + syntax?: (string|null); + + /** FileDescriptorProto edition */ + edition?: (google.protobuf.Edition|null); + } + + /** Represents a FileDescriptorProto. */ + class FileDescriptorProto implements IFileDescriptorProto { + + /** + * Constructs a new FileDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorProto); + + /** FileDescriptorProto name. */ + public name: string; + + /** FileDescriptorProto package. */ + public package: string; + + /** FileDescriptorProto dependency. */ + public dependency: string[]; + + /** FileDescriptorProto publicDependency. */ + public publicDependency: number[]; + + /** FileDescriptorProto weakDependency. */ + public weakDependency: number[]; + + /** FileDescriptorProto messageType. */ + public messageType: google.protobuf.IDescriptorProto[]; + + /** FileDescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** FileDescriptorProto service. */ + public service: google.protobuf.IServiceDescriptorProto[]; + + /** FileDescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** FileDescriptorProto options. */ + public options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo. */ + public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax. */ + public syntax: string; + + /** FileDescriptorProto edition. */ + public edition: google.protobuf.Edition; + + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; + + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @param message FileDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DescriptorProto. */ + interface IDescriptorProto { + + /** DescriptorProto name */ + name?: (string|null); + + /** DescriptorProto field */ + field?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto nestedType */ + nestedType?: (google.protobuf.IDescriptorProto[]|null); + + /** DescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** DescriptorProto extensionRange */ + extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); + + /** DescriptorProto oneofDecl */ + oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); + + /** DescriptorProto options */ + options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange */ + reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); + + /** DescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents a DescriptorProto. */ + class DescriptorProto implements IDescriptorProto { + + /** + * Constructs a new DescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDescriptorProto); + + /** DescriptorProto name. */ + public name: string; + + /** DescriptorProto field. */ + public field: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto nestedType. */ + public nestedType: google.protobuf.IDescriptorProto[]; + + /** DescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** DescriptorProto extensionRange. */ + public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; + + /** DescriptorProto oneofDecl. */ + public oneofDecl: google.protobuf.IOneofDescriptorProto[]; + + /** DescriptorProto options. */ + public options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange. */ + public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; + + /** DescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; + + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @param message DescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DescriptorProto { + + /** Properties of an ExtensionRange. */ + interface IExtensionRange { + + /** ExtensionRange start */ + start?: (number|null); + + /** ExtensionRange end */ + end?: (number|null); + + /** ExtensionRange options */ + options?: (google.protobuf.IExtensionRangeOptions|null); + } + + /** Represents an ExtensionRange. */ + class ExtensionRange implements IExtensionRange { + + /** + * Constructs a new ExtensionRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); + + /** ExtensionRange start. */ + public start: number; + + /** ExtensionRange end. */ + public end: number; + + /** ExtensionRange options. */ + public options?: (google.protobuf.IExtensionRangeOptions|null); + + /** + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @param message ExtensionRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReservedRange. */ + interface IReservedRange { + + /** ReservedRange start */ + start?: (number|null); + + /** ReservedRange end */ + end?: (number|null); + } + + /** Represents a ReservedRange. */ + class ReservedRange implements IReservedRange { + + /** + * Constructs a new ReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); + + /** ReservedRange start. */ + public start: number; + + /** ReservedRange end. */ + public end: number; + + /** + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @param message ReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an ExtensionRangeOptions. */ + interface IExtensionRangeOptions { + + /** ExtensionRangeOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ExtensionRangeOptions declaration */ + declaration?: (google.protobuf.ExtensionRangeOptions.IDeclaration[]|null); + + /** ExtensionRangeOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification */ + verification?: (google.protobuf.ExtensionRangeOptions.VerificationState|null); + } + + /** Represents an ExtensionRangeOptions. */ + class ExtensionRangeOptions implements IExtensionRangeOptions { + + /** + * Constructs a new ExtensionRangeOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IExtensionRangeOptions); + + /** ExtensionRangeOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** ExtensionRangeOptions declaration. */ + public declaration: google.protobuf.ExtensionRangeOptions.IDeclaration[]; + + /** ExtensionRangeOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification. */ + public verification: google.protobuf.ExtensionRangeOptions.VerificationState; + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRangeOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @param message ExtensionRangeOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRangeOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ExtensionRangeOptions { + + /** Properties of a Declaration. */ + interface IDeclaration { + + /** Declaration number */ + number?: (number|null); + + /** Declaration fullName */ + fullName?: (string|null); + + /** Declaration type */ + type?: (string|null); + + /** Declaration reserved */ + reserved?: (boolean|null); + + /** Declaration repeated */ + repeated?: (boolean|null); + } + + /** Represents a Declaration. */ + class Declaration implements IDeclaration { + + /** + * Constructs a new Declaration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ExtensionRangeOptions.IDeclaration); + + /** Declaration number. */ + public number: number; + + /** Declaration fullName. */ + public fullName: string; + + /** Declaration type. */ + public type: string; + + /** Declaration reserved. */ + public reserved: boolean; + + /** Declaration repeated. */ + public repeated: boolean; + + /** + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Declaration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions.Declaration; + + /** + * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * @param message Declaration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions.Declaration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Declaration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Declaration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** VerificationState enum. */ + type VerificationState = + "DECLARATION"| "UNVERIFIED"; + } + + /** Properties of a FieldDescriptorProto. */ + interface IFieldDescriptorProto { + + /** FieldDescriptorProto name */ + name?: (string|null); + + /** FieldDescriptorProto number */ + number?: (number|null); + + /** FieldDescriptorProto label */ + label?: (google.protobuf.FieldDescriptorProto.Label|null); + + /** FieldDescriptorProto type */ + type?: (google.protobuf.FieldDescriptorProto.Type|null); + + /** FieldDescriptorProto typeName */ + typeName?: (string|null); + + /** FieldDescriptorProto extendee */ + extendee?: (string|null); + + /** FieldDescriptorProto defaultValue */ + defaultValue?: (string|null); + + /** FieldDescriptorProto oneofIndex */ + oneofIndex?: (number|null); + + /** FieldDescriptorProto jsonName */ + jsonName?: (string|null); + + /** FieldDescriptorProto options */ + options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional */ + proto3Optional?: (boolean|null); + } + + /** Represents a FieldDescriptorProto. */ + class FieldDescriptorProto implements IFieldDescriptorProto { + + /** + * Constructs a new FieldDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldDescriptorProto); + + /** FieldDescriptorProto name. */ + public name: string; + + /** FieldDescriptorProto number. */ + public number: number; + + /** FieldDescriptorProto label. */ + public label: google.protobuf.FieldDescriptorProto.Label; + + /** FieldDescriptorProto type. */ + public type: google.protobuf.FieldDescriptorProto.Type; + + /** FieldDescriptorProto typeName. */ + public typeName: string; + + /** FieldDescriptorProto extendee. */ + public extendee: string; + + /** FieldDescriptorProto defaultValue. */ + public defaultValue: string; + + /** FieldDescriptorProto oneofIndex. */ + public oneofIndex: number; + + /** FieldDescriptorProto jsonName. */ + public jsonName: string; + + /** FieldDescriptorProto options. */ + public options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional. */ + public proto3Optional: boolean; + + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @param message FieldDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldDescriptorProto { + + /** Type enum. */ + type Type = + "TYPE_DOUBLE"| "TYPE_FLOAT"| "TYPE_INT64"| "TYPE_UINT64"| "TYPE_INT32"| "TYPE_FIXED64"| "TYPE_FIXED32"| "TYPE_BOOL"| "TYPE_STRING"| "TYPE_GROUP"| "TYPE_MESSAGE"| "TYPE_BYTES"| "TYPE_UINT32"| "TYPE_ENUM"| "TYPE_SFIXED32"| "TYPE_SFIXED64"| "TYPE_SINT32"| "TYPE_SINT64"; + + /** Label enum. */ + type Label = + "LABEL_OPTIONAL"| "LABEL_REPEATED"| "LABEL_REQUIRED"; + } + + /** Properties of an OneofDescriptorProto. */ + interface IOneofDescriptorProto { + + /** OneofDescriptorProto name */ + name?: (string|null); + + /** OneofDescriptorProto options */ + options?: (google.protobuf.IOneofOptions|null); + } + + /** Represents an OneofDescriptorProto. */ + class OneofDescriptorProto implements IOneofDescriptorProto { + + /** + * Constructs a new OneofDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofDescriptorProto); + + /** OneofDescriptorProto name. */ + public name: string; + + /** OneofDescriptorProto options. */ + public options?: (google.protobuf.IOneofOptions|null); + + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; + + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @param message OneofDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumDescriptorProto. */ + interface IEnumDescriptorProto { + + /** EnumDescriptorProto name */ + name?: (string|null); + + /** EnumDescriptorProto value */ + value?: (google.protobuf.IEnumValueDescriptorProto[]|null); + + /** EnumDescriptorProto options */ + options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange */ + reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); + + /** EnumDescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents an EnumDescriptorProto. */ + class EnumDescriptorProto implements IEnumDescriptorProto { + + /** + * Constructs a new EnumDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumDescriptorProto); + + /** EnumDescriptorProto name. */ + public name: string; + + /** EnumDescriptorProto value. */ + public value: google.protobuf.IEnumValueDescriptorProto[]; + + /** EnumDescriptorProto options. */ + public options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange. */ + public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; + + /** EnumDescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; + + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @param message EnumDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace EnumDescriptorProto { + + /** Properties of an EnumReservedRange. */ + interface IEnumReservedRange { + + /** EnumReservedRange start */ + start?: (number|null); + + /** EnumReservedRange end */ + end?: (number|null); + } + + /** Represents an EnumReservedRange. */ + class EnumReservedRange implements IEnumReservedRange { + + /** + * Constructs a new EnumReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); + + /** EnumReservedRange start. */ + public start: number; + + /** EnumReservedRange end. */ + public end: number; + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @param message EnumReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an EnumValueDescriptorProto. */ + interface IEnumValueDescriptorProto { + + /** EnumValueDescriptorProto name */ + name?: (string|null); + + /** EnumValueDescriptorProto number */ + number?: (number|null); + + /** EnumValueDescriptorProto options */ + options?: (google.protobuf.IEnumValueOptions|null); + } + + /** Represents an EnumValueDescriptorProto. */ + class EnumValueDescriptorProto implements IEnumValueDescriptorProto { + + /** + * Constructs a new EnumValueDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueDescriptorProto); + + /** EnumValueDescriptorProto name. */ + public name: string; + + /** EnumValueDescriptorProto number. */ + public number: number; + + /** EnumValueDescriptorProto options. */ + public options?: (google.protobuf.IEnumValueOptions|null); + + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; + + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @param message EnumValueDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceDescriptorProto. */ + interface IServiceDescriptorProto { + + /** ServiceDescriptorProto name */ + name?: (string|null); + + /** ServiceDescriptorProto method */ + method?: (google.protobuf.IMethodDescriptorProto[]|null); + + /** ServiceDescriptorProto options */ + options?: (google.protobuf.IServiceOptions|null); + } + + /** Represents a ServiceDescriptorProto. */ + class ServiceDescriptorProto implements IServiceDescriptorProto { + + /** + * Constructs a new ServiceDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceDescriptorProto); + + /** ServiceDescriptorProto name. */ + public name: string; + + /** ServiceDescriptorProto method. */ + public method: google.protobuf.IMethodDescriptorProto[]; + + /** ServiceDescriptorProto options. */ + public options?: (google.protobuf.IServiceOptions|null); + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @param message ServiceDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodDescriptorProto. */ + interface IMethodDescriptorProto { + + /** MethodDescriptorProto name */ + name?: (string|null); + + /** MethodDescriptorProto inputType */ + inputType?: (string|null); + + /** MethodDescriptorProto outputType */ + outputType?: (string|null); + + /** MethodDescriptorProto options */ + options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming */ + clientStreaming?: (boolean|null); + + /** MethodDescriptorProto serverStreaming */ + serverStreaming?: (boolean|null); + } + + /** Represents a MethodDescriptorProto. */ + class MethodDescriptorProto implements IMethodDescriptorProto { + + /** + * Constructs a new MethodDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodDescriptorProto); + + /** MethodDescriptorProto name. */ + public name: string; + + /** MethodDescriptorProto inputType. */ + public inputType: string; + + /** MethodDescriptorProto outputType. */ + public outputType: string; + + /** MethodDescriptorProto options. */ + public options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming. */ + public clientStreaming: boolean; + + /** MethodDescriptorProto serverStreaming. */ + public serverStreaming: boolean; + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @param message MethodDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FileOptions. */ + interface IFileOptions { + + /** FileOptions javaPackage */ + javaPackage?: (string|null); + + /** FileOptions javaOuterClassname */ + javaOuterClassname?: (string|null); + + /** FileOptions javaMultipleFiles */ + javaMultipleFiles?: (boolean|null); + + /** FileOptions javaGenerateEqualsAndHash */ + javaGenerateEqualsAndHash?: (boolean|null); + + /** FileOptions javaStringCheckUtf8 */ + javaStringCheckUtf8?: (boolean|null); + + /** FileOptions optimizeFor */ + optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); + + /** FileOptions goPackage */ + goPackage?: (string|null); + + /** FileOptions ccGenericServices */ + ccGenericServices?: (boolean|null); + + /** FileOptions javaGenericServices */ + javaGenericServices?: (boolean|null); + + /** FileOptions pyGenericServices */ + pyGenericServices?: (boolean|null); + + /** FileOptions deprecated */ + deprecated?: (boolean|null); + + /** FileOptions ccEnableArenas */ + ccEnableArenas?: (boolean|null); + + /** FileOptions objcClassPrefix */ + objcClassPrefix?: (string|null); + + /** FileOptions csharpNamespace */ + csharpNamespace?: (string|null); + + /** FileOptions swiftPrefix */ + swiftPrefix?: (string|null); + + /** FileOptions phpClassPrefix */ + phpClassPrefix?: (string|null); + + /** FileOptions phpNamespace */ + phpNamespace?: (string|null); + + /** FileOptions phpMetadataNamespace */ + phpMetadataNamespace?: (string|null); + + /** FileOptions rubyPackage */ + rubyPackage?: (string|null); + + /** FileOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FileOptions .google.api.resourceDefinition */ + ".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null); + } + + /** Represents a FileOptions. */ + class FileOptions implements IFileOptions { + + /** + * Constructs a new FileOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileOptions); + + /** FileOptions javaPackage. */ + public javaPackage: string; + + /** FileOptions javaOuterClassname. */ + public javaOuterClassname: string; + + /** FileOptions javaMultipleFiles. */ + public javaMultipleFiles: boolean; + + /** FileOptions javaGenerateEqualsAndHash. */ + public javaGenerateEqualsAndHash: boolean; + + /** FileOptions javaStringCheckUtf8. */ + public javaStringCheckUtf8: boolean; + + /** FileOptions optimizeFor. */ + public optimizeFor: google.protobuf.FileOptions.OptimizeMode; + + /** FileOptions goPackage. */ + public goPackage: string; + + /** FileOptions ccGenericServices. */ + public ccGenericServices: boolean; + + /** FileOptions javaGenericServices. */ + public javaGenericServices: boolean; + + /** FileOptions pyGenericServices. */ + public pyGenericServices: boolean; + + /** FileOptions deprecated. */ + public deprecated: boolean; + + /** FileOptions ccEnableArenas. */ + public ccEnableArenas: boolean; + + /** FileOptions objcClassPrefix. */ + public objcClassPrefix: string; + + /** FileOptions csharpNamespace. */ + public csharpNamespace: string; + + /** FileOptions swiftPrefix. */ + public swiftPrefix: string; + + /** FileOptions phpClassPrefix. */ + public phpClassPrefix: string; + + /** FileOptions phpNamespace. */ + public phpNamespace: string; + + /** FileOptions phpMetadataNamespace. */ + public phpMetadataNamespace: string; + + /** FileOptions rubyPackage. */ + public rubyPackage: string; + + /** FileOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; + + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @param message FileOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FileOptions { + + /** OptimizeMode enum. */ + type OptimizeMode = + "SPEED"| "CODE_SIZE"| "LITE_RUNTIME"; + } + + /** Properties of a MessageOptions. */ + interface IMessageOptions { + + /** MessageOptions messageSetWireFormat */ + messageSetWireFormat?: (boolean|null); + + /** MessageOptions noStandardDescriptorAccessor */ + noStandardDescriptorAccessor?: (boolean|null); + + /** MessageOptions deprecated */ + deprecated?: (boolean|null); + + /** MessageOptions mapEntry */ + mapEntry?: (boolean|null); + + /** MessageOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** MessageOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MessageOptions .google.api.resource */ + ".google.api.resource"?: (google.api.IResourceDescriptor|null); + } + + /** Represents a MessageOptions. */ + class MessageOptions implements IMessageOptions { + + /** + * Constructs a new MessageOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMessageOptions); + + /** MessageOptions messageSetWireFormat. */ + public messageSetWireFormat: boolean; + + /** MessageOptions noStandardDescriptorAccessor. */ + public noStandardDescriptorAccessor: boolean; + + /** MessageOptions deprecated. */ + public deprecated: boolean; + + /** MessageOptions mapEntry. */ + public mapEntry: boolean; + + /** MessageOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** MessageOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MessageOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; + + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @param message MessageOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MessageOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MessageOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldOptions. */ + interface IFieldOptions { + + /** FieldOptions ctype */ + ctype?: (google.protobuf.FieldOptions.CType|null); + + /** FieldOptions packed */ + packed?: (boolean|null); + + /** FieldOptions jstype */ + jstype?: (google.protobuf.FieldOptions.JSType|null); + + /** FieldOptions lazy */ + lazy?: (boolean|null); + + /** FieldOptions unverifiedLazy */ + unverifiedLazy?: (boolean|null); + + /** FieldOptions deprecated */ + deprecated?: (boolean|null); + + /** FieldOptions weak */ + weak?: (boolean|null); + + /** FieldOptions debugRedact */ + debugRedact?: (boolean|null); + + /** FieldOptions retention */ + retention?: (google.protobuf.FieldOptions.OptionRetention|null); + + /** FieldOptions targets */ + targets?: (google.protobuf.FieldOptions.OptionTargetType[]|null); + + /** FieldOptions editionDefaults */ + editionDefaults?: (google.protobuf.FieldOptions.IEditionDefault[]|null); + + /** FieldOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FieldOptions .google.api.fieldBehavior */ + ".google.api.fieldBehavior"?: (google.api.FieldBehavior[]|null); + + /** FieldOptions .google.api.resourceReference */ + ".google.api.resourceReference"?: (google.api.IResourceReference|null); + } + + /** Represents a FieldOptions. */ + class FieldOptions implements IFieldOptions { + + /** + * Constructs a new FieldOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldOptions); + + /** FieldOptions ctype. */ + public ctype: google.protobuf.FieldOptions.CType; + + /** FieldOptions packed. */ + public packed: boolean; + + /** FieldOptions jstype. */ + public jstype: google.protobuf.FieldOptions.JSType; + + /** FieldOptions lazy. */ + public lazy: boolean; + + /** FieldOptions unverifiedLazy. */ + public unverifiedLazy: boolean; + + /** FieldOptions deprecated. */ + public deprecated: boolean; + + /** FieldOptions weak. */ + public weak: boolean; + + /** FieldOptions debugRedact. */ + public debugRedact: boolean; + + /** FieldOptions retention. */ + public retention: google.protobuf.FieldOptions.OptionRetention; + + /** FieldOptions targets. */ + public targets: google.protobuf.FieldOptions.OptionTargetType[]; + + /** FieldOptions editionDefaults. */ + public editionDefaults: google.protobuf.FieldOptions.IEditionDefault[]; + + /** FieldOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; + + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @param message FieldOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldOptions { + + /** CType enum. */ + type CType = + "STRING"| "CORD"| "STRING_PIECE"; + + /** JSType enum. */ + type JSType = + "JS_NORMAL"| "JS_STRING"| "JS_NUMBER"; + + /** OptionRetention enum. */ + type OptionRetention = + "RETENTION_UNKNOWN"| "RETENTION_RUNTIME"| "RETENTION_SOURCE"; + + /** OptionTargetType enum. */ + type OptionTargetType = + "TARGET_TYPE_UNKNOWN"| "TARGET_TYPE_FILE"| "TARGET_TYPE_EXTENSION_RANGE"| "TARGET_TYPE_MESSAGE"| "TARGET_TYPE_FIELD"| "TARGET_TYPE_ONEOF"| "TARGET_TYPE_ENUM"| "TARGET_TYPE_ENUM_ENTRY"| "TARGET_TYPE_SERVICE"| "TARGET_TYPE_METHOD"; + + /** Properties of an EditionDefault. */ + interface IEditionDefault { + + /** EditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** EditionDefault value */ + value?: (string|null); + } + + /** Represents an EditionDefault. */ + class EditionDefault implements IEditionDefault { + + /** + * Constructs a new EditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FieldOptions.IEditionDefault); + + /** EditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** EditionDefault value. */ + public value: string; + + /** + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.EditionDefault; + + /** + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * @param message EditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions.EditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an OneofOptions. */ + interface IOneofOptions { + + /** OneofOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an OneofOptions. */ + class OneofOptions implements IOneofOptions { + + /** + * Constructs a new OneofOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofOptions); + + /** OneofOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @param message OneofOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumOptions. */ + interface IEnumOptions { + + /** EnumOptions allowAlias */ + allowAlias?: (boolean|null); + + /** EnumOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** EnumOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumOptions. */ + class EnumOptions implements IEnumOptions { + + /** + * Constructs a new EnumOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumOptions); + + /** EnumOptions allowAlias. */ + public allowAlias: boolean; + + /** EnumOptions deprecated. */ + public deprecated: boolean; + + /** EnumOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** EnumOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @param message EnumOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumValueOptions. */ + interface IEnumValueOptions { + + /** EnumValueOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumValueOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact */ + debugRedact?: (boolean|null); + + /** EnumValueOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumValueOptions. */ + class EnumValueOptions implements IEnumValueOptions { + + /** + * Constructs a new EnumValueOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueOptions); + + /** EnumValueOptions deprecated. */ + public deprecated: boolean; + + /** EnumValueOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact. */ + public debugRedact: boolean; + + /** EnumValueOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; + + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @param message EnumValueOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceOptions. */ + interface IServiceOptions { + + /** ServiceOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated */ + deprecated?: (boolean|null); + + /** ServiceOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ServiceOptions .google.api.defaultHost */ + ".google.api.defaultHost"?: (string|null); + + /** ServiceOptions .google.api.oauthScopes */ + ".google.api.oauthScopes"?: (string|null); + + /** ServiceOptions .google.api.apiVersion */ + ".google.api.apiVersion"?: (string|null); + } + + /** Represents a ServiceOptions. */ + class ServiceOptions implements IServiceOptions { + + /** + * Constructs a new ServiceOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceOptions); + + /** ServiceOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated. */ + public deprecated: boolean; + + /** ServiceOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @param message ServiceOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodOptions. */ + interface IMethodOptions { + + /** MethodOptions deprecated */ + deprecated?: (boolean|null); + + /** MethodOptions idempotencyLevel */ + idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); + + /** MethodOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MethodOptions .google.api.http */ + ".google.api.http"?: (google.api.IHttpRule|null); + + /** MethodOptions .google.api.methodSignature */ + ".google.api.methodSignature"?: (string[]|null); + + /** MethodOptions .google.longrunning.operationInfo */ + ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); + } + + /** Represents a MethodOptions. */ + class MethodOptions implements IMethodOptions { + + /** + * Constructs a new MethodOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodOptions); + + /** MethodOptions deprecated. */ + public deprecated: boolean; + + /** MethodOptions idempotencyLevel. */ + public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; + + /** MethodOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; + + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @param message MethodOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodOptions { + + /** IdempotencyLevel enum. */ + type IdempotencyLevel = + "IDEMPOTENCY_UNKNOWN"| "NO_SIDE_EFFECTS"| "IDEMPOTENT"; + } + + /** Properties of an UninterpretedOption. */ + interface IUninterpretedOption { + + /** UninterpretedOption name */ + name?: (google.protobuf.UninterpretedOption.INamePart[]|null); + + /** UninterpretedOption identifierValue */ + identifierValue?: (string|null); + + /** UninterpretedOption positiveIntValue */ + positiveIntValue?: (number|string|null); + + /** UninterpretedOption negativeIntValue */ + negativeIntValue?: (number|string|null); + + /** UninterpretedOption doubleValue */ + doubleValue?: (number|null); + + /** UninterpretedOption stringValue */ + stringValue?: (Uint8Array|null); + + /** UninterpretedOption aggregateValue */ + aggregateValue?: (string|null); + } + + /** Represents an UninterpretedOption. */ + class UninterpretedOption implements IUninterpretedOption { + + /** + * Constructs a new UninterpretedOption. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUninterpretedOption); + + /** UninterpretedOption name. */ + public name: google.protobuf.UninterpretedOption.INamePart[]; + + /** UninterpretedOption identifierValue. */ + public identifierValue: string; + + /** UninterpretedOption positiveIntValue. */ + public positiveIntValue: (number|string); + + /** UninterpretedOption negativeIntValue. */ + public negativeIntValue: (number|string); + + /** UninterpretedOption doubleValue. */ + public doubleValue: number; + + /** UninterpretedOption stringValue. */ + public stringValue: Uint8Array; + + /** UninterpretedOption aggregateValue. */ + public aggregateValue: string; + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UninterpretedOption + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @param message UninterpretedOption + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UninterpretedOption to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UninterpretedOption + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UninterpretedOption { + + /** Properties of a NamePart. */ + interface INamePart { + + /** NamePart namePart */ + namePart: string; + + /** NamePart isExtension */ + isExtension: boolean; + } + + /** Represents a NamePart. */ + class NamePart implements INamePart { + + /** + * Constructs a new NamePart. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.UninterpretedOption.INamePart); + + /** NamePart namePart. */ + public namePart: string; + + /** NamePart isExtension. */ + public isExtension: boolean; + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamePart + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @param message NamePart + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamePart to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NamePart + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a FeatureSet. */ + interface IFeatureSet { + + /** FeatureSet fieldPresence */ + fieldPresence?: (google.protobuf.FeatureSet.FieldPresence|null); + + /** FeatureSet enumType */ + enumType?: (google.protobuf.FeatureSet.EnumType|null); + + /** FeatureSet repeatedFieldEncoding */ + repeatedFieldEncoding?: (google.protobuf.FeatureSet.RepeatedFieldEncoding|null); + + /** FeatureSet utf8Validation */ + utf8Validation?: (google.protobuf.FeatureSet.Utf8Validation|null); + + /** FeatureSet messageEncoding */ + messageEncoding?: (google.protobuf.FeatureSet.MessageEncoding|null); + + /** FeatureSet jsonFormat */ + jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|null); + } + + /** Represents a FeatureSet. */ + class FeatureSet implements IFeatureSet { + + /** + * Constructs a new FeatureSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSet); + + /** FeatureSet fieldPresence. */ + public fieldPresence: google.protobuf.FeatureSet.FieldPresence; + + /** FeatureSet enumType. */ + public enumType: google.protobuf.FeatureSet.EnumType; + + /** FeatureSet repeatedFieldEncoding. */ + public repeatedFieldEncoding: google.protobuf.FeatureSet.RepeatedFieldEncoding; + + /** FeatureSet utf8Validation. */ + public utf8Validation: google.protobuf.FeatureSet.Utf8Validation; + + /** FeatureSet messageEncoding. */ + public messageEncoding: google.protobuf.FeatureSet.MessageEncoding; + + /** FeatureSet jsonFormat. */ + public jsonFormat: google.protobuf.FeatureSet.JsonFormat; + + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet; + + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @param message FeatureSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSet { + + /** FieldPresence enum. */ + type FieldPresence = + "FIELD_PRESENCE_UNKNOWN"| "EXPLICIT"| "IMPLICIT"| "LEGACY_REQUIRED"; + + /** EnumType enum. */ + type EnumType = + "ENUM_TYPE_UNKNOWN"| "OPEN"| "CLOSED"; + + /** RepeatedFieldEncoding enum. */ + type RepeatedFieldEncoding = + "REPEATED_FIELD_ENCODING_UNKNOWN"| "PACKED"| "EXPANDED"; + + /** Utf8Validation enum. */ + type Utf8Validation = + "UTF8_VALIDATION_UNKNOWN"| "VERIFY"| "NONE"; + + /** MessageEncoding enum. */ + type MessageEncoding = + "MESSAGE_ENCODING_UNKNOWN"| "LENGTH_PREFIXED"| "DELIMITED"; + + /** JsonFormat enum. */ + type JsonFormat = + "JSON_FORMAT_UNKNOWN"| "ALLOW"| "LEGACY_BEST_EFFORT"; + } + + /** Properties of a FeatureSetDefaults. */ + interface IFeatureSetDefaults { + + /** FeatureSetDefaults defaults */ + defaults?: (google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]|null); + + /** FeatureSetDefaults minimumEdition */ + minimumEdition?: (google.protobuf.Edition|null); + + /** FeatureSetDefaults maximumEdition */ + maximumEdition?: (google.protobuf.Edition|null); + } + + /** Represents a FeatureSetDefaults. */ + class FeatureSetDefaults implements IFeatureSetDefaults { + + /** + * Constructs a new FeatureSetDefaults. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSetDefaults); + + /** FeatureSetDefaults defaults. */ + public defaults: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]; + + /** FeatureSetDefaults minimumEdition. */ + public minimumEdition: google.protobuf.Edition; + + /** FeatureSetDefaults maximumEdition. */ + public maximumEdition: google.protobuf.Edition; + + /** + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetDefaults + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults; + + /** + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @param message FeatureSetDefaults + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetDefaults to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetDefaults + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSetDefaults { + + /** Properties of a FeatureSetEditionDefault. */ + interface IFeatureSetEditionDefault { + + /** FeatureSetEditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** FeatureSetEditionDefault features */ + features?: (google.protobuf.IFeatureSet|null); + } + + /** Represents a FeatureSetEditionDefault. */ + class FeatureSetEditionDefault implements IFeatureSetEditionDefault { + + /** + * Constructs a new FeatureSetEditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault); + + /** FeatureSetEditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** FeatureSetEditionDefault features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetEditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault; + + /** + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * @param message FeatureSetEditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetEditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetEditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a SourceCodeInfo. */ + interface ISourceCodeInfo { + + /** SourceCodeInfo location */ + location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); + } + + /** Represents a SourceCodeInfo. */ + class SourceCodeInfo implements ISourceCodeInfo { + + /** + * Constructs a new SourceCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ISourceCodeInfo); + + /** SourceCodeInfo location. */ + public location: google.protobuf.SourceCodeInfo.ILocation[]; + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @param message SourceCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace SourceCodeInfo { + + /** Properties of a Location. */ + interface ILocation { + + /** Location path */ + path?: (number[]|null); + + /** Location span */ + span?: (number[]|null); + + /** Location leadingComments */ + leadingComments?: (string|null); + + /** Location trailingComments */ + trailingComments?: (string|null); + + /** Location leadingDetachedComments */ + leadingDetachedComments?: (string[]|null); + } + + /** Represents a Location. */ + class Location implements ILocation { + + /** + * Constructs a new Location. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); + + /** Location path. */ + public path: number[]; + + /** Location span. */ + public span: number[]; + + /** Location leadingComments. */ + public leadingComments: string; + + /** Location trailingComments. */ + public trailingComments: string; + + /** Location leadingDetachedComments. */ + public leadingDetachedComments: string[]; + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Location + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @param message Location + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Location to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Location + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a GeneratedCodeInfo. */ + interface IGeneratedCodeInfo { + + /** GeneratedCodeInfo annotation */ + annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); + } + + /** Represents a GeneratedCodeInfo. */ + class GeneratedCodeInfo implements IGeneratedCodeInfo { + + /** + * Constructs a new GeneratedCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IGeneratedCodeInfo); + + /** GeneratedCodeInfo annotation. */ + public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; + + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GeneratedCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; + + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @param message GeneratedCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GeneratedCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace GeneratedCodeInfo { + + /** Properties of an Annotation. */ + interface IAnnotation { + + /** Annotation path */ + path?: (number[]|null); + + /** Annotation sourceFile */ + sourceFile?: (string|null); + + /** Annotation begin */ + begin?: (number|null); + + /** Annotation end */ + end?: (number|null); + + /** Annotation semantic */ + semantic?: (google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null); + } + + /** Represents an Annotation. */ + class Annotation implements IAnnotation { + + /** + * Constructs a new Annotation. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); + + /** Annotation path. */ + public path: number[]; + + /** Annotation sourceFile. */ + public sourceFile: string; + + /** Annotation begin. */ + public begin: number; + + /** Annotation end. */ + public end: number; + + /** Annotation semantic. */ + public semantic: google.protobuf.GeneratedCodeInfo.Annotation.Semantic; + + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Annotation + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @param message Annotation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Annotation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Annotation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Annotation { + + /** Semantic enum. */ + type Semantic = + "NONE"| "SET"| "ALIAS"; + } + } + + /** Properties of a Timestamp. */ + interface ITimestamp { + + /** Timestamp seconds */ + seconds?: (number|string|null); + + /** Timestamp nanos */ + nanos?: (number|null); + } + + /** Represents a Timestamp. */ + class Timestamp implements ITimestamp { + + /** + * Constructs a new Timestamp. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ITimestamp); + + /** Timestamp seconds. */ + public seconds: (number|string); + + /** Timestamp nanos. */ + public nanos: number; + + /** + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Timestamp + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; + + /** + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * @param message Timestamp + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Timestamp to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Timestamp + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Duration. */ + interface IDuration { + + /** Duration seconds */ + seconds?: (number|string|null); + + /** Duration nanos */ + nanos?: (number|null); + } + + /** Represents a Duration. */ + class Duration implements IDuration { + + /** + * Constructs a new Duration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDuration); + + /** Duration seconds. */ + public seconds: (number|string); + + /** Duration nanos. */ + public nanos: number; + + /** + * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Duration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; + + /** + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @param message Duration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Duration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Duration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Any. */ + interface IAny { + + /** Any type_url */ + type_url?: (string|null); + + /** Any value */ + value?: (Uint8Array|null); + } + + /** Represents an Any. */ + class Any implements IAny { + + /** + * Constructs a new Any. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IAny); + + /** Any type_url. */ + public type_url: string; + + /** Any value. */ + public value: Uint8Array; + + /** + * Creates an Any message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Any + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Any; + + /** + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @param message Any + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Any to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Any + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Empty. */ + interface IEmpty { + } + + /** Represents an Empty. */ + class Empty implements IEmpty { + + /** + * Constructs a new Empty. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEmpty); + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Empty + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @param message Empty + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Empty to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Empty + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldMask. */ + interface IFieldMask { + + /** FieldMask paths */ + paths?: (string[]|null); + } + + /** Represents a FieldMask. */ + class FieldMask implements IFieldMask { + + /** + * Constructs a new FieldMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldMask); + + /** FieldMask paths. */ + public paths: string[]; + + /** + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldMask + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; + + /** + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @param message FieldMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Struct. */ + interface IStruct { + + /** Struct fields */ + fields?: ({ [k: string]: google.protobuf.IValue }|null); + } + + /** Represents a Struct. */ + class Struct implements IStruct { + + /** + * Constructs a new Struct. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStruct); + + /** Struct fields. */ + public fields: { [k: string]: google.protobuf.IValue }; + + /** + * Creates a Struct message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Struct + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; + + /** + * Creates a plain object from a Struct message. Also converts values to other types if specified. + * @param message Struct + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Struct to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Struct + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Value. */ + interface IValue { + + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue */ + numberValue?: (number|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value boolValue */ + boolValue?: (boolean|null); + + /** Value structValue */ + structValue?: (google.protobuf.IStruct|null); + + /** Value listValue */ + listValue?: (google.protobuf.IListValue|null); + } + + /** Represents a Value. */ + class Value implements IValue { + + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IValue); + + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue. */ + public numberValue?: (number|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value boolValue. */ + public boolValue?: (boolean|null); + + /** Value structValue. */ + public structValue?: (google.protobuf.IStruct|null); + + /** Value listValue. */ + public listValue?: (google.protobuf.IListValue|null); + + /** Value kind. */ + public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Value; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** NullValue enum. */ + type NullValue = + "NULL_VALUE"; + + /** Properties of a ListValue. */ + interface IListValue { + + /** ListValue values */ + values?: (google.protobuf.IValue[]|null); + } + + /** Represents a ListValue. */ + class ListValue implements IListValue { + + /** + * Constructs a new ListValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IListValue); + + /** ListValue values. */ + public values: google.protobuf.IValue[]; + + /** + * Creates a ListValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; + + /** + * Creates a plain object from a ListValue message. Also converts values to other types if specified. + * @param message ListValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DoubleValue. */ + interface IDoubleValue { + + /** DoubleValue value */ + value?: (number|null); + } + + /** Represents a DoubleValue. */ + class DoubleValue implements IDoubleValue { + + /** + * Constructs a new DoubleValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDoubleValue); + + /** DoubleValue value. */ + public value: number; + + /** + * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DoubleValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DoubleValue; + + /** + * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. + * @param message DoubleValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DoubleValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DoubleValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DoubleValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FloatValue. */ + interface IFloatValue { + + /** FloatValue value */ + value?: (number|null); + } + + /** Represents a FloatValue. */ + class FloatValue implements IFloatValue { + + /** + * Constructs a new FloatValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFloatValue); + + /** FloatValue value. */ + public value: number; + + /** + * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FloatValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FloatValue; + + /** + * Creates a plain object from a FloatValue message. Also converts values to other types if specified. + * @param message FloatValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FloatValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FloatValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FloatValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int64Value. */ + interface IInt64Value { + + /** Int64Value value */ + value?: (number|string|null); + } + + /** Represents an Int64Value. */ + class Int64Value implements IInt64Value { + + /** + * Constructs a new Int64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt64Value); + + /** Int64Value value. */ + public value: (number|string); + + /** + * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int64Value; + + /** + * Creates a plain object from an Int64Value message. Also converts values to other types if specified. + * @param message Int64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt64Value. */ + interface IUInt64Value { + + /** UInt64Value value */ + value?: (number|string|null); + } + + /** Represents a UInt64Value. */ + class UInt64Value implements IUInt64Value { + + /** + * Constructs a new UInt64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt64Value); + + /** UInt64Value value. */ + public value: (number|string); + + /** + * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt64Value; + + /** + * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. + * @param message UInt64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int32Value. */ + interface IInt32Value { + + /** Int32Value value */ + value?: (number|null); + } + + /** Represents an Int32Value. */ + class Int32Value implements IInt32Value { + + /** + * Constructs a new Int32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt32Value); + + /** Int32Value value. */ + public value: number; + + /** + * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int32Value; + + /** + * Creates a plain object from an Int32Value message. Also converts values to other types if specified. + * @param message Int32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt32Value. */ + interface IUInt32Value { + + /** UInt32Value value */ + value?: (number|null); + } + + /** Represents a UInt32Value. */ + class UInt32Value implements IUInt32Value { + + /** + * Constructs a new UInt32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt32Value); + + /** UInt32Value value. */ + public value: number; + + /** + * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt32Value; + + /** + * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. + * @param message UInt32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BoolValue. */ + interface IBoolValue { + + /** BoolValue value */ + value?: (boolean|null); + } + + /** Represents a BoolValue. */ + class BoolValue implements IBoolValue { + + /** + * Constructs a new BoolValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBoolValue); + + /** BoolValue value. */ + public value: boolean; + + /** + * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BoolValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BoolValue; + + /** + * Creates a plain object from a BoolValue message. Also converts values to other types if specified. + * @param message BoolValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BoolValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BoolValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BoolValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StringValue. */ + interface IStringValue { + + /** StringValue value */ + value?: (string|null); + } + + /** Represents a StringValue. */ + class StringValue implements IStringValue { + + /** + * Constructs a new StringValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStringValue); + + /** StringValue value. */ + public value: string; + + /** + * Creates a StringValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StringValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.StringValue; + + /** + * Creates a plain object from a StringValue message. Also converts values to other types if specified. + * @param message StringValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.StringValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StringValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StringValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BytesValue. */ + interface IBytesValue { + + /** BytesValue value */ + value?: (Uint8Array|null); + } + + /** Represents a BytesValue. */ + class BytesValue implements IBytesValue { + + /** + * Constructs a new BytesValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBytesValue); + + /** BytesValue value. */ + public value: Uint8Array; + + /** + * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BytesValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BytesValue; + + /** + * Creates a plain object from a BytesValue message. Also converts values to other types if specified. + * @param message BytesValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BytesValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BytesValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BytesValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace type. */ + namespace type { + + /** DayOfWeek enum. */ + type DayOfWeek = + "DAY_OF_WEEK_UNSPECIFIED"| "MONDAY"| "TUESDAY"| "WEDNESDAY"| "THURSDAY"| "FRIDAY"| "SATURDAY"| "SUNDAY"; + + /** Properties of a LatLng. */ + interface ILatLng { + + /** LatLng latitude */ + latitude?: (number|null); + + /** LatLng longitude */ + longitude?: (number|null); + } + + /** Represents a LatLng. */ + class LatLng implements ILatLng { + + /** + * Constructs a new LatLng. + * @param [properties] Properties to set + */ + constructor(properties?: google.type.ILatLng); + + /** LatLng latitude. */ + public latitude: number; + + /** LatLng longitude. */ + public longitude: number; + + /** + * Creates a LatLng message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LatLng + */ + public static fromObject(object: { [k: string]: any }): google.type.LatLng; + + /** + * Creates a plain object from a LatLng message. Also converts values to other types if specified. + * @param message LatLng + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.type.LatLng, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LatLng to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LatLng + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace longrunning. */ + namespace longrunning { + + /** Represents an Operations */ + class Operations extends $protobuf.rpc.Service { + + /** + * Constructs a new Operations service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListOperationsResponse + */ + public listOperations(request: google.longrunning.IListOperationsRequest, callback: google.longrunning.Operations.ListOperationsCallback): void; + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @returns Promise + */ + public listOperations(request: google.longrunning.IListOperationsRequest): Promise; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public getOperation(request: google.longrunning.IGetOperationRequest, callback: google.longrunning.Operations.GetOperationCallback): void; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @returns Promise + */ + public getOperation(request: google.longrunning.IGetOperationRequest): Promise; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest, callback: google.longrunning.Operations.DeleteOperationCallback): void; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @returns Promise + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest): Promise; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest, callback: google.longrunning.Operations.CancelOperationCallback): void; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @returns Promise + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest): Promise; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest, callback: google.longrunning.Operations.WaitOperationCallback): void; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @returns Promise + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest): Promise; + } + + namespace Operations { + + /** + * Callback as used by {@link google.longrunning.Operations#listOperations}. + * @param error Error, if any + * @param [response] ListOperationsResponse + */ + type ListOperationsCallback = (error: (Error|null), response?: google.longrunning.ListOperationsResponse) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#getOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type GetOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#deleteOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#cancelOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type CancelOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#waitOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type WaitOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + } + + /** Properties of an Operation. */ + interface IOperation { + + /** Operation name */ + name?: (string|null); + + /** Operation metadata */ + metadata?: (google.protobuf.IAny|null); + + /** Operation done */ + done?: (boolean|null); + + /** Operation error */ + error?: (google.rpc.IStatus|null); + + /** Operation response */ + response?: (google.protobuf.IAny|null); + } + + /** Represents an Operation. */ + class Operation implements IOperation { + + /** + * Constructs a new Operation. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperation); + + /** Operation name. */ + public name: string; + + /** Operation metadata. */ + public metadata?: (google.protobuf.IAny|null); + + /** Operation done. */ + public done: boolean; + + /** Operation error. */ + public error?: (google.rpc.IStatus|null); + + /** Operation response. */ + public response?: (google.protobuf.IAny|null); + + /** Operation result. */ + public result?: ("error"|"response"); + + /** + * Creates an Operation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Operation + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.Operation; + + /** + * Creates a plain object from an Operation message. Also converts values to other types if specified. + * @param message Operation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.Operation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Operation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Operation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetOperationRequest. */ + interface IGetOperationRequest { + + /** GetOperationRequest name */ + name?: (string|null); + } + + /** Represents a GetOperationRequest. */ + class GetOperationRequest implements IGetOperationRequest { + + /** + * Constructs a new GetOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IGetOperationRequest); + + /** GetOperationRequest name. */ + public name: string; + + /** + * Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.GetOperationRequest; + + /** + * Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified. + * @param message GetOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.GetOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsRequest. */ + interface IListOperationsRequest { + + /** ListOperationsRequest name */ + name?: (string|null); + + /** ListOperationsRequest filter */ + filter?: (string|null); + + /** ListOperationsRequest pageSize */ + pageSize?: (number|null); + + /** ListOperationsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListOperationsRequest. */ + class ListOperationsRequest implements IListOperationsRequest { + + /** + * Constructs a new ListOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsRequest); + + /** ListOperationsRequest name. */ + public name: string; + + /** ListOperationsRequest filter. */ + public filter: string; + + /** ListOperationsRequest pageSize. */ + public pageSize: number; + + /** ListOperationsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsRequest; + + /** + * Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified. + * @param message ListOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsResponse. */ + interface IListOperationsResponse { + + /** ListOperationsResponse operations */ + operations?: (google.longrunning.IOperation[]|null); + + /** ListOperationsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListOperationsResponse. */ + class ListOperationsResponse implements IListOperationsResponse { + + /** + * Constructs a new ListOperationsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsResponse); + + /** ListOperationsResponse operations. */ + public operations: google.longrunning.IOperation[]; + + /** ListOperationsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsResponse + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsResponse; + + /** + * Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified. + * @param message ListOperationsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CancelOperationRequest. */ + interface ICancelOperationRequest { + + /** CancelOperationRequest name */ + name?: (string|null); + } + + /** Represents a CancelOperationRequest. */ + class CancelOperationRequest implements ICancelOperationRequest { + + /** + * Constructs a new CancelOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.ICancelOperationRequest); + + /** CancelOperationRequest name. */ + public name: string; + + /** + * Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CancelOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.CancelOperationRequest; + + /** + * Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified. + * @param message CancelOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.CancelOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CancelOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CancelOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteOperationRequest. */ + interface IDeleteOperationRequest { + + /** DeleteOperationRequest name */ + name?: (string|null); + } + + /** Represents a DeleteOperationRequest. */ + class DeleteOperationRequest implements IDeleteOperationRequest { + + /** + * Constructs a new DeleteOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IDeleteOperationRequest); + + /** DeleteOperationRequest name. */ + public name: string; + + /** + * Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.DeleteOperationRequest; + + /** + * Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified. + * @param message DeleteOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.DeleteOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WaitOperationRequest. */ + interface IWaitOperationRequest { + + /** WaitOperationRequest name */ + name?: (string|null); + + /** WaitOperationRequest timeout */ + timeout?: (google.protobuf.IDuration|null); + } + + /** Represents a WaitOperationRequest. */ + class WaitOperationRequest implements IWaitOperationRequest { + + /** + * Constructs a new WaitOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IWaitOperationRequest); + + /** WaitOperationRequest name. */ + public name: string; + + /** WaitOperationRequest timeout. */ + public timeout?: (google.protobuf.IDuration|null); + + /** + * Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WaitOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.WaitOperationRequest; + + /** + * Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified. + * @param message WaitOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.WaitOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WaitOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WaitOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an OperationInfo. */ + interface IOperationInfo { + + /** OperationInfo responseType */ + responseType?: (string|null); + + /** OperationInfo metadataType */ + metadataType?: (string|null); + } + + /** Represents an OperationInfo. */ + class OperationInfo implements IOperationInfo { + + /** + * Constructs a new OperationInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperationInfo); + + /** OperationInfo responseType. */ + public responseType: string; + + /** OperationInfo metadataType. */ + public metadataType: string; + + /** + * Creates an OperationInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OperationInfo + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.OperationInfo; + + /** + * Creates a plain object from an OperationInfo message. Also converts values to other types if specified. + * @param message OperationInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.OperationInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OperationInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OperationInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace rpc. */ + namespace rpc { + + /** Properties of a Status. */ + interface IStatus { + + /** Status code */ + code?: (number|null); + + /** Status message */ + message?: (string|null); + + /** Status details */ + details?: (google.protobuf.IAny[]|null); + } + + /** Represents a Status. */ + class Status implements IStatus { + + /** + * Constructs a new Status. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IStatus); + + /** Status code. */ + public code: number; + + /** Status message. */ + public message: string; + + /** Status details. */ + public details: google.protobuf.IAny[]; + + /** + * Creates a Status message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Status + */ + public static fromObject(object: { [k: string]: any }): google.rpc.Status; + + /** + * Creates a plain object from a Status message. Also converts values to other types if specified. + * @param message Status + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Status to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Status + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } +} diff --git a/node_modules/@google-cloud/firestore/types/protos/firestore_v1_proto_api.d.ts b/node_modules/@google-cloud/firestore/types/protos/firestore_v1_proto_api.d.ts new file mode 100644 index 0000000..c9c149e --- /dev/null +++ b/node_modules/@google-cloud/firestore/types/protos/firestore_v1_proto_api.d.ts @@ -0,0 +1,10576 @@ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as $protobuf from "protobufjs"; +/** Namespace firestore. */ +export namespace firestore { + + /** Properties of a BundledQuery. */ + interface IBundledQuery { + + /** BundledQuery parent */ + parent?: (string|null); + + /** BundledQuery structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** BundledQuery limitType */ + limitType?: (firestore.BundledQuery.LimitType|null); + } + + /** Represents a BundledQuery. */ + class BundledQuery implements IBundledQuery { + + /** + * Constructs a new BundledQuery. + * @param [properties] Properties to set + */ + constructor(properties?: firestore.IBundledQuery); + + /** BundledQuery parent. */ + public parent: string; + + /** BundledQuery structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** BundledQuery limitType. */ + public limitType: firestore.BundledQuery.LimitType; + + /** BundledQuery queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a BundledQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BundledQuery + */ + public static fromObject(object: { [k: string]: any }): firestore.BundledQuery; + + /** + * Creates a plain object from a BundledQuery message. Also converts values to other types if specified. + * @param message BundledQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: firestore.BundledQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BundledQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BundledQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace BundledQuery { + + /** LimitType enum. */ + type LimitType = + "FIRST"| "LAST"; + } + + /** Properties of a NamedQuery. */ + interface INamedQuery { + + /** NamedQuery name */ + name?: (string|null); + + /** NamedQuery bundledQuery */ + bundledQuery?: (firestore.IBundledQuery|null); + + /** NamedQuery readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a NamedQuery. */ + class NamedQuery implements INamedQuery { + + /** + * Constructs a new NamedQuery. + * @param [properties] Properties to set + */ + constructor(properties?: firestore.INamedQuery); + + /** NamedQuery name. */ + public name: string; + + /** NamedQuery bundledQuery. */ + public bundledQuery?: (firestore.IBundledQuery|null); + + /** NamedQuery readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a NamedQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamedQuery + */ + public static fromObject(object: { [k: string]: any }): firestore.NamedQuery; + + /** + * Creates a plain object from a NamedQuery message. Also converts values to other types if specified. + * @param message NamedQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: firestore.NamedQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamedQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NamedQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BundledDocumentMetadata. */ + interface IBundledDocumentMetadata { + + /** BundledDocumentMetadata name */ + name?: (string|null); + + /** BundledDocumentMetadata readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** BundledDocumentMetadata exists */ + exists?: (boolean|null); + + /** BundledDocumentMetadata queries */ + queries?: (string[]|null); + } + + /** Represents a BundledDocumentMetadata. */ + class BundledDocumentMetadata implements IBundledDocumentMetadata { + + /** + * Constructs a new BundledDocumentMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: firestore.IBundledDocumentMetadata); + + /** BundledDocumentMetadata name. */ + public name: string; + + /** BundledDocumentMetadata readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BundledDocumentMetadata exists. */ + public exists: boolean; + + /** BundledDocumentMetadata queries. */ + public queries: string[]; + + /** + * Creates a BundledDocumentMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BundledDocumentMetadata + */ + public static fromObject(object: { [k: string]: any }): firestore.BundledDocumentMetadata; + + /** + * Creates a plain object from a BundledDocumentMetadata message. Also converts values to other types if specified. + * @param message BundledDocumentMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: firestore.BundledDocumentMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BundledDocumentMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BundledDocumentMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BundleMetadata. */ + interface IBundleMetadata { + + /** BundleMetadata id */ + id?: (string|null); + + /** BundleMetadata createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** BundleMetadata version */ + version?: (number|null); + + /** BundleMetadata totalDocuments */ + totalDocuments?: (number|null); + + /** BundleMetadata totalBytes */ + totalBytes?: (number|string|null); + } + + /** Represents a BundleMetadata. */ + class BundleMetadata implements IBundleMetadata { + + /** + * Constructs a new BundleMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: firestore.IBundleMetadata); + + /** BundleMetadata id. */ + public id: string; + + /** BundleMetadata createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** BundleMetadata version. */ + public version: number; + + /** BundleMetadata totalDocuments. */ + public totalDocuments: number; + + /** BundleMetadata totalBytes. */ + public totalBytes: (number|string); + + /** + * Creates a BundleMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BundleMetadata + */ + public static fromObject(object: { [k: string]: any }): firestore.BundleMetadata; + + /** + * Creates a plain object from a BundleMetadata message. Also converts values to other types if specified. + * @param message BundleMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: firestore.BundleMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BundleMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BundleMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BundleElement. */ + interface IBundleElement { + + /** BundleElement metadata */ + metadata?: (firestore.IBundleMetadata|null); + + /** BundleElement namedQuery */ + namedQuery?: (firestore.INamedQuery|null); + + /** BundleElement documentMetadata */ + documentMetadata?: (firestore.IBundledDocumentMetadata|null); + + /** BundleElement document */ + document?: (google.firestore.v1.IDocument|null); + } + + /** Represents a BundleElement. */ + class BundleElement implements IBundleElement { + + /** + * Constructs a new BundleElement. + * @param [properties] Properties to set + */ + constructor(properties?: firestore.IBundleElement); + + /** BundleElement metadata. */ + public metadata?: (firestore.IBundleMetadata|null); + + /** BundleElement namedQuery. */ + public namedQuery?: (firestore.INamedQuery|null); + + /** BundleElement documentMetadata. */ + public documentMetadata?: (firestore.IBundledDocumentMetadata|null); + + /** BundleElement document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** BundleElement elementType. */ + public elementType?: ("metadata"|"namedQuery"|"documentMetadata"|"document"); + + /** + * Creates a BundleElement message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BundleElement + */ + public static fromObject(object: { [k: string]: any }): firestore.BundleElement; + + /** + * Creates a plain object from a BundleElement message. Also converts values to other types if specified. + * @param message BundleElement + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: firestore.BundleElement, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BundleElement to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BundleElement + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } +} + +/** Namespace google. */ +export namespace google { + + /** Namespace firestore. */ + namespace firestore { + + /** Namespace v1. */ + namespace v1 { + + /** Properties of an AggregationResult. */ + interface IAggregationResult { + + /** AggregationResult aggregateFields */ + aggregateFields?: ({ [k: string]: google.firestore.v1.IValue }|null); + } + + /** Represents an AggregationResult. */ + class AggregationResult implements IAggregationResult { + + /** + * Constructs a new AggregationResult. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IAggregationResult); + + /** AggregationResult aggregateFields. */ + public aggregateFields: { [k: string]: google.firestore.v1.IValue }; + + /** + * Creates an AggregationResult message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AggregationResult + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.AggregationResult; + + /** + * Creates a plain object from an AggregationResult message. Also converts values to other types if specified. + * @param message AggregationResult + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.AggregationResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AggregationResult to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AggregationResult + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Document. */ + interface IDocument { + + /** Document name */ + name?: (string|null); + + /** Document fields */ + fields?: ({ [k: string]: google.firestore.v1.IValue }|null); + + /** Document createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** Document updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a Document. */ + class Document implements IDocument { + + /** + * Constructs a new Document. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocument); + + /** Document name. */ + public name: string; + + /** Document fields. */ + public fields: { [k: string]: google.firestore.v1.IValue }; + + /** Document createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** Document updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a Document message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Document + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Document; + + /** + * Creates a plain object from a Document message. Also converts values to other types if specified. + * @param message Document + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Document, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Document to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Document + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Value. */ + interface IValue { + + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); + + /** Value booleanValue */ + booleanValue?: (boolean|null); + + /** Value integerValue */ + integerValue?: (number|string|null); + + /** Value doubleValue */ + doubleValue?: (number|null); + + /** Value timestampValue */ + timestampValue?: (google.protobuf.ITimestamp|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value bytesValue */ + bytesValue?: (Uint8Array|null); + + /** Value referenceValue */ + referenceValue?: (string|null); + + /** Value geoPointValue */ + geoPointValue?: (google.type.ILatLng|null); + + /** Value arrayValue */ + arrayValue?: (google.firestore.v1.IArrayValue|null); + + /** Value mapValue */ + mapValue?: (google.firestore.v1.IMapValue|null); + } + + /** Represents a Value. */ + class Value implements IValue { + + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IValue); + + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); + + /** Value booleanValue. */ + public booleanValue?: (boolean|null); + + /** Value integerValue. */ + public integerValue?: (number|string|null); + + /** Value doubleValue. */ + public doubleValue?: (number|null); + + /** Value timestampValue. */ + public timestampValue?: (google.protobuf.ITimestamp|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value bytesValue. */ + public bytesValue?: (Uint8Array|null); + + /** Value referenceValue. */ + public referenceValue?: (string|null); + + /** Value geoPointValue. */ + public geoPointValue?: (google.type.ILatLng|null); + + /** Value arrayValue. */ + public arrayValue?: (google.firestore.v1.IArrayValue|null); + + /** Value mapValue. */ + public mapValue?: (google.firestore.v1.IMapValue|null); + + /** Value valueType. */ + public valueType?: ("nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Value; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ArrayValue. */ + interface IArrayValue { + + /** ArrayValue values */ + values?: (google.firestore.v1.IValue[]|null); + } + + /** Represents an ArrayValue. */ + class ArrayValue implements IArrayValue { + + /** + * Constructs a new ArrayValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IArrayValue); + + /** ArrayValue values. */ + public values: google.firestore.v1.IValue[]; + + /** + * Creates an ArrayValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ArrayValue + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ArrayValue; + + /** + * Creates a plain object from an ArrayValue message. Also converts values to other types if specified. + * @param message ArrayValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ArrayValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ArrayValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ArrayValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MapValue. */ + interface IMapValue { + + /** MapValue fields */ + fields?: ({ [k: string]: google.firestore.v1.IValue }|null); + } + + /** Represents a MapValue. */ + class MapValue implements IMapValue { + + /** + * Constructs a new MapValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IMapValue); + + /** MapValue fields. */ + public fields: { [k: string]: google.firestore.v1.IValue }; + + /** + * Creates a MapValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MapValue + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.MapValue; + + /** + * Creates a plain object from a MapValue message. Also converts values to other types if specified. + * @param message MapValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.MapValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MapValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MapValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BitSequence. */ + interface IBitSequence { + + /** BitSequence bitmap */ + bitmap?: (Uint8Array|null); + + /** BitSequence padding */ + padding?: (number|null); + } + + /** Represents a BitSequence. */ + class BitSequence implements IBitSequence { + + /** + * Constructs a new BitSequence. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBitSequence); + + /** BitSequence bitmap. */ + public bitmap: Uint8Array; + + /** BitSequence padding. */ + public padding: number; + + /** + * Creates a BitSequence message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BitSequence + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BitSequence; + + /** + * Creates a plain object from a BitSequence message. Also converts values to other types if specified. + * @param message BitSequence + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BitSequence, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BitSequence to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BitSequence + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BloomFilter. */ + interface IBloomFilter { + + /** BloomFilter bits */ + bits?: (google.firestore.v1.IBitSequence|null); + + /** BloomFilter hashCount */ + hashCount?: (number|null); + } + + /** Represents a BloomFilter. */ + class BloomFilter implements IBloomFilter { + + /** + * Constructs a new BloomFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBloomFilter); + + /** BloomFilter bits. */ + public bits?: (google.firestore.v1.IBitSequence|null); + + /** BloomFilter hashCount. */ + public hashCount: number; + + /** + * Creates a BloomFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BloomFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BloomFilter; + + /** + * Creates a plain object from a BloomFilter message. Also converts values to other types if specified. + * @param message BloomFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BloomFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BloomFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BloomFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentMask. */ + interface IDocumentMask { + + /** DocumentMask fieldPaths */ + fieldPaths?: (string[]|null); + } + + /** Represents a DocumentMask. */ + class DocumentMask implements IDocumentMask { + + /** + * Constructs a new DocumentMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentMask); + + /** DocumentMask fieldPaths. */ + public fieldPaths: string[]; + + /** + * Creates a DocumentMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentMask + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentMask; + + /** + * Creates a plain object from a DocumentMask message. Also converts values to other types if specified. + * @param message DocumentMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Precondition. */ + interface IPrecondition { + + /** Precondition exists */ + exists?: (boolean|null); + + /** Precondition updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a Precondition. */ + class Precondition implements IPrecondition { + + /** + * Constructs a new Precondition. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPrecondition); + + /** Precondition exists. */ + public exists?: (boolean|null); + + /** Precondition updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** Precondition conditionType. */ + public conditionType?: ("exists"|"updateTime"); + + /** + * Creates a Precondition message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Precondition + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Precondition; + + /** + * Creates a plain object from a Precondition message. Also converts values to other types if specified. + * @param message Precondition + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Precondition, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Precondition to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Precondition + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a TransactionOptions. */ + interface ITransactionOptions { + + /** TransactionOptions readOnly */ + readOnly?: (google.firestore.v1.TransactionOptions.IReadOnly|null); + + /** TransactionOptions readWrite */ + readWrite?: (google.firestore.v1.TransactionOptions.IReadWrite|null); + } + + /** Represents a TransactionOptions. */ + class TransactionOptions implements ITransactionOptions { + + /** + * Constructs a new TransactionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ITransactionOptions); + + /** TransactionOptions readOnly. */ + public readOnly?: (google.firestore.v1.TransactionOptions.IReadOnly|null); + + /** TransactionOptions readWrite. */ + public readWrite?: (google.firestore.v1.TransactionOptions.IReadWrite|null); + + /** TransactionOptions mode. */ + public mode?: ("readOnly"|"readWrite"); + + /** + * Creates a TransactionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TransactionOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions; + + /** + * Creates a plain object from a TransactionOptions message. Also converts values to other types if specified. + * @param message TransactionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.TransactionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TransactionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TransactionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TransactionOptions { + + /** Properties of a ReadWrite. */ + interface IReadWrite { + + /** ReadWrite retryTransaction */ + retryTransaction?: (Uint8Array|null); + } + + /** Represents a ReadWrite. */ + class ReadWrite implements IReadWrite { + + /** + * Constructs a new ReadWrite. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.TransactionOptions.IReadWrite); + + /** ReadWrite retryTransaction. */ + public retryTransaction: Uint8Array; + + /** + * Creates a ReadWrite message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadWrite + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions.ReadWrite; + + /** + * Creates a plain object from a ReadWrite message. Also converts values to other types if specified. + * @param message ReadWrite + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.TransactionOptions.ReadWrite, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadWrite to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadWrite + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReadOnly. */ + interface IReadOnly { + + /** ReadOnly readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a ReadOnly. */ + class ReadOnly implements IReadOnly { + + /** + * Constructs a new ReadOnly. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.TransactionOptions.IReadOnly); + + /** ReadOnly readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ReadOnly consistencySelector. */ + public consistencySelector?: "readTime"; + + /** + * Creates a ReadOnly message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadOnly + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions.ReadOnly; + + /** + * Creates a plain object from a ReadOnly message. Also converts values to other types if specified. + * @param message ReadOnly + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.TransactionOptions.ReadOnly, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadOnly to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadOnly + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Represents a Firestore */ + class Firestore extends $protobuf.rpc.Service { + + /** + * Constructs a new Firestore service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls GetDocument. + * @param request GetDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public getDocument(request: google.firestore.v1.IGetDocumentRequest, callback: google.firestore.v1.Firestore.GetDocumentCallback): void; + + /** + * Calls GetDocument. + * @param request GetDocumentRequest message or plain object + * @returns Promise + */ + public getDocument(request: google.firestore.v1.IGetDocumentRequest): Promise; + + /** + * Calls ListDocuments. + * @param request ListDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListDocumentsResponse + */ + public listDocuments(request: google.firestore.v1.IListDocumentsRequest, callback: google.firestore.v1.Firestore.ListDocumentsCallback): void; + + /** + * Calls ListDocuments. + * @param request ListDocumentsRequest message or plain object + * @returns Promise + */ + public listDocuments(request: google.firestore.v1.IListDocumentsRequest): Promise; + + /** + * Calls UpdateDocument. + * @param request UpdateDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public updateDocument(request: google.firestore.v1.IUpdateDocumentRequest, callback: google.firestore.v1.Firestore.UpdateDocumentCallback): void; + + /** + * Calls UpdateDocument. + * @param request UpdateDocumentRequest message or plain object + * @returns Promise + */ + public updateDocument(request: google.firestore.v1.IUpdateDocumentRequest): Promise; + + /** + * Calls DeleteDocument. + * @param request DeleteDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteDocument(request: google.firestore.v1.IDeleteDocumentRequest, callback: google.firestore.v1.Firestore.DeleteDocumentCallback): void; + + /** + * Calls DeleteDocument. + * @param request DeleteDocumentRequest message or plain object + * @returns Promise + */ + public deleteDocument(request: google.firestore.v1.IDeleteDocumentRequest): Promise; + + /** + * Calls BatchGetDocuments. + * @param request BatchGetDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchGetDocumentsResponse + */ + public batchGetDocuments(request: google.firestore.v1.IBatchGetDocumentsRequest, callback: google.firestore.v1.Firestore.BatchGetDocumentsCallback): void; + + /** + * Calls BatchGetDocuments. + * @param request BatchGetDocumentsRequest message or plain object + * @returns Promise + */ + public batchGetDocuments(request: google.firestore.v1.IBatchGetDocumentsRequest): Promise; + + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BeginTransactionResponse + */ + public beginTransaction(request: google.firestore.v1.IBeginTransactionRequest, callback: google.firestore.v1.Firestore.BeginTransactionCallback): void; + + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @returns Promise + */ + public beginTransaction(request: google.firestore.v1.IBeginTransactionRequest): Promise; + + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @param callback Node-style callback called with the error, if any, and CommitResponse + */ + public commit(request: google.firestore.v1.ICommitRequest, callback: google.firestore.v1.Firestore.CommitCallback): void; + + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @returns Promise + */ + public commit(request: google.firestore.v1.ICommitRequest): Promise; + + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public rollback(request: google.firestore.v1.IRollbackRequest, callback: google.firestore.v1.Firestore.RollbackCallback): void; + + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @returns Promise + */ + public rollback(request: google.firestore.v1.IRollbackRequest): Promise; + + /** + * Calls RunQuery. + * @param request RunQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and RunQueryResponse + */ + public runQuery(request: google.firestore.v1.IRunQueryRequest, callback: google.firestore.v1.Firestore.RunQueryCallback): void; + + /** + * Calls RunQuery. + * @param request RunQueryRequest message or plain object + * @returns Promise + */ + public runQuery(request: google.firestore.v1.IRunQueryRequest): Promise; + + /** + * Calls RunAggregationQuery. + * @param request RunAggregationQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and RunAggregationQueryResponse + */ + public runAggregationQuery(request: google.firestore.v1.IRunAggregationQueryRequest, callback: google.firestore.v1.Firestore.RunAggregationQueryCallback): void; + + /** + * Calls RunAggregationQuery. + * @param request RunAggregationQueryRequest message or plain object + * @returns Promise + */ + public runAggregationQuery(request: google.firestore.v1.IRunAggregationQueryRequest): Promise; + + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and PartitionQueryResponse + */ + public partitionQuery(request: google.firestore.v1.IPartitionQueryRequest, callback: google.firestore.v1.Firestore.PartitionQueryCallback): void; + + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @returns Promise + */ + public partitionQuery(request: google.firestore.v1.IPartitionQueryRequest): Promise; + + /** + * Calls Write. + * @param request WriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and WriteResponse + */ + public write(request: google.firestore.v1.IWriteRequest, callback: google.firestore.v1.Firestore.WriteCallback): void; + + /** + * Calls Write. + * @param request WriteRequest message or plain object + * @returns Promise + */ + public write(request: google.firestore.v1.IWriteRequest): Promise; + + /** + * Calls Listen. + * @param request ListenRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListenResponse + */ + public listen(request: google.firestore.v1.IListenRequest, callback: google.firestore.v1.Firestore.ListenCallback): void; + + /** + * Calls Listen. + * @param request ListenRequest message or plain object + * @returns Promise + */ + public listen(request: google.firestore.v1.IListenRequest): Promise; + + /** + * Calls ListCollectionIds. + * @param request ListCollectionIdsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListCollectionIdsResponse + */ + public listCollectionIds(request: google.firestore.v1.IListCollectionIdsRequest, callback: google.firestore.v1.Firestore.ListCollectionIdsCallback): void; + + /** + * Calls ListCollectionIds. + * @param request ListCollectionIdsRequest message or plain object + * @returns Promise + */ + public listCollectionIds(request: google.firestore.v1.IListCollectionIdsRequest): Promise; + + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchWriteResponse + */ + public batchWrite(request: google.firestore.v1.IBatchWriteRequest, callback: google.firestore.v1.Firestore.BatchWriteCallback): void; + + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @returns Promise + */ + public batchWrite(request: google.firestore.v1.IBatchWriteRequest): Promise; + + /** + * Calls CreateDocument. + * @param request CreateDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public createDocument(request: google.firestore.v1.ICreateDocumentRequest, callback: google.firestore.v1.Firestore.CreateDocumentCallback): void; + + /** + * Calls CreateDocument. + * @param request CreateDocumentRequest message or plain object + * @returns Promise + */ + public createDocument(request: google.firestore.v1.ICreateDocumentRequest): Promise; + } + + namespace Firestore { + + /** + * Callback as used by {@link google.firestore.v1.Firestore#getDocument}. + * @param error Error, if any + * @param [response] Document + */ + type GetDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#listDocuments}. + * @param error Error, if any + * @param [response] ListDocumentsResponse + */ + type ListDocumentsCallback = (error: (Error|null), response?: google.firestore.v1.ListDocumentsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#updateDocument}. + * @param error Error, if any + * @param [response] Document + */ + type UpdateDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#deleteDocument}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteDocumentCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#batchGetDocuments}. + * @param error Error, if any + * @param [response] BatchGetDocumentsResponse + */ + type BatchGetDocumentsCallback = (error: (Error|null), response?: google.firestore.v1.BatchGetDocumentsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#beginTransaction}. + * @param error Error, if any + * @param [response] BeginTransactionResponse + */ + type BeginTransactionCallback = (error: (Error|null), response?: google.firestore.v1.BeginTransactionResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#commit}. + * @param error Error, if any + * @param [response] CommitResponse + */ + type CommitCallback = (error: (Error|null), response?: google.firestore.v1.CommitResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#rollback}. + * @param error Error, if any + * @param [response] Empty + */ + type RollbackCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#runQuery}. + * @param error Error, if any + * @param [response] RunQueryResponse + */ + type RunQueryCallback = (error: (Error|null), response?: google.firestore.v1.RunQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#runAggregationQuery}. + * @param error Error, if any + * @param [response] RunAggregationQueryResponse + */ + type RunAggregationQueryCallback = (error: (Error|null), response?: google.firestore.v1.RunAggregationQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#partitionQuery}. + * @param error Error, if any + * @param [response] PartitionQueryResponse + */ + type PartitionQueryCallback = (error: (Error|null), response?: google.firestore.v1.PartitionQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#write}. + * @param error Error, if any + * @param [response] WriteResponse + */ + type WriteCallback = (error: (Error|null), response?: google.firestore.v1.WriteResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#listen}. + * @param error Error, if any + * @param [response] ListenResponse + */ + type ListenCallback = (error: (Error|null), response?: google.firestore.v1.ListenResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#listCollectionIds}. + * @param error Error, if any + * @param [response] ListCollectionIdsResponse + */ + type ListCollectionIdsCallback = (error: (Error|null), response?: google.firestore.v1.ListCollectionIdsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#batchWrite}. + * @param error Error, if any + * @param [response] BatchWriteResponse + */ + type BatchWriteCallback = (error: (Error|null), response?: google.firestore.v1.BatchWriteResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#createDocument}. + * @param error Error, if any + * @param [response] Document + */ + type CreateDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + } + + /** Properties of a GetDocumentRequest. */ + interface IGetDocumentRequest { + + /** GetDocumentRequest name */ + name?: (string|null); + + /** GetDocumentRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + + /** GetDocumentRequest transaction */ + transaction?: (Uint8Array|null); + + /** GetDocumentRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a GetDocumentRequest. */ + class GetDocumentRequest implements IGetDocumentRequest { + + /** + * Constructs a new GetDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IGetDocumentRequest); + + /** GetDocumentRequest name. */ + public name: string; + + /** GetDocumentRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** GetDocumentRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** GetDocumentRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** GetDocumentRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"readTime"); + + /** + * Creates a GetDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.GetDocumentRequest; + + /** + * Creates a plain object from a GetDocumentRequest message. Also converts values to other types if specified. + * @param message GetDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.GetDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDocumentsRequest. */ + interface IListDocumentsRequest { + + /** ListDocumentsRequest parent */ + parent?: (string|null); + + /** ListDocumentsRequest collectionId */ + collectionId?: (string|null); + + /** ListDocumentsRequest pageSize */ + pageSize?: (number|null); + + /** ListDocumentsRequest pageToken */ + pageToken?: (string|null); + + /** ListDocumentsRequest orderBy */ + orderBy?: (string|null); + + /** ListDocumentsRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + + /** ListDocumentsRequest transaction */ + transaction?: (Uint8Array|null); + + /** ListDocumentsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** ListDocumentsRequest showMissing */ + showMissing?: (boolean|null); + } + + /** Represents a ListDocumentsRequest. */ + class ListDocumentsRequest implements IListDocumentsRequest { + + /** + * Constructs a new ListDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListDocumentsRequest); + + /** ListDocumentsRequest parent. */ + public parent: string; + + /** ListDocumentsRequest collectionId. */ + public collectionId: string; + + /** ListDocumentsRequest pageSize. */ + public pageSize: number; + + /** ListDocumentsRequest pageToken. */ + public pageToken: string; + + /** ListDocumentsRequest orderBy. */ + public orderBy: string; + + /** ListDocumentsRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** ListDocumentsRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** ListDocumentsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ListDocumentsRequest showMissing. */ + public showMissing: boolean; + + /** ListDocumentsRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"readTime"); + + /** + * Creates a ListDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListDocumentsRequest; + + /** + * Creates a plain object from a ListDocumentsRequest message. Also converts values to other types if specified. + * @param message ListDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDocumentsResponse. */ + interface IListDocumentsResponse { + + /** ListDocumentsResponse documents */ + documents?: (google.firestore.v1.IDocument[]|null); + + /** ListDocumentsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListDocumentsResponse. */ + class ListDocumentsResponse implements IListDocumentsResponse { + + /** + * Constructs a new ListDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListDocumentsResponse); + + /** ListDocumentsResponse documents. */ + public documents: google.firestore.v1.IDocument[]; + + /** ListDocumentsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListDocumentsResponse; + + /** + * Creates a plain object from a ListDocumentsResponse message. Also converts values to other types if specified. + * @param message ListDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDocumentRequest. */ + interface ICreateDocumentRequest { + + /** CreateDocumentRequest parent */ + parent?: (string|null); + + /** CreateDocumentRequest collectionId */ + collectionId?: (string|null); + + /** CreateDocumentRequest documentId */ + documentId?: (string|null); + + /** CreateDocumentRequest document */ + document?: (google.firestore.v1.IDocument|null); + + /** CreateDocumentRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + } + + /** Represents a CreateDocumentRequest. */ + class CreateDocumentRequest implements ICreateDocumentRequest { + + /** + * Constructs a new CreateDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICreateDocumentRequest); + + /** CreateDocumentRequest parent. */ + public parent: string; + + /** CreateDocumentRequest collectionId. */ + public collectionId: string; + + /** CreateDocumentRequest documentId. */ + public documentId: string; + + /** CreateDocumentRequest document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** CreateDocumentRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** + * Creates a CreateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.CreateDocumentRequest; + + /** + * Creates a plain object from a CreateDocumentRequest message. Also converts values to other types if specified. + * @param message CreateDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.CreateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDocumentRequest. */ + interface IUpdateDocumentRequest { + + /** UpdateDocumentRequest document */ + document?: (google.firestore.v1.IDocument|null); + + /** UpdateDocumentRequest updateMask */ + updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest currentDocument */ + currentDocument?: (google.firestore.v1.IPrecondition|null); + } + + /** Represents an UpdateDocumentRequest. */ + class UpdateDocumentRequest implements IUpdateDocumentRequest { + + /** + * Constructs a new UpdateDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IUpdateDocumentRequest); + + /** UpdateDocumentRequest document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** UpdateDocumentRequest updateMask. */ + public updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest currentDocument. */ + public currentDocument?: (google.firestore.v1.IPrecondition|null); + + /** + * Creates an UpdateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.UpdateDocumentRequest; + + /** + * Creates a plain object from an UpdateDocumentRequest message. Also converts values to other types if specified. + * @param message UpdateDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.UpdateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDocumentRequest. */ + interface IDeleteDocumentRequest { + + /** DeleteDocumentRequest name */ + name?: (string|null); + + /** DeleteDocumentRequest currentDocument */ + currentDocument?: (google.firestore.v1.IPrecondition|null); + } + + /** Represents a DeleteDocumentRequest. */ + class DeleteDocumentRequest implements IDeleteDocumentRequest { + + /** + * Constructs a new DeleteDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDeleteDocumentRequest); + + /** DeleteDocumentRequest name. */ + public name: string; + + /** DeleteDocumentRequest currentDocument. */ + public currentDocument?: (google.firestore.v1.IPrecondition|null); + + /** + * Creates a DeleteDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DeleteDocumentRequest; + + /** + * Creates a plain object from a DeleteDocumentRequest message. Also converts values to other types if specified. + * @param message DeleteDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DeleteDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchGetDocumentsRequest. */ + interface IBatchGetDocumentsRequest { + + /** BatchGetDocumentsRequest database */ + database?: (string|null); + + /** BatchGetDocumentsRequest documents */ + documents?: (string[]|null); + + /** BatchGetDocumentsRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + + /** BatchGetDocumentsRequest transaction */ + transaction?: (Uint8Array|null); + + /** BatchGetDocumentsRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** BatchGetDocumentsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BatchGetDocumentsRequest. */ + class BatchGetDocumentsRequest implements IBatchGetDocumentsRequest { + + /** + * Constructs a new BatchGetDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchGetDocumentsRequest); + + /** BatchGetDocumentsRequest database. */ + public database: string; + + /** BatchGetDocumentsRequest documents. */ + public documents: string[]; + + /** BatchGetDocumentsRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** BatchGetDocumentsRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** BatchGetDocumentsRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** BatchGetDocumentsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BatchGetDocumentsRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a BatchGetDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchGetDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchGetDocumentsRequest; + + /** + * Creates a plain object from a BatchGetDocumentsRequest message. Also converts values to other types if specified. + * @param message BatchGetDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchGetDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchGetDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchGetDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchGetDocumentsResponse. */ + interface IBatchGetDocumentsResponse { + + /** BatchGetDocumentsResponse found */ + found?: (google.firestore.v1.IDocument|null); + + /** BatchGetDocumentsResponse missing */ + missing?: (string|null); + + /** BatchGetDocumentsResponse transaction */ + transaction?: (Uint8Array|null); + + /** BatchGetDocumentsResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BatchGetDocumentsResponse. */ + class BatchGetDocumentsResponse implements IBatchGetDocumentsResponse { + + /** + * Constructs a new BatchGetDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchGetDocumentsResponse); + + /** BatchGetDocumentsResponse found. */ + public found?: (google.firestore.v1.IDocument|null); + + /** BatchGetDocumentsResponse missing. */ + public missing?: (string|null); + + /** BatchGetDocumentsResponse transaction. */ + public transaction: Uint8Array; + + /** BatchGetDocumentsResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BatchGetDocumentsResponse result. */ + public result?: ("found"|"missing"); + + /** + * Creates a BatchGetDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchGetDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchGetDocumentsResponse; + + /** + * Creates a plain object from a BatchGetDocumentsResponse message. Also converts values to other types if specified. + * @param message BatchGetDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchGetDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchGetDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchGetDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BeginTransactionRequest. */ + interface IBeginTransactionRequest { + + /** BeginTransactionRequest database */ + database?: (string|null); + + /** BeginTransactionRequest options */ + options?: (google.firestore.v1.ITransactionOptions|null); + } + + /** Represents a BeginTransactionRequest. */ + class BeginTransactionRequest implements IBeginTransactionRequest { + + /** + * Constructs a new BeginTransactionRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBeginTransactionRequest); + + /** BeginTransactionRequest database. */ + public database: string; + + /** BeginTransactionRequest options. */ + public options?: (google.firestore.v1.ITransactionOptions|null); + + /** + * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BeginTransactionRequest; + + /** + * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. + * @param message BeginTransactionRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BeginTransactionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BeginTransactionRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BeginTransactionResponse. */ + interface IBeginTransactionResponse { + + /** BeginTransactionResponse transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a BeginTransactionResponse. */ + class BeginTransactionResponse implements IBeginTransactionResponse { + + /** + * Constructs a new BeginTransactionResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBeginTransactionResponse); + + /** BeginTransactionResponse transaction. */ + public transaction: Uint8Array; + + /** + * Creates a BeginTransactionResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BeginTransactionResponse; + + /** + * Creates a plain object from a BeginTransactionResponse message. Also converts values to other types if specified. + * @param message BeginTransactionResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BeginTransactionResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BeginTransactionResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommitRequest. */ + interface ICommitRequest { + + /** CommitRequest database */ + database?: (string|null); + + /** CommitRequest writes */ + writes?: (google.firestore.v1.IWrite[]|null); + + /** CommitRequest transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a CommitRequest. */ + class CommitRequest implements ICommitRequest { + + /** + * Constructs a new CommitRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICommitRequest); + + /** CommitRequest database. */ + public database: string; + + /** CommitRequest writes. */ + public writes: google.firestore.v1.IWrite[]; + + /** CommitRequest transaction. */ + public transaction: Uint8Array; + + /** + * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.CommitRequest; + + /** + * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. + * @param message CommitRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.CommitRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommitResponse. */ + interface ICommitResponse { + + /** CommitResponse writeResults */ + writeResults?: (google.firestore.v1.IWriteResult[]|null); + + /** CommitResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a CommitResponse. */ + class CommitResponse implements ICommitResponse { + + /** + * Constructs a new CommitResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICommitResponse); + + /** CommitResponse writeResults. */ + public writeResults: google.firestore.v1.IWriteResult[]; + + /** CommitResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.CommitResponse; + + /** + * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. + * @param message CommitResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.CommitResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RollbackRequest. */ + interface IRollbackRequest { + + /** RollbackRequest database */ + database?: (string|null); + + /** RollbackRequest transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a RollbackRequest. */ + class RollbackRequest implements IRollbackRequest { + + /** + * Constructs a new RollbackRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRollbackRequest); + + /** RollbackRequest database. */ + public database: string; + + /** RollbackRequest transaction. */ + public transaction: Uint8Array; + + /** + * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RollbackRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RollbackRequest; + + /** + * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. + * @param message RollbackRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RollbackRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RollbackRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RollbackRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunQueryRequest. */ + interface IRunQueryRequest { + + /** RunQueryRequest parent */ + parent?: (string|null); + + /** RunQueryRequest structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** RunQueryRequest transaction */ + transaction?: (Uint8Array|null); + + /** RunQueryRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** RunQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryRequest explainOptions */ + explainOptions?: (google.firestore.v1.IExplainOptions|null); + } + + /** Represents a RunQueryRequest. */ + class RunQueryRequest implements IRunQueryRequest { + + /** + * Constructs a new RunQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunQueryRequest); + + /** RunQueryRequest parent. */ + public parent: string; + + /** RunQueryRequest structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** RunQueryRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** RunQueryRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** RunQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryRequest explainOptions. */ + public explainOptions?: (google.firestore.v1.IExplainOptions|null); + + /** RunQueryRequest queryType. */ + public queryType?: "structuredQuery"; + + /** RunQueryRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunQueryRequest; + + /** + * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. + * @param message RunQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunQueryResponse. */ + interface IRunQueryResponse { + + /** RunQueryResponse transaction */ + transaction?: (Uint8Array|null); + + /** RunQueryResponse document */ + document?: (google.firestore.v1.IDocument|null); + + /** RunQueryResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryResponse skippedResults */ + skippedResults?: (number|null); + + /** RunQueryResponse done */ + done?: (boolean|null); + + /** RunQueryResponse explainMetrics */ + explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + } + + /** Represents a RunQueryResponse. */ + class RunQueryResponse implements IRunQueryResponse { + + /** + * Constructs a new RunQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunQueryResponse); + + /** RunQueryResponse transaction. */ + public transaction: Uint8Array; + + /** RunQueryResponse document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** RunQueryResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryResponse skippedResults. */ + public skippedResults: number; + + /** RunQueryResponse done. */ + public done?: (boolean|null); + + /** RunQueryResponse explainMetrics. */ + public explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + + /** RunQueryResponse continuationSelector. */ + public continuationSelector?: "done"; + + /** + * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunQueryResponse; + + /** + * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. + * @param message RunQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunAggregationQueryRequest. */ + interface IRunAggregationQueryRequest { + + /** RunAggregationQueryRequest parent */ + parent?: (string|null); + + /** RunAggregationQueryRequest structuredAggregationQuery */ + structuredAggregationQuery?: (google.firestore.v1.IStructuredAggregationQuery|null); + + /** RunAggregationQueryRequest transaction */ + transaction?: (Uint8Array|null); + + /** RunAggregationQueryRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** RunAggregationQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryRequest explainOptions */ + explainOptions?: (google.firestore.v1.IExplainOptions|null); + } + + /** Represents a RunAggregationQueryRequest. */ + class RunAggregationQueryRequest implements IRunAggregationQueryRequest { + + /** + * Constructs a new RunAggregationQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunAggregationQueryRequest); + + /** RunAggregationQueryRequest parent. */ + public parent: string; + + /** RunAggregationQueryRequest structuredAggregationQuery. */ + public structuredAggregationQuery?: (google.firestore.v1.IStructuredAggregationQuery|null); + + /** RunAggregationQueryRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** RunAggregationQueryRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** RunAggregationQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryRequest explainOptions. */ + public explainOptions?: (google.firestore.v1.IExplainOptions|null); + + /** RunAggregationQueryRequest queryType. */ + public queryType?: "structuredAggregationQuery"; + + /** RunAggregationQueryRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a RunAggregationQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunAggregationQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunAggregationQueryRequest; + + /** + * Creates a plain object from a RunAggregationQueryRequest message. Also converts values to other types if specified. + * @param message RunAggregationQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunAggregationQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunAggregationQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunAggregationQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunAggregationQueryResponse. */ + interface IRunAggregationQueryResponse { + + /** RunAggregationQueryResponse result */ + result?: (google.firestore.v1.IAggregationResult|null); + + /** RunAggregationQueryResponse transaction */ + transaction?: (Uint8Array|null); + + /** RunAggregationQueryResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryResponse explainMetrics */ + explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + } + + /** Represents a RunAggregationQueryResponse. */ + class RunAggregationQueryResponse implements IRunAggregationQueryResponse { + + /** + * Constructs a new RunAggregationQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunAggregationQueryResponse); + + /** RunAggregationQueryResponse result. */ + public result?: (google.firestore.v1.IAggregationResult|null); + + /** RunAggregationQueryResponse transaction. */ + public transaction: Uint8Array; + + /** RunAggregationQueryResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryResponse explainMetrics. */ + public explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + + /** + * Creates a RunAggregationQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunAggregationQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunAggregationQueryResponse; + + /** + * Creates a plain object from a RunAggregationQueryResponse message. Also converts values to other types if specified. + * @param message RunAggregationQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunAggregationQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunAggregationQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunAggregationQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionQueryRequest. */ + interface IPartitionQueryRequest { + + /** PartitionQueryRequest parent */ + parent?: (string|null); + + /** PartitionQueryRequest structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** PartitionQueryRequest partitionCount */ + partitionCount?: (number|string|null); + + /** PartitionQueryRequest pageToken */ + pageToken?: (string|null); + + /** PartitionQueryRequest pageSize */ + pageSize?: (number|null); + + /** PartitionQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a PartitionQueryRequest. */ + class PartitionQueryRequest implements IPartitionQueryRequest { + + /** + * Constructs a new PartitionQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPartitionQueryRequest); + + /** PartitionQueryRequest parent. */ + public parent: string; + + /** PartitionQueryRequest structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** PartitionQueryRequest partitionCount. */ + public partitionCount: (number|string); + + /** PartitionQueryRequest pageToken. */ + public pageToken: string; + + /** PartitionQueryRequest pageSize. */ + public pageSize: number; + + /** PartitionQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** PartitionQueryRequest queryType. */ + public queryType?: "structuredQuery"; + + /** PartitionQueryRequest consistencySelector. */ + public consistencySelector?: "readTime"; + + /** + * Creates a PartitionQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.PartitionQueryRequest; + + /** + * Creates a plain object from a PartitionQueryRequest message. Also converts values to other types if specified. + * @param message PartitionQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.PartitionQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionQueryResponse. */ + interface IPartitionQueryResponse { + + /** PartitionQueryResponse partitions */ + partitions?: (google.firestore.v1.ICursor[]|null); + + /** PartitionQueryResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a PartitionQueryResponse. */ + class PartitionQueryResponse implements IPartitionQueryResponse { + + /** + * Constructs a new PartitionQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPartitionQueryResponse); + + /** PartitionQueryResponse partitions. */ + public partitions: google.firestore.v1.ICursor[]; + + /** PartitionQueryResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a PartitionQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.PartitionQueryResponse; + + /** + * Creates a plain object from a PartitionQueryResponse message. Also converts values to other types if specified. + * @param message PartitionQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.PartitionQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WriteRequest. */ + interface IWriteRequest { + + /** WriteRequest database */ + database?: (string|null); + + /** WriteRequest streamId */ + streamId?: (string|null); + + /** WriteRequest writes */ + writes?: (google.firestore.v1.IWrite[]|null); + + /** WriteRequest streamToken */ + streamToken?: (Uint8Array|null); + + /** WriteRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a WriteRequest. */ + class WriteRequest implements IWriteRequest { + + /** + * Constructs a new WriteRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWriteRequest); + + /** WriteRequest database. */ + public database: string; + + /** WriteRequest streamId. */ + public streamId: string; + + /** WriteRequest writes. */ + public writes: google.firestore.v1.IWrite[]; + + /** WriteRequest streamToken. */ + public streamToken: Uint8Array; + + /** WriteRequest labels. */ + public labels: { [k: string]: string }; + + /** + * Creates a WriteRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteRequest; + + /** + * Creates a plain object from a WriteRequest message. Also converts values to other types if specified. + * @param message WriteRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.WriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WriteResponse. */ + interface IWriteResponse { + + /** WriteResponse streamId */ + streamId?: (string|null); + + /** WriteResponse streamToken */ + streamToken?: (Uint8Array|null); + + /** WriteResponse writeResults */ + writeResults?: (google.firestore.v1.IWriteResult[]|null); + + /** WriteResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a WriteResponse. */ + class WriteResponse implements IWriteResponse { + + /** + * Constructs a new WriteResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWriteResponse); + + /** WriteResponse streamId. */ + public streamId: string; + + /** WriteResponse streamToken. */ + public streamToken: Uint8Array; + + /** WriteResponse writeResults. */ + public writeResults: google.firestore.v1.IWriteResult[]; + + /** WriteResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a WriteResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteResponse; + + /** + * Creates a plain object from a WriteResponse message. Also converts values to other types if specified. + * @param message WriteResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.WriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListenRequest. */ + interface IListenRequest { + + /** ListenRequest database */ + database?: (string|null); + + /** ListenRequest addTarget */ + addTarget?: (google.firestore.v1.ITarget|null); + + /** ListenRequest removeTarget */ + removeTarget?: (number|null); + + /** ListenRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a ListenRequest. */ + class ListenRequest implements IListenRequest { + + /** + * Constructs a new ListenRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListenRequest); + + /** ListenRequest database. */ + public database: string; + + /** ListenRequest addTarget. */ + public addTarget?: (google.firestore.v1.ITarget|null); + + /** ListenRequest removeTarget. */ + public removeTarget?: (number|null); + + /** ListenRequest labels. */ + public labels: { [k: string]: string }; + + /** ListenRequest targetChange. */ + public targetChange?: ("addTarget"|"removeTarget"); + + /** + * Creates a ListenRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListenRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListenRequest; + + /** + * Creates a plain object from a ListenRequest message. Also converts values to other types if specified. + * @param message ListenRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListenRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListenRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListenRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListenResponse. */ + interface IListenResponse { + + /** ListenResponse targetChange */ + targetChange?: (google.firestore.v1.ITargetChange|null); + + /** ListenResponse documentChange */ + documentChange?: (google.firestore.v1.IDocumentChange|null); + + /** ListenResponse documentDelete */ + documentDelete?: (google.firestore.v1.IDocumentDelete|null); + + /** ListenResponse documentRemove */ + documentRemove?: (google.firestore.v1.IDocumentRemove|null); + + /** ListenResponse filter */ + filter?: (google.firestore.v1.IExistenceFilter|null); + } + + /** Represents a ListenResponse. */ + class ListenResponse implements IListenResponse { + + /** + * Constructs a new ListenResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListenResponse); + + /** ListenResponse targetChange. */ + public targetChange?: (google.firestore.v1.ITargetChange|null); + + /** ListenResponse documentChange. */ + public documentChange?: (google.firestore.v1.IDocumentChange|null); + + /** ListenResponse documentDelete. */ + public documentDelete?: (google.firestore.v1.IDocumentDelete|null); + + /** ListenResponse documentRemove. */ + public documentRemove?: (google.firestore.v1.IDocumentRemove|null); + + /** ListenResponse filter. */ + public filter?: (google.firestore.v1.IExistenceFilter|null); + + /** ListenResponse responseType. */ + public responseType?: ("targetChange"|"documentChange"|"documentDelete"|"documentRemove"|"filter"); + + /** + * Creates a ListenResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListenResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListenResponse; + + /** + * Creates a plain object from a ListenResponse message. Also converts values to other types if specified. + * @param message ListenResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListenResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListenResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListenResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Target. */ + interface ITarget { + + /** Target query */ + query?: (google.firestore.v1.Target.IQueryTarget|null); + + /** Target documents */ + documents?: (google.firestore.v1.Target.IDocumentsTarget|null); + + /** Target resumeToken */ + resumeToken?: (Uint8Array|null); + + /** Target readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** Target targetId */ + targetId?: (number|null); + + /** Target once */ + once?: (boolean|null); + + /** Target expectedCount */ + expectedCount?: (google.protobuf.IInt32Value|null); + } + + /** Represents a Target. */ + class Target implements ITarget { + + /** + * Constructs a new Target. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ITarget); + + /** Target query. */ + public query?: (google.firestore.v1.Target.IQueryTarget|null); + + /** Target documents. */ + public documents?: (google.firestore.v1.Target.IDocumentsTarget|null); + + /** Target resumeToken. */ + public resumeToken?: (Uint8Array|null); + + /** Target readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** Target targetId. */ + public targetId: number; + + /** Target once. */ + public once: boolean; + + /** Target expectedCount. */ + public expectedCount?: (google.protobuf.IInt32Value|null); + + /** Target targetType. */ + public targetType?: ("query"|"documents"); + + /** Target resumeType. */ + public resumeType?: ("resumeToken"|"readTime"); + + /** + * Creates a Target message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Target + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target; + + /** + * Creates a plain object from a Target message. Also converts values to other types if specified. + * @param message Target + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Target, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Target to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Target + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Target { + + /** Properties of a DocumentsTarget. */ + interface IDocumentsTarget { + + /** DocumentsTarget documents */ + documents?: (string[]|null); + } + + /** Represents a DocumentsTarget. */ + class DocumentsTarget implements IDocumentsTarget { + + /** + * Constructs a new DocumentsTarget. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.Target.IDocumentsTarget); + + /** DocumentsTarget documents. */ + public documents: string[]; + + /** + * Creates a DocumentsTarget message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentsTarget + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target.DocumentsTarget; + + /** + * Creates a plain object from a DocumentsTarget message. Also converts values to other types if specified. + * @param message DocumentsTarget + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Target.DocumentsTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentsTarget to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentsTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a QueryTarget. */ + interface IQueryTarget { + + /** QueryTarget parent */ + parent?: (string|null); + + /** QueryTarget structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + } + + /** Represents a QueryTarget. */ + class QueryTarget implements IQueryTarget { + + /** + * Constructs a new QueryTarget. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.Target.IQueryTarget); + + /** QueryTarget parent. */ + public parent: string; + + /** QueryTarget structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** QueryTarget queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a QueryTarget message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns QueryTarget + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target.QueryTarget; + + /** + * Creates a plain object from a QueryTarget message. Also converts values to other types if specified. + * @param message QueryTarget + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Target.QueryTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this QueryTarget to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for QueryTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a TargetChange. */ + interface ITargetChange { + + /** TargetChange targetChangeType */ + targetChangeType?: (google.firestore.v1.TargetChange.TargetChangeType|null); + + /** TargetChange targetIds */ + targetIds?: (number[]|null); + + /** TargetChange cause */ + cause?: (google.rpc.IStatus|null); + + /** TargetChange resumeToken */ + resumeToken?: (Uint8Array|null); + + /** TargetChange readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a TargetChange. */ + class TargetChange implements ITargetChange { + + /** + * Constructs a new TargetChange. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ITargetChange); + + /** TargetChange targetChangeType. */ + public targetChangeType: google.firestore.v1.TargetChange.TargetChangeType; + + /** TargetChange targetIds. */ + public targetIds: number[]; + + /** TargetChange cause. */ + public cause?: (google.rpc.IStatus|null); + + /** TargetChange resumeToken. */ + public resumeToken: Uint8Array; + + /** TargetChange readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a TargetChange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TargetChange + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TargetChange; + + /** + * Creates a plain object from a TargetChange message. Also converts values to other types if specified. + * @param message TargetChange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.TargetChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TargetChange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TargetChange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TargetChange { + + /** TargetChangeType enum. */ + type TargetChangeType = + "NO_CHANGE"| "ADD"| "REMOVE"| "CURRENT"| "RESET"; + } + + /** Properties of a ListCollectionIdsRequest. */ + interface IListCollectionIdsRequest { + + /** ListCollectionIdsRequest parent */ + parent?: (string|null); + + /** ListCollectionIdsRequest pageSize */ + pageSize?: (number|null); + + /** ListCollectionIdsRequest pageToken */ + pageToken?: (string|null); + + /** ListCollectionIdsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a ListCollectionIdsRequest. */ + class ListCollectionIdsRequest implements IListCollectionIdsRequest { + + /** + * Constructs a new ListCollectionIdsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListCollectionIdsRequest); + + /** ListCollectionIdsRequest parent. */ + public parent: string; + + /** ListCollectionIdsRequest pageSize. */ + public pageSize: number; + + /** ListCollectionIdsRequest pageToken. */ + public pageToken: string; + + /** ListCollectionIdsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ListCollectionIdsRequest consistencySelector. */ + public consistencySelector?: "readTime"; + + /** + * Creates a ListCollectionIdsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCollectionIdsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListCollectionIdsRequest; + + /** + * Creates a plain object from a ListCollectionIdsRequest message. Also converts values to other types if specified. + * @param message ListCollectionIdsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListCollectionIdsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCollectionIdsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCollectionIdsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListCollectionIdsResponse. */ + interface IListCollectionIdsResponse { + + /** ListCollectionIdsResponse collectionIds */ + collectionIds?: (string[]|null); + + /** ListCollectionIdsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListCollectionIdsResponse. */ + class ListCollectionIdsResponse implements IListCollectionIdsResponse { + + /** + * Constructs a new ListCollectionIdsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListCollectionIdsResponse); + + /** ListCollectionIdsResponse collectionIds. */ + public collectionIds: string[]; + + /** ListCollectionIdsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListCollectionIdsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCollectionIdsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListCollectionIdsResponse; + + /** + * Creates a plain object from a ListCollectionIdsResponse message. Also converts values to other types if specified. + * @param message ListCollectionIdsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListCollectionIdsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCollectionIdsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCollectionIdsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchWriteRequest. */ + interface IBatchWriteRequest { + + /** BatchWriteRequest database */ + database?: (string|null); + + /** BatchWriteRequest writes */ + writes?: (google.firestore.v1.IWrite[]|null); + + /** BatchWriteRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a BatchWriteRequest. */ + class BatchWriteRequest implements IBatchWriteRequest { + + /** + * Constructs a new BatchWriteRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchWriteRequest); + + /** BatchWriteRequest database. */ + public database: string; + + /** BatchWriteRequest writes. */ + public writes: google.firestore.v1.IWrite[]; + + /** BatchWriteRequest labels. */ + public labels: { [k: string]: string }; + + /** + * Creates a BatchWriteRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchWriteRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchWriteRequest; + + /** + * Creates a plain object from a BatchWriteRequest message. Also converts values to other types if specified. + * @param message BatchWriteRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchWriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchWriteRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchWriteResponse. */ + interface IBatchWriteResponse { + + /** BatchWriteResponse writeResults */ + writeResults?: (google.firestore.v1.IWriteResult[]|null); + + /** BatchWriteResponse status */ + status?: (google.rpc.IStatus[]|null); + } + + /** Represents a BatchWriteResponse. */ + class BatchWriteResponse implements IBatchWriteResponse { + + /** + * Constructs a new BatchWriteResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchWriteResponse); + + /** BatchWriteResponse writeResults. */ + public writeResults: google.firestore.v1.IWriteResult[]; + + /** BatchWriteResponse status. */ + public status: google.rpc.IStatus[]; + + /** + * Creates a BatchWriteResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchWriteResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchWriteResponse; + + /** + * Creates a plain object from a BatchWriteResponse message. Also converts values to other types if specified. + * @param message BatchWriteResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchWriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchWriteResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StructuredQuery. */ + interface IStructuredQuery { + + /** StructuredQuery select */ + select?: (google.firestore.v1.StructuredQuery.IProjection|null); + + /** StructuredQuery from */ + from?: (google.firestore.v1.StructuredQuery.ICollectionSelector[]|null); + + /** StructuredQuery where */ + where?: (google.firestore.v1.StructuredQuery.IFilter|null); + + /** StructuredQuery orderBy */ + orderBy?: (google.firestore.v1.StructuredQuery.IOrder[]|null); + + /** StructuredQuery startAt */ + startAt?: (google.firestore.v1.ICursor|null); + + /** StructuredQuery endAt */ + endAt?: (google.firestore.v1.ICursor|null); + + /** StructuredQuery offset */ + offset?: (number|null); + + /** StructuredQuery limit */ + limit?: (google.protobuf.IInt32Value|null); + + /** StructuredQuery findNearest */ + findNearest?: (google.firestore.v1.StructuredQuery.IFindNearest|null); + } + + /** Represents a StructuredQuery. */ + class StructuredQuery implements IStructuredQuery { + + /** + * Constructs a new StructuredQuery. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IStructuredQuery); + + /** StructuredQuery select. */ + public select?: (google.firestore.v1.StructuredQuery.IProjection|null); + + /** StructuredQuery from. */ + public from: google.firestore.v1.StructuredQuery.ICollectionSelector[]; + + /** StructuredQuery where. */ + public where?: (google.firestore.v1.StructuredQuery.IFilter|null); + + /** StructuredQuery orderBy. */ + public orderBy: google.firestore.v1.StructuredQuery.IOrder[]; + + /** StructuredQuery startAt. */ + public startAt?: (google.firestore.v1.ICursor|null); + + /** StructuredQuery endAt. */ + public endAt?: (google.firestore.v1.ICursor|null); + + /** StructuredQuery offset. */ + public offset: number; + + /** StructuredQuery limit. */ + public limit?: (google.protobuf.IInt32Value|null); + + /** StructuredQuery findNearest. */ + public findNearest?: (google.firestore.v1.StructuredQuery.IFindNearest|null); + + /** + * Creates a StructuredQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StructuredQuery + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery; + + /** + * Creates a plain object from a StructuredQuery message. Also converts values to other types if specified. + * @param message StructuredQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StructuredQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StructuredQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace StructuredQuery { + + /** Properties of a CollectionSelector. */ + interface ICollectionSelector { + + /** CollectionSelector collectionId */ + collectionId?: (string|null); + + /** CollectionSelector allDescendants */ + allDescendants?: (boolean|null); + } + + /** Represents a CollectionSelector. */ + class CollectionSelector implements ICollectionSelector { + + /** + * Constructs a new CollectionSelector. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.ICollectionSelector); + + /** CollectionSelector collectionId. */ + public collectionId: string; + + /** CollectionSelector allDescendants. */ + public allDescendants: boolean; + + /** + * Creates a CollectionSelector message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CollectionSelector + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.CollectionSelector; + + /** + * Creates a plain object from a CollectionSelector message. Also converts values to other types if specified. + * @param message CollectionSelector + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.CollectionSelector, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CollectionSelector to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CollectionSelector + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Filter. */ + interface IFilter { + + /** Filter compositeFilter */ + compositeFilter?: (google.firestore.v1.StructuredQuery.ICompositeFilter|null); + + /** Filter fieldFilter */ + fieldFilter?: (google.firestore.v1.StructuredQuery.IFieldFilter|null); + + /** Filter unaryFilter */ + unaryFilter?: (google.firestore.v1.StructuredQuery.IUnaryFilter|null); + } + + /** Represents a Filter. */ + class Filter implements IFilter { + + /** + * Constructs a new Filter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFilter); + + /** Filter compositeFilter. */ + public compositeFilter?: (google.firestore.v1.StructuredQuery.ICompositeFilter|null); + + /** Filter fieldFilter. */ + public fieldFilter?: (google.firestore.v1.StructuredQuery.IFieldFilter|null); + + /** Filter unaryFilter. */ + public unaryFilter?: (google.firestore.v1.StructuredQuery.IUnaryFilter|null); + + /** Filter filterType. */ + public filterType?: ("compositeFilter"|"fieldFilter"|"unaryFilter"); + + /** + * Creates a Filter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Filter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Filter; + + /** + * Creates a plain object from a Filter message. Also converts values to other types if specified. + * @param message Filter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.Filter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Filter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Filter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CompositeFilter. */ + interface ICompositeFilter { + + /** CompositeFilter op */ + op?: (google.firestore.v1.StructuredQuery.CompositeFilter.Operator|null); + + /** CompositeFilter filters */ + filters?: (google.firestore.v1.StructuredQuery.IFilter[]|null); + } + + /** Represents a CompositeFilter. */ + class CompositeFilter implements ICompositeFilter { + + /** + * Constructs a new CompositeFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.ICompositeFilter); + + /** CompositeFilter op. */ + public op: google.firestore.v1.StructuredQuery.CompositeFilter.Operator; + + /** CompositeFilter filters. */ + public filters: google.firestore.v1.StructuredQuery.IFilter[]; + + /** + * Creates a CompositeFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CompositeFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.CompositeFilter; + + /** + * Creates a plain object from a CompositeFilter message. Also converts values to other types if specified. + * @param message CompositeFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.CompositeFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CompositeFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CompositeFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace CompositeFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "AND"| "OR"; + } + + /** Properties of a FieldFilter. */ + interface IFieldFilter { + + /** FieldFilter field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** FieldFilter op */ + op?: (google.firestore.v1.StructuredQuery.FieldFilter.Operator|null); + + /** FieldFilter value */ + value?: (google.firestore.v1.IValue|null); + } + + /** Represents a FieldFilter. */ + class FieldFilter implements IFieldFilter { + + /** + * Constructs a new FieldFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFieldFilter); + + /** FieldFilter field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** FieldFilter op. */ + public op: google.firestore.v1.StructuredQuery.FieldFilter.Operator; + + /** FieldFilter value. */ + public value?: (google.firestore.v1.IValue|null); + + /** + * Creates a FieldFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FieldFilter; + + /** + * Creates a plain object from a FieldFilter message. Also converts values to other types if specified. + * @param message FieldFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.FieldFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "LESS_THAN"| "LESS_THAN_OR_EQUAL"| "GREATER_THAN"| "GREATER_THAN_OR_EQUAL"| "EQUAL"| "NOT_EQUAL"| "ARRAY_CONTAINS"| "IN"| "ARRAY_CONTAINS_ANY"| "NOT_IN"; + } + + /** Properties of an UnaryFilter. */ + interface IUnaryFilter { + + /** UnaryFilter op */ + op?: (google.firestore.v1.StructuredQuery.UnaryFilter.Operator|null); + + /** UnaryFilter field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + } + + /** Represents an UnaryFilter. */ + class UnaryFilter implements IUnaryFilter { + + /** + * Constructs a new UnaryFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IUnaryFilter); + + /** UnaryFilter op. */ + public op: google.firestore.v1.StructuredQuery.UnaryFilter.Operator; + + /** UnaryFilter field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** UnaryFilter operandType. */ + public operandType?: "field"; + + /** + * Creates an UnaryFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UnaryFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.UnaryFilter; + + /** + * Creates a plain object from an UnaryFilter message. Also converts values to other types if specified. + * @param message UnaryFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.UnaryFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UnaryFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UnaryFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UnaryFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "IS_NAN"| "IS_NULL"| "IS_NOT_NAN"| "IS_NOT_NULL"; + } + + /** Properties of an Order. */ + interface IOrder { + + /** Order field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** Order direction */ + direction?: (google.firestore.v1.StructuredQuery.Direction|null); + } + + /** Represents an Order. */ + class Order implements IOrder { + + /** + * Constructs a new Order. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IOrder); + + /** Order field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** Order direction. */ + public direction: google.firestore.v1.StructuredQuery.Direction; + + /** + * Creates an Order message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Order + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Order; + + /** + * Creates a plain object from an Order message. Also converts values to other types if specified. + * @param message Order + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.Order, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Order to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Order + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Direction enum. */ + type Direction = + "DIRECTION_UNSPECIFIED"| "ASCENDING"| "DESCENDING"; + + /** Properties of a FieldReference. */ + interface IFieldReference { + + /** FieldReference fieldPath */ + fieldPath?: (string|null); + } + + /** Represents a FieldReference. */ + class FieldReference implements IFieldReference { + + /** + * Constructs a new FieldReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFieldReference); + + /** FieldReference fieldPath. */ + public fieldPath: string; + + /** + * Creates a FieldReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldReference + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FieldReference; + + /** + * Creates a plain object from a FieldReference message. Also converts values to other types if specified. + * @param message FieldReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.FieldReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Projection. */ + interface IProjection { + + /** Projection fields */ + fields?: (google.firestore.v1.StructuredQuery.IFieldReference[]|null); + } + + /** Represents a Projection. */ + class Projection implements IProjection { + + /** + * Constructs a new Projection. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IProjection); + + /** Projection fields. */ + public fields: google.firestore.v1.StructuredQuery.IFieldReference[]; + + /** + * Creates a Projection message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Projection + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Projection; + + /** + * Creates a plain object from a Projection message. Also converts values to other types if specified. + * @param message Projection + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.Projection, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Projection to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Projection + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FindNearest. */ + interface IFindNearest { + + /** FindNearest vectorField */ + vectorField?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** FindNearest queryVector */ + queryVector?: (google.firestore.v1.IValue|null); + + /** FindNearest distanceMeasure */ + distanceMeasure?: (google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure|null); + + /** FindNearest limit */ + limit?: (google.protobuf.IInt32Value|null); + + /** FindNearest distanceResultField */ + distanceResultField?: (string|null); + + /** FindNearest distanceThreshold */ + distanceThreshold?: (google.protobuf.IDoubleValue|null); + } + + /** Represents a FindNearest. */ + class FindNearest implements IFindNearest { + + /** + * Constructs a new FindNearest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFindNearest); + + /** FindNearest vectorField. */ + public vectorField?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** FindNearest queryVector. */ + public queryVector?: (google.firestore.v1.IValue|null); + + /** FindNearest distanceMeasure. */ + public distanceMeasure: google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure; + + /** FindNearest limit. */ + public limit?: (google.protobuf.IInt32Value|null); + + /** FindNearest distanceResultField. */ + public distanceResultField: string; + + /** FindNearest distanceThreshold. */ + public distanceThreshold?: (google.protobuf.IDoubleValue|null); + + /** + * Creates a FindNearest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FindNearest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FindNearest; + + /** + * Creates a plain object from a FindNearest message. Also converts values to other types if specified. + * @param message FindNearest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.FindNearest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FindNearest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FindNearest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FindNearest { + + /** DistanceMeasure enum. */ + type DistanceMeasure = + "DISTANCE_MEASURE_UNSPECIFIED"| "EUCLIDEAN"| "COSINE"| "DOT_PRODUCT"; + } + } + + /** Properties of a StructuredAggregationQuery. */ + interface IStructuredAggregationQuery { + + /** StructuredAggregationQuery structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** StructuredAggregationQuery aggregations */ + aggregations?: (google.firestore.v1.StructuredAggregationQuery.IAggregation[]|null); + } + + /** Represents a StructuredAggregationQuery. */ + class StructuredAggregationQuery implements IStructuredAggregationQuery { + + /** + * Constructs a new StructuredAggregationQuery. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IStructuredAggregationQuery); + + /** StructuredAggregationQuery structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** StructuredAggregationQuery aggregations. */ + public aggregations: google.firestore.v1.StructuredAggregationQuery.IAggregation[]; + + /** StructuredAggregationQuery queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a StructuredAggregationQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StructuredAggregationQuery + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery; + + /** + * Creates a plain object from a StructuredAggregationQuery message. Also converts values to other types if specified. + * @param message StructuredAggregationQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StructuredAggregationQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StructuredAggregationQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace StructuredAggregationQuery { + + /** Properties of an Aggregation. */ + interface IAggregation { + + /** Aggregation count */ + count?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null); + + /** Aggregation sum */ + sum?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null); + + /** Aggregation avg */ + avg?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null); + + /** Aggregation alias */ + alias?: (string|null); + } + + /** Represents an Aggregation. */ + class Aggregation implements IAggregation { + + /** + * Constructs a new Aggregation. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.IAggregation); + + /** Aggregation count. */ + public count?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null); + + /** Aggregation sum. */ + public sum?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null); + + /** Aggregation avg. */ + public avg?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null); + + /** Aggregation alias. */ + public alias: string; + + /** Aggregation operator. */ + public operator?: ("count"|"sum"|"avg"); + + /** + * Creates an Aggregation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Aggregation + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation; + + /** + * Creates a plain object from an Aggregation message. Also converts values to other types if specified. + * @param message Aggregation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Aggregation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Aggregation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Aggregation { + + /** Properties of a Count. */ + interface ICount { + + /** Count upTo */ + upTo?: (google.protobuf.IInt64Value|null); + } + + /** Represents a Count. */ + class Count implements ICount { + + /** + * Constructs a new Count. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount); + + /** Count upTo. */ + public upTo?: (google.protobuf.IInt64Value|null); + + /** + * Creates a Count message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Count + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Count; + + /** + * Creates a plain object from a Count message. Also converts values to other types if specified. + * @param message Count + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Count, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Count to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Count + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Sum. */ + interface ISum { + + /** Sum field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + } + + /** Represents a Sum. */ + class Sum implements ISum { + + /** + * Constructs a new Sum. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum); + + /** Sum field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** + * Creates a Sum message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Sum + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum; + + /** + * Creates a plain object from a Sum message. Also converts values to other types if specified. + * @param message Sum + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Sum to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Sum + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Avg. */ + interface IAvg { + + /** Avg field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + } + + /** Represents an Avg. */ + class Avg implements IAvg { + + /** + * Constructs a new Avg. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg); + + /** Avg field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** + * Creates an Avg message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Avg + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg; + + /** + * Creates a plain object from an Avg message. Also converts values to other types if specified. + * @param message Avg + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Avg to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Avg + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + + /** Properties of a Cursor. */ + interface ICursor { + + /** Cursor values */ + values?: (google.firestore.v1.IValue[]|null); + + /** Cursor before */ + before?: (boolean|null); + } + + /** Represents a Cursor. */ + class Cursor implements ICursor { + + /** + * Constructs a new Cursor. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICursor); + + /** Cursor values. */ + public values: google.firestore.v1.IValue[]; + + /** Cursor before. */ + public before: boolean; + + /** + * Creates a Cursor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Cursor + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Cursor; + + /** + * Creates a plain object from a Cursor message. Also converts values to other types if specified. + * @param message Cursor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Cursor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Cursor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Cursor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExplainOptions. */ + interface IExplainOptions { + + /** ExplainOptions analyze */ + analyze?: (boolean|null); + } + + /** Represents an ExplainOptions. */ + class ExplainOptions implements IExplainOptions { + + /** + * Constructs a new ExplainOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExplainOptions); + + /** ExplainOptions analyze. */ + public analyze: boolean; + + /** + * Creates an ExplainOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExplainOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExplainOptions; + + /** + * Creates a plain object from an ExplainOptions message. Also converts values to other types if specified. + * @param message ExplainOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExplainOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExplainOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExplainOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExplainMetrics. */ + interface IExplainMetrics { + + /** ExplainMetrics planSummary */ + planSummary?: (google.firestore.v1.IPlanSummary|null); + + /** ExplainMetrics executionStats */ + executionStats?: (google.firestore.v1.IExecutionStats|null); + } + + /** Represents an ExplainMetrics. */ + class ExplainMetrics implements IExplainMetrics { + + /** + * Constructs a new ExplainMetrics. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExplainMetrics); + + /** ExplainMetrics planSummary. */ + public planSummary?: (google.firestore.v1.IPlanSummary|null); + + /** ExplainMetrics executionStats. */ + public executionStats?: (google.firestore.v1.IExecutionStats|null); + + /** + * Creates an ExplainMetrics message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExplainMetrics + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExplainMetrics; + + /** + * Creates a plain object from an ExplainMetrics message. Also converts values to other types if specified. + * @param message ExplainMetrics + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExplainMetrics, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExplainMetrics to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExplainMetrics + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PlanSummary. */ + interface IPlanSummary { + + /** PlanSummary indexesUsed */ + indexesUsed?: (google.protobuf.IStruct[]|null); + } + + /** Represents a PlanSummary. */ + class PlanSummary implements IPlanSummary { + + /** + * Constructs a new PlanSummary. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPlanSummary); + + /** PlanSummary indexesUsed. */ + public indexesUsed: google.protobuf.IStruct[]; + + /** + * Creates a PlanSummary message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PlanSummary + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.PlanSummary; + + /** + * Creates a plain object from a PlanSummary message. Also converts values to other types if specified. + * @param message PlanSummary + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.PlanSummary, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PlanSummary to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PlanSummary + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExecutionStats. */ + interface IExecutionStats { + + /** ExecutionStats resultsReturned */ + resultsReturned?: (number|string|null); + + /** ExecutionStats executionDuration */ + executionDuration?: (google.protobuf.IDuration|null); + + /** ExecutionStats readOperations */ + readOperations?: (number|string|null); + + /** ExecutionStats debugStats */ + debugStats?: (google.protobuf.IStruct|null); + } + + /** Represents an ExecutionStats. */ + class ExecutionStats implements IExecutionStats { + + /** + * Constructs a new ExecutionStats. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExecutionStats); + + /** ExecutionStats resultsReturned. */ + public resultsReturned: (number|string); + + /** ExecutionStats executionDuration. */ + public executionDuration?: (google.protobuf.IDuration|null); + + /** ExecutionStats readOperations. */ + public readOperations: (number|string); + + /** ExecutionStats debugStats. */ + public debugStats?: (google.protobuf.IStruct|null); + + /** + * Creates an ExecutionStats message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExecutionStats + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExecutionStats; + + /** + * Creates a plain object from an ExecutionStats message. Also converts values to other types if specified. + * @param message ExecutionStats + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExecutionStats, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExecutionStats to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExecutionStats + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Write. */ + interface IWrite { + + /** Write update */ + update?: (google.firestore.v1.IDocument|null); + + /** Write delete */ + "delete"?: (string|null); + + /** Write transform */ + transform?: (google.firestore.v1.IDocumentTransform|null); + + /** Write updateMask */ + updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** Write updateTransforms */ + updateTransforms?: (google.firestore.v1.DocumentTransform.IFieldTransform[]|null); + + /** Write currentDocument */ + currentDocument?: (google.firestore.v1.IPrecondition|null); + } + + /** Represents a Write. */ + class Write implements IWrite { + + /** + * Constructs a new Write. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWrite); + + /** Write update. */ + public update?: (google.firestore.v1.IDocument|null); + + /** Write delete. */ + public delete?: (string|null); + + /** Write transform. */ + public transform?: (google.firestore.v1.IDocumentTransform|null); + + /** Write updateMask. */ + public updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** Write updateTransforms. */ + public updateTransforms: google.firestore.v1.DocumentTransform.IFieldTransform[]; + + /** Write currentDocument. */ + public currentDocument?: (google.firestore.v1.IPrecondition|null); + + /** Write operation. */ + public operation?: ("update"|"delete"|"transform"); + + /** + * Creates a Write message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Write + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Write; + + /** + * Creates a plain object from a Write message. Also converts values to other types if specified. + * @param message Write + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Write, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Write to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Write + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentTransform. */ + interface IDocumentTransform { + + /** DocumentTransform document */ + document?: (string|null); + + /** DocumentTransform fieldTransforms */ + fieldTransforms?: (google.firestore.v1.DocumentTransform.IFieldTransform[]|null); + } + + /** Represents a DocumentTransform. */ + class DocumentTransform implements IDocumentTransform { + + /** + * Constructs a new DocumentTransform. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentTransform); + + /** DocumentTransform document. */ + public document: string; + + /** DocumentTransform fieldTransforms. */ + public fieldTransforms: google.firestore.v1.DocumentTransform.IFieldTransform[]; + + /** + * Creates a DocumentTransform message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentTransform + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentTransform; + + /** + * Creates a plain object from a DocumentTransform message. Also converts values to other types if specified. + * @param message DocumentTransform + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentTransform to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DocumentTransform { + + /** Properties of a FieldTransform. */ + interface IFieldTransform { + + /** FieldTransform fieldPath */ + fieldPath?: (string|null); + + /** FieldTransform setToServerValue */ + setToServerValue?: (google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null); + + /** FieldTransform increment */ + increment?: (google.firestore.v1.IValue|null); + + /** FieldTransform maximum */ + maximum?: (google.firestore.v1.IValue|null); + + /** FieldTransform minimum */ + minimum?: (google.firestore.v1.IValue|null); + + /** FieldTransform appendMissingElements */ + appendMissingElements?: (google.firestore.v1.IArrayValue|null); + + /** FieldTransform removeAllFromArray */ + removeAllFromArray?: (google.firestore.v1.IArrayValue|null); + } + + /** Represents a FieldTransform. */ + class FieldTransform implements IFieldTransform { + + /** + * Constructs a new FieldTransform. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.DocumentTransform.IFieldTransform); + + /** FieldTransform fieldPath. */ + public fieldPath: string; + + /** FieldTransform setToServerValue. */ + public setToServerValue?: (google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null); + + /** FieldTransform increment. */ + public increment?: (google.firestore.v1.IValue|null); + + /** FieldTransform maximum. */ + public maximum?: (google.firestore.v1.IValue|null); + + /** FieldTransform minimum. */ + public minimum?: (google.firestore.v1.IValue|null); + + /** FieldTransform appendMissingElements. */ + public appendMissingElements?: (google.firestore.v1.IArrayValue|null); + + /** FieldTransform removeAllFromArray. */ + public removeAllFromArray?: (google.firestore.v1.IArrayValue|null); + + /** FieldTransform transformType. */ + public transformType?: ("setToServerValue"|"increment"|"maximum"|"minimum"|"appendMissingElements"|"removeAllFromArray"); + + /** + * Creates a FieldTransform message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldTransform + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentTransform.FieldTransform; + + /** + * Creates a plain object from a FieldTransform message. Also converts values to other types if specified. + * @param message FieldTransform + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentTransform.FieldTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldTransform to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldTransform { + + /** ServerValue enum. */ + type ServerValue = + "SERVER_VALUE_UNSPECIFIED"| "REQUEST_TIME"; + } + } + + /** Properties of a WriteResult. */ + interface IWriteResult { + + /** WriteResult updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** WriteResult transformResults */ + transformResults?: (google.firestore.v1.IValue[]|null); + } + + /** Represents a WriteResult. */ + class WriteResult implements IWriteResult { + + /** + * Constructs a new WriteResult. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWriteResult); + + /** WriteResult updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** WriteResult transformResults. */ + public transformResults: google.firestore.v1.IValue[]; + + /** + * Creates a WriteResult message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteResult + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteResult; + + /** + * Creates a plain object from a WriteResult message. Also converts values to other types if specified. + * @param message WriteResult + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.WriteResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteResult to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteResult + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentChange. */ + interface IDocumentChange { + + /** DocumentChange document */ + document?: (google.firestore.v1.IDocument|null); + + /** DocumentChange targetIds */ + targetIds?: (number[]|null); + + /** DocumentChange removedTargetIds */ + removedTargetIds?: (number[]|null); + } + + /** Represents a DocumentChange. */ + class DocumentChange implements IDocumentChange { + + /** + * Constructs a new DocumentChange. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentChange); + + /** DocumentChange document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** DocumentChange targetIds. */ + public targetIds: number[]; + + /** DocumentChange removedTargetIds. */ + public removedTargetIds: number[]; + + /** + * Creates a DocumentChange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentChange + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentChange; + + /** + * Creates a plain object from a DocumentChange message. Also converts values to other types if specified. + * @param message DocumentChange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentChange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentChange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentDelete. */ + interface IDocumentDelete { + + /** DocumentDelete document */ + document?: (string|null); + + /** DocumentDelete removedTargetIds */ + removedTargetIds?: (number[]|null); + + /** DocumentDelete readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a DocumentDelete. */ + class DocumentDelete implements IDocumentDelete { + + /** + * Constructs a new DocumentDelete. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentDelete); + + /** DocumentDelete document. */ + public document: string; + + /** DocumentDelete removedTargetIds. */ + public removedTargetIds: number[]; + + /** DocumentDelete readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a DocumentDelete message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentDelete + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentDelete; + + /** + * Creates a plain object from a DocumentDelete message. Also converts values to other types if specified. + * @param message DocumentDelete + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentDelete, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentDelete to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentDelete + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentRemove. */ + interface IDocumentRemove { + + /** DocumentRemove document */ + document?: (string|null); + + /** DocumentRemove removedTargetIds */ + removedTargetIds?: (number[]|null); + + /** DocumentRemove readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a DocumentRemove. */ + class DocumentRemove implements IDocumentRemove { + + /** + * Constructs a new DocumentRemove. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentRemove); + + /** DocumentRemove document. */ + public document: string; + + /** DocumentRemove removedTargetIds. */ + public removedTargetIds: number[]; + + /** DocumentRemove readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a DocumentRemove message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentRemove + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentRemove; + + /** + * Creates a plain object from a DocumentRemove message. Also converts values to other types if specified. + * @param message DocumentRemove + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentRemove, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentRemove to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentRemove + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExistenceFilter. */ + interface IExistenceFilter { + + /** ExistenceFilter targetId */ + targetId?: (number|null); + + /** ExistenceFilter count */ + count?: (number|null); + + /** ExistenceFilter unchangedNames */ + unchangedNames?: (google.firestore.v1.IBloomFilter|null); + } + + /** Represents an ExistenceFilter. */ + class ExistenceFilter implements IExistenceFilter { + + /** + * Constructs a new ExistenceFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExistenceFilter); + + /** ExistenceFilter targetId. */ + public targetId: number; + + /** ExistenceFilter count. */ + public count: number; + + /** ExistenceFilter unchangedNames. */ + public unchangedNames?: (google.firestore.v1.IBloomFilter|null); + + /** + * Creates an ExistenceFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExistenceFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExistenceFilter; + + /** + * Creates a plain object from an ExistenceFilter message. Also converts values to other types if specified. + * @param message ExistenceFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExistenceFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExistenceFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExistenceFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + + /** Namespace api. */ + namespace api { + + /** FieldBehavior enum. */ + type FieldBehavior = + "FIELD_BEHAVIOR_UNSPECIFIED"| "OPTIONAL"| "REQUIRED"| "OUTPUT_ONLY"| "INPUT_ONLY"| "IMMUTABLE"| "UNORDERED_LIST"| "NON_EMPTY_DEFAULT"| "IDENTIFIER"; + + /** Properties of a Http. */ + interface IHttp { + + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); + + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); + } + + /** Represents a Http. */ + class Http implements IHttp { + + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); + + /** Http rules. */ + public rules: google.api.IHttpRule[]; + + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Http + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a HttpRule. */ + interface IHttpRule { + + /** HttpRule selector */ + selector?: (string|null); + + /** HttpRule get */ + get?: (string|null); + + /** HttpRule put */ + put?: (string|null); + + /** HttpRule post */ + post?: (string|null); + + /** HttpRule delete */ + "delete"?: (string|null); + + /** HttpRule patch */ + patch?: (string|null); + + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body */ + body?: (string|null); + + /** HttpRule responseBody */ + responseBody?: (string|null); + + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); + } + + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { + + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); + + /** HttpRule selector. */ + public selector: string; + + /** HttpRule get. */ + public get?: (string|null); + + /** HttpRule put. */ + public put?: (string|null); + + /** HttpRule post. */ + public post?: (string|null); + + /** HttpRule delete. */ + public delete?: (string|null); + + /** HttpRule patch. */ + public patch?: (string|null); + + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body. */ + public body: string; + + /** HttpRule responseBody. */ + public responseBody: string; + + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; + + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for HttpRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { + + /** CustomHttpPattern kind */ + kind?: (string|null); + + /** CustomHttpPattern path */ + path?: (string|null); + } + + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { + + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); + + /** CustomHttpPattern kind. */ + public kind: string; + + /** CustomHttpPattern path. */ + public path: string; + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CustomHttpPattern + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommonLanguageSettings. */ + interface ICommonLanguageSettings { + + /** CommonLanguageSettings referenceDocsUri */ + referenceDocsUri?: (string|null); + + /** CommonLanguageSettings destinations */ + destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + } + + /** Represents a CommonLanguageSettings. */ + class CommonLanguageSettings implements ICommonLanguageSettings { + + /** + * Constructs a new CommonLanguageSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICommonLanguageSettings); + + /** CommonLanguageSettings referenceDocsUri. */ + public referenceDocsUri: string; + + /** CommonLanguageSettings destinations. */ + public destinations: google.api.ClientLibraryDestination[]; + + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommonLanguageSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CommonLanguageSettings; + + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @param message CommonLanguageSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CommonLanguageSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommonLanguageSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommonLanguageSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ClientLibrarySettings. */ + interface IClientLibrarySettings { + + /** ClientLibrarySettings version */ + version?: (string|null); + + /** ClientLibrarySettings launchStage */ + launchStage?: (google.api.LaunchStage|null); + + /** ClientLibrarySettings restNumericEnums */ + restNumericEnums?: (boolean|null); + + /** ClientLibrarySettings javaSettings */ + javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings */ + cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings */ + phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings */ + pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings */ + nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings */ + dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings */ + rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings */ + goSettings?: (google.api.IGoSettings|null); + } + + /** Represents a ClientLibrarySettings. */ + class ClientLibrarySettings implements IClientLibrarySettings { + + /** + * Constructs a new ClientLibrarySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IClientLibrarySettings); + + /** ClientLibrarySettings version. */ + public version: string; + + /** ClientLibrarySettings launchStage. */ + public launchStage: google.api.LaunchStage; + + /** ClientLibrarySettings restNumericEnums. */ + public restNumericEnums: boolean; + + /** ClientLibrarySettings javaSettings. */ + public javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings. */ + public cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings. */ + public phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings. */ + public pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings. */ + public nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings. */ + public dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings. */ + public rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings. */ + public goSettings?: (google.api.IGoSettings|null); + + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ClientLibrarySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.ClientLibrarySettings; + + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @param message ClientLibrarySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ClientLibrarySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ClientLibrarySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ClientLibrarySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Publishing. */ + interface IPublishing { + + /** Publishing methodSettings */ + methodSettings?: (google.api.IMethodSettings[]|null); + + /** Publishing newIssueUri */ + newIssueUri?: (string|null); + + /** Publishing documentationUri */ + documentationUri?: (string|null); + + /** Publishing apiShortName */ + apiShortName?: (string|null); + + /** Publishing githubLabel */ + githubLabel?: (string|null); + + /** Publishing codeownerGithubTeams */ + codeownerGithubTeams?: (string[]|null); + + /** Publishing docTagPrefix */ + docTagPrefix?: (string|null); + + /** Publishing organization */ + organization?: (google.api.ClientLibraryOrganization|null); + + /** Publishing librarySettings */ + librarySettings?: (google.api.IClientLibrarySettings[]|null); + + /** Publishing protoReferenceDocumentationUri */ + protoReferenceDocumentationUri?: (string|null); + + /** Publishing restReferenceDocumentationUri */ + restReferenceDocumentationUri?: (string|null); + } + + /** Represents a Publishing. */ + class Publishing implements IPublishing { + + /** + * Constructs a new Publishing. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPublishing); + + /** Publishing methodSettings. */ + public methodSettings: google.api.IMethodSettings[]; + + /** Publishing newIssueUri. */ + public newIssueUri: string; + + /** Publishing documentationUri. */ + public documentationUri: string; + + /** Publishing apiShortName. */ + public apiShortName: string; + + /** Publishing githubLabel. */ + public githubLabel: string; + + /** Publishing codeownerGithubTeams. */ + public codeownerGithubTeams: string[]; + + /** Publishing docTagPrefix. */ + public docTagPrefix: string; + + /** Publishing organization. */ + public organization: google.api.ClientLibraryOrganization; + + /** Publishing librarySettings. */ + public librarySettings: google.api.IClientLibrarySettings[]; + + /** Publishing protoReferenceDocumentationUri. */ + public protoReferenceDocumentationUri: string; + + /** Publishing restReferenceDocumentationUri. */ + public restReferenceDocumentationUri: string; + + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Publishing + */ + public static fromObject(object: { [k: string]: any }): google.api.Publishing; + + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @param message Publishing + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Publishing, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Publishing to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Publishing + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a JavaSettings. */ + interface IJavaSettings { + + /** JavaSettings libraryPackage */ + libraryPackage?: (string|null); + + /** JavaSettings serviceClassNames */ + serviceClassNames?: ({ [k: string]: string }|null); + + /** JavaSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a JavaSettings. */ + class JavaSettings implements IJavaSettings { + + /** + * Constructs a new JavaSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IJavaSettings); + + /** JavaSettings libraryPackage. */ + public libraryPackage: string; + + /** JavaSettings serviceClassNames. */ + public serviceClassNames: { [k: string]: string }; + + /** JavaSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns JavaSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.JavaSettings; + + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @param message JavaSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.JavaSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this JavaSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for JavaSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CppSettings. */ + interface ICppSettings { + + /** CppSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a CppSettings. */ + class CppSettings implements ICppSettings { + + /** + * Constructs a new CppSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICppSettings); + + /** CppSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CppSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CppSettings; + + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @param message CppSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CppSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CppSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CppSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PhpSettings. */ + interface IPhpSettings { + + /** PhpSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a PhpSettings. */ + class PhpSettings implements IPhpSettings { + + /** + * Constructs a new PhpSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPhpSettings); + + /** PhpSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PhpSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PhpSettings; + + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @param message PhpSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PhpSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PhpSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PhpSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PythonSettings. */ + interface IPythonSettings { + + /** PythonSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + } + + /** Represents a PythonSettings. */ + class PythonSettings implements IPythonSettings { + + /** + * Constructs a new PythonSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPythonSettings); + + /** PythonSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PythonSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings; + + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @param message PythonSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PythonSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PythonSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace PythonSettings { + + /** Properties of an ExperimentalFeatures. */ + interface IExperimentalFeatures { + + /** ExperimentalFeatures restAsyncIoEnabled */ + restAsyncIoEnabled?: (boolean|null); + + /** ExperimentalFeatures protobufPythonicTypesEnabled */ + protobufPythonicTypesEnabled?: (boolean|null); + } + + /** Represents an ExperimentalFeatures. */ + class ExperimentalFeatures implements IExperimentalFeatures { + + /** + * Constructs a new ExperimentalFeatures. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.PythonSettings.IExperimentalFeatures); + + /** ExperimentalFeatures restAsyncIoEnabled. */ + public restAsyncIoEnabled: boolean; + + /** ExperimentalFeatures protobufPythonicTypesEnabled. */ + public protobufPythonicTypesEnabled: boolean; + + /** + * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExperimentalFeatures + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. + * @param message ExperimentalFeatures + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings.ExperimentalFeatures, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExperimentalFeatures to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExperimentalFeatures + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a NodeSettings. */ + interface INodeSettings { + + /** NodeSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a NodeSettings. */ + class NodeSettings implements INodeSettings { + + /** + * Constructs a new NodeSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.INodeSettings); + + /** NodeSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NodeSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.NodeSettings; + + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @param message NodeSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.NodeSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NodeSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NodeSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DotnetSettings. */ + interface IDotnetSettings { + + /** DotnetSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + + /** DotnetSettings renamedResources */ + renamedResources?: ({ [k: string]: string }|null); + + /** DotnetSettings ignoredResources */ + ignoredResources?: (string[]|null); + + /** DotnetSettings forcedNamespaceAliases */ + forcedNamespaceAliases?: (string[]|null); + + /** DotnetSettings handwrittenSignatures */ + handwrittenSignatures?: (string[]|null); + } + + /** Represents a DotnetSettings. */ + class DotnetSettings implements IDotnetSettings { + + /** + * Constructs a new DotnetSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IDotnetSettings); + + /** DotnetSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** DotnetSettings renamedResources. */ + public renamedResources: { [k: string]: string }; + + /** DotnetSettings ignoredResources. */ + public ignoredResources: string[]; + + /** DotnetSettings forcedNamespaceAliases. */ + public forcedNamespaceAliases: string[]; + + /** DotnetSettings handwrittenSignatures. */ + public handwrittenSignatures: string[]; + + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DotnetSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.DotnetSettings; + + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @param message DotnetSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.DotnetSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DotnetSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DotnetSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RubySettings. */ + interface IRubySettings { + + /** RubySettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a RubySettings. */ + class RubySettings implements IRubySettings { + + /** + * Constructs a new RubySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRubySettings); + + /** RubySettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RubySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.RubySettings; + + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @param message RubySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RubySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RubySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RubySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GoSettings. */ + interface IGoSettings { + + /** GoSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + } + + /** Represents a GoSettings. */ + class GoSettings implements IGoSettings { + + /** + * Constructs a new GoSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IGoSettings); + + /** GoSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GoSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.GoSettings; + + /** + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @param message GoSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.GoSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GoSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GoSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodSettings. */ + interface IMethodSettings { + + /** MethodSettings selector */ + selector?: (string|null); + + /** MethodSettings longRunning */ + longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields */ + autoPopulatedFields?: (string[]|null); + } + + /** Represents a MethodSettings. */ + class MethodSettings implements IMethodSettings { + + /** + * Constructs a new MethodSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IMethodSettings); + + /** MethodSettings selector. */ + public selector: string; + + /** MethodSettings longRunning. */ + public longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields. */ + public autoPopulatedFields: string[]; + + /** + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings; + + /** + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @param message MethodSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodSettings { + + /** Properties of a LongRunning. */ + interface ILongRunning { + + /** LongRunning initialPollDelay */ + initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier */ + pollDelayMultiplier?: (number|null); + + /** LongRunning maxPollDelay */ + maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout */ + totalPollTimeout?: (google.protobuf.IDuration|null); + } + + /** Represents a LongRunning. */ + class LongRunning implements ILongRunning { + + /** + * Constructs a new LongRunning. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.MethodSettings.ILongRunning); + + /** LongRunning initialPollDelay. */ + public initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier. */ + public pollDelayMultiplier: number; + + /** LongRunning maxPollDelay. */ + public maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout. */ + public totalPollTimeout?: (google.protobuf.IDuration|null); + + /** + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LongRunning + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings.LongRunning; + + /** + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @param message LongRunning + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings.LongRunning, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LongRunning to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LongRunning + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** ClientLibraryOrganization enum. */ + type ClientLibraryOrganization = + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"| "CLOUD"| "ADS"| "PHOTOS"| "STREET_VIEW"| "SHOPPING"| "GEO"| "GENERATIVE_AI"; + + /** ClientLibraryDestination enum. */ + type ClientLibraryDestination = + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"| "GITHUB"| "PACKAGE_MANAGER"; + + /** Properties of a SelectiveGapicGeneration. */ + interface ISelectiveGapicGeneration { + + /** SelectiveGapicGeneration methods */ + methods?: (string[]|null); + + /** SelectiveGapicGeneration generateOmittedAsInternal */ + generateOmittedAsInternal?: (boolean|null); + } + + /** Represents a SelectiveGapicGeneration. */ + class SelectiveGapicGeneration implements ISelectiveGapicGeneration { + + /** + * Constructs a new SelectiveGapicGeneration. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ISelectiveGapicGeneration); + + /** SelectiveGapicGeneration methods. */ + public methods: string[]; + + /** SelectiveGapicGeneration generateOmittedAsInternal. */ + public generateOmittedAsInternal: boolean; + + /** + * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SelectiveGapicGeneration + */ + public static fromObject(object: { [k: string]: any }): google.api.SelectiveGapicGeneration; + + /** + * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. + * @param message SelectiveGapicGeneration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.SelectiveGapicGeneration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SelectiveGapicGeneration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SelectiveGapicGeneration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** LaunchStage enum. */ + type LaunchStage = + "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; + + /** Properties of a ResourceDescriptor. */ + interface IResourceDescriptor { + + /** ResourceDescriptor type */ + type?: (string|null); + + /** ResourceDescriptor pattern */ + pattern?: (string[]|null); + + /** ResourceDescriptor nameField */ + nameField?: (string|null); + + /** ResourceDescriptor history */ + history?: (google.api.ResourceDescriptor.History|null); + + /** ResourceDescriptor plural */ + plural?: (string|null); + + /** ResourceDescriptor singular */ + singular?: (string|null); + + /** ResourceDescriptor style */ + style?: (google.api.ResourceDescriptor.Style[]|null); + } + + /** Represents a ResourceDescriptor. */ + class ResourceDescriptor implements IResourceDescriptor { + + /** + * Constructs a new ResourceDescriptor. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceDescriptor); + + /** ResourceDescriptor type. */ + public type: string; + + /** ResourceDescriptor pattern. */ + public pattern: string[]; + + /** ResourceDescriptor nameField. */ + public nameField: string; + + /** ResourceDescriptor history. */ + public history: google.api.ResourceDescriptor.History; + + /** ResourceDescriptor plural. */ + public plural: string; + + /** ResourceDescriptor singular. */ + public singular: string; + + /** ResourceDescriptor style. */ + public style: google.api.ResourceDescriptor.Style[]; + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceDescriptor + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @param message ResourceDescriptor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceDescriptor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceDescriptor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ResourceDescriptor { + + /** History enum. */ + type History = + "HISTORY_UNSPECIFIED"| "ORIGINALLY_SINGLE_PATTERN"| "FUTURE_MULTI_PATTERN"; + + /** Style enum. */ + type Style = + "STYLE_UNSPECIFIED"| "DECLARATIVE_FRIENDLY"; + } + + /** Properties of a ResourceReference. */ + interface IResourceReference { + + /** ResourceReference type */ + type?: (string|null); + + /** ResourceReference childType */ + childType?: (string|null); + } + + /** Represents a ResourceReference. */ + class ResourceReference implements IResourceReference { + + /** + * Constructs a new ResourceReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceReference); + + /** ResourceReference type. */ + public type: string; + + /** ResourceReference childType. */ + public childType: string; + + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceReference + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; + + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @param message ResourceReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace protobuf. */ + namespace protobuf { + + /** Properties of a FileDescriptorSet. */ + interface IFileDescriptorSet { + + /** FileDescriptorSet file */ + file?: (google.protobuf.IFileDescriptorProto[]|null); + } + + /** Represents a FileDescriptorSet. */ + class FileDescriptorSet implements IFileDescriptorSet { + + /** + * Constructs a new FileDescriptorSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorSet); + + /** FileDescriptorSet file. */ + public file: google.protobuf.IFileDescriptorProto[]; + + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; + + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @param message FileDescriptorSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Edition enum. */ + type Edition = + "EDITION_UNKNOWN"| "EDITION_PROTO2"| "EDITION_PROTO3"| "EDITION_2023"| "EDITION_2024"| "EDITION_1_TEST_ONLY"| "EDITION_2_TEST_ONLY"| "EDITION_99997_TEST_ONLY"| "EDITION_99998_TEST_ONLY"| "EDITION_99999_TEST_ONLY"| "EDITION_MAX"; + + /** Properties of a FileDescriptorProto. */ + interface IFileDescriptorProto { + + /** FileDescriptorProto name */ + name?: (string|null); + + /** FileDescriptorProto package */ + "package"?: (string|null); + + /** FileDescriptorProto dependency */ + dependency?: (string[]|null); + + /** FileDescriptorProto publicDependency */ + publicDependency?: (number[]|null); + + /** FileDescriptorProto weakDependency */ + weakDependency?: (number[]|null); + + /** FileDescriptorProto messageType */ + messageType?: (google.protobuf.IDescriptorProto[]|null); + + /** FileDescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** FileDescriptorProto service */ + service?: (google.protobuf.IServiceDescriptorProto[]|null); + + /** FileDescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** FileDescriptorProto options */ + options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo */ + sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax */ + syntax?: (string|null); + + /** FileDescriptorProto edition */ + edition?: (google.protobuf.Edition|null); + } + + /** Represents a FileDescriptorProto. */ + class FileDescriptorProto implements IFileDescriptorProto { + + /** + * Constructs a new FileDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorProto); + + /** FileDescriptorProto name. */ + public name: string; + + /** FileDescriptorProto package. */ + public package: string; + + /** FileDescriptorProto dependency. */ + public dependency: string[]; + + /** FileDescriptorProto publicDependency. */ + public publicDependency: number[]; + + /** FileDescriptorProto weakDependency. */ + public weakDependency: number[]; + + /** FileDescriptorProto messageType. */ + public messageType: google.protobuf.IDescriptorProto[]; + + /** FileDescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** FileDescriptorProto service. */ + public service: google.protobuf.IServiceDescriptorProto[]; + + /** FileDescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** FileDescriptorProto options. */ + public options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo. */ + public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax. */ + public syntax: string; + + /** FileDescriptorProto edition. */ + public edition: google.protobuf.Edition; + + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; + + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @param message FileDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DescriptorProto. */ + interface IDescriptorProto { + + /** DescriptorProto name */ + name?: (string|null); + + /** DescriptorProto field */ + field?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto nestedType */ + nestedType?: (google.protobuf.IDescriptorProto[]|null); + + /** DescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** DescriptorProto extensionRange */ + extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); + + /** DescriptorProto oneofDecl */ + oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); + + /** DescriptorProto options */ + options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange */ + reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); + + /** DescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents a DescriptorProto. */ + class DescriptorProto implements IDescriptorProto { + + /** + * Constructs a new DescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDescriptorProto); + + /** DescriptorProto name. */ + public name: string; + + /** DescriptorProto field. */ + public field: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto nestedType. */ + public nestedType: google.protobuf.IDescriptorProto[]; + + /** DescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** DescriptorProto extensionRange. */ + public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; + + /** DescriptorProto oneofDecl. */ + public oneofDecl: google.protobuf.IOneofDescriptorProto[]; + + /** DescriptorProto options. */ + public options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange. */ + public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; + + /** DescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; + + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @param message DescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DescriptorProto { + + /** Properties of an ExtensionRange. */ + interface IExtensionRange { + + /** ExtensionRange start */ + start?: (number|null); + + /** ExtensionRange end */ + end?: (number|null); + + /** ExtensionRange options */ + options?: (google.protobuf.IExtensionRangeOptions|null); + } + + /** Represents an ExtensionRange. */ + class ExtensionRange implements IExtensionRange { + + /** + * Constructs a new ExtensionRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); + + /** ExtensionRange start. */ + public start: number; + + /** ExtensionRange end. */ + public end: number; + + /** ExtensionRange options. */ + public options?: (google.protobuf.IExtensionRangeOptions|null); + + /** + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @param message ExtensionRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReservedRange. */ + interface IReservedRange { + + /** ReservedRange start */ + start?: (number|null); + + /** ReservedRange end */ + end?: (number|null); + } + + /** Represents a ReservedRange. */ + class ReservedRange implements IReservedRange { + + /** + * Constructs a new ReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); + + /** ReservedRange start. */ + public start: number; + + /** ReservedRange end. */ + public end: number; + + /** + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @param message ReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an ExtensionRangeOptions. */ + interface IExtensionRangeOptions { + + /** ExtensionRangeOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ExtensionRangeOptions declaration */ + declaration?: (google.protobuf.ExtensionRangeOptions.IDeclaration[]|null); + + /** ExtensionRangeOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification */ + verification?: (google.protobuf.ExtensionRangeOptions.VerificationState|null); + } + + /** Represents an ExtensionRangeOptions. */ + class ExtensionRangeOptions implements IExtensionRangeOptions { + + /** + * Constructs a new ExtensionRangeOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IExtensionRangeOptions); + + /** ExtensionRangeOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** ExtensionRangeOptions declaration. */ + public declaration: google.protobuf.ExtensionRangeOptions.IDeclaration[]; + + /** ExtensionRangeOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification. */ + public verification: google.protobuf.ExtensionRangeOptions.VerificationState; + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRangeOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @param message ExtensionRangeOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRangeOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ExtensionRangeOptions { + + /** Properties of a Declaration. */ + interface IDeclaration { + + /** Declaration number */ + number?: (number|null); + + /** Declaration fullName */ + fullName?: (string|null); + + /** Declaration type */ + type?: (string|null); + + /** Declaration reserved */ + reserved?: (boolean|null); + + /** Declaration repeated */ + repeated?: (boolean|null); + } + + /** Represents a Declaration. */ + class Declaration implements IDeclaration { + + /** + * Constructs a new Declaration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ExtensionRangeOptions.IDeclaration); + + /** Declaration number. */ + public number: number; + + /** Declaration fullName. */ + public fullName: string; + + /** Declaration type. */ + public type: string; + + /** Declaration reserved. */ + public reserved: boolean; + + /** Declaration repeated. */ + public repeated: boolean; + + /** + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Declaration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions.Declaration; + + /** + * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * @param message Declaration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions.Declaration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Declaration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Declaration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** VerificationState enum. */ + type VerificationState = + "DECLARATION"| "UNVERIFIED"; + } + + /** Properties of a FieldDescriptorProto. */ + interface IFieldDescriptorProto { + + /** FieldDescriptorProto name */ + name?: (string|null); + + /** FieldDescriptorProto number */ + number?: (number|null); + + /** FieldDescriptorProto label */ + label?: (google.protobuf.FieldDescriptorProto.Label|null); + + /** FieldDescriptorProto type */ + type?: (google.protobuf.FieldDescriptorProto.Type|null); + + /** FieldDescriptorProto typeName */ + typeName?: (string|null); + + /** FieldDescriptorProto extendee */ + extendee?: (string|null); + + /** FieldDescriptorProto defaultValue */ + defaultValue?: (string|null); + + /** FieldDescriptorProto oneofIndex */ + oneofIndex?: (number|null); + + /** FieldDescriptorProto jsonName */ + jsonName?: (string|null); + + /** FieldDescriptorProto options */ + options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional */ + proto3Optional?: (boolean|null); + } + + /** Represents a FieldDescriptorProto. */ + class FieldDescriptorProto implements IFieldDescriptorProto { + + /** + * Constructs a new FieldDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldDescriptorProto); + + /** FieldDescriptorProto name. */ + public name: string; + + /** FieldDescriptorProto number. */ + public number: number; + + /** FieldDescriptorProto label. */ + public label: google.protobuf.FieldDescriptorProto.Label; + + /** FieldDescriptorProto type. */ + public type: google.protobuf.FieldDescriptorProto.Type; + + /** FieldDescriptorProto typeName. */ + public typeName: string; + + /** FieldDescriptorProto extendee. */ + public extendee: string; + + /** FieldDescriptorProto defaultValue. */ + public defaultValue: string; + + /** FieldDescriptorProto oneofIndex. */ + public oneofIndex: number; + + /** FieldDescriptorProto jsonName. */ + public jsonName: string; + + /** FieldDescriptorProto options. */ + public options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional. */ + public proto3Optional: boolean; + + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @param message FieldDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldDescriptorProto { + + /** Type enum. */ + type Type = + "TYPE_DOUBLE"| "TYPE_FLOAT"| "TYPE_INT64"| "TYPE_UINT64"| "TYPE_INT32"| "TYPE_FIXED64"| "TYPE_FIXED32"| "TYPE_BOOL"| "TYPE_STRING"| "TYPE_GROUP"| "TYPE_MESSAGE"| "TYPE_BYTES"| "TYPE_UINT32"| "TYPE_ENUM"| "TYPE_SFIXED32"| "TYPE_SFIXED64"| "TYPE_SINT32"| "TYPE_SINT64"; + + /** Label enum. */ + type Label = + "LABEL_OPTIONAL"| "LABEL_REPEATED"| "LABEL_REQUIRED"; + } + + /** Properties of an OneofDescriptorProto. */ + interface IOneofDescriptorProto { + + /** OneofDescriptorProto name */ + name?: (string|null); + + /** OneofDescriptorProto options */ + options?: (google.protobuf.IOneofOptions|null); + } + + /** Represents an OneofDescriptorProto. */ + class OneofDescriptorProto implements IOneofDescriptorProto { + + /** + * Constructs a new OneofDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofDescriptorProto); + + /** OneofDescriptorProto name. */ + public name: string; + + /** OneofDescriptorProto options. */ + public options?: (google.protobuf.IOneofOptions|null); + + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; + + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @param message OneofDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumDescriptorProto. */ + interface IEnumDescriptorProto { + + /** EnumDescriptorProto name */ + name?: (string|null); + + /** EnumDescriptorProto value */ + value?: (google.protobuf.IEnumValueDescriptorProto[]|null); + + /** EnumDescriptorProto options */ + options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange */ + reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); + + /** EnumDescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents an EnumDescriptorProto. */ + class EnumDescriptorProto implements IEnumDescriptorProto { + + /** + * Constructs a new EnumDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumDescriptorProto); + + /** EnumDescriptorProto name. */ + public name: string; + + /** EnumDescriptorProto value. */ + public value: google.protobuf.IEnumValueDescriptorProto[]; + + /** EnumDescriptorProto options. */ + public options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange. */ + public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; + + /** EnumDescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; + + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @param message EnumDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace EnumDescriptorProto { + + /** Properties of an EnumReservedRange. */ + interface IEnumReservedRange { + + /** EnumReservedRange start */ + start?: (number|null); + + /** EnumReservedRange end */ + end?: (number|null); + } + + /** Represents an EnumReservedRange. */ + class EnumReservedRange implements IEnumReservedRange { + + /** + * Constructs a new EnumReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); + + /** EnumReservedRange start. */ + public start: number; + + /** EnumReservedRange end. */ + public end: number; + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @param message EnumReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an EnumValueDescriptorProto. */ + interface IEnumValueDescriptorProto { + + /** EnumValueDescriptorProto name */ + name?: (string|null); + + /** EnumValueDescriptorProto number */ + number?: (number|null); + + /** EnumValueDescriptorProto options */ + options?: (google.protobuf.IEnumValueOptions|null); + } + + /** Represents an EnumValueDescriptorProto. */ + class EnumValueDescriptorProto implements IEnumValueDescriptorProto { + + /** + * Constructs a new EnumValueDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueDescriptorProto); + + /** EnumValueDescriptorProto name. */ + public name: string; + + /** EnumValueDescriptorProto number. */ + public number: number; + + /** EnumValueDescriptorProto options. */ + public options?: (google.protobuf.IEnumValueOptions|null); + + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; + + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @param message EnumValueDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceDescriptorProto. */ + interface IServiceDescriptorProto { + + /** ServiceDescriptorProto name */ + name?: (string|null); + + /** ServiceDescriptorProto method */ + method?: (google.protobuf.IMethodDescriptorProto[]|null); + + /** ServiceDescriptorProto options */ + options?: (google.protobuf.IServiceOptions|null); + } + + /** Represents a ServiceDescriptorProto. */ + class ServiceDescriptorProto implements IServiceDescriptorProto { + + /** + * Constructs a new ServiceDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceDescriptorProto); + + /** ServiceDescriptorProto name. */ + public name: string; + + /** ServiceDescriptorProto method. */ + public method: google.protobuf.IMethodDescriptorProto[]; + + /** ServiceDescriptorProto options. */ + public options?: (google.protobuf.IServiceOptions|null); + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @param message ServiceDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodDescriptorProto. */ + interface IMethodDescriptorProto { + + /** MethodDescriptorProto name */ + name?: (string|null); + + /** MethodDescriptorProto inputType */ + inputType?: (string|null); + + /** MethodDescriptorProto outputType */ + outputType?: (string|null); + + /** MethodDescriptorProto options */ + options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming */ + clientStreaming?: (boolean|null); + + /** MethodDescriptorProto serverStreaming */ + serverStreaming?: (boolean|null); + } + + /** Represents a MethodDescriptorProto. */ + class MethodDescriptorProto implements IMethodDescriptorProto { + + /** + * Constructs a new MethodDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodDescriptorProto); + + /** MethodDescriptorProto name. */ + public name: string; + + /** MethodDescriptorProto inputType. */ + public inputType: string; + + /** MethodDescriptorProto outputType. */ + public outputType: string; + + /** MethodDescriptorProto options. */ + public options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming. */ + public clientStreaming: boolean; + + /** MethodDescriptorProto serverStreaming. */ + public serverStreaming: boolean; + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @param message MethodDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FileOptions. */ + interface IFileOptions { + + /** FileOptions javaPackage */ + javaPackage?: (string|null); + + /** FileOptions javaOuterClassname */ + javaOuterClassname?: (string|null); + + /** FileOptions javaMultipleFiles */ + javaMultipleFiles?: (boolean|null); + + /** FileOptions javaGenerateEqualsAndHash */ + javaGenerateEqualsAndHash?: (boolean|null); + + /** FileOptions javaStringCheckUtf8 */ + javaStringCheckUtf8?: (boolean|null); + + /** FileOptions optimizeFor */ + optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); + + /** FileOptions goPackage */ + goPackage?: (string|null); + + /** FileOptions ccGenericServices */ + ccGenericServices?: (boolean|null); + + /** FileOptions javaGenericServices */ + javaGenericServices?: (boolean|null); + + /** FileOptions pyGenericServices */ + pyGenericServices?: (boolean|null); + + /** FileOptions deprecated */ + deprecated?: (boolean|null); + + /** FileOptions ccEnableArenas */ + ccEnableArenas?: (boolean|null); + + /** FileOptions objcClassPrefix */ + objcClassPrefix?: (string|null); + + /** FileOptions csharpNamespace */ + csharpNamespace?: (string|null); + + /** FileOptions swiftPrefix */ + swiftPrefix?: (string|null); + + /** FileOptions phpClassPrefix */ + phpClassPrefix?: (string|null); + + /** FileOptions phpNamespace */ + phpNamespace?: (string|null); + + /** FileOptions phpMetadataNamespace */ + phpMetadataNamespace?: (string|null); + + /** FileOptions rubyPackage */ + rubyPackage?: (string|null); + + /** FileOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FileOptions .google.api.resourceDefinition */ + ".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null); + } + + /** Represents a FileOptions. */ + class FileOptions implements IFileOptions { + + /** + * Constructs a new FileOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileOptions); + + /** FileOptions javaPackage. */ + public javaPackage: string; + + /** FileOptions javaOuterClassname. */ + public javaOuterClassname: string; + + /** FileOptions javaMultipleFiles. */ + public javaMultipleFiles: boolean; + + /** FileOptions javaGenerateEqualsAndHash. */ + public javaGenerateEqualsAndHash: boolean; + + /** FileOptions javaStringCheckUtf8. */ + public javaStringCheckUtf8: boolean; + + /** FileOptions optimizeFor. */ + public optimizeFor: google.protobuf.FileOptions.OptimizeMode; + + /** FileOptions goPackage. */ + public goPackage: string; + + /** FileOptions ccGenericServices. */ + public ccGenericServices: boolean; + + /** FileOptions javaGenericServices. */ + public javaGenericServices: boolean; + + /** FileOptions pyGenericServices. */ + public pyGenericServices: boolean; + + /** FileOptions deprecated. */ + public deprecated: boolean; + + /** FileOptions ccEnableArenas. */ + public ccEnableArenas: boolean; + + /** FileOptions objcClassPrefix. */ + public objcClassPrefix: string; + + /** FileOptions csharpNamespace. */ + public csharpNamespace: string; + + /** FileOptions swiftPrefix. */ + public swiftPrefix: string; + + /** FileOptions phpClassPrefix. */ + public phpClassPrefix: string; + + /** FileOptions phpNamespace. */ + public phpNamespace: string; + + /** FileOptions phpMetadataNamespace. */ + public phpMetadataNamespace: string; + + /** FileOptions rubyPackage. */ + public rubyPackage: string; + + /** FileOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; + + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @param message FileOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FileOptions { + + /** OptimizeMode enum. */ + type OptimizeMode = + "SPEED"| "CODE_SIZE"| "LITE_RUNTIME"; + } + + /** Properties of a MessageOptions. */ + interface IMessageOptions { + + /** MessageOptions messageSetWireFormat */ + messageSetWireFormat?: (boolean|null); + + /** MessageOptions noStandardDescriptorAccessor */ + noStandardDescriptorAccessor?: (boolean|null); + + /** MessageOptions deprecated */ + deprecated?: (boolean|null); + + /** MessageOptions mapEntry */ + mapEntry?: (boolean|null); + + /** MessageOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** MessageOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MessageOptions .google.api.resource */ + ".google.api.resource"?: (google.api.IResourceDescriptor|null); + } + + /** Represents a MessageOptions. */ + class MessageOptions implements IMessageOptions { + + /** + * Constructs a new MessageOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMessageOptions); + + /** MessageOptions messageSetWireFormat. */ + public messageSetWireFormat: boolean; + + /** MessageOptions noStandardDescriptorAccessor. */ + public noStandardDescriptorAccessor: boolean; + + /** MessageOptions deprecated. */ + public deprecated: boolean; + + /** MessageOptions mapEntry. */ + public mapEntry: boolean; + + /** MessageOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** MessageOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MessageOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; + + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @param message MessageOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MessageOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MessageOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldOptions. */ + interface IFieldOptions { + + /** FieldOptions ctype */ + ctype?: (google.protobuf.FieldOptions.CType|null); + + /** FieldOptions packed */ + packed?: (boolean|null); + + /** FieldOptions jstype */ + jstype?: (google.protobuf.FieldOptions.JSType|null); + + /** FieldOptions lazy */ + lazy?: (boolean|null); + + /** FieldOptions unverifiedLazy */ + unverifiedLazy?: (boolean|null); + + /** FieldOptions deprecated */ + deprecated?: (boolean|null); + + /** FieldOptions weak */ + weak?: (boolean|null); + + /** FieldOptions debugRedact */ + debugRedact?: (boolean|null); + + /** FieldOptions retention */ + retention?: (google.protobuf.FieldOptions.OptionRetention|null); + + /** FieldOptions targets */ + targets?: (google.protobuf.FieldOptions.OptionTargetType[]|null); + + /** FieldOptions editionDefaults */ + editionDefaults?: (google.protobuf.FieldOptions.IEditionDefault[]|null); + + /** FieldOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FieldOptions .google.api.fieldBehavior */ + ".google.api.fieldBehavior"?: (google.api.FieldBehavior[]|null); + + /** FieldOptions .google.api.resourceReference */ + ".google.api.resourceReference"?: (google.api.IResourceReference|null); + } + + /** Represents a FieldOptions. */ + class FieldOptions implements IFieldOptions { + + /** + * Constructs a new FieldOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldOptions); + + /** FieldOptions ctype. */ + public ctype: google.protobuf.FieldOptions.CType; + + /** FieldOptions packed. */ + public packed: boolean; + + /** FieldOptions jstype. */ + public jstype: google.protobuf.FieldOptions.JSType; + + /** FieldOptions lazy. */ + public lazy: boolean; + + /** FieldOptions unverifiedLazy. */ + public unverifiedLazy: boolean; + + /** FieldOptions deprecated. */ + public deprecated: boolean; + + /** FieldOptions weak. */ + public weak: boolean; + + /** FieldOptions debugRedact. */ + public debugRedact: boolean; + + /** FieldOptions retention. */ + public retention: google.protobuf.FieldOptions.OptionRetention; + + /** FieldOptions targets. */ + public targets: google.protobuf.FieldOptions.OptionTargetType[]; + + /** FieldOptions editionDefaults. */ + public editionDefaults: google.protobuf.FieldOptions.IEditionDefault[]; + + /** FieldOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; + + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @param message FieldOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldOptions { + + /** CType enum. */ + type CType = + "STRING"| "CORD"| "STRING_PIECE"; + + /** JSType enum. */ + type JSType = + "JS_NORMAL"| "JS_STRING"| "JS_NUMBER"; + + /** OptionRetention enum. */ + type OptionRetention = + "RETENTION_UNKNOWN"| "RETENTION_RUNTIME"| "RETENTION_SOURCE"; + + /** OptionTargetType enum. */ + type OptionTargetType = + "TARGET_TYPE_UNKNOWN"| "TARGET_TYPE_FILE"| "TARGET_TYPE_EXTENSION_RANGE"| "TARGET_TYPE_MESSAGE"| "TARGET_TYPE_FIELD"| "TARGET_TYPE_ONEOF"| "TARGET_TYPE_ENUM"| "TARGET_TYPE_ENUM_ENTRY"| "TARGET_TYPE_SERVICE"| "TARGET_TYPE_METHOD"; + + /** Properties of an EditionDefault. */ + interface IEditionDefault { + + /** EditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** EditionDefault value */ + value?: (string|null); + } + + /** Represents an EditionDefault. */ + class EditionDefault implements IEditionDefault { + + /** + * Constructs a new EditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FieldOptions.IEditionDefault); + + /** EditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** EditionDefault value. */ + public value: string; + + /** + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.EditionDefault; + + /** + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * @param message EditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions.EditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an OneofOptions. */ + interface IOneofOptions { + + /** OneofOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an OneofOptions. */ + class OneofOptions implements IOneofOptions { + + /** + * Constructs a new OneofOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofOptions); + + /** OneofOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @param message OneofOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumOptions. */ + interface IEnumOptions { + + /** EnumOptions allowAlias */ + allowAlias?: (boolean|null); + + /** EnumOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** EnumOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumOptions. */ + class EnumOptions implements IEnumOptions { + + /** + * Constructs a new EnumOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumOptions); + + /** EnumOptions allowAlias. */ + public allowAlias: boolean; + + /** EnumOptions deprecated. */ + public deprecated: boolean; + + /** EnumOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** EnumOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @param message EnumOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumValueOptions. */ + interface IEnumValueOptions { + + /** EnumValueOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumValueOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact */ + debugRedact?: (boolean|null); + + /** EnumValueOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumValueOptions. */ + class EnumValueOptions implements IEnumValueOptions { + + /** + * Constructs a new EnumValueOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueOptions); + + /** EnumValueOptions deprecated. */ + public deprecated: boolean; + + /** EnumValueOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact. */ + public debugRedact: boolean; + + /** EnumValueOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; + + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @param message EnumValueOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceOptions. */ + interface IServiceOptions { + + /** ServiceOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated */ + deprecated?: (boolean|null); + + /** ServiceOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ServiceOptions .google.api.defaultHost */ + ".google.api.defaultHost"?: (string|null); + + /** ServiceOptions .google.api.oauthScopes */ + ".google.api.oauthScopes"?: (string|null); + + /** ServiceOptions .google.api.apiVersion */ + ".google.api.apiVersion"?: (string|null); + } + + /** Represents a ServiceOptions. */ + class ServiceOptions implements IServiceOptions { + + /** + * Constructs a new ServiceOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceOptions); + + /** ServiceOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated. */ + public deprecated: boolean; + + /** ServiceOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @param message ServiceOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodOptions. */ + interface IMethodOptions { + + /** MethodOptions deprecated */ + deprecated?: (boolean|null); + + /** MethodOptions idempotencyLevel */ + idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); + + /** MethodOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MethodOptions .google.api.http */ + ".google.api.http"?: (google.api.IHttpRule|null); + + /** MethodOptions .google.api.methodSignature */ + ".google.api.methodSignature"?: (string[]|null); + + /** MethodOptions .google.longrunning.operationInfo */ + ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); + } + + /** Represents a MethodOptions. */ + class MethodOptions implements IMethodOptions { + + /** + * Constructs a new MethodOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodOptions); + + /** MethodOptions deprecated. */ + public deprecated: boolean; + + /** MethodOptions idempotencyLevel. */ + public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; + + /** MethodOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; + + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @param message MethodOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodOptions { + + /** IdempotencyLevel enum. */ + type IdempotencyLevel = + "IDEMPOTENCY_UNKNOWN"| "NO_SIDE_EFFECTS"| "IDEMPOTENT"; + } + + /** Properties of an UninterpretedOption. */ + interface IUninterpretedOption { + + /** UninterpretedOption name */ + name?: (google.protobuf.UninterpretedOption.INamePart[]|null); + + /** UninterpretedOption identifierValue */ + identifierValue?: (string|null); + + /** UninterpretedOption positiveIntValue */ + positiveIntValue?: (number|string|null); + + /** UninterpretedOption negativeIntValue */ + negativeIntValue?: (number|string|null); + + /** UninterpretedOption doubleValue */ + doubleValue?: (number|null); + + /** UninterpretedOption stringValue */ + stringValue?: (Uint8Array|null); + + /** UninterpretedOption aggregateValue */ + aggregateValue?: (string|null); + } + + /** Represents an UninterpretedOption. */ + class UninterpretedOption implements IUninterpretedOption { + + /** + * Constructs a new UninterpretedOption. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUninterpretedOption); + + /** UninterpretedOption name. */ + public name: google.protobuf.UninterpretedOption.INamePart[]; + + /** UninterpretedOption identifierValue. */ + public identifierValue: string; + + /** UninterpretedOption positiveIntValue. */ + public positiveIntValue: (number|string); + + /** UninterpretedOption negativeIntValue. */ + public negativeIntValue: (number|string); + + /** UninterpretedOption doubleValue. */ + public doubleValue: number; + + /** UninterpretedOption stringValue. */ + public stringValue: Uint8Array; + + /** UninterpretedOption aggregateValue. */ + public aggregateValue: string; + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UninterpretedOption + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @param message UninterpretedOption + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UninterpretedOption to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UninterpretedOption + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UninterpretedOption { + + /** Properties of a NamePart. */ + interface INamePart { + + /** NamePart namePart */ + namePart: string; + + /** NamePart isExtension */ + isExtension: boolean; + } + + /** Represents a NamePart. */ + class NamePart implements INamePart { + + /** + * Constructs a new NamePart. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.UninterpretedOption.INamePart); + + /** NamePart namePart. */ + public namePart: string; + + /** NamePart isExtension. */ + public isExtension: boolean; + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamePart + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @param message NamePart + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamePart to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NamePart + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a FeatureSet. */ + interface IFeatureSet { + + /** FeatureSet fieldPresence */ + fieldPresence?: (google.protobuf.FeatureSet.FieldPresence|null); + + /** FeatureSet enumType */ + enumType?: (google.protobuf.FeatureSet.EnumType|null); + + /** FeatureSet repeatedFieldEncoding */ + repeatedFieldEncoding?: (google.protobuf.FeatureSet.RepeatedFieldEncoding|null); + + /** FeatureSet utf8Validation */ + utf8Validation?: (google.protobuf.FeatureSet.Utf8Validation|null); + + /** FeatureSet messageEncoding */ + messageEncoding?: (google.protobuf.FeatureSet.MessageEncoding|null); + + /** FeatureSet jsonFormat */ + jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|null); + } + + /** Represents a FeatureSet. */ + class FeatureSet implements IFeatureSet { + + /** + * Constructs a new FeatureSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSet); + + /** FeatureSet fieldPresence. */ + public fieldPresence: google.protobuf.FeatureSet.FieldPresence; + + /** FeatureSet enumType. */ + public enumType: google.protobuf.FeatureSet.EnumType; + + /** FeatureSet repeatedFieldEncoding. */ + public repeatedFieldEncoding: google.protobuf.FeatureSet.RepeatedFieldEncoding; + + /** FeatureSet utf8Validation. */ + public utf8Validation: google.protobuf.FeatureSet.Utf8Validation; + + /** FeatureSet messageEncoding. */ + public messageEncoding: google.protobuf.FeatureSet.MessageEncoding; + + /** FeatureSet jsonFormat. */ + public jsonFormat: google.protobuf.FeatureSet.JsonFormat; + + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet; + + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @param message FeatureSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSet { + + /** FieldPresence enum. */ + type FieldPresence = + "FIELD_PRESENCE_UNKNOWN"| "EXPLICIT"| "IMPLICIT"| "LEGACY_REQUIRED"; + + /** EnumType enum. */ + type EnumType = + "ENUM_TYPE_UNKNOWN"| "OPEN"| "CLOSED"; + + /** RepeatedFieldEncoding enum. */ + type RepeatedFieldEncoding = + "REPEATED_FIELD_ENCODING_UNKNOWN"| "PACKED"| "EXPANDED"; + + /** Utf8Validation enum. */ + type Utf8Validation = + "UTF8_VALIDATION_UNKNOWN"| "VERIFY"| "NONE"; + + /** MessageEncoding enum. */ + type MessageEncoding = + "MESSAGE_ENCODING_UNKNOWN"| "LENGTH_PREFIXED"| "DELIMITED"; + + /** JsonFormat enum. */ + type JsonFormat = + "JSON_FORMAT_UNKNOWN"| "ALLOW"| "LEGACY_BEST_EFFORT"; + } + + /** Properties of a FeatureSetDefaults. */ + interface IFeatureSetDefaults { + + /** FeatureSetDefaults defaults */ + defaults?: (google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]|null); + + /** FeatureSetDefaults minimumEdition */ + minimumEdition?: (google.protobuf.Edition|null); + + /** FeatureSetDefaults maximumEdition */ + maximumEdition?: (google.protobuf.Edition|null); + } + + /** Represents a FeatureSetDefaults. */ + class FeatureSetDefaults implements IFeatureSetDefaults { + + /** + * Constructs a new FeatureSetDefaults. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSetDefaults); + + /** FeatureSetDefaults defaults. */ + public defaults: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]; + + /** FeatureSetDefaults minimumEdition. */ + public minimumEdition: google.protobuf.Edition; + + /** FeatureSetDefaults maximumEdition. */ + public maximumEdition: google.protobuf.Edition; + + /** + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetDefaults + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults; + + /** + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @param message FeatureSetDefaults + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetDefaults to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetDefaults + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSetDefaults { + + /** Properties of a FeatureSetEditionDefault. */ + interface IFeatureSetEditionDefault { + + /** FeatureSetEditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** FeatureSetEditionDefault features */ + features?: (google.protobuf.IFeatureSet|null); + } + + /** Represents a FeatureSetEditionDefault. */ + class FeatureSetEditionDefault implements IFeatureSetEditionDefault { + + /** + * Constructs a new FeatureSetEditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault); + + /** FeatureSetEditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** FeatureSetEditionDefault features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetEditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault; + + /** + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * @param message FeatureSetEditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetEditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetEditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a SourceCodeInfo. */ + interface ISourceCodeInfo { + + /** SourceCodeInfo location */ + location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); + } + + /** Represents a SourceCodeInfo. */ + class SourceCodeInfo implements ISourceCodeInfo { + + /** + * Constructs a new SourceCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ISourceCodeInfo); + + /** SourceCodeInfo location. */ + public location: google.protobuf.SourceCodeInfo.ILocation[]; + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @param message SourceCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace SourceCodeInfo { + + /** Properties of a Location. */ + interface ILocation { + + /** Location path */ + path?: (number[]|null); + + /** Location span */ + span?: (number[]|null); + + /** Location leadingComments */ + leadingComments?: (string|null); + + /** Location trailingComments */ + trailingComments?: (string|null); + + /** Location leadingDetachedComments */ + leadingDetachedComments?: (string[]|null); + } + + /** Represents a Location. */ + class Location implements ILocation { + + /** + * Constructs a new Location. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); + + /** Location path. */ + public path: number[]; + + /** Location span. */ + public span: number[]; + + /** Location leadingComments. */ + public leadingComments: string; + + /** Location trailingComments. */ + public trailingComments: string; + + /** Location leadingDetachedComments. */ + public leadingDetachedComments: string[]; + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Location + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @param message Location + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Location to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Location + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a GeneratedCodeInfo. */ + interface IGeneratedCodeInfo { + + /** GeneratedCodeInfo annotation */ + annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); + } + + /** Represents a GeneratedCodeInfo. */ + class GeneratedCodeInfo implements IGeneratedCodeInfo { + + /** + * Constructs a new GeneratedCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IGeneratedCodeInfo); + + /** GeneratedCodeInfo annotation. */ + public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; + + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GeneratedCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; + + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @param message GeneratedCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GeneratedCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace GeneratedCodeInfo { + + /** Properties of an Annotation. */ + interface IAnnotation { + + /** Annotation path */ + path?: (number[]|null); + + /** Annotation sourceFile */ + sourceFile?: (string|null); + + /** Annotation begin */ + begin?: (number|null); + + /** Annotation end */ + end?: (number|null); + + /** Annotation semantic */ + semantic?: (google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null); + } + + /** Represents an Annotation. */ + class Annotation implements IAnnotation { + + /** + * Constructs a new Annotation. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); + + /** Annotation path. */ + public path: number[]; + + /** Annotation sourceFile. */ + public sourceFile: string; + + /** Annotation begin. */ + public begin: number; + + /** Annotation end. */ + public end: number; + + /** Annotation semantic. */ + public semantic: google.protobuf.GeneratedCodeInfo.Annotation.Semantic; + + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Annotation + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @param message Annotation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Annotation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Annotation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Annotation { + + /** Semantic enum. */ + type Semantic = + "NONE"| "SET"| "ALIAS"; + } + } + + /** Properties of a Struct. */ + interface IStruct { + + /** Struct fields */ + fields?: ({ [k: string]: google.protobuf.IValue }|null); + } + + /** Represents a Struct. */ + class Struct implements IStruct { + + /** + * Constructs a new Struct. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStruct); + + /** Struct fields. */ + public fields: { [k: string]: google.protobuf.IValue }; + + /** + * Creates a Struct message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Struct + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; + + /** + * Creates a plain object from a Struct message. Also converts values to other types if specified. + * @param message Struct + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Struct to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Struct + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Value. */ + interface IValue { + + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue */ + numberValue?: (number|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value boolValue */ + boolValue?: (boolean|null); + + /** Value structValue */ + structValue?: (google.protobuf.IStruct|null); + + /** Value listValue */ + listValue?: (google.protobuf.IListValue|null); + } + + /** Represents a Value. */ + class Value implements IValue { + + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IValue); + + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue. */ + public numberValue?: (number|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value boolValue. */ + public boolValue?: (boolean|null); + + /** Value structValue. */ + public structValue?: (google.protobuf.IStruct|null); + + /** Value listValue. */ + public listValue?: (google.protobuf.IListValue|null); + + /** Value kind. */ + public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Value; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** NullValue enum. */ + type NullValue = + "NULL_VALUE"; + + /** Properties of a ListValue. */ + interface IListValue { + + /** ListValue values */ + values?: (google.protobuf.IValue[]|null); + } + + /** Represents a ListValue. */ + class ListValue implements IListValue { + + /** + * Constructs a new ListValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IListValue); + + /** ListValue values. */ + public values: google.protobuf.IValue[]; + + /** + * Creates a ListValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; + + /** + * Creates a plain object from a ListValue message. Also converts values to other types if specified. + * @param message ListValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Timestamp. */ + interface ITimestamp { + + /** Timestamp seconds */ + seconds?: (number|string|null); + + /** Timestamp nanos */ + nanos?: (number|null); + } + + /** Represents a Timestamp. */ + class Timestamp implements ITimestamp { + + /** + * Constructs a new Timestamp. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ITimestamp); + + /** Timestamp seconds. */ + public seconds: (number|string); + + /** Timestamp nanos. */ + public nanos: number; + + /** + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Timestamp + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; + + /** + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * @param message Timestamp + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Timestamp to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Timestamp + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Duration. */ + interface IDuration { + + /** Duration seconds */ + seconds?: (number|string|null); + + /** Duration nanos */ + nanos?: (number|null); + } + + /** Represents a Duration. */ + class Duration implements IDuration { + + /** + * Constructs a new Duration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDuration); + + /** Duration seconds. */ + public seconds: (number|string); + + /** Duration nanos. */ + public nanos: number; + + /** + * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Duration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; + + /** + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @param message Duration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Duration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Duration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DoubleValue. */ + interface IDoubleValue { + + /** DoubleValue value */ + value?: (number|null); + } + + /** Represents a DoubleValue. */ + class DoubleValue implements IDoubleValue { + + /** + * Constructs a new DoubleValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDoubleValue); + + /** DoubleValue value. */ + public value: number; + + /** + * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DoubleValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DoubleValue; + + /** + * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. + * @param message DoubleValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DoubleValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DoubleValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DoubleValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FloatValue. */ + interface IFloatValue { + + /** FloatValue value */ + value?: (number|null); + } + + /** Represents a FloatValue. */ + class FloatValue implements IFloatValue { + + /** + * Constructs a new FloatValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFloatValue); + + /** FloatValue value. */ + public value: number; + + /** + * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FloatValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FloatValue; + + /** + * Creates a plain object from a FloatValue message. Also converts values to other types if specified. + * @param message FloatValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FloatValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FloatValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FloatValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int64Value. */ + interface IInt64Value { + + /** Int64Value value */ + value?: (number|string|null); + } + + /** Represents an Int64Value. */ + class Int64Value implements IInt64Value { + + /** + * Constructs a new Int64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt64Value); + + /** Int64Value value. */ + public value: (number|string); + + /** + * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int64Value; + + /** + * Creates a plain object from an Int64Value message. Also converts values to other types if specified. + * @param message Int64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt64Value. */ + interface IUInt64Value { + + /** UInt64Value value */ + value?: (number|string|null); + } + + /** Represents a UInt64Value. */ + class UInt64Value implements IUInt64Value { + + /** + * Constructs a new UInt64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt64Value); + + /** UInt64Value value. */ + public value: (number|string); + + /** + * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt64Value; + + /** + * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. + * @param message UInt64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int32Value. */ + interface IInt32Value { + + /** Int32Value value */ + value?: (number|null); + } + + /** Represents an Int32Value. */ + class Int32Value implements IInt32Value { + + /** + * Constructs a new Int32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt32Value); + + /** Int32Value value. */ + public value: number; + + /** + * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int32Value; + + /** + * Creates a plain object from an Int32Value message. Also converts values to other types if specified. + * @param message Int32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt32Value. */ + interface IUInt32Value { + + /** UInt32Value value */ + value?: (number|null); + } + + /** Represents a UInt32Value. */ + class UInt32Value implements IUInt32Value { + + /** + * Constructs a new UInt32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt32Value); + + /** UInt32Value value. */ + public value: number; + + /** + * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt32Value; + + /** + * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. + * @param message UInt32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BoolValue. */ + interface IBoolValue { + + /** BoolValue value */ + value?: (boolean|null); + } + + /** Represents a BoolValue. */ + class BoolValue implements IBoolValue { + + /** + * Constructs a new BoolValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBoolValue); + + /** BoolValue value. */ + public value: boolean; + + /** + * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BoolValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BoolValue; + + /** + * Creates a plain object from a BoolValue message. Also converts values to other types if specified. + * @param message BoolValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BoolValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BoolValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BoolValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StringValue. */ + interface IStringValue { + + /** StringValue value */ + value?: (string|null); + } + + /** Represents a StringValue. */ + class StringValue implements IStringValue { + + /** + * Constructs a new StringValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStringValue); + + /** StringValue value. */ + public value: string; + + /** + * Creates a StringValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StringValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.StringValue; + + /** + * Creates a plain object from a StringValue message. Also converts values to other types if specified. + * @param message StringValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.StringValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StringValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StringValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BytesValue. */ + interface IBytesValue { + + /** BytesValue value */ + value?: (Uint8Array|null); + } + + /** Represents a BytesValue. */ + class BytesValue implements IBytesValue { + + /** + * Constructs a new BytesValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBytesValue); + + /** BytesValue value. */ + public value: Uint8Array; + + /** + * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BytesValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BytesValue; + + /** + * Creates a plain object from a BytesValue message. Also converts values to other types if specified. + * @param message BytesValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BytesValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BytesValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BytesValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Empty. */ + interface IEmpty { + } + + /** Represents an Empty. */ + class Empty implements IEmpty { + + /** + * Constructs a new Empty. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEmpty); + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Empty + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @param message Empty + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Empty to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Empty + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Any. */ + interface IAny { + + /** Any type_url */ + type_url?: (string|null); + + /** Any value */ + value?: (Uint8Array|null); + } + + /** Represents an Any. */ + class Any implements IAny { + + /** + * Constructs a new Any. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IAny); + + /** Any type_url. */ + public type_url: string; + + /** Any value. */ + public value: Uint8Array; + + /** + * Creates an Any message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Any + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Any; + + /** + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @param message Any + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Any to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Any + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldMask. */ + interface IFieldMask { + + /** FieldMask paths */ + paths?: (string[]|null); + } + + /** Represents a FieldMask. */ + class FieldMask implements IFieldMask { + + /** + * Constructs a new FieldMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldMask); + + /** FieldMask paths. */ + public paths: string[]; + + /** + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldMask + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; + + /** + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @param message FieldMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace type. */ + namespace type { + + /** Properties of a LatLng. */ + interface ILatLng { + + /** LatLng latitude */ + latitude?: (number|null); + + /** LatLng longitude */ + longitude?: (number|null); + } + + /** Represents a LatLng. */ + class LatLng implements ILatLng { + + /** + * Constructs a new LatLng. + * @param [properties] Properties to set + */ + constructor(properties?: google.type.ILatLng); + + /** LatLng latitude. */ + public latitude: number; + + /** LatLng longitude. */ + public longitude: number; + + /** + * Creates a LatLng message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LatLng + */ + public static fromObject(object: { [k: string]: any }): google.type.LatLng; + + /** + * Creates a plain object from a LatLng message. Also converts values to other types if specified. + * @param message LatLng + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.type.LatLng, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LatLng to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LatLng + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** DayOfWeek enum. */ + type DayOfWeek = + "DAY_OF_WEEK_UNSPECIFIED"| "MONDAY"| "TUESDAY"| "WEDNESDAY"| "THURSDAY"| "FRIDAY"| "SATURDAY"| "SUNDAY"; + } + + /** Namespace rpc. */ + namespace rpc { + + /** Properties of a Status. */ + interface IStatus { + + /** Status code */ + code?: (number|null); + + /** Status message */ + message?: (string|null); + + /** Status details */ + details?: (google.protobuf.IAny[]|null); + } + + /** Represents a Status. */ + class Status implements IStatus { + + /** + * Constructs a new Status. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IStatus); + + /** Status code. */ + public code: number; + + /** Status message. */ + public message: string; + + /** Status details. */ + public details: google.protobuf.IAny[]; + + /** + * Creates a Status message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Status + */ + public static fromObject(object: { [k: string]: any }): google.rpc.Status; + + /** + * Creates a plain object from a Status message. Also converts values to other types if specified. + * @param message Status + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Status to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Status + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace longrunning. */ + namespace longrunning { + + /** Represents an Operations */ + class Operations extends $protobuf.rpc.Service { + + /** + * Constructs a new Operations service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListOperationsResponse + */ + public listOperations(request: google.longrunning.IListOperationsRequest, callback: google.longrunning.Operations.ListOperationsCallback): void; + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @returns Promise + */ + public listOperations(request: google.longrunning.IListOperationsRequest): Promise; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public getOperation(request: google.longrunning.IGetOperationRequest, callback: google.longrunning.Operations.GetOperationCallback): void; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @returns Promise + */ + public getOperation(request: google.longrunning.IGetOperationRequest): Promise; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest, callback: google.longrunning.Operations.DeleteOperationCallback): void; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @returns Promise + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest): Promise; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest, callback: google.longrunning.Operations.CancelOperationCallback): void; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @returns Promise + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest): Promise; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest, callback: google.longrunning.Operations.WaitOperationCallback): void; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @returns Promise + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest): Promise; + } + + namespace Operations { + + /** + * Callback as used by {@link google.longrunning.Operations#listOperations}. + * @param error Error, if any + * @param [response] ListOperationsResponse + */ + type ListOperationsCallback = (error: (Error|null), response?: google.longrunning.ListOperationsResponse) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#getOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type GetOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#deleteOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#cancelOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type CancelOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#waitOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type WaitOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + } + + /** Properties of an Operation. */ + interface IOperation { + + /** Operation name */ + name?: (string|null); + + /** Operation metadata */ + metadata?: (google.protobuf.IAny|null); + + /** Operation done */ + done?: (boolean|null); + + /** Operation error */ + error?: (google.rpc.IStatus|null); + + /** Operation response */ + response?: (google.protobuf.IAny|null); + } + + /** Represents an Operation. */ + class Operation implements IOperation { + + /** + * Constructs a new Operation. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperation); + + /** Operation name. */ + public name: string; + + /** Operation metadata. */ + public metadata?: (google.protobuf.IAny|null); + + /** Operation done. */ + public done: boolean; + + /** Operation error. */ + public error?: (google.rpc.IStatus|null); + + /** Operation response. */ + public response?: (google.protobuf.IAny|null); + + /** Operation result. */ + public result?: ("error"|"response"); + + /** + * Creates an Operation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Operation + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.Operation; + + /** + * Creates a plain object from an Operation message. Also converts values to other types if specified. + * @param message Operation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.Operation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Operation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Operation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetOperationRequest. */ + interface IGetOperationRequest { + + /** GetOperationRequest name */ + name?: (string|null); + } + + /** Represents a GetOperationRequest. */ + class GetOperationRequest implements IGetOperationRequest { + + /** + * Constructs a new GetOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IGetOperationRequest); + + /** GetOperationRequest name. */ + public name: string; + + /** + * Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.GetOperationRequest; + + /** + * Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified. + * @param message GetOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.GetOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsRequest. */ + interface IListOperationsRequest { + + /** ListOperationsRequest name */ + name?: (string|null); + + /** ListOperationsRequest filter */ + filter?: (string|null); + + /** ListOperationsRequest pageSize */ + pageSize?: (number|null); + + /** ListOperationsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListOperationsRequest. */ + class ListOperationsRequest implements IListOperationsRequest { + + /** + * Constructs a new ListOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsRequest); + + /** ListOperationsRequest name. */ + public name: string; + + /** ListOperationsRequest filter. */ + public filter: string; + + /** ListOperationsRequest pageSize. */ + public pageSize: number; + + /** ListOperationsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsRequest; + + /** + * Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified. + * @param message ListOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsResponse. */ + interface IListOperationsResponse { + + /** ListOperationsResponse operations */ + operations?: (google.longrunning.IOperation[]|null); + + /** ListOperationsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListOperationsResponse. */ + class ListOperationsResponse implements IListOperationsResponse { + + /** + * Constructs a new ListOperationsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsResponse); + + /** ListOperationsResponse operations. */ + public operations: google.longrunning.IOperation[]; + + /** ListOperationsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsResponse + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsResponse; + + /** + * Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified. + * @param message ListOperationsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CancelOperationRequest. */ + interface ICancelOperationRequest { + + /** CancelOperationRequest name */ + name?: (string|null); + } + + /** Represents a CancelOperationRequest. */ + class CancelOperationRequest implements ICancelOperationRequest { + + /** + * Constructs a new CancelOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.ICancelOperationRequest); + + /** CancelOperationRequest name. */ + public name: string; + + /** + * Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CancelOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.CancelOperationRequest; + + /** + * Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified. + * @param message CancelOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.CancelOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CancelOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CancelOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteOperationRequest. */ + interface IDeleteOperationRequest { + + /** DeleteOperationRequest name */ + name?: (string|null); + } + + /** Represents a DeleteOperationRequest. */ + class DeleteOperationRequest implements IDeleteOperationRequest { + + /** + * Constructs a new DeleteOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IDeleteOperationRequest); + + /** DeleteOperationRequest name. */ + public name: string; + + /** + * Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.DeleteOperationRequest; + + /** + * Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified. + * @param message DeleteOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.DeleteOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WaitOperationRequest. */ + interface IWaitOperationRequest { + + /** WaitOperationRequest name */ + name?: (string|null); + + /** WaitOperationRequest timeout */ + timeout?: (google.protobuf.IDuration|null); + } + + /** Represents a WaitOperationRequest. */ + class WaitOperationRequest implements IWaitOperationRequest { + + /** + * Constructs a new WaitOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IWaitOperationRequest); + + /** WaitOperationRequest name. */ + public name: string; + + /** WaitOperationRequest timeout. */ + public timeout?: (google.protobuf.IDuration|null); + + /** + * Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WaitOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.WaitOperationRequest; + + /** + * Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified. + * @param message WaitOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.WaitOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WaitOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WaitOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an OperationInfo. */ + interface IOperationInfo { + + /** OperationInfo responseType */ + responseType?: (string|null); + + /** OperationInfo metadataType */ + metadataType?: (string|null); + } + + /** Represents an OperationInfo. */ + class OperationInfo implements IOperationInfo { + + /** + * Constructs a new OperationInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperationInfo); + + /** OperationInfo responseType. */ + public responseType: string; + + /** OperationInfo metadataType. */ + public metadataType: string; + + /** + * Creates an OperationInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OperationInfo + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.OperationInfo; + + /** + * Creates a plain object from an OperationInfo message. Also converts values to other types if specified. + * @param message OperationInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.OperationInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OperationInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OperationInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } +} diff --git a/node_modules/@google-cloud/firestore/types/protos/firestore_v1beta1_proto_api.d.ts b/node_modules/@google-cloud/firestore/types/protos/firestore_v1beta1_proto_api.d.ts new file mode 100644 index 0000000..2428495 --- /dev/null +++ b/node_modules/@google-cloud/firestore/types/protos/firestore_v1beta1_proto_api.d.ts @@ -0,0 +1,9363 @@ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as $protobuf from "protobufjs"; +/** Namespace google. */ +export namespace google { + + /** Namespace protobuf. */ + namespace protobuf { + + /** Properties of a Timestamp. */ + interface ITimestamp { + + /** Timestamp seconds */ + seconds?: (number|string|null); + + /** Timestamp nanos */ + nanos?: (number|null); + } + + /** Represents a Timestamp. */ + class Timestamp implements ITimestamp { + + /** + * Constructs a new Timestamp. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ITimestamp); + + /** Timestamp seconds. */ + public seconds: (number|string); + + /** Timestamp nanos. */ + public nanos: number; + + /** + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Timestamp + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; + + /** + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * @param message Timestamp + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Timestamp to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Timestamp + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Struct. */ + interface IStruct { + + /** Struct fields */ + fields?: ({ [k: string]: google.protobuf.IValue }|null); + } + + /** Represents a Struct. */ + class Struct implements IStruct { + + /** + * Constructs a new Struct. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStruct); + + /** Struct fields. */ + public fields: { [k: string]: google.protobuf.IValue }; + + /** + * Creates a Struct message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Struct + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; + + /** + * Creates a plain object from a Struct message. Also converts values to other types if specified. + * @param message Struct + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Struct to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Struct + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Value. */ + interface IValue { + + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue */ + numberValue?: (number|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value boolValue */ + boolValue?: (boolean|null); + + /** Value structValue */ + structValue?: (google.protobuf.IStruct|null); + + /** Value listValue */ + listValue?: (google.protobuf.IListValue|null); + } + + /** Represents a Value. */ + class Value implements IValue { + + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IValue); + + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue. */ + public numberValue?: (number|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value boolValue. */ + public boolValue?: (boolean|null); + + /** Value structValue. */ + public structValue?: (google.protobuf.IStruct|null); + + /** Value listValue. */ + public listValue?: (google.protobuf.IListValue|null); + + /** Value kind. */ + public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Value; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** NullValue enum. */ + type NullValue = + "NULL_VALUE"; + + /** Properties of a ListValue. */ + interface IListValue { + + /** ListValue values */ + values?: (google.protobuf.IValue[]|null); + } + + /** Represents a ListValue. */ + class ListValue implements IListValue { + + /** + * Constructs a new ListValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IListValue); + + /** ListValue values. */ + public values: google.protobuf.IValue[]; + + /** + * Creates a ListValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; + + /** + * Creates a plain object from a ListValue message. Also converts values to other types if specified. + * @param message ListValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FileDescriptorSet. */ + interface IFileDescriptorSet { + + /** FileDescriptorSet file */ + file?: (google.protobuf.IFileDescriptorProto[]|null); + } + + /** Represents a FileDescriptorSet. */ + class FileDescriptorSet implements IFileDescriptorSet { + + /** + * Constructs a new FileDescriptorSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorSet); + + /** FileDescriptorSet file. */ + public file: google.protobuf.IFileDescriptorProto[]; + + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; + + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @param message FileDescriptorSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Edition enum. */ + type Edition = + "EDITION_UNKNOWN"| "EDITION_PROTO2"| "EDITION_PROTO3"| "EDITION_2023"| "EDITION_2024"| "EDITION_1_TEST_ONLY"| "EDITION_2_TEST_ONLY"| "EDITION_99997_TEST_ONLY"| "EDITION_99998_TEST_ONLY"| "EDITION_99999_TEST_ONLY"| "EDITION_MAX"; + + /** Properties of a FileDescriptorProto. */ + interface IFileDescriptorProto { + + /** FileDescriptorProto name */ + name?: (string|null); + + /** FileDescriptorProto package */ + "package"?: (string|null); + + /** FileDescriptorProto dependency */ + dependency?: (string[]|null); + + /** FileDescriptorProto publicDependency */ + publicDependency?: (number[]|null); + + /** FileDescriptorProto weakDependency */ + weakDependency?: (number[]|null); + + /** FileDescriptorProto messageType */ + messageType?: (google.protobuf.IDescriptorProto[]|null); + + /** FileDescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** FileDescriptorProto service */ + service?: (google.protobuf.IServiceDescriptorProto[]|null); + + /** FileDescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** FileDescriptorProto options */ + options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo */ + sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax */ + syntax?: (string|null); + + /** FileDescriptorProto edition */ + edition?: (google.protobuf.Edition|null); + } + + /** Represents a FileDescriptorProto. */ + class FileDescriptorProto implements IFileDescriptorProto { + + /** + * Constructs a new FileDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorProto); + + /** FileDescriptorProto name. */ + public name: string; + + /** FileDescriptorProto package. */ + public package: string; + + /** FileDescriptorProto dependency. */ + public dependency: string[]; + + /** FileDescriptorProto publicDependency. */ + public publicDependency: number[]; + + /** FileDescriptorProto weakDependency. */ + public weakDependency: number[]; + + /** FileDescriptorProto messageType. */ + public messageType: google.protobuf.IDescriptorProto[]; + + /** FileDescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** FileDescriptorProto service. */ + public service: google.protobuf.IServiceDescriptorProto[]; + + /** FileDescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** FileDescriptorProto options. */ + public options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo. */ + public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax. */ + public syntax: string; + + /** FileDescriptorProto edition. */ + public edition: google.protobuf.Edition; + + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; + + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @param message FileDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DescriptorProto. */ + interface IDescriptorProto { + + /** DescriptorProto name */ + name?: (string|null); + + /** DescriptorProto field */ + field?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto nestedType */ + nestedType?: (google.protobuf.IDescriptorProto[]|null); + + /** DescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** DescriptorProto extensionRange */ + extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); + + /** DescriptorProto oneofDecl */ + oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); + + /** DescriptorProto options */ + options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange */ + reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); + + /** DescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents a DescriptorProto. */ + class DescriptorProto implements IDescriptorProto { + + /** + * Constructs a new DescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDescriptorProto); + + /** DescriptorProto name. */ + public name: string; + + /** DescriptorProto field. */ + public field: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto nestedType. */ + public nestedType: google.protobuf.IDescriptorProto[]; + + /** DescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** DescriptorProto extensionRange. */ + public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; + + /** DescriptorProto oneofDecl. */ + public oneofDecl: google.protobuf.IOneofDescriptorProto[]; + + /** DescriptorProto options. */ + public options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange. */ + public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; + + /** DescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; + + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @param message DescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DescriptorProto { + + /** Properties of an ExtensionRange. */ + interface IExtensionRange { + + /** ExtensionRange start */ + start?: (number|null); + + /** ExtensionRange end */ + end?: (number|null); + + /** ExtensionRange options */ + options?: (google.protobuf.IExtensionRangeOptions|null); + } + + /** Represents an ExtensionRange. */ + class ExtensionRange implements IExtensionRange { + + /** + * Constructs a new ExtensionRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); + + /** ExtensionRange start. */ + public start: number; + + /** ExtensionRange end. */ + public end: number; + + /** ExtensionRange options. */ + public options?: (google.protobuf.IExtensionRangeOptions|null); + + /** + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @param message ExtensionRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReservedRange. */ + interface IReservedRange { + + /** ReservedRange start */ + start?: (number|null); + + /** ReservedRange end */ + end?: (number|null); + } + + /** Represents a ReservedRange. */ + class ReservedRange implements IReservedRange { + + /** + * Constructs a new ReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); + + /** ReservedRange start. */ + public start: number; + + /** ReservedRange end. */ + public end: number; + + /** + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @param message ReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an ExtensionRangeOptions. */ + interface IExtensionRangeOptions { + + /** ExtensionRangeOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ExtensionRangeOptions declaration */ + declaration?: (google.protobuf.ExtensionRangeOptions.IDeclaration[]|null); + + /** ExtensionRangeOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification */ + verification?: (google.protobuf.ExtensionRangeOptions.VerificationState|null); + } + + /** Represents an ExtensionRangeOptions. */ + class ExtensionRangeOptions implements IExtensionRangeOptions { + + /** + * Constructs a new ExtensionRangeOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IExtensionRangeOptions); + + /** ExtensionRangeOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** ExtensionRangeOptions declaration. */ + public declaration: google.protobuf.ExtensionRangeOptions.IDeclaration[]; + + /** ExtensionRangeOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification. */ + public verification: google.protobuf.ExtensionRangeOptions.VerificationState; + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRangeOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @param message ExtensionRangeOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRangeOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ExtensionRangeOptions { + + /** Properties of a Declaration. */ + interface IDeclaration { + + /** Declaration number */ + number?: (number|null); + + /** Declaration fullName */ + fullName?: (string|null); + + /** Declaration type */ + type?: (string|null); + + /** Declaration reserved */ + reserved?: (boolean|null); + + /** Declaration repeated */ + repeated?: (boolean|null); + } + + /** Represents a Declaration. */ + class Declaration implements IDeclaration { + + /** + * Constructs a new Declaration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ExtensionRangeOptions.IDeclaration); + + /** Declaration number. */ + public number: number; + + /** Declaration fullName. */ + public fullName: string; + + /** Declaration type. */ + public type: string; + + /** Declaration reserved. */ + public reserved: boolean; + + /** Declaration repeated. */ + public repeated: boolean; + + /** + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Declaration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions.Declaration; + + /** + * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * @param message Declaration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions.Declaration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Declaration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Declaration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** VerificationState enum. */ + type VerificationState = + "DECLARATION"| "UNVERIFIED"; + } + + /** Properties of a FieldDescriptorProto. */ + interface IFieldDescriptorProto { + + /** FieldDescriptorProto name */ + name?: (string|null); + + /** FieldDescriptorProto number */ + number?: (number|null); + + /** FieldDescriptorProto label */ + label?: (google.protobuf.FieldDescriptorProto.Label|null); + + /** FieldDescriptorProto type */ + type?: (google.protobuf.FieldDescriptorProto.Type|null); + + /** FieldDescriptorProto typeName */ + typeName?: (string|null); + + /** FieldDescriptorProto extendee */ + extendee?: (string|null); + + /** FieldDescriptorProto defaultValue */ + defaultValue?: (string|null); + + /** FieldDescriptorProto oneofIndex */ + oneofIndex?: (number|null); + + /** FieldDescriptorProto jsonName */ + jsonName?: (string|null); + + /** FieldDescriptorProto options */ + options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional */ + proto3Optional?: (boolean|null); + } + + /** Represents a FieldDescriptorProto. */ + class FieldDescriptorProto implements IFieldDescriptorProto { + + /** + * Constructs a new FieldDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldDescriptorProto); + + /** FieldDescriptorProto name. */ + public name: string; + + /** FieldDescriptorProto number. */ + public number: number; + + /** FieldDescriptorProto label. */ + public label: google.protobuf.FieldDescriptorProto.Label; + + /** FieldDescriptorProto type. */ + public type: google.protobuf.FieldDescriptorProto.Type; + + /** FieldDescriptorProto typeName. */ + public typeName: string; + + /** FieldDescriptorProto extendee. */ + public extendee: string; + + /** FieldDescriptorProto defaultValue. */ + public defaultValue: string; + + /** FieldDescriptorProto oneofIndex. */ + public oneofIndex: number; + + /** FieldDescriptorProto jsonName. */ + public jsonName: string; + + /** FieldDescriptorProto options. */ + public options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional. */ + public proto3Optional: boolean; + + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @param message FieldDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldDescriptorProto { + + /** Type enum. */ + type Type = + "TYPE_DOUBLE"| "TYPE_FLOAT"| "TYPE_INT64"| "TYPE_UINT64"| "TYPE_INT32"| "TYPE_FIXED64"| "TYPE_FIXED32"| "TYPE_BOOL"| "TYPE_STRING"| "TYPE_GROUP"| "TYPE_MESSAGE"| "TYPE_BYTES"| "TYPE_UINT32"| "TYPE_ENUM"| "TYPE_SFIXED32"| "TYPE_SFIXED64"| "TYPE_SINT32"| "TYPE_SINT64"; + + /** Label enum. */ + type Label = + "LABEL_OPTIONAL"| "LABEL_REPEATED"| "LABEL_REQUIRED"; + } + + /** Properties of an OneofDescriptorProto. */ + interface IOneofDescriptorProto { + + /** OneofDescriptorProto name */ + name?: (string|null); + + /** OneofDescriptorProto options */ + options?: (google.protobuf.IOneofOptions|null); + } + + /** Represents an OneofDescriptorProto. */ + class OneofDescriptorProto implements IOneofDescriptorProto { + + /** + * Constructs a new OneofDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofDescriptorProto); + + /** OneofDescriptorProto name. */ + public name: string; + + /** OneofDescriptorProto options. */ + public options?: (google.protobuf.IOneofOptions|null); + + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; + + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @param message OneofDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumDescriptorProto. */ + interface IEnumDescriptorProto { + + /** EnumDescriptorProto name */ + name?: (string|null); + + /** EnumDescriptorProto value */ + value?: (google.protobuf.IEnumValueDescriptorProto[]|null); + + /** EnumDescriptorProto options */ + options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange */ + reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); + + /** EnumDescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents an EnumDescriptorProto. */ + class EnumDescriptorProto implements IEnumDescriptorProto { + + /** + * Constructs a new EnumDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumDescriptorProto); + + /** EnumDescriptorProto name. */ + public name: string; + + /** EnumDescriptorProto value. */ + public value: google.protobuf.IEnumValueDescriptorProto[]; + + /** EnumDescriptorProto options. */ + public options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange. */ + public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; + + /** EnumDescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; + + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @param message EnumDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace EnumDescriptorProto { + + /** Properties of an EnumReservedRange. */ + interface IEnumReservedRange { + + /** EnumReservedRange start */ + start?: (number|null); + + /** EnumReservedRange end */ + end?: (number|null); + } + + /** Represents an EnumReservedRange. */ + class EnumReservedRange implements IEnumReservedRange { + + /** + * Constructs a new EnumReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); + + /** EnumReservedRange start. */ + public start: number; + + /** EnumReservedRange end. */ + public end: number; + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @param message EnumReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an EnumValueDescriptorProto. */ + interface IEnumValueDescriptorProto { + + /** EnumValueDescriptorProto name */ + name?: (string|null); + + /** EnumValueDescriptorProto number */ + number?: (number|null); + + /** EnumValueDescriptorProto options */ + options?: (google.protobuf.IEnumValueOptions|null); + } + + /** Represents an EnumValueDescriptorProto. */ + class EnumValueDescriptorProto implements IEnumValueDescriptorProto { + + /** + * Constructs a new EnumValueDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueDescriptorProto); + + /** EnumValueDescriptorProto name. */ + public name: string; + + /** EnumValueDescriptorProto number. */ + public number: number; + + /** EnumValueDescriptorProto options. */ + public options?: (google.protobuf.IEnumValueOptions|null); + + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; + + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @param message EnumValueDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceDescriptorProto. */ + interface IServiceDescriptorProto { + + /** ServiceDescriptorProto name */ + name?: (string|null); + + /** ServiceDescriptorProto method */ + method?: (google.protobuf.IMethodDescriptorProto[]|null); + + /** ServiceDescriptorProto options */ + options?: (google.protobuf.IServiceOptions|null); + } + + /** Represents a ServiceDescriptorProto. */ + class ServiceDescriptorProto implements IServiceDescriptorProto { + + /** + * Constructs a new ServiceDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceDescriptorProto); + + /** ServiceDescriptorProto name. */ + public name: string; + + /** ServiceDescriptorProto method. */ + public method: google.protobuf.IMethodDescriptorProto[]; + + /** ServiceDescriptorProto options. */ + public options?: (google.protobuf.IServiceOptions|null); + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @param message ServiceDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodDescriptorProto. */ + interface IMethodDescriptorProto { + + /** MethodDescriptorProto name */ + name?: (string|null); + + /** MethodDescriptorProto inputType */ + inputType?: (string|null); + + /** MethodDescriptorProto outputType */ + outputType?: (string|null); + + /** MethodDescriptorProto options */ + options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming */ + clientStreaming?: (boolean|null); + + /** MethodDescriptorProto serverStreaming */ + serverStreaming?: (boolean|null); + } + + /** Represents a MethodDescriptorProto. */ + class MethodDescriptorProto implements IMethodDescriptorProto { + + /** + * Constructs a new MethodDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodDescriptorProto); + + /** MethodDescriptorProto name. */ + public name: string; + + /** MethodDescriptorProto inputType. */ + public inputType: string; + + /** MethodDescriptorProto outputType. */ + public outputType: string; + + /** MethodDescriptorProto options. */ + public options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming. */ + public clientStreaming: boolean; + + /** MethodDescriptorProto serverStreaming. */ + public serverStreaming: boolean; + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @param message MethodDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FileOptions. */ + interface IFileOptions { + + /** FileOptions javaPackage */ + javaPackage?: (string|null); + + /** FileOptions javaOuterClassname */ + javaOuterClassname?: (string|null); + + /** FileOptions javaMultipleFiles */ + javaMultipleFiles?: (boolean|null); + + /** FileOptions javaGenerateEqualsAndHash */ + javaGenerateEqualsAndHash?: (boolean|null); + + /** FileOptions javaStringCheckUtf8 */ + javaStringCheckUtf8?: (boolean|null); + + /** FileOptions optimizeFor */ + optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); + + /** FileOptions goPackage */ + goPackage?: (string|null); + + /** FileOptions ccGenericServices */ + ccGenericServices?: (boolean|null); + + /** FileOptions javaGenericServices */ + javaGenericServices?: (boolean|null); + + /** FileOptions pyGenericServices */ + pyGenericServices?: (boolean|null); + + /** FileOptions deprecated */ + deprecated?: (boolean|null); + + /** FileOptions ccEnableArenas */ + ccEnableArenas?: (boolean|null); + + /** FileOptions objcClassPrefix */ + objcClassPrefix?: (string|null); + + /** FileOptions csharpNamespace */ + csharpNamespace?: (string|null); + + /** FileOptions swiftPrefix */ + swiftPrefix?: (string|null); + + /** FileOptions phpClassPrefix */ + phpClassPrefix?: (string|null); + + /** FileOptions phpNamespace */ + phpNamespace?: (string|null); + + /** FileOptions phpMetadataNamespace */ + phpMetadataNamespace?: (string|null); + + /** FileOptions rubyPackage */ + rubyPackage?: (string|null); + + /** FileOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FileOptions .google.api.resourceDefinition */ + ".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null); + } + + /** Represents a FileOptions. */ + class FileOptions implements IFileOptions { + + /** + * Constructs a new FileOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileOptions); + + /** FileOptions javaPackage. */ + public javaPackage: string; + + /** FileOptions javaOuterClassname. */ + public javaOuterClassname: string; + + /** FileOptions javaMultipleFiles. */ + public javaMultipleFiles: boolean; + + /** FileOptions javaGenerateEqualsAndHash. */ + public javaGenerateEqualsAndHash: boolean; + + /** FileOptions javaStringCheckUtf8. */ + public javaStringCheckUtf8: boolean; + + /** FileOptions optimizeFor. */ + public optimizeFor: google.protobuf.FileOptions.OptimizeMode; + + /** FileOptions goPackage. */ + public goPackage: string; + + /** FileOptions ccGenericServices. */ + public ccGenericServices: boolean; + + /** FileOptions javaGenericServices. */ + public javaGenericServices: boolean; + + /** FileOptions pyGenericServices. */ + public pyGenericServices: boolean; + + /** FileOptions deprecated. */ + public deprecated: boolean; + + /** FileOptions ccEnableArenas. */ + public ccEnableArenas: boolean; + + /** FileOptions objcClassPrefix. */ + public objcClassPrefix: string; + + /** FileOptions csharpNamespace. */ + public csharpNamespace: string; + + /** FileOptions swiftPrefix. */ + public swiftPrefix: string; + + /** FileOptions phpClassPrefix. */ + public phpClassPrefix: string; + + /** FileOptions phpNamespace. */ + public phpNamespace: string; + + /** FileOptions phpMetadataNamespace. */ + public phpMetadataNamespace: string; + + /** FileOptions rubyPackage. */ + public rubyPackage: string; + + /** FileOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; + + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @param message FileOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FileOptions { + + /** OptimizeMode enum. */ + type OptimizeMode = + "SPEED"| "CODE_SIZE"| "LITE_RUNTIME"; + } + + /** Properties of a MessageOptions. */ + interface IMessageOptions { + + /** MessageOptions messageSetWireFormat */ + messageSetWireFormat?: (boolean|null); + + /** MessageOptions noStandardDescriptorAccessor */ + noStandardDescriptorAccessor?: (boolean|null); + + /** MessageOptions deprecated */ + deprecated?: (boolean|null); + + /** MessageOptions mapEntry */ + mapEntry?: (boolean|null); + + /** MessageOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** MessageOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MessageOptions .google.api.resource */ + ".google.api.resource"?: (google.api.IResourceDescriptor|null); + } + + /** Represents a MessageOptions. */ + class MessageOptions implements IMessageOptions { + + /** + * Constructs a new MessageOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMessageOptions); + + /** MessageOptions messageSetWireFormat. */ + public messageSetWireFormat: boolean; + + /** MessageOptions noStandardDescriptorAccessor. */ + public noStandardDescriptorAccessor: boolean; + + /** MessageOptions deprecated. */ + public deprecated: boolean; + + /** MessageOptions mapEntry. */ + public mapEntry: boolean; + + /** MessageOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** MessageOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MessageOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; + + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @param message MessageOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MessageOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MessageOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldOptions. */ + interface IFieldOptions { + + /** FieldOptions ctype */ + ctype?: (google.protobuf.FieldOptions.CType|null); + + /** FieldOptions packed */ + packed?: (boolean|null); + + /** FieldOptions jstype */ + jstype?: (google.protobuf.FieldOptions.JSType|null); + + /** FieldOptions lazy */ + lazy?: (boolean|null); + + /** FieldOptions unverifiedLazy */ + unverifiedLazy?: (boolean|null); + + /** FieldOptions deprecated */ + deprecated?: (boolean|null); + + /** FieldOptions weak */ + weak?: (boolean|null); + + /** FieldOptions debugRedact */ + debugRedact?: (boolean|null); + + /** FieldOptions retention */ + retention?: (google.protobuf.FieldOptions.OptionRetention|null); + + /** FieldOptions targets */ + targets?: (google.protobuf.FieldOptions.OptionTargetType[]|null); + + /** FieldOptions editionDefaults */ + editionDefaults?: (google.protobuf.FieldOptions.IEditionDefault[]|null); + + /** FieldOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FieldOptions .google.api.fieldBehavior */ + ".google.api.fieldBehavior"?: (google.api.FieldBehavior[]|null); + + /** FieldOptions .google.api.resourceReference */ + ".google.api.resourceReference"?: (google.api.IResourceReference|null); + } + + /** Represents a FieldOptions. */ + class FieldOptions implements IFieldOptions { + + /** + * Constructs a new FieldOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldOptions); + + /** FieldOptions ctype. */ + public ctype: google.protobuf.FieldOptions.CType; + + /** FieldOptions packed. */ + public packed: boolean; + + /** FieldOptions jstype. */ + public jstype: google.protobuf.FieldOptions.JSType; + + /** FieldOptions lazy. */ + public lazy: boolean; + + /** FieldOptions unverifiedLazy. */ + public unverifiedLazy: boolean; + + /** FieldOptions deprecated. */ + public deprecated: boolean; + + /** FieldOptions weak. */ + public weak: boolean; + + /** FieldOptions debugRedact. */ + public debugRedact: boolean; + + /** FieldOptions retention. */ + public retention: google.protobuf.FieldOptions.OptionRetention; + + /** FieldOptions targets. */ + public targets: google.protobuf.FieldOptions.OptionTargetType[]; + + /** FieldOptions editionDefaults. */ + public editionDefaults: google.protobuf.FieldOptions.IEditionDefault[]; + + /** FieldOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; + + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @param message FieldOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldOptions { + + /** CType enum. */ + type CType = + "STRING"| "CORD"| "STRING_PIECE"; + + /** JSType enum. */ + type JSType = + "JS_NORMAL"| "JS_STRING"| "JS_NUMBER"; + + /** OptionRetention enum. */ + type OptionRetention = + "RETENTION_UNKNOWN"| "RETENTION_RUNTIME"| "RETENTION_SOURCE"; + + /** OptionTargetType enum. */ + type OptionTargetType = + "TARGET_TYPE_UNKNOWN"| "TARGET_TYPE_FILE"| "TARGET_TYPE_EXTENSION_RANGE"| "TARGET_TYPE_MESSAGE"| "TARGET_TYPE_FIELD"| "TARGET_TYPE_ONEOF"| "TARGET_TYPE_ENUM"| "TARGET_TYPE_ENUM_ENTRY"| "TARGET_TYPE_SERVICE"| "TARGET_TYPE_METHOD"; + + /** Properties of an EditionDefault. */ + interface IEditionDefault { + + /** EditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** EditionDefault value */ + value?: (string|null); + } + + /** Represents an EditionDefault. */ + class EditionDefault implements IEditionDefault { + + /** + * Constructs a new EditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FieldOptions.IEditionDefault); + + /** EditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** EditionDefault value. */ + public value: string; + + /** + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.EditionDefault; + + /** + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * @param message EditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions.EditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an OneofOptions. */ + interface IOneofOptions { + + /** OneofOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an OneofOptions. */ + class OneofOptions implements IOneofOptions { + + /** + * Constructs a new OneofOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofOptions); + + /** OneofOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @param message OneofOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumOptions. */ + interface IEnumOptions { + + /** EnumOptions allowAlias */ + allowAlias?: (boolean|null); + + /** EnumOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** EnumOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumOptions. */ + class EnumOptions implements IEnumOptions { + + /** + * Constructs a new EnumOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumOptions); + + /** EnumOptions allowAlias. */ + public allowAlias: boolean; + + /** EnumOptions deprecated. */ + public deprecated: boolean; + + /** EnumOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** EnumOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @param message EnumOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumValueOptions. */ + interface IEnumValueOptions { + + /** EnumValueOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumValueOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact */ + debugRedact?: (boolean|null); + + /** EnumValueOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumValueOptions. */ + class EnumValueOptions implements IEnumValueOptions { + + /** + * Constructs a new EnumValueOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueOptions); + + /** EnumValueOptions deprecated. */ + public deprecated: boolean; + + /** EnumValueOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact. */ + public debugRedact: boolean; + + /** EnumValueOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; + + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @param message EnumValueOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceOptions. */ + interface IServiceOptions { + + /** ServiceOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated */ + deprecated?: (boolean|null); + + /** ServiceOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ServiceOptions .google.api.defaultHost */ + ".google.api.defaultHost"?: (string|null); + + /** ServiceOptions .google.api.oauthScopes */ + ".google.api.oauthScopes"?: (string|null); + + /** ServiceOptions .google.api.apiVersion */ + ".google.api.apiVersion"?: (string|null); + } + + /** Represents a ServiceOptions. */ + class ServiceOptions implements IServiceOptions { + + /** + * Constructs a new ServiceOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceOptions); + + /** ServiceOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated. */ + public deprecated: boolean; + + /** ServiceOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @param message ServiceOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodOptions. */ + interface IMethodOptions { + + /** MethodOptions deprecated */ + deprecated?: (boolean|null); + + /** MethodOptions idempotencyLevel */ + idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); + + /** MethodOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MethodOptions .google.api.http */ + ".google.api.http"?: (google.api.IHttpRule|null); + + /** MethodOptions .google.api.methodSignature */ + ".google.api.methodSignature"?: (string[]|null); + + /** MethodOptions .google.longrunning.operationInfo */ + ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); + } + + /** Represents a MethodOptions. */ + class MethodOptions implements IMethodOptions { + + /** + * Constructs a new MethodOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodOptions); + + /** MethodOptions deprecated. */ + public deprecated: boolean; + + /** MethodOptions idempotencyLevel. */ + public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; + + /** MethodOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; + + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @param message MethodOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodOptions { + + /** IdempotencyLevel enum. */ + type IdempotencyLevel = + "IDEMPOTENCY_UNKNOWN"| "NO_SIDE_EFFECTS"| "IDEMPOTENT"; + } + + /** Properties of an UninterpretedOption. */ + interface IUninterpretedOption { + + /** UninterpretedOption name */ + name?: (google.protobuf.UninterpretedOption.INamePart[]|null); + + /** UninterpretedOption identifierValue */ + identifierValue?: (string|null); + + /** UninterpretedOption positiveIntValue */ + positiveIntValue?: (number|string|null); + + /** UninterpretedOption negativeIntValue */ + negativeIntValue?: (number|string|null); + + /** UninterpretedOption doubleValue */ + doubleValue?: (number|null); + + /** UninterpretedOption stringValue */ + stringValue?: (Uint8Array|null); + + /** UninterpretedOption aggregateValue */ + aggregateValue?: (string|null); + } + + /** Represents an UninterpretedOption. */ + class UninterpretedOption implements IUninterpretedOption { + + /** + * Constructs a new UninterpretedOption. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUninterpretedOption); + + /** UninterpretedOption name. */ + public name: google.protobuf.UninterpretedOption.INamePart[]; + + /** UninterpretedOption identifierValue. */ + public identifierValue: string; + + /** UninterpretedOption positiveIntValue. */ + public positiveIntValue: (number|string); + + /** UninterpretedOption negativeIntValue. */ + public negativeIntValue: (number|string); + + /** UninterpretedOption doubleValue. */ + public doubleValue: number; + + /** UninterpretedOption stringValue. */ + public stringValue: Uint8Array; + + /** UninterpretedOption aggregateValue. */ + public aggregateValue: string; + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UninterpretedOption + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @param message UninterpretedOption + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UninterpretedOption to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UninterpretedOption + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UninterpretedOption { + + /** Properties of a NamePart. */ + interface INamePart { + + /** NamePart namePart */ + namePart: string; + + /** NamePart isExtension */ + isExtension: boolean; + } + + /** Represents a NamePart. */ + class NamePart implements INamePart { + + /** + * Constructs a new NamePart. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.UninterpretedOption.INamePart); + + /** NamePart namePart. */ + public namePart: string; + + /** NamePart isExtension. */ + public isExtension: boolean; + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamePart + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @param message NamePart + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamePart to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NamePart + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a FeatureSet. */ + interface IFeatureSet { + + /** FeatureSet fieldPresence */ + fieldPresence?: (google.protobuf.FeatureSet.FieldPresence|null); + + /** FeatureSet enumType */ + enumType?: (google.protobuf.FeatureSet.EnumType|null); + + /** FeatureSet repeatedFieldEncoding */ + repeatedFieldEncoding?: (google.protobuf.FeatureSet.RepeatedFieldEncoding|null); + + /** FeatureSet utf8Validation */ + utf8Validation?: (google.protobuf.FeatureSet.Utf8Validation|null); + + /** FeatureSet messageEncoding */ + messageEncoding?: (google.protobuf.FeatureSet.MessageEncoding|null); + + /** FeatureSet jsonFormat */ + jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|null); + } + + /** Represents a FeatureSet. */ + class FeatureSet implements IFeatureSet { + + /** + * Constructs a new FeatureSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSet); + + /** FeatureSet fieldPresence. */ + public fieldPresence: google.protobuf.FeatureSet.FieldPresence; + + /** FeatureSet enumType. */ + public enumType: google.protobuf.FeatureSet.EnumType; + + /** FeatureSet repeatedFieldEncoding. */ + public repeatedFieldEncoding: google.protobuf.FeatureSet.RepeatedFieldEncoding; + + /** FeatureSet utf8Validation. */ + public utf8Validation: google.protobuf.FeatureSet.Utf8Validation; + + /** FeatureSet messageEncoding. */ + public messageEncoding: google.protobuf.FeatureSet.MessageEncoding; + + /** FeatureSet jsonFormat. */ + public jsonFormat: google.protobuf.FeatureSet.JsonFormat; + + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet; + + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @param message FeatureSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSet { + + /** FieldPresence enum. */ + type FieldPresence = + "FIELD_PRESENCE_UNKNOWN"| "EXPLICIT"| "IMPLICIT"| "LEGACY_REQUIRED"; + + /** EnumType enum. */ + type EnumType = + "ENUM_TYPE_UNKNOWN"| "OPEN"| "CLOSED"; + + /** RepeatedFieldEncoding enum. */ + type RepeatedFieldEncoding = + "REPEATED_FIELD_ENCODING_UNKNOWN"| "PACKED"| "EXPANDED"; + + /** Utf8Validation enum. */ + type Utf8Validation = + "UTF8_VALIDATION_UNKNOWN"| "VERIFY"| "NONE"; + + /** MessageEncoding enum. */ + type MessageEncoding = + "MESSAGE_ENCODING_UNKNOWN"| "LENGTH_PREFIXED"| "DELIMITED"; + + /** JsonFormat enum. */ + type JsonFormat = + "JSON_FORMAT_UNKNOWN"| "ALLOW"| "LEGACY_BEST_EFFORT"; + } + + /** Properties of a FeatureSetDefaults. */ + interface IFeatureSetDefaults { + + /** FeatureSetDefaults defaults */ + defaults?: (google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]|null); + + /** FeatureSetDefaults minimumEdition */ + minimumEdition?: (google.protobuf.Edition|null); + + /** FeatureSetDefaults maximumEdition */ + maximumEdition?: (google.protobuf.Edition|null); + } + + /** Represents a FeatureSetDefaults. */ + class FeatureSetDefaults implements IFeatureSetDefaults { + + /** + * Constructs a new FeatureSetDefaults. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSetDefaults); + + /** FeatureSetDefaults defaults. */ + public defaults: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]; + + /** FeatureSetDefaults minimumEdition. */ + public minimumEdition: google.protobuf.Edition; + + /** FeatureSetDefaults maximumEdition. */ + public maximumEdition: google.protobuf.Edition; + + /** + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetDefaults + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults; + + /** + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @param message FeatureSetDefaults + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetDefaults to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetDefaults + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSetDefaults { + + /** Properties of a FeatureSetEditionDefault. */ + interface IFeatureSetEditionDefault { + + /** FeatureSetEditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** FeatureSetEditionDefault features */ + features?: (google.protobuf.IFeatureSet|null); + } + + /** Represents a FeatureSetEditionDefault. */ + class FeatureSetEditionDefault implements IFeatureSetEditionDefault { + + /** + * Constructs a new FeatureSetEditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault); + + /** FeatureSetEditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** FeatureSetEditionDefault features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetEditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault; + + /** + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * @param message FeatureSetEditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetEditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetEditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a SourceCodeInfo. */ + interface ISourceCodeInfo { + + /** SourceCodeInfo location */ + location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); + } + + /** Represents a SourceCodeInfo. */ + class SourceCodeInfo implements ISourceCodeInfo { + + /** + * Constructs a new SourceCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ISourceCodeInfo); + + /** SourceCodeInfo location. */ + public location: google.protobuf.SourceCodeInfo.ILocation[]; + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @param message SourceCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace SourceCodeInfo { + + /** Properties of a Location. */ + interface ILocation { + + /** Location path */ + path?: (number[]|null); + + /** Location span */ + span?: (number[]|null); + + /** Location leadingComments */ + leadingComments?: (string|null); + + /** Location trailingComments */ + trailingComments?: (string|null); + + /** Location leadingDetachedComments */ + leadingDetachedComments?: (string[]|null); + } + + /** Represents a Location. */ + class Location implements ILocation { + + /** + * Constructs a new Location. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); + + /** Location path. */ + public path: number[]; + + /** Location span. */ + public span: number[]; + + /** Location leadingComments. */ + public leadingComments: string; + + /** Location trailingComments. */ + public trailingComments: string; + + /** Location leadingDetachedComments. */ + public leadingDetachedComments: string[]; + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Location + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @param message Location + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Location to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Location + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a GeneratedCodeInfo. */ + interface IGeneratedCodeInfo { + + /** GeneratedCodeInfo annotation */ + annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); + } + + /** Represents a GeneratedCodeInfo. */ + class GeneratedCodeInfo implements IGeneratedCodeInfo { + + /** + * Constructs a new GeneratedCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IGeneratedCodeInfo); + + /** GeneratedCodeInfo annotation. */ + public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; + + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GeneratedCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; + + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @param message GeneratedCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GeneratedCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace GeneratedCodeInfo { + + /** Properties of an Annotation. */ + interface IAnnotation { + + /** Annotation path */ + path?: (number[]|null); + + /** Annotation sourceFile */ + sourceFile?: (string|null); + + /** Annotation begin */ + begin?: (number|null); + + /** Annotation end */ + end?: (number|null); + + /** Annotation semantic */ + semantic?: (google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null); + } + + /** Represents an Annotation. */ + class Annotation implements IAnnotation { + + /** + * Constructs a new Annotation. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); + + /** Annotation path. */ + public path: number[]; + + /** Annotation sourceFile. */ + public sourceFile: string; + + /** Annotation begin. */ + public begin: number; + + /** Annotation end. */ + public end: number; + + /** Annotation semantic. */ + public semantic: google.protobuf.GeneratedCodeInfo.Annotation.Semantic; + + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Annotation + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @param message Annotation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Annotation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Annotation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Annotation { + + /** Semantic enum. */ + type Semantic = + "NONE"| "SET"| "ALIAS"; + } + } + + /** Properties of a Duration. */ + interface IDuration { + + /** Duration seconds */ + seconds?: (number|string|null); + + /** Duration nanos */ + nanos?: (number|null); + } + + /** Represents a Duration. */ + class Duration implements IDuration { + + /** + * Constructs a new Duration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDuration); + + /** Duration seconds. */ + public seconds: (number|string); + + /** Duration nanos. */ + public nanos: number; + + /** + * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Duration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; + + /** + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @param message Duration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Duration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Duration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DoubleValue. */ + interface IDoubleValue { + + /** DoubleValue value */ + value?: (number|null); + } + + /** Represents a DoubleValue. */ + class DoubleValue implements IDoubleValue { + + /** + * Constructs a new DoubleValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDoubleValue); + + /** DoubleValue value. */ + public value: number; + + /** + * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DoubleValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DoubleValue; + + /** + * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. + * @param message DoubleValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DoubleValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DoubleValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DoubleValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FloatValue. */ + interface IFloatValue { + + /** FloatValue value */ + value?: (number|null); + } + + /** Represents a FloatValue. */ + class FloatValue implements IFloatValue { + + /** + * Constructs a new FloatValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFloatValue); + + /** FloatValue value. */ + public value: number; + + /** + * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FloatValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FloatValue; + + /** + * Creates a plain object from a FloatValue message. Also converts values to other types if specified. + * @param message FloatValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FloatValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FloatValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FloatValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int64Value. */ + interface IInt64Value { + + /** Int64Value value */ + value?: (number|string|null); + } + + /** Represents an Int64Value. */ + class Int64Value implements IInt64Value { + + /** + * Constructs a new Int64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt64Value); + + /** Int64Value value. */ + public value: (number|string); + + /** + * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int64Value; + + /** + * Creates a plain object from an Int64Value message. Also converts values to other types if specified. + * @param message Int64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt64Value. */ + interface IUInt64Value { + + /** UInt64Value value */ + value?: (number|string|null); + } + + /** Represents a UInt64Value. */ + class UInt64Value implements IUInt64Value { + + /** + * Constructs a new UInt64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt64Value); + + /** UInt64Value value. */ + public value: (number|string); + + /** + * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt64Value; + + /** + * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. + * @param message UInt64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int32Value. */ + interface IInt32Value { + + /** Int32Value value */ + value?: (number|null); + } + + /** Represents an Int32Value. */ + class Int32Value implements IInt32Value { + + /** + * Constructs a new Int32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt32Value); + + /** Int32Value value. */ + public value: number; + + /** + * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int32Value; + + /** + * Creates a plain object from an Int32Value message. Also converts values to other types if specified. + * @param message Int32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt32Value. */ + interface IUInt32Value { + + /** UInt32Value value */ + value?: (number|null); + } + + /** Represents a UInt32Value. */ + class UInt32Value implements IUInt32Value { + + /** + * Constructs a new UInt32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt32Value); + + /** UInt32Value value. */ + public value: number; + + /** + * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt32Value; + + /** + * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. + * @param message UInt32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BoolValue. */ + interface IBoolValue { + + /** BoolValue value */ + value?: (boolean|null); + } + + /** Represents a BoolValue. */ + class BoolValue implements IBoolValue { + + /** + * Constructs a new BoolValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBoolValue); + + /** BoolValue value. */ + public value: boolean; + + /** + * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BoolValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BoolValue; + + /** + * Creates a plain object from a BoolValue message. Also converts values to other types if specified. + * @param message BoolValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BoolValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BoolValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BoolValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StringValue. */ + interface IStringValue { + + /** StringValue value */ + value?: (string|null); + } + + /** Represents a StringValue. */ + class StringValue implements IStringValue { + + /** + * Constructs a new StringValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStringValue); + + /** StringValue value. */ + public value: string; + + /** + * Creates a StringValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StringValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.StringValue; + + /** + * Creates a plain object from a StringValue message. Also converts values to other types if specified. + * @param message StringValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.StringValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StringValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StringValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BytesValue. */ + interface IBytesValue { + + /** BytesValue value */ + value?: (Uint8Array|null); + } + + /** Represents a BytesValue. */ + class BytesValue implements IBytesValue { + + /** + * Constructs a new BytesValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBytesValue); + + /** BytesValue value. */ + public value: Uint8Array; + + /** + * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BytesValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BytesValue; + + /** + * Creates a plain object from a BytesValue message. Also converts values to other types if specified. + * @param message BytesValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BytesValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BytesValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BytesValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Empty. */ + interface IEmpty { + } + + /** Represents an Empty. */ + class Empty implements IEmpty { + + /** + * Constructs a new Empty. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEmpty); + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Empty + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @param message Empty + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Empty to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Empty + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Any. */ + interface IAny { + + /** Any type_url */ + type_url?: (string|null); + + /** Any value */ + value?: (Uint8Array|null); + } + + /** Represents an Any. */ + class Any implements IAny { + + /** + * Constructs a new Any. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IAny); + + /** Any type_url. */ + public type_url: string; + + /** Any value. */ + public value: Uint8Array; + + /** + * Creates an Any message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Any + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Any; + + /** + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @param message Any + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Any to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Any + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldMask. */ + interface IFieldMask { + + /** FieldMask paths */ + paths?: (string[]|null); + } + + /** Represents a FieldMask. */ + class FieldMask implements IFieldMask { + + /** + * Constructs a new FieldMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldMask); + + /** FieldMask paths. */ + public paths: string[]; + + /** + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldMask + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; + + /** + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @param message FieldMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace firestore. */ + namespace firestore { + + /** Namespace v1beta1. */ + namespace v1beta1 { + + /** Properties of a DocumentMask. */ + interface IDocumentMask { + + /** DocumentMask fieldPaths */ + fieldPaths?: (string[]|null); + } + + /** Represents a DocumentMask. */ + class DocumentMask implements IDocumentMask { + + /** + * Constructs a new DocumentMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocumentMask); + + /** DocumentMask fieldPaths. */ + public fieldPaths: string[]; + + /** + * Creates a DocumentMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentMask + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentMask; + + /** + * Creates a plain object from a DocumentMask message. Also converts values to other types if specified. + * @param message DocumentMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Precondition. */ + interface IPrecondition { + + /** Precondition exists */ + exists?: (boolean|null); + + /** Precondition updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a Precondition. */ + class Precondition implements IPrecondition { + + /** + * Constructs a new Precondition. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IPrecondition); + + /** Precondition exists. */ + public exists?: (boolean|null); + + /** Precondition updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** Precondition conditionType. */ + public conditionType?: ("exists"|"updateTime"); + + /** + * Creates a Precondition message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Precondition + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Precondition; + + /** + * Creates a plain object from a Precondition message. Also converts values to other types if specified. + * @param message Precondition + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Precondition, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Precondition to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Precondition + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a TransactionOptions. */ + interface ITransactionOptions { + + /** TransactionOptions readOnly */ + readOnly?: (google.firestore.v1beta1.TransactionOptions.IReadOnly|null); + + /** TransactionOptions readWrite */ + readWrite?: (google.firestore.v1beta1.TransactionOptions.IReadWrite|null); + } + + /** Represents a TransactionOptions. */ + class TransactionOptions implements ITransactionOptions { + + /** + * Constructs a new TransactionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ITransactionOptions); + + /** TransactionOptions readOnly. */ + public readOnly?: (google.firestore.v1beta1.TransactionOptions.IReadOnly|null); + + /** TransactionOptions readWrite. */ + public readWrite?: (google.firestore.v1beta1.TransactionOptions.IReadWrite|null); + + /** TransactionOptions mode. */ + public mode?: ("readOnly"|"readWrite"); + + /** + * Creates a TransactionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TransactionOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.TransactionOptions; + + /** + * Creates a plain object from a TransactionOptions message. Also converts values to other types if specified. + * @param message TransactionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.TransactionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TransactionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TransactionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TransactionOptions { + + /** Properties of a ReadWrite. */ + interface IReadWrite { + + /** ReadWrite retryTransaction */ + retryTransaction?: (Uint8Array|null); + } + + /** Represents a ReadWrite. */ + class ReadWrite implements IReadWrite { + + /** + * Constructs a new ReadWrite. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.TransactionOptions.IReadWrite); + + /** ReadWrite retryTransaction. */ + public retryTransaction: Uint8Array; + + /** + * Creates a ReadWrite message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadWrite + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.TransactionOptions.ReadWrite; + + /** + * Creates a plain object from a ReadWrite message. Also converts values to other types if specified. + * @param message ReadWrite + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.TransactionOptions.ReadWrite, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadWrite to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadWrite + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReadOnly. */ + interface IReadOnly { + + /** ReadOnly readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a ReadOnly. */ + class ReadOnly implements IReadOnly { + + /** + * Constructs a new ReadOnly. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.TransactionOptions.IReadOnly); + + /** ReadOnly readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ReadOnly consistencySelector. */ + public consistencySelector?: "readTime"; + + /** + * Creates a ReadOnly message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadOnly + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.TransactionOptions.ReadOnly; + + /** + * Creates a plain object from a ReadOnly message. Also converts values to other types if specified. + * @param message ReadOnly + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.TransactionOptions.ReadOnly, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadOnly to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadOnly + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a Document. */ + interface IDocument { + + /** Document name */ + name?: (string|null); + + /** Document fields */ + fields?: ({ [k: string]: google.firestore.v1beta1.IValue }|null); + + /** Document createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** Document updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a Document. */ + class Document implements IDocument { + + /** + * Constructs a new Document. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocument); + + /** Document name. */ + public name: string; + + /** Document fields. */ + public fields: { [k: string]: google.firestore.v1beta1.IValue }; + + /** Document createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** Document updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a Document message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Document + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Document; + + /** + * Creates a plain object from a Document message. Also converts values to other types if specified. + * @param message Document + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Document, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Document to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Document + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Value. */ + interface IValue { + + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); + + /** Value booleanValue */ + booleanValue?: (boolean|null); + + /** Value integerValue */ + integerValue?: (number|string|null); + + /** Value doubleValue */ + doubleValue?: (number|null); + + /** Value timestampValue */ + timestampValue?: (google.protobuf.ITimestamp|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value bytesValue */ + bytesValue?: (Uint8Array|null); + + /** Value referenceValue */ + referenceValue?: (string|null); + + /** Value geoPointValue */ + geoPointValue?: (google.type.ILatLng|null); + + /** Value arrayValue */ + arrayValue?: (google.firestore.v1beta1.IArrayValue|null); + + /** Value mapValue */ + mapValue?: (google.firestore.v1beta1.IMapValue|null); + } + + /** Represents a Value. */ + class Value implements IValue { + + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IValue); + + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); + + /** Value booleanValue. */ + public booleanValue?: (boolean|null); + + /** Value integerValue. */ + public integerValue?: (number|string|null); + + /** Value doubleValue. */ + public doubleValue?: (number|null); + + /** Value timestampValue. */ + public timestampValue?: (google.protobuf.ITimestamp|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value bytesValue. */ + public bytesValue?: (Uint8Array|null); + + /** Value referenceValue. */ + public referenceValue?: (string|null); + + /** Value geoPointValue. */ + public geoPointValue?: (google.type.ILatLng|null); + + /** Value arrayValue. */ + public arrayValue?: (google.firestore.v1beta1.IArrayValue|null); + + /** Value mapValue. */ + public mapValue?: (google.firestore.v1beta1.IMapValue|null); + + /** Value valueType. */ + public valueType?: ("nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Value; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ArrayValue. */ + interface IArrayValue { + + /** ArrayValue values */ + values?: (google.firestore.v1beta1.IValue[]|null); + } + + /** Represents an ArrayValue. */ + class ArrayValue implements IArrayValue { + + /** + * Constructs a new ArrayValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IArrayValue); + + /** ArrayValue values. */ + public values: google.firestore.v1beta1.IValue[]; + + /** + * Creates an ArrayValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ArrayValue + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ArrayValue; + + /** + * Creates a plain object from an ArrayValue message. Also converts values to other types if specified. + * @param message ArrayValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ArrayValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ArrayValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ArrayValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MapValue. */ + interface IMapValue { + + /** MapValue fields */ + fields?: ({ [k: string]: google.firestore.v1beta1.IValue }|null); + } + + /** Represents a MapValue. */ + class MapValue implements IMapValue { + + /** + * Constructs a new MapValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IMapValue); + + /** MapValue fields. */ + public fields: { [k: string]: google.firestore.v1beta1.IValue }; + + /** + * Creates a MapValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MapValue + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.MapValue; + + /** + * Creates a plain object from a MapValue message. Also converts values to other types if specified. + * @param message MapValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.MapValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MapValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MapValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Represents a Firestore */ + class Firestore extends $protobuf.rpc.Service { + + /** + * Constructs a new Firestore service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls GetDocument. + * @param request GetDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public getDocument(request: google.firestore.v1beta1.IGetDocumentRequest, callback: google.firestore.v1beta1.Firestore.GetDocumentCallback): void; + + /** + * Calls GetDocument. + * @param request GetDocumentRequest message or plain object + * @returns Promise + */ + public getDocument(request: google.firestore.v1beta1.IGetDocumentRequest): Promise; + + /** + * Calls ListDocuments. + * @param request ListDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListDocumentsResponse + */ + public listDocuments(request: google.firestore.v1beta1.IListDocumentsRequest, callback: google.firestore.v1beta1.Firestore.ListDocumentsCallback): void; + + /** + * Calls ListDocuments. + * @param request ListDocumentsRequest message or plain object + * @returns Promise + */ + public listDocuments(request: google.firestore.v1beta1.IListDocumentsRequest): Promise; + + /** + * Calls UpdateDocument. + * @param request UpdateDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public updateDocument(request: google.firestore.v1beta1.IUpdateDocumentRequest, callback: google.firestore.v1beta1.Firestore.UpdateDocumentCallback): void; + + /** + * Calls UpdateDocument. + * @param request UpdateDocumentRequest message or plain object + * @returns Promise + */ + public updateDocument(request: google.firestore.v1beta1.IUpdateDocumentRequest): Promise; + + /** + * Calls DeleteDocument. + * @param request DeleteDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteDocument(request: google.firestore.v1beta1.IDeleteDocumentRequest, callback: google.firestore.v1beta1.Firestore.DeleteDocumentCallback): void; + + /** + * Calls DeleteDocument. + * @param request DeleteDocumentRequest message or plain object + * @returns Promise + */ + public deleteDocument(request: google.firestore.v1beta1.IDeleteDocumentRequest): Promise; + + /** + * Calls BatchGetDocuments. + * @param request BatchGetDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchGetDocumentsResponse + */ + public batchGetDocuments(request: google.firestore.v1beta1.IBatchGetDocumentsRequest, callback: google.firestore.v1beta1.Firestore.BatchGetDocumentsCallback): void; + + /** + * Calls BatchGetDocuments. + * @param request BatchGetDocumentsRequest message or plain object + * @returns Promise + */ + public batchGetDocuments(request: google.firestore.v1beta1.IBatchGetDocumentsRequest): Promise; + + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BeginTransactionResponse + */ + public beginTransaction(request: google.firestore.v1beta1.IBeginTransactionRequest, callback: google.firestore.v1beta1.Firestore.BeginTransactionCallback): void; + + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @returns Promise + */ + public beginTransaction(request: google.firestore.v1beta1.IBeginTransactionRequest): Promise; + + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @param callback Node-style callback called with the error, if any, and CommitResponse + */ + public commit(request: google.firestore.v1beta1.ICommitRequest, callback: google.firestore.v1beta1.Firestore.CommitCallback): void; + + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @returns Promise + */ + public commit(request: google.firestore.v1beta1.ICommitRequest): Promise; + + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public rollback(request: google.firestore.v1beta1.IRollbackRequest, callback: google.firestore.v1beta1.Firestore.RollbackCallback): void; + + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @returns Promise + */ + public rollback(request: google.firestore.v1beta1.IRollbackRequest): Promise; + + /** + * Calls RunQuery. + * @param request RunQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and RunQueryResponse + */ + public runQuery(request: google.firestore.v1beta1.IRunQueryRequest, callback: google.firestore.v1beta1.Firestore.RunQueryCallback): void; + + /** + * Calls RunQuery. + * @param request RunQueryRequest message or plain object + * @returns Promise + */ + public runQuery(request: google.firestore.v1beta1.IRunQueryRequest): Promise; + + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and PartitionQueryResponse + */ + public partitionQuery(request: google.firestore.v1beta1.IPartitionQueryRequest, callback: google.firestore.v1beta1.Firestore.PartitionQueryCallback): void; + + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @returns Promise + */ + public partitionQuery(request: google.firestore.v1beta1.IPartitionQueryRequest): Promise; + + /** + * Calls Write. + * @param request WriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and WriteResponse + */ + public write(request: google.firestore.v1beta1.IWriteRequest, callback: google.firestore.v1beta1.Firestore.WriteCallback): void; + + /** + * Calls Write. + * @param request WriteRequest message or plain object + * @returns Promise + */ + public write(request: google.firestore.v1beta1.IWriteRequest): Promise; + + /** + * Calls Listen. + * @param request ListenRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListenResponse + */ + public listen(request: google.firestore.v1beta1.IListenRequest, callback: google.firestore.v1beta1.Firestore.ListenCallback): void; + + /** + * Calls Listen. + * @param request ListenRequest message or plain object + * @returns Promise + */ + public listen(request: google.firestore.v1beta1.IListenRequest): Promise; + + /** + * Calls ListCollectionIds. + * @param request ListCollectionIdsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListCollectionIdsResponse + */ + public listCollectionIds(request: google.firestore.v1beta1.IListCollectionIdsRequest, callback: google.firestore.v1beta1.Firestore.ListCollectionIdsCallback): void; + + /** + * Calls ListCollectionIds. + * @param request ListCollectionIdsRequest message or plain object + * @returns Promise + */ + public listCollectionIds(request: google.firestore.v1beta1.IListCollectionIdsRequest): Promise; + + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchWriteResponse + */ + public batchWrite(request: google.firestore.v1beta1.IBatchWriteRequest, callback: google.firestore.v1beta1.Firestore.BatchWriteCallback): void; + + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @returns Promise + */ + public batchWrite(request: google.firestore.v1beta1.IBatchWriteRequest): Promise; + + /** + * Calls CreateDocument. + * @param request CreateDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public createDocument(request: google.firestore.v1beta1.ICreateDocumentRequest, callback: google.firestore.v1beta1.Firestore.CreateDocumentCallback): void; + + /** + * Calls CreateDocument. + * @param request CreateDocumentRequest message or plain object + * @returns Promise + */ + public createDocument(request: google.firestore.v1beta1.ICreateDocumentRequest): Promise; + } + + namespace Firestore { + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#getDocument}. + * @param error Error, if any + * @param [response] Document + */ + type GetDocumentCallback = (error: (Error|null), response?: google.firestore.v1beta1.Document) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#listDocuments}. + * @param error Error, if any + * @param [response] ListDocumentsResponse + */ + type ListDocumentsCallback = (error: (Error|null), response?: google.firestore.v1beta1.ListDocumentsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#updateDocument}. + * @param error Error, if any + * @param [response] Document + */ + type UpdateDocumentCallback = (error: (Error|null), response?: google.firestore.v1beta1.Document) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#deleteDocument}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteDocumentCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#batchGetDocuments}. + * @param error Error, if any + * @param [response] BatchGetDocumentsResponse + */ + type BatchGetDocumentsCallback = (error: (Error|null), response?: google.firestore.v1beta1.BatchGetDocumentsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#beginTransaction}. + * @param error Error, if any + * @param [response] BeginTransactionResponse + */ + type BeginTransactionCallback = (error: (Error|null), response?: google.firestore.v1beta1.BeginTransactionResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#commit}. + * @param error Error, if any + * @param [response] CommitResponse + */ + type CommitCallback = (error: (Error|null), response?: google.firestore.v1beta1.CommitResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#rollback}. + * @param error Error, if any + * @param [response] Empty + */ + type RollbackCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#runQuery}. + * @param error Error, if any + * @param [response] RunQueryResponse + */ + type RunQueryCallback = (error: (Error|null), response?: google.firestore.v1beta1.RunQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#partitionQuery}. + * @param error Error, if any + * @param [response] PartitionQueryResponse + */ + type PartitionQueryCallback = (error: (Error|null), response?: google.firestore.v1beta1.PartitionQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#write}. + * @param error Error, if any + * @param [response] WriteResponse + */ + type WriteCallback = (error: (Error|null), response?: google.firestore.v1beta1.WriteResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#listen}. + * @param error Error, if any + * @param [response] ListenResponse + */ + type ListenCallback = (error: (Error|null), response?: google.firestore.v1beta1.ListenResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#listCollectionIds}. + * @param error Error, if any + * @param [response] ListCollectionIdsResponse + */ + type ListCollectionIdsCallback = (error: (Error|null), response?: google.firestore.v1beta1.ListCollectionIdsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#batchWrite}. + * @param error Error, if any + * @param [response] BatchWriteResponse + */ + type BatchWriteCallback = (error: (Error|null), response?: google.firestore.v1beta1.BatchWriteResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#createDocument}. + * @param error Error, if any + * @param [response] Document + */ + type CreateDocumentCallback = (error: (Error|null), response?: google.firestore.v1beta1.Document) => void; + } + + /** Properties of a GetDocumentRequest. */ + interface IGetDocumentRequest { + + /** GetDocumentRequest name */ + name?: (string|null); + + /** GetDocumentRequest mask */ + mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** GetDocumentRequest transaction */ + transaction?: (Uint8Array|null); + + /** GetDocumentRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a GetDocumentRequest. */ + class GetDocumentRequest implements IGetDocumentRequest { + + /** + * Constructs a new GetDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IGetDocumentRequest); + + /** GetDocumentRequest name. */ + public name: string; + + /** GetDocumentRequest mask. */ + public mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** GetDocumentRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** GetDocumentRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** GetDocumentRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"readTime"); + + /** + * Creates a GetDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.GetDocumentRequest; + + /** + * Creates a plain object from a GetDocumentRequest message. Also converts values to other types if specified. + * @param message GetDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.GetDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDocumentsRequest. */ + interface IListDocumentsRequest { + + /** ListDocumentsRequest parent */ + parent?: (string|null); + + /** ListDocumentsRequest collectionId */ + collectionId?: (string|null); + + /** ListDocumentsRequest pageSize */ + pageSize?: (number|null); + + /** ListDocumentsRequest pageToken */ + pageToken?: (string|null); + + /** ListDocumentsRequest orderBy */ + orderBy?: (string|null); + + /** ListDocumentsRequest mask */ + mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** ListDocumentsRequest transaction */ + transaction?: (Uint8Array|null); + + /** ListDocumentsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** ListDocumentsRequest showMissing */ + showMissing?: (boolean|null); + } + + /** Represents a ListDocumentsRequest. */ + class ListDocumentsRequest implements IListDocumentsRequest { + + /** + * Constructs a new ListDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListDocumentsRequest); + + /** ListDocumentsRequest parent. */ + public parent: string; + + /** ListDocumentsRequest collectionId. */ + public collectionId: string; + + /** ListDocumentsRequest pageSize. */ + public pageSize: number; + + /** ListDocumentsRequest pageToken. */ + public pageToken: string; + + /** ListDocumentsRequest orderBy. */ + public orderBy: string; + + /** ListDocumentsRequest mask. */ + public mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** ListDocumentsRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** ListDocumentsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ListDocumentsRequest showMissing. */ + public showMissing: boolean; + + /** ListDocumentsRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"readTime"); + + /** + * Creates a ListDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListDocumentsRequest; + + /** + * Creates a plain object from a ListDocumentsRequest message. Also converts values to other types if specified. + * @param message ListDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDocumentsResponse. */ + interface IListDocumentsResponse { + + /** ListDocumentsResponse documents */ + documents?: (google.firestore.v1beta1.IDocument[]|null); + + /** ListDocumentsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListDocumentsResponse. */ + class ListDocumentsResponse implements IListDocumentsResponse { + + /** + * Constructs a new ListDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListDocumentsResponse); + + /** ListDocumentsResponse documents. */ + public documents: google.firestore.v1beta1.IDocument[]; + + /** ListDocumentsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListDocumentsResponse; + + /** + * Creates a plain object from a ListDocumentsResponse message. Also converts values to other types if specified. + * @param message ListDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDocumentRequest. */ + interface ICreateDocumentRequest { + + /** CreateDocumentRequest parent */ + parent?: (string|null); + + /** CreateDocumentRequest collectionId */ + collectionId?: (string|null); + + /** CreateDocumentRequest documentId */ + documentId?: (string|null); + + /** CreateDocumentRequest document */ + document?: (google.firestore.v1beta1.IDocument|null); + + /** CreateDocumentRequest mask */ + mask?: (google.firestore.v1beta1.IDocumentMask|null); + } + + /** Represents a CreateDocumentRequest. */ + class CreateDocumentRequest implements ICreateDocumentRequest { + + /** + * Constructs a new CreateDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ICreateDocumentRequest); + + /** CreateDocumentRequest parent. */ + public parent: string; + + /** CreateDocumentRequest collectionId. */ + public collectionId: string; + + /** CreateDocumentRequest documentId. */ + public documentId: string; + + /** CreateDocumentRequest document. */ + public document?: (google.firestore.v1beta1.IDocument|null); + + /** CreateDocumentRequest mask. */ + public mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** + * Creates a CreateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.CreateDocumentRequest; + + /** + * Creates a plain object from a CreateDocumentRequest message. Also converts values to other types if specified. + * @param message CreateDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.CreateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDocumentRequest. */ + interface IUpdateDocumentRequest { + + /** UpdateDocumentRequest document */ + document?: (google.firestore.v1beta1.IDocument|null); + + /** UpdateDocumentRequest updateMask */ + updateMask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** UpdateDocumentRequest mask */ + mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** UpdateDocumentRequest currentDocument */ + currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + } + + /** Represents an UpdateDocumentRequest. */ + class UpdateDocumentRequest implements IUpdateDocumentRequest { + + /** + * Constructs a new UpdateDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IUpdateDocumentRequest); + + /** UpdateDocumentRequest document. */ + public document?: (google.firestore.v1beta1.IDocument|null); + + /** UpdateDocumentRequest updateMask. */ + public updateMask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** UpdateDocumentRequest mask. */ + public mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** UpdateDocumentRequest currentDocument. */ + public currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + + /** + * Creates an UpdateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.UpdateDocumentRequest; + + /** + * Creates a plain object from an UpdateDocumentRequest message. Also converts values to other types if specified. + * @param message UpdateDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.UpdateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDocumentRequest. */ + interface IDeleteDocumentRequest { + + /** DeleteDocumentRequest name */ + name?: (string|null); + + /** DeleteDocumentRequest currentDocument */ + currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + } + + /** Represents a DeleteDocumentRequest. */ + class DeleteDocumentRequest implements IDeleteDocumentRequest { + + /** + * Constructs a new DeleteDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDeleteDocumentRequest); + + /** DeleteDocumentRequest name. */ + public name: string; + + /** DeleteDocumentRequest currentDocument. */ + public currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + + /** + * Creates a DeleteDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DeleteDocumentRequest; + + /** + * Creates a plain object from a DeleteDocumentRequest message. Also converts values to other types if specified. + * @param message DeleteDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DeleteDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchGetDocumentsRequest. */ + interface IBatchGetDocumentsRequest { + + /** BatchGetDocumentsRequest database */ + database?: (string|null); + + /** BatchGetDocumentsRequest documents */ + documents?: (string[]|null); + + /** BatchGetDocumentsRequest mask */ + mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** BatchGetDocumentsRequest transaction */ + transaction?: (Uint8Array|null); + + /** BatchGetDocumentsRequest newTransaction */ + newTransaction?: (google.firestore.v1beta1.ITransactionOptions|null); + + /** BatchGetDocumentsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BatchGetDocumentsRequest. */ + class BatchGetDocumentsRequest implements IBatchGetDocumentsRequest { + + /** + * Constructs a new BatchGetDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBatchGetDocumentsRequest); + + /** BatchGetDocumentsRequest database. */ + public database: string; + + /** BatchGetDocumentsRequest documents. */ + public documents: string[]; + + /** BatchGetDocumentsRequest mask. */ + public mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** BatchGetDocumentsRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** BatchGetDocumentsRequest newTransaction. */ + public newTransaction?: (google.firestore.v1beta1.ITransactionOptions|null); + + /** BatchGetDocumentsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BatchGetDocumentsRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a BatchGetDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchGetDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BatchGetDocumentsRequest; + + /** + * Creates a plain object from a BatchGetDocumentsRequest message. Also converts values to other types if specified. + * @param message BatchGetDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BatchGetDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchGetDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchGetDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchGetDocumentsResponse. */ + interface IBatchGetDocumentsResponse { + + /** BatchGetDocumentsResponse found */ + found?: (google.firestore.v1beta1.IDocument|null); + + /** BatchGetDocumentsResponse missing */ + missing?: (string|null); + + /** BatchGetDocumentsResponse transaction */ + transaction?: (Uint8Array|null); + + /** BatchGetDocumentsResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BatchGetDocumentsResponse. */ + class BatchGetDocumentsResponse implements IBatchGetDocumentsResponse { + + /** + * Constructs a new BatchGetDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBatchGetDocumentsResponse); + + /** BatchGetDocumentsResponse found. */ + public found?: (google.firestore.v1beta1.IDocument|null); + + /** BatchGetDocumentsResponse missing. */ + public missing?: (string|null); + + /** BatchGetDocumentsResponse transaction. */ + public transaction: Uint8Array; + + /** BatchGetDocumentsResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BatchGetDocumentsResponse result. */ + public result?: ("found"|"missing"); + + /** + * Creates a BatchGetDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchGetDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BatchGetDocumentsResponse; + + /** + * Creates a plain object from a BatchGetDocumentsResponse message. Also converts values to other types if specified. + * @param message BatchGetDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BatchGetDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchGetDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchGetDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BeginTransactionRequest. */ + interface IBeginTransactionRequest { + + /** BeginTransactionRequest database */ + database?: (string|null); + + /** BeginTransactionRequest options */ + options?: (google.firestore.v1beta1.ITransactionOptions|null); + } + + /** Represents a BeginTransactionRequest. */ + class BeginTransactionRequest implements IBeginTransactionRequest { + + /** + * Constructs a new BeginTransactionRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBeginTransactionRequest); + + /** BeginTransactionRequest database. */ + public database: string; + + /** BeginTransactionRequest options. */ + public options?: (google.firestore.v1beta1.ITransactionOptions|null); + + /** + * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BeginTransactionRequest; + + /** + * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. + * @param message BeginTransactionRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BeginTransactionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BeginTransactionRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BeginTransactionResponse. */ + interface IBeginTransactionResponse { + + /** BeginTransactionResponse transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a BeginTransactionResponse. */ + class BeginTransactionResponse implements IBeginTransactionResponse { + + /** + * Constructs a new BeginTransactionResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBeginTransactionResponse); + + /** BeginTransactionResponse transaction. */ + public transaction: Uint8Array; + + /** + * Creates a BeginTransactionResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BeginTransactionResponse; + + /** + * Creates a plain object from a BeginTransactionResponse message. Also converts values to other types if specified. + * @param message BeginTransactionResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BeginTransactionResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BeginTransactionResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommitRequest. */ + interface ICommitRequest { + + /** CommitRequest database */ + database?: (string|null); + + /** CommitRequest writes */ + writes?: (google.firestore.v1beta1.IWrite[]|null); + + /** CommitRequest transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a CommitRequest. */ + class CommitRequest implements ICommitRequest { + + /** + * Constructs a new CommitRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ICommitRequest); + + /** CommitRequest database. */ + public database: string; + + /** CommitRequest writes. */ + public writes: google.firestore.v1beta1.IWrite[]; + + /** CommitRequest transaction. */ + public transaction: Uint8Array; + + /** + * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.CommitRequest; + + /** + * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. + * @param message CommitRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.CommitRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommitResponse. */ + interface ICommitResponse { + + /** CommitResponse writeResults */ + writeResults?: (google.firestore.v1beta1.IWriteResult[]|null); + + /** CommitResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a CommitResponse. */ + class CommitResponse implements ICommitResponse { + + /** + * Constructs a new CommitResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ICommitResponse); + + /** CommitResponse writeResults. */ + public writeResults: google.firestore.v1beta1.IWriteResult[]; + + /** CommitResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.CommitResponse; + + /** + * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. + * @param message CommitResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.CommitResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RollbackRequest. */ + interface IRollbackRequest { + + /** RollbackRequest database */ + database?: (string|null); + + /** RollbackRequest transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a RollbackRequest. */ + class RollbackRequest implements IRollbackRequest { + + /** + * Constructs a new RollbackRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IRollbackRequest); + + /** RollbackRequest database. */ + public database: string; + + /** RollbackRequest transaction. */ + public transaction: Uint8Array; + + /** + * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RollbackRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.RollbackRequest; + + /** + * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. + * @param message RollbackRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.RollbackRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RollbackRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RollbackRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunQueryRequest. */ + interface IRunQueryRequest { + + /** RunQueryRequest parent */ + parent?: (string|null); + + /** RunQueryRequest structuredQuery */ + structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + + /** RunQueryRequest transaction */ + transaction?: (Uint8Array|null); + + /** RunQueryRequest newTransaction */ + newTransaction?: (google.firestore.v1beta1.ITransactionOptions|null); + + /** RunQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a RunQueryRequest. */ + class RunQueryRequest implements IRunQueryRequest { + + /** + * Constructs a new RunQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IRunQueryRequest); + + /** RunQueryRequest parent. */ + public parent: string; + + /** RunQueryRequest structuredQuery. */ + public structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + + /** RunQueryRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** RunQueryRequest newTransaction. */ + public newTransaction?: (google.firestore.v1beta1.ITransactionOptions|null); + + /** RunQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryRequest queryType. */ + public queryType?: "structuredQuery"; + + /** RunQueryRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.RunQueryRequest; + + /** + * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. + * @param message RunQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.RunQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunQueryResponse. */ + interface IRunQueryResponse { + + /** RunQueryResponse transaction */ + transaction?: (Uint8Array|null); + + /** RunQueryResponse document */ + document?: (google.firestore.v1beta1.IDocument|null); + + /** RunQueryResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryResponse skippedResults */ + skippedResults?: (number|null); + } + + /** Represents a RunQueryResponse. */ + class RunQueryResponse implements IRunQueryResponse { + + /** + * Constructs a new RunQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IRunQueryResponse); + + /** RunQueryResponse transaction. */ + public transaction: Uint8Array; + + /** RunQueryResponse document. */ + public document?: (google.firestore.v1beta1.IDocument|null); + + /** RunQueryResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryResponse skippedResults. */ + public skippedResults: number; + + /** + * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.RunQueryResponse; + + /** + * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. + * @param message RunQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.RunQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionQueryRequest. */ + interface IPartitionQueryRequest { + + /** PartitionQueryRequest parent */ + parent?: (string|null); + + /** PartitionQueryRequest structuredQuery */ + structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + + /** PartitionQueryRequest partitionCount */ + partitionCount?: (number|string|null); + + /** PartitionQueryRequest pageToken */ + pageToken?: (string|null); + + /** PartitionQueryRequest pageSize */ + pageSize?: (number|null); + } + + /** Represents a PartitionQueryRequest. */ + class PartitionQueryRequest implements IPartitionQueryRequest { + + /** + * Constructs a new PartitionQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IPartitionQueryRequest); + + /** PartitionQueryRequest parent. */ + public parent: string; + + /** PartitionQueryRequest structuredQuery. */ + public structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + + /** PartitionQueryRequest partitionCount. */ + public partitionCount: (number|string); + + /** PartitionQueryRequest pageToken. */ + public pageToken: string; + + /** PartitionQueryRequest pageSize. */ + public pageSize: number; + + /** PartitionQueryRequest queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a PartitionQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.PartitionQueryRequest; + + /** + * Creates a plain object from a PartitionQueryRequest message. Also converts values to other types if specified. + * @param message PartitionQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.PartitionQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionQueryResponse. */ + interface IPartitionQueryResponse { + + /** PartitionQueryResponse partitions */ + partitions?: (google.firestore.v1beta1.ICursor[]|null); + + /** PartitionQueryResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a PartitionQueryResponse. */ + class PartitionQueryResponse implements IPartitionQueryResponse { + + /** + * Constructs a new PartitionQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IPartitionQueryResponse); + + /** PartitionQueryResponse partitions. */ + public partitions: google.firestore.v1beta1.ICursor[]; + + /** PartitionQueryResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a PartitionQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.PartitionQueryResponse; + + /** + * Creates a plain object from a PartitionQueryResponse message. Also converts values to other types if specified. + * @param message PartitionQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.PartitionQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WriteRequest. */ + interface IWriteRequest { + + /** WriteRequest database */ + database?: (string|null); + + /** WriteRequest streamId */ + streamId?: (string|null); + + /** WriteRequest writes */ + writes?: (google.firestore.v1beta1.IWrite[]|null); + + /** WriteRequest streamToken */ + streamToken?: (Uint8Array|null); + + /** WriteRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a WriteRequest. */ + class WriteRequest implements IWriteRequest { + + /** + * Constructs a new WriteRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IWriteRequest); + + /** WriteRequest database. */ + public database: string; + + /** WriteRequest streamId. */ + public streamId: string; + + /** WriteRequest writes. */ + public writes: google.firestore.v1beta1.IWrite[]; + + /** WriteRequest streamToken. */ + public streamToken: Uint8Array; + + /** WriteRequest labels. */ + public labels: { [k: string]: string }; + + /** + * Creates a WriteRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.WriteRequest; + + /** + * Creates a plain object from a WriteRequest message. Also converts values to other types if specified. + * @param message WriteRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.WriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WriteResponse. */ + interface IWriteResponse { + + /** WriteResponse streamId */ + streamId?: (string|null); + + /** WriteResponse streamToken */ + streamToken?: (Uint8Array|null); + + /** WriteResponse writeResults */ + writeResults?: (google.firestore.v1beta1.IWriteResult[]|null); + + /** WriteResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a WriteResponse. */ + class WriteResponse implements IWriteResponse { + + /** + * Constructs a new WriteResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IWriteResponse); + + /** WriteResponse streamId. */ + public streamId: string; + + /** WriteResponse streamToken. */ + public streamToken: Uint8Array; + + /** WriteResponse writeResults. */ + public writeResults: google.firestore.v1beta1.IWriteResult[]; + + /** WriteResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a WriteResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.WriteResponse; + + /** + * Creates a plain object from a WriteResponse message. Also converts values to other types if specified. + * @param message WriteResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.WriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListenRequest. */ + interface IListenRequest { + + /** ListenRequest database */ + database?: (string|null); + + /** ListenRequest addTarget */ + addTarget?: (google.firestore.v1beta1.ITarget|null); + + /** ListenRequest removeTarget */ + removeTarget?: (number|null); + + /** ListenRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a ListenRequest. */ + class ListenRequest implements IListenRequest { + + /** + * Constructs a new ListenRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListenRequest); + + /** ListenRequest database. */ + public database: string; + + /** ListenRequest addTarget. */ + public addTarget?: (google.firestore.v1beta1.ITarget|null); + + /** ListenRequest removeTarget. */ + public removeTarget?: (number|null); + + /** ListenRequest labels. */ + public labels: { [k: string]: string }; + + /** ListenRequest targetChange. */ + public targetChange?: ("addTarget"|"removeTarget"); + + /** + * Creates a ListenRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListenRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListenRequest; + + /** + * Creates a plain object from a ListenRequest message. Also converts values to other types if specified. + * @param message ListenRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListenRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListenRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListenRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListenResponse. */ + interface IListenResponse { + + /** ListenResponse targetChange */ + targetChange?: (google.firestore.v1beta1.ITargetChange|null); + + /** ListenResponse documentChange */ + documentChange?: (google.firestore.v1beta1.IDocumentChange|null); + + /** ListenResponse documentDelete */ + documentDelete?: (google.firestore.v1beta1.IDocumentDelete|null); + + /** ListenResponse documentRemove */ + documentRemove?: (google.firestore.v1beta1.IDocumentRemove|null); + + /** ListenResponse filter */ + filter?: (google.firestore.v1beta1.IExistenceFilter|null); + } + + /** Represents a ListenResponse. */ + class ListenResponse implements IListenResponse { + + /** + * Constructs a new ListenResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListenResponse); + + /** ListenResponse targetChange. */ + public targetChange?: (google.firestore.v1beta1.ITargetChange|null); + + /** ListenResponse documentChange. */ + public documentChange?: (google.firestore.v1beta1.IDocumentChange|null); + + /** ListenResponse documentDelete. */ + public documentDelete?: (google.firestore.v1beta1.IDocumentDelete|null); + + /** ListenResponse documentRemove. */ + public documentRemove?: (google.firestore.v1beta1.IDocumentRemove|null); + + /** ListenResponse filter. */ + public filter?: (google.firestore.v1beta1.IExistenceFilter|null); + + /** ListenResponse responseType. */ + public responseType?: ("targetChange"|"documentChange"|"documentDelete"|"documentRemove"|"filter"); + + /** + * Creates a ListenResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListenResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListenResponse; + + /** + * Creates a plain object from a ListenResponse message. Also converts values to other types if specified. + * @param message ListenResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListenResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListenResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListenResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Target. */ + interface ITarget { + + /** Target query */ + query?: (google.firestore.v1beta1.Target.IQueryTarget|null); + + /** Target documents */ + documents?: (google.firestore.v1beta1.Target.IDocumentsTarget|null); + + /** Target resumeToken */ + resumeToken?: (Uint8Array|null); + + /** Target readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** Target targetId */ + targetId?: (number|null); + + /** Target once */ + once?: (boolean|null); + } + + /** Represents a Target. */ + class Target implements ITarget { + + /** + * Constructs a new Target. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ITarget); + + /** Target query. */ + public query?: (google.firestore.v1beta1.Target.IQueryTarget|null); + + /** Target documents. */ + public documents?: (google.firestore.v1beta1.Target.IDocumentsTarget|null); + + /** Target resumeToken. */ + public resumeToken?: (Uint8Array|null); + + /** Target readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** Target targetId. */ + public targetId: number; + + /** Target once. */ + public once: boolean; + + /** Target targetType. */ + public targetType?: ("query"|"documents"); + + /** Target resumeType. */ + public resumeType?: ("resumeToken"|"readTime"); + + /** + * Creates a Target message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Target + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Target; + + /** + * Creates a plain object from a Target message. Also converts values to other types if specified. + * @param message Target + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Target, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Target to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Target + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Target { + + /** Properties of a DocumentsTarget. */ + interface IDocumentsTarget { + + /** DocumentsTarget documents */ + documents?: (string[]|null); + } + + /** Represents a DocumentsTarget. */ + class DocumentsTarget implements IDocumentsTarget { + + /** + * Constructs a new DocumentsTarget. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.Target.IDocumentsTarget); + + /** DocumentsTarget documents. */ + public documents: string[]; + + /** + * Creates a DocumentsTarget message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentsTarget + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Target.DocumentsTarget; + + /** + * Creates a plain object from a DocumentsTarget message. Also converts values to other types if specified. + * @param message DocumentsTarget + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Target.DocumentsTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentsTarget to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentsTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a QueryTarget. */ + interface IQueryTarget { + + /** QueryTarget parent */ + parent?: (string|null); + + /** QueryTarget structuredQuery */ + structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + } + + /** Represents a QueryTarget. */ + class QueryTarget implements IQueryTarget { + + /** + * Constructs a new QueryTarget. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.Target.IQueryTarget); + + /** QueryTarget parent. */ + public parent: string; + + /** QueryTarget structuredQuery. */ + public structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + + /** QueryTarget queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a QueryTarget message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns QueryTarget + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Target.QueryTarget; + + /** + * Creates a plain object from a QueryTarget message. Also converts values to other types if specified. + * @param message QueryTarget + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Target.QueryTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this QueryTarget to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for QueryTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a TargetChange. */ + interface ITargetChange { + + /** TargetChange targetChangeType */ + targetChangeType?: (google.firestore.v1beta1.TargetChange.TargetChangeType|null); + + /** TargetChange targetIds */ + targetIds?: (number[]|null); + + /** TargetChange cause */ + cause?: (google.rpc.IStatus|null); + + /** TargetChange resumeToken */ + resumeToken?: (Uint8Array|null); + + /** TargetChange readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a TargetChange. */ + class TargetChange implements ITargetChange { + + /** + * Constructs a new TargetChange. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ITargetChange); + + /** TargetChange targetChangeType. */ + public targetChangeType: google.firestore.v1beta1.TargetChange.TargetChangeType; + + /** TargetChange targetIds. */ + public targetIds: number[]; + + /** TargetChange cause. */ + public cause?: (google.rpc.IStatus|null); + + /** TargetChange resumeToken. */ + public resumeToken: Uint8Array; + + /** TargetChange readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a TargetChange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TargetChange + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.TargetChange; + + /** + * Creates a plain object from a TargetChange message. Also converts values to other types if specified. + * @param message TargetChange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.TargetChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TargetChange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TargetChange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TargetChange { + + /** TargetChangeType enum. */ + type TargetChangeType = + "NO_CHANGE"| "ADD"| "REMOVE"| "CURRENT"| "RESET"; + } + + /** Properties of a ListCollectionIdsRequest. */ + interface IListCollectionIdsRequest { + + /** ListCollectionIdsRequest parent */ + parent?: (string|null); + + /** ListCollectionIdsRequest pageSize */ + pageSize?: (number|null); + + /** ListCollectionIdsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListCollectionIdsRequest. */ + class ListCollectionIdsRequest implements IListCollectionIdsRequest { + + /** + * Constructs a new ListCollectionIdsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListCollectionIdsRequest); + + /** ListCollectionIdsRequest parent. */ + public parent: string; + + /** ListCollectionIdsRequest pageSize. */ + public pageSize: number; + + /** ListCollectionIdsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a ListCollectionIdsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCollectionIdsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListCollectionIdsRequest; + + /** + * Creates a plain object from a ListCollectionIdsRequest message. Also converts values to other types if specified. + * @param message ListCollectionIdsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListCollectionIdsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCollectionIdsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCollectionIdsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListCollectionIdsResponse. */ + interface IListCollectionIdsResponse { + + /** ListCollectionIdsResponse collectionIds */ + collectionIds?: (string[]|null); + + /** ListCollectionIdsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListCollectionIdsResponse. */ + class ListCollectionIdsResponse implements IListCollectionIdsResponse { + + /** + * Constructs a new ListCollectionIdsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListCollectionIdsResponse); + + /** ListCollectionIdsResponse collectionIds. */ + public collectionIds: string[]; + + /** ListCollectionIdsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListCollectionIdsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCollectionIdsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListCollectionIdsResponse; + + /** + * Creates a plain object from a ListCollectionIdsResponse message. Also converts values to other types if specified. + * @param message ListCollectionIdsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListCollectionIdsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCollectionIdsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCollectionIdsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchWriteRequest. */ + interface IBatchWriteRequest { + + /** BatchWriteRequest database */ + database?: (string|null); + + /** BatchWriteRequest writes */ + writes?: (google.firestore.v1beta1.IWrite[]|null); + + /** BatchWriteRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a BatchWriteRequest. */ + class BatchWriteRequest implements IBatchWriteRequest { + + /** + * Constructs a new BatchWriteRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBatchWriteRequest); + + /** BatchWriteRequest database. */ + public database: string; + + /** BatchWriteRequest writes. */ + public writes: google.firestore.v1beta1.IWrite[]; + + /** BatchWriteRequest labels. */ + public labels: { [k: string]: string }; + + /** + * Creates a BatchWriteRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchWriteRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BatchWriteRequest; + + /** + * Creates a plain object from a BatchWriteRequest message. Also converts values to other types if specified. + * @param message BatchWriteRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BatchWriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchWriteRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchWriteResponse. */ + interface IBatchWriteResponse { + + /** BatchWriteResponse writeResults */ + writeResults?: (google.firestore.v1beta1.IWriteResult[]|null); + + /** BatchWriteResponse status */ + status?: (google.rpc.IStatus[]|null); + } + + /** Represents a BatchWriteResponse. */ + class BatchWriteResponse implements IBatchWriteResponse { + + /** + * Constructs a new BatchWriteResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBatchWriteResponse); + + /** BatchWriteResponse writeResults. */ + public writeResults: google.firestore.v1beta1.IWriteResult[]; + + /** BatchWriteResponse status. */ + public status: google.rpc.IStatus[]; + + /** + * Creates a BatchWriteResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchWriteResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BatchWriteResponse; + + /** + * Creates a plain object from a BatchWriteResponse message. Also converts values to other types if specified. + * @param message BatchWriteResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BatchWriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchWriteResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StructuredQuery. */ + interface IStructuredQuery { + + /** StructuredQuery select */ + select?: (google.firestore.v1beta1.StructuredQuery.IProjection|null); + + /** StructuredQuery from */ + from?: (google.firestore.v1beta1.StructuredQuery.ICollectionSelector[]|null); + + /** StructuredQuery where */ + where?: (google.firestore.v1beta1.StructuredQuery.IFilter|null); + + /** StructuredQuery orderBy */ + orderBy?: (google.firestore.v1beta1.StructuredQuery.IOrder[]|null); + + /** StructuredQuery startAt */ + startAt?: (google.firestore.v1beta1.ICursor|null); + + /** StructuredQuery endAt */ + endAt?: (google.firestore.v1beta1.ICursor|null); + + /** StructuredQuery offset */ + offset?: (number|null); + + /** StructuredQuery limit */ + limit?: (google.protobuf.IInt32Value|null); + } + + /** Represents a StructuredQuery. */ + class StructuredQuery implements IStructuredQuery { + + /** + * Constructs a new StructuredQuery. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IStructuredQuery); + + /** StructuredQuery select. */ + public select?: (google.firestore.v1beta1.StructuredQuery.IProjection|null); + + /** StructuredQuery from. */ + public from: google.firestore.v1beta1.StructuredQuery.ICollectionSelector[]; + + /** StructuredQuery where. */ + public where?: (google.firestore.v1beta1.StructuredQuery.IFilter|null); + + /** StructuredQuery orderBy. */ + public orderBy: google.firestore.v1beta1.StructuredQuery.IOrder[]; + + /** StructuredQuery startAt. */ + public startAt?: (google.firestore.v1beta1.ICursor|null); + + /** StructuredQuery endAt. */ + public endAt?: (google.firestore.v1beta1.ICursor|null); + + /** StructuredQuery offset. */ + public offset: number; + + /** StructuredQuery limit. */ + public limit?: (google.protobuf.IInt32Value|null); + + /** + * Creates a StructuredQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StructuredQuery + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery; + + /** + * Creates a plain object from a StructuredQuery message. Also converts values to other types if specified. + * @param message StructuredQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StructuredQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StructuredQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace StructuredQuery { + + /** Properties of a CollectionSelector. */ + interface ICollectionSelector { + + /** CollectionSelector collectionId */ + collectionId?: (string|null); + + /** CollectionSelector allDescendants */ + allDescendants?: (boolean|null); + } + + /** Represents a CollectionSelector. */ + class CollectionSelector implements ICollectionSelector { + + /** + * Constructs a new CollectionSelector. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.ICollectionSelector); + + /** CollectionSelector collectionId. */ + public collectionId: string; + + /** CollectionSelector allDescendants. */ + public allDescendants: boolean; + + /** + * Creates a CollectionSelector message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CollectionSelector + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.CollectionSelector; + + /** + * Creates a plain object from a CollectionSelector message. Also converts values to other types if specified. + * @param message CollectionSelector + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.CollectionSelector, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CollectionSelector to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CollectionSelector + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Filter. */ + interface IFilter { + + /** Filter compositeFilter */ + compositeFilter?: (google.firestore.v1beta1.StructuredQuery.ICompositeFilter|null); + + /** Filter fieldFilter */ + fieldFilter?: (google.firestore.v1beta1.StructuredQuery.IFieldFilter|null); + + /** Filter unaryFilter */ + unaryFilter?: (google.firestore.v1beta1.StructuredQuery.IUnaryFilter|null); + } + + /** Represents a Filter. */ + class Filter implements IFilter { + + /** + * Constructs a new Filter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IFilter); + + /** Filter compositeFilter. */ + public compositeFilter?: (google.firestore.v1beta1.StructuredQuery.ICompositeFilter|null); + + /** Filter fieldFilter. */ + public fieldFilter?: (google.firestore.v1beta1.StructuredQuery.IFieldFilter|null); + + /** Filter unaryFilter. */ + public unaryFilter?: (google.firestore.v1beta1.StructuredQuery.IUnaryFilter|null); + + /** Filter filterType. */ + public filterType?: ("compositeFilter"|"fieldFilter"|"unaryFilter"); + + /** + * Creates a Filter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Filter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.Filter; + + /** + * Creates a plain object from a Filter message. Also converts values to other types if specified. + * @param message Filter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.Filter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Filter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Filter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CompositeFilter. */ + interface ICompositeFilter { + + /** CompositeFilter op */ + op?: (google.firestore.v1beta1.StructuredQuery.CompositeFilter.Operator|null); + + /** CompositeFilter filters */ + filters?: (google.firestore.v1beta1.StructuredQuery.IFilter[]|null); + } + + /** Represents a CompositeFilter. */ + class CompositeFilter implements ICompositeFilter { + + /** + * Constructs a new CompositeFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.ICompositeFilter); + + /** CompositeFilter op. */ + public op: google.firestore.v1beta1.StructuredQuery.CompositeFilter.Operator; + + /** CompositeFilter filters. */ + public filters: google.firestore.v1beta1.StructuredQuery.IFilter[]; + + /** + * Creates a CompositeFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CompositeFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.CompositeFilter; + + /** + * Creates a plain object from a CompositeFilter message. Also converts values to other types if specified. + * @param message CompositeFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.CompositeFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CompositeFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CompositeFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace CompositeFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "AND"; + } + + /** Properties of a FieldFilter. */ + interface IFieldFilter { + + /** FieldFilter field */ + field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + + /** FieldFilter op */ + op?: (google.firestore.v1beta1.StructuredQuery.FieldFilter.Operator|null); + + /** FieldFilter value */ + value?: (google.firestore.v1beta1.IValue|null); + } + + /** Represents a FieldFilter. */ + class FieldFilter implements IFieldFilter { + + /** + * Constructs a new FieldFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IFieldFilter); + + /** FieldFilter field. */ + public field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + + /** FieldFilter op. */ + public op: google.firestore.v1beta1.StructuredQuery.FieldFilter.Operator; + + /** FieldFilter value. */ + public value?: (google.firestore.v1beta1.IValue|null); + + /** + * Creates a FieldFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.FieldFilter; + + /** + * Creates a plain object from a FieldFilter message. Also converts values to other types if specified. + * @param message FieldFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.FieldFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "LESS_THAN"| "LESS_THAN_OR_EQUAL"| "GREATER_THAN"| "GREATER_THAN_OR_EQUAL"| "EQUAL"| "NOT_EQUAL"| "ARRAY_CONTAINS"| "IN"| "ARRAY_CONTAINS_ANY"| "NOT_IN"; + } + + /** Properties of an UnaryFilter. */ + interface IUnaryFilter { + + /** UnaryFilter op */ + op?: (google.firestore.v1beta1.StructuredQuery.UnaryFilter.Operator|null); + + /** UnaryFilter field */ + field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + } + + /** Represents an UnaryFilter. */ + class UnaryFilter implements IUnaryFilter { + + /** + * Constructs a new UnaryFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IUnaryFilter); + + /** UnaryFilter op. */ + public op: google.firestore.v1beta1.StructuredQuery.UnaryFilter.Operator; + + /** UnaryFilter field. */ + public field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + + /** UnaryFilter operandType. */ + public operandType?: "field"; + + /** + * Creates an UnaryFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UnaryFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.UnaryFilter; + + /** + * Creates a plain object from an UnaryFilter message. Also converts values to other types if specified. + * @param message UnaryFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.UnaryFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UnaryFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UnaryFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UnaryFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "IS_NAN"| "IS_NULL"| "IS_NOT_NAN"| "IS_NOT_NULL"; + } + + /** Properties of a FieldReference. */ + interface IFieldReference { + + /** FieldReference fieldPath */ + fieldPath?: (string|null); + } + + /** Represents a FieldReference. */ + class FieldReference implements IFieldReference { + + /** + * Constructs a new FieldReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IFieldReference); + + /** FieldReference fieldPath. */ + public fieldPath: string; + + /** + * Creates a FieldReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldReference + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.FieldReference; + + /** + * Creates a plain object from a FieldReference message. Also converts values to other types if specified. + * @param message FieldReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.FieldReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Order. */ + interface IOrder { + + /** Order field */ + field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + + /** Order direction */ + direction?: (google.firestore.v1beta1.StructuredQuery.Direction|null); + } + + /** Represents an Order. */ + class Order implements IOrder { + + /** + * Constructs a new Order. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IOrder); + + /** Order field. */ + public field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + + /** Order direction. */ + public direction: google.firestore.v1beta1.StructuredQuery.Direction; + + /** + * Creates an Order message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Order + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.Order; + + /** + * Creates a plain object from an Order message. Also converts values to other types if specified. + * @param message Order + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.Order, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Order to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Order + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Projection. */ + interface IProjection { + + /** Projection fields */ + fields?: (google.firestore.v1beta1.StructuredQuery.IFieldReference[]|null); + } + + /** Represents a Projection. */ + class Projection implements IProjection { + + /** + * Constructs a new Projection. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IProjection); + + /** Projection fields. */ + public fields: google.firestore.v1beta1.StructuredQuery.IFieldReference[]; + + /** + * Creates a Projection message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Projection + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.Projection; + + /** + * Creates a plain object from a Projection message. Also converts values to other types if specified. + * @param message Projection + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.Projection, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Projection to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Projection + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Direction enum. */ + type Direction = + "DIRECTION_UNSPECIFIED"| "ASCENDING"| "DESCENDING"; + } + + /** Properties of a Cursor. */ + interface ICursor { + + /** Cursor values */ + values?: (google.firestore.v1beta1.IValue[]|null); + + /** Cursor before */ + before?: (boolean|null); + } + + /** Represents a Cursor. */ + class Cursor implements ICursor { + + /** + * Constructs a new Cursor. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ICursor); + + /** Cursor values. */ + public values: google.firestore.v1beta1.IValue[]; + + /** Cursor before. */ + public before: boolean; + + /** + * Creates a Cursor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Cursor + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Cursor; + + /** + * Creates a plain object from a Cursor message. Also converts values to other types if specified. + * @param message Cursor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Cursor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Cursor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Cursor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Write. */ + interface IWrite { + + /** Write update */ + update?: (google.firestore.v1beta1.IDocument|null); + + /** Write delete */ + "delete"?: (string|null); + + /** Write transform */ + transform?: (google.firestore.v1beta1.IDocumentTransform|null); + + /** Write updateMask */ + updateMask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** Write updateTransforms */ + updateTransforms?: (google.firestore.v1beta1.DocumentTransform.IFieldTransform[]|null); + + /** Write currentDocument */ + currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + } + + /** Represents a Write. */ + class Write implements IWrite { + + /** + * Constructs a new Write. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IWrite); + + /** Write update. */ + public update?: (google.firestore.v1beta1.IDocument|null); + + /** Write delete. */ + public delete?: (string|null); + + /** Write transform. */ + public transform?: (google.firestore.v1beta1.IDocumentTransform|null); + + /** Write updateMask. */ + public updateMask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** Write updateTransforms. */ + public updateTransforms: google.firestore.v1beta1.DocumentTransform.IFieldTransform[]; + + /** Write currentDocument. */ + public currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + + /** Write operation. */ + public operation?: ("update"|"delete"|"transform"); + + /** + * Creates a Write message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Write + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Write; + + /** + * Creates a plain object from a Write message. Also converts values to other types if specified. + * @param message Write + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Write, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Write to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Write + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentTransform. */ + interface IDocumentTransform { + + /** DocumentTransform document */ + document?: (string|null); + + /** DocumentTransform fieldTransforms */ + fieldTransforms?: (google.firestore.v1beta1.DocumentTransform.IFieldTransform[]|null); + } + + /** Represents a DocumentTransform. */ + class DocumentTransform implements IDocumentTransform { + + /** + * Constructs a new DocumentTransform. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocumentTransform); + + /** DocumentTransform document. */ + public document: string; + + /** DocumentTransform fieldTransforms. */ + public fieldTransforms: google.firestore.v1beta1.DocumentTransform.IFieldTransform[]; + + /** + * Creates a DocumentTransform message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentTransform + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentTransform; + + /** + * Creates a plain object from a DocumentTransform message. Also converts values to other types if specified. + * @param message DocumentTransform + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentTransform to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DocumentTransform { + + /** Properties of a FieldTransform. */ + interface IFieldTransform { + + /** FieldTransform fieldPath */ + fieldPath?: (string|null); + + /** FieldTransform setToServerValue */ + setToServerValue?: (google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue|null); + + /** FieldTransform increment */ + increment?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform maximum */ + maximum?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform minimum */ + minimum?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform appendMissingElements */ + appendMissingElements?: (google.firestore.v1beta1.IArrayValue|null); + + /** FieldTransform removeAllFromArray */ + removeAllFromArray?: (google.firestore.v1beta1.IArrayValue|null); + } + + /** Represents a FieldTransform. */ + class FieldTransform implements IFieldTransform { + + /** + * Constructs a new FieldTransform. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.DocumentTransform.IFieldTransform); + + /** FieldTransform fieldPath. */ + public fieldPath: string; + + /** FieldTransform setToServerValue. */ + public setToServerValue?: (google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue|null); + + /** FieldTransform increment. */ + public increment?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform maximum. */ + public maximum?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform minimum. */ + public minimum?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform appendMissingElements. */ + public appendMissingElements?: (google.firestore.v1beta1.IArrayValue|null); + + /** FieldTransform removeAllFromArray. */ + public removeAllFromArray?: (google.firestore.v1beta1.IArrayValue|null); + + /** FieldTransform transformType. */ + public transformType?: ("setToServerValue"|"increment"|"maximum"|"minimum"|"appendMissingElements"|"removeAllFromArray"); + + /** + * Creates a FieldTransform message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldTransform + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentTransform.FieldTransform; + + /** + * Creates a plain object from a FieldTransform message. Also converts values to other types if specified. + * @param message FieldTransform + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentTransform.FieldTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldTransform to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldTransform { + + /** ServerValue enum. */ + type ServerValue = + "SERVER_VALUE_UNSPECIFIED"| "REQUEST_TIME"; + } + } + + /** Properties of a WriteResult. */ + interface IWriteResult { + + /** WriteResult updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** WriteResult transformResults */ + transformResults?: (google.firestore.v1beta1.IValue[]|null); + } + + /** Represents a WriteResult. */ + class WriteResult implements IWriteResult { + + /** + * Constructs a new WriteResult. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IWriteResult); + + /** WriteResult updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** WriteResult transformResults. */ + public transformResults: google.firestore.v1beta1.IValue[]; + + /** + * Creates a WriteResult message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteResult + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.WriteResult; + + /** + * Creates a plain object from a WriteResult message. Also converts values to other types if specified. + * @param message WriteResult + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.WriteResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteResult to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteResult + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentChange. */ + interface IDocumentChange { + + /** DocumentChange document */ + document?: (google.firestore.v1beta1.IDocument|null); + + /** DocumentChange targetIds */ + targetIds?: (number[]|null); + + /** DocumentChange removedTargetIds */ + removedTargetIds?: (number[]|null); + } + + /** Represents a DocumentChange. */ + class DocumentChange implements IDocumentChange { + + /** + * Constructs a new DocumentChange. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocumentChange); + + /** DocumentChange document. */ + public document?: (google.firestore.v1beta1.IDocument|null); + + /** DocumentChange targetIds. */ + public targetIds: number[]; + + /** DocumentChange removedTargetIds. */ + public removedTargetIds: number[]; + + /** + * Creates a DocumentChange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentChange + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentChange; + + /** + * Creates a plain object from a DocumentChange message. Also converts values to other types if specified. + * @param message DocumentChange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentChange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentChange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentDelete. */ + interface IDocumentDelete { + + /** DocumentDelete document */ + document?: (string|null); + + /** DocumentDelete removedTargetIds */ + removedTargetIds?: (number[]|null); + + /** DocumentDelete readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a DocumentDelete. */ + class DocumentDelete implements IDocumentDelete { + + /** + * Constructs a new DocumentDelete. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocumentDelete); + + /** DocumentDelete document. */ + public document: string; + + /** DocumentDelete removedTargetIds. */ + public removedTargetIds: number[]; + + /** DocumentDelete readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a DocumentDelete message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentDelete + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentDelete; + + /** + * Creates a plain object from a DocumentDelete message. Also converts values to other types if specified. + * @param message DocumentDelete + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentDelete, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentDelete to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentDelete + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentRemove. */ + interface IDocumentRemove { + + /** DocumentRemove document */ + document?: (string|null); + + /** DocumentRemove removedTargetIds */ + removedTargetIds?: (number[]|null); + + /** DocumentRemove readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a DocumentRemove. */ + class DocumentRemove implements IDocumentRemove { + + /** + * Constructs a new DocumentRemove. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocumentRemove); + + /** DocumentRemove document. */ + public document: string; + + /** DocumentRemove removedTargetIds. */ + public removedTargetIds: number[]; + + /** DocumentRemove readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a DocumentRemove message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentRemove + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentRemove; + + /** + * Creates a plain object from a DocumentRemove message. Also converts values to other types if specified. + * @param message DocumentRemove + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentRemove, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentRemove to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentRemove + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExistenceFilter. */ + interface IExistenceFilter { + + /** ExistenceFilter targetId */ + targetId?: (number|null); + + /** ExistenceFilter count */ + count?: (number|null); + } + + /** Represents an ExistenceFilter. */ + class ExistenceFilter implements IExistenceFilter { + + /** + * Constructs a new ExistenceFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IExistenceFilter); + + /** ExistenceFilter targetId. */ + public targetId: number; + + /** ExistenceFilter count. */ + public count: number; + + /** + * Creates an ExistenceFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExistenceFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ExistenceFilter; + + /** + * Creates a plain object from an ExistenceFilter message. Also converts values to other types if specified. + * @param message ExistenceFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ExistenceFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExistenceFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExistenceFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UndeliverableFirstGenEvent. */ + interface IUndeliverableFirstGenEvent { + + /** UndeliverableFirstGenEvent message */ + message?: (string|null); + + /** UndeliverableFirstGenEvent reason */ + reason?: (google.firestore.v1beta1.UndeliverableFirstGenEvent.Reason|null); + + /** UndeliverableFirstGenEvent documentName */ + documentName?: (string|null); + + /** UndeliverableFirstGenEvent documentChangeType */ + documentChangeType?: (google.firestore.v1beta1.UndeliverableFirstGenEvent.DocumentChangeType|null); + + /** UndeliverableFirstGenEvent functionName */ + functionName?: (string[]|null); + + /** UndeliverableFirstGenEvent triggeredTime */ + triggeredTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an UndeliverableFirstGenEvent. */ + class UndeliverableFirstGenEvent implements IUndeliverableFirstGenEvent { + + /** + * Constructs a new UndeliverableFirstGenEvent. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IUndeliverableFirstGenEvent); + + /** UndeliverableFirstGenEvent message. */ + public message: string; + + /** UndeliverableFirstGenEvent reason. */ + public reason: google.firestore.v1beta1.UndeliverableFirstGenEvent.Reason; + + /** UndeliverableFirstGenEvent documentName. */ + public documentName: string; + + /** UndeliverableFirstGenEvent documentChangeType. */ + public documentChangeType: google.firestore.v1beta1.UndeliverableFirstGenEvent.DocumentChangeType; + + /** UndeliverableFirstGenEvent functionName. */ + public functionName: string[]; + + /** UndeliverableFirstGenEvent triggeredTime. */ + public triggeredTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates an UndeliverableFirstGenEvent message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UndeliverableFirstGenEvent + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.UndeliverableFirstGenEvent; + + /** + * Creates a plain object from an UndeliverableFirstGenEvent message. Also converts values to other types if specified. + * @param message UndeliverableFirstGenEvent + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.UndeliverableFirstGenEvent, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UndeliverableFirstGenEvent to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UndeliverableFirstGenEvent + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UndeliverableFirstGenEvent { + + /** Reason enum. */ + type Reason = + "REASON_UNSPECIFIED"| "EXCEEDING_SIZE_LIMIT"; + + /** DocumentChangeType enum. */ + type DocumentChangeType = + "DOCUMENT_CHANGE_TYPE_UNSPECIFIED"| "CREATE"| "DELETE"| "UPDATE"; + } + } + } + + /** Namespace type. */ + namespace type { + + /** Properties of a LatLng. */ + interface ILatLng { + + /** LatLng latitude */ + latitude?: (number|null); + + /** LatLng longitude */ + longitude?: (number|null); + } + + /** Represents a LatLng. */ + class LatLng implements ILatLng { + + /** + * Constructs a new LatLng. + * @param [properties] Properties to set + */ + constructor(properties?: google.type.ILatLng); + + /** LatLng latitude. */ + public latitude: number; + + /** LatLng longitude. */ + public longitude: number; + + /** + * Creates a LatLng message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LatLng + */ + public static fromObject(object: { [k: string]: any }): google.type.LatLng; + + /** + * Creates a plain object from a LatLng message. Also converts values to other types if specified. + * @param message LatLng + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.type.LatLng, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LatLng to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LatLng + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** DayOfWeek enum. */ + type DayOfWeek = + "DAY_OF_WEEK_UNSPECIFIED"| "MONDAY"| "TUESDAY"| "WEDNESDAY"| "THURSDAY"| "FRIDAY"| "SATURDAY"| "SUNDAY"; + } + + /** Namespace api. */ + namespace api { + + /** Properties of a Http. */ + interface IHttp { + + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); + + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); + } + + /** Represents a Http. */ + class Http implements IHttp { + + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); + + /** Http rules. */ + public rules: google.api.IHttpRule[]; + + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Http + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a HttpRule. */ + interface IHttpRule { + + /** HttpRule selector */ + selector?: (string|null); + + /** HttpRule get */ + get?: (string|null); + + /** HttpRule put */ + put?: (string|null); + + /** HttpRule post */ + post?: (string|null); + + /** HttpRule delete */ + "delete"?: (string|null); + + /** HttpRule patch */ + patch?: (string|null); + + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body */ + body?: (string|null); + + /** HttpRule responseBody */ + responseBody?: (string|null); + + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); + } + + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { + + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); + + /** HttpRule selector. */ + public selector: string; + + /** HttpRule get. */ + public get?: (string|null); + + /** HttpRule put. */ + public put?: (string|null); + + /** HttpRule post. */ + public post?: (string|null); + + /** HttpRule delete. */ + public delete?: (string|null); + + /** HttpRule patch. */ + public patch?: (string|null); + + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body. */ + public body: string; + + /** HttpRule responseBody. */ + public responseBody: string; + + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; + + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for HttpRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { + + /** CustomHttpPattern kind */ + kind?: (string|null); + + /** CustomHttpPattern path */ + path?: (string|null); + } + + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { + + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); + + /** CustomHttpPattern kind. */ + public kind: string; + + /** CustomHttpPattern path. */ + public path: string; + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CustomHttpPattern + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommonLanguageSettings. */ + interface ICommonLanguageSettings { + + /** CommonLanguageSettings referenceDocsUri */ + referenceDocsUri?: (string|null); + + /** CommonLanguageSettings destinations */ + destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + } + + /** Represents a CommonLanguageSettings. */ + class CommonLanguageSettings implements ICommonLanguageSettings { + + /** + * Constructs a new CommonLanguageSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICommonLanguageSettings); + + /** CommonLanguageSettings referenceDocsUri. */ + public referenceDocsUri: string; + + /** CommonLanguageSettings destinations. */ + public destinations: google.api.ClientLibraryDestination[]; + + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommonLanguageSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CommonLanguageSettings; + + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @param message CommonLanguageSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CommonLanguageSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommonLanguageSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommonLanguageSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ClientLibrarySettings. */ + interface IClientLibrarySettings { + + /** ClientLibrarySettings version */ + version?: (string|null); + + /** ClientLibrarySettings launchStage */ + launchStage?: (google.api.LaunchStage|null); + + /** ClientLibrarySettings restNumericEnums */ + restNumericEnums?: (boolean|null); + + /** ClientLibrarySettings javaSettings */ + javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings */ + cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings */ + phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings */ + pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings */ + nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings */ + dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings */ + rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings */ + goSettings?: (google.api.IGoSettings|null); + } + + /** Represents a ClientLibrarySettings. */ + class ClientLibrarySettings implements IClientLibrarySettings { + + /** + * Constructs a new ClientLibrarySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IClientLibrarySettings); + + /** ClientLibrarySettings version. */ + public version: string; + + /** ClientLibrarySettings launchStage. */ + public launchStage: google.api.LaunchStage; + + /** ClientLibrarySettings restNumericEnums. */ + public restNumericEnums: boolean; + + /** ClientLibrarySettings javaSettings. */ + public javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings. */ + public cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings. */ + public phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings. */ + public pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings. */ + public nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings. */ + public dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings. */ + public rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings. */ + public goSettings?: (google.api.IGoSettings|null); + + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ClientLibrarySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.ClientLibrarySettings; + + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @param message ClientLibrarySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ClientLibrarySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ClientLibrarySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ClientLibrarySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Publishing. */ + interface IPublishing { + + /** Publishing methodSettings */ + methodSettings?: (google.api.IMethodSettings[]|null); + + /** Publishing newIssueUri */ + newIssueUri?: (string|null); + + /** Publishing documentationUri */ + documentationUri?: (string|null); + + /** Publishing apiShortName */ + apiShortName?: (string|null); + + /** Publishing githubLabel */ + githubLabel?: (string|null); + + /** Publishing codeownerGithubTeams */ + codeownerGithubTeams?: (string[]|null); + + /** Publishing docTagPrefix */ + docTagPrefix?: (string|null); + + /** Publishing organization */ + organization?: (google.api.ClientLibraryOrganization|null); + + /** Publishing librarySettings */ + librarySettings?: (google.api.IClientLibrarySettings[]|null); + + /** Publishing protoReferenceDocumentationUri */ + protoReferenceDocumentationUri?: (string|null); + + /** Publishing restReferenceDocumentationUri */ + restReferenceDocumentationUri?: (string|null); + } + + /** Represents a Publishing. */ + class Publishing implements IPublishing { + + /** + * Constructs a new Publishing. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPublishing); + + /** Publishing methodSettings. */ + public methodSettings: google.api.IMethodSettings[]; + + /** Publishing newIssueUri. */ + public newIssueUri: string; + + /** Publishing documentationUri. */ + public documentationUri: string; + + /** Publishing apiShortName. */ + public apiShortName: string; + + /** Publishing githubLabel. */ + public githubLabel: string; + + /** Publishing codeownerGithubTeams. */ + public codeownerGithubTeams: string[]; + + /** Publishing docTagPrefix. */ + public docTagPrefix: string; + + /** Publishing organization. */ + public organization: google.api.ClientLibraryOrganization; + + /** Publishing librarySettings. */ + public librarySettings: google.api.IClientLibrarySettings[]; + + /** Publishing protoReferenceDocumentationUri. */ + public protoReferenceDocumentationUri: string; + + /** Publishing restReferenceDocumentationUri. */ + public restReferenceDocumentationUri: string; + + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Publishing + */ + public static fromObject(object: { [k: string]: any }): google.api.Publishing; + + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @param message Publishing + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Publishing, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Publishing to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Publishing + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a JavaSettings. */ + interface IJavaSettings { + + /** JavaSettings libraryPackage */ + libraryPackage?: (string|null); + + /** JavaSettings serviceClassNames */ + serviceClassNames?: ({ [k: string]: string }|null); + + /** JavaSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a JavaSettings. */ + class JavaSettings implements IJavaSettings { + + /** + * Constructs a new JavaSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IJavaSettings); + + /** JavaSettings libraryPackage. */ + public libraryPackage: string; + + /** JavaSettings serviceClassNames. */ + public serviceClassNames: { [k: string]: string }; + + /** JavaSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns JavaSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.JavaSettings; + + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @param message JavaSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.JavaSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this JavaSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for JavaSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CppSettings. */ + interface ICppSettings { + + /** CppSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a CppSettings. */ + class CppSettings implements ICppSettings { + + /** + * Constructs a new CppSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICppSettings); + + /** CppSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CppSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CppSettings; + + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @param message CppSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CppSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CppSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CppSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PhpSettings. */ + interface IPhpSettings { + + /** PhpSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a PhpSettings. */ + class PhpSettings implements IPhpSettings { + + /** + * Constructs a new PhpSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPhpSettings); + + /** PhpSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PhpSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PhpSettings; + + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @param message PhpSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PhpSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PhpSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PhpSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PythonSettings. */ + interface IPythonSettings { + + /** PythonSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + } + + /** Represents a PythonSettings. */ + class PythonSettings implements IPythonSettings { + + /** + * Constructs a new PythonSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPythonSettings); + + /** PythonSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PythonSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings; + + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @param message PythonSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PythonSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PythonSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace PythonSettings { + + /** Properties of an ExperimentalFeatures. */ + interface IExperimentalFeatures { + + /** ExperimentalFeatures restAsyncIoEnabled */ + restAsyncIoEnabled?: (boolean|null); + + /** ExperimentalFeatures protobufPythonicTypesEnabled */ + protobufPythonicTypesEnabled?: (boolean|null); + } + + /** Represents an ExperimentalFeatures. */ + class ExperimentalFeatures implements IExperimentalFeatures { + + /** + * Constructs a new ExperimentalFeatures. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.PythonSettings.IExperimentalFeatures); + + /** ExperimentalFeatures restAsyncIoEnabled. */ + public restAsyncIoEnabled: boolean; + + /** ExperimentalFeatures protobufPythonicTypesEnabled. */ + public protobufPythonicTypesEnabled: boolean; + + /** + * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExperimentalFeatures + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. + * @param message ExperimentalFeatures + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings.ExperimentalFeatures, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExperimentalFeatures to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExperimentalFeatures + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a NodeSettings. */ + interface INodeSettings { + + /** NodeSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a NodeSettings. */ + class NodeSettings implements INodeSettings { + + /** + * Constructs a new NodeSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.INodeSettings); + + /** NodeSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NodeSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.NodeSettings; + + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @param message NodeSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.NodeSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NodeSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NodeSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DotnetSettings. */ + interface IDotnetSettings { + + /** DotnetSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + + /** DotnetSettings renamedResources */ + renamedResources?: ({ [k: string]: string }|null); + + /** DotnetSettings ignoredResources */ + ignoredResources?: (string[]|null); + + /** DotnetSettings forcedNamespaceAliases */ + forcedNamespaceAliases?: (string[]|null); + + /** DotnetSettings handwrittenSignatures */ + handwrittenSignatures?: (string[]|null); + } + + /** Represents a DotnetSettings. */ + class DotnetSettings implements IDotnetSettings { + + /** + * Constructs a new DotnetSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IDotnetSettings); + + /** DotnetSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** DotnetSettings renamedResources. */ + public renamedResources: { [k: string]: string }; + + /** DotnetSettings ignoredResources. */ + public ignoredResources: string[]; + + /** DotnetSettings forcedNamespaceAliases. */ + public forcedNamespaceAliases: string[]; + + /** DotnetSettings handwrittenSignatures. */ + public handwrittenSignatures: string[]; + + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DotnetSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.DotnetSettings; + + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @param message DotnetSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.DotnetSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DotnetSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DotnetSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RubySettings. */ + interface IRubySettings { + + /** RubySettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a RubySettings. */ + class RubySettings implements IRubySettings { + + /** + * Constructs a new RubySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRubySettings); + + /** RubySettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RubySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.RubySettings; + + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @param message RubySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RubySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RubySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RubySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GoSettings. */ + interface IGoSettings { + + /** GoSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + } + + /** Represents a GoSettings. */ + class GoSettings implements IGoSettings { + + /** + * Constructs a new GoSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IGoSettings); + + /** GoSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GoSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.GoSettings; + + /** + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @param message GoSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.GoSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GoSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GoSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodSettings. */ + interface IMethodSettings { + + /** MethodSettings selector */ + selector?: (string|null); + + /** MethodSettings longRunning */ + longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields */ + autoPopulatedFields?: (string[]|null); + } + + /** Represents a MethodSettings. */ + class MethodSettings implements IMethodSettings { + + /** + * Constructs a new MethodSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IMethodSettings); + + /** MethodSettings selector. */ + public selector: string; + + /** MethodSettings longRunning. */ + public longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields. */ + public autoPopulatedFields: string[]; + + /** + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings; + + /** + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @param message MethodSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodSettings { + + /** Properties of a LongRunning. */ + interface ILongRunning { + + /** LongRunning initialPollDelay */ + initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier */ + pollDelayMultiplier?: (number|null); + + /** LongRunning maxPollDelay */ + maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout */ + totalPollTimeout?: (google.protobuf.IDuration|null); + } + + /** Represents a LongRunning. */ + class LongRunning implements ILongRunning { + + /** + * Constructs a new LongRunning. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.MethodSettings.ILongRunning); + + /** LongRunning initialPollDelay. */ + public initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier. */ + public pollDelayMultiplier: number; + + /** LongRunning maxPollDelay. */ + public maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout. */ + public totalPollTimeout?: (google.protobuf.IDuration|null); + + /** + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LongRunning + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings.LongRunning; + + /** + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @param message LongRunning + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings.LongRunning, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LongRunning to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LongRunning + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** ClientLibraryOrganization enum. */ + type ClientLibraryOrganization = + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"| "CLOUD"| "ADS"| "PHOTOS"| "STREET_VIEW"| "SHOPPING"| "GEO"| "GENERATIVE_AI"; + + /** ClientLibraryDestination enum. */ + type ClientLibraryDestination = + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"| "GITHUB"| "PACKAGE_MANAGER"; + + /** Properties of a SelectiveGapicGeneration. */ + interface ISelectiveGapicGeneration { + + /** SelectiveGapicGeneration methods */ + methods?: (string[]|null); + + /** SelectiveGapicGeneration generateOmittedAsInternal */ + generateOmittedAsInternal?: (boolean|null); + } + + /** Represents a SelectiveGapicGeneration. */ + class SelectiveGapicGeneration implements ISelectiveGapicGeneration { + + /** + * Constructs a new SelectiveGapicGeneration. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ISelectiveGapicGeneration); + + /** SelectiveGapicGeneration methods. */ + public methods: string[]; + + /** SelectiveGapicGeneration generateOmittedAsInternal. */ + public generateOmittedAsInternal: boolean; + + /** + * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SelectiveGapicGeneration + */ + public static fromObject(object: { [k: string]: any }): google.api.SelectiveGapicGeneration; + + /** + * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. + * @param message SelectiveGapicGeneration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.SelectiveGapicGeneration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SelectiveGapicGeneration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SelectiveGapicGeneration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** LaunchStage enum. */ + type LaunchStage = + "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; + + /** FieldBehavior enum. */ + type FieldBehavior = + "FIELD_BEHAVIOR_UNSPECIFIED"| "OPTIONAL"| "REQUIRED"| "OUTPUT_ONLY"| "INPUT_ONLY"| "IMMUTABLE"| "UNORDERED_LIST"| "NON_EMPTY_DEFAULT"| "IDENTIFIER"; + + /** Properties of a ResourceDescriptor. */ + interface IResourceDescriptor { + + /** ResourceDescriptor type */ + type?: (string|null); + + /** ResourceDescriptor pattern */ + pattern?: (string[]|null); + + /** ResourceDescriptor nameField */ + nameField?: (string|null); + + /** ResourceDescriptor history */ + history?: (google.api.ResourceDescriptor.History|null); + + /** ResourceDescriptor plural */ + plural?: (string|null); + + /** ResourceDescriptor singular */ + singular?: (string|null); + + /** ResourceDescriptor style */ + style?: (google.api.ResourceDescriptor.Style[]|null); + } + + /** Represents a ResourceDescriptor. */ + class ResourceDescriptor implements IResourceDescriptor { + + /** + * Constructs a new ResourceDescriptor. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceDescriptor); + + /** ResourceDescriptor type. */ + public type: string; + + /** ResourceDescriptor pattern. */ + public pattern: string[]; + + /** ResourceDescriptor nameField. */ + public nameField: string; + + /** ResourceDescriptor history. */ + public history: google.api.ResourceDescriptor.History; + + /** ResourceDescriptor plural. */ + public plural: string; + + /** ResourceDescriptor singular. */ + public singular: string; + + /** ResourceDescriptor style. */ + public style: google.api.ResourceDescriptor.Style[]; + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceDescriptor + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @param message ResourceDescriptor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceDescriptor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceDescriptor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ResourceDescriptor { + + /** History enum. */ + type History = + "HISTORY_UNSPECIFIED"| "ORIGINALLY_SINGLE_PATTERN"| "FUTURE_MULTI_PATTERN"; + + /** Style enum. */ + type Style = + "STYLE_UNSPECIFIED"| "DECLARATIVE_FRIENDLY"; + } + + /** Properties of a ResourceReference. */ + interface IResourceReference { + + /** ResourceReference type */ + type?: (string|null); + + /** ResourceReference childType */ + childType?: (string|null); + } + + /** Represents a ResourceReference. */ + class ResourceReference implements IResourceReference { + + /** + * Constructs a new ResourceReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceReference); + + /** ResourceReference type. */ + public type: string; + + /** ResourceReference childType. */ + public childType: string; + + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceReference + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; + + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @param message ResourceReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace rpc. */ + namespace rpc { + + /** Properties of a Status. */ + interface IStatus { + + /** Status code */ + code?: (number|null); + + /** Status message */ + message?: (string|null); + + /** Status details */ + details?: (google.protobuf.IAny[]|null); + } + + /** Represents a Status. */ + class Status implements IStatus { + + /** + * Constructs a new Status. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IStatus); + + /** Status code. */ + public code: number; + + /** Status message. */ + public message: string; + + /** Status details. */ + public details: google.protobuf.IAny[]; + + /** + * Creates a Status message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Status + */ + public static fromObject(object: { [k: string]: any }): google.rpc.Status; + + /** + * Creates a plain object from a Status message. Also converts values to other types if specified. + * @param message Status + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Status to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Status + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace longrunning. */ + namespace longrunning { + + /** Represents an Operations */ + class Operations extends $protobuf.rpc.Service { + + /** + * Constructs a new Operations service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListOperationsResponse + */ + public listOperations(request: google.longrunning.IListOperationsRequest, callback: google.longrunning.Operations.ListOperationsCallback): void; + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @returns Promise + */ + public listOperations(request: google.longrunning.IListOperationsRequest): Promise; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public getOperation(request: google.longrunning.IGetOperationRequest, callback: google.longrunning.Operations.GetOperationCallback): void; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @returns Promise + */ + public getOperation(request: google.longrunning.IGetOperationRequest): Promise; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest, callback: google.longrunning.Operations.DeleteOperationCallback): void; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @returns Promise + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest): Promise; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest, callback: google.longrunning.Operations.CancelOperationCallback): void; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @returns Promise + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest): Promise; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest, callback: google.longrunning.Operations.WaitOperationCallback): void; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @returns Promise + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest): Promise; + } + + namespace Operations { + + /** + * Callback as used by {@link google.longrunning.Operations#listOperations}. + * @param error Error, if any + * @param [response] ListOperationsResponse + */ + type ListOperationsCallback = (error: (Error|null), response?: google.longrunning.ListOperationsResponse) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#getOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type GetOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#deleteOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#cancelOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type CancelOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#waitOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type WaitOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + } + + /** Properties of an Operation. */ + interface IOperation { + + /** Operation name */ + name?: (string|null); + + /** Operation metadata */ + metadata?: (google.protobuf.IAny|null); + + /** Operation done */ + done?: (boolean|null); + + /** Operation error */ + error?: (google.rpc.IStatus|null); + + /** Operation response */ + response?: (google.protobuf.IAny|null); + } + + /** Represents an Operation. */ + class Operation implements IOperation { + + /** + * Constructs a new Operation. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperation); + + /** Operation name. */ + public name: string; + + /** Operation metadata. */ + public metadata?: (google.protobuf.IAny|null); + + /** Operation done. */ + public done: boolean; + + /** Operation error. */ + public error?: (google.rpc.IStatus|null); + + /** Operation response. */ + public response?: (google.protobuf.IAny|null); + + /** Operation result. */ + public result?: ("error"|"response"); + + /** + * Creates an Operation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Operation + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.Operation; + + /** + * Creates a plain object from an Operation message. Also converts values to other types if specified. + * @param message Operation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.Operation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Operation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Operation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetOperationRequest. */ + interface IGetOperationRequest { + + /** GetOperationRequest name */ + name?: (string|null); + } + + /** Represents a GetOperationRequest. */ + class GetOperationRequest implements IGetOperationRequest { + + /** + * Constructs a new GetOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IGetOperationRequest); + + /** GetOperationRequest name. */ + public name: string; + + /** + * Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.GetOperationRequest; + + /** + * Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified. + * @param message GetOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.GetOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsRequest. */ + interface IListOperationsRequest { + + /** ListOperationsRequest name */ + name?: (string|null); + + /** ListOperationsRequest filter */ + filter?: (string|null); + + /** ListOperationsRequest pageSize */ + pageSize?: (number|null); + + /** ListOperationsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListOperationsRequest. */ + class ListOperationsRequest implements IListOperationsRequest { + + /** + * Constructs a new ListOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsRequest); + + /** ListOperationsRequest name. */ + public name: string; + + /** ListOperationsRequest filter. */ + public filter: string; + + /** ListOperationsRequest pageSize. */ + public pageSize: number; + + /** ListOperationsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsRequest; + + /** + * Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified. + * @param message ListOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsResponse. */ + interface IListOperationsResponse { + + /** ListOperationsResponse operations */ + operations?: (google.longrunning.IOperation[]|null); + + /** ListOperationsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListOperationsResponse. */ + class ListOperationsResponse implements IListOperationsResponse { + + /** + * Constructs a new ListOperationsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsResponse); + + /** ListOperationsResponse operations. */ + public operations: google.longrunning.IOperation[]; + + /** ListOperationsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsResponse + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsResponse; + + /** + * Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified. + * @param message ListOperationsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CancelOperationRequest. */ + interface ICancelOperationRequest { + + /** CancelOperationRequest name */ + name?: (string|null); + } + + /** Represents a CancelOperationRequest. */ + class CancelOperationRequest implements ICancelOperationRequest { + + /** + * Constructs a new CancelOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.ICancelOperationRequest); + + /** CancelOperationRequest name. */ + public name: string; + + /** + * Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CancelOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.CancelOperationRequest; + + /** + * Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified. + * @param message CancelOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.CancelOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CancelOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CancelOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteOperationRequest. */ + interface IDeleteOperationRequest { + + /** DeleteOperationRequest name */ + name?: (string|null); + } + + /** Represents a DeleteOperationRequest. */ + class DeleteOperationRequest implements IDeleteOperationRequest { + + /** + * Constructs a new DeleteOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IDeleteOperationRequest); + + /** DeleteOperationRequest name. */ + public name: string; + + /** + * Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.DeleteOperationRequest; + + /** + * Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified. + * @param message DeleteOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.DeleteOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WaitOperationRequest. */ + interface IWaitOperationRequest { + + /** WaitOperationRequest name */ + name?: (string|null); + + /** WaitOperationRequest timeout */ + timeout?: (google.protobuf.IDuration|null); + } + + /** Represents a WaitOperationRequest. */ + class WaitOperationRequest implements IWaitOperationRequest { + + /** + * Constructs a new WaitOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IWaitOperationRequest); + + /** WaitOperationRequest name. */ + public name: string; + + /** WaitOperationRequest timeout. */ + public timeout?: (google.protobuf.IDuration|null); + + /** + * Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WaitOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.WaitOperationRequest; + + /** + * Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified. + * @param message WaitOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.WaitOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WaitOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WaitOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an OperationInfo. */ + interface IOperationInfo { + + /** OperationInfo responseType */ + responseType?: (string|null); + + /** OperationInfo metadataType */ + metadataType?: (string|null); + } + + /** Represents an OperationInfo. */ + class OperationInfo implements IOperationInfo { + + /** + * Constructs a new OperationInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperationInfo); + + /** OperationInfo responseType. */ + public responseType: string; + + /** OperationInfo metadataType. */ + public metadataType: string; + + /** + * Creates an OperationInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OperationInfo + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.OperationInfo; + + /** + * Creates a plain object from an OperationInfo message. Also converts values to other types if specified. + * @param message OperationInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.OperationInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OperationInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OperationInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } +} diff --git a/node_modules/@google-cloud/firestore/types/v1/firestore_admin_client.d.ts b/node_modules/@google-cloud/firestore/types/v1/firestore_admin_client.d.ts new file mode 100644 index 0000000..2560792 --- /dev/null +++ b/node_modules/@google-cloud/firestore/types/v1/firestore_admin_client.d.ts @@ -0,0 +1,2405 @@ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type * as gax from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + LROperation, + PaginationCallback, + LocationsClient, + LocationProtos, +} from 'google-gax'; +import {Transform} from 'stream'; +import * as protos from '../protos/firestore_admin_v1_proto_api'; +/** + * The Cloud Firestore Admin API. + * + * This API provides several administrative services for Cloud Firestore. + * + * Project, Database, Namespace, Collection, Collection Group, and Document are + * used as defined in the Google Cloud Firestore API. + * + * Operation: An Operation represents work being performed in the background. + * + * The index service manages Cloud Firestore indexes. + * + * Index creation is performed asynchronously. + * An Operation resource is created for each such asynchronous operation. + * The state of the operation (including any errors encountered) + * may be queried via the Operation resource. + * + * The Operations collection provides a record of actions performed for the + * specified Project (including any Operations in progress). Operations are not + * created directly but through calls on other collections or resources. + * + * An Operation that is done may be deleted so that it is no longer listed as + * part of the Operation collection. Operations are garbage collected after + * 30 days. By default, ListOperations will only return in progress and failed + * operations. To list completed operation, issue a ListOperations request with + * the filter `done: true`. + * + * Operations are created by service `FirestoreAdmin`, but are accessed via + * service `google.longrunning.Operations`. + * @class + * @memberof v1 + */ +export declare class FirestoreAdminClient { + private _terminated; + private _opts; + private _providedCustomServicePath; + private _gaxModule; + private _gaxGrpc; + private _protos; + private _defaults; + private _universeDomain; + private _servicePath; + auth: gax.GoogleAuth; + descriptors: Descriptors; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: { + [name: string]: Function; + }; + locationsClient: LocationsClient; + pathTemplates: { + [name: string]: gax.PathTemplate; + }; + operationsClient: gax.OperationsClient; + firestoreAdminStub?: Promise<{ + [name: string]: Function; + }>; + /** + * Construct an instance of FirestoreAdminClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param {string} [options.apiEndpoint] - The domain name of the + * API remote host. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new FirestoreAdminClient({fallback: true}, gax); + * ``` + */ + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback + ); + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize(): Promise<{ + [name: string]: Function; + }>; + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath(): string; + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint(): string; + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint(): string; + get universeDomain(): string; + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port(): number; + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes(): string[]; + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Gets a composite index. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Index|Index}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.get_index.js + * region_tag:firestore_v1_generated_FirestoreAdmin_GetIndex_async + */ + getIndex( + request?: protos.google.firestore.admin.v1.IGetIndexRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | undefined, + {} | undefined, + ] + >; + getIndex( + request: protos.google.firestore.admin.v1.IGetIndexRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | null | undefined, + {} | null | undefined + > + ): void; + getIndex( + request: protos.google.firestore.admin.v1.IGetIndexRequest, + callback: Callback< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Deletes a composite index. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.delete_index.js + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteIndex_async + */ + deleteIndex( + request?: protos.google.firestore.admin.v1.IDeleteIndexRequest, + options?: CallOptions + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest | undefined, + {} | undefined, + ] + >; + deleteIndex( + request: protos.google.firestore.admin.v1.IDeleteIndexRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest | null | undefined, + {} | null | undefined + > + ): void; + deleteIndex( + request: protos.google.firestore.admin.v1.IDeleteIndexRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Gets the metadata and configuration for a Field. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Field|Field}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.get_field.js + * region_tag:firestore_v1_generated_FirestoreAdmin_GetField_async + */ + getField( + request?: protos.google.firestore.admin.v1.IGetFieldRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | undefined, + {} | undefined, + ] + >; + getField( + request: protos.google.firestore.admin.v1.IGetFieldRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | null | undefined, + {} | null | undefined + > + ): void; + getField( + request: protos.google.firestore.admin.v1.IGetFieldRequest, + callback: Callback< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Gets information about a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Database|Database}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.get_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_GetDatabase_async + */ + getDatabase( + request?: protos.google.firestore.admin.v1.IGetDatabaseRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest | undefined, + {} | undefined, + ] + >; + getDatabase( + request: protos.google.firestore.admin.v1.IGetDatabaseRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest | null | undefined, + {} | null | undefined + > + ): void; + getDatabase( + request: protos.google.firestore.admin.v1.IGetDatabaseRequest, + callback: Callback< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * List all the databases in the project. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}` + * @param {boolean} request.showDeleted + * If true, also returns deleted resources. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListDatabasesResponse|ListDatabasesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.list_databases.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ListDatabases_async + */ + listDatabases( + request?: protos.google.firestore.admin.v1.IListDatabasesRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest | undefined, + {} | undefined, + ] + >; + listDatabases( + request: protos.google.firestore.admin.v1.IListDatabasesRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest | null | undefined, + {} | null | undefined + > + ): void; + listDatabases( + request: protos.google.firestore.admin.v1.IListDatabasesRequest, + callback: Callback< + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Gets information about a backup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the backup to fetch. + * + * Format is `projects/{project}/locations/{location}/backups/{backup}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Backup|Backup}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.get_backup.js + * region_tag:firestore_v1_generated_FirestoreAdmin_GetBackup_async + */ + getBackup( + request?: protos.google.firestore.admin.v1.IGetBackupRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | undefined, + {} | undefined, + ] + >; + getBackup( + request: protos.google.firestore.admin.v1.IGetBackupRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | null | undefined, + {} | null | undefined + > + ): void; + getBackup( + request: protos.google.firestore.admin.v1.IGetBackupRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Lists all the backups. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The location to list backups from. + * + * Format is `projects/{project}/locations/{location}`. + * Use `{location} = '-'` to list backups from all locations for the given + * project. This allows listing backups from a single location or from all + * locations. + * @param {string} request.filter + * An expression that filters the list of returned backups. + * + * A filter expression consists of a field name, a comparison operator, and a + * value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the {@link protos.google.firestore.admin.v1.Backup|Backup} are + * eligible for filtering: + * + * * `database_uid` (supports `=` only) + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListBackupsResponse|ListBackupsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.list_backups.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ListBackups_async + */ + listBackups( + request?: protos.google.firestore.admin.v1.IListBackupsRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | undefined, + {} | undefined, + ] + >; + listBackups( + request: protos.google.firestore.admin.v1.IListBackupsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | null | undefined, + {} | null | undefined + > + ): void; + listBackups( + request: protos.google.firestore.admin.v1.IListBackupsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Deletes a backup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the backup to delete. + * + * format is `projects/{project}/locations/{location}/backups/{backup}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.delete_backup.js + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteBackup_async + */ + deleteBackup( + request?: protos.google.firestore.admin.v1.IDeleteBackupRequest, + options?: CallOptions + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | undefined, + {} | undefined, + ] + >; + deleteBackup( + request: protos.google.firestore.admin.v1.IDeleteBackupRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | null | undefined, + {} | null | undefined + > + ): void; + deleteBackup( + request: protos.google.firestore.admin.v1.IDeleteBackupRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Creates a backup schedule on a database. + * At most two backup schedules can be configured on a database, one daily + * backup schedule and one weekly backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent database. + * + * Format `projects/{project}/databases/{database}` + * @param {google.firestore.admin.v1.BackupSchedule} request.backupSchedule + * Required. The backup schedule to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.create_backup_schedule.js + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateBackupSchedule_async + */ + createBackupSchedule( + request?: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.ICreateBackupScheduleRequest | undefined, + {} | undefined, + ] + >; + createBackupSchedule( + request: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; + createBackupSchedule( + request: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; + /** + * Gets information about a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the backup schedule. + * + * Format + * `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.get_backup_schedule.js + * region_tag:firestore_v1_generated_FirestoreAdmin_GetBackupSchedule_async + */ + getBackupSchedule( + request?: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IGetBackupScheduleRequest | undefined, + {} | undefined, + ] + >; + getBackupSchedule( + request: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; + getBackupSchedule( + request: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; + /** + * List backup schedules. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent database. + * + * Format is `projects/{project}/databases/{database}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListBackupSchedulesResponse|ListBackupSchedulesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.list_backup_schedules.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ListBackupSchedules_async + */ + listBackupSchedules( + request?: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + protos.google.firestore.admin.v1.IListBackupSchedulesRequest | undefined, + {} | undefined, + ] + >; + listBackupSchedules( + request: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + | protos.google.firestore.admin.v1.IListBackupSchedulesRequest + | null + | undefined, + {} | null | undefined + > + ): void; + listBackupSchedules( + request: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + | protos.google.firestore.admin.v1.IListBackupSchedulesRequest + | null + | undefined, + {} | null | undefined + > + ): void; + /** + * Updates a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.admin.v1.BackupSchedule} request.backupSchedule + * Required. The backup schedule to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The list of fields to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.update_backup_schedule.js + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateBackupSchedule_async + */ + updateBackupSchedule( + request?: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest | undefined, + {} | undefined, + ] + >; + updateBackupSchedule( + request: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; + updateBackupSchedule( + request: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; + /** + * Deletes a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the backup schedule. + * + * Format + * `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.delete_backup_schedule.js + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteBackupSchedule_async + */ + deleteBackupSchedule( + request?: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + options?: CallOptions + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest | undefined, + {} | undefined, + ] + >; + deleteBackupSchedule( + request: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; + deleteBackupSchedule( + request: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; + /** + * Creates a composite index. This returns a + * {@link protos.google.longrunning.Operation|google.longrunning.Operation} which may be + * used to track the status of the creation. The metadata for the operation + * will be the type + * {@link protos.google.firestore.admin.v1.IndexOperationMetadata|IndexOperationMetadata}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {google.firestore.admin.v1.Index} request.index + * Required. The composite index to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.create_index.js + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateIndex_async + */ + createIndex( + request?: protos.google.firestore.admin.v1.ICreateIndexRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + createIndex( + request: protos.google.firestore.admin.v1.ICreateIndexRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + createIndex( + request: protos.google.firestore.admin.v1.ICreateIndexRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + /** + * Check the status of the long running operation returned by `createIndex()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.create_index.js + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateIndex_async + */ + checkCreateIndexProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Index, + protos.google.firestore.admin.v1.IndexOperationMetadata + > + >; + /** + * Updates a field configuration. Currently, field updates apply only to + * single field index configuration. However, calls to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.UpdateField|FirestoreAdmin.UpdateField} + * should provide a field mask to avoid changing any configuration that the + * caller isn't aware of. The field mask should be specified as: `{ paths: + * "index_config" }`. + * + * This call returns a + * {@link protos.google.longrunning.Operation|google.longrunning.Operation} which may be + * used to track the status of the field update. The metadata for the + * operation will be the type + * {@link protos.google.firestore.admin.v1.FieldOperationMetadata|FieldOperationMetadata}. + * + * To configure the default field settings for the database, use + * the special `Field` with resource name: + * `projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/*`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.admin.v1.Field} request.field + * Required. The field to be updated. + * @param {google.protobuf.FieldMask} request.updateMask + * A mask, relative to the field. If specified, only configuration specified + * by this field_mask will be updated in the field. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.update_field.js + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateField_async + */ + updateField( + request?: protos.google.firestore.admin.v1.IUpdateFieldRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + updateField( + request: protos.google.firestore.admin.v1.IUpdateFieldRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + updateField( + request: protos.google.firestore.admin.v1.IUpdateFieldRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + /** + * Check the status of the long running operation returned by `updateField()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.update_field.js + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateField_async + */ + checkUpdateFieldProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Field, + protos.google.firestore.admin.v1.FieldOperationMetadata + > + >; + /** + * Exports a copy of all or a subset of documents from Google Cloud Firestore + * to another storage system, such as Google Cloud Storage. Recent updates to + * documents may not be reflected in the export. The export occurs in the + * background and its progress can be monitored and managed via the + * Operation resource that is created. The output of an export may only be + * used once the associated operation is done. If an export operation is + * cancelled before completion it may leave partial data behind in Google + * Cloud Storage. + * + * For more details on export behavior and output format, refer to: + * https://cloud.google.com/firestore/docs/manage-data/export-import + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Database to export. Should be of the form: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.collectionIds + * Which collection IDs to export. Unspecified means all collections. Each + * collection ID in this list must be unique. + * @param {string} request.outputUriPrefix + * The output URI. Currently only supports Google Cloud Storage URIs of the + * form: `gs://BUCKET_NAME[/NAMESPACE_PATH]`, where `BUCKET_NAME` is the name + * of the Google Cloud Storage bucket and `NAMESPACE_PATH` is an optional + * Google Cloud Storage namespace path. When + * choosing a name, be sure to consider Google Cloud Storage naming + * guidelines: https://cloud.google.com/storage/docs/naming. + * If the URI is a bucket (without a namespace path), a prefix will be + * generated based on the start time. + * @param {string[]} request.namespaceIds + * An empty list represents all namespaces. This is the preferred + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to include them. Each namespace in this list must be unique. + * @param {google.protobuf.Timestamp} request.snapshotTime + * The timestamp that corresponds to the version of the database to be + * exported. The timestamp must be in the past, rounded to the minute and not + * older than + * {@link protos.google.firestore.admin.v1.Database.earliest_version_time|earliestVersionTime}. + * If specified, then the exported documents will represent a consistent view + * of the database at the provided time. Otherwise, there are no guarantees + * about the consistency of the exported documents. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.export_documents.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ExportDocuments_async + */ + exportDocuments( + request?: protos.google.firestore.admin.v1.IExportDocumentsRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + exportDocuments( + request: protos.google.firestore.admin.v1.IExportDocumentsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + exportDocuments( + request: protos.google.firestore.admin.v1.IExportDocumentsRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + /** + * Check the status of the long running operation returned by `exportDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.export_documents.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ExportDocuments_async + */ + checkExportDocumentsProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.ExportDocumentsResponse, + protos.google.firestore.admin.v1.ExportDocumentsMetadata + > + >; + /** + * Imports documents into Google Cloud Firestore. Existing documents with the + * same name are overwritten. The import occurs in the background and its + * progress can be monitored and managed via the Operation resource that is + * created. If an ImportDocuments operation is cancelled, it is possible + * that a subset of the data has already been imported to Cloud Firestore. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Database to import into. Should be of the form: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.collectionIds + * Which collection IDs to import. Unspecified means all collections included + * in the import. Each collection ID in this list must be unique. + * @param {string} request.inputUriPrefix + * Location of the exported files. + * This must match the output_uri_prefix of an ExportDocumentsResponse from + * an export that has completed successfully. + * See: + * {@link protos.google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix|google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix}. + * @param {string[]} request.namespaceIds + * An empty list represents all namespaces. This is the preferred + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to include them. Each namespace in this list must be unique. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.import_documents.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ImportDocuments_async + */ + importDocuments( + request?: protos.google.firestore.admin.v1.IImportDocumentsRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + importDocuments( + request: protos.google.firestore.admin.v1.IImportDocumentsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + importDocuments( + request: protos.google.firestore.admin.v1.IImportDocumentsRequest, + callback: Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + /** + * Check the status of the long running operation returned by `importDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.import_documents.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ImportDocuments_async + */ + checkImportDocumentsProgress( + name: string + ): Promise< + LROperation< + protos.google.protobuf.Empty, + protos.google.firestore.admin.v1.ImportDocumentsMetadata + > + >; + /** + * Bulk deletes a subset of documents from Google Cloud Firestore. + * Documents created or updated after the underlying system starts to process + * the request will not be deleted. The bulk delete occurs in the background + * and its progress can be monitored and managed via the Operation resource + * that is created. + * + * For more details on bulk delete behavior, refer to: + * https://cloud.google.com/firestore/docs/manage-data/bulk-delete + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Database to operate. Should be of the form: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} [request.collectionIds] + * Optional. IDs of the collection groups to delete. Unspecified means all + * collection groups. + * + * Each collection group in this list must be unique. + * @param {string[]} [request.namespaceIds] + * Optional. Namespaces to delete. + * + * An empty list means all namespaces. This is the recommended + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to delete from them. + * + * Each namespace in this list must be unique. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.bulk_delete_documents.js + * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async + */ + bulkDeleteDocuments( + request?: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + bulkDeleteDocuments( + request: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + bulkDeleteDocuments( + request: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + /** + * Check the status of the long running operation returned by `bulkDeleteDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.bulk_delete_documents.js + * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async + */ + checkBulkDeleteDocumentsProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.BulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.BulkDeleteDocumentsMetadata + > + >; + /** + * Create a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}` + * @param {google.firestore.admin.v1.Database} request.database + * Required. The Database to create. + * @param {string} request.databaseId + * Required. The ID to use for the database, which will become the final + * component of the database's resource name. + * + * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ + * with first character a letter and the last a letter or a number. Must not + * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + * + * "(default)" database ID is also valid. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.create_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateDatabase_async + */ + createDatabase( + request?: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + createDatabase( + request: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + createDatabase( + request: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + /** + * Check the status of the long running operation returned by `createDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.create_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateDatabase_async + */ + checkCreateDatabaseProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.CreateDatabaseMetadata + > + >; + /** + * Updates a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.admin.v1.Database} request.database + * Required. The database to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The list of fields to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.update_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async + */ + updateDatabase( + request?: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + updateDatabase( + request: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + updateDatabase( + request: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + /** + * Check the status of the long running operation returned by `updateDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.update_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async + */ + checkUpdateDatabaseProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.UpdateDatabaseMetadata + > + >; + /** + * Deletes a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}` + * @param {string} request.etag + * The current etag of the Database. + * If an etag is provided and does not match the current etag of the database, + * deletion will be blocked and a FAILED_PRECONDITION error will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.delete_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteDatabase_async + */ + deleteDatabase( + request?: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + deleteDatabase( + request: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + deleteDatabase( + request: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + /** + * Check the status of the long running operation returned by `deleteDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.delete_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteDatabase_async + */ + checkDeleteDatabaseProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.DeleteDatabaseMetadata + > + >; + /** + * Creates a new database by restoring from an existing backup. + * + * The new database must be in the same cloud region or multi-region location + * as the existing backup. This behaves similar to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.CreateDatabase|FirestoreAdmin.CreateDatabase} + * except instead of creating a new empty database, a new database is created + * with the database type, index configuration, and documents from an existing + * backup. + * + * The {@link protos.google.longrunning.Operation|long-running operation} can be used to + * track the progress of the restore, with the Operation's + * {@link protos.google.longrunning.Operation.metadata|metadata} field type being the + * {@link protos.google.firestore.admin.v1.RestoreDatabaseMetadata|RestoreDatabaseMetadata}. + * The {@link protos.google.longrunning.Operation.response|response} type is the + * {@link protos.google.firestore.admin.v1.Database|Database} if the restore was + * successful. The new database is not readable or writeable until the LRO has + * completed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project to restore the database in. Format is + * `projects/{project_id}`. + * @param {string} request.databaseId + * Required. The ID to use for the database, which will become the final + * component of the database's resource name. This database ID must not be + * associated with an existing database. + * + * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ + * with first character a letter and the last a letter or a number. Must not + * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + * + * "(default)" database ID is also valid. + * @param {string} request.backup + * Required. Backup to restore from. Must be from the same project as the + * parent. + * + * The restored database will be created in the same location as the source + * backup. + * + * Format is: `projects/{project_id}/locations/{location}/backups/{backup}` + * @param {google.firestore.admin.v1.Database.EncryptionConfig} [request.encryptionConfig] + * Optional. Encryption configuration for the restored database. + * + * If this field is not specified, the restored database will use + * the same encryption configuration as the backup, namely + * {@link protos.google.firestore.admin.v1.Database.EncryptionConfig.use_source_encryption|use_source_encryption}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.restore_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_RestoreDatabase_async + */ + restoreDatabase( + request?: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + restoreDatabase( + request: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + restoreDatabase( + request: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + /** + * Check the status of the long running operation returned by `restoreDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.restore_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_RestoreDatabase_async + */ + checkRestoreDatabaseProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.RestoreDatabaseMetadata + > + >; + /** + * Lists composite indexes. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.admin.v1.Index|Index}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listIndexesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listIndexes( + request?: protos.google.firestore.admin.v1.IListIndexesRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IIndex[], + protos.google.firestore.admin.v1.IListIndexesRequest | null, + protos.google.firestore.admin.v1.IListIndexesResponse, + ] + >; + listIndexes( + request: protos.google.firestore.admin.v1.IListIndexesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.admin.v1.IListIndexesRequest, + protos.google.firestore.admin.v1.IListIndexesResponse | null | undefined, + protos.google.firestore.admin.v1.IIndex + > + ): void; + listIndexes( + request: protos.google.firestore.admin.v1.IListIndexesRequest, + callback: PaginationCallback< + protos.google.firestore.admin.v1.IListIndexesRequest, + protos.google.firestore.admin.v1.IListIndexesResponse | null | undefined, + protos.google.firestore.admin.v1.IIndex + > + ): void; + /** + * Equivalent to `listIndexes`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.admin.v1.Index|Index} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listIndexesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listIndexesStream( + request?: protos.google.firestore.admin.v1.IListIndexesRequest, + options?: CallOptions + ): Transform; + /** + * Equivalent to `listIndexes`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.admin.v1.Index|Index}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.list_indexes.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ListIndexes_async + */ + listIndexesAsync( + request?: protos.google.firestore.admin.v1.IListIndexesRequest, + options?: CallOptions + ): AsyncIterable; + /** + * Lists the field configuration and metadata for this database. + * + * Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with the filter set to `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.admin.v1.Field|Field}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listFieldsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listFields( + request?: protos.google.firestore.admin.v1.IListFieldsRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IField[], + protos.google.firestore.admin.v1.IListFieldsRequest | null, + protos.google.firestore.admin.v1.IListFieldsResponse, + ] + >; + listFields( + request: protos.google.firestore.admin.v1.IListFieldsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.admin.v1.IListFieldsRequest, + protos.google.firestore.admin.v1.IListFieldsResponse | null | undefined, + protos.google.firestore.admin.v1.IField + > + ): void; + listFields( + request: protos.google.firestore.admin.v1.IListFieldsRequest, + callback: PaginationCallback< + protos.google.firestore.admin.v1.IListFieldsRequest, + protos.google.firestore.admin.v1.IListFieldsResponse | null | undefined, + protos.google.firestore.admin.v1.IField + > + ): void; + /** + * Equivalent to `listFields`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.admin.v1.Field|Field} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listFieldsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listFieldsStream( + request?: protos.google.firestore.admin.v1.IListFieldsRequest, + options?: CallOptions + ): Transform; + /** + * Equivalent to `listFields`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.admin.v1.Field|Field}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.list_fields.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ListFields_async + */ + listFieldsAsync( + request?: protos.google.firestore.admin.v1.IListFieldsRequest, + options?: CallOptions + ): AsyncIterable; + /** + * Gets information about a location. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Resource name for the location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html | CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.cloud.location.Location | Location}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * ``` + * const [response] = await client.getLocation(request); + * ``` + */ + getLocation( + request: LocationProtos.google.cloud.location.IGetLocationRequest, + options?: + | gax.CallOptions + | Callback< + LocationProtos.google.cloud.location.ILocation, + | LocationProtos.google.cloud.location.IGetLocationRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + LocationProtos.google.cloud.location.ILocation, + | LocationProtos.google.cloud.location.IGetLocationRequest + | null + | undefined, + {} | null | undefined + > + ): Promise; + /** + * Lists information about the supported locations for this service. Returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource that owns the locations collection, if applicable. + * @param {string} request.filter + * The standard list filter. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link google.cloud.location.Location | Location}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * ``` + * const iterable = client.listLocationsAsync(request); + * for await (const response of iterable) { + * // process response + * } + * ``` + */ + listLocationsAsync( + request: LocationProtos.google.cloud.location.IListLocationsRequest, + options?: CallOptions + ): AsyncIterable; + /** + * Gets the latest state of a long-running operation. Clients can use this + * method to poll the operation result at intervals as recommended by the API + * service. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} + * for the details. + * @param {function(?Error, ?Object)=} callback + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing + * {@link google.longrunning.Operation | google.longrunning.Operation}. + * @return {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * {@link google.longrunning.Operation | google.longrunning.Operation}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * const name = ''; + * const [response] = await client.getOperation({name}); + * // doThingsWith(response) + * ``` + */ + getOperation( + request: protos.google.longrunning.GetOperationRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + protos.google.longrunning.Operation, + protos.google.longrunning.GetOperationRequest, + {} | null | undefined + >, + callback?: Callback< + protos.google.longrunning.Operation, + protos.google.longrunning.GetOperationRequest, + {} | null | undefined + > + ): Promise<[protos.google.longrunning.Operation]>; + /** + * Lists operations that match the specified filter in the request. If the + * server doesn't support this method, it returns `UNIMPLEMENTED`. Returns an iterable object. + * + * For-await-of syntax is used with the iterable to recursively get response element on-demand. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation collection. + * @param {string} request.filter - The standard list filter. + * @param {number=} request.pageSize - + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} for the + * details. + * @returns {Object} + * An iterable Object that conforms to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | iteration protocols}. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * for await (const response of client.listOperationsAsync(request)); + * // doThingsWith(response) + * ``` + */ + listOperationsAsync( + request: protos.google.longrunning.ListOperationsRequest, + options?: gax.CallOptions + ): AsyncIterable; + /** + * Starts asynchronous cancellation on a long-running operation. The server + * makes a best effort to cancel the operation, but success is not + * guaranteed. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. Clients can use + * {@link Operations.GetOperation} or + * other methods to check whether the cancellation succeeded or whether the + * operation completed despite cancellation. On successful cancellation, + * the operation is not deleted; instead, it becomes an operation with + * an {@link Operation.error} value with a {@link google.rpc.Status.code} of + * 1, corresponding to `Code.CANCELLED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be cancelled. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} for the + * details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @return {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * await client.cancelOperation({name: ''}); + * ``` + */ + cancelOperation( + request: protos.google.longrunning.CancelOperationRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + protos.google.longrunning.CancelOperationRequest, + protos.google.protobuf.Empty, + {} | undefined | null + >, + callback?: Callback< + protos.google.longrunning.CancelOperationRequest, + protos.google.protobuf.Empty, + {} | undefined | null + > + ): Promise; + /** + * Deletes a long-running operation. This method indicates that the client is + * no longer interested in the operation result. It does not cancel the + * operation. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be deleted. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} + * for the details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @return {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * await client.deleteOperation({name: ''}); + * ``` + */ + deleteOperation( + request: protos.google.longrunning.DeleteOperationRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + protos.google.protobuf.Empty, + protos.google.longrunning.DeleteOperationRequest, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.Empty, + protos.google.longrunning.DeleteOperationRequest, + {} | null | undefined + > + ): Promise; + /** + * Return a fully-qualified backup resource name string. + * + * @param {string} project + * @param {string} location + * @param {string} backup + * @returns {string} Resource name string. + */ + backupPath(project: string, location: string, backup: string): string; + /** + * Parse the project from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the project. + */ + matchProjectFromBackupName(backupName: string): string | number; + /** + * Parse the location from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the location. + */ + matchLocationFromBackupName(backupName: string): string | number; + /** + * Parse the backup from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the backup. + */ + matchBackupFromBackupName(backupName: string): string | number; + /** + * Return a fully-qualified backupSchedule resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} backup_schedule + * @returns {string} Resource name string. + */ + backupSchedulePath( + project: string, + database: string, + backupSchedule: string + ): string; + /** + * Parse the project from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the project. + */ + matchProjectFromBackupScheduleName( + backupScheduleName: string + ): string | number; + /** + * Parse the database from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromBackupScheduleName( + backupScheduleName: string + ): string | number; + /** + * Parse the backup_schedule from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the backup_schedule. + */ + matchBackupScheduleFromBackupScheduleName( + backupScheduleName: string + ): string | number; + /** + * Return a fully-qualified collectionGroup resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} collection + * @returns {string} Resource name string. + */ + collectionGroupPath( + project: string, + database: string, + collection: string + ): string; + /** + * Parse the project from CollectionGroup resource. + * + * @param {string} collectionGroupName + * A fully-qualified path representing CollectionGroup resource. + * @returns {string} A string representing the project. + */ + matchProjectFromCollectionGroupName( + collectionGroupName: string + ): string | number; + /** + * Parse the database from CollectionGroup resource. + * + * @param {string} collectionGroupName + * A fully-qualified path representing CollectionGroup resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromCollectionGroupName( + collectionGroupName: string + ): string | number; + /** + * Parse the collection from CollectionGroup resource. + * + * @param {string} collectionGroupName + * A fully-qualified path representing CollectionGroup resource. + * @returns {string} A string representing the collection. + */ + matchCollectionFromCollectionGroupName( + collectionGroupName: string + ): string | number; + /** + * Return a fully-qualified database resource name string. + * + * @param {string} project + * @param {string} database + * @returns {string} Resource name string. + */ + databasePath(project: string, database: string): string; + /** + * Parse the project from Database resource. + * + * @param {string} databaseName + * A fully-qualified path representing Database resource. + * @returns {string} A string representing the project. + */ + matchProjectFromDatabaseName(databaseName: string): string | number; + /** + * Parse the database from Database resource. + * + * @param {string} databaseName + * A fully-qualified path representing Database resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromDatabaseName(databaseName: string): string | number; + /** + * Return a fully-qualified field resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} collection + * @param {string} field + * @returns {string} Resource name string. + */ + fieldPath( + project: string, + database: string, + collection: string, + field: string + ): string; + /** + * Parse the project from Field resource. + * + * @param {string} fieldName + * A fully-qualified path representing Field resource. + * @returns {string} A string representing the project. + */ + matchProjectFromFieldName(fieldName: string): string | number; + /** + * Parse the database from Field resource. + * + * @param {string} fieldName + * A fully-qualified path representing Field resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromFieldName(fieldName: string): string | number; + /** + * Parse the collection from Field resource. + * + * @param {string} fieldName + * A fully-qualified path representing Field resource. + * @returns {string} A string representing the collection. + */ + matchCollectionFromFieldName(fieldName: string): string | number; + /** + * Parse the field from Field resource. + * + * @param {string} fieldName + * A fully-qualified path representing Field resource. + * @returns {string} A string representing the field. + */ + matchFieldFromFieldName(fieldName: string): string | number; + /** + * Return a fully-qualified index resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} collection + * @param {string} index + * @returns {string} Resource name string. + */ + indexPath( + project: string, + database: string, + collection: string, + index: string + ): string; + /** + * Parse the project from Index resource. + * + * @param {string} indexName + * A fully-qualified path representing Index resource. + * @returns {string} A string representing the project. + */ + matchProjectFromIndexName(indexName: string): string | number; + /** + * Parse the database from Index resource. + * + * @param {string} indexName + * A fully-qualified path representing Index resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromIndexName(indexName: string): string | number; + /** + * Parse the collection from Index resource. + * + * @param {string} indexName + * A fully-qualified path representing Index resource. + * @returns {string} A string representing the collection. + */ + matchCollectionFromIndexName(indexName: string): string | number; + /** + * Parse the index from Index resource. + * + * @param {string} indexName + * A fully-qualified path representing Index resource. + * @returns {string} A string representing the index. + */ + matchIndexFromIndexName(indexName: string): string | number; + /** + * Return a fully-qualified location resource name string. + * + * @param {string} project + * @param {string} location + * @returns {string} Resource name string. + */ + locationPath(project: string, location: string): string; + /** + * Parse the project from Location resource. + * + * @param {string} locationName + * A fully-qualified path representing Location resource. + * @returns {string} A string representing the project. + */ + matchProjectFromLocationName(locationName: string): string | number; + /** + * Parse the location from Location resource. + * + * @param {string} locationName + * A fully-qualified path representing Location resource. + * @returns {string} A string representing the location. + */ + matchLocationFromLocationName(locationName: string): string | number; + /** + * Return a fully-qualified project resource name string. + * + * @param {string} project + * @returns {string} Resource name string. + */ + projectPath(project: string): string; + /** + * Parse the project from Project resource. + * + * @param {string} projectName + * A fully-qualified path representing Project resource. + * @returns {string} A string representing the project. + */ + matchProjectFromProjectName(projectName: string): string | number; + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise; +} diff --git a/node_modules/@google-cloud/firestore/types/v1/firestore_client.d.ts b/node_modules/@google-cloud/firestore/types/v1/firestore_client.d.ts new file mode 100644 index 0000000..3e2167f --- /dev/null +++ b/node_modules/@google-cloud/firestore/types/v1/firestore_client.d.ts @@ -0,0 +1,1450 @@ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type * as gax from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + LocationsClient, + LocationProtos, +} from 'google-gax'; +import {Transform} from 'stream'; +import * as protos from '../protos/firestore_v1_proto_api'; +/** + * The Cloud Firestore service. + * + * Cloud Firestore is a fast, fully managed, serverless, cloud-native NoSQL + * document database that simplifies storing, syncing, and querying data for + * your mobile, web, and IoT apps at global scale. Its client libraries provide + * live synchronization and offline support, while its security features and + * integrations with Firebase and Google Cloud Platform accelerate building + * truly serverless apps. + * @class + * @memberof v1 + */ +export declare class FirestoreClient { + private _terminated; + private _opts; + private _providedCustomServicePath; + private _gaxModule; + private _gaxGrpc; + private _protos; + private _defaults; + private _universeDomain; + private _servicePath; + auth: gax.GoogleAuth; + descriptors: Descriptors; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: { + [name: string]: Function; + }; + locationsClient: LocationsClient; + firestoreStub?: Promise<{ + [name: string]: Function; + }>; + /** + * Construct an instance of FirestoreClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param {string} [options.apiEndpoint] - The domain name of the + * API remote host. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new FirestoreClient({fallback: true}, gax); + * ``` + */ + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback + ); + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize(): Promise<{ + [name: string]: Function; + }>; + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath(): string; + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint(): string; + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint(): string; + get universeDomain(): string; + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port(): number; + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes(): string[]; + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Gets a single document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Document to get. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * @param {google.firestore.v1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If the document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Reads the document in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads the version of the document at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.get_document.js + * region_tag:firestore_v1_generated_Firestore_GetDocument_async + */ + getDocument( + request?: protos.google.firestore.v1.IGetDocumentRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | undefined, + {} | undefined, + ] + >; + getDocument( + request: protos.google.firestore.v1.IGetDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; + getDocument( + request: protos.google.firestore.v1.IGetDocumentRequest, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Updates or inserts a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.v1.Document} request.document + * Required. The updated document. + * Creates the document if it does not already exist. + * @param {google.firestore.v1.DocumentMask} request.updateMask + * The fields to update. + * None of the field paths in the mask may contain a reserved name. + * + * If the document exists on the server and has fields not referenced in the + * mask, they are left unchanged. + * Fields referenced in the mask, but not present in the input document, are + * deleted from the document on the server. + * @param {google.firestore.v1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If the document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {google.firestore.v1.Precondition} request.currentDocument + * An optional precondition on the document. + * The request will fail if this is set and not met by the target document. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.update_document.js + * region_tag:firestore_v1_generated_Firestore_UpdateDocument_async + */ + updateDocument( + request?: protos.google.firestore.v1.IUpdateDocumentRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | undefined, + {} | undefined, + ] + >; + updateDocument( + request: protos.google.firestore.v1.IUpdateDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; + updateDocument( + request: protos.google.firestore.v1.IUpdateDocumentRequest, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Deletes a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Document to delete. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * @param {google.firestore.v1.Precondition} request.currentDocument + * An optional precondition on the document. + * The request will fail if this is set and not met by the target document. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.delete_document.js + * region_tag:firestore_v1_generated_Firestore_DeleteDocument_async + */ + deleteDocument( + request?: protos.google.firestore.v1.IDeleteDocumentRequest, + options?: CallOptions + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | undefined, + {} | undefined, + ] + >; + deleteDocument( + request: protos.google.firestore.v1.IDeleteDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; + deleteDocument( + request: protos.google.firestore.v1.IDeleteDocumentRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Starts a new transaction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {google.firestore.v1.TransactionOptions} request.options + * The options for the transaction. + * Defaults to a read-write transaction. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.BeginTransactionResponse|BeginTransactionResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.begin_transaction.js + * region_tag:firestore_v1_generated_Firestore_BeginTransaction_async + */ + beginTransaction( + request?: protos.google.firestore.v1.IBeginTransactionRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest | undefined, + {} | undefined, + ] + >; + beginTransaction( + request: protos.google.firestore.v1.IBeginTransactionRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest | null | undefined, + {} | null | undefined + > + ): void; + beginTransaction( + request: protos.google.firestore.v1.IBeginTransactionRequest, + callback: Callback< + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Commits a transaction, while optionally updating documents. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {number[]} request.writes + * The writes to apply. + * + * Always executed atomically and in order. + * @param {Buffer} request.transaction + * If set, applies all writes in this transaction, and commits it. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.CommitResponse|CommitResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.commit.js + * region_tag:firestore_v1_generated_Firestore_Commit_async + */ + commit( + request?: protos.google.firestore.v1.ICommitRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | undefined, + {} | undefined, + ] + >; + commit( + request: protos.google.firestore.v1.ICommitRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | null | undefined, + {} | null | undefined + > + ): void; + commit( + request: protos.google.firestore.v1.ICommitRequest, + callback: Callback< + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Rolls back a transaction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {Buffer} request.transaction + * Required. The transaction to roll back. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.rollback.js + * region_tag:firestore_v1_generated_Firestore_Rollback_async + */ + rollback( + request?: protos.google.firestore.v1.IRollbackRequest, + options?: CallOptions + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | undefined, + {} | undefined, + ] + >; + rollback( + request: protos.google.firestore.v1.IRollbackRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | null | undefined, + {} | null | undefined + > + ): void; + rollback( + request: protos.google.firestore.v1.IRollbackRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Applies a batch of write operations. + * + * The BatchWrite method does not apply the write operations atomically + * and can apply them out of order. Method does not allow more than one write + * per document. Each write succeeds or fails independently. See the + * {@link protos.google.firestore.v1.BatchWriteResponse|BatchWriteResponse} for the + * success status of each write. + * + * If you require an atomically applied set of writes, use + * {@link protos.google.firestore.v1.Firestore.Commit|Commit} instead. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {number[]} request.writes + * The writes to apply. + * + * Method does not apply writes atomically and does not guarantee ordering. + * Each write succeeds or fails independently. You cannot write to the same + * document more than once per request. + * @param {number[]} request.labels + * Labels associated with this batch write. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.BatchWriteResponse|BatchWriteResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.batch_write.js + * region_tag:firestore_v1_generated_Firestore_BatchWrite_async + */ + batchWrite( + request?: protos.google.firestore.v1.IBatchWriteRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | undefined, + {} | undefined, + ] + >; + batchWrite( + request: protos.google.firestore.v1.IBatchWriteRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | null | undefined, + {} | null | undefined + > + ): void; + batchWrite( + request: protos.google.firestore.v1.IBatchWriteRequest, + callback: Callback< + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Creates a new document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource. For example: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: + * `chatrooms`. + * @param {string} request.documentId + * The client-assigned document ID to use for this document. + * + * Optional. If not specified, an ID will be assigned by the service. + * @param {google.firestore.v1.Document} request.document + * Required. The document to create. `name` must not be set. + * @param {google.firestore.v1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If the document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.create_document.js + * region_tag:firestore_v1_generated_Firestore_CreateDocument_async + */ + createDocument( + request?: protos.google.firestore.v1.ICreateDocumentRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | undefined, + {} | undefined, + ] + >; + createDocument( + request: protos.google.firestore.v1.ICreateDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; + createDocument( + request: protos.google.firestore.v1.ICreateDocumentRequest, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Gets multiple documents. + * + * Documents returned by this method are not guaranteed to be returned in the + * same order that they were requested. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.documents + * The names of the documents to retrieve. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * The request will fail if any of the document is not a child resource of the + * given `database`. Duplicate names will be elided. + * @param {google.firestore.v1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field will + * not be returned in the response. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * Starts a new transaction and reads the documents. + * Defaults to a read-only transaction. + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.BatchGetDocumentsResponse|BatchGetDocumentsResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.batch_get_documents.js + * region_tag:firestore_v1_generated_Firestore_BatchGetDocuments_async + */ + batchGetDocuments( + request?: protos.google.firestore.v1.IBatchGetDocumentsRequest, + options?: CallOptions + ): gax.CancellableStream; + /** + * Runs a query. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * @param {Buffer} request.transaction + * Run the query within an already active transaction. + * + * The value here is the opaque transaction ID to execute the query in. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * Starts a new transaction and reads the documents. + * Defaults to a read-only transaction. + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {google.firestore.v1.ExplainOptions} [request.explainOptions] + * Optional. Explain options for the query. If set, additional query + * statistics will be returned. If not, only query results will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.RunQueryResponse|RunQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.run_query.js + * region_tag:firestore_v1_generated_Firestore_RunQuery_async + */ + runQuery( + request?: protos.google.firestore.v1.IRunQueryRequest, + options?: CallOptions + ): gax.CancellableStream; + /** + * Runs an aggregation query. + * + * Rather than producing {@link protos.google.firestore.v1.Document|Document} results like + * {@link protos.google.firestore.v1.Firestore.RunQuery|Firestore.RunQuery}, this API + * allows running an aggregation to produce a series of + * {@link protos.google.firestore.v1.AggregationResult|AggregationResult} server-side. + * + * High-Level Example: + * + * ``` + * -- Return the number of documents in table given a filter. + * SELECT COUNT(*) FROM ( SELECT * FROM k where a = true ); + * ``` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {google.firestore.v1.StructuredAggregationQuery} request.structuredAggregationQuery + * An aggregation query. + * @param {Buffer} request.transaction + * Run the aggregation within an already active transaction. + * + * The value here is the opaque transaction ID to execute the query in. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * Starts a new transaction as part of the query, defaulting to read-only. + * + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Executes the query at the given timestamp. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {google.firestore.v1.ExplainOptions} [request.explainOptions] + * Optional. Explain options for the query. If set, additional query + * statistics will be returned. If not, only query results will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.RunAggregationQueryResponse|RunAggregationQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.run_aggregation_query.js + * region_tag:firestore_v1_generated_Firestore_RunAggregationQuery_async + */ + runAggregationQuery( + request?: protos.google.firestore.v1.IRunAggregationQueryRequest, + options?: CallOptions + ): gax.CancellableStream; + /** + * Streams batches of document updates and deletes, in order. This method is + * only available via gRPC or WebChannel (not REST). + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1.WriteRequest|WriteRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1.WriteResponse|WriteResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.write.js + * region_tag:firestore_v1_generated_Firestore_Write_async + */ + write(options?: CallOptions): gax.CancellableStream; + /** + * Listens to changes. This method is only available via gRPC or WebChannel + * (not REST). + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1.ListenRequest|ListenRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1.ListenResponse|ListenResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.listen.js + * region_tag:firestore_v1_generated_Firestore_Listen_async + */ + listen(options?: CallOptions): gax.CancellableStream; + /** + * Lists documents. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} [request.collectionId] + * Optional. The collection ID, relative to `parent`, to list. + * + * For example: `chatrooms` or `messages`. + * + * This is optional, and when not provided, Firestore will list documents + * from all collections under the provided `parent`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` response. + * + * Provide this to retrieve the subsequent page. When paginating, all other + * parameters (with the exception of `page_size`) must match the values set + * in the request that generated the page token. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * Optional. The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Perform the read as part of an already active transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Perform the read at the provided time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {boolean} request.showMissing + * If the list should show missing documents. + * + * A document is missing if it does not exist, but there are sub-documents + * nested underneath it. When true, such missing documents will be returned + * with a key but will not have fields, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.v1.Document|Document}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDocuments( + request?: protos.google.firestore.v1.IListDocumentsRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1.IDocument[], + protos.google.firestore.v1.IListDocumentsRequest | null, + protos.google.firestore.v1.IListDocumentsResponse, + ] + >; + listDocuments( + request: protos.google.firestore.v1.IListDocumentsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1.IListDocumentsRequest, + protos.google.firestore.v1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1.IDocument + > + ): void; + listDocuments( + request: protos.google.firestore.v1.IListDocumentsRequest, + callback: PaginationCallback< + protos.google.firestore.v1.IListDocumentsRequest, + protos.google.firestore.v1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1.IDocument + > + ): void; + /** + * Equivalent to `listDocuments`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} [request.collectionId] + * Optional. The collection ID, relative to `parent`, to list. + * + * For example: `chatrooms` or `messages`. + * + * This is optional, and when not provided, Firestore will list documents + * from all collections under the provided `parent`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` response. + * + * Provide this to retrieve the subsequent page. When paginating, all other + * parameters (with the exception of `page_size`) must match the values set + * in the request that generated the page token. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * Optional. The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Perform the read as part of an already active transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Perform the read at the provided time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {boolean} request.showMissing + * If the list should show missing documents. + * + * A document is missing if it does not exist, but there are sub-documents + * nested underneath it. When true, such missing documents will be returned + * with a key but will not have fields, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1.Document|Document} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDocumentsStream( + request?: protos.google.firestore.v1.IListDocumentsRequest, + options?: CallOptions + ): Transform; + /** + * Equivalent to `listDocuments`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} [request.collectionId] + * Optional. The collection ID, relative to `parent`, to list. + * + * For example: `chatrooms` or `messages`. + * + * This is optional, and when not provided, Firestore will list documents + * from all collections under the provided `parent`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` response. + * + * Provide this to retrieve the subsequent page. When paginating, all other + * parameters (with the exception of `page_size`) must match the values set + * in the request that generated the page token. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * Optional. The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Perform the read as part of an already active transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Perform the read at the provided time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {boolean} request.showMissing + * If the list should show missing documents. + * + * A document is missing if it does not exist, but there are sub-documents + * nested underneath it. When true, such missing documents will be returned + * with a key but will not have fields, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1.Document|Document}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.list_documents.js + * region_tag:firestore_v1_generated_Firestore_ListDocuments_async + */ + listDocumentsAsync( + request?: protos.google.firestore.v1.IListDocumentsRequest, + options?: CallOptions + ): AsyncIterable; + /** + * Partitions a query by returning partition cursors that can be used to run + * the query in parallel. The returned partition cursors are split points that + * can be used by RunQuery as starting/end points for the query results. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.v1.Cursor|Cursor}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + partitionQuery( + request?: protos.google.firestore.v1.IPartitionQueryRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1.ICursor[], + protos.google.firestore.v1.IPartitionQueryRequest | null, + protos.google.firestore.v1.IPartitionQueryResponse, + ] + >; + partitionQuery( + request: protos.google.firestore.v1.IPartitionQueryRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1.IPartitionQueryRequest, + protos.google.firestore.v1.IPartitionQueryResponse | null | undefined, + protos.google.firestore.v1.ICursor + > + ): void; + partitionQuery( + request: protos.google.firestore.v1.IPartitionQueryRequest, + callback: PaginationCallback< + protos.google.firestore.v1.IPartitionQueryRequest, + protos.google.firestore.v1.IPartitionQueryResponse | null | undefined, + protos.google.firestore.v1.ICursor + > + ): void; + /** + * Equivalent to `partitionQuery`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1.Cursor|Cursor} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + partitionQueryStream( + request?: protos.google.firestore.v1.IPartitionQueryRequest, + options?: CallOptions + ): Transform; + /** + * Equivalent to `partitionQuery`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1.Cursor|Cursor}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.partition_query.js + * region_tag:firestore_v1_generated_Firestore_PartitionQuery_async + */ + partitionQueryAsync( + request?: protos.google.firestore.v1.IPartitionQueryRequest, + options?: CallOptions + ): AsyncIterable; + /** + * Lists all the collection IDs underneath a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of string. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listCollectionIds( + request?: protos.google.firestore.v1.IListCollectionIdsRequest, + options?: CallOptions + ): Promise< + [ + string[], + protos.google.firestore.v1.IListCollectionIdsRequest | null, + protos.google.firestore.v1.IListCollectionIdsResponse, + ] + >; + listCollectionIds( + request: protos.google.firestore.v1.IListCollectionIdsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1.IListCollectionIdsRequest, + protos.google.firestore.v1.IListCollectionIdsResponse | null | undefined, + string + > + ): void; + listCollectionIds( + request: protos.google.firestore.v1.IListCollectionIdsRequest, + callback: PaginationCallback< + protos.google.firestore.v1.IListCollectionIdsRequest, + protos.google.firestore.v1.IListCollectionIdsResponse | null | undefined, + string + > + ): void; + /** + * Equivalent to `listCollectionIds`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing string on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listCollectionIdsStream( + request?: protos.google.firestore.v1.IListCollectionIdsRequest, + options?: CallOptions + ): Transform; + /** + * Equivalent to `listCollectionIds`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * string. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.list_collection_ids.js + * region_tag:firestore_v1_generated_Firestore_ListCollectionIds_async + */ + listCollectionIdsAsync( + request?: protos.google.firestore.v1.IListCollectionIdsRequest, + options?: CallOptions + ): AsyncIterable; + /** + * Gets information about a location. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Resource name for the location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html | CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.cloud.location.Location | Location}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * ``` + * const [response] = await client.getLocation(request); + * ``` + */ + getLocation( + request: LocationProtos.google.cloud.location.IGetLocationRequest, + options?: + | gax.CallOptions + | Callback< + LocationProtos.google.cloud.location.ILocation, + | LocationProtos.google.cloud.location.IGetLocationRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + LocationProtos.google.cloud.location.ILocation, + | LocationProtos.google.cloud.location.IGetLocationRequest + | null + | undefined, + {} | null | undefined + > + ): Promise; + /** + * Lists information about the supported locations for this service. Returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource that owns the locations collection, if applicable. + * @param {string} request.filter + * The standard list filter. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link google.cloud.location.Location | Location}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * ``` + * const iterable = client.listLocationsAsync(request); + * for await (const response of iterable) { + * // process response + * } + * ``` + */ + listLocationsAsync( + request: LocationProtos.google.cloud.location.IListLocationsRequest, + options?: CallOptions + ): AsyncIterable; + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise; +} diff --git a/node_modules/@google-cloud/firestore/types/v1beta1/firestore_client.d.ts b/node_modules/@google-cloud/firestore/types/v1beta1/firestore_client.d.ts new file mode 100644 index 0000000..bc74df6 --- /dev/null +++ b/node_modules/@google-cloud/firestore/types/v1beta1/firestore_client.d.ts @@ -0,0 +1,1211 @@ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type * as gax from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, +} from 'google-gax'; +import {Transform} from 'stream'; +import * as protos from '../protos/firestore_v1beta1_proto_api'; +/** + * The Cloud Firestore service. + * + * Cloud Firestore is a fast, fully managed, serverless, cloud-native NoSQL + * document database that simplifies storing, syncing, and querying data for + * your mobile, web, and IoT apps at global scale. Its client libraries provide + * live synchronization and offline support, while its security features and + * integrations with Firebase and Google Cloud Platform (GCP) accelerate + * building truly serverless apps. + * @class + * @deprecated Use v1/firestore_client instead. + * @memberof v1beta1 + */ +export declare class FirestoreClient { + private _terminated; + private _opts; + private _providedCustomServicePath; + private _gaxModule; + private _gaxGrpc; + private _protos; + private _defaults; + private _universeDomain; + private _servicePath; + auth: gax.GoogleAuth; + descriptors: Descriptors; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: { + [name: string]: Function; + }; + firestoreStub?: Promise<{ + [name: string]: Function; + }>; + /** + * Construct an instance of FirestoreClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param {string} [options.apiEndpoint] - The domain name of the + * API remote host. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new FirestoreClient({fallback: true}, gax); + * ``` + */ + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback + ); + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize(): Promise<{ + [name: string]: Function; + }>; + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath(): string; + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint(): string; + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint(): string; + get universeDomain(): string; + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port(): number; + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes(): string[]; + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Gets a single document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Document to get. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If the document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Reads the document in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads the version of the document at the given time. + * This may not be older than 270 seconds. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.get_document.js + * region_tag:firestore_v1beta1_generated_Firestore_GetDocument_async + */ + getDocument( + request?: protos.google.firestore.v1beta1.IGetDocumentRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IGetDocumentRequest | undefined, + {} | undefined, + ] + >; + getDocument( + request: protos.google.firestore.v1beta1.IGetDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IGetDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; + getDocument( + request: protos.google.firestore.v1beta1.IGetDocumentRequest, + callback: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IGetDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Updates or inserts a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.v1beta1.Document} request.document + * Required. The updated document. + * Creates the document if it does not already exist. + * @param {google.firestore.v1beta1.DocumentMask} request.updateMask + * The fields to update. + * None of the field paths in the mask may contain a reserved name. + * + * If the document exists on the server and has fields not referenced in the + * mask, they are left unchanged. + * Fields referenced in the mask, but not present in the input document, are + * deleted from the document on the server. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If the document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {google.firestore.v1beta1.Precondition} request.currentDocument + * An optional precondition on the document. + * The request will fail if this is set and not met by the target document. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.update_document.js + * region_tag:firestore_v1beta1_generated_Firestore_UpdateDocument_async + */ + updateDocument( + request?: protos.google.firestore.v1beta1.IUpdateDocumentRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IUpdateDocumentRequest | undefined, + {} | undefined, + ] + >; + updateDocument( + request: protos.google.firestore.v1beta1.IUpdateDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; + updateDocument( + request: protos.google.firestore.v1beta1.IUpdateDocumentRequest, + callback: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Deletes a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Document to delete. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * @param {google.firestore.v1beta1.Precondition} request.currentDocument + * An optional precondition on the document. + * The request will fail if this is set and not met by the target document. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.delete_document.js + * region_tag:firestore_v1beta1_generated_Firestore_DeleteDocument_async + */ + deleteDocument( + request?: protos.google.firestore.v1beta1.IDeleteDocumentRequest, + options?: CallOptions + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IDeleteDocumentRequest | undefined, + {} | undefined, + ] + >; + deleteDocument( + request: protos.google.firestore.v1beta1.IDeleteDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; + deleteDocument( + request: protos.google.firestore.v1beta1.IDeleteDocumentRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Starts a new transaction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {google.firestore.v1beta1.TransactionOptions} request.options + * The options for the transaction. + * Defaults to a read-write transaction. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.BeginTransactionResponse|BeginTransactionResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.begin_transaction.js + * region_tag:firestore_v1beta1_generated_Firestore_BeginTransaction_async + */ + beginTransaction( + request?: protos.google.firestore.v1beta1.IBeginTransactionRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1beta1.IBeginTransactionResponse, + protos.google.firestore.v1beta1.IBeginTransactionRequest | undefined, + {} | undefined, + ] + >; + beginTransaction( + request: protos.google.firestore.v1beta1.IBeginTransactionRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1beta1.IBeginTransactionResponse, + | protos.google.firestore.v1beta1.IBeginTransactionRequest + | null + | undefined, + {} | null | undefined + > + ): void; + beginTransaction( + request: protos.google.firestore.v1beta1.IBeginTransactionRequest, + callback: Callback< + protos.google.firestore.v1beta1.IBeginTransactionResponse, + | protos.google.firestore.v1beta1.IBeginTransactionRequest + | null + | undefined, + {} | null | undefined + > + ): void; + /** + * Commits a transaction, while optionally updating documents. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {number[]} request.writes + * The writes to apply. + * + * Always executed atomically and in order. + * @param {Buffer} request.transaction + * If set, applies all writes in this transaction, and commits it. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.CommitResponse|CommitResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.commit.js + * region_tag:firestore_v1beta1_generated_Firestore_Commit_async + */ + commit( + request?: protos.google.firestore.v1beta1.ICommitRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1beta1.ICommitResponse, + protos.google.firestore.v1beta1.ICommitRequest | undefined, + {} | undefined, + ] + >; + commit( + request: protos.google.firestore.v1beta1.ICommitRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1beta1.ICommitResponse, + protos.google.firestore.v1beta1.ICommitRequest | null | undefined, + {} | null | undefined + > + ): void; + commit( + request: protos.google.firestore.v1beta1.ICommitRequest, + callback: Callback< + protos.google.firestore.v1beta1.ICommitResponse, + protos.google.firestore.v1beta1.ICommitRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Rolls back a transaction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {Buffer} request.transaction + * Required. The transaction to roll back. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.rollback.js + * region_tag:firestore_v1beta1_generated_Firestore_Rollback_async + */ + rollback( + request?: protos.google.firestore.v1beta1.IRollbackRequest, + options?: CallOptions + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IRollbackRequest | undefined, + {} | undefined, + ] + >; + rollback( + request: protos.google.firestore.v1beta1.IRollbackRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IRollbackRequest | null | undefined, + {} | null | undefined + > + ): void; + rollback( + request: protos.google.firestore.v1beta1.IRollbackRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1beta1.IRollbackRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Applies a batch of write operations. + * + * The BatchWrite method does not apply the write operations atomically + * and can apply them out of order. Method does not allow more than one write + * per document. Each write succeeds or fails independently. See the + * {@link protos.google.firestore.v1beta1.BatchWriteResponse|BatchWriteResponse} for the success status of each write. + * + * If you require an atomically applied set of writes, use + * {@link protos.google.firestore.v1beta1.Firestore.Commit|Commit} instead. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {number[]} request.writes + * The writes to apply. + * + * Method does not apply writes atomically and does not guarantee ordering. + * Each write succeeds or fails independently. You cannot write to the same + * document more than once per request. + * @param {number[]} request.labels + * Labels associated with this batch write. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.BatchWriteResponse|BatchWriteResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.batch_write.js + * region_tag:firestore_v1beta1_generated_Firestore_BatchWrite_async + */ + batchWrite( + request?: protos.google.firestore.v1beta1.IBatchWriteRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1beta1.IBatchWriteResponse, + protos.google.firestore.v1beta1.IBatchWriteRequest | undefined, + {} | undefined, + ] + >; + batchWrite( + request: protos.google.firestore.v1beta1.IBatchWriteRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1beta1.IBatchWriteResponse, + protos.google.firestore.v1beta1.IBatchWriteRequest | null | undefined, + {} | null | undefined + > + ): void; + batchWrite( + request: protos.google.firestore.v1beta1.IBatchWriteRequest, + callback: Callback< + protos.google.firestore.v1beta1.IBatchWriteResponse, + protos.google.firestore.v1beta1.IBatchWriteRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Creates a new document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource. For example: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms`. + * @param {string} request.documentId + * The client-assigned document ID to use for this document. + * + * Optional. If not specified, an ID will be assigned by the service. + * @param {google.firestore.v1beta1.Document} request.document + * Required. The document to create. `name` must not be set. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If the document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.create_document.js + * region_tag:firestore_v1beta1_generated_Firestore_CreateDocument_async + */ + createDocument( + request?: protos.google.firestore.v1beta1.ICreateDocumentRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.ICreateDocumentRequest | undefined, + {} | undefined, + ] + >; + createDocument( + request: protos.google.firestore.v1beta1.ICreateDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; + createDocument( + request: protos.google.firestore.v1beta1.ICreateDocumentRequest, + callback: Callback< + protos.google.firestore.v1beta1.IDocument, + protos.google.firestore.v1beta1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Gets multiple documents. + * + * Documents returned by this method are not guaranteed to be returned in the + * same order that they were requested. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.documents + * The names of the documents to retrieve. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * The request will fail if any of the document is not a child resource of the + * given `database`. Duplicate names will be elided. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field will + * not be returned in the response. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.firestore.v1beta1.TransactionOptions} request.newTransaction + * Starts a new transaction and reads the documents. + * Defaults to a read-only transaction. + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1beta1.BatchGetDocumentsResponse|BatchGetDocumentsResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.batch_get_documents.js + * region_tag:firestore_v1beta1_generated_Firestore_BatchGetDocuments_async + */ + batchGetDocuments( + request?: protos.google.firestore.v1beta1.IBatchGetDocumentsRequest, + options?: CallOptions + ): gax.CancellableStream; + /** + * Runs a query. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {google.firestore.v1beta1.StructuredQuery} request.structuredQuery + * A structured query. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.firestore.v1beta1.TransactionOptions} request.newTransaction + * Starts a new transaction and reads the documents. + * Defaults to a read-only transaction. + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1beta1.RunQueryResponse|RunQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.run_query.js + * region_tag:firestore_v1beta1_generated_Firestore_RunQuery_async + */ + runQuery( + request?: protos.google.firestore.v1beta1.IRunQueryRequest, + options?: CallOptions + ): gax.CancellableStream; + /** + * Streams batches of document updates and deletes, in order. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1beta1.WriteRequest|WriteRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1beta1.WriteResponse|WriteResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.write.js + * region_tag:firestore_v1beta1_generated_Firestore_Write_async + */ + write(options?: CallOptions): gax.CancellableStream; + /** + * Listens to changes. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1beta1.ListenRequest|ListenRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1beta1.ListenResponse|ListenResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.listen.js + * region_tag:firestore_v1beta1_generated_Firestore_Listen_async + */ + listen(options?: CallOptions): gax.CancellableStream; + /** + * Lists documents. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` + * or `messages`. + * @param {number} request.pageSize + * The maximum number of documents to return. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous List request, if any. + * @param {string} request.orderBy + * The order to sort results by. For example: `priority desc, name`. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {boolean} request.showMissing + * If the list should show missing documents. A missing document is a + * document that does not exist but has sub-documents. These documents will + * be returned with a key but will not have fields, {@link protos.google.firestore.v1beta1.Document.create_time|Document.create_time}, + * or {@link protos.google.firestore.v1beta1.Document.update_time|Document.update_time} set. + * + * Requests with `show_missing` may not specify `where` or + * `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.v1beta1.Document|Document}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDocuments( + request?: protos.google.firestore.v1beta1.IListDocumentsRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1beta1.IDocument[], + protos.google.firestore.v1beta1.IListDocumentsRequest | null, + protos.google.firestore.v1beta1.IListDocumentsResponse, + ] + >; + listDocuments( + request: protos.google.firestore.v1beta1.IListDocumentsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1beta1.IListDocumentsRequest, + protos.google.firestore.v1beta1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1beta1.IDocument + > + ): void; + listDocuments( + request: protos.google.firestore.v1beta1.IListDocumentsRequest, + callback: PaginationCallback< + protos.google.firestore.v1beta1.IListDocumentsRequest, + protos.google.firestore.v1beta1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1beta1.IDocument + > + ): void; + /** + * Equivalent to `listDocuments`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` + * or `messages`. + * @param {number} request.pageSize + * The maximum number of documents to return. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous List request, if any. + * @param {string} request.orderBy + * The order to sort results by. For example: `priority desc, name`. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {boolean} request.showMissing + * If the list should show missing documents. A missing document is a + * document that does not exist but has sub-documents. These documents will + * be returned with a key but will not have fields, {@link protos.google.firestore.v1beta1.Document.create_time|Document.create_time}, + * or {@link protos.google.firestore.v1beta1.Document.update_time|Document.update_time} set. + * + * Requests with `show_missing` may not specify `where` or + * `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1beta1.Document|Document} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDocumentsStream( + request?: protos.google.firestore.v1beta1.IListDocumentsRequest, + options?: CallOptions + ): Transform; + /** + * Equivalent to `listDocuments`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` + * or `messages`. + * @param {number} request.pageSize + * The maximum number of documents to return. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous List request, if any. + * @param {string} request.orderBy + * The order to sort results by. For example: `priority desc, name`. + * @param {google.firestore.v1beta1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * This may not be older than 270 seconds. + * @param {boolean} request.showMissing + * If the list should show missing documents. A missing document is a + * document that does not exist but has sub-documents. These documents will + * be returned with a key but will not have fields, {@link protos.google.firestore.v1beta1.Document.create_time|Document.create_time}, + * or {@link protos.google.firestore.v1beta1.Document.update_time|Document.update_time} set. + * + * Requests with `show_missing` may not specify `where` or + * `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1beta1.Document|Document}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.list_documents.js + * region_tag:firestore_v1beta1_generated_Firestore_ListDocuments_async + */ + listDocumentsAsync( + request?: protos.google.firestore.v1beta1.IListDocumentsRequest, + options?: CallOptions + ): AsyncIterable; + /** + * Partitions a query by returning partition cursors that can be used to run + * the query in parallel. The returned partition cursors are split points that + * can be used by RunQuery as starting/end points for the query results. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1beta1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.v1beta1.Cursor|Cursor}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + partitionQuery( + request?: protos.google.firestore.v1beta1.IPartitionQueryRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1beta1.ICursor[], + protos.google.firestore.v1beta1.IPartitionQueryRequest | null, + protos.google.firestore.v1beta1.IPartitionQueryResponse, + ] + >; + partitionQuery( + request: protos.google.firestore.v1beta1.IPartitionQueryRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1beta1.IPartitionQueryRequest, + | protos.google.firestore.v1beta1.IPartitionQueryResponse + | null + | undefined, + protos.google.firestore.v1beta1.ICursor + > + ): void; + partitionQuery( + request: protos.google.firestore.v1beta1.IPartitionQueryRequest, + callback: PaginationCallback< + protos.google.firestore.v1beta1.IPartitionQueryRequest, + | protos.google.firestore.v1beta1.IPartitionQueryResponse + | null + | undefined, + protos.google.firestore.v1beta1.ICursor + > + ): void; + /** + * Equivalent to `partitionQuery`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1beta1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1beta1.Cursor|Cursor} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + partitionQueryStream( + request?: protos.google.firestore.v1beta1.IPartitionQueryRequest, + options?: CallOptions + ): Transform; + /** + * Equivalent to `partitionQuery`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1beta1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1beta1.Cursor|Cursor}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.partition_query.js + * region_tag:firestore_v1beta1_generated_Firestore_PartitionQuery_async + */ + partitionQueryAsync( + request?: protos.google.firestore.v1beta1.IPartitionQueryRequest, + options?: CallOptions + ): AsyncIterable; + /** + * Lists all the collection IDs underneath a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1beta1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of string. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listCollectionIds( + request?: protos.google.firestore.v1beta1.IListCollectionIdsRequest, + options?: CallOptions + ): Promise< + [ + string[], + protos.google.firestore.v1beta1.IListCollectionIdsRequest | null, + protos.google.firestore.v1beta1.IListCollectionIdsResponse, + ] + >; + listCollectionIds( + request: protos.google.firestore.v1beta1.IListCollectionIdsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1beta1.IListCollectionIdsRequest, + | protos.google.firestore.v1beta1.IListCollectionIdsResponse + | null + | undefined, + string + > + ): void; + listCollectionIds( + request: protos.google.firestore.v1beta1.IListCollectionIdsRequest, + callback: PaginationCallback< + protos.google.firestore.v1beta1.IListCollectionIdsRequest, + | protos.google.firestore.v1beta1.IListCollectionIdsResponse + | null + | undefined, + string + > + ): void; + /** + * Equivalent to `listCollectionIds`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1beta1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing string on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listCollectionIdsStream( + request?: protos.google.firestore.v1beta1.IListCollectionIdsRequest, + options?: CallOptions + ): Transform; + /** + * Equivalent to `listCollectionIds`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1beta1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * string. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/firestore.list_collection_ids.js + * region_tag:firestore_v1beta1_generated_Firestore_ListCollectionIds_async + */ + listCollectionIdsAsync( + request?: protos.google.firestore.v1beta1.IListCollectionIdsRequest, + options?: CallOptions + ): AsyncIterable; + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise; +} diff --git a/node_modules/@google-cloud/paginator/CHANGELOG.md b/node_modules/@google-cloud/paginator/CHANGELOG.md new file mode 100644 index 0000000..3b16722 --- /dev/null +++ b/node_modules/@google-cloud/paginator/CHANGELOG.md @@ -0,0 +1,262 @@ +# Changelog + +[npm history][1] + +[1]: https://www.npmjs.com/package/nodejs-paginator?activeTab=versions + +## [5.0.2](https://github.com/googleapis/nodejs-paginator/compare/v5.0.1...v5.0.2) (2024-05-23) + + +### Bug Fixes + +* Query should be on the list of extra args ([#365](https://github.com/googleapis/nodejs-paginator/issues/365)) ([50e40d0](https://github.com/googleapis/nodejs-paginator/commit/50e40d064aed1bd0d5f93a51ad54112343086644)) + +## [5.0.1](https://github.com/googleapis/nodejs-paginator/compare/v5.0.0...v5.0.1) (2024-05-22) + + +### Bug Fixes + +* Should pass extra callback arguments back to consumer ([#361](https://github.com/googleapis/nodejs-paginator/issues/361)) ([cc5c48b](https://github.com/googleapis/nodejs-paginator/commit/cc5c48b95b21e9c6a4e555ff98de267258657b6e)) + +## [5.0.0](https://github.com/googleapis/nodejs-paginator/compare/v4.0.1...v5.0.0) (2023-08-09) + + +### ⚠ BREAKING CHANGES + +* update to Node 14 ([#346](https://github.com/googleapis/nodejs-paginator/issues/346)) + +### Miscellaneous Chores + +* Update to Node 14 ([#346](https://github.com/googleapis/nodejs-paginator/issues/346)) ([262ad70](https://github.com/googleapis/nodejs-paginator/commit/262ad70d3cc5e1aa8a67ece54c04920b24ceea09)) + +## [4.0.1](https://github.com/googleapis/nodejs-paginator/compare/v4.0.0...v4.0.1) (2022-09-09) + + +### Bug Fixes + +* Remove pip install statements ([#1546](https://github.com/googleapis/nodejs-paginator/issues/1546)) ([#329](https://github.com/googleapis/nodejs-paginator/issues/329)) ([697567b](https://github.com/googleapis/nodejs-paginator/commit/697567bdd86226b740304734b9562a2f2241a96f)) + +## [4.0.0](https://github.com/googleapis/nodejs-paginator/compare/v3.0.7...v4.0.0) (2022-05-17) + + +### ⚠ BREAKING CHANGES + +* update library to use Node 12 (#325) + +### Build System + +* update library to use Node 12 ([#325](https://github.com/googleapis/nodejs-paginator/issues/325)) ([02887ae](https://github.com/googleapis/nodejs-paginator/commit/02887ae2b370bff18cae7fe1d434ecdf663b5748)) + +### [3.0.7](https://github.com/googleapis/nodejs-paginator/compare/v3.0.6...v3.0.7) (2022-02-14) + + +### Bug Fixes + +* update signature of end to comply with update node types definition ([#311](https://github.com/googleapis/nodejs-paginator/issues/311)) ([79e6fbd](https://github.com/googleapis/nodejs-paginator/commit/79e6fbdae5008d874613d2919a6cf723708fc919)) + +### [3.0.6](https://www.github.com/googleapis/nodejs-paginator/compare/v3.0.5...v3.0.6) (2021-09-09) + + +### Bug Fixes + +* **build:** switch primary branch to main ([#287](https://www.github.com/googleapis/nodejs-paginator/issues/287)) ([1b796f3](https://www.github.com/googleapis/nodejs-paginator/commit/1b796f3377174354a62b7475d16f52213197f650)) + +### [3.0.5](https://www.github.com/googleapis/nodejs-paginator/compare/v3.0.4...v3.0.5) (2020-09-02) + + +### Bug Fixes + +* add configs by running synthtool ([#241](https://www.github.com/googleapis/nodejs-paginator/issues/241)) ([643593a](https://www.github.com/googleapis/nodejs-paginator/commit/643593ae9ffb8febff69a7bdae19239f5bcb1266)) + +### [3.0.4](https://www.github.com/googleapis/nodejs-paginator/compare/v3.0.3...v3.0.4) (2020-08-06) + + +### Bug Fixes + +* destroy ResourceStream with pre-flight error ([#236](https://www.github.com/googleapis/nodejs-paginator/issues/236)) ([d57beb4](https://www.github.com/googleapis/nodejs-paginator/commit/d57beb424d875a7bf502d458cc208f1bbe47a42a)) + +### [3.0.3](https://www.github.com/googleapis/nodejs-paginator/compare/v3.0.2...v3.0.3) (2020-07-24) + + +### Bug Fixes + +* move gitattributes files to node templates ([#234](https://www.github.com/googleapis/nodejs-paginator/issues/234)) ([30e881c](https://www.github.com/googleapis/nodejs-paginator/commit/30e881ce7415749b93b6b7e4e71745ea3fb248b6)) + +### [3.0.2](https://www.github.com/googleapis/nodejs-paginator/compare/v3.0.1...v3.0.2) (2020-07-06) + + +### Bug Fixes + +* update node issue template ([#221](https://www.github.com/googleapis/nodejs-paginator/issues/221)) ([088153c](https://www.github.com/googleapis/nodejs-paginator/commit/088153c4fca6d53e2e5ef4bb42365ce5493b913d)) + +### [3.0.1](https://www.github.com/googleapis/nodejs-paginator/compare/v3.0.0...v3.0.1) (2020-05-20) + + +### Bug Fixes + +* apache license URL ([#468](https://www.github.com/googleapis/nodejs-paginator/issues/468)) ([#211](https://www.github.com/googleapis/nodejs-paginator/issues/211)) ([f343b7f](https://www.github.com/googleapis/nodejs-paginator/commit/f343b7f7e184fd1b453f20ac1463d17520aac7ad)) + +## [3.0.0](https://www.github.com/googleapis/nodejs-paginator/compare/v2.0.3...v3.0.0) (2020-03-25) + + +### ⚠ BREAKING CHANGES + +* **dep:** upgrade gts 2.0.0 (#194) +* **deps:** deprecated node 8 to 10; upgrade typescript + +### Miscellaneous Chores + +* **dep:** upgrade gts 2.0.0 ([#194](https://www.github.com/googleapis/nodejs-paginator/issues/194)) ([4eaf9be](https://www.github.com/googleapis/nodejs-paginator/commit/4eaf9bed1fcfd0f10e877ff15c1d0e968e3356c8)) +* **deps:** deprecated node 8 to 10; upgrade typescript ([f6434ab](https://www.github.com/googleapis/nodejs-paginator/commit/f6434ab9cacb6ab804c070f19c38b6072ca326b5)) + +### [2.0.3](https://www.github.com/googleapis/nodejs-paginator/compare/v2.0.2...v2.0.3) (2019-12-05) + + +### Bug Fixes + +* **deps:** pin TypeScript below 3.7.0 ([e06e1b0](https://www.github.com/googleapis/nodejs-paginator/commit/e06e1b0a2e2bb1cf56fc806c1703b8b5e468b954)) + +### [2.0.2](https://www.github.com/googleapis/nodejs-paginator/compare/v2.0.1...v2.0.2) (2019-11-13) + + +### Bug Fixes + +* **docs:** add jsdoc-region-tag plugin ([#155](https://www.github.com/googleapis/nodejs-paginator/issues/155)) ([b983799](https://www.github.com/googleapis/nodejs-paginator/commit/b98379905848fd179c6268aff3e1cfaf2bf76663)) + +### [2.0.1](https://www.github.com/googleapis/nodejs-paginator/compare/v2.0.0...v2.0.1) (2019-08-25) + + +### Bug Fixes + +* **deps:** use the latest extend ([#141](https://www.github.com/googleapis/nodejs-paginator/issues/141)) ([61b383e](https://www.github.com/googleapis/nodejs-paginator/commit/61b383e)) + +## [2.0.0](https://www.github.com/googleapis/nodejs-paginator/compare/v1.0.2...v2.0.0) (2019-07-12) + + +### ⚠ BREAKING CHANGES + +* rewrite streaming logic (#136) + +### Code Refactoring + +* rewrite streaming logic ([#136](https://www.github.com/googleapis/nodejs-paginator/issues/136)) ([641d82d](https://www.github.com/googleapis/nodejs-paginator/commit/641d82d)) + +### [1.0.2](https://www.github.com/googleapis/nodejs-paginator/compare/v1.0.1...v1.0.2) (2019-06-26) + + +### Bug Fixes + +* **docs:** link to reference docs section on googleapis.dev ([#132](https://www.github.com/googleapis/nodejs-paginator/issues/132)) ([be231be](https://www.github.com/googleapis/nodejs-paginator/commit/be231be)) + +### [1.0.1](https://www.github.com/googleapis/nodejs-paginator/compare/v1.0.0...v1.0.1) (2019-06-14) + + +### Bug Fixes + +* **docs:** move to new client docs URL ([#129](https://www.github.com/googleapis/nodejs-paginator/issues/129)) ([689f483](https://www.github.com/googleapis/nodejs-paginator/commit/689f483)) + +## [1.0.0](https://www.github.com/googleapis/nodejs-paginator/compare/v0.2.0...v1.0.0) (2019-05-03) + + +### Bug Fixes + +* **deps:** update dependency arrify to v2 ([#109](https://www.github.com/googleapis/nodejs-paginator/issues/109)) ([9f06c83](https://www.github.com/googleapis/nodejs-paginator/commit/9f06c83)) + + +### Build System + +* upgrade engines field to >=8.10.0 ([#115](https://www.github.com/googleapis/nodejs-paginator/issues/115)) ([0921076](https://www.github.com/googleapis/nodejs-paginator/commit/0921076)) + + +### BREAKING CHANGES + +* upgrade engines field to >=8.10.0 (#115) + +## v0.2.0 + +03-08-2019 12:15 PST + +### New Features +- feat: handle promise based functions ([#91](https://github.com/googleapis/nodejs-paginator/pull/91)) +- refactor(ts): create generic for object streams ([#101](https://github.com/googleapis/nodejs-paginator/pull/101)) + +### Dependencies +- chore(deps): update dependency through2 to v3 ([#53](https://github.com/googleapis/nodejs-paginator/pull/53)) +- chore(deps): update dependency @types/is to v0.0.21 ([#55](https://github.com/googleapis/nodejs-paginator/pull/55)) +- chore(deps): update dependency gts to ^0.9.0 ([#57](https://github.com/googleapis/nodejs-paginator/pull/57)) +- fix: Pin @types/sinon to last compatible version ([#61](https://github.com/googleapis/nodejs-paginator/pull/61)) +- refactor: trim a few dependencies ([#60](https://github.com/googleapis/nodejs-paginator/pull/60)) +- chore(deps): update dependency @types/sinon to v5.0.7 ([#62](https://github.com/googleapis/nodejs-paginator/pull/62)) +- chore(deps): update dependency @types/sinon to v7 ([#81](https://github.com/googleapis/nodejs-paginator/pull/81)) +- chore(deps): update dependency mocha to v6 + +### Documentation +- docs: add lint/fix example to contributing guide ([#85](https://github.com/googleapis/nodejs-paginator/pull/85)) +- chore: move CONTRIBUTING.md to root ([#87](https://github.com/googleapis/nodejs-paginator/pull/87)) +- docs: update links in contrib guide ([#94](https://github.com/googleapis/nodejs-paginator/pull/94)) +- docs: update contributing path in README ([#88](https://github.com/googleapis/nodejs-paginator/pull/88)) + +### Internal / Testing Changes +- chore: include build in eslintignore ([#49](https://github.com/googleapis/nodejs-paginator/pull/49)) +- chore: update CircleCI config ([#52](https://github.com/googleapis/nodejs-paginator/pull/52)) +- chore: use latest npm on Windows ([#54](https://github.com/googleapis/nodejs-paginator/pull/54)) +- chore: update eslintignore config ([#56](https://github.com/googleapis/nodejs-paginator/pull/56)) +- chore: add synth.metadata +- fix(build): fix system key decryption ([#64](https://github.com/googleapis/nodejs-paginator/pull/64)) +- chore: update license file ([#68](https://github.com/googleapis/nodejs-paginator/pull/68)) +- chore(build): update prettier config ([#69](https://github.com/googleapis/nodejs-paginator/pull/69)) +- chore: nyc ignore build/test by default ([#71](https://github.com/googleapis/nodejs-paginator/pull/71)) +- chore: always nyc report before calling codecov ([#72](https://github.com/googleapis/nodejs-paginator/pull/72)) +- build: add Kokoro configs for autorelease ([#75](https://github.com/googleapis/nodejs-paginator/pull/75)) +- fix(build): fix Kokoro release script ([#76](https://github.com/googleapis/nodejs-paginator/pull/76)) +- chore: fix publish.sh permission +x ([#77](https://github.com/googleapis/nodejs-paginator/pull/77)) +- chore: update nyc and eslint configs ([#79](https://github.com/googleapis/nodejs-paginator/pull/79)) +- chore(build): inject yoshi automation key ([#80](https://github.com/googleapis/nodejs-paginator/pull/80)) +- build: check broken links in generated docs ([#82](https://github.com/googleapis/nodejs-paginator/pull/82)) +- build: ignore googleapis.com in doc link check ([#84](https://github.com/googleapis/nodejs-paginator/pull/84)) +- build: test using @grpc/grpc-js in CI ([#89](https://github.com/googleapis/nodejs-paginator/pull/89)) +- build: create docs test npm scripts ([#90](https://github.com/googleapis/nodejs-paginator/pull/90)) +- build: use linkinator for docs test ([#93](https://github.com/googleapis/nodejs-paginator/pull/93)) +- build: update release configuration +- build: fix types for sinon ([#98](https://github.com/googleapis/nodejs-paginator/pull/98)) +- build: use node10 to run samples-test, system-test etc ([#97](https://github.com/googleapis/nodejs-paginator/pull/97)) +- build: Add docuploader credentials to node publish jobs ([#99](https://github.com/googleapis/nodejs-paginator/pull/99)) + +## v0.1.2 + +### Bug fixes +- fix: call limiter.makeRequest() instead of original method ([#43](https://github.com/googleapis/nodejs-paginator/pull/43)) + +### Internal / Testing Changes +- chore: update issue templates ([#42](https://github.com/googleapis/nodejs-paginator/pull/42)) +- chore: remove old issue template ([#40](https://github.com/googleapis/nodejs-paginator/pull/40)) +- build: run tests on node11 ([#39](https://github.com/googleapis/nodejs-paginator/pull/39)) +- chores(build): run codecov on continuous builds ([#36](https://github.com/googleapis/nodejs-paginator/pull/36)) +- chores(build): do not collect sponge.xml from windows builds ([#37](https://github.com/googleapis/nodejs-paginator/pull/37)) +- chore: update new issue template ([#35](https://github.com/googleapis/nodejs-paginator/pull/35)) +- chore(deps): update dependency sinon to v7 ([#31](https://github.com/googleapis/nodejs-paginator/pull/31)) +- build: fix codecov uploading on Kokoro ([#32](https://github.com/googleapis/nodejs-paginator/pull/32)) +- Update kokoro config ([#29](https://github.com/googleapis/nodejs-paginator/pull/29)) +- Update CI config ([#27](https://github.com/googleapis/nodejs-paginator/pull/27)) +- Don't publish sourcemaps ([#25](https://github.com/googleapis/nodejs-paginator/pull/25)) +- build: prevent system/sample-test from leaking credentials +- Update kokoro config ([#23](https://github.com/googleapis/nodejs-paginator/pull/23)) +- test: remove appveyor config ([#22](https://github.com/googleapis/nodejs-paginator/pull/22)) +- Update CI config ([#21](https://github.com/googleapis/nodejs-paginator/pull/21)) +- Enable prefer-const in the eslint config ([#20](https://github.com/googleapis/nodejs-paginator/pull/20)) +- Enable no-var in eslint ([#19](https://github.com/googleapis/nodejs-paginator/pull/19)) +- Update CI config ([#18](https://github.com/googleapis/nodejs-paginator/pull/18)) + +## v0.1.1 + +### Internal / Testing Changes +- Add synth script and update CI config (#14) +- chore(deps): update dependency nyc to v13 (#12) +- chore: ignore package-lock.json (#11) +- chore(deps): lock file maintenance (#10) +- chore: update renovate config (#9) +- remove that whitespace (#8) +- chore(deps): lock file maintenance (#7) +- chore(deps): update dependency typescript to v3 (#6) +- chore: assert.deelEqual => assert.deepStrictEqual (#5) +- chore: move mocha options to mocha.opts (#4) diff --git a/node_modules/@google-cloud/paginator/LICENSE b/node_modules/@google-cloud/paginator/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/@google-cloud/paginator/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@google-cloud/paginator/README.md b/node_modules/@google-cloud/paginator/README.md new file mode 100644 index 0000000..e85b650 --- /dev/null +++ b/node_modules/@google-cloud/paginator/README.md @@ -0,0 +1,136 @@ +[//]: # "This README.md file is auto-generated, all changes to this file will be lost." +[//]: # "To regenerate it, use `python -m synthtool`." +Google Cloud Platform logo + +# [Google Cloud Common Paginator: Node.js Client](https://github.com/googleapis/nodejs-paginator) + +[![release level](https://img.shields.io/badge/release%20level-stable-brightgreen.svg?style=flat)](https://cloud.google.com/terms/launch-stages) +[![npm version](https://img.shields.io/npm/v/@google-cloud/paginator.svg)](https://www.npmjs.org/package/@google-cloud/paginator) + + + + +A result paging utility used by Google node.js modules + + +A comprehensive list of changes in each version may be found in +[the CHANGELOG](https://github.com/googleapis/nodejs-paginator/blob/main/CHANGELOG.md). + +* [Google Cloud Common Paginator Node.js Client API Reference][client-docs] + +* [github.com/googleapis/nodejs-paginator](https://github.com/googleapis/nodejs-paginator) + +Read more about the client libraries for Cloud APIs, including the older +Google APIs Client Libraries, in [Client Libraries Explained][explained]. + +[explained]: https://cloud.google.com/apis/docs/client-libraries-explained + +**Table of contents:** + + +* [Quickstart](#quickstart) + + * [Installing the client library](#installing-the-client-library) + * [Using the client library](#using-the-client-library) +* [Samples](#samples) +* [Versioning](#versioning) +* [Contributing](#contributing) +* [License](#license) + +## Quickstart + +### Installing the client library + +```bash +npm install @google-cloud/paginator +``` + + +### Using the client library + +```javascript +const {paginator} = require('@google-cloud/paginator'); +console.log(paginator); + +``` + + + +## Samples + +Samples are in the [`samples/`](https://github.com/googleapis/nodejs-paginator/tree/main/samples) directory. Each sample's `README.md` has instructions for running its sample. + +| Sample | Source Code | Try it | +| --------------------------- | --------------------------------- | ------ | +| Quickstart | [source code](https://github.com/googleapis/nodejs-paginator/blob/main/samples/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-paginator&page=editor&open_in_editor=samples/quickstart.js,samples/README.md) | +| Streamify | [source code](https://github.com/googleapis/nodejs-paginator/blob/main/samples/streamify.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-paginator&page=editor&open_in_editor=samples/streamify.js,samples/README.md) | + + + +The [Google Cloud Common Paginator Node.js Client API Reference][client-docs] documentation +also contains samples. + +## Supported Node.js Versions + +Our client libraries follow the [Node.js release schedule](https://github.com/nodejs/release#release-schedule). +Libraries are compatible with all current _active_ and _maintenance_ versions of +Node.js. +If you are using an end-of-life version of Node.js, we recommend that you update +as soon as possible to an actively supported LTS version. + +Google's client libraries support legacy versions of Node.js runtimes on a +best-efforts basis with the following warnings: + +* Legacy versions are not tested in continuous integration. +* Some security patches and features cannot be backported. +* Dependencies cannot be kept up-to-date. + +Client libraries targeting some end-of-life versions of Node.js are available, and +can be installed through npm [dist-tags](https://docs.npmjs.com/cli/dist-tag). +The dist-tags follow the naming convention `legacy-(version)`. +For example, `npm install @google-cloud/paginator@legacy-8` installs client libraries +for versions compatible with Node.js 8. + +## Versioning + +This library follows [Semantic Versioning](http://semver.org/). + + + +This library is considered to be **stable**. The code surface will not change in backwards-incompatible ways +unless absolutely necessary (e.g. because of critical security issues) or with +an extensive deprecation period. Issues and requests against **stable** libraries +are addressed with the highest priority. + + + + + + +More Information: [Google Cloud Platform Launch Stages][launch_stages] + +[launch_stages]: https://cloud.google.com/terms/launch-stages + +## Contributing + +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/nodejs-paginator/blob/main/CONTRIBUTING.md). + +Please note that this `README.md`, the `samples/README.md`, +and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) +are generated from a central template. To edit one of these files, make an edit +to its templates in +[directory](https://github.com/googleapis/synthtool). + +## License + +Apache Version 2.0 + +See [LICENSE](https://github.com/googleapis/nodejs-paginator/blob/main/LICENSE) + +[client-docs]: https://cloud.google.com/nodejs/docs/reference/paginator/latest + +[shell_img]: https://gstatic.com/cloudssh/images/open-btn.png +[projects]: https://console.cloud.google.com/project +[billing]: https://support.google.com/cloud/answer/6293499#enable-billing + +[auth]: https://cloud.google.com/docs/authentication/getting-started diff --git a/node_modules/@google-cloud/paginator/build/src/index.d.ts b/node_modules/@google-cloud/paginator/build/src/index.d.ts new file mode 100644 index 0000000..7a090bd --- /dev/null +++ b/node_modules/@google-cloud/paginator/build/src/index.d.ts @@ -0,0 +1,131 @@ +/*! + * Copyright 2015 Google Inc. 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. + */ +/// +import { TransformOptions } from 'stream'; +import { ResourceStream } from './resource-stream'; +export interface ParsedArguments extends TransformOptions { + /** + * Query object. This is most commonly an object, but to make the API more + * simple, it can also be a string in some places. + */ + query?: ParsedArguments; + /** + * Callback function. + */ + callback?: Function; + /** + * Auto-pagination enabled. + */ + autoPaginate?: boolean; + /** + * Maximum API calls to make. + */ + maxApiCalls?: number; + /** + * Maximum results to return. + */ + maxResults?: number; + pageSize?: number; + streamOptions?: ParsedArguments; +} +/*! Developer Documentation + * + * paginator is used to auto-paginate `nextQuery` methods as well as + * streamifying them. + * + * Before: + * + * search.query('done=true', function(err, results, nextQuery) { + * search.query(nextQuery, function(err, results, nextQuery) {}); + * }); + * + * After: + * + * search.query('done=true', function(err, results) {}); + * + * Methods to extend should be written to accept callbacks and return a + * `nextQuery`. + */ +export declare class Paginator { + /** + * Cache the original method, then overwrite it on the Class's prototype. + * + * @param {function} Class - The parent class of the methods to extend. + * @param {string|string[]} methodNames - Name(s) of the methods to extend. + */ + extend(Class: Function, methodNames: string | string[]): void; + /** + * Wraps paginated API calls in a readable object stream. + * + * This method simply calls the nextQuery recursively, emitting results to a + * stream. The stream ends when `nextQuery` is null. + * + * `maxResults` will act as a cap for how many results are fetched and emitted + * to the stream. + * + * @param {string} methodName - Name of the method to streamify. + * @return {function} - Wrapped function. + */ + streamify(methodName: string): (this: { + [index: string]: Function; + }, ...args: any[]) => ResourceStream; + /** + * Parse a pseudo-array `arguments` for a query and callback. + * + * @param {array} args - The original `arguments` pseduo-array that the original + * method received. + */ + parseArguments_(args: any[]): ParsedArguments; + /** + * This simply checks to see if `autoPaginate` is set or not, if it's true + * then we buffer all results, otherwise simply call the original method. + * + * @param {array} parsedArguments - Parsed arguments from the original method + * call. + * @param {object=|string=} parsedArguments.query - Query object. This is most + * commonly an object, but to make the API more simple, it can also be a + * string in some places. + * @param {function=} parsedArguments.callback - Callback function. + * @param {boolean} parsedArguments.autoPaginate - Auto-pagination enabled. + * @param {boolean} parsedArguments.maxApiCalls - Maximum API calls to make. + * @param {number} parsedArguments.maxResults - Maximum results to return. + * @param {function} originalMethod - The cached method that accepts a callback + * and returns `nextQuery` to receive more results. + */ + run_(parsedArguments: ParsedArguments, originalMethod: Function): any; + /** + * This method simply calls the nextQuery recursively, emitting results to a + * stream. The stream ends when `nextQuery` is null. + * + * `maxResults` will act as a cap for how many results are fetched and emitted + * to the stream. + * + * @param {object=|string=} parsedArguments.query - Query object. This is most + * commonly an object, but to make the API more simple, it can also be a + * string in some places. + * @param {function=} parsedArguments.callback - Callback function. + * @param {boolean} parsedArguments.autoPaginate - Auto-pagination enabled. + * @param {boolean} parsedArguments.maxApiCalls - Maximum API calls to make. + * @param {number} parsedArguments.maxResults - Maximum results to return. + * @param {function} originalMethod - The cached method that accepts a callback + * and returns `nextQuery` to receive more results. + * @return {stream} - Readable object stream. + */ + runAsStream_(parsedArguments: ParsedArguments, originalMethod: Function): ResourceStream; +} +declare const paginator: Paginator; +export { paginator }; +export { ResourceStream }; diff --git a/node_modules/@google-cloud/paginator/build/src/index.js b/node_modules/@google-cloud/paginator/build/src/index.js new file mode 100644 index 0000000..18b5457 --- /dev/null +++ b/node_modules/@google-cloud/paginator/build/src/index.js @@ -0,0 +1,210 @@ +"use strict"; +/*! + * Copyright 2015 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ResourceStream = exports.paginator = exports.Paginator = void 0; +/*! + * @module common/paginator + */ +const arrify = require("arrify"); +const extend = require("extend"); +const resource_stream_1 = require("./resource-stream"); +Object.defineProperty(exports, "ResourceStream", { enumerable: true, get: function () { return resource_stream_1.ResourceStream; } }); +/*! Developer Documentation + * + * paginator is used to auto-paginate `nextQuery` methods as well as + * streamifying them. + * + * Before: + * + * search.query('done=true', function(err, results, nextQuery) { + * search.query(nextQuery, function(err, results, nextQuery) {}); + * }); + * + * After: + * + * search.query('done=true', function(err, results) {}); + * + * Methods to extend should be written to accept callbacks and return a + * `nextQuery`. + */ +class Paginator { + /** + * Cache the original method, then overwrite it on the Class's prototype. + * + * @param {function} Class - The parent class of the methods to extend. + * @param {string|string[]} methodNames - Name(s) of the methods to extend. + */ + // tslint:disable-next-line:variable-name + extend(Class, methodNames) { + methodNames = arrify(methodNames); + methodNames.forEach(methodName => { + const originalMethod = Class.prototype[methodName]; + // map the original method to a private member + Class.prototype[methodName + '_'] = originalMethod; + // overwrite the original to auto-paginate + /* eslint-disable @typescript-eslint/no-explicit-any */ + Class.prototype[methodName] = function (...args) { + const parsedArguments = paginator.parseArguments_(args); + return paginator.run_(parsedArguments, originalMethod.bind(this)); + }; + }); + } + /** + * Wraps paginated API calls in a readable object stream. + * + * This method simply calls the nextQuery recursively, emitting results to a + * stream. The stream ends when `nextQuery` is null. + * + * `maxResults` will act as a cap for how many results are fetched and emitted + * to the stream. + * + * @param {string} methodName - Name of the method to streamify. + * @return {function} - Wrapped function. + */ + /* eslint-disable @typescript-eslint/no-explicit-any */ + streamify(methodName) { + return function ( + /* eslint-disable @typescript-eslint/no-explicit-any */ + ...args) { + const parsedArguments = paginator.parseArguments_(args); + const originalMethod = this[methodName + '_'] || this[methodName]; + return paginator.runAsStream_(parsedArguments, originalMethod.bind(this)); + }; + } + /** + * Parse a pseudo-array `arguments` for a query and callback. + * + * @param {array} args - The original `arguments` pseduo-array that the original + * method received. + */ + /* eslint-disable @typescript-eslint/no-explicit-any */ + parseArguments_(args) { + let query; + let autoPaginate = true; + let maxApiCalls = -1; + let maxResults = -1; + let callback; + const firstArgument = args[0]; + const lastArgument = args[args.length - 1]; + if (typeof firstArgument === 'function') { + callback = firstArgument; + } + else { + query = firstArgument; + } + if (typeof lastArgument === 'function') { + callback = lastArgument; + } + if (typeof query === 'object') { + query = extend(true, {}, query); + // Check if the user only asked for a certain amount of results. + if (query.maxResults && typeof query.maxResults === 'number') { + // `maxResults` is used API-wide. + maxResults = query.maxResults; + } + else if (typeof query.pageSize === 'number') { + // `pageSize` is Pub/Sub's `maxResults`. + maxResults = query.pageSize; + } + if (query.maxApiCalls && typeof query.maxApiCalls === 'number') { + maxApiCalls = query.maxApiCalls; + delete query.maxApiCalls; + } + // maxResults is the user specified limit. + if (maxResults !== -1 || query.autoPaginate === false) { + autoPaginate = false; + } + } + const parsedArguments = { + query: query || {}, + autoPaginate, + maxApiCalls, + maxResults, + callback, + }; + parsedArguments.streamOptions = extend(true, {}, parsedArguments.query); + delete parsedArguments.streamOptions.autoPaginate; + delete parsedArguments.streamOptions.maxResults; + delete parsedArguments.streamOptions.pageSize; + return parsedArguments; + } + /** + * This simply checks to see if `autoPaginate` is set or not, if it's true + * then we buffer all results, otherwise simply call the original method. + * + * @param {array} parsedArguments - Parsed arguments from the original method + * call. + * @param {object=|string=} parsedArguments.query - Query object. This is most + * commonly an object, but to make the API more simple, it can also be a + * string in some places. + * @param {function=} parsedArguments.callback - Callback function. + * @param {boolean} parsedArguments.autoPaginate - Auto-pagination enabled. + * @param {boolean} parsedArguments.maxApiCalls - Maximum API calls to make. + * @param {number} parsedArguments.maxResults - Maximum results to return. + * @param {function} originalMethod - The cached method that accepts a callback + * and returns `nextQuery` to receive more results. + */ + run_(parsedArguments, originalMethod) { + const query = parsedArguments.query; + const callback = parsedArguments.callback; + if (!parsedArguments.autoPaginate) { + return originalMethod(query, callback); + } + const results = new Array(); + let otherArgs = []; + const promise = new Promise((resolve, reject) => { + const stream = paginator.runAsStream_(parsedArguments, originalMethod); + stream + .on('error', reject) + .on('data', (data) => results.push(data)) + .on('end', () => { + otherArgs = stream._otherArgs || []; + resolve(results); + }); + }); + if (!callback) { + return promise.then(results => [results, query, ...otherArgs]); + } + promise.then(results => callback(null, results, query, ...otherArgs), (err) => callback(err)); + } + /** + * This method simply calls the nextQuery recursively, emitting results to a + * stream. The stream ends when `nextQuery` is null. + * + * `maxResults` will act as a cap for how many results are fetched and emitted + * to the stream. + * + * @param {object=|string=} parsedArguments.query - Query object. This is most + * commonly an object, but to make the API more simple, it can also be a + * string in some places. + * @param {function=} parsedArguments.callback - Callback function. + * @param {boolean} parsedArguments.autoPaginate - Auto-pagination enabled. + * @param {boolean} parsedArguments.maxApiCalls - Maximum API calls to make. + * @param {number} parsedArguments.maxResults - Maximum results to return. + * @param {function} originalMethod - The cached method that accepts a callback + * and returns `nextQuery` to receive more results. + * @return {stream} - Readable object stream. + */ + /* eslint-disable @typescript-eslint/no-explicit-any */ + runAsStream_(parsedArguments, originalMethod) { + return new resource_stream_1.ResourceStream(parsedArguments, originalMethod); + } +} +exports.Paginator = Paginator; +const paginator = new Paginator(); +exports.paginator = paginator; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/paginator/build/src/resource-stream.d.ts b/node_modules/@google-cloud/paginator/build/src/resource-stream.d.ts new file mode 100644 index 0000000..0b17498 --- /dev/null +++ b/node_modules/@google-cloud/paginator/build/src/resource-stream.d.ts @@ -0,0 +1,41 @@ +/*! + * Copyright 2019 Google Inc. 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. + */ +/// +import { Transform, Writable } from 'stream'; +import { ParsedArguments } from './'; +interface ResourceEvents { + addListener(event: 'data', listener: (data: T) => void): this; + emit(event: 'data', data: T): boolean; + on(event: 'data', listener: (data: T) => void): this; + once(event: 'data', listener: (data: T) => void): this; + prependListener(event: 'data', listener: (data: T) => void): this; + prependOnceListener(event: 'data', listener: (data: T) => void): this; + removeListener(event: 'data', listener: (data: T) => void): this; +} +export declare class ResourceStream extends Transform implements ResourceEvents { + _ended: boolean; + _maxApiCalls: number; + _nextQuery: {} | null; + _otherArgs: unknown[]; + _reading: boolean; + _requestFn: Function; + _requestsMade: number; + _resultsToSend: number; + constructor(args: ParsedArguments, requestFn: Function); + end(...args: any[]): ReturnType extends Writable ? this : void; + _read(): void; +} +export {}; diff --git a/node_modules/@google-cloud/paginator/build/src/resource-stream.js b/node_modules/@google-cloud/paginator/build/src/resource-stream.js new file mode 100644 index 0000000..8fbb503 --- /dev/null +++ b/node_modules/@google-cloud/paginator/build/src/resource-stream.js @@ -0,0 +1,82 @@ +"use strict"; +/*! + * Copyright 2019 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ResourceStream = void 0; +const stream_1 = require("stream"); +class ResourceStream extends stream_1.Transform { + constructor(args, requestFn) { + const options = Object.assign({ objectMode: true }, args.streamOptions); + super(options); + this._ended = false; + this._maxApiCalls = args.maxApiCalls === -1 ? Infinity : args.maxApiCalls; + this._nextQuery = args.query; + this._reading = false; + this._requestFn = requestFn; + this._requestsMade = 0; + this._resultsToSend = args.maxResults === -1 ? Infinity : args.maxResults; + this._otherArgs = []; + } + /* eslint-disable @typescript-eslint/no-explicit-any */ + end(...args) { + this._ended = true; + return super.end(...args); + } + _read() { + if (this._reading) { + return; + } + this._reading = true; + // Wrap in a try/catch to catch input linting errors, e.g. + // an invalid BigQuery query. These errors are thrown in an + // async fashion, which makes them un-catchable by the user. + try { + this._requestFn(this._nextQuery, (err, results, nextQuery, ...otherArgs) => { + if (err) { + this.destroy(err); + return; + } + this._otherArgs = otherArgs; + this._nextQuery = nextQuery; + if (this._resultsToSend !== Infinity) { + results = results.splice(0, this._resultsToSend); + this._resultsToSend -= results.length; + } + let more = true; + for (const result of results) { + if (this._ended) { + break; + } + more = this.push(result); + } + const isFinished = !this._nextQuery || this._resultsToSend < 1; + const madeMaxCalls = ++this._requestsMade >= this._maxApiCalls; + if (isFinished || madeMaxCalls) { + this.end(); + } + if (more && !this._ended) { + setImmediate(() => this._read()); + } + this._reading = false; + }); + } + catch (e) { + this.destroy(e); + } + } +} +exports.ResourceStream = ResourceStream; +//# sourceMappingURL=resource-stream.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/paginator/package.json b/node_modules/@google-cloud/paginator/package.json new file mode 100644 index 0000000..1242a77 --- /dev/null +++ b/node_modules/@google-cloud/paginator/package.json @@ -0,0 +1,57 @@ +{ + "name": "@google-cloud/paginator", + "version": "5.0.2", + "description": "A result paging utility used by Google node.js modules", + "main": "build/src/index.js", + "types": "build/src/index.d.ts", + "repository": "googleapis/nodejs-paginator", + "scripts": { + "test": "c8 mocha build/test", + "compile": "tsc -p .", + "fix": "gts fix", + "prelint": "cd samples; npm link ../; npm install", + "lint": "gts check", + "prepare": "npm run compile", + "pretest": "npm run compile", + "docs": "compodoc src/", + "presystem-test": "npm run compile", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "system-test": "mocha build/system-test", + "docs-test": "linkinator docs", + "predocs-test": "npm run docs", + "clean": "gts clean", + "precompile": "gts clean" + }, + "keywords": [], + "files": [ + "build/src", + "!build/src/**/*.map" + ], + "author": "Google Inc.", + "license": "Apache-2.0", + "devDependencies": { + "@compodoc/compodoc": "1.1.23", + "@types/extend": "^3.0.0", + "@types/mocha": "^9.0.0", + "@types/node": "^20.4.9", + "@types/proxyquire": "^1.3.28", + "@types/sinon": "^17.0.0", + "@types/uuid": "^9.0.0", + "c8": "^9.0.0", + "codecov": "^3.0.4", + "gts": "^5.0.0", + "linkinator": "^4.0.0", + "mocha": "^9.2.2", + "proxyquire": "^2.0.1", + "sinon": "^17.0.0", + "typescript": "^5.1.6", + "uuid": "^9.0.0" + }, + "dependencies": { + "arrify": "^2.0.0", + "extend": "^3.0.2" + }, + "engines": { + "node": ">=14.0.0" + } +} diff --git a/node_modules/@google-cloud/projectify/CHANGELOG.md b/node_modules/@google-cloud/projectify/CHANGELOG.md new file mode 100644 index 0000000..328e4f3 --- /dev/null +++ b/node_modules/@google-cloud/projectify/CHANGELOG.md @@ -0,0 +1,196 @@ +# Changelog + +[npm history][1] + +[1]: https://www.npmjs.com/package/@google-cloud/projectify?activeTab=versions +## [4.0.0](https://github.com/googleapis/nodejs-projectify/compare/v3.0.0...v4.0.0) (2023-08-09) + + +### ⚠ BREAKING CHANGES + +* upgrade to Node 14 ([#318](https://github.com/googleapis/nodejs-projectify/issues/318)) + +### Bug Fixes + +* Remove pip install statements ([#1546](https://github.com/googleapis/nodejs-projectify/issues/1546)) ([#304](https://github.com/googleapis/nodejs-projectify/issues/304)) ([94cfff6](https://github.com/googleapis/nodejs-projectify/commit/94cfff665b7c6b8916b5c59e1c7a3cca7ff29303)) + + +### Miscellaneous Chores + +* Upgrade to Node 14 ([#318](https://github.com/googleapis/nodejs-projectify/issues/318)) ([6e9da4d](https://github.com/googleapis/nodejs-projectify/commit/6e9da4db77fab7ed6876e755a72156960b376d57)) + +## [3.0.0](https://github.com/googleapis/nodejs-projectify/compare/v2.1.1...v3.0.0) (2022-05-20) + + +### ⚠ BREAKING CHANGES + +* update library to use Node 12 (#299) + +### Build System + +* update library to use Node 12 ([#299](https://github.com/googleapis/nodejs-projectify/issues/299)) ([83b63ca](https://github.com/googleapis/nodejs-projectify/commit/83b63ca8cb89086a8535a9fc8abd39e95f0cecd4)) + +### [2.1.1](https://www.github.com/googleapis/nodejs-projectify/compare/v2.1.0...v2.1.1) (2021-09-09) + + +### Bug Fixes + +* **build:** switch primary branch to main ([#267](https://www.github.com/googleapis/nodejs-projectify/issues/267)) ([9e8d6e4](https://www.github.com/googleapis/nodejs-projectify/commit/9e8d6e48c080806b42164d7be0bd11197996f245)) + +## [2.1.0](https://www.github.com/googleapis/nodejs-projectify/compare/v2.0.1...v2.1.0) (2021-06-10) + + +### Features + +* add `gcf-owl-bot[bot]` to `ignoreAuthors` ([#245](https://www.github.com/googleapis/nodejs-projectify/issues/245)) ([30f0499](https://www.github.com/googleapis/nodejs-projectify/commit/30f0499ade5f140774c3aa672b44fd3538e72309)) + +### [2.0.1](https://www.github.com/googleapis/nodejs-projectify/compare/v2.0.0...v2.0.1) (2020-07-06) + + +### Bug Fixes + +* update node issue template ([#197](https://www.github.com/googleapis/nodejs-projectify/issues/197)) ([3406f2a](https://www.github.com/googleapis/nodejs-projectify/commit/3406f2aa431ed04541585b63c330c04270c602aa)) + +## [2.0.0](https://www.github.com/googleapis/nodejs-projectify/compare/v1.0.4...v2.0.0) (2020-03-24) + + +### ⚠ BREAKING CHANGES + +* typescript@3.7 introduced some breaking changes +* drop Node 8 from engines field (#172) + +### Features + +* drop Node 8 from engines field ([#172](https://www.github.com/googleapis/nodejs-projectify/issues/172)) ([3eac424](https://www.github.com/googleapis/nodejs-projectify/commit/3eac424bfb1ee47144a77888dc68db687988945e)) + + +### Build System + +* update to latest version of gts/typescript ([#171](https://www.github.com/googleapis/nodejs-projectify/issues/171)) ([30f90cc](https://www.github.com/googleapis/nodejs-projectify/commit/30f90cc172da6ed9394da91869556bf5eef42434)) + +### [1.0.4](https://www.github.com/googleapis/nodejs-projectify/compare/v1.0.3...v1.0.4) (2019-12-05) + + +### Bug Fixes + +* **publish:** publication failed to reach npm ([#141](https://www.github.com/googleapis/nodejs-projectify/issues/141)) ([5406ba5](https://www.github.com/googleapis/nodejs-projectify/commit/5406ba5e1d43a228a19072023c1baebce34190af)) + +### [1.0.3](https://www.github.com/googleapis/nodejs-projectify/compare/v1.0.2...v1.0.3) (2019-12-05) + + +### Bug Fixes + +* **deps:** pin TypeScript below 3.7.0 ([6c95307](https://www.github.com/googleapis/nodejs-projectify/commit/6c953070139a77d30c4ce5b7dee1443874046906)) + +### [1.0.2](https://www.github.com/googleapis/nodejs-projectify/compare/v1.0.1...v1.0.2) (2019-11-14) + + +### Bug Fixes + +* **docs:** add jsdoc-region-tag plugin ([#135](https://www.github.com/googleapis/nodejs-projectify/issues/135)) ([59301e7](https://www.github.com/googleapis/nodejs-projectify/commit/59301e7cfa855add4894dd9c46870e61fffa7413)) + +### [1.0.1](https://www.github.com/googleapis/nodejs-projectify/compare/v1.0.0...v1.0.1) (2019-06-26) + + +### Bug Fixes + +* **docs:** link to reference docs section on googleapis.dev ([#119](https://www.github.com/googleapis/nodejs-projectify/issues/119)) ([90a009f](https://www.github.com/googleapis/nodejs-projectify/commit/90a009f)) + +## [1.0.0](https://www.github.com/googleapis/nodejs-projectify/compare/v0.3.3...v1.0.0) (2019-05-02) + + +### Build System + +* upgrade engines field to >=8.10.0 ([#103](https://www.github.com/googleapis/nodejs-projectify/issues/103)) ([0149650](https://www.github.com/googleapis/nodejs-projectify/commit/0149650)) + + +### BREAKING CHANGES + +* upgrade engines field to >=8.10.0 (#103) + +## v0.3.3 + +03-12-2019 12:27 PDT + +This patch release contains a few updates to the docs. That's all! + +### Documentation +- docs: update links in contrib guide ([#86](https://github.com/googleapis/nodejs-projectify/pull/86)) +- docs: update contributing path in README ([#82](https://github.com/googleapis/nodejs-projectify/pull/82)) +- docs: move CONTRIBUTING.md to root ([#81](https://github.com/googleapis/nodejs-projectify/pull/81)) +- docs: add lint/fix example to contributing guide ([#79](https://github.com/googleapis/nodejs-projectify/pull/79)) + +### Internal / Testing Changes +- build: Add docuploader credentials to node publish jobs ([#90](https://github.com/googleapis/nodejs-projectify/pull/90)) +- build: use node10 to run samples-test, system-test etc ([#89](https://github.com/googleapis/nodejs-projectify/pull/89)) +- build: update release configuration +- chore(deps): update dependency mocha to v6 +- build: use linkinator for docs test ([#85](https://github.com/googleapis/nodejs-projectify/pull/85)) +- build: create docs test npm scripts ([#84](https://github.com/googleapis/nodejs-projectify/pull/84)) +- build: test using @grpc/grpc-js in CI ([#83](https://github.com/googleapis/nodejs-projectify/pull/83)) +- build: ignore googleapis.com in doc link check ([#78](https://github.com/googleapis/nodejs-projectify/pull/78)) +- build: check for 404s in the docs ([#77](https://github.com/googleapis/nodejs-projectify/pull/77)) +- chore(build): inject yoshi automation key ([#75](https://github.com/googleapis/nodejs-projectify/pull/75)) +- chore: update nyc and eslint configs ([#74](https://github.com/googleapis/nodejs-projectify/pull/74)) +- chore: fix publish.sh permission +x ([#72](https://github.com/googleapis/nodejs-projectify/pull/72)) +- fix(build): fix Kokoro release script ([#71](https://github.com/googleapis/nodejs-projectify/pull/71)) +- build: add Kokoro configs for autorelease ([#70](https://github.com/googleapis/nodejs-projectify/pull/70)) +- chore: always nyc report before calling codecov ([#67](https://github.com/googleapis/nodejs-projectify/pull/67)) +- chore: nyc ignore build/test by default ([#66](https://github.com/googleapis/nodejs-projectify/pull/66)) +- chore(build): update prettier config ([#64](https://github.com/googleapis/nodejs-projectify/pull/64)) +- chore: update license file ([#63](https://github.com/googleapis/nodejs-projectify/pull/63)) +- fix(build): fix system key decryption ([#59](https://github.com/googleapis/nodejs-projectify/pull/59)) +- chore: add synth.metadata + +## v0.3.2 + +### Bug fixes +- fix: do not replace projectId on stream objects ([#53](https://github.com/googleapis/nodejs-projectify/pull/53)) + +### Dependencies +- chore(deps): update dependency gts to ^0.9.0 ([#52](https://github.com/googleapis/nodejs-projectify/pull/52)) + +### Internal / Testing Changes +- chore: update eslintignore config ([#51](https://github.com/googleapis/nodejs-projectify/pull/51)) +- chore: use latest npm on Windows ([#50](https://github.com/googleapis/nodejs-projectify/pull/50)) +- chore: update CircleCI config ([#49](https://github.com/googleapis/nodejs-projectify/pull/49)) +- chore: include build in eslintignore ([#46](https://github.com/googleapis/nodejs-projectify/pull/46)) + +## v0.3.1 + +### Implementation Changes +- fix: replaceProjectId should not fail when passed a Buffer ([#43](https://github.com/googleapis/nodejs-projectify/pull/43)) + +### Dependencies +- chore(deps): update dependency nyc to v13 ([#13](https://github.com/googleapis/nodejs-projectify/pull/13)) +- chore(deps): lock file maintenance ([#11](https://github.com/googleapis/nodejs-projectify/pull/11)) +- chore(deps): lock file maintenance ([#8](https://github.com/googleapis/nodejs-projectify/pull/8)) +- chore(deps): update dependency typescript to v3 ([#7](https://github.com/googleapis/nodejs-projectify/pull/7)) +- chore(deps): update dependency gts to ^0.8.0 ([#2](https://github.com/googleapis/nodejs-projectify/pull/2)) +- chore(deps): lock file maintenance ([#4](https://github.com/googleapis/nodejs-projectify/pull/4)) +- chore(deps): lock file maintenance ([#3](https://github.com/googleapis/nodejs-projectify/pull/3)) + +### Internal / Testing Changes +- chore: update issue templates ([#40](https://github.com/googleapis/nodejs-projectify/pull/40)) +- chore: remove old issue template ([#38](https://github.com/googleapis/nodejs-projectify/pull/38)) +- build: run tests on node11 ([#37](https://github.com/googleapis/nodejs-projectify/pull/37)) +- chores(build): run codecov on continuous builds ([#34](https://github.com/googleapis/nodejs-projectify/pull/34)) +- chores(build): do not collect sponge.xml from windows builds ([#35](https://github.com/googleapis/nodejs-projectify/pull/35)) +- chore: update new issue template ([#33](https://github.com/googleapis/nodejs-projectify/pull/33)) +- build: fix codecov uploading on Kokoro ([#30](https://github.com/googleapis/nodejs-projectify/pull/30)) +- Update kokoro config ([#28](https://github.com/googleapis/nodejs-projectify/pull/28)) +- Update CI config ([#26](https://github.com/googleapis/nodejs-projectify/pull/26)) +- Don't publish sourcemaps ([#24](https://github.com/googleapis/nodejs-projectify/pull/24)) +- build: prevent system/sample-test from leaking credentials +- Update kokoro config ([#22](https://github.com/googleapis/nodejs-projectify/pull/22)) +- test: remove appveyor config ([#21](https://github.com/googleapis/nodejs-projectify/pull/21)) +- Update CI config ([#20](https://github.com/googleapis/nodejs-projectify/pull/20)) +- Enable prefer-const in the eslint config ([#19](https://github.com/googleapis/nodejs-projectify/pull/19)) +- Enable no-var in eslint ([#18](https://github.com/googleapis/nodejs-projectify/pull/18)) +- Update CI config ([#17](https://github.com/googleapis/nodejs-projectify/pull/17)) +- Add synth and update CI config ([#15](https://github.com/googleapis/nodejs-projectify/pull/15)) +- chore: ignore package-lock.json ([#12](https://github.com/googleapis/nodejs-projectify/pull/12)) +- chore: update renovate config ([#10](https://github.com/googleapis/nodejs-projectify/pull/10)) +- remove that whitespace ([#9](https://github.com/googleapis/nodejs-projectify/pull/9)) +- chore: assert.deelEqual => assert.deepStrictEqual ([#6](https://github.com/googleapis/nodejs-projectify/pull/6)) +- chore: move mocha options to mocha.opts ([#5](https://github.com/googleapis/nodejs-projectify/pull/5)) diff --git a/node_modules/@google-cloud/projectify/LICENSE b/node_modules/@google-cloud/projectify/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/@google-cloud/projectify/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@google-cloud/projectify/README.md b/node_modules/@google-cloud/projectify/README.md new file mode 100644 index 0000000..736e96a --- /dev/null +++ b/node_modules/@google-cloud/projectify/README.md @@ -0,0 +1,138 @@ +[//]: # "This README.md file is auto-generated, all changes to this file will be lost." +[//]: # "To regenerate it, use `python -m synthtool`." +Google Cloud Platform logo + +# [Google Cloud Common Projectify: Node.js Client](https://github.com/googleapis/nodejs-projectify) + +[![release level](https://img.shields.io/badge/release%20level-stable-brightgreen.svg?style=flat)](https://cloud.google.com/terms/launch-stages) +[![npm version](https://img.shields.io/npm/v/@google-cloud/projectify.svg)](https://www.npmjs.org/package/@google-cloud/projectify) + + + + +A simple utility for replacing the projectid token in objects. + + +A comprehensive list of changes in each version may be found in +[the CHANGELOG](https://github.com/googleapis/nodejs-projectify/blob/main/CHANGELOG.md). + +* [Google Cloud Common Projectify Node.js Client API Reference][client-docs] + +* [github.com/googleapis/nodejs-projectify](https://github.com/googleapis/nodejs-projectify) + +Read more about the client libraries for Cloud APIs, including the older +Google APIs Client Libraries, in [Client Libraries Explained][explained]. + +[explained]: https://cloud.google.com/apis/docs/client-libraries-explained + +**Table of contents:** + + +* [Quickstart](#quickstart) + + * [Installing the client library](#installing-the-client-library) + * [Using the client library](#using-the-client-library) +* [Samples](#samples) +* [Versioning](#versioning) +* [Contributing](#contributing) +* [License](#license) + +## Quickstart + +### Installing the client library + +```bash +npm install @google-cloud/projectify +``` + + +### Using the client library + +```javascript +const {replaceProjectIdToken} = require('@google-cloud/projectify'); +const options = { + projectId: '{{projectId}}', +}; +replaceProjectIdToken(options, 'fake-project-id'); + +``` + + + +## Samples + +Samples are in the [`samples/`](https://github.com/googleapis/nodejs-projectify/tree/main/samples) directory. Each sample's `README.md` has instructions for running its sample. + +| Sample | Source Code | Try it | +| --------------------------- | --------------------------------- | ------ | +| Quickstart | [source code](https://github.com/googleapis/nodejs-projectify/blob/main/samples/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-projectify&page=editor&open_in_editor=samples/quickstart.js,samples/README.md) | + + + +The [Google Cloud Common Projectify Node.js Client API Reference][client-docs] documentation +also contains samples. + +## Supported Node.js Versions + +Our client libraries follow the [Node.js release schedule](https://github.com/nodejs/release#release-schedule). +Libraries are compatible with all current _active_ and _maintenance_ versions of +Node.js. +If you are using an end-of-life version of Node.js, we recommend that you update +as soon as possible to an actively supported LTS version. + +Google's client libraries support legacy versions of Node.js runtimes on a +best-efforts basis with the following warnings: + +* Legacy versions are not tested in continuous integration. +* Some security patches and features cannot be backported. +* Dependencies cannot be kept up-to-date. + +Client libraries targeting some end-of-life versions of Node.js are available, and +can be installed through npm [dist-tags](https://docs.npmjs.com/cli/dist-tag). +The dist-tags follow the naming convention `legacy-(version)`. +For example, `npm install @google-cloud/projectify@legacy-8` installs client libraries +for versions compatible with Node.js 8. + +## Versioning + +This library follows [Semantic Versioning](http://semver.org/). + + + +This library is considered to be **stable**. The code surface will not change in backwards-incompatible ways +unless absolutely necessary (e.g. because of critical security issues) or with +an extensive deprecation period. Issues and requests against **stable** libraries +are addressed with the highest priority. + + + + + + +More Information: [Google Cloud Platform Launch Stages][launch_stages] + +[launch_stages]: https://cloud.google.com/terms/launch-stages + +## Contributing + +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/nodejs-projectify/blob/main/CONTRIBUTING.md). + +Please note that this `README.md`, the `samples/README.md`, +and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) +are generated from a central template. To edit one of these files, make an edit +to its templates in +[directory](https://github.com/googleapis/synthtool). + +## License + +Apache Version 2.0 + +See [LICENSE](https://github.com/googleapis/nodejs-projectify/blob/main/LICENSE) + +[client-docs]: https://cloud.google.com/nodejs/docs/reference/projectify/latest + +[shell_img]: https://gstatic.com/cloudssh/images/open-btn.png +[projects]: https://console.cloud.google.com/project +[billing]: https://support.google.com/cloud/answer/6293499#enable-billing + +[auth]: https://cloud.google.com/docs/authentication/getting-started diff --git a/node_modules/@google-cloud/projectify/build/src/index.d.ts b/node_modules/@google-cloud/projectify/build/src/index.d.ts new file mode 100644 index 0000000..f96f13c --- /dev/null +++ b/node_modules/@google-cloud/projectify/build/src/index.d.ts @@ -0,0 +1,16 @@ +/** + * Populate the `{{projectId}}` placeholder. + * + * @throws {Error} If a projectId is required, but one is not provided. + * + * @param {*} - Any input value that may contain a placeholder. Arrays and objects will be looped. + * @param {string} projectId - A projectId. If not provided + * @return {*} - The original argument with all placeholders populated. + */ +export declare function replaceProjectIdToken(value: any, projectId: string): any; +/** + * Custom error type for missing project ID errors. + */ +export declare class MissingProjectIdError extends Error { + message: string; +} diff --git a/node_modules/@google-cloud/projectify/build/src/index.js b/node_modules/@google-cloud/projectify/build/src/index.js new file mode 100644 index 0000000..085bff8 --- /dev/null +++ b/node_modules/@google-cloud/projectify/build/src/index.js @@ -0,0 +1,66 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MissingProjectIdError = exports.replaceProjectIdToken = void 0; +const stream_1 = require("stream"); +// Copyright 2014 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +/** + * Populate the `{{projectId}}` placeholder. + * + * @throws {Error} If a projectId is required, but one is not provided. + * + * @param {*} - Any input value that may contain a placeholder. Arrays and objects will be looped. + * @param {string} projectId - A projectId. If not provided + * @return {*} - The original argument with all placeholders populated. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function replaceProjectIdToken(value, projectId) { + if (Array.isArray(value)) { + value = value.map(v => replaceProjectIdToken(v, projectId)); + } + if (value !== null && + typeof value === 'object' && + !(value instanceof Buffer) && + !(value instanceof stream_1.Stream) && + typeof value.hasOwnProperty === 'function') { + for (const opt in value) { + // eslint-disable-next-line no-prototype-builtins + if (value.hasOwnProperty(opt)) { + value[opt] = replaceProjectIdToken(value[opt], projectId); + } + } + } + if (typeof value === 'string' && + value.indexOf('{{projectId}}') > -1) { + if (!projectId || projectId === '{{projectId}}') { + throw new MissingProjectIdError(); + } + value = value.replace(/{{projectId}}/g, projectId); + } + return value; +} +exports.replaceProjectIdToken = replaceProjectIdToken; +/** + * Custom error type for missing project ID errors. + */ +class MissingProjectIdError extends Error { + constructor() { + super(...arguments); + this.message = `Sorry, we cannot connect to Cloud Services without a project + ID. You may specify one with an environment variable named + "GOOGLE_CLOUD_PROJECT".`.replace(/ +/g, ' '); + } +} +exports.MissingProjectIdError = MissingProjectIdError; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/projectify/package.json b/node_modules/@google-cloud/projectify/package.json new file mode 100644 index 0000000..c191171 --- /dev/null +++ b/node_modules/@google-cloud/projectify/package.json @@ -0,0 +1,46 @@ +{ + "name": "@google-cloud/projectify", + "version": "4.0.0", + "description": "A simple utility for replacing the projectid token in objects.", + "main": "build/src/index.js", + "types": "build/src/index.d.ts", + "repository": "googleapis/nodejs-projectify", + "scripts": { + "test": "c8 mocha build/test", + "lint": "gts check", + "clean": "gts clean", + "compile": "tsc -p .", + "fix": "gts fix", + "prepare": "npm run compile", + "pretest": "npm run compile", + "docs": "compodoc src/", + "presystem-test": "npm run compile", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "system-test": "mocha build/system-test", + "docs-test": "linkinator docs", + "predocs-test": "npm run docs", + "prelint": "cd samples; npm link ../; npm install", + "precompile": "gts clean" + }, + "keywords": [], + "files": [ + "build/src", + "!build/src/**/*.map" + ], + "author": "Google Inc.", + "license": "Apache-2.0", + "devDependencies": { + "@compodoc/compodoc": "^1.1.11", + "@types/mocha": "^9.0.0", + "@types/node": "^20.4.9", + "c8": "^8.0.1", + "codecov": "^3.6.5", + "gts": "^5.0.0", + "linkinator": "^4.0.0", + "mocha": "^9.2.2", + "typescript": "^5.1.6" + }, + "engines": { + "node": ">=14.0.0" + } +} diff --git a/node_modules/@google-cloud/promisify/CHANGELOG.md b/node_modules/@google-cloud/promisify/CHANGELOG.md new file mode 100644 index 0000000..0393f3e --- /dev/null +++ b/node_modules/@google-cloud/promisify/CHANGELOG.md @@ -0,0 +1,191 @@ +# Changelog + +[npm history][1] + +[1]: https://www.npmjs.com/package/nodejs-promisify?activeTab=versions + +## [4.0.0](https://github.com/googleapis/nodejs-promisify/compare/v3.0.1...v4.0.0) (2023-08-08) + + +### ⚠ BREAKING CHANGES + +* upgrade to Node 14 ([#325](https://github.com/googleapis/nodejs-promisify/issues/325)) + +### Miscellaneous Chores + +* Upgrade to Node 14 ([#325](https://github.com/googleapis/nodejs-promisify/issues/325)) ([57d02c1](https://github.com/googleapis/nodejs-promisify/commit/57d02c1c23c65d63131bb99c07919ff80e5604cd)) + +## [3.0.1](https://github.com/googleapis/nodejs-promisify/compare/v3.0.0...v3.0.1) (2022-08-23) + + +### Bug Fixes + +* remove pip install statements ([#1546](https://github.com/googleapis/nodejs-promisify/issues/1546)) ([#310](https://github.com/googleapis/nodejs-promisify/issues/310)) ([c7c6883](https://github.com/googleapis/nodejs-promisify/commit/c7c688389de72ddc0181b19bceee2d95eacd3d96)) + +## [3.0.0](https://github.com/googleapis/nodejs-promisify/compare/v2.0.4...v3.0.0) (2022-05-03) + + +### ⚠ BREAKING CHANGES + +* drop node 10 from engines list, update typescript to 4.6.3 (#300) + +### Build System + +* drop node 10 from engines list, update typescript to 4.6.3 ([#300](https://github.com/googleapis/nodejs-promisify/issues/300)) ([fed2f14](https://github.com/googleapis/nodejs-promisify/commit/fed2f145a5256c939eb66b85a5c7c48332b8841d)) + +### [2.0.4](https://www.github.com/googleapis/nodejs-promisify/compare/v2.0.3...v2.0.4) (2021-09-09) + + +### Bug Fixes + +* **build:** switch primary branch to main ([#270](https://www.github.com/googleapis/nodejs-promisify/issues/270)) ([11242f7](https://www.github.com/googleapis/nodejs-promisify/commit/11242f7f76e170dae7a429f8d4064bf33be9bb3f)) + +### [2.0.3](https://www.github.com/googleapis/nodejs-promisify/compare/v2.0.2...v2.0.3) (2020-09-04) + + +### Bug Fixes + +* allow excluding accessor methods ([#228](https://www.github.com/googleapis/nodejs-promisify/issues/228)) ([114d8bc](https://www.github.com/googleapis/nodejs-promisify/commit/114d8bcef7093bdfda195a15e0c2f376195fd3fc)) + +### [2.0.2](https://www.github.com/googleapis/nodejs-promisify/compare/v2.0.1...v2.0.2) (2020-07-06) + + +### Bug Fixes + +* update node issue template ([#204](https://www.github.com/googleapis/nodejs-promisify/issues/204)) ([a2ba8d8](https://www.github.com/googleapis/nodejs-promisify/commit/a2ba8d8e45ef03d093d987292a467696745fc9fd)) + +### [2.0.1](https://www.github.com/googleapis/nodejs-promisify/compare/v2.0.0...v2.0.1) (2020-05-08) + + +### Bug Fixes + +* apache license URL ([#468](https://www.github.com/googleapis/nodejs-promisify/issues/468)) ([#191](https://www.github.com/googleapis/nodejs-promisify/issues/191)) ([0edc724](https://www.github.com/googleapis/nodejs-promisify/commit/0edc7246c53d25d9dd220b813561bcee97250783)) + +## [2.0.0](https://www.github.com/googleapis/nodejs-promisify/compare/v1.0.4...v2.0.0) (2020-03-23) + + +### ⚠ BREAKING CHANGES + +* update to latest version of gts/typescript (#183) +* drop Node 8 from engines field (#184) + +### Features + +* drop Node 8 from engines field ([#184](https://www.github.com/googleapis/nodejs-promisify/issues/184)) ([7e6d3c5](https://www.github.com/googleapis/nodejs-promisify/commit/7e6d3c54066d89530ed25c7f9722efd252f43fb8)) + + +### Build System + +* update to latest version of gts/typescript ([#183](https://www.github.com/googleapis/nodejs-promisify/issues/183)) ([9c3ed12](https://www.github.com/googleapis/nodejs-promisify/commit/9c3ed12c12f4bb1e17af7440c6371c4cefddcd59)) + +### [1.0.4](https://www.github.com/googleapis/nodejs-promisify/compare/v1.0.3...v1.0.4) (2019-12-05) + + +### Bug Fixes + +* **deps:** pin TypeScript below 3.7.0 ([e48750e](https://www.github.com/googleapis/nodejs-promisify/commit/e48750ef96aa20eb3a2b73fe2f062d04430468a7)) + +### [1.0.3](https://www.github.com/googleapis/nodejs-promisify/compare/v1.0.2...v1.0.3) (2019-11-13) + + +### Bug Fixes + +* **docs:** add jsdoc-region-tag plugin ([#146](https://www.github.com/googleapis/nodejs-promisify/issues/146)) ([ff0ee74](https://www.github.com/googleapis/nodejs-promisify/commit/ff0ee7408f50e8f7147b8ccf7e10337aa5920076)) + +### [1.0.2](https://www.github.com/googleapis/nodejs-promisify/compare/v1.0.1...v1.0.2) (2019-06-26) + + +### Bug Fixes + +* **docs:** link to reference docs section on googleapis.dev ([#128](https://www.github.com/googleapis/nodejs-promisify/issues/128)) ([5a8bd90](https://www.github.com/googleapis/nodejs-promisify/commit/5a8bd90)) + +### [1.0.1](https://www.github.com/googleapis/nodejs-promisify/compare/v1.0.0...v1.0.1) (2019-06-14) + + +### Bug Fixes + +* **docs:** move to new client docs URL ([#124](https://www.github.com/googleapis/nodejs-promisify/issues/124)) ([34d18cd](https://www.github.com/googleapis/nodejs-promisify/commit/34d18cd)) + +## [1.0.0](https://www.github.com/googleapis/nodejs-promisify/compare/v0.4.0...v1.0.0) (2019-05-02) + + +### Build System + +* upgrade engines field to >=8.10.0 ([#108](https://www.github.com/googleapis/nodejs-promisify/issues/108)) ([78ab89c](https://www.github.com/googleapis/nodejs-promisify/commit/78ab89c)) + + +### BREAKING CHANGES + +* upgrade engines field to >=8.10.0 (#108) + +## v0.4.0 + +02-12-2019 19:44 PST + +### New features +- feat: add callbackify() and callbackifyAll() methods ([#82](https://github.com/googleapis/nodejs-promisify/pull/82)) + +### Documentation +- docs: update contributing path in README ([#86](https://github.com/googleapis/nodejs-promisify/pull/86)) +- chore: move CONTRIBUTING.md to root ([#85](https://github.com/googleapis/nodejs-promisify/pull/85)) +- docs: add lint/fix example to contributing guide ([#83](https://github.com/googleapis/nodejs-promisify/pull/83)) + +### Internal / Testing Changes +- build: create docs test npm scripts ([#88](https://github.com/googleapis/nodejs-promisify/pull/88)) +- build: test using @grpc/grpc-js in CI ([#87](https://github.com/googleapis/nodejs-promisify/pull/87)) +- build: ignore googleapis.com in doc link check ([#81](https://github.com/googleapis/nodejs-promisify/pull/81)) +- build: check broken links in generated docs ([#79](https://github.com/googleapis/nodejs-promisify/pull/79)) +- chore(deps): update dependency @types/sinon to v7 ([#78](https://github.com/googleapis/nodejs-promisify/pull/78)) +- chore(build): inject yoshi automation key ([#77](https://github.com/googleapis/nodejs-promisify/pull/77)) +- chore: update nyc and eslint configs ([#76](https://github.com/googleapis/nodejs-promisify/pull/76)) +- chore: fix publish.sh permission +x ([#74](https://github.com/googleapis/nodejs-promisify/pull/74)) +- fix(build): fix Kokoro release script ([#73](https://github.com/googleapis/nodejs-promisify/pull/73)) +- build: add Kokoro configs for autorelease ([#72](https://github.com/googleapis/nodejs-promisify/pull/72)) +- chore: always nyc report before calling codecov ([#69](https://github.com/googleapis/nodejs-promisify/pull/69)) +- chore: nyc ignore build/test by default ([#68](https://github.com/googleapis/nodejs-promisify/pull/68)) +- chore(build): update prettier config ([#66](https://github.com/googleapis/nodejs-promisify/pull/66)) +- fix: get the build passing ([#65](https://github.com/googleapis/nodejs-promisify/pull/65)) +- chore: update license file ([#64](https://github.com/googleapis/nodejs-promisify/pull/64)) +- fix(build): fix system key decryption ([#60](https://github.com/googleapis/nodejs-promisify/pull/60)) +- chore(deps): update dependency @types/sinon to v5.0.7 ([#58](https://github.com/googleapis/nodejs-promisify/pull/58)) +- fix: Pin @types/sinon to last compatible version ([#57](https://github.com/googleapis/nodejs-promisify/pull/57)) +- chore: add synth.metadata +- chore(deps): update dependency gts to ^0.9.0 ([#54](https://github.com/googleapis/nodejs-promisify/pull/54)) +- chore: update eslintignore config ([#53](https://github.com/googleapis/nodejs-promisify/pull/53)) +- chore: use latest npm on Windows ([#52](https://github.com/googleapis/nodejs-promisify/pull/52)) +- chore: update CircleCI config ([#51](https://github.com/googleapis/nodejs-promisify/pull/51)) +- chore: include build in eslintignore ([#48](https://github.com/googleapis/nodejs-promisify/pull/48)) +- chore: update issue templates ([#44](https://github.com/googleapis/nodejs-promisify/pull/44)) +- chore: remove old issue template ([#42](https://github.com/googleapis/nodejs-promisify/pull/42)) +- build: run tests on node11 ([#41](https://github.com/googleapis/nodejs-promisify/pull/41)) +- chores(build): do not collect sponge.xml from windows builds ([#40](https://github.com/googleapis/nodejs-promisify/pull/40)) +- chores(build): run codecov on continuous builds ([#39](https://github.com/googleapis/nodejs-promisify/pull/39)) +- chore: update new issue template ([#38](https://github.com/googleapis/nodejs-promisify/pull/38)) +- chore(deps): update dependency sinon to v7 ([#33](https://github.com/googleapis/nodejs-promisify/pull/33)) +- build: fix codecov uploading on Kokoro ([#34](https://github.com/googleapis/nodejs-promisify/pull/34)) +- Update kokoro config ([#30](https://github.com/googleapis/nodejs-promisify/pull/30)) +- Update CI config ([#28](https://github.com/googleapis/nodejs-promisify/pull/28)) +- Don't publish sourcemaps ([#26](https://github.com/googleapis/nodejs-promisify/pull/26)) +- Update kokoro config ([#24](https://github.com/googleapis/nodejs-promisify/pull/24)) +- test: remove appveyor config ([#23](https://github.com/googleapis/nodejs-promisify/pull/23)) +- Update CI config ([#22](https://github.com/googleapis/nodejs-promisify/pull/22)) +- Enable prefer-const in the eslint config ([#21](https://github.com/googleapis/nodejs-promisify/pull/21)) +- Enable no-var in eslint ([#19](https://github.com/googleapis/nodejs-promisify/pull/19)) +- Update CI config ([#18](https://github.com/googleapis/nodejs-promisify/pull/18)) + +## v0.3.1 + +### Internal / Testing Changes +- Add synth script and update CI (#14) +- chore(deps): update dependency nyc to v13 (#12) +- chore: ignore package-lock.json (#11) +- chore(deps): lock file maintenance (#10) +- chore: update renovate config (#9) +- remove that whitespace (#8) +- chore(deps): lock file maintenance (#7) +- chore(deps): update dependency typescript to v3 (#6) +- chore: assert.deelEqual => assert.deepStrictEqual (#5) +- chore: move mocha options to mocha.opts (#4) +- chore(deps): update dependency gts to ^0.8.0 (#1) +- chore(deps): lock file maintenance (#3) +- chore(deps): lock file maintenance (#2) diff --git a/node_modules/@google-cloud/promisify/LICENSE b/node_modules/@google-cloud/promisify/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/@google-cloud/promisify/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@google-cloud/promisify/README.md b/node_modules/@google-cloud/promisify/README.md new file mode 100644 index 0000000..5702438 --- /dev/null +++ b/node_modules/@google-cloud/promisify/README.md @@ -0,0 +1,156 @@ +[//]: # "This README.md file is auto-generated, all changes to this file will be lost." +[//]: # "To regenerate it, use `python -m synthtool`." +Google Cloud Platform logo + +# [Google Cloud Common Promisify: Node.js Client](https://github.com/googleapis/nodejs-promisify) + +[![release level](https://img.shields.io/badge/release%20level-stable-brightgreen.svg?style=flat)](https://cloud.google.com/terms/launch-stages) +[![npm version](https://img.shields.io/npm/v/@google-cloud/promisify.svg)](https://www.npmjs.org/package/@google-cloud/promisify) + + + + +A simple utility for promisifying functions and classes. + + +A comprehensive list of changes in each version may be found in +[the CHANGELOG](https://github.com/googleapis/nodejs-promisify/blob/main/CHANGELOG.md). + +* [Google Cloud Common Promisify Node.js Client API Reference][client-docs] + +* [github.com/googleapis/nodejs-promisify](https://github.com/googleapis/nodejs-promisify) + +Read more about the client libraries for Cloud APIs, including the older +Google APIs Client Libraries, in [Client Libraries Explained][explained]. + +[explained]: https://cloud.google.com/apis/docs/client-libraries-explained + +**Table of contents:** + + +* [Quickstart](#quickstart) + + * [Installing the client library](#installing-the-client-library) + * [Using the client library](#using-the-client-library) +* [Samples](#samples) +* [Versioning](#versioning) +* [Contributing](#contributing) +* [License](#license) + +## Quickstart + +### Installing the client library + +```bash +npm install @google-cloud/promisify +``` + + +### Using the client library + +```javascript +const {promisify} = require('@google-cloud/promisify'); + +/** + * This is a very basic example function that accepts a callback. + */ +function someCallbackFunction(name, callback) { + if (!name) { + callback(new Error('Name is required!')); + } else { + callback(null, `Well hello there, ${name}!`); + } +} + +// let's promisify it! +const somePromiseFunction = promisify(someCallbackFunction); + +async function quickstart() { + // now we can just `await` the function to use it like a promisified method + const [result] = await somePromiseFunction('nodestronaut'); + console.log(result); +} +quickstart(); + +``` +It's unlikely you will need to install this package directly, as it will be +installed as a dependency when you install other `@google-cloud` packages. + + +## Samples + +Samples are in the [`samples/`](https://github.com/googleapis/nodejs-promisify/tree/main/samples) directory. Each sample's `README.md` has instructions for running its sample. + +| Sample | Source Code | Try it | +| --------------------------- | --------------------------------- | ------ | +| Quickstart | [source code](https://github.com/googleapis/nodejs-promisify/blob/main/samples/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-promisify&page=editor&open_in_editor=samples/quickstart.js,samples/README.md) | + + + +The [Google Cloud Common Promisify Node.js Client API Reference][client-docs] documentation +also contains samples. + +## Supported Node.js Versions + +Our client libraries follow the [Node.js release schedule](https://github.com/nodejs/release#release-schedule). +Libraries are compatible with all current _active_ and _maintenance_ versions of +Node.js. +If you are using an end-of-life version of Node.js, we recommend that you update +as soon as possible to an actively supported LTS version. + +Google's client libraries support legacy versions of Node.js runtimes on a +best-efforts basis with the following warnings: + +* Legacy versions are not tested in continuous integration. +* Some security patches and features cannot be backported. +* Dependencies cannot be kept up-to-date. + +Client libraries targeting some end-of-life versions of Node.js are available, and +can be installed through npm [dist-tags](https://docs.npmjs.com/cli/dist-tag). +The dist-tags follow the naming convention `legacy-(version)`. +For example, `npm install @google-cloud/promisify@legacy-8` installs client libraries +for versions compatible with Node.js 8. + +## Versioning + +This library follows [Semantic Versioning](http://semver.org/). + + + +This library is considered to be **stable**. The code surface will not change in backwards-incompatible ways +unless absolutely necessary (e.g. because of critical security issues) or with +an extensive deprecation period. Issues and requests against **stable** libraries +are addressed with the highest priority. + + + + + + +More Information: [Google Cloud Platform Launch Stages][launch_stages] + +[launch_stages]: https://cloud.google.com/terms/launch-stages + +## Contributing + +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/nodejs-promisify/blob/main/CONTRIBUTING.md). + +Please note that this `README.md`, the `samples/README.md`, +and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) +are generated from a central template. To edit one of these files, make an edit +to its templates in +[directory](https://github.com/googleapis/synthtool). + +## License + +Apache Version 2.0 + +See [LICENSE](https://github.com/googleapis/nodejs-promisify/blob/main/LICENSE) + +[client-docs]: https://googleapis.dev/nodejs/promisify/latest + +[shell_img]: https://gstatic.com/cloudssh/images/open-btn.png +[projects]: https://console.cloud.google.com/project +[billing]: https://support.google.com/cloud/answer/6293499#enable-billing + +[auth]: https://cloud.google.com/docs/authentication/getting-started diff --git a/node_modules/@google-cloud/promisify/build/src/index.d.ts b/node_modules/@google-cloud/promisify/build/src/index.d.ts new file mode 100644 index 0000000..9d75a39 --- /dev/null +++ b/node_modules/@google-cloud/promisify/build/src/index.d.ts @@ -0,0 +1,61 @@ +export interface PromisifyAllOptions extends PromisifyOptions { + /** + * Array of methods to ignore when promisifying. + */ + exclude?: string[]; +} +export interface PromisifyOptions { + /** + * Resolve the promise with single arg instead of an array. + */ + singular?: boolean; +} +export interface PromiseMethod extends Function { + promisified_?: boolean; +} +export interface WithPromise { + Promise?: PromiseConstructor; +} +export interface CallbackifyAllOptions { + /** + * Array of methods to ignore when callbackifying. + */ + exclude?: string[]; +} +export interface CallbackMethod extends Function { + callbackified_?: boolean; +} +/** + * Wraps a callback style function to conditionally return a promise. + * + * @param {function} originalMethod - The method to promisify. + * @param {object=} options - Promise options. + * @param {boolean} options.singular - Resolve the promise with single arg instead of an array. + * @return {function} wrapped + */ +export declare function promisify(originalMethod: PromiseMethod, options?: PromisifyOptions): any; +/** + * Promisifies certain Class methods. This will not promisify private or + * streaming methods. + * + * @param {module:common/service} Class - Service class. + * @param {object=} options - Configuration object. + */ +export declare function promisifyAll(Class: Function, options?: PromisifyAllOptions): void; +/** + * Wraps a promisy type function to conditionally call a callback function. + * + * @param {function} originalMethod - The method to callbackify. + * @param {object=} options - Callback options. + * @param {boolean} options.singular - Pass to the callback a single arg instead of an array. + * @return {function} wrapped + */ +export declare function callbackify(originalMethod: CallbackMethod): CallbackMethod; +/** + * Callbackifies certain Class methods. This will not callbackify private or + * streaming methods. + * + * @param {module:common/service} Class - Service class. + * @param {object=} options - Configuration object. + */ +export declare function callbackifyAll(Class: Function, options?: CallbackifyAllOptions): void; diff --git a/node_modules/@google-cloud/promisify/build/src/index.js b/node_modules/@google-cloud/promisify/build/src/index.js new file mode 100644 index 0000000..3199b96 --- /dev/null +++ b/node_modules/@google-cloud/promisify/build/src/index.js @@ -0,0 +1,148 @@ +"use strict"; +/* eslint-disable prefer-rest-params */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.callbackifyAll = exports.callbackify = exports.promisifyAll = exports.promisify = void 0; +/** + * Wraps a callback style function to conditionally return a promise. + * + * @param {function} originalMethod - The method to promisify. + * @param {object=} options - Promise options. + * @param {boolean} options.singular - Resolve the promise with single arg instead of an array. + * @return {function} wrapped + */ +function promisify(originalMethod, options) { + if (originalMethod.promisified_) { + return originalMethod; + } + options = options || {}; + const slice = Array.prototype.slice; + // tslint:disable-next-line:no-any + const wrapper = function () { + let last; + for (last = arguments.length - 1; last >= 0; last--) { + const arg = arguments[last]; + if (typeof arg === 'undefined') { + continue; // skip trailing undefined. + } + if (typeof arg !== 'function') { + break; // non-callback last argument found. + } + return originalMethod.apply(this, arguments); + } + // peel trailing undefined. + const args = slice.call(arguments, 0, last + 1); + // tslint:disable-next-line:variable-name + let PromiseCtor = Promise; + // Because dedupe will likely create a single install of + // @google-cloud/common to be shared amongst all modules, we need to + // localize it at the Service level. + if (this && this.Promise) { + PromiseCtor = this.Promise; + } + return new PromiseCtor((resolve, reject) => { + // tslint:disable-next-line:no-any + args.push((...args) => { + const callbackArgs = slice.call(args); + const err = callbackArgs.shift(); + if (err) { + return reject(err); + } + if (options.singular && callbackArgs.length === 1) { + resolve(callbackArgs[0]); + } + else { + resolve(callbackArgs); + } + }); + originalMethod.apply(this, args); + }); + }; + wrapper.promisified_ = true; + return wrapper; +} +exports.promisify = promisify; +/** + * Promisifies certain Class methods. This will not promisify private or + * streaming methods. + * + * @param {module:common/service} Class - Service class. + * @param {object=} options - Configuration object. + */ +// tslint:disable-next-line:variable-name +function promisifyAll(Class, options) { + const exclude = (options && options.exclude) || []; + const ownPropertyNames = Object.getOwnPropertyNames(Class.prototype); + const methods = ownPropertyNames.filter(methodName => { + // clang-format off + return (!exclude.includes(methodName) && + typeof Class.prototype[methodName] === 'function' && // is it a function? + !/(^_|(Stream|_)|promise$)|^constructor$/.test(methodName) // is it promisable? + ); + // clang-format on + }); + methods.forEach(methodName => { + const originalMethod = Class.prototype[methodName]; + if (!originalMethod.promisified_) { + Class.prototype[methodName] = exports.promisify(originalMethod, options); + } + }); +} +exports.promisifyAll = promisifyAll; +/** + * Wraps a promisy type function to conditionally call a callback function. + * + * @param {function} originalMethod - The method to callbackify. + * @param {object=} options - Callback options. + * @param {boolean} options.singular - Pass to the callback a single arg instead of an array. + * @return {function} wrapped + */ +function callbackify(originalMethod) { + if (originalMethod.callbackified_) { + return originalMethod; + } + // tslint:disable-next-line:no-any + const wrapper = function () { + if (typeof arguments[arguments.length - 1] !== 'function') { + return originalMethod.apply(this, arguments); + } + const cb = Array.prototype.pop.call(arguments); + originalMethod.apply(this, arguments).then( + // tslint:disable-next-line:no-any + (res) => { + res = Array.isArray(res) ? res : [res]; + cb(null, ...res); + }, (err) => cb(err)); + }; + wrapper.callbackified_ = true; + return wrapper; +} +exports.callbackify = callbackify; +/** + * Callbackifies certain Class methods. This will not callbackify private or + * streaming methods. + * + * @param {module:common/service} Class - Service class. + * @param {object=} options - Configuration object. + */ +function callbackifyAll( +// tslint:disable-next-line:variable-name +Class, options) { + const exclude = (options && options.exclude) || []; + const ownPropertyNames = Object.getOwnPropertyNames(Class.prototype); + const methods = ownPropertyNames.filter(methodName => { + // clang-format off + return (!exclude.includes(methodName) && + typeof Class.prototype[methodName] === 'function' && // is it a function? + !/^_|(Stream|_)|^constructor$/.test(methodName) // is it callbackifyable? + ); + // clang-format on + }); + methods.forEach(methodName => { + const originalMethod = Class.prototype[methodName]; + if (!originalMethod.callbackified_) { + Class.prototype[methodName] = exports.callbackify(originalMethod); + } + }); +} +exports.callbackifyAll = callbackifyAll; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/promisify/package.json b/node_modules/@google-cloud/promisify/package.json new file mode 100644 index 0000000..509150b --- /dev/null +++ b/node_modules/@google-cloud/promisify/package.json @@ -0,0 +1,50 @@ +{ + "name": "@google-cloud/promisify", + "version": "4.0.0", + "description": "A simple utility for promisifying functions and classes.", + "main": "build/src/index.js", + "types": "build/src/index.d.ts", + "repository": "googleapis/nodejs-promisify", + "scripts": { + "test": "c8 mocha build/test", + "lint": "gts check", + "compile": "tsc -p .", + "fix": "gts fix", + "prepare": "npm run compile", + "pretest": "npm run compile", + "docs": "compodoc src/", + "presystem-test": "npm run compile", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "system-test": "mocha build/system-test", + "docs-test": "linkinator docs", + "predocs-test": "npm run docs", + "prelint": "cd samples; npm link ../; npm install", + "clean": "gts clean", + "precompile": "gts clean" + }, + "keywords": [], + "files": [ + "build/src", + "!build/src/**/*.map" + ], + "author": "Google Inc.", + "license": "Apache-2.0", + "devDependencies": { + "@compodoc/compodoc": "^1.1.9", + "@types/mocha": "^9.0.0", + "@types/node": "^20.4.8", + "@types/sinon": "^10.0.0", + "c8": "^8.0.1", + "chai": "^4.2.0", + "codecov": "^3.0.4", + "gts": "^5.0.0", + "hard-rejection": "^2.1.0", + "linkinator": "^5.0.1", + "mocha": "^8.0.0", + "sinon": "^15.0.0", + "typescript": "^5.1.6" + }, + "engines": { + "node": ">=14" + } +} diff --git a/node_modules/@google-cloud/storage/LICENSE b/node_modules/@google-cloud/storage/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/@google-cloud/storage/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@google-cloud/storage/README.md b/node_modules/@google-cloud/storage/README.md new file mode 100644 index 0000000..ea2c8dc --- /dev/null +++ b/node_modules/@google-cloud/storage/README.md @@ -0,0 +1,302 @@ +[//]: # "This README.md file is auto-generated, all changes to this file will be lost." +[//]: # "To regenerate it, use `python -m synthtool`." +Google Cloud Platform logo + +# [Google Cloud Storage: Node.js Client](https://github.com/googleapis/nodejs-storage) + +[![release level](https://img.shields.io/badge/release%20level-stable-brightgreen.svg?style=flat)](https://cloud.google.com/terms/launch-stages) +[![npm version](https://img.shields.io/npm/v/@google-cloud/storage.svg)](https://www.npmjs.com/package/@google-cloud/storage) + + + + +> Node.js idiomatic client for [Cloud Storage][product-docs]. + +[Cloud Storage](https://cloud.google.com/storage/docs) allows world-wide +storage and retrieval of any amount of data at any time. You can use Google +Cloud Storage for a range of scenarios including serving website content, +storing data for archival and disaster recovery, or distributing large data +objects to users via direct download. + + +A comprehensive list of changes in each version may be found in +[the CHANGELOG](https://github.com/googleapis/nodejs-storage/blob/main/CHANGELOG.md). + +* [Google Cloud Storage Node.js Client API Reference][client-docs] +* [Google Cloud Storage Documentation][product-docs] +* [github.com/googleapis/nodejs-storage](https://github.com/googleapis/nodejs-storage) + +Read more about the client libraries for Cloud APIs, including the older +Google APIs Client Libraries, in [Client Libraries Explained][explained]. + +[explained]: https://cloud.google.com/apis/docs/client-libraries-explained + +**Table of contents:** + + +* [Quickstart](#quickstart) + * [Before you begin](#before-you-begin) + * [Installing the client library](#installing-the-client-library) + * [Using the client library](#using-the-client-library) +* [Samples](#samples) +* [Versioning](#versioning) +* [Contributing](#contributing) +* [License](#license) + +## Quickstart + +### Before you begin + +1. [Select or create a Cloud Platform project][projects]. +1. [Enable billing for your project][billing]. +1. [Enable the Google Cloud Storage API][enable_api]. +1. [Set up authentication][auth] so you can access the + API from your local workstation. + +### Installing the client library + +```bash +npm install @google-cloud/storage +``` + + +### Using the client library + +```javascript +// Imports the Google Cloud client library +const {Storage} = require('@google-cloud/storage'); + +// For more information on ways to initialize Storage, please see +// https://googleapis.dev/nodejs/storage/latest/Storage.html + +// Creates a client using Application Default Credentials +const storage = new Storage(); + +// Creates a client from a Google service account key +// const storage = new Storage({keyFilename: 'key.json'}); + +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// The ID of your GCS bucket +// const bucketName = 'your-unique-bucket-name'; + +async function createBucket() { + // Creates the new bucket + await storage.createBucket(bucketName); + console.log(`Bucket ${bucketName} created.`); +} + +createBucket().catch(console.error); + +``` + + + +## Samples + +Samples are in the [`samples/`](https://github.com/googleapis/nodejs-storage/tree/main/samples) directory. Each sample's `README.md` has instructions for running its sample. + +| Sample | Source Code | Try it | +| --------------------------- | --------------------------------- | ------ | +| Add Bucket Conditional Binding | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/addBucketConditionalBinding.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/addBucketConditionalBinding.js,samples/README.md) | +| Add Bucket Default Owner Acl | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/addBucketDefaultOwnerAcl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/addBucketDefaultOwnerAcl.js,samples/README.md) | +| Add Bucket Iam Member | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/addBucketIamMember.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/addBucketIamMember.js,samples/README.md) | +| Storage Add Bucket Label. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/addBucketLabel.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/addBucketLabel.js,samples/README.md) | +| Add Bucket Owner Acl | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/addBucketOwnerAcl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/addBucketOwnerAcl.js,samples/README.md) | +| Bucket Website Configuration. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/addBucketWebsiteConfiguration.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/addBucketWebsiteConfiguration.js,samples/README.md) | +| Add File Owner Acl | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/addFileOwnerAcl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/addFileOwnerAcl.js,samples/README.md) | +| Storage Get Bucket Metadata. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/bucketMetadata.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/bucketMetadata.js,samples/README.md) | +| Change Bucket's Default Storage Class. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/changeDefaultStorageClass.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/changeDefaultStorageClass.js,samples/README.md) | +| Storage File Convert CSEK to CMEK. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/changeFileCSEKToCMEK.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/changeFileCSEKToCMEK.js,samples/README.md) | +| Storage Combine files. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/composeFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/composeFile.js,samples/README.md) | +| Storage Configure Bucket Cors. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/configureBucketCors.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/configureBucketCors.js,samples/README.md) | +| Configure Retries | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/configureRetries.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/configureRetries.js,samples/README.md) | +| Copy File | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/copyFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/copyFile.js,samples/README.md) | +| Copy Old Version Of File. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/copyOldVersionOfFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/copyOldVersionOfFile.js,samples/README.md) | +| Create a Dual-Region Bucket | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/createBucketWithDualRegion.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/createBucketWithDualRegion.js,samples/README.md) | +| Create a hierarchical namespace enabled bucket | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/createBucketWithHierarchicalNamespace.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/createBucketWithHierarchicalNamespace.js,samples/README.md) | +| Create a Bucket with object retention enabled. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/createBucketWithObjectRetention.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/createBucketWithObjectRetention.js,samples/README.md) | +| Create Bucket With Storage Class and Location. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/createBucketWithStorageClassAndLocation.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/createBucketWithStorageClassAndLocation.js,samples/README.md) | +| Create Bucket With Turbo Replication | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/createBucketWithTurboReplication.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/createBucketWithTurboReplication.js,samples/README.md) | +| Create New Bucket | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/createNewBucket.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/createNewBucket.js,samples/README.md) | +| Create Notification | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/createNotification.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/createNotification.js,samples/README.md) | +| Delete Bucket | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/deleteBucket.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/deleteBucket.js,samples/README.md) | +| Delete File | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/deleteFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/deleteFile.js,samples/README.md) | +| Delete Notification | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/deleteNotification.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/deleteNotification.js,samples/README.md) | +| Delete Old Version Of File. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/deleteOldVersionOfFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/deleteOldVersionOfFile.js,samples/README.md) | +| Disable Bucket Lifecycle Management | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/disableBucketLifecycleManagement.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/disableBucketLifecycleManagement.js,samples/README.md) | +| Storage Disable Bucket Versioning. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/disableBucketVersioning.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/disableBucketVersioning.js,samples/README.md) | +| Disable Default Event Based Hold | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/disableDefaultEventBasedHold.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/disableDefaultEventBasedHold.js,samples/README.md) | +| Disable Requester Pays | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/disableRequesterPays.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/disableRequesterPays.js,samples/README.md) | +| Disable Soft Delete | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/disableSoftDelete.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/disableSoftDelete.js,samples/README.md) | +| Disable Uniform Bucket Level Access | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/disableUniformBucketLevelAccess.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/disableUniformBucketLevelAccess.js,samples/README.md) | +| Download Byte Range | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/downloadByteRange.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/downloadByteRange.js,samples/README.md) | +| Download Encrypted File | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/downloadEncryptedFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/downloadEncryptedFile.js,samples/README.md) | +| Download File | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/downloadFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/downloadFile.js,samples/README.md) | +| Download a File in Chunks With Transfer Manager | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/downloadFileInChunksWithTransferManager.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/downloadFileInChunksWithTransferManager.js,samples/README.md) | +| Download File Using Requester Pays | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/downloadFileUsingRequesterPays.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/downloadFileUsingRequesterPays.js,samples/README.md) | +| Download Folder With Transfer Manager | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/downloadFolderWithTransferManager.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/downloadFolderWithTransferManager.js,samples/README.md) | +| Download Into Memory | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/downloadIntoMemory.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/downloadIntoMemory.js,samples/README.md) | +| Download Many Files With Transfer Manager | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/downloadManyFilesWithTransferManager.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/downloadManyFilesWithTransferManager.js,samples/README.md) | +| Storage Download Public File. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/downloadPublicFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/downloadPublicFile.js,samples/README.md) | +| Enable Bucket Lifecycle Management | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/enableBucketLifecycleManagement.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/enableBucketLifecycleManagement.js,samples/README.md) | +| Storage Enable Bucket Versioning. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/enableBucketVersioning.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/enableBucketVersioning.js,samples/README.md) | +| Enable Default Event Based Hold | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/enableDefaultEventBasedHold.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/enableDefaultEventBasedHold.js,samples/README.md) | +| Enable Default KMS Key | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/enableDefaultKMSKey.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/enableDefaultKMSKey.js,samples/README.md) | +| Enable Requester Pays | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/enableRequesterPays.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/enableRequesterPays.js,samples/README.md) | +| Enable Uniform Bucket Level Access | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/enableUniformBucketLevelAccess.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/enableUniformBucketLevelAccess.js,samples/README.md) | +| Change File's Storage Class. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/fileChangeStorageClass.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/fileChangeStorageClass.js,samples/README.md) | +| Storage Set File Metadata. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/fileSetMetadata.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/fileSetMetadata.js,samples/README.md) | +| Generate Encryption Key | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/generateEncryptionKey.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/generateEncryptionKey.js,samples/README.md) | +| Generate Signed Url | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/generateSignedUrl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/generateSignedUrl.js,samples/README.md) | +| Generate V4 Read Signed Url | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/generateV4ReadSignedUrl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/generateV4ReadSignedUrl.js,samples/README.md) | +| Generate V4 Signed Policy | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/generateV4SignedPolicy.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/generateV4SignedPolicy.js,samples/README.md) | +| Generate V4 Upload Signed Url | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/generateV4UploadSignedUrl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/generateV4UploadSignedUrl.js,samples/README.md) | +| Get Autoclass | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getAutoclass.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getAutoclass.js,samples/README.md) | +| Get Default Event Based Hold | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getDefaultEventBasedHold.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getDefaultEventBasedHold.js,samples/README.md) | +| Get Metadata | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getMetadata.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getMetadata.js,samples/README.md) | +| Get Metadata Notifications | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getMetadataNotifications.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getMetadataNotifications.js,samples/README.md) | +| Get Public Access Prevention | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getPublicAccessPrevention.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getPublicAccessPrevention.js,samples/README.md) | +| Get RPO | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getRPO.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getRPO.js,samples/README.md) | +| Get Requester Pays Status | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getRequesterPaysStatus.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getRequesterPaysStatus.js,samples/README.md) | +| Get Retention Policy | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getRetentionPolicy.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getRetentionPolicy.js,samples/README.md) | +| Storage Get Service Account. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getServiceAccount.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getServiceAccount.js,samples/README.md) | +| Get Soft Delete Policy | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getSoftDeletePolicy.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getSoftDeletePolicy.js,samples/README.md) | +| Get Soft Deleted Bucket | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getSoftDeletedBucket.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getSoftDeletedBucket.js,samples/README.md) | +| Get Uniform Bucket Level Access | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getUniformBucketLevelAccess.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getUniformBucketLevelAccess.js,samples/README.md) | +| Activate HMAC SA Key. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/hmacKeyActivate.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/hmacKeyActivate.js,samples/README.md) | +| Create HMAC SA Key. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/hmacKeyCreate.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/hmacKeyCreate.js,samples/README.md) | +| Deactivate HMAC SA Key. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/hmacKeyDeactivate.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/hmacKeyDeactivate.js,samples/README.md) | +| Delete HMAC SA Key. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/hmacKeyDelete.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/hmacKeyDelete.js,samples/README.md) | +| Get HMAC SA Key Metadata. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/hmacKeyGet.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/hmacKeyGet.js,samples/README.md) | +| List HMAC SA Keys Metadata. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/hmacKeysList.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/hmacKeysList.js,samples/README.md) | +| List Buckets | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/listBuckets.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/listBuckets.js,samples/README.md) | +| List Buckets Partial Success | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/listBucketsPartialSuccess.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/listBucketsPartialSuccess.js,samples/README.md) | +| List Files | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/listFiles.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/listFiles.js,samples/README.md) | +| List Files By Prefix | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/listFilesByPrefix.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/listFilesByPrefix.js,samples/README.md) | +| List Files Paginate | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/listFilesPaginate.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/listFilesPaginate.js,samples/README.md) | +| List Files with Old Versions. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/listFilesWithOldVersions.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/listFilesWithOldVersions.js,samples/README.md) | +| List Notifications | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/listNotifications.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/listNotifications.js,samples/README.md) | +| List Soft Deleted Bucket | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/listSoftDeletedBucket.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/listSoftDeletedBucket.js,samples/README.md) | +| List Soft Deleted Object Versions | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/listSoftDeletedObjectVersions.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/listSoftDeletedObjectVersions.js,samples/README.md) | +| List Soft Deleted Objects | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/listSoftDeletedObjects.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/listSoftDeletedObjects.js,samples/README.md) | +| Lock Retention Policy | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/lockRetentionPolicy.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/lockRetentionPolicy.js,samples/README.md) | +| Storage Make Bucket Public. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/makeBucketPublic.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/makeBucketPublic.js,samples/README.md) | +| Make Public | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/makePublic.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/makePublic.js,samples/README.md) | +| Move File | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/moveFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/moveFile.js,samples/README.md) | +| Move File Atomic | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/moveFileAtomic.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/moveFileAtomic.js,samples/README.md) | +| Print Bucket Acl | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/printBucketAcl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/printBucketAcl.js,samples/README.md) | +| Print Bucket Acl For User | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/printBucketAclForUser.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/printBucketAclForUser.js,samples/README.md) | +| Print File Acl | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/printFileAcl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/printFileAcl.js,samples/README.md) | +| Print File Acl For User | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/printFileAclForUser.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/printFileAclForUser.js,samples/README.md) | +| Quickstart | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/quickstart.js,samples/README.md) | +| Release Event Based Hold | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/releaseEventBasedHold.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/releaseEventBasedHold.js,samples/README.md) | +| Release Temporary Hold | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/releaseTemporaryHold.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/releaseTemporaryHold.js,samples/README.md) | +| Remove Bucket Conditional Binding | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/removeBucketConditionalBinding.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/removeBucketConditionalBinding.js,samples/README.md) | +| Storage Remove Bucket Cors Configuration. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/removeBucketCors.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/removeBucketCors.js,samples/README.md) | +| Remove Bucket Default Owner | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/removeBucketDefaultOwner.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/removeBucketDefaultOwner.js,samples/README.md) | +| Remove Bucket Iam Member | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/removeBucketIamMember.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/removeBucketIamMember.js,samples/README.md) | +| Storage Remove Bucket Label. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/removeBucketLabel.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/removeBucketLabel.js,samples/README.md) | +| Remove Bucket Owner Acl | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/removeBucketOwnerAcl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/removeBucketOwnerAcl.js,samples/README.md) | +| Remove Default KMS Key. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/removeDefaultKMSKey.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/removeDefaultKMSKey.js,samples/README.md) | +| Remove File Owner Acl | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/removeFileOwnerAcl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/removeFileOwnerAcl.js,samples/README.md) | +| Remove Retention Policy | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/removeRetentionPolicy.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/removeRetentionPolicy.js,samples/README.md) | +| Rename File | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/renameFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/renameFile.js,samples/README.md) | +| Restore Soft Deleted Bucket | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/restoreSoftDeletedBucket.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/restoreSoftDeletedBucket.js,samples/README.md) | +| Restore Soft Deleted Object | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/restoreSoftDeletedObject.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/restoreSoftDeletedObject.js,samples/README.md) | +| Rotate Encryption Key | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/rotateEncryptionKey.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/rotateEncryptionKey.js,samples/README.md) | +| Set Autoclass | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setAutoclass.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setAutoclass.js,samples/README.md) | +| Set Client Endpoint | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setClientEndpoint.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setClientEndpoint.js,samples/README.md) | +| Set Event Based Hold | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setEventBasedHold.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setEventBasedHold.js,samples/README.md) | +| Set the object retention policy of a File. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setObjectRetentionPolicy.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setObjectRetentionPolicy.js,samples/README.md) | +| Set Public Access Prevention Enforced | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setPublicAccessPreventionEnforced.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setPublicAccessPreventionEnforced.js,samples/README.md) | +| Set Public Access Prevention Inherited | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setPublicAccessPreventionInherited.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setPublicAccessPreventionInherited.js,samples/README.md) | +| Set RPO Async Turbo | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setRPOAsyncTurbo.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setRPOAsyncTurbo.js,samples/README.md) | +| Set RPO Default | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setRPODefault.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setRPODefault.js,samples/README.md) | +| Set Retention Policy | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setRetentionPolicy.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setRetentionPolicy.js,samples/README.md) | +| Set Soft Delete Policy | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setSoftDeletePolicy.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setSoftDeletePolicy.js,samples/README.md) | +| Set Temporary Hold | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setTemporaryHold.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setTemporaryHold.js,samples/README.md) | +| Stream File Download | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/streamFileDownload.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/streamFileDownload.js,samples/README.md) | +| Stream File Upload | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/streamFileUpload.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/streamFileUpload.js,samples/README.md) | +| Upload a directory to a bucket. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadDirectory.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/uploadDirectory.js,samples/README.md) | +| Upload Directory With Transfer Manager | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadDirectoryWithTransferManager.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/uploadDirectoryWithTransferManager.js,samples/README.md) | +| Upload Encrypted File | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadEncryptedFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/uploadEncryptedFile.js,samples/README.md) | +| Upload File | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/uploadFile.js,samples/README.md) | +| Upload a File in Chunks With Transfer Manager | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadFileInChunksWithTransferManager.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/uploadFileInChunksWithTransferManager.js,samples/README.md) | +| Upload File With Kms Key | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadFileWithKmsKey.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/uploadFileWithKmsKey.js,samples/README.md) | +| Upload From Memory | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadFromMemory.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/uploadFromMemory.js,samples/README.md) | +| Upload Many Files With Transfer Manager | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadManyFilesWithTransferManager.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/uploadManyFilesWithTransferManager.js,samples/README.md) | +| Upload Without Authentication | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadWithoutAuthentication.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/uploadWithoutAuthentication.js,samples/README.md) | +| Upload Without Authentication Signed Url | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadWithoutAuthenticationSignedUrl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/uploadWithoutAuthenticationSignedUrl.js,samples/README.md) | +| View Bucket Iam Members | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/viewBucketIamMembers.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/viewBucketIamMembers.js,samples/README.md) | + + + +The [Google Cloud Storage Node.js Client API Reference][client-docs] documentation +also contains samples. + +## Supported Node.js Versions + +Our client libraries follow the [Node.js release schedule](https://github.com/nodejs/release#release-schedule). +Libraries are compatible with all current _active_ and _maintenance_ versions of +Node.js. +If you are using an end-of-life version of Node.js, we recommend that you update +as soon as possible to an actively supported LTS version. + +Google's client libraries support legacy versions of Node.js runtimes on a +best-efforts basis with the following warnings: + +* Legacy versions are not tested in continuous integration. +* Some security patches and features cannot be backported. +* Dependencies cannot be kept up-to-date. + +Client libraries targeting some end-of-life versions of Node.js are available, and +can be installed through npm [dist-tags](https://docs.npmjs.com/cli/dist-tag). +The dist-tags follow the naming convention `legacy-(version)`. +For example, `npm install @google-cloud/storage@legacy-8` installs client libraries +for versions compatible with Node.js 8. + +## Versioning + +This library follows [Semantic Versioning](http://semver.org/). + + + +This library is considered to be **stable**. The code surface will not change in backwards-incompatible ways +unless absolutely necessary (e.g. because of critical security issues) or with +an extensive deprecation period. Issues and requests against **stable** libraries +are addressed with the highest priority. + + + + + + +More Information: [Google Cloud Platform Launch Stages][launch_stages] + +[launch_stages]: https://cloud.google.com/terms/launch-stages + +## Contributing + +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/nodejs-storage/blob/main/CONTRIBUTING.md). + +Please note that this `README.md`, the `samples/README.md`, +and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) +are generated from a central template. To edit one of these files, make an edit +to its templates in +[directory](https://github.com/googleapis/synthtool). + +## License + +Apache Version 2.0 + +See [LICENSE](https://github.com/googleapis/nodejs-storage/blob/main/LICENSE) + +[client-docs]: https://cloud.google.com/nodejs/docs/reference/storage/latest +[product-docs]: https://cloud.google.com/storage +[shell_img]: https://gstatic.com/cloudssh/images/open-btn.png +[projects]: https://console.cloud.google.com/project +[billing]: https://support.google.com/cloud/answer/6293499#enable-billing +[enable_api]: https://console.cloud.google.com/flows/enableapi?apiid=storage-api.googleapis.com +[auth]: https://cloud.google.com/docs/authentication/external/set-up-adc-local diff --git a/node_modules/@google-cloud/storage/build/cjs/package.json b/node_modules/@google-cloud/storage/build/cjs/package.json new file mode 100644 index 0000000..6a0d2ef --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/build/cjs/src/acl.d.ts b/node_modules/@google-cloud/storage/build/cjs/src/acl.d.ts new file mode 100644 index 0000000..d8f31a2 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/acl.d.ts @@ -0,0 +1,165 @@ +import { BodyResponseCallback, DecorateRequestOptions, BaseMetadata } from './nodejs-common/index.js'; +export interface AclOptions { + pathPrefix: string; + request: (reqOpts: DecorateRequestOptions, callback: BodyResponseCallback) => void; +} +export type GetAclResponse = [ + AccessControlObject | AccessControlObject[], + AclMetadata +]; +export interface GetAclCallback { + (err: Error | null, acl?: AccessControlObject | AccessControlObject[] | null, apiResponse?: AclMetadata): void; +} +export interface GetAclOptions { + entity: string; + generation?: number; + userProject?: string; +} +export interface UpdateAclOptions { + entity: string; + role: string; + generation?: number; + userProject?: string; +} +export type UpdateAclResponse = [AccessControlObject, AclMetadata]; +export interface UpdateAclCallback { + (err: Error | null, acl?: AccessControlObject | null, apiResponse?: AclMetadata): void; +} +export interface AddAclOptions { + entity: string; + role: string; + generation?: number; + userProject?: string; +} +export type AddAclResponse = [AccessControlObject, AclMetadata]; +export interface AddAclCallback { + (err: Error | null, acl?: AccessControlObject | null, apiResponse?: AclMetadata): void; +} +export type RemoveAclResponse = [AclMetadata]; +export interface RemoveAclCallback { + (err: Error | null, apiResponse?: AclMetadata): void; +} +export interface RemoveAclOptions { + entity: string; + generation?: number; + userProject?: string; +} +export interface AccessControlObject { + entity: string; + role: string; + projectTeam: string; +} +export interface AclMetadata extends BaseMetadata { + bucket?: string; + domain?: string; + entity?: string; + entityId?: string; + generation?: string; + object?: string; + projectTeam?: { + projectNumber?: string; + team?: 'editors' | 'owners' | 'viewers'; + }; + role?: 'OWNER' | 'READER' | 'WRITER' | 'FULL_CONTROL'; + [key: string]: unknown; +} +/** + * Attach functionality to a {@link Storage.acl} instance. This will add an + * object for each role group (owners, readers, and writers), with each object + * containing methods to add or delete a type of entity. + * + * As an example, here are a few methods that are created. + * + * myBucket.acl.readers.deleteGroup('groupId', function(err) {}); + * + * myBucket.acl.owners.addUser('email@example.com', function(err, acl) {}); + * + * myBucket.acl.writers.addDomain('example.com', function(err, acl) {}); + * + * @private + */ +declare class AclRoleAccessorMethods { + private static accessMethods; + private static entities; + private static roles; + owners: {}; + readers: {}; + writers: {}; + constructor(); + _assignAccessMethods(role: string): void; +} +/** + * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share objects with other + * users and allow other users to access your buckets and objects. + * + * An ACL consists of one or more entries, where each entry grants permissions + * to an entity. Permissions define the actions that can be performed against an + * object or bucket (for example, `READ` or `WRITE`); the entity defines who the + * permission applies to (for example, a specific user or group of users). + * + * Where an `entity` value is accepted, we follow the format the Cloud Storage + * API expects. + * + * Refer to + * https://cloud.google.com/storage/docs/json_api/v1/defaultObjectAccessControls + * for the most up-to-date values. + * + * - `user-userId` + * - `user-email` + * - `group-groupId` + * - `group-email` + * - `domain-domain` + * - `project-team-projectId` + * - `allUsers` + * - `allAuthenticatedUsers` + * + * Examples: + * + * - The user "liz@example.com" would be `user-liz@example.com`. + * - The group "example@googlegroups.com" would be + * `group-example@googlegroups.com`. + * - To refer to all members of the Google Apps for Business domain + * "example.com", the entity would be `domain-example.com`. + * + * For more detailed information, see + * {@link http://goo.gl/6qBBPO| About Access Control Lists}. + * + * @constructor Acl + * @mixin + * @param {object} options Configuration options. + */ +declare class Acl extends AclRoleAccessorMethods { + default: Acl; + pathPrefix: string; + request_: (reqOpts: DecorateRequestOptions, callback: BodyResponseCallback) => void; + constructor(options: AclOptions); + add(options: AddAclOptions): Promise; + add(options: AddAclOptions, callback: AddAclCallback): void; + delete(options: RemoveAclOptions): Promise; + delete(options: RemoveAclOptions, callback: RemoveAclCallback): void; + get(options?: GetAclOptions): Promise; + get(options: GetAclOptions, callback: GetAclCallback): void; + get(callback: GetAclCallback): void; + update(options: UpdateAclOptions): Promise; + update(options: UpdateAclOptions, callback: UpdateAclCallback): void; + /** + * Transform API responses to a consistent object format. + * + * @private + */ + makeAclObject_(accessControlObject: AccessControlObject): AccessControlObject; + /** + * Patch requests up to the bucket's request object. + * + * @private + * + * @param {string} method Action. + * @param {string} path Request path. + * @param {*} query Request query object. + * @param {*} body Request body contents. + * @param {function} callback Callback function. + */ + request(reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void; +} +export { Acl, AclRoleAccessorMethods }; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/acl.js b/node_modules/@google-cloud/storage/build/cjs/src/acl.js new file mode 100644 index 0000000..194fb3b --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/acl.js @@ -0,0 +1,718 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AclRoleAccessorMethods = exports.Acl = void 0; +const promisify_1 = require("@google-cloud/promisify"); +/** + * Attach functionality to a {@link Storage.acl} instance. This will add an + * object for each role group (owners, readers, and writers), with each object + * containing methods to add or delete a type of entity. + * + * As an example, here are a few methods that are created. + * + * myBucket.acl.readers.deleteGroup('groupId', function(err) {}); + * + * myBucket.acl.owners.addUser('email@example.com', function(err, acl) {}); + * + * myBucket.acl.writers.addDomain('example.com', function(err, acl) {}); + * + * @private + */ +class AclRoleAccessorMethods { + constructor() { + this.owners = {}; + this.readers = {}; + this.writers = {}; + /** + * An object of convenience methods to add or delete owner ACL permissions + * for a given entity. + * + * The supported methods include: + * + * - `myFile.acl.owners.addAllAuthenticatedUsers` + * - `myFile.acl.owners.deleteAllAuthenticatedUsers` + * - `myFile.acl.owners.addAllUsers` + * - `myFile.acl.owners.deleteAllUsers` + * - `myFile.acl.owners.addDomain` + * - `myFile.acl.owners.deleteDomain` + * - `myFile.acl.owners.addGroup` + * - `myFile.acl.owners.deleteGroup` + * - `myFile.acl.owners.addProject` + * - `myFile.acl.owners.deleteProject` + * - `myFile.acl.owners.addUser` + * - `myFile.acl.owners.deleteUser` + * + * @name Acl#owners + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * //- + * // Add a user as an owner of a file. + * //- + * const myBucket = gcs.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * myFile.acl.owners.addUser('email@example.com', function(err, aclObject) + * {}); + * + * //- + * // For reference, the above command is the same as running the following. + * //- + * myFile.acl.add({ + * entity: 'user-email@example.com', + * role: gcs.acl.OWNER_ROLE + * }, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myFile.acl.owners.addUser('email@example.com').then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + this.owners = {}; + /** + * An object of convenience methods to add or delete reader ACL permissions + * for a given entity. + * + * The supported methods include: + * + * - `myFile.acl.readers.addAllAuthenticatedUsers` + * - `myFile.acl.readers.deleteAllAuthenticatedUsers` + * - `myFile.acl.readers.addAllUsers` + * - `myFile.acl.readers.deleteAllUsers` + * - `myFile.acl.readers.addDomain` + * - `myFile.acl.readers.deleteDomain` + * - `myFile.acl.readers.addGroup` + * - `myFile.acl.readers.deleteGroup` + * - `myFile.acl.readers.addProject` + * - `myFile.acl.readers.deleteProject` + * - `myFile.acl.readers.addUser` + * - `myFile.acl.readers.deleteUser` + * + * @name Acl#readers + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * //- + * // Add a user as a reader of a file. + * //- + * myFile.acl.readers.addUser('email@example.com', function(err, aclObject) + * {}); + * + * //- + * // For reference, the above command is the same as running the following. + * //- + * myFile.acl.add({ + * entity: 'user-email@example.com', + * role: gcs.acl.READER_ROLE + * }, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myFile.acl.readers.addUser('email@example.com').then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + this.readers = {}; + /** + * An object of convenience methods to add or delete writer ACL permissions + * for a given entity. + * + * The supported methods include: + * + * - `myFile.acl.writers.addAllAuthenticatedUsers` + * - `myFile.acl.writers.deleteAllAuthenticatedUsers` + * - `myFile.acl.writers.addAllUsers` + * - `myFile.acl.writers.deleteAllUsers` + * - `myFile.acl.writers.addDomain` + * - `myFile.acl.writers.deleteDomain` + * - `myFile.acl.writers.addGroup` + * - `myFile.acl.writers.deleteGroup` + * - `myFile.acl.writers.addProject` + * - `myFile.acl.writers.deleteProject` + * - `myFile.acl.writers.addUser` + * - `myFile.acl.writers.deleteUser` + * + * @name Acl#writers + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * //- + * // Add a user as a writer of a file. + * //- + * myFile.acl.writers.addUser('email@example.com', function(err, aclObject) + * {}); + * + * //- + * // For reference, the above command is the same as running the following. + * //- + * myFile.acl.add({ + * entity: 'user-email@example.com', + * role: gcs.acl.WRITER_ROLE + * }, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myFile.acl.writers.addUser('email@example.com').then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + this.writers = {}; + AclRoleAccessorMethods.roles.forEach(this._assignAccessMethods.bind(this)); + } + _assignAccessMethods(role) { + const accessMethods = AclRoleAccessorMethods.accessMethods; + const entities = AclRoleAccessorMethods.entities; + const roleGroup = role.toLowerCase() + 's'; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this[roleGroup] = entities.reduce((acc, entity) => { + const isPrefix = entity.charAt(entity.length - 1) === '-'; + accessMethods.forEach(accessMethod => { + let method = accessMethod + entity[0].toUpperCase() + entity.substring(1); + if (isPrefix) { + method = method.replace('-', ''); + } + // Wrap the parent accessor method (e.g. `add` or `delete`) to avoid the + // more complex API of specifying an `entity` and `role`. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + acc[method] = (entityId, options, callback) => { + let apiEntity; + if (typeof options === 'function') { + callback = options; + options = {}; + } + if (isPrefix) { + apiEntity = entity + entityId; + } + else { + // If the entity is not a prefix, it is a special entity group + // that does not require further details. The accessor methods + // only accept a callback. + apiEntity = entity; + callback = entityId; + } + options = Object.assign({ + entity: apiEntity, + role, + }, options); + const args = [options]; + if (typeof callback === 'function') { + args.push(callback); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return this[accessMethod].apply(this, args); + }; + }); + return acc; + }, {}); + } +} +exports.AclRoleAccessorMethods = AclRoleAccessorMethods; +AclRoleAccessorMethods.accessMethods = ['add', 'delete']; +AclRoleAccessorMethods.entities = [ + // Special entity groups that do not require further specification. + 'allAuthenticatedUsers', + 'allUsers', + // Entity groups that require specification, e.g. `user-email@example.com`. + 'domain-', + 'group-', + 'project-', + 'user-', +]; +AclRoleAccessorMethods.roles = ['OWNER', 'READER', 'WRITER']; +/** + * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share objects with other + * users and allow other users to access your buckets and objects. + * + * An ACL consists of one or more entries, where each entry grants permissions + * to an entity. Permissions define the actions that can be performed against an + * object or bucket (for example, `READ` or `WRITE`); the entity defines who the + * permission applies to (for example, a specific user or group of users). + * + * Where an `entity` value is accepted, we follow the format the Cloud Storage + * API expects. + * + * Refer to + * https://cloud.google.com/storage/docs/json_api/v1/defaultObjectAccessControls + * for the most up-to-date values. + * + * - `user-userId` + * - `user-email` + * - `group-groupId` + * - `group-email` + * - `domain-domain` + * - `project-team-projectId` + * - `allUsers` + * - `allAuthenticatedUsers` + * + * Examples: + * + * - The user "liz@example.com" would be `user-liz@example.com`. + * - The group "example@googlegroups.com" would be + * `group-example@googlegroups.com`. + * - To refer to all members of the Google Apps for Business domain + * "example.com", the entity would be `domain-example.com`. + * + * For more detailed information, see + * {@link http://goo.gl/6qBBPO| About Access Control Lists}. + * + * @constructor Acl + * @mixin + * @param {object} options Configuration options. + */ +class Acl extends AclRoleAccessorMethods { + constructor(options) { + super(); + this.pathPrefix = options.pathPrefix; + this.request_ = options.request; + } + /** + * @typedef {array} AddAclResponse + * @property {object} 0 The Acl Objects. + * @property {object} 1 The full API response. + */ + /** + * @callback AddAclCallback + * @param {?Error} err Request error, if any. + * @param {object} acl The Acl Objects. + * @param {object} apiResponse The full API response. + */ + /** + * Add access controls on a {@link Bucket} or {@link File}. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/insert| BucketAccessControls: insert API Documentation} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/insert| ObjectAccessControls: insert API Documentation} + * + * @param {object} options Configuration options. + * @param {string} options.entity Whose permissions will be added. + * @param {string} options.role Permissions allowed for the defined entity. + * See {@link https://cloud.google.com/storage/docs/access-control Access + * Control}. + * @param {number} [options.generation] **File Objects Only** Select a specific + * revision of this file (as opposed to the latest version, the default). + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {AddAclCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * const options = { + * entity: 'user-useremail@example.com', + * role: gcs.acl.OWNER_ROLE + * }; + * + * myBucket.acl.add(options, function(err, aclObject, apiResponse) {}); + * + * //- + * // For file ACL operations, you can also specify a `generation` property. + * // Here is how you would grant ownership permissions to a user on a + * specific + * // revision of a file. + * //- + * myFile.acl.add({ + * entity: 'user-useremail@example.com', + * role: gcs.acl.OWNER_ROLE, + * generation: 1 + * }, function(err, aclObject, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myBucket.acl.add(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/acl.js + * region_tag:storage_add_file_owner + * Example of adding an owner to a file: + * + * @example include:samples/acl.js + * region_tag:storage_add_bucket_owner + * Example of adding an owner to a bucket: + * + * @example include:samples/acl.js + * region_tag:storage_add_bucket_default_owner + * Example of adding a default owner to a bucket: + */ + add(options, callback) { + const query = {}; + if (options.generation) { + query.generation = options.generation; + } + if (options.userProject) { + query.userProject = options.userProject; + } + this.request({ + method: 'POST', + uri: '', + qs: query, + maxRetries: 0, //explicitly set this value since this is a non-idempotent function + json: { + entity: options.entity, + role: options.role.toUpperCase(), + }, + }, (err, resp) => { + if (err) { + callback(err, null, resp); + return; + } + callback(null, this.makeAclObject_(resp), resp); + }); + } + /** + * @typedef {array} RemoveAclResponse + * @property {object} 0 The full API response. + */ + /** + * @callback RemoveAclCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Delete access controls on a {@link Bucket} or {@link File}. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/delete| BucketAccessControls: delete API Documentation} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/delete| ObjectAccessControls: delete API Documentation} + * + * @param {object} options Configuration object. + * @param {string} options.entity Whose permissions will be revoked. + * @param {int} [options.generation] **File Objects Only** Select a specific + * revision of this file (as opposed to the latest version, the default). + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {RemoveAclCallback} callback The callback function. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * myBucket.acl.delete({ + * entity: 'user-useremail@example.com' + * }, function(err, apiResponse) {}); + * + * //- + * // For file ACL operations, you can also specify a `generation` property. + * //- + * myFile.acl.delete({ + * entity: 'user-useremail@example.com', + * generation: 1 + * }, function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myFile.acl.delete().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example include:samples/acl.js + * region_tag:storage_remove_bucket_owner + * Example of removing an owner from a bucket: + * + * @example include:samples/acl.js + * region_tag:storage_remove_bucket_default_owner + * Example of removing a default owner from a bucket: + * + * @example include:samples/acl.js + * region_tag:storage_remove_file_owner + * Example of removing an owner from a bucket: + */ + delete(options, callback) { + const query = {}; + if (options.generation) { + query.generation = options.generation; + } + if (options.userProject) { + query.userProject = options.userProject; + } + this.request({ + method: 'DELETE', + uri: '/' + encodeURIComponent(options.entity), + qs: query, + }, (err, resp) => { + callback(err, resp); + }); + } + /** + * @typedef {array} GetAclResponse + * @property {object|object[]} 0 Single or array of Acl Objects. + * @property {object} 1 The full API response. + */ + /** + * @callback GetAclCallback + * @param {?Error} err Request error, if any. + * @param {object|object[]} acl Single or array of Acl Objects. + * @param {object} apiResponse The full API response. + */ + /** + * Get access controls on a {@link Bucket} or {@link File}. If + * an entity is omitted, you will receive an array of all applicable access + * controls. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/get| BucketAccessControls: get API Documentation} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/get| ObjectAccessControls: get API Documentation} + * + * @param {object|function} [options] Configuration options. If you want to + * receive a list of all access controls, pass the callback function as + * the only argument. + * @param {string} options.entity Whose permissions will be fetched. + * @param {number} [options.generation] **File Objects Only** Select a specific + * revision of this file (as opposed to the latest version, the default). + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetAclCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * myBucket.acl.get({ + * entity: 'user-useremail@example.com' + * }, function(err, aclObject, apiResponse) {}); + * + * //- + * // Get all access controls. + * //- + * myBucket.acl.get(function(err, aclObjects, apiResponse) { + * // aclObjects = [ + * // { + * // entity: 'user-useremail@example.com', + * // role: 'owner' + * // } + * // ] + * }); + * + * //- + * // For file ACL operations, you can also specify a `generation` property. + * //- + * myFile.acl.get({ + * entity: 'user-useremail@example.com', + * generation: 1 + * }, function(err, aclObject, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myBucket.acl.get().then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/acl.js + * region_tag:storage_print_file_acl + * Example of printing a file's ACL: + * + * @example include:samples/acl.js + * region_tag:storage_print_file_acl_for_user + * Example of printing a file's ACL for a specific user: + * + * @example include:samples/acl.js + * region_tag:storage_print_bucket_acl + * Example of printing a bucket's ACL: + * + * @example include:samples/acl.js + * region_tag:storage_print_bucket_acl_for_user + * Example of printing a bucket's ACL for a specific user: + */ + get(optionsOrCallback, cb) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : null; + const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb; + let path = ''; + const query = {}; + if (options) { + path = '/' + encodeURIComponent(options.entity); + if (options.generation) { + query.generation = options.generation; + } + if (options.userProject) { + query.userProject = options.userProject; + } + } + this.request({ + uri: path, + qs: query, + }, (err, resp) => { + if (err) { + callback(err, null, resp); + return; + } + let results; + if (resp.items) { + results = resp.items.map(this.makeAclObject_); + } + else { + results = this.makeAclObject_(resp); + } + callback(null, results, resp); + }); + } + /** + * @typedef {array} UpdateAclResponse + * @property {object} 0 The updated Acl Objects. + * @property {object} 1 The full API response. + */ + /** + * @callback UpdateAclCallback + * @param {?Error} err Request error, if any. + * @param {object} acl The updated Acl Objects. + * @param {object} apiResponse The full API response. + */ + /** + * Update access controls on a {@link Bucket} or {@link File}. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/update| BucketAccessControls: update API Documentation} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/update| ObjectAccessControls: update API Documentation} + * + * @param {object} options Configuration options. + * @param {string} options.entity Whose permissions will be updated. + * @param {string} options.role Permissions allowed for the defined entity. + * See {@link Storage.acl}. + * @param {number} [options.generation] **File Objects Only** Select a specific + * revision of this file (as opposed to the latest version, the default). + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {UpdateAclCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * const options = { + * entity: 'user-useremail@example.com', + * role: gcs.acl.WRITER_ROLE + * }; + * + * myBucket.acl.update(options, function(err, aclObject, apiResponse) {}); + * + * //- + * // For file ACL operations, you can also specify a `generation` property. + * //- + * myFile.acl.update({ + * entity: 'user-useremail@example.com', + * role: gcs.acl.WRITER_ROLE, + * generation: 1 + * }, function(err, aclObject, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myFile.acl.update(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + update(options, callback) { + const query = {}; + if (options.generation) { + query.generation = options.generation; + } + if (options.userProject) { + query.userProject = options.userProject; + } + this.request({ + method: 'PUT', + uri: '/' + encodeURIComponent(options.entity), + qs: query, + json: { + role: options.role.toUpperCase(), + }, + }, (err, resp) => { + if (err) { + callback(err, null, resp); + return; + } + callback(null, this.makeAclObject_(resp), resp); + }); + } + /** + * Transform API responses to a consistent object format. + * + * @private + */ + makeAclObject_(accessControlObject) { + const obj = { + entity: accessControlObject.entity, + role: accessControlObject.role, + }; + if (accessControlObject.projectTeam) { + obj.projectTeam = accessControlObject.projectTeam; + } + return obj; + } + /** + * Patch requests up to the bucket's request object. + * + * @private + * + * @param {string} method Action. + * @param {string} path Request path. + * @param {*} query Request query object. + * @param {*} body Request body contents. + * @param {function} callback Callback function. + */ + request(reqOpts, callback) { + reqOpts.uri = this.pathPrefix + reqOpts.uri; + this.request_(reqOpts, callback); + } +} +exports.Acl = Acl; +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +(0, promisify_1.promisifyAll)(Acl, { + exclude: ['request'], +}); diff --git a/node_modules/@google-cloud/storage/build/cjs/src/bucket.d.ts b/node_modules/@google-cloud/storage/build/cjs/src/bucket.d.ts new file mode 100644 index 0000000..c9b57ea --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/bucket.d.ts @@ -0,0 +1,830 @@ +import { ApiError, BodyResponseCallback, DecorateRequestOptions, DeleteCallback, ExistsCallback, GetConfig, MetadataCallback, ServiceObject, SetMetadataResponse } from './nodejs-common/index.js'; +import { RequestResponse } from './nodejs-common/service-object.js'; +import * as http from 'http'; +import { Acl, AclMetadata } from './acl.js'; +import { Channel } from './channel.js'; +import { File, FileOptions, CreateResumableUploadOptions, CreateWriteStreamOptions } from './file.js'; +import { Iam } from './iam.js'; +import { Notification } from './notification.js'; +import { Storage, Cors, PreconditionOptions, BucketOptions } from './storage.js'; +import { GetSignedUrlResponse, GetSignedUrlCallback, SignerGetSignedUrlConfig, URLSigner, Query } from './signer.js'; +import { Readable } from 'stream'; +import { CRC32CValidatorGenerator } from './crc32c.js'; +import { URL } from 'url'; +import { BaseMetadata, SetMetadataOptions } from './nodejs-common/service-object.js'; +export type GetFilesResponse = [ + File[], + (GetFilesOptions | {}) & Partial>, + unknown +]; +export interface GetFilesCallback { + (err: Error | null, files?: File[], nextQuery?: {}, apiResponse?: unknown): void; +} +interface WatchAllOptions { + delimiter?: string; + maxResults?: number; + pageToken?: string; + prefix?: string; + projection?: string; + userProject?: string; + versions?: boolean; +} +export interface AddLifecycleRuleOptions extends PreconditionOptions { + append?: boolean; +} +export interface LifecycleAction { + type: 'Delete' | 'SetStorageClass' | 'AbortIncompleteMultipartUpload'; + storageClass?: string; +} +export interface LifecycleCondition { + age?: number; + createdBefore?: Date | string; + customTimeBefore?: Date | string; + daysSinceCustomTime?: number; + daysSinceNoncurrentTime?: number; + isLive?: boolean; + matchesPrefix?: string[]; + matchesSuffix?: string[]; + matchesStorageClass?: string[]; + noncurrentTimeBefore?: Date | string; + numNewerVersions?: number; +} +export interface LifecycleRule { + action: LifecycleAction; + condition: LifecycleCondition; +} +export interface LifecycleCondition { + age?: number; + createdBefore?: Date | string; + customTimeBefore?: Date | string; + daysSinceCustomTime?: number; + daysSinceNoncurrentTime?: number; + isLive?: boolean; + matchesPrefix?: string[]; + matchesSuffix?: string[]; + matchesStorageClass?: string[]; + noncurrentTimeBefore?: Date | string; + numNewerVersions?: number; +} +export interface LifecycleRule { + action: LifecycleAction; + condition: LifecycleCondition; +} +export interface EnableLoggingOptions extends PreconditionOptions { + bucket?: string | Bucket; + prefix: string; +} +export interface GetFilesOptions { + autoPaginate?: boolean; + delimiter?: string; + endOffset?: string; + includeFoldersAsPrefixes?: boolean; + includeTrailingDelimiter?: boolean; + prefix?: string; + matchGlob?: string; + maxApiCalls?: number; + maxResults?: number; + pageToken?: string; + softDeleted?: boolean; + startOffset?: string; + userProject?: string; + versions?: boolean; + fields?: string; +} +export interface CombineOptions extends PreconditionOptions { + kmsKeyName?: string; + userProject?: string; +} +export interface CombineCallback { + (err: Error | null, newFile: File | null, apiResponse: unknown): void; +} +export type CombineResponse = [File, unknown]; +export interface CreateChannelConfig extends WatchAllOptions { + address: string; +} +export interface CreateChannelOptions { + userProject?: string; +} +export type CreateChannelResponse = [Channel, unknown]; +export interface CreateChannelCallback { + (err: Error | null, channel: Channel | null, apiResponse: unknown): void; +} +export interface CreateNotificationOptions { + customAttributes?: { + [key: string]: string; + }; + eventTypes?: string[]; + objectNamePrefix?: string; + payloadFormat?: string; + userProject?: string; +} +export interface CreateNotificationCallback { + (err: Error | null, notification: Notification | null, apiResponse: unknown): void; +} +export type CreateNotificationResponse = [Notification, unknown]; +export interface DeleteBucketOptions { + ignoreNotFound?: boolean; + userProject?: string; +} +export type DeleteBucketResponse = [unknown]; +export interface DeleteBucketCallback extends DeleteCallback { + (err: Error | null, apiResponse: unknown): void; +} +export interface DeleteFilesOptions extends GetFilesOptions, PreconditionOptions { + force?: boolean; +} +export interface DeleteFilesCallback { + (err: Error | Error[] | null, apiResponse?: object): void; +} +export type DeleteLabelsResponse = [unknown]; +export type DeleteLabelsCallback = SetLabelsCallback; +export type DeleteLabelsOptions = PreconditionOptions; +export type DisableRequesterPaysOptions = PreconditionOptions; +export type DisableRequesterPaysResponse = [unknown]; +export interface DisableRequesterPaysCallback { + (err?: Error | null, apiResponse?: object): void; +} +export type EnableRequesterPaysResponse = [unknown]; +export interface EnableRequesterPaysCallback { + (err?: Error | null, apiResponse?: unknown): void; +} +export type EnableRequesterPaysOptions = PreconditionOptions; +export interface BucketExistsOptions extends GetConfig { + userProject?: string; +} +export type BucketExistsResponse = [boolean]; +export type BucketExistsCallback = ExistsCallback; +export interface GetBucketOptions extends GetConfig { + userProject?: string; +} +export type GetBucketResponse = [Bucket, unknown]; +export interface GetBucketCallback { + (err: ApiError | null, bucket: Bucket | null, apiResponse: unknown): void; +} +export interface GetLabelsOptions { + userProject?: string; +} +export type GetLabelsResponse = [unknown]; +export interface GetLabelsCallback { + (err: Error | null, labels: object | null): void; +} +export interface RestoreOptions { + generation: string; + projection?: 'full' | 'noAcl'; +} +export interface BucketMetadata extends BaseMetadata { + acl?: AclMetadata[] | null; + autoclass?: { + enabled?: boolean; + toggleTime?: string; + terminalStorageClass?: string; + terminalStorageClassUpdateTime?: string; + }; + billing?: { + requesterPays?: boolean; + }; + cors?: Cors[]; + customPlacementConfig?: { + dataLocations?: string[]; + }; + defaultEventBasedHold?: boolean; + defaultObjectAcl?: AclMetadata[]; + encryption?: { + defaultKmsKeyName?: string; + } | null; + hierarchicalNamespace?: { + enabled?: boolean; + }; + iamConfiguration?: { + publicAccessPrevention?: string; + uniformBucketLevelAccess?: { + enabled?: boolean; + lockedTime?: string; + }; + }; + labels?: { + [key: string]: string | null; + }; + lifecycle?: { + rule?: LifecycleRule[]; + } | null; + location?: string; + locationType?: string; + logging?: { + logBucket?: string; + logObjectPrefix?: string; + }; + generation?: string; + metageneration?: string; + name?: string; + objectRetention?: { + mode?: string; + }; + owner?: { + entity?: string; + entityId?: string; + }; + projectNumber?: string | number; + retentionPolicy?: { + effectiveTime?: string; + isLocked?: boolean; + retentionPeriod?: string | number; + } | null; + rpo?: string; + softDeleteTime?: string; + hardDeleteTime?: string; + softDeletePolicy?: { + retentionDurationSeconds?: string | number; + readonly effectiveTime?: string; + }; + storageClass?: string; + timeCreated?: string; + updated?: string; + versioning?: { + enabled?: boolean; + }; + website?: { + mainPageSuffix?: string; + notFoundPage?: string; + }; +} +export type GetBucketMetadataResponse = [BucketMetadata, unknown]; +export interface GetBucketMetadataCallback { + (err: ApiError | null, metadata: BucketMetadata | null, apiResponse: unknown): void; +} +export interface GetBucketMetadataOptions { + userProject?: string; +} +export interface GetBucketSignedUrlConfig extends Pick { + action: 'list'; + version?: 'v2' | 'v4'; + cname?: string; + virtualHostedStyle?: boolean; + expires: string | number | Date; + extensionHeaders?: http.OutgoingHttpHeaders; + queryParams?: Query; +} +export declare enum BucketActionToHTTPMethod { + list = "GET" +} +export declare enum AvailableServiceObjectMethods { + setMetadata = 0, + delete = 1 +} +export interface GetNotificationsOptions { + userProject?: string; +} +export interface GetNotificationsCallback { + (err: Error | null, notifications: Notification[] | null, apiResponse: unknown): void; +} +export type GetNotificationsResponse = [Notification[], unknown]; +export interface MakeBucketPrivateOptions { + includeFiles?: boolean; + force?: boolean; + metadata?: BucketMetadata; + userProject?: string; + preconditionOpts?: PreconditionOptions; +} +export type MakeBucketPrivateResponse = [File[]]; +export interface MakeBucketPrivateCallback { + (err?: Error | null, files?: File[]): void; +} +export interface MakeBucketPublicOptions { + includeFiles?: boolean; + force?: boolean; +} +export interface MakeBucketPublicCallback { + (err?: Error | null, files?: File[]): void; +} +export type MakeBucketPublicResponse = [File[]]; +export interface SetBucketMetadataOptions extends PreconditionOptions { + userProject?: string; +} +export type SetBucketMetadataResponse = [BucketMetadata]; +export interface SetBucketMetadataCallback { + (err?: Error | null, metadata?: BucketMetadata): void; +} +export interface BucketLockCallback { + (err?: Error | null, apiResponse?: unknown): void; +} +export type BucketLockResponse = [unknown]; +export interface Labels { + [key: string]: string; +} +export interface SetLabelsOptions extends PreconditionOptions { + userProject?: string; +} +export type SetLabelsResponse = [unknown]; +export interface SetLabelsCallback { + (err?: Error | null, metadata?: unknown): void; +} +export interface SetBucketStorageClassOptions extends PreconditionOptions { + userProject?: string; +} +export interface SetBucketStorageClassCallback { + (err?: Error | null): void; +} +export type UploadResponse = [File, unknown]; +export interface UploadCallback { + (err: Error | null, file?: File | null, apiResponse?: unknown): void; +} +export interface UploadOptions extends CreateResumableUploadOptions, CreateWriteStreamOptions { + destination?: string | File; + encryptionKey?: string | Buffer; + kmsKeyName?: string; + onUploadProgress?: (progressEvent: any) => void; +} +export interface MakeAllFilesPublicPrivateOptions { + force?: boolean; + private?: boolean; + public?: boolean; + userProject?: string; +} +interface MakeAllFilesPublicPrivateCallback { + (err?: Error | Error[] | null, files?: File[]): void; +} +type MakeAllFilesPublicPrivateResponse = [File[]]; +export declare enum BucketExceptionMessages { + PROVIDE_SOURCE_FILE = "You must provide at least one source file.", + DESTINATION_FILE_NOT_SPECIFIED = "A destination file must be specified.", + CHANNEL_ID_REQUIRED = "An ID is required to create a channel.", + TOPIC_NAME_REQUIRED = "A valid topic name is required.", + CONFIGURATION_OBJECT_PREFIX_REQUIRED = "A configuration object with a prefix is required.", + SPECIFY_FILE_NAME = "A file name must be specified.", + METAGENERATION_NOT_PROVIDED = "A metageneration must be provided.", + SUPPLY_NOTIFICATION_ID = "You must supply a notification ID." +} +/** + * @callback Crc32cGeneratorToStringCallback + * A method returning the CRC32C as a base64-encoded string. + * + * @returns {string} + * + * @example + * Hashing the string 'data' should return 'rth90Q==' + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.toString(); // 'rth90Q==' + * ``` + **/ +/** + * @callback Crc32cGeneratorValidateCallback + * A method validating a base64-encoded CRC32C string. + * + * @param {string} [value] base64-encoded CRC32C string to validate + * @returns {boolean} + * + * @example + * Should return `true` if the value matches, `false` otherwise + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.validate('DkjKuA=='); // false + * crc32c.validate('rth90Q=='); // true + * ``` + **/ +/** + * @callback Crc32cGeneratorUpdateCallback + * A method for passing `Buffer`s for CRC32C generation. + * + * @param {Buffer} [data] data to update CRC32C value with + * @returns {undefined} + * + * @example + * Hashing buffers from 'some ' and 'text\n' + * + * ```js + * const buffer1 = Buffer.from('some '); + * crc32c.update(buffer1); + * + * const buffer2 = Buffer.from('text\n'); + * crc32c.update(buffer2); + * + * crc32c.toString(); // 'DkjKuA==' + * ``` + **/ +/** + * @typedef {object} CRC32CValidator + * @property {Crc32cGeneratorToStringCallback} + * @property {Crc32cGeneratorValidateCallback} + * @property {Crc32cGeneratorUpdateCallback} + */ +/** + * A function that generates a CRC32C Validator. Defaults to {@link CRC32C} + * + * @name Bucket#crc32cGenerator + * @type {CRC32CValidator} + */ +/** + * Get and set IAM policies for your bucket. + * + * @name Bucket#iam + * @mixes Iam + * + * See {@link https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management| Cloud Storage IAM Management} + * See {@link https://cloud.google.com/iam/docs/granting-changing-revoking-access| Granting, Changing, and Revoking Access} + * See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Get the IAM policy for your bucket. + * //- + * bucket.iam.getPolicy(function(err, policy) { + * console.log(policy); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.iam.getPolicy().then(function(data) { + * const policy = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/iam.js + * region_tag:storage_view_bucket_iam_members + * Example of retrieving a bucket's IAM policy: + * + * @example include:samples/iam.js + * region_tag:storage_add_bucket_iam_member + * Example of adding to a bucket's IAM policy: + * + * @example include:samples/iam.js + * region_tag:storage_remove_bucket_iam_member + * Example of removing from a bucket's IAM policy: + */ +/** + * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share objects with other + * users and allow other users to access your buckets and objects. + * + * An ACL consists of one or more entries, where each entry grants permissions + * to an entity. Permissions define the actions that can be performed against + * an object or bucket (for example, `READ` or `WRITE`); the entity defines + * who the permission applies to (for example, a specific user or group of + * users). + * + * The `acl` object on a Bucket instance provides methods to get you a list of + * the ACLs defined on your bucket, as well as set, update, and delete them. + * + * Buckets also have + * {@link https://cloud.google.com/storage/docs/access-control/lists#default| default ACLs} + * for all created files. Default ACLs specify permissions that all new + * objects added to the bucket will inherit by default. You can add, delete, + * get, and update entities and permissions for these as well with + * {@link Bucket#acl.default}. + * + * See {@link http://goo.gl/6qBBPO| About Access Control Lists} + * See {@link https://cloud.google.com/storage/docs/access-control/lists#default| Default ACLs} + * + * @name Bucket#acl + * @mixes Acl + * @property {Acl} default Cloud Storage Buckets have + * {@link https://cloud.google.com/storage/docs/access-control/lists#default| default ACLs} + * for all created files. You can add, delete, get, and update entities and + * permissions for these as well. The method signatures and examples are all + * the same, after only prefixing the method call with `default`. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // Make a bucket's contents publicly readable. + * //- + * const myBucket = storage.bucket('my-bucket'); + * + * const options = { + * entity: 'allUsers', + * role: storage.acl.READER_ROLE + * }; + * + * myBucket.acl.add(options, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myBucket.acl.add(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/acl.js + * region_tag:storage_print_bucket_acl + * Example of printing a bucket's ACL: + * + * @example include:samples/acl.js + * region_tag:storage_print_bucket_acl_for_user + * Example of printing a bucket's ACL for a specific user: + * + * @example include:samples/acl.js + * region_tag:storage_add_bucket_owner + * Example of adding an owner to a bucket: + * + * @example include:samples/acl.js + * region_tag:storage_remove_bucket_owner + * Example of removing an owner from a bucket: + * + * @example include:samples/acl.js + * region_tag:storage_add_bucket_default_owner + * Example of adding a default owner to a bucket: + * + * @example include:samples/acl.js + * region_tag:storage_remove_bucket_default_owner + * Example of removing a default owner from a bucket: + */ +/** + * The API-formatted resource description of the bucket. + * + * Note: This is not guaranteed to be up-to-date when accessed. To get the + * latest record, call the `getMetadata()` method. + * + * @name Bucket#metadata + * @type {object} + */ +/** + * The bucket's name. + * @name Bucket#name + * @type {string} + */ +/** + * Get {@link File} objects for the files currently in the bucket as a + * readable object stream. + * + * @method Bucket#getFilesStream + * @param {GetFilesOptions} [query] Query object for listing files. + * @returns {ReadableStream} A readable stream that emits {@link File} instances. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.getFilesStream() + * .on('error', console.error) + * .on('data', function(file) { + * // file is a File object. + * }) + * .on('end', function() { + * // All files retrieved. + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * bucket.getFilesStream() + * .on('data', function(file) { + * this.end(); + * }); + * + * //- + * // If you're filtering files with a delimiter, you should use + * // {@link Bucket#getFiles} and set `autoPaginate: false` in order to + * // preserve the `apiResponse` argument. + * //- + * const prefixes = []; + * + * function callback(err, files, nextQuery, apiResponse) { + * prefixes = prefixes.concat(apiResponse.prefixes); + * + * if (nextQuery) { + * bucket.getFiles(nextQuery, callback); + * } else { + * // prefixes = The finished array of prefixes. + * } + * } + * + * bucket.getFiles({ + * autoPaginate: false, + * delimiter: '/' + * }, callback); + * ``` + */ +/** + * Create a Bucket object to interact with a Cloud Storage bucket. + * + * @class + * @hideconstructor + * + * @param {Storage} storage A {@link Storage} instance. + * @param {string} name The name of the bucket. + * @param {object} [options] Configuration object. + * @param {string} [options.userProject] User project. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * ``` + */ +declare class Bucket extends ServiceObject { + name: string; + /** + * A reference to the {@link Storage} associated with this {@link Bucket} + * instance. + * @name Bucket#storage + * @type {Storage} + */ + storage: Storage; + /** + * A user project to apply to each request from this bucket. + * @name Bucket#userProject + * @type {string} + */ + userProject?: string; + acl: Acl; + iam: Iam; + crc32cGenerator: CRC32CValidatorGenerator; + getFilesStream(query?: GetFilesOptions): Readable; + signer?: URLSigner; + private instanceRetryValue?; + instancePreconditionOpts?: PreconditionOptions; + /** + * Indicates whether this Bucket object is a placeholder for an item + * that the API failed to retrieve (unreachable) due to partial failure. + * Consumers must check this flag before accessing other properties. + */ + unreachable: boolean; + constructor(storage: Storage, name: string, options?: BucketOptions); + /** + * The bucket's Cloud Storage URI (`gs://`) + * + * @example + * ```ts + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * // `gs://my-bucket` + * const href = bucket.cloudStorageURI.href; + * ``` + */ + get cloudStorageURI(): URL; + addLifecycleRule(rule: LifecycleRule | LifecycleRule[], options?: AddLifecycleRuleOptions): Promise; + addLifecycleRule(rule: LifecycleRule | LifecycleRule[], options: AddLifecycleRuleOptions, callback: SetBucketMetadataCallback): void; + addLifecycleRule(rule: LifecycleRule | LifecycleRule[], callback: SetBucketMetadataCallback): void; + combine(sources: string[] | File[], destination: string | File, options?: CombineOptions): Promise; + combine(sources: string[] | File[], destination: string | File, options: CombineOptions, callback: CombineCallback): void; + combine(sources: string[] | File[], destination: string | File, callback: CombineCallback): void; + createChannel(id: string, config: CreateChannelConfig, options?: CreateChannelOptions): Promise; + createChannel(id: string, config: CreateChannelConfig, callback: CreateChannelCallback): void; + createChannel(id: string, config: CreateChannelConfig, options: CreateChannelOptions, callback: CreateChannelCallback): void; + createNotification(topic: string, options?: CreateNotificationOptions): Promise; + createNotification(topic: string, options: CreateNotificationOptions, callback: CreateNotificationCallback): void; + createNotification(topic: string, callback: CreateNotificationCallback): void; + deleteFiles(query?: DeleteFilesOptions): Promise; + deleteFiles(callback: DeleteFilesCallback): void; + deleteFiles(query: DeleteFilesOptions, callback: DeleteFilesCallback): void; + deleteLabels(labels?: string | string[]): Promise; + deleteLabels(options: DeleteLabelsOptions): Promise; + deleteLabels(callback: DeleteLabelsCallback): void; + deleteLabels(labels: string | string[], options: DeleteLabelsOptions): Promise; + deleteLabels(labels: string | string[], callback: DeleteLabelsCallback): void; + deleteLabels(labels: string | string[], options: DeleteLabelsOptions, callback: DeleteLabelsCallback): void; + disableRequesterPays(options?: DisableRequesterPaysOptions): Promise; + disableRequesterPays(callback: DisableRequesterPaysCallback): void; + disableRequesterPays(options: DisableRequesterPaysOptions, callback: DisableRequesterPaysCallback): void; + enableLogging(config: EnableLoggingOptions): Promise; + enableLogging(config: EnableLoggingOptions, callback: SetBucketMetadataCallback): void; + enableRequesterPays(options?: EnableRequesterPaysOptions): Promise; + enableRequesterPays(callback: EnableRequesterPaysCallback): void; + enableRequesterPays(options: EnableRequesterPaysOptions, callback: EnableRequesterPaysCallback): void; + /** + * Create a {@link File} object. See {@link File} to see how to handle + * the different use cases you may have. + * + * @param {string} name The name of the file in this bucket. + * @param {FileOptions} [options] Configuration options. + * @param {string|number} [options.generation] Only use a specific revision of + * this file. + * @param {string} [options.encryptionKey] A custom encryption key. See + * {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}. + * @param {string} [options.kmsKeyName] The name of the Cloud KMS key that will + * be used to encrypt the object. Must be in the format: + * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`. + * KMS key ring must use the same location as the bucket. + * @param {string} [options.userProject] The ID of the project which will be + * billed for all requests made from File object. + * @returns {File} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * const file = bucket.file('my-existing-file.png'); + * ``` + */ + file(name: string, options?: FileOptions): File; + getFiles(query?: GetFilesOptions): Promise; + getFiles(query: GetFilesOptions, callback: GetFilesCallback): void; + getFiles(callback: GetFilesCallback): void; + getLabels(options?: GetLabelsOptions): Promise; + getLabels(callback: GetLabelsCallback): void; + getLabels(options: GetLabelsOptions, callback: GetLabelsCallback): void; + getNotifications(options?: GetNotificationsOptions): Promise; + getNotifications(callback: GetNotificationsCallback): void; + getNotifications(options: GetNotificationsOptions, callback: GetNotificationsCallback): void; + getSignedUrl(cfg: GetBucketSignedUrlConfig): Promise; + getSignedUrl(cfg: GetBucketSignedUrlConfig, callback: GetSignedUrlCallback): void; + lock(metageneration: number | string): Promise; + lock(metageneration: number | string, callback: BucketLockCallback): void; + /** + * @typedef {object} RestoreOptions Options for Bucket#restore(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/restore#resource| Object resource}. + * @param {number} [generation] If present, selects a specific revision of this object. + * @param {string} [projection] Specifies the set of properties to return. If used, must be 'full' or 'noAcl'. + */ + /** + * Restores a soft-deleted bucket + * @param {RestoreOptions} options Restore options. + * @returns {Promise} + */ + restore(options: RestoreOptions): Promise; + makePrivate(options?: MakeBucketPrivateOptions): Promise; + makePrivate(callback: MakeBucketPrivateCallback): void; + makePrivate(options: MakeBucketPrivateOptions, callback: MakeBucketPrivateCallback): void; + makePublic(options?: MakeBucketPublicOptions): Promise; + makePublic(callback: MakeBucketPublicCallback): void; + makePublic(options: MakeBucketPublicOptions, callback: MakeBucketPublicCallback): void; + /** + * Get a reference to a Cloud Pub/Sub Notification. + * + * @param {string} id ID of notification. + * @returns {Notification} + * @see Notification + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const notification = bucket.notification('1'); + * ``` + */ + notification(id: string): Notification; + removeRetentionPeriod(options?: SetBucketMetadataOptions): Promise; + removeRetentionPeriod(callback: SetBucketMetadataCallback): void; + removeRetentionPeriod(options: SetBucketMetadataOptions, callback: SetBucketMetadataCallback): void; + request(reqOpts: DecorateRequestOptions): Promise; + request(reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void; + setLabels(labels: Labels, options?: SetLabelsOptions): Promise; + setLabels(labels: Labels, callback: SetLabelsCallback): void; + setLabels(labels: Labels, options: SetLabelsOptions, callback: SetLabelsCallback): void; + setMetadata(metadata: BucketMetadata, options?: SetMetadataOptions): Promise>; + setMetadata(metadata: BucketMetadata, callback: MetadataCallback): void; + setMetadata(metadata: BucketMetadata, options: SetMetadataOptions, callback: MetadataCallback): void; + setRetentionPeriod(duration: number, options?: SetBucketMetadataOptions): Promise; + setRetentionPeriod(duration: number, callback: SetBucketMetadataCallback): void; + setRetentionPeriod(duration: number, options: SetBucketMetadataOptions, callback: SetBucketMetadataCallback): void; + setCorsConfiguration(corsConfiguration: Cors[], options?: SetBucketMetadataOptions): Promise; + setCorsConfiguration(corsConfiguration: Cors[], callback: SetBucketMetadataCallback): void; + setCorsConfiguration(corsConfiguration: Cors[], options: SetBucketMetadataOptions, callback: SetBucketMetadataCallback): void; + setStorageClass(storageClass: string, options?: SetBucketStorageClassOptions): Promise; + setStorageClass(storageClass: string, callback: SetBucketStorageClassCallback): void; + setStorageClass(storageClass: string, options: SetBucketStorageClassOptions, callback: SetBucketStorageClassCallback): void; + /** + * Set a user project to be billed for all requests made from this Bucket + * object and any files referenced from this Bucket object. + * + * @param {string} userProject The user project. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.setUserProject('grape-spaceship-123'); + * ``` + */ + setUserProject(userProject: string): void; + upload(pathString: string, options?: UploadOptions): Promise; + upload(pathString: string, options: UploadOptions, callback: UploadCallback): void; + upload(pathString: string, callback: UploadCallback): void; + makeAllFilesPublicPrivate_(options?: MakeAllFilesPublicPrivateOptions): Promise; + makeAllFilesPublicPrivate_(callback: MakeAllFilesPublicPrivateCallback): void; + makeAllFilesPublicPrivate_(options: MakeAllFilesPublicPrivateOptions, callback: MakeAllFilesPublicPrivateCallback): void; + getId(): string; + disableAutoRetryConditionallyIdempotent_(coreOpts: any, methodType: AvailableServiceObjectMethods, localPreconditionOptions?: PreconditionOptions): void; +} +/** + * Reference to the {@link Bucket} class. + * @name module:@google-cloud/storage.Bucket + * @see Bucket + */ +export { Bucket }; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/bucket.js b/node_modules/@google-cloud/storage/build/cjs/src/bucket.js new file mode 100644 index 0000000..ed05d6d --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/bucket.js @@ -0,0 +1,3568 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Bucket = exports.BucketExceptionMessages = exports.AvailableServiceObjectMethods = exports.BucketActionToHTTPMethod = void 0; +const index_js_1 = require("./nodejs-common/index.js"); +const paginator_1 = require("@google-cloud/paginator"); +const promisify_1 = require("@google-cloud/promisify"); +const fs = __importStar(require("fs")); +const mime_1 = __importDefault(require("mime")); +const path = __importStar(require("path")); +const p_limit_1 = __importDefault(require("p-limit")); +const util_1 = require("util"); +const async_retry_1 = __importDefault(require("async-retry")); +const util_js_1 = require("./util.js"); +const acl_js_1 = require("./acl.js"); +const file_js_1 = require("./file.js"); +const iam_js_1 = require("./iam.js"); +const notification_js_1 = require("./notification.js"); +const storage_js_1 = require("./storage.js"); +const signer_js_1 = require("./signer.js"); +const stream_1 = require("stream"); +const url_1 = require("url"); +var BucketActionToHTTPMethod; +(function (BucketActionToHTTPMethod) { + BucketActionToHTTPMethod["list"] = "GET"; +})(BucketActionToHTTPMethod || (exports.BucketActionToHTTPMethod = BucketActionToHTTPMethod = {})); +var AvailableServiceObjectMethods; +(function (AvailableServiceObjectMethods) { + AvailableServiceObjectMethods[AvailableServiceObjectMethods["setMetadata"] = 0] = "setMetadata"; + AvailableServiceObjectMethods[AvailableServiceObjectMethods["delete"] = 1] = "delete"; +})(AvailableServiceObjectMethods || (exports.AvailableServiceObjectMethods = AvailableServiceObjectMethods = {})); +var BucketExceptionMessages; +(function (BucketExceptionMessages) { + BucketExceptionMessages["PROVIDE_SOURCE_FILE"] = "You must provide at least one source file."; + BucketExceptionMessages["DESTINATION_FILE_NOT_SPECIFIED"] = "A destination file must be specified."; + BucketExceptionMessages["CHANNEL_ID_REQUIRED"] = "An ID is required to create a channel."; + BucketExceptionMessages["TOPIC_NAME_REQUIRED"] = "A valid topic name is required."; + BucketExceptionMessages["CONFIGURATION_OBJECT_PREFIX_REQUIRED"] = "A configuration object with a prefix is required."; + BucketExceptionMessages["SPECIFY_FILE_NAME"] = "A file name must be specified."; + BucketExceptionMessages["METAGENERATION_NOT_PROVIDED"] = "A metageneration must be provided."; + BucketExceptionMessages["SUPPLY_NOTIFICATION_ID"] = "You must supply a notification ID."; +})(BucketExceptionMessages || (exports.BucketExceptionMessages = BucketExceptionMessages = {})); +/** + * @callback Crc32cGeneratorToStringCallback + * A method returning the CRC32C as a base64-encoded string. + * + * @returns {string} + * + * @example + * Hashing the string 'data' should return 'rth90Q==' + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.toString(); // 'rth90Q==' + * ``` + **/ +/** + * @callback Crc32cGeneratorValidateCallback + * A method validating a base64-encoded CRC32C string. + * + * @param {string} [value] base64-encoded CRC32C string to validate + * @returns {boolean} + * + * @example + * Should return `true` if the value matches, `false` otherwise + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.validate('DkjKuA=='); // false + * crc32c.validate('rth90Q=='); // true + * ``` + **/ +/** + * @callback Crc32cGeneratorUpdateCallback + * A method for passing `Buffer`s for CRC32C generation. + * + * @param {Buffer} [data] data to update CRC32C value with + * @returns {undefined} + * + * @example + * Hashing buffers from 'some ' and 'text\n' + * + * ```js + * const buffer1 = Buffer.from('some '); + * crc32c.update(buffer1); + * + * const buffer2 = Buffer.from('text\n'); + * crc32c.update(buffer2); + * + * crc32c.toString(); // 'DkjKuA==' + * ``` + **/ +/** + * @typedef {object} CRC32CValidator + * @property {Crc32cGeneratorToStringCallback} + * @property {Crc32cGeneratorValidateCallback} + * @property {Crc32cGeneratorUpdateCallback} + */ +/** + * A function that generates a CRC32C Validator. Defaults to {@link CRC32C} + * + * @name Bucket#crc32cGenerator + * @type {CRC32CValidator} + */ +/** + * Get and set IAM policies for your bucket. + * + * @name Bucket#iam + * @mixes Iam + * + * See {@link https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management| Cloud Storage IAM Management} + * See {@link https://cloud.google.com/iam/docs/granting-changing-revoking-access| Granting, Changing, and Revoking Access} + * See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Get the IAM policy for your bucket. + * //- + * bucket.iam.getPolicy(function(err, policy) { + * console.log(policy); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.iam.getPolicy().then(function(data) { + * const policy = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/iam.js + * region_tag:storage_view_bucket_iam_members + * Example of retrieving a bucket's IAM policy: + * + * @example include:samples/iam.js + * region_tag:storage_add_bucket_iam_member + * Example of adding to a bucket's IAM policy: + * + * @example include:samples/iam.js + * region_tag:storage_remove_bucket_iam_member + * Example of removing from a bucket's IAM policy: + */ +/** + * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share objects with other + * users and allow other users to access your buckets and objects. + * + * An ACL consists of one or more entries, where each entry grants permissions + * to an entity. Permissions define the actions that can be performed against + * an object or bucket (for example, `READ` or `WRITE`); the entity defines + * who the permission applies to (for example, a specific user or group of + * users). + * + * The `acl` object on a Bucket instance provides methods to get you a list of + * the ACLs defined on your bucket, as well as set, update, and delete them. + * + * Buckets also have + * {@link https://cloud.google.com/storage/docs/access-control/lists#default| default ACLs} + * for all created files. Default ACLs specify permissions that all new + * objects added to the bucket will inherit by default. You can add, delete, + * get, and update entities and permissions for these as well with + * {@link Bucket#acl.default}. + * + * See {@link http://goo.gl/6qBBPO| About Access Control Lists} + * See {@link https://cloud.google.com/storage/docs/access-control/lists#default| Default ACLs} + * + * @name Bucket#acl + * @mixes Acl + * @property {Acl} default Cloud Storage Buckets have + * {@link https://cloud.google.com/storage/docs/access-control/lists#default| default ACLs} + * for all created files. You can add, delete, get, and update entities and + * permissions for these as well. The method signatures and examples are all + * the same, after only prefixing the method call with `default`. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // Make a bucket's contents publicly readable. + * //- + * const myBucket = storage.bucket('my-bucket'); + * + * const options = { + * entity: 'allUsers', + * role: storage.acl.READER_ROLE + * }; + * + * myBucket.acl.add(options, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myBucket.acl.add(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/acl.js + * region_tag:storage_print_bucket_acl + * Example of printing a bucket's ACL: + * + * @example include:samples/acl.js + * region_tag:storage_print_bucket_acl_for_user + * Example of printing a bucket's ACL for a specific user: + * + * @example include:samples/acl.js + * region_tag:storage_add_bucket_owner + * Example of adding an owner to a bucket: + * + * @example include:samples/acl.js + * region_tag:storage_remove_bucket_owner + * Example of removing an owner from a bucket: + * + * @example include:samples/acl.js + * region_tag:storage_add_bucket_default_owner + * Example of adding a default owner to a bucket: + * + * @example include:samples/acl.js + * region_tag:storage_remove_bucket_default_owner + * Example of removing a default owner from a bucket: + */ +/** + * The API-formatted resource description of the bucket. + * + * Note: This is not guaranteed to be up-to-date when accessed. To get the + * latest record, call the `getMetadata()` method. + * + * @name Bucket#metadata + * @type {object} + */ +/** + * The bucket's name. + * @name Bucket#name + * @type {string} + */ +/** + * Get {@link File} objects for the files currently in the bucket as a + * readable object stream. + * + * @method Bucket#getFilesStream + * @param {GetFilesOptions} [query] Query object for listing files. + * @returns {ReadableStream} A readable stream that emits {@link File} instances. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.getFilesStream() + * .on('error', console.error) + * .on('data', function(file) { + * // file is a File object. + * }) + * .on('end', function() { + * // All files retrieved. + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * bucket.getFilesStream() + * .on('data', function(file) { + * this.end(); + * }); + * + * //- + * // If you're filtering files with a delimiter, you should use + * // {@link Bucket#getFiles} and set `autoPaginate: false` in order to + * // preserve the `apiResponse` argument. + * //- + * const prefixes = []; + * + * function callback(err, files, nextQuery, apiResponse) { + * prefixes = prefixes.concat(apiResponse.prefixes); + * + * if (nextQuery) { + * bucket.getFiles(nextQuery, callback); + * } else { + * // prefixes = The finished array of prefixes. + * } + * } + * + * bucket.getFiles({ + * autoPaginate: false, + * delimiter: '/' + * }, callback); + * ``` + */ +/** + * Create a Bucket object to interact with a Cloud Storage bucket. + * + * @class + * @hideconstructor + * + * @param {Storage} storage A {@link Storage} instance. + * @param {string} name The name of the bucket. + * @param {object} [options] Configuration object. + * @param {string} [options.userProject] User project. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * ``` + */ +class Bucket extends index_js_1.ServiceObject { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getFilesStream(query) { + // placeholder body, overwritten in constructor + return new stream_1.Readable(); + } + constructor(storage, name, options) { + var _a, _b, _c, _d; + options = options || {}; + // Allow for "gs://"-style input, and strip any trailing slashes. + name = name.replace(/^gs:\/\//, '').replace(/\/+$/, ''); + const requestQueryObject = {}; + if ((_a = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) { + requestQueryObject.ifGenerationMatch = + options.preconditionOpts.ifGenerationMatch; + } + if ((_b = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _b === void 0 ? void 0 : _b.ifGenerationNotMatch) { + requestQueryObject.ifGenerationNotMatch = + options.preconditionOpts.ifGenerationNotMatch; + } + if ((_c = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _c === void 0 ? void 0 : _c.ifMetagenerationMatch) { + requestQueryObject.ifMetagenerationMatch = + options.preconditionOpts.ifMetagenerationMatch; + } + if ((_d = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _d === void 0 ? void 0 : _d.ifMetagenerationNotMatch) { + requestQueryObject.ifMetagenerationNotMatch = + options.preconditionOpts.ifMetagenerationNotMatch; + } + const userProject = options.userProject; + if (typeof userProject === 'string') { + requestQueryObject.userProject = userProject; + } + const methods = { + /** + * Create a bucket. + * + * @method Bucket#create + * @param {CreateBucketRequest} [metadata] Metadata to set for the bucket. + * @param {CreateBucketCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * bucket.create(function(err, bucket, apiResponse) { + * if (!err) { + * // The bucket was created successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.create().then(function(data) { + * const bucket = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + create: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * IamDeleteBucketOptions Configuration options. + * @property {boolean} [ignoreNotFound = false] Ignore an error if + * the bucket does not exist. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @typedef {array} DeleteBucketResponse + * @property {object} 0 The full API response. + */ + /** + * @callback DeleteBucketCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Delete the bucket. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/delete| Buckets: delete API Documentation} + * + * @method Bucket#delete + * @param {DeleteBucketOptions} [options] Configuration options. + * @param {boolean} [options.ignoreNotFound = false] Ignore an error if + * the bucket does not exist. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {DeleteBucketCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * bucket.delete(function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.delete().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example include:samples/buckets.js + * region_tag:storage_delete_bucket + * Another example: + */ + delete: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {object} BucketExistsOptions Configuration options for Bucket#exists(). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @typedef {array} BucketExistsResponse + * @property {boolean} 0 Whether the {@link Bucket} exists. + */ + /** + * @callback BucketExistsCallback + * @param {?Error} err Request error, if any. + * @param {boolean} exists Whether the {@link Bucket} exists. + */ + /** + * Check if the bucket exists. + * + * @method Bucket#exists + * @param {BucketExistsOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {BucketExistsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.exists(function(err, exists) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.exists().then(function(data) { + * const exists = data[0]; + * }); + * ``` + */ + exists: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {object} [GetBucketOptions] Configuration options for Bucket#get() + * @property {boolean} [autoCreate] Automatically create the object if + * it does not exist. Default: `false` + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @typedef {array} GetBucketResponse + * @property {Bucket} 0 The {@link Bucket}. + * @property {object} 1 The full API response. + */ + /** + * @callback GetBucketCallback + * @param {?Error} err Request error, if any. + * @param {Bucket} bucket The {@link Bucket}. + * @param {object} apiResponse The full API response. + */ + /** + * Get a bucket if it exists. + * + * You may optionally use this to "get or create" an object by providing + * an object with `autoCreate` set to `true`. Any extra configuration that + * is normally required for the `create` method must be contained within + * this object as well. + * + * @method Bucket#get + * @param {GetBucketOptions} [options] Configuration options. + * @param {boolean} [options.autoCreate] Automatically create the object if + * it does not exist. Default: `false` + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetBucketCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.get(function(err, bucket, apiResponse) { + * // `bucket.metadata` has been populated. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.get().then(function(data) { + * const bucket = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + get: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {array} GetBucketMetadataResponse + * @property {object} 0 The bucket metadata. + * @property {object} 1 The full API response. + */ + /** + * @callback GetBucketMetadataCallback + * @param {?Error} err Request error, if any. + * @param {object} metadata The bucket metadata. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {object} GetBucketMetadataOptions Configuration options for Bucket#getMetadata(). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * Get the bucket's metadata. + * + * To set metadata, see {@link Bucket#setMetadata}. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/get| Buckets: get API Documentation} + * + * @method Bucket#getMetadata + * @param {GetBucketMetadataOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetBucketMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.getMetadata(function(err, metadata, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.getMetadata().then(function(data) { + * const metadata = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/requesterPays.js + * region_tag:storage_get_requester_pays_status + * Example of retrieving the requester pays status of a bucket: + */ + getMetadata: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {object} SetBucketMetadataOptions Configuration options for Bucket#setMetadata(). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @typedef {array} SetBucketMetadataResponse + * @property {object} apiResponse The full API response. + */ + /** + * @callback SetBucketMetadataCallback + * @param {?Error} err Request error, if any. + * @param {object} metadata The bucket metadata. + */ + /** + * Set the bucket's metadata. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch| Buckets: patch API Documentation} + * + * @method Bucket#setMetadata + * @param {object} metadata The metadata you wish to set. + * @param {SetBucketMetadataOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {SetBucketMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Set website metadata field on the bucket. + * //- + * const metadata = { + * website: { + * mainPageSuffix: 'http://example.com', + * notFoundPage: 'http://example.com/404.html' + * } + * }; + * + * bucket.setMetadata(metadata, function(err, apiResponse) {}); + * + * //- + * // Enable versioning for your bucket. + * //- + * bucket.setMetadata({ + * versioning: { + * enabled: true + * } + * }, function(err, apiResponse) {}); + * + * //- + * // Enable KMS encryption for objects within this bucket. + * //- + * bucket.setMetadata({ + * encryption: { + * defaultKmsKeyName: 'projects/grape-spaceship-123/...' + * } + * }, function(err, apiResponse) {}); + * + * //- + * // Set the default event-based hold value for new objects in this + * // bucket. + * //- + * bucket.setMetadata({ + * defaultEventBasedHold: true + * }, function(err, apiResponse) {}); + * + * //- + * // Remove object lifecycle rules. + * //- + * bucket.setMetadata({ + * lifecycle: null + * }, function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.setMetadata(metadata).then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + setMetadata: { + reqOpts: { + qs: requestQueryObject, + }, + }, + }; + super({ + parent: storage, + baseUrl: '/b', + id: name, + createMethod: storage.createBucket.bind(storage), + methods, + }); + /** + * Indicates whether this Bucket object is a placeholder for an item + * that the API failed to retrieve (unreachable) due to partial failure. + * Consumers must check this flag before accessing other properties. + */ + this.unreachable = false; + this.name = name; + this.storage = storage; + this.userProject = options.userProject; + this.acl = new acl_js_1.Acl({ + request: this.request.bind(this), + pathPrefix: '/acl', + }); + this.acl.default = new acl_js_1.Acl({ + request: this.request.bind(this), + pathPrefix: '/defaultObjectAcl', + }); + this.crc32cGenerator = + options.crc32cGenerator || this.storage.crc32cGenerator; + this.iam = new iam_js_1.Iam(this); + this.getFilesStream = paginator_1.paginator.streamify('getFiles'); + this.instanceRetryValue = storage.retryOptions.autoRetry; + this.instancePreconditionOpts = options === null || options === void 0 ? void 0 : options.preconditionOpts; + } + /** + * The bucket's Cloud Storage URI (`gs://`) + * + * @example + * ```ts + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * // `gs://my-bucket` + * const href = bucket.cloudStorageURI.href; + * ``` + */ + get cloudStorageURI() { + const uri = new url_1.URL('gs://'); + uri.host = this.name; + return uri; + } + /** + * @typedef {object} AddLifecycleRuleOptions Configuration options for Bucket#addLifecycleRule(). + * @property {boolean} [append=true] The new rules will be appended to any + * pre-existing rules. + */ + /** + * + * @typedef {object} LifecycleRule The new lifecycle rule to be added to objects + * in this bucket. + * @property {string|object} action The action to be taken upon matching of + * all the conditions 'delete', 'setStorageClass', or 'AbortIncompleteMultipartUpload'. + * **Note**: For configuring a raw-formatted rule object to be passed as `action` + * please refer to the [examples]{@link https://cloud.google.com/storage/docs/managing-lifecycles#configexamples}. + * @property {object} condition Condition a bucket must meet before the + * action occurs on the bucket. Refer to following supported [conditions]{@link https://cloud.google.com/storage/docs/lifecycle#conditions}. + * @property {string} [storageClass] When using the `setStorageClass` + * action, provide this option to dictate which storage class the object + * should update to. Please see + * [SetStorageClass option documentation]{@link https://cloud.google.com/storage/docs/lifecycle#setstorageclass} for supported transitions. + */ + /** + * Add an object lifecycle management rule to the bucket. + * + * By default, an Object Lifecycle Management rule provided to this method + * will be included to the existing policy. To replace all existing rules, + * supply the `options` argument, setting `append` to `false`. + * + * To add multiple rules, pass a list to the `rule` parameter. Calling this + * function multiple times asynchronously does not guarantee that all rules + * are added correctly. + * + * See {@link https://cloud.google.com/storage/docs/lifecycle| Object Lifecycle Management} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch| Buckets: patch API Documentation} + * + * @param {LifecycleRule|LifecycleRule[]} rule The new lifecycle rule or rules to be added to objects + * in this bucket. + * @param {string|object} rule.action The action to be taken upon matching of + * all the conditions 'delete', 'setStorageClass', or 'AbortIncompleteMultipartUpload'. + * **Note**: For configuring a raw-formatted rule object to be passed as `action` + * please refer to the [examples]{@link https://cloud.google.com/storage/docs/managing-lifecycles#configexamples}. + * @param {object} rule.condition Condition a bucket must meet before the + * action occurs on the bucket. Refer to following supported [conditions]{@link https://cloud.google.com/storage/docs/lifecycle#conditions}. + * @param {string} [rule.storageClass] When using the `setStorageClass` + * action, provide this option to dictate which storage class the object + * should update to. + * @param {AddLifecycleRuleOptions} [options] Configuration object. + * @param {boolean} [options.append=true] Append the new rule to the existing + * policy. + * @param {SetBucketMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Automatically have an object deleted from this bucket once it is 3 years + * // of age. + * //- + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * age: 365 * 3 // Specified in days. + * } + * }, function(err, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * const lifecycleRules = bucket.metadata.lifecycle.rule; + * + * // Iterate over the Object Lifecycle Management rules on this bucket. + * lifecycleRules.forEach(lifecycleRule => {}); + * }); + * + * //- + * // By default, the rule you provide will be added to the existing policy. + * // Optionally, you can disable this behavior to replace all of the + * // pre-existing rules. + * //- + * const options = { + * append: false + * }; + * + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * age: 365 * 3 // Specified in days. + * } + * }, options, function(err, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * // All rules have been replaced with the new "delete" rule. + * + * // Iterate over the Object Lifecycle Management rules on this bucket. + * lifecycleRules.forEach(lifecycleRule => {}); + * }); + * + * //- + * // For objects created before 2018, "downgrade" the storage class. + * //- + * bucket.addLifecycleRule({ + * action: 'setStorageClass', + * storageClass: 'COLDLINE', + * condition: { + * createdBefore: new Date('2018') + * } + * }, function(err, apiResponse) {}); + * + * //- + * // Delete objects created before 2016 which have the Coldline storage + * // class. + * //- + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * matchesStorageClass: [ + * 'COLDLINE' + * ], + * createdBefore: new Date('2016') + * } + * }, function(err, apiResponse) {}); + * + * //- + * // Delete object that has a noncurrent timestamp that is at least 100 days. + * //- + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * daysSinceNoncurrentTime: 100 + * } + * }, function(err, apiResponse) {}); + * + * //- + * // Delete object that has a noncurrent timestamp before 2020-01-01. + * //- + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * noncurrentTimeBefore: new Date('2020-01-01') + * } + * }, function(err, apiResponse) {}); + * + * //- + * // Delete object that has a customTime that is at least 100 days. + * //- + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * daysSinceCustomTime: 100 + * } + * }, function(err, apiResponse) ()); + * + * //- + * // Delete object that has a customTime before 2020-01-01. + * //- + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * customTimeBefore: new Date('2020-01-01') + * } + * }, function(err, apiResponse) {}); + * ``` + */ + addLifecycleRule(rule, optionsOrCallback, callback) { + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else if (optionsOrCallback) { + options = optionsOrCallback; + } + options = options || {}; + const rules = Array.isArray(rule) ? rule : [rule]; + for (const curRule of rules) { + if (curRule.condition.createdBefore instanceof Date) { + curRule.condition.createdBefore = curRule.condition.createdBefore + .toISOString() + .replace(/T.+$/, ''); + } + if (curRule.condition.customTimeBefore instanceof Date) { + curRule.condition.customTimeBefore = curRule.condition.customTimeBefore + .toISOString() + .replace(/T.+$/, ''); + } + if (curRule.condition.noncurrentTimeBefore instanceof Date) { + curRule.condition.noncurrentTimeBefore = + curRule.condition.noncurrentTimeBefore + .toISOString() + .replace(/T.+$/, ''); + } + } + if (options.append === false) { + this.setMetadata({ lifecycle: { rule: rules } }, options, callback); + return; + } + // The default behavior appends the previously-defined lifecycle rules with + // the new ones just passed in by the user. + this.getMetadata((err, metadata) => { + var _a, _b; + if (err) { + callback(err); + return; + } + const currentLifecycleRules = Array.isArray((_a = metadata.lifecycle) === null || _a === void 0 ? void 0 : _a.rule) + ? (_b = metadata.lifecycle) === null || _b === void 0 ? void 0 : _b.rule + : []; + this.setMetadata({ + lifecycle: { rule: currentLifecycleRules.concat(rules) }, + }, options, callback); + }); + } + /** + * @typedef {object} CombineOptions + * @property {string} [kmsKeyName] Resource name of the Cloud KMS key, of + * the form + * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`, + * that will be used to encrypt the object. Overwrites the object + * metadata's `kms_key_name` value, if any. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @callback CombineCallback + * @param {?Error} err Request error, if any. + * @param {File} newFile The new {@link File}. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} CombineResponse + * @property {File} 0 The new {@link File}. + * @property {object} 1 The full API response. + */ + /** + * Combine multiple files into one new file. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/compose| Objects: compose API Documentation} + * + * @throws {Error} if a non-array is provided as sources argument. + * @throws {Error} if no sources are provided. + * @throws {Error} if no destination is provided. + * + * @param {string[]|File[]} sources The source files that will be + * combined. + * @param {string|File} destination The file you would like the + * source files combined into. + * @param {CombineOptions} [options] Configuration options. + * @param {string} [options.kmsKeyName] Resource name of the Cloud KMS key, of + * the form + * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`, + * that will be used to encrypt the object. Overwrites the object + * metadata's `kms_key_name` value, if any. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + + * @param {CombineCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const logBucket = storage.bucket('log-bucket'); + * + * const sources = [ + * logBucket.file('2013-logs.txt'), + * logBucket.file('2014-logs.txt') + * ]; + * + * const allLogs = logBucket.file('all-logs.txt'); + * + * logBucket.combine(sources, allLogs, function(err, newFile, apiResponse) { + * // newFile === allLogs + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * logBucket.combine(sources, allLogs).then(function(data) { + * const newFile = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + combine(sources, destination, optionsOrCallback, callback) { + var _a; + if (!Array.isArray(sources) || sources.length === 0) { + throw new Error(BucketExceptionMessages.PROVIDE_SOURCE_FILE); + } + if (!destination) { + throw new Error(BucketExceptionMessages.DESTINATION_FILE_NOT_SPECIFIED); + } + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else if (optionsOrCallback) { + options = optionsOrCallback; + } + this.disableAutoRetryConditionallyIdempotent_(this.methods.setMetadata, // Not relevant but param is required + AvailableServiceObjectMethods.setMetadata, // Same as above + options); + const convertToFile = (file) => { + if (file instanceof file_js_1.File) { + return file; + } + return this.file(file); + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sources = sources.map(convertToFile); + const destinationFile = convertToFile(destination); + callback = callback || index_js_1.util.noop; + if (!destinationFile.metadata.contentType) { + const destinationContentType = mime_1.default.getType(destinationFile.name) || undefined; + if (destinationContentType) { + destinationFile.metadata.contentType = destinationContentType; + } + } + let maxRetries = this.storage.retryOptions.maxRetries; + if ((((_a = destinationFile === null || destinationFile === void 0 ? void 0 : destinationFile.instancePreconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) === + undefined && + options.ifGenerationMatch === undefined && + this.storage.retryOptions.idempotencyStrategy === + storage_js_1.IdempotencyStrategy.RetryConditional) || + this.storage.retryOptions.idempotencyStrategy === + storage_js_1.IdempotencyStrategy.RetryNever) { + maxRetries = 0; + } + if (options.ifGenerationMatch === undefined) { + Object.assign(options, destinationFile.instancePreconditionOpts, options); + } + // Make the request from the destination File object. + destinationFile.request({ + method: 'POST', + uri: '/compose', + maxRetries, + json: { + destination: { + contentType: destinationFile.metadata.contentType, + contentEncoding: destinationFile.metadata.contentEncoding, + }, + sourceObjects: sources.map(source => { + const sourceObject = { + name: source.name, + }; + if (source.metadata && source.metadata.generation) { + sourceObject.generation = parseInt(source.metadata.generation.toString()); + } + return sourceObject; + }), + }, + qs: options, + }, (err, resp) => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + if (err) { + callback(err, null, resp); + return; + } + callback(null, destinationFile, resp); + }); + } + /** + * See a {@link https://cloud.google.com/storage/docs/json_api/v1/objects/watchAll| Objects: watchAll request body}. + * + * @typedef {object} CreateChannelConfig + * @property {string} address The address where notifications are + * delivered for this channel. + * @property {string} [delimiter] Returns results in a directory-like mode. + * @property {number} [maxResults] Maximum number of `items` plus `prefixes` + * to return in a single page of responses. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @property {string} [prefix] Filter results to objects whose names begin + * with this prefix. + * @property {string} [projection=noAcl] Set of properties to return. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {boolean} [versions=false] If `true`, lists all versions of an object + * as distinct results. + */ + /** + * @typedef {object} CreateChannelOptions + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @typedef {array} CreateChannelResponse + * @property {Channel} 0 The new {@link Channel}. + * @property {object} 1 The full API response. + */ + /** + * @callback CreateChannelCallback + * @param {?Error} err Request error, if any. + * @param {Channel} channel The new {@link Channel}. + * @param {object} apiResponse The full API response. + */ + /** + * Create a channel that will be notified when objects in this bucket changes. + * + * @throws {Error} If an ID is not provided. + * @throws {Error} If an address is not provided. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/watchAll| Objects: watchAll API Documentation} + * + * @param {string} id The ID of the channel to create. + * @param {CreateChannelConfig} config Configuration for creating channel. + * @param {string} config.address The address where notifications are + * delivered for this channel. + * @param {string} [config.delimiter] Returns results in a directory-like mode. + * @param {number} [config.maxResults] Maximum number of `items` plus `prefixes` + * to return in a single page of responses. + * @param {string} [config.pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @param {string} [config.prefix] Filter results to objects whose names begin + * with this prefix. + * @param {string} [config.projection=noAcl] Set of properties to return. + * @param {string} [config.userProject] The ID of the project which will be + * billed for the request. + * @param {boolean} [config.versions=false] If `true`, lists all versions of an object + * as distinct results. + * @param {CreateChannelOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {CreateChannelCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * const id = 'new-channel-id'; + * + * const config = { + * address: 'https://...' + * }; + * + * bucket.createChannel(id, config, function(err, channel, apiResponse) { + * if (!err) { + * // Channel created successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.createChannel(id, config).then(function(data) { + * const channel = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + createChannel(id, config, optionsOrCallback, callback) { + if (typeof id !== 'string') { + throw new Error(BucketExceptionMessages.CHANNEL_ID_REQUIRED); + } + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else if (optionsOrCallback) { + options = optionsOrCallback; + } + this.request({ + method: 'POST', + uri: '/o/watch', + json: Object.assign({ + id, + type: 'web_hook', + }, config), + qs: options, + }, (err, apiResponse) => { + if (err) { + callback(err, null, apiResponse); + return; + } + const resourceId = apiResponse.resourceId; + const channel = this.storage.channel(id, resourceId); + channel.metadata = apiResponse; + callback(null, channel, apiResponse); + }); + } + /** + * Metadata to set for the Notification. + * + * @typedef {object} CreateNotificationOptions + * @property {object} [customAttributes] An optional list of additional + * attributes to attach to each Cloud PubSub message published for this + * notification subscription. + * @property {string[]} [eventTypes] If present, only send notifications about + * listed event types. If empty, sent notifications for all event types. + * @property {string} [objectNamePrefix] If present, only apply this + * notification configuration to object names that begin with this prefix. + * @property {string} [payloadFormat] The desired content of the Payload. + * Defaults to `JSON_API_V1`. + * + * Acceptable values are: + * - `JSON_API_V1` + * + * - `NONE` + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @callback CreateNotificationCallback + * @param {?Error} err Request error, if any. + * @param {Notification} notification The new {@link Notification}. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} CreateNotificationResponse + * @property {Notification} 0 The new {@link Notification}. + * @property {object} 1 The full API response. + */ + /** + * Creates a notification subscription for the bucket. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/insert| Notifications: insert} + * + * @param {Topic|string} topic The Cloud PubSub topic to which this + * subscription publishes. If the project ID is omitted, the current + * project ID will be used. + * + * Acceptable formats are: + * - `projects/grape-spaceship-123/topics/my-topic` + * + * - `my-topic` + * @param {CreateNotificationOptions} [options] Metadata to set for the + * notification. + * @param {object} [options.customAttributes] An optional list of additional + * attributes to attach to each Cloud PubSub message published for this + * notification subscription. + * @param {string[]} [options.eventTypes] If present, only send notifications about + * listed event types. If empty, sent notifications for all event types. + * @param {string} [options.objectNamePrefix] If present, only apply this + * notification configuration to object names that begin with this prefix. + * @param {string} [options.payloadFormat] The desired content of the Payload. + * Defaults to `JSON_API_V1`. + * + * Acceptable values are: + * - `JSON_API_V1` + * + * - `NONE` + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {CreateNotificationCallback} [callback] Callback function. + * @returns {Promise} + * @throws {Error} If a valid topic is not provided. + * @see Notification#create + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const callback = function(err, notification, apiResponse) { + * if (!err) { + * // The notification was created successfully. + * } + * }; + * + * myBucket.createNotification('my-topic', callback); + * + * //- + * // Configure the notification by providing Notification metadata. + * //- + * const metadata = { + * objectNamePrefix: 'prefix-' + * }; + * + * myBucket.createNotification('my-topic', metadata, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myBucket.createNotification('my-topic').then(function(data) { + * const notification = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/createNotification.js + * region_tag:storage_create_bucket_notifications + * Another example: + */ + createNotification(topic, optionsOrCallback, callback) { + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else if (optionsOrCallback) { + options = optionsOrCallback; + } + const topicIsObject = topic !== null && typeof topic === 'object'; + if (topicIsObject && index_js_1.util.isCustomType(topic, 'pubsub/topic')) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + topic = topic.name; + } + if (typeof topic !== 'string') { + throw new Error(BucketExceptionMessages.TOPIC_NAME_REQUIRED); + } + const body = Object.assign({ topic }, options); + if (body.topic.indexOf('projects') !== 0) { + body.topic = 'projects/{{projectId}}/topics/' + body.topic; + } + body.topic = `//pubsub.${this.storage.universeDomain}/` + body.topic; + if (!body.payloadFormat) { + body.payloadFormat = 'JSON_API_V1'; + } + const query = {}; + if (body.userProject) { + query.userProject = body.userProject; + delete body.userProject; + } + this.request({ + method: 'POST', + uri: '/notificationConfigs', + json: (0, util_js_1.convertObjKeysToSnakeCase)(body), + qs: query, + maxRetries: 0, //explicitly set this value since this is a non-idempotent function + }, (err, apiResponse) => { + if (err) { + callback(err, null, apiResponse); + return; + } + const notification = this.notification(apiResponse.id); + notification.metadata = apiResponse; + callback(null, notification, apiResponse); + }); + } + /** + * @typedef {object} DeleteFilesOptions Query object. See {@link Bucket#getFiles} + * for all of the supported properties. + * @property {boolean} [force] Suppress errors until all files have been + * processed. + */ + /** + * @callback DeleteFilesCallback + * @param {?Error|?Error[]} err Request error, if any, or array of errors from + * files that were not able to be deleted. + * @param {object} [apiResponse] The full API response. + */ + /** + * Iterate over the bucket's files, calling `file.delete()` on each. + * + * This is not an atomic request. A delete attempt will be + * made for each file individually. Any one can fail, in which case only a + * portion of the files you intended to be deleted would have. + * + * Operations are performed in parallel, up to 10 at once. The first error + * breaks the loop and will execute the provided callback with it. Specify + * `{ force: true }` to suppress the errors until all files have had a chance + * to be processed. + * + * File preconditions cannot be passed to this function. It will not retry unless + * the idempotency strategy is set to retry always. + * + * The `query` object passed as the first argument will also be passed to + * {@link Bucket#getFiles}. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/delete| Objects: delete API Documentation} + * + * @param {DeleteFilesOptions} [query] Query object. See {@link Bucket#getFiles} + * @param {boolean} [query.force] Suppress errors until all files have been + * processed. + * @param {DeleteFilesCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Delete all of the files in the bucket. + * //- + * bucket.deleteFiles(function(err) {}); + * + * //- + * // By default, if a file cannot be deleted, this method will stop deleting + * // files from your bucket. You can override this setting with `force: + * // true`. + * //- + * bucket.deleteFiles({ + * force: true + * }, function(errors) { + * // `errors`: + * // Array of errors if any occurred, otherwise null. + * }); + * + * //- + * // The first argument to this method acts as a query to + * // {@link Bucket#getFiles}. As an example, you can delete files + * // which match a prefix. + * //- + * bucket.deleteFiles({ + * prefix: 'images/' + * }, function(err) { + * if (!err) { + * // All files in the `images` directory have been deleted. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.deleteFiles().then(function() {}); + * ``` + */ + deleteFiles(queryOrCallback, callback) { + let query = {}; + if (typeof queryOrCallback === 'function') { + callback = queryOrCallback; + } + else if (queryOrCallback) { + query = queryOrCallback; + } + const MAX_PARALLEL_LIMIT = 10; + const MAX_QUEUE_SIZE = 1000; + const errors = []; + const deleteFile = (file) => { + return file.delete(query).catch(err => { + if (!query.force) { + throw err; + } + errors.push(err); + }); + }; + (async () => { + try { + let promises = []; + const limit = (0, p_limit_1.default)(MAX_PARALLEL_LIMIT); + const filesStream = this.getFilesStream(query); + for await (const curFile of filesStream) { + if (promises.length >= MAX_QUEUE_SIZE) { + await Promise.all(promises); + promises = []; + } + promises.push(limit(() => deleteFile(curFile)).catch(e => { + filesStream.destroy(); + throw e; + })); + } + await Promise.all(promises); + callback(errors.length > 0 ? errors : null); + } + catch (e) { + callback(e); + return; + } + })(); + } + /** + * @deprecated + * @typedef {array} DeleteLabelsResponse + * @property {object} 0 The full API response. + */ + /** + * @deprecated + * @callback DeleteLabelsCallback + * @param {?Error} err Request error, if any. + * @param {object} metadata Bucket's metadata. + */ + /** + * @deprecated Use setMetadata directly + * Delete one or more labels from this bucket. + * + * @param {string|string[]} [labels] The labels to delete. If no labels are + * provided, all of the labels are removed. + * @param {DeleteLabelsCallback} [callback] Callback function. + * @param {DeleteLabelsOptions} [options] Options, including precondition options + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Delete all of the labels from this bucket. + * //- + * bucket.deleteLabels(function(err, apiResponse) {}); + * + * //- + * // Delete a single label. + * //- + * bucket.deleteLabels('labelone', function(err, apiResponse) {}); + * + * //- + * // Delete a specific set of labels. + * //- + * bucket.deleteLabels([ + * 'labelone', + * 'labeltwo' + * ], function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.deleteLabels().then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + deleteLabels(labelsOrCallbackOrOptions, optionsOrCallback, callback) { + let labels = new Array(); + let options = {}; + if (typeof labelsOrCallbackOrOptions === 'function') { + callback = labelsOrCallbackOrOptions; + } + else if (typeof labelsOrCallbackOrOptions === 'string') { + labels = [labelsOrCallbackOrOptions]; + } + else if (Array.isArray(labelsOrCallbackOrOptions)) { + labels = labelsOrCallbackOrOptions; + } + else if (labelsOrCallbackOrOptions) { + options = labelsOrCallbackOrOptions; + } + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else if (optionsOrCallback) { + options = optionsOrCallback; + } + const deleteLabels = (labels) => { + const nullLabelMap = labels.reduce((nullLabelMap, labelKey) => { + nullLabelMap[labelKey] = null; + return nullLabelMap; + }, {}); + if ((options === null || options === void 0 ? void 0 : options.ifMetagenerationMatch) !== undefined) { + this.setLabels(nullLabelMap, options, callback); + } + else { + this.setLabels(nullLabelMap, callback); + } + }; + if (labels.length === 0) { + this.getLabels((err, labels) => { + if (err) { + callback(err); + return; + } + deleteLabels(Object.keys(labels)); + }); + } + else { + deleteLabels(labels); + } + } + /** + * @typedef {array} DisableRequesterPaysResponse + * @property {object} 0 The full API response. + */ + /** + * @callback DisableRequesterPaysCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + *

+ * Early Access Testers Only + *

+ * This feature is not yet widely-available. + *

+ *
+ * + * Disable `requesterPays` functionality from this bucket. + * + * @param {DisableRequesterPaysCallback} [callback] Callback function. + * @param {DisableRequesterPaysOptions} [options] Options, including precondition options + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.disableRequesterPays(function(err, apiResponse) { + * if (!err) { + * // requesterPays functionality disabled successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.disableRequesterPays().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example include:samples/requesterPays.js + * region_tag:storage_disable_requester_pays + * Example of disabling requester pays: + */ + disableRequesterPays(optionsOrCallback, callback) { + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else if (optionsOrCallback) { + options = optionsOrCallback; + } + this.setMetadata({ + billing: { + requesterPays: false, + }, + }, options, callback); + } + /** + * Configuration object for enabling logging. + * + * @typedef {object} EnableLoggingOptions + * @property {string|Bucket} [bucket] The bucket for the log entries. By + * default, the current bucket is used. + * @property {string} prefix A unique prefix for log object names. + */ + /** + * Enable logging functionality for this bucket. This will make two API + * requests, first to grant Cloud Storage WRITE permission to the bucket, then + * to set the appropriate configuration on the Bucket's metadata. + * + * @param {EnableLoggingOptions} config Configuration options. + * @param {string|Bucket} [config.bucket] The bucket for the log entries. By + * default, the current bucket is used. + * @param {string} config.prefix A unique prefix for log object names. + * @param {SetBucketMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * const config = { + * prefix: 'log' + * }; + * + * bucket.enableLogging(config, function(err, apiResponse) { + * if (!err) { + * // Logging functionality enabled successfully. + * } + * }); + * + * ``` + * @example + * Optionally, provide a destination bucket. + * ``` + * const config = { + * prefix: 'log', + * bucket: 'destination-bucket' + * }; + * + * bucket.enableLogging(config, function(err, apiResponse) {}); + * ``` + * + * @example + * If the callback is omitted, we'll return a Promise. + * ``` + * bucket.enableLogging(config).then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + enableLogging(config, callback) { + if (!config || + typeof config === 'function' || + typeof config.prefix === 'undefined') { + throw new Error(BucketExceptionMessages.CONFIGURATION_OBJECT_PREFIX_REQUIRED); + } + let logBucket = this.id; + if (config.bucket && config.bucket instanceof Bucket) { + logBucket = config.bucket.id; + } + else if (config.bucket && typeof config.bucket === 'string') { + logBucket = config.bucket; + } + const options = {}; + if (config === null || config === void 0 ? void 0 : config.ifMetagenerationMatch) { + options.ifMetagenerationMatch = config.ifMetagenerationMatch; + } + if (config === null || config === void 0 ? void 0 : config.ifMetagenerationNotMatch) { + options.ifMetagenerationNotMatch = config.ifMetagenerationNotMatch; + } + (async () => { + try { + const [policy] = await this.iam.getPolicy(); + policy.bindings.push({ + members: ['group:cloud-storage-analytics@google.com'], + role: 'roles/storage.objectCreator', + }); + await this.iam.setPolicy(policy); + this.setMetadata({ + logging: { + logBucket, + logObjectPrefix: config.prefix, + }, + }, options, callback); + } + catch (e) { + callback(e); + return; + } + })(); + } + /** + * @typedef {array} EnableRequesterPaysResponse + * @property {object} 0 The full API response. + */ + /** + * @callback EnableRequesterPaysCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + *
+ * Early Access Testers Only + *

+ * This feature is not yet widely-available. + *

+ *
+ * + * Enable `requesterPays` functionality for this bucket. This enables you, the + * bucket owner, to have the requesting user assume the charges for the access + * to your bucket and its contents. + * + * @param {EnableRequesterPaysCallback | EnableRequesterPaysOptions} [optionsOrCallback] + * Callback function or precondition options. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.enableRequesterPays(function(err, apiResponse) { + * if (!err) { + * // requesterPays functionality enabled successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.enableRequesterPays().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example include:samples/requesterPays.js + * region_tag:storage_enable_requester_pays + * Example of enabling requester pays: + */ + enableRequesterPays(optionsOrCallback, cb) { + let options = {}; + if (typeof optionsOrCallback === 'function') { + cb = optionsOrCallback; + } + else if (optionsOrCallback) { + options = optionsOrCallback; + } + this.setMetadata({ + billing: { + requesterPays: true, + }, + }, options, cb); + } + /** + * Create a {@link File} object. See {@link File} to see how to handle + * the different use cases you may have. + * + * @param {string} name The name of the file in this bucket. + * @param {FileOptions} [options] Configuration options. + * @param {string|number} [options.generation] Only use a specific revision of + * this file. + * @param {string} [options.encryptionKey] A custom encryption key. See + * {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}. + * @param {string} [options.kmsKeyName] The name of the Cloud KMS key that will + * be used to encrypt the object. Must be in the format: + * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`. + * KMS key ring must use the same location as the bucket. + * @param {string} [options.userProject] The ID of the project which will be + * billed for all requests made from File object. + * @returns {File} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * const file = bucket.file('my-existing-file.png'); + * ``` + */ + file(name, options) { + if (!name) { + throw Error(BucketExceptionMessages.SPECIFY_FILE_NAME); + } + return new file_js_1.File(this, name, options); + } + /** + * @typedef {array} GetFilesResponse + * @property {File[]} 0 Array of {@link File} instances. + * @param {object} nextQuery 1 A query object to receive more results. + * @param {object} apiResponse 2 The full API response. + */ + /** + * @callback GetFilesCallback + * @param {?Error} err Request error, if any. + * @param {File[]} files Array of {@link File} instances. + * @param {object} nextQuery A query object to receive more results. + * @param {object} apiResponse The full API response. + */ + /** + * Query object for listing files. + * + * @typedef {object} GetFilesOptions + * @property {boolean} [autoPaginate=true] Have pagination handled + * automatically. + * @property {string} [delimiter] Results will contain only objects whose + * names, aside from the prefix, do not contain delimiter. Objects whose + * names, aside from the prefix, contain delimiter will have their name + * truncated after the delimiter, returned in `apiResponse.prefixes`. + * Duplicate prefixes are omitted. + * @property {string} [endOffset] Filter results to objects whose names are + * lexicographically before endOffset. If startOffset is also set, the objects + * listed have names between startOffset (inclusive) and endOffset (exclusive). + * @property {boolean} [includeFoldersAsPrefixes] If true, includes folders and + * managed folders in the set of prefixes returned by the query. Only applicable if + * delimiter is set to / and autoPaginate is set to false. + * See: https://cloud.google.com/storage/docs/managed-folders + * @property {boolean} [includeTrailingDelimiter] If true, objects that end in + * exactly one instance of delimiter have their metadata included in items[] + * in addition to the relevant part of the object name appearing in prefixes[]. + * @property {string} [prefix] Filter results to objects whose names begin + * with this prefix. + * @property {string} [matchGlob] A glob pattern used to filter results, + * for example foo*bar + * @property {number} [maxApiCalls] Maximum number of API calls to make. + * @property {number} [maxResults] Maximum number of items plus prefixes to + * return per call. + * Note: By default will handle pagination automatically + * if more than 1 page worth of results are requested per call. + * When `autoPaginate` is set to `false` the smaller of `maxResults` + * or 1 page of results will be returned per call. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @property {boolean} [softDeleted] If true, only soft-deleted object versions will be + * listed as distinct results in order of generation number. Note `soft_deleted` and + * `versions` cannot be set to true simultaneously. + * @property {string} [startOffset] Filter results to objects whose names are + * lexicographically equal to or after startOffset. If endOffset is also set, + * the objects listed have names between startOffset (inclusive) and endOffset (exclusive). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {boolean} [versions] If true, returns File objects scoped to + * their versions. + */ + /** + * Get {@link File} objects for the files currently in the bucket. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/list| Objects: list API Documentation} + * + * @param {GetFilesOptions} [query] Query object for listing files. + * @param {boolean} [query.autoPaginate=true] Have pagination handled + * automatically. + * @param {string} [query.delimiter] Results will contain only objects whose + * names, aside from the prefix, do not contain delimiter. Objects whose + * names, aside from the prefix, contain delimiter will have their name + * truncated after the delimiter, returned in `apiResponse.prefixes`. + * Duplicate prefixes are omitted. + * @param {string} [query.endOffset] Filter results to objects whose names are + * lexicographically before endOffset. If startOffset is also set, the objects + * listed have names between startOffset (inclusive) and endOffset (exclusive). + * @param {boolean} [query.includeFoldersAsPrefixes] If true, includes folders and + * managed folders in the set of prefixes returned by the query. Only applicable if + * delimiter is set to / and autoPaginate is set to false. + * See: https://cloud.google.com/storage/docs/managed-folders + * @param {boolean} [query.includeTrailingDelimiter] If true, objects that end in + * exactly one instance of delimiter have their metadata included in items[] + * in addition to the relevant part of the object name appearing in prefixes[]. + * @param {string} [query.prefix] Filter results to objects whose names begin + * with this prefix. + * @param {number} [query.maxApiCalls] Maximum number of API calls to make. + * @param {number} [query.maxResults] Maximum number of items plus prefixes to + * return per call. + * Note: By default will handle pagination automatically + * if more than 1 page worth of results are requested per call. + * When `autoPaginate` is set to `false` the smaller of `maxResults` + * or 1 page of results will be returned per call. + * @param {string} [query.pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @param {boolean} [query.softDeleted] If true, only soft-deleted object versions will be + * listed as distinct results in order of generation number. Note `soft_deleted` and + * `versions` cannot be set to true simultaneously. + * @param {string} [query.startOffset] Filter results to objects whose names are + * lexicographically equal to or after startOffset. If endOffset is also set, + * the objects listed have names between startOffset (inclusive) and endOffset (exclusive). + * @param {string} [query.userProject] The ID of the project which will be + * billed for the request. + * @param {boolean} [query.versions] If true, returns File objects scoped to + * their versions. + * @param {GetFilesCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.getFiles(function(err, files) { + * if (!err) { + * // files is an array of File objects. + * } + * }); + * + * //- + * // If your bucket has versioning enabled, you can get all of your files + * // scoped to their generation. + * //- + * bucket.getFiles({ + * versions: true + * }, function(err, files) { + * // Each file is scoped to its generation. + * }); + * + * //- + * // To control how many API requests are made and page through the results + * // manually, set `autoPaginate` to `false`. + * //- + * const callback = function(err, files, nextQuery, apiResponse) { + * if (nextQuery) { + * // More results exist. + * bucket.getFiles(nextQuery, callback); + * } + * + * // The `metadata` property is populated for you with the metadata at the + * // time of fetching. + * files[0].metadata; + * + * // However, in cases where you are concerned the metadata could have + * // changed, use the `getMetadata` method. + * files[0].getMetadata(function(err, metadata) {}); + * }; + * + * bucket.getFiles({ + * autoPaginate: false + * }, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.getFiles().then(function(data) { + * const files = data[0]; + * }); + * + * ``` + * @example + *
Simulating a File System

With `autoPaginate: false`, it's possible to iterate over files which incorporate a common structure using a delimiter.

Consider the following remote objects:

  1. "a"
  2. "a/b/c/d"
  3. "b/d/e"

Using a delimiter of `/` will return a single file, "a".

`apiResponse.prefixes` will return the "sub-directories" that were found:

  1. "a/"
  2. "b/"
+ * ``` + * bucket.getFiles({ + * autoPaginate: false, + * delimiter: '/' + * }, function(err, files, nextQuery, apiResponse) { + * // files = [ + * // {File} // File object for file "a" + * // ] + * + * // apiResponse.prefixes = [ + * // 'a/', + * // 'b/' + * // ] + * }); + * ``` + * + * @example + * Using prefixes, it's now possible to simulate a file system with follow-up requests. + * ``` + * bucket.getFiles({ + * autoPaginate: false, + * delimiter: '/', + * prefix: 'a/' + * }, function(err, files, nextQuery, apiResponse) { + * // No files found within "directory" a. + * // files = [] + * + * // However, a "sub-directory" was found. + * // This prefix can be used to continue traversing the "file system". + * // apiResponse.prefixes = [ + * // 'a/b/' + * // ] + * }); + * ``` + * + * @example include:samples/files.js + * region_tag:storage_list_files + * Another example: + * + * @example include:samples/files.js + * region_tag:storage_list_files_with_prefix + * Example of listing files, filtered by a prefix: + */ + getFiles(queryOrCallback, callback) { + let query = typeof queryOrCallback === 'object' ? queryOrCallback : {}; + if (!callback) { + callback = queryOrCallback; + } + query = Object.assign({}, query); + if (query.fields && + query.autoPaginate && + !query.fields.includes('nextPageToken')) { + query.fields = `${query.fields},nextPageToken`; + } + this.request({ + uri: '/o', + qs: query, + }, (err, resp) => { + if (err) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callback(err, null, null, resp); + return; + } + const itemsArray = resp.items ? resp.items : []; + const files = itemsArray.map((file) => { + const options = {}; + if (query.fields) { + const fileInstance = file; + return fileInstance; + } + if (query.versions) { + options.generation = file.generation; + } + if (file.kmsKeyName) { + options.kmsKeyName = file.kmsKeyName; + } + const fileInstance = this.file(file.name, options); + fileInstance.metadata = file; + return fileInstance; + }); + let nextQuery = null; + if (resp.nextPageToken) { + nextQuery = Object.assign({}, query, { + pageToken: resp.nextPageToken, + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callback(null, files, nextQuery, resp); + }); + } + /** + * @deprecated + * @typedef {object} GetLabelsOptions Configuration options for Bucket#getLabels(). + * @param {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @deprecated + * @typedef {array} GetLabelsResponse + * @property {object} 0 Object of labels currently set on this bucket. + */ + /** + * @deprecated + * @callback GetLabelsCallback + * @param {?Error} err Request error, if any. + * @param {object} labels Object of labels currently set on this bucket. + */ + /** + * @deprecated Use getMetadata directly. + * Get the labels currently set on this bucket. + * + * @param {object} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetLabelsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.getLabels(function(err, labels) { + * if (err) { + * // Error handling omitted. + * } + * + * // labels = { + * // label: 'labelValue', + * // ... + * // } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.getLabels().then(function(data) { + * const labels = data[0]; + * }); + * ``` + */ + getLabels(optionsOrCallback, callback) { + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else if (optionsOrCallback) { + options = optionsOrCallback; + } + this.getMetadata(options, (err, metadata) => { + if (err) { + callback(err, null); + return; + } + callback(null, (metadata === null || metadata === void 0 ? void 0 : metadata.labels) || {}); + }); + } + /** + * @typedef {object} GetNotificationsOptions Configuration options for Bucket#getNotification(). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @callback GetNotificationsCallback + * @param {?Error} err Request error, if any. + * @param {Notification[]} notifications Array of {@link Notification} + * instances. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} GetNotificationsResponse + * @property {Notification[]} 0 Array of {@link Notification} instances. + * @property {object} 1 The full API response. + */ + /** + * Retrieves a list of notification subscriptions for a given bucket. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/list| Notifications: list} + * + * @param {GetNotificationsOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetNotificationsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * bucket.getNotifications(function(err, notifications, apiResponse) { + * if (!err) { + * // notifications is an array of Notification objects. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.getNotifications().then(function(data) { + * const notifications = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/listNotifications.js + * region_tag:storage_list_bucket_notifications + * Another example: + */ + getNotifications(optionsOrCallback, callback) { + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else if (optionsOrCallback) { + options = optionsOrCallback; + } + this.request({ + uri: '/notificationConfigs', + qs: options, + }, (err, resp) => { + if (err) { + callback(err, null, resp); + return; + } + const itemsArray = resp.items ? resp.items : []; + const notifications = itemsArray.map((notification) => { + const notificationInstance = this.notification(notification.id); + notificationInstance.metadata = notification; + return notificationInstance; + }); + callback(null, notifications, resp); + }); + } + /** + * @typedef {array} GetSignedUrlResponse + * @property {object} 0 The signed URL. + */ + /** + * @callback GetSignedUrlCallback + * @param {?Error} err Request error, if any. + * @param {object} url The signed URL. + */ + /** + * @typedef {object} GetBucketSignedUrlConfig + * @property {string} action Only listing objects within a bucket (HTTP: GET) is supported for bucket-level signed URLs. + * @property {*} expires A timestamp when this link will expire. Any value + * given is passed to `new Date()`. + * Note: 'v4' supports maximum duration of 7 days (604800 seconds) from now. + * @property {string} [version='v2'] The signing version to use, either + * 'v2' or 'v4'. + * @property {boolean} [virtualHostedStyle=false] Use virtual hosted-style + * URLs ('https://mybucket.storage.googleapis.com/...') instead of path-style + * ('https://storage.googleapis.com/mybucket/...'). Virtual hosted-style URLs + * should generally be preferred instead of path-style URL. + * Currently defaults to `false` for path-style, although this may change in a + * future major-version release. + * @property {string} [cname] The cname for this bucket, i.e., + * "https://cdn.example.com". + * See [reference]{@link https://cloud.google.com/storage/docs/access-control/signed-urls#example} + * @property {object} [extensionHeaders] If these headers are used, the + * server will check to make sure that the client provides matching + * values. See {@link https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers| Canonical extension headers} + * for the requirements of this feature, most notably: + * - The header name must be prefixed with `x-goog-` + * - The header name must be all lowercase + * + * Note: Multi-valued header passed as an array in the extensionHeaders + * object is converted into a string, delimited by `,` with + * no space. Requests made using the signed URL will need to + * delimit multi-valued headers using a single `,` as well, or + * else the server will report a mismatched signature. + * @property {object} [queryParams] Additional query parameters to include + * in the signed URL. + */ + /** + * Get a signed URL to allow limited time access to a bucket. + * + * In Google Cloud Platform environments, such as Cloud Functions and App + * Engine, you usually don't provide a `keyFilename` or `credentials` during + * instantiation. In those environments, we call the + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob| signBlob API} + * to create a signed URL. That API requires either the + * `https://www.googleapis.com/auth/iam` or + * `https://www.googleapis.com/auth/cloud-platform` scope, so be sure they are + * enabled. + * + * See {@link https://cloud.google.com/storage/docs/access-control/signed-urls| Signed URLs Reference} + * + * @throws {Error} if an expiration timestamp from the past is given. + * + * @param {GetBucketSignedUrlConfig} config Configuration object. + * @param {string} config.action Currently only supports "list" (HTTP: GET). + * @param {*} config.expires A timestamp when this link will expire. Any value + * given is passed to `new Date()`. + * Note: 'v4' supports maximum duration of 7 days (604800 seconds) from now. + * @param {string} [config.version='v2'] The signing version to use, either + * 'v2' or 'v4'. + * @param {boolean} [config.virtualHostedStyle=false] Use virtual hosted-style + * URLs ('https://mybucket.storage.googleapis.com/...') instead of path-style + * ('https://storage.googleapis.com/mybucket/...'). Virtual hosted-style URLs + * should generally be preferred instead of path-style URL. + * Currently defaults to `false` for path-style, although this may change in a + * future major-version release. + * @param {string} [config.cname] The cname for this bucket, i.e., + * "https://cdn.example.com". + * See [reference]{@link https://cloud.google.com/storage/docs/access-control/signed-urls#example} + * @param {object} [config.extensionHeaders] If these headers are used, the + * server will check to make sure that the client provides matching + * values. See {@link https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers| Canonical extension headers} + * for the requirements of this feature, most notably: + * - The header name must be prefixed with `x-goog-` + * - The header name must be all lowercase + * + * Note: Multi-valued header passed as an array in the extensionHeaders + * object is converted into a string, delimited by `,` with + * no space. Requests made using the signed URL will need to + * delimit multi-valued headers using a single `,` as well, or + * else the server will report a mismatched signature. + * @property {object} [config.queryParams] Additional query parameters to include + * in the signed URL. + * @param {GetSignedUrlCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * //- + * // Generate a URL that allows temporary access to list files in a bucket. + * //- + * const request = require('request'); + * + * const config = { + * action: 'list', + * expires: '03-17-2025' + * }; + * + * bucket.getSignedUrl(config, function(err, url) { + * if (err) { + * console.error(err); + * return; + * } + * + * // The bucket is now available to be listed from this URL. + * request(url, function(err, resp) { + * // resp.statusCode = 200 + * }); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.getSignedUrl(config).then(function(data) { + * const url = data[0]; + * }); + * ``` + */ + getSignedUrl(cfg, callback) { + const method = BucketActionToHTTPMethod[cfg.action]; + const signConfig = { + method, + expires: cfg.expires, + version: cfg.version, + cname: cfg.cname, + extensionHeaders: cfg.extensionHeaders || {}, + queryParams: cfg.queryParams || {}, + host: cfg.host, + signingEndpoint: cfg.signingEndpoint, + }; + if (!this.signer) { + this.signer = new signer_js_1.URLSigner(this.storage.authClient, this, undefined, this.storage); + } + this.signer + .getSignedUrl(signConfig) + .then(signedUrl => callback(null, signedUrl), callback); + } + /** + * @callback BucketLockCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Lock a previously-defined retention policy. This will prevent changes to + * the policy. + * + * @throws {Error} if a metageneration is not provided. + * + * @param {number|string} metageneration The bucket's metageneration. This is + * accessible from calling {@link File#getMetadata}. + * @param {BucketLockCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const bucket = storage.bucket('albums'); + * + * const metageneration = 2; + * + * bucket.lock(metageneration, function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.lock(metageneration).then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + lock(metageneration, callback) { + const metatype = typeof metageneration; + if (metatype !== 'number' && metatype !== 'string') { + throw new Error(BucketExceptionMessages.METAGENERATION_NOT_PROVIDED); + } + this.request({ + method: 'POST', + uri: '/lockRetentionPolicy', + qs: { + ifMetagenerationMatch: metageneration, + }, + }, callback); + } + /** + * @typedef {object} RestoreOptions Options for Bucket#restore(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/restore#resource| Object resource}. + * @param {number} [generation] If present, selects a specific revision of this object. + * @param {string} [projection] Specifies the set of properties to return. If used, must be 'full' or 'noAcl'. + */ + /** + * Restores a soft-deleted bucket + * @param {RestoreOptions} options Restore options. + * @returns {Promise} + */ + async restore(options) { + const [bucket] = await this.request({ + method: 'POST', + uri: '/restore', + qs: options, + }); + return bucket; + } + /** + * @typedef {array} MakeBucketPrivateResponse + * @property {File[]} 0 List of files made private. + */ + /** + * @callback MakeBucketPrivateCallback + * @param {?Error} err Request error, if any. + * @param {File[]} files List of files made private. + */ + /** + * @typedef {object} MakeBucketPrivateOptions + * @property {boolean} [includeFiles=false] Make each file in the bucket + * private. + * @property {Metadata} [metadata] Define custom metadata properties to define + * along with the operation. + * @property {boolean} [force] Queue errors occurred while making files + * private until all files have been processed. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * Make the bucket listing private. + * + * You may also choose to make the contents of the bucket private by + * specifying `includeFiles: true`. This will automatically run + * {@link File#makePrivate} for every file in the bucket. + * + * When specifying `includeFiles: true`, use `force: true` to delay execution + * of your callback until all files have been processed. By default, the + * callback is executed after the first error. Use `force` to queue such + * errors until all files have been processed, after which they will be + * returned as an array as the first argument to your callback. + * + * NOTE: This may cause the process to be long-running and use a high number + * of requests. Use with caution. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch| Buckets: patch API Documentation} + * + * @param {MakeBucketPrivateOptions} [options] Configuration options. + * @param {boolean} [options.includeFiles=false] Make each file in the bucket + * private. + * @param {Metadata} [options.metadata] Define custom metadata properties to define + * along with the operation. + * @param {boolean} [options.force] Queue errors occurred while making files + * private until all files have been processed. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {MakeBucketPrivateCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Make the bucket private. + * //- + * bucket.makePrivate(function(err) {}); + * + * //- + * // Make the bucket and its contents private. + * //- + * const opts = { + * includeFiles: true + * }; + * + * bucket.makePrivate(opts, function(err, files) { + * // `err`: + * // The first error to occur, otherwise null. + * // + * // `files`: + * // Array of files successfully made private in the bucket. + * }); + * + * //- + * // Make the bucket and its contents private, using force to suppress errors + * // until all files have been processed. + * //- + * const opts = { + * includeFiles: true, + * force: true + * }; + * + * bucket.makePrivate(opts, function(errors, files) { + * // `errors`: + * // Array of errors if any occurred, otherwise null. + * // + * // `files`: + * // Array of files successfully made private in the bucket. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.makePrivate(opts).then(function(data) { + * const files = data[0]; + * }); + * ``` + */ + makePrivate(optionsOrCallback, callback) { + var _a, _b, _c, _d; + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + options.private = true; + const query = { + predefinedAcl: 'projectPrivate', + }; + if (options.userProject) { + query.userProject = options.userProject; + } + if ((_a = options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) { + query.ifGenerationMatch = options.preconditionOpts.ifGenerationMatch; + } + if ((_b = options.preconditionOpts) === null || _b === void 0 ? void 0 : _b.ifGenerationNotMatch) { + query.ifGenerationNotMatch = + options.preconditionOpts.ifGenerationNotMatch; + } + if ((_c = options.preconditionOpts) === null || _c === void 0 ? void 0 : _c.ifMetagenerationMatch) { + query.ifMetagenerationMatch = + options.preconditionOpts.ifMetagenerationMatch; + } + if ((_d = options.preconditionOpts) === null || _d === void 0 ? void 0 : _d.ifMetagenerationNotMatch) { + query.ifMetagenerationNotMatch = + options.preconditionOpts.ifMetagenerationNotMatch; + } + // You aren't allowed to set both predefinedAcl & acl properties on a bucket + // so acl must explicitly be nullified. + const metadata = { ...options.metadata, acl: null }; + this.setMetadata(metadata, query, (err) => { + if (err) { + callback(err); + } + const internalCall = () => { + if (options.includeFiles) { + return (0, util_1.promisify)(this.makeAllFilesPublicPrivate_).call(this, options); + } + return Promise.resolve([]); + }; + internalCall() + .then(files => callback(null, files)) + .catch(callback); + }); + } + /** + * @typedef {object} MakeBucketPublicOptions + * @property {boolean} [includeFiles=false] Make each file in the bucket + * private. + * @property {boolean} [force] Queue errors occurred while making files + * private until all files have been processed. + */ + /** + * @callback MakeBucketPublicCallback + * @param {?Error} err Request error, if any. + * @param {File[]} files List of files made public. + */ + /** + * @typedef {array} MakeBucketPublicResponse + * @property {File[]} 0 List of files made public. + */ + /** + * Make the bucket publicly readable. + * + * You may also choose to make the contents of the bucket publicly readable by + * specifying `includeFiles: true`. This will automatically run + * {@link File#makePublic} for every file in the bucket. + * + * When specifying `includeFiles: true`, use `force: true` to delay execution + * of your callback until all files have been processed. By default, the + * callback is executed after the first error. Use `force` to queue such + * errors until all files have been processed, after which they will be + * returned as an array as the first argument to your callback. + * + * NOTE: This may cause the process to be long-running and use a high number + * of requests. Use with caution. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch| Buckets: patch API Documentation} + * + * @param {MakeBucketPublicOptions} [options] Configuration options. + * @param {boolean} [options.includeFiles=false] Make each file in the bucket + * private. + * @param {boolean} [options.force] Queue errors occurred while making files + * private until all files have been processed. + * @param {MakeBucketPublicCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Make the bucket publicly readable. + * //- + * bucket.makePublic(function(err) {}); + * + * //- + * // Make the bucket and its contents publicly readable. + * //- + * const opts = { + * includeFiles: true + * }; + * + * bucket.makePublic(opts, function(err, files) { + * // `err`: + * // The first error to occur, otherwise null. + * // + * // `files`: + * // Array of files successfully made public in the bucket. + * }); + * + * //- + * // Make the bucket and its contents publicly readable, using force to + * // suppress errors until all files have been processed. + * //- + * const opts = { + * includeFiles: true, + * force: true + * }; + * + * bucket.makePublic(opts, function(errors, files) { + * // `errors`: + * // Array of errors if any occurred, otherwise null. + * // + * // `files`: + * // Array of files successfully made public in the bucket. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.makePublic(opts).then(function(data) { + * const files = data[0]; + * }); + * ``` + */ + makePublic(optionsOrCallback, callback) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + const req = { public: true, ...options }; + this.acl + .add({ + entity: 'allUsers', + role: 'READER', + }) + .then(() => { + return this.acl.default.add({ + entity: 'allUsers', + role: 'READER', + }); + }) + .then(() => { + if (req.includeFiles) { + return (0, util_1.promisify)(this.makeAllFilesPublicPrivate_).call(this, req); + } + return []; + }) + .then(files => callback(null, files), callback); + } + /** + * Get a reference to a Cloud Pub/Sub Notification. + * + * @param {string} id ID of notification. + * @returns {Notification} + * @see Notification + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const notification = bucket.notification('1'); + * ``` + */ + notification(id) { + if (!id) { + throw new Error(BucketExceptionMessages.SUPPLY_NOTIFICATION_ID); + } + return new notification_js_1.Notification(this, id); + } + /** + * Remove an already-existing retention policy from this bucket, if it is not + * locked. + * + * @param {SetBucketMetadataCallback} [callback] Callback function. + * @param {SetBucketMetadataOptions} [options] Options, including precondition options + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const bucket = storage.bucket('albums'); + * + * bucket.removeRetentionPeriod(function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.removeRetentionPeriod().then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + removeRetentionPeriod(optionsOrCallback, callback) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + this.setMetadata({ + retentionPolicy: null, + }, options, callback); + } + /** + * Makes request and applies userProject query parameter if necessary. + * + * @private + * + * @param {object} reqOpts - The request options. + * @param {function} callback - The callback function. + */ + request(reqOpts, callback) { + if (this.userProject && (!reqOpts.qs || !reqOpts.qs.userProject)) { + reqOpts.qs = { ...reqOpts.qs, userProject: this.userProject }; + } + return super.request(reqOpts, callback); + } + /** + * @deprecated + * @typedef {array} SetLabelsResponse + * @property {object} 0 The bucket metadata. + */ + /** + * @deprecated + * @callback SetLabelsCallback + * @param {?Error} err Request error, if any. + * @param {object} metadata The bucket metadata. + */ + /** + * @deprecated + * @typedef {object} SetLabelsOptions Configuration options for Bucket#setLabels(). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @deprecated Use setMetadata directly. + * Set labels on the bucket. + * + * This makes an underlying call to {@link Bucket#setMetadata}, which + * is a PATCH request. This means an individual label can be overwritten, but + * unmentioned labels will not be touched. + * + * @param {object} labels Labels to set on the bucket. + * @param {SetLabelsOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {SetLabelsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * const labels = { + * labelone: 'labelonevalue', + * labeltwo: 'labeltwovalue' + * }; + * + * bucket.setLabels(labels, function(err, metadata) { + * if (!err) { + * // Labels set successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.setLabels(labels).then(function(data) { + * const metadata = data[0]; + * }); + * ``` + */ + setLabels(labels, optionsOrCallback, callback) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + callback = callback || index_js_1.util.noop; + this.setMetadata({ labels }, options, callback); + } + setMetadata(metadata, optionsOrCallback, cb) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + cb = + typeof optionsOrCallback === 'function' + ? optionsOrCallback + : cb; + this.disableAutoRetryConditionallyIdempotent_(this.methods.setMetadata, AvailableServiceObjectMethods.setMetadata, options); + super + .setMetadata(metadata, options) + .then(resp => cb(null, ...resp)) + .catch(cb) + .finally(() => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + }); + } + /** + * Lock all objects contained in the bucket, based on their creation time. Any + * attempt to overwrite or delete objects younger than the retention period + * will result in a `PERMISSION_DENIED` error. + * + * An unlocked retention policy can be modified or removed from the bucket via + * {@link File#removeRetentionPeriod} and {@link File#setRetentionPeriod}. A + * locked retention policy cannot be removed or shortened in duration for the + * lifetime of the bucket. Attempting to remove or decrease period of a locked + * retention policy will result in a `PERMISSION_DENIED` error. You can still + * increase the policy. + * + * @param {*} duration In seconds, the minimum retention time for all objects + * contained in this bucket. + * @param {SetBucketMetadataCallback} [callback] Callback function. + * @param {SetBucketMetadataCallback} [options] Options, including precondition options. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const bucket = storage.bucket('albums'); + * + * const DURATION_SECONDS = 15780000; // 6 months. + * + * //- + * // Lock the objects in this bucket for 6 months. + * //- + * bucket.setRetentionPeriod(DURATION_SECONDS, function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.setRetentionPeriod(DURATION_SECONDS).then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + setRetentionPeriod(duration, optionsOrCallback, callback) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + this.setMetadata({ + retentionPolicy: { + retentionPeriod: duration.toString(), + }, + }, options, callback); + } + /** + * + * @typedef {object} Cors + * @property {number} [maxAgeSeconds] The number of seconds the browser is + * allowed to make requests before it must repeat the preflight request. + * @property {string[]} [method] HTTP method allowed for cross origin resource + * sharing with this bucket. + * @property {string[]} [origin] an origin allowed for cross origin resource + * sharing with this bucket. + * @property {string[]} [responseHeader] A header allowed for cross origin + * resource sharing with this bucket. + */ + /** + * This can be used to set the CORS configuration on the bucket. + * + * The configuration will be overwritten with the value passed into this. + * + * @param {Cors[]} corsConfiguration The new CORS configuration to set + * @param {number} [corsConfiguration.maxAgeSeconds] The number of seconds the browser is + * allowed to make requests before it must repeat the preflight request. + * @param {string[]} [corsConfiguration.method] HTTP method allowed for cross origin resource + * sharing with this bucket. + * @param {string[]} [corsConfiguration.origin] an origin allowed for cross origin resource + * sharing with this bucket. + * @param {string[]} [corsConfiguration.responseHeader] A header allowed for cross origin + * resource sharing with this bucket. + * @param {SetBucketMetadataCallback} [callback] Callback function. + * @param {SetBucketMetadataOptions} [options] Options, including precondition options. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const bucket = storage.bucket('albums'); + * + * const corsConfiguration = [{maxAgeSeconds: 3600}]; // 1 hour + * bucket.setCorsConfiguration(corsConfiguration); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.setCorsConfiguration(corsConfiguration).then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + setCorsConfiguration(corsConfiguration, optionsOrCallback, callback) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + this.setMetadata({ + cors: corsConfiguration, + }, options, callback); + } + /** + * @typedef {object} SetBucketStorageClassOptions + * @property {string} [userProject] - The ID of the project which will be + * billed for the request. + */ + /** + * @callback SetBucketStorageClassCallback + * @param {?Error} err Request error, if any. + */ + /** + * Set the default storage class for new files in this bucket. + * + * See {@link https://cloud.google.com/storage/docs/storage-classes| Storage Classes} + * + * @param {string} storageClass The new storage class. (`standard`, + * `nearline`, `coldline`, or `archive`). + * **Note:** The storage classes `multi_regional`, `regional`, and + * `durable_reduced_availability` are now legacy and will be deprecated in + * the future. + * @param {object} [options] Configuration options. + * @param {string} [options.userProject] - The ID of the project which will be + * billed for the request. + * @param {SetStorageClassCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.setStorageClass('nearline', function(err, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * // The storage class was updated successfully. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.setStorageClass('nearline').then(function() {}); + * ``` + */ + setStorageClass(storageClass, optionsOrCallback, callback) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + // In case we get input like `storageClass`, convert to `storage_class`. + storageClass = storageClass + .replace(/-/g, '_') + .replace(/([a-z])([A-Z])/g, (_, low, up) => { + return low + '_' + up; + }) + .toUpperCase(); + this.setMetadata({ storageClass }, options, callback); + } + /** + * Set a user project to be billed for all requests made from this Bucket + * object and any files referenced from this Bucket object. + * + * @param {string} userProject The user project. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.setUserProject('grape-spaceship-123'); + * ``` + */ + setUserProject(userProject) { + this.userProject = userProject; + const methods = [ + 'create', + 'delete', + 'exists', + 'get', + 'getMetadata', + 'setMetadata', + ]; + methods.forEach(method => { + const methodConfig = this.methods[method]; + if (typeof methodConfig === 'object') { + if (typeof methodConfig.reqOpts === 'object') { + Object.assign(methodConfig.reqOpts.qs, { userProject }); + } + else { + methodConfig.reqOpts = { + qs: { userProject }, + }; + } + } + }); + } + /** + * @typedef {object} UploadOptions Configuration options for Bucket#upload(). + * @property {string|File} [destination] The place to save + * your file. If given a string, the file will be uploaded to the bucket + * using the string as a filename. When given a File object, your local + * file will be uploaded to the File object's bucket and under the File + * object's name. Lastly, when this argument is omitted, the file is uploaded + * to your bucket using the name of the local file. + * @property {string} [encryptionKey] A custom encryption key. See + * {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}. + * @property {boolean} [gzip] Automatically gzip the file. This will set + * `options.metadata.contentEncoding` to `gzip`. + * @property {string} [kmsKeyName] The name of the Cloud KMS key that will + * be used to encrypt the object. Must be in the format: + * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`. + * @property {object} [metadata] See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON| Objects: insert request body}. + * @property {string} [offset] The starting byte of the upload stream, for + * resuming an interrupted upload. Defaults to 0. + * @property {string} [predefinedAcl] Apply a predefined set of access + * controls to this object. + * + * Acceptable values are: + * - **`authenticatedRead`** - Object owner gets `OWNER` access, and + * `allAuthenticatedUsers` get `READER` access. + * + * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and + * project team owners get `OWNER` access. + * + * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project + * team owners get `READER` access. + * + * - **`private`** - Object owner gets `OWNER` access. + * + * - **`projectPrivate`** - Object owner gets `OWNER` access, and project + * team members get access according to their roles. + * + * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers` + * get `READER` access. + * @property {boolean} [private] Make the uploaded file private. (Alias for + * `options.predefinedAcl = 'private'`) + * @property {boolean} [public] Make the uploaded file public. (Alias for + * `options.predefinedAcl = 'publicRead'`) + * @property {boolean} [resumable=true] Resumable uploads are automatically + * enabled and must be shut off explicitly by setting to false. + * @property {number} [timeout=60000] Set the HTTP request timeout in + * milliseconds. This option is not available for resumable uploads. + * Default: `60000` + * @property {string} [uri] The URI for an already-created resumable + * upload. See {@link File#createResumableUpload}. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {string|boolean} [validation] Possible values: `"md5"`, + * `"crc32c"`, or `false`. By default, data integrity is validated with an + * MD5 checksum for maximum reliability. CRC32c will provide better + * performance with less reliability. You may also choose to skip + * validation completely, however this is **not recommended**. + */ + /** + * @typedef {array} UploadResponse + * @property {object} 0 The uploaded {@link File}. + * @property {object} 1 The full API response. + */ + /** + * @callback UploadCallback + * @param {?Error} err Request error, if any. + * @param {object} file The uploaded {@link File}. + * @param {object} apiResponse The full API response. + */ + /** + * Upload a file to the bucket. This is a convenience method that wraps + * {@link File#createWriteStream}. + * + * Resumable uploads are enabled by default + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload#uploads| Upload Options (Simple or Resumable)} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert| Objects: insert API Documentation} + * + * @param {string} pathString The fully qualified path to the file you + * wish to upload to your bucket. + * @param {UploadOptions} [options] Configuration options. + * @param {string|File} [options.destination] The place to save + * your file. If given a string, the file will be uploaded to the bucket + * using the string as a filename. When given a File object, your local + * file will be uploaded to the File object's bucket and under the File + * object's name. Lastly, when this argument is omitted, the file is uploaded + * to your bucket using the name of the local file. + * @param {string} [options.encryptionKey] A custom encryption key. See + * {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}. + * @param {boolean} [options.gzip] Automatically gzip the file. This will set + * `options.metadata.contentEncoding` to `gzip`. + * @param {string} [options.kmsKeyName] The name of the Cloud KMS key that will + * be used to encrypt the object. Must be in the format: + * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`. + * @param {object} [options.metadata] See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON| Objects: insert request body}. + * @param {string} [options.offset] The starting byte of the upload stream, for + * resuming an interrupted upload. Defaults to 0. + * @param {string} [options.predefinedAcl] Apply a predefined set of access + * controls to this object. + * Acceptable values are: + * - **`authenticatedRead`** - Object owner gets `OWNER` access, and + * `allAuthenticatedUsers` get `READER` access. + * + * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and + * project team owners get `OWNER` access. + * + * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project + * team owners get `READER` access. + * + * - **`private`** - Object owner gets `OWNER` access. + * + * - **`projectPrivate`** - Object owner gets `OWNER` access, and project + * team members get access according to their roles. + * + * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers` + * get `READER` access. + * @param {boolean} [options.private] Make the uploaded file private. (Alias for + * `options.predefinedAcl = 'private'`) + * @param {boolean} [options.public] Make the uploaded file public. (Alias for + * `options.predefinedAcl = 'publicRead'`) + * @param {boolean} [options.resumable=true] Resumable uploads are automatically + * enabled and must be shut off explicitly by setting to false. + * @param {number} [options.timeout=60000] Set the HTTP request timeout in + * milliseconds. This option is not available for resumable uploads. + * Default: `60000` + * @param {string} [options.uri] The URI for an already-created resumable + * upload. See {@link File#createResumableUpload}. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {string|boolean} [options.validation] Possible values: `"md5"`, + * `"crc32c"`, or `false`. By default, data integrity is validated with an + * MD5 checksum for maximum reliability. CRC32c will provide better + * performance with less reliability. You may also choose to skip + * validation completely, however this is **not recommended**. + * @param {UploadCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Upload a file from a local path. + * //- + * bucket.upload('/local/path/image.png', function(err, file, apiResponse) { + * // Your bucket now contains: + * // - "image.png" (with the contents of `/local/path/image.png') + * + * // `file` is an instance of a File object that refers to your new file. + * }); + * + * + * //- + * // It's not always that easy. You will likely want to specify the filename + * // used when your new file lands in your bucket. + * // + * // You may also want to set metadata or customize other options. + * //- + * const options = { + * destination: 'new-image.png', + * validation: 'crc32c', + * metadata: { + * metadata: { + * event: 'Fall trip to the zoo' + * } + * } + * }; + * + * bucket.upload('local-image.png', options, function(err, file) { + * // Your bucket now contains: + * // - "new-image.png" (with the contents of `local-image.png') + * + * // `file` is an instance of a File object that refers to your new file. + * }); + * + * //- + * // You can also have a file gzip'd on the fly. + * //- + * bucket.upload('index.html', { gzip: true }, function(err, file) { + * // Your bucket now contains: + * // - "index.html" (automatically compressed with gzip) + * + * // Downloading the file with `file.download` will automatically decode + * the + * // file. + * }); + * + * //- + * // You may also re-use a File object, {File}, that references + * // the file you wish to create or overwrite. + * //- + * const options = { + * destination: bucket.file('existing-file.png'), + * resumable: false + * }; + * + * bucket.upload('local-img.png', options, function(err, newFile) { + * // Your bucket now contains: + * // - "existing-file.png" (with the contents of `local-img.png') + * + * // Note: + * // The `newFile` parameter is equal to `file`. + * }); + * + * //- + * // To use + * // + * // Customer-supplied Encryption Keys, provide the `encryptionKey` + * option. + * //- + * const crypto = require('crypto'); + * const encryptionKey = crypto.randomBytes(32); + * + * bucket.upload('img.png', { + * encryptionKey: encryptionKey + * }, function(err, newFile) { + * // `img.png` was uploaded with your custom encryption key. + * + * // `newFile` is already configured to use the encryption key when making + * // operations on the remote object. + * + * // However, to use your encryption key later, you must create a `File` + * // instance with the `key` supplied: + * const file = bucket.file('img.png', { + * encryptionKey: encryptionKey + * }); + * + * // Or with `file#setEncryptionKey`: + * const file = bucket.file('img.png'); + * file.setEncryptionKey(encryptionKey); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.upload('local-image.png').then(function(data) { + * const file = data[0]; + * }); + * + * To upload a file from a URL, use {@link File#createWriteStream}. + * + * ``` + * @example include:samples/files.js + * region_tag:storage_upload_file + * Another example: + * + * @example include:samples/encryption.js + * region_tag:storage_upload_encrypted_file + * Example of uploading an encrypted file: + */ + upload(pathString, optionsOrCallback, callback) { + var _a, _b; + const upload = (numberOfRetries) => { + const returnValue = (0, async_retry_1.default)(async (bail) => { + await new Promise((resolve, reject) => { + var _a, _b; + if (numberOfRetries === 0 && + ((_b = (_a = newFile === null || newFile === void 0 ? void 0 : newFile.storage) === null || _a === void 0 ? void 0 : _a.retryOptions) === null || _b === void 0 ? void 0 : _b.autoRetry)) { + newFile.storage.retryOptions.autoRetry = false; + } + const writable = newFile.createWriteStream(options); + if (options.onUploadProgress) { + writable.on('progress', options.onUploadProgress); + } + fs.createReadStream(pathString) + .on('error', bail) + .pipe(writable) + .on('error', err => { + if (this.storage.retryOptions.autoRetry && + this.storage.retryOptions.retryableErrorFn(err)) { + return reject(err); + } + else { + return bail(err); + } + }) + .on('finish', () => { + return resolve(); + }); + }); + }, { + retries: numberOfRetries, + factor: this.storage.retryOptions.retryDelayMultiplier, + maxTimeout: this.storage.retryOptions.maxRetryDelay * 1000, //convert to milliseconds + maxRetryTime: this.storage.retryOptions.totalTimeout * 1000, //convert to milliseconds + }); + if (!callback) { + return returnValue; + } + else { + return returnValue + .then(() => { + if (callback) { + return callback(null, newFile, newFile.metadata); + } + }) + .catch(callback); + } + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (global['GCLOUD_SANDBOX_ENV']) { + return; + } + let options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + options = Object.assign({ + metadata: {}, + }, options); + // Do not retry if precondition option ifGenerationMatch is not set + // because this is a file operation + let maxRetries = this.storage.retryOptions.maxRetries; + if ((((_a = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) === undefined && + ((_b = this.instancePreconditionOpts) === null || _b === void 0 ? void 0 : _b.ifGenerationMatch) === undefined && + this.storage.retryOptions.idempotencyStrategy === + storage_js_1.IdempotencyStrategy.RetryConditional) || + this.storage.retryOptions.idempotencyStrategy === + storage_js_1.IdempotencyStrategy.RetryNever) { + maxRetries = 0; + } + let newFile; + if (options.destination instanceof file_js_1.File) { + newFile = options.destination; + } + else if (options.destination !== null && + typeof options.destination === 'string') { + // Use the string as the name of the file. + newFile = this.file(options.destination, { + encryptionKey: options.encryptionKey, + kmsKeyName: options.kmsKeyName, + preconditionOpts: this.instancePreconditionOpts, + }); + } + else { + // Resort to using the name of the incoming file. + const destination = path.basename(pathString); + newFile = this.file(destination, { + encryptionKey: options.encryptionKey, + kmsKeyName: options.kmsKeyName, + preconditionOpts: this.instancePreconditionOpts, + }); + } + upload(maxRetries); + } + /** + * @private + * + * @typedef {object} MakeAllFilesPublicPrivateOptions + * @property {boolean} [force] Suppress errors until all files have been + * processed. + * @property {boolean} [private] Make files private. + * @property {boolean} [public] Make files public. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @private + * + * @callback SetBucketMetadataCallback + * @param {?Error} err Request error, if any. + * @param {File[]} files Files that were updated. + */ + /** + * @typedef {array} MakeAllFilesPublicPrivateResponse + * @property {File[]} 0 List of files affected. + */ + /** + * Iterate over all of a bucket's files, calling `file.makePublic()` (public) + * or `file.makePrivate()` (private) on each. + * + * Operations are performed in parallel, up to 10 at once. The first error + * breaks the loop, and will execute the provided callback with it. Specify + * `{ force: true }` to suppress the errors. + * + * @private + * + * @param {MakeAllFilesPublicPrivateOptions} [options] Configuration options. + * @param {boolean} [options.force] Suppress errors until all files have been + * processed. + * @param {boolean} [options.private] Make files private. + * @param {boolean} [options.public] Make files public. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + + * @param {MakeAllFilesPublicPrivateCallback} callback Callback function. + * + * @return {Promise} + */ + makeAllFilesPublicPrivate_(optionsOrCallback, callback) { + const MAX_PARALLEL_LIMIT = 10; + const errors = []; + const updatedFiles = []; + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + const processFile = async (file) => { + try { + await (options.public ? file.makePublic() : file.makePrivate(options)); + updatedFiles.push(file); + } + catch (e) { + if (!options.force) { + throw e; + } + errors.push(e); + } + }; + this.getFiles(options) + .then(([files]) => { + const limit = (0, p_limit_1.default)(MAX_PARALLEL_LIMIT); + const promises = files.map(file => { + return limit(() => processFile(file)); + }); + return Promise.all(promises); + }) + .then(() => callback(errors.length > 0 ? errors : null, updatedFiles), err => callback(err, updatedFiles)); + } + getId() { + return this.id; + } + disableAutoRetryConditionallyIdempotent_( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + coreOpts, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + methodType, localPreconditionOptions) { + var _a, _b; + if (typeof coreOpts === 'object' && + ((_b = (_a = coreOpts === null || coreOpts === void 0 ? void 0 : coreOpts.reqOpts) === null || _a === void 0 ? void 0 : _a.qs) === null || _b === void 0 ? void 0 : _b.ifMetagenerationMatch) === undefined && + (localPreconditionOptions === null || localPreconditionOptions === void 0 ? void 0 : localPreconditionOptions.ifMetagenerationMatch) === undefined && + (methodType === AvailableServiceObjectMethods.setMetadata || + methodType === AvailableServiceObjectMethods.delete) && + this.storage.retryOptions.idempotencyStrategy === + storage_js_1.IdempotencyStrategy.RetryConditional) { + this.storage.retryOptions.autoRetry = false; + } + else if (this.storage.retryOptions.idempotencyStrategy === + storage_js_1.IdempotencyStrategy.RetryNever) { + this.storage.retryOptions.autoRetry = false; + } + } +} +exports.Bucket = Bucket; +/*! Developer Documentation + * + * These methods can be auto-paginated. + */ +paginator_1.paginator.extend(Bucket, 'getFiles'); +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +(0, promisify_1.promisifyAll)(Bucket, { + exclude: ['cloudStorageURI', 'request', 'file', 'notification', 'restore'], +}); diff --git a/node_modules/@google-cloud/storage/build/cjs/src/channel.d.ts b/node_modules/@google-cloud/storage/build/cjs/src/channel.d.ts new file mode 100644 index 0000000..6bb52b9 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/channel.d.ts @@ -0,0 +1,33 @@ +import { BaseMetadata, ServiceObject } from './nodejs-common/index.js'; +import { Storage } from './storage.js'; +export interface StopCallback { + (err: Error | null, apiResponse?: unknown): void; +} +/** + * Create a channel object to interact with a Cloud Storage channel. + * + * See {@link https://cloud.google.com/storage/docs/object-change-notification| Object Change Notification} + * + * @class + * + * @param {string} id The ID of the channel. + * @param {string} resourceId The resource ID of the channel. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const channel = storage.channel('id', 'resource-id'); + * ``` + */ +declare class Channel extends ServiceObject { + constructor(storage: Storage, id: string, resourceId: string); + stop(): Promise; + stop(callback: StopCallback): void; +} +/** + * Reference to the {@link Channel} class. + * @name module:@google-cloud/storage.Channel + * @see Channel + */ +export { Channel }; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/channel.js b/node_modules/@google-cloud/storage/build/cjs/src/channel.js new file mode 100644 index 0000000..5b9c91c --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/channel.js @@ -0,0 +1,104 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Channel = void 0; +const index_js_1 = require("./nodejs-common/index.js"); +const promisify_1 = require("@google-cloud/promisify"); +/** + * Create a channel object to interact with a Cloud Storage channel. + * + * See {@link https://cloud.google.com/storage/docs/object-change-notification| Object Change Notification} + * + * @class + * + * @param {string} id The ID of the channel. + * @param {string} resourceId The resource ID of the channel. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const channel = storage.channel('id', 'resource-id'); + * ``` + */ +class Channel extends index_js_1.ServiceObject { + constructor(storage, id, resourceId) { + const config = { + parent: storage, + baseUrl: '/channels', + // An ID shouldn't be included in the API requests. + // RE: + // https://github.com/GoogleCloudPlatform/google-cloud-node/issues/1145 + id: '', + methods: { + // Only need `request`. + }, + }; + super(config); + this.metadata.id = id; + this.metadata.resourceId = resourceId; + } + /** + * @typedef {array} StopResponse + * @property {object} 0 The full API response. + */ + /** + * @callback StopCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Stop this channel. + * + * @param {StopCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const channel = storage.channel('id', 'resource-id'); + * channel.stop(function(err, apiResponse) { + * if (!err) { + * // Channel stopped successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * channel.stop().then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + stop(callback) { + callback = callback || index_js_1.util.noop; + this.request({ + method: 'POST', + uri: '/stop', + json: this.metadata, + }, (err, apiResponse) => { + callback(err, apiResponse); + }); + } +} +exports.Channel = Channel; +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +(0, promisify_1.promisifyAll)(Channel); diff --git a/node_modules/@google-cloud/storage/build/cjs/src/crc32c.d.ts b/node_modules/@google-cloud/storage/build/cjs/src/crc32c.d.ts new file mode 100644 index 0000000..8b5a701 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/crc32c.d.ts @@ -0,0 +1,143 @@ +import { PathLike } from 'fs'; +/** + * Ported from {@link https://github.com/google/crc32c/blob/21fc8ef30415a635e7351ffa0e5d5367943d4a94/src/crc32c_portable.cc#L16-L59 github.com/google/crc32c} + */ +declare const CRC32C_EXTENSIONS: readonly [0, 4067132163, 3778769143, 324072436, 3348797215, 904991772, 648144872, 3570033899, 2329499855, 2024987596, 1809983544, 2575936315, 1296289744, 3207089363, 2893594407, 1578318884, 274646895, 3795141740, 4049975192, 51262619, 3619967088, 632279923, 922689671, 3298075524, 2592579488, 1760304291, 2075979607, 2312596564, 1562183871, 2943781820, 3156637768, 1313733451, 549293790, 3537243613, 3246849577, 871202090, 3878099393, 357341890, 102525238, 4101499445, 2858735121, 1477399826, 1264559846, 3107202533, 1845379342, 2677391885, 2361733625, 2125378298, 820201905, 3263744690, 3520608582, 598981189, 4151959214, 85089709, 373468761, 3827903834, 3124367742, 1213305469, 1526817161, 2842354314, 2107672161, 2412447074, 2627466902, 1861252501, 1098587580, 3004210879, 2688576843, 1378610760, 2262928035, 1955203488, 1742404180, 2511436119, 3416409459, 969524848, 714683780, 3639785095, 205050476, 4266873199, 3976438427, 526918040, 1361435347, 2739821008, 2954799652, 1114974503, 2529119692, 1691668175, 2005155131, 2247081528, 3690758684, 697762079, 986182379, 3366744552, 476452099, 3993867776, 4250756596, 255256311, 1640403810, 2477592673, 2164122517, 1922457750, 2791048317, 1412925310, 1197962378, 3037525897, 3944729517, 427051182, 170179418, 4165941337, 746937522, 3740196785, 3451792453, 1070968646, 1905808397, 2213795598, 2426610938, 1657317369, 3053634322, 1147748369, 1463399397, 2773627110, 4215344322, 153784257, 444234805, 3893493558, 1021025245, 3467647198, 3722505002, 797665321, 2197175160, 1889384571, 1674398607, 2443626636, 1164749927, 3070701412, 2757221520, 1446797203, 137323447, 4198817972, 3910406976, 461344835, 3484808360, 1037989803, 781091935, 3705997148, 2460548119, 1623424788, 1939049696, 2180517859, 1429367560, 2807687179, 3020495871, 1180866812, 410100952, 3927582683, 4182430767, 186734380, 3756733383, 763408580, 1053836080, 3434856499, 2722870694, 1344288421, 1131464017, 2971354706, 1708204729, 2545590714, 2229949006, 1988219213, 680717673, 3673779818, 3383336350, 1002577565, 4010310262, 493091189, 238226049, 4233660802, 2987750089, 1082061258, 1395524158, 2705686845, 1972364758, 2279892693, 2494862625, 1725896226, 952904198, 3399985413, 3656866545, 731699698, 4283874585, 222117402, 510512622, 3959836397, 3280807620, 837199303, 582374963, 3504198960, 68661723, 4135334616, 3844915500, 390545967, 1230274059, 3141532936, 2825850620, 1510247935, 2395924756, 2091215383, 1878366691, 2644384480, 3553878443, 565732008, 854102364, 3229815391, 340358836, 3861050807, 4117890627, 119113024, 1493875044, 2875275879, 3090270611, 1247431312, 2660249211, 1828433272, 2141937292, 2378227087, 3811616794, 291187481, 34330861, 4032846830, 615137029, 3603020806, 3314634738, 939183345, 1776939221, 2609017814, 2295496738, 2058945313, 2926798794, 1545135305, 1330124605, 3173225534, 4084100981, 17165430, 307568514, 3762199681, 888469610, 3332340585, 3587147933, 665062302, 2042050490, 2346497209, 2559330125, 1793573966, 3190661285, 1279665062, 1595330642, 2910671697]; +declare const CRC32C_EXTENSION_TABLE: Int32Array; +/** An interface for CRC32C hashing and validation */ +interface CRC32CValidator { + /** + * A method returning the CRC32C as a base64-encoded string. + * + * @example + * Hashing the string 'data' should return 'rth90Q==' + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.toString(); // 'rth90Q==' + * ``` + **/ + toString: () => string; + /** + * A method validating a base64-encoded CRC32C string. + * + * @example + * Should return `true` if the value matches, `false` otherwise + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.validate('DkjKuA=='); // false + * crc32c.validate('rth90Q=='); // true + * ``` + */ + validate: (value: string) => boolean; + /** + * A method for passing `Buffer`s for CRC32C generation. + * + * @example + * Hashing buffers from 'some ' and 'text\n' + * + * ```js + * const buffer1 = Buffer.from('some '); + * crc32c.update(buffer1); + * + * const buffer2 = Buffer.from('text\n'); + * crc32c.update(buffer2); + * + * crc32c.toString(); // 'DkjKuA==' + * ``` + */ + update: (data: Buffer) => void; +} +/** A function that generates a CRC32C Validator */ +interface CRC32CValidatorGenerator { + /** Should return a new, ready-to-use `CRC32CValidator` */ + (): CRC32CValidator; +} +declare const CRC32C_DEFAULT_VALIDATOR_GENERATOR: CRC32CValidatorGenerator; +declare const CRC32C_EXCEPTION_MESSAGES: { + readonly INVALID_INIT_BASE64_RANGE: (l: number) => string; + readonly INVALID_INIT_BUFFER_LENGTH: (l: number) => string; + readonly INVALID_INIT_INTEGER: (l: number) => string; +}; +declare class CRC32C implements CRC32CValidator { + #private; + /** + * Constructs a new `CRC32C` object. + * + * Reconstruction is recommended via the `CRC32C.from` static method. + * + * @param initialValue An initial CRC32C value - a signed 32-bit integer. + */ + constructor(initialValue?: number); + /** + * Calculates a CRC32C from a provided buffer. + * + * Implementation inspired from: + * - {@link https://github.com/google/crc32c/blob/21fc8ef30415a635e7351ffa0e5d5367943d4a94/src/crc32c_portable.cc github.com/google/crc32c} + * - {@link https://github.com/googleapis/python-crc32c/blob/a595e758c08df445a99c3bf132ee8e80a3ec4308/src/google_crc32c/python.py github.com/googleapis/python-crc32c} + * - {@link https://github.com/googleapis/java-storage/pull/1376/files github.com/googleapis/java-storage} + * + * @param data The `Buffer` to generate the CRC32C from + */ + update(data: Buffer): void; + /** + * Validates a provided input to the current CRC32C value. + * + * @param input A Buffer, `CRC32C`-compatible object, base64-encoded data (string), or signed 32-bit integer + */ + validate(input: Buffer | CRC32CValidator | string | number): boolean; + /** + * Returns a `Buffer` representation of the CRC32C value + */ + toBuffer(): Buffer; + /** + * Returns a JSON-compatible, base64-encoded representation of the CRC32C value. + * + * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify `JSON#stringify`} + */ + toJSON(): string; + /** + * Returns a base64-encoded representation of the CRC32C value. + * + * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString `Object#toString`} + */ + toString(): string; + /** + * Returns the `number` representation of the CRC32C value as a signed 32-bit integer + * + * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf `Object#valueOf`} + */ + valueOf(): number; + static readonly CRC32C_EXTENSIONS: readonly [0, 4067132163, 3778769143, 324072436, 3348797215, 904991772, 648144872, 3570033899, 2329499855, 2024987596, 1809983544, 2575936315, 1296289744, 3207089363, 2893594407, 1578318884, 274646895, 3795141740, 4049975192, 51262619, 3619967088, 632279923, 922689671, 3298075524, 2592579488, 1760304291, 2075979607, 2312596564, 1562183871, 2943781820, 3156637768, 1313733451, 549293790, 3537243613, 3246849577, 871202090, 3878099393, 357341890, 102525238, 4101499445, 2858735121, 1477399826, 1264559846, 3107202533, 1845379342, 2677391885, 2361733625, 2125378298, 820201905, 3263744690, 3520608582, 598981189, 4151959214, 85089709, 373468761, 3827903834, 3124367742, 1213305469, 1526817161, 2842354314, 2107672161, 2412447074, 2627466902, 1861252501, 1098587580, 3004210879, 2688576843, 1378610760, 2262928035, 1955203488, 1742404180, 2511436119, 3416409459, 969524848, 714683780, 3639785095, 205050476, 4266873199, 3976438427, 526918040, 1361435347, 2739821008, 2954799652, 1114974503, 2529119692, 1691668175, 2005155131, 2247081528, 3690758684, 697762079, 986182379, 3366744552, 476452099, 3993867776, 4250756596, 255256311, 1640403810, 2477592673, 2164122517, 1922457750, 2791048317, 1412925310, 1197962378, 3037525897, 3944729517, 427051182, 170179418, 4165941337, 746937522, 3740196785, 3451792453, 1070968646, 1905808397, 2213795598, 2426610938, 1657317369, 3053634322, 1147748369, 1463399397, 2773627110, 4215344322, 153784257, 444234805, 3893493558, 1021025245, 3467647198, 3722505002, 797665321, 2197175160, 1889384571, 1674398607, 2443626636, 1164749927, 3070701412, 2757221520, 1446797203, 137323447, 4198817972, 3910406976, 461344835, 3484808360, 1037989803, 781091935, 3705997148, 2460548119, 1623424788, 1939049696, 2180517859, 1429367560, 2807687179, 3020495871, 1180866812, 410100952, 3927582683, 4182430767, 186734380, 3756733383, 763408580, 1053836080, 3434856499, 2722870694, 1344288421, 1131464017, 2971354706, 1708204729, 2545590714, 2229949006, 1988219213, 680717673, 3673779818, 3383336350, 1002577565, 4010310262, 493091189, 238226049, 4233660802, 2987750089, 1082061258, 1395524158, 2705686845, 1972364758, 2279892693, 2494862625, 1725896226, 952904198, 3399985413, 3656866545, 731699698, 4283874585, 222117402, 510512622, 3959836397, 3280807620, 837199303, 582374963, 3504198960, 68661723, 4135334616, 3844915500, 390545967, 1230274059, 3141532936, 2825850620, 1510247935, 2395924756, 2091215383, 1878366691, 2644384480, 3553878443, 565732008, 854102364, 3229815391, 340358836, 3861050807, 4117890627, 119113024, 1493875044, 2875275879, 3090270611, 1247431312, 2660249211, 1828433272, 2141937292, 2378227087, 3811616794, 291187481, 34330861, 4032846830, 615137029, 3603020806, 3314634738, 939183345, 1776939221, 2609017814, 2295496738, 2058945313, 2926798794, 1545135305, 1330124605, 3173225534, 4084100981, 17165430, 307568514, 3762199681, 888469610, 3332340585, 3587147933, 665062302, 2042050490, 2346497209, 2559330125, 1793573966, 3190661285, 1279665062, 1595330642, 2910671697]; + static readonly CRC32C_EXTENSION_TABLE: Int32Array; + /** + * Generates a `CRC32C` from a compatible buffer format. + * + * @param value 4-byte `ArrayBufferView`/`Buffer`/`TypedArray` + */ + private static fromBuffer; + static fromFile(file: PathLike): Promise; + /** + * Generates a `CRC32C` from 4-byte base64-encoded data (string). + * + * @param value 4-byte base64-encoded data (string) + */ + private static fromString; + /** + * Generates a `CRC32C` from a safe, unsigned 32-bit integer. + * + * @param value an unsigned 32-bit integer + */ + private static fromNumber; + /** + * Generates a `CRC32C` from a variety of compatable types. + * Note: strings are treated as input, not as file paths to read from. + * + * @param value A number, 4-byte `ArrayBufferView`/`Buffer`/`TypedArray`, or 4-byte base64-encoded data (string) + */ + static from(value: ArrayBuffer | ArrayBufferView | CRC32CValidator | string | number): CRC32C; +} +export { CRC32C, CRC32C_DEFAULT_VALIDATOR_GENERATOR, CRC32C_EXCEPTION_MESSAGES, CRC32C_EXTENSIONS, CRC32C_EXTENSION_TABLE, CRC32CValidator, CRC32CValidatorGenerator, }; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/crc32c.js b/node_modules/@google-cloud/storage/build/cjs/src/crc32c.js new file mode 100644 index 0000000..efa4a27 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/crc32c.js @@ -0,0 +1,261 @@ +"use strict"; +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _CRC32C_crc32c; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CRC32C_EXTENSION_TABLE = exports.CRC32C_EXTENSIONS = exports.CRC32C_EXCEPTION_MESSAGES = exports.CRC32C_DEFAULT_VALIDATOR_GENERATOR = exports.CRC32C = void 0; +const fs_1 = require("fs"); +/** + * Ported from {@link https://github.com/google/crc32c/blob/21fc8ef30415a635e7351ffa0e5d5367943d4a94/src/crc32c_portable.cc#L16-L59 github.com/google/crc32c} + */ +const CRC32C_EXTENSIONS = [ + 0x00000000, 0xf26b8303, 0xe13b70f7, 0x1350f3f4, 0xc79a971f, 0x35f1141c, + 0x26a1e7e8, 0xd4ca64eb, 0x8ad958cf, 0x78b2dbcc, 0x6be22838, 0x9989ab3b, + 0x4d43cfd0, 0xbf284cd3, 0xac78bf27, 0x5e133c24, 0x105ec76f, 0xe235446c, + 0xf165b798, 0x030e349b, 0xd7c45070, 0x25afd373, 0x36ff2087, 0xc494a384, + 0x9a879fa0, 0x68ec1ca3, 0x7bbcef57, 0x89d76c54, 0x5d1d08bf, 0xaf768bbc, + 0xbc267848, 0x4e4dfb4b, 0x20bd8ede, 0xd2d60ddd, 0xc186fe29, 0x33ed7d2a, + 0xe72719c1, 0x154c9ac2, 0x061c6936, 0xf477ea35, 0xaa64d611, 0x580f5512, + 0x4b5fa6e6, 0xb93425e5, 0x6dfe410e, 0x9f95c20d, 0x8cc531f9, 0x7eaeb2fa, + 0x30e349b1, 0xc288cab2, 0xd1d83946, 0x23b3ba45, 0xf779deae, 0x05125dad, + 0x1642ae59, 0xe4292d5a, 0xba3a117e, 0x4851927d, 0x5b016189, 0xa96ae28a, + 0x7da08661, 0x8fcb0562, 0x9c9bf696, 0x6ef07595, 0x417b1dbc, 0xb3109ebf, + 0xa0406d4b, 0x522bee48, 0x86e18aa3, 0x748a09a0, 0x67dafa54, 0x95b17957, + 0xcba24573, 0x39c9c670, 0x2a993584, 0xd8f2b687, 0x0c38d26c, 0xfe53516f, + 0xed03a29b, 0x1f682198, 0x5125dad3, 0xa34e59d0, 0xb01eaa24, 0x42752927, + 0x96bf4dcc, 0x64d4cecf, 0x77843d3b, 0x85efbe38, 0xdbfc821c, 0x2997011f, + 0x3ac7f2eb, 0xc8ac71e8, 0x1c661503, 0xee0d9600, 0xfd5d65f4, 0x0f36e6f7, + 0x61c69362, 0x93ad1061, 0x80fde395, 0x72966096, 0xa65c047d, 0x5437877e, + 0x4767748a, 0xb50cf789, 0xeb1fcbad, 0x197448ae, 0x0a24bb5a, 0xf84f3859, + 0x2c855cb2, 0xdeeedfb1, 0xcdbe2c45, 0x3fd5af46, 0x7198540d, 0x83f3d70e, + 0x90a324fa, 0x62c8a7f9, 0xb602c312, 0x44694011, 0x5739b3e5, 0xa55230e6, + 0xfb410cc2, 0x092a8fc1, 0x1a7a7c35, 0xe811ff36, 0x3cdb9bdd, 0xceb018de, + 0xdde0eb2a, 0x2f8b6829, 0x82f63b78, 0x709db87b, 0x63cd4b8f, 0x91a6c88c, + 0x456cac67, 0xb7072f64, 0xa457dc90, 0x563c5f93, 0x082f63b7, 0xfa44e0b4, + 0xe9141340, 0x1b7f9043, 0xcfb5f4a8, 0x3dde77ab, 0x2e8e845f, 0xdce5075c, + 0x92a8fc17, 0x60c37f14, 0x73938ce0, 0x81f80fe3, 0x55326b08, 0xa759e80b, + 0xb4091bff, 0x466298fc, 0x1871a4d8, 0xea1a27db, 0xf94ad42f, 0x0b21572c, + 0xdfeb33c7, 0x2d80b0c4, 0x3ed04330, 0xccbbc033, 0xa24bb5a6, 0x502036a5, + 0x4370c551, 0xb11b4652, 0x65d122b9, 0x97baa1ba, 0x84ea524e, 0x7681d14d, + 0x2892ed69, 0xdaf96e6a, 0xc9a99d9e, 0x3bc21e9d, 0xef087a76, 0x1d63f975, + 0x0e330a81, 0xfc588982, 0xb21572c9, 0x407ef1ca, 0x532e023e, 0xa145813d, + 0x758fe5d6, 0x87e466d5, 0x94b49521, 0x66df1622, 0x38cc2a06, 0xcaa7a905, + 0xd9f75af1, 0x2b9cd9f2, 0xff56bd19, 0x0d3d3e1a, 0x1e6dcdee, 0xec064eed, + 0xc38d26c4, 0x31e6a5c7, 0x22b65633, 0xd0ddd530, 0x0417b1db, 0xf67c32d8, + 0xe52cc12c, 0x1747422f, 0x49547e0b, 0xbb3ffd08, 0xa86f0efc, 0x5a048dff, + 0x8ecee914, 0x7ca56a17, 0x6ff599e3, 0x9d9e1ae0, 0xd3d3e1ab, 0x21b862a8, + 0x32e8915c, 0xc083125f, 0x144976b4, 0xe622f5b7, 0xf5720643, 0x07198540, + 0x590ab964, 0xab613a67, 0xb831c993, 0x4a5a4a90, 0x9e902e7b, 0x6cfbad78, + 0x7fab5e8c, 0x8dc0dd8f, 0xe330a81a, 0x115b2b19, 0x020bd8ed, 0xf0605bee, + 0x24aa3f05, 0xd6c1bc06, 0xc5914ff2, 0x37faccf1, 0x69e9f0d5, 0x9b8273d6, + 0x88d28022, 0x7ab90321, 0xae7367ca, 0x5c18e4c9, 0x4f48173d, 0xbd23943e, + 0xf36e6f75, 0x0105ec76, 0x12551f82, 0xe03e9c81, 0x34f4f86a, 0xc69f7b69, + 0xd5cf889d, 0x27a40b9e, 0x79b737ba, 0x8bdcb4b9, 0x988c474d, 0x6ae7c44e, + 0xbe2da0a5, 0x4c4623a6, 0x5f16d052, 0xad7d5351, +]; +exports.CRC32C_EXTENSIONS = CRC32C_EXTENSIONS; +const CRC32C_EXTENSION_TABLE = new Int32Array(CRC32C_EXTENSIONS); +exports.CRC32C_EXTENSION_TABLE = CRC32C_EXTENSION_TABLE; +const CRC32C_DEFAULT_VALIDATOR_GENERATOR = () => new CRC32C(); +exports.CRC32C_DEFAULT_VALIDATOR_GENERATOR = CRC32C_DEFAULT_VALIDATOR_GENERATOR; +const CRC32C_EXCEPTION_MESSAGES = { + INVALID_INIT_BASE64_RANGE: (l) => `base64-encoded data expected to equal 4 bytes, not ${l}`, + INVALID_INIT_BUFFER_LENGTH: (l) => `Buffer expected to equal 4 bytes, not ${l}`, + INVALID_INIT_INTEGER: (l) => `Number expected to be a safe, unsigned 32-bit integer, not ${l}`, +}; +exports.CRC32C_EXCEPTION_MESSAGES = CRC32C_EXCEPTION_MESSAGES; +class CRC32C { + /** + * Constructs a new `CRC32C` object. + * + * Reconstruction is recommended via the `CRC32C.from` static method. + * + * @param initialValue An initial CRC32C value - a signed 32-bit integer. + */ + constructor(initialValue = 0) { + /** Current CRC32C value */ + _CRC32C_crc32c.set(this, 0); + __classPrivateFieldSet(this, _CRC32C_crc32c, initialValue, "f"); + } + /** + * Calculates a CRC32C from a provided buffer. + * + * Implementation inspired from: + * - {@link https://github.com/google/crc32c/blob/21fc8ef30415a635e7351ffa0e5d5367943d4a94/src/crc32c_portable.cc github.com/google/crc32c} + * - {@link https://github.com/googleapis/python-crc32c/blob/a595e758c08df445a99c3bf132ee8e80a3ec4308/src/google_crc32c/python.py github.com/googleapis/python-crc32c} + * - {@link https://github.com/googleapis/java-storage/pull/1376/files github.com/googleapis/java-storage} + * + * @param data The `Buffer` to generate the CRC32C from + */ + update(data) { + let current = __classPrivateFieldGet(this, _CRC32C_crc32c, "f") ^ 0xffffffff; + for (const d of data) { + const tablePoly = CRC32C.CRC32C_EXTENSION_TABLE[(d ^ current) & 0xff]; + current = tablePoly ^ (current >>> 8); + } + __classPrivateFieldSet(this, _CRC32C_crc32c, current ^ 0xffffffff, "f"); + } + /** + * Validates a provided input to the current CRC32C value. + * + * @param input A Buffer, `CRC32C`-compatible object, base64-encoded data (string), or signed 32-bit integer + */ + validate(input) { + if (typeof input === 'number') { + return input === __classPrivateFieldGet(this, _CRC32C_crc32c, "f"); + } + else if (typeof input === 'string') { + return input === this.toString(); + } + else if (Buffer.isBuffer(input)) { + return Buffer.compare(input, this.toBuffer()) === 0; + } + else { + // `CRC32C`-like object + return input.toString() === this.toString(); + } + } + /** + * Returns a `Buffer` representation of the CRC32C value + */ + toBuffer() { + const buffer = Buffer.alloc(4); + buffer.writeInt32BE(__classPrivateFieldGet(this, _CRC32C_crc32c, "f")); + return buffer; + } + /** + * Returns a JSON-compatible, base64-encoded representation of the CRC32C value. + * + * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify `JSON#stringify`} + */ + toJSON() { + return this.toString(); + } + /** + * Returns a base64-encoded representation of the CRC32C value. + * + * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString `Object#toString`} + */ + toString() { + return this.toBuffer().toString('base64'); + } + /** + * Returns the `number` representation of the CRC32C value as a signed 32-bit integer + * + * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf `Object#valueOf`} + */ + valueOf() { + return __classPrivateFieldGet(this, _CRC32C_crc32c, "f"); + } + /** + * Generates a `CRC32C` from a compatible buffer format. + * + * @param value 4-byte `ArrayBufferView`/`Buffer`/`TypedArray` + */ + static fromBuffer(value) { + let buffer; + if (Buffer.isBuffer(value)) { + buffer = value; + } + else if ('buffer' in value) { + // `ArrayBufferView` + buffer = Buffer.from(value.buffer); + } + else { + // `ArrayBuffer` + buffer = Buffer.from(value); + } + if (buffer.byteLength !== 4) { + throw new RangeError(CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_BUFFER_LENGTH(buffer.byteLength)); + } + return new CRC32C(buffer.readInt32BE()); + } + static async fromFile(file) { + const crc32c = new CRC32C(); + await new Promise((resolve, reject) => { + (0, fs_1.createReadStream)(file) + .on('data', (d) => { + if (typeof d === 'string') { + crc32c.update(Buffer.from(d)); + } + else { + crc32c.update(d); + } + }) + .on('end', () => resolve()) + .on('error', reject); + }); + return crc32c; + } + /** + * Generates a `CRC32C` from 4-byte base64-encoded data (string). + * + * @param value 4-byte base64-encoded data (string) + */ + static fromString(value) { + const buffer = Buffer.from(value, 'base64'); + if (buffer.byteLength !== 4) { + throw new RangeError(CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_BASE64_RANGE(buffer.byteLength)); + } + return this.fromBuffer(buffer); + } + /** + * Generates a `CRC32C` from a safe, unsigned 32-bit integer. + * + * @param value an unsigned 32-bit integer + */ + static fromNumber(value) { + if (!Number.isSafeInteger(value) || value > 2 ** 32 || value < -(2 ** 32)) { + throw new RangeError(CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_INTEGER(value)); + } + return new CRC32C(value); + } + /** + * Generates a `CRC32C` from a variety of compatable types. + * Note: strings are treated as input, not as file paths to read from. + * + * @param value A number, 4-byte `ArrayBufferView`/`Buffer`/`TypedArray`, or 4-byte base64-encoded data (string) + */ + static from(value) { + if (typeof value === 'number') { + return this.fromNumber(value); + } + else if (typeof value === 'string') { + return this.fromString(value); + } + else if ('byteLength' in value) { + // `ArrayBuffer` | `Buffer` | `ArrayBufferView` + return this.fromBuffer(value); + } + else { + // `CRC32CValidator`/`CRC32C`-like + return this.fromString(value.toString()); + } + } +} +exports.CRC32C = CRC32C; +_CRC32C_crc32c = new WeakMap(); +CRC32C.CRC32C_EXTENSIONS = CRC32C_EXTENSIONS; +CRC32C.CRC32C_EXTENSION_TABLE = CRC32C_EXTENSION_TABLE; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/file.d.ts b/node_modules/@google-cloud/storage/build/cjs/src/file.d.ts new file mode 100644 index 0000000..e80a092 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/file.d.ts @@ -0,0 +1,982 @@ +import { BodyResponseCallback, DecorateRequestOptions, GetConfig, MetadataCallback, ServiceObject, SetMetadataResponse } from './nodejs-common/index.js'; +import * as resumableUpload from './resumable-upload.js'; +import { Writable, Readable, PipelineSource } from 'stream'; +import * as http from 'http'; +import { PreconditionOptions, Storage } from './storage.js'; +import { AvailableServiceObjectMethods, Bucket } from './bucket.js'; +import { Acl, AclMetadata } from './acl.js'; +import { GetSignedUrlResponse, GetSignedUrlCallback, URLSigner, SignerGetSignedUrlConfig, Query } from './signer.js'; +import { Duplexify, GCCL_GCS_CMD_KEY } from './nodejs-common/util.js'; +import { CRC32C, CRC32CValidatorGenerator } from './crc32c.js'; +import { URL } from 'url'; +import { BaseMetadata, DeleteCallback, DeleteOptions, GetResponse, InstanceResponseCallback, RequestResponse, SetMetadataOptions } from './nodejs-common/service-object.js'; +import * as r from 'teeny-request'; +export type GetExpirationDateResponse = [Date]; +export interface GetExpirationDateCallback { + (err: Error | null, expirationDate?: Date | null, apiResponse?: unknown): void; +} +export interface PolicyDocument { + string: string; + base64: string; + signature: string; +} +export type SaveData = string | Buffer | Uint8Array | PipelineSource; +export type GenerateSignedPostPolicyV2Response = [PolicyDocument]; +export interface GenerateSignedPostPolicyV2Callback { + (err: Error | null, policy?: PolicyDocument): void; +} +export interface GenerateSignedPostPolicyV2Options { + equals?: string[] | string[][]; + expires: string | number | Date; + startsWith?: string[] | string[][]; + acl?: string; + successRedirect?: string; + successStatus?: string; + contentLengthRange?: { + min?: number; + max?: number; + }; + /** + * @example + * 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/' + */ + signingEndpoint?: string; +} +export interface PolicyFields { + [key: string]: string; +} +export interface GenerateSignedPostPolicyV4Options { + expires: string | number | Date; + bucketBoundHostname?: string; + virtualHostedStyle?: boolean; + conditions?: object[]; + fields?: PolicyFields; + /** + * @example + * 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/' + */ + signingEndpoint?: string; +} +export interface GenerateSignedPostPolicyV4Callback { + (err: Error | null, output?: SignedPostPolicyV4Output): void; +} +export type GenerateSignedPostPolicyV4Response = [SignedPostPolicyV4Output]; +export interface SignedPostPolicyV4Output { + url: string; + fields: PolicyFields; +} +export interface GetSignedUrlConfig extends Pick { + action: 'read' | 'write' | 'delete' | 'resumable'; + version?: 'v2' | 'v4'; + virtualHostedStyle?: boolean; + cname?: string; + contentMd5?: string; + contentType?: string; + expires: string | number | Date; + accessibleAt?: string | number | Date; + extensionHeaders?: http.OutgoingHttpHeaders; + promptSaveAs?: string; + responseDisposition?: string; + responseType?: string; + queryParams?: Query; +} +export interface GetFileMetadataOptions { + userProject?: string; +} +export type GetFileMetadataResponse = [FileMetadata, unknown]; +export interface GetFileMetadataCallback { + (err: Error | null, metadata?: FileMetadata, apiResponse?: unknown): void; +} +export interface GetFileOptions extends GetConfig { + userProject?: string; + generation?: number; + restoreToken?: string; + softDeleted?: boolean; +} +export type GetFileResponse = [File, unknown]; +export interface GetFileCallback { + (err: Error | null, file?: File, apiResponse?: unknown): void; +} +export interface FileExistsOptions { + userProject?: string; +} +export type FileExistsResponse = [boolean]; +export interface FileExistsCallback { + (err: Error | null, exists?: boolean): void; +} +export interface DeleteFileOptions { + ignoreNotFound?: boolean; + userProject?: string; +} +export type DeleteFileResponse = [unknown]; +export interface DeleteFileCallback { + (err: Error | null, apiResponse?: unknown): void; +} +export type PredefinedAcl = 'authenticatedRead' | 'bucketOwnerFullControl' | 'bucketOwnerRead' | 'private' | 'projectPrivate' | 'publicRead'; +type PublicResumableUploadOptions = 'chunkSize' | 'highWaterMark' | 'isPartialUpload' | 'metadata' | 'origin' | 'offset' | 'predefinedAcl' | 'private' | 'public' | 'uri' | 'userProject'; +export interface CreateResumableUploadOptions extends Pick { + /** + * A CRC32C to resume from when continuing a previous upload. It is recommended + * to capture the `crc32c` event from previous upload sessions to provide in + * subsequent requests in order to accurately track the upload. This is **required** + * when validating a final portion of the uploaded object. + * + * @see {@link CRC32C.from} for possible values. + */ + resumeCRC32C?: Parameters<(typeof CRC32C)['from']>[0]; + preconditionOpts?: PreconditionOptions; + [GCCL_GCS_CMD_KEY]?: resumableUpload.UploadConfig[typeof GCCL_GCS_CMD_KEY]; +} +export type CreateResumableUploadResponse = [string]; +export interface CreateResumableUploadCallback { + (err: Error | null, uri?: string): void; +} +export interface CreateWriteStreamOptions extends CreateResumableUploadOptions { + contentType?: string; + gzip?: string | boolean; + resumable?: boolean; + timeout?: number; + validation?: string | boolean; +} +export interface MakeFilePrivateOptions { + metadata?: FileMetadata; + strict?: boolean; + userProject?: string; + preconditionOpts?: PreconditionOptions; +} +export type MakeFilePrivateResponse = [unknown]; +export type MakeFilePrivateCallback = SetFileMetadataCallback; +export interface IsPublicCallback { + (err: Error | null, resp?: boolean): void; +} +export type IsPublicResponse = [boolean]; +export type MakeFilePublicResponse = [unknown]; +export interface MakeFilePublicCallback { + (err?: Error | null, apiResponse?: unknown): void; +} +export type MoveResponse = [unknown]; +export interface MoveCallback { + (err: Error | null, destinationFile?: File | null, apiResponse?: unknown): void; +} +export interface MoveOptions { + userProject?: string; + preconditionOpts?: PreconditionOptions; +} +export type MoveFileAtomicOptions = MoveOptions; +export type MoveFileAtomicCallback = MoveCallback; +export type MoveFileAtomicResponse = MoveResponse; +export type RenameOptions = MoveOptions; +export type RenameResponse = MoveResponse; +export type RenameCallback = MoveCallback; +export type RotateEncryptionKeyOptions = string | Buffer | EncryptionKeyOptions; +export interface EncryptionKeyOptions { + encryptionKey?: string | Buffer; + kmsKeyName?: string; + preconditionOpts?: PreconditionOptions; +} +export type RotateEncryptionKeyCallback = CopyCallback; +export type RotateEncryptionKeyResponse = CopyResponse; +export declare enum ActionToHTTPMethod { + read = "GET", + write = "PUT", + delete = "DELETE", + resumable = "POST" +} +/** + * @deprecated - no longer used + */ +export declare const STORAGE_POST_POLICY_BASE_URL = "https://storage.googleapis.com"; +export interface FileOptions { + crc32cGenerator?: CRC32CValidatorGenerator; + encryptionKey?: string | Buffer; + generation?: number | string; + restoreToken?: string; + kmsKeyName?: string; + preconditionOpts?: PreconditionOptions; + userProject?: string; +} +export interface CopyOptions { + cacheControl?: string; + contentEncoding?: string; + contentType?: string; + contentDisposition?: string; + destinationKmsKeyName?: string; + metadata?: { + [key: string]: string | boolean | number | null; + }; + predefinedAcl?: string; + token?: string; + userProject?: string; + preconditionOpts?: PreconditionOptions; +} +export type CopyResponse = [File, unknown]; +export interface CopyCallback { + (err: Error | null, file?: File | null, apiResponse?: unknown): void; +} +export type DownloadResponse = [Buffer]; +export type DownloadCallback = (err: RequestError | null, contents: Buffer) => void; +export interface DownloadOptions extends CreateReadStreamOptions { + destination?: string; + encryptionKey?: string | Buffer; +} +export interface CreateReadStreamOptions { + userProject?: string; + validation?: 'md5' | 'crc32c' | false | true; + start?: number; + end?: number; + decompress?: boolean; + [GCCL_GCS_CMD_KEY]?: string; +} +export interface SaveOptions extends CreateWriteStreamOptions { + onUploadProgress?: (progressEvent: any) => void; +} +export interface SaveCallback { + (err?: Error | null): void; +} +export interface SetFileMetadataOptions { + userProject?: string; +} +export interface SetFileMetadataCallback { + (err?: Error | null, apiResponse?: unknown): void; +} +export type SetFileMetadataResponse = [unknown]; +export type SetStorageClassResponse = [unknown]; +export interface SetStorageClassOptions { + userProject?: string; + preconditionOpts?: PreconditionOptions; +} +export interface SetStorageClassCallback { + (err?: Error | null, apiResponse?: unknown): void; +} +export interface RestoreOptions extends PreconditionOptions { + generation: number; + restoreToken?: string; + projection?: 'full' | 'noAcl'; +} +export interface FileMetadata extends BaseMetadata { + acl?: AclMetadata[] | null; + bucket?: string; + cacheControl?: string; + componentCount?: number; + contentDisposition?: string; + contentEncoding?: string; + contentLanguage?: string; + contentType?: string; + crc32c?: string; + customerEncryption?: { + encryptionAlgorithm?: string; + keySha256?: string; + }; + customTime?: string; + eventBasedHold?: boolean | null; + readonly eventBasedHoldReleaseTime?: string; + generation?: string | number; + restoreToken?: string; + hardDeleteTime?: string; + kmsKeyName?: string; + md5Hash?: string; + mediaLink?: string; + metadata?: { + [key: string]: string | boolean | number | null; + }; + metageneration?: string | number; + name?: string; + owner?: { + entity?: string; + entityId?: string; + }; + retention?: { + retainUntilTime?: string; + mode?: string; + } | null; + retentionExpirationTime?: string; + size?: string | number; + softDeleteTime?: string; + storageClass?: string; + temporaryHold?: boolean | null; + timeCreated?: string; + timeDeleted?: string; + timeStorageClassUpdated?: string; + updated?: string; +} +export declare class RequestError extends Error { + code?: string; + errors?: Error[]; +} +export declare enum FileExceptionMessages { + EXPIRATION_TIME_NA = "An expiration time is not available.", + DESTINATION_NO_NAME = "Destination file should have a name.", + INVALID_VALIDATION_FILE_RANGE = "Cannot use validation with file ranges (start/end).", + MD5_NOT_AVAILABLE = "MD5 verification was specified, but is not available for the requested object. MD5 is not available for composite objects.", + EQUALS_CONDITION_TWO_ELEMENTS = "Equals condition must be an array of 2 elements.", + STARTS_WITH_TWO_ELEMENTS = "StartsWith condition must be an array of 2 elements.", + CONTENT_LENGTH_RANGE_MIN_MAX = "ContentLengthRange must have numeric min & max fields.", + DOWNLOAD_MISMATCH = "The downloaded data did not match the data from the server. To be sure the content is the same, you should download the file again.", + UPLOAD_MISMATCH_DELETE_FAIL = "The uploaded data did not match the data from the server.\n As a precaution, we attempted to delete the file, but it was not successful.\n To be sure the content is the same, you should try removing the file manually,\n then uploading the file again.\n \n\nThe delete attempt failed with this message:\n\n ", + UPLOAD_MISMATCH = "The uploaded data did not match the data from the server.\n As a precaution, the file has been deleted.\n To be sure the content is the same, you should try uploading the file again.", + MD5_RESUMED_UPLOAD = "MD5 cannot be used with a continued resumable upload as MD5 cannot be extended from an existing value", + MISSING_RESUME_CRC32C_FINAL_UPLOAD = "The CRC32C is missing for the final portion of a resumed upload, which is required for validation. Please provide `resumeCRC32C` if validation is required, or disable `validation`." +} +/** + * A File object is created from your {@link Bucket} object using + * {@link Bucket#file}. + * + * @class + */ +declare class File extends ServiceObject { + #private; + acl: Acl; + crc32cGenerator: CRC32CValidatorGenerator; + bucket: Bucket; + storage: Storage; + kmsKeyName?: string; + userProject?: string; + signer?: URLSigner; + name: string; + generation?: number; + restoreToken?: string; + parent: Bucket; + private encryptionKey?; + private encryptionKeyBase64?; + private encryptionKeyHash?; + private encryptionKeyInterceptor?; + private instanceRetryValue?; + instancePreconditionOpts?: PreconditionOptions; + /** + * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share objects with other + * users and allow other users to access your buckets and objects. + * + * An ACL consists of one or more entries, where each entry grants permissions + * to an entity. Permissions define the actions that can be performed against + * an object or bucket (for example, `READ` or `WRITE`); the entity defines + * who the permission applies to (for example, a specific user or group of + * users). + * + * The `acl` object on a File instance provides methods to get you a list of + * the ACLs defined on your bucket, as well as set, update, and delete them. + * + * See {@link http://goo.gl/6qBBPO| About Access Control lists} + * + * @name File#acl + * @mixes Acl + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * //- + * // Make a file publicly readable. + * //- + * const options = { + * entity: 'allUsers', + * role: storage.acl.READER_ROLE + * }; + * + * file.acl.add(options, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.acl.add(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + /** + * The API-formatted resource description of the file. + * + * Note: This is not guaranteed to be up-to-date when accessed. To get the + * latest record, call the `getMetadata()` method. + * + * @name File#metadata + * @type {object} + */ + /** + * The file's name. + * @name File#name + * @type {string} + */ + /** + * @callback Crc32cGeneratorToStringCallback + * A method returning the CRC32C as a base64-encoded string. + * + * @returns {string} + * + * @example + * Hashing the string 'data' should return 'rth90Q==' + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.toString(); // 'rth90Q==' + * ``` + **/ + /** + * @callback Crc32cGeneratorValidateCallback + * A method validating a base64-encoded CRC32C string. + * + * @param {string} [value] base64-encoded CRC32C string to validate + * @returns {boolean} + * + * @example + * Should return `true` if the value matches, `false` otherwise + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.validate('DkjKuA=='); // false + * crc32c.validate('rth90Q=='); // true + * ``` + **/ + /** + * @callback Crc32cGeneratorUpdateCallback + * A method for passing `Buffer`s for CRC32C generation. + * + * @param {Buffer} [data] data to update CRC32C value with + * @returns {undefined} + * + * @example + * Hashing buffers from 'some ' and 'text\n' + * + * ```js + * const buffer1 = Buffer.from('some '); + * crc32c.update(buffer1); + * + * const buffer2 = Buffer.from('text\n'); + * crc32c.update(buffer2); + * + * crc32c.toString(); // 'DkjKuA==' + * ``` + **/ + /** + * @typedef {object} CRC32CValidator + * @property {Crc32cGeneratorToStringCallback} + * @property {Crc32cGeneratorValidateCallback} + * @property {Crc32cGeneratorUpdateCallback} + */ + /** + * @callback Crc32cGeneratorCallback + * @returns {CRC32CValidator} + */ + /** + * @typedef {object} FileOptions Options passed to the File constructor. + * @property {string} [encryptionKey] A custom encryption key. + * @property {number} [generation] Generation to scope the file to. + * @property {string} [kmsKeyName] Cloud KMS Key used to encrypt this + * object, if the object is encrypted by such a key. Limited availability; + * usable only by enabled projects. + * @property {string} [userProject] The ID of the project which will be + * billed for all requests made from File object. + * @property {Crc32cGeneratorCallback} [callback] A function that generates a CRC32C Validator. Defaults to {@link CRC32C} + */ + /** + * Constructs a file object. + * + * @param {Bucket} bucket The Bucket instance this file is + * attached to. + * @param {string} name The name of the remote file. + * @param {FileOptions} [options] Configuration options. + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * ``` + */ + constructor(bucket: Bucket, name: string, options?: FileOptions); + /** + * The object's Cloud Storage URI (`gs://`) + * + * @example + * ```ts + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const file = bucket.file('image.png'); + * + * // `gs://my-bucket/image.png` + * const href = file.cloudStorageURI.href; + * ``` + */ + get cloudStorageURI(): URL; + /** + * A helper method for determining if a request should be retried based on preconditions. + * This should only be used for methods where the idempotency is determined by + * `ifGenerationMatch` + * @private + * + * A request should not be retried under the following conditions: + * - if precondition option `ifGenerationMatch` is not set OR + * - if `idempotencyStrategy` is set to `RetryNever` + */ + private shouldRetryBasedOnPreconditionAndIdempotencyStrat; + copy(destination: string | Bucket | File, options?: CopyOptions): Promise; + copy(destination: string | Bucket | File, callback: CopyCallback): void; + copy(destination: string | Bucket | File, options: CopyOptions, callback: CopyCallback): void; + /** + * @typedef {object} CreateReadStreamOptions Configuration options for File#createReadStream. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {string|boolean} [validation] Possible values: `"md5"`, + * `"crc32c"`, or `false`. By default, data integrity is validated with a + * CRC32c checksum. You may use MD5 if preferred, but that hash is not + * supported for composite objects. An error will be raised if MD5 is + * specified but is not available. You may also choose to skip validation + * completely, however this is **not recommended**. + * @property {number} [start] A byte offset to begin the file's download + * from. Default is 0. NOTE: Byte ranges are inclusive; that is, + * `options.start = 0` and `options.end = 999` represent the first 1000 + * bytes in a file or object. NOTE: when specifying a byte range, data + * integrity is not available. + * @property {number} [end] A byte offset to stop reading the file at. + * NOTE: Byte ranges are inclusive; that is, `options.start = 0` and + * `options.end = 999` represent the first 1000 bytes in a file or object. + * NOTE: when specifying a byte range, data integrity is not available. + * @property {boolean} [decompress=true] Disable auto decompression of the + * received data. By default this option is set to `true`. + * Applicable in cases where the data was uploaded with + * `gzip: true` option. See {@link File#createWriteStream}. + */ + /** + * Create a readable stream to read the contents of the remote file. It can be + * piped to a writable stream or listened to for 'data' events to read a + * file's contents. + * + * In the unlikely event there is a mismatch between what you downloaded and + * the version in your Bucket, your error handler will receive an error with + * code "CONTENT_DOWNLOAD_MISMATCH". If you receive this error, the best + * recourse is to try downloading the file again. + * + * NOTE: Readable streams will emit the `end` event when the file is fully + * downloaded. + * + * @param {CreateReadStreamOptions} [options] Configuration options. + * @returns {ReadableStream} + * + * @example + * ``` + * //- + * //

Downloading a File

+ * // + * // The example below demonstrates how we can reference a remote file, then + * // pipe its contents to a local file. This is effectively creating a local + * // backup of your remote data. + * //- + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * const fs = require('fs'); + * const remoteFile = bucket.file('image.png'); + * const localFilename = '/Users/stephen/Photos/image.png'; + * + * remoteFile.createReadStream() + * .on('error', function(err) {}) + * .on('response', function(response) { + * // Server connected and responded with the specified status and headers. + * }) + * .on('end', function() { + * // The file is fully downloaded. + * }) + * .pipe(fs.createWriteStream(localFilename)); + * + * //- + * // To limit the downloaded data to only a byte range, pass an options + * // object. + * //- + * const logFile = myBucket.file('access_log'); + * logFile.createReadStream({ + * start: 10000, + * end: 20000 + * }) + * .on('error', function(err) {}) + * .pipe(fs.createWriteStream('/Users/stephen/logfile.txt')); + * + * //- + * // To read a tail byte range, specify only `options.end` as a negative + * // number. + * //- + * const logFile = myBucket.file('access_log'); + * logFile.createReadStream({ + * end: -100 + * }) + * .on('error', function(err) {}) + * .pipe(fs.createWriteStream('/Users/stephen/logfile.txt')); + * ``` + */ + createReadStream(options?: CreateReadStreamOptions): Readable; + createResumableUpload(options?: CreateResumableUploadOptions): Promise; + createResumableUpload(options: CreateResumableUploadOptions, callback: CreateResumableUploadCallback): void; + createResumableUpload(callback: CreateResumableUploadCallback): void; + /** + * @typedef {object} CreateWriteStreamOptions Configuration options for File#createWriteStream(). + * @property {string} [contentType] Alias for + * `options.metadata.contentType`. If set to `auto`, the file name is used + * to determine the contentType. + * @property {string|boolean} [gzip] If true, automatically gzip the file. + * If set to `auto`, the contentType is used to determine if the file + * should be gzipped. This will set `options.metadata.contentEncoding` to + * `gzip` if necessary. + * @property {object} [metadata] See the examples below or + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON| Objects: insert request body} + * for more details. + * @property {number} [offset] The starting byte of the upload stream, for + * resuming an interrupted upload. Defaults to 0. + * @property {string} [predefinedAcl] Apply a predefined set of access + * controls to this object. + * + * Acceptable values are: + * - **`authenticatedRead`** - Object owner gets `OWNER` access, and + * `allAuthenticatedUsers` get `READER` access. + * + * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and + * project team owners get `OWNER` access. + * + * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project + * team owners get `READER` access. + * + * - **`private`** - Object owner gets `OWNER` access. + * + * - **`projectPrivate`** - Object owner gets `OWNER` access, and project + * team members get access according to their roles. + * + * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers` + * get `READER` access. + * @property {boolean} [private] Make the uploaded file private. (Alias for + * `options.predefinedAcl = 'private'`) + * @property {boolean} [public] Make the uploaded file public. (Alias for + * `options.predefinedAcl = 'publicRead'`) + * @property {boolean} [resumable] Force a resumable upload. NOTE: When + * working with streams, the file format and size is unknown until it's + * completely consumed. Because of this, it's best for you to be explicit + * for what makes sense given your input. + * @property {number} [timeout=60000] Set the HTTP request timeout in + * milliseconds. This option is not available for resumable uploads. + * Default: `60000` + * @property {string} [uri] The URI for an already-created resumable + * upload. See {@link File#createResumableUpload}. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {string|boolean} [validation] Possible values: `"md5"`, + * `"crc32c"`, or `false`. By default, data integrity is validated with a + * CRC32c checksum. You may use MD5 if preferred, but that hash is not + * supported for composite objects. An error will be raised if MD5 is + * specified but is not available. You may also choose to skip validation + * completely, however this is **not recommended**. In addition to specifying + * validation type, providing `metadata.crc32c` or `metadata.md5Hash` will + * cause the server to perform validation in addition to client validation. + * NOTE: Validation is automatically skipped for objects that were + * uploaded using the `gzip` option and have already compressed content. + */ + /** + * Create a writable stream to overwrite the contents of the file in your + * bucket. + * + * A File object can also be used to create files for the first time. + * + * Resumable uploads are automatically enabled and must be shut off explicitly + * by setting `options.resumable` to `false`. + * + * + *

+ * There is some overhead when using a resumable upload that can cause + * noticeable performance degradation while uploading a series of small + * files. When uploading files less than 10MB, it is recommended that the + * resumable feature is disabled. + *

+ * + * NOTE: Writable streams will emit the `finish` event when the file is fully + * uploaded. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload Upload Options (Simple or Resumable)} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert Objects: insert API Documentation} + * + * @param {CreateWriteStreamOptions} [options] Configuration options. + * @returns {WritableStream} + * + * @example + * ``` + * const fs = require('fs'); + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * //- + * //

Uploading a File

+ * // + * // Now, consider a case where we want to upload a file to your bucket. You + * // have the option of using {@link Bucket#upload}, but that is just + * // a convenience method which will do the following. + * //- + * fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg') + * .pipe(file.createWriteStream()) + * .on('error', function(err) {}) + * .on('finish', function() { + * // The file upload is complete. + * }); + * + * //- + * //

Uploading a File with gzip compression

+ * //- + * fs.createReadStream('/Users/stephen/site/index.html') + * .pipe(file.createWriteStream({ gzip: true })) + * .on('error', function(err) {}) + * .on('finish', function() { + * // The file upload is complete. + * }); + * + * //- + * // Downloading the file with `createReadStream` will automatically decode + * // the file. + * //- + * + * //- + * //

Uploading a File with Metadata

+ * // + * // One last case you may run into is when you want to upload a file to your + * // bucket and set its metadata at the same time. Like above, you can use + * // {@link Bucket#upload} to do this, which is just a wrapper around + * // the following. + * //- + * fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg') + * .pipe(file.createWriteStream({ + * metadata: { + * contentType: 'image/jpeg', + * metadata: { + * custom: 'metadata' + * } + * } + * })) + * .on('error', function(err) {}) + * .on('finish', function() { + * // The file upload is complete. + * }); + * ``` + * + * //- + * //

Continuing a Resumable Upload

+ * // + * // One can capture a `uri` from a resumable upload to reuse later. + * // Additionally, for validation, one can also capture and pass `crc32c`. + * //- + * let uri: string | undefined = undefined; + * let resumeCRC32C: string | undefined = undefined; + * + * fs.createWriteStream() + * .on('uri', link => {uri = link}) + * .on('crc32', crc32c => {resumeCRC32C = crc32c}); + * + * // later... + * fs.createWriteStream({uri, resumeCRC32C}); + */ + createWriteStream(options?: CreateWriteStreamOptions): Writable; + /** + * Delete the object. + * + * @param {function=} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.apiResponse - The full API response. + */ + delete(options?: DeleteOptions): Promise<[r.Response]>; + delete(options: DeleteOptions, callback: DeleteCallback): void; + delete(callback: DeleteCallback): void; + download(options?: DownloadOptions): Promise; + download(options: DownloadOptions, callback: DownloadCallback): void; + download(callback: DownloadCallback): void; + /** + * The Storage API allows you to use a custom key for server-side encryption. + * + * See {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys} + * + * @param {string|buffer} encryptionKey An AES-256 encryption key. + * @returns {File} + * + * @example + * ``` + * const crypto = require('crypto'); + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const encryptionKey = crypto.randomBytes(32); + * + * const fileWithCustomEncryption = myBucket.file('my-file'); + * fileWithCustomEncryption.setEncryptionKey(encryptionKey); + * + * const fileWithoutCustomEncryption = myBucket.file('my-file'); + * + * fileWithCustomEncryption.save('data', function(err) { + * // Try to download with the File object that hasn't had + * // `setEncryptionKey()` called: + * fileWithoutCustomEncryption.download(function(err) { + * // We will receive an error: + * // err.message === 'Bad Request' + * + * // Try again with the File object we called `setEncryptionKey()` on: + * fileWithCustomEncryption.download(function(err, contents) { + * // contents.toString() === 'data' + * }); + * }); + * }); + * + * ``` + * @example include:samples/encryption.js + * region_tag:storage_upload_encrypted_file + * Example of uploading an encrypted file: + * + * @example include:samples/encryption.js + * region_tag:storage_download_encrypted_file + * Example of downloading an encrypted file: + */ + setEncryptionKey(encryptionKey: string | Buffer): this; + /** + * Gets a reference to a Cloud Storage {@link File} file from the provided URL in string format. + * @param {string} publicUrlOrGsUrl the URL as a string. Must be of the format gs://bucket/file + * or https://storage.googleapis.com/bucket/file. + * @param {Storage} storageInstance an instance of a Storage object. + * @param {FileOptions} [options] Configuration options + * @returns {File} + */ + static from(publicUrlOrGsUrl: string, storageInstance: Storage, options?: FileOptions): File; + get(options?: GetFileOptions): Promise>; + get(callback: InstanceResponseCallback): void; + get(options: GetFileOptions, callback: InstanceResponseCallback): void; + getExpirationDate(): Promise; + getExpirationDate(callback: GetExpirationDateCallback): void; + generateSignedPostPolicyV2(options: GenerateSignedPostPolicyV2Options): Promise; + generateSignedPostPolicyV2(options: GenerateSignedPostPolicyV2Options, callback: GenerateSignedPostPolicyV2Callback): void; + generateSignedPostPolicyV2(callback: GenerateSignedPostPolicyV2Callback): void; + generateSignedPostPolicyV4(options: GenerateSignedPostPolicyV4Options): Promise; + generateSignedPostPolicyV4(options: GenerateSignedPostPolicyV4Options, callback: GenerateSignedPostPolicyV4Callback): void; + generateSignedPostPolicyV4(callback: GenerateSignedPostPolicyV4Callback): void; + getSignedUrl(cfg: GetSignedUrlConfig): Promise; + getSignedUrl(cfg: GetSignedUrlConfig, callback: GetSignedUrlCallback): void; + isPublic(): Promise; + isPublic(callback: IsPublicCallback): void; + makePrivate(options?: MakeFilePrivateOptions): Promise; + makePrivate(callback: MakeFilePrivateCallback): void; + makePrivate(options: MakeFilePrivateOptions, callback: MakeFilePrivateCallback): void; + makePublic(): Promise; + makePublic(callback: MakeFilePublicCallback): void; + /** + * The public URL of this File + * Use {@link File#makePublic} to enable anonymous access via the returned URL. + * + * @returns {string} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * const file = bucket.file('my-file'); + * + * // publicUrl will be "https://storage.googleapis.com/albums/my-file" + * const publicUrl = file.publicUrl(); + * ``` + */ + publicUrl(): string; + moveFileAtomic(destination: string | File, options?: MoveFileAtomicOptions): Promise; + moveFileAtomic(destination: string | File, callback: MoveFileAtomicCallback): void; + moveFileAtomic(destination: string | File, options: MoveFileAtomicOptions, callback: MoveFileAtomicCallback): void; + move(destination: string | Bucket | File, options?: MoveOptions): Promise; + move(destination: string | Bucket | File, callback: MoveCallback): void; + move(destination: string | Bucket | File, options: MoveOptions, callback: MoveCallback): void; + rename(destinationFile: string | File, options?: RenameOptions): Promise; + rename(destinationFile: string | File, callback: RenameCallback): void; + rename(destinationFile: string | File, options: RenameOptions, callback: RenameCallback): void; + /** + * @typedef {object} RestoreOptions Options for File#restore(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}. + * @param {string} [userProject] The ID of the project which will be + * billed for the request. + * @param {number} [generation] If present, selects a specific revision of this object. + * @param {string} [restoreToken] Returns an option that must be specified when getting a soft-deleted object from an HNS-enabled + * bucket that has a naming and generation conflict with another object in the same bucket. + * @param {string} [projection] Specifies the set of properties to return. If used, must be 'full' or 'noAcl'. + * @param {string | number} [ifGenerationMatch] Request proceeds if the generation of the target resource + * matches the value used in the precondition. + * If the values don't match, the request fails with a 412 Precondition Failed response. + * @param {string | number} [ifGenerationNotMatch] Request proceeds if the generation of the target resource does + * not match the value used in the precondition. If the values match, the request fails with a 304 Not Modified response. + * @param {string | number} [ifMetagenerationMatch] Request proceeds if the meta-generation of the target resource + * matches the value used in the precondition. + * If the values don't match, the request fails with a 412 Precondition Failed response. + * @param {string | number} [ifMetagenerationNotMatch] Request proceeds if the meta-generation of the target resource does + * not match the value used in the precondition. If the values match, the request fails with a 304 Not Modified response. + */ + /** + * Restores a soft-deleted file + * @param {RestoreOptions} options Restore options. + * @returns {Promise} + */ + restore(options: RestoreOptions): Promise; + request(reqOpts: DecorateRequestOptions): Promise; + request(reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void; + rotateEncryptionKey(options?: RotateEncryptionKeyOptions): Promise; + rotateEncryptionKey(callback: RotateEncryptionKeyCallback): void; + rotateEncryptionKey(options: RotateEncryptionKeyOptions, callback: RotateEncryptionKeyCallback): void; + save(data: SaveData, options?: SaveOptions): Promise; + save(data: SaveData, callback: SaveCallback): void; + save(data: SaveData, options: SaveOptions, callback: SaveCallback): void; + setMetadata(metadata: FileMetadata, options?: SetMetadataOptions): Promise>; + setMetadata(metadata: FileMetadata, callback: MetadataCallback): void; + setMetadata(metadata: FileMetadata, options: SetMetadataOptions, callback: MetadataCallback): void; + setStorageClass(storageClass: string, options?: SetStorageClassOptions): Promise; + setStorageClass(storageClass: string, options: SetStorageClassOptions, callback: SetStorageClassCallback): void; + setStorageClass(storageClass: string, callback?: SetStorageClassCallback): void; + /** + * Set a user project to be billed for all requests made from this File + * object. + * + * @param {string} userProject The user project. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * const file = bucket.file('my-file'); + * + * file.setUserProject('grape-spaceship-123'); + * ``` + */ + setUserProject(userProject: string): void; + /** + * This creates a resumable-upload upload stream. + * + * @param {Duplexify} stream - Duplexify stream of data to pipe to the file. + * @param {object=} options - Configuration object. + * + * @private + */ + startResumableUpload_(dup: Duplexify, options?: CreateResumableUploadOptions): void; + /** + * Takes a readable stream and pipes it to a remote file. Unlike + * `startResumableUpload_`, which uses the resumable upload technique, this + * method uses a simple upload (all or nothing). + * + * @param {Duplexify} dup - Duplexify stream of data to pipe to the file. + * @param {object=} options - Configuration object. + * + * @private + */ + startSimpleUpload_(dup: Duplexify, options?: CreateWriteStreamOptions): void; + disableAutoRetryConditionallyIdempotent_(coreOpts: any, methodType: AvailableServiceObjectMethods, localPreconditionOptions?: PreconditionOptions): void; + private getBufferFromReadable; +} +/** + * Reference to the {@link File} class. + * @name module:@google-cloud/storage.File + * @see File + */ +export { File }; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/file.js b/node_modules/@google-cloud/storage/build/cjs/src/file.js new file mode 100644 index 0000000..0101325 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/file.js @@ -0,0 +1,3592 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +var _File_instances, _File_validateIntegrity; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.File = exports.FileExceptionMessages = exports.RequestError = exports.STORAGE_POST_POLICY_BASE_URL = exports.ActionToHTTPMethod = void 0; +const index_js_1 = require("./nodejs-common/index.js"); +const promisify_1 = require("@google-cloud/promisify"); +const crypto = __importStar(require("crypto")); +const fs = __importStar(require("fs")); +const mime_1 = __importDefault(require("mime")); +const resumableUpload = __importStar(require("./resumable-upload.js")); +const stream_1 = require("stream"); +const zlib = __importStar(require("zlib")); +const storage_js_1 = require("./storage.js"); +const bucket_js_1 = require("./bucket.js"); +const acl_js_1 = require("./acl.js"); +const signer_js_1 = require("./signer.js"); +const util_js_1 = require("./nodejs-common/util.js"); +const duplexify_1 = __importDefault(require("duplexify")); +const util_js_2 = require("./util.js"); +const crc32c_js_1 = require("./crc32c.js"); +const hash_stream_validator_js_1 = require("./hash-stream-validator.js"); +const async_retry_1 = __importDefault(require("async-retry")); +var ActionToHTTPMethod; +(function (ActionToHTTPMethod) { + ActionToHTTPMethod["read"] = "GET"; + ActionToHTTPMethod["write"] = "PUT"; + ActionToHTTPMethod["delete"] = "DELETE"; + ActionToHTTPMethod["resumable"] = "POST"; +})(ActionToHTTPMethod || (exports.ActionToHTTPMethod = ActionToHTTPMethod = {})); +/** + * @deprecated - no longer used + */ +exports.STORAGE_POST_POLICY_BASE_URL = 'https://storage.googleapis.com'; +/** + * @private + */ +const GS_URL_REGEXP = /^gs:\/\/([a-z0-9_.-]+)\/(.+)$/; +/** + * @private + * This regex will match compressible content types. These are primarily text/*, +json, +text, +xml content types. + * This was based off of mime-db and may periodically need to be updated if new compressible content types become + * standards. + */ +const COMPRESSIBLE_MIME_REGEX = new RegExp([ + /^text\/|application\/ecmascript|application\/javascript|application\/json/, + /|application\/postscript|application\/rtf|application\/toml|application\/vnd.dart/, + /|application\/vnd.ms-fontobject|application\/wasm|application\/x-httpd-php|application\/x-ns-proxy-autoconfig/, + /|application\/x-sh(?!ockwave-flash)|application\/x-tar|application\/x-virtualbox-hdd|application\/x-virtualbox-ova|application\/x-virtualbox-ovf/, + /|^application\/x-virtualbox-vbox$|application\/x-virtualbox-vdi|application\/x-virtualbox-vhd|application\/x-virtualbox-vmdk/, + /|application\/xml|application\/xml-dtd|font\/otf|font\/ttf|image\/bmp|image\/vnd.adobe.photoshop|image\/vnd.microsoft.icon/, + /|image\/vnd.ms-dds|image\/x-icon|image\/x-ms-bmp|message\/rfc822|model\/gltf-binary|\+json|\+text|\+xml|\+yaml/, +] + .map(r => r.source) + .join(''), 'i'); +class RequestError extends Error { +} +exports.RequestError = RequestError; +const SEVEN_DAYS = 7 * 24 * 60 * 60; +const GS_UTIL_URL_REGEX = /(gs):\/\/([a-z0-9_.-]+)\/(.+)/g; +const HTTPS_PUBLIC_URL_REGEX = /(https):\/\/(storage\.googleapis\.com)\/([a-z0-9_.-]+)\/(.+)/g; +var FileExceptionMessages; +(function (FileExceptionMessages) { + FileExceptionMessages["EXPIRATION_TIME_NA"] = "An expiration time is not available."; + FileExceptionMessages["DESTINATION_NO_NAME"] = "Destination file should have a name."; + FileExceptionMessages["INVALID_VALIDATION_FILE_RANGE"] = "Cannot use validation with file ranges (start/end)."; + FileExceptionMessages["MD5_NOT_AVAILABLE"] = "MD5 verification was specified, but is not available for the requested object. MD5 is not available for composite objects."; + FileExceptionMessages["EQUALS_CONDITION_TWO_ELEMENTS"] = "Equals condition must be an array of 2 elements."; + FileExceptionMessages["STARTS_WITH_TWO_ELEMENTS"] = "StartsWith condition must be an array of 2 elements."; + FileExceptionMessages["CONTENT_LENGTH_RANGE_MIN_MAX"] = "ContentLengthRange must have numeric min & max fields."; + FileExceptionMessages["DOWNLOAD_MISMATCH"] = "The downloaded data did not match the data from the server. To be sure the content is the same, you should download the file again."; + FileExceptionMessages["UPLOAD_MISMATCH_DELETE_FAIL"] = "The uploaded data did not match the data from the server.\n As a precaution, we attempted to delete the file, but it was not successful.\n To be sure the content is the same, you should try removing the file manually,\n then uploading the file again.\n \n\nThe delete attempt failed with this message:\n\n "; + FileExceptionMessages["UPLOAD_MISMATCH"] = "The uploaded data did not match the data from the server.\n As a precaution, the file has been deleted.\n To be sure the content is the same, you should try uploading the file again."; + FileExceptionMessages["MD5_RESUMED_UPLOAD"] = "MD5 cannot be used with a continued resumable upload as MD5 cannot be extended from an existing value"; + FileExceptionMessages["MISSING_RESUME_CRC32C_FINAL_UPLOAD"] = "The CRC32C is missing for the final portion of a resumed upload, which is required for validation. Please provide `resumeCRC32C` if validation is required, or disable `validation`."; +})(FileExceptionMessages || (exports.FileExceptionMessages = FileExceptionMessages = {})); +/** + * A File object is created from your {@link Bucket} object using + * {@link Bucket#file}. + * + * @class + */ +class File extends index_js_1.ServiceObject { + /** + * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share objects with other + * users and allow other users to access your buckets and objects. + * + * An ACL consists of one or more entries, where each entry grants permissions + * to an entity. Permissions define the actions that can be performed against + * an object or bucket (for example, `READ` or `WRITE`); the entity defines + * who the permission applies to (for example, a specific user or group of + * users). + * + * The `acl` object on a File instance provides methods to get you a list of + * the ACLs defined on your bucket, as well as set, update, and delete them. + * + * See {@link http://goo.gl/6qBBPO| About Access Control lists} + * + * @name File#acl + * @mixes Acl + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * //- + * // Make a file publicly readable. + * //- + * const options = { + * entity: 'allUsers', + * role: storage.acl.READER_ROLE + * }; + * + * file.acl.add(options, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.acl.add(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + /** + * The API-formatted resource description of the file. + * + * Note: This is not guaranteed to be up-to-date when accessed. To get the + * latest record, call the `getMetadata()` method. + * + * @name File#metadata + * @type {object} + */ + /** + * The file's name. + * @name File#name + * @type {string} + */ + /** + * @callback Crc32cGeneratorToStringCallback + * A method returning the CRC32C as a base64-encoded string. + * + * @returns {string} + * + * @example + * Hashing the string 'data' should return 'rth90Q==' + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.toString(); // 'rth90Q==' + * ``` + **/ + /** + * @callback Crc32cGeneratorValidateCallback + * A method validating a base64-encoded CRC32C string. + * + * @param {string} [value] base64-encoded CRC32C string to validate + * @returns {boolean} + * + * @example + * Should return `true` if the value matches, `false` otherwise + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.validate('DkjKuA=='); // false + * crc32c.validate('rth90Q=='); // true + * ``` + **/ + /** + * @callback Crc32cGeneratorUpdateCallback + * A method for passing `Buffer`s for CRC32C generation. + * + * @param {Buffer} [data] data to update CRC32C value with + * @returns {undefined} + * + * @example + * Hashing buffers from 'some ' and 'text\n' + * + * ```js + * const buffer1 = Buffer.from('some '); + * crc32c.update(buffer1); + * + * const buffer2 = Buffer.from('text\n'); + * crc32c.update(buffer2); + * + * crc32c.toString(); // 'DkjKuA==' + * ``` + **/ + /** + * @typedef {object} CRC32CValidator + * @property {Crc32cGeneratorToStringCallback} + * @property {Crc32cGeneratorValidateCallback} + * @property {Crc32cGeneratorUpdateCallback} + */ + /** + * @callback Crc32cGeneratorCallback + * @returns {CRC32CValidator} + */ + /** + * @typedef {object} FileOptions Options passed to the File constructor. + * @property {string} [encryptionKey] A custom encryption key. + * @property {number} [generation] Generation to scope the file to. + * @property {string} [kmsKeyName] Cloud KMS Key used to encrypt this + * object, if the object is encrypted by such a key. Limited availability; + * usable only by enabled projects. + * @property {string} [userProject] The ID of the project which will be + * billed for all requests made from File object. + * @property {Crc32cGeneratorCallback} [callback] A function that generates a CRC32C Validator. Defaults to {@link CRC32C} + */ + /** + * Constructs a file object. + * + * @param {Bucket} bucket The Bucket instance this file is + * attached to. + * @param {string} name The name of the remote file. + * @param {FileOptions} [options] Configuration options. + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * ``` + */ + constructor(bucket, name, options = {}) { + var _a, _b; + const requestQueryObject = {}; + let generation; + if (options.generation !== null) { + if (typeof options.generation === 'string') { + generation = Number(options.generation); + } + else { + generation = options.generation; + } + if (!isNaN(generation)) { + requestQueryObject.generation = generation; + } + } + Object.assign(requestQueryObject, options.preconditionOpts); + const userProject = options.userProject || bucket.userProject; + if (typeof userProject === 'string') { + requestQueryObject.userProject = userProject; + } + const methods = { + /** + * @typedef {array} DeleteFileResponse + * @property {object} 0 The full API response. + */ + /** + * @callback DeleteFileCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Delete the file. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/delete| Objects: delete API Documentation} + * + * @method File#delete + * @param {object} [options] Configuration options. + * @param {boolean} [options.ignoreNotFound = false] Ignore an error if + * the file does not exist. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {DeleteFileCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * file.delete(function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.delete().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example include:samples/files.js + * region_tag:storage_delete_file + * Another example: + */ + delete: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {array} FileExistsResponse + * @property {boolean} 0 Whether the {@link File} exists. + */ + /** + * @callback FileExistsCallback + * @param {?Error} err Request error, if any. + * @param {boolean} exists Whether the {@link File} exists. + */ + /** + * Check if the file exists. + * + * @method File#exists + * @param {options} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {FileExistsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * file.exists(function(err, exists) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.exists().then(function(data) { + * const exists = data[0]; + * }); + * ``` + */ + exists: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {array} GetFileResponse + * @property {File} 0 The {@link File}. + * @property {object} 1 The full API response. + */ + /** + * @callback GetFileCallback + * @param {?Error} err Request error, if any. + * @param {File} file The {@link File}. + * @param {object} apiResponse The full API response. + */ + /** + * Get a file object and its metadata if it exists. + * + * @method File#get + * @param {options} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {number} [options.generation] The generation number to get + * @param {string} [options.restoreToken] If this is a soft-deleted object in an HNS-enabled bucket, returns the restore token which will + * be necessary to restore it if there's a name conflict with another object. + * @param {boolean} [options.softDeleted] If true, returns the soft-deleted object. + Object `generation` is required if `softDeleted` is set to True. + * @param {GetFileCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * file.get(function(err, file, apiResponse) { + * // file.metadata` has been populated. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.get().then(function(data) { + * const file = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + get: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {array} GetFileMetadataResponse + * @property {object} 0 The {@link File} metadata. + * @property {object} 1 The full API response. + */ + /** + * @callback GetFileMetadataCallback + * @param {?Error} err Request error, if any. + * @param {object} metadata The {@link File} metadata. + * @param {object} apiResponse The full API response. + */ + /** + * Get the file's metadata. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/get| Objects: get API Documentation} + * + * @method File#getMetadata + * @param {object} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetFileMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * file.getMetadata(function(err, metadata, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.getMetadata().then(function(data) { + * const metadata = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/files.js + * region_tag:storage_get_metadata + * Another example: + */ + getMetadata: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {object} SetFileMetadataOptions Configuration options for File#setMetadata(). + * @param {string} [userProject] The ID of the project which will be billed for the request. + */ + /** + * @callback SetFileMetadataCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} SetFileMetadataResponse + * @property {object} 0 The full API response. + */ + /** + * Merge the given metadata with the current remote file's metadata. This + * will set metadata if it was previously unset or update previously set + * metadata. To unset previously set metadata, set its value to null. + * + * You can set custom key/value pairs in the metadata key of the given + * object, however the other properties outside of this object must adhere + * to the {@link https://goo.gl/BOnnCK| official API documentation}. + * + * + * See the examples below for more information. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/patch| Objects: patch API Documentation} + * + * @method File#setMetadata + * @param {object} [metadata] The metadata you wish to update. + * @param {SetFileMetadataOptions} [options] Configuration options. + * @param {SetFileMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * const metadata = { + * contentType: 'application/x-font-ttf', + * metadata: { + * my: 'custom', + * properties: 'go here' + * } + * }; + * + * file.setMetadata(metadata, function(err, apiResponse) {}); + * + * // Assuming current metadata = { hello: 'world', unsetMe: 'will do' } + * file.setMetadata({ + * metadata: { + * abc: '123', // will be set. + * unsetMe: null, // will be unset (deleted). + * hello: 'goodbye' // will be updated from 'world' to 'goodbye'. + * } + * }, function(err, apiResponse) { + * // metadata should now be { abc: '123', hello: 'goodbye' } + * }); + * + * //- + * // Set a temporary hold on this file from its bucket's retention period + * // configuration. + * // + * file.setMetadata({ + * temporaryHold: true + * }, function(err, apiResponse) {}); + * + * //- + * // Alternatively, you may set a temporary hold. This will follow the + * // same behavior as an event-based hold, with the exception that the + * // bucket's retention policy will not renew for this file from the time + * // the hold is released. + * //- + * file.setMetadata({ + * eventBasedHold: true + * }, function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.setMetadata(metadata).then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + setMetadata: { + reqOpts: { + qs: requestQueryObject, + }, + }, + }; + super({ + parent: bucket, + baseUrl: '/o', + id: encodeURIComponent(name), + methods, + }); + _File_instances.add(this); + this.bucket = bucket; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.storage = bucket.parent; + // @TODO Can this duplicate code from above be avoided? + if (options.generation !== null) { + let generation; + if (typeof options.generation === 'string') { + generation = Number(options.generation); + } + else { + generation = options.generation; + } + if (!isNaN(generation)) { + this.generation = generation; + } + } + this.kmsKeyName = options.kmsKeyName; + this.userProject = userProject; + this.name = name; + if (options.encryptionKey) { + this.setEncryptionKey(options.encryptionKey); + } + this.acl = new acl_js_1.Acl({ + request: this.request.bind(this), + pathPrefix: '/acl', + }); + this.crc32cGenerator = + options.crc32cGenerator || this.bucket.crc32cGenerator; + this.instanceRetryValue = (_b = (_a = this.storage) === null || _a === void 0 ? void 0 : _a.retryOptions) === null || _b === void 0 ? void 0 : _b.autoRetry; + this.instancePreconditionOpts = options === null || options === void 0 ? void 0 : options.preconditionOpts; + } + /** + * The object's Cloud Storage URI (`gs://`) + * + * @example + * ```ts + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const file = bucket.file('image.png'); + * + * // `gs://my-bucket/image.png` + * const href = file.cloudStorageURI.href; + * ``` + */ + get cloudStorageURI() { + const uri = this.bucket.cloudStorageURI; + uri.pathname = this.name; + return uri; + } + /** + * A helper method for determining if a request should be retried based on preconditions. + * This should only be used for methods where the idempotency is determined by + * `ifGenerationMatch` + * @private + * + * A request should not be retried under the following conditions: + * - if precondition option `ifGenerationMatch` is not set OR + * - if `idempotencyStrategy` is set to `RetryNever` + */ + shouldRetryBasedOnPreconditionAndIdempotencyStrat(options) { + var _a; + return !(((options === null || options === void 0 ? void 0 : options.ifGenerationMatch) === undefined && + ((_a = this.instancePreconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) === undefined && + this.storage.retryOptions.idempotencyStrategy === + storage_js_1.IdempotencyStrategy.RetryConditional) || + this.storage.retryOptions.idempotencyStrategy === + storage_js_1.IdempotencyStrategy.RetryNever); + } + /** + * @typedef {array} CopyResponse + * @property {File} 0 The copied {@link File}. + * @property {object} 1 The full API response. + */ + /** + * @callback CopyCallback + * @param {?Error} err Request error, if any. + * @param {File} copiedFile The copied {@link File}. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {object} CopyOptions Configuration options for File#copy(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}. + * @property {string} [cacheControl] The cacheControl setting for the new file. + * @property {string} [contentEncoding] The contentEncoding setting for the new file. + * @property {string} [contentType] The contentType setting for the new file. + * @property {string} [destinationKmsKeyName] Resource name of the Cloud + * KMS key, of the form + * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`, + * that will be used to encrypt the object. Overwrites the object + * metadata's `kms_key_name` value, if any. + * @property {Metadata} [metadata] Metadata to specify on the copied file. + * @property {string} [predefinedAcl] Set the ACL for the new file. + * @property {string} [token] A previously-returned `rewriteToken` from an + * unfinished rewrite request. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * Copy this file to another file. By default, this will copy the file to the + * same bucket, but you can choose to copy it to another Bucket by providing + * a Bucket or File object or a URL starting with "gs://". + * The generation of the file will not be preserved. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/rewrite| Objects: rewrite API Documentation} + * + * @throws {Error} If the destination file is not provided. + * + * @param {string|Bucket|File} destination Destination file. + * @param {CopyOptions} [options] Configuration options. See an + * @param {CopyCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // You can pass in a variety of types for the destination. + * // + * // For all of the below examples, assume we are working with the following + * // Bucket and File objects. + * //- + * const bucket = storage.bucket('my-bucket'); + * const file = bucket.file('my-image.png'); + * + * //- + * // If you pass in a string for the destination, the file is copied to its + * // current bucket, under the new name provided. + * //- + * file.copy('my-image-copy.png', function(err, copiedFile, apiResponse) { + * // `my-bucket` now contains: + * // - "my-image.png" + * // - "my-image-copy.png" + * + * // `copiedFile` is an instance of a File object that refers to your new + * // file. + * }); + * + * //- + * // If you pass in a string starting with "gs://" for the destination, the + * // file is copied to the other bucket and under the new name provided. + * //- + * const newLocation = 'gs://another-bucket/my-image-copy.png'; + * file.copy(newLocation, function(err, copiedFile, apiResponse) { + * // `my-bucket` still contains: + * // - "my-image.png" + * // + * // `another-bucket` now contains: + * // - "my-image-copy.png" + * + * // `copiedFile` is an instance of a File object that refers to your new + * // file. + * }); + * + * //- + * // If you pass in a Bucket object, the file will be copied to that bucket + * // using the same name. + * //- + * const anotherBucket = storage.bucket('another-bucket'); + * file.copy(anotherBucket, function(err, copiedFile, apiResponse) { + * // `my-bucket` still contains: + * // - "my-image.png" + * // + * // `another-bucket` now contains: + * // - "my-image.png" + * + * // `copiedFile` is an instance of a File object that refers to your new + * // file. + * }); + * + * //- + * // If you pass in a File object, you have complete control over the new + * // bucket and filename. + * //- + * const anotherFile = anotherBucket.file('my-awesome-image.png'); + * file.copy(anotherFile, function(err, copiedFile, apiResponse) { + * // `my-bucket` still contains: + * // - "my-image.png" + * // + * // `another-bucket` now contains: + * // - "my-awesome-image.png" + * + * // Note: + * // The `copiedFile` parameter is equal to `anotherFile`. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.copy(newLocation).then(function(data) { + * const newFile = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/files.js + * region_tag:storage_copy_file + * Another example: + */ + copy(destination, optionsOrCallback, callback) { + var _a, _b; + const noDestinationError = new Error(FileExceptionMessages.DESTINATION_NO_NAME); + if (!destination) { + throw noDestinationError; + } + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else if (optionsOrCallback) { + options = { ...optionsOrCallback }; + } + callback = callback || index_js_1.util.noop; + let destBucket; + let destName; + let newFile; + if (typeof destination === 'string') { + const parsedDestination = GS_URL_REGEXP.exec(destination); + if (parsedDestination !== null && parsedDestination.length === 3) { + destBucket = this.storage.bucket(parsedDestination[1]); + destName = parsedDestination[2]; + } + else { + destBucket = this.bucket; + destName = destination; + } + } + else if (destination instanceof bucket_js_1.Bucket) { + destBucket = destination; + destName = this.name; + } + else if (destination instanceof File) { + destBucket = destination.bucket; + destName = destination.name; + newFile = destination; + } + else { + throw noDestinationError; + } + const query = {}; + if (this.generation !== undefined) { + query.sourceGeneration = this.generation; + } + if (options.token !== undefined) { + query.rewriteToken = options.token; + } + if (options.userProject !== undefined) { + query.userProject = options.userProject; + delete options.userProject; + } + if (options.predefinedAcl !== undefined) { + query.destinationPredefinedAcl = options.predefinedAcl; + delete options.predefinedAcl; + } + newFile = newFile || destBucket.file(destName); + const headers = {}; + if (this.encryptionKey !== undefined) { + headers['x-goog-copy-source-encryption-algorithm'] = 'AES256'; + headers['x-goog-copy-source-encryption-key'] = this.encryptionKeyBase64; + headers['x-goog-copy-source-encryption-key-sha256'] = + this.encryptionKeyHash; + } + if (newFile.encryptionKey !== undefined) { + this.setEncryptionKey(newFile.encryptionKey); + } + else if (options.destinationKmsKeyName !== undefined) { + query.destinationKmsKeyName = options.destinationKmsKeyName; + delete options.destinationKmsKeyName; + } + else if (newFile.kmsKeyName !== undefined) { + query.destinationKmsKeyName = newFile.kmsKeyName; + } + if (query.destinationKmsKeyName) { + this.kmsKeyName = query.destinationKmsKeyName; + const keyIndex = this.interceptors.indexOf(this.encryptionKeyInterceptor); + if (keyIndex > -1) { + this.interceptors.splice(keyIndex, 1); + } + } + if (!this.shouldRetryBasedOnPreconditionAndIdempotencyStrat(options === null || options === void 0 ? void 0 : options.preconditionOpts)) { + this.storage.retryOptions.autoRetry = false; + } + if (((_a = options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) !== undefined) { + query.ifGenerationMatch = (_b = options.preconditionOpts) === null || _b === void 0 ? void 0 : _b.ifGenerationMatch; + delete options.preconditionOpts; + } + this.request({ + method: 'POST', + uri: `/rewriteTo/b/${destBucket.name}/o/${encodeURIComponent(newFile.name)}`, + qs: query, + json: options, + headers, + }, (err, resp) => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + if (err) { + callback(err, null, resp); + return; + } + if (resp.rewriteToken) { + const options = { + token: resp.rewriteToken, + }; + if (query.userProject) { + options.userProject = query.userProject; + } + if (query.destinationKmsKeyName) { + options.destinationKmsKeyName = query.destinationKmsKeyName; + } + this.copy(newFile, options, callback); + return; + } + callback(null, newFile, resp); + }); + } + /** + * @typedef {object} CreateReadStreamOptions Configuration options for File#createReadStream. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {string|boolean} [validation] Possible values: `"md5"`, + * `"crc32c"`, or `false`. By default, data integrity is validated with a + * CRC32c checksum. You may use MD5 if preferred, but that hash is not + * supported for composite objects. An error will be raised if MD5 is + * specified but is not available. You may also choose to skip validation + * completely, however this is **not recommended**. + * @property {number} [start] A byte offset to begin the file's download + * from. Default is 0. NOTE: Byte ranges are inclusive; that is, + * `options.start = 0` and `options.end = 999` represent the first 1000 + * bytes in a file or object. NOTE: when specifying a byte range, data + * integrity is not available. + * @property {number} [end] A byte offset to stop reading the file at. + * NOTE: Byte ranges are inclusive; that is, `options.start = 0` and + * `options.end = 999` represent the first 1000 bytes in a file or object. + * NOTE: when specifying a byte range, data integrity is not available. + * @property {boolean} [decompress=true] Disable auto decompression of the + * received data. By default this option is set to `true`. + * Applicable in cases where the data was uploaded with + * `gzip: true` option. See {@link File#createWriteStream}. + */ + /** + * Create a readable stream to read the contents of the remote file. It can be + * piped to a writable stream or listened to for 'data' events to read a + * file's contents. + * + * In the unlikely event there is a mismatch between what you downloaded and + * the version in your Bucket, your error handler will receive an error with + * code "CONTENT_DOWNLOAD_MISMATCH". If you receive this error, the best + * recourse is to try downloading the file again. + * + * NOTE: Readable streams will emit the `end` event when the file is fully + * downloaded. + * + * @param {CreateReadStreamOptions} [options] Configuration options. + * @returns {ReadableStream} + * + * @example + * ``` + * //- + * //

Downloading a File

+ * // + * // The example below demonstrates how we can reference a remote file, then + * // pipe its contents to a local file. This is effectively creating a local + * // backup of your remote data. + * //- + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * const fs = require('fs'); + * const remoteFile = bucket.file('image.png'); + * const localFilename = '/Users/stephen/Photos/image.png'; + * + * remoteFile.createReadStream() + * .on('error', function(err) {}) + * .on('response', function(response) { + * // Server connected and responded with the specified status and headers. + * }) + * .on('end', function() { + * // The file is fully downloaded. + * }) + * .pipe(fs.createWriteStream(localFilename)); + * + * //- + * // To limit the downloaded data to only a byte range, pass an options + * // object. + * //- + * const logFile = myBucket.file('access_log'); + * logFile.createReadStream({ + * start: 10000, + * end: 20000 + * }) + * .on('error', function(err) {}) + * .pipe(fs.createWriteStream('/Users/stephen/logfile.txt')); + * + * //- + * // To read a tail byte range, specify only `options.end` as a negative + * // number. + * //- + * const logFile = myBucket.file('access_log'); + * logFile.createReadStream({ + * end: -100 + * }) + * .on('error', function(err) {}) + * .pipe(fs.createWriteStream('/Users/stephen/logfile.txt')); + * ``` + */ + createReadStream(options = {}) { + options = Object.assign({ decompress: true }, options); + const rangeRequest = typeof options.start === 'number' || typeof options.end === 'number'; + const tailRequest = options.end < 0; + let validateStream = undefined; + let request = undefined; + const throughStream = new util_js_2.PassThroughShim(); + let crc32c = true; + let md5 = false; + if (typeof options.validation === 'string') { + const value = options.validation.toLowerCase().trim(); + crc32c = value === 'crc32c'; + md5 = value === 'md5'; + } + else if (options.validation === false) { + crc32c = false; + } + const shouldRunValidation = !rangeRequest && (crc32c || md5); + if (rangeRequest) { + if (typeof options.validation === 'string' || + options.validation === true) { + throw new Error(FileExceptionMessages.INVALID_VALIDATION_FILE_RANGE); + } + // Range requests can't receive data integrity checks. + crc32c = false; + md5 = false; + } + const onComplete = (err) => { + if (err) { + // There is an issue with node-fetch 2.x that if the stream errors the underlying socket connection is not closed. + // This causes a memory leak, so cleanup the sockets manually here by destroying the agent. + if (request === null || request === void 0 ? void 0 : request.agent) { + request.agent.destroy(); + } + throughStream.destroy(err); + } + }; + // We listen to the response event from the request stream so that we + // can... + // + // 1) Intercept any data from going to the user if an error occurred. + // 2) Calculate the hashes from the http.IncomingMessage response + // stream, + // which will return the bytes from the source without decompressing + // gzip'd content. We then send it through decompressed, if + // applicable, to the user. + const onResponse = (err, _body, rawResponseStream) => { + if (err) { + // Get error message from the body. + this.getBufferFromReadable(rawResponseStream).then(body => { + err.message = body.toString('utf8'); + throughStream.destroy(err); + }); + return; + } + request = rawResponseStream.request; + const headers = rawResponseStream.toJSON().headers; + const isCompressed = headers['content-encoding'] === 'gzip'; + const hashes = {}; + // The object is safe to validate if: + // 1. It was stored gzip and returned to us gzip OR + // 2. It was never stored as gzip + const safeToValidate = (headers['x-goog-stored-content-encoding'] === 'gzip' && + isCompressed) || + headers['x-goog-stored-content-encoding'] === 'identity'; + const transformStreams = []; + if (shouldRunValidation) { + // The x-goog-hash header should be set with a crc32c and md5 hash. + // ex: headers['x-goog-hash'] = 'crc32c=xxxx,md5=xxxx' + if (typeof headers['x-goog-hash'] === 'string') { + headers['x-goog-hash'] + .split(',') + .forEach((hashKeyValPair) => { + const delimiterIndex = hashKeyValPair.indexOf('='); + const hashType = hashKeyValPair.substring(0, delimiterIndex); + const hashValue = hashKeyValPair.substring(delimiterIndex + 1); + hashes[hashType] = hashValue; + }); + } + validateStream = new hash_stream_validator_js_1.HashStreamValidator({ + crc32c, + md5, + crc32cGenerator: this.crc32cGenerator, + crc32cExpected: hashes.crc32c, + md5Expected: hashes.md5, + }); + } + if (md5 && !hashes.md5) { + const hashError = new RequestError(FileExceptionMessages.MD5_NOT_AVAILABLE); + hashError.code = 'MD5_NOT_AVAILABLE'; + throughStream.destroy(hashError); + return; + } + if (safeToValidate && shouldRunValidation && validateStream) { + transformStreams.push(validateStream); + } + if (isCompressed && options.decompress) { + transformStreams.push(zlib.createGunzip()); + } + (0, stream_1.pipeline)(rawResponseStream, ...transformStreams, throughStream, onComplete); + }; + // Authenticate the request, then pipe the remote API request to the stream + // returned to the user. + const makeRequest = () => { + const query = { alt: 'media' }; + if (this.generation) { + query.generation = this.generation; + } + if (options.userProject) { + query.userProject = options.userProject; + } + const headers = { + 'Accept-Encoding': 'gzip', + 'Cache-Control': 'no-store', + }; + if (rangeRequest) { + const start = typeof options.start === 'number' ? options.start : '0'; + const end = typeof options.end === 'number' ? options.end : ''; + headers.Range = `bytes=${tailRequest ? end : `${start}-${end}`}`; + } + const reqOpts = { + uri: '', + headers, + qs: query, + }; + if (options[util_js_1.GCCL_GCS_CMD_KEY]) { + reqOpts[util_js_1.GCCL_GCS_CMD_KEY] = options[util_js_1.GCCL_GCS_CMD_KEY]; + } + this.requestStream(reqOpts) + .on('error', err => { + throughStream.destroy(err); + }) + .on('response', res => { + throughStream.emit('response', res); + index_js_1.util.handleResp(null, res, null, onResponse); + }) + .resume(); + }; + throughStream.on('reading', makeRequest); + return throughStream; + } + /** + * @callback CreateResumableUploadCallback + * @param {?Error} err Request error, if any. + * @param {string} uri The resumable upload's unique session URI. + */ + /** + * @typedef {array} CreateResumableUploadResponse + * @property {string} 0 The resumable upload's unique session URI. + */ + /** + * @typedef {object} CreateResumableUploadOptions + * @property {object} [metadata] Metadata to set on the file. + * @property {number} [offset] The starting byte of the upload stream for resuming an interrupted upload. + * @property {string} [origin] Origin header to set for the upload. + * @property {string} [predefinedAcl] Apply a predefined set of access + * controls to this object. + * + * Acceptable values are: + * - **`authenticatedRead`** - Object owner gets `OWNER` access, and + * `allAuthenticatedUsers` get `READER` access. + * + * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and + * project team owners get `OWNER` access. + * + * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project + * team owners get `READER` access. + * + * - **`private`** - Object owner gets `OWNER` access. + * + * - **`projectPrivate`** - Object owner gets `OWNER` access, and project + * team members get access according to their roles. + * + * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers` + * get `READER` access. + * @property {boolean} [private] Make the uploaded file private. (Alias for + * `options.predefinedAcl = 'private'`) + * @property {boolean} [public] Make the uploaded file public. (Alias for + * `options.predefinedAcl = 'publicRead'`) + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {string} [chunkSize] Create a separate request per chunk. This + * value is in bytes and should be a multiple of 256 KiB (2^18). + * {@link https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload| We recommend using at least 8 MiB for the chunk size.} + */ + /** + * Create a unique resumable upload session URI. This is the first step when + * performing a resumable upload. + * + * See the {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload| Resumable upload guide} + * for more on how the entire process works. + * + *

Note

+ * + * If you are just looking to perform a resumable upload without worrying + * about any of the details, see {@link File#createWriteStream}. Resumable + * uploads are performed by default. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload| Resumable upload guide} + * + * @param {CreateResumableUploadOptions} [options] Configuration options. + * @param {CreateResumableUploadCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * file.createResumableUpload(function(err, uri) { + * if (!err) { + * // `uri` can be used to PUT data to. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.createResumableUpload().then(function(data) { + * const uri = data[0]; + * }); + * ``` + */ + createResumableUpload(optionsOrCallback, callback) { + var _a, _b; + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + const retryOptions = this.storage.retryOptions; + if ((((_a = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) === undefined && + ((_b = this.instancePreconditionOpts) === null || _b === void 0 ? void 0 : _b.ifGenerationMatch) === undefined && + this.storage.retryOptions.idempotencyStrategy === + storage_js_1.IdempotencyStrategy.RetryConditional) || + this.storage.retryOptions.idempotencyStrategy === + storage_js_1.IdempotencyStrategy.RetryNever) { + retryOptions.autoRetry = false; + } + resumableUpload.createURI({ + authClient: this.storage.authClient, + apiEndpoint: this.storage.apiEndpoint, + bucket: this.bucket.name, + customRequestOptions: this.getRequestInterceptors().reduce((reqOpts, interceptorFn) => interceptorFn(reqOpts), {}), + file: this.name, + generation: this.generation, + key: this.encryptionKey, + kmsKeyName: this.kmsKeyName, + metadata: options.metadata, + offset: options.offset, + origin: options.origin, + predefinedAcl: options.predefinedAcl, + private: options.private, + public: options.public, + userProject: options.userProject || this.userProject, + retryOptions: retryOptions, + params: (options === null || options === void 0 ? void 0 : options.preconditionOpts) || this.instancePreconditionOpts, + universeDomain: this.bucket.storage.universeDomain, + useAuthWithCustomEndpoint: this.storage.useAuthWithCustomEndpoint, + [util_js_1.GCCL_GCS_CMD_KEY]: options[util_js_1.GCCL_GCS_CMD_KEY], + }, callback); + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + } + /** + * @typedef {object} CreateWriteStreamOptions Configuration options for File#createWriteStream(). + * @property {string} [contentType] Alias for + * `options.metadata.contentType`. If set to `auto`, the file name is used + * to determine the contentType. + * @property {string|boolean} [gzip] If true, automatically gzip the file. + * If set to `auto`, the contentType is used to determine if the file + * should be gzipped. This will set `options.metadata.contentEncoding` to + * `gzip` if necessary. + * @property {object} [metadata] See the examples below or + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON| Objects: insert request body} + * for more details. + * @property {number} [offset] The starting byte of the upload stream, for + * resuming an interrupted upload. Defaults to 0. + * @property {string} [predefinedAcl] Apply a predefined set of access + * controls to this object. + * + * Acceptable values are: + * - **`authenticatedRead`** - Object owner gets `OWNER` access, and + * `allAuthenticatedUsers` get `READER` access. + * + * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and + * project team owners get `OWNER` access. + * + * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project + * team owners get `READER` access. + * + * - **`private`** - Object owner gets `OWNER` access. + * + * - **`projectPrivate`** - Object owner gets `OWNER` access, and project + * team members get access according to their roles. + * + * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers` + * get `READER` access. + * @property {boolean} [private] Make the uploaded file private. (Alias for + * `options.predefinedAcl = 'private'`) + * @property {boolean} [public] Make the uploaded file public. (Alias for + * `options.predefinedAcl = 'publicRead'`) + * @property {boolean} [resumable] Force a resumable upload. NOTE: When + * working with streams, the file format and size is unknown until it's + * completely consumed. Because of this, it's best for you to be explicit + * for what makes sense given your input. + * @property {number} [timeout=60000] Set the HTTP request timeout in + * milliseconds. This option is not available for resumable uploads. + * Default: `60000` + * @property {string} [uri] The URI for an already-created resumable + * upload. See {@link File#createResumableUpload}. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {string|boolean} [validation] Possible values: `"md5"`, + * `"crc32c"`, or `false`. By default, data integrity is validated with a + * CRC32c checksum. You may use MD5 if preferred, but that hash is not + * supported for composite objects. An error will be raised if MD5 is + * specified but is not available. You may also choose to skip validation + * completely, however this is **not recommended**. In addition to specifying + * validation type, providing `metadata.crc32c` or `metadata.md5Hash` will + * cause the server to perform validation in addition to client validation. + * NOTE: Validation is automatically skipped for objects that were + * uploaded using the `gzip` option and have already compressed content. + */ + /** + * Create a writable stream to overwrite the contents of the file in your + * bucket. + * + * A File object can also be used to create files for the first time. + * + * Resumable uploads are automatically enabled and must be shut off explicitly + * by setting `options.resumable` to `false`. + * + * + *

+ * There is some overhead when using a resumable upload that can cause + * noticeable performance degradation while uploading a series of small + * files. When uploading files less than 10MB, it is recommended that the + * resumable feature is disabled. + *

+ * + * NOTE: Writable streams will emit the `finish` event when the file is fully + * uploaded. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload Upload Options (Simple or Resumable)} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert Objects: insert API Documentation} + * + * @param {CreateWriteStreamOptions} [options] Configuration options. + * @returns {WritableStream} + * + * @example + * ``` + * const fs = require('fs'); + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * //- + * //

Uploading a File

+ * // + * // Now, consider a case where we want to upload a file to your bucket. You + * // have the option of using {@link Bucket#upload}, but that is just + * // a convenience method which will do the following. + * //- + * fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg') + * .pipe(file.createWriteStream()) + * .on('error', function(err) {}) + * .on('finish', function() { + * // The file upload is complete. + * }); + * + * //- + * //

Uploading a File with gzip compression

+ * //- + * fs.createReadStream('/Users/stephen/site/index.html') + * .pipe(file.createWriteStream({ gzip: true })) + * .on('error', function(err) {}) + * .on('finish', function() { + * // The file upload is complete. + * }); + * + * //- + * // Downloading the file with `createReadStream` will automatically decode + * // the file. + * //- + * + * //- + * //

Uploading a File with Metadata

+ * // + * // One last case you may run into is when you want to upload a file to your + * // bucket and set its metadata at the same time. Like above, you can use + * // {@link Bucket#upload} to do this, which is just a wrapper around + * // the following. + * //- + * fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg') + * .pipe(file.createWriteStream({ + * metadata: { + * contentType: 'image/jpeg', + * metadata: { + * custom: 'metadata' + * } + * } + * })) + * .on('error', function(err) {}) + * .on('finish', function() { + * // The file upload is complete. + * }); + * ``` + * + * //- + * //

Continuing a Resumable Upload

+ * // + * // One can capture a `uri` from a resumable upload to reuse later. + * // Additionally, for validation, one can also capture and pass `crc32c`. + * //- + * let uri: string | undefined = undefined; + * let resumeCRC32C: string | undefined = undefined; + * + * fs.createWriteStream() + * .on('uri', link => {uri = link}) + * .on('crc32', crc32c => {resumeCRC32C = crc32c}); + * + * // later... + * fs.createWriteStream({uri, resumeCRC32C}); + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + createWriteStream(options = {}) { + var _a; + (_a = options.metadata) !== null && _a !== void 0 ? _a : (options.metadata = {}); + if (options.contentType) { + options.metadata.contentType = options.contentType; + } + if (!options.metadata.contentType || + options.metadata.contentType === 'auto') { + const detectedContentType = mime_1.default.getType(this.name); + if (detectedContentType) { + options.metadata.contentType = detectedContentType; + } + } + let gzip = options.gzip; + if (gzip === 'auto') { + gzip = COMPRESSIBLE_MIME_REGEX.test(options.metadata.contentType || ''); + } + if (gzip) { + options.metadata.contentEncoding = 'gzip'; + } + let crc32c = true; + let md5 = false; + if (typeof options.validation === 'string') { + options.validation = options.validation.toLowerCase(); + crc32c = options.validation === 'crc32c'; + md5 = options.validation === 'md5'; + } + else if (options.validation === false) { + crc32c = false; + md5 = false; + } + if (options.offset) { + if (md5) { + throw new RangeError(FileExceptionMessages.MD5_RESUMED_UPLOAD); + } + if (crc32c && !options.isPartialUpload && !options.resumeCRC32C) { + throw new RangeError(FileExceptionMessages.MISSING_RESUME_CRC32C_FINAL_UPLOAD); + } + } + /** + * A callback for determining when the underlying pipeline is complete. + * It's possible the pipeline callback could error before the write stream + * calls `final` so by default this will destroy the write stream unless the + * write stream sets this callback via its `final` handler. + * @param error An optional error + */ + let pipelineCallback = error => { + writeStream.destroy(error || undefined); + }; + // A stream for consumer to write to + const writeStream = new stream_1.Writable({ + final(cb) { + // Set the pipeline callback to this callback so the pipeline's results + // can be populated to the consumer + pipelineCallback = cb; + emitStream.end(); + }, + write(chunk, encoding, cb) { + emitStream.write(chunk, encoding, cb); + }, + }); + // If the write stream, which is returned to the caller, catches an error we need to make sure that + // at least one of the streams in the pipeline below gets notified so that they + // all get cleaned up / destroyed. + writeStream.once('error', e => { + emitStream.destroy(e); + }); + // If the write stream is closed, cleanup the pipeline below by calling destroy on one of the streams. + writeStream.once('close', () => { + emitStream.destroy(); + }); + const transformStreams = []; + if (gzip) { + transformStreams.push(zlib.createGzip()); + } + const emitStream = new util_js_2.PassThroughShim(); + // If `writeStream` is destroyed before the `writing` event, `emitStream` will not have any listeners. This prevents an unhandled error. + const noop = () => { }; + emitStream.on('error', noop); + let hashCalculatingStream = null; + if (crc32c || md5) { + const crc32cInstance = options.resumeCRC32C + ? crc32c_js_1.CRC32C.from(options.resumeCRC32C) + : undefined; + hashCalculatingStream = new hash_stream_validator_js_1.HashStreamValidator({ + crc32c, + crc32cInstance, + md5, + crc32cGenerator: this.crc32cGenerator, + updateHashesOnly: true, + }); + transformStreams.push(hashCalculatingStream); + } + const fileWriteStream = (0, duplexify_1.default)(); + let fileWriteStreamMetadataReceived = false; + // Handing off emitted events to users + emitStream.on('reading', () => writeStream.emit('reading')); + emitStream.on('writing', () => writeStream.emit('writing')); + fileWriteStream.on('uri', evt => writeStream.emit('uri', evt)); + fileWriteStream.on('progress', evt => writeStream.emit('progress', evt)); + fileWriteStream.on('response', resp => writeStream.emit('response', resp)); + fileWriteStream.once('metadata', () => { + fileWriteStreamMetadataReceived = true; + }); + writeStream.once('writing', () => { + if (options.resumable === false) { + this.startSimpleUpload_(fileWriteStream, options); + } + else { + this.startResumableUpload_(fileWriteStream, options); + } + // remove temporary noop listener as we now create a pipeline that handles the errors + emitStream.removeListener('error', noop); + (0, stream_1.pipeline)(emitStream, ...transformStreams, fileWriteStream, async (e) => { + if (e) { + return pipelineCallback(e); + } + // We want to make sure we've received the metadata from the server in order + // to properly validate the object's integrity. Depending on the type of upload, + // the stream could close before the response is returned. + if (!fileWriteStreamMetadataReceived) { + try { + await new Promise((resolve, reject) => { + fileWriteStream.once('metadata', resolve); + fileWriteStream.once('error', reject); + }); + } + catch (e) { + return pipelineCallback(e); + } + } + // Emit the local CRC32C value for future validation, if validation is enabled. + if (hashCalculatingStream === null || hashCalculatingStream === void 0 ? void 0 : hashCalculatingStream.crc32c) { + writeStream.emit('crc32c', hashCalculatingStream.crc32c); + } + try { + // Metadata may not be ready if the upload is a partial upload, + // nothing to validate yet. + const metadataNotReady = options.isPartialUpload && !this.metadata; + if (hashCalculatingStream && !metadataNotReady) { + await __classPrivateFieldGet(this, _File_instances, "m", _File_validateIntegrity).call(this, hashCalculatingStream, { + crc32c, + md5, + }); + } + pipelineCallback(); + } + catch (e) { + pipelineCallback(e); + } + }); + }); + return writeStream; + } + delete(optionsOrCallback, cb) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + cb = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb; + this.disableAutoRetryConditionallyIdempotent_(this.methods.delete, bucket_js_1.AvailableServiceObjectMethods.delete, options); + super + .delete(options) + .then(resp => cb(null, ...resp)) + .catch(cb) + .finally(() => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + }); + } + /** + * @typedef {array} DownloadResponse + * @property [0] The contents of a File. + */ + /** + * @callback DownloadCallback + * @param err Request error, if any. + * @param contents The contents of a File. + */ + /** + * Convenience method to download a file into memory or to a local + * destination. + * + * @param {object} [options] Configuration options. The arguments match those + * passed to {@link File#createReadStream}. + * @param {string} [options.destination] Local file path to write the file's + * contents to. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {DownloadCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * //- + * // Download a file into memory. The contents will be available as the + * second + * // argument in the demonstration below, `contents`. + * //- + * file.download(function(err, contents) {}); + * + * //- + * // Download a file to a local destination. + * //- + * file.download({ + * destination: '/Users/me/Desktop/file-backup.txt' + * }, function(err) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.download().then(function(data) { + * const contents = data[0]; + * }); + * + * ``` + * @example include:samples/files.js + * region_tag:storage_download_file + * Another example: + * + * @example include:samples/encryption.js + * region_tag:storage_download_encrypted_file + * Example of downloading an encrypted file: + * + * @example include:samples/requesterPays.js + * region_tag:storage_download_file_requester_pays + * Example of downloading a file where the requester pays: + */ + download(optionsOrCallback, cb) { + let options; + if (typeof optionsOrCallback === 'function') { + cb = optionsOrCallback; + options = {}; + } + else { + options = Object.assign({}, optionsOrCallback); + } + let called = false; + const callback = ((...args) => { + if (!called) + cb(...args); + called = true; + }); + const destination = options.destination; + delete options.destination; + if (options.encryptionKey) { + this.setEncryptionKey(options.encryptionKey); + delete options.encryptionKey; + } + const fileStream = this.createReadStream(options); + let receivedData = false; + if (destination) { + fileStream + .on('error', callback) + .once('data', data => { + receivedData = true; + // We know that the file exists the server - now we can truncate/write to a file + const writable = fs.createWriteStream(destination); + writable.write(data); + fileStream + .pipe(writable) + .on('error', (err) => { + callback(err, Buffer.from('')); + }) + .on('finish', () => { + callback(null, data); + }); + }) + .on('end', () => { + // In the case of an empty file no data will be received before the end event fires + if (!receivedData) { + const data = Buffer.alloc(0); + try { + fs.writeFileSync(destination, data); + callback(null, data); + } + catch (e) { + callback(e, data); + } + } + }); + } + else { + this.getBufferFromReadable(fileStream) + .then(contents => callback === null || callback === void 0 ? void 0 : callback(null, contents)) + .catch(callback); + } + } + /** + * The Storage API allows you to use a custom key for server-side encryption. + * + * See {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys} + * + * @param {string|buffer} encryptionKey An AES-256 encryption key. + * @returns {File} + * + * @example + * ``` + * const crypto = require('crypto'); + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const encryptionKey = crypto.randomBytes(32); + * + * const fileWithCustomEncryption = myBucket.file('my-file'); + * fileWithCustomEncryption.setEncryptionKey(encryptionKey); + * + * const fileWithoutCustomEncryption = myBucket.file('my-file'); + * + * fileWithCustomEncryption.save('data', function(err) { + * // Try to download with the File object that hasn't had + * // `setEncryptionKey()` called: + * fileWithoutCustomEncryption.download(function(err) { + * // We will receive an error: + * // err.message === 'Bad Request' + * + * // Try again with the File object we called `setEncryptionKey()` on: + * fileWithCustomEncryption.download(function(err, contents) { + * // contents.toString() === 'data' + * }); + * }); + * }); + * + * ``` + * @example include:samples/encryption.js + * region_tag:storage_upload_encrypted_file + * Example of uploading an encrypted file: + * + * @example include:samples/encryption.js + * region_tag:storage_download_encrypted_file + * Example of downloading an encrypted file: + */ + setEncryptionKey(encryptionKey) { + this.encryptionKey = encryptionKey; + this.encryptionKeyBase64 = Buffer.from(encryptionKey).toString('base64'); + this.encryptionKeyHash = crypto + .createHash('sha256') + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .update(this.encryptionKeyBase64, 'base64') + .digest('base64'); + this.encryptionKeyInterceptor = { + request: reqOpts => { + reqOpts.headers = reqOpts.headers || {}; + reqOpts.headers['x-goog-encryption-algorithm'] = 'AES256'; + reqOpts.headers['x-goog-encryption-key'] = this.encryptionKeyBase64; + reqOpts.headers['x-goog-encryption-key-sha256'] = + this.encryptionKeyHash; + return reqOpts; + }, + }; + this.interceptors.push(this.encryptionKeyInterceptor); + return this; + } + /** + * Gets a reference to a Cloud Storage {@link File} file from the provided URL in string format. + * @param {string} publicUrlOrGsUrl the URL as a string. Must be of the format gs://bucket/file + * or https://storage.googleapis.com/bucket/file. + * @param {Storage} storageInstance an instance of a Storage object. + * @param {FileOptions} [options] Configuration options + * @returns {File} + */ + static from(publicUrlOrGsUrl, storageInstance, options) { + const gsMatches = [...publicUrlOrGsUrl.matchAll(GS_UTIL_URL_REGEX)]; + const httpsMatches = [...publicUrlOrGsUrl.matchAll(HTTPS_PUBLIC_URL_REGEX)]; + if (gsMatches.length > 0) { + const bucket = new bucket_js_1.Bucket(storageInstance, gsMatches[0][2]); + return new File(bucket, gsMatches[0][3], options); + } + else if (httpsMatches.length > 0) { + const bucket = new bucket_js_1.Bucket(storageInstance, httpsMatches[0][3]); + return new File(bucket, httpsMatches[0][4], options); + } + else { + throw new Error('URL string must be of format gs://bucket/file or https://storage.googleapis.com/bucket/file'); + } + } + get(optionsOrCallback, cb) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + cb = + typeof optionsOrCallback === 'function' + ? optionsOrCallback + : cb; + super + .get(options) + .then(resp => cb(null, ...resp)) + .catch(cb); + } + /** + * @typedef {array} GetExpirationDateResponse + * @property {date} 0 A Date object representing the earliest time this file's + * retention policy will expire. + */ + /** + * @callback GetExpirationDateCallback + * @param {?Error} err Request error, if any. + * @param {date} expirationDate A Date object representing the earliest time + * this file's retention policy will expire. + */ + /** + * If this bucket has a retention policy defined, use this method to get a + * Date object representing the earliest time this file will expire. + * + * @param {GetExpirationDateCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * file.getExpirationDate(function(err, expirationDate) { + * // expirationDate is a Date object. + * }); + * ``` + */ + getExpirationDate(callback) { + this.getMetadata((err, metadata, apiResponse) => { + if (err) { + callback(err, null, apiResponse); + return; + } + if (!metadata.retentionExpirationTime) { + const error = new Error(FileExceptionMessages.EXPIRATION_TIME_NA); + callback(error, null, apiResponse); + return; + } + callback(null, new Date(metadata.retentionExpirationTime), apiResponse); + }); + } + /** + * @typedef {array} GenerateSignedPostPolicyV2Response + * @property {object} 0 The document policy. + */ + /** + * @callback GenerateSignedPostPolicyV2Callback + * @param {?Error} err Request error, if any. + * @param {object} policy The document policy. + */ + /** + * Get a signed policy document to allow a user to upload data with a POST + * request. + * + * In Google Cloud Platform environments, such as Cloud Functions and App + * Engine, you usually don't provide a `keyFilename` or `credentials` during + * instantiation. In those environments, we call the + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob| signBlob API} + * to create a signed policy. That API requires either the + * `https://www.googleapis.com/auth/iam` or + * `https://www.googleapis.com/auth/cloud-platform` scope, so be sure they are + * enabled. + * + * See {@link https://cloud.google.com/storage/docs/xml-api/post-object-v2| POST Object with the V2 signing process} + * + * @throws {Error} If an expiration timestamp from the past is given. + * @throws {Error} If options.equals has an array with less or more than two + * members. + * @throws {Error} If options.startsWith has an array with less or more than two + * members. + * + * @param {object} options Configuration options. + * @param {array|array[]} [options.equals] Array of request parameters and + * their expected value (e.g. [['$', '']]). Values are + * translated into equality constraints in the conditions field of the + * policy document (e.g. ['eq', '$', '']). If only one + * equality condition is to be specified, options.equals can be a one- + * dimensional array (e.g. ['$', '']). + * @param {*} options.expires - A timestamp when this policy will expire. Any + * value given is passed to `new Date()`. + * @param {array|array[]} [options.startsWith] Array of request parameters and + * their expected prefixes (e.g. [['$', '']). Values are + * translated into starts-with constraints in the conditions field of the + * policy document (e.g. ['starts-with', '$', '']). If only + * one prefix condition is to be specified, options.startsWith can be a + * one- dimensional array (e.g. ['$', '']). + * @param {string} [options.acl] ACL for the object from possibly predefined + * ACLs. + * @param {string} [options.successRedirect] The URL to which the user client + * is redirected if the upload is successful. + * @param {string} [options.successStatus] - The status of the Google Storage + * response if the upload is successful (must be string). + * @param {object} [options.contentLengthRange] + * @param {number} [options.contentLengthRange.min] Minimum value for the + * request's content length. + * @param {number} [options.contentLengthRange.max] Maximum value for the + * request's content length. + * @param {GenerateSignedPostPolicyV2Callback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * const options = { + * equals: ['$Content-Type', 'image/jpeg'], + * expires: '10-25-2022', + * contentLengthRange: { + * min: 0, + * max: 1024 + * } + * }; + * + * file.generateSignedPostPolicyV2(options, function(err, policy) { + * // policy.string: the policy document in plain text. + * // policy.base64: the policy document in base64. + * // policy.signature: the policy signature in base64. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.generateSignedPostPolicyV2(options).then(function(data) { + * const policy = data[0]; + * }); + * ``` + */ + generateSignedPostPolicyV2(optionsOrCallback, cb) { + const args = (0, util_js_2.normalize)(optionsOrCallback, cb); + let options = args.options; + const callback = args.callback; + const expires = new Date(options.expires); + if (isNaN(expires.getTime())) { + throw new Error(storage_js_1.ExceptionMessages.EXPIRATION_DATE_INVALID); + } + if (expires.valueOf() < Date.now()) { + throw new Error(storage_js_1.ExceptionMessages.EXPIRATION_DATE_PAST); + } + options = Object.assign({}, options); + const conditions = [ + ['eq', '$key', this.name], + { + bucket: this.bucket.name, + }, + ]; + if (Array.isArray(options.equals)) { + if (!Array.isArray(options.equals[0])) { + options.equals = [options.equals]; + } + options.equals.forEach(condition => { + if (!Array.isArray(condition) || condition.length !== 2) { + throw new Error(FileExceptionMessages.EQUALS_CONDITION_TWO_ELEMENTS); + } + conditions.push(['eq', condition[0], condition[1]]); + }); + } + if (Array.isArray(options.startsWith)) { + if (!Array.isArray(options.startsWith[0])) { + options.startsWith = [options.startsWith]; + } + options.startsWith.forEach(condition => { + if (!Array.isArray(condition) || condition.length !== 2) { + throw new Error(FileExceptionMessages.STARTS_WITH_TWO_ELEMENTS); + } + conditions.push(['starts-with', condition[0], condition[1]]); + }); + } + if (options.acl) { + conditions.push({ + acl: options.acl, + }); + } + if (options.successRedirect) { + conditions.push({ + success_action_redirect: options.successRedirect, + }); + } + if (options.successStatus) { + conditions.push({ + success_action_status: options.successStatus, + }); + } + if (options.contentLengthRange) { + const min = options.contentLengthRange.min; + const max = options.contentLengthRange.max; + if (typeof min !== 'number' || typeof max !== 'number') { + throw new Error(FileExceptionMessages.CONTENT_LENGTH_RANGE_MIN_MAX); + } + conditions.push(['content-length-range', min, max]); + } + const policy = { + expiration: expires.toISOString(), + conditions, + }; + const policyString = JSON.stringify(policy); + const policyBase64 = Buffer.from(policyString).toString('base64'); + this.storage.authClient.sign(policyBase64, options.signingEndpoint).then(signature => { + callback(null, { + string: policyString, + base64: policyBase64, + signature, + }); + }, err => { + callback(new signer_js_1.SigningError(err.message)); + }); + } + /** + * @typedef {object} SignedPostPolicyV4Output + * @property {string} url The request URL. + * @property {object} fields The form fields to include in the POST request. + */ + /** + * @typedef {array} GenerateSignedPostPolicyV4Response + * @property {SignedPostPolicyV4Output} 0 An object containing the request URL and form fields. + */ + /** + * @callback GenerateSignedPostPolicyV4Callback + * @param {?Error} err Request error, if any. + * @param {SignedPostPolicyV4Output} output An object containing the request URL and form fields. + */ + /** + * Get a v4 signed policy document to allow a user to upload data with a POST + * request. + * + * In Google Cloud Platform environments, such as Cloud Functions and App + * Engine, you usually don't provide a `keyFilename` or `credentials` during + * instantiation. In those environments, we call the + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob| signBlob API} + * to create a signed policy. That API requires either the + * `https://www.googleapis.com/auth/iam` or + * `https://www.googleapis.com/auth/cloud-platform` scope, so be sure they are + * enabled. + * + * See {@link https://cloud.google.com/storage/docs/xml-api/post-object#policydocument| Policy Document Reference} + * + * @param {object} options Configuration options. + * @param {Date|number|string} options.expires - A timestamp when this policy will expire. Any + * value given is passed to `new Date()`. + * @param {boolean} [config.virtualHostedStyle=false] Use virtual hosted-style + * URLs ('https://mybucket.storage.googleapis.com/...') instead of path-style + * ('https://storage.googleapis.com/mybucket/...'). Virtual hosted-style URLs + * should generally be preferred instead of path-style URL. + * Currently defaults to `false` for path-style, although this may change in a + * future major-version release. + * @param {string} [config.bucketBoundHostname] The bucket-bound hostname to return in + * the result, e.g. "https://cdn.example.com". + * @param {object} [config.fields] [Form fields]{@link https://cloud.google.com/storage/docs/xml-api/post-object#policydocument} + * to include in the signed policy. Any fields with key beginning with 'x-ignore-' + * will not be included in the policy to be signed. + * @param {object[]} [config.conditions] [Conditions]{@link https://cloud.google.com/storage/docs/authentication/signatures#policy-document} + * to include in the signed policy. All fields given in `config.fields` are + * automatically included in the conditions array, adding the same entry + * in both `fields` and `conditions` will result in duplicate entries. + * + * @param {GenerateSignedPostPolicyV4Callback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * const options = { + * expires: '10-25-2022', + * conditions: [ + * ['eq', '$Content-Type', 'image/jpeg'], + * ['content-length-range', 0, 1024], + * ], + * fields: { + * acl: 'public-read', + * 'x-goog-meta-foo': 'bar', + * 'x-ignore-mykey': 'data' + * } + * }; + * + * file.generateSignedPostPolicyV4(options, function(err, response) { + * // response.url The request URL + * // response.fields The form fields (including the signature) to include + * // to be used to upload objects by HTML forms. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.generateSignedPostPolicyV4(options).then(function(data) { + * const response = data[0]; + * // response.url The request URL + * // response.fields The form fields (including the signature) to include + * // to be used to upload objects by HTML forms. + * }); + * ``` + */ + generateSignedPostPolicyV4(optionsOrCallback, cb) { + const args = (0, util_js_2.normalize)(optionsOrCallback, cb); + let options = args.options; + const callback = args.callback; + const expires = new Date(options.expires); + if (isNaN(expires.getTime())) { + throw new Error(storage_js_1.ExceptionMessages.EXPIRATION_DATE_INVALID); + } + if (expires.valueOf() < Date.now()) { + throw new Error(storage_js_1.ExceptionMessages.EXPIRATION_DATE_PAST); + } + if (expires.valueOf() - Date.now() > SEVEN_DAYS * 1000) { + throw new Error(`Max allowed expiration is seven days (${SEVEN_DAYS} seconds).`); + } + options = Object.assign({}, options); + let fields = Object.assign({}, options.fields); + const now = new Date(); + const nowISO = (0, util_js_2.formatAsUTCISO)(now, true); + const todayISO = (0, util_js_2.formatAsUTCISO)(now); + const sign = async () => { + const { client_email } = await this.storage.authClient.getCredentials(); + const credential = `${client_email}/${todayISO}/auto/storage/goog4_request`; + fields = { + ...fields, + bucket: this.bucket.name, + key: this.name, + 'x-goog-date': nowISO, + 'x-goog-credential': credential, + 'x-goog-algorithm': 'GOOG4-RSA-SHA256', + }; + const conditions = options.conditions || []; + Object.entries(fields).forEach(([key, value]) => { + if (!key.startsWith('x-ignore-')) { + conditions.push({ [key]: value }); + } + }); + delete fields.bucket; + const expiration = (0, util_js_2.formatAsUTCISO)(expires, true, '-', ':'); + const policy = { + conditions, + expiration, + }; + const policyString = (0, util_js_2.unicodeJSONStringify)(policy); + const policyBase64 = Buffer.from(policyString).toString('base64'); + try { + const signature = await this.storage.authClient.sign(policyBase64, options.signingEndpoint); + const signatureHex = Buffer.from(signature, 'base64').toString('hex'); + const universe = this.parent.storage.universeDomain; + fields['policy'] = policyBase64; + fields['x-goog-signature'] = signatureHex; + let url; + if (this.storage.customEndpoint) { + url = this.storage.apiEndpoint; + } + else if (options.virtualHostedStyle) { + url = `https://${this.bucket.name}.storage.${universe}/`; + } + else if (options.bucketBoundHostname) { + url = `${options.bucketBoundHostname}/`; + } + else { + url = `https://storage.${universe}/${this.bucket.name}/`; + } + return { + url, + fields, + }; + } + catch (err) { + throw new signer_js_1.SigningError(err.message); + } + }; + sign().then(res => callback(null, res), callback); + } + /** + * @typedef {array} GetSignedUrlResponse + * @property {object} 0 The signed URL. + */ + /** + * @callback GetSignedUrlCallback + * @param {?Error} err Request error, if any. + * @param {object} url The signed URL. + */ + /** + * Get a signed URL to allow limited time access to the file. + * + * In Google Cloud Platform environments, such as Cloud Functions and App + * Engine, you usually don't provide a `keyFilename` or `credentials` during + * instantiation. In those environments, we call the + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob| signBlob API} + * to create a signed URL. That API requires either the + * `https://www.googleapis.com/auth/iam` or + * `https://www.googleapis.com/auth/cloud-platform` scope, so be sure they are + * enabled. + * + * See {@link https://cloud.google.com/storage/docs/access-control/signed-urls| Signed URLs Reference} + * + * @throws {Error} if an expiration timestamp from the past is given. + * + * @param {object} config Configuration object. + * @param {string} config.action "read" (HTTP: GET), "write" (HTTP: PUT), or + * "delete" (HTTP: DELETE), "resumable" (HTTP: POST). + * When using "resumable", the header `X-Goog-Resumable: start` has + * to be sent when making a request with the signed URL. + * @param {*} config.expires A timestamp when this link will expire. Any value + * given is passed to `new Date()`. + * Note: 'v4' supports maximum duration of 7 days (604800 seconds) from now. + * See [reference]{@link https://cloud.google.com/storage/docs/access-control/signed-urls#example} + * @param {string} [config.version='v2'] The signing version to use, either + * 'v2' or 'v4'. + * @param {boolean} [config.virtualHostedStyle=false] Use virtual hosted-style + * URLs (e.g. 'https://mybucket.storage.googleapis.com/...') instead of path-style + * (e.g. 'https://storage.googleapis.com/mybucket/...'). Virtual hosted-style URLs + * should generally be preferred instead of path-style URL. + * Currently defaults to `false` for path-style, although this may change in a + * future major-version release. + * @param {string} [config.cname] The cname for this bucket, i.e., + * "https://cdn.example.com". + * @param {string} [config.contentMd5] The MD5 digest value in base64. Just like + * if you provide this, the client must provide this HTTP header with this same + * value in its request, so to if this parameter is not provided here, + * the client must not provide any value for this HTTP header in its request. + * @param {string} [config.contentType] Just like if you provide this, the client + * must provide this HTTP header with this same value in its request, so to if + * this parameter is not provided here, the client must not provide any value + * for this HTTP header in its request. + * @param {object} [config.extensionHeaders] If these headers are used, the + * server will check to make sure that the client provides matching + * values. See {@link https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers| Canonical extension headers} + * for the requirements of this feature, most notably: + * - The header name must be prefixed with `x-goog-` + * - The header name must be all lowercase + * + * Note: Multi-valued header passed as an array in the extensionHeaders + * object is converted into a string, delimited by `,` with + * no space. Requests made using the signed URL will need to + * delimit multi-valued headers using a single `,` as well, or + * else the server will report a mismatched signature. + * @param {object} [config.queryParams] Additional query parameters to include + * in the signed URL. + * @param {string} [config.promptSaveAs] The filename to prompt the user to + * save the file as when the signed url is accessed. This is ignored if + * `config.responseDisposition` is set. + * @param {string} [config.responseDisposition] The + * {@link http://goo.gl/yMWxQV| response-content-disposition parameter} of the + * signed url. + * @param {*} [config.accessibleAt=Date.now()] A timestamp when this link became usable. Any value + * given is passed to `new Date()`. + * Note: Use for 'v4' only. + * @param {string} [config.responseType] The response-content-type parameter + * of the signed url. + * @param {GetSignedUrlCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * //- + * // Generate a URL that allows temporary access to download your file. + * //- + * const request = require('request'); + * + * const config = { + * action: 'read', + * expires: '03-17-2025', + * }; + * + * file.getSignedUrl(config, function(err, url) { + * if (err) { + * console.error(err); + * return; + * } + * + * // The file is now available to read from this URL. + * request(url, function(err, resp) { + * // resp.statusCode = 200 + * }); + * }); + * + * //- + * // Generate a URL that allows temporary access to download your file. + * // Access will begin at accessibleAt and end at expires. + * //- + * const request = require('request'); + * + * const config = { + * action: 'read', + * expires: '03-17-2025', + * accessibleAt: '03-13-2025' + * }; + * + * file.getSignedUrl(config, function(err, url) { + * if (err) { + * console.error(err); + * return; + * } + * + * // The file will be available to read from this URL from 03-13-2025 to 03-17-2025. + * request(url, function(err, resp) { + * // resp.statusCode = 200 + * }); + * }); + * + * //- + * // Generate a URL to allow write permissions. This means anyone with this + * URL + * // can send a POST request with new data that will overwrite the file. + * //- + * file.getSignedUrl({ + * action: 'write', + * expires: '03-17-2025' + * }, function(err, url) { + * if (err) { + * console.error(err); + * return; + * } + * + * // The file is now available to be written to. + * const writeStream = request.put(url); + * writeStream.end('New data'); + * + * writeStream.on('complete', function(resp) { + * // Confirm the new content was saved. + * file.download(function(err, fileContents) { + * console.log('Contents:', fileContents.toString()); + * // Contents: New data + * }); + * }); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.getSignedUrl(config).then(function(data) { + * const url = data[0]; + * }); + * + * ``` + * @example include:samples/files.js + * region_tag:storage_generate_signed_url + * Another example: + */ + getSignedUrl(cfg, callback) { + const method = ActionToHTTPMethod[cfg.action]; + const extensionHeaders = (0, util_js_2.objectKeyToLowercase)(cfg.extensionHeaders || {}); + if (cfg.action === 'resumable') { + extensionHeaders['x-goog-resumable'] = 'start'; + } + const queryParams = Object.assign({}, cfg.queryParams); + if (typeof cfg.responseType === 'string') { + queryParams['response-content-type'] = cfg.responseType; + } + if (typeof cfg.promptSaveAs === 'string') { + queryParams['response-content-disposition'] = + 'attachment; filename="' + cfg.promptSaveAs + '"'; + } + if (typeof cfg.responseDisposition === 'string') { + queryParams['response-content-disposition'] = cfg.responseDisposition; + } + if (this.generation) { + queryParams['generation'] = this.generation.toString(); + } + const signConfig = { + method, + expires: cfg.expires, + accessibleAt: cfg.accessibleAt, + extensionHeaders, + queryParams, + contentMd5: cfg.contentMd5, + contentType: cfg.contentType, + host: cfg.host, + }; + if (cfg.cname) { + signConfig.cname = cfg.cname; + } + if (cfg.version) { + signConfig.version = cfg.version; + } + if (cfg.virtualHostedStyle) { + signConfig.virtualHostedStyle = cfg.virtualHostedStyle; + } + if (!this.signer) { + this.signer = new signer_js_1.URLSigner(this.storage.authClient, this.bucket, this, this.storage); + } + this.signer + .getSignedUrl(signConfig) + .then(signedUrl => callback(null, signedUrl), callback); + } + /** + * @callback IsPublicCallback + * @param {?Error} err Request error, if any. + * @param {boolean} resp Whether file is public or not. + */ + /** + * @typedef {array} IsPublicResponse + * @property {boolean} 0 Whether file is public or not. + */ + /** + * Check whether this file is public or not by sending + * a HEAD request without credentials. + * No errors from the server indicates that the current + * file is public. + * A 403-Forbidden error {@link https://cloud.google.com/storage/docs/json_api/v1/status-codes#403_Forbidden} + * indicates that file is private. + * Any other non 403 error is propagated to user. + * + * @param {IsPublicCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * //- + * // Check whether the file is publicly accessible. + * //- + * file.isPublic(function(err, resp) { + * if (err) { + * console.error(err); + * return; + * } + * console.log(`the file ${file.id} is public: ${resp}`) ; + * }) + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.isPublic().then(function(data) { + * const resp = data[0]; + * }); + * ``` + */ + isPublic(callback) { + var _a; + // Build any custom headers based on the defined interceptors on the parent + // storage object and this object + const storageInterceptors = ((_a = this.storage) === null || _a === void 0 ? void 0 : _a.interceptors) || []; + const fileInterceptors = this.interceptors || []; + const allInterceptors = storageInterceptors.concat(fileInterceptors); + const headers = allInterceptors.reduce((acc, curInterceptor) => { + const currentHeaders = curInterceptor.request({ + uri: `${this.storage.apiEndpoint}/${this.bucket.name}/${encodeURIComponent(this.name)}`, + }); + Object.assign(acc, currentHeaders.headers); + return acc; + }, {}); + index_js_1.util.makeRequest({ + method: 'GET', + uri: `${this.storage.apiEndpoint}/${this.bucket.name}/${encodeURIComponent(this.name)}`, + headers, + }, { + retryOptions: this.storage.retryOptions, + }, (err) => { + if (err) { + const apiError = err; + if (apiError.code === 403) { + callback(null, false); + } + else { + callback(err); + } + } + else { + callback(null, true); + } + }); + } + /** + * @typedef {object} MakeFilePrivateOptions Configuration options for File#makePrivate(). + * @property {Metadata} [metadata] Define custom metadata properties to define + * along with the operation. + * @property {boolean} [strict] If true, set the file to be private to + * only the owner user. Otherwise, it will be private to the project. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @callback MakeFilePrivateCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} MakeFilePrivateResponse + * @property {object} 0 The full API response. + */ + /** + * Make a file private to the project and remove all other permissions. + * Set `options.strict` to true to make the file private to only the owner. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/patch| Objects: patch API Documentation} + * + * @param {MakeFilePrivateOptions} [options] Configuration options. + * @param {MakeFilePrivateCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * //- + * // Set the file private so only project maintainers can see and modify it. + * //- + * file.makePrivate(function(err) {}); + * + * //- + * // Set the file private so only the owner can see and modify it. + * //- + * file.makePrivate({ strict: true }, function(err) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.makePrivate().then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + makePrivate(optionsOrCallback, callback) { + var _a, _b; + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + const query = { + predefinedAcl: options.strict ? 'private' : 'projectPrivate', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }; + if (((_a = options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifMetagenerationMatch) !== undefined) { + query.ifMetagenerationMatch = + (_b = options.preconditionOpts) === null || _b === void 0 ? void 0 : _b.ifMetagenerationMatch; + delete options.preconditionOpts; + } + if (options.userProject) { + query.userProject = options.userProject; + } + // You aren't allowed to set both predefinedAcl & acl properties on a file, + // so acl must explicitly be nullified, destroying all previous acls on the + // file. + const metadata = { ...options.metadata, acl: null }; + this.setMetadata(metadata, query, callback); + } + /** + * @typedef {array} MakeFilePublicResponse + * @property {object} 0 The full API response. + */ + /** + * @callback MakeFilePublicCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Set a file to be publicly readable and maintain all previous permissions. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/insert| ObjectAccessControls: insert API Documentation} + * + * @param {MakeFilePublicCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * file.makePublic(function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.makePublic().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example include:samples/files.js + * region_tag:storage_make_public + * Another example: + */ + makePublic(callback) { + callback = callback || index_js_1.util.noop; + this.acl.add({ + entity: 'allUsers', + role: 'READER', + }, (err, acl, resp) => { + callback(err, resp); + }); + } + /** + * The public URL of this File + * Use {@link File#makePublic} to enable anonymous access via the returned URL. + * + * @returns {string} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * const file = bucket.file('my-file'); + * + * // publicUrl will be "https://storage.googleapis.com/albums/my-file" + * const publicUrl = file.publicUrl(); + * ``` + */ + publicUrl() { + return `${this.storage.apiEndpoint}/${this.bucket.name}/${encodeURIComponent(this.name)}`; + } + /** + * @typedef {array} MoveFileAtomicResponse + * @property {File} 0 The moved {@link File}. + * @property {object} 1 The full API response. + */ + /** + * @callback MoveFileAtomicCallback + * @param {?Error} err Request error, if any. + * @param {File} movedFile The moved {@link File}. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {object} MoveFileAtomicOptions Configuration options for File#moveFileAtomic(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {object} [preconditionOpts] Precondition options. + * @property {number} [preconditionOpts.ifGenerationMatch] Makes the operation conditional on whether the object's current generation matches the given value. + */ + /** + * Move this file within the same bucket. + * The source object must exist and be a live object. + * The source and destination object IDs must be different. + * Overwriting the destination object is allowed by default, but can be prevented + * using preconditions. + * If the destination path includes non-existent parent folders, they will be created. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/move| Objects: move API Documentation} + * + * @throws {Error} If the destination file is not provided. + * + * @param {string|File} destination Destination file name or File object within the same bucket.. + * @param {MoveFileAtomicOptions} [options] Configuration options. See an + * @param {MoveFileAtomicCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // Assume 'my-bucket' is a bucket. + * //- + * const bucket = storage.bucket('my-bucket'); + * const file = bucket.file('my-image.png'); + * + * //- + * // If you pass in a string for the destination, the file is copied to its + * // current bucket, under the new name provided. + * //- + * file.moveFileAtomic('moved-image.png', function(err, movedFile, apiResponse) { + * // `my-bucket` now contains: + * // - "moved-image.png" + * + * // `movedFile` is an instance of a File object that refers to your new + * // file. + * }); + * + * //- + * // Move the file to a subdirectory, creating parent folders if necessary. + * //- + * file.moveFileAtomic('new-folder/subfolder/moved-image.png', function(err, movedFile, apiResponse) { + * // `my-bucket` now contains: + * // - "new-folder/subfolder/moved-image.png" + * }); + * + * //- + * // Prevent overwriting an existing destination object using preconditions. + * //- + * file.moveFileAtomic('existing-destination.png', { + * preconditionOpts: { + * ifGenerationMatch: 0 // Fails if the destination object exists. + * } + * }, function(err, movedFile, apiResponse) { + * if (err) { + * // Handle the error (e.g., the destination object already exists). + * } else { + * // Move successful. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.moveFileAtomic('moved-image.png).then(function(data) { + * const newFile = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/files.js + * region_tag:storage_move_file + * Another example: + */ + moveFileAtomic(destination, optionsOrCallback, callback) { + var _a, _b; + const noDestinationError = new Error(FileExceptionMessages.DESTINATION_NO_NAME); + if (!destination) { + throw noDestinationError; + } + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else if (optionsOrCallback) { + options = { ...optionsOrCallback }; + } + callback = callback || index_js_1.util.noop; + let destName; + let newFile; + if (typeof destination === 'string') { + const parsedDestination = GS_URL_REGEXP.exec(destination); + if (parsedDestination !== null && parsedDestination.length === 3) { + destName = parsedDestination[2]; + } + else { + destName = destination; + } + } + else if (destination instanceof File) { + destName = destination.name; + newFile = destination; + } + else { + throw noDestinationError; + } + newFile = newFile || this.bucket.file(destName); + if (!this.shouldRetryBasedOnPreconditionAndIdempotencyStrat(options === null || options === void 0 ? void 0 : options.preconditionOpts)) { + this.storage.retryOptions.autoRetry = false; + } + const query = {}; + if (options.userProject !== undefined) { + query.userProject = options.userProject; + delete options.userProject; + } + if (((_a = options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) !== undefined) { + query.ifGenerationMatch = (_b = options.preconditionOpts) === null || _b === void 0 ? void 0 : _b.ifGenerationMatch; + delete options.preconditionOpts; + } + this.request({ + method: 'POST', + uri: `/moveTo/o/${encodeURIComponent(newFile.name)}`, + qs: query, + json: options, + }, (err, resp) => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + if (err) { + callback(err, null, resp); + return; + } + callback(null, newFile, resp); + }); + } + /** + * @typedef {array} MoveResponse + * @property {File} 0 The destination File. + * @property {object} 1 The full API response. + */ + /** + * @callback MoveCallback + * @param {?Error} err Request error, if any. + * @param {?File} destinationFile The destination File. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {object} MoveOptions Configuration options for File#move(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}. + * @param {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * Move this file to another location. By default, this will rename the file + * and keep it in the same bucket, but you can choose to move it to another + * Bucket by providing a Bucket or File object or a URL beginning with + * "gs://". + * + * **Warning**: + * There is currently no atomic `move` method in the Cloud Storage API, + * so this method is a composition of {@link File#copy} (to the new + * location) and {@link File#delete} (from the old location). While + * unlikely, it is possible that an error returned to your callback could be + * triggered from either one of these API calls failing, which could leave a + * duplicate file lingering. The error message will indicate what operation + * has failed. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/copy| Objects: copy API Documentation} + * + * @throws {Error} If the destination file is not provided. + * + * @param {string|Bucket|File} destination Destination file. + * @param {MoveCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * //- + * // You can pass in a variety of types for the destination. + * // + * // For all of the below examples, assume we are working with the following + * // Bucket and File objects. + * //- + * const bucket = storage.bucket('my-bucket'); + * const file = bucket.file('my-image.png'); + * + * //- + * // If you pass in a string for the destination, the file is moved to its + * // current bucket, under the new name provided. + * //- + * file.move('my-image-new.png', function(err, destinationFile, apiResponse) { + * // `my-bucket` no longer contains: + * // - "my-image.png" + * // but contains instead: + * // - "my-image-new.png" + * + * // `destinationFile` is an instance of a File object that refers to your + * // new file. + * }); + * + * //- + * // If you pass in a string starting with "gs://" for the destination, the + * // file is copied to the other bucket and under the new name provided. + * //- + * const newLocation = 'gs://another-bucket/my-image-new.png'; + * file.move(newLocation, function(err, destinationFile, apiResponse) { + * // `my-bucket` no longer contains: + * // - "my-image.png" + * // + * // `another-bucket` now contains: + * // - "my-image-new.png" + * + * // `destinationFile` is an instance of a File object that refers to your + * // new file. + * }); + * + * //- + * // If you pass in a Bucket object, the file will be moved to that bucket + * // using the same name. + * //- + * const anotherBucket = gcs.bucket('another-bucket'); + * + * file.move(anotherBucket, function(err, destinationFile, apiResponse) { + * // `my-bucket` no longer contains: + * // - "my-image.png" + * // + * // `another-bucket` now contains: + * // - "my-image.png" + * + * // `destinationFile` is an instance of a File object that refers to your + * // new file. + * }); + * + * //- + * // If you pass in a File object, you have complete control over the new + * // bucket and filename. + * //- + * const anotherFile = anotherBucket.file('my-awesome-image.png'); + * + * file.move(anotherFile, function(err, destinationFile, apiResponse) { + * // `my-bucket` no longer contains: + * // - "my-image.png" + * // + * // `another-bucket` now contains: + * // - "my-awesome-image.png" + * + * // Note: + * // The `destinationFile` parameter is equal to `anotherFile`. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.move('my-image-new.png').then(function(data) { + * const destinationFile = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/files.js + * region_tag:storage_move_file + * Another example: + */ + move(destination, optionsOrCallback, callback) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + callback = callback || index_js_1.util.noop; + this.copy(destination, options, (err, destinationFile, copyApiResponse) => { + if (err) { + err.message = 'file#copy failed with an error - ' + err.message; + callback(err, null, copyApiResponse); + return; + } + if (this.name !== destinationFile.name || + this.bucket.name !== destinationFile.bucket.name) { + this.delete(options, (err, apiResponse) => { + if (err) { + err.message = 'file#delete failed with an error - ' + err.message; + callback(err, destinationFile, apiResponse); + return; + } + callback(null, destinationFile, copyApiResponse); + }); + } + else { + callback(null, destinationFile, copyApiResponse); + } + }); + } + /** + * @typedef {array} RenameResponse + * @property {File} 0 The destination File. + * @property {object} 1 The full API response. + */ + /** + * @callback RenameCallback + * @param {?Error} err Request error, if any. + * @param {?File} destinationFile The destination File. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {object} RenameOptions Configuration options for File#move(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}. + * @param {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * Rename this file. + * + * **Warning**: + * There is currently no atomic `rename` method in the Cloud Storage API, + * so this method is an alias of {@link File#move}, which in turn is a + * composition of {@link File#copy} (to the new location) and + * {@link File#delete} (from the old location). While + * unlikely, it is possible that an error returned to your callback could be + * triggered from either one of these API calls failing, which could leave a + * duplicate file lingering. The error message will indicate what operation + * has failed. + * + * @param {string|File} destinationFile Destination file. + * @param {RenameCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // You can pass in a string or a File object. + * // + * // For all of the below examples, assume we are working with the following + * // Bucket and File objects. + * //- + * + * const bucket = storage.bucket('my-bucket'); + * const file = bucket.file('my-image.png'); + * + * //- + * // You can pass in a string for the destinationFile. + * //- + * file.rename('renamed-image.png', function(err, renamedFile, apiResponse) { + * // `my-bucket` no longer contains: + * // - "my-image.png" + * // but contains instead: + * // - "renamed-image.png" + * + * // `renamedFile` is an instance of a File object that refers to your + * // renamed file. + * }); + * + * //- + * // You can pass in a File object. + * //- + * const anotherFile = anotherBucket.file('my-awesome-image.png'); + * + * file.rename(anotherFile, function(err, renamedFile, apiResponse) { + * // `my-bucket` no longer contains: + * // - "my-image.png" + * + * // Note: + * // The `renamedFile` parameter is equal to `anotherFile`. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.rename('my-renamed-image.png').then(function(data) { + * const renamedFile = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + rename(destinationFile, optionsOrCallback, callback) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + callback = callback || index_js_1.util.noop; + this.move(destinationFile, options, callback); + } + /** + * @typedef {object} RestoreOptions Options for File#restore(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}. + * @param {string} [userProject] The ID of the project which will be + * billed for the request. + * @param {number} [generation] If present, selects a specific revision of this object. + * @param {string} [restoreToken] Returns an option that must be specified when getting a soft-deleted object from an HNS-enabled + * bucket that has a naming and generation conflict with another object in the same bucket. + * @param {string} [projection] Specifies the set of properties to return. If used, must be 'full' or 'noAcl'. + * @param {string | number} [ifGenerationMatch] Request proceeds if the generation of the target resource + * matches the value used in the precondition. + * If the values don't match, the request fails with a 412 Precondition Failed response. + * @param {string | number} [ifGenerationNotMatch] Request proceeds if the generation of the target resource does + * not match the value used in the precondition. If the values match, the request fails with a 304 Not Modified response. + * @param {string | number} [ifMetagenerationMatch] Request proceeds if the meta-generation of the target resource + * matches the value used in the precondition. + * If the values don't match, the request fails with a 412 Precondition Failed response. + * @param {string | number} [ifMetagenerationNotMatch] Request proceeds if the meta-generation of the target resource does + * not match the value used in the precondition. If the values match, the request fails with a 304 Not Modified response. + */ + /** + * Restores a soft-deleted file + * @param {RestoreOptions} options Restore options. + * @returns {Promise} + */ + async restore(options) { + const [file] = await this.request({ + method: 'POST', + uri: '/restore', + qs: options, + }); + return file; + } + /** + * Makes request and applies userProject query parameter if necessary. + * + * @private + * + * @param {object} reqOpts - The request options. + * @param {function} callback - The callback function. + */ + request(reqOpts, callback) { + return this.parent.request.call(this, reqOpts, callback); + } + /** + * @callback RotateEncryptionKeyCallback + * @extends CopyCallback + */ + /** + * @typedef RotateEncryptionKeyResponse + * @extends CopyResponse + */ + /** + * @param {string|buffer|object} RotateEncryptionKeyOptions Configuration options + * for File#rotateEncryptionKey(). + * If a string or Buffer is provided, it is interpreted as an AES-256, + * customer-supplied encryption key. If you'd like to use a Cloud KMS key + * name, you must specify an options object with the property name: + * `kmsKeyName`. + * @param {string|buffer} [options.encryptionKey] An AES-256 encryption key. + * @param {string} [options.kmsKeyName] A Cloud KMS key name. + */ + /** + * This method allows you to update the encryption key associated with this + * file. + * + * See {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys} + * + * @param {RotateEncryptionKeyOptions} [options] - Configuration options. + * @param {RotateEncryptionKeyCallback} [callback] + * @returns {Promise} + * + * @example include:samples/encryption.js + * region_tag:storage_rotate_encryption_key + * Example of rotating the encryption key for this file: + */ + rotateEncryptionKey(optionsOrCallback, callback) { + var _a; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + let options = {}; + if (typeof optionsOrCallback === 'string' || + optionsOrCallback instanceof Buffer) { + options = { + encryptionKey: optionsOrCallback, + }; + } + else if (typeof optionsOrCallback === 'object') { + options = optionsOrCallback; + } + const newFile = this.bucket.file(this.id, options); + const copyOptions = ((_a = options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) !== undefined + ? { preconditionOpts: options.preconditionOpts } + : {}; + this.copy(newFile, copyOptions, callback); + } + /** + * @typedef {object} SaveOptions + * @extends CreateWriteStreamOptions + */ + /** + * @callback SaveCallback + * @param {?Error} err Request error, if any. + */ + /** + * Write strings or buffers to a file. + * + * *This is a convenience method which wraps {@link File#createWriteStream}.* + * To upload arbitrary data to a file, please use {@link File#createWriteStream} directly. + * + * Resumable uploads are automatically enabled and must be shut off explicitly + * by setting `options.resumable` to `false`. + * + * Multipart uploads with retryable error codes will be retried 3 times with exponential backoff. + * + *

+ * There is some overhead when using a resumable upload that can cause + * noticeable performance degradation while uploading a series of small + * files. When uploading files less than 10MB, it is recommended that the + * resumable feature is disabled. + *

+ * + * @param {SaveData} data The data to write to a file. + * @param {SaveOptions} [options] See {@link File#createWriteStream}'s `options` + * parameter. + * @param {SaveCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * const contents = 'This is the contents of the file.'; + * + * file.save(contents, function(err) { + * if (!err) { + * // File written successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.save(contents).then(function() {}); + * ``` + */ + save(data, optionsOrCallback, callback) { + // tslint:enable:no-any + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + let maxRetries = this.storage.retryOptions.maxRetries; + if (!this.shouldRetryBasedOnPreconditionAndIdempotencyStrat(options === null || options === void 0 ? void 0 : options.preconditionOpts)) { + maxRetries = 0; + } + const returnValue = (0, async_retry_1.default)(async (bail) => { + return new Promise((resolve, reject) => { + if (maxRetries === 0) { + this.storage.retryOptions.autoRetry = false; + } + const writable = this.createWriteStream(options); + if (options.onUploadProgress) { + writable.on('progress', options.onUploadProgress); + } + const handleError = (err) => { + if (this.storage.retryOptions.autoRetry && + this.storage.retryOptions.retryableErrorFn(err)) { + return reject(err); + } + return bail(err); + }; + if (typeof data === 'string' || + Buffer.isBuffer(data) || + data instanceof Uint8Array) { + writable + .on('error', handleError) + .on('finish', () => resolve()) + .end(data); + } + else { + (0, stream_1.pipeline)(data, writable, err => { + if (err) { + if (typeof data !== 'function') { + // Only PipelineSourceFunction can be retried. Async-iterables + // and Readable streams can only be consumed once. + return bail(err); + } + handleError(err); + } + else { + resolve(); + } + }); + } + }); + }, { + retries: maxRetries, + factor: this.storage.retryOptions.retryDelayMultiplier, + maxTimeout: this.storage.retryOptions.maxRetryDelay * 1000, //convert to milliseconds + maxRetryTime: this.storage.retryOptions.totalTimeout * 1000, //convert to milliseconds + }); + if (!callback) { + return returnValue; + } + else { + return returnValue + .then(() => { + if (callback) { + return callback(); + } + }) + .catch(callback); + } + } + setMetadata(metadata, optionsOrCallback, cb) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + cb = + typeof optionsOrCallback === 'function' + ? optionsOrCallback + : cb; + this.disableAutoRetryConditionallyIdempotent_(this.methods.setMetadata, bucket_js_1.AvailableServiceObjectMethods.setMetadata, options); + super + .setMetadata(metadata, options) + .then(resp => cb(null, ...resp)) + .catch(cb) + .finally(() => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + }); + } + /** + * @typedef {array} SetStorageClassResponse + * @property {object} 0 The full API response. + */ + /** + * @typedef {object} SetStorageClassOptions Configuration options for File#setStorageClass(). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @callback SetStorageClassCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Set the storage class for this file. + * + * See {@link https://cloud.google.com/storage/docs/per-object-storage-class| Per-Object Storage Class} + * See {@link https://cloud.google.com/storage/docs/storage-classes| Storage Classes} + * + * @param {string} storageClass The new storage class. (`standard`, + * `nearline`, `coldline`, or `archive`) + * **Note:** The storage classes `multi_regional` and `regional` + * are now legacy and will be deprecated in the future. + * @param {SetStorageClassOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {SetStorageClassCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * file.setStorageClass('nearline', function(err, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * // The storage class was updated successfully. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.setStorageClass('nearline').then(function() {}); + * ``` + */ + setStorageClass(storageClass, optionsOrCallback, callback) { + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const req = { + ...options, + // In case we get input like `storageClass`, convert to `storage_class`. + storageClass: storageClass + .replace(/-/g, '_') + .replace(/([a-z])([A-Z])/g, (_, low, up) => { + return low + '_' + up; + }) + .toUpperCase(), + }; + this.copy(this, req, (err, file, apiResponse) => { + if (err) { + callback(err, apiResponse); + return; + } + this.metadata = file.metadata; + callback(null, apiResponse); + }); + } + /** + * Set a user project to be billed for all requests made from this File + * object. + * + * @param {string} userProject The user project. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * const file = bucket.file('my-file'); + * + * file.setUserProject('grape-spaceship-123'); + * ``` + */ + setUserProject(userProject) { + this.bucket.setUserProject.call(this, userProject); + } + /** + * This creates a resumable-upload upload stream. + * + * @param {Duplexify} stream - Duplexify stream of data to pipe to the file. + * @param {object=} options - Configuration object. + * + * @private + */ + startResumableUpload_(dup, options = {}) { + var _a; + (_a = options.metadata) !== null && _a !== void 0 ? _a : (options.metadata = {}); + const retryOptions = this.storage.retryOptions; + if (!this.shouldRetryBasedOnPreconditionAndIdempotencyStrat(options.preconditionOpts)) { + retryOptions.autoRetry = false; + } + const cfg = { + authClient: this.storage.authClient, + apiEndpoint: this.storage.apiEndpoint, + bucket: this.bucket.name, + customRequestOptions: this.getRequestInterceptors().reduce((reqOpts, interceptorFn) => interceptorFn(reqOpts), {}), + file: this.name, + generation: this.generation, + isPartialUpload: options.isPartialUpload, + key: this.encryptionKey, + kmsKeyName: this.kmsKeyName, + metadata: options.metadata, + offset: options.offset, + predefinedAcl: options.predefinedAcl, + private: options.private, + public: options.public, + uri: options.uri, + userProject: options.userProject || this.userProject, + retryOptions: { ...retryOptions }, + params: (options === null || options === void 0 ? void 0 : options.preconditionOpts) || this.instancePreconditionOpts, + chunkSize: options === null || options === void 0 ? void 0 : options.chunkSize, + highWaterMark: options === null || options === void 0 ? void 0 : options.highWaterMark, + universeDomain: this.bucket.storage.universeDomain, + [util_js_1.GCCL_GCS_CMD_KEY]: options[util_js_1.GCCL_GCS_CMD_KEY], + }; + let uploadStream; + try { + uploadStream = resumableUpload.upload(cfg); + } + catch (error) { + dup.destroy(error); + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + return; + } + uploadStream + .on('response', resp => { + dup.emit('response', resp); + }) + .on('uri', uri => { + dup.emit('uri', uri); + }) + .on('metadata', metadata => { + this.metadata = metadata; + dup.emit('metadata'); + }) + .on('finish', () => { + dup.emit('complete'); + }) + .on('progress', evt => dup.emit('progress', evt)); + dup.setWritable(uploadStream); + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + } + /** + * Takes a readable stream and pipes it to a remote file. Unlike + * `startResumableUpload_`, which uses the resumable upload technique, this + * method uses a simple upload (all or nothing). + * + * @param {Duplexify} dup - Duplexify stream of data to pipe to the file. + * @param {object=} options - Configuration object. + * + * @private + */ + startSimpleUpload_(dup, options = {}) { + var _a; + (_a = options.metadata) !== null && _a !== void 0 ? _a : (options.metadata = {}); + const apiEndpoint = this.storage.apiEndpoint; + const bucketName = this.bucket.name; + const uri = `${apiEndpoint}/upload/storage/v1/b/${bucketName}/o`; + const reqOpts = { + qs: { + name: this.name, + }, + uri: uri, + [util_js_1.GCCL_GCS_CMD_KEY]: options[util_js_1.GCCL_GCS_CMD_KEY], + }; + if (this.generation !== undefined) { + reqOpts.qs.ifGenerationMatch = this.generation; + } + if (this.kmsKeyName !== undefined) { + reqOpts.qs.kmsKeyName = this.kmsKeyName; + } + if (typeof options.timeout === 'number') { + reqOpts.timeout = options.timeout; + } + if (options.userProject || this.userProject) { + reqOpts.qs.userProject = options.userProject || this.userProject; + } + if (options.predefinedAcl) { + reqOpts.qs.predefinedAcl = options.predefinedAcl; + } + else if (options.private) { + reqOpts.qs.predefinedAcl = 'private'; + } + else if (options.public) { + reqOpts.qs.predefinedAcl = 'publicRead'; + } + Object.assign(reqOpts.qs, this.instancePreconditionOpts, options.preconditionOpts); + index_js_1.util.makeWritableStream(dup, { + makeAuthenticatedRequest: (reqOpts) => { + this.request(reqOpts, (err, body, resp) => { + if (err) { + dup.destroy(err); + return; + } + this.metadata = body; + dup.emit('metadata', body); + dup.emit('response', resp); + dup.emit('complete'); + }); + }, + metadata: options.metadata, + request: reqOpts, + }); + } + disableAutoRetryConditionallyIdempotent_( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + coreOpts, methodType, localPreconditionOptions) { + var _a, _b, _c, _d; + if ((typeof coreOpts === 'object' && + ((_b = (_a = coreOpts === null || coreOpts === void 0 ? void 0 : coreOpts.reqOpts) === null || _a === void 0 ? void 0 : _a.qs) === null || _b === void 0 ? void 0 : _b.ifGenerationMatch) === undefined && + (localPreconditionOptions === null || localPreconditionOptions === void 0 ? void 0 : localPreconditionOptions.ifGenerationMatch) === undefined && + methodType === bucket_js_1.AvailableServiceObjectMethods.delete && + this.storage.retryOptions.idempotencyStrategy === + storage_js_1.IdempotencyStrategy.RetryConditional) || + this.storage.retryOptions.idempotencyStrategy === + storage_js_1.IdempotencyStrategy.RetryNever) { + this.storage.retryOptions.autoRetry = false; + } + if ((typeof coreOpts === 'object' && + ((_d = (_c = coreOpts === null || coreOpts === void 0 ? void 0 : coreOpts.reqOpts) === null || _c === void 0 ? void 0 : _c.qs) === null || _d === void 0 ? void 0 : _d.ifMetagenerationMatch) === undefined && + (localPreconditionOptions === null || localPreconditionOptions === void 0 ? void 0 : localPreconditionOptions.ifMetagenerationMatch) === undefined && + methodType === bucket_js_1.AvailableServiceObjectMethods.setMetadata && + this.storage.retryOptions.idempotencyStrategy === + storage_js_1.IdempotencyStrategy.RetryConditional) || + this.storage.retryOptions.idempotencyStrategy === + storage_js_1.IdempotencyStrategy.RetryNever) { + this.storage.retryOptions.autoRetry = false; + } + } + async getBufferFromReadable(readable) { + const buf = []; + for await (const chunk of readable) { + buf.push(chunk); + } + return Buffer.concat(buf); + } +} +exports.File = File; +_File_instances = new WeakSet(), _File_validateIntegrity = +/** + * + * @param hashCalculatingStream + * @param verify + * @returns {boolean} Returns `true` if valid, throws with error otherwise + */ +async function _File_validateIntegrity(hashCalculatingStream, verify = {}) { + const metadata = this.metadata; + // If we're doing validation, assume the worst + let dataMismatch = !!(verify.crc32c || verify.md5); + if (verify.crc32c && metadata.crc32c) { + dataMismatch = !hashCalculatingStream.test('crc32c', metadata.crc32c); + } + if (verify.md5 && metadata.md5Hash) { + dataMismatch = !hashCalculatingStream.test('md5', metadata.md5Hash); + } + if (dataMismatch) { + const errors = []; + let code = ''; + let message = ''; + try { + await this.delete(); + if (verify.md5 && !metadata.md5Hash) { + code = 'MD5_NOT_AVAILABLE'; + message = FileExceptionMessages.MD5_NOT_AVAILABLE; + } + else { + code = 'FILE_NO_UPLOAD'; + message = FileExceptionMessages.UPLOAD_MISMATCH; + } + } + catch (e) { + const error = e; + code = 'FILE_NO_UPLOAD_DELETE'; + message = `${FileExceptionMessages.UPLOAD_MISMATCH_DELETE_FAIL}${error.message}`; + errors.push(error); + } + const error = new RequestError(message); + error.code = code; + error.errors = errors; + throw error; + } + return true; +}; +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +(0, promisify_1.promisifyAll)(File, { + exclude: [ + 'cloudStorageURI', + 'publicUrl', + 'request', + 'save', + 'setEncryptionKey', + 'shouldRetryBasedOnPreconditionAndIdempotencyStrat', + 'getBufferFromReadable', + 'restore', + ], +}); diff --git a/node_modules/@google-cloud/storage/build/cjs/src/hash-stream-validator.d.ts b/node_modules/@google-cloud/storage/build/cjs/src/hash-stream-validator.d.ts new file mode 100644 index 0000000..c16e3ba --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/hash-stream-validator.d.ts @@ -0,0 +1,35 @@ +import { Transform } from 'stream'; +import { CRC32CValidatorGenerator, CRC32CValidator } from './crc32c.js'; +interface HashStreamValidatorOptions { + /** Enables CRC32C calculation. To validate a provided value use `crc32cExpected`. */ + crc32c: boolean; + /** Enables MD5 calculation. To validate a provided value use `md5Expected`. */ + md5: boolean; + /** A CRC32C instance for validation. To validate a provided value use `crc32cExpected`. */ + crc32cInstance: CRC32CValidator; + /** Set a custom CRC32C generator. Used if `crc32cInstance` has not been provided. */ + crc32cGenerator: CRC32CValidatorGenerator; + /** Sets the expected CRC32C value to verify once all data has been consumed. Also sets the `crc32c` option to `true` */ + crc32cExpected?: string; + /** Sets the expected MD5 value to verify once all data has been consumed. Also sets the `md5` option to `true` */ + md5Expected?: string; + /** Indicates whether or not to run a validation check or only update the hash values */ + updateHashesOnly?: boolean; +} +declare class HashStreamValidator extends Transform { + #private; + readonly crc32cEnabled: boolean; + readonly md5Enabled: boolean; + readonly crc32cExpected: string | undefined; + readonly md5Expected: string | undefined; + readonly updateHashesOnly: boolean; + constructor(options?: Partial); + /** + * Return the current CRC32C value, if available. + */ + get crc32c(): string | undefined; + _flush(callback: (error?: Error | null | undefined) => void): void; + _transform(chunk: Buffer, encoding: BufferEncoding, callback: (e?: Error) => void): void; + test(hash: 'crc32c' | 'md5', sum: Buffer | string): boolean; +} +export { HashStreamValidator, HashStreamValidatorOptions }; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/hash-stream-validator.js b/node_modules/@google-cloud/storage/build/cjs/src/hash-stream-validator.js new file mode 100644 index 0000000..ef61e0c --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/hash-stream-validator.js @@ -0,0 +1,119 @@ +"use strict"; +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _HashStreamValidator_crc32cHash, _HashStreamValidator_md5Hash, _HashStreamValidator_md5Digest; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HashStreamValidator = void 0; +const crypto_1 = require("crypto"); +const stream_1 = require("stream"); +const crc32c_js_1 = require("./crc32c.js"); +const file_js_1 = require("./file.js"); +class HashStreamValidator extends stream_1.Transform { + constructor(options = {}) { + super(); + this.updateHashesOnly = false; + _HashStreamValidator_crc32cHash.set(this, undefined); + _HashStreamValidator_md5Hash.set(this, undefined); + _HashStreamValidator_md5Digest.set(this, ''); + this.crc32cEnabled = !!options.crc32c; + this.md5Enabled = !!options.md5; + this.updateHashesOnly = !!options.updateHashesOnly; + this.crc32cExpected = options.crc32cExpected; + this.md5Expected = options.md5Expected; + if (this.crc32cEnabled) { + if (options.crc32cInstance) { + __classPrivateFieldSet(this, _HashStreamValidator_crc32cHash, options.crc32cInstance, "f"); + } + else { + const crc32cGenerator = options.crc32cGenerator || crc32c_js_1.CRC32C_DEFAULT_VALIDATOR_GENERATOR; + __classPrivateFieldSet(this, _HashStreamValidator_crc32cHash, crc32cGenerator(), "f"); + } + } + if (this.md5Enabled) { + __classPrivateFieldSet(this, _HashStreamValidator_md5Hash, (0, crypto_1.createHash)('md5'), "f"); + } + } + /** + * Return the current CRC32C value, if available. + */ + get crc32c() { + var _a; + return (_a = __classPrivateFieldGet(this, _HashStreamValidator_crc32cHash, "f")) === null || _a === void 0 ? void 0 : _a.toString(); + } + _flush(callback) { + if (__classPrivateFieldGet(this, _HashStreamValidator_md5Hash, "f")) { + __classPrivateFieldSet(this, _HashStreamValidator_md5Digest, __classPrivateFieldGet(this, _HashStreamValidator_md5Hash, "f").digest('base64'), "f"); + } + if (this.updateHashesOnly) { + callback(); + return; + } + // If we're doing validation, assume the worst-- a data integrity + // mismatch. If not, these tests won't be performed, and we can assume + // the best. + // We must check if the server decompressed the data on serve because hash + // validation is not possible in this case. + let failed = this.crc32cEnabled || this.md5Enabled; + if (this.crc32cEnabled && this.crc32cExpected) { + failed = !this.test('crc32c', this.crc32cExpected); + } + if (this.md5Enabled && this.md5Expected) { + failed = !this.test('md5', this.md5Expected); + } + if (failed) { + const mismatchError = new file_js_1.RequestError(file_js_1.FileExceptionMessages.DOWNLOAD_MISMATCH); + mismatchError.code = 'CONTENT_DOWNLOAD_MISMATCH'; + callback(mismatchError); + } + else { + callback(); + } + } + _transform(chunk, encoding, callback) { + this.push(chunk, encoding); + try { + if (__classPrivateFieldGet(this, _HashStreamValidator_crc32cHash, "f")) + __classPrivateFieldGet(this, _HashStreamValidator_crc32cHash, "f").update(chunk); + if (__classPrivateFieldGet(this, _HashStreamValidator_md5Hash, "f")) + __classPrivateFieldGet(this, _HashStreamValidator_md5Hash, "f").update(chunk); + callback(); + } + catch (e) { + callback(e); + } + } + test(hash, sum) { + const check = Buffer.isBuffer(sum) ? sum.toString('base64') : sum; + if (hash === 'crc32c' && __classPrivateFieldGet(this, _HashStreamValidator_crc32cHash, "f")) { + return __classPrivateFieldGet(this, _HashStreamValidator_crc32cHash, "f").validate(check); + } + if (hash === 'md5' && __classPrivateFieldGet(this, _HashStreamValidator_md5Hash, "f")) { + return __classPrivateFieldGet(this, _HashStreamValidator_md5Digest, "f") === check; + } + return false; + } +} +exports.HashStreamValidator = HashStreamValidator; +_HashStreamValidator_crc32cHash = new WeakMap(), _HashStreamValidator_md5Hash = new WeakMap(), _HashStreamValidator_md5Digest = new WeakMap(); diff --git a/node_modules/@google-cloud/storage/build/cjs/src/hmacKey.d.ts b/node_modules/@google-cloud/storage/build/cjs/src/hmacKey.d.ts new file mode 100644 index 0000000..4433a83 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/hmacKey.d.ts @@ -0,0 +1,93 @@ +import { ServiceObject, MetadataCallback, SetMetadataResponse } from './nodejs-common/index.js'; +import { BaseMetadata, SetMetadataOptions } from './nodejs-common/service-object.js'; +import { Storage } from './storage.js'; +export interface HmacKeyOptions { + projectId?: string; +} +export interface HmacKeyMetadata extends BaseMetadata { + accessId?: string; + etag?: string; + projectId?: string; + serviceAccountEmail?: string; + state?: string; + timeCreated?: string; + updated?: string; +} +export interface SetHmacKeyMetadataOptions { + /** + * This parameter is currently ignored. + */ + userProject?: string; +} +export interface SetHmacKeyMetadata { + state?: 'ACTIVE' | 'INACTIVE'; + etag?: string; +} +export interface HmacKeyMetadataCallback { + (err: Error | null, metadata?: HmacKeyMetadata, apiResponse?: unknown): void; +} +export type HmacKeyMetadataResponse = [HmacKeyMetadata, unknown]; +/** + * The API-formatted resource description of the HMAC key. + * + * Note: This is not guaranteed to be up-to-date when accessed. To get the + * latest record, call the `getMetadata()` method. + * + * @name HmacKey#metadata + * @type {object} + */ +/** + * An HmacKey object contains metadata of an HMAC key created from a + * service account through the {@link Storage} client using + * {@link Storage#createHmacKey}. + * + * See {@link https://cloud.google.com/storage/docs/authentication/hmackeys| HMAC keys documentation} + * + * @class + */ +export declare class HmacKey extends ServiceObject { + /** + * A reference to the {@link Storage} associated with this {@link HmacKey} + * instance. + * @name HmacKey#storage + * @type {Storage} + */ + storage: Storage; + private instanceRetryValue?; + /** + * @typedef {object} HmacKeyOptions + * @property {string} [projectId] The project ID of the project that owns + * the service account of the requested HMAC key. If not provided, + * the project ID used to instantiate the Storage client will be used. + */ + /** + * Constructs an HmacKey object. + * + * Note: this only create a local reference to an HMAC key, to create + * an HMAC key, use {@link Storage#createHmacKey}. + * + * @param {Storage} storage The Storage instance this HMAC key is + * attached to. + * @param {string} accessId The unique accessId for this HMAC key. + * @param {HmacKeyOptions} options Constructor configurations. + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const hmacKey = storage.hmacKey('access-id'); + * ``` + */ + constructor(storage: Storage, accessId: string, options?: HmacKeyOptions); + /** + * Set the metadata for this object. + * + * @param {object} metadata - The metadata to set on this object. + * @param {object=} options - Configuration options. + * @param {function=} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.apiResponse - The full API response. + */ + setMetadata(metadata: HmacKeyMetadata, options?: SetMetadataOptions): Promise>; + setMetadata(metadata: HmacKeyMetadata, callback: MetadataCallback): void; + setMetadata(metadata: HmacKeyMetadata, options: SetMetadataOptions, callback: MetadataCallback): void; +} diff --git a/node_modules/@google-cloud/storage/build/cjs/src/hmacKey.js b/node_modules/@google-cloud/storage/build/cjs/src/hmacKey.js new file mode 100644 index 0000000..aaf654a --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/hmacKey.js @@ -0,0 +1,336 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HmacKey = void 0; +const index_js_1 = require("./nodejs-common/index.js"); +const storage_js_1 = require("./storage.js"); +const promisify_1 = require("@google-cloud/promisify"); +/** + * The API-formatted resource description of the HMAC key. + * + * Note: This is not guaranteed to be up-to-date when accessed. To get the + * latest record, call the `getMetadata()` method. + * + * @name HmacKey#metadata + * @type {object} + */ +/** + * An HmacKey object contains metadata of an HMAC key created from a + * service account through the {@link Storage} client using + * {@link Storage#createHmacKey}. + * + * See {@link https://cloud.google.com/storage/docs/authentication/hmackeys| HMAC keys documentation} + * + * @class + */ +class HmacKey extends index_js_1.ServiceObject { + /** + * @typedef {object} HmacKeyOptions + * @property {string} [projectId] The project ID of the project that owns + * the service account of the requested HMAC key. If not provided, + * the project ID used to instantiate the Storage client will be used. + */ + /** + * Constructs an HmacKey object. + * + * Note: this only create a local reference to an HMAC key, to create + * an HMAC key, use {@link Storage#createHmacKey}. + * + * @param {Storage} storage The Storage instance this HMAC key is + * attached to. + * @param {string} accessId The unique accessId for this HMAC key. + * @param {HmacKeyOptions} options Constructor configurations. + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const hmacKey = storage.hmacKey('access-id'); + * ``` + */ + constructor(storage, accessId, options) { + const methods = { + /** + * @typedef {object} DeleteHmacKeyOptions + * @property {string} [userProject] This parameter is currently ignored. + */ + /** + * @typedef {array} DeleteHmacKeyResponse + * @property {object} 0 The full API response. + */ + /** + * @callback DeleteHmacKeyCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Deletes an HMAC key. + * Key state must be set to `INACTIVE` prior to deletion. + * Caution: HMAC keys cannot be recovered once you delete them. + * + * The authenticated user must have `storage.hmacKeys.delete` permission for the project in which the key exists. + * + * @method HmacKey#delete + * @param {DeleteHmacKeyOptions} [options] Configuration options. + * @param {DeleteHmacKeyCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // Delete HMAC key after making the key inactive. + * //- + * const hmacKey = storage.hmacKey('ACCESS_ID'); + * hmacKey.setMetadata({state: 'INACTIVE'}, (err, hmacKeyMetadata) => { + * if (err) { + * // The request was an error. + * console.error(err); + * return; + * } + * hmacKey.delete((err) => { + * if (err) { + * console.error(err); + * return; + * } + * // The HMAC key is deleted. + * }); + * }); + * + * //- + * // If the callback is omitted, a promise is returned. + * //- + * const hmacKey = storage.hmacKey('ACCESS_ID'); + * hmacKey + * .setMetadata({state: 'INACTIVE'}) + * .then(() => { + * return hmacKey.delete(); + * }); + * ``` + */ + delete: true, + /** + * @callback GetHmacKeyCallback + * @param {?Error} err Request error, if any. + * @param {HmacKey} hmacKey this {@link HmacKey} instance. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} GetHmacKeyResponse + * @property {HmacKey} 0 This {@link HmacKey} instance. + * @property {object} 1 The full API response. + */ + /** + * @typedef {object} GetHmacKeyOptions + * @property {string} [userProject] This parameter is currently ignored. + */ + /** + * Retrieves and populate an HMAC key's metadata, and return + * this {@link HmacKey} instance. + * + * HmacKey.get() does not give the HMAC key secret, as + * it is only returned on creation. + * + * The authenticated user must have `storage.hmacKeys.get` permission + * for the project in which the key exists. + * + * @method HmacKey#get + * @param {GetHmacKeyOptions} [options] Configuration options. + * @param {GetHmacKeyCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // Get the HmacKey's Metadata. + * //- + * storage.hmacKey('ACCESS_ID') + * .get((err, hmacKey) => { + * if (err) { + * // The request was an error. + * console.error(err); + * return; + * } + * // do something with the returned HmacKey object. + * }); + * + * //- + * // If the callback is omitted, a promise is returned. + * //- + * storage.hmacKey('ACCESS_ID') + * .get() + * .then((data) => { + * const hmacKey = data[0]; + * }); + * ``` + */ + get: true, + /** + * @typedef {object} GetHmacKeyMetadataOptions + * @property {string} [userProject] This parameter is currently ignored. + */ + /** + * Retrieves and populate an HMAC key's metadata, and return + * the HMAC key's metadata as an object. + * + * HmacKey.getMetadata() does not give the HMAC key secret, as + * it is only returned on creation. + * + * The authenticated user must have `storage.hmacKeys.get` permission + * for the project in which the key exists. + * + * @method HmacKey#getMetadata + * @param {GetHmacKeyMetadataOptions} [options] Configuration options. + * @param {HmacKeyMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // Get the HmacKey's metadata and populate to the metadata property. + * //- + * storage.hmacKey('ACCESS_ID') + * .getMetadata((err, hmacKeyMetadata) => { + * if (err) { + * // The request was an error. + * console.error(err); + * return; + * } + * console.log(hmacKeyMetadata); + * }); + * + * //- + * // If the callback is omitted, a promise is returned. + * //- + * storage.hmacKey('ACCESS_ID') + * .getMetadata() + * .then((data) => { + * const hmacKeyMetadata = data[0]; + * console.log(hmacKeyMetadata); + * }); + * ``` + */ + getMetadata: true, + /** + * @typedef {object} SetHmacKeyMetadata Subset of {@link HmacKeyMetadata} to update. + * @property {string} state New state of the HmacKey. Either 'ACTIVE' or 'INACTIVE'. + * @property {string} [etag] Include an etag from a previous get HMAC key request + * to perform safe read-modify-write. + */ + /** + * @typedef {object} SetHmacKeyMetadataOptions + * @property {string} [userProject] This parameter is currently ignored. + */ + /** + * @callback HmacKeyMetadataCallback + * @param {?Error} err Request error, if any. + * @param {HmacKeyMetadata} metadata The updated {@link HmacKeyMetadata} object. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} HmacKeyMetadataResponse + * @property {HmacKeyMetadata} 0 The updated {@link HmacKeyMetadata} object. + * @property {object} 1 The full API response. + */ + /** + * Updates the state of an HMAC key. See {@link SetHmacKeyMetadata} for + * valid states. + * + * @method HmacKey#setMetadata + * @param {SetHmacKeyMetadata} metadata The new metadata. + * @param {SetHmacKeyMetadataOptions} [options] Configuration options. + * @param {HmacKeyMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * const metadata = { + * state: 'INACTIVE', + * }; + * + * storage.hmacKey('ACCESS_ID') + * .setMetadata(metadata, (err, hmacKeyMetadata) => { + * if (err) { + * // The request was an error. + * console.error(err); + * return; + * } + * console.log(hmacKeyMetadata); + * }); + * + * //- + * // If the callback is omitted, a promise is returned. + * //- + * storage.hmacKey('ACCESS_ID') + * .setMetadata(metadata) + * .then((data) => { + * const hmacKeyMetadata = data[0]; + * console.log(hmacKeyMetadata); + * }); + * ``` + */ + setMetadata: { + reqOpts: { + method: 'PUT', + }, + }, + }; + const projectId = (options && options.projectId) || storage.projectId; + super({ + parent: storage, + id: accessId, + baseUrl: `/projects/${projectId}/hmacKeys`, + methods, + }); + this.storage = storage; + this.instanceRetryValue = storage.retryOptions.autoRetry; + } + setMetadata(metadata, optionsOrCallback, cb) { + // ETag preconditions are not currently supported. Retries should be disabled if the idempotency strategy is not set to RetryAlways + if (this.storage.retryOptions.idempotencyStrategy !== + storage_js_1.IdempotencyStrategy.RetryAlways) { + this.storage.retryOptions.autoRetry = false; + } + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + cb = + typeof optionsOrCallback === 'function' + ? optionsOrCallback + : cb; + super + .setMetadata(metadata, options) + .then(resp => cb(null, ...resp)) + .catch(cb) + .finally(() => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + }); + } +} +exports.HmacKey = HmacKey; +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +(0, promisify_1.promisifyAll)(HmacKey); diff --git a/node_modules/@google-cloud/storage/build/cjs/src/iam.d.ts b/node_modules/@google-cloud/storage/build/cjs/src/iam.d.ts new file mode 100644 index 0000000..3ceb19c --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/iam.d.ts @@ -0,0 +1,117 @@ +import { Bucket } from './bucket.js'; +export interface GetPolicyOptions { + userProject?: string; + requestedPolicyVersion?: number; +} +export type GetPolicyResponse = [Policy, unknown]; +/** + * @callback GetPolicyCallback + * @param {?Error} err Request error, if any. + * @param {object} acl The policy. + * @param {object} apiResponse The full API response. + */ +export interface GetPolicyCallback { + (err?: Error | null, acl?: Policy, apiResponse?: unknown): void; +} +/** + * @typedef {object} SetPolicyOptions + * @param {string} [userProject] The ID of the project which will be + * billed for the request. + */ +export interface SetPolicyOptions { + userProject?: string; +} +/** + * @typedef {array} SetPolicyResponse + * @property {object} 0 The policy. + * @property {object} 1 The full API response. + */ +export type SetPolicyResponse = [Policy, unknown]; +/** + * @callback SetPolicyCallback + * @param {?Error} err Request error, if any. + * @param {object} acl The policy. + * @param {object} apiResponse The full API response. + */ +export interface SetPolicyCallback { + (err?: Error | null, acl?: Policy, apiResponse?: object): void; +} +export interface Policy { + bindings: PolicyBinding[]; + version?: number; + etag?: string; +} +export interface PolicyBinding { + role: string; + members: string[]; + condition?: Expr; +} +export interface Expr { + title?: string; + description?: string; + expression: string; +} +/** + * @typedef {array} TestIamPermissionsResponse + * @property {object} 0 A subset of permissions that the caller is allowed. + * @property {object} 1 The full API response. + */ +export type TestIamPermissionsResponse = [{ + [key: string]: boolean; +}, unknown]; +/** + * @callback TestIamPermissionsCallback + * @param {?Error} err Request error, if any. + * @param {object} acl A subset of permissions that the caller is allowed. + * @param {object} apiResponse The full API response. + */ +export interface TestIamPermissionsCallback { + (err?: Error | null, acl?: { + [key: string]: boolean; + } | null, apiResponse?: unknown): void; +} +/** + * @typedef {object} TestIamPermissionsOptions Configuration options for Iam#testPermissions(). + * @param {string} [userProject] The ID of the project which will be + * billed for the request. + */ +export interface TestIamPermissionsOptions { + userProject?: string; +} +export declare enum IAMExceptionMessages { + POLICY_OBJECT_REQUIRED = "A policy object is required.", + PERMISSIONS_REQUIRED = "Permissions are required." +} +/** + * Get and set IAM policies for your Cloud Storage bucket. + * + * See {@link https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management| Cloud Storage IAM Management} + * See {@link https://cloud.google.com/iam/docs/granting-changing-revoking-access| Granting, Changing, and Revoking Access} + * See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles} + * + * @constructor Iam + * + * @param {Bucket} bucket The parent instance. + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * // bucket.iam + * ``` + */ +declare class Iam { + private request_; + private resourceId_; + constructor(bucket: Bucket); + getPolicy(options?: GetPolicyOptions): Promise; + getPolicy(options: GetPolicyOptions, callback: GetPolicyCallback): void; + getPolicy(callback: GetPolicyCallback): void; + setPolicy(policy: Policy, options?: SetPolicyOptions): Promise; + setPolicy(policy: Policy, callback: SetPolicyCallback): void; + setPolicy(policy: Policy, options: SetPolicyOptions, callback: SetPolicyCallback): void; + testPermissions(permissions: string | string[], options?: TestIamPermissionsOptions): Promise; + testPermissions(permissions: string | string[], callback: TestIamPermissionsCallback): void; + testPermissions(permissions: string | string[], options: TestIamPermissionsOptions, callback: TestIamPermissionsCallback): void; +} +export { Iam }; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/iam.js b/node_modules/@google-cloud/storage/build/cjs/src/iam.js new file mode 100644 index 0000000..9d4ce67 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/iam.js @@ -0,0 +1,306 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Iam = exports.IAMExceptionMessages = void 0; +const promisify_1 = require("@google-cloud/promisify"); +const util_js_1 = require("./util.js"); +var IAMExceptionMessages; +(function (IAMExceptionMessages) { + IAMExceptionMessages["POLICY_OBJECT_REQUIRED"] = "A policy object is required."; + IAMExceptionMessages["PERMISSIONS_REQUIRED"] = "Permissions are required."; +})(IAMExceptionMessages || (exports.IAMExceptionMessages = IAMExceptionMessages = {})); +/** + * Get and set IAM policies for your Cloud Storage bucket. + * + * See {@link https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management| Cloud Storage IAM Management} + * See {@link https://cloud.google.com/iam/docs/granting-changing-revoking-access| Granting, Changing, and Revoking Access} + * See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles} + * + * @constructor Iam + * + * @param {Bucket} bucket The parent instance. + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * // bucket.iam + * ``` + */ +class Iam { + constructor(bucket) { + this.request_ = bucket.request.bind(bucket); + this.resourceId_ = 'buckets/' + bucket.getId(); + } + /** + * @typedef {object} GetPolicyOptions Requested options for IAM#getPolicy(). + * @property {number} [requestedPolicyVersion] The version of IAM policies to + * request. If a policy with a condition is requested without setting + * this, the server will return an error. This must be set to a value + * of 3 to retrieve IAM policies containing conditions. This is to + * prevent client code that isn't aware of IAM conditions from + * interpreting and modifying policies incorrectly. The service might + * return a policy with version lower than the one that was requested, + * based on the feature syntax in the policy fetched. + * See {@link https://cloud.google.com/iam/docs/policies#versions| IAM Policy versions} + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @typedef {array} GetPolicyResponse + * @property {Policy} 0 The policy. + * @property {object} 1 The full API response. + */ + /** + * @typedef {object} Policy + * @property {PolicyBinding[]} policy.bindings Bindings associate members with roles. + * @property {string} [policy.etag] Etags are used to perform a read-modify-write. + * @property {number} [policy.version] The syntax schema version of the Policy. + * To set an IAM policy with conditional binding, this field must be set to + * 3 or greater. + * See {@link https://cloud.google.com/iam/docs/policies#versions| IAM Policy versions} + */ + /** + * @typedef {object} PolicyBinding + * @property {string} role Role that is assigned to members. + * @property {string[]} members Specifies the identities requesting access for the bucket. + * @property {Expr} [condition] The condition that is associated with this binding. + */ + /** + * @typedef {object} Expr + * @property {string} [title] An optional title for the expression, i.e. a + * short string describing its purpose. This can be used e.g. in UIs + * which allow to enter the expression. + * @property {string} [description] An optional description of the + * expression. This is a longer text which describes the expression, + * e.g. when hovered over it in a UI. + * @property {string} expression Textual representation of an expression in + * Common Expression Language syntax. The application context of the + * containing message determines which well-known feature set of CEL + * is supported.The condition that is associated with this binding. + * + * @see [Condition] https://cloud.google.com/storage/docs/access-control/iam#conditions + */ + /** + * Get the IAM policy. + * + * @param {GetPolicyOptions} [options] Request options. + * @param {GetPolicyCallback} [callback] Callback function. + * @returns {Promise} + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy| Buckets: setIamPolicy API Documentation} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * bucket.iam.getPolicy( + * {requestedPolicyVersion: 3}, + * function(err, policy, apiResponse) { + * + * }, + * ); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.iam.getPolicy({requestedPolicyVersion: 3}) + * .then(function(data) { + * const policy = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/iam.js + * region_tag:storage_view_bucket_iam_members + * Example of retrieving a bucket's IAM policy: + */ + getPolicy(optionsOrCallback, callback) { + const { options, callback: cb } = (0, util_js_1.normalize)(optionsOrCallback, callback); + const qs = {}; + if (options.userProject) { + qs.userProject = options.userProject; + } + if (options.requestedPolicyVersion !== null && + options.requestedPolicyVersion !== undefined) { + qs.optionsRequestedPolicyVersion = options.requestedPolicyVersion; + } + this.request_({ + uri: '/iam', + qs, + }, cb); + } + /** + * Set the IAM policy. + * + * @throws {Error} If no policy is provided. + * + * @param {Policy} policy The policy. + * @param {SetPolicyOptions} [options] Configuration options. + * @param {SetPolicyCallback} callback Callback function. + * @returns {Promise} + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/setIamPolicy| Buckets: setIamPolicy API Documentation} + * See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * const myPolicy = { + * bindings: [ + * { + * role: 'roles/storage.admin', + * members: + * ['serviceAccount:myotherproject@appspot.gserviceaccount.com'] + * } + * ] + * }; + * + * bucket.iam.setPolicy(myPolicy, function(err, policy, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.iam.setPolicy(myPolicy).then(function(data) { + * const policy = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/iam.js + * region_tag:storage_add_bucket_iam_member + * Example of adding to a bucket's IAM policy: + * + * @example include:samples/iam.js + * region_tag:storage_remove_bucket_iam_member + * Example of removing from a bucket's IAM policy: + */ + setPolicy(policy, optionsOrCallback, callback) { + if (policy === null || typeof policy !== 'object') { + throw new Error(IAMExceptionMessages.POLICY_OBJECT_REQUIRED); + } + const { options, callback: cb } = (0, util_js_1.normalize)(optionsOrCallback, callback); + let maxRetries; + if (policy.etag === undefined) { + maxRetries = 0; + } + this.request_({ + method: 'PUT', + uri: '/iam', + maxRetries, + json: Object.assign({ + resourceId: this.resourceId_, + }, policy), + qs: options, + }, cb); + } + /** + * Test a set of permissions for a resource. + * + * @throws {Error} If permissions are not provided. + * + * @param {string|string[]} permissions The permission(s) to test for. + * @param {TestIamPermissionsOptions} [options] Configuration object. + * @param {TestIamPermissionsCallback} [callback] Callback function. + * @returns {Promise} + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/testIamPermissions| Buckets: testIamPermissions API Documentation} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * //- + * // Test a single permission. + * //- + * const test = 'storage.buckets.delete'; + * + * bucket.iam.testPermissions(test, function(err, permissions, apiResponse) { + * console.log(permissions); + * // { + * // "storage.buckets.delete": true + * // } + * }); + * + * //- + * // Test several permissions at once. + * //- + * const tests = [ + * 'storage.buckets.delete', + * 'storage.buckets.get' + * ]; + * + * bucket.iam.testPermissions(tests, function(err, permissions) { + * console.log(permissions); + * // { + * // "storage.buckets.delete": false, + * // "storage.buckets.get": true + * // } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.iam.testPermissions(test).then(function(data) { + * const permissions = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + testPermissions(permissions, optionsOrCallback, callback) { + if (!Array.isArray(permissions) && typeof permissions !== 'string') { + throw new Error(IAMExceptionMessages.PERMISSIONS_REQUIRED); + } + const { options, callback: cb } = (0, util_js_1.normalize)(optionsOrCallback, callback); + const permissionsArray = Array.isArray(permissions) + ? permissions + : [permissions]; + const req = Object.assign({ + permissions: permissionsArray, + }, options); + this.request_({ + uri: '/iam/testPermissions', + qs: req, + useQuerystring: true, + }, (err, resp) => { + if (err) { + cb(err, null, resp); + return; + } + const availablePermissions = Array.isArray(resp.permissions) + ? resp.permissions + : []; + const permissionsHash = permissionsArray.reduce((acc, permission) => { + acc[permission] = availablePermissions.indexOf(permission) > -1; + return acc; + }, {}); + cb(null, permissionsHash, resp); + }); + } +} +exports.Iam = Iam; +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +(0, promisify_1.promisifyAll)(Iam); diff --git a/node_modules/@google-cloud/storage/build/cjs/src/index.d.ts b/node_modules/@google-cloud/storage/build/cjs/src/index.d.ts new file mode 100644 index 0000000..82c50e0 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/index.d.ts @@ -0,0 +1,57 @@ +/** + * The `@google-cloud/storage` package has a single named export which is the + * {@link Storage} (ES6) class, which should be instantiated with `new`. + * + * See {@link Storage} and {@link ClientConfig} for client methods and + * configuration options. + * + * @module {Storage} @google-cloud/storage + * @alias nodejs-storage + * + * @example + * Install the client library with npm: + * ``` + * npm install --save @google-cloud/storage + * ``` + * + * @example + * Import the client library + * ``` + * const {Storage} = require('@google-cloud/storage'); + * ``` + * + * @example + * Create a client that uses Application + * Default Credentials (ADC): + * ``` + * const storage = new Storage(); + * ``` + * + * @example + * Create a client with explicit + * credentials: + * ``` + * const storage = new Storage({ projectId: + * 'your-project-id', keyFilename: '/path/to/keyfile.json' + * }); + * ``` + * + * @example include:samples/quickstart.js + * region_tag:storage_quickstart + * Full quickstart example: + */ +export { ApiError } from './nodejs-common/index.js'; +export { BucketCallback, BucketOptions, CreateBucketQuery, CreateBucketRequest, CreateBucketResponse, CreateHmacKeyCallback, CreateHmacKeyOptions, CreateHmacKeyResponse, GetBucketsCallback, GetBucketsRequest, GetBucketsResponse, GetHmacKeysCallback, GetHmacKeysOptions, GetHmacKeysResponse, GetServiceAccountCallback, GetServiceAccountOptions, GetServiceAccountResponse, HmacKeyResourceResponse, IdempotencyStrategy, PreconditionOptions, RETRYABLE_ERR_FN_DEFAULT, ServiceAccount, Storage, StorageOptions, } from './storage.js'; +export { AclMetadata, AccessControlObject, AclOptions, AddAclCallback, AddAclOptions, AddAclResponse, GetAclCallback, GetAclOptions, GetAclResponse, RemoveAclCallback, RemoveAclOptions, RemoveAclResponse, UpdateAclCallback, UpdateAclOptions, UpdateAclResponse, } from './acl.js'; +export { Bucket, BucketExistsCallback, BucketExistsOptions, BucketExistsResponse, BucketLockCallback, BucketLockResponse, BucketMetadata, CombineCallback, CombineOptions, CombineResponse, CreateChannelCallback, CreateChannelConfig, CreateChannelOptions, CreateChannelResponse, CreateNotificationCallback, CreateNotificationOptions, CreateNotificationResponse, DeleteBucketCallback, DeleteBucketOptions, DeleteBucketResponse, DeleteFilesCallback, DeleteFilesOptions, DeleteLabelsCallback, DeleteLabelsResponse, DisableRequesterPaysCallback, DisableRequesterPaysResponse, EnableRequesterPaysCallback, EnableRequesterPaysResponse, GetBucketCallback, GetBucketMetadataCallback, GetBucketMetadataOptions, GetBucketMetadataResponse, GetBucketOptions, GetBucketResponse, GetBucketSignedUrlConfig, GetFilesCallback, GetFilesOptions, GetFilesResponse, GetLabelsCallback, GetLabelsOptions, GetLabelsResponse, GetNotificationsCallback, GetNotificationsOptions, GetNotificationsResponse, Labels, LifecycleAction, LifecycleCondition, LifecycleRule, MakeBucketPrivateCallback, MakeBucketPrivateOptions, MakeBucketPrivateResponse, MakeBucketPublicCallback, MakeBucketPublicOptions, MakeBucketPublicResponse, SetBucketMetadataCallback, SetBucketMetadataOptions, SetBucketMetadataResponse, SetBucketStorageClassCallback, SetBucketStorageClassOptions, SetLabelsCallback, SetLabelsOptions, SetLabelsResponse, UploadCallback, UploadOptions, UploadResponse, } from './bucket.js'; +export * from './crc32c.js'; +export { Channel, StopCallback } from './channel.js'; +export { CopyCallback, CopyOptions, CopyResponse, CreateReadStreamOptions, CreateResumableUploadCallback, CreateResumableUploadOptions, CreateResumableUploadResponse, CreateWriteStreamOptions, DeleteFileCallback, DeleteFileOptions, DeleteFileResponse, DownloadCallback, DownloadOptions, DownloadResponse, EncryptionKeyOptions, File, FileExistsCallback, FileExistsOptions, FileExistsResponse, FileMetadata, FileOptions, GetExpirationDateCallback, GetExpirationDateResponse, GetFileCallback, GetFileMetadataCallback, GetFileMetadataOptions, GetFileMetadataResponse, GetFileOptions, GetFileResponse, GenerateSignedPostPolicyV2Callback, GenerateSignedPostPolicyV2Options, GenerateSignedPostPolicyV2Response, GenerateSignedPostPolicyV4Callback, GenerateSignedPostPolicyV4Options, GenerateSignedPostPolicyV4Response, GetSignedUrlConfig, MakeFilePrivateCallback, MakeFilePrivateOptions, MakeFilePrivateResponse, MakeFilePublicCallback, MakeFilePublicResponse, MoveCallback, MoveOptions, MoveResponse, MoveFileAtomicOptions, MoveFileAtomicCallback, MoveFileAtomicResponse, PolicyDocument, PolicyFields, PredefinedAcl, RotateEncryptionKeyCallback, RotateEncryptionKeyOptions, RotateEncryptionKeyResponse, SaveCallback, SaveData, SaveOptions, SetFileMetadataCallback, SetFileMetadataOptions, SetFileMetadataResponse, SetStorageClassCallback, SetStorageClassOptions, SetStorageClassResponse, SignedPostPolicyV4Output, } from './file.js'; +export * from './hash-stream-validator.js'; +export { HmacKey, HmacKeyMetadata, HmacKeyMetadataCallback, HmacKeyMetadataResponse, SetHmacKeyMetadata, SetHmacKeyMetadataOptions, } from './hmacKey.js'; +export { GetPolicyCallback, GetPolicyOptions, GetPolicyResponse, Iam, Policy, SetPolicyCallback, SetPolicyOptions, SetPolicyResponse, TestIamPermissionsCallback, TestIamPermissionsOptions, TestIamPermissionsResponse, } from './iam.js'; +export { DeleteNotificationCallback, DeleteNotificationOptions, GetNotificationCallback, GetNotificationMetadataCallback, GetNotificationMetadataOptions, GetNotificationMetadataResponse, GetNotificationOptions, GetNotificationResponse, Notification, NotificationMetadata, } from './notification.js'; +export { GetSignedUrlCallback, GetSignedUrlResponse } from './signer.js'; +export * from './transfer-manager.js'; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/index.js b/node_modules/@google-cloud/storage/build/cjs/src/index.js new file mode 100644 index 0000000..79f4feb --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/index.js @@ -0,0 +1,95 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Notification = exports.Iam = exports.HmacKey = exports.File = exports.Channel = exports.Bucket = exports.Storage = exports.RETRYABLE_ERR_FN_DEFAULT = exports.IdempotencyStrategy = exports.ApiError = void 0; +/** + * The `@google-cloud/storage` package has a single named export which is the + * {@link Storage} (ES6) class, which should be instantiated with `new`. + * + * See {@link Storage} and {@link ClientConfig} for client methods and + * configuration options. + * + * @module {Storage} @google-cloud/storage + * @alias nodejs-storage + * + * @example + * Install the client library with npm: + * ``` + * npm install --save @google-cloud/storage + * ``` + * + * @example + * Import the client library + * ``` + * const {Storage} = require('@google-cloud/storage'); + * ``` + * + * @example + * Create a client that uses Application + * Default Credentials (ADC): + * ``` + * const storage = new Storage(); + * ``` + * + * @example + * Create a client with explicit + * credentials: + * ``` + * const storage = new Storage({ projectId: + * 'your-project-id', keyFilename: '/path/to/keyfile.json' + * }); + * ``` + * + * @example include:samples/quickstart.js + * region_tag:storage_quickstart + * Full quickstart example: + */ +var index_js_1 = require("./nodejs-common/index.js"); +Object.defineProperty(exports, "ApiError", { enumerable: true, get: function () { return index_js_1.ApiError; } }); +var storage_js_1 = require("./storage.js"); +Object.defineProperty(exports, "IdempotencyStrategy", { enumerable: true, get: function () { return storage_js_1.IdempotencyStrategy; } }); +Object.defineProperty(exports, "RETRYABLE_ERR_FN_DEFAULT", { enumerable: true, get: function () { return storage_js_1.RETRYABLE_ERR_FN_DEFAULT; } }); +Object.defineProperty(exports, "Storage", { enumerable: true, get: function () { return storage_js_1.Storage; } }); +var bucket_js_1 = require("./bucket.js"); +Object.defineProperty(exports, "Bucket", { enumerable: true, get: function () { return bucket_js_1.Bucket; } }); +__exportStar(require("./crc32c.js"), exports); +var channel_js_1 = require("./channel.js"); +Object.defineProperty(exports, "Channel", { enumerable: true, get: function () { return channel_js_1.Channel; } }); +var file_js_1 = require("./file.js"); +Object.defineProperty(exports, "File", { enumerable: true, get: function () { return file_js_1.File; } }); +__exportStar(require("./hash-stream-validator.js"), exports); +var hmacKey_js_1 = require("./hmacKey.js"); +Object.defineProperty(exports, "HmacKey", { enumerable: true, get: function () { return hmacKey_js_1.HmacKey; } }); +var iam_js_1 = require("./iam.js"); +Object.defineProperty(exports, "Iam", { enumerable: true, get: function () { return iam_js_1.Iam; } }); +var notification_js_1 = require("./notification.js"); +Object.defineProperty(exports, "Notification", { enumerable: true, get: function () { return notification_js_1.Notification; } }); +__exportStar(require("./transfer-manager.js"), exports); diff --git a/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/index.d.ts b/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/index.d.ts new file mode 100644 index 0000000..72588c7 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/index.d.ts @@ -0,0 +1,19 @@ +/*! + * Copyright 2022 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. + */ +export { GoogleAuthOptions } from 'google-auth-library'; +export { Service, ServiceConfig, ServiceOptions, StreamRequestOptions, } from './service.js'; +export { BaseMetadata, DeleteCallback, ExistsCallback, GetConfig, InstanceResponseCallback, Interceptor, MetadataCallback, MetadataResponse, Methods, ResponseCallback, ServiceObject, ServiceObjectConfig, ServiceObjectParent, SetMetadataResponse, } from './service-object.js'; +export { Abortable, AbortableDuplex, ApiError, BodyResponseCallback, DecorateRequestOptions, ResponseBody, util, } from './util.js'; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/index.js b/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/index.js new file mode 100644 index 0000000..bf7023c --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/index.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.util = exports.ApiError = exports.ServiceObject = exports.Service = void 0; +var service_js_1 = require("./service.js"); +Object.defineProperty(exports, "Service", { enumerable: true, get: function () { return service_js_1.Service; } }); +var service_object_js_1 = require("./service-object.js"); +Object.defineProperty(exports, "ServiceObject", { enumerable: true, get: function () { return service_object_js_1.ServiceObject; } }); +var util_js_1 = require("./util.js"); +Object.defineProperty(exports, "ApiError", { enumerable: true, get: function () { return util_js_1.ApiError; } }); +Object.defineProperty(exports, "util", { enumerable: true, get: function () { return util_js_1.util; } }); diff --git a/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/service-object.d.ts b/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/service-object.d.ts new file mode 100644 index 0000000..108c0ce --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/service-object.d.ts @@ -0,0 +1,217 @@ +import { EventEmitter } from 'events'; +import * as r from 'teeny-request'; +import { ApiError, BodyResponseCallback, DecorateRequestOptions } from './util.js'; +export type RequestResponse = [unknown, r.Response]; +export interface ServiceObjectParent { + interceptors: Interceptor[]; + getRequestInterceptors(): Function[]; + requestStream(reqOpts: DecorateRequestOptions): r.Request; + request(reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void; +} +export interface Interceptor { + request(opts: r.Options): DecorateRequestOptions; +} +export type GetMetadataOptions = object; +export type MetadataResponse = [K, r.Response]; +export type MetadataCallback = (err: Error | null, metadata?: K, apiResponse?: r.Response) => void; +export type ExistsOptions = object; +export interface ExistsCallback { + (err: Error | null, exists?: boolean): void; +} +export interface ServiceObjectConfig { + /** + * The base URL to make API requests to. + */ + baseUrl?: string; + /** + * The method which creates this object. + */ + createMethod?: Function; + /** + * The identifier of the object. For example, the name of a Storage bucket or + * Pub/Sub topic. + */ + id?: string; + /** + * A map of each method name that should be inherited. + */ + methods?: Methods; + /** + * The parent service instance. For example, an instance of Storage if the + * object is Bucket. + */ + parent: ServiceObjectParent; + /** + * Override of projectId, used to allow access to resources in another project. + * For example, a BigQuery dataset in another project to which the user has been + * granted permission. + */ + projectId?: string; +} +export interface Methods { + [methodName: string]: { + reqOpts?: r.CoreOptions; + } | boolean; +} +export interface InstanceResponseCallback { + (err: ApiError | null, instance?: T | null, apiResponse?: r.Response): void; +} +export interface CreateOptions { +} +export type CreateResponse = any[]; +export interface CreateCallback { + (err: ApiError | null, instance?: T | null, ...args: any[]): void; +} +export type DeleteOptions = { + ignoreNotFound?: boolean; + ifGenerationMatch?: number | string; + ifGenerationNotMatch?: number | string; + ifMetagenerationMatch?: number | string; + ifMetagenerationNotMatch?: number | string; +} & object; +export interface DeleteCallback { + (err: Error | null, apiResponse?: r.Response): void; +} +export interface GetConfig { + /** + * Create the object if it doesn't already exist. + */ + autoCreate?: boolean; +} +export type GetOrCreateOptions = GetConfig & CreateOptions; +export type GetResponse = [T, r.Response]; +export interface ResponseCallback { + (err?: Error | null, apiResponse?: r.Response): void; +} +export type SetMetadataResponse = [K]; +export type SetMetadataOptions = object; +export interface BaseMetadata { + id?: string; + kind?: string; + etag?: string; + selfLink?: string; + [key: string]: unknown; +} +/** + * ServiceObject is a base class, meant to be inherited from by a "service + * object," like a BigQuery dataset or Storage bucket. + * + * Most of the time, these objects share common functionality; they can be + * created or deleted, and you can get or set their metadata. + * + * By inheriting from this class, a service object will be extended with these + * shared behaviors. Note that any method can be overridden when the service + * object requires specific behavior. + */ +declare class ServiceObject extends EventEmitter { + metadata: K; + baseUrl?: string; + parent: ServiceObjectParent; + id?: string; + private createMethod?; + protected methods: Methods; + interceptors: Interceptor[]; + projectId?: string; + constructor(config: ServiceObjectConfig); + /** + * Create the object. + * + * @param {object=} options - Configuration object. + * @param {function} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.instance - The instance. + * @param {object} callback.apiResponse - The full API response. + */ + create(options?: CreateOptions): Promise>; + create(options: CreateOptions, callback: CreateCallback): void; + create(callback: CreateCallback): void; + /** + * Delete the object. + * + * @param {function=} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.apiResponse - The full API response. + */ + delete(options?: DeleteOptions): Promise<[r.Response]>; + delete(options: DeleteOptions, callback: DeleteCallback): void; + delete(callback: DeleteCallback): void; + /** + * Check if the object exists. + * + * @param {function} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {boolean} callback.exists - Whether the object exists or not. + */ + exists(options?: ExistsOptions): Promise<[boolean]>; + exists(options: ExistsOptions, callback: ExistsCallback): void; + exists(callback: ExistsCallback): void; + /** + * Get the object if it exists. Optionally have the object created if an + * options object is provided with `autoCreate: true`. + * + * @param {object=} options - The configuration object that will be used to + * create the object if necessary. + * @param {boolean} options.autoCreate - Create the object if it doesn't already exist. + * @param {function} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.instance - The instance. + * @param {object} callback.apiResponse - The full API response. + */ + get(options?: GetOrCreateOptions): Promise>; + get(callback: InstanceResponseCallback): void; + get(options: GetOrCreateOptions, callback: InstanceResponseCallback): void; + /** + * Get the metadata of this object. + * + * @param {function} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.metadata - The metadata for this object. + * @param {object} callback.apiResponse - The full API response. + */ + getMetadata(options?: GetMetadataOptions): Promise>; + getMetadata(options: GetMetadataOptions, callback: MetadataCallback): void; + getMetadata(callback: MetadataCallback): void; + /** + * Return the user's custom request interceptors. + */ + getRequestInterceptors(): Function[]; + /** + * Set the metadata for this object. + * + * @param {object} metadata - The metadata to set on this object. + * @param {object=} options - Configuration options. + * @param {function=} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.apiResponse - The full API response. + */ + setMetadata(metadata: K, options?: SetMetadataOptions): Promise>; + setMetadata(metadata: K, callback: MetadataCallback): void; + setMetadata(metadata: K, options: SetMetadataOptions, callback: MetadataCallback): void; + /** + * Make an authenticated API request. + * + * @private + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + * @param {function} callback - The callback function passed to `request`. + */ + private request_; + /** + * Make an authenticated API request. + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + * @param {function} callback - The callback function passed to `request`. + */ + request(reqOpts: DecorateRequestOptions): Promise; + request(reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void; + /** + * Make an authenticated API request. + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + */ + requestStream(reqOpts: DecorateRequestOptions): r.Request; +} +export { ServiceObject }; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/service-object.js b/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/service-object.js new file mode 100644 index 0000000..7b2cdc8 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/service-object.js @@ -0,0 +1,292 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ServiceObject = void 0; +/*! + * Copyright 2022 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. + */ +const promisify_1 = require("@google-cloud/promisify"); +const events_1 = require("events"); +const util_js_1 = require("./util.js"); +/** + * ServiceObject is a base class, meant to be inherited from by a "service + * object," like a BigQuery dataset or Storage bucket. + * + * Most of the time, these objects share common functionality; they can be + * created or deleted, and you can get or set their metadata. + * + * By inheriting from this class, a service object will be extended with these + * shared behaviors. Note that any method can be overridden when the service + * object requires specific behavior. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +class ServiceObject extends events_1.EventEmitter { + /* + * @constructor + * @alias module:common/service-object + * + * @private + * + * @param {object} config - Configuration object. + * @param {string} config.baseUrl - The base URL to make API requests to. + * @param {string} config.createMethod - The method which creates this object. + * @param {string=} config.id - The identifier of the object. For example, the + * name of a Storage bucket or Pub/Sub topic. + * @param {object=} config.methods - A map of each method name that should be inherited. + * @param {object} config.methods[].reqOpts - Default request options for this + * particular method. A common use case is when `setMetadata` requires a + * `PUT` method to override the default `PATCH`. + * @param {object} config.parent - The parent service instance. For example, an + * instance of Storage if the object is Bucket. + */ + constructor(config) { + super(); + this.metadata = {}; + this.baseUrl = config.baseUrl; + this.parent = config.parent; // Parent class. + this.id = config.id; // Name or ID (e.g. dataset ID, bucket name, etc). + this.createMethod = config.createMethod; + this.methods = config.methods || {}; + this.interceptors = []; + this.projectId = config.projectId; + if (config.methods) { + // This filters the ServiceObject instance (e.g. a "File") to only have + // the configured methods. We make a couple of exceptions for core- + // functionality ("request()" and "getRequestInterceptors()") + Object.getOwnPropertyNames(ServiceObject.prototype) + .filter(methodName => { + return ( + // All ServiceObjects need `request` and `getRequestInterceptors`. + // clang-format off + !/^request/.test(methodName) && + !/^getRequestInterceptors/.test(methodName) && + // clang-format on + // The ServiceObject didn't redefine the method. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this[methodName] === + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ServiceObject.prototype[methodName] && + // This method isn't wanted. + !config.methods[methodName]); + }) + .forEach(methodName => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this[methodName] = undefined; + }); + } + } + create(optionsOrCallback, callback) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const self = this; + const args = [this.id]; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + if (typeof optionsOrCallback === 'object') { + args.push(optionsOrCallback); + } + // Wrap the callback to return *this* instance of the object, not the + // newly-created one. + // tslint: disable-next-line no-any + function onCreate(...args) { + const [err, instance] = args; + if (!err) { + self.metadata = instance.metadata; + if (self.id && instance.metadata) { + self.id = instance.metadata.id; + } + args[1] = self; // replace the created `instance` with this one. + } + callback(...args); + } + args.push(onCreate); + // eslint-disable-next-line prefer-spread + this.createMethod.apply(null, args); + } + delete(optionsOrCallback, cb) { + var _a; + const [options, callback] = util_js_1.util.maybeOptionsOrCallback(optionsOrCallback, cb); + const ignoreNotFound = options.ignoreNotFound; + delete options.ignoreNotFound; + const methodConfig = (typeof this.methods.delete === 'object' && this.methods.delete) || {}; + const reqOpts = { + method: 'DELETE', + uri: '', + ...methodConfig.reqOpts, + qs: { + ...(_a = methodConfig.reqOpts) === null || _a === void 0 ? void 0 : _a.qs, + ...options, + }, + }; + // The `request` method may have been overridden to hold any special + // behavior. Ensure we call the original `request` method. + ServiceObject.prototype.request.call(this, reqOpts, (err, body, res) => { + if (err) { + if (err.code === 404 && ignoreNotFound) { + err = null; + } + } + callback(err, res); + }); + } + exists(optionsOrCallback, cb) { + const [options, callback] = util_js_1.util.maybeOptionsOrCallback(optionsOrCallback, cb); + this.get(options, err => { + if (err) { + if (err.code === 404) { + callback(null, false); + } + else { + callback(err); + } + return; + } + callback(null, true); + }); + } + get(optionsOrCallback, cb) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const self = this; + const [opts, callback] = util_js_1.util.maybeOptionsOrCallback(optionsOrCallback, cb); + const options = Object.assign({}, opts); + const autoCreate = options.autoCreate && typeof this.create === 'function'; + delete options.autoCreate; + function onCreate(err, instance, apiResponse) { + if (err) { + if (err.code === 409) { + self.get(options, callback); + return; + } + callback(err, null, apiResponse); + return; + } + callback(null, instance, apiResponse); + } + this.getMetadata(options, (err, metadata) => { + if (err) { + if (err.code === 404 && autoCreate) { + const args = []; + if (Object.keys(options).length > 0) { + args.push(options); + } + args.push(onCreate); + self.create(...args); + return; + } + callback(err, null, metadata); + return; + } + callback(null, self, metadata); + }); + } + getMetadata(optionsOrCallback, cb) { + var _a; + const [options, callback] = util_js_1.util.maybeOptionsOrCallback(optionsOrCallback, cb); + const methodConfig = (typeof this.methods.getMetadata === 'object' && + this.methods.getMetadata) || + {}; + const reqOpts = { + uri: '', + ...methodConfig.reqOpts, + qs: { + ...(_a = methodConfig.reqOpts) === null || _a === void 0 ? void 0 : _a.qs, + ...options, + }, + }; + // The `request` method may have been overridden to hold any special + // behavior. Ensure we call the original `request` method. + ServiceObject.prototype.request.call(this, reqOpts, (err, body, res) => { + this.metadata = body; + callback(err, this.metadata, res); + }); + } + /** + * Return the user's custom request interceptors. + */ + getRequestInterceptors() { + // Interceptors should be returned in the order they were assigned. + const localInterceptors = this.interceptors + .filter(interceptor => typeof interceptor.request === 'function') + .map(interceptor => interceptor.request); + return this.parent.getRequestInterceptors().concat(localInterceptors); + } + setMetadata(metadata, optionsOrCallback, cb) { + var _a, _b; + const [options, callback] = util_js_1.util.maybeOptionsOrCallback(optionsOrCallback, cb); + const methodConfig = (typeof this.methods.setMetadata === 'object' && + this.methods.setMetadata) || + {}; + const reqOpts = { + method: 'PATCH', + uri: '', + ...methodConfig.reqOpts, + json: { + ...(_a = methodConfig.reqOpts) === null || _a === void 0 ? void 0 : _a.json, + ...metadata, + }, + qs: { + ...(_b = methodConfig.reqOpts) === null || _b === void 0 ? void 0 : _b.qs, + ...options, + }, + }; + // The `request` method may have been overridden to hold any special + // behavior. Ensure we call the original `request` method. + ServiceObject.prototype.request.call(this, reqOpts, (err, body, res) => { + this.metadata = body; + callback(err, this.metadata, res); + }); + } + request_(reqOpts, callback) { + reqOpts = { ...reqOpts }; + if (this.projectId) { + reqOpts.projectId = this.projectId; + } + const isAbsoluteUrl = reqOpts.uri.indexOf('http') === 0; + const uriComponents = [this.baseUrl, this.id || '', reqOpts.uri]; + if (isAbsoluteUrl) { + uriComponents.splice(0, uriComponents.indexOf(reqOpts.uri)); + } + reqOpts.uri = uriComponents + .filter(x => x.trim()) // Limit to non-empty strings. + .map(uriComponent => { + const trimSlashesRegex = /^\/*|\/*$/g; + return uriComponent.replace(trimSlashesRegex, ''); + }) + .join('/'); + const childInterceptors = Array.isArray(reqOpts.interceptors_) + ? reqOpts.interceptors_ + : []; + const localInterceptors = [].slice.call(this.interceptors); + reqOpts.interceptors_ = childInterceptors.concat(localInterceptors); + if (reqOpts.shouldReturnStream) { + return this.parent.requestStream(reqOpts); + } + this.parent.request(reqOpts, callback); + } + request(reqOpts, callback) { + this.request_(reqOpts, callback); + } + /** + * Make an authenticated API request. + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + */ + requestStream(reqOpts) { + const opts = { ...reqOpts, shouldReturnStream: true }; + return this.request_(opts); + } +} +exports.ServiceObject = ServiceObject; +(0, promisify_1.promisifyAll)(ServiceObject, { exclude: ['getRequestInterceptors'] }); diff --git a/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/service.d.ts b/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/service.d.ts new file mode 100644 index 0000000..073c180 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/service.d.ts @@ -0,0 +1,130 @@ +/*! + * Copyright 2022 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. + */ +import { AuthClient, GoogleAuth, GoogleAuthOptions } from 'google-auth-library'; +import * as r from 'teeny-request'; +import { Interceptor } from './service-object.js'; +import { BodyResponseCallback, DecorateRequestOptions, MakeAuthenticatedRequest, PackageJson } from './util.js'; +export declare const DEFAULT_PROJECT_ID_TOKEN = "{{projectId}}"; +export interface StreamRequestOptions extends DecorateRequestOptions { + shouldReturnStream: true; +} +export interface ServiceConfig { + /** + * The base URL to make API requests to. + */ + baseUrl: string; + /** + * The API Endpoint to use when connecting to the service. + * Example: storage.googleapis.com + */ + apiEndpoint: string; + /** + * The scopes required for the request. + */ + scopes: string[]; + projectIdRequired?: boolean; + packageJson: PackageJson; + /** + * Reuse an existing `AuthClient` or `GoogleAuth` client instead of creating a new one. + */ + authClient?: AuthClient | GoogleAuth; + /** + * Set to true if the endpoint is a custom URL + */ + customEndpoint?: boolean; + /** + * Controls whether or not to use authentication when using a custom endpoint. + */ + useAuthWithCustomEndpoint?: boolean; +} +export interface ServiceOptions extends Omit { + authClient?: AuthClient | GoogleAuth; + interceptors_?: Interceptor[]; + email?: string; + token?: string; + timeout?: number; + userAgent?: string; + useAuthWithCustomEndpoint?: boolean; +} +export declare class Service { + baseUrl: string; + private globalInterceptors; + interceptors: Interceptor[]; + private packageJson; + projectId: string; + private projectIdRequired; + providedUserAgent?: string; + makeAuthenticatedRequest: MakeAuthenticatedRequest; + authClient: GoogleAuth; + apiEndpoint: string; + timeout?: number; + universeDomain: string; + customEndpoint: boolean; + useAuthWithCustomEndpoint?: boolean; + /** + * Service is a base class, meant to be inherited from by a "service," like + * BigQuery or Storage. + * + * This handles making authenticated requests by exposing a `makeReq_` + * function. + * + * @constructor + * @alias module:common/service + * + * @param {object} config - Configuration object. + * @param {string} config.baseUrl - The base URL to make API requests to. + * @param {string[]} config.scopes - The scopes required for the request. + * @param {object=} options - [Configuration object](#/docs). + */ + constructor(config: ServiceConfig, options?: ServiceOptions); + /** + * Return the user's custom request interceptors. + */ + getRequestInterceptors(): Function[]; + /** + * Get and update the Service's project ID. + * + * @param {function} callback - The callback function. + */ + getProjectId(): Promise; + getProjectId(callback: (err: Error | null, projectId?: string) => void): void; + protected getProjectIdAsync(): Promise; + /** + * Make an authenticated API request. + * + * @private + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + * @param {function} callback - The callback function passed to `request`. + */ + private request_; + /** + * Make an authenticated API request. + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + * @param {function} callback - The callback function passed to `request`. + */ + request(reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void; + /** + * Make an authenticated API request. + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + */ + requestStream(reqOpts: DecorateRequestOptions): r.Request; +} diff --git a/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/service.js b/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/service.js new file mode 100644 index 0000000..a50f605 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/service.js @@ -0,0 +1,219 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Service = exports.DEFAULT_PROJECT_ID_TOKEN = void 0; +/*! + * Copyright 2022 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. + */ +const google_auth_library_1 = require("google-auth-library"); +const uuid = __importStar(require("uuid")); +const util_js_1 = require("./util.js"); +const util_js_2 = require("../util.js"); +exports.DEFAULT_PROJECT_ID_TOKEN = '{{projectId}}'; +class Service { + /** + * Service is a base class, meant to be inherited from by a "service," like + * BigQuery or Storage. + * + * This handles making authenticated requests by exposing a `makeReq_` + * function. + * + * @constructor + * @alias module:common/service + * + * @param {object} config - Configuration object. + * @param {string} config.baseUrl - The base URL to make API requests to. + * @param {string[]} config.scopes - The scopes required for the request. + * @param {object=} options - [Configuration object](#/docs). + */ + constructor(config, options = {}) { + this.baseUrl = config.baseUrl; + this.apiEndpoint = config.apiEndpoint; + this.timeout = options.timeout; + this.globalInterceptors = Array.isArray(options.interceptors_) + ? options.interceptors_ + : []; + this.interceptors = []; + this.packageJson = config.packageJson; + this.projectId = options.projectId || exports.DEFAULT_PROJECT_ID_TOKEN; + this.projectIdRequired = config.projectIdRequired !== false; + this.providedUserAgent = options.userAgent; + this.universeDomain = options.universeDomain || google_auth_library_1.DEFAULT_UNIVERSE; + this.customEndpoint = config.customEndpoint || false; + this.useAuthWithCustomEndpoint = config.useAuthWithCustomEndpoint; + this.makeAuthenticatedRequest = util_js_1.util.makeAuthenticatedRequestFactory({ + ...config, + projectIdRequired: this.projectIdRequired, + projectId: this.projectId, + authClient: options.authClient || config.authClient, + credentials: options.credentials, + keyFile: options.keyFilename, + email: options.email, + clientOptions: { + universeDomain: options.universeDomain, + ...options.clientOptions, + }, + }); + this.authClient = this.makeAuthenticatedRequest.authClient; + const isCloudFunctionEnv = !!process.env.FUNCTION_NAME; + if (isCloudFunctionEnv) { + this.interceptors.push({ + request(reqOpts) { + reqOpts.forever = false; + return reqOpts; + }, + }); + } + } + /** + * Return the user's custom request interceptors. + */ + getRequestInterceptors() { + // Interceptors should be returned in the order they were assigned. + return [].slice + .call(this.globalInterceptors) + .concat(this.interceptors) + .filter(interceptor => typeof interceptor.request === 'function') + .map(interceptor => interceptor.request); + } + getProjectId(callback) { + if (!callback) { + return this.getProjectIdAsync(); + } + this.getProjectIdAsync().then(p => callback(null, p), callback); + } + async getProjectIdAsync() { + const projectId = await this.authClient.getProjectId(); + if (this.projectId === exports.DEFAULT_PROJECT_ID_TOKEN && projectId) { + this.projectId = projectId; + } + return this.projectId; + } + request_(reqOpts, callback) { + reqOpts = { ...reqOpts, timeout: this.timeout }; + const isAbsoluteUrl = reqOpts.uri.indexOf('http') === 0; + const uriComponents = [this.baseUrl]; + if (this.projectIdRequired) { + if (reqOpts.projectId) { + uriComponents.push('projects'); + uriComponents.push(reqOpts.projectId); + } + else { + uriComponents.push('projects'); + uriComponents.push(this.projectId); + } + } + uriComponents.push(reqOpts.uri); + if (isAbsoluteUrl) { + uriComponents.splice(0, uriComponents.indexOf(reqOpts.uri)); + } + reqOpts.uri = uriComponents + .map(uriComponent => { + const trimSlashesRegex = /^\/*|\/*$/g; + return uriComponent.replace(trimSlashesRegex, ''); + }) + .join('/') + // Some URIs have colon separators. + // Bad: https://.../projects/:list + // Good: https://.../projects:list + .replace(/\/:/g, ':'); + const requestInterceptors = this.getRequestInterceptors(); + const interceptorArray = Array.isArray(reqOpts.interceptors_) + ? reqOpts.interceptors_ + : []; + interceptorArray.forEach(interceptor => { + if (typeof interceptor.request === 'function') { + requestInterceptors.push(interceptor.request); + } + }); + requestInterceptors.forEach(requestInterceptor => { + reqOpts = requestInterceptor(reqOpts); + }); + delete reqOpts.interceptors_; + const pkg = this.packageJson; + let userAgent = (0, util_js_2.getUserAgentString)(); + if (this.providedUserAgent) { + userAgent = `${this.providedUserAgent} ${userAgent}`; + } + reqOpts.headers = { + ...reqOpts.headers, + 'User-Agent': userAgent, + 'x-goog-api-client': `${(0, util_js_2.getRuntimeTrackingString)()} gccl/${pkg.version}-${(0, util_js_2.getModuleFormat)()} gccl-invocation-id/${uuid.v4()}`, + }; + if (reqOpts[util_js_1.GCCL_GCS_CMD_KEY]) { + reqOpts.headers['x-goog-api-client'] += + ` gccl-gcs-cmd/${reqOpts[util_js_1.GCCL_GCS_CMD_KEY]}`; + } + if (reqOpts.shouldReturnStream) { + return this.makeAuthenticatedRequest(reqOpts); + } + else { + this.makeAuthenticatedRequest(reqOpts, callback); + } + } + /** + * Make an authenticated API request. + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + * @param {function} callback - The callback function passed to `request`. + */ + request(reqOpts, callback) { + Service.prototype.request_.call(this, reqOpts, callback); + } + /** + * Make an authenticated API request. + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + */ + requestStream(reqOpts) { + const opts = { ...reqOpts, shouldReturnStream: true }; + return Service.prototype.request_.call(this, opts); + } +} +exports.Service = Service; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/util.d.ts b/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/util.d.ts new file mode 100644 index 0000000..a4a4380 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/util.d.ts @@ -0,0 +1,333 @@ +/*! + * Copyright 2022 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. + */ +import { AuthClient, GoogleAuth, GoogleAuthOptions } from 'google-auth-library'; +import { CredentialBody } from 'google-auth-library'; +import * as r from 'teeny-request'; +import { Duplex, DuplexOptions, Readable, Writable } from 'stream'; +import { Interceptor } from './service-object.js'; +/** + * A unique symbol for providing a `gccl-gcs-cmd` value + * for the `X-Goog-API-Client` header. + * + * E.g. the `V` in `X-Goog-API-Client: gccl-gcs-cmd/V` + **/ +export declare const GCCL_GCS_CMD_KEY: unique symbol; +export type ResponseBody = any; +export interface DuplexifyOptions extends DuplexOptions { + autoDestroy?: boolean; + end?: boolean; +} +export interface Duplexify extends Duplex { + readonly destroyed: boolean; + setWritable(writable: Writable | false | null): void; + setReadable(readable: Readable | false | null): void; +} +export interface DuplexifyConstructor { + obj(writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify; + new (writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify; + (writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify; +} +export interface ParsedHttpRespMessage { + resp: r.Response; + err?: ApiError; +} +export interface MakeAuthenticatedRequest { + (reqOpts: DecorateRequestOptions): Duplexify; + (reqOpts: DecorateRequestOptions, options?: MakeAuthenticatedRequestOptions): void | Abortable; + (reqOpts: DecorateRequestOptions, callback?: BodyResponseCallback): void | Abortable; + (reqOpts: DecorateRequestOptions, optionsOrCallback?: MakeAuthenticatedRequestOptions | BodyResponseCallback): void | Abortable | Duplexify; + getCredentials: (callback: (err?: Error | null, credentials?: CredentialBody) => void) => void; + authClient: GoogleAuth; +} +export interface Abortable { + abort(): void; +} +export type AbortableDuplex = Duplexify & Abortable; +export interface PackageJson { + name: string; + version: string; +} +export interface MakeAuthenticatedRequestFactoryConfig extends Omit { + /** + * Automatically retry requests if the response is related to rate limits or + * certain intermittent server errors. We will exponentially backoff + * subsequent requests by default. (default: true) + */ + autoRetry?: boolean; + /** + * If true, just return the provided request options. Default: false. + */ + customEndpoint?: boolean; + /** + * If true, will authenticate when using a custom endpoint. Default: false. + */ + useAuthWithCustomEndpoint?: boolean; + /** + * Account email address, required for PEM/P12 usage. + */ + email?: string; + /** + * Maximum number of automatic retries attempted before returning the error. + * (default: 3) + */ + maxRetries?: number; + stream?: Duplexify; + /** + * A pre-instantiated `AuthClient` or `GoogleAuth` client that should be used. + * A new client will be created if this is not set. + */ + authClient?: AuthClient | GoogleAuth; + /** + * Determines if a projectId is required for authenticated requests. Defaults to `true`. + */ + projectIdRequired?: boolean; +} +export interface MakeAuthenticatedRequestOptions { + onAuthenticated: OnAuthenticatedCallback; +} +export interface OnAuthenticatedCallback { + (err: Error | null, reqOpts?: DecorateRequestOptions): void; +} +export interface GoogleErrorBody { + code: number; + errors?: GoogleInnerError[]; + response: r.Response; + message?: string; +} +export interface GoogleInnerError { + reason?: string; + message?: string; +} +export interface MakeWritableStreamOptions { + /** + * A connection instance used to get a token with and send the request + * through. + */ + connection?: {}; + /** + * Metadata to send at the head of the request. + */ + metadata?: { + contentType?: string; + }; + /** + * Request object, in the format of a standard Node.js http.request() object. + */ + request?: r.Options; + makeAuthenticatedRequest(reqOpts: r.OptionsWithUri & { + [GCCL_GCS_CMD_KEY]?: string; + }, fnobj: { + onAuthenticated(err: Error | null, authenticatedReqOpts?: r.Options): void; + }): void; +} +export interface DecorateRequestOptions extends r.CoreOptions { + autoPaginate?: boolean; + autoPaginateVal?: boolean; + objectMode?: boolean; + maxRetries?: number; + uri: string; + interceptors_?: Interceptor[]; + shouldReturnStream?: boolean; + projectId?: string; + [GCCL_GCS_CMD_KEY]?: string; +} +export interface ParsedHttpResponseBody { + body: ResponseBody; + err?: Error; +} +/** + * Custom error type for API errors. + * + * @param {object} errorBody - Error object. + */ +export declare class ApiError extends Error { + code?: number; + errors?: GoogleInnerError[]; + response?: r.Response; + constructor(errorMessage: string); + constructor(errorBody: GoogleErrorBody); + /** + * Pieces together an error message by combining all unique error messages + * returned from a single GoogleError + * + * @private + * + * @param {GoogleErrorBody} err The original error. + * @param {GoogleInnerError[]} [errors] Inner errors, if any. + * @returns {string} + */ + static createMultiErrorMessage(err: GoogleErrorBody, errors?: GoogleInnerError[]): string; +} +/** + * Custom error type for partial errors returned from the API. + * + * @param {object} b - Error object. + */ +export declare class PartialFailureError extends Error { + errors?: GoogleInnerError[]; + response?: r.Response; + constructor(b: GoogleErrorBody); +} +export interface BodyResponseCallback { + (err: Error | ApiError | null, body?: ResponseBody, res?: r.Response): void; +} +export interface RetryOptions { + retryDelayMultiplier?: number; + totalTimeout?: number; + maxRetryDelay?: number; + autoRetry?: boolean; + maxRetries?: number; + retryableErrorFn?: (err: ApiError) => boolean; +} +export interface MakeRequestConfig { + /** + * Automatically retry requests if the response is related to rate limits or + * certain intermittent server errors. We will exponentially backoff + * subsequent requests by default. (default: true) + */ + autoRetry?: boolean; + /** + * Maximum number of automatic retries attempted before returning the error. + * (default: 3) + */ + maxRetries?: number; + retries?: number; + retryOptions?: RetryOptions; + stream?: Duplexify; + shouldRetryFn?: (response?: r.Response) => boolean; +} +export declare class Util { + ApiError: typeof ApiError; + PartialFailureError: typeof PartialFailureError; + /** + * No op. + * + * @example + * function doSomething(callback) { + * callback = callback || noop; + * } + */ + noop(): void; + /** + * Uniformly process an API response. + * + * @param {*} err - Error value. + * @param {*} resp - Response value. + * @param {*} body - Body value. + * @param {function} callback - The callback function. + */ + handleResp(err: Error | null, resp?: r.Response | null, body?: ResponseBody, callback?: BodyResponseCallback): void; + /** + * Sniff an incoming HTTP response message for errors. + * + * @param {object} httpRespMessage - An incoming HTTP response message from `request`. + * @return {object} parsedHttpRespMessage - The parsed response. + * @param {?error} parsedHttpRespMessage.err - An error detected. + * @param {object} parsedHttpRespMessage.resp - The original response object. + */ + parseHttpRespMessage(httpRespMessage: r.Response): ParsedHttpRespMessage; + /** + * Parse the response body from an HTTP request. + * + * @param {object} body - The response body. + * @return {object} parsedHttpRespMessage - The parsed response. + * @param {?error} parsedHttpRespMessage.err - An error detected. + * @param {object} parsedHttpRespMessage.body - The original body value provided + * will try to be JSON.parse'd. If it's successful, the parsed value will + * be returned here, otherwise the original value and an error will be returned. + */ + parseHttpRespBody(body: ResponseBody): ParsedHttpResponseBody; + /** + * Take a Duplexify stream, fetch an authenticated connection header, and + * create an outgoing writable stream. + * + * @param {Duplexify} dup - Duplexify stream. + * @param {object} options - Configuration object. + * @param {module:common/connection} options.connection - A connection instance used to get a token with and send the request through. + * @param {object} options.metadata - Metadata to send at the head of the request. + * @param {object} options.request - Request object, in the format of a standard Node.js http.request() object. + * @param {string=} options.request.method - Default: "POST". + * @param {string=} options.request.qs.uploadType - Default: "multipart". + * @param {string=} options.streamContentType - Default: "application/octet-stream". + * @param {function} onComplete - Callback, executed after the writable Request stream has completed. + */ + makeWritableStream(dup: Duplexify, options: MakeWritableStreamOptions, onComplete?: Function): void; + /** + * Returns true if the API request should be retried, given the error that was + * given the first time the request was attempted. This is used for rate limit + * related errors as well as intermittent server errors. + * + * @param {error} err - The API error to check if it is appropriate to retry. + * @return {boolean} True if the API request should be retried, false otherwise. + */ + shouldRetryRequest(err?: ApiError): boolean; + /** + * Get a function for making authenticated requests. + * + * @param {object} config - Configuration object. + * @param {boolean=} config.autoRetry - Automatically retry requests if the + * response is related to rate limits or certain intermittent server + * errors. We will exponentially backoff subsequent requests by default. + * (default: true) + * @param {object=} config.credentials - Credentials object. + * @param {boolean=} config.customEndpoint - If true, just return the provided request options. Default: false. + * @param {boolean=} config.useAuthWithCustomEndpoint - If true, will authenticate when using a custom endpoint. Default: false. + * @param {string=} config.email - Account email address, required for PEM/P12 usage. + * @param {number=} config.maxRetries - Maximum number of automatic retries attempted before returning the error. (default: 3) + * @param {string=} config.keyFile - Path to a .json, .pem, or .p12 keyfile. + * @param {array} config.scopes - Array of scopes required for the API. + */ + makeAuthenticatedRequestFactory(config: MakeAuthenticatedRequestFactoryConfig): MakeAuthenticatedRequest; + /** + * Make a request through the `retryRequest` module with built-in error + * handling and exponential back off. + * + * @param {object} reqOpts - Request options in the format `request` expects. + * @param {object=} config - Configuration object. + * @param {boolean=} config.autoRetry - Automatically retry requests if the + * response is related to rate limits or certain intermittent server + * errors. We will exponentially backoff subsequent requests by default. + * (default: true) + * @param {number=} config.maxRetries - Maximum number of automatic retries + * attempted before returning the error. (default: 3) + * @param {object=} config.request - HTTP module for request calls. + * @param {function} callback - The callback function. + */ + makeRequest(reqOpts: DecorateRequestOptions, config: MakeRequestConfig, callback: BodyResponseCallback): void | Abortable; + /** + * Decorate the options about to be made in a request. + * + * @param {object} reqOpts - The options to be passed to `request`. + * @param {string} projectId - The project ID. + * @return {object} reqOpts - The decorated reqOpts. + */ + decorateRequest(reqOpts: DecorateRequestOptions, projectId: string): DecorateRequestOptions; + isCustomType(unknown: any, module: string): boolean; + /** + * Given two parameters, figure out if this is either: + * - Just a callback function + * - An options object, and then a callback function + * @param optionsOrCallback An options object or callback. + * @param cb A potentially undefined callback. + */ + maybeOptionsOrCallback void>(optionsOrCallback?: T | C, cb?: C): [T, C]; + _getDefaultHeaders(gcclGcsCmd?: string): { + 'User-Agent': string; + 'x-goog-api-client': string; + }; +} +declare const util: Util; +export { util }; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/util.js b/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/util.js new file mode 100644 index 0000000..6b9047f --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/nodejs-common/util.js @@ -0,0 +1,711 @@ +"use strict"; +/*! + * Copyright 2022 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. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.util = exports.Util = exports.PartialFailureError = exports.ApiError = exports.GCCL_GCS_CMD_KEY = void 0; +/*! + * @module common/util + */ +const projectify_1 = require("@google-cloud/projectify"); +const htmlEntities = __importStar(require("html-entities")); +const google_auth_library_1 = require("google-auth-library"); +const retry_request_1 = __importDefault(require("retry-request")); +const stream_1 = require("stream"); +const teeny_request_1 = require("teeny-request"); +const uuid = __importStar(require("uuid")); +const service_js_1 = require("./service.js"); +const util_js_1 = require("../util.js"); +const duplexify_1 = __importDefault(require("duplexify")); +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore +const package_json_helper_cjs_1 = require("../package-json-helper.cjs"); +const packageJson = (0, package_json_helper_cjs_1.getPackageJSON)(); +/** + * A unique symbol for providing a `gccl-gcs-cmd` value + * for the `X-Goog-API-Client` header. + * + * E.g. the `V` in `X-Goog-API-Client: gccl-gcs-cmd/V` + **/ +exports.GCCL_GCS_CMD_KEY = Symbol.for('GCCL_GCS_CMD'); +const requestDefaults = { + timeout: 60000, + gzip: true, + forever: true, + pool: { + maxSockets: Infinity, + }, +}; +/** + * Default behavior: Automatically retry retriable server errors. + * + * @const {boolean} + * @private + */ +const AUTO_RETRY_DEFAULT = true; +/** + * Default behavior: Only attempt to retry retriable errors 3 times. + * + * @const {number} + * @private + */ +const MAX_RETRY_DEFAULT = 3; +/** + * Custom error type for API errors. + * + * @param {object} errorBody - Error object. + */ +class ApiError extends Error { + constructor(errorBodyOrMessage) { + super(); + if (typeof errorBodyOrMessage !== 'object') { + this.message = errorBodyOrMessage || ''; + return; + } + const errorBody = errorBodyOrMessage; + this.code = errorBody.code; + this.errors = errorBody.errors; + this.response = errorBody.response; + try { + this.errors = JSON.parse(this.response.body).error.errors; + } + catch (e) { + this.errors = errorBody.errors; + } + this.message = ApiError.createMultiErrorMessage(errorBody, this.errors); + Error.captureStackTrace(this); + } + /** + * Pieces together an error message by combining all unique error messages + * returned from a single GoogleError + * + * @private + * + * @param {GoogleErrorBody} err The original error. + * @param {GoogleInnerError[]} [errors] Inner errors, if any. + * @returns {string} + */ + static createMultiErrorMessage(err, errors) { + const messages = new Set(); + if (err.message) { + messages.add(err.message); + } + if (errors && errors.length) { + errors.forEach(({ message }) => messages.add(message)); + } + else if (err.response && err.response.body) { + messages.add(htmlEntities.decode(err.response.body.toString())); + } + else if (!err.message) { + messages.add('A failure occurred during this request.'); + } + let messageArr = Array.from(messages); + if (messageArr.length > 1) { + messageArr = messageArr.map((message, i) => ` ${i + 1}. ${message}`); + messageArr.unshift('Multiple errors occurred during the request. Please see the `errors` array for complete details.\n'); + messageArr.push('\n'); + } + return messageArr.join('\n'); + } +} +exports.ApiError = ApiError; +/** + * Custom error type for partial errors returned from the API. + * + * @param {object} b - Error object. + */ +class PartialFailureError extends Error { + constructor(b) { + super(); + const errorObject = b; + this.errors = errorObject.errors; + this.name = 'PartialFailureError'; + this.response = errorObject.response; + this.message = ApiError.createMultiErrorMessage(errorObject, this.errors); + } +} +exports.PartialFailureError = PartialFailureError; +class Util { + constructor() { + this.ApiError = ApiError; + this.PartialFailureError = PartialFailureError; + } + /** + * No op. + * + * @example + * function doSomething(callback) { + * callback = callback || noop; + * } + */ + noop() { } + /** + * Uniformly process an API response. + * + * @param {*} err - Error value. + * @param {*} resp - Response value. + * @param {*} body - Body value. + * @param {function} callback - The callback function. + */ + handleResp(err, resp, body, callback) { + callback = callback || util.noop; + const parsedResp = { + err: err || null, + ...(resp && util.parseHttpRespMessage(resp)), + ...(body && util.parseHttpRespBody(body)), + }; + // Assign the parsed body to resp.body, even if { json: false } was passed + // as a request option. + // We assume that nobody uses the previously unparsed value of resp.body. + if (!parsedResp.err && resp && typeof parsedResp.body === 'object') { + parsedResp.resp.body = parsedResp.body; + } + if (parsedResp.err && resp) { + parsedResp.err.response = resp; + } + callback(parsedResp.err, parsedResp.body, parsedResp.resp); + } + /** + * Sniff an incoming HTTP response message for errors. + * + * @param {object} httpRespMessage - An incoming HTTP response message from `request`. + * @return {object} parsedHttpRespMessage - The parsed response. + * @param {?error} parsedHttpRespMessage.err - An error detected. + * @param {object} parsedHttpRespMessage.resp - The original response object. + */ + parseHttpRespMessage(httpRespMessage) { + const parsedHttpRespMessage = { + resp: httpRespMessage, + }; + if (httpRespMessage.statusCode < 200 || httpRespMessage.statusCode > 299) { + // Unknown error. Format according to ApiError standard. + parsedHttpRespMessage.err = new ApiError({ + errors: new Array(), + code: httpRespMessage.statusCode, + message: httpRespMessage.statusMessage, + response: httpRespMessage, + }); + } + return parsedHttpRespMessage; + } + /** + * Parse the response body from an HTTP request. + * + * @param {object} body - The response body. + * @return {object} parsedHttpRespMessage - The parsed response. + * @param {?error} parsedHttpRespMessage.err - An error detected. + * @param {object} parsedHttpRespMessage.body - The original body value provided + * will try to be JSON.parse'd. If it's successful, the parsed value will + * be returned here, otherwise the original value and an error will be returned. + */ + parseHttpRespBody(body) { + const parsedHttpRespBody = { + body, + }; + if (typeof body === 'string') { + try { + parsedHttpRespBody.body = JSON.parse(body); + } + catch (err) { + parsedHttpRespBody.body = body; + } + } + if (parsedHttpRespBody.body && parsedHttpRespBody.body.error) { + // Error from JSON API. + parsedHttpRespBody.err = new ApiError(parsedHttpRespBody.body.error); + } + return parsedHttpRespBody; + } + /** + * Take a Duplexify stream, fetch an authenticated connection header, and + * create an outgoing writable stream. + * + * @param {Duplexify} dup - Duplexify stream. + * @param {object} options - Configuration object. + * @param {module:common/connection} options.connection - A connection instance used to get a token with and send the request through. + * @param {object} options.metadata - Metadata to send at the head of the request. + * @param {object} options.request - Request object, in the format of a standard Node.js http.request() object. + * @param {string=} options.request.method - Default: "POST". + * @param {string=} options.request.qs.uploadType - Default: "multipart". + * @param {string=} options.streamContentType - Default: "application/octet-stream". + * @param {function} onComplete - Callback, executed after the writable Request stream has completed. + */ + makeWritableStream(dup, options, onComplete) { + var _a; + onComplete = onComplete || util.noop; + const writeStream = new ProgressStream(); + writeStream.on('progress', evt => dup.emit('progress', evt)); + dup.setWritable(writeStream); + const defaultReqOpts = { + method: 'POST', + qs: { + uploadType: 'multipart', + }, + timeout: 0, + maxRetries: 0, + }; + const metadata = options.metadata || {}; + const reqOpts = { + ...defaultReqOpts, + ...options.request, + qs: { + ...defaultReqOpts.qs, + ...(_a = options.request) === null || _a === void 0 ? void 0 : _a.qs, + }, + multipart: [ + { + 'Content-Type': 'application/json', + body: JSON.stringify(metadata), + }, + { + 'Content-Type': metadata.contentType || 'application/octet-stream', + body: writeStream, + }, + ], + }; + options.makeAuthenticatedRequest(reqOpts, { + onAuthenticated(err, authenticatedReqOpts) { + if (err) { + dup.destroy(err); + return; + } + requestDefaults.headers = util._getDefaultHeaders(reqOpts[exports.GCCL_GCS_CMD_KEY]); + const request = teeny_request_1.teenyRequest.defaults(requestDefaults); + request(authenticatedReqOpts, (err, resp, body) => { + util.handleResp(err, resp, body, (err, data) => { + if (err) { + dup.destroy(err); + return; + } + dup.emit('response', resp); + onComplete(data); + }); + }); + }, + }); + } + /** + * Returns true if the API request should be retried, given the error that was + * given the first time the request was attempted. This is used for rate limit + * related errors as well as intermittent server errors. + * + * @param {error} err - The API error to check if it is appropriate to retry. + * @return {boolean} True if the API request should be retried, false otherwise. + */ + shouldRetryRequest(err) { + if (err) { + if ([408, 429, 500, 502, 503, 504].indexOf(err.code) !== -1) { + return true; + } + if (err.errors) { + for (const e of err.errors) { + const reason = e.reason; + if (reason === 'rateLimitExceeded') { + return true; + } + if (reason === 'userRateLimitExceeded') { + return true; + } + if (reason && reason.includes('EAI_AGAIN')) { + return true; + } + } + } + } + return false; + } + /** + * Get a function for making authenticated requests. + * + * @param {object} config - Configuration object. + * @param {boolean=} config.autoRetry - Automatically retry requests if the + * response is related to rate limits or certain intermittent server + * errors. We will exponentially backoff subsequent requests by default. + * (default: true) + * @param {object=} config.credentials - Credentials object. + * @param {boolean=} config.customEndpoint - If true, just return the provided request options. Default: false. + * @param {boolean=} config.useAuthWithCustomEndpoint - If true, will authenticate when using a custom endpoint. Default: false. + * @param {string=} config.email - Account email address, required for PEM/P12 usage. + * @param {number=} config.maxRetries - Maximum number of automatic retries attempted before returning the error. (default: 3) + * @param {string=} config.keyFile - Path to a .json, .pem, or .p12 keyfile. + * @param {array} config.scopes - Array of scopes required for the API. + */ + makeAuthenticatedRequestFactory(config) { + const googleAutoAuthConfig = { ...config }; + if (googleAutoAuthConfig.projectId === service_js_1.DEFAULT_PROJECT_ID_TOKEN) { + delete googleAutoAuthConfig.projectId; + } + let authClient; + if (googleAutoAuthConfig.authClient instanceof google_auth_library_1.GoogleAuth) { + // Use an existing `GoogleAuth` + authClient = googleAutoAuthConfig.authClient; + } + else { + // Pass an `AuthClient` & `clientOptions` to `GoogleAuth`, if available + authClient = new google_auth_library_1.GoogleAuth({ + ...googleAutoAuthConfig, + authClient: googleAutoAuthConfig.authClient, + clientOptions: googleAutoAuthConfig.clientOptions, + }); + } + function makeAuthenticatedRequest(reqOpts, optionsOrCallback) { + let stream; + let projectId; + const reqConfig = { ...config }; + let activeRequest_; + if (!optionsOrCallback) { + stream = (0, duplexify_1.default)(); + reqConfig.stream = stream; + } + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : undefined; + const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : undefined; + async function setProjectId() { + projectId = await authClient.getProjectId(); + } + const onAuthenticated = async (err, authenticatedReqOpts) => { + const authLibraryError = err; + const autoAuthFailed = err && + typeof err.message === 'string' && + err.message.indexOf('Could not load the default credentials') > -1; + if (autoAuthFailed) { + // Even though authentication failed, the API might not actually + // care. + authenticatedReqOpts = reqOpts; + } + if (!err || autoAuthFailed) { + try { + // Try with existing `projectId` value + authenticatedReqOpts = util.decorateRequest(authenticatedReqOpts, projectId); + err = null; + } + catch (e) { + if (e instanceof projectify_1.MissingProjectIdError) { + // A `projectId` was required, but we don't have one. + try { + // Attempt to get the `projectId` + await setProjectId(); + authenticatedReqOpts = util.decorateRequest(authenticatedReqOpts, projectId); + err = null; + } + catch (e) { + // Re-use the "Could not load the default credentials error" if + // auto auth failed. + err = err || e; + } + } + else { + // Some other error unrelated to missing `projectId` + err = err || e; + } + } + } + if (err) { + if (stream) { + stream.destroy(err); + } + else { + const fn = options && options.onAuthenticated + ? options.onAuthenticated + : callback; + fn(err); + } + return; + } + if (options && options.onAuthenticated) { + options.onAuthenticated(null, authenticatedReqOpts); + } + else { + activeRequest_ = util.makeRequest(authenticatedReqOpts, reqConfig, (apiResponseError, ...params) => { + if (apiResponseError && + apiResponseError.code === 401 && + authLibraryError) { + // Re-use the "Could not load the default credentials error" if + // the API request failed due to missing credentials. + apiResponseError = authLibraryError; + } + callback(apiResponseError, ...params); + }); + } + }; + const prepareRequest = async () => { + try { + const getProjectId = async () => { + if (config.projectId && + config.projectId !== service_js_1.DEFAULT_PROJECT_ID_TOKEN) { + // The user provided a project ID. We don't need to check with the + // auth client, it could be incorrect. + return config.projectId; + } + if (config.projectIdRequired === false) { + // A projectId is not required. Return the default. + return service_js_1.DEFAULT_PROJECT_ID_TOKEN; + } + return setProjectId(); + }; + const authorizeRequest = async () => { + if (reqConfig.customEndpoint && + !reqConfig.useAuthWithCustomEndpoint) { + // Using a custom API override. Do not use `google-auth-library` for + // authentication. (ex: connecting to a local Datastore server) + return reqOpts; + } + else { + return authClient.authorizeRequest(reqOpts); + } + }; + const [_projectId, authorizedReqOpts] = await Promise.all([ + getProjectId(), + authorizeRequest(), + ]); + if (_projectId) { + projectId = _projectId; + } + return onAuthenticated(null, authorizedReqOpts); + } + catch (e) { + return onAuthenticated(e); + } + }; + prepareRequest(); + if (stream) { + return stream; + } + return { + abort() { + setImmediate(() => { + if (activeRequest_) { + activeRequest_.abort(); + activeRequest_ = null; + } + }); + }, + }; + } + const mar = makeAuthenticatedRequest; + mar.getCredentials = authClient.getCredentials.bind(authClient); + mar.authClient = authClient; + return mar; + } + /** + * Make a request through the `retryRequest` module with built-in error + * handling and exponential back off. + * + * @param {object} reqOpts - Request options in the format `request` expects. + * @param {object=} config - Configuration object. + * @param {boolean=} config.autoRetry - Automatically retry requests if the + * response is related to rate limits or certain intermittent server + * errors. We will exponentially backoff subsequent requests by default. + * (default: true) + * @param {number=} config.maxRetries - Maximum number of automatic retries + * attempted before returning the error. (default: 3) + * @param {object=} config.request - HTTP module for request calls. + * @param {function} callback - The callback function. + */ + makeRequest(reqOpts, config, callback) { + var _a, _b, _c, _d, _e; + let autoRetryValue = AUTO_RETRY_DEFAULT; + if (config.autoRetry !== undefined) { + autoRetryValue = config.autoRetry; + } + else if (((_a = config.retryOptions) === null || _a === void 0 ? void 0 : _a.autoRetry) !== undefined) { + autoRetryValue = config.retryOptions.autoRetry; + } + let maxRetryValue = MAX_RETRY_DEFAULT; + if (config.maxRetries !== undefined) { + maxRetryValue = config.maxRetries; + } + else if (((_b = config.retryOptions) === null || _b === void 0 ? void 0 : _b.maxRetries) !== undefined) { + maxRetryValue = config.retryOptions.maxRetries; + } + requestDefaults.headers = this._getDefaultHeaders(reqOpts[exports.GCCL_GCS_CMD_KEY]); + const options = { + request: teeny_request_1.teenyRequest.defaults(requestDefaults), + retries: autoRetryValue !== false ? maxRetryValue : 0, + noResponseRetries: autoRetryValue !== false ? maxRetryValue : 0, + shouldRetryFn(httpRespMessage) { + var _a, _b; + const err = util.parseHttpRespMessage(httpRespMessage).err; + if ((_a = config.retryOptions) === null || _a === void 0 ? void 0 : _a.retryableErrorFn) { + return err && ((_b = config.retryOptions) === null || _b === void 0 ? void 0 : _b.retryableErrorFn(err)); + } + return err && util.shouldRetryRequest(err); + }, + maxRetryDelay: (_c = config.retryOptions) === null || _c === void 0 ? void 0 : _c.maxRetryDelay, + retryDelayMultiplier: (_d = config.retryOptions) === null || _d === void 0 ? void 0 : _d.retryDelayMultiplier, + totalTimeout: (_e = config.retryOptions) === null || _e === void 0 ? void 0 : _e.totalTimeout, + }; + if (typeof reqOpts.maxRetries === 'number') { + options.retries = reqOpts.maxRetries; + options.noResponseRetries = reqOpts.maxRetries; + } + if (!config.stream) { + return (0, retry_request_1.default)(reqOpts, options, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (err, response, body) => { + util.handleResp(err, response, body, callback); + }); + } + const dup = config.stream; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let requestStream; + const isGetRequest = (reqOpts.method || 'GET').toUpperCase() === 'GET'; + if (isGetRequest) { + requestStream = (0, retry_request_1.default)(reqOpts, options); + dup.setReadable(requestStream); + } + else { + // Streaming writable HTTP requests cannot be retried. + requestStream = options.request(reqOpts); + dup.setWritable(requestStream); + } + // Replay the Request events back to the stream. + requestStream + .on('error', dup.destroy.bind(dup)) + .on('response', dup.emit.bind(dup, 'response')) + .on('complete', dup.emit.bind(dup, 'complete')); + dup.abort = requestStream.abort; + return dup; + } + /** + * Decorate the options about to be made in a request. + * + * @param {object} reqOpts - The options to be passed to `request`. + * @param {string} projectId - The project ID. + * @return {object} reqOpts - The decorated reqOpts. + */ + decorateRequest(reqOpts, projectId) { + delete reqOpts.autoPaginate; + delete reqOpts.autoPaginateVal; + delete reqOpts.objectMode; + if (reqOpts.qs !== null && typeof reqOpts.qs === 'object') { + delete reqOpts.qs.autoPaginate; + delete reqOpts.qs.autoPaginateVal; + reqOpts.qs = (0, projectify_1.replaceProjectIdToken)(reqOpts.qs, projectId); + } + if (Array.isArray(reqOpts.multipart)) { + reqOpts.multipart = reqOpts.multipart.map(part => { + return (0, projectify_1.replaceProjectIdToken)(part, projectId); + }); + } + if (reqOpts.json !== null && typeof reqOpts.json === 'object') { + delete reqOpts.json.autoPaginate; + delete reqOpts.json.autoPaginateVal; + reqOpts.json = (0, projectify_1.replaceProjectIdToken)(reqOpts.json, projectId); + } + reqOpts.uri = (0, projectify_1.replaceProjectIdToken)(reqOpts.uri, projectId); + return reqOpts; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + isCustomType(unknown, module) { + function getConstructorName(obj) { + return obj.constructor && obj.constructor.name.toLowerCase(); + } + const moduleNameParts = module.split('/'); + const parentModuleName = moduleNameParts[0] && moduleNameParts[0].toLowerCase(); + const subModuleName = moduleNameParts[1] && moduleNameParts[1].toLowerCase(); + if (subModuleName && getConstructorName(unknown) !== subModuleName) { + return false; + } + let walkingModule = unknown; + // eslint-disable-next-line no-constant-condition + while (true) { + if (getConstructorName(walkingModule) === parentModuleName) { + return true; + } + walkingModule = walkingModule.parent; + if (!walkingModule) { + return false; + } + } + } + /** + * Given two parameters, figure out if this is either: + * - Just a callback function + * - An options object, and then a callback function + * @param optionsOrCallback An options object or callback. + * @param cb A potentially undefined callback. + */ + maybeOptionsOrCallback(optionsOrCallback, cb) { + return typeof optionsOrCallback === 'function' + ? [{}, optionsOrCallback] + : [optionsOrCallback, cb]; + } + _getDefaultHeaders(gcclGcsCmd) { + const headers = { + 'User-Agent': (0, util_js_1.getUserAgentString)(), + 'x-goog-api-client': `${(0, util_js_1.getRuntimeTrackingString)()} gccl/${packageJson.version}-${(0, util_js_1.getModuleFormat)()} gccl-invocation-id/${uuid.v4()}`, + }; + if (gcclGcsCmd) { + headers['x-goog-api-client'] += ` gccl-gcs-cmd/${gcclGcsCmd}`; + } + return headers; + } +} +exports.Util = Util; +/** + * Basic Passthrough Stream that records the number of bytes read + * every time the cursor is moved. + */ +class ProgressStream extends stream_1.Transform { + constructor() { + super(...arguments); + this.bytesRead = 0; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _transform(chunk, encoding, callback) { + this.bytesRead += chunk.length; + this.emit('progress', { bytesWritten: this.bytesRead, contentLength: '*' }); + this.push(chunk); + callback(); + } +} +const util = new Util(); +exports.util = util; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/notification.d.ts b/node_modules/@google-cloud/storage/build/cjs/src/notification.d.ts new file mode 100644 index 0000000..0d3341a --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/notification.d.ts @@ -0,0 +1,106 @@ +import { BaseMetadata, ServiceObject } from './nodejs-common/index.js'; +import { ResponseBody } from './nodejs-common/util.js'; +import { Bucket } from './bucket.js'; +export interface DeleteNotificationOptions { + userProject?: string; +} +export interface GetNotificationMetadataOptions { + userProject?: string; +} +/** + * @typedef {array} GetNotificationMetadataResponse + * @property {object} 0 The notification metadata. + * @property {object} 1 The full API response. + */ +export type GetNotificationMetadataResponse = [ResponseBody, unknown]; +/** + * @callback GetNotificationMetadataCallback + * @param {?Error} err Request error, if any. + * @param {object} files The notification metadata. + * @param {object} apiResponse The full API response. + */ +export interface GetNotificationMetadataCallback { + (err: Error | null, metadata?: ResponseBody, apiResponse?: unknown): void; +} +/** + * @typedef {array} GetNotificationResponse + * @property {Notification} 0 The {@link Notification} + * @property {object} 1 The full API response. + */ +export type GetNotificationResponse = [Notification, unknown]; +export interface GetNotificationOptions { + /** + * Automatically create the object if it does not exist. Default: `false`. + */ + autoCreate?: boolean; + /** + * The ID of the project which will be billed for the request. + */ + userProject?: string; +} +/** + * @callback GetNotificationCallback + * @param {?Error} err Request error, if any. + * @param {Notification} notification The {@link Notification}. + * @param {object} apiResponse The full API response. + */ +export interface GetNotificationCallback { + (err: Error | null, notification?: Notification | null, apiResponse?: unknown): void; +} +/** + * @callback DeleteNotificationCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ +export interface DeleteNotificationCallback { + (err: Error | null, apiResponse?: unknown): void; +} +export interface NotificationMetadata extends BaseMetadata { + custom_attributes?: { + [key: string]: string; + }; + event_types?: string[]; + object_name_prefix?: string; + payload_format?: 'JSON_API_V1' | 'NONE'; + topic?: string; +} +/** + * The API-formatted resource description of the notification. + * + * Note: This is not guaranteed to be up-to-date when accessed. To get the + * latest record, call the `getMetadata()` method. + * + * @name Notification#metadata + * @type {object} + */ +/** + * A Notification object is created from your {@link Bucket} object using + * {@link Bucket#notification}. Use it to interact with Cloud Pub/Sub + * notifications. + * + * See {@link https://cloud.google.com/storage/docs/pubsub-notifications| Cloud Pub/Sub Notifications for Google Cloud Storage} + * + * @class + * @hideconstructor + * + * @param {Bucket} bucket The bucket instance this notification is attached to. + * @param {string} id The ID of the notification. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const notification = myBucket.notification('1'); + * ``` + */ +declare class Notification extends ServiceObject { + constructor(bucket: Bucket, id: string); +} +/** + * Reference to the {@link Notification} class. + * @name module:@google-cloud/storage.Notification + * @see Notification + */ +export { Notification }; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/notification.js b/node_modules/@google-cloud/storage/build/cjs/src/notification.js new file mode 100644 index 0000000..6bf57a3 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/notification.js @@ -0,0 +1,265 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Notification = void 0; +const index_js_1 = require("./nodejs-common/index.js"); +const promisify_1 = require("@google-cloud/promisify"); +/** + * The API-formatted resource description of the notification. + * + * Note: This is not guaranteed to be up-to-date when accessed. To get the + * latest record, call the `getMetadata()` method. + * + * @name Notification#metadata + * @type {object} + */ +/** + * A Notification object is created from your {@link Bucket} object using + * {@link Bucket#notification}. Use it to interact with Cloud Pub/Sub + * notifications. + * + * See {@link https://cloud.google.com/storage/docs/pubsub-notifications| Cloud Pub/Sub Notifications for Google Cloud Storage} + * + * @class + * @hideconstructor + * + * @param {Bucket} bucket The bucket instance this notification is attached to. + * @param {string} id The ID of the notification. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const notification = myBucket.notification('1'); + * ``` + */ +class Notification extends index_js_1.ServiceObject { + constructor(bucket, id) { + const requestQueryObject = {}; + const methods = { + /** + * Creates a notification subscription for the bucket. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/insert| Notifications: insert} + * @method Notification#create + * + * @param {Topic|string} topic The Cloud PubSub topic to which this + * subscription publishes. If the project ID is omitted, the current + * project ID will be used. + * + * Acceptable formats are: + * - `projects/grape-spaceship-123/topics/my-topic` + * + * - `my-topic` + * @param {CreateNotificationRequest} [options] Metadata to set for + * the notification. + * @param {CreateNotificationCallback} [callback] Callback function. + * @returns {Promise} + * @throws {Error} If a valid topic is not provided. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * const notification = myBucket.notification('1'); + * + * notification.create(function(err, notification, apiResponse) { + * if (!err) { + * // The notification was created successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * notification.create().then(function(data) { + * const notification = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + create: true, + /** + * @typedef {array} DeleteNotificationResponse + * @property {object} 0 The full API response. + */ + /** + * Permanently deletes a notification subscription. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/delete| Notifications: delete API Documentation} + * + * @param {object} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {DeleteNotificationCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * const notification = myBucket.notification('1'); + * + * notification.delete(function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * notification.delete().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example include:samples/deleteNotification.js + * region_tag:storage_delete_bucket_notification + * Another example: + */ + delete: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * Get a notification and its metadata if it exists. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/get| Notifications: get API Documentation} + * + * @param {object} [options] Configuration options. + * See {@link Bucket#createNotification} for create options. + * @param {boolean} [options.autoCreate] Automatically create the object if + * it does not exist. Default: `false`. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetNotificationCallback} [callback] Callback function. + * @return {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * const notification = myBucket.notification('1'); + * + * notification.get(function(err, notification, apiResponse) { + * // `notification.metadata` has been populated. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * notification.get().then(function(data) { + * const notification = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + get: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * Get the notification's metadata. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/get| Notifications: get API Documentation} + * + * @param {object} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetNotificationMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * const notification = myBucket.notification('1'); + * + * notification.getMetadata(function(err, metadata, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * notification.getMetadata().then(function(data) { + * const metadata = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/getMetadataNotifications.js + * region_tag:storage_print_pubsub_bucket_notification + * Another example: + */ + getMetadata: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {array} NotificationExistsResponse + * @property {boolean} 0 Whether the notification exists or not. + */ + /** + * @callback NotificationExistsCallback + * @param {?Error} err Request error, if any. + * @param {boolean} exists Whether the notification exists or not. + */ + /** + * Check if the notification exists. + * + * @method Notification#exists + * @param {NotificationExistsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * const notification = myBucket.notification('1'); + * + * notification.exists(function(err, exists) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * notification.exists().then(function(data) { + * const exists = data[0]; + * }); + * ``` + */ + exists: true, + }; + super({ + parent: bucket, + baseUrl: '/notificationConfigs', + id: id.toString(), + createMethod: bucket.createNotification.bind(bucket), + methods, + }); + } +} +exports.Notification = Notification; +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +(0, promisify_1.promisifyAll)(Notification); diff --git a/node_modules/@google-cloud/storage/build/cjs/src/package-json-helper.cjs b/node_modules/@google-cloud/storage/build/cjs/src/package-json-helper.cjs new file mode 100644 index 0000000..794923b --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/package-json-helper.cjs @@ -0,0 +1,21 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/* eslint-disable node/no-missing-require */ + +function getPackageJSON() { + return require('../../../package.json'); +} + +exports.getPackageJSON = getPackageJSON; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/resumable-upload.d.ts b/node_modules/@google-cloud/storage/build/cjs/src/resumable-upload.d.ts new file mode 100644 index 0000000..751e917 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/resumable-upload.d.ts @@ -0,0 +1,341 @@ +import { GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +import { GoogleAuthOptions } from 'google-auth-library'; +import { Writable, WritableOptions } from 'stream'; +import { RetryOptions, PreconditionOptions } from './storage.js'; +import { GCCL_GCS_CMD_KEY } from './nodejs-common/util.js'; +import { FileMetadata } from './file.js'; +export declare const PROTOCOL_REGEX: RegExp; +export interface ErrorWithCode extends Error { + code: number; + status?: number | string; +} +export type CreateUriCallback = (err: Error | null, uri?: string) => void; +export interface Encryption { + key: {}; + hash: {}; +} +export type PredefinedAcl = 'authenticatedRead' | 'bucketOwnerFullControl' | 'bucketOwnerRead' | 'private' | 'projectPrivate' | 'publicRead'; +export interface QueryParameters extends PreconditionOptions { + contentEncoding?: string; + kmsKeyName?: string; + predefinedAcl?: PredefinedAcl; + projection?: 'full' | 'noAcl'; + userProject?: string; +} +export interface UploadConfig extends Pick { + /** + * The API endpoint used for the request. + * Defaults to `storage.googleapis.com`. + * + * **Warning**: + * If this value does not match the current GCP universe an emulator context + * will be assumed and authentication will be bypassed. + */ + apiEndpoint?: string; + /** + * The name of the destination bucket. + */ + bucket: string; + /** + * The name of the destination file. + */ + file: string; + /** + * The GoogleAuthOptions passed to google-auth-library + */ + authConfig?: GoogleAuthOptions; + /** + * If you want to re-use an auth client from google-auto-auth, pass an + * instance here. + * Defaults to GoogleAuth and gets automatically overridden if an + * emulator context is detected. + */ + authClient?: { + request: (opts: GaxiosOptions) => Promise> | GaxiosPromise; + }; + /** + * Create a separate request per chunk. + * + * This value is in bytes and should be a multiple of 256 KiB (2^18). + * We recommend using at least 8 MiB for the chunk size. + * + * @link https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload + */ + chunkSize?: number; + /** + * For each API request we send, you may specify custom request options that + * we'll add onto the request. The request options follow the gaxios API: + * https://github.com/googleapis/gaxios#request-options. + */ + customRequestOptions?: GaxiosOptions; + /** + * This will cause the upload to fail if the current generation of the remote + * object does not match the one provided here. + */ + generation?: number; + /** + * Set to `true` if the upload is only a subset of the overall object to upload. + * This can be used when planning to continue the upload an object in another + * session. + * + * **Must be used with {@link UploadConfig.chunkSize} != `0`**. + * + * If this is a continuation of a previous upload, {@link UploadConfig.offset} + * should be set. + * + * @see {@link checkUploadStatus} for checking the status of an existing upload. + */ + isPartialUpload?: boolean; + /** + * A customer-supplied encryption key. See + * https://cloud.google.com/storage/docs/encryption#customer-supplied. + */ + key?: string | Buffer; + /** + * Resource name of the Cloud KMS key, of the form + * `projects/my-project/locations/global/keyRings/my-kr/cryptoKeys/my-key`, + * that will be used to encrypt the object. Overrides the object metadata's + * `kms_key_name` value, if any. + */ + kmsKeyName?: string; + /** + * Any metadata you wish to set on the object. + */ + metadata?: ConfigMetadata; + /** + * The starting byte in relation to the final uploaded object. + * **Must be used with {@link UploadConfig.uri}**. + * + * If resuming an interrupted stream, do not supply this argument unless you + * know the exact number of bytes the service has AND the provided stream's + * first byte is a continuation from that provided offset. If resuming an + * interrupted stream and this option has not been provided, we will treat + * the provided upload stream as the object to upload - where the first byte + * of the upload stream is the first byte of the object to upload; skipping + * any bytes that are already present on the server. + * + * @see {@link checkUploadStatus} for checking the status of an existing upload. + * @see {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload#resume-upload.} + */ + offset?: number; + /** + * Set an Origin header when creating the resumable upload URI. + */ + origin?: string; + /** + * Specify query parameters that go along with the initial upload request. See + * https://cloud.google.com/storage/docs/json_api/v1/objects/insert#parameters + */ + params?: QueryParameters; + /** + * Apply a predefined set of access controls to the created file. + */ + predefinedAcl?: PredefinedAcl; + /** + * Make the uploaded file private. (Alias for config.predefinedAcl = + * 'private') + */ + private?: boolean; + /** + * Make the uploaded file public. (Alias for config.predefinedAcl = + * 'publicRead') + */ + public?: boolean; + /** + * The service domain for a given Cloud universe. + */ + universeDomain?: string; + /** + * If you already have a resumable URI from a previously-created resumable + * upload, just pass it in here and we'll use that. + * + * If resuming an interrupted stream and the {@link UploadConfig.offset} + * option has not been provided, we will treat the provided upload stream as + * the object to upload - where the first byte of the upload stream is the + * first byte of the object to upload; skipping any bytes that are already + * present on the server. + * + * @see {@link checkUploadStatus} for checking the status of an existing upload. + */ + uri?: string; + /** + * If the bucket being accessed has requesterPays functionality enabled, this + * can be set to control which project is billed for the access of this file. + */ + userProject?: string; + /** + * Configuration options for retrying retryable errors. + */ + retryOptions: RetryOptions; + /** + * Controls whether or not to use authentication when using a custom endpoint. + */ + useAuthWithCustomEndpoint?: boolean; + [GCCL_GCS_CMD_KEY]?: string; +} +export interface ConfigMetadata { + [key: string]: any; + /** + * Set the length of the object being uploaded. If uploading a partial + * object, this is the overall size of the finalized object. + */ + contentLength?: number; + /** + * Set the content type of the incoming data. + */ + contentType?: string; +} +export interface GoogleInnerError { + reason?: string; +} +export interface ApiError extends Error { + code?: number; + errors?: GoogleInnerError[]; +} +export interface CheckUploadStatusConfig { + /** + * Set to `false` to disable retries within this method. + * + * @defaultValue `true` + */ + retry?: boolean; +} +export declare class Upload extends Writable { + #private; + bucket: string; + file: string; + apiEndpoint: string; + baseURI: string; + authConfig?: { + scopes?: string[]; + }; + authClient: { + request: (opts: GaxiosOptions) => Promise> | GaxiosPromise; + }; + cacheKey: string; + chunkSize?: number; + customRequestOptions: GaxiosOptions; + generation?: number; + key?: string | Buffer; + kmsKeyName?: string; + metadata: ConfigMetadata; + offset?: number; + origin?: string; + params: QueryParameters; + predefinedAcl?: PredefinedAcl; + private?: boolean; + public?: boolean; + uri?: string; + userProject?: string; + encryption?: Encryption; + uriProvidedManually: boolean; + numBytesWritten: number; + numRetries: number; + contentLength: number | '*'; + retryOptions: RetryOptions; + timeOfFirstRequest: number; + isPartialUpload: boolean; + private currentInvocationId; + /** + * A cache of buffers written to this instance, ready for consuming + */ + private writeBuffers; + private numChunksReadInRequest; + /** + * An array of buffers used for caching the most recent upload chunk. + * We should not assume that the server received all bytes sent in the request. + * - https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload + */ + private localWriteCache; + private localWriteCacheByteLength; + private upstreamEnded; + constructor(cfg: UploadConfig); + /** + * Prevent 'finish' event until the upload has succeeded. + * + * @param fireFinishEvent The finish callback + */ + _final(fireFinishEvent?: () => void): void; + /** + * Handles incoming data from upstream + * + * @param chunk The chunk to append to the buffer + * @param encoding The encoding of the chunk + * @param readCallback A callback for when the buffer has been read downstream + */ + _write(chunk: Buffer | string, encoding: BufferEncoding, readCallback?: () => void): void; + /** + * Prepends the local buffer to write buffer and resets it. + * + * @param keepLastBytes number of bytes to keep from the end of the local buffer. + */ + private prependLocalBufferToUpstream; + /** + * Retrieves data from upstream's buffer. + * + * @param limit The maximum amount to return from the buffer. + */ + private pullFromChunkBuffer; + /** + * A handler for determining if data is ready to be read from upstream. + * + * @returns If there will be more chunks to read in the future + */ + private waitForNextChunk; + /** + * Reads data from upstream up to the provided `limit`. + * Ends when the limit has reached or no data is expected to be pushed from upstream. + * + * @param limit The most amount of data this iterator should return. `Infinity` by default. + */ + private upstreamIterator; + createURI(): Promise; + createURI(callback: CreateUriCallback): void; + protected createURIAsync(): Promise; + private continueUploading; + startUploading(): Promise; + private responseHandler; + /** + * Check the status of an existing resumable upload. + * + * @param cfg A configuration to use. `uri` is required. + * @returns the current upload status + */ + checkUploadStatus(config?: CheckUploadStatusConfig): Promise>; + private getAndSetOffset; + private makeRequest; + private makeRequestStream; + /** + * @return {bool} is the request good? + */ + private onResponse; + /** + * @param resp GaxiosResponse object from previous attempt + */ + private attemptDelayedRetry; + /** + * The amount of time to wait before retrying the request, in milliseconds. + * If negative, do not retry. + * + * @returns the amount of time to wait, in milliseconds. + */ + private getRetryDelay; + private sanitizeEndpoint; + /** + * Check if a given status code is 2xx + * + * @param status The status code to check + * @returns if the status is 2xx + */ + isSuccessfulResponse(status: number): boolean; +} +export declare function upload(cfg: UploadConfig): Upload; +export declare function createURI(cfg: UploadConfig): Promise; +export declare function createURI(cfg: UploadConfig, callback: CreateUriCallback): void; +/** + * Check the status of an existing resumable upload. + * + * @param cfg A configuration to use. `uri` is required. + * @returns the current upload status + */ +export declare function checkUploadStatus(cfg: UploadConfig & Required>): Promise>; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/resumable-upload.js b/node_modules/@google-cloud/storage/build/cjs/src/resumable-upload.js new file mode 100644 index 0000000..7cd4298 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/resumable-upload.js @@ -0,0 +1,909 @@ +"use strict"; +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +var _Upload_instances, _Upload_gcclGcsCmd, _Upload_resetLocalBuffersCache, _Upload_addLocalBufferCache; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Upload = exports.PROTOCOL_REGEX = void 0; +exports.upload = upload; +exports.createURI = createURI; +exports.checkUploadStatus = checkUploadStatus; +const abort_controller_1 = __importDefault(require("abort-controller")); +const crypto_1 = require("crypto"); +const gaxios = __importStar(require("gaxios")); +const google_auth_library_1 = require("google-auth-library"); +const stream_1 = require("stream"); +const async_retry_1 = __importDefault(require("async-retry")); +const uuid = __importStar(require("uuid")); +const util_js_1 = require("./util.js"); +const util_js_2 = require("./nodejs-common/util.js"); +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore +const package_json_helper_cjs_1 = require("./package-json-helper.cjs"); +const NOT_FOUND_STATUS_CODE = 404; +const RESUMABLE_INCOMPLETE_STATUS_CODE = 308; +const packageJson = (0, package_json_helper_cjs_1.getPackageJSON)(); +exports.PROTOCOL_REGEX = /^(\w*):\/\//; +class Upload extends stream_1.Writable { + constructor(cfg) { + var _a; + super(cfg); + _Upload_instances.add(this); + this.numBytesWritten = 0; + this.numRetries = 0; + this.currentInvocationId = { + checkUploadStatus: uuid.v4(), + chunk: uuid.v4(), + uri: uuid.v4(), + }; + /** + * A cache of buffers written to this instance, ready for consuming + */ + this.writeBuffers = []; + this.numChunksReadInRequest = 0; + /** + * An array of buffers used for caching the most recent upload chunk. + * We should not assume that the server received all bytes sent in the request. + * - https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload + */ + this.localWriteCache = []; + this.localWriteCacheByteLength = 0; + this.upstreamEnded = false; + _Upload_gcclGcsCmd.set(this, void 0); + cfg = cfg || {}; + if (!cfg.bucket || !cfg.file) { + throw new Error('A bucket and file name are required'); + } + if (cfg.offset && !cfg.uri) { + throw new RangeError('Cannot provide an `offset` without providing a `uri`'); + } + if (cfg.isPartialUpload && !cfg.chunkSize) { + throw new RangeError('Cannot set `isPartialUpload` without providing a `chunkSize`'); + } + cfg.authConfig = cfg.authConfig || {}; + cfg.authConfig.scopes = [ + 'https://www.googleapis.com/auth/devstorage.full_control', + ]; + this.authClient = cfg.authClient || new google_auth_library_1.GoogleAuth(cfg.authConfig); + const universe = cfg.universeDomain || google_auth_library_1.DEFAULT_UNIVERSE; + this.apiEndpoint = `https://storage.${universe}`; + if (cfg.apiEndpoint && cfg.apiEndpoint !== this.apiEndpoint) { + this.apiEndpoint = this.sanitizeEndpoint(cfg.apiEndpoint); + const hostname = new URL(this.apiEndpoint).hostname; + // check if it is a domain of a known universe + const isDomain = hostname === universe; + const isDefaultUniverseDomain = hostname === google_auth_library_1.DEFAULT_UNIVERSE; + // check if it is a subdomain of a known universe + // by checking a last (universe's length + 1) of a hostname + const isSubDomainOfUniverse = hostname.slice(-(universe.length + 1)) === `.${universe}`; + const isSubDomainOfDefaultUniverse = hostname.slice(-(google_auth_library_1.DEFAULT_UNIVERSE.length + 1)) === + `.${google_auth_library_1.DEFAULT_UNIVERSE}`; + if (!isDomain && + !isDefaultUniverseDomain && + !isSubDomainOfUniverse && + !isSubDomainOfDefaultUniverse) { + // Check if we should use auth with custom endpoint + if (cfg.useAuthWithCustomEndpoint !== true) { + // Only bypass auth if explicitly not requested + this.authClient = gaxios; + } + // Otherwise keep the authenticated client + } + } + this.baseURI = `${this.apiEndpoint}/upload/storage/v1/b`; + this.bucket = cfg.bucket; + const cacheKeyElements = [cfg.bucket, cfg.file]; + if (typeof cfg.generation === 'number') { + cacheKeyElements.push(`${cfg.generation}`); + } + this.cacheKey = cacheKeyElements.join('/'); + this.customRequestOptions = cfg.customRequestOptions || {}; + this.file = cfg.file; + this.generation = cfg.generation; + this.kmsKeyName = cfg.kmsKeyName; + this.metadata = cfg.metadata || {}; + this.offset = cfg.offset; + this.origin = cfg.origin; + this.params = cfg.params || {}; + this.userProject = cfg.userProject; + this.chunkSize = cfg.chunkSize; + this.retryOptions = cfg.retryOptions; + this.isPartialUpload = (_a = cfg.isPartialUpload) !== null && _a !== void 0 ? _a : false; + if (cfg.key) { + if (typeof cfg.key === 'string') { + const base64Key = Buffer.from(cfg.key).toString('base64'); + this.encryption = { + key: base64Key, + hash: (0, crypto_1.createHash)('sha256').update(cfg.key).digest('base64'), + }; + } + else { + const base64Key = cfg.key.toString('base64'); + this.encryption = { + key: base64Key, + hash: (0, crypto_1.createHash)('sha256').update(cfg.key).digest('base64'), + }; + } + } + this.predefinedAcl = cfg.predefinedAcl; + if (cfg.private) + this.predefinedAcl = 'private'; + if (cfg.public) + this.predefinedAcl = 'publicRead'; + const autoRetry = cfg.retryOptions.autoRetry; + this.uriProvidedManually = !!cfg.uri; + this.uri = cfg.uri; + if (this.offset) { + // we're resuming an incomplete upload + this.numBytesWritten = this.offset; + } + this.numRetries = 0; // counter for number of retries currently executed + if (!autoRetry) { + cfg.retryOptions.maxRetries = 0; + } + this.timeOfFirstRequest = Date.now(); + const contentLength = cfg.metadata + ? Number(cfg.metadata.contentLength) + : NaN; + this.contentLength = isNaN(contentLength) ? '*' : contentLength; + __classPrivateFieldSet(this, _Upload_gcclGcsCmd, cfg[util_js_2.GCCL_GCS_CMD_KEY], "f"); + this.once('writing', () => { + if (this.uri) { + this.continueUploading(); + } + else { + this.createURI(err => { + if (err) { + return this.destroy(err); + } + this.startUploading(); + return; + }); + } + }); + } + /** + * Prevent 'finish' event until the upload has succeeded. + * + * @param fireFinishEvent The finish callback + */ + _final(fireFinishEvent = () => { }) { + this.upstreamEnded = true; + this.once('uploadFinished', fireFinishEvent); + process.nextTick(() => { + this.emit('upstreamFinished'); + // it's possible `_write` may not be called - namely for empty object uploads + this.emit('writing'); + }); + } + /** + * Handles incoming data from upstream + * + * @param chunk The chunk to append to the buffer + * @param encoding The encoding of the chunk + * @param readCallback A callback for when the buffer has been read downstream + */ + _write(chunk, encoding, readCallback = () => { }) { + // Backwards-compatible event + this.emit('writing'); + this.writeBuffers.push(typeof chunk === 'string' ? Buffer.from(chunk, encoding) : chunk); + this.once('readFromChunkBuffer', readCallback); + process.nextTick(() => this.emit('wroteToChunkBuffer')); + } + /** + * Prepends the local buffer to write buffer and resets it. + * + * @param keepLastBytes number of bytes to keep from the end of the local buffer. + */ + prependLocalBufferToUpstream(keepLastBytes) { + // Typically, the upstream write buffers should be smaller than the local + // cache, so we can save time by setting the local cache as the new + // upstream write buffer array and appending the old array to it + let initialBuffers = []; + if (keepLastBytes) { + // we only want the last X bytes + let bytesKept = 0; + while (keepLastBytes > bytesKept) { + // load backwards because we want the last X bytes + // note: `localWriteCacheByteLength` is reset below + let buf = this.localWriteCache.pop(); + if (!buf) + break; + bytesKept += buf.byteLength; + if (bytesKept > keepLastBytes) { + // we have gone over the amount desired, let's keep the last X bytes + // of this buffer + const diff = bytesKept - keepLastBytes; + buf = buf.subarray(diff); + bytesKept -= diff; + } + initialBuffers.unshift(buf); + } + } + else { + // we're keeping all of the local cache, simply use it as the initial buffer + initialBuffers = this.localWriteCache; + } + // Append the old upstream to the new + const append = this.writeBuffers; + this.writeBuffers = initialBuffers; + for (const buf of append) { + this.writeBuffers.push(buf); + } + // reset last buffers sent + __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_resetLocalBuffersCache).call(this); + } + /** + * Retrieves data from upstream's buffer. + * + * @param limit The maximum amount to return from the buffer. + */ + *pullFromChunkBuffer(limit) { + while (limit) { + const buf = this.writeBuffers.shift(); + if (!buf) + break; + let bufToYield = buf; + if (buf.byteLength > limit) { + bufToYield = buf.subarray(0, limit); + this.writeBuffers.unshift(buf.subarray(limit)); + limit = 0; + } + else { + limit -= buf.byteLength; + } + yield bufToYield; + // Notify upstream we've read from the buffer and we're able to consume + // more. It can also potentially send more data down as we're currently + // iterating. + this.emit('readFromChunkBuffer'); + } + } + /** + * A handler for determining if data is ready to be read from upstream. + * + * @returns If there will be more chunks to read in the future + */ + async waitForNextChunk() { + const willBeMoreChunks = await new Promise(resolve => { + // There's data available - it should be digested + if (this.writeBuffers.length) { + return resolve(true); + } + // The upstream writable ended, we shouldn't expect any more data. + if (this.upstreamEnded) { + return resolve(false); + } + // Nothing immediate seems to be determined. We need to prepare some + // listeners to determine next steps... + const wroteToChunkBufferCallback = () => { + removeListeners(); + return resolve(true); + }; + const upstreamFinishedCallback = () => { + removeListeners(); + // this should be the last chunk, if there's anything there + if (this.writeBuffers.length) + return resolve(true); + return resolve(false); + }; + // Remove listeners when we're ready to callback. + const removeListeners = () => { + this.removeListener('wroteToChunkBuffer', wroteToChunkBufferCallback); + this.removeListener('upstreamFinished', upstreamFinishedCallback); + }; + // If there's data recently written it should be digested + this.once('wroteToChunkBuffer', wroteToChunkBufferCallback); + // If the upstream finishes let's see if there's anything to grab + this.once('upstreamFinished', upstreamFinishedCallback); + }); + return willBeMoreChunks; + } + /** + * Reads data from upstream up to the provided `limit`. + * Ends when the limit has reached or no data is expected to be pushed from upstream. + * + * @param limit The most amount of data this iterator should return. `Infinity` by default. + */ + async *upstreamIterator(limit = Infinity) { + // read from upstream chunk buffer + while (limit && (await this.waitForNextChunk())) { + // read until end or limit has been reached + for (const chunk of this.pullFromChunkBuffer(limit)) { + limit -= chunk.byteLength; + yield chunk; + } + } + } + createURI(callback) { + if (!callback) { + return this.createURIAsync(); + } + this.createURIAsync().then(r => callback(null, r), callback); + } + async createURIAsync() { + const metadata = { ...this.metadata }; + const headers = {}; + // Delete content length and content type from metadata if they exist. + // These are headers and should not be sent as part of the metadata. + if (metadata.contentLength) { + headers['X-Upload-Content-Length'] = metadata.contentLength.toString(); + delete metadata.contentLength; + } + if (metadata.contentType) { + headers['X-Upload-Content-Type'] = metadata.contentType; + delete metadata.contentType; + } + let googAPIClient = `${(0, util_js_1.getRuntimeTrackingString)()} gccl/${packageJson.version}-${(0, util_js_1.getModuleFormat)()} gccl-invocation-id/${this.currentInvocationId.uri}`; + if (__classPrivateFieldGet(this, _Upload_gcclGcsCmd, "f")) { + googAPIClient += ` gccl-gcs-cmd/${__classPrivateFieldGet(this, _Upload_gcclGcsCmd, "f")}`; + } + // Check if headers already exist before creating new ones + const reqOpts = { + method: 'POST', + url: [this.baseURI, this.bucket, 'o'].join('/'), + params: Object.assign({ + name: this.file, + uploadType: 'resumable', + }, this.params), + data: metadata, + headers: { + 'User-Agent': (0, util_js_1.getUserAgentString)(), + 'x-goog-api-client': googAPIClient, + ...headers, + }, + }; + if (metadata.contentLength) { + reqOpts.headers['X-Upload-Content-Length'] = + metadata.contentLength.toString(); + } + if (metadata.contentType) { + reqOpts.headers['X-Upload-Content-Type'] = metadata.contentType; + } + if (typeof this.generation !== 'undefined') { + reqOpts.params.ifGenerationMatch = this.generation; + } + if (this.kmsKeyName) { + reqOpts.params.kmsKeyName = this.kmsKeyName; + } + if (this.predefinedAcl) { + reqOpts.params.predefinedAcl = this.predefinedAcl; + } + if (this.origin) { + reqOpts.headers.Origin = this.origin; + } + const uri = await (0, async_retry_1.default)(async (bail) => { + var _a, _b, _c; + try { + const res = await this.makeRequest(reqOpts); + // We have successfully got a URI we can now create a new invocation id + this.currentInvocationId.uri = uuid.v4(); + return res.headers.location; + } + catch (err) { + const e = err; + const apiError = { + code: (_a = e.response) === null || _a === void 0 ? void 0 : _a.status, + name: (_b = e.response) === null || _b === void 0 ? void 0 : _b.statusText, + message: (_c = e.response) === null || _c === void 0 ? void 0 : _c.statusText, + errors: [ + { + reason: e.code, + }, + ], + }; + if (this.retryOptions.maxRetries > 0 && + this.retryOptions.retryableErrorFn(apiError)) { + throw e; + } + else { + return bail(e); + } + } + }, { + retries: this.retryOptions.maxRetries, + factor: this.retryOptions.retryDelayMultiplier, + maxTimeout: this.retryOptions.maxRetryDelay * 1000, //convert to milliseconds + maxRetryTime: this.retryOptions.totalTimeout * 1000, //convert to milliseconds + }); + this.uri = uri; + this.offset = 0; + // emit the newly generated URI for future reuse, if necessary. + this.emit('uri', uri); + return uri; + } + async continueUploading() { + var _a; + (_a = this.offset) !== null && _a !== void 0 ? _a : (await this.getAndSetOffset()); + return this.startUploading(); + } + async startUploading() { + const multiChunkMode = !!this.chunkSize; + let responseReceived = false; + this.numChunksReadInRequest = 0; + if (!this.offset) { + this.offset = 0; + } + // Check if the offset (server) is too far behind the current stream + if (this.offset < this.numBytesWritten) { + const delta = this.numBytesWritten - this.offset; + const message = `The offset is lower than the number of bytes written. The server has ${this.offset} bytes and while ${this.numBytesWritten} bytes has been uploaded - thus ${delta} bytes are missing. Stopping as this could result in data loss. Initiate a new upload to continue.`; + this.emit('error', new RangeError(message)); + return; + } + // Check if we should 'fast-forward' to the relevant data to upload + if (this.numBytesWritten < this.offset) { + // 'fast-forward' to the byte where we need to upload. + // only push data from the byte after the one we left off on + const fastForwardBytes = this.offset - this.numBytesWritten; + for await (const _chunk of this.upstreamIterator(fastForwardBytes)) { + _chunk; // discard the data up until the point we want + } + this.numBytesWritten = this.offset; + } + let expectedUploadSize = undefined; + // Set `expectedUploadSize` to `contentLength - this.numBytesWritten`, if available + if (typeof this.contentLength === 'number') { + expectedUploadSize = this.contentLength - this.numBytesWritten; + } + // `expectedUploadSize` should be no more than the `chunkSize`. + // It's possible this is the last chunk request for a multiple + // chunk upload, thus smaller than the chunk size. + if (this.chunkSize) { + expectedUploadSize = expectedUploadSize + ? Math.min(this.chunkSize, expectedUploadSize) + : this.chunkSize; + } + // A queue for the upstream data + const upstreamQueue = this.upstreamIterator(expectedUploadSize); + // The primary read stream for this request. This stream retrieves no more + // than the exact requested amount from upstream. + const requestStream = new stream_1.Readable({ + read: async () => { + // Don't attempt to retrieve data upstream if we already have a response + if (responseReceived) + requestStream.push(null); + const result = await upstreamQueue.next(); + if (result.value) { + this.numChunksReadInRequest++; + if (multiChunkMode) { + // save ever buffer used in the request in multi-chunk mode + __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_addLocalBufferCache).call(this, result.value); + } + else { + __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_resetLocalBuffersCache).call(this); + __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_addLocalBufferCache).call(this, result.value); + } + this.numBytesWritten += result.value.byteLength; + this.emit('progress', { + bytesWritten: this.numBytesWritten, + contentLength: this.contentLength, + }); + requestStream.push(result.value); + } + if (result.done) { + requestStream.push(null); + } + }, + }); + let googAPIClient = `${(0, util_js_1.getRuntimeTrackingString)()} gccl/${packageJson.version}-${(0, util_js_1.getModuleFormat)()} gccl-invocation-id/${this.currentInvocationId.chunk}`; + if (__classPrivateFieldGet(this, _Upload_gcclGcsCmd, "f")) { + googAPIClient += ` gccl-gcs-cmd/${__classPrivateFieldGet(this, _Upload_gcclGcsCmd, "f")}`; + } + const headers = { + 'User-Agent': (0, util_js_1.getUserAgentString)(), + 'x-goog-api-client': googAPIClient, + }; + // If using multiple chunk upload, set appropriate header + if (multiChunkMode) { + // We need to know how much data is available upstream to set the `Content-Range` header. + // https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload + for await (const chunk of this.upstreamIterator(expectedUploadSize)) { + // This will conveniently track and keep the size of the buffers. + // We will reach either the expected upload size or the remainder of the stream. + __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_addLocalBufferCache).call(this, chunk); + } + // This is the sum from the `#addLocalBufferCache` calls + const bytesToUpload = this.localWriteCacheByteLength; + // Important: we want to know if the upstream has ended and the queue is empty before + // unshifting data back into the queue. This way we will know if this is the last request or not. + const isLastChunkOfUpload = !(await this.waitForNextChunk()); + // Important: put the data back in the queue for the actual upload + this.prependLocalBufferToUpstream(); + let totalObjectSize = this.contentLength; + if (typeof this.contentLength !== 'number' && + isLastChunkOfUpload && + !this.isPartialUpload) { + // Let's let the server know this is the last chunk of the object since we didn't set it before. + totalObjectSize = bytesToUpload + this.numBytesWritten; + } + // `- 1` as the ending byte is inclusive in the request. + const endingByte = bytesToUpload + this.numBytesWritten - 1; + // `Content-Length` for multiple chunk uploads is the size of the chunk, + // not the overall object + headers['Content-Length'] = bytesToUpload; + headers['Content-Range'] = + `bytes ${this.offset}-${endingByte}/${totalObjectSize}`; + } + else { + headers['Content-Range'] = `bytes ${this.offset}-*/${this.contentLength}`; + } + const reqOpts = { + method: 'PUT', + url: this.uri, + headers, + body: requestStream, + }; + try { + const resp = await this.makeRequestStream(reqOpts); + if (resp) { + responseReceived = true; + await this.responseHandler(resp); + } + } + catch (e) { + const err = e; + if (this.retryOptions.retryableErrorFn(err)) { + this.attemptDelayedRetry({ + status: NaN, + data: err, + }); + return; + } + this.destroy(err); + } + } + // Process the API response to look for errors that came in + // the response body. + async responseHandler(resp) { + if (resp.data.error) { + this.destroy(resp.data.error); + return; + } + // At this point we can safely create a new id for the chunk + this.currentInvocationId.chunk = uuid.v4(); + const moreDataToUpload = await this.waitForNextChunk(); + const shouldContinueWithNextMultiChunkRequest = this.chunkSize && + resp.status === RESUMABLE_INCOMPLETE_STATUS_CODE && + resp.headers.range && + moreDataToUpload; + /** + * This is true when we're expecting to upload more data in a future request, + * yet the upstream for the upload session has been exhausted. + */ + const shouldContinueUploadInAnotherRequest = this.isPartialUpload && + resp.status === RESUMABLE_INCOMPLETE_STATUS_CODE && + !moreDataToUpload; + if (shouldContinueWithNextMultiChunkRequest) { + // Use the upper value in this header to determine where to start the next chunk. + // We should not assume that the server received all bytes sent in the request. + // https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload + const range = resp.headers.range; + this.offset = Number(range.split('-')[1]) + 1; + // We should not assume that the server received all bytes sent in the request. + // - https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload + const missingBytes = this.numBytesWritten - this.offset; + if (missingBytes) { + // As multi-chunk uploads send one chunk per request and pulls one + // chunk into the pipeline, prepending the missing bytes back should + // be fine for the next request. + this.prependLocalBufferToUpstream(missingBytes); + this.numBytesWritten -= missingBytes; + } + else { + // No bytes missing - no need to keep the local cache + __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_resetLocalBuffersCache).call(this); + } + // continue uploading next chunk + this.continueUploading(); + } + else if (!this.isSuccessfulResponse(resp.status) && + !shouldContinueUploadInAnotherRequest) { + const err = new Error('Upload failed'); + err.code = resp.status; + err.name = 'Upload failed'; + if (resp === null || resp === void 0 ? void 0 : resp.data) { + err.errors = [resp === null || resp === void 0 ? void 0 : resp.data]; + } + this.destroy(err); + } + else { + // no need to keep the cache + __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_resetLocalBuffersCache).call(this); + if (resp && resp.data) { + resp.data.size = Number(resp.data.size); + } + this.emit('metadata', resp.data); + // Allow the object (Upload) to continue naturally so the user's + // "finish" event fires. + this.emit('uploadFinished'); + } + } + /** + * Check the status of an existing resumable upload. + * + * @param cfg A configuration to use. `uri` is required. + * @returns the current upload status + */ + async checkUploadStatus(config = {}) { + let googAPIClient = `${(0, util_js_1.getRuntimeTrackingString)()} gccl/${packageJson.version}-${(0, util_js_1.getModuleFormat)()} gccl-invocation-id/${this.currentInvocationId.checkUploadStatus}`; + if (__classPrivateFieldGet(this, _Upload_gcclGcsCmd, "f")) { + googAPIClient += ` gccl-gcs-cmd/${__classPrivateFieldGet(this, _Upload_gcclGcsCmd, "f")}`; + } + const opts = { + method: 'PUT', + url: this.uri, + headers: { + 'Content-Length': 0, + 'Content-Range': 'bytes */*', + 'User-Agent': (0, util_js_1.getUserAgentString)(), + 'x-goog-api-client': googAPIClient, + }, + }; + try { + const resp = await this.makeRequest(opts); + // Successfully got the offset we can now create a new offset invocation id + this.currentInvocationId.checkUploadStatus = uuid.v4(); + return resp; + } + catch (e) { + if (config.retry === false || + !(e instanceof Error) || + !this.retryOptions.retryableErrorFn(e)) { + throw e; + } + const retryDelay = this.getRetryDelay(); + if (retryDelay <= 0) { + throw e; + } + await new Promise(res => setTimeout(res, retryDelay)); + return this.checkUploadStatus(config); + } + } + async getAndSetOffset() { + try { + // we want to handle retries in this method. + const resp = await this.checkUploadStatus({ retry: false }); + if (resp.status === RESUMABLE_INCOMPLETE_STATUS_CODE) { + if (typeof resp.headers.range === 'string') { + this.offset = Number(resp.headers.range.split('-')[1]) + 1; + return; + } + } + this.offset = 0; + } + catch (e) { + const err = e; + if (this.retryOptions.retryableErrorFn(err)) { + this.attemptDelayedRetry({ + status: NaN, + data: err, + }); + return; + } + this.destroy(err); + } + } + async makeRequest(reqOpts) { + if (this.encryption) { + reqOpts.headers = reqOpts.headers || {}; + reqOpts.headers['x-goog-encryption-algorithm'] = 'AES256'; + reqOpts.headers['x-goog-encryption-key'] = this.encryption.key.toString(); + reqOpts.headers['x-goog-encryption-key-sha256'] = + this.encryption.hash.toString(); + } + if (this.userProject) { + reqOpts.params = reqOpts.params || {}; + reqOpts.params.userProject = this.userProject; + } + // Let gaxios know we will handle a 308 error code ourselves. + reqOpts.validateStatus = (status) => { + return (this.isSuccessfulResponse(status) || + status === RESUMABLE_INCOMPLETE_STATUS_CODE); + }; + const combinedReqOpts = { + ...this.customRequestOptions, + ...reqOpts, + headers: { + ...this.customRequestOptions.headers, + ...reqOpts.headers, + }, + }; + const res = await this.authClient.request(combinedReqOpts); + if (res.data && res.data.error) { + throw res.data.error; + } + return res; + } + async makeRequestStream(reqOpts) { + const controller = new abort_controller_1.default(); + const errorCallback = () => controller.abort(); + this.once('error', errorCallback); + if (this.userProject) { + reqOpts.params = reqOpts.params || {}; + reqOpts.params.userProject = this.userProject; + } + reqOpts.signal = controller.signal; + reqOpts.validateStatus = () => true; + const combinedReqOpts = { + ...this.customRequestOptions, + ...reqOpts, + headers: { + ...this.customRequestOptions.headers, + ...reqOpts.headers, + }, + }; + const res = await this.authClient.request(combinedReqOpts); + const successfulRequest = this.onResponse(res); + this.removeListener('error', errorCallback); + return successfulRequest ? res : null; + } + /** + * @return {bool} is the request good? + */ + onResponse(resp) { + if (resp.status !== 200 && + this.retryOptions.retryableErrorFn({ + code: resp.status, + message: resp.statusText, + name: resp.statusText, + })) { + this.attemptDelayedRetry(resp); + return false; + } + this.emit('response', resp); + return true; + } + /** + * @param resp GaxiosResponse object from previous attempt + */ + attemptDelayedRetry(resp) { + if (this.numRetries < this.retryOptions.maxRetries) { + if (resp.status === NOT_FOUND_STATUS_CODE && + this.numChunksReadInRequest === 0) { + this.startUploading(); + } + else { + const retryDelay = this.getRetryDelay(); + if (retryDelay <= 0) { + this.destroy(new Error(`Retry total time limit exceeded - ${JSON.stringify(resp.data)}`)); + return; + } + // Unshift the local cache back in case it's needed for the next request. + this.numBytesWritten -= this.localWriteCacheByteLength; + this.prependLocalBufferToUpstream(); + // We don't know how much data has been received by the server. + // `continueUploading` will recheck the offset via `getAndSetOffset`. + // If `offset` < `numberBytesReceived` then we will raise a RangeError + // as we've streamed too much data that has been missed - this should + // not be the case for multi-chunk uploads as `lastChunkSent` is the + // body of the entire request. + this.offset = undefined; + setTimeout(this.continueUploading.bind(this), retryDelay); + } + this.numRetries++; + } + else { + this.destroy(new Error(`Retry limit exceeded - ${JSON.stringify(resp.data)}`)); + } + } + /** + * The amount of time to wait before retrying the request, in milliseconds. + * If negative, do not retry. + * + * @returns the amount of time to wait, in milliseconds. + */ + getRetryDelay() { + const randomMs = Math.round(Math.random() * 1000); + const waitTime = Math.pow(this.retryOptions.retryDelayMultiplier, this.numRetries) * + 1000 + + randomMs; + const maxAllowableDelayMs = this.retryOptions.totalTimeout * 1000 - + (Date.now() - this.timeOfFirstRequest); + const maxRetryDelayMs = this.retryOptions.maxRetryDelay * 1000; + return Math.min(waitTime, maxRetryDelayMs, maxAllowableDelayMs); + } + /* + * Prepare user-defined API endpoint for compatibility with our API. + */ + sanitizeEndpoint(url) { + if (!exports.PROTOCOL_REGEX.test(url)) { + url = `https://${url}`; + } + return url.replace(/\/+$/, ''); // Remove trailing slashes + } + /** + * Check if a given status code is 2xx + * + * @param status The status code to check + * @returns if the status is 2xx + */ + isSuccessfulResponse(status) { + return status >= 200 && status < 300; + } +} +exports.Upload = Upload; +_Upload_gcclGcsCmd = new WeakMap(), _Upload_instances = new WeakSet(), _Upload_resetLocalBuffersCache = function _Upload_resetLocalBuffersCache() { + this.localWriteCache = []; + this.localWriteCacheByteLength = 0; +}, _Upload_addLocalBufferCache = function _Upload_addLocalBufferCache(buf) { + this.localWriteCache.push(buf); + this.localWriteCacheByteLength += buf.byteLength; +}; +function upload(cfg) { + return new Upload(cfg); +} +function createURI(cfg, callback) { + const up = new Upload(cfg); + if (!callback) { + return up.createURI(); + } + up.createURI().then(r => callback(null, r), callback); +} +/** + * Check the status of an existing resumable upload. + * + * @param cfg A configuration to use. `uri` is required. + * @returns the current upload status + */ +function checkUploadStatus(cfg) { + const up = new Upload(cfg); + return up.checkUploadStatus(); +} diff --git a/node_modules/@google-cloud/storage/build/cjs/src/signer.d.ts b/node_modules/@google-cloud/storage/build/cjs/src/signer.d.ts new file mode 100644 index 0000000..337961f --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/signer.d.ts @@ -0,0 +1,146 @@ +import * as http from 'http'; +import { Storage } from './storage.js'; +import { GoogleAuth } from 'google-auth-library'; +type GoogleAuthLike = Pick; +/** + * @deprecated Use {@link GoogleAuth} instead + */ +export interface AuthClient { + sign(blobToSign: string): Promise; + getCredentials(): Promise<{ + client_email?: string; + }>; +} +export interface BucketI { + name: string; +} +export interface FileI { + name: string; +} +export interface Query { + [key: string]: string; +} +export interface GetSignedUrlConfigInternal { + expiration: number; + accessibleAt?: Date; + method: string; + extensionHeaders?: http.OutgoingHttpHeaders; + queryParams?: Query; + cname?: string; + contentMd5?: string; + contentType?: string; + bucket: string; + file?: string; + /** + * The host for the generated signed URL + * + * @example + * 'https://localhost:8080/' + */ + host?: string | URL; + /** + * An endpoint for generating the signed URL + * + * @example + * 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/' + */ + signingEndpoint?: string | URL; +} +export interface SignerGetSignedUrlConfig { + method: 'GET' | 'PUT' | 'DELETE' | 'POST'; + expires: string | number | Date; + accessibleAt?: string | number | Date; + virtualHostedStyle?: boolean; + version?: 'v2' | 'v4'; + cname?: string; + extensionHeaders?: http.OutgoingHttpHeaders; + queryParams?: Query; + contentMd5?: string; + contentType?: string; + /** + * The host for the generated signed URL + * + * @example + * 'https://localhost:8080/' + */ + host?: string | URL; + /** + * An endpoint for generating the signed URL + * + * @example + * 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/' + */ + signingEndpoint?: string | URL; +} +export type SignerGetSignedUrlResponse = string; +export type GetSignedUrlResponse = [SignerGetSignedUrlResponse]; +export interface GetSignedUrlCallback { + (err: Error | null, url?: string): void; +} +export declare enum SignerExceptionMessages { + ACCESSIBLE_DATE_INVALID = "The accessible at date provided was invalid.", + EXPIRATION_BEFORE_ACCESSIBLE_DATE = "An expiration date cannot be before accessible date.", + X_GOOG_CONTENT_SHA256 = "The header X-Goog-Content-SHA256 must be a hexadecimal string." +} +/** + * @const {string} + * @deprecated - unused + */ +export declare const PATH_STYLED_HOST = "https://storage.googleapis.com"; +export declare class URLSigner { + private auth; + private bucket; + private file?; + /** + * A {@link Storage} object. + * + * @privateRemarks + * + * Technically this is a required field, however it would be a breaking change to + * move it before optional properties. In the next major we should refactor the + * constructor of this class to only accept a config object. + */ + private storage; + constructor(auth: AuthClient | GoogleAuthLike, bucket: BucketI, file?: FileI | undefined, + /** + * A {@link Storage} object. + * + * @privateRemarks + * + * Technically this is a required field, however it would be a breaking change to + * move it before optional properties. In the next major we should refactor the + * constructor of this class to only accept a config object. + */ + storage?: Storage); + getSignedUrl(cfg: SignerGetSignedUrlConfig): Promise; + private getSignedUrlV2; + private getSignedUrlV4; + /** + * Create canonical headers for signing v4 url. + * + * The canonical headers for v4-signing a request demands header names are + * first lowercased, followed by sorting the header names. + * Then, construct the canonical headers part of the request: + * + ":" + Trim() + "\n" + * .. + * + ":" + Trim() + "\n" + * + * @param headers + * @private + */ + getCanonicalHeaders(headers: http.OutgoingHttpHeaders): string; + getCanonicalRequest(method: string, path: string, query: string, headers: string, signedHeaders: string, contentSha256?: string): string; + getCanonicalQueryParams(query: Query): string; + getResourcePath(cname: boolean, bucket: string, file?: string): string; + parseExpires(expires: string | number | Date, current?: Date): number; + parseAccessibleAt(accessibleAt?: string | number | Date): number; +} +/** + * Custom error type for errors related to getting signed errors and policies. + * + * @private + */ +export declare class SigningError extends Error { + name: string; +} +export {}; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/signer.js b/node_modules/@google-cloud/storage/build/cjs/src/signer.js new file mode 100644 index 0000000..2f9dfc9 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/signer.js @@ -0,0 +1,337 @@ +"use strict"; +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SigningError = exports.URLSigner = exports.PATH_STYLED_HOST = exports.SignerExceptionMessages = void 0; +const crypto = __importStar(require("crypto")); +const url = __importStar(require("url")); +const storage_js_1 = require("./storage.js"); +const util_js_1 = require("./util.js"); +var SignerExceptionMessages; +(function (SignerExceptionMessages) { + SignerExceptionMessages["ACCESSIBLE_DATE_INVALID"] = "The accessible at date provided was invalid."; + SignerExceptionMessages["EXPIRATION_BEFORE_ACCESSIBLE_DATE"] = "An expiration date cannot be before accessible date."; + SignerExceptionMessages["X_GOOG_CONTENT_SHA256"] = "The header X-Goog-Content-SHA256 must be a hexadecimal string."; +})(SignerExceptionMessages || (exports.SignerExceptionMessages = SignerExceptionMessages = {})); +/* + * Default signing version for getSignedUrl is 'v2'. + */ +const DEFAULT_SIGNING_VERSION = 'v2'; +const SEVEN_DAYS = 7 * 24 * 60 * 60; +/** + * @const {string} + * @deprecated - unused + */ +exports.PATH_STYLED_HOST = 'https://storage.googleapis.com'; +class URLSigner { + constructor(auth, bucket, file, + /** + * A {@link Storage} object. + * + * @privateRemarks + * + * Technically this is a required field, however it would be a breaking change to + * move it before optional properties. In the next major we should refactor the + * constructor of this class to only accept a config object. + */ + storage = new storage_js_1.Storage()) { + this.auth = auth; + this.bucket = bucket; + this.file = file; + this.storage = storage; + } + getSignedUrl(cfg) { + const expiresInSeconds = this.parseExpires(cfg.expires); + const method = cfg.method; + const accessibleAtInSeconds = this.parseAccessibleAt(cfg.accessibleAt); + if (expiresInSeconds < accessibleAtInSeconds) { + throw new Error(SignerExceptionMessages.EXPIRATION_BEFORE_ACCESSIBLE_DATE); + } + let customHost; + // Default style is `path`. + const isVirtualHostedStyle = cfg.virtualHostedStyle || false; + if (cfg.cname) { + customHost = cfg.cname; + } + else if (isVirtualHostedStyle) { + customHost = `https://${this.bucket.name}.storage.${this.storage.universeDomain}`; + } + const secondsToMilliseconds = 1000; + const config = Object.assign({}, cfg, { + method, + expiration: expiresInSeconds, + accessibleAt: new Date(secondsToMilliseconds * accessibleAtInSeconds), + bucket: this.bucket.name, + file: this.file ? (0, util_js_1.encodeURI)(this.file.name, false) : undefined, + }); + if (customHost) { + config.cname = customHost; + } + const version = cfg.version || DEFAULT_SIGNING_VERSION; + let promise; + if (version === 'v2') { + promise = this.getSignedUrlV2(config); + } + else if (version === 'v4') { + promise = this.getSignedUrlV4(config); + } + else { + throw new Error(`Invalid signed URL version: ${version}. Supported versions are 'v2' and 'v4'.`); + } + return promise.then(query => { + var _a; + query = Object.assign(query, cfg.queryParams); + const signedUrl = new url.URL(((_a = cfg.host) === null || _a === void 0 ? void 0 : _a.toString()) || config.cname || this.storage.apiEndpoint); + signedUrl.pathname = this.getResourcePath(!!config.cname, this.bucket.name, config.file); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + signedUrl.search = (0, util_js_1.qsStringify)(query); + return signedUrl.href; + }); + } + getSignedUrlV2(config) { + const canonicalHeadersString = this.getCanonicalHeaders(config.extensionHeaders || {}); + const resourcePath = this.getResourcePath(false, config.bucket, config.file); + const blobToSign = [ + config.method, + config.contentMd5 || '', + config.contentType || '', + config.expiration, + canonicalHeadersString + resourcePath, + ].join('\n'); + const sign = async () => { + var _a; + const auth = this.auth; + try { + const signature = await auth.sign(blobToSign, (_a = config.signingEndpoint) === null || _a === void 0 ? void 0 : _a.toString()); + const credentials = await auth.getCredentials(); + return { + GoogleAccessId: credentials.client_email, + Expires: config.expiration, + Signature: signature, + }; + } + catch (err) { + const error = err; + const signingErr = new SigningError(error.message); + signingErr.stack = error.stack; + throw signingErr; + } + }; + return sign(); + } + getSignedUrlV4(config) { + var _a; + config.accessibleAt = config.accessibleAt + ? config.accessibleAt + : new Date(); + const millisecondsToSeconds = 1.0 / 1000.0; + const expiresPeriodInSeconds = config.expiration - config.accessibleAt.valueOf() * millisecondsToSeconds; + // v4 limit expiration to be 7 days maximum + if (expiresPeriodInSeconds > SEVEN_DAYS) { + throw new Error(`Max allowed expiration is seven days (${SEVEN_DAYS} seconds).`); + } + const extensionHeaders = Object.assign({}, config.extensionHeaders); + const fqdn = new url.URL(((_a = config.host) === null || _a === void 0 ? void 0 : _a.toString()) || config.cname || this.storage.apiEndpoint); + extensionHeaders.host = fqdn.hostname; + if (config.contentMd5) { + extensionHeaders['content-md5'] = config.contentMd5; + } + if (config.contentType) { + extensionHeaders['content-type'] = config.contentType; + } + let contentSha256; + const sha256Header = extensionHeaders['x-goog-content-sha256']; + if (sha256Header) { + if (typeof sha256Header !== 'string' || + !/[A-Fa-f0-9]{40}/.test(sha256Header)) { + throw new Error(SignerExceptionMessages.X_GOOG_CONTENT_SHA256); + } + contentSha256 = sha256Header; + } + const signedHeaders = Object.keys(extensionHeaders) + .map(header => header.toLowerCase()) + .sort() + .join(';'); + const extensionHeadersString = this.getCanonicalHeaders(extensionHeaders); + const datestamp = (0, util_js_1.formatAsUTCISO)(config.accessibleAt); + const credentialScope = `${datestamp}/auto/storage/goog4_request`; + const sign = async () => { + var _a; + const credentials = await this.auth.getCredentials(); + const credential = `${credentials.client_email}/${credentialScope}`; + const dateISO = (0, util_js_1.formatAsUTCISO)(config.accessibleAt ? config.accessibleAt : new Date(), true); + const queryParams = { + 'X-Goog-Algorithm': 'GOOG4-RSA-SHA256', + 'X-Goog-Credential': credential, + 'X-Goog-Date': dateISO, + 'X-Goog-Expires': expiresPeriodInSeconds.toString(10), + 'X-Goog-SignedHeaders': signedHeaders, + ...(config.queryParams || {}), + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const canonicalQueryParams = this.getCanonicalQueryParams(queryParams); + const canonicalRequest = this.getCanonicalRequest(config.method, this.getResourcePath(!!config.cname, config.bucket, config.file), canonicalQueryParams, extensionHeadersString, signedHeaders, contentSha256); + const hash = crypto + .createHash('sha256') + .update(canonicalRequest) + .digest('hex'); + const blobToSign = [ + 'GOOG4-RSA-SHA256', + dateISO, + credentialScope, + hash, + ].join('\n'); + try { + const signature = await this.auth.sign(blobToSign, (_a = config.signingEndpoint) === null || _a === void 0 ? void 0 : _a.toString()); + const signatureHex = Buffer.from(signature, 'base64').toString('hex'); + const signedQuery = Object.assign({}, queryParams, { + 'X-Goog-Signature': signatureHex, + }); + return signedQuery; + } + catch (err) { + const error = err; + const signingErr = new SigningError(error.message); + signingErr.stack = error.stack; + throw signingErr; + } + }; + return sign(); + } + /** + * Create canonical headers for signing v4 url. + * + * The canonical headers for v4-signing a request demands header names are + * first lowercased, followed by sorting the header names. + * Then, construct the canonical headers part of the request: + * + ":" + Trim() + "\n" + * .. + * + ":" + Trim() + "\n" + * + * @param headers + * @private + */ + getCanonicalHeaders(headers) { + // Sort headers by their lowercased names + const sortedHeaders = (0, util_js_1.objectEntries)(headers) + // Convert header names to lowercase + .map(([headerName, value]) => [ + headerName.toLowerCase(), + value, + ]) + .sort((a, b) => a[0].localeCompare(b[0])); + return sortedHeaders + .filter(([, value]) => value !== undefined) + .map(([headerName, value]) => { + // - Convert Array (multi-valued header) into string, delimited by + // ',' (no space). + // - Trim leading and trailing spaces. + // - Convert sequential (2+) spaces into a single space + const canonicalValue = `${value}`.trim().replace(/\s{2,}/g, ' '); + return `${headerName}:${canonicalValue}\n`; + }) + .join(''); + } + getCanonicalRequest(method, path, query, headers, signedHeaders, contentSha256) { + return [ + method, + path, + query, + headers, + signedHeaders, + contentSha256 || 'UNSIGNED-PAYLOAD', + ].join('\n'); + } + getCanonicalQueryParams(query) { + return (0, util_js_1.objectEntries)(query) + .map(([key, value]) => [(0, util_js_1.encodeURI)(key, true), (0, util_js_1.encodeURI)(value, true)]) + .sort((a, b) => (a[0] < b[0] ? -1 : 1)) + .map(([key, value]) => `${key}=${value}`) + .join('&'); + } + getResourcePath(cname, bucket, file) { + if (cname) { + return '/' + (file || ''); + } + else if (file) { + return `/${bucket}/${file}`; + } + else { + return `/${bucket}`; + } + } + parseExpires(expires, current = new Date()) { + const expiresInMSeconds = new Date(expires).valueOf(); + if (isNaN(expiresInMSeconds)) { + throw new Error(storage_js_1.ExceptionMessages.EXPIRATION_DATE_INVALID); + } + if (expiresInMSeconds < current.valueOf()) { + throw new Error(storage_js_1.ExceptionMessages.EXPIRATION_DATE_PAST); + } + return Math.floor(expiresInMSeconds / 1000); // The API expects seconds. + } + parseAccessibleAt(accessibleAt) { + const accessibleAtInMSeconds = new Date(accessibleAt || new Date()).valueOf(); + if (isNaN(accessibleAtInMSeconds)) { + throw new Error(SignerExceptionMessages.ACCESSIBLE_DATE_INVALID); + } + return Math.floor(accessibleAtInMSeconds / 1000); // The API expects seconds. + } +} +exports.URLSigner = URLSigner; +/** + * Custom error type for errors related to getting signed errors and policies. + * + * @private + */ +class SigningError extends Error { + constructor() { + super(...arguments); + this.name = 'SigningError'; + } +} +exports.SigningError = SigningError; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/storage.d.ts b/node_modules/@google-cloud/storage/build/cjs/src/storage.d.ts new file mode 100644 index 0000000..393b59d --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/storage.d.ts @@ -0,0 +1,730 @@ +import { ApiError, Service, ServiceOptions } from './nodejs-common/index.js'; +import { Readable } from 'stream'; +import { Bucket, BucketMetadata } from './bucket.js'; +import { Channel } from './channel.js'; +import { File } from './file.js'; +import { HmacKey, HmacKeyMetadata, HmacKeyOptions } from './hmacKey.js'; +import { CRC32CValidatorGenerator } from './crc32c.js'; +export interface GetServiceAccountOptions { + userProject?: string; + projectIdentifier?: string; +} +export interface ServiceAccount { + emailAddress?: string; +} +export type GetServiceAccountResponse = [ServiceAccount, unknown]; +export interface GetServiceAccountCallback { + (err: Error | null, serviceAccount?: ServiceAccount, apiResponse?: unknown): void; +} +export interface CreateBucketQuery { + enableObjectRetention: boolean; + predefinedAcl?: 'authenticatedRead' | 'private' | 'projectPrivate' | 'publicRead' | 'publicReadWrite'; + predefinedDefaultObjectAcl?: 'authenticatedRead' | 'bucketOwnerFullControl' | 'bucketOwnerRead' | 'private' | 'projectPrivate' | 'publicRead'; + project: string; + projection?: 'full' | 'noAcl'; + userProject: string; +} +export declare enum IdempotencyStrategy { + RetryAlways = 0, + RetryConditional = 1, + RetryNever = 2 +} +export interface RetryOptions { + retryDelayMultiplier?: number; + totalTimeout?: number; + maxRetryDelay?: number; + autoRetry?: boolean; + maxRetries?: number; + retryableErrorFn?: (err: ApiError) => boolean; + idempotencyStrategy?: IdempotencyStrategy; +} +export interface PreconditionOptions { + ifGenerationMatch?: number | string; + ifGenerationNotMatch?: number | string; + ifMetagenerationMatch?: number | string; + ifMetagenerationNotMatch?: number | string; +} +export interface StorageOptions extends ServiceOptions { + /** + * The API endpoint of the service used to make requests. + * Defaults to `storage.googleapis.com`. + */ + apiEndpoint?: string; + crc32cGenerator?: CRC32CValidatorGenerator; + retryOptions?: RetryOptions; +} +export interface BucketOptions { + crc32cGenerator?: CRC32CValidatorGenerator; + kmsKeyName?: string; + preconditionOpts?: PreconditionOptions; + userProject?: string; + generation?: number; + softDeleted?: boolean; +} +export interface Cors { + maxAgeSeconds?: number; + method?: string[]; + origin?: string[]; + responseHeader?: string[]; +} +interface Versioning { + enabled: boolean; +} +/** + * Custom placement configuration. + * Initially used for dual-region buckets. + **/ +export interface CustomPlacementConfig { + dataLocations?: string[]; +} +export interface AutoclassConfig { + enabled?: boolean; + terminalStorageClass?: 'NEARLINE' | 'ARCHIVE'; +} +export interface CreateBucketRequest extends BucketMetadata { + archive?: boolean; + coldline?: boolean; + dataLocations?: string[]; + dra?: boolean; + enableObjectRetention?: boolean; + multiRegional?: boolean; + nearline?: boolean; + predefinedAcl?: 'authenticatedRead' | 'private' | 'projectPrivate' | 'publicRead' | 'publicReadWrite'; + predefinedDefaultObjectAcl?: 'authenticatedRead' | 'bucketOwnerFullControl' | 'bucketOwnerRead' | 'private' | 'projectPrivate' | 'publicRead'; + projection?: 'full' | 'noAcl'; + regional?: boolean; + requesterPays?: boolean; + rpo?: string; + standard?: boolean; + storageClass?: string; + userProject?: string; + versioning?: Versioning; +} +export type CreateBucketResponse = [Bucket, unknown]; +export interface BucketCallback { + (err: Error | null, bucket?: Bucket | null, apiResponse?: unknown): void; +} +export type GetBucketsResponse = [Bucket[], {}, unknown]; +export interface GetBucketsCallback { + (err: Error | null, buckets: Bucket[], nextQuery?: {}, apiResponse?: unknown): void; +} +export interface GetBucketsRequest { + prefix?: string; + project?: string; + autoPaginate?: boolean; + maxApiCalls?: number; + maxResults?: number; + pageToken?: string; + userProject?: string; + softDeleted?: boolean; + generation?: number; + returnPartialSuccess?: boolean; +} +export interface HmacKeyResourceResponse { + metadata: HmacKeyMetadata; + secret: string; +} +export type CreateHmacKeyResponse = [HmacKey, string, HmacKeyResourceResponse]; +export interface CreateHmacKeyOptions { + projectId?: string; + userProject?: string; +} +export interface CreateHmacKeyCallback { + (err: Error | null, hmacKey?: HmacKey | null, secret?: string | null, apiResponse?: HmacKeyResourceResponse): void; +} +export interface GetHmacKeysOptions { + projectId?: string; + serviceAccountEmail?: string; + showDeletedKeys?: boolean; + autoPaginate?: boolean; + maxApiCalls?: number; + maxResults?: number; + pageToken?: string; + userProject?: string; +} +export interface GetHmacKeysCallback { + (err: Error | null, hmacKeys: HmacKey[] | null, nextQuery?: {}, apiResponse?: unknown): void; +} +export declare enum ExceptionMessages { + EXPIRATION_DATE_INVALID = "The expiration date provided was invalid.", + EXPIRATION_DATE_PAST = "An expiration date cannot be in the past." +} +export declare enum StorageExceptionMessages { + BUCKET_NAME_REQUIRED = "A bucket name is needed to use Cloud Storage.", + BUCKET_NAME_REQUIRED_CREATE = "A name is required to create a bucket.", + HMAC_SERVICE_ACCOUNT = "The first argument must be a service account email to create an HMAC key.", + HMAC_ACCESS_ID = "An access ID is needed to create an HmacKey object." +} +export type GetHmacKeysResponse = [HmacKey[]]; +export declare const PROTOCOL_REGEX: RegExp; +/** + * Default behavior: Automatically retry retriable server errors. + * + * @const {boolean} + */ +export declare const AUTO_RETRY_DEFAULT = true; +/** + * Default behavior: Only attempt to retry retriable errors 3 times. + * + * @const {number} + */ +export declare const MAX_RETRY_DEFAULT = 3; +/** + * Default behavior: Wait twice as long as previous retry before retrying. + * + * @const {number} + */ +export declare const RETRY_DELAY_MULTIPLIER_DEFAULT = 2; +/** + * Default behavior: If the operation doesn't succeed after 600 seconds, + * stop retrying. + * + * @const {number} + */ +export declare const TOTAL_TIMEOUT_DEFAULT = 600; +/** + * Default behavior: Wait no more than 64 seconds between retries. + * + * @const {number} + */ +export declare const MAX_RETRY_DELAY_DEFAULT = 64; +/** + * Returns true if the API request should be retried, given the error that was + * given the first time the request was attempted. + * @const + * @param {error} err - The API error to check if it is appropriate to retry. + * @return {boolean} True if the API request should be retried, false otherwise. + */ +export declare const RETRYABLE_ERR_FN_DEFAULT: (err?: ApiError) => boolean; +/*! Developer Documentation + * + * Invoke this method to create a new Storage object bound with pre-determined + * configuration options. For each object that can be created (e.g., a bucket), + * there is an equivalent static and instance method. While they are classes, + * they can be instantiated without use of the `new` keyword. + */ +/** + * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share objects with other + * users and allow other users to access your buckets and objects. + * + * This object provides constants to refer to the three permission levels that + * can be granted to an entity: + * + * - `gcs.acl.OWNER_ROLE` - ("OWNER") + * - `gcs.acl.READER_ROLE` - ("READER") + * - `gcs.acl.WRITER_ROLE` - ("WRITER") + * + * See {@link https://cloud.google.com/storage/docs/access-control/lists| About Access Control Lists} + * + * @name Storage#acl + * @type {object} + * @property {string} OWNER_ROLE + * @property {string} READER_ROLE + * @property {string} WRITER_ROLE + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const albums = storage.bucket('albums'); + * + * //- + * // Make all of the files currently in a bucket publicly readable. + * //- + * const options = { + * entity: 'allUsers', + * role: storage.acl.READER_ROLE + * }; + * + * albums.acl.add(options, function(err, aclObject) {}); + * + * //- + * // Make any new objects added to a bucket publicly readable. + * //- + * albums.acl.default.add(options, function(err, aclObject) {}); + * + * //- + * // Grant a user ownership permissions to a bucket. + * //- + * albums.acl.add({ + * entity: 'user-useremail@example.com', + * role: storage.acl.OWNER_ROLE + * }, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * albums.acl.add(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ +/** + * Get {@link Bucket} objects for all of the buckets in your project as + * a readable object stream. + * + * @method Storage#getBucketsStream + * @param {GetBucketsRequest} [query] Query object for listing buckets. + * @returns {ReadableStream} A readable stream that emits {@link Bucket} + * instances. + * + * @example + * ``` + * storage.getBucketsStream() + * .on('error', console.error) + * .on('data', function(bucket) { + * // bucket is a Bucket object. + * }) + * .on('end', function() { + * // All buckets retrieved. + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * storage.getBucketsStream() + * .on('data', function(bucket) { + * this.end(); + * }); + * ``` + */ +/** + * Get {@link HmacKey} objects for all of the HMAC keys in the project in a + * readable object stream. + * + * @method Storage#getHmacKeysStream + * @param {GetHmacKeysOptions} [options] Configuration options. + * @returns {ReadableStream} A readable stream that emits {@link HmacKey} + * instances. + * + * @example + * ``` + * storage.getHmacKeysStream() + * .on('error', console.error) + * .on('data', function(hmacKey) { + * // hmacKey is an HmacKey object. + * }) + * .on('end', function() { + * // All HmacKey retrieved. + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * storage.getHmacKeysStream() + * .on('data', function(bucket) { + * this.end(); + * }); + * ``` + */ +/** + *

ACLs

+ * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share files with other users + * and allow other users to access your buckets and files. + * + * To learn more about ACLs, read this overview on + * {@link https://cloud.google.com/storage/docs/access-control| Access Control}. + * + * See {@link https://cloud.google.com/storage/docs/overview| Cloud Storage overview} + * See {@link https://cloud.google.com/storage/docs/access-control| Access Control} + * + * @class + */ +export declare class Storage extends Service { + /** + * {@link Bucket} class. + * + * @name Storage.Bucket + * @see Bucket + * @type {Constructor} + */ + static Bucket: typeof Bucket; + /** + * {@link Channel} class. + * + * @name Storage.Channel + * @see Channel + * @type {Constructor} + */ + static Channel: typeof Channel; + /** + * {@link File} class. + * + * @name Storage.File + * @see File + * @type {Constructor} + */ + static File: typeof File; + /** + * {@link HmacKey} class. + * + * @name Storage.HmacKey + * @see HmacKey + * @type {Constructor} + */ + static HmacKey: typeof HmacKey; + static acl: { + OWNER_ROLE: string; + READER_ROLE: string; + WRITER_ROLE: string; + }; + /** + * Reference to {@link Storage.acl}. + * + * @name Storage#acl + * @see Storage.acl + */ + acl: typeof Storage.acl; + crc32cGenerator: CRC32CValidatorGenerator; + getBucketsStream(): Readable; + getHmacKeysStream(): Readable; + retryOptions: RetryOptions; + /** + * @callback Crc32cGeneratorToStringCallback + * A method returning the CRC32C as a base64-encoded string. + * + * @returns {string} + * + * @example + * Hashing the string 'data' should return 'rth90Q==' + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.toString(); // 'rth90Q==' + * ``` + **/ + /** + * @callback Crc32cGeneratorValidateCallback + * A method validating a base64-encoded CRC32C string. + * + * @param {string} [value] base64-encoded CRC32C string to validate + * @returns {boolean} + * + * @example + * Should return `true` if the value matches, `false` otherwise + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.validate('DkjKuA=='); // false + * crc32c.validate('rth90Q=='); // true + * ``` + **/ + /** + * @callback Crc32cGeneratorUpdateCallback + * A method for passing `Buffer`s for CRC32C generation. + * + * @param {Buffer} [data] data to update CRC32C value with + * @returns {undefined} + * + * @example + * Hashing buffers from 'some ' and 'text\n' + * + * ```js + * const buffer1 = Buffer.from('some '); + * crc32c.update(buffer1); + * + * const buffer2 = Buffer.from('text\n'); + * crc32c.update(buffer2); + * + * crc32c.toString(); // 'DkjKuA==' + * ``` + **/ + /** + * @typedef {object} CRC32CValidator + * @property {Crc32cGeneratorToStringCallback} + * @property {Crc32cGeneratorValidateCallback} + * @property {Crc32cGeneratorUpdateCallback} + */ + /** + * @callback Crc32cGeneratorCallback + * @returns {CRC32CValidator} + */ + /** + * @typedef {object} StorageOptions + * @property {string} [projectId] The project ID from the Google Developer's + * Console, e.g. 'grape-spaceship-123'. We will also check the environment + * variable `GCLOUD_PROJECT` for your project ID. If your app is running + * in an environment which supports {@link + * https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application + * Application Default Credentials}, your project ID will be detected + * automatically. + * @property {string} [keyFilename] Full path to the a .json, .pem, or .p12 key + * downloaded from the Google Developers Console. If you provide a path to + * a JSON file, the `projectId` option above is not necessary. NOTE: .pem and + * .p12 require you to specify the `email` option as well. + * @property {string} [email] Account email address. Required when using a .pem + * or .p12 keyFilename. + * @property {object} [credentials] Credentials object. + * @property {string} [credentials.client_email] + * @property {string} [credentials.private_key] + * @property {object} [retryOptions] Options for customizing retries. Retriable server errors + * will be retried with exponential delay between them dictated by the formula + * max(maxRetryDelay, retryDelayMultiplier*retryNumber) until maxRetries or totalTimeout + * has been reached. Retries will only happen if autoRetry is set to true. + * @property {boolean} [retryOptions.autoRetry=true] Automatically retry requests if the + * response is related to rate limits or certain intermittent server + * errors. We will exponentially backoff subsequent requests by default. + * @property {number} [retryOptions.retryDelayMultiplier = 2] the multiplier by which to + * increase the delay time between the completion of failed requests, and the + * initiation of the subsequent retrying request. + * @property {number} [retryOptions.totalTimeout = 600] The total time, starting from + * when the initial request is sent, after which an error will + * be returned, regardless of the retrying attempts made meanwhile. + * @property {number} [retryOptions.maxRetryDelay = 64] The maximum delay time between requests. + * When this value is reached, ``retryDelayMultiplier`` will no longer be used to + * increase delay time. + * @property {number} [retryOptions.maxRetries=3] Maximum number of automatic retries + * attempted before returning the error. + * @property {function} [retryOptions.retryableErrorFn] Function that returns true if a given + * error should be retried and false otherwise. + * @property {enum} [retryOptions.idempotencyStrategy=IdempotencyStrategy.RetryConditional] Enumeration + * controls how conditionally idempotent operations are retried. Possible values are: RetryAlways - + * will respect other retry settings and attempt to retry conditionally idempotent operations. RetryConditional - + * will retry conditionally idempotent operations if the correct preconditions are set. RetryNever - never + * retry a conditionally idempotent operation. + * @property {string} [userAgent] The value to be prepended to the User-Agent + * header in API requests. + * @property {object} [authClient] `AuthClient` or `GoogleAuth` client to reuse instead of creating a new one. + * @property {number} [timeout] The amount of time in milliseconds to wait per http request before timing out. + * @property {object[]} [interceptors_] Array of custom request interceptors to be returned in the order they were assigned. + * @property {string} [apiEndpoint = storage.google.com] The API endpoint of the service used to make requests. + * @property {boolean} [useAuthWithCustomEndpoint = false] Controls whether or not to use authentication when using a custom endpoint. + * @property {Crc32cGeneratorCallback} [callback] A function that generates a CRC32C Validator. Defaults to {@link CRC32C} + */ + /** + * Constructs the Storage client. + * + * @example + * Create a client that uses Application Default Credentials + * (ADC) + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * ``` + * + * @example + * Create a client with explicit credentials + * ``` + * const storage = new Storage({ + * projectId: 'your-project-id', + * keyFilename: '/path/to/keyfile.json' + * }); + * ``` + * + * @example + * Create a client with credentials passed + * by value as a JavaScript object + * ``` + * const storage = new Storage({ + * projectId: 'your-project-id', + * credentials: { + * type: 'service_account', + * project_id: 'xxxxxxx', + * private_key_id: 'xxxx', + * private_key:'-----BEGIN PRIVATE KEY-----xxxxxxx\n-----END PRIVATE KEY-----\n', + * client_email: 'xxxx', + * client_id: 'xxx', + * auth_uri: 'https://accounts.google.com/o/oauth2/auth', + * token_uri: 'https://oauth2.googleapis.com/token', + * auth_provider_x509_cert_url: 'https://www.googleapis.com/oauth2/v1/certs', + * client_x509_cert_url: 'xxx', + * } + * }); + * ``` + * + * @example + * Create a client with credentials passed + * by loading a JSON file directly from disk + * ``` + * const storage = new Storage({ + * projectId: 'your-project-id', + * credentials: require('/path/to-keyfile.json') + * }); + * ``` + * + * @example + * Create a client with an `AuthClient` (e.g. `DownscopedClient`) + * ``` + * const {DownscopedClient} = require('google-auth-library'); + * const authClient = new DownscopedClient({...}); + * + * const storage = new Storage({authClient}); + * ``` + * + * Additional samples: + * - https://github.com/googleapis/google-auth-library-nodejs#sample-usage-1 + * - https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/downscopedclient.js + * + * @param {StorageOptions} [options] Configuration options. + */ + constructor(options?: StorageOptions); + private static sanitizeEndpoint; + /** + * Get a reference to a Cloud Storage bucket. + * + * @param {string} name Name of the bucket. + * @param {object} [options] Configuration object. + * @param {string} [options.kmsKeyName] A Cloud KMS key that will be used to + * encrypt objects inserted into this bucket, if no encryption method is + * specified. + * @param {string} [options.userProject] User project to be billed for all + * requests made from this Bucket object. + * @returns {Bucket} + * @see Bucket + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const albums = storage.bucket('albums'); + * const photos = storage.bucket('photos'); + * ``` + */ + bucket(name: string, options?: BucketOptions): Bucket; + /** + * Reference a channel to receive notifications about changes to your bucket. + * + * @param {string} id The ID of the channel. + * @param {string} resourceId The resource ID of the channel. + * @returns {Channel} + * @see Channel + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const channel = storage.channel('id', 'resource-id'); + * ``` + */ + channel(id: string, resourceId: string): Channel; + createBucket(name: string, metadata?: CreateBucketRequest): Promise; + createBucket(name: string, callback: BucketCallback): void; + createBucket(name: string, metadata: CreateBucketRequest, callback: BucketCallback): void; + createBucket(name: string, metadata: CreateBucketRequest, callback: BucketCallback): void; + createHmacKey(serviceAccountEmail: string, options?: CreateHmacKeyOptions): Promise; + createHmacKey(serviceAccountEmail: string, callback: CreateHmacKeyCallback): void; + createHmacKey(serviceAccountEmail: string, options: CreateHmacKeyOptions, callback: CreateHmacKeyCallback): void; + getBuckets(options?: GetBucketsRequest): Promise; + getBuckets(options: GetBucketsRequest, callback: GetBucketsCallback): void; + getBuckets(callback: GetBucketsCallback): void; + /** + * Query object for listing HMAC keys. + * + * @typedef {object} GetHmacKeysOptions + * @property {string} [projectId] The project ID of the project that owns + * the service account of the requested HMAC key. If not provided, + * the project ID used to instantiate the Storage client will be used. + * @property {string} [serviceAccountEmail] If present, only HMAC keys for the + * given service account are returned. + * @property {boolean} [showDeletedKeys=false] If true, include keys in the DELETE + * state. Default is false. + * @property {boolean} [autoPaginate=true] Have pagination handled + * automatically. + * @property {number} [maxApiCalls] Maximum number of API calls to make. + * @property {number} [maxResults] Maximum number of items plus prefixes to + * return per call. + * Note: By default will handle pagination automatically + * if more than 1 page worth of results are requested per call. + * When `autoPaginate` is set to `false` the smaller of `maxResults` + * or 1 page of results will be returned per call. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @property {string} [userProject] This parameter is currently ignored. + */ + /** + * @typedef {array} GetHmacKeysResponse + * @property {HmacKey[]} 0 Array of {@link HmacKey} instances. + * @param {object} nextQuery 1 A query object to receive more results. + * @param {object} apiResponse 2 The full API response. + */ + /** + * @callback GetHmacKeysCallback + * @param {?Error} err Request error, if any. + * @param {HmacKey[]} hmacKeys Array of {@link HmacKey} instances. + * @param {object} nextQuery A query object to receive more results. + * @param {object} apiResponse The full API response. + */ + /** + * Retrieves a list of HMAC keys matching the criteria. + * + * The authenticated user must have storage.hmacKeys.list permission for the project in which the key exists. + * + * @param {GetHmacKeysOption} options Configuration options. + * @param {GetHmacKeysCallback} callback Callback function. + * @return {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * storage.getHmacKeys(function(err, hmacKeys) { + * if (!err) { + * // hmacKeys is an array of HmacKey objects. + * } + * }); + * + * //- + * // To control how many API requests are made and page through the results + * // manually, set `autoPaginate` to `false`. + * //- + * const callback = function(err, hmacKeys, nextQuery, apiResponse) { + * if (nextQuery) { + * // More results exist. + * storage.getHmacKeys(nextQuery, callback); + * } + * + * // The `metadata` property is populated for you with the metadata at the + * // time of fetching. + * hmacKeys[0].metadata; + * }; + * + * storage.getHmacKeys({ + * autoPaginate: false + * }, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * storage.getHmacKeys().then(function(data) { + * const hmacKeys = data[0]; + * }); + * ``` + */ + getHmacKeys(options?: GetHmacKeysOptions): Promise; + getHmacKeys(callback: GetHmacKeysCallback): void; + getHmacKeys(options: GetHmacKeysOptions, callback: GetHmacKeysCallback): void; + getServiceAccount(options?: GetServiceAccountOptions): Promise; + getServiceAccount(options?: GetServiceAccountOptions): Promise; + getServiceAccount(options: GetServiceAccountOptions, callback: GetServiceAccountCallback): void; + getServiceAccount(callback: GetServiceAccountCallback): void; + /** + * Get a reference to an HmacKey object. + * Note: this does not fetch the HMAC key's metadata. Use HmacKey#get() to + * retrieve and populate the metadata. + * + * To get a reference to an HMAC key that's not created for a service + * account in the same project used to instantiate the Storage client, + * supply the project's ID as `projectId` in the `options` argument. + * + * @param {string} accessId The HMAC key's access ID. + * @param {HmacKeyOptions} options HmacKey constructor options. + * @returns {HmacKey} + * @see HmacKey + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const hmacKey = storage.hmacKey('ACCESS_ID'); + * ``` + */ + hmacKey(accessId: string, options?: HmacKeyOptions): HmacKey; +} +export {}; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/storage.js b/node_modules/@google-cloud/storage/build/cjs/src/storage.js new file mode 100644 index 0000000..c4b13c8 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/storage.js @@ -0,0 +1,1175 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Storage = exports.RETRYABLE_ERR_FN_DEFAULT = exports.MAX_RETRY_DELAY_DEFAULT = exports.TOTAL_TIMEOUT_DEFAULT = exports.RETRY_DELAY_MULTIPLIER_DEFAULT = exports.MAX_RETRY_DEFAULT = exports.AUTO_RETRY_DEFAULT = exports.PROTOCOL_REGEX = exports.StorageExceptionMessages = exports.ExceptionMessages = exports.IdempotencyStrategy = void 0; +const index_js_1 = require("./nodejs-common/index.js"); +const paginator_1 = require("@google-cloud/paginator"); +const promisify_1 = require("@google-cloud/promisify"); +const stream_1 = require("stream"); +const bucket_js_1 = require("./bucket.js"); +const channel_js_1 = require("./channel.js"); +const file_js_1 = require("./file.js"); +const util_js_1 = require("./util.js"); +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore +const package_json_helper_cjs_1 = require("./package-json-helper.cjs"); +const hmacKey_js_1 = require("./hmacKey.js"); +const crc32c_js_1 = require("./crc32c.js"); +const google_auth_library_1 = require("google-auth-library"); +var IdempotencyStrategy; +(function (IdempotencyStrategy) { + IdempotencyStrategy[IdempotencyStrategy["RetryAlways"] = 0] = "RetryAlways"; + IdempotencyStrategy[IdempotencyStrategy["RetryConditional"] = 1] = "RetryConditional"; + IdempotencyStrategy[IdempotencyStrategy["RetryNever"] = 2] = "RetryNever"; +})(IdempotencyStrategy || (exports.IdempotencyStrategy = IdempotencyStrategy = {})); +var ExceptionMessages; +(function (ExceptionMessages) { + ExceptionMessages["EXPIRATION_DATE_INVALID"] = "The expiration date provided was invalid."; + ExceptionMessages["EXPIRATION_DATE_PAST"] = "An expiration date cannot be in the past."; +})(ExceptionMessages || (exports.ExceptionMessages = ExceptionMessages = {})); +var StorageExceptionMessages; +(function (StorageExceptionMessages) { + StorageExceptionMessages["BUCKET_NAME_REQUIRED"] = "A bucket name is needed to use Cloud Storage."; + StorageExceptionMessages["BUCKET_NAME_REQUIRED_CREATE"] = "A name is required to create a bucket."; + StorageExceptionMessages["HMAC_SERVICE_ACCOUNT"] = "The first argument must be a service account email to create an HMAC key."; + StorageExceptionMessages["HMAC_ACCESS_ID"] = "An access ID is needed to create an HmacKey object."; +})(StorageExceptionMessages || (exports.StorageExceptionMessages = StorageExceptionMessages = {})); +exports.PROTOCOL_REGEX = /^(\w*):\/\//; +/** + * Default behavior: Automatically retry retriable server errors. + * + * @const {boolean} + */ +exports.AUTO_RETRY_DEFAULT = true; +/** + * Default behavior: Only attempt to retry retriable errors 3 times. + * + * @const {number} + */ +exports.MAX_RETRY_DEFAULT = 3; +/** + * Default behavior: Wait twice as long as previous retry before retrying. + * + * @const {number} + */ +exports.RETRY_DELAY_MULTIPLIER_DEFAULT = 2; +/** + * Default behavior: If the operation doesn't succeed after 600 seconds, + * stop retrying. + * + * @const {number} + */ +exports.TOTAL_TIMEOUT_DEFAULT = 600; +/** + * Default behavior: Wait no more than 64 seconds between retries. + * + * @const {number} + */ +exports.MAX_RETRY_DELAY_DEFAULT = 64; +/** + * Default behavior: Retry conditionally idempotent operations if correct preconditions are set. + * + * @const {enum} + * @private + */ +const IDEMPOTENCY_STRATEGY_DEFAULT = IdempotencyStrategy.RetryConditional; +/** + * Returns true if the API request should be retried, given the error that was + * given the first time the request was attempted. + * @const + * @param {error} err - The API error to check if it is appropriate to retry. + * @return {boolean} True if the API request should be retried, false otherwise. + */ +const RETRYABLE_ERR_FN_DEFAULT = function (err) { + var _a; + const isConnectionProblem = (reason) => { + return (reason.includes('eai_again') || // DNS lookup error + reason === 'econnreset' || + reason === 'unexpected connection closure' || + reason === 'epipe' || + reason === 'socket connection timeout'); + }; + if (err) { + if ([408, 429, 500, 502, 503, 504].indexOf(err.code) !== -1) { + return true; + } + if (typeof err.code === 'string') { + if (['408', '429', '500', '502', '503', '504'].indexOf(err.code) !== -1) { + return true; + } + const reason = err.code.toLowerCase(); + if (isConnectionProblem(reason)) { + return true; + } + } + if (err.errors) { + for (const e of err.errors) { + const reason = (_a = e === null || e === void 0 ? void 0 : e.reason) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase(); + if (reason && isConnectionProblem(reason)) { + return true; + } + } + } + } + return false; +}; +exports.RETRYABLE_ERR_FN_DEFAULT = RETRYABLE_ERR_FN_DEFAULT; +/*! Developer Documentation + * + * Invoke this method to create a new Storage object bound with pre-determined + * configuration options. For each object that can be created (e.g., a bucket), + * there is an equivalent static and instance method. While they are classes, + * they can be instantiated without use of the `new` keyword. + */ +/** + * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share objects with other + * users and allow other users to access your buckets and objects. + * + * This object provides constants to refer to the three permission levels that + * can be granted to an entity: + * + * - `gcs.acl.OWNER_ROLE` - ("OWNER") + * - `gcs.acl.READER_ROLE` - ("READER") + * - `gcs.acl.WRITER_ROLE` - ("WRITER") + * + * See {@link https://cloud.google.com/storage/docs/access-control/lists| About Access Control Lists} + * + * @name Storage#acl + * @type {object} + * @property {string} OWNER_ROLE + * @property {string} READER_ROLE + * @property {string} WRITER_ROLE + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const albums = storage.bucket('albums'); + * + * //- + * // Make all of the files currently in a bucket publicly readable. + * //- + * const options = { + * entity: 'allUsers', + * role: storage.acl.READER_ROLE + * }; + * + * albums.acl.add(options, function(err, aclObject) {}); + * + * //- + * // Make any new objects added to a bucket publicly readable. + * //- + * albums.acl.default.add(options, function(err, aclObject) {}); + * + * //- + * // Grant a user ownership permissions to a bucket. + * //- + * albums.acl.add({ + * entity: 'user-useremail@example.com', + * role: storage.acl.OWNER_ROLE + * }, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * albums.acl.add(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ +/** + * Get {@link Bucket} objects for all of the buckets in your project as + * a readable object stream. + * + * @method Storage#getBucketsStream + * @param {GetBucketsRequest} [query] Query object for listing buckets. + * @returns {ReadableStream} A readable stream that emits {@link Bucket} + * instances. + * + * @example + * ``` + * storage.getBucketsStream() + * .on('error', console.error) + * .on('data', function(bucket) { + * // bucket is a Bucket object. + * }) + * .on('end', function() { + * // All buckets retrieved. + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * storage.getBucketsStream() + * .on('data', function(bucket) { + * this.end(); + * }); + * ``` + */ +/** + * Get {@link HmacKey} objects for all of the HMAC keys in the project in a + * readable object stream. + * + * @method Storage#getHmacKeysStream + * @param {GetHmacKeysOptions} [options] Configuration options. + * @returns {ReadableStream} A readable stream that emits {@link HmacKey} + * instances. + * + * @example + * ``` + * storage.getHmacKeysStream() + * .on('error', console.error) + * .on('data', function(hmacKey) { + * // hmacKey is an HmacKey object. + * }) + * .on('end', function() { + * // All HmacKey retrieved. + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * storage.getHmacKeysStream() + * .on('data', function(bucket) { + * this.end(); + * }); + * ``` + */ +/** + *

ACLs

+ * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share files with other users + * and allow other users to access your buckets and files. + * + * To learn more about ACLs, read this overview on + * {@link https://cloud.google.com/storage/docs/access-control| Access Control}. + * + * See {@link https://cloud.google.com/storage/docs/overview| Cloud Storage overview} + * See {@link https://cloud.google.com/storage/docs/access-control| Access Control} + * + * @class + */ +class Storage extends index_js_1.Service { + getBucketsStream() { + // placeholder body, overwritten in constructor + return new stream_1.Readable(); + } + getHmacKeysStream() { + // placeholder body, overwritten in constructor + return new stream_1.Readable(); + } + /** + * @callback Crc32cGeneratorToStringCallback + * A method returning the CRC32C as a base64-encoded string. + * + * @returns {string} + * + * @example + * Hashing the string 'data' should return 'rth90Q==' + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.toString(); // 'rth90Q==' + * ``` + **/ + /** + * @callback Crc32cGeneratorValidateCallback + * A method validating a base64-encoded CRC32C string. + * + * @param {string} [value] base64-encoded CRC32C string to validate + * @returns {boolean} + * + * @example + * Should return `true` if the value matches, `false` otherwise + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.validate('DkjKuA=='); // false + * crc32c.validate('rth90Q=='); // true + * ``` + **/ + /** + * @callback Crc32cGeneratorUpdateCallback + * A method for passing `Buffer`s for CRC32C generation. + * + * @param {Buffer} [data] data to update CRC32C value with + * @returns {undefined} + * + * @example + * Hashing buffers from 'some ' and 'text\n' + * + * ```js + * const buffer1 = Buffer.from('some '); + * crc32c.update(buffer1); + * + * const buffer2 = Buffer.from('text\n'); + * crc32c.update(buffer2); + * + * crc32c.toString(); // 'DkjKuA==' + * ``` + **/ + /** + * @typedef {object} CRC32CValidator + * @property {Crc32cGeneratorToStringCallback} + * @property {Crc32cGeneratorValidateCallback} + * @property {Crc32cGeneratorUpdateCallback} + */ + /** + * @callback Crc32cGeneratorCallback + * @returns {CRC32CValidator} + */ + /** + * @typedef {object} StorageOptions + * @property {string} [projectId] The project ID from the Google Developer's + * Console, e.g. 'grape-spaceship-123'. We will also check the environment + * variable `GCLOUD_PROJECT` for your project ID. If your app is running + * in an environment which supports {@link + * https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application + * Application Default Credentials}, your project ID will be detected + * automatically. + * @property {string} [keyFilename] Full path to the a .json, .pem, or .p12 key + * downloaded from the Google Developers Console. If you provide a path to + * a JSON file, the `projectId` option above is not necessary. NOTE: .pem and + * .p12 require you to specify the `email` option as well. + * @property {string} [email] Account email address. Required when using a .pem + * or .p12 keyFilename. + * @property {object} [credentials] Credentials object. + * @property {string} [credentials.client_email] + * @property {string} [credentials.private_key] + * @property {object} [retryOptions] Options for customizing retries. Retriable server errors + * will be retried with exponential delay between them dictated by the formula + * max(maxRetryDelay, retryDelayMultiplier*retryNumber) until maxRetries or totalTimeout + * has been reached. Retries will only happen if autoRetry is set to true. + * @property {boolean} [retryOptions.autoRetry=true] Automatically retry requests if the + * response is related to rate limits or certain intermittent server + * errors. We will exponentially backoff subsequent requests by default. + * @property {number} [retryOptions.retryDelayMultiplier = 2] the multiplier by which to + * increase the delay time between the completion of failed requests, and the + * initiation of the subsequent retrying request. + * @property {number} [retryOptions.totalTimeout = 600] The total time, starting from + * when the initial request is sent, after which an error will + * be returned, regardless of the retrying attempts made meanwhile. + * @property {number} [retryOptions.maxRetryDelay = 64] The maximum delay time between requests. + * When this value is reached, ``retryDelayMultiplier`` will no longer be used to + * increase delay time. + * @property {number} [retryOptions.maxRetries=3] Maximum number of automatic retries + * attempted before returning the error. + * @property {function} [retryOptions.retryableErrorFn] Function that returns true if a given + * error should be retried and false otherwise. + * @property {enum} [retryOptions.idempotencyStrategy=IdempotencyStrategy.RetryConditional] Enumeration + * controls how conditionally idempotent operations are retried. Possible values are: RetryAlways - + * will respect other retry settings and attempt to retry conditionally idempotent operations. RetryConditional - + * will retry conditionally idempotent operations if the correct preconditions are set. RetryNever - never + * retry a conditionally idempotent operation. + * @property {string} [userAgent] The value to be prepended to the User-Agent + * header in API requests. + * @property {object} [authClient] `AuthClient` or `GoogleAuth` client to reuse instead of creating a new one. + * @property {number} [timeout] The amount of time in milliseconds to wait per http request before timing out. + * @property {object[]} [interceptors_] Array of custom request interceptors to be returned in the order they were assigned. + * @property {string} [apiEndpoint = storage.google.com] The API endpoint of the service used to make requests. + * @property {boolean} [useAuthWithCustomEndpoint = false] Controls whether or not to use authentication when using a custom endpoint. + * @property {Crc32cGeneratorCallback} [callback] A function that generates a CRC32C Validator. Defaults to {@link CRC32C} + */ + /** + * Constructs the Storage client. + * + * @example + * Create a client that uses Application Default Credentials + * (ADC) + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * ``` + * + * @example + * Create a client with explicit credentials + * ``` + * const storage = new Storage({ + * projectId: 'your-project-id', + * keyFilename: '/path/to/keyfile.json' + * }); + * ``` + * + * @example + * Create a client with credentials passed + * by value as a JavaScript object + * ``` + * const storage = new Storage({ + * projectId: 'your-project-id', + * credentials: { + * type: 'service_account', + * project_id: 'xxxxxxx', + * private_key_id: 'xxxx', + * private_key:'-----BEGIN PRIVATE KEY-----xxxxxxx\n-----END PRIVATE KEY-----\n', + * client_email: 'xxxx', + * client_id: 'xxx', + * auth_uri: 'https://accounts.google.com/o/oauth2/auth', + * token_uri: 'https://oauth2.googleapis.com/token', + * auth_provider_x509_cert_url: 'https://www.googleapis.com/oauth2/v1/certs', + * client_x509_cert_url: 'xxx', + * } + * }); + * ``` + * + * @example + * Create a client with credentials passed + * by loading a JSON file directly from disk + * ``` + * const storage = new Storage({ + * projectId: 'your-project-id', + * credentials: require('/path/to-keyfile.json') + * }); + * ``` + * + * @example + * Create a client with an `AuthClient` (e.g. `DownscopedClient`) + * ``` + * const {DownscopedClient} = require('google-auth-library'); + * const authClient = new DownscopedClient({...}); + * + * const storage = new Storage({authClient}); + * ``` + * + * Additional samples: + * - https://github.com/googleapis/google-auth-library-nodejs#sample-usage-1 + * - https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/downscopedclient.js + * + * @param {StorageOptions} [options] Configuration options. + */ + constructor(options = {}) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; + const universe = options.universeDomain || google_auth_library_1.DEFAULT_UNIVERSE; + let apiEndpoint = `https://storage.${universe}`; + let customEndpoint = false; + // Note: EMULATOR_HOST is an experimental configuration variable. Use apiEndpoint instead. + const EMULATOR_HOST = process.env.STORAGE_EMULATOR_HOST; + if (typeof EMULATOR_HOST === 'string') { + apiEndpoint = Storage.sanitizeEndpoint(EMULATOR_HOST); + customEndpoint = true; + } + if (options.apiEndpoint && options.apiEndpoint !== apiEndpoint) { + apiEndpoint = Storage.sanitizeEndpoint(options.apiEndpoint); + customEndpoint = true; + } + options = Object.assign({}, options, { apiEndpoint }); + // Note: EMULATOR_HOST is an experimental configuration variable. Use apiEndpoint instead. + const baseUrl = EMULATOR_HOST || `${options.apiEndpoint}/storage/v1`; + const config = { + apiEndpoint: options.apiEndpoint, + retryOptions: { + autoRetry: ((_a = options.retryOptions) === null || _a === void 0 ? void 0 : _a.autoRetry) !== undefined + ? (_b = options.retryOptions) === null || _b === void 0 ? void 0 : _b.autoRetry + : exports.AUTO_RETRY_DEFAULT, + maxRetries: ((_c = options.retryOptions) === null || _c === void 0 ? void 0 : _c.maxRetries) + ? (_d = options.retryOptions) === null || _d === void 0 ? void 0 : _d.maxRetries + : exports.MAX_RETRY_DEFAULT, + retryDelayMultiplier: ((_e = options.retryOptions) === null || _e === void 0 ? void 0 : _e.retryDelayMultiplier) + ? (_f = options.retryOptions) === null || _f === void 0 ? void 0 : _f.retryDelayMultiplier + : exports.RETRY_DELAY_MULTIPLIER_DEFAULT, + totalTimeout: ((_g = options.retryOptions) === null || _g === void 0 ? void 0 : _g.totalTimeout) + ? (_h = options.retryOptions) === null || _h === void 0 ? void 0 : _h.totalTimeout + : exports.TOTAL_TIMEOUT_DEFAULT, + maxRetryDelay: ((_j = options.retryOptions) === null || _j === void 0 ? void 0 : _j.maxRetryDelay) + ? (_k = options.retryOptions) === null || _k === void 0 ? void 0 : _k.maxRetryDelay + : exports.MAX_RETRY_DELAY_DEFAULT, + retryableErrorFn: ((_l = options.retryOptions) === null || _l === void 0 ? void 0 : _l.retryableErrorFn) + ? (_m = options.retryOptions) === null || _m === void 0 ? void 0 : _m.retryableErrorFn + : exports.RETRYABLE_ERR_FN_DEFAULT, + idempotencyStrategy: ((_o = options.retryOptions) === null || _o === void 0 ? void 0 : _o.idempotencyStrategy) !== undefined + ? (_p = options.retryOptions) === null || _p === void 0 ? void 0 : _p.idempotencyStrategy + : IDEMPOTENCY_STRATEGY_DEFAULT, + }, + baseUrl, + customEndpoint, + useAuthWithCustomEndpoint: options === null || options === void 0 ? void 0 : options.useAuthWithCustomEndpoint, + projectIdRequired: false, + scopes: [ + 'https://www.googleapis.com/auth/iam', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/devstorage.full_control', + ], + packageJson: (0, package_json_helper_cjs_1.getPackageJSON)(), + }; + super(config, options); + /** + * Reference to {@link Storage.acl}. + * + * @name Storage#acl + * @see Storage.acl + */ + this.acl = Storage.acl; + this.crc32cGenerator = + options.crc32cGenerator || crc32c_js_1.CRC32C_DEFAULT_VALIDATOR_GENERATOR; + this.retryOptions = config.retryOptions; + this.getBucketsStream = paginator_1.paginator.streamify('getBuckets'); + this.getHmacKeysStream = paginator_1.paginator.streamify('getHmacKeys'); + } + static sanitizeEndpoint(url) { + if (!exports.PROTOCOL_REGEX.test(url)) { + url = `https://${url}`; + } + return url.replace(/\/+$/, ''); // Remove trailing slashes + } + /** + * Get a reference to a Cloud Storage bucket. + * + * @param {string} name Name of the bucket. + * @param {object} [options] Configuration object. + * @param {string} [options.kmsKeyName] A Cloud KMS key that will be used to + * encrypt objects inserted into this bucket, if no encryption method is + * specified. + * @param {string} [options.userProject] User project to be billed for all + * requests made from this Bucket object. + * @returns {Bucket} + * @see Bucket + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const albums = storage.bucket('albums'); + * const photos = storage.bucket('photos'); + * ``` + */ + bucket(name, options) { + if (!name) { + throw new Error(StorageExceptionMessages.BUCKET_NAME_REQUIRED); + } + return new bucket_js_1.Bucket(this, name, options); + } + /** + * Reference a channel to receive notifications about changes to your bucket. + * + * @param {string} id The ID of the channel. + * @param {string} resourceId The resource ID of the channel. + * @returns {Channel} + * @see Channel + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const channel = storage.channel('id', 'resource-id'); + * ``` + */ + channel(id, resourceId) { + return new channel_js_1.Channel(this, id, resourceId); + } + /** + * @typedef {array} CreateBucketResponse + * @property {Bucket} 0 The new {@link Bucket}. + * @property {object} 1 The full API response. + */ + /** + * @callback CreateBucketCallback + * @param {?Error} err Request error, if any. + * @param {Bucket} bucket The new {@link Bucket}. + * @param {object} apiResponse The full API response. + */ + /** + * Metadata to set for the bucket. + * + * @typedef {object} CreateBucketRequest + * @property {boolean} [archive=false] Specify the storage class as Archive. + * @property {object} [autoclass.enabled=false] Specify whether Autoclass is + * enabled for the bucket. + * @property {object} [autoclass.terminalStorageClass='NEARLINE'] The storage class that objects in an Autoclass bucket eventually transition to if + * they are not read for a certain length of time. Valid values are NEARLINE and ARCHIVE. + * @property {boolean} [coldline=false] Specify the storage class as Coldline. + * @property {Cors[]} [cors=[]] Specify the CORS configuration to use. + * @property {CustomPlacementConfig} [customPlacementConfig={}] Specify the bucket's regions for dual-region buckets. + * For more information, see {@link https://cloud.google.com/storage/docs/locations| Bucket Locations}. + * @property {boolean} [dra=false] Specify the storage class as Durable Reduced + * Availability. + * @property {boolean} [enableObjectRetention=false] Specify whether or not object retention should be enabled on this bucket. + * @property {object} [hierarchicalNamespace.enabled=false] Specify whether or not to enable hierarchical namespace on this bucket. + * @property {string} [location] Specify the bucket's location. If specifying + * a dual-region, the `customPlacementConfig` property should be set in conjunction. + * For more information, see {@link https://cloud.google.com/storage/docs/locations| Bucket Locations}. + * @property {boolean} [multiRegional=false] Specify the storage class as + * Multi-Regional. + * @property {boolean} [nearline=false] Specify the storage class as Nearline. + * @property {boolean} [regional=false] Specify the storage class as Regional. + * @property {boolean} [requesterPays=false] Force the use of the User Project metadata field to assign operational + * costs when an operation is made on a Bucket and its objects. + * @property {string} [rpo] For dual-region buckets, controls whether turbo + * replication is enabled (`ASYNC_TURBO`) or disabled (`DEFAULT`). + * @property {boolean} [standard=true] Specify the storage class as Standard. + * @property {string} [storageClass] The new storage class. (`standard`, + * `nearline`, `coldline`, or `archive`). + * **Note:** The storage classes `multi_regional`, `regional`, and + * `durable_reduced_availability` are now legacy and will be deprecated in + * the future. + * @property {Versioning} [versioning=undefined] Specify the versioning status. + * @property {string} [userProject] The ID of the project which will be billed + * for the request. + */ + /** + * Create a bucket. + * + * Cloud Storage uses a flat namespace, so you can't create a bucket with + * a name that is already in use. For more information, see + * {@link https://cloud.google.com/storage/docs/bucketnaming.html#requirements| Bucket Naming Guidelines}. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/insert| Buckets: insert API Documentation} + * See {@link https://cloud.google.com/storage/docs/storage-classes| Storage Classes} + * + * @param {string} name Name of the bucket to create. + * @param {CreateBucketRequest} [metadata] Metadata to set for the bucket. + * @param {CreateBucketCallback} [callback] Callback function. + * @returns {Promise} + * @throws {Error} If a name is not provided. + * @see Bucket#create + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const callback = function(err, bucket, apiResponse) { + * // `bucket` is a Bucket object. + * }; + * + * storage.createBucket('new-bucket', callback); + * + * //- + * // Create a bucket in a specific location and region. See the + * // Official JSON API docs for complete details on the `location` + * option. + * // + * //- + * const metadata = { + * location: 'US-CENTRAL1', + * regional: true + * }; + * + * storage.createBucket('new-bucket', metadata, callback); + * + * //- + * // Create a bucket with a retention policy of 6 months. + * //- + * const metadata = { + * retentionPolicy: { + * retentionPeriod: 15780000 // 6 months in seconds. + * } + * }; + * + * storage.createBucket('new-bucket', metadata, callback); + * + * //- + * // Enable versioning on a new bucket. + * //- + * const metadata = { + * versioning: { + * enabled: true + * } + * }; + * + * storage.createBucket('new-bucket', metadata, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * storage.createBucket('new-bucket').then(function(data) { + * const bucket = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/buckets.js + * region_tag:storage_create_bucket + * Another example: + */ + createBucket(name, metadataOrCallback, callback) { + if (!name) { + throw new Error(StorageExceptionMessages.BUCKET_NAME_REQUIRED_CREATE); + } + let metadata; + if (!callback) { + callback = metadataOrCallback; + metadata = {}; + } + else { + metadata = metadataOrCallback; + } + const body = { + ...metadata, + name, + }; + const storageClasses = { + archive: 'ARCHIVE', + coldline: 'COLDLINE', + dra: 'DURABLE_REDUCED_AVAILABILITY', + multiRegional: 'MULTI_REGIONAL', + nearline: 'NEARLINE', + regional: 'REGIONAL', + standard: 'STANDARD', + }; + const storageClassKeys = Object.keys(storageClasses); + for (const storageClass of storageClassKeys) { + if (body[storageClass]) { + if (metadata.storageClass && metadata.storageClass !== storageClass) { + throw new Error(`Both \`${storageClass}\` and \`storageClass\` were provided.`); + } + body.storageClass = storageClasses[storageClass]; + delete body[storageClass]; + } + } + if (body.requesterPays) { + body.billing = { + requesterPays: body.requesterPays, + }; + delete body.requesterPays; + } + const query = { + project: this.projectId, + }; + if (body.userProject) { + query.userProject = body.userProject; + delete body.userProject; + } + if (body.enableObjectRetention) { + query.enableObjectRetention = body.enableObjectRetention; + delete body.enableObjectRetention; + } + if (body.predefinedAcl) { + query.predefinedAcl = body.predefinedAcl; + delete body.predefinedAcl; + } + if (body.predefinedDefaultObjectAcl) { + query.predefinedDefaultObjectAcl = body.predefinedDefaultObjectAcl; + delete body.predefinedDefaultObjectAcl; + } + if (body.projection) { + query.projection = body.projection; + delete body.projection; + } + this.request({ + method: 'POST', + uri: '/b', + qs: query, + json: body, + }, (err, resp) => { + if (err) { + callback(err, null, resp); + return; + } + const bucket = this.bucket(name); + bucket.metadata = resp; + callback(null, bucket, resp); + }); + } + /** + * @typedef {object} CreateHmacKeyOptions + * @property {string} [projectId] The project ID of the project that owns + * the service account of the requested HMAC key. If not provided, + * the project ID used to instantiate the Storage client will be used. + * @property {string} [userProject] This parameter is currently ignored. + */ + /** + * @typedef {object} HmacKeyMetadata + * @property {string} accessId The access id identifies which HMAC key was + * used to sign a request when authenticating with HMAC. + * @property {string} etag Used to perform a read-modify-write of the key. + * @property {string} id The resource name of the HMAC key. + * @property {string} projectId The project ID. + * @property {string} serviceAccountEmail The service account's email this + * HMAC key is created for. + * @property {string} state The state of this HMAC key. One of "ACTIVE", + * "INACTIVE" or "DELETED". + * @property {string} timeCreated The creation time of the HMAC key in + * RFC 3339 format. + * @property {string} [updated] The time this HMAC key was last updated in + * RFC 3339 format. + */ + /** + * @typedef {array} CreateHmacKeyResponse + * @property {HmacKey} 0 The HmacKey instance created from API response. + * @property {string} 1 The HMAC key's secret used to access the XML API. + * @property {object} 3 The raw API response. + */ + /** + * @callback CreateHmacKeyCallback Callback function. + * @param {?Error} err Request error, if any. + * @param {HmacKey} hmacKey The HmacKey instance created from API response. + * @param {string} secret The HMAC key's secret used to access the XML API. + * @param {object} apiResponse The raw API response. + */ + /** + * Create an HMAC key associated with an service account to authenticate + * requests to the Cloud Storage XML API. + * + * See {@link https://cloud.google.com/storage/docs/authentication/hmackeys| HMAC keys documentation} + * + * @param {string} serviceAccountEmail The service account's email address + * with which the HMAC key is created for. + * @param {CreateHmacKeyCallback} [callback] Callback function. + * @return {Promise} + * + * @example + * ``` + * const {Storage} = require('google-cloud/storage'); + * const storage = new Storage(); + * + * // Replace with your service account's email address + * const serviceAccountEmail = + * 'my-service-account@appspot.gserviceaccount.com'; + * + * storage.createHmacKey(serviceAccountEmail, function(err, hmacKey, secret) { + * if (!err) { + * // Securely store the secret for use with the XML API. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * storage.createHmacKey(serviceAccountEmail) + * .then((response) => { + * const hmacKey = response[0]; + * const secret = response[1]; + * // Securely store the secret for use with the XML API. + * }); + * ``` + */ + createHmacKey(serviceAccountEmail, optionsOrCb, cb) { + if (typeof serviceAccountEmail !== 'string') { + throw new Error(StorageExceptionMessages.HMAC_SERVICE_ACCOUNT); + } + const { options, callback } = (0, util_js_1.normalize)(optionsOrCb, cb); + const query = Object.assign({}, options, { serviceAccountEmail }); + const projectId = query.projectId || this.projectId; + delete query.projectId; + this.request({ + method: 'POST', + uri: `/projects/${projectId}/hmacKeys`, + qs: query, + maxRetries: 0, //explicitly set this value since this is a non-idempotent function + }, (err, resp) => { + if (err) { + callback(err, null, null, resp); + return; + } + const metadata = resp.metadata; + const hmacKey = this.hmacKey(metadata.accessId, { + projectId: metadata.projectId, + }); + hmacKey.metadata = resp.metadata; + callback(null, hmacKey, resp.secret, resp); + }); + } + /** + * Query object for listing buckets. + * + * @typedef {object} GetBucketsRequest + * @property {boolean} [autoPaginate=true] Have pagination handled + * automatically. + * @property {number} [maxApiCalls] Maximum number of API calls to make. + * @property {number} [maxResults] Maximum number of items plus prefixes to + * return per call. + * Note: By default will handle pagination automatically + * if more than 1 page worth of results are requested per call. + * When `autoPaginate` is set to `false` the smaller of `maxResults` + * or 1 page of results will be returned per call. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @property {string} [userProject] The ID of the project which will be billed + * for the request. + * @param {boolean} [softDeleted] If true, returns the soft-deleted object. + * Object `generation` is required if `softDeleted` is set to True. + */ + /** + * @typedef {array} GetBucketsResponse + * @property {Bucket[]} 0 Array of {@link Bucket} instances. + * @property {object} 1 nextQuery A query object to receive more results. + * @property {object} 2 The full API response. + */ + /** + * @callback GetBucketsCallback + * @param {?Error} err Request error, if any. + * @param {Bucket[]} buckets Array of {@link Bucket} instances. + * @param {object} nextQuery A query object to receive more results. + * @param {object} apiResponse The full API response. + */ + /** + * Get Bucket objects for all of the buckets in your project. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/list| Buckets: list API Documentation} + * + * @param {GetBucketsRequest} [query] Query object for listing buckets. + * @param {GetBucketsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * storage.getBuckets(function(err, buckets) { + * if (!err) { + * // buckets is an array of Bucket objects. + * } + * }); + * + * //- + * // To control how many API requests are made and page through the results + * // manually, set `autoPaginate` to `false`. + * //- + * const callback = function(err, buckets, nextQuery, apiResponse) { + * if (nextQuery) { + * // More results exist. + * storage.getBuckets(nextQuery, callback); + * } + * + * // The `metadata` property is populated for you with the metadata at the + * // time of fetching. + * buckets[0].metadata; + * + * // However, in cases where you are concerned the metadata could have + * // changed, use the `getMetadata` method. + * buckets[0].getMetadata(function(err, metadata, apiResponse) {}); + * }; + * + * storage.getBuckets({ + * autoPaginate: false + * }, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * storage.getBuckets().then(function(data) { + * const buckets = data[0]; + * }); + * + * ``` + * @example include:samples/buckets.js + * region_tag:storage_list_buckets + * Another example: + */ + getBuckets(optionsOrCallback, cb) { + const { options, callback } = (0, util_js_1.normalize)(optionsOrCallback, cb); + options.project = options.project || this.projectId; + this.request({ + uri: '/b', + qs: options, + }, (err, resp) => { + if (err) { + callback(err, null, null, resp); + return; + } + const itemsArray = resp.items ? resp.items : []; + const unreachableArray = resp.unreachable ? resp.unreachable : []; + const buckets = itemsArray.map((bucket) => { + const bucketInstance = this.bucket(bucket.id); + bucketInstance.metadata = bucket; + return bucketInstance; + }); + if (unreachableArray.length > 0) { + unreachableArray.forEach((fullPath) => { + const name = fullPath.split('/').pop(); + if (name) { + const placeholder = this.bucket(name); + placeholder.unreachable = true; + placeholder.metadata = {}; + buckets.push(placeholder); + } + }); + } + const nextQuery = resp.nextPageToken + ? Object.assign({}, options, { pageToken: resp.nextPageToken }) + : null; + callback(null, buckets, nextQuery, resp); + }); + } + getHmacKeys(optionsOrCb, cb) { + const { options, callback } = (0, util_js_1.normalize)(optionsOrCb, cb); + const query = Object.assign({}, options); + const projectId = query.projectId || this.projectId; + delete query.projectId; + this.request({ + uri: `/projects/${projectId}/hmacKeys`, + qs: query, + }, (err, resp) => { + if (err) { + callback(err, null, null, resp); + return; + } + const itemsArray = resp.items ? resp.items : []; + const hmacKeys = itemsArray.map((hmacKey) => { + const hmacKeyInstance = this.hmacKey(hmacKey.accessId, { + projectId: hmacKey.projectId, + }); + hmacKeyInstance.metadata = hmacKey; + return hmacKeyInstance; + }); + const nextQuery = resp.nextPageToken + ? Object.assign({}, options, { pageToken: resp.nextPageToken }) + : null; + callback(null, hmacKeys, nextQuery, resp); + }); + } + /** + * @typedef {array} GetServiceAccountResponse + * @property {object} 0 The service account resource. + * @property {object} 1 The full + * {@link https://cloud.google.com/storage/docs/json_api/v1/projects/serviceAccount#resource| API response}. + */ + /** + * @callback GetServiceAccountCallback + * @param {?Error} err Request error, if any. + * @param {object} serviceAccount The serviceAccount resource. + * @param {string} serviceAccount.emailAddress The service account email + * address. + * @param {object} apiResponse The full + * {@link https://cloud.google.com/storage/docs/json_api/v1/projects/serviceAccount#resource| API response}. + */ + /** + * Get the email address of this project's Google Cloud Storage service + * account. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/projects/serviceAccount/get| Projects.serviceAccount: get API Documentation} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/projects/serviceAccount#resource| Projects.serviceAccount Resource} + * + * @param {object} [options] Configuration object. + * @param {string} [options.userProject] User project to be billed for this + * request. + * @param {GetServiceAccountCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * storage.getServiceAccount(function(err, serviceAccount, apiResponse) { + * if (!err) { + * const serviceAccountEmail = serviceAccount.emailAddress; + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * storage.getServiceAccount().then(function(data) { + * const serviceAccountEmail = data[0].emailAddress; + * const apiResponse = data[1]; + * }); + * ``` + */ + getServiceAccount(optionsOrCallback, cb) { + const { options, callback } = (0, util_js_1.normalize)(optionsOrCallback, cb); + this.request({ + uri: `/projects/${this.projectId}/serviceAccount`, + qs: options, + }, (err, resp) => { + if (err) { + callback(err, null, resp); + return; + } + const camelCaseResponse = {}; + for (const prop in resp) { + // eslint-disable-next-line no-prototype-builtins + if (resp.hasOwnProperty(prop)) { + const camelCaseProp = prop.replace(/_(\w)/g, (_, match) => match.toUpperCase()); + camelCaseResponse[camelCaseProp] = resp[prop]; + } + } + callback(null, camelCaseResponse, resp); + }); + } + /** + * Get a reference to an HmacKey object. + * Note: this does not fetch the HMAC key's metadata. Use HmacKey#get() to + * retrieve and populate the metadata. + * + * To get a reference to an HMAC key that's not created for a service + * account in the same project used to instantiate the Storage client, + * supply the project's ID as `projectId` in the `options` argument. + * + * @param {string} accessId The HMAC key's access ID. + * @param {HmacKeyOptions} options HmacKey constructor options. + * @returns {HmacKey} + * @see HmacKey + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const hmacKey = storage.hmacKey('ACCESS_ID'); + * ``` + */ + hmacKey(accessId, options) { + if (!accessId) { + throw new Error(StorageExceptionMessages.HMAC_ACCESS_ID); + } + return new hmacKey_js_1.HmacKey(this, accessId, options); + } +} +exports.Storage = Storage; +/** + * {@link Bucket} class. + * + * @name Storage.Bucket + * @see Bucket + * @type {Constructor} + */ +Storage.Bucket = bucket_js_1.Bucket; +/** + * {@link Channel} class. + * + * @name Storage.Channel + * @see Channel + * @type {Constructor} + */ +Storage.Channel = channel_js_1.Channel; +/** + * {@link File} class. + * + * @name Storage.File + * @see File + * @type {Constructor} + */ +Storage.File = file_js_1.File; +/** + * {@link HmacKey} class. + * + * @name Storage.HmacKey + * @see HmacKey + * @type {Constructor} + */ +Storage.HmacKey = hmacKey_js_1.HmacKey; +Storage.acl = { + OWNER_ROLE: 'OWNER', + READER_ROLE: 'READER', + WRITER_ROLE: 'WRITER', +}; +/*! Developer Documentation + * + * These methods can be auto-paginated. + */ +paginator_1.paginator.extend(Storage, ['getBuckets', 'getHmacKeys']); +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +(0, promisify_1.promisifyAll)(Storage, { + exclude: ['bucket', 'channel', 'hmacKey'], +}); diff --git a/node_modules/@google-cloud/storage/build/cjs/src/transfer-manager.d.ts b/node_modules/@google-cloud/storage/build/cjs/src/transfer-manager.d.ts new file mode 100644 index 0000000..c846e94 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/transfer-manager.d.ts @@ -0,0 +1,253 @@ +/*! + * Copyright 2022 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. + */ +import { Bucket, UploadOptions, UploadResponse } from './bucket.js'; +import { DownloadOptions, DownloadResponse, File } from './file.js'; +import { GaxiosResponse } from 'gaxios'; +export interface UploadManyFilesOptions { + concurrencyLimit?: number; + customDestinationBuilder?(path: string, options: UploadManyFilesOptions): string; + skipIfExists?: boolean; + prefix?: string; + passthroughOptions?: Omit; +} +export interface DownloadManyFilesOptions { + concurrencyLimit?: number; + prefix?: string; + stripPrefix?: string; + passthroughOptions?: DownloadOptions; + skipIfExists?: boolean; +} +export interface DownloadFileInChunksOptions { + concurrencyLimit?: number; + chunkSizeBytes?: number; + destination?: string; + validation?: 'crc32c' | false; + noReturnData?: boolean; +} +export interface UploadFileInChunksOptions { + concurrencyLimit?: number; + chunkSizeBytes?: number; + uploadName?: string; + maxQueueSize?: number; + uploadId?: string; + autoAbortFailure?: boolean; + partsMap?: Map; + validation?: 'md5' | false; + headers?: { + [key: string]: string; + }; +} +export interface MultiPartUploadHelper { + bucket: Bucket; + fileName: string; + uploadId?: string; + partsMap?: Map; + initiateUpload(headers?: { + [key: string]: string; + }): Promise; + uploadPart(partNumber: number, chunk: Buffer, validation?: 'md5' | false): Promise; + completeUpload(): Promise; + abortUpload(): Promise; +} +export type MultiPartHelperGenerator = (bucket: Bucket, fileName: string, uploadId?: string, partsMap?: Map) => MultiPartUploadHelper; +export declare class MultiPartUploadError extends Error { + private uploadId; + private partsMap; + constructor(message: string, uploadId: string, partsMap: Map); +} +/** + * Create a TransferManager object to perform parallel transfer operations on a Cloud Storage bucket. + * + * @class + * @hideconstructor + * + * @param {Bucket} bucket A {@link Bucket} instance + * + */ +export declare class TransferManager { + bucket: Bucket; + constructor(bucket: Bucket); + /** + * @typedef {object} UploadManyFilesOptions + * @property {number} [concurrencyLimit] The number of concurrently executing promises + * to use when uploading the files. + * @property {Function} [customDestinationBuilder] A function that will take the current path of a local file + * and return a string representing a custom path to be used to upload the file to GCS. + * @property {boolean} [skipIfExists] Do not upload the file if it already exists in + * the bucket. This will set the precondition ifGenerationMatch = 0. + * @property {string} [prefix] A prefix to append to all of the uploaded files. + * @property {object} [passthroughOptions] {@link UploadOptions} Options to be passed through + * to each individual upload operation. + * + */ + /** + * Upload multiple files in parallel to the bucket. This is a convenience method + * that utilizes {@link Bucket#upload} to perform the upload. + * + * @param {array | string} [filePathsOrDirectory] An array of fully qualified paths to the files or a directory name. + * If a directory name is provided, the directory will be recursively walked and all files will be added to the upload list. + * to be uploaded to the bucket + * @param {UploadManyFilesOptions} [options] Configuration options. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const transferManager = new TransferManager(bucket); + * + * //- + * // Upload multiple files in parallel. + * //- + * const response = await transferManager.uploadManyFiles(['/local/path/file1.txt, 'local/path/file2.txt']); + * // Your bucket now contains: + * // - "local/path/file1.txt" (with the contents of '/local/path/file1.txt') + * // - "local/path/file2.txt" (with the contents of '/local/path/file2.txt') + * const response = await transferManager.uploadManyFiles('/local/directory'); + * // Your bucket will now contain all files contained in '/local/directory' maintaining the subdirectory structure. + * ``` + * + */ + uploadManyFiles(filePathsOrDirectory: string[] | string, options?: UploadManyFilesOptions): Promise; + /** + * @typedef {object} DownloadManyFilesOptions + * @property {number} [concurrencyLimit] The number of concurrently executing promises + * to use when downloading the files. + * @property {string} [prefix] A prefix to append to all of the downloaded files. + * @property {string} [stripPrefix] A prefix to remove from all of the downloaded files. + * @property {object} [passthroughOptions] {@link DownloadOptions} Options to be passed through + * to each individual download operation. + * @property {boolean} [skipIfExists] Do not download the file if it already exists in + * the destination. + * + */ + /** + * Download multiple files in parallel to the local filesystem. This is a convenience method + * that utilizes {@link File#download} to perform the download. + * + * @param {array | string} [filesOrFolder] An array of file name strings or file objects to be downloaded. If + * a string is provided this will be treated as a GCS prefix and all files with that prefix will be downloaded. + * @param {DownloadManyFilesOptions} [options] Configuration options. Setting options.prefix or options.stripPrefix + * or options.passthroughOptions.destination will cause the downloaded files to be written to the file system + * instead of being returned as a buffer. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const transferManager = new TransferManager(bucket); + * + * //- + * // Download multiple files in parallel. + * //- + * const response = await transferManager.downloadManyFiles(['file1.txt', 'file2.txt']); + * // The following files have been downloaded: + * // - "file1.txt" (with the contents from my-bucket.file1.txt) + * // - "file2.txt" (with the contents from my-bucket.file2.txt) + * const response = await transferManager.downloadManyFiles([bucket.File('file1.txt'), bucket.File('file2.txt')]); + * // The following files have been downloaded: + * // - "file1.txt" (with the contents from my-bucket.file1.txt) + * // - "file2.txt" (with the contents from my-bucket.file2.txt) + * const response = await transferManager.downloadManyFiles('test-folder'); + * // All files with GCS prefix of 'test-folder' have been downloaded. + * ``` + * + */ + downloadManyFiles(filesOrFolder: File[] | string[] | string, options?: DownloadManyFilesOptions): Promise; + /** + * @typedef {object} DownloadFileInChunksOptions + * @property {number} [concurrencyLimit] The number of concurrently executing promises + * to use when downloading the file. + * @property {number} [chunkSizeBytes] The size in bytes of each chunk to be downloaded. + * @property {string | boolean} [validation] Whether or not to perform a CRC32C validation check when download is complete. + * @property {boolean} [noReturnData] Whether or not to return the downloaded data. A `true` value here would be useful for files with a size that will not fit into memory. + * + */ + /** + * Download a large file in chunks utilizing parallel download operations. This is a convenience method + * that utilizes {@link File#download} to perform the download. + * + * @param {File | string} fileOrName {@link File} to download. + * @param {DownloadFileInChunksOptions} [options] Configuration options. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const transferManager = new TransferManager(bucket); + * + * //- + * // Download a large file in chunks utilizing parallel operations. + * //- + * const response = await transferManager.downloadFileInChunks(bucket.file('large-file.txt'); + * // Your local directory now contains: + * // - "large-file.txt" (with the contents from my-bucket.large-file.txt) + * ``` + * + */ + downloadFileInChunks(fileOrName: File | string, options?: DownloadFileInChunksOptions): Promise; + /** + * @typedef {object} UploadFileInChunksOptions + * @property {number} [concurrencyLimit] The number of concurrently executing promises + * to use when uploading the file. + * @property {number} [chunkSizeBytes] The size in bytes of each chunk to be uploaded. + * @property {string} [uploadName] Name of the file when saving to GCS. If omitted the name is taken from the file path. + * @property {number} [maxQueueSize] The number of chunks to be uploaded to hold in memory concurrently. If not specified + * defaults to the specified concurrency limit. + * @property {string} [uploadId] If specified attempts to resume a previous upload. + * @property {Map} [partsMap] If specified alongside uploadId, attempts to resume a previous upload from the last chunk + * specified in partsMap + * @property {object} [headers] headers to be sent when initiating the multipart upload. + * See {@link https://cloud.google.com/storage/docs/xml-api/post-object-multipart#request_headers| Request Headers: Initiate a Multipart Upload} + * @property {boolean} [autoAbortFailure] boolean to indicate if an in progress upload session will be automatically aborted upon failure. If not set, + * failures will be automatically aborted. + * + */ + /** + * Upload a large file in chunks utilizing parallel upload operations. If the upload fails, an uploadId and + * map containing all the successfully uploaded parts will be returned to the caller. These arguments can be used to + * resume the upload. + * + * @param {string} [filePath] The path of the file to be uploaded + * @param {UploadFileInChunksOptions} [options] Configuration options. + * @param {MultiPartHelperGenerator} [generator] A function that will return a type that implements the MPU interface. Most users will not need to use this. + * @returns {Promise} If successful a promise resolving to void, otherwise a error containing the message, uploadId, and parts map. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const transferManager = new TransferManager(bucket); + * + * //- + * // Upload a large file in chunks utilizing parallel operations. + * //- + * const response = await transferManager.uploadFileInChunks('large-file.txt'); + * // Your bucket now contains: + * // - "large-file.txt" + * ``` + * + * + */ + uploadFileInChunks(filePath: string, options?: UploadFileInChunksOptions, generator?: MultiPartHelperGenerator): Promise; + private getPathsFromDirectory; +} diff --git a/node_modules/@google-cloud/storage/build/cjs/src/transfer-manager.js b/node_modules/@google-cloud/storage/build/cjs/src/transfer-manager.js new file mode 100644 index 0000000..c864b71 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/transfer-manager.js @@ -0,0 +1,694 @@ +"use strict"; +/*! + * Copyright 2022 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. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +var _XMLMultiPartUploadHelper_instances, _XMLMultiPartUploadHelper_setGoogApiClientHeaders, _XMLMultiPartUploadHelper_handleErrorResponse; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TransferManager = exports.MultiPartUploadError = void 0; +const file_js_1 = require("./file.js"); +const p_limit_1 = __importDefault(require("p-limit")); +const path = __importStar(require("path")); +const fs_1 = require("fs"); +const crc32c_js_1 = require("./crc32c.js"); +const google_auth_library_1 = require("google-auth-library"); +const fast_xml_parser_1 = require("fast-xml-parser"); +const async_retry_1 = __importDefault(require("async-retry")); +const crypto_1 = require("crypto"); +const util_js_1 = require("./nodejs-common/util.js"); +const util_js_2 = require("./util.js"); +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore +const package_json_helper_cjs_1 = require("./package-json-helper.cjs"); +const packageJson = (0, package_json_helper_cjs_1.getPackageJSON)(); +/** + * Default number of concurrently executing promises to use when calling uploadManyFiles. + * + */ +const DEFAULT_PARALLEL_UPLOAD_LIMIT = 5; +/** + * Default number of concurrently executing promises to use when calling downloadManyFiles. + * + */ +const DEFAULT_PARALLEL_DOWNLOAD_LIMIT = 5; +/** + * Default number of concurrently executing promises to use when calling downloadFileInChunks. + * + */ +const DEFAULT_PARALLEL_CHUNKED_DOWNLOAD_LIMIT = 5; +/** + * The minimum size threshold in bytes at which to apply a chunked download strategy when calling downloadFileInChunks. + * + */ +const DOWNLOAD_IN_CHUNKS_FILE_SIZE_THRESHOLD = 32 * 1024 * 1024; +/** + * The chunk size in bytes to use when calling downloadFileInChunks. + * + */ +const DOWNLOAD_IN_CHUNKS_DEFAULT_CHUNK_SIZE = 32 * 1024 * 1024; +/** + * The chunk size in bytes to use when calling uploadFileInChunks. + * + */ +const UPLOAD_IN_CHUNKS_DEFAULT_CHUNK_SIZE = 32 * 1024 * 1024; +/** + * Default number of concurrently executing promises to use when calling uploadFileInChunks. + * + */ +const DEFAULT_PARALLEL_CHUNKED_UPLOAD_LIMIT = 5; +const EMPTY_REGEX = '(?:)'; +/** + * The `gccl-gcs-cmd` value for the `X-Goog-API-Client` header. + * Example: `gccl-gcs-cmd/tm.upload_many` + * + * @see {@link GCCL_GCS_CMD}. + * @see {@link GCCL_GCS_CMD_KEY}. + */ +const GCCL_GCS_CMD_FEATURE = { + UPLOAD_MANY: 'tm.upload_many', + DOWNLOAD_MANY: 'tm.download_many', + UPLOAD_SHARDED: 'tm.upload_sharded', + DOWNLOAD_SHARDED: 'tm.download_sharded', +}; +const defaultMultiPartGenerator = (bucket, fileName, uploadId, partsMap) => { + return new XMLMultiPartUploadHelper(bucket, fileName, uploadId, partsMap); +}; +class MultiPartUploadError extends Error { + constructor(message, uploadId, partsMap) { + super(message); + this.uploadId = uploadId; + this.partsMap = partsMap; + } +} +exports.MultiPartUploadError = MultiPartUploadError; +/** + * Class representing an implementation of MPU in the XML API. This class is not meant for public usage. + * + * @private + * + */ +class XMLMultiPartUploadHelper { + constructor(bucket, fileName, uploadId, partsMap) { + _XMLMultiPartUploadHelper_instances.add(this); + this.authClient = bucket.storage.authClient || new google_auth_library_1.GoogleAuth(); + this.uploadId = uploadId || ''; + this.bucket = bucket; + this.fileName = fileName; + this.baseUrl = `https://${bucket.name}.${new URL(this.bucket.storage.apiEndpoint).hostname}/${fileName}`; + this.xmlBuilder = new fast_xml_parser_1.XMLBuilder({ arrayNodeName: 'Part' }); + this.xmlParser = new fast_xml_parser_1.XMLParser(); + this.partsMap = partsMap || new Map(); + this.retryOptions = { + retries: this.bucket.storage.retryOptions.maxRetries, + factor: this.bucket.storage.retryOptions.retryDelayMultiplier, + maxTimeout: this.bucket.storage.retryOptions.maxRetryDelay * 1000, + maxRetryTime: this.bucket.storage.retryOptions.totalTimeout * 1000, + }; + } + /** + * Initiates a multipart upload (MPU) to the XML API and stores the resultant upload id. + * + * @returns {Promise} + */ + async initiateUpload(headers = {}) { + const url = `${this.baseUrl}?uploads`; + return (0, async_retry_1.default)(async (bail) => { + try { + const res = await this.authClient.request({ + headers: __classPrivateFieldGet(this, _XMLMultiPartUploadHelper_instances, "m", _XMLMultiPartUploadHelper_setGoogApiClientHeaders).call(this, headers), + method: 'POST', + url, + }); + if (res.data && res.data.error) { + throw res.data.error; + } + const parsedXML = this.xmlParser.parse(res.data); + this.uploadId = parsedXML.InitiateMultipartUploadResult.UploadId; + } + catch (e) { + __classPrivateFieldGet(this, _XMLMultiPartUploadHelper_instances, "m", _XMLMultiPartUploadHelper_handleErrorResponse).call(this, e, bail); + } + }, this.retryOptions); + } + /** + * Uploads the provided chunk of data to the XML API using the previously created upload id. + * + * @param {number} partNumber the sequence number of this chunk. + * @param {Buffer} chunk the chunk of data to be uploaded. + * @param {string | false} validation whether or not to include the md5 hash in the headers to cause the server + * to validate the chunk was not corrupted. + * @returns {Promise} + */ + async uploadPart(partNumber, chunk, validation) { + const url = `${this.baseUrl}?partNumber=${partNumber}&uploadId=${this.uploadId}`; + let headers = __classPrivateFieldGet(this, _XMLMultiPartUploadHelper_instances, "m", _XMLMultiPartUploadHelper_setGoogApiClientHeaders).call(this); + if (validation === 'md5') { + const hash = (0, crypto_1.createHash)('md5').update(chunk).digest('base64'); + headers = { + 'Content-MD5': hash, + }; + } + return (0, async_retry_1.default)(async (bail) => { + try { + const res = await this.authClient.request({ + url, + method: 'PUT', + body: chunk, + headers, + }); + if (res.data && res.data.error) { + throw res.data.error; + } + this.partsMap.set(partNumber, res.headers['etag']); + } + catch (e) { + __classPrivateFieldGet(this, _XMLMultiPartUploadHelper_instances, "m", _XMLMultiPartUploadHelper_handleErrorResponse).call(this, e, bail); + } + }, this.retryOptions); + } + /** + * Sends the final request of the MPU to tell GCS the upload is now complete. + * + * @returns {Promise} + */ + async completeUpload() { + const url = `${this.baseUrl}?uploadId=${this.uploadId}`; + const sortedMap = new Map([...this.partsMap.entries()].sort((a, b) => a[0] - b[0])); + const parts = []; + for (const entry of sortedMap.entries()) { + parts.push({ PartNumber: entry[0], ETag: entry[1] }); + } + const body = `${this.xmlBuilder.build(parts)}`; + return (0, async_retry_1.default)(async (bail) => { + try { + const res = await this.authClient.request({ + headers: __classPrivateFieldGet(this, _XMLMultiPartUploadHelper_instances, "m", _XMLMultiPartUploadHelper_setGoogApiClientHeaders).call(this), + url, + method: 'POST', + body, + }); + if (res.data && res.data.error) { + throw res.data.error; + } + return res; + } + catch (e) { + __classPrivateFieldGet(this, _XMLMultiPartUploadHelper_instances, "m", _XMLMultiPartUploadHelper_handleErrorResponse).call(this, e, bail); + return; + } + }, this.retryOptions); + } + /** + * Aborts an multipart upload that is in progress. Once aborted, any parts in the process of being uploaded fail, + * and future requests using the upload ID fail. + * + * @returns {Promise} + */ + async abortUpload() { + const url = `${this.baseUrl}?uploadId=${this.uploadId}`; + return (0, async_retry_1.default)(async (bail) => { + try { + const res = await this.authClient.request({ + url, + method: 'DELETE', + }); + if (res.data && res.data.error) { + throw res.data.error; + } + } + catch (e) { + __classPrivateFieldGet(this, _XMLMultiPartUploadHelper_instances, "m", _XMLMultiPartUploadHelper_handleErrorResponse).call(this, e, bail); + return; + } + }, this.retryOptions); + } +} +_XMLMultiPartUploadHelper_instances = new WeakSet(), _XMLMultiPartUploadHelper_setGoogApiClientHeaders = function _XMLMultiPartUploadHelper_setGoogApiClientHeaders(headers = {}) { + let headerFound = false; + let userAgentFound = false; + for (const [key, value] of Object.entries(headers)) { + if (key.toLocaleLowerCase().trim() === 'x-goog-api-client') { + headerFound = true; + // Prepend command feature to value, if not already there + if (!value.includes(GCCL_GCS_CMD_FEATURE.UPLOAD_SHARDED)) { + headers[key] = + `${value} gccl-gcs-cmd/${GCCL_GCS_CMD_FEATURE.UPLOAD_SHARDED}`; + } + } + else if (key.toLocaleLowerCase().trim() === 'user-agent') { + userAgentFound = true; + } + } + // If the header isn't present, add it + if (!headerFound) { + headers['x-goog-api-client'] = `${(0, util_js_2.getRuntimeTrackingString)()} gccl/${packageJson.version} gccl-gcs-cmd/${GCCL_GCS_CMD_FEATURE.UPLOAD_SHARDED}`; + } + // If the User-Agent isn't present, add it + if (!userAgentFound) { + headers['User-Agent'] = (0, util_js_2.getUserAgentString)(); + } + return headers; +}, _XMLMultiPartUploadHelper_handleErrorResponse = function _XMLMultiPartUploadHelper_handleErrorResponse(err, bail) { + if (this.bucket.storage.retryOptions.autoRetry && + this.bucket.storage.retryOptions.retryableErrorFn(err)) { + throw err; + } + else { + bail(err); + } +}; +/** + * Create a TransferManager object to perform parallel transfer operations on a Cloud Storage bucket. + * + * @class + * @hideconstructor + * + * @param {Bucket} bucket A {@link Bucket} instance + * + */ +class TransferManager { + constructor(bucket) { + this.bucket = bucket; + } + /** + * @typedef {object} UploadManyFilesOptions + * @property {number} [concurrencyLimit] The number of concurrently executing promises + * to use when uploading the files. + * @property {Function} [customDestinationBuilder] A function that will take the current path of a local file + * and return a string representing a custom path to be used to upload the file to GCS. + * @property {boolean} [skipIfExists] Do not upload the file if it already exists in + * the bucket. This will set the precondition ifGenerationMatch = 0. + * @property {string} [prefix] A prefix to append to all of the uploaded files. + * @property {object} [passthroughOptions] {@link UploadOptions} Options to be passed through + * to each individual upload operation. + * + */ + /** + * Upload multiple files in parallel to the bucket. This is a convenience method + * that utilizes {@link Bucket#upload} to perform the upload. + * + * @param {array | string} [filePathsOrDirectory] An array of fully qualified paths to the files or a directory name. + * If a directory name is provided, the directory will be recursively walked and all files will be added to the upload list. + * to be uploaded to the bucket + * @param {UploadManyFilesOptions} [options] Configuration options. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const transferManager = new TransferManager(bucket); + * + * //- + * // Upload multiple files in parallel. + * //- + * const response = await transferManager.uploadManyFiles(['/local/path/file1.txt, 'local/path/file2.txt']); + * // Your bucket now contains: + * // - "local/path/file1.txt" (with the contents of '/local/path/file1.txt') + * // - "local/path/file2.txt" (with the contents of '/local/path/file2.txt') + * const response = await transferManager.uploadManyFiles('/local/directory'); + * // Your bucket will now contain all files contained in '/local/directory' maintaining the subdirectory structure. + * ``` + * + */ + async uploadManyFiles(filePathsOrDirectory, options = {}) { + var _a; + if (options.skipIfExists && ((_a = options.passthroughOptions) === null || _a === void 0 ? void 0 : _a.preconditionOpts)) { + options.passthroughOptions.preconditionOpts.ifGenerationMatch = 0; + } + else if (options.skipIfExists && + options.passthroughOptions === undefined) { + options.passthroughOptions = { + preconditionOpts: { + ifGenerationMatch: 0, + }, + }; + } + const limit = (0, p_limit_1.default)(options.concurrencyLimit || DEFAULT_PARALLEL_UPLOAD_LIMIT); + const promises = []; + let allPaths = []; + if (!Array.isArray(filePathsOrDirectory)) { + for await (const curPath of this.getPathsFromDirectory(filePathsOrDirectory)) { + allPaths.push(curPath); + } + } + else { + allPaths = filePathsOrDirectory; + } + for (const filePath of allPaths) { + const stat = await fs_1.promises.lstat(filePath); + if (stat.isDirectory()) { + continue; + } + const passThroughOptionsCopy = { + ...options.passthroughOptions, + [util_js_1.GCCL_GCS_CMD_KEY]: GCCL_GCS_CMD_FEATURE.UPLOAD_MANY, + }; + passThroughOptionsCopy.destination = options.customDestinationBuilder + ? options.customDestinationBuilder(filePath, options) + : filePath.split(path.sep).join(path.posix.sep); + if (options.prefix) { + passThroughOptionsCopy.destination = path.posix.join(...options.prefix.split(path.sep), passThroughOptionsCopy.destination); + } + promises.push(limit(() => this.bucket.upload(filePath, passThroughOptionsCopy))); + } + return Promise.all(promises); + } + /** + * @typedef {object} DownloadManyFilesOptions + * @property {number} [concurrencyLimit] The number of concurrently executing promises + * to use when downloading the files. + * @property {string} [prefix] A prefix to append to all of the downloaded files. + * @property {string} [stripPrefix] A prefix to remove from all of the downloaded files. + * @property {object} [passthroughOptions] {@link DownloadOptions} Options to be passed through + * to each individual download operation. + * @property {boolean} [skipIfExists] Do not download the file if it already exists in + * the destination. + * + */ + /** + * Download multiple files in parallel to the local filesystem. This is a convenience method + * that utilizes {@link File#download} to perform the download. + * + * @param {array | string} [filesOrFolder] An array of file name strings or file objects to be downloaded. If + * a string is provided this will be treated as a GCS prefix and all files with that prefix will be downloaded. + * @param {DownloadManyFilesOptions} [options] Configuration options. Setting options.prefix or options.stripPrefix + * or options.passthroughOptions.destination will cause the downloaded files to be written to the file system + * instead of being returned as a buffer. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const transferManager = new TransferManager(bucket); + * + * //- + * // Download multiple files in parallel. + * //- + * const response = await transferManager.downloadManyFiles(['file1.txt', 'file2.txt']); + * // The following files have been downloaded: + * // - "file1.txt" (with the contents from my-bucket.file1.txt) + * // - "file2.txt" (with the contents from my-bucket.file2.txt) + * const response = await transferManager.downloadManyFiles([bucket.File('file1.txt'), bucket.File('file2.txt')]); + * // The following files have been downloaded: + * // - "file1.txt" (with the contents from my-bucket.file1.txt) + * // - "file2.txt" (with the contents from my-bucket.file2.txt) + * const response = await transferManager.downloadManyFiles('test-folder'); + * // All files with GCS prefix of 'test-folder' have been downloaded. + * ``` + * + */ + async downloadManyFiles(filesOrFolder, options = {}) { + const limit = (0, p_limit_1.default)(options.concurrencyLimit || DEFAULT_PARALLEL_DOWNLOAD_LIMIT); + const promises = []; + let files = []; + if (!Array.isArray(filesOrFolder)) { + const directoryFiles = await this.bucket.getFiles({ + prefix: filesOrFolder, + }); + files = directoryFiles[0]; + } + else { + files = filesOrFolder.map(curFile => { + if (typeof curFile === 'string') { + return this.bucket.file(curFile); + } + return curFile; + }); + } + const stripRegexString = options.stripPrefix + ? `^${options.stripPrefix}` + : EMPTY_REGEX; + const regex = new RegExp(stripRegexString, 'g'); + for (const file of files) { + const passThroughOptionsCopy = { + ...options.passthroughOptions, + [util_js_1.GCCL_GCS_CMD_KEY]: GCCL_GCS_CMD_FEATURE.DOWNLOAD_MANY, + }; + if (options.prefix || passThroughOptionsCopy.destination) { + passThroughOptionsCopy.destination = path.join(options.prefix || '', passThroughOptionsCopy.destination || '', file.name); + } + if (options.stripPrefix) { + passThroughOptionsCopy.destination = file.name.replace(regex, ''); + } + if (options.skipIfExists && + (0, fs_1.existsSync)(passThroughOptionsCopy.destination || '')) { + continue; + } + promises.push(limit(async () => { + const destination = passThroughOptionsCopy.destination; + if (destination && destination.endsWith(path.sep)) { + await fs_1.promises.mkdir(destination, { recursive: true }); + return Promise.resolve([ + Buffer.alloc(0), + ]); + } + return file.download(passThroughOptionsCopy); + })); + } + return Promise.all(promises); + } + /** + * @typedef {object} DownloadFileInChunksOptions + * @property {number} [concurrencyLimit] The number of concurrently executing promises + * to use when downloading the file. + * @property {number} [chunkSizeBytes] The size in bytes of each chunk to be downloaded. + * @property {string | boolean} [validation] Whether or not to perform a CRC32C validation check when download is complete. + * @property {boolean} [noReturnData] Whether or not to return the downloaded data. A `true` value here would be useful for files with a size that will not fit into memory. + * + */ + /** + * Download a large file in chunks utilizing parallel download operations. This is a convenience method + * that utilizes {@link File#download} to perform the download. + * + * @param {File | string} fileOrName {@link File} to download. + * @param {DownloadFileInChunksOptions} [options] Configuration options. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const transferManager = new TransferManager(bucket); + * + * //- + * // Download a large file in chunks utilizing parallel operations. + * //- + * const response = await transferManager.downloadFileInChunks(bucket.file('large-file.txt'); + * // Your local directory now contains: + * // - "large-file.txt" (with the contents from my-bucket.large-file.txt) + * ``` + * + */ + async downloadFileInChunks(fileOrName, options = {}) { + let chunkSize = options.chunkSizeBytes || DOWNLOAD_IN_CHUNKS_DEFAULT_CHUNK_SIZE; + let limit = (0, p_limit_1.default)(options.concurrencyLimit || DEFAULT_PARALLEL_CHUNKED_DOWNLOAD_LIMIT); + const noReturnData = Boolean(options.noReturnData); + const promises = []; + const file = typeof fileOrName === 'string' + ? this.bucket.file(fileOrName) + : fileOrName; + const fileInfo = await file.get(); + const size = parseInt(fileInfo[0].metadata.size.toString()); + // If the file size does not meet the threshold download it as a single chunk. + if (size < DOWNLOAD_IN_CHUNKS_FILE_SIZE_THRESHOLD) { + limit = (0, p_limit_1.default)(1); + chunkSize = size; + } + let start = 0; + const filePath = options.destination || path.basename(file.name); + const fileToWrite = await fs_1.promises.open(filePath, 'w'); + while (start < size) { + const chunkStart = start; + let chunkEnd = start + chunkSize - 1; + chunkEnd = chunkEnd > size ? size : chunkEnd; + promises.push(limit(async () => { + const resp = await file.download({ + start: chunkStart, + end: chunkEnd, + [util_js_1.GCCL_GCS_CMD_KEY]: GCCL_GCS_CMD_FEATURE.DOWNLOAD_SHARDED, + }); + const result = await fileToWrite.write(resp[0], 0, resp[0].length, chunkStart); + if (noReturnData) + return; + return result.buffer; + })); + start += chunkSize; + } + let chunks; + try { + chunks = await Promise.all(promises); + } + finally { + await fileToWrite.close(); + } + if (options.validation === 'crc32c' && fileInfo[0].metadata.crc32c) { + const downloadedCrc32C = await crc32c_js_1.CRC32C.fromFile(filePath); + if (!downloadedCrc32C.validate(fileInfo[0].metadata.crc32c)) { + const mismatchError = new file_js_1.RequestError(file_js_1.FileExceptionMessages.DOWNLOAD_MISMATCH); + mismatchError.code = 'CONTENT_DOWNLOAD_MISMATCH'; + throw mismatchError; + } + } + if (noReturnData) + return; + return [Buffer.concat(chunks, size)]; + } + /** + * @typedef {object} UploadFileInChunksOptions + * @property {number} [concurrencyLimit] The number of concurrently executing promises + * to use when uploading the file. + * @property {number} [chunkSizeBytes] The size in bytes of each chunk to be uploaded. + * @property {string} [uploadName] Name of the file when saving to GCS. If omitted the name is taken from the file path. + * @property {number} [maxQueueSize] The number of chunks to be uploaded to hold in memory concurrently. If not specified + * defaults to the specified concurrency limit. + * @property {string} [uploadId] If specified attempts to resume a previous upload. + * @property {Map} [partsMap] If specified alongside uploadId, attempts to resume a previous upload from the last chunk + * specified in partsMap + * @property {object} [headers] headers to be sent when initiating the multipart upload. + * See {@link https://cloud.google.com/storage/docs/xml-api/post-object-multipart#request_headers| Request Headers: Initiate a Multipart Upload} + * @property {boolean} [autoAbortFailure] boolean to indicate if an in progress upload session will be automatically aborted upon failure. If not set, + * failures will be automatically aborted. + * + */ + /** + * Upload a large file in chunks utilizing parallel upload operations. If the upload fails, an uploadId and + * map containing all the successfully uploaded parts will be returned to the caller. These arguments can be used to + * resume the upload. + * + * @param {string} [filePath] The path of the file to be uploaded + * @param {UploadFileInChunksOptions} [options] Configuration options. + * @param {MultiPartHelperGenerator} [generator] A function that will return a type that implements the MPU interface. Most users will not need to use this. + * @returns {Promise} If successful a promise resolving to void, otherwise a error containing the message, uploadId, and parts map. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const transferManager = new TransferManager(bucket); + * + * //- + * // Upload a large file in chunks utilizing parallel operations. + * //- + * const response = await transferManager.uploadFileInChunks('large-file.txt'); + * // Your bucket now contains: + * // - "large-file.txt" + * ``` + * + * + */ + async uploadFileInChunks(filePath, options = {}, generator = defaultMultiPartGenerator) { + const chunkSize = options.chunkSizeBytes || UPLOAD_IN_CHUNKS_DEFAULT_CHUNK_SIZE; + const limit = (0, p_limit_1.default)(options.concurrencyLimit || DEFAULT_PARALLEL_CHUNKED_UPLOAD_LIMIT); + const maxQueueSize = options.maxQueueSize || + options.concurrencyLimit || + DEFAULT_PARALLEL_CHUNKED_UPLOAD_LIMIT; + const fileName = options.uploadName || path.basename(filePath); + const mpuHelper = generator(this.bucket, fileName, options.uploadId, options.partsMap); + let partNumber = 1; + let promises = []; + try { + if (options.uploadId === undefined) { + await mpuHelper.initiateUpload(options.headers); + } + const startOrResumptionByte = mpuHelper.partsMap.size * chunkSize; + const readStream = (0, fs_1.createReadStream)(filePath, { + highWaterMark: chunkSize, + start: startOrResumptionByte, + }); + // p-limit only limits the number of running promises. We do not want to hold an entire + // large file in memory at once so promises acts a queue that will hold only maxQueueSize in memory. + for await (const curChunk of readStream) { + if (promises.length >= maxQueueSize) { + await Promise.all(promises); + promises = []; + } + promises.push(limit(() => mpuHelper.uploadPart(partNumber++, curChunk, options.validation))); + } + await Promise.all(promises); + return await mpuHelper.completeUpload(); + } + catch (e) { + if ((options.autoAbortFailure === undefined || options.autoAbortFailure) && + mpuHelper.uploadId) { + try { + await mpuHelper.abortUpload(); + return; + } + catch (e) { + throw new MultiPartUploadError(e.message, mpuHelper.uploadId, mpuHelper.partsMap); + } + } + throw new MultiPartUploadError(e.message, mpuHelper.uploadId, mpuHelper.partsMap); + } + } + async *getPathsFromDirectory(directory) { + const filesAndSubdirectories = await fs_1.promises.readdir(directory, { + withFileTypes: true, + }); + for (const curFileOrDirectory of filesAndSubdirectories) { + const fullPath = path.join(directory, curFileOrDirectory.name); + curFileOrDirectory.isDirectory() + ? yield* this.getPathsFromDirectory(fullPath) + : yield fullPath; + } + } +} +exports.TransferManager = TransferManager; diff --git a/node_modules/@google-cloud/storage/build/cjs/src/util.d.ts b/node_modules/@google-cloud/storage/build/cjs/src/util.d.ts new file mode 100644 index 0000000..d2cf333 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/util.d.ts @@ -0,0 +1,85 @@ +import * as querystring from 'querystring'; +import { PassThrough } from 'stream'; +export declare function normalize(optionsOrCallback?: T | U, cb?: U): { + options: T; + callback: U; +}; +/** + * Flatten an object into an Array of arrays, [[key, value], ..]. + * Implements Object.entries() for Node.js <8 + * @internal + */ +export declare function objectEntries(obj: { + [key: string]: T; +}): Array<[string, T]>; +/** + * Encode `str` with encodeURIComponent, plus these + * reserved characters: `! * ' ( )`. + * + * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent| MDN: fixedEncodeURIComponent} + * + * @param {string} str The URI component to encode. + * @return {string} The encoded string. + */ +export declare function fixedEncodeURIComponent(str: string): string; +/** + * URI encode `uri` for generating signed URLs, using fixedEncodeURIComponent. + * + * Encode every byte except `A-Z a-Z 0-9 ~ - . _`. + * + * @param {string} uri The URI to encode. + * @param [boolean=false] encodeSlash If `true`, the "/" character is not encoded. + * @return {string} The encoded string. + */ +export declare function encodeURI(uri: string, encodeSlash: boolean): string; +/** + * Serialize an object to a URL query string using util.encodeURI(uri, true). + * @param {string} url The object to serialize. + * @return {string} Serialized string. + */ +export declare function qsStringify(qs: querystring.ParsedUrlQueryInput): string; +export declare function objectKeyToLowercase(object: { + [key: string]: T; +}): { + [key: string]: T; +}; +/** + * JSON encode str, with unicode \u+ representation. + * @param {object} obj The object to encode. + * @return {string} Serialized string. + */ +export declare function unicodeJSONStringify(obj: object): string; +/** + * Converts the given objects keys to snake_case + * @param {object} obj object to convert keys to snake case. + * @returns {object} object with keys converted to snake case. + */ +export declare function convertObjKeysToSnakeCase(obj: object): object; +/** + * Formats the provided date object as a UTC ISO string. + * @param {Date} dateTimeToFormat date object to be formatted. + * @param {boolean} includeTime flag to include hours, minutes, seconds in output. + * @param {string} dateDelimiter delimiter between date components. + * @param {string} timeDelimiter delimiter between time components. + * @returns {string} UTC ISO format of provided date object. + */ +export declare function formatAsUTCISO(dateTimeToFormat: Date, includeTime?: boolean, dateDelimiter?: string, timeDelimiter?: string): string; +/** + * Examines the runtime environment and returns the appropriate tracking string. + * @returns {string} metrics tracking string based on the current runtime environment. + */ +export declare function getRuntimeTrackingString(): string; +/** + * Looks at package.json and creates the user-agent string to be applied to request headers. + * @returns {string} user agent string. + */ +export declare function getUserAgentString(): string; +export declare function getDirName(): string; +export declare function getModuleFormat(): "ESM" | "CJS"; +export declare class PassThroughShim extends PassThrough { + private shouldEmitReading; + private shouldEmitWriting; + _read(size: number): void; + _write(chunk: never, encoding: BufferEncoding, callback: (error?: Error | null | undefined) => void): void; + _final(callback: (error?: Error | null | undefined) => void): void; +} diff --git a/node_modules/@google-cloud/storage/build/cjs/src/util.js b/node_modules/@google-cloud/storage/build/cjs/src/util.js new file mode 100644 index 0000000..cf15791 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/cjs/src/util.js @@ -0,0 +1,280 @@ +"use strict"; + +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __createBinding = this && this.__createBinding || (Object.create ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { + enumerable: true, + get: function () { + return m[k]; + } + }; + } + Object.defineProperty(o, k2, desc); +} : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +}); +var __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function (o, v) { + Object.defineProperty(o, "default", { + enumerable: true, + value: v + }); +} : function (o, v) { + o["default"] = v; +}); +var __importStar = this && this.__importStar || function () { + var ownKeys = function (o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +}(); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.PassThroughShim = void 0; +exports.normalize = normalize; +exports.objectEntries = objectEntries; +exports.fixedEncodeURIComponent = fixedEncodeURIComponent; +exports.encodeURI = encodeURI; +exports.qsStringify = qsStringify; +exports.objectKeyToLowercase = objectKeyToLowercase; +exports.unicodeJSONStringify = unicodeJSONStringify; +exports.convertObjKeysToSnakeCase = convertObjKeysToSnakeCase; +exports.formatAsUTCISO = formatAsUTCISO; +exports.getRuntimeTrackingString = getRuntimeTrackingString; +exports.getUserAgentString = getUserAgentString; +exports.getDirName = getDirName; +exports.getModuleFormat = getModuleFormat; +const path = __importStar(require("path")); +const querystring = __importStar(require("querystring")); +const stream_1 = require("stream"); +const url = __importStar(require("url")); +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore +const package_json_helper_cjs_1 = require("./package-json-helper.cjs"); +// Done to avoid a problem with mangling of identifiers when using esModuleInterop +const fileURLToPath = url.fileURLToPath; +const isEsm = false; +function normalize(optionsOrCallback, cb) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb; + return { + options, + callback + }; +} +/** + * Flatten an object into an Array of arrays, [[key, value], ..]. + * Implements Object.entries() for Node.js <8 + * @internal + */ +function objectEntries(obj) { + return Object.keys(obj).map(key => [key, obj[key]]); +} +/** + * Encode `str` with encodeURIComponent, plus these + * reserved characters: `! * ' ( )`. + * + * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent| MDN: fixedEncodeURIComponent} + * + * @param {string} str The URI component to encode. + * @return {string} The encoded string. + */ +function fixedEncodeURIComponent(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase()); +} +/** + * URI encode `uri` for generating signed URLs, using fixedEncodeURIComponent. + * + * Encode every byte except `A-Z a-Z 0-9 ~ - . _`. + * + * @param {string} uri The URI to encode. + * @param [boolean=false] encodeSlash If `true`, the "/" character is not encoded. + * @return {string} The encoded string. + */ +function encodeURI(uri, encodeSlash) { + // Split the string by `/`, and conditionally rejoin them with either + // %2F if encodeSlash is `true`, or '/' if `false`. + return uri.split('/').map(fixedEncodeURIComponent).join(encodeSlash ? '%2F' : '/'); +} +/** + * Serialize an object to a URL query string using util.encodeURI(uri, true). + * @param {string} url The object to serialize. + * @return {string} Serialized string. + */ +function qsStringify(qs) { + return querystring.stringify(qs, '&', '=', { + encodeURIComponent: component => encodeURI(component, true) + }); +} +function objectKeyToLowercase(object) { + const newObj = {}; + for (let key of Object.keys(object)) { + const value = object[key]; + key = key.toLowerCase(); + newObj[key] = value; + } + return newObj; +} +/** + * JSON encode str, with unicode \u+ representation. + * @param {object} obj The object to encode. + * @return {string} Serialized string. + */ +function unicodeJSONStringify(obj) { + return JSON.stringify(obj).replace(/[\u0080-\uFFFF]/g, char => '\\u' + ('0000' + char.charCodeAt(0).toString(16)).slice(-4)); +} +/** + * Converts the given objects keys to snake_case + * @param {object} obj object to convert keys to snake case. + * @returns {object} object with keys converted to snake case. + */ +function convertObjKeysToSnakeCase(obj) { + if (obj instanceof Date || obj instanceof RegExp) { + return obj; + } + if (Array.isArray(obj)) { + return obj.map(convertObjKeysToSnakeCase); + } + if (obj instanceof Object) { + return Object.keys(obj).reduce((acc, cur) => { + const s = cur[0].toLocaleLowerCase() + cur.slice(1).replace(/([A-Z]+)/g, (match, p1) => { + return `_${p1.toLowerCase()}`; + }); + acc[s] = convertObjKeysToSnakeCase(obj[cur]); + return acc; + }, Object()); + } + return obj; +} +/** + * Formats the provided date object as a UTC ISO string. + * @param {Date} dateTimeToFormat date object to be formatted. + * @param {boolean} includeTime flag to include hours, minutes, seconds in output. + * @param {string} dateDelimiter delimiter between date components. + * @param {string} timeDelimiter delimiter between time components. + * @returns {string} UTC ISO format of provided date object. + */ +function formatAsUTCISO(dateTimeToFormat, includeTime = false, dateDelimiter = '', timeDelimiter = '') { + const year = dateTimeToFormat.getUTCFullYear(); + const month = dateTimeToFormat.getUTCMonth() + 1; + const day = dateTimeToFormat.getUTCDate(); + const hour = dateTimeToFormat.getUTCHours(); + const minute = dateTimeToFormat.getUTCMinutes(); + const second = dateTimeToFormat.getUTCSeconds(); + let resultString = `${year.toString().padStart(4, '0')}${dateDelimiter}${month.toString().padStart(2, '0')}${dateDelimiter}${day.toString().padStart(2, '0')}`; + if (includeTime) { + resultString = `${resultString}T${hour.toString().padStart(2, '0')}${timeDelimiter}${minute.toString().padStart(2, '0')}${timeDelimiter}${second.toString().padStart(2, '0')}Z`; + } + return resultString; +} +/** + * Examines the runtime environment and returns the appropriate tracking string. + * @returns {string} metrics tracking string based on the current runtime environment. + */ +function getRuntimeTrackingString() { + if ( + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + globalThis.Deno && + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + globalThis.Deno.version && + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + globalThis.Deno.version.deno) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + return `gl-deno/${globalThis.Deno.version.deno}`; + } else { + return `gl-node/${process.versions.node}`; + } +} +/** + * Looks at package.json and creates the user-agent string to be applied to request headers. + * @returns {string} user agent string. + */ +function getUserAgentString() { + const pkg = (0, package_json_helper_cjs_1.getPackageJSON)(); + const hyphenatedPackageName = pkg.name.replace('@google-cloud', 'gcloud-node') // For legacy purposes. + .replace('/', '-'); // For UA spec-compliance purposes. + return hyphenatedPackageName + '/' + pkg.version; +} +function getDirName() { + let dirToUse = ''; + try { + dirToUse = __dirname; + } catch (e) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + dirToUse = __dirname; + } + return dirToUse; +} +function getModuleFormat() { + return isEsm ? 'ESM' : 'CJS'; +} +class PassThroughShim extends stream_1.PassThrough { + constructor() { + super(...arguments); + this.shouldEmitReading = true; + this.shouldEmitWriting = true; + } + _read(size) { + if (this.shouldEmitReading) { + this.emit('reading'); + this.shouldEmitReading = false; + } + super._read(size); + } + _write(chunk, encoding, callback) { + if (this.shouldEmitWriting) { + this.emit('writing'); + this.shouldEmitWriting = false; + } + // Per the nodejs documentation, callback must be invoked on the next tick + process.nextTick(() => { + super._write(chunk, encoding, callback); + }); + } + _final(callback) { + // If the stream is empty (i.e. empty file) final will be invoked before _read / _write + // and we should still emit the proper events. + if (this.shouldEmitReading) { + this.emit('reading'); + this.shouldEmitReading = false; + } + if (this.shouldEmitWriting) { + this.emit('writing'); + this.shouldEmitWriting = false; + } + callback(null); + } +} +exports.PassThroughShim = PassThroughShim; diff --git a/node_modules/@google-cloud/storage/build/esm/src/acl.d.ts b/node_modules/@google-cloud/storage/build/esm/src/acl.d.ts new file mode 100644 index 0000000..d8f31a2 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/acl.d.ts @@ -0,0 +1,165 @@ +import { BodyResponseCallback, DecorateRequestOptions, BaseMetadata } from './nodejs-common/index.js'; +export interface AclOptions { + pathPrefix: string; + request: (reqOpts: DecorateRequestOptions, callback: BodyResponseCallback) => void; +} +export type GetAclResponse = [ + AccessControlObject | AccessControlObject[], + AclMetadata +]; +export interface GetAclCallback { + (err: Error | null, acl?: AccessControlObject | AccessControlObject[] | null, apiResponse?: AclMetadata): void; +} +export interface GetAclOptions { + entity: string; + generation?: number; + userProject?: string; +} +export interface UpdateAclOptions { + entity: string; + role: string; + generation?: number; + userProject?: string; +} +export type UpdateAclResponse = [AccessControlObject, AclMetadata]; +export interface UpdateAclCallback { + (err: Error | null, acl?: AccessControlObject | null, apiResponse?: AclMetadata): void; +} +export interface AddAclOptions { + entity: string; + role: string; + generation?: number; + userProject?: string; +} +export type AddAclResponse = [AccessControlObject, AclMetadata]; +export interface AddAclCallback { + (err: Error | null, acl?: AccessControlObject | null, apiResponse?: AclMetadata): void; +} +export type RemoveAclResponse = [AclMetadata]; +export interface RemoveAclCallback { + (err: Error | null, apiResponse?: AclMetadata): void; +} +export interface RemoveAclOptions { + entity: string; + generation?: number; + userProject?: string; +} +export interface AccessControlObject { + entity: string; + role: string; + projectTeam: string; +} +export interface AclMetadata extends BaseMetadata { + bucket?: string; + domain?: string; + entity?: string; + entityId?: string; + generation?: string; + object?: string; + projectTeam?: { + projectNumber?: string; + team?: 'editors' | 'owners' | 'viewers'; + }; + role?: 'OWNER' | 'READER' | 'WRITER' | 'FULL_CONTROL'; + [key: string]: unknown; +} +/** + * Attach functionality to a {@link Storage.acl} instance. This will add an + * object for each role group (owners, readers, and writers), with each object + * containing methods to add or delete a type of entity. + * + * As an example, here are a few methods that are created. + * + * myBucket.acl.readers.deleteGroup('groupId', function(err) {}); + * + * myBucket.acl.owners.addUser('email@example.com', function(err, acl) {}); + * + * myBucket.acl.writers.addDomain('example.com', function(err, acl) {}); + * + * @private + */ +declare class AclRoleAccessorMethods { + private static accessMethods; + private static entities; + private static roles; + owners: {}; + readers: {}; + writers: {}; + constructor(); + _assignAccessMethods(role: string): void; +} +/** + * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share objects with other + * users and allow other users to access your buckets and objects. + * + * An ACL consists of one or more entries, where each entry grants permissions + * to an entity. Permissions define the actions that can be performed against an + * object or bucket (for example, `READ` or `WRITE`); the entity defines who the + * permission applies to (for example, a specific user or group of users). + * + * Where an `entity` value is accepted, we follow the format the Cloud Storage + * API expects. + * + * Refer to + * https://cloud.google.com/storage/docs/json_api/v1/defaultObjectAccessControls + * for the most up-to-date values. + * + * - `user-userId` + * - `user-email` + * - `group-groupId` + * - `group-email` + * - `domain-domain` + * - `project-team-projectId` + * - `allUsers` + * - `allAuthenticatedUsers` + * + * Examples: + * + * - The user "liz@example.com" would be `user-liz@example.com`. + * - The group "example@googlegroups.com" would be + * `group-example@googlegroups.com`. + * - To refer to all members of the Google Apps for Business domain + * "example.com", the entity would be `domain-example.com`. + * + * For more detailed information, see + * {@link http://goo.gl/6qBBPO| About Access Control Lists}. + * + * @constructor Acl + * @mixin + * @param {object} options Configuration options. + */ +declare class Acl extends AclRoleAccessorMethods { + default: Acl; + pathPrefix: string; + request_: (reqOpts: DecorateRequestOptions, callback: BodyResponseCallback) => void; + constructor(options: AclOptions); + add(options: AddAclOptions): Promise; + add(options: AddAclOptions, callback: AddAclCallback): void; + delete(options: RemoveAclOptions): Promise; + delete(options: RemoveAclOptions, callback: RemoveAclCallback): void; + get(options?: GetAclOptions): Promise; + get(options: GetAclOptions, callback: GetAclCallback): void; + get(callback: GetAclCallback): void; + update(options: UpdateAclOptions): Promise; + update(options: UpdateAclOptions, callback: UpdateAclCallback): void; + /** + * Transform API responses to a consistent object format. + * + * @private + */ + makeAclObject_(accessControlObject: AccessControlObject): AccessControlObject; + /** + * Patch requests up to the bucket's request object. + * + * @private + * + * @param {string} method Action. + * @param {string} path Request path. + * @param {*} query Request query object. + * @param {*} body Request body contents. + * @param {function} callback Callback function. + */ + request(reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void; +} +export { Acl, AclRoleAccessorMethods }; diff --git a/node_modules/@google-cloud/storage/build/esm/src/acl.js b/node_modules/@google-cloud/storage/build/esm/src/acl.js new file mode 100644 index 0000000..d546a8d --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/acl.js @@ -0,0 +1,714 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +import { promisifyAll } from '@google-cloud/promisify'; +/** + * Attach functionality to a {@link Storage.acl} instance. This will add an + * object for each role group (owners, readers, and writers), with each object + * containing methods to add or delete a type of entity. + * + * As an example, here are a few methods that are created. + * + * myBucket.acl.readers.deleteGroup('groupId', function(err) {}); + * + * myBucket.acl.owners.addUser('email@example.com', function(err, acl) {}); + * + * myBucket.acl.writers.addDomain('example.com', function(err, acl) {}); + * + * @private + */ +class AclRoleAccessorMethods { + constructor() { + this.owners = {}; + this.readers = {}; + this.writers = {}; + /** + * An object of convenience methods to add or delete owner ACL permissions + * for a given entity. + * + * The supported methods include: + * + * - `myFile.acl.owners.addAllAuthenticatedUsers` + * - `myFile.acl.owners.deleteAllAuthenticatedUsers` + * - `myFile.acl.owners.addAllUsers` + * - `myFile.acl.owners.deleteAllUsers` + * - `myFile.acl.owners.addDomain` + * - `myFile.acl.owners.deleteDomain` + * - `myFile.acl.owners.addGroup` + * - `myFile.acl.owners.deleteGroup` + * - `myFile.acl.owners.addProject` + * - `myFile.acl.owners.deleteProject` + * - `myFile.acl.owners.addUser` + * - `myFile.acl.owners.deleteUser` + * + * @name Acl#owners + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * //- + * // Add a user as an owner of a file. + * //- + * const myBucket = gcs.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * myFile.acl.owners.addUser('email@example.com', function(err, aclObject) + * {}); + * + * //- + * // For reference, the above command is the same as running the following. + * //- + * myFile.acl.add({ + * entity: 'user-email@example.com', + * role: gcs.acl.OWNER_ROLE + * }, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myFile.acl.owners.addUser('email@example.com').then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + this.owners = {}; + /** + * An object of convenience methods to add or delete reader ACL permissions + * for a given entity. + * + * The supported methods include: + * + * - `myFile.acl.readers.addAllAuthenticatedUsers` + * - `myFile.acl.readers.deleteAllAuthenticatedUsers` + * - `myFile.acl.readers.addAllUsers` + * - `myFile.acl.readers.deleteAllUsers` + * - `myFile.acl.readers.addDomain` + * - `myFile.acl.readers.deleteDomain` + * - `myFile.acl.readers.addGroup` + * - `myFile.acl.readers.deleteGroup` + * - `myFile.acl.readers.addProject` + * - `myFile.acl.readers.deleteProject` + * - `myFile.acl.readers.addUser` + * - `myFile.acl.readers.deleteUser` + * + * @name Acl#readers + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * //- + * // Add a user as a reader of a file. + * //- + * myFile.acl.readers.addUser('email@example.com', function(err, aclObject) + * {}); + * + * //- + * // For reference, the above command is the same as running the following. + * //- + * myFile.acl.add({ + * entity: 'user-email@example.com', + * role: gcs.acl.READER_ROLE + * }, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myFile.acl.readers.addUser('email@example.com').then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + this.readers = {}; + /** + * An object of convenience methods to add or delete writer ACL permissions + * for a given entity. + * + * The supported methods include: + * + * - `myFile.acl.writers.addAllAuthenticatedUsers` + * - `myFile.acl.writers.deleteAllAuthenticatedUsers` + * - `myFile.acl.writers.addAllUsers` + * - `myFile.acl.writers.deleteAllUsers` + * - `myFile.acl.writers.addDomain` + * - `myFile.acl.writers.deleteDomain` + * - `myFile.acl.writers.addGroup` + * - `myFile.acl.writers.deleteGroup` + * - `myFile.acl.writers.addProject` + * - `myFile.acl.writers.deleteProject` + * - `myFile.acl.writers.addUser` + * - `myFile.acl.writers.deleteUser` + * + * @name Acl#writers + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * //- + * // Add a user as a writer of a file. + * //- + * myFile.acl.writers.addUser('email@example.com', function(err, aclObject) + * {}); + * + * //- + * // For reference, the above command is the same as running the following. + * //- + * myFile.acl.add({ + * entity: 'user-email@example.com', + * role: gcs.acl.WRITER_ROLE + * }, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myFile.acl.writers.addUser('email@example.com').then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + this.writers = {}; + AclRoleAccessorMethods.roles.forEach(this._assignAccessMethods.bind(this)); + } + _assignAccessMethods(role) { + const accessMethods = AclRoleAccessorMethods.accessMethods; + const entities = AclRoleAccessorMethods.entities; + const roleGroup = role.toLowerCase() + 's'; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this[roleGroup] = entities.reduce((acc, entity) => { + const isPrefix = entity.charAt(entity.length - 1) === '-'; + accessMethods.forEach(accessMethod => { + let method = accessMethod + entity[0].toUpperCase() + entity.substring(1); + if (isPrefix) { + method = method.replace('-', ''); + } + // Wrap the parent accessor method (e.g. `add` or `delete`) to avoid the + // more complex API of specifying an `entity` and `role`. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + acc[method] = (entityId, options, callback) => { + let apiEntity; + if (typeof options === 'function') { + callback = options; + options = {}; + } + if (isPrefix) { + apiEntity = entity + entityId; + } + else { + // If the entity is not a prefix, it is a special entity group + // that does not require further details. The accessor methods + // only accept a callback. + apiEntity = entity; + callback = entityId; + } + options = Object.assign({ + entity: apiEntity, + role, + }, options); + const args = [options]; + if (typeof callback === 'function') { + args.push(callback); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return this[accessMethod].apply(this, args); + }; + }); + return acc; + }, {}); + } +} +AclRoleAccessorMethods.accessMethods = ['add', 'delete']; +AclRoleAccessorMethods.entities = [ + // Special entity groups that do not require further specification. + 'allAuthenticatedUsers', + 'allUsers', + // Entity groups that require specification, e.g. `user-email@example.com`. + 'domain-', + 'group-', + 'project-', + 'user-', +]; +AclRoleAccessorMethods.roles = ['OWNER', 'READER', 'WRITER']; +/** + * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share objects with other + * users and allow other users to access your buckets and objects. + * + * An ACL consists of one or more entries, where each entry grants permissions + * to an entity. Permissions define the actions that can be performed against an + * object or bucket (for example, `READ` or `WRITE`); the entity defines who the + * permission applies to (for example, a specific user or group of users). + * + * Where an `entity` value is accepted, we follow the format the Cloud Storage + * API expects. + * + * Refer to + * https://cloud.google.com/storage/docs/json_api/v1/defaultObjectAccessControls + * for the most up-to-date values. + * + * - `user-userId` + * - `user-email` + * - `group-groupId` + * - `group-email` + * - `domain-domain` + * - `project-team-projectId` + * - `allUsers` + * - `allAuthenticatedUsers` + * + * Examples: + * + * - The user "liz@example.com" would be `user-liz@example.com`. + * - The group "example@googlegroups.com" would be + * `group-example@googlegroups.com`. + * - To refer to all members of the Google Apps for Business domain + * "example.com", the entity would be `domain-example.com`. + * + * For more detailed information, see + * {@link http://goo.gl/6qBBPO| About Access Control Lists}. + * + * @constructor Acl + * @mixin + * @param {object} options Configuration options. + */ +class Acl extends AclRoleAccessorMethods { + constructor(options) { + super(); + this.pathPrefix = options.pathPrefix; + this.request_ = options.request; + } + /** + * @typedef {array} AddAclResponse + * @property {object} 0 The Acl Objects. + * @property {object} 1 The full API response. + */ + /** + * @callback AddAclCallback + * @param {?Error} err Request error, if any. + * @param {object} acl The Acl Objects. + * @param {object} apiResponse The full API response. + */ + /** + * Add access controls on a {@link Bucket} or {@link File}. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/insert| BucketAccessControls: insert API Documentation} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/insert| ObjectAccessControls: insert API Documentation} + * + * @param {object} options Configuration options. + * @param {string} options.entity Whose permissions will be added. + * @param {string} options.role Permissions allowed for the defined entity. + * See {@link https://cloud.google.com/storage/docs/access-control Access + * Control}. + * @param {number} [options.generation] **File Objects Only** Select a specific + * revision of this file (as opposed to the latest version, the default). + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {AddAclCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * const options = { + * entity: 'user-useremail@example.com', + * role: gcs.acl.OWNER_ROLE + * }; + * + * myBucket.acl.add(options, function(err, aclObject, apiResponse) {}); + * + * //- + * // For file ACL operations, you can also specify a `generation` property. + * // Here is how you would grant ownership permissions to a user on a + * specific + * // revision of a file. + * //- + * myFile.acl.add({ + * entity: 'user-useremail@example.com', + * role: gcs.acl.OWNER_ROLE, + * generation: 1 + * }, function(err, aclObject, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myBucket.acl.add(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/acl.js + * region_tag:storage_add_file_owner + * Example of adding an owner to a file: + * + * @example include:samples/acl.js + * region_tag:storage_add_bucket_owner + * Example of adding an owner to a bucket: + * + * @example include:samples/acl.js + * region_tag:storage_add_bucket_default_owner + * Example of adding a default owner to a bucket: + */ + add(options, callback) { + const query = {}; + if (options.generation) { + query.generation = options.generation; + } + if (options.userProject) { + query.userProject = options.userProject; + } + this.request({ + method: 'POST', + uri: '', + qs: query, + maxRetries: 0, //explicitly set this value since this is a non-idempotent function + json: { + entity: options.entity, + role: options.role.toUpperCase(), + }, + }, (err, resp) => { + if (err) { + callback(err, null, resp); + return; + } + callback(null, this.makeAclObject_(resp), resp); + }); + } + /** + * @typedef {array} RemoveAclResponse + * @property {object} 0 The full API response. + */ + /** + * @callback RemoveAclCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Delete access controls on a {@link Bucket} or {@link File}. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/delete| BucketAccessControls: delete API Documentation} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/delete| ObjectAccessControls: delete API Documentation} + * + * @param {object} options Configuration object. + * @param {string} options.entity Whose permissions will be revoked. + * @param {int} [options.generation] **File Objects Only** Select a specific + * revision of this file (as opposed to the latest version, the default). + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {RemoveAclCallback} callback The callback function. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * myBucket.acl.delete({ + * entity: 'user-useremail@example.com' + * }, function(err, apiResponse) {}); + * + * //- + * // For file ACL operations, you can also specify a `generation` property. + * //- + * myFile.acl.delete({ + * entity: 'user-useremail@example.com', + * generation: 1 + * }, function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myFile.acl.delete().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example include:samples/acl.js + * region_tag:storage_remove_bucket_owner + * Example of removing an owner from a bucket: + * + * @example include:samples/acl.js + * region_tag:storage_remove_bucket_default_owner + * Example of removing a default owner from a bucket: + * + * @example include:samples/acl.js + * region_tag:storage_remove_file_owner + * Example of removing an owner from a bucket: + */ + delete(options, callback) { + const query = {}; + if (options.generation) { + query.generation = options.generation; + } + if (options.userProject) { + query.userProject = options.userProject; + } + this.request({ + method: 'DELETE', + uri: '/' + encodeURIComponent(options.entity), + qs: query, + }, (err, resp) => { + callback(err, resp); + }); + } + /** + * @typedef {array} GetAclResponse + * @property {object|object[]} 0 Single or array of Acl Objects. + * @property {object} 1 The full API response. + */ + /** + * @callback GetAclCallback + * @param {?Error} err Request error, if any. + * @param {object|object[]} acl Single or array of Acl Objects. + * @param {object} apiResponse The full API response. + */ + /** + * Get access controls on a {@link Bucket} or {@link File}. If + * an entity is omitted, you will receive an array of all applicable access + * controls. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/get| BucketAccessControls: get API Documentation} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/get| ObjectAccessControls: get API Documentation} + * + * @param {object|function} [options] Configuration options. If you want to + * receive a list of all access controls, pass the callback function as + * the only argument. + * @param {string} options.entity Whose permissions will be fetched. + * @param {number} [options.generation] **File Objects Only** Select a specific + * revision of this file (as opposed to the latest version, the default). + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetAclCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * myBucket.acl.get({ + * entity: 'user-useremail@example.com' + * }, function(err, aclObject, apiResponse) {}); + * + * //- + * // Get all access controls. + * //- + * myBucket.acl.get(function(err, aclObjects, apiResponse) { + * // aclObjects = [ + * // { + * // entity: 'user-useremail@example.com', + * // role: 'owner' + * // } + * // ] + * }); + * + * //- + * // For file ACL operations, you can also specify a `generation` property. + * //- + * myFile.acl.get({ + * entity: 'user-useremail@example.com', + * generation: 1 + * }, function(err, aclObject, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myBucket.acl.get().then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/acl.js + * region_tag:storage_print_file_acl + * Example of printing a file's ACL: + * + * @example include:samples/acl.js + * region_tag:storage_print_file_acl_for_user + * Example of printing a file's ACL for a specific user: + * + * @example include:samples/acl.js + * region_tag:storage_print_bucket_acl + * Example of printing a bucket's ACL: + * + * @example include:samples/acl.js + * region_tag:storage_print_bucket_acl_for_user + * Example of printing a bucket's ACL for a specific user: + */ + get(optionsOrCallback, cb) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : null; + const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb; + let path = ''; + const query = {}; + if (options) { + path = '/' + encodeURIComponent(options.entity); + if (options.generation) { + query.generation = options.generation; + } + if (options.userProject) { + query.userProject = options.userProject; + } + } + this.request({ + uri: path, + qs: query, + }, (err, resp) => { + if (err) { + callback(err, null, resp); + return; + } + let results; + if (resp.items) { + results = resp.items.map(this.makeAclObject_); + } + else { + results = this.makeAclObject_(resp); + } + callback(null, results, resp); + }); + } + /** + * @typedef {array} UpdateAclResponse + * @property {object} 0 The updated Acl Objects. + * @property {object} 1 The full API response. + */ + /** + * @callback UpdateAclCallback + * @param {?Error} err Request error, if any. + * @param {object} acl The updated Acl Objects. + * @param {object} apiResponse The full API response. + */ + /** + * Update access controls on a {@link Bucket} or {@link File}. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/update| BucketAccessControls: update API Documentation} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/update| ObjectAccessControls: update API Documentation} + * + * @param {object} options Configuration options. + * @param {string} options.entity Whose permissions will be updated. + * @param {string} options.role Permissions allowed for the defined entity. + * See {@link Storage.acl}. + * @param {number} [options.generation] **File Objects Only** Select a specific + * revision of this file (as opposed to the latest version, the default). + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {UpdateAclCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * const options = { + * entity: 'user-useremail@example.com', + * role: gcs.acl.WRITER_ROLE + * }; + * + * myBucket.acl.update(options, function(err, aclObject, apiResponse) {}); + * + * //- + * // For file ACL operations, you can also specify a `generation` property. + * //- + * myFile.acl.update({ + * entity: 'user-useremail@example.com', + * role: gcs.acl.WRITER_ROLE, + * generation: 1 + * }, function(err, aclObject, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myFile.acl.update(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + update(options, callback) { + const query = {}; + if (options.generation) { + query.generation = options.generation; + } + if (options.userProject) { + query.userProject = options.userProject; + } + this.request({ + method: 'PUT', + uri: '/' + encodeURIComponent(options.entity), + qs: query, + json: { + role: options.role.toUpperCase(), + }, + }, (err, resp) => { + if (err) { + callback(err, null, resp); + return; + } + callback(null, this.makeAclObject_(resp), resp); + }); + } + /** + * Transform API responses to a consistent object format. + * + * @private + */ + makeAclObject_(accessControlObject) { + const obj = { + entity: accessControlObject.entity, + role: accessControlObject.role, + }; + if (accessControlObject.projectTeam) { + obj.projectTeam = accessControlObject.projectTeam; + } + return obj; + } + /** + * Patch requests up to the bucket's request object. + * + * @private + * + * @param {string} method Action. + * @param {string} path Request path. + * @param {*} query Request query object. + * @param {*} body Request body contents. + * @param {function} callback Callback function. + */ + request(reqOpts, callback) { + reqOpts.uri = this.pathPrefix + reqOpts.uri; + this.request_(reqOpts, callback); + } +} +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Acl, { + exclude: ['request'], +}); +export { Acl, AclRoleAccessorMethods }; diff --git a/node_modules/@google-cloud/storage/build/esm/src/bucket.d.ts b/node_modules/@google-cloud/storage/build/esm/src/bucket.d.ts new file mode 100644 index 0000000..c9b57ea --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/bucket.d.ts @@ -0,0 +1,830 @@ +import { ApiError, BodyResponseCallback, DecorateRequestOptions, DeleteCallback, ExistsCallback, GetConfig, MetadataCallback, ServiceObject, SetMetadataResponse } from './nodejs-common/index.js'; +import { RequestResponse } from './nodejs-common/service-object.js'; +import * as http from 'http'; +import { Acl, AclMetadata } from './acl.js'; +import { Channel } from './channel.js'; +import { File, FileOptions, CreateResumableUploadOptions, CreateWriteStreamOptions } from './file.js'; +import { Iam } from './iam.js'; +import { Notification } from './notification.js'; +import { Storage, Cors, PreconditionOptions, BucketOptions } from './storage.js'; +import { GetSignedUrlResponse, GetSignedUrlCallback, SignerGetSignedUrlConfig, URLSigner, Query } from './signer.js'; +import { Readable } from 'stream'; +import { CRC32CValidatorGenerator } from './crc32c.js'; +import { URL } from 'url'; +import { BaseMetadata, SetMetadataOptions } from './nodejs-common/service-object.js'; +export type GetFilesResponse = [ + File[], + (GetFilesOptions | {}) & Partial>, + unknown +]; +export interface GetFilesCallback { + (err: Error | null, files?: File[], nextQuery?: {}, apiResponse?: unknown): void; +} +interface WatchAllOptions { + delimiter?: string; + maxResults?: number; + pageToken?: string; + prefix?: string; + projection?: string; + userProject?: string; + versions?: boolean; +} +export interface AddLifecycleRuleOptions extends PreconditionOptions { + append?: boolean; +} +export interface LifecycleAction { + type: 'Delete' | 'SetStorageClass' | 'AbortIncompleteMultipartUpload'; + storageClass?: string; +} +export interface LifecycleCondition { + age?: number; + createdBefore?: Date | string; + customTimeBefore?: Date | string; + daysSinceCustomTime?: number; + daysSinceNoncurrentTime?: number; + isLive?: boolean; + matchesPrefix?: string[]; + matchesSuffix?: string[]; + matchesStorageClass?: string[]; + noncurrentTimeBefore?: Date | string; + numNewerVersions?: number; +} +export interface LifecycleRule { + action: LifecycleAction; + condition: LifecycleCondition; +} +export interface LifecycleCondition { + age?: number; + createdBefore?: Date | string; + customTimeBefore?: Date | string; + daysSinceCustomTime?: number; + daysSinceNoncurrentTime?: number; + isLive?: boolean; + matchesPrefix?: string[]; + matchesSuffix?: string[]; + matchesStorageClass?: string[]; + noncurrentTimeBefore?: Date | string; + numNewerVersions?: number; +} +export interface LifecycleRule { + action: LifecycleAction; + condition: LifecycleCondition; +} +export interface EnableLoggingOptions extends PreconditionOptions { + bucket?: string | Bucket; + prefix: string; +} +export interface GetFilesOptions { + autoPaginate?: boolean; + delimiter?: string; + endOffset?: string; + includeFoldersAsPrefixes?: boolean; + includeTrailingDelimiter?: boolean; + prefix?: string; + matchGlob?: string; + maxApiCalls?: number; + maxResults?: number; + pageToken?: string; + softDeleted?: boolean; + startOffset?: string; + userProject?: string; + versions?: boolean; + fields?: string; +} +export interface CombineOptions extends PreconditionOptions { + kmsKeyName?: string; + userProject?: string; +} +export interface CombineCallback { + (err: Error | null, newFile: File | null, apiResponse: unknown): void; +} +export type CombineResponse = [File, unknown]; +export interface CreateChannelConfig extends WatchAllOptions { + address: string; +} +export interface CreateChannelOptions { + userProject?: string; +} +export type CreateChannelResponse = [Channel, unknown]; +export interface CreateChannelCallback { + (err: Error | null, channel: Channel | null, apiResponse: unknown): void; +} +export interface CreateNotificationOptions { + customAttributes?: { + [key: string]: string; + }; + eventTypes?: string[]; + objectNamePrefix?: string; + payloadFormat?: string; + userProject?: string; +} +export interface CreateNotificationCallback { + (err: Error | null, notification: Notification | null, apiResponse: unknown): void; +} +export type CreateNotificationResponse = [Notification, unknown]; +export interface DeleteBucketOptions { + ignoreNotFound?: boolean; + userProject?: string; +} +export type DeleteBucketResponse = [unknown]; +export interface DeleteBucketCallback extends DeleteCallback { + (err: Error | null, apiResponse: unknown): void; +} +export interface DeleteFilesOptions extends GetFilesOptions, PreconditionOptions { + force?: boolean; +} +export interface DeleteFilesCallback { + (err: Error | Error[] | null, apiResponse?: object): void; +} +export type DeleteLabelsResponse = [unknown]; +export type DeleteLabelsCallback = SetLabelsCallback; +export type DeleteLabelsOptions = PreconditionOptions; +export type DisableRequesterPaysOptions = PreconditionOptions; +export type DisableRequesterPaysResponse = [unknown]; +export interface DisableRequesterPaysCallback { + (err?: Error | null, apiResponse?: object): void; +} +export type EnableRequesterPaysResponse = [unknown]; +export interface EnableRequesterPaysCallback { + (err?: Error | null, apiResponse?: unknown): void; +} +export type EnableRequesterPaysOptions = PreconditionOptions; +export interface BucketExistsOptions extends GetConfig { + userProject?: string; +} +export type BucketExistsResponse = [boolean]; +export type BucketExistsCallback = ExistsCallback; +export interface GetBucketOptions extends GetConfig { + userProject?: string; +} +export type GetBucketResponse = [Bucket, unknown]; +export interface GetBucketCallback { + (err: ApiError | null, bucket: Bucket | null, apiResponse: unknown): void; +} +export interface GetLabelsOptions { + userProject?: string; +} +export type GetLabelsResponse = [unknown]; +export interface GetLabelsCallback { + (err: Error | null, labels: object | null): void; +} +export interface RestoreOptions { + generation: string; + projection?: 'full' | 'noAcl'; +} +export interface BucketMetadata extends BaseMetadata { + acl?: AclMetadata[] | null; + autoclass?: { + enabled?: boolean; + toggleTime?: string; + terminalStorageClass?: string; + terminalStorageClassUpdateTime?: string; + }; + billing?: { + requesterPays?: boolean; + }; + cors?: Cors[]; + customPlacementConfig?: { + dataLocations?: string[]; + }; + defaultEventBasedHold?: boolean; + defaultObjectAcl?: AclMetadata[]; + encryption?: { + defaultKmsKeyName?: string; + } | null; + hierarchicalNamespace?: { + enabled?: boolean; + }; + iamConfiguration?: { + publicAccessPrevention?: string; + uniformBucketLevelAccess?: { + enabled?: boolean; + lockedTime?: string; + }; + }; + labels?: { + [key: string]: string | null; + }; + lifecycle?: { + rule?: LifecycleRule[]; + } | null; + location?: string; + locationType?: string; + logging?: { + logBucket?: string; + logObjectPrefix?: string; + }; + generation?: string; + metageneration?: string; + name?: string; + objectRetention?: { + mode?: string; + }; + owner?: { + entity?: string; + entityId?: string; + }; + projectNumber?: string | number; + retentionPolicy?: { + effectiveTime?: string; + isLocked?: boolean; + retentionPeriod?: string | number; + } | null; + rpo?: string; + softDeleteTime?: string; + hardDeleteTime?: string; + softDeletePolicy?: { + retentionDurationSeconds?: string | number; + readonly effectiveTime?: string; + }; + storageClass?: string; + timeCreated?: string; + updated?: string; + versioning?: { + enabled?: boolean; + }; + website?: { + mainPageSuffix?: string; + notFoundPage?: string; + }; +} +export type GetBucketMetadataResponse = [BucketMetadata, unknown]; +export interface GetBucketMetadataCallback { + (err: ApiError | null, metadata: BucketMetadata | null, apiResponse: unknown): void; +} +export interface GetBucketMetadataOptions { + userProject?: string; +} +export interface GetBucketSignedUrlConfig extends Pick { + action: 'list'; + version?: 'v2' | 'v4'; + cname?: string; + virtualHostedStyle?: boolean; + expires: string | number | Date; + extensionHeaders?: http.OutgoingHttpHeaders; + queryParams?: Query; +} +export declare enum BucketActionToHTTPMethod { + list = "GET" +} +export declare enum AvailableServiceObjectMethods { + setMetadata = 0, + delete = 1 +} +export interface GetNotificationsOptions { + userProject?: string; +} +export interface GetNotificationsCallback { + (err: Error | null, notifications: Notification[] | null, apiResponse: unknown): void; +} +export type GetNotificationsResponse = [Notification[], unknown]; +export interface MakeBucketPrivateOptions { + includeFiles?: boolean; + force?: boolean; + metadata?: BucketMetadata; + userProject?: string; + preconditionOpts?: PreconditionOptions; +} +export type MakeBucketPrivateResponse = [File[]]; +export interface MakeBucketPrivateCallback { + (err?: Error | null, files?: File[]): void; +} +export interface MakeBucketPublicOptions { + includeFiles?: boolean; + force?: boolean; +} +export interface MakeBucketPublicCallback { + (err?: Error | null, files?: File[]): void; +} +export type MakeBucketPublicResponse = [File[]]; +export interface SetBucketMetadataOptions extends PreconditionOptions { + userProject?: string; +} +export type SetBucketMetadataResponse = [BucketMetadata]; +export interface SetBucketMetadataCallback { + (err?: Error | null, metadata?: BucketMetadata): void; +} +export interface BucketLockCallback { + (err?: Error | null, apiResponse?: unknown): void; +} +export type BucketLockResponse = [unknown]; +export interface Labels { + [key: string]: string; +} +export interface SetLabelsOptions extends PreconditionOptions { + userProject?: string; +} +export type SetLabelsResponse = [unknown]; +export interface SetLabelsCallback { + (err?: Error | null, metadata?: unknown): void; +} +export interface SetBucketStorageClassOptions extends PreconditionOptions { + userProject?: string; +} +export interface SetBucketStorageClassCallback { + (err?: Error | null): void; +} +export type UploadResponse = [File, unknown]; +export interface UploadCallback { + (err: Error | null, file?: File | null, apiResponse?: unknown): void; +} +export interface UploadOptions extends CreateResumableUploadOptions, CreateWriteStreamOptions { + destination?: string | File; + encryptionKey?: string | Buffer; + kmsKeyName?: string; + onUploadProgress?: (progressEvent: any) => void; +} +export interface MakeAllFilesPublicPrivateOptions { + force?: boolean; + private?: boolean; + public?: boolean; + userProject?: string; +} +interface MakeAllFilesPublicPrivateCallback { + (err?: Error | Error[] | null, files?: File[]): void; +} +type MakeAllFilesPublicPrivateResponse = [File[]]; +export declare enum BucketExceptionMessages { + PROVIDE_SOURCE_FILE = "You must provide at least one source file.", + DESTINATION_FILE_NOT_SPECIFIED = "A destination file must be specified.", + CHANNEL_ID_REQUIRED = "An ID is required to create a channel.", + TOPIC_NAME_REQUIRED = "A valid topic name is required.", + CONFIGURATION_OBJECT_PREFIX_REQUIRED = "A configuration object with a prefix is required.", + SPECIFY_FILE_NAME = "A file name must be specified.", + METAGENERATION_NOT_PROVIDED = "A metageneration must be provided.", + SUPPLY_NOTIFICATION_ID = "You must supply a notification ID." +} +/** + * @callback Crc32cGeneratorToStringCallback + * A method returning the CRC32C as a base64-encoded string. + * + * @returns {string} + * + * @example + * Hashing the string 'data' should return 'rth90Q==' + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.toString(); // 'rth90Q==' + * ``` + **/ +/** + * @callback Crc32cGeneratorValidateCallback + * A method validating a base64-encoded CRC32C string. + * + * @param {string} [value] base64-encoded CRC32C string to validate + * @returns {boolean} + * + * @example + * Should return `true` if the value matches, `false` otherwise + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.validate('DkjKuA=='); // false + * crc32c.validate('rth90Q=='); // true + * ``` + **/ +/** + * @callback Crc32cGeneratorUpdateCallback + * A method for passing `Buffer`s for CRC32C generation. + * + * @param {Buffer} [data] data to update CRC32C value with + * @returns {undefined} + * + * @example + * Hashing buffers from 'some ' and 'text\n' + * + * ```js + * const buffer1 = Buffer.from('some '); + * crc32c.update(buffer1); + * + * const buffer2 = Buffer.from('text\n'); + * crc32c.update(buffer2); + * + * crc32c.toString(); // 'DkjKuA==' + * ``` + **/ +/** + * @typedef {object} CRC32CValidator + * @property {Crc32cGeneratorToStringCallback} + * @property {Crc32cGeneratorValidateCallback} + * @property {Crc32cGeneratorUpdateCallback} + */ +/** + * A function that generates a CRC32C Validator. Defaults to {@link CRC32C} + * + * @name Bucket#crc32cGenerator + * @type {CRC32CValidator} + */ +/** + * Get and set IAM policies for your bucket. + * + * @name Bucket#iam + * @mixes Iam + * + * See {@link https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management| Cloud Storage IAM Management} + * See {@link https://cloud.google.com/iam/docs/granting-changing-revoking-access| Granting, Changing, and Revoking Access} + * See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Get the IAM policy for your bucket. + * //- + * bucket.iam.getPolicy(function(err, policy) { + * console.log(policy); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.iam.getPolicy().then(function(data) { + * const policy = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/iam.js + * region_tag:storage_view_bucket_iam_members + * Example of retrieving a bucket's IAM policy: + * + * @example include:samples/iam.js + * region_tag:storage_add_bucket_iam_member + * Example of adding to a bucket's IAM policy: + * + * @example include:samples/iam.js + * region_tag:storage_remove_bucket_iam_member + * Example of removing from a bucket's IAM policy: + */ +/** + * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share objects with other + * users and allow other users to access your buckets and objects. + * + * An ACL consists of one or more entries, where each entry grants permissions + * to an entity. Permissions define the actions that can be performed against + * an object or bucket (for example, `READ` or `WRITE`); the entity defines + * who the permission applies to (for example, a specific user or group of + * users). + * + * The `acl` object on a Bucket instance provides methods to get you a list of + * the ACLs defined on your bucket, as well as set, update, and delete them. + * + * Buckets also have + * {@link https://cloud.google.com/storage/docs/access-control/lists#default| default ACLs} + * for all created files. Default ACLs specify permissions that all new + * objects added to the bucket will inherit by default. You can add, delete, + * get, and update entities and permissions for these as well with + * {@link Bucket#acl.default}. + * + * See {@link http://goo.gl/6qBBPO| About Access Control Lists} + * See {@link https://cloud.google.com/storage/docs/access-control/lists#default| Default ACLs} + * + * @name Bucket#acl + * @mixes Acl + * @property {Acl} default Cloud Storage Buckets have + * {@link https://cloud.google.com/storage/docs/access-control/lists#default| default ACLs} + * for all created files. You can add, delete, get, and update entities and + * permissions for these as well. The method signatures and examples are all + * the same, after only prefixing the method call with `default`. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // Make a bucket's contents publicly readable. + * //- + * const myBucket = storage.bucket('my-bucket'); + * + * const options = { + * entity: 'allUsers', + * role: storage.acl.READER_ROLE + * }; + * + * myBucket.acl.add(options, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myBucket.acl.add(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/acl.js + * region_tag:storage_print_bucket_acl + * Example of printing a bucket's ACL: + * + * @example include:samples/acl.js + * region_tag:storage_print_bucket_acl_for_user + * Example of printing a bucket's ACL for a specific user: + * + * @example include:samples/acl.js + * region_tag:storage_add_bucket_owner + * Example of adding an owner to a bucket: + * + * @example include:samples/acl.js + * region_tag:storage_remove_bucket_owner + * Example of removing an owner from a bucket: + * + * @example include:samples/acl.js + * region_tag:storage_add_bucket_default_owner + * Example of adding a default owner to a bucket: + * + * @example include:samples/acl.js + * region_tag:storage_remove_bucket_default_owner + * Example of removing a default owner from a bucket: + */ +/** + * The API-formatted resource description of the bucket. + * + * Note: This is not guaranteed to be up-to-date when accessed. To get the + * latest record, call the `getMetadata()` method. + * + * @name Bucket#metadata + * @type {object} + */ +/** + * The bucket's name. + * @name Bucket#name + * @type {string} + */ +/** + * Get {@link File} objects for the files currently in the bucket as a + * readable object stream. + * + * @method Bucket#getFilesStream + * @param {GetFilesOptions} [query] Query object for listing files. + * @returns {ReadableStream} A readable stream that emits {@link File} instances. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.getFilesStream() + * .on('error', console.error) + * .on('data', function(file) { + * // file is a File object. + * }) + * .on('end', function() { + * // All files retrieved. + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * bucket.getFilesStream() + * .on('data', function(file) { + * this.end(); + * }); + * + * //- + * // If you're filtering files with a delimiter, you should use + * // {@link Bucket#getFiles} and set `autoPaginate: false` in order to + * // preserve the `apiResponse` argument. + * //- + * const prefixes = []; + * + * function callback(err, files, nextQuery, apiResponse) { + * prefixes = prefixes.concat(apiResponse.prefixes); + * + * if (nextQuery) { + * bucket.getFiles(nextQuery, callback); + * } else { + * // prefixes = The finished array of prefixes. + * } + * } + * + * bucket.getFiles({ + * autoPaginate: false, + * delimiter: '/' + * }, callback); + * ``` + */ +/** + * Create a Bucket object to interact with a Cloud Storage bucket. + * + * @class + * @hideconstructor + * + * @param {Storage} storage A {@link Storage} instance. + * @param {string} name The name of the bucket. + * @param {object} [options] Configuration object. + * @param {string} [options.userProject] User project. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * ``` + */ +declare class Bucket extends ServiceObject { + name: string; + /** + * A reference to the {@link Storage} associated with this {@link Bucket} + * instance. + * @name Bucket#storage + * @type {Storage} + */ + storage: Storage; + /** + * A user project to apply to each request from this bucket. + * @name Bucket#userProject + * @type {string} + */ + userProject?: string; + acl: Acl; + iam: Iam; + crc32cGenerator: CRC32CValidatorGenerator; + getFilesStream(query?: GetFilesOptions): Readable; + signer?: URLSigner; + private instanceRetryValue?; + instancePreconditionOpts?: PreconditionOptions; + /** + * Indicates whether this Bucket object is a placeholder for an item + * that the API failed to retrieve (unreachable) due to partial failure. + * Consumers must check this flag before accessing other properties. + */ + unreachable: boolean; + constructor(storage: Storage, name: string, options?: BucketOptions); + /** + * The bucket's Cloud Storage URI (`gs://`) + * + * @example + * ```ts + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * // `gs://my-bucket` + * const href = bucket.cloudStorageURI.href; + * ``` + */ + get cloudStorageURI(): URL; + addLifecycleRule(rule: LifecycleRule | LifecycleRule[], options?: AddLifecycleRuleOptions): Promise; + addLifecycleRule(rule: LifecycleRule | LifecycleRule[], options: AddLifecycleRuleOptions, callback: SetBucketMetadataCallback): void; + addLifecycleRule(rule: LifecycleRule | LifecycleRule[], callback: SetBucketMetadataCallback): void; + combine(sources: string[] | File[], destination: string | File, options?: CombineOptions): Promise; + combine(sources: string[] | File[], destination: string | File, options: CombineOptions, callback: CombineCallback): void; + combine(sources: string[] | File[], destination: string | File, callback: CombineCallback): void; + createChannel(id: string, config: CreateChannelConfig, options?: CreateChannelOptions): Promise; + createChannel(id: string, config: CreateChannelConfig, callback: CreateChannelCallback): void; + createChannel(id: string, config: CreateChannelConfig, options: CreateChannelOptions, callback: CreateChannelCallback): void; + createNotification(topic: string, options?: CreateNotificationOptions): Promise; + createNotification(topic: string, options: CreateNotificationOptions, callback: CreateNotificationCallback): void; + createNotification(topic: string, callback: CreateNotificationCallback): void; + deleteFiles(query?: DeleteFilesOptions): Promise; + deleteFiles(callback: DeleteFilesCallback): void; + deleteFiles(query: DeleteFilesOptions, callback: DeleteFilesCallback): void; + deleteLabels(labels?: string | string[]): Promise; + deleteLabels(options: DeleteLabelsOptions): Promise; + deleteLabels(callback: DeleteLabelsCallback): void; + deleteLabels(labels: string | string[], options: DeleteLabelsOptions): Promise; + deleteLabels(labels: string | string[], callback: DeleteLabelsCallback): void; + deleteLabels(labels: string | string[], options: DeleteLabelsOptions, callback: DeleteLabelsCallback): void; + disableRequesterPays(options?: DisableRequesterPaysOptions): Promise; + disableRequesterPays(callback: DisableRequesterPaysCallback): void; + disableRequesterPays(options: DisableRequesterPaysOptions, callback: DisableRequesterPaysCallback): void; + enableLogging(config: EnableLoggingOptions): Promise; + enableLogging(config: EnableLoggingOptions, callback: SetBucketMetadataCallback): void; + enableRequesterPays(options?: EnableRequesterPaysOptions): Promise; + enableRequesterPays(callback: EnableRequesterPaysCallback): void; + enableRequesterPays(options: EnableRequesterPaysOptions, callback: EnableRequesterPaysCallback): void; + /** + * Create a {@link File} object. See {@link File} to see how to handle + * the different use cases you may have. + * + * @param {string} name The name of the file in this bucket. + * @param {FileOptions} [options] Configuration options. + * @param {string|number} [options.generation] Only use a specific revision of + * this file. + * @param {string} [options.encryptionKey] A custom encryption key. See + * {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}. + * @param {string} [options.kmsKeyName] The name of the Cloud KMS key that will + * be used to encrypt the object. Must be in the format: + * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`. + * KMS key ring must use the same location as the bucket. + * @param {string} [options.userProject] The ID of the project which will be + * billed for all requests made from File object. + * @returns {File} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * const file = bucket.file('my-existing-file.png'); + * ``` + */ + file(name: string, options?: FileOptions): File; + getFiles(query?: GetFilesOptions): Promise; + getFiles(query: GetFilesOptions, callback: GetFilesCallback): void; + getFiles(callback: GetFilesCallback): void; + getLabels(options?: GetLabelsOptions): Promise; + getLabels(callback: GetLabelsCallback): void; + getLabels(options: GetLabelsOptions, callback: GetLabelsCallback): void; + getNotifications(options?: GetNotificationsOptions): Promise; + getNotifications(callback: GetNotificationsCallback): void; + getNotifications(options: GetNotificationsOptions, callback: GetNotificationsCallback): void; + getSignedUrl(cfg: GetBucketSignedUrlConfig): Promise; + getSignedUrl(cfg: GetBucketSignedUrlConfig, callback: GetSignedUrlCallback): void; + lock(metageneration: number | string): Promise; + lock(metageneration: number | string, callback: BucketLockCallback): void; + /** + * @typedef {object} RestoreOptions Options for Bucket#restore(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/restore#resource| Object resource}. + * @param {number} [generation] If present, selects a specific revision of this object. + * @param {string} [projection] Specifies the set of properties to return. If used, must be 'full' or 'noAcl'. + */ + /** + * Restores a soft-deleted bucket + * @param {RestoreOptions} options Restore options. + * @returns {Promise} + */ + restore(options: RestoreOptions): Promise; + makePrivate(options?: MakeBucketPrivateOptions): Promise; + makePrivate(callback: MakeBucketPrivateCallback): void; + makePrivate(options: MakeBucketPrivateOptions, callback: MakeBucketPrivateCallback): void; + makePublic(options?: MakeBucketPublicOptions): Promise; + makePublic(callback: MakeBucketPublicCallback): void; + makePublic(options: MakeBucketPublicOptions, callback: MakeBucketPublicCallback): void; + /** + * Get a reference to a Cloud Pub/Sub Notification. + * + * @param {string} id ID of notification. + * @returns {Notification} + * @see Notification + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const notification = bucket.notification('1'); + * ``` + */ + notification(id: string): Notification; + removeRetentionPeriod(options?: SetBucketMetadataOptions): Promise; + removeRetentionPeriod(callback: SetBucketMetadataCallback): void; + removeRetentionPeriod(options: SetBucketMetadataOptions, callback: SetBucketMetadataCallback): void; + request(reqOpts: DecorateRequestOptions): Promise; + request(reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void; + setLabels(labels: Labels, options?: SetLabelsOptions): Promise; + setLabels(labels: Labels, callback: SetLabelsCallback): void; + setLabels(labels: Labels, options: SetLabelsOptions, callback: SetLabelsCallback): void; + setMetadata(metadata: BucketMetadata, options?: SetMetadataOptions): Promise>; + setMetadata(metadata: BucketMetadata, callback: MetadataCallback): void; + setMetadata(metadata: BucketMetadata, options: SetMetadataOptions, callback: MetadataCallback): void; + setRetentionPeriod(duration: number, options?: SetBucketMetadataOptions): Promise; + setRetentionPeriod(duration: number, callback: SetBucketMetadataCallback): void; + setRetentionPeriod(duration: number, options: SetBucketMetadataOptions, callback: SetBucketMetadataCallback): void; + setCorsConfiguration(corsConfiguration: Cors[], options?: SetBucketMetadataOptions): Promise; + setCorsConfiguration(corsConfiguration: Cors[], callback: SetBucketMetadataCallback): void; + setCorsConfiguration(corsConfiguration: Cors[], options: SetBucketMetadataOptions, callback: SetBucketMetadataCallback): void; + setStorageClass(storageClass: string, options?: SetBucketStorageClassOptions): Promise; + setStorageClass(storageClass: string, callback: SetBucketStorageClassCallback): void; + setStorageClass(storageClass: string, options: SetBucketStorageClassOptions, callback: SetBucketStorageClassCallback): void; + /** + * Set a user project to be billed for all requests made from this Bucket + * object and any files referenced from this Bucket object. + * + * @param {string} userProject The user project. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.setUserProject('grape-spaceship-123'); + * ``` + */ + setUserProject(userProject: string): void; + upload(pathString: string, options?: UploadOptions): Promise; + upload(pathString: string, options: UploadOptions, callback: UploadCallback): void; + upload(pathString: string, callback: UploadCallback): void; + makeAllFilesPublicPrivate_(options?: MakeAllFilesPublicPrivateOptions): Promise; + makeAllFilesPublicPrivate_(callback: MakeAllFilesPublicPrivateCallback): void; + makeAllFilesPublicPrivate_(options: MakeAllFilesPublicPrivateOptions, callback: MakeAllFilesPublicPrivateCallback): void; + getId(): string; + disableAutoRetryConditionallyIdempotent_(coreOpts: any, methodType: AvailableServiceObjectMethods, localPreconditionOptions?: PreconditionOptions): void; +} +/** + * Reference to the {@link Bucket} class. + * @name module:@google-cloud/storage.Bucket + * @see Bucket + */ +export { Bucket }; diff --git a/node_modules/@google-cloud/storage/build/esm/src/bucket.js b/node_modules/@google-cloud/storage/build/esm/src/bucket.js new file mode 100644 index 0000000..919282e --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/bucket.js @@ -0,0 +1,3534 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +import { ServiceObject, util, } from './nodejs-common/index.js'; +import { paginator } from '@google-cloud/paginator'; +import { promisifyAll } from '@google-cloud/promisify'; +import * as fs from 'fs'; +import mime from 'mime'; +import * as path from 'path'; +import pLimit from 'p-limit'; +import { promisify } from 'util'; +import AsyncRetry from 'async-retry'; +import { convertObjKeysToSnakeCase } from './util.js'; +import { Acl } from './acl.js'; +import { File, } from './file.js'; +import { Iam } from './iam.js'; +import { Notification } from './notification.js'; +import { IdempotencyStrategy, } from './storage.js'; +import { URLSigner, } from './signer.js'; +import { Readable } from 'stream'; +import { URL } from 'url'; +export var BucketActionToHTTPMethod; +(function (BucketActionToHTTPMethod) { + BucketActionToHTTPMethod["list"] = "GET"; +})(BucketActionToHTTPMethod || (BucketActionToHTTPMethod = {})); +export var AvailableServiceObjectMethods; +(function (AvailableServiceObjectMethods) { + AvailableServiceObjectMethods[AvailableServiceObjectMethods["setMetadata"] = 0] = "setMetadata"; + AvailableServiceObjectMethods[AvailableServiceObjectMethods["delete"] = 1] = "delete"; +})(AvailableServiceObjectMethods || (AvailableServiceObjectMethods = {})); +export var BucketExceptionMessages; +(function (BucketExceptionMessages) { + BucketExceptionMessages["PROVIDE_SOURCE_FILE"] = "You must provide at least one source file."; + BucketExceptionMessages["DESTINATION_FILE_NOT_SPECIFIED"] = "A destination file must be specified."; + BucketExceptionMessages["CHANNEL_ID_REQUIRED"] = "An ID is required to create a channel."; + BucketExceptionMessages["TOPIC_NAME_REQUIRED"] = "A valid topic name is required."; + BucketExceptionMessages["CONFIGURATION_OBJECT_PREFIX_REQUIRED"] = "A configuration object with a prefix is required."; + BucketExceptionMessages["SPECIFY_FILE_NAME"] = "A file name must be specified."; + BucketExceptionMessages["METAGENERATION_NOT_PROVIDED"] = "A metageneration must be provided."; + BucketExceptionMessages["SUPPLY_NOTIFICATION_ID"] = "You must supply a notification ID."; +})(BucketExceptionMessages || (BucketExceptionMessages = {})); +/** + * @callback Crc32cGeneratorToStringCallback + * A method returning the CRC32C as a base64-encoded string. + * + * @returns {string} + * + * @example + * Hashing the string 'data' should return 'rth90Q==' + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.toString(); // 'rth90Q==' + * ``` + **/ +/** + * @callback Crc32cGeneratorValidateCallback + * A method validating a base64-encoded CRC32C string. + * + * @param {string} [value] base64-encoded CRC32C string to validate + * @returns {boolean} + * + * @example + * Should return `true` if the value matches, `false` otherwise + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.validate('DkjKuA=='); // false + * crc32c.validate('rth90Q=='); // true + * ``` + **/ +/** + * @callback Crc32cGeneratorUpdateCallback + * A method for passing `Buffer`s for CRC32C generation. + * + * @param {Buffer} [data] data to update CRC32C value with + * @returns {undefined} + * + * @example + * Hashing buffers from 'some ' and 'text\n' + * + * ```js + * const buffer1 = Buffer.from('some '); + * crc32c.update(buffer1); + * + * const buffer2 = Buffer.from('text\n'); + * crc32c.update(buffer2); + * + * crc32c.toString(); // 'DkjKuA==' + * ``` + **/ +/** + * @typedef {object} CRC32CValidator + * @property {Crc32cGeneratorToStringCallback} + * @property {Crc32cGeneratorValidateCallback} + * @property {Crc32cGeneratorUpdateCallback} + */ +/** + * A function that generates a CRC32C Validator. Defaults to {@link CRC32C} + * + * @name Bucket#crc32cGenerator + * @type {CRC32CValidator} + */ +/** + * Get and set IAM policies for your bucket. + * + * @name Bucket#iam + * @mixes Iam + * + * See {@link https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management| Cloud Storage IAM Management} + * See {@link https://cloud.google.com/iam/docs/granting-changing-revoking-access| Granting, Changing, and Revoking Access} + * See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Get the IAM policy for your bucket. + * //- + * bucket.iam.getPolicy(function(err, policy) { + * console.log(policy); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.iam.getPolicy().then(function(data) { + * const policy = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/iam.js + * region_tag:storage_view_bucket_iam_members + * Example of retrieving a bucket's IAM policy: + * + * @example include:samples/iam.js + * region_tag:storage_add_bucket_iam_member + * Example of adding to a bucket's IAM policy: + * + * @example include:samples/iam.js + * region_tag:storage_remove_bucket_iam_member + * Example of removing from a bucket's IAM policy: + */ +/** + * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share objects with other + * users and allow other users to access your buckets and objects. + * + * An ACL consists of one or more entries, where each entry grants permissions + * to an entity. Permissions define the actions that can be performed against + * an object or bucket (for example, `READ` or `WRITE`); the entity defines + * who the permission applies to (for example, a specific user or group of + * users). + * + * The `acl` object on a Bucket instance provides methods to get you a list of + * the ACLs defined on your bucket, as well as set, update, and delete them. + * + * Buckets also have + * {@link https://cloud.google.com/storage/docs/access-control/lists#default| default ACLs} + * for all created files. Default ACLs specify permissions that all new + * objects added to the bucket will inherit by default. You can add, delete, + * get, and update entities and permissions for these as well with + * {@link Bucket#acl.default}. + * + * See {@link http://goo.gl/6qBBPO| About Access Control Lists} + * See {@link https://cloud.google.com/storage/docs/access-control/lists#default| Default ACLs} + * + * @name Bucket#acl + * @mixes Acl + * @property {Acl} default Cloud Storage Buckets have + * {@link https://cloud.google.com/storage/docs/access-control/lists#default| default ACLs} + * for all created files. You can add, delete, get, and update entities and + * permissions for these as well. The method signatures and examples are all + * the same, after only prefixing the method call with `default`. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // Make a bucket's contents publicly readable. + * //- + * const myBucket = storage.bucket('my-bucket'); + * + * const options = { + * entity: 'allUsers', + * role: storage.acl.READER_ROLE + * }; + * + * myBucket.acl.add(options, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myBucket.acl.add(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/acl.js + * region_tag:storage_print_bucket_acl + * Example of printing a bucket's ACL: + * + * @example include:samples/acl.js + * region_tag:storage_print_bucket_acl_for_user + * Example of printing a bucket's ACL for a specific user: + * + * @example include:samples/acl.js + * region_tag:storage_add_bucket_owner + * Example of adding an owner to a bucket: + * + * @example include:samples/acl.js + * region_tag:storage_remove_bucket_owner + * Example of removing an owner from a bucket: + * + * @example include:samples/acl.js + * region_tag:storage_add_bucket_default_owner + * Example of adding a default owner to a bucket: + * + * @example include:samples/acl.js + * region_tag:storage_remove_bucket_default_owner + * Example of removing a default owner from a bucket: + */ +/** + * The API-formatted resource description of the bucket. + * + * Note: This is not guaranteed to be up-to-date when accessed. To get the + * latest record, call the `getMetadata()` method. + * + * @name Bucket#metadata + * @type {object} + */ +/** + * The bucket's name. + * @name Bucket#name + * @type {string} + */ +/** + * Get {@link File} objects for the files currently in the bucket as a + * readable object stream. + * + * @method Bucket#getFilesStream + * @param {GetFilesOptions} [query] Query object for listing files. + * @returns {ReadableStream} A readable stream that emits {@link File} instances. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.getFilesStream() + * .on('error', console.error) + * .on('data', function(file) { + * // file is a File object. + * }) + * .on('end', function() { + * // All files retrieved. + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * bucket.getFilesStream() + * .on('data', function(file) { + * this.end(); + * }); + * + * //- + * // If you're filtering files with a delimiter, you should use + * // {@link Bucket#getFiles} and set `autoPaginate: false` in order to + * // preserve the `apiResponse` argument. + * //- + * const prefixes = []; + * + * function callback(err, files, nextQuery, apiResponse) { + * prefixes = prefixes.concat(apiResponse.prefixes); + * + * if (nextQuery) { + * bucket.getFiles(nextQuery, callback); + * } else { + * // prefixes = The finished array of prefixes. + * } + * } + * + * bucket.getFiles({ + * autoPaginate: false, + * delimiter: '/' + * }, callback); + * ``` + */ +/** + * Create a Bucket object to interact with a Cloud Storage bucket. + * + * @class + * @hideconstructor + * + * @param {Storage} storage A {@link Storage} instance. + * @param {string} name The name of the bucket. + * @param {object} [options] Configuration object. + * @param {string} [options.userProject] User project. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * ``` + */ +class Bucket extends ServiceObject { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getFilesStream(query) { + // placeholder body, overwritten in constructor + return new Readable(); + } + constructor(storage, name, options) { + var _a, _b, _c, _d; + options = options || {}; + // Allow for "gs://"-style input, and strip any trailing slashes. + name = name.replace(/^gs:\/\//, '').replace(/\/+$/, ''); + const requestQueryObject = {}; + if ((_a = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) { + requestQueryObject.ifGenerationMatch = + options.preconditionOpts.ifGenerationMatch; + } + if ((_b = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _b === void 0 ? void 0 : _b.ifGenerationNotMatch) { + requestQueryObject.ifGenerationNotMatch = + options.preconditionOpts.ifGenerationNotMatch; + } + if ((_c = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _c === void 0 ? void 0 : _c.ifMetagenerationMatch) { + requestQueryObject.ifMetagenerationMatch = + options.preconditionOpts.ifMetagenerationMatch; + } + if ((_d = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _d === void 0 ? void 0 : _d.ifMetagenerationNotMatch) { + requestQueryObject.ifMetagenerationNotMatch = + options.preconditionOpts.ifMetagenerationNotMatch; + } + const userProject = options.userProject; + if (typeof userProject === 'string') { + requestQueryObject.userProject = userProject; + } + const methods = { + /** + * Create a bucket. + * + * @method Bucket#create + * @param {CreateBucketRequest} [metadata] Metadata to set for the bucket. + * @param {CreateBucketCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * bucket.create(function(err, bucket, apiResponse) { + * if (!err) { + * // The bucket was created successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.create().then(function(data) { + * const bucket = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + create: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * IamDeleteBucketOptions Configuration options. + * @property {boolean} [ignoreNotFound = false] Ignore an error if + * the bucket does not exist. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @typedef {array} DeleteBucketResponse + * @property {object} 0 The full API response. + */ + /** + * @callback DeleteBucketCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Delete the bucket. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/delete| Buckets: delete API Documentation} + * + * @method Bucket#delete + * @param {DeleteBucketOptions} [options] Configuration options. + * @param {boolean} [options.ignoreNotFound = false] Ignore an error if + * the bucket does not exist. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {DeleteBucketCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * bucket.delete(function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.delete().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example include:samples/buckets.js + * region_tag:storage_delete_bucket + * Another example: + */ + delete: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {object} BucketExistsOptions Configuration options for Bucket#exists(). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @typedef {array} BucketExistsResponse + * @property {boolean} 0 Whether the {@link Bucket} exists. + */ + /** + * @callback BucketExistsCallback + * @param {?Error} err Request error, if any. + * @param {boolean} exists Whether the {@link Bucket} exists. + */ + /** + * Check if the bucket exists. + * + * @method Bucket#exists + * @param {BucketExistsOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {BucketExistsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.exists(function(err, exists) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.exists().then(function(data) { + * const exists = data[0]; + * }); + * ``` + */ + exists: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {object} [GetBucketOptions] Configuration options for Bucket#get() + * @property {boolean} [autoCreate] Automatically create the object if + * it does not exist. Default: `false` + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @typedef {array} GetBucketResponse + * @property {Bucket} 0 The {@link Bucket}. + * @property {object} 1 The full API response. + */ + /** + * @callback GetBucketCallback + * @param {?Error} err Request error, if any. + * @param {Bucket} bucket The {@link Bucket}. + * @param {object} apiResponse The full API response. + */ + /** + * Get a bucket if it exists. + * + * You may optionally use this to "get or create" an object by providing + * an object with `autoCreate` set to `true`. Any extra configuration that + * is normally required for the `create` method must be contained within + * this object as well. + * + * @method Bucket#get + * @param {GetBucketOptions} [options] Configuration options. + * @param {boolean} [options.autoCreate] Automatically create the object if + * it does not exist. Default: `false` + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetBucketCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.get(function(err, bucket, apiResponse) { + * // `bucket.metadata` has been populated. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.get().then(function(data) { + * const bucket = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + get: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {array} GetBucketMetadataResponse + * @property {object} 0 The bucket metadata. + * @property {object} 1 The full API response. + */ + /** + * @callback GetBucketMetadataCallback + * @param {?Error} err Request error, if any. + * @param {object} metadata The bucket metadata. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {object} GetBucketMetadataOptions Configuration options for Bucket#getMetadata(). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * Get the bucket's metadata. + * + * To set metadata, see {@link Bucket#setMetadata}. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/get| Buckets: get API Documentation} + * + * @method Bucket#getMetadata + * @param {GetBucketMetadataOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetBucketMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.getMetadata(function(err, metadata, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.getMetadata().then(function(data) { + * const metadata = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/requesterPays.js + * region_tag:storage_get_requester_pays_status + * Example of retrieving the requester pays status of a bucket: + */ + getMetadata: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {object} SetBucketMetadataOptions Configuration options for Bucket#setMetadata(). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @typedef {array} SetBucketMetadataResponse + * @property {object} apiResponse The full API response. + */ + /** + * @callback SetBucketMetadataCallback + * @param {?Error} err Request error, if any. + * @param {object} metadata The bucket metadata. + */ + /** + * Set the bucket's metadata. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch| Buckets: patch API Documentation} + * + * @method Bucket#setMetadata + * @param {object} metadata The metadata you wish to set. + * @param {SetBucketMetadataOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {SetBucketMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Set website metadata field on the bucket. + * //- + * const metadata = { + * website: { + * mainPageSuffix: 'http://example.com', + * notFoundPage: 'http://example.com/404.html' + * } + * }; + * + * bucket.setMetadata(metadata, function(err, apiResponse) {}); + * + * //- + * // Enable versioning for your bucket. + * //- + * bucket.setMetadata({ + * versioning: { + * enabled: true + * } + * }, function(err, apiResponse) {}); + * + * //- + * // Enable KMS encryption for objects within this bucket. + * //- + * bucket.setMetadata({ + * encryption: { + * defaultKmsKeyName: 'projects/grape-spaceship-123/...' + * } + * }, function(err, apiResponse) {}); + * + * //- + * // Set the default event-based hold value for new objects in this + * // bucket. + * //- + * bucket.setMetadata({ + * defaultEventBasedHold: true + * }, function(err, apiResponse) {}); + * + * //- + * // Remove object lifecycle rules. + * //- + * bucket.setMetadata({ + * lifecycle: null + * }, function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.setMetadata(metadata).then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + setMetadata: { + reqOpts: { + qs: requestQueryObject, + }, + }, + }; + super({ + parent: storage, + baseUrl: '/b', + id: name, + createMethod: storage.createBucket.bind(storage), + methods, + }); + /** + * Indicates whether this Bucket object is a placeholder for an item + * that the API failed to retrieve (unreachable) due to partial failure. + * Consumers must check this flag before accessing other properties. + */ + this.unreachable = false; + this.name = name; + this.storage = storage; + this.userProject = options.userProject; + this.acl = new Acl({ + request: this.request.bind(this), + pathPrefix: '/acl', + }); + this.acl.default = new Acl({ + request: this.request.bind(this), + pathPrefix: '/defaultObjectAcl', + }); + this.crc32cGenerator = + options.crc32cGenerator || this.storage.crc32cGenerator; + this.iam = new Iam(this); + this.getFilesStream = paginator.streamify('getFiles'); + this.instanceRetryValue = storage.retryOptions.autoRetry; + this.instancePreconditionOpts = options === null || options === void 0 ? void 0 : options.preconditionOpts; + } + /** + * The bucket's Cloud Storage URI (`gs://`) + * + * @example + * ```ts + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * // `gs://my-bucket` + * const href = bucket.cloudStorageURI.href; + * ``` + */ + get cloudStorageURI() { + const uri = new URL('gs://'); + uri.host = this.name; + return uri; + } + /** + * @typedef {object} AddLifecycleRuleOptions Configuration options for Bucket#addLifecycleRule(). + * @property {boolean} [append=true] The new rules will be appended to any + * pre-existing rules. + */ + /** + * + * @typedef {object} LifecycleRule The new lifecycle rule to be added to objects + * in this bucket. + * @property {string|object} action The action to be taken upon matching of + * all the conditions 'delete', 'setStorageClass', or 'AbortIncompleteMultipartUpload'. + * **Note**: For configuring a raw-formatted rule object to be passed as `action` + * please refer to the [examples]{@link https://cloud.google.com/storage/docs/managing-lifecycles#configexamples}. + * @property {object} condition Condition a bucket must meet before the + * action occurs on the bucket. Refer to following supported [conditions]{@link https://cloud.google.com/storage/docs/lifecycle#conditions}. + * @property {string} [storageClass] When using the `setStorageClass` + * action, provide this option to dictate which storage class the object + * should update to. Please see + * [SetStorageClass option documentation]{@link https://cloud.google.com/storage/docs/lifecycle#setstorageclass} for supported transitions. + */ + /** + * Add an object lifecycle management rule to the bucket. + * + * By default, an Object Lifecycle Management rule provided to this method + * will be included to the existing policy. To replace all existing rules, + * supply the `options` argument, setting `append` to `false`. + * + * To add multiple rules, pass a list to the `rule` parameter. Calling this + * function multiple times asynchronously does not guarantee that all rules + * are added correctly. + * + * See {@link https://cloud.google.com/storage/docs/lifecycle| Object Lifecycle Management} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch| Buckets: patch API Documentation} + * + * @param {LifecycleRule|LifecycleRule[]} rule The new lifecycle rule or rules to be added to objects + * in this bucket. + * @param {string|object} rule.action The action to be taken upon matching of + * all the conditions 'delete', 'setStorageClass', or 'AbortIncompleteMultipartUpload'. + * **Note**: For configuring a raw-formatted rule object to be passed as `action` + * please refer to the [examples]{@link https://cloud.google.com/storage/docs/managing-lifecycles#configexamples}. + * @param {object} rule.condition Condition a bucket must meet before the + * action occurs on the bucket. Refer to following supported [conditions]{@link https://cloud.google.com/storage/docs/lifecycle#conditions}. + * @param {string} [rule.storageClass] When using the `setStorageClass` + * action, provide this option to dictate which storage class the object + * should update to. + * @param {AddLifecycleRuleOptions} [options] Configuration object. + * @param {boolean} [options.append=true] Append the new rule to the existing + * policy. + * @param {SetBucketMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Automatically have an object deleted from this bucket once it is 3 years + * // of age. + * //- + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * age: 365 * 3 // Specified in days. + * } + * }, function(err, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * const lifecycleRules = bucket.metadata.lifecycle.rule; + * + * // Iterate over the Object Lifecycle Management rules on this bucket. + * lifecycleRules.forEach(lifecycleRule => {}); + * }); + * + * //- + * // By default, the rule you provide will be added to the existing policy. + * // Optionally, you can disable this behavior to replace all of the + * // pre-existing rules. + * //- + * const options = { + * append: false + * }; + * + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * age: 365 * 3 // Specified in days. + * } + * }, options, function(err, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * // All rules have been replaced with the new "delete" rule. + * + * // Iterate over the Object Lifecycle Management rules on this bucket. + * lifecycleRules.forEach(lifecycleRule => {}); + * }); + * + * //- + * // For objects created before 2018, "downgrade" the storage class. + * //- + * bucket.addLifecycleRule({ + * action: 'setStorageClass', + * storageClass: 'COLDLINE', + * condition: { + * createdBefore: new Date('2018') + * } + * }, function(err, apiResponse) {}); + * + * //- + * // Delete objects created before 2016 which have the Coldline storage + * // class. + * //- + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * matchesStorageClass: [ + * 'COLDLINE' + * ], + * createdBefore: new Date('2016') + * } + * }, function(err, apiResponse) {}); + * + * //- + * // Delete object that has a noncurrent timestamp that is at least 100 days. + * //- + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * daysSinceNoncurrentTime: 100 + * } + * }, function(err, apiResponse) {}); + * + * //- + * // Delete object that has a noncurrent timestamp before 2020-01-01. + * //- + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * noncurrentTimeBefore: new Date('2020-01-01') + * } + * }, function(err, apiResponse) {}); + * + * //- + * // Delete object that has a customTime that is at least 100 days. + * //- + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * daysSinceCustomTime: 100 + * } + * }, function(err, apiResponse) ()); + * + * //- + * // Delete object that has a customTime before 2020-01-01. + * //- + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * customTimeBefore: new Date('2020-01-01') + * } + * }, function(err, apiResponse) {}); + * ``` + */ + addLifecycleRule(rule, optionsOrCallback, callback) { + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else if (optionsOrCallback) { + options = optionsOrCallback; + } + options = options || {}; + const rules = Array.isArray(rule) ? rule : [rule]; + for (const curRule of rules) { + if (curRule.condition.createdBefore instanceof Date) { + curRule.condition.createdBefore = curRule.condition.createdBefore + .toISOString() + .replace(/T.+$/, ''); + } + if (curRule.condition.customTimeBefore instanceof Date) { + curRule.condition.customTimeBefore = curRule.condition.customTimeBefore + .toISOString() + .replace(/T.+$/, ''); + } + if (curRule.condition.noncurrentTimeBefore instanceof Date) { + curRule.condition.noncurrentTimeBefore = + curRule.condition.noncurrentTimeBefore + .toISOString() + .replace(/T.+$/, ''); + } + } + if (options.append === false) { + this.setMetadata({ lifecycle: { rule: rules } }, options, callback); + return; + } + // The default behavior appends the previously-defined lifecycle rules with + // the new ones just passed in by the user. + this.getMetadata((err, metadata) => { + var _a, _b; + if (err) { + callback(err); + return; + } + const currentLifecycleRules = Array.isArray((_a = metadata.lifecycle) === null || _a === void 0 ? void 0 : _a.rule) + ? (_b = metadata.lifecycle) === null || _b === void 0 ? void 0 : _b.rule + : []; + this.setMetadata({ + lifecycle: { rule: currentLifecycleRules.concat(rules) }, + }, options, callback); + }); + } + /** + * @typedef {object} CombineOptions + * @property {string} [kmsKeyName] Resource name of the Cloud KMS key, of + * the form + * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`, + * that will be used to encrypt the object. Overwrites the object + * metadata's `kms_key_name` value, if any. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @callback CombineCallback + * @param {?Error} err Request error, if any. + * @param {File} newFile The new {@link File}. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} CombineResponse + * @property {File} 0 The new {@link File}. + * @property {object} 1 The full API response. + */ + /** + * Combine multiple files into one new file. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/compose| Objects: compose API Documentation} + * + * @throws {Error} if a non-array is provided as sources argument. + * @throws {Error} if no sources are provided. + * @throws {Error} if no destination is provided. + * + * @param {string[]|File[]} sources The source files that will be + * combined. + * @param {string|File} destination The file you would like the + * source files combined into. + * @param {CombineOptions} [options] Configuration options. + * @param {string} [options.kmsKeyName] Resource name of the Cloud KMS key, of + * the form + * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`, + * that will be used to encrypt the object. Overwrites the object + * metadata's `kms_key_name` value, if any. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + + * @param {CombineCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const logBucket = storage.bucket('log-bucket'); + * + * const sources = [ + * logBucket.file('2013-logs.txt'), + * logBucket.file('2014-logs.txt') + * ]; + * + * const allLogs = logBucket.file('all-logs.txt'); + * + * logBucket.combine(sources, allLogs, function(err, newFile, apiResponse) { + * // newFile === allLogs + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * logBucket.combine(sources, allLogs).then(function(data) { + * const newFile = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + combine(sources, destination, optionsOrCallback, callback) { + var _a; + if (!Array.isArray(sources) || sources.length === 0) { + throw new Error(BucketExceptionMessages.PROVIDE_SOURCE_FILE); + } + if (!destination) { + throw new Error(BucketExceptionMessages.DESTINATION_FILE_NOT_SPECIFIED); + } + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else if (optionsOrCallback) { + options = optionsOrCallback; + } + this.disableAutoRetryConditionallyIdempotent_(this.methods.setMetadata, // Not relevant but param is required + AvailableServiceObjectMethods.setMetadata, // Same as above + options); + const convertToFile = (file) => { + if (file instanceof File) { + return file; + } + return this.file(file); + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sources = sources.map(convertToFile); + const destinationFile = convertToFile(destination); + callback = callback || util.noop; + if (!destinationFile.metadata.contentType) { + const destinationContentType = mime.getType(destinationFile.name) || undefined; + if (destinationContentType) { + destinationFile.metadata.contentType = destinationContentType; + } + } + let maxRetries = this.storage.retryOptions.maxRetries; + if ((((_a = destinationFile === null || destinationFile === void 0 ? void 0 : destinationFile.instancePreconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) === + undefined && + options.ifGenerationMatch === undefined && + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryConditional) || + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryNever) { + maxRetries = 0; + } + if (options.ifGenerationMatch === undefined) { + Object.assign(options, destinationFile.instancePreconditionOpts, options); + } + // Make the request from the destination File object. + destinationFile.request({ + method: 'POST', + uri: '/compose', + maxRetries, + json: { + destination: { + contentType: destinationFile.metadata.contentType, + contentEncoding: destinationFile.metadata.contentEncoding, + }, + sourceObjects: sources.map(source => { + const sourceObject = { + name: source.name, + }; + if (source.metadata && source.metadata.generation) { + sourceObject.generation = parseInt(source.metadata.generation.toString()); + } + return sourceObject; + }), + }, + qs: options, + }, (err, resp) => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + if (err) { + callback(err, null, resp); + return; + } + callback(null, destinationFile, resp); + }); + } + /** + * See a {@link https://cloud.google.com/storage/docs/json_api/v1/objects/watchAll| Objects: watchAll request body}. + * + * @typedef {object} CreateChannelConfig + * @property {string} address The address where notifications are + * delivered for this channel. + * @property {string} [delimiter] Returns results in a directory-like mode. + * @property {number} [maxResults] Maximum number of `items` plus `prefixes` + * to return in a single page of responses. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @property {string} [prefix] Filter results to objects whose names begin + * with this prefix. + * @property {string} [projection=noAcl] Set of properties to return. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {boolean} [versions=false] If `true`, lists all versions of an object + * as distinct results. + */ + /** + * @typedef {object} CreateChannelOptions + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @typedef {array} CreateChannelResponse + * @property {Channel} 0 The new {@link Channel}. + * @property {object} 1 The full API response. + */ + /** + * @callback CreateChannelCallback + * @param {?Error} err Request error, if any. + * @param {Channel} channel The new {@link Channel}. + * @param {object} apiResponse The full API response. + */ + /** + * Create a channel that will be notified when objects in this bucket changes. + * + * @throws {Error} If an ID is not provided. + * @throws {Error} If an address is not provided. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/watchAll| Objects: watchAll API Documentation} + * + * @param {string} id The ID of the channel to create. + * @param {CreateChannelConfig} config Configuration for creating channel. + * @param {string} config.address The address where notifications are + * delivered for this channel. + * @param {string} [config.delimiter] Returns results in a directory-like mode. + * @param {number} [config.maxResults] Maximum number of `items` plus `prefixes` + * to return in a single page of responses. + * @param {string} [config.pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @param {string} [config.prefix] Filter results to objects whose names begin + * with this prefix. + * @param {string} [config.projection=noAcl] Set of properties to return. + * @param {string} [config.userProject] The ID of the project which will be + * billed for the request. + * @param {boolean} [config.versions=false] If `true`, lists all versions of an object + * as distinct results. + * @param {CreateChannelOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {CreateChannelCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * const id = 'new-channel-id'; + * + * const config = { + * address: 'https://...' + * }; + * + * bucket.createChannel(id, config, function(err, channel, apiResponse) { + * if (!err) { + * // Channel created successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.createChannel(id, config).then(function(data) { + * const channel = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + createChannel(id, config, optionsOrCallback, callback) { + if (typeof id !== 'string') { + throw new Error(BucketExceptionMessages.CHANNEL_ID_REQUIRED); + } + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else if (optionsOrCallback) { + options = optionsOrCallback; + } + this.request({ + method: 'POST', + uri: '/o/watch', + json: Object.assign({ + id, + type: 'web_hook', + }, config), + qs: options, + }, (err, apiResponse) => { + if (err) { + callback(err, null, apiResponse); + return; + } + const resourceId = apiResponse.resourceId; + const channel = this.storage.channel(id, resourceId); + channel.metadata = apiResponse; + callback(null, channel, apiResponse); + }); + } + /** + * Metadata to set for the Notification. + * + * @typedef {object} CreateNotificationOptions + * @property {object} [customAttributes] An optional list of additional + * attributes to attach to each Cloud PubSub message published for this + * notification subscription. + * @property {string[]} [eventTypes] If present, only send notifications about + * listed event types. If empty, sent notifications for all event types. + * @property {string} [objectNamePrefix] If present, only apply this + * notification configuration to object names that begin with this prefix. + * @property {string} [payloadFormat] The desired content of the Payload. + * Defaults to `JSON_API_V1`. + * + * Acceptable values are: + * - `JSON_API_V1` + * + * - `NONE` + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @callback CreateNotificationCallback + * @param {?Error} err Request error, if any. + * @param {Notification} notification The new {@link Notification}. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} CreateNotificationResponse + * @property {Notification} 0 The new {@link Notification}. + * @property {object} 1 The full API response. + */ + /** + * Creates a notification subscription for the bucket. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/insert| Notifications: insert} + * + * @param {Topic|string} topic The Cloud PubSub topic to which this + * subscription publishes. If the project ID is omitted, the current + * project ID will be used. + * + * Acceptable formats are: + * - `projects/grape-spaceship-123/topics/my-topic` + * + * - `my-topic` + * @param {CreateNotificationOptions} [options] Metadata to set for the + * notification. + * @param {object} [options.customAttributes] An optional list of additional + * attributes to attach to each Cloud PubSub message published for this + * notification subscription. + * @param {string[]} [options.eventTypes] If present, only send notifications about + * listed event types. If empty, sent notifications for all event types. + * @param {string} [options.objectNamePrefix] If present, only apply this + * notification configuration to object names that begin with this prefix. + * @param {string} [options.payloadFormat] The desired content of the Payload. + * Defaults to `JSON_API_V1`. + * + * Acceptable values are: + * - `JSON_API_V1` + * + * - `NONE` + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {CreateNotificationCallback} [callback] Callback function. + * @returns {Promise} + * @throws {Error} If a valid topic is not provided. + * @see Notification#create + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const callback = function(err, notification, apiResponse) { + * if (!err) { + * // The notification was created successfully. + * } + * }; + * + * myBucket.createNotification('my-topic', callback); + * + * //- + * // Configure the notification by providing Notification metadata. + * //- + * const metadata = { + * objectNamePrefix: 'prefix-' + * }; + * + * myBucket.createNotification('my-topic', metadata, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myBucket.createNotification('my-topic').then(function(data) { + * const notification = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/createNotification.js + * region_tag:storage_create_bucket_notifications + * Another example: + */ + createNotification(topic, optionsOrCallback, callback) { + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else if (optionsOrCallback) { + options = optionsOrCallback; + } + const topicIsObject = topic !== null && typeof topic === 'object'; + if (topicIsObject && util.isCustomType(topic, 'pubsub/topic')) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + topic = topic.name; + } + if (typeof topic !== 'string') { + throw new Error(BucketExceptionMessages.TOPIC_NAME_REQUIRED); + } + const body = Object.assign({ topic }, options); + if (body.topic.indexOf('projects') !== 0) { + body.topic = 'projects/{{projectId}}/topics/' + body.topic; + } + body.topic = `//pubsub.${this.storage.universeDomain}/` + body.topic; + if (!body.payloadFormat) { + body.payloadFormat = 'JSON_API_V1'; + } + const query = {}; + if (body.userProject) { + query.userProject = body.userProject; + delete body.userProject; + } + this.request({ + method: 'POST', + uri: '/notificationConfigs', + json: convertObjKeysToSnakeCase(body), + qs: query, + maxRetries: 0, //explicitly set this value since this is a non-idempotent function + }, (err, apiResponse) => { + if (err) { + callback(err, null, apiResponse); + return; + } + const notification = this.notification(apiResponse.id); + notification.metadata = apiResponse; + callback(null, notification, apiResponse); + }); + } + /** + * @typedef {object} DeleteFilesOptions Query object. See {@link Bucket#getFiles} + * for all of the supported properties. + * @property {boolean} [force] Suppress errors until all files have been + * processed. + */ + /** + * @callback DeleteFilesCallback + * @param {?Error|?Error[]} err Request error, if any, or array of errors from + * files that were not able to be deleted. + * @param {object} [apiResponse] The full API response. + */ + /** + * Iterate over the bucket's files, calling `file.delete()` on each. + * + * This is not an atomic request. A delete attempt will be + * made for each file individually. Any one can fail, in which case only a + * portion of the files you intended to be deleted would have. + * + * Operations are performed in parallel, up to 10 at once. The first error + * breaks the loop and will execute the provided callback with it. Specify + * `{ force: true }` to suppress the errors until all files have had a chance + * to be processed. + * + * File preconditions cannot be passed to this function. It will not retry unless + * the idempotency strategy is set to retry always. + * + * The `query` object passed as the first argument will also be passed to + * {@link Bucket#getFiles}. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/delete| Objects: delete API Documentation} + * + * @param {DeleteFilesOptions} [query] Query object. See {@link Bucket#getFiles} + * @param {boolean} [query.force] Suppress errors until all files have been + * processed. + * @param {DeleteFilesCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Delete all of the files in the bucket. + * //- + * bucket.deleteFiles(function(err) {}); + * + * //- + * // By default, if a file cannot be deleted, this method will stop deleting + * // files from your bucket. You can override this setting with `force: + * // true`. + * //- + * bucket.deleteFiles({ + * force: true + * }, function(errors) { + * // `errors`: + * // Array of errors if any occurred, otherwise null. + * }); + * + * //- + * // The first argument to this method acts as a query to + * // {@link Bucket#getFiles}. As an example, you can delete files + * // which match a prefix. + * //- + * bucket.deleteFiles({ + * prefix: 'images/' + * }, function(err) { + * if (!err) { + * // All files in the `images` directory have been deleted. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.deleteFiles().then(function() {}); + * ``` + */ + deleteFiles(queryOrCallback, callback) { + let query = {}; + if (typeof queryOrCallback === 'function') { + callback = queryOrCallback; + } + else if (queryOrCallback) { + query = queryOrCallback; + } + const MAX_PARALLEL_LIMIT = 10; + const MAX_QUEUE_SIZE = 1000; + const errors = []; + const deleteFile = (file) => { + return file.delete(query).catch(err => { + if (!query.force) { + throw err; + } + errors.push(err); + }); + }; + (async () => { + try { + let promises = []; + const limit = pLimit(MAX_PARALLEL_LIMIT); + const filesStream = this.getFilesStream(query); + for await (const curFile of filesStream) { + if (promises.length >= MAX_QUEUE_SIZE) { + await Promise.all(promises); + promises = []; + } + promises.push(limit(() => deleteFile(curFile)).catch(e => { + filesStream.destroy(); + throw e; + })); + } + await Promise.all(promises); + callback(errors.length > 0 ? errors : null); + } + catch (e) { + callback(e); + return; + } + })(); + } + /** + * @deprecated + * @typedef {array} DeleteLabelsResponse + * @property {object} 0 The full API response. + */ + /** + * @deprecated + * @callback DeleteLabelsCallback + * @param {?Error} err Request error, if any. + * @param {object} metadata Bucket's metadata. + */ + /** + * @deprecated Use setMetadata directly + * Delete one or more labels from this bucket. + * + * @param {string|string[]} [labels] The labels to delete. If no labels are + * provided, all of the labels are removed. + * @param {DeleteLabelsCallback} [callback] Callback function. + * @param {DeleteLabelsOptions} [options] Options, including precondition options + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Delete all of the labels from this bucket. + * //- + * bucket.deleteLabels(function(err, apiResponse) {}); + * + * //- + * // Delete a single label. + * //- + * bucket.deleteLabels('labelone', function(err, apiResponse) {}); + * + * //- + * // Delete a specific set of labels. + * //- + * bucket.deleteLabels([ + * 'labelone', + * 'labeltwo' + * ], function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.deleteLabels().then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + deleteLabels(labelsOrCallbackOrOptions, optionsOrCallback, callback) { + let labels = new Array(); + let options = {}; + if (typeof labelsOrCallbackOrOptions === 'function') { + callback = labelsOrCallbackOrOptions; + } + else if (typeof labelsOrCallbackOrOptions === 'string') { + labels = [labelsOrCallbackOrOptions]; + } + else if (Array.isArray(labelsOrCallbackOrOptions)) { + labels = labelsOrCallbackOrOptions; + } + else if (labelsOrCallbackOrOptions) { + options = labelsOrCallbackOrOptions; + } + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else if (optionsOrCallback) { + options = optionsOrCallback; + } + const deleteLabels = (labels) => { + const nullLabelMap = labels.reduce((nullLabelMap, labelKey) => { + nullLabelMap[labelKey] = null; + return nullLabelMap; + }, {}); + if ((options === null || options === void 0 ? void 0 : options.ifMetagenerationMatch) !== undefined) { + this.setLabels(nullLabelMap, options, callback); + } + else { + this.setLabels(nullLabelMap, callback); + } + }; + if (labels.length === 0) { + this.getLabels((err, labels) => { + if (err) { + callback(err); + return; + } + deleteLabels(Object.keys(labels)); + }); + } + else { + deleteLabels(labels); + } + } + /** + * @typedef {array} DisableRequesterPaysResponse + * @property {object} 0 The full API response. + */ + /** + * @callback DisableRequesterPaysCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + *
+ * Early Access Testers Only + *

+ * This feature is not yet widely-available. + *

+ *
+ * + * Disable `requesterPays` functionality from this bucket. + * + * @param {DisableRequesterPaysCallback} [callback] Callback function. + * @param {DisableRequesterPaysOptions} [options] Options, including precondition options + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.disableRequesterPays(function(err, apiResponse) { + * if (!err) { + * // requesterPays functionality disabled successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.disableRequesterPays().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example include:samples/requesterPays.js + * region_tag:storage_disable_requester_pays + * Example of disabling requester pays: + */ + disableRequesterPays(optionsOrCallback, callback) { + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else if (optionsOrCallback) { + options = optionsOrCallback; + } + this.setMetadata({ + billing: { + requesterPays: false, + }, + }, options, callback); + } + /** + * Configuration object for enabling logging. + * + * @typedef {object} EnableLoggingOptions + * @property {string|Bucket} [bucket] The bucket for the log entries. By + * default, the current bucket is used. + * @property {string} prefix A unique prefix for log object names. + */ + /** + * Enable logging functionality for this bucket. This will make two API + * requests, first to grant Cloud Storage WRITE permission to the bucket, then + * to set the appropriate configuration on the Bucket's metadata. + * + * @param {EnableLoggingOptions} config Configuration options. + * @param {string|Bucket} [config.bucket] The bucket for the log entries. By + * default, the current bucket is used. + * @param {string} config.prefix A unique prefix for log object names. + * @param {SetBucketMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * const config = { + * prefix: 'log' + * }; + * + * bucket.enableLogging(config, function(err, apiResponse) { + * if (!err) { + * // Logging functionality enabled successfully. + * } + * }); + * + * ``` + * @example + * Optionally, provide a destination bucket. + * ``` + * const config = { + * prefix: 'log', + * bucket: 'destination-bucket' + * }; + * + * bucket.enableLogging(config, function(err, apiResponse) {}); + * ``` + * + * @example + * If the callback is omitted, we'll return a Promise. + * ``` + * bucket.enableLogging(config).then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + enableLogging(config, callback) { + if (!config || + typeof config === 'function' || + typeof config.prefix === 'undefined') { + throw new Error(BucketExceptionMessages.CONFIGURATION_OBJECT_PREFIX_REQUIRED); + } + let logBucket = this.id; + if (config.bucket && config.bucket instanceof Bucket) { + logBucket = config.bucket.id; + } + else if (config.bucket && typeof config.bucket === 'string') { + logBucket = config.bucket; + } + const options = {}; + if (config === null || config === void 0 ? void 0 : config.ifMetagenerationMatch) { + options.ifMetagenerationMatch = config.ifMetagenerationMatch; + } + if (config === null || config === void 0 ? void 0 : config.ifMetagenerationNotMatch) { + options.ifMetagenerationNotMatch = config.ifMetagenerationNotMatch; + } + (async () => { + try { + const [policy] = await this.iam.getPolicy(); + policy.bindings.push({ + members: ['group:cloud-storage-analytics@google.com'], + role: 'roles/storage.objectCreator', + }); + await this.iam.setPolicy(policy); + this.setMetadata({ + logging: { + logBucket, + logObjectPrefix: config.prefix, + }, + }, options, callback); + } + catch (e) { + callback(e); + return; + } + })(); + } + /** + * @typedef {array} EnableRequesterPaysResponse + * @property {object} 0 The full API response. + */ + /** + * @callback EnableRequesterPaysCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + *
+ * Early Access Testers Only + *

+ * This feature is not yet widely-available. + *

+ *
+ * + * Enable `requesterPays` functionality for this bucket. This enables you, the + * bucket owner, to have the requesting user assume the charges for the access + * to your bucket and its contents. + * + * @param {EnableRequesterPaysCallback | EnableRequesterPaysOptions} [optionsOrCallback] + * Callback function or precondition options. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.enableRequesterPays(function(err, apiResponse) { + * if (!err) { + * // requesterPays functionality enabled successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.enableRequesterPays().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example include:samples/requesterPays.js + * region_tag:storage_enable_requester_pays + * Example of enabling requester pays: + */ + enableRequesterPays(optionsOrCallback, cb) { + let options = {}; + if (typeof optionsOrCallback === 'function') { + cb = optionsOrCallback; + } + else if (optionsOrCallback) { + options = optionsOrCallback; + } + this.setMetadata({ + billing: { + requesterPays: true, + }, + }, options, cb); + } + /** + * Create a {@link File} object. See {@link File} to see how to handle + * the different use cases you may have. + * + * @param {string} name The name of the file in this bucket. + * @param {FileOptions} [options] Configuration options. + * @param {string|number} [options.generation] Only use a specific revision of + * this file. + * @param {string} [options.encryptionKey] A custom encryption key. See + * {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}. + * @param {string} [options.kmsKeyName] The name of the Cloud KMS key that will + * be used to encrypt the object. Must be in the format: + * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`. + * KMS key ring must use the same location as the bucket. + * @param {string} [options.userProject] The ID of the project which will be + * billed for all requests made from File object. + * @returns {File} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * const file = bucket.file('my-existing-file.png'); + * ``` + */ + file(name, options) { + if (!name) { + throw Error(BucketExceptionMessages.SPECIFY_FILE_NAME); + } + return new File(this, name, options); + } + /** + * @typedef {array} GetFilesResponse + * @property {File[]} 0 Array of {@link File} instances. + * @param {object} nextQuery 1 A query object to receive more results. + * @param {object} apiResponse 2 The full API response. + */ + /** + * @callback GetFilesCallback + * @param {?Error} err Request error, if any. + * @param {File[]} files Array of {@link File} instances. + * @param {object} nextQuery A query object to receive more results. + * @param {object} apiResponse The full API response. + */ + /** + * Query object for listing files. + * + * @typedef {object} GetFilesOptions + * @property {boolean} [autoPaginate=true] Have pagination handled + * automatically. + * @property {string} [delimiter] Results will contain only objects whose + * names, aside from the prefix, do not contain delimiter. Objects whose + * names, aside from the prefix, contain delimiter will have their name + * truncated after the delimiter, returned in `apiResponse.prefixes`. + * Duplicate prefixes are omitted. + * @property {string} [endOffset] Filter results to objects whose names are + * lexicographically before endOffset. If startOffset is also set, the objects + * listed have names between startOffset (inclusive) and endOffset (exclusive). + * @property {boolean} [includeFoldersAsPrefixes] If true, includes folders and + * managed folders in the set of prefixes returned by the query. Only applicable if + * delimiter is set to / and autoPaginate is set to false. + * See: https://cloud.google.com/storage/docs/managed-folders + * @property {boolean} [includeTrailingDelimiter] If true, objects that end in + * exactly one instance of delimiter have their metadata included in items[] + * in addition to the relevant part of the object name appearing in prefixes[]. + * @property {string} [prefix] Filter results to objects whose names begin + * with this prefix. + * @property {string} [matchGlob] A glob pattern used to filter results, + * for example foo*bar + * @property {number} [maxApiCalls] Maximum number of API calls to make. + * @property {number} [maxResults] Maximum number of items plus prefixes to + * return per call. + * Note: By default will handle pagination automatically + * if more than 1 page worth of results are requested per call. + * When `autoPaginate` is set to `false` the smaller of `maxResults` + * or 1 page of results will be returned per call. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @property {boolean} [softDeleted] If true, only soft-deleted object versions will be + * listed as distinct results in order of generation number. Note `soft_deleted` and + * `versions` cannot be set to true simultaneously. + * @property {string} [startOffset] Filter results to objects whose names are + * lexicographically equal to or after startOffset. If endOffset is also set, + * the objects listed have names between startOffset (inclusive) and endOffset (exclusive). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {boolean} [versions] If true, returns File objects scoped to + * their versions. + */ + /** + * Get {@link File} objects for the files currently in the bucket. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/list| Objects: list API Documentation} + * + * @param {GetFilesOptions} [query] Query object for listing files. + * @param {boolean} [query.autoPaginate=true] Have pagination handled + * automatically. + * @param {string} [query.delimiter] Results will contain only objects whose + * names, aside from the prefix, do not contain delimiter. Objects whose + * names, aside from the prefix, contain delimiter will have their name + * truncated after the delimiter, returned in `apiResponse.prefixes`. + * Duplicate prefixes are omitted. + * @param {string} [query.endOffset] Filter results to objects whose names are + * lexicographically before endOffset. If startOffset is also set, the objects + * listed have names between startOffset (inclusive) and endOffset (exclusive). + * @param {boolean} [query.includeFoldersAsPrefixes] If true, includes folders and + * managed folders in the set of prefixes returned by the query. Only applicable if + * delimiter is set to / and autoPaginate is set to false. + * See: https://cloud.google.com/storage/docs/managed-folders + * @param {boolean} [query.includeTrailingDelimiter] If true, objects that end in + * exactly one instance of delimiter have their metadata included in items[] + * in addition to the relevant part of the object name appearing in prefixes[]. + * @param {string} [query.prefix] Filter results to objects whose names begin + * with this prefix. + * @param {number} [query.maxApiCalls] Maximum number of API calls to make. + * @param {number} [query.maxResults] Maximum number of items plus prefixes to + * return per call. + * Note: By default will handle pagination automatically + * if more than 1 page worth of results are requested per call. + * When `autoPaginate` is set to `false` the smaller of `maxResults` + * or 1 page of results will be returned per call. + * @param {string} [query.pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @param {boolean} [query.softDeleted] If true, only soft-deleted object versions will be + * listed as distinct results in order of generation number. Note `soft_deleted` and + * `versions` cannot be set to true simultaneously. + * @param {string} [query.startOffset] Filter results to objects whose names are + * lexicographically equal to or after startOffset. If endOffset is also set, + * the objects listed have names between startOffset (inclusive) and endOffset (exclusive). + * @param {string} [query.userProject] The ID of the project which will be + * billed for the request. + * @param {boolean} [query.versions] If true, returns File objects scoped to + * their versions. + * @param {GetFilesCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.getFiles(function(err, files) { + * if (!err) { + * // files is an array of File objects. + * } + * }); + * + * //- + * // If your bucket has versioning enabled, you can get all of your files + * // scoped to their generation. + * //- + * bucket.getFiles({ + * versions: true + * }, function(err, files) { + * // Each file is scoped to its generation. + * }); + * + * //- + * // To control how many API requests are made and page through the results + * // manually, set `autoPaginate` to `false`. + * //- + * const callback = function(err, files, nextQuery, apiResponse) { + * if (nextQuery) { + * // More results exist. + * bucket.getFiles(nextQuery, callback); + * } + * + * // The `metadata` property is populated for you with the metadata at the + * // time of fetching. + * files[0].metadata; + * + * // However, in cases where you are concerned the metadata could have + * // changed, use the `getMetadata` method. + * files[0].getMetadata(function(err, metadata) {}); + * }; + * + * bucket.getFiles({ + * autoPaginate: false + * }, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.getFiles().then(function(data) { + * const files = data[0]; + * }); + * + * ``` + * @example + *
Simulating a File System

With `autoPaginate: false`, it's possible to iterate over files which incorporate a common structure using a delimiter.

Consider the following remote objects:

  1. "a"
  2. "a/b/c/d"
  3. "b/d/e"

Using a delimiter of `/` will return a single file, "a".

`apiResponse.prefixes` will return the "sub-directories" that were found:

  1. "a/"
  2. "b/"
+ * ``` + * bucket.getFiles({ + * autoPaginate: false, + * delimiter: '/' + * }, function(err, files, nextQuery, apiResponse) { + * // files = [ + * // {File} // File object for file "a" + * // ] + * + * // apiResponse.prefixes = [ + * // 'a/', + * // 'b/' + * // ] + * }); + * ``` + * + * @example + * Using prefixes, it's now possible to simulate a file system with follow-up requests. + * ``` + * bucket.getFiles({ + * autoPaginate: false, + * delimiter: '/', + * prefix: 'a/' + * }, function(err, files, nextQuery, apiResponse) { + * // No files found within "directory" a. + * // files = [] + * + * // However, a "sub-directory" was found. + * // This prefix can be used to continue traversing the "file system". + * // apiResponse.prefixes = [ + * // 'a/b/' + * // ] + * }); + * ``` + * + * @example include:samples/files.js + * region_tag:storage_list_files + * Another example: + * + * @example include:samples/files.js + * region_tag:storage_list_files_with_prefix + * Example of listing files, filtered by a prefix: + */ + getFiles(queryOrCallback, callback) { + let query = typeof queryOrCallback === 'object' ? queryOrCallback : {}; + if (!callback) { + callback = queryOrCallback; + } + query = Object.assign({}, query); + if (query.fields && + query.autoPaginate && + !query.fields.includes('nextPageToken')) { + query.fields = `${query.fields},nextPageToken`; + } + this.request({ + uri: '/o', + qs: query, + }, (err, resp) => { + if (err) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callback(err, null, null, resp); + return; + } + const itemsArray = resp.items ? resp.items : []; + const files = itemsArray.map((file) => { + const options = {}; + if (query.fields) { + const fileInstance = file; + return fileInstance; + } + if (query.versions) { + options.generation = file.generation; + } + if (file.kmsKeyName) { + options.kmsKeyName = file.kmsKeyName; + } + const fileInstance = this.file(file.name, options); + fileInstance.metadata = file; + return fileInstance; + }); + let nextQuery = null; + if (resp.nextPageToken) { + nextQuery = Object.assign({}, query, { + pageToken: resp.nextPageToken, + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callback(null, files, nextQuery, resp); + }); + } + /** + * @deprecated + * @typedef {object} GetLabelsOptions Configuration options for Bucket#getLabels(). + * @param {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @deprecated + * @typedef {array} GetLabelsResponse + * @property {object} 0 Object of labels currently set on this bucket. + */ + /** + * @deprecated + * @callback GetLabelsCallback + * @param {?Error} err Request error, if any. + * @param {object} labels Object of labels currently set on this bucket. + */ + /** + * @deprecated Use getMetadata directly. + * Get the labels currently set on this bucket. + * + * @param {object} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetLabelsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.getLabels(function(err, labels) { + * if (err) { + * // Error handling omitted. + * } + * + * // labels = { + * // label: 'labelValue', + * // ... + * // } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.getLabels().then(function(data) { + * const labels = data[0]; + * }); + * ``` + */ + getLabels(optionsOrCallback, callback) { + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else if (optionsOrCallback) { + options = optionsOrCallback; + } + this.getMetadata(options, (err, metadata) => { + if (err) { + callback(err, null); + return; + } + callback(null, (metadata === null || metadata === void 0 ? void 0 : metadata.labels) || {}); + }); + } + /** + * @typedef {object} GetNotificationsOptions Configuration options for Bucket#getNotification(). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @callback GetNotificationsCallback + * @param {?Error} err Request error, if any. + * @param {Notification[]} notifications Array of {@link Notification} + * instances. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} GetNotificationsResponse + * @property {Notification[]} 0 Array of {@link Notification} instances. + * @property {object} 1 The full API response. + */ + /** + * Retrieves a list of notification subscriptions for a given bucket. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/list| Notifications: list} + * + * @param {GetNotificationsOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetNotificationsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * bucket.getNotifications(function(err, notifications, apiResponse) { + * if (!err) { + * // notifications is an array of Notification objects. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.getNotifications().then(function(data) { + * const notifications = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/listNotifications.js + * region_tag:storage_list_bucket_notifications + * Another example: + */ + getNotifications(optionsOrCallback, callback) { + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else if (optionsOrCallback) { + options = optionsOrCallback; + } + this.request({ + uri: '/notificationConfigs', + qs: options, + }, (err, resp) => { + if (err) { + callback(err, null, resp); + return; + } + const itemsArray = resp.items ? resp.items : []; + const notifications = itemsArray.map((notification) => { + const notificationInstance = this.notification(notification.id); + notificationInstance.metadata = notification; + return notificationInstance; + }); + callback(null, notifications, resp); + }); + } + /** + * @typedef {array} GetSignedUrlResponse + * @property {object} 0 The signed URL. + */ + /** + * @callback GetSignedUrlCallback + * @param {?Error} err Request error, if any. + * @param {object} url The signed URL. + */ + /** + * @typedef {object} GetBucketSignedUrlConfig + * @property {string} action Only listing objects within a bucket (HTTP: GET) is supported for bucket-level signed URLs. + * @property {*} expires A timestamp when this link will expire. Any value + * given is passed to `new Date()`. + * Note: 'v4' supports maximum duration of 7 days (604800 seconds) from now. + * @property {string} [version='v2'] The signing version to use, either + * 'v2' or 'v4'. + * @property {boolean} [virtualHostedStyle=false] Use virtual hosted-style + * URLs ('https://mybucket.storage.googleapis.com/...') instead of path-style + * ('https://storage.googleapis.com/mybucket/...'). Virtual hosted-style URLs + * should generally be preferred instead of path-style URL. + * Currently defaults to `false` for path-style, although this may change in a + * future major-version release. + * @property {string} [cname] The cname for this bucket, i.e., + * "https://cdn.example.com". + * See [reference]{@link https://cloud.google.com/storage/docs/access-control/signed-urls#example} + * @property {object} [extensionHeaders] If these headers are used, the + * server will check to make sure that the client provides matching + * values. See {@link https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers| Canonical extension headers} + * for the requirements of this feature, most notably: + * - The header name must be prefixed with `x-goog-` + * - The header name must be all lowercase + * + * Note: Multi-valued header passed as an array in the extensionHeaders + * object is converted into a string, delimited by `,` with + * no space. Requests made using the signed URL will need to + * delimit multi-valued headers using a single `,` as well, or + * else the server will report a mismatched signature. + * @property {object} [queryParams] Additional query parameters to include + * in the signed URL. + */ + /** + * Get a signed URL to allow limited time access to a bucket. + * + * In Google Cloud Platform environments, such as Cloud Functions and App + * Engine, you usually don't provide a `keyFilename` or `credentials` during + * instantiation. In those environments, we call the + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob| signBlob API} + * to create a signed URL. That API requires either the + * `https://www.googleapis.com/auth/iam` or + * `https://www.googleapis.com/auth/cloud-platform` scope, so be sure they are + * enabled. + * + * See {@link https://cloud.google.com/storage/docs/access-control/signed-urls| Signed URLs Reference} + * + * @throws {Error} if an expiration timestamp from the past is given. + * + * @param {GetBucketSignedUrlConfig} config Configuration object. + * @param {string} config.action Currently only supports "list" (HTTP: GET). + * @param {*} config.expires A timestamp when this link will expire. Any value + * given is passed to `new Date()`. + * Note: 'v4' supports maximum duration of 7 days (604800 seconds) from now. + * @param {string} [config.version='v2'] The signing version to use, either + * 'v2' or 'v4'. + * @param {boolean} [config.virtualHostedStyle=false] Use virtual hosted-style + * URLs ('https://mybucket.storage.googleapis.com/...') instead of path-style + * ('https://storage.googleapis.com/mybucket/...'). Virtual hosted-style URLs + * should generally be preferred instead of path-style URL. + * Currently defaults to `false` for path-style, although this may change in a + * future major-version release. + * @param {string} [config.cname] The cname for this bucket, i.e., + * "https://cdn.example.com". + * See [reference]{@link https://cloud.google.com/storage/docs/access-control/signed-urls#example} + * @param {object} [config.extensionHeaders] If these headers are used, the + * server will check to make sure that the client provides matching + * values. See {@link https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers| Canonical extension headers} + * for the requirements of this feature, most notably: + * - The header name must be prefixed with `x-goog-` + * - The header name must be all lowercase + * + * Note: Multi-valued header passed as an array in the extensionHeaders + * object is converted into a string, delimited by `,` with + * no space. Requests made using the signed URL will need to + * delimit multi-valued headers using a single `,` as well, or + * else the server will report a mismatched signature. + * @property {object} [config.queryParams] Additional query parameters to include + * in the signed URL. + * @param {GetSignedUrlCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * //- + * // Generate a URL that allows temporary access to list files in a bucket. + * //- + * const request = require('request'); + * + * const config = { + * action: 'list', + * expires: '03-17-2025' + * }; + * + * bucket.getSignedUrl(config, function(err, url) { + * if (err) { + * console.error(err); + * return; + * } + * + * // The bucket is now available to be listed from this URL. + * request(url, function(err, resp) { + * // resp.statusCode = 200 + * }); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.getSignedUrl(config).then(function(data) { + * const url = data[0]; + * }); + * ``` + */ + getSignedUrl(cfg, callback) { + const method = BucketActionToHTTPMethod[cfg.action]; + const signConfig = { + method, + expires: cfg.expires, + version: cfg.version, + cname: cfg.cname, + extensionHeaders: cfg.extensionHeaders || {}, + queryParams: cfg.queryParams || {}, + host: cfg.host, + signingEndpoint: cfg.signingEndpoint, + }; + if (!this.signer) { + this.signer = new URLSigner(this.storage.authClient, this, undefined, this.storage); + } + this.signer + .getSignedUrl(signConfig) + .then(signedUrl => callback(null, signedUrl), callback); + } + /** + * @callback BucketLockCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Lock a previously-defined retention policy. This will prevent changes to + * the policy. + * + * @throws {Error} if a metageneration is not provided. + * + * @param {number|string} metageneration The bucket's metageneration. This is + * accessible from calling {@link File#getMetadata}. + * @param {BucketLockCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const bucket = storage.bucket('albums'); + * + * const metageneration = 2; + * + * bucket.lock(metageneration, function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.lock(metageneration).then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + lock(metageneration, callback) { + const metatype = typeof metageneration; + if (metatype !== 'number' && metatype !== 'string') { + throw new Error(BucketExceptionMessages.METAGENERATION_NOT_PROVIDED); + } + this.request({ + method: 'POST', + uri: '/lockRetentionPolicy', + qs: { + ifMetagenerationMatch: metageneration, + }, + }, callback); + } + /** + * @typedef {object} RestoreOptions Options for Bucket#restore(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/restore#resource| Object resource}. + * @param {number} [generation] If present, selects a specific revision of this object. + * @param {string} [projection] Specifies the set of properties to return. If used, must be 'full' or 'noAcl'. + */ + /** + * Restores a soft-deleted bucket + * @param {RestoreOptions} options Restore options. + * @returns {Promise} + */ + async restore(options) { + const [bucket] = await this.request({ + method: 'POST', + uri: '/restore', + qs: options, + }); + return bucket; + } + /** + * @typedef {array} MakeBucketPrivateResponse + * @property {File[]} 0 List of files made private. + */ + /** + * @callback MakeBucketPrivateCallback + * @param {?Error} err Request error, if any. + * @param {File[]} files List of files made private. + */ + /** + * @typedef {object} MakeBucketPrivateOptions + * @property {boolean} [includeFiles=false] Make each file in the bucket + * private. + * @property {Metadata} [metadata] Define custom metadata properties to define + * along with the operation. + * @property {boolean} [force] Queue errors occurred while making files + * private until all files have been processed. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * Make the bucket listing private. + * + * You may also choose to make the contents of the bucket private by + * specifying `includeFiles: true`. This will automatically run + * {@link File#makePrivate} for every file in the bucket. + * + * When specifying `includeFiles: true`, use `force: true` to delay execution + * of your callback until all files have been processed. By default, the + * callback is executed after the first error. Use `force` to queue such + * errors until all files have been processed, after which they will be + * returned as an array as the first argument to your callback. + * + * NOTE: This may cause the process to be long-running and use a high number + * of requests. Use with caution. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch| Buckets: patch API Documentation} + * + * @param {MakeBucketPrivateOptions} [options] Configuration options. + * @param {boolean} [options.includeFiles=false] Make each file in the bucket + * private. + * @param {Metadata} [options.metadata] Define custom metadata properties to define + * along with the operation. + * @param {boolean} [options.force] Queue errors occurred while making files + * private until all files have been processed. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {MakeBucketPrivateCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Make the bucket private. + * //- + * bucket.makePrivate(function(err) {}); + * + * //- + * // Make the bucket and its contents private. + * //- + * const opts = { + * includeFiles: true + * }; + * + * bucket.makePrivate(opts, function(err, files) { + * // `err`: + * // The first error to occur, otherwise null. + * // + * // `files`: + * // Array of files successfully made private in the bucket. + * }); + * + * //- + * // Make the bucket and its contents private, using force to suppress errors + * // until all files have been processed. + * //- + * const opts = { + * includeFiles: true, + * force: true + * }; + * + * bucket.makePrivate(opts, function(errors, files) { + * // `errors`: + * // Array of errors if any occurred, otherwise null. + * // + * // `files`: + * // Array of files successfully made private in the bucket. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.makePrivate(opts).then(function(data) { + * const files = data[0]; + * }); + * ``` + */ + makePrivate(optionsOrCallback, callback) { + var _a, _b, _c, _d; + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + options.private = true; + const query = { + predefinedAcl: 'projectPrivate', + }; + if (options.userProject) { + query.userProject = options.userProject; + } + if ((_a = options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) { + query.ifGenerationMatch = options.preconditionOpts.ifGenerationMatch; + } + if ((_b = options.preconditionOpts) === null || _b === void 0 ? void 0 : _b.ifGenerationNotMatch) { + query.ifGenerationNotMatch = + options.preconditionOpts.ifGenerationNotMatch; + } + if ((_c = options.preconditionOpts) === null || _c === void 0 ? void 0 : _c.ifMetagenerationMatch) { + query.ifMetagenerationMatch = + options.preconditionOpts.ifMetagenerationMatch; + } + if ((_d = options.preconditionOpts) === null || _d === void 0 ? void 0 : _d.ifMetagenerationNotMatch) { + query.ifMetagenerationNotMatch = + options.preconditionOpts.ifMetagenerationNotMatch; + } + // You aren't allowed to set both predefinedAcl & acl properties on a bucket + // so acl must explicitly be nullified. + const metadata = { ...options.metadata, acl: null }; + this.setMetadata(metadata, query, (err) => { + if (err) { + callback(err); + } + const internalCall = () => { + if (options.includeFiles) { + return promisify(this.makeAllFilesPublicPrivate_).call(this, options); + } + return Promise.resolve([]); + }; + internalCall() + .then(files => callback(null, files)) + .catch(callback); + }); + } + /** + * @typedef {object} MakeBucketPublicOptions + * @property {boolean} [includeFiles=false] Make each file in the bucket + * private. + * @property {boolean} [force] Queue errors occurred while making files + * private until all files have been processed. + */ + /** + * @callback MakeBucketPublicCallback + * @param {?Error} err Request error, if any. + * @param {File[]} files List of files made public. + */ + /** + * @typedef {array} MakeBucketPublicResponse + * @property {File[]} 0 List of files made public. + */ + /** + * Make the bucket publicly readable. + * + * You may also choose to make the contents of the bucket publicly readable by + * specifying `includeFiles: true`. This will automatically run + * {@link File#makePublic} for every file in the bucket. + * + * When specifying `includeFiles: true`, use `force: true` to delay execution + * of your callback until all files have been processed. By default, the + * callback is executed after the first error. Use `force` to queue such + * errors until all files have been processed, after which they will be + * returned as an array as the first argument to your callback. + * + * NOTE: This may cause the process to be long-running and use a high number + * of requests. Use with caution. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch| Buckets: patch API Documentation} + * + * @param {MakeBucketPublicOptions} [options] Configuration options. + * @param {boolean} [options.includeFiles=false] Make each file in the bucket + * private. + * @param {boolean} [options.force] Queue errors occurred while making files + * private until all files have been processed. + * @param {MakeBucketPublicCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Make the bucket publicly readable. + * //- + * bucket.makePublic(function(err) {}); + * + * //- + * // Make the bucket and its contents publicly readable. + * //- + * const opts = { + * includeFiles: true + * }; + * + * bucket.makePublic(opts, function(err, files) { + * // `err`: + * // The first error to occur, otherwise null. + * // + * // `files`: + * // Array of files successfully made public in the bucket. + * }); + * + * //- + * // Make the bucket and its contents publicly readable, using force to + * // suppress errors until all files have been processed. + * //- + * const opts = { + * includeFiles: true, + * force: true + * }; + * + * bucket.makePublic(opts, function(errors, files) { + * // `errors`: + * // Array of errors if any occurred, otherwise null. + * // + * // `files`: + * // Array of files successfully made public in the bucket. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.makePublic(opts).then(function(data) { + * const files = data[0]; + * }); + * ``` + */ + makePublic(optionsOrCallback, callback) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + const req = { public: true, ...options }; + this.acl + .add({ + entity: 'allUsers', + role: 'READER', + }) + .then(() => { + return this.acl.default.add({ + entity: 'allUsers', + role: 'READER', + }); + }) + .then(() => { + if (req.includeFiles) { + return promisify(this.makeAllFilesPublicPrivate_).call(this, req); + } + return []; + }) + .then(files => callback(null, files), callback); + } + /** + * Get a reference to a Cloud Pub/Sub Notification. + * + * @param {string} id ID of notification. + * @returns {Notification} + * @see Notification + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const notification = bucket.notification('1'); + * ``` + */ + notification(id) { + if (!id) { + throw new Error(BucketExceptionMessages.SUPPLY_NOTIFICATION_ID); + } + return new Notification(this, id); + } + /** + * Remove an already-existing retention policy from this bucket, if it is not + * locked. + * + * @param {SetBucketMetadataCallback} [callback] Callback function. + * @param {SetBucketMetadataOptions} [options] Options, including precondition options + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const bucket = storage.bucket('albums'); + * + * bucket.removeRetentionPeriod(function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.removeRetentionPeriod().then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + removeRetentionPeriod(optionsOrCallback, callback) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + this.setMetadata({ + retentionPolicy: null, + }, options, callback); + } + /** + * Makes request and applies userProject query parameter if necessary. + * + * @private + * + * @param {object} reqOpts - The request options. + * @param {function} callback - The callback function. + */ + request(reqOpts, callback) { + if (this.userProject && (!reqOpts.qs || !reqOpts.qs.userProject)) { + reqOpts.qs = { ...reqOpts.qs, userProject: this.userProject }; + } + return super.request(reqOpts, callback); + } + /** + * @deprecated + * @typedef {array} SetLabelsResponse + * @property {object} 0 The bucket metadata. + */ + /** + * @deprecated + * @callback SetLabelsCallback + * @param {?Error} err Request error, if any. + * @param {object} metadata The bucket metadata. + */ + /** + * @deprecated + * @typedef {object} SetLabelsOptions Configuration options for Bucket#setLabels(). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @deprecated Use setMetadata directly. + * Set labels on the bucket. + * + * This makes an underlying call to {@link Bucket#setMetadata}, which + * is a PATCH request. This means an individual label can be overwritten, but + * unmentioned labels will not be touched. + * + * @param {object} labels Labels to set on the bucket. + * @param {SetLabelsOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {SetLabelsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * const labels = { + * labelone: 'labelonevalue', + * labeltwo: 'labeltwovalue' + * }; + * + * bucket.setLabels(labels, function(err, metadata) { + * if (!err) { + * // Labels set successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.setLabels(labels).then(function(data) { + * const metadata = data[0]; + * }); + * ``` + */ + setLabels(labels, optionsOrCallback, callback) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + callback = callback || util.noop; + this.setMetadata({ labels }, options, callback); + } + setMetadata(metadata, optionsOrCallback, cb) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + cb = + typeof optionsOrCallback === 'function' + ? optionsOrCallback + : cb; + this.disableAutoRetryConditionallyIdempotent_(this.methods.setMetadata, AvailableServiceObjectMethods.setMetadata, options); + super + .setMetadata(metadata, options) + .then(resp => cb(null, ...resp)) + .catch(cb) + .finally(() => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + }); + } + /** + * Lock all objects contained in the bucket, based on their creation time. Any + * attempt to overwrite or delete objects younger than the retention period + * will result in a `PERMISSION_DENIED` error. + * + * An unlocked retention policy can be modified or removed from the bucket via + * {@link File#removeRetentionPeriod} and {@link File#setRetentionPeriod}. A + * locked retention policy cannot be removed or shortened in duration for the + * lifetime of the bucket. Attempting to remove or decrease period of a locked + * retention policy will result in a `PERMISSION_DENIED` error. You can still + * increase the policy. + * + * @param {*} duration In seconds, the minimum retention time for all objects + * contained in this bucket. + * @param {SetBucketMetadataCallback} [callback] Callback function. + * @param {SetBucketMetadataCallback} [options] Options, including precondition options. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const bucket = storage.bucket('albums'); + * + * const DURATION_SECONDS = 15780000; // 6 months. + * + * //- + * // Lock the objects in this bucket for 6 months. + * //- + * bucket.setRetentionPeriod(DURATION_SECONDS, function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.setRetentionPeriod(DURATION_SECONDS).then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + setRetentionPeriod(duration, optionsOrCallback, callback) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + this.setMetadata({ + retentionPolicy: { + retentionPeriod: duration.toString(), + }, + }, options, callback); + } + /** + * + * @typedef {object} Cors + * @property {number} [maxAgeSeconds] The number of seconds the browser is + * allowed to make requests before it must repeat the preflight request. + * @property {string[]} [method] HTTP method allowed for cross origin resource + * sharing with this bucket. + * @property {string[]} [origin] an origin allowed for cross origin resource + * sharing with this bucket. + * @property {string[]} [responseHeader] A header allowed for cross origin + * resource sharing with this bucket. + */ + /** + * This can be used to set the CORS configuration on the bucket. + * + * The configuration will be overwritten with the value passed into this. + * + * @param {Cors[]} corsConfiguration The new CORS configuration to set + * @param {number} [corsConfiguration.maxAgeSeconds] The number of seconds the browser is + * allowed to make requests before it must repeat the preflight request. + * @param {string[]} [corsConfiguration.method] HTTP method allowed for cross origin resource + * sharing with this bucket. + * @param {string[]} [corsConfiguration.origin] an origin allowed for cross origin resource + * sharing with this bucket. + * @param {string[]} [corsConfiguration.responseHeader] A header allowed for cross origin + * resource sharing with this bucket. + * @param {SetBucketMetadataCallback} [callback] Callback function. + * @param {SetBucketMetadataOptions} [options] Options, including precondition options. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const bucket = storage.bucket('albums'); + * + * const corsConfiguration = [{maxAgeSeconds: 3600}]; // 1 hour + * bucket.setCorsConfiguration(corsConfiguration); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.setCorsConfiguration(corsConfiguration).then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + setCorsConfiguration(corsConfiguration, optionsOrCallback, callback) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + this.setMetadata({ + cors: corsConfiguration, + }, options, callback); + } + /** + * @typedef {object} SetBucketStorageClassOptions + * @property {string} [userProject] - The ID of the project which will be + * billed for the request. + */ + /** + * @callback SetBucketStorageClassCallback + * @param {?Error} err Request error, if any. + */ + /** + * Set the default storage class for new files in this bucket. + * + * See {@link https://cloud.google.com/storage/docs/storage-classes| Storage Classes} + * + * @param {string} storageClass The new storage class. (`standard`, + * `nearline`, `coldline`, or `archive`). + * **Note:** The storage classes `multi_regional`, `regional`, and + * `durable_reduced_availability` are now legacy and will be deprecated in + * the future. + * @param {object} [options] Configuration options. + * @param {string} [options.userProject] - The ID of the project which will be + * billed for the request. + * @param {SetStorageClassCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.setStorageClass('nearline', function(err, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * // The storage class was updated successfully. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.setStorageClass('nearline').then(function() {}); + * ``` + */ + setStorageClass(storageClass, optionsOrCallback, callback) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + // In case we get input like `storageClass`, convert to `storage_class`. + storageClass = storageClass + .replace(/-/g, '_') + .replace(/([a-z])([A-Z])/g, (_, low, up) => { + return low + '_' + up; + }) + .toUpperCase(); + this.setMetadata({ storageClass }, options, callback); + } + /** + * Set a user project to be billed for all requests made from this Bucket + * object and any files referenced from this Bucket object. + * + * @param {string} userProject The user project. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.setUserProject('grape-spaceship-123'); + * ``` + */ + setUserProject(userProject) { + this.userProject = userProject; + const methods = [ + 'create', + 'delete', + 'exists', + 'get', + 'getMetadata', + 'setMetadata', + ]; + methods.forEach(method => { + const methodConfig = this.methods[method]; + if (typeof methodConfig === 'object') { + if (typeof methodConfig.reqOpts === 'object') { + Object.assign(methodConfig.reqOpts.qs, { userProject }); + } + else { + methodConfig.reqOpts = { + qs: { userProject }, + }; + } + } + }); + } + /** + * @typedef {object} UploadOptions Configuration options for Bucket#upload(). + * @property {string|File} [destination] The place to save + * your file. If given a string, the file will be uploaded to the bucket + * using the string as a filename. When given a File object, your local + * file will be uploaded to the File object's bucket and under the File + * object's name. Lastly, when this argument is omitted, the file is uploaded + * to your bucket using the name of the local file. + * @property {string} [encryptionKey] A custom encryption key. See + * {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}. + * @property {boolean} [gzip] Automatically gzip the file. This will set + * `options.metadata.contentEncoding` to `gzip`. + * @property {string} [kmsKeyName] The name of the Cloud KMS key that will + * be used to encrypt the object. Must be in the format: + * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`. + * @property {object} [metadata] See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON| Objects: insert request body}. + * @property {string} [offset] The starting byte of the upload stream, for + * resuming an interrupted upload. Defaults to 0. + * @property {string} [predefinedAcl] Apply a predefined set of access + * controls to this object. + * + * Acceptable values are: + * - **`authenticatedRead`** - Object owner gets `OWNER` access, and + * `allAuthenticatedUsers` get `READER` access. + * + * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and + * project team owners get `OWNER` access. + * + * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project + * team owners get `READER` access. + * + * - **`private`** - Object owner gets `OWNER` access. + * + * - **`projectPrivate`** - Object owner gets `OWNER` access, and project + * team members get access according to their roles. + * + * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers` + * get `READER` access. + * @property {boolean} [private] Make the uploaded file private. (Alias for + * `options.predefinedAcl = 'private'`) + * @property {boolean} [public] Make the uploaded file public. (Alias for + * `options.predefinedAcl = 'publicRead'`) + * @property {boolean} [resumable=true] Resumable uploads are automatically + * enabled and must be shut off explicitly by setting to false. + * @property {number} [timeout=60000] Set the HTTP request timeout in + * milliseconds. This option is not available for resumable uploads. + * Default: `60000` + * @property {string} [uri] The URI for an already-created resumable + * upload. See {@link File#createResumableUpload}. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {string|boolean} [validation] Possible values: `"md5"`, + * `"crc32c"`, or `false`. By default, data integrity is validated with an + * MD5 checksum for maximum reliability. CRC32c will provide better + * performance with less reliability. You may also choose to skip + * validation completely, however this is **not recommended**. + */ + /** + * @typedef {array} UploadResponse + * @property {object} 0 The uploaded {@link File}. + * @property {object} 1 The full API response. + */ + /** + * @callback UploadCallback + * @param {?Error} err Request error, if any. + * @param {object} file The uploaded {@link File}. + * @param {object} apiResponse The full API response. + */ + /** + * Upload a file to the bucket. This is a convenience method that wraps + * {@link File#createWriteStream}. + * + * Resumable uploads are enabled by default + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload#uploads| Upload Options (Simple or Resumable)} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert| Objects: insert API Documentation} + * + * @param {string} pathString The fully qualified path to the file you + * wish to upload to your bucket. + * @param {UploadOptions} [options] Configuration options. + * @param {string|File} [options.destination] The place to save + * your file. If given a string, the file will be uploaded to the bucket + * using the string as a filename. When given a File object, your local + * file will be uploaded to the File object's bucket and under the File + * object's name. Lastly, when this argument is omitted, the file is uploaded + * to your bucket using the name of the local file. + * @param {string} [options.encryptionKey] A custom encryption key. See + * {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}. + * @param {boolean} [options.gzip] Automatically gzip the file. This will set + * `options.metadata.contentEncoding` to `gzip`. + * @param {string} [options.kmsKeyName] The name of the Cloud KMS key that will + * be used to encrypt the object. Must be in the format: + * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`. + * @param {object} [options.metadata] See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON| Objects: insert request body}. + * @param {string} [options.offset] The starting byte of the upload stream, for + * resuming an interrupted upload. Defaults to 0. + * @param {string} [options.predefinedAcl] Apply a predefined set of access + * controls to this object. + * Acceptable values are: + * - **`authenticatedRead`** - Object owner gets `OWNER` access, and + * `allAuthenticatedUsers` get `READER` access. + * + * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and + * project team owners get `OWNER` access. + * + * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project + * team owners get `READER` access. + * + * - **`private`** - Object owner gets `OWNER` access. + * + * - **`projectPrivate`** - Object owner gets `OWNER` access, and project + * team members get access according to their roles. + * + * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers` + * get `READER` access. + * @param {boolean} [options.private] Make the uploaded file private. (Alias for + * `options.predefinedAcl = 'private'`) + * @param {boolean} [options.public] Make the uploaded file public. (Alias for + * `options.predefinedAcl = 'publicRead'`) + * @param {boolean} [options.resumable=true] Resumable uploads are automatically + * enabled and must be shut off explicitly by setting to false. + * @param {number} [options.timeout=60000] Set the HTTP request timeout in + * milliseconds. This option is not available for resumable uploads. + * Default: `60000` + * @param {string} [options.uri] The URI for an already-created resumable + * upload. See {@link File#createResumableUpload}. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {string|boolean} [options.validation] Possible values: `"md5"`, + * `"crc32c"`, or `false`. By default, data integrity is validated with an + * MD5 checksum for maximum reliability. CRC32c will provide better + * performance with less reliability. You may also choose to skip + * validation completely, however this is **not recommended**. + * @param {UploadCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Upload a file from a local path. + * //- + * bucket.upload('/local/path/image.png', function(err, file, apiResponse) { + * // Your bucket now contains: + * // - "image.png" (with the contents of `/local/path/image.png') + * + * // `file` is an instance of a File object that refers to your new file. + * }); + * + * + * //- + * // It's not always that easy. You will likely want to specify the filename + * // used when your new file lands in your bucket. + * // + * // You may also want to set metadata or customize other options. + * //- + * const options = { + * destination: 'new-image.png', + * validation: 'crc32c', + * metadata: { + * metadata: { + * event: 'Fall trip to the zoo' + * } + * } + * }; + * + * bucket.upload('local-image.png', options, function(err, file) { + * // Your bucket now contains: + * // - "new-image.png" (with the contents of `local-image.png') + * + * // `file` is an instance of a File object that refers to your new file. + * }); + * + * //- + * // You can also have a file gzip'd on the fly. + * //- + * bucket.upload('index.html', { gzip: true }, function(err, file) { + * // Your bucket now contains: + * // - "index.html" (automatically compressed with gzip) + * + * // Downloading the file with `file.download` will automatically decode + * the + * // file. + * }); + * + * //- + * // You may also re-use a File object, {File}, that references + * // the file you wish to create or overwrite. + * //- + * const options = { + * destination: bucket.file('existing-file.png'), + * resumable: false + * }; + * + * bucket.upload('local-img.png', options, function(err, newFile) { + * // Your bucket now contains: + * // - "existing-file.png" (with the contents of `local-img.png') + * + * // Note: + * // The `newFile` parameter is equal to `file`. + * }); + * + * //- + * // To use + * // + * // Customer-supplied Encryption Keys, provide the `encryptionKey` + * option. + * //- + * const crypto = require('crypto'); + * const encryptionKey = crypto.randomBytes(32); + * + * bucket.upload('img.png', { + * encryptionKey: encryptionKey + * }, function(err, newFile) { + * // `img.png` was uploaded with your custom encryption key. + * + * // `newFile` is already configured to use the encryption key when making + * // operations on the remote object. + * + * // However, to use your encryption key later, you must create a `File` + * // instance with the `key` supplied: + * const file = bucket.file('img.png', { + * encryptionKey: encryptionKey + * }); + * + * // Or with `file#setEncryptionKey`: + * const file = bucket.file('img.png'); + * file.setEncryptionKey(encryptionKey); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.upload('local-image.png').then(function(data) { + * const file = data[0]; + * }); + * + * To upload a file from a URL, use {@link File#createWriteStream}. + * + * ``` + * @example include:samples/files.js + * region_tag:storage_upload_file + * Another example: + * + * @example include:samples/encryption.js + * region_tag:storage_upload_encrypted_file + * Example of uploading an encrypted file: + */ + upload(pathString, optionsOrCallback, callback) { + var _a, _b; + const upload = (numberOfRetries) => { + const returnValue = AsyncRetry(async (bail) => { + await new Promise((resolve, reject) => { + var _a, _b; + if (numberOfRetries === 0 && + ((_b = (_a = newFile === null || newFile === void 0 ? void 0 : newFile.storage) === null || _a === void 0 ? void 0 : _a.retryOptions) === null || _b === void 0 ? void 0 : _b.autoRetry)) { + newFile.storage.retryOptions.autoRetry = false; + } + const writable = newFile.createWriteStream(options); + if (options.onUploadProgress) { + writable.on('progress', options.onUploadProgress); + } + fs.createReadStream(pathString) + .on('error', bail) + .pipe(writable) + .on('error', err => { + if (this.storage.retryOptions.autoRetry && + this.storage.retryOptions.retryableErrorFn(err)) { + return reject(err); + } + else { + return bail(err); + } + }) + .on('finish', () => { + return resolve(); + }); + }); + }, { + retries: numberOfRetries, + factor: this.storage.retryOptions.retryDelayMultiplier, + maxTimeout: this.storage.retryOptions.maxRetryDelay * 1000, //convert to milliseconds + maxRetryTime: this.storage.retryOptions.totalTimeout * 1000, //convert to milliseconds + }); + if (!callback) { + return returnValue; + } + else { + return returnValue + .then(() => { + if (callback) { + return callback(null, newFile, newFile.metadata); + } + }) + .catch(callback); + } + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (global['GCLOUD_SANDBOX_ENV']) { + return; + } + let options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + options = Object.assign({ + metadata: {}, + }, options); + // Do not retry if precondition option ifGenerationMatch is not set + // because this is a file operation + let maxRetries = this.storage.retryOptions.maxRetries; + if ((((_a = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) === undefined && + ((_b = this.instancePreconditionOpts) === null || _b === void 0 ? void 0 : _b.ifGenerationMatch) === undefined && + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryConditional) || + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryNever) { + maxRetries = 0; + } + let newFile; + if (options.destination instanceof File) { + newFile = options.destination; + } + else if (options.destination !== null && + typeof options.destination === 'string') { + // Use the string as the name of the file. + newFile = this.file(options.destination, { + encryptionKey: options.encryptionKey, + kmsKeyName: options.kmsKeyName, + preconditionOpts: this.instancePreconditionOpts, + }); + } + else { + // Resort to using the name of the incoming file. + const destination = path.basename(pathString); + newFile = this.file(destination, { + encryptionKey: options.encryptionKey, + kmsKeyName: options.kmsKeyName, + preconditionOpts: this.instancePreconditionOpts, + }); + } + upload(maxRetries); + } + /** + * @private + * + * @typedef {object} MakeAllFilesPublicPrivateOptions + * @property {boolean} [force] Suppress errors until all files have been + * processed. + * @property {boolean} [private] Make files private. + * @property {boolean} [public] Make files public. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @private + * + * @callback SetBucketMetadataCallback + * @param {?Error} err Request error, if any. + * @param {File[]} files Files that were updated. + */ + /** + * @typedef {array} MakeAllFilesPublicPrivateResponse + * @property {File[]} 0 List of files affected. + */ + /** + * Iterate over all of a bucket's files, calling `file.makePublic()` (public) + * or `file.makePrivate()` (private) on each. + * + * Operations are performed in parallel, up to 10 at once. The first error + * breaks the loop, and will execute the provided callback with it. Specify + * `{ force: true }` to suppress the errors. + * + * @private + * + * @param {MakeAllFilesPublicPrivateOptions} [options] Configuration options. + * @param {boolean} [options.force] Suppress errors until all files have been + * processed. + * @param {boolean} [options.private] Make files private. + * @param {boolean} [options.public] Make files public. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + + * @param {MakeAllFilesPublicPrivateCallback} callback Callback function. + * + * @return {Promise} + */ + makeAllFilesPublicPrivate_(optionsOrCallback, callback) { + const MAX_PARALLEL_LIMIT = 10; + const errors = []; + const updatedFiles = []; + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + const processFile = async (file) => { + try { + await (options.public ? file.makePublic() : file.makePrivate(options)); + updatedFiles.push(file); + } + catch (e) { + if (!options.force) { + throw e; + } + errors.push(e); + } + }; + this.getFiles(options) + .then(([files]) => { + const limit = pLimit(MAX_PARALLEL_LIMIT); + const promises = files.map(file => { + return limit(() => processFile(file)); + }); + return Promise.all(promises); + }) + .then(() => callback(errors.length > 0 ? errors : null, updatedFiles), err => callback(err, updatedFiles)); + } + getId() { + return this.id; + } + disableAutoRetryConditionallyIdempotent_( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + coreOpts, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + methodType, localPreconditionOptions) { + var _a, _b; + if (typeof coreOpts === 'object' && + ((_b = (_a = coreOpts === null || coreOpts === void 0 ? void 0 : coreOpts.reqOpts) === null || _a === void 0 ? void 0 : _a.qs) === null || _b === void 0 ? void 0 : _b.ifMetagenerationMatch) === undefined && + (localPreconditionOptions === null || localPreconditionOptions === void 0 ? void 0 : localPreconditionOptions.ifMetagenerationMatch) === undefined && + (methodType === AvailableServiceObjectMethods.setMetadata || + methodType === AvailableServiceObjectMethods.delete) && + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryConditional) { + this.storage.retryOptions.autoRetry = false; + } + else if (this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryNever) { + this.storage.retryOptions.autoRetry = false; + } + } +} +/*! Developer Documentation + * + * These methods can be auto-paginated. + */ +paginator.extend(Bucket, 'getFiles'); +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Bucket, { + exclude: ['cloudStorageURI', 'request', 'file', 'notification', 'restore'], +}); +/** + * Reference to the {@link Bucket} class. + * @name module:@google-cloud/storage.Bucket + * @see Bucket + */ +export { Bucket }; diff --git a/node_modules/@google-cloud/storage/build/esm/src/channel.d.ts b/node_modules/@google-cloud/storage/build/esm/src/channel.d.ts new file mode 100644 index 0000000..6bb52b9 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/channel.d.ts @@ -0,0 +1,33 @@ +import { BaseMetadata, ServiceObject } from './nodejs-common/index.js'; +import { Storage } from './storage.js'; +export interface StopCallback { + (err: Error | null, apiResponse?: unknown): void; +} +/** + * Create a channel object to interact with a Cloud Storage channel. + * + * See {@link https://cloud.google.com/storage/docs/object-change-notification| Object Change Notification} + * + * @class + * + * @param {string} id The ID of the channel. + * @param {string} resourceId The resource ID of the channel. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const channel = storage.channel('id', 'resource-id'); + * ``` + */ +declare class Channel extends ServiceObject { + constructor(storage: Storage, id: string, resourceId: string); + stop(): Promise; + stop(callback: StopCallback): void; +} +/** + * Reference to the {@link Channel} class. + * @name module:@google-cloud/storage.Channel + * @see Channel + */ +export { Channel }; diff --git a/node_modules/@google-cloud/storage/build/esm/src/channel.js b/node_modules/@google-cloud/storage/build/esm/src/channel.js new file mode 100644 index 0000000..f6328cf --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/channel.js @@ -0,0 +1,106 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +import { ServiceObject, util } from './nodejs-common/index.js'; +import { promisifyAll } from '@google-cloud/promisify'; +/** + * Create a channel object to interact with a Cloud Storage channel. + * + * See {@link https://cloud.google.com/storage/docs/object-change-notification| Object Change Notification} + * + * @class + * + * @param {string} id The ID of the channel. + * @param {string} resourceId The resource ID of the channel. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const channel = storage.channel('id', 'resource-id'); + * ``` + */ +class Channel extends ServiceObject { + constructor(storage, id, resourceId) { + const config = { + parent: storage, + baseUrl: '/channels', + // An ID shouldn't be included in the API requests. + // RE: + // https://github.com/GoogleCloudPlatform/google-cloud-node/issues/1145 + id: '', + methods: { + // Only need `request`. + }, + }; + super(config); + this.metadata.id = id; + this.metadata.resourceId = resourceId; + } + /** + * @typedef {array} StopResponse + * @property {object} 0 The full API response. + */ + /** + * @callback StopCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Stop this channel. + * + * @param {StopCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const channel = storage.channel('id', 'resource-id'); + * channel.stop(function(err, apiResponse) { + * if (!err) { + * // Channel stopped successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * channel.stop().then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + stop(callback) { + callback = callback || util.noop; + this.request({ + method: 'POST', + uri: '/stop', + json: this.metadata, + }, (err, apiResponse) => { + callback(err, apiResponse); + }); + } +} +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Channel); +/** + * Reference to the {@link Channel} class. + * @name module:@google-cloud/storage.Channel + * @see Channel + */ +export { Channel }; diff --git a/node_modules/@google-cloud/storage/build/esm/src/crc32c.d.ts b/node_modules/@google-cloud/storage/build/esm/src/crc32c.d.ts new file mode 100644 index 0000000..8b5a701 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/crc32c.d.ts @@ -0,0 +1,143 @@ +import { PathLike } from 'fs'; +/** + * Ported from {@link https://github.com/google/crc32c/blob/21fc8ef30415a635e7351ffa0e5d5367943d4a94/src/crc32c_portable.cc#L16-L59 github.com/google/crc32c} + */ +declare const CRC32C_EXTENSIONS: readonly [0, 4067132163, 3778769143, 324072436, 3348797215, 904991772, 648144872, 3570033899, 2329499855, 2024987596, 1809983544, 2575936315, 1296289744, 3207089363, 2893594407, 1578318884, 274646895, 3795141740, 4049975192, 51262619, 3619967088, 632279923, 922689671, 3298075524, 2592579488, 1760304291, 2075979607, 2312596564, 1562183871, 2943781820, 3156637768, 1313733451, 549293790, 3537243613, 3246849577, 871202090, 3878099393, 357341890, 102525238, 4101499445, 2858735121, 1477399826, 1264559846, 3107202533, 1845379342, 2677391885, 2361733625, 2125378298, 820201905, 3263744690, 3520608582, 598981189, 4151959214, 85089709, 373468761, 3827903834, 3124367742, 1213305469, 1526817161, 2842354314, 2107672161, 2412447074, 2627466902, 1861252501, 1098587580, 3004210879, 2688576843, 1378610760, 2262928035, 1955203488, 1742404180, 2511436119, 3416409459, 969524848, 714683780, 3639785095, 205050476, 4266873199, 3976438427, 526918040, 1361435347, 2739821008, 2954799652, 1114974503, 2529119692, 1691668175, 2005155131, 2247081528, 3690758684, 697762079, 986182379, 3366744552, 476452099, 3993867776, 4250756596, 255256311, 1640403810, 2477592673, 2164122517, 1922457750, 2791048317, 1412925310, 1197962378, 3037525897, 3944729517, 427051182, 170179418, 4165941337, 746937522, 3740196785, 3451792453, 1070968646, 1905808397, 2213795598, 2426610938, 1657317369, 3053634322, 1147748369, 1463399397, 2773627110, 4215344322, 153784257, 444234805, 3893493558, 1021025245, 3467647198, 3722505002, 797665321, 2197175160, 1889384571, 1674398607, 2443626636, 1164749927, 3070701412, 2757221520, 1446797203, 137323447, 4198817972, 3910406976, 461344835, 3484808360, 1037989803, 781091935, 3705997148, 2460548119, 1623424788, 1939049696, 2180517859, 1429367560, 2807687179, 3020495871, 1180866812, 410100952, 3927582683, 4182430767, 186734380, 3756733383, 763408580, 1053836080, 3434856499, 2722870694, 1344288421, 1131464017, 2971354706, 1708204729, 2545590714, 2229949006, 1988219213, 680717673, 3673779818, 3383336350, 1002577565, 4010310262, 493091189, 238226049, 4233660802, 2987750089, 1082061258, 1395524158, 2705686845, 1972364758, 2279892693, 2494862625, 1725896226, 952904198, 3399985413, 3656866545, 731699698, 4283874585, 222117402, 510512622, 3959836397, 3280807620, 837199303, 582374963, 3504198960, 68661723, 4135334616, 3844915500, 390545967, 1230274059, 3141532936, 2825850620, 1510247935, 2395924756, 2091215383, 1878366691, 2644384480, 3553878443, 565732008, 854102364, 3229815391, 340358836, 3861050807, 4117890627, 119113024, 1493875044, 2875275879, 3090270611, 1247431312, 2660249211, 1828433272, 2141937292, 2378227087, 3811616794, 291187481, 34330861, 4032846830, 615137029, 3603020806, 3314634738, 939183345, 1776939221, 2609017814, 2295496738, 2058945313, 2926798794, 1545135305, 1330124605, 3173225534, 4084100981, 17165430, 307568514, 3762199681, 888469610, 3332340585, 3587147933, 665062302, 2042050490, 2346497209, 2559330125, 1793573966, 3190661285, 1279665062, 1595330642, 2910671697]; +declare const CRC32C_EXTENSION_TABLE: Int32Array; +/** An interface for CRC32C hashing and validation */ +interface CRC32CValidator { + /** + * A method returning the CRC32C as a base64-encoded string. + * + * @example + * Hashing the string 'data' should return 'rth90Q==' + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.toString(); // 'rth90Q==' + * ``` + **/ + toString: () => string; + /** + * A method validating a base64-encoded CRC32C string. + * + * @example + * Should return `true` if the value matches, `false` otherwise + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.validate('DkjKuA=='); // false + * crc32c.validate('rth90Q=='); // true + * ``` + */ + validate: (value: string) => boolean; + /** + * A method for passing `Buffer`s for CRC32C generation. + * + * @example + * Hashing buffers from 'some ' and 'text\n' + * + * ```js + * const buffer1 = Buffer.from('some '); + * crc32c.update(buffer1); + * + * const buffer2 = Buffer.from('text\n'); + * crc32c.update(buffer2); + * + * crc32c.toString(); // 'DkjKuA==' + * ``` + */ + update: (data: Buffer) => void; +} +/** A function that generates a CRC32C Validator */ +interface CRC32CValidatorGenerator { + /** Should return a new, ready-to-use `CRC32CValidator` */ + (): CRC32CValidator; +} +declare const CRC32C_DEFAULT_VALIDATOR_GENERATOR: CRC32CValidatorGenerator; +declare const CRC32C_EXCEPTION_MESSAGES: { + readonly INVALID_INIT_BASE64_RANGE: (l: number) => string; + readonly INVALID_INIT_BUFFER_LENGTH: (l: number) => string; + readonly INVALID_INIT_INTEGER: (l: number) => string; +}; +declare class CRC32C implements CRC32CValidator { + #private; + /** + * Constructs a new `CRC32C` object. + * + * Reconstruction is recommended via the `CRC32C.from` static method. + * + * @param initialValue An initial CRC32C value - a signed 32-bit integer. + */ + constructor(initialValue?: number); + /** + * Calculates a CRC32C from a provided buffer. + * + * Implementation inspired from: + * - {@link https://github.com/google/crc32c/blob/21fc8ef30415a635e7351ffa0e5d5367943d4a94/src/crc32c_portable.cc github.com/google/crc32c} + * - {@link https://github.com/googleapis/python-crc32c/blob/a595e758c08df445a99c3bf132ee8e80a3ec4308/src/google_crc32c/python.py github.com/googleapis/python-crc32c} + * - {@link https://github.com/googleapis/java-storage/pull/1376/files github.com/googleapis/java-storage} + * + * @param data The `Buffer` to generate the CRC32C from + */ + update(data: Buffer): void; + /** + * Validates a provided input to the current CRC32C value. + * + * @param input A Buffer, `CRC32C`-compatible object, base64-encoded data (string), or signed 32-bit integer + */ + validate(input: Buffer | CRC32CValidator | string | number): boolean; + /** + * Returns a `Buffer` representation of the CRC32C value + */ + toBuffer(): Buffer; + /** + * Returns a JSON-compatible, base64-encoded representation of the CRC32C value. + * + * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify `JSON#stringify`} + */ + toJSON(): string; + /** + * Returns a base64-encoded representation of the CRC32C value. + * + * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString `Object#toString`} + */ + toString(): string; + /** + * Returns the `number` representation of the CRC32C value as a signed 32-bit integer + * + * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf `Object#valueOf`} + */ + valueOf(): number; + static readonly CRC32C_EXTENSIONS: readonly [0, 4067132163, 3778769143, 324072436, 3348797215, 904991772, 648144872, 3570033899, 2329499855, 2024987596, 1809983544, 2575936315, 1296289744, 3207089363, 2893594407, 1578318884, 274646895, 3795141740, 4049975192, 51262619, 3619967088, 632279923, 922689671, 3298075524, 2592579488, 1760304291, 2075979607, 2312596564, 1562183871, 2943781820, 3156637768, 1313733451, 549293790, 3537243613, 3246849577, 871202090, 3878099393, 357341890, 102525238, 4101499445, 2858735121, 1477399826, 1264559846, 3107202533, 1845379342, 2677391885, 2361733625, 2125378298, 820201905, 3263744690, 3520608582, 598981189, 4151959214, 85089709, 373468761, 3827903834, 3124367742, 1213305469, 1526817161, 2842354314, 2107672161, 2412447074, 2627466902, 1861252501, 1098587580, 3004210879, 2688576843, 1378610760, 2262928035, 1955203488, 1742404180, 2511436119, 3416409459, 969524848, 714683780, 3639785095, 205050476, 4266873199, 3976438427, 526918040, 1361435347, 2739821008, 2954799652, 1114974503, 2529119692, 1691668175, 2005155131, 2247081528, 3690758684, 697762079, 986182379, 3366744552, 476452099, 3993867776, 4250756596, 255256311, 1640403810, 2477592673, 2164122517, 1922457750, 2791048317, 1412925310, 1197962378, 3037525897, 3944729517, 427051182, 170179418, 4165941337, 746937522, 3740196785, 3451792453, 1070968646, 1905808397, 2213795598, 2426610938, 1657317369, 3053634322, 1147748369, 1463399397, 2773627110, 4215344322, 153784257, 444234805, 3893493558, 1021025245, 3467647198, 3722505002, 797665321, 2197175160, 1889384571, 1674398607, 2443626636, 1164749927, 3070701412, 2757221520, 1446797203, 137323447, 4198817972, 3910406976, 461344835, 3484808360, 1037989803, 781091935, 3705997148, 2460548119, 1623424788, 1939049696, 2180517859, 1429367560, 2807687179, 3020495871, 1180866812, 410100952, 3927582683, 4182430767, 186734380, 3756733383, 763408580, 1053836080, 3434856499, 2722870694, 1344288421, 1131464017, 2971354706, 1708204729, 2545590714, 2229949006, 1988219213, 680717673, 3673779818, 3383336350, 1002577565, 4010310262, 493091189, 238226049, 4233660802, 2987750089, 1082061258, 1395524158, 2705686845, 1972364758, 2279892693, 2494862625, 1725896226, 952904198, 3399985413, 3656866545, 731699698, 4283874585, 222117402, 510512622, 3959836397, 3280807620, 837199303, 582374963, 3504198960, 68661723, 4135334616, 3844915500, 390545967, 1230274059, 3141532936, 2825850620, 1510247935, 2395924756, 2091215383, 1878366691, 2644384480, 3553878443, 565732008, 854102364, 3229815391, 340358836, 3861050807, 4117890627, 119113024, 1493875044, 2875275879, 3090270611, 1247431312, 2660249211, 1828433272, 2141937292, 2378227087, 3811616794, 291187481, 34330861, 4032846830, 615137029, 3603020806, 3314634738, 939183345, 1776939221, 2609017814, 2295496738, 2058945313, 2926798794, 1545135305, 1330124605, 3173225534, 4084100981, 17165430, 307568514, 3762199681, 888469610, 3332340585, 3587147933, 665062302, 2042050490, 2346497209, 2559330125, 1793573966, 3190661285, 1279665062, 1595330642, 2910671697]; + static readonly CRC32C_EXTENSION_TABLE: Int32Array; + /** + * Generates a `CRC32C` from a compatible buffer format. + * + * @param value 4-byte `ArrayBufferView`/`Buffer`/`TypedArray` + */ + private static fromBuffer; + static fromFile(file: PathLike): Promise; + /** + * Generates a `CRC32C` from 4-byte base64-encoded data (string). + * + * @param value 4-byte base64-encoded data (string) + */ + private static fromString; + /** + * Generates a `CRC32C` from a safe, unsigned 32-bit integer. + * + * @param value an unsigned 32-bit integer + */ + private static fromNumber; + /** + * Generates a `CRC32C` from a variety of compatable types. + * Note: strings are treated as input, not as file paths to read from. + * + * @param value A number, 4-byte `ArrayBufferView`/`Buffer`/`TypedArray`, or 4-byte base64-encoded data (string) + */ + static from(value: ArrayBuffer | ArrayBufferView | CRC32CValidator | string | number): CRC32C; +} +export { CRC32C, CRC32C_DEFAULT_VALIDATOR_GENERATOR, CRC32C_EXCEPTION_MESSAGES, CRC32C_EXTENSIONS, CRC32C_EXTENSION_TABLE, CRC32CValidator, CRC32CValidatorGenerator, }; diff --git a/node_modules/@google-cloud/storage/build/esm/src/crc32c.js b/node_modules/@google-cloud/storage/build/esm/src/crc32c.js new file mode 100644 index 0000000..8efd20f --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/crc32c.js @@ -0,0 +1,254 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _CRC32C_crc32c; +import { createReadStream } from 'fs'; +/** + * Ported from {@link https://github.com/google/crc32c/blob/21fc8ef30415a635e7351ffa0e5d5367943d4a94/src/crc32c_portable.cc#L16-L59 github.com/google/crc32c} + */ +const CRC32C_EXTENSIONS = [ + 0x00000000, 0xf26b8303, 0xe13b70f7, 0x1350f3f4, 0xc79a971f, 0x35f1141c, + 0x26a1e7e8, 0xd4ca64eb, 0x8ad958cf, 0x78b2dbcc, 0x6be22838, 0x9989ab3b, + 0x4d43cfd0, 0xbf284cd3, 0xac78bf27, 0x5e133c24, 0x105ec76f, 0xe235446c, + 0xf165b798, 0x030e349b, 0xd7c45070, 0x25afd373, 0x36ff2087, 0xc494a384, + 0x9a879fa0, 0x68ec1ca3, 0x7bbcef57, 0x89d76c54, 0x5d1d08bf, 0xaf768bbc, + 0xbc267848, 0x4e4dfb4b, 0x20bd8ede, 0xd2d60ddd, 0xc186fe29, 0x33ed7d2a, + 0xe72719c1, 0x154c9ac2, 0x061c6936, 0xf477ea35, 0xaa64d611, 0x580f5512, + 0x4b5fa6e6, 0xb93425e5, 0x6dfe410e, 0x9f95c20d, 0x8cc531f9, 0x7eaeb2fa, + 0x30e349b1, 0xc288cab2, 0xd1d83946, 0x23b3ba45, 0xf779deae, 0x05125dad, + 0x1642ae59, 0xe4292d5a, 0xba3a117e, 0x4851927d, 0x5b016189, 0xa96ae28a, + 0x7da08661, 0x8fcb0562, 0x9c9bf696, 0x6ef07595, 0x417b1dbc, 0xb3109ebf, + 0xa0406d4b, 0x522bee48, 0x86e18aa3, 0x748a09a0, 0x67dafa54, 0x95b17957, + 0xcba24573, 0x39c9c670, 0x2a993584, 0xd8f2b687, 0x0c38d26c, 0xfe53516f, + 0xed03a29b, 0x1f682198, 0x5125dad3, 0xa34e59d0, 0xb01eaa24, 0x42752927, + 0x96bf4dcc, 0x64d4cecf, 0x77843d3b, 0x85efbe38, 0xdbfc821c, 0x2997011f, + 0x3ac7f2eb, 0xc8ac71e8, 0x1c661503, 0xee0d9600, 0xfd5d65f4, 0x0f36e6f7, + 0x61c69362, 0x93ad1061, 0x80fde395, 0x72966096, 0xa65c047d, 0x5437877e, + 0x4767748a, 0xb50cf789, 0xeb1fcbad, 0x197448ae, 0x0a24bb5a, 0xf84f3859, + 0x2c855cb2, 0xdeeedfb1, 0xcdbe2c45, 0x3fd5af46, 0x7198540d, 0x83f3d70e, + 0x90a324fa, 0x62c8a7f9, 0xb602c312, 0x44694011, 0x5739b3e5, 0xa55230e6, + 0xfb410cc2, 0x092a8fc1, 0x1a7a7c35, 0xe811ff36, 0x3cdb9bdd, 0xceb018de, + 0xdde0eb2a, 0x2f8b6829, 0x82f63b78, 0x709db87b, 0x63cd4b8f, 0x91a6c88c, + 0x456cac67, 0xb7072f64, 0xa457dc90, 0x563c5f93, 0x082f63b7, 0xfa44e0b4, + 0xe9141340, 0x1b7f9043, 0xcfb5f4a8, 0x3dde77ab, 0x2e8e845f, 0xdce5075c, + 0x92a8fc17, 0x60c37f14, 0x73938ce0, 0x81f80fe3, 0x55326b08, 0xa759e80b, + 0xb4091bff, 0x466298fc, 0x1871a4d8, 0xea1a27db, 0xf94ad42f, 0x0b21572c, + 0xdfeb33c7, 0x2d80b0c4, 0x3ed04330, 0xccbbc033, 0xa24bb5a6, 0x502036a5, + 0x4370c551, 0xb11b4652, 0x65d122b9, 0x97baa1ba, 0x84ea524e, 0x7681d14d, + 0x2892ed69, 0xdaf96e6a, 0xc9a99d9e, 0x3bc21e9d, 0xef087a76, 0x1d63f975, + 0x0e330a81, 0xfc588982, 0xb21572c9, 0x407ef1ca, 0x532e023e, 0xa145813d, + 0x758fe5d6, 0x87e466d5, 0x94b49521, 0x66df1622, 0x38cc2a06, 0xcaa7a905, + 0xd9f75af1, 0x2b9cd9f2, 0xff56bd19, 0x0d3d3e1a, 0x1e6dcdee, 0xec064eed, + 0xc38d26c4, 0x31e6a5c7, 0x22b65633, 0xd0ddd530, 0x0417b1db, 0xf67c32d8, + 0xe52cc12c, 0x1747422f, 0x49547e0b, 0xbb3ffd08, 0xa86f0efc, 0x5a048dff, + 0x8ecee914, 0x7ca56a17, 0x6ff599e3, 0x9d9e1ae0, 0xd3d3e1ab, 0x21b862a8, + 0x32e8915c, 0xc083125f, 0x144976b4, 0xe622f5b7, 0xf5720643, 0x07198540, + 0x590ab964, 0xab613a67, 0xb831c993, 0x4a5a4a90, 0x9e902e7b, 0x6cfbad78, + 0x7fab5e8c, 0x8dc0dd8f, 0xe330a81a, 0x115b2b19, 0x020bd8ed, 0xf0605bee, + 0x24aa3f05, 0xd6c1bc06, 0xc5914ff2, 0x37faccf1, 0x69e9f0d5, 0x9b8273d6, + 0x88d28022, 0x7ab90321, 0xae7367ca, 0x5c18e4c9, 0x4f48173d, 0xbd23943e, + 0xf36e6f75, 0x0105ec76, 0x12551f82, 0xe03e9c81, 0x34f4f86a, 0xc69f7b69, + 0xd5cf889d, 0x27a40b9e, 0x79b737ba, 0x8bdcb4b9, 0x988c474d, 0x6ae7c44e, + 0xbe2da0a5, 0x4c4623a6, 0x5f16d052, 0xad7d5351, +]; +const CRC32C_EXTENSION_TABLE = new Int32Array(CRC32C_EXTENSIONS); +const CRC32C_DEFAULT_VALIDATOR_GENERATOR = () => new CRC32C(); +const CRC32C_EXCEPTION_MESSAGES = { + INVALID_INIT_BASE64_RANGE: (l) => `base64-encoded data expected to equal 4 bytes, not ${l}`, + INVALID_INIT_BUFFER_LENGTH: (l) => `Buffer expected to equal 4 bytes, not ${l}`, + INVALID_INIT_INTEGER: (l) => `Number expected to be a safe, unsigned 32-bit integer, not ${l}`, +}; +class CRC32C { + /** + * Constructs a new `CRC32C` object. + * + * Reconstruction is recommended via the `CRC32C.from` static method. + * + * @param initialValue An initial CRC32C value - a signed 32-bit integer. + */ + constructor(initialValue = 0) { + /** Current CRC32C value */ + _CRC32C_crc32c.set(this, 0); + __classPrivateFieldSet(this, _CRC32C_crc32c, initialValue, "f"); + } + /** + * Calculates a CRC32C from a provided buffer. + * + * Implementation inspired from: + * - {@link https://github.com/google/crc32c/blob/21fc8ef30415a635e7351ffa0e5d5367943d4a94/src/crc32c_portable.cc github.com/google/crc32c} + * - {@link https://github.com/googleapis/python-crc32c/blob/a595e758c08df445a99c3bf132ee8e80a3ec4308/src/google_crc32c/python.py github.com/googleapis/python-crc32c} + * - {@link https://github.com/googleapis/java-storage/pull/1376/files github.com/googleapis/java-storage} + * + * @param data The `Buffer` to generate the CRC32C from + */ + update(data) { + let current = __classPrivateFieldGet(this, _CRC32C_crc32c, "f") ^ 0xffffffff; + for (const d of data) { + const tablePoly = CRC32C.CRC32C_EXTENSION_TABLE[(d ^ current) & 0xff]; + current = tablePoly ^ (current >>> 8); + } + __classPrivateFieldSet(this, _CRC32C_crc32c, current ^ 0xffffffff, "f"); + } + /** + * Validates a provided input to the current CRC32C value. + * + * @param input A Buffer, `CRC32C`-compatible object, base64-encoded data (string), or signed 32-bit integer + */ + validate(input) { + if (typeof input === 'number') { + return input === __classPrivateFieldGet(this, _CRC32C_crc32c, "f"); + } + else if (typeof input === 'string') { + return input === this.toString(); + } + else if (Buffer.isBuffer(input)) { + return Buffer.compare(input, this.toBuffer()) === 0; + } + else { + // `CRC32C`-like object + return input.toString() === this.toString(); + } + } + /** + * Returns a `Buffer` representation of the CRC32C value + */ + toBuffer() { + const buffer = Buffer.alloc(4); + buffer.writeInt32BE(__classPrivateFieldGet(this, _CRC32C_crc32c, "f")); + return buffer; + } + /** + * Returns a JSON-compatible, base64-encoded representation of the CRC32C value. + * + * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify `JSON#stringify`} + */ + toJSON() { + return this.toString(); + } + /** + * Returns a base64-encoded representation of the CRC32C value. + * + * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString `Object#toString`} + */ + toString() { + return this.toBuffer().toString('base64'); + } + /** + * Returns the `number` representation of the CRC32C value as a signed 32-bit integer + * + * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf `Object#valueOf`} + */ + valueOf() { + return __classPrivateFieldGet(this, _CRC32C_crc32c, "f"); + } + /** + * Generates a `CRC32C` from a compatible buffer format. + * + * @param value 4-byte `ArrayBufferView`/`Buffer`/`TypedArray` + */ + static fromBuffer(value) { + let buffer; + if (Buffer.isBuffer(value)) { + buffer = value; + } + else if ('buffer' in value) { + // `ArrayBufferView` + buffer = Buffer.from(value.buffer); + } + else { + // `ArrayBuffer` + buffer = Buffer.from(value); + } + if (buffer.byteLength !== 4) { + throw new RangeError(CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_BUFFER_LENGTH(buffer.byteLength)); + } + return new CRC32C(buffer.readInt32BE()); + } + static async fromFile(file) { + const crc32c = new CRC32C(); + await new Promise((resolve, reject) => { + createReadStream(file) + .on('data', (d) => { + if (typeof d === 'string') { + crc32c.update(Buffer.from(d)); + } + else { + crc32c.update(d); + } + }) + .on('end', () => resolve()) + .on('error', reject); + }); + return crc32c; + } + /** + * Generates a `CRC32C` from 4-byte base64-encoded data (string). + * + * @param value 4-byte base64-encoded data (string) + */ + static fromString(value) { + const buffer = Buffer.from(value, 'base64'); + if (buffer.byteLength !== 4) { + throw new RangeError(CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_BASE64_RANGE(buffer.byteLength)); + } + return this.fromBuffer(buffer); + } + /** + * Generates a `CRC32C` from a safe, unsigned 32-bit integer. + * + * @param value an unsigned 32-bit integer + */ + static fromNumber(value) { + if (!Number.isSafeInteger(value) || value > 2 ** 32 || value < -(2 ** 32)) { + throw new RangeError(CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_INTEGER(value)); + } + return new CRC32C(value); + } + /** + * Generates a `CRC32C` from a variety of compatable types. + * Note: strings are treated as input, not as file paths to read from. + * + * @param value A number, 4-byte `ArrayBufferView`/`Buffer`/`TypedArray`, or 4-byte base64-encoded data (string) + */ + static from(value) { + if (typeof value === 'number') { + return this.fromNumber(value); + } + else if (typeof value === 'string') { + return this.fromString(value); + } + else if ('byteLength' in value) { + // `ArrayBuffer` | `Buffer` | `ArrayBufferView` + return this.fromBuffer(value); + } + else { + // `CRC32CValidator`/`CRC32C`-like + return this.fromString(value.toString()); + } + } +} +_CRC32C_crc32c = new WeakMap(); +CRC32C.CRC32C_EXTENSIONS = CRC32C_EXTENSIONS; +CRC32C.CRC32C_EXTENSION_TABLE = CRC32C_EXTENSION_TABLE; +export { CRC32C, CRC32C_DEFAULT_VALIDATOR_GENERATOR, CRC32C_EXCEPTION_MESSAGES, CRC32C_EXTENSIONS, CRC32C_EXTENSION_TABLE, }; diff --git a/node_modules/@google-cloud/storage/build/esm/src/file.d.ts b/node_modules/@google-cloud/storage/build/esm/src/file.d.ts new file mode 100644 index 0000000..e80a092 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/file.d.ts @@ -0,0 +1,982 @@ +import { BodyResponseCallback, DecorateRequestOptions, GetConfig, MetadataCallback, ServiceObject, SetMetadataResponse } from './nodejs-common/index.js'; +import * as resumableUpload from './resumable-upload.js'; +import { Writable, Readable, PipelineSource } from 'stream'; +import * as http from 'http'; +import { PreconditionOptions, Storage } from './storage.js'; +import { AvailableServiceObjectMethods, Bucket } from './bucket.js'; +import { Acl, AclMetadata } from './acl.js'; +import { GetSignedUrlResponse, GetSignedUrlCallback, URLSigner, SignerGetSignedUrlConfig, Query } from './signer.js'; +import { Duplexify, GCCL_GCS_CMD_KEY } from './nodejs-common/util.js'; +import { CRC32C, CRC32CValidatorGenerator } from './crc32c.js'; +import { URL } from 'url'; +import { BaseMetadata, DeleteCallback, DeleteOptions, GetResponse, InstanceResponseCallback, RequestResponse, SetMetadataOptions } from './nodejs-common/service-object.js'; +import * as r from 'teeny-request'; +export type GetExpirationDateResponse = [Date]; +export interface GetExpirationDateCallback { + (err: Error | null, expirationDate?: Date | null, apiResponse?: unknown): void; +} +export interface PolicyDocument { + string: string; + base64: string; + signature: string; +} +export type SaveData = string | Buffer | Uint8Array | PipelineSource; +export type GenerateSignedPostPolicyV2Response = [PolicyDocument]; +export interface GenerateSignedPostPolicyV2Callback { + (err: Error | null, policy?: PolicyDocument): void; +} +export interface GenerateSignedPostPolicyV2Options { + equals?: string[] | string[][]; + expires: string | number | Date; + startsWith?: string[] | string[][]; + acl?: string; + successRedirect?: string; + successStatus?: string; + contentLengthRange?: { + min?: number; + max?: number; + }; + /** + * @example + * 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/' + */ + signingEndpoint?: string; +} +export interface PolicyFields { + [key: string]: string; +} +export interface GenerateSignedPostPolicyV4Options { + expires: string | number | Date; + bucketBoundHostname?: string; + virtualHostedStyle?: boolean; + conditions?: object[]; + fields?: PolicyFields; + /** + * @example + * 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/' + */ + signingEndpoint?: string; +} +export interface GenerateSignedPostPolicyV4Callback { + (err: Error | null, output?: SignedPostPolicyV4Output): void; +} +export type GenerateSignedPostPolicyV4Response = [SignedPostPolicyV4Output]; +export interface SignedPostPolicyV4Output { + url: string; + fields: PolicyFields; +} +export interface GetSignedUrlConfig extends Pick { + action: 'read' | 'write' | 'delete' | 'resumable'; + version?: 'v2' | 'v4'; + virtualHostedStyle?: boolean; + cname?: string; + contentMd5?: string; + contentType?: string; + expires: string | number | Date; + accessibleAt?: string | number | Date; + extensionHeaders?: http.OutgoingHttpHeaders; + promptSaveAs?: string; + responseDisposition?: string; + responseType?: string; + queryParams?: Query; +} +export interface GetFileMetadataOptions { + userProject?: string; +} +export type GetFileMetadataResponse = [FileMetadata, unknown]; +export interface GetFileMetadataCallback { + (err: Error | null, metadata?: FileMetadata, apiResponse?: unknown): void; +} +export interface GetFileOptions extends GetConfig { + userProject?: string; + generation?: number; + restoreToken?: string; + softDeleted?: boolean; +} +export type GetFileResponse = [File, unknown]; +export interface GetFileCallback { + (err: Error | null, file?: File, apiResponse?: unknown): void; +} +export interface FileExistsOptions { + userProject?: string; +} +export type FileExistsResponse = [boolean]; +export interface FileExistsCallback { + (err: Error | null, exists?: boolean): void; +} +export interface DeleteFileOptions { + ignoreNotFound?: boolean; + userProject?: string; +} +export type DeleteFileResponse = [unknown]; +export interface DeleteFileCallback { + (err: Error | null, apiResponse?: unknown): void; +} +export type PredefinedAcl = 'authenticatedRead' | 'bucketOwnerFullControl' | 'bucketOwnerRead' | 'private' | 'projectPrivate' | 'publicRead'; +type PublicResumableUploadOptions = 'chunkSize' | 'highWaterMark' | 'isPartialUpload' | 'metadata' | 'origin' | 'offset' | 'predefinedAcl' | 'private' | 'public' | 'uri' | 'userProject'; +export interface CreateResumableUploadOptions extends Pick { + /** + * A CRC32C to resume from when continuing a previous upload. It is recommended + * to capture the `crc32c` event from previous upload sessions to provide in + * subsequent requests in order to accurately track the upload. This is **required** + * when validating a final portion of the uploaded object. + * + * @see {@link CRC32C.from} for possible values. + */ + resumeCRC32C?: Parameters<(typeof CRC32C)['from']>[0]; + preconditionOpts?: PreconditionOptions; + [GCCL_GCS_CMD_KEY]?: resumableUpload.UploadConfig[typeof GCCL_GCS_CMD_KEY]; +} +export type CreateResumableUploadResponse = [string]; +export interface CreateResumableUploadCallback { + (err: Error | null, uri?: string): void; +} +export interface CreateWriteStreamOptions extends CreateResumableUploadOptions { + contentType?: string; + gzip?: string | boolean; + resumable?: boolean; + timeout?: number; + validation?: string | boolean; +} +export interface MakeFilePrivateOptions { + metadata?: FileMetadata; + strict?: boolean; + userProject?: string; + preconditionOpts?: PreconditionOptions; +} +export type MakeFilePrivateResponse = [unknown]; +export type MakeFilePrivateCallback = SetFileMetadataCallback; +export interface IsPublicCallback { + (err: Error | null, resp?: boolean): void; +} +export type IsPublicResponse = [boolean]; +export type MakeFilePublicResponse = [unknown]; +export interface MakeFilePublicCallback { + (err?: Error | null, apiResponse?: unknown): void; +} +export type MoveResponse = [unknown]; +export interface MoveCallback { + (err: Error | null, destinationFile?: File | null, apiResponse?: unknown): void; +} +export interface MoveOptions { + userProject?: string; + preconditionOpts?: PreconditionOptions; +} +export type MoveFileAtomicOptions = MoveOptions; +export type MoveFileAtomicCallback = MoveCallback; +export type MoveFileAtomicResponse = MoveResponse; +export type RenameOptions = MoveOptions; +export type RenameResponse = MoveResponse; +export type RenameCallback = MoveCallback; +export type RotateEncryptionKeyOptions = string | Buffer | EncryptionKeyOptions; +export interface EncryptionKeyOptions { + encryptionKey?: string | Buffer; + kmsKeyName?: string; + preconditionOpts?: PreconditionOptions; +} +export type RotateEncryptionKeyCallback = CopyCallback; +export type RotateEncryptionKeyResponse = CopyResponse; +export declare enum ActionToHTTPMethod { + read = "GET", + write = "PUT", + delete = "DELETE", + resumable = "POST" +} +/** + * @deprecated - no longer used + */ +export declare const STORAGE_POST_POLICY_BASE_URL = "https://storage.googleapis.com"; +export interface FileOptions { + crc32cGenerator?: CRC32CValidatorGenerator; + encryptionKey?: string | Buffer; + generation?: number | string; + restoreToken?: string; + kmsKeyName?: string; + preconditionOpts?: PreconditionOptions; + userProject?: string; +} +export interface CopyOptions { + cacheControl?: string; + contentEncoding?: string; + contentType?: string; + contentDisposition?: string; + destinationKmsKeyName?: string; + metadata?: { + [key: string]: string | boolean | number | null; + }; + predefinedAcl?: string; + token?: string; + userProject?: string; + preconditionOpts?: PreconditionOptions; +} +export type CopyResponse = [File, unknown]; +export interface CopyCallback { + (err: Error | null, file?: File | null, apiResponse?: unknown): void; +} +export type DownloadResponse = [Buffer]; +export type DownloadCallback = (err: RequestError | null, contents: Buffer) => void; +export interface DownloadOptions extends CreateReadStreamOptions { + destination?: string; + encryptionKey?: string | Buffer; +} +export interface CreateReadStreamOptions { + userProject?: string; + validation?: 'md5' | 'crc32c' | false | true; + start?: number; + end?: number; + decompress?: boolean; + [GCCL_GCS_CMD_KEY]?: string; +} +export interface SaveOptions extends CreateWriteStreamOptions { + onUploadProgress?: (progressEvent: any) => void; +} +export interface SaveCallback { + (err?: Error | null): void; +} +export interface SetFileMetadataOptions { + userProject?: string; +} +export interface SetFileMetadataCallback { + (err?: Error | null, apiResponse?: unknown): void; +} +export type SetFileMetadataResponse = [unknown]; +export type SetStorageClassResponse = [unknown]; +export interface SetStorageClassOptions { + userProject?: string; + preconditionOpts?: PreconditionOptions; +} +export interface SetStorageClassCallback { + (err?: Error | null, apiResponse?: unknown): void; +} +export interface RestoreOptions extends PreconditionOptions { + generation: number; + restoreToken?: string; + projection?: 'full' | 'noAcl'; +} +export interface FileMetadata extends BaseMetadata { + acl?: AclMetadata[] | null; + bucket?: string; + cacheControl?: string; + componentCount?: number; + contentDisposition?: string; + contentEncoding?: string; + contentLanguage?: string; + contentType?: string; + crc32c?: string; + customerEncryption?: { + encryptionAlgorithm?: string; + keySha256?: string; + }; + customTime?: string; + eventBasedHold?: boolean | null; + readonly eventBasedHoldReleaseTime?: string; + generation?: string | number; + restoreToken?: string; + hardDeleteTime?: string; + kmsKeyName?: string; + md5Hash?: string; + mediaLink?: string; + metadata?: { + [key: string]: string | boolean | number | null; + }; + metageneration?: string | number; + name?: string; + owner?: { + entity?: string; + entityId?: string; + }; + retention?: { + retainUntilTime?: string; + mode?: string; + } | null; + retentionExpirationTime?: string; + size?: string | number; + softDeleteTime?: string; + storageClass?: string; + temporaryHold?: boolean | null; + timeCreated?: string; + timeDeleted?: string; + timeStorageClassUpdated?: string; + updated?: string; +} +export declare class RequestError extends Error { + code?: string; + errors?: Error[]; +} +export declare enum FileExceptionMessages { + EXPIRATION_TIME_NA = "An expiration time is not available.", + DESTINATION_NO_NAME = "Destination file should have a name.", + INVALID_VALIDATION_FILE_RANGE = "Cannot use validation with file ranges (start/end).", + MD5_NOT_AVAILABLE = "MD5 verification was specified, but is not available for the requested object. MD5 is not available for composite objects.", + EQUALS_CONDITION_TWO_ELEMENTS = "Equals condition must be an array of 2 elements.", + STARTS_WITH_TWO_ELEMENTS = "StartsWith condition must be an array of 2 elements.", + CONTENT_LENGTH_RANGE_MIN_MAX = "ContentLengthRange must have numeric min & max fields.", + DOWNLOAD_MISMATCH = "The downloaded data did not match the data from the server. To be sure the content is the same, you should download the file again.", + UPLOAD_MISMATCH_DELETE_FAIL = "The uploaded data did not match the data from the server.\n As a precaution, we attempted to delete the file, but it was not successful.\n To be sure the content is the same, you should try removing the file manually,\n then uploading the file again.\n \n\nThe delete attempt failed with this message:\n\n ", + UPLOAD_MISMATCH = "The uploaded data did not match the data from the server.\n As a precaution, the file has been deleted.\n To be sure the content is the same, you should try uploading the file again.", + MD5_RESUMED_UPLOAD = "MD5 cannot be used with a continued resumable upload as MD5 cannot be extended from an existing value", + MISSING_RESUME_CRC32C_FINAL_UPLOAD = "The CRC32C is missing for the final portion of a resumed upload, which is required for validation. Please provide `resumeCRC32C` if validation is required, or disable `validation`." +} +/** + * A File object is created from your {@link Bucket} object using + * {@link Bucket#file}. + * + * @class + */ +declare class File extends ServiceObject { + #private; + acl: Acl; + crc32cGenerator: CRC32CValidatorGenerator; + bucket: Bucket; + storage: Storage; + kmsKeyName?: string; + userProject?: string; + signer?: URLSigner; + name: string; + generation?: number; + restoreToken?: string; + parent: Bucket; + private encryptionKey?; + private encryptionKeyBase64?; + private encryptionKeyHash?; + private encryptionKeyInterceptor?; + private instanceRetryValue?; + instancePreconditionOpts?: PreconditionOptions; + /** + * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share objects with other + * users and allow other users to access your buckets and objects. + * + * An ACL consists of one or more entries, where each entry grants permissions + * to an entity. Permissions define the actions that can be performed against + * an object or bucket (for example, `READ` or `WRITE`); the entity defines + * who the permission applies to (for example, a specific user or group of + * users). + * + * The `acl` object on a File instance provides methods to get you a list of + * the ACLs defined on your bucket, as well as set, update, and delete them. + * + * See {@link http://goo.gl/6qBBPO| About Access Control lists} + * + * @name File#acl + * @mixes Acl + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * //- + * // Make a file publicly readable. + * //- + * const options = { + * entity: 'allUsers', + * role: storage.acl.READER_ROLE + * }; + * + * file.acl.add(options, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.acl.add(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + /** + * The API-formatted resource description of the file. + * + * Note: This is not guaranteed to be up-to-date when accessed. To get the + * latest record, call the `getMetadata()` method. + * + * @name File#metadata + * @type {object} + */ + /** + * The file's name. + * @name File#name + * @type {string} + */ + /** + * @callback Crc32cGeneratorToStringCallback + * A method returning the CRC32C as a base64-encoded string. + * + * @returns {string} + * + * @example + * Hashing the string 'data' should return 'rth90Q==' + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.toString(); // 'rth90Q==' + * ``` + **/ + /** + * @callback Crc32cGeneratorValidateCallback + * A method validating a base64-encoded CRC32C string. + * + * @param {string} [value] base64-encoded CRC32C string to validate + * @returns {boolean} + * + * @example + * Should return `true` if the value matches, `false` otherwise + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.validate('DkjKuA=='); // false + * crc32c.validate('rth90Q=='); // true + * ``` + **/ + /** + * @callback Crc32cGeneratorUpdateCallback + * A method for passing `Buffer`s for CRC32C generation. + * + * @param {Buffer} [data] data to update CRC32C value with + * @returns {undefined} + * + * @example + * Hashing buffers from 'some ' and 'text\n' + * + * ```js + * const buffer1 = Buffer.from('some '); + * crc32c.update(buffer1); + * + * const buffer2 = Buffer.from('text\n'); + * crc32c.update(buffer2); + * + * crc32c.toString(); // 'DkjKuA==' + * ``` + **/ + /** + * @typedef {object} CRC32CValidator + * @property {Crc32cGeneratorToStringCallback} + * @property {Crc32cGeneratorValidateCallback} + * @property {Crc32cGeneratorUpdateCallback} + */ + /** + * @callback Crc32cGeneratorCallback + * @returns {CRC32CValidator} + */ + /** + * @typedef {object} FileOptions Options passed to the File constructor. + * @property {string} [encryptionKey] A custom encryption key. + * @property {number} [generation] Generation to scope the file to. + * @property {string} [kmsKeyName] Cloud KMS Key used to encrypt this + * object, if the object is encrypted by such a key. Limited availability; + * usable only by enabled projects. + * @property {string} [userProject] The ID of the project which will be + * billed for all requests made from File object. + * @property {Crc32cGeneratorCallback} [callback] A function that generates a CRC32C Validator. Defaults to {@link CRC32C} + */ + /** + * Constructs a file object. + * + * @param {Bucket} bucket The Bucket instance this file is + * attached to. + * @param {string} name The name of the remote file. + * @param {FileOptions} [options] Configuration options. + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * ``` + */ + constructor(bucket: Bucket, name: string, options?: FileOptions); + /** + * The object's Cloud Storage URI (`gs://`) + * + * @example + * ```ts + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const file = bucket.file('image.png'); + * + * // `gs://my-bucket/image.png` + * const href = file.cloudStorageURI.href; + * ``` + */ + get cloudStorageURI(): URL; + /** + * A helper method for determining if a request should be retried based on preconditions. + * This should only be used for methods where the idempotency is determined by + * `ifGenerationMatch` + * @private + * + * A request should not be retried under the following conditions: + * - if precondition option `ifGenerationMatch` is not set OR + * - if `idempotencyStrategy` is set to `RetryNever` + */ + private shouldRetryBasedOnPreconditionAndIdempotencyStrat; + copy(destination: string | Bucket | File, options?: CopyOptions): Promise; + copy(destination: string | Bucket | File, callback: CopyCallback): void; + copy(destination: string | Bucket | File, options: CopyOptions, callback: CopyCallback): void; + /** + * @typedef {object} CreateReadStreamOptions Configuration options for File#createReadStream. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {string|boolean} [validation] Possible values: `"md5"`, + * `"crc32c"`, or `false`. By default, data integrity is validated with a + * CRC32c checksum. You may use MD5 if preferred, but that hash is not + * supported for composite objects. An error will be raised if MD5 is + * specified but is not available. You may also choose to skip validation + * completely, however this is **not recommended**. + * @property {number} [start] A byte offset to begin the file's download + * from. Default is 0. NOTE: Byte ranges are inclusive; that is, + * `options.start = 0` and `options.end = 999` represent the first 1000 + * bytes in a file or object. NOTE: when specifying a byte range, data + * integrity is not available. + * @property {number} [end] A byte offset to stop reading the file at. + * NOTE: Byte ranges are inclusive; that is, `options.start = 0` and + * `options.end = 999` represent the first 1000 bytes in a file or object. + * NOTE: when specifying a byte range, data integrity is not available. + * @property {boolean} [decompress=true] Disable auto decompression of the + * received data. By default this option is set to `true`. + * Applicable in cases where the data was uploaded with + * `gzip: true` option. See {@link File#createWriteStream}. + */ + /** + * Create a readable stream to read the contents of the remote file. It can be + * piped to a writable stream or listened to for 'data' events to read a + * file's contents. + * + * In the unlikely event there is a mismatch between what you downloaded and + * the version in your Bucket, your error handler will receive an error with + * code "CONTENT_DOWNLOAD_MISMATCH". If you receive this error, the best + * recourse is to try downloading the file again. + * + * NOTE: Readable streams will emit the `end` event when the file is fully + * downloaded. + * + * @param {CreateReadStreamOptions} [options] Configuration options. + * @returns {ReadableStream} + * + * @example + * ``` + * //- + * //

Downloading a File

+ * // + * // The example below demonstrates how we can reference a remote file, then + * // pipe its contents to a local file. This is effectively creating a local + * // backup of your remote data. + * //- + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * const fs = require('fs'); + * const remoteFile = bucket.file('image.png'); + * const localFilename = '/Users/stephen/Photos/image.png'; + * + * remoteFile.createReadStream() + * .on('error', function(err) {}) + * .on('response', function(response) { + * // Server connected and responded with the specified status and headers. + * }) + * .on('end', function() { + * // The file is fully downloaded. + * }) + * .pipe(fs.createWriteStream(localFilename)); + * + * //- + * // To limit the downloaded data to only a byte range, pass an options + * // object. + * //- + * const logFile = myBucket.file('access_log'); + * logFile.createReadStream({ + * start: 10000, + * end: 20000 + * }) + * .on('error', function(err) {}) + * .pipe(fs.createWriteStream('/Users/stephen/logfile.txt')); + * + * //- + * // To read a tail byte range, specify only `options.end` as a negative + * // number. + * //- + * const logFile = myBucket.file('access_log'); + * logFile.createReadStream({ + * end: -100 + * }) + * .on('error', function(err) {}) + * .pipe(fs.createWriteStream('/Users/stephen/logfile.txt')); + * ``` + */ + createReadStream(options?: CreateReadStreamOptions): Readable; + createResumableUpload(options?: CreateResumableUploadOptions): Promise; + createResumableUpload(options: CreateResumableUploadOptions, callback: CreateResumableUploadCallback): void; + createResumableUpload(callback: CreateResumableUploadCallback): void; + /** + * @typedef {object} CreateWriteStreamOptions Configuration options for File#createWriteStream(). + * @property {string} [contentType] Alias for + * `options.metadata.contentType`. If set to `auto`, the file name is used + * to determine the contentType. + * @property {string|boolean} [gzip] If true, automatically gzip the file. + * If set to `auto`, the contentType is used to determine if the file + * should be gzipped. This will set `options.metadata.contentEncoding` to + * `gzip` if necessary. + * @property {object} [metadata] See the examples below or + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON| Objects: insert request body} + * for more details. + * @property {number} [offset] The starting byte of the upload stream, for + * resuming an interrupted upload. Defaults to 0. + * @property {string} [predefinedAcl] Apply a predefined set of access + * controls to this object. + * + * Acceptable values are: + * - **`authenticatedRead`** - Object owner gets `OWNER` access, and + * `allAuthenticatedUsers` get `READER` access. + * + * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and + * project team owners get `OWNER` access. + * + * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project + * team owners get `READER` access. + * + * - **`private`** - Object owner gets `OWNER` access. + * + * - **`projectPrivate`** - Object owner gets `OWNER` access, and project + * team members get access according to their roles. + * + * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers` + * get `READER` access. + * @property {boolean} [private] Make the uploaded file private. (Alias for + * `options.predefinedAcl = 'private'`) + * @property {boolean} [public] Make the uploaded file public. (Alias for + * `options.predefinedAcl = 'publicRead'`) + * @property {boolean} [resumable] Force a resumable upload. NOTE: When + * working with streams, the file format and size is unknown until it's + * completely consumed. Because of this, it's best for you to be explicit + * for what makes sense given your input. + * @property {number} [timeout=60000] Set the HTTP request timeout in + * milliseconds. This option is not available for resumable uploads. + * Default: `60000` + * @property {string} [uri] The URI for an already-created resumable + * upload. See {@link File#createResumableUpload}. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {string|boolean} [validation] Possible values: `"md5"`, + * `"crc32c"`, or `false`. By default, data integrity is validated with a + * CRC32c checksum. You may use MD5 if preferred, but that hash is not + * supported for composite objects. An error will be raised if MD5 is + * specified but is not available. You may also choose to skip validation + * completely, however this is **not recommended**. In addition to specifying + * validation type, providing `metadata.crc32c` or `metadata.md5Hash` will + * cause the server to perform validation in addition to client validation. + * NOTE: Validation is automatically skipped for objects that were + * uploaded using the `gzip` option and have already compressed content. + */ + /** + * Create a writable stream to overwrite the contents of the file in your + * bucket. + * + * A File object can also be used to create files for the first time. + * + * Resumable uploads are automatically enabled and must be shut off explicitly + * by setting `options.resumable` to `false`. + * + * + *

+ * There is some overhead when using a resumable upload that can cause + * noticeable performance degradation while uploading a series of small + * files. When uploading files less than 10MB, it is recommended that the + * resumable feature is disabled. + *

+ * + * NOTE: Writable streams will emit the `finish` event when the file is fully + * uploaded. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload Upload Options (Simple or Resumable)} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert Objects: insert API Documentation} + * + * @param {CreateWriteStreamOptions} [options] Configuration options. + * @returns {WritableStream} + * + * @example + * ``` + * const fs = require('fs'); + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * //- + * //

Uploading a File

+ * // + * // Now, consider a case where we want to upload a file to your bucket. You + * // have the option of using {@link Bucket#upload}, but that is just + * // a convenience method which will do the following. + * //- + * fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg') + * .pipe(file.createWriteStream()) + * .on('error', function(err) {}) + * .on('finish', function() { + * // The file upload is complete. + * }); + * + * //- + * //

Uploading a File with gzip compression

+ * //- + * fs.createReadStream('/Users/stephen/site/index.html') + * .pipe(file.createWriteStream({ gzip: true })) + * .on('error', function(err) {}) + * .on('finish', function() { + * // The file upload is complete. + * }); + * + * //- + * // Downloading the file with `createReadStream` will automatically decode + * // the file. + * //- + * + * //- + * //

Uploading a File with Metadata

+ * // + * // One last case you may run into is when you want to upload a file to your + * // bucket and set its metadata at the same time. Like above, you can use + * // {@link Bucket#upload} to do this, which is just a wrapper around + * // the following. + * //- + * fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg') + * .pipe(file.createWriteStream({ + * metadata: { + * contentType: 'image/jpeg', + * metadata: { + * custom: 'metadata' + * } + * } + * })) + * .on('error', function(err) {}) + * .on('finish', function() { + * // The file upload is complete. + * }); + * ``` + * + * //- + * //

Continuing a Resumable Upload

+ * // + * // One can capture a `uri` from a resumable upload to reuse later. + * // Additionally, for validation, one can also capture and pass `crc32c`. + * //- + * let uri: string | undefined = undefined; + * let resumeCRC32C: string | undefined = undefined; + * + * fs.createWriteStream() + * .on('uri', link => {uri = link}) + * .on('crc32', crc32c => {resumeCRC32C = crc32c}); + * + * // later... + * fs.createWriteStream({uri, resumeCRC32C}); + */ + createWriteStream(options?: CreateWriteStreamOptions): Writable; + /** + * Delete the object. + * + * @param {function=} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.apiResponse - The full API response. + */ + delete(options?: DeleteOptions): Promise<[r.Response]>; + delete(options: DeleteOptions, callback: DeleteCallback): void; + delete(callback: DeleteCallback): void; + download(options?: DownloadOptions): Promise; + download(options: DownloadOptions, callback: DownloadCallback): void; + download(callback: DownloadCallback): void; + /** + * The Storage API allows you to use a custom key for server-side encryption. + * + * See {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys} + * + * @param {string|buffer} encryptionKey An AES-256 encryption key. + * @returns {File} + * + * @example + * ``` + * const crypto = require('crypto'); + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const encryptionKey = crypto.randomBytes(32); + * + * const fileWithCustomEncryption = myBucket.file('my-file'); + * fileWithCustomEncryption.setEncryptionKey(encryptionKey); + * + * const fileWithoutCustomEncryption = myBucket.file('my-file'); + * + * fileWithCustomEncryption.save('data', function(err) { + * // Try to download with the File object that hasn't had + * // `setEncryptionKey()` called: + * fileWithoutCustomEncryption.download(function(err) { + * // We will receive an error: + * // err.message === 'Bad Request' + * + * // Try again with the File object we called `setEncryptionKey()` on: + * fileWithCustomEncryption.download(function(err, contents) { + * // contents.toString() === 'data' + * }); + * }); + * }); + * + * ``` + * @example include:samples/encryption.js + * region_tag:storage_upload_encrypted_file + * Example of uploading an encrypted file: + * + * @example include:samples/encryption.js + * region_tag:storage_download_encrypted_file + * Example of downloading an encrypted file: + */ + setEncryptionKey(encryptionKey: string | Buffer): this; + /** + * Gets a reference to a Cloud Storage {@link File} file from the provided URL in string format. + * @param {string} publicUrlOrGsUrl the URL as a string. Must be of the format gs://bucket/file + * or https://storage.googleapis.com/bucket/file. + * @param {Storage} storageInstance an instance of a Storage object. + * @param {FileOptions} [options] Configuration options + * @returns {File} + */ + static from(publicUrlOrGsUrl: string, storageInstance: Storage, options?: FileOptions): File; + get(options?: GetFileOptions): Promise>; + get(callback: InstanceResponseCallback): void; + get(options: GetFileOptions, callback: InstanceResponseCallback): void; + getExpirationDate(): Promise; + getExpirationDate(callback: GetExpirationDateCallback): void; + generateSignedPostPolicyV2(options: GenerateSignedPostPolicyV2Options): Promise; + generateSignedPostPolicyV2(options: GenerateSignedPostPolicyV2Options, callback: GenerateSignedPostPolicyV2Callback): void; + generateSignedPostPolicyV2(callback: GenerateSignedPostPolicyV2Callback): void; + generateSignedPostPolicyV4(options: GenerateSignedPostPolicyV4Options): Promise; + generateSignedPostPolicyV4(options: GenerateSignedPostPolicyV4Options, callback: GenerateSignedPostPolicyV4Callback): void; + generateSignedPostPolicyV4(callback: GenerateSignedPostPolicyV4Callback): void; + getSignedUrl(cfg: GetSignedUrlConfig): Promise; + getSignedUrl(cfg: GetSignedUrlConfig, callback: GetSignedUrlCallback): void; + isPublic(): Promise; + isPublic(callback: IsPublicCallback): void; + makePrivate(options?: MakeFilePrivateOptions): Promise; + makePrivate(callback: MakeFilePrivateCallback): void; + makePrivate(options: MakeFilePrivateOptions, callback: MakeFilePrivateCallback): void; + makePublic(): Promise; + makePublic(callback: MakeFilePublicCallback): void; + /** + * The public URL of this File + * Use {@link File#makePublic} to enable anonymous access via the returned URL. + * + * @returns {string} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * const file = bucket.file('my-file'); + * + * // publicUrl will be "https://storage.googleapis.com/albums/my-file" + * const publicUrl = file.publicUrl(); + * ``` + */ + publicUrl(): string; + moveFileAtomic(destination: string | File, options?: MoveFileAtomicOptions): Promise; + moveFileAtomic(destination: string | File, callback: MoveFileAtomicCallback): void; + moveFileAtomic(destination: string | File, options: MoveFileAtomicOptions, callback: MoveFileAtomicCallback): void; + move(destination: string | Bucket | File, options?: MoveOptions): Promise; + move(destination: string | Bucket | File, callback: MoveCallback): void; + move(destination: string | Bucket | File, options: MoveOptions, callback: MoveCallback): void; + rename(destinationFile: string | File, options?: RenameOptions): Promise; + rename(destinationFile: string | File, callback: RenameCallback): void; + rename(destinationFile: string | File, options: RenameOptions, callback: RenameCallback): void; + /** + * @typedef {object} RestoreOptions Options for File#restore(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}. + * @param {string} [userProject] The ID of the project which will be + * billed for the request. + * @param {number} [generation] If present, selects a specific revision of this object. + * @param {string} [restoreToken] Returns an option that must be specified when getting a soft-deleted object from an HNS-enabled + * bucket that has a naming and generation conflict with another object in the same bucket. + * @param {string} [projection] Specifies the set of properties to return. If used, must be 'full' or 'noAcl'. + * @param {string | number} [ifGenerationMatch] Request proceeds if the generation of the target resource + * matches the value used in the precondition. + * If the values don't match, the request fails with a 412 Precondition Failed response. + * @param {string | number} [ifGenerationNotMatch] Request proceeds if the generation of the target resource does + * not match the value used in the precondition. If the values match, the request fails with a 304 Not Modified response. + * @param {string | number} [ifMetagenerationMatch] Request proceeds if the meta-generation of the target resource + * matches the value used in the precondition. + * If the values don't match, the request fails with a 412 Precondition Failed response. + * @param {string | number} [ifMetagenerationNotMatch] Request proceeds if the meta-generation of the target resource does + * not match the value used in the precondition. If the values match, the request fails with a 304 Not Modified response. + */ + /** + * Restores a soft-deleted file + * @param {RestoreOptions} options Restore options. + * @returns {Promise} + */ + restore(options: RestoreOptions): Promise; + request(reqOpts: DecorateRequestOptions): Promise; + request(reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void; + rotateEncryptionKey(options?: RotateEncryptionKeyOptions): Promise; + rotateEncryptionKey(callback: RotateEncryptionKeyCallback): void; + rotateEncryptionKey(options: RotateEncryptionKeyOptions, callback: RotateEncryptionKeyCallback): void; + save(data: SaveData, options?: SaveOptions): Promise; + save(data: SaveData, callback: SaveCallback): void; + save(data: SaveData, options: SaveOptions, callback: SaveCallback): void; + setMetadata(metadata: FileMetadata, options?: SetMetadataOptions): Promise>; + setMetadata(metadata: FileMetadata, callback: MetadataCallback): void; + setMetadata(metadata: FileMetadata, options: SetMetadataOptions, callback: MetadataCallback): void; + setStorageClass(storageClass: string, options?: SetStorageClassOptions): Promise; + setStorageClass(storageClass: string, options: SetStorageClassOptions, callback: SetStorageClassCallback): void; + setStorageClass(storageClass: string, callback?: SetStorageClassCallback): void; + /** + * Set a user project to be billed for all requests made from this File + * object. + * + * @param {string} userProject The user project. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * const file = bucket.file('my-file'); + * + * file.setUserProject('grape-spaceship-123'); + * ``` + */ + setUserProject(userProject: string): void; + /** + * This creates a resumable-upload upload stream. + * + * @param {Duplexify} stream - Duplexify stream of data to pipe to the file. + * @param {object=} options - Configuration object. + * + * @private + */ + startResumableUpload_(dup: Duplexify, options?: CreateResumableUploadOptions): void; + /** + * Takes a readable stream and pipes it to a remote file. Unlike + * `startResumableUpload_`, which uses the resumable upload technique, this + * method uses a simple upload (all or nothing). + * + * @param {Duplexify} dup - Duplexify stream of data to pipe to the file. + * @param {object=} options - Configuration object. + * + * @private + */ + startSimpleUpload_(dup: Duplexify, options?: CreateWriteStreamOptions): void; + disableAutoRetryConditionallyIdempotent_(coreOpts: any, methodType: AvailableServiceObjectMethods, localPreconditionOptions?: PreconditionOptions): void; + private getBufferFromReadable; +} +/** + * Reference to the {@link File} class. + * @name module:@google-cloud/storage.File + * @see File + */ +export { File }; diff --git a/node_modules/@google-cloud/storage/build/esm/src/file.js b/node_modules/@google-cloud/storage/build/esm/src/file.js new file mode 100644 index 0000000..3734c0b --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/file.js @@ -0,0 +1,3557 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _File_instances, _File_validateIntegrity; +import { ServiceObject, util, } from './nodejs-common/index.js'; +import { promisifyAll } from '@google-cloud/promisify'; +import * as crypto from 'crypto'; +import * as fs from 'fs'; +import mime from 'mime'; +import * as resumableUpload from './resumable-upload.js'; +import { Writable, pipeline } from 'stream'; +import * as zlib from 'zlib'; +import { ExceptionMessages, IdempotencyStrategy, } from './storage.js'; +import { AvailableServiceObjectMethods, Bucket } from './bucket.js'; +import { Acl } from './acl.js'; +import { SigningError, URLSigner, } from './signer.js'; +import { GCCL_GCS_CMD_KEY, } from './nodejs-common/util.js'; +import duplexify from 'duplexify'; +import { normalize, objectKeyToLowercase, unicodeJSONStringify, formatAsUTCISO, PassThroughShim, } from './util.js'; +import { CRC32C } from './crc32c.js'; +import { HashStreamValidator } from './hash-stream-validator.js'; +import AsyncRetry from 'async-retry'; +export var ActionToHTTPMethod; +(function (ActionToHTTPMethod) { + ActionToHTTPMethod["read"] = "GET"; + ActionToHTTPMethod["write"] = "PUT"; + ActionToHTTPMethod["delete"] = "DELETE"; + ActionToHTTPMethod["resumable"] = "POST"; +})(ActionToHTTPMethod || (ActionToHTTPMethod = {})); +/** + * @deprecated - no longer used + */ +export const STORAGE_POST_POLICY_BASE_URL = 'https://storage.googleapis.com'; +/** + * @private + */ +const GS_URL_REGEXP = /^gs:\/\/([a-z0-9_.-]+)\/(.+)$/; +/** + * @private + * This regex will match compressible content types. These are primarily text/*, +json, +text, +xml content types. + * This was based off of mime-db and may periodically need to be updated if new compressible content types become + * standards. + */ +const COMPRESSIBLE_MIME_REGEX = new RegExp([ + /^text\/|application\/ecmascript|application\/javascript|application\/json/, + /|application\/postscript|application\/rtf|application\/toml|application\/vnd.dart/, + /|application\/vnd.ms-fontobject|application\/wasm|application\/x-httpd-php|application\/x-ns-proxy-autoconfig/, + /|application\/x-sh(?!ockwave-flash)|application\/x-tar|application\/x-virtualbox-hdd|application\/x-virtualbox-ova|application\/x-virtualbox-ovf/, + /|^application\/x-virtualbox-vbox$|application\/x-virtualbox-vdi|application\/x-virtualbox-vhd|application\/x-virtualbox-vmdk/, + /|application\/xml|application\/xml-dtd|font\/otf|font\/ttf|image\/bmp|image\/vnd.adobe.photoshop|image\/vnd.microsoft.icon/, + /|image\/vnd.ms-dds|image\/x-icon|image\/x-ms-bmp|message\/rfc822|model\/gltf-binary|\+json|\+text|\+xml|\+yaml/, +] + .map(r => r.source) + .join(''), 'i'); +export class RequestError extends Error { +} +const SEVEN_DAYS = 7 * 24 * 60 * 60; +const GS_UTIL_URL_REGEX = /(gs):\/\/([a-z0-9_.-]+)\/(.+)/g; +const HTTPS_PUBLIC_URL_REGEX = /(https):\/\/(storage\.googleapis\.com)\/([a-z0-9_.-]+)\/(.+)/g; +export var FileExceptionMessages; +(function (FileExceptionMessages) { + FileExceptionMessages["EXPIRATION_TIME_NA"] = "An expiration time is not available."; + FileExceptionMessages["DESTINATION_NO_NAME"] = "Destination file should have a name."; + FileExceptionMessages["INVALID_VALIDATION_FILE_RANGE"] = "Cannot use validation with file ranges (start/end)."; + FileExceptionMessages["MD5_NOT_AVAILABLE"] = "MD5 verification was specified, but is not available for the requested object. MD5 is not available for composite objects."; + FileExceptionMessages["EQUALS_CONDITION_TWO_ELEMENTS"] = "Equals condition must be an array of 2 elements."; + FileExceptionMessages["STARTS_WITH_TWO_ELEMENTS"] = "StartsWith condition must be an array of 2 elements."; + FileExceptionMessages["CONTENT_LENGTH_RANGE_MIN_MAX"] = "ContentLengthRange must have numeric min & max fields."; + FileExceptionMessages["DOWNLOAD_MISMATCH"] = "The downloaded data did not match the data from the server. To be sure the content is the same, you should download the file again."; + FileExceptionMessages["UPLOAD_MISMATCH_DELETE_FAIL"] = "The uploaded data did not match the data from the server.\n As a precaution, we attempted to delete the file, but it was not successful.\n To be sure the content is the same, you should try removing the file manually,\n then uploading the file again.\n \n\nThe delete attempt failed with this message:\n\n "; + FileExceptionMessages["UPLOAD_MISMATCH"] = "The uploaded data did not match the data from the server.\n As a precaution, the file has been deleted.\n To be sure the content is the same, you should try uploading the file again."; + FileExceptionMessages["MD5_RESUMED_UPLOAD"] = "MD5 cannot be used with a continued resumable upload as MD5 cannot be extended from an existing value"; + FileExceptionMessages["MISSING_RESUME_CRC32C_FINAL_UPLOAD"] = "The CRC32C is missing for the final portion of a resumed upload, which is required for validation. Please provide `resumeCRC32C` if validation is required, or disable `validation`."; +})(FileExceptionMessages || (FileExceptionMessages = {})); +/** + * A File object is created from your {@link Bucket} object using + * {@link Bucket#file}. + * + * @class + */ +class File extends ServiceObject { + /** + * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share objects with other + * users and allow other users to access your buckets and objects. + * + * An ACL consists of one or more entries, where each entry grants permissions + * to an entity. Permissions define the actions that can be performed against + * an object or bucket (for example, `READ` or `WRITE`); the entity defines + * who the permission applies to (for example, a specific user or group of + * users). + * + * The `acl` object on a File instance provides methods to get you a list of + * the ACLs defined on your bucket, as well as set, update, and delete them. + * + * See {@link http://goo.gl/6qBBPO| About Access Control lists} + * + * @name File#acl + * @mixes Acl + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * //- + * // Make a file publicly readable. + * //- + * const options = { + * entity: 'allUsers', + * role: storage.acl.READER_ROLE + * }; + * + * file.acl.add(options, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.acl.add(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + /** + * The API-formatted resource description of the file. + * + * Note: This is not guaranteed to be up-to-date when accessed. To get the + * latest record, call the `getMetadata()` method. + * + * @name File#metadata + * @type {object} + */ + /** + * The file's name. + * @name File#name + * @type {string} + */ + /** + * @callback Crc32cGeneratorToStringCallback + * A method returning the CRC32C as a base64-encoded string. + * + * @returns {string} + * + * @example + * Hashing the string 'data' should return 'rth90Q==' + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.toString(); // 'rth90Q==' + * ``` + **/ + /** + * @callback Crc32cGeneratorValidateCallback + * A method validating a base64-encoded CRC32C string. + * + * @param {string} [value] base64-encoded CRC32C string to validate + * @returns {boolean} + * + * @example + * Should return `true` if the value matches, `false` otherwise + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.validate('DkjKuA=='); // false + * crc32c.validate('rth90Q=='); // true + * ``` + **/ + /** + * @callback Crc32cGeneratorUpdateCallback + * A method for passing `Buffer`s for CRC32C generation. + * + * @param {Buffer} [data] data to update CRC32C value with + * @returns {undefined} + * + * @example + * Hashing buffers from 'some ' and 'text\n' + * + * ```js + * const buffer1 = Buffer.from('some '); + * crc32c.update(buffer1); + * + * const buffer2 = Buffer.from('text\n'); + * crc32c.update(buffer2); + * + * crc32c.toString(); // 'DkjKuA==' + * ``` + **/ + /** + * @typedef {object} CRC32CValidator + * @property {Crc32cGeneratorToStringCallback} + * @property {Crc32cGeneratorValidateCallback} + * @property {Crc32cGeneratorUpdateCallback} + */ + /** + * @callback Crc32cGeneratorCallback + * @returns {CRC32CValidator} + */ + /** + * @typedef {object} FileOptions Options passed to the File constructor. + * @property {string} [encryptionKey] A custom encryption key. + * @property {number} [generation] Generation to scope the file to. + * @property {string} [kmsKeyName] Cloud KMS Key used to encrypt this + * object, if the object is encrypted by such a key. Limited availability; + * usable only by enabled projects. + * @property {string} [userProject] The ID of the project which will be + * billed for all requests made from File object. + * @property {Crc32cGeneratorCallback} [callback] A function that generates a CRC32C Validator. Defaults to {@link CRC32C} + */ + /** + * Constructs a file object. + * + * @param {Bucket} bucket The Bucket instance this file is + * attached to. + * @param {string} name The name of the remote file. + * @param {FileOptions} [options] Configuration options. + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * ``` + */ + constructor(bucket, name, options = {}) { + var _a, _b; + const requestQueryObject = {}; + let generation; + if (options.generation !== null) { + if (typeof options.generation === 'string') { + generation = Number(options.generation); + } + else { + generation = options.generation; + } + if (!isNaN(generation)) { + requestQueryObject.generation = generation; + } + } + Object.assign(requestQueryObject, options.preconditionOpts); + const userProject = options.userProject || bucket.userProject; + if (typeof userProject === 'string') { + requestQueryObject.userProject = userProject; + } + const methods = { + /** + * @typedef {array} DeleteFileResponse + * @property {object} 0 The full API response. + */ + /** + * @callback DeleteFileCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Delete the file. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/delete| Objects: delete API Documentation} + * + * @method File#delete + * @param {object} [options] Configuration options. + * @param {boolean} [options.ignoreNotFound = false] Ignore an error if + * the file does not exist. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {DeleteFileCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * file.delete(function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.delete().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example include:samples/files.js + * region_tag:storage_delete_file + * Another example: + */ + delete: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {array} FileExistsResponse + * @property {boolean} 0 Whether the {@link File} exists. + */ + /** + * @callback FileExistsCallback + * @param {?Error} err Request error, if any. + * @param {boolean} exists Whether the {@link File} exists. + */ + /** + * Check if the file exists. + * + * @method File#exists + * @param {options} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {FileExistsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * file.exists(function(err, exists) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.exists().then(function(data) { + * const exists = data[0]; + * }); + * ``` + */ + exists: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {array} GetFileResponse + * @property {File} 0 The {@link File}. + * @property {object} 1 The full API response. + */ + /** + * @callback GetFileCallback + * @param {?Error} err Request error, if any. + * @param {File} file The {@link File}. + * @param {object} apiResponse The full API response. + */ + /** + * Get a file object and its metadata if it exists. + * + * @method File#get + * @param {options} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {number} [options.generation] The generation number to get + * @param {string} [options.restoreToken] If this is a soft-deleted object in an HNS-enabled bucket, returns the restore token which will + * be necessary to restore it if there's a name conflict with another object. + * @param {boolean} [options.softDeleted] If true, returns the soft-deleted object. + Object `generation` is required if `softDeleted` is set to True. + * @param {GetFileCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * file.get(function(err, file, apiResponse) { + * // file.metadata` has been populated. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.get().then(function(data) { + * const file = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + get: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {array} GetFileMetadataResponse + * @property {object} 0 The {@link File} metadata. + * @property {object} 1 The full API response. + */ + /** + * @callback GetFileMetadataCallback + * @param {?Error} err Request error, if any. + * @param {object} metadata The {@link File} metadata. + * @param {object} apiResponse The full API response. + */ + /** + * Get the file's metadata. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/get| Objects: get API Documentation} + * + * @method File#getMetadata + * @param {object} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetFileMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * file.getMetadata(function(err, metadata, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.getMetadata().then(function(data) { + * const metadata = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/files.js + * region_tag:storage_get_metadata + * Another example: + */ + getMetadata: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {object} SetFileMetadataOptions Configuration options for File#setMetadata(). + * @param {string} [userProject] The ID of the project which will be billed for the request. + */ + /** + * @callback SetFileMetadataCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} SetFileMetadataResponse + * @property {object} 0 The full API response. + */ + /** + * Merge the given metadata with the current remote file's metadata. This + * will set metadata if it was previously unset or update previously set + * metadata. To unset previously set metadata, set its value to null. + * + * You can set custom key/value pairs in the metadata key of the given + * object, however the other properties outside of this object must adhere + * to the {@link https://goo.gl/BOnnCK| official API documentation}. + * + * + * See the examples below for more information. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/patch| Objects: patch API Documentation} + * + * @method File#setMetadata + * @param {object} [metadata] The metadata you wish to update. + * @param {SetFileMetadataOptions} [options] Configuration options. + * @param {SetFileMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * const metadata = { + * contentType: 'application/x-font-ttf', + * metadata: { + * my: 'custom', + * properties: 'go here' + * } + * }; + * + * file.setMetadata(metadata, function(err, apiResponse) {}); + * + * // Assuming current metadata = { hello: 'world', unsetMe: 'will do' } + * file.setMetadata({ + * metadata: { + * abc: '123', // will be set. + * unsetMe: null, // will be unset (deleted). + * hello: 'goodbye' // will be updated from 'world' to 'goodbye'. + * } + * }, function(err, apiResponse) { + * // metadata should now be { abc: '123', hello: 'goodbye' } + * }); + * + * //- + * // Set a temporary hold on this file from its bucket's retention period + * // configuration. + * // + * file.setMetadata({ + * temporaryHold: true + * }, function(err, apiResponse) {}); + * + * //- + * // Alternatively, you may set a temporary hold. This will follow the + * // same behavior as an event-based hold, with the exception that the + * // bucket's retention policy will not renew for this file from the time + * // the hold is released. + * //- + * file.setMetadata({ + * eventBasedHold: true + * }, function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.setMetadata(metadata).then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + setMetadata: { + reqOpts: { + qs: requestQueryObject, + }, + }, + }; + super({ + parent: bucket, + baseUrl: '/o', + id: encodeURIComponent(name), + methods, + }); + _File_instances.add(this); + this.bucket = bucket; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.storage = bucket.parent; + // @TODO Can this duplicate code from above be avoided? + if (options.generation !== null) { + let generation; + if (typeof options.generation === 'string') { + generation = Number(options.generation); + } + else { + generation = options.generation; + } + if (!isNaN(generation)) { + this.generation = generation; + } + } + this.kmsKeyName = options.kmsKeyName; + this.userProject = userProject; + this.name = name; + if (options.encryptionKey) { + this.setEncryptionKey(options.encryptionKey); + } + this.acl = new Acl({ + request: this.request.bind(this), + pathPrefix: '/acl', + }); + this.crc32cGenerator = + options.crc32cGenerator || this.bucket.crc32cGenerator; + this.instanceRetryValue = (_b = (_a = this.storage) === null || _a === void 0 ? void 0 : _a.retryOptions) === null || _b === void 0 ? void 0 : _b.autoRetry; + this.instancePreconditionOpts = options === null || options === void 0 ? void 0 : options.preconditionOpts; + } + /** + * The object's Cloud Storage URI (`gs://`) + * + * @example + * ```ts + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const file = bucket.file('image.png'); + * + * // `gs://my-bucket/image.png` + * const href = file.cloudStorageURI.href; + * ``` + */ + get cloudStorageURI() { + const uri = this.bucket.cloudStorageURI; + uri.pathname = this.name; + return uri; + } + /** + * A helper method for determining if a request should be retried based on preconditions. + * This should only be used for methods where the idempotency is determined by + * `ifGenerationMatch` + * @private + * + * A request should not be retried under the following conditions: + * - if precondition option `ifGenerationMatch` is not set OR + * - if `idempotencyStrategy` is set to `RetryNever` + */ + shouldRetryBasedOnPreconditionAndIdempotencyStrat(options) { + var _a; + return !(((options === null || options === void 0 ? void 0 : options.ifGenerationMatch) === undefined && + ((_a = this.instancePreconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) === undefined && + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryConditional) || + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryNever); + } + /** + * @typedef {array} CopyResponse + * @property {File} 0 The copied {@link File}. + * @property {object} 1 The full API response. + */ + /** + * @callback CopyCallback + * @param {?Error} err Request error, if any. + * @param {File} copiedFile The copied {@link File}. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {object} CopyOptions Configuration options for File#copy(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}. + * @property {string} [cacheControl] The cacheControl setting for the new file. + * @property {string} [contentEncoding] The contentEncoding setting for the new file. + * @property {string} [contentType] The contentType setting for the new file. + * @property {string} [destinationKmsKeyName] Resource name of the Cloud + * KMS key, of the form + * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`, + * that will be used to encrypt the object. Overwrites the object + * metadata's `kms_key_name` value, if any. + * @property {Metadata} [metadata] Metadata to specify on the copied file. + * @property {string} [predefinedAcl] Set the ACL for the new file. + * @property {string} [token] A previously-returned `rewriteToken` from an + * unfinished rewrite request. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * Copy this file to another file. By default, this will copy the file to the + * same bucket, but you can choose to copy it to another Bucket by providing + * a Bucket or File object or a URL starting with "gs://". + * The generation of the file will not be preserved. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/rewrite| Objects: rewrite API Documentation} + * + * @throws {Error} If the destination file is not provided. + * + * @param {string|Bucket|File} destination Destination file. + * @param {CopyOptions} [options] Configuration options. See an + * @param {CopyCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // You can pass in a variety of types for the destination. + * // + * // For all of the below examples, assume we are working with the following + * // Bucket and File objects. + * //- + * const bucket = storage.bucket('my-bucket'); + * const file = bucket.file('my-image.png'); + * + * //- + * // If you pass in a string for the destination, the file is copied to its + * // current bucket, under the new name provided. + * //- + * file.copy('my-image-copy.png', function(err, copiedFile, apiResponse) { + * // `my-bucket` now contains: + * // - "my-image.png" + * // - "my-image-copy.png" + * + * // `copiedFile` is an instance of a File object that refers to your new + * // file. + * }); + * + * //- + * // If you pass in a string starting with "gs://" for the destination, the + * // file is copied to the other bucket and under the new name provided. + * //- + * const newLocation = 'gs://another-bucket/my-image-copy.png'; + * file.copy(newLocation, function(err, copiedFile, apiResponse) { + * // `my-bucket` still contains: + * // - "my-image.png" + * // + * // `another-bucket` now contains: + * // - "my-image-copy.png" + * + * // `copiedFile` is an instance of a File object that refers to your new + * // file. + * }); + * + * //- + * // If you pass in a Bucket object, the file will be copied to that bucket + * // using the same name. + * //- + * const anotherBucket = storage.bucket('another-bucket'); + * file.copy(anotherBucket, function(err, copiedFile, apiResponse) { + * // `my-bucket` still contains: + * // - "my-image.png" + * // + * // `another-bucket` now contains: + * // - "my-image.png" + * + * // `copiedFile` is an instance of a File object that refers to your new + * // file. + * }); + * + * //- + * // If you pass in a File object, you have complete control over the new + * // bucket and filename. + * //- + * const anotherFile = anotherBucket.file('my-awesome-image.png'); + * file.copy(anotherFile, function(err, copiedFile, apiResponse) { + * // `my-bucket` still contains: + * // - "my-image.png" + * // + * // `another-bucket` now contains: + * // - "my-awesome-image.png" + * + * // Note: + * // The `copiedFile` parameter is equal to `anotherFile`. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.copy(newLocation).then(function(data) { + * const newFile = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/files.js + * region_tag:storage_copy_file + * Another example: + */ + copy(destination, optionsOrCallback, callback) { + var _a, _b; + const noDestinationError = new Error(FileExceptionMessages.DESTINATION_NO_NAME); + if (!destination) { + throw noDestinationError; + } + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else if (optionsOrCallback) { + options = { ...optionsOrCallback }; + } + callback = callback || util.noop; + let destBucket; + let destName; + let newFile; + if (typeof destination === 'string') { + const parsedDestination = GS_URL_REGEXP.exec(destination); + if (parsedDestination !== null && parsedDestination.length === 3) { + destBucket = this.storage.bucket(parsedDestination[1]); + destName = parsedDestination[2]; + } + else { + destBucket = this.bucket; + destName = destination; + } + } + else if (destination instanceof Bucket) { + destBucket = destination; + destName = this.name; + } + else if (destination instanceof File) { + destBucket = destination.bucket; + destName = destination.name; + newFile = destination; + } + else { + throw noDestinationError; + } + const query = {}; + if (this.generation !== undefined) { + query.sourceGeneration = this.generation; + } + if (options.token !== undefined) { + query.rewriteToken = options.token; + } + if (options.userProject !== undefined) { + query.userProject = options.userProject; + delete options.userProject; + } + if (options.predefinedAcl !== undefined) { + query.destinationPredefinedAcl = options.predefinedAcl; + delete options.predefinedAcl; + } + newFile = newFile || destBucket.file(destName); + const headers = {}; + if (this.encryptionKey !== undefined) { + headers['x-goog-copy-source-encryption-algorithm'] = 'AES256'; + headers['x-goog-copy-source-encryption-key'] = this.encryptionKeyBase64; + headers['x-goog-copy-source-encryption-key-sha256'] = + this.encryptionKeyHash; + } + if (newFile.encryptionKey !== undefined) { + this.setEncryptionKey(newFile.encryptionKey); + } + else if (options.destinationKmsKeyName !== undefined) { + query.destinationKmsKeyName = options.destinationKmsKeyName; + delete options.destinationKmsKeyName; + } + else if (newFile.kmsKeyName !== undefined) { + query.destinationKmsKeyName = newFile.kmsKeyName; + } + if (query.destinationKmsKeyName) { + this.kmsKeyName = query.destinationKmsKeyName; + const keyIndex = this.interceptors.indexOf(this.encryptionKeyInterceptor); + if (keyIndex > -1) { + this.interceptors.splice(keyIndex, 1); + } + } + if (!this.shouldRetryBasedOnPreconditionAndIdempotencyStrat(options === null || options === void 0 ? void 0 : options.preconditionOpts)) { + this.storage.retryOptions.autoRetry = false; + } + if (((_a = options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) !== undefined) { + query.ifGenerationMatch = (_b = options.preconditionOpts) === null || _b === void 0 ? void 0 : _b.ifGenerationMatch; + delete options.preconditionOpts; + } + this.request({ + method: 'POST', + uri: `/rewriteTo/b/${destBucket.name}/o/${encodeURIComponent(newFile.name)}`, + qs: query, + json: options, + headers, + }, (err, resp) => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + if (err) { + callback(err, null, resp); + return; + } + if (resp.rewriteToken) { + const options = { + token: resp.rewriteToken, + }; + if (query.userProject) { + options.userProject = query.userProject; + } + if (query.destinationKmsKeyName) { + options.destinationKmsKeyName = query.destinationKmsKeyName; + } + this.copy(newFile, options, callback); + return; + } + callback(null, newFile, resp); + }); + } + /** + * @typedef {object} CreateReadStreamOptions Configuration options for File#createReadStream. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {string|boolean} [validation] Possible values: `"md5"`, + * `"crc32c"`, or `false`. By default, data integrity is validated with a + * CRC32c checksum. You may use MD5 if preferred, but that hash is not + * supported for composite objects. An error will be raised if MD5 is + * specified but is not available. You may also choose to skip validation + * completely, however this is **not recommended**. + * @property {number} [start] A byte offset to begin the file's download + * from. Default is 0. NOTE: Byte ranges are inclusive; that is, + * `options.start = 0` and `options.end = 999` represent the first 1000 + * bytes in a file or object. NOTE: when specifying a byte range, data + * integrity is not available. + * @property {number} [end] A byte offset to stop reading the file at. + * NOTE: Byte ranges are inclusive; that is, `options.start = 0` and + * `options.end = 999` represent the first 1000 bytes in a file or object. + * NOTE: when specifying a byte range, data integrity is not available. + * @property {boolean} [decompress=true] Disable auto decompression of the + * received data. By default this option is set to `true`. + * Applicable in cases where the data was uploaded with + * `gzip: true` option. See {@link File#createWriteStream}. + */ + /** + * Create a readable stream to read the contents of the remote file. It can be + * piped to a writable stream or listened to for 'data' events to read a + * file's contents. + * + * In the unlikely event there is a mismatch between what you downloaded and + * the version in your Bucket, your error handler will receive an error with + * code "CONTENT_DOWNLOAD_MISMATCH". If you receive this error, the best + * recourse is to try downloading the file again. + * + * NOTE: Readable streams will emit the `end` event when the file is fully + * downloaded. + * + * @param {CreateReadStreamOptions} [options] Configuration options. + * @returns {ReadableStream} + * + * @example + * ``` + * //- + * //

Downloading a File

+ * // + * // The example below demonstrates how we can reference a remote file, then + * // pipe its contents to a local file. This is effectively creating a local + * // backup of your remote data. + * //- + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * const fs = require('fs'); + * const remoteFile = bucket.file('image.png'); + * const localFilename = '/Users/stephen/Photos/image.png'; + * + * remoteFile.createReadStream() + * .on('error', function(err) {}) + * .on('response', function(response) { + * // Server connected and responded with the specified status and headers. + * }) + * .on('end', function() { + * // The file is fully downloaded. + * }) + * .pipe(fs.createWriteStream(localFilename)); + * + * //- + * // To limit the downloaded data to only a byte range, pass an options + * // object. + * //- + * const logFile = myBucket.file('access_log'); + * logFile.createReadStream({ + * start: 10000, + * end: 20000 + * }) + * .on('error', function(err) {}) + * .pipe(fs.createWriteStream('/Users/stephen/logfile.txt')); + * + * //- + * // To read a tail byte range, specify only `options.end` as a negative + * // number. + * //- + * const logFile = myBucket.file('access_log'); + * logFile.createReadStream({ + * end: -100 + * }) + * .on('error', function(err) {}) + * .pipe(fs.createWriteStream('/Users/stephen/logfile.txt')); + * ``` + */ + createReadStream(options = {}) { + options = Object.assign({ decompress: true }, options); + const rangeRequest = typeof options.start === 'number' || typeof options.end === 'number'; + const tailRequest = options.end < 0; + let validateStream = undefined; + let request = undefined; + const throughStream = new PassThroughShim(); + let crc32c = true; + let md5 = false; + if (typeof options.validation === 'string') { + const value = options.validation.toLowerCase().trim(); + crc32c = value === 'crc32c'; + md5 = value === 'md5'; + } + else if (options.validation === false) { + crc32c = false; + } + const shouldRunValidation = !rangeRequest && (crc32c || md5); + if (rangeRequest) { + if (typeof options.validation === 'string' || + options.validation === true) { + throw new Error(FileExceptionMessages.INVALID_VALIDATION_FILE_RANGE); + } + // Range requests can't receive data integrity checks. + crc32c = false; + md5 = false; + } + const onComplete = (err) => { + if (err) { + // There is an issue with node-fetch 2.x that if the stream errors the underlying socket connection is not closed. + // This causes a memory leak, so cleanup the sockets manually here by destroying the agent. + if (request === null || request === void 0 ? void 0 : request.agent) { + request.agent.destroy(); + } + throughStream.destroy(err); + } + }; + // We listen to the response event from the request stream so that we + // can... + // + // 1) Intercept any data from going to the user if an error occurred. + // 2) Calculate the hashes from the http.IncomingMessage response + // stream, + // which will return the bytes from the source without decompressing + // gzip'd content. We then send it through decompressed, if + // applicable, to the user. + const onResponse = (err, _body, rawResponseStream) => { + if (err) { + // Get error message from the body. + this.getBufferFromReadable(rawResponseStream).then(body => { + err.message = body.toString('utf8'); + throughStream.destroy(err); + }); + return; + } + request = rawResponseStream.request; + const headers = rawResponseStream.toJSON().headers; + const isCompressed = headers['content-encoding'] === 'gzip'; + const hashes = {}; + // The object is safe to validate if: + // 1. It was stored gzip and returned to us gzip OR + // 2. It was never stored as gzip + const safeToValidate = (headers['x-goog-stored-content-encoding'] === 'gzip' && + isCompressed) || + headers['x-goog-stored-content-encoding'] === 'identity'; + const transformStreams = []; + if (shouldRunValidation) { + // The x-goog-hash header should be set with a crc32c and md5 hash. + // ex: headers['x-goog-hash'] = 'crc32c=xxxx,md5=xxxx' + if (typeof headers['x-goog-hash'] === 'string') { + headers['x-goog-hash'] + .split(',') + .forEach((hashKeyValPair) => { + const delimiterIndex = hashKeyValPair.indexOf('='); + const hashType = hashKeyValPair.substring(0, delimiterIndex); + const hashValue = hashKeyValPair.substring(delimiterIndex + 1); + hashes[hashType] = hashValue; + }); + } + validateStream = new HashStreamValidator({ + crc32c, + md5, + crc32cGenerator: this.crc32cGenerator, + crc32cExpected: hashes.crc32c, + md5Expected: hashes.md5, + }); + } + if (md5 && !hashes.md5) { + const hashError = new RequestError(FileExceptionMessages.MD5_NOT_AVAILABLE); + hashError.code = 'MD5_NOT_AVAILABLE'; + throughStream.destroy(hashError); + return; + } + if (safeToValidate && shouldRunValidation && validateStream) { + transformStreams.push(validateStream); + } + if (isCompressed && options.decompress) { + transformStreams.push(zlib.createGunzip()); + } + pipeline(rawResponseStream, ...transformStreams, throughStream, onComplete); + }; + // Authenticate the request, then pipe the remote API request to the stream + // returned to the user. + const makeRequest = () => { + const query = { alt: 'media' }; + if (this.generation) { + query.generation = this.generation; + } + if (options.userProject) { + query.userProject = options.userProject; + } + const headers = { + 'Accept-Encoding': 'gzip', + 'Cache-Control': 'no-store', + }; + if (rangeRequest) { + const start = typeof options.start === 'number' ? options.start : '0'; + const end = typeof options.end === 'number' ? options.end : ''; + headers.Range = `bytes=${tailRequest ? end : `${start}-${end}`}`; + } + const reqOpts = { + uri: '', + headers, + qs: query, + }; + if (options[GCCL_GCS_CMD_KEY]) { + reqOpts[GCCL_GCS_CMD_KEY] = options[GCCL_GCS_CMD_KEY]; + } + this.requestStream(reqOpts) + .on('error', err => { + throughStream.destroy(err); + }) + .on('response', res => { + throughStream.emit('response', res); + util.handleResp(null, res, null, onResponse); + }) + .resume(); + }; + throughStream.on('reading', makeRequest); + return throughStream; + } + /** + * @callback CreateResumableUploadCallback + * @param {?Error} err Request error, if any. + * @param {string} uri The resumable upload's unique session URI. + */ + /** + * @typedef {array} CreateResumableUploadResponse + * @property {string} 0 The resumable upload's unique session URI. + */ + /** + * @typedef {object} CreateResumableUploadOptions + * @property {object} [metadata] Metadata to set on the file. + * @property {number} [offset] The starting byte of the upload stream for resuming an interrupted upload. + * @property {string} [origin] Origin header to set for the upload. + * @property {string} [predefinedAcl] Apply a predefined set of access + * controls to this object. + * + * Acceptable values are: + * - **`authenticatedRead`** - Object owner gets `OWNER` access, and + * `allAuthenticatedUsers` get `READER` access. + * + * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and + * project team owners get `OWNER` access. + * + * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project + * team owners get `READER` access. + * + * - **`private`** - Object owner gets `OWNER` access. + * + * - **`projectPrivate`** - Object owner gets `OWNER` access, and project + * team members get access according to their roles. + * + * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers` + * get `READER` access. + * @property {boolean} [private] Make the uploaded file private. (Alias for + * `options.predefinedAcl = 'private'`) + * @property {boolean} [public] Make the uploaded file public. (Alias for + * `options.predefinedAcl = 'publicRead'`) + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {string} [chunkSize] Create a separate request per chunk. This + * value is in bytes and should be a multiple of 256 KiB (2^18). + * {@link https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload| We recommend using at least 8 MiB for the chunk size.} + */ + /** + * Create a unique resumable upload session URI. This is the first step when + * performing a resumable upload. + * + * See the {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload| Resumable upload guide} + * for more on how the entire process works. + * + *

Note

+ * + * If you are just looking to perform a resumable upload without worrying + * about any of the details, see {@link File#createWriteStream}. Resumable + * uploads are performed by default. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload| Resumable upload guide} + * + * @param {CreateResumableUploadOptions} [options] Configuration options. + * @param {CreateResumableUploadCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * file.createResumableUpload(function(err, uri) { + * if (!err) { + * // `uri` can be used to PUT data to. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.createResumableUpload().then(function(data) { + * const uri = data[0]; + * }); + * ``` + */ + createResumableUpload(optionsOrCallback, callback) { + var _a, _b; + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + const retryOptions = this.storage.retryOptions; + if ((((_a = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) === undefined && + ((_b = this.instancePreconditionOpts) === null || _b === void 0 ? void 0 : _b.ifGenerationMatch) === undefined && + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryConditional) || + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryNever) { + retryOptions.autoRetry = false; + } + resumableUpload.createURI({ + authClient: this.storage.authClient, + apiEndpoint: this.storage.apiEndpoint, + bucket: this.bucket.name, + customRequestOptions: this.getRequestInterceptors().reduce((reqOpts, interceptorFn) => interceptorFn(reqOpts), {}), + file: this.name, + generation: this.generation, + key: this.encryptionKey, + kmsKeyName: this.kmsKeyName, + metadata: options.metadata, + offset: options.offset, + origin: options.origin, + predefinedAcl: options.predefinedAcl, + private: options.private, + public: options.public, + userProject: options.userProject || this.userProject, + retryOptions: retryOptions, + params: (options === null || options === void 0 ? void 0 : options.preconditionOpts) || this.instancePreconditionOpts, + universeDomain: this.bucket.storage.universeDomain, + useAuthWithCustomEndpoint: this.storage.useAuthWithCustomEndpoint, + [GCCL_GCS_CMD_KEY]: options[GCCL_GCS_CMD_KEY], + }, callback); + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + } + /** + * @typedef {object} CreateWriteStreamOptions Configuration options for File#createWriteStream(). + * @property {string} [contentType] Alias for + * `options.metadata.contentType`. If set to `auto`, the file name is used + * to determine the contentType. + * @property {string|boolean} [gzip] If true, automatically gzip the file. + * If set to `auto`, the contentType is used to determine if the file + * should be gzipped. This will set `options.metadata.contentEncoding` to + * `gzip` if necessary. + * @property {object} [metadata] See the examples below or + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON| Objects: insert request body} + * for more details. + * @property {number} [offset] The starting byte of the upload stream, for + * resuming an interrupted upload. Defaults to 0. + * @property {string} [predefinedAcl] Apply a predefined set of access + * controls to this object. + * + * Acceptable values are: + * - **`authenticatedRead`** - Object owner gets `OWNER` access, and + * `allAuthenticatedUsers` get `READER` access. + * + * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and + * project team owners get `OWNER` access. + * + * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project + * team owners get `READER` access. + * + * - **`private`** - Object owner gets `OWNER` access. + * + * - **`projectPrivate`** - Object owner gets `OWNER` access, and project + * team members get access according to their roles. + * + * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers` + * get `READER` access. + * @property {boolean} [private] Make the uploaded file private. (Alias for + * `options.predefinedAcl = 'private'`) + * @property {boolean} [public] Make the uploaded file public. (Alias for + * `options.predefinedAcl = 'publicRead'`) + * @property {boolean} [resumable] Force a resumable upload. NOTE: When + * working with streams, the file format and size is unknown until it's + * completely consumed. Because of this, it's best for you to be explicit + * for what makes sense given your input. + * @property {number} [timeout=60000] Set the HTTP request timeout in + * milliseconds. This option is not available for resumable uploads. + * Default: `60000` + * @property {string} [uri] The URI for an already-created resumable + * upload. See {@link File#createResumableUpload}. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {string|boolean} [validation] Possible values: `"md5"`, + * `"crc32c"`, or `false`. By default, data integrity is validated with a + * CRC32c checksum. You may use MD5 if preferred, but that hash is not + * supported for composite objects. An error will be raised if MD5 is + * specified but is not available. You may also choose to skip validation + * completely, however this is **not recommended**. In addition to specifying + * validation type, providing `metadata.crc32c` or `metadata.md5Hash` will + * cause the server to perform validation in addition to client validation. + * NOTE: Validation is automatically skipped for objects that were + * uploaded using the `gzip` option and have already compressed content. + */ + /** + * Create a writable stream to overwrite the contents of the file in your + * bucket. + * + * A File object can also be used to create files for the first time. + * + * Resumable uploads are automatically enabled and must be shut off explicitly + * by setting `options.resumable` to `false`. + * + * + *

+ * There is some overhead when using a resumable upload that can cause + * noticeable performance degradation while uploading a series of small + * files. When uploading files less than 10MB, it is recommended that the + * resumable feature is disabled. + *

+ * + * NOTE: Writable streams will emit the `finish` event when the file is fully + * uploaded. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload Upload Options (Simple or Resumable)} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert Objects: insert API Documentation} + * + * @param {CreateWriteStreamOptions} [options] Configuration options. + * @returns {WritableStream} + * + * @example + * ``` + * const fs = require('fs'); + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * //- + * //

Uploading a File

+ * // + * // Now, consider a case where we want to upload a file to your bucket. You + * // have the option of using {@link Bucket#upload}, but that is just + * // a convenience method which will do the following. + * //- + * fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg') + * .pipe(file.createWriteStream()) + * .on('error', function(err) {}) + * .on('finish', function() { + * // The file upload is complete. + * }); + * + * //- + * //

Uploading a File with gzip compression

+ * //- + * fs.createReadStream('/Users/stephen/site/index.html') + * .pipe(file.createWriteStream({ gzip: true })) + * .on('error', function(err) {}) + * .on('finish', function() { + * // The file upload is complete. + * }); + * + * //- + * // Downloading the file with `createReadStream` will automatically decode + * // the file. + * //- + * + * //- + * //

Uploading a File with Metadata

+ * // + * // One last case you may run into is when you want to upload a file to your + * // bucket and set its metadata at the same time. Like above, you can use + * // {@link Bucket#upload} to do this, which is just a wrapper around + * // the following. + * //- + * fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg') + * .pipe(file.createWriteStream({ + * metadata: { + * contentType: 'image/jpeg', + * metadata: { + * custom: 'metadata' + * } + * } + * })) + * .on('error', function(err) {}) + * .on('finish', function() { + * // The file upload is complete. + * }); + * ``` + * + * //- + * //

Continuing a Resumable Upload

+ * // + * // One can capture a `uri` from a resumable upload to reuse later. + * // Additionally, for validation, one can also capture and pass `crc32c`. + * //- + * let uri: string | undefined = undefined; + * let resumeCRC32C: string | undefined = undefined; + * + * fs.createWriteStream() + * .on('uri', link => {uri = link}) + * .on('crc32', crc32c => {resumeCRC32C = crc32c}); + * + * // later... + * fs.createWriteStream({uri, resumeCRC32C}); + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + createWriteStream(options = {}) { + var _a; + (_a = options.metadata) !== null && _a !== void 0 ? _a : (options.metadata = {}); + if (options.contentType) { + options.metadata.contentType = options.contentType; + } + if (!options.metadata.contentType || + options.metadata.contentType === 'auto') { + const detectedContentType = mime.getType(this.name); + if (detectedContentType) { + options.metadata.contentType = detectedContentType; + } + } + let gzip = options.gzip; + if (gzip === 'auto') { + gzip = COMPRESSIBLE_MIME_REGEX.test(options.metadata.contentType || ''); + } + if (gzip) { + options.metadata.contentEncoding = 'gzip'; + } + let crc32c = true; + let md5 = false; + if (typeof options.validation === 'string') { + options.validation = options.validation.toLowerCase(); + crc32c = options.validation === 'crc32c'; + md5 = options.validation === 'md5'; + } + else if (options.validation === false) { + crc32c = false; + md5 = false; + } + if (options.offset) { + if (md5) { + throw new RangeError(FileExceptionMessages.MD5_RESUMED_UPLOAD); + } + if (crc32c && !options.isPartialUpload && !options.resumeCRC32C) { + throw new RangeError(FileExceptionMessages.MISSING_RESUME_CRC32C_FINAL_UPLOAD); + } + } + /** + * A callback for determining when the underlying pipeline is complete. + * It's possible the pipeline callback could error before the write stream + * calls `final` so by default this will destroy the write stream unless the + * write stream sets this callback via its `final` handler. + * @param error An optional error + */ + let pipelineCallback = error => { + writeStream.destroy(error || undefined); + }; + // A stream for consumer to write to + const writeStream = new Writable({ + final(cb) { + // Set the pipeline callback to this callback so the pipeline's results + // can be populated to the consumer + pipelineCallback = cb; + emitStream.end(); + }, + write(chunk, encoding, cb) { + emitStream.write(chunk, encoding, cb); + }, + }); + // If the write stream, which is returned to the caller, catches an error we need to make sure that + // at least one of the streams in the pipeline below gets notified so that they + // all get cleaned up / destroyed. + writeStream.once('error', e => { + emitStream.destroy(e); + }); + // If the write stream is closed, cleanup the pipeline below by calling destroy on one of the streams. + writeStream.once('close', () => { + emitStream.destroy(); + }); + const transformStreams = []; + if (gzip) { + transformStreams.push(zlib.createGzip()); + } + const emitStream = new PassThroughShim(); + // If `writeStream` is destroyed before the `writing` event, `emitStream` will not have any listeners. This prevents an unhandled error. + const noop = () => { }; + emitStream.on('error', noop); + let hashCalculatingStream = null; + if (crc32c || md5) { + const crc32cInstance = options.resumeCRC32C + ? CRC32C.from(options.resumeCRC32C) + : undefined; + hashCalculatingStream = new HashStreamValidator({ + crc32c, + crc32cInstance, + md5, + crc32cGenerator: this.crc32cGenerator, + updateHashesOnly: true, + }); + transformStreams.push(hashCalculatingStream); + } + const fileWriteStream = duplexify(); + let fileWriteStreamMetadataReceived = false; + // Handing off emitted events to users + emitStream.on('reading', () => writeStream.emit('reading')); + emitStream.on('writing', () => writeStream.emit('writing')); + fileWriteStream.on('uri', evt => writeStream.emit('uri', evt)); + fileWriteStream.on('progress', evt => writeStream.emit('progress', evt)); + fileWriteStream.on('response', resp => writeStream.emit('response', resp)); + fileWriteStream.once('metadata', () => { + fileWriteStreamMetadataReceived = true; + }); + writeStream.once('writing', () => { + if (options.resumable === false) { + this.startSimpleUpload_(fileWriteStream, options); + } + else { + this.startResumableUpload_(fileWriteStream, options); + } + // remove temporary noop listener as we now create a pipeline that handles the errors + emitStream.removeListener('error', noop); + pipeline(emitStream, ...transformStreams, fileWriteStream, async (e) => { + if (e) { + return pipelineCallback(e); + } + // We want to make sure we've received the metadata from the server in order + // to properly validate the object's integrity. Depending on the type of upload, + // the stream could close before the response is returned. + if (!fileWriteStreamMetadataReceived) { + try { + await new Promise((resolve, reject) => { + fileWriteStream.once('metadata', resolve); + fileWriteStream.once('error', reject); + }); + } + catch (e) { + return pipelineCallback(e); + } + } + // Emit the local CRC32C value for future validation, if validation is enabled. + if (hashCalculatingStream === null || hashCalculatingStream === void 0 ? void 0 : hashCalculatingStream.crc32c) { + writeStream.emit('crc32c', hashCalculatingStream.crc32c); + } + try { + // Metadata may not be ready if the upload is a partial upload, + // nothing to validate yet. + const metadataNotReady = options.isPartialUpload && !this.metadata; + if (hashCalculatingStream && !metadataNotReady) { + await __classPrivateFieldGet(this, _File_instances, "m", _File_validateIntegrity).call(this, hashCalculatingStream, { + crc32c, + md5, + }); + } + pipelineCallback(); + } + catch (e) { + pipelineCallback(e); + } + }); + }); + return writeStream; + } + delete(optionsOrCallback, cb) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + cb = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb; + this.disableAutoRetryConditionallyIdempotent_(this.methods.delete, AvailableServiceObjectMethods.delete, options); + super + .delete(options) + .then(resp => cb(null, ...resp)) + .catch(cb) + .finally(() => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + }); + } + /** + * @typedef {array} DownloadResponse + * @property [0] The contents of a File. + */ + /** + * @callback DownloadCallback + * @param err Request error, if any. + * @param contents The contents of a File. + */ + /** + * Convenience method to download a file into memory or to a local + * destination. + * + * @param {object} [options] Configuration options. The arguments match those + * passed to {@link File#createReadStream}. + * @param {string} [options.destination] Local file path to write the file's + * contents to. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {DownloadCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * //- + * // Download a file into memory. The contents will be available as the + * second + * // argument in the demonstration below, `contents`. + * //- + * file.download(function(err, contents) {}); + * + * //- + * // Download a file to a local destination. + * //- + * file.download({ + * destination: '/Users/me/Desktop/file-backup.txt' + * }, function(err) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.download().then(function(data) { + * const contents = data[0]; + * }); + * + * ``` + * @example include:samples/files.js + * region_tag:storage_download_file + * Another example: + * + * @example include:samples/encryption.js + * region_tag:storage_download_encrypted_file + * Example of downloading an encrypted file: + * + * @example include:samples/requesterPays.js + * region_tag:storage_download_file_requester_pays + * Example of downloading a file where the requester pays: + */ + download(optionsOrCallback, cb) { + let options; + if (typeof optionsOrCallback === 'function') { + cb = optionsOrCallback; + options = {}; + } + else { + options = Object.assign({}, optionsOrCallback); + } + let called = false; + const callback = ((...args) => { + if (!called) + cb(...args); + called = true; + }); + const destination = options.destination; + delete options.destination; + if (options.encryptionKey) { + this.setEncryptionKey(options.encryptionKey); + delete options.encryptionKey; + } + const fileStream = this.createReadStream(options); + let receivedData = false; + if (destination) { + fileStream + .on('error', callback) + .once('data', data => { + receivedData = true; + // We know that the file exists the server - now we can truncate/write to a file + const writable = fs.createWriteStream(destination); + writable.write(data); + fileStream + .pipe(writable) + .on('error', (err) => { + callback(err, Buffer.from('')); + }) + .on('finish', () => { + callback(null, data); + }); + }) + .on('end', () => { + // In the case of an empty file no data will be received before the end event fires + if (!receivedData) { + const data = Buffer.alloc(0); + try { + fs.writeFileSync(destination, data); + callback(null, data); + } + catch (e) { + callback(e, data); + } + } + }); + } + else { + this.getBufferFromReadable(fileStream) + .then(contents => callback === null || callback === void 0 ? void 0 : callback(null, contents)) + .catch(callback); + } + } + /** + * The Storage API allows you to use a custom key for server-side encryption. + * + * See {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys} + * + * @param {string|buffer} encryptionKey An AES-256 encryption key. + * @returns {File} + * + * @example + * ``` + * const crypto = require('crypto'); + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const encryptionKey = crypto.randomBytes(32); + * + * const fileWithCustomEncryption = myBucket.file('my-file'); + * fileWithCustomEncryption.setEncryptionKey(encryptionKey); + * + * const fileWithoutCustomEncryption = myBucket.file('my-file'); + * + * fileWithCustomEncryption.save('data', function(err) { + * // Try to download with the File object that hasn't had + * // `setEncryptionKey()` called: + * fileWithoutCustomEncryption.download(function(err) { + * // We will receive an error: + * // err.message === 'Bad Request' + * + * // Try again with the File object we called `setEncryptionKey()` on: + * fileWithCustomEncryption.download(function(err, contents) { + * // contents.toString() === 'data' + * }); + * }); + * }); + * + * ``` + * @example include:samples/encryption.js + * region_tag:storage_upload_encrypted_file + * Example of uploading an encrypted file: + * + * @example include:samples/encryption.js + * region_tag:storage_download_encrypted_file + * Example of downloading an encrypted file: + */ + setEncryptionKey(encryptionKey) { + this.encryptionKey = encryptionKey; + this.encryptionKeyBase64 = Buffer.from(encryptionKey).toString('base64'); + this.encryptionKeyHash = crypto + .createHash('sha256') + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .update(this.encryptionKeyBase64, 'base64') + .digest('base64'); + this.encryptionKeyInterceptor = { + request: reqOpts => { + reqOpts.headers = reqOpts.headers || {}; + reqOpts.headers['x-goog-encryption-algorithm'] = 'AES256'; + reqOpts.headers['x-goog-encryption-key'] = this.encryptionKeyBase64; + reqOpts.headers['x-goog-encryption-key-sha256'] = + this.encryptionKeyHash; + return reqOpts; + }, + }; + this.interceptors.push(this.encryptionKeyInterceptor); + return this; + } + /** + * Gets a reference to a Cloud Storage {@link File} file from the provided URL in string format. + * @param {string} publicUrlOrGsUrl the URL as a string. Must be of the format gs://bucket/file + * or https://storage.googleapis.com/bucket/file. + * @param {Storage} storageInstance an instance of a Storage object. + * @param {FileOptions} [options] Configuration options + * @returns {File} + */ + static from(publicUrlOrGsUrl, storageInstance, options) { + const gsMatches = [...publicUrlOrGsUrl.matchAll(GS_UTIL_URL_REGEX)]; + const httpsMatches = [...publicUrlOrGsUrl.matchAll(HTTPS_PUBLIC_URL_REGEX)]; + if (gsMatches.length > 0) { + const bucket = new Bucket(storageInstance, gsMatches[0][2]); + return new File(bucket, gsMatches[0][3], options); + } + else if (httpsMatches.length > 0) { + const bucket = new Bucket(storageInstance, httpsMatches[0][3]); + return new File(bucket, httpsMatches[0][4], options); + } + else { + throw new Error('URL string must be of format gs://bucket/file or https://storage.googleapis.com/bucket/file'); + } + } + get(optionsOrCallback, cb) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + cb = + typeof optionsOrCallback === 'function' + ? optionsOrCallback + : cb; + super + .get(options) + .then(resp => cb(null, ...resp)) + .catch(cb); + } + /** + * @typedef {array} GetExpirationDateResponse + * @property {date} 0 A Date object representing the earliest time this file's + * retention policy will expire. + */ + /** + * @callback GetExpirationDateCallback + * @param {?Error} err Request error, if any. + * @param {date} expirationDate A Date object representing the earliest time + * this file's retention policy will expire. + */ + /** + * If this bucket has a retention policy defined, use this method to get a + * Date object representing the earliest time this file will expire. + * + * @param {GetExpirationDateCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * file.getExpirationDate(function(err, expirationDate) { + * // expirationDate is a Date object. + * }); + * ``` + */ + getExpirationDate(callback) { + this.getMetadata((err, metadata, apiResponse) => { + if (err) { + callback(err, null, apiResponse); + return; + } + if (!metadata.retentionExpirationTime) { + const error = new Error(FileExceptionMessages.EXPIRATION_TIME_NA); + callback(error, null, apiResponse); + return; + } + callback(null, new Date(metadata.retentionExpirationTime), apiResponse); + }); + } + /** + * @typedef {array} GenerateSignedPostPolicyV2Response + * @property {object} 0 The document policy. + */ + /** + * @callback GenerateSignedPostPolicyV2Callback + * @param {?Error} err Request error, if any. + * @param {object} policy The document policy. + */ + /** + * Get a signed policy document to allow a user to upload data with a POST + * request. + * + * In Google Cloud Platform environments, such as Cloud Functions and App + * Engine, you usually don't provide a `keyFilename` or `credentials` during + * instantiation. In those environments, we call the + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob| signBlob API} + * to create a signed policy. That API requires either the + * `https://www.googleapis.com/auth/iam` or + * `https://www.googleapis.com/auth/cloud-platform` scope, so be sure they are + * enabled. + * + * See {@link https://cloud.google.com/storage/docs/xml-api/post-object-v2| POST Object with the V2 signing process} + * + * @throws {Error} If an expiration timestamp from the past is given. + * @throws {Error} If options.equals has an array with less or more than two + * members. + * @throws {Error} If options.startsWith has an array with less or more than two + * members. + * + * @param {object} options Configuration options. + * @param {array|array[]} [options.equals] Array of request parameters and + * their expected value (e.g. [['$', '']]). Values are + * translated into equality constraints in the conditions field of the + * policy document (e.g. ['eq', '$', '']). If only one + * equality condition is to be specified, options.equals can be a one- + * dimensional array (e.g. ['$', '']). + * @param {*} options.expires - A timestamp when this policy will expire. Any + * value given is passed to `new Date()`. + * @param {array|array[]} [options.startsWith] Array of request parameters and + * their expected prefixes (e.g. [['$', '']). Values are + * translated into starts-with constraints in the conditions field of the + * policy document (e.g. ['starts-with', '$', '']). If only + * one prefix condition is to be specified, options.startsWith can be a + * one- dimensional array (e.g. ['$', '']). + * @param {string} [options.acl] ACL for the object from possibly predefined + * ACLs. + * @param {string} [options.successRedirect] The URL to which the user client + * is redirected if the upload is successful. + * @param {string} [options.successStatus] - The status of the Google Storage + * response if the upload is successful (must be string). + * @param {object} [options.contentLengthRange] + * @param {number} [options.contentLengthRange.min] Minimum value for the + * request's content length. + * @param {number} [options.contentLengthRange.max] Maximum value for the + * request's content length. + * @param {GenerateSignedPostPolicyV2Callback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * const options = { + * equals: ['$Content-Type', 'image/jpeg'], + * expires: '10-25-2022', + * contentLengthRange: { + * min: 0, + * max: 1024 + * } + * }; + * + * file.generateSignedPostPolicyV2(options, function(err, policy) { + * // policy.string: the policy document in plain text. + * // policy.base64: the policy document in base64. + * // policy.signature: the policy signature in base64. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.generateSignedPostPolicyV2(options).then(function(data) { + * const policy = data[0]; + * }); + * ``` + */ + generateSignedPostPolicyV2(optionsOrCallback, cb) { + const args = normalize(optionsOrCallback, cb); + let options = args.options; + const callback = args.callback; + const expires = new Date(options.expires); + if (isNaN(expires.getTime())) { + throw new Error(ExceptionMessages.EXPIRATION_DATE_INVALID); + } + if (expires.valueOf() < Date.now()) { + throw new Error(ExceptionMessages.EXPIRATION_DATE_PAST); + } + options = Object.assign({}, options); + const conditions = [ + ['eq', '$key', this.name], + { + bucket: this.bucket.name, + }, + ]; + if (Array.isArray(options.equals)) { + if (!Array.isArray(options.equals[0])) { + options.equals = [options.equals]; + } + options.equals.forEach(condition => { + if (!Array.isArray(condition) || condition.length !== 2) { + throw new Error(FileExceptionMessages.EQUALS_CONDITION_TWO_ELEMENTS); + } + conditions.push(['eq', condition[0], condition[1]]); + }); + } + if (Array.isArray(options.startsWith)) { + if (!Array.isArray(options.startsWith[0])) { + options.startsWith = [options.startsWith]; + } + options.startsWith.forEach(condition => { + if (!Array.isArray(condition) || condition.length !== 2) { + throw new Error(FileExceptionMessages.STARTS_WITH_TWO_ELEMENTS); + } + conditions.push(['starts-with', condition[0], condition[1]]); + }); + } + if (options.acl) { + conditions.push({ + acl: options.acl, + }); + } + if (options.successRedirect) { + conditions.push({ + success_action_redirect: options.successRedirect, + }); + } + if (options.successStatus) { + conditions.push({ + success_action_status: options.successStatus, + }); + } + if (options.contentLengthRange) { + const min = options.contentLengthRange.min; + const max = options.contentLengthRange.max; + if (typeof min !== 'number' || typeof max !== 'number') { + throw new Error(FileExceptionMessages.CONTENT_LENGTH_RANGE_MIN_MAX); + } + conditions.push(['content-length-range', min, max]); + } + const policy = { + expiration: expires.toISOString(), + conditions, + }; + const policyString = JSON.stringify(policy); + const policyBase64 = Buffer.from(policyString).toString('base64'); + this.storage.authClient.sign(policyBase64, options.signingEndpoint).then(signature => { + callback(null, { + string: policyString, + base64: policyBase64, + signature, + }); + }, err => { + callback(new SigningError(err.message)); + }); + } + /** + * @typedef {object} SignedPostPolicyV4Output + * @property {string} url The request URL. + * @property {object} fields The form fields to include in the POST request. + */ + /** + * @typedef {array} GenerateSignedPostPolicyV4Response + * @property {SignedPostPolicyV4Output} 0 An object containing the request URL and form fields. + */ + /** + * @callback GenerateSignedPostPolicyV4Callback + * @param {?Error} err Request error, if any. + * @param {SignedPostPolicyV4Output} output An object containing the request URL and form fields. + */ + /** + * Get a v4 signed policy document to allow a user to upload data with a POST + * request. + * + * In Google Cloud Platform environments, such as Cloud Functions and App + * Engine, you usually don't provide a `keyFilename` or `credentials` during + * instantiation. In those environments, we call the + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob| signBlob API} + * to create a signed policy. That API requires either the + * `https://www.googleapis.com/auth/iam` or + * `https://www.googleapis.com/auth/cloud-platform` scope, so be sure they are + * enabled. + * + * See {@link https://cloud.google.com/storage/docs/xml-api/post-object#policydocument| Policy Document Reference} + * + * @param {object} options Configuration options. + * @param {Date|number|string} options.expires - A timestamp when this policy will expire. Any + * value given is passed to `new Date()`. + * @param {boolean} [config.virtualHostedStyle=false] Use virtual hosted-style + * URLs ('https://mybucket.storage.googleapis.com/...') instead of path-style + * ('https://storage.googleapis.com/mybucket/...'). Virtual hosted-style URLs + * should generally be preferred instead of path-style URL. + * Currently defaults to `false` for path-style, although this may change in a + * future major-version release. + * @param {string} [config.bucketBoundHostname] The bucket-bound hostname to return in + * the result, e.g. "https://cdn.example.com". + * @param {object} [config.fields] [Form fields]{@link https://cloud.google.com/storage/docs/xml-api/post-object#policydocument} + * to include in the signed policy. Any fields with key beginning with 'x-ignore-' + * will not be included in the policy to be signed. + * @param {object[]} [config.conditions] [Conditions]{@link https://cloud.google.com/storage/docs/authentication/signatures#policy-document} + * to include in the signed policy. All fields given in `config.fields` are + * automatically included in the conditions array, adding the same entry + * in both `fields` and `conditions` will result in duplicate entries. + * + * @param {GenerateSignedPostPolicyV4Callback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * const options = { + * expires: '10-25-2022', + * conditions: [ + * ['eq', '$Content-Type', 'image/jpeg'], + * ['content-length-range', 0, 1024], + * ], + * fields: { + * acl: 'public-read', + * 'x-goog-meta-foo': 'bar', + * 'x-ignore-mykey': 'data' + * } + * }; + * + * file.generateSignedPostPolicyV4(options, function(err, response) { + * // response.url The request URL + * // response.fields The form fields (including the signature) to include + * // to be used to upload objects by HTML forms. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.generateSignedPostPolicyV4(options).then(function(data) { + * const response = data[0]; + * // response.url The request URL + * // response.fields The form fields (including the signature) to include + * // to be used to upload objects by HTML forms. + * }); + * ``` + */ + generateSignedPostPolicyV4(optionsOrCallback, cb) { + const args = normalize(optionsOrCallback, cb); + let options = args.options; + const callback = args.callback; + const expires = new Date(options.expires); + if (isNaN(expires.getTime())) { + throw new Error(ExceptionMessages.EXPIRATION_DATE_INVALID); + } + if (expires.valueOf() < Date.now()) { + throw new Error(ExceptionMessages.EXPIRATION_DATE_PAST); + } + if (expires.valueOf() - Date.now() > SEVEN_DAYS * 1000) { + throw new Error(`Max allowed expiration is seven days (${SEVEN_DAYS} seconds).`); + } + options = Object.assign({}, options); + let fields = Object.assign({}, options.fields); + const now = new Date(); + const nowISO = formatAsUTCISO(now, true); + const todayISO = formatAsUTCISO(now); + const sign = async () => { + const { client_email } = await this.storage.authClient.getCredentials(); + const credential = `${client_email}/${todayISO}/auto/storage/goog4_request`; + fields = { + ...fields, + bucket: this.bucket.name, + key: this.name, + 'x-goog-date': nowISO, + 'x-goog-credential': credential, + 'x-goog-algorithm': 'GOOG4-RSA-SHA256', + }; + const conditions = options.conditions || []; + Object.entries(fields).forEach(([key, value]) => { + if (!key.startsWith('x-ignore-')) { + conditions.push({ [key]: value }); + } + }); + delete fields.bucket; + const expiration = formatAsUTCISO(expires, true, '-', ':'); + const policy = { + conditions, + expiration, + }; + const policyString = unicodeJSONStringify(policy); + const policyBase64 = Buffer.from(policyString).toString('base64'); + try { + const signature = await this.storage.authClient.sign(policyBase64, options.signingEndpoint); + const signatureHex = Buffer.from(signature, 'base64').toString('hex'); + const universe = this.parent.storage.universeDomain; + fields['policy'] = policyBase64; + fields['x-goog-signature'] = signatureHex; + let url; + if (this.storage.customEndpoint) { + url = this.storage.apiEndpoint; + } + else if (options.virtualHostedStyle) { + url = `https://${this.bucket.name}.storage.${universe}/`; + } + else if (options.bucketBoundHostname) { + url = `${options.bucketBoundHostname}/`; + } + else { + url = `https://storage.${universe}/${this.bucket.name}/`; + } + return { + url, + fields, + }; + } + catch (err) { + throw new SigningError(err.message); + } + }; + sign().then(res => callback(null, res), callback); + } + /** + * @typedef {array} GetSignedUrlResponse + * @property {object} 0 The signed URL. + */ + /** + * @callback GetSignedUrlCallback + * @param {?Error} err Request error, if any. + * @param {object} url The signed URL. + */ + /** + * Get a signed URL to allow limited time access to the file. + * + * In Google Cloud Platform environments, such as Cloud Functions and App + * Engine, you usually don't provide a `keyFilename` or `credentials` during + * instantiation. In those environments, we call the + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob| signBlob API} + * to create a signed URL. That API requires either the + * `https://www.googleapis.com/auth/iam` or + * `https://www.googleapis.com/auth/cloud-platform` scope, so be sure they are + * enabled. + * + * See {@link https://cloud.google.com/storage/docs/access-control/signed-urls| Signed URLs Reference} + * + * @throws {Error} if an expiration timestamp from the past is given. + * + * @param {object} config Configuration object. + * @param {string} config.action "read" (HTTP: GET), "write" (HTTP: PUT), or + * "delete" (HTTP: DELETE), "resumable" (HTTP: POST). + * When using "resumable", the header `X-Goog-Resumable: start` has + * to be sent when making a request with the signed URL. + * @param {*} config.expires A timestamp when this link will expire. Any value + * given is passed to `new Date()`. + * Note: 'v4' supports maximum duration of 7 days (604800 seconds) from now. + * See [reference]{@link https://cloud.google.com/storage/docs/access-control/signed-urls#example} + * @param {string} [config.version='v2'] The signing version to use, either + * 'v2' or 'v4'. + * @param {boolean} [config.virtualHostedStyle=false] Use virtual hosted-style + * URLs (e.g. 'https://mybucket.storage.googleapis.com/...') instead of path-style + * (e.g. 'https://storage.googleapis.com/mybucket/...'). Virtual hosted-style URLs + * should generally be preferred instead of path-style URL. + * Currently defaults to `false` for path-style, although this may change in a + * future major-version release. + * @param {string} [config.cname] The cname for this bucket, i.e., + * "https://cdn.example.com". + * @param {string} [config.contentMd5] The MD5 digest value in base64. Just like + * if you provide this, the client must provide this HTTP header with this same + * value in its request, so to if this parameter is not provided here, + * the client must not provide any value for this HTTP header in its request. + * @param {string} [config.contentType] Just like if you provide this, the client + * must provide this HTTP header with this same value in its request, so to if + * this parameter is not provided here, the client must not provide any value + * for this HTTP header in its request. + * @param {object} [config.extensionHeaders] If these headers are used, the + * server will check to make sure that the client provides matching + * values. See {@link https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers| Canonical extension headers} + * for the requirements of this feature, most notably: + * - The header name must be prefixed with `x-goog-` + * - The header name must be all lowercase + * + * Note: Multi-valued header passed as an array in the extensionHeaders + * object is converted into a string, delimited by `,` with + * no space. Requests made using the signed URL will need to + * delimit multi-valued headers using a single `,` as well, or + * else the server will report a mismatched signature. + * @param {object} [config.queryParams] Additional query parameters to include + * in the signed URL. + * @param {string} [config.promptSaveAs] The filename to prompt the user to + * save the file as when the signed url is accessed. This is ignored if + * `config.responseDisposition` is set. + * @param {string} [config.responseDisposition] The + * {@link http://goo.gl/yMWxQV| response-content-disposition parameter} of the + * signed url. + * @param {*} [config.accessibleAt=Date.now()] A timestamp when this link became usable. Any value + * given is passed to `new Date()`. + * Note: Use for 'v4' only. + * @param {string} [config.responseType] The response-content-type parameter + * of the signed url. + * @param {GetSignedUrlCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * //- + * // Generate a URL that allows temporary access to download your file. + * //- + * const request = require('request'); + * + * const config = { + * action: 'read', + * expires: '03-17-2025', + * }; + * + * file.getSignedUrl(config, function(err, url) { + * if (err) { + * console.error(err); + * return; + * } + * + * // The file is now available to read from this URL. + * request(url, function(err, resp) { + * // resp.statusCode = 200 + * }); + * }); + * + * //- + * // Generate a URL that allows temporary access to download your file. + * // Access will begin at accessibleAt and end at expires. + * //- + * const request = require('request'); + * + * const config = { + * action: 'read', + * expires: '03-17-2025', + * accessibleAt: '03-13-2025' + * }; + * + * file.getSignedUrl(config, function(err, url) { + * if (err) { + * console.error(err); + * return; + * } + * + * // The file will be available to read from this URL from 03-13-2025 to 03-17-2025. + * request(url, function(err, resp) { + * // resp.statusCode = 200 + * }); + * }); + * + * //- + * // Generate a URL to allow write permissions. This means anyone with this + * URL + * // can send a POST request with new data that will overwrite the file. + * //- + * file.getSignedUrl({ + * action: 'write', + * expires: '03-17-2025' + * }, function(err, url) { + * if (err) { + * console.error(err); + * return; + * } + * + * // The file is now available to be written to. + * const writeStream = request.put(url); + * writeStream.end('New data'); + * + * writeStream.on('complete', function(resp) { + * // Confirm the new content was saved. + * file.download(function(err, fileContents) { + * console.log('Contents:', fileContents.toString()); + * // Contents: New data + * }); + * }); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.getSignedUrl(config).then(function(data) { + * const url = data[0]; + * }); + * + * ``` + * @example include:samples/files.js + * region_tag:storage_generate_signed_url + * Another example: + */ + getSignedUrl(cfg, callback) { + const method = ActionToHTTPMethod[cfg.action]; + const extensionHeaders = objectKeyToLowercase(cfg.extensionHeaders || {}); + if (cfg.action === 'resumable') { + extensionHeaders['x-goog-resumable'] = 'start'; + } + const queryParams = Object.assign({}, cfg.queryParams); + if (typeof cfg.responseType === 'string') { + queryParams['response-content-type'] = cfg.responseType; + } + if (typeof cfg.promptSaveAs === 'string') { + queryParams['response-content-disposition'] = + 'attachment; filename="' + cfg.promptSaveAs + '"'; + } + if (typeof cfg.responseDisposition === 'string') { + queryParams['response-content-disposition'] = cfg.responseDisposition; + } + if (this.generation) { + queryParams['generation'] = this.generation.toString(); + } + const signConfig = { + method, + expires: cfg.expires, + accessibleAt: cfg.accessibleAt, + extensionHeaders, + queryParams, + contentMd5: cfg.contentMd5, + contentType: cfg.contentType, + host: cfg.host, + }; + if (cfg.cname) { + signConfig.cname = cfg.cname; + } + if (cfg.version) { + signConfig.version = cfg.version; + } + if (cfg.virtualHostedStyle) { + signConfig.virtualHostedStyle = cfg.virtualHostedStyle; + } + if (!this.signer) { + this.signer = new URLSigner(this.storage.authClient, this.bucket, this, this.storage); + } + this.signer + .getSignedUrl(signConfig) + .then(signedUrl => callback(null, signedUrl), callback); + } + /** + * @callback IsPublicCallback + * @param {?Error} err Request error, if any. + * @param {boolean} resp Whether file is public or not. + */ + /** + * @typedef {array} IsPublicResponse + * @property {boolean} 0 Whether file is public or not. + */ + /** + * Check whether this file is public or not by sending + * a HEAD request without credentials. + * No errors from the server indicates that the current + * file is public. + * A 403-Forbidden error {@link https://cloud.google.com/storage/docs/json_api/v1/status-codes#403_Forbidden} + * indicates that file is private. + * Any other non 403 error is propagated to user. + * + * @param {IsPublicCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * //- + * // Check whether the file is publicly accessible. + * //- + * file.isPublic(function(err, resp) { + * if (err) { + * console.error(err); + * return; + * } + * console.log(`the file ${file.id} is public: ${resp}`) ; + * }) + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.isPublic().then(function(data) { + * const resp = data[0]; + * }); + * ``` + */ + isPublic(callback) { + var _a; + // Build any custom headers based on the defined interceptors on the parent + // storage object and this object + const storageInterceptors = ((_a = this.storage) === null || _a === void 0 ? void 0 : _a.interceptors) || []; + const fileInterceptors = this.interceptors || []; + const allInterceptors = storageInterceptors.concat(fileInterceptors); + const headers = allInterceptors.reduce((acc, curInterceptor) => { + const currentHeaders = curInterceptor.request({ + uri: `${this.storage.apiEndpoint}/${this.bucket.name}/${encodeURIComponent(this.name)}`, + }); + Object.assign(acc, currentHeaders.headers); + return acc; + }, {}); + util.makeRequest({ + method: 'GET', + uri: `${this.storage.apiEndpoint}/${this.bucket.name}/${encodeURIComponent(this.name)}`, + headers, + }, { + retryOptions: this.storage.retryOptions, + }, (err) => { + if (err) { + const apiError = err; + if (apiError.code === 403) { + callback(null, false); + } + else { + callback(err); + } + } + else { + callback(null, true); + } + }); + } + /** + * @typedef {object} MakeFilePrivateOptions Configuration options for File#makePrivate(). + * @property {Metadata} [metadata] Define custom metadata properties to define + * along with the operation. + * @property {boolean} [strict] If true, set the file to be private to + * only the owner user. Otherwise, it will be private to the project. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @callback MakeFilePrivateCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} MakeFilePrivateResponse + * @property {object} 0 The full API response. + */ + /** + * Make a file private to the project and remove all other permissions. + * Set `options.strict` to true to make the file private to only the owner. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/patch| Objects: patch API Documentation} + * + * @param {MakeFilePrivateOptions} [options] Configuration options. + * @param {MakeFilePrivateCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * //- + * // Set the file private so only project maintainers can see and modify it. + * //- + * file.makePrivate(function(err) {}); + * + * //- + * // Set the file private so only the owner can see and modify it. + * //- + * file.makePrivate({ strict: true }, function(err) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.makePrivate().then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + makePrivate(optionsOrCallback, callback) { + var _a, _b; + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + const query = { + predefinedAcl: options.strict ? 'private' : 'projectPrivate', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }; + if (((_a = options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifMetagenerationMatch) !== undefined) { + query.ifMetagenerationMatch = + (_b = options.preconditionOpts) === null || _b === void 0 ? void 0 : _b.ifMetagenerationMatch; + delete options.preconditionOpts; + } + if (options.userProject) { + query.userProject = options.userProject; + } + // You aren't allowed to set both predefinedAcl & acl properties on a file, + // so acl must explicitly be nullified, destroying all previous acls on the + // file. + const metadata = { ...options.metadata, acl: null }; + this.setMetadata(metadata, query, callback); + } + /** + * @typedef {array} MakeFilePublicResponse + * @property {object} 0 The full API response. + */ + /** + * @callback MakeFilePublicCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Set a file to be publicly readable and maintain all previous permissions. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/insert| ObjectAccessControls: insert API Documentation} + * + * @param {MakeFilePublicCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * file.makePublic(function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.makePublic().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example include:samples/files.js + * region_tag:storage_make_public + * Another example: + */ + makePublic(callback) { + callback = callback || util.noop; + this.acl.add({ + entity: 'allUsers', + role: 'READER', + }, (err, acl, resp) => { + callback(err, resp); + }); + } + /** + * The public URL of this File + * Use {@link File#makePublic} to enable anonymous access via the returned URL. + * + * @returns {string} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * const file = bucket.file('my-file'); + * + * // publicUrl will be "https://storage.googleapis.com/albums/my-file" + * const publicUrl = file.publicUrl(); + * ``` + */ + publicUrl() { + return `${this.storage.apiEndpoint}/${this.bucket.name}/${encodeURIComponent(this.name)}`; + } + /** + * @typedef {array} MoveFileAtomicResponse + * @property {File} 0 The moved {@link File}. + * @property {object} 1 The full API response. + */ + /** + * @callback MoveFileAtomicCallback + * @param {?Error} err Request error, if any. + * @param {File} movedFile The moved {@link File}. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {object} MoveFileAtomicOptions Configuration options for File#moveFileAtomic(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {object} [preconditionOpts] Precondition options. + * @property {number} [preconditionOpts.ifGenerationMatch] Makes the operation conditional on whether the object's current generation matches the given value. + */ + /** + * Move this file within the same bucket. + * The source object must exist and be a live object. + * The source and destination object IDs must be different. + * Overwriting the destination object is allowed by default, but can be prevented + * using preconditions. + * If the destination path includes non-existent parent folders, they will be created. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/move| Objects: move API Documentation} + * + * @throws {Error} If the destination file is not provided. + * + * @param {string|File} destination Destination file name or File object within the same bucket.. + * @param {MoveFileAtomicOptions} [options] Configuration options. See an + * @param {MoveFileAtomicCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // Assume 'my-bucket' is a bucket. + * //- + * const bucket = storage.bucket('my-bucket'); + * const file = bucket.file('my-image.png'); + * + * //- + * // If you pass in a string for the destination, the file is copied to its + * // current bucket, under the new name provided. + * //- + * file.moveFileAtomic('moved-image.png', function(err, movedFile, apiResponse) { + * // `my-bucket` now contains: + * // - "moved-image.png" + * + * // `movedFile` is an instance of a File object that refers to your new + * // file. + * }); + * + * //- + * // Move the file to a subdirectory, creating parent folders if necessary. + * //- + * file.moveFileAtomic('new-folder/subfolder/moved-image.png', function(err, movedFile, apiResponse) { + * // `my-bucket` now contains: + * // - "new-folder/subfolder/moved-image.png" + * }); + * + * //- + * // Prevent overwriting an existing destination object using preconditions. + * //- + * file.moveFileAtomic('existing-destination.png', { + * preconditionOpts: { + * ifGenerationMatch: 0 // Fails if the destination object exists. + * } + * }, function(err, movedFile, apiResponse) { + * if (err) { + * // Handle the error (e.g., the destination object already exists). + * } else { + * // Move successful. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.moveFileAtomic('moved-image.png).then(function(data) { + * const newFile = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/files.js + * region_tag:storage_move_file + * Another example: + */ + moveFileAtomic(destination, optionsOrCallback, callback) { + var _a, _b; + const noDestinationError = new Error(FileExceptionMessages.DESTINATION_NO_NAME); + if (!destination) { + throw noDestinationError; + } + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else if (optionsOrCallback) { + options = { ...optionsOrCallback }; + } + callback = callback || util.noop; + let destName; + let newFile; + if (typeof destination === 'string') { + const parsedDestination = GS_URL_REGEXP.exec(destination); + if (parsedDestination !== null && parsedDestination.length === 3) { + destName = parsedDestination[2]; + } + else { + destName = destination; + } + } + else if (destination instanceof File) { + destName = destination.name; + newFile = destination; + } + else { + throw noDestinationError; + } + newFile = newFile || this.bucket.file(destName); + if (!this.shouldRetryBasedOnPreconditionAndIdempotencyStrat(options === null || options === void 0 ? void 0 : options.preconditionOpts)) { + this.storage.retryOptions.autoRetry = false; + } + const query = {}; + if (options.userProject !== undefined) { + query.userProject = options.userProject; + delete options.userProject; + } + if (((_a = options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) !== undefined) { + query.ifGenerationMatch = (_b = options.preconditionOpts) === null || _b === void 0 ? void 0 : _b.ifGenerationMatch; + delete options.preconditionOpts; + } + this.request({ + method: 'POST', + uri: `/moveTo/o/${encodeURIComponent(newFile.name)}`, + qs: query, + json: options, + }, (err, resp) => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + if (err) { + callback(err, null, resp); + return; + } + callback(null, newFile, resp); + }); + } + /** + * @typedef {array} MoveResponse + * @property {File} 0 The destination File. + * @property {object} 1 The full API response. + */ + /** + * @callback MoveCallback + * @param {?Error} err Request error, if any. + * @param {?File} destinationFile The destination File. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {object} MoveOptions Configuration options for File#move(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}. + * @param {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * Move this file to another location. By default, this will rename the file + * and keep it in the same bucket, but you can choose to move it to another + * Bucket by providing a Bucket or File object or a URL beginning with + * "gs://". + * + * **Warning**: + * There is currently no atomic `move` method in the Cloud Storage API, + * so this method is a composition of {@link File#copy} (to the new + * location) and {@link File#delete} (from the old location). While + * unlikely, it is possible that an error returned to your callback could be + * triggered from either one of these API calls failing, which could leave a + * duplicate file lingering. The error message will indicate what operation + * has failed. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/copy| Objects: copy API Documentation} + * + * @throws {Error} If the destination file is not provided. + * + * @param {string|Bucket|File} destination Destination file. + * @param {MoveCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * //- + * // You can pass in a variety of types for the destination. + * // + * // For all of the below examples, assume we are working with the following + * // Bucket and File objects. + * //- + * const bucket = storage.bucket('my-bucket'); + * const file = bucket.file('my-image.png'); + * + * //- + * // If you pass in a string for the destination, the file is moved to its + * // current bucket, under the new name provided. + * //- + * file.move('my-image-new.png', function(err, destinationFile, apiResponse) { + * // `my-bucket` no longer contains: + * // - "my-image.png" + * // but contains instead: + * // - "my-image-new.png" + * + * // `destinationFile` is an instance of a File object that refers to your + * // new file. + * }); + * + * //- + * // If you pass in a string starting with "gs://" for the destination, the + * // file is copied to the other bucket and under the new name provided. + * //- + * const newLocation = 'gs://another-bucket/my-image-new.png'; + * file.move(newLocation, function(err, destinationFile, apiResponse) { + * // `my-bucket` no longer contains: + * // - "my-image.png" + * // + * // `another-bucket` now contains: + * // - "my-image-new.png" + * + * // `destinationFile` is an instance of a File object that refers to your + * // new file. + * }); + * + * //- + * // If you pass in a Bucket object, the file will be moved to that bucket + * // using the same name. + * //- + * const anotherBucket = gcs.bucket('another-bucket'); + * + * file.move(anotherBucket, function(err, destinationFile, apiResponse) { + * // `my-bucket` no longer contains: + * // - "my-image.png" + * // + * // `another-bucket` now contains: + * // - "my-image.png" + * + * // `destinationFile` is an instance of a File object that refers to your + * // new file. + * }); + * + * //- + * // If you pass in a File object, you have complete control over the new + * // bucket and filename. + * //- + * const anotherFile = anotherBucket.file('my-awesome-image.png'); + * + * file.move(anotherFile, function(err, destinationFile, apiResponse) { + * // `my-bucket` no longer contains: + * // - "my-image.png" + * // + * // `another-bucket` now contains: + * // - "my-awesome-image.png" + * + * // Note: + * // The `destinationFile` parameter is equal to `anotherFile`. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.move('my-image-new.png').then(function(data) { + * const destinationFile = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/files.js + * region_tag:storage_move_file + * Another example: + */ + move(destination, optionsOrCallback, callback) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + callback = callback || util.noop; + this.copy(destination, options, (err, destinationFile, copyApiResponse) => { + if (err) { + err.message = 'file#copy failed with an error - ' + err.message; + callback(err, null, copyApiResponse); + return; + } + if (this.name !== destinationFile.name || + this.bucket.name !== destinationFile.bucket.name) { + this.delete(options, (err, apiResponse) => { + if (err) { + err.message = 'file#delete failed with an error - ' + err.message; + callback(err, destinationFile, apiResponse); + return; + } + callback(null, destinationFile, copyApiResponse); + }); + } + else { + callback(null, destinationFile, copyApiResponse); + } + }); + } + /** + * @typedef {array} RenameResponse + * @property {File} 0 The destination File. + * @property {object} 1 The full API response. + */ + /** + * @callback RenameCallback + * @param {?Error} err Request error, if any. + * @param {?File} destinationFile The destination File. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {object} RenameOptions Configuration options for File#move(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}. + * @param {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * Rename this file. + * + * **Warning**: + * There is currently no atomic `rename` method in the Cloud Storage API, + * so this method is an alias of {@link File#move}, which in turn is a + * composition of {@link File#copy} (to the new location) and + * {@link File#delete} (from the old location). While + * unlikely, it is possible that an error returned to your callback could be + * triggered from either one of these API calls failing, which could leave a + * duplicate file lingering. The error message will indicate what operation + * has failed. + * + * @param {string|File} destinationFile Destination file. + * @param {RenameCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // You can pass in a string or a File object. + * // + * // For all of the below examples, assume we are working with the following + * // Bucket and File objects. + * //- + * + * const bucket = storage.bucket('my-bucket'); + * const file = bucket.file('my-image.png'); + * + * //- + * // You can pass in a string for the destinationFile. + * //- + * file.rename('renamed-image.png', function(err, renamedFile, apiResponse) { + * // `my-bucket` no longer contains: + * // - "my-image.png" + * // but contains instead: + * // - "renamed-image.png" + * + * // `renamedFile` is an instance of a File object that refers to your + * // renamed file. + * }); + * + * //- + * // You can pass in a File object. + * //- + * const anotherFile = anotherBucket.file('my-awesome-image.png'); + * + * file.rename(anotherFile, function(err, renamedFile, apiResponse) { + * // `my-bucket` no longer contains: + * // - "my-image.png" + * + * // Note: + * // The `renamedFile` parameter is equal to `anotherFile`. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.rename('my-renamed-image.png').then(function(data) { + * const renamedFile = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + rename(destinationFile, optionsOrCallback, callback) { + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + callback = callback || util.noop; + this.move(destinationFile, options, callback); + } + /** + * @typedef {object} RestoreOptions Options for File#restore(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}. + * @param {string} [userProject] The ID of the project which will be + * billed for the request. + * @param {number} [generation] If present, selects a specific revision of this object. + * @param {string} [restoreToken] Returns an option that must be specified when getting a soft-deleted object from an HNS-enabled + * bucket that has a naming and generation conflict with another object in the same bucket. + * @param {string} [projection] Specifies the set of properties to return. If used, must be 'full' or 'noAcl'. + * @param {string | number} [ifGenerationMatch] Request proceeds if the generation of the target resource + * matches the value used in the precondition. + * If the values don't match, the request fails with a 412 Precondition Failed response. + * @param {string | number} [ifGenerationNotMatch] Request proceeds if the generation of the target resource does + * not match the value used in the precondition. If the values match, the request fails with a 304 Not Modified response. + * @param {string | number} [ifMetagenerationMatch] Request proceeds if the meta-generation of the target resource + * matches the value used in the precondition. + * If the values don't match, the request fails with a 412 Precondition Failed response. + * @param {string | number} [ifMetagenerationNotMatch] Request proceeds if the meta-generation of the target resource does + * not match the value used in the precondition. If the values match, the request fails with a 304 Not Modified response. + */ + /** + * Restores a soft-deleted file + * @param {RestoreOptions} options Restore options. + * @returns {Promise} + */ + async restore(options) { + const [file] = await this.request({ + method: 'POST', + uri: '/restore', + qs: options, + }); + return file; + } + /** + * Makes request and applies userProject query parameter if necessary. + * + * @private + * + * @param {object} reqOpts - The request options. + * @param {function} callback - The callback function. + */ + request(reqOpts, callback) { + return this.parent.request.call(this, reqOpts, callback); + } + /** + * @callback RotateEncryptionKeyCallback + * @extends CopyCallback + */ + /** + * @typedef RotateEncryptionKeyResponse + * @extends CopyResponse + */ + /** + * @param {string|buffer|object} RotateEncryptionKeyOptions Configuration options + * for File#rotateEncryptionKey(). + * If a string or Buffer is provided, it is interpreted as an AES-256, + * customer-supplied encryption key. If you'd like to use a Cloud KMS key + * name, you must specify an options object with the property name: + * `kmsKeyName`. + * @param {string|buffer} [options.encryptionKey] An AES-256 encryption key. + * @param {string} [options.kmsKeyName] A Cloud KMS key name. + */ + /** + * This method allows you to update the encryption key associated with this + * file. + * + * See {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys} + * + * @param {RotateEncryptionKeyOptions} [options] - Configuration options. + * @param {RotateEncryptionKeyCallback} [callback] + * @returns {Promise} + * + * @example include:samples/encryption.js + * region_tag:storage_rotate_encryption_key + * Example of rotating the encryption key for this file: + */ + rotateEncryptionKey(optionsOrCallback, callback) { + var _a; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + let options = {}; + if (typeof optionsOrCallback === 'string' || + optionsOrCallback instanceof Buffer) { + options = { + encryptionKey: optionsOrCallback, + }; + } + else if (typeof optionsOrCallback === 'object') { + options = optionsOrCallback; + } + const newFile = this.bucket.file(this.id, options); + const copyOptions = ((_a = options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) !== undefined + ? { preconditionOpts: options.preconditionOpts } + : {}; + this.copy(newFile, copyOptions, callback); + } + /** + * @typedef {object} SaveOptions + * @extends CreateWriteStreamOptions + */ + /** + * @callback SaveCallback + * @param {?Error} err Request error, if any. + */ + /** + * Write strings or buffers to a file. + * + * *This is a convenience method which wraps {@link File#createWriteStream}.* + * To upload arbitrary data to a file, please use {@link File#createWriteStream} directly. + * + * Resumable uploads are automatically enabled and must be shut off explicitly + * by setting `options.resumable` to `false`. + * + * Multipart uploads with retryable error codes will be retried 3 times with exponential backoff. + * + *

+ * There is some overhead when using a resumable upload that can cause + * noticeable performance degradation while uploading a series of small + * files. When uploading files less than 10MB, it is recommended that the + * resumable feature is disabled. + *

+ * + * @param {SaveData} data The data to write to a file. + * @param {SaveOptions} [options] See {@link File#createWriteStream}'s `options` + * parameter. + * @param {SaveCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * const contents = 'This is the contents of the file.'; + * + * file.save(contents, function(err) { + * if (!err) { + * // File written successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.save(contents).then(function() {}); + * ``` + */ + save(data, optionsOrCallback, callback) { + // tslint:enable:no-any + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + let maxRetries = this.storage.retryOptions.maxRetries; + if (!this.shouldRetryBasedOnPreconditionAndIdempotencyStrat(options === null || options === void 0 ? void 0 : options.preconditionOpts)) { + maxRetries = 0; + } + const returnValue = AsyncRetry(async (bail) => { + return new Promise((resolve, reject) => { + if (maxRetries === 0) { + this.storage.retryOptions.autoRetry = false; + } + const writable = this.createWriteStream(options); + if (options.onUploadProgress) { + writable.on('progress', options.onUploadProgress); + } + const handleError = (err) => { + if (this.storage.retryOptions.autoRetry && + this.storage.retryOptions.retryableErrorFn(err)) { + return reject(err); + } + return bail(err); + }; + if (typeof data === 'string' || + Buffer.isBuffer(data) || + data instanceof Uint8Array) { + writable + .on('error', handleError) + .on('finish', () => resolve()) + .end(data); + } + else { + pipeline(data, writable, err => { + if (err) { + if (typeof data !== 'function') { + // Only PipelineSourceFunction can be retried. Async-iterables + // and Readable streams can only be consumed once. + return bail(err); + } + handleError(err); + } + else { + resolve(); + } + }); + } + }); + }, { + retries: maxRetries, + factor: this.storage.retryOptions.retryDelayMultiplier, + maxTimeout: this.storage.retryOptions.maxRetryDelay * 1000, //convert to milliseconds + maxRetryTime: this.storage.retryOptions.totalTimeout * 1000, //convert to milliseconds + }); + if (!callback) { + return returnValue; + } + else { + return returnValue + .then(() => { + if (callback) { + return callback(); + } + }) + .catch(callback); + } + } + setMetadata(metadata, optionsOrCallback, cb) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + cb = + typeof optionsOrCallback === 'function' + ? optionsOrCallback + : cb; + this.disableAutoRetryConditionallyIdempotent_(this.methods.setMetadata, AvailableServiceObjectMethods.setMetadata, options); + super + .setMetadata(metadata, options) + .then(resp => cb(null, ...resp)) + .catch(cb) + .finally(() => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + }); + } + /** + * @typedef {array} SetStorageClassResponse + * @property {object} 0 The full API response. + */ + /** + * @typedef {object} SetStorageClassOptions Configuration options for File#setStorageClass(). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @callback SetStorageClassCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Set the storage class for this file. + * + * See {@link https://cloud.google.com/storage/docs/per-object-storage-class| Per-Object Storage Class} + * See {@link https://cloud.google.com/storage/docs/storage-classes| Storage Classes} + * + * @param {string} storageClass The new storage class. (`standard`, + * `nearline`, `coldline`, or `archive`) + * **Note:** The storage classes `multi_regional` and `regional` + * are now legacy and will be deprecated in the future. + * @param {SetStorageClassOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {SetStorageClassCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * file.setStorageClass('nearline', function(err, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * // The storage class was updated successfully. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.setStorageClass('nearline').then(function() {}); + * ``` + */ + setStorageClass(storageClass, optionsOrCallback, callback) { + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const req = { + ...options, + // In case we get input like `storageClass`, convert to `storage_class`. + storageClass: storageClass + .replace(/-/g, '_') + .replace(/([a-z])([A-Z])/g, (_, low, up) => { + return low + '_' + up; + }) + .toUpperCase(), + }; + this.copy(this, req, (err, file, apiResponse) => { + if (err) { + callback(err, apiResponse); + return; + } + this.metadata = file.metadata; + callback(null, apiResponse); + }); + } + /** + * Set a user project to be billed for all requests made from this File + * object. + * + * @param {string} userProject The user project. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * const file = bucket.file('my-file'); + * + * file.setUserProject('grape-spaceship-123'); + * ``` + */ + setUserProject(userProject) { + this.bucket.setUserProject.call(this, userProject); + } + /** + * This creates a resumable-upload upload stream. + * + * @param {Duplexify} stream - Duplexify stream of data to pipe to the file. + * @param {object=} options - Configuration object. + * + * @private + */ + startResumableUpload_(dup, options = {}) { + var _a; + (_a = options.metadata) !== null && _a !== void 0 ? _a : (options.metadata = {}); + const retryOptions = this.storage.retryOptions; + if (!this.shouldRetryBasedOnPreconditionAndIdempotencyStrat(options.preconditionOpts)) { + retryOptions.autoRetry = false; + } + const cfg = { + authClient: this.storage.authClient, + apiEndpoint: this.storage.apiEndpoint, + bucket: this.bucket.name, + customRequestOptions: this.getRequestInterceptors().reduce((reqOpts, interceptorFn) => interceptorFn(reqOpts), {}), + file: this.name, + generation: this.generation, + isPartialUpload: options.isPartialUpload, + key: this.encryptionKey, + kmsKeyName: this.kmsKeyName, + metadata: options.metadata, + offset: options.offset, + predefinedAcl: options.predefinedAcl, + private: options.private, + public: options.public, + uri: options.uri, + userProject: options.userProject || this.userProject, + retryOptions: { ...retryOptions }, + params: (options === null || options === void 0 ? void 0 : options.preconditionOpts) || this.instancePreconditionOpts, + chunkSize: options === null || options === void 0 ? void 0 : options.chunkSize, + highWaterMark: options === null || options === void 0 ? void 0 : options.highWaterMark, + universeDomain: this.bucket.storage.universeDomain, + [GCCL_GCS_CMD_KEY]: options[GCCL_GCS_CMD_KEY], + }; + let uploadStream; + try { + uploadStream = resumableUpload.upload(cfg); + } + catch (error) { + dup.destroy(error); + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + return; + } + uploadStream + .on('response', resp => { + dup.emit('response', resp); + }) + .on('uri', uri => { + dup.emit('uri', uri); + }) + .on('metadata', metadata => { + this.metadata = metadata; + dup.emit('metadata'); + }) + .on('finish', () => { + dup.emit('complete'); + }) + .on('progress', evt => dup.emit('progress', evt)); + dup.setWritable(uploadStream); + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + } + /** + * Takes a readable stream and pipes it to a remote file. Unlike + * `startResumableUpload_`, which uses the resumable upload technique, this + * method uses a simple upload (all or nothing). + * + * @param {Duplexify} dup - Duplexify stream of data to pipe to the file. + * @param {object=} options - Configuration object. + * + * @private + */ + startSimpleUpload_(dup, options = {}) { + var _a; + (_a = options.metadata) !== null && _a !== void 0 ? _a : (options.metadata = {}); + const apiEndpoint = this.storage.apiEndpoint; + const bucketName = this.bucket.name; + const uri = `${apiEndpoint}/upload/storage/v1/b/${bucketName}/o`; + const reqOpts = { + qs: { + name: this.name, + }, + uri: uri, + [GCCL_GCS_CMD_KEY]: options[GCCL_GCS_CMD_KEY], + }; + if (this.generation !== undefined) { + reqOpts.qs.ifGenerationMatch = this.generation; + } + if (this.kmsKeyName !== undefined) { + reqOpts.qs.kmsKeyName = this.kmsKeyName; + } + if (typeof options.timeout === 'number') { + reqOpts.timeout = options.timeout; + } + if (options.userProject || this.userProject) { + reqOpts.qs.userProject = options.userProject || this.userProject; + } + if (options.predefinedAcl) { + reqOpts.qs.predefinedAcl = options.predefinedAcl; + } + else if (options.private) { + reqOpts.qs.predefinedAcl = 'private'; + } + else if (options.public) { + reqOpts.qs.predefinedAcl = 'publicRead'; + } + Object.assign(reqOpts.qs, this.instancePreconditionOpts, options.preconditionOpts); + util.makeWritableStream(dup, { + makeAuthenticatedRequest: (reqOpts) => { + this.request(reqOpts, (err, body, resp) => { + if (err) { + dup.destroy(err); + return; + } + this.metadata = body; + dup.emit('metadata', body); + dup.emit('response', resp); + dup.emit('complete'); + }); + }, + metadata: options.metadata, + request: reqOpts, + }); + } + disableAutoRetryConditionallyIdempotent_( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + coreOpts, methodType, localPreconditionOptions) { + var _a, _b, _c, _d; + if ((typeof coreOpts === 'object' && + ((_b = (_a = coreOpts === null || coreOpts === void 0 ? void 0 : coreOpts.reqOpts) === null || _a === void 0 ? void 0 : _a.qs) === null || _b === void 0 ? void 0 : _b.ifGenerationMatch) === undefined && + (localPreconditionOptions === null || localPreconditionOptions === void 0 ? void 0 : localPreconditionOptions.ifGenerationMatch) === undefined && + methodType === AvailableServiceObjectMethods.delete && + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryConditional) || + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryNever) { + this.storage.retryOptions.autoRetry = false; + } + if ((typeof coreOpts === 'object' && + ((_d = (_c = coreOpts === null || coreOpts === void 0 ? void 0 : coreOpts.reqOpts) === null || _c === void 0 ? void 0 : _c.qs) === null || _d === void 0 ? void 0 : _d.ifMetagenerationMatch) === undefined && + (localPreconditionOptions === null || localPreconditionOptions === void 0 ? void 0 : localPreconditionOptions.ifMetagenerationMatch) === undefined && + methodType === AvailableServiceObjectMethods.setMetadata && + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryConditional) || + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryNever) { + this.storage.retryOptions.autoRetry = false; + } + } + async getBufferFromReadable(readable) { + const buf = []; + for await (const chunk of readable) { + buf.push(chunk); + } + return Buffer.concat(buf); + } +} +_File_instances = new WeakSet(), _File_validateIntegrity = +/** + * + * @param hashCalculatingStream + * @param verify + * @returns {boolean} Returns `true` if valid, throws with error otherwise + */ +async function _File_validateIntegrity(hashCalculatingStream, verify = {}) { + const metadata = this.metadata; + // If we're doing validation, assume the worst + let dataMismatch = !!(verify.crc32c || verify.md5); + if (verify.crc32c && metadata.crc32c) { + dataMismatch = !hashCalculatingStream.test('crc32c', metadata.crc32c); + } + if (verify.md5 && metadata.md5Hash) { + dataMismatch = !hashCalculatingStream.test('md5', metadata.md5Hash); + } + if (dataMismatch) { + const errors = []; + let code = ''; + let message = ''; + try { + await this.delete(); + if (verify.md5 && !metadata.md5Hash) { + code = 'MD5_NOT_AVAILABLE'; + message = FileExceptionMessages.MD5_NOT_AVAILABLE; + } + else { + code = 'FILE_NO_UPLOAD'; + message = FileExceptionMessages.UPLOAD_MISMATCH; + } + } + catch (e) { + const error = e; + code = 'FILE_NO_UPLOAD_DELETE'; + message = `${FileExceptionMessages.UPLOAD_MISMATCH_DELETE_FAIL}${error.message}`; + errors.push(error); + } + const error = new RequestError(message); + error.code = code; + error.errors = errors; + throw error; + } + return true; +}; +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(File, { + exclude: [ + 'cloudStorageURI', + 'publicUrl', + 'request', + 'save', + 'setEncryptionKey', + 'shouldRetryBasedOnPreconditionAndIdempotencyStrat', + 'getBufferFromReadable', + 'restore', + ], +}); +/** + * Reference to the {@link File} class. + * @name module:@google-cloud/storage.File + * @see File + */ +export { File }; diff --git a/node_modules/@google-cloud/storage/build/esm/src/hash-stream-validator.d.ts b/node_modules/@google-cloud/storage/build/esm/src/hash-stream-validator.d.ts new file mode 100644 index 0000000..c16e3ba --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/hash-stream-validator.d.ts @@ -0,0 +1,35 @@ +import { Transform } from 'stream'; +import { CRC32CValidatorGenerator, CRC32CValidator } from './crc32c.js'; +interface HashStreamValidatorOptions { + /** Enables CRC32C calculation. To validate a provided value use `crc32cExpected`. */ + crc32c: boolean; + /** Enables MD5 calculation. To validate a provided value use `md5Expected`. */ + md5: boolean; + /** A CRC32C instance for validation. To validate a provided value use `crc32cExpected`. */ + crc32cInstance: CRC32CValidator; + /** Set a custom CRC32C generator. Used if `crc32cInstance` has not been provided. */ + crc32cGenerator: CRC32CValidatorGenerator; + /** Sets the expected CRC32C value to verify once all data has been consumed. Also sets the `crc32c` option to `true` */ + crc32cExpected?: string; + /** Sets the expected MD5 value to verify once all data has been consumed. Also sets the `md5` option to `true` */ + md5Expected?: string; + /** Indicates whether or not to run a validation check or only update the hash values */ + updateHashesOnly?: boolean; +} +declare class HashStreamValidator extends Transform { + #private; + readonly crc32cEnabled: boolean; + readonly md5Enabled: boolean; + readonly crc32cExpected: string | undefined; + readonly md5Expected: string | undefined; + readonly updateHashesOnly: boolean; + constructor(options?: Partial); + /** + * Return the current CRC32C value, if available. + */ + get crc32c(): string | undefined; + _flush(callback: (error?: Error | null | undefined) => void): void; + _transform(chunk: Buffer, encoding: BufferEncoding, callback: (e?: Error) => void): void; + test(hash: 'crc32c' | 'md5', sum: Buffer | string): boolean; +} +export { HashStreamValidator, HashStreamValidatorOptions }; diff --git a/node_modules/@google-cloud/storage/build/esm/src/hash-stream-validator.js b/node_modules/@google-cloud/storage/build/esm/src/hash-stream-validator.js new file mode 100644 index 0000000..31c6d5a --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/hash-stream-validator.js @@ -0,0 +1,116 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _HashStreamValidator_crc32cHash, _HashStreamValidator_md5Hash, _HashStreamValidator_md5Digest; +import { createHash } from 'crypto'; +import { Transform } from 'stream'; +import { CRC32C_DEFAULT_VALIDATOR_GENERATOR, } from './crc32c.js'; +import { FileExceptionMessages, RequestError } from './file.js'; +class HashStreamValidator extends Transform { + constructor(options = {}) { + super(); + this.updateHashesOnly = false; + _HashStreamValidator_crc32cHash.set(this, undefined); + _HashStreamValidator_md5Hash.set(this, undefined); + _HashStreamValidator_md5Digest.set(this, ''); + this.crc32cEnabled = !!options.crc32c; + this.md5Enabled = !!options.md5; + this.updateHashesOnly = !!options.updateHashesOnly; + this.crc32cExpected = options.crc32cExpected; + this.md5Expected = options.md5Expected; + if (this.crc32cEnabled) { + if (options.crc32cInstance) { + __classPrivateFieldSet(this, _HashStreamValidator_crc32cHash, options.crc32cInstance, "f"); + } + else { + const crc32cGenerator = options.crc32cGenerator || CRC32C_DEFAULT_VALIDATOR_GENERATOR; + __classPrivateFieldSet(this, _HashStreamValidator_crc32cHash, crc32cGenerator(), "f"); + } + } + if (this.md5Enabled) { + __classPrivateFieldSet(this, _HashStreamValidator_md5Hash, createHash('md5'), "f"); + } + } + /** + * Return the current CRC32C value, if available. + */ + get crc32c() { + var _a; + return (_a = __classPrivateFieldGet(this, _HashStreamValidator_crc32cHash, "f")) === null || _a === void 0 ? void 0 : _a.toString(); + } + _flush(callback) { + if (__classPrivateFieldGet(this, _HashStreamValidator_md5Hash, "f")) { + __classPrivateFieldSet(this, _HashStreamValidator_md5Digest, __classPrivateFieldGet(this, _HashStreamValidator_md5Hash, "f").digest('base64'), "f"); + } + if (this.updateHashesOnly) { + callback(); + return; + } + // If we're doing validation, assume the worst-- a data integrity + // mismatch. If not, these tests won't be performed, and we can assume + // the best. + // We must check if the server decompressed the data on serve because hash + // validation is not possible in this case. + let failed = this.crc32cEnabled || this.md5Enabled; + if (this.crc32cEnabled && this.crc32cExpected) { + failed = !this.test('crc32c', this.crc32cExpected); + } + if (this.md5Enabled && this.md5Expected) { + failed = !this.test('md5', this.md5Expected); + } + if (failed) { + const mismatchError = new RequestError(FileExceptionMessages.DOWNLOAD_MISMATCH); + mismatchError.code = 'CONTENT_DOWNLOAD_MISMATCH'; + callback(mismatchError); + } + else { + callback(); + } + } + _transform(chunk, encoding, callback) { + this.push(chunk, encoding); + try { + if (__classPrivateFieldGet(this, _HashStreamValidator_crc32cHash, "f")) + __classPrivateFieldGet(this, _HashStreamValidator_crc32cHash, "f").update(chunk); + if (__classPrivateFieldGet(this, _HashStreamValidator_md5Hash, "f")) + __classPrivateFieldGet(this, _HashStreamValidator_md5Hash, "f").update(chunk); + callback(); + } + catch (e) { + callback(e); + } + } + test(hash, sum) { + const check = Buffer.isBuffer(sum) ? sum.toString('base64') : sum; + if (hash === 'crc32c' && __classPrivateFieldGet(this, _HashStreamValidator_crc32cHash, "f")) { + return __classPrivateFieldGet(this, _HashStreamValidator_crc32cHash, "f").validate(check); + } + if (hash === 'md5' && __classPrivateFieldGet(this, _HashStreamValidator_md5Hash, "f")) { + return __classPrivateFieldGet(this, _HashStreamValidator_md5Digest, "f") === check; + } + return false; + } +} +_HashStreamValidator_crc32cHash = new WeakMap(), _HashStreamValidator_md5Hash = new WeakMap(), _HashStreamValidator_md5Digest = new WeakMap(); +export { HashStreamValidator }; diff --git a/node_modules/@google-cloud/storage/build/esm/src/hmacKey.d.ts b/node_modules/@google-cloud/storage/build/esm/src/hmacKey.d.ts new file mode 100644 index 0000000..4433a83 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/hmacKey.d.ts @@ -0,0 +1,93 @@ +import { ServiceObject, MetadataCallback, SetMetadataResponse } from './nodejs-common/index.js'; +import { BaseMetadata, SetMetadataOptions } from './nodejs-common/service-object.js'; +import { Storage } from './storage.js'; +export interface HmacKeyOptions { + projectId?: string; +} +export interface HmacKeyMetadata extends BaseMetadata { + accessId?: string; + etag?: string; + projectId?: string; + serviceAccountEmail?: string; + state?: string; + timeCreated?: string; + updated?: string; +} +export interface SetHmacKeyMetadataOptions { + /** + * This parameter is currently ignored. + */ + userProject?: string; +} +export interface SetHmacKeyMetadata { + state?: 'ACTIVE' | 'INACTIVE'; + etag?: string; +} +export interface HmacKeyMetadataCallback { + (err: Error | null, metadata?: HmacKeyMetadata, apiResponse?: unknown): void; +} +export type HmacKeyMetadataResponse = [HmacKeyMetadata, unknown]; +/** + * The API-formatted resource description of the HMAC key. + * + * Note: This is not guaranteed to be up-to-date when accessed. To get the + * latest record, call the `getMetadata()` method. + * + * @name HmacKey#metadata + * @type {object} + */ +/** + * An HmacKey object contains metadata of an HMAC key created from a + * service account through the {@link Storage} client using + * {@link Storage#createHmacKey}. + * + * See {@link https://cloud.google.com/storage/docs/authentication/hmackeys| HMAC keys documentation} + * + * @class + */ +export declare class HmacKey extends ServiceObject { + /** + * A reference to the {@link Storage} associated with this {@link HmacKey} + * instance. + * @name HmacKey#storage + * @type {Storage} + */ + storage: Storage; + private instanceRetryValue?; + /** + * @typedef {object} HmacKeyOptions + * @property {string} [projectId] The project ID of the project that owns + * the service account of the requested HMAC key. If not provided, + * the project ID used to instantiate the Storage client will be used. + */ + /** + * Constructs an HmacKey object. + * + * Note: this only create a local reference to an HMAC key, to create + * an HMAC key, use {@link Storage#createHmacKey}. + * + * @param {Storage} storage The Storage instance this HMAC key is + * attached to. + * @param {string} accessId The unique accessId for this HMAC key. + * @param {HmacKeyOptions} options Constructor configurations. + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const hmacKey = storage.hmacKey('access-id'); + * ``` + */ + constructor(storage: Storage, accessId: string, options?: HmacKeyOptions); + /** + * Set the metadata for this object. + * + * @param {object} metadata - The metadata to set on this object. + * @param {object=} options - Configuration options. + * @param {function=} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.apiResponse - The full API response. + */ + setMetadata(metadata: HmacKeyMetadata, options?: SetMetadataOptions): Promise>; + setMetadata(metadata: HmacKeyMetadata, callback: MetadataCallback): void; + setMetadata(metadata: HmacKeyMetadata, options: SetMetadataOptions, callback: MetadataCallback): void; +} diff --git a/node_modules/@google-cloud/storage/build/esm/src/hmacKey.js b/node_modules/@google-cloud/storage/build/esm/src/hmacKey.js new file mode 100644 index 0000000..9030248 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/hmacKey.js @@ -0,0 +1,332 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +import { ServiceObject, } from './nodejs-common/index.js'; +import { IdempotencyStrategy } from './storage.js'; +import { promisifyAll } from '@google-cloud/promisify'; +/** + * The API-formatted resource description of the HMAC key. + * + * Note: This is not guaranteed to be up-to-date when accessed. To get the + * latest record, call the `getMetadata()` method. + * + * @name HmacKey#metadata + * @type {object} + */ +/** + * An HmacKey object contains metadata of an HMAC key created from a + * service account through the {@link Storage} client using + * {@link Storage#createHmacKey}. + * + * See {@link https://cloud.google.com/storage/docs/authentication/hmackeys| HMAC keys documentation} + * + * @class + */ +export class HmacKey extends ServiceObject { + /** + * @typedef {object} HmacKeyOptions + * @property {string} [projectId] The project ID of the project that owns + * the service account of the requested HMAC key. If not provided, + * the project ID used to instantiate the Storage client will be used. + */ + /** + * Constructs an HmacKey object. + * + * Note: this only create a local reference to an HMAC key, to create + * an HMAC key, use {@link Storage#createHmacKey}. + * + * @param {Storage} storage The Storage instance this HMAC key is + * attached to. + * @param {string} accessId The unique accessId for this HMAC key. + * @param {HmacKeyOptions} options Constructor configurations. + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const hmacKey = storage.hmacKey('access-id'); + * ``` + */ + constructor(storage, accessId, options) { + const methods = { + /** + * @typedef {object} DeleteHmacKeyOptions + * @property {string} [userProject] This parameter is currently ignored. + */ + /** + * @typedef {array} DeleteHmacKeyResponse + * @property {object} 0 The full API response. + */ + /** + * @callback DeleteHmacKeyCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Deletes an HMAC key. + * Key state must be set to `INACTIVE` prior to deletion. + * Caution: HMAC keys cannot be recovered once you delete them. + * + * The authenticated user must have `storage.hmacKeys.delete` permission for the project in which the key exists. + * + * @method HmacKey#delete + * @param {DeleteHmacKeyOptions} [options] Configuration options. + * @param {DeleteHmacKeyCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // Delete HMAC key after making the key inactive. + * //- + * const hmacKey = storage.hmacKey('ACCESS_ID'); + * hmacKey.setMetadata({state: 'INACTIVE'}, (err, hmacKeyMetadata) => { + * if (err) { + * // The request was an error. + * console.error(err); + * return; + * } + * hmacKey.delete((err) => { + * if (err) { + * console.error(err); + * return; + * } + * // The HMAC key is deleted. + * }); + * }); + * + * //- + * // If the callback is omitted, a promise is returned. + * //- + * const hmacKey = storage.hmacKey('ACCESS_ID'); + * hmacKey + * .setMetadata({state: 'INACTIVE'}) + * .then(() => { + * return hmacKey.delete(); + * }); + * ``` + */ + delete: true, + /** + * @callback GetHmacKeyCallback + * @param {?Error} err Request error, if any. + * @param {HmacKey} hmacKey this {@link HmacKey} instance. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} GetHmacKeyResponse + * @property {HmacKey} 0 This {@link HmacKey} instance. + * @property {object} 1 The full API response. + */ + /** + * @typedef {object} GetHmacKeyOptions + * @property {string} [userProject] This parameter is currently ignored. + */ + /** + * Retrieves and populate an HMAC key's metadata, and return + * this {@link HmacKey} instance. + * + * HmacKey.get() does not give the HMAC key secret, as + * it is only returned on creation. + * + * The authenticated user must have `storage.hmacKeys.get` permission + * for the project in which the key exists. + * + * @method HmacKey#get + * @param {GetHmacKeyOptions} [options] Configuration options. + * @param {GetHmacKeyCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // Get the HmacKey's Metadata. + * //- + * storage.hmacKey('ACCESS_ID') + * .get((err, hmacKey) => { + * if (err) { + * // The request was an error. + * console.error(err); + * return; + * } + * // do something with the returned HmacKey object. + * }); + * + * //- + * // If the callback is omitted, a promise is returned. + * //- + * storage.hmacKey('ACCESS_ID') + * .get() + * .then((data) => { + * const hmacKey = data[0]; + * }); + * ``` + */ + get: true, + /** + * @typedef {object} GetHmacKeyMetadataOptions + * @property {string} [userProject] This parameter is currently ignored. + */ + /** + * Retrieves and populate an HMAC key's metadata, and return + * the HMAC key's metadata as an object. + * + * HmacKey.getMetadata() does not give the HMAC key secret, as + * it is only returned on creation. + * + * The authenticated user must have `storage.hmacKeys.get` permission + * for the project in which the key exists. + * + * @method HmacKey#getMetadata + * @param {GetHmacKeyMetadataOptions} [options] Configuration options. + * @param {HmacKeyMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // Get the HmacKey's metadata and populate to the metadata property. + * //- + * storage.hmacKey('ACCESS_ID') + * .getMetadata((err, hmacKeyMetadata) => { + * if (err) { + * // The request was an error. + * console.error(err); + * return; + * } + * console.log(hmacKeyMetadata); + * }); + * + * //- + * // If the callback is omitted, a promise is returned. + * //- + * storage.hmacKey('ACCESS_ID') + * .getMetadata() + * .then((data) => { + * const hmacKeyMetadata = data[0]; + * console.log(hmacKeyMetadata); + * }); + * ``` + */ + getMetadata: true, + /** + * @typedef {object} SetHmacKeyMetadata Subset of {@link HmacKeyMetadata} to update. + * @property {string} state New state of the HmacKey. Either 'ACTIVE' or 'INACTIVE'. + * @property {string} [etag] Include an etag from a previous get HMAC key request + * to perform safe read-modify-write. + */ + /** + * @typedef {object} SetHmacKeyMetadataOptions + * @property {string} [userProject] This parameter is currently ignored. + */ + /** + * @callback HmacKeyMetadataCallback + * @param {?Error} err Request error, if any. + * @param {HmacKeyMetadata} metadata The updated {@link HmacKeyMetadata} object. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} HmacKeyMetadataResponse + * @property {HmacKeyMetadata} 0 The updated {@link HmacKeyMetadata} object. + * @property {object} 1 The full API response. + */ + /** + * Updates the state of an HMAC key. See {@link SetHmacKeyMetadata} for + * valid states. + * + * @method HmacKey#setMetadata + * @param {SetHmacKeyMetadata} metadata The new metadata. + * @param {SetHmacKeyMetadataOptions} [options] Configuration options. + * @param {HmacKeyMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * const metadata = { + * state: 'INACTIVE', + * }; + * + * storage.hmacKey('ACCESS_ID') + * .setMetadata(metadata, (err, hmacKeyMetadata) => { + * if (err) { + * // The request was an error. + * console.error(err); + * return; + * } + * console.log(hmacKeyMetadata); + * }); + * + * //- + * // If the callback is omitted, a promise is returned. + * //- + * storage.hmacKey('ACCESS_ID') + * .setMetadata(metadata) + * .then((data) => { + * const hmacKeyMetadata = data[0]; + * console.log(hmacKeyMetadata); + * }); + * ``` + */ + setMetadata: { + reqOpts: { + method: 'PUT', + }, + }, + }; + const projectId = (options && options.projectId) || storage.projectId; + super({ + parent: storage, + id: accessId, + baseUrl: `/projects/${projectId}/hmacKeys`, + methods, + }); + this.storage = storage; + this.instanceRetryValue = storage.retryOptions.autoRetry; + } + setMetadata(metadata, optionsOrCallback, cb) { + // ETag preconditions are not currently supported. Retries should be disabled if the idempotency strategy is not set to RetryAlways + if (this.storage.retryOptions.idempotencyStrategy !== + IdempotencyStrategy.RetryAlways) { + this.storage.retryOptions.autoRetry = false; + } + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + cb = + typeof optionsOrCallback === 'function' + ? optionsOrCallback + : cb; + super + .setMetadata(metadata, options) + .then(resp => cb(null, ...resp)) + .catch(cb) + .finally(() => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + }); + } +} +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(HmacKey); diff --git a/node_modules/@google-cloud/storage/build/esm/src/iam.d.ts b/node_modules/@google-cloud/storage/build/esm/src/iam.d.ts new file mode 100644 index 0000000..3ceb19c --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/iam.d.ts @@ -0,0 +1,117 @@ +import { Bucket } from './bucket.js'; +export interface GetPolicyOptions { + userProject?: string; + requestedPolicyVersion?: number; +} +export type GetPolicyResponse = [Policy, unknown]; +/** + * @callback GetPolicyCallback + * @param {?Error} err Request error, if any. + * @param {object} acl The policy. + * @param {object} apiResponse The full API response. + */ +export interface GetPolicyCallback { + (err?: Error | null, acl?: Policy, apiResponse?: unknown): void; +} +/** + * @typedef {object} SetPolicyOptions + * @param {string} [userProject] The ID of the project which will be + * billed for the request. + */ +export interface SetPolicyOptions { + userProject?: string; +} +/** + * @typedef {array} SetPolicyResponse + * @property {object} 0 The policy. + * @property {object} 1 The full API response. + */ +export type SetPolicyResponse = [Policy, unknown]; +/** + * @callback SetPolicyCallback + * @param {?Error} err Request error, if any. + * @param {object} acl The policy. + * @param {object} apiResponse The full API response. + */ +export interface SetPolicyCallback { + (err?: Error | null, acl?: Policy, apiResponse?: object): void; +} +export interface Policy { + bindings: PolicyBinding[]; + version?: number; + etag?: string; +} +export interface PolicyBinding { + role: string; + members: string[]; + condition?: Expr; +} +export interface Expr { + title?: string; + description?: string; + expression: string; +} +/** + * @typedef {array} TestIamPermissionsResponse + * @property {object} 0 A subset of permissions that the caller is allowed. + * @property {object} 1 The full API response. + */ +export type TestIamPermissionsResponse = [{ + [key: string]: boolean; +}, unknown]; +/** + * @callback TestIamPermissionsCallback + * @param {?Error} err Request error, if any. + * @param {object} acl A subset of permissions that the caller is allowed. + * @param {object} apiResponse The full API response. + */ +export interface TestIamPermissionsCallback { + (err?: Error | null, acl?: { + [key: string]: boolean; + } | null, apiResponse?: unknown): void; +} +/** + * @typedef {object} TestIamPermissionsOptions Configuration options for Iam#testPermissions(). + * @param {string} [userProject] The ID of the project which will be + * billed for the request. + */ +export interface TestIamPermissionsOptions { + userProject?: string; +} +export declare enum IAMExceptionMessages { + POLICY_OBJECT_REQUIRED = "A policy object is required.", + PERMISSIONS_REQUIRED = "Permissions are required." +} +/** + * Get and set IAM policies for your Cloud Storage bucket. + * + * See {@link https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management| Cloud Storage IAM Management} + * See {@link https://cloud.google.com/iam/docs/granting-changing-revoking-access| Granting, Changing, and Revoking Access} + * See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles} + * + * @constructor Iam + * + * @param {Bucket} bucket The parent instance. + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * // bucket.iam + * ``` + */ +declare class Iam { + private request_; + private resourceId_; + constructor(bucket: Bucket); + getPolicy(options?: GetPolicyOptions): Promise; + getPolicy(options: GetPolicyOptions, callback: GetPolicyCallback): void; + getPolicy(callback: GetPolicyCallback): void; + setPolicy(policy: Policy, options?: SetPolicyOptions): Promise; + setPolicy(policy: Policy, callback: SetPolicyCallback): void; + setPolicy(policy: Policy, options: SetPolicyOptions, callback: SetPolicyCallback): void; + testPermissions(permissions: string | string[], options?: TestIamPermissionsOptions): Promise; + testPermissions(permissions: string | string[], callback: TestIamPermissionsCallback): void; + testPermissions(permissions: string | string[], options: TestIamPermissionsOptions, callback: TestIamPermissionsCallback): void; +} +export { Iam }; diff --git a/node_modules/@google-cloud/storage/build/esm/src/iam.js b/node_modules/@google-cloud/storage/build/esm/src/iam.js new file mode 100644 index 0000000..7ca2ce8 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/iam.js @@ -0,0 +1,303 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +import { promisifyAll } from '@google-cloud/promisify'; +import { normalize } from './util.js'; +export var IAMExceptionMessages; +(function (IAMExceptionMessages) { + IAMExceptionMessages["POLICY_OBJECT_REQUIRED"] = "A policy object is required."; + IAMExceptionMessages["PERMISSIONS_REQUIRED"] = "Permissions are required."; +})(IAMExceptionMessages || (IAMExceptionMessages = {})); +/** + * Get and set IAM policies for your Cloud Storage bucket. + * + * See {@link https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management| Cloud Storage IAM Management} + * See {@link https://cloud.google.com/iam/docs/granting-changing-revoking-access| Granting, Changing, and Revoking Access} + * See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles} + * + * @constructor Iam + * + * @param {Bucket} bucket The parent instance. + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * // bucket.iam + * ``` + */ +class Iam { + constructor(bucket) { + this.request_ = bucket.request.bind(bucket); + this.resourceId_ = 'buckets/' + bucket.getId(); + } + /** + * @typedef {object} GetPolicyOptions Requested options for IAM#getPolicy(). + * @property {number} [requestedPolicyVersion] The version of IAM policies to + * request. If a policy with a condition is requested without setting + * this, the server will return an error. This must be set to a value + * of 3 to retrieve IAM policies containing conditions. This is to + * prevent client code that isn't aware of IAM conditions from + * interpreting and modifying policies incorrectly. The service might + * return a policy with version lower than the one that was requested, + * based on the feature syntax in the policy fetched. + * See {@link https://cloud.google.com/iam/docs/policies#versions| IAM Policy versions} + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @typedef {array} GetPolicyResponse + * @property {Policy} 0 The policy. + * @property {object} 1 The full API response. + */ + /** + * @typedef {object} Policy + * @property {PolicyBinding[]} policy.bindings Bindings associate members with roles. + * @property {string} [policy.etag] Etags are used to perform a read-modify-write. + * @property {number} [policy.version] The syntax schema version of the Policy. + * To set an IAM policy with conditional binding, this field must be set to + * 3 or greater. + * See {@link https://cloud.google.com/iam/docs/policies#versions| IAM Policy versions} + */ + /** + * @typedef {object} PolicyBinding + * @property {string} role Role that is assigned to members. + * @property {string[]} members Specifies the identities requesting access for the bucket. + * @property {Expr} [condition] The condition that is associated with this binding. + */ + /** + * @typedef {object} Expr + * @property {string} [title] An optional title for the expression, i.e. a + * short string describing its purpose. This can be used e.g. in UIs + * which allow to enter the expression. + * @property {string} [description] An optional description of the + * expression. This is a longer text which describes the expression, + * e.g. when hovered over it in a UI. + * @property {string} expression Textual representation of an expression in + * Common Expression Language syntax. The application context of the + * containing message determines which well-known feature set of CEL + * is supported.The condition that is associated with this binding. + * + * @see [Condition] https://cloud.google.com/storage/docs/access-control/iam#conditions + */ + /** + * Get the IAM policy. + * + * @param {GetPolicyOptions} [options] Request options. + * @param {GetPolicyCallback} [callback] Callback function. + * @returns {Promise} + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy| Buckets: setIamPolicy API Documentation} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * bucket.iam.getPolicy( + * {requestedPolicyVersion: 3}, + * function(err, policy, apiResponse) { + * + * }, + * ); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.iam.getPolicy({requestedPolicyVersion: 3}) + * .then(function(data) { + * const policy = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/iam.js + * region_tag:storage_view_bucket_iam_members + * Example of retrieving a bucket's IAM policy: + */ + getPolicy(optionsOrCallback, callback) { + const { options, callback: cb } = normalize(optionsOrCallback, callback); + const qs = {}; + if (options.userProject) { + qs.userProject = options.userProject; + } + if (options.requestedPolicyVersion !== null && + options.requestedPolicyVersion !== undefined) { + qs.optionsRequestedPolicyVersion = options.requestedPolicyVersion; + } + this.request_({ + uri: '/iam', + qs, + }, cb); + } + /** + * Set the IAM policy. + * + * @throws {Error} If no policy is provided. + * + * @param {Policy} policy The policy. + * @param {SetPolicyOptions} [options] Configuration options. + * @param {SetPolicyCallback} callback Callback function. + * @returns {Promise} + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/setIamPolicy| Buckets: setIamPolicy API Documentation} + * See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * const myPolicy = { + * bindings: [ + * { + * role: 'roles/storage.admin', + * members: + * ['serviceAccount:myotherproject@appspot.gserviceaccount.com'] + * } + * ] + * }; + * + * bucket.iam.setPolicy(myPolicy, function(err, policy, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.iam.setPolicy(myPolicy).then(function(data) { + * const policy = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/iam.js + * region_tag:storage_add_bucket_iam_member + * Example of adding to a bucket's IAM policy: + * + * @example include:samples/iam.js + * region_tag:storage_remove_bucket_iam_member + * Example of removing from a bucket's IAM policy: + */ + setPolicy(policy, optionsOrCallback, callback) { + if (policy === null || typeof policy !== 'object') { + throw new Error(IAMExceptionMessages.POLICY_OBJECT_REQUIRED); + } + const { options, callback: cb } = normalize(optionsOrCallback, callback); + let maxRetries; + if (policy.etag === undefined) { + maxRetries = 0; + } + this.request_({ + method: 'PUT', + uri: '/iam', + maxRetries, + json: Object.assign({ + resourceId: this.resourceId_, + }, policy), + qs: options, + }, cb); + } + /** + * Test a set of permissions for a resource. + * + * @throws {Error} If permissions are not provided. + * + * @param {string|string[]} permissions The permission(s) to test for. + * @param {TestIamPermissionsOptions} [options] Configuration object. + * @param {TestIamPermissionsCallback} [callback] Callback function. + * @returns {Promise} + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/testIamPermissions| Buckets: testIamPermissions API Documentation} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * //- + * // Test a single permission. + * //- + * const test = 'storage.buckets.delete'; + * + * bucket.iam.testPermissions(test, function(err, permissions, apiResponse) { + * console.log(permissions); + * // { + * // "storage.buckets.delete": true + * // } + * }); + * + * //- + * // Test several permissions at once. + * //- + * const tests = [ + * 'storage.buckets.delete', + * 'storage.buckets.get' + * ]; + * + * bucket.iam.testPermissions(tests, function(err, permissions) { + * console.log(permissions); + * // { + * // "storage.buckets.delete": false, + * // "storage.buckets.get": true + * // } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.iam.testPermissions(test).then(function(data) { + * const permissions = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + testPermissions(permissions, optionsOrCallback, callback) { + if (!Array.isArray(permissions) && typeof permissions !== 'string') { + throw new Error(IAMExceptionMessages.PERMISSIONS_REQUIRED); + } + const { options, callback: cb } = normalize(optionsOrCallback, callback); + const permissionsArray = Array.isArray(permissions) + ? permissions + : [permissions]; + const req = Object.assign({ + permissions: permissionsArray, + }, options); + this.request_({ + uri: '/iam/testPermissions', + qs: req, + useQuerystring: true, + }, (err, resp) => { + if (err) { + cb(err, null, resp); + return; + } + const availablePermissions = Array.isArray(resp.permissions) + ? resp.permissions + : []; + const permissionsHash = permissionsArray.reduce((acc, permission) => { + acc[permission] = availablePermissions.indexOf(permission) > -1; + return acc; + }, {}); + cb(null, permissionsHash, resp); + }); + } +} +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Iam); +export { Iam }; diff --git a/node_modules/@google-cloud/storage/build/esm/src/index.d.ts b/node_modules/@google-cloud/storage/build/esm/src/index.d.ts new file mode 100644 index 0000000..82c50e0 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/index.d.ts @@ -0,0 +1,57 @@ +/** + * The `@google-cloud/storage` package has a single named export which is the + * {@link Storage} (ES6) class, which should be instantiated with `new`. + * + * See {@link Storage} and {@link ClientConfig} for client methods and + * configuration options. + * + * @module {Storage} @google-cloud/storage + * @alias nodejs-storage + * + * @example + * Install the client library with npm: + * ``` + * npm install --save @google-cloud/storage + * ``` + * + * @example + * Import the client library + * ``` + * const {Storage} = require('@google-cloud/storage'); + * ``` + * + * @example + * Create a client that uses Application + * Default Credentials (ADC): + * ``` + * const storage = new Storage(); + * ``` + * + * @example + * Create a client with explicit + * credentials: + * ``` + * const storage = new Storage({ projectId: + * 'your-project-id', keyFilename: '/path/to/keyfile.json' + * }); + * ``` + * + * @example include:samples/quickstart.js + * region_tag:storage_quickstart + * Full quickstart example: + */ +export { ApiError } from './nodejs-common/index.js'; +export { BucketCallback, BucketOptions, CreateBucketQuery, CreateBucketRequest, CreateBucketResponse, CreateHmacKeyCallback, CreateHmacKeyOptions, CreateHmacKeyResponse, GetBucketsCallback, GetBucketsRequest, GetBucketsResponse, GetHmacKeysCallback, GetHmacKeysOptions, GetHmacKeysResponse, GetServiceAccountCallback, GetServiceAccountOptions, GetServiceAccountResponse, HmacKeyResourceResponse, IdempotencyStrategy, PreconditionOptions, RETRYABLE_ERR_FN_DEFAULT, ServiceAccount, Storage, StorageOptions, } from './storage.js'; +export { AclMetadata, AccessControlObject, AclOptions, AddAclCallback, AddAclOptions, AddAclResponse, GetAclCallback, GetAclOptions, GetAclResponse, RemoveAclCallback, RemoveAclOptions, RemoveAclResponse, UpdateAclCallback, UpdateAclOptions, UpdateAclResponse, } from './acl.js'; +export { Bucket, BucketExistsCallback, BucketExistsOptions, BucketExistsResponse, BucketLockCallback, BucketLockResponse, BucketMetadata, CombineCallback, CombineOptions, CombineResponse, CreateChannelCallback, CreateChannelConfig, CreateChannelOptions, CreateChannelResponse, CreateNotificationCallback, CreateNotificationOptions, CreateNotificationResponse, DeleteBucketCallback, DeleteBucketOptions, DeleteBucketResponse, DeleteFilesCallback, DeleteFilesOptions, DeleteLabelsCallback, DeleteLabelsResponse, DisableRequesterPaysCallback, DisableRequesterPaysResponse, EnableRequesterPaysCallback, EnableRequesterPaysResponse, GetBucketCallback, GetBucketMetadataCallback, GetBucketMetadataOptions, GetBucketMetadataResponse, GetBucketOptions, GetBucketResponse, GetBucketSignedUrlConfig, GetFilesCallback, GetFilesOptions, GetFilesResponse, GetLabelsCallback, GetLabelsOptions, GetLabelsResponse, GetNotificationsCallback, GetNotificationsOptions, GetNotificationsResponse, Labels, LifecycleAction, LifecycleCondition, LifecycleRule, MakeBucketPrivateCallback, MakeBucketPrivateOptions, MakeBucketPrivateResponse, MakeBucketPublicCallback, MakeBucketPublicOptions, MakeBucketPublicResponse, SetBucketMetadataCallback, SetBucketMetadataOptions, SetBucketMetadataResponse, SetBucketStorageClassCallback, SetBucketStorageClassOptions, SetLabelsCallback, SetLabelsOptions, SetLabelsResponse, UploadCallback, UploadOptions, UploadResponse, } from './bucket.js'; +export * from './crc32c.js'; +export { Channel, StopCallback } from './channel.js'; +export { CopyCallback, CopyOptions, CopyResponse, CreateReadStreamOptions, CreateResumableUploadCallback, CreateResumableUploadOptions, CreateResumableUploadResponse, CreateWriteStreamOptions, DeleteFileCallback, DeleteFileOptions, DeleteFileResponse, DownloadCallback, DownloadOptions, DownloadResponse, EncryptionKeyOptions, File, FileExistsCallback, FileExistsOptions, FileExistsResponse, FileMetadata, FileOptions, GetExpirationDateCallback, GetExpirationDateResponse, GetFileCallback, GetFileMetadataCallback, GetFileMetadataOptions, GetFileMetadataResponse, GetFileOptions, GetFileResponse, GenerateSignedPostPolicyV2Callback, GenerateSignedPostPolicyV2Options, GenerateSignedPostPolicyV2Response, GenerateSignedPostPolicyV4Callback, GenerateSignedPostPolicyV4Options, GenerateSignedPostPolicyV4Response, GetSignedUrlConfig, MakeFilePrivateCallback, MakeFilePrivateOptions, MakeFilePrivateResponse, MakeFilePublicCallback, MakeFilePublicResponse, MoveCallback, MoveOptions, MoveResponse, MoveFileAtomicOptions, MoveFileAtomicCallback, MoveFileAtomicResponse, PolicyDocument, PolicyFields, PredefinedAcl, RotateEncryptionKeyCallback, RotateEncryptionKeyOptions, RotateEncryptionKeyResponse, SaveCallback, SaveData, SaveOptions, SetFileMetadataCallback, SetFileMetadataOptions, SetFileMetadataResponse, SetStorageClassCallback, SetStorageClassOptions, SetStorageClassResponse, SignedPostPolicyV4Output, } from './file.js'; +export * from './hash-stream-validator.js'; +export { HmacKey, HmacKeyMetadata, HmacKeyMetadataCallback, HmacKeyMetadataResponse, SetHmacKeyMetadata, SetHmacKeyMetadataOptions, } from './hmacKey.js'; +export { GetPolicyCallback, GetPolicyOptions, GetPolicyResponse, Iam, Policy, SetPolicyCallback, SetPolicyOptions, SetPolicyResponse, TestIamPermissionsCallback, TestIamPermissionsOptions, TestIamPermissionsResponse, } from './iam.js'; +export { DeleteNotificationCallback, DeleteNotificationOptions, GetNotificationCallback, GetNotificationMetadataCallback, GetNotificationMetadataOptions, GetNotificationMetadataResponse, GetNotificationOptions, GetNotificationResponse, Notification, NotificationMetadata, } from './notification.js'; +export { GetSignedUrlCallback, GetSignedUrlResponse } from './signer.js'; +export * from './transfer-manager.js'; diff --git a/node_modules/@google-cloud/storage/build/esm/src/index.js b/node_modules/@google-cloud/storage/build/esm/src/index.js new file mode 100644 index 0000000..afb2bfc --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/index.js @@ -0,0 +1,68 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +/** + * The `@google-cloud/storage` package has a single named export which is the + * {@link Storage} (ES6) class, which should be instantiated with `new`. + * + * See {@link Storage} and {@link ClientConfig} for client methods and + * configuration options. + * + * @module {Storage} @google-cloud/storage + * @alias nodejs-storage + * + * @example + * Install the client library with npm: + * ``` + * npm install --save @google-cloud/storage + * ``` + * + * @example + * Import the client library + * ``` + * const {Storage} = require('@google-cloud/storage'); + * ``` + * + * @example + * Create a client that uses Application + * Default Credentials (ADC): + * ``` + * const storage = new Storage(); + * ``` + * + * @example + * Create a client with explicit + * credentials: + * ``` + * const storage = new Storage({ projectId: + * 'your-project-id', keyFilename: '/path/to/keyfile.json' + * }); + * ``` + * + * @example include:samples/quickstart.js + * region_tag:storage_quickstart + * Full quickstart example: + */ +export { ApiError } from './nodejs-common/index.js'; +export { IdempotencyStrategy, RETRYABLE_ERR_FN_DEFAULT, Storage, } from './storage.js'; +export { Bucket, } from './bucket.js'; +export * from './crc32c.js'; +export { Channel } from './channel.js'; +export { File, } from './file.js'; +export * from './hash-stream-validator.js'; +export { HmacKey, } from './hmacKey.js'; +export { Iam, } from './iam.js'; +export { Notification, } from './notification.js'; +export * from './transfer-manager.js'; diff --git a/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/index.d.ts b/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/index.d.ts new file mode 100644 index 0000000..72588c7 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/index.d.ts @@ -0,0 +1,19 @@ +/*! + * Copyright 2022 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. + */ +export { GoogleAuthOptions } from 'google-auth-library'; +export { Service, ServiceConfig, ServiceOptions, StreamRequestOptions, } from './service.js'; +export { BaseMetadata, DeleteCallback, ExistsCallback, GetConfig, InstanceResponseCallback, Interceptor, MetadataCallback, MetadataResponse, Methods, ResponseCallback, ServiceObject, ServiceObjectConfig, ServiceObjectParent, SetMetadataResponse, } from './service-object.js'; +export { Abortable, AbortableDuplex, ApiError, BodyResponseCallback, DecorateRequestOptions, ResponseBody, util, } from './util.js'; diff --git a/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/index.js b/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/index.js new file mode 100644 index 0000000..8056304 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/index.js @@ -0,0 +1,3 @@ +export { Service, } from './service.js'; +export { ServiceObject, } from './service-object.js'; +export { ApiError, util, } from './util.js'; diff --git a/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/service-object.d.ts b/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/service-object.d.ts new file mode 100644 index 0000000..108c0ce --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/service-object.d.ts @@ -0,0 +1,217 @@ +import { EventEmitter } from 'events'; +import * as r from 'teeny-request'; +import { ApiError, BodyResponseCallback, DecorateRequestOptions } from './util.js'; +export type RequestResponse = [unknown, r.Response]; +export interface ServiceObjectParent { + interceptors: Interceptor[]; + getRequestInterceptors(): Function[]; + requestStream(reqOpts: DecorateRequestOptions): r.Request; + request(reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void; +} +export interface Interceptor { + request(opts: r.Options): DecorateRequestOptions; +} +export type GetMetadataOptions = object; +export type MetadataResponse = [K, r.Response]; +export type MetadataCallback = (err: Error | null, metadata?: K, apiResponse?: r.Response) => void; +export type ExistsOptions = object; +export interface ExistsCallback { + (err: Error | null, exists?: boolean): void; +} +export interface ServiceObjectConfig { + /** + * The base URL to make API requests to. + */ + baseUrl?: string; + /** + * The method which creates this object. + */ + createMethod?: Function; + /** + * The identifier of the object. For example, the name of a Storage bucket or + * Pub/Sub topic. + */ + id?: string; + /** + * A map of each method name that should be inherited. + */ + methods?: Methods; + /** + * The parent service instance. For example, an instance of Storage if the + * object is Bucket. + */ + parent: ServiceObjectParent; + /** + * Override of projectId, used to allow access to resources in another project. + * For example, a BigQuery dataset in another project to which the user has been + * granted permission. + */ + projectId?: string; +} +export interface Methods { + [methodName: string]: { + reqOpts?: r.CoreOptions; + } | boolean; +} +export interface InstanceResponseCallback { + (err: ApiError | null, instance?: T | null, apiResponse?: r.Response): void; +} +export interface CreateOptions { +} +export type CreateResponse = any[]; +export interface CreateCallback { + (err: ApiError | null, instance?: T | null, ...args: any[]): void; +} +export type DeleteOptions = { + ignoreNotFound?: boolean; + ifGenerationMatch?: number | string; + ifGenerationNotMatch?: number | string; + ifMetagenerationMatch?: number | string; + ifMetagenerationNotMatch?: number | string; +} & object; +export interface DeleteCallback { + (err: Error | null, apiResponse?: r.Response): void; +} +export interface GetConfig { + /** + * Create the object if it doesn't already exist. + */ + autoCreate?: boolean; +} +export type GetOrCreateOptions = GetConfig & CreateOptions; +export type GetResponse = [T, r.Response]; +export interface ResponseCallback { + (err?: Error | null, apiResponse?: r.Response): void; +} +export type SetMetadataResponse = [K]; +export type SetMetadataOptions = object; +export interface BaseMetadata { + id?: string; + kind?: string; + etag?: string; + selfLink?: string; + [key: string]: unknown; +} +/** + * ServiceObject is a base class, meant to be inherited from by a "service + * object," like a BigQuery dataset or Storage bucket. + * + * Most of the time, these objects share common functionality; they can be + * created or deleted, and you can get or set their metadata. + * + * By inheriting from this class, a service object will be extended with these + * shared behaviors. Note that any method can be overridden when the service + * object requires specific behavior. + */ +declare class ServiceObject extends EventEmitter { + metadata: K; + baseUrl?: string; + parent: ServiceObjectParent; + id?: string; + private createMethod?; + protected methods: Methods; + interceptors: Interceptor[]; + projectId?: string; + constructor(config: ServiceObjectConfig); + /** + * Create the object. + * + * @param {object=} options - Configuration object. + * @param {function} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.instance - The instance. + * @param {object} callback.apiResponse - The full API response. + */ + create(options?: CreateOptions): Promise>; + create(options: CreateOptions, callback: CreateCallback): void; + create(callback: CreateCallback): void; + /** + * Delete the object. + * + * @param {function=} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.apiResponse - The full API response. + */ + delete(options?: DeleteOptions): Promise<[r.Response]>; + delete(options: DeleteOptions, callback: DeleteCallback): void; + delete(callback: DeleteCallback): void; + /** + * Check if the object exists. + * + * @param {function} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {boolean} callback.exists - Whether the object exists or not. + */ + exists(options?: ExistsOptions): Promise<[boolean]>; + exists(options: ExistsOptions, callback: ExistsCallback): void; + exists(callback: ExistsCallback): void; + /** + * Get the object if it exists. Optionally have the object created if an + * options object is provided with `autoCreate: true`. + * + * @param {object=} options - The configuration object that will be used to + * create the object if necessary. + * @param {boolean} options.autoCreate - Create the object if it doesn't already exist. + * @param {function} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.instance - The instance. + * @param {object} callback.apiResponse - The full API response. + */ + get(options?: GetOrCreateOptions): Promise>; + get(callback: InstanceResponseCallback): void; + get(options: GetOrCreateOptions, callback: InstanceResponseCallback): void; + /** + * Get the metadata of this object. + * + * @param {function} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.metadata - The metadata for this object. + * @param {object} callback.apiResponse - The full API response. + */ + getMetadata(options?: GetMetadataOptions): Promise>; + getMetadata(options: GetMetadataOptions, callback: MetadataCallback): void; + getMetadata(callback: MetadataCallback): void; + /** + * Return the user's custom request interceptors. + */ + getRequestInterceptors(): Function[]; + /** + * Set the metadata for this object. + * + * @param {object} metadata - The metadata to set on this object. + * @param {object=} options - Configuration options. + * @param {function=} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.apiResponse - The full API response. + */ + setMetadata(metadata: K, options?: SetMetadataOptions): Promise>; + setMetadata(metadata: K, callback: MetadataCallback): void; + setMetadata(metadata: K, options: SetMetadataOptions, callback: MetadataCallback): void; + /** + * Make an authenticated API request. + * + * @private + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + * @param {function} callback - The callback function passed to `request`. + */ + private request_; + /** + * Make an authenticated API request. + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + * @param {function} callback - The callback function passed to `request`. + */ + request(reqOpts: DecorateRequestOptions): Promise; + request(reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void; + /** + * Make an authenticated API request. + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + */ + requestStream(reqOpts: DecorateRequestOptions): r.Request; +} +export { ServiceObject }; diff --git a/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/service-object.js b/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/service-object.js new file mode 100644 index 0000000..b2dfa43 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/service-object.js @@ -0,0 +1,289 @@ +/*! + * Copyright 2022 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. + */ +import { promisifyAll } from '@google-cloud/promisify'; +import { EventEmitter } from 'events'; +import { util, } from './util.js'; +/** + * ServiceObject is a base class, meant to be inherited from by a "service + * object," like a BigQuery dataset or Storage bucket. + * + * Most of the time, these objects share common functionality; they can be + * created or deleted, and you can get or set their metadata. + * + * By inheriting from this class, a service object will be extended with these + * shared behaviors. Note that any method can be overridden when the service + * object requires specific behavior. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +class ServiceObject extends EventEmitter { + /* + * @constructor + * @alias module:common/service-object + * + * @private + * + * @param {object} config - Configuration object. + * @param {string} config.baseUrl - The base URL to make API requests to. + * @param {string} config.createMethod - The method which creates this object. + * @param {string=} config.id - The identifier of the object. For example, the + * name of a Storage bucket or Pub/Sub topic. + * @param {object=} config.methods - A map of each method name that should be inherited. + * @param {object} config.methods[].reqOpts - Default request options for this + * particular method. A common use case is when `setMetadata` requires a + * `PUT` method to override the default `PATCH`. + * @param {object} config.parent - The parent service instance. For example, an + * instance of Storage if the object is Bucket. + */ + constructor(config) { + super(); + this.metadata = {}; + this.baseUrl = config.baseUrl; + this.parent = config.parent; // Parent class. + this.id = config.id; // Name or ID (e.g. dataset ID, bucket name, etc). + this.createMethod = config.createMethod; + this.methods = config.methods || {}; + this.interceptors = []; + this.projectId = config.projectId; + if (config.methods) { + // This filters the ServiceObject instance (e.g. a "File") to only have + // the configured methods. We make a couple of exceptions for core- + // functionality ("request()" and "getRequestInterceptors()") + Object.getOwnPropertyNames(ServiceObject.prototype) + .filter(methodName => { + return ( + // All ServiceObjects need `request` and `getRequestInterceptors`. + // clang-format off + !/^request/.test(methodName) && + !/^getRequestInterceptors/.test(methodName) && + // clang-format on + // The ServiceObject didn't redefine the method. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this[methodName] === + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ServiceObject.prototype[methodName] && + // This method isn't wanted. + !config.methods[methodName]); + }) + .forEach(methodName => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this[methodName] = undefined; + }); + } + } + create(optionsOrCallback, callback) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const self = this; + const args = [this.id]; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + if (typeof optionsOrCallback === 'object') { + args.push(optionsOrCallback); + } + // Wrap the callback to return *this* instance of the object, not the + // newly-created one. + // tslint: disable-next-line no-any + function onCreate(...args) { + const [err, instance] = args; + if (!err) { + self.metadata = instance.metadata; + if (self.id && instance.metadata) { + self.id = instance.metadata.id; + } + args[1] = self; // replace the created `instance` with this one. + } + callback(...args); + } + args.push(onCreate); + // eslint-disable-next-line prefer-spread + this.createMethod.apply(null, args); + } + delete(optionsOrCallback, cb) { + var _a; + const [options, callback] = util.maybeOptionsOrCallback(optionsOrCallback, cb); + const ignoreNotFound = options.ignoreNotFound; + delete options.ignoreNotFound; + const methodConfig = (typeof this.methods.delete === 'object' && this.methods.delete) || {}; + const reqOpts = { + method: 'DELETE', + uri: '', + ...methodConfig.reqOpts, + qs: { + ...(_a = methodConfig.reqOpts) === null || _a === void 0 ? void 0 : _a.qs, + ...options, + }, + }; + // The `request` method may have been overridden to hold any special + // behavior. Ensure we call the original `request` method. + ServiceObject.prototype.request.call(this, reqOpts, (err, body, res) => { + if (err) { + if (err.code === 404 && ignoreNotFound) { + err = null; + } + } + callback(err, res); + }); + } + exists(optionsOrCallback, cb) { + const [options, callback] = util.maybeOptionsOrCallback(optionsOrCallback, cb); + this.get(options, err => { + if (err) { + if (err.code === 404) { + callback(null, false); + } + else { + callback(err); + } + return; + } + callback(null, true); + }); + } + get(optionsOrCallback, cb) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const self = this; + const [opts, callback] = util.maybeOptionsOrCallback(optionsOrCallback, cb); + const options = Object.assign({}, opts); + const autoCreate = options.autoCreate && typeof this.create === 'function'; + delete options.autoCreate; + function onCreate(err, instance, apiResponse) { + if (err) { + if (err.code === 409) { + self.get(options, callback); + return; + } + callback(err, null, apiResponse); + return; + } + callback(null, instance, apiResponse); + } + this.getMetadata(options, (err, metadata) => { + if (err) { + if (err.code === 404 && autoCreate) { + const args = []; + if (Object.keys(options).length > 0) { + args.push(options); + } + args.push(onCreate); + self.create(...args); + return; + } + callback(err, null, metadata); + return; + } + callback(null, self, metadata); + }); + } + getMetadata(optionsOrCallback, cb) { + var _a; + const [options, callback] = util.maybeOptionsOrCallback(optionsOrCallback, cb); + const methodConfig = (typeof this.methods.getMetadata === 'object' && + this.methods.getMetadata) || + {}; + const reqOpts = { + uri: '', + ...methodConfig.reqOpts, + qs: { + ...(_a = methodConfig.reqOpts) === null || _a === void 0 ? void 0 : _a.qs, + ...options, + }, + }; + // The `request` method may have been overridden to hold any special + // behavior. Ensure we call the original `request` method. + ServiceObject.prototype.request.call(this, reqOpts, (err, body, res) => { + this.metadata = body; + callback(err, this.metadata, res); + }); + } + /** + * Return the user's custom request interceptors. + */ + getRequestInterceptors() { + // Interceptors should be returned in the order they were assigned. + const localInterceptors = this.interceptors + .filter(interceptor => typeof interceptor.request === 'function') + .map(interceptor => interceptor.request); + return this.parent.getRequestInterceptors().concat(localInterceptors); + } + setMetadata(metadata, optionsOrCallback, cb) { + var _a, _b; + const [options, callback] = util.maybeOptionsOrCallback(optionsOrCallback, cb); + const methodConfig = (typeof this.methods.setMetadata === 'object' && + this.methods.setMetadata) || + {}; + const reqOpts = { + method: 'PATCH', + uri: '', + ...methodConfig.reqOpts, + json: { + ...(_a = methodConfig.reqOpts) === null || _a === void 0 ? void 0 : _a.json, + ...metadata, + }, + qs: { + ...(_b = methodConfig.reqOpts) === null || _b === void 0 ? void 0 : _b.qs, + ...options, + }, + }; + // The `request` method may have been overridden to hold any special + // behavior. Ensure we call the original `request` method. + ServiceObject.prototype.request.call(this, reqOpts, (err, body, res) => { + this.metadata = body; + callback(err, this.metadata, res); + }); + } + request_(reqOpts, callback) { + reqOpts = { ...reqOpts }; + if (this.projectId) { + reqOpts.projectId = this.projectId; + } + const isAbsoluteUrl = reqOpts.uri.indexOf('http') === 0; + const uriComponents = [this.baseUrl, this.id || '', reqOpts.uri]; + if (isAbsoluteUrl) { + uriComponents.splice(0, uriComponents.indexOf(reqOpts.uri)); + } + reqOpts.uri = uriComponents + .filter(x => x.trim()) // Limit to non-empty strings. + .map(uriComponent => { + const trimSlashesRegex = /^\/*|\/*$/g; + return uriComponent.replace(trimSlashesRegex, ''); + }) + .join('/'); + const childInterceptors = Array.isArray(reqOpts.interceptors_) + ? reqOpts.interceptors_ + : []; + const localInterceptors = [].slice.call(this.interceptors); + reqOpts.interceptors_ = childInterceptors.concat(localInterceptors); + if (reqOpts.shouldReturnStream) { + return this.parent.requestStream(reqOpts); + } + this.parent.request(reqOpts, callback); + } + request(reqOpts, callback) { + this.request_(reqOpts, callback); + } + /** + * Make an authenticated API request. + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + */ + requestStream(reqOpts) { + const opts = { ...reqOpts, shouldReturnStream: true }; + return this.request_(opts); + } +} +promisifyAll(ServiceObject, { exclude: ['getRequestInterceptors'] }); +export { ServiceObject }; diff --git a/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/service.d.ts b/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/service.d.ts new file mode 100644 index 0000000..073c180 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/service.d.ts @@ -0,0 +1,130 @@ +/*! + * Copyright 2022 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. + */ +import { AuthClient, GoogleAuth, GoogleAuthOptions } from 'google-auth-library'; +import * as r from 'teeny-request'; +import { Interceptor } from './service-object.js'; +import { BodyResponseCallback, DecorateRequestOptions, MakeAuthenticatedRequest, PackageJson } from './util.js'; +export declare const DEFAULT_PROJECT_ID_TOKEN = "{{projectId}}"; +export interface StreamRequestOptions extends DecorateRequestOptions { + shouldReturnStream: true; +} +export interface ServiceConfig { + /** + * The base URL to make API requests to. + */ + baseUrl: string; + /** + * The API Endpoint to use when connecting to the service. + * Example: storage.googleapis.com + */ + apiEndpoint: string; + /** + * The scopes required for the request. + */ + scopes: string[]; + projectIdRequired?: boolean; + packageJson: PackageJson; + /** + * Reuse an existing `AuthClient` or `GoogleAuth` client instead of creating a new one. + */ + authClient?: AuthClient | GoogleAuth; + /** + * Set to true if the endpoint is a custom URL + */ + customEndpoint?: boolean; + /** + * Controls whether or not to use authentication when using a custom endpoint. + */ + useAuthWithCustomEndpoint?: boolean; +} +export interface ServiceOptions extends Omit { + authClient?: AuthClient | GoogleAuth; + interceptors_?: Interceptor[]; + email?: string; + token?: string; + timeout?: number; + userAgent?: string; + useAuthWithCustomEndpoint?: boolean; +} +export declare class Service { + baseUrl: string; + private globalInterceptors; + interceptors: Interceptor[]; + private packageJson; + projectId: string; + private projectIdRequired; + providedUserAgent?: string; + makeAuthenticatedRequest: MakeAuthenticatedRequest; + authClient: GoogleAuth; + apiEndpoint: string; + timeout?: number; + universeDomain: string; + customEndpoint: boolean; + useAuthWithCustomEndpoint?: boolean; + /** + * Service is a base class, meant to be inherited from by a "service," like + * BigQuery or Storage. + * + * This handles making authenticated requests by exposing a `makeReq_` + * function. + * + * @constructor + * @alias module:common/service + * + * @param {object} config - Configuration object. + * @param {string} config.baseUrl - The base URL to make API requests to. + * @param {string[]} config.scopes - The scopes required for the request. + * @param {object=} options - [Configuration object](#/docs). + */ + constructor(config: ServiceConfig, options?: ServiceOptions); + /** + * Return the user's custom request interceptors. + */ + getRequestInterceptors(): Function[]; + /** + * Get and update the Service's project ID. + * + * @param {function} callback - The callback function. + */ + getProjectId(): Promise; + getProjectId(callback: (err: Error | null, projectId?: string) => void): void; + protected getProjectIdAsync(): Promise; + /** + * Make an authenticated API request. + * + * @private + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + * @param {function} callback - The callback function passed to `request`. + */ + private request_; + /** + * Make an authenticated API request. + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + * @param {function} callback - The callback function passed to `request`. + */ + request(reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void; + /** + * Make an authenticated API request. + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + */ + requestStream(reqOpts: DecorateRequestOptions): r.Request; +} diff --git a/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/service.js b/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/service.js new file mode 100644 index 0000000..b584795 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/service.js @@ -0,0 +1,182 @@ +/*! + * Copyright 2022 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. + */ +import { DEFAULT_UNIVERSE, } from 'google-auth-library'; +import * as uuid from 'uuid'; +import { GCCL_GCS_CMD_KEY, util, } from './util.js'; +import { getRuntimeTrackingString, getUserAgentString, getModuleFormat, } from '../util.js'; +export const DEFAULT_PROJECT_ID_TOKEN = '{{projectId}}'; +export class Service { + /** + * Service is a base class, meant to be inherited from by a "service," like + * BigQuery or Storage. + * + * This handles making authenticated requests by exposing a `makeReq_` + * function. + * + * @constructor + * @alias module:common/service + * + * @param {object} config - Configuration object. + * @param {string} config.baseUrl - The base URL to make API requests to. + * @param {string[]} config.scopes - The scopes required for the request. + * @param {object=} options - [Configuration object](#/docs). + */ + constructor(config, options = {}) { + this.baseUrl = config.baseUrl; + this.apiEndpoint = config.apiEndpoint; + this.timeout = options.timeout; + this.globalInterceptors = Array.isArray(options.interceptors_) + ? options.interceptors_ + : []; + this.interceptors = []; + this.packageJson = config.packageJson; + this.projectId = options.projectId || DEFAULT_PROJECT_ID_TOKEN; + this.projectIdRequired = config.projectIdRequired !== false; + this.providedUserAgent = options.userAgent; + this.universeDomain = options.universeDomain || DEFAULT_UNIVERSE; + this.customEndpoint = config.customEndpoint || false; + this.useAuthWithCustomEndpoint = config.useAuthWithCustomEndpoint; + this.makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory({ + ...config, + projectIdRequired: this.projectIdRequired, + projectId: this.projectId, + authClient: options.authClient || config.authClient, + credentials: options.credentials, + keyFile: options.keyFilename, + email: options.email, + clientOptions: { + universeDomain: options.universeDomain, + ...options.clientOptions, + }, + }); + this.authClient = this.makeAuthenticatedRequest.authClient; + const isCloudFunctionEnv = !!process.env.FUNCTION_NAME; + if (isCloudFunctionEnv) { + this.interceptors.push({ + request(reqOpts) { + reqOpts.forever = false; + return reqOpts; + }, + }); + } + } + /** + * Return the user's custom request interceptors. + */ + getRequestInterceptors() { + // Interceptors should be returned in the order they were assigned. + return [].slice + .call(this.globalInterceptors) + .concat(this.interceptors) + .filter(interceptor => typeof interceptor.request === 'function') + .map(interceptor => interceptor.request); + } + getProjectId(callback) { + if (!callback) { + return this.getProjectIdAsync(); + } + this.getProjectIdAsync().then(p => callback(null, p), callback); + } + async getProjectIdAsync() { + const projectId = await this.authClient.getProjectId(); + if (this.projectId === DEFAULT_PROJECT_ID_TOKEN && projectId) { + this.projectId = projectId; + } + return this.projectId; + } + request_(reqOpts, callback) { + reqOpts = { ...reqOpts, timeout: this.timeout }; + const isAbsoluteUrl = reqOpts.uri.indexOf('http') === 0; + const uriComponents = [this.baseUrl]; + if (this.projectIdRequired) { + if (reqOpts.projectId) { + uriComponents.push('projects'); + uriComponents.push(reqOpts.projectId); + } + else { + uriComponents.push('projects'); + uriComponents.push(this.projectId); + } + } + uriComponents.push(reqOpts.uri); + if (isAbsoluteUrl) { + uriComponents.splice(0, uriComponents.indexOf(reqOpts.uri)); + } + reqOpts.uri = uriComponents + .map(uriComponent => { + const trimSlashesRegex = /^\/*|\/*$/g; + return uriComponent.replace(trimSlashesRegex, ''); + }) + .join('/') + // Some URIs have colon separators. + // Bad: https://.../projects/:list + // Good: https://.../projects:list + .replace(/\/:/g, ':'); + const requestInterceptors = this.getRequestInterceptors(); + const interceptorArray = Array.isArray(reqOpts.interceptors_) + ? reqOpts.interceptors_ + : []; + interceptorArray.forEach(interceptor => { + if (typeof interceptor.request === 'function') { + requestInterceptors.push(interceptor.request); + } + }); + requestInterceptors.forEach(requestInterceptor => { + reqOpts = requestInterceptor(reqOpts); + }); + delete reqOpts.interceptors_; + const pkg = this.packageJson; + let userAgent = getUserAgentString(); + if (this.providedUserAgent) { + userAgent = `${this.providedUserAgent} ${userAgent}`; + } + reqOpts.headers = { + ...reqOpts.headers, + 'User-Agent': userAgent, + 'x-goog-api-client': `${getRuntimeTrackingString()} gccl/${pkg.version}-${getModuleFormat()} gccl-invocation-id/${uuid.v4()}`, + }; + if (reqOpts[GCCL_GCS_CMD_KEY]) { + reqOpts.headers['x-goog-api-client'] += + ` gccl-gcs-cmd/${reqOpts[GCCL_GCS_CMD_KEY]}`; + } + if (reqOpts.shouldReturnStream) { + return this.makeAuthenticatedRequest(reqOpts); + } + else { + this.makeAuthenticatedRequest(reqOpts, callback); + } + } + /** + * Make an authenticated API request. + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + * @param {function} callback - The callback function passed to `request`. + */ + request(reqOpts, callback) { + Service.prototype.request_.call(this, reqOpts, callback); + } + /** + * Make an authenticated API request. + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + */ + requestStream(reqOpts) { + const opts = { ...reqOpts, shouldReturnStream: true }; + return Service.prototype.request_.call(this, opts); + } +} diff --git a/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/util.d.ts b/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/util.d.ts new file mode 100644 index 0000000..a4a4380 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/util.d.ts @@ -0,0 +1,333 @@ +/*! + * Copyright 2022 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. + */ +import { AuthClient, GoogleAuth, GoogleAuthOptions } from 'google-auth-library'; +import { CredentialBody } from 'google-auth-library'; +import * as r from 'teeny-request'; +import { Duplex, DuplexOptions, Readable, Writable } from 'stream'; +import { Interceptor } from './service-object.js'; +/** + * A unique symbol for providing a `gccl-gcs-cmd` value + * for the `X-Goog-API-Client` header. + * + * E.g. the `V` in `X-Goog-API-Client: gccl-gcs-cmd/V` + **/ +export declare const GCCL_GCS_CMD_KEY: unique symbol; +export type ResponseBody = any; +export interface DuplexifyOptions extends DuplexOptions { + autoDestroy?: boolean; + end?: boolean; +} +export interface Duplexify extends Duplex { + readonly destroyed: boolean; + setWritable(writable: Writable | false | null): void; + setReadable(readable: Readable | false | null): void; +} +export interface DuplexifyConstructor { + obj(writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify; + new (writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify; + (writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify; +} +export interface ParsedHttpRespMessage { + resp: r.Response; + err?: ApiError; +} +export interface MakeAuthenticatedRequest { + (reqOpts: DecorateRequestOptions): Duplexify; + (reqOpts: DecorateRequestOptions, options?: MakeAuthenticatedRequestOptions): void | Abortable; + (reqOpts: DecorateRequestOptions, callback?: BodyResponseCallback): void | Abortable; + (reqOpts: DecorateRequestOptions, optionsOrCallback?: MakeAuthenticatedRequestOptions | BodyResponseCallback): void | Abortable | Duplexify; + getCredentials: (callback: (err?: Error | null, credentials?: CredentialBody) => void) => void; + authClient: GoogleAuth; +} +export interface Abortable { + abort(): void; +} +export type AbortableDuplex = Duplexify & Abortable; +export interface PackageJson { + name: string; + version: string; +} +export interface MakeAuthenticatedRequestFactoryConfig extends Omit { + /** + * Automatically retry requests if the response is related to rate limits or + * certain intermittent server errors. We will exponentially backoff + * subsequent requests by default. (default: true) + */ + autoRetry?: boolean; + /** + * If true, just return the provided request options. Default: false. + */ + customEndpoint?: boolean; + /** + * If true, will authenticate when using a custom endpoint. Default: false. + */ + useAuthWithCustomEndpoint?: boolean; + /** + * Account email address, required for PEM/P12 usage. + */ + email?: string; + /** + * Maximum number of automatic retries attempted before returning the error. + * (default: 3) + */ + maxRetries?: number; + stream?: Duplexify; + /** + * A pre-instantiated `AuthClient` or `GoogleAuth` client that should be used. + * A new client will be created if this is not set. + */ + authClient?: AuthClient | GoogleAuth; + /** + * Determines if a projectId is required for authenticated requests. Defaults to `true`. + */ + projectIdRequired?: boolean; +} +export interface MakeAuthenticatedRequestOptions { + onAuthenticated: OnAuthenticatedCallback; +} +export interface OnAuthenticatedCallback { + (err: Error | null, reqOpts?: DecorateRequestOptions): void; +} +export interface GoogleErrorBody { + code: number; + errors?: GoogleInnerError[]; + response: r.Response; + message?: string; +} +export interface GoogleInnerError { + reason?: string; + message?: string; +} +export interface MakeWritableStreamOptions { + /** + * A connection instance used to get a token with and send the request + * through. + */ + connection?: {}; + /** + * Metadata to send at the head of the request. + */ + metadata?: { + contentType?: string; + }; + /** + * Request object, in the format of a standard Node.js http.request() object. + */ + request?: r.Options; + makeAuthenticatedRequest(reqOpts: r.OptionsWithUri & { + [GCCL_GCS_CMD_KEY]?: string; + }, fnobj: { + onAuthenticated(err: Error | null, authenticatedReqOpts?: r.Options): void; + }): void; +} +export interface DecorateRequestOptions extends r.CoreOptions { + autoPaginate?: boolean; + autoPaginateVal?: boolean; + objectMode?: boolean; + maxRetries?: number; + uri: string; + interceptors_?: Interceptor[]; + shouldReturnStream?: boolean; + projectId?: string; + [GCCL_GCS_CMD_KEY]?: string; +} +export interface ParsedHttpResponseBody { + body: ResponseBody; + err?: Error; +} +/** + * Custom error type for API errors. + * + * @param {object} errorBody - Error object. + */ +export declare class ApiError extends Error { + code?: number; + errors?: GoogleInnerError[]; + response?: r.Response; + constructor(errorMessage: string); + constructor(errorBody: GoogleErrorBody); + /** + * Pieces together an error message by combining all unique error messages + * returned from a single GoogleError + * + * @private + * + * @param {GoogleErrorBody} err The original error. + * @param {GoogleInnerError[]} [errors] Inner errors, if any. + * @returns {string} + */ + static createMultiErrorMessage(err: GoogleErrorBody, errors?: GoogleInnerError[]): string; +} +/** + * Custom error type for partial errors returned from the API. + * + * @param {object} b - Error object. + */ +export declare class PartialFailureError extends Error { + errors?: GoogleInnerError[]; + response?: r.Response; + constructor(b: GoogleErrorBody); +} +export interface BodyResponseCallback { + (err: Error | ApiError | null, body?: ResponseBody, res?: r.Response): void; +} +export interface RetryOptions { + retryDelayMultiplier?: number; + totalTimeout?: number; + maxRetryDelay?: number; + autoRetry?: boolean; + maxRetries?: number; + retryableErrorFn?: (err: ApiError) => boolean; +} +export interface MakeRequestConfig { + /** + * Automatically retry requests if the response is related to rate limits or + * certain intermittent server errors. We will exponentially backoff + * subsequent requests by default. (default: true) + */ + autoRetry?: boolean; + /** + * Maximum number of automatic retries attempted before returning the error. + * (default: 3) + */ + maxRetries?: number; + retries?: number; + retryOptions?: RetryOptions; + stream?: Duplexify; + shouldRetryFn?: (response?: r.Response) => boolean; +} +export declare class Util { + ApiError: typeof ApiError; + PartialFailureError: typeof PartialFailureError; + /** + * No op. + * + * @example + * function doSomething(callback) { + * callback = callback || noop; + * } + */ + noop(): void; + /** + * Uniformly process an API response. + * + * @param {*} err - Error value. + * @param {*} resp - Response value. + * @param {*} body - Body value. + * @param {function} callback - The callback function. + */ + handleResp(err: Error | null, resp?: r.Response | null, body?: ResponseBody, callback?: BodyResponseCallback): void; + /** + * Sniff an incoming HTTP response message for errors. + * + * @param {object} httpRespMessage - An incoming HTTP response message from `request`. + * @return {object} parsedHttpRespMessage - The parsed response. + * @param {?error} parsedHttpRespMessage.err - An error detected. + * @param {object} parsedHttpRespMessage.resp - The original response object. + */ + parseHttpRespMessage(httpRespMessage: r.Response): ParsedHttpRespMessage; + /** + * Parse the response body from an HTTP request. + * + * @param {object} body - The response body. + * @return {object} parsedHttpRespMessage - The parsed response. + * @param {?error} parsedHttpRespMessage.err - An error detected. + * @param {object} parsedHttpRespMessage.body - The original body value provided + * will try to be JSON.parse'd. If it's successful, the parsed value will + * be returned here, otherwise the original value and an error will be returned. + */ + parseHttpRespBody(body: ResponseBody): ParsedHttpResponseBody; + /** + * Take a Duplexify stream, fetch an authenticated connection header, and + * create an outgoing writable stream. + * + * @param {Duplexify} dup - Duplexify stream. + * @param {object} options - Configuration object. + * @param {module:common/connection} options.connection - A connection instance used to get a token with and send the request through. + * @param {object} options.metadata - Metadata to send at the head of the request. + * @param {object} options.request - Request object, in the format of a standard Node.js http.request() object. + * @param {string=} options.request.method - Default: "POST". + * @param {string=} options.request.qs.uploadType - Default: "multipart". + * @param {string=} options.streamContentType - Default: "application/octet-stream". + * @param {function} onComplete - Callback, executed after the writable Request stream has completed. + */ + makeWritableStream(dup: Duplexify, options: MakeWritableStreamOptions, onComplete?: Function): void; + /** + * Returns true if the API request should be retried, given the error that was + * given the first time the request was attempted. This is used for rate limit + * related errors as well as intermittent server errors. + * + * @param {error} err - The API error to check if it is appropriate to retry. + * @return {boolean} True if the API request should be retried, false otherwise. + */ + shouldRetryRequest(err?: ApiError): boolean; + /** + * Get a function for making authenticated requests. + * + * @param {object} config - Configuration object. + * @param {boolean=} config.autoRetry - Automatically retry requests if the + * response is related to rate limits or certain intermittent server + * errors. We will exponentially backoff subsequent requests by default. + * (default: true) + * @param {object=} config.credentials - Credentials object. + * @param {boolean=} config.customEndpoint - If true, just return the provided request options. Default: false. + * @param {boolean=} config.useAuthWithCustomEndpoint - If true, will authenticate when using a custom endpoint. Default: false. + * @param {string=} config.email - Account email address, required for PEM/P12 usage. + * @param {number=} config.maxRetries - Maximum number of automatic retries attempted before returning the error. (default: 3) + * @param {string=} config.keyFile - Path to a .json, .pem, or .p12 keyfile. + * @param {array} config.scopes - Array of scopes required for the API. + */ + makeAuthenticatedRequestFactory(config: MakeAuthenticatedRequestFactoryConfig): MakeAuthenticatedRequest; + /** + * Make a request through the `retryRequest` module with built-in error + * handling and exponential back off. + * + * @param {object} reqOpts - Request options in the format `request` expects. + * @param {object=} config - Configuration object. + * @param {boolean=} config.autoRetry - Automatically retry requests if the + * response is related to rate limits or certain intermittent server + * errors. We will exponentially backoff subsequent requests by default. + * (default: true) + * @param {number=} config.maxRetries - Maximum number of automatic retries + * attempted before returning the error. (default: 3) + * @param {object=} config.request - HTTP module for request calls. + * @param {function} callback - The callback function. + */ + makeRequest(reqOpts: DecorateRequestOptions, config: MakeRequestConfig, callback: BodyResponseCallback): void | Abortable; + /** + * Decorate the options about to be made in a request. + * + * @param {object} reqOpts - The options to be passed to `request`. + * @param {string} projectId - The project ID. + * @return {object} reqOpts - The decorated reqOpts. + */ + decorateRequest(reqOpts: DecorateRequestOptions, projectId: string): DecorateRequestOptions; + isCustomType(unknown: any, module: string): boolean; + /** + * Given two parameters, figure out if this is either: + * - Just a callback function + * - An options object, and then a callback function + * @param optionsOrCallback An options object or callback. + * @param cb A potentially undefined callback. + */ + maybeOptionsOrCallback void>(optionsOrCallback?: T | C, cb?: C): [T, C]; + _getDefaultHeaders(gcclGcsCmd?: string): { + 'User-Agent': string; + 'x-goog-api-client': string; + }; +} +declare const util: Util; +export { util }; diff --git a/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/util.js b/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/util.js new file mode 100644 index 0000000..9dde092 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/nodejs-common/util.js @@ -0,0 +1,669 @@ +/*! + * Copyright 2022 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. + */ +/*! + * @module common/util + */ +import { replaceProjectIdToken, MissingProjectIdError, } from '@google-cloud/projectify'; +import * as htmlEntities from 'html-entities'; +import { GoogleAuth } from 'google-auth-library'; +import retryRequest from 'retry-request'; +import { Transform } from 'stream'; +import { teenyRequest } from 'teeny-request'; +import * as uuid from 'uuid'; +import { DEFAULT_PROJECT_ID_TOKEN } from './service.js'; +import { getModuleFormat, getRuntimeTrackingString, getUserAgentString, } from '../util.js'; +import duplexify from 'duplexify'; +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore +import { getPackageJSON } from '../package-json-helper.cjs'; +const packageJson = getPackageJSON(); +/** + * A unique symbol for providing a `gccl-gcs-cmd` value + * for the `X-Goog-API-Client` header. + * + * E.g. the `V` in `X-Goog-API-Client: gccl-gcs-cmd/V` + **/ +export const GCCL_GCS_CMD_KEY = Symbol.for('GCCL_GCS_CMD'); +const requestDefaults = { + timeout: 60000, + gzip: true, + forever: true, + pool: { + maxSockets: Infinity, + }, +}; +/** + * Default behavior: Automatically retry retriable server errors. + * + * @const {boolean} + * @private + */ +const AUTO_RETRY_DEFAULT = true; +/** + * Default behavior: Only attempt to retry retriable errors 3 times. + * + * @const {number} + * @private + */ +const MAX_RETRY_DEFAULT = 3; +/** + * Custom error type for API errors. + * + * @param {object} errorBody - Error object. + */ +export class ApiError extends Error { + constructor(errorBodyOrMessage) { + super(); + if (typeof errorBodyOrMessage !== 'object') { + this.message = errorBodyOrMessage || ''; + return; + } + const errorBody = errorBodyOrMessage; + this.code = errorBody.code; + this.errors = errorBody.errors; + this.response = errorBody.response; + try { + this.errors = JSON.parse(this.response.body).error.errors; + } + catch (e) { + this.errors = errorBody.errors; + } + this.message = ApiError.createMultiErrorMessage(errorBody, this.errors); + Error.captureStackTrace(this); + } + /** + * Pieces together an error message by combining all unique error messages + * returned from a single GoogleError + * + * @private + * + * @param {GoogleErrorBody} err The original error. + * @param {GoogleInnerError[]} [errors] Inner errors, if any. + * @returns {string} + */ + static createMultiErrorMessage(err, errors) { + const messages = new Set(); + if (err.message) { + messages.add(err.message); + } + if (errors && errors.length) { + errors.forEach(({ message }) => messages.add(message)); + } + else if (err.response && err.response.body) { + messages.add(htmlEntities.decode(err.response.body.toString())); + } + else if (!err.message) { + messages.add('A failure occurred during this request.'); + } + let messageArr = Array.from(messages); + if (messageArr.length > 1) { + messageArr = messageArr.map((message, i) => ` ${i + 1}. ${message}`); + messageArr.unshift('Multiple errors occurred during the request. Please see the `errors` array for complete details.\n'); + messageArr.push('\n'); + } + return messageArr.join('\n'); + } +} +/** + * Custom error type for partial errors returned from the API. + * + * @param {object} b - Error object. + */ +export class PartialFailureError extends Error { + constructor(b) { + super(); + const errorObject = b; + this.errors = errorObject.errors; + this.name = 'PartialFailureError'; + this.response = errorObject.response; + this.message = ApiError.createMultiErrorMessage(errorObject, this.errors); + } +} +export class Util { + constructor() { + this.ApiError = ApiError; + this.PartialFailureError = PartialFailureError; + } + /** + * No op. + * + * @example + * function doSomething(callback) { + * callback = callback || noop; + * } + */ + noop() { } + /** + * Uniformly process an API response. + * + * @param {*} err - Error value. + * @param {*} resp - Response value. + * @param {*} body - Body value. + * @param {function} callback - The callback function. + */ + handleResp(err, resp, body, callback) { + callback = callback || util.noop; + const parsedResp = { + err: err || null, + ...(resp && util.parseHttpRespMessage(resp)), + ...(body && util.parseHttpRespBody(body)), + }; + // Assign the parsed body to resp.body, even if { json: false } was passed + // as a request option. + // We assume that nobody uses the previously unparsed value of resp.body. + if (!parsedResp.err && resp && typeof parsedResp.body === 'object') { + parsedResp.resp.body = parsedResp.body; + } + if (parsedResp.err && resp) { + parsedResp.err.response = resp; + } + callback(parsedResp.err, parsedResp.body, parsedResp.resp); + } + /** + * Sniff an incoming HTTP response message for errors. + * + * @param {object} httpRespMessage - An incoming HTTP response message from `request`. + * @return {object} parsedHttpRespMessage - The parsed response. + * @param {?error} parsedHttpRespMessage.err - An error detected. + * @param {object} parsedHttpRespMessage.resp - The original response object. + */ + parseHttpRespMessage(httpRespMessage) { + const parsedHttpRespMessage = { + resp: httpRespMessage, + }; + if (httpRespMessage.statusCode < 200 || httpRespMessage.statusCode > 299) { + // Unknown error. Format according to ApiError standard. + parsedHttpRespMessage.err = new ApiError({ + errors: new Array(), + code: httpRespMessage.statusCode, + message: httpRespMessage.statusMessage, + response: httpRespMessage, + }); + } + return parsedHttpRespMessage; + } + /** + * Parse the response body from an HTTP request. + * + * @param {object} body - The response body. + * @return {object} parsedHttpRespMessage - The parsed response. + * @param {?error} parsedHttpRespMessage.err - An error detected. + * @param {object} parsedHttpRespMessage.body - The original body value provided + * will try to be JSON.parse'd. If it's successful, the parsed value will + * be returned here, otherwise the original value and an error will be returned. + */ + parseHttpRespBody(body) { + const parsedHttpRespBody = { + body, + }; + if (typeof body === 'string') { + try { + parsedHttpRespBody.body = JSON.parse(body); + } + catch (err) { + parsedHttpRespBody.body = body; + } + } + if (parsedHttpRespBody.body && parsedHttpRespBody.body.error) { + // Error from JSON API. + parsedHttpRespBody.err = new ApiError(parsedHttpRespBody.body.error); + } + return parsedHttpRespBody; + } + /** + * Take a Duplexify stream, fetch an authenticated connection header, and + * create an outgoing writable stream. + * + * @param {Duplexify} dup - Duplexify stream. + * @param {object} options - Configuration object. + * @param {module:common/connection} options.connection - A connection instance used to get a token with and send the request through. + * @param {object} options.metadata - Metadata to send at the head of the request. + * @param {object} options.request - Request object, in the format of a standard Node.js http.request() object. + * @param {string=} options.request.method - Default: "POST". + * @param {string=} options.request.qs.uploadType - Default: "multipart". + * @param {string=} options.streamContentType - Default: "application/octet-stream". + * @param {function} onComplete - Callback, executed after the writable Request stream has completed. + */ + makeWritableStream(dup, options, onComplete) { + var _a; + onComplete = onComplete || util.noop; + const writeStream = new ProgressStream(); + writeStream.on('progress', evt => dup.emit('progress', evt)); + dup.setWritable(writeStream); + const defaultReqOpts = { + method: 'POST', + qs: { + uploadType: 'multipart', + }, + timeout: 0, + maxRetries: 0, + }; + const metadata = options.metadata || {}; + const reqOpts = { + ...defaultReqOpts, + ...options.request, + qs: { + ...defaultReqOpts.qs, + ...(_a = options.request) === null || _a === void 0 ? void 0 : _a.qs, + }, + multipart: [ + { + 'Content-Type': 'application/json', + body: JSON.stringify(metadata), + }, + { + 'Content-Type': metadata.contentType || 'application/octet-stream', + body: writeStream, + }, + ], + }; + options.makeAuthenticatedRequest(reqOpts, { + onAuthenticated(err, authenticatedReqOpts) { + if (err) { + dup.destroy(err); + return; + } + requestDefaults.headers = util._getDefaultHeaders(reqOpts[GCCL_GCS_CMD_KEY]); + const request = teenyRequest.defaults(requestDefaults); + request(authenticatedReqOpts, (err, resp, body) => { + util.handleResp(err, resp, body, (err, data) => { + if (err) { + dup.destroy(err); + return; + } + dup.emit('response', resp); + onComplete(data); + }); + }); + }, + }); + } + /** + * Returns true if the API request should be retried, given the error that was + * given the first time the request was attempted. This is used for rate limit + * related errors as well as intermittent server errors. + * + * @param {error} err - The API error to check if it is appropriate to retry. + * @return {boolean} True if the API request should be retried, false otherwise. + */ + shouldRetryRequest(err) { + if (err) { + if ([408, 429, 500, 502, 503, 504].indexOf(err.code) !== -1) { + return true; + } + if (err.errors) { + for (const e of err.errors) { + const reason = e.reason; + if (reason === 'rateLimitExceeded') { + return true; + } + if (reason === 'userRateLimitExceeded') { + return true; + } + if (reason && reason.includes('EAI_AGAIN')) { + return true; + } + } + } + } + return false; + } + /** + * Get a function for making authenticated requests. + * + * @param {object} config - Configuration object. + * @param {boolean=} config.autoRetry - Automatically retry requests if the + * response is related to rate limits or certain intermittent server + * errors. We will exponentially backoff subsequent requests by default. + * (default: true) + * @param {object=} config.credentials - Credentials object. + * @param {boolean=} config.customEndpoint - If true, just return the provided request options. Default: false. + * @param {boolean=} config.useAuthWithCustomEndpoint - If true, will authenticate when using a custom endpoint. Default: false. + * @param {string=} config.email - Account email address, required for PEM/P12 usage. + * @param {number=} config.maxRetries - Maximum number of automatic retries attempted before returning the error. (default: 3) + * @param {string=} config.keyFile - Path to a .json, .pem, or .p12 keyfile. + * @param {array} config.scopes - Array of scopes required for the API. + */ + makeAuthenticatedRequestFactory(config) { + const googleAutoAuthConfig = { ...config }; + if (googleAutoAuthConfig.projectId === DEFAULT_PROJECT_ID_TOKEN) { + delete googleAutoAuthConfig.projectId; + } + let authClient; + if (googleAutoAuthConfig.authClient instanceof GoogleAuth) { + // Use an existing `GoogleAuth` + authClient = googleAutoAuthConfig.authClient; + } + else { + // Pass an `AuthClient` & `clientOptions` to `GoogleAuth`, if available + authClient = new GoogleAuth({ + ...googleAutoAuthConfig, + authClient: googleAutoAuthConfig.authClient, + clientOptions: googleAutoAuthConfig.clientOptions, + }); + } + function makeAuthenticatedRequest(reqOpts, optionsOrCallback) { + let stream; + let projectId; + const reqConfig = { ...config }; + let activeRequest_; + if (!optionsOrCallback) { + stream = duplexify(); + reqConfig.stream = stream; + } + const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : undefined; + const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : undefined; + async function setProjectId() { + projectId = await authClient.getProjectId(); + } + const onAuthenticated = async (err, authenticatedReqOpts) => { + const authLibraryError = err; + const autoAuthFailed = err && + typeof err.message === 'string' && + err.message.indexOf('Could not load the default credentials') > -1; + if (autoAuthFailed) { + // Even though authentication failed, the API might not actually + // care. + authenticatedReqOpts = reqOpts; + } + if (!err || autoAuthFailed) { + try { + // Try with existing `projectId` value + authenticatedReqOpts = util.decorateRequest(authenticatedReqOpts, projectId); + err = null; + } + catch (e) { + if (e instanceof MissingProjectIdError) { + // A `projectId` was required, but we don't have one. + try { + // Attempt to get the `projectId` + await setProjectId(); + authenticatedReqOpts = util.decorateRequest(authenticatedReqOpts, projectId); + err = null; + } + catch (e) { + // Re-use the "Could not load the default credentials error" if + // auto auth failed. + err = err || e; + } + } + else { + // Some other error unrelated to missing `projectId` + err = err || e; + } + } + } + if (err) { + if (stream) { + stream.destroy(err); + } + else { + const fn = options && options.onAuthenticated + ? options.onAuthenticated + : callback; + fn(err); + } + return; + } + if (options && options.onAuthenticated) { + options.onAuthenticated(null, authenticatedReqOpts); + } + else { + activeRequest_ = util.makeRequest(authenticatedReqOpts, reqConfig, (apiResponseError, ...params) => { + if (apiResponseError && + apiResponseError.code === 401 && + authLibraryError) { + // Re-use the "Could not load the default credentials error" if + // the API request failed due to missing credentials. + apiResponseError = authLibraryError; + } + callback(apiResponseError, ...params); + }); + } + }; + const prepareRequest = async () => { + try { + const getProjectId = async () => { + if (config.projectId && + config.projectId !== DEFAULT_PROJECT_ID_TOKEN) { + // The user provided a project ID. We don't need to check with the + // auth client, it could be incorrect. + return config.projectId; + } + if (config.projectIdRequired === false) { + // A projectId is not required. Return the default. + return DEFAULT_PROJECT_ID_TOKEN; + } + return setProjectId(); + }; + const authorizeRequest = async () => { + if (reqConfig.customEndpoint && + !reqConfig.useAuthWithCustomEndpoint) { + // Using a custom API override. Do not use `google-auth-library` for + // authentication. (ex: connecting to a local Datastore server) + return reqOpts; + } + else { + return authClient.authorizeRequest(reqOpts); + } + }; + const [_projectId, authorizedReqOpts] = await Promise.all([ + getProjectId(), + authorizeRequest(), + ]); + if (_projectId) { + projectId = _projectId; + } + return onAuthenticated(null, authorizedReqOpts); + } + catch (e) { + return onAuthenticated(e); + } + }; + prepareRequest(); + if (stream) { + return stream; + } + return { + abort() { + setImmediate(() => { + if (activeRequest_) { + activeRequest_.abort(); + activeRequest_ = null; + } + }); + }, + }; + } + const mar = makeAuthenticatedRequest; + mar.getCredentials = authClient.getCredentials.bind(authClient); + mar.authClient = authClient; + return mar; + } + /** + * Make a request through the `retryRequest` module with built-in error + * handling and exponential back off. + * + * @param {object} reqOpts - Request options in the format `request` expects. + * @param {object=} config - Configuration object. + * @param {boolean=} config.autoRetry - Automatically retry requests if the + * response is related to rate limits or certain intermittent server + * errors. We will exponentially backoff subsequent requests by default. + * (default: true) + * @param {number=} config.maxRetries - Maximum number of automatic retries + * attempted before returning the error. (default: 3) + * @param {object=} config.request - HTTP module for request calls. + * @param {function} callback - The callback function. + */ + makeRequest(reqOpts, config, callback) { + var _a, _b, _c, _d, _e; + let autoRetryValue = AUTO_RETRY_DEFAULT; + if (config.autoRetry !== undefined) { + autoRetryValue = config.autoRetry; + } + else if (((_a = config.retryOptions) === null || _a === void 0 ? void 0 : _a.autoRetry) !== undefined) { + autoRetryValue = config.retryOptions.autoRetry; + } + let maxRetryValue = MAX_RETRY_DEFAULT; + if (config.maxRetries !== undefined) { + maxRetryValue = config.maxRetries; + } + else if (((_b = config.retryOptions) === null || _b === void 0 ? void 0 : _b.maxRetries) !== undefined) { + maxRetryValue = config.retryOptions.maxRetries; + } + requestDefaults.headers = this._getDefaultHeaders(reqOpts[GCCL_GCS_CMD_KEY]); + const options = { + request: teenyRequest.defaults(requestDefaults), + retries: autoRetryValue !== false ? maxRetryValue : 0, + noResponseRetries: autoRetryValue !== false ? maxRetryValue : 0, + shouldRetryFn(httpRespMessage) { + var _a, _b; + const err = util.parseHttpRespMessage(httpRespMessage).err; + if ((_a = config.retryOptions) === null || _a === void 0 ? void 0 : _a.retryableErrorFn) { + return err && ((_b = config.retryOptions) === null || _b === void 0 ? void 0 : _b.retryableErrorFn(err)); + } + return err && util.shouldRetryRequest(err); + }, + maxRetryDelay: (_c = config.retryOptions) === null || _c === void 0 ? void 0 : _c.maxRetryDelay, + retryDelayMultiplier: (_d = config.retryOptions) === null || _d === void 0 ? void 0 : _d.retryDelayMultiplier, + totalTimeout: (_e = config.retryOptions) === null || _e === void 0 ? void 0 : _e.totalTimeout, + }; + if (typeof reqOpts.maxRetries === 'number') { + options.retries = reqOpts.maxRetries; + options.noResponseRetries = reqOpts.maxRetries; + } + if (!config.stream) { + return retryRequest(reqOpts, options, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (err, response, body) => { + util.handleResp(err, response, body, callback); + }); + } + const dup = config.stream; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let requestStream; + const isGetRequest = (reqOpts.method || 'GET').toUpperCase() === 'GET'; + if (isGetRequest) { + requestStream = retryRequest(reqOpts, options); + dup.setReadable(requestStream); + } + else { + // Streaming writable HTTP requests cannot be retried. + requestStream = options.request(reqOpts); + dup.setWritable(requestStream); + } + // Replay the Request events back to the stream. + requestStream + .on('error', dup.destroy.bind(dup)) + .on('response', dup.emit.bind(dup, 'response')) + .on('complete', dup.emit.bind(dup, 'complete')); + dup.abort = requestStream.abort; + return dup; + } + /** + * Decorate the options about to be made in a request. + * + * @param {object} reqOpts - The options to be passed to `request`. + * @param {string} projectId - The project ID. + * @return {object} reqOpts - The decorated reqOpts. + */ + decorateRequest(reqOpts, projectId) { + delete reqOpts.autoPaginate; + delete reqOpts.autoPaginateVal; + delete reqOpts.objectMode; + if (reqOpts.qs !== null && typeof reqOpts.qs === 'object') { + delete reqOpts.qs.autoPaginate; + delete reqOpts.qs.autoPaginateVal; + reqOpts.qs = replaceProjectIdToken(reqOpts.qs, projectId); + } + if (Array.isArray(reqOpts.multipart)) { + reqOpts.multipart = reqOpts.multipart.map(part => { + return replaceProjectIdToken(part, projectId); + }); + } + if (reqOpts.json !== null && typeof reqOpts.json === 'object') { + delete reqOpts.json.autoPaginate; + delete reqOpts.json.autoPaginateVal; + reqOpts.json = replaceProjectIdToken(reqOpts.json, projectId); + } + reqOpts.uri = replaceProjectIdToken(reqOpts.uri, projectId); + return reqOpts; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + isCustomType(unknown, module) { + function getConstructorName(obj) { + return obj.constructor && obj.constructor.name.toLowerCase(); + } + const moduleNameParts = module.split('/'); + const parentModuleName = moduleNameParts[0] && moduleNameParts[0].toLowerCase(); + const subModuleName = moduleNameParts[1] && moduleNameParts[1].toLowerCase(); + if (subModuleName && getConstructorName(unknown) !== subModuleName) { + return false; + } + let walkingModule = unknown; + // eslint-disable-next-line no-constant-condition + while (true) { + if (getConstructorName(walkingModule) === parentModuleName) { + return true; + } + walkingModule = walkingModule.parent; + if (!walkingModule) { + return false; + } + } + } + /** + * Given two parameters, figure out if this is either: + * - Just a callback function + * - An options object, and then a callback function + * @param optionsOrCallback An options object or callback. + * @param cb A potentially undefined callback. + */ + maybeOptionsOrCallback(optionsOrCallback, cb) { + return typeof optionsOrCallback === 'function' + ? [{}, optionsOrCallback] + : [optionsOrCallback, cb]; + } + _getDefaultHeaders(gcclGcsCmd) { + const headers = { + 'User-Agent': getUserAgentString(), + 'x-goog-api-client': `${getRuntimeTrackingString()} gccl/${packageJson.version}-${getModuleFormat()} gccl-invocation-id/${uuid.v4()}`, + }; + if (gcclGcsCmd) { + headers['x-goog-api-client'] += ` gccl-gcs-cmd/${gcclGcsCmd}`; + } + return headers; + } +} +/** + * Basic Passthrough Stream that records the number of bytes read + * every time the cursor is moved. + */ +class ProgressStream extends Transform { + constructor() { + super(...arguments); + this.bytesRead = 0; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _transform(chunk, encoding, callback) { + this.bytesRead += chunk.length; + this.emit('progress', { bytesWritten: this.bytesRead, contentLength: '*' }); + this.push(chunk); + callback(); + } +} +const util = new Util(); +export { util }; diff --git a/node_modules/@google-cloud/storage/build/esm/src/notification.d.ts b/node_modules/@google-cloud/storage/build/esm/src/notification.d.ts new file mode 100644 index 0000000..0d3341a --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/notification.d.ts @@ -0,0 +1,106 @@ +import { BaseMetadata, ServiceObject } from './nodejs-common/index.js'; +import { ResponseBody } from './nodejs-common/util.js'; +import { Bucket } from './bucket.js'; +export interface DeleteNotificationOptions { + userProject?: string; +} +export interface GetNotificationMetadataOptions { + userProject?: string; +} +/** + * @typedef {array} GetNotificationMetadataResponse + * @property {object} 0 The notification metadata. + * @property {object} 1 The full API response. + */ +export type GetNotificationMetadataResponse = [ResponseBody, unknown]; +/** + * @callback GetNotificationMetadataCallback + * @param {?Error} err Request error, if any. + * @param {object} files The notification metadata. + * @param {object} apiResponse The full API response. + */ +export interface GetNotificationMetadataCallback { + (err: Error | null, metadata?: ResponseBody, apiResponse?: unknown): void; +} +/** + * @typedef {array} GetNotificationResponse + * @property {Notification} 0 The {@link Notification} + * @property {object} 1 The full API response. + */ +export type GetNotificationResponse = [Notification, unknown]; +export interface GetNotificationOptions { + /** + * Automatically create the object if it does not exist. Default: `false`. + */ + autoCreate?: boolean; + /** + * The ID of the project which will be billed for the request. + */ + userProject?: string; +} +/** + * @callback GetNotificationCallback + * @param {?Error} err Request error, if any. + * @param {Notification} notification The {@link Notification}. + * @param {object} apiResponse The full API response. + */ +export interface GetNotificationCallback { + (err: Error | null, notification?: Notification | null, apiResponse?: unknown): void; +} +/** + * @callback DeleteNotificationCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ +export interface DeleteNotificationCallback { + (err: Error | null, apiResponse?: unknown): void; +} +export interface NotificationMetadata extends BaseMetadata { + custom_attributes?: { + [key: string]: string; + }; + event_types?: string[]; + object_name_prefix?: string; + payload_format?: 'JSON_API_V1' | 'NONE'; + topic?: string; +} +/** + * The API-formatted resource description of the notification. + * + * Note: This is not guaranteed to be up-to-date when accessed. To get the + * latest record, call the `getMetadata()` method. + * + * @name Notification#metadata + * @type {object} + */ +/** + * A Notification object is created from your {@link Bucket} object using + * {@link Bucket#notification}. Use it to interact with Cloud Pub/Sub + * notifications. + * + * See {@link https://cloud.google.com/storage/docs/pubsub-notifications| Cloud Pub/Sub Notifications for Google Cloud Storage} + * + * @class + * @hideconstructor + * + * @param {Bucket} bucket The bucket instance this notification is attached to. + * @param {string} id The ID of the notification. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const notification = myBucket.notification('1'); + * ``` + */ +declare class Notification extends ServiceObject { + constructor(bucket: Bucket, id: string); +} +/** + * Reference to the {@link Notification} class. + * @name module:@google-cloud/storage.Notification + * @see Notification + */ +export { Notification }; diff --git a/node_modules/@google-cloud/storage/build/esm/src/notification.js b/node_modules/@google-cloud/storage/build/esm/src/notification.js new file mode 100644 index 0000000..682defe --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/notification.js @@ -0,0 +1,267 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +import { ServiceObject } from './nodejs-common/index.js'; +import { promisifyAll } from '@google-cloud/promisify'; +/** + * The API-formatted resource description of the notification. + * + * Note: This is not guaranteed to be up-to-date when accessed. To get the + * latest record, call the `getMetadata()` method. + * + * @name Notification#metadata + * @type {object} + */ +/** + * A Notification object is created from your {@link Bucket} object using + * {@link Bucket#notification}. Use it to interact with Cloud Pub/Sub + * notifications. + * + * See {@link https://cloud.google.com/storage/docs/pubsub-notifications| Cloud Pub/Sub Notifications for Google Cloud Storage} + * + * @class + * @hideconstructor + * + * @param {Bucket} bucket The bucket instance this notification is attached to. + * @param {string} id The ID of the notification. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const notification = myBucket.notification('1'); + * ``` + */ +class Notification extends ServiceObject { + constructor(bucket, id) { + const requestQueryObject = {}; + const methods = { + /** + * Creates a notification subscription for the bucket. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/insert| Notifications: insert} + * @method Notification#create + * + * @param {Topic|string} topic The Cloud PubSub topic to which this + * subscription publishes. If the project ID is omitted, the current + * project ID will be used. + * + * Acceptable formats are: + * - `projects/grape-spaceship-123/topics/my-topic` + * + * - `my-topic` + * @param {CreateNotificationRequest} [options] Metadata to set for + * the notification. + * @param {CreateNotificationCallback} [callback] Callback function. + * @returns {Promise} + * @throws {Error} If a valid topic is not provided. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * const notification = myBucket.notification('1'); + * + * notification.create(function(err, notification, apiResponse) { + * if (!err) { + * // The notification was created successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * notification.create().then(function(data) { + * const notification = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + create: true, + /** + * @typedef {array} DeleteNotificationResponse + * @property {object} 0 The full API response. + */ + /** + * Permanently deletes a notification subscription. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/delete| Notifications: delete API Documentation} + * + * @param {object} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {DeleteNotificationCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * const notification = myBucket.notification('1'); + * + * notification.delete(function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * notification.delete().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example include:samples/deleteNotification.js + * region_tag:storage_delete_bucket_notification + * Another example: + */ + delete: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * Get a notification and its metadata if it exists. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/get| Notifications: get API Documentation} + * + * @param {object} [options] Configuration options. + * See {@link Bucket#createNotification} for create options. + * @param {boolean} [options.autoCreate] Automatically create the object if + * it does not exist. Default: `false`. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetNotificationCallback} [callback] Callback function. + * @return {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * const notification = myBucket.notification('1'); + * + * notification.get(function(err, notification, apiResponse) { + * // `notification.metadata` has been populated. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * notification.get().then(function(data) { + * const notification = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + get: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * Get the notification's metadata. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/get| Notifications: get API Documentation} + * + * @param {object} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetNotificationMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * const notification = myBucket.notification('1'); + * + * notification.getMetadata(function(err, metadata, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * notification.getMetadata().then(function(data) { + * const metadata = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/getMetadataNotifications.js + * region_tag:storage_print_pubsub_bucket_notification + * Another example: + */ + getMetadata: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {array} NotificationExistsResponse + * @property {boolean} 0 Whether the notification exists or not. + */ + /** + * @callback NotificationExistsCallback + * @param {?Error} err Request error, if any. + * @param {boolean} exists Whether the notification exists or not. + */ + /** + * Check if the notification exists. + * + * @method Notification#exists + * @param {NotificationExistsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * const notification = myBucket.notification('1'); + * + * notification.exists(function(err, exists) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * notification.exists().then(function(data) { + * const exists = data[0]; + * }); + * ``` + */ + exists: true, + }; + super({ + parent: bucket, + baseUrl: '/notificationConfigs', + id: id.toString(), + createMethod: bucket.createNotification.bind(bucket), + methods, + }); + } +} +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Notification); +/** + * Reference to the {@link Notification} class. + * @name module:@google-cloud/storage.Notification + * @see Notification + */ +export { Notification }; diff --git a/node_modules/@google-cloud/storage/build/esm/src/package-json-helper.cjs b/node_modules/@google-cloud/storage/build/esm/src/package-json-helper.cjs new file mode 100644 index 0000000..794923b --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/package-json-helper.cjs @@ -0,0 +1,21 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/* eslint-disable node/no-missing-require */ + +function getPackageJSON() { + return require('../../../package.json'); +} + +exports.getPackageJSON = getPackageJSON; diff --git a/node_modules/@google-cloud/storage/build/esm/src/resumable-upload.d.ts b/node_modules/@google-cloud/storage/build/esm/src/resumable-upload.d.ts new file mode 100644 index 0000000..751e917 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/resumable-upload.d.ts @@ -0,0 +1,341 @@ +import { GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +import { GoogleAuthOptions } from 'google-auth-library'; +import { Writable, WritableOptions } from 'stream'; +import { RetryOptions, PreconditionOptions } from './storage.js'; +import { GCCL_GCS_CMD_KEY } from './nodejs-common/util.js'; +import { FileMetadata } from './file.js'; +export declare const PROTOCOL_REGEX: RegExp; +export interface ErrorWithCode extends Error { + code: number; + status?: number | string; +} +export type CreateUriCallback = (err: Error | null, uri?: string) => void; +export interface Encryption { + key: {}; + hash: {}; +} +export type PredefinedAcl = 'authenticatedRead' | 'bucketOwnerFullControl' | 'bucketOwnerRead' | 'private' | 'projectPrivate' | 'publicRead'; +export interface QueryParameters extends PreconditionOptions { + contentEncoding?: string; + kmsKeyName?: string; + predefinedAcl?: PredefinedAcl; + projection?: 'full' | 'noAcl'; + userProject?: string; +} +export interface UploadConfig extends Pick { + /** + * The API endpoint used for the request. + * Defaults to `storage.googleapis.com`. + * + * **Warning**: + * If this value does not match the current GCP universe an emulator context + * will be assumed and authentication will be bypassed. + */ + apiEndpoint?: string; + /** + * The name of the destination bucket. + */ + bucket: string; + /** + * The name of the destination file. + */ + file: string; + /** + * The GoogleAuthOptions passed to google-auth-library + */ + authConfig?: GoogleAuthOptions; + /** + * If you want to re-use an auth client from google-auto-auth, pass an + * instance here. + * Defaults to GoogleAuth and gets automatically overridden if an + * emulator context is detected. + */ + authClient?: { + request: (opts: GaxiosOptions) => Promise> | GaxiosPromise; + }; + /** + * Create a separate request per chunk. + * + * This value is in bytes and should be a multiple of 256 KiB (2^18). + * We recommend using at least 8 MiB for the chunk size. + * + * @link https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload + */ + chunkSize?: number; + /** + * For each API request we send, you may specify custom request options that + * we'll add onto the request. The request options follow the gaxios API: + * https://github.com/googleapis/gaxios#request-options. + */ + customRequestOptions?: GaxiosOptions; + /** + * This will cause the upload to fail if the current generation of the remote + * object does not match the one provided here. + */ + generation?: number; + /** + * Set to `true` if the upload is only a subset of the overall object to upload. + * This can be used when planning to continue the upload an object in another + * session. + * + * **Must be used with {@link UploadConfig.chunkSize} != `0`**. + * + * If this is a continuation of a previous upload, {@link UploadConfig.offset} + * should be set. + * + * @see {@link checkUploadStatus} for checking the status of an existing upload. + */ + isPartialUpload?: boolean; + /** + * A customer-supplied encryption key. See + * https://cloud.google.com/storage/docs/encryption#customer-supplied. + */ + key?: string | Buffer; + /** + * Resource name of the Cloud KMS key, of the form + * `projects/my-project/locations/global/keyRings/my-kr/cryptoKeys/my-key`, + * that will be used to encrypt the object. Overrides the object metadata's + * `kms_key_name` value, if any. + */ + kmsKeyName?: string; + /** + * Any metadata you wish to set on the object. + */ + metadata?: ConfigMetadata; + /** + * The starting byte in relation to the final uploaded object. + * **Must be used with {@link UploadConfig.uri}**. + * + * If resuming an interrupted stream, do not supply this argument unless you + * know the exact number of bytes the service has AND the provided stream's + * first byte is a continuation from that provided offset. If resuming an + * interrupted stream and this option has not been provided, we will treat + * the provided upload stream as the object to upload - where the first byte + * of the upload stream is the first byte of the object to upload; skipping + * any bytes that are already present on the server. + * + * @see {@link checkUploadStatus} for checking the status of an existing upload. + * @see {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload#resume-upload.} + */ + offset?: number; + /** + * Set an Origin header when creating the resumable upload URI. + */ + origin?: string; + /** + * Specify query parameters that go along with the initial upload request. See + * https://cloud.google.com/storage/docs/json_api/v1/objects/insert#parameters + */ + params?: QueryParameters; + /** + * Apply a predefined set of access controls to the created file. + */ + predefinedAcl?: PredefinedAcl; + /** + * Make the uploaded file private. (Alias for config.predefinedAcl = + * 'private') + */ + private?: boolean; + /** + * Make the uploaded file public. (Alias for config.predefinedAcl = + * 'publicRead') + */ + public?: boolean; + /** + * The service domain for a given Cloud universe. + */ + universeDomain?: string; + /** + * If you already have a resumable URI from a previously-created resumable + * upload, just pass it in here and we'll use that. + * + * If resuming an interrupted stream and the {@link UploadConfig.offset} + * option has not been provided, we will treat the provided upload stream as + * the object to upload - where the first byte of the upload stream is the + * first byte of the object to upload; skipping any bytes that are already + * present on the server. + * + * @see {@link checkUploadStatus} for checking the status of an existing upload. + */ + uri?: string; + /** + * If the bucket being accessed has requesterPays functionality enabled, this + * can be set to control which project is billed for the access of this file. + */ + userProject?: string; + /** + * Configuration options for retrying retryable errors. + */ + retryOptions: RetryOptions; + /** + * Controls whether or not to use authentication when using a custom endpoint. + */ + useAuthWithCustomEndpoint?: boolean; + [GCCL_GCS_CMD_KEY]?: string; +} +export interface ConfigMetadata { + [key: string]: any; + /** + * Set the length of the object being uploaded. If uploading a partial + * object, this is the overall size of the finalized object. + */ + contentLength?: number; + /** + * Set the content type of the incoming data. + */ + contentType?: string; +} +export interface GoogleInnerError { + reason?: string; +} +export interface ApiError extends Error { + code?: number; + errors?: GoogleInnerError[]; +} +export interface CheckUploadStatusConfig { + /** + * Set to `false` to disable retries within this method. + * + * @defaultValue `true` + */ + retry?: boolean; +} +export declare class Upload extends Writable { + #private; + bucket: string; + file: string; + apiEndpoint: string; + baseURI: string; + authConfig?: { + scopes?: string[]; + }; + authClient: { + request: (opts: GaxiosOptions) => Promise> | GaxiosPromise; + }; + cacheKey: string; + chunkSize?: number; + customRequestOptions: GaxiosOptions; + generation?: number; + key?: string | Buffer; + kmsKeyName?: string; + metadata: ConfigMetadata; + offset?: number; + origin?: string; + params: QueryParameters; + predefinedAcl?: PredefinedAcl; + private?: boolean; + public?: boolean; + uri?: string; + userProject?: string; + encryption?: Encryption; + uriProvidedManually: boolean; + numBytesWritten: number; + numRetries: number; + contentLength: number | '*'; + retryOptions: RetryOptions; + timeOfFirstRequest: number; + isPartialUpload: boolean; + private currentInvocationId; + /** + * A cache of buffers written to this instance, ready for consuming + */ + private writeBuffers; + private numChunksReadInRequest; + /** + * An array of buffers used for caching the most recent upload chunk. + * We should not assume that the server received all bytes sent in the request. + * - https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload + */ + private localWriteCache; + private localWriteCacheByteLength; + private upstreamEnded; + constructor(cfg: UploadConfig); + /** + * Prevent 'finish' event until the upload has succeeded. + * + * @param fireFinishEvent The finish callback + */ + _final(fireFinishEvent?: () => void): void; + /** + * Handles incoming data from upstream + * + * @param chunk The chunk to append to the buffer + * @param encoding The encoding of the chunk + * @param readCallback A callback for when the buffer has been read downstream + */ + _write(chunk: Buffer | string, encoding: BufferEncoding, readCallback?: () => void): void; + /** + * Prepends the local buffer to write buffer and resets it. + * + * @param keepLastBytes number of bytes to keep from the end of the local buffer. + */ + private prependLocalBufferToUpstream; + /** + * Retrieves data from upstream's buffer. + * + * @param limit The maximum amount to return from the buffer. + */ + private pullFromChunkBuffer; + /** + * A handler for determining if data is ready to be read from upstream. + * + * @returns If there will be more chunks to read in the future + */ + private waitForNextChunk; + /** + * Reads data from upstream up to the provided `limit`. + * Ends when the limit has reached or no data is expected to be pushed from upstream. + * + * @param limit The most amount of data this iterator should return. `Infinity` by default. + */ + private upstreamIterator; + createURI(): Promise; + createURI(callback: CreateUriCallback): void; + protected createURIAsync(): Promise; + private continueUploading; + startUploading(): Promise; + private responseHandler; + /** + * Check the status of an existing resumable upload. + * + * @param cfg A configuration to use. `uri` is required. + * @returns the current upload status + */ + checkUploadStatus(config?: CheckUploadStatusConfig): Promise>; + private getAndSetOffset; + private makeRequest; + private makeRequestStream; + /** + * @return {bool} is the request good? + */ + private onResponse; + /** + * @param resp GaxiosResponse object from previous attempt + */ + private attemptDelayedRetry; + /** + * The amount of time to wait before retrying the request, in milliseconds. + * If negative, do not retry. + * + * @returns the amount of time to wait, in milliseconds. + */ + private getRetryDelay; + private sanitizeEndpoint; + /** + * Check if a given status code is 2xx + * + * @param status The status code to check + * @returns if the status is 2xx + */ + isSuccessfulResponse(status: number): boolean; +} +export declare function upload(cfg: UploadConfig): Upload; +export declare function createURI(cfg: UploadConfig): Promise; +export declare function createURI(cfg: UploadConfig, callback: CreateUriCallback): void; +/** + * Check the status of an existing resumable upload. + * + * @param cfg A configuration to use. `uri` is required. + * @returns the current upload status + */ +export declare function checkUploadStatus(cfg: UploadConfig & Required>): Promise>; diff --git a/node_modules/@google-cloud/storage/build/esm/src/resumable-upload.js b/node_modules/@google-cloud/storage/build/esm/src/resumable-upload.js new file mode 100644 index 0000000..96d553a --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/resumable-upload.js @@ -0,0 +1,866 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _Upload_instances, _Upload_gcclGcsCmd, _Upload_resetLocalBuffersCache, _Upload_addLocalBufferCache; +import AbortController from 'abort-controller'; +import { createHash } from 'crypto'; +import * as gaxios from 'gaxios'; +import { DEFAULT_UNIVERSE, GoogleAuth, } from 'google-auth-library'; +import { Readable, Writable } from 'stream'; +import AsyncRetry from 'async-retry'; +import * as uuid from 'uuid'; +import { getRuntimeTrackingString, getModuleFormat, getUserAgentString, } from './util.js'; +import { GCCL_GCS_CMD_KEY } from './nodejs-common/util.js'; +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore +import { getPackageJSON } from './package-json-helper.cjs'; +const NOT_FOUND_STATUS_CODE = 404; +const RESUMABLE_INCOMPLETE_STATUS_CODE = 308; +const packageJson = getPackageJSON(); +export const PROTOCOL_REGEX = /^(\w*):\/\//; +export class Upload extends Writable { + constructor(cfg) { + var _a; + super(cfg); + _Upload_instances.add(this); + this.numBytesWritten = 0; + this.numRetries = 0; + this.currentInvocationId = { + checkUploadStatus: uuid.v4(), + chunk: uuid.v4(), + uri: uuid.v4(), + }; + /** + * A cache of buffers written to this instance, ready for consuming + */ + this.writeBuffers = []; + this.numChunksReadInRequest = 0; + /** + * An array of buffers used for caching the most recent upload chunk. + * We should not assume that the server received all bytes sent in the request. + * - https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload + */ + this.localWriteCache = []; + this.localWriteCacheByteLength = 0; + this.upstreamEnded = false; + _Upload_gcclGcsCmd.set(this, void 0); + cfg = cfg || {}; + if (!cfg.bucket || !cfg.file) { + throw new Error('A bucket and file name are required'); + } + if (cfg.offset && !cfg.uri) { + throw new RangeError('Cannot provide an `offset` without providing a `uri`'); + } + if (cfg.isPartialUpload && !cfg.chunkSize) { + throw new RangeError('Cannot set `isPartialUpload` without providing a `chunkSize`'); + } + cfg.authConfig = cfg.authConfig || {}; + cfg.authConfig.scopes = [ + 'https://www.googleapis.com/auth/devstorage.full_control', + ]; + this.authClient = cfg.authClient || new GoogleAuth(cfg.authConfig); + const universe = cfg.universeDomain || DEFAULT_UNIVERSE; + this.apiEndpoint = `https://storage.${universe}`; + if (cfg.apiEndpoint && cfg.apiEndpoint !== this.apiEndpoint) { + this.apiEndpoint = this.sanitizeEndpoint(cfg.apiEndpoint); + const hostname = new URL(this.apiEndpoint).hostname; + // check if it is a domain of a known universe + const isDomain = hostname === universe; + const isDefaultUniverseDomain = hostname === DEFAULT_UNIVERSE; + // check if it is a subdomain of a known universe + // by checking a last (universe's length + 1) of a hostname + const isSubDomainOfUniverse = hostname.slice(-(universe.length + 1)) === `.${universe}`; + const isSubDomainOfDefaultUniverse = hostname.slice(-(DEFAULT_UNIVERSE.length + 1)) === + `.${DEFAULT_UNIVERSE}`; + if (!isDomain && + !isDefaultUniverseDomain && + !isSubDomainOfUniverse && + !isSubDomainOfDefaultUniverse) { + // Check if we should use auth with custom endpoint + if (cfg.useAuthWithCustomEndpoint !== true) { + // Only bypass auth if explicitly not requested + this.authClient = gaxios; + } + // Otherwise keep the authenticated client + } + } + this.baseURI = `${this.apiEndpoint}/upload/storage/v1/b`; + this.bucket = cfg.bucket; + const cacheKeyElements = [cfg.bucket, cfg.file]; + if (typeof cfg.generation === 'number') { + cacheKeyElements.push(`${cfg.generation}`); + } + this.cacheKey = cacheKeyElements.join('/'); + this.customRequestOptions = cfg.customRequestOptions || {}; + this.file = cfg.file; + this.generation = cfg.generation; + this.kmsKeyName = cfg.kmsKeyName; + this.metadata = cfg.metadata || {}; + this.offset = cfg.offset; + this.origin = cfg.origin; + this.params = cfg.params || {}; + this.userProject = cfg.userProject; + this.chunkSize = cfg.chunkSize; + this.retryOptions = cfg.retryOptions; + this.isPartialUpload = (_a = cfg.isPartialUpload) !== null && _a !== void 0 ? _a : false; + if (cfg.key) { + if (typeof cfg.key === 'string') { + const base64Key = Buffer.from(cfg.key).toString('base64'); + this.encryption = { + key: base64Key, + hash: createHash('sha256').update(cfg.key).digest('base64'), + }; + } + else { + const base64Key = cfg.key.toString('base64'); + this.encryption = { + key: base64Key, + hash: createHash('sha256').update(cfg.key).digest('base64'), + }; + } + } + this.predefinedAcl = cfg.predefinedAcl; + if (cfg.private) + this.predefinedAcl = 'private'; + if (cfg.public) + this.predefinedAcl = 'publicRead'; + const autoRetry = cfg.retryOptions.autoRetry; + this.uriProvidedManually = !!cfg.uri; + this.uri = cfg.uri; + if (this.offset) { + // we're resuming an incomplete upload + this.numBytesWritten = this.offset; + } + this.numRetries = 0; // counter for number of retries currently executed + if (!autoRetry) { + cfg.retryOptions.maxRetries = 0; + } + this.timeOfFirstRequest = Date.now(); + const contentLength = cfg.metadata + ? Number(cfg.metadata.contentLength) + : NaN; + this.contentLength = isNaN(contentLength) ? '*' : contentLength; + __classPrivateFieldSet(this, _Upload_gcclGcsCmd, cfg[GCCL_GCS_CMD_KEY], "f"); + this.once('writing', () => { + if (this.uri) { + this.continueUploading(); + } + else { + this.createURI(err => { + if (err) { + return this.destroy(err); + } + this.startUploading(); + return; + }); + } + }); + } + /** + * Prevent 'finish' event until the upload has succeeded. + * + * @param fireFinishEvent The finish callback + */ + _final(fireFinishEvent = () => { }) { + this.upstreamEnded = true; + this.once('uploadFinished', fireFinishEvent); + process.nextTick(() => { + this.emit('upstreamFinished'); + // it's possible `_write` may not be called - namely for empty object uploads + this.emit('writing'); + }); + } + /** + * Handles incoming data from upstream + * + * @param chunk The chunk to append to the buffer + * @param encoding The encoding of the chunk + * @param readCallback A callback for when the buffer has been read downstream + */ + _write(chunk, encoding, readCallback = () => { }) { + // Backwards-compatible event + this.emit('writing'); + this.writeBuffers.push(typeof chunk === 'string' ? Buffer.from(chunk, encoding) : chunk); + this.once('readFromChunkBuffer', readCallback); + process.nextTick(() => this.emit('wroteToChunkBuffer')); + } + /** + * Prepends the local buffer to write buffer and resets it. + * + * @param keepLastBytes number of bytes to keep from the end of the local buffer. + */ + prependLocalBufferToUpstream(keepLastBytes) { + // Typically, the upstream write buffers should be smaller than the local + // cache, so we can save time by setting the local cache as the new + // upstream write buffer array and appending the old array to it + let initialBuffers = []; + if (keepLastBytes) { + // we only want the last X bytes + let bytesKept = 0; + while (keepLastBytes > bytesKept) { + // load backwards because we want the last X bytes + // note: `localWriteCacheByteLength` is reset below + let buf = this.localWriteCache.pop(); + if (!buf) + break; + bytesKept += buf.byteLength; + if (bytesKept > keepLastBytes) { + // we have gone over the amount desired, let's keep the last X bytes + // of this buffer + const diff = bytesKept - keepLastBytes; + buf = buf.subarray(diff); + bytesKept -= diff; + } + initialBuffers.unshift(buf); + } + } + else { + // we're keeping all of the local cache, simply use it as the initial buffer + initialBuffers = this.localWriteCache; + } + // Append the old upstream to the new + const append = this.writeBuffers; + this.writeBuffers = initialBuffers; + for (const buf of append) { + this.writeBuffers.push(buf); + } + // reset last buffers sent + __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_resetLocalBuffersCache).call(this); + } + /** + * Retrieves data from upstream's buffer. + * + * @param limit The maximum amount to return from the buffer. + */ + *pullFromChunkBuffer(limit) { + while (limit) { + const buf = this.writeBuffers.shift(); + if (!buf) + break; + let bufToYield = buf; + if (buf.byteLength > limit) { + bufToYield = buf.subarray(0, limit); + this.writeBuffers.unshift(buf.subarray(limit)); + limit = 0; + } + else { + limit -= buf.byteLength; + } + yield bufToYield; + // Notify upstream we've read from the buffer and we're able to consume + // more. It can also potentially send more data down as we're currently + // iterating. + this.emit('readFromChunkBuffer'); + } + } + /** + * A handler for determining if data is ready to be read from upstream. + * + * @returns If there will be more chunks to read in the future + */ + async waitForNextChunk() { + const willBeMoreChunks = await new Promise(resolve => { + // There's data available - it should be digested + if (this.writeBuffers.length) { + return resolve(true); + } + // The upstream writable ended, we shouldn't expect any more data. + if (this.upstreamEnded) { + return resolve(false); + } + // Nothing immediate seems to be determined. We need to prepare some + // listeners to determine next steps... + const wroteToChunkBufferCallback = () => { + removeListeners(); + return resolve(true); + }; + const upstreamFinishedCallback = () => { + removeListeners(); + // this should be the last chunk, if there's anything there + if (this.writeBuffers.length) + return resolve(true); + return resolve(false); + }; + // Remove listeners when we're ready to callback. + const removeListeners = () => { + this.removeListener('wroteToChunkBuffer', wroteToChunkBufferCallback); + this.removeListener('upstreamFinished', upstreamFinishedCallback); + }; + // If there's data recently written it should be digested + this.once('wroteToChunkBuffer', wroteToChunkBufferCallback); + // If the upstream finishes let's see if there's anything to grab + this.once('upstreamFinished', upstreamFinishedCallback); + }); + return willBeMoreChunks; + } + /** + * Reads data from upstream up to the provided `limit`. + * Ends when the limit has reached or no data is expected to be pushed from upstream. + * + * @param limit The most amount of data this iterator should return. `Infinity` by default. + */ + async *upstreamIterator(limit = Infinity) { + // read from upstream chunk buffer + while (limit && (await this.waitForNextChunk())) { + // read until end or limit has been reached + for (const chunk of this.pullFromChunkBuffer(limit)) { + limit -= chunk.byteLength; + yield chunk; + } + } + } + createURI(callback) { + if (!callback) { + return this.createURIAsync(); + } + this.createURIAsync().then(r => callback(null, r), callback); + } + async createURIAsync() { + const metadata = { ...this.metadata }; + const headers = {}; + // Delete content length and content type from metadata if they exist. + // These are headers and should not be sent as part of the metadata. + if (metadata.contentLength) { + headers['X-Upload-Content-Length'] = metadata.contentLength.toString(); + delete metadata.contentLength; + } + if (metadata.contentType) { + headers['X-Upload-Content-Type'] = metadata.contentType; + delete metadata.contentType; + } + let googAPIClient = `${getRuntimeTrackingString()} gccl/${packageJson.version}-${getModuleFormat()} gccl-invocation-id/${this.currentInvocationId.uri}`; + if (__classPrivateFieldGet(this, _Upload_gcclGcsCmd, "f")) { + googAPIClient += ` gccl-gcs-cmd/${__classPrivateFieldGet(this, _Upload_gcclGcsCmd, "f")}`; + } + // Check if headers already exist before creating new ones + const reqOpts = { + method: 'POST', + url: [this.baseURI, this.bucket, 'o'].join('/'), + params: Object.assign({ + name: this.file, + uploadType: 'resumable', + }, this.params), + data: metadata, + headers: { + 'User-Agent': getUserAgentString(), + 'x-goog-api-client': googAPIClient, + ...headers, + }, + }; + if (metadata.contentLength) { + reqOpts.headers['X-Upload-Content-Length'] = + metadata.contentLength.toString(); + } + if (metadata.contentType) { + reqOpts.headers['X-Upload-Content-Type'] = metadata.contentType; + } + if (typeof this.generation !== 'undefined') { + reqOpts.params.ifGenerationMatch = this.generation; + } + if (this.kmsKeyName) { + reqOpts.params.kmsKeyName = this.kmsKeyName; + } + if (this.predefinedAcl) { + reqOpts.params.predefinedAcl = this.predefinedAcl; + } + if (this.origin) { + reqOpts.headers.Origin = this.origin; + } + const uri = await AsyncRetry(async (bail) => { + var _a, _b, _c; + try { + const res = await this.makeRequest(reqOpts); + // We have successfully got a URI we can now create a new invocation id + this.currentInvocationId.uri = uuid.v4(); + return res.headers.location; + } + catch (err) { + const e = err; + const apiError = { + code: (_a = e.response) === null || _a === void 0 ? void 0 : _a.status, + name: (_b = e.response) === null || _b === void 0 ? void 0 : _b.statusText, + message: (_c = e.response) === null || _c === void 0 ? void 0 : _c.statusText, + errors: [ + { + reason: e.code, + }, + ], + }; + if (this.retryOptions.maxRetries > 0 && + this.retryOptions.retryableErrorFn(apiError)) { + throw e; + } + else { + return bail(e); + } + } + }, { + retries: this.retryOptions.maxRetries, + factor: this.retryOptions.retryDelayMultiplier, + maxTimeout: this.retryOptions.maxRetryDelay * 1000, //convert to milliseconds + maxRetryTime: this.retryOptions.totalTimeout * 1000, //convert to milliseconds + }); + this.uri = uri; + this.offset = 0; + // emit the newly generated URI for future reuse, if necessary. + this.emit('uri', uri); + return uri; + } + async continueUploading() { + var _a; + (_a = this.offset) !== null && _a !== void 0 ? _a : (await this.getAndSetOffset()); + return this.startUploading(); + } + async startUploading() { + const multiChunkMode = !!this.chunkSize; + let responseReceived = false; + this.numChunksReadInRequest = 0; + if (!this.offset) { + this.offset = 0; + } + // Check if the offset (server) is too far behind the current stream + if (this.offset < this.numBytesWritten) { + const delta = this.numBytesWritten - this.offset; + const message = `The offset is lower than the number of bytes written. The server has ${this.offset} bytes and while ${this.numBytesWritten} bytes has been uploaded - thus ${delta} bytes are missing. Stopping as this could result in data loss. Initiate a new upload to continue.`; + this.emit('error', new RangeError(message)); + return; + } + // Check if we should 'fast-forward' to the relevant data to upload + if (this.numBytesWritten < this.offset) { + // 'fast-forward' to the byte where we need to upload. + // only push data from the byte after the one we left off on + const fastForwardBytes = this.offset - this.numBytesWritten; + for await (const _chunk of this.upstreamIterator(fastForwardBytes)) { + _chunk; // discard the data up until the point we want + } + this.numBytesWritten = this.offset; + } + let expectedUploadSize = undefined; + // Set `expectedUploadSize` to `contentLength - this.numBytesWritten`, if available + if (typeof this.contentLength === 'number') { + expectedUploadSize = this.contentLength - this.numBytesWritten; + } + // `expectedUploadSize` should be no more than the `chunkSize`. + // It's possible this is the last chunk request for a multiple + // chunk upload, thus smaller than the chunk size. + if (this.chunkSize) { + expectedUploadSize = expectedUploadSize + ? Math.min(this.chunkSize, expectedUploadSize) + : this.chunkSize; + } + // A queue for the upstream data + const upstreamQueue = this.upstreamIterator(expectedUploadSize); + // The primary read stream for this request. This stream retrieves no more + // than the exact requested amount from upstream. + const requestStream = new Readable({ + read: async () => { + // Don't attempt to retrieve data upstream if we already have a response + if (responseReceived) + requestStream.push(null); + const result = await upstreamQueue.next(); + if (result.value) { + this.numChunksReadInRequest++; + if (multiChunkMode) { + // save ever buffer used in the request in multi-chunk mode + __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_addLocalBufferCache).call(this, result.value); + } + else { + __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_resetLocalBuffersCache).call(this); + __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_addLocalBufferCache).call(this, result.value); + } + this.numBytesWritten += result.value.byteLength; + this.emit('progress', { + bytesWritten: this.numBytesWritten, + contentLength: this.contentLength, + }); + requestStream.push(result.value); + } + if (result.done) { + requestStream.push(null); + } + }, + }); + let googAPIClient = `${getRuntimeTrackingString()} gccl/${packageJson.version}-${getModuleFormat()} gccl-invocation-id/${this.currentInvocationId.chunk}`; + if (__classPrivateFieldGet(this, _Upload_gcclGcsCmd, "f")) { + googAPIClient += ` gccl-gcs-cmd/${__classPrivateFieldGet(this, _Upload_gcclGcsCmd, "f")}`; + } + const headers = { + 'User-Agent': getUserAgentString(), + 'x-goog-api-client': googAPIClient, + }; + // If using multiple chunk upload, set appropriate header + if (multiChunkMode) { + // We need to know how much data is available upstream to set the `Content-Range` header. + // https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload + for await (const chunk of this.upstreamIterator(expectedUploadSize)) { + // This will conveniently track and keep the size of the buffers. + // We will reach either the expected upload size or the remainder of the stream. + __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_addLocalBufferCache).call(this, chunk); + } + // This is the sum from the `#addLocalBufferCache` calls + const bytesToUpload = this.localWriteCacheByteLength; + // Important: we want to know if the upstream has ended and the queue is empty before + // unshifting data back into the queue. This way we will know if this is the last request or not. + const isLastChunkOfUpload = !(await this.waitForNextChunk()); + // Important: put the data back in the queue for the actual upload + this.prependLocalBufferToUpstream(); + let totalObjectSize = this.contentLength; + if (typeof this.contentLength !== 'number' && + isLastChunkOfUpload && + !this.isPartialUpload) { + // Let's let the server know this is the last chunk of the object since we didn't set it before. + totalObjectSize = bytesToUpload + this.numBytesWritten; + } + // `- 1` as the ending byte is inclusive in the request. + const endingByte = bytesToUpload + this.numBytesWritten - 1; + // `Content-Length` for multiple chunk uploads is the size of the chunk, + // not the overall object + headers['Content-Length'] = bytesToUpload; + headers['Content-Range'] = + `bytes ${this.offset}-${endingByte}/${totalObjectSize}`; + } + else { + headers['Content-Range'] = `bytes ${this.offset}-*/${this.contentLength}`; + } + const reqOpts = { + method: 'PUT', + url: this.uri, + headers, + body: requestStream, + }; + try { + const resp = await this.makeRequestStream(reqOpts); + if (resp) { + responseReceived = true; + await this.responseHandler(resp); + } + } + catch (e) { + const err = e; + if (this.retryOptions.retryableErrorFn(err)) { + this.attemptDelayedRetry({ + status: NaN, + data: err, + }); + return; + } + this.destroy(err); + } + } + // Process the API response to look for errors that came in + // the response body. + async responseHandler(resp) { + if (resp.data.error) { + this.destroy(resp.data.error); + return; + } + // At this point we can safely create a new id for the chunk + this.currentInvocationId.chunk = uuid.v4(); + const moreDataToUpload = await this.waitForNextChunk(); + const shouldContinueWithNextMultiChunkRequest = this.chunkSize && + resp.status === RESUMABLE_INCOMPLETE_STATUS_CODE && + resp.headers.range && + moreDataToUpload; + /** + * This is true when we're expecting to upload more data in a future request, + * yet the upstream for the upload session has been exhausted. + */ + const shouldContinueUploadInAnotherRequest = this.isPartialUpload && + resp.status === RESUMABLE_INCOMPLETE_STATUS_CODE && + !moreDataToUpload; + if (shouldContinueWithNextMultiChunkRequest) { + // Use the upper value in this header to determine where to start the next chunk. + // We should not assume that the server received all bytes sent in the request. + // https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload + const range = resp.headers.range; + this.offset = Number(range.split('-')[1]) + 1; + // We should not assume that the server received all bytes sent in the request. + // - https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload + const missingBytes = this.numBytesWritten - this.offset; + if (missingBytes) { + // As multi-chunk uploads send one chunk per request and pulls one + // chunk into the pipeline, prepending the missing bytes back should + // be fine for the next request. + this.prependLocalBufferToUpstream(missingBytes); + this.numBytesWritten -= missingBytes; + } + else { + // No bytes missing - no need to keep the local cache + __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_resetLocalBuffersCache).call(this); + } + // continue uploading next chunk + this.continueUploading(); + } + else if (!this.isSuccessfulResponse(resp.status) && + !shouldContinueUploadInAnotherRequest) { + const err = new Error('Upload failed'); + err.code = resp.status; + err.name = 'Upload failed'; + if (resp === null || resp === void 0 ? void 0 : resp.data) { + err.errors = [resp === null || resp === void 0 ? void 0 : resp.data]; + } + this.destroy(err); + } + else { + // no need to keep the cache + __classPrivateFieldGet(this, _Upload_instances, "m", _Upload_resetLocalBuffersCache).call(this); + if (resp && resp.data) { + resp.data.size = Number(resp.data.size); + } + this.emit('metadata', resp.data); + // Allow the object (Upload) to continue naturally so the user's + // "finish" event fires. + this.emit('uploadFinished'); + } + } + /** + * Check the status of an existing resumable upload. + * + * @param cfg A configuration to use. `uri` is required. + * @returns the current upload status + */ + async checkUploadStatus(config = {}) { + let googAPIClient = `${getRuntimeTrackingString()} gccl/${packageJson.version}-${getModuleFormat()} gccl-invocation-id/${this.currentInvocationId.checkUploadStatus}`; + if (__classPrivateFieldGet(this, _Upload_gcclGcsCmd, "f")) { + googAPIClient += ` gccl-gcs-cmd/${__classPrivateFieldGet(this, _Upload_gcclGcsCmd, "f")}`; + } + const opts = { + method: 'PUT', + url: this.uri, + headers: { + 'Content-Length': 0, + 'Content-Range': 'bytes */*', + 'User-Agent': getUserAgentString(), + 'x-goog-api-client': googAPIClient, + }, + }; + try { + const resp = await this.makeRequest(opts); + // Successfully got the offset we can now create a new offset invocation id + this.currentInvocationId.checkUploadStatus = uuid.v4(); + return resp; + } + catch (e) { + if (config.retry === false || + !(e instanceof Error) || + !this.retryOptions.retryableErrorFn(e)) { + throw e; + } + const retryDelay = this.getRetryDelay(); + if (retryDelay <= 0) { + throw e; + } + await new Promise(res => setTimeout(res, retryDelay)); + return this.checkUploadStatus(config); + } + } + async getAndSetOffset() { + try { + // we want to handle retries in this method. + const resp = await this.checkUploadStatus({ retry: false }); + if (resp.status === RESUMABLE_INCOMPLETE_STATUS_CODE) { + if (typeof resp.headers.range === 'string') { + this.offset = Number(resp.headers.range.split('-')[1]) + 1; + return; + } + } + this.offset = 0; + } + catch (e) { + const err = e; + if (this.retryOptions.retryableErrorFn(err)) { + this.attemptDelayedRetry({ + status: NaN, + data: err, + }); + return; + } + this.destroy(err); + } + } + async makeRequest(reqOpts) { + if (this.encryption) { + reqOpts.headers = reqOpts.headers || {}; + reqOpts.headers['x-goog-encryption-algorithm'] = 'AES256'; + reqOpts.headers['x-goog-encryption-key'] = this.encryption.key.toString(); + reqOpts.headers['x-goog-encryption-key-sha256'] = + this.encryption.hash.toString(); + } + if (this.userProject) { + reqOpts.params = reqOpts.params || {}; + reqOpts.params.userProject = this.userProject; + } + // Let gaxios know we will handle a 308 error code ourselves. + reqOpts.validateStatus = (status) => { + return (this.isSuccessfulResponse(status) || + status === RESUMABLE_INCOMPLETE_STATUS_CODE); + }; + const combinedReqOpts = { + ...this.customRequestOptions, + ...reqOpts, + headers: { + ...this.customRequestOptions.headers, + ...reqOpts.headers, + }, + }; + const res = await this.authClient.request(combinedReqOpts); + if (res.data && res.data.error) { + throw res.data.error; + } + return res; + } + async makeRequestStream(reqOpts) { + const controller = new AbortController(); + const errorCallback = () => controller.abort(); + this.once('error', errorCallback); + if (this.userProject) { + reqOpts.params = reqOpts.params || {}; + reqOpts.params.userProject = this.userProject; + } + reqOpts.signal = controller.signal; + reqOpts.validateStatus = () => true; + const combinedReqOpts = { + ...this.customRequestOptions, + ...reqOpts, + headers: { + ...this.customRequestOptions.headers, + ...reqOpts.headers, + }, + }; + const res = await this.authClient.request(combinedReqOpts); + const successfulRequest = this.onResponse(res); + this.removeListener('error', errorCallback); + return successfulRequest ? res : null; + } + /** + * @return {bool} is the request good? + */ + onResponse(resp) { + if (resp.status !== 200 && + this.retryOptions.retryableErrorFn({ + code: resp.status, + message: resp.statusText, + name: resp.statusText, + })) { + this.attemptDelayedRetry(resp); + return false; + } + this.emit('response', resp); + return true; + } + /** + * @param resp GaxiosResponse object from previous attempt + */ + attemptDelayedRetry(resp) { + if (this.numRetries < this.retryOptions.maxRetries) { + if (resp.status === NOT_FOUND_STATUS_CODE && + this.numChunksReadInRequest === 0) { + this.startUploading(); + } + else { + const retryDelay = this.getRetryDelay(); + if (retryDelay <= 0) { + this.destroy(new Error(`Retry total time limit exceeded - ${JSON.stringify(resp.data)}`)); + return; + } + // Unshift the local cache back in case it's needed for the next request. + this.numBytesWritten -= this.localWriteCacheByteLength; + this.prependLocalBufferToUpstream(); + // We don't know how much data has been received by the server. + // `continueUploading` will recheck the offset via `getAndSetOffset`. + // If `offset` < `numberBytesReceived` then we will raise a RangeError + // as we've streamed too much data that has been missed - this should + // not be the case for multi-chunk uploads as `lastChunkSent` is the + // body of the entire request. + this.offset = undefined; + setTimeout(this.continueUploading.bind(this), retryDelay); + } + this.numRetries++; + } + else { + this.destroy(new Error(`Retry limit exceeded - ${JSON.stringify(resp.data)}`)); + } + } + /** + * The amount of time to wait before retrying the request, in milliseconds. + * If negative, do not retry. + * + * @returns the amount of time to wait, in milliseconds. + */ + getRetryDelay() { + const randomMs = Math.round(Math.random() * 1000); + const waitTime = Math.pow(this.retryOptions.retryDelayMultiplier, this.numRetries) * + 1000 + + randomMs; + const maxAllowableDelayMs = this.retryOptions.totalTimeout * 1000 - + (Date.now() - this.timeOfFirstRequest); + const maxRetryDelayMs = this.retryOptions.maxRetryDelay * 1000; + return Math.min(waitTime, maxRetryDelayMs, maxAllowableDelayMs); + } + /* + * Prepare user-defined API endpoint for compatibility with our API. + */ + sanitizeEndpoint(url) { + if (!PROTOCOL_REGEX.test(url)) { + url = `https://${url}`; + } + return url.replace(/\/+$/, ''); // Remove trailing slashes + } + /** + * Check if a given status code is 2xx + * + * @param status The status code to check + * @returns if the status is 2xx + */ + isSuccessfulResponse(status) { + return status >= 200 && status < 300; + } +} +_Upload_gcclGcsCmd = new WeakMap(), _Upload_instances = new WeakSet(), _Upload_resetLocalBuffersCache = function _Upload_resetLocalBuffersCache() { + this.localWriteCache = []; + this.localWriteCacheByteLength = 0; +}, _Upload_addLocalBufferCache = function _Upload_addLocalBufferCache(buf) { + this.localWriteCache.push(buf); + this.localWriteCacheByteLength += buf.byteLength; +}; +export function upload(cfg) { + return new Upload(cfg); +} +export function createURI(cfg, callback) { + const up = new Upload(cfg); + if (!callback) { + return up.createURI(); + } + up.createURI().then(r => callback(null, r), callback); +} +/** + * Check the status of an existing resumable upload. + * + * @param cfg A configuration to use. `uri` is required. + * @returns the current upload status + */ +export function checkUploadStatus(cfg) { + const up = new Upload(cfg); + return up.checkUploadStatus(); +} diff --git a/node_modules/@google-cloud/storage/build/esm/src/signer.d.ts b/node_modules/@google-cloud/storage/build/esm/src/signer.d.ts new file mode 100644 index 0000000..337961f --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/signer.d.ts @@ -0,0 +1,146 @@ +import * as http from 'http'; +import { Storage } from './storage.js'; +import { GoogleAuth } from 'google-auth-library'; +type GoogleAuthLike = Pick; +/** + * @deprecated Use {@link GoogleAuth} instead + */ +export interface AuthClient { + sign(blobToSign: string): Promise; + getCredentials(): Promise<{ + client_email?: string; + }>; +} +export interface BucketI { + name: string; +} +export interface FileI { + name: string; +} +export interface Query { + [key: string]: string; +} +export interface GetSignedUrlConfigInternal { + expiration: number; + accessibleAt?: Date; + method: string; + extensionHeaders?: http.OutgoingHttpHeaders; + queryParams?: Query; + cname?: string; + contentMd5?: string; + contentType?: string; + bucket: string; + file?: string; + /** + * The host for the generated signed URL + * + * @example + * 'https://localhost:8080/' + */ + host?: string | URL; + /** + * An endpoint for generating the signed URL + * + * @example + * 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/' + */ + signingEndpoint?: string | URL; +} +export interface SignerGetSignedUrlConfig { + method: 'GET' | 'PUT' | 'DELETE' | 'POST'; + expires: string | number | Date; + accessibleAt?: string | number | Date; + virtualHostedStyle?: boolean; + version?: 'v2' | 'v4'; + cname?: string; + extensionHeaders?: http.OutgoingHttpHeaders; + queryParams?: Query; + contentMd5?: string; + contentType?: string; + /** + * The host for the generated signed URL + * + * @example + * 'https://localhost:8080/' + */ + host?: string | URL; + /** + * An endpoint for generating the signed URL + * + * @example + * 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/' + */ + signingEndpoint?: string | URL; +} +export type SignerGetSignedUrlResponse = string; +export type GetSignedUrlResponse = [SignerGetSignedUrlResponse]; +export interface GetSignedUrlCallback { + (err: Error | null, url?: string): void; +} +export declare enum SignerExceptionMessages { + ACCESSIBLE_DATE_INVALID = "The accessible at date provided was invalid.", + EXPIRATION_BEFORE_ACCESSIBLE_DATE = "An expiration date cannot be before accessible date.", + X_GOOG_CONTENT_SHA256 = "The header X-Goog-Content-SHA256 must be a hexadecimal string." +} +/** + * @const {string} + * @deprecated - unused + */ +export declare const PATH_STYLED_HOST = "https://storage.googleapis.com"; +export declare class URLSigner { + private auth; + private bucket; + private file?; + /** + * A {@link Storage} object. + * + * @privateRemarks + * + * Technically this is a required field, however it would be a breaking change to + * move it before optional properties. In the next major we should refactor the + * constructor of this class to only accept a config object. + */ + private storage; + constructor(auth: AuthClient | GoogleAuthLike, bucket: BucketI, file?: FileI | undefined, + /** + * A {@link Storage} object. + * + * @privateRemarks + * + * Technically this is a required field, however it would be a breaking change to + * move it before optional properties. In the next major we should refactor the + * constructor of this class to only accept a config object. + */ + storage?: Storage); + getSignedUrl(cfg: SignerGetSignedUrlConfig): Promise; + private getSignedUrlV2; + private getSignedUrlV4; + /** + * Create canonical headers for signing v4 url. + * + * The canonical headers for v4-signing a request demands header names are + * first lowercased, followed by sorting the header names. + * Then, construct the canonical headers part of the request: + * + ":" + Trim() + "\n" + * .. + * + ":" + Trim() + "\n" + * + * @param headers + * @private + */ + getCanonicalHeaders(headers: http.OutgoingHttpHeaders): string; + getCanonicalRequest(method: string, path: string, query: string, headers: string, signedHeaders: string, contentSha256?: string): string; + getCanonicalQueryParams(query: Query): string; + getResourcePath(cname: boolean, bucket: string, file?: string): string; + parseExpires(expires: string | number | Date, current?: Date): number; + parseAccessibleAt(accessibleAt?: string | number | Date): number; +} +/** + * Custom error type for errors related to getting signed errors and policies. + * + * @private + */ +export declare class SigningError extends Error { + name: string; +} +export {}; diff --git a/node_modules/@google-cloud/storage/build/esm/src/signer.js b/node_modules/@google-cloud/storage/build/esm/src/signer.js new file mode 100644 index 0000000..f05c94e --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/signer.js @@ -0,0 +1,299 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +import * as crypto from 'crypto'; +import * as url from 'url'; +import { ExceptionMessages, Storage } from './storage.js'; +import { encodeURI, qsStringify, objectEntries, formatAsUTCISO } from './util.js'; +export var SignerExceptionMessages; +(function (SignerExceptionMessages) { + SignerExceptionMessages["ACCESSIBLE_DATE_INVALID"] = "The accessible at date provided was invalid."; + SignerExceptionMessages["EXPIRATION_BEFORE_ACCESSIBLE_DATE"] = "An expiration date cannot be before accessible date."; + SignerExceptionMessages["X_GOOG_CONTENT_SHA256"] = "The header X-Goog-Content-SHA256 must be a hexadecimal string."; +})(SignerExceptionMessages || (SignerExceptionMessages = {})); +/* + * Default signing version for getSignedUrl is 'v2'. + */ +const DEFAULT_SIGNING_VERSION = 'v2'; +const SEVEN_DAYS = 7 * 24 * 60 * 60; +/** + * @const {string} + * @deprecated - unused + */ +export const PATH_STYLED_HOST = 'https://storage.googleapis.com'; +export class URLSigner { + constructor(auth, bucket, file, + /** + * A {@link Storage} object. + * + * @privateRemarks + * + * Technically this is a required field, however it would be a breaking change to + * move it before optional properties. In the next major we should refactor the + * constructor of this class to only accept a config object. + */ + storage = new Storage()) { + this.auth = auth; + this.bucket = bucket; + this.file = file; + this.storage = storage; + } + getSignedUrl(cfg) { + const expiresInSeconds = this.parseExpires(cfg.expires); + const method = cfg.method; + const accessibleAtInSeconds = this.parseAccessibleAt(cfg.accessibleAt); + if (expiresInSeconds < accessibleAtInSeconds) { + throw new Error(SignerExceptionMessages.EXPIRATION_BEFORE_ACCESSIBLE_DATE); + } + let customHost; + // Default style is `path`. + const isVirtualHostedStyle = cfg.virtualHostedStyle || false; + if (cfg.cname) { + customHost = cfg.cname; + } + else if (isVirtualHostedStyle) { + customHost = `https://${this.bucket.name}.storage.${this.storage.universeDomain}`; + } + const secondsToMilliseconds = 1000; + const config = Object.assign({}, cfg, { + method, + expiration: expiresInSeconds, + accessibleAt: new Date(secondsToMilliseconds * accessibleAtInSeconds), + bucket: this.bucket.name, + file: this.file ? encodeURI(this.file.name, false) : undefined, + }); + if (customHost) { + config.cname = customHost; + } + const version = cfg.version || DEFAULT_SIGNING_VERSION; + let promise; + if (version === 'v2') { + promise = this.getSignedUrlV2(config); + } + else if (version === 'v4') { + promise = this.getSignedUrlV4(config); + } + else { + throw new Error(`Invalid signed URL version: ${version}. Supported versions are 'v2' and 'v4'.`); + } + return promise.then(query => { + var _a; + query = Object.assign(query, cfg.queryParams); + const signedUrl = new url.URL(((_a = cfg.host) === null || _a === void 0 ? void 0 : _a.toString()) || config.cname || this.storage.apiEndpoint); + signedUrl.pathname = this.getResourcePath(!!config.cname, this.bucket.name, config.file); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + signedUrl.search = qsStringify(query); + return signedUrl.href; + }); + } + getSignedUrlV2(config) { + const canonicalHeadersString = this.getCanonicalHeaders(config.extensionHeaders || {}); + const resourcePath = this.getResourcePath(false, config.bucket, config.file); + const blobToSign = [ + config.method, + config.contentMd5 || '', + config.contentType || '', + config.expiration, + canonicalHeadersString + resourcePath, + ].join('\n'); + const sign = async () => { + var _a; + const auth = this.auth; + try { + const signature = await auth.sign(blobToSign, (_a = config.signingEndpoint) === null || _a === void 0 ? void 0 : _a.toString()); + const credentials = await auth.getCredentials(); + return { + GoogleAccessId: credentials.client_email, + Expires: config.expiration, + Signature: signature, + }; + } + catch (err) { + const error = err; + const signingErr = new SigningError(error.message); + signingErr.stack = error.stack; + throw signingErr; + } + }; + return sign(); + } + getSignedUrlV4(config) { + var _a; + config.accessibleAt = config.accessibleAt + ? config.accessibleAt + : new Date(); + const millisecondsToSeconds = 1.0 / 1000.0; + const expiresPeriodInSeconds = config.expiration - config.accessibleAt.valueOf() * millisecondsToSeconds; + // v4 limit expiration to be 7 days maximum + if (expiresPeriodInSeconds > SEVEN_DAYS) { + throw new Error(`Max allowed expiration is seven days (${SEVEN_DAYS} seconds).`); + } + const extensionHeaders = Object.assign({}, config.extensionHeaders); + const fqdn = new url.URL(((_a = config.host) === null || _a === void 0 ? void 0 : _a.toString()) || config.cname || this.storage.apiEndpoint); + extensionHeaders.host = fqdn.hostname; + if (config.contentMd5) { + extensionHeaders['content-md5'] = config.contentMd5; + } + if (config.contentType) { + extensionHeaders['content-type'] = config.contentType; + } + let contentSha256; + const sha256Header = extensionHeaders['x-goog-content-sha256']; + if (sha256Header) { + if (typeof sha256Header !== 'string' || + !/[A-Fa-f0-9]{40}/.test(sha256Header)) { + throw new Error(SignerExceptionMessages.X_GOOG_CONTENT_SHA256); + } + contentSha256 = sha256Header; + } + const signedHeaders = Object.keys(extensionHeaders) + .map(header => header.toLowerCase()) + .sort() + .join(';'); + const extensionHeadersString = this.getCanonicalHeaders(extensionHeaders); + const datestamp = formatAsUTCISO(config.accessibleAt); + const credentialScope = `${datestamp}/auto/storage/goog4_request`; + const sign = async () => { + var _a; + const credentials = await this.auth.getCredentials(); + const credential = `${credentials.client_email}/${credentialScope}`; + const dateISO = formatAsUTCISO(config.accessibleAt ? config.accessibleAt : new Date(), true); + const queryParams = { + 'X-Goog-Algorithm': 'GOOG4-RSA-SHA256', + 'X-Goog-Credential': credential, + 'X-Goog-Date': dateISO, + 'X-Goog-Expires': expiresPeriodInSeconds.toString(10), + 'X-Goog-SignedHeaders': signedHeaders, + ...(config.queryParams || {}), + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const canonicalQueryParams = this.getCanonicalQueryParams(queryParams); + const canonicalRequest = this.getCanonicalRequest(config.method, this.getResourcePath(!!config.cname, config.bucket, config.file), canonicalQueryParams, extensionHeadersString, signedHeaders, contentSha256); + const hash = crypto + .createHash('sha256') + .update(canonicalRequest) + .digest('hex'); + const blobToSign = [ + 'GOOG4-RSA-SHA256', + dateISO, + credentialScope, + hash, + ].join('\n'); + try { + const signature = await this.auth.sign(blobToSign, (_a = config.signingEndpoint) === null || _a === void 0 ? void 0 : _a.toString()); + const signatureHex = Buffer.from(signature, 'base64').toString('hex'); + const signedQuery = Object.assign({}, queryParams, { + 'X-Goog-Signature': signatureHex, + }); + return signedQuery; + } + catch (err) { + const error = err; + const signingErr = new SigningError(error.message); + signingErr.stack = error.stack; + throw signingErr; + } + }; + return sign(); + } + /** + * Create canonical headers for signing v4 url. + * + * The canonical headers for v4-signing a request demands header names are + * first lowercased, followed by sorting the header names. + * Then, construct the canonical headers part of the request: + * + ":" + Trim() + "\n" + * .. + * + ":" + Trim() + "\n" + * + * @param headers + * @private + */ + getCanonicalHeaders(headers) { + // Sort headers by their lowercased names + const sortedHeaders = objectEntries(headers) + // Convert header names to lowercase + .map(([headerName, value]) => [ + headerName.toLowerCase(), + value, + ]) + .sort((a, b) => a[0].localeCompare(b[0])); + return sortedHeaders + .filter(([, value]) => value !== undefined) + .map(([headerName, value]) => { + // - Convert Array (multi-valued header) into string, delimited by + // ',' (no space). + // - Trim leading and trailing spaces. + // - Convert sequential (2+) spaces into a single space + const canonicalValue = `${value}`.trim().replace(/\s{2,}/g, ' '); + return `${headerName}:${canonicalValue}\n`; + }) + .join(''); + } + getCanonicalRequest(method, path, query, headers, signedHeaders, contentSha256) { + return [ + method, + path, + query, + headers, + signedHeaders, + contentSha256 || 'UNSIGNED-PAYLOAD', + ].join('\n'); + } + getCanonicalQueryParams(query) { + return objectEntries(query) + .map(([key, value]) => [encodeURI(key, true), encodeURI(value, true)]) + .sort((a, b) => (a[0] < b[0] ? -1 : 1)) + .map(([key, value]) => `${key}=${value}`) + .join('&'); + } + getResourcePath(cname, bucket, file) { + if (cname) { + return '/' + (file || ''); + } + else if (file) { + return `/${bucket}/${file}`; + } + else { + return `/${bucket}`; + } + } + parseExpires(expires, current = new Date()) { + const expiresInMSeconds = new Date(expires).valueOf(); + if (isNaN(expiresInMSeconds)) { + throw new Error(ExceptionMessages.EXPIRATION_DATE_INVALID); + } + if (expiresInMSeconds < current.valueOf()) { + throw new Error(ExceptionMessages.EXPIRATION_DATE_PAST); + } + return Math.floor(expiresInMSeconds / 1000); // The API expects seconds. + } + parseAccessibleAt(accessibleAt) { + const accessibleAtInMSeconds = new Date(accessibleAt || new Date()).valueOf(); + if (isNaN(accessibleAtInMSeconds)) { + throw new Error(SignerExceptionMessages.ACCESSIBLE_DATE_INVALID); + } + return Math.floor(accessibleAtInMSeconds / 1000); // The API expects seconds. + } +} +/** + * Custom error type for errors related to getting signed errors and policies. + * + * @private + */ +export class SigningError extends Error { + constructor() { + super(...arguments); + this.name = 'SigningError'; + } +} diff --git a/node_modules/@google-cloud/storage/build/esm/src/storage.d.ts b/node_modules/@google-cloud/storage/build/esm/src/storage.d.ts new file mode 100644 index 0000000..393b59d --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/storage.d.ts @@ -0,0 +1,730 @@ +import { ApiError, Service, ServiceOptions } from './nodejs-common/index.js'; +import { Readable } from 'stream'; +import { Bucket, BucketMetadata } from './bucket.js'; +import { Channel } from './channel.js'; +import { File } from './file.js'; +import { HmacKey, HmacKeyMetadata, HmacKeyOptions } from './hmacKey.js'; +import { CRC32CValidatorGenerator } from './crc32c.js'; +export interface GetServiceAccountOptions { + userProject?: string; + projectIdentifier?: string; +} +export interface ServiceAccount { + emailAddress?: string; +} +export type GetServiceAccountResponse = [ServiceAccount, unknown]; +export interface GetServiceAccountCallback { + (err: Error | null, serviceAccount?: ServiceAccount, apiResponse?: unknown): void; +} +export interface CreateBucketQuery { + enableObjectRetention: boolean; + predefinedAcl?: 'authenticatedRead' | 'private' | 'projectPrivate' | 'publicRead' | 'publicReadWrite'; + predefinedDefaultObjectAcl?: 'authenticatedRead' | 'bucketOwnerFullControl' | 'bucketOwnerRead' | 'private' | 'projectPrivate' | 'publicRead'; + project: string; + projection?: 'full' | 'noAcl'; + userProject: string; +} +export declare enum IdempotencyStrategy { + RetryAlways = 0, + RetryConditional = 1, + RetryNever = 2 +} +export interface RetryOptions { + retryDelayMultiplier?: number; + totalTimeout?: number; + maxRetryDelay?: number; + autoRetry?: boolean; + maxRetries?: number; + retryableErrorFn?: (err: ApiError) => boolean; + idempotencyStrategy?: IdempotencyStrategy; +} +export interface PreconditionOptions { + ifGenerationMatch?: number | string; + ifGenerationNotMatch?: number | string; + ifMetagenerationMatch?: number | string; + ifMetagenerationNotMatch?: number | string; +} +export interface StorageOptions extends ServiceOptions { + /** + * The API endpoint of the service used to make requests. + * Defaults to `storage.googleapis.com`. + */ + apiEndpoint?: string; + crc32cGenerator?: CRC32CValidatorGenerator; + retryOptions?: RetryOptions; +} +export interface BucketOptions { + crc32cGenerator?: CRC32CValidatorGenerator; + kmsKeyName?: string; + preconditionOpts?: PreconditionOptions; + userProject?: string; + generation?: number; + softDeleted?: boolean; +} +export interface Cors { + maxAgeSeconds?: number; + method?: string[]; + origin?: string[]; + responseHeader?: string[]; +} +interface Versioning { + enabled: boolean; +} +/** + * Custom placement configuration. + * Initially used for dual-region buckets. + **/ +export interface CustomPlacementConfig { + dataLocations?: string[]; +} +export interface AutoclassConfig { + enabled?: boolean; + terminalStorageClass?: 'NEARLINE' | 'ARCHIVE'; +} +export interface CreateBucketRequest extends BucketMetadata { + archive?: boolean; + coldline?: boolean; + dataLocations?: string[]; + dra?: boolean; + enableObjectRetention?: boolean; + multiRegional?: boolean; + nearline?: boolean; + predefinedAcl?: 'authenticatedRead' | 'private' | 'projectPrivate' | 'publicRead' | 'publicReadWrite'; + predefinedDefaultObjectAcl?: 'authenticatedRead' | 'bucketOwnerFullControl' | 'bucketOwnerRead' | 'private' | 'projectPrivate' | 'publicRead'; + projection?: 'full' | 'noAcl'; + regional?: boolean; + requesterPays?: boolean; + rpo?: string; + standard?: boolean; + storageClass?: string; + userProject?: string; + versioning?: Versioning; +} +export type CreateBucketResponse = [Bucket, unknown]; +export interface BucketCallback { + (err: Error | null, bucket?: Bucket | null, apiResponse?: unknown): void; +} +export type GetBucketsResponse = [Bucket[], {}, unknown]; +export interface GetBucketsCallback { + (err: Error | null, buckets: Bucket[], nextQuery?: {}, apiResponse?: unknown): void; +} +export interface GetBucketsRequest { + prefix?: string; + project?: string; + autoPaginate?: boolean; + maxApiCalls?: number; + maxResults?: number; + pageToken?: string; + userProject?: string; + softDeleted?: boolean; + generation?: number; + returnPartialSuccess?: boolean; +} +export interface HmacKeyResourceResponse { + metadata: HmacKeyMetadata; + secret: string; +} +export type CreateHmacKeyResponse = [HmacKey, string, HmacKeyResourceResponse]; +export interface CreateHmacKeyOptions { + projectId?: string; + userProject?: string; +} +export interface CreateHmacKeyCallback { + (err: Error | null, hmacKey?: HmacKey | null, secret?: string | null, apiResponse?: HmacKeyResourceResponse): void; +} +export interface GetHmacKeysOptions { + projectId?: string; + serviceAccountEmail?: string; + showDeletedKeys?: boolean; + autoPaginate?: boolean; + maxApiCalls?: number; + maxResults?: number; + pageToken?: string; + userProject?: string; +} +export interface GetHmacKeysCallback { + (err: Error | null, hmacKeys: HmacKey[] | null, nextQuery?: {}, apiResponse?: unknown): void; +} +export declare enum ExceptionMessages { + EXPIRATION_DATE_INVALID = "The expiration date provided was invalid.", + EXPIRATION_DATE_PAST = "An expiration date cannot be in the past." +} +export declare enum StorageExceptionMessages { + BUCKET_NAME_REQUIRED = "A bucket name is needed to use Cloud Storage.", + BUCKET_NAME_REQUIRED_CREATE = "A name is required to create a bucket.", + HMAC_SERVICE_ACCOUNT = "The first argument must be a service account email to create an HMAC key.", + HMAC_ACCESS_ID = "An access ID is needed to create an HmacKey object." +} +export type GetHmacKeysResponse = [HmacKey[]]; +export declare const PROTOCOL_REGEX: RegExp; +/** + * Default behavior: Automatically retry retriable server errors. + * + * @const {boolean} + */ +export declare const AUTO_RETRY_DEFAULT = true; +/** + * Default behavior: Only attempt to retry retriable errors 3 times. + * + * @const {number} + */ +export declare const MAX_RETRY_DEFAULT = 3; +/** + * Default behavior: Wait twice as long as previous retry before retrying. + * + * @const {number} + */ +export declare const RETRY_DELAY_MULTIPLIER_DEFAULT = 2; +/** + * Default behavior: If the operation doesn't succeed after 600 seconds, + * stop retrying. + * + * @const {number} + */ +export declare const TOTAL_TIMEOUT_DEFAULT = 600; +/** + * Default behavior: Wait no more than 64 seconds between retries. + * + * @const {number} + */ +export declare const MAX_RETRY_DELAY_DEFAULT = 64; +/** + * Returns true if the API request should be retried, given the error that was + * given the first time the request was attempted. + * @const + * @param {error} err - The API error to check if it is appropriate to retry. + * @return {boolean} True if the API request should be retried, false otherwise. + */ +export declare const RETRYABLE_ERR_FN_DEFAULT: (err?: ApiError) => boolean; +/*! Developer Documentation + * + * Invoke this method to create a new Storage object bound with pre-determined + * configuration options. For each object that can be created (e.g., a bucket), + * there is an equivalent static and instance method. While they are classes, + * they can be instantiated without use of the `new` keyword. + */ +/** + * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share objects with other + * users and allow other users to access your buckets and objects. + * + * This object provides constants to refer to the three permission levels that + * can be granted to an entity: + * + * - `gcs.acl.OWNER_ROLE` - ("OWNER") + * - `gcs.acl.READER_ROLE` - ("READER") + * - `gcs.acl.WRITER_ROLE` - ("WRITER") + * + * See {@link https://cloud.google.com/storage/docs/access-control/lists| About Access Control Lists} + * + * @name Storage#acl + * @type {object} + * @property {string} OWNER_ROLE + * @property {string} READER_ROLE + * @property {string} WRITER_ROLE + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const albums = storage.bucket('albums'); + * + * //- + * // Make all of the files currently in a bucket publicly readable. + * //- + * const options = { + * entity: 'allUsers', + * role: storage.acl.READER_ROLE + * }; + * + * albums.acl.add(options, function(err, aclObject) {}); + * + * //- + * // Make any new objects added to a bucket publicly readable. + * //- + * albums.acl.default.add(options, function(err, aclObject) {}); + * + * //- + * // Grant a user ownership permissions to a bucket. + * //- + * albums.acl.add({ + * entity: 'user-useremail@example.com', + * role: storage.acl.OWNER_ROLE + * }, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * albums.acl.add(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ +/** + * Get {@link Bucket} objects for all of the buckets in your project as + * a readable object stream. + * + * @method Storage#getBucketsStream + * @param {GetBucketsRequest} [query] Query object for listing buckets. + * @returns {ReadableStream} A readable stream that emits {@link Bucket} + * instances. + * + * @example + * ``` + * storage.getBucketsStream() + * .on('error', console.error) + * .on('data', function(bucket) { + * // bucket is a Bucket object. + * }) + * .on('end', function() { + * // All buckets retrieved. + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * storage.getBucketsStream() + * .on('data', function(bucket) { + * this.end(); + * }); + * ``` + */ +/** + * Get {@link HmacKey} objects for all of the HMAC keys in the project in a + * readable object stream. + * + * @method Storage#getHmacKeysStream + * @param {GetHmacKeysOptions} [options] Configuration options. + * @returns {ReadableStream} A readable stream that emits {@link HmacKey} + * instances. + * + * @example + * ``` + * storage.getHmacKeysStream() + * .on('error', console.error) + * .on('data', function(hmacKey) { + * // hmacKey is an HmacKey object. + * }) + * .on('end', function() { + * // All HmacKey retrieved. + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * storage.getHmacKeysStream() + * .on('data', function(bucket) { + * this.end(); + * }); + * ``` + */ +/** + *

ACLs

+ * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share files with other users + * and allow other users to access your buckets and files. + * + * To learn more about ACLs, read this overview on + * {@link https://cloud.google.com/storage/docs/access-control| Access Control}. + * + * See {@link https://cloud.google.com/storage/docs/overview| Cloud Storage overview} + * See {@link https://cloud.google.com/storage/docs/access-control| Access Control} + * + * @class + */ +export declare class Storage extends Service { + /** + * {@link Bucket} class. + * + * @name Storage.Bucket + * @see Bucket + * @type {Constructor} + */ + static Bucket: typeof Bucket; + /** + * {@link Channel} class. + * + * @name Storage.Channel + * @see Channel + * @type {Constructor} + */ + static Channel: typeof Channel; + /** + * {@link File} class. + * + * @name Storage.File + * @see File + * @type {Constructor} + */ + static File: typeof File; + /** + * {@link HmacKey} class. + * + * @name Storage.HmacKey + * @see HmacKey + * @type {Constructor} + */ + static HmacKey: typeof HmacKey; + static acl: { + OWNER_ROLE: string; + READER_ROLE: string; + WRITER_ROLE: string; + }; + /** + * Reference to {@link Storage.acl}. + * + * @name Storage#acl + * @see Storage.acl + */ + acl: typeof Storage.acl; + crc32cGenerator: CRC32CValidatorGenerator; + getBucketsStream(): Readable; + getHmacKeysStream(): Readable; + retryOptions: RetryOptions; + /** + * @callback Crc32cGeneratorToStringCallback + * A method returning the CRC32C as a base64-encoded string. + * + * @returns {string} + * + * @example + * Hashing the string 'data' should return 'rth90Q==' + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.toString(); // 'rth90Q==' + * ``` + **/ + /** + * @callback Crc32cGeneratorValidateCallback + * A method validating a base64-encoded CRC32C string. + * + * @param {string} [value] base64-encoded CRC32C string to validate + * @returns {boolean} + * + * @example + * Should return `true` if the value matches, `false` otherwise + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.validate('DkjKuA=='); // false + * crc32c.validate('rth90Q=='); // true + * ``` + **/ + /** + * @callback Crc32cGeneratorUpdateCallback + * A method for passing `Buffer`s for CRC32C generation. + * + * @param {Buffer} [data] data to update CRC32C value with + * @returns {undefined} + * + * @example + * Hashing buffers from 'some ' and 'text\n' + * + * ```js + * const buffer1 = Buffer.from('some '); + * crc32c.update(buffer1); + * + * const buffer2 = Buffer.from('text\n'); + * crc32c.update(buffer2); + * + * crc32c.toString(); // 'DkjKuA==' + * ``` + **/ + /** + * @typedef {object} CRC32CValidator + * @property {Crc32cGeneratorToStringCallback} + * @property {Crc32cGeneratorValidateCallback} + * @property {Crc32cGeneratorUpdateCallback} + */ + /** + * @callback Crc32cGeneratorCallback + * @returns {CRC32CValidator} + */ + /** + * @typedef {object} StorageOptions + * @property {string} [projectId] The project ID from the Google Developer's + * Console, e.g. 'grape-spaceship-123'. We will also check the environment + * variable `GCLOUD_PROJECT` for your project ID. If your app is running + * in an environment which supports {@link + * https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application + * Application Default Credentials}, your project ID will be detected + * automatically. + * @property {string} [keyFilename] Full path to the a .json, .pem, or .p12 key + * downloaded from the Google Developers Console. If you provide a path to + * a JSON file, the `projectId` option above is not necessary. NOTE: .pem and + * .p12 require you to specify the `email` option as well. + * @property {string} [email] Account email address. Required when using a .pem + * or .p12 keyFilename. + * @property {object} [credentials] Credentials object. + * @property {string} [credentials.client_email] + * @property {string} [credentials.private_key] + * @property {object} [retryOptions] Options for customizing retries. Retriable server errors + * will be retried with exponential delay between them dictated by the formula + * max(maxRetryDelay, retryDelayMultiplier*retryNumber) until maxRetries or totalTimeout + * has been reached. Retries will only happen if autoRetry is set to true. + * @property {boolean} [retryOptions.autoRetry=true] Automatically retry requests if the + * response is related to rate limits or certain intermittent server + * errors. We will exponentially backoff subsequent requests by default. + * @property {number} [retryOptions.retryDelayMultiplier = 2] the multiplier by which to + * increase the delay time between the completion of failed requests, and the + * initiation of the subsequent retrying request. + * @property {number} [retryOptions.totalTimeout = 600] The total time, starting from + * when the initial request is sent, after which an error will + * be returned, regardless of the retrying attempts made meanwhile. + * @property {number} [retryOptions.maxRetryDelay = 64] The maximum delay time between requests. + * When this value is reached, ``retryDelayMultiplier`` will no longer be used to + * increase delay time. + * @property {number} [retryOptions.maxRetries=3] Maximum number of automatic retries + * attempted before returning the error. + * @property {function} [retryOptions.retryableErrorFn] Function that returns true if a given + * error should be retried and false otherwise. + * @property {enum} [retryOptions.idempotencyStrategy=IdempotencyStrategy.RetryConditional] Enumeration + * controls how conditionally idempotent operations are retried. Possible values are: RetryAlways - + * will respect other retry settings and attempt to retry conditionally idempotent operations. RetryConditional - + * will retry conditionally idempotent operations if the correct preconditions are set. RetryNever - never + * retry a conditionally idempotent operation. + * @property {string} [userAgent] The value to be prepended to the User-Agent + * header in API requests. + * @property {object} [authClient] `AuthClient` or `GoogleAuth` client to reuse instead of creating a new one. + * @property {number} [timeout] The amount of time in milliseconds to wait per http request before timing out. + * @property {object[]} [interceptors_] Array of custom request interceptors to be returned in the order they were assigned. + * @property {string} [apiEndpoint = storage.google.com] The API endpoint of the service used to make requests. + * @property {boolean} [useAuthWithCustomEndpoint = false] Controls whether or not to use authentication when using a custom endpoint. + * @property {Crc32cGeneratorCallback} [callback] A function that generates a CRC32C Validator. Defaults to {@link CRC32C} + */ + /** + * Constructs the Storage client. + * + * @example + * Create a client that uses Application Default Credentials + * (ADC) + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * ``` + * + * @example + * Create a client with explicit credentials + * ``` + * const storage = new Storage({ + * projectId: 'your-project-id', + * keyFilename: '/path/to/keyfile.json' + * }); + * ``` + * + * @example + * Create a client with credentials passed + * by value as a JavaScript object + * ``` + * const storage = new Storage({ + * projectId: 'your-project-id', + * credentials: { + * type: 'service_account', + * project_id: 'xxxxxxx', + * private_key_id: 'xxxx', + * private_key:'-----BEGIN PRIVATE KEY-----xxxxxxx\n-----END PRIVATE KEY-----\n', + * client_email: 'xxxx', + * client_id: 'xxx', + * auth_uri: 'https://accounts.google.com/o/oauth2/auth', + * token_uri: 'https://oauth2.googleapis.com/token', + * auth_provider_x509_cert_url: 'https://www.googleapis.com/oauth2/v1/certs', + * client_x509_cert_url: 'xxx', + * } + * }); + * ``` + * + * @example + * Create a client with credentials passed + * by loading a JSON file directly from disk + * ``` + * const storage = new Storage({ + * projectId: 'your-project-id', + * credentials: require('/path/to-keyfile.json') + * }); + * ``` + * + * @example + * Create a client with an `AuthClient` (e.g. `DownscopedClient`) + * ``` + * const {DownscopedClient} = require('google-auth-library'); + * const authClient = new DownscopedClient({...}); + * + * const storage = new Storage({authClient}); + * ``` + * + * Additional samples: + * - https://github.com/googleapis/google-auth-library-nodejs#sample-usage-1 + * - https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/downscopedclient.js + * + * @param {StorageOptions} [options] Configuration options. + */ + constructor(options?: StorageOptions); + private static sanitizeEndpoint; + /** + * Get a reference to a Cloud Storage bucket. + * + * @param {string} name Name of the bucket. + * @param {object} [options] Configuration object. + * @param {string} [options.kmsKeyName] A Cloud KMS key that will be used to + * encrypt objects inserted into this bucket, if no encryption method is + * specified. + * @param {string} [options.userProject] User project to be billed for all + * requests made from this Bucket object. + * @returns {Bucket} + * @see Bucket + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const albums = storage.bucket('albums'); + * const photos = storage.bucket('photos'); + * ``` + */ + bucket(name: string, options?: BucketOptions): Bucket; + /** + * Reference a channel to receive notifications about changes to your bucket. + * + * @param {string} id The ID of the channel. + * @param {string} resourceId The resource ID of the channel. + * @returns {Channel} + * @see Channel + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const channel = storage.channel('id', 'resource-id'); + * ``` + */ + channel(id: string, resourceId: string): Channel; + createBucket(name: string, metadata?: CreateBucketRequest): Promise; + createBucket(name: string, callback: BucketCallback): void; + createBucket(name: string, metadata: CreateBucketRequest, callback: BucketCallback): void; + createBucket(name: string, metadata: CreateBucketRequest, callback: BucketCallback): void; + createHmacKey(serviceAccountEmail: string, options?: CreateHmacKeyOptions): Promise; + createHmacKey(serviceAccountEmail: string, callback: CreateHmacKeyCallback): void; + createHmacKey(serviceAccountEmail: string, options: CreateHmacKeyOptions, callback: CreateHmacKeyCallback): void; + getBuckets(options?: GetBucketsRequest): Promise; + getBuckets(options: GetBucketsRequest, callback: GetBucketsCallback): void; + getBuckets(callback: GetBucketsCallback): void; + /** + * Query object for listing HMAC keys. + * + * @typedef {object} GetHmacKeysOptions + * @property {string} [projectId] The project ID of the project that owns + * the service account of the requested HMAC key. If not provided, + * the project ID used to instantiate the Storage client will be used. + * @property {string} [serviceAccountEmail] If present, only HMAC keys for the + * given service account are returned. + * @property {boolean} [showDeletedKeys=false] If true, include keys in the DELETE + * state. Default is false. + * @property {boolean} [autoPaginate=true] Have pagination handled + * automatically. + * @property {number} [maxApiCalls] Maximum number of API calls to make. + * @property {number} [maxResults] Maximum number of items plus prefixes to + * return per call. + * Note: By default will handle pagination automatically + * if more than 1 page worth of results are requested per call. + * When `autoPaginate` is set to `false` the smaller of `maxResults` + * or 1 page of results will be returned per call. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @property {string} [userProject] This parameter is currently ignored. + */ + /** + * @typedef {array} GetHmacKeysResponse + * @property {HmacKey[]} 0 Array of {@link HmacKey} instances. + * @param {object} nextQuery 1 A query object to receive more results. + * @param {object} apiResponse 2 The full API response. + */ + /** + * @callback GetHmacKeysCallback + * @param {?Error} err Request error, if any. + * @param {HmacKey[]} hmacKeys Array of {@link HmacKey} instances. + * @param {object} nextQuery A query object to receive more results. + * @param {object} apiResponse The full API response. + */ + /** + * Retrieves a list of HMAC keys matching the criteria. + * + * The authenticated user must have storage.hmacKeys.list permission for the project in which the key exists. + * + * @param {GetHmacKeysOption} options Configuration options. + * @param {GetHmacKeysCallback} callback Callback function. + * @return {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * storage.getHmacKeys(function(err, hmacKeys) { + * if (!err) { + * // hmacKeys is an array of HmacKey objects. + * } + * }); + * + * //- + * // To control how many API requests are made and page through the results + * // manually, set `autoPaginate` to `false`. + * //- + * const callback = function(err, hmacKeys, nextQuery, apiResponse) { + * if (nextQuery) { + * // More results exist. + * storage.getHmacKeys(nextQuery, callback); + * } + * + * // The `metadata` property is populated for you with the metadata at the + * // time of fetching. + * hmacKeys[0].metadata; + * }; + * + * storage.getHmacKeys({ + * autoPaginate: false + * }, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * storage.getHmacKeys().then(function(data) { + * const hmacKeys = data[0]; + * }); + * ``` + */ + getHmacKeys(options?: GetHmacKeysOptions): Promise; + getHmacKeys(callback: GetHmacKeysCallback): void; + getHmacKeys(options: GetHmacKeysOptions, callback: GetHmacKeysCallback): void; + getServiceAccount(options?: GetServiceAccountOptions): Promise; + getServiceAccount(options?: GetServiceAccountOptions): Promise; + getServiceAccount(options: GetServiceAccountOptions, callback: GetServiceAccountCallback): void; + getServiceAccount(callback: GetServiceAccountCallback): void; + /** + * Get a reference to an HmacKey object. + * Note: this does not fetch the HMAC key's metadata. Use HmacKey#get() to + * retrieve and populate the metadata. + * + * To get a reference to an HMAC key that's not created for a service + * account in the same project used to instantiate the Storage client, + * supply the project's ID as `projectId` in the `options` argument. + * + * @param {string} accessId The HMAC key's access ID. + * @param {HmacKeyOptions} options HmacKey constructor options. + * @returns {HmacKey} + * @see HmacKey + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const hmacKey = storage.hmacKey('ACCESS_ID'); + * ``` + */ + hmacKey(accessId: string, options?: HmacKeyOptions): HmacKey; +} +export {}; diff --git a/node_modules/@google-cloud/storage/build/esm/src/storage.js b/node_modules/@google-cloud/storage/build/esm/src/storage.js new file mode 100644 index 0000000..b2b50e7 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/storage.js @@ -0,0 +1,1170 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +import { Service } from './nodejs-common/index.js'; +import { paginator } from '@google-cloud/paginator'; +import { promisifyAll } from '@google-cloud/promisify'; +import { Readable } from 'stream'; +import { Bucket } from './bucket.js'; +import { Channel } from './channel.js'; +import { File } from './file.js'; +import { normalize } from './util.js'; +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore +import { getPackageJSON } from './package-json-helper.cjs'; +import { HmacKey } from './hmacKey.js'; +import { CRC32C_DEFAULT_VALIDATOR_GENERATOR, } from './crc32c.js'; +import { DEFAULT_UNIVERSE } from 'google-auth-library'; +export var IdempotencyStrategy; +(function (IdempotencyStrategy) { + IdempotencyStrategy[IdempotencyStrategy["RetryAlways"] = 0] = "RetryAlways"; + IdempotencyStrategy[IdempotencyStrategy["RetryConditional"] = 1] = "RetryConditional"; + IdempotencyStrategy[IdempotencyStrategy["RetryNever"] = 2] = "RetryNever"; +})(IdempotencyStrategy || (IdempotencyStrategy = {})); +export var ExceptionMessages; +(function (ExceptionMessages) { + ExceptionMessages["EXPIRATION_DATE_INVALID"] = "The expiration date provided was invalid."; + ExceptionMessages["EXPIRATION_DATE_PAST"] = "An expiration date cannot be in the past."; +})(ExceptionMessages || (ExceptionMessages = {})); +export var StorageExceptionMessages; +(function (StorageExceptionMessages) { + StorageExceptionMessages["BUCKET_NAME_REQUIRED"] = "A bucket name is needed to use Cloud Storage."; + StorageExceptionMessages["BUCKET_NAME_REQUIRED_CREATE"] = "A name is required to create a bucket."; + StorageExceptionMessages["HMAC_SERVICE_ACCOUNT"] = "The first argument must be a service account email to create an HMAC key."; + StorageExceptionMessages["HMAC_ACCESS_ID"] = "An access ID is needed to create an HmacKey object."; +})(StorageExceptionMessages || (StorageExceptionMessages = {})); +export const PROTOCOL_REGEX = /^(\w*):\/\//; +/** + * Default behavior: Automatically retry retriable server errors. + * + * @const {boolean} + */ +export const AUTO_RETRY_DEFAULT = true; +/** + * Default behavior: Only attempt to retry retriable errors 3 times. + * + * @const {number} + */ +export const MAX_RETRY_DEFAULT = 3; +/** + * Default behavior: Wait twice as long as previous retry before retrying. + * + * @const {number} + */ +export const RETRY_DELAY_MULTIPLIER_DEFAULT = 2; +/** + * Default behavior: If the operation doesn't succeed after 600 seconds, + * stop retrying. + * + * @const {number} + */ +export const TOTAL_TIMEOUT_DEFAULT = 600; +/** + * Default behavior: Wait no more than 64 seconds between retries. + * + * @const {number} + */ +export const MAX_RETRY_DELAY_DEFAULT = 64; +/** + * Default behavior: Retry conditionally idempotent operations if correct preconditions are set. + * + * @const {enum} + * @private + */ +const IDEMPOTENCY_STRATEGY_DEFAULT = IdempotencyStrategy.RetryConditional; +/** + * Returns true if the API request should be retried, given the error that was + * given the first time the request was attempted. + * @const + * @param {error} err - The API error to check if it is appropriate to retry. + * @return {boolean} True if the API request should be retried, false otherwise. + */ +export const RETRYABLE_ERR_FN_DEFAULT = function (err) { + var _a; + const isConnectionProblem = (reason) => { + return (reason.includes('eai_again') || // DNS lookup error + reason === 'econnreset' || + reason === 'unexpected connection closure' || + reason === 'epipe' || + reason === 'socket connection timeout'); + }; + if (err) { + if ([408, 429, 500, 502, 503, 504].indexOf(err.code) !== -1) { + return true; + } + if (typeof err.code === 'string') { + if (['408', '429', '500', '502', '503', '504'].indexOf(err.code) !== -1) { + return true; + } + const reason = err.code.toLowerCase(); + if (isConnectionProblem(reason)) { + return true; + } + } + if (err.errors) { + for (const e of err.errors) { + const reason = (_a = e === null || e === void 0 ? void 0 : e.reason) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase(); + if (reason && isConnectionProblem(reason)) { + return true; + } + } + } + } + return false; +}; +/*! Developer Documentation + * + * Invoke this method to create a new Storage object bound with pre-determined + * configuration options. For each object that can be created (e.g., a bucket), + * there is an equivalent static and instance method. While they are classes, + * they can be instantiated without use of the `new` keyword. + */ +/** + * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share objects with other + * users and allow other users to access your buckets and objects. + * + * This object provides constants to refer to the three permission levels that + * can be granted to an entity: + * + * - `gcs.acl.OWNER_ROLE` - ("OWNER") + * - `gcs.acl.READER_ROLE` - ("READER") + * - `gcs.acl.WRITER_ROLE` - ("WRITER") + * + * See {@link https://cloud.google.com/storage/docs/access-control/lists| About Access Control Lists} + * + * @name Storage#acl + * @type {object} + * @property {string} OWNER_ROLE + * @property {string} READER_ROLE + * @property {string} WRITER_ROLE + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const albums = storage.bucket('albums'); + * + * //- + * // Make all of the files currently in a bucket publicly readable. + * //- + * const options = { + * entity: 'allUsers', + * role: storage.acl.READER_ROLE + * }; + * + * albums.acl.add(options, function(err, aclObject) {}); + * + * //- + * // Make any new objects added to a bucket publicly readable. + * //- + * albums.acl.default.add(options, function(err, aclObject) {}); + * + * //- + * // Grant a user ownership permissions to a bucket. + * //- + * albums.acl.add({ + * entity: 'user-useremail@example.com', + * role: storage.acl.OWNER_ROLE + * }, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * albums.acl.add(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ +/** + * Get {@link Bucket} objects for all of the buckets in your project as + * a readable object stream. + * + * @method Storage#getBucketsStream + * @param {GetBucketsRequest} [query] Query object for listing buckets. + * @returns {ReadableStream} A readable stream that emits {@link Bucket} + * instances. + * + * @example + * ``` + * storage.getBucketsStream() + * .on('error', console.error) + * .on('data', function(bucket) { + * // bucket is a Bucket object. + * }) + * .on('end', function() { + * // All buckets retrieved. + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * storage.getBucketsStream() + * .on('data', function(bucket) { + * this.end(); + * }); + * ``` + */ +/** + * Get {@link HmacKey} objects for all of the HMAC keys in the project in a + * readable object stream. + * + * @method Storage#getHmacKeysStream + * @param {GetHmacKeysOptions} [options] Configuration options. + * @returns {ReadableStream} A readable stream that emits {@link HmacKey} + * instances. + * + * @example + * ``` + * storage.getHmacKeysStream() + * .on('error', console.error) + * .on('data', function(hmacKey) { + * // hmacKey is an HmacKey object. + * }) + * .on('end', function() { + * // All HmacKey retrieved. + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * storage.getHmacKeysStream() + * .on('data', function(bucket) { + * this.end(); + * }); + * ``` + */ +/** + *

ACLs

+ * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share files with other users + * and allow other users to access your buckets and files. + * + * To learn more about ACLs, read this overview on + * {@link https://cloud.google.com/storage/docs/access-control| Access Control}. + * + * See {@link https://cloud.google.com/storage/docs/overview| Cloud Storage overview} + * See {@link https://cloud.google.com/storage/docs/access-control| Access Control} + * + * @class + */ +export class Storage extends Service { + getBucketsStream() { + // placeholder body, overwritten in constructor + return new Readable(); + } + getHmacKeysStream() { + // placeholder body, overwritten in constructor + return new Readable(); + } + /** + * @callback Crc32cGeneratorToStringCallback + * A method returning the CRC32C as a base64-encoded string. + * + * @returns {string} + * + * @example + * Hashing the string 'data' should return 'rth90Q==' + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.toString(); // 'rth90Q==' + * ``` + **/ + /** + * @callback Crc32cGeneratorValidateCallback + * A method validating a base64-encoded CRC32C string. + * + * @param {string} [value] base64-encoded CRC32C string to validate + * @returns {boolean} + * + * @example + * Should return `true` if the value matches, `false` otherwise + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.validate('DkjKuA=='); // false + * crc32c.validate('rth90Q=='); // true + * ``` + **/ + /** + * @callback Crc32cGeneratorUpdateCallback + * A method for passing `Buffer`s for CRC32C generation. + * + * @param {Buffer} [data] data to update CRC32C value with + * @returns {undefined} + * + * @example + * Hashing buffers from 'some ' and 'text\n' + * + * ```js + * const buffer1 = Buffer.from('some '); + * crc32c.update(buffer1); + * + * const buffer2 = Buffer.from('text\n'); + * crc32c.update(buffer2); + * + * crc32c.toString(); // 'DkjKuA==' + * ``` + **/ + /** + * @typedef {object} CRC32CValidator + * @property {Crc32cGeneratorToStringCallback} + * @property {Crc32cGeneratorValidateCallback} + * @property {Crc32cGeneratorUpdateCallback} + */ + /** + * @callback Crc32cGeneratorCallback + * @returns {CRC32CValidator} + */ + /** + * @typedef {object} StorageOptions + * @property {string} [projectId] The project ID from the Google Developer's + * Console, e.g. 'grape-spaceship-123'. We will also check the environment + * variable `GCLOUD_PROJECT` for your project ID. If your app is running + * in an environment which supports {@link + * https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application + * Application Default Credentials}, your project ID will be detected + * automatically. + * @property {string} [keyFilename] Full path to the a .json, .pem, or .p12 key + * downloaded from the Google Developers Console. If you provide a path to + * a JSON file, the `projectId` option above is not necessary. NOTE: .pem and + * .p12 require you to specify the `email` option as well. + * @property {string} [email] Account email address. Required when using a .pem + * or .p12 keyFilename. + * @property {object} [credentials] Credentials object. + * @property {string} [credentials.client_email] + * @property {string} [credentials.private_key] + * @property {object} [retryOptions] Options for customizing retries. Retriable server errors + * will be retried with exponential delay between them dictated by the formula + * max(maxRetryDelay, retryDelayMultiplier*retryNumber) until maxRetries or totalTimeout + * has been reached. Retries will only happen if autoRetry is set to true. + * @property {boolean} [retryOptions.autoRetry=true] Automatically retry requests if the + * response is related to rate limits or certain intermittent server + * errors. We will exponentially backoff subsequent requests by default. + * @property {number} [retryOptions.retryDelayMultiplier = 2] the multiplier by which to + * increase the delay time between the completion of failed requests, and the + * initiation of the subsequent retrying request. + * @property {number} [retryOptions.totalTimeout = 600] The total time, starting from + * when the initial request is sent, after which an error will + * be returned, regardless of the retrying attempts made meanwhile. + * @property {number} [retryOptions.maxRetryDelay = 64] The maximum delay time between requests. + * When this value is reached, ``retryDelayMultiplier`` will no longer be used to + * increase delay time. + * @property {number} [retryOptions.maxRetries=3] Maximum number of automatic retries + * attempted before returning the error. + * @property {function} [retryOptions.retryableErrorFn] Function that returns true if a given + * error should be retried and false otherwise. + * @property {enum} [retryOptions.idempotencyStrategy=IdempotencyStrategy.RetryConditional] Enumeration + * controls how conditionally idempotent operations are retried. Possible values are: RetryAlways - + * will respect other retry settings and attempt to retry conditionally idempotent operations. RetryConditional - + * will retry conditionally idempotent operations if the correct preconditions are set. RetryNever - never + * retry a conditionally idempotent operation. + * @property {string} [userAgent] The value to be prepended to the User-Agent + * header in API requests. + * @property {object} [authClient] `AuthClient` or `GoogleAuth` client to reuse instead of creating a new one. + * @property {number} [timeout] The amount of time in milliseconds to wait per http request before timing out. + * @property {object[]} [interceptors_] Array of custom request interceptors to be returned in the order they were assigned. + * @property {string} [apiEndpoint = storage.google.com] The API endpoint of the service used to make requests. + * @property {boolean} [useAuthWithCustomEndpoint = false] Controls whether or not to use authentication when using a custom endpoint. + * @property {Crc32cGeneratorCallback} [callback] A function that generates a CRC32C Validator. Defaults to {@link CRC32C} + */ + /** + * Constructs the Storage client. + * + * @example + * Create a client that uses Application Default Credentials + * (ADC) + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * ``` + * + * @example + * Create a client with explicit credentials + * ``` + * const storage = new Storage({ + * projectId: 'your-project-id', + * keyFilename: '/path/to/keyfile.json' + * }); + * ``` + * + * @example + * Create a client with credentials passed + * by value as a JavaScript object + * ``` + * const storage = new Storage({ + * projectId: 'your-project-id', + * credentials: { + * type: 'service_account', + * project_id: 'xxxxxxx', + * private_key_id: 'xxxx', + * private_key:'-----BEGIN PRIVATE KEY-----xxxxxxx\n-----END PRIVATE KEY-----\n', + * client_email: 'xxxx', + * client_id: 'xxx', + * auth_uri: 'https://accounts.google.com/o/oauth2/auth', + * token_uri: 'https://oauth2.googleapis.com/token', + * auth_provider_x509_cert_url: 'https://www.googleapis.com/oauth2/v1/certs', + * client_x509_cert_url: 'xxx', + * } + * }); + * ``` + * + * @example + * Create a client with credentials passed + * by loading a JSON file directly from disk + * ``` + * const storage = new Storage({ + * projectId: 'your-project-id', + * credentials: require('/path/to-keyfile.json') + * }); + * ``` + * + * @example + * Create a client with an `AuthClient` (e.g. `DownscopedClient`) + * ``` + * const {DownscopedClient} = require('google-auth-library'); + * const authClient = new DownscopedClient({...}); + * + * const storage = new Storage({authClient}); + * ``` + * + * Additional samples: + * - https://github.com/googleapis/google-auth-library-nodejs#sample-usage-1 + * - https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/downscopedclient.js + * + * @param {StorageOptions} [options] Configuration options. + */ + constructor(options = {}) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; + const universe = options.universeDomain || DEFAULT_UNIVERSE; + let apiEndpoint = `https://storage.${universe}`; + let customEndpoint = false; + // Note: EMULATOR_HOST is an experimental configuration variable. Use apiEndpoint instead. + const EMULATOR_HOST = process.env.STORAGE_EMULATOR_HOST; + if (typeof EMULATOR_HOST === 'string') { + apiEndpoint = Storage.sanitizeEndpoint(EMULATOR_HOST); + customEndpoint = true; + } + if (options.apiEndpoint && options.apiEndpoint !== apiEndpoint) { + apiEndpoint = Storage.sanitizeEndpoint(options.apiEndpoint); + customEndpoint = true; + } + options = Object.assign({}, options, { apiEndpoint }); + // Note: EMULATOR_HOST is an experimental configuration variable. Use apiEndpoint instead. + const baseUrl = EMULATOR_HOST || `${options.apiEndpoint}/storage/v1`; + const config = { + apiEndpoint: options.apiEndpoint, + retryOptions: { + autoRetry: ((_a = options.retryOptions) === null || _a === void 0 ? void 0 : _a.autoRetry) !== undefined + ? (_b = options.retryOptions) === null || _b === void 0 ? void 0 : _b.autoRetry + : AUTO_RETRY_DEFAULT, + maxRetries: ((_c = options.retryOptions) === null || _c === void 0 ? void 0 : _c.maxRetries) + ? (_d = options.retryOptions) === null || _d === void 0 ? void 0 : _d.maxRetries + : MAX_RETRY_DEFAULT, + retryDelayMultiplier: ((_e = options.retryOptions) === null || _e === void 0 ? void 0 : _e.retryDelayMultiplier) + ? (_f = options.retryOptions) === null || _f === void 0 ? void 0 : _f.retryDelayMultiplier + : RETRY_DELAY_MULTIPLIER_DEFAULT, + totalTimeout: ((_g = options.retryOptions) === null || _g === void 0 ? void 0 : _g.totalTimeout) + ? (_h = options.retryOptions) === null || _h === void 0 ? void 0 : _h.totalTimeout + : TOTAL_TIMEOUT_DEFAULT, + maxRetryDelay: ((_j = options.retryOptions) === null || _j === void 0 ? void 0 : _j.maxRetryDelay) + ? (_k = options.retryOptions) === null || _k === void 0 ? void 0 : _k.maxRetryDelay + : MAX_RETRY_DELAY_DEFAULT, + retryableErrorFn: ((_l = options.retryOptions) === null || _l === void 0 ? void 0 : _l.retryableErrorFn) + ? (_m = options.retryOptions) === null || _m === void 0 ? void 0 : _m.retryableErrorFn + : RETRYABLE_ERR_FN_DEFAULT, + idempotencyStrategy: ((_o = options.retryOptions) === null || _o === void 0 ? void 0 : _o.idempotencyStrategy) !== undefined + ? (_p = options.retryOptions) === null || _p === void 0 ? void 0 : _p.idempotencyStrategy + : IDEMPOTENCY_STRATEGY_DEFAULT, + }, + baseUrl, + customEndpoint, + useAuthWithCustomEndpoint: options === null || options === void 0 ? void 0 : options.useAuthWithCustomEndpoint, + projectIdRequired: false, + scopes: [ + 'https://www.googleapis.com/auth/iam', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/devstorage.full_control', + ], + packageJson: getPackageJSON(), + }; + super(config, options); + /** + * Reference to {@link Storage.acl}. + * + * @name Storage#acl + * @see Storage.acl + */ + this.acl = Storage.acl; + this.crc32cGenerator = + options.crc32cGenerator || CRC32C_DEFAULT_VALIDATOR_GENERATOR; + this.retryOptions = config.retryOptions; + this.getBucketsStream = paginator.streamify('getBuckets'); + this.getHmacKeysStream = paginator.streamify('getHmacKeys'); + } + static sanitizeEndpoint(url) { + if (!PROTOCOL_REGEX.test(url)) { + url = `https://${url}`; + } + return url.replace(/\/+$/, ''); // Remove trailing slashes + } + /** + * Get a reference to a Cloud Storage bucket. + * + * @param {string} name Name of the bucket. + * @param {object} [options] Configuration object. + * @param {string} [options.kmsKeyName] A Cloud KMS key that will be used to + * encrypt objects inserted into this bucket, if no encryption method is + * specified. + * @param {string} [options.userProject] User project to be billed for all + * requests made from this Bucket object. + * @returns {Bucket} + * @see Bucket + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const albums = storage.bucket('albums'); + * const photos = storage.bucket('photos'); + * ``` + */ + bucket(name, options) { + if (!name) { + throw new Error(StorageExceptionMessages.BUCKET_NAME_REQUIRED); + } + return new Bucket(this, name, options); + } + /** + * Reference a channel to receive notifications about changes to your bucket. + * + * @param {string} id The ID of the channel. + * @param {string} resourceId The resource ID of the channel. + * @returns {Channel} + * @see Channel + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const channel = storage.channel('id', 'resource-id'); + * ``` + */ + channel(id, resourceId) { + return new Channel(this, id, resourceId); + } + /** + * @typedef {array} CreateBucketResponse + * @property {Bucket} 0 The new {@link Bucket}. + * @property {object} 1 The full API response. + */ + /** + * @callback CreateBucketCallback + * @param {?Error} err Request error, if any. + * @param {Bucket} bucket The new {@link Bucket}. + * @param {object} apiResponse The full API response. + */ + /** + * Metadata to set for the bucket. + * + * @typedef {object} CreateBucketRequest + * @property {boolean} [archive=false] Specify the storage class as Archive. + * @property {object} [autoclass.enabled=false] Specify whether Autoclass is + * enabled for the bucket. + * @property {object} [autoclass.terminalStorageClass='NEARLINE'] The storage class that objects in an Autoclass bucket eventually transition to if + * they are not read for a certain length of time. Valid values are NEARLINE and ARCHIVE. + * @property {boolean} [coldline=false] Specify the storage class as Coldline. + * @property {Cors[]} [cors=[]] Specify the CORS configuration to use. + * @property {CustomPlacementConfig} [customPlacementConfig={}] Specify the bucket's regions for dual-region buckets. + * For more information, see {@link https://cloud.google.com/storage/docs/locations| Bucket Locations}. + * @property {boolean} [dra=false] Specify the storage class as Durable Reduced + * Availability. + * @property {boolean} [enableObjectRetention=false] Specify whether or not object retention should be enabled on this bucket. + * @property {object} [hierarchicalNamespace.enabled=false] Specify whether or not to enable hierarchical namespace on this bucket. + * @property {string} [location] Specify the bucket's location. If specifying + * a dual-region, the `customPlacementConfig` property should be set in conjunction. + * For more information, see {@link https://cloud.google.com/storage/docs/locations| Bucket Locations}. + * @property {boolean} [multiRegional=false] Specify the storage class as + * Multi-Regional. + * @property {boolean} [nearline=false] Specify the storage class as Nearline. + * @property {boolean} [regional=false] Specify the storage class as Regional. + * @property {boolean} [requesterPays=false] Force the use of the User Project metadata field to assign operational + * costs when an operation is made on a Bucket and its objects. + * @property {string} [rpo] For dual-region buckets, controls whether turbo + * replication is enabled (`ASYNC_TURBO`) or disabled (`DEFAULT`). + * @property {boolean} [standard=true] Specify the storage class as Standard. + * @property {string} [storageClass] The new storage class. (`standard`, + * `nearline`, `coldline`, or `archive`). + * **Note:** The storage classes `multi_regional`, `regional`, and + * `durable_reduced_availability` are now legacy and will be deprecated in + * the future. + * @property {Versioning} [versioning=undefined] Specify the versioning status. + * @property {string} [userProject] The ID of the project which will be billed + * for the request. + */ + /** + * Create a bucket. + * + * Cloud Storage uses a flat namespace, so you can't create a bucket with + * a name that is already in use. For more information, see + * {@link https://cloud.google.com/storage/docs/bucketnaming.html#requirements| Bucket Naming Guidelines}. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/insert| Buckets: insert API Documentation} + * See {@link https://cloud.google.com/storage/docs/storage-classes| Storage Classes} + * + * @param {string} name Name of the bucket to create. + * @param {CreateBucketRequest} [metadata] Metadata to set for the bucket. + * @param {CreateBucketCallback} [callback] Callback function. + * @returns {Promise} + * @throws {Error} If a name is not provided. + * @see Bucket#create + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const callback = function(err, bucket, apiResponse) { + * // `bucket` is a Bucket object. + * }; + * + * storage.createBucket('new-bucket', callback); + * + * //- + * // Create a bucket in a specific location and region. See the + * // Official JSON API docs for complete details on the `location` + * option. + * // + * //- + * const metadata = { + * location: 'US-CENTRAL1', + * regional: true + * }; + * + * storage.createBucket('new-bucket', metadata, callback); + * + * //- + * // Create a bucket with a retention policy of 6 months. + * //- + * const metadata = { + * retentionPolicy: { + * retentionPeriod: 15780000 // 6 months in seconds. + * } + * }; + * + * storage.createBucket('new-bucket', metadata, callback); + * + * //- + * // Enable versioning on a new bucket. + * //- + * const metadata = { + * versioning: { + * enabled: true + * } + * }; + * + * storage.createBucket('new-bucket', metadata, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * storage.createBucket('new-bucket').then(function(data) { + * const bucket = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example include:samples/buckets.js + * region_tag:storage_create_bucket + * Another example: + */ + createBucket(name, metadataOrCallback, callback) { + if (!name) { + throw new Error(StorageExceptionMessages.BUCKET_NAME_REQUIRED_CREATE); + } + let metadata; + if (!callback) { + callback = metadataOrCallback; + metadata = {}; + } + else { + metadata = metadataOrCallback; + } + const body = { + ...metadata, + name, + }; + const storageClasses = { + archive: 'ARCHIVE', + coldline: 'COLDLINE', + dra: 'DURABLE_REDUCED_AVAILABILITY', + multiRegional: 'MULTI_REGIONAL', + nearline: 'NEARLINE', + regional: 'REGIONAL', + standard: 'STANDARD', + }; + const storageClassKeys = Object.keys(storageClasses); + for (const storageClass of storageClassKeys) { + if (body[storageClass]) { + if (metadata.storageClass && metadata.storageClass !== storageClass) { + throw new Error(`Both \`${storageClass}\` and \`storageClass\` were provided.`); + } + body.storageClass = storageClasses[storageClass]; + delete body[storageClass]; + } + } + if (body.requesterPays) { + body.billing = { + requesterPays: body.requesterPays, + }; + delete body.requesterPays; + } + const query = { + project: this.projectId, + }; + if (body.userProject) { + query.userProject = body.userProject; + delete body.userProject; + } + if (body.enableObjectRetention) { + query.enableObjectRetention = body.enableObjectRetention; + delete body.enableObjectRetention; + } + if (body.predefinedAcl) { + query.predefinedAcl = body.predefinedAcl; + delete body.predefinedAcl; + } + if (body.predefinedDefaultObjectAcl) { + query.predefinedDefaultObjectAcl = body.predefinedDefaultObjectAcl; + delete body.predefinedDefaultObjectAcl; + } + if (body.projection) { + query.projection = body.projection; + delete body.projection; + } + this.request({ + method: 'POST', + uri: '/b', + qs: query, + json: body, + }, (err, resp) => { + if (err) { + callback(err, null, resp); + return; + } + const bucket = this.bucket(name); + bucket.metadata = resp; + callback(null, bucket, resp); + }); + } + /** + * @typedef {object} CreateHmacKeyOptions + * @property {string} [projectId] The project ID of the project that owns + * the service account of the requested HMAC key. If not provided, + * the project ID used to instantiate the Storage client will be used. + * @property {string} [userProject] This parameter is currently ignored. + */ + /** + * @typedef {object} HmacKeyMetadata + * @property {string} accessId The access id identifies which HMAC key was + * used to sign a request when authenticating with HMAC. + * @property {string} etag Used to perform a read-modify-write of the key. + * @property {string} id The resource name of the HMAC key. + * @property {string} projectId The project ID. + * @property {string} serviceAccountEmail The service account's email this + * HMAC key is created for. + * @property {string} state The state of this HMAC key. One of "ACTIVE", + * "INACTIVE" or "DELETED". + * @property {string} timeCreated The creation time of the HMAC key in + * RFC 3339 format. + * @property {string} [updated] The time this HMAC key was last updated in + * RFC 3339 format. + */ + /** + * @typedef {array} CreateHmacKeyResponse + * @property {HmacKey} 0 The HmacKey instance created from API response. + * @property {string} 1 The HMAC key's secret used to access the XML API. + * @property {object} 3 The raw API response. + */ + /** + * @callback CreateHmacKeyCallback Callback function. + * @param {?Error} err Request error, if any. + * @param {HmacKey} hmacKey The HmacKey instance created from API response. + * @param {string} secret The HMAC key's secret used to access the XML API. + * @param {object} apiResponse The raw API response. + */ + /** + * Create an HMAC key associated with an service account to authenticate + * requests to the Cloud Storage XML API. + * + * See {@link https://cloud.google.com/storage/docs/authentication/hmackeys| HMAC keys documentation} + * + * @param {string} serviceAccountEmail The service account's email address + * with which the HMAC key is created for. + * @param {CreateHmacKeyCallback} [callback] Callback function. + * @return {Promise} + * + * @example + * ``` + * const {Storage} = require('google-cloud/storage'); + * const storage = new Storage(); + * + * // Replace with your service account's email address + * const serviceAccountEmail = + * 'my-service-account@appspot.gserviceaccount.com'; + * + * storage.createHmacKey(serviceAccountEmail, function(err, hmacKey, secret) { + * if (!err) { + * // Securely store the secret for use with the XML API. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * storage.createHmacKey(serviceAccountEmail) + * .then((response) => { + * const hmacKey = response[0]; + * const secret = response[1]; + * // Securely store the secret for use with the XML API. + * }); + * ``` + */ + createHmacKey(serviceAccountEmail, optionsOrCb, cb) { + if (typeof serviceAccountEmail !== 'string') { + throw new Error(StorageExceptionMessages.HMAC_SERVICE_ACCOUNT); + } + const { options, callback } = normalize(optionsOrCb, cb); + const query = Object.assign({}, options, { serviceAccountEmail }); + const projectId = query.projectId || this.projectId; + delete query.projectId; + this.request({ + method: 'POST', + uri: `/projects/${projectId}/hmacKeys`, + qs: query, + maxRetries: 0, //explicitly set this value since this is a non-idempotent function + }, (err, resp) => { + if (err) { + callback(err, null, null, resp); + return; + } + const metadata = resp.metadata; + const hmacKey = this.hmacKey(metadata.accessId, { + projectId: metadata.projectId, + }); + hmacKey.metadata = resp.metadata; + callback(null, hmacKey, resp.secret, resp); + }); + } + /** + * Query object for listing buckets. + * + * @typedef {object} GetBucketsRequest + * @property {boolean} [autoPaginate=true] Have pagination handled + * automatically. + * @property {number} [maxApiCalls] Maximum number of API calls to make. + * @property {number} [maxResults] Maximum number of items plus prefixes to + * return per call. + * Note: By default will handle pagination automatically + * if more than 1 page worth of results are requested per call. + * When `autoPaginate` is set to `false` the smaller of `maxResults` + * or 1 page of results will be returned per call. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @property {string} [userProject] The ID of the project which will be billed + * for the request. + * @param {boolean} [softDeleted] If true, returns the soft-deleted object. + * Object `generation` is required if `softDeleted` is set to True. + */ + /** + * @typedef {array} GetBucketsResponse + * @property {Bucket[]} 0 Array of {@link Bucket} instances. + * @property {object} 1 nextQuery A query object to receive more results. + * @property {object} 2 The full API response. + */ + /** + * @callback GetBucketsCallback + * @param {?Error} err Request error, if any. + * @param {Bucket[]} buckets Array of {@link Bucket} instances. + * @param {object} nextQuery A query object to receive more results. + * @param {object} apiResponse The full API response. + */ + /** + * Get Bucket objects for all of the buckets in your project. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/list| Buckets: list API Documentation} + * + * @param {GetBucketsRequest} [query] Query object for listing buckets. + * @param {GetBucketsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * storage.getBuckets(function(err, buckets) { + * if (!err) { + * // buckets is an array of Bucket objects. + * } + * }); + * + * //- + * // To control how many API requests are made and page through the results + * // manually, set `autoPaginate` to `false`. + * //- + * const callback = function(err, buckets, nextQuery, apiResponse) { + * if (nextQuery) { + * // More results exist. + * storage.getBuckets(nextQuery, callback); + * } + * + * // The `metadata` property is populated for you with the metadata at the + * // time of fetching. + * buckets[0].metadata; + * + * // However, in cases where you are concerned the metadata could have + * // changed, use the `getMetadata` method. + * buckets[0].getMetadata(function(err, metadata, apiResponse) {}); + * }; + * + * storage.getBuckets({ + * autoPaginate: false + * }, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * storage.getBuckets().then(function(data) { + * const buckets = data[0]; + * }); + * + * ``` + * @example include:samples/buckets.js + * region_tag:storage_list_buckets + * Another example: + */ + getBuckets(optionsOrCallback, cb) { + const { options, callback } = normalize(optionsOrCallback, cb); + options.project = options.project || this.projectId; + this.request({ + uri: '/b', + qs: options, + }, (err, resp) => { + if (err) { + callback(err, null, null, resp); + return; + } + const itemsArray = resp.items ? resp.items : []; + const unreachableArray = resp.unreachable ? resp.unreachable : []; + const buckets = itemsArray.map((bucket) => { + const bucketInstance = this.bucket(bucket.id); + bucketInstance.metadata = bucket; + return bucketInstance; + }); + if (unreachableArray.length > 0) { + unreachableArray.forEach((fullPath) => { + const name = fullPath.split('/').pop(); + if (name) { + const placeholder = this.bucket(name); + placeholder.unreachable = true; + placeholder.metadata = {}; + buckets.push(placeholder); + } + }); + } + const nextQuery = resp.nextPageToken + ? Object.assign({}, options, { pageToken: resp.nextPageToken }) + : null; + callback(null, buckets, nextQuery, resp); + }); + } + getHmacKeys(optionsOrCb, cb) { + const { options, callback } = normalize(optionsOrCb, cb); + const query = Object.assign({}, options); + const projectId = query.projectId || this.projectId; + delete query.projectId; + this.request({ + uri: `/projects/${projectId}/hmacKeys`, + qs: query, + }, (err, resp) => { + if (err) { + callback(err, null, null, resp); + return; + } + const itemsArray = resp.items ? resp.items : []; + const hmacKeys = itemsArray.map((hmacKey) => { + const hmacKeyInstance = this.hmacKey(hmacKey.accessId, { + projectId: hmacKey.projectId, + }); + hmacKeyInstance.metadata = hmacKey; + return hmacKeyInstance; + }); + const nextQuery = resp.nextPageToken + ? Object.assign({}, options, { pageToken: resp.nextPageToken }) + : null; + callback(null, hmacKeys, nextQuery, resp); + }); + } + /** + * @typedef {array} GetServiceAccountResponse + * @property {object} 0 The service account resource. + * @property {object} 1 The full + * {@link https://cloud.google.com/storage/docs/json_api/v1/projects/serviceAccount#resource| API response}. + */ + /** + * @callback GetServiceAccountCallback + * @param {?Error} err Request error, if any. + * @param {object} serviceAccount The serviceAccount resource. + * @param {string} serviceAccount.emailAddress The service account email + * address. + * @param {object} apiResponse The full + * {@link https://cloud.google.com/storage/docs/json_api/v1/projects/serviceAccount#resource| API response}. + */ + /** + * Get the email address of this project's Google Cloud Storage service + * account. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/projects/serviceAccount/get| Projects.serviceAccount: get API Documentation} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/projects/serviceAccount#resource| Projects.serviceAccount Resource} + * + * @param {object} [options] Configuration object. + * @param {string} [options.userProject] User project to be billed for this + * request. + * @param {GetServiceAccountCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * storage.getServiceAccount(function(err, serviceAccount, apiResponse) { + * if (!err) { + * const serviceAccountEmail = serviceAccount.emailAddress; + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * storage.getServiceAccount().then(function(data) { + * const serviceAccountEmail = data[0].emailAddress; + * const apiResponse = data[1]; + * }); + * ``` + */ + getServiceAccount(optionsOrCallback, cb) { + const { options, callback } = normalize(optionsOrCallback, cb); + this.request({ + uri: `/projects/${this.projectId}/serviceAccount`, + qs: options, + }, (err, resp) => { + if (err) { + callback(err, null, resp); + return; + } + const camelCaseResponse = {}; + for (const prop in resp) { + // eslint-disable-next-line no-prototype-builtins + if (resp.hasOwnProperty(prop)) { + const camelCaseProp = prop.replace(/_(\w)/g, (_, match) => match.toUpperCase()); + camelCaseResponse[camelCaseProp] = resp[prop]; + } + } + callback(null, camelCaseResponse, resp); + }); + } + /** + * Get a reference to an HmacKey object. + * Note: this does not fetch the HMAC key's metadata. Use HmacKey#get() to + * retrieve and populate the metadata. + * + * To get a reference to an HMAC key that's not created for a service + * account in the same project used to instantiate the Storage client, + * supply the project's ID as `projectId` in the `options` argument. + * + * @param {string} accessId The HMAC key's access ID. + * @param {HmacKeyOptions} options HmacKey constructor options. + * @returns {HmacKey} + * @see HmacKey + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const hmacKey = storage.hmacKey('ACCESS_ID'); + * ``` + */ + hmacKey(accessId, options) { + if (!accessId) { + throw new Error(StorageExceptionMessages.HMAC_ACCESS_ID); + } + return new HmacKey(this, accessId, options); + } +} +/** + * {@link Bucket} class. + * + * @name Storage.Bucket + * @see Bucket + * @type {Constructor} + */ +Storage.Bucket = Bucket; +/** + * {@link Channel} class. + * + * @name Storage.Channel + * @see Channel + * @type {Constructor} + */ +Storage.Channel = Channel; +/** + * {@link File} class. + * + * @name Storage.File + * @see File + * @type {Constructor} + */ +Storage.File = File; +/** + * {@link HmacKey} class. + * + * @name Storage.HmacKey + * @see HmacKey + * @type {Constructor} + */ +Storage.HmacKey = HmacKey; +Storage.acl = { + OWNER_ROLE: 'OWNER', + READER_ROLE: 'READER', + WRITER_ROLE: 'WRITER', +}; +/*! Developer Documentation + * + * These methods can be auto-paginated. + */ +paginator.extend(Storage, ['getBuckets', 'getHmacKeys']); +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Storage, { + exclude: ['bucket', 'channel', 'hmacKey'], +}); diff --git a/node_modules/@google-cloud/storage/build/esm/src/transfer-manager.d.ts b/node_modules/@google-cloud/storage/build/esm/src/transfer-manager.d.ts new file mode 100644 index 0000000..c846e94 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/transfer-manager.d.ts @@ -0,0 +1,253 @@ +/*! + * Copyright 2022 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. + */ +import { Bucket, UploadOptions, UploadResponse } from './bucket.js'; +import { DownloadOptions, DownloadResponse, File } from './file.js'; +import { GaxiosResponse } from 'gaxios'; +export interface UploadManyFilesOptions { + concurrencyLimit?: number; + customDestinationBuilder?(path: string, options: UploadManyFilesOptions): string; + skipIfExists?: boolean; + prefix?: string; + passthroughOptions?: Omit; +} +export interface DownloadManyFilesOptions { + concurrencyLimit?: number; + prefix?: string; + stripPrefix?: string; + passthroughOptions?: DownloadOptions; + skipIfExists?: boolean; +} +export interface DownloadFileInChunksOptions { + concurrencyLimit?: number; + chunkSizeBytes?: number; + destination?: string; + validation?: 'crc32c' | false; + noReturnData?: boolean; +} +export interface UploadFileInChunksOptions { + concurrencyLimit?: number; + chunkSizeBytes?: number; + uploadName?: string; + maxQueueSize?: number; + uploadId?: string; + autoAbortFailure?: boolean; + partsMap?: Map; + validation?: 'md5' | false; + headers?: { + [key: string]: string; + }; +} +export interface MultiPartUploadHelper { + bucket: Bucket; + fileName: string; + uploadId?: string; + partsMap?: Map; + initiateUpload(headers?: { + [key: string]: string; + }): Promise; + uploadPart(partNumber: number, chunk: Buffer, validation?: 'md5' | false): Promise; + completeUpload(): Promise; + abortUpload(): Promise; +} +export type MultiPartHelperGenerator = (bucket: Bucket, fileName: string, uploadId?: string, partsMap?: Map) => MultiPartUploadHelper; +export declare class MultiPartUploadError extends Error { + private uploadId; + private partsMap; + constructor(message: string, uploadId: string, partsMap: Map); +} +/** + * Create a TransferManager object to perform parallel transfer operations on a Cloud Storage bucket. + * + * @class + * @hideconstructor + * + * @param {Bucket} bucket A {@link Bucket} instance + * + */ +export declare class TransferManager { + bucket: Bucket; + constructor(bucket: Bucket); + /** + * @typedef {object} UploadManyFilesOptions + * @property {number} [concurrencyLimit] The number of concurrently executing promises + * to use when uploading the files. + * @property {Function} [customDestinationBuilder] A function that will take the current path of a local file + * and return a string representing a custom path to be used to upload the file to GCS. + * @property {boolean} [skipIfExists] Do not upload the file if it already exists in + * the bucket. This will set the precondition ifGenerationMatch = 0. + * @property {string} [prefix] A prefix to append to all of the uploaded files. + * @property {object} [passthroughOptions] {@link UploadOptions} Options to be passed through + * to each individual upload operation. + * + */ + /** + * Upload multiple files in parallel to the bucket. This is a convenience method + * that utilizes {@link Bucket#upload} to perform the upload. + * + * @param {array | string} [filePathsOrDirectory] An array of fully qualified paths to the files or a directory name. + * If a directory name is provided, the directory will be recursively walked and all files will be added to the upload list. + * to be uploaded to the bucket + * @param {UploadManyFilesOptions} [options] Configuration options. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const transferManager = new TransferManager(bucket); + * + * //- + * // Upload multiple files in parallel. + * //- + * const response = await transferManager.uploadManyFiles(['/local/path/file1.txt, 'local/path/file2.txt']); + * // Your bucket now contains: + * // - "local/path/file1.txt" (with the contents of '/local/path/file1.txt') + * // - "local/path/file2.txt" (with the contents of '/local/path/file2.txt') + * const response = await transferManager.uploadManyFiles('/local/directory'); + * // Your bucket will now contain all files contained in '/local/directory' maintaining the subdirectory structure. + * ``` + * + */ + uploadManyFiles(filePathsOrDirectory: string[] | string, options?: UploadManyFilesOptions): Promise; + /** + * @typedef {object} DownloadManyFilesOptions + * @property {number} [concurrencyLimit] The number of concurrently executing promises + * to use when downloading the files. + * @property {string} [prefix] A prefix to append to all of the downloaded files. + * @property {string} [stripPrefix] A prefix to remove from all of the downloaded files. + * @property {object} [passthroughOptions] {@link DownloadOptions} Options to be passed through + * to each individual download operation. + * @property {boolean} [skipIfExists] Do not download the file if it already exists in + * the destination. + * + */ + /** + * Download multiple files in parallel to the local filesystem. This is a convenience method + * that utilizes {@link File#download} to perform the download. + * + * @param {array | string} [filesOrFolder] An array of file name strings or file objects to be downloaded. If + * a string is provided this will be treated as a GCS prefix and all files with that prefix will be downloaded. + * @param {DownloadManyFilesOptions} [options] Configuration options. Setting options.prefix or options.stripPrefix + * or options.passthroughOptions.destination will cause the downloaded files to be written to the file system + * instead of being returned as a buffer. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const transferManager = new TransferManager(bucket); + * + * //- + * // Download multiple files in parallel. + * //- + * const response = await transferManager.downloadManyFiles(['file1.txt', 'file2.txt']); + * // The following files have been downloaded: + * // - "file1.txt" (with the contents from my-bucket.file1.txt) + * // - "file2.txt" (with the contents from my-bucket.file2.txt) + * const response = await transferManager.downloadManyFiles([bucket.File('file1.txt'), bucket.File('file2.txt')]); + * // The following files have been downloaded: + * // - "file1.txt" (with the contents from my-bucket.file1.txt) + * // - "file2.txt" (with the contents from my-bucket.file2.txt) + * const response = await transferManager.downloadManyFiles('test-folder'); + * // All files with GCS prefix of 'test-folder' have been downloaded. + * ``` + * + */ + downloadManyFiles(filesOrFolder: File[] | string[] | string, options?: DownloadManyFilesOptions): Promise; + /** + * @typedef {object} DownloadFileInChunksOptions + * @property {number} [concurrencyLimit] The number of concurrently executing promises + * to use when downloading the file. + * @property {number} [chunkSizeBytes] The size in bytes of each chunk to be downloaded. + * @property {string | boolean} [validation] Whether or not to perform a CRC32C validation check when download is complete. + * @property {boolean} [noReturnData] Whether or not to return the downloaded data. A `true` value here would be useful for files with a size that will not fit into memory. + * + */ + /** + * Download a large file in chunks utilizing parallel download operations. This is a convenience method + * that utilizes {@link File#download} to perform the download. + * + * @param {File | string} fileOrName {@link File} to download. + * @param {DownloadFileInChunksOptions} [options] Configuration options. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const transferManager = new TransferManager(bucket); + * + * //- + * // Download a large file in chunks utilizing parallel operations. + * //- + * const response = await transferManager.downloadFileInChunks(bucket.file('large-file.txt'); + * // Your local directory now contains: + * // - "large-file.txt" (with the contents from my-bucket.large-file.txt) + * ``` + * + */ + downloadFileInChunks(fileOrName: File | string, options?: DownloadFileInChunksOptions): Promise; + /** + * @typedef {object} UploadFileInChunksOptions + * @property {number} [concurrencyLimit] The number of concurrently executing promises + * to use when uploading the file. + * @property {number} [chunkSizeBytes] The size in bytes of each chunk to be uploaded. + * @property {string} [uploadName] Name of the file when saving to GCS. If omitted the name is taken from the file path. + * @property {number} [maxQueueSize] The number of chunks to be uploaded to hold in memory concurrently. If not specified + * defaults to the specified concurrency limit. + * @property {string} [uploadId] If specified attempts to resume a previous upload. + * @property {Map} [partsMap] If specified alongside uploadId, attempts to resume a previous upload from the last chunk + * specified in partsMap + * @property {object} [headers] headers to be sent when initiating the multipart upload. + * See {@link https://cloud.google.com/storage/docs/xml-api/post-object-multipart#request_headers| Request Headers: Initiate a Multipart Upload} + * @property {boolean} [autoAbortFailure] boolean to indicate if an in progress upload session will be automatically aborted upon failure. If not set, + * failures will be automatically aborted. + * + */ + /** + * Upload a large file in chunks utilizing parallel upload operations. If the upload fails, an uploadId and + * map containing all the successfully uploaded parts will be returned to the caller. These arguments can be used to + * resume the upload. + * + * @param {string} [filePath] The path of the file to be uploaded + * @param {UploadFileInChunksOptions} [options] Configuration options. + * @param {MultiPartHelperGenerator} [generator] A function that will return a type that implements the MPU interface. Most users will not need to use this. + * @returns {Promise} If successful a promise resolving to void, otherwise a error containing the message, uploadId, and parts map. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const transferManager = new TransferManager(bucket); + * + * //- + * // Upload a large file in chunks utilizing parallel operations. + * //- + * const response = await transferManager.uploadFileInChunks('large-file.txt'); + * // Your bucket now contains: + * // - "large-file.txt" + * ``` + * + * + */ + uploadFileInChunks(filePath: string, options?: UploadFileInChunksOptions, generator?: MultiPartHelperGenerator): Promise; + private getPathsFromDirectory; +} diff --git a/node_modules/@google-cloud/storage/build/esm/src/transfer-manager.js b/node_modules/@google-cloud/storage/build/esm/src/transfer-manager.js new file mode 100644 index 0000000..b373f34 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/transfer-manager.js @@ -0,0 +1,653 @@ +/*! + * Copyright 2022 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. + */ +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _XMLMultiPartUploadHelper_instances, _XMLMultiPartUploadHelper_setGoogApiClientHeaders, _XMLMultiPartUploadHelper_handleErrorResponse; +import { FileExceptionMessages, RequestError, } from './file.js'; +import pLimit from 'p-limit'; +import * as path from 'path'; +import { createReadStream, existsSync, promises as fsp } from 'fs'; +import { CRC32C } from './crc32c.js'; +import { GoogleAuth } from 'google-auth-library'; +import { XMLParser, XMLBuilder } from 'fast-xml-parser'; +import AsyncRetry from 'async-retry'; +import { createHash } from 'crypto'; +import { GCCL_GCS_CMD_KEY } from './nodejs-common/util.js'; +import { getRuntimeTrackingString, getUserAgentString } from './util.js'; +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore +import { getPackageJSON } from './package-json-helper.cjs'; +const packageJson = getPackageJSON(); +/** + * Default number of concurrently executing promises to use when calling uploadManyFiles. + * + */ +const DEFAULT_PARALLEL_UPLOAD_LIMIT = 5; +/** + * Default number of concurrently executing promises to use when calling downloadManyFiles. + * + */ +const DEFAULT_PARALLEL_DOWNLOAD_LIMIT = 5; +/** + * Default number of concurrently executing promises to use when calling downloadFileInChunks. + * + */ +const DEFAULT_PARALLEL_CHUNKED_DOWNLOAD_LIMIT = 5; +/** + * The minimum size threshold in bytes at which to apply a chunked download strategy when calling downloadFileInChunks. + * + */ +const DOWNLOAD_IN_CHUNKS_FILE_SIZE_THRESHOLD = 32 * 1024 * 1024; +/** + * The chunk size in bytes to use when calling downloadFileInChunks. + * + */ +const DOWNLOAD_IN_CHUNKS_DEFAULT_CHUNK_SIZE = 32 * 1024 * 1024; +/** + * The chunk size in bytes to use when calling uploadFileInChunks. + * + */ +const UPLOAD_IN_CHUNKS_DEFAULT_CHUNK_SIZE = 32 * 1024 * 1024; +/** + * Default number of concurrently executing promises to use when calling uploadFileInChunks. + * + */ +const DEFAULT_PARALLEL_CHUNKED_UPLOAD_LIMIT = 5; +const EMPTY_REGEX = '(?:)'; +/** + * The `gccl-gcs-cmd` value for the `X-Goog-API-Client` header. + * Example: `gccl-gcs-cmd/tm.upload_many` + * + * @see {@link GCCL_GCS_CMD}. + * @see {@link GCCL_GCS_CMD_KEY}. + */ +const GCCL_GCS_CMD_FEATURE = { + UPLOAD_MANY: 'tm.upload_many', + DOWNLOAD_MANY: 'tm.download_many', + UPLOAD_SHARDED: 'tm.upload_sharded', + DOWNLOAD_SHARDED: 'tm.download_sharded', +}; +const defaultMultiPartGenerator = (bucket, fileName, uploadId, partsMap) => { + return new XMLMultiPartUploadHelper(bucket, fileName, uploadId, partsMap); +}; +export class MultiPartUploadError extends Error { + constructor(message, uploadId, partsMap) { + super(message); + this.uploadId = uploadId; + this.partsMap = partsMap; + } +} +/** + * Class representing an implementation of MPU in the XML API. This class is not meant for public usage. + * + * @private + * + */ +class XMLMultiPartUploadHelper { + constructor(bucket, fileName, uploadId, partsMap) { + _XMLMultiPartUploadHelper_instances.add(this); + this.authClient = bucket.storage.authClient || new GoogleAuth(); + this.uploadId = uploadId || ''; + this.bucket = bucket; + this.fileName = fileName; + this.baseUrl = `https://${bucket.name}.${new URL(this.bucket.storage.apiEndpoint).hostname}/${fileName}`; + this.xmlBuilder = new XMLBuilder({ arrayNodeName: 'Part' }); + this.xmlParser = new XMLParser(); + this.partsMap = partsMap || new Map(); + this.retryOptions = { + retries: this.bucket.storage.retryOptions.maxRetries, + factor: this.bucket.storage.retryOptions.retryDelayMultiplier, + maxTimeout: this.bucket.storage.retryOptions.maxRetryDelay * 1000, + maxRetryTime: this.bucket.storage.retryOptions.totalTimeout * 1000, + }; + } + /** + * Initiates a multipart upload (MPU) to the XML API and stores the resultant upload id. + * + * @returns {Promise} + */ + async initiateUpload(headers = {}) { + const url = `${this.baseUrl}?uploads`; + return AsyncRetry(async (bail) => { + try { + const res = await this.authClient.request({ + headers: __classPrivateFieldGet(this, _XMLMultiPartUploadHelper_instances, "m", _XMLMultiPartUploadHelper_setGoogApiClientHeaders).call(this, headers), + method: 'POST', + url, + }); + if (res.data && res.data.error) { + throw res.data.error; + } + const parsedXML = this.xmlParser.parse(res.data); + this.uploadId = parsedXML.InitiateMultipartUploadResult.UploadId; + } + catch (e) { + __classPrivateFieldGet(this, _XMLMultiPartUploadHelper_instances, "m", _XMLMultiPartUploadHelper_handleErrorResponse).call(this, e, bail); + } + }, this.retryOptions); + } + /** + * Uploads the provided chunk of data to the XML API using the previously created upload id. + * + * @param {number} partNumber the sequence number of this chunk. + * @param {Buffer} chunk the chunk of data to be uploaded. + * @param {string | false} validation whether or not to include the md5 hash in the headers to cause the server + * to validate the chunk was not corrupted. + * @returns {Promise} + */ + async uploadPart(partNumber, chunk, validation) { + const url = `${this.baseUrl}?partNumber=${partNumber}&uploadId=${this.uploadId}`; + let headers = __classPrivateFieldGet(this, _XMLMultiPartUploadHelper_instances, "m", _XMLMultiPartUploadHelper_setGoogApiClientHeaders).call(this); + if (validation === 'md5') { + const hash = createHash('md5').update(chunk).digest('base64'); + headers = { + 'Content-MD5': hash, + }; + } + return AsyncRetry(async (bail) => { + try { + const res = await this.authClient.request({ + url, + method: 'PUT', + body: chunk, + headers, + }); + if (res.data && res.data.error) { + throw res.data.error; + } + this.partsMap.set(partNumber, res.headers['etag']); + } + catch (e) { + __classPrivateFieldGet(this, _XMLMultiPartUploadHelper_instances, "m", _XMLMultiPartUploadHelper_handleErrorResponse).call(this, e, bail); + } + }, this.retryOptions); + } + /** + * Sends the final request of the MPU to tell GCS the upload is now complete. + * + * @returns {Promise} + */ + async completeUpload() { + const url = `${this.baseUrl}?uploadId=${this.uploadId}`; + const sortedMap = new Map([...this.partsMap.entries()].sort((a, b) => a[0] - b[0])); + const parts = []; + for (const entry of sortedMap.entries()) { + parts.push({ PartNumber: entry[0], ETag: entry[1] }); + } + const body = `${this.xmlBuilder.build(parts)}`; + return AsyncRetry(async (bail) => { + try { + const res = await this.authClient.request({ + headers: __classPrivateFieldGet(this, _XMLMultiPartUploadHelper_instances, "m", _XMLMultiPartUploadHelper_setGoogApiClientHeaders).call(this), + url, + method: 'POST', + body, + }); + if (res.data && res.data.error) { + throw res.data.error; + } + return res; + } + catch (e) { + __classPrivateFieldGet(this, _XMLMultiPartUploadHelper_instances, "m", _XMLMultiPartUploadHelper_handleErrorResponse).call(this, e, bail); + return; + } + }, this.retryOptions); + } + /** + * Aborts an multipart upload that is in progress. Once aborted, any parts in the process of being uploaded fail, + * and future requests using the upload ID fail. + * + * @returns {Promise} + */ + async abortUpload() { + const url = `${this.baseUrl}?uploadId=${this.uploadId}`; + return AsyncRetry(async (bail) => { + try { + const res = await this.authClient.request({ + url, + method: 'DELETE', + }); + if (res.data && res.data.error) { + throw res.data.error; + } + } + catch (e) { + __classPrivateFieldGet(this, _XMLMultiPartUploadHelper_instances, "m", _XMLMultiPartUploadHelper_handleErrorResponse).call(this, e, bail); + return; + } + }, this.retryOptions); + } +} +_XMLMultiPartUploadHelper_instances = new WeakSet(), _XMLMultiPartUploadHelper_setGoogApiClientHeaders = function _XMLMultiPartUploadHelper_setGoogApiClientHeaders(headers = {}) { + let headerFound = false; + let userAgentFound = false; + for (const [key, value] of Object.entries(headers)) { + if (key.toLocaleLowerCase().trim() === 'x-goog-api-client') { + headerFound = true; + // Prepend command feature to value, if not already there + if (!value.includes(GCCL_GCS_CMD_FEATURE.UPLOAD_SHARDED)) { + headers[key] = + `${value} gccl-gcs-cmd/${GCCL_GCS_CMD_FEATURE.UPLOAD_SHARDED}`; + } + } + else if (key.toLocaleLowerCase().trim() === 'user-agent') { + userAgentFound = true; + } + } + // If the header isn't present, add it + if (!headerFound) { + headers['x-goog-api-client'] = `${getRuntimeTrackingString()} gccl/${packageJson.version} gccl-gcs-cmd/${GCCL_GCS_CMD_FEATURE.UPLOAD_SHARDED}`; + } + // If the User-Agent isn't present, add it + if (!userAgentFound) { + headers['User-Agent'] = getUserAgentString(); + } + return headers; +}, _XMLMultiPartUploadHelper_handleErrorResponse = function _XMLMultiPartUploadHelper_handleErrorResponse(err, bail) { + if (this.bucket.storage.retryOptions.autoRetry && + this.bucket.storage.retryOptions.retryableErrorFn(err)) { + throw err; + } + else { + bail(err); + } +}; +/** + * Create a TransferManager object to perform parallel transfer operations on a Cloud Storage bucket. + * + * @class + * @hideconstructor + * + * @param {Bucket} bucket A {@link Bucket} instance + * + */ +export class TransferManager { + constructor(bucket) { + this.bucket = bucket; + } + /** + * @typedef {object} UploadManyFilesOptions + * @property {number} [concurrencyLimit] The number of concurrently executing promises + * to use when uploading the files. + * @property {Function} [customDestinationBuilder] A function that will take the current path of a local file + * and return a string representing a custom path to be used to upload the file to GCS. + * @property {boolean} [skipIfExists] Do not upload the file if it already exists in + * the bucket. This will set the precondition ifGenerationMatch = 0. + * @property {string} [prefix] A prefix to append to all of the uploaded files. + * @property {object} [passthroughOptions] {@link UploadOptions} Options to be passed through + * to each individual upload operation. + * + */ + /** + * Upload multiple files in parallel to the bucket. This is a convenience method + * that utilizes {@link Bucket#upload} to perform the upload. + * + * @param {array | string} [filePathsOrDirectory] An array of fully qualified paths to the files or a directory name. + * If a directory name is provided, the directory will be recursively walked and all files will be added to the upload list. + * to be uploaded to the bucket + * @param {UploadManyFilesOptions} [options] Configuration options. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const transferManager = new TransferManager(bucket); + * + * //- + * // Upload multiple files in parallel. + * //- + * const response = await transferManager.uploadManyFiles(['/local/path/file1.txt, 'local/path/file2.txt']); + * // Your bucket now contains: + * // - "local/path/file1.txt" (with the contents of '/local/path/file1.txt') + * // - "local/path/file2.txt" (with the contents of '/local/path/file2.txt') + * const response = await transferManager.uploadManyFiles('/local/directory'); + * // Your bucket will now contain all files contained in '/local/directory' maintaining the subdirectory structure. + * ``` + * + */ + async uploadManyFiles(filePathsOrDirectory, options = {}) { + var _a; + if (options.skipIfExists && ((_a = options.passthroughOptions) === null || _a === void 0 ? void 0 : _a.preconditionOpts)) { + options.passthroughOptions.preconditionOpts.ifGenerationMatch = 0; + } + else if (options.skipIfExists && + options.passthroughOptions === undefined) { + options.passthroughOptions = { + preconditionOpts: { + ifGenerationMatch: 0, + }, + }; + } + const limit = pLimit(options.concurrencyLimit || DEFAULT_PARALLEL_UPLOAD_LIMIT); + const promises = []; + let allPaths = []; + if (!Array.isArray(filePathsOrDirectory)) { + for await (const curPath of this.getPathsFromDirectory(filePathsOrDirectory)) { + allPaths.push(curPath); + } + } + else { + allPaths = filePathsOrDirectory; + } + for (const filePath of allPaths) { + const stat = await fsp.lstat(filePath); + if (stat.isDirectory()) { + continue; + } + const passThroughOptionsCopy = { + ...options.passthroughOptions, + [GCCL_GCS_CMD_KEY]: GCCL_GCS_CMD_FEATURE.UPLOAD_MANY, + }; + passThroughOptionsCopy.destination = options.customDestinationBuilder + ? options.customDestinationBuilder(filePath, options) + : filePath.split(path.sep).join(path.posix.sep); + if (options.prefix) { + passThroughOptionsCopy.destination = path.posix.join(...options.prefix.split(path.sep), passThroughOptionsCopy.destination); + } + promises.push(limit(() => this.bucket.upload(filePath, passThroughOptionsCopy))); + } + return Promise.all(promises); + } + /** + * @typedef {object} DownloadManyFilesOptions + * @property {number} [concurrencyLimit] The number of concurrently executing promises + * to use when downloading the files. + * @property {string} [prefix] A prefix to append to all of the downloaded files. + * @property {string} [stripPrefix] A prefix to remove from all of the downloaded files. + * @property {object} [passthroughOptions] {@link DownloadOptions} Options to be passed through + * to each individual download operation. + * @property {boolean} [skipIfExists] Do not download the file if it already exists in + * the destination. + * + */ + /** + * Download multiple files in parallel to the local filesystem. This is a convenience method + * that utilizes {@link File#download} to perform the download. + * + * @param {array | string} [filesOrFolder] An array of file name strings or file objects to be downloaded. If + * a string is provided this will be treated as a GCS prefix and all files with that prefix will be downloaded. + * @param {DownloadManyFilesOptions} [options] Configuration options. Setting options.prefix or options.stripPrefix + * or options.passthroughOptions.destination will cause the downloaded files to be written to the file system + * instead of being returned as a buffer. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const transferManager = new TransferManager(bucket); + * + * //- + * // Download multiple files in parallel. + * //- + * const response = await transferManager.downloadManyFiles(['file1.txt', 'file2.txt']); + * // The following files have been downloaded: + * // - "file1.txt" (with the contents from my-bucket.file1.txt) + * // - "file2.txt" (with the contents from my-bucket.file2.txt) + * const response = await transferManager.downloadManyFiles([bucket.File('file1.txt'), bucket.File('file2.txt')]); + * // The following files have been downloaded: + * // - "file1.txt" (with the contents from my-bucket.file1.txt) + * // - "file2.txt" (with the contents from my-bucket.file2.txt) + * const response = await transferManager.downloadManyFiles('test-folder'); + * // All files with GCS prefix of 'test-folder' have been downloaded. + * ``` + * + */ + async downloadManyFiles(filesOrFolder, options = {}) { + const limit = pLimit(options.concurrencyLimit || DEFAULT_PARALLEL_DOWNLOAD_LIMIT); + const promises = []; + let files = []; + if (!Array.isArray(filesOrFolder)) { + const directoryFiles = await this.bucket.getFiles({ + prefix: filesOrFolder, + }); + files = directoryFiles[0]; + } + else { + files = filesOrFolder.map(curFile => { + if (typeof curFile === 'string') { + return this.bucket.file(curFile); + } + return curFile; + }); + } + const stripRegexString = options.stripPrefix + ? `^${options.stripPrefix}` + : EMPTY_REGEX; + const regex = new RegExp(stripRegexString, 'g'); + for (const file of files) { + const passThroughOptionsCopy = { + ...options.passthroughOptions, + [GCCL_GCS_CMD_KEY]: GCCL_GCS_CMD_FEATURE.DOWNLOAD_MANY, + }; + if (options.prefix || passThroughOptionsCopy.destination) { + passThroughOptionsCopy.destination = path.join(options.prefix || '', passThroughOptionsCopy.destination || '', file.name); + } + if (options.stripPrefix) { + passThroughOptionsCopy.destination = file.name.replace(regex, ''); + } + if (options.skipIfExists && + existsSync(passThroughOptionsCopy.destination || '')) { + continue; + } + promises.push(limit(async () => { + const destination = passThroughOptionsCopy.destination; + if (destination && destination.endsWith(path.sep)) { + await fsp.mkdir(destination, { recursive: true }); + return Promise.resolve([ + Buffer.alloc(0), + ]); + } + return file.download(passThroughOptionsCopy); + })); + } + return Promise.all(promises); + } + /** + * @typedef {object} DownloadFileInChunksOptions + * @property {number} [concurrencyLimit] The number of concurrently executing promises + * to use when downloading the file. + * @property {number} [chunkSizeBytes] The size in bytes of each chunk to be downloaded. + * @property {string | boolean} [validation] Whether or not to perform a CRC32C validation check when download is complete. + * @property {boolean} [noReturnData] Whether or not to return the downloaded data. A `true` value here would be useful for files with a size that will not fit into memory. + * + */ + /** + * Download a large file in chunks utilizing parallel download operations. This is a convenience method + * that utilizes {@link File#download} to perform the download. + * + * @param {File | string} fileOrName {@link File} to download. + * @param {DownloadFileInChunksOptions} [options] Configuration options. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const transferManager = new TransferManager(bucket); + * + * //- + * // Download a large file in chunks utilizing parallel operations. + * //- + * const response = await transferManager.downloadFileInChunks(bucket.file('large-file.txt'); + * // Your local directory now contains: + * // - "large-file.txt" (with the contents from my-bucket.large-file.txt) + * ``` + * + */ + async downloadFileInChunks(fileOrName, options = {}) { + let chunkSize = options.chunkSizeBytes || DOWNLOAD_IN_CHUNKS_DEFAULT_CHUNK_SIZE; + let limit = pLimit(options.concurrencyLimit || DEFAULT_PARALLEL_CHUNKED_DOWNLOAD_LIMIT); + const noReturnData = Boolean(options.noReturnData); + const promises = []; + const file = typeof fileOrName === 'string' + ? this.bucket.file(fileOrName) + : fileOrName; + const fileInfo = await file.get(); + const size = parseInt(fileInfo[0].metadata.size.toString()); + // If the file size does not meet the threshold download it as a single chunk. + if (size < DOWNLOAD_IN_CHUNKS_FILE_SIZE_THRESHOLD) { + limit = pLimit(1); + chunkSize = size; + } + let start = 0; + const filePath = options.destination || path.basename(file.name); + const fileToWrite = await fsp.open(filePath, 'w'); + while (start < size) { + const chunkStart = start; + let chunkEnd = start + chunkSize - 1; + chunkEnd = chunkEnd > size ? size : chunkEnd; + promises.push(limit(async () => { + const resp = await file.download({ + start: chunkStart, + end: chunkEnd, + [GCCL_GCS_CMD_KEY]: GCCL_GCS_CMD_FEATURE.DOWNLOAD_SHARDED, + }); + const result = await fileToWrite.write(resp[0], 0, resp[0].length, chunkStart); + if (noReturnData) + return; + return result.buffer; + })); + start += chunkSize; + } + let chunks; + try { + chunks = await Promise.all(promises); + } + finally { + await fileToWrite.close(); + } + if (options.validation === 'crc32c' && fileInfo[0].metadata.crc32c) { + const downloadedCrc32C = await CRC32C.fromFile(filePath); + if (!downloadedCrc32C.validate(fileInfo[0].metadata.crc32c)) { + const mismatchError = new RequestError(FileExceptionMessages.DOWNLOAD_MISMATCH); + mismatchError.code = 'CONTENT_DOWNLOAD_MISMATCH'; + throw mismatchError; + } + } + if (noReturnData) + return; + return [Buffer.concat(chunks, size)]; + } + /** + * @typedef {object} UploadFileInChunksOptions + * @property {number} [concurrencyLimit] The number of concurrently executing promises + * to use when uploading the file. + * @property {number} [chunkSizeBytes] The size in bytes of each chunk to be uploaded. + * @property {string} [uploadName] Name of the file when saving to GCS. If omitted the name is taken from the file path. + * @property {number} [maxQueueSize] The number of chunks to be uploaded to hold in memory concurrently. If not specified + * defaults to the specified concurrency limit. + * @property {string} [uploadId] If specified attempts to resume a previous upload. + * @property {Map} [partsMap] If specified alongside uploadId, attempts to resume a previous upload from the last chunk + * specified in partsMap + * @property {object} [headers] headers to be sent when initiating the multipart upload. + * See {@link https://cloud.google.com/storage/docs/xml-api/post-object-multipart#request_headers| Request Headers: Initiate a Multipart Upload} + * @property {boolean} [autoAbortFailure] boolean to indicate if an in progress upload session will be automatically aborted upon failure. If not set, + * failures will be automatically aborted. + * + */ + /** + * Upload a large file in chunks utilizing parallel upload operations. If the upload fails, an uploadId and + * map containing all the successfully uploaded parts will be returned to the caller. These arguments can be used to + * resume the upload. + * + * @param {string} [filePath] The path of the file to be uploaded + * @param {UploadFileInChunksOptions} [options] Configuration options. + * @param {MultiPartHelperGenerator} [generator] A function that will return a type that implements the MPU interface. Most users will not need to use this. + * @returns {Promise} If successful a promise resolving to void, otherwise a error containing the message, uploadId, and parts map. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const transferManager = new TransferManager(bucket); + * + * //- + * // Upload a large file in chunks utilizing parallel operations. + * //- + * const response = await transferManager.uploadFileInChunks('large-file.txt'); + * // Your bucket now contains: + * // - "large-file.txt" + * ``` + * + * + */ + async uploadFileInChunks(filePath, options = {}, generator = defaultMultiPartGenerator) { + const chunkSize = options.chunkSizeBytes || UPLOAD_IN_CHUNKS_DEFAULT_CHUNK_SIZE; + const limit = pLimit(options.concurrencyLimit || DEFAULT_PARALLEL_CHUNKED_UPLOAD_LIMIT); + const maxQueueSize = options.maxQueueSize || + options.concurrencyLimit || + DEFAULT_PARALLEL_CHUNKED_UPLOAD_LIMIT; + const fileName = options.uploadName || path.basename(filePath); + const mpuHelper = generator(this.bucket, fileName, options.uploadId, options.partsMap); + let partNumber = 1; + let promises = []; + try { + if (options.uploadId === undefined) { + await mpuHelper.initiateUpload(options.headers); + } + const startOrResumptionByte = mpuHelper.partsMap.size * chunkSize; + const readStream = createReadStream(filePath, { + highWaterMark: chunkSize, + start: startOrResumptionByte, + }); + // p-limit only limits the number of running promises. We do not want to hold an entire + // large file in memory at once so promises acts a queue that will hold only maxQueueSize in memory. + for await (const curChunk of readStream) { + if (promises.length >= maxQueueSize) { + await Promise.all(promises); + promises = []; + } + promises.push(limit(() => mpuHelper.uploadPart(partNumber++, curChunk, options.validation))); + } + await Promise.all(promises); + return await mpuHelper.completeUpload(); + } + catch (e) { + if ((options.autoAbortFailure === undefined || options.autoAbortFailure) && + mpuHelper.uploadId) { + try { + await mpuHelper.abortUpload(); + return; + } + catch (e) { + throw new MultiPartUploadError(e.message, mpuHelper.uploadId, mpuHelper.partsMap); + } + } + throw new MultiPartUploadError(e.message, mpuHelper.uploadId, mpuHelper.partsMap); + } + } + async *getPathsFromDirectory(directory) { + const filesAndSubdirectories = await fsp.readdir(directory, { + withFileTypes: true, + }); + for (const curFileOrDirectory of filesAndSubdirectories) { + const fullPath = path.join(directory, curFileOrDirectory.name); + curFileOrDirectory.isDirectory() + ? yield* this.getPathsFromDirectory(fullPath) + : yield fullPath; + } + } +} diff --git a/node_modules/@google-cloud/storage/build/esm/src/util.d.ts b/node_modules/@google-cloud/storage/build/esm/src/util.d.ts new file mode 100644 index 0000000..d2cf333 --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/util.d.ts @@ -0,0 +1,85 @@ +import * as querystring from 'querystring'; +import { PassThrough } from 'stream'; +export declare function normalize(optionsOrCallback?: T | U, cb?: U): { + options: T; + callback: U; +}; +/** + * Flatten an object into an Array of arrays, [[key, value], ..]. + * Implements Object.entries() for Node.js <8 + * @internal + */ +export declare function objectEntries(obj: { + [key: string]: T; +}): Array<[string, T]>; +/** + * Encode `str` with encodeURIComponent, plus these + * reserved characters: `! * ' ( )`. + * + * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent| MDN: fixedEncodeURIComponent} + * + * @param {string} str The URI component to encode. + * @return {string} The encoded string. + */ +export declare function fixedEncodeURIComponent(str: string): string; +/** + * URI encode `uri` for generating signed URLs, using fixedEncodeURIComponent. + * + * Encode every byte except `A-Z a-Z 0-9 ~ - . _`. + * + * @param {string} uri The URI to encode. + * @param [boolean=false] encodeSlash If `true`, the "/" character is not encoded. + * @return {string} The encoded string. + */ +export declare function encodeURI(uri: string, encodeSlash: boolean): string; +/** + * Serialize an object to a URL query string using util.encodeURI(uri, true). + * @param {string} url The object to serialize. + * @return {string} Serialized string. + */ +export declare function qsStringify(qs: querystring.ParsedUrlQueryInput): string; +export declare function objectKeyToLowercase(object: { + [key: string]: T; +}): { + [key: string]: T; +}; +/** + * JSON encode str, with unicode \u+ representation. + * @param {object} obj The object to encode. + * @return {string} Serialized string. + */ +export declare function unicodeJSONStringify(obj: object): string; +/** + * Converts the given objects keys to snake_case + * @param {object} obj object to convert keys to snake case. + * @returns {object} object with keys converted to snake case. + */ +export declare function convertObjKeysToSnakeCase(obj: object): object; +/** + * Formats the provided date object as a UTC ISO string. + * @param {Date} dateTimeToFormat date object to be formatted. + * @param {boolean} includeTime flag to include hours, minutes, seconds in output. + * @param {string} dateDelimiter delimiter between date components. + * @param {string} timeDelimiter delimiter between time components. + * @returns {string} UTC ISO format of provided date object. + */ +export declare function formatAsUTCISO(dateTimeToFormat: Date, includeTime?: boolean, dateDelimiter?: string, timeDelimiter?: string): string; +/** + * Examines the runtime environment and returns the appropriate tracking string. + * @returns {string} metrics tracking string based on the current runtime environment. + */ +export declare function getRuntimeTrackingString(): string; +/** + * Looks at package.json and creates the user-agent string to be applied to request headers. + * @returns {string} user agent string. + */ +export declare function getUserAgentString(): string; +export declare function getDirName(): string; +export declare function getModuleFormat(): "ESM" | "CJS"; +export declare class PassThroughShim extends PassThrough { + private shouldEmitReading; + private shouldEmitWriting; + _read(size: number): void; + _write(chunk: never, encoding: BufferEncoding, callback: (error?: Error | null | undefined) => void): void; + _final(callback: (error?: Error | null | undefined) => void): void; +} diff --git a/node_modules/@google-cloud/storage/build/esm/src/util.js b/node_modules/@google-cloud/storage/build/esm/src/util.js new file mode 100644 index 0000000..c751a8a --- /dev/null +++ b/node_modules/@google-cloud/storage/build/esm/src/util.js @@ -0,0 +1,229 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +import * as path from 'path'; +import * as querystring from 'querystring'; +import { PassThrough } from 'stream'; +import * as url from 'url'; +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore +import { getPackageJSON } from './package-json-helper.cjs'; +// Done to avoid a problem with mangling of identifiers when using esModuleInterop +const fileURLToPath = url.fileURLToPath; +const isEsm = true; +export function normalize(optionsOrCallback, cb) { + const options = (typeof optionsOrCallback === 'object' ? optionsOrCallback : {}); + const callback = (typeof optionsOrCallback === 'function' ? optionsOrCallback : cb); + return { options, callback }; +} +/** + * Flatten an object into an Array of arrays, [[key, value], ..]. + * Implements Object.entries() for Node.js <8 + * @internal + */ +export function objectEntries(obj) { + return Object.keys(obj).map(key => [key, obj[key]]); +} +/** + * Encode `str` with encodeURIComponent, plus these + * reserved characters: `! * ' ( )`. + * + * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent| MDN: fixedEncodeURIComponent} + * + * @param {string} str The URI component to encode. + * @return {string} The encoded string. + */ +export function fixedEncodeURIComponent(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase()); +} +/** + * URI encode `uri` for generating signed URLs, using fixedEncodeURIComponent. + * + * Encode every byte except `A-Z a-Z 0-9 ~ - . _`. + * + * @param {string} uri The URI to encode. + * @param [boolean=false] encodeSlash If `true`, the "/" character is not encoded. + * @return {string} The encoded string. + */ +export function encodeURI(uri, encodeSlash) { + // Split the string by `/`, and conditionally rejoin them with either + // %2F if encodeSlash is `true`, or '/' if `false`. + return uri + .split('/') + .map(fixedEncodeURIComponent) + .join(encodeSlash ? '%2F' : '/'); +} +/** + * Serialize an object to a URL query string using util.encodeURI(uri, true). + * @param {string} url The object to serialize. + * @return {string} Serialized string. + */ +export function qsStringify(qs) { + return querystring.stringify(qs, '&', '=', { + encodeURIComponent: (component) => encodeURI(component, true), + }); +} +export function objectKeyToLowercase(object) { + const newObj = {}; + for (let key of Object.keys(object)) { + const value = object[key]; + key = key.toLowerCase(); + newObj[key] = value; + } + return newObj; +} +/** + * JSON encode str, with unicode \u+ representation. + * @param {object} obj The object to encode. + * @return {string} Serialized string. + */ +export function unicodeJSONStringify(obj) { + return JSON.stringify(obj).replace(/[\u0080-\uFFFF]/g, (char) => '\\u' + ('0000' + char.charCodeAt(0).toString(16)).slice(-4)); +} +/** + * Converts the given objects keys to snake_case + * @param {object} obj object to convert keys to snake case. + * @returns {object} object with keys converted to snake case. + */ +export function convertObjKeysToSnakeCase(obj) { + if (obj instanceof Date || obj instanceof RegExp) { + return obj; + } + if (Array.isArray(obj)) { + return obj.map(convertObjKeysToSnakeCase); + } + if (obj instanceof Object) { + return Object.keys(obj).reduce((acc, cur) => { + const s = cur[0].toLocaleLowerCase() + + cur.slice(1).replace(/([A-Z]+)/g, (match, p1) => { + return `_${p1.toLowerCase()}`; + }); + acc[s] = convertObjKeysToSnakeCase(obj[cur]); + return acc; + }, Object()); + } + return obj; +} +/** + * Formats the provided date object as a UTC ISO string. + * @param {Date} dateTimeToFormat date object to be formatted. + * @param {boolean} includeTime flag to include hours, minutes, seconds in output. + * @param {string} dateDelimiter delimiter between date components. + * @param {string} timeDelimiter delimiter between time components. + * @returns {string} UTC ISO format of provided date object. + */ +export function formatAsUTCISO(dateTimeToFormat, includeTime = false, dateDelimiter = '', timeDelimiter = '') { + const year = dateTimeToFormat.getUTCFullYear(); + const month = dateTimeToFormat.getUTCMonth() + 1; + const day = dateTimeToFormat.getUTCDate(); + const hour = dateTimeToFormat.getUTCHours(); + const minute = dateTimeToFormat.getUTCMinutes(); + const second = dateTimeToFormat.getUTCSeconds(); + let resultString = `${year.toString().padStart(4, '0')}${dateDelimiter}${month + .toString() + .padStart(2, '0')}${dateDelimiter}${day.toString().padStart(2, '0')}`; + if (includeTime) { + resultString = `${resultString}T${hour + .toString() + .padStart(2, '0')}${timeDelimiter}${minute + .toString() + .padStart(2, '0')}${timeDelimiter}${second.toString().padStart(2, '0')}Z`; + } + return resultString; +} +/** + * Examines the runtime environment and returns the appropriate tracking string. + * @returns {string} metrics tracking string based on the current runtime environment. + */ +export function getRuntimeTrackingString() { + if ( + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + globalThis.Deno && + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + globalThis.Deno.version && + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + globalThis.Deno.version.deno) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + return `gl-deno/${globalThis.Deno.version.deno}`; + } + else { + return `gl-node/${process.versions.node}`; + } +} +/** + * Looks at package.json and creates the user-agent string to be applied to request headers. + * @returns {string} user agent string. + */ +export function getUserAgentString() { + const pkg = getPackageJSON(); + const hyphenatedPackageName = pkg.name + .replace('@google-cloud', 'gcloud-node') // For legacy purposes. + .replace('/', '-'); // For UA spec-compliance purposes. + return hyphenatedPackageName + '/' + pkg.version; +} +export function getDirName() { + let dirToUse = ''; + try { + dirToUse = __dirname; + } + catch (e) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + dirToUse = path.dirname(fileURLToPath(import.meta.url)); + } + return dirToUse; +} +export function getModuleFormat() { + return isEsm ? 'ESM' : 'CJS'; +} +export class PassThroughShim extends PassThrough { + constructor() { + super(...arguments); + this.shouldEmitReading = true; + this.shouldEmitWriting = true; + } + _read(size) { + if (this.shouldEmitReading) { + this.emit('reading'); + this.shouldEmitReading = false; + } + super._read(size); + } + _write(chunk, encoding, callback) { + if (this.shouldEmitWriting) { + this.emit('writing'); + this.shouldEmitWriting = false; + } + // Per the nodejs documentation, callback must be invoked on the next tick + process.nextTick(() => { + super._write(chunk, encoding, callback); + }); + } + _final(callback) { + // If the stream is empty (i.e. empty file) final will be invoked before _read / _write + // and we should still emit the proper events. + if (this.shouldEmitReading) { + this.emit('reading'); + this.shouldEmitReading = false; + } + if (this.shouldEmitWriting) { + this.emit('writing'); + this.shouldEmitWriting = false; + } + callback(null); + } +} diff --git a/node_modules/@google-cloud/storage/node_modules/.bin/uuid b/node_modules/@google-cloud/storage/node_modules/.bin/uuid new file mode 100644 index 0000000..0c2d469 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/.bin/uuid @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../uuid/dist/bin/uuid" "$@" +else + exec node "$basedir/../uuid/dist/bin/uuid" "$@" +fi diff --git a/node_modules/@google-cloud/storage/node_modules/.bin/uuid.cmd b/node_modules/@google-cloud/storage/node_modules/.bin/uuid.cmd new file mode 100644 index 0000000..0f2376e --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/.bin/uuid.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\uuid\dist\bin\uuid" %* diff --git a/node_modules/@google-cloud/storage/node_modules/.bin/uuid.ps1 b/node_modules/@google-cloud/storage/node_modules/.bin/uuid.ps1 new file mode 100644 index 0000000..7804628 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/.bin/uuid.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } else { + & "$basedir/node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } else { + & "node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/CHANGELOG.md b/node_modules/@google-cloud/storage/node_modules/uuid/CHANGELOG.md new file mode 100644 index 0000000..7519d19 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/CHANGELOG.md @@ -0,0 +1,229 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +### [8.3.2](https://github.com/uuidjs/uuid/compare/v8.3.1...v8.3.2) (2020-12-08) + +### Bug Fixes + +- lazy load getRandomValues ([#537](https://github.com/uuidjs/uuid/issues/537)) ([16c8f6d](https://github.com/uuidjs/uuid/commit/16c8f6df2f6b09b4d6235602d6a591188320a82e)), closes [#536](https://github.com/uuidjs/uuid/issues/536) + +### [8.3.1](https://github.com/uuidjs/uuid/compare/v8.3.0...v8.3.1) (2020-10-04) + +### Bug Fixes + +- support expo>=39.0.0 ([#515](https://github.com/uuidjs/uuid/issues/515)) ([c65a0f3](https://github.com/uuidjs/uuid/commit/c65a0f3fa73b901959d638d1e3591dfacdbed867)), closes [#375](https://github.com/uuidjs/uuid/issues/375) + +## [8.3.0](https://github.com/uuidjs/uuid/compare/v8.2.0...v8.3.0) (2020-07-27) + +### Features + +- add parse/stringify/validate/version/NIL APIs ([#479](https://github.com/uuidjs/uuid/issues/479)) ([0e6c10b](https://github.com/uuidjs/uuid/commit/0e6c10ba1bf9517796ff23c052fc0468eedfd5f4)), closes [#475](https://github.com/uuidjs/uuid/issues/475) [#478](https://github.com/uuidjs/uuid/issues/478) [#480](https://github.com/uuidjs/uuid/issues/480) [#481](https://github.com/uuidjs/uuid/issues/481) [#180](https://github.com/uuidjs/uuid/issues/180) + +## [8.2.0](https://github.com/uuidjs/uuid/compare/v8.1.0...v8.2.0) (2020-06-23) + +### Features + +- improve performance of v1 string representation ([#453](https://github.com/uuidjs/uuid/issues/453)) ([0ee0b67](https://github.com/uuidjs/uuid/commit/0ee0b67c37846529c66089880414d29f3ae132d5)) +- remove deprecated v4 string parameter ([#454](https://github.com/uuidjs/uuid/issues/454)) ([88ce3ca](https://github.com/uuidjs/uuid/commit/88ce3ca0ba046f60856de62c7ce03f7ba98ba46c)), closes [#437](https://github.com/uuidjs/uuid/issues/437) +- support jspm ([#473](https://github.com/uuidjs/uuid/issues/473)) ([e9f2587](https://github.com/uuidjs/uuid/commit/e9f2587a92575cac31bc1d4ae944e17c09756659)) + +### Bug Fixes + +- prepare package exports for webpack 5 ([#468](https://github.com/uuidjs/uuid/issues/468)) ([8d6e6a5](https://github.com/uuidjs/uuid/commit/8d6e6a5f8965ca9575eb4d92e99a43435f4a58a8)) + +## [8.1.0](https://github.com/uuidjs/uuid/compare/v8.0.0...v8.1.0) (2020-05-20) + +### Features + +- improve v4 performance by reusing random number array ([#435](https://github.com/uuidjs/uuid/issues/435)) ([bf4af0d](https://github.com/uuidjs/uuid/commit/bf4af0d711b4d2ed03d1f74fd12ad0baa87dc79d)) +- optimize V8 performance of bytesToUuid ([#434](https://github.com/uuidjs/uuid/issues/434)) ([e156415](https://github.com/uuidjs/uuid/commit/e156415448ec1af2351fa0b6660cfb22581971f2)) + +### Bug Fixes + +- export package.json required by react-native and bundlers ([#449](https://github.com/uuidjs/uuid/issues/449)) ([be1c8fe](https://github.com/uuidjs/uuid/commit/be1c8fe9a3206c358e0059b52fafd7213aa48a52)), closes [ai/nanoevents#44](https://github.com/ai/nanoevents/issues/44#issuecomment-602010343) [#444](https://github.com/uuidjs/uuid/issues/444) + +## [8.0.0](https://github.com/uuidjs/uuid/compare/v7.0.3...v8.0.0) (2020-04-29) + +### ⚠ BREAKING CHANGES + +- For native ECMAScript Module (ESM) usage in Node.js only named exports are exposed, there is no more default export. + + ```diff + -import uuid from 'uuid'; + -console.log(uuid.v4()); // -> 'cd6c3b08-0adc-4f4b-a6ef-36087a1c9869' + +import { v4 as uuidv4 } from 'uuid'; + +uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' + ``` + +- Deep requiring specific algorithms of this library like `require('uuid/v4')`, which has been deprecated in `uuid@7`, is no longer supported. + + Instead use the named exports that this module exports. + + For ECMAScript Modules (ESM): + + ```diff + -import uuidv4 from 'uuid/v4'; + +import { v4 as uuidv4 } from 'uuid'; + uuidv4(); + ``` + + For CommonJS: + + ```diff + -const uuidv4 = require('uuid/v4'); + +const { v4: uuidv4 } = require('uuid'); + uuidv4(); + ``` + +### Features + +- native Node.js ES Modules (wrapper approach) ([#423](https://github.com/uuidjs/uuid/issues/423)) ([2d9f590](https://github.com/uuidjs/uuid/commit/2d9f590ad9701d692625c07ed62f0a0f91227991)), closes [#245](https://github.com/uuidjs/uuid/issues/245) [#419](https://github.com/uuidjs/uuid/issues/419) [#342](https://github.com/uuidjs/uuid/issues/342) +- remove deep requires ([#426](https://github.com/uuidjs/uuid/issues/426)) ([daf72b8](https://github.com/uuidjs/uuid/commit/daf72b84ceb20272a81bb5fbddb05dd95922cbba)) + +### Bug Fixes + +- add CommonJS syntax example to README quickstart section ([#417](https://github.com/uuidjs/uuid/issues/417)) ([e0ec840](https://github.com/uuidjs/uuid/commit/e0ec8402c7ad44b7ef0453036c612f5db513fda0)) + +### [7.0.3](https://github.com/uuidjs/uuid/compare/v7.0.2...v7.0.3) (2020-03-31) + +### Bug Fixes + +- make deep require deprecation warning work in browsers ([#409](https://github.com/uuidjs/uuid/issues/409)) ([4b71107](https://github.com/uuidjs/uuid/commit/4b71107d8c0d2ef56861ede6403fc9dc35a1e6bf)), closes [#408](https://github.com/uuidjs/uuid/issues/408) + +### [7.0.2](https://github.com/uuidjs/uuid/compare/v7.0.1...v7.0.2) (2020-03-04) + +### Bug Fixes + +- make access to msCrypto consistent ([#393](https://github.com/uuidjs/uuid/issues/393)) ([8bf2a20](https://github.com/uuidjs/uuid/commit/8bf2a20f3565df743da7215eebdbada9d2df118c)) +- simplify link in deprecation warning ([#391](https://github.com/uuidjs/uuid/issues/391)) ([bb2c8e4](https://github.com/uuidjs/uuid/commit/bb2c8e4e9f4c5f9c1eaaf3ea59710c633cd90cb7)) +- update links to match content in readme ([#386](https://github.com/uuidjs/uuid/issues/386)) ([44f2f86](https://github.com/uuidjs/uuid/commit/44f2f86e9d2bbf14ee5f0f00f72a3db1292666d4)) + +### [7.0.1](https://github.com/uuidjs/uuid/compare/v7.0.0...v7.0.1) (2020-02-25) + +### Bug Fixes + +- clean up esm builds for node and browser ([#383](https://github.com/uuidjs/uuid/issues/383)) ([59e6a49](https://github.com/uuidjs/uuid/commit/59e6a49e7ce7b3e8fb0f3ee52b9daae72af467dc)) +- provide browser versions independent from module system ([#380](https://github.com/uuidjs/uuid/issues/380)) ([4344a22](https://github.com/uuidjs/uuid/commit/4344a22e7aed33be8627eeaaf05360f256a21753)), closes [#378](https://github.com/uuidjs/uuid/issues/378) + +## [7.0.0](https://github.com/uuidjs/uuid/compare/v3.4.0...v7.0.0) (2020-02-24) + +### ⚠ BREAKING CHANGES + +- The default export, which used to be the v4() method but which was already discouraged in v3.x of this library, has been removed. +- Explicitly note that deep imports of the different uuid version functions are deprecated and no longer encouraged and that ECMAScript module named imports should be used instead. Emit a deprecation warning for people who deep-require the different algorithm variants. +- Remove builtin support for insecure random number generators in the browser. Users who want that will have to supply their own random number generator function. +- Remove support for generating v3 and v5 UUIDs in Node.js<4.x +- Convert code base to ECMAScript Modules (ESM) and release CommonJS build for node and ESM build for browser bundlers. + +### Features + +- add UMD build to npm package ([#357](https://github.com/uuidjs/uuid/issues/357)) ([4e75adf](https://github.com/uuidjs/uuid/commit/4e75adf435196f28e3fbbe0185d654b5ded7ca2c)), closes [#345](https://github.com/uuidjs/uuid/issues/345) +- add various es module and CommonJS examples ([b238510](https://github.com/uuidjs/uuid/commit/b238510bf352463521f74bab175a3af9b7a42555)) +- ensure that docs are up-to-date in CI ([ee5e77d](https://github.com/uuidjs/uuid/commit/ee5e77db547474f5a8f23d6c857a6d399209986b)) +- hybrid CommonJS & ECMAScript modules build ([a3f078f](https://github.com/uuidjs/uuid/commit/a3f078faa0baff69ab41aed08e041f8f9c8993d0)) +- remove insecure fallback random number generator ([3a5842b](https://github.com/uuidjs/uuid/commit/3a5842b141a6e5de0ae338f391661e6b84b167c9)), closes [#173](https://github.com/uuidjs/uuid/issues/173) +- remove support for pre Node.js v4 Buffer API ([#356](https://github.com/uuidjs/uuid/issues/356)) ([b59b5c5](https://github.com/uuidjs/uuid/commit/b59b5c5ecad271c5453f1a156f011671f6d35627)) +- rename repository to github:uuidjs/uuid ([#351](https://github.com/uuidjs/uuid/issues/351)) ([c37a518](https://github.com/uuidjs/uuid/commit/c37a518e367ac4b6d0aa62dba1bc6ce9e85020f7)), closes [#338](https://github.com/uuidjs/uuid/issues/338) + +### Bug Fixes + +- add deep-require proxies for local testing and adjust tests ([#365](https://github.com/uuidjs/uuid/issues/365)) ([7fedc79](https://github.com/uuidjs/uuid/commit/7fedc79ac8fda4bfd1c566c7f05ef4ac13b2db48)) +- add note about removal of default export ([#372](https://github.com/uuidjs/uuid/issues/372)) ([12749b7](https://github.com/uuidjs/uuid/commit/12749b700eb49db8a9759fd306d8be05dbfbd58c)), closes [#370](https://github.com/uuidjs/uuid/issues/370) +- deprecated deep requiring of the different algorithm versions ([#361](https://github.com/uuidjs/uuid/issues/361)) ([c0bdf15](https://github.com/uuidjs/uuid/commit/c0bdf15e417639b1aeb0b247b2fb11f7a0a26b23)) + +## [3.4.0](https://github.com/uuidjs/uuid/compare/v3.3.3...v3.4.0) (2020-01-16) + +### Features + +- rename repository to github:uuidjs/uuid ([#351](https://github.com/uuidjs/uuid/issues/351)) ([e2d7314](https://github.com/uuidjs/uuid/commit/e2d7314)), closes [#338](https://github.com/uuidjs/uuid/issues/338) + +## [3.3.3](https://github.com/uuidjs/uuid/compare/v3.3.2...v3.3.3) (2019-08-19) + +### Bug Fixes + +- no longer run ci tests on node v4 +- upgrade dependencies + +## [3.3.2](https://github.com/uuidjs/uuid/compare/v3.3.1...v3.3.2) (2018-06-28) + +### Bug Fixes + +- typo ([305d877](https://github.com/uuidjs/uuid/commit/305d877)) + +## [3.3.1](https://github.com/uuidjs/uuid/compare/v3.3.0...v3.3.1) (2018-06-28) + +### Bug Fixes + +- fix [#284](https://github.com/uuidjs/uuid/issues/284) by setting function name in try-catch ([f2a60f2](https://github.com/uuidjs/uuid/commit/f2a60f2)) + +# [3.3.0](https://github.com/uuidjs/uuid/compare/v3.2.1...v3.3.0) (2018-06-22) + +### Bug Fixes + +- assignment to readonly property to allow running in strict mode ([#270](https://github.com/uuidjs/uuid/issues/270)) ([d062fdc](https://github.com/uuidjs/uuid/commit/d062fdc)) +- fix [#229](https://github.com/uuidjs/uuid/issues/229) ([c9684d4](https://github.com/uuidjs/uuid/commit/c9684d4)) +- Get correct version of IE11 crypto ([#274](https://github.com/uuidjs/uuid/issues/274)) ([153d331](https://github.com/uuidjs/uuid/commit/153d331)) +- mem issue when generating uuid ([#267](https://github.com/uuidjs/uuid/issues/267)) ([c47702c](https://github.com/uuidjs/uuid/commit/c47702c)) + +### Features + +- enforce Conventional Commit style commit messages ([#282](https://github.com/uuidjs/uuid/issues/282)) ([cc9a182](https://github.com/uuidjs/uuid/commit/cc9a182)) + +## [3.2.1](https://github.com/uuidjs/uuid/compare/v3.2.0...v3.2.1) (2018-01-16) + +### Bug Fixes + +- use msCrypto if available. Fixes [#241](https://github.com/uuidjs/uuid/issues/241) ([#247](https://github.com/uuidjs/uuid/issues/247)) ([1fef18b](https://github.com/uuidjs/uuid/commit/1fef18b)) + +# [3.2.0](https://github.com/uuidjs/uuid/compare/v3.1.0...v3.2.0) (2018-01-16) + +### Bug Fixes + +- remove mistakenly added typescript dependency, rollback version (standard-version will auto-increment) ([09fa824](https://github.com/uuidjs/uuid/commit/09fa824)) +- use msCrypto if available. Fixes [#241](https://github.com/uuidjs/uuid/issues/241) ([#247](https://github.com/uuidjs/uuid/issues/247)) ([1fef18b](https://github.com/uuidjs/uuid/commit/1fef18b)) + +### Features + +- Add v3 Support ([#217](https://github.com/uuidjs/uuid/issues/217)) ([d94f726](https://github.com/uuidjs/uuid/commit/d94f726)) + +# [3.1.0](https://github.com/uuidjs/uuid/compare/v3.1.0...v3.0.1) (2017-06-17) + +### Bug Fixes + +- (fix) Add .npmignore file to exclude test/ and other non-essential files from packing. (#183) +- Fix typo (#178) +- Simple typo fix (#165) + +### Features + +- v5 support in CLI (#197) +- V5 support (#188) + +# 3.0.1 (2016-11-28) + +- split uuid versions into separate files + +# 3.0.0 (2016-11-17) + +- remove .parse and .unparse + +# 2.0.0 + +- Removed uuid.BufferClass + +# 1.4.0 + +- Improved module context detection +- Removed public RNG functions + +# 1.3.2 + +- Improve tests and handling of v1() options (Issue #24) +- Expose RNG option to allow for perf testing with different generators + +# 1.3.0 + +- Support for version 1 ids, thanks to [@ctavan](https://github.com/ctavan)! +- Support for node.js crypto API +- De-emphasizing performance in favor of a) cryptographic quality PRNGs where available and b) more manageable code diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/CONTRIBUTING.md b/node_modules/@google-cloud/storage/node_modules/uuid/CONTRIBUTING.md new file mode 100644 index 0000000..4a4503d --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/CONTRIBUTING.md @@ -0,0 +1,18 @@ +# Contributing + +Please feel free to file GitHub Issues or propose Pull Requests. We're always happy to discuss improvements to this library! + +## Testing + +```shell +npm test +``` + +## Releasing + +Releases are supposed to be done from master, version bumping is automated through [`standard-version`](https://github.com/conventional-changelog/standard-version): + +```shell +npm run release -- --dry-run # verify output manually +npm run release # follow the instructions from the output of this command +``` diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/LICENSE.md b/node_modules/@google-cloud/storage/node_modules/uuid/LICENSE.md new file mode 100644 index 0000000..3934168 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/LICENSE.md @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2010-2020 Robert Kieffer and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/README.md b/node_modules/@google-cloud/storage/node_modules/uuid/README.md new file mode 100644 index 0000000..ed27e57 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/README.md @@ -0,0 +1,505 @@ + + +# uuid [![CI](https://github.com/uuidjs/uuid/workflows/CI/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ACI) [![Browser](https://github.com/uuidjs/uuid/workflows/Browser/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ABrowser) + +For the creation of [RFC4122](http://www.ietf.org/rfc/rfc4122.txt) UUIDs + +- **Complete** - Support for RFC4122 version 1, 3, 4, and 5 UUIDs +- **Cross-platform** - Support for ... + - CommonJS, [ECMAScript Modules](#ecmascript-modules) and [CDN builds](#cdn-builds) + - Node 8, 10, 12, 14 + - Chrome, Safari, Firefox, Edge, IE 11 browsers + - Webpack and rollup.js module bundlers + - [React Native / Expo](#react-native--expo) +- **Secure** - Cryptographically-strong random values +- **Small** - Zero-dependency, small footprint, plays nice with "tree shaking" packagers +- **CLI** - Includes the [`uuid` command line](#command-line) utility + +**Upgrading from `uuid@3.x`?** Your code is probably okay, but check out [Upgrading From `uuid@3.x`](#upgrading-from-uuid3x) for details. + +## Quickstart + +To create a random UUID... + +**1. Install** + +```shell +npm install uuid +``` + +**2. Create a UUID** (ES6 module syntax) + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' +``` + +... or using CommonJS syntax: + +```javascript +const { v4: uuidv4 } = require('uuid'); +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +For timestamp UUIDs, namespace UUIDs, and other options read on ... + +## API Summary + +| | | | +| --- | --- | --- | +| [`uuid.NIL`](#uuidnil) | The nil UUID string (all zeros) | New in `uuid@8.3` | +| [`uuid.parse()`](#uuidparsestr) | Convert UUID string to array of bytes | New in `uuid@8.3` | +| [`uuid.stringify()`](#uuidstringifyarr-offset) | Convert array of bytes to UUID string | New in `uuid@8.3` | +| [`uuid.v1()`](#uuidv1options-buffer-offset) | Create a version 1 (timestamp) UUID | | +| [`uuid.v3()`](#uuidv3name-namespace-buffer-offset) | Create a version 3 (namespace w/ MD5) UUID | | +| [`uuid.v4()`](#uuidv4options-buffer-offset) | Create a version 4 (random) UUID | | +| [`uuid.v5()`](#uuidv5name-namespace-buffer-offset) | Create a version 5 (namespace w/ SHA-1) UUID | | +| [`uuid.validate()`](#uuidvalidatestr) | Test a string to see if it is a valid UUID | New in `uuid@8.3` | +| [`uuid.version()`](#uuidversionstr) | Detect RFC version of a UUID | New in `uuid@8.3` | + +## API + +### uuid.NIL + +The nil UUID string (all zeros). + +Example: + +```javascript +import { NIL as NIL_UUID } from 'uuid'; + +NIL_UUID; // ⇨ '00000000-0000-0000-0000-000000000000' +``` + +### uuid.parse(str) + +Convert UUID string to array of bytes + +| | | +| --------- | ---------------------------------------- | +| `str` | A valid UUID `String` | +| _returns_ | `Uint8Array[16]` | +| _throws_ | `TypeError` if `str` is not a valid UUID | + +Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left ↠ right order of hex-pairs in UUID strings. As shown in the example below. + +Example: + +```javascript +import { parse as uuidParse } from 'uuid'; + +// Parse a UUID +const bytes = uuidParse('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); + +// Convert to hex strings to show byte order (for documentation purposes) +[...bytes].map((v) => v.toString(16).padStart(2, '0')); // ⇨ + // [ + // '6e', 'c0', 'bd', '7f', + // '11', 'c0', '43', 'da', + // '97', '5e', '2a', '8a', + // 'd9', 'eb', 'ae', '0b' + // ] +``` + +### uuid.stringify(arr[, offset]) + +Convert array of bytes to UUID string + +| | | +| -------------- | ---------------------------------------------------------------------------- | +| `arr` | `Array`-like collection of 16 values (starting from `offset`) between 0-255. | +| [`offset` = 0] | `Number` Starting index in the Array | +| _returns_ | `String` | +| _throws_ | `TypeError` if a valid UUID string cannot be generated | + +Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left ↠ right order of hex-pairs in UUID strings. As shown in the example below. + +Example: + +```javascript +import { stringify as uuidStringify } from 'uuid'; + +const uuidBytes = [ + 0x6e, + 0xc0, + 0xbd, + 0x7f, + 0x11, + 0xc0, + 0x43, + 0xda, + 0x97, + 0x5e, + 0x2a, + 0x8a, + 0xd9, + 0xeb, + 0xae, + 0x0b, +]; + +uuidStringify(uuidBytes); // ⇨ '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b' +``` + +### uuid.v1([options[, buffer[, offset]]]) + +Create an RFC version 1 (timestamp) UUID + +| | | +| --- | --- | +| [`options`] | `Object` with one or more of the following properties: | +| [`options.node` ] | RFC "node" field as an `Array[6]` of byte values (per 4.1.6) | +| [`options.clockseq`] | RFC "clock sequence" as a `Number` between 0 - 0x3fff | +| [`options.msecs`] | RFC "timestamp" field (`Number` of milliseconds, unix epoch) | +| [`options.nsecs`] | RFC "timestamp" field (`Number` of nanseconds to add to `msecs`, should be 0-10,000) | +| [`options.random`] | `Array` of 16 random bytes (0-255) | +| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | +| _throws_ | `Error` if more than 10M UUIDs/sec are requested | + +Note: The default [node id](https://tools.ietf.org/html/rfc4122#section-4.1.6) (the last 12 digits in the UUID) is generated once, randomly, on process startup, and then remains unchanged for the duration of the process. + +Note: `options.random` and `options.rng` are only meaningful on the very first call to `v1()`, where they may be passed to initialize the internal `node` and `clockseq` fields. + +Example: + +```javascript +import { v1 as uuidv1 } from 'uuid'; + +uuidv1(); // ⇨ '2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d' +``` + +Example using `options`: + +```javascript +import { v1 as uuidv1 } from 'uuid'; + +const v1options = { + node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab], + clockseq: 0x1234, + msecs: new Date('2011-11-01').getTime(), + nsecs: 5678, +}; +uuidv1(v1options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab' +``` + +### uuid.v3(name, namespace[, buffer[, offset]]) + +Create an RFC version 3 (namespace w/ MD5) UUID + +API is identical to `v5()`, but uses "v3" instead. + +⚠️ Note: Per the RFC, "_If backward compatibility is not an issue, SHA-1 [Version 5] is preferred_." + +### uuid.v4([options[, buffer[, offset]]]) + +Create an RFC version 4 (random) UUID + +| | | +| --- | --- | +| [`options`] | `Object` with one or more of the following properties: | +| [`options.random`] | `Array` of 16 random bytes (0-255) | +| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | + +Example: + +```javascript +import { v4 as uuidv4 } from 'uuid'; + +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +Example using predefined `random` values: + +```javascript +import { v4 as uuidv4 } from 'uuid'; + +const v4options = { + random: [ + 0x10, + 0x91, + 0x56, + 0xbe, + 0xc4, + 0xfb, + 0xc1, + 0xea, + 0x71, + 0xb4, + 0xef, + 0xe1, + 0x67, + 0x1c, + 0x58, + 0x36, + ], +}; +uuidv4(v4options); // ⇨ '109156be-c4fb-41ea-b1b4-efe1671c5836' +``` + +### uuid.v5(name, namespace[, buffer[, offset]]) + +Create an RFC version 5 (namespace w/ SHA-1) UUID + +| | | +| --- | --- | +| `name` | `String \| Array` | +| `namespace` | `String \| Array[16]` Namespace UUID | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | + +Note: The RFC `DNS` and `URL` namespaces are available as `v5.DNS` and `v5.URL`. + +Example with custom namespace: + +```javascript +import { v5 as uuidv5 } from 'uuid'; + +// Define a custom namespace. Readers, create your own using something like +// https://www.uuidgenerator.net/ +const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; + +uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681' +``` + +Example with RFC `URL` namespace: + +```javascript +import { v5 as uuidv5 } from 'uuid'; + +uuidv5('https://www.w3.org/', uuidv5.URL); // ⇨ 'c106a26a-21bb-5538-8bf2-57095d1976c1' +``` + +### uuid.validate(str) + +Test a string to see if it is a valid UUID + +| | | +| --------- | --------------------------------------------------- | +| `str` | `String` to validate | +| _returns_ | `true` if string is a valid UUID, `false` otherwise | + +Example: + +```javascript +import { validate as uuidValidate } from 'uuid'; + +uuidValidate('not a UUID'); // ⇨ false +uuidValidate('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ true +``` + +Using `validate` and `version` together it is possible to do per-version validation, e.g. validate for only v4 UUIds. + +```javascript +import { version as uuidVersion } from 'uuid'; +import { validate as uuidValidate } from 'uuid'; + +function uuidValidateV4(uuid) { + return uuidValidate(uuid) && uuidVersion(uuid) === 4; +} + +const v1Uuid = 'd9428888-122b-11e1-b85c-61cd3cbb3210'; +const v4Uuid = '109156be-c4fb-41ea-b1b4-efe1671c5836'; + +uuidValidateV4(v4Uuid); // ⇨ true +uuidValidateV4(v1Uuid); // ⇨ false +``` + +### uuid.version(str) + +Detect RFC version of a UUID + +| | | +| --------- | ---------------------------------------- | +| `str` | A valid UUID `String` | +| _returns_ | `Number` The RFC version of the UUID | +| _throws_ | `TypeError` if `str` is not a valid UUID | + +Example: + +```javascript +import { version as uuidVersion } from 'uuid'; + +uuidVersion('45637ec4-c85f-11ea-87d0-0242ac130003'); // ⇨ 1 +uuidVersion('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ 4 +``` + +## Command Line + +UUIDs can be generated from the command line using `uuid`. + +```shell +$ uuid +ddeb27fb-d9a0-4624-be4d-4615062daed4 +``` + +The default is to generate version 4 UUIDS, however the other versions are supported. Type `uuid --help` for details: + +```shell +$ uuid --help + +Usage: + uuid + uuid v1 + uuid v3 + uuid v4 + uuid v5 + uuid --help + +Note: may be "URL" or "DNS" to use the corresponding UUIDs +defined by RFC4122 +``` + +## ECMAScript Modules + +This library comes with [ECMAScript Modules](https://www.ecma-international.org/ecma-262/6.0/#sec-modules) (ESM) support for Node.js versions that support it ([example](./examples/node-esmodules/)) as well as bundlers like [rollup.js](https://rollupjs.org/guide/en/#tree-shaking) ([example](./examples/browser-rollup/)) and [webpack](https://webpack.js.org/guides/tree-shaking/) ([example](./examples/browser-webpack/)) (targeting both, Node.js and browser environments). + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +To run the examples you must first create a dist build of this library in the module root: + +```shell +npm run build +``` + +## CDN Builds + +### ECMAScript Modules + +To load this module directly into modern browsers that [support loading ECMAScript Modules](https://caniuse.com/#feat=es6-module) you can make use of [jspm](https://jspm.org/): + +```html + +``` + +### UMD + +To load this module directly into older browsers you can use the [UMD (Universal Module Definition)](https://github.com/umdjs/umd) builds from any of the following CDNs: + +**Using [UNPKG](https://unpkg.com/uuid@latest/dist/umd/)**: + +```html + +``` + +**Using [jsDelivr](https://cdn.jsdelivr.net/npm/uuid@latest/dist/umd/)**: + +```html + +``` + +**Using [cdnjs](https://cdnjs.com/libraries/uuid)**: + +```html + +``` + +These CDNs all provide the same [`uuidv4()`](#uuidv4options-buffer-offset) method: + +```html + +``` + +Methods for the other algorithms ([`uuidv1()`](#uuidv1options-buffer-offset), [`uuidv3()`](#uuidv3name-namespace-buffer-offset) and [`uuidv5()`](#uuidv5name-namespace-buffer-offset)) are available from the files `uuidv1.min.js`, `uuidv3.min.js` and `uuidv5.min.js` respectively. + +## "getRandomValues() not supported" + +This error occurs in environments where the standard [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) API is not supported. This issue can be resolved by adding an appropriate polyfill: + +### React Native / Expo + +1. Install [`react-native-get-random-values`](https://github.com/LinusU/react-native-get-random-values#readme) +1. Import it _before_ `uuid`. Since `uuid` might also appear as a transitive dependency of some other imports it's safest to just import `react-native-get-random-values` as the very first thing in your entry point: + +```javascript +import 'react-native-get-random-values'; +import { v4 as uuidv4 } from 'uuid'; +``` + +Note: If you are using Expo, you must be using at least `react-native-get-random-values@1.5.0` and `expo@39.0.0`. + +### Web Workers / Service Workers (Edge <= 18) + +[In Edge <= 18, Web Crypto is not supported in Web Workers or Service Workers](https://caniuse.com/#feat=cryptography) and we are not aware of a polyfill (let us know if you find one, please). + +## Upgrading From `uuid@7.x` + +### Only Named Exports Supported When Using with Node.js ESM + +`uuid@7.x` did not come with native ECMAScript Module (ESM) support for Node.js. Importing it in Node.js ESM consequently imported the CommonJS source with a default export. This library now comes with true Node.js ESM support and only provides named exports. + +Instead of doing: + +```javascript +import uuid from 'uuid'; +uuid.v4(); +``` + +you will now have to use the named exports: + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); +``` + +### Deep Requires No Longer Supported + +Deep requires like `require('uuid/v4')` [which have been deprecated in `uuid@7.x`](#deep-requires-now-deprecated) are no longer supported. + +## Upgrading From `uuid@3.x` + +"_Wait... what happened to `uuid@4.x` - `uuid@6.x`?!?_" + +In order to avoid confusion with RFC [version 4](#uuidv4options-buffer-offset) and [version 5](#uuidv5name-namespace-buffer-offset) UUIDs, and a possible [version 6](http://gh.peabody.io/uuidv6/), releases 4 thru 6 of this module have been skipped. + +### Deep Requires Now Deprecated + +`uuid@3.x` encouraged the use of deep requires to minimize the bundle size of browser builds: + +```javascript +const uuidv4 = require('uuid/v4'); // <== NOW DEPRECATED! +uuidv4(); +``` + +As of `uuid@7.x` this library now provides ECMAScript modules builds, which allow packagers like Webpack and Rollup to do "tree-shaking" to remove dead code. Instead, use the `import` syntax: + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); +``` + +... or for CommonJS: + +```javascript +const { v4: uuidv4 } = require('uuid'); +uuidv4(); +``` + +### Default Export Removed + +`uuid@3.x` was exporting the Version 4 UUID method as a default export: + +```javascript +const uuid = require('uuid'); // <== REMOVED! +``` + +This usage pattern was already discouraged in `uuid@3.x` and has been removed in `uuid@7.x`. + +---- +Markdown generated from [README_js.md](README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd) \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/bin/uuid b/node_modules/@google-cloud/storage/node_modules/uuid/dist/bin/uuid new file mode 100644 index 0000000..f38d2ee --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/bin/uuid @@ -0,0 +1,2 @@ +#!/usr/bin/env node +require('../uuid-bin'); diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/index.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/index.js new file mode 100644 index 0000000..1db6f6d --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/index.js @@ -0,0 +1,9 @@ +export { default as v1 } from './v1.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as NIL } from './nil.js'; +export { default as version } from './version.js'; +export { default as validate } from './validate.js'; +export { default as stringify } from './stringify.js'; +export { default as parse } from './parse.js'; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/md5.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/md5.js new file mode 100644 index 0000000..8b5d46a --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/md5.js @@ -0,0 +1,215 @@ +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes === 'string') { + var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Uint8Array(msg.length); + + for (var i = 0; i < msg.length; ++i) { + bytes[i] = msg.charCodeAt(i); + } + } + + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); +} +/* + * Convert an array of little-endian words to an array of bytes + */ + + +function md5ToHexEncodedArray(input) { + var output = []; + var length32 = input.length * 32; + var hexTab = '0123456789abcdef'; + + for (var i = 0; i < length32; i += 8) { + var x = input[i >> 5] >>> i % 32 & 0xff; + var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); + } + + return output; +} +/** + * Calculate output length with padding and bit length + */ + + +function getOutputLength(inputLength8) { + return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; +} +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + + +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[getOutputLength(len) - 1] = len; + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + + for (var i = 0; i < x.length; i += 16) { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; +} +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + + +function bytesToWords(input) { + if (input.length === 0) { + return []; + } + + var length8 = input.length * 8; + var output = new Uint32Array(getOutputLength(length8)); + + for (var i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } + + return output; +} +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + + +function safeAdd(x, y) { + var lsw = (x & 0xffff) + (y & 0xffff); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; +} +/* + * Bitwise rotate a 32-bit number to the left. + */ + + +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; +} +/* + * These functions implement the four basic operations the algorithm uses. + */ + + +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} + +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); +} + +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); +} + +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} + +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} + +export default md5; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/nil.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/nil.js new file mode 100644 index 0000000..b36324c --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/nil.js @@ -0,0 +1 @@ +export default '00000000-0000-0000-0000-000000000000'; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/parse.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/parse.js new file mode 100644 index 0000000..7c5b1d5 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/parse.js @@ -0,0 +1,35 @@ +import validate from './validate.js'; + +function parse(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + var v; + var arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +export default parse; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/regex.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/regex.js new file mode 100644 index 0000000..3da8673 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/regex.js @@ -0,0 +1 @@ +export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/rng.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/rng.js new file mode 100644 index 0000000..8abbf2e --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/rng.js @@ -0,0 +1,19 @@ +// Unique ID creation requires a high quality random # generator. In the browser we therefore +// require the crypto API and do not support built-in fallback to lower quality random number +// generators (like Math.random()). +var getRandomValues; +var rnds8 = new Uint8Array(16); +export default function rng() { + // lazy load so that environments that need to polyfill have a chance to do so + if (!getRandomValues) { + // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also, + // find the complete implementation of crypto (msCrypto) on IE11. + getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto); + + if (!getRandomValues) { + throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); + } + } + + return getRandomValues(rnds8); +} \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/sha1.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/sha1.js new file mode 100644 index 0000000..940548b --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/sha1.js @@ -0,0 +1,96 @@ +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + + case 1: + return x ^ y ^ z; + + case 2: + return x & y ^ x & z ^ y & z; + + case 3: + return x ^ y ^ z; + } +} + +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} + +function sha1(bytes) { + var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof bytes === 'string') { + var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = []; + + for (var i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + // Convert Array-like to Array + bytes = Array.prototype.slice.call(bytes); + } + + bytes.push(0x80); + var l = bytes.length / 4 + 2; + var N = Math.ceil(l / 16); + var M = new Array(N); + + for (var _i = 0; _i < N; ++_i) { + var arr = new Uint32Array(16); + + for (var j = 0; j < 16; ++j) { + arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3]; + } + + M[_i] = arr; + } + + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; + + for (var _i2 = 0; _i2 < N; ++_i2) { + var W = new Uint32Array(80); + + for (var t = 0; t < 16; ++t) { + W[t] = M[_i2][t]; + } + + for (var _t = 16; _t < 80; ++_t) { + W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1); + } + + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + var e = H[4]; + + for (var _t2 = 0; _t2 < 80; ++_t2) { + var s = Math.floor(_t2 / 20); + var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; +} + +export default sha1; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/stringify.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/stringify.js new file mode 100644 index 0000000..3102111 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/stringify.js @@ -0,0 +1,30 @@ +import validate from './validate.js'; +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ + +var byteToHex = []; + +for (var i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).substr(1)); +} + +function stringify(arr) { + var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!validate(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +export default stringify; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/v1.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/v1.js new file mode 100644 index 0000000..1a22591 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/v1.js @@ -0,0 +1,95 @@ +import rng from './rng.js'; +import stringify from './stringify.js'; // **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +var _nodeId; + +var _clockseq; // Previous uuid creation time + + +var _lastMSecs = 0; +var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + var i = buf && offset || 0; + var b = buf || new Array(16); + options = options || {}; + var node = options.node || _nodeId; + var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + var seedBytes = options.random || (options.rng || rng)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + var msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + var tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (var n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || stringify(b); +} + +export default v1; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/v3.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/v3.js new file mode 100644 index 0000000..c9ab9a4 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/v3.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import md5 from './md5.js'; +var v3 = v35('v3', 0x30, md5); +export default v3; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/v35.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/v35.js new file mode 100644 index 0000000..31dd8a1 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/v35.js @@ -0,0 +1,64 @@ +import stringify from './stringify.js'; +import parse from './parse.js'; + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + var bytes = []; + + for (var i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +export var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +export var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +export default function (name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + if (typeof value === 'string') { + value = stringToBytes(value); + } + + if (typeof namespace === 'string') { + namespace = parse(namespace); + } + + if (namespace.length !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + var bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (var i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return stringify(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/v4.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/v4.js new file mode 100644 index 0000000..404810a --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/v4.js @@ -0,0 +1,24 @@ +import rng from './rng.js'; +import stringify from './stringify.js'; + +function v4(options, buf, offset) { + options = options || {}; + var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (var i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return stringify(rnds); +} + +export default v4; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/v5.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/v5.js new file mode 100644 index 0000000..c08d96b --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/v5.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import sha1 from './sha1.js'; +var v5 = v35('v5', 0x50, sha1); +export default v5; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/validate.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/validate.js new file mode 100644 index 0000000..f1cdc7a --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/validate.js @@ -0,0 +1,7 @@ +import REGEX from './regex.js'; + +function validate(uuid) { + return typeof uuid === 'string' && REGEX.test(uuid); +} + +export default validate; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/version.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/version.js new file mode 100644 index 0000000..77530e9 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-browser/version.js @@ -0,0 +1,11 @@ +import validate from './validate.js'; + +function version(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.substr(14, 1), 16); +} + +export default version; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/index.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/index.js new file mode 100644 index 0000000..1db6f6d --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/index.js @@ -0,0 +1,9 @@ +export { default as v1 } from './v1.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as NIL } from './nil.js'; +export { default as version } from './version.js'; +export { default as validate } from './validate.js'; +export { default as stringify } from './stringify.js'; +export { default as parse } from './parse.js'; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/md5.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/md5.js new file mode 100644 index 0000000..4d68b04 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/md5.js @@ -0,0 +1,13 @@ +import crypto from 'crypto'; + +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return crypto.createHash('md5').update(bytes).digest(); +} + +export default md5; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/nil.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/nil.js new file mode 100644 index 0000000..b36324c --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/nil.js @@ -0,0 +1 @@ +export default '00000000-0000-0000-0000-000000000000'; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/parse.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/parse.js new file mode 100644 index 0000000..6421c5d --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/parse.js @@ -0,0 +1,35 @@ +import validate from './validate.js'; + +function parse(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +export default parse; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/regex.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/regex.js new file mode 100644 index 0000000..3da8673 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/regex.js @@ -0,0 +1 @@ +export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/rng.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/rng.js new file mode 100644 index 0000000..8006244 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/rng.js @@ -0,0 +1,12 @@ +import crypto from 'crypto'; +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate + +let poolPtr = rnds8Pool.length; +export default function rng() { + if (poolPtr > rnds8Pool.length - 16) { + crypto.randomFillSync(rnds8Pool); + poolPtr = 0; + } + + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/sha1.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/sha1.js new file mode 100644 index 0000000..e23850b --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/sha1.js @@ -0,0 +1,13 @@ +import crypto from 'crypto'; + +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return crypto.createHash('sha1').update(bytes).digest(); +} + +export default sha1; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/stringify.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/stringify.js new file mode 100644 index 0000000..f9bca12 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/stringify.js @@ -0,0 +1,29 @@ +import validate from './validate.js'; +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ + +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).substr(1)); +} + +function stringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!validate(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +export default stringify; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/v1.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/v1.js new file mode 100644 index 0000000..ebf81ac --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/v1.js @@ -0,0 +1,95 @@ +import rng from './rng.js'; +import stringify from './stringify.js'; // **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || rng)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || stringify(b); +} + +export default v1; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/v3.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/v3.js new file mode 100644 index 0000000..09063b8 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/v3.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import md5 from './md5.js'; +const v3 = v35('v3', 0x30, md5); +export default v3; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/v35.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/v35.js new file mode 100644 index 0000000..22f6a19 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/v35.js @@ -0,0 +1,64 @@ +import stringify from './stringify.js'; +import parse from './parse.js'; + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +export const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +export const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +export default function (name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + if (typeof value === 'string') { + value = stringToBytes(value); + } + + if (typeof namespace === 'string') { + namespace = parse(namespace); + } + + if (namespace.length !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return stringify(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/v4.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/v4.js new file mode 100644 index 0000000..efad926 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/v4.js @@ -0,0 +1,24 @@ +import rng from './rng.js'; +import stringify from './stringify.js'; + +function v4(options, buf, offset) { + options = options || {}; + const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return stringify(rnds); +} + +export default v4; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/v5.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/v5.js new file mode 100644 index 0000000..e87fe31 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/v5.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import sha1 from './sha1.js'; +const v5 = v35('v5', 0x50, sha1); +export default v5; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/validate.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/validate.js new file mode 100644 index 0000000..f1cdc7a --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/validate.js @@ -0,0 +1,7 @@ +import REGEX from './regex.js'; + +function validate(uuid) { + return typeof uuid === 'string' && REGEX.test(uuid); +} + +export default validate; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/version.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/version.js new file mode 100644 index 0000000..77530e9 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/esm-node/version.js @@ -0,0 +1,11 @@ +import validate from './validate.js'; + +function version(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.substr(14, 1), 16); +} + +export default version; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/index.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/index.js new file mode 100644 index 0000000..bf13b10 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/index.js @@ -0,0 +1,79 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "v1", { + enumerable: true, + get: function () { + return _v.default; + } +}); +Object.defineProperty(exports, "v3", { + enumerable: true, + get: function () { + return _v2.default; + } +}); +Object.defineProperty(exports, "v4", { + enumerable: true, + get: function () { + return _v3.default; + } +}); +Object.defineProperty(exports, "v5", { + enumerable: true, + get: function () { + return _v4.default; + } +}); +Object.defineProperty(exports, "NIL", { + enumerable: true, + get: function () { + return _nil.default; + } +}); +Object.defineProperty(exports, "version", { + enumerable: true, + get: function () { + return _version.default; + } +}); +Object.defineProperty(exports, "validate", { + enumerable: true, + get: function () { + return _validate.default; + } +}); +Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function () { + return _stringify.default; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function () { + return _parse.default; + } +}); + +var _v = _interopRequireDefault(require("./v1.js")); + +var _v2 = _interopRequireDefault(require("./v3.js")); + +var _v3 = _interopRequireDefault(require("./v4.js")); + +var _v4 = _interopRequireDefault(require("./v5.js")); + +var _nil = _interopRequireDefault(require("./nil.js")); + +var _version = _interopRequireDefault(require("./version.js")); + +var _validate = _interopRequireDefault(require("./validate.js")); + +var _stringify = _interopRequireDefault(require("./stringify.js")); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/md5-browser.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/md5-browser.js new file mode 100644 index 0000000..7a4582a --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/md5-browser.js @@ -0,0 +1,223 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Uint8Array(msg.length); + + for (let i = 0; i < msg.length; ++i) { + bytes[i] = msg.charCodeAt(i); + } + } + + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); +} +/* + * Convert an array of little-endian words to an array of bytes + */ + + +function md5ToHexEncodedArray(input) { + const output = []; + const length32 = input.length * 32; + const hexTab = '0123456789abcdef'; + + for (let i = 0; i < length32; i += 8) { + const x = input[i >> 5] >>> i % 32 & 0xff; + const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); + } + + return output; +} +/** + * Calculate output length with padding and bit length + */ + + +function getOutputLength(inputLength8) { + return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; +} +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + + +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[getOutputLength(len) - 1] = len; + let a = 1732584193; + let b = -271733879; + let c = -1732584194; + let d = 271733878; + + for (let i = 0; i < x.length; i += 16) { + const olda = a; + const oldb = b; + const oldc = c; + const oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; +} +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + + +function bytesToWords(input) { + if (input.length === 0) { + return []; + } + + const length8 = input.length * 8; + const output = new Uint32Array(getOutputLength(length8)); + + for (let i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } + + return output; +} +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + + +function safeAdd(x, y) { + const lsw = (x & 0xffff) + (y & 0xffff); + const msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; +} +/* + * Bitwise rotate a 32-bit number to the left. + */ + + +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; +} +/* + * These functions implement the four basic operations the algorithm uses. + */ + + +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} + +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); +} + +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); +} + +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} + +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} + +var _default = md5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/md5.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/md5.js new file mode 100644 index 0000000..824d481 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/md5.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return _crypto.default.createHash('md5').update(bytes).digest(); +} + +var _default = md5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/nil.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/nil.js new file mode 100644 index 0000000..7ade577 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/nil.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = '00000000-0000-0000-0000-000000000000'; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/parse.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/parse.js new file mode 100644 index 0000000..4c69fc3 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/parse.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +var _default = parse; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/regex.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/regex.js new file mode 100644 index 0000000..1ef91d6 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/regex.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/rng-browser.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/rng-browser.js new file mode 100644 index 0000000..91faeae --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/rng-browser.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rng; +// Unique ID creation requires a high quality random # generator. In the browser we therefore +// require the crypto API and do not support built-in fallback to lower quality random number +// generators (like Math.random()). +let getRandomValues; +const rnds8 = new Uint8Array(16); + +function rng() { + // lazy load so that environments that need to polyfill have a chance to do so + if (!getRandomValues) { + // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also, + // find the complete implementation of crypto (msCrypto) on IE11. + getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto); + + if (!getRandomValues) { + throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); + } + } + + return getRandomValues(rnds8); +} \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/rng.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/rng.js new file mode 100644 index 0000000..3507f93 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/rng.js @@ -0,0 +1,24 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rng; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate + +let poolPtr = rnds8Pool.length; + +function rng() { + if (poolPtr > rnds8Pool.length - 16) { + _crypto.default.randomFillSync(rnds8Pool); + + poolPtr = 0; + } + + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/sha1-browser.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/sha1-browser.js new file mode 100644 index 0000000..24cbced --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/sha1-browser.js @@ -0,0 +1,104 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + + case 1: + return x ^ y ^ z; + + case 2: + return x & y ^ x & z ^ y & z; + + case 3: + return x ^ y ^ z; + } +} + +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} + +function sha1(bytes) { + const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = []; + + for (let i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + // Convert Array-like to Array + bytes = Array.prototype.slice.call(bytes); + } + + bytes.push(0x80); + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + + for (let i = 0; i < N; ++i) { + const arr = new Uint32Array(16); + + for (let j = 0; j < 16; ++j) { + arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + } + + M[i] = arr; + } + + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; + + for (let i = 0; i < N; ++i) { + const W = new Uint32Array(80); + + for (let t = 0; t < 16; ++t) { + W[t] = M[i][t]; + } + + for (let t = 16; t < 80; ++t) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } + + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; +} + +var _default = sha1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/sha1.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/sha1.js new file mode 100644 index 0000000..03bdd63 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/sha1.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return _crypto.default.createHash('sha1').update(bytes).digest(); +} + +var _default = sha1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/stringify.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/stringify.js new file mode 100644 index 0000000..b8e7519 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/stringify.js @@ -0,0 +1,39 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).substr(1)); +} + +function stringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!(0, _validate.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +var _default = stringify; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuid.min.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuid.min.js new file mode 100644 index 0000000..639ca2f --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuid.min.js @@ -0,0 +1 @@ +!function(r,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((r="undefined"!=typeof globalThis?globalThis:r||self).uuid={})}(this,(function(r){"use strict";var e,n=new Uint8Array(16);function t(){if(!e&&!(e="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return e(n)}var o=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function a(r){return"string"==typeof r&&o.test(r)}for(var i,u,f=[],s=0;s<256;++s)f.push((s+256).toString(16).substr(1));function c(r){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=(f[r[e+0]]+f[r[e+1]]+f[r[e+2]]+f[r[e+3]]+"-"+f[r[e+4]]+f[r[e+5]]+"-"+f[r[e+6]]+f[r[e+7]]+"-"+f[r[e+8]]+f[r[e+9]]+"-"+f[r[e+10]]+f[r[e+11]]+f[r[e+12]]+f[r[e+13]]+f[r[e+14]]+f[r[e+15]]).toLowerCase();if(!a(n))throw TypeError("Stringified UUID is invalid");return n}var l=0,d=0;function v(r){if(!a(r))throw TypeError("Invalid UUID");var e,n=new Uint8Array(16);return n[0]=(e=parseInt(r.slice(0,8),16))>>>24,n[1]=e>>>16&255,n[2]=e>>>8&255,n[3]=255&e,n[4]=(e=parseInt(r.slice(9,13),16))>>>8,n[5]=255&e,n[6]=(e=parseInt(r.slice(14,18),16))>>>8,n[7]=255&e,n[8]=(e=parseInt(r.slice(19,23),16))>>>8,n[9]=255&e,n[10]=(e=parseInt(r.slice(24,36),16))/1099511627776&255,n[11]=e/4294967296&255,n[12]=e>>>24&255,n[13]=e>>>16&255,n[14]=e>>>8&255,n[15]=255&e,n}function p(r,e,n){function t(r,t,o,a){if("string"==typeof r&&(r=function(r){r=unescape(encodeURIComponent(r));for(var e=[],n=0;n>>9<<4)+1}function y(r,e){var n=(65535&r)+(65535&e);return(r>>16)+(e>>16)+(n>>16)<<16|65535&n}function g(r,e,n,t,o,a){return y((i=y(y(e,r),y(t,a)))<<(u=o)|i>>>32-u,n);var i,u}function m(r,e,n,t,o,a,i){return g(e&n|~e&t,r,e,o,a,i)}function w(r,e,n,t,o,a,i){return g(e&t|n&~t,r,e,o,a,i)}function b(r,e,n,t,o,a,i){return g(e^n^t,r,e,o,a,i)}function A(r,e,n,t,o,a,i){return g(n^(e|~t),r,e,o,a,i)}var U=p("v3",48,(function(r){if("string"==typeof r){var e=unescape(encodeURIComponent(r));r=new Uint8Array(e.length);for(var n=0;n>5]>>>o%32&255,i=parseInt(t.charAt(a>>>4&15)+t.charAt(15&a),16);e.push(i)}return e}(function(r,e){r[e>>5]|=128<>5]|=(255&r[t/8])<>>32-e}var R=p("v5",80,(function(r){var e=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof r){var t=unescape(encodeURIComponent(r));r=[];for(var o=0;o>>0;w=m,m=g,g=C(y,30)>>>0,y=h,h=U}n[0]=n[0]+h>>>0,n[1]=n[1]+y>>>0,n[2]=n[2]+g>>>0,n[3]=n[3]+m>>>0,n[4]=n[4]+w>>>0}return[n[0]>>24&255,n[0]>>16&255,n[0]>>8&255,255&n[0],n[1]>>24&255,n[1]>>16&255,n[1]>>8&255,255&n[1],n[2]>>24&255,n[2]>>16&255,n[2]>>8&255,255&n[2],n[3]>>24&255,n[3]>>16&255,n[3]>>8&255,255&n[3],n[4]>>24&255,n[4]>>16&255,n[4]>>8&255,255&n[4]]}));r.NIL="00000000-0000-0000-0000-000000000000",r.parse=v,r.stringify=c,r.v1=function(r,e,n){var o=e&&n||0,a=e||new Array(16),f=(r=r||{}).node||i,s=void 0!==r.clockseq?r.clockseq:u;if(null==f||null==s){var v=r.random||(r.rng||t)();null==f&&(f=i=[1|v[0],v[1],v[2],v[3],v[4],v[5]]),null==s&&(s=u=16383&(v[6]<<8|v[7]))}var p=void 0!==r.msecs?r.msecs:Date.now(),h=void 0!==r.nsecs?r.nsecs:d+1,y=p-l+(h-d)/1e4;if(y<0&&void 0===r.clockseq&&(s=s+1&16383),(y<0||p>l)&&void 0===r.nsecs&&(h=0),h>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");l=p,d=h,u=s;var g=(1e4*(268435455&(p+=122192928e5))+h)%4294967296;a[o++]=g>>>24&255,a[o++]=g>>>16&255,a[o++]=g>>>8&255,a[o++]=255&g;var m=p/4294967296*1e4&268435455;a[o++]=m>>>8&255,a[o++]=255&m,a[o++]=m>>>24&15|16,a[o++]=m>>>16&255,a[o++]=s>>>8|128,a[o++]=255&s;for(var w=0;w<6;++w)a[o+w]=f[w];return e||c(a)},r.v3=U,r.v4=function(r,e,n){var o=(r=r||{}).random||(r.rng||t)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,e){n=n||0;for(var a=0;a<16;++a)e[n+a]=o[a];return e}return c(o)},r.v5=R,r.validate=a,r.version=function(r){if(!a(r))throw TypeError("Invalid UUID");return parseInt(r.substr(14,1),16)},Object.defineProperty(r,"__esModule",{value:!0})})); \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidNIL.min.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidNIL.min.js new file mode 100644 index 0000000..30b28a7 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidNIL.min.js @@ -0,0 +1 @@ +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e="undefined"!=typeof globalThis?globalThis:e||self).uuidNIL=n()}(this,(function(){"use strict";return"00000000-0000-0000-0000-000000000000"})); \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidParse.min.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidParse.min.js new file mode 100644 index 0000000..d48ea6a --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidParse.min.js @@ -0,0 +1 @@ +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e="undefined"!=typeof globalThis?globalThis:e||self).uuidParse=n()}(this,(function(){"use strict";var e=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;return function(n){if(!function(n){return"string"==typeof n&&e.test(n)}(n))throw TypeError("Invalid UUID");var t,i=new Uint8Array(16);return i[0]=(t=parseInt(n.slice(0,8),16))>>>24,i[1]=t>>>16&255,i[2]=t>>>8&255,i[3]=255&t,i[4]=(t=parseInt(n.slice(9,13),16))>>>8,i[5]=255&t,i[6]=(t=parseInt(n.slice(14,18),16))>>>8,i[7]=255&t,i[8]=(t=parseInt(n.slice(19,23),16))>>>8,i[9]=255&t,i[10]=(t=parseInt(n.slice(24,36),16))/1099511627776&255,i[11]=t/4294967296&255,i[12]=t>>>24&255,i[13]=t>>>16&255,i[14]=t>>>8&255,i[15]=255&t,i}})); \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidStringify.min.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidStringify.min.js new file mode 100644 index 0000000..fd39adc --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidStringify.min.js @@ -0,0 +1 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).uuidStringify=t()}(this,(function(){"use strict";var e=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function t(t){return"string"==typeof t&&e.test(t)}for(var i=[],n=0;n<256;++n)i.push((n+256).toString(16).substr(1));return function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,f=(i[e[n+0]]+i[e[n+1]]+i[e[n+2]]+i[e[n+3]]+"-"+i[e[n+4]]+i[e[n+5]]+"-"+i[e[n+6]]+i[e[n+7]]+"-"+i[e[n+8]]+i[e[n+9]]+"-"+i[e[n+10]]+i[e[n+11]]+i[e[n+12]]+i[e[n+13]]+i[e[n+14]]+i[e[n+15]]).toLowerCase();if(!t(f))throw TypeError("Stringified UUID is invalid");return f}})); \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidValidate.min.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidValidate.min.js new file mode 100644 index 0000000..378e5b9 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidValidate.min.js @@ -0,0 +1 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).uuidValidate=t()}(this,(function(){"use strict";var e=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;return function(t){return"string"==typeof t&&e.test(t)}})); \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidVersion.min.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidVersion.min.js new file mode 100644 index 0000000..274bb09 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidVersion.min.js @@ -0,0 +1 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).uuidVersion=t()}(this,(function(){"use strict";var e=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;return function(t){if(!function(t){return"string"==typeof t&&e.test(t)}(t))throw TypeError("Invalid UUID");return parseInt(t.substr(14,1),16)}})); \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidv1.min.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidv1.min.js new file mode 100644 index 0000000..2622889 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidv1.min.js @@ -0,0 +1 @@ +!function(e,o){"object"==typeof exports&&"undefined"!=typeof module?module.exports=o():"function"==typeof define&&define.amd?define(o):(e="undefined"!=typeof globalThis?globalThis:e||self).uuidv1=o()}(this,(function(){"use strict";var e,o=new Uint8Array(16);function t(){if(!e&&!(e="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return e(o)}var n=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function r(e){return"string"==typeof e&&n.test(e)}for(var i,u,s=[],a=0;a<256;++a)s.push((a+256).toString(16).substr(1));var d=0,f=0;return function(e,o,n){var a=o&&n||0,c=o||new Array(16),l=(e=e||{}).node||i,p=void 0!==e.clockseq?e.clockseq:u;if(null==l||null==p){var v=e.random||(e.rng||t)();null==l&&(l=i=[1|v[0],v[1],v[2],v[3],v[4],v[5]]),null==p&&(p=u=16383&(v[6]<<8|v[7]))}var y=void 0!==e.msecs?e.msecs:Date.now(),m=void 0!==e.nsecs?e.nsecs:f+1,g=y-d+(m-f)/1e4;if(g<0&&void 0===e.clockseq&&(p=p+1&16383),(g<0||y>d)&&void 0===e.nsecs&&(m=0),m>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");d=y,f=m,u=p;var h=(1e4*(268435455&(y+=122192928e5))+m)%4294967296;c[a++]=h>>>24&255,c[a++]=h>>>16&255,c[a++]=h>>>8&255,c[a++]=255&h;var w=y/4294967296*1e4&268435455;c[a++]=w>>>8&255,c[a++]=255&w,c[a++]=w>>>24&15|16,c[a++]=w>>>16&255,c[a++]=p>>>8|128,c[a++]=255&p;for(var b=0;b<6;++b)c[a+b]=l[b];return o||function(e){var o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,t=(s[e[o+0]]+s[e[o+1]]+s[e[o+2]]+s[e[o+3]]+"-"+s[e[o+4]]+s[e[o+5]]+"-"+s[e[o+6]]+s[e[o+7]]+"-"+s[e[o+8]]+s[e[o+9]]+"-"+s[e[o+10]]+s[e[o+11]]+s[e[o+12]]+s[e[o+13]]+s[e[o+14]]+s[e[o+15]]).toLowerCase();if(!r(t))throw TypeError("Stringified UUID is invalid");return t}(c)}})); \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidv3.min.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidv3.min.js new file mode 100644 index 0000000..8d37b62 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidv3.min.js @@ -0,0 +1 @@ +!function(n,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(n="undefined"!=typeof globalThis?globalThis:n||self).uuidv3=r()}(this,(function(){"use strict";var n=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function r(r){return"string"==typeof r&&n.test(r)}for(var e=[],t=0;t<256;++t)e.push((t+256).toString(16).substr(1));function i(n){return 14+(n+64>>>9<<4)+1}function o(n,r){var e=(65535&n)+(65535&r);return(n>>16)+(r>>16)+(e>>16)<<16|65535&e}function a(n,r,e,t,i,a){return o((f=o(o(r,n),o(t,a)))<<(u=i)|f>>>32-u,e);var f,u}function f(n,r,e,t,i,o,f){return a(r&e|~r&t,n,r,i,o,f)}function u(n,r,e,t,i,o,f){return a(r&t|e&~t,n,r,i,o,f)}function c(n,r,e,t,i,o,f){return a(r^e^t,n,r,i,o,f)}function s(n,r,e,t,i,o,f){return a(e^(r|~t),n,r,i,o,f)}return function(n,t,i){function o(n,o,a,f){if("string"==typeof n&&(n=function(n){n=unescape(encodeURIComponent(n));for(var r=[],e=0;e>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=255&e,t[4]=(e=parseInt(n.slice(9,13),16))>>>8,t[5]=255&e,t[6]=(e=parseInt(n.slice(14,18),16))>>>8,t[7]=255&e,t[8]=(e=parseInt(n.slice(19,23),16))>>>8,t[9]=255&e,t[10]=(e=parseInt(n.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=255&e,t}(o)),16!==o.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var u=new Uint8Array(16+n.length);if(u.set(o),u.set(n,o.length),(u=i(u))[6]=15&u[6]|t,u[8]=63&u[8]|128,a){f=f||0;for(var c=0;c<16;++c)a[f+c]=u[c];return a}return function(n){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=(e[n[t+0]]+e[n[t+1]]+e[n[t+2]]+e[n[t+3]]+"-"+e[n[t+4]]+e[n[t+5]]+"-"+e[n[t+6]]+e[n[t+7]]+"-"+e[n[t+8]]+e[n[t+9]]+"-"+e[n[t+10]]+e[n[t+11]]+e[n[t+12]]+e[n[t+13]]+e[n[t+14]]+e[n[t+15]]).toLowerCase();if(!r(i))throw TypeError("Stringified UUID is invalid");return i}(u)}try{o.name=n}catch(n){}return o.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",o.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",o}("v3",48,(function(n){if("string"==typeof n){var r=unescape(encodeURIComponent(n));n=new Uint8Array(r.length);for(var e=0;e>5]>>>i%32&255,a=parseInt(t.charAt(o>>>4&15)+t.charAt(15&o),16);r.push(a)}return r}(function(n,r){n[r>>5]|=128<>5]|=(255&n[t/8])<1&&void 0!==arguments[1]?arguments[1]:0,o=(i[t[e+0]]+i[t[e+1]]+i[t[e+2]]+i[t[e+3]]+"-"+i[t[e+4]]+i[t[e+5]]+"-"+i[t[e+6]]+i[t[e+7]]+"-"+i[t[e+8]]+i[t[e+9]]+"-"+i[t[e+10]]+i[t[e+11]]+i[t[e+12]]+i[t[e+13]]+i[t[e+14]]+i[t[e+15]]).toLowerCase();if(!r(o))throw TypeError("Stringified UUID is invalid");return o}(u)}})); \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidv5.min.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidv5.min.js new file mode 100644 index 0000000..ba6fc63 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/umd/uuidv5.min.js @@ -0,0 +1 @@ +!function(r,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(r="undefined"!=typeof globalThis?globalThis:r||self).uuidv5=e()}(this,(function(){"use strict";var r=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function e(e){return"string"==typeof e&&r.test(e)}for(var t=[],n=0;n<256;++n)t.push((n+256).toString(16).substr(1));function a(r,e,t,n){switch(r){case 0:return e&t^~e&n;case 1:return e^t^n;case 2:return e&t^e&n^t&n;case 3:return e^t^n}}function o(r,e){return r<>>32-e}return function(r,n,a){function o(r,o,i,f){if("string"==typeof r&&(r=function(r){r=unescape(encodeURIComponent(r));for(var e=[],t=0;t>>24,n[1]=t>>>16&255,n[2]=t>>>8&255,n[3]=255&t,n[4]=(t=parseInt(r.slice(9,13),16))>>>8,n[5]=255&t,n[6]=(t=parseInt(r.slice(14,18),16))>>>8,n[7]=255&t,n[8]=(t=parseInt(r.slice(19,23),16))>>>8,n[9]=255&t,n[10]=(t=parseInt(r.slice(24,36),16))/1099511627776&255,n[11]=t/4294967296&255,n[12]=t>>>24&255,n[13]=t>>>16&255,n[14]=t>>>8&255,n[15]=255&t,n}(o)),16!==o.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var s=new Uint8Array(16+r.length);if(s.set(o),s.set(r,o.length),(s=a(s))[6]=15&s[6]|n,s[8]=63&s[8]|128,i){f=f||0;for(var u=0;u<16;++u)i[f+u]=s[u];return i}return function(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,a=(t[r[n+0]]+t[r[n+1]]+t[r[n+2]]+t[r[n+3]]+"-"+t[r[n+4]]+t[r[n+5]]+"-"+t[r[n+6]]+t[r[n+7]]+"-"+t[r[n+8]]+t[r[n+9]]+"-"+t[r[n+10]]+t[r[n+11]]+t[r[n+12]]+t[r[n+13]]+t[r[n+14]]+t[r[n+15]]).toLowerCase();if(!e(a))throw TypeError("Stringified UUID is invalid");return a}(s)}try{o.name=r}catch(r){}return o.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",o.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",o}("v5",80,(function(r){var e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof r){var n=unescape(encodeURIComponent(r));r=[];for(var i=0;i>>0;A=U,U=w,w=o(b,30)>>>0,b=g,g=C}t[0]=t[0]+g>>>0,t[1]=t[1]+b>>>0,t[2]=t[2]+w>>>0,t[3]=t[3]+U>>>0,t[4]=t[4]+A>>>0}return[t[0]>>24&255,t[0]>>16&255,t[0]>>8&255,255&t[0],t[1]>>24&255,t[1]>>16&255,t[1]>>8&255,255&t[1],t[2]>>24&255,t[2]>>16&255,t[2]>>8&255,255&t[2],t[3]>>24&255,t[3]>>16&255,t[3]>>8&255,255&t[3],t[4]>>24&255,t[4]>>16&255,t[4]>>8&255,255&t[4]]}))})); \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/uuid-bin.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/uuid-bin.js new file mode 100644 index 0000000..50a7a9f --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/uuid-bin.js @@ -0,0 +1,85 @@ +"use strict"; + +var _assert = _interopRequireDefault(require("assert")); + +var _v = _interopRequireDefault(require("./v1.js")); + +var _v2 = _interopRequireDefault(require("./v3.js")); + +var _v3 = _interopRequireDefault(require("./v4.js")); + +var _v4 = _interopRequireDefault(require("./v5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function usage() { + console.log('Usage:'); + console.log(' uuid'); + console.log(' uuid v1'); + console.log(' uuid v3 '); + console.log(' uuid v4'); + console.log(' uuid v5 '); + console.log(' uuid --help'); + console.log('\nNote: may be "URL" or "DNS" to use the corresponding UUIDs defined by RFC4122'); +} + +const args = process.argv.slice(2); + +if (args.indexOf('--help') >= 0) { + usage(); + process.exit(0); +} + +const version = args.shift() || 'v4'; + +switch (version) { + case 'v1': + console.log((0, _v.default)()); + break; + + case 'v3': + { + const name = args.shift(); + let namespace = args.shift(); + (0, _assert.default)(name != null, 'v3 name not specified'); + (0, _assert.default)(namespace != null, 'v3 namespace not specified'); + + if (namespace === 'URL') { + namespace = _v2.default.URL; + } + + if (namespace === 'DNS') { + namespace = _v2.default.DNS; + } + + console.log((0, _v2.default)(name, namespace)); + break; + } + + case 'v4': + console.log((0, _v3.default)()); + break; + + case 'v5': + { + const name = args.shift(); + let namespace = args.shift(); + (0, _assert.default)(name != null, 'v5 name not specified'); + (0, _assert.default)(namespace != null, 'v5 namespace not specified'); + + if (namespace === 'URL') { + namespace = _v4.default.URL; + } + + if (namespace === 'DNS') { + namespace = _v4.default.DNS; + } + + console.log((0, _v4.default)(name, namespace)); + break; + } + + default: + usage(); + process.exit(1); +} \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/v1.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/v1.js new file mode 100644 index 0000000..abb9b3d --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/v1.js @@ -0,0 +1,107 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = _interopRequireDefault(require("./stringify.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || _rng.default)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || (0, _stringify.default)(b); +} + +var _default = v1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/v3.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/v3.js new file mode 100644 index 0000000..6b47ff5 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/v3.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _md = _interopRequireDefault(require("./md5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/v35.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/v35.js new file mode 100644 index 0000000..f784c63 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/v35.js @@ -0,0 +1,78 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; +exports.URL = exports.DNS = void 0; + +var _stringify = _interopRequireDefault(require("./stringify.js")); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.DNS = DNS; +const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = URL; + +function _default(name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + if (typeof value === 'string') { + value = stringToBytes(value); + } + + if (typeof namespace === 'string') { + namespace = (0, _parse.default)(namespace); + } + + if (namespace.length !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return (0, _stringify.default)(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/v4.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/v4.js new file mode 100644 index 0000000..838ce0b --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/v4.js @@ -0,0 +1,37 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = _interopRequireDefault(require("./stringify.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function v4(options, buf, offset) { + options = options || {}; + + const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return (0, _stringify.default)(rnds); +} + +var _default = v4; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/v5.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/v5.js new file mode 100644 index 0000000..99d615e --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/v5.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _sha = _interopRequireDefault(require("./sha1.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/validate.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/validate.js new file mode 100644 index 0000000..fd05215 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/validate.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _regex = _interopRequireDefault(require("./regex.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function validate(uuid) { + return typeof uuid === 'string' && _regex.default.test(uuid); +} + +var _default = validate; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/dist/version.js b/node_modules/@google-cloud/storage/node_modules/uuid/dist/version.js new file mode 100644 index 0000000..b72949c --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/dist/version.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function version(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.substr(14, 1), 16); +} + +var _default = version; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/package.json b/node_modules/@google-cloud/storage/node_modules/uuid/package.json new file mode 100644 index 0000000..f0ab371 --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/package.json @@ -0,0 +1,135 @@ +{ + "name": "uuid", + "version": "8.3.2", + "description": "RFC4122 (v1, v4, and v5) UUIDs", + "commitlint": { + "extends": [ + "@commitlint/config-conventional" + ] + }, + "keywords": [ + "uuid", + "guid", + "rfc4122" + ], + "license": "MIT", + "bin": { + "uuid": "./dist/bin/uuid" + }, + "sideEffects": false, + "main": "./dist/index.js", + "exports": { + ".": { + "node": { + "module": "./dist/esm-node/index.js", + "require": "./dist/index.js", + "import": "./wrapper.mjs" + }, + "default": "./dist/esm-browser/index.js" + }, + "./package.json": "./package.json" + }, + "module": "./dist/esm-node/index.js", + "browser": { + "./dist/md5.js": "./dist/md5-browser.js", + "./dist/rng.js": "./dist/rng-browser.js", + "./dist/sha1.js": "./dist/sha1-browser.js", + "./dist/esm-node/index.js": "./dist/esm-browser/index.js" + }, + "files": [ + "CHANGELOG.md", + "CONTRIBUTING.md", + "LICENSE.md", + "README.md", + "dist", + "wrapper.mjs" + ], + "devDependencies": { + "@babel/cli": "7.11.6", + "@babel/core": "7.11.6", + "@babel/preset-env": "7.11.5", + "@commitlint/cli": "11.0.0", + "@commitlint/config-conventional": "11.0.0", + "@rollup/plugin-node-resolve": "9.0.0", + "babel-eslint": "10.1.0", + "bundlewatch": "0.3.1", + "eslint": "7.10.0", + "eslint-config-prettier": "6.12.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.22.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-prettier": "3.1.4", + "eslint-plugin-promise": "4.2.1", + "eslint-plugin-standard": "4.0.1", + "husky": "4.3.0", + "jest": "25.5.4", + "lint-staged": "10.4.0", + "npm-run-all": "4.1.5", + "optional-dev-dependency": "2.0.1", + "prettier": "2.1.2", + "random-seed": "0.3.0", + "rollup": "2.28.2", + "rollup-plugin-terser": "7.0.2", + "runmd": "1.3.2", + "standard-version": "9.0.0" + }, + "optionalDevDependencies": { + "@wdio/browserstack-service": "6.4.0", + "@wdio/cli": "6.4.0", + "@wdio/jasmine-framework": "6.4.0", + "@wdio/local-runner": "6.4.0", + "@wdio/spec-reporter": "6.4.0", + "@wdio/static-server-service": "6.4.0", + "@wdio/sync": "6.4.0" + }, + "scripts": { + "examples:browser:webpack:build": "cd examples/browser-webpack && npm install && npm run build", + "examples:browser:rollup:build": "cd examples/browser-rollup && npm install && npm run build", + "examples:node:commonjs:test": "cd examples/node-commonjs && npm install && npm test", + "examples:node:esmodules:test": "cd examples/node-esmodules && npm install && npm test", + "lint": "npm run eslint:check && npm run prettier:check", + "eslint:check": "eslint src/ test/ examples/ *.js", + "eslint:fix": "eslint --fix src/ test/ examples/ *.js", + "pretest": "[ -n $CI ] || npm run build", + "test": "BABEL_ENV=commonjs node --throw-deprecation node_modules/.bin/jest test/unit/", + "pretest:browser": "optional-dev-dependency && npm run build && npm-run-all --parallel examples:browser:**", + "test:browser": "wdio run ./wdio.conf.js", + "pretest:node": "npm run build", + "test:node": "npm-run-all --parallel examples:node:**", + "test:pack": "./scripts/testpack.sh", + "pretest:benchmark": "npm run build", + "test:benchmark": "cd examples/benchmark && npm install && npm test", + "prettier:check": "prettier --ignore-path .prettierignore --check '**/*.{js,jsx,json,md}'", + "prettier:fix": "prettier --ignore-path .prettierignore --write '**/*.{js,jsx,json,md}'", + "bundlewatch": "npm run pretest:browser && bundlewatch --config bundlewatch.config.json", + "md": "runmd --watch --output=README.md README_js.md", + "docs": "( node --version | grep -q 'v12' ) && ( npm run build && runmd --output=README.md README_js.md )", + "docs:diff": "npm run docs && git diff --quiet README.md", + "build": "./scripts/build.sh", + "prepack": "npm run build", + "release": "standard-version --no-verify" + }, + "repository": { + "type": "git", + "url": "https://github.com/uuidjs/uuid.git" + }, + "husky": { + "hooks": { + "commit-msg": "commitlint -E HUSKY_GIT_PARAMS", + "pre-commit": "lint-staged" + } + }, + "lint-staged": { + "*.{js,jsx,json,md}": [ + "prettier --write" + ], + "*.{js,jsx}": [ + "eslint --fix" + ] + }, + "standard-version": { + "scripts": { + "postchangelog": "prettier --write CHANGELOG.md" + } + } +} diff --git a/node_modules/@google-cloud/storage/node_modules/uuid/wrapper.mjs b/node_modules/@google-cloud/storage/node_modules/uuid/wrapper.mjs new file mode 100644 index 0000000..c31e9ce --- /dev/null +++ b/node_modules/@google-cloud/storage/node_modules/uuid/wrapper.mjs @@ -0,0 +1,10 @@ +import uuid from './dist/index.js'; +export const v1 = uuid.v1; +export const v3 = uuid.v3; +export const v4 = uuid.v4; +export const v5 = uuid.v5; +export const NIL = uuid.NIL; +export const version = uuid.version; +export const validate = uuid.validate; +export const stringify = uuid.stringify; +export const parse = uuid.parse; diff --git a/node_modules/@google-cloud/storage/package.json b/node_modules/@google-cloud/storage/package.json new file mode 100644 index 0000000..92455c8 --- /dev/null +++ b/node_modules/@google-cloud/storage/package.json @@ -0,0 +1,131 @@ +{ + "name": "@google-cloud/storage", + "description": "Cloud Storage Client Library for Node.js", + "version": "7.18.0", + "license": "Apache-2.0", + "author": "Google Inc.", + "engines": { + "node": ">=14" + }, + "repository": "googleapis/nodejs-storage", + "main": "./build/cjs/src/index.js", + "types": "./build/cjs/src/index.d.ts", + "type": "module", + "exports": { + ".": { + "import": { + "types": "./build/esm/src/index.d.ts", + "default": "./build/esm/src/index.js" + }, + "require": { + "types": "./build/cjs/src/index.d.ts", + "default": "./build/cjs/src/index.js" + } + } + }, + "files": [ + "build/cjs/src", + "build/cjs/package.json", + "!build/cjs/src/**/*.map", + "build/esm/src", + "!build/esm/src/**/*.map" + ], + "keywords": [ + "google apis client", + "google api client", + "google apis", + "google api", + "google", + "google cloud platform", + "google cloud", + "cloud", + "google storage", + "storage" + ], + "scripts": { + "all-test": "npm test && npm run system-test && npm run samples-test", + "benchwrapper": "node bin/benchwrapper.js", + "check": "gts check", + "clean": "rm -rf build/", + "compile:cjs": "tsc -p ./tsconfig.cjs.json", + "compile:esm": "tsc -p .", + "compile": "npm run compile:cjs && npm run compile:esm", + "conformance-test": "mocha --parallel build/cjs/conformance-test/ --require build/cjs/conformance-test/globalHooks.js", + "docs-test": "linkinator docs", + "docs": "jsdoc -c .jsdoc.json", + "fix": "gts fix", + "lint": "gts check", + "postcompile": "cp ./src/package-json-helper.cjs ./build/cjs/src && cp ./src/package-json-helper.cjs ./build/esm/src", + "postcompile:cjs": "babel --plugins gapic-tools/build/src/replaceImportMetaUrl,gapic-tools/build/src/toggleESMFlagVariable build/cjs/src/util.js -o build/cjs/src/util.js && cp internal-tooling/helpers/package.cjs.json build/cjs/package.json", + "precompile": "rm -rf build/", + "preconformance-test": "npm run compile:cjs -- --sourceMap", + "predocs-test": "npm run docs", + "predocs": "npm run compile:cjs -- --sourceMap", + "prelint": "cd samples; npm link ../; npm install", + "prepare": "npm run compile", + "presystem-test:esm": "npm run compile:esm", + "presystem-test": "npm run compile -- --sourceMap", + "pretest": "npm run compile -- --sourceMap", + "samples-test": "npm link && cd samples/ && npm link ../ && npm test && cd ../", + "system-test:esm": "mocha build/esm/system-test --timeout 600000 --exit", + "system-test": "mocha build/cjs/system-test --timeout 600000 --exit", + "test": "c8 mocha build/cjs/test" + }, + "dependencies": { + "@google-cloud/paginator": "^5.0.0", + "@google-cloud/projectify": "^4.0.0", + "@google-cloud/promisify": "<4.1.0", + "abort-controller": "^3.0.0", + "async-retry": "^1.3.3", + "duplexify": "^4.1.3", + "fast-xml-parser": "^4.4.1", + "gaxios": "^6.0.2", + "google-auth-library": "^9.6.3", + "html-entities": "^2.5.2", + "mime": "^3.0.0", + "p-limit": "^3.0.1", + "retry-request": "^7.0.0", + "teeny-request": "^9.0.0", + "uuid": "^8.0.0" + }, + "devDependencies": { + "@babel/cli": "^7.22.10", + "@babel/core": "^7.22.11", + "@google-cloud/pubsub": "^4.0.0", + "@grpc/grpc-js": "^1.0.3", + "@grpc/proto-loader": "^0.8.0", + "@types/async-retry": "^1.4.3", + "@types/duplexify": "^3.6.4", + "@types/mime": "^3.0.0", + "@types/mocha": "^9.1.1", + "@types/mockery": "^1.4.29", + "@types/node": "^24.0.0", + "@types/node-fetch": "^2.1.3", + "@types/proxyquire": "^1.3.28", + "@types/request": "^2.48.4", + "@types/sinon": "^17.0.0", + "@types/tmp": "0.2.6", + "@types/uuid": "^8.0.0", + "@types/yargs": "^17.0.10", + "c8": "^9.0.0", + "form-data": "^4.0.4", + "gapic-tools": "^0.4.0", + "gts": "^5.0.0", + "jsdoc": "^4.0.4", + "jsdoc-fresh": "^5.0.0", + "jsdoc-region-tag": "^4.0.0", + "linkinator": "^3.0.0", + "mocha": "^9.2.2", + "mockery": "^2.1.0", + "nock": "~13.5.0", + "node-fetch": "^2.6.7", + "pack-n-play": "^2.0.0", + "proxyquire": "^2.1.3", + "sinon": "^18.0.0", + "nise": "6.0.0", + "path-to-regexp": "6.3.0", + "tmp": "^0.2.0", + "typescript": "^5.1.6", + "yargs": "^17.3.1" + } +} diff --git a/node_modules/@grpc/grpc-js/LICENSE b/node_modules/@grpc/grpc-js/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/node_modules/@grpc/grpc-js/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@grpc/grpc-js/README.md b/node_modules/@grpc/grpc-js/README.md new file mode 100644 index 0000000..7b1ff43 --- /dev/null +++ b/node_modules/@grpc/grpc-js/README.md @@ -0,0 +1,84 @@ +# Pure JavaScript gRPC Client + +## Installation + +Node 12 is recommended. The exact set of compatible Node versions can be found in the `engines` field of the `package.json` file. + +```sh +npm install @grpc/grpc-js +``` + +## Documentation + +Documentation specifically for the `@grpc/grpc-js` package is currently not available. However, [documentation is available for the `grpc` package](https://grpc.github.io/grpc/node/grpc.html), and the two packages contain mostly the same interface. There are a few notable differences, however, and these differences are noted in the "Migrating from grpc" section below. + +## Features + +- Clients +- Automatic reconnection +- Servers +- Streaming +- Metadata +- Partial compression support: clients can compress and decompress messages, and servers can decompress request messages +- Pick first and round robin load balancing policies +- Client Interceptors +- Connection Keepalives +- HTTP Connect support (proxies) + +If you need a feature from the `grpc` package that is not provided by the `@grpc/grpc-js`, please file a feature request with that information. + +This library does not directly handle `.proto` files. To use `.proto` files with this library we recommend using the `@grpc/proto-loader` package. + +## Migrating from [`grpc`](https://www.npmjs.com/package/grpc) + +`@grpc/grpc-js` is almost a drop-in replacement for `grpc`, but you may need to make a few code changes to use it: + +- If you are currently loading `.proto` files using `grpc.load`, that function is not available in this library. You should instead load your `.proto` files using `@grpc/proto-loader` and load the resulting package definition objects into `@grpc/grpc-js` using `grpc.loadPackageDefinition`. +- If you are currently loading packages generated by `grpc-tools`, you should instead generate your files using the `generate_package_definition` option in `grpc-tools`, then load the object exported by the generated file into `@grpc/grpc-js` using `grpc.loadPackageDefinition`. +- If you have a server and you are using `Server#bind` to bind ports, you will need to use `Server#bindAsync` instead. +- If you are using any channel options supported in `grpc` but not supported in `@grpc/grpc-js`, you may need to adjust your code to handle the different behavior. Refer to [the list of supported options](#supported-channel-options) below. +- Refer to the [detailed package comparison](https://github.com/grpc/grpc-node/blob/master/PACKAGE-COMPARISON.md) for more details on the differences between `grpc` and `@grpc/grpc-js`. + +## Supported Channel Options +Many channel arguments supported in `grpc` are not supported in `@grpc/grpc-js`. The channel arguments supported by `@grpc/grpc-js` are: + - `grpc.ssl_target_name_override` + - `grpc.primary_user_agent` + - `grpc.secondary_user_agent` + - `grpc.default_authority` + - `grpc.keepalive_time_ms` + - `grpc.keepalive_timeout_ms` + - `grpc.keepalive_permit_without_calls` + - `grpc.service_config` + - `grpc.max_concurrent_streams` + - `grpc.initial_reconnect_backoff_ms` + - `grpc.max_reconnect_backoff_ms` + - `grpc.use_local_subchannel_pool` + - `grpc.max_send_message_length` + - `grpc.max_receive_message_length` + - `grpc.enable_http_proxy` + - `grpc.default_compression_algorithm` + - `grpc.enable_channelz` + - `grpc.dns_min_time_between_resolutions_ms` + - `grpc.enable_retries` + - `grpc.max_connection_age_ms` + - `grpc.max_connection_age_grace_ms` + - `grpc.max_connection_idle_ms` + - `grpc.per_rpc_retry_buffer_size` + - `grpc.retry_buffer_size` + - `grpc.service_config_disable_resolution` + - `grpc.client_idle_timeout_ms` + - `grpc-node.max_session_memory` + - `grpc-node.tls_enable_trace` + - `grpc-node.retry_max_attempts_limit` + - `grpc-node.flow_control_window` + - `channelOverride` + - `channelFactoryOverride` + +## Some Notes on API Guarantees + +The public API of this library follows semantic versioning, with some caveats: + +- Some methods are prefixed with an underscore. These methods are internal and should not be considered part of the public API. +- The class `Call` is only exposed due to limitations of TypeScript. It should not be considered part of the public API. +- In general, any API that is exposed by this library but is not exposed by the `grpc` library is likely an error and should not be considered part of the public API. +- The `grpc.experimental` namespace contains APIs that have not stabilized. Any API in that namespace may break in any minor version update. diff --git a/node_modules/@grpc/grpc-js/build/src/admin.d.ts b/node_modules/@grpc/grpc-js/build/src/admin.d.ts new file mode 100644 index 0000000..92b9bba --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/admin.d.ts @@ -0,0 +1,11 @@ +import { ServiceDefinition } from './make-client'; +import { Server, UntypedServiceImplementation } from './server'; +interface GetServiceDefinition { + (): ServiceDefinition; +} +interface GetHandlers { + (): UntypedServiceImplementation; +} +export declare function registerAdminService(getServiceDefinition: GetServiceDefinition, getHandlers: GetHandlers): void; +export declare function addAdminServicesToServer(server: Server): void; +export {}; diff --git a/node_modules/@grpc/grpc-js/build/src/admin.js b/node_modules/@grpc/grpc-js/build/src/admin.js new file mode 100644 index 0000000..6189c52 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/admin.js @@ -0,0 +1,30 @@ +"use strict"; +/* + * Copyright 2021 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.registerAdminService = registerAdminService; +exports.addAdminServicesToServer = addAdminServicesToServer; +const registeredAdminServices = []; +function registerAdminService(getServiceDefinition, getHandlers) { + registeredAdminServices.push({ getServiceDefinition, getHandlers }); +} +function addAdminServicesToServer(server) { + for (const { getServiceDefinition, getHandlers } of registeredAdminServices) { + server.addService(getServiceDefinition(), getHandlers()); + } +} +//# sourceMappingURL=admin.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/admin.js.map b/node_modules/@grpc/grpc-js/build/src/admin.js.map new file mode 100644 index 0000000..44885c5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/admin.js.map @@ -0,0 +1 @@ +{"version":3,"file":"admin.js","sourceRoot":"","sources":["../../src/admin.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAkBH,oDAKC;AAED,4DAIC;AAhBD,MAAM,uBAAuB,GAGvB,EAAE,CAAC;AAET,SAAgB,oBAAoB,CAClC,oBAA0C,EAC1C,WAAwB;IAExB,uBAAuB,CAAC,IAAI,CAAC,EAAE,oBAAoB,EAAE,WAAW,EAAE,CAAC,CAAC;AACtE,CAAC;AAED,SAAgB,wBAAwB,CAAC,MAAc;IACrD,KAAK,MAAM,EAAE,oBAAoB,EAAE,WAAW,EAAE,IAAI,uBAAuB,EAAE,CAAC;QAC5E,MAAM,CAAC,UAAU,CAAC,oBAAoB,EAAE,EAAE,WAAW,EAAE,CAAC,CAAC;IAC3D,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/auth-context.d.ts b/node_modules/@grpc/grpc-js/build/src/auth-context.d.ts new file mode 100644 index 0000000..f58e923 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/auth-context.d.ts @@ -0,0 +1,5 @@ +import { PeerCertificate } from "tls"; +export interface AuthContext { + transportSecurityType?: string; + sslPeerCertificate?: PeerCertificate; +} diff --git a/node_modules/@grpc/grpc-js/build/src/auth-context.js b/node_modules/@grpc/grpc-js/build/src/auth-context.js new file mode 100644 index 0000000..b602f66 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/auth-context.js @@ -0,0 +1,19 @@ +"use strict"; +/* + * Copyright 2025 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=auth-context.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/auth-context.js.map b/node_modules/@grpc/grpc-js/build/src/auth-context.js.map new file mode 100644 index 0000000..512cbe7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/auth-context.js.map @@ -0,0 +1 @@ +{"version":3,"file":"auth-context.js","sourceRoot":"","sources":["../../src/auth-context.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/backoff-timeout.d.ts b/node_modules/@grpc/grpc-js/build/src/backoff-timeout.d.ts new file mode 100644 index 0000000..7c41bd7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/backoff-timeout.d.ts @@ -0,0 +1,94 @@ +export interface BackoffOptions { + initialDelay?: number; + multiplier?: number; + jitter?: number; + maxDelay?: number; +} +export declare class BackoffTimeout { + private callback; + /** + * The delay time at the start, and after each reset. + */ + private readonly initialDelay; + /** + * The exponential backoff multiplier. + */ + private readonly multiplier; + /** + * The maximum delay time + */ + private readonly maxDelay; + /** + * The maximum fraction by which the delay time can randomly vary after + * applying the multiplier. + */ + private readonly jitter; + /** + * The delay time for the next time the timer runs. + */ + private nextDelay; + /** + * The handle of the underlying timer. If running is false, this value refers + * to an object representing a timer that has ended, but it can still be + * interacted with without error. + */ + private timerId; + /** + * Indicates whether the timer is currently running. + */ + private running; + /** + * Indicates whether the timer should keep the Node process running if no + * other async operation is doing so. + */ + private hasRef; + /** + * The time that the currently running timer was started. Only valid if + * running is true. + */ + private startTime; + /** + * The approximate time that the currently running timer will end. Only valid + * if running is true. + */ + private endTime; + private id; + private static nextId; + constructor(callback: () => void, options?: BackoffOptions); + private static getNextId; + private trace; + private runTimer; + /** + * Call the callback after the current amount of delay time + */ + runOnce(): void; + /** + * Stop the timer. The callback will not be called until `runOnce` is called + * again. + */ + stop(): void; + /** + * Reset the delay time to its initial value. If the timer is still running, + * retroactively apply that reset to the current timer. + */ + reset(): void; + /** + * Check whether the timer is currently running. + */ + isRunning(): boolean; + /** + * Set that while the timer is running, it should keep the Node process + * running. + */ + ref(): void; + /** + * Set that while the timer is running, it should not keep the Node process + * running. + */ + unref(): void; + /** + * Get the approximate timestamp of when the timer will fire. Only valid if + * this.isRunning() is true. + */ + getEndTime(): Date; +} diff --git a/node_modules/@grpc/grpc-js/build/src/backoff-timeout.js b/node_modules/@grpc/grpc-js/build/src/backoff-timeout.js new file mode 100644 index 0000000..b4721f3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/backoff-timeout.js @@ -0,0 +1,191 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BackoffTimeout = void 0; +const constants_1 = require("./constants"); +const logging = require("./logging"); +const TRACER_NAME = 'backoff'; +const INITIAL_BACKOFF_MS = 1000; +const BACKOFF_MULTIPLIER = 1.6; +const MAX_BACKOFF_MS = 120000; +const BACKOFF_JITTER = 0.2; +/** + * Get a number uniformly at random in the range [min, max) + * @param min + * @param max + */ +function uniformRandom(min, max) { + return Math.random() * (max - min) + min; +} +class BackoffTimeout { + constructor(callback, options) { + this.callback = callback; + /** + * The delay time at the start, and after each reset. + */ + this.initialDelay = INITIAL_BACKOFF_MS; + /** + * The exponential backoff multiplier. + */ + this.multiplier = BACKOFF_MULTIPLIER; + /** + * The maximum delay time + */ + this.maxDelay = MAX_BACKOFF_MS; + /** + * The maximum fraction by which the delay time can randomly vary after + * applying the multiplier. + */ + this.jitter = BACKOFF_JITTER; + /** + * Indicates whether the timer is currently running. + */ + this.running = false; + /** + * Indicates whether the timer should keep the Node process running if no + * other async operation is doing so. + */ + this.hasRef = true; + /** + * The time that the currently running timer was started. Only valid if + * running is true. + */ + this.startTime = new Date(); + /** + * The approximate time that the currently running timer will end. Only valid + * if running is true. + */ + this.endTime = new Date(); + this.id = BackoffTimeout.getNextId(); + if (options) { + if (options.initialDelay) { + this.initialDelay = options.initialDelay; + } + if (options.multiplier) { + this.multiplier = options.multiplier; + } + if (options.jitter) { + this.jitter = options.jitter; + } + if (options.maxDelay) { + this.maxDelay = options.maxDelay; + } + } + this.trace('constructed initialDelay=' + this.initialDelay + ' multiplier=' + this.multiplier + ' jitter=' + this.jitter + ' maxDelay=' + this.maxDelay); + this.nextDelay = this.initialDelay; + this.timerId = setTimeout(() => { }, 0); + clearTimeout(this.timerId); + } + static getNextId() { + return this.nextId++; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '{' + this.id + '} ' + text); + } + runTimer(delay) { + var _a, _b; + this.trace('runTimer(delay=' + delay + ')'); + this.endTime = this.startTime; + this.endTime.setMilliseconds(this.endTime.getMilliseconds() + delay); + clearTimeout(this.timerId); + this.timerId = setTimeout(() => { + this.trace('timer fired'); + this.running = false; + this.callback(); + }, delay); + if (!this.hasRef) { + (_b = (_a = this.timerId).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + } + /** + * Call the callback after the current amount of delay time + */ + runOnce() { + this.trace('runOnce()'); + this.running = true; + this.startTime = new Date(); + this.runTimer(this.nextDelay); + const nextBackoff = Math.min(this.nextDelay * this.multiplier, this.maxDelay); + const jitterMagnitude = nextBackoff * this.jitter; + this.nextDelay = + nextBackoff + uniformRandom(-jitterMagnitude, jitterMagnitude); + } + /** + * Stop the timer. The callback will not be called until `runOnce` is called + * again. + */ + stop() { + this.trace('stop()'); + clearTimeout(this.timerId); + this.running = false; + } + /** + * Reset the delay time to its initial value. If the timer is still running, + * retroactively apply that reset to the current timer. + */ + reset() { + this.trace('reset() running=' + this.running); + this.nextDelay = this.initialDelay; + if (this.running) { + const now = new Date(); + const newEndTime = this.startTime; + newEndTime.setMilliseconds(newEndTime.getMilliseconds() + this.nextDelay); + clearTimeout(this.timerId); + if (now < newEndTime) { + this.runTimer(newEndTime.getTime() - now.getTime()); + } + else { + this.running = false; + } + } + } + /** + * Check whether the timer is currently running. + */ + isRunning() { + return this.running; + } + /** + * Set that while the timer is running, it should keep the Node process + * running. + */ + ref() { + var _a, _b; + this.hasRef = true; + (_b = (_a = this.timerId).ref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + /** + * Set that while the timer is running, it should not keep the Node process + * running. + */ + unref() { + var _a, _b; + this.hasRef = false; + (_b = (_a = this.timerId).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + /** + * Get the approximate timestamp of when the timer will fire. Only valid if + * this.isRunning() is true. + */ + getEndTime() { + return this.endTime; + } +} +exports.BackoffTimeout = BackoffTimeout; +BackoffTimeout.nextId = 0; +//# sourceMappingURL=backoff-timeout.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/backoff-timeout.js.map b/node_modules/@grpc/grpc-js/build/src/backoff-timeout.js.map new file mode 100644 index 0000000..a108e38 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/backoff-timeout.js.map @@ -0,0 +1 @@ +{"version":3,"file":"backoff-timeout.js","sourceRoot":"","sources":["../../src/backoff-timeout.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,2CAA2C;AAC3C,qCAAqC;AAErC,MAAM,WAAW,GAAG,SAAS,CAAC;AAE9B,MAAM,kBAAkB,GAAG,IAAI,CAAC;AAChC,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAC/B,MAAM,cAAc,GAAG,MAAM,CAAC;AAC9B,MAAM,cAAc,GAAG,GAAG,CAAC;AAE3B;;;;GAIG;AACH,SAAS,aAAa,CAAC,GAAW,EAAE,GAAW;IAC7C,OAAO,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC;AAC3C,CAAC;AASD,MAAa,cAAc;IAoDzB,YAAoB,QAAoB,EAAE,OAAwB;QAA9C,aAAQ,GAAR,QAAQ,CAAY;QAnDxC;;WAEG;QACc,iBAAY,GAAW,kBAAkB,CAAC;QAC3D;;WAEG;QACc,eAAU,GAAW,kBAAkB,CAAC;QACzD;;WAEG;QACc,aAAQ,GAAW,cAAc,CAAC;QACnD;;;W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AM,GAAG,KAAK,CAAC;QACpB,MAAA,MAAA,IAAI,CAAC,OAAO,EAAC,KAAK,kDAAI,CAAC;IACzB,CAAC;IAED;;;OAGG;IACH,UAAU;QACR,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;;AAjLH,wCAkLC;AAhIgB,qBAAM,GAAG,CAAC,AAAJ,CAAK"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/call-credentials.d.ts b/node_modules/@grpc/grpc-js/build/src/call-credentials.d.ts new file mode 100644 index 0000000..ecdb3f9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call-credentials.d.ts @@ -0,0 +1,57 @@ +import { Metadata } from './metadata'; +export interface CallMetadataOptions { + method_name: string; + service_url: string; +} +export type CallMetadataGenerator = (options: CallMetadataOptions, cb: (err: Error | null, metadata?: Metadata) => void) => void; +export interface OldOAuth2Client { + getRequestMetadata: (url: string, callback: (err: Error | null, headers?: { + [index: string]: string; + }) => void) => void; +} +export interface CurrentOAuth2Client { + getRequestHeaders: (url?: string) => Promise<{ + [index: string]: string; + }>; +} +export type OAuth2Client = OldOAuth2Client | CurrentOAuth2Client; +/** + * A class that represents a generic method of adding authentication-related + * metadata on a per-request basis. + */ +export declare abstract class CallCredentials { + /** + * Asynchronously generates a new Metadata object. + * @param options Options used in generating the Metadata object. + */ + abstract generateMetadata(options: CallMetadataOptions): Promise; + /** + * Creates a new CallCredentials object from properties of both this and + * another CallCredentials object. This object's metadata generator will be + * called first. + * @param callCredentials The other CallCredentials object. + */ + abstract compose(callCredentials: CallCredentials): CallCredentials; + /** + * Check whether two call credentials objects are equal. Separate + * SingleCallCredentials with identical metadata generator functions are + * equal. + * @param other The other CallCredentials object to compare with. + */ + abstract _equals(other: CallCredentials): boolean; + /** + * Creates a new CallCredentials object from a given function that generates + * Metadata objects. + * @param metadataGenerator A function that accepts a set of options, and + * generates a Metadata object based on these options, which is passed back + * to the caller via a supplied (err, metadata) callback. + */ + static createFromMetadataGenerator(metadataGenerator: CallMetadataGenerator): CallCredentials; + /** + * Create a gRPC credential from a Google credential object. + * @param googleCredentials The authentication client to use. + * @return The resulting CallCredentials object. + */ + static createFromGoogleCredential(googleCredentials: OAuth2Client): CallCredentials; + static createEmpty(): CallCredentials; +} diff --git a/node_modules/@grpc/grpc-js/build/src/call-credentials.js b/node_modules/@grpc/grpc-js/build/src/call-credentials.js new file mode 100644 index 0000000..67b9266 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call-credentials.js @@ -0,0 +1,153 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CallCredentials = void 0; +const metadata_1 = require("./metadata"); +function isCurrentOauth2Client(client) { + return ('getRequestHeaders' in client && + typeof client.getRequestHeaders === 'function'); +} +/** + * A class that represents a generic method of adding authentication-related + * metadata on a per-request basis. + */ +class CallCredentials { + /** + * Creates a new CallCredentials object from a given function that generates + * Metadata objects. + * @param metadataGenerator A function that accepts a set of options, and + * generates a Metadata object based on these options, which is passed back + * to the caller via a supplied (err, metadata) callback. + */ + static createFromMetadataGenerator(metadataGenerator) { + return new SingleCallCredentials(metadataGenerator); + } + /** + * Create a gRPC credential from a Google credential object. + * @param googleCredentials The authentication client to use. + * @return The resulting CallCredentials object. + */ + static createFromGoogleCredential(googleCredentials) { + return CallCredentials.createFromMetadataGenerator((options, callback) => { + let getHeaders; + if (isCurrentOauth2Client(googleCredentials)) { + getHeaders = googleCredentials.getRequestHeaders(options.service_url); + } + else { + getHeaders = new Promise((resolve, reject) => { + googleCredentials.getRequestMetadata(options.service_url, (err, headers) => { + if (err) { + reject(err); + return; + } + if (!headers) { + reject(new Error('Headers not set by metadata plugin')); + return; + } + resolve(headers); + }); + }); + } + getHeaders.then(headers => { + const metadata = new metadata_1.Metadata(); + for (const key of Object.keys(headers)) { + metadata.add(key, headers[key]); + } + callback(null, metadata); + }, err => { + callback(err); + }); + }); + } + static createEmpty() { + return new EmptyCallCredentials(); + } +} +exports.CallCredentials = CallCredentials; +class ComposedCallCredentials extends CallCredentials { + constructor(creds) { + super(); + this.creds = creds; + } + async generateMetadata(options) { + const base = new metadata_1.Metadata(); + const generated = await Promise.all(this.creds.map(cred => cred.generateMetadata(options))); + for (const gen of generated) { + base.merge(gen); + } + return base; + } + compose(other) { + return new ComposedCallCredentials(this.creds.concat([other])); + } + _equals(other) { + if (this === other) { + return true; + } + if (other instanceof ComposedCallCredentials) { + return this.creds.every((value, index) => value._equals(other.creds[index])); + } + else { + return false; + } + } +} +class SingleCallCredentials extends CallCredentials { + constructor(metadataGenerator) { + super(); + this.metadataGenerator = metadataGenerator; + } + generateMetadata(options) { + return new Promise((resolve, reject) => { + this.metadataGenerator(options, (err, metadata) => { + if (metadata !== undefined) { + resolve(metadata); + } + else { + reject(err); + } + }); + }); + } + compose(other) { + return new ComposedCallCredentials([this, other]); + } + _equals(other) { + if (this === other) { + return true; + } + if (other instanceof SingleCallCredentials) { + return this.metadataGenerator === other.metadataGenerator; + } + else { + return false; + } + } +} +class EmptyCallCredentials extends CallCredentials { + generateMetadata(options) { + return Promise.resolve(new metadata_1.Metadata()); + } + compose(other) { + return other; + } + _equals(other) { + return other instanceof EmptyCallCredentials; + } +} +//# sourceMappingURL=call-credentials.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/call-credentials.js.map b/node_modules/@grpc/grpc-js/build/src/call-credentials.js.map new file mode 100644 index 0000000..71ad1c3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call-credentials.js.map @@ -0,0 +1 @@ +{"version":3,"file":"call-credentials.js","s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IACH,CAAC;CACF;AAED,MAAM,oBAAqB,SAAQ,eAAe;IAChD,gBAAgB,CAAC,OAA4B;QAC3C,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,mBAAQ,EAAE,CAAC,CAAC;IACzC,CAAC;IAED,OAAO,CAAC,KAAsB;QAC5B,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,CAAC,KAAsB;QAC5B,OAAO,KAAK,YAAY,oBAAoB,CAAC;IAC/C,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/call-interface.d.ts b/node_modules/@grpc/grpc-js/build/src/call-interface.d.ts new file mode 100644 index 0000000..c33a3d7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call-interface.d.ts @@ -0,0 +1,101 @@ +import { AuthContext } from './auth-context'; +import { CallCredentials } from './call-credentials'; +import { Status } from './constants'; +import { Deadline } from './deadline'; +import { Metadata } from './metadata'; +import { ServerSurfaceCall } from './server-call'; +export interface CallStreamOptions { + deadline: Deadline; + flags: number; + host: string; + parentCall: ServerSurfaceCall | null; +} +export type PartialCallStreamOptions = Partial; +export interface StatusObject { + code: Status; + details: string; + metadata: Metadata; +} +export type PartialStatusObject = Pick & { + metadata?: Metadata | null | undefined; +}; +export interface StatusOrOk { + ok: true; + value: T; +} +export interface StatusOrError { + ok: false; + error: StatusObject; +} +export type StatusOr = StatusOrOk | StatusOrError; +export declare function statusOrFromValue(value: T): StatusOr; +export declare function statusOrFromError(error: PartialStatusObject): StatusOr; +export declare const enum WriteFlags { + BufferHint = 1, + NoCompress = 2, + WriteThrough = 4 +} +export interface WriteObject { + message: Buffer; + flags?: number; +} +export interface MetadataListener { + (metadata: Metadata, next: (metadata: Metadata) => void): void; +} +export interface MessageListener { + (message: any, next: (message: any) => void): void; +} +export interface StatusListener { + (status: StatusObject, next: (status: StatusObject) => void): void; +} +export interface FullListener { + onReceiveMetadata: MetadataListener; + onReceiveMessage: MessageListener; + onReceiveStatus: StatusListener; +} +export type Listener = Partial; +/** + * An object with methods for handling the responses to a call. + */ +export interface InterceptingListener { + onReceiveMetadata(metadata: Metadata): void; + onReceiveMessage(message: any): void; + onReceiveStatus(status: StatusObject): void; +} +export declare function isInterceptingListener(listener: Listener | InterceptingListener): listener is InterceptingListener; +export declare class InterceptingListenerImpl implements InterceptingListener { + private listener; + private nextListener; + private processingMetadata; + private hasPendingMessage; + private pendingMessage; + private processingMessage; + private pendingStatus; + constructor(listener: FullListener, nextListener: InterceptingListener); + private processPendingMessage; + private processPendingStatus; + onReceiveMetadata(metadata: Metadata): void; + onReceiveMessage(message: any): void; + onReceiveStatus(status: StatusObject): void; +} +export interface WriteCallback { + (error?: Error | null): void; +} +export interface MessageContext { + callback?: WriteCallback; + flags?: number; +} +export interface Call { + cancelWithStatus(status: Status, details: string): void; + getPeer(): string; + start(metadata: Metadata, listener: InterceptingListener): void; + sendMessageWithContext(context: MessageContext, message: Buffer): void; + startRead(): void; + halfClose(): void; + getCallNumber(): number; + setCredentials(credentials: CallCredentials): void; + getAuthContext(): AuthContext | null; +} +export interface DeadlineInfoProvider { + getDeadlineInfo(): string[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/call-interface.js b/node_modules/@grpc/grpc-js/build/src/call-interface.js new file mode 100644 index 0000000..88abb51 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call-interface.js @@ -0,0 +1,100 @@ +"use strict"; +/* + * Copyright 2022 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InterceptingListenerImpl = void 0; +exports.statusOrFromValue = statusOrFromValue; +exports.statusOrFromError = statusOrFromError; +exports.isInterceptingListener = isInterceptingListener; +const metadata_1 = require("./metadata"); +function statusOrFromValue(value) { + return { + ok: true, + value: value + }; +} +function statusOrFromError(error) { + var _a; + return { + ok: false, + error: Object.assign(Object.assign({}, error), { metadata: (_a = error.metadata) !== null && _a !== void 0 ? _a : new metadata_1.Metadata() }) + }; +} +function isInterceptingListener(listener) { + return (listener.onReceiveMetadata !== undefined && + listener.onReceiveMetadata.length === 1); +} +class InterceptingListenerImpl { + constructor(listener, nextListener) { + this.listener = listener; + this.nextListener = nextListener; + this.processingMetadata = false; + this.hasPendingMessage = false; + this.processingMessage = false; + this.pendingStatus = null; + } + processPendingMessage() { + if (this.hasPendingMessage) { + this.nextListener.onReceiveMessage(this.pendingMessage); + this.pendingMessage = null; + this.hasPendingMessage = false; + } + } + processPendingStatus() { + if (this.pendingStatus) { + this.nextListener.onReceiveStatus(this.pendingStatus); + } + } + onReceiveMetadata(metadata) { + this.processingMetadata = true; + this.listener.onReceiveMetadata(metadata, metadata => { + this.processingMetadata = false; + this.nextListener.onReceiveMetadata(metadata); + this.processPendingMessage(); + this.processPendingStatus(); + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message) { + /* If this listener processes messages asynchronously, the last message may + * be reordered with respect to the status */ + this.processingMessage = true; + this.listener.onReceiveMessage(message, msg => { + this.processingMessage = false; + if (this.processingMetadata) { + this.pendingMessage = msg; + this.hasPendingMessage = true; + } + else { + this.nextListener.onReceiveMessage(msg); + this.processPendingStatus(); + } + }); + } + onReceiveStatus(status) { + this.listener.onReceiveStatus(status, processedStatus => { + if (this.processingMetadata || this.processingMessage) { + this.pendingStatus = processedStatus; + } + else { + this.nextListener.onReceiveStatus(processedStatus); + } + }); + } +} +exports.InterceptingListenerImpl = InterceptingListenerImpl; +//# sourceMappingURL=call-interface.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/call-interface.js.map b/node_modules/@grpc/grpc-js/build/src/call-interface.js.map new file mode 100644 index 0000000..ccf8fdd --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call-interface.js.map @@ -0,0 +1 @@ +{"version":3,"file":"call-interface.js","sourceRoot":"","sources":["../../src/call-interface.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAwCH,8CAKC;AAED,8CAQC;AA4CD,wDAOC;AApGD,yCAAsC;AAkCtC,SAAgB,iBAAiB,CAAI,KAAQ;IAC3C,OAAO;QACL,EAAE,EAAE,IAAI;QACR,KAAK,EAAE,KAAK;KACb,CAAC;AACJ,CAAC;AAED,SAAgB,iBAAiB,CAAI,KAA0B;;IAC7D,OAAO;QACL,EAAE,EAAE,KAAK;QACT,KAAK,kCACA,KAAK,KACR,QAAQ,EAAE,MAAA,KAAK,CAAC,QAAQ,mCAAI,IAAI,mBAAQ,EAAE,GAC3C;KACF,CAAC;AACJ,CAAC;AA4CD,SAAgB,sBAAsB,CACpC,QAAyC;IAEzC,OAAO,CACL,QAAQ,CAAC,iBAAiB,KAAK,SAAS;QACxC,QAAQ,CAAC,iBAAiB,CAAC,MAAM,KAAK,CAAC,CACxC,CAAC;AACJ,CAAC;AAED,MAAa,wBAAwB;IAMnC,YACU,QAAsB,EACtB,YAAkC;QADlC,aAAQ,GAAR,QAAQ,CAAc;QACtB,iBAAY,GAAZ,YAAY,CAAsB;QAPpC,uBAAkB,GAAG,KAAK,CAAC;QAC3B,sBAAiB,GAAG,KAAK,CAAC;QAE1B,sBAAiB,GAAG,KAAK,CAAC;QAC1B,kBAAa,GAAwB,IAAI,CAAC;IAI/C,CAAC;IAEI,qBAAqB;QAC3B,IAAI,IAAI,CAAC,iBAAiB,EAAE,CAAC;YAC3B,IAAI,CAAC,YAAY,CAAC,gBAAgB,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;YACxD,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;YAC3B,IAAI,CAAC,iBAAiB,GAAG,KAAK,CAAC;QACjC,CAAC;IACH,CAAC;IAEO,o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IAAI,CAAC,aAAa,GAAG,eAAe,CAAC;YACvC,CAAC;iBAAM,CAAC;gBACN,IAAI,CAAC,YAAY,CAAC,eAAe,CAAC,eAAe,CAAC,CAAC;YACrD,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA3DD,4DA2DC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/call-number.d.ts b/node_modules/@grpc/grpc-js/build/src/call-number.d.ts new file mode 100644 index 0000000..a679ff6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call-number.d.ts @@ -0,0 +1 @@ +export declare function getNextCallNumber(): number; diff --git a/node_modules/@grpc/grpc-js/build/src/call-number.js b/node_modules/@grpc/grpc-js/build/src/call-number.js new file mode 100644 index 0000000..ed8bcdf --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call-number.js @@ -0,0 +1,24 @@ +"use strict"; +/* + * Copyright 2022 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getNextCallNumber = getNextCallNumber; +let nextCallNumber = 0; +function getNextCallNumber() { + return nextCallNumber++; +} +//# sourceMappingURL=call-number.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/call-number.js.map b/node_modules/@grpc/grpc-js/build/src/call-number.js.map new file mode 100644 index 0000000..7d3a9ae --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call-number.js.map @@ -0,0 +1 @@ +{"version":3,"file":"call-number.js","sourceRoot":"","sources":["../../src/call-number.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAIH,8CAEC;AAJD,IAAI,cAAc,GAAG,CAAC,CAAC;AAEvB,SAAgB,iBAAiB;IAC/B,OAAO,cAAc,EAAE,CAAC;AAC1B,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/call.d.ts b/node_modules/@grpc/grpc-js/build/src/call.d.ts new file mode 100644 index 0000000..7fac22a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call.d.ts @@ -0,0 +1,86 @@ +import { EventEmitter } from 'events'; +import { Duplex, Readable, Writable } from 'stream'; +import { StatusObject } from './call-interface'; +import { EmitterAugmentation1 } from './events'; +import { Metadata } from './metadata'; +import { ObjectReadable, ObjectWritable, WriteCallback } from './object-stream'; +import { InterceptingCallInterface } from './client-interceptors'; +import { AuthContext } from './auth-context'; +/** + * A type extending the built-in Error object with additional fields. + */ +export type ServiceError = StatusObject & Error; +/** + * A base type for all user-facing values returned by client-side method calls. + */ +export type SurfaceCall = { + call?: InterceptingCallInterface; + cancel(): void; + getPeer(): string; + getAuthContext(): AuthContext | null; +} & EmitterAugmentation1<'metadata', Metadata> & EmitterAugmentation1<'status', StatusObject> & EventEmitter; +/** + * A type representing the return value of a unary method call. + */ +export type ClientUnaryCall = SurfaceCall; +/** + * A type representing the return value of a server stream method call. + */ +export type ClientReadableStream = { + deserialize: (chunk: Buffer) => ResponseType; +} & SurfaceCall & ObjectReadable; +/** + * A type representing the return value of a client stream method call. + */ +export type ClientWritableStream = { + serialize: (value: RequestType) => Buffer; +} & SurfaceCall & ObjectWritable; +/** + * A type representing the return value of a bidirectional stream method call. + */ +export type ClientDuplexStream = ClientWritableStream & ClientReadableStream; +/** + * Construct a ServiceError from a StatusObject. This function exists primarily + * as an attempt to make the error stack trace clearly communicate that the + * error is not necessarily a problem in gRPC itself. + * @param status + */ +export declare function callErrorFromStatus(status: StatusObject, callerStack: string): ServiceError; +export declare class ClientUnaryCallImpl extends EventEmitter implements ClientUnaryCall { + call?: InterceptingCallInterface; + constructor(); + cancel(): void; + getPeer(): string; + getAuthContext(): AuthContext | null; +} +export declare class ClientReadableStreamImpl extends Readable implements ClientReadableStream { + readonly deserialize: (chunk: Buffer) => ResponseType; + call?: InterceptingCallInterface; + constructor(deserialize: (chunk: Buffer) => ResponseType); + cancel(): void; + getPeer(): string; + getAuthContext(): AuthContext | null; + _read(_size: number): void; +} +export declare class ClientWritableStreamImpl extends Writable implements ClientWritableStream { + readonly serialize: (value: RequestType) => Buffer; + call?: InterceptingCallInterface; + constructor(serialize: (value: RequestType) => Buffer); + cancel(): void; + getPeer(): string; + getAuthContext(): AuthContext | null; + _write(chunk: RequestType, encoding: string, cb: WriteCallback): void; + _final(cb: Function): void; +} +export declare class ClientDuplexStreamImpl extends Duplex implements ClientDuplexStream { + readonly serialize: (value: RequestType) => Buffer; + readonly deserialize: (chunk: Buffer) => ResponseType; + call?: InterceptingCallInterface; + constructor(serialize: (value: RequestType) => Buffer, deserialize: (chunk: Buffer) => ResponseType); + cancel(): void; + getPeer(): string; + getAuthContext(): AuthContext | null; + _read(_size: number): void; + _write(chunk: RequestType, encoding: string, cb: WriteCallback): void; + _final(cb: Function): void; +} diff --git a/node_modules/@grpc/grpc-js/build/src/call.js b/node_modules/@grpc/grpc-js/build/src/call.js new file mode 100644 index 0000000..ff6d179 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call.js @@ -0,0 +1,152 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ClientDuplexStreamImpl = exports.ClientWritableStreamImpl = exports.ClientReadableStreamImpl = exports.ClientUnaryCallImpl = void 0; +exports.callErrorFromStatus = callErrorFromStatus; +const events_1 = require("events"); +const stream_1 = require("stream"); +const constants_1 = require("./constants"); +/** + * Construct a ServiceError from a StatusObject. This function exists primarily + * as an attempt to make the error stack trace clearly communicate that the + * error is not necessarily a problem in gRPC itself. + * @param status + */ +function callErrorFromStatus(status, callerStack) { + const message = `${status.code} ${constants_1.Status[status.code]}: ${status.details}`; + const error = new Error(message); + const stack = `${error.stack}\nfor call at\n${callerStack}`; + return Object.assign(new Error(message), status, { stack }); +} +class ClientUnaryCallImpl extends events_1.EventEmitter { + constructor() { + super(); + } + cancel() { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client'); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown'; + } + getAuthContext() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; + } +} +exports.ClientUnaryCallImpl = ClientUnaryCallImpl; +class ClientReadableStreamImpl extends stream_1.Readable { + constructor(deserialize) { + super({ objectMode: true }); + this.deserialize = deserialize; + } + cancel() { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client'); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown'; + } + getAuthContext() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; + } + _read(_size) { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.startRead(); + } +} +exports.ClientReadableStreamImpl = ClientReadableStreamImpl; +class ClientWritableStreamImpl extends stream_1.Writable { + constructor(serialize) { + super({ objectMode: true }); + this.serialize = serialize; + } + cancel() { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client'); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown'; + } + getAuthContext() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; + } + _write(chunk, encoding, cb) { + var _a; + const context = { + callback: cb, + }; + const flags = Number(encoding); + if (!Number.isNaN(flags)) { + context.flags = flags; + } + (_a = this.call) === null || _a === void 0 ? void 0 : _a.sendMessageWithContext(context, chunk); + } + _final(cb) { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.halfClose(); + cb(); + } +} +exports.ClientWritableStreamImpl = ClientWritableStreamImpl; +class ClientDuplexStreamImpl extends stream_1.Duplex { + constructor(serialize, deserialize) { + super({ objectMode: true }); + this.serialize = serialize; + this.deserialize = deserialize; + } + cancel() { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client'); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown'; + } + getAuthContext() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; + } + _read(_size) { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.startRead(); + } + _write(chunk, encoding, cb) { + var _a; + const context = { + callback: cb, + }; + const flags = Number(encoding); + if (!Number.isNaN(flags)) { + context.flags = flags; + } + (_a = this.call) === null || _a === void 0 ? void 0 : _a.sendMessageWithContext(context, chunk); + } + _final(cb) { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.halfClose(); + cb(); + } +} +exports.ClientDuplexStreamImpl = ClientDuplexStreamImpl; +//# sourceMappingURL=call.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/call.js.map b/node_modules/@grpc/grpc-js/build/src/call.js.map new file mode 100644 index 0000000..0b0689d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call.js.map @@ -0,0 +1 @@ +{"version":3,"file":"call.js","sourceRoot":"","sources":["../../src/call.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AA+DH,kDAQC;AArED,mCAAsC;AACtC,mCAAoD;AAGpD,2CAAqC;AAmDrC;;;;;GAKG;AACH,SAAgB,mBAAmB,CACjC,MAAoB,EACpB,WAAmB;IAEnB,MAAM,OAAO,GAAG,GAAG,MAAM,CAAC,IAAI,IAAI,kBAAM,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,MAAM,CAAC,OAAO,EAAE,CAAC;IAC3E,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;IACjC,MAAM,KAAK,GAAG,GAAG,KAAK,CAAC,KAAK,kBAAkB,WAAW,EAAE,CAAC;IAC5D,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;AAC9D,CAAC;AAED,MAAa,mBACX,SAAQ,qBAAY;IAIpB;QACE,KAAK,EAAE,CAAC;IACV,CAAC;IAED,MAAM;;QACJ,MAAA,IAAI,CAAC,IAAI,0CAAE,gBAAgB,CAAC,kBAAM,CAAC,SAAS,EAAE,qBAAqB,CAAC,CAAC;IACvE,CAAC;IAED,OAAO;;QACL,OAAO,MAAA,MAAA,IAAI,CAAC,IAAI,0CAAE,OAAO,EAAE,mCAAI,SAAS,CAAC;IAC3C,CAAC;IAED,cAAc;;QACZ,OAAO,MAAA,MAAA,IAAI,CAAC,IAAI,0CAAE,cAAc,EAAE,mCAAI,IAAI,CAAC;IAC7C,CAAC;CACF;AApBD,kDAoBC;AAED,MAAa,wBACX,SAAQ,iBAAQ;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AAG,KAAK,CAAC;QACxB,CAAC;QACD,MAAA,IAAI,CAAC,IAAI,0CAAE,sBAAsB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IACpD,CAAC;IAED,MAAM,CAAC,EAAY;;QACjB,MAAA,IAAI,CAAC,IAAI,0CAAE,SAAS,EAAE,CAAC;QACvB,EAAE,EAAE,CAAC;IACP,CAAC;CACF;AA3CD,wDA2CC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/certificate-provider.d.ts b/node_modules/@grpc/grpc-js/build/src/certificate-provider.d.ts new file mode 100644 index 0000000..d0ddf3e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/certificate-provider.d.ts @@ -0,0 +1,43 @@ +export interface CaCertificateUpdate { + caCertificate: Buffer; +} +export interface IdentityCertificateUpdate { + certificate: Buffer; + privateKey: Buffer; +} +export interface CaCertificateUpdateListener { + (update: CaCertificateUpdate | null): void; +} +export interface IdentityCertificateUpdateListener { + (update: IdentityCertificateUpdate | null): void; +} +export interface CertificateProvider { + addCaCertificateListener(listener: CaCertificateUpdateListener): void; + removeCaCertificateListener(listener: CaCertificateUpdateListener): void; + addIdentityCertificateListener(listener: IdentityCertificateUpdateListener): void; + removeIdentityCertificateListener(listener: IdentityCertificateUpdateListener): void; +} +export interface FileWatcherCertificateProviderConfig { + certificateFile?: string | undefined; + privateKeyFile?: string | undefined; + caCertificateFile?: string | undefined; + refreshIntervalMs: number; +} +export declare class FileWatcherCertificateProvider implements CertificateProvider { + private config; + private refreshTimer; + private fileResultPromise; + private latestCaUpdate; + private caListeners; + private latestIdentityUpdate; + private identityListeners; + private lastUpdateTime; + constructor(config: FileWatcherCertificateProviderConfig); + private updateCertificates; + private maybeStartWatchingFiles; + private maybeStopWatchingFiles; + addCaCertificateListener(listener: CaCertificateUpdateListener): void; + removeCaCertificateListener(listener: CaCertificateUpdateListener): void; + addIdentityCertificateListener(listener: IdentityCertificateUpdateListener): void; + removeIdentityCertificateListener(listener: IdentityCertificateUpdateListener): void; +} diff --git a/node_modules/@grpc/grpc-js/build/src/certificate-provider.js b/node_modules/@grpc/grpc-js/build/src/certificate-provider.js new file mode 100644 index 0000000..75cd0f8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/certificate-provider.js @@ -0,0 +1,141 @@ +"use strict"; +/* + * Copyright 2024 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FileWatcherCertificateProvider = void 0; +const fs = require("fs"); +const logging = require("./logging"); +const constants_1 = require("./constants"); +const util_1 = require("util"); +const TRACER_NAME = 'certificate_provider'; +function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); +} +const readFilePromise = (0, util_1.promisify)(fs.readFile); +class FileWatcherCertificateProvider { + constructor(config) { + this.config = config; + this.refreshTimer = null; + this.fileResultPromise = null; + this.latestCaUpdate = undefined; + this.caListeners = new Set(); + this.latestIdentityUpdate = undefined; + this.identityListeners = new Set(); + this.lastUpdateTime = null; + if ((config.certificateFile === undefined) !== (config.privateKeyFile === undefined)) { + throw new Error('certificateFile and privateKeyFile must be set or unset together'); + } + if (config.certificateFile === undefined && config.caCertificateFile === undefined) { + throw new Error('At least one of certificateFile and caCertificateFile must be set'); + } + trace('File watcher constructed with config ' + JSON.stringify(config)); + } + updateCertificates() { + if (this.fileResultPromise) { + return; + } + this.fileResultPromise = Promise.allSettled([ + this.config.certificateFile ? readFilePromise(this.config.certificateFile) : Promise.reject(), + this.config.privateKeyFile ? readFilePromise(this.config.privateKeyFile) : Promise.reject(), + this.config.caCertificateFile ? readFilePromise(this.config.caCertificateFile) : Promise.reject() + ]); + this.fileResultPromise.then(([certificateResult, privateKeyResult, caCertificateResult]) => { + if (!this.refreshTimer) { + return; + } + trace('File watcher read certificates certificate ' + certificateResult.status + ', privateKey ' + privateKeyResult.status + ', CA certificate ' + caCertificateResult.status); + this.lastUpdateTime = new Date(); + this.fileResultPromise = null; + if (certificateResult.status === 'fulfilled' && privateKeyResult.status === 'fulfilled') { + this.latestIdentityUpdate = { + certificate: certificateResult.value, + privateKey: privateKeyResult.value + }; + } + else { + this.latestIdentityUpdate = null; + } + if (caCertificateResult.status === 'fulfilled') { + this.latestCaUpdate = { + caCertificate: caCertificateResult.value + }; + } + else { + this.latestCaUpdate = null; + } + for (const listener of this.identityListeners) { + listener(this.latestIdentityUpdate); + } + for (const listener of this.caListeners) { + listener(this.latestCaUpdate); + } + }); + trace('File watcher initiated certificate update'); + } + maybeStartWatchingFiles() { + if (!this.refreshTimer) { + /* Perform the first read immediately, but only if there was not already + * a recent read, to avoid reading from the filesystem significantly more + * frequently than configured if the provider quickly switches between + * used and unused. */ + const timeSinceLastUpdate = this.lastUpdateTime ? (new Date()).getTime() - this.lastUpdateTime.getTime() : Infinity; + if (timeSinceLastUpdate > this.config.refreshIntervalMs) { + this.updateCertificates(); + } + if (timeSinceLastUpdate > this.config.refreshIntervalMs * 2) { + // Clear out old updates if they are definitely stale + this.latestCaUpdate = undefined; + this.latestIdentityUpdate = undefined; + } + this.refreshTimer = setInterval(() => this.updateCertificates(), this.config.refreshIntervalMs); + trace('File watcher started watching'); + } + } + maybeStopWatchingFiles() { + if (this.caListeners.size === 0 && this.identityListeners.size === 0) { + this.fileResultPromise = null; + if (this.refreshTimer) { + clearInterval(this.refreshTimer); + this.refreshTimer = null; + } + } + } + addCaCertificateListener(listener) { + this.caListeners.add(listener); + this.maybeStartWatchingFiles(); + if (this.latestCaUpdate !== undefined) { + process.nextTick(listener, this.latestCaUpdate); + } + } + removeCaCertificateListener(listener) { + this.caListeners.delete(listener); + this.maybeStopWatchingFiles(); + } + addIdentityCertificateListener(listener) { + this.identityListeners.add(listener); + this.maybeStartWatchingFiles(); + if (this.latestIdentityUpdate !== undefined) { + process.nextTick(listener, this.latestIdentityUpdate); + } + } + removeIdentityCertificateListener(listener) { + this.identityListeners.delete(listener); + this.maybeStopWatchingFiles(); + } +} +exports.FileWatcherCertificateProvider = FileWatcherCertificateProvider; +//# sourceMappingURL=certificate-provider.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/certificate-provider.js.map b/node_modules/@grpc/grpc-js/build/src/certificate-provider.js.map new file mode 100644 index 0000000..390b450 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/certificate-provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"certificate-provider.js","sourceRoot":"","sources":["../../src/certificate-provider.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,yBAAyB;AACzB,qCAAqC;AACrC,2CAA2C;AAC3C,+BAAiC;AAEjC,MAAM,WAAW,GAAG,sBAAsB,CAAC;AAE3C,SAAS,KAAK,CAAC,IAAY;IACzB,OAAO,CAAC,KAAK,CAAC,wBAAY,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;AACvD,CAAC;AAiCD,MAAM,eAAe,GAAG,IAAA,gBAAS,EAAC,EAAE,CAAC,QAAQ,CAAC,CAAC;AAE/C,MAAa,8BAA8B;IASzC,YACU,MAA4C;QAA5C,WAAM,GAAN,MAAM,CAAsC;QAT9C,iBAAY,GAA0B,IAAI,CAAC;QAC3C,sBAAiB,GAA+G,IAAI,CAAC;QACrI,mBAAc,GAA2C,SAAS,CAAC;QACnE,gBAAW,GAAqC,IAAI,GAAG,EAAE,CAAC;QAC1D,yBAAoB,GAAiD,SAAS,CAAC;QAC/E,sBAAiB,GAA2C,IAAI,GAAG,EAAE,CAAC;QACtE,mBAAc,GAAgB,IAAI,CAAC;QAKzC,IAAI,CAAC,MAAM,CAAC,eAAe,KAAK,SAAS,CAAC,KAAK,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,WAAW,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QAClC,IAAI,CAAC,sBAAsB,EAAE,CAAC;IAChC,CAAC;IACD,8BAA8B,CAAC,QAA2C;QACxE,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QACrC,IAAI,CAAC,uBAAuB,EAAE,CAAC;QAC/B,IAAI,IAAI,CAAC,oBAAoB,KAAK,SAAS,EAAE,CAAC;YAC5C,OAAO,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,oBAAoB,CAAC,CAAC;QACxD,CAAC;IACH,CAAC;IACD,iCAAiC,CAAC,QAA2C;QAC3E,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QACxC,IAAI,CAAC,sBAAsB,EAAE,CAAC;IAChC,CAAC;CACF;AAlHD,wEAkHC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/channel-credentials.d.ts b/node_modules/@grpc/grpc-js/build/src/channel-credentials.d.ts new file mode 100644 index 0000000..3935757 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channel-credentials.d.ts @@ -0,0 +1,119 @@ +import { PeerCertificate, SecureContext } from 'tls'; +import { CallCredentials } from './call-credentials'; +import { CertificateProvider } from './certificate-provider'; +import { Socket } from 'net'; +import { ChannelOptions } from './channel-options'; +import { GrpcUri } from './uri-parser'; +/** + * A callback that will receive the expected hostname and presented peer + * certificate as parameters. The callback should return an error to + * indicate that the presented certificate is considered invalid and + * otherwise returned undefined. + */ +export type CheckServerIdentityCallback = (hostname: string, cert: PeerCertificate) => Error | undefined; +/** + * Additional peer verification options that can be set when creating + * SSL credentials. + */ +export interface VerifyOptions { + /** + * If set, this callback will be invoked after the usual hostname verification + * has been performed on the peer certificate. + */ + checkServerIdentity?: CheckServerIdentityCallback; + rejectUnauthorized?: boolean; +} +export interface SecureConnectResult { + socket: Socket; + secure: boolean; +} +export interface SecureConnector { + connect(socket: Socket): Promise; + waitForReady(): Promise; + getCallCredentials(): CallCredentials; + destroy(): void; +} +/** + * A class that contains credentials for communicating over a channel, as well + * as a set of per-call credentials, which are applied to every method call made + * over a channel initialized with an instance of this class. + */ +export declare abstract class ChannelCredentials { + /** + * Returns a copy of this object with the included set of per-call credentials + * expanded to include callCredentials. + * @param callCredentials A CallCredentials object to associate with this + * instance. + */ + compose(callCredentials: CallCredentials): ChannelCredentials; + /** + * Indicates whether this credentials object creates a secure channel. + */ + abstract _isSecure(): boolean; + /** + * Check whether two channel credentials objects are equal. Two secure + * credentials are equal if they were constructed with the same parameters. + * @param other The other ChannelCredentials Object + */ + abstract _equals(other: ChannelCredentials): boolean; + abstract _createSecureConnector(channelTarget: GrpcUri, options: ChannelOptions, callCredentials?: CallCredentials): SecureConnector; + /** + * Return a new ChannelCredentials instance with a given set of credentials. + * The resulting instance can be used to construct a Channel that communicates + * over TLS. + * @param rootCerts The root certificate data. + * @param privateKey The client certificate private key, if available. + * @param certChain The client certificate key chain, if available. + * @param verifyOptions Additional options to modify certificate verification + */ + static createSsl(rootCerts?: Buffer | null, privateKey?: Buffer | null, certChain?: Buffer | null, verifyOptions?: VerifyOptions): ChannelCredentials; + /** + * Return a new ChannelCredentials instance with credentials created using + * the provided secureContext. The resulting instances can be used to + * construct a Channel that communicates over TLS. gRPC will not override + * anything in the provided secureContext, so the environment variables + * GRPC_SSL_CIPHER_SUITES and GRPC_DEFAULT_SSL_ROOTS_FILE_PATH will + * not be applied. + * @param secureContext The return value of tls.createSecureContext() + * @param verifyOptions Additional options to modify certificate verification + */ + static createFromSecureContext(secureContext: SecureContext, verifyOptions?: VerifyOptions): ChannelCredentials; + /** + * Return a new ChannelCredentials instance with no credentials. + */ + static createInsecure(): ChannelCredentials; +} +declare class CertificateProviderChannelCredentialsImpl extends ChannelCredentials { + private caCertificateProvider; + private identityCertificateProvider; + private verifyOptions; + private refcount; + /** + * `undefined` means that the certificates have not yet been loaded. `null` + * means that an attempt to load them has completed, and has failed. + */ + private latestCaUpdate; + /** + * `undefined` means that the certificates have not yet been loaded. `null` + * means that an attempt to load them has completed, and has failed. + */ + private latestIdentityUpdate; + private caCertificateUpdateListener; + private identityCertificateUpdateListener; + private secureContextWatchers; + private static SecureConnectorImpl; + constructor(caCertificateProvider: CertificateProvider, identityCertificateProvider: CertificateProvider | null, verifyOptions: VerifyOptions); + _isSecure(): boolean; + _equals(other: ChannelCredentials): boolean; + private ref; + private unref; + _createSecureConnector(channelTarget: GrpcUri, options: ChannelOptions, callCredentials?: CallCredentials): SecureConnector; + private maybeUpdateWatchers; + private handleCaCertificateUpdate; + private handleIdentityCertitificateUpdate; + private hasReceivedUpdates; + private getSecureContext; + private getLatestSecureContext; +} +export declare function createCertificateProviderChannelCredentials(caCertificateProvider: CertificateProvider, identityCertificateProvider: CertificateProvider | null, verifyOptions?: VerifyOptions): CertificateProviderChannelCredentialsImpl; +export {}; diff --git a/node_modules/@grpc/grpc-js/build/src/channel-credentials.js b/node_modules/@grpc/grpc-js/build/src/channel-credentials.js new file mode 100644 index 0000000..9be5ea3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channel-credentials.js @@ -0,0 +1,430 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChannelCredentials = void 0; +exports.createCertificateProviderChannelCredentials = createCertificateProviderChannelCredentials; +const tls_1 = require("tls"); +const call_credentials_1 = require("./call-credentials"); +const tls_helpers_1 = require("./tls-helpers"); +const uri_parser_1 = require("./uri-parser"); +const resolver_1 = require("./resolver"); +const logging_1 = require("./logging"); +const constants_1 = require("./constants"); +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function verifyIsBufferOrNull(obj, friendlyName) { + if (obj && !(obj instanceof Buffer)) { + throw new TypeError(`${friendlyName}, if provided, must be a Buffer.`); + } +} +/** + * A class that contains credentials for communicating over a channel, as well + * as a set of per-call credentials, which are applied to every method call made + * over a channel initialized with an instance of this class. + */ +class ChannelCredentials { + /** + * Returns a copy of this object with the included set of per-call credentials + * expanded to include callCredentials. + * @param callCredentials A CallCredentials object to associate with this + * instance. + */ + compose(callCredentials) { + return new ComposedChannelCredentialsImpl(this, callCredentials); + } + /** + * Return a new ChannelCredentials instance with a given set of credentials. + * The resulting instance can be used to construct a Channel that communicates + * over TLS. + * @param rootCerts The root certificate data. + * @param privateKey The client certificate private key, if available. + * @param certChain The client certificate key chain, if available. + * @param verifyOptions Additional options to modify certificate verification + */ + static createSsl(rootCerts, privateKey, certChain, verifyOptions) { + var _a; + verifyIsBufferOrNull(rootCerts, 'Root certificate'); + verifyIsBufferOrNull(privateKey, 'Private key'); + verifyIsBufferOrNull(certChain, 'Certificate chain'); + if (privateKey && !certChain) { + throw new Error('Private key must be given with accompanying certificate chain'); + } + if (!privateKey && certChain) { + throw new Error('Certificate chain must be given with accompanying private key'); + } + const secureContext = (0, tls_1.createSecureContext)({ + ca: (_a = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a !== void 0 ? _a : undefined, + key: privateKey !== null && privateKey !== void 0 ? privateKey : undefined, + cert: certChain !== null && certChain !== void 0 ? certChain : undefined, + ciphers: tls_helpers_1.CIPHER_SUITES, + }); + return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {}); + } + /** + * Return a new ChannelCredentials instance with credentials created using + * the provided secureContext. The resulting instances can be used to + * construct a Channel that communicates over TLS. gRPC will not override + * anything in the provided secureContext, so the environment variables + * GRPC_SSL_CIPHER_SUITES and GRPC_DEFAULT_SSL_ROOTS_FILE_PATH will + * not be applied. + * @param secureContext The return value of tls.createSecureContext() + * @param verifyOptions Additional options to modify certificate verification + */ + static createFromSecureContext(secureContext, verifyOptions) { + return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {}); + } + /** + * Return a new ChannelCredentials instance with no credentials. + */ + static createInsecure() { + return new InsecureChannelCredentialsImpl(); + } +} +exports.ChannelCredentials = ChannelCredentials; +class InsecureChannelCredentialsImpl extends ChannelCredentials { + constructor() { + super(); + } + compose(callCredentials) { + throw new Error('Cannot compose insecure credentials'); + } + _isSecure() { + return false; + } + _equals(other) { + return other instanceof InsecureChannelCredentialsImpl; + } + _createSecureConnector(channelTarget, options, callCredentials) { + return { + connect(socket) { + return Promise.resolve({ + socket, + secure: false + }); + }, + waitForReady: () => { + return Promise.resolve(); + }, + getCallCredentials: () => { + return callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty(); + }, + destroy() { } + }; + } +} +function getConnectionOptions(secureContext, verifyOptions, channelTarget, options) { + var _a, _b; + const connectionOptions = { + secureContext: secureContext + }; + let realTarget = channelTarget; + if ('grpc.http_connect_target' in options) { + const parsedTarget = (0, uri_parser_1.parseUri)(options['grpc.http_connect_target']); + if (parsedTarget) { + realTarget = parsedTarget; + } + } + const targetPath = (0, resolver_1.getDefaultAuthority)(realTarget); + const hostPort = (0, uri_parser_1.splitHostPort)(targetPath); + const remoteHost = (_a = hostPort === null || hostPort === void 0 ? void 0 : hostPort.host) !== null && _a !== void 0 ? _a : targetPath; + connectionOptions.host = remoteHost; + if (verifyOptions.checkServerIdentity) { + connectionOptions.checkServerIdentity = verifyOptions.checkServerIdentity; + } + if (verifyOptions.rejectUnauthorized !== undefined) { + connectionOptions.rejectUnauthorized = verifyOptions.rejectUnauthorized; + } + connectionOptions.ALPNProtocols = ['h2']; + if (options['grpc.ssl_target_name_override']) { + const sslTargetNameOverride = options['grpc.ssl_target_name_override']; + const originalCheckServerIdentity = (_b = connectionOptions.checkServerIdentity) !== null && _b !== void 0 ? _b : tls_1.checkServerIdentity; + connectionOptions.checkServerIdentity = (host, cert) => { + return originalCheckServerIdentity(sslTargetNameOverride, cert); + }; + connectionOptions.servername = sslTargetNameOverride; + } + else { + connectionOptions.servername = remoteHost; + } + if (options['grpc-node.tls_enable_trace']) { + connectionOptions.enableTrace = true; + } + return connectionOptions; +} +class SecureConnectorImpl { + constructor(connectionOptions, callCredentials) { + this.connectionOptions = connectionOptions; + this.callCredentials = callCredentials; + } + connect(socket) { + const tlsConnectOptions = Object.assign({ socket: socket }, this.connectionOptions); + return new Promise((resolve, reject) => { + const tlsSocket = (0, tls_1.connect)(tlsConnectOptions, () => { + var _a; + if (((_a = this.connectionOptions.rejectUnauthorized) !== null && _a !== void 0 ? _a : true) && !tlsSocket.authorized) { + reject(tlsSocket.authorizationError); + return; + } + resolve({ + socket: tlsSocket, + secure: true + }); + }); + tlsSocket.on('error', (error) => { + reject(error); + }); + }); + } + waitForReady() { + return Promise.resolve(); + } + getCallCredentials() { + return this.callCredentials; + } + destroy() { } +} +class SecureChannelCredentialsImpl extends ChannelCredentials { + constructor(secureContext, verifyOptions) { + super(); + this.secureContext = secureContext; + this.verifyOptions = verifyOptions; + } + _isSecure() { + return true; + } + _equals(other) { + if (this === other) { + return true; + } + if (other instanceof SecureChannelCredentialsImpl) { + return (this.secureContext === other.secureContext && + this.verifyOptions.checkServerIdentity === + other.verifyOptions.checkServerIdentity); + } + else { + return false; + } + } + _createSecureConnector(channelTarget, options, callCredentials) { + const connectionOptions = getConnectionOptions(this.secureContext, this.verifyOptions, channelTarget, options); + return new SecureConnectorImpl(connectionOptions, callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); + } +} +class CertificateProviderChannelCredentialsImpl extends ChannelCredentials { + constructor(caCertificateProvider, identityCertificateProvider, verifyOptions) { + super(); + this.caCertificateProvider = caCertificateProvider; + this.identityCertificateProvider = identityCertificateProvider; + this.verifyOptions = verifyOptions; + this.refcount = 0; + /** + * `undefined` means that the certificates have not yet been loaded. `null` + * means that an attempt to load them has completed, and has failed. + */ + this.latestCaUpdate = undefined; + /** + * `undefined` means that the certificates have not yet been loaded. `null` + * means that an attempt to load them has completed, and has failed. + */ + this.latestIdentityUpdate = undefined; + this.caCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this); + this.identityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this); + this.secureContextWatchers = []; + } + _isSecure() { + return true; + } + _equals(other) { + var _a, _b; + if (this === other) { + return true; + } + if (other instanceof CertificateProviderChannelCredentialsImpl) { + return this.caCertificateProvider === other.caCertificateProvider && + this.identityCertificateProvider === other.identityCertificateProvider && + ((_a = this.verifyOptions) === null || _a === void 0 ? void 0 : _a.checkServerIdentity) === ((_b = other.verifyOptions) === null || _b === void 0 ? void 0 : _b.checkServerIdentity); + } + else { + return false; + } + } + ref() { + var _a; + if (this.refcount === 0) { + this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener); + (_a = this.identityCertificateProvider) === null || _a === void 0 ? void 0 : _a.addIdentityCertificateListener(this.identityCertificateUpdateListener); + } + this.refcount += 1; + } + unref() { + var _a; + this.refcount -= 1; + if (this.refcount === 0) { + this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener); + (_a = this.identityCertificateProvider) === null || _a === void 0 ? void 0 : _a.removeIdentityCertificateListener(this.identityCertificateUpdateListener); + } + } + _createSecureConnector(channelTarget, options, callCredentials) { + this.ref(); + return new CertificateProviderChannelCredentialsImpl.SecureConnectorImpl(this, channelTarget, options, callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); + } + maybeUpdateWatchers() { + if (this.hasReceivedUpdates()) { + for (const watcher of this.secureContextWatchers) { + watcher(this.getLatestSecureContext()); + } + this.secureContextWatchers = []; + } + } + handleCaCertificateUpdate(update) { + this.latestCaUpdate = update; + this.maybeUpdateWatchers(); + } + handleIdentityCertitificateUpdate(update) { + this.latestIdentityUpdate = update; + this.maybeUpdateWatchers(); + } + hasReceivedUpdates() { + if (this.latestCaUpdate === undefined) { + return false; + } + if (this.identityCertificateProvider && this.latestIdentityUpdate === undefined) { + return false; + } + return true; + } + getSecureContext() { + if (this.hasReceivedUpdates()) { + return Promise.resolve(this.getLatestSecureContext()); + } + else { + return new Promise(resolve => { + this.secureContextWatchers.push(resolve); + }); + } + } + getLatestSecureContext() { + var _a, _b; + if (!this.latestCaUpdate) { + return null; + } + if (this.identityCertificateProvider !== null && !this.latestIdentityUpdate) { + return null; + } + try { + return (0, tls_1.createSecureContext)({ + ca: this.latestCaUpdate.caCertificate, + key: (_a = this.latestIdentityUpdate) === null || _a === void 0 ? void 0 : _a.privateKey, + cert: (_b = this.latestIdentityUpdate) === null || _b === void 0 ? void 0 : _b.certificate, + ciphers: tls_helpers_1.CIPHER_SUITES + }); + } + catch (e) { + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, 'Failed to createSecureContext with error ' + e.message); + return null; + } + } +} +CertificateProviderChannelCredentialsImpl.SecureConnectorImpl = class { + constructor(parent, channelTarget, options, callCredentials) { + this.parent = parent; + this.channelTarget = channelTarget; + this.options = options; + this.callCredentials = callCredentials; + } + connect(socket) { + return new Promise((resolve, reject) => { + const secureContext = this.parent.getLatestSecureContext(); + if (!secureContext) { + reject(new Error('Failed to load credentials')); + return; + } + if (socket.closed) { + reject(new Error('Socket closed while loading credentials')); + } + const connnectionOptions = getConnectionOptions(secureContext, this.parent.verifyOptions, this.channelTarget, this.options); + const tlsConnectOptions = Object.assign({ socket: socket }, connnectionOptions); + const closeCallback = () => { + reject(new Error('Socket closed')); + }; + const errorCallback = (error) => { + reject(error); + }; + const tlsSocket = (0, tls_1.connect)(tlsConnectOptions, () => { + var _a; + tlsSocket.removeListener('close', closeCallback); + tlsSocket.removeListener('error', errorCallback); + if (((_a = this.parent.verifyOptions.rejectUnauthorized) !== null && _a !== void 0 ? _a : true) && !tlsSocket.authorized) { + reject(tlsSocket.authorizationError); + return; + } + resolve({ + socket: tlsSocket, + secure: true + }); + }); + tlsSocket.once('close', closeCallback); + tlsSocket.once('error', errorCallback); + }); + } + async waitForReady() { + await this.parent.getSecureContext(); + } + getCallCredentials() { + return this.callCredentials; + } + destroy() { + this.parent.unref(); + } +}; +function createCertificateProviderChannelCredentials(caCertificateProvider, identityCertificateProvider, verifyOptions) { + return new CertificateProviderChannelCredentialsImpl(caCertificateProvider, identityCertificateProvider, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {}); +} +class ComposedChannelCredentialsImpl extends ChannelCredentials { + constructor(channelCredentials, callCredentials) { + super(); + this.channelCredentials = channelCredentials; + this.callCredentials = callCredentials; + if (!channelCredentials._isSecure()) { + throw new Error('Cannot compose insecure credentials'); + } + } + compose(callCredentials) { + const combinedCallCredentials = this.callCredentials.compose(callCredentials); + return new ComposedChannelCredentialsImpl(this.channelCredentials, combinedCallCredentials); + } + _isSecure() { + return true; + } + _equals(other) { + if (this === other) { + return true; + } + if (other instanceof ComposedChannelCredentialsImpl) { + return (this.channelCredentials._equals(other.channelCredentials) && + this.callCredentials._equals(other.callCredentials)); + } + else { + return false; + } + } + _createSecureConnector(channelTarget, options, callCredentials) { + const combinedCallCredentials = this.callCredentials.compose(callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); + return this.channelCredentials._createSecureConnector(channelTarget, options, combinedCallCredentials); + } +} +//# sourceMappingURL=channel-credentials.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/channel-credentials.js.map b/node_modules/@grpc/grpc-js/build/src/channel-credentials.js.map new file mode 100644 index 0000000..af3bce2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channel-credentials.js.map @@ -0,0 +1 @@ +{"version":3,"file":"channel-credentials.js","sourceRoot":"","sources":["../../src/channel-credentials.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AA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IAAI,KAAK,YAAY,8BAA8B,EAAE,CAAC;YACpD,OAAO,CACL,IAAI,CAAC,kBAAkB,CAAC,OAAO,CAAC,KAAK,CAAC,kBAAkB,CAAC;gBACzD,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,KAAK,CAAC,eAAe,CAAC,CACpD,CAAC;QACJ,CAAC;aAAM,CAAC;YACN,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IACD,sBAAsB,CAAC,aAAsB,EAAE,OAAuB,EAAE,eAAiC;QACvG,MAAM,uBAAuB,GAAG,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,eAAe,aAAf,eAAe,cAAf,eAAe,GAAI,kCAAe,CAAC,WAAW,EAAE,CAAC,CAAC;QAC/G,OAAO,IAAI,CAAC,kBAAkB,CAAC,sBAAsB,CAAC,aAAa,EAAE,OAAO,EAAE,uBAAuB,CAAC,CAAC;IACzG,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/channel-options.d.ts b/node_modules/@grpc/grpc-js/build/src/channel-options.d.ts new file mode 100644 index 0000000..e3b4584 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channel-options.d.ts @@ -0,0 +1,81 @@ +import { CompressionAlgorithms } from './compression-algorithms'; +/** + * An interface that contains options used when initializing a Channel instance. + */ +export interface ChannelOptions { + 'grpc.ssl_target_name_override'?: string; + 'grpc.primary_user_agent'?: string; + 'grpc.secondary_user_agent'?: string; + 'grpc.default_authority'?: string; + 'grpc.keepalive_time_ms'?: number; + 'grpc.keepalive_timeout_ms'?: number; + 'grpc.keepalive_permit_without_calls'?: number; + 'grpc.service_config'?: string; + 'grpc.max_concurrent_streams'?: number; + 'grpc.initial_reconnect_backoff_ms'?: number; + 'grpc.max_reconnect_backoff_ms'?: number; + 'grpc.use_local_subchannel_pool'?: number; + 'grpc.max_send_message_length'?: number; + 'grpc.max_receive_message_length'?: number; + 'grpc.enable_http_proxy'?: number; + 'grpc.http_connect_target'?: string; + 'grpc.http_connect_creds'?: string; + 'grpc.default_compression_algorithm'?: CompressionAlgorithms; + 'grpc.enable_channelz'?: number; + 'grpc.dns_min_time_between_resolutions_ms'?: number; + 'grpc.enable_retries'?: number; + 'grpc.per_rpc_retry_buffer_size'?: number; + 'grpc.retry_buffer_size'?: number; + 'grpc.max_connection_age_ms'?: number; + 'grpc.max_connection_age_grace_ms'?: number; + 'grpc.max_connection_idle_ms'?: number; + 'grpc-node.max_session_memory'?: number; + 'grpc.service_config_disable_resolution'?: number; + 'grpc.client_idle_timeout_ms'?: number; + /** + * Set the enableTrace option in TLS clients and servers + */ + 'grpc-node.tls_enable_trace'?: number; + 'grpc.lb.ring_hash.ring_size_cap'?: number; + 'grpc-node.retry_max_attempts_limit'?: number; + 'grpc-node.flow_control_window'?: number; + 'grpc.server_call_metric_recording'?: number; + [key: string]: any; +} +/** + * This is for checking provided options at runtime. This is an object for + * easier membership checking. + */ +export declare const recognizedOptions: { + 'grpc.ssl_target_name_override': boolean; + 'grpc.primary_user_agent': boolean; + 'grpc.secondary_user_agent': boolean; + 'grpc.default_authority': boolean; + 'grpc.keepalive_time_ms': boolean; + 'grpc.keepalive_timeout_ms': boolean; + 'grpc.keepalive_permit_without_calls': boolean; + 'grpc.service_config': boolean; + 'grpc.max_concurrent_streams': boolean; + 'grpc.initial_reconnect_backoff_ms': boolean; + 'grpc.max_reconnect_backoff_ms': boolean; + 'grpc.use_local_subchannel_pool': boolean; + 'grpc.max_send_message_length': boolean; + 'grpc.max_receive_message_length': boolean; + 'grpc.enable_http_proxy': boolean; + 'grpc.enable_channelz': boolean; + 'grpc.dns_min_time_between_resolutions_ms': boolean; + 'grpc.enable_retries': boolean; + 'grpc.per_rpc_retry_buffer_size': boolean; + 'grpc.retry_buffer_size': boolean; + 'grpc.max_connection_age_ms': boolean; + 'grpc.max_connection_age_grace_ms': boolean; + 'grpc-node.max_session_memory': boolean; + 'grpc.service_config_disable_resolution': boolean; + 'grpc.client_idle_timeout_ms': boolean; + 'grpc-node.tls_enable_trace': boolean; + 'grpc.lb.ring_hash.ring_size_cap': boolean; + 'grpc-node.retry_max_attempts_limit': boolean; + 'grpc-node.flow_control_window': boolean; + 'grpc.server_call_metric_recording': boolean; +}; +export declare function channelOptionsEqual(options1: ChannelOptions, options2: ChannelOptions): boolean; diff --git a/node_modules/@grpc/grpc-js/build/src/channel-options.js b/node_modules/@grpc/grpc-js/build/src/channel-options.js new file mode 100644 index 0000000..c6aaa95 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channel-options.js @@ -0,0 +1,73 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.recognizedOptions = void 0; +exports.channelOptionsEqual = channelOptionsEqual; +/** + * This is for checking provided options at runtime. This is an object for + * easier membership checking. + */ +exports.recognizedOptions = { + 'grpc.ssl_target_name_override': true, + 'grpc.primary_user_agent': true, + 'grpc.secondary_user_agent': true, + 'grpc.default_authority': true, + 'grpc.keepalive_time_ms': true, + 'grpc.keepalive_timeout_ms': true, + 'grpc.keepalive_permit_without_calls': true, + 'grpc.service_config': true, + 'grpc.max_concurrent_streams': true, + 'grpc.initial_reconnect_backoff_ms': true, + 'grpc.max_reconnect_backoff_ms': true, + 'grpc.use_local_subchannel_pool': true, + 'grpc.max_send_message_length': true, + 'grpc.max_receive_message_length': true, + 'grpc.enable_http_proxy': true, + 'grpc.enable_channelz': true, + 'grpc.dns_min_time_between_resolutions_ms': true, + 'grpc.enable_retries': true, + 'grpc.per_rpc_retry_buffer_size': true, + 'grpc.retry_buffer_size': true, + 'grpc.max_connection_age_ms': true, + 'grpc.max_connection_age_grace_ms': true, + 'grpc-node.max_session_memory': true, + 'grpc.service_config_disable_resolution': true, + 'grpc.client_idle_timeout_ms': true, + 'grpc-node.tls_enable_trace': true, + 'grpc.lb.ring_hash.ring_size_cap': true, + 'grpc-node.retry_max_attempts_limit': true, + 'grpc-node.flow_control_window': true, + 'grpc.server_call_metric_recording': true +}; +function channelOptionsEqual(options1, options2) { + const keys1 = Object.keys(options1).sort(); + const keys2 = Object.keys(options2).sort(); + if (keys1.length !== keys2.length) { + return false; + } + for (let i = 0; i < keys1.length; i += 1) { + if (keys1[i] !== keys2[i]) { + return false; + } + if (options1[keys1[i]] !== options2[keys2[i]]) { + return false; + } + } + return true; +} +//# sourceMappingURL=channel-options.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/channel-options.js.map b/node_modules/@grpc/grpc-js/build/src/channel-options.js.map new file mode 100644 index 0000000..26ac269 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channel-options.js.map @@ -0,0 +1 @@ +{"version":3,"file":"channel-options.js","sourceRoot":"","sources":["../../src/channel-options.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AA8FH,kDAkBC;AAvDD;;;GAGG;AACU,QAAA,iBAAiB,GAAG;IAC/B,+BAA+B,EAAE,IAAI;IACrC,yBAAyB,EAAE,IAAI;IAC/B,2BAA2B,EAAE,IAAI;IACjC,wBAAwB,EAAE,IAAI;IAC9B,wBAAwB,EAAE,IAAI;IAC9B,2BAA2B,EAAE,IAAI;IACjC,qCAAqC,EAAE,IAAI;IAC3C,qBAAqB,EAAE,IAAI;IAC3B,6BAA6B,EAAE,IAAI;IACnC,mCAAmC,EAAE,IAAI;IACzC,+BAA+B,EAAE,IAAI;IACrC,gCAAgC,EAAE,IAAI;IACtC,8BAA8B,EAAE,IAAI;IACpC,iCAAiC,EAAE,IAAI;IACvC,wBAAwB,EAAE,IAAI;IAC9B,sBAAsB,EAAE,IAAI;IAC5B,0CAA0C,EAAE,IAAI;IAChD,qBAAqB,EAAE,IAAI;IAC3B,gCAAgC,EAAE,IAAI;IACtC,wBAAwB,EAAE,IAAI;IAC9B,4BAA4B,EAAE,IAAI;IAClC,kCAAkC,EAAE,IAAI;IACxC,8BAA8B,EAAE,IAAI;IACpC,wCAAwC,EAAE,IAAI;IAC9C,6BAA6B,EAAE,IAAI;IACnC,4BAA4B,EAAE,IAAI;IAClC,iCAAiC,EAAE,IAAI;IACvC,oCAAoC,EAAE,IAAI;IAC1C,+BAA+B,EAAE,IAAI;IACrC,mCAAmC,EAAE,IAAI;CAC1C,CAAC;AAEF,SAAgB,mBAAmB,CACjC,QAAwB,EACxB,QAAwB;IAExB,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC;IAC3C,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC;IAC3C,IAAI,KAAK,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,EAAE,CAAC;QAClC,OAAO,KAAK,CAAC;IACf,CAAC;IACD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;QACzC,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;YAC1B,OAAO,KAAK,CAAC;QACf,CAAC;QACD,IAAI,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;YAC9C,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/channel.d.ts b/node_modules/@grpc/grpc-js/build/src/channel.d.ts new file mode 100644 index 0000000..f4d646e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channel.d.ts @@ -0,0 +1,76 @@ +import { ChannelCredentials } from './channel-credentials'; +import { ChannelOptions } from './channel-options'; +import { ServerSurfaceCall } from './server-call'; +import { ConnectivityState } from './connectivity-state'; +import type { ChannelRef } from './channelz'; +import { Call } from './call-interface'; +import { Deadline } from './deadline'; +/** + * An interface that represents a communication channel to a server specified + * by a given address. + */ +export interface Channel { + /** + * Close the channel. This has the same functionality as the existing + * grpc.Client.prototype.close + */ + close(): void; + /** + * Return the target that this channel connects to + */ + getTarget(): string; + /** + * Get the channel's current connectivity state. This method is here mainly + * because it is in the existing internal Channel class, and there isn't + * another good place to put it. + * @param tryToConnect If true, the channel will start connecting if it is + * idle. Otherwise, idle channels will only start connecting when a + * call starts. + */ + getConnectivityState(tryToConnect: boolean): ConnectivityState; + /** + * Watch for connectivity state changes. This is also here mainly because + * it is in the existing external Channel class. + * @param currentState The state to watch for transitions from. This should + * always be populated by calling getConnectivityState immediately + * before. + * @param deadline A deadline for waiting for a state change + * @param callback Called with no error when a state change, or with an + * error if the deadline passes without a state change. + */ + watchConnectivityState(currentState: ConnectivityState, deadline: Date | number, callback: (error?: Error) => void): void; + /** + * Get the channelz reference object for this channel. A request to the + * channelz service for the id in this object will provide information + * about this channel. + */ + getChannelzRef(): ChannelRef; + /** + * Create a call object. Call is an opaque type that is used by the Client + * class. This function is called by the gRPC library when starting a + * request. Implementers should return an instance of Call that is returned + * from calling createCall on an instance of the provided Channel class. + * @param method The full method string to request. + * @param deadline The call deadline + * @param host A host string override for making the request + * @param parentCall A server call to propagate some information from + * @param propagateFlags A bitwise combination of elements of grpc.propagate + * that indicates what information to propagate from parentCall. + */ + createCall(method: string, deadline: Deadline, host: string | null | undefined, parentCall: ServerSurfaceCall | null, propagateFlags: number | null | undefined): Call; +} +export declare class ChannelImplementation implements Channel { + private internalChannel; + constructor(target: string, credentials: ChannelCredentials, options: ChannelOptions); + close(): void; + getTarget(): string; + getConnectivityState(tryToConnect: boolean): ConnectivityState; + watchConnectivityState(currentState: ConnectivityState, deadline: Date | number, callback: (error?: Error) => void): void; + /** + * Get the channelz reference object for this channel. The returned value is + * garbage if channelz is disabled for this channel. + * @returns + */ + getChannelzRef(): ChannelRef; + createCall(method: string, deadline: Deadline, host: string | null | undefined, parentCall: ServerSurfaceCall | null, propagateFlags: number | null | undefined): Call; +} diff --git a/node_modules/@grpc/grpc-js/build/src/channel.js b/node_modules/@grpc/grpc-js/build/src/channel.js new file mode 100644 index 0000000..49e8639 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channel.js @@ -0,0 +1,68 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChannelImplementation = void 0; +const channel_credentials_1 = require("./channel-credentials"); +const internal_channel_1 = require("./internal-channel"); +class ChannelImplementation { + constructor(target, credentials, options) { + if (typeof target !== 'string') { + throw new TypeError('Channel target must be a string'); + } + if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) { + throw new TypeError('Channel credentials must be a ChannelCredentials object'); + } + if (options) { + if (typeof options !== 'object') { + throw new TypeError('Channel options must be an object'); + } + } + this.internalChannel = new internal_channel_1.InternalChannel(target, credentials, options); + } + close() { + this.internalChannel.close(); + } + getTarget() { + return this.internalChannel.getTarget(); + } + getConnectivityState(tryToConnect) { + return this.internalChannel.getConnectivityState(tryToConnect); + } + watchConnectivityState(currentState, deadline, callback) { + this.internalChannel.watchConnectivityState(currentState, deadline, callback); + } + /** + * Get the channelz reference object for this channel. The returned value is + * garbage if channelz is disabled for this channel. + * @returns + */ + getChannelzRef() { + return this.internalChannel.getChannelzRef(); + } + createCall(method, deadline, host, parentCall, propagateFlags) { + if (typeof method !== 'string') { + throw new TypeError('Channel#createCall: method must be a string'); + } + if (!(typeof deadline === 'number' || deadline instanceof Date)) { + throw new TypeError('Channel#createCall: deadline must be a number or Date'); + } + return this.internalChannel.createCall(method, deadline, host, parentCall, propagateFlags); + } +} +exports.ChannelImplementation = ChannelImplementation; +//# sourceMappingURL=channel.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/channel.js.map b/node_modules/@grpc/grpc-js/build/src/channel.js.map new file mode 100644 index 0000000..8758e84 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"channel.js","sourceRoot":"","sources":["../../src/channel.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,+DAA2D;AAO3D,yDAAqD;AAoErD,MAAa,qBAAqB;IAGhC,YACE,MAAc,EACd,WAA+B,EAC/B,OAAuB;QAEvB,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;YAC/B,MAAM,IAAI,SAAS,CAAC,iCAAiC,CAAC,CAAC;QACzD,CAAC;QACD,IAAI,CAAC,CAAC,WAAW,YAAY,wCAAkB,CAAC,EAAE,CAAC;YACjD,MAAM,IAAI,SAAS,CACjB,yDAAyD,CAC1D,CAAC;QACJ,CAAC;QACD,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;gBAChC,MAAM,IAAI,SAAS,CAAC,mCAAmC,CAAC,CAAC;YAC3D,CAAC;QACH,CAAC;QAED,IAAI,CAAC,eAAe,GAAG,IAAI,kCAAe,CAAC,MAAM,EAAE,WAAW,EAAE,OAAO,CAAC,CAAC;IAC3E,CAAC;IAED,KAAK;QACH,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,CAAC;IAC/B,CAAC;IAED,SAAS;QACP,OAAO,IAAI,CAAC,eAAe,CAAC,SAAS,EAAE,CAAC;IAC1C,CAAC;IAED,oBAAoB,CAAC,YAAqB;QACxC,OAAO,IAAI,CAAC,eAAe,CAAC,oBAAoB,CAAC,YAAY,CAAC,CAAC;IACjE,CAAC;IAED,sBAAsB,CACpB,YAA+B,EAC/B,QAAuB,EACvB,QAAiC;QAEjC,IAAI,CAAC,eAAe,CAAC,sBAAsB,CACzC,YAAY,EACZ,QAAQ,EACR,QAAQ,CACT,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACH,cAAc;QACZ,OAAO,IAAI,CAAC,eAAe,CAAC,cAAc,EAAE,CAAC;IAC/C,CAAC;IAED,UAAU,CACR,MAAc,EACd,QAAkB,EAClB,IAA+B,EAC/B,UAAoC,EACpC,cAAyC;QAEzC,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;YAC/B,MAAM,IAAI,SAAS,CAAC,6CAA6C,CAAC,CAAC;QACrE,CAAC;QACD,IAAI,CAAC,CAAC,OAAO,QAAQ,KAAK,QAAQ,IAAI,QAAQ,YAAY,IAAI,CAAC,EAAE,CAAC;YAChE,MAAM,IAAI,SAAS,CACjB,uDAAuD,CACxD,CAAC;QACJ,CAAC;QACD,OAAO,IAAI,CAAC,eAAe,CAAC,UAAU,CACpC,MAAM,EACN,QAAQ,EACR,IAAI,EACJ,UAAU,EACV,cAAc,CACf,CAAC;IACJ,CAAC;CACF;AAjFD,sDAiFC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/channelz.d.ts b/node_modules/@grpc/grpc-js/build/src/channelz.d.ts new file mode 100644 index 0000000..831222d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channelz.d.ts @@ -0,0 +1,158 @@ +import { OrderedMap } from '@js-sdsl/ordered-map'; +import { ConnectivityState } from './connectivity-state'; +import { ChannelTrace } from './generated/grpc/channelz/v1/ChannelTrace'; +import { SubchannelAddress } from './subchannel-address'; +import { ChannelzDefinition, ChannelzHandlers } from './generated/grpc/channelz/v1/Channelz'; +export type TraceSeverity = 'CT_UNKNOWN' | 'CT_INFO' | 'CT_WARNING' | 'CT_ERROR'; +interface Ref { + kind: EntityTypes; + id: number; + name: string; +} +export interface ChannelRef extends Ref { + kind: EntityTypes.channel; +} +export interface SubchannelRef extends Ref { + kind: EntityTypes.subchannel; +} +export interface ServerRef extends Ref { + kind: EntityTypes.server; +} +export interface SocketRef extends Ref { + kind: EntityTypes.socket; +} +interface TraceEvent { + description: string; + severity: TraceSeverity; + timestamp: Date; + childChannel?: ChannelRef; + childSubchannel?: SubchannelRef; +} +export declare class ChannelzTraceStub { + readonly events: TraceEvent[]; + readonly creationTimestamp: Date; + readonly eventsLogged = 0; + addTrace(): void; + getTraceMessage(): ChannelTrace; +} +export declare class ChannelzTrace { + events: TraceEvent[]; + creationTimestamp: Date; + eventsLogged: number; + constructor(); + addTrace(severity: TraceSeverity, description: string, child?: ChannelRef | SubchannelRef): void; + getTraceMessage(): ChannelTrace; +} +export declare class ChannelzChildrenTracker { + private channelChildren; + private subchannelChildren; + private socketChildren; + private trackerMap; + refChild(child: ChannelRef | SubchannelRef | SocketRef): void; + unrefChild(child: ChannelRef | SubchannelRef | SocketRef): void; + getChildLists(): ChannelzChildren; +} +export declare class ChannelzChildrenTrackerStub extends ChannelzChildrenTracker { + refChild(): void; + unrefChild(): void; +} +export declare class ChannelzCallTracker { + callsStarted: number; + callsSucceeded: number; + callsFailed: number; + lastCallStartedTimestamp: Date | null; + addCallStarted(): void; + addCallSucceeded(): void; + addCallFailed(): void; +} +export declare class ChannelzCallTrackerStub extends ChannelzCallTracker { + addCallStarted(): void; + addCallSucceeded(): void; + addCallFailed(): void; +} +export interface ChannelzChildren { + channels: OrderedMap; + subchannels: OrderedMap; + sockets: OrderedMap; +} +export interface ChannelInfo { + target: string; + state: ConnectivityState; + trace: ChannelzTrace | ChannelzTraceStub; + callTracker: ChannelzCallTracker | ChannelzCallTrackerStub; + children: ChannelzChildren; +} +export type SubchannelInfo = ChannelInfo; +export interface ServerInfo { + trace: ChannelzTrace; + callTracker: ChannelzCallTracker; + listenerChildren: ChannelzChildren; + sessionChildren: ChannelzChildren; +} +export interface TlsInfo { + cipherSuiteStandardName: string | null; + cipherSuiteOtherName: string | null; + localCertificate: Buffer | null; + remoteCertificate: Buffer | null; +} +export interface SocketInfo { + localAddress: SubchannelAddress | null; + remoteAddress: SubchannelAddress | null; + security: TlsInfo | null; + remoteName: string | null; + streamsStarted: number; + streamsSucceeded: number; + streamsFailed: number; + messagesSent: number; + messagesReceived: number; + keepAlivesSent: number; + lastLocalStreamCreatedTimestamp: Date | null; + lastRemoteStreamCreatedTimestamp: Date | null; + lastMessageSentTimestamp: Date | null; + lastMessageReceivedTimestamp: Date | null; + localFlowControlWindow: number | null; + remoteFlowControlWindow: number | null; +} +interface ChannelEntry { + ref: ChannelRef; + getInfo(): ChannelInfo; +} +interface SubchannelEntry { + ref: SubchannelRef; + getInfo(): SubchannelInfo; +} +interface ServerEntry { + ref: ServerRef; + getInfo(): ServerInfo; +} +interface SocketEntry { + ref: SocketRef; + getInfo(): SocketInfo; +} +export declare const enum EntityTypes { + channel = "channel", + subchannel = "subchannel", + server = "server", + socket = "socket" +} +export type RefByType = T extends EntityTypes.channel ? ChannelRef : T extends EntityTypes.server ? ServerRef : T extends EntityTypes.socket ? SocketRef : T extends EntityTypes.subchannel ? SubchannelRef : never; +export type EntryByType = T extends EntityTypes.channel ? ChannelEntry : T extends EntityTypes.server ? ServerEntry : T extends EntityTypes.socket ? SocketEntry : T extends EntityTypes.subchannel ? SubchannelEntry : never; +export type InfoByType = T extends EntityTypes.channel ? ChannelInfo : T extends EntityTypes.subchannel ? SubchannelInfo : T extends EntityTypes.server ? ServerInfo : T extends EntityTypes.socket ? SocketInfo : never; +export declare const registerChannelzChannel: (name: string, getInfo: () => ChannelInfo, channelzEnabled: boolean) => ChannelRef; +export declare const registerChannelzSubchannel: (name: string, getInfo: () => ChannelInfo, channelzEnabled: boolean) => SubchannelRef; +export declare const registerChannelzServer: (name: string, getInfo: () => ServerInfo, channelzEnabled: boolean) => ServerRef; +export declare const registerChannelzSocket: (name: string, getInfo: () => SocketInfo, channelzEnabled: boolean) => SocketRef; +export declare function unregisterChannelzRef(ref: ChannelRef | SubchannelRef | ServerRef | SocketRef): void; +export declare function getChannelzHandlers(): ChannelzHandlers; +export declare function getChannelzServiceDefinition(): ChannelzDefinition; +export declare function setup(): void; +export {}; diff --git a/node_modules/@grpc/grpc-js/build/src/channelz.js b/node_modules/@grpc/grpc-js/build/src/channelz.js new file mode 100644 index 0000000..91e9ace --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channelz.js @@ -0,0 +1,598 @@ +"use strict"; +/* + * Copyright 2021 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.registerChannelzSocket = exports.registerChannelzServer = exports.registerChannelzSubchannel = exports.registerChannelzChannel = exports.ChannelzCallTrackerStub = exports.ChannelzCallTracker = exports.ChannelzChildrenTrackerStub = exports.ChannelzChildrenTracker = exports.ChannelzTrace = exports.ChannelzTraceStub = void 0; +exports.unregisterChannelzRef = unregisterChannelzRef; +exports.getChannelzHandlers = getChannelzHandlers; +exports.getChannelzServiceDefinition = getChannelzServiceDefinition; +exports.setup = setup; +const net_1 = require("net"); +const ordered_map_1 = require("@js-sdsl/ordered-map"); +const connectivity_state_1 = require("./connectivity-state"); +const constants_1 = require("./constants"); +const subchannel_address_1 = require("./subchannel-address"); +const admin_1 = require("./admin"); +const make_client_1 = require("./make-client"); +function channelRefToMessage(ref) { + return { + channel_id: ref.id, + name: ref.name, + }; +} +function subchannelRefToMessage(ref) { + return { + subchannel_id: ref.id, + name: ref.name, + }; +} +function serverRefToMessage(ref) { + return { + server_id: ref.id, + }; +} +function socketRefToMessage(ref) { + return { + socket_id: ref.id, + name: ref.name, + }; +} +/** + * The loose upper bound on the number of events that should be retained in a + * trace. This may be exceeded by up to a factor of 2. Arbitrarily chosen as a + * number that should be large enough to contain the recent relevant + * information, but small enough to not use excessive memory. + */ +const TARGET_RETAINED_TRACES = 32; +/** + * Default number of sockets/servers/channels/subchannels to return + */ +const DEFAULT_MAX_RESULTS = 100; +class ChannelzTraceStub { + constructor() { + this.events = []; + this.creationTimestamp = new Date(); + this.eventsLogged = 0; + } + addTrace() { } + getTraceMessage() { + return { + creation_timestamp: dateToProtoTimestamp(this.creationTimestamp), + num_events_logged: this.eventsLogged, + events: [], + }; + } +} +exports.ChannelzTraceStub = ChannelzTraceStub; +class ChannelzTrace { + constructor() { + this.events = []; + this.eventsLogged = 0; + this.creationTimestamp = new Date(); + } + addTrace(severity, description, child) { + const timestamp = new Date(); + this.events.push({ + description: description, + severity: severity, + timestamp: timestamp, + childChannel: (child === null || child === void 0 ? void 0 : child.kind) === 'channel' ? child : undefined, + childSubchannel: (child === null || child === void 0 ? void 0 : child.kind) === 'subchannel' ? child : undefined, + }); + // Whenever the trace array gets too large, discard the first half + if (this.events.length >= TARGET_RETAINED_TRACES * 2) { + this.events = this.events.slice(TARGET_RETAINED_TRACES); + } + this.eventsLogged += 1; + } + getTraceMessage() { + return { + creation_timestamp: dateToProtoTimestamp(this.creationTimestamp), + num_events_logged: this.eventsLogged, + events: this.events.map(event => { + return { + description: event.description, + severity: event.severity, + timestamp: dateToProtoTimestamp(event.timestamp), + channel_ref: event.childChannel + ? channelRefToMessage(event.childChannel) + : null, + subchannel_ref: event.childSubchannel + ? subchannelRefToMessage(event.childSubchannel) + : null, + }; + }), + }; + } +} +exports.ChannelzTrace = ChannelzTrace; +class ChannelzChildrenTracker { + constructor() { + this.channelChildren = new ordered_map_1.OrderedMap(); + this.subchannelChildren = new ordered_map_1.OrderedMap(); + this.socketChildren = new ordered_map_1.OrderedMap(); + this.trackerMap = { + ["channel" /* EntityTypes.channel */]: this.channelChildren, + ["subchannel" /* EntityTypes.subchannel */]: this.subchannelChildren, + ["socket" /* EntityTypes.socket */]: this.socketChildren, + }; + } + refChild(child) { + const tracker = this.trackerMap[child.kind]; + const trackedChild = tracker.find(child.id); + if (trackedChild.equals(tracker.end())) { + tracker.setElement(child.id, { + ref: child, + count: 1, + }, trackedChild); + } + else { + trackedChild.pointer[1].count += 1; + } + } + unrefChild(child) { + const tracker = this.trackerMap[child.kind]; + const trackedChild = tracker.getElementByKey(child.id); + if (trackedChild !== undefined) { + trackedChild.count -= 1; + if (trackedChild.count === 0) { + tracker.eraseElementByKey(child.id); + } + } + } + getChildLists() { + return { + channels: this.channelChildren, + subchannels: this.subchannelChildren, + sockets: this.socketChildren, + }; + } +} +exports.ChannelzChildrenTracker = ChannelzChildrenTracker; +class ChannelzChildrenTrackerStub extends ChannelzChildrenTracker { + refChild() { } + unrefChild() { } +} +exports.ChannelzChildrenTrackerStub = ChannelzChildrenTrackerStub; +class ChannelzCallTracker { + constructor() { + this.callsStarted = 0; + this.callsSucceeded = 0; + this.callsFailed = 0; + this.lastCallStartedTimestamp = null; + } + addCallStarted() { + this.callsStarted += 1; + this.lastCallStartedTimestamp = new Date(); + } + addCallSucceeded() { + this.callsSucceeded += 1; + } + addCallFailed() { + this.callsFailed += 1; + } +} +exports.ChannelzCallTracker = ChannelzCallTracker; +class ChannelzCallTrackerStub extends ChannelzCallTracker { + addCallStarted() { } + addCallSucceeded() { } + addCallFailed() { } +} +exports.ChannelzCallTrackerStub = ChannelzCallTrackerStub; +const entityMaps = { + ["channel" /* EntityTypes.channel */]: new ordered_map_1.OrderedMap(), + ["subchannel" /* EntityTypes.subchannel */]: new ordered_map_1.OrderedMap(), + ["server" /* EntityTypes.server */]: new ordered_map_1.OrderedMap(), + ["socket" /* EntityTypes.socket */]: new ordered_map_1.OrderedMap(), +}; +const generateRegisterFn = (kind) => { + let nextId = 1; + function getNextId() { + return nextId++; + } + const entityMap = entityMaps[kind]; + return (name, getInfo, channelzEnabled) => { + const id = getNextId(); + const ref = { id, name, kind }; + if (channelzEnabled) { + entityMap.setElement(id, { ref, getInfo }); + } + return ref; + }; +}; +exports.registerChannelzChannel = generateRegisterFn("channel" /* EntityTypes.channel */); +exports.registerChannelzSubchannel = generateRegisterFn("subchannel" /* EntityTypes.subchannel */); +exports.registerChannelzServer = generateRegisterFn("server" /* EntityTypes.server */); +exports.registerChannelzSocket = generateRegisterFn("socket" /* EntityTypes.socket */); +function unregisterChannelzRef(ref) { + entityMaps[ref.kind].eraseElementByKey(ref.id); +} +/** + * Parse a single section of an IPv6 address as two bytes + * @param addressSection A hexadecimal string of length up to 4 + * @returns The pair of bytes representing this address section + */ +function parseIPv6Section(addressSection) { + const numberValue = Number.parseInt(addressSection, 16); + return [(numberValue / 256) | 0, numberValue % 256]; +} +/** + * Parse a chunk of an IPv6 address string to some number of bytes + * @param addressChunk Some number of segments of up to 4 hexadecimal + * characters each, joined by colons. + * @returns The list of bytes representing this address chunk + */ +function parseIPv6Chunk(addressChunk) { + if (addressChunk === '') { + return []; + } + const bytePairs = addressChunk + .split(':') + .map(section => parseIPv6Section(section)); + const result = []; + return result.concat(...bytePairs); +} +function isIPv6MappedIPv4(ipAddress) { + return (0, net_1.isIPv6)(ipAddress) && ipAddress.toLowerCase().startsWith('::ffff:') && (0, net_1.isIPv4)(ipAddress.substring(7)); +} +/** + * Prerequisite: isIPv4(ipAddress) + * @param ipAddress + * @returns + */ +function ipv4AddressStringToBuffer(ipAddress) { + return Buffer.from(Uint8Array.from(ipAddress.split('.').map(segment => Number.parseInt(segment)))); +} +/** + * Converts an IPv4 or IPv6 address from string representation to binary + * representation + * @param ipAddress an IP address in standard IPv4 or IPv6 text format + * @returns + */ +function ipAddressStringToBuffer(ipAddress) { + if ((0, net_1.isIPv4)(ipAddress)) { + return ipv4AddressStringToBuffer(ipAddress); + } + else if (isIPv6MappedIPv4(ipAddress)) { + return ipv4AddressStringToBuffer(ipAddress.substring(7)); + } + else if ((0, net_1.isIPv6)(ipAddress)) { + let leftSection; + let rightSection; + const doubleColonIndex = ipAddress.indexOf('::'); + if (doubleColonIndex === -1) { + leftSection = ipAddress; + rightSection = ''; + } + else { + leftSection = ipAddress.substring(0, doubleColonIndex); + rightSection = ipAddress.substring(doubleColonIndex + 2); + } + const leftBuffer = Buffer.from(parseIPv6Chunk(leftSection)); + const rightBuffer = Buffer.from(parseIPv6Chunk(rightSection)); + const middleBuffer = Buffer.alloc(16 - leftBuffer.length - rightBuffer.length, 0); + return Buffer.concat([leftBuffer, middleBuffer, rightBuffer]); + } + else { + return null; + } +} +function connectivityStateToMessage(state) { + switch (state) { + case connectivity_state_1.ConnectivityState.CONNECTING: + return { + state: 'CONNECTING', + }; + case connectivity_state_1.ConnectivityState.IDLE: + return { + state: 'IDLE', + }; + case connectivity_state_1.ConnectivityState.READY: + return { + state: 'READY', + }; + case connectivity_state_1.ConnectivityState.SHUTDOWN: + return { + state: 'SHUTDOWN', + }; + case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE: + return { + state: 'TRANSIENT_FAILURE', + }; + default: + return { + state: 'UNKNOWN', + }; + } +} +function dateToProtoTimestamp(date) { + if (!date) { + return null; + } + const millisSinceEpoch = date.getTime(); + return { + seconds: (millisSinceEpoch / 1000) | 0, + nanos: (millisSinceEpoch % 1000) * 1000000, + }; +} +function getChannelMessage(channelEntry) { + const resolvedInfo = channelEntry.getInfo(); + const channelRef = []; + const subchannelRef = []; + resolvedInfo.children.channels.forEach(el => { + channelRef.push(channelRefToMessage(el[1].ref)); + }); + resolvedInfo.children.subchannels.forEach(el => { + subchannelRef.push(subchannelRefToMessage(el[1].ref)); + }); + return { + ref: channelRefToMessage(channelEntry.ref), + data: { + target: resolvedInfo.target, + state: connectivityStateToMessage(resolvedInfo.state), + calls_started: resolvedInfo.callTracker.callsStarted, + calls_succeeded: resolvedInfo.callTracker.callsSucceeded, + calls_failed: resolvedInfo.callTracker.callsFailed, + last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), + trace: resolvedInfo.trace.getTraceMessage(), + }, + channel_ref: channelRef, + subchannel_ref: subchannelRef, + }; +} +function GetChannel(call, callback) { + const channelId = parseInt(call.request.channel_id, 10); + const channelEntry = entityMaps["channel" /* EntityTypes.channel */].getElementByKey(channelId); + if (channelEntry === undefined) { + callback({ + code: constants_1.Status.NOT_FOUND, + details: 'No channel data found for id ' + channelId, + }); + return; + } + callback(null, { channel: getChannelMessage(channelEntry) }); +} +function GetTopChannels(call, callback) { + const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; + const resultList = []; + const startId = parseInt(call.request.start_channel_id, 10); + const channelEntries = entityMaps["channel" /* EntityTypes.channel */]; + let i; + for (i = channelEntries.lowerBound(startId); !i.equals(channelEntries.end()) && resultList.length < maxResults; i = i.next()) { + resultList.push(getChannelMessage(i.pointer[1])); + } + callback(null, { + channel: resultList, + end: i.equals(channelEntries.end()), + }); +} +function getServerMessage(serverEntry) { + const resolvedInfo = serverEntry.getInfo(); + const listenSocket = []; + resolvedInfo.listenerChildren.sockets.forEach(el => { + listenSocket.push(socketRefToMessage(el[1].ref)); + }); + return { + ref: serverRefToMessage(serverEntry.ref), + data: { + calls_started: resolvedInfo.callTracker.callsStarted, + calls_succeeded: resolvedInfo.callTracker.callsSucceeded, + calls_failed: resolvedInfo.callTracker.callsFailed, + last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), + trace: resolvedInfo.trace.getTraceMessage(), + }, + listen_socket: listenSocket, + }; +} +function GetServer(call, callback) { + const serverId = parseInt(call.request.server_id, 10); + const serverEntries = entityMaps["server" /* EntityTypes.server */]; + const serverEntry = serverEntries.getElementByKey(serverId); + if (serverEntry === undefined) { + callback({ + code: constants_1.Status.NOT_FOUND, + details: 'No server data found for id ' + serverId, + }); + return; + } + callback(null, { server: getServerMessage(serverEntry) }); +} +function GetServers(call, callback) { + const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; + const startId = parseInt(call.request.start_server_id, 10); + const serverEntries = entityMaps["server" /* EntityTypes.server */]; + const resultList = []; + let i; + for (i = serverEntries.lowerBound(startId); !i.equals(serverEntries.end()) && resultList.length < maxResults; i = i.next()) { + resultList.push(getServerMessage(i.pointer[1])); + } + callback(null, { + server: resultList, + end: i.equals(serverEntries.end()), + }); +} +function GetSubchannel(call, callback) { + const subchannelId = parseInt(call.request.subchannel_id, 10); + const subchannelEntry = entityMaps["subchannel" /* EntityTypes.subchannel */].getElementByKey(subchannelId); + if (subchannelEntry === undefined) { + callback({ + code: constants_1.Status.NOT_FOUND, + details: 'No subchannel data found for id ' + subchannelId, + }); + return; + } + const resolvedInfo = subchannelEntry.getInfo(); + const listenSocket = []; + resolvedInfo.children.sockets.forEach(el => { + listenSocket.push(socketRefToMessage(el[1].ref)); + }); + const subchannelMessage = { + ref: subchannelRefToMessage(subchannelEntry.ref), + data: { + target: resolvedInfo.target, + state: connectivityStateToMessage(resolvedInfo.state), + calls_started: resolvedInfo.callTracker.callsStarted, + calls_succeeded: resolvedInfo.callTracker.callsSucceeded, + calls_failed: resolvedInfo.callTracker.callsFailed, + last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), + trace: resolvedInfo.trace.getTraceMessage(), + }, + socket_ref: listenSocket, + }; + callback(null, { subchannel: subchannelMessage }); +} +function subchannelAddressToAddressMessage(subchannelAddress) { + var _a; + if ((0, subchannel_address_1.isTcpSubchannelAddress)(subchannelAddress)) { + return { + address: 'tcpip_address', + tcpip_address: { + ip_address: (_a = ipAddressStringToBuffer(subchannelAddress.host)) !== null && _a !== void 0 ? _a : undefined, + port: subchannelAddress.port, + }, + }; + } + else { + return { + address: 'uds_address', + uds_address: { + filename: subchannelAddress.path, + }, + }; + } +} +function GetSocket(call, callback) { + var _a, _b, _c, _d, _e; + const socketId = parseInt(call.request.socket_id, 10); + const socketEntry = entityMaps["socket" /* EntityTypes.socket */].getElementByKey(socketId); + if (socketEntry === undefined) { + callback({ + code: constants_1.Status.NOT_FOUND, + details: 'No socket data found for id ' + socketId, + }); + return; + } + const resolvedInfo = socketEntry.getInfo(); + const securityMessage = resolvedInfo.security + ? { + model: 'tls', + tls: { + cipher_suite: resolvedInfo.security.cipherSuiteStandardName + ? 'standard_name' + : 'other_name', + standard_name: (_a = resolvedInfo.security.cipherSuiteStandardName) !== null && _a !== void 0 ? _a : undefined, + other_name: (_b = resolvedInfo.security.cipherSuiteOtherName) !== null && _b !== void 0 ? _b : undefined, + local_certificate: (_c = resolvedInfo.security.localCertificate) !== null && _c !== void 0 ? _c : undefined, + remote_certificate: (_d = resolvedInfo.security.remoteCertificate) !== null && _d !== void 0 ? _d : undefined, + }, + } + : null; + const socketMessage = { + ref: socketRefToMessage(socketEntry.ref), + local: resolvedInfo.localAddress + ? subchannelAddressToAddressMessage(resolvedInfo.localAddress) + : null, + remote: resolvedInfo.remoteAddress + ? subchannelAddressToAddressMessage(resolvedInfo.remoteAddress) + : null, + remote_name: (_e = resolvedInfo.remoteName) !== null && _e !== void 0 ? _e : undefined, + security: securityMessage, + data: { + keep_alives_sent: resolvedInfo.keepAlivesSent, + streams_started: resolvedInfo.streamsStarted, + streams_succeeded: resolvedInfo.streamsSucceeded, + streams_failed: resolvedInfo.streamsFailed, + last_local_stream_created_timestamp: dateToProtoTimestamp(resolvedInfo.lastLocalStreamCreatedTimestamp), + last_remote_stream_created_timestamp: dateToProtoTimestamp(resolvedInfo.lastRemoteStreamCreatedTimestamp), + messages_received: resolvedInfo.messagesReceived, + messages_sent: resolvedInfo.messagesSent, + last_message_received_timestamp: dateToProtoTimestamp(resolvedInfo.lastMessageReceivedTimestamp), + last_message_sent_timestamp: dateToProtoTimestamp(resolvedInfo.lastMessageSentTimestamp), + local_flow_control_window: resolvedInfo.localFlowControlWindow + ? { value: resolvedInfo.localFlowControlWindow } + : null, + remote_flow_control_window: resolvedInfo.remoteFlowControlWindow + ? { value: resolvedInfo.remoteFlowControlWindow } + : null, + }, + }; + callback(null, { socket: socketMessage }); +} +function GetServerSockets(call, callback) { + const serverId = parseInt(call.request.server_id, 10); + const serverEntry = entityMaps["server" /* EntityTypes.server */].getElementByKey(serverId); + if (serverEntry === undefined) { + callback({ + code: constants_1.Status.NOT_FOUND, + details: 'No server data found for id ' + serverId, + }); + return; + } + const startId = parseInt(call.request.start_socket_id, 10); + const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; + const resolvedInfo = serverEntry.getInfo(); + // If we wanted to include listener sockets in the result, this line would + // instead say + // const allSockets = resolvedInfo.listenerChildren.sockets.concat(resolvedInfo.sessionChildren.sockets).sort((ref1, ref2) => ref1.id - ref2.id); + const allSockets = resolvedInfo.sessionChildren.sockets; + const resultList = []; + let i; + for (i = allSockets.lowerBound(startId); !i.equals(allSockets.end()) && resultList.length < maxResults; i = i.next()) { + resultList.push(socketRefToMessage(i.pointer[1].ref)); + } + callback(null, { + socket_ref: resultList, + end: i.equals(allSockets.end()), + }); +} +function getChannelzHandlers() { + return { + GetChannel, + GetTopChannels, + GetServer, + GetServers, + GetSubchannel, + GetSocket, + GetServerSockets, + }; +} +let loadedChannelzDefinition = null; +function getChannelzServiceDefinition() { + if (loadedChannelzDefinition) { + return loadedChannelzDefinition; + } + /* The purpose of this complexity is to avoid loading @grpc/proto-loader at + * runtime for users who will not use/enable channelz. */ + const loaderLoadSync = require('@grpc/proto-loader') + .loadSync; + const loadedProto = loaderLoadSync('channelz.proto', { + keepCase: true, + longs: String, + enums: String, + defaults: true, + oneofs: true, + includeDirs: [`${__dirname}/../../proto`], + }); + const channelzGrpcObject = (0, make_client_1.loadPackageDefinition)(loadedProto); + loadedChannelzDefinition = + channelzGrpcObject.grpc.channelz.v1.Channelz.service; + return loadedChannelzDefinition; +} +function setup() { + (0, admin_1.registerAdminService)(getChannelzServiceDefinition, getChannelzHandlers); +} +//# sourceMappingURL=channelz.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/channelz.js.map b/node_modules/@grpc/grpc-js/build/src/channelz.js.map new file mode 100644 index 0000000..1536e0b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channelz.js.map @@ -0,0 +1 @@ +{"version":3,"file":"channelz.js","sourceRoot":"","sources":["../../src/channelz.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AA8ZH,sDAIC;AAmbD,kDAUC;AAID,oEAsBC;AAED,sBAEC;AA33BD,6BAAqC;AACrC,sDAA2E;AAC3E,6DAAyD;AACzD,2CAAqC;AAWrC,6DAG8B;AAyB9B,mCAA+C;AAC/C,+CAAsD;AA8BtD,SAAS,mBAAmB,CAAC,GAAe;IAC1C,OAAO;QACL,UAAU,EAAE,GAAG,CAAC,EAAE;QAClB,IAAI,EAAE,GAAG,CAAC,IAAI;KACf,CAAC;AACJ,CAAC;AAED,SAAS,sBAAsB,CAAC,GAAkB;IAChD,OAAO;QACL,aAAa,EAAE,GAAG,CAAC,EAAE;QACrB,IAAI,EAAE,GAAG,CAAC,IAAI;KACf,CAAC;AACJ,CAAC;AAED,SAAS,kBAAkB,CAAC,GAAc;IACxC,OAAO;QACL,SAAS,EAAE,GAAG,CAAC,EAAE;KAClB,CAAC;AACJ,CAAC;AAED,SAAS,kBAAkB,CAAC,GAAc;IACxC,OAAO;QACL,SAAS,EAAE,GAAG,CAAC,EAAE;QACjB,IAAI,EAAE,GAAG,CAAC,IAAI;KACf,CAAC;AACJ,CAAC;AAUD;;;;;GAKG;AACH,MAAM,sBAAsB,GAAG,EAAE,CAAC;AAElC;;GAEG;AACH,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAEhC,MAAa,iBAAiB;IAA9B;QACW,WAAM,GAAiB,EAAE,CAAC;QAC1B,sBAAiB,GAAS,IAAI,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M;QACb,QAAQ,EAAE,IAAI;QACd,MAAM,EAAE,IAAI;QACZ,WAAW,EAAE,CAAC,GAAG,SAAS,cAAc,CAAC;KAC1C,CAAC,CAAC;IACH,MAAM,kBAAkB,GAAG,IAAA,mCAAqB,EAC9C,WAAW,CACwB,CAAC;IACtC,wBAAwB;QACtB,kBAAkB,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC;IACvD,OAAO,wBAAwB,CAAC;AAClC,CAAC;AAED,SAAgB,KAAK;IACnB,IAAA,4BAAoB,EAAC,4BAA4B,EAAE,mBAAmB,CAAC,CAAC;AAC1E,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/client-interceptors.d.ts b/node_modules/@grpc/grpc-js/build/src/client-interceptors.d.ts new file mode 100644 index 0000000..4da2b9c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/client-interceptors.d.ts @@ -0,0 +1,123 @@ +import { Metadata } from './metadata'; +import { Listener, MetadataListener, MessageListener, StatusListener, InterceptingListener, MessageContext } from './call-interface'; +import { Status } from './constants'; +import { Channel } from './channel'; +import { CallOptions } from './client'; +import { ClientMethodDefinition } from './make-client'; +import { AuthContext } from './auth-context'; +/** + * Error class associated with passing both interceptors and interceptor + * providers to a client constructor or as call options. + */ +export declare class InterceptorConfigurationError extends Error { + constructor(message: string); +} +export interface MetadataRequester { + (metadata: Metadata, listener: InterceptingListener, next: (metadata: Metadata, listener: InterceptingListener | Listener) => void): void; +} +export interface MessageRequester { + (message: any, next: (message: any) => void): void; +} +export interface CloseRequester { + (next: () => void): void; +} +export interface CancelRequester { + (next: () => void): void; +} +/** + * An object with methods for intercepting and modifying outgoing call operations. + */ +export interface FullRequester { + start: MetadataRequester; + sendMessage: MessageRequester; + halfClose: CloseRequester; + cancel: CancelRequester; +} +export type Requester = Partial; +export declare class ListenerBuilder { + private metadata; + private message; + private status; + withOnReceiveMetadata(onReceiveMetadata: MetadataListener): this; + withOnReceiveMessage(onReceiveMessage: MessageListener): this; + withOnReceiveStatus(onReceiveStatus: StatusListener): this; + build(): Listener; +} +export declare class RequesterBuilder { + private start; + private message; + private halfClose; + private cancel; + withStart(start: MetadataRequester): this; + withSendMessage(sendMessage: MessageRequester): this; + withHalfClose(halfClose: CloseRequester): this; + withCancel(cancel: CancelRequester): this; + build(): Requester; +} +export interface InterceptorOptions extends CallOptions { + method_definition: ClientMethodDefinition; +} +export interface InterceptingCallInterface { + cancelWithStatus(status: Status, details: string): void; + getPeer(): string; + start(metadata: Metadata, listener?: Partial): void; + sendMessageWithContext(context: MessageContext, message: any): void; + sendMessage(message: any): void; + startRead(): void; + halfClose(): void; + getAuthContext(): AuthContext | null; +} +export declare class InterceptingCall implements InterceptingCallInterface { + private nextCall; + /** + * The requester that this InterceptingCall uses to modify outgoing operations + */ + private requester; + /** + * Indicates that metadata has been passed to the requester's start + * method but it has not been passed to the corresponding next callback + */ + private processingMetadata; + /** + * Message context for a pending message that is waiting for + */ + private pendingMessageContext; + private pendingMessage; + /** + * Indicates that a message has been passed to the requester's sendMessage + * method but it has not been passed to the corresponding next callback + */ + private processingMessage; + /** + * Indicates that a status was received but could not be propagated because + * a message was still being processed. + */ + private pendingHalfClose; + constructor(nextCall: InterceptingCallInterface, requester?: Requester); + cancelWithStatus(status: Status, details: string): void; + getPeer(): string; + private processPendingMessage; + private processPendingHalfClose; + start(metadata: Metadata, interceptingListener?: Partial): void; + sendMessageWithContext(context: MessageContext, message: any): void; + sendMessage(message: any): void; + startRead(): void; + halfClose(): void; + getAuthContext(): AuthContext | null; +} +export interface NextCall { + (options: InterceptorOptions): InterceptingCallInterface; +} +export interface Interceptor { + (options: InterceptorOptions, nextCall: NextCall): InterceptingCall; +} +export interface InterceptorProvider { + (methodDefinition: ClientMethodDefinition): Interceptor; +} +export interface InterceptorArguments { + clientInterceptors: Interceptor[]; + clientInterceptorProviders: InterceptorProvider[]; + callInterceptors: Interceptor[]; + callInterceptorProviders: InterceptorProvider[]; +} +export declare function getInterceptingCall(interceptorArgs: InterceptorArguments, methodDefinition: ClientMethodDefinition, options: CallOptions, channel: Channel): InterceptingCallInterface; diff --git a/node_modules/@grpc/grpc-js/build/src/client-interceptors.js b/node_modules/@grpc/grpc-js/build/src/client-interceptors.js new file mode 100644 index 0000000..51fa979 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/client-interceptors.js @@ -0,0 +1,434 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InterceptingCall = exports.RequesterBuilder = exports.ListenerBuilder = exports.InterceptorConfigurationError = void 0; +exports.getInterceptingCall = getInterceptingCall; +const metadata_1 = require("./metadata"); +const call_interface_1 = require("./call-interface"); +const constants_1 = require("./constants"); +const error_1 = require("./error"); +/** + * Error class associated with passing both interceptors and interceptor + * providers to a client constructor or as call options. + */ +class InterceptorConfigurationError extends Error { + constructor(message) { + super(message); + this.name = 'InterceptorConfigurationError'; + Error.captureStackTrace(this, InterceptorConfigurationError); + } +} +exports.InterceptorConfigurationError = InterceptorConfigurationError; +class ListenerBuilder { + constructor() { + this.metadata = undefined; + this.message = undefined; + this.status = undefined; + } + withOnReceiveMetadata(onReceiveMetadata) { + this.metadata = onReceiveMetadata; + return this; + } + withOnReceiveMessage(onReceiveMessage) { + this.message = onReceiveMessage; + return this; + } + withOnReceiveStatus(onReceiveStatus) { + this.status = onReceiveStatus; + return this; + } + build() { + return { + onReceiveMetadata: this.metadata, + onReceiveMessage: this.message, + onReceiveStatus: this.status, + }; + } +} +exports.ListenerBuilder = ListenerBuilder; +class RequesterBuilder { + constructor() { + this.start = undefined; + this.message = undefined; + this.halfClose = undefined; + this.cancel = undefined; + } + withStart(start) { + this.start = start; + return this; + } + withSendMessage(sendMessage) { + this.message = sendMessage; + return this; + } + withHalfClose(halfClose) { + this.halfClose = halfClose; + return this; + } + withCancel(cancel) { + this.cancel = cancel; + return this; + } + build() { + return { + start: this.start, + sendMessage: this.message, + halfClose: this.halfClose, + cancel: this.cancel, + }; + } +} +exports.RequesterBuilder = RequesterBuilder; +/** + * A Listener with a default pass-through implementation of each method. Used + * for filling out Listeners with some methods omitted. + */ +const defaultListener = { + onReceiveMetadata: (metadata, next) => { + next(metadata); + }, + onReceiveMessage: (message, next) => { + next(message); + }, + onReceiveStatus: (status, next) => { + next(status); + }, +}; +/** + * A Requester with a default pass-through implementation of each method. Used + * for filling out Requesters with some methods omitted. + */ +const defaultRequester = { + start: (metadata, listener, next) => { + next(metadata, listener); + }, + sendMessage: (message, next) => { + next(message); + }, + halfClose: next => { + next(); + }, + cancel: next => { + next(); + }, +}; +class InterceptingCall { + constructor(nextCall, requester) { + var _a, _b, _c, _d; + this.nextCall = nextCall; + /** + * Indicates that metadata has been passed to the requester's start + * method but it has not been passed to the corresponding next callback + */ + this.processingMetadata = false; + /** + * Message context for a pending message that is waiting for + */ + this.pendingMessageContext = null; + /** + * Indicates that a message has been passed to the requester's sendMessage + * method but it has not been passed to the corresponding next callback + */ + this.processingMessage = false; + /** + * Indicates that a status was received but could not be propagated because + * a message was still being processed. + */ + this.pendingHalfClose = false; + if (requester) { + this.requester = { + start: (_a = requester.start) !== null && _a !== void 0 ? _a : defaultRequester.start, + sendMessage: (_b = requester.sendMessage) !== null && _b !== void 0 ? _b : defaultRequester.sendMessage, + halfClose: (_c = requester.halfClose) !== null && _c !== void 0 ? _c : defaultRequester.halfClose, + cancel: (_d = requester.cancel) !== null && _d !== void 0 ? _d : defaultRequester.cancel, + }; + } + else { + this.requester = defaultRequester; + } + } + cancelWithStatus(status, details) { + this.requester.cancel(() => { + this.nextCall.cancelWithStatus(status, details); + }); + } + getPeer() { + return this.nextCall.getPeer(); + } + processPendingMessage() { + if (this.pendingMessageContext) { + this.nextCall.sendMessageWithContext(this.pendingMessageContext, this.pendingMessage); + this.pendingMessageContext = null; + this.pendingMessage = null; + } + } + processPendingHalfClose() { + if (this.pendingHalfClose) { + this.nextCall.halfClose(); + } + } + start(metadata, interceptingListener) { + var _a, _b, _c, _d, _e, _f; + const fullInterceptingListener = { + onReceiveMetadata: (_b = (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.bind(interceptingListener)) !== null && _b !== void 0 ? _b : (metadata => { }), + onReceiveMessage: (_d = (_c = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _c === void 0 ? void 0 : _c.bind(interceptingListener)) !== null && _d !== void 0 ? _d : (message => { }), + onReceiveStatus: (_f = (_e = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _e === void 0 ? void 0 : _e.bind(interceptingListener)) !== null && _f !== void 0 ? _f : (status => { }), + }; + this.processingMetadata = true; + this.requester.start(metadata, fullInterceptingListener, (md, listener) => { + var _a, _b, _c; + this.processingMetadata = false; + let finalInterceptingListener; + if ((0, call_interface_1.isInterceptingListener)(listener)) { + finalInterceptingListener = listener; + } + else { + const fullListener = { + onReceiveMetadata: (_a = listener.onReceiveMetadata) !== null && _a !== void 0 ? _a : defaultListener.onReceiveMetadata, + onReceiveMessage: (_b = listener.onReceiveMessage) !== null && _b !== void 0 ? _b : defaultListener.onReceiveMessage, + onReceiveStatus: (_c = listener.onReceiveStatus) !== null && _c !== void 0 ? _c : defaultListener.onReceiveStatus, + }; + finalInterceptingListener = new call_interface_1.InterceptingListenerImpl(fullListener, fullInterceptingListener); + } + this.nextCall.start(md, finalInterceptingListener); + this.processPendingMessage(); + this.processPendingHalfClose(); + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessageWithContext(context, message) { + this.processingMessage = true; + this.requester.sendMessage(message, finalMessage => { + this.processingMessage = false; + if (this.processingMetadata) { + this.pendingMessageContext = context; + this.pendingMessage = message; + } + else { + this.nextCall.sendMessageWithContext(context, finalMessage); + this.processPendingHalfClose(); + } + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessage(message) { + this.sendMessageWithContext({}, message); + } + startRead() { + this.nextCall.startRead(); + } + halfClose() { + this.requester.halfClose(() => { + if (this.processingMetadata || this.processingMessage) { + this.pendingHalfClose = true; + } + else { + this.nextCall.halfClose(); + } + }); + } + getAuthContext() { + return this.nextCall.getAuthContext(); + } +} +exports.InterceptingCall = InterceptingCall; +function getCall(channel, path, options) { + var _a, _b; + const deadline = (_a = options.deadline) !== null && _a !== void 0 ? _a : Infinity; + const host = options.host; + const parent = (_b = options.parent) !== null && _b !== void 0 ? _b : null; + const propagateFlags = options.propagate_flags; + const credentials = options.credentials; + const call = channel.createCall(path, deadline, host, parent, propagateFlags); + if (credentials) { + call.setCredentials(credentials); + } + return call; +} +/** + * InterceptingCall implementation that directly owns the underlying Call + * object and handles serialization and deseraizliation. + */ +class BaseInterceptingCall { + constructor(call, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + methodDefinition) { + this.call = call; + this.methodDefinition = methodDefinition; + } + cancelWithStatus(status, details) { + this.call.cancelWithStatus(status, details); + } + getPeer() { + return this.call.getPeer(); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessageWithContext(context, message) { + let serialized; + try { + serialized = this.methodDefinition.requestSerialize(message); + } + catch (e) { + this.call.cancelWithStatus(constants_1.Status.INTERNAL, `Request message serialization failure: ${(0, error_1.getErrorMessage)(e)}`); + return; + } + this.call.sendMessageWithContext(context, serialized); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessage(message) { + this.sendMessageWithContext({}, message); + } + start(metadata, interceptingListener) { + let readError = null; + this.call.start(metadata, { + onReceiveMetadata: metadata => { + var _a; + (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, metadata); + }, + onReceiveMessage: message => { + var _a; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let deserialized; + try { + deserialized = this.methodDefinition.responseDeserialize(message); + } + catch (e) { + readError = { + code: constants_1.Status.INTERNAL, + details: `Response message parsing error: ${(0, error_1.getErrorMessage)(e)}`, + metadata: new metadata_1.Metadata(), + }; + this.call.cancelWithStatus(readError.code, readError.details); + return; + } + (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, deserialized); + }, + onReceiveStatus: status => { + var _a, _b; + if (readError) { + (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, readError); + } + else { + (_b = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _b === void 0 ? void 0 : _b.call(interceptingListener, status); + } + }, + }); + } + startRead() { + this.call.startRead(); + } + halfClose() { + this.call.halfClose(); + } + getAuthContext() { + return this.call.getAuthContext(); + } +} +/** + * BaseInterceptingCall with special-cased behavior for methods with unary + * responses. + */ +class BaseUnaryInterceptingCall extends BaseInterceptingCall { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + constructor(call, methodDefinition) { + super(call, methodDefinition); + } + start(metadata, listener) { + var _a, _b; + let receivedMessage = false; + const wrapperListener = { + onReceiveMetadata: (_b = (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.bind(listener)) !== null && _b !== void 0 ? _b : (metadata => { }), + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage: (message) => { + var _a; + receivedMessage = true; + (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(listener, message); + }, + onReceiveStatus: (status) => { + var _a, _b; + if (!receivedMessage) { + (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(listener, null); + } + (_b = listener === null || listener === void 0 ? void 0 : listener.onReceiveStatus) === null || _b === void 0 ? void 0 : _b.call(listener, status); + }, + }; + super.start(metadata, wrapperListener); + this.call.startRead(); + } +} +/** + * BaseInterceptingCall with special-cased behavior for methods with streaming + * responses. + */ +class BaseStreamingInterceptingCall extends BaseInterceptingCall { +} +function getBottomInterceptingCall(channel, options, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +methodDefinition) { + const call = getCall(channel, methodDefinition.path, options); + if (methodDefinition.responseStream) { + return new BaseStreamingInterceptingCall(call, methodDefinition); + } + else { + return new BaseUnaryInterceptingCall(call, methodDefinition); + } +} +function getInterceptingCall(interceptorArgs, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +methodDefinition, options, channel) { + if (interceptorArgs.clientInterceptors.length > 0 && + interceptorArgs.clientInterceptorProviders.length > 0) { + throw new InterceptorConfigurationError('Both interceptors and interceptor_providers were passed as options ' + + 'to the client constructor. Only one of these is allowed.'); + } + if (interceptorArgs.callInterceptors.length > 0 && + interceptorArgs.callInterceptorProviders.length > 0) { + throw new InterceptorConfigurationError('Both interceptors and interceptor_providers were passed as call ' + + 'options. Only one of these is allowed.'); + } + let interceptors = []; + // Interceptors passed to the call override interceptors passed to the client constructor + if (interceptorArgs.callInterceptors.length > 0 || + interceptorArgs.callInterceptorProviders.length > 0) { + interceptors = [] + .concat(interceptorArgs.callInterceptors, interceptorArgs.callInterceptorProviders.map(provider => provider(methodDefinition))) + .filter(interceptor => interceptor); + // Filter out falsy values when providers return nothing + } + else { + interceptors = [] + .concat(interceptorArgs.clientInterceptors, interceptorArgs.clientInterceptorProviders.map(provider => provider(methodDefinition))) + .filter(interceptor => interceptor); + // Filter out falsy values when providers return nothing + } + const interceptorOptions = Object.assign({}, options, { + method_definition: methodDefinition, + }); + /* For each interceptor in the list, the nextCall function passed to it is + * based on the next interceptor in the list, using a nextCall function + * constructed with the following interceptor in the list, and so on. The + * initialValue, which is effectively at the end of the list, is a nextCall + * function that invokes getBottomInterceptingCall, the result of which + * handles (de)serialization and also gets the underlying call from the + * channel. */ + const getCall = interceptors.reduceRight((nextCall, nextInterceptor) => { + return currentOptions => nextInterceptor(currentOptions, nextCall); + }, (finalOptions) => getBottomInterceptingCall(channel, finalOptions, methodDefinition)); + return getCall(interceptorOptions); +} +//# sourceMappingURL=client-interceptors.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/client-interceptors.js.map b/node_modules/@grpc/grpc-js/build/src/client-interceptors.js.map new file mode 100644 index 0000000..9a961ea --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/client-interceptors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"client-interceptors.js","sourceRoot":"","sources":["../../src/client-interceptors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAofH,kDAqEC;AAvjBD,yCAAsC;AACtC,qDAY0B;AAC1B,2CAAqC;AAIrC,mCAA0C;AAG1C;;;GAGG;AACH,MAAa,6BAA8B,SAAQ,KAAK;IACtD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,+BAA+B,CAAC;QAC5C,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,6BAA6B,CAAC,CAAC;IAC/D,CAAC;CACF;AAND,sEAMC;AAsCD,MAAa,eAAe;IAA5B;QACU,aAAQ,GAAiC,SAAS,CAAC;QACnD,YAAO,GAAgC,SAAS,CAAC;QACjD,WAAM,GAA+B,SAAS,CAAC;IAwBzD,CAAC;IAtBC,qBAAqB,CAAC,iBAAmC;QACvD,IAAI,CAAC,QAAQ,GAAG,iBAAiB,CAAC;QAClC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,oBAAoB,CAAC,gBAAiC;QACpD,IAAI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AAe,CAAC,wBAAwB,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CACtD,QAAQ,CAAC,gBAAgB,CAAC,CAC3B,CACF;aACA,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC,WAAW,CAAC,CAAC;QACtC,wDAAwD;IAC1D,CAAC;SAAM,CAAC;QACN,YAAY,GAAI,EAAoB;aACjC,MAAM,CACL,eAAe,CAAC,kBAAkB,EAClC,eAAe,CAAC,0BAA0B,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CACxD,QAAQ,CAAC,gBAAgB,CAAC,CAC3B,CACF;aACA,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC,WAAW,CAAC,CAAC;QACtC,wDAAwD;IAC1D,CAAC;IACD,MAAM,kBAAkB,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,OAAO,EAAE;QACpD,iBAAiB,EAAE,gBAAgB;KACpC,CAAC,CAAC;IACH;;;;;;kBAMc;IACd,MAAM,OAAO,GAAa,YAAY,CAAC,WAAW,CAChD,CAAC,QAAkB,EAAE,eAA4B,EAAE,EAAE;QACnD,OAAO,cAAc,CAAC,EAAE,CAAC,eAAe,CAAC,cAAc,EAAE,QAAQ,CAAC,CAAC;IACrE,CAAC,EACD,CAAC,YAAgC,EAAE,EAAE,CACnC,yBAAyB,CAAC,OAAO,EAAE,YAAY,EAAE,gBAAgB,CAAC,CACrE,CAAC;IACF,OAAO,OAAO,CAAC,kBAAkB,CAAC,CAAC;AACrC,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/client.d.ts b/node_modules/@grpc/grpc-js/build/src/client.d.ts new file mode 100644 index 0000000..5c71ae4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/client.d.ts @@ -0,0 +1,74 @@ +import { ClientDuplexStream, ClientReadableStream, ClientUnaryCall, ClientWritableStream, ServiceError, SurfaceCall } from './call'; +import { CallCredentials } from './call-credentials'; +import { Channel } from './channel'; +import { ChannelCredentials } from './channel-credentials'; +import { ChannelOptions } from './channel-options'; +import { Metadata } from './metadata'; +import { ClientMethodDefinition } from './make-client'; +import { Interceptor, InterceptorProvider } from './client-interceptors'; +import { ServerUnaryCall, ServerReadableStream, ServerWritableStream, ServerDuplexStream } from './server-call'; +import { Deadline } from './deadline'; +declare const CHANNEL_SYMBOL: unique symbol; +declare const INTERCEPTOR_SYMBOL: unique symbol; +declare const INTERCEPTOR_PROVIDER_SYMBOL: unique symbol; +declare const CALL_INVOCATION_TRANSFORMER_SYMBOL: unique symbol; +export interface UnaryCallback { + (err: ServiceError | null, value?: ResponseType): void; +} +export interface CallOptions { + deadline?: Deadline; + host?: string; + parent?: ServerUnaryCall | ServerReadableStream | ServerWritableStream | ServerDuplexStream; + propagate_flags?: number; + credentials?: CallCredentials; + interceptors?: Interceptor[]; + interceptor_providers?: InterceptorProvider[]; +} +export interface CallProperties { + argument?: RequestType; + metadata: Metadata; + call: SurfaceCall; + channel: Channel; + methodDefinition: ClientMethodDefinition; + callOptions: CallOptions; + callback?: UnaryCallback; +} +export interface CallInvocationTransformer { + (callProperties: CallProperties): CallProperties; +} +export type ClientOptions = Partial & { + channelOverride?: Channel; + channelFactoryOverride?: (address: string, credentials: ChannelCredentials, options: ClientOptions) => Channel; + interceptors?: Interceptor[]; + interceptor_providers?: InterceptorProvider[]; + callInvocationTransformer?: CallInvocationTransformer; +}; +/** + * A generic gRPC client. Primarily useful as a base class for all generated + * clients. + */ +export declare class Client { + private readonly [CHANNEL_SYMBOL]; + private readonly [INTERCEPTOR_SYMBOL]; + private readonly [INTERCEPTOR_PROVIDER_SYMBOL]; + private readonly [CALL_INVOCATION_TRANSFORMER_SYMBOL]?; + constructor(address: string, credentials: ChannelCredentials, options?: ClientOptions); + close(): void; + getChannel(): Channel; + waitForReady(deadline: Deadline, callback: (error?: Error) => void): void; + private checkOptionalUnaryResponseArguments; + makeUnaryRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, argument: RequestType, metadata: Metadata, options: CallOptions, callback: UnaryCallback): ClientUnaryCall; + makeUnaryRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, argument: RequestType, metadata: Metadata, callback: UnaryCallback): ClientUnaryCall; + makeUnaryRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, argument: RequestType, options: CallOptions, callback: UnaryCallback): ClientUnaryCall; + makeUnaryRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, argument: RequestType, callback: UnaryCallback): ClientUnaryCall; + makeClientStreamRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, metadata: Metadata, options: CallOptions, callback: UnaryCallback): ClientWritableStream; + makeClientStreamRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, metadata: Metadata, callback: UnaryCallback): ClientWritableStream; + makeClientStreamRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, options: CallOptions, callback: UnaryCallback): ClientWritableStream; + makeClientStreamRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, callback: UnaryCallback): ClientWritableStream; + private checkMetadataAndOptions; + makeServerStreamRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, argument: RequestType, metadata: Metadata, options?: CallOptions): ClientReadableStream; + makeServerStreamRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, argument: RequestType, options?: CallOptions): ClientReadableStream; + makeBidiStreamRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, metadata: Metadata, options?: CallOptions): ClientDuplexStream; + makeBidiStreamRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, options?: CallOptions): ClientDuplexStream; +} +export {}; diff --git a/node_modules/@grpc/grpc-js/build/src/client.js b/node_modules/@grpc/grpc-js/build/src/client.js new file mode 100644 index 0000000..9cd559a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/client.js @@ -0,0 +1,433 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Client = void 0; +const call_1 = require("./call"); +const channel_1 = require("./channel"); +const connectivity_state_1 = require("./connectivity-state"); +const constants_1 = require("./constants"); +const metadata_1 = require("./metadata"); +const client_interceptors_1 = require("./client-interceptors"); +const CHANNEL_SYMBOL = Symbol(); +const INTERCEPTOR_SYMBOL = Symbol(); +const INTERCEPTOR_PROVIDER_SYMBOL = Symbol(); +const CALL_INVOCATION_TRANSFORMER_SYMBOL = Symbol(); +function isFunction(arg) { + return typeof arg === 'function'; +} +function getErrorStackString(error) { + var _a; + return ((_a = error.stack) === null || _a === void 0 ? void 0 : _a.split('\n').slice(1).join('\n')) || 'no stack trace available'; +} +/** + * A generic gRPC client. Primarily useful as a base class for all generated + * clients. + */ +class Client { + constructor(address, credentials, options = {}) { + var _a, _b; + options = Object.assign({}, options); + this[INTERCEPTOR_SYMBOL] = (_a = options.interceptors) !== null && _a !== void 0 ? _a : []; + delete options.interceptors; + this[INTERCEPTOR_PROVIDER_SYMBOL] = (_b = options.interceptor_providers) !== null && _b !== void 0 ? _b : []; + delete options.interceptor_providers; + if (this[INTERCEPTOR_SYMBOL].length > 0 && + this[INTERCEPTOR_PROVIDER_SYMBOL].length > 0) { + throw new Error('Both interceptors and interceptor_providers were passed as options ' + + 'to the client constructor. Only one of these is allowed.'); + } + this[CALL_INVOCATION_TRANSFORMER_SYMBOL] = + options.callInvocationTransformer; + delete options.callInvocationTransformer; + if (options.channelOverride) { + this[CHANNEL_SYMBOL] = options.channelOverride; + } + else if (options.channelFactoryOverride) { + const channelFactoryOverride = options.channelFactoryOverride; + delete options.channelFactoryOverride; + this[CHANNEL_SYMBOL] = channelFactoryOverride(address, credentials, options); + } + else { + this[CHANNEL_SYMBOL] = new channel_1.ChannelImplementation(address, credentials, options); + } + } + close() { + this[CHANNEL_SYMBOL].close(); + } + getChannel() { + return this[CHANNEL_SYMBOL]; + } + waitForReady(deadline, callback) { + const checkState = (err) => { + if (err) { + callback(new Error('Failed to connect before the deadline')); + return; + } + let newState; + try { + newState = this[CHANNEL_SYMBOL].getConnectivityState(true); + } + catch (e) { + callback(new Error('The channel has been closed')); + return; + } + if (newState === connectivity_state_1.ConnectivityState.READY) { + callback(); + } + else { + try { + this[CHANNEL_SYMBOL].watchConnectivityState(newState, deadline, checkState); + } + catch (e) { + callback(new Error('The channel has been closed')); + } + } + }; + setImmediate(checkState); + } + checkOptionalUnaryResponseArguments(arg1, arg2, arg3) { + if (isFunction(arg1)) { + return { metadata: new metadata_1.Metadata(), options: {}, callback: arg1 }; + } + else if (isFunction(arg2)) { + if (arg1 instanceof metadata_1.Metadata) { + return { metadata: arg1, options: {}, callback: arg2 }; + } + else { + return { metadata: new metadata_1.Metadata(), options: arg1, callback: arg2 }; + } + } + else { + if (!(arg1 instanceof metadata_1.Metadata && + arg2 instanceof Object && + isFunction(arg3))) { + throw new Error('Incorrect arguments passed'); + } + return { metadata: arg1, options: arg2, callback: arg3 }; + } + } + makeUnaryRequest(method, serialize, deserialize, argument, metadata, options, callback) { + var _a, _b; + const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options, callback); + const methodDefinition = { + path: method, + requestStream: false, + responseStream: false, + requestSerialize: serialize, + responseDeserialize: deserialize, + }; + let callProperties = { + argument: argument, + metadata: checkedArguments.metadata, + call: new call_1.ClientUnaryCallImpl(), + channel: this[CHANNEL_SYMBOL], + methodDefinition: methodDefinition, + callOptions: checkedArguments.options, + callback: checkedArguments.callback, + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); + } + const emitter = callProperties.call; + const interceptorArgs = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], + callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [], + }; + const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); + /* This needs to happen before the emitter is used. Unfortunately we can't + * enforce this with the type system. We need to construct this emitter + * before calling the CallInvocationTransformer, and we need to create the + * call after that. */ + emitter.call = call; + let responseMessage = null; + let receivedStatus = false; + let callerStackError = new Error(); + call.start(callProperties.metadata, { + onReceiveMetadata: metadata => { + emitter.emit('metadata', metadata); + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message) { + if (responseMessage !== null) { + call.cancelWithStatus(constants_1.Status.UNIMPLEMENTED, 'Too many responses received'); + } + responseMessage = message; + }, + onReceiveStatus(status) { + if (receivedStatus) { + return; + } + receivedStatus = true; + if (status.code === constants_1.Status.OK) { + if (responseMessage === null) { + const callerStack = getErrorStackString(callerStackError); + callProperties.callback((0, call_1.callErrorFromStatus)({ + code: constants_1.Status.UNIMPLEMENTED, + details: 'No message received', + metadata: status.metadata, + }, callerStack)); + } + else { + callProperties.callback(null, responseMessage); + } + } + else { + const callerStack = getErrorStackString(callerStackError); + callProperties.callback((0, call_1.callErrorFromStatus)(status, callerStack)); + } + /* Avoid retaining the callerStackError object in the call context of + * the status event handler. */ + callerStackError = null; + emitter.emit('status', status); + }, + }); + call.sendMessage(argument); + call.halfClose(); + return emitter; + } + makeClientStreamRequest(method, serialize, deserialize, metadata, options, callback) { + var _a, _b; + const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options, callback); + const methodDefinition = { + path: method, + requestStream: true, + responseStream: false, + requestSerialize: serialize, + responseDeserialize: deserialize, + }; + let callProperties = { + metadata: checkedArguments.metadata, + call: new call_1.ClientWritableStreamImpl(serialize), + channel: this[CHANNEL_SYMBOL], + methodDefinition: methodDefinition, + callOptions: checkedArguments.options, + callback: checkedArguments.callback, + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); + } + const emitter = callProperties.call; + const interceptorArgs = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], + callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [], + }; + const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); + /* This needs to happen before the emitter is used. Unfortunately we can't + * enforce this with the type system. We need to construct this emitter + * before calling the CallInvocationTransformer, and we need to create the + * call after that. */ + emitter.call = call; + let responseMessage = null; + let receivedStatus = false; + let callerStackError = new Error(); + call.start(callProperties.metadata, { + onReceiveMetadata: metadata => { + emitter.emit('metadata', metadata); + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message) { + if (responseMessage !== null) { + call.cancelWithStatus(constants_1.Status.UNIMPLEMENTED, 'Too many responses received'); + } + responseMessage = message; + call.startRead(); + }, + onReceiveStatus(status) { + if (receivedStatus) { + return; + } + receivedStatus = true; + if (status.code === constants_1.Status.OK) { + if (responseMessage === null) { + const callerStack = getErrorStackString(callerStackError); + callProperties.callback((0, call_1.callErrorFromStatus)({ + code: constants_1.Status.UNIMPLEMENTED, + details: 'No message received', + metadata: status.metadata, + }, callerStack)); + } + else { + callProperties.callback(null, responseMessage); + } + } + else { + const callerStack = getErrorStackString(callerStackError); + callProperties.callback((0, call_1.callErrorFromStatus)(status, callerStack)); + } + /* Avoid retaining the callerStackError object in the call context of + * the status event handler. */ + callerStackError = null; + emitter.emit('status', status); + }, + }); + return emitter; + } + checkMetadataAndOptions(arg1, arg2) { + let metadata; + let options; + if (arg1 instanceof metadata_1.Metadata) { + metadata = arg1; + if (arg2) { + options = arg2; + } + else { + options = {}; + } + } + else { + if (arg1) { + options = arg1; + } + else { + options = {}; + } + metadata = new metadata_1.Metadata(); + } + return { metadata, options }; + } + makeServerStreamRequest(method, serialize, deserialize, argument, metadata, options) { + var _a, _b; + const checkedArguments = this.checkMetadataAndOptions(metadata, options); + const methodDefinition = { + path: method, + requestStream: false, + responseStream: true, + requestSerialize: serialize, + responseDeserialize: deserialize, + }; + let callProperties = { + argument: argument, + metadata: checkedArguments.metadata, + call: new call_1.ClientReadableStreamImpl(deserialize), + channel: this[CHANNEL_SYMBOL], + methodDefinition: methodDefinition, + callOptions: checkedArguments.options, + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); + } + const stream = callProperties.call; + const interceptorArgs = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], + callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [], + }; + const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); + /* This needs to happen before the emitter is used. Unfortunately we can't + * enforce this with the type system. We need to construct this emitter + * before calling the CallInvocationTransformer, and we need to create the + * call after that. */ + stream.call = call; + let receivedStatus = false; + let callerStackError = new Error(); + call.start(callProperties.metadata, { + onReceiveMetadata(metadata) { + stream.emit('metadata', metadata); + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message) { + stream.push(message); + }, + onReceiveStatus(status) { + if (receivedStatus) { + return; + } + receivedStatus = true; + stream.push(null); + if (status.code !== constants_1.Status.OK) { + const callerStack = getErrorStackString(callerStackError); + stream.emit('error', (0, call_1.callErrorFromStatus)(status, callerStack)); + } + /* Avoid retaining the callerStackError object in the call context of + * the status event handler. */ + callerStackError = null; + stream.emit('status', status); + }, + }); + call.sendMessage(argument); + call.halfClose(); + return stream; + } + makeBidiStreamRequest(method, serialize, deserialize, metadata, options) { + var _a, _b; + const checkedArguments = this.checkMetadataAndOptions(metadata, options); + const methodDefinition = { + path: method, + requestStream: true, + responseStream: true, + requestSerialize: serialize, + responseDeserialize: deserialize, + }; + let callProperties = { + metadata: checkedArguments.metadata, + call: new call_1.ClientDuplexStreamImpl(serialize, deserialize), + channel: this[CHANNEL_SYMBOL], + methodDefinition: methodDefinition, + callOptions: checkedArguments.options, + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); + } + const stream = callProperties.call; + const interceptorArgs = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], + callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [], + }; + const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); + /* This needs to happen before the emitter is used. Unfortunately we can't + * enforce this with the type system. We need to construct this emitter + * before calling the CallInvocationTransformer, and we need to create the + * call after that. */ + stream.call = call; + let receivedStatus = false; + let callerStackError = new Error(); + call.start(callProperties.metadata, { + onReceiveMetadata(metadata) { + stream.emit('metadata', metadata); + }, + onReceiveMessage(message) { + stream.push(message); + }, + onReceiveStatus(status) { + if (receivedStatus) { + return; + } + receivedStatus = true; + stream.push(null); + if (status.code !== constants_1.Status.OK) { + const callerStack = getErrorStackString(callerStackError); + stream.emit('error', (0, call_1.callErrorFromStatus)(status, callerStack)); + } + /* Avoid retaining the callerStackError object in the call context of + * the status event handler. */ + callerStackError = null; + stream.emit('status', status); + }, + }); + return stream; + } +} +exports.Client = Client; +//# sourceMappingURL=client.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/client.js.map b/node_modules/@grpc/grpc-js/build/src/client.js.map new file mode 100644 index 0000000..8b62cc5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/client.js.map @@ -0,0 +1 @@ +{"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/client.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,iCAYgB;AAGhB,uCAA2D;AAC3D,6DAAyD;AAGzD,2CAAqC;AACrC,yCAAsC;AAEtC,+DAM+B;AAS/B,MAAM,cAAc,GAAG,MAAM,EAAE,CAAC;AAChC,MAAM,kBAAkB,GAAG,MAAM,EAAE,CAAC;AACpC,MAAM,2BAA2B,GAAG,MAAM,EAAE,CAAC;AAC7C,MAAM,kCAAkC,GAAG,MAAM,EAAE,CAAC;AAEpD,SAAS,UAAU,CACjB,GAAqE;IAErE,OAAO,OAAO,GAAG,KAAK,UAAU,CAAC;AACnC,CAAC;AAgDD,SAAS,mBAAmB,CAAC,KAAY;;IACvC,OAAO,CAAA,MAAA,KAAK,CAAC,KAAK,0CAAE,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,KAAI,0BAA0B,CAAC;AACpF,CAAC;AAED;;;GAGG;AACH,MAAa,MAAM;IAKjB,YACE,OAAe,EACf,WAA+B,EAC/B,UAAyB,EAAE;;QAE3B,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACrC,IAAI,CAAC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C;QACH,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAplBD,wBAolBC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/compression-algorithms.d.ts b/node_modules/@grpc/grpc-js/build/src/compression-algorithms.d.ts new file mode 100644 index 0000000..555b222 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/compression-algorithms.d.ts @@ -0,0 +1,5 @@ +export declare enum CompressionAlgorithms { + identity = 0, + deflate = 1, + gzip = 2 +} diff --git a/node_modules/@grpc/grpc-js/build/src/compression-algorithms.js b/node_modules/@grpc/grpc-js/build/src/compression-algorithms.js new file mode 100644 index 0000000..15a4f00 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/compression-algorithms.js @@ -0,0 +1,26 @@ +"use strict"; +/* + * Copyright 2021 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CompressionAlgorithms = void 0; +var CompressionAlgorithms; +(function (CompressionAlgorithms) { + CompressionAlgorithms[CompressionAlgorithms["identity"] = 0] = "identity"; + CompressionAlgorithms[CompressionAlgorithms["deflate"] = 1] = "deflate"; + CompressionAlgorithms[CompressionAlgorithms["gzip"] = 2] = "gzip"; +})(CompressionAlgorithms || (exports.CompressionAlgorithms = CompressionAlgorithms = {})); +//# sourceMappingURL=compression-algorithms.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/compression-algorithms.js.map b/node_modules/@grpc/grpc-js/build/src/compression-algorithms.js.map new file mode 100644 index 0000000..760772f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/compression-algorithms.js.map @@ -0,0 +1 @@ +{"version":3,"file":"compression-algorithms.js","sourceRoot":"","sources":["../../src/compression-algorithms.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,IAAY,qBAIX;AAJD,WAAY,qBAAqB;IAC/B,yEAAY,CAAA;IACZ,uEAAW,CAAA;IACX,iEAAQ,CAAA;AACV,CAAC,EAJW,qBAAqB,qCAArB,qBAAqB,QAIhC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/compression-filter.d.ts b/node_modules/@grpc/grpc-js/build/src/compression-filter.d.ts new file mode 100644 index 0000000..d1667c3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/compression-filter.d.ts @@ -0,0 +1,28 @@ +import { WriteObject } from './call-interface'; +import { Channel } from './channel'; +import { ChannelOptions } from './channel-options'; +import { BaseFilter, Filter, FilterFactory } from './filter'; +import { Metadata } from './metadata'; +type SharedCompressionFilterConfig = { + serverSupportedEncodingHeader?: string; +}; +export declare class CompressionFilter extends BaseFilter implements Filter { + private sharedFilterConfig; + private sendCompression; + private receiveCompression; + private currentCompressionAlgorithm; + private maxReceiveMessageLength; + private maxSendMessageLength; + constructor(channelOptions: ChannelOptions, sharedFilterConfig: SharedCompressionFilterConfig); + sendMetadata(metadata: Promise): Promise; + receiveMetadata(metadata: Metadata): Metadata; + sendMessage(message: Promise): Promise; + receiveMessage(message: Promise): Promise>; +} +export declare class CompressionFilterFactory implements FilterFactory { + private readonly options; + private sharedFilterConfig; + constructor(channel: Channel, options: ChannelOptions); + createFilter(): CompressionFilter; +} +export {}; diff --git a/node_modules/@grpc/grpc-js/build/src/compression-filter.js b/node_modules/@grpc/grpc-js/build/src/compression-filter.js new file mode 100644 index 0000000..a0af9f9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/compression-filter.js @@ -0,0 +1,295 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CompressionFilterFactory = exports.CompressionFilter = void 0; +const zlib = require("zlib"); +const compression_algorithms_1 = require("./compression-algorithms"); +const constants_1 = require("./constants"); +const filter_1 = require("./filter"); +const logging = require("./logging"); +const isCompressionAlgorithmKey = (key) => { + return (typeof key === 'number' && typeof compression_algorithms_1.CompressionAlgorithms[key] === 'string'); +}; +class CompressionHandler { + /** + * @param message Raw uncompressed message bytes + * @param compress Indicates whether the message should be compressed + * @return Framed message, compressed if applicable + */ + async writeMessage(message, compress) { + let messageBuffer = message; + if (compress) { + messageBuffer = await this.compressMessage(messageBuffer); + } + const output = Buffer.allocUnsafe(messageBuffer.length + 5); + output.writeUInt8(compress ? 1 : 0, 0); + output.writeUInt32BE(messageBuffer.length, 1); + messageBuffer.copy(output, 5); + return output; + } + /** + * @param data Framed message, possibly compressed + * @return Uncompressed message + */ + async readMessage(data) { + const compressed = data.readUInt8(0) === 1; + let messageBuffer = data.slice(5); + if (compressed) { + messageBuffer = await this.decompressMessage(messageBuffer); + } + return messageBuffer; + } +} +class IdentityHandler extends CompressionHandler { + async compressMessage(message) { + return message; + } + async writeMessage(message, compress) { + const output = Buffer.allocUnsafe(message.length + 5); + /* With "identity" compression, messages should always be marked as + * uncompressed */ + output.writeUInt8(0, 0); + output.writeUInt32BE(message.length, 1); + message.copy(output, 5); + return output; + } + decompressMessage(message) { + return Promise.reject(new Error('Received compressed message but "grpc-encoding" header was identity')); + } +} +class DeflateHandler extends CompressionHandler { + constructor(maxRecvMessageLength) { + super(); + this.maxRecvMessageLength = maxRecvMessageLength; + } + compressMessage(message) { + return new Promise((resolve, reject) => { + zlib.deflate(message, (err, output) => { + if (err) { + reject(err); + } + else { + resolve(output); + } + }); + }); + } + decompressMessage(message) { + return new Promise((resolve, reject) => { + let totalLength = 0; + const messageParts = []; + const decompresser = zlib.createInflate(); + decompresser.on('data', (chunk) => { + messageParts.push(chunk); + totalLength += chunk.byteLength; + if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) { + decompresser.destroy(); + reject({ + code: constants_1.Status.RESOURCE_EXHAUSTED, + details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}` + }); + } + }); + decompresser.on('end', () => { + resolve(Buffer.concat(messageParts)); + }); + decompresser.write(message); + decompresser.end(); + }); + } +} +class GzipHandler extends CompressionHandler { + constructor(maxRecvMessageLength) { + super(); + this.maxRecvMessageLength = maxRecvMessageLength; + } + compressMessage(message) { + return new Promise((resolve, reject) => { + zlib.gzip(message, (err, output) => { + if (err) { + reject(err); + } + else { + resolve(output); + } + }); + }); + } + decompressMessage(message) { + return new Promise((resolve, reject) => { + let totalLength = 0; + const messageParts = []; + const decompresser = zlib.createGunzip(); + decompresser.on('data', (chunk) => { + messageParts.push(chunk); + totalLength += chunk.byteLength; + if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) { + decompresser.destroy(); + reject({ + code: constants_1.Status.RESOURCE_EXHAUSTED, + details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}` + }); + } + }); + decompresser.on('end', () => { + resolve(Buffer.concat(messageParts)); + }); + decompresser.write(message); + decompresser.end(); + }); + } +} +class UnknownHandler extends CompressionHandler { + constructor(compressionName) { + super(); + this.compressionName = compressionName; + } + compressMessage(message) { + return Promise.reject(new Error(`Received message compressed with unsupported compression method ${this.compressionName}`)); + } + decompressMessage(message) { + // This should be unreachable + return Promise.reject(new Error(`Compression method not supported: ${this.compressionName}`)); + } +} +function getCompressionHandler(compressionName, maxReceiveMessageSize) { + switch (compressionName) { + case 'identity': + return new IdentityHandler(); + case 'deflate': + return new DeflateHandler(maxReceiveMessageSize); + case 'gzip': + return new GzipHandler(maxReceiveMessageSize); + default: + return new UnknownHandler(compressionName); + } +} +class CompressionFilter extends filter_1.BaseFilter { + constructor(channelOptions, sharedFilterConfig) { + var _a, _b, _c; + super(); + this.sharedFilterConfig = sharedFilterConfig; + this.sendCompression = new IdentityHandler(); + this.receiveCompression = new IdentityHandler(); + this.currentCompressionAlgorithm = 'identity'; + const compressionAlgorithmKey = channelOptions['grpc.default_compression_algorithm']; + this.maxReceiveMessageLength = (_a = channelOptions['grpc.max_receive_message_length']) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; + this.maxSendMessageLength = (_b = channelOptions['grpc.max_send_message_length']) !== null && _b !== void 0 ? _b : constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH; + if (compressionAlgorithmKey !== undefined) { + if (isCompressionAlgorithmKey(compressionAlgorithmKey)) { + const clientSelectedEncoding = compression_algorithms_1.CompressionAlgorithms[compressionAlgorithmKey]; + const serverSupportedEncodings = (_c = sharedFilterConfig.serverSupportedEncodingHeader) === null || _c === void 0 ? void 0 : _c.split(','); + /** + * There are two possible situations here: + * 1) We don't have any info yet from the server about what compression it supports + * In that case we should just use what the client tells us to use + * 2) We've previously received a response from the server including a grpc-accept-encoding header + * In that case we only want to use the encoding chosen by the client if the server supports it + */ + if (!serverSupportedEncodings || + serverSupportedEncodings.includes(clientSelectedEncoding)) { + this.currentCompressionAlgorithm = clientSelectedEncoding; + this.sendCompression = getCompressionHandler(this.currentCompressionAlgorithm, -1); + } + } + else { + logging.log(constants_1.LogVerbosity.ERROR, `Invalid value provided for grpc.default_compression_algorithm option: ${compressionAlgorithmKey}`); + } + } + } + async sendMetadata(metadata) { + const headers = await metadata; + headers.set('grpc-accept-encoding', 'identity,deflate,gzip'); + headers.set('accept-encoding', 'identity'); + // No need to send the header if it's "identity" - behavior is identical; save the bandwidth + if (this.currentCompressionAlgorithm === 'identity') { + headers.remove('grpc-encoding'); + } + else { + headers.set('grpc-encoding', this.currentCompressionAlgorithm); + } + return headers; + } + receiveMetadata(metadata) { + const receiveEncoding = metadata.get('grpc-encoding'); + if (receiveEncoding.length > 0) { + const encoding = receiveEncoding[0]; + if (typeof encoding === 'string') { + this.receiveCompression = getCompressionHandler(encoding, this.maxReceiveMessageLength); + } + } + metadata.remove('grpc-encoding'); + /* Check to see if the compression we're using to send messages is supported by the server + * If not, reset the sendCompression filter and have it use the default IdentityHandler */ + const serverSupportedEncodingsHeader = metadata.get('grpc-accept-encoding')[0]; + if (serverSupportedEncodingsHeader) { + this.sharedFilterConfig.serverSupportedEncodingHeader = + serverSupportedEncodingsHeader; + const serverSupportedEncodings = serverSupportedEncodingsHeader.split(','); + if (!serverSupportedEncodings.includes(this.currentCompressionAlgorithm)) { + this.sendCompression = new IdentityHandler(); + this.currentCompressionAlgorithm = 'identity'; + } + } + metadata.remove('grpc-accept-encoding'); + return metadata; + } + async sendMessage(message) { + var _a; + /* This filter is special. The input message is the bare message bytes, + * and the output is a framed and possibly compressed message. For this + * reason, this filter should be at the bottom of the filter stack */ + const resolvedMessage = await message; + if (this.maxSendMessageLength !== -1 && resolvedMessage.message.length > this.maxSendMessageLength) { + throw { + code: constants_1.Status.RESOURCE_EXHAUSTED, + details: `Attempted to send message with a size larger than ${this.maxSendMessageLength}` + }; + } + let compress; + if (this.sendCompression instanceof IdentityHandler) { + compress = false; + } + else { + compress = (((_a = resolvedMessage.flags) !== null && _a !== void 0 ? _a : 0) & 2 /* WriteFlags.NoCompress */) === 0; + } + return { + message: await this.sendCompression.writeMessage(resolvedMessage.message, compress), + flags: resolvedMessage.flags, + }; + } + async receiveMessage(message) { + /* This filter is also special. The input message is framed and possibly + * compressed, and the output message is deframed and uncompressed. So + * this is another reason that this filter should be at the bottom of the + * filter stack. */ + return this.receiveCompression.readMessage(await message); + } +} +exports.CompressionFilter = CompressionFilter; +class CompressionFilterFactory { + constructor(channel, options) { + this.options = options; + this.sharedFilterConfig = {}; + } + createFilter() { + return new CompressionFilter(this.options, this.sharedFilterConfig); + } +} +exports.CompressionFilterFactory = CompressionFilterFactory; +//# sourceMappingURL=compression-filter.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/compression-filter.js.map b/node_modules/@grpc/grpc-js/build/src/compression-filter.js.map new file mode 100644 index 0000000..ed9cda1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/compression-filter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"compression-filter.js","sourceRoot":"","sources":["../../src/compression-filter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,6BAA6B;AAK7B,qEAAiE;AACjE,2CAAwH;AACxH,qCAA6D;AAC7D,qCAAqC;AAGrC,MAAM,yBAAyB,GAAG,CAChC,GAAW,EACmB,EAAE;IAChC,OAAO,CACL,OAAO,GAAG,KAAK,QAAQ,IAAI,OAAO,8CAAqB,CAAC,GAAG,CAAC,KAAK,QAAQ,CAC1E,CAAC;AACJ,CAAC,CAAC;AAQF,MAAe,kBAAkB;IAG/B;;;;OAIG;IACH,KAAK,CAAC,YAAY,CAAC,OAAe,EAAE,QAAiB;QACnD,IAAI,aAAa,GAAG,OAAO,CAAC;QAC5B,IAAI,QAAQ,EAAE,CAAC;YACb,aAAa,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,CAAC;QAC5D,CAAC;QACD,MAAM,MAAM,GAAG,MAAM,CAAC,WAAW,CAAC,aAAa,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAC5D,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QACvC,MAAM,CAAC,aAAa,CAAC,aAAa,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QAC9C,aAAa,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QAC9B,OAAO,MAAM,CAAC;IAChB,CAAC;IACD;;;OAGG;IACH,KAAK,CA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AI,eAAe,CAAC,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,oBAAoB,EAAE,CAAC;YACnG,MAAM;gBACJ,IAAI,EAAE,kBAAM,CAAC,kBAAkB;gBAC/B,OAAO,EAAE,qDAAqD,IAAI,CAAC,oBAAoB,EAAE;aAC1F,CAAC;QACJ,CAAC;QACD,IAAI,QAAiB,CAAC;QACtB,IAAI,IAAI,CAAC,eAAe,YAAY,eAAe,EAAE,CAAC;YACpD,QAAQ,GAAG,KAAK,CAAC;QACnB,CAAC;aAAM,CAAC;YACN,QAAQ,GAAG,CAAC,CAAC,MAAA,eAAe,CAAC,KAAK,mCAAI,CAAC,CAAC,gCAAwB,CAAC,KAAK,CAAC,CAAC;QAC1E,CAAC;QAED,OAAO;YACL,OAAO,EAAE,MAAM,IAAI,CAAC,eAAe,CAAC,YAAY,CAC9C,eAAe,CAAC,OAAO,EACvB,QAAQ,CACT;YACD,KAAK,EAAE,eAAe,CAAC,KAAK;SAC7B,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,OAAwB;QAC3C;;;2BAGmB;QACnB,OAAO,IAAI,CAAC,kBAAkB,CAAC,WAAW,CAAC,MAAM,OAAO,CAAC,CAAC;IAC5D,CAAC;CACF;AAnID,8CAmIC;AAED,MAAa,wBAAwB;IAInC,YAAY,OAAgB,EAAmB,OAAuB;QAAvB,YAAO,GAAP,OAAO,CAAgB;QAD9D,uBAAkB,GAAkC,EAAE,CAAC;IACU,CAAC;IAC1E,YAAY;QACV,OAAO,IAAI,iBAAiB,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,kBAAkB,CAAC,CAAC;IACtE,CAAC;CACF;AARD,4DAQC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/connectivity-state.d.ts b/node_modules/@grpc/grpc-js/build/src/connectivity-state.d.ts new file mode 100644 index 0000000..048ea39 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/connectivity-state.d.ts @@ -0,0 +1,7 @@ +export declare enum ConnectivityState { + IDLE = 0, + CONNECTING = 1, + READY = 2, + TRANSIENT_FAILURE = 3, + SHUTDOWN = 4 +} diff --git a/node_modules/@grpc/grpc-js/build/src/connectivity-state.js b/node_modules/@grpc/grpc-js/build/src/connectivity-state.js new file mode 100644 index 0000000..c8540b0 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/connectivity-state.js @@ -0,0 +1,28 @@ +"use strict"; +/* + * Copyright 2021 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConnectivityState = void 0; +var ConnectivityState; +(function (ConnectivityState) { + ConnectivityState[ConnectivityState["IDLE"] = 0] = "IDLE"; + ConnectivityState[ConnectivityState["CONNECTING"] = 1] = "CONNECTING"; + ConnectivityState[ConnectivityState["READY"] = 2] = "READY"; + ConnectivityState[ConnectivityState["TRANSIENT_FAILURE"] = 3] = "TRANSIENT_FAILURE"; + ConnectivityState[ConnectivityState["SHUTDOWN"] = 4] = "SHUTDOWN"; +})(ConnectivityState || (exports.ConnectivityState = ConnectivityState = {})); +//# sourceMappingURL=connectivity-state.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/connectivity-state.js.map b/node_modules/@grpc/grpc-js/build/src/connectivity-state.js.map new file mode 100644 index 0000000..1afc24d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/connectivity-state.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connectivity-state.js","sourceRoot":"","sources":["../../src/connectivity-state.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,IAAY,iBAMX;AAND,WAAY,iBAAiB;IAC3B,yDAAI,CAAA;IACJ,qEAAU,CAAA;IACV,2DAAK,CAAA;IACL,mFAAiB,CAAA;IACjB,iEAAQ,CAAA;AACV,CAAC,EANW,iBAAiB,iCAAjB,iBAAiB,QAM5B"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/constants.d.ts b/node_modules/@grpc/grpc-js/build/src/constants.d.ts new file mode 100644 index 0000000..43ec358 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/constants.d.ts @@ -0,0 +1,38 @@ +export declare enum Status { + OK = 0, + CANCELLED = 1, + UNKNOWN = 2, + INVALID_ARGUMENT = 3, + DEADLINE_EXCEEDED = 4, + NOT_FOUND = 5, + ALREADY_EXISTS = 6, + PERMISSION_DENIED = 7, + RESOURCE_EXHAUSTED = 8, + FAILED_PRECONDITION = 9, + ABORTED = 10, + OUT_OF_RANGE = 11, + UNIMPLEMENTED = 12, + INTERNAL = 13, + UNAVAILABLE = 14, + DATA_LOSS = 15, + UNAUTHENTICATED = 16 +} +export declare enum LogVerbosity { + DEBUG = 0, + INFO = 1, + ERROR = 2, + NONE = 3 +} +/** + * NOTE: This enum is not currently used in any implemented API in this + * library. It is included only for type parity with the other implementation. + */ +export declare enum Propagate { + DEADLINE = 1, + CENSUS_STATS_CONTEXT = 2, + CENSUS_TRACING_CONTEXT = 4, + CANCELLATION = 8, + DEFAULTS = 65535 +} +export declare const DEFAULT_MAX_SEND_MESSAGE_LENGTH = -1; +export declare const DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH: number; diff --git a/node_modules/@grpc/grpc-js/build/src/constants.js b/node_modules/@grpc/grpc-js/build/src/constants.js new file mode 100644 index 0000000..6e6b8ed --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/constants.js @@ -0,0 +1,64 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = exports.DEFAULT_MAX_SEND_MESSAGE_LENGTH = exports.Propagate = exports.LogVerbosity = exports.Status = void 0; +var Status; +(function (Status) { + Status[Status["OK"] = 0] = "OK"; + Status[Status["CANCELLED"] = 1] = "CANCELLED"; + Status[Status["UNKNOWN"] = 2] = "UNKNOWN"; + Status[Status["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT"; + Status[Status["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED"; + Status[Status["NOT_FOUND"] = 5] = "NOT_FOUND"; + Status[Status["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS"; + Status[Status["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED"; + Status[Status["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED"; + Status[Status["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION"; + Status[Status["ABORTED"] = 10] = "ABORTED"; + Status[Status["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE"; + Status[Status["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED"; + Status[Status["INTERNAL"] = 13] = "INTERNAL"; + Status[Status["UNAVAILABLE"] = 14] = "UNAVAILABLE"; + Status[Status["DATA_LOSS"] = 15] = "DATA_LOSS"; + Status[Status["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED"; +})(Status || (exports.Status = Status = {})); +var LogVerbosity; +(function (LogVerbosity) { + LogVerbosity[LogVerbosity["DEBUG"] = 0] = "DEBUG"; + LogVerbosity[LogVerbosity["INFO"] = 1] = "INFO"; + LogVerbosity[LogVerbosity["ERROR"] = 2] = "ERROR"; + LogVerbosity[LogVerbosity["NONE"] = 3] = "NONE"; +})(LogVerbosity || (exports.LogVerbosity = LogVerbosity = {})); +/** + * NOTE: This enum is not currently used in any implemented API in this + * library. It is included only for type parity with the other implementation. + */ +var Propagate; +(function (Propagate) { + Propagate[Propagate["DEADLINE"] = 1] = "DEADLINE"; + Propagate[Propagate["CENSUS_STATS_CONTEXT"] = 2] = "CENSUS_STATS_CONTEXT"; + Propagate[Propagate["CENSUS_TRACING_CONTEXT"] = 4] = "CENSUS_TRACING_CONTEXT"; + Propagate[Propagate["CANCELLATION"] = 8] = "CANCELLATION"; + // https://github.com/grpc/grpc/blob/master/include/grpc/impl/codegen/propagation_bits.h#L43 + Propagate[Propagate["DEFAULTS"] = 65535] = "DEFAULTS"; +})(Propagate || (exports.Propagate = Propagate = {})); +// -1 means unlimited +exports.DEFAULT_MAX_SEND_MESSAGE_LENGTH = -1; +// 4 MB default +exports.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = 4 * 1024 * 1024; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/constants.js.map b/node_modules/@grpc/grpc-js/build/src/constants.js.map new file mode 100644 index 0000000..a3c5c87 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,IAAY,MAkBX;AAlBD,WAAY,MAAM;IAChB,+BAAM,CAAA;IACN,6CAAS,CAAA;IACT,yCAAO,CAAA;IACP,2DAAgB,CAAA;IAChB,6DAAiB,CAAA;IACjB,6CAAS,CAAA;IACT,uDAAc,CAAA;IACd,6DAAiB,CAAA;IACjB,+DAAkB,CAAA;IAClB,iEAAmB,CAAA;IACnB,0CAAO,CAAA;IACP,oDAAY,CAAA;IACZ,sDAAa,CAAA;IACb,4CAAQ,CAAA;IACR,kDAAW,CAAA;IACX,8CAAS,CAAA;IACT,0DAAe,CAAA;AACjB,CAAC,EAlBW,MAAM,sBAAN,MAAM,QAkBjB;AAED,IAAY,YAKX;AALD,WAAY,YAAY;IACtB,iDAAS,CAAA;IACT,+CAAI,CAAA;IACJ,iDAAK,CAAA;IACL,+CAAI,CAAA;AACN,CAAC,EALW,YAAY,4BAAZ,YAAY,QAKvB;AAED;;;GAGG;AACH,IAAY,SAWX;AAXD,WAAY,SAAS;IACnB,iDAAY,CAAA;IACZ,yEAAwB,CAAA;IACxB,6EAA0B,CAAA;IAC1B,yDAAgB,CAAA;IAChB,4FAA4F;IAC5F,qDAIwB,CAAA;AAC1B,CAAC,EAXW,SAAS,yBAAT,SAAS,QAWpB;AAED,qBAAqB;AACR,QAAA,+BAA+B,GAAG,CAAC,CAAC,CAAC;AAElD,eAAe;AACF,QAAA,kCAAkC,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/control-plane-status.d.ts b/node_modules/@grpc/grpc-js/build/src/control-plane-status.d.ts new file mode 100644 index 0000000..a137cab --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/control-plane-status.d.ts @@ -0,0 +1,5 @@ +import { Status } from './constants'; +export declare function restrictControlPlaneStatusCode(code: Status, details: string): { + code: Status; + details: string; +}; diff --git a/node_modules/@grpc/grpc-js/build/src/control-plane-status.js b/node_modules/@grpc/grpc-js/build/src/control-plane-status.js new file mode 100644 index 0000000..5d55796 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/control-plane-status.js @@ -0,0 +1,42 @@ +"use strict"; +/* + * Copyright 2022 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.restrictControlPlaneStatusCode = restrictControlPlaneStatusCode; +const constants_1 = require("./constants"); +const INAPPROPRIATE_CONTROL_PLANE_CODES = [ + constants_1.Status.OK, + constants_1.Status.INVALID_ARGUMENT, + constants_1.Status.NOT_FOUND, + constants_1.Status.ALREADY_EXISTS, + constants_1.Status.FAILED_PRECONDITION, + constants_1.Status.ABORTED, + constants_1.Status.OUT_OF_RANGE, + constants_1.Status.DATA_LOSS, +]; +function restrictControlPlaneStatusCode(code, details) { + if (INAPPROPRIATE_CONTROL_PLANE_CODES.includes(code)) { + return { + code: constants_1.Status.INTERNAL, + details: `Invalid status from control plane: ${code} ${constants_1.Status[code]} ${details}`, + }; + } + else { + return { code, details }; + } +} +//# sourceMappingURL=control-plane-status.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/control-plane-status.js.map b/node_modules/@grpc/grpc-js/build/src/control-plane-status.js.map new file mode 100644 index 0000000..b5c0b71 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/control-plane-status.js.map @@ -0,0 +1 @@ +{"version":3,"file":"control-plane-status.js","sourceRoot":"","sources":["../../src/control-plane-status.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAeH,wEAYC;AAzBD,2CAAqC;AAErC,MAAM,iCAAiC,GAAa;IAClD,kBAAM,CAAC,EAAE;IACT,kBAAM,CAAC,gBAAgB;IACvB,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,cAAc;IACrB,kBAAM,CAAC,mBAAmB;IAC1B,kBAAM,CAAC,OAAO;IACd,kBAAM,CAAC,YAAY;IACnB,kBAAM,CAAC,SAAS;CACjB,CAAC;AAEF,SAAgB,8BAA8B,CAC5C,IAAY,EACZ,OAAe;IAEf,IAAI,iCAAiC,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;QACrD,OAAO;YACL,IAAI,EAAE,kBAAM,CAAC,QAAQ;YACrB,OAAO,EAAE,sCAAsC,IAAI,IAAI,kBAAM,CAAC,IAAI,CAAC,IAAI,OAAO,EAAE;SACjF,CAAC;IACJ,CAAC;SAAM,CAAC;QACN,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;IAC3B,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/deadline.d.ts b/node_modules/@grpc/grpc-js/build/src/deadline.d.ts new file mode 100644 index 0000000..63db6af --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/deadline.d.ts @@ -0,0 +1,22 @@ +export type Deadline = Date | number; +export declare function minDeadline(...deadlineList: Deadline[]): Deadline; +export declare function getDeadlineTimeoutString(deadline: Deadline): string; +/** + * Get the timeout value that should be passed to setTimeout now for the timer + * to end at the deadline. For any deadline before now, the timer should end + * immediately, represented by a value of 0. For any deadline more than + * MAX_TIMEOUT_TIME milliseconds in the future, a timer cannot be set that will + * end at that time, so it is treated as infinitely far in the future. + * @param deadline + * @returns + */ +export declare function getRelativeTimeout(deadline: Deadline): number; +export declare function deadlineToString(deadline: Deadline): string; +/** + * Calculate the difference between two dates as a number of seconds and format + * it as a string. + * @param startDate + * @param endDate + * @returns + */ +export declare function formatDateDifference(startDate: Date, endDate: Date): string; diff --git a/node_modules/@grpc/grpc-js/build/src/deadline.js b/node_modules/@grpc/grpc-js/build/src/deadline.js new file mode 100644 index 0000000..8b4a39e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/deadline.js @@ -0,0 +1,108 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.minDeadline = minDeadline; +exports.getDeadlineTimeoutString = getDeadlineTimeoutString; +exports.getRelativeTimeout = getRelativeTimeout; +exports.deadlineToString = deadlineToString; +exports.formatDateDifference = formatDateDifference; +function minDeadline(...deadlineList) { + let minValue = Infinity; + for (const deadline of deadlineList) { + const deadlineMsecs = deadline instanceof Date ? deadline.getTime() : deadline; + if (deadlineMsecs < minValue) { + minValue = deadlineMsecs; + } + } + return minValue; +} +const units = [ + ['m', 1], + ['S', 1000], + ['M', 60 * 1000], + ['H', 60 * 60 * 1000], +]; +function getDeadlineTimeoutString(deadline) { + const now = new Date().getTime(); + if (deadline instanceof Date) { + deadline = deadline.getTime(); + } + const timeoutMs = Math.max(deadline - now, 0); + for (const [unit, factor] of units) { + const amount = timeoutMs / factor; + if (amount < 1e8) { + return String(Math.ceil(amount)) + unit; + } + } + throw new Error('Deadline is too far in the future'); +} +/** + * See https://nodejs.org/api/timers.html#settimeoutcallback-delay-args + * In particular, "When delay is larger than 2147483647 or less than 1, the + * delay will be set to 1. Non-integer delays are truncated to an integer." + * This number of milliseconds is almost 25 days. + */ +const MAX_TIMEOUT_TIME = 2147483647; +/** + * Get the timeout value that should be passed to setTimeout now for the timer + * to end at the deadline. For any deadline before now, the timer should end + * immediately, represented by a value of 0. For any deadline more than + * MAX_TIMEOUT_TIME milliseconds in the future, a timer cannot be set that will + * end at that time, so it is treated as infinitely far in the future. + * @param deadline + * @returns + */ +function getRelativeTimeout(deadline) { + const deadlineMs = deadline instanceof Date ? deadline.getTime() : deadline; + const now = new Date().getTime(); + const timeout = deadlineMs - now; + if (timeout < 0) { + return 0; + } + else if (timeout > MAX_TIMEOUT_TIME) { + return Infinity; + } + else { + return timeout; + } +} +function deadlineToString(deadline) { + if (deadline instanceof Date) { + return deadline.toISOString(); + } + else { + const dateDeadline = new Date(deadline); + if (Number.isNaN(dateDeadline.getTime())) { + return '' + deadline; + } + else { + return dateDeadline.toISOString(); + } + } +} +/** + * Calculate the difference between two dates as a number of seconds and format + * it as a string. + * @param startDate + * @param endDate + * @returns + */ +function formatDateDifference(startDate, endDate) { + return ((endDate.getTime() - startDate.getTime()) / 1000).toFixed(3) + 's'; +} +//# sourceMappingURL=deadline.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/deadline.js.map b/node_modules/@grpc/grpc-js/build/src/deadline.js.map new file mode 100644 index 0000000..8176a9c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/deadline.js.map @@ -0,0 +1 @@ +{"version":3,"file":"deadline.js","sourceRoot":"","sources":["../../src/deadline.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAIH,kCAUC;AASD,4DAaC;AAmBD,gDAWC;AAED,4CAWC;AASD,oDAEC;AAtFD,SAAgB,WAAW,CAAC,GAAG,YAAwB;IACrD,IAAI,QAAQ,GAAG,QAAQ,CAAC;IACxB,KAAK,MAAM,QAAQ,IAAI,YAAY,EAAE,CAAC;QACpC,MAAM,aAAa,GACjB,QAAQ,YAAY,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC;QAC3D,IAAI,aAAa,GAAG,QAAQ,EAAE,CAAC;YAC7B,QAAQ,GAAG,aAAa,CAAC;QAC3B,CAAC;IACH,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,MAAM,KAAK,GAA4B;IACrC,CAAC,GAAG,EAAE,CAAC,CAAC;IACR,CAAC,GAAG,EAAE,IAAI,CAAC;IACX,CAAC,GAAG,EAAE,EAAE,GAAG,IAAI,CAAC;IAChB,CAAC,GAAG,EAAE,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;CACtB,CAAC;AAEF,SAAgB,wBAAwB,CAAC,QAAkB;IACzD,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAC;IACjC,IAAI,QAAQ,YAAY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,IAAI,IAAI,CAAC,QAAQ,CAAC,CAAC;QACxC,IAAI,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC;YACzC,OAAO,EAAE,GAAG,QAAQ,CAAC;QACvB,CAAC;aAAM,CAAC;YACN,OAAO,YAAY,CAAC,WAAW,EAAE,CAAC;QACpC,CAAC;IACH,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,oBAAoB,CAAC,SAAe,EAAE,OAAa;IACjE,OAAO,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,SAAS,CAAC,OAAO,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC;AAC7E,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/duration.d.ts b/node_modules/@grpc/grpc-js/build/src/duration.d.ts new file mode 100644 index 0000000..6d306ed --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/duration.d.ts @@ -0,0 +1,15 @@ +export interface Duration { + seconds: number; + nanos: number; +} +export interface DurationMessage { + seconds: string; + nanos: number; +} +export declare function durationMessageToDuration(message: DurationMessage): Duration; +export declare function msToDuration(millis: number): Duration; +export declare function durationToMs(duration: Duration): number; +export declare function isDuration(value: any): value is Duration; +export declare function isDurationMessage(value: any): value is DurationMessage; +export declare function parseDuration(value: string): Duration | null; +export declare function durationToString(duration: Duration): string; diff --git a/node_modules/@grpc/grpc-js/build/src/duration.js b/node_modules/@grpc/grpc-js/build/src/duration.js new file mode 100644 index 0000000..f48caa5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/duration.js @@ -0,0 +1,74 @@ +"use strict"; +/* + * Copyright 2022 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.durationMessageToDuration = durationMessageToDuration; +exports.msToDuration = msToDuration; +exports.durationToMs = durationToMs; +exports.isDuration = isDuration; +exports.isDurationMessage = isDurationMessage; +exports.parseDuration = parseDuration; +exports.durationToString = durationToString; +function durationMessageToDuration(message) { + return { + seconds: Number.parseInt(message.seconds), + nanos: message.nanos + }; +} +function msToDuration(millis) { + return { + seconds: (millis / 1000) | 0, + nanos: ((millis % 1000) * 1000000) | 0, + }; +} +function durationToMs(duration) { + return (duration.seconds * 1000 + duration.nanos / 1000000) | 0; +} +function isDuration(value) { + return typeof value.seconds === 'number' && typeof value.nanos === 'number'; +} +function isDurationMessage(value) { + return typeof value.seconds === 'string' && typeof value.nanos === 'number'; +} +const durationRegex = /^(\d+)(?:\.(\d+))?s$/; +function parseDuration(value) { + const match = value.match(durationRegex); + if (!match) { + return null; + } + return { + seconds: Number.parseInt(match[1], 10), + nanos: match[2] ? Number.parseInt(match[2].padEnd(9, '0'), 10) : 0 + }; +} +function durationToString(duration) { + if (duration.nanos === 0) { + return `${duration.seconds}s`; + } + let scaleFactor; + if (duration.nanos % 1000000 === 0) { + scaleFactor = 1000000; + } + else if (duration.nanos % 1000 === 0) { + scaleFactor = 1000; + } + else { + scaleFactor = 1; + } + return `${duration.seconds}.${duration.nanos / scaleFactor}s`; +} +//# sourceMappingURL=duration.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/duration.js.map b/node_modules/@grpc/grpc-js/build/src/duration.js.map new file mode 100644 index 0000000..4efe75a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/duration.js.map @@ -0,0 +1 @@ +{"version":3,"file":"duration.js","sourceRoot":"","sources":["../../src/duration.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAYH,8DAKC;AAED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,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;KACnE,CAAC;AACJ,CAAC;AAED,SAAgB,gBAAgB,CAAC,QAAkB;IACjD,IAAI,QAAQ,CAAC,KAAK,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,GAAG,QAAQ,CAAC,OAAO,GAAG,CAAC;IAChC,CAAC;IACD,IAAI,WAAmB,CAAC;IACxB,IAAI,QAAQ,CAAC,KAAK,GAAG,OAAS,KAAK,CAAC,EAAE,CAAC;QACrC,WAAW,GAAG,OAAS,CAAC;IAC1B,CAAC;SAAM,IAAI,QAAQ,CAAC,KAAK,GAAG,IAAK,KAAK,CAAC,EAAE,CAAC;QACxC,WAAW,GAAG,IAAK,CAAC;IACtB,CAAC;SAAM,CAAC;QACN,WAAW,GAAG,CAAC,CAAC;IAClB,CAAC;IACD,OAAO,GAAG,QAAQ,CAAC,OAAO,IAAI,QAAQ,CAAC,KAAK,GAAC,WAAW,GAAG,CAAC;AAC9D,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/environment.d.ts b/node_modules/@grpc/grpc-js/build/src/environment.d.ts new file mode 100644 index 0000000..de68f25 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/environment.d.ts @@ -0,0 +1 @@ +export declare const GRPC_NODE_USE_ALTERNATIVE_RESOLVER: boolean; diff --git a/node_modules/@grpc/grpc-js/build/src/environment.js b/node_modules/@grpc/grpc-js/build/src/environment.js new file mode 100644 index 0000000..e8d67c2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/environment.js @@ -0,0 +1,22 @@ +"use strict"; +/* + * Copyright 2024 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +var _a; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = void 0; +exports.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = ((_a = process.env.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) !== null && _a !== void 0 ? _a : 'false') === 'true'; +//# sourceMappingURL=environment.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/environment.js.map b/node_modules/@grpc/grpc-js/build/src/environment.js.map new file mode 100644 index 0000000..84205a5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/environment.js.map @@ -0,0 +1 @@ +{"version":3,"file":"environment.js","sourceRoot":"","sources":["../../src/environment.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;;AAEU,QAAA,kCAAkC,GAC7C,CAAC,MAAA,OAAO,CAAC,GAAG,CAAC,kCAAkC,mCAAI,OAAO,CAAC,KAAK,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/error.d.ts b/node_modules/@grpc/grpc-js/build/src/error.d.ts new file mode 100644 index 0000000..fd4cc77 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/error.d.ts @@ -0,0 +1,2 @@ +export declare function getErrorMessage(error: unknown): string; +export declare function getErrorCode(error: unknown): number | null; diff --git a/node_modules/@grpc/grpc-js/build/src/error.js b/node_modules/@grpc/grpc-js/build/src/error.js new file mode 100644 index 0000000..5cb1539 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/error.js @@ -0,0 +1,40 @@ +"use strict"; +/* + * Copyright 2022 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getErrorMessage = getErrorMessage; +exports.getErrorCode = getErrorCode; +function getErrorMessage(error) { + if (error instanceof Error) { + return error.message; + } + else { + return String(error); + } +} +function getErrorCode(error) { + if (typeof error === 'object' && + error !== null && + 'code' in error && + typeof error.code === 'number') { + return error.code; + } + else { + return null; + } +} +//# sourceMappingURL=error.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/error.js.map b/node_modules/@grpc/grpc-js/build/src/error.js.map new file mode 100644 index 0000000..ab40258 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/error.js.map @@ -0,0 +1 @@ +{"version":3,"file":"error.js","sourceRoot":"","sources":["../../src/error.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAEH,0CAMC;AAED,oCAWC;AAnBD,SAAgB,eAAe,CAAC,KAAc;IAC5C,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;QAC3B,OAAO,KAAK,CAAC,OAAO,CAAC;IACvB,CAAC;SAAM,CAAC;QACN,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;AACH,CAAC;AAED,SAAgB,YAAY,CAAC,KAAc;IACzC,IACE,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,MAAM,IAAI,KAAK;QACf,OAAQ,KAAiC,CAAC,IAAI,KAAK,QAAQ,EAC3D,CAAC;QACD,OAAQ,KAAgC,CAAC,IAAI,CAAC;IAChD,CAAC;SAAM,CAAC;QACN,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/events.d.ts b/node_modules/@grpc/grpc-js/build/src/events.d.ts new file mode 100644 index 0000000..d1a764e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/events.d.ts @@ -0,0 +1,9 @@ +export interface EmitterAugmentation1 { + addListener(event: Name, listener: (arg1: Arg) => void): this; + emit(event: Name, arg1: Arg): boolean; + on(event: Name, listener: (arg1: Arg) => void): this; + once(event: Name, listener: (arg1: Arg) => void): this; + prependListener(event: Name, listener: (arg1: Arg) => void): this; + prependOnceListener(event: Name, listener: (arg1: Arg) => void): this; + removeListener(event: Name, listener: (arg1: Arg) => void): this; +} diff --git a/node_modules/@grpc/grpc-js/build/src/events.js b/node_modules/@grpc/grpc-js/build/src/events.js new file mode 100644 index 0000000..082ed9b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/events.js @@ -0,0 +1,19 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=events.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/events.js.map b/node_modules/@grpc/grpc-js/build/src/events.js.map new file mode 100644 index 0000000..ba39b5d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/events.js.map @@ -0,0 +1 @@ +{"version":3,"file":"events.js","sourceRoot":"","sources":["../../src/events.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/experimental.d.ts b/node_modules/@grpc/grpc-js/build/src/experimental.d.ts new file mode 100644 index 0000000..f636190 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/experimental.d.ts @@ -0,0 +1,20 @@ +export { trace, log } from './logging'; +export { Resolver, ResolverListener, registerResolver, ConfigSelector, createResolver, CHANNEL_ARGS_CONFIG_SELECTOR_KEY, } from './resolver'; +export { GrpcUri, uriToString, splitHostPort, HostPort } from './uri-parser'; +export { Duration, durationToMs, parseDuration } from './duration'; +export { BackoffTimeout } from './backoff-timeout'; +export { LoadBalancer, TypedLoadBalancingConfig, ChannelControlHelper, createChildChannelControlHelper, registerLoadBalancerType, selectLbConfigFromList, parseLoadBalancingConfig, isLoadBalancerNameRegistered, } from './load-balancer'; +export { LeafLoadBalancer } from './load-balancer-pick-first'; +export { SubchannelAddress, subchannelAddressToString, Endpoint, endpointToString, endpointHasAddress, EndpointMap, } from './subchannel-address'; +export { ChildLoadBalancerHandler } from './load-balancer-child-handler'; +export { Picker, UnavailablePicker, QueuePicker, PickResult, PickArgs, PickResultType, } from './picker'; +export { Call as CallStream, StatusOr, statusOrFromValue, statusOrFromError } from './call-interface'; +export { Filter, BaseFilter, FilterFactory } from './filter'; +export { FilterStackFactory } from './filter-stack'; +export { registerAdminService } from './admin'; +export { SubchannelInterface, BaseSubchannelWrapper, ConnectivityStateListener, HealthListener, } from './subchannel-interface'; +export { OutlierDetectionRawConfig, SuccessRateEjectionConfig, FailurePercentageEjectionConfig, } from './load-balancer-outlier-detection'; +export { createServerCredentialsWithInterceptors, createCertificateProviderServerCredentials } from './server-credentials'; +export { CaCertificateUpdate, CaCertificateUpdateListener, IdentityCertificateUpdate, IdentityCertificateUpdateListener, CertificateProvider, FileWatcherCertificateProvider, FileWatcherCertificateProviderConfig } from './certificate-provider'; +export { createCertificateProviderChannelCredentials, SecureConnector, SecureConnectResult } from './channel-credentials'; +export { SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX } from './internal-channel'; diff --git a/node_modules/@grpc/grpc-js/build/src/experimental.js b/node_modules/@grpc/grpc-js/build/src/experimental.js new file mode 100644 index 0000000..3f2835c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/experimental.js @@ -0,0 +1,58 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = exports.createCertificateProviderChannelCredentials = exports.FileWatcherCertificateProvider = exports.createCertificateProviderServerCredentials = exports.createServerCredentialsWithInterceptors = exports.BaseSubchannelWrapper = exports.registerAdminService = exports.FilterStackFactory = exports.BaseFilter = exports.statusOrFromError = exports.statusOrFromValue = exports.PickResultType = exports.QueuePicker = exports.UnavailablePicker = exports.ChildLoadBalancerHandler = exports.EndpointMap = exports.endpointHasAddress = exports.endpointToString = exports.subchannelAddressToString = exports.LeafLoadBalancer = exports.isLoadBalancerNameRegistered = exports.parseLoadBalancingConfig = exports.selectLbConfigFromList = exports.registerLoadBalancerType = exports.createChildChannelControlHelper = exports.BackoffTimeout = exports.parseDuration = exports.durationToMs = exports.splitHostPort = exports.uriToString = exports.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = exports.createResolver = exports.registerResolver = exports.log = exports.trace = void 0; +var logging_1 = require("./logging"); +Object.defineProperty(exports, "trace", { enumerable: true, get: function () { return logging_1.trace; } }); +Object.defineProperty(exports, "log", { enumerable: true, get: function () { return logging_1.log; } }); +var resolver_1 = require("./resolver"); +Object.defineProperty(exports, "registerResolver", { enumerable: true, get: function () { return resolver_1.registerResolver; } }); +Object.defineProperty(exports, "createResolver", { enumerable: true, get: function () { return resolver_1.createResolver; } }); +Object.defineProperty(exports, "CHANNEL_ARGS_CONFIG_SELECTOR_KEY", { enumerable: true, get: function () { return resolver_1.CHANNEL_ARGS_CONFIG_SELECTOR_KEY; } }); +var uri_parser_1 = require("./uri-parser"); +Object.defineProperty(exports, "uriToString", { enumerable: true, get: function () { return uri_parser_1.uriToString; } }); +Object.defineProperty(exports, "splitHostPort", { enumerable: true, get: function () { return uri_parser_1.splitHostPort; } }); +var duration_1 = require("./duration"); +Object.defineProperty(exports, "durationToMs", { enumerable: true, get: function () { return duration_1.durationToMs; } }); +Object.defineProperty(exports, "parseDuration", { enumerable: true, get: function () { return duration_1.parseDuration; } }); +var backoff_timeout_1 = require("./backoff-timeout"); +Object.defineProperty(exports, "BackoffTimeout", { enumerable: true, get: function () { return backoff_timeout_1.BackoffTimeout; } }); +var load_balancer_1 = require("./load-balancer"); +Object.defineProperty(exports, "createChildChannelControlHelper", { enumerable: true, get: function () { return load_balancer_1.createChildChannelControlHelper; } }); +Object.defineProperty(exports, "registerLoadBalancerType", { enumerable: true, get: function () { return load_balancer_1.registerLoadBalancerType; } }); +Object.defineProperty(exports, "selectLbConfigFromList", { enumerable: true, get: function () { return load_balancer_1.selectLbConfigFromList; } }); +Object.defineProperty(exports, "parseLoadBalancingConfig", { enumerable: true, get: function () { return load_balancer_1.parseLoadBalancingConfig; } }); +Object.defineProperty(exports, "isLoadBalancerNameRegistered", { enumerable: true, get: function () { return load_balancer_1.isLoadBalancerNameRegistered; } }); +var load_balancer_pick_first_1 = require("./load-balancer-pick-first"); +Object.defineProperty(exports, "LeafLoadBalancer", { enumerable: true, get: function () { return load_balancer_pick_first_1.LeafLoadBalancer; } }); +var subchannel_address_1 = require("./subchannel-address"); +Object.defineProperty(exports, "subchannelAddressToString", { enumerable: true, get: function () { return subchannel_address_1.subchannelAddressToString; } }); +Object.defineProperty(exports, "endpointToString", { enumerable: true, get: function () { return subchannel_address_1.endpointToString; } }); +Object.defineProperty(exports, "endpointHasAddress", { enumerable: true, get: function () { return subchannel_address_1.endpointHasAddress; } }); +Object.defineProperty(exports, "EndpointMap", { enumerable: true, get: function () { return subchannel_address_1.EndpointMap; } }); +var load_balancer_child_handler_1 = require("./load-balancer-child-handler"); +Object.defineProperty(exports, "ChildLoadBalancerHandler", { enumerable: true, get: function () { return load_balancer_child_handler_1.ChildLoadBalancerHandler; } }); +var picker_1 = require("./picker"); +Object.defineProperty(exports, "UnavailablePicker", { enumerable: true, get: function () { return picker_1.UnavailablePicker; } }); +Object.defineProperty(exports, "QueuePicker", { enumerable: true, get: function () { return picker_1.QueuePicker; } }); +Object.defineProperty(exports, "PickResultType", { enumerable: true, get: function () { return picker_1.PickResultType; } }); +var call_interface_1 = require("./call-interface"); +Object.defineProperty(exports, "statusOrFromValue", { enumerable: true, get: function () { return call_interface_1.statusOrFromValue; } }); +Object.defineProperty(exports, "statusOrFromError", { enumerable: true, get: function () { return call_interface_1.statusOrFromError; } }); +var filter_1 = require("./filter"); +Object.defineProperty(exports, "BaseFilter", { enumerable: true, get: function () { return filter_1.BaseFilter; } }); +var filter_stack_1 = require("./filter-stack"); +Object.defineProperty(exports, "FilterStackFactory", { enumerable: true, get: function () { return filter_stack_1.FilterStackFactory; } }); +var admin_1 = require("./admin"); +Object.defineProperty(exports, "registerAdminService", { enumerable: true, get: function () { return admin_1.registerAdminService; } }); +var subchannel_interface_1 = require("./subchannel-interface"); +Object.defineProperty(exports, "BaseSubchannelWrapper", { enumerable: true, get: function () { return subchannel_interface_1.BaseSubchannelWrapper; } }); +var server_credentials_1 = require("./server-credentials"); +Object.defineProperty(exports, "createServerCredentialsWithInterceptors", { enumerable: true, get: function () { return server_credentials_1.createServerCredentialsWithInterceptors; } }); +Object.defineProperty(exports, "createCertificateProviderServerCredentials", { enumerable: true, get: function () { return server_credentials_1.createCertificateProviderServerCredentials; } }); +var certificate_provider_1 = require("./certificate-provider"); +Object.defineProperty(exports, "FileWatcherCertificateProvider", { enumerable: true, get: function () { return certificate_provider_1.FileWatcherCertificateProvider; } }); +var channel_credentials_1 = require("./channel-credentials"); +Object.defineProperty(exports, "createCertificateProviderChannelCredentials", { enumerable: true, get: function () { return channel_credentials_1.createCertificateProviderChannelCredentials; } }); +var internal_channel_1 = require("./internal-channel"); +Object.defineProperty(exports, "SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX", { enumerable: true, get: function () { return internal_channel_1.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX; } }); +//# sourceMappingURL=experimental.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/experimental.js.map b/node_modules/@grpc/grpc-js/build/src/experimental.js.map new file mode 100644 index 0000000..bbffebf --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/experimental.js.map @@ -0,0 +1 @@ +{"version":3,"file":"experimental.js","sourceRoot":"","sources":["../../src/experimental.ts"],"names":[],"mappings":";;;AAAA,qCAAuC;AAA9B,gGAAA,KAAK,OAAA;AAAE,8FAAA,GAAG,OAAA;AACnB,uCAOoB;AAJlB,4GAAA,gBAAgB,OAAA;AAEhB,0GAAA,cAAc,OAAA;AACd,4HAAA,gCAAgC,OAAA;AAElC,2CAA6E;AAA3D,yGAAA,WAAW,OAAA;AAAE,2GAAA,aAAa,OAAA;AAC5C,uCAAmE;AAAhD,wGAAA,YAAY,OAAA;AAAE,yGAAA,aAAa,OAAA;AAC9C,qDAAmD;AAA1C,iHAAA,cAAc,OAAA;AACvB,iDASyB;AALvB,gIAAA,+BAA+B,OAAA;AAC/B,yHAAA,wBAAwB,OAAA;AACxB,uHAAA,sBAAsB,OAAA;AACtB,yHAAA,wBAAwB,OAAA;AACxB,6HAAA,4BAA4B,OAAA;AAE9B,uEAA8D;AAArD,4HAAA,gBAAgB,OAAA;AACzB,2DAO8B;AAL5B,+HAAA,yBAAyB,OAAA;AAEzB,sHAAA,gBAAgB,OAAA;AAChB,wHAAA,kBAAkB,OAAA;AAClB,iHAAA,WAAW,OAAA;AAEb,6EAAyE;AAAhE,uIAAA,wBAAwB,OAAA;AACjC,mCAOkB;AALhB,2GAAA,iBAAiB,OAAA;AACjB,qGAAA,WAAW,OAAA;AAGX,wGAAA,cAAc,OAAA;AAEhB,mDAK0B;AAFxB,mHAAA,iBAAiB,OAAA;AACjB,mHAAA,iBAAiB,OAAA;AAEnB,mCAA6D;AAA5C,oGAAA,UAAU,OAAA;AAC3B,+CAAoD;AAA3C,kHAAA,kBAAkB,OAAA;AAC3B,iCAA+C;AAAtC,6GAAA,oBAAoB,OAAA;AAC7B,+DAKgC;AAH9B,6HAAA,qBAAqB,OAAA;AAUvB,2DAA2H;AAAlH,6IAAA,uCAAuC,OAAA;AAAE,gJAAA,0CAA0C,OAAA;AAC5F,+DAQgC;AAF9B,sIAAA,8BAA8B,OAAA;AAGhC,6DAA0H;AAAjH,kJAAA,2CAA2C,OAAA;AACpD,uDAAwE;AAA/D,sIAAA,kCAAkC,OAAA"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/filter-stack.d.ts b/node_modules/@grpc/grpc-js/build/src/filter-stack.d.ts new file mode 100644 index 0000000..1689c2d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/filter-stack.d.ts @@ -0,0 +1,21 @@ +import { StatusObject, WriteObject } from './call-interface'; +import { Filter, FilterFactory } from './filter'; +import { Metadata } from './metadata'; +export declare class FilterStack implements Filter { + private readonly filters; + constructor(filters: Filter[]); + sendMetadata(metadata: Promise): Promise; + receiveMetadata(metadata: Metadata): Metadata; + sendMessage(message: Promise): Promise; + receiveMessage(message: Promise): Promise; + receiveTrailers(status: StatusObject): StatusObject; + push(filters: Filter[]): void; + getFilters(): Filter[]; +} +export declare class FilterStackFactory implements FilterFactory { + private readonly factories; + constructor(factories: Array>); + push(filterFactories: FilterFactory[]): void; + clone(): FilterStackFactory; + createFilter(): FilterStack; +} diff --git a/node_modules/@grpc/grpc-js/build/src/filter-stack.js b/node_modules/@grpc/grpc-js/build/src/filter-stack.js new file mode 100644 index 0000000..6cf2e1a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/filter-stack.js @@ -0,0 +1,82 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FilterStackFactory = exports.FilterStack = void 0; +class FilterStack { + constructor(filters) { + this.filters = filters; + } + sendMetadata(metadata) { + let result = metadata; + for (let i = 0; i < this.filters.length; i++) { + result = this.filters[i].sendMetadata(result); + } + return result; + } + receiveMetadata(metadata) { + let result = metadata; + for (let i = this.filters.length - 1; i >= 0; i--) { + result = this.filters[i].receiveMetadata(result); + } + return result; + } + sendMessage(message) { + let result = message; + for (let i = 0; i < this.filters.length; i++) { + result = this.filters[i].sendMessage(result); + } + return result; + } + receiveMessage(message) { + let result = message; + for (let i = this.filters.length - 1; i >= 0; i--) { + result = this.filters[i].receiveMessage(result); + } + return result; + } + receiveTrailers(status) { + let result = status; + for (let i = this.filters.length - 1; i >= 0; i--) { + result = this.filters[i].receiveTrailers(result); + } + return result; + } + push(filters) { + this.filters.unshift(...filters); + } + getFilters() { + return this.filters; + } +} +exports.FilterStack = FilterStack; +class FilterStackFactory { + constructor(factories) { + this.factories = factories; + } + push(filterFactories) { + this.factories.unshift(...filterFactories); + } + clone() { + return new FilterStackFactory([...this.factories]); + } + createFilter() { + return new FilterStack(this.factories.map(factory => factory.createFilter())); + } +} +exports.FilterStackFactory = FilterStackFactory; +//# sourceMappingURL=filter-stack.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/filter-stack.js.map b/node_modules/@grpc/grpc-js/build/src/filter-stack.js.map new file mode 100644 index 0000000..ffbeadf --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/filter-stack.js.map @@ -0,0 +1 @@ +{"version":3,"file":"filter-stack.js","sourceRoot":"","sources":["../../src/filter-stack.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAMH,MAAa,WAAW;IACtB,YAA6B,OAAiB;QAAjB,YAAO,GAAP,OAAO,CAAU;IAAG,CAAC;IAElD,YAAY,CAAC,QAA2B;QACtC,IAAI,MAAM,GAAsB,QAAQ,CAAC;QAEzC,KAAK,IAAI,CAAC,GAAG,CAAC,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B,MAAM,CAAC;QAElC,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;YAClD,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;QACnD,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,IAAI,CAAC,OAAiB;QACpB,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,CAAC;IACnC,CAAC;IAED,UAAU;QACR,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;CACF;AA5DD,kCA4DC;AAED,MAAa,kBAAkB;IAC7B,YAA6B,SAAuC;QAAvC,cAAS,GAAT,SAAS,CAA8B;IAAG,CAAC;IAExE,IAAI,CAAC,eAAwC;QAC3C,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,GAAG,eAAe,CAAC,CAAC;IAC7C,CAAC;IAED,KAAK;QACH,OAAO,IAAI,kBAAkB,CAAC,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IACrD,CAAC;IAED,YAAY;QACV,OAAO,IAAI,WAAW,CACpB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC,CACtD,CAAC;IACJ,CAAC;CACF;AAhBD,gDAgBC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/filter.d.ts b/node_modules/@grpc/grpc-js/build/src/filter.d.ts new file mode 100644 index 0000000..e3fe87d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/filter.d.ts @@ -0,0 +1,25 @@ +import { StatusObject, WriteObject } from './call-interface'; +import { Metadata } from './metadata'; +/** + * Filter classes represent related per-call logic and state that is primarily + * used to modify incoming and outgoing data. All async filters can be + * rejected. The rejection error must be a StatusObject, and a rejection will + * cause the call to end with that status. + */ +export interface Filter { + sendMetadata(metadata: Promise): Promise; + receiveMetadata(metadata: Metadata): Metadata; + sendMessage(message: Promise): Promise; + receiveMessage(message: Promise): Promise; + receiveTrailers(status: StatusObject): StatusObject; +} +export declare abstract class BaseFilter implements Filter { + sendMetadata(metadata: Promise): Promise; + receiveMetadata(metadata: Metadata): Metadata; + sendMessage(message: Promise): Promise; + receiveMessage(message: Promise): Promise; + receiveTrailers(status: StatusObject): StatusObject; +} +export interface FilterFactory { + createFilter(): T; +} diff --git a/node_modules/@grpc/grpc-js/build/src/filter.js b/node_modules/@grpc/grpc-js/build/src/filter.js new file mode 100644 index 0000000..d888a82 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/filter.js @@ -0,0 +1,38 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BaseFilter = void 0; +class BaseFilter { + async sendMetadata(metadata) { + return metadata; + } + receiveMetadata(metadata) { + return metadata; + } + async sendMessage(message) { + return message; + } + async receiveMessage(message) { + return message; + } + receiveTrailers(status) { + return status; + } +} +exports.BaseFilter = BaseFilter; +//# sourceMappingURL=filter.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/filter.js.map b/node_modules/@grpc/grpc-js/build/src/filter.js.map new file mode 100644 index 0000000..1ddf110 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/filter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"filter.js","sourceRoot":"","sources":["../../src/filter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAuBH,MAAsB,UAAU;IAC9B,KAAK,CAAC,YAAY,CAAC,QAA2B;QAC5C,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,eAAe,CAAC,QAAkB;QAChC,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,OAA6B;QAC7C,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,OAAwB;QAC3C,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,eAAe,CAAC,MAAoB;QAClC,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AApBD,gCAoBC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/channelz.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/channelz.d.ts new file mode 100644 index 0000000..434d8b0 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/channelz.d.ts @@ -0,0 +1,118 @@ +import type * as grpc from '../index'; +import type { MessageTypeDefinition } from '@grpc/proto-loader'; +import type { Any as _google_protobuf_Any, Any__Output as _google_protobuf_Any__Output } from './google/protobuf/Any'; +import type { BoolValue as _google_protobuf_BoolValue, BoolValue__Output as _google_protobuf_BoolValue__Output } from './google/protobuf/BoolValue'; +import type { BytesValue as _google_protobuf_BytesValue, BytesValue__Output as _google_protobuf_BytesValue__Output } from './google/protobuf/BytesValue'; +import type { DoubleValue as _google_protobuf_DoubleValue, DoubleValue__Output as _google_protobuf_DoubleValue__Output } from './google/protobuf/DoubleValue'; +import type { Duration as _google_protobuf_Duration, Duration__Output as _google_protobuf_Duration__Output } from './google/protobuf/Duration'; +import type { FloatValue as _google_protobuf_FloatValue, FloatValue__Output as _google_protobuf_FloatValue__Output } from './google/protobuf/FloatValue'; +import type { Int32Value as _google_protobuf_Int32Value, Int32Value__Output as _google_protobuf_Int32Value__Output } from './google/protobuf/Int32Value'; +import type { Int64Value as _google_protobuf_Int64Value, Int64Value__Output as _google_protobuf_Int64Value__Output } from './google/protobuf/Int64Value'; +import type { StringValue as _google_protobuf_StringValue, StringValue__Output as _google_protobuf_StringValue__Output } from './google/protobuf/StringValue'; +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from './google/protobuf/Timestamp'; +import type { UInt32Value as _google_protobuf_UInt32Value, UInt32Value__Output as _google_protobuf_UInt32Value__Output } from './google/protobuf/UInt32Value'; +import type { UInt64Value as _google_protobuf_UInt64Value, UInt64Value__Output as _google_protobuf_UInt64Value__Output } from './google/protobuf/UInt64Value'; +import type { Address as _grpc_channelz_v1_Address, Address__Output as _grpc_channelz_v1_Address__Output } from './grpc/channelz/v1/Address'; +import type { Channel as _grpc_channelz_v1_Channel, Channel__Output as _grpc_channelz_v1_Channel__Output } from './grpc/channelz/v1/Channel'; +import type { ChannelConnectivityState as _grpc_channelz_v1_ChannelConnectivityState, ChannelConnectivityState__Output as _grpc_channelz_v1_ChannelConnectivityState__Output } from './grpc/channelz/v1/ChannelConnectivityState'; +import type { ChannelData as _grpc_channelz_v1_ChannelData, ChannelData__Output as _grpc_channelz_v1_ChannelData__Output } from './grpc/channelz/v1/ChannelData'; +import type { ChannelRef as _grpc_channelz_v1_ChannelRef, ChannelRef__Output as _grpc_channelz_v1_ChannelRef__Output } from './grpc/channelz/v1/ChannelRef'; +import type { ChannelTrace as _grpc_channelz_v1_ChannelTrace, ChannelTrace__Output as _grpc_channelz_v1_ChannelTrace__Output } from './grpc/channelz/v1/ChannelTrace'; +import type { ChannelTraceEvent as _grpc_channelz_v1_ChannelTraceEvent, ChannelTraceEvent__Output as _grpc_channelz_v1_ChannelTraceEvent__Output } from './grpc/channelz/v1/ChannelTraceEvent'; +import type { ChannelzClient as _grpc_channelz_v1_ChannelzClient, ChannelzDefinition as _grpc_channelz_v1_ChannelzDefinition } from './grpc/channelz/v1/Channelz'; +import type { GetChannelRequest as _grpc_channelz_v1_GetChannelRequest, GetChannelRequest__Output as _grpc_channelz_v1_GetChannelRequest__Output } from './grpc/channelz/v1/GetChannelRequest'; +import type { GetChannelResponse as _grpc_channelz_v1_GetChannelResponse, GetChannelResponse__Output as _grpc_channelz_v1_GetChannelResponse__Output } from './grpc/channelz/v1/GetChannelResponse'; +import type { GetServerRequest as _grpc_channelz_v1_GetServerRequest, GetServerRequest__Output as _grpc_channelz_v1_GetServerRequest__Output } from './grpc/channelz/v1/GetServerRequest'; +import type { GetServerResponse as _grpc_channelz_v1_GetServerResponse, GetServerResponse__Output as _grpc_channelz_v1_GetServerResponse__Output } from './grpc/channelz/v1/GetServerResponse'; +import type { GetServerSocketsRequest as _grpc_channelz_v1_GetServerSocketsRequest, GetServerSocketsRequest__Output as _grpc_channelz_v1_GetServerSocketsRequest__Output } from './grpc/channelz/v1/GetServerSocketsRequest'; +import type { GetServerSocketsResponse as _grpc_channelz_v1_GetServerSocketsResponse, GetServerSocketsResponse__Output as _grpc_channelz_v1_GetServerSocketsResponse__Output } from './grpc/channelz/v1/GetServerSocketsResponse'; +import type { GetServersRequest as _grpc_channelz_v1_GetServersRequest, GetServersRequest__Output as _grpc_channelz_v1_GetServersRequest__Output } from './grpc/channelz/v1/GetServersRequest'; +import type { GetServersResponse as _grpc_channelz_v1_GetServersResponse, GetServersResponse__Output as _grpc_channelz_v1_GetServersResponse__Output } from './grpc/channelz/v1/GetServersResponse'; +import type { GetSocketRequest as _grpc_channelz_v1_GetSocketRequest, GetSocketRequest__Output as _grpc_channelz_v1_GetSocketRequest__Output } from './grpc/channelz/v1/GetSocketRequest'; +import type { GetSocketResponse as _grpc_channelz_v1_GetSocketResponse, GetSocketResponse__Output as _grpc_channelz_v1_GetSocketResponse__Output } from './grpc/channelz/v1/GetSocketResponse'; +import type { GetSubchannelRequest as _grpc_channelz_v1_GetSubchannelRequest, GetSubchannelRequest__Output as _grpc_channelz_v1_GetSubchannelRequest__Output } from './grpc/channelz/v1/GetSubchannelRequest'; +import type { GetSubchannelResponse as _grpc_channelz_v1_GetSubchannelResponse, GetSubchannelResponse__Output as _grpc_channelz_v1_GetSubchannelResponse__Output } from './grpc/channelz/v1/GetSubchannelResponse'; +import type { GetTopChannelsRequest as _grpc_channelz_v1_GetTopChannelsRequest, GetTopChannelsRequest__Output as _grpc_channelz_v1_GetTopChannelsRequest__Output } from './grpc/channelz/v1/GetTopChannelsRequest'; +import type { GetTopChannelsResponse as _grpc_channelz_v1_GetTopChannelsResponse, GetTopChannelsResponse__Output as _grpc_channelz_v1_GetTopChannelsResponse__Output } from './grpc/channelz/v1/GetTopChannelsResponse'; +import type { Security as _grpc_channelz_v1_Security, Security__Output as _grpc_channelz_v1_Security__Output } from './grpc/channelz/v1/Security'; +import type { Server as _grpc_channelz_v1_Server, Server__Output as _grpc_channelz_v1_Server__Output } from './grpc/channelz/v1/Server'; +import type { ServerData as _grpc_channelz_v1_ServerData, ServerData__Output as _grpc_channelz_v1_ServerData__Output } from './grpc/channelz/v1/ServerData'; +import type { ServerRef as _grpc_channelz_v1_ServerRef, ServerRef__Output as _grpc_channelz_v1_ServerRef__Output } from './grpc/channelz/v1/ServerRef'; +import type { Socket as _grpc_channelz_v1_Socket, Socket__Output as _grpc_channelz_v1_Socket__Output } from './grpc/channelz/v1/Socket'; +import type { SocketData as _grpc_channelz_v1_SocketData, SocketData__Output as _grpc_channelz_v1_SocketData__Output } from './grpc/channelz/v1/SocketData'; +import type { SocketOption as _grpc_channelz_v1_SocketOption, SocketOption__Output as _grpc_channelz_v1_SocketOption__Output } from './grpc/channelz/v1/SocketOption'; +import type { SocketOptionLinger as _grpc_channelz_v1_SocketOptionLinger, SocketOptionLinger__Output as _grpc_channelz_v1_SocketOptionLinger__Output } from './grpc/channelz/v1/SocketOptionLinger'; +import type { SocketOptionTcpInfo as _grpc_channelz_v1_SocketOptionTcpInfo, SocketOptionTcpInfo__Output as _grpc_channelz_v1_SocketOptionTcpInfo__Output } from './grpc/channelz/v1/SocketOptionTcpInfo'; +import type { SocketOptionTimeout as _grpc_channelz_v1_SocketOptionTimeout, SocketOptionTimeout__Output as _grpc_channelz_v1_SocketOptionTimeout__Output } from './grpc/channelz/v1/SocketOptionTimeout'; +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from './grpc/channelz/v1/SocketRef'; +import type { Subchannel as _grpc_channelz_v1_Subchannel, Subchannel__Output as _grpc_channelz_v1_Subchannel__Output } from './grpc/channelz/v1/Subchannel'; +import type { SubchannelRef as _grpc_channelz_v1_SubchannelRef, SubchannelRef__Output as _grpc_channelz_v1_SubchannelRef__Output } from './grpc/channelz/v1/SubchannelRef'; +type SubtypeConstructor any, Subtype> = { + new (...args: ConstructorParameters): Subtype; +}; +export interface ProtoGrpcType { + google: { + protobuf: { + Any: MessageTypeDefinition<_google_protobuf_Any, _google_protobuf_Any__Output>; + BoolValue: MessageTypeDefinition<_google_protobuf_BoolValue, _google_protobuf_BoolValue__Output>; + BytesValue: MessageTypeDefinition<_google_protobuf_BytesValue, _google_protobuf_BytesValue__Output>; + DoubleValue: MessageTypeDefinition<_google_protobuf_DoubleValue, _google_protobuf_DoubleValue__Output>; + Duration: MessageTypeDefinition<_google_protobuf_Duration, _google_protobuf_Duration__Output>; + FloatValue: MessageTypeDefinition<_google_protobuf_FloatValue, _google_protobuf_FloatValue__Output>; + Int32Value: MessageTypeDefinition<_google_protobuf_Int32Value, _google_protobuf_Int32Value__Output>; + Int64Value: MessageTypeDefinition<_google_protobuf_Int64Value, _google_protobuf_Int64Value__Output>; + StringValue: MessageTypeDefinition<_google_protobuf_StringValue, _google_protobuf_StringValue__Output>; + Timestamp: MessageTypeDefinition<_google_protobuf_Timestamp, _google_protobuf_Timestamp__Output>; + UInt32Value: MessageTypeDefinition<_google_protobuf_UInt32Value, _google_protobuf_UInt32Value__Output>; + UInt64Value: MessageTypeDefinition<_google_protobuf_UInt64Value, _google_protobuf_UInt64Value__Output>; + }; + }; + grpc: { + channelz: { + v1: { + Address: MessageTypeDefinition<_grpc_channelz_v1_Address, _grpc_channelz_v1_Address__Output>; + Channel: MessageTypeDefinition<_grpc_channelz_v1_Channel, _grpc_channelz_v1_Channel__Output>; + ChannelConnectivityState: MessageTypeDefinition<_grpc_channelz_v1_ChannelConnectivityState, _grpc_channelz_v1_ChannelConnectivityState__Output>; + ChannelData: MessageTypeDefinition<_grpc_channelz_v1_ChannelData, _grpc_channelz_v1_ChannelData__Output>; + ChannelRef: MessageTypeDefinition<_grpc_channelz_v1_ChannelRef, _grpc_channelz_v1_ChannelRef__Output>; + ChannelTrace: MessageTypeDefinition<_grpc_channelz_v1_ChannelTrace, _grpc_channelz_v1_ChannelTrace__Output>; + ChannelTraceEvent: MessageTypeDefinition<_grpc_channelz_v1_ChannelTraceEvent, _grpc_channelz_v1_ChannelTraceEvent__Output>; + /** + * Channelz is a service exposed by gRPC servers that provides detailed debug + * information. + */ + Channelz: SubtypeConstructor & { + service: _grpc_channelz_v1_ChannelzDefinition; + }; + GetChannelRequest: MessageTypeDefinition<_grpc_channelz_v1_GetChannelRequest, _grpc_channelz_v1_GetChannelRequest__Output>; + GetChannelResponse: MessageTypeDefinition<_grpc_channelz_v1_GetChannelResponse, _grpc_channelz_v1_GetChannelResponse__Output>; + GetServerRequest: MessageTypeDefinition<_grpc_channelz_v1_GetServerRequest, _grpc_channelz_v1_GetServerRequest__Output>; + GetServerResponse: MessageTypeDefinition<_grpc_channelz_v1_GetServerResponse, _grpc_channelz_v1_GetServerResponse__Output>; + GetServerSocketsRequest: MessageTypeDefinition<_grpc_channelz_v1_GetServerSocketsRequest, _grpc_channelz_v1_GetServerSocketsRequest__Output>; + GetServerSocketsResponse: MessageTypeDefinition<_grpc_channelz_v1_GetServerSocketsResponse, _grpc_channelz_v1_GetServerSocketsResponse__Output>; + GetServersRequest: MessageTypeDefinition<_grpc_channelz_v1_GetServersRequest, _grpc_channelz_v1_GetServersRequest__Output>; + GetServersResponse: MessageTypeDefinition<_grpc_channelz_v1_GetServersResponse, _grpc_channelz_v1_GetServersResponse__Output>; + GetSocketRequest: MessageTypeDefinition<_grpc_channelz_v1_GetSocketRequest, _grpc_channelz_v1_GetSocketRequest__Output>; + GetSocketResponse: MessageTypeDefinition<_grpc_channelz_v1_GetSocketResponse, _grpc_channelz_v1_GetSocketResponse__Output>; + GetSubchannelRequest: MessageTypeDefinition<_grpc_channelz_v1_GetSubchannelRequest, _grpc_channelz_v1_GetSubchannelRequest__Output>; + GetSubchannelResponse: MessageTypeDefinition<_grpc_channelz_v1_GetSubchannelResponse, _grpc_channelz_v1_GetSubchannelResponse__Output>; + GetTopChannelsRequest: MessageTypeDefinition<_grpc_channelz_v1_GetTopChannelsRequest, _grpc_channelz_v1_GetTopChannelsRequest__Output>; + GetTopChannelsResponse: MessageTypeDefinition<_grpc_channelz_v1_GetTopChannelsResponse, _grpc_channelz_v1_GetTopChannelsResponse__Output>; + Security: MessageTypeDefinition<_grpc_channelz_v1_Security, _grpc_channelz_v1_Security__Output>; + Server: MessageTypeDefinition<_grpc_channelz_v1_Server, _grpc_channelz_v1_Server__Output>; + ServerData: MessageTypeDefinition<_grpc_channelz_v1_ServerData, _grpc_channelz_v1_ServerData__Output>; + ServerRef: MessageTypeDefinition<_grpc_channelz_v1_ServerRef, _grpc_channelz_v1_ServerRef__Output>; + Socket: MessageTypeDefinition<_grpc_channelz_v1_Socket, _grpc_channelz_v1_Socket__Output>; + SocketData: MessageTypeDefinition<_grpc_channelz_v1_SocketData, _grpc_channelz_v1_SocketData__Output>; + SocketOption: MessageTypeDefinition<_grpc_channelz_v1_SocketOption, _grpc_channelz_v1_SocketOption__Output>; + SocketOptionLinger: MessageTypeDefinition<_grpc_channelz_v1_SocketOptionLinger, _grpc_channelz_v1_SocketOptionLinger__Output>; + SocketOptionTcpInfo: MessageTypeDefinition<_grpc_channelz_v1_SocketOptionTcpInfo, _grpc_channelz_v1_SocketOptionTcpInfo__Output>; + SocketOptionTimeout: MessageTypeDefinition<_grpc_channelz_v1_SocketOptionTimeout, _grpc_channelz_v1_SocketOptionTimeout__Output>; + SocketRef: MessageTypeDefinition<_grpc_channelz_v1_SocketRef, _grpc_channelz_v1_SocketRef__Output>; + Subchannel: MessageTypeDefinition<_grpc_channelz_v1_Subchannel, _grpc_channelz_v1_Subchannel__Output>; + SubchannelRef: MessageTypeDefinition<_grpc_channelz_v1_SubchannelRef, _grpc_channelz_v1_SubchannelRef__Output>; + }; + }; + }; +} +export {}; diff --git a/node_modules/@grpc/grpc-js/build/src/generated/channelz.js b/node_modules/@grpc/grpc-js/build/src/generated/channelz.js new file mode 100644 index 0000000..0c2cf67 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/channelz.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=channelz.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/channelz.js.map b/node_modules/@grpc/grpc-js/build/src/generated/channelz.js.map new file mode 100644 index 0000000..af4016b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/channelz.js.map @@ -0,0 +1 @@ +{"version":3,"file":"channelz.js","sourceRoot":"","sources":["../../../src/generated/channelz.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.d.ts new file mode 100644 index 0000000..1aa55a4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.d.ts @@ -0,0 +1,9 @@ +import type { AnyExtension } from '@grpc/proto-loader'; +export type Any = AnyExtension | { + type_url: string; + value: Buffer | Uint8Array | string; +}; +export interface Any__Output { + 'type_url': (string); + 'value': (Buffer); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.js new file mode 100644 index 0000000..f9651f8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Any.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.js.map new file mode 100644 index 0000000..2e75474 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Any.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/Any.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.d.ts new file mode 100644 index 0000000..b7235a7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.d.ts @@ -0,0 +1,6 @@ +export interface BoolValue { + 'value'?: (boolean); +} +export interface BoolValue__Output { + 'value': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.js new file mode 100644 index 0000000..f893f74 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=BoolValue.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.js.map new file mode 100644 index 0000000..3573853 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.js.map @@ -0,0 +1 @@ +{"version":3,"file":"BoolValue.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/BoolValue.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.d.ts new file mode 100644 index 0000000..ec0dae9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.d.ts @@ -0,0 +1,6 @@ +export interface BytesValue { + 'value'?: (Buffer | Uint8Array | string); +} +export interface BytesValue__Output { + 'value': (Buffer); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.js new file mode 100644 index 0000000..4cac93e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=BytesValue.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.js.map new file mode 100644 index 0000000..a589ea5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.js.map @@ -0,0 +1 @@ +{"version":3,"file":"BytesValue.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/BytesValue.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DescriptorProto.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DescriptorProto.d.ts new file mode 100644 index 0000000..35e95e1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DescriptorProto.d.ts @@ -0,0 +1,51 @@ +import type { FieldDescriptorProto as _google_protobuf_FieldDescriptorProto, FieldDescriptorProto__Output as _google_protobuf_FieldDescriptorProto__Output } from '../../google/protobuf/FieldDescriptorProto'; +import type { DescriptorProto as _google_protobuf_DescriptorProto, DescriptorProto__Output as _google_protobuf_DescriptorProto__Output } from '../../google/protobuf/DescriptorProto'; +import type { EnumDescriptorProto as _google_protobuf_EnumDescriptorProto, EnumDescriptorProto__Output as _google_protobuf_EnumDescriptorProto__Output } from '../../google/protobuf/EnumDescriptorProto'; +import type { MessageOptions as _google_protobuf_MessageOptions, MessageOptions__Output as _google_protobuf_MessageOptions__Output } from '../../google/protobuf/MessageOptions'; +import type { OneofDescriptorProto as _google_protobuf_OneofDescriptorProto, OneofDescriptorProto__Output as _google_protobuf_OneofDescriptorProto__Output } from '../../google/protobuf/OneofDescriptorProto'; +import type { SymbolVisibility as _google_protobuf_SymbolVisibility, SymbolVisibility__Output as _google_protobuf_SymbolVisibility__Output } from '../../google/protobuf/SymbolVisibility'; +import type { ExtensionRangeOptions as _google_protobuf_ExtensionRangeOptions, ExtensionRangeOptions__Output as _google_protobuf_ExtensionRangeOptions__Output } from '../../google/protobuf/ExtensionRangeOptions'; +export interface _google_protobuf_DescriptorProto_ExtensionRange { + 'start'?: (number); + 'end'?: (number); + 'options'?: (_google_protobuf_ExtensionRangeOptions | null); +} +export interface _google_protobuf_DescriptorProto_ExtensionRange__Output { + 'start': (number); + 'end': (number); + 'options': (_google_protobuf_ExtensionRangeOptions__Output | null); +} +export interface _google_protobuf_DescriptorProto_ReservedRange { + 'start'?: (number); + 'end'?: (number); +} +export interface _google_protobuf_DescriptorProto_ReservedRange__Output { + 'start': (number); + 'end': (number); +} +export interface DescriptorProto { + 'name'?: (string); + 'field'?: (_google_protobuf_FieldDescriptorProto)[]; + 'nestedType'?: (_google_protobuf_DescriptorProto)[]; + 'enumType'?: (_google_protobuf_EnumDescriptorProto)[]; + 'extensionRange'?: (_google_protobuf_DescriptorProto_ExtensionRange)[]; + 'extension'?: (_google_protobuf_FieldDescriptorProto)[]; + 'options'?: (_google_protobuf_MessageOptions | null); + 'oneofDecl'?: (_google_protobuf_OneofDescriptorProto)[]; + 'reservedRange'?: (_google_protobuf_DescriptorProto_ReservedRange)[]; + 'reservedName'?: (string)[]; + 'visibility'?: (_google_protobuf_SymbolVisibility); +} +export interface DescriptorProto__Output { + 'name': (string); + 'field': (_google_protobuf_FieldDescriptorProto__Output)[]; + 'nestedType': (_google_protobuf_DescriptorProto__Output)[]; + 'enumType': (_google_protobuf_EnumDescriptorProto__Output)[]; + 'extensionRange': (_google_protobuf_DescriptorProto_ExtensionRange__Output)[]; + 'extension': (_google_protobuf_FieldDescriptorProto__Output)[]; + 'options': (_google_protobuf_MessageOptions__Output | null); + 'oneofDecl': (_google_protobuf_OneofDescriptorProto__Output)[]; + 'reservedRange': (_google_protobuf_DescriptorProto_ReservedRange__Output)[]; + 'reservedName': (string)[]; + 'visibility': (_google_protobuf_SymbolVisibility__Output); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DescriptorProto.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DescriptorProto.js new file mode 100644 index 0000000..ea5f608 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DescriptorProto.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=DescriptorProto.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DescriptorProto.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DescriptorProto.js.map new file mode 100644 index 0000000..0855a90 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DescriptorProto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"DescriptorProto.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/DescriptorProto.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.d.ts new file mode 100644 index 0000000..e4e2204 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.d.ts @@ -0,0 +1,6 @@ +export interface DoubleValue { + 'value'?: (number | string); +} +export interface DoubleValue__Output { + 'value': (number); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.js new file mode 100644 index 0000000..133e011 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=DoubleValue.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.js.map new file mode 100644 index 0000000..7f28720 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.js.map @@ -0,0 +1 @@ +{"version":3,"file":"DoubleValue.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/DoubleValue.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.d.ts new file mode 100644 index 0000000..7e04ea6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.d.ts @@ -0,0 +1,9 @@ +import type { Long } from '@grpc/proto-loader'; +export interface Duration { + 'seconds'?: (number | string | Long); + 'nanos'?: (number); +} +export interface Duration__Output { + 'seconds': (string); + 'nanos': (number); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.js new file mode 100644 index 0000000..b071b70 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Duration.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.js.map new file mode 100644 index 0000000..3fc8fe8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Duration.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/Duration.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Edition.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Edition.d.ts new file mode 100644 index 0000000..6ec1032 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Edition.d.ts @@ -0,0 +1,16 @@ +export declare const Edition: { + readonly EDITION_UNKNOWN: "EDITION_UNKNOWN"; + readonly EDITION_LEGACY: "EDITION_LEGACY"; + readonly EDITION_PROTO2: "EDITION_PROTO2"; + readonly EDITION_PROTO3: "EDITION_PROTO3"; + readonly EDITION_2023: "EDITION_2023"; + readonly EDITION_2024: "EDITION_2024"; + readonly EDITION_1_TEST_ONLY: "EDITION_1_TEST_ONLY"; + readonly EDITION_2_TEST_ONLY: "EDITION_2_TEST_ONLY"; + readonly EDITION_99997_TEST_ONLY: "EDITION_99997_TEST_ONLY"; + readonly EDITION_99998_TEST_ONLY: "EDITION_99998_TEST_ONLY"; + readonly EDITION_99999_TEST_ONLY: "EDITION_99999_TEST_ONLY"; + readonly EDITION_MAX: "EDITION_MAX"; +}; +export type Edition = 'EDITION_UNKNOWN' | 0 | 'EDITION_LEGACY' | 900 | 'EDITION_PROTO2' | 998 | 'EDITION_PROTO3' | 999 | 'EDITION_2023' | 1000 | 'EDITION_2024' | 1001 | 'EDITION_1_TEST_ONLY' | 1 | 'EDITION_2_TEST_ONLY' | 2 | 'EDITION_99997_TEST_ONLY' | 99997 | 'EDITION_99998_TEST_ONLY' | 99998 | 'EDITION_99999_TEST_ONLY' | 99999 | 'EDITION_MAX' | 2147483647; +export type Edition__Output = typeof Edition[keyof typeof Edition]; diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Edition.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Edition.js new file mode 100644 index 0000000..e3d848d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Edition.js @@ -0,0 +1,19 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Edition = void 0; +exports.Edition = { + EDITION_UNKNOWN: 'EDITION_UNKNOWN', + EDITION_LEGACY: 'EDITION_LEGACY', + EDITION_PROTO2: 'EDITION_PROTO2', + EDITION_PROTO3: 'EDITION_PROTO3', + EDITION_2023: 'EDITION_2023', + EDITION_2024: 'EDITION_2024', + EDITION_1_TEST_ONLY: 'EDITION_1_TEST_ONLY', + EDITION_2_TEST_ONLY: 'EDITION_2_TEST_ONLY', + EDITION_99997_TEST_ONLY: 'EDITION_99997_TEST_ONLY', + EDITION_99998_TEST_ONLY: 'EDITION_99998_TEST_ONLY', + EDITION_99999_TEST_ONLY: 'EDITION_99999_TEST_ONLY', + EDITION_MAX: 'EDITION_MAX', +}; +//# sourceMappingURL=Edition.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Edition.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Edition.js.map new file mode 100644 index 0000000..ce43ad0 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Edition.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Edition.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/Edition.ts"],"names":[],"mappings":";AAAA,sBAAsB;;;AAET,QAAA,OAAO,GAAG;IACrB,eAAe,EAAE,iBAAiB;IAClC,cAAc,EAAE,gBAAgB;IAChC,cAAc,EAAE,gBAAgB;IAChC,cAAc,EAAE,gBAAgB;IAChC,YAAY,EAAE,cAAc;IAC5B,YAAY,EAAE,cAAc;IAC5B,mBAAmB,EAAE,qBAAqB;IAC1C,mBAAmB,EAAE,qBAAqB;IAC1C,uBAAuB,EAAE,yBAAyB;IAClD,uBAAuB,EAAE,yBAAyB;IAClD,uBAAuB,EAAE,yBAAyB;IAClD,WAAW,EAAE,aAAa;CAClB,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumDescriptorProto.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumDescriptorProto.d.ts new file mode 100644 index 0000000..943eb31 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumDescriptorProto.d.ts @@ -0,0 +1,27 @@ +import type { EnumValueDescriptorProto as _google_protobuf_EnumValueDescriptorProto, EnumValueDescriptorProto__Output as _google_protobuf_EnumValueDescriptorProto__Output } from '../../google/protobuf/EnumValueDescriptorProto'; +import type { EnumOptions as _google_protobuf_EnumOptions, EnumOptions__Output as _google_protobuf_EnumOptions__Output } from '../../google/protobuf/EnumOptions'; +import type { SymbolVisibility as _google_protobuf_SymbolVisibility, SymbolVisibility__Output as _google_protobuf_SymbolVisibility__Output } from '../../google/protobuf/SymbolVisibility'; +export interface _google_protobuf_EnumDescriptorProto_EnumReservedRange { + 'start'?: (number); + 'end'?: (number); +} +export interface _google_protobuf_EnumDescriptorProto_EnumReservedRange__Output { + 'start': (number); + 'end': (number); +} +export interface EnumDescriptorProto { + 'name'?: (string); + 'value'?: (_google_protobuf_EnumValueDescriptorProto)[]; + 'options'?: (_google_protobuf_EnumOptions | null); + 'reservedRange'?: (_google_protobuf_EnumDescriptorProto_EnumReservedRange)[]; + 'reservedName'?: (string)[]; + 'visibility'?: (_google_protobuf_SymbolVisibility); +} +export interface EnumDescriptorProto__Output { + 'name': (string); + 'value': (_google_protobuf_EnumValueDescriptorProto__Output)[]; + 'options': (_google_protobuf_EnumOptions__Output | null); + 'reservedRange': (_google_protobuf_EnumDescriptorProto_EnumReservedRange__Output)[]; + 'reservedName': (string)[]; + 'visibility': (_google_protobuf_SymbolVisibility__Output); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumDescriptorProto.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumDescriptorProto.js new file mode 100644 index 0000000..903ec03 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumDescriptorProto.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=EnumDescriptorProto.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumDescriptorProto.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumDescriptorProto.js.map new file mode 100644 index 0000000..9eef1e6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumDescriptorProto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"EnumDescriptorProto.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/EnumDescriptorProto.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumOptions.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumOptions.d.ts new file mode 100644 index 0000000..690d0dc --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumOptions.d.ts @@ -0,0 +1,22 @@ +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from '../../google/protobuf/FeatureSet'; +import type { UninterpretedOption as _google_protobuf_UninterpretedOption, UninterpretedOption__Output as _google_protobuf_UninterpretedOption__Output } from '../../google/protobuf/UninterpretedOption'; +export interface EnumOptions { + 'allowAlias'?: (boolean); + 'deprecated'?: (boolean); + /** + * @deprecated + */ + 'deprecatedLegacyJsonFieldConflicts'?: (boolean); + 'features'?: (_google_protobuf_FeatureSet | null); + 'uninterpretedOption'?: (_google_protobuf_UninterpretedOption)[]; +} +export interface EnumOptions__Output { + 'allowAlias': (boolean); + 'deprecated': (boolean); + /** + * @deprecated + */ + 'deprecatedLegacyJsonFieldConflicts': (boolean); + 'features': (_google_protobuf_FeatureSet__Output | null); + 'uninterpretedOption': (_google_protobuf_UninterpretedOption__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumOptions.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumOptions.js new file mode 100644 index 0000000..9b8fa44 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumOptions.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=EnumOptions.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumOptions.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumOptions.js.map new file mode 100644 index 0000000..5f1f05a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumOptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"EnumOptions.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/EnumOptions.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueDescriptorProto.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueDescriptorProto.d.ts new file mode 100644 index 0000000..b0a458b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueDescriptorProto.d.ts @@ -0,0 +1,11 @@ +import type { EnumValueOptions as _google_protobuf_EnumValueOptions, EnumValueOptions__Output as _google_protobuf_EnumValueOptions__Output } from '../../google/protobuf/EnumValueOptions'; +export interface EnumValueDescriptorProto { + 'name'?: (string); + 'number'?: (number); + 'options'?: (_google_protobuf_EnumValueOptions | null); +} +export interface EnumValueDescriptorProto__Output { + 'name': (string); + 'number': (number); + 'options': (_google_protobuf_EnumValueOptions__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueDescriptorProto.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueDescriptorProto.js new file mode 100644 index 0000000..d19f3db --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueDescriptorProto.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=EnumValueDescriptorProto.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueDescriptorProto.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueDescriptorProto.js.map new file mode 100644 index 0000000..624fe37 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueDescriptorProto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"EnumValueDescriptorProto.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/EnumValueDescriptorProto.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueOptions.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueOptions.d.ts new file mode 100644 index 0000000..198dde7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueOptions.d.ts @@ -0,0 +1,17 @@ +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from '../../google/protobuf/FeatureSet'; +import type { _google_protobuf_FieldOptions_FeatureSupport, _google_protobuf_FieldOptions_FeatureSupport__Output } from '../../google/protobuf/FieldOptions'; +import type { UninterpretedOption as _google_protobuf_UninterpretedOption, UninterpretedOption__Output as _google_protobuf_UninterpretedOption__Output } from '../../google/protobuf/UninterpretedOption'; +export interface EnumValueOptions { + 'deprecated'?: (boolean); + 'features'?: (_google_protobuf_FeatureSet | null); + 'debugRedact'?: (boolean); + 'featureSupport'?: (_google_protobuf_FieldOptions_FeatureSupport | null); + 'uninterpretedOption'?: (_google_protobuf_UninterpretedOption)[]; +} +export interface EnumValueOptions__Output { + 'deprecated': (boolean); + 'features': (_google_protobuf_FeatureSet__Output | null); + 'debugRedact': (boolean); + 'featureSupport': (_google_protobuf_FieldOptions_FeatureSupport__Output | null); + 'uninterpretedOption': (_google_protobuf_UninterpretedOption__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueOptions.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueOptions.js new file mode 100644 index 0000000..bfe5888 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueOptions.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=EnumValueOptions.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueOptions.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueOptions.js.map new file mode 100644 index 0000000..bc6df35 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/EnumValueOptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"EnumValueOptions.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/EnumValueOptions.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ExtensionRangeOptions.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ExtensionRangeOptions.d.ts new file mode 100644 index 0000000..b296f6e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ExtensionRangeOptions.d.ts @@ -0,0 +1,34 @@ +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from '../../google/protobuf/FeatureSet'; +import type { UninterpretedOption as _google_protobuf_UninterpretedOption, UninterpretedOption__Output as _google_protobuf_UninterpretedOption__Output } from '../../google/protobuf/UninterpretedOption'; +export interface _google_protobuf_ExtensionRangeOptions_Declaration { + 'number'?: (number); + 'fullName'?: (string); + 'type'?: (string); + 'reserved'?: (boolean); + 'repeated'?: (boolean); +} +export interface _google_protobuf_ExtensionRangeOptions_Declaration__Output { + 'number': (number); + 'fullName': (string); + 'type': (string); + 'reserved': (boolean); + 'repeated': (boolean); +} +export declare const _google_protobuf_ExtensionRangeOptions_VerificationState: { + readonly DECLARATION: "DECLARATION"; + readonly UNVERIFIED: "UNVERIFIED"; +}; +export type _google_protobuf_ExtensionRangeOptions_VerificationState = 'DECLARATION' | 0 | 'UNVERIFIED' | 1; +export type _google_protobuf_ExtensionRangeOptions_VerificationState__Output = typeof _google_protobuf_ExtensionRangeOptions_VerificationState[keyof typeof _google_protobuf_ExtensionRangeOptions_VerificationState]; +export interface ExtensionRangeOptions { + 'declaration'?: (_google_protobuf_ExtensionRangeOptions_Declaration)[]; + 'verification'?: (_google_protobuf_ExtensionRangeOptions_VerificationState); + 'features'?: (_google_protobuf_FeatureSet | null); + 'uninterpretedOption'?: (_google_protobuf_UninterpretedOption)[]; +} +export interface ExtensionRangeOptions__Output { + 'declaration': (_google_protobuf_ExtensionRangeOptions_Declaration__Output)[]; + 'verification': (_google_protobuf_ExtensionRangeOptions_VerificationState__Output); + 'features': (_google_protobuf_FeatureSet__Output | null); + 'uninterpretedOption': (_google_protobuf_UninterpretedOption__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ExtensionRangeOptions.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ExtensionRangeOptions.js new file mode 100644 index 0000000..d210aaf --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ExtensionRangeOptions.js @@ -0,0 +1,10 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +exports._google_protobuf_ExtensionRangeOptions_VerificationState = void 0; +// Original file: null +exports._google_protobuf_ExtensionRangeOptions_VerificationState = { + DECLARATION: 'DECLARATION', + UNVERIFIED: 'UNVERIFIED', +}; +//# sourceMappingURL=ExtensionRangeOptions.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ExtensionRangeOptions.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ExtensionRangeOptions.js.map new file mode 100644 index 0000000..1c37476 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ExtensionRangeOptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ExtensionRangeOptions.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/ExtensionRangeOptions.ts"],"names":[],"mappings":";AAAA,sBAAsB;;;AAqBtB,sBAAsB;AAET,QAAA,wDAAwD,GAAG;IACtE,WAAW,EAAE,aAAa;IAC1B,UAAU,EAAE,YAAY;CAChB,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSet.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSet.d.ts new file mode 100644 index 0000000..7d60053 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSet.d.ts @@ -0,0 +1,83 @@ +export declare const _google_protobuf_FeatureSet_VisibilityFeature_DefaultSymbolVisibility: { + readonly DEFAULT_SYMBOL_VISIBILITY_UNKNOWN: "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN"; + readonly EXPORT_ALL: "EXPORT_ALL"; + readonly EXPORT_TOP_LEVEL: "EXPORT_TOP_LEVEL"; + readonly LOCAL_ALL: "LOCAL_ALL"; + readonly STRICT: "STRICT"; +}; +export type _google_protobuf_FeatureSet_VisibilityFeature_DefaultSymbolVisibility = 'DEFAULT_SYMBOL_VISIBILITY_UNKNOWN' | 0 | 'EXPORT_ALL' | 1 | 'EXPORT_TOP_LEVEL' | 2 | 'LOCAL_ALL' | 3 | 'STRICT' | 4; +export type _google_protobuf_FeatureSet_VisibilityFeature_DefaultSymbolVisibility__Output = typeof _google_protobuf_FeatureSet_VisibilityFeature_DefaultSymbolVisibility[keyof typeof _google_protobuf_FeatureSet_VisibilityFeature_DefaultSymbolVisibility]; +export declare const _google_protobuf_FeatureSet_EnforceNamingStyle: { + readonly ENFORCE_NAMING_STYLE_UNKNOWN: "ENFORCE_NAMING_STYLE_UNKNOWN"; + readonly STYLE2024: "STYLE2024"; + readonly STYLE_LEGACY: "STYLE_LEGACY"; +}; +export type _google_protobuf_FeatureSet_EnforceNamingStyle = 'ENFORCE_NAMING_STYLE_UNKNOWN' | 0 | 'STYLE2024' | 1 | 'STYLE_LEGACY' | 2; +export type _google_protobuf_FeatureSet_EnforceNamingStyle__Output = typeof _google_protobuf_FeatureSet_EnforceNamingStyle[keyof typeof _google_protobuf_FeatureSet_EnforceNamingStyle]; +export declare const _google_protobuf_FeatureSet_EnumType: { + readonly ENUM_TYPE_UNKNOWN: "ENUM_TYPE_UNKNOWN"; + readonly OPEN: "OPEN"; + readonly CLOSED: "CLOSED"; +}; +export type _google_protobuf_FeatureSet_EnumType = 'ENUM_TYPE_UNKNOWN' | 0 | 'OPEN' | 1 | 'CLOSED' | 2; +export type _google_protobuf_FeatureSet_EnumType__Output = typeof _google_protobuf_FeatureSet_EnumType[keyof typeof _google_protobuf_FeatureSet_EnumType]; +export declare const _google_protobuf_FeatureSet_FieldPresence: { + readonly FIELD_PRESENCE_UNKNOWN: "FIELD_PRESENCE_UNKNOWN"; + readonly EXPLICIT: "EXPLICIT"; + readonly IMPLICIT: "IMPLICIT"; + readonly LEGACY_REQUIRED: "LEGACY_REQUIRED"; +}; +export type _google_protobuf_FeatureSet_FieldPresence = 'FIELD_PRESENCE_UNKNOWN' | 0 | 'EXPLICIT' | 1 | 'IMPLICIT' | 2 | 'LEGACY_REQUIRED' | 3; +export type _google_protobuf_FeatureSet_FieldPresence__Output = typeof _google_protobuf_FeatureSet_FieldPresence[keyof typeof _google_protobuf_FeatureSet_FieldPresence]; +export declare const _google_protobuf_FeatureSet_JsonFormat: { + readonly JSON_FORMAT_UNKNOWN: "JSON_FORMAT_UNKNOWN"; + readonly ALLOW: "ALLOW"; + readonly LEGACY_BEST_EFFORT: "LEGACY_BEST_EFFORT"; +}; +export type _google_protobuf_FeatureSet_JsonFormat = 'JSON_FORMAT_UNKNOWN' | 0 | 'ALLOW' | 1 | 'LEGACY_BEST_EFFORT' | 2; +export type _google_protobuf_FeatureSet_JsonFormat__Output = typeof _google_protobuf_FeatureSet_JsonFormat[keyof typeof _google_protobuf_FeatureSet_JsonFormat]; +export declare const _google_protobuf_FeatureSet_MessageEncoding: { + readonly MESSAGE_ENCODING_UNKNOWN: "MESSAGE_ENCODING_UNKNOWN"; + readonly LENGTH_PREFIXED: "LENGTH_PREFIXED"; + readonly DELIMITED: "DELIMITED"; +}; +export type _google_protobuf_FeatureSet_MessageEncoding = 'MESSAGE_ENCODING_UNKNOWN' | 0 | 'LENGTH_PREFIXED' | 1 | 'DELIMITED' | 2; +export type _google_protobuf_FeatureSet_MessageEncoding__Output = typeof _google_protobuf_FeatureSet_MessageEncoding[keyof typeof _google_protobuf_FeatureSet_MessageEncoding]; +export declare const _google_protobuf_FeatureSet_RepeatedFieldEncoding: { + readonly REPEATED_FIELD_ENCODING_UNKNOWN: "REPEATED_FIELD_ENCODING_UNKNOWN"; + readonly PACKED: "PACKED"; + readonly EXPANDED: "EXPANDED"; +}; +export type _google_protobuf_FeatureSet_RepeatedFieldEncoding = 'REPEATED_FIELD_ENCODING_UNKNOWN' | 0 | 'PACKED' | 1 | 'EXPANDED' | 2; +export type _google_protobuf_FeatureSet_RepeatedFieldEncoding__Output = typeof _google_protobuf_FeatureSet_RepeatedFieldEncoding[keyof typeof _google_protobuf_FeatureSet_RepeatedFieldEncoding]; +export declare const _google_protobuf_FeatureSet_Utf8Validation: { + readonly UTF8_VALIDATION_UNKNOWN: "UTF8_VALIDATION_UNKNOWN"; + readonly VERIFY: "VERIFY"; + readonly NONE: "NONE"; +}; +export type _google_protobuf_FeatureSet_Utf8Validation = 'UTF8_VALIDATION_UNKNOWN' | 0 | 'VERIFY' | 2 | 'NONE' | 3; +export type _google_protobuf_FeatureSet_Utf8Validation__Output = typeof _google_protobuf_FeatureSet_Utf8Validation[keyof typeof _google_protobuf_FeatureSet_Utf8Validation]; +export interface _google_protobuf_FeatureSet_VisibilityFeature { +} +export interface _google_protobuf_FeatureSet_VisibilityFeature__Output { +} +export interface FeatureSet { + 'fieldPresence'?: (_google_protobuf_FeatureSet_FieldPresence); + 'enumType'?: (_google_protobuf_FeatureSet_EnumType); + 'repeatedFieldEncoding'?: (_google_protobuf_FeatureSet_RepeatedFieldEncoding); + 'utf8Validation'?: (_google_protobuf_FeatureSet_Utf8Validation); + 'messageEncoding'?: (_google_protobuf_FeatureSet_MessageEncoding); + 'jsonFormat'?: (_google_protobuf_FeatureSet_JsonFormat); + 'enforceNamingStyle'?: (_google_protobuf_FeatureSet_EnforceNamingStyle); + 'defaultSymbolVisibility'?: (_google_protobuf_FeatureSet_VisibilityFeature_DefaultSymbolVisibility); +} +export interface FeatureSet__Output { + 'fieldPresence': (_google_protobuf_FeatureSet_FieldPresence__Output); + 'enumType': (_google_protobuf_FeatureSet_EnumType__Output); + 'repeatedFieldEncoding': (_google_protobuf_FeatureSet_RepeatedFieldEncoding__Output); + 'utf8Validation': (_google_protobuf_FeatureSet_Utf8Validation__Output); + 'messageEncoding': (_google_protobuf_FeatureSet_MessageEncoding__Output); + 'jsonFormat': (_google_protobuf_FeatureSet_JsonFormat__Output); + 'enforceNamingStyle': (_google_protobuf_FeatureSet_EnforceNamingStyle__Output); + 'defaultSymbolVisibility': (_google_protobuf_FeatureSet_VisibilityFeature_DefaultSymbolVisibility__Output); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSet.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSet.js new file mode 100644 index 0000000..2aa1002 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSet.js @@ -0,0 +1,56 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +exports._google_protobuf_FeatureSet_Utf8Validation = exports._google_protobuf_FeatureSet_RepeatedFieldEncoding = exports._google_protobuf_FeatureSet_MessageEncoding = exports._google_protobuf_FeatureSet_JsonFormat = exports._google_protobuf_FeatureSet_FieldPresence = exports._google_protobuf_FeatureSet_EnumType = exports._google_protobuf_FeatureSet_EnforceNamingStyle = exports._google_protobuf_FeatureSet_VisibilityFeature_DefaultSymbolVisibility = void 0; +// Original file: null +exports._google_protobuf_FeatureSet_VisibilityFeature_DefaultSymbolVisibility = { + DEFAULT_SYMBOL_VISIBILITY_UNKNOWN: 'DEFAULT_SYMBOL_VISIBILITY_UNKNOWN', + EXPORT_ALL: 'EXPORT_ALL', + EXPORT_TOP_LEVEL: 'EXPORT_TOP_LEVEL', + LOCAL_ALL: 'LOCAL_ALL', + STRICT: 'STRICT', +}; +// Original file: null +exports._google_protobuf_FeatureSet_EnforceNamingStyle = { + ENFORCE_NAMING_STYLE_UNKNOWN: 'ENFORCE_NAMING_STYLE_UNKNOWN', + STYLE2024: 'STYLE2024', + STYLE_LEGACY: 'STYLE_LEGACY', +}; +// Original file: null +exports._google_protobuf_FeatureSet_EnumType = { + ENUM_TYPE_UNKNOWN: 'ENUM_TYPE_UNKNOWN', + OPEN: 'OPEN', + CLOSED: 'CLOSED', +}; +// Original file: null +exports._google_protobuf_FeatureSet_FieldPresence = { + FIELD_PRESENCE_UNKNOWN: 'FIELD_PRESENCE_UNKNOWN', + EXPLICIT: 'EXPLICIT', + IMPLICIT: 'IMPLICIT', + LEGACY_REQUIRED: 'LEGACY_REQUIRED', +}; +// Original file: null +exports._google_protobuf_FeatureSet_JsonFormat = { + JSON_FORMAT_UNKNOWN: 'JSON_FORMAT_UNKNOWN', + ALLOW: 'ALLOW', + LEGACY_BEST_EFFORT: 'LEGACY_BEST_EFFORT', +}; +// Original file: null +exports._google_protobuf_FeatureSet_MessageEncoding = { + MESSAGE_ENCODING_UNKNOWN: 'MESSAGE_ENCODING_UNKNOWN', + LENGTH_PREFIXED: 'LENGTH_PREFIXED', + DELIMITED: 'DELIMITED', +}; +// Original file: null +exports._google_protobuf_FeatureSet_RepeatedFieldEncoding = { + REPEATED_FIELD_ENCODING_UNKNOWN: 'REPEATED_FIELD_ENCODING_UNKNOWN', + PACKED: 'PACKED', + EXPANDED: 'EXPANDED', +}; +// Original file: null +exports._google_protobuf_FeatureSet_Utf8Validation = { + UTF8_VALIDATION_UNKNOWN: 'UTF8_VALIDATION_UNKNOWN', + VERIFY: 'VERIFY', + NONE: 'NONE', +}; +//# sourceMappingURL=FeatureSet.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSet.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSet.js.map new file mode 100644 index 0000000..86820cb --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSet.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FeatureSet.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/FeatureSet.ts"],"names":[],"mappings":";AAAA,sBAAsB;;;AAGtB,sBAAsB;AAET,QAAA,qEAAqE,GAAG;IACnF,iCAAiC,EAAE,mCAAmC;IACtE,UAAU,EAAE,YAAY;IACxB,gBAAgB,EAAE,kBAAkB;IACpC,SAAS,EAAE,WAAW;IACtB,MAAM,EAAE,QAAQ;CACR,CAAC;AAgBX,sBAAsB;AAET,QAAA,8CAA8C,GAAG;IAC5D,4BAA4B,EAAE,8BAA8B;IAC5D,SAAS,EAAE,WAAW;IACtB,YAAY,EAAE,cAAc;CACpB,CAAC;AAYX,sBAAsB;AAET,QAAA,oCAAoC,GAAG;IAClD,iBAAiB,EAAE,mBAAmB;IACtC,IAAI,EAAE,MAAM;IACZ,MAAM,EAAE,QAAQ;CACR,CAAC;AAYX,sBAAsB;AAET,QAAA,yCAAyC,GAAG;IACvD,sBAAsB,EAAE,wBAAwB;IAChD,QAAQ,EAAE,UAAU;IACpB,QAAQ,EAAE,UAAU;IACpB,eAAe,EAAE,iBAAiB;CAC1B,CAAC;AAcX,sBAAsB;AAET,QAAA,sCAAsC,GAAG;IACpD,mBAAmB,EAAE,qBAAqB;IAC1C,KAAK,EAAE,OAAO;IACd,kBAAkB,EAAE,oBAAoB;CAChC,CAAC;AAYX,sBAAsB;AAET,QAAA,2CAA2C,GAAG;IACzD,wBAAwB,EAAE,0BAA0B;IACpD,eAAe,EAAE,iBAAiB;IAClC,SAAS,EAAE,WAAW;CACd,CAAC;AAYX,sBAAsB;AAET,QAAA,iDAAiD,GAAG;IAC/D,+BAA+B,EAAE,iCAAiC;IAClE,MAAM,EAAE,QAAQ;IAChB,QAAQ,EAAE,UAAU;CACZ,CAAC;AAYX,sBAAsB;AAET,QAAA,0CAA0C,GAAG;IACxD,uBAAuB,EAAE,yBAAyB;IAClD,MAAM,EAAE,QAAQ;IAChB,IAAI,EAAE,MAAM;CACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSetDefaults.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSetDefaults.d.ts new file mode 100644 index 0000000..c305486 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSetDefaults.d.ts @@ -0,0 +1,22 @@ +import type { Edition as _google_protobuf_Edition, Edition__Output as _google_protobuf_Edition__Output } from '../../google/protobuf/Edition'; +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from '../../google/protobuf/FeatureSet'; +export interface _google_protobuf_FeatureSetDefaults_FeatureSetEditionDefault { + 'edition'?: (_google_protobuf_Edition); + 'overridableFeatures'?: (_google_protobuf_FeatureSet | null); + 'fixedFeatures'?: (_google_protobuf_FeatureSet | null); +} +export interface _google_protobuf_FeatureSetDefaults_FeatureSetEditionDefault__Output { + 'edition': (_google_protobuf_Edition__Output); + 'overridableFeatures': (_google_protobuf_FeatureSet__Output | null); + 'fixedFeatures': (_google_protobuf_FeatureSet__Output | null); +} +export interface FeatureSetDefaults { + 'defaults'?: (_google_protobuf_FeatureSetDefaults_FeatureSetEditionDefault)[]; + 'minimumEdition'?: (_google_protobuf_Edition); + 'maximumEdition'?: (_google_protobuf_Edition); +} +export interface FeatureSetDefaults__Output { + 'defaults': (_google_protobuf_FeatureSetDefaults_FeatureSetEditionDefault__Output)[]; + 'minimumEdition': (_google_protobuf_Edition__Output); + 'maximumEdition': (_google_protobuf_Edition__Output); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSetDefaults.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSetDefaults.js new file mode 100644 index 0000000..fbf2c8c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSetDefaults.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=FeatureSetDefaults.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSetDefaults.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSetDefaults.js.map new file mode 100644 index 0000000..a81eced --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FeatureSetDefaults.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FeatureSetDefaults.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/FeatureSetDefaults.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldDescriptorProto.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldDescriptorProto.d.ts new file mode 100644 index 0000000..b1250f1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldDescriptorProto.d.ts @@ -0,0 +1,56 @@ +import type { FieldOptions as _google_protobuf_FieldOptions, FieldOptions__Output as _google_protobuf_FieldOptions__Output } from '../../google/protobuf/FieldOptions'; +export declare const _google_protobuf_FieldDescriptorProto_Label: { + readonly LABEL_OPTIONAL: "LABEL_OPTIONAL"; + readonly LABEL_REPEATED: "LABEL_REPEATED"; + readonly LABEL_REQUIRED: "LABEL_REQUIRED"; +}; +export type _google_protobuf_FieldDescriptorProto_Label = 'LABEL_OPTIONAL' | 1 | 'LABEL_REPEATED' | 3 | 'LABEL_REQUIRED' | 2; +export type _google_protobuf_FieldDescriptorProto_Label__Output = typeof _google_protobuf_FieldDescriptorProto_Label[keyof typeof _google_protobuf_FieldDescriptorProto_Label]; +export declare const _google_protobuf_FieldDescriptorProto_Type: { + readonly TYPE_DOUBLE: "TYPE_DOUBLE"; + readonly TYPE_FLOAT: "TYPE_FLOAT"; + readonly TYPE_INT64: "TYPE_INT64"; + readonly TYPE_UINT64: "TYPE_UINT64"; + readonly TYPE_INT32: "TYPE_INT32"; + readonly TYPE_FIXED64: "TYPE_FIXED64"; + readonly TYPE_FIXED32: "TYPE_FIXED32"; + readonly TYPE_BOOL: "TYPE_BOOL"; + readonly TYPE_STRING: "TYPE_STRING"; + readonly TYPE_GROUP: "TYPE_GROUP"; + readonly TYPE_MESSAGE: "TYPE_MESSAGE"; + readonly TYPE_BYTES: "TYPE_BYTES"; + readonly TYPE_UINT32: "TYPE_UINT32"; + readonly TYPE_ENUM: "TYPE_ENUM"; + readonly TYPE_SFIXED32: "TYPE_SFIXED32"; + readonly TYPE_SFIXED64: "TYPE_SFIXED64"; + readonly TYPE_SINT32: "TYPE_SINT32"; + readonly TYPE_SINT64: "TYPE_SINT64"; +}; +export type _google_protobuf_FieldDescriptorProto_Type = 'TYPE_DOUBLE' | 1 | 'TYPE_FLOAT' | 2 | 'TYPE_INT64' | 3 | 'TYPE_UINT64' | 4 | 'TYPE_INT32' | 5 | 'TYPE_FIXED64' | 6 | 'TYPE_FIXED32' | 7 | 'TYPE_BOOL' | 8 | 'TYPE_STRING' | 9 | 'TYPE_GROUP' | 10 | 'TYPE_MESSAGE' | 11 | 'TYPE_BYTES' | 12 | 'TYPE_UINT32' | 13 | 'TYPE_ENUM' | 14 | 'TYPE_SFIXED32' | 15 | 'TYPE_SFIXED64' | 16 | 'TYPE_SINT32' | 17 | 'TYPE_SINT64' | 18; +export type _google_protobuf_FieldDescriptorProto_Type__Output = typeof _google_protobuf_FieldDescriptorProto_Type[keyof typeof _google_protobuf_FieldDescriptorProto_Type]; +export interface FieldDescriptorProto { + 'name'?: (string); + 'extendee'?: (string); + 'number'?: (number); + 'label'?: (_google_protobuf_FieldDescriptorProto_Label); + 'type'?: (_google_protobuf_FieldDescriptorProto_Type); + 'typeName'?: (string); + 'defaultValue'?: (string); + 'options'?: (_google_protobuf_FieldOptions | null); + 'oneofIndex'?: (number); + 'jsonName'?: (string); + 'proto3Optional'?: (boolean); +} +export interface FieldDescriptorProto__Output { + 'name': (string); + 'extendee': (string); + 'number': (number); + 'label': (_google_protobuf_FieldDescriptorProto_Label__Output); + 'type': (_google_protobuf_FieldDescriptorProto_Type__Output); + 'typeName': (string); + 'defaultValue': (string); + 'options': (_google_protobuf_FieldOptions__Output | null); + 'oneofIndex': (number); + 'jsonName': (string); + 'proto3Optional': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldDescriptorProto.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldDescriptorProto.js new file mode 100644 index 0000000..b47a320 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldDescriptorProto.js @@ -0,0 +1,32 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +exports._google_protobuf_FieldDescriptorProto_Type = exports._google_protobuf_FieldDescriptorProto_Label = void 0; +// Original file: null +exports._google_protobuf_FieldDescriptorProto_Label = { + LABEL_OPTIONAL: 'LABEL_OPTIONAL', + LABEL_REPEATED: 'LABEL_REPEATED', + LABEL_REQUIRED: 'LABEL_REQUIRED', +}; +// Original file: null +exports._google_protobuf_FieldDescriptorProto_Type = { + TYPE_DOUBLE: 'TYPE_DOUBLE', + TYPE_FLOAT: 'TYPE_FLOAT', + TYPE_INT64: 'TYPE_INT64', + TYPE_UINT64: 'TYPE_UINT64', + TYPE_INT32: 'TYPE_INT32', + TYPE_FIXED64: 'TYPE_FIXED64', + TYPE_FIXED32: 'TYPE_FIXED32', + TYPE_BOOL: 'TYPE_BOOL', + TYPE_STRING: 'TYPE_STRING', + TYPE_GROUP: 'TYPE_GROUP', + TYPE_MESSAGE: 'TYPE_MESSAGE', + TYPE_BYTES: 'TYPE_BYTES', + TYPE_UINT32: 'TYPE_UINT32', + TYPE_ENUM: 'TYPE_ENUM', + TYPE_SFIXED32: 'TYPE_SFIXED32', + TYPE_SFIXED64: 'TYPE_SFIXED64', + TYPE_SINT32: 'TYPE_SINT32', + TYPE_SINT64: 'TYPE_SINT64', +}; +//# sourceMappingURL=FieldDescriptorProto.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldDescriptorProto.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldDescriptorProto.js.map new file mode 100644 index 0000000..95373d0 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldDescriptorProto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FieldDescriptorProto.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/FieldDescriptorProto.ts"],"names":[],"mappings":";AAAA,sBAAsB;;;AAItB,sBAAsB;AAET,QAAA,2CAA2C,GAAG;IACzD,cAAc,EAAE,gBAAgB;IAChC,cAAc,EAAE,gBAAgB;IAChC,cAAc,EAAE,gBAAgB;CACxB,CAAC;AAYX,sBAAsB;AAET,QAAA,0CAA0C,GAAG;IACxD,WAAW,EAAE,aAAa;IAC1B,UAAU,EAAE,YAAY;IACxB,UAAU,EAAE,YAAY;IACxB,WAAW,EAAE,aAAa;IAC1B,UAAU,EAAE,YAAY;IACxB,YAAY,EAAE,cAAc;IAC5B,YAAY,EAAE,cAAc;IAC5B,SAAS,EAAE,WAAW;IACtB,WAAW,EAAE,aAAa;IAC1B,UAAU,EAAE,YAAY;IACxB,YAAY,EAAE,cAAc;IAC5B,UAAU,EAAE,YAAY;IACxB,WAAW,EAAE,aAAa;IAC1B,SAAS,EAAE,WAAW;IACtB,aAAa,EAAE,eAAe;IAC9B,aAAa,EAAE,eAAe;IAC9B,WAAW,EAAE,aAAa;IAC1B,WAAW,EAAE,aAAa;CAClB,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldOptions.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldOptions.d.ts new file mode 100644 index 0000000..7cc46ff --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldOptions.d.ts @@ -0,0 +1,99 @@ +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from '../../google/protobuf/FeatureSet'; +import type { UninterpretedOption as _google_protobuf_UninterpretedOption, UninterpretedOption__Output as _google_protobuf_UninterpretedOption__Output } from '../../google/protobuf/UninterpretedOption'; +import type { FieldRules as _validate_FieldRules, FieldRules__Output as _validate_FieldRules__Output } from '../../validate/FieldRules'; +import type { Edition as _google_protobuf_Edition, Edition__Output as _google_protobuf_Edition__Output } from '../../google/protobuf/Edition'; +export declare const _google_protobuf_FieldOptions_CType: { + readonly STRING: "STRING"; + readonly CORD: "CORD"; + readonly STRING_PIECE: "STRING_PIECE"; +}; +export type _google_protobuf_FieldOptions_CType = 'STRING' | 0 | 'CORD' | 1 | 'STRING_PIECE' | 2; +export type _google_protobuf_FieldOptions_CType__Output = typeof _google_protobuf_FieldOptions_CType[keyof typeof _google_protobuf_FieldOptions_CType]; +export interface _google_protobuf_FieldOptions_EditionDefault { + 'edition'?: (_google_protobuf_Edition); + 'value'?: (string); +} +export interface _google_protobuf_FieldOptions_EditionDefault__Output { + 'edition': (_google_protobuf_Edition__Output); + 'value': (string); +} +export interface _google_protobuf_FieldOptions_FeatureSupport { + 'editionIntroduced'?: (_google_protobuf_Edition); + 'editionDeprecated'?: (_google_protobuf_Edition); + 'deprecationWarning'?: (string); + 'editionRemoved'?: (_google_protobuf_Edition); +} +export interface _google_protobuf_FieldOptions_FeatureSupport__Output { + 'editionIntroduced': (_google_protobuf_Edition__Output); + 'editionDeprecated': (_google_protobuf_Edition__Output); + 'deprecationWarning': (string); + 'editionRemoved': (_google_protobuf_Edition__Output); +} +export declare const _google_protobuf_FieldOptions_JSType: { + readonly JS_NORMAL: "JS_NORMAL"; + readonly JS_STRING: "JS_STRING"; + readonly JS_NUMBER: "JS_NUMBER"; +}; +export type _google_protobuf_FieldOptions_JSType = 'JS_NORMAL' | 0 | 'JS_STRING' | 1 | 'JS_NUMBER' | 2; +export type _google_protobuf_FieldOptions_JSType__Output = typeof _google_protobuf_FieldOptions_JSType[keyof typeof _google_protobuf_FieldOptions_JSType]; +export declare const _google_protobuf_FieldOptions_OptionRetention: { + readonly RETENTION_UNKNOWN: "RETENTION_UNKNOWN"; + readonly RETENTION_RUNTIME: "RETENTION_RUNTIME"; + readonly RETENTION_SOURCE: "RETENTION_SOURCE"; +}; +export type _google_protobuf_FieldOptions_OptionRetention = 'RETENTION_UNKNOWN' | 0 | 'RETENTION_RUNTIME' | 1 | 'RETENTION_SOURCE' | 2; +export type _google_protobuf_FieldOptions_OptionRetention__Output = typeof _google_protobuf_FieldOptions_OptionRetention[keyof typeof _google_protobuf_FieldOptions_OptionRetention]; +export declare const _google_protobuf_FieldOptions_OptionTargetType: { + readonly TARGET_TYPE_UNKNOWN: "TARGET_TYPE_UNKNOWN"; + readonly TARGET_TYPE_FILE: "TARGET_TYPE_FILE"; + readonly TARGET_TYPE_EXTENSION_RANGE: "TARGET_TYPE_EXTENSION_RANGE"; + readonly TARGET_TYPE_MESSAGE: "TARGET_TYPE_MESSAGE"; + readonly TARGET_TYPE_FIELD: "TARGET_TYPE_FIELD"; + readonly TARGET_TYPE_ONEOF: "TARGET_TYPE_ONEOF"; + readonly TARGET_TYPE_ENUM: "TARGET_TYPE_ENUM"; + readonly TARGET_TYPE_ENUM_ENTRY: "TARGET_TYPE_ENUM_ENTRY"; + readonly TARGET_TYPE_SERVICE: "TARGET_TYPE_SERVICE"; + readonly TARGET_TYPE_METHOD: "TARGET_TYPE_METHOD"; +}; +export type _google_protobuf_FieldOptions_OptionTargetType = 'TARGET_TYPE_UNKNOWN' | 0 | 'TARGET_TYPE_FILE' | 1 | 'TARGET_TYPE_EXTENSION_RANGE' | 2 | 'TARGET_TYPE_MESSAGE' | 3 | 'TARGET_TYPE_FIELD' | 4 | 'TARGET_TYPE_ONEOF' | 5 | 'TARGET_TYPE_ENUM' | 6 | 'TARGET_TYPE_ENUM_ENTRY' | 7 | 'TARGET_TYPE_SERVICE' | 8 | 'TARGET_TYPE_METHOD' | 9; +export type _google_protobuf_FieldOptions_OptionTargetType__Output = typeof _google_protobuf_FieldOptions_OptionTargetType[keyof typeof _google_protobuf_FieldOptions_OptionTargetType]; +export interface FieldOptions { + 'ctype'?: (_google_protobuf_FieldOptions_CType); + 'packed'?: (boolean); + 'deprecated'?: (boolean); + 'lazy'?: (boolean); + 'jstype'?: (_google_protobuf_FieldOptions_JSType); + /** + * @deprecated + */ + 'weak'?: (boolean); + 'unverifiedLazy'?: (boolean); + 'debugRedact'?: (boolean); + 'retention'?: (_google_protobuf_FieldOptions_OptionRetention); + 'targets'?: (_google_protobuf_FieldOptions_OptionTargetType)[]; + 'editionDefaults'?: (_google_protobuf_FieldOptions_EditionDefault)[]; + 'features'?: (_google_protobuf_FeatureSet | null); + 'featureSupport'?: (_google_protobuf_FieldOptions_FeatureSupport | null); + 'uninterpretedOption'?: (_google_protobuf_UninterpretedOption)[]; + '.validate.rules'?: (_validate_FieldRules | null); +} +export interface FieldOptions__Output { + 'ctype': (_google_protobuf_FieldOptions_CType__Output); + 'packed': (boolean); + 'deprecated': (boolean); + 'lazy': (boolean); + 'jstype': (_google_protobuf_FieldOptions_JSType__Output); + /** + * @deprecated + */ + 'weak': (boolean); + 'unverifiedLazy': (boolean); + 'debugRedact': (boolean); + 'retention': (_google_protobuf_FieldOptions_OptionRetention__Output); + 'targets': (_google_protobuf_FieldOptions_OptionTargetType__Output)[]; + 'editionDefaults': (_google_protobuf_FieldOptions_EditionDefault__Output)[]; + 'features': (_google_protobuf_FeatureSet__Output | null); + 'featureSupport': (_google_protobuf_FieldOptions_FeatureSupport__Output | null); + 'uninterpretedOption': (_google_protobuf_UninterpretedOption__Output)[]; + '.validate.rules': (_validate_FieldRules__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldOptions.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldOptions.js new file mode 100644 index 0000000..d0cca00 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldOptions.js @@ -0,0 +1,36 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +exports._google_protobuf_FieldOptions_OptionTargetType = exports._google_protobuf_FieldOptions_OptionRetention = exports._google_protobuf_FieldOptions_JSType = exports._google_protobuf_FieldOptions_CType = void 0; +// Original file: null +exports._google_protobuf_FieldOptions_CType = { + STRING: 'STRING', + CORD: 'CORD', + STRING_PIECE: 'STRING_PIECE', +}; +// Original file: null +exports._google_protobuf_FieldOptions_JSType = { + JS_NORMAL: 'JS_NORMAL', + JS_STRING: 'JS_STRING', + JS_NUMBER: 'JS_NUMBER', +}; +// Original file: null +exports._google_protobuf_FieldOptions_OptionRetention = { + RETENTION_UNKNOWN: 'RETENTION_UNKNOWN', + RETENTION_RUNTIME: 'RETENTION_RUNTIME', + RETENTION_SOURCE: 'RETENTION_SOURCE', +}; +// Original file: null +exports._google_protobuf_FieldOptions_OptionTargetType = { + TARGET_TYPE_UNKNOWN: 'TARGET_TYPE_UNKNOWN', + TARGET_TYPE_FILE: 'TARGET_TYPE_FILE', + TARGET_TYPE_EXTENSION_RANGE: 'TARGET_TYPE_EXTENSION_RANGE', + TARGET_TYPE_MESSAGE: 'TARGET_TYPE_MESSAGE', + TARGET_TYPE_FIELD: 'TARGET_TYPE_FIELD', + TARGET_TYPE_ONEOF: 'TARGET_TYPE_ONEOF', + TARGET_TYPE_ENUM: 'TARGET_TYPE_ENUM', + TARGET_TYPE_ENUM_ENTRY: 'TARGET_TYPE_ENUM_ENTRY', + TARGET_TYPE_SERVICE: 'TARGET_TYPE_SERVICE', + TARGET_TYPE_METHOD: 'TARGET_TYPE_METHOD', +}; +//# sourceMappingURL=FieldOptions.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldOptions.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldOptions.js.map new file mode 100644 index 0000000..ddf7116 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FieldOptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FieldOptions.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/FieldOptions.ts"],"names":[],"mappings":";AAAA,sBAAsB;;;AAOtB,sBAAsB;AAET,QAAA,mCAAmC,GAAG;IACjD,MAAM,EAAE,QAAQ;IAChB,IAAI,EAAE,MAAM;IACZ,YAAY,EAAE,cAAc;CACpB,CAAC;AAoCX,sBAAsB;AAET,QAAA,oCAAoC,GAAG;IAClD,SAAS,EAAE,WAAW;IACtB,SAAS,EAAE,WAAW;IACtB,SAAS,EAAE,WAAW;CACd,CAAC;AAYX,sBAAsB;AAET,QAAA,6CAA6C,GAAG;IAC3D,iBAAiB,EAAE,mBAAmB;IACtC,iBAAiB,EAAE,mBAAmB;IACtC,gBAAgB,EAAE,kBAAkB;CAC5B,CAAC;AAYX,sBAAsB;AAET,QAAA,8CAA8C,GAAG;IAC5D,mBAAmB,EAAE,qBAAqB;IAC1C,gBAAgB,EAAE,kBAAkB;IACpC,2BAA2B,EAAE,6BAA6B;IAC1D,mBAAmB,EAAE,qBAAqB;IAC1C,iBAAiB,EAAE,mBAAmB;IACtC,iBAAiB,EAAE,mBAAmB;IACtC,gBAAgB,EAAE,kBAAkB;IACpC,sBAAsB,EAAE,wBAAwB;IAChD,mBAAmB,EAAE,qBAAqB;IAC1C,kBAAkB,EAAE,oBAAoB;CAChC,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorProto.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorProto.d.ts new file mode 100644 index 0000000..6e71048 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorProto.d.ts @@ -0,0 +1,39 @@ +import type { DescriptorProto as _google_protobuf_DescriptorProto, DescriptorProto__Output as _google_protobuf_DescriptorProto__Output } from '../../google/protobuf/DescriptorProto'; +import type { EnumDescriptorProto as _google_protobuf_EnumDescriptorProto, EnumDescriptorProto__Output as _google_protobuf_EnumDescriptorProto__Output } from '../../google/protobuf/EnumDescriptorProto'; +import type { ServiceDescriptorProto as _google_protobuf_ServiceDescriptorProto, ServiceDescriptorProto__Output as _google_protobuf_ServiceDescriptorProto__Output } from '../../google/protobuf/ServiceDescriptorProto'; +import type { FieldDescriptorProto as _google_protobuf_FieldDescriptorProto, FieldDescriptorProto__Output as _google_protobuf_FieldDescriptorProto__Output } from '../../google/protobuf/FieldDescriptorProto'; +import type { FileOptions as _google_protobuf_FileOptions, FileOptions__Output as _google_protobuf_FileOptions__Output } from '../../google/protobuf/FileOptions'; +import type { SourceCodeInfo as _google_protobuf_SourceCodeInfo, SourceCodeInfo__Output as _google_protobuf_SourceCodeInfo__Output } from '../../google/protobuf/SourceCodeInfo'; +import type { Edition as _google_protobuf_Edition, Edition__Output as _google_protobuf_Edition__Output } from '../../google/protobuf/Edition'; +export interface FileDescriptorProto { + 'name'?: (string); + 'package'?: (string); + 'dependency'?: (string)[]; + 'messageType'?: (_google_protobuf_DescriptorProto)[]; + 'enumType'?: (_google_protobuf_EnumDescriptorProto)[]; + 'service'?: (_google_protobuf_ServiceDescriptorProto)[]; + 'extension'?: (_google_protobuf_FieldDescriptorProto)[]; + 'options'?: (_google_protobuf_FileOptions | null); + 'sourceCodeInfo'?: (_google_protobuf_SourceCodeInfo | null); + 'publicDependency'?: (number)[]; + 'weakDependency'?: (number)[]; + 'syntax'?: (string); + 'edition'?: (_google_protobuf_Edition); + 'optionDependency'?: (string)[]; +} +export interface FileDescriptorProto__Output { + 'name': (string); + 'package': (string); + 'dependency': (string)[]; + 'messageType': (_google_protobuf_DescriptorProto__Output)[]; + 'enumType': (_google_protobuf_EnumDescriptorProto__Output)[]; + 'service': (_google_protobuf_ServiceDescriptorProto__Output)[]; + 'extension': (_google_protobuf_FieldDescriptorProto__Output)[]; + 'options': (_google_protobuf_FileOptions__Output | null); + 'sourceCodeInfo': (_google_protobuf_SourceCodeInfo__Output | null); + 'publicDependency': (number)[]; + 'weakDependency': (number)[]; + 'syntax': (string); + 'edition': (_google_protobuf_Edition__Output); + 'optionDependency': (string)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorProto.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorProto.js new file mode 100644 index 0000000..9eb665d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorProto.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=FileDescriptorProto.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorProto.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorProto.js.map new file mode 100644 index 0000000..cb1e0ce --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorProto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FileDescriptorProto.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/FileDescriptorProto.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorSet.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorSet.d.ts new file mode 100644 index 0000000..18931c1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorSet.d.ts @@ -0,0 +1,7 @@ +import type { FileDescriptorProto as _google_protobuf_FileDescriptorProto, FileDescriptorProto__Output as _google_protobuf_FileDescriptorProto__Output } from '../../google/protobuf/FileDescriptorProto'; +export interface FileDescriptorSet { + 'file'?: (_google_protobuf_FileDescriptorProto)[]; +} +export interface FileDescriptorSet__Output { + 'file': (_google_protobuf_FileDescriptorProto__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorSet.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorSet.js new file mode 100644 index 0000000..fcbe86a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorSet.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=FileDescriptorSet.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorSet.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorSet.js.map new file mode 100644 index 0000000..a911e6f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileDescriptorSet.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FileDescriptorSet.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/FileDescriptorSet.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileOptions.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileOptions.d.ts new file mode 100644 index 0000000..e5bfa52 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileOptions.d.ts @@ -0,0 +1,61 @@ +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from '../../google/protobuf/FeatureSet'; +import type { UninterpretedOption as _google_protobuf_UninterpretedOption, UninterpretedOption__Output as _google_protobuf_UninterpretedOption__Output } from '../../google/protobuf/UninterpretedOption'; +export declare const _google_protobuf_FileOptions_OptimizeMode: { + readonly SPEED: "SPEED"; + readonly CODE_SIZE: "CODE_SIZE"; + readonly LITE_RUNTIME: "LITE_RUNTIME"; +}; +export type _google_protobuf_FileOptions_OptimizeMode = 'SPEED' | 1 | 'CODE_SIZE' | 2 | 'LITE_RUNTIME' | 3; +export type _google_protobuf_FileOptions_OptimizeMode__Output = typeof _google_protobuf_FileOptions_OptimizeMode[keyof typeof _google_protobuf_FileOptions_OptimizeMode]; +export interface FileOptions { + 'javaPackage'?: (string); + 'javaOuterClassname'?: (string); + 'optimizeFor'?: (_google_protobuf_FileOptions_OptimizeMode); + 'javaMultipleFiles'?: (boolean); + 'goPackage'?: (string); + 'ccGenericServices'?: (boolean); + 'javaGenericServices'?: (boolean); + 'pyGenericServices'?: (boolean); + /** + * @deprecated + */ + 'javaGenerateEqualsAndHash'?: (boolean); + 'deprecated'?: (boolean); + 'javaStringCheckUtf8'?: (boolean); + 'ccEnableArenas'?: (boolean); + 'objcClassPrefix'?: (string); + 'csharpNamespace'?: (string); + 'swiftPrefix'?: (string); + 'phpClassPrefix'?: (string); + 'phpNamespace'?: (string); + 'phpMetadataNamespace'?: (string); + 'rubyPackage'?: (string); + 'features'?: (_google_protobuf_FeatureSet | null); + 'uninterpretedOption'?: (_google_protobuf_UninterpretedOption)[]; +} +export interface FileOptions__Output { + 'javaPackage': (string); + 'javaOuterClassname': (string); + 'optimizeFor': (_google_protobuf_FileOptions_OptimizeMode__Output); + 'javaMultipleFiles': (boolean); + 'goPackage': (string); + 'ccGenericServices': (boolean); + 'javaGenericServices': (boolean); + 'pyGenericServices': (boolean); + /** + * @deprecated + */ + 'javaGenerateEqualsAndHash': (boolean); + 'deprecated': (boolean); + 'javaStringCheckUtf8': (boolean); + 'ccEnableArenas': (boolean); + 'objcClassPrefix': (string); + 'csharpNamespace': (string); + 'swiftPrefix': (string); + 'phpClassPrefix': (string); + 'phpNamespace': (string); + 'phpMetadataNamespace': (string); + 'rubyPackage': (string); + 'features': (_google_protobuf_FeatureSet__Output | null); + 'uninterpretedOption': (_google_protobuf_UninterpretedOption__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileOptions.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileOptions.js new file mode 100644 index 0000000..abf630e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileOptions.js @@ -0,0 +1,11 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +exports._google_protobuf_FileOptions_OptimizeMode = void 0; +// Original file: null +exports._google_protobuf_FileOptions_OptimizeMode = { + SPEED: 'SPEED', + CODE_SIZE: 'CODE_SIZE', + LITE_RUNTIME: 'LITE_RUNTIME', +}; +//# sourceMappingURL=FileOptions.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileOptions.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileOptions.js.map new file mode 100644 index 0000000..3b2bc9e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FileOptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FileOptions.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/FileOptions.ts"],"names":[],"mappings":";AAAA,sBAAsB;;;AAKtB,sBAAsB;AAET,QAAA,yCAAyC,GAAG;IACvD,KAAK,EAAE,OAAO;IACd,SAAS,EAAE,WAAW;IACtB,YAAY,EAAE,cAAc;CACpB,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.d.ts new file mode 100644 index 0000000..33bd60b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.d.ts @@ -0,0 +1,6 @@ +export interface FloatValue { + 'value'?: (number | string); +} +export interface FloatValue__Output { + 'value': (number); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.js new file mode 100644 index 0000000..17290a2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=FloatValue.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.js.map new file mode 100644 index 0000000..bf27b78 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FloatValue.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/FloatValue.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/GeneratedCodeInfo.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/GeneratedCodeInfo.d.ts new file mode 100644 index 0000000..586daa7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/GeneratedCodeInfo.d.ts @@ -0,0 +1,27 @@ +export interface _google_protobuf_GeneratedCodeInfo_Annotation { + 'path'?: (number)[]; + 'sourceFile'?: (string); + 'begin'?: (number); + 'end'?: (number); + 'semantic'?: (_google_protobuf_GeneratedCodeInfo_Annotation_Semantic); +} +export interface _google_protobuf_GeneratedCodeInfo_Annotation__Output { + 'path': (number)[]; + 'sourceFile': (string); + 'begin': (number); + 'end': (number); + 'semantic': (_google_protobuf_GeneratedCodeInfo_Annotation_Semantic__Output); +} +export declare const _google_protobuf_GeneratedCodeInfo_Annotation_Semantic: { + readonly NONE: "NONE"; + readonly SET: "SET"; + readonly ALIAS: "ALIAS"; +}; +export type _google_protobuf_GeneratedCodeInfo_Annotation_Semantic = 'NONE' | 0 | 'SET' | 1 | 'ALIAS' | 2; +export type _google_protobuf_GeneratedCodeInfo_Annotation_Semantic__Output = typeof _google_protobuf_GeneratedCodeInfo_Annotation_Semantic[keyof typeof _google_protobuf_GeneratedCodeInfo_Annotation_Semantic]; +export interface GeneratedCodeInfo { + 'annotation'?: (_google_protobuf_GeneratedCodeInfo_Annotation)[]; +} +export interface GeneratedCodeInfo__Output { + 'annotation': (_google_protobuf_GeneratedCodeInfo_Annotation__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/GeneratedCodeInfo.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/GeneratedCodeInfo.js new file mode 100644 index 0000000..b63e564 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/GeneratedCodeInfo.js @@ -0,0 +1,11 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +exports._google_protobuf_GeneratedCodeInfo_Annotation_Semantic = void 0; +// Original file: null +exports._google_protobuf_GeneratedCodeInfo_Annotation_Semantic = { + NONE: 'NONE', + SET: 'SET', + ALIAS: 'ALIAS', +}; +//# sourceMappingURL=GeneratedCodeInfo.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/GeneratedCodeInfo.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/GeneratedCodeInfo.js.map new file mode 100644 index 0000000..c26b200 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/GeneratedCodeInfo.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GeneratedCodeInfo.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/GeneratedCodeInfo.ts"],"names":[],"mappings":";AAAA,sBAAsB;;;AAmBtB,sBAAsB;AAET,QAAA,sDAAsD,GAAG;IACpE,IAAI,EAAE,MAAM;IACZ,GAAG,EAAE,KAAK;IACV,KAAK,EAAE,OAAO;CACN,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.d.ts new file mode 100644 index 0000000..895fb9d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.d.ts @@ -0,0 +1,6 @@ +export interface Int32Value { + 'value'?: (number); +} +export interface Int32Value__Output { + 'value': (number); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.js new file mode 100644 index 0000000..dc46343 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Int32Value.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.js.map new file mode 100644 index 0000000..157e73a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Int32Value.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/Int32Value.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.d.ts new file mode 100644 index 0000000..00bd119 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.d.ts @@ -0,0 +1,7 @@ +import type { Long } from '@grpc/proto-loader'; +export interface Int64Value { + 'value'?: (number | string | Long); +} +export interface Int64Value__Output { + 'value': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.js new file mode 100644 index 0000000..a77bc96 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Int64Value.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.js.map new file mode 100644 index 0000000..b8894b1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Int64Value.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/Int64Value.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MessageOptions.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MessageOptions.d.ts new file mode 100644 index 0000000..3369f96 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MessageOptions.d.ts @@ -0,0 +1,28 @@ +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from '../../google/protobuf/FeatureSet'; +import type { UninterpretedOption as _google_protobuf_UninterpretedOption, UninterpretedOption__Output as _google_protobuf_UninterpretedOption__Output } from '../../google/protobuf/UninterpretedOption'; +export interface MessageOptions { + 'messageSetWireFormat'?: (boolean); + 'noStandardDescriptorAccessor'?: (boolean); + 'deprecated'?: (boolean); + 'mapEntry'?: (boolean); + /** + * @deprecated + */ + 'deprecatedLegacyJsonFieldConflicts'?: (boolean); + 'features'?: (_google_protobuf_FeatureSet | null); + 'uninterpretedOption'?: (_google_protobuf_UninterpretedOption)[]; + '.validate.disabled'?: (boolean); +} +export interface MessageOptions__Output { + 'messageSetWireFormat': (boolean); + 'noStandardDescriptorAccessor': (boolean); + 'deprecated': (boolean); + 'mapEntry': (boolean); + /** + * @deprecated + */ + 'deprecatedLegacyJsonFieldConflicts': (boolean); + 'features': (_google_protobuf_FeatureSet__Output | null); + 'uninterpretedOption': (_google_protobuf_UninterpretedOption__Output)[]; + '.validate.disabled': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MessageOptions.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MessageOptions.js new file mode 100644 index 0000000..aff6546 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MessageOptions.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=MessageOptions.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MessageOptions.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MessageOptions.js.map new file mode 100644 index 0000000..0f78196 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MessageOptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MessageOptions.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/MessageOptions.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodDescriptorProto.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodDescriptorProto.d.ts new file mode 100644 index 0000000..7b39b72 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodDescriptorProto.d.ts @@ -0,0 +1,17 @@ +import type { MethodOptions as _google_protobuf_MethodOptions, MethodOptions__Output as _google_protobuf_MethodOptions__Output } from '../../google/protobuf/MethodOptions'; +export interface MethodDescriptorProto { + 'name'?: (string); + 'inputType'?: (string); + 'outputType'?: (string); + 'options'?: (_google_protobuf_MethodOptions | null); + 'clientStreaming'?: (boolean); + 'serverStreaming'?: (boolean); +} +export interface MethodDescriptorProto__Output { + 'name': (string); + 'inputType': (string); + 'outputType': (string); + 'options': (_google_protobuf_MethodOptions__Output | null); + 'clientStreaming': (boolean); + 'serverStreaming': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodDescriptorProto.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodDescriptorProto.js new file mode 100644 index 0000000..939d4e2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodDescriptorProto.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=MethodDescriptorProto.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodDescriptorProto.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodDescriptorProto.js.map new file mode 100644 index 0000000..6b6f373 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodDescriptorProto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MethodDescriptorProto.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/MethodDescriptorProto.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodOptions.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodOptions.d.ts new file mode 100644 index 0000000..389f621 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodOptions.d.ts @@ -0,0 +1,21 @@ +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from '../../google/protobuf/FeatureSet'; +import type { UninterpretedOption as _google_protobuf_UninterpretedOption, UninterpretedOption__Output as _google_protobuf_UninterpretedOption__Output } from '../../google/protobuf/UninterpretedOption'; +export declare const _google_protobuf_MethodOptions_IdempotencyLevel: { + readonly IDEMPOTENCY_UNKNOWN: "IDEMPOTENCY_UNKNOWN"; + readonly NO_SIDE_EFFECTS: "NO_SIDE_EFFECTS"; + readonly IDEMPOTENT: "IDEMPOTENT"; +}; +export type _google_protobuf_MethodOptions_IdempotencyLevel = 'IDEMPOTENCY_UNKNOWN' | 0 | 'NO_SIDE_EFFECTS' | 1 | 'IDEMPOTENT' | 2; +export type _google_protobuf_MethodOptions_IdempotencyLevel__Output = typeof _google_protobuf_MethodOptions_IdempotencyLevel[keyof typeof _google_protobuf_MethodOptions_IdempotencyLevel]; +export interface MethodOptions { + 'deprecated'?: (boolean); + 'idempotencyLevel'?: (_google_protobuf_MethodOptions_IdempotencyLevel); + 'features'?: (_google_protobuf_FeatureSet | null); + 'uninterpretedOption'?: (_google_protobuf_UninterpretedOption)[]; +} +export interface MethodOptions__Output { + 'deprecated': (boolean); + 'idempotencyLevel': (_google_protobuf_MethodOptions_IdempotencyLevel__Output); + 'features': (_google_protobuf_FeatureSet__Output | null); + 'uninterpretedOption': (_google_protobuf_UninterpretedOption__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodOptions.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodOptions.js new file mode 100644 index 0000000..c82ee01 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodOptions.js @@ -0,0 +1,11 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +exports._google_protobuf_MethodOptions_IdempotencyLevel = void 0; +// Original file: null +exports._google_protobuf_MethodOptions_IdempotencyLevel = { + IDEMPOTENCY_UNKNOWN: 'IDEMPOTENCY_UNKNOWN', + NO_SIDE_EFFECTS: 'NO_SIDE_EFFECTS', + IDEMPOTENT: 'IDEMPOTENT', +}; +//# sourceMappingURL=MethodOptions.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodOptions.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodOptions.js.map new file mode 100644 index 0000000..4c2d1a3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/MethodOptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MethodOptions.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/MethodOptions.ts"],"names":[],"mappings":";AAAA,sBAAsB;;;AAKtB,sBAAsB;AAET,QAAA,+CAA+C,GAAG;IAC7D,mBAAmB,EAAE,qBAAqB;IAC1C,eAAe,EAAE,iBAAiB;IAClC,UAAU,EAAE,YAAY;CAChB,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofDescriptorProto.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofDescriptorProto.d.ts new file mode 100644 index 0000000..4dc1e13 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofDescriptorProto.d.ts @@ -0,0 +1,9 @@ +import type { OneofOptions as _google_protobuf_OneofOptions, OneofOptions__Output as _google_protobuf_OneofOptions__Output } from '../../google/protobuf/OneofOptions'; +export interface OneofDescriptorProto { + 'name'?: (string); + 'options'?: (_google_protobuf_OneofOptions | null); +} +export interface OneofDescriptorProto__Output { + 'name': (string); + 'options': (_google_protobuf_OneofOptions__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofDescriptorProto.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofDescriptorProto.js new file mode 100644 index 0000000..80102f4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofDescriptorProto.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=OneofDescriptorProto.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofDescriptorProto.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofDescriptorProto.js.map new file mode 100644 index 0000000..b6d3568 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofDescriptorProto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"OneofDescriptorProto.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/OneofDescriptorProto.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofOptions.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofOptions.d.ts new file mode 100644 index 0000000..072d3e2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofOptions.d.ts @@ -0,0 +1,12 @@ +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from '../../google/protobuf/FeatureSet'; +import type { UninterpretedOption as _google_protobuf_UninterpretedOption, UninterpretedOption__Output as _google_protobuf_UninterpretedOption__Output } from '../../google/protobuf/UninterpretedOption'; +export interface OneofOptions { + 'features'?: (_google_protobuf_FeatureSet | null); + 'uninterpretedOption'?: (_google_protobuf_UninterpretedOption)[]; + '.validate.required'?: (boolean); +} +export interface OneofOptions__Output { + 'features': (_google_protobuf_FeatureSet__Output | null); + 'uninterpretedOption': (_google_protobuf_UninterpretedOption__Output)[]; + '.validate.required': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofOptions.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofOptions.js new file mode 100644 index 0000000..5060198 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofOptions.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=OneofOptions.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofOptions.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofOptions.js.map new file mode 100644 index 0000000..207e815 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/OneofOptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"OneofOptions.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/OneofOptions.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceDescriptorProto.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceDescriptorProto.d.ts new file mode 100644 index 0000000..96b5517 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceDescriptorProto.d.ts @@ -0,0 +1,12 @@ +import type { MethodDescriptorProto as _google_protobuf_MethodDescriptorProto, MethodDescriptorProto__Output as _google_protobuf_MethodDescriptorProto__Output } from '../../google/protobuf/MethodDescriptorProto'; +import type { ServiceOptions as _google_protobuf_ServiceOptions, ServiceOptions__Output as _google_protobuf_ServiceOptions__Output } from '../../google/protobuf/ServiceOptions'; +export interface ServiceDescriptorProto { + 'name'?: (string); + 'method'?: (_google_protobuf_MethodDescriptorProto)[]; + 'options'?: (_google_protobuf_ServiceOptions | null); +} +export interface ServiceDescriptorProto__Output { + 'name': (string); + 'method': (_google_protobuf_MethodDescriptorProto__Output)[]; + 'options': (_google_protobuf_ServiceOptions__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceDescriptorProto.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceDescriptorProto.js new file mode 100644 index 0000000..727eeb4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceDescriptorProto.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=ServiceDescriptorProto.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceDescriptorProto.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceDescriptorProto.js.map new file mode 100644 index 0000000..92e01ad --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceDescriptorProto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ServiceDescriptorProto.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/ServiceDescriptorProto.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceOptions.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceOptions.d.ts new file mode 100644 index 0000000..cf0d0ad --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceOptions.d.ts @@ -0,0 +1,12 @@ +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from '../../google/protobuf/FeatureSet'; +import type { UninterpretedOption as _google_protobuf_UninterpretedOption, UninterpretedOption__Output as _google_protobuf_UninterpretedOption__Output } from '../../google/protobuf/UninterpretedOption'; +export interface ServiceOptions { + 'deprecated'?: (boolean); + 'features'?: (_google_protobuf_FeatureSet | null); + 'uninterpretedOption'?: (_google_protobuf_UninterpretedOption)[]; +} +export interface ServiceOptions__Output { + 'deprecated': (boolean); + 'features': (_google_protobuf_FeatureSet__Output | null); + 'uninterpretedOption': (_google_protobuf_UninterpretedOption__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceOptions.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceOptions.js new file mode 100644 index 0000000..f8ad6b7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceOptions.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=ServiceOptions.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceOptions.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceOptions.js.map new file mode 100644 index 0000000..10443df --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/ServiceOptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ServiceOptions.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/ServiceOptions.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SourceCodeInfo.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SourceCodeInfo.d.ts new file mode 100644 index 0000000..165dbfa --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SourceCodeInfo.d.ts @@ -0,0 +1,20 @@ +export interface _google_protobuf_SourceCodeInfo_Location { + 'path'?: (number)[]; + 'span'?: (number)[]; + 'leadingComments'?: (string); + 'trailingComments'?: (string); + 'leadingDetachedComments'?: (string)[]; +} +export interface _google_protobuf_SourceCodeInfo_Location__Output { + 'path': (number)[]; + 'span': (number)[]; + 'leadingComments': (string); + 'trailingComments': (string); + 'leadingDetachedComments': (string)[]; +} +export interface SourceCodeInfo { + 'location'?: (_google_protobuf_SourceCodeInfo_Location)[]; +} +export interface SourceCodeInfo__Output { + 'location': (_google_protobuf_SourceCodeInfo_Location__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SourceCodeInfo.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SourceCodeInfo.js new file mode 100644 index 0000000..065992b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SourceCodeInfo.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SourceCodeInfo.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SourceCodeInfo.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SourceCodeInfo.js.map new file mode 100644 index 0000000..13b7406 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SourceCodeInfo.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SourceCodeInfo.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/SourceCodeInfo.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.d.ts new file mode 100644 index 0000000..74230c9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.d.ts @@ -0,0 +1,6 @@ +export interface StringValue { + 'value'?: (string); +} +export interface StringValue__Output { + 'value': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.js new file mode 100644 index 0000000..0836e97 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=StringValue.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.js.map new file mode 100644 index 0000000..bc05ddc --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.js.map @@ -0,0 +1 @@ +{"version":3,"file":"StringValue.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/StringValue.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SymbolVisibility.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SymbolVisibility.d.ts new file mode 100644 index 0000000..7327d0a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SymbolVisibility.d.ts @@ -0,0 +1,7 @@ +export declare const SymbolVisibility: { + readonly VISIBILITY_UNSET: "VISIBILITY_UNSET"; + readonly VISIBILITY_LOCAL: "VISIBILITY_LOCAL"; + readonly VISIBILITY_EXPORT: "VISIBILITY_EXPORT"; +}; +export type SymbolVisibility = 'VISIBILITY_UNSET' | 0 | 'VISIBILITY_LOCAL' | 1 | 'VISIBILITY_EXPORT' | 2; +export type SymbolVisibility__Output = typeof SymbolVisibility[keyof typeof SymbolVisibility]; diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SymbolVisibility.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SymbolVisibility.js new file mode 100644 index 0000000..4119671 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SymbolVisibility.js @@ -0,0 +1,10 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SymbolVisibility = void 0; +exports.SymbolVisibility = { + VISIBILITY_UNSET: 'VISIBILITY_UNSET', + VISIBILITY_LOCAL: 'VISIBILITY_LOCAL', + VISIBILITY_EXPORT: 'VISIBILITY_EXPORT', +}; +//# sourceMappingURL=SymbolVisibility.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SymbolVisibility.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SymbolVisibility.js.map new file mode 100644 index 0000000..f69c165 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/SymbolVisibility.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SymbolVisibility.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/SymbolVisibility.ts"],"names":[],"mappings":";AAAA,sBAAsB;;;AAET,QAAA,gBAAgB,GAAG;IAC9B,gBAAgB,EAAE,kBAAkB;IACpC,gBAAgB,EAAE,kBAAkB;IACpC,iBAAiB,EAAE,mBAAmB;CAC9B,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.d.ts new file mode 100644 index 0000000..900ff5a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.d.ts @@ -0,0 +1,9 @@ +import type { Long } from '@grpc/proto-loader'; +export interface Timestamp { + 'seconds'?: (number | string | Long); + 'nanos'?: (number); +} +export interface Timestamp__Output { + 'seconds': (string); + 'nanos': (number); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.js new file mode 100644 index 0000000..dcca213 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Timestamp.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.js.map new file mode 100644 index 0000000..e90342e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Timestamp.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/Timestamp.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.d.ts new file mode 100644 index 0000000..d7e185f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.d.ts @@ -0,0 +1,6 @@ +export interface UInt32Value { + 'value'?: (number); +} +export interface UInt32Value__Output { + 'value': (number); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.js new file mode 100644 index 0000000..889cd2e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=UInt32Value.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.js.map new file mode 100644 index 0000000..2a0420f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.js.map @@ -0,0 +1 @@ +{"version":3,"file":"UInt32Value.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/UInt32Value.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.d.ts new file mode 100644 index 0000000..fe94d29 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.d.ts @@ -0,0 +1,7 @@ +import type { Long } from '@grpc/proto-loader'; +export interface UInt64Value { + 'value'?: (number | string | Long); +} +export interface UInt64Value__Output { + 'value': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.js new file mode 100644 index 0000000..2a06a69 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=UInt64Value.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.js.map new file mode 100644 index 0000000..4ea43ca --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.js.map @@ -0,0 +1 @@ +{"version":3,"file":"UInt64Value.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/UInt64Value.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UninterpretedOption.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UninterpretedOption.d.ts new file mode 100644 index 0000000..9bc5adc --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UninterpretedOption.d.ts @@ -0,0 +1,27 @@ +import type { Long } from '@grpc/proto-loader'; +export interface _google_protobuf_UninterpretedOption_NamePart { + 'namePart'?: (string); + 'isExtension'?: (boolean); +} +export interface _google_protobuf_UninterpretedOption_NamePart__Output { + 'namePart': (string); + 'isExtension': (boolean); +} +export interface UninterpretedOption { + 'name'?: (_google_protobuf_UninterpretedOption_NamePart)[]; + 'identifierValue'?: (string); + 'positiveIntValue'?: (number | string | Long); + 'negativeIntValue'?: (number | string | Long); + 'doubleValue'?: (number | string); + 'stringValue'?: (Buffer | Uint8Array | string); + 'aggregateValue'?: (string); +} +export interface UninterpretedOption__Output { + 'name': (_google_protobuf_UninterpretedOption_NamePart__Output)[]; + 'identifierValue': (string); + 'positiveIntValue': (string); + 'negativeIntValue': (string); + 'doubleValue': (number); + 'stringValue': (Buffer); + 'aggregateValue': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UninterpretedOption.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UninterpretedOption.js new file mode 100644 index 0000000..b3ebb69 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UninterpretedOption.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=UninterpretedOption.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UninterpretedOption.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UninterpretedOption.js.map new file mode 100644 index 0000000..607583a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UninterpretedOption.js.map @@ -0,0 +1 @@ +{"version":3,"file":"UninterpretedOption.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/UninterpretedOption.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.d.ts new file mode 100644 index 0000000..dbf0fa8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.d.ts @@ -0,0 +1,79 @@ +import type { Any as _google_protobuf_Any, Any__Output as _google_protobuf_Any__Output } from '../../../google/protobuf/Any'; +/** + * An address type not included above. + */ +export interface _grpc_channelz_v1_Address_OtherAddress { + /** + * The human readable version of the value. This value should be set. + */ + 'name'?: (string); + /** + * The actual address message. + */ + 'value'?: (_google_protobuf_Any | null); +} +/** + * An address type not included above. + */ +export interface _grpc_channelz_v1_Address_OtherAddress__Output { + /** + * The human readable version of the value. This value should be set. + */ + 'name': (string); + /** + * The actual address message. + */ + 'value': (_google_protobuf_Any__Output | null); +} +export interface _grpc_channelz_v1_Address_TcpIpAddress { + /** + * Either the IPv4 or IPv6 address in bytes. Will be either 4 bytes or 16 + * bytes in length. + */ + 'ip_address'?: (Buffer | Uint8Array | string); + /** + * 0-64k, or -1 if not appropriate. + */ + 'port'?: (number); +} +export interface _grpc_channelz_v1_Address_TcpIpAddress__Output { + /** + * Either the IPv4 or IPv6 address in bytes. Will be either 4 bytes or 16 + * bytes in length. + */ + 'ip_address': (Buffer); + /** + * 0-64k, or -1 if not appropriate. + */ + 'port': (number); +} +/** + * A Unix Domain Socket address. + */ +export interface _grpc_channelz_v1_Address_UdsAddress { + 'filename'?: (string); +} +/** + * A Unix Domain Socket address. + */ +export interface _grpc_channelz_v1_Address_UdsAddress__Output { + 'filename': (string); +} +/** + * Address represents the address used to create the socket. + */ +export interface Address { + 'tcpip_address'?: (_grpc_channelz_v1_Address_TcpIpAddress | null); + 'uds_address'?: (_grpc_channelz_v1_Address_UdsAddress | null); + 'other_address'?: (_grpc_channelz_v1_Address_OtherAddress | null); + 'address'?: "tcpip_address" | "uds_address" | "other_address"; +} +/** + * Address represents the address used to create the socket. + */ +export interface Address__Output { + 'tcpip_address'?: (_grpc_channelz_v1_Address_TcpIpAddress__Output | null); + 'uds_address'?: (_grpc_channelz_v1_Address_UdsAddress__Output | null); + 'other_address'?: (_grpc_channelz_v1_Address_OtherAddress__Output | null); + 'address'?: "tcpip_address" | "uds_address" | "other_address"; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.js new file mode 100644 index 0000000..6f15b91 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Address.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.js.map new file mode 100644 index 0000000..554d6da --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Address.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/Address.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.d.ts new file mode 100644 index 0000000..3bd11ca --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.d.ts @@ -0,0 +1,64 @@ +import type { ChannelRef as _grpc_channelz_v1_ChannelRef, ChannelRef__Output as _grpc_channelz_v1_ChannelRef__Output } from '../../../grpc/channelz/v1/ChannelRef'; +import type { ChannelData as _grpc_channelz_v1_ChannelData, ChannelData__Output as _grpc_channelz_v1_ChannelData__Output } from '../../../grpc/channelz/v1/ChannelData'; +import type { SubchannelRef as _grpc_channelz_v1_SubchannelRef, SubchannelRef__Output as _grpc_channelz_v1_SubchannelRef__Output } from '../../../grpc/channelz/v1/SubchannelRef'; +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from '../../../grpc/channelz/v1/SocketRef'; +/** + * Channel is a logical grouping of channels, subchannels, and sockets. + */ +export interface Channel { + /** + * The identifier for this channel. This should bet set. + */ + 'ref'?: (_grpc_channelz_v1_ChannelRef | null); + /** + * Data specific to this channel. + */ + 'data'?: (_grpc_channelz_v1_ChannelData | null); + /** + * There are no ordering guarantees on the order of channel refs. + * There may not be cycles in the ref graph. + * A channel ref may be present in more than one channel or subchannel. + */ + 'channel_ref'?: (_grpc_channelz_v1_ChannelRef)[]; + /** + * At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + * There are no ordering guarantees on the order of subchannel refs. + * There may not be cycles in the ref graph. + * A sub channel ref may be present in more than one channel or subchannel. + */ + 'subchannel_ref'?: (_grpc_channelz_v1_SubchannelRef)[]; + /** + * There are no ordering guarantees on the order of sockets. + */ + 'socket_ref'?: (_grpc_channelz_v1_SocketRef)[]; +} +/** + * Channel is a logical grouping of channels, subchannels, and sockets. + */ +export interface Channel__Output { + /** + * The identifier for this channel. This should bet set. + */ + 'ref': (_grpc_channelz_v1_ChannelRef__Output | null); + /** + * Data specific to this channel. + */ + 'data': (_grpc_channelz_v1_ChannelData__Output | null); + /** + * There are no ordering guarantees on the order of channel refs. + * There may not be cycles in the ref graph. + * A channel ref may be present in more than one channel or subchannel. + */ + 'channel_ref': (_grpc_channelz_v1_ChannelRef__Output)[]; + /** + * At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + * There are no ordering guarantees on the order of subchannel refs. + * There may not be cycles in the ref graph. + * A sub channel ref may be present in more than one channel or subchannel. + */ + 'subchannel_ref': (_grpc_channelz_v1_SubchannelRef__Output)[]; + /** + * There are no ordering guarantees on the order of sockets. + */ + 'socket_ref': (_grpc_channelz_v1_SocketRef__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.js new file mode 100644 index 0000000..d9bc55a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Channel.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.js.map new file mode 100644 index 0000000..5dd6b69 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Channel.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/Channel.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.d.ts new file mode 100644 index 0000000..2ea3833 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.d.ts @@ -0,0 +1,24 @@ +export declare const _grpc_channelz_v1_ChannelConnectivityState_State: { + readonly UNKNOWN: "UNKNOWN"; + readonly IDLE: "IDLE"; + readonly CONNECTING: "CONNECTING"; + readonly READY: "READY"; + readonly TRANSIENT_FAILURE: "TRANSIENT_FAILURE"; + readonly SHUTDOWN: "SHUTDOWN"; +}; +export type _grpc_channelz_v1_ChannelConnectivityState_State = 'UNKNOWN' | 0 | 'IDLE' | 1 | 'CONNECTING' | 2 | 'READY' | 3 | 'TRANSIENT_FAILURE' | 4 | 'SHUTDOWN' | 5; +export type _grpc_channelz_v1_ChannelConnectivityState_State__Output = typeof _grpc_channelz_v1_ChannelConnectivityState_State[keyof typeof _grpc_channelz_v1_ChannelConnectivityState_State]; +/** + * These come from the specified states in this document: + * https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md + */ +export interface ChannelConnectivityState { + 'state'?: (_grpc_channelz_v1_ChannelConnectivityState_State); +} +/** + * These come from the specified states in this document: + * https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md + */ +export interface ChannelConnectivityState__Output { + 'state': (_grpc_channelz_v1_ChannelConnectivityState_State__Output); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.js new file mode 100644 index 0000000..2a783d9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.js @@ -0,0 +1,14 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +exports._grpc_channelz_v1_ChannelConnectivityState_State = void 0; +// Original file: proto/channelz.proto +exports._grpc_channelz_v1_ChannelConnectivityState_State = { + UNKNOWN: 'UNKNOWN', + IDLE: 'IDLE', + CONNECTING: 'CONNECTING', + READY: 'READY', + TRANSIENT_FAILURE: 'TRANSIENT_FAILURE', + SHUTDOWN: 'SHUTDOWN', +}; +//# sourceMappingURL=ChannelConnectivityState.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.js.map new file mode 100644 index 0000000..d4b2567 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ChannelConnectivityState.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/ChannelConnectivityState.ts"],"names":[],"mappings":";AAAA,sCAAsC;;;AAGtC,sCAAsC;AAEzB,QAAA,gDAAgD,GAAG;IAC9D,OAAO,EAAE,SAAS;IAClB,IAAI,EAAE,MAAM;IACZ,UAAU,EAAE,YAAY;IACxB,KAAK,EAAE,OAAO;IACd,iBAAiB,EAAE,mBAAmB;IACtC,QAAQ,EAAE,UAAU;CACZ,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.d.ts new file mode 100644 index 0000000..3d9716a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.d.ts @@ -0,0 +1,72 @@ +import type { ChannelConnectivityState as _grpc_channelz_v1_ChannelConnectivityState, ChannelConnectivityState__Output as _grpc_channelz_v1_ChannelConnectivityState__Output } from '../../../grpc/channelz/v1/ChannelConnectivityState'; +import type { ChannelTrace as _grpc_channelz_v1_ChannelTrace, ChannelTrace__Output as _grpc_channelz_v1_ChannelTrace__Output } from '../../../grpc/channelz/v1/ChannelTrace'; +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../../../google/protobuf/Timestamp'; +import type { Long } from '@grpc/proto-loader'; +/** + * Channel data is data related to a specific Channel or Subchannel. + */ +export interface ChannelData { + /** + * The connectivity state of the channel or subchannel. Implementations + * should always set this. + */ + 'state'?: (_grpc_channelz_v1_ChannelConnectivityState | null); + /** + * The target this channel originally tried to connect to. May be absent + */ + 'target'?: (string); + /** + * A trace of recent events on the channel. May be absent. + */ + 'trace'?: (_grpc_channelz_v1_ChannelTrace | null); + /** + * The number of calls started on the channel + */ + 'calls_started'?: (number | string | Long); + /** + * The number of calls that have completed with an OK status + */ + 'calls_succeeded'?: (number | string | Long); + /** + * The number of calls that have completed with a non-OK status + */ + 'calls_failed'?: (number | string | Long); + /** + * The last time a call was started on the channel. + */ + 'last_call_started_timestamp'?: (_google_protobuf_Timestamp | null); +} +/** + * Channel data is data related to a specific Channel or Subchannel. + */ +export interface ChannelData__Output { + /** + * The connectivity state of the channel or subchannel. Implementations + * should always set this. + */ + 'state': (_grpc_channelz_v1_ChannelConnectivityState__Output | null); + /** + * The target this channel originally tried to connect to. May be absent + */ + 'target': (string); + /** + * A trace of recent events on the channel. May be absent. + */ + 'trace': (_grpc_channelz_v1_ChannelTrace__Output | null); + /** + * The number of calls started on the channel + */ + 'calls_started': (string); + /** + * The number of calls that have completed with an OK status + */ + 'calls_succeeded': (string); + /** + * The number of calls that have completed with a non-OK status + */ + 'calls_failed': (string); + /** + * The last time a call was started on the channel. + */ + 'last_call_started_timestamp': (_google_protobuf_Timestamp__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.js new file mode 100644 index 0000000..dffbd45 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=ChannelData.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.js.map new file mode 100644 index 0000000..bb2b4c4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ChannelData.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/ChannelData.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.d.ts new file mode 100644 index 0000000..29deef9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.d.ts @@ -0,0 +1,27 @@ +import type { Long } from '@grpc/proto-loader'; +/** + * ChannelRef is a reference to a Channel. + */ +export interface ChannelRef { + /** + * The globally unique id for this channel. Must be a positive number. + */ + 'channel_id'?: (number | string | Long); + /** + * An optional name associated with the channel. + */ + 'name'?: (string); +} +/** + * ChannelRef is a reference to a Channel. + */ +export interface ChannelRef__Output { + /** + * The globally unique id for this channel. Must be a positive number. + */ + 'channel_id': (string); + /** + * An optional name associated with the channel. + */ + 'name': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.js new file mode 100644 index 0000000..d239819 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=ChannelRef.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.js.map new file mode 100644 index 0000000..1030ded --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ChannelRef.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/ChannelRef.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.d.ts new file mode 100644 index 0000000..5b6170a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.d.ts @@ -0,0 +1,41 @@ +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../../../google/protobuf/Timestamp'; +import type { ChannelTraceEvent as _grpc_channelz_v1_ChannelTraceEvent, ChannelTraceEvent__Output as _grpc_channelz_v1_ChannelTraceEvent__Output } from '../../../grpc/channelz/v1/ChannelTraceEvent'; +import type { Long } from '@grpc/proto-loader'; +/** + * ChannelTrace represents the recent events that have occurred on the channel. + */ +export interface ChannelTrace { + /** + * Number of events ever logged in this tracing object. This can differ from + * events.size() because events can be overwritten or garbage collected by + * implementations. + */ + 'num_events_logged'?: (number | string | Long); + /** + * Time that this channel was created. + */ + 'creation_timestamp'?: (_google_protobuf_Timestamp | null); + /** + * List of events that have occurred on this channel. + */ + 'events'?: (_grpc_channelz_v1_ChannelTraceEvent)[]; +} +/** + * ChannelTrace represents the recent events that have occurred on the channel. + */ +export interface ChannelTrace__Output { + /** + * Number of events ever logged in this tracing object. This can differ from + * events.size() because events can be overwritten or garbage collected by + * implementations. + */ + 'num_events_logged': (string); + /** + * Time that this channel was created. + */ + 'creation_timestamp': (_google_protobuf_Timestamp__Output | null); + /** + * List of events that have occurred on this channel. + */ + 'events': (_grpc_channelz_v1_ChannelTraceEvent__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.js new file mode 100644 index 0000000..112069c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=ChannelTrace.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.js.map new file mode 100644 index 0000000..2f665dc --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ChannelTrace.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/ChannelTrace.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.d.ts new file mode 100644 index 0000000..7cb594d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.d.ts @@ -0,0 +1,74 @@ +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../../../google/protobuf/Timestamp'; +import type { ChannelRef as _grpc_channelz_v1_ChannelRef, ChannelRef__Output as _grpc_channelz_v1_ChannelRef__Output } from '../../../grpc/channelz/v1/ChannelRef'; +import type { SubchannelRef as _grpc_channelz_v1_SubchannelRef, SubchannelRef__Output as _grpc_channelz_v1_SubchannelRef__Output } from '../../../grpc/channelz/v1/SubchannelRef'; +/** + * The supported severity levels of trace events. + */ +export declare const _grpc_channelz_v1_ChannelTraceEvent_Severity: { + readonly CT_UNKNOWN: "CT_UNKNOWN"; + readonly CT_INFO: "CT_INFO"; + readonly CT_WARNING: "CT_WARNING"; + readonly CT_ERROR: "CT_ERROR"; +}; +/** + * The supported severity levels of trace events. + */ +export type _grpc_channelz_v1_ChannelTraceEvent_Severity = 'CT_UNKNOWN' | 0 | 'CT_INFO' | 1 | 'CT_WARNING' | 2 | 'CT_ERROR' | 3; +/** + * The supported severity levels of trace events. + */ +export type _grpc_channelz_v1_ChannelTraceEvent_Severity__Output = typeof _grpc_channelz_v1_ChannelTraceEvent_Severity[keyof typeof _grpc_channelz_v1_ChannelTraceEvent_Severity]; +/** + * A trace event is an interesting thing that happened to a channel or + * subchannel, such as creation, address resolution, subchannel creation, etc. + */ +export interface ChannelTraceEvent { + /** + * High level description of the event. + */ + 'description'?: (string); + /** + * the severity of the trace event + */ + 'severity'?: (_grpc_channelz_v1_ChannelTraceEvent_Severity); + /** + * When this event occurred. + */ + 'timestamp'?: (_google_protobuf_Timestamp | null); + 'channel_ref'?: (_grpc_channelz_v1_ChannelRef | null); + 'subchannel_ref'?: (_grpc_channelz_v1_SubchannelRef | null); + /** + * ref of referenced channel or subchannel. + * Optional, only present if this event refers to a child object. For example, + * this field would be filled if this trace event was for a subchannel being + * created. + */ + 'child_ref'?: "channel_ref" | "subchannel_ref"; +} +/** + * A trace event is an interesting thing that happened to a channel or + * subchannel, such as creation, address resolution, subchannel creation, etc. + */ +export interface ChannelTraceEvent__Output { + /** + * High level description of the event. + */ + 'description': (string); + /** + * the severity of the trace event + */ + 'severity': (_grpc_channelz_v1_ChannelTraceEvent_Severity__Output); + /** + * When this event occurred. + */ + 'timestamp': (_google_protobuf_Timestamp__Output | null); + 'channel_ref'?: (_grpc_channelz_v1_ChannelRef__Output | null); + 'subchannel_ref'?: (_grpc_channelz_v1_SubchannelRef__Output | null); + /** + * ref of referenced channel or subchannel. + * Optional, only present if this event refers to a child object. For example, + * this field would be filled if this trace event was for a subchannel being + * created. + */ + 'child_ref'?: "channel_ref" | "subchannel_ref"; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.js new file mode 100644 index 0000000..ae9981b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.js @@ -0,0 +1,15 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +exports._grpc_channelz_v1_ChannelTraceEvent_Severity = void 0; +// Original file: proto/channelz.proto +/** + * The supported severity levels of trace events. + */ +exports._grpc_channelz_v1_ChannelTraceEvent_Severity = { + CT_UNKNOWN: 'CT_UNKNOWN', + CT_INFO: 'CT_INFO', + CT_WARNING: 'CT_WARNING', + CT_ERROR: 'CT_ERROR', +}; +//# sourceMappingURL=ChannelTraceEvent.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.js.map new file mode 100644 index 0000000..2ed003c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ChannelTraceEvent.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/ChannelTraceEvent.ts"],"names":[],"mappings":";AAAA,sCAAsC;;;AAMtC,sCAAsC;AAEtC;;GAEG;AACU,QAAA,4CAA4C,GAAG;IAC1D,UAAU,EAAE,YAAY;IACxB,OAAO,EAAE,SAAS;IAClB,UAAU,EAAE,YAAY;IACxB,QAAQ,EAAE,UAAU;CACZ,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.d.ts new file mode 100644 index 0000000..3e9eb98 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.d.ts @@ -0,0 +1,159 @@ +import type * as grpc from '../../../../index'; +import type { MethodDefinition } from '@grpc/proto-loader'; +import type { GetChannelRequest as _grpc_channelz_v1_GetChannelRequest, GetChannelRequest__Output as _grpc_channelz_v1_GetChannelRequest__Output } from '../../../grpc/channelz/v1/GetChannelRequest'; +import type { GetChannelResponse as _grpc_channelz_v1_GetChannelResponse, GetChannelResponse__Output as _grpc_channelz_v1_GetChannelResponse__Output } from '../../../grpc/channelz/v1/GetChannelResponse'; +import type { GetServerRequest as _grpc_channelz_v1_GetServerRequest, GetServerRequest__Output as _grpc_channelz_v1_GetServerRequest__Output } from '../../../grpc/channelz/v1/GetServerRequest'; +import type { GetServerResponse as _grpc_channelz_v1_GetServerResponse, GetServerResponse__Output as _grpc_channelz_v1_GetServerResponse__Output } from '../../../grpc/channelz/v1/GetServerResponse'; +import type { GetServerSocketsRequest as _grpc_channelz_v1_GetServerSocketsRequest, GetServerSocketsRequest__Output as _grpc_channelz_v1_GetServerSocketsRequest__Output } from '../../../grpc/channelz/v1/GetServerSocketsRequest'; +import type { GetServerSocketsResponse as _grpc_channelz_v1_GetServerSocketsResponse, GetServerSocketsResponse__Output as _grpc_channelz_v1_GetServerSocketsResponse__Output } from '../../../grpc/channelz/v1/GetServerSocketsResponse'; +import type { GetServersRequest as _grpc_channelz_v1_GetServersRequest, GetServersRequest__Output as _grpc_channelz_v1_GetServersRequest__Output } from '../../../grpc/channelz/v1/GetServersRequest'; +import type { GetServersResponse as _grpc_channelz_v1_GetServersResponse, GetServersResponse__Output as _grpc_channelz_v1_GetServersResponse__Output } from '../../../grpc/channelz/v1/GetServersResponse'; +import type { GetSocketRequest as _grpc_channelz_v1_GetSocketRequest, GetSocketRequest__Output as _grpc_channelz_v1_GetSocketRequest__Output } from '../../../grpc/channelz/v1/GetSocketRequest'; +import type { GetSocketResponse as _grpc_channelz_v1_GetSocketResponse, GetSocketResponse__Output as _grpc_channelz_v1_GetSocketResponse__Output } from '../../../grpc/channelz/v1/GetSocketResponse'; +import type { GetSubchannelRequest as _grpc_channelz_v1_GetSubchannelRequest, GetSubchannelRequest__Output as _grpc_channelz_v1_GetSubchannelRequest__Output } from '../../../grpc/channelz/v1/GetSubchannelRequest'; +import type { GetSubchannelResponse as _grpc_channelz_v1_GetSubchannelResponse, GetSubchannelResponse__Output as _grpc_channelz_v1_GetSubchannelResponse__Output } from '../../../grpc/channelz/v1/GetSubchannelResponse'; +import type { GetTopChannelsRequest as _grpc_channelz_v1_GetTopChannelsRequest, GetTopChannelsRequest__Output as _grpc_channelz_v1_GetTopChannelsRequest__Output } from '../../../grpc/channelz/v1/GetTopChannelsRequest'; +import type { GetTopChannelsResponse as _grpc_channelz_v1_GetTopChannelsResponse, GetTopChannelsResponse__Output as _grpc_channelz_v1_GetTopChannelsResponse__Output } from '../../../grpc/channelz/v1/GetTopChannelsResponse'; +/** + * Channelz is a service exposed by gRPC servers that provides detailed debug + * information. + */ +export interface ChannelzClient extends grpc.Client { + /** + * Returns a single Channel, or else a NOT_FOUND code. + */ + GetChannel(argument: _grpc_channelz_v1_GetChannelRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetChannelResponse__Output>): grpc.ClientUnaryCall; + GetChannel(argument: _grpc_channelz_v1_GetChannelRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetChannelResponse__Output>): grpc.ClientUnaryCall; + GetChannel(argument: _grpc_channelz_v1_GetChannelRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetChannelResponse__Output>): grpc.ClientUnaryCall; + GetChannel(argument: _grpc_channelz_v1_GetChannelRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetChannelResponse__Output>): grpc.ClientUnaryCall; + /** + * Returns a single Server, or else a NOT_FOUND code. + */ + GetServer(argument: _grpc_channelz_v1_GetServerRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + GetServer(argument: _grpc_channelz_v1_GetServerRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + GetServer(argument: _grpc_channelz_v1_GetServerRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + GetServer(argument: _grpc_channelz_v1_GetServerRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + /** + * Returns a single Server, or else a NOT_FOUND code. + */ + getServer(argument: _grpc_channelz_v1_GetServerRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + getServer(argument: _grpc_channelz_v1_GetServerRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + getServer(argument: _grpc_channelz_v1_GetServerRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + getServer(argument: _grpc_channelz_v1_GetServerRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + /** + * Gets all server sockets that exist in the process. + */ + GetServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + GetServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + GetServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + GetServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + /** + * Gets all server sockets that exist in the process. + */ + getServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + getServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + getServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + getServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + /** + * Gets all servers that exist in the process. + */ + GetServers(argument: _grpc_channelz_v1_GetServersRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + GetServers(argument: _grpc_channelz_v1_GetServersRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + GetServers(argument: _grpc_channelz_v1_GetServersRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + GetServers(argument: _grpc_channelz_v1_GetServersRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + /** + * Gets all servers that exist in the process. + */ + getServers(argument: _grpc_channelz_v1_GetServersRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + getServers(argument: _grpc_channelz_v1_GetServersRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + getServers(argument: _grpc_channelz_v1_GetServersRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + getServers(argument: _grpc_channelz_v1_GetServersRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + /** + * Returns a single Socket or else a NOT_FOUND code. + */ + GetSocket(argument: _grpc_channelz_v1_GetSocketRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + GetSocket(argument: _grpc_channelz_v1_GetSocketRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + GetSocket(argument: _grpc_channelz_v1_GetSocketRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + GetSocket(argument: _grpc_channelz_v1_GetSocketRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + /** + * Returns a single Socket or else a NOT_FOUND code. + */ + getSocket(argument: _grpc_channelz_v1_GetSocketRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + getSocket(argument: _grpc_channelz_v1_GetSocketRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + getSocket(argument: _grpc_channelz_v1_GetSocketRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + getSocket(argument: _grpc_channelz_v1_GetSocketRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + /** + * Returns a single Subchannel, or else a NOT_FOUND code. + */ + GetSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + GetSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + GetSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + GetSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + /** + * Returns a single Subchannel, or else a NOT_FOUND code. + */ + getSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + getSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + getSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + getSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + /** + * Gets all root channels (i.e. channels the application has directly + * created). This does not include subchannels nor non-top level channels. + */ + GetTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + GetTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + GetTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + GetTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + /** + * Gets all root channels (i.e. channels the application has directly + * created). This does not include subchannels nor non-top level channels. + */ + getTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + getTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + getTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + getTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; +} +/** + * Channelz is a service exposed by gRPC servers that provides detailed debug + * information. + */ +export interface ChannelzHandlers extends grpc.UntypedServiceImplementation { + /** + * Returns a single Channel, or else a NOT_FOUND code. + */ + GetChannel: grpc.handleUnaryCall<_grpc_channelz_v1_GetChannelRequest__Output, _grpc_channelz_v1_GetChannelResponse>; + /** + * Returns a single Server, or else a NOT_FOUND code. + */ + GetServer: grpc.handleUnaryCall<_grpc_channelz_v1_GetServerRequest__Output, _grpc_channelz_v1_GetServerResponse>; + /** + * Gets all server sockets that exist in the process. + */ + GetServerSockets: grpc.handleUnaryCall<_grpc_channelz_v1_GetServerSocketsRequest__Output, _grpc_channelz_v1_GetServerSocketsResponse>; + /** + * Gets all servers that exist in the process. + */ + GetServers: grpc.handleUnaryCall<_grpc_channelz_v1_GetServersRequest__Output, _grpc_channelz_v1_GetServersResponse>; + /** + * Returns a single Socket or else a NOT_FOUND code. + */ + GetSocket: grpc.handleUnaryCall<_grpc_channelz_v1_GetSocketRequest__Output, _grpc_channelz_v1_GetSocketResponse>; + /** + * Returns a single Subchannel, or else a NOT_FOUND code. + */ + GetSubchannel: grpc.handleUnaryCall<_grpc_channelz_v1_GetSubchannelRequest__Output, _grpc_channelz_v1_GetSubchannelResponse>; + /** + * Gets all root channels (i.e. channels the application has directly + * created). This does not include subchannels nor non-top level channels. + */ + GetTopChannels: grpc.handleUnaryCall<_grpc_channelz_v1_GetTopChannelsRequest__Output, _grpc_channelz_v1_GetTopChannelsResponse>; +} +export interface ChannelzDefinition extends grpc.ServiceDefinition { + GetChannel: MethodDefinition<_grpc_channelz_v1_GetChannelRequest, _grpc_channelz_v1_GetChannelResponse, _grpc_channelz_v1_GetChannelRequest__Output, _grpc_channelz_v1_GetChannelResponse__Output>; + GetServer: MethodDefinition<_grpc_channelz_v1_GetServerRequest, _grpc_channelz_v1_GetServerResponse, _grpc_channelz_v1_GetServerRequest__Output, _grpc_channelz_v1_GetServerResponse__Output>; + GetServerSockets: MethodDefinition<_grpc_channelz_v1_GetServerSocketsRequest, _grpc_channelz_v1_GetServerSocketsResponse, _grpc_channelz_v1_GetServerSocketsRequest__Output, _grpc_channelz_v1_GetServerSocketsResponse__Output>; + GetServers: MethodDefinition<_grpc_channelz_v1_GetServersRequest, _grpc_channelz_v1_GetServersResponse, _grpc_channelz_v1_GetServersRequest__Output, _grpc_channelz_v1_GetServersResponse__Output>; + GetSocket: MethodDefinition<_grpc_channelz_v1_GetSocketRequest, _grpc_channelz_v1_GetSocketResponse, _grpc_channelz_v1_GetSocketRequest__Output, _grpc_channelz_v1_GetSocketResponse__Output>; + GetSubchannel: MethodDefinition<_grpc_channelz_v1_GetSubchannelRequest, _grpc_channelz_v1_GetSubchannelResponse, _grpc_channelz_v1_GetSubchannelRequest__Output, _grpc_channelz_v1_GetSubchannelResponse__Output>; + GetTopChannels: MethodDefinition<_grpc_channelz_v1_GetTopChannelsRequest, _grpc_channelz_v1_GetTopChannelsResponse, _grpc_channelz_v1_GetTopChannelsRequest__Output, _grpc_channelz_v1_GetTopChannelsResponse__Output>; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.js new file mode 100644 index 0000000..9fdf9fc --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Channelz.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.js.map new file mode 100644 index 0000000..86fafec --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Channelz.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/Channelz.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.d.ts new file mode 100644 index 0000000..4956cfa --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.d.ts @@ -0,0 +1,13 @@ +import type { Long } from '@grpc/proto-loader'; +export interface GetChannelRequest { + /** + * channel_id is the identifier of the specific channel to get. + */ + 'channel_id'?: (number | string | Long); +} +export interface GetChannelRequest__Output { + /** + * channel_id is the identifier of the specific channel to get. + */ + 'channel_id': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.js new file mode 100644 index 0000000..10948d4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetChannelRequest.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.js.map new file mode 100644 index 0000000..0ae3f26 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetChannelRequest.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetChannelRequest.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.d.ts new file mode 100644 index 0000000..2fbab92 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.d.ts @@ -0,0 +1,15 @@ +import type { Channel as _grpc_channelz_v1_Channel, Channel__Output as _grpc_channelz_v1_Channel__Output } from '../../../grpc/channelz/v1/Channel'; +export interface GetChannelResponse { + /** + * The Channel that corresponds to the requested channel_id. This field + * should be set. + */ + 'channel'?: (_grpc_channelz_v1_Channel | null); +} +export interface GetChannelResponse__Output { + /** + * The Channel that corresponds to the requested channel_id. This field + * should be set. + */ + 'channel': (_grpc_channelz_v1_Channel__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.js new file mode 100644 index 0000000..02a4426 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetChannelResponse.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.js.map new file mode 100644 index 0000000..a3cfefb --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetChannelResponse.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetChannelResponse.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.d.ts new file mode 100644 index 0000000..1df8503 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.d.ts @@ -0,0 +1,13 @@ +import type { Long } from '@grpc/proto-loader'; +export interface GetServerRequest { + /** + * server_id is the identifier of the specific server to get. + */ + 'server_id'?: (number | string | Long); +} +export interface GetServerRequest__Output { + /** + * server_id is the identifier of the specific server to get. + */ + 'server_id': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.js new file mode 100644 index 0000000..77717b4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetServerRequest.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.js.map new file mode 100644 index 0000000..86fbba6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetServerRequest.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetServerRequest.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.d.ts new file mode 100644 index 0000000..2da13dd --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.d.ts @@ -0,0 +1,15 @@ +import type { Server as _grpc_channelz_v1_Server, Server__Output as _grpc_channelz_v1_Server__Output } from '../../../grpc/channelz/v1/Server'; +export interface GetServerResponse { + /** + * The Server that corresponds to the requested server_id. This field + * should be set. + */ + 'server'?: (_grpc_channelz_v1_Server | null); +} +export interface GetServerResponse__Output { + /** + * The Server that corresponds to the requested server_id. This field + * should be set. + */ + 'server': (_grpc_channelz_v1_Server__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.js new file mode 100644 index 0000000..130eb1b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetServerResponse.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.js.map new file mode 100644 index 0000000..f4b16ff --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetServerResponse.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetServerResponse.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.d.ts new file mode 100644 index 0000000..d810b92 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.d.ts @@ -0,0 +1,35 @@ +import type { Long } from '@grpc/proto-loader'; +export interface GetServerSocketsRequest { + 'server_id'?: (number | string | Long); + /** + * start_socket_id indicates that only sockets at or above this id should be + * included in the results. + * To request the first page, this must be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_socket_id'?: (number | string | Long); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results'?: (number | string | Long); +} +export interface GetServerSocketsRequest__Output { + 'server_id': (string); + /** + * start_socket_id indicates that only sockets at or above this id should be + * included in the results. + * To request the first page, this must be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_socket_id': (string); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.js new file mode 100644 index 0000000..1a15183 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetServerSocketsRequest.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.js.map new file mode 100644 index 0000000..458dd98 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetServerSocketsRequest.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetServerSocketsRequest.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.d.ts new file mode 100644 index 0000000..4c329ae --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.d.ts @@ -0,0 +1,29 @@ +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from '../../../grpc/channelz/v1/SocketRef'; +export interface GetServerSocketsResponse { + /** + * list of socket refs that the connection detail service knows about. Sorted in + * ascending socket_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'socket_ref'?: (_grpc_channelz_v1_SocketRef)[]; + /** + * If set, indicates that the list of sockets is the final list. Requesting + * more sockets will only return more if they are created after this RPC + * completes. + */ + 'end'?: (boolean); +} +export interface GetServerSocketsResponse__Output { + /** + * list of socket refs that the connection detail service knows about. Sorted in + * ascending socket_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'socket_ref': (_grpc_channelz_v1_SocketRef__Output)[]; + /** + * If set, indicates that the list of sockets is the final list. Requesting + * more sockets will only return more if they are created after this RPC + * completes. + */ + 'end': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.js new file mode 100644 index 0000000..29e424f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetServerSocketsResponse.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.js.map new file mode 100644 index 0000000..dc99923 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetServerSocketsResponse.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetServerSocketsResponse.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.d.ts new file mode 100644 index 0000000..64ace6e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.d.ts @@ -0,0 +1,33 @@ +import type { Long } from '@grpc/proto-loader'; +export interface GetServersRequest { + /** + * start_server_id indicates that only servers at or above this id should be + * included in the results. + * To request the first page, this must be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_server_id'?: (number | string | Long); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results'?: (number | string | Long); +} +export interface GetServersRequest__Output { + /** + * start_server_id indicates that only servers at or above this id should be + * included in the results. + * To request the first page, this must be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_server_id': (string); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.js new file mode 100644 index 0000000..7371813 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetServersRequest.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.js.map new file mode 100644 index 0000000..db7c710 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetServersRequest.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetServersRequest.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.d.ts new file mode 100644 index 0000000..d3840cd --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.d.ts @@ -0,0 +1,29 @@ +import type { Server as _grpc_channelz_v1_Server, Server__Output as _grpc_channelz_v1_Server__Output } from '../../../grpc/channelz/v1/Server'; +export interface GetServersResponse { + /** + * list of servers that the connection detail service knows about. Sorted in + * ascending server_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'server'?: (_grpc_channelz_v1_Server)[]; + /** + * If set, indicates that the list of servers is the final list. Requesting + * more servers will only return more if they are created after this RPC + * completes. + */ + 'end'?: (boolean); +} +export interface GetServersResponse__Output { + /** + * list of servers that the connection detail service knows about. Sorted in + * ascending server_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'server': (_grpc_channelz_v1_Server__Output)[]; + /** + * If set, indicates that the list of servers is the final list. Requesting + * more servers will only return more if they are created after this RPC + * completes. + */ + 'end': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.js new file mode 100644 index 0000000..5124298 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetServersResponse.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.js.map new file mode 100644 index 0000000..74e4bba --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetServersResponse.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetServersResponse.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.d.ts new file mode 100644 index 0000000..f80615c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.d.ts @@ -0,0 +1,25 @@ +import type { Long } from '@grpc/proto-loader'; +export interface GetSocketRequest { + /** + * socket_id is the identifier of the specific socket to get. + */ + 'socket_id'?: (number | string | Long); + /** + * If true, the response will contain only high level information + * that is inexpensive to obtain. Fields thay may be omitted are + * documented. + */ + 'summary'?: (boolean); +} +export interface GetSocketRequest__Output { + /** + * socket_id is the identifier of the specific socket to get. + */ + 'socket_id': (string); + /** + * If true, the response will contain only high level information + * that is inexpensive to obtain. Fields thay may be omitted are + * documented. + */ + 'summary': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.js new file mode 100644 index 0000000..40ad25b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetSocketRequest.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.js.map new file mode 100644 index 0000000..3b4c180 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetSocketRequest.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetSocketRequest.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.d.ts new file mode 100644 index 0000000..a9795d3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.d.ts @@ -0,0 +1,15 @@ +import type { Socket as _grpc_channelz_v1_Socket, Socket__Output as _grpc_channelz_v1_Socket__Output } from '../../../grpc/channelz/v1/Socket'; +export interface GetSocketResponse { + /** + * The Socket that corresponds to the requested socket_id. This field + * should be set. + */ + 'socket'?: (_grpc_channelz_v1_Socket | null); +} +export interface GetSocketResponse__Output { + /** + * The Socket that corresponds to the requested socket_id. This field + * should be set. + */ + 'socket': (_grpc_channelz_v1_Socket__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.js new file mode 100644 index 0000000..ace0ef2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetSocketResponse.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.js.map new file mode 100644 index 0000000..90fada3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetSocketResponse.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetSocketResponse.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.d.ts new file mode 100644 index 0000000..114a91f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.d.ts @@ -0,0 +1,13 @@ +import type { Long } from '@grpc/proto-loader'; +export interface GetSubchannelRequest { + /** + * subchannel_id is the identifier of the specific subchannel to get. + */ + 'subchannel_id'?: (number | string | Long); +} +export interface GetSubchannelRequest__Output { + /** + * subchannel_id is the identifier of the specific subchannel to get. + */ + 'subchannel_id': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.js new file mode 100644 index 0000000..90f45ea --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetSubchannelRequest.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.js.map new file mode 100644 index 0000000..b8f8f62 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetSubchannelRequest.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetSubchannelRequest.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.d.ts new file mode 100644 index 0000000..455639f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.d.ts @@ -0,0 +1,15 @@ +import type { Subchannel as _grpc_channelz_v1_Subchannel, Subchannel__Output as _grpc_channelz_v1_Subchannel__Output } from '../../../grpc/channelz/v1/Subchannel'; +export interface GetSubchannelResponse { + /** + * The Subchannel that corresponds to the requested subchannel_id. This + * field should be set. + */ + 'subchannel'?: (_grpc_channelz_v1_Subchannel | null); +} +export interface GetSubchannelResponse__Output { + /** + * The Subchannel that corresponds to the requested subchannel_id. This + * field should be set. + */ + 'subchannel': (_grpc_channelz_v1_Subchannel__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.js new file mode 100644 index 0000000..52d4111 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetSubchannelResponse.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.js.map new file mode 100644 index 0000000..b39861f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetSubchannelResponse.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetSubchannelResponse.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.d.ts new file mode 100644 index 0000000..43049af --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.d.ts @@ -0,0 +1,33 @@ +import type { Long } from '@grpc/proto-loader'; +export interface GetTopChannelsRequest { + /** + * start_channel_id indicates that only channels at or above this id should be + * included in the results. + * To request the first page, this should be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_channel_id'?: (number | string | Long); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results'?: (number | string | Long); +} +export interface GetTopChannelsRequest__Output { + /** + * start_channel_id indicates that only channels at or above this id should be + * included in the results. + * To request the first page, this should be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_channel_id': (string); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.js new file mode 100644 index 0000000..8b3e023 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetTopChannelsRequest.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.js.map new file mode 100644 index 0000000..c4ffc68 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetTopChannelsRequest.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetTopChannelsRequest.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.d.ts new file mode 100644 index 0000000..03f282f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.d.ts @@ -0,0 +1,29 @@ +import type { Channel as _grpc_channelz_v1_Channel, Channel__Output as _grpc_channelz_v1_Channel__Output } from '../../../grpc/channelz/v1/Channel'; +export interface GetTopChannelsResponse { + /** + * list of channels that the connection detail service knows about. Sorted in + * ascending channel_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'channel'?: (_grpc_channelz_v1_Channel)[]; + /** + * If set, indicates that the list of channels is the final list. Requesting + * more channels can only return more if they are created after this RPC + * completes. + */ + 'end'?: (boolean); +} +export interface GetTopChannelsResponse__Output { + /** + * list of channels that the connection detail service knows about. Sorted in + * ascending channel_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'channel': (_grpc_channelz_v1_Channel__Output)[]; + /** + * If set, indicates that the list of channels is the final list. Requesting + * more channels can only return more if they are created after this RPC + * completes. + */ + 'end': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.js new file mode 100644 index 0000000..44f1c91 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetTopChannelsResponse.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.js.map new file mode 100644 index 0000000..b691e5e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetTopChannelsResponse.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetTopChannelsResponse.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.d.ts new file mode 100644 index 0000000..a30090a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.d.ts @@ -0,0 +1,79 @@ +import type { Any as _google_protobuf_Any, Any__Output as _google_protobuf_Any__Output } from '../../../google/protobuf/Any'; +export interface _grpc_channelz_v1_Security_OtherSecurity { + /** + * The human readable version of the value. + */ + 'name'?: (string); + /** + * The actual security details message. + */ + 'value'?: (_google_protobuf_Any | null); +} +export interface _grpc_channelz_v1_Security_OtherSecurity__Output { + /** + * The human readable version of the value. + */ + 'name': (string); + /** + * The actual security details message. + */ + 'value': (_google_protobuf_Any__Output | null); +} +export interface _grpc_channelz_v1_Security_Tls { + /** + * The cipher suite name in the RFC 4346 format: + * https://tools.ietf.org/html/rfc4346#appendix-C + */ + 'standard_name'?: (string); + /** + * Some other way to describe the cipher suite if + * the RFC 4346 name is not available. + */ + 'other_name'?: (string); + /** + * the certificate used by this endpoint. + */ + 'local_certificate'?: (Buffer | Uint8Array | string); + /** + * the certificate used by the remote endpoint. + */ + 'remote_certificate'?: (Buffer | Uint8Array | string); + 'cipher_suite'?: "standard_name" | "other_name"; +} +export interface _grpc_channelz_v1_Security_Tls__Output { + /** + * The cipher suite name in the RFC 4346 format: + * https://tools.ietf.org/html/rfc4346#appendix-C + */ + 'standard_name'?: (string); + /** + * Some other way to describe the cipher suite if + * the RFC 4346 name is not available. + */ + 'other_name'?: (string); + /** + * the certificate used by this endpoint. + */ + 'local_certificate': (Buffer); + /** + * the certificate used by the remote endpoint. + */ + 'remote_certificate': (Buffer); + 'cipher_suite'?: "standard_name" | "other_name"; +} +/** + * Security represents details about how secure the socket is. + */ +export interface Security { + 'tls'?: (_grpc_channelz_v1_Security_Tls | null); + 'other'?: (_grpc_channelz_v1_Security_OtherSecurity | null); + 'model'?: "tls" | "other"; +} +/** + * Security represents details about how secure the socket is. + */ +export interface Security__Output { + 'tls'?: (_grpc_channelz_v1_Security_Tls__Output | null); + 'other'?: (_grpc_channelz_v1_Security_OtherSecurity__Output | null); + 'model'?: "tls" | "other"; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.js new file mode 100644 index 0000000..022b367 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Security.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.js.map new file mode 100644 index 0000000..3243c97 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Security.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/Security.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.d.ts new file mode 100644 index 0000000..8d984af --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.d.ts @@ -0,0 +1,41 @@ +import type { ServerRef as _grpc_channelz_v1_ServerRef, ServerRef__Output as _grpc_channelz_v1_ServerRef__Output } from '../../../grpc/channelz/v1/ServerRef'; +import type { ServerData as _grpc_channelz_v1_ServerData, ServerData__Output as _grpc_channelz_v1_ServerData__Output } from '../../../grpc/channelz/v1/ServerData'; +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from '../../../grpc/channelz/v1/SocketRef'; +/** + * Server represents a single server. There may be multiple servers in a single + * program. + */ +export interface Server { + /** + * The identifier for a Server. This should be set. + */ + 'ref'?: (_grpc_channelz_v1_ServerRef | null); + /** + * The associated data of the Server. + */ + 'data'?: (_grpc_channelz_v1_ServerData | null); + /** + * The sockets that the server is listening on. There are no ordering + * guarantees. This may be absent. + */ + 'listen_socket'?: (_grpc_channelz_v1_SocketRef)[]; +} +/** + * Server represents a single server. There may be multiple servers in a single + * program. + */ +export interface Server__Output { + /** + * The identifier for a Server. This should be set. + */ + 'ref': (_grpc_channelz_v1_ServerRef__Output | null); + /** + * The associated data of the Server. + */ + 'data': (_grpc_channelz_v1_ServerData__Output | null); + /** + * The sockets that the server is listening on. There are no ordering + * guarantees. This may be absent. + */ + 'listen_socket': (_grpc_channelz_v1_SocketRef__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.js new file mode 100644 index 0000000..b230e4d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Server.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.js.map new file mode 100644 index 0000000..522934d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Server.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/Server.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.d.ts new file mode 100644 index 0000000..7a2de0f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.d.ts @@ -0,0 +1,53 @@ +import type { ChannelTrace as _grpc_channelz_v1_ChannelTrace, ChannelTrace__Output as _grpc_channelz_v1_ChannelTrace__Output } from '../../../grpc/channelz/v1/ChannelTrace'; +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../../../google/protobuf/Timestamp'; +import type { Long } from '@grpc/proto-loader'; +/** + * ServerData is data for a specific Server. + */ +export interface ServerData { + /** + * A trace of recent events on the server. May be absent. + */ + 'trace'?: (_grpc_channelz_v1_ChannelTrace | null); + /** + * The number of incoming calls started on the server + */ + 'calls_started'?: (number | string | Long); + /** + * The number of incoming calls that have completed with an OK status + */ + 'calls_succeeded'?: (number | string | Long); + /** + * The number of incoming calls that have a completed with a non-OK status + */ + 'calls_failed'?: (number | string | Long); + /** + * The last time a call was started on the server. + */ + 'last_call_started_timestamp'?: (_google_protobuf_Timestamp | null); +} +/** + * ServerData is data for a specific Server. + */ +export interface ServerData__Output { + /** + * A trace of recent events on the server. May be absent. + */ + 'trace': (_grpc_channelz_v1_ChannelTrace__Output | null); + /** + * The number of incoming calls started on the server + */ + 'calls_started': (string); + /** + * The number of incoming calls that have completed with an OK status + */ + 'calls_succeeded': (string); + /** + * The number of incoming calls that have a completed with a non-OK status + */ + 'calls_failed': (string); + /** + * The last time a call was started on the server. + */ + 'last_call_started_timestamp': (_google_protobuf_Timestamp__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.js new file mode 100644 index 0000000..53d92a6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=ServerData.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.js.map new file mode 100644 index 0000000..b78c5b4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ServerData.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/ServerData.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.d.ts new file mode 100644 index 0000000..778b87d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.d.ts @@ -0,0 +1,27 @@ +import type { Long } from '@grpc/proto-loader'; +/** + * ServerRef is a reference to a Server. + */ +export interface ServerRef { + /** + * A globally unique identifier for this server. Must be a positive number. + */ + 'server_id'?: (number | string | Long); + /** + * An optional name associated with the server. + */ + 'name'?: (string); +} +/** + * ServerRef is a reference to a Server. + */ +export interface ServerRef__Output { + /** + * A globally unique identifier for this server. Must be a positive number. + */ + 'server_id': (string); + /** + * An optional name associated with the server. + */ + 'name': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.js new file mode 100644 index 0000000..9a623c7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=ServerRef.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.js.map new file mode 100644 index 0000000..75f5aad --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ServerRef.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/ServerRef.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.d.ts new file mode 100644 index 0000000..91d4ad8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.d.ts @@ -0,0 +1,66 @@ +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from '../../../grpc/channelz/v1/SocketRef'; +import type { SocketData as _grpc_channelz_v1_SocketData, SocketData__Output as _grpc_channelz_v1_SocketData__Output } from '../../../grpc/channelz/v1/SocketData'; +import type { Address as _grpc_channelz_v1_Address, Address__Output as _grpc_channelz_v1_Address__Output } from '../../../grpc/channelz/v1/Address'; +import type { Security as _grpc_channelz_v1_Security, Security__Output as _grpc_channelz_v1_Security__Output } from '../../../grpc/channelz/v1/Security'; +/** + * Information about an actual connection. Pronounced "sock-ay". + */ +export interface Socket { + /** + * The identifier for the Socket. + */ + 'ref'?: (_grpc_channelz_v1_SocketRef | null); + /** + * Data specific to this Socket. + */ + 'data'?: (_grpc_channelz_v1_SocketData | null); + /** + * The locally bound address. + */ + 'local'?: (_grpc_channelz_v1_Address | null); + /** + * The remote bound address. May be absent. + */ + 'remote'?: (_grpc_channelz_v1_Address | null); + /** + * Security details for this socket. May be absent if not available, or + * there is no security on the socket. + */ + 'security'?: (_grpc_channelz_v1_Security | null); + /** + * Optional, represents the name of the remote endpoint, if different than + * the original target name. + */ + 'remote_name'?: (string); +} +/** + * Information about an actual connection. Pronounced "sock-ay". + */ +export interface Socket__Output { + /** + * The identifier for the Socket. + */ + 'ref': (_grpc_channelz_v1_SocketRef__Output | null); + /** + * Data specific to this Socket. + */ + 'data': (_grpc_channelz_v1_SocketData__Output | null); + /** + * The locally bound address. + */ + 'local': (_grpc_channelz_v1_Address__Output | null); + /** + * The remote bound address. May be absent. + */ + 'remote': (_grpc_channelz_v1_Address__Output | null); + /** + * Security details for this socket. May be absent if not available, or + * there is no security on the socket. + */ + 'security': (_grpc_channelz_v1_Security__Output | null); + /** + * Optional, represents the name of the remote endpoint, if different than + * the original target name. + */ + 'remote_name': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.js new file mode 100644 index 0000000..c1e5004 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Socket.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.js.map new file mode 100644 index 0000000..d49d9df --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Socket.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/Socket.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.d.ts new file mode 100644 index 0000000..5553cb2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.d.ts @@ -0,0 +1,146 @@ +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../../../google/protobuf/Timestamp'; +import type { Int64Value as _google_protobuf_Int64Value, Int64Value__Output as _google_protobuf_Int64Value__Output } from '../../../google/protobuf/Int64Value'; +import type { SocketOption as _grpc_channelz_v1_SocketOption, SocketOption__Output as _grpc_channelz_v1_SocketOption__Output } from '../../../grpc/channelz/v1/SocketOption'; +import type { Long } from '@grpc/proto-loader'; +/** + * SocketData is data associated for a specific Socket. The fields present + * are specific to the implementation, so there may be minor differences in + * the semantics. (e.g. flow control windows) + */ +export interface SocketData { + /** + * The number of streams that have been started. + */ + 'streams_started'?: (number | string | Long); + /** + * The number of streams that have ended successfully: + * On client side, received frame with eos bit set; + * On server side, sent frame with eos bit set. + */ + 'streams_succeeded'?: (number | string | Long); + /** + * The number of streams that have ended unsuccessfully: + * On client side, ended without receiving frame with eos bit set; + * On server side, ended without sending frame with eos bit set. + */ + 'streams_failed'?: (number | string | Long); + /** + * The number of grpc messages successfully sent on this socket. + */ + 'messages_sent'?: (number | string | Long); + /** + * The number of grpc messages received on this socket. + */ + 'messages_received'?: (number | string | Long); + /** + * The number of keep alives sent. This is typically implemented with HTTP/2 + * ping messages. + */ + 'keep_alives_sent'?: (number | string | Long); + /** + * The last time a stream was created by this endpoint. Usually unset for + * servers. + */ + 'last_local_stream_created_timestamp'?: (_google_protobuf_Timestamp | null); + /** + * The last time a stream was created by the remote endpoint. Usually unset + * for clients. + */ + 'last_remote_stream_created_timestamp'?: (_google_protobuf_Timestamp | null); + /** + * The last time a message was sent by this endpoint. + */ + 'last_message_sent_timestamp'?: (_google_protobuf_Timestamp | null); + /** + * The last time a message was received by this endpoint. + */ + 'last_message_received_timestamp'?: (_google_protobuf_Timestamp | null); + /** + * The amount of window, granted to the local endpoint by the remote endpoint. + * This may be slightly out of date due to network latency. This does NOT + * include stream level or TCP level flow control info. + */ + 'local_flow_control_window'?: (_google_protobuf_Int64Value | null); + /** + * The amount of window, granted to the remote endpoint by the local endpoint. + * This may be slightly out of date due to network latency. This does NOT + * include stream level or TCP level flow control info. + */ + 'remote_flow_control_window'?: (_google_protobuf_Int64Value | null); + /** + * Socket options set on this socket. May be absent if 'summary' is set + * on GetSocketRequest. + */ + 'option'?: (_grpc_channelz_v1_SocketOption)[]; +} +/** + * SocketData is data associated for a specific Socket. The fields present + * are specific to the implementation, so there may be minor differences in + * the semantics. (e.g. flow control windows) + */ +export interface SocketData__Output { + /** + * The number of streams that have been started. + */ + 'streams_started': (string); + /** + * The number of streams that have ended successfully: + * On client side, received frame with eos bit set; + * On server side, sent frame with eos bit set. + */ + 'streams_succeeded': (string); + /** + * The number of streams that have ended unsuccessfully: + * On client side, ended without receiving frame with eos bit set; + * On server side, ended without sending frame with eos bit set. + */ + 'streams_failed': (string); + /** + * The number of grpc messages successfully sent on this socket. + */ + 'messages_sent': (string); + /** + * The number of grpc messages received on this socket. + */ + 'messages_received': (string); + /** + * The number of keep alives sent. This is typically implemented with HTTP/2 + * ping messages. + */ + 'keep_alives_sent': (string); + /** + * The last time a stream was created by this endpoint. Usually unset for + * servers. + */ + 'last_local_stream_created_timestamp': (_google_protobuf_Timestamp__Output | null); + /** + * The last time a stream was created by the remote endpoint. Usually unset + * for clients. + */ + 'last_remote_stream_created_timestamp': (_google_protobuf_Timestamp__Output | null); + /** + * The last time a message was sent by this endpoint. + */ + 'last_message_sent_timestamp': (_google_protobuf_Timestamp__Output | null); + /** + * The last time a message was received by this endpoint. + */ + 'last_message_received_timestamp': (_google_protobuf_Timestamp__Output | null); + /** + * The amount of window, granted to the local endpoint by the remote endpoint. + * This may be slightly out of date due to network latency. This does NOT + * include stream level or TCP level flow control info. + */ + 'local_flow_control_window': (_google_protobuf_Int64Value__Output | null); + /** + * The amount of window, granted to the remote endpoint by the local endpoint. + * This may be slightly out of date due to network latency. This does NOT + * include stream level or TCP level flow control info. + */ + 'remote_flow_control_window': (_google_protobuf_Int64Value__Output | null); + /** + * Socket options set on this socket. May be absent if 'summary' is set + * on GetSocketRequest. + */ + 'option': (_grpc_channelz_v1_SocketOption__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.js new file mode 100644 index 0000000..40638de --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SocketData.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.js.map new file mode 100644 index 0000000..c17becd --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SocketData.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/SocketData.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.d.ts new file mode 100644 index 0000000..53c23a2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.d.ts @@ -0,0 +1,43 @@ +import type { Any as _google_protobuf_Any, Any__Output as _google_protobuf_Any__Output } from '../../../google/protobuf/Any'; +/** + * SocketOption represents socket options for a socket. Specifically, these + * are the options returned by getsockopt(). + */ +export interface SocketOption { + /** + * The full name of the socket option. Typically this will be the upper case + * name, such as "SO_REUSEPORT". + */ + 'name'?: (string); + /** + * The human readable value of this socket option. At least one of value or + * additional will be set. + */ + 'value'?: (string); + /** + * Additional data associated with the socket option. At least one of value + * or additional will be set. + */ + 'additional'?: (_google_protobuf_Any | null); +} +/** + * SocketOption represents socket options for a socket. Specifically, these + * are the options returned by getsockopt(). + */ +export interface SocketOption__Output { + /** + * The full name of the socket option. Typically this will be the upper case + * name, such as "SO_REUSEPORT". + */ + 'name': (string); + /** + * The human readable value of this socket option. At least one of value or + * additional will be set. + */ + 'value': (string); + /** + * Additional data associated with the socket option. At least one of value + * or additional will be set. + */ + 'additional': (_google_protobuf_Any__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.js new file mode 100644 index 0000000..c459962 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SocketOption.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.js.map new file mode 100644 index 0000000..6b8bf59 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SocketOption.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/SocketOption.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.d.ts new file mode 100644 index 0000000..d0fd4b0 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.d.ts @@ -0,0 +1,29 @@ +import type { Duration as _google_protobuf_Duration, Duration__Output as _google_protobuf_Duration__Output } from '../../../google/protobuf/Duration'; +/** + * For use with SocketOption's additional field. This is primarily used for + * SO_LINGER. + */ +export interface SocketOptionLinger { + /** + * active maps to `struct linger.l_onoff` + */ + 'active'?: (boolean); + /** + * duration maps to `struct linger.l_linger` + */ + 'duration'?: (_google_protobuf_Duration | null); +} +/** + * For use with SocketOption's additional field. This is primarily used for + * SO_LINGER. + */ +export interface SocketOptionLinger__Output { + /** + * active maps to `struct linger.l_onoff` + */ + 'active': (boolean); + /** + * duration maps to `struct linger.l_linger` + */ + 'duration': (_google_protobuf_Duration__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.js new file mode 100644 index 0000000..01028c8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SocketOptionLinger.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.js.map new file mode 100644 index 0000000..a5283ab --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SocketOptionLinger.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/SocketOptionLinger.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.d.ts new file mode 100644 index 0000000..d2457e1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.d.ts @@ -0,0 +1,70 @@ +/** + * For use with SocketOption's additional field. Tcp info for + * SOL_TCP and TCP_INFO. + */ +export interface SocketOptionTcpInfo { + 'tcpi_state'?: (number); + 'tcpi_ca_state'?: (number); + 'tcpi_retransmits'?: (number); + 'tcpi_probes'?: (number); + 'tcpi_backoff'?: (number); + 'tcpi_options'?: (number); + 'tcpi_snd_wscale'?: (number); + 'tcpi_rcv_wscale'?: (number); + 'tcpi_rto'?: (number); + 'tcpi_ato'?: (number); + 'tcpi_snd_mss'?: (number); + 'tcpi_rcv_mss'?: (number); + 'tcpi_unacked'?: (number); + 'tcpi_sacked'?: (number); + 'tcpi_lost'?: (number); + 'tcpi_retrans'?: (number); + 'tcpi_fackets'?: (number); + 'tcpi_last_data_sent'?: (number); + 'tcpi_last_ack_sent'?: (number); + 'tcpi_last_data_recv'?: (number); + 'tcpi_last_ack_recv'?: (number); + 'tcpi_pmtu'?: (number); + 'tcpi_rcv_ssthresh'?: (number); + 'tcpi_rtt'?: (number); + 'tcpi_rttvar'?: (number); + 'tcpi_snd_ssthresh'?: (number); + 'tcpi_snd_cwnd'?: (number); + 'tcpi_advmss'?: (number); + 'tcpi_reordering'?: (number); +} +/** + * For use with SocketOption's additional field. Tcp info for + * SOL_TCP and TCP_INFO. + */ +export interface SocketOptionTcpInfo__Output { + 'tcpi_state': (number); + 'tcpi_ca_state': (number); + 'tcpi_retransmits': (number); + 'tcpi_probes': (number); + 'tcpi_backoff': (number); + 'tcpi_options': (number); + 'tcpi_snd_wscale': (number); + 'tcpi_rcv_wscale': (number); + 'tcpi_rto': (number); + 'tcpi_ato': (number); + 'tcpi_snd_mss': (number); + 'tcpi_rcv_mss': (number); + 'tcpi_unacked': (number); + 'tcpi_sacked': (number); + 'tcpi_lost': (number); + 'tcpi_retrans': (number); + 'tcpi_fackets': (number); + 'tcpi_last_data_sent': (number); + 'tcpi_last_ack_sent': (number); + 'tcpi_last_data_recv': (number); + 'tcpi_last_ack_recv': (number); + 'tcpi_pmtu': (number); + 'tcpi_rcv_ssthresh': (number); + 'tcpi_rtt': (number); + 'tcpi_rttvar': (number); + 'tcpi_snd_ssthresh': (number); + 'tcpi_snd_cwnd': (number); + 'tcpi_advmss': (number); + 'tcpi_reordering': (number); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.js new file mode 100644 index 0000000..b663a2e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SocketOptionTcpInfo.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.js.map new file mode 100644 index 0000000..cb68a32 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SocketOptionTcpInfo.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/SocketOptionTcpInfo.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.d.ts new file mode 100644 index 0000000..b102a34 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.d.ts @@ -0,0 +1,15 @@ +import type { Duration as _google_protobuf_Duration, Duration__Output as _google_protobuf_Duration__Output } from '../../../google/protobuf/Duration'; +/** + * For use with SocketOption's additional field. This is primarily used for + * SO_RCVTIMEO and SO_SNDTIMEO + */ +export interface SocketOptionTimeout { + 'duration'?: (_google_protobuf_Duration | null); +} +/** + * For use with SocketOption's additional field. This is primarily used for + * SO_RCVTIMEO and SO_SNDTIMEO + */ +export interface SocketOptionTimeout__Output { + 'duration': (_google_protobuf_Duration__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.js new file mode 100644 index 0000000..bcef7f5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SocketOptionTimeout.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.js.map new file mode 100644 index 0000000..73c8085 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SocketOptionTimeout.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/SocketOptionTimeout.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.d.ts new file mode 100644 index 0000000..2f34d65 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.d.ts @@ -0,0 +1,27 @@ +import type { Long } from '@grpc/proto-loader'; +/** + * SocketRef is a reference to a Socket. + */ +export interface SocketRef { + /** + * The globally unique id for this socket. Must be a positive number. + */ + 'socket_id'?: (number | string | Long); + /** + * An optional name associated with the socket. + */ + 'name'?: (string); +} +/** + * SocketRef is a reference to a Socket. + */ +export interface SocketRef__Output { + /** + * The globally unique id for this socket. Must be a positive number. + */ + 'socket_id': (string); + /** + * An optional name associated with the socket. + */ + 'name': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.js new file mode 100644 index 0000000..a73587f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SocketRef.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.js.map new file mode 100644 index 0000000..d970f9c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SocketRef.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/SocketRef.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.d.ts new file mode 100644 index 0000000..1222cb5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.d.ts @@ -0,0 +1,66 @@ +import type { SubchannelRef as _grpc_channelz_v1_SubchannelRef, SubchannelRef__Output as _grpc_channelz_v1_SubchannelRef__Output } from '../../../grpc/channelz/v1/SubchannelRef'; +import type { ChannelData as _grpc_channelz_v1_ChannelData, ChannelData__Output as _grpc_channelz_v1_ChannelData__Output } from '../../../grpc/channelz/v1/ChannelData'; +import type { ChannelRef as _grpc_channelz_v1_ChannelRef, ChannelRef__Output as _grpc_channelz_v1_ChannelRef__Output } from '../../../grpc/channelz/v1/ChannelRef'; +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from '../../../grpc/channelz/v1/SocketRef'; +/** + * Subchannel is a logical grouping of channels, subchannels, and sockets. + * A subchannel is load balanced over by it's ancestor + */ +export interface Subchannel { + /** + * The identifier for this channel. + */ + 'ref'?: (_grpc_channelz_v1_SubchannelRef | null); + /** + * Data specific to this channel. + */ + 'data'?: (_grpc_channelz_v1_ChannelData | null); + /** + * There are no ordering guarantees on the order of channel refs. + * There may not be cycles in the ref graph. + * A channel ref may be present in more than one channel or subchannel. + */ + 'channel_ref'?: (_grpc_channelz_v1_ChannelRef)[]; + /** + * At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + * There are no ordering guarantees on the order of subchannel refs. + * There may not be cycles in the ref graph. + * A sub channel ref may be present in more than one channel or subchannel. + */ + 'subchannel_ref'?: (_grpc_channelz_v1_SubchannelRef)[]; + /** + * There are no ordering guarantees on the order of sockets. + */ + 'socket_ref'?: (_grpc_channelz_v1_SocketRef)[]; +} +/** + * Subchannel is a logical grouping of channels, subchannels, and sockets. + * A subchannel is load balanced over by it's ancestor + */ +export interface Subchannel__Output { + /** + * The identifier for this channel. + */ + 'ref': (_grpc_channelz_v1_SubchannelRef__Output | null); + /** + * Data specific to this channel. + */ + 'data': (_grpc_channelz_v1_ChannelData__Output | null); + /** + * There are no ordering guarantees on the order of channel refs. + * There may not be cycles in the ref graph. + * A channel ref may be present in more than one channel or subchannel. + */ + 'channel_ref': (_grpc_channelz_v1_ChannelRef__Output)[]; + /** + * At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + * There are no ordering guarantees on the order of subchannel refs. + * There may not be cycles in the ref graph. + * A sub channel ref may be present in more than one channel or subchannel. + */ + 'subchannel_ref': (_grpc_channelz_v1_SubchannelRef__Output)[]; + /** + * There are no ordering guarantees on the order of sockets. + */ + 'socket_ref': (_grpc_channelz_v1_SocketRef__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.js new file mode 100644 index 0000000..6a5e543 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Subchannel.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.js.map new file mode 100644 index 0000000..6441346 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Subchannel.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/Subchannel.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.d.ts new file mode 100644 index 0000000..290fc85 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.d.ts @@ -0,0 +1,27 @@ +import type { Long } from '@grpc/proto-loader'; +/** + * SubchannelRef is a reference to a Subchannel. + */ +export interface SubchannelRef { + /** + * The globally unique id for this subchannel. Must be a positive number. + */ + 'subchannel_id'?: (number | string | Long); + /** + * An optional name associated with the subchannel. + */ + 'name'?: (string); +} +/** + * SubchannelRef is a reference to a Subchannel. + */ +export interface SubchannelRef__Output { + /** + * The globally unique id for this subchannel. Must be a positive number. + */ + 'subchannel_id': (string); + /** + * An optional name associated with the subchannel. + */ + 'name': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.js new file mode 100644 index 0000000..68520f9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SubchannelRef.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.js.map new file mode 100644 index 0000000..1e4b009 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SubchannelRef.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/SubchannelRef.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/orca.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/orca.d.ts new file mode 100644 index 0000000..c1d2b01 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/orca.d.ts @@ -0,0 +1,145 @@ +import type * as grpc from '../index'; +import type { EnumTypeDefinition, MessageTypeDefinition } from '@grpc/proto-loader'; +import type { DescriptorProto as _google_protobuf_DescriptorProto, DescriptorProto__Output as _google_protobuf_DescriptorProto__Output } from './google/protobuf/DescriptorProto'; +import type { Duration as _google_protobuf_Duration, Duration__Output as _google_protobuf_Duration__Output } from './google/protobuf/Duration'; +import type { EnumDescriptorProto as _google_protobuf_EnumDescriptorProto, EnumDescriptorProto__Output as _google_protobuf_EnumDescriptorProto__Output } from './google/protobuf/EnumDescriptorProto'; +import type { EnumOptions as _google_protobuf_EnumOptions, EnumOptions__Output as _google_protobuf_EnumOptions__Output } from './google/protobuf/EnumOptions'; +import type { EnumValueDescriptorProto as _google_protobuf_EnumValueDescriptorProto, EnumValueDescriptorProto__Output as _google_protobuf_EnumValueDescriptorProto__Output } from './google/protobuf/EnumValueDescriptorProto'; +import type { EnumValueOptions as _google_protobuf_EnumValueOptions, EnumValueOptions__Output as _google_protobuf_EnumValueOptions__Output } from './google/protobuf/EnumValueOptions'; +import type { ExtensionRangeOptions as _google_protobuf_ExtensionRangeOptions, ExtensionRangeOptions__Output as _google_protobuf_ExtensionRangeOptions__Output } from './google/protobuf/ExtensionRangeOptions'; +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from './google/protobuf/FeatureSet'; +import type { FeatureSetDefaults as _google_protobuf_FeatureSetDefaults, FeatureSetDefaults__Output as _google_protobuf_FeatureSetDefaults__Output } from './google/protobuf/FeatureSetDefaults'; +import type { FieldDescriptorProto as _google_protobuf_FieldDescriptorProto, FieldDescriptorProto__Output as _google_protobuf_FieldDescriptorProto__Output } from './google/protobuf/FieldDescriptorProto'; +import type { FieldOptions as _google_protobuf_FieldOptions, FieldOptions__Output as _google_protobuf_FieldOptions__Output } from './google/protobuf/FieldOptions'; +import type { FileDescriptorProto as _google_protobuf_FileDescriptorProto, FileDescriptorProto__Output as _google_protobuf_FileDescriptorProto__Output } from './google/protobuf/FileDescriptorProto'; +import type { FileDescriptorSet as _google_protobuf_FileDescriptorSet, FileDescriptorSet__Output as _google_protobuf_FileDescriptorSet__Output } from './google/protobuf/FileDescriptorSet'; +import type { FileOptions as _google_protobuf_FileOptions, FileOptions__Output as _google_protobuf_FileOptions__Output } from './google/protobuf/FileOptions'; +import type { GeneratedCodeInfo as _google_protobuf_GeneratedCodeInfo, GeneratedCodeInfo__Output as _google_protobuf_GeneratedCodeInfo__Output } from './google/protobuf/GeneratedCodeInfo'; +import type { MessageOptions as _google_protobuf_MessageOptions, MessageOptions__Output as _google_protobuf_MessageOptions__Output } from './google/protobuf/MessageOptions'; +import type { MethodDescriptorProto as _google_protobuf_MethodDescriptorProto, MethodDescriptorProto__Output as _google_protobuf_MethodDescriptorProto__Output } from './google/protobuf/MethodDescriptorProto'; +import type { MethodOptions as _google_protobuf_MethodOptions, MethodOptions__Output as _google_protobuf_MethodOptions__Output } from './google/protobuf/MethodOptions'; +import type { OneofDescriptorProto as _google_protobuf_OneofDescriptorProto, OneofDescriptorProto__Output as _google_protobuf_OneofDescriptorProto__Output } from './google/protobuf/OneofDescriptorProto'; +import type { OneofOptions as _google_protobuf_OneofOptions, OneofOptions__Output as _google_protobuf_OneofOptions__Output } from './google/protobuf/OneofOptions'; +import type { ServiceDescriptorProto as _google_protobuf_ServiceDescriptorProto, ServiceDescriptorProto__Output as _google_protobuf_ServiceDescriptorProto__Output } from './google/protobuf/ServiceDescriptorProto'; +import type { ServiceOptions as _google_protobuf_ServiceOptions, ServiceOptions__Output as _google_protobuf_ServiceOptions__Output } from './google/protobuf/ServiceOptions'; +import type { SourceCodeInfo as _google_protobuf_SourceCodeInfo, SourceCodeInfo__Output as _google_protobuf_SourceCodeInfo__Output } from './google/protobuf/SourceCodeInfo'; +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from './google/protobuf/Timestamp'; +import type { UninterpretedOption as _google_protobuf_UninterpretedOption, UninterpretedOption__Output as _google_protobuf_UninterpretedOption__Output } from './google/protobuf/UninterpretedOption'; +import type { AnyRules as _validate_AnyRules, AnyRules__Output as _validate_AnyRules__Output } from './validate/AnyRules'; +import type { BoolRules as _validate_BoolRules, BoolRules__Output as _validate_BoolRules__Output } from './validate/BoolRules'; +import type { BytesRules as _validate_BytesRules, BytesRules__Output as _validate_BytesRules__Output } from './validate/BytesRules'; +import type { DoubleRules as _validate_DoubleRules, DoubleRules__Output as _validate_DoubleRules__Output } from './validate/DoubleRules'; +import type { DurationRules as _validate_DurationRules, DurationRules__Output as _validate_DurationRules__Output } from './validate/DurationRules'; +import type { EnumRules as _validate_EnumRules, EnumRules__Output as _validate_EnumRules__Output } from './validate/EnumRules'; +import type { FieldRules as _validate_FieldRules, FieldRules__Output as _validate_FieldRules__Output } from './validate/FieldRules'; +import type { Fixed32Rules as _validate_Fixed32Rules, Fixed32Rules__Output as _validate_Fixed32Rules__Output } from './validate/Fixed32Rules'; +import type { Fixed64Rules as _validate_Fixed64Rules, Fixed64Rules__Output as _validate_Fixed64Rules__Output } from './validate/Fixed64Rules'; +import type { FloatRules as _validate_FloatRules, FloatRules__Output as _validate_FloatRules__Output } from './validate/FloatRules'; +import type { Int32Rules as _validate_Int32Rules, Int32Rules__Output as _validate_Int32Rules__Output } from './validate/Int32Rules'; +import type { Int64Rules as _validate_Int64Rules, Int64Rules__Output as _validate_Int64Rules__Output } from './validate/Int64Rules'; +import type { MapRules as _validate_MapRules, MapRules__Output as _validate_MapRules__Output } from './validate/MapRules'; +import type { MessageRules as _validate_MessageRules, MessageRules__Output as _validate_MessageRules__Output } from './validate/MessageRules'; +import type { RepeatedRules as _validate_RepeatedRules, RepeatedRules__Output as _validate_RepeatedRules__Output } from './validate/RepeatedRules'; +import type { SFixed32Rules as _validate_SFixed32Rules, SFixed32Rules__Output as _validate_SFixed32Rules__Output } from './validate/SFixed32Rules'; +import type { SFixed64Rules as _validate_SFixed64Rules, SFixed64Rules__Output as _validate_SFixed64Rules__Output } from './validate/SFixed64Rules'; +import type { SInt32Rules as _validate_SInt32Rules, SInt32Rules__Output as _validate_SInt32Rules__Output } from './validate/SInt32Rules'; +import type { SInt64Rules as _validate_SInt64Rules, SInt64Rules__Output as _validate_SInt64Rules__Output } from './validate/SInt64Rules'; +import type { StringRules as _validate_StringRules, StringRules__Output as _validate_StringRules__Output } from './validate/StringRules'; +import type { TimestampRules as _validate_TimestampRules, TimestampRules__Output as _validate_TimestampRules__Output } from './validate/TimestampRules'; +import type { UInt32Rules as _validate_UInt32Rules, UInt32Rules__Output as _validate_UInt32Rules__Output } from './validate/UInt32Rules'; +import type { UInt64Rules as _validate_UInt64Rules, UInt64Rules__Output as _validate_UInt64Rules__Output } from './validate/UInt64Rules'; +import type { OrcaLoadReport as _xds_data_orca_v3_OrcaLoadReport, OrcaLoadReport__Output as _xds_data_orca_v3_OrcaLoadReport__Output } from './xds/data/orca/v3/OrcaLoadReport'; +import type { OpenRcaServiceClient as _xds_service_orca_v3_OpenRcaServiceClient, OpenRcaServiceDefinition as _xds_service_orca_v3_OpenRcaServiceDefinition } from './xds/service/orca/v3/OpenRcaService'; +import type { OrcaLoadReportRequest as _xds_service_orca_v3_OrcaLoadReportRequest, OrcaLoadReportRequest__Output as _xds_service_orca_v3_OrcaLoadReportRequest__Output } from './xds/service/orca/v3/OrcaLoadReportRequest'; +type SubtypeConstructor any, Subtype> = { + new (...args: ConstructorParameters): Subtype; +}; +export interface ProtoGrpcType { + google: { + protobuf: { + DescriptorProto: MessageTypeDefinition<_google_protobuf_DescriptorProto, _google_protobuf_DescriptorProto__Output>; + Duration: MessageTypeDefinition<_google_protobuf_Duration, _google_protobuf_Duration__Output>; + Edition: EnumTypeDefinition; + EnumDescriptorProto: MessageTypeDefinition<_google_protobuf_EnumDescriptorProto, _google_protobuf_EnumDescriptorProto__Output>; + EnumOptions: MessageTypeDefinition<_google_protobuf_EnumOptions, _google_protobuf_EnumOptions__Output>; + EnumValueDescriptorProto: MessageTypeDefinition<_google_protobuf_EnumValueDescriptorProto, _google_protobuf_EnumValueDescriptorProto__Output>; + EnumValueOptions: MessageTypeDefinition<_google_protobuf_EnumValueOptions, _google_protobuf_EnumValueOptions__Output>; + ExtensionRangeOptions: MessageTypeDefinition<_google_protobuf_ExtensionRangeOptions, _google_protobuf_ExtensionRangeOptions__Output>; + FeatureSet: MessageTypeDefinition<_google_protobuf_FeatureSet, _google_protobuf_FeatureSet__Output>; + FeatureSetDefaults: MessageTypeDefinition<_google_protobuf_FeatureSetDefaults, _google_protobuf_FeatureSetDefaults__Output>; + FieldDescriptorProto: MessageTypeDefinition<_google_protobuf_FieldDescriptorProto, _google_protobuf_FieldDescriptorProto__Output>; + FieldOptions: MessageTypeDefinition<_google_protobuf_FieldOptions, _google_protobuf_FieldOptions__Output>; + FileDescriptorProto: MessageTypeDefinition<_google_protobuf_FileDescriptorProto, _google_protobuf_FileDescriptorProto__Output>; + FileDescriptorSet: MessageTypeDefinition<_google_protobuf_FileDescriptorSet, _google_protobuf_FileDescriptorSet__Output>; + FileOptions: MessageTypeDefinition<_google_protobuf_FileOptions, _google_protobuf_FileOptions__Output>; + GeneratedCodeInfo: MessageTypeDefinition<_google_protobuf_GeneratedCodeInfo, _google_protobuf_GeneratedCodeInfo__Output>; + MessageOptions: MessageTypeDefinition<_google_protobuf_MessageOptions, _google_protobuf_MessageOptions__Output>; + MethodDescriptorProto: MessageTypeDefinition<_google_protobuf_MethodDescriptorProto, _google_protobuf_MethodDescriptorProto__Output>; + MethodOptions: MessageTypeDefinition<_google_protobuf_MethodOptions, _google_protobuf_MethodOptions__Output>; + OneofDescriptorProto: MessageTypeDefinition<_google_protobuf_OneofDescriptorProto, _google_protobuf_OneofDescriptorProto__Output>; + OneofOptions: MessageTypeDefinition<_google_protobuf_OneofOptions, _google_protobuf_OneofOptions__Output>; + ServiceDescriptorProto: MessageTypeDefinition<_google_protobuf_ServiceDescriptorProto, _google_protobuf_ServiceDescriptorProto__Output>; + ServiceOptions: MessageTypeDefinition<_google_protobuf_ServiceOptions, _google_protobuf_ServiceOptions__Output>; + SourceCodeInfo: MessageTypeDefinition<_google_protobuf_SourceCodeInfo, _google_protobuf_SourceCodeInfo__Output>; + SymbolVisibility: EnumTypeDefinition; + Timestamp: MessageTypeDefinition<_google_protobuf_Timestamp, _google_protobuf_Timestamp__Output>; + UninterpretedOption: MessageTypeDefinition<_google_protobuf_UninterpretedOption, _google_protobuf_UninterpretedOption__Output>; + }; + }; + validate: { + AnyRules: MessageTypeDefinition<_validate_AnyRules, _validate_AnyRules__Output>; + BoolRules: MessageTypeDefinition<_validate_BoolRules, _validate_BoolRules__Output>; + BytesRules: MessageTypeDefinition<_validate_BytesRules, _validate_BytesRules__Output>; + DoubleRules: MessageTypeDefinition<_validate_DoubleRules, _validate_DoubleRules__Output>; + DurationRules: MessageTypeDefinition<_validate_DurationRules, _validate_DurationRules__Output>; + EnumRules: MessageTypeDefinition<_validate_EnumRules, _validate_EnumRules__Output>; + FieldRules: MessageTypeDefinition<_validate_FieldRules, _validate_FieldRules__Output>; + Fixed32Rules: MessageTypeDefinition<_validate_Fixed32Rules, _validate_Fixed32Rules__Output>; + Fixed64Rules: MessageTypeDefinition<_validate_Fixed64Rules, _validate_Fixed64Rules__Output>; + FloatRules: MessageTypeDefinition<_validate_FloatRules, _validate_FloatRules__Output>; + Int32Rules: MessageTypeDefinition<_validate_Int32Rules, _validate_Int32Rules__Output>; + Int64Rules: MessageTypeDefinition<_validate_Int64Rules, _validate_Int64Rules__Output>; + KnownRegex: EnumTypeDefinition; + MapRules: MessageTypeDefinition<_validate_MapRules, _validate_MapRules__Output>; + MessageRules: MessageTypeDefinition<_validate_MessageRules, _validate_MessageRules__Output>; + RepeatedRules: MessageTypeDefinition<_validate_RepeatedRules, _validate_RepeatedRules__Output>; + SFixed32Rules: MessageTypeDefinition<_validate_SFixed32Rules, _validate_SFixed32Rules__Output>; + SFixed64Rules: MessageTypeDefinition<_validate_SFixed64Rules, _validate_SFixed64Rules__Output>; + SInt32Rules: MessageTypeDefinition<_validate_SInt32Rules, _validate_SInt32Rules__Output>; + SInt64Rules: MessageTypeDefinition<_validate_SInt64Rules, _validate_SInt64Rules__Output>; + StringRules: MessageTypeDefinition<_validate_StringRules, _validate_StringRules__Output>; + TimestampRules: MessageTypeDefinition<_validate_TimestampRules, _validate_TimestampRules__Output>; + UInt32Rules: MessageTypeDefinition<_validate_UInt32Rules, _validate_UInt32Rules__Output>; + UInt64Rules: MessageTypeDefinition<_validate_UInt64Rules, _validate_UInt64Rules__Output>; + }; + xds: { + data: { + orca: { + v3: { + OrcaLoadReport: MessageTypeDefinition<_xds_data_orca_v3_OrcaLoadReport, _xds_data_orca_v3_OrcaLoadReport__Output>; + }; + }; + }; + service: { + orca: { + v3: { + /** + * Out-of-band (OOB) load reporting service for the additional load reporting + * agent that does not sit in the request path. Reports are periodically sampled + * with sufficient frequency to provide temporal association with requests. + * OOB reporting compensates the limitation of in-band reporting in revealing + * costs for backends that do not provide a steady stream of telemetry such as + * long running stream operations and zero QPS services. This is a server + * streaming service, client needs to terminate current RPC and initiate + * a new call to change backend reporting frequency. + */ + OpenRcaService: SubtypeConstructor & { + service: _xds_service_orca_v3_OpenRcaServiceDefinition; + }; + OrcaLoadReportRequest: MessageTypeDefinition<_xds_service_orca_v3_OrcaLoadReportRequest, _xds_service_orca_v3_OrcaLoadReportRequest__Output>; + }; + }; + }; + }; +} +export {}; diff --git a/node_modules/@grpc/grpc-js/build/src/generated/orca.js b/node_modules/@grpc/grpc-js/build/src/generated/orca.js new file mode 100644 index 0000000..fd23d4e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/orca.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=orca.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/orca.js.map b/node_modules/@grpc/grpc-js/build/src/generated/orca.js.map new file mode 100644 index 0000000..5451d45 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/orca.js.map @@ -0,0 +1 @@ +{"version":3,"file":"orca.js","sourceRoot":"","sources":["../../../src/generated/orca.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/AnyRules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/AnyRules.d.ts new file mode 100644 index 0000000..7d7ff8d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/AnyRules.d.ts @@ -0,0 +1,40 @@ +/** + * AnyRules describe constraints applied exclusively to the + * `google.protobuf.Any` well-known type + */ +export interface AnyRules { + /** + * Required specifies that this field must be set + */ + 'required'?: (boolean); + /** + * In specifies that this field's `type_url` must be equal to one of the + * specified values. + */ + 'in'?: (string)[]; + /** + * NotIn specifies that this field's `type_url` must not be equal to any of + * the specified values. + */ + 'not_in'?: (string)[]; +} +/** + * AnyRules describe constraints applied exclusively to the + * `google.protobuf.Any` well-known type + */ +export interface AnyRules__Output { + /** + * Required specifies that this field must be set + */ + 'required': (boolean); + /** + * In specifies that this field's `type_url` must be equal to one of the + * specified values. + */ + 'in': (string)[]; + /** + * NotIn specifies that this field's `type_url` must not be equal to any of + * the specified values. + */ + 'not_in': (string)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/AnyRules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/AnyRules.js new file mode 100644 index 0000000..2d1e6ca --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/AnyRules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=AnyRules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/AnyRules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/AnyRules.js.map new file mode 100644 index 0000000..23bf70f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/AnyRules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AnyRules.js","sourceRoot":"","sources":["../../../../src/generated/validate/AnyRules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/BoolRules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/BoolRules.d.ts new file mode 100644 index 0000000..3fed392 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/BoolRules.d.ts @@ -0,0 +1,18 @@ +/** + * BoolRules describes the constraints applied to `bool` values + */ +export interface BoolRules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (boolean); +} +/** + * BoolRules describes the constraints applied to `bool` values + */ +export interface BoolRules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/BoolRules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/BoolRules.js new file mode 100644 index 0000000..16b1b53 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/BoolRules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=BoolRules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/BoolRules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/BoolRules.js.map new file mode 100644 index 0000000..3222bae --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/BoolRules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"BoolRules.js","sourceRoot":"","sources":["../../../../src/generated/validate/BoolRules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/BytesRules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/BytesRules.d.ts new file mode 100644 index 0000000..b542026 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/BytesRules.d.ts @@ -0,0 +1,149 @@ +import type { Long } from '@grpc/proto-loader'; +/** + * BytesRules describe the constraints applied to `bytes` values + */ +export interface BytesRules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (Buffer | Uint8Array | string); + /** + * MinLen specifies that this field must be the specified number of bytes + * at a minimum + */ + 'min_len'?: (number | string | Long); + /** + * MaxLen specifies that this field must be the specified number of bytes + * at a maximum + */ + 'max_len'?: (number | string | Long); + /** + * Pattern specifes that this field must match against the specified + * regular expression (RE2 syntax). The included expression should elide + * any delimiters. + */ + 'pattern'?: (string); + /** + * Prefix specifies that this field must have the specified bytes at the + * beginning of the string. + */ + 'prefix'?: (Buffer | Uint8Array | string); + /** + * Suffix specifies that this field must have the specified bytes at the + * end of the string. + */ + 'suffix'?: (Buffer | Uint8Array | string); + /** + * Contains specifies that this field must have the specified bytes + * anywhere in the string. + */ + 'contains'?: (Buffer | Uint8Array | string); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (Buffer | Uint8Array | string)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (Buffer | Uint8Array | string)[]; + /** + * Ip specifies that the field must be a valid IP (v4 or v6) address in + * byte format + */ + 'ip'?: (boolean); + /** + * Ipv4 specifies that the field must be a valid IPv4 address in byte + * format + */ + 'ipv4'?: (boolean); + /** + * Ipv6 specifies that the field must be a valid IPv6 address in byte + * format + */ + 'ipv6'?: (boolean); + /** + * Len specifies that this field must be the specified number of bytes + */ + 'len'?: (number | string | Long); + /** + * WellKnown rules provide advanced constraints against common byte + * patterns + */ + 'well_known'?: "ip" | "ipv4" | "ipv6"; +} +/** + * BytesRules describe the constraints applied to `bytes` values + */ +export interface BytesRules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (Buffer); + /** + * MinLen specifies that this field must be the specified number of bytes + * at a minimum + */ + 'min_len': (string); + /** + * MaxLen specifies that this field must be the specified number of bytes + * at a maximum + */ + 'max_len': (string); + /** + * Pattern specifes that this field must match against the specified + * regular expression (RE2 syntax). The included expression should elide + * any delimiters. + */ + 'pattern': (string); + /** + * Prefix specifies that this field must have the specified bytes at the + * beginning of the string. + */ + 'prefix': (Buffer); + /** + * Suffix specifies that this field must have the specified bytes at the + * end of the string. + */ + 'suffix': (Buffer); + /** + * Contains specifies that this field must have the specified bytes + * anywhere in the string. + */ + 'contains': (Buffer); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (Buffer)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (Buffer)[]; + /** + * Ip specifies that the field must be a valid IP (v4 or v6) address in + * byte format + */ + 'ip'?: (boolean); + /** + * Ipv4 specifies that the field must be a valid IPv4 address in byte + * format + */ + 'ipv4'?: (boolean); + /** + * Ipv6 specifies that the field must be a valid IPv6 address in byte + * format + */ + 'ipv6'?: (boolean); + /** + * Len specifies that this field must be the specified number of bytes + */ + 'len': (string); + /** + * WellKnown rules provide advanced constraints against common byte + * patterns + */ + 'well_known'?: "ip" | "ipv4" | "ipv6"; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/BytesRules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/BytesRules.js new file mode 100644 index 0000000..a33075c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/BytesRules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=BytesRules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/BytesRules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/BytesRules.js.map new file mode 100644 index 0000000..40114fb --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/BytesRules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"BytesRules.js","sourceRoot":"","sources":["../../../../src/generated/validate/BytesRules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/DoubleRules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/DoubleRules.d.ts new file mode 100644 index 0000000..973aa44 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/DoubleRules.d.ts @@ -0,0 +1,82 @@ +/** + * DoubleRules describes the constraints applied to `double` values + */ +export interface DoubleRules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number | string); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number | string); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number | string); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number | string); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number | string); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number | string)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number | string)[]; +} +/** + * DoubleRules describes the constraints applied to `double` values + */ +export interface DoubleRules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (number)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/DoubleRules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/DoubleRules.js new file mode 100644 index 0000000..1e104ae --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/DoubleRules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=DoubleRules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/DoubleRules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/DoubleRules.js.map new file mode 100644 index 0000000..1734270 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/DoubleRules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"DoubleRules.js","sourceRoot":"","sources":["../../../../src/generated/validate/DoubleRules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/DurationRules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/DurationRules.d.ts new file mode 100644 index 0000000..c6b9351 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/DurationRules.d.ts @@ -0,0 +1,89 @@ +import type { Duration as _google_protobuf_Duration, Duration__Output as _google_protobuf_Duration__Output } from '../google/protobuf/Duration'; +/** + * DurationRules describe the constraints applied exclusively to the + * `google.protobuf.Duration` well-known type + */ +export interface DurationRules { + /** + * Required specifies that this field must be set + */ + 'required'?: (boolean); + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (_google_protobuf_Duration | null); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (_google_protobuf_Duration | null); + /** + * Lt specifies that this field must be less than the specified value, + * inclusive + */ + 'lte'?: (_google_protobuf_Duration | null); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive + */ + 'gt'?: (_google_protobuf_Duration | null); + /** + * Gte specifies that this field must be greater than the specified value, + * inclusive + */ + 'gte'?: (_google_protobuf_Duration | null); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (_google_protobuf_Duration)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (_google_protobuf_Duration)[]; +} +/** + * DurationRules describe the constraints applied exclusively to the + * `google.protobuf.Duration` well-known type + */ +export interface DurationRules__Output { + /** + * Required specifies that this field must be set + */ + 'required': (boolean); + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (_google_protobuf_Duration__Output | null); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (_google_protobuf_Duration__Output | null); + /** + * Lt specifies that this field must be less than the specified value, + * inclusive + */ + 'lte': (_google_protobuf_Duration__Output | null); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive + */ + 'gt': (_google_protobuf_Duration__Output | null); + /** + * Gte specifies that this field must be greater than the specified value, + * inclusive + */ + 'gte': (_google_protobuf_Duration__Output | null); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (_google_protobuf_Duration__Output)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (_google_protobuf_Duration__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/DurationRules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/DurationRules.js new file mode 100644 index 0000000..afd338e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/DurationRules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=DurationRules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/DurationRules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/DurationRules.js.map new file mode 100644 index 0000000..7d18655 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/DurationRules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"DurationRules.js","sourceRoot":"","sources":["../../../../src/generated/validate/DurationRules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/EnumRules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/EnumRules.d.ts new file mode 100644 index 0000000..e6750d5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/EnumRules.d.ts @@ -0,0 +1,48 @@ +/** + * EnumRules describe the constraints applied to enum values + */ +export interface EnumRules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number); + /** + * DefinedOnly specifies that this field must be only one of the defined + * values for this enum, failing on any undefined value. + */ + 'defined_only'?: (boolean); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number)[]; +} +/** + * EnumRules describe the constraints applied to enum values + */ +export interface EnumRules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (number); + /** + * DefinedOnly specifies that this field must be only one of the defined + * values for this enum, failing on any undefined value. + */ + 'defined_only': (boolean); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (number)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/EnumRules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/EnumRules.js new file mode 100644 index 0000000..7532c8e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/EnumRules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=EnumRules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/EnumRules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/EnumRules.js.map new file mode 100644 index 0000000..4af04d4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/EnumRules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"EnumRules.js","sourceRoot":"","sources":["../../../../src/generated/validate/EnumRules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/FieldRules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/FieldRules.d.ts new file mode 100644 index 0000000..26faab8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/FieldRules.d.ts @@ -0,0 +1,98 @@ +import type { FloatRules as _validate_FloatRules, FloatRules__Output as _validate_FloatRules__Output } from '../validate/FloatRules'; +import type { DoubleRules as _validate_DoubleRules, DoubleRules__Output as _validate_DoubleRules__Output } from '../validate/DoubleRules'; +import type { Int32Rules as _validate_Int32Rules, Int32Rules__Output as _validate_Int32Rules__Output } from '../validate/Int32Rules'; +import type { Int64Rules as _validate_Int64Rules, Int64Rules__Output as _validate_Int64Rules__Output } from '../validate/Int64Rules'; +import type { UInt32Rules as _validate_UInt32Rules, UInt32Rules__Output as _validate_UInt32Rules__Output } from '../validate/UInt32Rules'; +import type { UInt64Rules as _validate_UInt64Rules, UInt64Rules__Output as _validate_UInt64Rules__Output } from '../validate/UInt64Rules'; +import type { SInt32Rules as _validate_SInt32Rules, SInt32Rules__Output as _validate_SInt32Rules__Output } from '../validate/SInt32Rules'; +import type { SInt64Rules as _validate_SInt64Rules, SInt64Rules__Output as _validate_SInt64Rules__Output } from '../validate/SInt64Rules'; +import type { Fixed32Rules as _validate_Fixed32Rules, Fixed32Rules__Output as _validate_Fixed32Rules__Output } from '../validate/Fixed32Rules'; +import type { Fixed64Rules as _validate_Fixed64Rules, Fixed64Rules__Output as _validate_Fixed64Rules__Output } from '../validate/Fixed64Rules'; +import type { SFixed32Rules as _validate_SFixed32Rules, SFixed32Rules__Output as _validate_SFixed32Rules__Output } from '../validate/SFixed32Rules'; +import type { SFixed64Rules as _validate_SFixed64Rules, SFixed64Rules__Output as _validate_SFixed64Rules__Output } from '../validate/SFixed64Rules'; +import type { BoolRules as _validate_BoolRules, BoolRules__Output as _validate_BoolRules__Output } from '../validate/BoolRules'; +import type { StringRules as _validate_StringRules, StringRules__Output as _validate_StringRules__Output } from '../validate/StringRules'; +import type { BytesRules as _validate_BytesRules, BytesRules__Output as _validate_BytesRules__Output } from '../validate/BytesRules'; +import type { EnumRules as _validate_EnumRules, EnumRules__Output as _validate_EnumRules__Output } from '../validate/EnumRules'; +import type { MessageRules as _validate_MessageRules, MessageRules__Output as _validate_MessageRules__Output } from '../validate/MessageRules'; +import type { RepeatedRules as _validate_RepeatedRules, RepeatedRules__Output as _validate_RepeatedRules__Output } from '../validate/RepeatedRules'; +import type { MapRules as _validate_MapRules, MapRules__Output as _validate_MapRules__Output } from '../validate/MapRules'; +import type { AnyRules as _validate_AnyRules, AnyRules__Output as _validate_AnyRules__Output } from '../validate/AnyRules'; +import type { DurationRules as _validate_DurationRules, DurationRules__Output as _validate_DurationRules__Output } from '../validate/DurationRules'; +import type { TimestampRules as _validate_TimestampRules, TimestampRules__Output as _validate_TimestampRules__Output } from '../validate/TimestampRules'; +/** + * FieldRules encapsulates the rules for each type of field. Depending on the + * field, the correct set should be used to ensure proper validations. + */ +export interface FieldRules { + /** + * Scalar Field Types + */ + 'float'?: (_validate_FloatRules | null); + 'double'?: (_validate_DoubleRules | null); + 'int32'?: (_validate_Int32Rules | null); + 'int64'?: (_validate_Int64Rules | null); + 'uint32'?: (_validate_UInt32Rules | null); + 'uint64'?: (_validate_UInt64Rules | null); + 'sint32'?: (_validate_SInt32Rules | null); + 'sint64'?: (_validate_SInt64Rules | null); + 'fixed32'?: (_validate_Fixed32Rules | null); + 'fixed64'?: (_validate_Fixed64Rules | null); + 'sfixed32'?: (_validate_SFixed32Rules | null); + 'sfixed64'?: (_validate_SFixed64Rules | null); + 'bool'?: (_validate_BoolRules | null); + 'string'?: (_validate_StringRules | null); + 'bytes'?: (_validate_BytesRules | null); + /** + * Complex Field Types + */ + 'enum'?: (_validate_EnumRules | null); + 'message'?: (_validate_MessageRules | null); + 'repeated'?: (_validate_RepeatedRules | null); + 'map'?: (_validate_MapRules | null); + /** + * Well-Known Field Types + */ + 'any'?: (_validate_AnyRules | null); + 'duration'?: (_validate_DurationRules | null); + 'timestamp'?: (_validate_TimestampRules | null); + 'type'?: "float" | "double" | "int32" | "int64" | "uint32" | "uint64" | "sint32" | "sint64" | "fixed32" | "fixed64" | "sfixed32" | "sfixed64" | "bool" | "string" | "bytes" | "enum" | "repeated" | "map" | "any" | "duration" | "timestamp"; +} +/** + * FieldRules encapsulates the rules for each type of field. Depending on the + * field, the correct set should be used to ensure proper validations. + */ +export interface FieldRules__Output { + /** + * Scalar Field Types + */ + 'float'?: (_validate_FloatRules__Output | null); + 'double'?: (_validate_DoubleRules__Output | null); + 'int32'?: (_validate_Int32Rules__Output | null); + 'int64'?: (_validate_Int64Rules__Output | null); + 'uint32'?: (_validate_UInt32Rules__Output | null); + 'uint64'?: (_validate_UInt64Rules__Output | null); + 'sint32'?: (_validate_SInt32Rules__Output | null); + 'sint64'?: (_validate_SInt64Rules__Output | null); + 'fixed32'?: (_validate_Fixed32Rules__Output | null); + 'fixed64'?: (_validate_Fixed64Rules__Output | null); + 'sfixed32'?: (_validate_SFixed32Rules__Output | null); + 'sfixed64'?: (_validate_SFixed64Rules__Output | null); + 'bool'?: (_validate_BoolRules__Output | null); + 'string'?: (_validate_StringRules__Output | null); + 'bytes'?: (_validate_BytesRules__Output | null); + /** + * Complex Field Types + */ + 'enum'?: (_validate_EnumRules__Output | null); + 'message': (_validate_MessageRules__Output | null); + 'repeated'?: (_validate_RepeatedRules__Output | null); + 'map'?: (_validate_MapRules__Output | null); + /** + * Well-Known Field Types + */ + 'any'?: (_validate_AnyRules__Output | null); + 'duration'?: (_validate_DurationRules__Output | null); + 'timestamp'?: (_validate_TimestampRules__Output | null); + 'type'?: "float" | "double" | "int32" | "int64" | "uint32" | "uint64" | "sint32" | "sint64" | "fixed32" | "fixed64" | "sfixed32" | "sfixed64" | "bool" | "string" | "bytes" | "enum" | "repeated" | "map" | "any" | "duration" | "timestamp"; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/FieldRules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/FieldRules.js new file mode 100644 index 0000000..e6c39ec --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/FieldRules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=FieldRules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/FieldRules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/FieldRules.js.map new file mode 100644 index 0000000..8ed4b19 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/FieldRules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FieldRules.js","sourceRoot":"","sources":["../../../../src/generated/validate/FieldRules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed32Rules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed32Rules.d.ts new file mode 100644 index 0000000..688e2dd --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed32Rules.d.ts @@ -0,0 +1,82 @@ +/** + * Fixed32Rules describes the constraints applied to `fixed32` values + */ +export interface Fixed32Rules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number)[]; +} +/** + * Fixed32Rules describes the constraints applied to `fixed32` values + */ +export interface Fixed32Rules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (number)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed32Rules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed32Rules.js new file mode 100644 index 0000000..da4f301 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed32Rules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Fixed32Rules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed32Rules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed32Rules.js.map new file mode 100644 index 0000000..b2f3a5c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed32Rules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Fixed32Rules.js","sourceRoot":"","sources":["../../../../src/generated/validate/Fixed32Rules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed64Rules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed64Rules.d.ts new file mode 100644 index 0000000..6c84a9e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed64Rules.d.ts @@ -0,0 +1,83 @@ +import type { Long } from '@grpc/proto-loader'; +/** + * Fixed64Rules describes the constraints applied to `fixed64` values + */ +export interface Fixed64Rules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number | string | Long); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number | string | Long); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number | string | Long); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number | string | Long); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number | string | Long); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number | string | Long)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number | string | Long)[]; +} +/** + * Fixed64Rules describes the constraints applied to `fixed64` values + */ +export interface Fixed64Rules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (string); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (string); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (string); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (string); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (string); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (string)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (string)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed64Rules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed64Rules.js new file mode 100644 index 0000000..1b22d0c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed64Rules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Fixed64Rules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed64Rules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed64Rules.js.map new file mode 100644 index 0000000..7f93808 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/Fixed64Rules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Fixed64Rules.js","sourceRoot":"","sources":["../../../../src/generated/validate/Fixed64Rules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/FloatRules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/FloatRules.d.ts new file mode 100644 index 0000000..c1cdaaf --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/FloatRules.d.ts @@ -0,0 +1,82 @@ +/** + * FloatRules describes the constraints applied to `float` values + */ +export interface FloatRules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number | string); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number | string); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number | string); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number | string); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number | string); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number | string)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number | string)[]; +} +/** + * FloatRules describes the constraints applied to `float` values + */ +export interface FloatRules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (number)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/FloatRules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/FloatRules.js new file mode 100644 index 0000000..6402268 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/FloatRules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=FloatRules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/FloatRules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/FloatRules.js.map new file mode 100644 index 0000000..ac4ae7e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/FloatRules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FloatRules.js","sourceRoot":"","sources":["../../../../src/generated/validate/FloatRules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/Int32Rules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/Int32Rules.d.ts new file mode 100644 index 0000000..e1010fc --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/Int32Rules.d.ts @@ -0,0 +1,82 @@ +/** + * Int32Rules describes the constraints applied to `int32` values + */ +export interface Int32Rules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number)[]; +} +/** + * Int32Rules describes the constraints applied to `int32` values + */ +export interface Int32Rules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (number)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/Int32Rules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/Int32Rules.js new file mode 100644 index 0000000..69a8264 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/Int32Rules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Int32Rules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/Int32Rules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/Int32Rules.js.map new file mode 100644 index 0000000..83e7e94 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/Int32Rules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Int32Rules.js","sourceRoot":"","sources":["../../../../src/generated/validate/Int32Rules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/Int64Rules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/Int64Rules.d.ts new file mode 100644 index 0000000..423c229 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/Int64Rules.d.ts @@ -0,0 +1,83 @@ +import type { Long } from '@grpc/proto-loader'; +/** + * Int64Rules describes the constraints applied to `int64` values + */ +export interface Int64Rules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number | string | Long); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number | string | Long); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number | string | Long); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number | string | Long); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number | string | Long); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number | string | Long)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number | string | Long)[]; +} +/** + * Int64Rules describes the constraints applied to `int64` values + */ +export interface Int64Rules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (string); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (string); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (string); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (string); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (string); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (string)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (string)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/Int64Rules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/Int64Rules.js new file mode 100644 index 0000000..93797e9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/Int64Rules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Int64Rules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/Int64Rules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/Int64Rules.js.map new file mode 100644 index 0000000..5d632a3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/Int64Rules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Int64Rules.js","sourceRoot":"","sources":["../../../../src/generated/validate/Int64Rules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/KnownRegex.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/KnownRegex.d.ts new file mode 100644 index 0000000..8af850b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/KnownRegex.d.ts @@ -0,0 +1,30 @@ +/** + * WellKnownRegex contain some well-known patterns. + */ +export declare const KnownRegex: { + readonly UNKNOWN: "UNKNOWN"; + /** + * HTTP header name as defined by RFC 7230. + */ + readonly HTTP_HEADER_NAME: "HTTP_HEADER_NAME"; + /** + * HTTP header value as defined by RFC 7230. + */ + readonly HTTP_HEADER_VALUE: "HTTP_HEADER_VALUE"; +}; +/** + * WellKnownRegex contain some well-known patterns. + */ +export type KnownRegex = 'UNKNOWN' | 0 +/** + * HTTP header name as defined by RFC 7230. + */ + | 'HTTP_HEADER_NAME' | 1 +/** + * HTTP header value as defined by RFC 7230. + */ + | 'HTTP_HEADER_VALUE' | 2; +/** + * WellKnownRegex contain some well-known patterns. + */ +export type KnownRegex__Output = typeof KnownRegex[keyof typeof KnownRegex]; diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/KnownRegex.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/KnownRegex.js new file mode 100644 index 0000000..5431991 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/KnownRegex.js @@ -0,0 +1,19 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +exports.KnownRegex = void 0; +/** + * WellKnownRegex contain some well-known patterns. + */ +exports.KnownRegex = { + UNKNOWN: 'UNKNOWN', + /** + * HTTP header name as defined by RFC 7230. + */ + HTTP_HEADER_NAME: 'HTTP_HEADER_NAME', + /** + * HTTP header value as defined by RFC 7230. + */ + HTTP_HEADER_VALUE: 'HTTP_HEADER_VALUE', +}; +//# sourceMappingURL=KnownRegex.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/KnownRegex.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/KnownRegex.js.map new file mode 100644 index 0000000..b00a48f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/KnownRegex.js.map @@ -0,0 +1 @@ +{"version":3,"file":"KnownRegex.js","sourceRoot":"","sources":["../../../../src/generated/validate/KnownRegex.ts"],"names":[],"mappings":";AAAA,mEAAmE;;;AAEnE;;GAEG;AACU,QAAA,UAAU,GAAG;IACxB,OAAO,EAAE,SAAS;IAClB;;OAEG;IACH,gBAAgB,EAAE,kBAAkB;IACpC;;OAEG;IACH,iBAAiB,EAAE,mBAAmB;CAC9B,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/MapRules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/MapRules.d.ts new file mode 100644 index 0000000..d5afb2e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/MapRules.d.ts @@ -0,0 +1,62 @@ +import type { FieldRules as _validate_FieldRules, FieldRules__Output as _validate_FieldRules__Output } from '../validate/FieldRules'; +import type { Long } from '@grpc/proto-loader'; +/** + * MapRules describe the constraints applied to `map` values + */ +export interface MapRules { + /** + * MinPairs specifies that this field must have the specified number of + * KVs at a minimum + */ + 'min_pairs'?: (number | string | Long); + /** + * MaxPairs specifies that this field must have the specified number of + * KVs at a maximum + */ + 'max_pairs'?: (number | string | Long); + /** + * NoSparse specifies values in this field cannot be unset. This only + * applies to map's with message value types. + */ + 'no_sparse'?: (boolean); + /** + * Keys specifies the constraints to be applied to each key in the field. + */ + 'keys'?: (_validate_FieldRules | null); + /** + * Values specifies the constraints to be applied to the value of each key + * in the field. Message values will still have their validations evaluated + * unless skip is specified here. + */ + 'values'?: (_validate_FieldRules | null); +} +/** + * MapRules describe the constraints applied to `map` values + */ +export interface MapRules__Output { + /** + * MinPairs specifies that this field must have the specified number of + * KVs at a minimum + */ + 'min_pairs': (string); + /** + * MaxPairs specifies that this field must have the specified number of + * KVs at a maximum + */ + 'max_pairs': (string); + /** + * NoSparse specifies values in this field cannot be unset. This only + * applies to map's with message value types. + */ + 'no_sparse': (boolean); + /** + * Keys specifies the constraints to be applied to each key in the field. + */ + 'keys': (_validate_FieldRules__Output | null); + /** + * Values specifies the constraints to be applied to the value of each key + * in the field. Message values will still have their validations evaluated + * unless skip is specified here. + */ + 'values': (_validate_FieldRules__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/MapRules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/MapRules.js new file mode 100644 index 0000000..cf32fd8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/MapRules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=MapRules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/MapRules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/MapRules.js.map new file mode 100644 index 0000000..12d3ae7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/MapRules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MapRules.js","sourceRoot":"","sources":["../../../../src/generated/validate/MapRules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/MessageRules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/MessageRules.d.ts new file mode 100644 index 0000000..a8b48b9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/MessageRules.d.ts @@ -0,0 +1,30 @@ +/** + * MessageRules describe the constraints applied to embedded message values. + * For message-type fields, validation is performed recursively. + */ +export interface MessageRules { + /** + * Skip specifies that the validation rules of this field should not be + * evaluated + */ + 'skip'?: (boolean); + /** + * Required specifies that this field must be set + */ + 'required'?: (boolean); +} +/** + * MessageRules describe the constraints applied to embedded message values. + * For message-type fields, validation is performed recursively. + */ +export interface MessageRules__Output { + /** + * Skip specifies that the validation rules of this field should not be + * evaluated + */ + 'skip': (boolean); + /** + * Required specifies that this field must be set + */ + 'required': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/MessageRules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/MessageRules.js new file mode 100644 index 0000000..f54cd2f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/MessageRules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=MessageRules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/MessageRules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/MessageRules.js.map new file mode 100644 index 0000000..1e7bdba --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/MessageRules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MessageRules.js","sourceRoot":"","sources":["../../../../src/generated/validate/MessageRules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/RepeatedRules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/RepeatedRules.d.ts new file mode 100644 index 0000000..d7e7f37 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/RepeatedRules.d.ts @@ -0,0 +1,56 @@ +import type { FieldRules as _validate_FieldRules, FieldRules__Output as _validate_FieldRules__Output } from '../validate/FieldRules'; +import type { Long } from '@grpc/proto-loader'; +/** + * RepeatedRules describe the constraints applied to `repeated` values + */ +export interface RepeatedRules { + /** + * MinItems specifies that this field must have the specified number of + * items at a minimum + */ + 'min_items'?: (number | string | Long); + /** + * MaxItems specifies that this field must have the specified number of + * items at a maximum + */ + 'max_items'?: (number | string | Long); + /** + * Unique specifies that all elements in this field must be unique. This + * contraint is only applicable to scalar and enum types (messages are not + * supported). + */ + 'unique'?: (boolean); + /** + * Items specifies the contraints to be applied to each item in the field. + * Repeated message fields will still execute validation against each item + * unless skip is specified here. + */ + 'items'?: (_validate_FieldRules | null); +} +/** + * RepeatedRules describe the constraints applied to `repeated` values + */ +export interface RepeatedRules__Output { + /** + * MinItems specifies that this field must have the specified number of + * items at a minimum + */ + 'min_items': (string); + /** + * MaxItems specifies that this field must have the specified number of + * items at a maximum + */ + 'max_items': (string); + /** + * Unique specifies that all elements in this field must be unique. This + * contraint is only applicable to scalar and enum types (messages are not + * supported). + */ + 'unique': (boolean); + /** + * Items specifies the contraints to be applied to each item in the field. + * Repeated message fields will still execute validation against each item + * unless skip is specified here. + */ + 'items': (_validate_FieldRules__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/RepeatedRules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/RepeatedRules.js new file mode 100644 index 0000000..1a9bf34 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/RepeatedRules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=RepeatedRules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/RepeatedRules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/RepeatedRules.js.map new file mode 100644 index 0000000..74fbaa1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/RepeatedRules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RepeatedRules.js","sourceRoot":"","sources":["../../../../src/generated/validate/RepeatedRules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed32Rules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed32Rules.d.ts new file mode 100644 index 0000000..d2014d3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed32Rules.d.ts @@ -0,0 +1,82 @@ +/** + * SFixed32Rules describes the constraints applied to `sfixed32` values + */ +export interface SFixed32Rules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number)[]; +} +/** + * SFixed32Rules describes the constraints applied to `sfixed32` values + */ +export interface SFixed32Rules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (number)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed32Rules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed32Rules.js new file mode 100644 index 0000000..a07d027 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed32Rules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SFixed32Rules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed32Rules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed32Rules.js.map new file mode 100644 index 0000000..df8f6d0 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed32Rules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SFixed32Rules.js","sourceRoot":"","sources":["../../../../src/generated/validate/SFixed32Rules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed64Rules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed64Rules.d.ts new file mode 100644 index 0000000..fbbce08 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed64Rules.d.ts @@ -0,0 +1,83 @@ +import type { Long } from '@grpc/proto-loader'; +/** + * SFixed64Rules describes the constraints applied to `sfixed64` values + */ +export interface SFixed64Rules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number | string | Long); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number | string | Long); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number | string | Long); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number | string | Long); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number | string | Long); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number | string | Long)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number | string | Long)[]; +} +/** + * SFixed64Rules describes the constraints applied to `sfixed64` values + */ +export interface SFixed64Rules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (string); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (string); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (string); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (string); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (string); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (string)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (string)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed64Rules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed64Rules.js new file mode 100644 index 0000000..ef129da --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed64Rules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SFixed64Rules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed64Rules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed64Rules.js.map new file mode 100644 index 0000000..8c118fd --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/SFixed64Rules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SFixed64Rules.js","sourceRoot":"","sources":["../../../../src/generated/validate/SFixed64Rules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/SInt32Rules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/SInt32Rules.d.ts new file mode 100644 index 0000000..12db298 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/SInt32Rules.d.ts @@ -0,0 +1,82 @@ +/** + * SInt32Rules describes the constraints applied to `sint32` values + */ +export interface SInt32Rules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number)[]; +} +/** + * SInt32Rules describes the constraints applied to `sint32` values + */ +export interface SInt32Rules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (number)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/SInt32Rules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/SInt32Rules.js new file mode 100644 index 0000000..76f2858 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/SInt32Rules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SInt32Rules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/SInt32Rules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/SInt32Rules.js.map new file mode 100644 index 0000000..b81fc7f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/SInt32Rules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SInt32Rules.js","sourceRoot":"","sources":["../../../../src/generated/validate/SInt32Rules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/SInt64Rules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/SInt64Rules.d.ts new file mode 100644 index 0000000..90203d9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/SInt64Rules.d.ts @@ -0,0 +1,83 @@ +import type { Long } from '@grpc/proto-loader'; +/** + * SInt64Rules describes the constraints applied to `sint64` values + */ +export interface SInt64Rules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number | string | Long); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number | string | Long); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number | string | Long); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number | string | Long); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number | string | Long); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number | string | Long)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number | string | Long)[]; +} +/** + * SInt64Rules describes the constraints applied to `sint64` values + */ +export interface SInt64Rules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (string); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (string); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (string); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (string); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (string); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (string)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (string)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/SInt64Rules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/SInt64Rules.js new file mode 100644 index 0000000..0c5c333 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/SInt64Rules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SInt64Rules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/SInt64Rules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/SInt64Rules.js.map new file mode 100644 index 0000000..9641f9e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/SInt64Rules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SInt64Rules.js","sourceRoot":"","sources":["../../../../src/generated/validate/SInt64Rules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/StringRules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/StringRules.d.ts new file mode 100644 index 0000000..cef14ce --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/StringRules.d.ts @@ -0,0 +1,284 @@ +import type { KnownRegex as _validate_KnownRegex, KnownRegex__Output as _validate_KnownRegex__Output } from '../validate/KnownRegex'; +import type { Long } from '@grpc/proto-loader'; +/** + * StringRules describe the constraints applied to `string` values + */ +export interface StringRules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (string); + /** + * MinLen specifies that this field must be the specified number of + * characters (Unicode code points) at a minimum. Note that the number of + * characters may differ from the number of bytes in the string. + */ + 'min_len'?: (number | string | Long); + /** + * MaxLen specifies that this field must be the specified number of + * characters (Unicode code points) at a maximum. Note that the number of + * characters may differ from the number of bytes in the string. + */ + 'max_len'?: (number | string | Long); + /** + * MinBytes specifies that this field must be the specified number of bytes + * at a minimum + */ + 'min_bytes'?: (number | string | Long); + /** + * MaxBytes specifies that this field must be the specified number of bytes + * at a maximum + */ + 'max_bytes'?: (number | string | Long); + /** + * Pattern specifes that this field must match against the specified + * regular expression (RE2 syntax). The included expression should elide + * any delimiters. + */ + 'pattern'?: (string); + /** + * Prefix specifies that this field must have the specified substring at + * the beginning of the string. + */ + 'prefix'?: (string); + /** + * Suffix specifies that this field must have the specified substring at + * the end of the string. + */ + 'suffix'?: (string); + /** + * Contains specifies that this field must have the specified substring + * anywhere in the string. + */ + 'contains'?: (string); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (string)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (string)[]; + /** + * Email specifies that the field must be a valid email address as + * defined by RFC 5322 + */ + 'email'?: (boolean); + /** + * Hostname specifies that the field must be a valid hostname as + * defined by RFC 1034. This constraint does not support + * internationalized domain names (IDNs). + */ + 'hostname'?: (boolean); + /** + * Ip specifies that the field must be a valid IP (v4 or v6) address. + * Valid IPv6 addresses should not include surrounding square brackets. + */ + 'ip'?: (boolean); + /** + * Ipv4 specifies that the field must be a valid IPv4 address. + */ + 'ipv4'?: (boolean); + /** + * Ipv6 specifies that the field must be a valid IPv6 address. Valid + * IPv6 addresses should not include surrounding square brackets. + */ + 'ipv6'?: (boolean); + /** + * Uri specifies that the field must be a valid, absolute URI as defined + * by RFC 3986 + */ + 'uri'?: (boolean); + /** + * UriRef specifies that the field must be a valid URI as defined by RFC + * 3986 and may be relative or absolute. + */ + 'uri_ref'?: (boolean); + /** + * Len specifies that this field must be the specified number of + * characters (Unicode code points). Note that the number of + * characters may differ from the number of bytes in the string. + */ + 'len'?: (number | string | Long); + /** + * LenBytes specifies that this field must be the specified number of bytes + * at a minimum + */ + 'len_bytes'?: (number | string | Long); + /** + * Address specifies that the field must be either a valid hostname as + * defined by RFC 1034 (which does not support internationalized domain + * names or IDNs), or it can be a valid IP (v4 or v6). + */ + 'address'?: (boolean); + /** + * Uuid specifies that the field must be a valid UUID as defined by + * RFC 4122 + */ + 'uuid'?: (boolean); + /** + * NotContains specifies that this field cannot have the specified substring + * anywhere in the string. + */ + 'not_contains'?: (string); + /** + * WellKnownRegex specifies a common well known pattern defined as a regex. + */ + 'well_known_regex'?: (_validate_KnownRegex); + /** + * This applies to regexes HTTP_HEADER_NAME and HTTP_HEADER_VALUE to enable + * strict header validation. + * By default, this is true, and HTTP header validations are RFC-compliant. + * Setting to false will enable a looser validations that only disallows + * \r\n\0 characters, which can be used to bypass header matching rules. + */ + 'strict'?: (boolean); + /** + * WellKnown rules provide advanced constraints against common string + * patterns + */ + 'well_known'?: "email" | "hostname" | "ip" | "ipv4" | "ipv6" | "uri" | "uri_ref" | "address" | "uuid" | "well_known_regex"; +} +/** + * StringRules describe the constraints applied to `string` values + */ +export interface StringRules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (string); + /** + * MinLen specifies that this field must be the specified number of + * characters (Unicode code points) at a minimum. Note that the number of + * characters may differ from the number of bytes in the string. + */ + 'min_len': (string); + /** + * MaxLen specifies that this field must be the specified number of + * characters (Unicode code points) at a maximum. Note that the number of + * characters may differ from the number of bytes in the string. + */ + 'max_len': (string); + /** + * MinBytes specifies that this field must be the specified number of bytes + * at a minimum + */ + 'min_bytes': (string); + /** + * MaxBytes specifies that this field must be the specified number of bytes + * at a maximum + */ + 'max_bytes': (string); + /** + * Pattern specifes that this field must match against the specified + * regular expression (RE2 syntax). The included expression should elide + * any delimiters. + */ + 'pattern': (string); + /** + * Prefix specifies that this field must have the specified substring at + * the beginning of the string. + */ + 'prefix': (string); + /** + * Suffix specifies that this field must have the specified substring at + * the end of the string. + */ + 'suffix': (string); + /** + * Contains specifies that this field must have the specified substring + * anywhere in the string. + */ + 'contains': (string); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (string)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (string)[]; + /** + * Email specifies that the field must be a valid email address as + * defined by RFC 5322 + */ + 'email'?: (boolean); + /** + * Hostname specifies that the field must be a valid hostname as + * defined by RFC 1034. This constraint does not support + * internationalized domain names (IDNs). + */ + 'hostname'?: (boolean); + /** + * Ip specifies that the field must be a valid IP (v4 or v6) address. + * Valid IPv6 addresses should not include surrounding square brackets. + */ + 'ip'?: (boolean); + /** + * Ipv4 specifies that the field must be a valid IPv4 address. + */ + 'ipv4'?: (boolean); + /** + * Ipv6 specifies that the field must be a valid IPv6 address. Valid + * IPv6 addresses should not include surrounding square brackets. + */ + 'ipv6'?: (boolean); + /** + * Uri specifies that the field must be a valid, absolute URI as defined + * by RFC 3986 + */ + 'uri'?: (boolean); + /** + * UriRef specifies that the field must be a valid URI as defined by RFC + * 3986 and may be relative or absolute. + */ + 'uri_ref'?: (boolean); + /** + * Len specifies that this field must be the specified number of + * characters (Unicode code points). Note that the number of + * characters may differ from the number of bytes in the string. + */ + 'len': (string); + /** + * LenBytes specifies that this field must be the specified number of bytes + * at a minimum + */ + 'len_bytes': (string); + /** + * Address specifies that the field must be either a valid hostname as + * defined by RFC 1034 (which does not support internationalized domain + * names or IDNs), or it can be a valid IP (v4 or v6). + */ + 'address'?: (boolean); + /** + * Uuid specifies that the field must be a valid UUID as defined by + * RFC 4122 + */ + 'uuid'?: (boolean); + /** + * NotContains specifies that this field cannot have the specified substring + * anywhere in the string. + */ + 'not_contains': (string); + /** + * WellKnownRegex specifies a common well known pattern defined as a regex. + */ + 'well_known_regex'?: (_validate_KnownRegex__Output); + /** + * This applies to regexes HTTP_HEADER_NAME and HTTP_HEADER_VALUE to enable + * strict header validation. + * By default, this is true, and HTTP header validations are RFC-compliant. + * Setting to false will enable a looser validations that only disallows + * \r\n\0 characters, which can be used to bypass header matching rules. + */ + 'strict': (boolean); + /** + * WellKnown rules provide advanced constraints against common string + * patterns + */ + 'well_known'?: "email" | "hostname" | "ip" | "ipv4" | "ipv6" | "uri" | "uri_ref" | "address" | "uuid" | "well_known_regex"; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/StringRules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/StringRules.js new file mode 100644 index 0000000..0a64d7b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/StringRules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=StringRules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/StringRules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/StringRules.js.map new file mode 100644 index 0000000..5d1e033 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/StringRules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"StringRules.js","sourceRoot":"","sources":["../../../../src/generated/validate/StringRules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/TimestampRules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/TimestampRules.d.ts new file mode 100644 index 0000000..6919a4a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/TimestampRules.d.ts @@ -0,0 +1,102 @@ +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../google/protobuf/Timestamp'; +import type { Duration as _google_protobuf_Duration, Duration__Output as _google_protobuf_Duration__Output } from '../google/protobuf/Duration'; +/** + * TimestampRules describe the constraints applied exclusively to the + * `google.protobuf.Timestamp` well-known type + */ +export interface TimestampRules { + /** + * Required specifies that this field must be set + */ + 'required'?: (boolean); + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (_google_protobuf_Timestamp | null); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (_google_protobuf_Timestamp | null); + /** + * Lte specifies that this field must be less than the specified value, + * inclusive + */ + 'lte'?: (_google_protobuf_Timestamp | null); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive + */ + 'gt'?: (_google_protobuf_Timestamp | null); + /** + * Gte specifies that this field must be greater than the specified value, + * inclusive + */ + 'gte'?: (_google_protobuf_Timestamp | null); + /** + * LtNow specifies that this must be less than the current time. LtNow + * can only be used with the Within rule. + */ + 'lt_now'?: (boolean); + /** + * GtNow specifies that this must be greater than the current time. GtNow + * can only be used with the Within rule. + */ + 'gt_now'?: (boolean); + /** + * Within specifies that this field must be within this duration of the + * current time. This constraint can be used alone or with the LtNow and + * GtNow rules. + */ + 'within'?: (_google_protobuf_Duration | null); +} +/** + * TimestampRules describe the constraints applied exclusively to the + * `google.protobuf.Timestamp` well-known type + */ +export interface TimestampRules__Output { + /** + * Required specifies that this field must be set + */ + 'required': (boolean); + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (_google_protobuf_Timestamp__Output | null); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (_google_protobuf_Timestamp__Output | null); + /** + * Lte specifies that this field must be less than the specified value, + * inclusive + */ + 'lte': (_google_protobuf_Timestamp__Output | null); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive + */ + 'gt': (_google_protobuf_Timestamp__Output | null); + /** + * Gte specifies that this field must be greater than the specified value, + * inclusive + */ + 'gte': (_google_protobuf_Timestamp__Output | null); + /** + * LtNow specifies that this must be less than the current time. LtNow + * can only be used with the Within rule. + */ + 'lt_now': (boolean); + /** + * GtNow specifies that this must be greater than the current time. GtNow + * can only be used with the Within rule. + */ + 'gt_now': (boolean); + /** + * Within specifies that this field must be within this duration of the + * current time. This constraint can be used alone or with the LtNow and + * GtNow rules. + */ + 'within': (_google_protobuf_Duration__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/TimestampRules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/TimestampRules.js new file mode 100644 index 0000000..4668d53 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/TimestampRules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=TimestampRules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/TimestampRules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/TimestampRules.js.map new file mode 100644 index 0000000..f06278f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/TimestampRules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"TimestampRules.js","sourceRoot":"","sources":["../../../../src/generated/validate/TimestampRules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/UInt32Rules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/UInt32Rules.d.ts new file mode 100644 index 0000000..68d6d77 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/UInt32Rules.d.ts @@ -0,0 +1,82 @@ +/** + * UInt32Rules describes the constraints applied to `uint32` values + */ +export interface UInt32Rules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number)[]; +} +/** + * UInt32Rules describes the constraints applied to `uint32` values + */ +export interface UInt32Rules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (number)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/UInt32Rules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/UInt32Rules.js new file mode 100644 index 0000000..a447f24 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/UInt32Rules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=UInt32Rules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/UInt32Rules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/UInt32Rules.js.map new file mode 100644 index 0000000..5bbb825 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/UInt32Rules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"UInt32Rules.js","sourceRoot":"","sources":["../../../../src/generated/validate/UInt32Rules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/UInt64Rules.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/validate/UInt64Rules.d.ts new file mode 100644 index 0000000..c0da066 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/UInt64Rules.d.ts @@ -0,0 +1,83 @@ +import type { Long } from '@grpc/proto-loader'; +/** + * UInt64Rules describes the constraints applied to `uint64` values + */ +export interface UInt64Rules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number | string | Long); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number | string | Long); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number | string | Long); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number | string | Long); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number | string | Long); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number | string | Long)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number | string | Long)[]; +} +/** + * UInt64Rules describes the constraints applied to `uint64` values + */ +export interface UInt64Rules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (string); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (string); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (string); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (string); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (string); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (string)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (string)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/UInt64Rules.js b/node_modules/@grpc/grpc-js/build/src/generated/validate/UInt64Rules.js new file mode 100644 index 0000000..381e3e1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/UInt64Rules.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/protoc-gen-validate/validate/validate.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=UInt64Rules.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/validate/UInt64Rules.js.map b/node_modules/@grpc/grpc-js/build/src/generated/validate/UInt64Rules.js.map new file mode 100644 index 0000000..ee77fc4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/validate/UInt64Rules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"UInt64Rules.js","sourceRoot":"","sources":["../../../../src/generated/validate/UInt64Rules.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/xds/data/orca/v3/OrcaLoadReport.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/xds/data/orca/v3/OrcaLoadReport.d.ts new file mode 100644 index 0000000..758a270 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/xds/data/orca/v3/OrcaLoadReport.d.ts @@ -0,0 +1,121 @@ +import type { Long } from '@grpc/proto-loader'; +export interface OrcaLoadReport { + /** + * CPU utilization expressed as a fraction of available CPU resources. This + * should be derived from the latest sample or measurement. The value may be + * larger than 1.0 when the usage exceeds the reporter dependent notion of + * soft limits. + */ + 'cpu_utilization'?: (number | string); + /** + * Memory utilization expressed as a fraction of available memory + * resources. This should be derived from the latest sample or measurement. + */ + 'mem_utilization'?: (number | string); + /** + * Total RPS being served by an endpoint. This should cover all services that an endpoint is + * responsible for. + * Deprecated -- use ``rps_fractional`` field instead. + * @deprecated + */ + 'rps'?: (number | string | Long); + /** + * Application specific requests costs. Each value is an absolute cost (e.g. 3487 bytes of + * storage) associated with the request. + */ + 'request_cost'?: ({ + [key: string]: number | string; + }); + /** + * Resource utilization values. Each value is expressed as a fraction of total resources + * available, derived from the latest sample or measurement. + */ + 'utilization'?: ({ + [key: string]: number | string; + }); + /** + * Total RPS being served by an endpoint. This should cover all services that an endpoint is + * responsible for. + */ + 'rps_fractional'?: (number | string); + /** + * Total EPS (errors/second) being served by an endpoint. This should cover + * all services that an endpoint is responsible for. + */ + 'eps'?: (number | string); + /** + * Application specific opaque metrics. + */ + 'named_metrics'?: ({ + [key: string]: number | string; + }); + /** + * Application specific utilization expressed as a fraction of available + * resources. For example, an application may report the max of CPU and memory + * utilization for better load balancing if it is both CPU and memory bound. + * This should be derived from the latest sample or measurement. + * The value may be larger than 1.0 when the usage exceeds the reporter + * dependent notion of soft limits. + */ + 'application_utilization'?: (number | string); +} +export interface OrcaLoadReport__Output { + /** + * CPU utilization expressed as a fraction of available CPU resources. This + * should be derived from the latest sample or measurement. The value may be + * larger than 1.0 when the usage exceeds the reporter dependent notion of + * soft limits. + */ + 'cpu_utilization': (number); + /** + * Memory utilization expressed as a fraction of available memory + * resources. This should be derived from the latest sample or measurement. + */ + 'mem_utilization': (number); + /** + * Total RPS being served by an endpoint. This should cover all services that an endpoint is + * responsible for. + * Deprecated -- use ``rps_fractional`` field instead. + * @deprecated + */ + 'rps': (string); + /** + * Application specific requests costs. Each value is an absolute cost (e.g. 3487 bytes of + * storage) associated with the request. + */ + 'request_cost': ({ + [key: string]: number; + }); + /** + * Resource utilization values. Each value is expressed as a fraction of total resources + * available, derived from the latest sample or measurement. + */ + 'utilization': ({ + [key: string]: number; + }); + /** + * Total RPS being served by an endpoint. This should cover all services that an endpoint is + * responsible for. + */ + 'rps_fractional': (number); + /** + * Total EPS (errors/second) being served by an endpoint. This should cover + * all services that an endpoint is responsible for. + */ + 'eps': (number); + /** + * Application specific opaque metrics. + */ + 'named_metrics': ({ + [key: string]: number; + }); + /** + * Application specific utilization expressed as a fraction of available + * resources. For example, an application may report the max of CPU and memory + * utilization for better load balancing if it is both CPU and memory bound. + * This should be derived from the latest sample or measurement. + * The value may be larger than 1.0 when the usage exceeds the reporter + * dependent notion of soft limits. + */ + 'application_utilization': (number); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/xds/data/orca/v3/OrcaLoadReport.js b/node_modules/@grpc/grpc-js/build/src/generated/xds/data/orca/v3/OrcaLoadReport.js new file mode 100644 index 0000000..ca275f3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/xds/data/orca/v3/OrcaLoadReport.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/xds/xds/data/orca/v3/orca_load_report.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=OrcaLoadReport.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/xds/data/orca/v3/OrcaLoadReport.js.map b/node_modules/@grpc/grpc-js/build/src/generated/xds/data/orca/v3/OrcaLoadReport.js.map new file mode 100644 index 0000000..619fad8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/xds/data/orca/v3/OrcaLoadReport.js.map @@ -0,0 +1 @@ +{"version":3,"file":"OrcaLoadReport.js","sourceRoot":"","sources":["../../../../../../../src/generated/xds/data/orca/v3/OrcaLoadReport.ts"],"names":[],"mappings":";AAAA,mEAAmE"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OpenRcaService.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OpenRcaService.d.ts new file mode 100644 index 0000000..0d3fd0b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OpenRcaService.d.ts @@ -0,0 +1,36 @@ +import type * as grpc from '../../../../../index'; +import type { MethodDefinition } from '@grpc/proto-loader'; +import type { OrcaLoadReport as _xds_data_orca_v3_OrcaLoadReport, OrcaLoadReport__Output as _xds_data_orca_v3_OrcaLoadReport__Output } from '../../../../xds/data/orca/v3/OrcaLoadReport'; +import type { OrcaLoadReportRequest as _xds_service_orca_v3_OrcaLoadReportRequest, OrcaLoadReportRequest__Output as _xds_service_orca_v3_OrcaLoadReportRequest__Output } from '../../../../xds/service/orca/v3/OrcaLoadReportRequest'; +/** + * Out-of-band (OOB) load reporting service for the additional load reporting + * agent that does not sit in the request path. Reports are periodically sampled + * with sufficient frequency to provide temporal association with requests. + * OOB reporting compensates the limitation of in-band reporting in revealing + * costs for backends that do not provide a steady stream of telemetry such as + * long running stream operations and zero QPS services. This is a server + * streaming service, client needs to terminate current RPC and initiate + * a new call to change backend reporting frequency. + */ +export interface OpenRcaServiceClient extends grpc.Client { + StreamCoreMetrics(argument: _xds_service_orca_v3_OrcaLoadReportRequest, metadata: grpc.Metadata, options?: grpc.CallOptions): grpc.ClientReadableStream<_xds_data_orca_v3_OrcaLoadReport__Output>; + StreamCoreMetrics(argument: _xds_service_orca_v3_OrcaLoadReportRequest, options?: grpc.CallOptions): grpc.ClientReadableStream<_xds_data_orca_v3_OrcaLoadReport__Output>; + streamCoreMetrics(argument: _xds_service_orca_v3_OrcaLoadReportRequest, metadata: grpc.Metadata, options?: grpc.CallOptions): grpc.ClientReadableStream<_xds_data_orca_v3_OrcaLoadReport__Output>; + streamCoreMetrics(argument: _xds_service_orca_v3_OrcaLoadReportRequest, options?: grpc.CallOptions): grpc.ClientReadableStream<_xds_data_orca_v3_OrcaLoadReport__Output>; +} +/** + * Out-of-band (OOB) load reporting service for the additional load reporting + * agent that does not sit in the request path. Reports are periodically sampled + * with sufficient frequency to provide temporal association with requests. + * OOB reporting compensates the limitation of in-band reporting in revealing + * costs for backends that do not provide a steady stream of telemetry such as + * long running stream operations and zero QPS services. This is a server + * streaming service, client needs to terminate current RPC and initiate + * a new call to change backend reporting frequency. + */ +export interface OpenRcaServiceHandlers extends grpc.UntypedServiceImplementation { + StreamCoreMetrics: grpc.handleServerStreamingCall<_xds_service_orca_v3_OrcaLoadReportRequest__Output, _xds_data_orca_v3_OrcaLoadReport>; +} +export interface OpenRcaServiceDefinition extends grpc.ServiceDefinition { + StreamCoreMetrics: MethodDefinition<_xds_service_orca_v3_OrcaLoadReportRequest, _xds_data_orca_v3_OrcaLoadReport, _xds_service_orca_v3_OrcaLoadReportRequest__Output, _xds_data_orca_v3_OrcaLoadReport__Output>; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OpenRcaService.js b/node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OpenRcaService.js new file mode 100644 index 0000000..fea4f9e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OpenRcaService.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/xds/xds/service/orca/v3/orca.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=OpenRcaService.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OpenRcaService.js.map b/node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OpenRcaService.js.map new file mode 100644 index 0000000..d5c32c8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OpenRcaService.js.map @@ -0,0 +1 @@ +{"version":3,"file":"OpenRcaService.js","sourceRoot":"","sources":["../../../../../../../src/generated/xds/service/orca/v3/OpenRcaService.ts"],"names":[],"mappings":";AAAA,0DAA0D"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OrcaLoadReportRequest.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OrcaLoadReportRequest.d.ts new file mode 100644 index 0000000..2c83eff --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OrcaLoadReportRequest.d.ts @@ -0,0 +1,25 @@ +import type { Duration as _google_protobuf_Duration, Duration__Output as _google_protobuf_Duration__Output } from '../../../../google/protobuf/Duration'; +export interface OrcaLoadReportRequest { + /** + * Interval for generating Open RCA core metric responses. + */ + 'report_interval'?: (_google_protobuf_Duration | null); + /** + * Request costs to collect. If this is empty, all known requests costs tracked by + * the load reporting agent will be returned. This provides an opportunity for + * the client to selectively obtain a subset of tracked costs. + */ + 'request_cost_names'?: (string)[]; +} +export interface OrcaLoadReportRequest__Output { + /** + * Interval for generating Open RCA core metric responses. + */ + 'report_interval': (_google_protobuf_Duration__Output | null); + /** + * Request costs to collect. If this is empty, all known requests costs tracked by + * the load reporting agent will be returned. This provides an opportunity for + * the client to selectively obtain a subset of tracked costs. + */ + 'request_cost_names': (string)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OrcaLoadReportRequest.js b/node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OrcaLoadReportRequest.js new file mode 100644 index 0000000..bd89fd0 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OrcaLoadReportRequest.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/xds/xds/service/orca/v3/orca.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=OrcaLoadReportRequest.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OrcaLoadReportRequest.js.map b/node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OrcaLoadReportRequest.js.map new file mode 100644 index 0000000..b7b7862 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/xds/service/orca/v3/OrcaLoadReportRequest.js.map @@ -0,0 +1 @@ +{"version":3,"file":"OrcaLoadReportRequest.js","sourceRoot":"","sources":["../../../../../../../src/generated/xds/service/orca/v3/OrcaLoadReportRequest.ts"],"names":[],"mappings":";AAAA,0DAA0D"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/http_proxy.d.ts b/node_modules/@grpc/grpc-js/build/src/http_proxy.d.ts new file mode 100644 index 0000000..29a97a4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/http_proxy.d.ts @@ -0,0 +1,16 @@ +import { Socket } from 'net'; +import { SubchannelAddress } from './subchannel-address'; +import { ChannelOptions } from './channel-options'; +import { GrpcUri } from './uri-parser'; +interface CIDRNotation { + ip: number; + prefixLength: number; +} +export declare function parseCIDR(cidrString: string): CIDRNotation | null; +export interface ProxyMapResult { + target: GrpcUri; + extraOptions: ChannelOptions; +} +export declare function mapProxyName(target: GrpcUri, options: ChannelOptions): ProxyMapResult; +export declare function getProxiedConnection(address: SubchannelAddress, channelOptions: ChannelOptions): Promise; +export {}; diff --git a/node_modules/@grpc/grpc-js/build/src/http_proxy.js b/node_modules/@grpc/grpc-js/build/src/http_proxy.js new file mode 100644 index 0000000..114017c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/http_proxy.js @@ -0,0 +1,274 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseCIDR = parseCIDR; +exports.mapProxyName = mapProxyName; +exports.getProxiedConnection = getProxiedConnection; +const logging_1 = require("./logging"); +const constants_1 = require("./constants"); +const net_1 = require("net"); +const http = require("http"); +const logging = require("./logging"); +const subchannel_address_1 = require("./subchannel-address"); +const uri_parser_1 = require("./uri-parser"); +const url_1 = require("url"); +const resolver_dns_1 = require("./resolver-dns"); +const TRACER_NAME = 'proxy'; +function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); +} +function getProxyInfo() { + let proxyEnv = ''; + let envVar = ''; + /* Prefer using 'grpc_proxy'. Fallback on 'http_proxy' if it is not set. + * Also prefer using 'https_proxy' with fallback on 'http_proxy'. The + * fallback behavior can be removed if there's a demand for it. + */ + if (process.env.grpc_proxy) { + envVar = 'grpc_proxy'; + proxyEnv = process.env.grpc_proxy; + } + else if (process.env.https_proxy) { + envVar = 'https_proxy'; + proxyEnv = process.env.https_proxy; + } + else if (process.env.http_proxy) { + envVar = 'http_proxy'; + proxyEnv = process.env.http_proxy; + } + else { + return {}; + } + let proxyUrl; + try { + proxyUrl = new url_1.URL(proxyEnv); + } + catch (e) { + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, `cannot parse value of "${envVar}" env var`); + return {}; + } + if (proxyUrl.protocol !== 'http:') { + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, `"${proxyUrl.protocol}" scheme not supported in proxy URI`); + return {}; + } + let userCred = null; + if (proxyUrl.username) { + if (proxyUrl.password) { + (0, logging_1.log)(constants_1.LogVerbosity.INFO, 'userinfo found in proxy URI'); + userCred = decodeURIComponent(`${proxyUrl.username}:${proxyUrl.password}`); + } + else { + userCred = proxyUrl.username; + } + } + const hostname = proxyUrl.hostname; + let port = proxyUrl.port; + /* The proxy URL uses the scheme "http:", which has a default port number of + * 80. We need to set that explicitly here if it is omitted because otherwise + * it will use gRPC's default port 443. */ + if (port === '') { + port = '80'; + } + const result = { + address: `${hostname}:${port}`, + }; + if (userCred) { + result.creds = userCred; + } + trace('Proxy server ' + result.address + ' set by environment variable ' + envVar); + return result; +} +function getNoProxyHostList() { + /* Prefer using 'no_grpc_proxy'. Fallback on 'no_proxy' if it is not set. */ + let noProxyStr = process.env.no_grpc_proxy; + let envVar = 'no_grpc_proxy'; + if (!noProxyStr) { + noProxyStr = process.env.no_proxy; + envVar = 'no_proxy'; + } + if (noProxyStr) { + trace('No proxy server list set by environment variable ' + envVar); + return noProxyStr.split(','); + } + else { + return []; + } +} +/* + * The groups correspond to CIDR parts as follows: + * 1. ip + * 2. prefixLength + */ +function parseCIDR(cidrString) { + const splitRange = cidrString.split('/'); + if (splitRange.length !== 2) { + return null; + } + const prefixLength = parseInt(splitRange[1], 10); + if (!(0, net_1.isIPv4)(splitRange[0]) || Number.isNaN(prefixLength) || prefixLength < 0 || prefixLength > 32) { + return null; + } + return { + ip: ipToInt(splitRange[0]), + prefixLength: prefixLength + }; +} +function ipToInt(ip) { + return ip.split(".").reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0); +} +function isIpInCIDR(cidr, serverHost) { + const ip = cidr.ip; + const mask = -1 << (32 - cidr.prefixLength); + const hostIP = ipToInt(serverHost); + return (hostIP & mask) === (ip & mask); +} +function hostMatchesNoProxyList(serverHost) { + for (const host of getNoProxyHostList()) { + const parsedCIDR = parseCIDR(host); + // host is a CIDR and serverHost is an IP address + if ((0, net_1.isIPv4)(serverHost) && parsedCIDR && isIpInCIDR(parsedCIDR, serverHost)) { + return true; + } + else if (serverHost.endsWith(host)) { + // host is a single IP or a domain name suffix + return true; + } + } + return false; +} +function mapProxyName(target, options) { + var _a; + const noProxyResult = { + target: target, + extraOptions: {}, + }; + if (((_a = options['grpc.enable_http_proxy']) !== null && _a !== void 0 ? _a : 1) === 0) { + return noProxyResult; + } + if (target.scheme === 'unix') { + return noProxyResult; + } + const proxyInfo = getProxyInfo(); + if (!proxyInfo.address) { + return noProxyResult; + } + const hostPort = (0, uri_parser_1.splitHostPort)(target.path); + if (!hostPort) { + return noProxyResult; + } + const serverHost = hostPort.host; + if (hostMatchesNoProxyList(serverHost)) { + trace('Not using proxy for target in no_proxy list: ' + (0, uri_parser_1.uriToString)(target)); + return noProxyResult; + } + const extraOptions = { + 'grpc.http_connect_target': (0, uri_parser_1.uriToString)(target), + }; + if (proxyInfo.creds) { + extraOptions['grpc.http_connect_creds'] = proxyInfo.creds; + } + return { + target: { + scheme: 'dns', + path: proxyInfo.address, + }, + extraOptions: extraOptions, + }; +} +function getProxiedConnection(address, channelOptions) { + var _a; + if (!('grpc.http_connect_target' in channelOptions)) { + return Promise.resolve(null); + } + const realTarget = channelOptions['grpc.http_connect_target']; + const parsedTarget = (0, uri_parser_1.parseUri)(realTarget); + if (parsedTarget === null) { + return Promise.resolve(null); + } + const splitHostPost = (0, uri_parser_1.splitHostPort)(parsedTarget.path); + if (splitHostPost === null) { + return Promise.resolve(null); + } + const hostPort = `${splitHostPost.host}:${(_a = splitHostPost.port) !== null && _a !== void 0 ? _a : resolver_dns_1.DEFAULT_PORT}`; + const options = { + method: 'CONNECT', + path: hostPort, + }; + const headers = { + Host: hostPort, + }; + // Connect to the subchannel address as a proxy + if ((0, subchannel_address_1.isTcpSubchannelAddress)(address)) { + options.host = address.host; + options.port = address.port; + } + else { + options.socketPath = address.path; + } + if ('grpc.http_connect_creds' in channelOptions) { + headers['Proxy-Authorization'] = + 'Basic ' + + Buffer.from(channelOptions['grpc.http_connect_creds']).toString('base64'); + } + options.headers = headers; + const proxyAddressString = (0, subchannel_address_1.subchannelAddressToString)(address); + trace('Using proxy ' + proxyAddressString + ' to connect to ' + options.path); + return new Promise((resolve, reject) => { + const request = http.request(options); + request.once('connect', (res, socket, head) => { + request.removeAllListeners(); + socket.removeAllListeners(); + if (res.statusCode === 200) { + trace('Successfully connected to ' + + options.path + + ' through proxy ' + + proxyAddressString); + // The HTTP client may have already read a few bytes of the proxied + // connection. If that's the case, put them back into the socket. + // See https://github.com/grpc/grpc-node/issues/2744. + if (head.length > 0) { + socket.unshift(head); + } + trace('Successfully established a plaintext connection to ' + + options.path + + ' through proxy ' + + proxyAddressString); + resolve(socket); + } + else { + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, 'Failed to connect to ' + + options.path + + ' through proxy ' + + proxyAddressString + + ' with status ' + + res.statusCode); + reject(); + } + }); + request.once('error', err => { + request.removeAllListeners(); + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, 'Failed to connect to proxy ' + + proxyAddressString + + ' with error ' + + err.message); + reject(); + }); + request.end(); + }); +} +//# sourceMappingURL=http_proxy.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/http_proxy.js.map b/node_modules/@grpc/grpc-js/build/src/http_proxy.js.map new file mode 100644 index 0000000..85e768c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/http_proxy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"http_proxy.js","sourceRoot":"","sources":["../../src/http_proxy.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAqHH,8BAaC;AAiCD,oCAwCC;AAED,oDA8FC;AAzSD,uCAAgC;AAChC,2CAA2C;AAC3C,6BAAqC;AACrC,6BAA6B;AAC7B,qCAAqC;AACrC,6DAI8B;AAE9B,6CAA6E;AAC7E,6BAA0B;AAC1B,iDAA8C;AAE9C,MAAM,WAAW,GAAG,OAAO,CAAC;AAE5B,SAAS,KAAK,CAAC,IAAY;IACzB,OAAO,CAAC,KAAK,CAAC,wBAAY,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;AACvD,CAAC;AAOD,SAAS,YAAY;IACnB,IAAI,QAAQ,GAAG,EAAE,CAAC;IAClB,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB;;;OAGG;IACH,IAAI,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,CAAC;QAC3B,MAAM,GAAG,YAAY,CAAC;QACtB,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC;IACpC,CAAC;SAAM,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,EAAE,CAAC;QACnC,MAAM,GAAG,aAAa,CAAC;QACvB,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC;IACrC,CAAC;SAAM,IAAI,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,CAAC;QAClC,MAAM,GAAG,YAAY,CAAC;QACtB,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC;IACpC,CAAC;SAAM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ACd,CAAC;YACF,MAAM,EAAE,CAAC;QACX,CAAC,CAAC,CAAC;QACH,OAAO,CAAC,GAAG,EAAE,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/index.d.ts b/node_modules/@grpc/grpc-js/build/src/index.d.ts new file mode 100644 index 0000000..5e959ef --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/index.d.ts @@ -0,0 +1,79 @@ +import { ClientDuplexStream, ClientReadableStream, ClientUnaryCall, ClientWritableStream, ServiceError } from './call'; +import { CallCredentials, OAuth2Client } from './call-credentials'; +import { StatusObject } from './call-interface'; +import { Channel, ChannelImplementation } from './channel'; +import { CompressionAlgorithms } from './compression-algorithms'; +import { ConnectivityState } from './connectivity-state'; +import { ChannelCredentials, VerifyOptions } from './channel-credentials'; +import { CallOptions, Client, ClientOptions, CallInvocationTransformer, CallProperties, UnaryCallback } from './client'; +import { LogVerbosity, Status, Propagate } from './constants'; +import { Deserialize, loadPackageDefinition, makeClientConstructor, MethodDefinition, Serialize, ServerMethodDefinition, ServiceDefinition } from './make-client'; +import { Metadata, MetadataOptions, MetadataValue } from './metadata'; +import { ConnectionInjector, Server, ServerOptions, UntypedHandleCall, UntypedServiceImplementation } from './server'; +import { KeyCertPair, ServerCredentials } from './server-credentials'; +import { StatusBuilder } from './status-builder'; +import { handleBidiStreamingCall, handleServerStreamingCall, handleClientStreamingCall, handleUnaryCall, sendUnaryData, ServerUnaryCall, ServerReadableStream, ServerWritableStream, ServerDuplexStream, ServerErrorResponse } from './server-call'; +export { OAuth2Client }; +/**** Client Credentials ****/ +export declare const credentials: { + /** + * Combine a ChannelCredentials with any number of CallCredentials into a + * single ChannelCredentials object. + * @param channelCredentials The ChannelCredentials object. + * @param callCredentials Any number of CallCredentials objects. + * @return The resulting ChannelCredentials object. + */ + combineChannelCredentials: (channelCredentials: ChannelCredentials, ...callCredentials: CallCredentials[]) => ChannelCredentials; + /** + * Combine any number of CallCredentials into a single CallCredentials + * object. + * @param first The first CallCredentials object. + * @param additional Any number of additional CallCredentials objects. + * @return The resulting CallCredentials object. + */ + combineCallCredentials: (first: CallCredentials, ...additional: CallCredentials[]) => CallCredentials; + createInsecure: typeof ChannelCredentials.createInsecure; + createSsl: typeof ChannelCredentials.createSsl; + createFromSecureContext: typeof ChannelCredentials.createFromSecureContext; + createFromMetadataGenerator: typeof CallCredentials.createFromMetadataGenerator; + createFromGoogleCredential: typeof CallCredentials.createFromGoogleCredential; + createEmpty: typeof CallCredentials.createEmpty; +}; +/**** Metadata ****/ +export { Metadata, MetadataOptions, MetadataValue }; +/**** Constants ****/ +export { LogVerbosity as logVerbosity, Status as status, ConnectivityState as connectivityState, Propagate as propagate, CompressionAlgorithms as compressionAlgorithms, }; +/**** Client ****/ +export { Client, ClientOptions, loadPackageDefinition, makeClientConstructor, makeClientConstructor as makeGenericClientConstructor, CallProperties, CallInvocationTransformer, ChannelImplementation as Channel, Channel as ChannelInterface, UnaryCallback as requestCallback, }; +/** + * Close a Client object. + * @param client The client to close. + */ +export declare const closeClient: (client: Client) => void; +export declare const waitForClientReady: (client: Client, deadline: Date | number, callback: (error?: Error) => void) => void; +export { sendUnaryData, ChannelCredentials, CallCredentials, Deadline, Serialize as serialize, Deserialize as deserialize, ClientUnaryCall, ClientReadableStream, ClientWritableStream, ClientDuplexStream, CallOptions, MethodDefinition, StatusObject, ServiceError, ServerUnaryCall, ServerReadableStream, ServerWritableStream, ServerDuplexStream, ServerErrorResponse, ServerMethodDefinition, ServiceDefinition, UntypedHandleCall, UntypedServiceImplementation, VerifyOptions, }; +/**** Server ****/ +export { handleBidiStreamingCall, handleServerStreamingCall, handleUnaryCall, handleClientStreamingCall, }; +export type Call = ClientUnaryCall | ClientReadableStream | ClientWritableStream | ClientDuplexStream; +/**** Unimplemented function stubs ****/ +export declare const loadObject: (value: any, options: any) => never; +export declare const load: (filename: any, format: any, options: any) => never; +export declare const setLogger: (logger: Partial) => void; +export declare const setLogVerbosity: (verbosity: LogVerbosity) => void; +export { ConnectionInjector, Server, ServerOptions }; +export { ServerCredentials }; +export { KeyCertPair }; +export declare const getClientChannel: (client: Client) => Channel; +export { StatusBuilder }; +export { Listener, InterceptingListener } from './call-interface'; +export { Requester, ListenerBuilder, RequesterBuilder, Interceptor, InterceptorOptions, InterceptorProvider, InterceptingCall, InterceptorConfigurationError, NextCall, } from './client-interceptors'; +export { GrpcObject, ServiceClientConstructor, ProtobufTypeDefinition, } from './make-client'; +export { ChannelOptions } from './channel-options'; +export { getChannelzServiceDefinition, getChannelzHandlers } from './channelz'; +export { addAdminServicesToServer } from './admin'; +export { ServiceConfig, LoadBalancingConfig, MethodConfig, RetryPolicy, } from './service-config'; +export { ServerListener, FullServerListener, ServerListenerBuilder, Responder, FullResponder, ResponderBuilder, ServerInterceptingCallInterface, ServerInterceptingCall, ServerInterceptor, } from './server-interceptors'; +export { ServerMetricRecorder } from './orca'; +import * as experimental from './experimental'; +export { experimental }; +import { Deadline } from './deadline'; diff --git a/node_modules/@grpc/grpc-js/build/src/index.js b/node_modules/@grpc/grpc-js/build/src/index.js new file mode 100644 index 0000000..0c5c58a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/index.js @@ -0,0 +1,148 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.experimental = exports.ServerMetricRecorder = exports.ServerInterceptingCall = exports.ResponderBuilder = exports.ServerListenerBuilder = exports.addAdminServicesToServer = exports.getChannelzHandlers = exports.getChannelzServiceDefinition = exports.InterceptorConfigurationError = exports.InterceptingCall = exports.RequesterBuilder = exports.ListenerBuilder = exports.StatusBuilder = exports.getClientChannel = exports.ServerCredentials = exports.Server = exports.setLogVerbosity = exports.setLogger = exports.load = exports.loadObject = exports.CallCredentials = exports.ChannelCredentials = exports.waitForClientReady = exports.closeClient = exports.Channel = exports.makeGenericClientConstructor = exports.makeClientConstructor = exports.loadPackageDefinition = exports.Client = exports.compressionAlgorithms = exports.propagate = exports.connectivityState = exports.status = exports.logVerbosity = exports.Metadata = exports.credentials = void 0; +const call_credentials_1 = require("./call-credentials"); +Object.defineProperty(exports, "CallCredentials", { enumerable: true, get: function () { return call_credentials_1.CallCredentials; } }); +const channel_1 = require("./channel"); +Object.defineProperty(exports, "Channel", { enumerable: true, get: function () { return channel_1.ChannelImplementation; } }); +const compression_algorithms_1 = require("./compression-algorithms"); +Object.defineProperty(exports, "compressionAlgorithms", { enumerable: true, get: function () { return compression_algorithms_1.CompressionAlgorithms; } }); +const connectivity_state_1 = require("./connectivity-state"); +Object.defineProperty(exports, "connectivityState", { enumerable: true, get: function () { return connectivity_state_1.ConnectivityState; } }); +const channel_credentials_1 = require("./channel-credentials"); +Object.defineProperty(exports, "ChannelCredentials", { enumerable: true, get: function () { return channel_credentials_1.ChannelCredentials; } }); +const client_1 = require("./client"); +Object.defineProperty(exports, "Client", { enumerable: true, get: function () { return client_1.Client; } }); +const constants_1 = require("./constants"); +Object.defineProperty(exports, "logVerbosity", { enumerable: true, get: function () { return constants_1.LogVerbosity; } }); +Object.defineProperty(exports, "status", { enumerable: true, get: function () { return constants_1.Status; } }); +Object.defineProperty(exports, "propagate", { enumerable: true, get: function () { return constants_1.Propagate; } }); +const logging = require("./logging"); +const make_client_1 = require("./make-client"); +Object.defineProperty(exports, "loadPackageDefinition", { enumerable: true, get: function () { return make_client_1.loadPackageDefinition; } }); +Object.defineProperty(exports, "makeClientConstructor", { enumerable: true, get: function () { return make_client_1.makeClientConstructor; } }); +Object.defineProperty(exports, "makeGenericClientConstructor", { enumerable: true, get: function () { return make_client_1.makeClientConstructor; } }); +const metadata_1 = require("./metadata"); +Object.defineProperty(exports, "Metadata", { enumerable: true, get: function () { return metadata_1.Metadata; } }); +const server_1 = require("./server"); +Object.defineProperty(exports, "Server", { enumerable: true, get: function () { return server_1.Server; } }); +const server_credentials_1 = require("./server-credentials"); +Object.defineProperty(exports, "ServerCredentials", { enumerable: true, get: function () { return server_credentials_1.ServerCredentials; } }); +const status_builder_1 = require("./status-builder"); +Object.defineProperty(exports, "StatusBuilder", { enumerable: true, get: function () { return status_builder_1.StatusBuilder; } }); +/**** Client Credentials ****/ +// Using assign only copies enumerable properties, which is what we want +exports.credentials = { + /** + * Combine a ChannelCredentials with any number of CallCredentials into a + * single ChannelCredentials object. + * @param channelCredentials The ChannelCredentials object. + * @param callCredentials Any number of CallCredentials objects. + * @return The resulting ChannelCredentials object. + */ + combineChannelCredentials: (channelCredentials, ...callCredentials) => { + return callCredentials.reduce((acc, other) => acc.compose(other), channelCredentials); + }, + /** + * Combine any number of CallCredentials into a single CallCredentials + * object. + * @param first The first CallCredentials object. + * @param additional Any number of additional CallCredentials objects. + * @return The resulting CallCredentials object. + */ + combineCallCredentials: (first, ...additional) => { + return additional.reduce((acc, other) => acc.compose(other), first); + }, + // from channel-credentials.ts + createInsecure: channel_credentials_1.ChannelCredentials.createInsecure, + createSsl: channel_credentials_1.ChannelCredentials.createSsl, + createFromSecureContext: channel_credentials_1.ChannelCredentials.createFromSecureContext, + // from call-credentials.ts + createFromMetadataGenerator: call_credentials_1.CallCredentials.createFromMetadataGenerator, + createFromGoogleCredential: call_credentials_1.CallCredentials.createFromGoogleCredential, + createEmpty: call_credentials_1.CallCredentials.createEmpty, +}; +/** + * Close a Client object. + * @param client The client to close. + */ +const closeClient = (client) => client.close(); +exports.closeClient = closeClient; +const waitForClientReady = (client, deadline, callback) => client.waitForReady(deadline, callback); +exports.waitForClientReady = waitForClientReady; +/* eslint-enable @typescript-eslint/no-explicit-any */ +/**** Unimplemented function stubs ****/ +/* eslint-disable @typescript-eslint/no-explicit-any */ +const loadObject = (value, options) => { + throw new Error('Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead'); +}; +exports.loadObject = loadObject; +const load = (filename, format, options) => { + throw new Error('Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead'); +}; +exports.load = load; +const setLogger = (logger) => { + logging.setLogger(logger); +}; +exports.setLogger = setLogger; +const setLogVerbosity = (verbosity) => { + logging.setLoggerVerbosity(verbosity); +}; +exports.setLogVerbosity = setLogVerbosity; +const getClientChannel = (client) => { + return client_1.Client.prototype.getChannel.call(client); +}; +exports.getClientChannel = getClientChannel; +var client_interceptors_1 = require("./client-interceptors"); +Object.defineProperty(exports, "ListenerBuilder", { enumerable: true, get: function () { return client_interceptors_1.ListenerBuilder; } }); +Object.defineProperty(exports, "RequesterBuilder", { enumerable: true, get: function () { return client_interceptors_1.RequesterBuilder; } }); +Object.defineProperty(exports, "InterceptingCall", { enumerable: true, get: function () { return client_interceptors_1.InterceptingCall; } }); +Object.defineProperty(exports, "InterceptorConfigurationError", { enumerable: true, get: function () { return client_interceptors_1.InterceptorConfigurationError; } }); +var channelz_1 = require("./channelz"); +Object.defineProperty(exports, "getChannelzServiceDefinition", { enumerable: true, get: function () { return channelz_1.getChannelzServiceDefinition; } }); +Object.defineProperty(exports, "getChannelzHandlers", { enumerable: true, get: function () { return channelz_1.getChannelzHandlers; } }); +var admin_1 = require("./admin"); +Object.defineProperty(exports, "addAdminServicesToServer", { enumerable: true, get: function () { return admin_1.addAdminServicesToServer; } }); +var server_interceptors_1 = require("./server-interceptors"); +Object.defineProperty(exports, "ServerListenerBuilder", { enumerable: true, get: function () { return server_interceptors_1.ServerListenerBuilder; } }); +Object.defineProperty(exports, "ResponderBuilder", { enumerable: true, get: function () { return server_interceptors_1.ResponderBuilder; } }); +Object.defineProperty(exports, "ServerInterceptingCall", { enumerable: true, get: function () { return server_interceptors_1.ServerInterceptingCall; } }); +var orca_1 = require("./orca"); +Object.defineProperty(exports, "ServerMetricRecorder", { enumerable: true, get: function () { return orca_1.ServerMetricRecorder; } }); +const experimental = require("./experimental"); +exports.experimental = experimental; +const resolver_dns = require("./resolver-dns"); +const resolver_uds = require("./resolver-uds"); +const resolver_ip = require("./resolver-ip"); +const load_balancer_pick_first = require("./load-balancer-pick-first"); +const load_balancer_round_robin = require("./load-balancer-round-robin"); +const load_balancer_outlier_detection = require("./load-balancer-outlier-detection"); +const load_balancer_weighted_round_robin = require("./load-balancer-weighted-round-robin"); +const channelz = require("./channelz"); +(() => { + resolver_dns.setup(); + resolver_uds.setup(); + resolver_ip.setup(); + load_balancer_pick_first.setup(); + load_balancer_round_robin.setup(); + load_balancer_outlier_detection.setup(); + load_balancer_weighted_round_robin.setup(); + channelz.setup(); +})(); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/index.js.map b/node_modules/@grpc/grpc-js/build/src/index.js.map new file mode 100644 index 0000000..4555836 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AASH,yDAAmE;AA+IjE,gGA/IO,kCAAe,OA+IP;AA7IjB,uCAA2D;AAuHhC,wFAvHT,+BAAqB,OAuHL;AAtHlC,qEAAiE;AAwGtC,sGAxGlB,8CAAqB,OAwGkB;AAvGhD,6DAAyD;AAqGlC,kGArGd,sCAAiB,OAqGc;AApGxC,+DAA0E;AAyIxE,mGAzIO,wCAAkB,OAyIP;AAxIpB,qCAOkB;AAqGhB,uFA1GA,eAAM,OA0GA;AApGR,2CAA8D;AAyF5C,6FAzFT,wBAAY,OAyFS;AAClB,uFA1FW,kBAAM,OA0FX;AAEH,0FA5FgB,qBAAS,OA4FhB;AA3FxB,qCAAqC;AACrC,+CAQuB;AA4FrB,sGAlGA,mCAAqB,OAkGA;AACrB,sGAlGA,mCAA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,uHAAA,gBAAgB,OAAA;AAEhB,6HAAA,sBAAsB,OAAA;AAIxB,+BAA8C;AAArC,4GAAA,oBAAoB,OAAA;AAE7B,+CAA+C;AACtC,oCAAY;AAErB,+CAA+C;AAC/C,+CAA+C;AAC/C,6CAA6C;AAC7C,uEAAuE;AACvE,yEAAyE;AACzE,qFAAqF;AACrF,2FAA2F;AAC3F,uCAAuC;AAGvC,CAAC,GAAG,EAAE;IACJ,YAAY,CAAC,KAAK,EAAE,CAAC;IACrB,YAAY,CAAC,KAAK,EAAE,CAAC;IACrB,WAAW,CAAC,KAAK,EAAE,CAAC;IACpB,wBAAwB,CAAC,KAAK,EAAE,CAAC;IACjC,yBAAyB,CAAC,KAAK,EAAE,CAAC;IAClC,+BAA+B,CAAC,KAAK,EAAE,CAAC;IACxC,kCAAkC,CAAC,KAAK,EAAE,CAAC;IAC3C,QAAQ,CAAC,KAAK,EAAE,CAAC;AACnB,CAAC,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/internal-channel.d.ts b/node_modules/@grpc/grpc-js/build/src/internal-channel.d.ts new file mode 100644 index 0000000..9568a92 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/internal-channel.d.ts @@ -0,0 +1,124 @@ +import { ChannelCredentials } from './channel-credentials'; +import { ChannelOptions } from './channel-options'; +import { PickResult } from './picker'; +import { Metadata } from './metadata'; +import { CallConfig } from './resolver'; +import { ServerSurfaceCall } from './server-call'; +import { ConnectivityState } from './connectivity-state'; +import { ChannelRef } from './channelz'; +import { LoadBalancingCall } from './load-balancing-call'; +import { CallCredentials } from './call-credentials'; +import { Call, StatusObject } from './call-interface'; +import { Deadline } from './deadline'; +import { ResolvingCall } from './resolving-call'; +import { RetryingCall } from './retrying-call'; +import { BaseSubchannelWrapper, SubchannelInterface } from './subchannel-interface'; +interface NoneConfigResult { + type: 'NONE'; +} +interface SuccessConfigResult { + type: 'SUCCESS'; + config: CallConfig; +} +interface ErrorConfigResult { + type: 'ERROR'; + error: StatusObject; +} +type GetConfigResult = NoneConfigResult | SuccessConfigResult | ErrorConfigResult; +declare class ChannelSubchannelWrapper extends BaseSubchannelWrapper implements SubchannelInterface { + private channel; + private refCount; + private subchannelStateListener; + constructor(childSubchannel: SubchannelInterface, channel: InternalChannel); + ref(): void; + unref(): void; +} +export declare const SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = "grpc.internal.no_subchannel"; +export declare class InternalChannel { + private readonly credentials; + private readonly options; + private readonly resolvingLoadBalancer; + private readonly subchannelPool; + private connectivityState; + private currentPicker; + /** + * Calls queued up to get a call config. Should only be populated before the + * first time the resolver returns a result, which includes the ConfigSelector. + */ + private configSelectionQueue; + private pickQueue; + private connectivityStateWatchers; + private readonly defaultAuthority; + private readonly filterStackFactory; + private readonly target; + /** + * This timer does not do anything on its own. Its purpose is to hold the + * event loop open while there are any pending calls for the channel that + * have not yet been assigned to specific subchannels. In other words, + * the invariant is that callRefTimer is reffed if and only if pickQueue + * is non-empty. In addition, the timer is null while the state is IDLE or + * SHUTDOWN and there are no pending calls. + */ + private callRefTimer; + private configSelector; + /** + * This is the error from the name resolver if it failed most recently. It + * is only used to end calls that start while there is no config selector + * and the name resolver is in backoff, so it should be nulled if + * configSelector becomes set or the channel state becomes anything other + * than TRANSIENT_FAILURE. + */ + private currentResolutionError; + private readonly retryBufferTracker; + private keepaliveTime; + private readonly wrappedSubchannels; + private callCount; + private idleTimer; + private readonly idleTimeoutMs; + private lastActivityTimestamp; + private readonly channelzEnabled; + private readonly channelzRef; + private readonly channelzInfoTracker; + /** + * Randomly generated ID to be passed to the config selector, for use by + * ring_hash in xDS. An integer distributed approximately uniformly between + * 0 and MAX_SAFE_INTEGER. + */ + private readonly randomChannelId; + constructor(target: string, credentials: ChannelCredentials, options: ChannelOptions); + private trace; + private callRefTimerRef; + private callRefTimerUnref; + private removeConnectivityStateWatcher; + private updateState; + throttleKeepalive(newKeepaliveTime: number): void; + addWrappedSubchannel(wrappedSubchannel: ChannelSubchannelWrapper): void; + removeWrappedSubchannel(wrappedSubchannel: ChannelSubchannelWrapper): void; + doPick(metadata: Metadata, extraPickInfo: { + [key: string]: string; + }): PickResult; + queueCallForPick(call: LoadBalancingCall): void; + getConfig(method: string, metadata: Metadata): GetConfigResult; + queueCallForConfig(call: ResolvingCall): void; + private enterIdle; + private startIdleTimeout; + private maybeStartIdleTimer; + private onCallStart; + private onCallEnd; + createLoadBalancingCall(callConfig: CallConfig, method: string, host: string, credentials: CallCredentials, deadline: Deadline): LoadBalancingCall; + createRetryingCall(callConfig: CallConfig, method: string, host: string, credentials: CallCredentials, deadline: Deadline): RetryingCall; + createResolvingCall(method: string, deadline: Deadline, host: string | null | undefined, parentCall: ServerSurfaceCall | null, propagateFlags: number | null | undefined): ResolvingCall; + close(): void; + getTarget(): string; + getConnectivityState(tryToConnect: boolean): ConnectivityState; + watchConnectivityState(currentState: ConnectivityState, deadline: Date | number, callback: (error?: Error) => void): void; + /** + * Get the channelz reference object for this channel. The returned value is + * garbage if channelz is disabled for this channel. + * @returns + */ + getChannelzRef(): ChannelRef; + createCall(method: string, deadline: Deadline, host: string | null | undefined, parentCall: ServerSurfaceCall | null, propagateFlags: number | null | undefined): Call; + getOptions(): ChannelOptions; +} +export {}; diff --git a/node_modules/@grpc/grpc-js/build/src/internal-channel.js b/node_modules/@grpc/grpc-js/build/src/internal-channel.js new file mode 100644 index 0000000..e52f881 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/internal-channel.js @@ -0,0 +1,605 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InternalChannel = exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = void 0; +const channel_credentials_1 = require("./channel-credentials"); +const resolving_load_balancer_1 = require("./resolving-load-balancer"); +const subchannel_pool_1 = require("./subchannel-pool"); +const picker_1 = require("./picker"); +const metadata_1 = require("./metadata"); +const constants_1 = require("./constants"); +const filter_stack_1 = require("./filter-stack"); +const compression_filter_1 = require("./compression-filter"); +const resolver_1 = require("./resolver"); +const logging_1 = require("./logging"); +const http_proxy_1 = require("./http_proxy"); +const uri_parser_1 = require("./uri-parser"); +const connectivity_state_1 = require("./connectivity-state"); +const channelz_1 = require("./channelz"); +const load_balancing_call_1 = require("./load-balancing-call"); +const deadline_1 = require("./deadline"); +const resolving_call_1 = require("./resolving-call"); +const call_number_1 = require("./call-number"); +const control_plane_status_1 = require("./control-plane-status"); +const retrying_call_1 = require("./retrying-call"); +const subchannel_interface_1 = require("./subchannel-interface"); +/** + * See https://nodejs.org/api/timers.html#timers_setinterval_callback_delay_args + */ +const MAX_TIMEOUT_TIME = 2147483647; +const MIN_IDLE_TIMEOUT_MS = 1000; +// 30 minutes +const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000; +const RETRY_THROTTLER_MAP = new Map(); +const DEFAULT_RETRY_BUFFER_SIZE_BYTES = 1 << 24; // 16 MB +const DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES = 1 << 20; // 1 MB +class ChannelSubchannelWrapper extends subchannel_interface_1.BaseSubchannelWrapper { + constructor(childSubchannel, channel) { + super(childSubchannel); + this.channel = channel; + this.refCount = 0; + this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime) => { + channel.throttleKeepalive(keepaliveTime); + }; + } + ref() { + if (this.refCount === 0) { + this.child.addConnectivityStateListener(this.subchannelStateListener); + this.channel.addWrappedSubchannel(this); + } + this.child.ref(); + this.refCount += 1; + } + unref() { + this.child.unref(); + this.refCount -= 1; + if (this.refCount <= 0) { + this.child.removeConnectivityStateListener(this.subchannelStateListener); + this.channel.removeWrappedSubchannel(this); + } + } +} +class ShutdownPicker { + pick(pickArgs) { + return { + pickResultType: picker_1.PickResultType.DROP, + status: { + code: constants_1.Status.UNAVAILABLE, + details: 'Channel closed before call started', + metadata: new metadata_1.Metadata() + }, + subchannel: null, + onCallStarted: null, + onCallEnded: null + }; + } +} +exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = 'grpc.internal.no_subchannel'; +class ChannelzInfoTracker { + constructor(target) { + this.target = target; + this.trace = new channelz_1.ChannelzTrace(); + this.callTracker = new channelz_1.ChannelzCallTracker(); + this.childrenTracker = new channelz_1.ChannelzChildrenTracker(); + this.state = connectivity_state_1.ConnectivityState.IDLE; + } + getChannelzInfoCallback() { + return () => { + return { + target: this.target, + state: this.state, + trace: this.trace, + callTracker: this.callTracker, + children: this.childrenTracker.getChildLists() + }; + }; + } +} +class InternalChannel { + constructor(target, credentials, options) { + var _a, _b, _c, _d, _e, _f; + this.credentials = credentials; + this.options = options; + this.connectivityState = connectivity_state_1.ConnectivityState.IDLE; + this.currentPicker = new picker_1.UnavailablePicker(); + /** + * Calls queued up to get a call config. Should only be populated before the + * first time the resolver returns a result, which includes the ConfigSelector. + */ + this.configSelectionQueue = []; + this.pickQueue = []; + this.connectivityStateWatchers = []; + /** + * This timer does not do anything on its own. Its purpose is to hold the + * event loop open while there are any pending calls for the channel that + * have not yet been assigned to specific subchannels. In other words, + * the invariant is that callRefTimer is reffed if and only if pickQueue + * is non-empty. In addition, the timer is null while the state is IDLE or + * SHUTDOWN and there are no pending calls. + */ + this.callRefTimer = null; + this.configSelector = null; + /** + * This is the error from the name resolver if it failed most recently. It + * is only used to end calls that start while there is no config selector + * and the name resolver is in backoff, so it should be nulled if + * configSelector becomes set or the channel state becomes anything other + * than TRANSIENT_FAILURE. + */ + this.currentResolutionError = null; + this.wrappedSubchannels = new Set(); + this.callCount = 0; + this.idleTimer = null; + // Channelz info + this.channelzEnabled = true; + /** + * Randomly generated ID to be passed to the config selector, for use by + * ring_hash in xDS. An integer distributed approximately uniformly between + * 0 and MAX_SAFE_INTEGER. + */ + this.randomChannelId = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER); + if (typeof target !== 'string') { + throw new TypeError('Channel target must be a string'); + } + if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) { + throw new TypeError('Channel credentials must be a ChannelCredentials object'); + } + if (options) { + if (typeof options !== 'object') { + throw new TypeError('Channel options must be an object'); + } + } + this.channelzInfoTracker = new ChannelzInfoTracker(target); + const originalTargetUri = (0, uri_parser_1.parseUri)(target); + if (originalTargetUri === null) { + throw new Error(`Could not parse target name "${target}"`); + } + /* This ensures that the target has a scheme that is registered with the + * resolver */ + const defaultSchemeMapResult = (0, resolver_1.mapUriDefaultScheme)(originalTargetUri); + if (defaultSchemeMapResult === null) { + throw new Error(`Could not find a default scheme for target name "${target}"`); + } + if (this.options['grpc.enable_channelz'] === 0) { + this.channelzEnabled = false; + } + this.channelzRef = (0, channelz_1.registerChannelzChannel)(target, this.channelzInfoTracker.getChannelzInfoCallback(), this.channelzEnabled); + if (this.channelzEnabled) { + this.channelzInfoTracker.trace.addTrace('CT_INFO', 'Channel created'); + } + if (this.options['grpc.default_authority']) { + this.defaultAuthority = this.options['grpc.default_authority']; + } + else { + this.defaultAuthority = (0, resolver_1.getDefaultAuthority)(defaultSchemeMapResult); + } + const proxyMapResult = (0, http_proxy_1.mapProxyName)(defaultSchemeMapResult, options); + this.target = proxyMapResult.target; + this.options = Object.assign({}, this.options, proxyMapResult.extraOptions); + /* The global boolean parameter to getSubchannelPool has the inverse meaning to what + * the grpc.use_local_subchannel_pool channel option means. */ + this.subchannelPool = (0, subchannel_pool_1.getSubchannelPool)(((_a = this.options['grpc.use_local_subchannel_pool']) !== null && _a !== void 0 ? _a : 0) === 0); + this.retryBufferTracker = new retrying_call_1.MessageBufferTracker((_b = this.options['grpc.retry_buffer_size']) !== null && _b !== void 0 ? _b : DEFAULT_RETRY_BUFFER_SIZE_BYTES, (_c = this.options['grpc.per_rpc_retry_buffer_size']) !== null && _c !== void 0 ? _c : DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES); + this.keepaliveTime = (_d = this.options['grpc.keepalive_time_ms']) !== null && _d !== void 0 ? _d : -1; + this.idleTimeoutMs = Math.max((_e = this.options['grpc.client_idle_timeout_ms']) !== null && _e !== void 0 ? _e : DEFAULT_IDLE_TIMEOUT_MS, MIN_IDLE_TIMEOUT_MS); + const channelControlHelper = { + createSubchannel: (subchannelAddress, subchannelArgs) => { + const finalSubchannelArgs = {}; + for (const [key, value] of Object.entries(subchannelArgs)) { + if (!key.startsWith(exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX)) { + finalSubchannelArgs[key] = value; + } + } + const subchannel = this.subchannelPool.getOrCreateSubchannel(this.target, subchannelAddress, finalSubchannelArgs, this.credentials); + subchannel.throttleKeepalive(this.keepaliveTime); + if (this.channelzEnabled) { + this.channelzInfoTracker.trace.addTrace('CT_INFO', 'Created subchannel or used existing subchannel', subchannel.getChannelzRef()); + } + const wrappedSubchannel = new ChannelSubchannelWrapper(subchannel, this); + return wrappedSubchannel; + }, + updateState: (connectivityState, picker) => { + this.currentPicker = picker; + const queueCopy = this.pickQueue.slice(); + this.pickQueue = []; + if (queueCopy.length > 0) { + this.callRefTimerUnref(); + } + for (const call of queueCopy) { + call.doPick(); + } + this.updateState(connectivityState); + }, + requestReresolution: () => { + // This should never be called. + throw new Error('Resolving load balancer should never call requestReresolution'); + }, + addChannelzChild: (child) => { + if (this.channelzEnabled) { + this.channelzInfoTracker.childrenTracker.refChild(child); + } + }, + removeChannelzChild: (child) => { + if (this.channelzEnabled) { + this.channelzInfoTracker.childrenTracker.unrefChild(child); + } + }, + }; + this.resolvingLoadBalancer = new resolving_load_balancer_1.ResolvingLoadBalancer(this.target, channelControlHelper, this.options, (serviceConfig, configSelector) => { + var _a; + if (serviceConfig.retryThrottling) { + RETRY_THROTTLER_MAP.set(this.getTarget(), new retrying_call_1.RetryThrottler(serviceConfig.retryThrottling.maxTokens, serviceConfig.retryThrottling.tokenRatio, RETRY_THROTTLER_MAP.get(this.getTarget()))); + } + else { + RETRY_THROTTLER_MAP.delete(this.getTarget()); + } + if (this.channelzEnabled) { + this.channelzInfoTracker.trace.addTrace('CT_INFO', 'Address resolution succeeded'); + } + (_a = this.configSelector) === null || _a === void 0 ? void 0 : _a.unref(); + this.configSelector = configSelector; + this.currentResolutionError = null; + /* We process the queue asynchronously to ensure that the corresponding + * load balancer update has completed. */ + process.nextTick(() => { + const localQueue = this.configSelectionQueue; + this.configSelectionQueue = []; + if (localQueue.length > 0) { + this.callRefTimerUnref(); + } + for (const call of localQueue) { + call.getConfig(); + } + }); + }, status => { + if (this.channelzEnabled) { + this.channelzInfoTracker.trace.addTrace('CT_WARNING', 'Address resolution failed with code ' + + status.code + + ' and details "' + + status.details + + '"'); + } + if (this.configSelectionQueue.length > 0) { + this.trace('Name resolution failed with calls queued for config selection'); + } + if (this.configSelector === null) { + this.currentResolutionError = Object.assign(Object.assign({}, (0, control_plane_status_1.restrictControlPlaneStatusCode)(status.code, status.details)), { metadata: status.metadata }); + } + const localQueue = this.configSelectionQueue; + this.configSelectionQueue = []; + if (localQueue.length > 0) { + this.callRefTimerUnref(); + } + for (const call of localQueue) { + call.reportResolverError(status); + } + }); + this.filterStackFactory = new filter_stack_1.FilterStackFactory([ + new compression_filter_1.CompressionFilterFactory(this, this.options), + ]); + this.trace('Channel constructed with options ' + + JSON.stringify(options, undefined, 2)); + const error = new Error(); + if ((0, logging_1.isTracerEnabled)('channel_stacktrace')) { + (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, 'channel_stacktrace', '(' + + this.channelzRef.id + + ') ' + + 'Channel constructed \n' + + ((_f = error.stack) === null || _f === void 0 ? void 0 : _f.substring(error.stack.indexOf('\n') + 1))); + } + this.lastActivityTimestamp = new Date(); + } + trace(text, verbosityOverride) { + (0, logging_1.trace)(verbosityOverride !== null && verbosityOverride !== void 0 ? verbosityOverride : constants_1.LogVerbosity.DEBUG, 'channel', '(' + this.channelzRef.id + ') ' + (0, uri_parser_1.uriToString)(this.target) + ' ' + text); + } + callRefTimerRef() { + var _a, _b, _c, _d; + if (!this.callRefTimer) { + this.callRefTimer = setInterval(() => { }, MAX_TIMEOUT_TIME); + } + // If the hasRef function does not exist, always run the code + if (!((_b = (_a = this.callRefTimer).hasRef) === null || _b === void 0 ? void 0 : _b.call(_a))) { + this.trace('callRefTimer.ref | configSelectionQueue.length=' + + this.configSelectionQueue.length + + ' pickQueue.length=' + + this.pickQueue.length); + (_d = (_c = this.callRefTimer).ref) === null || _d === void 0 ? void 0 : _d.call(_c); + } + } + callRefTimerUnref() { + var _a, _b, _c; + // If the timer or the hasRef function does not exist, always run the code + if (!((_a = this.callRefTimer) === null || _a === void 0 ? void 0 : _a.hasRef) || this.callRefTimer.hasRef()) { + this.trace('callRefTimer.unref | configSelectionQueue.length=' + + this.configSelectionQueue.length + + ' pickQueue.length=' + + this.pickQueue.length); + (_c = (_b = this.callRefTimer) === null || _b === void 0 ? void 0 : _b.unref) === null || _c === void 0 ? void 0 : _c.call(_b); + } + } + removeConnectivityStateWatcher(watcherObject) { + const watcherIndex = this.connectivityStateWatchers.findIndex(value => value === watcherObject); + if (watcherIndex >= 0) { + this.connectivityStateWatchers.splice(watcherIndex, 1); + } + } + updateState(newState) { + (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, 'connectivity_state', '(' + + this.channelzRef.id + + ') ' + + (0, uri_parser_1.uriToString)(this.target) + + ' ' + + connectivity_state_1.ConnectivityState[this.connectivityState] + + ' -> ' + + connectivity_state_1.ConnectivityState[newState]); + if (this.channelzEnabled) { + this.channelzInfoTracker.trace.addTrace('CT_INFO', 'Connectivity state change to ' + connectivity_state_1.ConnectivityState[newState]); + } + this.connectivityState = newState; + this.channelzInfoTracker.state = newState; + const watchersCopy = this.connectivityStateWatchers.slice(); + for (const watcherObject of watchersCopy) { + if (newState !== watcherObject.currentState) { + if (watcherObject.timer) { + clearTimeout(watcherObject.timer); + } + this.removeConnectivityStateWatcher(watcherObject); + watcherObject.callback(); + } + } + if (newState !== connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { + this.currentResolutionError = null; + } + } + throttleKeepalive(newKeepaliveTime) { + if (newKeepaliveTime > this.keepaliveTime) { + this.keepaliveTime = newKeepaliveTime; + for (const wrappedSubchannel of this.wrappedSubchannels) { + wrappedSubchannel.throttleKeepalive(newKeepaliveTime); + } + } + } + addWrappedSubchannel(wrappedSubchannel) { + this.wrappedSubchannels.add(wrappedSubchannel); + } + removeWrappedSubchannel(wrappedSubchannel) { + this.wrappedSubchannels.delete(wrappedSubchannel); + } + doPick(metadata, extraPickInfo) { + return this.currentPicker.pick({ + metadata: metadata, + extraPickInfo: extraPickInfo, + }); + } + queueCallForPick(call) { + this.pickQueue.push(call); + this.callRefTimerRef(); + } + getConfig(method, metadata) { + if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN) { + this.resolvingLoadBalancer.exitIdle(); + } + if (this.configSelector) { + return { + type: 'SUCCESS', + config: this.configSelector.invoke(method, metadata, this.randomChannelId), + }; + } + else { + if (this.currentResolutionError) { + return { + type: 'ERROR', + error: this.currentResolutionError, + }; + } + else { + return { + type: 'NONE', + }; + } + } + } + queueCallForConfig(call) { + this.configSelectionQueue.push(call); + this.callRefTimerRef(); + } + enterIdle() { + this.resolvingLoadBalancer.destroy(); + this.updateState(connectivity_state_1.ConnectivityState.IDLE); + this.currentPicker = new picker_1.QueuePicker(this.resolvingLoadBalancer); + if (this.idleTimer) { + clearTimeout(this.idleTimer); + this.idleTimer = null; + } + if (this.callRefTimer) { + clearInterval(this.callRefTimer); + this.callRefTimer = null; + } + } + startIdleTimeout(timeoutMs) { + var _a, _b; + this.idleTimer = setTimeout(() => { + if (this.callCount > 0) { + /* If there is currently a call, the channel will not go idle for a + * period of at least idleTimeoutMs, so check again after that time. + */ + this.startIdleTimeout(this.idleTimeoutMs); + return; + } + const now = new Date(); + const timeSinceLastActivity = now.valueOf() - this.lastActivityTimestamp.valueOf(); + if (timeSinceLastActivity >= this.idleTimeoutMs) { + this.trace('Idle timer triggered after ' + + this.idleTimeoutMs + + 'ms of inactivity'); + this.enterIdle(); + } + else { + /* Whenever the timer fires with the latest activity being too recent, + * set the timer again for the time when the time since the last + * activity is equal to the timeout. This should result in the timer + * firing no more than once every idleTimeoutMs/2 on average. */ + this.startIdleTimeout(this.idleTimeoutMs - timeSinceLastActivity); + } + }, timeoutMs); + (_b = (_a = this.idleTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + maybeStartIdleTimer() { + if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN && + !this.idleTimer) { + this.startIdleTimeout(this.idleTimeoutMs); + } + } + onCallStart() { + if (this.channelzEnabled) { + this.channelzInfoTracker.callTracker.addCallStarted(); + } + this.callCount += 1; + } + onCallEnd(status) { + if (this.channelzEnabled) { + if (status.code === constants_1.Status.OK) { + this.channelzInfoTracker.callTracker.addCallSucceeded(); + } + else { + this.channelzInfoTracker.callTracker.addCallFailed(); + } + } + this.callCount -= 1; + this.lastActivityTimestamp = new Date(); + this.maybeStartIdleTimer(); + } + createLoadBalancingCall(callConfig, method, host, credentials, deadline) { + const callNumber = (0, call_number_1.getNextCallNumber)(); + this.trace('createLoadBalancingCall [' + callNumber + '] method="' + method + '"'); + return new load_balancing_call_1.LoadBalancingCall(this, callConfig, method, host, credentials, deadline, callNumber); + } + createRetryingCall(callConfig, method, host, credentials, deadline) { + const callNumber = (0, call_number_1.getNextCallNumber)(); + this.trace('createRetryingCall [' + callNumber + '] method="' + method + '"'); + return new retrying_call_1.RetryingCall(this, callConfig, method, host, credentials, deadline, callNumber, this.retryBufferTracker, RETRY_THROTTLER_MAP.get(this.getTarget())); + } + createResolvingCall(method, deadline, host, parentCall, propagateFlags) { + const callNumber = (0, call_number_1.getNextCallNumber)(); + this.trace('createResolvingCall [' + + callNumber + + '] method="' + + method + + '", deadline=' + + (0, deadline_1.deadlineToString)(deadline)); + const finalOptions = { + deadline: deadline, + flags: propagateFlags !== null && propagateFlags !== void 0 ? propagateFlags : constants_1.Propagate.DEFAULTS, + host: host !== null && host !== void 0 ? host : this.defaultAuthority, + parentCall: parentCall, + }; + const call = new resolving_call_1.ResolvingCall(this, method, finalOptions, this.filterStackFactory.clone(), callNumber); + this.onCallStart(); + call.addStatusWatcher(status => { + this.onCallEnd(status); + }); + return call; + } + close() { + var _a; + this.resolvingLoadBalancer.destroy(); + this.updateState(connectivity_state_1.ConnectivityState.SHUTDOWN); + this.currentPicker = new ShutdownPicker(); + for (const call of this.configSelectionQueue) { + call.cancelWithStatus(constants_1.Status.UNAVAILABLE, 'Channel closed before call started'); + } + this.configSelectionQueue = []; + for (const call of this.pickQueue) { + call.cancelWithStatus(constants_1.Status.UNAVAILABLE, 'Channel closed before call started'); + } + this.pickQueue = []; + if (this.callRefTimer) { + clearInterval(this.callRefTimer); + } + if (this.idleTimer) { + clearTimeout(this.idleTimer); + } + if (this.channelzEnabled) { + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + } + this.subchannelPool.unrefUnusedSubchannels(); + (_a = this.configSelector) === null || _a === void 0 ? void 0 : _a.unref(); + this.configSelector = null; + } + getTarget() { + return (0, uri_parser_1.uriToString)(this.target); + } + getConnectivityState(tryToConnect) { + const connectivityState = this.connectivityState; + if (tryToConnect) { + this.resolvingLoadBalancer.exitIdle(); + this.lastActivityTimestamp = new Date(); + this.maybeStartIdleTimer(); + } + return connectivityState; + } + watchConnectivityState(currentState, deadline, callback) { + if (this.connectivityState === connectivity_state_1.ConnectivityState.SHUTDOWN) { + throw new Error('Channel has been shut down'); + } + let timer = null; + if (deadline !== Infinity) { + const deadlineDate = deadline instanceof Date ? deadline : new Date(deadline); + const now = new Date(); + if (deadline === -Infinity || deadlineDate <= now) { + process.nextTick(callback, new Error('Deadline passed without connectivity state change')); + return; + } + timer = setTimeout(() => { + this.removeConnectivityStateWatcher(watcherObject); + callback(new Error('Deadline passed without connectivity state change')); + }, deadlineDate.getTime() - now.getTime()); + } + const watcherObject = { + currentState, + callback, + timer, + }; + this.connectivityStateWatchers.push(watcherObject); + } + /** + * Get the channelz reference object for this channel. The returned value is + * garbage if channelz is disabled for this channel. + * @returns + */ + getChannelzRef() { + return this.channelzRef; + } + createCall(method, deadline, host, parentCall, propagateFlags) { + if (typeof method !== 'string') { + throw new TypeError('Channel#createCall: method must be a string'); + } + if (!(typeof deadline === 'number' || deadline instanceof Date)) { + throw new TypeError('Channel#createCall: deadline must be a number or Date'); + } + if (this.connectivityState === connectivity_state_1.ConnectivityState.SHUTDOWN) { + throw new Error('Channel has been shut down'); + } + return this.createResolvingCall(method, deadline, host, parentCall, propagateFlags); + } + getOptions() { + return this.options; + } +} +exports.InternalChannel = InternalChannel; +//# sourceMappingURL=internal-channel.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/internal-channel.js.map b/node_modules/@grpc/grpc-js/build/src/internal-channel.js.map new file mode 100644 index 0000000..70174ab --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/internal-channel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"internal-channel.js","sourceRoot":"","sources":["../../src/internal-channel.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,+DAA2D;AAE3D,uEAAkE;AAClE,uDAAsE;AAEtE,qCAAwG;AACxG,yCAAsC;AACtC,2CAA8D;AAC9D,iDAAoD;AACpD,6DAAgE;AAChE,yCAKoB;AACpB,uCAAmD;AAEnD,6CAA4C;AAC5C,6CAA8D;AAG9D,6DAAyD;AACzD,yCASoB;AACpB,+DAA0D;AAG1D,yCAAwD;AACxD,qDAAiD;AACjD,+CAAkD;AAClD,iEAAwE;AACxE,mDAIyB;AACzB,iEAIgC;AAEhC;;GAEG;AACH,MAAM,gBAAgB,GAAG,UAAU,CAAC;AAEpC,MAAM,mBAAmB,GAAG,IAAI,CAA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AC;QAChD,CAAC;QACD,OAAO,IAAI,CAAC,mBAAmB,CAC7B,MAAM,EACN,QAAQ,EACR,IAAI,EACJ,UAAU,EACV,cAAc,CACf,CAAC;IACJ,CAAC;IAED,UAAU;QACR,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;CACF;AAprBD,0CAorBC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.d.ts b/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.d.ts new file mode 100644 index 0000000..c3d571f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.d.ts @@ -0,0 +1,24 @@ +import { ChannelControlHelper, TypedLoadBalancingConfig } from './load-balancer'; +import { Endpoint } from './subchannel-address'; +import { ChannelOptions } from './channel-options'; +import { StatusOr } from './call-interface'; +export declare class ChildLoadBalancerHandler { + private readonly channelControlHelper; + private currentChild; + private pendingChild; + private latestConfig; + private ChildPolicyHelper; + constructor(channelControlHelper: ChannelControlHelper); + protected configUpdateRequiresNewPolicyInstance(oldConfig: TypedLoadBalancingConfig, newConfig: TypedLoadBalancingConfig): boolean; + /** + * Prerequisites: lbConfig !== null and lbConfig.name is registered + * @param endpointList + * @param lbConfig + * @param attributes + */ + updateAddressList(endpointList: StatusOr, lbConfig: TypedLoadBalancingConfig, options: ChannelOptions, resolutionNote: string): boolean; + exitIdle(): void; + resetBackoff(): void; + destroy(): void; + getTypeName(): string; +} diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js b/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js new file mode 100644 index 0000000..d8c37a9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js @@ -0,0 +1,151 @@ +"use strict"; +/* + * Copyright 2020 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChildLoadBalancerHandler = void 0; +const load_balancer_1 = require("./load-balancer"); +const connectivity_state_1 = require("./connectivity-state"); +const TYPE_NAME = 'child_load_balancer_helper'; +class ChildLoadBalancerHandler { + constructor(channelControlHelper) { + this.channelControlHelper = channelControlHelper; + this.currentChild = null; + this.pendingChild = null; + this.latestConfig = null; + this.ChildPolicyHelper = class { + constructor(parent) { + this.parent = parent; + this.child = null; + } + createSubchannel(subchannelAddress, subchannelArgs) { + return this.parent.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); + } + updateState(connectivityState, picker, errorMessage) { + var _a; + if (this.calledByPendingChild()) { + if (connectivityState === connectivity_state_1.ConnectivityState.CONNECTING) { + return; + } + (_a = this.parent.currentChild) === null || _a === void 0 ? void 0 : _a.destroy(); + this.parent.currentChild = this.parent.pendingChild; + this.parent.pendingChild = null; + } + else if (!this.calledByCurrentChild()) { + return; + } + this.parent.channelControlHelper.updateState(connectivityState, picker, errorMessage); + } + requestReresolution() { + var _a; + const latestChild = (_a = this.parent.pendingChild) !== null && _a !== void 0 ? _a : this.parent.currentChild; + if (this.child === latestChild) { + this.parent.channelControlHelper.requestReresolution(); + } + } + setChild(newChild) { + this.child = newChild; + } + addChannelzChild(child) { + this.parent.channelControlHelper.addChannelzChild(child); + } + removeChannelzChild(child) { + this.parent.channelControlHelper.removeChannelzChild(child); + } + calledByPendingChild() { + return this.child === this.parent.pendingChild; + } + calledByCurrentChild() { + return this.child === this.parent.currentChild; + } + }; + } + configUpdateRequiresNewPolicyInstance(oldConfig, newConfig) { + return oldConfig.getLoadBalancerName() !== newConfig.getLoadBalancerName(); + } + /** + * Prerequisites: lbConfig !== null and lbConfig.name is registered + * @param endpointList + * @param lbConfig + * @param attributes + */ + updateAddressList(endpointList, lbConfig, options, resolutionNote) { + let childToUpdate; + if (this.currentChild === null || + this.latestConfig === null || + this.configUpdateRequiresNewPolicyInstance(this.latestConfig, lbConfig)) { + const newHelper = new this.ChildPolicyHelper(this); + const newChild = (0, load_balancer_1.createLoadBalancer)(lbConfig, newHelper); + newHelper.setChild(newChild); + if (this.currentChild === null) { + this.currentChild = newChild; + childToUpdate = this.currentChild; + } + else { + if (this.pendingChild) { + this.pendingChild.destroy(); + } + this.pendingChild = newChild; + childToUpdate = this.pendingChild; + } + } + else { + if (this.pendingChild === null) { + childToUpdate = this.currentChild; + } + else { + childToUpdate = this.pendingChild; + } + } + this.latestConfig = lbConfig; + return childToUpdate.updateAddressList(endpointList, lbConfig, options, resolutionNote); + } + exitIdle() { + if (this.currentChild) { + this.currentChild.exitIdle(); + if (this.pendingChild) { + this.pendingChild.exitIdle(); + } + } + } + resetBackoff() { + if (this.currentChild) { + this.currentChild.resetBackoff(); + if (this.pendingChild) { + this.pendingChild.resetBackoff(); + } + } + } + destroy() { + /* Note: state updates are only propagated from the child balancer if that + * object is equal to this.currentChild or this.pendingChild. Since this + * function sets both of those to null, no further state updates will + * occur after this function returns. */ + if (this.currentChild) { + this.currentChild.destroy(); + this.currentChild = null; + } + if (this.pendingChild) { + this.pendingChild.destroy(); + this.pendingChild = null; + } + } + getTypeName() { + return TYPE_NAME; + } +} +exports.ChildLoadBalancerHandler = ChildLoadBalancerHandler; +//# sourceMappingURL=load-balancer-child-handler.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js.map b/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js.map new file mode 100644 index 0000000..26f16dc --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js.map @@ -0,0 +1 @@ +{"version":3,"file":"load-balancer-child-handler.js","sourceRoot":"","sources":["../../src/load-balancer-child-handler.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAe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CAAC;YACnC,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO;QACL;;;gDAGwC;QACxC,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtB,IAAI,CAAC,YAAY,CAAC,OAAO,EAAE,CAAC;YAC5B,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;QAC3B,CAAC;QACD,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtB,IAAI,CAAC,YAAY,CAAC,OAAO,EAAE,CAAC;YAC5B,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;QAC3B,CAAC;IACH,CAAC;IACD,WAAW;QACT,OAAO,SAAS,CAAC;IACnB,CAAC;CACF;AA3ID,4DA2IC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.d.ts b/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.d.ts new file mode 100644 index 0000000..afcee90 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.d.ts @@ -0,0 +1,71 @@ +import { ChannelOptions } from './channel-options'; +import { Duration } from './duration'; +import { ChannelControlHelper } from './experimental'; +import { LoadBalancer, TypedLoadBalancingConfig } from './load-balancer'; +import { Endpoint } from './subchannel-address'; +import { LoadBalancingConfig } from './service-config'; +import { StatusOr } from './call-interface'; +export interface SuccessRateEjectionConfig { + readonly stdev_factor: number; + readonly enforcement_percentage: number; + readonly minimum_hosts: number; + readonly request_volume: number; +} +export interface FailurePercentageEjectionConfig { + readonly threshold: number; + readonly enforcement_percentage: number; + readonly minimum_hosts: number; + readonly request_volume: number; +} +export interface OutlierDetectionRawConfig { + interval?: Duration; + base_ejection_time?: Duration; + max_ejection_time?: Duration; + max_ejection_percent?: number; + success_rate_ejection?: Partial; + failure_percentage_ejection?: Partial; + child_policy: LoadBalancingConfig[]; +} +export declare class OutlierDetectionLoadBalancingConfig implements TypedLoadBalancingConfig { + private readonly childPolicy; + private readonly intervalMs; + private readonly baseEjectionTimeMs; + private readonly maxEjectionTimeMs; + private readonly maxEjectionPercent; + private readonly successRateEjection; + private readonly failurePercentageEjection; + constructor(intervalMs: number | null, baseEjectionTimeMs: number | null, maxEjectionTimeMs: number | null, maxEjectionPercent: number | null, successRateEjection: Partial | null, failurePercentageEjection: Partial | null, childPolicy: TypedLoadBalancingConfig); + getLoadBalancerName(): string; + toJsonObject(): object; + getIntervalMs(): number; + getBaseEjectionTimeMs(): number; + getMaxEjectionTimeMs(): number; + getMaxEjectionPercent(): number; + getSuccessRateEjectionConfig(): SuccessRateEjectionConfig | null; + getFailurePercentageEjectionConfig(): FailurePercentageEjectionConfig | null; + getChildPolicy(): TypedLoadBalancingConfig; + static createFromJson(obj: any): OutlierDetectionLoadBalancingConfig; +} +export declare class OutlierDetectionLoadBalancer implements LoadBalancer { + private childBalancer; + private entryMap; + private latestConfig; + private ejectionTimer; + private timerStartTime; + constructor(channelControlHelper: ChannelControlHelper); + private isCountingEnabled; + private getCurrentEjectionPercent; + private runSuccessRateCheck; + private runFailurePercentageCheck; + private eject; + private uneject; + private switchAllBuckets; + private startTimer; + private runChecks; + updateAddressList(endpointList: StatusOr, lbConfig: TypedLoadBalancingConfig, options: ChannelOptions, resolutionNote: string): boolean; + exitIdle(): void; + resetBackoff(): void; + destroy(): void; + getTypeName(): string; +} +export declare function setup(): void; diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js b/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js new file mode 100644 index 0000000..ee32bf3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js @@ -0,0 +1,571 @@ +"use strict"; +/* + * Copyright 2022 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +var _a; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OutlierDetectionLoadBalancer = exports.OutlierDetectionLoadBalancingConfig = void 0; +exports.setup = setup; +const connectivity_state_1 = require("./connectivity-state"); +const constants_1 = require("./constants"); +const duration_1 = require("./duration"); +const experimental_1 = require("./experimental"); +const load_balancer_1 = require("./load-balancer"); +const load_balancer_child_handler_1 = require("./load-balancer-child-handler"); +const picker_1 = require("./picker"); +const subchannel_address_1 = require("./subchannel-address"); +const subchannel_interface_1 = require("./subchannel-interface"); +const logging = require("./logging"); +const TRACER_NAME = 'outlier_detection'; +function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); +} +const TYPE_NAME = 'outlier_detection'; +const OUTLIER_DETECTION_ENABLED = ((_a = process.env.GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION) !== null && _a !== void 0 ? _a : 'true') === 'true'; +const defaultSuccessRateEjectionConfig = { + stdev_factor: 1900, + enforcement_percentage: 100, + minimum_hosts: 5, + request_volume: 100, +}; +const defaultFailurePercentageEjectionConfig = { + threshold: 85, + enforcement_percentage: 100, + minimum_hosts: 5, + request_volume: 50, +}; +function validateFieldType(obj, fieldName, expectedType, objectName) { + if (fieldName in obj && + obj[fieldName] !== undefined && + typeof obj[fieldName] !== expectedType) { + const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; + throw new Error(`outlier detection config ${fullFieldName} parse error: expected ${expectedType}, got ${typeof obj[fieldName]}`); + } +} +function validatePositiveDuration(obj, fieldName, objectName) { + const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; + if (fieldName in obj && obj[fieldName] !== undefined) { + if (!(0, duration_1.isDuration)(obj[fieldName])) { + throw new Error(`outlier detection config ${fullFieldName} parse error: expected Duration, got ${typeof obj[fieldName]}`); + } + if (!(obj[fieldName].seconds >= 0 && + obj[fieldName].seconds <= 315576000000 && + obj[fieldName].nanos >= 0 && + obj[fieldName].nanos <= 999999999)) { + throw new Error(`outlier detection config ${fullFieldName} parse error: values out of range for non-negative Duaration`); + } + } +} +function validatePercentage(obj, fieldName, objectName) { + const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; + validateFieldType(obj, fieldName, 'number', objectName); + if (fieldName in obj && + obj[fieldName] !== undefined && + !(obj[fieldName] >= 0 && obj[fieldName] <= 100)) { + throw new Error(`outlier detection config ${fullFieldName} parse error: value out of range for percentage (0-100)`); + } +} +class OutlierDetectionLoadBalancingConfig { + constructor(intervalMs, baseEjectionTimeMs, maxEjectionTimeMs, maxEjectionPercent, successRateEjection, failurePercentageEjection, childPolicy) { + this.childPolicy = childPolicy; + if (childPolicy.getLoadBalancerName() === 'pick_first') { + throw new Error('outlier_detection LB policy cannot have a pick_first child policy'); + } + this.intervalMs = intervalMs !== null && intervalMs !== void 0 ? intervalMs : 10000; + this.baseEjectionTimeMs = baseEjectionTimeMs !== null && baseEjectionTimeMs !== void 0 ? baseEjectionTimeMs : 30000; + this.maxEjectionTimeMs = maxEjectionTimeMs !== null && maxEjectionTimeMs !== void 0 ? maxEjectionTimeMs : 300000; + this.maxEjectionPercent = maxEjectionPercent !== null && maxEjectionPercent !== void 0 ? maxEjectionPercent : 10; + this.successRateEjection = successRateEjection + ? Object.assign(Object.assign({}, defaultSuccessRateEjectionConfig), successRateEjection) : null; + this.failurePercentageEjection = failurePercentageEjection + ? Object.assign(Object.assign({}, defaultFailurePercentageEjectionConfig), failurePercentageEjection) : null; + } + getLoadBalancerName() { + return TYPE_NAME; + } + toJsonObject() { + var _a, _b; + return { + outlier_detection: { + interval: (0, duration_1.msToDuration)(this.intervalMs), + base_ejection_time: (0, duration_1.msToDuration)(this.baseEjectionTimeMs), + max_ejection_time: (0, duration_1.msToDuration)(this.maxEjectionTimeMs), + max_ejection_percent: this.maxEjectionPercent, + success_rate_ejection: (_a = this.successRateEjection) !== null && _a !== void 0 ? _a : undefined, + failure_percentage_ejection: (_b = this.failurePercentageEjection) !== null && _b !== void 0 ? _b : undefined, + child_policy: [this.childPolicy.toJsonObject()], + }, + }; + } + getIntervalMs() { + return this.intervalMs; + } + getBaseEjectionTimeMs() { + return this.baseEjectionTimeMs; + } + getMaxEjectionTimeMs() { + return this.maxEjectionTimeMs; + } + getMaxEjectionPercent() { + return this.maxEjectionPercent; + } + getSuccessRateEjectionConfig() { + return this.successRateEjection; + } + getFailurePercentageEjectionConfig() { + return this.failurePercentageEjection; + } + getChildPolicy() { + return this.childPolicy; + } + static createFromJson(obj) { + var _a; + validatePositiveDuration(obj, 'interval'); + validatePositiveDuration(obj, 'base_ejection_time'); + validatePositiveDuration(obj, 'max_ejection_time'); + validatePercentage(obj, 'max_ejection_percent'); + if ('success_rate_ejection' in obj && + obj.success_rate_ejection !== undefined) { + if (typeof obj.success_rate_ejection !== 'object') { + throw new Error('outlier detection config success_rate_ejection must be an object'); + } + validateFieldType(obj.success_rate_ejection, 'stdev_factor', 'number', 'success_rate_ejection'); + validatePercentage(obj.success_rate_ejection, 'enforcement_percentage', 'success_rate_ejection'); + validateFieldType(obj.success_rate_ejection, 'minimum_hosts', 'number', 'success_rate_ejection'); + validateFieldType(obj.success_rate_ejection, 'request_volume', 'number', 'success_rate_ejection'); + } + if ('failure_percentage_ejection' in obj && + obj.failure_percentage_ejection !== undefined) { + if (typeof obj.failure_percentage_ejection !== 'object') { + throw new Error('outlier detection config failure_percentage_ejection must be an object'); + } + validatePercentage(obj.failure_percentage_ejection, 'threshold', 'failure_percentage_ejection'); + validatePercentage(obj.failure_percentage_ejection, 'enforcement_percentage', 'failure_percentage_ejection'); + validateFieldType(obj.failure_percentage_ejection, 'minimum_hosts', 'number', 'failure_percentage_ejection'); + validateFieldType(obj.failure_percentage_ejection, 'request_volume', 'number', 'failure_percentage_ejection'); + } + if (!('child_policy' in obj) || !Array.isArray(obj.child_policy)) { + throw new Error('outlier detection config child_policy must be an array'); + } + const childPolicy = (0, load_balancer_1.selectLbConfigFromList)(obj.child_policy); + if (!childPolicy) { + throw new Error('outlier detection config child_policy: no valid recognized policy found'); + } + return new OutlierDetectionLoadBalancingConfig(obj.interval ? (0, duration_1.durationToMs)(obj.interval) : null, obj.base_ejection_time ? (0, duration_1.durationToMs)(obj.base_ejection_time) : null, obj.max_ejection_time ? (0, duration_1.durationToMs)(obj.max_ejection_time) : null, (_a = obj.max_ejection_percent) !== null && _a !== void 0 ? _a : null, obj.success_rate_ejection, obj.failure_percentage_ejection, childPolicy); + } +} +exports.OutlierDetectionLoadBalancingConfig = OutlierDetectionLoadBalancingConfig; +class OutlierDetectionSubchannelWrapper extends subchannel_interface_1.BaseSubchannelWrapper { + constructor(childSubchannel, mapEntry) { + super(childSubchannel); + this.mapEntry = mapEntry; + this.refCount = 0; + } + ref() { + this.child.ref(); + this.refCount += 1; + } + unref() { + this.child.unref(); + this.refCount -= 1; + if (this.refCount <= 0) { + if (this.mapEntry) { + const index = this.mapEntry.subchannelWrappers.indexOf(this); + if (index >= 0) { + this.mapEntry.subchannelWrappers.splice(index, 1); + } + } + } + } + eject() { + this.setHealthy(false); + } + uneject() { + this.setHealthy(true); + } + getMapEntry() { + return this.mapEntry; + } + getWrappedSubchannel() { + return this.child; + } +} +function createEmptyBucket() { + return { + success: 0, + failure: 0, + }; +} +class CallCounter { + constructor() { + this.activeBucket = createEmptyBucket(); + this.inactiveBucket = createEmptyBucket(); + } + addSuccess() { + this.activeBucket.success += 1; + } + addFailure() { + this.activeBucket.failure += 1; + } + switchBuckets() { + this.inactiveBucket = this.activeBucket; + this.activeBucket = createEmptyBucket(); + } + getLastSuccesses() { + return this.inactiveBucket.success; + } + getLastFailures() { + return this.inactiveBucket.failure; + } +} +class OutlierDetectionPicker { + constructor(wrappedPicker, countCalls) { + this.wrappedPicker = wrappedPicker; + this.countCalls = countCalls; + } + pick(pickArgs) { + const wrappedPick = this.wrappedPicker.pick(pickArgs); + if (wrappedPick.pickResultType === picker_1.PickResultType.COMPLETE) { + const subchannelWrapper = wrappedPick.subchannel; + const mapEntry = subchannelWrapper.getMapEntry(); + if (mapEntry) { + let onCallEnded = wrappedPick.onCallEnded; + if (this.countCalls) { + onCallEnded = (statusCode, details, metadata) => { + var _a; + if (statusCode === constants_1.Status.OK) { + mapEntry.counter.addSuccess(); + } + else { + mapEntry.counter.addFailure(); + } + (_a = wrappedPick.onCallEnded) === null || _a === void 0 ? void 0 : _a.call(wrappedPick, statusCode, details, metadata); + }; + } + return Object.assign(Object.assign({}, wrappedPick), { subchannel: subchannelWrapper.getWrappedSubchannel(), onCallEnded: onCallEnded }); + } + else { + return Object.assign(Object.assign({}, wrappedPick), { subchannel: subchannelWrapper.getWrappedSubchannel() }); + } + } + else { + return wrappedPick; + } + } +} +class OutlierDetectionLoadBalancer { + constructor(channelControlHelper) { + this.entryMap = new subchannel_address_1.EndpointMap(); + this.latestConfig = null; + this.timerStartTime = null; + this.childBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler((0, experimental_1.createChildChannelControlHelper)(channelControlHelper, { + createSubchannel: (subchannelAddress, subchannelArgs) => { + const originalSubchannel = channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); + const mapEntry = this.entryMap.getForSubchannelAddress(subchannelAddress); + const subchannelWrapper = new OutlierDetectionSubchannelWrapper(originalSubchannel, mapEntry); + if ((mapEntry === null || mapEntry === void 0 ? void 0 : mapEntry.currentEjectionTimestamp) !== null) { + // If the address is ejected, propagate that to the new subchannel wrapper + subchannelWrapper.eject(); + } + mapEntry === null || mapEntry === void 0 ? void 0 : mapEntry.subchannelWrappers.push(subchannelWrapper); + return subchannelWrapper; + }, + updateState: (connectivityState, picker, errorMessage) => { + if (connectivityState === connectivity_state_1.ConnectivityState.READY) { + channelControlHelper.updateState(connectivityState, new OutlierDetectionPicker(picker, this.isCountingEnabled()), errorMessage); + } + else { + channelControlHelper.updateState(connectivityState, picker, errorMessage); + } + }, + })); + this.ejectionTimer = setInterval(() => { }, 0); + clearInterval(this.ejectionTimer); + } + isCountingEnabled() { + return (this.latestConfig !== null && + (this.latestConfig.getSuccessRateEjectionConfig() !== null || + this.latestConfig.getFailurePercentageEjectionConfig() !== null)); + } + getCurrentEjectionPercent() { + let ejectionCount = 0; + for (const mapEntry of this.entryMap.values()) { + if (mapEntry.currentEjectionTimestamp !== null) { + ejectionCount += 1; + } + } + return (ejectionCount * 100) / this.entryMap.size; + } + runSuccessRateCheck(ejectionTimestamp) { + if (!this.latestConfig) { + return; + } + const successRateConfig = this.latestConfig.getSuccessRateEjectionConfig(); + if (!successRateConfig) { + return; + } + trace('Running success rate check'); + // Step 1 + const targetRequestVolume = successRateConfig.request_volume; + let addresesWithTargetVolume = 0; + const successRates = []; + for (const [endpoint, mapEntry] of this.entryMap.entries()) { + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + trace('Stats for ' + + (0, subchannel_address_1.endpointToString)(endpoint) + + ': successes=' + + successes + + ' failures=' + + failures + + ' targetRequestVolume=' + + targetRequestVolume); + if (successes + failures >= targetRequestVolume) { + addresesWithTargetVolume += 1; + successRates.push(successes / (successes + failures)); + } + } + trace('Found ' + + addresesWithTargetVolume + + ' success rate candidates; currentEjectionPercent=' + + this.getCurrentEjectionPercent() + + ' successRates=[' + + successRates + + ']'); + if (addresesWithTargetVolume < successRateConfig.minimum_hosts) { + return; + } + // Step 2 + const successRateMean = successRates.reduce((a, b) => a + b) / successRates.length; + let successRateDeviationSum = 0; + for (const rate of successRates) { + const deviation = rate - successRateMean; + successRateDeviationSum += deviation * deviation; + } + const successRateVariance = successRateDeviationSum / successRates.length; + const successRateStdev = Math.sqrt(successRateVariance); + const ejectionThreshold = successRateMean - + successRateStdev * (successRateConfig.stdev_factor / 1000); + trace('stdev=' + successRateStdev + ' ejectionThreshold=' + ejectionThreshold); + // Step 3 + for (const [address, mapEntry] of this.entryMap.entries()) { + // Step 3.i + if (this.getCurrentEjectionPercent() >= + this.latestConfig.getMaxEjectionPercent()) { + break; + } + // Step 3.ii + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + if (successes + failures < targetRequestVolume) { + continue; + } + // Step 3.iii + const successRate = successes / (successes + failures); + trace('Checking candidate ' + address + ' successRate=' + successRate); + if (successRate < ejectionThreshold) { + const randomNumber = Math.random() * 100; + trace('Candidate ' + + address + + ' randomNumber=' + + randomNumber + + ' enforcement_percentage=' + + successRateConfig.enforcement_percentage); + if (randomNumber < successRateConfig.enforcement_percentage) { + trace('Ejecting candidate ' + address); + this.eject(mapEntry, ejectionTimestamp); + } + } + } + } + runFailurePercentageCheck(ejectionTimestamp) { + if (!this.latestConfig) { + return; + } + const failurePercentageConfig = this.latestConfig.getFailurePercentageEjectionConfig(); + if (!failurePercentageConfig) { + return; + } + trace('Running failure percentage check. threshold=' + + failurePercentageConfig.threshold + + ' request volume threshold=' + + failurePercentageConfig.request_volume); + // Step 1 + let addressesWithTargetVolume = 0; + for (const mapEntry of this.entryMap.values()) { + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + if (successes + failures >= failurePercentageConfig.request_volume) { + addressesWithTargetVolume += 1; + } + } + if (addressesWithTargetVolume < failurePercentageConfig.minimum_hosts) { + return; + } + // Step 2 + for (const [address, mapEntry] of this.entryMap.entries()) { + // Step 2.i + if (this.getCurrentEjectionPercent() >= + this.latestConfig.getMaxEjectionPercent()) { + break; + } + // Step 2.ii + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + trace('Candidate successes=' + successes + ' failures=' + failures); + if (successes + failures < failurePercentageConfig.request_volume) { + continue; + } + // Step 2.iii + const failurePercentage = (failures * 100) / (failures + successes); + if (failurePercentage > failurePercentageConfig.threshold) { + const randomNumber = Math.random() * 100; + trace('Candidate ' + + address + + ' randomNumber=' + + randomNumber + + ' enforcement_percentage=' + + failurePercentageConfig.enforcement_percentage); + if (randomNumber < failurePercentageConfig.enforcement_percentage) { + trace('Ejecting candidate ' + address); + this.eject(mapEntry, ejectionTimestamp); + } + } + } + } + eject(mapEntry, ejectionTimestamp) { + mapEntry.currentEjectionTimestamp = new Date(); + mapEntry.ejectionTimeMultiplier += 1; + for (const subchannelWrapper of mapEntry.subchannelWrappers) { + subchannelWrapper.eject(); + } + } + uneject(mapEntry) { + mapEntry.currentEjectionTimestamp = null; + for (const subchannelWrapper of mapEntry.subchannelWrappers) { + subchannelWrapper.uneject(); + } + } + switchAllBuckets() { + for (const mapEntry of this.entryMap.values()) { + mapEntry.counter.switchBuckets(); + } + } + startTimer(delayMs) { + var _a, _b; + this.ejectionTimer = setTimeout(() => this.runChecks(), delayMs); + (_b = (_a = this.ejectionTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + runChecks() { + const ejectionTimestamp = new Date(); + trace('Ejection timer running'); + this.switchAllBuckets(); + if (!this.latestConfig) { + return; + } + this.timerStartTime = ejectionTimestamp; + this.startTimer(this.latestConfig.getIntervalMs()); + this.runSuccessRateCheck(ejectionTimestamp); + this.runFailurePercentageCheck(ejectionTimestamp); + for (const [address, mapEntry] of this.entryMap.entries()) { + if (mapEntry.currentEjectionTimestamp === null) { + if (mapEntry.ejectionTimeMultiplier > 0) { + mapEntry.ejectionTimeMultiplier -= 1; + } + } + else { + const baseEjectionTimeMs = this.latestConfig.getBaseEjectionTimeMs(); + const maxEjectionTimeMs = this.latestConfig.getMaxEjectionTimeMs(); + const returnTime = new Date(mapEntry.currentEjectionTimestamp.getTime()); + returnTime.setMilliseconds(returnTime.getMilliseconds() + + Math.min(baseEjectionTimeMs * mapEntry.ejectionTimeMultiplier, Math.max(baseEjectionTimeMs, maxEjectionTimeMs))); + if (returnTime < new Date()) { + trace('Unejecting ' + address); + this.uneject(mapEntry); + } + } + } + } + updateAddressList(endpointList, lbConfig, options, resolutionNote) { + if (!(lbConfig instanceof OutlierDetectionLoadBalancingConfig)) { + return false; + } + trace('Received update with config: ' + JSON.stringify(lbConfig.toJsonObject(), undefined, 2)); + if (endpointList.ok) { + for (const endpoint of endpointList.value) { + if (!this.entryMap.has(endpoint)) { + trace('Adding map entry for ' + (0, subchannel_address_1.endpointToString)(endpoint)); + this.entryMap.set(endpoint, { + counter: new CallCounter(), + currentEjectionTimestamp: null, + ejectionTimeMultiplier: 0, + subchannelWrappers: [], + }); + } + } + this.entryMap.deleteMissing(endpointList.value); + } + const childPolicy = lbConfig.getChildPolicy(); + this.childBalancer.updateAddressList(endpointList, childPolicy, options, resolutionNote); + if (lbConfig.getSuccessRateEjectionConfig() || + lbConfig.getFailurePercentageEjectionConfig()) { + if (this.timerStartTime) { + trace('Previous timer existed. Replacing timer'); + clearTimeout(this.ejectionTimer); + const remainingDelay = lbConfig.getIntervalMs() - + (new Date().getTime() - this.timerStartTime.getTime()); + this.startTimer(remainingDelay); + } + else { + trace('Starting new timer'); + this.timerStartTime = new Date(); + this.startTimer(lbConfig.getIntervalMs()); + this.switchAllBuckets(); + } + } + else { + trace('Counting disabled. Cancelling timer.'); + this.timerStartTime = null; + clearTimeout(this.ejectionTimer); + for (const mapEntry of this.entryMap.values()) { + this.uneject(mapEntry); + mapEntry.ejectionTimeMultiplier = 0; + } + } + this.latestConfig = lbConfig; + return true; + } + exitIdle() { + this.childBalancer.exitIdle(); + } + resetBackoff() { + this.childBalancer.resetBackoff(); + } + destroy() { + clearTimeout(this.ejectionTimer); + this.childBalancer.destroy(); + } + getTypeName() { + return TYPE_NAME; + } +} +exports.OutlierDetectionLoadBalancer = OutlierDetectionLoadBalancer; +function setup() { + if (OUTLIER_DETECTION_ENABLED) { + (0, experimental_1.registerLoadBalancerType)(TYPE_NAME, OutlierDetectionLoadBalancer, OutlierDetectionLoadBalancingConfig); + } +} +//# sourceMappingURL=load-balancer-outlier-detection.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js.map b/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js.map new file mode 100644 index 0000000..eebff2e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"load-balancer-outlier-detection.js","sourceRoot":"","sources":["../../src/load-balancer-outlier-detection.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;;AAgzBH,sBAQC;AArzBD,6DAAyD;AACzD,2CAAmD;AACnD,yCAA8E;AAC9E,iDAIwB;AACxB,mDAIyB;AACzB,+EAAyE;AACzE,qCAAwE;AACxE,6DAK8B;AAC9B,iEAGgC;AAChC,qCAAqC;AAIrC,MAAM,WAAW,GAAG,mBAAmB,CAAC;AAExC,SAAS,KAAK,CAAC,IAAY;IACzB,OAAO,CAAC,KAAK,CAAC,wBAAY,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;AACvD,CAAC;AAED,MAAM,SAAS,GAAG,mBAAmB,CAAC;AAEtC,MAAM,yBAAyB,GAC7B,CAAC,MAAA,OAAO,CAAC,GAAG,CAAC,0CAA0C,mCAAI,MAAM,CAAC,KAAK,MAAM,CAAC;AA0BhF,MAAM,gCAAgC,GAA8B;IAClE,YAAY,EAAE,IAAI;IAClB,sBAAsB,EAAE,GAAG;IAC3B,aAAa,EAAE,CAAC;IAChB,cAAc,EAAE,GAAG;CACpB,CAAC;AAEF,MAAM,sCAAsC,GAC1C;IACE,SAAS,EAAE,EAAE;IACb,sBAAsB,EAAE,GAAG;IAC3B,aAAa,EAAE,CAAC;IAChB,cAAc,EAAE,EAAE;CACnB,CAAC;AAUJ,SAAS,iBAAiB,CACxB,GAAQ,EACR,SAAiB,EACjB,YAA0B,EAC1B,UAAmB;IAEnB,IACE,SAAS,IAAI,GAAG;QAChB,GAAG,CAAC,SAAS,CAAC,KAAK,SAAS;QAC5B,OAAO,GAAG,CAAC,SAAS,CAAC,KAAK,YAAY,EACtC,CAAC;QACD,MAAM,aAAa,GAAG,UAAU,CAAC,CAAC,CAAC,GAAG,UAAU,IAAI,SAAS,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;QAC5E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d,CAAC;IACD,QAAQ;QACN,IAAI,CAAC,aAAa,CAAC,QAAQ,EAAE,CAAC;IAChC,CAAC;IACD,YAAY;QACV,IAAI,CAAC,aAAa,CAAC,YAAY,EAAE,CAAC;IACpC,CAAC;IACD,OAAO;QACL,YAAY,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;QACjC,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,CAAC;IAC/B,CAAC;IACD,WAAW;QACT,OAAO,SAAS,CAAC;IACnB,CAAC;CACF;AA9WD,oEA8WC;AAED,SAAgB,KAAK;IACnB,IAAI,yBAAyB,EAAE,CAAC;QAC9B,IAAA,uCAAwB,EACtB,SAAS,EACT,4BAA4B,EAC5B,mCAAmC,CACpC,CAAC;IACJ,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.d.ts b/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.d.ts new file mode 100644 index 0000000..d49e02b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.d.ts @@ -0,0 +1,134 @@ +import { LoadBalancer, ChannelControlHelper, TypedLoadBalancingConfig } from './load-balancer'; +import { ConnectivityState } from './connectivity-state'; +import { Picker } from './picker'; +import { Endpoint } from './subchannel-address'; +import { ChannelOptions } from './channel-options'; +import { StatusOr } from './call-interface'; +export declare class PickFirstLoadBalancingConfig implements TypedLoadBalancingConfig { + private readonly shuffleAddressList; + constructor(shuffleAddressList: boolean); + getLoadBalancerName(): string; + toJsonObject(): object; + getShuffleAddressList(): boolean; + static createFromJson(obj: any): PickFirstLoadBalancingConfig; +} +/** + * Return a new array with the elements of the input array in a random order + * @param list The input array + * @returns A shuffled array of the elements of list + */ +export declare function shuffled(list: T[]): T[]; +export declare class PickFirstLoadBalancer implements LoadBalancer { + private readonly channelControlHelper; + /** + * The list of subchannels this load balancer is currently attempting to + * connect to. + */ + private children; + /** + * The current connectivity state of the load balancer. + */ + private currentState; + /** + * The index within the `subchannels` array of the subchannel with the most + * recently started connection attempt. + */ + private currentSubchannelIndex; + /** + * The currently picked subchannel used for making calls. Populated if + * and only if the load balancer's current state is READY. In that case, + * the subchannel's current state is also READY. + */ + private currentPick; + /** + * Listener callback attached to each subchannel in the `subchannels` list + * while establishing a connection. + */ + private subchannelStateListener; + private pickedSubchannelHealthListener; + /** + * Timer reference for the timer tracking when to start + */ + private connectionDelayTimeout; + /** + * The LB policy enters sticky TRANSIENT_FAILURE mode when all + * subchannels have failed to connect at least once, and it stays in that + * mode until a connection attempt is successful. While in sticky TF mode, + * the LB policy continuously attempts to connect to all of its subchannels. + */ + private stickyTransientFailureMode; + private reportHealthStatus; + /** + * The most recent error reported by any subchannel as it transitioned to + * TRANSIENT_FAILURE. + */ + private lastError; + private latestAddressList; + private latestOptions; + private latestResolutionNote; + /** + * Load balancer that attempts to connect to each backend in the address list + * in order, and picks the first one that connects, using it for every + * request. + * @param channelControlHelper `ChannelControlHelper` instance provided by + * this load balancer's owner. + */ + constructor(channelControlHelper: ChannelControlHelper); + private allChildrenHaveReportedTF; + private resetChildrenReportedTF; + private calculateAndReportNewState; + private requestReresolution; + private maybeEnterStickyTransientFailureMode; + private removeCurrentPick; + private onSubchannelStateUpdate; + private startNextSubchannelConnecting; + /** + * Have a single subchannel in the `subchannels` list start connecting. + * @param subchannelIndex The index into the `subchannels` list. + */ + private startConnecting; + /** + * Declare that the specified subchannel should be used to make requests. + * This functions the same independent of whether subchannel is a member of + * this.children and whether it is equal to this.currentPick. + * Prerequisite: subchannel.getConnectivityState() === READY. + * @param subchannel + */ + private pickSubchannel; + private updateState; + private resetSubchannelList; + private connectToAddressList; + updateAddressList(maybeEndpointList: StatusOr, lbConfig: TypedLoadBalancingConfig, options: ChannelOptions, resolutionNote: string): boolean; + exitIdle(): void; + resetBackoff(): void; + destroy(): void; + getTypeName(): string; +} +/** + * This class handles the leaf load balancing operations for a single endpoint. + * It is a thin wrapper around a PickFirstLoadBalancer with a different API + * that more closely reflects how it will be used as a leaf balancer. + */ +export declare class LeafLoadBalancer { + private endpoint; + private options; + private resolutionNote; + private pickFirstBalancer; + private latestState; + private latestPicker; + constructor(endpoint: Endpoint, channelControlHelper: ChannelControlHelper, options: ChannelOptions, resolutionNote: string); + startConnecting(): void; + /** + * Update the endpoint associated with this LeafLoadBalancer to a new + * endpoint. Does not trigger connection establishment if a connection + * attempt is not already in progress. + * @param newEndpoint + */ + updateEndpoint(newEndpoint: Endpoint, newOptions: ChannelOptions): void; + getConnectivityState(): ConnectivityState; + getPicker(): Picker; + getEndpoint(): Endpoint; + exitIdle(): void; + destroy(): void; +} +export declare function setup(): void; diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js b/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js new file mode 100644 index 0000000..c68ef12 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js @@ -0,0 +1,514 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LeafLoadBalancer = exports.PickFirstLoadBalancer = exports.PickFirstLoadBalancingConfig = void 0; +exports.shuffled = shuffled; +exports.setup = setup; +const load_balancer_1 = require("./load-balancer"); +const connectivity_state_1 = require("./connectivity-state"); +const picker_1 = require("./picker"); +const subchannel_address_1 = require("./subchannel-address"); +const logging = require("./logging"); +const constants_1 = require("./constants"); +const subchannel_address_2 = require("./subchannel-address"); +const net_1 = require("net"); +const call_interface_1 = require("./call-interface"); +const TRACER_NAME = 'pick_first'; +function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); +} +const TYPE_NAME = 'pick_first'; +/** + * Delay after starting a connection on a subchannel before starting a + * connection on the next subchannel in the list, for Happy Eyeballs algorithm. + */ +const CONNECTION_DELAY_INTERVAL_MS = 250; +class PickFirstLoadBalancingConfig { + constructor(shuffleAddressList) { + this.shuffleAddressList = shuffleAddressList; + } + getLoadBalancerName() { + return TYPE_NAME; + } + toJsonObject() { + return { + [TYPE_NAME]: { + shuffleAddressList: this.shuffleAddressList, + }, + }; + } + getShuffleAddressList() { + return this.shuffleAddressList; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static createFromJson(obj) { + if ('shuffleAddressList' in obj && + !(typeof obj.shuffleAddressList === 'boolean')) { + throw new Error('pick_first config field shuffleAddressList must be a boolean if provided'); + } + return new PickFirstLoadBalancingConfig(obj.shuffleAddressList === true); + } +} +exports.PickFirstLoadBalancingConfig = PickFirstLoadBalancingConfig; +/** + * Picker for a `PickFirstLoadBalancer` in the READY state. Always returns the + * picked subchannel. + */ +class PickFirstPicker { + constructor(subchannel) { + this.subchannel = subchannel; + } + pick(pickArgs) { + return { + pickResultType: picker_1.PickResultType.COMPLETE, + subchannel: this.subchannel, + status: null, + onCallStarted: null, + onCallEnded: null, + }; + } +} +/** + * Return a new array with the elements of the input array in a random order + * @param list The input array + * @returns A shuffled array of the elements of list + */ +function shuffled(list) { + const result = list.slice(); + for (let i = result.length - 1; i > 1; i--) { + const j = Math.floor(Math.random() * (i + 1)); + const temp = result[i]; + result[i] = result[j]; + result[j] = temp; + } + return result; +} +/** + * Interleave addresses in addressList by family in accordance with RFC-8304 section 4 + * @param addressList + * @returns + */ +function interleaveAddressFamilies(addressList) { + if (addressList.length === 0) { + return []; + } + const result = []; + const ipv6Addresses = []; + const ipv4Addresses = []; + const ipv6First = (0, subchannel_address_2.isTcpSubchannelAddress)(addressList[0]) && (0, net_1.isIPv6)(addressList[0].host); + for (const address of addressList) { + if ((0, subchannel_address_2.isTcpSubchannelAddress)(address) && (0, net_1.isIPv6)(address.host)) { + ipv6Addresses.push(address); + } + else { + ipv4Addresses.push(address); + } + } + const firstList = ipv6First ? ipv6Addresses : ipv4Addresses; + const secondList = ipv6First ? ipv4Addresses : ipv6Addresses; + for (let i = 0; i < Math.max(firstList.length, secondList.length); i++) { + if (i < firstList.length) { + result.push(firstList[i]); + } + if (i < secondList.length) { + result.push(secondList[i]); + } + } + return result; +} +const REPORT_HEALTH_STATUS_OPTION_NAME = 'grpc-node.internal.pick-first.report_health_status'; +class PickFirstLoadBalancer { + /** + * Load balancer that attempts to connect to each backend in the address list + * in order, and picks the first one that connects, using it for every + * request. + * @param channelControlHelper `ChannelControlHelper` instance provided by + * this load balancer's owner. + */ + constructor(channelControlHelper) { + this.channelControlHelper = channelControlHelper; + /** + * The list of subchannels this load balancer is currently attempting to + * connect to. + */ + this.children = []; + /** + * The current connectivity state of the load balancer. + */ + this.currentState = connectivity_state_1.ConnectivityState.IDLE; + /** + * The index within the `subchannels` array of the subchannel with the most + * recently started connection attempt. + */ + this.currentSubchannelIndex = 0; + /** + * The currently picked subchannel used for making calls. Populated if + * and only if the load balancer's current state is READY. In that case, + * the subchannel's current state is also READY. + */ + this.currentPick = null; + /** + * Listener callback attached to each subchannel in the `subchannels` list + * while establishing a connection. + */ + this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime, errorMessage) => { + this.onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage); + }; + this.pickedSubchannelHealthListener = () => this.calculateAndReportNewState(); + /** + * The LB policy enters sticky TRANSIENT_FAILURE mode when all + * subchannels have failed to connect at least once, and it stays in that + * mode until a connection attempt is successful. While in sticky TF mode, + * the LB policy continuously attempts to connect to all of its subchannels. + */ + this.stickyTransientFailureMode = false; + this.reportHealthStatus = false; + /** + * The most recent error reported by any subchannel as it transitioned to + * TRANSIENT_FAILURE. + */ + this.lastError = null; + this.latestAddressList = null; + this.latestOptions = {}; + this.latestResolutionNote = ''; + this.connectionDelayTimeout = setTimeout(() => { }, 0); + clearTimeout(this.connectionDelayTimeout); + } + allChildrenHaveReportedTF() { + return this.children.every(child => child.hasReportedTransientFailure); + } + resetChildrenReportedTF() { + this.children.every(child => child.hasReportedTransientFailure = false); + } + calculateAndReportNewState() { + var _a; + if (this.currentPick) { + if (this.reportHealthStatus && !this.currentPick.isHealthy()) { + const errorMessage = `Picked subchannel ${this.currentPick.getAddress()} is unhealthy`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ + details: errorMessage, + }), errorMessage); + } + else { + this.updateState(connectivity_state_1.ConnectivityState.READY, new PickFirstPicker(this.currentPick), null); + } + } + else if (((_a = this.latestAddressList) === null || _a === void 0 ? void 0 : _a.length) === 0) { + const errorMessage = `No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ + details: errorMessage, + }), errorMessage); + } + else if (this.children.length === 0) { + this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); + } + else { + if (this.stickyTransientFailureMode) { + const errorMessage = `No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ + details: errorMessage, + }), errorMessage); + } + else { + this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); + } + } + } + requestReresolution() { + this.channelControlHelper.requestReresolution(); + } + maybeEnterStickyTransientFailureMode() { + if (!this.allChildrenHaveReportedTF()) { + return; + } + this.requestReresolution(); + this.resetChildrenReportedTF(); + if (this.stickyTransientFailureMode) { + this.calculateAndReportNewState(); + return; + } + this.stickyTransientFailureMode = true; + for (const { subchannel } of this.children) { + subchannel.startConnecting(); + } + this.calculateAndReportNewState(); + } + removeCurrentPick() { + if (this.currentPick !== null) { + this.currentPick.removeConnectivityStateListener(this.subchannelStateListener); + this.channelControlHelper.removeChannelzChild(this.currentPick.getChannelzRef()); + this.currentPick.removeHealthStateWatcher(this.pickedSubchannelHealthListener); + // Unref last, to avoid triggering listeners + this.currentPick.unref(); + this.currentPick = null; + } + } + onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage) { + var _a; + if ((_a = this.currentPick) === null || _a === void 0 ? void 0 : _a.realSubchannelEquals(subchannel)) { + if (newState !== connectivity_state_1.ConnectivityState.READY) { + this.removeCurrentPick(); + this.calculateAndReportNewState(); + } + return; + } + for (const [index, child] of this.children.entries()) { + if (subchannel.realSubchannelEquals(child.subchannel)) { + if (newState === connectivity_state_1.ConnectivityState.READY) { + this.pickSubchannel(child.subchannel); + } + if (newState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { + child.hasReportedTransientFailure = true; + if (errorMessage) { + this.lastError = errorMessage; + } + this.maybeEnterStickyTransientFailureMode(); + if (index === this.currentSubchannelIndex) { + this.startNextSubchannelConnecting(index + 1); + } + } + child.subchannel.startConnecting(); + return; + } + } + } + startNextSubchannelConnecting(startIndex) { + clearTimeout(this.connectionDelayTimeout); + for (const [index, child] of this.children.entries()) { + if (index >= startIndex) { + const subchannelState = child.subchannel.getConnectivityState(); + if (subchannelState === connectivity_state_1.ConnectivityState.IDLE || + subchannelState === connectivity_state_1.ConnectivityState.CONNECTING) { + this.startConnecting(index); + return; + } + } + } + this.maybeEnterStickyTransientFailureMode(); + } + /** + * Have a single subchannel in the `subchannels` list start connecting. + * @param subchannelIndex The index into the `subchannels` list. + */ + startConnecting(subchannelIndex) { + var _a, _b; + clearTimeout(this.connectionDelayTimeout); + this.currentSubchannelIndex = subchannelIndex; + if (this.children[subchannelIndex].subchannel.getConnectivityState() === + connectivity_state_1.ConnectivityState.IDLE) { + trace('Start connecting to subchannel with address ' + + this.children[subchannelIndex].subchannel.getAddress()); + process.nextTick(() => { + var _a; + (_a = this.children[subchannelIndex]) === null || _a === void 0 ? void 0 : _a.subchannel.startConnecting(); + }); + } + this.connectionDelayTimeout = setTimeout(() => { + this.startNextSubchannelConnecting(subchannelIndex + 1); + }, CONNECTION_DELAY_INTERVAL_MS); + (_b = (_a = this.connectionDelayTimeout).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + /** + * Declare that the specified subchannel should be used to make requests. + * This functions the same independent of whether subchannel is a member of + * this.children and whether it is equal to this.currentPick. + * Prerequisite: subchannel.getConnectivityState() === READY. + * @param subchannel + */ + pickSubchannel(subchannel) { + trace('Pick subchannel with address ' + subchannel.getAddress()); + this.stickyTransientFailureMode = false; + /* Ref before removeCurrentPick and resetSubchannelList to avoid the + * refcount dropping to 0 during this process. */ + subchannel.ref(); + this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef()); + this.removeCurrentPick(); + this.resetSubchannelList(); + subchannel.addConnectivityStateListener(this.subchannelStateListener); + subchannel.addHealthStateWatcher(this.pickedSubchannelHealthListener); + this.currentPick = subchannel; + clearTimeout(this.connectionDelayTimeout); + this.calculateAndReportNewState(); + } + updateState(newState, picker, errorMessage) { + trace(connectivity_state_1.ConnectivityState[this.currentState] + + ' -> ' + + connectivity_state_1.ConnectivityState[newState]); + this.currentState = newState; + this.channelControlHelper.updateState(newState, picker, errorMessage); + } + resetSubchannelList() { + for (const child of this.children) { + /* Always remoev the connectivity state listener. If the subchannel is + getting picked, it will be re-added then. */ + child.subchannel.removeConnectivityStateListener(this.subchannelStateListener); + /* Refs are counted independently for the children list and the + * currentPick, so we call unref whether or not the child is the + * currentPick. Channelz child references are also refcounted, so + * removeChannelzChild can be handled the same way. */ + child.subchannel.unref(); + this.channelControlHelper.removeChannelzChild(child.subchannel.getChannelzRef()); + } + this.currentSubchannelIndex = 0; + this.children = []; + } + connectToAddressList(addressList, options) { + trace('connectToAddressList([' + addressList.map(address => (0, subchannel_address_1.subchannelAddressToString)(address)) + '])'); + const newChildrenList = addressList.map(address => ({ + subchannel: this.channelControlHelper.createSubchannel(address, options), + hasReportedTransientFailure: false, + })); + for (const { subchannel } of newChildrenList) { + if (subchannel.getConnectivityState() === connectivity_state_1.ConnectivityState.READY) { + this.pickSubchannel(subchannel); + return; + } + } + /* Ref each subchannel before resetting the list, to ensure that + * subchannels shared between the list don't drop to 0 refs during the + * transition. */ + for (const { subchannel } of newChildrenList) { + subchannel.ref(); + this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef()); + } + this.resetSubchannelList(); + this.children = newChildrenList; + for (const { subchannel } of this.children) { + subchannel.addConnectivityStateListener(this.subchannelStateListener); + } + for (const child of this.children) { + if (child.subchannel.getConnectivityState() === + connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { + child.hasReportedTransientFailure = true; + } + } + this.startNextSubchannelConnecting(0); + this.calculateAndReportNewState(); + } + updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { + if (!(lbConfig instanceof PickFirstLoadBalancingConfig)) { + return false; + } + if (!maybeEndpointList.ok) { + if (this.children.length === 0 && this.currentPick === null) { + this.channelControlHelper.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); + } + return true; + } + let endpointList = maybeEndpointList.value; + this.reportHealthStatus = options[REPORT_HEALTH_STATUS_OPTION_NAME]; + /* Previously, an update would be discarded if it was identical to the + * previous update, to minimize churn. Now the DNS resolver is + * rate-limited, so that is less of a concern. */ + if (lbConfig.getShuffleAddressList()) { + endpointList = shuffled(endpointList); + } + const rawAddressList = [].concat(...endpointList.map(endpoint => endpoint.addresses)); + trace('updateAddressList([' + rawAddressList.map(address => (0, subchannel_address_1.subchannelAddressToString)(address)) + '])'); + const addressList = interleaveAddressFamilies(rawAddressList); + this.latestAddressList = addressList; + this.latestOptions = options; + this.connectToAddressList(addressList, options); + this.latestResolutionNote = resolutionNote; + if (rawAddressList.length > 0) { + return true; + } + else { + this.lastError = 'No addresses resolved'; + return false; + } + } + exitIdle() { + if (this.currentState === connectivity_state_1.ConnectivityState.IDLE && + this.latestAddressList) { + this.connectToAddressList(this.latestAddressList, this.latestOptions); + } + } + resetBackoff() { + /* The pick first load balancer does not have a connection backoff, so this + * does nothing */ + } + destroy() { + this.resetSubchannelList(); + this.removeCurrentPick(); + } + getTypeName() { + return TYPE_NAME; + } +} +exports.PickFirstLoadBalancer = PickFirstLoadBalancer; +const LEAF_CONFIG = new PickFirstLoadBalancingConfig(false); +/** + * This class handles the leaf load balancing operations for a single endpoint. + * It is a thin wrapper around a PickFirstLoadBalancer with a different API + * that more closely reflects how it will be used as a leaf balancer. + */ +class LeafLoadBalancer { + constructor(endpoint, channelControlHelper, options, resolutionNote) { + this.endpoint = endpoint; + this.options = options; + this.resolutionNote = resolutionNote; + this.latestState = connectivity_state_1.ConnectivityState.IDLE; + const childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, { + updateState: (connectivityState, picker, errorMessage) => { + this.latestState = connectivityState; + this.latestPicker = picker; + channelControlHelper.updateState(connectivityState, picker, errorMessage); + }, + }); + this.pickFirstBalancer = new PickFirstLoadBalancer(childChannelControlHelper); + this.latestPicker = new picker_1.QueuePicker(this.pickFirstBalancer); + } + startConnecting() { + this.pickFirstBalancer.updateAddressList((0, call_interface_1.statusOrFromValue)([this.endpoint]), LEAF_CONFIG, Object.assign(Object.assign({}, this.options), { [REPORT_HEALTH_STATUS_OPTION_NAME]: true }), this.resolutionNote); + } + /** + * Update the endpoint associated with this LeafLoadBalancer to a new + * endpoint. Does not trigger connection establishment if a connection + * attempt is not already in progress. + * @param newEndpoint + */ + updateEndpoint(newEndpoint, newOptions) { + this.options = newOptions; + this.endpoint = newEndpoint; + if (this.latestState !== connectivity_state_1.ConnectivityState.IDLE) { + this.startConnecting(); + } + } + getConnectivityState() { + return this.latestState; + } + getPicker() { + return this.latestPicker; + } + getEndpoint() { + return this.endpoint; + } + exitIdle() { + this.pickFirstBalancer.exitIdle(); + } + destroy() { + this.pickFirstBalancer.destroy(); + } +} +exports.LeafLoadBalancer = LeafLoadBalancer; +function setup() { + (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, PickFirstLoadBalancer, PickFirstLoadBalancingConfig); + (0, load_balancer_1.registerDefaultLoadBalancerType)(TYPE_NAME); +} +//# sourceMappingURL=load-balancer-pick-first.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js.map b/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js.map new file mode 100644 index 0000000..2735cd3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js.map @@ -0,0 +1 @@ +{"version":3,"file":"load-balancer-pick-first.js","sourceRoot":"","sources":["../../src/load-balancer-pick-first.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AA2GH,4BASC;AA2gBD,sBAOC;AApoBD,mDAOyB;AACzB,6DAAyD;AACzD,qCAOkB;AAClB,6DAA8F;AAC9F,qCAAqC;AACrC,2CAA2C;AAM3C,6DAA8D;AAC9D,6BAA6B;AAE7B,qDAA+D;AAE/D,MAAM,WAAW,GAAG,YAAY,CAAC;AAEjC,SAAS,KAAK,CAAC,IAAY;IACzB,OAAO,CAAC,KAAK,CAAC,wBAAY,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;AACvD,CAAC;AAED,MAAM,SAAS,GAAG,YAAY,CAAC;AAE/B;;;GAGG;AACH,MAAM,4BAA4B,GAAG,GAAG,CAAC;AAEzC,MAAa,4BAA4B;IACvC,YAA6B,kBAA2B;QAA3B,uBAAkB,GAAlB,kBAAkB,CAAS;IAAG,CAAC;IAE5D,mBAAmB;QACjB,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,YAAY;QACV,OAAO;YACL,CAAC,SAAS,CAAC,EAAE;gBACX,kBAAkB,EAAE,IAAI,CAAC,kBAAkB;aAC5C;SACF,CAAC;IACJ,CAAC;IAED,qBAAqB;QACnB,OAAO,IAAI,CAAC,kBAAkB,CAAC;IACjC,CAAC;IAED,8DAA8D;IAC9D,MAAM,C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AAC,WAAW,CAAC;IAC1B,CAAC;IAED,SAAS;QACP,OAAO,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;IAED,WAAW;QACT,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED,QAAQ;QACN,IAAI,CAAC,iBAAiB,CAAC,QAAQ,EAAE,CAAC;IACpC,CAAC;IAED,OAAO;QACL,IAAI,CAAC,iBAAiB,CAAC,OAAO,EAAE,CAAC;IACnC,CAAC;CACF;AApED,4CAoEC;AAED,SAAgB,KAAK;IACnB,IAAA,wCAAwB,EACtB,SAAS,EACT,qBAAqB,EACrB,4BAA4B,CAC7B,CAAC;IACF,IAAA,+CAA+B,EAAC,SAAS,CAAC,CAAC;AAC7C,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.d.ts b/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.d.ts new file mode 100644 index 0000000..a7e747f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.d.ts @@ -0,0 +1,24 @@ +import { LoadBalancer, ChannelControlHelper, TypedLoadBalancingConfig } from './load-balancer'; +import { Endpoint } from './subchannel-address'; +import { ChannelOptions } from './channel-options'; +import { StatusOr } from './call-interface'; +export declare class RoundRobinLoadBalancer implements LoadBalancer { + private readonly channelControlHelper; + private children; + private currentState; + private currentReadyPicker; + private updatesPaused; + private childChannelControlHelper; + private lastError; + constructor(channelControlHelper: ChannelControlHelper); + private countChildrenWithState; + private calculateAndUpdateState; + private updateState; + private resetSubchannelList; + updateAddressList(maybeEndpointList: StatusOr, lbConfig: TypedLoadBalancingConfig, options: ChannelOptions, resolutionNote: string): boolean; + exitIdle(): void; + resetBackoff(): void; + destroy(): void; + getTypeName(): string; +} +export declare function setup(): void; diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js b/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js new file mode 100644 index 0000000..a49d0e0 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js @@ -0,0 +1,204 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RoundRobinLoadBalancer = void 0; +exports.setup = setup; +const load_balancer_1 = require("./load-balancer"); +const connectivity_state_1 = require("./connectivity-state"); +const picker_1 = require("./picker"); +const logging = require("./logging"); +const constants_1 = require("./constants"); +const subchannel_address_1 = require("./subchannel-address"); +const load_balancer_pick_first_1 = require("./load-balancer-pick-first"); +const TRACER_NAME = 'round_robin'; +function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); +} +const TYPE_NAME = 'round_robin'; +class RoundRobinLoadBalancingConfig { + getLoadBalancerName() { + return TYPE_NAME; + } + constructor() { } + toJsonObject() { + return { + [TYPE_NAME]: {}, + }; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static createFromJson(obj) { + return new RoundRobinLoadBalancingConfig(); + } +} +class RoundRobinPicker { + constructor(children, nextIndex = 0) { + this.children = children; + this.nextIndex = nextIndex; + } + pick(pickArgs) { + const childPicker = this.children[this.nextIndex].picker; + this.nextIndex = (this.nextIndex + 1) % this.children.length; + return childPicker.pick(pickArgs); + } + /** + * Check what the next subchannel returned would be. Used by the load + * balancer implementation to preserve this part of the picker state if + * possible when a subchannel connects or disconnects. + */ + peekNextEndpoint() { + return this.children[this.nextIndex].endpoint; + } +} +function rotateArray(list, startIndex) { + return [...list.slice(startIndex), ...list.slice(0, startIndex)]; +} +class RoundRobinLoadBalancer { + constructor(channelControlHelper) { + this.channelControlHelper = channelControlHelper; + this.children = []; + this.currentState = connectivity_state_1.ConnectivityState.IDLE; + this.currentReadyPicker = null; + this.updatesPaused = false; + this.lastError = null; + this.childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, { + updateState: (connectivityState, picker, errorMessage) => { + /* Ensure that name resolution is requested again after active + * connections are dropped. This is more aggressive than necessary to + * accomplish that, so we are counting on resolvers to have + * reasonable rate limits. */ + if (this.currentState === connectivity_state_1.ConnectivityState.READY && connectivityState !== connectivity_state_1.ConnectivityState.READY) { + this.channelControlHelper.requestReresolution(); + } + if (errorMessage) { + this.lastError = errorMessage; + } + this.calculateAndUpdateState(); + }, + }); + } + countChildrenWithState(state) { + return this.children.filter(child => child.getConnectivityState() === state) + .length; + } + calculateAndUpdateState() { + if (this.updatesPaused) { + return; + } + if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.READY) > 0) { + const readyChildren = this.children.filter(child => child.getConnectivityState() === connectivity_state_1.ConnectivityState.READY); + let index = 0; + if (this.currentReadyPicker !== null) { + const nextPickedEndpoint = this.currentReadyPicker.peekNextEndpoint(); + index = readyChildren.findIndex(child => (0, subchannel_address_1.endpointEqual)(child.getEndpoint(), nextPickedEndpoint)); + if (index < 0) { + index = 0; + } + } + this.updateState(connectivity_state_1.ConnectivityState.READY, new RoundRobinPicker(readyChildren.map(child => ({ + endpoint: child.getEndpoint(), + picker: child.getPicker(), + })), index), null); + } + else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.CONNECTING) > 0) { + this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); + } + else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) > 0) { + const errorMessage = `round_robin: No connection established. Last error: ${this.lastError}`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ + details: errorMessage, + }), errorMessage); + } + else { + this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); + } + /* round_robin should keep all children connected, this is how we do that. + * We can't do this more efficiently in the individual child's updateState + * callback because that doesn't have a reference to which child the state + * change is associated with. */ + for (const child of this.children) { + if (child.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) { + child.exitIdle(); + } + } + } + updateState(newState, picker, errorMessage) { + trace(connectivity_state_1.ConnectivityState[this.currentState] + + ' -> ' + + connectivity_state_1.ConnectivityState[newState]); + if (newState === connectivity_state_1.ConnectivityState.READY) { + this.currentReadyPicker = picker; + } + else { + this.currentReadyPicker = null; + } + this.currentState = newState; + this.channelControlHelper.updateState(newState, picker, errorMessage); + } + resetSubchannelList() { + for (const child of this.children) { + child.destroy(); + } + this.children = []; + } + updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { + if (!(lbConfig instanceof RoundRobinLoadBalancingConfig)) { + return false; + } + if (!maybeEndpointList.ok) { + if (this.children.length === 0) { + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); + } + return true; + } + const startIndex = (Math.random() * maybeEndpointList.value.length) | 0; + const endpointList = rotateArray(maybeEndpointList.value, startIndex); + this.resetSubchannelList(); + if (endpointList.length === 0) { + const errorMessage = `No addresses resolved. Resolution note: ${resolutionNote}`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ details: errorMessage }), errorMessage); + } + trace('Connect to endpoint list ' + endpointList.map(subchannel_address_1.endpointToString)); + this.updatesPaused = true; + this.children = endpointList.map(endpoint => new load_balancer_pick_first_1.LeafLoadBalancer(endpoint, this.childChannelControlHelper, options, resolutionNote)); + for (const child of this.children) { + child.startConnecting(); + } + this.updatesPaused = false; + this.calculateAndUpdateState(); + return true; + } + exitIdle() { + /* The round_robin LB policy is only in the IDLE state if it has no + * addresses to try to connect to and it has no picked subchannel. + * In that case, there is no meaningful action that can be taken here. */ + } + resetBackoff() { + // This LB policy has no backoff to reset + } + destroy() { + this.resetSubchannelList(); + } + getTypeName() { + return TYPE_NAME; + } +} +exports.RoundRobinLoadBalancer = RoundRobinLoadBalancer; +function setup() { + (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, RoundRobinLoadBalancer, RoundRobinLoadBalancingConfig); +} +//# sourceMappingURL=load-balancer-round-robin.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js.map b/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js.map new file mode 100644 index 0000000..8e5ad1c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js.map @@ -0,0 +1 @@ +{"version":3,"file":"load-balancer-round-robin.js","sourceRoot":"","sources":["../../src/load-balancer-round-robin.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAyQH,sBAMC;AA7QD,mDAMyB;AACzB,6DAAyD;AACzD,qCAMkB;AAClB,qCAAqC;AACrC,2CAA2C;AAC3C,6DAI8B;AAC9B,yEAA8D;AAI9D,MAAM,WAAW,GAAG,aAAa,CAAC;AAElC,SAAS,KAAK,CAAC,IAAY;IACzB,OAAO,CAAC,KAAK,CAAC,wBAAY,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;AACvD,CAAC;AAED,MAAM,SAAS,GAAG,aAAa,CAAC;AAEhC,MAAM,6BAA6B;IACjC,mBAAmB;QACjB,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,gBAAe,CAAC;IAEhB,YAAY;QACV,OAAO;YACL,CAAC,SAAS,CAAC,EAAE,EAAE;SAChB,CAAC;IACJ,CAAC;IAED,8DAA8D;IAC9D,MAAM,CAAC,cAAc,CAAC,GAAQ;QAC5B,OAAO,IAAI,6BAA6B,EAAE,CAAC;IAC7C,CAAC;CACF;AAED,MAAM,gBAAgB;IACpB,YACmB,QAAkD,EAC3D,YAAY,CAAC;QADJ,aAAQ,GAAR,QAAQ,CAA0C;QAC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AAM,YAAY,GAAG,2CAA2C,cAAc,EAAE,CAAC;YACjF,IAAI,CAAC,WAAW,CACd,sCAAiB,CAAC,iBAAiB,EACnC,IAAI,0BAAiB,CAAC,EAAC,OAAO,EAAE,YAAY,EAAC,CAAC,EAC9C,YAAY,CACb,CAAC;QACJ,CAAC;QACD,KAAK,CAAC,2BAA2B,GAAG,YAAY,CAAC,GAAG,CAAC,qCAAgB,CAAC,CAAC,CAAC;QACxE,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC1B,IAAI,CAAC,QAAQ,GAAG,YAAY,CAAC,GAAG,CAC9B,QAAQ,CAAC,EAAE,CACT,IAAI,2CAAgB,CAClB,QAAQ,EACR,IAAI,CAAC,yBAAyB,EAC9B,OAAO,EACP,cAAc,CACf,CACJ,CAAC;QACF,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAClC,KAAK,CAAC,eAAe,EAAE,CAAC;QAC1B,CAAC;QACD,IAAI,CAAC,aAAa,GAAG,KAAK,CAAC;QAC3B,IAAI,CAAC,uBAAuB,EAAE,CAAC;QAC/B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,QAAQ;QACN;;iFAEyE;IAC3E,CAAC;IACD,YAAY;QACV,yCAAyC;IAC3C,CAAC;IACD,OAAO;QACL,IAAI,CAAC,mBAAmB,EAAE,CAAC;IAC7B,CAAC;IACD,WAAW;QACT,OAAO,SAAS,CAAC;IACnB,CAAC;CACF;AAtLD,wDAsLC;AAED,SAAgB,KAAK;IACnB,IAAA,wCAAwB,EACtB,SAAS,EACT,sBAAsB,EACtB,6BAA6B,CAC9B,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.d.ts b/node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.d.ts new file mode 100644 index 0000000..f6838c8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.d.ts @@ -0,0 +1,20 @@ +import { TypedLoadBalancingConfig } from './load-balancer'; +export declare class WeightedRoundRobinLoadBalancingConfig implements TypedLoadBalancingConfig { + private readonly enableOobLoadReport; + private readonly oobLoadReportingPeriodMs; + private readonly blackoutPeriodMs; + private readonly weightExpirationPeriodMs; + private readonly weightUpdatePeriodMs; + private readonly errorUtilizationPenalty; + constructor(enableOobLoadReport: boolean | null, oobLoadReportingPeriodMs: number | null, blackoutPeriodMs: number | null, weightExpirationPeriodMs: number | null, weightUpdatePeriodMs: number | null, errorUtilizationPenalty: number | null); + getLoadBalancerName(): string; + toJsonObject(): object; + static createFromJson(obj: any): WeightedRoundRobinLoadBalancingConfig; + getEnableOobLoadReport(): boolean; + getOobLoadReportingPeriodMs(): number; + getBlackoutPeriodMs(): number; + getWeightExpirationPeriodMs(): number; + getWeightUpdatePeriodMs(): number; + getErrorUtilizationPenalty(): number; +} +export declare function setup(): void; diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.js b/node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.js new file mode 100644 index 0000000..919c36a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.js @@ -0,0 +1,392 @@ +"use strict"; +/* + * Copyright 2025 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WeightedRoundRobinLoadBalancingConfig = void 0; +exports.setup = setup; +const connectivity_state_1 = require("./connectivity-state"); +const constants_1 = require("./constants"); +const duration_1 = require("./duration"); +const load_balancer_1 = require("./load-balancer"); +const load_balancer_pick_first_1 = require("./load-balancer-pick-first"); +const logging = require("./logging"); +const orca_1 = require("./orca"); +const picker_1 = require("./picker"); +const priority_queue_1 = require("./priority-queue"); +const subchannel_address_1 = require("./subchannel-address"); +const TRACER_NAME = 'weighted_round_robin'; +function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); +} +const TYPE_NAME = 'weighted_round_robin'; +const DEFAULT_OOB_REPORTING_PERIOD_MS = 10000; +const DEFAULT_BLACKOUT_PERIOD_MS = 10000; +const DEFAULT_WEIGHT_EXPIRATION_PERIOD_MS = 3 * 60000; +const DEFAULT_WEIGHT_UPDATE_PERIOD_MS = 1000; +const DEFAULT_ERROR_UTILIZATION_PENALTY = 1; +function validateFieldType(obj, fieldName, expectedType) { + if (fieldName in obj && + obj[fieldName] !== undefined && + typeof obj[fieldName] !== expectedType) { + throw new Error(`weighted round robin config ${fieldName} parse error: expected ${expectedType}, got ${typeof obj[fieldName]}`); + } +} +function parseDurationField(obj, fieldName) { + if (fieldName in obj && obj[fieldName] !== undefined && obj[fieldName] !== null) { + let durationObject; + if ((0, duration_1.isDuration)(obj[fieldName])) { + durationObject = obj[fieldName]; + } + else if ((0, duration_1.isDurationMessage)(obj[fieldName])) { + durationObject = (0, duration_1.durationMessageToDuration)(obj[fieldName]); + } + else if (typeof obj[fieldName] === 'string') { + const parsedDuration = (0, duration_1.parseDuration)(obj[fieldName]); + if (!parsedDuration) { + throw new Error(`weighted round robin config ${fieldName}: failed to parse duration string ${obj[fieldName]}`); + } + durationObject = parsedDuration; + } + else { + throw new Error(`weighted round robin config ${fieldName}: expected duration, got ${typeof obj[fieldName]}`); + } + return (0, duration_1.durationToMs)(durationObject); + } + return null; +} +class WeightedRoundRobinLoadBalancingConfig { + constructor(enableOobLoadReport, oobLoadReportingPeriodMs, blackoutPeriodMs, weightExpirationPeriodMs, weightUpdatePeriodMs, errorUtilizationPenalty) { + this.enableOobLoadReport = enableOobLoadReport !== null && enableOobLoadReport !== void 0 ? enableOobLoadReport : false; + this.oobLoadReportingPeriodMs = oobLoadReportingPeriodMs !== null && oobLoadReportingPeriodMs !== void 0 ? oobLoadReportingPeriodMs : DEFAULT_OOB_REPORTING_PERIOD_MS; + this.blackoutPeriodMs = blackoutPeriodMs !== null && blackoutPeriodMs !== void 0 ? blackoutPeriodMs : DEFAULT_BLACKOUT_PERIOD_MS; + this.weightExpirationPeriodMs = weightExpirationPeriodMs !== null && weightExpirationPeriodMs !== void 0 ? weightExpirationPeriodMs : DEFAULT_WEIGHT_EXPIRATION_PERIOD_MS; + this.weightUpdatePeriodMs = Math.max(weightUpdatePeriodMs !== null && weightUpdatePeriodMs !== void 0 ? weightUpdatePeriodMs : DEFAULT_WEIGHT_UPDATE_PERIOD_MS, 100); + this.errorUtilizationPenalty = errorUtilizationPenalty !== null && errorUtilizationPenalty !== void 0 ? errorUtilizationPenalty : DEFAULT_ERROR_UTILIZATION_PENALTY; + } + getLoadBalancerName() { + return TYPE_NAME; + } + toJsonObject() { + return { + enable_oob_load_report: this.enableOobLoadReport, + oob_load_reporting_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.oobLoadReportingPeriodMs)), + blackout_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.blackoutPeriodMs)), + weight_expiration_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.weightExpirationPeriodMs)), + weight_update_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.weightUpdatePeriodMs)), + error_utilization_penalty: this.errorUtilizationPenalty + }; + } + static createFromJson(obj) { + validateFieldType(obj, 'enable_oob_load_report', 'boolean'); + validateFieldType(obj, 'error_utilization_penalty', 'number'); + if (obj.error_utilization_penalty < 0) { + throw new Error('weighted round robin config error_utilization_penalty < 0'); + } + return new WeightedRoundRobinLoadBalancingConfig(obj.enable_oob_load_report, parseDurationField(obj, 'oob_load_reporting_period'), parseDurationField(obj, 'blackout_period'), parseDurationField(obj, 'weight_expiration_period'), parseDurationField(obj, 'weight_update_period'), obj.error_utilization_penalty); + } + getEnableOobLoadReport() { + return this.enableOobLoadReport; + } + getOobLoadReportingPeriodMs() { + return this.oobLoadReportingPeriodMs; + } + getBlackoutPeriodMs() { + return this.blackoutPeriodMs; + } + getWeightExpirationPeriodMs() { + return this.weightExpirationPeriodMs; + } + getWeightUpdatePeriodMs() { + return this.weightUpdatePeriodMs; + } + getErrorUtilizationPenalty() { + return this.errorUtilizationPenalty; + } +} +exports.WeightedRoundRobinLoadBalancingConfig = WeightedRoundRobinLoadBalancingConfig; +class WeightedRoundRobinPicker { + constructor(children, metricsHandler) { + this.metricsHandler = metricsHandler; + this.queue = new priority_queue_1.PriorityQueue((a, b) => a.deadline < b.deadline); + const positiveWeight = children.filter(picker => picker.weight > 0); + let averageWeight; + if (positiveWeight.length < 2) { + averageWeight = 1; + } + else { + let weightSum = 0; + for (const { weight } of positiveWeight) { + weightSum += weight; + } + averageWeight = weightSum / positiveWeight.length; + } + for (const child of children) { + const period = child.weight > 0 ? 1 / child.weight : averageWeight; + this.queue.push({ + endpointName: child.endpointName, + picker: child.picker, + period: period, + deadline: Math.random() * period + }); + } + } + pick(pickArgs) { + const entry = this.queue.pop(); + this.queue.push(Object.assign(Object.assign({}, entry), { deadline: entry.deadline + entry.period })); + const childPick = entry.picker.pick(pickArgs); + if (childPick.pickResultType === picker_1.PickResultType.COMPLETE) { + if (this.metricsHandler) { + return Object.assign(Object.assign({}, childPick), { onCallEnded: (0, orca_1.createMetricsReader)(loadReport => this.metricsHandler(loadReport, entry.endpointName), childPick.onCallEnded) }); + } + else { + const subchannelWrapper = childPick.subchannel; + return Object.assign(Object.assign({}, childPick), { subchannel: subchannelWrapper.getWrappedSubchannel() }); + } + } + else { + return childPick; + } + } +} +class WeightedRoundRobinLoadBalancer { + constructor(channelControlHelper) { + this.channelControlHelper = channelControlHelper; + this.latestConfig = null; + this.children = new Map(); + this.currentState = connectivity_state_1.ConnectivityState.IDLE; + this.updatesPaused = false; + this.lastError = null; + this.weightUpdateTimer = null; + } + countChildrenWithState(state) { + let count = 0; + for (const entry of this.children.values()) { + if (entry.child.getConnectivityState() === state) { + count += 1; + } + } + return count; + } + updateWeight(entry, loadReport) { + var _a, _b; + const qps = loadReport.rps_fractional; + let utilization = loadReport.application_utilization; + if (utilization > 0 && qps > 0) { + utilization += (loadReport.eps / qps) * ((_b = (_a = this.latestConfig) === null || _a === void 0 ? void 0 : _a.getErrorUtilizationPenalty()) !== null && _b !== void 0 ? _b : 0); + } + const newWeight = utilization === 0 ? 0 : qps / utilization; + if (newWeight === 0) { + return; + } + const now = new Date(); + if (entry.nonEmptySince === null) { + entry.nonEmptySince = now; + } + entry.lastUpdated = now; + entry.weight = newWeight; + } + getWeight(entry) { + if (!this.latestConfig) { + return 0; + } + const now = new Date().getTime(); + if (now - entry.lastUpdated.getTime() >= this.latestConfig.getWeightExpirationPeriodMs()) { + entry.nonEmptySince = null; + return 0; + } + const blackoutPeriod = this.latestConfig.getBlackoutPeriodMs(); + if (blackoutPeriod > 0 && (entry.nonEmptySince === null || now - entry.nonEmptySince.getTime() < blackoutPeriod)) { + return 0; + } + return entry.weight; + } + calculateAndUpdateState() { + if (this.updatesPaused || !this.latestConfig) { + return; + } + if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.READY) > 0) { + const weightedPickers = []; + for (const [endpoint, entry] of this.children) { + if (entry.child.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { + continue; + } + weightedPickers.push({ + endpointName: endpoint, + picker: entry.child.getPicker(), + weight: this.getWeight(entry) + }); + } + trace('Created picker with weights: ' + weightedPickers.map(entry => entry.endpointName + ':' + entry.weight).join(',')); + let metricsHandler; + if (!this.latestConfig.getEnableOobLoadReport()) { + metricsHandler = (loadReport, endpointName) => { + const childEntry = this.children.get(endpointName); + if (childEntry) { + this.updateWeight(childEntry, loadReport); + } + }; + } + else { + metricsHandler = null; + } + this.updateState(connectivity_state_1.ConnectivityState.READY, new WeightedRoundRobinPicker(weightedPickers, metricsHandler), null); + } + else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.CONNECTING) > 0) { + this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); + } + else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) > 0) { + const errorMessage = `weighted_round_robin: No connection established. Last error: ${this.lastError}`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ + details: errorMessage, + }), errorMessage); + } + else { + this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); + } + /* round_robin should keep all children connected, this is how we do that. + * We can't do this more efficiently in the individual child's updateState + * callback because that doesn't have a reference to which child the state + * change is associated with. */ + for (const { child } of this.children.values()) { + if (child.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) { + child.exitIdle(); + } + } + } + updateState(newState, picker, errorMessage) { + trace(connectivity_state_1.ConnectivityState[this.currentState] + + ' -> ' + + connectivity_state_1.ConnectivityState[newState]); + this.currentState = newState; + this.channelControlHelper.updateState(newState, picker, errorMessage); + } + updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { + var _a, _b; + if (!(lbConfig instanceof WeightedRoundRobinLoadBalancingConfig)) { + return false; + } + if (!maybeEndpointList.ok) { + if (this.children.size === 0) { + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); + } + return true; + } + if (maybeEndpointList.value.length === 0) { + const errorMessage = `No addresses resolved. Resolution note: ${resolutionNote}`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ details: errorMessage }), errorMessage); + return false; + } + trace('Connect to endpoint list ' + maybeEndpointList.value.map(subchannel_address_1.endpointToString)); + const now = new Date(); + const seenEndpointNames = new Set(); + this.updatesPaused = true; + this.latestConfig = lbConfig; + for (const endpoint of maybeEndpointList.value) { + const name = (0, subchannel_address_1.endpointToString)(endpoint); + seenEndpointNames.add(name); + let entry = this.children.get(name); + if (!entry) { + entry = { + child: new load_balancer_pick_first_1.LeafLoadBalancer(endpoint, (0, load_balancer_1.createChildChannelControlHelper)(this.channelControlHelper, { + updateState: (connectivityState, picker, errorMessage) => { + /* Ensure that name resolution is requested again after active + * connections are dropped. This is more aggressive than necessary to + * accomplish that, so we are counting on resolvers to have + * reasonable rate limits. */ + if (this.currentState === connectivity_state_1.ConnectivityState.READY && connectivityState !== connectivity_state_1.ConnectivityState.READY) { + this.channelControlHelper.requestReresolution(); + } + if (connectivityState === connectivity_state_1.ConnectivityState.READY) { + entry.nonEmptySince = null; + } + if (errorMessage) { + this.lastError = errorMessage; + } + this.calculateAndUpdateState(); + }, + createSubchannel: (subchannelAddress, subchannelArgs) => { + const subchannel = this.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); + if (entry === null || entry === void 0 ? void 0 : entry.oobMetricsListener) { + return new orca_1.OrcaOobMetricsSubchannelWrapper(subchannel, entry.oobMetricsListener, this.latestConfig.getOobLoadReportingPeriodMs()); + } + else { + return subchannel; + } + } + }), options, resolutionNote), + lastUpdated: now, + nonEmptySince: null, + weight: 0, + oobMetricsListener: null + }; + this.children.set(name, entry); + } + if (lbConfig.getEnableOobLoadReport()) { + entry.oobMetricsListener = loadReport => { + this.updateWeight(entry, loadReport); + }; + } + else { + entry.oobMetricsListener = null; + } + } + for (const [endpointName, entry] of this.children) { + if (seenEndpointNames.has(endpointName)) { + entry.child.startConnecting(); + } + else { + entry.child.destroy(); + this.children.delete(endpointName); + } + } + this.updatesPaused = false; + this.calculateAndUpdateState(); + if (this.weightUpdateTimer) { + clearInterval(this.weightUpdateTimer); + } + this.weightUpdateTimer = (_b = (_a = setInterval(() => { + if (this.currentState === connectivity_state_1.ConnectivityState.READY) { + this.calculateAndUpdateState(); + } + }, lbConfig.getWeightUpdatePeriodMs())).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + return true; + } + exitIdle() { + /* The weighted_round_robin LB policy is only in the IDLE state if it has + * no addresses to try to connect to and it has no picked subchannel. + * In that case, there is no meaningful action that can be taken here. */ + } + resetBackoff() { + // This LB policy has no backoff to reset + } + destroy() { + for (const entry of this.children.values()) { + entry.child.destroy(); + } + this.children.clear(); + if (this.weightUpdateTimer) { + clearInterval(this.weightUpdateTimer); + } + } + getTypeName() { + return TYPE_NAME; + } +} +function setup() { + (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, WeightedRoundRobinLoadBalancer, WeightedRoundRobinLoadBalancingConfig); +} +//# sourceMappingURL=load-balancer-weighted-round-robin.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.js.map b/node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.js.map new file mode 100644 index 0000000..3bc2b03 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.js.map @@ -0,0 +1 @@ +{"version":3,"file":"load-balancer-weighted-round-robin.js","sourceRoot":"","sources":["../../src/load-balancer-weighted-round-robin.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAwdH,sBAMC;AA1dD,6DAAyD;AACzD,2CAA2C;AAC3C,yCAA6J;AAE7J,mDAA0J;AAC1J,yEAA8D;AAC9D,qCAAqC;AACrC,iCAA+F;AAC/F,qCAAwG;AACxG,qDAAiD;AACjD,6DAAkE;AAElE,MAAM,WAAW,GAAG,sBAAsB,CAAC;AAE3C,SAAS,KAAK,CAAC,IAAY;IACzB,OAAO,CAAC,KAAK,CAAC,wBAAY,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;AACvD,CAAC;AAED,MAAM,SAAS,GAAG,sBAAsB,CAAC;AAEzC,MAAM,+BAA+B,GAAG,KAAM,CAAC;AAC/C,MAAM,0BAA0B,GAAG,KAAM,CAAC;AAC1C,MAAM,mCAAmC,GAAG,CAAC,GAAG,KAAM,CAAC;AACvD,MAAM,+BAA+B,GAAG,IAAK,CAAC;AAC9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rC,CAAC;QACH,CAAC;QACD,IAAI,CAAC,aAAa,GAAG,KAAK,CAAC;QAC3B,IAAI,CAAC,uBAAuB,EAAE,CAAC;QAC/B,IAAI,IAAI,CAAC,iBAAiB,EAAE,CAAC;YAC3B,aAAa,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;QACxC,CAAC;QACD,IAAI,CAAC,iBAAiB,GAAG,MAAA,MAAA,WAAW,CAAC,GAAG,EAAE;YACxC,IAAI,IAAI,CAAC,YAAY,KAAK,sCAAiB,CAAC,KAAK,EAAE,CAAC;gBAClD,IAAI,CAAC,uBAAuB,EAAE,CAAC;YACjC,CAAC;QACH,CAAC,EAAE,QAAQ,CAAC,uBAAuB,EAAE,CAAC,EAAC,KAAK,kDAAI,CAAC;QACjD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,QAAQ;QACN;;iFAEyE;IAC3E,CAAC;IACD,YAAY;QACV,yCAAyC;IAC3C,CAAC;IACD,OAAO;QACL,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,EAAE,CAAC;YAC3C,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;QACxB,CAAC;QACD,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;QACtB,IAAI,IAAI,CAAC,iBAAiB,EAAE,CAAC;YAC3B,aAAa,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;QACxC,CAAC;IACH,CAAC;IACD,WAAW;QACT,OAAO,SAAS,CAAC;IACnB,CAAC;CACF;AAED,SAAgB,KAAK;IACnB,IAAA,wCAAwB,EACtB,SAAS,EACT,8BAA8B,EAC9B,qCAAqC,CACtC,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer.d.ts b/node_modules/@grpc/grpc-js/build/src/load-balancer.d.ts new file mode 100644 index 0000000..2f18461 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer.d.ts @@ -0,0 +1,101 @@ +import { ChannelOptions } from './channel-options'; +import { Endpoint, SubchannelAddress } from './subchannel-address'; +import { ConnectivityState } from './connectivity-state'; +import { Picker } from './picker'; +import type { ChannelRef, SubchannelRef } from './channelz'; +import { SubchannelInterface } from './subchannel-interface'; +import { LoadBalancingConfig } from './service-config'; +import { StatusOr } from './call-interface'; +/** + * A collection of functions associated with a channel that a load balancer + * can call as necessary. + */ +export interface ChannelControlHelper { + /** + * Returns a subchannel connected to the specified address. + * @param subchannelAddress The address to connect to + * @param subchannelArgs Channel arguments to use to construct the subchannel + */ + createSubchannel(subchannelAddress: SubchannelAddress, subchannelArgs: ChannelOptions): SubchannelInterface; + /** + * Passes a new subchannel picker up to the channel. This is called if either + * the connectivity state changes or if a different picker is needed for any + * other reason. + * @param connectivityState New connectivity state + * @param picker New picker + */ + updateState(connectivityState: ConnectivityState, picker: Picker, errorMessage: string | null): void; + /** + * Request new data from the resolver. + */ + requestReresolution(): void; + addChannelzChild(child: ChannelRef | SubchannelRef): void; + removeChannelzChild(child: ChannelRef | SubchannelRef): void; +} +/** + * Create a child ChannelControlHelper that overrides some methods of the + * parent while letting others pass through to the parent unmodified. This + * allows other code to create these children without needing to know about + * all of the methods to be passed through. + * @param parent + * @param overrides + */ +export declare function createChildChannelControlHelper(parent: ChannelControlHelper, overrides: Partial): ChannelControlHelper; +/** + * Tracks one or more connected subchannels and determines which subchannel + * each request should use. + */ +export interface LoadBalancer { + /** + * Gives the load balancer a new list of addresses to start connecting to. + * The load balancer will start establishing connections with the new list, + * but will continue using any existing connections until the new connections + * are established + * @param endpointList The new list of addresses to connect to + * @param lbConfig The load balancing config object from the service config, + * if one was provided + * @param channelOptions Channel options from the channel, plus resolver + * attributes + * @param resolutionNote A not from the resolver to include in errors + */ + updateAddressList(endpointList: StatusOr, lbConfig: TypedLoadBalancingConfig, channelOptions: ChannelOptions, resolutionNote: string): boolean; + /** + * If the load balancer is currently in the IDLE state, start connecting. + */ + exitIdle(): void; + /** + * If the load balancer is currently in the CONNECTING or TRANSIENT_FAILURE + * state, reset the current connection backoff timeout to its base value and + * transition to CONNECTING if in TRANSIENT_FAILURE. + */ + resetBackoff(): void; + /** + * The load balancer unrefs all of its subchannels and stops calling methods + * of its channel control helper. + */ + destroy(): void; + /** + * Get the type name for this load balancer type. Must be constant across an + * entire load balancer implementation class and must match the name that the + * balancer implementation class was registered with. + */ + getTypeName(): string; +} +export interface LoadBalancerConstructor { + new (channelControlHelper: ChannelControlHelper): LoadBalancer; +} +export interface TypedLoadBalancingConfig { + getLoadBalancerName(): string; + toJsonObject(): object; +} +export interface TypedLoadBalancingConfigConstructor { + new (...args: any): TypedLoadBalancingConfig; + createFromJson(obj: any): TypedLoadBalancingConfig; +} +export declare function registerLoadBalancerType(typeName: string, loadBalancerType: LoadBalancerConstructor, loadBalancingConfigType: TypedLoadBalancingConfigConstructor): void; +export declare function registerDefaultLoadBalancerType(typeName: string): void; +export declare function createLoadBalancer(config: TypedLoadBalancingConfig, channelControlHelper: ChannelControlHelper): LoadBalancer | null; +export declare function isLoadBalancerNameRegistered(typeName: string): boolean; +export declare function parseLoadBalancingConfig(rawConfig: LoadBalancingConfig): TypedLoadBalancingConfig; +export declare function getDefaultConfig(): TypedLoadBalancingConfig; +export declare function selectLbConfigFromList(configs: LoadBalancingConfig[], fallbackTodefault?: boolean): TypedLoadBalancingConfig | null; diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer.js b/node_modules/@grpc/grpc-js/build/src/load-balancer.js new file mode 100644 index 0000000..adda9c6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer.js @@ -0,0 +1,116 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createChildChannelControlHelper = createChildChannelControlHelper; +exports.registerLoadBalancerType = registerLoadBalancerType; +exports.registerDefaultLoadBalancerType = registerDefaultLoadBalancerType; +exports.createLoadBalancer = createLoadBalancer; +exports.isLoadBalancerNameRegistered = isLoadBalancerNameRegistered; +exports.parseLoadBalancingConfig = parseLoadBalancingConfig; +exports.getDefaultConfig = getDefaultConfig; +exports.selectLbConfigFromList = selectLbConfigFromList; +const logging_1 = require("./logging"); +const constants_1 = require("./constants"); +/** + * Create a child ChannelControlHelper that overrides some methods of the + * parent while letting others pass through to the parent unmodified. This + * allows other code to create these children without needing to know about + * all of the methods to be passed through. + * @param parent + * @param overrides + */ +function createChildChannelControlHelper(parent, overrides) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; + return { + createSubchannel: (_b = (_a = overrides.createSubchannel) === null || _a === void 0 ? void 0 : _a.bind(overrides)) !== null && _b !== void 0 ? _b : parent.createSubchannel.bind(parent), + updateState: (_d = (_c = overrides.updateState) === null || _c === void 0 ? void 0 : _c.bind(overrides)) !== null && _d !== void 0 ? _d : parent.updateState.bind(parent), + requestReresolution: (_f = (_e = overrides.requestReresolution) === null || _e === void 0 ? void 0 : _e.bind(overrides)) !== null && _f !== void 0 ? _f : parent.requestReresolution.bind(parent), + addChannelzChild: (_h = (_g = overrides.addChannelzChild) === null || _g === void 0 ? void 0 : _g.bind(overrides)) !== null && _h !== void 0 ? _h : parent.addChannelzChild.bind(parent), + removeChannelzChild: (_k = (_j = overrides.removeChannelzChild) === null || _j === void 0 ? void 0 : _j.bind(overrides)) !== null && _k !== void 0 ? _k : parent.removeChannelzChild.bind(parent), + }; +} +const registeredLoadBalancerTypes = {}; +let defaultLoadBalancerType = null; +function registerLoadBalancerType(typeName, loadBalancerType, loadBalancingConfigType) { + registeredLoadBalancerTypes[typeName] = { + LoadBalancer: loadBalancerType, + LoadBalancingConfig: loadBalancingConfigType, + }; +} +function registerDefaultLoadBalancerType(typeName) { + defaultLoadBalancerType = typeName; +} +function createLoadBalancer(config, channelControlHelper) { + const typeName = config.getLoadBalancerName(); + if (typeName in registeredLoadBalancerTypes) { + return new registeredLoadBalancerTypes[typeName].LoadBalancer(channelControlHelper); + } + else { + return null; + } +} +function isLoadBalancerNameRegistered(typeName) { + return typeName in registeredLoadBalancerTypes; +} +function parseLoadBalancingConfig(rawConfig) { + const keys = Object.keys(rawConfig); + if (keys.length !== 1) { + throw new Error('Provided load balancing config has multiple conflicting entries'); + } + const typeName = keys[0]; + if (typeName in registeredLoadBalancerTypes) { + try { + return registeredLoadBalancerTypes[typeName].LoadBalancingConfig.createFromJson(rawConfig[typeName]); + } + catch (e) { + throw new Error(`${typeName}: ${e.message}`); + } + } + else { + throw new Error(`Unrecognized load balancing config name ${typeName}`); + } +} +function getDefaultConfig() { + if (!defaultLoadBalancerType) { + throw new Error('No default load balancer type registered'); + } + return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig(); +} +function selectLbConfigFromList(configs, fallbackTodefault = false) { + for (const config of configs) { + try { + return parseLoadBalancingConfig(config); + } + catch (e) { + (0, logging_1.log)(constants_1.LogVerbosity.DEBUG, 'Config parsing failed with error', e.message); + continue; + } + } + if (fallbackTodefault) { + if (defaultLoadBalancerType) { + return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig(); + } + else { + return null; + } + } + else { + return null; + } +} +//# sourceMappingURL=load-balancer.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer.js.map b/node_modules/@grpc/grpc-js/build/src/load-balancer.js.map new file mode 100644 index 0000000..2eec632 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"load-balancer.js","sourceRoot":"","sources":["../../src/load-balancer.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;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AK,CAAC,0CAA0C,CAAC,CAAC;IAC9D,CAAC;IACD,OAAO,IAAI,2BAA2B,CACpC,uBAAuB,CACvB,CAAC,mBAAmB,EAAE,CAAC;AAC3B,CAAC;AAED,SAAgB,sBAAsB,CACpC,OAA8B,EAC9B,iBAAiB,GAAG,KAAK;IAEzB,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,CAAC;YACH,OAAO,wBAAwB,CAAC,MAAM,CAAC,CAAC;QAC1C,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,IAAA,aAAG,EACD,wBAAY,CAAC,KAAK,EAClB,kCAAkC,EACjC,CAAW,CAAC,OAAO,CACrB,CAAC;YACF,SAAS;QACX,CAAC;IACH,CAAC;IACD,IAAI,iBAAiB,EAAE,CAAC;QACtB,IAAI,uBAAuB,EAAE,CAAC;YAC5B,OAAO,IAAI,2BAA2B,CACpC,uBAAuB,CACvB,CAAC,mBAAmB,EAAE,CAAC;QAC3B,CAAC;aAAM,CAAC;YACN,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;SAAM,CAAC;QACN,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancing-call.d.ts b/node_modules/@grpc/grpc-js/build/src/load-balancing-call.d.ts new file mode 100644 index 0000000..983049b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancing-call.d.ts @@ -0,0 +1,49 @@ +import { CallCredentials } from './call-credentials'; +import { Call, DeadlineInfoProvider, InterceptingListener, MessageContext, StatusObject } from './call-interface'; +import { Status } from './constants'; +import { Deadline } from './deadline'; +import { InternalChannel } from './internal-channel'; +import { Metadata } from './metadata'; +import { CallConfig } from './resolver'; +import { AuthContext } from './auth-context'; +export type RpcProgress = 'NOT_STARTED' | 'DROP' | 'REFUSED' | 'PROCESSED'; +export interface StatusObjectWithProgress extends StatusObject { + progress: RpcProgress; +} +export interface LoadBalancingCallInterceptingListener extends InterceptingListener { + onReceiveStatus(status: StatusObjectWithProgress): void; +} +export declare class LoadBalancingCall implements Call, DeadlineInfoProvider { + private readonly channel; + private readonly callConfig; + private readonly methodName; + private readonly host; + private readonly credentials; + private readonly deadline; + private readonly callNumber; + private child; + private readPending; + private pendingMessage; + private pendingHalfClose; + private ended; + private serviceUrl; + private metadata; + private listener; + private onCallEnded; + private startTime; + private childStartTime; + constructor(channel: InternalChannel, callConfig: CallConfig, methodName: string, host: string, credentials: CallCredentials, deadline: Deadline, callNumber: number); + getDeadlineInfo(): string[]; + private trace; + private outputStatus; + doPick(): void; + cancelWithStatus(status: Status, details: string): void; + getPeer(): string; + start(metadata: Metadata, listener: LoadBalancingCallInterceptingListener): void; + sendMessageWithContext(context: MessageContext, message: Buffer): void; + startRead(): void; + halfClose(): void; + setCredentials(credentials: CallCredentials): void; + getCallNumber(): number; + getAuthContext(): AuthContext | null; +} diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancing-call.js b/node_modules/@grpc/grpc-js/build/src/load-balancing-call.js new file mode 100644 index 0000000..44edbd0 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancing-call.js @@ -0,0 +1,302 @@ +"use strict"; +/* + * Copyright 2022 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LoadBalancingCall = void 0; +const connectivity_state_1 = require("./connectivity-state"); +const constants_1 = require("./constants"); +const deadline_1 = require("./deadline"); +const metadata_1 = require("./metadata"); +const picker_1 = require("./picker"); +const uri_parser_1 = require("./uri-parser"); +const logging = require("./logging"); +const control_plane_status_1 = require("./control-plane-status"); +const http2 = require("http2"); +const TRACER_NAME = 'load_balancing_call'; +class LoadBalancingCall { + constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber) { + var _a, _b; + this.channel = channel; + this.callConfig = callConfig; + this.methodName = methodName; + this.host = host; + this.credentials = credentials; + this.deadline = deadline; + this.callNumber = callNumber; + this.child = null; + this.readPending = false; + this.pendingMessage = null; + this.pendingHalfClose = false; + this.ended = false; + this.metadata = null; + this.listener = null; + this.onCallEnded = null; + this.childStartTime = null; + const splitPath = this.methodName.split('/'); + let serviceName = ''; + /* The standard path format is "/{serviceName}/{methodName}", so if we split + * by '/', the first item should be empty and the second should be the + * service name */ + if (splitPath.length >= 2) { + serviceName = splitPath[1]; + } + const hostname = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : 'localhost'; + /* Currently, call credentials are only allowed on HTTPS connections, so we + * can assume that the scheme is "https" */ + this.serviceUrl = `https://${hostname}/${serviceName}`; + this.startTime = new Date(); + } + getDeadlineInfo() { + var _a, _b; + const deadlineInfo = []; + if (this.childStartTime) { + if (this.childStartTime > this.startTime) { + if ((_a = this.metadata) === null || _a === void 0 ? void 0 : _a.getOptions().waitForReady) { + deadlineInfo.push('wait_for_ready'); + } + deadlineInfo.push(`LB pick: ${(0, deadline_1.formatDateDifference)(this.startTime, this.childStartTime)}`); + } + deadlineInfo.push(...this.child.getDeadlineInfo()); + return deadlineInfo; + } + else { + if ((_b = this.metadata) === null || _b === void 0 ? void 0 : _b.getOptions().waitForReady) { + deadlineInfo.push('wait_for_ready'); + } + deadlineInfo.push('Waiting for LB pick'); + } + return deadlineInfo; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callNumber + '] ' + text); + } + outputStatus(status, progress) { + var _a, _b; + if (!this.ended) { + this.ended = true; + this.trace('ended with status: code=' + + status.code + + ' details="' + + status.details + + '" start time=' + + this.startTime.toISOString()); + const finalStatus = Object.assign(Object.assign({}, status), { progress }); + (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus(finalStatus); + (_b = this.onCallEnded) === null || _b === void 0 ? void 0 : _b.call(this, finalStatus.code, finalStatus.details, finalStatus.metadata); + } + } + doPick() { + var _a, _b; + if (this.ended) { + return; + } + if (!this.metadata) { + throw new Error('doPick called before start'); + } + this.trace('Pick called'); + const finalMetadata = this.metadata.clone(); + const pickResult = this.channel.doPick(finalMetadata, this.callConfig.pickInformation); + const subchannelString = pickResult.subchannel + ? '(' + + pickResult.subchannel.getChannelzRef().id + + ') ' + + pickResult.subchannel.getAddress() + : '' + pickResult.subchannel; + this.trace('Pick result: ' + + picker_1.PickResultType[pickResult.pickResultType] + + ' subchannel: ' + + subchannelString + + ' status: ' + + ((_a = pickResult.status) === null || _a === void 0 ? void 0 : _a.code) + + ' ' + + ((_b = pickResult.status) === null || _b === void 0 ? void 0 : _b.details)); + switch (pickResult.pickResultType) { + case picker_1.PickResultType.COMPLETE: + const combinedCallCredentials = this.credentials.compose(pickResult.subchannel.getCallCredentials()); + combinedCallCredentials + .generateMetadata({ method_name: this.methodName, service_url: this.serviceUrl }) + .then(credsMetadata => { + var _a; + /* If this call was cancelled (e.g. by the deadline) before + * metadata generation finished, we shouldn't do anything with + * it. */ + if (this.ended) { + this.trace('Credentials metadata generation finished after call ended'); + return; + } + finalMetadata.merge(credsMetadata); + if (finalMetadata.get('authorization').length > 1) { + this.outputStatus({ + code: constants_1.Status.INTERNAL, + details: '"authorization" metadata cannot have multiple values', + metadata: new metadata_1.Metadata(), + }, 'PROCESSED'); + } + if (pickResult.subchannel.getConnectivityState() !== + connectivity_state_1.ConnectivityState.READY) { + this.trace('Picked subchannel ' + + subchannelString + + ' has state ' + + connectivity_state_1.ConnectivityState[pickResult.subchannel.getConnectivityState()] + + ' after getting credentials metadata. Retrying pick'); + this.doPick(); + return; + } + if (this.deadline !== Infinity) { + finalMetadata.set('grpc-timeout', (0, deadline_1.getDeadlineTimeoutString)(this.deadline)); + } + try { + this.child = pickResult + .subchannel.getRealSubchannel() + .createCall(finalMetadata, this.host, this.methodName, { + onReceiveMetadata: metadata => { + this.trace('Received metadata'); + this.listener.onReceiveMetadata(metadata); + }, + onReceiveMessage: message => { + this.trace('Received message'); + this.listener.onReceiveMessage(message); + }, + onReceiveStatus: status => { + this.trace('Received status'); + if (status.rstCode === + http2.constants.NGHTTP2_REFUSED_STREAM) { + this.outputStatus(status, 'REFUSED'); + } + else { + this.outputStatus(status, 'PROCESSED'); + } + }, + }); + this.childStartTime = new Date(); + } + catch (error) { + this.trace('Failed to start call on picked subchannel ' + + subchannelString + + ' with error ' + + error.message); + this.outputStatus({ + code: constants_1.Status.INTERNAL, + details: 'Failed to start HTTP/2 stream with error ' + + error.message, + metadata: new metadata_1.Metadata(), + }, 'NOT_STARTED'); + return; + } + (_a = pickResult.onCallStarted) === null || _a === void 0 ? void 0 : _a.call(pickResult); + this.onCallEnded = pickResult.onCallEnded; + this.trace('Created child call [' + this.child.getCallNumber() + ']'); + if (this.readPending) { + this.child.startRead(); + } + if (this.pendingMessage) { + this.child.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message); + } + if (this.pendingHalfClose) { + this.child.halfClose(); + } + }, (error) => { + // We assume the error code isn't 0 (Status.OK) + const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(typeof error.code === 'number' ? error.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error.message}`); + this.outputStatus({ + code: code, + details: details, + metadata: new metadata_1.Metadata(), + }, 'PROCESSED'); + }); + break; + case picker_1.PickResultType.DROP: + const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(pickResult.status.code, pickResult.status.details); + setImmediate(() => { + this.outputStatus({ code, details, metadata: pickResult.status.metadata }, 'DROP'); + }); + break; + case picker_1.PickResultType.TRANSIENT_FAILURE: + if (this.metadata.getOptions().waitForReady) { + this.channel.queueCallForPick(this); + } + else { + const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(pickResult.status.code, pickResult.status.details); + setImmediate(() => { + this.outputStatus({ code, details, metadata: pickResult.status.metadata }, 'PROCESSED'); + }); + } + break; + case picker_1.PickResultType.QUEUE: + this.channel.queueCallForPick(this); + } + } + cancelWithStatus(status, details) { + var _a; + this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"'); + (_a = this.child) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(status, details); + this.outputStatus({ code: status, details: details, metadata: new metadata_1.Metadata() }, 'PROCESSED'); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.child) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.channel.getTarget(); + } + start(metadata, listener) { + this.trace('start called'); + this.listener = listener; + this.metadata = metadata; + this.doPick(); + } + sendMessageWithContext(context, message) { + this.trace('write() called with message of length ' + message.length); + if (this.child) { + this.child.sendMessageWithContext(context, message); + } + else { + this.pendingMessage = { context, message }; + } + } + startRead() { + this.trace('startRead called'); + if (this.child) { + this.child.startRead(); + } + else { + this.readPending = true; + } + } + halfClose() { + this.trace('halfClose called'); + if (this.child) { + this.child.halfClose(); + } + else { + this.pendingHalfClose = true; + } + } + setCredentials(credentials) { + throw new Error('Method not implemented.'); + } + getCallNumber() { + return this.callNumber; + } + getAuthContext() { + if (this.child) { + return this.child.getAuthContext(); + } + else { + return null; + } + } +} +exports.LoadBalancingCall = LoadBalancingCall; +//# sourceMappingURL=load-balancing-call.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancing-call.js.map b/node_modules/@grpc/grpc-js/build/src/load-balancing-call.js.map new file mode 100644 index 0000000..34701f5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancing-call.js.map @@ -0,0 +1 @@ +{"version":3,"file":"load-balancing-call.js","sourceRoot":"","sources":["../../src/load-balancing-call.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAWH,6DAA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AI,CAAC,KAAK,CAAC,SAAS,EAAE,CAAC;QACzB,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC;QAC/B,CAAC;IACH,CAAC;IACD,cAAc,CAAC,WAA4B;QACzC,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IAED,aAAa;QACX,OAAO,IAAI,CAAC,UAAU,CAAC;IACzB,CAAC;IAED,cAAc;QACZ,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YACf,OAAO,IAAI,CAAC,KAAK,CAAC,cAAc,EAAE,CAAC;QACrC,CAAC;aAAM,CAAC;YACN,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;CACF;AA9UD,8CA8UC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/logging.d.ts b/node_modules/@grpc/grpc-js/build/src/logging.d.ts new file mode 100644 index 0000000..f89da44 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/logging.d.ts @@ -0,0 +1,7 @@ +import { LogVerbosity } from './constants'; +export declare const getLogger: () => Partial; +export declare const setLogger: (logger: Partial) => void; +export declare const setLoggerVerbosity: (verbosity: LogVerbosity) => void; +export declare const log: (severity: LogVerbosity, ...args: any[]) => void; +export declare function trace(severity: LogVerbosity, tracer: string, text: string): void; +export declare function isTracerEnabled(tracer: string): boolean; diff --git a/node_modules/@grpc/grpc-js/build/src/logging.js b/node_modules/@grpc/grpc-js/build/src/logging.js new file mode 100644 index 0000000..af7a8c8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/logging.js @@ -0,0 +1,122 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +var _a, _b, _c, _d; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.log = exports.setLoggerVerbosity = exports.setLogger = exports.getLogger = void 0; +exports.trace = trace; +exports.isTracerEnabled = isTracerEnabled; +const constants_1 = require("./constants"); +const process_1 = require("process"); +const clientVersion = require('../../package.json').version; +const DEFAULT_LOGGER = { + error: (message, ...optionalParams) => { + console.error('E ' + message, ...optionalParams); + }, + info: (message, ...optionalParams) => { + console.error('I ' + message, ...optionalParams); + }, + debug: (message, ...optionalParams) => { + console.error('D ' + message, ...optionalParams); + }, +}; +let _logger = DEFAULT_LOGGER; +let _logVerbosity = constants_1.LogVerbosity.ERROR; +const verbosityString = (_b = (_a = process.env.GRPC_NODE_VERBOSITY) !== null && _a !== void 0 ? _a : process.env.GRPC_VERBOSITY) !== null && _b !== void 0 ? _b : ''; +switch (verbosityString.toUpperCase()) { + case 'DEBUG': + _logVerbosity = constants_1.LogVerbosity.DEBUG; + break; + case 'INFO': + _logVerbosity = constants_1.LogVerbosity.INFO; + break; + case 'ERROR': + _logVerbosity = constants_1.LogVerbosity.ERROR; + break; + case 'NONE': + _logVerbosity = constants_1.LogVerbosity.NONE; + break; + default: + // Ignore any other values +} +const getLogger = () => { + return _logger; +}; +exports.getLogger = getLogger; +const setLogger = (logger) => { + _logger = logger; +}; +exports.setLogger = setLogger; +const setLoggerVerbosity = (verbosity) => { + _logVerbosity = verbosity; +}; +exports.setLoggerVerbosity = setLoggerVerbosity; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const log = (severity, ...args) => { + let logFunction; + if (severity >= _logVerbosity) { + switch (severity) { + case constants_1.LogVerbosity.DEBUG: + logFunction = _logger.debug; + break; + case constants_1.LogVerbosity.INFO: + logFunction = _logger.info; + break; + case constants_1.LogVerbosity.ERROR: + logFunction = _logger.error; + break; + } + /* Fall back to _logger.error when other methods are not available for + * compatiblity with older behavior that always logged to _logger.error */ + if (!logFunction) { + logFunction = _logger.error; + } + if (logFunction) { + logFunction.bind(_logger)(...args); + } + } +}; +exports.log = log; +const tracersString = (_d = (_c = process.env.GRPC_NODE_TRACE) !== null && _c !== void 0 ? _c : process.env.GRPC_TRACE) !== null && _d !== void 0 ? _d : ''; +const enabledTracers = new Set(); +const disabledTracers = new Set(); +for (const tracerName of tracersString.split(',')) { + if (tracerName.startsWith('-')) { + disabledTracers.add(tracerName.substring(1)); + } + else { + enabledTracers.add(tracerName); + } +} +const allEnabled = enabledTracers.has('all'); +function trace(severity, tracer, text) { + if (isTracerEnabled(tracer)) { + (0, exports.log)(severity, new Date().toISOString() + + ' | v' + + clientVersion + + ' ' + + process_1.pid + + ' | ' + + tracer + + ' | ' + + text); + } +} +function isTracerEnabled(tracer) { + return (!disabledTracers.has(tracer) && (allEnabled || enabledTracers.has(tracer))); +} +//# sourceMappingURL=logging.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/logging.js.map b/node_modules/@grpc/grpc-js/build/src/logging.js.map new file mode 100644 index 0000000..9fdc293 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/logging.js.map @@ -0,0 +1 @@ +{"version":3,"file":"logging.js","sourceRoot":"","sources":["../../src/logging.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;;AA6FH,sBAmBC;AAED,0CAIC;AApHD,2CAA2C;AAC3C,qCAA8B;AAE9B,MAAM,aAAa,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO,CAAC;AAE5D,MAAM,cAAc,GAAqB;IACvC,KAAK,EAAE,CAAC,OAAa,EAAE,GAAG,cAAqB,EAAE,EAAE;QACjD,OAAO,CAAC,KAAK,CAAC,IAAI,GAAG,OAAO,EAAE,GAAG,cAAc,CAAC,CAAC;IACnD,CAAC;IACD,IAAI,EAAE,CAAC,OAAa,EAAE,GAAG,cAAqB,EAAE,EAAE;QAChD,OAAO,CAAC,KAAK,CAAC,IAAI,GAAG,OAAO,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CAAC,KAAK,CAAC,CAAC;AAE7C,SAAgB,KAAK,CACnB,QAAsB,EACtB,MAAc,EACd,IAAY;IAEZ,IAAI,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC;QAC5B,IAAA,WAAG,EACD,QAAQ,EACR,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACtB,MAAM;YACN,aAAa;YACb,GAAG;YACH,aAAG;YACH,KAAK;YACL,MAAM;YACN,KAAK;YACL,IAAI,CACP,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAgB,eAAe,CAAC,MAAc;IAC5C,OAAO,CACL,CAAC,eAAe,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,IAAI,cAAc,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAC3E,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/make-client.d.ts b/node_modules/@grpc/grpc-js/build/src/make-client.d.ts new file mode 100644 index 0000000..e095e6e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/make-client.d.ts @@ -0,0 +1,71 @@ +import { ChannelCredentials } from './channel-credentials'; +import { ChannelOptions } from './channel-options'; +import { Client } from './client'; +import { UntypedServiceImplementation } from './server'; +export interface Serialize { + (value: T): Buffer; +} +export interface Deserialize { + (bytes: Buffer): T; +} +export interface ClientMethodDefinition { + path: string; + requestStream: boolean; + responseStream: boolean; + requestSerialize: Serialize; + responseDeserialize: Deserialize; + originalName?: string; +} +export interface ServerMethodDefinition { + path: string; + requestStream: boolean; + responseStream: boolean; + responseSerialize: Serialize; + requestDeserialize: Deserialize; + originalName?: string; +} +export interface MethodDefinition extends ClientMethodDefinition, ServerMethodDefinition { +} +export type ServiceDefinition = { + readonly [index in keyof ImplementationType]: MethodDefinition; +}; +export interface ProtobufTypeDefinition { + format: string; + type: object; + fileDescriptorProtos: Buffer[]; +} +export interface PackageDefinition { + [index: string]: ServiceDefinition | ProtobufTypeDefinition; +} +export interface ServiceClient extends Client { + [methodName: string]: Function; +} +export interface ServiceClientConstructor { + new (address: string, credentials: ChannelCredentials, options?: Partial): ServiceClient; + service: ServiceDefinition; + serviceName: string; +} +/** + * Creates a constructor for a client with the given methods, as specified in + * the methods argument. The resulting class will have an instance method for + * each method in the service, which is a partial application of one of the + * [Client]{@link grpc.Client} request methods, depending on `requestSerialize` + * and `responseSerialize`, with the `method`, `serialize`, and `deserialize` + * arguments predefined. + * @param methods An object mapping method names to + * method attributes + * @param serviceName The fully qualified name of the service + * @param classOptions An options object. + * @return New client constructor, which is a subclass of + * {@link grpc.Client}, and has the same arguments as that constructor. + */ +export declare function makeClientConstructor(methods: ServiceDefinition, serviceName: string, classOptions?: {}): ServiceClientConstructor; +export interface GrpcObject { + [index: string]: GrpcObject | ServiceClientConstructor | ProtobufTypeDefinition; +} +/** + * Load a gRPC package definition as a gRPC object hierarchy. + * @param packageDef The package definition object. + * @return The resulting gRPC object. + */ +export declare function loadPackageDefinition(packageDef: PackageDefinition): GrpcObject; diff --git a/node_modules/@grpc/grpc-js/build/src/make-client.js b/node_modules/@grpc/grpc-js/build/src/make-client.js new file mode 100644 index 0000000..c7d9958 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/make-client.js @@ -0,0 +1,143 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.makeClientConstructor = makeClientConstructor; +exports.loadPackageDefinition = loadPackageDefinition; +const client_1 = require("./client"); +/** + * Map with short names for each of the requester maker functions. Used in + * makeClientConstructor + * @private + */ +const requesterFuncs = { + unary: client_1.Client.prototype.makeUnaryRequest, + server_stream: client_1.Client.prototype.makeServerStreamRequest, + client_stream: client_1.Client.prototype.makeClientStreamRequest, + bidi: client_1.Client.prototype.makeBidiStreamRequest, +}; +/** + * Returns true, if given key is included in the blacklisted + * keys. + * @param key key for check, string. + */ +function isPrototypePolluted(key) { + return ['__proto__', 'prototype', 'constructor'].includes(key); +} +/** + * Creates a constructor for a client with the given methods, as specified in + * the methods argument. The resulting class will have an instance method for + * each method in the service, which is a partial application of one of the + * [Client]{@link grpc.Client} request methods, depending on `requestSerialize` + * and `responseSerialize`, with the `method`, `serialize`, and `deserialize` + * arguments predefined. + * @param methods An object mapping method names to + * method attributes + * @param serviceName The fully qualified name of the service + * @param classOptions An options object. + * @return New client constructor, which is a subclass of + * {@link grpc.Client}, and has the same arguments as that constructor. + */ +function makeClientConstructor(methods, serviceName, classOptions) { + if (!classOptions) { + classOptions = {}; + } + class ServiceClientImpl extends client_1.Client { + } + Object.keys(methods).forEach(name => { + if (isPrototypePolluted(name)) { + return; + } + const attrs = methods[name]; + let methodType; + // TODO(murgatroid99): Verify that we don't need this anymore + if (typeof name === 'string' && name.charAt(0) === '$') { + throw new Error('Method names cannot start with $'); + } + if (attrs.requestStream) { + if (attrs.responseStream) { + methodType = 'bidi'; + } + else { + methodType = 'client_stream'; + } + } + else { + if (attrs.responseStream) { + methodType = 'server_stream'; + } + else { + methodType = 'unary'; + } + } + const serialize = attrs.requestSerialize; + const deserialize = attrs.responseDeserialize; + const methodFunc = partial(requesterFuncs[methodType], attrs.path, serialize, deserialize); + ServiceClientImpl.prototype[name] = methodFunc; + // Associate all provided attributes with the method + Object.assign(ServiceClientImpl.prototype[name], attrs); + if (attrs.originalName && !isPrototypePolluted(attrs.originalName)) { + ServiceClientImpl.prototype[attrs.originalName] = + ServiceClientImpl.prototype[name]; + } + }); + ServiceClientImpl.service = methods; + ServiceClientImpl.serviceName = serviceName; + return ServiceClientImpl; +} +function partial(fn, path, serialize, deserialize) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return function (...args) { + return fn.call(this, path, serialize, deserialize, ...args); + }; +} +function isProtobufTypeDefinition(obj) { + return 'format' in obj; +} +/** + * Load a gRPC package definition as a gRPC object hierarchy. + * @param packageDef The package definition object. + * @return The resulting gRPC object. + */ +function loadPackageDefinition(packageDef) { + const result = {}; + for (const serviceFqn in packageDef) { + if (Object.prototype.hasOwnProperty.call(packageDef, serviceFqn)) { + const service = packageDef[serviceFqn]; + const nameComponents = serviceFqn.split('.'); + if (nameComponents.some((comp) => isPrototypePolluted(comp))) { + continue; + } + const serviceName = nameComponents[nameComponents.length - 1]; + let current = result; + for (const packageName of nameComponents.slice(0, -1)) { + if (!current[packageName]) { + current[packageName] = {}; + } + current = current[packageName]; + } + if (isProtobufTypeDefinition(service)) { + current[serviceName] = service; + } + else { + current[serviceName] = makeClientConstructor(service, serviceName, {}); + } + } + } + return result; +} +//# sourceMappingURL=make-client.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/make-client.js.map b/node_modules/@grpc/grpc-js/build/src/make-client.js.map new file mode 100644 index 0000000..6e6b476 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/make-client.js.map @@ -0,0 +1 @@ +{"version":3,"file":"make-client.js","sourceRoot":"","sources":["../../src/make-client.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAwGH,sDA2DC;AAgCD,sDA2BC;AA1ND,qCAAkC;AAmDlC;;;;GAIG;AACH,MAAM,cAAc,GAAG;IACrB,KAAK,EAAE,eAAM,CAAC,SAAS,CAAC,gBAAgB;IACxC,aAAa,EAAE,eAAM,CAAC,SAAS,CAAC,uBAAuB;IACvD,aAAa,EAAE,eAAM,CAAC,SAAS,CAAC,uBAAuB;IACvD,IAAI,EAAE,eAAM,CAAC,SAAS,CAAC,qBAAqB;CAC7C,CAAC;AAgBF;;;;GAIG;AACH,SAAS,mBAAmB,CAAC,GAAW;IACtC,OAAO,CAAC,WAAW,EAAE,WAAW,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,CAAC,GAAG,CAAC,CAAC;YAC7C,IAAI,cAAc,CAAC,IAAI,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,mBAAmB,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC;gBACrE,SAAS;YACX,CAAC;YACD,MAAM,WAAW,GAAG,cAAc,CAAC,cAAc,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YAC9D,IAAI,OAAO,GAAG,MAAM,CAAC;YACrB,KAAK,MAAM,WAAW,IAAI,cAAc,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;gBACtD,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,EAAE,CAAC;oBAC1B,OAAO,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC;gBAC5B,CAAC;gBACD,OAAO,GAAG,OAAO,CAAC,WAAW,CAAe,CAAC;YAC/C,CAAC;YACD,IAAI,wBAAwB,CAAC,OAAO,CAAC,EAAE,CAAC;gBACtC,OAAO,CAAC,WAAW,CAAC,GAAG,OAAO,CAAC;YACjC,CAAC;iBAAM,CAAC;gBACN,OAAO,CAAC,WAAW,CAAC,GAAG,qBAAqB,CAAC,OAAO,EAAE,WAAW,EAAE,EAAE,CAAC,CAAC;YACzE,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/metadata.d.ts b/node_modules/@grpc/grpc-js/build/src/metadata.d.ts new file mode 100644 index 0000000..7ee8191 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/metadata.d.ts @@ -0,0 +1,100 @@ +import * as http2 from 'http2'; +export type MetadataValue = string | Buffer; +export type MetadataObject = Map; +export interface MetadataOptions { + idempotentRequest?: boolean; + waitForReady?: boolean; + cacheableRequest?: boolean; + corked?: boolean; +} +/** + * A class for storing metadata. Keys are normalized to lowercase ASCII. + */ +export declare class Metadata { + protected internalRepr: MetadataObject; + private options; + private opaqueData; + constructor(options?: MetadataOptions); + /** + * Sets the given value for the given key by replacing any other values + * associated with that key. Normalizes the key. + * @param key The key to whose value should be set. + * @param value The value to set. Must be a buffer if and only + * if the normalized key ends with '-bin'. + */ + set(key: string, value: MetadataValue): void; + /** + * Adds the given value for the given key by appending to a list of previous + * values associated with that key. Normalizes the key. + * @param key The key for which a new value should be appended. + * @param value The value to add. Must be a buffer if and only + * if the normalized key ends with '-bin'. + */ + add(key: string, value: MetadataValue): void; + /** + * Removes the given key and any associated values. Normalizes the key. + * @param key The key whose values should be removed. + */ + remove(key: string): void; + /** + * Gets a list of all values associated with the key. Normalizes the key. + * @param key The key whose value should be retrieved. + * @return A list of values associated with the given key. + */ + get(key: string): MetadataValue[]; + /** + * Gets a plain object mapping each key to the first value associated with it. + * This reflects the most common way that people will want to see metadata. + * @return A key/value mapping of the metadata. + */ + getMap(): { + [key: string]: MetadataValue; + }; + /** + * Clones the metadata object. + * @return The newly cloned object. + */ + clone(): Metadata; + /** + * Merges all key-value pairs from a given Metadata object into this one. + * If both this object and the given object have values in the same key, + * values from the other Metadata object will be appended to this object's + * values. + * @param other A Metadata object. + */ + merge(other: Metadata): void; + setOptions(options: MetadataOptions): void; + getOptions(): MetadataOptions; + /** + * Creates an OutgoingHttpHeaders object that can be used with the http2 API. + */ + toHttp2Headers(): http2.OutgoingHttpHeaders; + /** + * This modifies the behavior of JSON.stringify to show an object + * representation of the metadata map. + */ + toJSON(): { + [key: string]: MetadataValue[]; + }; + /** + * Attach additional data of any type to the metadata object, which will not + * be included when sending headers. The data can later be retrieved with + * `getOpaque`. Keys with the prefix `grpc` are reserved for use by this + * library. + * @param key + * @param value + */ + setOpaque(key: string, value: unknown): void; + /** + * Retrieve data previously added with `setOpaque`. + * @param key + * @returns + */ + getOpaque(key: string): unknown; + /** + * Returns a new Metadata object based fields in a given IncomingHttpHeaders + * object. + * @param headers An IncomingHttpHeaders object. + */ + static fromHttp2Headers(headers: http2.IncomingHttpHeaders): Metadata; +} diff --git a/node_modules/@grpc/grpc-js/build/src/metadata.js b/node_modules/@grpc/grpc-js/build/src/metadata.js new file mode 100644 index 0000000..d4773d4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/metadata.js @@ -0,0 +1,272 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Metadata = void 0; +const logging_1 = require("./logging"); +const constants_1 = require("./constants"); +const error_1 = require("./error"); +const LEGAL_KEY_REGEX = /^[:0-9a-z_.-]+$/; +const LEGAL_NON_BINARY_VALUE_REGEX = /^[ -~]*$/; +function isLegalKey(key) { + return LEGAL_KEY_REGEX.test(key); +} +function isLegalNonBinaryValue(value) { + return LEGAL_NON_BINARY_VALUE_REGEX.test(value); +} +function isBinaryKey(key) { + return key.endsWith('-bin'); +} +function isCustomMetadata(key) { + return !key.startsWith('grpc-'); +} +function normalizeKey(key) { + return key.toLowerCase(); +} +function validate(key, value) { + if (!isLegalKey(key)) { + throw new Error('Metadata key "' + key + '" contains illegal characters'); + } + if (value !== null && value !== undefined) { + if (isBinaryKey(key)) { + if (!Buffer.isBuffer(value)) { + throw new Error("keys that end with '-bin' must have Buffer values"); + } + } + else { + if (Buffer.isBuffer(value)) { + throw new Error("keys that don't end with '-bin' must have String values"); + } + if (!isLegalNonBinaryValue(value)) { + throw new Error('Metadata string value "' + value + '" contains illegal characters'); + } + } + } +} +/** + * A class for storing metadata. Keys are normalized to lowercase ASCII. + */ +class Metadata { + constructor(options = {}) { + this.internalRepr = new Map(); + this.opaqueData = new Map(); + this.options = options; + } + /** + * Sets the given value for the given key by replacing any other values + * associated with that key. Normalizes the key. + * @param key The key to whose value should be set. + * @param value The value to set. Must be a buffer if and only + * if the normalized key ends with '-bin'. + */ + set(key, value) { + key = normalizeKey(key); + validate(key, value); + this.internalRepr.set(key, [value]); + } + /** + * Adds the given value for the given key by appending to a list of previous + * values associated with that key. Normalizes the key. + * @param key The key for which a new value should be appended. + * @param value The value to add. Must be a buffer if and only + * if the normalized key ends with '-bin'. + */ + add(key, value) { + key = normalizeKey(key); + validate(key, value); + const existingValue = this.internalRepr.get(key); + if (existingValue === undefined) { + this.internalRepr.set(key, [value]); + } + else { + existingValue.push(value); + } + } + /** + * Removes the given key and any associated values. Normalizes the key. + * @param key The key whose values should be removed. + */ + remove(key) { + key = normalizeKey(key); + // validate(key); + this.internalRepr.delete(key); + } + /** + * Gets a list of all values associated with the key. Normalizes the key. + * @param key The key whose value should be retrieved. + * @return A list of values associated with the given key. + */ + get(key) { + key = normalizeKey(key); + // validate(key); + return this.internalRepr.get(key) || []; + } + /** + * Gets a plain object mapping each key to the first value associated with it. + * This reflects the most common way that people will want to see metadata. + * @return A key/value mapping of the metadata. + */ + getMap() { + const result = {}; + for (const [key, values] of this.internalRepr) { + if (values.length > 0) { + const v = values[0]; + result[key] = Buffer.isBuffer(v) ? Buffer.from(v) : v; + } + } + return result; + } + /** + * Clones the metadata object. + * @return The newly cloned object. + */ + clone() { + const newMetadata = new Metadata(this.options); + const newInternalRepr = newMetadata.internalRepr; + for (const [key, value] of this.internalRepr) { + const clonedValue = value.map(v => { + if (Buffer.isBuffer(v)) { + return Buffer.from(v); + } + else { + return v; + } + }); + newInternalRepr.set(key, clonedValue); + } + return newMetadata; + } + /** + * Merges all key-value pairs from a given Metadata object into this one. + * If both this object and the given object have values in the same key, + * values from the other Metadata object will be appended to this object's + * values. + * @param other A Metadata object. + */ + merge(other) { + for (const [key, values] of other.internalRepr) { + const mergedValue = (this.internalRepr.get(key) || []).concat(values); + this.internalRepr.set(key, mergedValue); + } + } + setOptions(options) { + this.options = options; + } + getOptions() { + return this.options; + } + /** + * Creates an OutgoingHttpHeaders object that can be used with the http2 API. + */ + toHttp2Headers() { + // NOTE: Node <8.9 formats http2 headers incorrectly. + const result = {}; + for (const [key, values] of this.internalRepr) { + if (key.startsWith(':')) { + continue; + } + // We assume that the user's interaction with this object is limited to + // through its public API (i.e. keys and values are already validated). + result[key] = values.map(bufToString); + } + return result; + } + /** + * This modifies the behavior of JSON.stringify to show an object + * representation of the metadata map. + */ + toJSON() { + const result = {}; + for (const [key, values] of this.internalRepr) { + result[key] = values; + } + return result; + } + /** + * Attach additional data of any type to the metadata object, which will not + * be included when sending headers. The data can later be retrieved with + * `getOpaque`. Keys with the prefix `grpc` are reserved for use by this + * library. + * @param key + * @param value + */ + setOpaque(key, value) { + this.opaqueData.set(key, value); + } + /** + * Retrieve data previously added with `setOpaque`. + * @param key + * @returns + */ + getOpaque(key) { + return this.opaqueData.get(key); + } + /** + * Returns a new Metadata object based fields in a given IncomingHttpHeaders + * object. + * @param headers An IncomingHttpHeaders object. + */ + static fromHttp2Headers(headers) { + const result = new Metadata(); + for (const key of Object.keys(headers)) { + // Reserved headers (beginning with `:`) are not valid keys. + if (key.charAt(0) === ':') { + continue; + } + const values = headers[key]; + try { + if (isBinaryKey(key)) { + if (Array.isArray(values)) { + values.forEach(value => { + result.add(key, Buffer.from(value, 'base64')); + }); + } + else if (values !== undefined) { + if (isCustomMetadata(key)) { + values.split(',').forEach(v => { + result.add(key, Buffer.from(v.trim(), 'base64')); + }); + } + else { + result.add(key, Buffer.from(values, 'base64')); + } + } + } + else { + if (Array.isArray(values)) { + values.forEach(value => { + result.add(key, value); + }); + } + else if (values !== undefined) { + result.add(key, values); + } + } + } + catch (error) { + const message = `Failed to add metadata entry ${key}: ${values}. ${(0, error_1.getErrorMessage)(error)}. For more information see https://github.com/grpc/grpc-node/issues/1173`; + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, message); + } + } + return result; + } +} +exports.Metadata = Metadata; +const bufToString = (val) => { + return Buffer.isBuffer(val) ? val.toString('base64') : val; +}; +//# sourceMappingURL=metadata.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/metadata.js.map b/node_modules/@grpc/grpc-js/build/src/metadata.js.map new file mode 100644 index 0000000..ebf0111 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/metadata.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../src/metadata.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAGH,uCAAgC;AAChC,2CAA2C;AAC3C,mCAA0C;AAC1C,MAAM,eAAe,GAAG,iBAAiB,CAAC;AAC1C,MAAM,4BAA4B,GAAG,UAAU,CAAC;AAKhD,SAAS,UAAU,CAAC,GAAW;IAC7B,OAAO,eAAe,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACnC,CAAC;AAED,SAAS,qBAAqB,CAAC,KAAa;IAC1C,OAAO,4BAA4B,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAClD,CAAC;AAED,SAAS,WAAW,CAAC,GAAW;IAC9B,OAAO,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AAC9B,CAAC;AAED,SAAS,gBAAgB,CAAC,GAAW;IACnC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;AAClC,CAAC;AAED,SAAS,YAAY,CAAC,GAAW;IAC/B,OAAO,GAAG,CAAC,WAAW,EAAE,CAAC;AAC3B,CAAC;AAED,SAAS,QAAQ,CAAC,GAAW,EAAE,KAAqB;IAClD,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CAAC,gBAAgB,GAAG,GAAG,GAAG,+BAA+B,CAAC,CAAC;IAC5E,CAAC;IAED,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QAC1C,IAAI,WAAW,CAAC,GAAG,CA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AAC,CAAC,CAAC,CAAC,GAAG,CAAC;AAC7D,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/object-stream.d.ts b/node_modules/@grpc/grpc-js/build/src/object-stream.d.ts new file mode 100644 index 0000000..309fd03 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/object-stream.d.ts @@ -0,0 +1,27 @@ +import { Readable, Writable } from 'stream'; +import { EmitterAugmentation1 } from './events'; +export type WriteCallback = (error: Error | null | undefined) => void; +export interface IntermediateObjectReadable extends Readable { + read(size?: number): any & T; +} +export type ObjectReadable = { + read(size?: number): T; +} & EmitterAugmentation1<'data', T> & IntermediateObjectReadable; +export interface IntermediateObjectWritable extends Writable { + _write(chunk: any & T, encoding: string, callback: Function): void; + write(chunk: any & T, cb?: WriteCallback): boolean; + write(chunk: any & T, encoding?: any, cb?: WriteCallback): boolean; + setDefaultEncoding(encoding: string): this; + end(): ReturnType extends Writable ? this : void; + end(chunk: any & T, cb?: Function): ReturnType extends Writable ? this : void; + end(chunk: any & T, encoding?: any, cb?: Function): ReturnType extends Writable ? this : void; +} +export interface ObjectWritable extends IntermediateObjectWritable { + _write(chunk: T, encoding: string, callback: Function): void; + write(chunk: T, cb?: Function): boolean; + write(chunk: T, encoding?: any, cb?: Function): boolean; + setDefaultEncoding(encoding: string): this; + end(): ReturnType extends Writable ? this : void; + end(chunk: T, cb?: Function): ReturnType extends Writable ? this : void; + end(chunk: T, encoding?: any, cb?: Function): ReturnType extends Writable ? this : void; +} diff --git a/node_modules/@grpc/grpc-js/build/src/object-stream.js b/node_modules/@grpc/grpc-js/build/src/object-stream.js new file mode 100644 index 0000000..b947656 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/object-stream.js @@ -0,0 +1,19 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=object-stream.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/object-stream.js.map b/node_modules/@grpc/grpc-js/build/src/object-stream.js.map new file mode 100644 index 0000000..fe8b624 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/object-stream.js.map @@ -0,0 +1 @@ +{"version":3,"file":"object-stream.js","sourceRoot":"","sources":["../../src/object-stream.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/orca.d.ts b/node_modules/@grpc/grpc-js/build/src/orca.d.ts new file mode 100644 index 0000000..f15ea60 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/orca.d.ts @@ -0,0 +1,89 @@ +import { OrcaLoadReport__Output } from "./generated/xds/data/orca/v3/OrcaLoadReport"; +import { OpenRcaServiceClient } from "./generated/xds/service/orca/v3/OpenRcaService"; +import { Server } from "./server"; +import { Channel } from "./channel"; +import { OnCallEnded } from "./picker"; +import { BaseSubchannelWrapper, SubchannelInterface } from "./subchannel-interface"; +/** + * ORCA metrics recorder for a single request + */ +export declare class PerRequestMetricRecorder { + private message; + /** + * Records a request cost metric measurement for the call. + * @param name + * @param value + */ + recordRequestCostMetric(name: string, value: number): void; + /** + * Records a request cost metric measurement for the call. + * @param name + * @param value + */ + recordUtilizationMetric(name: string, value: number): void; + /** + * Records an opaque named metric measurement for the call. + * @param name + * @param value + */ + recordNamedMetric(name: string, value: number): void; + /** + * Records the CPU utilization metric measurement for the call. + * @param value + */ + recordCPUUtilizationMetric(value: number): void; + /** + * Records the memory utilization metric measurement for the call. + * @param value + */ + recordMemoryUtilizationMetric(value: number): void; + /** + * Records the memory utilization metric measurement for the call. + * @param value + */ + recordApplicationUtilizationMetric(value: number): void; + /** + * Records the queries per second measurement. + * @param value + */ + recordQpsMetric(value: number): void; + /** + * Records the errors per second measurement. + * @param value + */ + recordEpsMetric(value: number): void; + serialize(): Buffer; +} +export declare class ServerMetricRecorder { + private message; + private serviceImplementation; + putUtilizationMetric(name: string, value: number): void; + setAllUtilizationMetrics(metrics: { + [name: string]: number; + }): void; + deleteUtilizationMetric(name: string): void; + setCpuUtilizationMetric(value: number): void; + deleteCpuUtilizationMetric(): void; + setApplicationUtilizationMetric(value: number): void; + deleteApplicationUtilizationMetric(): void; + setQpsMetric(value: number): void; + deleteQpsMetric(): void; + setEpsMetric(value: number): void; + deleteEpsMetric(): void; + addToServer(server: Server): void; +} +export declare function createOrcaClient(channel: Channel): OpenRcaServiceClient; +export type MetricsListener = (loadReport: OrcaLoadReport__Output) => void; +export declare const GRPC_METRICS_HEADER = "endpoint-load-metrics-bin"; +/** + * Create an onCallEnded callback for use in a picker. + * @param listener The listener to handle metrics, whenever they are provided. + * @param previousOnCallEnded The previous onCallEnded callback to propagate + * to, if applicable. + * @returns + */ +export declare function createMetricsReader(listener: MetricsListener, previousOnCallEnded: OnCallEnded | null): OnCallEnded; +export declare class OrcaOobMetricsSubchannelWrapper extends BaseSubchannelWrapper { + constructor(child: SubchannelInterface, metricsListener: MetricsListener, intervalMs: number); + getWrappedSubchannel(): SubchannelInterface; +} diff --git a/node_modules/@grpc/grpc-js/build/src/orca.js b/node_modules/@grpc/grpc-js/build/src/orca.js new file mode 100644 index 0000000..5bcd57e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/orca.js @@ -0,0 +1,323 @@ +"use strict"; +/* + * Copyright 2025 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OrcaOobMetricsSubchannelWrapper = exports.GRPC_METRICS_HEADER = exports.ServerMetricRecorder = exports.PerRequestMetricRecorder = void 0; +exports.createOrcaClient = createOrcaClient; +exports.createMetricsReader = createMetricsReader; +const make_client_1 = require("./make-client"); +const duration_1 = require("./duration"); +const channel_credentials_1 = require("./channel-credentials"); +const subchannel_interface_1 = require("./subchannel-interface"); +const constants_1 = require("./constants"); +const backoff_timeout_1 = require("./backoff-timeout"); +const connectivity_state_1 = require("./connectivity-state"); +const loadedOrcaProto = null; +function loadOrcaProto() { + if (loadedOrcaProto) { + return loadedOrcaProto; + } + /* The purpose of this complexity is to avoid loading @grpc/proto-loader at + * runtime for users who will not use/enable ORCA. */ + const loaderLoadSync = require('@grpc/proto-loader') + .loadSync; + const loadedProto = loaderLoadSync('xds/service/orca/v3/orca.proto', { + keepCase: true, + longs: String, + enums: String, + defaults: true, + oneofs: true, + includeDirs: [ + `${__dirname}/../../proto/xds`, + `${__dirname}/../../proto/protoc-gen-validate` + ], + }); + return (0, make_client_1.loadPackageDefinition)(loadedProto); +} +/** + * ORCA metrics recorder for a single request + */ +class PerRequestMetricRecorder { + constructor() { + this.message = {}; + } + /** + * Records a request cost metric measurement for the call. + * @param name + * @param value + */ + recordRequestCostMetric(name, value) { + if (!this.message.request_cost) { + this.message.request_cost = {}; + } + this.message.request_cost[name] = value; + } + /** + * Records a request cost metric measurement for the call. + * @param name + * @param value + */ + recordUtilizationMetric(name, value) { + if (!this.message.utilization) { + this.message.utilization = {}; + } + this.message.utilization[name] = value; + } + /** + * Records an opaque named metric measurement for the call. + * @param name + * @param value + */ + recordNamedMetric(name, value) { + if (!this.message.named_metrics) { + this.message.named_metrics = {}; + } + this.message.named_metrics[name] = value; + } + /** + * Records the CPU utilization metric measurement for the call. + * @param value + */ + recordCPUUtilizationMetric(value) { + this.message.cpu_utilization = value; + } + /** + * Records the memory utilization metric measurement for the call. + * @param value + */ + recordMemoryUtilizationMetric(value) { + this.message.mem_utilization = value; + } + /** + * Records the memory utilization metric measurement for the call. + * @param value + */ + recordApplicationUtilizationMetric(value) { + this.message.application_utilization = value; + } + /** + * Records the queries per second measurement. + * @param value + */ + recordQpsMetric(value) { + this.message.rps_fractional = value; + } + /** + * Records the errors per second measurement. + * @param value + */ + recordEpsMetric(value) { + this.message.eps = value; + } + serialize() { + const orcaProto = loadOrcaProto(); + return orcaProto.xds.data.orca.v3.OrcaLoadReport.serialize(this.message); + } +} +exports.PerRequestMetricRecorder = PerRequestMetricRecorder; +const DEFAULT_REPORT_INTERVAL_MS = 30000; +class ServerMetricRecorder { + constructor() { + this.message = {}; + this.serviceImplementation = { + StreamCoreMetrics: call => { + const reportInterval = call.request.report_interval ? + (0, duration_1.durationToMs)((0, duration_1.durationMessageToDuration)(call.request.report_interval)) : + DEFAULT_REPORT_INTERVAL_MS; + const reportTimer = setInterval(() => { + call.write(this.message); + }, reportInterval); + call.on('cancelled', () => { + clearInterval(reportTimer); + }); + } + }; + } + putUtilizationMetric(name, value) { + if (!this.message.utilization) { + this.message.utilization = {}; + } + this.message.utilization[name] = value; + } + setAllUtilizationMetrics(metrics) { + this.message.utilization = Object.assign({}, metrics); + } + deleteUtilizationMetric(name) { + var _a; + (_a = this.message.utilization) === null || _a === void 0 ? true : delete _a[name]; + } + setCpuUtilizationMetric(value) { + this.message.cpu_utilization = value; + } + deleteCpuUtilizationMetric() { + delete this.message.cpu_utilization; + } + setApplicationUtilizationMetric(value) { + this.message.application_utilization = value; + } + deleteApplicationUtilizationMetric() { + delete this.message.application_utilization; + } + setQpsMetric(value) { + this.message.rps_fractional = value; + } + deleteQpsMetric() { + delete this.message.rps_fractional; + } + setEpsMetric(value) { + this.message.eps = value; + } + deleteEpsMetric() { + delete this.message.eps; + } + addToServer(server) { + const serviceDefinition = loadOrcaProto().xds.service.orca.v3.OpenRcaService.service; + server.addService(serviceDefinition, this.serviceImplementation); + } +} +exports.ServerMetricRecorder = ServerMetricRecorder; +function createOrcaClient(channel) { + const ClientClass = loadOrcaProto().xds.service.orca.v3.OpenRcaService; + return new ClientClass('unused', channel_credentials_1.ChannelCredentials.createInsecure(), { channelOverride: channel }); +} +exports.GRPC_METRICS_HEADER = 'endpoint-load-metrics-bin'; +const PARSED_LOAD_REPORT_KEY = 'grpc_orca_load_report'; +/** + * Create an onCallEnded callback for use in a picker. + * @param listener The listener to handle metrics, whenever they are provided. + * @param previousOnCallEnded The previous onCallEnded callback to propagate + * to, if applicable. + * @returns + */ +function createMetricsReader(listener, previousOnCallEnded) { + return (code, details, metadata) => { + let parsedLoadReport = metadata.getOpaque(PARSED_LOAD_REPORT_KEY); + if (parsedLoadReport) { + listener(parsedLoadReport); + } + else { + const serializedLoadReport = metadata.get(exports.GRPC_METRICS_HEADER); + if (serializedLoadReport.length > 0) { + const orcaProto = loadOrcaProto(); + parsedLoadReport = orcaProto.xds.data.orca.v3.OrcaLoadReport.deserialize(serializedLoadReport[0]); + listener(parsedLoadReport); + metadata.setOpaque(PARSED_LOAD_REPORT_KEY, parsedLoadReport); + } + } + if (previousOnCallEnded) { + previousOnCallEnded(code, details, metadata); + } + }; +} +const DATA_PRODUCER_KEY = 'orca_oob_metrics'; +class OobMetricsDataWatcher { + constructor(metricsListener, intervalMs) { + this.metricsListener = metricsListener; + this.intervalMs = intervalMs; + this.dataProducer = null; + } + setSubchannel(subchannel) { + const producer = subchannel.getOrCreateDataProducer(DATA_PRODUCER_KEY, createOobMetricsDataProducer); + this.dataProducer = producer; + producer.addDataWatcher(this); + } + destroy() { + var _a; + (_a = this.dataProducer) === null || _a === void 0 ? void 0 : _a.removeDataWatcher(this); + } + getInterval() { + return this.intervalMs; + } + onMetricsUpdate(metrics) { + this.metricsListener(metrics); + } +} +class OobMetricsDataProducer { + constructor(subchannel) { + this.subchannel = subchannel; + this.dataWatchers = new Set(); + this.orcaSupported = true; + this.metricsCall = null; + this.currentInterval = Infinity; + this.backoffTimer = new backoff_timeout_1.BackoffTimeout(() => this.updateMetricsSubscription()); + this.subchannelStateListener = () => this.updateMetricsSubscription(); + const channel = subchannel.getChannel(); + this.client = createOrcaClient(channel); + subchannel.addConnectivityStateListener(this.subchannelStateListener); + } + addDataWatcher(dataWatcher) { + this.dataWatchers.add(dataWatcher); + this.updateMetricsSubscription(); + } + removeDataWatcher(dataWatcher) { + var _a; + this.dataWatchers.delete(dataWatcher); + if (this.dataWatchers.size === 0) { + this.subchannel.removeDataProducer(DATA_PRODUCER_KEY); + (_a = this.metricsCall) === null || _a === void 0 ? void 0 : _a.cancel(); + this.metricsCall = null; + this.client.close(); + this.subchannel.removeConnectivityStateListener(this.subchannelStateListener); + } + else { + this.updateMetricsSubscription(); + } + } + updateMetricsSubscription() { + var _a; + if (this.dataWatchers.size === 0 || !this.orcaSupported || this.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { + return; + } + const newInterval = Math.min(...Array.from(this.dataWatchers).map(watcher => watcher.getInterval())); + if (!this.metricsCall || newInterval !== this.currentInterval) { + (_a = this.metricsCall) === null || _a === void 0 ? void 0 : _a.cancel(); + this.currentInterval = newInterval; + const metricsCall = this.client.streamCoreMetrics({ report_interval: (0, duration_1.msToDuration)(newInterval) }); + this.metricsCall = metricsCall; + metricsCall.on('data', (report) => { + this.dataWatchers.forEach(watcher => { + watcher.onMetricsUpdate(report); + }); + }); + metricsCall.on('error', (error) => { + this.metricsCall = null; + if (error.code === constants_1.Status.UNIMPLEMENTED) { + this.orcaSupported = false; + return; + } + if (error.code === constants_1.Status.CANCELLED) { + return; + } + this.backoffTimer.runOnce(); + }); + } + } +} +class OrcaOobMetricsSubchannelWrapper extends subchannel_interface_1.BaseSubchannelWrapper { + constructor(child, metricsListener, intervalMs) { + super(child); + this.addDataWatcher(new OobMetricsDataWatcher(metricsListener, intervalMs)); + } + getWrappedSubchannel() { + return this.child; + } +} +exports.OrcaOobMetricsSubchannelWrapper = OrcaOobMetricsSubchannelWrapper; +function createOobMetricsDataProducer(subchannel) { + return new OobMetricsDataProducer(subchannel); +} +//# sourceMappingURL=orca.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/orca.js.map b/node_modules/@grpc/grpc-js/build/src/orca.js.map new file mode 100644 index 0000000..5c6736f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/orca.js.map @@ -0,0 +1 @@ +{"version":3,"file":"orca.js","sourceRoot":"","sources":["../../src/orca.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AA2MH,4CAGC;AAcD,kDAkBC;AAxOD,+CAAsD;AAEtD,yCAAmF;AAEnF,+DAA2D;AAI3D,iEAAiG;AAEjG,2CAAqC;AACrC,uDAAmD;AACnD,6DAAyD;AAEzD,MAAM,eAAe,GAA6B,IAAI,CAAC;AACvD,SAAS,aAAa;IACpB,IAAI,eAAe,EAAE,CAAC;QACpB,OAAO,eAAe,CAAC;IACzB,CAAC;IACD;yDACqD;IACrD,MAAM,cAAc,GAAG,OAAO,CAAC,oBAAoB,CAAC;SACjD,QAA2B,CAAC;IAC/B,MAAM,WAAW,GAAG,cAAc,CAAC,gCAAgC,EAAE;QACnE,QAAQ,EAAE,IAAI;QACd,KAAK,EAAE,MAAM;QACb,KAAK,EAAE,MAAM;QACb,QAAQ,EAAE,IAAI;QACd,MAAM,EAAE,IAAI;QACZ,WAAW,EAAE;YACX,GAAG,SAAS,kBAAkB;YAC9B,GAAG,SAAS,kCAAkC;SAC/C;KACF,CAAC,CAAC;IACH,OAAO,IAAA,mCAAqB,EAAC,WAAW,CAAiC,CAAC;AAC5E,CAAC;AAED;;GAEG;AACH,MAAa,wBAAwB;IAArC;QACU,YAAO,GAAmB,EAAE,CAAC;IAkFvC,CAAC;IAhFC;;;;OAIG;IACH,uBAAuB,CAAC,IAAY,EAAE,KAAa;QACjD,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,YAAY,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A8B,EAAE,EAAE;gBACxD,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;oBAClC,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;gBAClC,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;YACH,WAAW,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,KAAmB,EAAE,EAAE;gBAC9C,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;gBACxB,IAAI,KAAK,CAAC,IAAI,KAAK,kBAAM,CAAC,aAAa,EAAE,CAAC;oBACxC,IAAI,CAAC,aAAa,GAAG,KAAK,CAAC;oBAC3B,OAAO;gBACT,CAAC;gBACD,IAAI,KAAK,CAAC,IAAI,KAAK,kBAAM,CAAC,SAAS,EAAE,CAAC;oBACpC,OAAO;gBACT,CAAC;gBACD,IAAI,CAAC,YAAY,CAAC,OAAO,EAAE,CAAC;YAC9B,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;CACF;AAED,MAAa,+BAAgC,SAAQ,4CAAqB;IACxE,YAAY,KAA0B,EAAE,eAAgC,EAAE,UAAkB;QAC1F,KAAK,CAAC,KAAK,CAAC,CAAC;QACb,IAAI,CAAC,cAAc,CAAC,IAAI,qBAAqB,CAAC,eAAe,EAAE,UAAU,CAAC,CAAC,CAAC;IAC9E,CAAC;IAED,oBAAoB;QAClB,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;CACF;AATD,0EASC;AAED,SAAS,4BAA4B,CAAC,UAAsB;IAC1D,OAAO,IAAI,sBAAsB,CAAC,UAAU,CAAC,CAAC;AAChD,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/picker.d.ts b/node_modules/@grpc/grpc-js/build/src/picker.d.ts new file mode 100644 index 0000000..8a9a915 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/picker.d.ts @@ -0,0 +1,95 @@ +import { StatusObject } from './call-interface'; +import { Metadata } from './metadata'; +import { Status } from './constants'; +import { LoadBalancer } from './load-balancer'; +import { SubchannelInterface } from './subchannel-interface'; +export declare enum PickResultType { + COMPLETE = 0, + QUEUE = 1, + TRANSIENT_FAILURE = 2, + DROP = 3 +} +export type OnCallEnded = (statusCode: Status, details: string, metadata: Metadata) => void; +export interface PickResult { + pickResultType: PickResultType; + /** + * The subchannel to use as the transport for the call. Only meaningful if + * `pickResultType` is COMPLETE. If null, indicates that the call should be + * dropped. + */ + subchannel: SubchannelInterface | null; + /** + * The status object to end the call with. Populated if and only if + * `pickResultType` is TRANSIENT_FAILURE. + */ + status: StatusObject | null; + onCallStarted: (() => void) | null; + onCallEnded: OnCallEnded | null; +} +export interface CompletePickResult extends PickResult { + pickResultType: PickResultType.COMPLETE; + subchannel: SubchannelInterface | null; + status: null; + onCallStarted: (() => void) | null; + onCallEnded: OnCallEnded | null; +} +export interface QueuePickResult extends PickResult { + pickResultType: PickResultType.QUEUE; + subchannel: null; + status: null; + onCallStarted: null; + onCallEnded: null; +} +export interface TransientFailurePickResult extends PickResult { + pickResultType: PickResultType.TRANSIENT_FAILURE; + subchannel: null; + status: StatusObject; + onCallStarted: null; + onCallEnded: null; +} +export interface DropCallPickResult extends PickResult { + pickResultType: PickResultType.DROP; + subchannel: null; + status: StatusObject; + onCallStarted: null; + onCallEnded: null; +} +export interface PickArgs { + metadata: Metadata; + extraPickInfo: { + [key: string]: string; + }; +} +/** + * A proxy object representing the momentary state of a load balancer. Picks + * subchannels or returns other information based on that state. Should be + * replaced every time the load balancer changes state. + */ +export interface Picker { + pick(pickArgs: PickArgs): PickResult; +} +/** + * A standard picker representing a load balancer in the TRANSIENT_FAILURE + * state. Always responds to every pick request with an UNAVAILABLE status. + */ +export declare class UnavailablePicker implements Picker { + private status; + constructor(status?: Partial); + pick(pickArgs: PickArgs): TransientFailurePickResult; +} +/** + * A standard picker representing a load balancer in the IDLE or CONNECTING + * state. Always responds to every pick request with a QUEUE pick result + * indicating that the pick should be tried again with the next `Picker`. Also + * reports back to the load balancer that a connection should be established + * once any pick is attempted. + * If the childPicker is provided, delegate to it instead of returning the + * hardcoded QUEUE pick result, but still calls exitIdle. + */ +export declare class QueuePicker { + private loadBalancer; + private childPicker?; + private calledExitIdle; + constructor(loadBalancer: LoadBalancer, childPicker?: Picker | undefined); + pick(pickArgs: PickArgs): PickResult; +} diff --git a/node_modules/@grpc/grpc-js/build/src/picker.js b/node_modules/@grpc/grpc-js/build/src/picker.js new file mode 100644 index 0000000..e796f09 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/picker.js @@ -0,0 +1,86 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.QueuePicker = exports.UnavailablePicker = exports.PickResultType = void 0; +const metadata_1 = require("./metadata"); +const constants_1 = require("./constants"); +var PickResultType; +(function (PickResultType) { + PickResultType[PickResultType["COMPLETE"] = 0] = "COMPLETE"; + PickResultType[PickResultType["QUEUE"] = 1] = "QUEUE"; + PickResultType[PickResultType["TRANSIENT_FAILURE"] = 2] = "TRANSIENT_FAILURE"; + PickResultType[PickResultType["DROP"] = 3] = "DROP"; +})(PickResultType || (exports.PickResultType = PickResultType = {})); +/** + * A standard picker representing a load balancer in the TRANSIENT_FAILURE + * state. Always responds to every pick request with an UNAVAILABLE status. + */ +class UnavailablePicker { + constructor(status) { + this.status = Object.assign({ code: constants_1.Status.UNAVAILABLE, details: 'No connection established', metadata: new metadata_1.Metadata() }, status); + } + pick(pickArgs) { + return { + pickResultType: PickResultType.TRANSIENT_FAILURE, + subchannel: null, + status: this.status, + onCallStarted: null, + onCallEnded: null, + }; + } +} +exports.UnavailablePicker = UnavailablePicker; +/** + * A standard picker representing a load balancer in the IDLE or CONNECTING + * state. Always responds to every pick request with a QUEUE pick result + * indicating that the pick should be tried again with the next `Picker`. Also + * reports back to the load balancer that a connection should be established + * once any pick is attempted. + * If the childPicker is provided, delegate to it instead of returning the + * hardcoded QUEUE pick result, but still calls exitIdle. + */ +class QueuePicker { + // Constructed with a load balancer. Calls exitIdle on it the first time pick is called + constructor(loadBalancer, childPicker) { + this.loadBalancer = loadBalancer; + this.childPicker = childPicker; + this.calledExitIdle = false; + } + pick(pickArgs) { + if (!this.calledExitIdle) { + process.nextTick(() => { + this.loadBalancer.exitIdle(); + }); + this.calledExitIdle = true; + } + if (this.childPicker) { + return this.childPicker.pick(pickArgs); + } + else { + return { + pickResultType: PickResultType.QUEUE, + subchannel: null, + status: null, + onCallStarted: null, + onCallEnded: null, + }; + } + } +} +exports.QueuePicker = QueuePicker; +//# sourceMappingURL=picker.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/picker.js.map b/node_modules/@grpc/grpc-js/build/src/picker.js.map new file mode 100644 index 0000000..5853180 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/picker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"picker.js","sourceRoot":"","sources":["../../src/picker.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAGH,yCAAsC;AACtC,2CAAqC;AAIrC,IAAY,cAKX;AALD,WAAY,cAAc;IACxB,2DAAQ,CAAA;IACR,qDAAK,CAAA;IACL,6EAAiB,CAAA;IACjB,mDAAI,CAAA;AACN,CAAC,EALW,cAAc,8BAAd,cAAc,QAKzB;AAmED;;;GAGG;AACH,MAAa,iBAAiB;IAE5B,YAAY,MAA8B;QACxC,IAAI,CAAC,MAAM,mBACT,IAAI,EAAE,kBAAM,CAAC,WAAW,EACxB,OAAO,EAAE,2BAA2B,EACpC,QAAQ,EAAE,IAAI,mBAAQ,EAAE,IACrB,MAAM,CACV,CAAC;IACJ,CAAC;IACD,IAAI,CAAC,QAAkB;QACrB,OAAO;YACL,cAAc,EAAE,cAAc,CAAC,iBAAiB;YAChD,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,aAAa,EAAE,IAAI;YACnB,WAAW,EAAE,IAAI;SAClB,CAAC;IACJ,CAAC;CACF;AAnBD,8CAmBC;AAED;;;;;;;;GAQG;AACH,MAAa,WAAW;IAEtB,uFAAuF;IACvF,YACU,YAA0B,EAC1B,WAAoB;QADpB,iBAAY,GAAZ,YAAY,CAAc;QAC1B,gBAAW,GAAX,WAAW,CAAS;QAJtB,mBAAc,GAAG,KAAK,CAAC;IAK5B,CAAC;IAEJ,IAAI,CAAC,QAAkB;QACrB,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC;YACzB,OAAO,CAAC,QAAQ,CAAC,GAAG,EAAE;gBACpB,IAAI,CAAC,YAAY,CAAC,QAAQ,EAAE,CAAC;YAC/B,CAAC,CAAC,CAAC;YACH,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;QAC7B,CAAC;QACD,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;YACrB,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACzC,CAAC;aAAM,CAAC;YACN,OAAO;gBACL,cAAc,EAAE,cAAc,CAAC,KAAK;gBACpC,UAAU,EAAE,IAAI;gBAChB,MAAM,EAAE,IAAI;gBACZ,aAAa,EAAE,IAAI;gBACnB,WAAW,EAAE,IAAI;aAClB,CAAC;QACJ,CAAC;IACH,CAAC;CACF;AA3BD,kCA2BC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/priority-queue.d.ts b/node_modules/@grpc/grpc-js/build/src/priority-queue.d.ts new file mode 100644 index 0000000..6ce3c7a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/priority-queue.d.ts @@ -0,0 +1,50 @@ +/** + * A generic priority queue implemented as an array-based binary heap. + * Adapted from https://stackoverflow.com/a/42919752/159388 + */ +export declare class PriorityQueue { + private readonly comparator; + private readonly heap; + /** + * + * @param comparator Returns true if the first argument should precede the + * second in the queue. Defaults to `(a, b) => a > b` + */ + constructor(comparator?: (a: T, b: T) => boolean); + /** + * @returns The number of items currently in the queue + */ + size(): number; + /** + * @returns True if there are no items in the queue, false otherwise + */ + isEmpty(): boolean; + /** + * Look at the front item that would be popped, without modifying the contents + * of the queue + * @returns The front item in the queue, or undefined if the queue is empty + */ + peek(): T | undefined; + /** + * Add the items to the queue + * @param values The items to add + * @returns The new size of the queue after adding the items + */ + push(...values: T[]): number; + /** + * Remove the front item in the queue and return it + * @returns The front item in the queue, or undefined if the queue is empty + */ + pop(): T | undefined; + /** + * Simultaneously remove the front item in the queue and add the provided + * item. + * @param value The item to add + * @returns The front item in the queue, or undefined if the queue is empty + */ + replace(value: T): T | undefined; + private greater; + private swap; + private siftUp; + private siftDown; +} diff --git a/node_modules/@grpc/grpc-js/build/src/priority-queue.js b/node_modules/@grpc/grpc-js/build/src/priority-queue.js new file mode 100644 index 0000000..8628b56 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/priority-queue.js @@ -0,0 +1,120 @@ +"use strict"; +/* + * Copyright 2025 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PriorityQueue = void 0; +const top = 0; +const parent = (i) => Math.floor(i / 2); +const left = (i) => i * 2 + 1; +const right = (i) => i * 2 + 2; +/** + * A generic priority queue implemented as an array-based binary heap. + * Adapted from https://stackoverflow.com/a/42919752/159388 + */ +class PriorityQueue { + /** + * + * @param comparator Returns true if the first argument should precede the + * second in the queue. Defaults to `(a, b) => a > b` + */ + constructor(comparator = (a, b) => a > b) { + this.comparator = comparator; + this.heap = []; + } + /** + * @returns The number of items currently in the queue + */ + size() { + return this.heap.length; + } + /** + * @returns True if there are no items in the queue, false otherwise + */ + isEmpty() { + return this.size() == 0; + } + /** + * Look at the front item that would be popped, without modifying the contents + * of the queue + * @returns The front item in the queue, or undefined if the queue is empty + */ + peek() { + return this.heap[top]; + } + /** + * Add the items to the queue + * @param values The items to add + * @returns The new size of the queue after adding the items + */ + push(...values) { + values.forEach(value => { + this.heap.push(value); + this.siftUp(); + }); + return this.size(); + } + /** + * Remove the front item in the queue and return it + * @returns The front item in the queue, or undefined if the queue is empty + */ + pop() { + const poppedValue = this.peek(); + const bottom = this.size() - 1; + if (bottom > top) { + this.swap(top, bottom); + } + this.heap.pop(); + this.siftDown(); + return poppedValue; + } + /** + * Simultaneously remove the front item in the queue and add the provided + * item. + * @param value The item to add + * @returns The front item in the queue, or undefined if the queue is empty + */ + replace(value) { + const replacedValue = this.peek(); + this.heap[top] = value; + this.siftDown(); + return replacedValue; + } + greater(i, j) { + return this.comparator(this.heap[i], this.heap[j]); + } + swap(i, j) { + [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]]; + } + siftUp() { + let node = this.size() - 1; + while (node > top && this.greater(node, parent(node))) { + this.swap(node, parent(node)); + node = parent(node); + } + } + siftDown() { + let node = top; + while ((left(node) < this.size() && this.greater(left(node), node)) || + (right(node) < this.size() && this.greater(right(node), node))) { + let maxChild = (right(node) < this.size() && this.greater(right(node), left(node))) ? right(node) : left(node); + this.swap(node, maxChild); + node = maxChild; + } + } +} +exports.PriorityQueue = PriorityQueue; +//# sourceMappingURL=priority-queue.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/priority-queue.js.map b/node_modules/@grpc/grpc-js/build/src/priority-queue.js.map new file mode 100644 index 0000000..06fd2ee --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/priority-queue.js.map @@ -0,0 +1 @@ +{"version":3,"file":"priority-queue.js","sourceRoot":"","sources":["../../src/priority-queue.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,MAAM,GAAG,GAAG,CAAC,CAAC;AACd,MAAM,MAAM,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAChD,MAAM,IAAI,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACtC,MAAM,KAAK,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAEvC;;;GAGG;AACH,MAAa,aAAa;IAExB;;;;OAIG;IACH,YAA6B,aAAa,CAAC,CAAI,EAAE,CAAI,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC;QAAlC,eAAU,GAAV,UAAU,CAAwB;QAN9C,SAAI,GAAQ,EAAE,CAAC;IAMkC,CAAC;IAEnE;;OAEG;IACH,IAAI;QACF,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC;IAC1B,CAAC;IACD;;OAEG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC1B,CAAC;IACD;;;;OAIG;IACH,IAAI;QACF,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACxB,CAAC;IACD;;;;OAIG;IACH,IAAI,CAAC,GAAG,MAAW;QACjB,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;YACrB,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACtB,IAAI,CAAC,MAAM,EAAE,CAAC;QAChB,CAAC,CAAC,CAAC;QACH,OAAO,IAAI,CAAC,IAAI,EAAE,CAAC;IACrB,CAAC;IACD;;;OAGG;IAC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,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;YAC9B,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;QACtB,CAAC;IACH,CAAC;IACO,QAAQ;QACd,IAAI,IAAI,GAAG,GAAG,CAAC;QACf,OACE,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,EAAE,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;YAC5D,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,EAAE,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC,EAC9D,CAAC;YACD,IAAI,QAAQ,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,EAAE,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAC/G,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;YAC1B,IAAI,GAAG,QAAQ,CAAC;QAClB,CAAC;IACH,CAAC;CACF;AA3FD,sCA2FC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolver-dns.d.ts b/node_modules/@grpc/grpc-js/build/src/resolver-dns.d.ts new file mode 100644 index 0000000..138f7f1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver-dns.d.ts @@ -0,0 +1,13 @@ +/** + * The default TCP port to connect to if not explicitly specified in the target. + */ +export declare const DEFAULT_PORT = 443; +/** + * Set up the DNS resolver class by registering it as the handler for the + * "dns:" prefix and as the default resolver. + */ +export declare function setup(): void; +export interface DnsUrl { + host: string; + port?: string; +} diff --git a/node_modules/@grpc/grpc-js/build/src/resolver-dns.js b/node_modules/@grpc/grpc-js/build/src/resolver-dns.js new file mode 100644 index 0000000..1221464 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver-dns.js @@ -0,0 +1,363 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DEFAULT_PORT = void 0; +exports.setup = setup; +const resolver_1 = require("./resolver"); +const dns_1 = require("dns"); +const service_config_1 = require("./service-config"); +const constants_1 = require("./constants"); +const call_interface_1 = require("./call-interface"); +const metadata_1 = require("./metadata"); +const logging = require("./logging"); +const constants_2 = require("./constants"); +const uri_parser_1 = require("./uri-parser"); +const net_1 = require("net"); +const backoff_timeout_1 = require("./backoff-timeout"); +const environment_1 = require("./environment"); +const TRACER_NAME = 'dns_resolver'; +function trace(text) { + logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text); +} +/** + * The default TCP port to connect to if not explicitly specified in the target. + */ +exports.DEFAULT_PORT = 443; +const DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS = 30000; +/** + * Resolver implementation that handles DNS names and IP addresses. + */ +class DnsResolver { + constructor(target, listener, channelOptions) { + var _a, _b, _c; + this.target = target; + this.listener = listener; + this.pendingLookupPromise = null; + this.pendingTxtPromise = null; + this.latestLookupResult = null; + this.latestServiceConfigResult = null; + this.continueResolving = false; + this.isNextResolutionTimerRunning = false; + this.isServiceConfigEnabled = true; + this.returnedIpResult = false; + this.alternativeResolver = new dns_1.promises.Resolver(); + trace('Resolver constructed for target ' + (0, uri_parser_1.uriToString)(target)); + if (target.authority) { + this.alternativeResolver.setServers([target.authority]); + } + const hostPort = (0, uri_parser_1.splitHostPort)(target.path); + if (hostPort === null) { + this.ipResult = null; + this.dnsHostname = null; + this.port = null; + } + else { + if ((0, net_1.isIPv4)(hostPort.host) || (0, net_1.isIPv6)(hostPort.host)) { + this.ipResult = [ + { + addresses: [ + { + host: hostPort.host, + port: (_a = hostPort.port) !== null && _a !== void 0 ? _a : exports.DEFAULT_PORT, + }, + ], + }, + ]; + this.dnsHostname = null; + this.port = null; + } + else { + this.ipResult = null; + this.dnsHostname = hostPort.host; + this.port = (_b = hostPort.port) !== null && _b !== void 0 ? _b : exports.DEFAULT_PORT; + } + } + this.percentage = Math.random() * 100; + if (channelOptions['grpc.service_config_disable_resolution'] === 1) { + this.isServiceConfigEnabled = false; + } + this.defaultResolutionError = { + code: constants_1.Status.UNAVAILABLE, + details: `Name resolution failed for target ${(0, uri_parser_1.uriToString)(this.target)}`, + metadata: new metadata_1.Metadata(), + }; + const backoffOptions = { + initialDelay: channelOptions['grpc.initial_reconnect_backoff_ms'], + maxDelay: channelOptions['grpc.max_reconnect_backoff_ms'], + }; + this.backoff = new backoff_timeout_1.BackoffTimeout(() => { + if (this.continueResolving) { + this.startResolutionWithBackoff(); + } + }, backoffOptions); + this.backoff.unref(); + this.minTimeBetweenResolutionsMs = + (_c = channelOptions['grpc.dns_min_time_between_resolutions_ms']) !== null && _c !== void 0 ? _c : DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS; + this.nextResolutionTimer = setTimeout(() => { }, 0); + clearTimeout(this.nextResolutionTimer); + } + /** + * If the target is an IP address, just provide that address as a result. + * Otherwise, initiate A, AAAA, and TXT lookups + */ + startResolution() { + if (this.ipResult !== null) { + if (!this.returnedIpResult) { + trace('Returning IP address for target ' + (0, uri_parser_1.uriToString)(this.target)); + setImmediate(() => { + this.listener((0, call_interface_1.statusOrFromValue)(this.ipResult), {}, null, ''); + }); + this.returnedIpResult = true; + } + this.backoff.stop(); + this.backoff.reset(); + this.stopNextResolutionTimer(); + return; + } + if (this.dnsHostname === null) { + trace('Failed to parse DNS address ' + (0, uri_parser_1.uriToString)(this.target)); + setImmediate(() => { + this.listener((0, call_interface_1.statusOrFromError)({ + code: constants_1.Status.UNAVAILABLE, + details: `Failed to parse DNS address ${(0, uri_parser_1.uriToString)(this.target)}` + }), {}, null, ''); + }); + this.stopNextResolutionTimer(); + } + else { + if (this.pendingLookupPromise !== null) { + return; + } + trace('Looking up DNS hostname ' + this.dnsHostname); + /* We clear out latestLookupResult here to ensure that it contains the + * latest result since the last time we started resolving. That way, the + * TXT resolution handler can use it, but only if it finishes second. We + * don't clear out any previous service config results because it's + * better to use a service config that's slightly out of date than to + * revert to an effectively blank one. */ + this.latestLookupResult = null; + const hostname = this.dnsHostname; + this.pendingLookupPromise = this.lookup(hostname); + this.pendingLookupPromise.then(addressList => { + if (this.pendingLookupPromise === null) { + return; + } + this.pendingLookupPromise = null; + this.latestLookupResult = (0, call_interface_1.statusOrFromValue)(addressList.map(address => ({ + addresses: [address], + }))); + const allAddressesString = '[' + + addressList.map(addr => addr.host + ':' + addr.port).join(',') + + ']'; + trace('Resolved addresses for target ' + + (0, uri_parser_1.uriToString)(this.target) + + ': ' + + allAddressesString); + /* If the TXT lookup has not yet finished, both of the last two + * arguments will be null, which is the equivalent of getting an + * empty TXT response. When the TXT lookup does finish, its handler + * can update the service config by using the same address list */ + const healthStatus = this.listener(this.latestLookupResult, {}, this.latestServiceConfigResult, ''); + this.handleHealthStatus(healthStatus); + }, err => { + if (this.pendingLookupPromise === null) { + return; + } + trace('Resolution error for target ' + + (0, uri_parser_1.uriToString)(this.target) + + ': ' + + err.message); + this.pendingLookupPromise = null; + this.stopNextResolutionTimer(); + this.listener((0, call_interface_1.statusOrFromError)(this.defaultResolutionError), {}, this.latestServiceConfigResult, ''); + }); + /* If there already is a still-pending TXT resolution, we can just use + * that result when it comes in */ + if (this.isServiceConfigEnabled && this.pendingTxtPromise === null) { + /* We handle the TXT query promise differently than the others because + * the name resolution attempt as a whole is a success even if the TXT + * lookup fails */ + this.pendingTxtPromise = this.resolveTxt(hostname); + this.pendingTxtPromise.then(txtRecord => { + if (this.pendingTxtPromise === null) { + return; + } + this.pendingTxtPromise = null; + let serviceConfig; + try { + serviceConfig = (0, service_config_1.extractAndSelectServiceConfig)(txtRecord, this.percentage); + if (serviceConfig) { + this.latestServiceConfigResult = (0, call_interface_1.statusOrFromValue)(serviceConfig); + } + else { + this.latestServiceConfigResult = null; + } + } + catch (err) { + this.latestServiceConfigResult = (0, call_interface_1.statusOrFromError)({ + code: constants_1.Status.UNAVAILABLE, + details: `Parsing service config failed with error ${err.message}` + }); + } + if (this.latestLookupResult !== null) { + /* We rely here on the assumption that calling this function with + * identical parameters will be essentialy idempotent, and calling + * it with the same address list and a different service config + * should result in a fast and seamless switchover. */ + this.listener(this.latestLookupResult, {}, this.latestServiceConfigResult, ''); + } + }, err => { + /* If TXT lookup fails we should do nothing, which means that we + * continue to use the result of the most recent successful lookup, + * or the default null config object if there has never been a + * successful lookup. We do not set the latestServiceConfigError + * here because that is specifically used for response validation + * errors. We still need to handle this error so that it does not + * bubble up as an unhandled promise rejection. */ + }); + } + } + } + /** + * The ResolverListener returns a boolean indicating whether the LB policy + * accepted the resolution result. A false result on an otherwise successful + * resolution should be treated as a resolution failure. + * @param healthStatus + */ + handleHealthStatus(healthStatus) { + if (healthStatus) { + this.backoff.stop(); + this.backoff.reset(); + } + else { + this.continueResolving = true; + } + } + async lookup(hostname) { + if (environment_1.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) { + trace('Using alternative DNS resolver.'); + const records = await Promise.allSettled([ + this.alternativeResolver.resolve4(hostname), + this.alternativeResolver.resolve6(hostname), + ]); + if (records.every(result => result.status === 'rejected')) { + throw new Error(records[0].reason); + } + return records + .reduce((acc, result) => { + return result.status === 'fulfilled' + ? [...acc, ...result.value] + : acc; + }, []) + .map(addr => ({ + host: addr, + port: +this.port, + })); + } + /* We lookup both address families here and then split them up later + * because when looking up a single family, dns.lookup outputs an error + * if the name exists but there are no records for that family, and that + * error is indistinguishable from other kinds of errors */ + const addressList = await dns_1.promises.lookup(hostname, { all: true }); + return addressList.map(addr => ({ host: addr.address, port: +this.port })); + } + async resolveTxt(hostname) { + if (environment_1.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) { + trace('Using alternative DNS resolver.'); + return this.alternativeResolver.resolveTxt(hostname); + } + return dns_1.promises.resolveTxt(hostname); + } + startNextResolutionTimer() { + var _a, _b; + clearTimeout(this.nextResolutionTimer); + this.nextResolutionTimer = setTimeout(() => { + this.stopNextResolutionTimer(); + if (this.continueResolving) { + this.startResolutionWithBackoff(); + } + }, this.minTimeBetweenResolutionsMs); + (_b = (_a = this.nextResolutionTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + this.isNextResolutionTimerRunning = true; + } + stopNextResolutionTimer() { + clearTimeout(this.nextResolutionTimer); + this.isNextResolutionTimerRunning = false; + } + startResolutionWithBackoff() { + if (this.pendingLookupPromise === null) { + this.continueResolving = false; + this.backoff.runOnce(); + this.startNextResolutionTimer(); + this.startResolution(); + } + } + updateResolution() { + /* If there is a pending lookup, just let it finish. Otherwise, if the + * nextResolutionTimer or backoff timer is running, set the + * continueResolving flag to resolve when whichever of those timers + * fires. Otherwise, start resolving immediately. */ + if (this.pendingLookupPromise === null) { + if (this.isNextResolutionTimerRunning || this.backoff.isRunning()) { + if (this.isNextResolutionTimerRunning) { + trace('resolution update delayed by "min time between resolutions" rate limit'); + } + else { + trace('resolution update delayed by backoff timer until ' + + this.backoff.getEndTime().toISOString()); + } + this.continueResolving = true; + } + else { + this.startResolutionWithBackoff(); + } + } + } + /** + * Reset the resolver to the same state it had when it was created. In-flight + * DNS requests cannot be cancelled, but they are discarded and their results + * will be ignored. + */ + destroy() { + this.continueResolving = false; + this.backoff.reset(); + this.backoff.stop(); + this.stopNextResolutionTimer(); + this.pendingLookupPromise = null; + this.pendingTxtPromise = null; + this.latestLookupResult = null; + this.latestServiceConfigResult = null; + this.returnedIpResult = false; + } + /** + * Get the default authority for the given target. For IP targets, that is + * the IP address. For DNS targets, it is the hostname. + * @param target + */ + static getDefaultAuthority(target) { + return target.path; + } +} +/** + * Set up the DNS resolver class by registering it as the handler for the + * "dns:" prefix and as the default resolver. + */ +function setup() { + (0, resolver_1.registerResolver)('dns', DnsResolver); + (0, resolver_1.registerDefaultScheme)('dns'); +} +//# sourceMappingURL=resolver-dns.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolver-dns.js.map b/node_modules/@grpc/grpc-js/build/src/resolver-dns.js.map new file mode 100644 index 0000000..c7a950f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver-dns.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolver-dns.js","sourceRoot":"","sources":["../../src/resolver-dns.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AA0aH,sBAGC;AA3aD,yCAKoB;AACpB,6BAAsC;AACtC,qDAAgF;AAChF,2CAAqC;AACrC,qDAAgG;AAChG,yCAAsC;AACtC,qCAAqC;AACrC,2CAA2C;AAE3C,6CAAmE;AACnE,6BAAqC;AAErC,uDAAmE;AACnE,+CAAmE;AAEnE,MAAM,WAAW,GAAG,cAAc,CAAC;AAEnC,SAAS,KAAK,CAAC,IAAY;IACzB,OAAO,CAAC,KAAK,CAAC,wBAAY,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;AACvD,CAAC;AAED;;GAEG;AACU,QAAA,YAAY,GAAG,GAAG,CAAC;AAEhC,MAAM,uCAAuC,GAAG,KAAM,CAAC;AAEvD;;GAEG;AACH,MAAM,WAAW;IAwBf,YACU,MAAe,EACf,QAA0B,EAClC,cAA8B;;QAFtB,WAAM,GAAN,MAAM,CAAS;QACf,aAAQ,GAAR,QAAQ,CAAkB;QAhB5B,yBAAoB,GAA2C,IAAI,CAAC;QACpE,sBAAiB,GAA+B,IAA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B,GAAG,IAAI,CAAC;QACtC,IAAI,CAAC,gBAAgB,GAAG,KAAK,CAAC;IAChC,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,mBAAmB,CAAC,MAAe;QACxC,OAAO,MAAM,CAAC,IAAI,CAAC;IACrB,CAAC;CACF;AAED;;;GAGG;AACH,SAAgB,KAAK;IACnB,IAAA,2BAAgB,EAAC,KAAK,EAAE,WAAW,CAAC,CAAC;IACrC,IAAA,gCAAqB,EAAC,KAAK,CAAC,CAAC;AAC/B,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolver-ip.d.ts b/node_modules/@grpc/grpc-js/build/src/resolver-ip.d.ts new file mode 100644 index 0000000..2bec678 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver-ip.d.ts @@ -0,0 +1 @@ +export declare function setup(): void; diff --git a/node_modules/@grpc/grpc-js/build/src/resolver-ip.js b/node_modules/@grpc/grpc-js/build/src/resolver-ip.js new file mode 100644 index 0000000..411d64c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver-ip.js @@ -0,0 +1,106 @@ +"use strict"; +/* + * Copyright 2021 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setup = setup; +const net_1 = require("net"); +const call_interface_1 = require("./call-interface"); +const constants_1 = require("./constants"); +const metadata_1 = require("./metadata"); +const resolver_1 = require("./resolver"); +const subchannel_address_1 = require("./subchannel-address"); +const uri_parser_1 = require("./uri-parser"); +const logging = require("./logging"); +const TRACER_NAME = 'ip_resolver'; +function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); +} +const IPV4_SCHEME = 'ipv4'; +const IPV6_SCHEME = 'ipv6'; +/** + * The default TCP port to connect to if not explicitly specified in the target. + */ +const DEFAULT_PORT = 443; +class IpResolver { + constructor(target, listener, channelOptions) { + var _a; + this.listener = listener; + this.endpoints = []; + this.error = null; + this.hasReturnedResult = false; + trace('Resolver constructed for target ' + (0, uri_parser_1.uriToString)(target)); + const addresses = []; + if (!(target.scheme === IPV4_SCHEME || target.scheme === IPV6_SCHEME)) { + this.error = { + code: constants_1.Status.UNAVAILABLE, + details: `Unrecognized scheme ${target.scheme} in IP resolver`, + metadata: new metadata_1.Metadata(), + }; + return; + } + const pathList = target.path.split(','); + for (const path of pathList) { + const hostPort = (0, uri_parser_1.splitHostPort)(path); + if (hostPort === null) { + this.error = { + code: constants_1.Status.UNAVAILABLE, + details: `Failed to parse ${target.scheme} address ${path}`, + metadata: new metadata_1.Metadata(), + }; + return; + } + if ((target.scheme === IPV4_SCHEME && !(0, net_1.isIPv4)(hostPort.host)) || + (target.scheme === IPV6_SCHEME && !(0, net_1.isIPv6)(hostPort.host))) { + this.error = { + code: constants_1.Status.UNAVAILABLE, + details: `Failed to parse ${target.scheme} address ${path}`, + metadata: new metadata_1.Metadata(), + }; + return; + } + addresses.push({ + host: hostPort.host, + port: (_a = hostPort.port) !== null && _a !== void 0 ? _a : DEFAULT_PORT, + }); + } + this.endpoints = addresses.map(address => ({ addresses: [address] })); + trace('Parsed ' + target.scheme + ' address list ' + addresses.map(subchannel_address_1.subchannelAddressToString)); + } + updateResolution() { + if (!this.hasReturnedResult) { + this.hasReturnedResult = true; + process.nextTick(() => { + if (this.error) { + this.listener((0, call_interface_1.statusOrFromError)(this.error), {}, null, ''); + } + else { + this.listener((0, call_interface_1.statusOrFromValue)(this.endpoints), {}, null, ''); + } + }); + } + } + destroy() { + this.hasReturnedResult = false; + } + static getDefaultAuthority(target) { + return target.path.split(',')[0]; + } +} +function setup() { + (0, resolver_1.registerResolver)(IPV4_SCHEME, IpResolver); + (0, resolver_1.registerResolver)(IPV6_SCHEME, IpResolver); +} +//# sourceMappingURL=resolver-ip.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolver-ip.js.map b/node_modules/@grpc/grpc-js/build/src/resolver-ip.js.map new file mode 100644 index 0000000..7bfdbf8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver-ip.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolver-ip.js","sourceRoot":"","sources":["../../src/resolver-ip.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AA0GH,sBAGC;AA3GD,6BAAqC;AACrC,qDAAsF;AAEtF,2CAAmD;AACnD,yCAAsC;AACtC,yCAA0E;AAC1E,6DAA8F;AAC9F,6CAAmE;AACnE,qCAAqC;AAErC,MAAM,WAAW,GAAG,aAAa,CAAC;AAElC,SAAS,KAAK,CAAC,IAAY;IACzB,OAAO,CAAC,KAAK,CAAC,wBAAY,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;AACvD,CAAC;AAED,MAAM,WAAW,GAAG,MAAM,CAAC;AAC3B,MAAM,WAAW,GAAG,MAAM,CAAC;AAE3B;;GAEG;AACH,MAAM,YAAY,GAAG,GAAG,CAAC;AAEzB,MAAM,UAAU;IAId,YACE,MAAe,EACP,QAA0B,EAClC,cAA8B;;QADtB,aAAQ,GAAR,QAAQ,CAAkB;QAL5B,cAAS,GAAe,EAAE,CAAC;QAC3B,UAAK,GAAwB,IAAI,CAAC;QAClC,sBAAiB,GAAG,KAAK,CAAC;QAMhC,KAAK,CAAC,kCAAkC,GAAG,IAAA,wBAAW,EAAC,MAAM,CAAC,CAAC,CAAC;QAChE,MAAM,SAAS,GAAwB,EAAE,CAAC;QAC1C,IAAI,CAAC,CAAC,MAAM,CAAC,MAAM,KAAK,WAAW,IAAI,MAAM,CAAC,MAAM,KAAK,WAAW,CAAC,EAAE,CAAC;YACtE,IAAI,CAAC,KAA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AG,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC;QACtE,KAAK,CAAC,SAAS,GAAG,MAAM,CAAC,MAAM,GAAG,gBAAgB,GAAG,SAAS,CAAC,GAAG,CAAC,8CAAyB,CAAC,CAAC,CAAC;IACjG,CAAC;IACD,gBAAgB;QACd,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,CAAC;YAC5B,IAAI,CAAC,iBAAiB,GAAG,IAAI,CAAC;YAC9B,OAAO,CAAC,QAAQ,CAAC,GAAG,EAAE;gBACpB,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;oBACf,IAAI,CAAC,QAAQ,CACX,IAAA,kCAAiB,EAAC,IAAI,CAAC,KAAK,CAAC,EAC7B,EAAE,EACF,IAAI,EACJ,EAAE,CACH,CAAC;gBACJ,CAAC;qBAAM,CAAC;oBACN,IAAI,CAAC,QAAQ,CACX,IAAA,kCAAiB,EAAC,IAAI,CAAC,SAAS,CAAC,EACjC,EAAE,EACF,IAAI,EACJ,EAAE,CACH,CAAC;gBACJ,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,OAAO;QACL,IAAI,CAAC,iBAAiB,GAAG,KAAK,CAAC;IACjC,CAAC;IAED,MAAM,CAAC,mBAAmB,CAAC,MAAe;QACxC,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IACnC,CAAC;CACF;AAED,SAAgB,KAAK;IACnB,IAAA,2BAAgB,EAAC,WAAW,EAAE,UAAU,CAAC,CAAC;IAC1C,IAAA,2BAAgB,EAAC,WAAW,EAAE,UAAU,CAAC,CAAC;AAC5C,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolver-uds.d.ts b/node_modules/@grpc/grpc-js/build/src/resolver-uds.d.ts new file mode 100644 index 0000000..2bec678 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver-uds.d.ts @@ -0,0 +1 @@ +export declare function setup(): void; diff --git a/node_modules/@grpc/grpc-js/build/src/resolver-uds.js b/node_modules/@grpc/grpc-js/build/src/resolver-uds.js new file mode 100644 index 0000000..79290d4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver-uds.js @@ -0,0 +1,51 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setup = setup; +const resolver_1 = require("./resolver"); +const call_interface_1 = require("./call-interface"); +class UdsResolver { + constructor(target, listener, channelOptions) { + this.listener = listener; + this.hasReturnedResult = false; + this.endpoints = []; + let path; + if (target.authority === '') { + path = '/' + target.path; + } + else { + path = target.path; + } + this.endpoints = [{ addresses: [{ path }] }]; + } + updateResolution() { + if (!this.hasReturnedResult) { + this.hasReturnedResult = true; + process.nextTick(this.listener, (0, call_interface_1.statusOrFromValue)(this.endpoints), {}, null, ''); + } + } + destroy() { + this.hasReturnedResult = false; + } + static getDefaultAuthority(target) { + return 'localhost'; + } +} +function setup() { + (0, resolver_1.registerResolver)('unix', UdsResolver); +} +//# sourceMappingURL=resolver-uds.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolver-uds.js.map b/node_modules/@grpc/grpc-js/build/src/resolver-uds.js.map new file mode 100644 index 0000000..fdecd59 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver-uds.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolver-uds.js","sourceRoot":"","sources":["../../src/resolver-uds.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AA8CH,sBAEC;AA9CD,yCAA0E;AAI1E,qDAAqD;AAErD,MAAM,WAAW;IAGf,YACE,MAAe,EACP,QAA0B,EAClC,cAA8B;QADtB,aAAQ,GAAR,QAAQ,CAAkB;QAJ5B,sBAAiB,GAAG,KAAK,CAAC;QAC1B,cAAS,GAAe,EAAE,CAAC;QAMjC,IAAI,IAAY,CAAC;QACjB,IAAI,MAAM,CAAC,SAAS,KAAK,EAAE,EAAE,CAAC;YAC5B,IAAI,GAAG,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC;QAC3B,CAAC;aAAM,CAAC;YACN,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC;QACrB,CAAC;QACD,IAAI,CAAC,SAAS,GAAG,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC;IAC/C,CAAC;IACD,gBAAgB;QACd,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,CAAC;YAC5B,IAAI,CAAC,iBAAiB,GAAG,IAAI,CAAC;YAC9B,OAAO,CAAC,QAAQ,CACd,IAAI,CAAC,QAAQ,EACb,IAAA,kCAAiB,EAAC,IAAI,CAAC,SAAS,CAAC,EACjC,EAAE,EACF,IAAI,EACJ,EAAE,CACH,CAAC;QACJ,CAAC;IACH,CAAC;IAED,OAAO;QACL,IAAI,CAAC,iBAAiB,GAAG,KAAK,CAAC;IACjC,CAAC;IAED,MAAM,CAAC,mBAAmB,CAAC,MAAe;QACxC,OAAO,WAAW,CAAC;IACrB,CAAC;CACF;AAED,SAAgB,KAAK;IACnB,IAAA,2BAAgB,EAAC,MAAM,EAAE,WAAW,CAAC,CAAC;AACxC,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolver.d.ts b/node_modules/@grpc/grpc-js/build/src/resolver.d.ts new file mode 100644 index 0000000..a3610a9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver.d.ts @@ -0,0 +1,102 @@ +import { MethodConfig, ServiceConfig } from './service-config'; +import { StatusOr } from './call-interface'; +import { Endpoint } from './subchannel-address'; +import { GrpcUri } from './uri-parser'; +import { ChannelOptions } from './channel-options'; +import { Metadata } from './metadata'; +import { Status } from './constants'; +import { Filter, FilterFactory } from './filter'; +export declare const CHANNEL_ARGS_CONFIG_SELECTOR_KEY = "grpc.internal.config_selector"; +export interface CallConfig { + methodConfig: MethodConfig; + onCommitted?: () => void; + pickInformation: { + [key: string]: string; + }; + status: Status; + dynamicFilterFactories: FilterFactory[]; +} +/** + * Selects a configuration for a method given the name and metadata. Defined in + * https://github.com/grpc/proposal/blob/master/A31-xds-timeout-support-and-config-selector.md#new-functionality-in-grpc + */ +export interface ConfigSelector { + invoke(methodName: string, metadata: Metadata, channelId: number): CallConfig; + unref(): void; +} +export interface ResolverListener { + /** + * Called whenever the resolver has new name resolution results or an error to + * report. + * @param endpointList The list of endpoints, or an error if resolution failed + * @param attributes Arbitrary key/value pairs to pass along to load balancing + * policies + * @param serviceConfig The service service config for the endpoint list, or an + * error if the retrieved service config is invalid, or null if there is no + * service config + * @param resolutionNote Provides additional context to RPC failure status + * messages generated by the load balancing policy. + * @returns Whether or not the load balancing policy accepted the result. + */ + (endpointList: StatusOr, attributes: { + [key: string]: unknown; + }, serviceConfig: StatusOr | null, resolutionNote: string): boolean; +} +/** + * A resolver class that handles one or more of the name syntax schemes defined + * in the [gRPC Name Resolution document](https://github.com/grpc/grpc/blob/master/doc/naming.md) + */ +export interface Resolver { + /** + * Indicates that the caller wants new name resolution data. Calling this + * function may eventually result in calling one of the `ResolverListener` + * functions, but that is not guaranteed. Those functions will never be + * called synchronously with the constructor or updateResolution. + */ + updateResolution(): void; + /** + * Discard all resources owned by the resolver. A later call to + * `updateResolution` should reinitialize those resources. No + * `ResolverListener` callbacks should be called after `destroy` is called + * until `updateResolution` is called again. + */ + destroy(): void; +} +export interface ResolverConstructor { + new (target: GrpcUri, listener: ResolverListener, channelOptions: ChannelOptions): Resolver; + /** + * Get the default authority for a target. This loosely corresponds to that + * target's hostname. Throws an error if this resolver class cannot parse the + * `target`. + * @param target + */ + getDefaultAuthority(target: GrpcUri): string; +} +/** + * Register a resolver class to handle target names prefixed with the `prefix` + * string. This prefix should correspond to a URI scheme name listed in the + * [gRPC Name Resolution document](https://github.com/grpc/grpc/blob/master/doc/naming.md) + * @param prefix + * @param resolverClass + */ +export declare function registerResolver(scheme: string, resolverClass: ResolverConstructor): void; +/** + * Register a default resolver to handle target names that do not start with + * any registered prefix. + * @param resolverClass + */ +export declare function registerDefaultScheme(scheme: string): void; +/** + * Create a name resolver for the specified target, if possible. Throws an + * error if no such name resolver can be created. + * @param target + * @param listener + */ +export declare function createResolver(target: GrpcUri, listener: ResolverListener, options: ChannelOptions): Resolver; +/** + * Get the default authority for the specified target, if possible. Throws an + * error if no registered name resolver can parse that target string. + * @param target + */ +export declare function getDefaultAuthority(target: GrpcUri): string; +export declare function mapUriDefaultScheme(target: GrpcUri): GrpcUri | null; diff --git a/node_modules/@grpc/grpc-js/build/src/resolver.js b/node_modules/@grpc/grpc-js/build/src/resolver.js new file mode 100644 index 0000000..6b1a7c9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver.js @@ -0,0 +1,89 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = void 0; +exports.registerResolver = registerResolver; +exports.registerDefaultScheme = registerDefaultScheme; +exports.createResolver = createResolver; +exports.getDefaultAuthority = getDefaultAuthority; +exports.mapUriDefaultScheme = mapUriDefaultScheme; +const uri_parser_1 = require("./uri-parser"); +exports.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = 'grpc.internal.config_selector'; +const registeredResolvers = {}; +let defaultScheme = null; +/** + * Register a resolver class to handle target names prefixed with the `prefix` + * string. This prefix should correspond to a URI scheme name listed in the + * [gRPC Name Resolution document](https://github.com/grpc/grpc/blob/master/doc/naming.md) + * @param prefix + * @param resolverClass + */ +function registerResolver(scheme, resolverClass) { + registeredResolvers[scheme] = resolverClass; +} +/** + * Register a default resolver to handle target names that do not start with + * any registered prefix. + * @param resolverClass + */ +function registerDefaultScheme(scheme) { + defaultScheme = scheme; +} +/** + * Create a name resolver for the specified target, if possible. Throws an + * error if no such name resolver can be created. + * @param target + * @param listener + */ +function createResolver(target, listener, options) { + if (target.scheme !== undefined && target.scheme in registeredResolvers) { + return new registeredResolvers[target.scheme](target, listener, options); + } + else { + throw new Error(`No resolver could be created for target ${(0, uri_parser_1.uriToString)(target)}`); + } +} +/** + * Get the default authority for the specified target, if possible. Throws an + * error if no registered name resolver can parse that target string. + * @param target + */ +function getDefaultAuthority(target) { + if (target.scheme !== undefined && target.scheme in registeredResolvers) { + return registeredResolvers[target.scheme].getDefaultAuthority(target); + } + else { + throw new Error(`Invalid target ${(0, uri_parser_1.uriToString)(target)}`); + } +} +function mapUriDefaultScheme(target) { + if (target.scheme === undefined || !(target.scheme in registeredResolvers)) { + if (defaultScheme !== null) { + return { + scheme: defaultScheme, + authority: undefined, + path: (0, uri_parser_1.uriToString)(target), + }; + } + else { + return null; + } + } + return target; +} +//# sourceMappingURL=resolver.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolver.js.map b/node_modules/@grpc/grpc-js/build/src/resolver.js.map new file mode 100644 index 0000000..7b6c268 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolver.js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AAC,CAAC;IAC3D,CAAC;AACH,CAAC;AAED,SAAgB,mBAAmB,CAAC,MAAe;IACjD,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS,IAAI,CAAC,CAAC,MAAM,CAAC,MAAM,IAAI,mBAAmB,CAAC,EAAE,CAAC;QAC3E,IAAI,aAAa,KAAK,IAAI,EAAE,CAAC;YAC3B,OAAO;gBACL,MAAM,EAAE,aAAa;gBACrB,SAAS,EAAE,SAAS;gBACpB,IAAI,EAAE,IAAA,wBAAW,EAAC,MAAM,CAAC;aAC1B,CAAC;QACJ,CAAC;aAAM,CAAC;YACN,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolving-call.d.ts b/node_modules/@grpc/grpc-js/build/src/resolving-call.d.ts new file mode 100644 index 0000000..c94288b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolving-call.d.ts @@ -0,0 +1,54 @@ +import { CallCredentials } from './call-credentials'; +import { Call, CallStreamOptions, InterceptingListener, MessageContext, StatusObject } from './call-interface'; +import { Status } from './constants'; +import { FilterStackFactory } from './filter-stack'; +import { InternalChannel } from './internal-channel'; +import { Metadata } from './metadata'; +import { AuthContext } from './auth-context'; +export declare class ResolvingCall implements Call { + private readonly channel; + private readonly method; + private readonly filterStackFactory; + private callNumber; + private child; + private readPending; + private pendingMessage; + private pendingHalfClose; + private ended; + private readFilterPending; + private writeFilterPending; + private pendingChildStatus; + private metadata; + private listener; + private deadline; + private host; + private statusWatchers; + private deadlineTimer; + private filterStack; + private deadlineStartTime; + private configReceivedTime; + private childStartTime; + /** + * Credentials configured for this specific call. Does not include + * call credentials associated with the channel credentials used to create + * the channel. + */ + private credentials; + constructor(channel: InternalChannel, method: string, options: CallStreamOptions, filterStackFactory: FilterStackFactory, callNumber: number); + private trace; + private runDeadlineTimer; + private outputStatus; + private sendMessageOnChild; + getConfig(): void; + reportResolverError(status: StatusObject): void; + cancelWithStatus(status: Status, details: string): void; + getPeer(): string; + start(metadata: Metadata, listener: InterceptingListener): void; + sendMessageWithContext(context: MessageContext, message: Buffer): void; + startRead(): void; + halfClose(): void; + setCredentials(credentials: CallCredentials): void; + addStatusWatcher(watcher: (status: StatusObject) => void): void; + getCallNumber(): number; + getAuthContext(): AuthContext | null; +} diff --git a/node_modules/@grpc/grpc-js/build/src/resolving-call.js b/node_modules/@grpc/grpc-js/build/src/resolving-call.js new file mode 100644 index 0000000..8a47166 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolving-call.js @@ -0,0 +1,319 @@ +"use strict"; +/* + * Copyright 2022 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ResolvingCall = void 0; +const call_credentials_1 = require("./call-credentials"); +const constants_1 = require("./constants"); +const deadline_1 = require("./deadline"); +const metadata_1 = require("./metadata"); +const logging = require("./logging"); +const control_plane_status_1 = require("./control-plane-status"); +const TRACER_NAME = 'resolving_call'; +class ResolvingCall { + constructor(channel, method, options, filterStackFactory, callNumber) { + this.channel = channel; + this.method = method; + this.filterStackFactory = filterStackFactory; + this.callNumber = callNumber; + this.child = null; + this.readPending = false; + this.pendingMessage = null; + this.pendingHalfClose = false; + this.ended = false; + this.readFilterPending = false; + this.writeFilterPending = false; + this.pendingChildStatus = null; + this.metadata = null; + this.listener = null; + this.statusWatchers = []; + this.deadlineTimer = setTimeout(() => { }, 0); + this.filterStack = null; + this.deadlineStartTime = null; + this.configReceivedTime = null; + this.childStartTime = null; + /** + * Credentials configured for this specific call. Does not include + * call credentials associated with the channel credentials used to create + * the channel. + */ + this.credentials = call_credentials_1.CallCredentials.createEmpty(); + this.deadline = options.deadline; + this.host = options.host; + if (options.parentCall) { + if (options.flags & constants_1.Propagate.CANCELLATION) { + options.parentCall.on('cancelled', () => { + this.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled by parent call'); + }); + } + if (options.flags & constants_1.Propagate.DEADLINE) { + this.trace('Propagating deadline from parent: ' + + options.parentCall.getDeadline()); + this.deadline = (0, deadline_1.minDeadline)(this.deadline, options.parentCall.getDeadline()); + } + } + this.trace('Created'); + this.runDeadlineTimer(); + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callNumber + '] ' + text); + } + runDeadlineTimer() { + clearTimeout(this.deadlineTimer); + this.deadlineStartTime = new Date(); + this.trace('Deadline: ' + (0, deadline_1.deadlineToString)(this.deadline)); + const timeout = (0, deadline_1.getRelativeTimeout)(this.deadline); + if (timeout !== Infinity) { + this.trace('Deadline will be reached in ' + timeout + 'ms'); + const handleDeadline = () => { + if (!this.deadlineStartTime) { + this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, 'Deadline exceeded'); + return; + } + const deadlineInfo = []; + const deadlineEndTime = new Date(); + deadlineInfo.push(`Deadline exceeded after ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, deadlineEndTime)}`); + if (this.configReceivedTime) { + if (this.configReceivedTime > this.deadlineStartTime) { + deadlineInfo.push(`name resolution: ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, this.configReceivedTime)}`); + } + if (this.childStartTime) { + if (this.childStartTime > this.configReceivedTime) { + deadlineInfo.push(`metadata filters: ${(0, deadline_1.formatDateDifference)(this.configReceivedTime, this.childStartTime)}`); + } + } + else { + deadlineInfo.push('waiting for metadata filters'); + } + } + else { + deadlineInfo.push('waiting for name resolution'); + } + if (this.child) { + deadlineInfo.push(...this.child.getDeadlineInfo()); + } + this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, deadlineInfo.join(',')); + }; + if (timeout <= 0) { + process.nextTick(handleDeadline); + } + else { + this.deadlineTimer = setTimeout(handleDeadline, timeout); + } + } + } + outputStatus(status) { + if (!this.ended) { + this.ended = true; + if (!this.filterStack) { + this.filterStack = this.filterStackFactory.createFilter(); + } + clearTimeout(this.deadlineTimer); + const filteredStatus = this.filterStack.receiveTrailers(status); + this.trace('ended with status: code=' + + filteredStatus.code + + ' details="' + + filteredStatus.details + + '"'); + this.statusWatchers.forEach(watcher => watcher(filteredStatus)); + process.nextTick(() => { + var _a; + (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus(filteredStatus); + }); + } + } + sendMessageOnChild(context, message) { + if (!this.child) { + throw new Error('sendMessageonChild called with child not populated'); + } + const child = this.child; + this.writeFilterPending = true; + this.filterStack.sendMessage(Promise.resolve({ message: message, flags: context.flags })).then(filteredMessage => { + this.writeFilterPending = false; + child.sendMessageWithContext(context, filteredMessage.message); + if (this.pendingHalfClose) { + child.halfClose(); + } + }, (status) => { + this.cancelWithStatus(status.code, status.details); + }); + } + getConfig() { + if (this.ended) { + return; + } + if (!this.metadata || !this.listener) { + throw new Error('getConfig called before start'); + } + const configResult = this.channel.getConfig(this.method, this.metadata); + if (configResult.type === 'NONE') { + this.channel.queueCallForConfig(this); + return; + } + else if (configResult.type === 'ERROR') { + if (this.metadata.getOptions().waitForReady) { + this.channel.queueCallForConfig(this); + } + else { + this.outputStatus(configResult.error); + } + return; + } + // configResult.type === 'SUCCESS' + this.configReceivedTime = new Date(); + const config = configResult.config; + if (config.status !== constants_1.Status.OK) { + const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(config.status, 'Failed to route call to method ' + this.method); + this.outputStatus({ + code: code, + details: details, + metadata: new metadata_1.Metadata(), + }); + return; + } + if (config.methodConfig.timeout) { + const configDeadline = new Date(); + configDeadline.setSeconds(configDeadline.getSeconds() + config.methodConfig.timeout.seconds); + configDeadline.setMilliseconds(configDeadline.getMilliseconds() + + config.methodConfig.timeout.nanos / 1000000); + this.deadline = (0, deadline_1.minDeadline)(this.deadline, configDeadline); + this.runDeadlineTimer(); + } + this.filterStackFactory.push(config.dynamicFilterFactories); + this.filterStack = this.filterStackFactory.createFilter(); + this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then(filteredMetadata => { + this.child = this.channel.createRetryingCall(config, this.method, this.host, this.credentials, this.deadline); + this.trace('Created child [' + this.child.getCallNumber() + ']'); + this.childStartTime = new Date(); + this.child.start(filteredMetadata, { + onReceiveMetadata: metadata => { + this.trace('Received metadata'); + this.listener.onReceiveMetadata(this.filterStack.receiveMetadata(metadata)); + }, + onReceiveMessage: message => { + this.trace('Received message'); + this.readFilterPending = true; + this.filterStack.receiveMessage(message).then(filteredMesssage => { + this.trace('Finished filtering received message'); + this.readFilterPending = false; + this.listener.onReceiveMessage(filteredMesssage); + if (this.pendingChildStatus) { + this.outputStatus(this.pendingChildStatus); + } + }, (status) => { + this.cancelWithStatus(status.code, status.details); + }); + }, + onReceiveStatus: status => { + this.trace('Received status'); + if (this.readFilterPending) { + this.pendingChildStatus = status; + } + else { + this.outputStatus(status); + } + }, + }); + if (this.readPending) { + this.child.startRead(); + } + if (this.pendingMessage) { + this.sendMessageOnChild(this.pendingMessage.context, this.pendingMessage.message); + } + else if (this.pendingHalfClose) { + this.child.halfClose(); + } + }, (status) => { + this.outputStatus(status); + }); + } + reportResolverError(status) { + var _a; + if ((_a = this.metadata) === null || _a === void 0 ? void 0 : _a.getOptions().waitForReady) { + this.channel.queueCallForConfig(this); + } + else { + this.outputStatus(status); + } + } + cancelWithStatus(status, details) { + var _a; + this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"'); + (_a = this.child) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(status, details); + this.outputStatus({ + code: status, + details: details, + metadata: new metadata_1.Metadata(), + }); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.child) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.channel.getTarget(); + } + start(metadata, listener) { + this.trace('start called'); + this.metadata = metadata.clone(); + this.listener = listener; + this.getConfig(); + } + sendMessageWithContext(context, message) { + this.trace('write() called with message of length ' + message.length); + if (this.child) { + this.sendMessageOnChild(context, message); + } + else { + this.pendingMessage = { context, message }; + } + } + startRead() { + this.trace('startRead called'); + if (this.child) { + this.child.startRead(); + } + else { + this.readPending = true; + } + } + halfClose() { + this.trace('halfClose called'); + if (this.child && !this.writeFilterPending) { + this.child.halfClose(); + } + else { + this.pendingHalfClose = true; + } + } + setCredentials(credentials) { + this.credentials = credentials; + } + addStatusWatcher(watcher) { + this.statusWatchers.push(watcher); + } + getCallNumber() { + return this.callNumber; + } + getAuthContext() { + if (this.child) { + return this.child.getAuthContext(); + } + else { + return null; + } + } +} +exports.ResolvingCall = ResolvingCall; +//# sourceMappingURL=resolving-call.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolving-call.js.map b/node_modules/@grpc/grpc-js/build/src/resolving-call.js.map new file mode 100644 index 0000000..62bda26 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolving-call.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolving-call.js","sourceRoot":"","sources":["../../src/resolving-call.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,yDAAqD;AASrD,2CAA8D;AAC9D,yCAMoB;AAGpB,yCAAsC;AACtC,qCAAqC;AACrC,iEAAwE;AAGxE,MAAM,WAAW,GAAG,gBAAgB,CAAC;AAErC,MAAa,aAAa;IA6BxB,YACmB,OAAwB,EACxB,MAAc,EAC/B,OAA0B,EACT,kBAAsC,EAC/C,UAAkB;QAJT,YAAO,GAAP,OAAO,CAAiB;QACxB,WAAM,GAAN,MAAM,CAAQ;QAEd,uBAAkB,GAAlB,kBAAkB,CAAoB;QAC/C,eAAU,GAAV,UAAU,CAAQ;QAjCpB,UAAK,GAAyC,IAAI,CAAC;QACnD,gBAAW,GAAG,KA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G,IAAI,CAAC;QAC/B,CAAC;IACH,CAAC;IACD,cAAc,CAAC,WAA4B;QACzC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;IAED,gBAAgB,CAAC,OAAuC;QACtD,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACpC,CAAC;IAED,aAAa;QACX,OAAO,IAAI,CAAC,UAAU,CAAC;IACzB,CAAC;IAED,cAAc;QACZ,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YACf,OAAO,IAAI,CAAC,KAAK,CAAC,cAAc,EAAE,CAAC;QACrC,CAAC;aAAM,CAAC;YACN,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;CACF;AA/UD,sCA+UC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.d.ts b/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.d.ts new file mode 100644 index 0000000..bd6e2e8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.d.ts @@ -0,0 +1,70 @@ +import { ChannelControlHelper, LoadBalancer, TypedLoadBalancingConfig } from './load-balancer'; +import { ServiceConfig } from './service-config'; +import { ConfigSelector } from './resolver'; +import { StatusObject, StatusOr } from './call-interface'; +import { Endpoint } from './subchannel-address'; +import { GrpcUri } from './uri-parser'; +import { ChannelOptions } from './channel-options'; +export interface ResolutionCallback { + (serviceConfig: ServiceConfig, configSelector: ConfigSelector): void; +} +export interface ResolutionFailureCallback { + (status: StatusObject): void; +} +export declare class ResolvingLoadBalancer implements LoadBalancer { + private readonly target; + private readonly channelControlHelper; + private readonly channelOptions; + private readonly onSuccessfulResolution; + private readonly onFailedResolution; + /** + * The resolver class constructed for the target address. + */ + private readonly innerResolver; + private readonly childLoadBalancer; + private latestChildState; + private latestChildPicker; + private latestChildErrorMessage; + /** + * This resolving load balancer's current connectivity state. + */ + private currentState; + private readonly defaultServiceConfig; + /** + * The service config object from the last successful resolution, if + * available. A value of null indicates that we have not yet received a valid + * service config from the resolver. + */ + private previousServiceConfig; + /** + * The backoff timer for handling name resolution failures. + */ + private readonly backoffTimeout; + /** + * Indicates whether we should attempt to resolve again after the backoff + * timer runs out. + */ + private continueResolving; + /** + * Wrapper class that behaves like a `LoadBalancer` and also handles name + * resolution internally. + * @param target The address of the backend to connect to. + * @param channelControlHelper `ChannelControlHelper` instance provided by + * this load balancer's owner. + * @param defaultServiceConfig The default service configuration to be used + * if none is provided by the name resolver. A `null` value indicates + * that the default behavior should be the default unconfigured behavior. + * In practice, that means using the "pick first" load balancer + * implmentation + */ + constructor(target: GrpcUri, channelControlHelper: ChannelControlHelper, channelOptions: ChannelOptions, onSuccessfulResolution: ResolutionCallback, onFailedResolution: ResolutionFailureCallback); + private handleResolverResult; + private updateResolution; + private updateState; + private handleResolutionFailure; + exitIdle(): void; + updateAddressList(endpointList: StatusOr, lbConfig: TypedLoadBalancingConfig | null): never; + resetBackoff(): void; + destroy(): void; + getTypeName(): string; +} diff --git a/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js b/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js new file mode 100644 index 0000000..ca61474 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js @@ -0,0 +1,304 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ResolvingLoadBalancer = void 0; +const load_balancer_1 = require("./load-balancer"); +const service_config_1 = require("./service-config"); +const connectivity_state_1 = require("./connectivity-state"); +const resolver_1 = require("./resolver"); +const picker_1 = require("./picker"); +const backoff_timeout_1 = require("./backoff-timeout"); +const constants_1 = require("./constants"); +const metadata_1 = require("./metadata"); +const logging = require("./logging"); +const constants_2 = require("./constants"); +const uri_parser_1 = require("./uri-parser"); +const load_balancer_child_handler_1 = require("./load-balancer-child-handler"); +const TRACER_NAME = 'resolving_load_balancer'; +function trace(text) { + logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text); +} +/** + * Name match levels in order from most to least specific. This is the order in + * which searches will be performed. + */ +const NAME_MATCH_LEVEL_ORDER = [ + 'SERVICE_AND_METHOD', + 'SERVICE', + 'EMPTY', +]; +function hasMatchingName(service, method, methodConfig, matchLevel) { + for (const name of methodConfig.name) { + switch (matchLevel) { + case 'EMPTY': + if (!name.service && !name.method) { + return true; + } + break; + case 'SERVICE': + if (name.service === service && !name.method) { + return true; + } + break; + case 'SERVICE_AND_METHOD': + if (name.service === service && name.method === method) { + return true; + } + } + } + return false; +} +function findMatchingConfig(service, method, methodConfigs, matchLevel) { + for (const config of methodConfigs) { + if (hasMatchingName(service, method, config, matchLevel)) { + return config; + } + } + return null; +} +function getDefaultConfigSelector(serviceConfig) { + return { + invoke(methodName, metadata) { + var _a, _b; + const splitName = methodName.split('/').filter(x => x.length > 0); + const service = (_a = splitName[0]) !== null && _a !== void 0 ? _a : ''; + const method = (_b = splitName[1]) !== null && _b !== void 0 ? _b : ''; + if (serviceConfig && serviceConfig.methodConfig) { + /* Check for the following in order, and return the first method + * config that matches: + * 1. A name that exactly matches the service and method + * 2. A name with no method set that matches the service + * 3. An empty name + */ + for (const matchLevel of NAME_MATCH_LEVEL_ORDER) { + const matchingConfig = findMatchingConfig(service, method, serviceConfig.methodConfig, matchLevel); + if (matchingConfig) { + return { + methodConfig: matchingConfig, + pickInformation: {}, + status: constants_1.Status.OK, + dynamicFilterFactories: [], + }; + } + } + } + return { + methodConfig: { name: [] }, + pickInformation: {}, + status: constants_1.Status.OK, + dynamicFilterFactories: [], + }; + }, + unref() { } + }; +} +class ResolvingLoadBalancer { + /** + * Wrapper class that behaves like a `LoadBalancer` and also handles name + * resolution internally. + * @param target The address of the backend to connect to. + * @param channelControlHelper `ChannelControlHelper` instance provided by + * this load balancer's owner. + * @param defaultServiceConfig The default service configuration to be used + * if none is provided by the name resolver. A `null` value indicates + * that the default behavior should be the default unconfigured behavior. + * In practice, that means using the "pick first" load balancer + * implmentation + */ + constructor(target, channelControlHelper, channelOptions, onSuccessfulResolution, onFailedResolution) { + this.target = target; + this.channelControlHelper = channelControlHelper; + this.channelOptions = channelOptions; + this.onSuccessfulResolution = onSuccessfulResolution; + this.onFailedResolution = onFailedResolution; + this.latestChildState = connectivity_state_1.ConnectivityState.IDLE; + this.latestChildPicker = new picker_1.QueuePicker(this); + this.latestChildErrorMessage = null; + /** + * This resolving load balancer's current connectivity state. + */ + this.currentState = connectivity_state_1.ConnectivityState.IDLE; + /** + * The service config object from the last successful resolution, if + * available. A value of null indicates that we have not yet received a valid + * service config from the resolver. + */ + this.previousServiceConfig = null; + /** + * Indicates whether we should attempt to resolve again after the backoff + * timer runs out. + */ + this.continueResolving = false; + if (channelOptions['grpc.service_config']) { + this.defaultServiceConfig = (0, service_config_1.validateServiceConfig)(JSON.parse(channelOptions['grpc.service_config'])); + } + else { + this.defaultServiceConfig = { + loadBalancingConfig: [], + methodConfig: [], + }; + } + this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); + this.childLoadBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler({ + createSubchannel: channelControlHelper.createSubchannel.bind(channelControlHelper), + requestReresolution: () => { + /* If the backoffTimeout is running, we're still backing off from + * making resolve requests, so we shouldn't make another one here. + * In that case, the backoff timer callback will call + * updateResolution */ + if (this.backoffTimeout.isRunning()) { + trace('requestReresolution delayed by backoff timer until ' + + this.backoffTimeout.getEndTime().toISOString()); + this.continueResolving = true; + } + else { + this.updateResolution(); + } + }, + updateState: (newState, picker, errorMessage) => { + this.latestChildState = newState; + this.latestChildPicker = picker; + this.latestChildErrorMessage = errorMessage; + this.updateState(newState, picker, errorMessage); + }, + addChannelzChild: channelControlHelper.addChannelzChild.bind(channelControlHelper), + removeChannelzChild: channelControlHelper.removeChannelzChild.bind(channelControlHelper), + }); + this.innerResolver = (0, resolver_1.createResolver)(target, this.handleResolverResult.bind(this), channelOptions); + const backoffOptions = { + initialDelay: channelOptions['grpc.initial_reconnect_backoff_ms'], + maxDelay: channelOptions['grpc.max_reconnect_backoff_ms'], + }; + this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => { + if (this.continueResolving) { + this.updateResolution(); + this.continueResolving = false; + } + else { + this.updateState(this.latestChildState, this.latestChildPicker, this.latestChildErrorMessage); + } + }, backoffOptions); + this.backoffTimeout.unref(); + } + handleResolverResult(endpointList, attributes, serviceConfig, resolutionNote) { + var _a, _b; + this.backoffTimeout.stop(); + this.backoffTimeout.reset(); + let resultAccepted = true; + let workingServiceConfig = null; + if (serviceConfig === null) { + workingServiceConfig = this.defaultServiceConfig; + } + else if (serviceConfig.ok) { + workingServiceConfig = serviceConfig.value; + } + else { + if (this.previousServiceConfig !== null) { + workingServiceConfig = this.previousServiceConfig; + } + else { + resultAccepted = false; + this.handleResolutionFailure(serviceConfig.error); + } + } + if (workingServiceConfig !== null) { + const workingConfigList = (_a = workingServiceConfig === null || workingServiceConfig === void 0 ? void 0 : workingServiceConfig.loadBalancingConfig) !== null && _a !== void 0 ? _a : []; + const loadBalancingConfig = (0, load_balancer_1.selectLbConfigFromList)(workingConfigList, true); + if (loadBalancingConfig === null) { + resultAccepted = false; + this.handleResolutionFailure({ + code: constants_1.Status.UNAVAILABLE, + details: 'All load balancer options in service config are not compatible', + metadata: new metadata_1.Metadata(), + }); + } + else { + resultAccepted = this.childLoadBalancer.updateAddressList(endpointList, loadBalancingConfig, Object.assign(Object.assign({}, this.channelOptions), attributes), resolutionNote); + } + } + if (resultAccepted) { + this.onSuccessfulResolution(workingServiceConfig, (_b = attributes[resolver_1.CHANNEL_ARGS_CONFIG_SELECTOR_KEY]) !== null && _b !== void 0 ? _b : getDefaultConfigSelector(workingServiceConfig)); + } + return resultAccepted; + } + updateResolution() { + this.innerResolver.updateResolution(); + if (this.currentState === connectivity_state_1.ConnectivityState.IDLE) { + /* this.latestChildPicker is initialized as new QueuePicker(this), which + * is an appropriate value here if the child LB policy is unset. + * Otherwise, we want to delegate to the child here, in case that + * triggers something. */ + this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, this.latestChildPicker, this.latestChildErrorMessage); + } + this.backoffTimeout.runOnce(); + } + updateState(connectivityState, picker, errorMessage) { + trace((0, uri_parser_1.uriToString)(this.target) + + ' ' + + connectivity_state_1.ConnectivityState[this.currentState] + + ' -> ' + + connectivity_state_1.ConnectivityState[connectivityState]); + // Ensure that this.exitIdle() is called by the picker + if (connectivityState === connectivity_state_1.ConnectivityState.IDLE) { + picker = new picker_1.QueuePicker(this, picker); + } + this.currentState = connectivityState; + this.channelControlHelper.updateState(connectivityState, picker, errorMessage); + } + handleResolutionFailure(error) { + if (this.latestChildState === connectivity_state_1.ConnectivityState.IDLE) { + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(error), error.details); + this.onFailedResolution(error); + } + } + exitIdle() { + if (this.currentState === connectivity_state_1.ConnectivityState.IDLE || + this.currentState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { + if (this.backoffTimeout.isRunning()) { + this.continueResolving = true; + } + else { + this.updateResolution(); + } + } + this.childLoadBalancer.exitIdle(); + } + updateAddressList(endpointList, lbConfig) { + throw new Error('updateAddressList not supported on ResolvingLoadBalancer'); + } + resetBackoff() { + this.backoffTimeout.reset(); + this.childLoadBalancer.resetBackoff(); + } + destroy() { + this.childLoadBalancer.destroy(); + this.innerResolver.destroy(); + this.backoffTimeout.reset(); + this.backoffTimeout.stop(); + this.latestChildState = connectivity_state_1.ConnectivityState.IDLE; + this.latestChildPicker = new picker_1.QueuePicker(this); + this.currentState = connectivity_state_1.ConnectivityState.IDLE; + this.previousServiceConfig = null; + this.continueResolving = false; + } + getTypeName() { + return 'resolving_load_balancer'; + } +} +exports.ResolvingLoadBalancer = ResolvingLoadBalancer; +//# sourceMappingURL=resolving-load-balancer.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js.map b/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js.map new file mode 100644 index 0000000..79b48eb --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolving-load-balancer.js","sourceRoot":"","sources":["../../src/resolving-load-balancer.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,mDAKyB;AACzB,qDAI0B;AAC1B,6DAAyD;AACzD,yCAAwG;AACxG,qCAAkE;AAClE,uDAAmE;AACnE,2CAAqC;AAErC,yCAAsC;AACtC,qCAAqC;AACrC,2CAA2C;AAE3C,6CAAoD;AACpD,+EAAyE;AAGzE,MAAM,WAAW,GAAG,yBAAyB,CAAC;AAE9C,SAAS,KAAK,CAAC,IAAY;IACzB,OAAO,CAAC,KAAK,CAAC,wBAAY,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;AACvD,CAAC;AAID;;;GAGG;AACH,MAAM,sBAAsB,GAAqB;IAC/C,oBAAoB;IACpB,SAAS;IACT,OAAO;CACR,CAAC;AAEF,SAAS,eAAe,CACtB,OAAe,EACf,MAAc,EACd,YAA0B,EAC1B,UAA0B;IAE1B,KAAK,MAAM,IAAI,IAAI,YAAY,CAAC,IAAI,EAAE,CAAC;QACrC,QAAQ,UAAU,EAAE,CAAC;YACnB,KAAK,OAAO;gBACV,IAAI,CAAC,IAAI,CAAC,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;oBAClC,OAAO,IAAI,CAAC;gBACd,CAAC;gBACD,MAAM;YACR,KAAK,SAAS;gBACZ,IAAI,IAAI,C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IAED,iBAAiB,CACf,YAAkC,EAClC,QAAyC;QAEzC,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;IAC9E,CAAC;IAED,YAAY;QACV,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,CAAC;QAC5B,IAAI,CAAC,iBAAiB,CAAC,YAAY,EAAE,CAAC;IACxC,CAAC;IAED,OAAO;QACL,IAAI,CAAC,iBAAiB,CAAC,OAAO,EAAE,CAAC;QACjC,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,CAAC;QAC7B,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,CAAC;QAC5B,IAAI,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC;QAC3B,IAAI,CAAC,gBAAgB,GAAG,sCAAiB,CAAC,IAAI,CAAC;QAC/C,IAAI,CAAC,iBAAiB,GAAG,IAAI,oBAAW,CAAC,IAAI,CAAC,CAAC;QAC/C,IAAI,CAAC,YAAY,GAAG,sCAAiB,CAAC,IAAI,CAAC;QAC3C,IAAI,CAAC,qBAAqB,GAAG,IAAI,CAAC;QAClC,IAAI,CAAC,iBAAiB,GAAG,KAAK,CAAC;IACjC,CAAC;IAED,WAAW;QACT,OAAO,yBAAyB,CAAC;IACnC,CAAC;CACF;AA3PD,sDA2PC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/retrying-call.d.ts b/node_modules/@grpc/grpc-js/build/src/retrying-call.d.ts new file mode 100644 index 0000000..560e876 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/retrying-call.d.ts @@ -0,0 +1,100 @@ +import { CallCredentials } from './call-credentials'; +import { Status } from './constants'; +import { Deadline } from './deadline'; +import { Metadata } from './metadata'; +import { CallConfig } from './resolver'; +import { Call, DeadlineInfoProvider, InterceptingListener, MessageContext } from './call-interface'; +import { InternalChannel } from './internal-channel'; +import { AuthContext } from './auth-context'; +export declare class RetryThrottler { + private readonly maxTokens; + private readonly tokenRatio; + private tokens; + constructor(maxTokens: number, tokenRatio: number, previousRetryThrottler?: RetryThrottler); + addCallSucceeded(): void; + addCallFailed(): void; + canRetryCall(): boolean; +} +export declare class MessageBufferTracker { + private totalLimit; + private limitPerCall; + private totalAllocated; + private allocatedPerCall; + constructor(totalLimit: number, limitPerCall: number); + allocate(size: number, callId: number): boolean; + free(size: number, callId: number): void; + freeAll(callId: number): void; +} +export declare class RetryingCall implements Call, DeadlineInfoProvider { + private readonly channel; + private readonly callConfig; + private readonly methodName; + private readonly host; + private readonly credentials; + private readonly deadline; + private readonly callNumber; + private readonly bufferTracker; + private readonly retryThrottler?; + private state; + private listener; + private initialMetadata; + private underlyingCalls; + private writeBuffer; + /** + * The offset of message indices in the writeBuffer. For example, if + * writeBufferOffset is 10, message 10 is in writeBuffer[0] and message 15 + * is in writeBuffer[5]. + */ + private writeBufferOffset; + /** + * Tracks whether a read has been started, so that we know whether to start + * reads on new child calls. This only matters for the first read, because + * once a message comes in the child call becomes committed and there will + * be no new child calls. + */ + private readStarted; + private transparentRetryUsed; + /** + * Number of attempts so far + */ + private attempts; + private hedgingTimer; + private committedCallIndex; + private initialRetryBackoffSec; + private nextRetryBackoffSec; + private startTime; + private maxAttempts; + constructor(channel: InternalChannel, callConfig: CallConfig, methodName: string, host: string, credentials: CallCredentials, deadline: Deadline, callNumber: number, bufferTracker: MessageBufferTracker, retryThrottler?: RetryThrottler | undefined); + getDeadlineInfo(): string[]; + getCallNumber(): number; + private trace; + private reportStatus; + cancelWithStatus(status: Status, details: string): void; + getPeer(): string; + private getBufferEntry; + private getNextBufferIndex; + private clearSentMessages; + private commitCall; + private commitCallWithMostMessages; + private isStatusCodeInList; + private getNextRetryJitter; + private getNextRetryBackoffMs; + private maybeRetryCall; + private countActiveCalls; + private handleProcessedStatus; + private getPushback; + private handleChildStatus; + private maybeStartHedgingAttempt; + private maybeStartHedgingTimer; + private startNewAttempt; + start(metadata: Metadata, listener: InterceptingListener): void; + private handleChildWriteCompleted; + private sendNextChildMessage; + sendMessageWithContext(context: MessageContext, message: Buffer): void; + startRead(): void; + halfClose(): void; + setCredentials(newCredentials: CallCredentials): void; + getMethod(): string; + getHost(): string; + getAuthContext(): AuthContext | null; +} diff --git a/node_modules/@grpc/grpc-js/build/src/retrying-call.js b/node_modules/@grpc/grpc-js/build/src/retrying-call.js new file mode 100644 index 0000000..890df24 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/retrying-call.js @@ -0,0 +1,700 @@ +"use strict"; +/* + * Copyright 2022 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RetryingCall = exports.MessageBufferTracker = exports.RetryThrottler = void 0; +const constants_1 = require("./constants"); +const deadline_1 = require("./deadline"); +const metadata_1 = require("./metadata"); +const logging = require("./logging"); +const TRACER_NAME = 'retrying_call'; +class RetryThrottler { + constructor(maxTokens, tokenRatio, previousRetryThrottler) { + this.maxTokens = maxTokens; + this.tokenRatio = tokenRatio; + if (previousRetryThrottler) { + /* When carrying over tokens from a previous config, rescale them to the + * new max value */ + this.tokens = + previousRetryThrottler.tokens * + (maxTokens / previousRetryThrottler.maxTokens); + } + else { + this.tokens = maxTokens; + } + } + addCallSucceeded() { + this.tokens = Math.min(this.tokens + this.tokenRatio, this.maxTokens); + } + addCallFailed() { + this.tokens = Math.max(this.tokens - 1, 0); + } + canRetryCall() { + return this.tokens > (this.maxTokens / 2); + } +} +exports.RetryThrottler = RetryThrottler; +class MessageBufferTracker { + constructor(totalLimit, limitPerCall) { + this.totalLimit = totalLimit; + this.limitPerCall = limitPerCall; + this.totalAllocated = 0; + this.allocatedPerCall = new Map(); + } + allocate(size, callId) { + var _a; + const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; + if (this.limitPerCall - currentPerCall < size || + this.totalLimit - this.totalAllocated < size) { + return false; + } + this.allocatedPerCall.set(callId, currentPerCall + size); + this.totalAllocated += size; + return true; + } + free(size, callId) { + var _a; + if (this.totalAllocated < size) { + throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > total allocated ${this.totalAllocated}`); + } + this.totalAllocated -= size; + const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; + if (currentPerCall < size) { + throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > allocated for call ${currentPerCall}`); + } + this.allocatedPerCall.set(callId, currentPerCall - size); + } + freeAll(callId) { + var _a; + const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; + if (this.totalAllocated < currentPerCall) { + throw new Error(`Invalid buffer allocation state: call ${callId} allocated ${currentPerCall} > total allocated ${this.totalAllocated}`); + } + this.totalAllocated -= currentPerCall; + this.allocatedPerCall.delete(callId); + } +} +exports.MessageBufferTracker = MessageBufferTracker; +const PREVIONS_RPC_ATTEMPTS_METADATA_KEY = 'grpc-previous-rpc-attempts'; +const DEFAULT_MAX_ATTEMPTS_LIMIT = 5; +class RetryingCall { + constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber, bufferTracker, retryThrottler) { + var _a; + this.channel = channel; + this.callConfig = callConfig; + this.methodName = methodName; + this.host = host; + this.credentials = credentials; + this.deadline = deadline; + this.callNumber = callNumber; + this.bufferTracker = bufferTracker; + this.retryThrottler = retryThrottler; + this.listener = null; + this.initialMetadata = null; + this.underlyingCalls = []; + this.writeBuffer = []; + /** + * The offset of message indices in the writeBuffer. For example, if + * writeBufferOffset is 10, message 10 is in writeBuffer[0] and message 15 + * is in writeBuffer[5]. + */ + this.writeBufferOffset = 0; + /** + * Tracks whether a read has been started, so that we know whether to start + * reads on new child calls. This only matters for the first read, because + * once a message comes in the child call becomes committed and there will + * be no new child calls. + */ + this.readStarted = false; + this.transparentRetryUsed = false; + /** + * Number of attempts so far + */ + this.attempts = 0; + this.hedgingTimer = null; + this.committedCallIndex = null; + this.initialRetryBackoffSec = 0; + this.nextRetryBackoffSec = 0; + const maxAttemptsLimit = (_a = channel.getOptions()['grpc-node.retry_max_attempts_limit']) !== null && _a !== void 0 ? _a : DEFAULT_MAX_ATTEMPTS_LIMIT; + if (channel.getOptions()['grpc.enable_retries'] === 0) { + this.state = 'NO_RETRY'; + this.maxAttempts = 1; + } + else if (callConfig.methodConfig.retryPolicy) { + this.state = 'RETRY'; + const retryPolicy = callConfig.methodConfig.retryPolicy; + this.nextRetryBackoffSec = this.initialRetryBackoffSec = Number(retryPolicy.initialBackoff.substring(0, retryPolicy.initialBackoff.length - 1)); + this.maxAttempts = Math.min(retryPolicy.maxAttempts, maxAttemptsLimit); + } + else if (callConfig.methodConfig.hedgingPolicy) { + this.state = 'HEDGING'; + this.maxAttempts = Math.min(callConfig.methodConfig.hedgingPolicy.maxAttempts, maxAttemptsLimit); + } + else { + this.state = 'TRANSPARENT_ONLY'; + this.maxAttempts = 1; + } + this.startTime = new Date(); + } + getDeadlineInfo() { + if (this.underlyingCalls.length === 0) { + return []; + } + const deadlineInfo = []; + const latestCall = this.underlyingCalls[this.underlyingCalls.length - 1]; + if (this.underlyingCalls.length > 1) { + deadlineInfo.push(`previous attempts: ${this.underlyingCalls.length - 1}`); + } + if (latestCall.startTime > this.startTime) { + deadlineInfo.push(`time to current attempt start: ${(0, deadline_1.formatDateDifference)(this.startTime, latestCall.startTime)}`); + } + deadlineInfo.push(...latestCall.call.getDeadlineInfo()); + return deadlineInfo; + } + getCallNumber() { + return this.callNumber; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callNumber + '] ' + text); + } + reportStatus(statusObject) { + this.trace('ended with status: code=' + + statusObject.code + + ' details="' + + statusObject.details + + '" start time=' + + this.startTime.toISOString()); + this.bufferTracker.freeAll(this.callNumber); + this.writeBufferOffset = this.writeBufferOffset + this.writeBuffer.length; + this.writeBuffer = []; + process.nextTick(() => { + var _a; + // Explicitly construct status object to remove progress field + (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus({ + code: statusObject.code, + details: statusObject.details, + metadata: statusObject.metadata, + }); + }); + } + cancelWithStatus(status, details) { + this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"'); + this.reportStatus({ code: status, details, metadata: new metadata_1.Metadata() }); + for (const { call } of this.underlyingCalls) { + call.cancelWithStatus(status, details); + } + } + getPeer() { + if (this.committedCallIndex !== null) { + return this.underlyingCalls[this.committedCallIndex].call.getPeer(); + } + else { + return 'unknown'; + } + } + getBufferEntry(messageIndex) { + var _a; + return ((_a = this.writeBuffer[messageIndex - this.writeBufferOffset]) !== null && _a !== void 0 ? _a : { + entryType: 'FREED', + allocated: false, + }); + } + getNextBufferIndex() { + return this.writeBufferOffset + this.writeBuffer.length; + } + clearSentMessages() { + if (this.state !== 'COMMITTED') { + return; + } + let earliestNeededMessageIndex; + if (this.underlyingCalls[this.committedCallIndex].state === 'COMPLETED') { + /* If the committed call is completed, clear all messages, even if some + * have not been sent. */ + earliestNeededMessageIndex = this.getNextBufferIndex(); + } + else { + earliestNeededMessageIndex = + this.underlyingCalls[this.committedCallIndex].nextMessageToSend; + } + for (let messageIndex = this.writeBufferOffset; messageIndex < earliestNeededMessageIndex; messageIndex++) { + const bufferEntry = this.getBufferEntry(messageIndex); + if (bufferEntry.allocated) { + this.bufferTracker.free(bufferEntry.message.message.length, this.callNumber); + } + } + this.writeBuffer = this.writeBuffer.slice(earliestNeededMessageIndex - this.writeBufferOffset); + this.writeBufferOffset = earliestNeededMessageIndex; + } + commitCall(index) { + var _a, _b; + if (this.state === 'COMMITTED') { + return; + } + this.trace('Committing call [' + + this.underlyingCalls[index].call.getCallNumber() + + '] at index ' + + index); + this.state = 'COMMITTED'; + (_b = (_a = this.callConfig).onCommitted) === null || _b === void 0 ? void 0 : _b.call(_a); + this.committedCallIndex = index; + for (let i = 0; i < this.underlyingCalls.length; i++) { + if (i === index) { + continue; + } + if (this.underlyingCalls[i].state === 'COMPLETED') { + continue; + } + this.underlyingCalls[i].state = 'COMPLETED'; + this.underlyingCalls[i].call.cancelWithStatus(constants_1.Status.CANCELLED, 'Discarded in favor of other hedged attempt'); + } + this.clearSentMessages(); + } + commitCallWithMostMessages() { + if (this.state === 'COMMITTED') { + return; + } + let mostMessages = -1; + let callWithMostMessages = -1; + for (const [index, childCall] of this.underlyingCalls.entries()) { + if (childCall.state === 'ACTIVE' && + childCall.nextMessageToSend > mostMessages) { + mostMessages = childCall.nextMessageToSend; + callWithMostMessages = index; + } + } + if (callWithMostMessages === -1) { + /* There are no active calls, disable retries to force the next call that + * is started to be committed. */ + this.state = 'TRANSPARENT_ONLY'; + } + else { + this.commitCall(callWithMostMessages); + } + } + isStatusCodeInList(list, code) { + return list.some(value => { + var _a; + return value === code || + value.toString().toLowerCase() === ((_a = constants_1.Status[code]) === null || _a === void 0 ? void 0 : _a.toLowerCase()); + }); + } + getNextRetryJitter() { + /* Jitter of +-20% is applied: https://github.com/grpc/proposal/blob/master/A6-client-retries.md#exponential-backoff */ + return Math.random() * (1.2 - 0.8) + 0.8; + } + getNextRetryBackoffMs() { + var _a; + const retryPolicy = (_a = this.callConfig) === null || _a === void 0 ? void 0 : _a.methodConfig.retryPolicy; + if (!retryPolicy) { + return 0; + } + const jitter = this.getNextRetryJitter(); + const nextBackoffMs = jitter * this.nextRetryBackoffSec * 1000; + const maxBackoffSec = Number(retryPolicy.maxBackoff.substring(0, retryPolicy.maxBackoff.length - 1)); + this.nextRetryBackoffSec = Math.min(this.nextRetryBackoffSec * retryPolicy.backoffMultiplier, maxBackoffSec); + return nextBackoffMs; + } + maybeRetryCall(pushback, callback) { + if (this.state !== 'RETRY') { + callback(false); + return; + } + if (this.attempts >= this.maxAttempts) { + callback(false); + return; + } + let retryDelayMs; + if (pushback === null) { + retryDelayMs = this.getNextRetryBackoffMs(); + } + else if (pushback < 0) { + this.state = 'TRANSPARENT_ONLY'; + callback(false); + return; + } + else { + retryDelayMs = pushback; + this.nextRetryBackoffSec = this.initialRetryBackoffSec; + } + setTimeout(() => { + var _a, _b; + if (this.state !== 'RETRY') { + callback(false); + return; + } + if ((_b = (_a = this.retryThrottler) === null || _a === void 0 ? void 0 : _a.canRetryCall()) !== null && _b !== void 0 ? _b : true) { + callback(true); + this.attempts += 1; + this.startNewAttempt(); + } + else { + this.trace('Retry attempt denied by throttling policy'); + callback(false); + } + }, retryDelayMs); + } + countActiveCalls() { + let count = 0; + for (const call of this.underlyingCalls) { + if ((call === null || call === void 0 ? void 0 : call.state) === 'ACTIVE') { + count += 1; + } + } + return count; + } + handleProcessedStatus(status, callIndex, pushback) { + var _a, _b, _c; + switch (this.state) { + case 'COMMITTED': + case 'NO_RETRY': + case 'TRANSPARENT_ONLY': + this.commitCall(callIndex); + this.reportStatus(status); + break; + case 'HEDGING': + if (this.isStatusCodeInList((_a = this.callConfig.methodConfig.hedgingPolicy.nonFatalStatusCodes) !== null && _a !== void 0 ? _a : [], status.code)) { + (_b = this.retryThrottler) === null || _b === void 0 ? void 0 : _b.addCallFailed(); + let delayMs; + if (pushback === null) { + delayMs = 0; + } + else if (pushback < 0) { + this.state = 'TRANSPARENT_ONLY'; + this.commitCall(callIndex); + this.reportStatus(status); + return; + } + else { + delayMs = pushback; + } + setTimeout(() => { + this.maybeStartHedgingAttempt(); + // If after trying to start a call there are no active calls, this was the last one + if (this.countActiveCalls() === 0) { + this.commitCall(callIndex); + this.reportStatus(status); + } + }, delayMs); + } + else { + this.commitCall(callIndex); + this.reportStatus(status); + } + break; + case 'RETRY': + if (this.isStatusCodeInList(this.callConfig.methodConfig.retryPolicy.retryableStatusCodes, status.code)) { + (_c = this.retryThrottler) === null || _c === void 0 ? void 0 : _c.addCallFailed(); + this.maybeRetryCall(pushback, retried => { + if (!retried) { + this.commitCall(callIndex); + this.reportStatus(status); + } + }); + } + else { + this.commitCall(callIndex); + this.reportStatus(status); + } + break; + } + } + getPushback(metadata) { + const mdValue = metadata.get('grpc-retry-pushback-ms'); + if (mdValue.length === 0) { + return null; + } + try { + return parseInt(mdValue[0]); + } + catch (e) { + return -1; + } + } + handleChildStatus(status, callIndex) { + var _a; + if (this.underlyingCalls[callIndex].state === 'COMPLETED') { + return; + } + this.trace('state=' + + this.state + + ' handling status with progress ' + + status.progress + + ' from child [' + + this.underlyingCalls[callIndex].call.getCallNumber() + + '] in state ' + + this.underlyingCalls[callIndex].state); + this.underlyingCalls[callIndex].state = 'COMPLETED'; + if (status.code === constants_1.Status.OK) { + (_a = this.retryThrottler) === null || _a === void 0 ? void 0 : _a.addCallSucceeded(); + this.commitCall(callIndex); + this.reportStatus(status); + return; + } + if (this.state === 'NO_RETRY') { + this.commitCall(callIndex); + this.reportStatus(status); + return; + } + if (this.state === 'COMMITTED') { + this.reportStatus(status); + return; + } + const pushback = this.getPushback(status.metadata); + switch (status.progress) { + case 'NOT_STARTED': + // RPC never leaves the client, always safe to retry + this.startNewAttempt(); + break; + case 'REFUSED': + // RPC reaches the server library, but not the server application logic + if (this.transparentRetryUsed) { + this.handleProcessedStatus(status, callIndex, pushback); + } + else { + this.transparentRetryUsed = true; + this.startNewAttempt(); + } + break; + case 'DROP': + this.commitCall(callIndex); + this.reportStatus(status); + break; + case 'PROCESSED': + this.handleProcessedStatus(status, callIndex, pushback); + break; + } + } + maybeStartHedgingAttempt() { + if (this.state !== 'HEDGING') { + return; + } + if (!this.callConfig.methodConfig.hedgingPolicy) { + return; + } + if (this.attempts >= this.maxAttempts) { + return; + } + this.attempts += 1; + this.startNewAttempt(); + this.maybeStartHedgingTimer(); + } + maybeStartHedgingTimer() { + var _a, _b, _c; + if (this.hedgingTimer) { + clearTimeout(this.hedgingTimer); + } + if (this.state !== 'HEDGING') { + return; + } + if (!this.callConfig.methodConfig.hedgingPolicy) { + return; + } + const hedgingPolicy = this.callConfig.methodConfig.hedgingPolicy; + if (this.attempts >= this.maxAttempts) { + return; + } + const hedgingDelayString = (_a = hedgingPolicy.hedgingDelay) !== null && _a !== void 0 ? _a : '0s'; + const hedgingDelaySec = Number(hedgingDelayString.substring(0, hedgingDelayString.length - 1)); + this.hedgingTimer = setTimeout(() => { + this.maybeStartHedgingAttempt(); + }, hedgingDelaySec * 1000); + (_c = (_b = this.hedgingTimer).unref) === null || _c === void 0 ? void 0 : _c.call(_b); + } + startNewAttempt() { + const child = this.channel.createLoadBalancingCall(this.callConfig, this.methodName, this.host, this.credentials, this.deadline); + this.trace('Created child call [' + + child.getCallNumber() + + '] for attempt ' + + this.attempts); + const index = this.underlyingCalls.length; + this.underlyingCalls.push({ + state: 'ACTIVE', + call: child, + nextMessageToSend: 0, + startTime: new Date(), + }); + const previousAttempts = this.attempts - 1; + const initialMetadata = this.initialMetadata.clone(); + if (previousAttempts > 0) { + initialMetadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); + } + let receivedMetadata = false; + child.start(initialMetadata, { + onReceiveMetadata: metadata => { + this.trace('Received metadata from child [' + child.getCallNumber() + ']'); + this.commitCall(index); + receivedMetadata = true; + if (previousAttempts > 0) { + metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); + } + if (this.underlyingCalls[index].state === 'ACTIVE') { + this.listener.onReceiveMetadata(metadata); + } + }, + onReceiveMessage: message => { + this.trace('Received message from child [' + child.getCallNumber() + ']'); + this.commitCall(index); + if (this.underlyingCalls[index].state === 'ACTIVE') { + this.listener.onReceiveMessage(message); + } + }, + onReceiveStatus: status => { + this.trace('Received status from child [' + child.getCallNumber() + ']'); + if (!receivedMetadata && previousAttempts > 0) { + status.metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); + } + this.handleChildStatus(status, index); + }, + }); + this.sendNextChildMessage(index); + if (this.readStarted) { + child.startRead(); + } + } + start(metadata, listener) { + this.trace('start called'); + this.listener = listener; + this.initialMetadata = metadata; + this.attempts += 1; + this.startNewAttempt(); + this.maybeStartHedgingTimer(); + } + handleChildWriteCompleted(childIndex) { + var _a, _b; + const childCall = this.underlyingCalls[childIndex]; + const messageIndex = childCall.nextMessageToSend; + (_b = (_a = this.getBufferEntry(messageIndex)).callback) === null || _b === void 0 ? void 0 : _b.call(_a); + this.clearSentMessages(); + childCall.nextMessageToSend += 1; + this.sendNextChildMessage(childIndex); + } + sendNextChildMessage(childIndex) { + const childCall = this.underlyingCalls[childIndex]; + if (childCall.state === 'COMPLETED') { + return; + } + if (this.getBufferEntry(childCall.nextMessageToSend)) { + const bufferEntry = this.getBufferEntry(childCall.nextMessageToSend); + switch (bufferEntry.entryType) { + case 'MESSAGE': + childCall.call.sendMessageWithContext({ + callback: error => { + // Ignore error + this.handleChildWriteCompleted(childIndex); + }, + }, bufferEntry.message.message); + break; + case 'HALF_CLOSE': + childCall.nextMessageToSend += 1; + childCall.call.halfClose(); + break; + case 'FREED': + // Should not be possible + break; + } + } + } + sendMessageWithContext(context, message) { + var _a; + this.trace('write() called with message of length ' + message.length); + const writeObj = { + message, + flags: context.flags, + }; + const messageIndex = this.getNextBufferIndex(); + const bufferEntry = { + entryType: 'MESSAGE', + message: writeObj, + allocated: this.bufferTracker.allocate(message.length, this.callNumber), + }; + this.writeBuffer.push(bufferEntry); + if (bufferEntry.allocated) { + (_a = context.callback) === null || _a === void 0 ? void 0 : _a.call(context); + for (const [callIndex, call] of this.underlyingCalls.entries()) { + if (call.state === 'ACTIVE' && + call.nextMessageToSend === messageIndex) { + call.call.sendMessageWithContext({ + callback: error => { + // Ignore error + this.handleChildWriteCompleted(callIndex); + }, + }, message); + } + } + } + else { + this.commitCallWithMostMessages(); + // commitCallWithMostMessages can fail if we are between ping attempts + if (this.committedCallIndex === null) { + return; + } + const call = this.underlyingCalls[this.committedCallIndex]; + bufferEntry.callback = context.callback; + if (call.state === 'ACTIVE' && call.nextMessageToSend === messageIndex) { + call.call.sendMessageWithContext({ + callback: error => { + // Ignore error + this.handleChildWriteCompleted(this.committedCallIndex); + }, + }, message); + } + } + } + startRead() { + this.trace('startRead called'); + this.readStarted = true; + for (const underlyingCall of this.underlyingCalls) { + if ((underlyingCall === null || underlyingCall === void 0 ? void 0 : underlyingCall.state) === 'ACTIVE') { + underlyingCall.call.startRead(); + } + } + } + halfClose() { + this.trace('halfClose called'); + const halfCloseIndex = this.getNextBufferIndex(); + this.writeBuffer.push({ + entryType: 'HALF_CLOSE', + allocated: false, + }); + for (const call of this.underlyingCalls) { + if ((call === null || call === void 0 ? void 0 : call.state) === 'ACTIVE' && + call.nextMessageToSend === halfCloseIndex) { + call.nextMessageToSend += 1; + call.call.halfClose(); + } + } + } + setCredentials(newCredentials) { + throw new Error('Method not implemented.'); + } + getMethod() { + return this.methodName; + } + getHost() { + return this.host; + } + getAuthContext() { + if (this.committedCallIndex !== null) { + return this.underlyingCalls[this.committedCallIndex].call.getAuthContext(); + } + else { + return null; + } + } +} +exports.RetryingCall = RetryingCall; +//# sourceMappingURL=retrying-call.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/retrying-call.js.map b/node_modules/@grpc/grpc-js/build/src/retrying-call.js.map new file mode 100644 index 0000000..5173d68 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/retrying-call.js.map @@ -0,0 +1 @@ +{"version":3,"file":"retrying-call.js","sourceRoot":"","sources":["../../src/retrying-call.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAGH,2CAAmD;AACnD,yCAA4D;AAC5D,yCAAsC;AAEtC,qCAAqC;AAiBrC,MAAM,WAAW,GAAG,eAAe,CAAC;AAEpC,MAAa,cAAc;IAEzB,YACmB,SAAiB,EACjB,UAAkB,EACnC,sBAAuC;QAFtB,cAAS,GAAT,SAAS,CAAQ;QACjB,eAAU,GAAV,UAAU,CAAQ;QAGnC,IAAI,sBAAsB,EAAE,CAAC;YAC3B;+BACmB;YACnB,IAAI,CAAC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;QACH,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;YACxC,IACE,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,KAAK,MAAK,QAAQ;gBACxB,IAAI,CAAC,iBAAiB,KAAK,cAAc,EACzC,CAAC;gBACD,IAAI,CAAC,iBAAiB,IAAI,CAAC,CAAC;gBAC5B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;YACxB,CAAC;QACH,CAAC;IACH,CAAC;IACD,cAAc,CAAC,cAA+B;QAC5C,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IACD,SAAS;QACP,OAAO,IAAI,CAAC,UAAU,CAAC;IACzB,CAAC;IACD,OAAO;QACL,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;IACD,cAAc;QACZ,IAAI,IAAI,CAAC,kBAAkB,KAAK,IAAI,EAAE,CAAC;YACrC,OAAO,IAAI,CAAC,eAAe,CACzB,IAAI,CAAC,kBAAkB,CACxB,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC;QAC1B,CAAC;aAAM,CAAC;YACN,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;CACF;AA1sBD,oCA0sBC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/server-call.d.ts b/node_modules/@grpc/grpc-js/build/src/server-call.d.ts new file mode 100644 index 0000000..0f3d779 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server-call.d.ts @@ -0,0 +1,141 @@ +import { EventEmitter } from 'events'; +import { Duplex, Readable, Writable } from 'stream'; +import type { Deserialize, Serialize } from './make-client'; +import { Metadata } from './metadata'; +import type { ObjectReadable, ObjectWritable } from './object-stream'; +import type { StatusObject, PartialStatusObject } from './call-interface'; +import type { Deadline } from './deadline'; +import type { ServerInterceptingCallInterface } from './server-interceptors'; +import { AuthContext } from './auth-context'; +import { PerRequestMetricRecorder } from './orca'; +export type ServerStatusResponse = Partial; +export type ServerErrorResponse = ServerStatusResponse & Error; +export type ServerSurfaceCall = { + cancelled: boolean; + readonly metadata: Metadata; + getPeer(): string; + sendMetadata(responseMetadata: Metadata): void; + getDeadline(): Deadline; + getPath(): string; + getHost(): string; + getAuthContext(): AuthContext; + getMetricsRecorder(): PerRequestMetricRecorder; +} & EventEmitter; +export type ServerUnaryCall = ServerSurfaceCall & { + request: RequestType; +}; +export type ServerReadableStream = ServerSurfaceCall & ObjectReadable; +export type ServerWritableStream = ServerSurfaceCall & ObjectWritable & { + request: RequestType; + end: (metadata?: Metadata) => void; +}; +export type ServerDuplexStream = ServerSurfaceCall & ObjectReadable & ObjectWritable & { + end: (metadata?: Metadata) => void; +}; +export declare function serverErrorToStatus(error: ServerErrorResponse | ServerStatusResponse, overrideTrailers?: Metadata | undefined): PartialStatusObject; +export declare class ServerUnaryCallImpl extends EventEmitter implements ServerUnaryCall { + private path; + private call; + metadata: Metadata; + request: RequestType; + cancelled: boolean; + constructor(path: string, call: ServerInterceptingCallInterface, metadata: Metadata, request: RequestType); + getPeer(): string; + sendMetadata(responseMetadata: Metadata): void; + getDeadline(): Deadline; + getPath(): string; + getHost(): string; + getAuthContext(): AuthContext; + getMetricsRecorder(): PerRequestMetricRecorder; +} +export declare class ServerReadableStreamImpl extends Readable implements ServerReadableStream { + private path; + private call; + metadata: Metadata; + cancelled: boolean; + constructor(path: string, call: ServerInterceptingCallInterface, metadata: Metadata); + _read(size: number): void; + getPeer(): string; + sendMetadata(responseMetadata: Metadata): void; + getDeadline(): Deadline; + getPath(): string; + getHost(): string; + getAuthContext(): AuthContext; + getMetricsRecorder(): PerRequestMetricRecorder; +} +export declare class ServerWritableStreamImpl extends Writable implements ServerWritableStream { + private path; + private call; + metadata: Metadata; + request: RequestType; + cancelled: boolean; + private trailingMetadata; + private pendingStatus; + constructor(path: string, call: ServerInterceptingCallInterface, metadata: Metadata, request: RequestType); + getPeer(): string; + sendMetadata(responseMetadata: Metadata): void; + getDeadline(): Deadline; + getPath(): string; + getHost(): string; + getAuthContext(): AuthContext; + getMetricsRecorder(): PerRequestMetricRecorder; + _write(chunk: ResponseType, encoding: string, callback: (...args: any[]) => void): void; + _final(callback: Function): void; + end(metadata?: any): this; +} +export declare class ServerDuplexStreamImpl extends Duplex implements ServerDuplexStream { + private path; + private call; + metadata: Metadata; + cancelled: boolean; + private trailingMetadata; + private pendingStatus; + constructor(path: string, call: ServerInterceptingCallInterface, metadata: Metadata); + getPeer(): string; + sendMetadata(responseMetadata: Metadata): void; + getDeadline(): Deadline; + getPath(): string; + getHost(): string; + getAuthContext(): AuthContext; + getMetricsRecorder(): PerRequestMetricRecorder; + _read(size: number): void; + _write(chunk: ResponseType, encoding: string, callback: (...args: any[]) => void): void; + _final(callback: Function): void; + end(metadata?: any): this; +} +export type sendUnaryData = (error: ServerErrorResponse | ServerStatusResponse | null, value?: ResponseType | null, trailer?: Metadata, flags?: number) => void; +export type handleUnaryCall = (call: ServerUnaryCall, callback: sendUnaryData) => void; +export type handleClientStreamingCall = (call: ServerReadableStream, callback: sendUnaryData) => void; +export type handleServerStreamingCall = (call: ServerWritableStream) => void; +export type handleBidiStreamingCall = (call: ServerDuplexStream) => void; +export type HandleCall = handleUnaryCall | handleClientStreamingCall | handleServerStreamingCall | handleBidiStreamingCall; +export interface UnaryHandler { + func: handleUnaryCall; + serialize: Serialize; + deserialize: Deserialize; + type: 'unary'; + path: string; +} +export interface ClientStreamingHandler { + func: handleClientStreamingCall; + serialize: Serialize; + deserialize: Deserialize; + type: 'clientStream'; + path: string; +} +export interface ServerStreamingHandler { + func: handleServerStreamingCall; + serialize: Serialize; + deserialize: Deserialize; + type: 'serverStream'; + path: string; +} +export interface BidiStreamingHandler { + func: handleBidiStreamingCall; + serialize: Serialize; + deserialize: Deserialize; + type: 'bidi'; + path: string; +} +export type Handler = UnaryHandler | ClientStreamingHandler | ServerStreamingHandler | BidiStreamingHandler; +export type HandlerType = 'bidi' | 'clientStream' | 'serverStream' | 'unary'; diff --git a/node_modules/@grpc/grpc-js/build/src/server-call.js b/node_modules/@grpc/grpc-js/build/src/server-call.js new file mode 100644 index 0000000..521f4d3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server-call.js @@ -0,0 +1,226 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ServerDuplexStreamImpl = exports.ServerWritableStreamImpl = exports.ServerReadableStreamImpl = exports.ServerUnaryCallImpl = void 0; +exports.serverErrorToStatus = serverErrorToStatus; +const events_1 = require("events"); +const stream_1 = require("stream"); +const constants_1 = require("./constants"); +const metadata_1 = require("./metadata"); +function serverErrorToStatus(error, overrideTrailers) { + var _a; + const status = { + code: constants_1.Status.UNKNOWN, + details: 'message' in error ? error.message : 'Unknown Error', + metadata: (_a = overrideTrailers !== null && overrideTrailers !== void 0 ? overrideTrailers : error.metadata) !== null && _a !== void 0 ? _a : null, + }; + if ('code' in error && + typeof error.code === 'number' && + Number.isInteger(error.code)) { + status.code = error.code; + if ('details' in error && typeof error.details === 'string') { + status.details = error.details; + } + } + return status; +} +class ServerUnaryCallImpl extends events_1.EventEmitter { + constructor(path, call, metadata, request) { + super(); + this.path = path; + this.call = call; + this.metadata = metadata; + this.request = request; + this.cancelled = false; + } + getPeer() { + return this.call.getPeer(); + } + sendMetadata(responseMetadata) { + this.call.sendMetadata(responseMetadata); + } + getDeadline() { + return this.call.getDeadline(); + } + getPath() { + return this.path; + } + getHost() { + return this.call.getHost(); + } + getAuthContext() { + return this.call.getAuthContext(); + } + getMetricsRecorder() { + return this.call.getMetricsRecorder(); + } +} +exports.ServerUnaryCallImpl = ServerUnaryCallImpl; +class ServerReadableStreamImpl extends stream_1.Readable { + constructor(path, call, metadata) { + super({ objectMode: true }); + this.path = path; + this.call = call; + this.metadata = metadata; + this.cancelled = false; + } + _read(size) { + this.call.startRead(); + } + getPeer() { + return this.call.getPeer(); + } + sendMetadata(responseMetadata) { + this.call.sendMetadata(responseMetadata); + } + getDeadline() { + return this.call.getDeadline(); + } + getPath() { + return this.path; + } + getHost() { + return this.call.getHost(); + } + getAuthContext() { + return this.call.getAuthContext(); + } + getMetricsRecorder() { + return this.call.getMetricsRecorder(); + } +} +exports.ServerReadableStreamImpl = ServerReadableStreamImpl; +class ServerWritableStreamImpl extends stream_1.Writable { + constructor(path, call, metadata, request) { + super({ objectMode: true }); + this.path = path; + this.call = call; + this.metadata = metadata; + this.request = request; + this.pendingStatus = { + code: constants_1.Status.OK, + details: 'OK', + }; + this.cancelled = false; + this.trailingMetadata = new metadata_1.Metadata(); + this.on('error', err => { + this.pendingStatus = serverErrorToStatus(err); + this.end(); + }); + } + getPeer() { + return this.call.getPeer(); + } + sendMetadata(responseMetadata) { + this.call.sendMetadata(responseMetadata); + } + getDeadline() { + return this.call.getDeadline(); + } + getPath() { + return this.path; + } + getHost() { + return this.call.getHost(); + } + getAuthContext() { + return this.call.getAuthContext(); + } + getMetricsRecorder() { + return this.call.getMetricsRecorder(); + } + _write(chunk, encoding, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callback) { + this.call.sendMessage(chunk, callback); + } + _final(callback) { + var _a; + callback(null); + this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a = this.pendingStatus.metadata) !== null && _a !== void 0 ? _a : this.trailingMetadata })); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + end(metadata) { + if (metadata) { + this.trailingMetadata = metadata; + } + return super.end(); + } +} +exports.ServerWritableStreamImpl = ServerWritableStreamImpl; +class ServerDuplexStreamImpl extends stream_1.Duplex { + constructor(path, call, metadata) { + super({ objectMode: true }); + this.path = path; + this.call = call; + this.metadata = metadata; + this.pendingStatus = { + code: constants_1.Status.OK, + details: 'OK', + }; + this.cancelled = false; + this.trailingMetadata = new metadata_1.Metadata(); + this.on('error', err => { + this.pendingStatus = serverErrorToStatus(err); + this.end(); + }); + } + getPeer() { + return this.call.getPeer(); + } + sendMetadata(responseMetadata) { + this.call.sendMetadata(responseMetadata); + } + getDeadline() { + return this.call.getDeadline(); + } + getPath() { + return this.path; + } + getHost() { + return this.call.getHost(); + } + getAuthContext() { + return this.call.getAuthContext(); + } + getMetricsRecorder() { + return this.call.getMetricsRecorder(); + } + _read(size) { + this.call.startRead(); + } + _write(chunk, encoding, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callback) { + this.call.sendMessage(chunk, callback); + } + _final(callback) { + var _a; + callback(null); + this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a = this.pendingStatus.metadata) !== null && _a !== void 0 ? _a : this.trailingMetadata })); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + end(metadata) { + if (metadata) { + this.trailingMetadata = metadata; + } + return super.end(); + } +} +exports.ServerDuplexStreamImpl = ServerDuplexStreamImpl; +//# sourceMappingURL=server-call.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/server-call.js.map b/node_modules/@grpc/grpc-js/build/src/server-call.js.map new file mode 100644 index 0000000..51c2053 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server-call.js.map @@ -0,0 +1 @@ +{"version":3,"file":"server-call.js","sourceRoot":"","sources":["../../src/server-call.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AA8CH,kDAsBC;AAlED,mCAAsC;AACtC,mCAAoD;AAEpD,2CAAqC;AAErC,yCAAsC;AAuCtC,SAAgB,mBAAmB,CACjC,KAAiD,EACjD,gBAAuC;;IAEvC,MAAM,MAAM,GAAwB;QAClC,IAAI,EAAE,kBAAM,CAAC,OAAO;QACpB,OA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C,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,gBAAgB,CAAC,CAAC;IAC3C,CAAC;IAED,WAAW;QACT,OAAO,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC;IACjC,CAAC;IAED,OAAO;QACL,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;IAED,OAAO;QACL,OAAO,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;IAC7B,CAAC;IAED,cAAc;QACZ,OAAO,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC;IACpC,CAAC;IAED,kBAAkB;QAChB,OAAO,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,CAAC;IACxC,CAAC;IAED,KAAK,CAAC,IAAY;QAChB,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;IACxB,CAAC;IAED,MAAM,CACJ,KAAmB,EACnB,QAAgB;IAChB,8DAA8D;IAC9D,QAAkC;QAElC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IACzC,CAAC;IAED,MAAM,CAAC,QAAkB;;QACvB,QAAQ,CAAC,IAAI,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,CAAC,UAAU,iCACf,IAAI,CAAC,aAAa,KACrB,QAAQ,EAAE,MAAA,IAAI,CAAC,aAAa,CAAC,QAAQ,mCAAI,IAAI,CAAC,gBAAgB,IAC9D,CAAC;IACL,CAAC;IAED,8DAA8D;IAC9D,GAAG,CAAC,QAAc;QAChB,IAAI,QAAQ,EAAE,CAAC;YACb,IAAI,CAAC,gBAAgB,GAAG,QAAQ,CAAC;QACnC,CAAC;QAED,OAAO,KAAK,CAAC,GAAG,EAAE,CAAC;IACrB,CAAC;CACF;AAnFD,wDAmFC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/server-credentials.d.ts b/node_modules/@grpc/grpc-js/build/src/server-credentials.d.ts new file mode 100644 index 0000000..2d4fe0c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server-credentials.d.ts @@ -0,0 +1,48 @@ +import { SecureServerOptions } from 'http2'; +import { SecureContextOptions } from 'tls'; +import { ServerInterceptor } from '.'; +import { CertificateProvider } from './certificate-provider'; +export interface KeyCertPair { + private_key: Buffer; + cert_chain: Buffer; +} +export interface SecureContextWatcher { + (context: SecureContextOptions | null): void; +} +export declare abstract class ServerCredentials { + private serverConstructorOptions; + private watchers; + private latestContextOptions; + constructor(serverConstructorOptions: SecureServerOptions | null, contextOptions?: SecureContextOptions); + _addWatcher(watcher: SecureContextWatcher): void; + _removeWatcher(watcher: SecureContextWatcher): void; + protected getWatcherCount(): number; + protected updateSecureContextOptions(options: SecureContextOptions | null): void; + _isSecure(): boolean; + _getSecureContextOptions(): SecureContextOptions | null; + _getConstructorOptions(): SecureServerOptions | null; + _getInterceptors(): ServerInterceptor[]; + abstract _equals(other: ServerCredentials): boolean; + static createInsecure(): ServerCredentials; + static createSsl(rootCerts: Buffer | null, keyCertPairs: KeyCertPair[], checkClientCertificate?: boolean): ServerCredentials; +} +declare class CertificateProviderServerCredentials extends ServerCredentials { + private identityCertificateProvider; + private caCertificateProvider; + private requireClientCertificate; + private latestCaUpdate; + private latestIdentityUpdate; + private caCertificateUpdateListener; + private identityCertificateUpdateListener; + constructor(identityCertificateProvider: CertificateProvider, caCertificateProvider: CertificateProvider | null, requireClientCertificate: boolean); + _addWatcher(watcher: SecureContextWatcher): void; + _removeWatcher(watcher: SecureContextWatcher): void; + _equals(other: ServerCredentials): boolean; + private calculateSecureContextOptions; + private finalizeUpdate; + private handleCaCertificateUpdate; + private handleIdentityCertitificateUpdate; +} +export declare function createCertificateProviderServerCredentials(caCertificateProvider: CertificateProvider, identityCertificateProvider: CertificateProvider | null, requireClientCertificate: boolean): CertificateProviderServerCredentials; +export declare function createServerCredentialsWithInterceptors(credentials: ServerCredentials, interceptors: ServerInterceptor[]): ServerCredentials; +export {}; diff --git a/node_modules/@grpc/grpc-js/build/src/server-credentials.js b/node_modules/@grpc/grpc-js/build/src/server-credentials.js new file mode 100644 index 0000000..f8800f8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server-credentials.js @@ -0,0 +1,314 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ServerCredentials = void 0; +exports.createCertificateProviderServerCredentials = createCertificateProviderServerCredentials; +exports.createServerCredentialsWithInterceptors = createServerCredentialsWithInterceptors; +const tls_helpers_1 = require("./tls-helpers"); +class ServerCredentials { + constructor(serverConstructorOptions, contextOptions) { + this.serverConstructorOptions = serverConstructorOptions; + this.watchers = new Set(); + this.latestContextOptions = null; + this.latestContextOptions = contextOptions !== null && contextOptions !== void 0 ? contextOptions : null; + } + _addWatcher(watcher) { + this.watchers.add(watcher); + } + _removeWatcher(watcher) { + this.watchers.delete(watcher); + } + getWatcherCount() { + return this.watchers.size; + } + updateSecureContextOptions(options) { + this.latestContextOptions = options; + for (const watcher of this.watchers) { + watcher(this.latestContextOptions); + } + } + _isSecure() { + return this.serverConstructorOptions !== null; + } + _getSecureContextOptions() { + return this.latestContextOptions; + } + _getConstructorOptions() { + return this.serverConstructorOptions; + } + _getInterceptors() { + return []; + } + static createInsecure() { + return new InsecureServerCredentials(); + } + static createSsl(rootCerts, keyCertPairs, checkClientCertificate = false) { + var _a; + if (rootCerts !== null && !Buffer.isBuffer(rootCerts)) { + throw new TypeError('rootCerts must be null or a Buffer'); + } + if (!Array.isArray(keyCertPairs)) { + throw new TypeError('keyCertPairs must be an array'); + } + if (typeof checkClientCertificate !== 'boolean') { + throw new TypeError('checkClientCertificate must be a boolean'); + } + const cert = []; + const key = []; + for (let i = 0; i < keyCertPairs.length; i++) { + const pair = keyCertPairs[i]; + if (pair === null || typeof pair !== 'object') { + throw new TypeError(`keyCertPair[${i}] must be an object`); + } + if (!Buffer.isBuffer(pair.private_key)) { + throw new TypeError(`keyCertPair[${i}].private_key must be a Buffer`); + } + if (!Buffer.isBuffer(pair.cert_chain)) { + throw new TypeError(`keyCertPair[${i}].cert_chain must be a Buffer`); + } + cert.push(pair.cert_chain); + key.push(pair.private_key); + } + return new SecureServerCredentials({ + requestCert: checkClientCertificate, + ciphers: tls_helpers_1.CIPHER_SUITES, + }, { + ca: (_a = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a !== void 0 ? _a : undefined, + cert, + key, + }); + } +} +exports.ServerCredentials = ServerCredentials; +class InsecureServerCredentials extends ServerCredentials { + constructor() { + super(null); + } + _getSettings() { + return null; + } + _equals(other) { + return other instanceof InsecureServerCredentials; + } +} +class SecureServerCredentials extends ServerCredentials { + constructor(constructorOptions, contextOptions) { + super(constructorOptions, contextOptions); + this.options = Object.assign(Object.assign({}, constructorOptions), contextOptions); + } + /** + * Checks equality by checking the options that are actually set by + * createSsl. + * @param other + * @returns + */ + _equals(other) { + if (this === other) { + return true; + } + if (!(other instanceof SecureServerCredentials)) { + return false; + } + // options.ca equality check + if (Buffer.isBuffer(this.options.ca) && Buffer.isBuffer(other.options.ca)) { + if (!this.options.ca.equals(other.options.ca)) { + return false; + } + } + else { + if (this.options.ca !== other.options.ca) { + return false; + } + } + // options.cert equality check + if (Array.isArray(this.options.cert) && Array.isArray(other.options.cert)) { + if (this.options.cert.length !== other.options.cert.length) { + return false; + } + for (let i = 0; i < this.options.cert.length; i++) { + const thisCert = this.options.cert[i]; + const otherCert = other.options.cert[i]; + if (Buffer.isBuffer(thisCert) && Buffer.isBuffer(otherCert)) { + if (!thisCert.equals(otherCert)) { + return false; + } + } + else { + if (thisCert !== otherCert) { + return false; + } + } + } + } + else { + if (this.options.cert !== other.options.cert) { + return false; + } + } + // options.key equality check + if (Array.isArray(this.options.key) && Array.isArray(other.options.key)) { + if (this.options.key.length !== other.options.key.length) { + return false; + } + for (let i = 0; i < this.options.key.length; i++) { + const thisKey = this.options.key[i]; + const otherKey = other.options.key[i]; + if (Buffer.isBuffer(thisKey) && Buffer.isBuffer(otherKey)) { + if (!thisKey.equals(otherKey)) { + return false; + } + } + else { + if (thisKey !== otherKey) { + return false; + } + } + } + } + else { + if (this.options.key !== other.options.key) { + return false; + } + } + // options.requestCert equality check + if (this.options.requestCert !== other.options.requestCert) { + return false; + } + /* ciphers is derived from a value that is constant for the process, so no + * equality check is needed. */ + return true; + } +} +class CertificateProviderServerCredentials extends ServerCredentials { + constructor(identityCertificateProvider, caCertificateProvider, requireClientCertificate) { + super({ + requestCert: caCertificateProvider !== null, + rejectUnauthorized: requireClientCertificate, + ciphers: tls_helpers_1.CIPHER_SUITES + }); + this.identityCertificateProvider = identityCertificateProvider; + this.caCertificateProvider = caCertificateProvider; + this.requireClientCertificate = requireClientCertificate; + this.latestCaUpdate = null; + this.latestIdentityUpdate = null; + this.caCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this); + this.identityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this); + } + _addWatcher(watcher) { + var _a; + if (this.getWatcherCount() === 0) { + (_a = this.caCertificateProvider) === null || _a === void 0 ? void 0 : _a.addCaCertificateListener(this.caCertificateUpdateListener); + this.identityCertificateProvider.addIdentityCertificateListener(this.identityCertificateUpdateListener); + } + super._addWatcher(watcher); + } + _removeWatcher(watcher) { + var _a; + super._removeWatcher(watcher); + if (this.getWatcherCount() === 0) { + (_a = this.caCertificateProvider) === null || _a === void 0 ? void 0 : _a.removeCaCertificateListener(this.caCertificateUpdateListener); + this.identityCertificateProvider.removeIdentityCertificateListener(this.identityCertificateUpdateListener); + } + } + _equals(other) { + if (this === other) { + return true; + } + if (!(other instanceof CertificateProviderServerCredentials)) { + return false; + } + return (this.caCertificateProvider === other.caCertificateProvider && + this.identityCertificateProvider === other.identityCertificateProvider && + this.requireClientCertificate === other.requireClientCertificate); + } + calculateSecureContextOptions() { + var _a; + if (this.latestIdentityUpdate === null) { + return null; + } + if (this.caCertificateProvider !== null && this.latestCaUpdate === null) { + return null; + } + return { + ca: (_a = this.latestCaUpdate) === null || _a === void 0 ? void 0 : _a.caCertificate, + cert: [this.latestIdentityUpdate.certificate], + key: [this.latestIdentityUpdate.privateKey], + }; + } + finalizeUpdate() { + const secureContextOptions = this.calculateSecureContextOptions(); + this.updateSecureContextOptions(secureContextOptions); + } + handleCaCertificateUpdate(update) { + this.latestCaUpdate = update; + this.finalizeUpdate(); + } + handleIdentityCertitificateUpdate(update) { + this.latestIdentityUpdate = update; + this.finalizeUpdate(); + } +} +function createCertificateProviderServerCredentials(caCertificateProvider, identityCertificateProvider, requireClientCertificate) { + return new CertificateProviderServerCredentials(caCertificateProvider, identityCertificateProvider, requireClientCertificate); +} +class InterceptorServerCredentials extends ServerCredentials { + constructor(childCredentials, interceptors) { + super({}); + this.childCredentials = childCredentials; + this.interceptors = interceptors; + } + _isSecure() { + return this.childCredentials._isSecure(); + } + _equals(other) { + if (!(other instanceof InterceptorServerCredentials)) { + return false; + } + if (!(this.childCredentials._equals(other.childCredentials))) { + return false; + } + if (this.interceptors.length !== other.interceptors.length) { + return false; + } + for (let i = 0; i < this.interceptors.length; i++) { + if (this.interceptors[i] !== other.interceptors[i]) { + return false; + } + } + return true; + } + _getInterceptors() { + return this.interceptors; + } + _addWatcher(watcher) { + this.childCredentials._addWatcher(watcher); + } + _removeWatcher(watcher) { + this.childCredentials._removeWatcher(watcher); + } + _getConstructorOptions() { + return this.childCredentials._getConstructorOptions(); + } + _getSecureContextOptions() { + return this.childCredentials._getSecureContextOptions(); + } +} +function createServerCredentialsWithInterceptors(credentials, interceptors) { + return new InterceptorServerCredentials(credentials, interceptors); +} +//# sourceMappingURL=server-credentials.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/server-credentials.js.map b/node_modules/@grpc/grpc-js/build/src/server-credentials.js.map new file mode 100644 index 0000000..02658e0 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server-credentials.js.map @@ -0,0 +1 @@ +{"version":3,"file":"server-credentials.js","sourceRoot":"","sources":["../../src/server-credentials.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AA0RH,gGASC;AA2CD,0FAEC;AA7UD,+CAAmE;AAcnE,MAAsB,iBAAiB;IAGrC,YAAoB,wBAAoD,EAAE,cAAqC;QAA3F,6BAAwB,GAAxB,wBAAwB,CAA4B;QAFhE,aAAQ,GAA8B,IAAI,GAAG,EAAE,CAAC;QAChD,yBAAoB,GAAgC,IAAI,CAAC;QAE/D,IAAI,CAAC,oBAAoB,GAAG,cAAc,aAAd,cAAc,cAAd,cAAc,GAAI,IAAI,CAAC;IACrD,CAAC;IAED,WAAW,CAAC,OAA6B;QACvC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAC7B,CAAC;IACD,cAAc,CAAC,OAA6B;QAC1C,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAChC,CAAC;IACS,eAAe;QACvB,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;IAC5B,CAAC;IACS,0BAA0B,CAAC,OAAoC;QACvE,IAAI,CAAC,oBAAoB,GAAG,OAAO,CAAC;QACpC,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YACpC,OAAO,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;QACrC,CAAC;IACH,CAAC;IACD,SAAS;QACP,OAAO,IAAI,CAAC,wBAAwB,KAAK,IAAI,CAAC;IAChD,CAAC;IACD,wBAAwB;QACtB,OAAO,IAAI,CAAC,oBAAoB,CAAC;IACnC,CAAC;IACD,sBAAsB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,IAAI,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,KAAK,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,CAAC;gBACnD,OAAO,KAAK,CAAC;YACf,CAAC;QACH,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IACQ,gBAAgB;QACvB,OAAO,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;IACQ,WAAW,CAAC,OAA6B;QAChD,IAAI,CAAC,gBAAgB,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IAC7C,CAAC;IACQ,cAAc,CAAC,OAA6B;QACnD,IAAI,CAAC,gBAAgB,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;IAChD,CAAC;IACQ,sBAAsB;QAC7B,OAAO,IAAI,CAAC,gBAAgB,CAAC,sBAAsB,EAAE,CAAC;IACxD,CAAC;IACQ,wBAAwB;QAC/B,OAAO,IAAI,CAAC,gBAAgB,CAAC,wBAAwB,EAAE,CAAC;IAC1D,CAAC;CACF;AAED,SAAgB,uCAAuC,CAAC,WAA8B,EAAE,YAAiC;IACvH,OAAO,IAAI,4BAA4B,CAAC,WAAW,EAAE,YAAY,CAAC,CAAC;AACrE,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/server-interceptors.d.ts b/node_modules/@grpc/grpc-js/build/src/server-interceptors.d.ts new file mode 100644 index 0000000..ab05b76 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server-interceptors.d.ts @@ -0,0 +1,216 @@ +import { PartialStatusObject } from './call-interface'; +import { ServerMethodDefinition } from './make-client'; +import { Metadata } from './metadata'; +import { ChannelOptions } from './channel-options'; +import { Handler } from './server-call'; +import { Deadline } from './deadline'; +import * as http2 from 'http2'; +import { CallEventTracker } from './transport'; +import { AuthContext } from './auth-context'; +import { PerRequestMetricRecorder } from './orca'; +export interface ServerMetadataListener { + (metadata: Metadata, next: (metadata: Metadata) => void): void; +} +export interface ServerMessageListener { + (message: any, next: (message: any) => void): void; +} +export interface ServerHalfCloseListener { + (next: () => void): void; +} +export interface ServerCancelListener { + (): void; +} +export interface FullServerListener { + onReceiveMetadata: ServerMetadataListener; + onReceiveMessage: ServerMessageListener; + onReceiveHalfClose: ServerHalfCloseListener; + onCancel: ServerCancelListener; +} +export type ServerListener = Partial; +export declare class ServerListenerBuilder { + private metadata; + private message; + private halfClose; + private cancel; + withOnReceiveMetadata(onReceiveMetadata: ServerMetadataListener): this; + withOnReceiveMessage(onReceiveMessage: ServerMessageListener): this; + withOnReceiveHalfClose(onReceiveHalfClose: ServerHalfCloseListener): this; + withOnCancel(onCancel: ServerCancelListener): this; + build(): ServerListener; +} +export interface InterceptingServerListener { + onReceiveMetadata(metadata: Metadata): void; + onReceiveMessage(message: any): void; + onReceiveHalfClose(): void; + onCancel(): void; +} +export declare function isInterceptingServerListener(listener: ServerListener | InterceptingServerListener): listener is InterceptingServerListener; +export interface StartResponder { + (next: (listener?: ServerListener) => void): void; +} +export interface MetadataResponder { + (metadata: Metadata, next: (metadata: Metadata) => void): void; +} +export interface MessageResponder { + (message: any, next: (message: any) => void): void; +} +export interface StatusResponder { + (status: PartialStatusObject, next: (status: PartialStatusObject) => void): void; +} +export interface FullResponder { + start: StartResponder; + sendMetadata: MetadataResponder; + sendMessage: MessageResponder; + sendStatus: StatusResponder; +} +export type Responder = Partial; +export declare class ResponderBuilder { + private start; + private metadata; + private message; + private status; + withStart(start: StartResponder): this; + withSendMetadata(sendMetadata: MetadataResponder): this; + withSendMessage(sendMessage: MessageResponder): this; + withSendStatus(sendStatus: StatusResponder): this; + build(): Responder; +} +export interface ConnectionInfo { + localAddress?: string | undefined; + localPort?: number | undefined; + remoteAddress?: string | undefined; + remotePort?: number | undefined; +} +export interface ServerInterceptingCallInterface { + /** + * Register the listener to handle inbound events. + */ + start(listener: InterceptingServerListener): void; + /** + * Send response metadata. + */ + sendMetadata(metadata: Metadata): void; + /** + * Send a response message. + */ + sendMessage(message: any, callback: () => void): void; + /** + * End the call by sending this status. + */ + sendStatus(status: PartialStatusObject): void; + /** + * Start a single read, eventually triggering either listener.onReceiveMessage or listener.onReceiveHalfClose. + */ + startRead(): void; + /** + * Return the peer address of the client making the request, if known, or "unknown" otherwise + */ + getPeer(): string; + /** + * Return the call deadline set by the client. The value is Infinity if there is no deadline. + */ + getDeadline(): Deadline; + /** + * Return the host requested by the client in the ":authority" header. + */ + getHost(): string; + /** + * Return the auth context of the connection the call is associated with. + */ + getAuthContext(): AuthContext; + /** + * Return information about the connection used to make the call. + */ + getConnectionInfo(): ConnectionInfo; + /** + * Get the metrics recorder for this call. Metrics will not be sent unless + * the server was constructed with the `grpc.server_call_metric_recording` + * option. + */ + getMetricsRecorder(): PerRequestMetricRecorder; +} +export declare class ServerInterceptingCall implements ServerInterceptingCallInterface { + private nextCall; + private responder; + private processingMetadata; + private sentMetadata; + private processingMessage; + private pendingMessage; + private pendingMessageCallback; + private pendingStatus; + constructor(nextCall: ServerInterceptingCallInterface, responder?: Responder); + private processPendingMessage; + private processPendingStatus; + start(listener: InterceptingServerListener): void; + sendMetadata(metadata: Metadata): void; + sendMessage(message: any, callback: () => void): void; + sendStatus(status: PartialStatusObject): void; + startRead(): void; + getPeer(): string; + getDeadline(): Deadline; + getHost(): string; + getAuthContext(): AuthContext; + getConnectionInfo(): ConnectionInfo; + getMetricsRecorder(): PerRequestMetricRecorder; +} +export interface ServerInterceptor { + (methodDescriptor: ServerMethodDefinition, call: ServerInterceptingCallInterface): ServerInterceptingCall; +} +export declare class BaseServerInterceptingCall implements ServerInterceptingCallInterface { + private readonly stream; + private readonly callEventTracker; + private readonly handler; + private listener; + private metadata; + private deadlineTimer; + private deadline; + private maxSendMessageSize; + private maxReceiveMessageSize; + private cancelled; + private metadataSent; + private wantTrailers; + private cancelNotified; + private incomingEncoding; + private decoder; + private readQueue; + private isReadPending; + private receivedHalfClose; + private streamEnded; + private host; + private connectionInfo; + private metricsRecorder; + private shouldSendMetrics; + constructor(stream: http2.ServerHttp2Stream, headers: http2.IncomingHttpHeaders, callEventTracker: CallEventTracker | null, handler: Handler, options: ChannelOptions); + private handleTimeoutHeader; + private checkCancelled; + private notifyOnCancel; + /** + * A server handler can start sending messages without explicitly sending + * metadata. In that case, we need to send headers before sending any + * messages. This function does that if necessary. + */ + private maybeSendMetadata; + /** + * Serialize a message to a length-delimited byte string. + * @param value + * @returns + */ + private serializeMessage; + private decompressMessage; + private decompressAndMaybePush; + private maybePushNextMessage; + private handleDataFrame; + private handleEndEvent; + start(listener: InterceptingServerListener): void; + sendMetadata(metadata: Metadata): void; + sendMessage(message: any, callback: () => void): void; + sendStatus(status: PartialStatusObject): void; + startRead(): void; + getPeer(): string; + getDeadline(): Deadline; + getHost(): string; + getAuthContext(): AuthContext; + getConnectionInfo(): ConnectionInfo; + getMetricsRecorder(): PerRequestMetricRecorder; +} +export declare function getServerInterceptingCall(interceptors: ServerInterceptor[], stream: http2.ServerHttp2Stream, headers: http2.IncomingHttpHeaders, callEventTracker: CallEventTracker | null, handler: Handler, options: ChannelOptions): ServerInterceptingCallInterface; diff --git a/node_modules/@grpc/grpc-js/build/src/server-interceptors.js b/node_modules/@grpc/grpc-js/build/src/server-interceptors.js new file mode 100644 index 0000000..a159707 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server-interceptors.js @@ -0,0 +1,817 @@ +"use strict"; +/* + * Copyright 2024 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BaseServerInterceptingCall = exports.ServerInterceptingCall = exports.ResponderBuilder = exports.ServerListenerBuilder = void 0; +exports.isInterceptingServerListener = isInterceptingServerListener; +exports.getServerInterceptingCall = getServerInterceptingCall; +const metadata_1 = require("./metadata"); +const constants_1 = require("./constants"); +const http2 = require("http2"); +const error_1 = require("./error"); +const zlib = require("zlib"); +const stream_decoder_1 = require("./stream-decoder"); +const logging = require("./logging"); +const tls_1 = require("tls"); +const orca_1 = require("./orca"); +const TRACER_NAME = 'server_call'; +function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); +} +class ServerListenerBuilder { + constructor() { + this.metadata = undefined; + this.message = undefined; + this.halfClose = undefined; + this.cancel = undefined; + } + withOnReceiveMetadata(onReceiveMetadata) { + this.metadata = onReceiveMetadata; + return this; + } + withOnReceiveMessage(onReceiveMessage) { + this.message = onReceiveMessage; + return this; + } + withOnReceiveHalfClose(onReceiveHalfClose) { + this.halfClose = onReceiveHalfClose; + return this; + } + withOnCancel(onCancel) { + this.cancel = onCancel; + return this; + } + build() { + return { + onReceiveMetadata: this.metadata, + onReceiveMessage: this.message, + onReceiveHalfClose: this.halfClose, + onCancel: this.cancel, + }; + } +} +exports.ServerListenerBuilder = ServerListenerBuilder; +function isInterceptingServerListener(listener) { + return (listener.onReceiveMetadata !== undefined && + listener.onReceiveMetadata.length === 1); +} +class InterceptingServerListenerImpl { + constructor(listener, nextListener) { + this.listener = listener; + this.nextListener = nextListener; + /** + * Once the call is cancelled, ignore all other events. + */ + this.cancelled = false; + this.processingMetadata = false; + this.hasPendingMessage = false; + this.pendingMessage = null; + this.processingMessage = false; + this.hasPendingHalfClose = false; + } + processPendingMessage() { + if (this.hasPendingMessage) { + this.nextListener.onReceiveMessage(this.pendingMessage); + this.pendingMessage = null; + this.hasPendingMessage = false; + } + } + processPendingHalfClose() { + if (this.hasPendingHalfClose) { + this.nextListener.onReceiveHalfClose(); + this.hasPendingHalfClose = false; + } + } + onReceiveMetadata(metadata) { + if (this.cancelled) { + return; + } + this.processingMetadata = true; + this.listener.onReceiveMetadata(metadata, interceptedMetadata => { + this.processingMetadata = false; + if (this.cancelled) { + return; + } + this.nextListener.onReceiveMetadata(interceptedMetadata); + this.processPendingMessage(); + this.processPendingHalfClose(); + }); + } + onReceiveMessage(message) { + if (this.cancelled) { + return; + } + this.processingMessage = true; + this.listener.onReceiveMessage(message, msg => { + this.processingMessage = false; + if (this.cancelled) { + return; + } + if (this.processingMetadata) { + this.pendingMessage = msg; + this.hasPendingMessage = true; + } + else { + this.nextListener.onReceiveMessage(msg); + this.processPendingHalfClose(); + } + }); + } + onReceiveHalfClose() { + if (this.cancelled) { + return; + } + this.listener.onReceiveHalfClose(() => { + if (this.cancelled) { + return; + } + if (this.processingMetadata || this.processingMessage) { + this.hasPendingHalfClose = true; + } + else { + this.nextListener.onReceiveHalfClose(); + } + }); + } + onCancel() { + this.cancelled = true; + this.listener.onCancel(); + this.nextListener.onCancel(); + } +} +class ResponderBuilder { + constructor() { + this.start = undefined; + this.metadata = undefined; + this.message = undefined; + this.status = undefined; + } + withStart(start) { + this.start = start; + return this; + } + withSendMetadata(sendMetadata) { + this.metadata = sendMetadata; + return this; + } + withSendMessage(sendMessage) { + this.message = sendMessage; + return this; + } + withSendStatus(sendStatus) { + this.status = sendStatus; + return this; + } + build() { + return { + start: this.start, + sendMetadata: this.metadata, + sendMessage: this.message, + sendStatus: this.status, + }; + } +} +exports.ResponderBuilder = ResponderBuilder; +const defaultServerListener = { + onReceiveMetadata: (metadata, next) => { + next(metadata); + }, + onReceiveMessage: (message, next) => { + next(message); + }, + onReceiveHalfClose: next => { + next(); + }, + onCancel: () => { }, +}; +const defaultResponder = { + start: next => { + next(); + }, + sendMetadata: (metadata, next) => { + next(metadata); + }, + sendMessage: (message, next) => { + next(message); + }, + sendStatus: (status, next) => { + next(status); + }, +}; +class ServerInterceptingCall { + constructor(nextCall, responder) { + var _a, _b, _c, _d; + this.nextCall = nextCall; + this.processingMetadata = false; + this.sentMetadata = false; + this.processingMessage = false; + this.pendingMessage = null; + this.pendingMessageCallback = null; + this.pendingStatus = null; + this.responder = { + start: (_a = responder === null || responder === void 0 ? void 0 : responder.start) !== null && _a !== void 0 ? _a : defaultResponder.start, + sendMetadata: (_b = responder === null || responder === void 0 ? void 0 : responder.sendMetadata) !== null && _b !== void 0 ? _b : defaultResponder.sendMetadata, + sendMessage: (_c = responder === null || responder === void 0 ? void 0 : responder.sendMessage) !== null && _c !== void 0 ? _c : defaultResponder.sendMessage, + sendStatus: (_d = responder === null || responder === void 0 ? void 0 : responder.sendStatus) !== null && _d !== void 0 ? _d : defaultResponder.sendStatus, + }; + } + processPendingMessage() { + if (this.pendingMessageCallback) { + this.nextCall.sendMessage(this.pendingMessage, this.pendingMessageCallback); + this.pendingMessage = null; + this.pendingMessageCallback = null; + } + } + processPendingStatus() { + if (this.pendingStatus) { + this.nextCall.sendStatus(this.pendingStatus); + this.pendingStatus = null; + } + } + start(listener) { + this.responder.start(interceptedListener => { + var _a, _b, _c, _d; + const fullInterceptedListener = { + onReceiveMetadata: (_a = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveMetadata) !== null && _a !== void 0 ? _a : defaultServerListener.onReceiveMetadata, + onReceiveMessage: (_b = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveMessage) !== null && _b !== void 0 ? _b : defaultServerListener.onReceiveMessage, + onReceiveHalfClose: (_c = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveHalfClose) !== null && _c !== void 0 ? _c : defaultServerListener.onReceiveHalfClose, + onCancel: (_d = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onCancel) !== null && _d !== void 0 ? _d : defaultServerListener.onCancel, + }; + const finalInterceptingListener = new InterceptingServerListenerImpl(fullInterceptedListener, listener); + this.nextCall.start(finalInterceptingListener); + }); + } + sendMetadata(metadata) { + this.processingMetadata = true; + this.sentMetadata = true; + this.responder.sendMetadata(metadata, interceptedMetadata => { + this.processingMetadata = false; + this.nextCall.sendMetadata(interceptedMetadata); + this.processPendingMessage(); + this.processPendingStatus(); + }); + } + sendMessage(message, callback) { + this.processingMessage = true; + if (!this.sentMetadata) { + this.sendMetadata(new metadata_1.Metadata()); + } + this.responder.sendMessage(message, interceptedMessage => { + this.processingMessage = false; + if (this.processingMetadata) { + this.pendingMessage = interceptedMessage; + this.pendingMessageCallback = callback; + } + else { + this.nextCall.sendMessage(interceptedMessage, callback); + } + }); + } + sendStatus(status) { + this.responder.sendStatus(status, interceptedStatus => { + if (this.processingMetadata || this.processingMessage) { + this.pendingStatus = interceptedStatus; + } + else { + this.nextCall.sendStatus(interceptedStatus); + } + }); + } + startRead() { + this.nextCall.startRead(); + } + getPeer() { + return this.nextCall.getPeer(); + } + getDeadline() { + return this.nextCall.getDeadline(); + } + getHost() { + return this.nextCall.getHost(); + } + getAuthContext() { + return this.nextCall.getAuthContext(); + } + getConnectionInfo() { + return this.nextCall.getConnectionInfo(); + } + getMetricsRecorder() { + return this.nextCall.getMetricsRecorder(); + } +} +exports.ServerInterceptingCall = ServerInterceptingCall; +const GRPC_ACCEPT_ENCODING_HEADER = 'grpc-accept-encoding'; +const GRPC_ENCODING_HEADER = 'grpc-encoding'; +const GRPC_MESSAGE_HEADER = 'grpc-message'; +const GRPC_STATUS_HEADER = 'grpc-status'; +const GRPC_TIMEOUT_HEADER = 'grpc-timeout'; +const DEADLINE_REGEX = /(\d{1,8})\s*([HMSmun])/; +const deadlineUnitsToMs = { + H: 3600000, + M: 60000, + S: 1000, + m: 1, + u: 0.001, + n: 0.000001, +}; +const defaultCompressionHeaders = { + // TODO(cjihrig): Remove these encoding headers from the default response + // once compression is integrated. + [GRPC_ACCEPT_ENCODING_HEADER]: 'identity,deflate,gzip', + [GRPC_ENCODING_HEADER]: 'identity', +}; +const defaultResponseHeaders = { + [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, + [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: 'application/grpc+proto', +}; +const defaultResponseOptions = { + waitForTrailers: true, +}; +class BaseServerInterceptingCall { + constructor(stream, headers, callEventTracker, handler, options) { + var _a, _b; + this.stream = stream; + this.callEventTracker = callEventTracker; + this.handler = handler; + this.listener = null; + this.deadlineTimer = null; + this.deadline = Infinity; + this.maxSendMessageSize = constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH; + this.maxReceiveMessageSize = constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; + this.cancelled = false; + this.metadataSent = false; + this.wantTrailers = false; + this.cancelNotified = false; + this.incomingEncoding = 'identity'; + this.readQueue = []; + this.isReadPending = false; + this.receivedHalfClose = false; + this.streamEnded = false; + this.metricsRecorder = new orca_1.PerRequestMetricRecorder(); + this.stream.once('error', (err) => { + /* We need an error handler to avoid uncaught error event exceptions, but + * there is nothing we can reasonably do here. Any error event should + * have a corresponding close event, which handles emitting the cancelled + * event. And the stream is now in a bad state, so we can't reasonably + * expect to be able to send an error over it. */ + }); + this.stream.once('close', () => { + var _a; + trace('Request to method ' + + ((_a = this.handler) === null || _a === void 0 ? void 0 : _a.path) + + ' stream closed with rstCode ' + + this.stream.rstCode); + if (this.callEventTracker && !this.streamEnded) { + this.streamEnded = true; + this.callEventTracker.onStreamEnd(false); + this.callEventTracker.onCallEnd({ + code: constants_1.Status.CANCELLED, + details: 'Stream closed before sending status', + metadata: null, + }); + } + this.notifyOnCancel(); + }); + this.stream.on('data', (data) => { + this.handleDataFrame(data); + }); + this.stream.pause(); + this.stream.on('end', () => { + this.handleEndEvent(); + }); + if ('grpc.max_send_message_length' in options) { + this.maxSendMessageSize = options['grpc.max_send_message_length']; + } + if ('grpc.max_receive_message_length' in options) { + this.maxReceiveMessageSize = options['grpc.max_receive_message_length']; + } + this.host = (_a = headers[':authority']) !== null && _a !== void 0 ? _a : headers.host; + this.decoder = new stream_decoder_1.StreamDecoder(this.maxReceiveMessageSize); + const metadata = metadata_1.Metadata.fromHttp2Headers(headers); + if (logging.isTracerEnabled(TRACER_NAME)) { + trace('Request to ' + + this.handler.path + + ' received headers ' + + JSON.stringify(metadata.toJSON())); + } + const timeoutHeader = metadata.get(GRPC_TIMEOUT_HEADER); + if (timeoutHeader.length > 0) { + this.handleTimeoutHeader(timeoutHeader[0]); + } + const encodingHeader = metadata.get(GRPC_ENCODING_HEADER); + if (encodingHeader.length > 0) { + this.incomingEncoding = encodingHeader[0]; + } + // Remove several headers that should not be propagated to the application + metadata.remove(GRPC_TIMEOUT_HEADER); + metadata.remove(GRPC_ENCODING_HEADER); + metadata.remove(GRPC_ACCEPT_ENCODING_HEADER); + metadata.remove(http2.constants.HTTP2_HEADER_ACCEPT_ENCODING); + metadata.remove(http2.constants.HTTP2_HEADER_TE); + metadata.remove(http2.constants.HTTP2_HEADER_CONTENT_TYPE); + this.metadata = metadata; + const socket = (_b = stream.session) === null || _b === void 0 ? void 0 : _b.socket; + this.connectionInfo = { + localAddress: socket === null || socket === void 0 ? void 0 : socket.localAddress, + localPort: socket === null || socket === void 0 ? void 0 : socket.localPort, + remoteAddress: socket === null || socket === void 0 ? void 0 : socket.remoteAddress, + remotePort: socket === null || socket === void 0 ? void 0 : socket.remotePort + }; + this.shouldSendMetrics = !!options['grpc.server_call_metric_recording']; + } + handleTimeoutHeader(timeoutHeader) { + const match = timeoutHeader.toString().match(DEADLINE_REGEX); + if (match === null) { + const status = { + code: constants_1.Status.INTERNAL, + details: `Invalid ${GRPC_TIMEOUT_HEADER} value "${timeoutHeader}"`, + metadata: null, + }; + // Wait for the constructor to complete before sending the error. + process.nextTick(() => { + this.sendStatus(status); + }); + return; + } + const timeout = (+match[1] * deadlineUnitsToMs[match[2]]) | 0; + const now = new Date(); + this.deadline = now.setMilliseconds(now.getMilliseconds() + timeout); + this.deadlineTimer = setTimeout(() => { + const status = { + code: constants_1.Status.DEADLINE_EXCEEDED, + details: 'Deadline exceeded', + metadata: null, + }; + this.sendStatus(status); + }, timeout); + } + checkCancelled() { + /* In some cases the stream can become destroyed before the close event + * fires. That creates a race condition that this check works around */ + if (!this.cancelled && (this.stream.destroyed || this.stream.closed)) { + this.notifyOnCancel(); + this.cancelled = true; + } + return this.cancelled; + } + notifyOnCancel() { + if (this.cancelNotified) { + return; + } + this.cancelNotified = true; + this.cancelled = true; + process.nextTick(() => { + var _a; + (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onCancel(); + }); + if (this.deadlineTimer) { + clearTimeout(this.deadlineTimer); + } + // Flush incoming data frames + this.stream.resume(); + } + /** + * A server handler can start sending messages without explicitly sending + * metadata. In that case, we need to send headers before sending any + * messages. This function does that if necessary. + */ + maybeSendMetadata() { + if (!this.metadataSent) { + this.sendMetadata(new metadata_1.Metadata()); + } + } + /** + * Serialize a message to a length-delimited byte string. + * @param value + * @returns + */ + serializeMessage(value) { + const messageBuffer = this.handler.serialize(value); + const byteLength = messageBuffer.byteLength; + const output = Buffer.allocUnsafe(byteLength + 5); + /* Note: response compression is currently not supported, so this + * compressed bit is always 0. */ + output.writeUInt8(0, 0); + output.writeUInt32BE(byteLength, 1); + messageBuffer.copy(output, 5); + return output; + } + decompressMessage(message, encoding) { + const messageContents = message.subarray(5); + if (encoding === 'identity') { + return messageContents; + } + else if (encoding === 'deflate' || encoding === 'gzip') { + let decompresser; + if (encoding === 'deflate') { + decompresser = zlib.createInflate(); + } + else { + decompresser = zlib.createGunzip(); + } + return new Promise((resolve, reject) => { + let totalLength = 0; + const messageParts = []; + decompresser.on('data', (chunk) => { + messageParts.push(chunk); + totalLength += chunk.byteLength; + if (this.maxReceiveMessageSize !== -1 && totalLength > this.maxReceiveMessageSize) { + decompresser.destroy(); + reject({ + code: constants_1.Status.RESOURCE_EXHAUSTED, + details: `Received message that decompresses to a size larger than ${this.maxReceiveMessageSize}` + }); + } + }); + decompresser.on('end', () => { + resolve(Buffer.concat(messageParts)); + }); + decompresser.write(messageContents); + decompresser.end(); + }); + } + else { + return Promise.reject({ + code: constants_1.Status.UNIMPLEMENTED, + details: `Received message compressed with unsupported encoding "${encoding}"`, + }); + } + } + async decompressAndMaybePush(queueEntry) { + if (queueEntry.type !== 'COMPRESSED') { + throw new Error(`Invalid queue entry type: ${queueEntry.type}`); + } + const compressed = queueEntry.compressedMessage.readUInt8(0) === 1; + const compressedMessageEncoding = compressed + ? this.incomingEncoding + : 'identity'; + let decompressedMessage; + try { + decompressedMessage = await this.decompressMessage(queueEntry.compressedMessage, compressedMessageEncoding); + } + catch (err) { + this.sendStatus(err); + return; + } + try { + queueEntry.parsedMessage = this.handler.deserialize(decompressedMessage); + } + catch (err) { + this.sendStatus({ + code: constants_1.Status.INTERNAL, + details: `Error deserializing request: ${err.message}`, + }); + return; + } + queueEntry.type = 'READABLE'; + this.maybePushNextMessage(); + } + maybePushNextMessage() { + if (this.listener && + this.isReadPending && + this.readQueue.length > 0 && + this.readQueue[0].type !== 'COMPRESSED') { + this.isReadPending = false; + const nextQueueEntry = this.readQueue.shift(); + if (nextQueueEntry.type === 'READABLE') { + this.listener.onReceiveMessage(nextQueueEntry.parsedMessage); + } + else { + // nextQueueEntry.type === 'HALF_CLOSE' + this.listener.onReceiveHalfClose(); + } + } + } + handleDataFrame(data) { + var _a; + if (this.checkCancelled()) { + return; + } + trace('Request to ' + + this.handler.path + + ' received data frame of size ' + + data.length); + let rawMessages; + try { + rawMessages = this.decoder.write(data); + } + catch (e) { + this.sendStatus({ code: constants_1.Status.RESOURCE_EXHAUSTED, details: e.message }); + return; + } + for (const messageBytes of rawMessages) { + this.stream.pause(); + const queueEntry = { + type: 'COMPRESSED', + compressedMessage: messageBytes, + parsedMessage: null, + }; + this.readQueue.push(queueEntry); + this.decompressAndMaybePush(queueEntry); + (_a = this.callEventTracker) === null || _a === void 0 ? void 0 : _a.addMessageReceived(); + } + } + handleEndEvent() { + this.readQueue.push({ + type: 'HALF_CLOSE', + compressedMessage: null, + parsedMessage: null, + }); + this.receivedHalfClose = true; + this.maybePushNextMessage(); + } + start(listener) { + trace('Request to ' + this.handler.path + ' start called'); + if (this.checkCancelled()) { + return; + } + this.listener = listener; + listener.onReceiveMetadata(this.metadata); + } + sendMetadata(metadata) { + if (this.checkCancelled()) { + return; + } + if (this.metadataSent) { + return; + } + this.metadataSent = true; + const custom = metadata ? metadata.toHttp2Headers() : null; + const headers = Object.assign(Object.assign(Object.assign({}, defaultResponseHeaders), defaultCompressionHeaders), custom); + this.stream.respond(headers, defaultResponseOptions); + } + sendMessage(message, callback) { + if (this.checkCancelled()) { + return; + } + let response; + try { + response = this.serializeMessage(message); + } + catch (e) { + this.sendStatus({ + code: constants_1.Status.INTERNAL, + details: `Error serializing response: ${(0, error_1.getErrorMessage)(e)}`, + metadata: null, + }); + return; + } + if (this.maxSendMessageSize !== -1 && + response.length - 5 > this.maxSendMessageSize) { + this.sendStatus({ + code: constants_1.Status.RESOURCE_EXHAUSTED, + details: `Sent message larger than max (${response.length} vs. ${this.maxSendMessageSize})`, + metadata: null, + }); + return; + } + this.maybeSendMetadata(); + trace('Request to ' + + this.handler.path + + ' sent data frame of size ' + + response.length); + this.stream.write(response, error => { + var _a; + if (error) { + this.sendStatus({ + code: constants_1.Status.INTERNAL, + details: `Error writing message: ${(0, error_1.getErrorMessage)(error)}`, + metadata: null, + }); + return; + } + (_a = this.callEventTracker) === null || _a === void 0 ? void 0 : _a.addMessageSent(); + callback(); + }); + } + sendStatus(status) { + var _a, _b, _c; + if (this.checkCancelled()) { + return; + } + trace('Request to method ' + + ((_a = this.handler) === null || _a === void 0 ? void 0 : _a.path) + + ' ended with status code: ' + + constants_1.Status[status.code] + + ' details: ' + + status.details); + const statusMetadata = (_c = (_b = status.metadata) === null || _b === void 0 ? void 0 : _b.clone()) !== null && _c !== void 0 ? _c : new metadata_1.Metadata(); + if (this.shouldSendMetrics) { + statusMetadata.set(orca_1.GRPC_METRICS_HEADER, this.metricsRecorder.serialize()); + } + if (this.metadataSent) { + if (!this.wantTrailers) { + this.wantTrailers = true; + this.stream.once('wantTrailers', () => { + if (this.callEventTracker && !this.streamEnded) { + this.streamEnded = true; + this.callEventTracker.onStreamEnd(true); + this.callEventTracker.onCallEnd(status); + } + const trailersToSend = Object.assign({ [GRPC_STATUS_HEADER]: status.code, [GRPC_MESSAGE_HEADER]: encodeURI(status.details) }, statusMetadata.toHttp2Headers()); + this.stream.sendTrailers(trailersToSend); + this.notifyOnCancel(); + }); + this.stream.end(); + } + else { + this.notifyOnCancel(); + } + } + else { + if (this.callEventTracker && !this.streamEnded) { + this.streamEnded = true; + this.callEventTracker.onStreamEnd(true); + this.callEventTracker.onCallEnd(status); + } + // Trailers-only response + const trailersToSend = Object.assign(Object.assign({ [GRPC_STATUS_HEADER]: status.code, [GRPC_MESSAGE_HEADER]: encodeURI(status.details) }, defaultResponseHeaders), statusMetadata.toHttp2Headers()); + this.stream.respond(trailersToSend, { endStream: true }); + this.notifyOnCancel(); + } + } + startRead() { + trace('Request to ' + this.handler.path + ' startRead called'); + if (this.checkCancelled()) { + return; + } + this.isReadPending = true; + if (this.readQueue.length === 0) { + if (!this.receivedHalfClose) { + this.stream.resume(); + } + } + else { + this.maybePushNextMessage(); + } + } + getPeer() { + var _a; + const socket = (_a = this.stream.session) === null || _a === void 0 ? void 0 : _a.socket; + if (socket === null || socket === void 0 ? void 0 : socket.remoteAddress) { + if (socket.remotePort) { + return `${socket.remoteAddress}:${socket.remotePort}`; + } + else { + return socket.remoteAddress; + } + } + else { + return 'unknown'; + } + } + getDeadline() { + return this.deadline; + } + getHost() { + return this.host; + } + getAuthContext() { + var _a; + if (((_a = this.stream.session) === null || _a === void 0 ? void 0 : _a.socket) instanceof tls_1.TLSSocket) { + const peerCertificate = this.stream.session.socket.getPeerCertificate(); + return { + transportSecurityType: 'ssl', + sslPeerCertificate: peerCertificate.raw ? peerCertificate : undefined + }; + } + else { + return {}; + } + } + getConnectionInfo() { + return this.connectionInfo; + } + getMetricsRecorder() { + return this.metricsRecorder; + } +} +exports.BaseServerInterceptingCall = BaseServerInterceptingCall; +function getServerInterceptingCall(interceptors, stream, headers, callEventTracker, handler, options) { + const methodDefinition = { + path: handler.path, + requestStream: handler.type === 'clientStream' || handler.type === 'bidi', + responseStream: handler.type === 'serverStream' || handler.type === 'bidi', + requestDeserialize: handler.deserialize, + responseSerialize: handler.serialize, + }; + const baseCall = new BaseServerInterceptingCall(stream, headers, callEventTracker, handler, options); + return interceptors.reduce((call, interceptor) => { + return interceptor(methodDefinition, call); + }, baseCall); +} +//# sourceMappingURL=server-interceptors.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/server-interceptors.js.map b/node_modules/@grpc/grpc-js/build/src/server-interceptors.js.map new file mode 100644 index 0000000..e0e834d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server-interceptors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"server-interceptors.js","sourceRoot":"","sources":["../../src/server-interceptors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAoGH,oEAOC;AAw5BD,8DA4BC;AA3hCD,yCAAsC;AAItC,2CAKqB;AACrB,+BAA+B;AAC/B,mCAA0C;AAC1C,6BAA6B;AAC7B,qDAAiD;AAEjD,qCAAqC;AAErC,6BAAgC;AAChC,iCAAuE;AAEvE,MAAM,WAAW,GAAG,aAAa,CAAC;AAElC,SAAS,KAAK,CAAC,IAAY;IACzB,OAAO,CAAC,KAAK,CAAC,wBAAY,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;AACvD,CAAC;AA4BD,MAAa,qBAAqB;IAAlC;QACU,aAAQ,GAAuC,SAAS,CAAC;QACzD,YAAO,GAAsC,SAAS,CAAC;QACvD,cAAS,GAAwC,SAAS,CAAC;QAC3D,WAAM,GAAqC,SAAS,CAAC;IA8B/D,CAAC;IA5BC,qBAAqB,CAAC,iBAAyC;QAC7D,IAAI,CAAC,QAAQ,GAAG,iBAAiB,CAAC;QAClC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,oBAAoB,CAAC,gBAAuC;QAC1D,IAAI,CAAC,OAAO,GAAG,gBAAgB,CAAC;QAChC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,sBAAsB,CAAC,kBAA2C;QAChE,IAAI,CAA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I,KAAK,cAAc,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM;QAC1E,kBAAkB,EAAE,OAAO,CAAC,WAAW;QACvC,iBAAiB,EAAE,OAAO,CAAC,SAAS;KACrC,CAAC;IACF,MAAM,QAAQ,GAAG,IAAI,0BAA0B,CAC7C,MAAM,EACN,OAAO,EACP,gBAAgB,EAChB,OAAO,EACP,OAAO,CACR,CAAC;IACF,OAAO,YAAY,CAAC,MAAM,CACxB,CAAC,IAAqC,EAAE,WAA8B,EAAE,EAAE;QACxE,OAAO,WAAW,CAAC,gBAAgB,EAAE,IAAI,CAAC,CAAC;IAC7C,CAAC,EACD,QAAQ,CACT,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/server.d.ts b/node_modules/@grpc/grpc-js/build/src/server.d.ts new file mode 100644 index 0000000..a1f821e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server.d.ts @@ -0,0 +1,140 @@ +import { Deserialize, Serialize, ServiceDefinition } from './make-client'; +import { HandleCall } from './server-call'; +import { ServerCredentials } from './server-credentials'; +import { ChannelOptions } from './channel-options'; +import { SubchannelAddress } from './subchannel-address'; +import { ServerRef, SocketRef } from './channelz'; +import { ServerInterceptor } from './server-interceptors'; +import { Duplex } from 'stream'; +export type UntypedHandleCall = HandleCall; +export interface UntypedServiceImplementation { + [name: string]: UntypedHandleCall; +} +export interface ServerOptions extends ChannelOptions { + interceptors?: ServerInterceptor[]; +} +export interface ConnectionInjector { + injectConnection(connection: Duplex): void; + drain(graceTimeMs: number): void; + destroy(): void; +} +export declare class Server { + private boundPorts; + private http2Servers; + private sessionIdleTimeouts; + private handlers; + private sessions; + /** + * This field only exists to ensure that the start method throws an error if + * it is called twice, as it did previously. + */ + private started; + private shutdown; + private options; + private serverAddressString; + private readonly channelzEnabled; + private channelzRef; + private channelzTrace; + private callTracker; + private listenerChildrenTracker; + private sessionChildrenTracker; + private readonly maxConnectionAgeMs; + private readonly maxConnectionAgeGraceMs; + private readonly keepaliveTimeMs; + private readonly keepaliveTimeoutMs; + private readonly sessionIdleTimeout; + private readonly interceptors; + /** + * Options that will be used to construct all Http2Server instances for this + * Server. + */ + private commonServerOptions; + constructor(options?: ServerOptions); + private getChannelzInfo; + private getChannelzSessionInfo; + private trace; + private keepaliveTrace; + addProtoService(): never; + addService(service: ServiceDefinition, implementation: UntypedServiceImplementation): void; + removeService(service: ServiceDefinition): void; + bind(port: string, creds: ServerCredentials): never; + /** + * This API is experimental, so API stability is not guaranteed across minor versions. + * @param boundAddress + * @returns + */ + protected experimentalRegisterListenerToChannelz(boundAddress: SubchannelAddress): SocketRef; + protected experimentalUnregisterListenerFromChannelz(channelzRef: SocketRef): void; + private createHttp2Server; + private bindOneAddress; + private bindManyPorts; + private bindAddressList; + private resolvePort; + private bindPort; + private normalizePort; + bindAsync(port: string, creds: ServerCredentials, callback: (error: Error | null, port: number) => void): void; + private registerInjectorToChannelz; + /** + * This API is experimental, so API stability is not guaranteed across minor versions. + * @param credentials + * @param channelzRef + * @returns + */ + protected experimentalCreateConnectionInjectorWithChannelzRef(credentials: ServerCredentials, channelzRef: SocketRef, ownsChannelzRef?: boolean): { + injectConnection: (connection: Duplex) => void; + drain: (graceTimeMs: number) => void; + destroy: () => void; + }; + createConnectionInjector(credentials: ServerCredentials): ConnectionInjector; + private closeServer; + private closeSession; + private completeUnbind; + /** + * Unbind a previously bound port, or cancel an in-progress bindAsync + * operation. If port 0 was bound, only the actual bound port can be + * unbound. For example, if bindAsync was called with "localhost:0" and the + * bound port result was 54321, it can be unbound as "localhost:54321". + * @param port + */ + unbind(port: string): void; + /** + * Gracefully close all connections associated with a previously bound port. + * After the grace time, forcefully close all remaining open connections. + * + * If port 0 was bound, only the actual bound port can be + * drained. For example, if bindAsync was called with "localhost:0" and the + * bound port result was 54321, it can be drained as "localhost:54321". + * @param port + * @param graceTimeMs + * @returns + */ + drain(port: string, graceTimeMs: number): void; + forceShutdown(): void; + register(name: string, handler: HandleCall, serialize: Serialize, deserialize: Deserialize, type: string): boolean; + unregister(name: string): boolean; + /** + * @deprecated No longer needed as of version 1.10.x + */ + start(): void; + tryShutdown(callback: (error?: Error) => void): void; + addHttp2Port(): never; + /** + * Get the channelz reference object for this server. The returned value is + * garbage if channelz is disabled for this server. + * @returns + */ + getChannelzRef(): ServerRef; + private _verifyContentType; + private _retrieveHandler; + private _respondWithError; + private _channelzHandler; + private _streamHandler; + private _runHandlerForCall; + private _setupHandlers; + private _sessionHandler; + private _channelzSessionHandler; + private enableIdleTimeout; + private onIdleTimeout; + private onStreamOpened; + private onStreamClose; +} diff --git a/node_modules/@grpc/grpc-js/build/src/server.js b/node_modules/@grpc/grpc-js/build/src/server.js new file mode 100644 index 0000000..98f5176 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server.js @@ -0,0 +1,1608 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; +var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + 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 _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(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 (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Server = void 0; +const http2 = require("http2"); +const util = require("util"); +const constants_1 = require("./constants"); +const server_call_1 = require("./server-call"); +const server_credentials_1 = require("./server-credentials"); +const resolver_1 = require("./resolver"); +const logging = require("./logging"); +const subchannel_address_1 = require("./subchannel-address"); +const uri_parser_1 = require("./uri-parser"); +const channelz_1 = require("./channelz"); +const server_interceptors_1 = require("./server-interceptors"); +const UNLIMITED_CONNECTION_AGE_MS = ~(1 << 31); +const KEEPALIVE_MAX_TIME_MS = ~(1 << 31); +const KEEPALIVE_TIMEOUT_MS = 20000; +const MAX_CONNECTION_IDLE_MS = ~(1 << 31); +const { HTTP2_HEADER_PATH } = http2.constants; +const TRACER_NAME = 'server'; +const kMaxAge = Buffer.from('max_age'); +function serverCallTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, 'server_call', text); +} +function noop() { } +/** + * Decorator to wrap a class method with util.deprecate + * @param message The message to output if the deprecated method is called + * @returns + */ +function deprecate(message) { + return function (target, context) { + return util.deprecate(target, message); + }; +} +function getUnimplementedStatusResponse(methodName) { + return { + code: constants_1.Status.UNIMPLEMENTED, + details: `The server does not implement the method ${methodName}`, + }; +} +function getDefaultHandler(handlerType, methodName) { + const unimplementedStatusResponse = getUnimplementedStatusResponse(methodName); + switch (handlerType) { + case 'unary': + return (call, callback) => { + callback(unimplementedStatusResponse, null); + }; + case 'clientStream': + return (call, callback) => { + callback(unimplementedStatusResponse, null); + }; + case 'serverStream': + return (call) => { + call.emit('error', unimplementedStatusResponse); + }; + case 'bidi': + return (call) => { + call.emit('error', unimplementedStatusResponse); + }; + default: + throw new Error(`Invalid handlerType ${handlerType}`); + } +} +let Server = (() => { + var _a; + let _instanceExtraInitializers = []; + let _start_decorators; + return _a = class Server { + constructor(options) { + var _b, _c, _d, _e, _f, _g; + this.boundPorts = (__runInitializers(this, _instanceExtraInitializers), new Map()); + this.http2Servers = new Map(); + this.sessionIdleTimeouts = new Map(); + this.handlers = new Map(); + this.sessions = new Map(); + /** + * This field only exists to ensure that the start method throws an error if + * it is called twice, as it did previously. + */ + this.started = false; + this.shutdown = false; + this.serverAddressString = 'null'; + // Channelz Info + this.channelzEnabled = true; + this.options = options !== null && options !== void 0 ? options : {}; + if (this.options['grpc.enable_channelz'] === 0) { + this.channelzEnabled = false; + this.channelzTrace = new channelz_1.ChannelzTraceStub(); + this.callTracker = new channelz_1.ChannelzCallTrackerStub(); + this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); + this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); + } + else { + this.channelzTrace = new channelz_1.ChannelzTrace(); + this.callTracker = new channelz_1.ChannelzCallTracker(); + this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTracker(); + this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTracker(); + } + this.channelzRef = (0, channelz_1.registerChannelzServer)('server', () => this.getChannelzInfo(), this.channelzEnabled); + this.channelzTrace.addTrace('CT_INFO', 'Server created'); + this.maxConnectionAgeMs = + (_b = this.options['grpc.max_connection_age_ms']) !== null && _b !== void 0 ? _b : UNLIMITED_CONNECTION_AGE_MS; + this.maxConnectionAgeGraceMs = + (_c = this.options['grpc.max_connection_age_grace_ms']) !== null && _c !== void 0 ? _c : UNLIMITED_CONNECTION_AGE_MS; + this.keepaliveTimeMs = + (_d = this.options['grpc.keepalive_time_ms']) !== null && _d !== void 0 ? _d : KEEPALIVE_MAX_TIME_MS; + this.keepaliveTimeoutMs = + (_e = this.options['grpc.keepalive_timeout_ms']) !== null && _e !== void 0 ? _e : KEEPALIVE_TIMEOUT_MS; + this.sessionIdleTimeout = + (_f = this.options['grpc.max_connection_idle_ms']) !== null && _f !== void 0 ? _f : MAX_CONNECTION_IDLE_MS; + this.commonServerOptions = { + maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER, + }; + if ('grpc-node.max_session_memory' in this.options) { + this.commonServerOptions.maxSessionMemory = + this.options['grpc-node.max_session_memory']; + } + else { + /* By default, set a very large max session memory limit, to effectively + * disable enforcement of the limit. Some testing indicates that Node's + * behavior degrades badly when this limit is reached, so we solve that + * by disabling the check entirely. */ + this.commonServerOptions.maxSessionMemory = Number.MAX_SAFE_INTEGER; + } + if ('grpc.max_concurrent_streams' in this.options) { + this.commonServerOptions.settings = { + maxConcurrentStreams: this.options['grpc.max_concurrent_streams'], + }; + } + this.interceptors = (_g = this.options.interceptors) !== null && _g !== void 0 ? _g : []; + this.trace('Server constructed'); + } + getChannelzInfo() { + return { + trace: this.channelzTrace, + callTracker: this.callTracker, + listenerChildren: this.listenerChildrenTracker.getChildLists(), + sessionChildren: this.sessionChildrenTracker.getChildLists(), + }; + } + getChannelzSessionInfo(session) { + var _b, _c, _d; + const sessionInfo = this.sessions.get(session); + const sessionSocket = session.socket; + const remoteAddress = sessionSocket.remoteAddress + ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.remoteAddress, sessionSocket.remotePort) + : null; + const localAddress = sessionSocket.localAddress + ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.localAddress, sessionSocket.localPort) + : null; + let tlsInfo; + if (session.encrypted) { + const tlsSocket = sessionSocket; + const cipherInfo = tlsSocket.getCipher(); + const certificate = tlsSocket.getCertificate(); + const peerCertificate = tlsSocket.getPeerCertificate(); + tlsInfo = { + cipherSuiteStandardName: (_b = cipherInfo.standardName) !== null && _b !== void 0 ? _b : null, + cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, + localCertificate: certificate && 'raw' in certificate ? certificate.raw : null, + remoteCertificate: peerCertificate && 'raw' in peerCertificate + ? peerCertificate.raw + : null, + }; + } + else { + tlsInfo = null; + } + const socketInfo = { + remoteAddress: remoteAddress, + localAddress: localAddress, + security: tlsInfo, + remoteName: null, + streamsStarted: sessionInfo.streamTracker.callsStarted, + streamsSucceeded: sessionInfo.streamTracker.callsSucceeded, + streamsFailed: sessionInfo.streamTracker.callsFailed, + messagesSent: sessionInfo.messagesSent, + messagesReceived: sessionInfo.messagesReceived, + keepAlivesSent: sessionInfo.keepAlivesSent, + lastLocalStreamCreatedTimestamp: null, + lastRemoteStreamCreatedTimestamp: sessionInfo.streamTracker.lastCallStartedTimestamp, + lastMessageSentTimestamp: sessionInfo.lastMessageSentTimestamp, + lastMessageReceivedTimestamp: sessionInfo.lastMessageReceivedTimestamp, + localFlowControlWindow: (_c = session.state.localWindowSize) !== null && _c !== void 0 ? _c : null, + remoteFlowControlWindow: (_d = session.state.remoteWindowSize) !== null && _d !== void 0 ? _d : null, + }; + return socketInfo; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '(' + this.channelzRef.id + ') ' + text); + } + keepaliveTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, 'keepalive', '(' + this.channelzRef.id + ') ' + text); + } + addProtoService() { + throw new Error('Not implemented. Use addService() instead'); + } + addService(service, implementation) { + if (service === null || + typeof service !== 'object' || + implementation === null || + typeof implementation !== 'object') { + throw new Error('addService() requires two objects as arguments'); + } + const serviceKeys = Object.keys(service); + if (serviceKeys.length === 0) { + throw new Error('Cannot add an empty service to a server'); + } + serviceKeys.forEach(name => { + const attrs = service[name]; + let methodType; + if (attrs.requestStream) { + if (attrs.responseStream) { + methodType = 'bidi'; + } + else { + methodType = 'clientStream'; + } + } + else { + if (attrs.responseStream) { + methodType = 'serverStream'; + } + else { + methodType = 'unary'; + } + } + let implFn = implementation[name]; + let impl; + if (implFn === undefined && typeof attrs.originalName === 'string') { + implFn = implementation[attrs.originalName]; + } + if (implFn !== undefined) { + impl = implFn.bind(implementation); + } + else { + impl = getDefaultHandler(methodType, name); + } + const success = this.register(attrs.path, impl, attrs.responseSerialize, attrs.requestDeserialize, methodType); + if (success === false) { + throw new Error(`Method handler for ${attrs.path} already provided.`); + } + }); + } + removeService(service) { + if (service === null || typeof service !== 'object') { + throw new Error('removeService() requires object as argument'); + } + const serviceKeys = Object.keys(service); + serviceKeys.forEach(name => { + const attrs = service[name]; + this.unregister(attrs.path); + }); + } + bind(port, creds) { + throw new Error('Not implemented. Use bindAsync() instead'); + } + /** + * This API is experimental, so API stability is not guaranteed across minor versions. + * @param boundAddress + * @returns + */ + experimentalRegisterListenerToChannelz(boundAddress) { + return (0, channelz_1.registerChannelzSocket)((0, subchannel_address_1.subchannelAddressToString)(boundAddress), () => { + return { + localAddress: boundAddress, + remoteAddress: null, + security: null, + remoteName: null, + streamsStarted: 0, + streamsSucceeded: 0, + streamsFailed: 0, + messagesSent: 0, + messagesReceived: 0, + keepAlivesSent: 0, + lastLocalStreamCreatedTimestamp: null, + lastRemoteStreamCreatedTimestamp: null, + lastMessageSentTimestamp: null, + lastMessageReceivedTimestamp: null, + localFlowControlWindow: null, + remoteFlowControlWindow: null, + }; + }, this.channelzEnabled); + } + experimentalUnregisterListenerFromChannelz(channelzRef) { + (0, channelz_1.unregisterChannelzRef)(channelzRef); + } + createHttp2Server(credentials) { + let http2Server; + if (credentials._isSecure()) { + const constructorOptions = credentials._getConstructorOptions(); + const contextOptions = credentials._getSecureContextOptions(); + const secureServerOptions = Object.assign(Object.assign(Object.assign(Object.assign({}, this.commonServerOptions), constructorOptions), contextOptions), { enableTrace: this.options['grpc-node.tls_enable_trace'] === 1 }); + let areCredentialsValid = contextOptions !== null; + this.trace('Initial credentials valid: ' + areCredentialsValid); + http2Server = http2.createSecureServer(secureServerOptions); + http2Server.prependListener('connection', (socket) => { + if (!areCredentialsValid) { + this.trace('Dropped connection from ' + JSON.stringify(socket.address()) + ' due to unloaded credentials'); + socket.destroy(); + } + }); + http2Server.on('secureConnection', (socket) => { + /* These errors need to be handled by the user of Http2SecureServer, + * according to https://github.com/nodejs/node/issues/35824 */ + socket.on('error', (e) => { + this.trace('An incoming TLS connection closed with error: ' + e.message); + }); + }); + const credsWatcher = options => { + if (options) { + const secureServer = http2Server; + try { + secureServer.setSecureContext(options); + } + catch (e) { + logging.log(constants_1.LogVerbosity.ERROR, 'Failed to set secure context with error ' + e.message); + options = null; + } + } + areCredentialsValid = options !== null; + this.trace('Post-update credentials valid: ' + areCredentialsValid); + }; + credentials._addWatcher(credsWatcher); + http2Server.on('close', () => { + credentials._removeWatcher(credsWatcher); + }); + } + else { + http2Server = http2.createServer(this.commonServerOptions); + } + http2Server.setTimeout(0, noop); + this._setupHandlers(http2Server, credentials._getInterceptors()); + return http2Server; + } + bindOneAddress(address, boundPortObject) { + this.trace('Attempting to bind ' + (0, subchannel_address_1.subchannelAddressToString)(address)); + const http2Server = this.createHttp2Server(boundPortObject.credentials); + return new Promise((resolve, reject) => { + const onError = (err) => { + this.trace('Failed to bind ' + + (0, subchannel_address_1.subchannelAddressToString)(address) + + ' with error ' + + err.message); + resolve({ + port: 'port' in address ? address.port : 1, + error: err.message, + }); + }; + http2Server.once('error', onError); + http2Server.listen(address, () => { + const boundAddress = http2Server.address(); + let boundSubchannelAddress; + if (typeof boundAddress === 'string') { + boundSubchannelAddress = { + path: boundAddress, + }; + } + else { + boundSubchannelAddress = { + host: boundAddress.address, + port: boundAddress.port, + }; + } + const channelzRef = this.experimentalRegisterListenerToChannelz(boundSubchannelAddress); + this.listenerChildrenTracker.refChild(channelzRef); + this.http2Servers.set(http2Server, { + channelzRef: channelzRef, + sessions: new Set(), + ownsChannelzRef: true + }); + boundPortObject.listeningServers.add(http2Server); + this.trace('Successfully bound ' + + (0, subchannel_address_1.subchannelAddressToString)(boundSubchannelAddress)); + resolve({ + port: 'port' in boundSubchannelAddress ? boundSubchannelAddress.port : 1, + }); + http2Server.removeListener('error', onError); + }); + }); + } + async bindManyPorts(addressList, boundPortObject) { + if (addressList.length === 0) { + return { + count: 0, + port: 0, + errors: [], + }; + } + if ((0, subchannel_address_1.isTcpSubchannelAddress)(addressList[0]) && addressList[0].port === 0) { + /* If binding to port 0, first try to bind the first address, then bind + * the rest of the address list to the specific port that it binds. */ + const firstAddressResult = await this.bindOneAddress(addressList[0], boundPortObject); + if (firstAddressResult.error) { + /* If the first address fails to bind, try the same operation starting + * from the second item in the list. */ + const restAddressResult = await this.bindManyPorts(addressList.slice(1), boundPortObject); + return Object.assign(Object.assign({}, restAddressResult), { errors: [firstAddressResult.error, ...restAddressResult.errors] }); + } + else { + const restAddresses = addressList + .slice(1) + .map(address => (0, subchannel_address_1.isTcpSubchannelAddress)(address) + ? { host: address.host, port: firstAddressResult.port } + : address); + const restAddressResult = await Promise.all(restAddresses.map(address => this.bindOneAddress(address, boundPortObject))); + const allResults = [firstAddressResult, ...restAddressResult]; + return { + count: allResults.filter(result => result.error === undefined).length, + port: firstAddressResult.port, + errors: allResults + .filter(result => result.error) + .map(result => result.error), + }; + } + } + else { + const allResults = await Promise.all(addressList.map(address => this.bindOneAddress(address, boundPortObject))); + return { + count: allResults.filter(result => result.error === undefined).length, + port: allResults[0].port, + errors: allResults + .filter(result => result.error) + .map(result => result.error), + }; + } + } + async bindAddressList(addressList, boundPortObject) { + const bindResult = await this.bindManyPorts(addressList, boundPortObject); + if (bindResult.count > 0) { + if (bindResult.count < addressList.length) { + logging.log(constants_1.LogVerbosity.INFO, `WARNING Only ${bindResult.count} addresses added out of total ${addressList.length} resolved`); + } + return bindResult.port; + } + else { + const errorString = `No address added out of total ${addressList.length} resolved`; + logging.log(constants_1.LogVerbosity.ERROR, errorString); + throw new Error(`${errorString} errors: [${bindResult.errors.join(',')}]`); + } + } + resolvePort(port) { + return new Promise((resolve, reject) => { + let seenResolution = false; + const resolverListener = (endpointList, attributes, serviceConfig, resolutionNote) => { + if (seenResolution) { + return true; + } + seenResolution = true; + if (!endpointList.ok) { + reject(new Error(endpointList.error.details)); + return true; + } + const addressList = [].concat(...endpointList.value.map(endpoint => endpoint.addresses)); + if (addressList.length === 0) { + reject(new Error(`No addresses resolved for port ${port}`)); + return true; + } + resolve(addressList); + return true; + }; + const resolver = (0, resolver_1.createResolver)(port, resolverListener, this.options); + resolver.updateResolution(); + }); + } + async bindPort(port, boundPortObject) { + const addressList = await this.resolvePort(port); + if (boundPortObject.cancelled) { + this.completeUnbind(boundPortObject); + throw new Error('bindAsync operation cancelled by unbind call'); + } + const portNumber = await this.bindAddressList(addressList, boundPortObject); + if (boundPortObject.cancelled) { + this.completeUnbind(boundPortObject); + throw new Error('bindAsync operation cancelled by unbind call'); + } + return portNumber; + } + normalizePort(port) { + const initialPortUri = (0, uri_parser_1.parseUri)(port); + if (initialPortUri === null) { + throw new Error(`Could not parse port "${port}"`); + } + const portUri = (0, resolver_1.mapUriDefaultScheme)(initialPortUri); + if (portUri === null) { + throw new Error(`Could not get a default scheme for port "${port}"`); + } + return portUri; + } + bindAsync(port, creds, callback) { + if (this.shutdown) { + throw new Error('bindAsync called after shutdown'); + } + if (typeof port !== 'string') { + throw new TypeError('port must be a string'); + } + if (creds === null || !(creds instanceof server_credentials_1.ServerCredentials)) { + throw new TypeError('creds must be a ServerCredentials object'); + } + if (typeof callback !== 'function') { + throw new TypeError('callback must be a function'); + } + this.trace('bindAsync port=' + port); + const portUri = this.normalizePort(port); + const deferredCallback = (error, port) => { + process.nextTick(() => callback(error, port)); + }; + /* First, if this port is already bound or that bind operation is in + * progress, use that result. */ + let boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); + if (boundPortObject) { + if (!creds._equals(boundPortObject.credentials)) { + deferredCallback(new Error(`${port} already bound with incompatible credentials`), 0); + return; + } + /* If that operation has previously been cancelled by an unbind call, + * uncancel it. */ + boundPortObject.cancelled = false; + if (boundPortObject.completionPromise) { + boundPortObject.completionPromise.then(portNum => callback(null, portNum), error => callback(error, 0)); + } + else { + deferredCallback(null, boundPortObject.portNumber); + } + return; + } + boundPortObject = { + mapKey: (0, uri_parser_1.uriToString)(portUri), + originalUri: portUri, + completionPromise: null, + cancelled: false, + portNumber: 0, + credentials: creds, + listeningServers: new Set(), + }; + const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); + const completionPromise = this.bindPort(portUri, boundPortObject); + boundPortObject.completionPromise = completionPromise; + /* If the port number is 0, defer populating the map entry until after the + * bind operation completes and we have a specific port number. Otherwise, + * populate it immediately. */ + if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { + completionPromise.then(portNum => { + const finalUri = { + scheme: portUri.scheme, + authority: portUri.authority, + path: (0, uri_parser_1.combineHostPort)({ host: splitPort.host, port: portNum }), + }; + boundPortObject.mapKey = (0, uri_parser_1.uriToString)(finalUri); + boundPortObject.completionPromise = null; + boundPortObject.portNumber = portNum; + this.boundPorts.set(boundPortObject.mapKey, boundPortObject); + callback(null, portNum); + }, error => { + callback(error, 0); + }); + } + else { + this.boundPorts.set(boundPortObject.mapKey, boundPortObject); + completionPromise.then(portNum => { + boundPortObject.completionPromise = null; + boundPortObject.portNumber = portNum; + callback(null, portNum); + }, error => { + callback(error, 0); + }); + } + } + registerInjectorToChannelz() { + return (0, channelz_1.registerChannelzSocket)('injector', () => { + return { + localAddress: null, + remoteAddress: null, + security: null, + remoteName: null, + streamsStarted: 0, + streamsSucceeded: 0, + streamsFailed: 0, + messagesSent: 0, + messagesReceived: 0, + keepAlivesSent: 0, + lastLocalStreamCreatedTimestamp: null, + lastRemoteStreamCreatedTimestamp: null, + lastMessageSentTimestamp: null, + lastMessageReceivedTimestamp: null, + localFlowControlWindow: null, + remoteFlowControlWindow: null, + }; + }, this.channelzEnabled); + } + /** + * This API is experimental, so API stability is not guaranteed across minor versions. + * @param credentials + * @param channelzRef + * @returns + */ + experimentalCreateConnectionInjectorWithChannelzRef(credentials, channelzRef, ownsChannelzRef = false) { + if (credentials === null || !(credentials instanceof server_credentials_1.ServerCredentials)) { + throw new TypeError('creds must be a ServerCredentials object'); + } + if (this.channelzEnabled) { + this.listenerChildrenTracker.refChild(channelzRef); + } + const server = this.createHttp2Server(credentials); + const sessionsSet = new Set(); + this.http2Servers.set(server, { + channelzRef: channelzRef, + sessions: sessionsSet, + ownsChannelzRef + }); + return { + injectConnection: (connection) => { + server.emit('connection', connection); + }, + drain: (graceTimeMs) => { + var _b, _c; + for (const session of sessionsSet) { + this.closeSession(session); + } + (_c = (_b = setTimeout(() => { + for (const session of sessionsSet) { + session.destroy(http2.constants.NGHTTP2_CANCEL); + } + }, graceTimeMs)).unref) === null || _c === void 0 ? void 0 : _c.call(_b); + }, + destroy: () => { + this.closeServer(server); + for (const session of sessionsSet) { + this.closeSession(session); + } + } + }; + } + createConnectionInjector(credentials) { + if (credentials === null || !(credentials instanceof server_credentials_1.ServerCredentials)) { + throw new TypeError('creds must be a ServerCredentials object'); + } + const channelzRef = this.registerInjectorToChannelz(); + return this.experimentalCreateConnectionInjectorWithChannelzRef(credentials, channelzRef, true); + } + closeServer(server, callback) { + this.trace('Closing server with address ' + JSON.stringify(server.address())); + const serverInfo = this.http2Servers.get(server); + server.close(() => { + if (serverInfo && serverInfo.ownsChannelzRef) { + this.listenerChildrenTracker.unrefChild(serverInfo.channelzRef); + (0, channelz_1.unregisterChannelzRef)(serverInfo.channelzRef); + } + this.http2Servers.delete(server); + callback === null || callback === void 0 ? void 0 : callback(); + }); + } + closeSession(session, callback) { + var _b; + this.trace('Closing session initiated by ' + ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress)); + const sessionInfo = this.sessions.get(session); + const closeCallback = () => { + if (sessionInfo) { + this.sessionChildrenTracker.unrefChild(sessionInfo.ref); + (0, channelz_1.unregisterChannelzRef)(sessionInfo.ref); + } + callback === null || callback === void 0 ? void 0 : callback(); + }; + if (session.closed) { + queueMicrotask(closeCallback); + } + else { + session.close(closeCallback); + } + } + completeUnbind(boundPortObject) { + for (const server of boundPortObject.listeningServers) { + const serverInfo = this.http2Servers.get(server); + this.closeServer(server, () => { + boundPortObject.listeningServers.delete(server); + }); + if (serverInfo) { + for (const session of serverInfo.sessions) { + this.closeSession(session); + } + } + } + this.boundPorts.delete(boundPortObject.mapKey); + } + /** + * Unbind a previously bound port, or cancel an in-progress bindAsync + * operation. If port 0 was bound, only the actual bound port can be + * unbound. For example, if bindAsync was called with "localhost:0" and the + * bound port result was 54321, it can be unbound as "localhost:54321". + * @param port + */ + unbind(port) { + this.trace('unbind port=' + port); + const portUri = this.normalizePort(port); + const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); + if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { + throw new Error('Cannot unbind port 0'); + } + const boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); + if (boundPortObject) { + this.trace('unbinding ' + + boundPortObject.mapKey + + ' originally bound as ' + + (0, uri_parser_1.uriToString)(boundPortObject.originalUri)); + /* If the bind operation is pending, the cancelled flag will trigger + * the unbind operation later. */ + if (boundPortObject.completionPromise) { + boundPortObject.cancelled = true; + } + else { + this.completeUnbind(boundPortObject); + } + } + } + /** + * Gracefully close all connections associated with a previously bound port. + * After the grace time, forcefully close all remaining open connections. + * + * If port 0 was bound, only the actual bound port can be + * drained. For example, if bindAsync was called with "localhost:0" and the + * bound port result was 54321, it can be drained as "localhost:54321". + * @param port + * @param graceTimeMs + * @returns + */ + drain(port, graceTimeMs) { + var _b, _c; + this.trace('drain port=' + port + ' graceTimeMs=' + graceTimeMs); + const portUri = this.normalizePort(port); + const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); + if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { + throw new Error('Cannot drain port 0'); + } + const boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); + if (!boundPortObject) { + return; + } + const allSessions = new Set(); + for (const http2Server of boundPortObject.listeningServers) { + const serverEntry = this.http2Servers.get(http2Server); + if (serverEntry) { + for (const session of serverEntry.sessions) { + allSessions.add(session); + this.closeSession(session, () => { + allSessions.delete(session); + }); + } + } + } + /* After the grace time ends, send another goaway to all remaining sessions + * with the CANCEL code. */ + (_c = (_b = setTimeout(() => { + for (const session of allSessions) { + session.destroy(http2.constants.NGHTTP2_CANCEL); + } + }, graceTimeMs)).unref) === null || _c === void 0 ? void 0 : _c.call(_b); + } + forceShutdown() { + for (const boundPortObject of this.boundPorts.values()) { + boundPortObject.cancelled = true; + } + this.boundPorts.clear(); + // Close the server if it is still running. + for (const server of this.http2Servers.keys()) { + this.closeServer(server); + } + // Always destroy any available sessions. It's possible that one or more + // tryShutdown() calls are in progress. Don't wait on them to finish. + this.sessions.forEach((channelzInfo, session) => { + this.closeSession(session); + // Cast NGHTTP2_CANCEL to any because TypeScript doesn't seem to + // recognize destroy(code) as a valid signature. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + session.destroy(http2.constants.NGHTTP2_CANCEL); + }); + this.sessions.clear(); + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + this.shutdown = true; + } + register(name, handler, serialize, deserialize, type) { + if (this.handlers.has(name)) { + return false; + } + this.handlers.set(name, { + func: handler, + serialize, + deserialize, + type, + path: name, + }); + return true; + } + unregister(name) { + return this.handlers.delete(name); + } + /** + * @deprecated No longer needed as of version 1.10.x + */ + start() { + if (this.http2Servers.size === 0 || + [...this.http2Servers.keys()].every(server => !server.listening)) { + throw new Error('server must be bound in order to start'); + } + if (this.started === true) { + throw new Error('server is already started'); + } + this.started = true; + } + tryShutdown(callback) { + var _b; + const wrappedCallback = (error) => { + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + callback(error); + }; + let pendingChecks = 0; + function maybeCallback() { + pendingChecks--; + if (pendingChecks === 0) { + wrappedCallback(); + } + } + this.shutdown = true; + for (const [serverKey, server] of this.http2Servers.entries()) { + pendingChecks++; + const serverString = server.channelzRef.name; + this.trace('Waiting for server ' + serverString + ' to close'); + this.closeServer(serverKey, () => { + this.trace('Server ' + serverString + ' finished closing'); + maybeCallback(); + }); + for (const session of server.sessions.keys()) { + pendingChecks++; + const sessionString = (_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress; + this.trace('Waiting for session ' + sessionString + ' to close'); + this.closeSession(session, () => { + this.trace('Session ' + sessionString + ' finished closing'); + maybeCallback(); + }); + } + } + if (pendingChecks === 0) { + wrappedCallback(); + } + } + addHttp2Port() { + throw new Error('Not yet implemented'); + } + /** + * Get the channelz reference object for this server. The returned value is + * garbage if channelz is disabled for this server. + * @returns + */ + getChannelzRef() { + return this.channelzRef; + } + _verifyContentType(stream, headers) { + const contentType = headers[http2.constants.HTTP2_HEADER_CONTENT_TYPE]; + if (typeof contentType !== 'string' || + !contentType.startsWith('application/grpc')) { + stream.respond({ + [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, + }, { endStream: true }); + return false; + } + return true; + } + _retrieveHandler(path) { + serverCallTrace('Received call to method ' + + path + + ' at address ' + + this.serverAddressString); + const handler = this.handlers.get(path); + if (handler === undefined) { + serverCallTrace('No handler registered for method ' + + path + + '. Sending UNIMPLEMENTED status.'); + return null; + } + return handler; + } + _respondWithError(err, stream, channelzSessionInfo = null) { + var _b, _c; + const trailersToSend = Object.assign({ 'grpc-status': (_b = err.code) !== null && _b !== void 0 ? _b : constants_1.Status.INTERNAL, 'grpc-message': err.details, [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: 'application/grpc+proto' }, (_c = err.metadata) === null || _c === void 0 ? void 0 : _c.toHttp2Headers()); + stream.respond(trailersToSend, { endStream: true }); + this.callTracker.addCallFailed(); + channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); + } + _channelzHandler(extraInterceptors, stream, headers) { + // for handling idle timeout + this.onStreamOpened(stream); + const channelzSessionInfo = this.sessions.get(stream.session); + this.callTracker.addCallStarted(); + channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallStarted(); + if (!this._verifyContentType(stream, headers)) { + this.callTracker.addCallFailed(); + channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); + return; + } + const path = headers[HTTP2_HEADER_PATH]; + const handler = this._retrieveHandler(path); + if (!handler) { + this._respondWithError(getUnimplementedStatusResponse(path), stream, channelzSessionInfo); + return; + } + const callEventTracker = { + addMessageSent: () => { + if (channelzSessionInfo) { + channelzSessionInfo.messagesSent += 1; + channelzSessionInfo.lastMessageSentTimestamp = new Date(); + } + }, + addMessageReceived: () => { + if (channelzSessionInfo) { + channelzSessionInfo.messagesReceived += 1; + channelzSessionInfo.lastMessageReceivedTimestamp = new Date(); + } + }, + onCallEnd: status => { + if (status.code === constants_1.Status.OK) { + this.callTracker.addCallSucceeded(); + } + else { + this.callTracker.addCallFailed(); + } + }, + onStreamEnd: success => { + if (channelzSessionInfo) { + if (success) { + channelzSessionInfo.streamTracker.addCallSucceeded(); + } + else { + channelzSessionInfo.streamTracker.addCallFailed(); + } + } + }, + }; + const call = (0, server_interceptors_1.getServerInterceptingCall)([...extraInterceptors, ...this.interceptors], stream, headers, callEventTracker, handler, this.options); + if (!this._runHandlerForCall(call, handler)) { + this.callTracker.addCallFailed(); + channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); + call.sendStatus({ + code: constants_1.Status.INTERNAL, + details: `Unknown handler type: ${handler.type}`, + }); + } + } + _streamHandler(extraInterceptors, stream, headers) { + // for handling idle timeout + this.onStreamOpened(stream); + if (this._verifyContentType(stream, headers) !== true) { + return; + } + const path = headers[HTTP2_HEADER_PATH]; + const handler = this._retrieveHandler(path); + if (!handler) { + this._respondWithError(getUnimplementedStatusResponse(path), stream, null); + return; + } + const call = (0, server_interceptors_1.getServerInterceptingCall)([...extraInterceptors, ...this.interceptors], stream, headers, null, handler, this.options); + if (!this._runHandlerForCall(call, handler)) { + call.sendStatus({ + code: constants_1.Status.INTERNAL, + details: `Unknown handler type: ${handler.type}`, + }); + } + } + _runHandlerForCall(call, handler) { + const { type } = handler; + if (type === 'unary') { + handleUnary(call, handler); + } + else if (type === 'clientStream') { + handleClientStreaming(call, handler); + } + else if (type === 'serverStream') { + handleServerStreaming(call, handler); + } + else if (type === 'bidi') { + handleBidiStreaming(call, handler); + } + else { + return false; + } + return true; + } + _setupHandlers(http2Server, extraInterceptors) { + if (http2Server === null) { + return; + } + const serverAddress = http2Server.address(); + let serverAddressString = 'null'; + if (serverAddress) { + if (typeof serverAddress === 'string') { + serverAddressString = serverAddress; + } + else { + serverAddressString = serverAddress.address + ':' + serverAddress.port; + } + } + this.serverAddressString = serverAddressString; + const handler = this.channelzEnabled + ? this._channelzHandler + : this._streamHandler; + const sessionHandler = this.channelzEnabled + ? this._channelzSessionHandler(http2Server) + : this._sessionHandler(http2Server); + http2Server.on('stream', handler.bind(this, extraInterceptors)); + http2Server.on('session', sessionHandler); + } + _sessionHandler(http2Server) { + return (session) => { + var _b, _c; + (_b = this.http2Servers.get(http2Server)) === null || _b === void 0 ? void 0 : _b.sessions.add(session); + let connectionAgeTimer = null; + let connectionAgeGraceTimer = null; + let keepaliveTimer = null; + let sessionClosedByServer = false; + const idleTimeoutObj = this.enableIdleTimeout(session); + if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) { + // Apply a random jitter within a +/-10% range + const jitterMagnitude = this.maxConnectionAgeMs / 10; + const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude; + connectionAgeTimer = setTimeout(() => { + var _b, _c; + sessionClosedByServer = true; + this.trace('Connection dropped by max connection age: ' + + ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress)); + try { + session.goaway(http2.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge); + } + catch (e) { + // The goaway can't be sent because the session is already closed + session.destroy(); + return; + } + session.close(); + /* Allow a grace period after sending the GOAWAY before forcibly + * closing the connection. */ + if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) { + connectionAgeGraceTimer = setTimeout(() => { + session.destroy(); + }, this.maxConnectionAgeGraceMs); + (_c = connectionAgeGraceTimer.unref) === null || _c === void 0 ? void 0 : _c.call(connectionAgeGraceTimer); + } + }, this.maxConnectionAgeMs + jitter); + (_c = connectionAgeTimer.unref) === null || _c === void 0 ? void 0 : _c.call(connectionAgeTimer); + } + const clearKeepaliveTimeout = () => { + if (keepaliveTimer) { + clearTimeout(keepaliveTimer); + keepaliveTimer = null; + } + }; + const canSendPing = () => { + return (!session.destroyed && + this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && + this.keepaliveTimeMs > 0); + }; + /* eslint-disable-next-line prefer-const */ + let sendPing; // hoisted for use in maybeStartKeepalivePingTimer + const maybeStartKeepalivePingTimer = () => { + var _b; + if (!canSendPing()) { + return; + } + this.keepaliveTrace('Starting keepalive timer for ' + this.keepaliveTimeMs + 'ms'); + keepaliveTimer = setTimeout(() => { + clearKeepaliveTimeout(); + sendPing(); + }, this.keepaliveTimeMs); + (_b = keepaliveTimer.unref) === null || _b === void 0 ? void 0 : _b.call(keepaliveTimer); + }; + sendPing = () => { + var _b; + if (!canSendPing()) { + return; + } + this.keepaliveTrace('Sending ping with timeout ' + this.keepaliveTimeoutMs + 'ms'); + let pingSendError = ''; + try { + const pingSentSuccessfully = session.ping((err, duration, payload) => { + clearKeepaliveTimeout(); + if (err) { + this.keepaliveTrace('Ping failed with error: ' + err.message); + sessionClosedByServer = true; + session.destroy(); + } + else { + this.keepaliveTrace('Received ping response'); + maybeStartKeepalivePingTimer(); + } + }); + if (!pingSentSuccessfully) { + pingSendError = 'Ping returned false'; + } + } + catch (e) { + // grpc/grpc-node#2139 + pingSendError = + (e instanceof Error ? e.message : '') || 'Unknown error'; + } + if (pingSendError) { + this.keepaliveTrace('Ping send failed: ' + pingSendError); + this.trace('Connection dropped due to ping send error: ' + pingSendError); + sessionClosedByServer = true; + session.destroy(); + return; + } + keepaliveTimer = setTimeout(() => { + clearKeepaliveTimeout(); + this.keepaliveTrace('Ping timeout passed without response'); + this.trace('Connection dropped by keepalive timeout'); + sessionClosedByServer = true; + session.destroy(); + }, this.keepaliveTimeoutMs); + (_b = keepaliveTimer.unref) === null || _b === void 0 ? void 0 : _b.call(keepaliveTimer); + }; + maybeStartKeepalivePingTimer(); + session.on('close', () => { + var _b, _c; + if (!sessionClosedByServer) { + this.trace(`Connection dropped by client ${(_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress}`); + } + if (connectionAgeTimer) { + clearTimeout(connectionAgeTimer); + } + if (connectionAgeGraceTimer) { + clearTimeout(connectionAgeGraceTimer); + } + clearKeepaliveTimeout(); + if (idleTimeoutObj !== null) { + clearTimeout(idleTimeoutObj.timeout); + this.sessionIdleTimeouts.delete(session); + } + (_c = this.http2Servers.get(http2Server)) === null || _c === void 0 ? void 0 : _c.sessions.delete(session); + }); + }; + } + _channelzSessionHandler(http2Server) { + return (session) => { + var _b, _c, _d, _e; + const channelzRef = (0, channelz_1.registerChannelzSocket)((_c = (_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress) !== null && _c !== void 0 ? _c : 'unknown', this.getChannelzSessionInfo.bind(this, session), this.channelzEnabled); + const channelzSessionInfo = { + ref: channelzRef, + streamTracker: new channelz_1.ChannelzCallTracker(), + messagesSent: 0, + messagesReceived: 0, + keepAlivesSent: 0, + lastMessageSentTimestamp: null, + lastMessageReceivedTimestamp: null, + }; + (_d = this.http2Servers.get(http2Server)) === null || _d === void 0 ? void 0 : _d.sessions.add(session); + this.sessions.set(session, channelzSessionInfo); + const clientAddress = `${session.socket.remoteAddress}:${session.socket.remotePort}`; + this.channelzTrace.addTrace('CT_INFO', 'Connection established by client ' + clientAddress); + this.trace('Connection established by client ' + clientAddress); + this.sessionChildrenTracker.refChild(channelzRef); + let connectionAgeTimer = null; + let connectionAgeGraceTimer = null; + let keepaliveTimeout = null; + let sessionClosedByServer = false; + const idleTimeoutObj = this.enableIdleTimeout(session); + if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) { + // Apply a random jitter within a +/-10% range + const jitterMagnitude = this.maxConnectionAgeMs / 10; + const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude; + connectionAgeTimer = setTimeout(() => { + var _b; + sessionClosedByServer = true; + this.channelzTrace.addTrace('CT_INFO', 'Connection dropped by max connection age from ' + clientAddress); + try { + session.goaway(http2.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge); + } + catch (e) { + // The goaway can't be sent because the session is already closed + session.destroy(); + return; + } + session.close(); + /* Allow a grace period after sending the GOAWAY before forcibly + * closing the connection. */ + if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) { + connectionAgeGraceTimer = setTimeout(() => { + session.destroy(); + }, this.maxConnectionAgeGraceMs); + (_b = connectionAgeGraceTimer.unref) === null || _b === void 0 ? void 0 : _b.call(connectionAgeGraceTimer); + } + }, this.maxConnectionAgeMs + jitter); + (_e = connectionAgeTimer.unref) === null || _e === void 0 ? void 0 : _e.call(connectionAgeTimer); + } + const clearKeepaliveTimeout = () => { + if (keepaliveTimeout) { + clearTimeout(keepaliveTimeout); + keepaliveTimeout = null; + } + }; + const canSendPing = () => { + return (!session.destroyed && + this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && + this.keepaliveTimeMs > 0); + }; + /* eslint-disable-next-line prefer-const */ + let sendPing; // hoisted for use in maybeStartKeepalivePingTimer + const maybeStartKeepalivePingTimer = () => { + var _b; + if (!canSendPing()) { + return; + } + this.keepaliveTrace('Starting keepalive timer for ' + this.keepaliveTimeMs + 'ms'); + keepaliveTimeout = setTimeout(() => { + clearKeepaliveTimeout(); + sendPing(); + }, this.keepaliveTimeMs); + (_b = keepaliveTimeout.unref) === null || _b === void 0 ? void 0 : _b.call(keepaliveTimeout); + }; + sendPing = () => { + var _b; + if (!canSendPing()) { + return; + } + this.keepaliveTrace('Sending ping with timeout ' + this.keepaliveTimeoutMs + 'ms'); + let pingSendError = ''; + try { + const pingSentSuccessfully = session.ping((err, duration, payload) => { + clearKeepaliveTimeout(); + if (err) { + this.keepaliveTrace('Ping failed with error: ' + err.message); + this.channelzTrace.addTrace('CT_INFO', 'Connection dropped due to error of a ping frame ' + + err.message + + ' return in ' + + duration); + sessionClosedByServer = true; + session.destroy(); + } + else { + this.keepaliveTrace('Received ping response'); + maybeStartKeepalivePingTimer(); + } + }); + if (!pingSentSuccessfully) { + pingSendError = 'Ping returned false'; + } + } + catch (e) { + // grpc/grpc-node#2139 + pingSendError = + (e instanceof Error ? e.message : '') || 'Unknown error'; + } + if (pingSendError) { + this.keepaliveTrace('Ping send failed: ' + pingSendError); + this.channelzTrace.addTrace('CT_INFO', 'Connection dropped due to ping send error: ' + pingSendError); + sessionClosedByServer = true; + session.destroy(); + return; + } + channelzSessionInfo.keepAlivesSent += 1; + keepaliveTimeout = setTimeout(() => { + clearKeepaliveTimeout(); + this.keepaliveTrace('Ping timeout passed without response'); + this.channelzTrace.addTrace('CT_INFO', 'Connection dropped by keepalive timeout from ' + clientAddress); + sessionClosedByServer = true; + session.destroy(); + }, this.keepaliveTimeoutMs); + (_b = keepaliveTimeout.unref) === null || _b === void 0 ? void 0 : _b.call(keepaliveTimeout); + }; + maybeStartKeepalivePingTimer(); + session.on('close', () => { + var _b; + if (!sessionClosedByServer) { + this.channelzTrace.addTrace('CT_INFO', 'Connection dropped by client ' + clientAddress); + } + this.sessionChildrenTracker.unrefChild(channelzRef); + (0, channelz_1.unregisterChannelzRef)(channelzRef); + if (connectionAgeTimer) { + clearTimeout(connectionAgeTimer); + } + if (connectionAgeGraceTimer) { + clearTimeout(connectionAgeGraceTimer); + } + clearKeepaliveTimeout(); + if (idleTimeoutObj !== null) { + clearTimeout(idleTimeoutObj.timeout); + this.sessionIdleTimeouts.delete(session); + } + (_b = this.http2Servers.get(http2Server)) === null || _b === void 0 ? void 0 : _b.sessions.delete(session); + this.sessions.delete(session); + }); + }; + } + enableIdleTimeout(session) { + var _b, _c; + if (this.sessionIdleTimeout >= MAX_CONNECTION_IDLE_MS) { + return null; + } + const idleTimeoutObj = { + activeStreams: 0, + lastIdle: Date.now(), + onClose: this.onStreamClose.bind(this, session), + timeout: setTimeout(this.onIdleTimeout, this.sessionIdleTimeout, this, session), + }; + (_c = (_b = idleTimeoutObj.timeout).unref) === null || _c === void 0 ? void 0 : _c.call(_b); + this.sessionIdleTimeouts.set(session, idleTimeoutObj); + const { socket } = session; + this.trace('Enable idle timeout for ' + + socket.remoteAddress + + ':' + + socket.remotePort); + return idleTimeoutObj; + } + onIdleTimeout(ctx, session) { + const { socket } = session; + const sessionInfo = ctx.sessionIdleTimeouts.get(session); + // if it is called while we have activeStreams - timer will not be rescheduled + // until last active stream is closed, then it will call .refresh() on the timer + // important part is to not clearTimeout(timer) or it becomes unusable + // for future refreshes + if (sessionInfo !== undefined && + sessionInfo.activeStreams === 0) { + if (Date.now() - sessionInfo.lastIdle >= ctx.sessionIdleTimeout) { + ctx.trace('Session idle timeout triggered for ' + + (socket === null || socket === void 0 ? void 0 : socket.remoteAddress) + + ':' + + (socket === null || socket === void 0 ? void 0 : socket.remotePort) + + ' last idle at ' + + sessionInfo.lastIdle); + ctx.closeSession(session); + } + else { + sessionInfo.timeout.refresh(); + } + } + } + onStreamOpened(stream) { + const session = stream.session; + const idleTimeoutObj = this.sessionIdleTimeouts.get(session); + if (idleTimeoutObj) { + idleTimeoutObj.activeStreams += 1; + stream.once('close', idleTimeoutObj.onClose); + } + } + onStreamClose(session) { + var _b, _c; + const idleTimeoutObj = this.sessionIdleTimeouts.get(session); + if (idleTimeoutObj) { + idleTimeoutObj.activeStreams -= 1; + if (idleTimeoutObj.activeStreams === 0) { + idleTimeoutObj.lastIdle = Date.now(); + idleTimeoutObj.timeout.refresh(); + this.trace('Session onStreamClose' + + ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress) + + ':' + + ((_c = session.socket) === null || _c === void 0 ? void 0 : _c.remotePort) + + ' at ' + + idleTimeoutObj.lastIdle); + } + } + } + }, + (() => { + const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; + _start_decorators = [deprecate('Calling start() is no longer necessary. It can be safely omitted.')]; + __esDecorate(_a, null, _start_decorators, { kind: "method", name: "start", static: false, private: false, access: { has: obj => "start" in obj, get: obj => obj.start }, metadata: _metadata }, null, _instanceExtraInitializers); + if (_metadata) Object.defineProperty(_a, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); + })(), + _a; +})(); +exports.Server = Server; +async function handleUnary(call, handler) { + let stream; + function respond(err, value, trailer, flags) { + if (err) { + call.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer)); + return; + } + call.sendMessage(value, () => { + call.sendStatus({ + code: constants_1.Status.OK, + details: 'OK', + metadata: trailer !== null && trailer !== void 0 ? trailer : null, + }); + }); + } + let requestMetadata; + let requestMessage = null; + call.start({ + onReceiveMetadata(metadata) { + requestMetadata = metadata; + call.startRead(); + }, + onReceiveMessage(message) { + if (requestMessage) { + call.sendStatus({ + code: constants_1.Status.UNIMPLEMENTED, + details: `Received a second request message for server streaming method ${handler.path}`, + metadata: null, + }); + return; + } + requestMessage = message; + call.startRead(); + }, + onReceiveHalfClose() { + if (!requestMessage) { + call.sendStatus({ + code: constants_1.Status.UNIMPLEMENTED, + details: `Received no request message for server streaming method ${handler.path}`, + metadata: null, + }); + return; + } + stream = new server_call_1.ServerWritableStreamImpl(handler.path, call, requestMetadata, requestMessage); + try { + handler.func(stream, respond); + } + catch (err) { + call.sendStatus({ + code: constants_1.Status.UNKNOWN, + details: `Server method handler threw error ${err.message}`, + metadata: null, + }); + } + }, + onCancel() { + if (stream) { + stream.cancelled = true; + stream.emit('cancelled', 'cancelled'); + } + }, + }); +} +function handleClientStreaming(call, handler) { + let stream; + function respond(err, value, trailer, flags) { + if (err) { + call.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer)); + return; + } + call.sendMessage(value, () => { + call.sendStatus({ + code: constants_1.Status.OK, + details: 'OK', + metadata: trailer !== null && trailer !== void 0 ? trailer : null, + }); + }); + } + call.start({ + onReceiveMetadata(metadata) { + stream = new server_call_1.ServerDuplexStreamImpl(handler.path, call, metadata); + try { + handler.func(stream, respond); + } + catch (err) { + call.sendStatus({ + code: constants_1.Status.UNKNOWN, + details: `Server method handler threw error ${err.message}`, + metadata: null, + }); + } + }, + onReceiveMessage(message) { + stream.push(message); + }, + onReceiveHalfClose() { + stream.push(null); + }, + onCancel() { + if (stream) { + stream.cancelled = true; + stream.emit('cancelled', 'cancelled'); + stream.destroy(); + } + }, + }); +} +function handleServerStreaming(call, handler) { + let stream; + let requestMetadata; + let requestMessage = null; + call.start({ + onReceiveMetadata(metadata) { + requestMetadata = metadata; + call.startRead(); + }, + onReceiveMessage(message) { + if (requestMessage) { + call.sendStatus({ + code: constants_1.Status.UNIMPLEMENTED, + details: `Received a second request message for server streaming method ${handler.path}`, + metadata: null, + }); + return; + } + requestMessage = message; + call.startRead(); + }, + onReceiveHalfClose() { + if (!requestMessage) { + call.sendStatus({ + code: constants_1.Status.UNIMPLEMENTED, + details: `Received no request message for server streaming method ${handler.path}`, + metadata: null, + }); + return; + } + stream = new server_call_1.ServerWritableStreamImpl(handler.path, call, requestMetadata, requestMessage); + try { + handler.func(stream); + } + catch (err) { + call.sendStatus({ + code: constants_1.Status.UNKNOWN, + details: `Server method handler threw error ${err.message}`, + metadata: null, + }); + } + }, + onCancel() { + if (stream) { + stream.cancelled = true; + stream.emit('cancelled', 'cancelled'); + stream.destroy(); + } + }, + }); +} +function handleBidiStreaming(call, handler) { + let stream; + call.start({ + onReceiveMetadata(metadata) { + stream = new server_call_1.ServerDuplexStreamImpl(handler.path, call, metadata); + try { + handler.func(stream); + } + catch (err) { + call.sendStatus({ + code: constants_1.Status.UNKNOWN, + details: `Server method handler threw error ${err.message}`, + metadata: null, + }); + } + }, + onReceiveMessage(message) { + stream.push(message); + }, + onReceiveHalfClose() { + stream.push(null); + }, + onCancel() { + if (stream) { + stream.cancelled = true; + stream.emit('cancelled', 'cancelled'); + stream.destroy(); + } + }, + }); +} +//# sourceMappingURL=server.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/server.js.map b/node_modules/@grpc/grpc-js/build/src/server.js.map new file mode 100644 index 0000000..72340cb --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server.js.map @@ -0,0 +1 @@ +{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,+BAA+B;AAC/B,6BAA6B;AAG7B,2CAAmD;AAGnD,+CAkBuB;AACvB,6DAA+E;AAE/E,yCAIoB;AACpB,qCAAqC;AACrC,6DAK8B;AAC9B,6CAMsB;AACtB,yCAeoB;AAEpB,+DAI+B;AAM/B,MAAM,2BAA2B,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;AAC/C,MAAM,qBAAqB,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;AACzC,MAAM,oBAAoB,GAAG,KAAK,CAAC;AACnC,MAAM,sBAAsB,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;AAE1C,MAAM,EAAE,iBAAiB,EAAE,GAAG,KAAK,CAAC,SAAS,CAAC;AAE9C,MAAM,WAAW,GAAG,QAAQ,CAAC;AAC7B,MAAM,OAAO,GAAG,MAAM,CAAC,IAA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gBAAgB,CAAC,OAAO;YACtB,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;QACD,kBAAkB;YAChB,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACpB,CAAC;QACD,QAAQ;YACN,IAAI,MAAM,EAAE,CAAC;gBACX,MAAM,CAAC,SAAS,GAAG,IAAI,CAAC;gBACxB,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;gBACtC,MAAM,CAAC,OAAO,EAAE,CAAC;YACnB,CAAC;QACH,CAAC;KACF,CAAC,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/service-config.d.ts b/node_modules/@grpc/grpc-js/build/src/service-config.d.ts new file mode 100644 index 0000000..c638f4f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/service-config.d.ts @@ -0,0 +1,58 @@ +import { Status } from './constants'; +import { Duration } from './duration'; +export interface MethodConfigName { + service?: string; + method?: string; +} +export interface RetryPolicy { + maxAttempts: number; + initialBackoff: string; + maxBackoff: string; + backoffMultiplier: number; + retryableStatusCodes: (Status | string)[]; +} +export interface HedgingPolicy { + maxAttempts: number; + hedgingDelay?: string; + nonFatalStatusCodes?: (Status | string)[]; +} +export interface MethodConfig { + name: MethodConfigName[]; + waitForReady?: boolean; + timeout?: Duration; + maxRequestBytes?: number; + maxResponseBytes?: number; + retryPolicy?: RetryPolicy; + hedgingPolicy?: HedgingPolicy; +} +export interface RetryThrottling { + maxTokens: number; + tokenRatio: number; +} +export interface LoadBalancingConfig { + [key: string]: object; +} +export interface ServiceConfig { + loadBalancingPolicy?: string; + loadBalancingConfig: LoadBalancingConfig[]; + methodConfig: MethodConfig[]; + retryThrottling?: RetryThrottling; +} +export interface ServiceConfigCanaryConfig { + clientLanguage?: string[]; + percentage?: number; + clientHostname?: string[]; + serviceConfig: ServiceConfig; +} +export declare function validateRetryThrottling(obj: any): RetryThrottling; +export declare function validateServiceConfig(obj: any): ServiceConfig; +/** + * Find the "grpc_config" record among the TXT records, parse its value as JSON, validate its contents, + * and select a service config with selection fields that all match this client. Most of these steps + * can fail with an error; the caller must handle any errors thrown this way. + * @param txtRecord The TXT record array that is output from a successful call to dns.resolveTxt + * @param percentage A number chosen from the range [0, 100) that is used to select which config to use + * @return The service configuration to use, given the percentage value, or null if the service config + * data has a valid format but none of the options match the current client. + */ +export declare function extractAndSelectServiceConfig(txtRecord: string[][], percentage: number): ServiceConfig | null; diff --git a/node_modules/@grpc/grpc-js/build/src/service-config.js b/node_modules/@grpc/grpc-js/build/src/service-config.js new file mode 100644 index 0000000..d7accd3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/service-config.js @@ -0,0 +1,430 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateRetryThrottling = validateRetryThrottling; +exports.validateServiceConfig = validateServiceConfig; +exports.extractAndSelectServiceConfig = extractAndSelectServiceConfig; +/* This file implements gRFC A2 and the service config spec: + * https://github.com/grpc/proposal/blob/master/A2-service-configs-in-dns.md + * https://github.com/grpc/grpc/blob/master/doc/service_config.md. Each + * function here takes an object with unknown structure and returns its + * specific object type if the input has the right structure, and throws an + * error otherwise. */ +/* The any type is purposely used here. All functions validate their input at + * runtime */ +/* eslint-disable @typescript-eslint/no-explicit-any */ +const os = require("os"); +const constants_1 = require("./constants"); +/** + * Recognizes a number with up to 9 digits after the decimal point, followed by + * an "s", representing a number of seconds. + */ +const DURATION_REGEX = /^\d+(\.\d{1,9})?s$/; +/** + * Client language name used for determining whether this client matches a + * `ServiceConfigCanaryConfig`'s `clientLanguage` list. + */ +const CLIENT_LANGUAGE_STRING = 'node'; +function validateName(obj) { + // In this context, and unset field and '' are considered the same + if ('service' in obj && obj.service !== '') { + if (typeof obj.service !== 'string') { + throw new Error(`Invalid method config name: invalid service: expected type string, got ${typeof obj.service}`); + } + if ('method' in obj && obj.method !== '') { + if (typeof obj.method !== 'string') { + throw new Error(`Invalid method config name: invalid method: expected type string, got ${typeof obj.service}`); + } + return { + service: obj.service, + method: obj.method, + }; + } + else { + return { + service: obj.service, + }; + } + } + else { + if ('method' in obj && obj.method !== undefined) { + throw new Error(`Invalid method config name: method set with empty or unset service`); + } + return {}; + } +} +function validateRetryPolicy(obj) { + if (!('maxAttempts' in obj) || + !Number.isInteger(obj.maxAttempts) || + obj.maxAttempts < 2) { + throw new Error('Invalid method config retry policy: maxAttempts must be an integer at least 2'); + } + if (!('initialBackoff' in obj) || + typeof obj.initialBackoff !== 'string' || + !DURATION_REGEX.test(obj.initialBackoff)) { + throw new Error('Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer or decimal followed by s'); + } + if (!('maxBackoff' in obj) || + typeof obj.maxBackoff !== 'string' || + !DURATION_REGEX.test(obj.maxBackoff)) { + throw new Error('Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer or decimal followed by s'); + } + if (!('backoffMultiplier' in obj) || + typeof obj.backoffMultiplier !== 'number' || + obj.backoffMultiplier <= 0) { + throw new Error('Invalid method config retry policy: backoffMultiplier must be a number greater than 0'); + } + if (!('retryableStatusCodes' in obj && Array.isArray(obj.retryableStatusCodes))) { + throw new Error('Invalid method config retry policy: retryableStatusCodes is required'); + } + if (obj.retryableStatusCodes.length === 0) { + throw new Error('Invalid method config retry policy: retryableStatusCodes must be non-empty'); + } + for (const value of obj.retryableStatusCodes) { + if (typeof value === 'number') { + if (!Object.values(constants_1.Status).includes(value)) { + throw new Error('Invalid method config retry policy: retryableStatusCodes value not in status code range'); + } + } + else if (typeof value === 'string') { + if (!Object.values(constants_1.Status).includes(value.toUpperCase())) { + throw new Error('Invalid method config retry policy: retryableStatusCodes value not a status code name'); + } + } + else { + throw new Error('Invalid method config retry policy: retryableStatusCodes value must be a string or number'); + } + } + return { + maxAttempts: obj.maxAttempts, + initialBackoff: obj.initialBackoff, + maxBackoff: obj.maxBackoff, + backoffMultiplier: obj.backoffMultiplier, + retryableStatusCodes: obj.retryableStatusCodes, + }; +} +function validateHedgingPolicy(obj) { + if (!('maxAttempts' in obj) || + !Number.isInteger(obj.maxAttempts) || + obj.maxAttempts < 2) { + throw new Error('Invalid method config hedging policy: maxAttempts must be an integer at least 2'); + } + if ('hedgingDelay' in obj && + (typeof obj.hedgingDelay !== 'string' || + !DURATION_REGEX.test(obj.hedgingDelay))) { + throw new Error('Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s'); + } + if ('nonFatalStatusCodes' in obj && Array.isArray(obj.nonFatalStatusCodes)) { + for (const value of obj.nonFatalStatusCodes) { + if (typeof value === 'number') { + if (!Object.values(constants_1.Status).includes(value)) { + throw new Error('Invalid method config hedging policy: nonFatalStatusCodes value not in status code range'); + } + } + else if (typeof value === 'string') { + if (!Object.values(constants_1.Status).includes(value.toUpperCase())) { + throw new Error('Invalid method config hedging policy: nonFatalStatusCodes value not a status code name'); + } + } + else { + throw new Error('Invalid method config hedging policy: nonFatalStatusCodes value must be a string or number'); + } + } + } + const result = { + maxAttempts: obj.maxAttempts, + }; + if (obj.hedgingDelay) { + result.hedgingDelay = obj.hedgingDelay; + } + if (obj.nonFatalStatusCodes) { + result.nonFatalStatusCodes = obj.nonFatalStatusCodes; + } + return result; +} +function validateMethodConfig(obj) { + var _a; + const result = { + name: [], + }; + if (!('name' in obj) || !Array.isArray(obj.name)) { + throw new Error('Invalid method config: invalid name array'); + } + for (const name of obj.name) { + result.name.push(validateName(name)); + } + if ('waitForReady' in obj) { + if (typeof obj.waitForReady !== 'boolean') { + throw new Error('Invalid method config: invalid waitForReady'); + } + result.waitForReady = obj.waitForReady; + } + if ('timeout' in obj) { + if (typeof obj.timeout === 'object') { + if (!('seconds' in obj.timeout) || + !(typeof obj.timeout.seconds === 'number')) { + throw new Error('Invalid method config: invalid timeout.seconds'); + } + if (!('nanos' in obj.timeout) || + !(typeof obj.timeout.nanos === 'number')) { + throw new Error('Invalid method config: invalid timeout.nanos'); + } + result.timeout = obj.timeout; + } + else if (typeof obj.timeout === 'string' && + DURATION_REGEX.test(obj.timeout)) { + const timeoutParts = obj.timeout + .substring(0, obj.timeout.length - 1) + .split('.'); + result.timeout = { + seconds: timeoutParts[0] | 0, + nanos: ((_a = timeoutParts[1]) !== null && _a !== void 0 ? _a : 0) | 0, + }; + } + else { + throw new Error('Invalid method config: invalid timeout'); + } + } + if ('maxRequestBytes' in obj) { + if (typeof obj.maxRequestBytes !== 'number') { + throw new Error('Invalid method config: invalid maxRequestBytes'); + } + result.maxRequestBytes = obj.maxRequestBytes; + } + if ('maxResponseBytes' in obj) { + if (typeof obj.maxResponseBytes !== 'number') { + throw new Error('Invalid method config: invalid maxRequestBytes'); + } + result.maxResponseBytes = obj.maxResponseBytes; + } + if ('retryPolicy' in obj) { + if ('hedgingPolicy' in obj) { + throw new Error('Invalid method config: retryPolicy and hedgingPolicy cannot both be specified'); + } + else { + result.retryPolicy = validateRetryPolicy(obj.retryPolicy); + } + } + else if ('hedgingPolicy' in obj) { + result.hedgingPolicy = validateHedgingPolicy(obj.hedgingPolicy); + } + return result; +} +function validateRetryThrottling(obj) { + if (!('maxTokens' in obj) || + typeof obj.maxTokens !== 'number' || + obj.maxTokens <= 0 || + obj.maxTokens > 1000) { + throw new Error('Invalid retryThrottling: maxTokens must be a number in (0, 1000]'); + } + if (!('tokenRatio' in obj) || + typeof obj.tokenRatio !== 'number' || + obj.tokenRatio <= 0) { + throw new Error('Invalid retryThrottling: tokenRatio must be a number greater than 0'); + } + return { + maxTokens: +obj.maxTokens.toFixed(3), + tokenRatio: +obj.tokenRatio.toFixed(3), + }; +} +function validateLoadBalancingConfig(obj) { + if (!(typeof obj === 'object' && obj !== null)) { + throw new Error(`Invalid loadBalancingConfig: unexpected type ${typeof obj}`); + } + const keys = Object.keys(obj); + if (keys.length > 1) { + throw new Error(`Invalid loadBalancingConfig: unexpected multiple keys ${keys}`); + } + if (keys.length === 0) { + throw new Error('Invalid loadBalancingConfig: load balancing policy name required'); + } + return { + [keys[0]]: obj[keys[0]], + }; +} +function validateServiceConfig(obj) { + const result = { + loadBalancingConfig: [], + methodConfig: [], + }; + if ('loadBalancingPolicy' in obj) { + if (typeof obj.loadBalancingPolicy === 'string') { + result.loadBalancingPolicy = obj.loadBalancingPolicy; + } + else { + throw new Error('Invalid service config: invalid loadBalancingPolicy'); + } + } + if ('loadBalancingConfig' in obj) { + if (Array.isArray(obj.loadBalancingConfig)) { + for (const config of obj.loadBalancingConfig) { + result.loadBalancingConfig.push(validateLoadBalancingConfig(config)); + } + } + else { + throw new Error('Invalid service config: invalid loadBalancingConfig'); + } + } + if ('methodConfig' in obj) { + if (Array.isArray(obj.methodConfig)) { + for (const methodConfig of obj.methodConfig) { + result.methodConfig.push(validateMethodConfig(methodConfig)); + } + } + } + if ('retryThrottling' in obj) { + result.retryThrottling = validateRetryThrottling(obj.retryThrottling); + } + // Validate method name uniqueness + const seenMethodNames = []; + for (const methodConfig of result.methodConfig) { + for (const name of methodConfig.name) { + for (const seenName of seenMethodNames) { + if (name.service === seenName.service && + name.method === seenName.method) { + throw new Error(`Invalid service config: duplicate name ${name.service}/${name.method}`); + } + } + seenMethodNames.push(name); + } + } + return result; +} +function validateCanaryConfig(obj) { + if (!('serviceConfig' in obj)) { + throw new Error('Invalid service config choice: missing service config'); + } + const result = { + serviceConfig: validateServiceConfig(obj.serviceConfig), + }; + if ('clientLanguage' in obj) { + if (Array.isArray(obj.clientLanguage)) { + result.clientLanguage = []; + for (const lang of obj.clientLanguage) { + if (typeof lang === 'string') { + result.clientLanguage.push(lang); + } + else { + throw new Error('Invalid service config choice: invalid clientLanguage'); + } + } + } + else { + throw new Error('Invalid service config choice: invalid clientLanguage'); + } + } + if ('clientHostname' in obj) { + if (Array.isArray(obj.clientHostname)) { + result.clientHostname = []; + for (const lang of obj.clientHostname) { + if (typeof lang === 'string') { + result.clientHostname.push(lang); + } + else { + throw new Error('Invalid service config choice: invalid clientHostname'); + } + } + } + else { + throw new Error('Invalid service config choice: invalid clientHostname'); + } + } + if ('percentage' in obj) { + if (typeof obj.percentage === 'number' && + 0 <= obj.percentage && + obj.percentage <= 100) { + result.percentage = obj.percentage; + } + else { + throw new Error('Invalid service config choice: invalid percentage'); + } + } + // Validate that no unexpected fields are present + const allowedFields = [ + 'clientLanguage', + 'percentage', + 'clientHostname', + 'serviceConfig', + ]; + for (const field in obj) { + if (!allowedFields.includes(field)) { + throw new Error(`Invalid service config choice: unexpected field ${field}`); + } + } + return result; +} +function validateAndSelectCanaryConfig(obj, percentage) { + if (!Array.isArray(obj)) { + throw new Error('Invalid service config list'); + } + for (const config of obj) { + const validatedConfig = validateCanaryConfig(config); + /* For each field, we check if it is present, then only discard the + * config if the field value does not match the current client */ + if (typeof validatedConfig.percentage === 'number' && + percentage > validatedConfig.percentage) { + continue; + } + if (Array.isArray(validatedConfig.clientHostname)) { + let hostnameMatched = false; + for (const hostname of validatedConfig.clientHostname) { + if (hostname === os.hostname()) { + hostnameMatched = true; + } + } + if (!hostnameMatched) { + continue; + } + } + if (Array.isArray(validatedConfig.clientLanguage)) { + let languageMatched = false; + for (const language of validatedConfig.clientLanguage) { + if (language === CLIENT_LANGUAGE_STRING) { + languageMatched = true; + } + } + if (!languageMatched) { + continue; + } + } + return validatedConfig.serviceConfig; + } + throw new Error('No matching service config found'); +} +/** + * Find the "grpc_config" record among the TXT records, parse its value as JSON, validate its contents, + * and select a service config with selection fields that all match this client. Most of these steps + * can fail with an error; the caller must handle any errors thrown this way. + * @param txtRecord The TXT record array that is output from a successful call to dns.resolveTxt + * @param percentage A number chosen from the range [0, 100) that is used to select which config to use + * @return The service configuration to use, given the percentage value, or null if the service config + * data has a valid format but none of the options match the current client. + */ +function extractAndSelectServiceConfig(txtRecord, percentage) { + for (const record of txtRecord) { + if (record.length > 0 && record[0].startsWith('grpc_config=')) { + /* Treat the list of strings in this record as a single string and remove + * "grpc_config=" from the beginning. The rest should be a JSON string */ + const recordString = record.join('').substring('grpc_config='.length); + const recordJson = JSON.parse(recordString); + return validateAndSelectCanaryConfig(recordJson, percentage); + } + } + return null; +} +//# sourceMappingURL=service-config.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/service-config.js.map b/node_modules/@grpc/grpc-js/build/src/service-config.js.map new file mode 100644 index 0000000..1aa51f4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/service-config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"service-config.js","sourceRoot":"","sources":["../../src/service-config.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AA2TH,0DAwBC;AAwBD,sDAiDC;AA0HD,sEAcC;AAliBD;;;;;sBAKsB;AAEtB;aACa;AACb,uDAAuD;AAEvD,yBAAyB;AACzB,2CAAqC;AAuDrC;;;GAGG;AACH,MAAM,cAAc,GAAG,oBAAoB,CAAC;AAE5C;;;GAGG;AACH,MAAM,sBAAsB,GAAG,MAAM,CAAC;AAEtC,SAAS,YAAY,CAAC,GAAQ;IAC5B,kEAAkE;IAClE,IAAI,SAAS,IAAI,GAAG,IAAI,GAAG,CAAC,OAAO,KAAK,EAAE,EAAE,CAAC;QAC3C,IAAI,OAAO,GAAG,CAAC,OAAO,KAAK,QAAQ,EAAE,CAAC;YACpC,MAAM,IAAI,KAAK,CACb,0EAA0E,OAAO,GAAG,CAAC,OAAO,EAAE,CAC/F,CAAC;QACJ,CAAC;QACD,IAAI,QAAQ,IAAI,GAAG,IAAI,GAAG,CAAC,MAAM,KAAK,EAAE,EAAE,CAAC;YACzC,IAAI,OAAO,GAAG,CAAC,MAAM,KAAK,QAAQ,EAAE,CAAC;gBACnC,MAAM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-js/build/src/single-subchannel-channel.d.ts b/node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.d.ts new file mode 100644 index 0000000..a9a412f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.d.ts @@ -0,0 +1,25 @@ +import { Call } from "./call-interface"; +import { Channel } from "./channel"; +import { ChannelOptions } from "./channel-options"; +import { ChannelRef } from "./channelz"; +import { ConnectivityState } from "./connectivity-state"; +import { Deadline } from "./deadline"; +import { Subchannel } from "./subchannel"; +import { GrpcUri } from "./uri-parser"; +export declare class SingleSubchannelChannel implements Channel { + private subchannel; + private target; + private channelzRef; + private channelzEnabled; + private channelzTrace; + private callTracker; + private childrenTracker; + private filterStackFactory; + constructor(subchannel: Subchannel, target: GrpcUri, options: ChannelOptions); + close(): void; + getTarget(): string; + getConnectivityState(tryToConnect: boolean): ConnectivityState; + watchConnectivityState(currentState: ConnectivityState, deadline: Date | number, callback: (error?: Error) => void): void; + getChannelzRef(): ChannelRef; + createCall(method: string, deadline: Deadline): Call; +} diff --git a/node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.js b/node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.js new file mode 100644 index 0000000..72343f5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.js @@ -0,0 +1,245 @@ +"use strict"; +/* + * Copyright 2025 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SingleSubchannelChannel = void 0; +const call_number_1 = require("./call-number"); +const channelz_1 = require("./channelz"); +const compression_filter_1 = require("./compression-filter"); +const connectivity_state_1 = require("./connectivity-state"); +const constants_1 = require("./constants"); +const control_plane_status_1 = require("./control-plane-status"); +const deadline_1 = require("./deadline"); +const filter_stack_1 = require("./filter-stack"); +const metadata_1 = require("./metadata"); +const resolver_1 = require("./resolver"); +const uri_parser_1 = require("./uri-parser"); +class SubchannelCallWrapper { + constructor(subchannel, method, filterStackFactory, options, callNumber) { + var _a, _b; + this.subchannel = subchannel; + this.method = method; + this.options = options; + this.callNumber = callNumber; + this.childCall = null; + this.pendingMessage = null; + this.readPending = false; + this.halfClosePending = false; + this.pendingStatus = null; + this.readFilterPending = false; + this.writeFilterPending = false; + const splitPath = this.method.split('/'); + let serviceName = ''; + /* The standard path format is "/{serviceName}/{methodName}", so if we split + * by '/', the first item should be empty and the second should be the + * service name */ + if (splitPath.length >= 2) { + serviceName = splitPath[1]; + } + const hostname = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.options.host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : 'localhost'; + /* Currently, call credentials are only allowed on HTTPS connections, so we + * can assume that the scheme is "https" */ + this.serviceUrl = `https://${hostname}/${serviceName}`; + const timeout = (0, deadline_1.getRelativeTimeout)(options.deadline); + if (timeout !== Infinity) { + if (timeout <= 0) { + this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, 'Deadline exceeded'); + } + else { + setTimeout(() => { + this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, 'Deadline exceeded'); + }, timeout); + } + } + this.filterStack = filterStackFactory.createFilter(); + } + cancelWithStatus(status, details) { + if (this.childCall) { + this.childCall.cancelWithStatus(status, details); + } + else { + this.pendingStatus = { + code: status, + details: details, + metadata: new metadata_1.Metadata() + }; + } + } + getPeer() { + var _a, _b; + return (_b = (_a = this.childCall) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.subchannel.getAddress(); + } + async start(metadata, listener) { + if (this.pendingStatus) { + listener.onReceiveStatus(this.pendingStatus); + return; + } + if (this.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { + listener.onReceiveStatus({ + code: constants_1.Status.UNAVAILABLE, + details: 'Subchannel not ready', + metadata: new metadata_1.Metadata() + }); + return; + } + const filteredMetadata = await this.filterStack.sendMetadata(Promise.resolve(metadata)); + let credsMetadata; + try { + credsMetadata = await this.subchannel.getCallCredentials() + .generateMetadata({ method_name: this.method, service_url: this.serviceUrl }); + } + catch (e) { + const error = e; + const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(typeof error.code === 'number' ? error.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error.message}`); + listener.onReceiveStatus({ + code: code, + details: details, + metadata: new metadata_1.Metadata(), + }); + return; + } + credsMetadata.merge(filteredMetadata); + const childListener = { + onReceiveMetadata: async (metadata) => { + listener.onReceiveMetadata(await this.filterStack.receiveMetadata(metadata)); + }, + onReceiveMessage: async (message) => { + this.readFilterPending = true; + const filteredMessage = await this.filterStack.receiveMessage(message); + this.readFilterPending = false; + listener.onReceiveMessage(filteredMessage); + if (this.pendingStatus) { + listener.onReceiveStatus(this.pendingStatus); + } + }, + onReceiveStatus: async (status) => { + const filteredStatus = await this.filterStack.receiveTrailers(status); + if (this.readFilterPending) { + this.pendingStatus = filteredStatus; + } + else { + listener.onReceiveStatus(filteredStatus); + } + } + }; + this.childCall = this.subchannel.createCall(credsMetadata, this.options.host, this.method, childListener); + if (this.readPending) { + this.childCall.startRead(); + } + if (this.pendingMessage) { + this.childCall.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message); + } + if (this.halfClosePending && !this.writeFilterPending) { + this.childCall.halfClose(); + } + } + async sendMessageWithContext(context, message) { + this.writeFilterPending = true; + const filteredMessage = await this.filterStack.sendMessage(Promise.resolve({ message: message, flags: context.flags })); + this.writeFilterPending = false; + if (this.childCall) { + this.childCall.sendMessageWithContext(context, filteredMessage.message); + if (this.halfClosePending) { + this.childCall.halfClose(); + } + } + else { + this.pendingMessage = { context, message: filteredMessage.message }; + } + } + startRead() { + if (this.childCall) { + this.childCall.startRead(); + } + else { + this.readPending = true; + } + } + halfClose() { + if (this.childCall && !this.writeFilterPending) { + this.childCall.halfClose(); + } + else { + this.halfClosePending = true; + } + } + getCallNumber() { + return this.callNumber; + } + setCredentials(credentials) { + throw new Error("Method not implemented."); + } + getAuthContext() { + if (this.childCall) { + return this.childCall.getAuthContext(); + } + else { + return null; + } + } +} +class SingleSubchannelChannel { + constructor(subchannel, target, options) { + this.subchannel = subchannel; + this.target = target; + this.channelzEnabled = false; + this.channelzTrace = new channelz_1.ChannelzTrace(); + this.callTracker = new channelz_1.ChannelzCallTracker(); + this.childrenTracker = new channelz_1.ChannelzChildrenTracker(); + this.channelzEnabled = options['grpc.enable_channelz'] !== 0; + this.channelzRef = (0, channelz_1.registerChannelzChannel)((0, uri_parser_1.uriToString)(target), () => ({ + target: `${(0, uri_parser_1.uriToString)(target)} (${subchannel.getAddress()})`, + state: this.subchannel.getConnectivityState(), + trace: this.channelzTrace, + callTracker: this.callTracker, + children: this.childrenTracker.getChildLists() + }), this.channelzEnabled); + if (this.channelzEnabled) { + this.childrenTracker.refChild(subchannel.getChannelzRef()); + } + this.filterStackFactory = new filter_stack_1.FilterStackFactory([new compression_filter_1.CompressionFilterFactory(this, options)]); + } + close() { + if (this.channelzEnabled) { + this.childrenTracker.unrefChild(this.subchannel.getChannelzRef()); + } + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + } + getTarget() { + return (0, uri_parser_1.uriToString)(this.target); + } + getConnectivityState(tryToConnect) { + throw new Error("Method not implemented."); + } + watchConnectivityState(currentState, deadline, callback) { + throw new Error("Method not implemented."); + } + getChannelzRef() { + return this.channelzRef; + } + createCall(method, deadline) { + const callOptions = { + deadline: deadline, + host: (0, resolver_1.getDefaultAuthority)(this.target), + flags: constants_1.Propagate.DEFAULTS, + parentCall: null + }; + return new SubchannelCallWrapper(this.subchannel, method, this.filterStackFactory, callOptions, (0, call_number_1.getNextCallNumber)()); + } +} +exports.SingleSubchannelChannel = SingleSubchannelChannel; +//# sourceMappingURL=single-subchannel-channel.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.js.map b/node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.js.map new file mode 100644 index 0000000..8b39287 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"single-subchannel-channel.js","sourceRoot":"","sources":["../../src/single-subchannel-channel.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAKH,+CAAkD;AAGlD,yCAAqJ;AACrJ,6DAAgE;AAChE,6DAAyD;AACzD,2CAAgD;AAChD,iEAAwE;AACxE,yCAA0D;AAC1D,iDAAiE;AACjE,yCAAsC;AACtC,yCAAiD;AAGjD,6CAAmE;AAEnE,MAAM,qBAAqB;IAWzB,YAAoB,UAAsB,EAAU,MAAc,EAAE,kBAAsC,EAAU,OAA0B,EAAU,UAAkB;;QAAtJ,eAAU,GAAV,UAAU,CAAY;QAAU,WAAM,GAAN,MAAM,CAAQ;QAAkD,YAAO,GAAP,OAAO,CAAmB;QAAU,eAAU,GAAV,UAAU,CAAQ;QAVlK,cAAS,GAA0B,IAAI,CAAC;QACxC,mBAAc,GACpB,IAAI,CAAC;QACC,gBAAW,GAAG,KAAK,CAAC;QACpB,qBAAgB,GAAG,KAAK,CAAC;QACzB,kBAAa,GAAwB,IAAI,CAAC;QAG1C,sBAAiB,GAAG,KAAK,CAAC;QAC1B,uBAAkB,GAAG,KAAK,CAAC;QAEjC,MAAM,SAAS,GAAa,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACnD,IAAI,WAAW,GAAG,EAAE,CAAC;QACrB;;2BAEmB;QACnB,IAAI,SAAS,CAAC,MAAM,IAAI,CAAC,EAAE,CAAC;YAC1B,WAAW,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;QAC7B,CAAC;QACD,MAA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kBAAkB,EAAE,WAAW,EAAE,IAAA,+BAAiB,GAAE,CAAC,CAAC;IACvH,CAAC;CACF;AAlDD,0DAkDC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/status-builder.d.ts b/node_modules/@grpc/grpc-js/build/src/status-builder.d.ts new file mode 100644 index 0000000..5628226 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/status-builder.d.ts @@ -0,0 +1,28 @@ +import { StatusObject } from './call-interface'; +import { Status } from './constants'; +import { Metadata } from './metadata'; +/** + * A builder for gRPC status objects. + */ +export declare class StatusBuilder { + private code; + private details; + private metadata; + constructor(); + /** + * Adds a status code to the builder. + */ + withCode(code: Status): this; + /** + * Adds details to the builder. + */ + withDetails(details: string): this; + /** + * Adds metadata to the builder. + */ + withMetadata(metadata: Metadata): this; + /** + * Builds the status object. + */ + build(): Partial; +} diff --git a/node_modules/@grpc/grpc-js/build/src/status-builder.js b/node_modules/@grpc/grpc-js/build/src/status-builder.js new file mode 100644 index 0000000..7426e54 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/status-builder.js @@ -0,0 +1,68 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StatusBuilder = void 0; +/** + * A builder for gRPC status objects. + */ +class StatusBuilder { + constructor() { + this.code = null; + this.details = null; + this.metadata = null; + } + /** + * Adds a status code to the builder. + */ + withCode(code) { + this.code = code; + return this; + } + /** + * Adds details to the builder. + */ + withDetails(details) { + this.details = details; + return this; + } + /** + * Adds metadata to the builder. + */ + withMetadata(metadata) { + this.metadata = metadata; + return this; + } + /** + * Builds the status object. + */ + build() { + const status = {}; + if (this.code !== null) { + status.code = this.code; + } + if (this.details !== null) { + status.details = this.details; + } + if (this.metadata !== null) { + status.metadata = this.metadata; + } + return status; + } +} +exports.StatusBuilder = StatusBuilder; +//# sourceMappingURL=status-builder.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/status-builder.js.map b/node_modules/@grpc/grpc-js/build/src/status-builder.js.map new file mode 100644 index 0000000..33277b2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/status-builder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"status-builder.js","sourceRoot":"","sources":["../../src/status-builder.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAMH;;GAEG;AACH,MAAa,aAAa;IAKxB;QACE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QACpB,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;IACvB,CAAC;IAED;;OAEG;IACH,QAAQ,CAAC,IAAY;QACnB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;OAEG;IACH,WAAW,CAAC,OAAe;QACzB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;OAEG;IACH,YAAY,CAAC,QAAkB;QAC7B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;OAEG;IACH,KAAK;QACH,MAAM,MAAM,GAA0B,EAAE,CAAC;QAEzC,IAAI,IAAI,CAAC,IAAI,KAAK,IAAI,EAAE,CAAC;YACvB,MAAM,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;QAC1B,CAAC;QAED,IAAI,IAAI,CAAC,OAAO,KAAK,IAAI,EAAE,CAAC;YAC1B,MAAM,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAChC,CAAC;QAED,IAAI,IAAI,CAAC,QAAQ,KAAK,IAAI,EAAE,CAAC;YAC3B,MAAM,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAClC,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAvDD,sCAuDC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/stream-decoder.d.ts b/node_modules/@grpc/grpc-js/build/src/stream-decoder.d.ts new file mode 100644 index 0000000..7ff04f3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/stream-decoder.d.ts @@ -0,0 +1,12 @@ +export declare class StreamDecoder { + private maxReadMessageLength; + private readState; + private readCompressFlag; + private readPartialSize; + private readSizeRemaining; + private readMessageSize; + private readPartialMessage; + private readMessageRemaining; + constructor(maxReadMessageLength: number); + write(data: Buffer): Buffer[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/stream-decoder.js b/node_modules/@grpc/grpc-js/build/src/stream-decoder.js new file mode 100644 index 0000000..b3857c0 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/stream-decoder.js @@ -0,0 +1,100 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StreamDecoder = void 0; +var ReadState; +(function (ReadState) { + ReadState[ReadState["NO_DATA"] = 0] = "NO_DATA"; + ReadState[ReadState["READING_SIZE"] = 1] = "READING_SIZE"; + ReadState[ReadState["READING_MESSAGE"] = 2] = "READING_MESSAGE"; +})(ReadState || (ReadState = {})); +class StreamDecoder { + constructor(maxReadMessageLength) { + this.maxReadMessageLength = maxReadMessageLength; + this.readState = ReadState.NO_DATA; + this.readCompressFlag = Buffer.alloc(1); + this.readPartialSize = Buffer.alloc(4); + this.readSizeRemaining = 4; + this.readMessageSize = 0; + this.readPartialMessage = []; + this.readMessageRemaining = 0; + } + write(data) { + let readHead = 0; + let toRead; + const result = []; + while (readHead < data.length) { + switch (this.readState) { + case ReadState.NO_DATA: + this.readCompressFlag = data.slice(readHead, readHead + 1); + readHead += 1; + this.readState = ReadState.READING_SIZE; + this.readPartialSize.fill(0); + this.readSizeRemaining = 4; + this.readMessageSize = 0; + this.readMessageRemaining = 0; + this.readPartialMessage = []; + break; + case ReadState.READING_SIZE: + toRead = Math.min(data.length - readHead, this.readSizeRemaining); + data.copy(this.readPartialSize, 4 - this.readSizeRemaining, readHead, readHead + toRead); + this.readSizeRemaining -= toRead; + readHead += toRead; + // readSizeRemaining >=0 here + if (this.readSizeRemaining === 0) { + this.readMessageSize = this.readPartialSize.readUInt32BE(0); + if (this.maxReadMessageLength !== -1 && this.readMessageSize > this.maxReadMessageLength) { + throw new Error(`Received message larger than max (${this.readMessageSize} vs ${this.maxReadMessageLength})`); + } + this.readMessageRemaining = this.readMessageSize; + if (this.readMessageRemaining > 0) { + this.readState = ReadState.READING_MESSAGE; + } + else { + const message = Buffer.concat([this.readCompressFlag, this.readPartialSize], 5); + this.readState = ReadState.NO_DATA; + result.push(message); + } + } + break; + case ReadState.READING_MESSAGE: + toRead = Math.min(data.length - readHead, this.readMessageRemaining); + this.readPartialMessage.push(data.slice(readHead, readHead + toRead)); + this.readMessageRemaining -= toRead; + readHead += toRead; + // readMessageRemaining >=0 here + if (this.readMessageRemaining === 0) { + // At this point, we have read a full message + const framedMessageBuffers = [ + this.readCompressFlag, + this.readPartialSize, + ].concat(this.readPartialMessage); + const framedMessage = Buffer.concat(framedMessageBuffers, this.readMessageSize + 5); + this.readState = ReadState.NO_DATA; + result.push(framedMessage); + } + break; + default: + throw new Error('Unexpected read state'); + } + } + return result; + } +} +exports.StreamDecoder = StreamDecoder; +//# sourceMappingURL=stream-decoder.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/stream-decoder.js.map b/node_modules/@grpc/grpc-js/build/src/stream-decoder.js.map new file mode 100644 index 0000000..fc6498a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/stream-decoder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stream-decoder.js","sourceRoot":"","sources":["../../src/stream-decoder.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,IAAK,SAIJ;AAJD,WAAK,SAAS;IACZ,+CAAO,CAAA;IACP,yDAAY,CAAA;IACZ,+DAAe,CAAA;AACjB,CAAC,EAJI,SAAS,KAAT,SAAS,QAIb;AAED,MAAa,aAAa;IASxB,YAAoB,oBAA4B;QAA5B,yBAAoB,GAApB,oBAAoB,CAAQ;QARxC,cAAS,GAAc,SAAS,CAAC,OAAO,CAAC;QACzC,qBAAgB,GAAW,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QAC3C,oBAAe,GAAW,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QAC1C,sBAAiB,GAAG,CAAC,CAAC;QACtB,oBAAe,GAAG,CAAC,CAAC;QACpB,uBAAkB,GAAa,EAAE,CAAC;QAClC,yBAAoB,GAAG,CAAC,CAAC;IAEkB,CAAC;IAEpD,KAAK,CAAC,IAAY;QAChB,IAAI,QAAQ,GAAG,CAAC,CAAC;QACjB,IAAI,MAAc,CAAC;QACnB,MAAM,MAAM,GAAa,EAAE,CAAC;QAE5B,OAAO,QAAQ,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;YAC9B,QAAQ,IAAI,CAAC,SAAS,EAAE,CAAC;gBACvB,KAAK,SAAS,CAAC,OAAO;oBACpB,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,QAA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C,CAAC;QACH,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAtFD,sCAsFC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-address.d.ts b/node_modules/@grpc/grpc-js/build/src/subchannel-address.d.ts new file mode 100644 index 0000000..f403563 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-address.d.ts @@ -0,0 +1,42 @@ +export interface TcpSubchannelAddress { + port: number; + host: string; +} +export interface IpcSubchannelAddress { + path: string; +} +/** + * This represents a single backend address to connect to. This interface is a + * subset of net.SocketConnectOpts, i.e. the options described at + * https://nodejs.org/api/net.html#net_socket_connect_options_connectlistener. + * Those are in turn a subset of the options that can be passed to http2.connect. + */ +export type SubchannelAddress = TcpSubchannelAddress | IpcSubchannelAddress; +export declare function isTcpSubchannelAddress(address: SubchannelAddress): address is TcpSubchannelAddress; +export declare function subchannelAddressEqual(address1?: SubchannelAddress, address2?: SubchannelAddress): boolean; +export declare function subchannelAddressToString(address: SubchannelAddress): string; +export declare function stringToSubchannelAddress(addressString: string, port?: number): SubchannelAddress; +export interface Endpoint { + addresses: SubchannelAddress[]; +} +export declare function endpointEqual(endpoint1: Endpoint, endpoint2: Endpoint): boolean; +export declare function endpointToString(endpoint: Endpoint): string; +export declare function endpointHasAddress(endpoint: Endpoint, expectedAddress: SubchannelAddress): boolean; +export declare class EndpointMap { + private map; + get size(): number; + getForSubchannelAddress(address: SubchannelAddress): ValueType | undefined; + /** + * Delete any entries in this map with keys that are not in endpoints + * @param endpoints + */ + deleteMissing(endpoints: Endpoint[]): ValueType[]; + get(endpoint: Endpoint): ValueType | undefined; + set(endpoint: Endpoint, mapEntry: ValueType): void; + delete(endpoint: Endpoint): void; + has(endpoint: Endpoint): boolean; + clear(): void; + keys(): IterableIterator; + values(): IterableIterator; + entries(): IterableIterator<[Endpoint, ValueType]>; +} diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-address.js b/node_modules/@grpc/grpc-js/build/src/subchannel-address.js new file mode 100644 index 0000000..d48d0c2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-address.js @@ -0,0 +1,202 @@ +"use strict"; +/* + * Copyright 2021 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EndpointMap = void 0; +exports.isTcpSubchannelAddress = isTcpSubchannelAddress; +exports.subchannelAddressEqual = subchannelAddressEqual; +exports.subchannelAddressToString = subchannelAddressToString; +exports.stringToSubchannelAddress = stringToSubchannelAddress; +exports.endpointEqual = endpointEqual; +exports.endpointToString = endpointToString; +exports.endpointHasAddress = endpointHasAddress; +const net_1 = require("net"); +function isTcpSubchannelAddress(address) { + return 'port' in address; +} +function subchannelAddressEqual(address1, address2) { + if (!address1 && !address2) { + return true; + } + if (!address1 || !address2) { + return false; + } + if (isTcpSubchannelAddress(address1)) { + return (isTcpSubchannelAddress(address2) && + address1.host === address2.host && + address1.port === address2.port); + } + else { + return !isTcpSubchannelAddress(address2) && address1.path === address2.path; + } +} +function subchannelAddressToString(address) { + if (isTcpSubchannelAddress(address)) { + if ((0, net_1.isIPv6)(address.host)) { + return '[' + address.host + ']:' + address.port; + } + else { + return address.host + ':' + address.port; + } + } + else { + return address.path; + } +} +const DEFAULT_PORT = 443; +function stringToSubchannelAddress(addressString, port) { + if ((0, net_1.isIP)(addressString)) { + return { + host: addressString, + port: port !== null && port !== void 0 ? port : DEFAULT_PORT, + }; + } + else { + return { + path: addressString, + }; + } +} +function endpointEqual(endpoint1, endpoint2) { + if (endpoint1.addresses.length !== endpoint2.addresses.length) { + return false; + } + for (let i = 0; i < endpoint1.addresses.length; i++) { + if (!subchannelAddressEqual(endpoint1.addresses[i], endpoint2.addresses[i])) { + return false; + } + } + return true; +} +function endpointToString(endpoint) { + return ('[' + endpoint.addresses.map(subchannelAddressToString).join(', ') + ']'); +} +function endpointHasAddress(endpoint, expectedAddress) { + for (const address of endpoint.addresses) { + if (subchannelAddressEqual(address, expectedAddress)) { + return true; + } + } + return false; +} +function endpointEqualUnordered(endpoint1, endpoint2) { + if (endpoint1.addresses.length !== endpoint2.addresses.length) { + return false; + } + for (const address1 of endpoint1.addresses) { + let matchFound = false; + for (const address2 of endpoint2.addresses) { + if (subchannelAddressEqual(address1, address2)) { + matchFound = true; + break; + } + } + if (!matchFound) { + return false; + } + } + return true; +} +class EndpointMap { + constructor() { + this.map = new Set(); + } + get size() { + return this.map.size; + } + getForSubchannelAddress(address) { + for (const entry of this.map) { + if (endpointHasAddress(entry.key, address)) { + return entry.value; + } + } + return undefined; + } + /** + * Delete any entries in this map with keys that are not in endpoints + * @param endpoints + */ + deleteMissing(endpoints) { + const removedValues = []; + for (const entry of this.map) { + let foundEntry = false; + for (const endpoint of endpoints) { + if (endpointEqualUnordered(endpoint, entry.key)) { + foundEntry = true; + } + } + if (!foundEntry) { + removedValues.push(entry.value); + this.map.delete(entry); + } + } + return removedValues; + } + get(endpoint) { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint, entry.key)) { + return entry.value; + } + } + return undefined; + } + set(endpoint, mapEntry) { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint, entry.key)) { + entry.value = mapEntry; + return; + } + } + this.map.add({ key: endpoint, value: mapEntry }); + } + delete(endpoint) { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint, entry.key)) { + this.map.delete(entry); + return; + } + } + } + has(endpoint) { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint, entry.key)) { + return true; + } + } + return false; + } + clear() { + this.map.clear(); + } + *keys() { + for (const entry of this.map) { + yield entry.key; + } + } + *values() { + for (const entry of this.map) { + yield entry.value; + } + } + *entries() { + for (const entry of this.map) { + yield [entry.key, entry.value]; + } + } +} +exports.EndpointMap = EndpointMap; +//# sourceMappingURL=subchannel-address.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-address.js.map b/node_modules/@grpc/grpc-js/build/src/subchannel-address.js.map new file mode 100644 index 0000000..8dd5aed --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-address.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subchannel-address.js","sourceRoot":"","sources":["../../src/subchannel-address.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAqBH,wDAIC;AAED,wDAmBC;AAED,8DAUC;AAID,8DAcC;AAMD,sCAYC;AAED,4CAIC;AAED,gDAUC;AA9GD,6BAAmC;AAmBnC,SAAgB,sBAAsB,CACpC,OAA0B;IAE1B,OAAO,MAAM,IAAI,OAAO,CAAC;AAC3B,CAAC;AAED,SAAgB,sBAAsB,CACpC,QAA4B,EAC5B,QAA4B;IAE5B,IAAI,CAAC,QAAQ,IAAI,CAAC,QAAQ,EAAE,CAAC;QAC3B,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,CAAC,QAAQ,IAAI,CAAC,QAAQ,EAAE,CAAC;QAC3B,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IAAI,sBAAsB,CAAC,QAAQ,CAAC,EAAE,CAAC;QACrC,OAAO,CACL,sBAAsB,CAAC,QAAQ,CAAC;YAChC,QAAQ,CAAC,IAAI,KAAK,QAAQ,CAAC,IAAI;YAC/B,QAAQ,CAAC,IAAI,KAAK,QAAQ,CAAC,IAAI,CAChC,CAAC;IACJ,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,sBAAsB,CAAC,QAAQ,CAAC,IAAI,QAAQ,CAAC,IAAI,KAAK,QAAQ,CAAC,IAAI,CAAC;IAC9E,CAAC;AACH,CAAC;AAED,SAAgB,yBAAyB,CAAC,OAA0B;IAClE,IAAI,sBAAsB,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d.ts b/node_modules/@grpc/grpc-js/build/src/subchannel-call.d.ts new file mode 100644 index 0000000..3f534c9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-call.d.ts @@ -0,0 +1,68 @@ +import * as http2 from 'http2'; +import { Status } from './constants'; +import { InterceptingListener, MessageContext, StatusObject } from './call-interface'; +import { CallEventTracker, Transport } from './transport'; +import { AuthContext } from './auth-context'; +export interface SubchannelCall { + cancelWithStatus(status: Status, details: string): void; + getPeer(): string; + sendMessageWithContext(context: MessageContext, message: Buffer): void; + startRead(): void; + halfClose(): void; + getCallNumber(): number; + getDeadlineInfo(): string[]; + getAuthContext(): AuthContext; +} +export interface StatusObjectWithRstCode extends StatusObject { + rstCode?: number; +} +export interface SubchannelCallInterceptingListener extends InterceptingListener { + onReceiveStatus(status: StatusObjectWithRstCode): void; +} +export declare class Http2SubchannelCall implements SubchannelCall { + private readonly http2Stream; + private readonly callEventTracker; + private readonly listener; + private readonly transport; + private readonly callId; + private decoder; + private isReadFilterPending; + private isPushPending; + private canPush; + /** + * Indicates that an 'end' event has come from the http2 stream, so there + * will be no more data events. + */ + private readsClosed; + private statusOutput; + private unpushedReadMessages; + private httpStatusCode; + private finalStatus; + private internalError; + private serverEndedCall; + private connectionDropped; + constructor(http2Stream: http2.ClientHttp2Stream, callEventTracker: CallEventTracker, listener: SubchannelCallInterceptingListener, transport: Transport, callId: number); + getDeadlineInfo(): string[]; + onDisconnect(): void; + private outputStatus; + private trace; + /** + * On first call, emits a 'status' event with the given StatusObject. + * Subsequent calls are no-ops. + * @param status The status of the call. + */ + private endCall; + private maybeOutputStatus; + private push; + private tryPush; + private handleTrailers; + private destroyHttp2Stream; + cancelWithStatus(status: Status, details: string): void; + getStatus(): StatusObject | null; + getPeer(): string; + getCallNumber(): number; + getAuthContext(): AuthContext; + startRead(): void; + sendMessageWithContext(context: MessageContext, message: Buffer): void; + halfClose(): void; +} diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-call.js b/node_modules/@grpc/grpc-js/build/src/subchannel-call.js new file mode 100644 index 0000000..e448ad3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-call.js @@ -0,0 +1,545 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Http2SubchannelCall = void 0; +const http2 = require("http2"); +const os = require("os"); +const constants_1 = require("./constants"); +const metadata_1 = require("./metadata"); +const stream_decoder_1 = require("./stream-decoder"); +const logging = require("./logging"); +const constants_2 = require("./constants"); +const TRACER_NAME = 'subchannel_call'; +/** + * Should do approximately the same thing as util.getSystemErrorName but the + * TypeScript types don't have that function for some reason so I just made my + * own. + * @param errno + */ +function getSystemErrorName(errno) { + for (const [name, num] of Object.entries(os.constants.errno)) { + if (num === errno) { + return name; + } + } + return 'Unknown system error ' + errno; +} +function mapHttpStatusCode(code) { + const details = `Received HTTP status code ${code}`; + let mappedStatusCode; + switch (code) { + // TODO(murgatroid99): handle 100 and 101 + case 400: + mappedStatusCode = constants_1.Status.INTERNAL; + break; + case 401: + mappedStatusCode = constants_1.Status.UNAUTHENTICATED; + break; + case 403: + mappedStatusCode = constants_1.Status.PERMISSION_DENIED; + break; + case 404: + mappedStatusCode = constants_1.Status.UNIMPLEMENTED; + break; + case 429: + case 502: + case 503: + case 504: + mappedStatusCode = constants_1.Status.UNAVAILABLE; + break; + default: + mappedStatusCode = constants_1.Status.UNKNOWN; + } + return { + code: mappedStatusCode, + details: details, + metadata: new metadata_1.Metadata() + }; +} +class Http2SubchannelCall { + constructor(http2Stream, callEventTracker, listener, transport, callId) { + var _a; + this.http2Stream = http2Stream; + this.callEventTracker = callEventTracker; + this.listener = listener; + this.transport = transport; + this.callId = callId; + this.isReadFilterPending = false; + this.isPushPending = false; + this.canPush = false; + /** + * Indicates that an 'end' event has come from the http2 stream, so there + * will be no more data events. + */ + this.readsClosed = false; + this.statusOutput = false; + this.unpushedReadMessages = []; + // This is populated (non-null) if and only if the call has ended + this.finalStatus = null; + this.internalError = null; + this.serverEndedCall = false; + this.connectionDropped = false; + const maxReceiveMessageLength = (_a = transport.getOptions()['grpc.max_receive_message_length']) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; + this.decoder = new stream_decoder_1.StreamDecoder(maxReceiveMessageLength); + http2Stream.on('response', (headers, flags) => { + let headersString = ''; + for (const header of Object.keys(headers)) { + headersString += '\t\t' + header + ': ' + headers[header] + '\n'; + } + this.trace('Received server headers:\n' + headersString); + this.httpStatusCode = headers[':status']; + if (flags & http2.constants.NGHTTP2_FLAG_END_STREAM) { + this.handleTrailers(headers); + } + else { + let metadata; + try { + metadata = metadata_1.Metadata.fromHttp2Headers(headers); + } + catch (error) { + this.endCall({ + code: constants_1.Status.UNKNOWN, + details: error.message, + metadata: new metadata_1.Metadata(), + }); + return; + } + this.listener.onReceiveMetadata(metadata); + } + }); + http2Stream.on('trailers', (headers) => { + this.handleTrailers(headers); + }); + http2Stream.on('data', (data) => { + /* If the status has already been output, allow the http2 stream to + * drain without processing the data. */ + if (this.statusOutput) { + return; + } + this.trace('receive HTTP/2 data frame of length ' + data.length); + let messages; + try { + messages = this.decoder.write(data); + } + catch (e) { + /* Some servers send HTML error pages along with HTTP status codes. + * When the client attempts to parse this as a length-delimited + * message, the parsed message size is greater than the default limit, + * resulting in a message decoding error. In that situation, the HTTP + * error code information is more useful to the user than the + * RESOURCE_EXHAUSTED error is, so we report that instead. Normally, + * we delay processing the HTTP status until after the stream ends, to + * prioritize reporting the gRPC status from trailers if it is present, + * but when there is a message parsing error we end the stream early + * before processing trailers. */ + if (this.httpStatusCode !== undefined && this.httpStatusCode !== 200) { + const mappedStatus = mapHttpStatusCode(this.httpStatusCode); + this.cancelWithStatus(mappedStatus.code, mappedStatus.details); + } + else { + this.cancelWithStatus(constants_1.Status.RESOURCE_EXHAUSTED, e.message); + } + return; + } + for (const message of messages) { + this.trace('parsed message of length ' + message.length); + this.callEventTracker.addMessageReceived(); + this.tryPush(message); + } + }); + http2Stream.on('end', () => { + this.readsClosed = true; + this.maybeOutputStatus(); + }); + http2Stream.on('close', () => { + this.serverEndedCall = true; + /* Use process.next tick to ensure that this code happens after any + * "error" event that may be emitted at about the same time, so that + * we can bubble up the error message from that event. */ + process.nextTick(() => { + var _a; + this.trace('HTTP/2 stream closed with code ' + http2Stream.rstCode); + /* If we have a final status with an OK status code, that means that + * we have received all of the messages and we have processed the + * trailers and the call completed successfully, so it doesn't matter + * how the stream ends after that */ + if (((_a = this.finalStatus) === null || _a === void 0 ? void 0 : _a.code) === constants_1.Status.OK) { + return; + } + let code; + let details = ''; + switch (http2Stream.rstCode) { + case http2.constants.NGHTTP2_NO_ERROR: + /* If we get a NO_ERROR code and we already have a status, the + * stream completed properly and we just haven't fully processed + * it yet */ + if (this.finalStatus !== null) { + return; + } + if (this.httpStatusCode && this.httpStatusCode !== 200) { + const mappedStatus = mapHttpStatusCode(this.httpStatusCode); + code = mappedStatus.code; + details = mappedStatus.details; + } + else { + code = constants_1.Status.INTERNAL; + details = `Received RST_STREAM with code ${http2Stream.rstCode} (Call ended without gRPC status)`; + } + break; + case http2.constants.NGHTTP2_REFUSED_STREAM: + code = constants_1.Status.UNAVAILABLE; + details = 'Stream refused by server'; + break; + case http2.constants.NGHTTP2_CANCEL: + /* Bug reports indicate that Node synthesizes a NGHTTP2_CANCEL + * code from connection drops. We want to prioritize reporting + * an unavailable status when that happens. */ + if (this.connectionDropped) { + code = constants_1.Status.UNAVAILABLE; + details = 'Connection dropped'; + } + else { + code = constants_1.Status.CANCELLED; + details = 'Call cancelled'; + } + break; + case http2.constants.NGHTTP2_ENHANCE_YOUR_CALM: + code = constants_1.Status.RESOURCE_EXHAUSTED; + details = 'Bandwidth exhausted or memory limit exceeded'; + break; + case http2.constants.NGHTTP2_INADEQUATE_SECURITY: + code = constants_1.Status.PERMISSION_DENIED; + details = 'Protocol not secure enough'; + break; + case http2.constants.NGHTTP2_INTERNAL_ERROR: + code = constants_1.Status.INTERNAL; + if (this.internalError === null) { + /* This error code was previously handled in the default case, and + * there are several instances of it online, so I wanted to + * preserve the original error message so that people find existing + * information in searches, but also include the more recognizable + * "Internal server error" message. */ + details = `Received RST_STREAM with code ${http2Stream.rstCode} (Internal server error)`; + } + else { + if (this.internalError.code === 'ECONNRESET' || + this.internalError.code === 'ETIMEDOUT') { + code = constants_1.Status.UNAVAILABLE; + details = this.internalError.message; + } + else { + /* The "Received RST_STREAM with code ..." error is preserved + * here for continuity with errors reported online, but the + * error message at the end will probably be more relevant in + * most cases. */ + details = `Received RST_STREAM with code ${http2Stream.rstCode} triggered by internal client error: ${this.internalError.message}`; + } + } + break; + default: + code = constants_1.Status.INTERNAL; + details = `Received RST_STREAM with code ${http2Stream.rstCode}`; + } + // This is a no-op if trailers were received at all. + // This is OK, because status codes emitted here correspond to more + // catastrophic issues that prevent us from receiving trailers in the + // first place. + this.endCall({ + code, + details, + metadata: new metadata_1.Metadata(), + rstCode: http2Stream.rstCode, + }); + }); + }); + http2Stream.on('error', (err) => { + /* We need an error handler here to stop "Uncaught Error" exceptions + * from bubbling up. However, errors here should all correspond to + * "close" events, where we will handle the error more granularly */ + /* Specifically looking for stream errors that were *not* constructed + * from a RST_STREAM response here: + * https://github.com/nodejs/node/blob/8b8620d580314050175983402dfddf2674e8e22a/lib/internal/http2/core.js#L2267 + */ + if (err.code !== 'ERR_HTTP2_STREAM_ERROR') { + this.trace('Node error event: message=' + + err.message + + ' code=' + + err.code + + ' errno=' + + getSystemErrorName(err.errno) + + ' syscall=' + + err.syscall); + this.internalError = err; + } + this.callEventTracker.onStreamEnd(false); + }); + } + getDeadlineInfo() { + return [`remote_addr=${this.getPeer()}`]; + } + onDisconnect() { + this.connectionDropped = true; + /* Give the call an event loop cycle to finish naturally before reporting + * the disconnection as an error. */ + setImmediate(() => { + this.endCall({ + code: constants_1.Status.UNAVAILABLE, + details: 'Connection dropped', + metadata: new metadata_1.Metadata(), + }); + }); + } + outputStatus() { + /* Precondition: this.finalStatus !== null */ + if (!this.statusOutput) { + this.statusOutput = true; + this.trace('ended with status: code=' + + this.finalStatus.code + + ' details="' + + this.finalStatus.details + + '"'); + this.callEventTracker.onCallEnd(this.finalStatus); + /* We delay the actual action of bubbling up the status to insulate the + * cleanup code in this class from any errors that may be thrown in the + * upper layers as a result of bubbling up the status. In particular, + * if the status is not OK, the "error" event may be emitted + * synchronously at the top level, which will result in a thrown error if + * the user does not handle that event. */ + process.nextTick(() => { + this.listener.onReceiveStatus(this.finalStatus); + }); + /* Leave the http2 stream in flowing state to drain incoming messages, to + * ensure that the stream closure completes. The call stream already does + * not push more messages after the status is output, so the messages go + * nowhere either way. */ + this.http2Stream.resume(); + } + } + trace(text) { + logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callId + '] ' + text); + } + /** + * On first call, emits a 'status' event with the given StatusObject. + * Subsequent calls are no-ops. + * @param status The status of the call. + */ + endCall(status) { + /* If the status is OK and a new status comes in (e.g. from a + * deserialization failure), that new status takes priority */ + if (this.finalStatus === null || this.finalStatus.code === constants_1.Status.OK) { + this.finalStatus = status; + this.maybeOutputStatus(); + } + this.destroyHttp2Stream(); + } + maybeOutputStatus() { + if (this.finalStatus !== null) { + /* The combination check of readsClosed and that the two message buffer + * arrays are empty checks that there all incoming data has been fully + * processed */ + if (this.finalStatus.code !== constants_1.Status.OK || + (this.readsClosed && + this.unpushedReadMessages.length === 0 && + !this.isReadFilterPending && + !this.isPushPending)) { + this.outputStatus(); + } + } + } + push(message) { + this.trace('pushing to reader message of length ' + + (message instanceof Buffer ? message.length : null)); + this.canPush = false; + this.isPushPending = true; + process.nextTick(() => { + this.isPushPending = false; + /* If we have already output the status any later messages should be + * ignored, and can cause out-of-order operation errors higher up in the + * stack. Checking as late as possible here to avoid any race conditions. + */ + if (this.statusOutput) { + return; + } + this.listener.onReceiveMessage(message); + this.maybeOutputStatus(); + }); + } + tryPush(messageBytes) { + if (this.canPush) { + this.http2Stream.pause(); + this.push(messageBytes); + } + else { + this.trace('unpushedReadMessages.push message of length ' + messageBytes.length); + this.unpushedReadMessages.push(messageBytes); + } + } + handleTrailers(headers) { + this.serverEndedCall = true; + this.callEventTracker.onStreamEnd(true); + let headersString = ''; + for (const header of Object.keys(headers)) { + headersString += '\t\t' + header + ': ' + headers[header] + '\n'; + } + this.trace('Received server trailers:\n' + headersString); + let metadata; + try { + metadata = metadata_1.Metadata.fromHttp2Headers(headers); + } + catch (e) { + metadata = new metadata_1.Metadata(); + } + const metadataMap = metadata.getMap(); + let status; + if (typeof metadataMap['grpc-status'] === 'string') { + const receivedStatus = Number(metadataMap['grpc-status']); + this.trace('received status code ' + receivedStatus + ' from server'); + metadata.remove('grpc-status'); + let details = ''; + if (typeof metadataMap['grpc-message'] === 'string') { + try { + details = decodeURI(metadataMap['grpc-message']); + } + catch (e) { + details = metadataMap['grpc-message']; + } + metadata.remove('grpc-message'); + this.trace('received status details string "' + details + '" from server'); + } + status = { + code: receivedStatus, + details: details, + metadata: metadata + }; + } + else if (this.httpStatusCode) { + status = mapHttpStatusCode(this.httpStatusCode); + status.metadata = metadata; + } + else { + status = { + code: constants_1.Status.UNKNOWN, + details: 'No status information received', + metadata: metadata + }; + } + // This is a no-op if the call was already ended when handling headers. + this.endCall(status); + } + destroyHttp2Stream() { + var _a; + // The http2 stream could already have been destroyed if cancelWithStatus + // is called in response to an internal http2 error. + if (this.http2Stream.destroyed) { + return; + } + /* If the server ended the call, sending an RST_STREAM is redundant, so we + * just half close on the client side instead to finish closing the stream. + */ + if (this.serverEndedCall) { + this.http2Stream.end(); + } + else { + /* If the call has ended with an OK status, communicate that when closing + * the stream, partly to avoid a situation in which we detect an error + * RST_STREAM as a result after we have the status */ + let code; + if (((_a = this.finalStatus) === null || _a === void 0 ? void 0 : _a.code) === constants_1.Status.OK) { + code = http2.constants.NGHTTP2_NO_ERROR; + } + else { + code = http2.constants.NGHTTP2_CANCEL; + } + this.trace('close http2 stream with code ' + code); + this.http2Stream.close(code); + } + } + cancelWithStatus(status, details) { + this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"'); + this.endCall({ code: status, details, metadata: new metadata_1.Metadata() }); + } + getStatus() { + return this.finalStatus; + } + getPeer() { + return this.transport.getPeerName(); + } + getCallNumber() { + return this.callId; + } + getAuthContext() { + return this.transport.getAuthContext(); + } + startRead() { + /* If the stream has ended with an error, we should not emit any more + * messages and we should communicate that the stream has ended */ + if (this.finalStatus !== null && this.finalStatus.code !== constants_1.Status.OK) { + this.readsClosed = true; + this.maybeOutputStatus(); + return; + } + this.canPush = true; + if (this.unpushedReadMessages.length > 0) { + const nextMessage = this.unpushedReadMessages.shift(); + this.push(nextMessage); + return; + } + /* Only resume reading from the http2Stream if we don't have any pending + * messages to emit */ + this.http2Stream.resume(); + } + sendMessageWithContext(context, message) { + this.trace('write() called with message of length ' + message.length); + const cb = (error) => { + /* nextTick here ensures that no stream action can be taken in the call + * stack of the write callback, in order to hopefully work around + * https://github.com/nodejs/node/issues/49147 */ + process.nextTick(() => { + var _a; + let code = constants_1.Status.UNAVAILABLE; + if ((error === null || error === void 0 ? void 0 : error.code) === + 'ERR_STREAM_WRITE_AFTER_END') { + code = constants_1.Status.INTERNAL; + } + if (error) { + this.cancelWithStatus(code, `Write error: ${error.message}`); + } + (_a = context.callback) === null || _a === void 0 ? void 0 : _a.call(context); + }); + }; + this.trace('sending data chunk of length ' + message.length); + this.callEventTracker.addMessageSent(); + try { + this.http2Stream.write(message, cb); + } + catch (error) { + this.endCall({ + code: constants_1.Status.UNAVAILABLE, + details: `Write failed with error ${error.message}`, + metadata: new metadata_1.Metadata(), + }); + } + } + halfClose() { + this.trace('end() called'); + this.trace('calling end() on HTTP/2 stream'); + this.http2Stream.end(); + } +} +exports.Http2SubchannelCall = Http2SubchannelCall; +//# sourceMappingURL=subchannel-call.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-call.js.map b/node_modules/@grpc/grpc-js/build/src/subchannel-call.js.map new file mode 100644 index 0000000..2c2e09f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-call.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subchannel-call.js","sourceRoot":"","sources":["../../src/subchannel-call.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,+BAA+B;AAC/B,yBAAyB;AAEzB,2CAAyE;AACzE,yCAAsC;AACtC,qDAAiD;AACjD,qCAAqC;AACrC,2CAA2C;AAU3C,MAAM,WAAW,GAAG,iBAAiB,CAAC;AAiBtC;;;;;GAKG;AACH,SAAS,kBAAkB,CAAC,KAAa;IACvC,KAAK,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC;QAC7D,IAAI,GAAG,KAAK,KAAK,EAAE,CAAC;YAClB,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,uBAAuB,GAAG,KAAK,CAAC;AACzC,CAAC;AAsBD,SAAS,iBAAiB,CAAC,IAAY;IACrC,MAAM,OAAO,GAAG,6BAA6B,IAAI,EAAE,CAAC;IACpD,IAAI,gBAAwB,CAAC;IAC7B,QAAQ,IAAI,EAAE,CAAC;QACb,yCAAyC;QACzC,KAAK,GAAG;YACN,gBAAgB,GAAG,kBAAM,CAAC,QAAQ,CAAC;YACnC,MAAM;QACR,KAAK,GAAG;YACN,gBAAgB,GAAG,kBAAM,CAAC,eAAe,CAAC;YAC1C,MAAM;QACR,KAAK,GAAG;YACN,gBAAgB,GAAG,kBAAM,C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,GAAW,kBAAM,CAAC,WAAW,CAAC;gBACtC,IACE,CAAC,KAA+B,aAA/B,KAAK,uBAAL,KAAK,CAA4B,IAAI;oBACtC,4BAA4B,EAC5B,CAAC;oBACD,IAAI,GAAG,kBAAM,CAAC,QAAQ,CAAC;gBACzB,CAAC;gBACD,IAAI,KAAK,EAAE,CAAC;oBACV,IAAI,CAAC,gBAAgB,CAAC,IAAI,EAAE,gBAAgB,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;gBAC/D,CAAC;gBACD,MAAA,OAAO,CAAC,QAAQ,uDAAI,CAAC;YACvB,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;QACF,IAAI,CAAC,KAAK,CAAC,+BAA+B,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;QAC7D,IAAI,CAAC,gBAAgB,CAAC,cAAc,EAAE,CAAC;QACvC,IAAI,CAAC;YACH,IAAI,CAAC,WAAY,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;QACvC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,OAAO,CAAC;gBACX,IAAI,EAAE,kBAAM,CAAC,WAAW;gBACxB,OAAO,EAAE,2BAA4B,KAAe,CAAC,OAAO,EAAE;gBAC9D,QAAQ,EAAE,IAAI,mBAAQ,EAAE;aACzB,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,SAAS;QACP,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;QAC3B,IAAI,CAAC,KAAK,CAAC,gCAAgC,CAAC,CAAC;QAC7C,IAAI,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC;IACzB,CAAC;CACF;AAtfD,kDAsfC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-interface.d.ts b/node_modules/@grpc/grpc-js/build/src/subchannel-interface.d.ts new file mode 100644 index 0000000..7b1eb81 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-interface.d.ts @@ -0,0 +1,82 @@ +import { CallCredentials } from './call-credentials'; +import { Channel } from './channel'; +import type { SubchannelRef } from './channelz'; +import { ConnectivityState } from './connectivity-state'; +import { Subchannel } from './subchannel'; +export type ConnectivityStateListener = (subchannel: SubchannelInterface, previousState: ConnectivityState, newState: ConnectivityState, keepaliveTime: number, errorMessage?: string) => void; +export type HealthListener = (healthy: boolean) => void; +export interface DataWatcher { + setSubchannel(subchannel: Subchannel): void; + destroy(): void; +} +/** + * This is an interface for load balancing policies to use to interact with + * subchannels. This allows load balancing policies to wrap and unwrap + * subchannels. + * + * Any load balancing policy that wraps subchannels must unwrap the subchannel + * in the picker, so that other load balancing policies consistently have + * access to their own wrapper objects. + */ +export interface SubchannelInterface { + getConnectivityState(): ConnectivityState; + addConnectivityStateListener(listener: ConnectivityStateListener): void; + removeConnectivityStateListener(listener: ConnectivityStateListener): void; + startConnecting(): void; + getAddress(): string; + throttleKeepalive(newKeepaliveTime: number): void; + ref(): void; + unref(): void; + getChannelzRef(): SubchannelRef; + isHealthy(): boolean; + addHealthStateWatcher(listener: HealthListener): void; + removeHealthStateWatcher(listener: HealthListener): void; + addDataWatcher(dataWatcher: DataWatcher): void; + /** + * If this is a wrapper, return the wrapped subchannel, otherwise return this + */ + getRealSubchannel(): Subchannel; + /** + * Returns true if this and other both proxy the same underlying subchannel. + * Can be used instead of directly accessing getRealSubchannel to allow mocks + * to avoid implementing getRealSubchannel + */ + realSubchannelEquals(other: SubchannelInterface): boolean; + /** + * Get the call credentials associated with the channel credentials for this + * subchannel. + */ + getCallCredentials(): CallCredentials; + /** + * Get a channel that can be used to make requests with just this + */ + getChannel(): Channel; +} +export declare abstract class BaseSubchannelWrapper implements SubchannelInterface { + protected child: SubchannelInterface; + private healthy; + private healthListeners; + private refcount; + private dataWatchers; + constructor(child: SubchannelInterface); + private updateHealthListeners; + getConnectivityState(): ConnectivityState; + addConnectivityStateListener(listener: ConnectivityStateListener): void; + removeConnectivityStateListener(listener: ConnectivityStateListener): void; + startConnecting(): void; + getAddress(): string; + throttleKeepalive(newKeepaliveTime: number): void; + ref(): void; + unref(): void; + protected destroy(): void; + getChannelzRef(): SubchannelRef; + isHealthy(): boolean; + addHealthStateWatcher(listener: HealthListener): void; + removeHealthStateWatcher(listener: HealthListener): void; + addDataWatcher(dataWatcher: DataWatcher): void; + protected setHealthy(healthy: boolean): void; + getRealSubchannel(): Subchannel; + realSubchannelEquals(other: SubchannelInterface): boolean; + getCallCredentials(): CallCredentials; + getChannel(): Channel; +} diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-interface.js b/node_modules/@grpc/grpc-js/build/src/subchannel-interface.js new file mode 100644 index 0000000..6faf71a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-interface.js @@ -0,0 +1,114 @@ +"use strict"; +/* + * Copyright 2022 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BaseSubchannelWrapper = void 0; +class BaseSubchannelWrapper { + constructor(child) { + this.child = child; + this.healthy = true; + this.healthListeners = new Set(); + this.refcount = 0; + this.dataWatchers = new Set(); + child.addHealthStateWatcher(childHealthy => { + /* A change to the child health state only affects this wrapper's overall + * health state if this wrapper is reporting healthy. */ + if (this.healthy) { + this.updateHealthListeners(); + } + }); + } + updateHealthListeners() { + for (const listener of this.healthListeners) { + listener(this.isHealthy()); + } + } + getConnectivityState() { + return this.child.getConnectivityState(); + } + addConnectivityStateListener(listener) { + this.child.addConnectivityStateListener(listener); + } + removeConnectivityStateListener(listener) { + this.child.removeConnectivityStateListener(listener); + } + startConnecting() { + this.child.startConnecting(); + } + getAddress() { + return this.child.getAddress(); + } + throttleKeepalive(newKeepaliveTime) { + this.child.throttleKeepalive(newKeepaliveTime); + } + ref() { + this.child.ref(); + this.refcount += 1; + } + unref() { + this.child.unref(); + this.refcount -= 1; + if (this.refcount === 0) { + this.destroy(); + } + } + destroy() { + for (const watcher of this.dataWatchers) { + watcher.destroy(); + } + } + getChannelzRef() { + return this.child.getChannelzRef(); + } + isHealthy() { + return this.healthy && this.child.isHealthy(); + } + addHealthStateWatcher(listener) { + this.healthListeners.add(listener); + } + removeHealthStateWatcher(listener) { + this.healthListeners.delete(listener); + } + addDataWatcher(dataWatcher) { + dataWatcher.setSubchannel(this.getRealSubchannel()); + this.dataWatchers.add(dataWatcher); + } + setHealthy(healthy) { + if (healthy !== this.healthy) { + this.healthy = healthy; + /* A change to this wrapper's health state only affects the overall + * reported health state if the child is healthy. */ + if (this.child.isHealthy()) { + this.updateHealthListeners(); + } + } + } + getRealSubchannel() { + return this.child.getRealSubchannel(); + } + realSubchannelEquals(other) { + return this.getRealSubchannel() === other.getRealSubchannel(); + } + getCallCredentials() { + return this.child.getCallCredentials(); + } + getChannel() { + return this.child.getChannel(); + } +} +exports.BaseSubchannelWrapper = BaseSubchannelWrapper; +//# sourceMappingURL=subchannel-interface.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-interface.js.map b/node_modules/@grpc/grpc-js/build/src/subchannel-interface.js.map new file mode 100644 index 0000000..d298ea0 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-interface.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subchannel-interface.js","sourceRoot":"","sources":["../../src/subchannel-interface.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAmEH,MAAsB,qBAAqB;IAKzC,YAAsB,KAA0B;QAA1B,UAAK,GAAL,KAAK,CAAqB;QAJxC,YAAO,GAAG,IAAI,CAAC;QACf,oBAAe,GAAwB,IAAI,GAAG,EAAE,CAAC;QACjD,aAAQ,GA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AAC,kBAAkB,EAAE,CAAC;IACzC,CAAC;IACD,UAAU;QACN,OAAO,IAAI,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC;IACnC,CAAC;CACF;AA7FD,sDA6FC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-pool.d.ts b/node_modules/@grpc/grpc-js/build/src/subchannel-pool.d.ts new file mode 100644 index 0000000..9c00300 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-pool.d.ts @@ -0,0 +1,40 @@ +import { ChannelOptions } from './channel-options'; +import { Subchannel } from './subchannel'; +import { SubchannelAddress } from './subchannel-address'; +import { ChannelCredentials } from './channel-credentials'; +import { GrpcUri } from './uri-parser'; +export declare class SubchannelPool { + private pool; + /** + * A timer of a task performing a periodic subchannel cleanup. + */ + private cleanupTimer; + /** + * A pool of subchannels use for making connections. Subchannels with the + * exact same parameters will be reused. + */ + constructor(); + /** + * Unrefs all unused subchannels and cancels the cleanup task if all + * subchannels have been unrefed. + */ + unrefUnusedSubchannels(): void; + /** + * Ensures that the cleanup task is spawned. + */ + ensureCleanupTask(): void; + /** + * Get a subchannel if one already exists with exactly matching parameters. + * Otherwise, create and save a subchannel with those parameters. + * @param channelTarget + * @param subchannelTarget + * @param channelArguments + * @param channelCredentials + */ + getOrCreateSubchannel(channelTargetUri: GrpcUri, subchannelTarget: SubchannelAddress, channelArguments: ChannelOptions, channelCredentials: ChannelCredentials): Subchannel; +} +/** + * Get either the global subchannel pool, or a new subchannel pool. + * @param global + */ +export declare function getSubchannelPool(global: boolean): SubchannelPool; diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-pool.js b/node_modules/@grpc/grpc-js/build/src/subchannel-pool.js new file mode 100644 index 0000000..e10d66d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-pool.js @@ -0,0 +1,137 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SubchannelPool = void 0; +exports.getSubchannelPool = getSubchannelPool; +const channel_options_1 = require("./channel-options"); +const subchannel_1 = require("./subchannel"); +const subchannel_address_1 = require("./subchannel-address"); +const uri_parser_1 = require("./uri-parser"); +const transport_1 = require("./transport"); +// 10 seconds in milliseconds. This value is arbitrary. +/** + * The amount of time in between checks for dropping subchannels that have no + * other references + */ +const REF_CHECK_INTERVAL = 10000; +class SubchannelPool { + /** + * A pool of subchannels use for making connections. Subchannels with the + * exact same parameters will be reused. + */ + constructor() { + this.pool = Object.create(null); + /** + * A timer of a task performing a periodic subchannel cleanup. + */ + this.cleanupTimer = null; + } + /** + * Unrefs all unused subchannels and cancels the cleanup task if all + * subchannels have been unrefed. + */ + unrefUnusedSubchannels() { + let allSubchannelsUnrefed = true; + /* These objects are created with Object.create(null), so they do not + * have a prototype, which means that for (... in ...) loops over them + * do not need to be filtered */ + // eslint-disable-disable-next-line:forin + for (const channelTarget in this.pool) { + const subchannelObjArray = this.pool[channelTarget]; + const refedSubchannels = subchannelObjArray.filter(value => !value.subchannel.unrefIfOneRef()); + if (refedSubchannels.length > 0) { + allSubchannelsUnrefed = false; + } + /* For each subchannel in the pool, try to unref it if it has + * exactly one ref (which is the ref from the pool itself). If that + * does happen, remove the subchannel from the pool */ + this.pool[channelTarget] = refedSubchannels; + } + /* Currently we do not delete keys with empty values. If that results + * in significant memory usage we should change it. */ + // Cancel the cleanup task if all subchannels have been unrefed. + if (allSubchannelsUnrefed && this.cleanupTimer !== null) { + clearInterval(this.cleanupTimer); + this.cleanupTimer = null; + } + } + /** + * Ensures that the cleanup task is spawned. + */ + ensureCleanupTask() { + var _a, _b; + if (this.cleanupTimer === null) { + this.cleanupTimer = setInterval(() => { + this.unrefUnusedSubchannels(); + }, REF_CHECK_INTERVAL); + // Unref because this timer should not keep the event loop running. + // Call unref only if it exists to address electron/electron#21162 + (_b = (_a = this.cleanupTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + } + /** + * Get a subchannel if one already exists with exactly matching parameters. + * Otherwise, create and save a subchannel with those parameters. + * @param channelTarget + * @param subchannelTarget + * @param channelArguments + * @param channelCredentials + */ + getOrCreateSubchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials) { + this.ensureCleanupTask(); + const channelTarget = (0, uri_parser_1.uriToString)(channelTargetUri); + if (channelTarget in this.pool) { + const subchannelObjArray = this.pool[channelTarget]; + for (const subchannelObj of subchannelObjArray) { + if ((0, subchannel_address_1.subchannelAddressEqual)(subchannelTarget, subchannelObj.subchannelAddress) && + (0, channel_options_1.channelOptionsEqual)(channelArguments, subchannelObj.channelArguments) && + channelCredentials._equals(subchannelObj.channelCredentials)) { + return subchannelObj.subchannel; + } + } + } + // If we get here, no matching subchannel was found + const subchannel = new subchannel_1.Subchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials, new transport_1.Http2SubchannelConnector(channelTargetUri)); + if (!(channelTarget in this.pool)) { + this.pool[channelTarget] = []; + } + this.pool[channelTarget].push({ + subchannelAddress: subchannelTarget, + channelArguments, + channelCredentials, + subchannel, + }); + subchannel.ref(); + return subchannel; + } +} +exports.SubchannelPool = SubchannelPool; +const globalSubchannelPool = new SubchannelPool(); +/** + * Get either the global subchannel pool, or a new subchannel pool. + * @param global + */ +function getSubchannelPool(global) { + if (global) { + return globalSubchannelPool; + } + else { + return new SubchannelPool(); + } +} +//# sourceMappingURL=subchannel-pool.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-pool.js.map b/node_modules/@grpc/grpc-js/build/src/subchannel-pool.js.map new file mode 100644 index 0000000..d1b988a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-pool.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subchannel-pool.js","sourceRoot":"","sources":["../../src/subchannel-pool.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AA0JH,8CAMC;AA9JD,uDAAwE;AACxE,6CAA0C;AAC1C,6DAG8B;AAE9B,6CAAoD;AACpD,2CAAuD;AAEvD,uDAAuD;AACvD;;;GAGG;AACH,MAAM,kBAAkB,GAAG,KAAM,CAAC;AAElC,MAAa,cAAc;IAezB;;;OAGG;IACH;QAlBQ,SAAI,GAOR,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAExB;;WAEG;QACK,iBAAY,GAA0B,IAAI,CAAC;IAMpC,CAAC;IAEhB;;;OAGG;IACH,sBAAsB;QACpB,IAAI,qBAAqB,GAAG,IAAI,CAAC;QAEjC;;wCAEgC;QAChC,yCAAyC;QACzC,KAAK,MAAM,aAAa,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YACtC,MAAM,kBAAkB,GAAG,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;YAEpD,MAAM,gBAAgB,GAAG,kBAAkB,CAAC,MAAM,CAChD,KAAK,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,aAAa,EAAE,CAC3C,CAAC;YAEF,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBAChC,qBAAqB,GAAG,KAAK,CAAC;YAChC,CAAC;YAED;;kEAEsD;YACtD,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,gBAAgB,CAAC;QAC9C,CAAC;QACD;8DACsD;QAEtD,gEAAgE;QAChE,IAAI,qBAAqB,IAAI,IAAI,CAAC,YAAY,KAAK,IAAI,EAAE,CAAC;YACxD,aAAa,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;YACjC,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;QAC3B,CAAC;IACH,CA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CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,CAAC;QAChC,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,IAAI,CAAC;YAC5B,iBAAiB,EAAE,gBAAgB;YACnC,gBAAgB;YAChB,kBAAkB;YAClB,UAAU;SACX,CAAC,CAAC;QACH,UAAU,CAAC,GAAG,EAAE,CAAC;QACjB,OAAO,UAAU,CAAC;IACpB,CAAC;CACF;AA/HD,wCA+HC;AAED,MAAM,oBAAoB,GAAG,IAAI,cAAc,EAAE,CAAC;AAElD;;;GAGG;AACH,SAAgB,iBAAiB,CAAC,MAAe;IAC/C,IAAI,MAAM,EAAE,CAAC;QACX,OAAO,oBAAoB,CAAC;IAC9B,CAAC;SAAM,CAAC;QACN,OAAO,IAAI,cAAc,EAAE,CAAC;IAC9B,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel.d.ts b/node_modules/@grpc/grpc-js/build/src/subchannel.d.ts new file mode 100644 index 0000000..1a1689b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel.d.ts @@ -0,0 +1,135 @@ +import { ChannelCredentials } from './channel-credentials'; +import { Metadata } from './metadata'; +import { ChannelOptions } from './channel-options'; +import { ConnectivityState } from './connectivity-state'; +import { GrpcUri } from './uri-parser'; +import { SubchannelAddress } from './subchannel-address'; +import { SubchannelRef } from './channelz'; +import { ConnectivityStateListener, DataWatcher, SubchannelInterface } from './subchannel-interface'; +import { SubchannelCallInterceptingListener } from './subchannel-call'; +import { SubchannelCall } from './subchannel-call'; +import { SubchannelConnector } from './transport'; +import { CallCredentials } from './call-credentials'; +import { Channel } from './channel'; +export interface DataProducer { + addDataWatcher(dataWatcher: DataWatcher): void; + removeDataWatcher(dataWatcher: DataWatcher): void; +} +export declare class Subchannel implements SubchannelInterface { + private channelTarget; + private subchannelAddress; + private options; + private connector; + /** + * The subchannel's current connectivity state. Invariant: `session` === `null` + * if and only if `connectivityState` is IDLE or TRANSIENT_FAILURE. + */ + private connectivityState; + /** + * The underlying http2 session used to make requests. + */ + private transport; + /** + * Indicates that the subchannel should transition from TRANSIENT_FAILURE to + * CONNECTING instead of IDLE when the backoff timeout ends. + */ + private continueConnecting; + /** + * A list of listener functions that will be called whenever the connectivity + * state changes. Will be modified by `addConnectivityStateListener` and + * `removeConnectivityStateListener` + */ + private stateListeners; + private backoffTimeout; + private keepaliveTime; + /** + * Tracks channels and subchannel pools with references to this subchannel + */ + private refcount; + /** + * A string representation of the subchannel address, for logging/tracing + */ + private subchannelAddressString; + private readonly channelzEnabled; + private channelzRef; + private channelzTrace; + private callTracker; + private childrenTracker; + private streamTracker; + private secureConnector; + private dataProducers; + private subchannelChannel; + /** + * A class representing a connection to a single backend. + * @param channelTarget The target string for the channel as a whole + * @param subchannelAddress The address for the backend that this subchannel + * will connect to + * @param options The channel options, plus any specific subchannel options + * for this subchannel + * @param credentials The channel credentials used to establish this + * connection + */ + constructor(channelTarget: GrpcUri, subchannelAddress: SubchannelAddress, options: ChannelOptions, credentials: ChannelCredentials, connector: SubchannelConnector); + private getChannelzInfo; + private trace; + private refTrace; + private handleBackoffTimer; + /** + * Start a backoff timer with the current nextBackoff timeout + */ + private startBackoff; + private stopBackoff; + private startConnectingInternal; + /** + * Initiate a state transition from any element of oldStates to the new + * state. If the current connectivityState is not in oldStates, do nothing. + * @param oldStates The set of states to transition from + * @param newState The state to transition to + * @returns True if the state changed, false otherwise + */ + private transitionToState; + ref(): void; + unref(): void; + unrefIfOneRef(): boolean; + createCall(metadata: Metadata, host: string, method: string, listener: SubchannelCallInterceptingListener): SubchannelCall; + /** + * If the subchannel is currently IDLE, start connecting and switch to the + * CONNECTING state. If the subchannel is current in TRANSIENT_FAILURE, + * the next time it would transition to IDLE, start connecting again instead. + * Otherwise, do nothing. + */ + startConnecting(): void; + /** + * Get the subchannel's current connectivity state. + */ + getConnectivityState(): ConnectivityState; + /** + * Add a listener function to be called whenever the subchannel's + * connectivity state changes. + * @param listener + */ + addConnectivityStateListener(listener: ConnectivityStateListener): void; + /** + * Remove a listener previously added with `addConnectivityStateListener` + * @param listener A reference to a function previously passed to + * `addConnectivityStateListener` + */ + removeConnectivityStateListener(listener: ConnectivityStateListener): void; + /** + * Reset the backoff timeout, and immediately start connecting if in backoff. + */ + resetBackoff(): void; + getAddress(): string; + getChannelzRef(): SubchannelRef; + isHealthy(): boolean; + addHealthStateWatcher(listener: (healthy: boolean) => void): void; + removeHealthStateWatcher(listener: (healthy: boolean) => void): void; + getRealSubchannel(): this; + realSubchannelEquals(other: SubchannelInterface): boolean; + throttleKeepalive(newKeepaliveTime: number): void; + getCallCredentials(): CallCredentials; + getChannel(): Channel; + addDataWatcher(dataWatcher: DataWatcher): void; + getOrCreateDataProducer(name: string, createDataProducer: (subchannel: Subchannel) => DataProducer): DataProducer; + removeDataProducer(name: string): void; +} diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel.js b/node_modules/@grpc/grpc-js/build/src/subchannel.js new file mode 100644 index 0000000..abdb420 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel.js @@ -0,0 +1,397 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Subchannel = void 0; +const connectivity_state_1 = require("./connectivity-state"); +const backoff_timeout_1 = require("./backoff-timeout"); +const logging = require("./logging"); +const constants_1 = require("./constants"); +const uri_parser_1 = require("./uri-parser"); +const subchannel_address_1 = require("./subchannel-address"); +const channelz_1 = require("./channelz"); +const single_subchannel_channel_1 = require("./single-subchannel-channel"); +const TRACER_NAME = 'subchannel'; +/* setInterval and setTimeout only accept signed 32 bit integers. JS doesn't + * have a constant for the max signed 32 bit integer, so this is a simple way + * to calculate it */ +const KEEPALIVE_MAX_TIME_MS = ~(1 << 31); +class Subchannel { + /** + * A class representing a connection to a single backend. + * @param channelTarget The target string for the channel as a whole + * @param subchannelAddress The address for the backend that this subchannel + * will connect to + * @param options The channel options, plus any specific subchannel options + * for this subchannel + * @param credentials The channel credentials used to establish this + * connection + */ + constructor(channelTarget, subchannelAddress, options, credentials, connector) { + var _a; + this.channelTarget = channelTarget; + this.subchannelAddress = subchannelAddress; + this.options = options; + this.connector = connector; + /** + * The subchannel's current connectivity state. Invariant: `session` === `null` + * if and only if `connectivityState` is IDLE or TRANSIENT_FAILURE. + */ + this.connectivityState = connectivity_state_1.ConnectivityState.IDLE; + /** + * The underlying http2 session used to make requests. + */ + this.transport = null; + /** + * Indicates that the subchannel should transition from TRANSIENT_FAILURE to + * CONNECTING instead of IDLE when the backoff timeout ends. + */ + this.continueConnecting = false; + /** + * A list of listener functions that will be called whenever the connectivity + * state changes. Will be modified by `addConnectivityStateListener` and + * `removeConnectivityStateListener` + */ + this.stateListeners = new Set(); + /** + * Tracks channels and subchannel pools with references to this subchannel + */ + this.refcount = 0; + // Channelz info + this.channelzEnabled = true; + this.dataProducers = new Map(); + this.subchannelChannel = null; + const backoffOptions = { + initialDelay: options['grpc.initial_reconnect_backoff_ms'], + maxDelay: options['grpc.max_reconnect_backoff_ms'], + }; + this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => { + this.handleBackoffTimer(); + }, backoffOptions); + this.backoffTimeout.unref(); + this.subchannelAddressString = (0, subchannel_address_1.subchannelAddressToString)(subchannelAddress); + this.keepaliveTime = (_a = options['grpc.keepalive_time_ms']) !== null && _a !== void 0 ? _a : -1; + if (options['grpc.enable_channelz'] === 0) { + this.channelzEnabled = false; + this.channelzTrace = new channelz_1.ChannelzTraceStub(); + this.callTracker = new channelz_1.ChannelzCallTrackerStub(); + this.childrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); + this.streamTracker = new channelz_1.ChannelzCallTrackerStub(); + } + else { + this.channelzTrace = new channelz_1.ChannelzTrace(); + this.callTracker = new channelz_1.ChannelzCallTracker(); + this.childrenTracker = new channelz_1.ChannelzChildrenTracker(); + this.streamTracker = new channelz_1.ChannelzCallTracker(); + } + this.channelzRef = (0, channelz_1.registerChannelzSubchannel)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled); + this.channelzTrace.addTrace('CT_INFO', 'Subchannel created'); + this.trace('Subchannel constructed with options ' + + JSON.stringify(options, undefined, 2)); + this.secureConnector = credentials._createSecureConnector(channelTarget, options); + } + getChannelzInfo() { + return { + state: this.connectivityState, + trace: this.channelzTrace, + callTracker: this.callTracker, + children: this.childrenTracker.getChildLists(), + target: this.subchannelAddressString, + }; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text); + } + refTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, 'subchannel_refcount', '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text); + } + handleBackoffTimer() { + if (this.continueConnecting) { + this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING); + } + else { + this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.IDLE); + } + } + /** + * Start a backoff timer with the current nextBackoff timeout + */ + startBackoff() { + this.backoffTimeout.runOnce(); + } + stopBackoff() { + this.backoffTimeout.stop(); + this.backoffTimeout.reset(); + } + startConnectingInternal() { + let options = this.options; + if (options['grpc.keepalive_time_ms']) { + const adjustedKeepaliveTime = Math.min(this.keepaliveTime, KEEPALIVE_MAX_TIME_MS); + options = Object.assign(Object.assign({}, options), { 'grpc.keepalive_time_ms': adjustedKeepaliveTime }); + } + this.connector + .connect(this.subchannelAddress, this.secureConnector, options) + .then(transport => { + if (this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.READY)) { + this.transport = transport; + if (this.channelzEnabled) { + this.childrenTracker.refChild(transport.getChannelzRef()); + } + transport.addDisconnectListener(tooManyPings => { + this.transitionToState([connectivity_state_1.ConnectivityState.READY], connectivity_state_1.ConnectivityState.IDLE); + if (tooManyPings && this.keepaliveTime > 0) { + this.keepaliveTime *= 2; + logging.log(constants_1.LogVerbosity.ERROR, `Connection to ${(0, uri_parser_1.uriToString)(this.channelTarget)} at ${this.subchannelAddressString} rejected by server because of excess pings. Increasing ping interval to ${this.keepaliveTime} ms`); + } + }); + } + else { + /* If we can't transition from CONNECTING to READY here, we will + * not be using this transport, so release its resources. */ + transport.shutdown(); + } + }, error => { + this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, `${error}`); + }); + } + /** + * Initiate a state transition from any element of oldStates to the new + * state. If the current connectivityState is not in oldStates, do nothing. + * @param oldStates The set of states to transition from + * @param newState The state to transition to + * @returns True if the state changed, false otherwise + */ + transitionToState(oldStates, newState, errorMessage) { + var _a, _b; + if (oldStates.indexOf(this.connectivityState) === -1) { + return false; + } + if (errorMessage) { + this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + + ' -> ' + + connectivity_state_1.ConnectivityState[newState] + + ' with error "' + errorMessage + '"'); + } + else { + this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + + ' -> ' + + connectivity_state_1.ConnectivityState[newState]); + } + if (this.channelzEnabled) { + this.channelzTrace.addTrace('CT_INFO', 'Connectivity state change to ' + connectivity_state_1.ConnectivityState[newState]); + } + const previousState = this.connectivityState; + this.connectivityState = newState; + switch (newState) { + case connectivity_state_1.ConnectivityState.READY: + this.stopBackoff(); + break; + case connectivity_state_1.ConnectivityState.CONNECTING: + this.startBackoff(); + this.startConnectingInternal(); + this.continueConnecting = false; + break; + case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE: + if (this.channelzEnabled && this.transport) { + this.childrenTracker.unrefChild(this.transport.getChannelzRef()); + } + (_a = this.transport) === null || _a === void 0 ? void 0 : _a.shutdown(); + this.transport = null; + /* If the backoff timer has already ended by the time we get to the + * TRANSIENT_FAILURE state, we want to immediately transition out of + * TRANSIENT_FAILURE as though the backoff timer is ending right now */ + if (!this.backoffTimeout.isRunning()) { + process.nextTick(() => { + this.handleBackoffTimer(); + }); + } + break; + case connectivity_state_1.ConnectivityState.IDLE: + if (this.channelzEnabled && this.transport) { + this.childrenTracker.unrefChild(this.transport.getChannelzRef()); + } + (_b = this.transport) === null || _b === void 0 ? void 0 : _b.shutdown(); + this.transport = null; + break; + default: + throw new Error(`Invalid state: unknown ConnectivityState ${newState}`); + } + for (const listener of this.stateListeners) { + listener(this, previousState, newState, this.keepaliveTime, errorMessage); + } + return true; + } + ref() { + this.refTrace('refcount ' + this.refcount + ' -> ' + (this.refcount + 1)); + this.refcount += 1; + } + unref() { + this.refTrace('refcount ' + this.refcount + ' -> ' + (this.refcount - 1)); + this.refcount -= 1; + if (this.refcount === 0) { + this.channelzTrace.addTrace('CT_INFO', 'Shutting down'); + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + this.secureConnector.destroy(); + process.nextTick(() => { + this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING, connectivity_state_1.ConnectivityState.READY], connectivity_state_1.ConnectivityState.IDLE); + }); + } + } + unrefIfOneRef() { + if (this.refcount === 1) { + this.unref(); + return true; + } + return false; + } + createCall(metadata, host, method, listener) { + if (!this.transport) { + throw new Error('Cannot create call, subchannel not READY'); + } + let statsTracker; + if (this.channelzEnabled) { + this.callTracker.addCallStarted(); + this.streamTracker.addCallStarted(); + statsTracker = { + onCallEnd: status => { + if (status.code === constants_1.Status.OK) { + this.callTracker.addCallSucceeded(); + } + else { + this.callTracker.addCallFailed(); + } + }, + }; + } + else { + statsTracker = {}; + } + return this.transport.createCall(metadata, host, method, listener, statsTracker); + } + /** + * If the subchannel is currently IDLE, start connecting and switch to the + * CONNECTING state. If the subchannel is current in TRANSIENT_FAILURE, + * the next time it would transition to IDLE, start connecting again instead. + * Otherwise, do nothing. + */ + startConnecting() { + process.nextTick(() => { + /* First, try to transition from IDLE to connecting. If that doesn't happen + * because the state is not currently IDLE, check if it is + * TRANSIENT_FAILURE, and if so indicate that it should go back to + * connecting after the backoff timer ends. Otherwise do nothing */ + if (!this.transitionToState([connectivity_state_1.ConnectivityState.IDLE], connectivity_state_1.ConnectivityState.CONNECTING)) { + if (this.connectivityState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { + this.continueConnecting = true; + } + } + }); + } + /** + * Get the subchannel's current connectivity state. + */ + getConnectivityState() { + return this.connectivityState; + } + /** + * Add a listener function to be called whenever the subchannel's + * connectivity state changes. + * @param listener + */ + addConnectivityStateListener(listener) { + this.stateListeners.add(listener); + } + /** + * Remove a listener previously added with `addConnectivityStateListener` + * @param listener A reference to a function previously passed to + * `addConnectivityStateListener` + */ + removeConnectivityStateListener(listener) { + this.stateListeners.delete(listener); + } + /** + * Reset the backoff timeout, and immediately start connecting if in backoff. + */ + resetBackoff() { + process.nextTick(() => { + this.backoffTimeout.reset(); + this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING); + }); + } + getAddress() { + return this.subchannelAddressString; + } + getChannelzRef() { + return this.channelzRef; + } + isHealthy() { + return true; + } + addHealthStateWatcher(listener) { + // Do nothing with the listener + } + removeHealthStateWatcher(listener) { + // Do nothing with the listener + } + getRealSubchannel() { + return this; + } + realSubchannelEquals(other) { + return other.getRealSubchannel() === this; + } + throttleKeepalive(newKeepaliveTime) { + if (newKeepaliveTime > this.keepaliveTime) { + this.keepaliveTime = newKeepaliveTime; + } + } + getCallCredentials() { + return this.secureConnector.getCallCredentials(); + } + getChannel() { + if (!this.subchannelChannel) { + this.subchannelChannel = new single_subchannel_channel_1.SingleSubchannelChannel(this, this.channelTarget, this.options); + } + return this.subchannelChannel; + } + addDataWatcher(dataWatcher) { + throw new Error('Not implemented'); + } + getOrCreateDataProducer(name, createDataProducer) { + const existingProducer = this.dataProducers.get(name); + if (existingProducer) { + return existingProducer; + } + const newProducer = createDataProducer(this); + this.dataProducers.set(name, newProducer); + return newProducer; + } + removeDataProducer(name) { + this.dataProducers.delete(name); + } +} +exports.Subchannel = Subchannel; +//# sourceMappingURL=subchannel.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel.js.map b/node_modules/@grpc/grpc-js/build/src/subchannel.js.map new file mode 100644 index 0000000..f3feb8b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subchannel.js","sourceRoot":"","sources":["../../src/subchannel.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAKH,6DAAyD;AACzD,uDAAmE;AACnE,qCAAqC;AACrC,2CAAmD;AACnD,6CAAoD;AACpD,6DAG8B;AAC9B,yCAWoB;AAUpB,2EAAsE;AAGtE,MAAM,WAAW,GAAG,YAAY,CAAC;AAEjC;;qBAEqB;AACrB,MAAM,qBAAqB,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;AAOzC,MAAa,UAAU;IAsDrB;;;;;;;;;OASG;IACH,YACU,aAAsB,EACtB,iBAAoC,EACpC,OAAuB,EAC/B,WAA+B,EACvB,SAA8B;;QAJ9B,kBAAa,GAAb,aAAa,CAAS;QACtB,sBAAiB,GAAjB,iBAAiB,CAAmB;QACpC,YAAO,GAAP,OAAO,CAAgB;QAEvB,cAAS,GAAT,SAAS,CAAqB;QApExC;;;WAGG;QACK,sBAAiB,GAAsB,sCAAiB,CAAC,IAAI,CAAC;QACtE;;WAEG;QACK,cAAS,GAAqB,IAAI,CAAC;QAC3C;;;WAGG;QACK,uBAAkB,GAAG,KAAK,CAAC;QACnC;;;;WAI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;IAC5C,CAAC;IAED,iBAAiB,CAAC,gBAAwB;QACxC,IAAI,gBAAgB,GAAG,IAAI,CAAC,aAAa,EAAE,CAAC;YAC1C,IAAI,CAAC,aAAa,GAAG,gBAAgB,CAAC;QACxC,CAAC;IACH,CAAC;IACD,kBAAkB;QAChB,OAAO,IAAI,CAAC,eAAe,CAAC,kBAAkB,EAAE,CAAC;IACnD,CAAC;IAED,UAAU;QACR,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,CAAC;YAC5B,IAAI,CAAC,iBAAiB,GAAG,IAAI,mDAAuB,CAAC,IAAI,EAAE,IAAI,CAAC,aAAa,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QAC/F,CAAC;QACD,OAAO,IAAI,CAAC,iBAAiB,CAAC;IAChC,CAAC;IAED,cAAc,CAAC,WAAwB;QACrC,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC;IACrC,CAAC;IAED,uBAAuB,CAAC,IAAY,EAAE,kBAA4D;QAChG,MAAM,gBAAgB,GAAG,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACtD,IAAI,gBAAgB,EAAC,CAAC;YACpB,OAAO,gBAAgB,CAAC;QAC1B,CAAC;QACD,MAAM,WAAW,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC;QAC7C,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;QAC1C,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,kBAAkB,CAAC,IAAY;QAC7B,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAClC,CAAC;CACF;AA7eD,gCA6eC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/tls-helpers.d.ts b/node_modules/@grpc/grpc-js/build/src/tls-helpers.d.ts new file mode 100644 index 0000000..c1e2ff2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/tls-helpers.d.ts @@ -0,0 +1,2 @@ +export declare const CIPHER_SUITES: string | undefined; +export declare function getDefaultRootsData(): Buffer | null; diff --git a/node_modules/@grpc/grpc-js/build/src/tls-helpers.js b/node_modules/@grpc/grpc-js/build/src/tls-helpers.js new file mode 100644 index 0000000..14c521d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/tls-helpers.js @@ -0,0 +1,34 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CIPHER_SUITES = void 0; +exports.getDefaultRootsData = getDefaultRootsData; +const fs = require("fs"); +exports.CIPHER_SUITES = process.env.GRPC_SSL_CIPHER_SUITES; +const DEFAULT_ROOTS_FILE_PATH = process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH; +let defaultRootsData = null; +function getDefaultRootsData() { + if (DEFAULT_ROOTS_FILE_PATH) { + if (defaultRootsData === null) { + defaultRootsData = fs.readFileSync(DEFAULT_ROOTS_FILE_PATH); + } + return defaultRootsData; + } + return null; +} +//# sourceMappingURL=tls-helpers.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/tls-helpers.js.map b/node_modules/@grpc/grpc-js/build/src/tls-helpers.js.map new file mode 100644 index 0000000..07294da --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/tls-helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tls-helpers.js","sourceRoot":"","sources":["../../src/tls-helpers.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAWH,kDAQC;AAjBD,yBAAyB;AAEZ,QAAA,aAAa,GACxB,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC;AAErC,MAAM,uBAAuB,GAAG,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC;AAE7E,IAAI,gBAAgB,GAAkB,IAAI,CAAC;AAE3C,SAAgB,mBAAmB;IACjC,IAAI,uBAAuB,EAAE,CAAC;QAC5B,IAAI,gBAAgB,KAAK,IAAI,EAAE,CAAC;YAC9B,gBAAgB,GAAG,EAAE,CAAC,YAAY,CAAC,uBAAuB,CAAC,CAAC;QAC9D,CAAC;QACD,OAAO,gBAAgB,CAAC;IAC1B,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/transport.d.ts b/node_modules/@grpc/grpc-js/build/src/transport.d.ts new file mode 100644 index 0000000..179c2fe --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/transport.d.ts @@ -0,0 +1,135 @@ +import * as http2 from 'http2'; +import { PartialStatusObject } from './call-interface'; +import { SecureConnector } from './channel-credentials'; +import { ChannelOptions } from './channel-options'; +import { SocketRef } from './channelz'; +import { SubchannelAddress } from './subchannel-address'; +import { GrpcUri } from './uri-parser'; +import { Http2SubchannelCall, SubchannelCall, SubchannelCallInterceptingListener } from './subchannel-call'; +import { Metadata } from './metadata'; +import { AuthContext } from './auth-context'; +export interface CallEventTracker { + addMessageSent(): void; + addMessageReceived(): void; + onCallEnd(status: PartialStatusObject): void; + onStreamEnd(success: boolean): void; +} +export interface TransportDisconnectListener { + (tooManyPings: boolean): void; +} +export interface Transport { + getChannelzRef(): SocketRef; + getPeerName(): string; + getOptions(): ChannelOptions; + getAuthContext(): AuthContext; + createCall(metadata: Metadata, host: string, method: string, listener: SubchannelCallInterceptingListener, subchannelCallStatsTracker: Partial): SubchannelCall; + addDisconnectListener(listener: TransportDisconnectListener): void; + shutdown(): void; +} +declare class Http2Transport implements Transport { + private session; + private options; + /** + * Name of the remote server, if it is not the same as the subchannel + * address, i.e. if connecting through an HTTP CONNECT proxy. + */ + private remoteName; + /** + * The amount of time in between sending pings + */ + private readonly keepaliveTimeMs; + /** + * The amount of time to wait for an acknowledgement after sending a ping + */ + private readonly keepaliveTimeoutMs; + /** + * Indicates whether keepalive pings should be sent without any active calls + */ + private readonly keepaliveWithoutCalls; + /** + * Timer reference indicating when to send the next ping or when the most recent ping will be considered lost. + */ + private keepaliveTimer; + /** + * Indicates that the keepalive timer ran out while there were no active + * calls, and a ping should be sent the next time a call starts. + */ + private pendingSendKeepalivePing; + private userAgent; + private activeCalls; + private subchannelAddressString; + private disconnectListeners; + private disconnectHandled; + private authContext; + private channelzRef; + private readonly channelzEnabled; + private streamTracker; + private keepalivesSent; + private messagesSent; + private messagesReceived; + private lastMessageSentTimestamp; + private lastMessageReceivedTimestamp; + constructor(session: http2.ClientHttp2Session, subchannelAddress: SubchannelAddress, options: ChannelOptions, + /** + * Name of the remote server, if it is not the same as the subchannel + * address, i.e. if connecting through an HTTP CONNECT proxy. + */ + remoteName: string | null); + private getChannelzInfo; + private trace; + private keepaliveTrace; + private flowControlTrace; + private internalsTrace; + /** + * Indicate to the owner of this object that this transport should no longer + * be used. That happens if the connection drops, or if the server sends a + * GOAWAY. + * @param tooManyPings If true, this was triggered by a GOAWAY with data + * indicating that the session was closed becaues the client sent too many + * pings. + * @returns + */ + private reportDisconnectToOwner; + /** + * Handle connection drops, but not GOAWAYs. + */ + private handleDisconnect; + addDisconnectListener(listener: TransportDisconnectListener): void; + private canSendPing; + private maybeSendPing; + /** + * Starts the keepalive ping timer if appropriate. If the timer already ran + * out while there were no active requests, instead send a ping immediately. + * If the ping timer is already running or a ping is currently in flight, + * instead do nothing and wait for them to resolve. + */ + private maybeStartKeepalivePingTimer; + /** + * Clears whichever keepalive timeout is currently active, if any. + */ + private clearKeepaliveTimeout; + private removeActiveCall; + private addActiveCall; + createCall(metadata: Metadata, host: string, method: string, listener: SubchannelCallInterceptingListener, subchannelCallStatsTracker: Partial): Http2SubchannelCall; + getChannelzRef(): SocketRef; + getPeerName(): string; + getOptions(): ChannelOptions; + getAuthContext(): AuthContext; + shutdown(): void; +} +export interface SubchannelConnector { + connect(address: SubchannelAddress, secureConnector: SecureConnector, options: ChannelOptions): Promise; + shutdown(): void; +} +export declare class Http2SubchannelConnector implements SubchannelConnector { + private channelTarget; + private session; + private isShutdown; + constructor(channelTarget: GrpcUri); + private trace; + private createSession; + private tcpConnect; + connect(address: SubchannelAddress, secureConnector: SecureConnector, options: ChannelOptions): Promise; + shutdown(): void; +} +export {}; diff --git a/node_modules/@grpc/grpc-js/build/src/transport.js b/node_modules/@grpc/grpc-js/build/src/transport.js new file mode 100644 index 0000000..9cd187a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/transport.js @@ -0,0 +1,640 @@ +"use strict"; +/* + * Copyright 2023 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Http2SubchannelConnector = void 0; +const http2 = require("http2"); +const tls_1 = require("tls"); +const channelz_1 = require("./channelz"); +const constants_1 = require("./constants"); +const http_proxy_1 = require("./http_proxy"); +const logging = require("./logging"); +const resolver_1 = require("./resolver"); +const subchannel_address_1 = require("./subchannel-address"); +const uri_parser_1 = require("./uri-parser"); +const net = require("net"); +const subchannel_call_1 = require("./subchannel-call"); +const call_number_1 = require("./call-number"); +const TRACER_NAME = 'transport'; +const FLOW_CONTROL_TRACER_NAME = 'transport_flowctrl'; +const clientVersion = require('../../package.json').version; +const { HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_TE, HTTP2_HEADER_USER_AGENT, } = http2.constants; +const KEEPALIVE_TIMEOUT_MS = 20000; +const tooManyPingsData = Buffer.from('too_many_pings', 'ascii'); +class Http2Transport { + constructor(session, subchannelAddress, options, + /** + * Name of the remote server, if it is not the same as the subchannel + * address, i.e. if connecting through an HTTP CONNECT proxy. + */ + remoteName) { + this.session = session; + this.options = options; + this.remoteName = remoteName; + /** + * Timer reference indicating when to send the next ping or when the most recent ping will be considered lost. + */ + this.keepaliveTimer = null; + /** + * Indicates that the keepalive timer ran out while there were no active + * calls, and a ping should be sent the next time a call starts. + */ + this.pendingSendKeepalivePing = false; + this.activeCalls = new Set(); + this.disconnectListeners = []; + this.disconnectHandled = false; + this.channelzEnabled = true; + this.keepalivesSent = 0; + this.messagesSent = 0; + this.messagesReceived = 0; + this.lastMessageSentTimestamp = null; + this.lastMessageReceivedTimestamp = null; + /* Populate subchannelAddressString and channelzRef before doing anything + * else, because they are used in the trace methods. */ + this.subchannelAddressString = (0, subchannel_address_1.subchannelAddressToString)(subchannelAddress); + if (options['grpc.enable_channelz'] === 0) { + this.channelzEnabled = false; + this.streamTracker = new channelz_1.ChannelzCallTrackerStub(); + } + else { + this.streamTracker = new channelz_1.ChannelzCallTracker(); + } + this.channelzRef = (0, channelz_1.registerChannelzSocket)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled); + // Build user-agent string. + this.userAgent = [ + options['grpc.primary_user_agent'], + `grpc-node-js/${clientVersion}`, + options['grpc.secondary_user_agent'], + ] + .filter(e => e) + .join(' '); // remove falsey values first + if ('grpc.keepalive_time_ms' in options) { + this.keepaliveTimeMs = options['grpc.keepalive_time_ms']; + } + else { + this.keepaliveTimeMs = -1; + } + if ('grpc.keepalive_timeout_ms' in options) { + this.keepaliveTimeoutMs = options['grpc.keepalive_timeout_ms']; + } + else { + this.keepaliveTimeoutMs = KEEPALIVE_TIMEOUT_MS; + } + if ('grpc.keepalive_permit_without_calls' in options) { + this.keepaliveWithoutCalls = + options['grpc.keepalive_permit_without_calls'] === 1; + } + else { + this.keepaliveWithoutCalls = false; + } + session.once('close', () => { + this.trace('session closed'); + this.handleDisconnect(); + }); + session.once('goaway', (errorCode, lastStreamID, opaqueData) => { + let tooManyPings = false; + /* See the last paragraph of + * https://github.com/grpc/proposal/blob/master/A8-client-side-keepalive.md#basic-keepalive */ + if (errorCode === http2.constants.NGHTTP2_ENHANCE_YOUR_CALM && + opaqueData && + opaqueData.equals(tooManyPingsData)) { + tooManyPings = true; + } + this.trace('connection closed by GOAWAY with code ' + + errorCode + + ' and data ' + + (opaqueData === null || opaqueData === void 0 ? void 0 : opaqueData.toString())); + this.reportDisconnectToOwner(tooManyPings); + }); + session.once('error', error => { + this.trace('connection closed with error ' + error.message); + this.handleDisconnect(); + }); + session.socket.once('close', (hadError) => { + this.trace('connection closed. hadError=' + hadError); + this.handleDisconnect(); + }); + if (logging.isTracerEnabled(TRACER_NAME)) { + session.on('remoteSettings', (settings) => { + this.trace('new settings received' + + (this.session !== session ? ' on the old connection' : '') + + ': ' + + JSON.stringify(settings)); + }); + session.on('localSettings', (settings) => { + this.trace('local settings acknowledged by remote' + + (this.session !== session ? ' on the old connection' : '') + + ': ' + + JSON.stringify(settings)); + }); + } + /* Start the keepalive timer last, because this can trigger trace logs, + * which should only happen after everything else is set up. */ + if (this.keepaliveWithoutCalls) { + this.maybeStartKeepalivePingTimer(); + } + if (session.socket instanceof tls_1.TLSSocket) { + this.authContext = { + transportSecurityType: 'ssl', + sslPeerCertificate: session.socket.getPeerCertificate() + }; + } + else { + this.authContext = {}; + } + } + getChannelzInfo() { + var _a, _b, _c; + const sessionSocket = this.session.socket; + const remoteAddress = sessionSocket.remoteAddress + ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.remoteAddress, sessionSocket.remotePort) + : null; + const localAddress = sessionSocket.localAddress + ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.localAddress, sessionSocket.localPort) + : null; + let tlsInfo; + if (this.session.encrypted) { + const tlsSocket = sessionSocket; + const cipherInfo = tlsSocket.getCipher(); + const certificate = tlsSocket.getCertificate(); + const peerCertificate = tlsSocket.getPeerCertificate(); + tlsInfo = { + cipherSuiteStandardName: (_a = cipherInfo.standardName) !== null && _a !== void 0 ? _a : null, + cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, + localCertificate: certificate && 'raw' in certificate ? certificate.raw : null, + remoteCertificate: peerCertificate && 'raw' in peerCertificate + ? peerCertificate.raw + : null, + }; + } + else { + tlsInfo = null; + } + const socketInfo = { + remoteAddress: remoteAddress, + localAddress: localAddress, + security: tlsInfo, + remoteName: this.remoteName, + streamsStarted: this.streamTracker.callsStarted, + streamsSucceeded: this.streamTracker.callsSucceeded, + streamsFailed: this.streamTracker.callsFailed, + messagesSent: this.messagesSent, + messagesReceived: this.messagesReceived, + keepAlivesSent: this.keepalivesSent, + lastLocalStreamCreatedTimestamp: this.streamTracker.lastCallStartedTimestamp, + lastRemoteStreamCreatedTimestamp: null, + lastMessageSentTimestamp: this.lastMessageSentTimestamp, + lastMessageReceivedTimestamp: this.lastMessageReceivedTimestamp, + localFlowControlWindow: (_b = this.session.state.localWindowSize) !== null && _b !== void 0 ? _b : null, + remoteFlowControlWindow: (_c = this.session.state.remoteWindowSize) !== null && _c !== void 0 ? _c : null, + }; + return socketInfo; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text); + } + keepaliveTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, 'keepalive', '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text); + } + flowControlTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, FLOW_CONTROL_TRACER_NAME, '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text); + } + internalsTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, 'transport_internals', '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text); + } + /** + * Indicate to the owner of this object that this transport should no longer + * be used. That happens if the connection drops, or if the server sends a + * GOAWAY. + * @param tooManyPings If true, this was triggered by a GOAWAY with data + * indicating that the session was closed becaues the client sent too many + * pings. + * @returns + */ + reportDisconnectToOwner(tooManyPings) { + if (this.disconnectHandled) { + return; + } + this.disconnectHandled = true; + this.disconnectListeners.forEach(listener => listener(tooManyPings)); + } + /** + * Handle connection drops, but not GOAWAYs. + */ + handleDisconnect() { + this.clearKeepaliveTimeout(); + this.reportDisconnectToOwner(false); + for (const call of this.activeCalls) { + call.onDisconnect(); + } + // Wait an event loop cycle before destroying the connection + setImmediate(() => { + this.session.destroy(); + }); + } + addDisconnectListener(listener) { + this.disconnectListeners.push(listener); + } + canSendPing() { + return (!this.session.destroyed && + this.keepaliveTimeMs > 0 && + (this.keepaliveWithoutCalls || this.activeCalls.size > 0)); + } + maybeSendPing() { + var _a, _b; + if (!this.canSendPing()) { + this.pendingSendKeepalivePing = true; + return; + } + if (this.keepaliveTimer) { + console.error('keepaliveTimeout is not null'); + return; + } + if (this.channelzEnabled) { + this.keepalivesSent += 1; + } + this.keepaliveTrace('Sending ping with timeout ' + this.keepaliveTimeoutMs + 'ms'); + this.keepaliveTimer = setTimeout(() => { + this.keepaliveTimer = null; + this.keepaliveTrace('Ping timeout passed without response'); + this.handleDisconnect(); + }, this.keepaliveTimeoutMs); + (_b = (_a = this.keepaliveTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + let pingSendError = ''; + try { + const pingSentSuccessfully = this.session.ping((err, duration, payload) => { + this.clearKeepaliveTimeout(); + if (err) { + this.keepaliveTrace('Ping failed with error ' + err.message); + this.handleDisconnect(); + } + else { + this.keepaliveTrace('Received ping response'); + this.maybeStartKeepalivePingTimer(); + } + }); + if (!pingSentSuccessfully) { + pingSendError = 'Ping returned false'; + } + } + catch (e) { + // grpc/grpc-node#2139 + pingSendError = (e instanceof Error ? e.message : '') || 'Unknown error'; + } + if (pingSendError) { + this.keepaliveTrace('Ping send failed: ' + pingSendError); + this.handleDisconnect(); + } + } + /** + * Starts the keepalive ping timer if appropriate. If the timer already ran + * out while there were no active requests, instead send a ping immediately. + * If the ping timer is already running or a ping is currently in flight, + * instead do nothing and wait for them to resolve. + */ + maybeStartKeepalivePingTimer() { + var _a, _b; + if (!this.canSendPing()) { + return; + } + if (this.pendingSendKeepalivePing) { + this.pendingSendKeepalivePing = false; + this.maybeSendPing(); + } + else if (!this.keepaliveTimer) { + this.keepaliveTrace('Starting keepalive timer for ' + this.keepaliveTimeMs + 'ms'); + this.keepaliveTimer = setTimeout(() => { + this.keepaliveTimer = null; + this.maybeSendPing(); + }, this.keepaliveTimeMs); + (_b = (_a = this.keepaliveTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + /* Otherwise, there is already either a keepalive timer or a ping pending, + * wait for those to resolve. */ + } + /** + * Clears whichever keepalive timeout is currently active, if any. + */ + clearKeepaliveTimeout() { + if (this.keepaliveTimer) { + clearTimeout(this.keepaliveTimer); + this.keepaliveTimer = null; + } + } + removeActiveCall(call) { + this.activeCalls.delete(call); + if (this.activeCalls.size === 0) { + this.session.unref(); + } + } + addActiveCall(call) { + this.activeCalls.add(call); + if (this.activeCalls.size === 1) { + this.session.ref(); + if (!this.keepaliveWithoutCalls) { + this.maybeStartKeepalivePingTimer(); + } + } + } + createCall(metadata, host, method, listener, subchannelCallStatsTracker) { + const headers = metadata.toHttp2Headers(); + headers[HTTP2_HEADER_AUTHORITY] = host; + headers[HTTP2_HEADER_USER_AGENT] = this.userAgent; + headers[HTTP2_HEADER_CONTENT_TYPE] = 'application/grpc'; + headers[HTTP2_HEADER_METHOD] = 'POST'; + headers[HTTP2_HEADER_PATH] = method; + headers[HTTP2_HEADER_TE] = 'trailers'; + let http2Stream; + /* In theory, if an error is thrown by session.request because session has + * become unusable (e.g. because it has received a goaway), this subchannel + * should soon see the corresponding close or goaway event anyway and leave + * READY. But we have seen reports that this does not happen + * (https://github.com/googleapis/nodejs-firestore/issues/1023#issuecomment-653204096) + * so for defense in depth, we just discard the session when we see an + * error here. + */ + try { + http2Stream = this.session.request(headers); + } + catch (e) { + this.handleDisconnect(); + throw e; + } + this.flowControlTrace('local window size: ' + + this.session.state.localWindowSize + + ' remote window size: ' + + this.session.state.remoteWindowSize); + this.internalsTrace('session.closed=' + + this.session.closed + + ' session.destroyed=' + + this.session.destroyed + + ' session.socket.destroyed=' + + this.session.socket.destroyed); + let eventTracker; + // eslint-disable-next-line prefer-const + let call; + if (this.channelzEnabled) { + this.streamTracker.addCallStarted(); + eventTracker = { + addMessageSent: () => { + var _a; + this.messagesSent += 1; + this.lastMessageSentTimestamp = new Date(); + (_a = subchannelCallStatsTracker.addMessageSent) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); + }, + addMessageReceived: () => { + var _a; + this.messagesReceived += 1; + this.lastMessageReceivedTimestamp = new Date(); + (_a = subchannelCallStatsTracker.addMessageReceived) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); + }, + onCallEnd: status => { + var _a; + (_a = subchannelCallStatsTracker.onCallEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, status); + this.removeActiveCall(call); + }, + onStreamEnd: success => { + var _a; + if (success) { + this.streamTracker.addCallSucceeded(); + } + else { + this.streamTracker.addCallFailed(); + } + (_a = subchannelCallStatsTracker.onStreamEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, success); + }, + }; + } + else { + eventTracker = { + addMessageSent: () => { + var _a; + (_a = subchannelCallStatsTracker.addMessageSent) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); + }, + addMessageReceived: () => { + var _a; + (_a = subchannelCallStatsTracker.addMessageReceived) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); + }, + onCallEnd: status => { + var _a; + (_a = subchannelCallStatsTracker.onCallEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, status); + this.removeActiveCall(call); + }, + onStreamEnd: success => { + var _a; + (_a = subchannelCallStatsTracker.onStreamEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, success); + }, + }; + } + call = new subchannel_call_1.Http2SubchannelCall(http2Stream, eventTracker, listener, this, (0, call_number_1.getNextCallNumber)()); + this.addActiveCall(call); + return call; + } + getChannelzRef() { + return this.channelzRef; + } + getPeerName() { + return this.subchannelAddressString; + } + getOptions() { + return this.options; + } + getAuthContext() { + return this.authContext; + } + shutdown() { + this.session.close(); + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + } +} +class Http2SubchannelConnector { + constructor(channelTarget) { + this.channelTarget = channelTarget; + this.session = null; + this.isShutdown = false; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, (0, uri_parser_1.uriToString)(this.channelTarget) + ' ' + text); + } + createSession(secureConnectResult, address, options) { + if (this.isShutdown) { + return Promise.reject(); + } + if (secureConnectResult.socket.closed) { + return Promise.reject('Connection closed before starting HTTP/2 handshake'); + } + return new Promise((resolve, reject) => { + var _a, _b, _c, _d, _e, _f, _g, _h; + let remoteName = null; + let realTarget = this.channelTarget; + if ('grpc.http_connect_target' in options) { + const parsedTarget = (0, uri_parser_1.parseUri)(options['grpc.http_connect_target']); + if (parsedTarget) { + realTarget = parsedTarget; + remoteName = (0, uri_parser_1.uriToString)(parsedTarget); + } + } + const scheme = secureConnectResult.secure ? 'https' : 'http'; + const targetPath = (0, resolver_1.getDefaultAuthority)(realTarget); + const closeHandler = () => { + var _a; + (_a = this.session) === null || _a === void 0 ? void 0 : _a.destroy(); + this.session = null; + // Leave time for error event to happen before rejecting + setImmediate(() => { + if (!reportedError) { + reportedError = true; + reject(`${errorMessage.trim()} (${new Date().toISOString()})`); + } + }); + }; + const errorHandler = (error) => { + var _a; + (_a = this.session) === null || _a === void 0 ? void 0 : _a.destroy(); + errorMessage = error.message; + this.trace('connection failed with error ' + errorMessage); + if (!reportedError) { + reportedError = true; + reject(`${errorMessage} (${new Date().toISOString()})`); + } + }; + const sessionOptions = { + createConnection: (authority, option) => { + return secureConnectResult.socket; + }, + settings: { + initialWindowSize: (_d = (_a = options['grpc-node.flow_control_window']) !== null && _a !== void 0 ? _a : (_c = (_b = http2.getDefaultSettings) === null || _b === void 0 ? void 0 : _b.call(http2)) === null || _c === void 0 ? void 0 : _c.initialWindowSize) !== null && _d !== void 0 ? _d : 65535, + }, + maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER, + /* By default, set a very large max session memory limit, to effectively + * disable enforcement of the limit. Some testing indicates that Node's + * behavior degrades badly when this limit is reached, so we solve that + * by disabling the check entirely. */ + maxSessionMemory: (_e = options['grpc-node.max_session_memory']) !== null && _e !== void 0 ? _e : Number.MAX_SAFE_INTEGER + }; + const session = http2.connect(`${scheme}://${targetPath}`, sessionOptions); + // Prepare window size configuration for remoteSettings handler + const defaultWin = (_h = (_g = (_f = http2.getDefaultSettings) === null || _f === void 0 ? void 0 : _f.call(http2)) === null || _g === void 0 ? void 0 : _g.initialWindowSize) !== null && _h !== void 0 ? _h : 65535; // 65 535 B + const connWin = options['grpc-node.flow_control_window']; + this.session = session; + let errorMessage = 'Failed to connect'; + let reportedError = false; + session.unref(); + session.once('remoteSettings', () => { + var _a; + // Send WINDOW_UPDATE now to avoid 65 KB start-window stall. + if (connWin && connWin > defaultWin) { + try { + // Node ≥ 14.18 + session.setLocalWindowSize(connWin); + } + catch (_b) { + // Older Node: bump by the delta + const delta = connWin - ((_a = session.state.localWindowSize) !== null && _a !== void 0 ? _a : defaultWin); + if (delta > 0) + session.incrementWindowSize(delta); + } + } + session.removeAllListeners(); + secureConnectResult.socket.removeListener('close', closeHandler); + secureConnectResult.socket.removeListener('error', errorHandler); + resolve(new Http2Transport(session, address, options, remoteName)); + this.session = null; + }); + session.once('close', closeHandler); + session.once('error', errorHandler); + secureConnectResult.socket.once('close', closeHandler); + secureConnectResult.socket.once('error', errorHandler); + }); + } + tcpConnect(address, options) { + return (0, http_proxy_1.getProxiedConnection)(address, options).then(proxiedSocket => { + if (proxiedSocket) { + return proxiedSocket; + } + else { + return new Promise((resolve, reject) => { + const closeCallback = () => { + reject(new Error('Socket closed')); + }; + const errorCallback = (error) => { + reject(error); + }; + const socket = net.connect(address, () => { + socket.removeListener('close', closeCallback); + socket.removeListener('error', errorCallback); + resolve(socket); + }); + socket.once('close', closeCallback); + socket.once('error', errorCallback); + }); + } + }); + } + async connect(address, secureConnector, options) { + if (this.isShutdown) { + return Promise.reject(); + } + let tcpConnection = null; + let secureConnectResult = null; + const addressString = (0, subchannel_address_1.subchannelAddressToString)(address); + try { + this.trace(addressString + ' Waiting for secureConnector to be ready'); + await secureConnector.waitForReady(); + this.trace(addressString + ' secureConnector is ready'); + tcpConnection = await this.tcpConnect(address, options); + tcpConnection.setNoDelay(); + this.trace(addressString + ' Established TCP connection'); + secureConnectResult = await secureConnector.connect(tcpConnection); + this.trace(addressString + ' Established secure connection'); + return this.createSession(secureConnectResult, address, options); + } + catch (e) { + tcpConnection === null || tcpConnection === void 0 ? void 0 : tcpConnection.destroy(); + secureConnectResult === null || secureConnectResult === void 0 ? void 0 : secureConnectResult.socket.destroy(); + throw e; + } + } + shutdown() { + var _a; + this.isShutdown = true; + (_a = this.session) === null || _a === void 0 ? void 0 : _a.close(); + this.session = null; + } +} +exports.Http2SubchannelConnector = Http2SubchannelConnector; +//# sourceMappingURL=transport.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/transport.js.map b/node_modules/@grpc/grpc-js/build/src/transport.js.map new file mode 100644 index 0000000..06e7fcd --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/transport.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transport.js","sourceRoot":"","sources":["../../src/transport.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,+BAA+B;AAC/B,6BAGa;AAIb,yCAQoB;AACpB,2CAA2C;AAC3C,6CAAoD;AACpD,qCAA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grpc-js/build/src/uri-parser.d.ts new file mode 100644 index 0000000..26db9c6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/uri-parser.d.ts @@ -0,0 +1,13 @@ +export interface GrpcUri { + scheme?: string; + authority?: string; + path: string; +} +export declare function parseUri(uriString: string): GrpcUri | null; +export interface HostPort { + host: string; + port?: number; +} +export declare function splitHostPort(path: string): HostPort | null; +export declare function combineHostPort(hostPort: HostPort): string; +export declare function uriToString(uri: GrpcUri): string; diff --git a/node_modules/@grpc/grpc-js/build/src/uri-parser.js b/node_modules/@grpc/grpc-js/build/src/uri-parser.js new file mode 100644 index 0000000..5b4e6d5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/uri-parser.js @@ -0,0 +1,125 @@ +"use strict"; +/* + * Copyright 2020 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseUri = parseUri; +exports.splitHostPort = splitHostPort; +exports.combineHostPort = combineHostPort; +exports.uriToString = uriToString; +/* + * The groups correspond to URI parts as follows: + * 1. scheme + * 2. authority + * 3. path + */ +const URI_REGEX = /^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/; +function parseUri(uriString) { + const parsedUri = URI_REGEX.exec(uriString); + if (parsedUri === null) { + return null; + } + return { + scheme: parsedUri[1], + authority: parsedUri[2], + path: parsedUri[3], + }; +} +const NUMBER_REGEX = /^\d+$/; +function splitHostPort(path) { + if (path.startsWith('[')) { + const hostEnd = path.indexOf(']'); + if (hostEnd === -1) { + return null; + } + const host = path.substring(1, hostEnd); + /* Only an IPv6 address should be in bracketed notation, and an IPv6 + * address should have at least one colon */ + if (host.indexOf(':') === -1) { + return null; + } + if (path.length > hostEnd + 1) { + if (path[hostEnd + 1] === ':') { + const portString = path.substring(hostEnd + 2); + if (NUMBER_REGEX.test(portString)) { + return { + host: host, + port: +portString, + }; + } + else { + return null; + } + } + else { + return null; + } + } + else { + return { + host, + }; + } + } + else { + const splitPath = path.split(':'); + /* Exactly one colon means that this is host:port. Zero colons means that + * there is no port. And multiple colons means that this is a bare IPv6 + * address with no port */ + if (splitPath.length === 2) { + if (NUMBER_REGEX.test(splitPath[1])) { + return { + host: splitPath[0], + port: +splitPath[1], + }; + } + else { + return null; + } + } + else { + return { + host: path, + }; + } + } +} +function combineHostPort(hostPort) { + if (hostPort.port === undefined) { + return hostPort.host; + } + else { + // Only an IPv6 host should include a colon + if (hostPort.host.includes(':')) { + return `[${hostPort.host}]:${hostPort.port}`; + } + else { + return `${hostPort.host}:${hostPort.port}`; + } + } +} +function uriToString(uri) { + let result = ''; + if (uri.scheme !== undefined) { + result += uri.scheme + ':'; + } + if (uri.authority !== undefined) { + result += '//' + uri.authority + '/'; + } + result += uri.path; + return result; +} +//# sourceMappingURL=uri-parser.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/uri-parser.js.map b/node_modules/@grpc/grpc-js/build/src/uri-parser.js.map new file mode 100644 index 0000000..878db02 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/uri-parser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uri-parser.js","sourceRoot":"","sources":["../../src/uri-parser.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAgBH,4BAUC;AASD,sCAmDC;AAED,0CAWC;AAED,kCAUC;AAvGD;;;;;GAKG;AACH,MAAM,SAAS,GAAG,iDAAiD,CAAC;AAEpE,SAAgB,QAAQ,CAAC,SAAiB;IACxC,MAAM,SAAS,GAAG,SAAS,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAC5C,IAAI,SAAS,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ChC,MAAM,IAAI,IAAI,GAAG,GAAG,CAAC,SAAS,GAAG,GAAG,CAAC;IACvC,CAAC;IACD,MAAM,IAAI,GAAG,CAAC,IAAI,CAAC;IACnB,OAAO,MAAM,CAAC;AAChB,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/node_modules/.bin/proto-loader-gen-types b/node_modules/@grpc/grpc-js/node_modules/.bin/proto-loader-gen-types new file mode 100644 index 0000000..03c2fcc --- /dev/null +++ b/node_modules/@grpc/grpc-js/node_modules/.bin/proto-loader-gen-types @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../@grpc/proto-loader/build/bin/proto-loader-gen-types.js" "$@" +else + exec node "$basedir/../@grpc/proto-loader/build/bin/proto-loader-gen-types.js" "$@" +fi diff --git a/node_modules/@grpc/grpc-js/node_modules/.bin/proto-loader-gen-types.cmd b/node_modules/@grpc/grpc-js/node_modules/.bin/proto-loader-gen-types.cmd new file mode 100644 index 0000000..772529b --- /dev/null +++ b/node_modules/@grpc/grpc-js/node_modules/.bin/proto-loader-gen-types.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%\..\@grpc\proto-loader\build\bin\proto-loader-gen-types.js" %* diff --git a/node_modules/@grpc/grpc-js/node_modules/.bin/proto-loader-gen-types.ps1 b/node_modules/@grpc/grpc-js/node_modules/.bin/proto-loader-gen-types.ps1 new file mode 100644 index 0000000..d1db451 --- /dev/null +++ b/node_modules/@grpc/grpc-js/node_modules/.bin/proto-loader-gen-types.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/../@grpc/proto-loader/build/bin/proto-loader-gen-types.js" $args + } else { + & "$basedir/node$exe" "$basedir/../@grpc/proto-loader/build/bin/proto-loader-gen-types.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../@grpc/proto-loader/build/bin/proto-loader-gen-types.js" $args + } else { + & "node$exe" "$basedir/../@grpc/proto-loader/build/bin/proto-loader-gen-types.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/LICENSE b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/README.md b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/README.md new file mode 100644 index 0000000..935c100 --- /dev/null +++ b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/README.md @@ -0,0 +1,140 @@ +# gRPC Protobuf Loader + +A utility package for loading `.proto` files for use with gRPC, using the latest Protobuf.js package. +Please refer to [protobuf.js' documentation](https://github.com/dcodeIO/protobuf.js/blob/master/README.md) +to understands its features and limitations. + +## Installation + +```sh +npm install @grpc/proto-loader +``` + +## Usage + +```js +const protoLoader = require('@grpc/proto-loader'); +const grpcLibrary = require('grpc'); +// OR +const grpcLibrary = require('@grpc/grpc-js'); + +protoLoader.load(protoFileName, options).then(packageDefinition => { + const packageObject = grpcLibrary.loadPackageDefinition(packageDefinition); +}); +// OR +const packageDefinition = protoLoader.loadSync(protoFileName, options); +const packageObject = grpcLibrary.loadPackageDefinition(packageDefinition); +``` + +The options parameter is an object that can have the following optional properties: + +| Field name | Valid values | Description +|------------|--------------|------------ +| `keepCase` | `true` or `false` | Preserve field names. The default is to change them to camel case. +| `longs` | `String` or `Number` | The type to use to represent `long` values. Defaults to a `Long` object type. +| `enums` | `String` | The type to use to represent `enum` values. Defaults to the numeric value. +| `bytes` | `Array` or `String` | The type to use to represent `bytes` values. Defaults to `Buffer`. +| `defaults` | `true` or `false` | Set default values on output objects. Defaults to `false`. +| `arrays` | `true` or `false` | Set empty arrays for missing array values even if `defaults` is `false` Defaults to `false`. +| `objects` | `true` or `false` | Set empty objects for missing object values even if `defaults` is `false` Defaults to `false`. +| `oneofs` | `true` or `false` | Set virtual oneof properties to the present field's name. Defaults to `false`. +| `json` | `true` or `false` | Represent `Infinity` and `NaN` as strings in `float` fields, and automatically decode `google.protobuf.Any` values. Defaults to `false` +| `includeDirs` | An array of strings | A list of search paths for imported `.proto` files. + +The following options object closely approximates the existing behavior of `grpc.load`: + +```js +const options = { + keepCase: true, + longs: String, + enums: String, + defaults: true, + oneofs: true +} +``` + +## Generating TypeScript types + +The `proto-loader-gen-types` script distributed with this package can be used to generate TypeScript type information for the objects loaded at runtime. More information about how to use it can be found in [the *@grpc/proto-loader TypeScript Type Generator CLI Tool* proposal document](https://github.com/grpc/proposal/blob/master/L70-node-proto-loader-type-generator.md). The arguments mostly match the `load` function's options; the full usage information is as follows: + +```console +proto-loader-gen-types.js [options] filenames... + +Options: + --help Show help [boolean] + --version Show version number [boolean] + --keepCase Preserve the case of field names + [boolean] [default: false] + --longs The type that should be used to output 64 bit + integer values. Can be String, Number + [string] [default: "Long"] + --enums The type that should be used to output enum fields. + Can be String [string] [default: "number"] + --bytes The type that should be used to output bytes + fields. Can be String, Array + [string] [default: "Buffer"] + --defaults Output default values for omitted fields + [boolean] [default: false] + --arrays Output default values for omitted repeated fields + even if --defaults is not set + [boolean] [default: false] + --objects Output default values for omitted message fields + even if --defaults is not set + [boolean] [default: false] + --oneofs Output virtual oneof fields set to the present + field's name [boolean] [default: false] + --json Represent Infinity and NaN as strings in float + fields. Also decode google.protobuf.Any + automatically [boolean] [default: false] + --includeComments Generate doc comments from comments in the original + files [boolean] [default: false] + -I, --includeDirs Directories to search for included files [array] + -O, --outDir Directory in which to output files + [string] [required] + --grpcLib The gRPC implementation library that these types + will be used with. If not provided, some types will + not be generated [string] + --inputTemplate Template for mapping input or "permissive" type + names [string] [default: "%s"] + --outputTemplate Template for mapping output or "restricted" type + names [string] [default: "%s__Output"] + --inputBranded Output property for branded type for "permissive" + types with fullName of the Message as its value + [boolean] [default: false] + --outputBranded Output property for branded type for "restricted" + types with fullName of the Message as its value + [boolean] [default: false] + --targetFileExtension File extension for generated files. + [string] [default: ".ts"] + --importFileExtension File extension for import specifiers in generated + code. [string] [default: ""] +``` + +### Example Usage + +Generate the types: + +```sh +$(npm bin)/proto-loader-gen-types --longs=String --enums=String --defaults --oneofs --grpcLib=@grpc/grpc-js --outDir=proto/ proto/*.proto +``` + +Consume the types: + +```ts +import * as grpc from '@grpc/grpc-js'; +import * as protoLoader from '@grpc/proto-loader'; +import type { ProtoGrpcType } from './proto/example.ts'; +import type { ExampleHandlers } from './proto/example_package/Example.ts'; + +const exampleServer: ExampleHandlers = { + // server handlers implementation... +}; + +const packageDefinition = protoLoader.loadSync('./proto/example.proto'); +const proto = (grpc.loadPackageDefinition( + packageDefinition +) as unknown) as ProtoGrpcType; + +const server = new grpc.Server(); +server.addService(proto.example_package.Example.service, exampleServer); +``` diff --git a/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js new file mode 100644 index 0000000..f00071e --- /dev/null +++ b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js @@ -0,0 +1,915 @@ +#!/usr/bin/env node +"use strict"; +/** + * @license + * Copyright 2020 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const fs = require("fs"); +const path = require("path"); +const Protobuf = require("protobufjs"); +const yargs = require("yargs"); +const camelCase = require("lodash.camelcase"); +const util_1 = require("../src/util"); +const templateStr = "%s"; +const useNameFmter = ({ outputTemplate, inputTemplate }) => { + if (outputTemplate === inputTemplate) { + throw new Error('inputTemplate and outputTemplate must differ'); + } + return { + outputName: (n) => outputTemplate.replace(templateStr, n), + inputName: (n) => inputTemplate.replace(templateStr, n) + }; +}; +class TextFormatter { + constructor() { + this.indentText = ' '; + this.indentValue = 0; + this.textParts = []; + } + indent() { + this.indentValue += 1; + } + unindent() { + this.indentValue -= 1; + } + writeLine(line) { + for (let i = 0; i < this.indentValue; i += 1) { + this.textParts.push(this.indentText); + } + this.textParts.push(line); + this.textParts.push('\n'); + } + getFullText() { + return this.textParts.join(''); + } +} +// GENERATOR UTILITY FUNCTIONS +function compareName(x, y) { + if (x.name < y.name) { + return -1; + } + else if (x.name > y.name) { + return 1; + } + else { + return 0; + } +} +function isNamespaceBase(obj) { + return Array.isArray(obj.nestedArray); +} +function stripLeadingPeriod(name) { + return name.startsWith('.') ? name.substring(1) : name; +} +function getImportPath(to) { + /* If the thing we are importing is defined in a message, it is generated in + * the same file as that message. */ + if (to.parent instanceof Protobuf.Type) { + return getImportPath(to.parent); + } + return stripLeadingPeriod(to.fullName).replace(/\./g, '/'); +} +function getPath(to, options) { + return stripLeadingPeriod(to.fullName).replace(/\./g, '/') + options.targetFileExtension; +} +function getPathToRoot(from) { + const depth = stripLeadingPeriod(from.fullName).split('.').length - 1; + if (depth === 0) { + return './'; + } + let path = ''; + for (let i = 0; i < depth; i++) { + path += '../'; + } + return path; +} +function getRelativeImportPath(from, to) { + return getPathToRoot(from) + getImportPath(to); +} +function getTypeInterfaceName(type) { + return type.fullName.replace(/\./g, '_'); +} +function getImportLine(dependency, from, options) { + const filePath = from === undefined ? './' + getImportPath(dependency) : getRelativeImportPath(from, dependency); + const { outputName, inputName } = useNameFmter(options); + const typeInterfaceName = getTypeInterfaceName(dependency); + let importedTypes; + /* If the dependency is defined within a message, it will be generated in that + * message's file and exported using its typeInterfaceName. */ + if (dependency.parent instanceof Protobuf.Type) { + if (dependency instanceof Protobuf.Type || dependency instanceof Protobuf.Enum) { + importedTypes = `${inputName(typeInterfaceName)}, ${outputName(typeInterfaceName)}`; + } + else if (dependency instanceof Protobuf.Service) { + importedTypes = `${typeInterfaceName}Client, ${typeInterfaceName}Definition`; + } + else { + throw new Error('Invalid object passed to getImportLine'); + } + } + else { + if (dependency instanceof Protobuf.Type || dependency instanceof Protobuf.Enum) { + importedTypes = `${inputName(dependency.name)} as ${inputName(typeInterfaceName)}, ${outputName(dependency.name)} as ${outputName(typeInterfaceName)}`; + } + else if (dependency instanceof Protobuf.Service) { + importedTypes = `${dependency.name}Client as ${typeInterfaceName}Client, ${dependency.name}Definition as ${typeInterfaceName}Definition`; + } + else { + throw new Error('Invalid object passed to getImportLine'); + } + } + return `import type { ${importedTypes} } from '${filePath}${options.importFileExtension}';`; +} +function getChildMessagesAndEnums(namespace) { + const messageList = []; + for (const nested of namespace.nestedArray) { + if (nested instanceof Protobuf.Type || nested instanceof Protobuf.Enum) { + messageList.push(nested); + } + if (isNamespaceBase(nested)) { + messageList.push(...getChildMessagesAndEnums(nested)); + } + } + return messageList; +} +function formatComment(formatter, comment, options) { + if (!comment && !(options === null || options === void 0 ? void 0 : options.deprecated)) { + return; + } + formatter.writeLine('/**'); + if (comment) { + for (const line of comment.split('\n')) { + formatter.writeLine(` * ${line.replace(/\*\//g, '* /')}`); + } + } + if (options === null || options === void 0 ? void 0 : options.deprecated) { + formatter.writeLine(' * @deprecated'); + } + formatter.writeLine(' */'); +} +const typeBrandHint = `This field is a type brand and is not populated at runtime. Instances of this type should be created using type assertions. +https://github.com/grpc/grpc-node/pull/2281`; +function formatTypeBrand(formatter, messageType) { + formatComment(formatter, typeBrandHint); + formatter.writeLine(`__type: '${messageType.fullName}'`); +} +// GENERATOR FUNCTIONS +function getTypeNamePermissive(fieldType, resolvedType, repeated, map, options) { + const { inputName } = useNameFmter(options); + switch (fieldType) { + case 'double': + case 'float': + return 'number | string'; + case 'int32': + case 'uint32': + case 'sint32': + case 'fixed32': + case 'sfixed32': + return 'number'; + case 'int64': + case 'uint64': + case 'sint64': + case 'fixed64': + case 'sfixed64': + return 'number | string | Long'; + case 'bool': + return 'boolean'; + case 'string': + return 'string'; + case 'bytes': + return 'Buffer | Uint8Array | string'; + default: + if (resolvedType === null) { + throw new Error('Found field with no usable type'); + } + const typeInterfaceName = getTypeInterfaceName(resolvedType); + if (resolvedType instanceof Protobuf.Type) { + if (repeated || map) { + return inputName(typeInterfaceName); + } + else { + return `${inputName(typeInterfaceName)} | null`; + } + } + else { + // Enum + return inputName(typeInterfaceName); + } + } +} +function getFieldTypePermissive(field, options) { + const valueType = getTypeNamePermissive(field.type, field.resolvedType, field.repeated, field.map, options); + if (field instanceof Protobuf.MapField) { + const keyType = field.keyType === 'string' ? 'string' : 'number'; + return `{[key: ${keyType}]: ${valueType}}`; + } + else { + return valueType; + } +} +function generatePermissiveMessageInterface(formatter, messageType, options, nameOverride) { + const { inputName } = useNameFmter(options); + if (options.includeComments) { + formatComment(formatter, messageType.comment, messageType.options); + } + if (messageType.fullName === '.google.protobuf.Any') { + /* This describes the behavior of the Protobuf.js Any wrapper fromObject + * replacement function */ + formatter.writeLine(`export type ${inputName('Any')} = AnyExtension | {`); + formatter.writeLine(' type_url: string;'); + formatter.writeLine(' value: Buffer | Uint8Array | string;'); + formatter.writeLine('}'); + return; + } + formatter.writeLine(`export interface ${inputName(nameOverride !== null && nameOverride !== void 0 ? nameOverride : messageType.name)} {`); + formatter.indent(); + for (const field of messageType.fieldsArray) { + const repeatedString = field.repeated ? '[]' : ''; + const type = getFieldTypePermissive(field, options); + if (options.includeComments) { + formatComment(formatter, field.comment, field.options); + } + formatter.writeLine(`'${field.name}'?: (${type})${repeatedString};`); + } + for (const oneof of messageType.oneofsArray) { + const typeString = oneof.fieldsArray.map(field => `"${field.name}"`).join('|'); + if (options.includeComments) { + formatComment(formatter, oneof.comment, oneof.options); + } + formatter.writeLine(`'${oneof.name}'?: ${typeString};`); + } + if (options.inputBranded) { + formatTypeBrand(formatter, messageType); + } + formatter.unindent(); + formatter.writeLine('}'); +} +function getTypeNameRestricted(fieldType, resolvedType, repeated, map, options) { + const { outputName } = useNameFmter(options); + switch (fieldType) { + case 'double': + case 'float': + if (options.json) { + return 'number | string'; + } + else { + return 'number'; + } + case 'int32': + case 'uint32': + case 'sint32': + case 'fixed32': + case 'sfixed32': + return 'number'; + case 'int64': + case 'uint64': + case 'sint64': + case 'fixed64': + case 'sfixed64': + if (options.longs === Number) { + return 'number'; + } + else if (options.longs === String) { + return 'string'; + } + else { + return 'Long'; + } + case 'bool': + return 'boolean'; + case 'string': + return 'string'; + case 'bytes': + if (options.bytes === Array) { + return 'Uint8Array'; + } + else if (options.bytes === String) { + return 'string'; + } + else { + return 'Buffer'; + } + default: + if (resolvedType === null) { + throw new Error('Found field with no usable type'); + } + const typeInterfaceName = getTypeInterfaceName(resolvedType); + if (resolvedType instanceof Protobuf.Type) { + /* null is only used to represent absent message values if the defaults + * option is set, and only for non-repeated, non-map fields. */ + if (options.defaults && !repeated && !map) { + return `${outputName(typeInterfaceName)} | null`; + } + else { + return `${outputName(typeInterfaceName)}`; + } + } + else { + // Enum + return outputName(typeInterfaceName); + } + } +} +function getFieldTypeRestricted(field, options) { + const valueType = getTypeNameRestricted(field.type, field.resolvedType, field.repeated, field.map, options); + if (field instanceof Protobuf.MapField) { + const keyType = field.keyType === 'string' ? 'string' : 'number'; + return `{[key: ${keyType}]: ${valueType}}`; + } + else { + return valueType; + } +} +function generateRestrictedMessageInterface(formatter, messageType, options, nameOverride) { + var _a, _b, _c; + const { outputName } = useNameFmter(options); + if (options.includeComments) { + formatComment(formatter, messageType.comment, messageType.options); + } + if (messageType.fullName === '.google.protobuf.Any' && options.json) { + /* This describes the behavior of the Protobuf.js Any wrapper toObject + * replacement function */ + let optionalString = options.defaults ? '' : '?'; + formatter.writeLine(`export type ${outputName('Any')} = AnyExtension | {`); + formatter.writeLine(` type_url${optionalString}: string;`); + formatter.writeLine(` value${optionalString}: ${getTypeNameRestricted('bytes', null, false, false, options)};`); + formatter.writeLine('}'); + return; + } + formatter.writeLine(`export interface ${outputName(nameOverride !== null && nameOverride !== void 0 ? nameOverride : messageType.name)} {`); + formatter.indent(); + for (const field of messageType.fieldsArray) { + let fieldGuaranteed; + if (field.partOf) { + // The field is not guaranteed populated if it is part of a oneof + fieldGuaranteed = false; + } + else if (field.repeated) { + fieldGuaranteed = (_a = (options.defaults || options.arrays)) !== null && _a !== void 0 ? _a : false; + } + else if (field.map) { + fieldGuaranteed = (_b = (options.defaults || options.objects)) !== null && _b !== void 0 ? _b : false; + } + else { + fieldGuaranteed = (_c = options.defaults) !== null && _c !== void 0 ? _c : false; + } + const optionalString = fieldGuaranteed ? '' : '?'; + const repeatedString = field.repeated ? '[]' : ''; + const type = getFieldTypeRestricted(field, options); + if (options.includeComments) { + formatComment(formatter, field.comment, field.options); + } + formatter.writeLine(`'${field.name}'${optionalString}: (${type})${repeatedString};`); + } + if (options.oneofs) { + for (const oneof of messageType.oneofsArray) { + const typeString = oneof.fieldsArray.map(field => `"${field.name}"`).join('|'); + if (options.includeComments) { + formatComment(formatter, oneof.comment, oneof.options); + } + formatter.writeLine(`'${oneof.name}'?: ${typeString};`); + } + } + if (options.outputBranded) { + formatTypeBrand(formatter, messageType); + } + formatter.unindent(); + formatter.writeLine('}'); +} +function generateMessageInterfaces(formatter, messageType, options) { + var _a, _b; + let usesLong = false; + let seenDeps = new Set(); + const childTypes = getChildMessagesAndEnums(messageType); + formatter.writeLine(`// Original file: ${(_b = ((_a = messageType.filename) !== null && _a !== void 0 ? _a : 'null')) === null || _b === void 0 ? void 0 : _b.replace(/\\/g, '/')}`); + formatter.writeLine(''); + const isLongField = (field) => ['int64', 'uint64', 'sint64', 'fixed64', 'sfixed64'].includes(field.type); + messageType.fieldsArray.sort((fieldA, fieldB) => fieldA.id - fieldB.id); + for (const field of messageType.fieldsArray) { + if (field.resolvedType && childTypes.indexOf(field.resolvedType) < 0) { + const dependency = field.resolvedType; + if (seenDeps.has(dependency.fullName)) { + continue; + } + seenDeps.add(dependency.fullName); + formatter.writeLine(getImportLine(dependency, messageType, options)); + } + if (isLongField(field)) { + usesLong = true; + } + } + for (const childType of childTypes) { + if (childType instanceof Protobuf.Type) { + for (const field of childType.fieldsArray) { + if (field.resolvedType && childTypes.indexOf(field.resolvedType) < 0) { + const dependency = field.resolvedType; + if (seenDeps.has(dependency.fullName)) { + continue; + } + seenDeps.add(dependency.fullName); + formatter.writeLine(getImportLine(dependency, messageType, options)); + } + if (isLongField(field)) { + usesLong = true; + } + } + } + } + if (usesLong) { + formatter.writeLine("import type { Long } from '@grpc/proto-loader';"); + } + if (messageType.fullName === '.google.protobuf.Any') { + formatter.writeLine("import type { AnyExtension } from '@grpc/proto-loader';"); + } + formatter.writeLine(''); + for (const childType of childTypes.sort(compareName)) { + const nameOverride = getTypeInterfaceName(childType); + if (childType instanceof Protobuf.Type) { + generatePermissiveMessageInterface(formatter, childType, options, nameOverride); + formatter.writeLine(''); + generateRestrictedMessageInterface(formatter, childType, options, nameOverride); + } + else { + generateEnumInterface(formatter, childType, options, nameOverride); + } + formatter.writeLine(''); + } + generatePermissiveMessageInterface(formatter, messageType, options); + formatter.writeLine(''); + generateRestrictedMessageInterface(formatter, messageType, options); +} +function generateEnumInterface(formatter, enumType, options, nameOverride) { + var _a, _b, _c; + const { inputName, outputName } = useNameFmter(options); + const name = nameOverride !== null && nameOverride !== void 0 ? nameOverride : enumType.name; + formatter.writeLine(`// Original file: ${(_b = ((_a = enumType.filename) !== null && _a !== void 0 ? _a : 'null')) === null || _b === void 0 ? void 0 : _b.replace(/\\/g, '/')}`); + formatter.writeLine(''); + if (options.includeComments) { + formatComment(formatter, enumType.comment, enumType.options); + } + formatter.writeLine(`export const ${name} = {`); + formatter.indent(); + for (const key of Object.keys(enumType.values)) { + if (options.includeComments) { + formatComment(formatter, enumType.comments[key], ((_c = enumType.valuesOptions) !== null && _c !== void 0 ? _c : {})[key]); + } + formatter.writeLine(`${key}: ${options.enums == String ? `'${key}'` : enumType.values[key]},`); + } + formatter.unindent(); + formatter.writeLine('} as const;'); + // Permissive Type + formatter.writeLine(''); + if (options.includeComments) { + formatComment(formatter, enumType.comment, enumType.options); + } + formatter.writeLine(`export type ${inputName(name)} =`); + formatter.indent(); + for (const key of Object.keys(enumType.values)) { + if (options.includeComments) { + formatComment(formatter, enumType.comments[key]); + } + formatter.writeLine(`| '${key}'`); + formatter.writeLine(`| ${enumType.values[key]}`); + } + formatter.unindent(); + // Restrictive Type + formatter.writeLine(''); + if (options.includeComments) { + formatComment(formatter, enumType.comment, enumType.options); + } + formatter.writeLine(`export type ${outputName(name)} = typeof ${name}[keyof typeof ${name}]`); +} +/** + * This is a list of methods that are exist in the generic Client class in the + * gRPC libraries. TypeScript has a problem with methods in subclasses with the + * same names as methods in the superclass, but with mismatched APIs. So, we + * avoid generating methods with these names in the service client interfaces. + * We always generate two service client methods per service method: one camel + * cased, and one with the original casing. So we will still generate one + * service client method for any conflicting name. + * + * Technically, at runtime conflicting name in the service client method + * actually shadows the original method, but TypeScript does not have a good + * way to represent that. So this change is not 100% accurate, but it gets the + * generated code to compile. + * + * This is just a list of the methods in the Client class definitions in + * grpc@1.24.11 and @grpc/grpc-js@1.4.0. + */ +const CLIENT_RESERVED_METHOD_NAMES = new Set([ + 'close', + 'getChannel', + 'waitForReady', + 'makeUnaryRequest', + 'makeClientStreamRequest', + 'makeServerStreamRequest', + 'makeBidiStreamRequest', + 'resolveCallInterceptors', + /* These methods are private, but TypeScript is not happy with overriding even + * private methods with mismatched APIs. */ + 'checkOptionalUnaryResponseArguments', + 'checkMetadataAndOptions' +]); +function generateServiceClientInterface(formatter, serviceType, options) { + const { outputName, inputName } = useNameFmter(options); + if (options.includeComments) { + formatComment(formatter, serviceType.comment, serviceType.options); + } + formatter.writeLine(`export interface ${serviceType.name}Client extends grpc.Client {`); + formatter.indent(); + for (const methodName of Object.keys(serviceType.methods).sort()) { + const method = serviceType.methods[methodName]; + for (const name of new Set([methodName, camelCase(methodName)])) { + if (CLIENT_RESERVED_METHOD_NAMES.has(name)) { + continue; + } + if (options.includeComments) { + formatComment(formatter, method.comment, method.options); + } + const requestType = inputName(getTypeInterfaceName(method.resolvedRequestType)); + const responseType = outputName(getTypeInterfaceName(method.resolvedResponseType)); + const callbackType = `grpc.requestCallback<${responseType}>`; + if (method.requestStream) { + if (method.responseStream) { + // Bidi streaming + const callType = `grpc.ClientDuplexStream<${requestType}, ${responseType}>`; + formatter.writeLine(`${name}(metadata: grpc.Metadata, options?: grpc.CallOptions): ${callType};`); + formatter.writeLine(`${name}(options?: grpc.CallOptions): ${callType};`); + } + else { + // Client streaming + const callType = `grpc.ClientWritableStream<${requestType}>`; + formatter.writeLine(`${name}(metadata: grpc.Metadata, options: grpc.CallOptions, callback: ${callbackType}): ${callType};`); + formatter.writeLine(`${name}(metadata: grpc.Metadata, callback: ${callbackType}): ${callType};`); + formatter.writeLine(`${name}(options: grpc.CallOptions, callback: ${callbackType}): ${callType};`); + formatter.writeLine(`${name}(callback: ${callbackType}): ${callType};`); + } + } + else { + if (method.responseStream) { + // Server streaming + const callType = `grpc.ClientReadableStream<${responseType}>`; + formatter.writeLine(`${name}(argument: ${requestType}, metadata: grpc.Metadata, options?: grpc.CallOptions): ${callType};`); + formatter.writeLine(`${name}(argument: ${requestType}, options?: grpc.CallOptions): ${callType};`); + } + else { + // Unary + const callType = 'grpc.ClientUnaryCall'; + formatter.writeLine(`${name}(argument: ${requestType}, metadata: grpc.Metadata, options: grpc.CallOptions, callback: ${callbackType}): ${callType};`); + formatter.writeLine(`${name}(argument: ${requestType}, metadata: grpc.Metadata, callback: ${callbackType}): ${callType};`); + formatter.writeLine(`${name}(argument: ${requestType}, options: grpc.CallOptions, callback: ${callbackType}): ${callType};`); + formatter.writeLine(`${name}(argument: ${requestType}, callback: ${callbackType}): ${callType};`); + } + } + } + formatter.writeLine(''); + } + formatter.unindent(); + formatter.writeLine('}'); +} +function generateServiceHandlerInterface(formatter, serviceType, options) { + const { inputName, outputName } = useNameFmter(options); + if (options.includeComments) { + formatComment(formatter, serviceType.comment, serviceType.options); + } + formatter.writeLine(`export interface ${serviceType.name}Handlers extends grpc.UntypedServiceImplementation {`); + formatter.indent(); + for (const methodName of Object.keys(serviceType.methods).sort()) { + const method = serviceType.methods[methodName]; + if (options.includeComments) { + formatComment(formatter, method.comment, serviceType.options); + } + const requestType = outputName(getTypeInterfaceName(method.resolvedRequestType)); + const responseType = inputName(getTypeInterfaceName(method.resolvedResponseType)); + if (method.requestStream) { + if (method.responseStream) { + // Bidi streaming + formatter.writeLine(`${methodName}: grpc.handleBidiStreamingCall<${requestType}, ${responseType}>;`); + } + else { + // Client streaming + formatter.writeLine(`${methodName}: grpc.handleClientStreamingCall<${requestType}, ${responseType}>;`); + } + } + else { + if (method.responseStream) { + // Server streaming + formatter.writeLine(`${methodName}: grpc.handleServerStreamingCall<${requestType}, ${responseType}>;`); + } + else { + // Unary + formatter.writeLine(`${methodName}: grpc.handleUnaryCall<${requestType}, ${responseType}>;`); + } + } + formatter.writeLine(''); + } + formatter.unindent(); + formatter.writeLine('}'); +} +function generateServiceDefinitionInterface(formatter, serviceType, options) { + const { inputName, outputName } = useNameFmter(options); + if (options.grpcLib) { + formatter.writeLine(`export interface ${serviceType.name}Definition extends grpc.ServiceDefinition {`); + } + else { + formatter.writeLine(`export interface ${serviceType.name}Definition {`); + } + formatter.indent(); + for (const methodName of Object.keys(serviceType.methods).sort()) { + const method = serviceType.methods[methodName]; + const requestType = getTypeInterfaceName(method.resolvedRequestType); + const responseType = getTypeInterfaceName(method.resolvedResponseType); + formatter.writeLine(`${methodName}: MethodDefinition<${inputName(requestType)}, ${inputName(responseType)}, ${outputName(requestType)}, ${outputName(responseType)}>`); + } + formatter.unindent(); + formatter.writeLine('}'); +} +function generateServiceInterfaces(formatter, serviceType, options) { + var _a, _b; + formatter.writeLine(`// Original file: ${(_b = ((_a = serviceType.filename) !== null && _a !== void 0 ? _a : 'null')) === null || _b === void 0 ? void 0 : _b.replace(/\\/g, '/')}`); + formatter.writeLine(''); + if (options.grpcLib) { + const grpcImportPath = options.grpcLib.startsWith('.') ? getPathToRoot(serviceType) + options.grpcLib : options.grpcLib; + formatter.writeLine(`import type * as grpc from '${grpcImportPath}'`); + } + formatter.writeLine(`import type { MethodDefinition } from '@grpc/proto-loader'`); + const dependencies = new Set(); + for (const method of serviceType.methodsArray) { + dependencies.add(method.resolvedRequestType); + dependencies.add(method.resolvedResponseType); + } + for (const dep of Array.from(dependencies.values()).sort(compareName)) { + formatter.writeLine(getImportLine(dep, serviceType, options)); + } + formatter.writeLine(''); + if (options.grpcLib) { + generateServiceClientInterface(formatter, serviceType, options); + formatter.writeLine(''); + generateServiceHandlerInterface(formatter, serviceType, options); + formatter.writeLine(''); + } + generateServiceDefinitionInterface(formatter, serviceType, options); +} +function containsDefinition(definitionType, namespace) { + for (const nested of namespace.nestedArray.sort(compareName)) { + if (nested instanceof definitionType) { + return true; + } + else if (isNamespaceBase(nested) && !(nested instanceof Protobuf.Type) && !(nested instanceof Protobuf.Enum) && containsDefinition(definitionType, nested)) { + return true; + } + } + return false; +} +function generateDefinitionImports(formatter, namespace, options) { + const imports = []; + if (containsDefinition(Protobuf.Enum, namespace)) { + imports.push('EnumTypeDefinition'); + } + if (containsDefinition(Protobuf.Type, namespace)) { + imports.push('MessageTypeDefinition'); + } + if (imports.length) { + formatter.writeLine(`import type { ${imports.join(', ')} } from '@grpc/proto-loader';`); + } +} +function generateDynamicImports(formatter, namespace, options) { + for (const nested of namespace.nestedArray.sort(compareName)) { + if (nested instanceof Protobuf.Service || nested instanceof Protobuf.Type) { + formatter.writeLine(getImportLine(nested, undefined, options)); + } + else if (isNamespaceBase(nested) && !(nested instanceof Protobuf.Enum)) { + generateDynamicImports(formatter, nested, options); + } + } +} +function generateSingleLoadedDefinitionType(formatter, nested, options) { + if (nested instanceof Protobuf.Service) { + if (options.includeComments) { + formatComment(formatter, nested.comment, nested.options); + } + const typeInterfaceName = getTypeInterfaceName(nested); + formatter.writeLine(`${nested.name}: SubtypeConstructor & { service: ${typeInterfaceName}Definition }`); + } + else if (nested instanceof Protobuf.Enum) { + formatter.writeLine(`${nested.name}: EnumTypeDefinition`); + } + else if (nested instanceof Protobuf.Type) { + const typeInterfaceName = getTypeInterfaceName(nested); + const { inputName, outputName } = useNameFmter(options); + formatter.writeLine(`${nested.name}: MessageTypeDefinition<${inputName(typeInterfaceName)}, ${outputName(typeInterfaceName)}>`); + } + else if (isNamespaceBase(nested)) { + generateLoadedDefinitionTypes(formatter, nested, options); + } +} +function generateLoadedDefinitionTypes(formatter, namespace, options) { + formatter.writeLine(`${namespace.name}: {`); + formatter.indent(); + for (const nested of namespace.nestedArray.sort(compareName)) { + generateSingleLoadedDefinitionType(formatter, nested, options); + } + formatter.unindent(); + formatter.writeLine('}'); +} +function generateRootFile(formatter, root, options) { + if (!options.grpcLib) { + return; + } + formatter.writeLine(`import type * as grpc from '${options.grpcLib}';`); + generateDefinitionImports(formatter, root, options); + formatter.writeLine(''); + generateDynamicImports(formatter, root, options); + formatter.writeLine(''); + formatter.writeLine('type SubtypeConstructor any, Subtype> = {'); + formatter.writeLine(' new(...args: ConstructorParameters): Subtype;'); + formatter.writeLine('};'); + formatter.writeLine(''); + formatter.writeLine('export interface ProtoGrpcType {'); + formatter.indent(); + for (const nested of root.nestedArray) { + generateSingleLoadedDefinitionType(formatter, nested, options); + } + formatter.unindent(); + formatter.writeLine('}'); + formatter.writeLine(''); +} +async function writeFile(filename, contents) { + await fs.promises.mkdir(path.dirname(filename), { recursive: true }); + return fs.promises.writeFile(filename, contents); +} +function generateFilesForNamespace(namespace, options) { + const filePromises = []; + for (const nested of namespace.nestedArray) { + const fileFormatter = new TextFormatter(); + if (nested instanceof Protobuf.Type) { + generateMessageInterfaces(fileFormatter, nested, options); + if (options.verbose) { + console.log(`Writing ${options.outDir}/${getPath(nested, options)} from file ${nested.filename}`); + } + filePromises.push(writeFile(`${options.outDir}/${getPath(nested, options)}`, fileFormatter.getFullText())); + } + else if (nested instanceof Protobuf.Enum) { + generateEnumInterface(fileFormatter, nested, options); + if (options.verbose) { + console.log(`Writing ${options.outDir}/${getPath(nested, options)} from file ${nested.filename}`); + } + filePromises.push(writeFile(`${options.outDir}/${getPath(nested, options)}`, fileFormatter.getFullText())); + } + else if (nested instanceof Protobuf.Service) { + generateServiceInterfaces(fileFormatter, nested, options); + if (options.verbose) { + console.log(`Writing ${options.outDir}/${getPath(nested, options)} from file ${nested.filename}`); + } + filePromises.push(writeFile(`${options.outDir}/${getPath(nested, options)}`, fileFormatter.getFullText())); + } + else if (isNamespaceBase(nested)) { + filePromises.push(...generateFilesForNamespace(nested, options)); + } + } + return filePromises; +} +function writeFilesForRoot(root, masterFileName, options) { + const filePromises = []; + const masterFileFormatter = new TextFormatter(); + if (options.grpcLib) { + generateRootFile(masterFileFormatter, root, options); + if (options.verbose) { + console.log(`Writing ${options.outDir}/${masterFileName}`); + } + filePromises.push(writeFile(`${options.outDir}/${masterFileName}`, masterFileFormatter.getFullText())); + } + filePromises.push(...generateFilesForNamespace(root, options)); + return filePromises; +} +async function writeAllFiles(protoFiles, options) { + await fs.promises.mkdir(options.outDir, { recursive: true }); + const basenameMap = new Map(); + for (const filename of protoFiles) { + const basename = path.basename(filename).replace(/\.proto$/, options.targetFileExtension); + if (basenameMap.has(basename)) { + basenameMap.get(basename).push(filename); + } + else { + basenameMap.set(basename, [filename]); + } + } + for (const [basename, filenames] of basenameMap.entries()) { + const loadedRoot = await (0, util_1.loadProtosWithOptions)(filenames, options); + writeFilesForRoot(loadedRoot, basename, options); + } +} +async function runScript() { + const boolDefaultFalseOption = { + boolean: true, + default: false, + }; + const argv = await yargs + .parserConfiguration({ + 'parse-positional-numbers': false + }) + .option('keepCase', boolDefaultFalseOption) + .option('longs', { string: true, default: 'Long' }) + .option('enums', { string: true, default: 'number' }) + .option('bytes', { string: true, default: 'Buffer' }) + .option('defaults', boolDefaultFalseOption) + .option('arrays', boolDefaultFalseOption) + .option('objects', boolDefaultFalseOption) + .option('oneofs', boolDefaultFalseOption) + .option('json', boolDefaultFalseOption) + .boolean('verbose') + .option('includeComments', boolDefaultFalseOption) + .option('includeDirs', { + normalize: true, + array: true, + alias: 'I' + }) + .option('outDir', { + alias: 'O', + normalize: true, + }) + .option('grpcLib', { string: true }) + .option('inputTemplate', { string: true, default: `${templateStr}` }) + .option('outputTemplate', { string: true, default: `${templateStr}__Output` }) + .option('inputBranded', boolDefaultFalseOption) + .option('outputBranded', boolDefaultFalseOption) + .option('targetFileExtension', { string: true, default: '.ts' }) + .option('importFileExtension', { string: true, default: '' }) + .coerce('longs', value => { + switch (value) { + case 'String': return String; + case 'Number': return Number; + default: return undefined; + } + }).coerce('enums', value => { + if (value === 'String') { + return String; + } + else { + return undefined; + } + }).coerce('bytes', value => { + switch (value) { + case 'Array': return Array; + case 'String': return String; + default: return undefined; + } + }) + .alias({ + verbose: 'v' + }).describe({ + keepCase: 'Preserve the case of field names', + longs: 'The type that should be used to output 64 bit integer values. Can be String, Number', + enums: 'The type that should be used to output enum fields. Can be String', + bytes: 'The type that should be used to output bytes fields. Can be String, Array', + defaults: 'Output default values for omitted fields', + arrays: 'Output default values for omitted repeated fields even if --defaults is not set', + objects: 'Output default values for omitted message fields even if --defaults is not set', + oneofs: 'Output virtual oneof fields set to the present field\'s name', + json: 'Represent Infinity and NaN as strings in float fields. Also decode google.protobuf.Any automatically', + includeComments: 'Generate doc comments from comments in the original files', + includeDirs: 'Directories to search for included files', + outDir: 'Directory in which to output files', + grpcLib: 'The gRPC implementation library that these types will be used with. If not provided, some types will not be generated', + inputTemplate: 'Template for mapping input or "permissive" type names', + outputTemplate: 'Template for mapping output or "restricted" type names', + inputBranded: 'Output property for branded type for "permissive" types with fullName of the Message as its value', + outputBranded: 'Output property for branded type for "restricted" types with fullName of the Message as its value', + targetFileExtension: 'File extension for generated files.', + importFileExtension: 'File extension for import specifiers in generated code.' + }).demandOption(['outDir']) + .demand(1) + .usage('$0 [options] filenames...') + .epilogue('WARNING: This tool is in alpha. The CLI and generated code are subject to change') + .argv; + if (argv.verbose) { + console.log('Parsed arguments:', argv); + } + (0, util_1.addCommonProtos)(); + writeAllFiles(argv._, Object.assign(Object.assign({}, argv), { alternateCommentMode: true })).then(() => { + if (argv.verbose) { + console.log('Success'); + } + }, (error) => { + console.error(error); + process.exit(1); + }); +} +if (require.main === module) { + runScript(); +} +//# sourceMappingURL=proto-loader-gen-types.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js.map b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js.map new file mode 100644 index 0000000..8a260e4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"proto-loader-gen-types.js","sourceRoot":"","sources":["../../bin/proto-loader-gen-types.ts"],"names":[],"mappings":";;AACA;;;;;;;;;;;;;;;;GAgBG;;AAEH,yBAAyB;AACzB,6BAA6B;AAE7B,uCAAuC;AACvC,+BAA+B;AAE/B,8CAA+C;AAC/C,sCAAqE;AAErE,MAAM,WAAW,GAAG,IAAI,CAAC;AACzB,MAAM,YAAY,GAAG,CAAC,EAAC,cAAc,EAAE,aAAa,EAAmB,EAAE,EAAE;IACzE,IAAI,cAAc,KAAK,aAAa,EAAE;QACpC,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAA;KAChE;IACD,OAAO;QACL,UAAU,EAAE,CAAC,CAAS,EAAE,EAAE,CAAC,cAAc,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;QACjE,SAAS,EAAE,CAAC,CAAS,EAAE,EAAE,CAAC,aAAa,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;KAChE,CAAC;AACJ,CAAC,CAAA;AAgBD,MAAM,aAAa;IAIjB;QAHiB,eAAU,GAAG,IAAI,CAAC;QAC3B,gBAAW,GAAG,CAAC,CAAC;QAChB,cAAS,GAAa,EAAE,CAAC;IAClB,CAAC;IAEhB,MAAM;QACJ,IAAI,CAAC,WAAW,IAAI,CAAC,CAAC;IACxB,CAAC;IAED,QAAQ;QACN,IAAI,CAAC,WAAW,IAAI,CAAC,CAAC;IACxB,CAAC;IAED,SAAS,CAAC,IAAY;QACpB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ACH,CAAC,EAAE,CAAC,KAAK,EAAE,EAAE;QACX,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;QACpB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE;IAC3B,SAAS,EAAE,CAAC;CACb"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/index.d.ts b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/index.d.ts new file mode 100644 index 0000000..34b8fa4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/index.d.ts @@ -0,0 +1,162 @@ +/** + * @license + * Copyright 2018 gRPC authors. + * + * 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. + * + */ +/// +import * as Protobuf from 'protobufjs'; +import * as descriptor from 'protobufjs/ext/descriptor'; +import { Options } from './util'; +import Long = require('long'); +export { Options, Long }; +/** + * This type exists for use with code generated by the proto-loader-gen-types + * tool. This type should be used with another interface, e.g. + * MessageType & AnyExtension for an object that is converted to or from a + * google.protobuf.Any message. + * For example, when processing an Any message: + * + * ```ts + * if (isAnyExtension(message)) { + * switch (message['@type']) { + * case TYPE1_URL: + * handleType1(message as AnyExtension & Type1); + * break; + * case TYPE2_URL: + * handleType2(message as AnyExtension & Type2); + * break; + * // ... + * } + * } + * ``` + */ +export interface AnyExtension { + /** + * The fully qualified name of the message type that this object represents, + * possibly including a URL prefix. + */ + '@type': string; +} +export declare function isAnyExtension(obj: object): obj is AnyExtension; +declare module 'protobufjs' { + interface Type { + toDescriptor(protoVersion: string): Protobuf.Message & descriptor.IDescriptorProto; + } + interface RootConstructor { + new (options?: Options): Root; + fromDescriptor(descriptorSet: descriptor.IFileDescriptorSet | Protobuf.Reader | Uint8Array): Root; + fromJSON(json: Protobuf.INamespace, root?: Root): Root; + } + interface Root { + toDescriptor(protoVersion: string): Protobuf.Message & descriptor.IFileDescriptorSet; + } + interface Enum { + toDescriptor(protoVersion: string): Protobuf.Message & descriptor.IEnumDescriptorProto; + } +} +export interface Serialize { + (value: T): Buffer; +} +export interface Deserialize { + (bytes: Buffer): T; +} +export interface ProtobufTypeDefinition { + format: string; + type: object; + fileDescriptorProtos: Buffer[]; +} +export interface MessageTypeDefinition extends ProtobufTypeDefinition { + format: 'Protocol Buffer 3 DescriptorProto'; + serialize: Serialize; + deserialize: Deserialize; +} +export interface EnumTypeDefinition extends ProtobufTypeDefinition { + format: 'Protocol Buffer 3 EnumDescriptorProto'; +} +export declare enum IdempotencyLevel { + IDEMPOTENCY_UNKNOWN = "IDEMPOTENCY_UNKNOWN", + NO_SIDE_EFFECTS = "NO_SIDE_EFFECTS", + IDEMPOTENT = "IDEMPOTENT" +} +export interface NamePart { + name_part: string; + is_extension: boolean; +} +export interface UninterpretedOption { + name?: NamePart[]; + identifier_value?: string; + positive_int_value?: number; + negative_int_value?: number; + double_value?: number; + string_value?: string; + aggregate_value?: string; +} +export interface MethodOptions { + deprecated: boolean; + idempotency_level: IdempotencyLevel; + uninterpreted_option: UninterpretedOption[]; + [k: string]: unknown; +} +export interface MethodDefinition { + path: string; + requestStream: boolean; + responseStream: boolean; + requestSerialize: Serialize; + responseSerialize: Serialize; + requestDeserialize: Deserialize; + responseDeserialize: Deserialize; + originalName?: string; + requestType: MessageTypeDefinition; + responseType: MessageTypeDefinition; + options: MethodOptions; +} +export interface ServiceDefinition { + [index: string]: MethodDefinition; +} +export declare type AnyDefinition = ServiceDefinition | MessageTypeDefinition | EnumTypeDefinition; +export interface PackageDefinition { + [index: string]: AnyDefinition; +} +/** + * Load a .proto file with the specified options. + * @param filename One or multiple file paths to load. Can be an absolute path + * or relative to an include path. + * @param options.keepCase Preserve field names. The default is to change them + * to camel case. + * @param options.longs The type that should be used to represent `long` values. + * Valid options are `Number` and `String`. Defaults to a `Long` object type + * from a library. + * @param options.enums The type that should be used to represent `enum` values. + * The only valid option is `String`. Defaults to the numeric value. + * @param options.bytes The type that should be used to represent `bytes` + * values. Valid options are `Array` and `String`. The default is to use + * `Buffer`. + * @param options.defaults Set default values on output objects. Defaults to + * `false`. + * @param options.arrays Set empty arrays for missing array values even if + * `defaults` is `false`. Defaults to `false`. + * @param options.objects Set empty objects for missing object values even if + * `defaults` is `false`. Defaults to `false`. + * @param options.oneofs Set virtual oneof properties to the present field's + * name + * @param options.json Represent Infinity and NaN as strings in float fields, + * and automatically decode google.protobuf.Any values. + * @param options.includeDirs Paths to search for imported `.proto` files. + */ +export declare function load(filename: string | string[], options?: Options): Promise; +export declare function loadSync(filename: string | string[], options?: Options): PackageDefinition; +export declare function fromJSON(json: Protobuf.INamespace, options?: Options): PackageDefinition; +export declare function loadFileDescriptorSetFromBuffer(descriptorSet: Buffer, options?: Options): PackageDefinition; +export declare function loadFileDescriptorSetFromObject(descriptorSet: Parameters[0], options?: Options): PackageDefinition; diff --git a/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/index.js b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/index.js new file mode 100644 index 0000000..69b4431 --- /dev/null +++ b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/index.js @@ -0,0 +1,246 @@ +"use strict"; +/** + * @license + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.loadFileDescriptorSetFromObject = exports.loadFileDescriptorSetFromBuffer = exports.fromJSON = exports.loadSync = exports.load = exports.IdempotencyLevel = exports.isAnyExtension = exports.Long = void 0; +const camelCase = require("lodash.camelcase"); +const Protobuf = require("protobufjs"); +const descriptor = require("protobufjs/ext/descriptor"); +const util_1 = require("./util"); +const Long = require("long"); +exports.Long = Long; +function isAnyExtension(obj) { + return ('@type' in obj) && (typeof obj['@type'] === 'string'); +} +exports.isAnyExtension = isAnyExtension; +var IdempotencyLevel; +(function (IdempotencyLevel) { + IdempotencyLevel["IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN"; + IdempotencyLevel["NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS"; + IdempotencyLevel["IDEMPOTENT"] = "IDEMPOTENT"; +})(IdempotencyLevel = exports.IdempotencyLevel || (exports.IdempotencyLevel = {})); +const descriptorOptions = { + longs: String, + enums: String, + bytes: String, + defaults: true, + oneofs: true, + json: true, +}; +function joinName(baseName, name) { + if (baseName === '') { + return name; + } + else { + return baseName + '.' + name; + } +} +function isHandledReflectionObject(obj) { + return (obj instanceof Protobuf.Service || + obj instanceof Protobuf.Type || + obj instanceof Protobuf.Enum); +} +function isNamespaceBase(obj) { + return obj instanceof Protobuf.Namespace || obj instanceof Protobuf.Root; +} +function getAllHandledReflectionObjects(obj, parentName) { + const objName = joinName(parentName, obj.name); + if (isHandledReflectionObject(obj)) { + return [[objName, obj]]; + } + else { + if (isNamespaceBase(obj) && typeof obj.nested !== 'undefined') { + return Object.keys(obj.nested) + .map(name => { + return getAllHandledReflectionObjects(obj.nested[name], objName); + }) + .reduce((accumulator, currentValue) => accumulator.concat(currentValue), []); + } + } + return []; +} +function createDeserializer(cls, options) { + return function deserialize(argBuf) { + return cls.toObject(cls.decode(argBuf), options); + }; +} +function createSerializer(cls) { + return function serialize(arg) { + if (Array.isArray(arg)) { + throw new Error(`Failed to serialize message: expected object with ${cls.name} structure, got array instead`); + } + const message = cls.fromObject(arg); + return cls.encode(message).finish(); + }; +} +function mapMethodOptions(options) { + return (options || []).reduce((obj, item) => { + for (const [key, value] of Object.entries(item)) { + switch (key) { + case 'uninterpreted_option': + obj.uninterpreted_option.push(item.uninterpreted_option); + break; + default: + obj[key] = value; + } + } + return obj; + }, { + deprecated: false, + idempotency_level: IdempotencyLevel.IDEMPOTENCY_UNKNOWN, + uninterpreted_option: [], + }); +} +function createMethodDefinition(method, serviceName, options, fileDescriptors) { + /* This is only ever called after the corresponding root.resolveAll(), so we + * can assume that the resolved request and response types are non-null */ + const requestType = method.resolvedRequestType; + const responseType = method.resolvedResponseType; + return { + path: '/' + serviceName + '/' + method.name, + requestStream: !!method.requestStream, + responseStream: !!method.responseStream, + requestSerialize: createSerializer(requestType), + requestDeserialize: createDeserializer(requestType, options), + responseSerialize: createSerializer(responseType), + responseDeserialize: createDeserializer(responseType, options), + // TODO(murgatroid99): Find a better way to handle this + originalName: camelCase(method.name), + requestType: createMessageDefinition(requestType, options, fileDescriptors), + responseType: createMessageDefinition(responseType, options, fileDescriptors), + options: mapMethodOptions(method.parsedOptions), + }; +} +function createServiceDefinition(service, name, options, fileDescriptors) { + const def = {}; + for (const method of service.methodsArray) { + def[method.name] = createMethodDefinition(method, name, options, fileDescriptors); + } + return def; +} +function createMessageDefinition(message, options, fileDescriptors) { + const messageDescriptor = message.toDescriptor('proto3'); + return { + format: 'Protocol Buffer 3 DescriptorProto', + type: messageDescriptor.$type.toObject(messageDescriptor, descriptorOptions), + fileDescriptorProtos: fileDescriptors, + serialize: createSerializer(message), + deserialize: createDeserializer(message, options) + }; +} +function createEnumDefinition(enumType, fileDescriptors) { + const enumDescriptor = enumType.toDescriptor('proto3'); + return { + format: 'Protocol Buffer 3 EnumDescriptorProto', + type: enumDescriptor.$type.toObject(enumDescriptor, descriptorOptions), + fileDescriptorProtos: fileDescriptors, + }; +} +/** + * function createDefinition(obj: Protobuf.Service, name: string, options: + * Options): ServiceDefinition; function createDefinition(obj: Protobuf.Type, + * name: string, options: Options): MessageTypeDefinition; function + * createDefinition(obj: Protobuf.Enum, name: string, options: Options): + * EnumTypeDefinition; + */ +function createDefinition(obj, name, options, fileDescriptors) { + if (obj instanceof Protobuf.Service) { + return createServiceDefinition(obj, name, options, fileDescriptors); + } + else if (obj instanceof Protobuf.Type) { + return createMessageDefinition(obj, options, fileDescriptors); + } + else if (obj instanceof Protobuf.Enum) { + return createEnumDefinition(obj, fileDescriptors); + } + else { + throw new Error('Type mismatch in reflection object handling'); + } +} +function createPackageDefinition(root, options) { + const def = {}; + root.resolveAll(); + const descriptorList = root.toDescriptor('proto3').file; + const bufferList = descriptorList.map(value => Buffer.from(descriptor.FileDescriptorProto.encode(value).finish())); + for (const [name, obj] of getAllHandledReflectionObjects(root, '')) { + def[name] = createDefinition(obj, name, options, bufferList); + } + return def; +} +function createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options) { + options = options || {}; + const root = Protobuf.Root.fromDescriptor(decodedDescriptorSet); + root.resolveAll(); + return createPackageDefinition(root, options); +} +/** + * Load a .proto file with the specified options. + * @param filename One or multiple file paths to load. Can be an absolute path + * or relative to an include path. + * @param options.keepCase Preserve field names. The default is to change them + * to camel case. + * @param options.longs The type that should be used to represent `long` values. + * Valid options are `Number` and `String`. Defaults to a `Long` object type + * from a library. + * @param options.enums The type that should be used to represent `enum` values. + * The only valid option is `String`. Defaults to the numeric value. + * @param options.bytes The type that should be used to represent `bytes` + * values. Valid options are `Array` and `String`. The default is to use + * `Buffer`. + * @param options.defaults Set default values on output objects. Defaults to + * `false`. + * @param options.arrays Set empty arrays for missing array values even if + * `defaults` is `false`. Defaults to `false`. + * @param options.objects Set empty objects for missing object values even if + * `defaults` is `false`. Defaults to `false`. + * @param options.oneofs Set virtual oneof properties to the present field's + * name + * @param options.json Represent Infinity and NaN as strings in float fields, + * and automatically decode google.protobuf.Any values. + * @param options.includeDirs Paths to search for imported `.proto` files. + */ +function load(filename, options) { + return (0, util_1.loadProtosWithOptions)(filename, options).then(loadedRoot => { + return createPackageDefinition(loadedRoot, options); + }); +} +exports.load = load; +function loadSync(filename, options) { + const loadedRoot = (0, util_1.loadProtosWithOptionsSync)(filename, options); + return createPackageDefinition(loadedRoot, options); +} +exports.loadSync = loadSync; +function fromJSON(json, options) { + options = options || {}; + const loadedRoot = Protobuf.Root.fromJSON(json); + loadedRoot.resolveAll(); + return createPackageDefinition(loadedRoot, options); +} +exports.fromJSON = fromJSON; +function loadFileDescriptorSetFromBuffer(descriptorSet, options) { + const decodedDescriptorSet = descriptor.FileDescriptorSet.decode(descriptorSet); + return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); +} +exports.loadFileDescriptorSetFromBuffer = loadFileDescriptorSetFromBuffer; +function loadFileDescriptorSetFromObject(descriptorSet, options) { + const decodedDescriptorSet = descriptor.FileDescriptorSet.fromObject(descriptorSet); + return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); +} +exports.loadFileDescriptorSetFromObject = loadFileDescriptorSetFromObject; +(0, util_1.addCommonProtos)(); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/index.js.map b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/index.js.map new file mode 100644 index 0000000..ce3c911 --- /dev/null +++ b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;GAgBG;;;AAEH,8CAA+C;AAC/C,uCAAuC;AACvC,wDAAwD;AAExD,iCAAoG;AAEpG,6BAA8B;AAEZ,oBAAI;AA+BtB,SAAgB,cAAc,CAAC,GAAW;IACxC,OAAO,CAAC,OAAO,IAAI,GAAG,CAAC,IAAI,CAA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 No newline at end of file diff --git a/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/util.d.ts b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/util.d.ts new file mode 100644 index 0000000..d0b13d9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/util.d.ts @@ -0,0 +1,27 @@ +/** + * @license + * Copyright 2018 gRPC authors. + * + * 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. + * + */ +import * as Protobuf from 'protobufjs'; +export declare type Options = Protobuf.IParseOptions & Protobuf.IConversionOptions & { + includeDirs?: string[]; +}; +export declare function loadProtosWithOptions(filename: string | string[], options?: Options): Promise; +export declare function loadProtosWithOptionsSync(filename: string | string[], options?: Options): Protobuf.Root; +/** + * Load Google's well-known proto files that aren't exposed by Protobuf.js. + */ +export declare function addCommonProtos(): void; diff --git a/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/util.js b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/util.js new file mode 100644 index 0000000..7ade36b --- /dev/null +++ b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/util.js @@ -0,0 +1,89 @@ +"use strict"; +/** + * @license + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.addCommonProtos = exports.loadProtosWithOptionsSync = exports.loadProtosWithOptions = void 0; +const fs = require("fs"); +const path = require("path"); +const Protobuf = require("protobufjs"); +function addIncludePathResolver(root, includePaths) { + const originalResolvePath = root.resolvePath; + root.resolvePath = (origin, target) => { + if (path.isAbsolute(target)) { + return target; + } + for (const directory of includePaths) { + const fullPath = path.join(directory, target); + try { + fs.accessSync(fullPath, fs.constants.R_OK); + return fullPath; + } + catch (err) { + continue; + } + } + process.emitWarning(`${target} not found in any of the include paths ${includePaths}`); + return originalResolvePath(origin, target); + }; +} +async function loadProtosWithOptions(filename, options) { + const root = new Protobuf.Root(); + options = options || {}; + if (!!options.includeDirs) { + if (!Array.isArray(options.includeDirs)) { + return Promise.reject(new Error('The includeDirs option must be an array')); + } + addIncludePathResolver(root, options.includeDirs); + } + const loadedRoot = await root.load(filename, options); + loadedRoot.resolveAll(); + return loadedRoot; +} +exports.loadProtosWithOptions = loadProtosWithOptions; +function loadProtosWithOptionsSync(filename, options) { + const root = new Protobuf.Root(); + options = options || {}; + if (!!options.includeDirs) { + if (!Array.isArray(options.includeDirs)) { + throw new Error('The includeDirs option must be an array'); + } + addIncludePathResolver(root, options.includeDirs); + } + const loadedRoot = root.loadSync(filename, options); + loadedRoot.resolveAll(); + return loadedRoot; +} +exports.loadProtosWithOptionsSync = loadProtosWithOptionsSync; +/** + * Load Google's well-known proto files that aren't exposed by Protobuf.js. + */ +function addCommonProtos() { + // Protobuf.js exposes: any, duration, empty, field_mask, struct, timestamp, + // and wrappers. compiler/plugin is excluded in Protobuf.js and here. + // Using constant strings for compatibility with tools like Webpack + const apiDescriptor = require('protobufjs/google/protobuf/api.json'); + const descriptorDescriptor = require('protobufjs/google/protobuf/descriptor.json'); + const sourceContextDescriptor = require('protobufjs/google/protobuf/source_context.json'); + const typeDescriptor = require('protobufjs/google/protobuf/type.json'); + Protobuf.common('api', apiDescriptor.nested.google.nested.protobuf.nested); + Protobuf.common('descriptor', descriptorDescriptor.nested.google.nested.protobuf.nested); + Protobuf.common('source_context', sourceContextDescriptor.nested.google.nested.protobuf.nested); + Protobuf.common('type', typeDescriptor.nested.google.nested.protobuf.nested); +} +exports.addCommonProtos = addCommonProtos; +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/util.js.map b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/util.js.map new file mode 100644 index 0000000..bb517f7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/build/src/util.js.map @@ -0,0 +1 @@ +{"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/util.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;GAgBG;;;AAEH,yBAAyB;AACzB,6BAA6B;AAC7B,uCAAuC;AAEvC,SAAS,sBAAsB,CAAC,IAAmB,EAAE,YAAsB;IACzE,MAAM,mBAAmB,GAAG,IAAI,CAAC,WAAW,CAAC;IAC7C,IAAI,CAAC,WAAW,GAAG,CAAC,MAAc,EAAE,MAAc,EAAE,EAAE;QACpD,IAAI,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE;YAC3B,OAAO,MAAM,CAAC;SACf;QACD,KAAK,MAAM,SAAS,IAAI,YAAY,EAAE;YACpC,MAAM,QAAQ,GAAW,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;YACtD,IAAI;gBACF,EAAE,CAAC,UAAU,CAAC,QAAQ,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;gBAC3C,OAAO,QAAQ,CAAC;aACjB;YAAC,OAAO,GAAG,EAAE;gBACZ,SAAS;aACV;SACF;QACD,OAAO,CAAC,WAAW,CAAC,GAAG,MAAM,0CAA0C,YAAY,EAAE,CAAC,CAAC;QACvF,OAAO,mBAAmB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7C,CAAC,CAAC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;IAC5E,qEAAqE;IAErE,mEAAmE;IACnE,MAAM,aAAa,GAAG,OAAO,CAAC,qCAAqC,CAAC,CAAC;IACrE,MAAM,oBAAoB,GAAG,OAAO,CAAC,4CAA4C,CAAC,CAAC;IACnF,MAAM,uBAAuB,GAAG,OAAO,CAAC,gDAAgD,CAAC,CAAC;IAC1F,MAAM,cAAc,GAAG,OAAO,CAAC,sCAAsC,CAAC,CAAC;IAEvE,QAAQ,CAAC,MAAM,CACb,KAAK,EACL,aAAa,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CACnD,CAAC;IACF,QAAQ,CAAC,MAAM,CACb,YAAY,EACZ,oBAAoB,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAC1D,CAAC;IACF,QAAQ,CAAC,MAAM,CACb,gBAAgB,EAChB,uBAAuB,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAC7D,CAAC;IACF,QAAQ,CAAC,MAAM,CACb,MAAM,EACN,cAAc,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CACpD,CAAC;AACJ,CAAC;AA1BD,0CA0BC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/package.json b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/package.json new file mode 100644 index 0000000..c14a7bb --- /dev/null +++ b/node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader/package.json @@ -0,0 +1,69 @@ +{ + "name": "@grpc/proto-loader", + "version": "0.8.0", + "author": "Google Inc.", + "contributors": [ + { + "name": "Michael Lumish", + "email": "mlumish@google.com" + } + ], + "description": "gRPC utility library for loading .proto files", + "homepage": "https://grpc.io/", + "main": "build/src/index.js", + "typings": "build/src/index.d.ts", + "scripts": { + "build": "npm run compile", + "clean": "rimraf ./build", + "compile": "tsc -p .", + "format": "clang-format -i -style=\"{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}\" src/*.ts test/*.ts", + "lint": "tslint -c node_modules/google-ts-style/tslint.json -p . -t codeFrame --type-check", + "prepare": "npm run compile", + "test": "gulp test", + "check": "gts check", + "fix": "gts fix", + "pretest": "npm run compile", + "posttest": "npm run check", + "generate-golden": "node ./build/bin/proto-loader-gen-types.js --keepCase --longs=String --enums=String --defaults --oneofs --json --includeComments --inputTemplate=I%s --outputTemplate=O%s -I deps/gapic-showcase/schema/ deps/googleapis/ -O ./golden-generated --grpcLib @grpc/grpc-js google/showcase/v1beta1/echo.proto", + "validate-golden": "rm -rf ./golden-generated-old && mv ./golden-generated/ ./golden-generated-old && npm run generate-golden && diff -rb ./golden-generated ./golden-generated-old" + }, + "repository": { + "type": "git", + "url": "https://github.com/grpc/grpc-node.git" + }, + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/grpc/grpc-node/issues" + }, + "files": [ + "LICENSE", + "build/src/*.d.ts", + "build/src/*.{js,js.map}", + "build/bin/*.{js,js.map}" + ], + "bin": { + "proto-loader-gen-types": "./build/bin/proto-loader-gen-types.js" + }, + "dependencies": { + "lodash.camelcase": "^4.3.0", + "long": "^5.0.0", + "protobufjs": "^7.5.3", + "yargs": "^17.7.2" + }, + "devDependencies": { + "@types/lodash.camelcase": "^4.3.4", + "@types/mkdirp": "^1.0.1", + "@types/mocha": "^5.2.7", + "@types/node": "^10.17.26", + "@types/yargs": "^17.0.24", + "clang-format": "^1.2.2", + "google-proto-files": "^3.0.2", + "gts": "^3.1.0", + "rimraf": "^3.0.2", + "ts-node": "^10.9.2", + "typescript": "~4.7.4" + }, + "engines": { + "node": ">=6" + } +} diff --git a/node_modules/@grpc/grpc-js/package.json b/node_modules/@grpc/grpc-js/package.json new file mode 100644 index 0000000..b157dc3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/package.json @@ -0,0 +1,89 @@ +{ + "name": "@grpc/grpc-js", + "version": "1.14.2", + "description": "gRPC Library for Node - pure JS implementation", + "homepage": "https://grpc.io/", + "repository": "https://github.com/grpc/grpc-node/tree/master/packages/grpc-js", + "main": "build/src/index.js", + "engines": { + "node": ">=12.10.0" + }, + "keywords": [], + "author": { + "name": "Google Inc." + }, + "types": "build/src/index.d.ts", + "license": "Apache-2.0", + "devDependencies": { + "@grpc/proto-loader": "file:../proto-loader", + "@types/gulp": "^4.0.17", + "@types/gulp-mocha": "0.0.37", + "@types/lodash": "^4.14.202", + "@types/mocha": "^10.0.6", + "@types/ncp": "^2.0.8", + "@types/node": ">=20.11.20", + "@types/pify": "^5.0.4", + "@types/semver": "^7.5.8", + "@typescript-eslint/eslint-plugin": "^7.1.0", + "@typescript-eslint/parser": "^7.1.0", + "@typescript-eslint/typescript-estree": "^7.1.0", + "clang-format": "^1.8.0", + "eslint": "^8.42.0", + "eslint-config-prettier": "^8.8.0", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-prettier": "^4.2.1", + "execa": "^2.0.3", + "gulp": "^4.0.2", + "gulp-mocha": "^6.0.0", + "lodash": "^4.17.21", + "madge": "^5.0.1", + "mocha-jenkins-reporter": "^0.4.1", + "ncp": "^2.0.0", + "pify": "^4.0.1", + "prettier": "^2.8.8", + "rimraf": "^3.0.2", + "semver": "^7.6.0", + "ts-node": "^10.9.2", + "typescript": "^5.3.3" + }, + "contributors": [ + { + "name": "Google Inc." + } + ], + "scripts": { + "build": "npm run compile", + "clean": "rimraf ./build", + "compile": "tsc -p .", + "format": "clang-format -i -style=\"{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}\" src/*.ts test/*.ts", + "lint": "eslint src/*.ts test/*.ts", + "prepare": "npm run copy-protos && npm run generate-types && npm run generate-test-types && npm run compile", + "test": "gulp test", + "check": "npm run lint", + "fix": "eslint --fix src/*.ts test/*.ts", + "pretest": "npm run generate-types && npm run generate-test-types && npm run compile", + "posttest": "npm run check && madge -c ./build/src", + "generate-types": "proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --includeDirs proto/ --include-dirs proto/ proto/xds/ proto/protoc-gen-validate/ -O src/generated/ --grpcLib ../index channelz.proto xds/service/orca/v3/orca.proto", + "generate-test-types": "proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --include-dirs test/fixtures/ -O test/generated/ --grpcLib ../../src/index test_service.proto echo_service.proto", + "copy-protos": "node ./copy-protos" + }, + "dependencies": { + "@grpc/proto-loader": "^0.8.0", + "@js-sdsl/ordered-map": "^4.4.2" + }, + "files": [ + "src/**/*.ts", + "build/src/**/*.{js,d.ts,js.map}", + "proto/**/*.proto", + "proto/**/LICENSE", + "LICENSE", + "deps/envoy-api/envoy/api/v2/**/*.proto", + "deps/envoy-api/envoy/config/**/*.proto", + "deps/envoy-api/envoy/service/**/*.proto", + "deps/envoy-api/envoy/type/**/*.proto", + "deps/udpa/udpa/**/*.proto", + "deps/googleapis/google/api/*.proto", + "deps/googleapis/google/rpc/*.proto", + "deps/protoc-gen-validate/validate/**/*.proto" + ] +} diff --git a/node_modules/@grpc/grpc-js/proto/channelz.proto b/node_modules/@grpc/grpc-js/proto/channelz.proto new file mode 100644 index 0000000..446e979 --- /dev/null +++ b/node_modules/@grpc/grpc-js/proto/channelz.proto @@ -0,0 +1,564 @@ +// Copyright 2018 The gRPC Authors +// +// 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. + +// This file defines an interface for exporting monitoring information +// out of gRPC servers. See the full design at +// https://github.com/grpc/proposal/blob/master/A14-channelz.md +// +// The canonical version of this proto can be found at +// https://github.com/grpc/grpc-proto/blob/master/grpc/channelz/v1/channelz.proto + +syntax = "proto3"; + +package grpc.channelz.v1; + +import "google/protobuf/any.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/timestamp.proto"; +import "google/protobuf/wrappers.proto"; + +option go_package = "google.golang.org/grpc/channelz/grpc_channelz_v1"; +option java_multiple_files = true; +option java_package = "io.grpc.channelz.v1"; +option java_outer_classname = "ChannelzProto"; + +// Channel is a logical grouping of channels, subchannels, and sockets. +message Channel { + // The identifier for this channel. This should bet set. + ChannelRef ref = 1; + // Data specific to this channel. + ChannelData data = 2; + // At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + + // There are no ordering guarantees on the order of channel refs. + // There may not be cycles in the ref graph. + // A channel ref may be present in more than one channel or subchannel. + repeated ChannelRef channel_ref = 3; + + // At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + // There are no ordering guarantees on the order of subchannel refs. + // There may not be cycles in the ref graph. + // A sub channel ref may be present in more than one channel or subchannel. + repeated SubchannelRef subchannel_ref = 4; + + // There are no ordering guarantees on the order of sockets. + repeated SocketRef socket_ref = 5; +} + +// Subchannel is a logical grouping of channels, subchannels, and sockets. +// A subchannel is load balanced over by it's ancestor +message Subchannel { + // The identifier for this channel. + SubchannelRef ref = 1; + // Data specific to this channel. + ChannelData data = 2; + // At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + + // There are no ordering guarantees on the order of channel refs. + // There may not be cycles in the ref graph. + // A channel ref may be present in more than one channel or subchannel. + repeated ChannelRef channel_ref = 3; + + // At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + // There are no ordering guarantees on the order of subchannel refs. + // There may not be cycles in the ref graph. + // A sub channel ref may be present in more than one channel or subchannel. + repeated SubchannelRef subchannel_ref = 4; + + // There are no ordering guarantees on the order of sockets. + repeated SocketRef socket_ref = 5; +} + +// These come from the specified states in this document: +// https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md +message ChannelConnectivityState { + enum State { + UNKNOWN = 0; + IDLE = 1; + CONNECTING = 2; + READY = 3; + TRANSIENT_FAILURE = 4; + SHUTDOWN = 5; + } + State state = 1; +} + +// Channel data is data related to a specific Channel or Subchannel. +message ChannelData { + // The connectivity state of the channel or subchannel. Implementations + // should always set this. + ChannelConnectivityState state = 1; + + // The target this channel originally tried to connect to. May be absent + string target = 2; + + // A trace of recent events on the channel. May be absent. + ChannelTrace trace = 3; + + // The number of calls started on the channel + int64 calls_started = 4; + // The number of calls that have completed with an OK status + int64 calls_succeeded = 5; + // The number of calls that have completed with a non-OK status + int64 calls_failed = 6; + + // The last time a call was started on the channel. + google.protobuf.Timestamp last_call_started_timestamp = 7; +} + +// A trace event is an interesting thing that happened to a channel or +// subchannel, such as creation, address resolution, subchannel creation, etc. +message ChannelTraceEvent { + // High level description of the event. + string description = 1; + // The supported severity levels of trace events. + enum Severity { + CT_UNKNOWN = 0; + CT_INFO = 1; + CT_WARNING = 2; + CT_ERROR = 3; + } + // the severity of the trace event + Severity severity = 2; + // When this event occurred. + google.protobuf.Timestamp timestamp = 3; + // ref of referenced channel or subchannel. + // Optional, only present if this event refers to a child object. For example, + // this field would be filled if this trace event was for a subchannel being + // created. + oneof child_ref { + ChannelRef channel_ref = 4; + SubchannelRef subchannel_ref = 5; + } +} + +// ChannelTrace represents the recent events that have occurred on the channel. +message ChannelTrace { + // Number of events ever logged in this tracing object. This can differ from + // events.size() because events can be overwritten or garbage collected by + // implementations. + int64 num_events_logged = 1; + // Time that this channel was created. + google.protobuf.Timestamp creation_timestamp = 2; + // List of events that have occurred on this channel. + repeated ChannelTraceEvent events = 3; +} + +// ChannelRef is a reference to a Channel. +message ChannelRef { + // The globally unique id for this channel. Must be a positive number. + int64 channel_id = 1; + // An optional name associated with the channel. + string name = 2; + // Intentionally don't use field numbers from other refs. + reserved 3, 4, 5, 6, 7, 8; +} + +// SubchannelRef is a reference to a Subchannel. +message SubchannelRef { + // The globally unique id for this subchannel. Must be a positive number. + int64 subchannel_id = 7; + // An optional name associated with the subchannel. + string name = 8; + // Intentionally don't use field numbers from other refs. + reserved 1, 2, 3, 4, 5, 6; +} + +// SocketRef is a reference to a Socket. +message SocketRef { + // The globally unique id for this socket. Must be a positive number. + int64 socket_id = 3; + // An optional name associated with the socket. + string name = 4; + // Intentionally don't use field numbers from other refs. + reserved 1, 2, 5, 6, 7, 8; +} + +// ServerRef is a reference to a Server. +message ServerRef { + // A globally unique identifier for this server. Must be a positive number. + int64 server_id = 5; + // An optional name associated with the server. + string name = 6; + // Intentionally don't use field numbers from other refs. + reserved 1, 2, 3, 4, 7, 8; +} + +// Server represents a single server. There may be multiple servers in a single +// program. +message Server { + // The identifier for a Server. This should be set. + ServerRef ref = 1; + // The associated data of the Server. + ServerData data = 2; + + // The sockets that the server is listening on. There are no ordering + // guarantees. This may be absent. + repeated SocketRef listen_socket = 3; +} + +// ServerData is data for a specific Server. +message ServerData { + // A trace of recent events on the server. May be absent. + ChannelTrace trace = 1; + + // The number of incoming calls started on the server + int64 calls_started = 2; + // The number of incoming calls that have completed with an OK status + int64 calls_succeeded = 3; + // The number of incoming calls that have a completed with a non-OK status + int64 calls_failed = 4; + + // The last time a call was started on the server. + google.protobuf.Timestamp last_call_started_timestamp = 5; +} + +// Information about an actual connection. Pronounced "sock-ay". +message Socket { + // The identifier for the Socket. + SocketRef ref = 1; + + // Data specific to this Socket. + SocketData data = 2; + // The locally bound address. + Address local = 3; + // The remote bound address. May be absent. + Address remote = 4; + // Security details for this socket. May be absent if not available, or + // there is no security on the socket. + Security security = 5; + + // Optional, represents the name of the remote endpoint, if different than + // the original target name. + string remote_name = 6; +} + +// SocketData is data associated for a specific Socket. The fields present +// are specific to the implementation, so there may be minor differences in +// the semantics. (e.g. flow control windows) +message SocketData { + // The number of streams that have been started. + int64 streams_started = 1; + // The number of streams that have ended successfully: + // On client side, received frame with eos bit set; + // On server side, sent frame with eos bit set. + int64 streams_succeeded = 2; + // The number of streams that have ended unsuccessfully: + // On client side, ended without receiving frame with eos bit set; + // On server side, ended without sending frame with eos bit set. + int64 streams_failed = 3; + // The number of grpc messages successfully sent on this socket. + int64 messages_sent = 4; + // The number of grpc messages received on this socket. + int64 messages_received = 5; + + // The number of keep alives sent. This is typically implemented with HTTP/2 + // ping messages. + int64 keep_alives_sent = 6; + + // The last time a stream was created by this endpoint. Usually unset for + // servers. + google.protobuf.Timestamp last_local_stream_created_timestamp = 7; + // The last time a stream was created by the remote endpoint. Usually unset + // for clients. + google.protobuf.Timestamp last_remote_stream_created_timestamp = 8; + + // The last time a message was sent by this endpoint. + google.protobuf.Timestamp last_message_sent_timestamp = 9; + // The last time a message was received by this endpoint. + google.protobuf.Timestamp last_message_received_timestamp = 10; + + // The amount of window, granted to the local endpoint by the remote endpoint. + // This may be slightly out of date due to network latency. This does NOT + // include stream level or TCP level flow control info. + google.protobuf.Int64Value local_flow_control_window = 11; + + // The amount of window, granted to the remote endpoint by the local endpoint. + // This may be slightly out of date due to network latency. This does NOT + // include stream level or TCP level flow control info. + google.protobuf.Int64Value remote_flow_control_window = 12; + + // Socket options set on this socket. May be absent if 'summary' is set + // on GetSocketRequest. + repeated SocketOption option = 13; +} + +// Address represents the address used to create the socket. +message Address { + message TcpIpAddress { + // Either the IPv4 or IPv6 address in bytes. Will be either 4 bytes or 16 + // bytes in length. + bytes ip_address = 1; + // 0-64k, or -1 if not appropriate. + int32 port = 2; + } + // A Unix Domain Socket address. + message UdsAddress { + string filename = 1; + } + // An address type not included above. + message OtherAddress { + // The human readable version of the value. This value should be set. + string name = 1; + // The actual address message. + google.protobuf.Any value = 2; + } + + oneof address { + TcpIpAddress tcpip_address = 1; + UdsAddress uds_address = 2; + OtherAddress other_address = 3; + } +} + +// Security represents details about how secure the socket is. +message Security { + message Tls { + oneof cipher_suite { + // The cipher suite name in the RFC 4346 format: + // https://tools.ietf.org/html/rfc4346#appendix-C + string standard_name = 1; + // Some other way to describe the cipher suite if + // the RFC 4346 name is not available. + string other_name = 2; + } + // the certificate used by this endpoint. + bytes local_certificate = 3; + // the certificate used by the remote endpoint. + bytes remote_certificate = 4; + } + message OtherSecurity { + // The human readable version of the value. + string name = 1; + // The actual security details message. + google.protobuf.Any value = 2; + } + oneof model { + Tls tls = 1; + OtherSecurity other = 2; + } +} + +// SocketOption represents socket options for a socket. Specifically, these +// are the options returned by getsockopt(). +message SocketOption { + // The full name of the socket option. Typically this will be the upper case + // name, such as "SO_REUSEPORT". + string name = 1; + // The human readable value of this socket option. At least one of value or + // additional will be set. + string value = 2; + // Additional data associated with the socket option. At least one of value + // or additional will be set. + google.protobuf.Any additional = 3; +} + +// For use with SocketOption's additional field. This is primarily used for +// SO_RCVTIMEO and SO_SNDTIMEO +message SocketOptionTimeout { + google.protobuf.Duration duration = 1; +} + +// For use with SocketOption's additional field. This is primarily used for +// SO_LINGER. +message SocketOptionLinger { + // active maps to `struct linger.l_onoff` + bool active = 1; + // duration maps to `struct linger.l_linger` + google.protobuf.Duration duration = 2; +} + +// For use with SocketOption's additional field. Tcp info for +// SOL_TCP and TCP_INFO. +message SocketOptionTcpInfo { + uint32 tcpi_state = 1; + + uint32 tcpi_ca_state = 2; + uint32 tcpi_retransmits = 3; + uint32 tcpi_probes = 4; + uint32 tcpi_backoff = 5; + uint32 tcpi_options = 6; + uint32 tcpi_snd_wscale = 7; + uint32 tcpi_rcv_wscale = 8; + + uint32 tcpi_rto = 9; + uint32 tcpi_ato = 10; + uint32 tcpi_snd_mss = 11; + uint32 tcpi_rcv_mss = 12; + + uint32 tcpi_unacked = 13; + uint32 tcpi_sacked = 14; + uint32 tcpi_lost = 15; + uint32 tcpi_retrans = 16; + uint32 tcpi_fackets = 17; + + uint32 tcpi_last_data_sent = 18; + uint32 tcpi_last_ack_sent = 19; + uint32 tcpi_last_data_recv = 20; + uint32 tcpi_last_ack_recv = 21; + + uint32 tcpi_pmtu = 22; + uint32 tcpi_rcv_ssthresh = 23; + uint32 tcpi_rtt = 24; + uint32 tcpi_rttvar = 25; + uint32 tcpi_snd_ssthresh = 26; + uint32 tcpi_snd_cwnd = 27; + uint32 tcpi_advmss = 28; + uint32 tcpi_reordering = 29; +} + +// Channelz is a service exposed by gRPC servers that provides detailed debug +// information. +service Channelz { + // Gets all root channels (i.e. channels the application has directly + // created). This does not include subchannels nor non-top level channels. + rpc GetTopChannels(GetTopChannelsRequest) returns (GetTopChannelsResponse); + // Gets all servers that exist in the process. + rpc GetServers(GetServersRequest) returns (GetServersResponse); + // Returns a single Server, or else a NOT_FOUND code. + rpc GetServer(GetServerRequest) returns (GetServerResponse); + // Gets all server sockets that exist in the process. + rpc GetServerSockets(GetServerSocketsRequest) returns (GetServerSocketsResponse); + // Returns a single Channel, or else a NOT_FOUND code. + rpc GetChannel(GetChannelRequest) returns (GetChannelResponse); + // Returns a single Subchannel, or else a NOT_FOUND code. + rpc GetSubchannel(GetSubchannelRequest) returns (GetSubchannelResponse); + // Returns a single Socket or else a NOT_FOUND code. + rpc GetSocket(GetSocketRequest) returns (GetSocketResponse); +} + +message GetTopChannelsRequest { + // start_channel_id indicates that only channels at or above this id should be + // included in the results. + // To request the first page, this should be set to 0. To request + // subsequent pages, the client generates this value by adding 1 to + // the highest seen result ID. + int64 start_channel_id = 1; + + // If non-zero, the server will return a page of results containing + // at most this many items. If zero, the server will choose a + // reasonable page size. Must never be negative. + int64 max_results = 2; +} + +message GetTopChannelsResponse { + // list of channels that the connection detail service knows about. Sorted in + // ascending channel_id order. + // Must contain at least 1 result, otherwise 'end' must be true. + repeated Channel channel = 1; + // If set, indicates that the list of channels is the final list. Requesting + // more channels can only return more if they are created after this RPC + // completes. + bool end = 2; +} + +message GetServersRequest { + // start_server_id indicates that only servers at or above this id should be + // included in the results. + // To request the first page, this must be set to 0. To request + // subsequent pages, the client generates this value by adding 1 to + // the highest seen result ID. + int64 start_server_id = 1; + + // If non-zero, the server will return a page of results containing + // at most this many items. If zero, the server will choose a + // reasonable page size. Must never be negative. + int64 max_results = 2; +} + +message GetServersResponse { + // list of servers that the connection detail service knows about. Sorted in + // ascending server_id order. + // Must contain at least 1 result, otherwise 'end' must be true. + repeated Server server = 1; + // If set, indicates that the list of servers is the final list. Requesting + // more servers will only return more if they are created after this RPC + // completes. + bool end = 2; +} + +message GetServerRequest { + // server_id is the identifier of the specific server to get. + int64 server_id = 1; +} + +message GetServerResponse { + // The Server that corresponds to the requested server_id. This field + // should be set. + Server server = 1; +} + +message GetServerSocketsRequest { + int64 server_id = 1; + // start_socket_id indicates that only sockets at or above this id should be + // included in the results. + // To request the first page, this must be set to 0. To request + // subsequent pages, the client generates this value by adding 1 to + // the highest seen result ID. + int64 start_socket_id = 2; + + // If non-zero, the server will return a page of results containing + // at most this many items. If zero, the server will choose a + // reasonable page size. Must never be negative. + int64 max_results = 3; +} + +message GetServerSocketsResponse { + // list of socket refs that the connection detail service knows about. Sorted in + // ascending socket_id order. + // Must contain at least 1 result, otherwise 'end' must be true. + repeated SocketRef socket_ref = 1; + // If set, indicates that the list of sockets is the final list. Requesting + // more sockets will only return more if they are created after this RPC + // completes. + bool end = 2; +} + +message GetChannelRequest { + // channel_id is the identifier of the specific channel to get. + int64 channel_id = 1; +} + +message GetChannelResponse { + // The Channel that corresponds to the requested channel_id. This field + // should be set. + Channel channel = 1; +} + +message GetSubchannelRequest { + // subchannel_id is the identifier of the specific subchannel to get. + int64 subchannel_id = 1; +} + +message GetSubchannelResponse { + // The Subchannel that corresponds to the requested subchannel_id. This + // field should be set. + Subchannel subchannel = 1; +} + +message GetSocketRequest { + // socket_id is the identifier of the specific socket to get. + int64 socket_id = 1; + + // If true, the response will contain only high level information + // that is inexpensive to obtain. Fields thay may be omitted are + // documented. + bool summary = 2; +} + +message GetSocketResponse { + // The Socket that corresponds to the requested socket_id. This field + // should be set. + Socket socket = 1; +} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/proto/protoc-gen-validate/LICENSE b/node_modules/@grpc/grpc-js/proto/protoc-gen-validate/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/@grpc/grpc-js/proto/protoc-gen-validate/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@grpc/grpc-js/proto/protoc-gen-validate/validate/validate.proto b/node_modules/@grpc/grpc-js/proto/protoc-gen-validate/validate/validate.proto new file mode 100644 index 0000000..7767f0a --- /dev/null +++ b/node_modules/@grpc/grpc-js/proto/protoc-gen-validate/validate/validate.proto @@ -0,0 +1,797 @@ +syntax = "proto2"; +package validate; + +option go_package = "github.com/envoyproxy/protoc-gen-validate/validate"; +option java_package = "io.envoyproxy.pgv.validate"; + +import "google/protobuf/descriptor.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/timestamp.proto"; + +// Validation rules applied at the message level +extend google.protobuf.MessageOptions { + // Disabled nullifies any validation rules for this message, including any + // message fields associated with it that do support validation. + optional bool disabled = 1071; +} + +// Validation rules applied at the oneof level +extend google.protobuf.OneofOptions { + // Required ensures that exactly one the field options in a oneof is set; + // validation fails if no fields in the oneof are set. + optional bool required = 1071; +} + +// Validation rules applied at the field level +extend google.protobuf.FieldOptions { + // Rules specify the validations to be performed on this field. By default, + // no validation is performed against a field. + optional FieldRules rules = 1071; +} + +// FieldRules encapsulates the rules for each type of field. Depending on the +// field, the correct set should be used to ensure proper validations. +message FieldRules { + optional MessageRules message = 17; + oneof type { + // Scalar Field Types + FloatRules float = 1; + DoubleRules double = 2; + Int32Rules int32 = 3; + Int64Rules int64 = 4; + UInt32Rules uint32 = 5; + UInt64Rules uint64 = 6; + SInt32Rules sint32 = 7; + SInt64Rules sint64 = 8; + Fixed32Rules fixed32 = 9; + Fixed64Rules fixed64 = 10; + SFixed32Rules sfixed32 = 11; + SFixed64Rules sfixed64 = 12; + BoolRules bool = 13; + StringRules string = 14; + BytesRules bytes = 15; + + // Complex Field Types + EnumRules enum = 16; + RepeatedRules repeated = 18; + MapRules map = 19; + + // Well-Known Field Types + AnyRules any = 20; + DurationRules duration = 21; + TimestampRules timestamp = 22; + } +} + +// FloatRules describes the constraints applied to `float` values +message FloatRules { + // Const specifies that this field must be exactly the specified value + optional float const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional float lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional float lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional float gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional float gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated float in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated float not_in = 7; +} + +// DoubleRules describes the constraints applied to `double` values +message DoubleRules { + // Const specifies that this field must be exactly the specified value + optional double const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional double lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional double lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional double gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional double gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated double in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated double not_in = 7; +} + +// Int32Rules describes the constraints applied to `int32` values +message Int32Rules { + // Const specifies that this field must be exactly the specified value + optional int32 const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional int32 lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional int32 lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional int32 gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional int32 gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated int32 in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated int32 not_in = 7; +} + +// Int64Rules describes the constraints applied to `int64` values +message Int64Rules { + // Const specifies that this field must be exactly the specified value + optional int64 const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional int64 lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional int64 lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional int64 gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional int64 gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated int64 in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated int64 not_in = 7; +} + +// UInt32Rules describes the constraints applied to `uint32` values +message UInt32Rules { + // Const specifies that this field must be exactly the specified value + optional uint32 const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional uint32 lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional uint32 lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional uint32 gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional uint32 gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated uint32 in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated uint32 not_in = 7; +} + +// UInt64Rules describes the constraints applied to `uint64` values +message UInt64Rules { + // Const specifies that this field must be exactly the specified value + optional uint64 const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional uint64 lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional uint64 lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional uint64 gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional uint64 gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated uint64 in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated uint64 not_in = 7; +} + +// SInt32Rules describes the constraints applied to `sint32` values +message SInt32Rules { + // Const specifies that this field must be exactly the specified value + optional sint32 const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional sint32 lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional sint32 lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional sint32 gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional sint32 gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated sint32 in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated sint32 not_in = 7; +} + +// SInt64Rules describes the constraints applied to `sint64` values +message SInt64Rules { + // Const specifies that this field must be exactly the specified value + optional sint64 const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional sint64 lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional sint64 lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional sint64 gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional sint64 gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated sint64 in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated sint64 not_in = 7; +} + +// Fixed32Rules describes the constraints applied to `fixed32` values +message Fixed32Rules { + // Const specifies that this field must be exactly the specified value + optional fixed32 const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional fixed32 lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional fixed32 lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional fixed32 gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional fixed32 gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated fixed32 in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated fixed32 not_in = 7; +} + +// Fixed64Rules describes the constraints applied to `fixed64` values +message Fixed64Rules { + // Const specifies that this field must be exactly the specified value + optional fixed64 const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional fixed64 lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional fixed64 lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional fixed64 gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional fixed64 gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated fixed64 in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated fixed64 not_in = 7; +} + +// SFixed32Rules describes the constraints applied to `sfixed32` values +message SFixed32Rules { + // Const specifies that this field must be exactly the specified value + optional sfixed32 const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional sfixed32 lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional sfixed32 lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional sfixed32 gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional sfixed32 gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated sfixed32 in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated sfixed32 not_in = 7; +} + +// SFixed64Rules describes the constraints applied to `sfixed64` values +message SFixed64Rules { + // Const specifies that this field must be exactly the specified value + optional sfixed64 const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional sfixed64 lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional sfixed64 lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional sfixed64 gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional sfixed64 gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated sfixed64 in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated sfixed64 not_in = 7; +} + +// BoolRules describes the constraints applied to `bool` values +message BoolRules { + // Const specifies that this field must be exactly the specified value + optional bool const = 1; +} + +// StringRules describe the constraints applied to `string` values +message StringRules { + // Const specifies that this field must be exactly the specified value + optional string const = 1; + + // Len specifies that this field must be the specified number of + // characters (Unicode code points). Note that the number of + // characters may differ from the number of bytes in the string. + optional uint64 len = 19; + + // MinLen specifies that this field must be the specified number of + // characters (Unicode code points) at a minimum. Note that the number of + // characters may differ from the number of bytes in the string. + optional uint64 min_len = 2; + + // MaxLen specifies that this field must be the specified number of + // characters (Unicode code points) at a maximum. Note that the number of + // characters may differ from the number of bytes in the string. + optional uint64 max_len = 3; + + // LenBytes specifies that this field must be the specified number of bytes + // at a minimum + optional uint64 len_bytes = 20; + + // MinBytes specifies that this field must be the specified number of bytes + // at a minimum + optional uint64 min_bytes = 4; + + // MaxBytes specifies that this field must be the specified number of bytes + // at a maximum + optional uint64 max_bytes = 5; + + // Pattern specifes that this field must match against the specified + // regular expression (RE2 syntax). The included expression should elide + // any delimiters. + optional string pattern = 6; + + // Prefix specifies that this field must have the specified substring at + // the beginning of the string. + optional string prefix = 7; + + // Suffix specifies that this field must have the specified substring at + // the end of the string. + optional string suffix = 8; + + // Contains specifies that this field must have the specified substring + // anywhere in the string. + optional string contains = 9; + + // NotContains specifies that this field cannot have the specified substring + // anywhere in the string. + optional string not_contains = 23; + + // In specifies that this field must be equal to one of the specified + // values + repeated string in = 10; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated string not_in = 11; + + // WellKnown rules provide advanced constraints against common string + // patterns + oneof well_known { + // Email specifies that the field must be a valid email address as + // defined by RFC 5322 + bool email = 12; + + // Hostname specifies that the field must be a valid hostname as + // defined by RFC 1034. This constraint does not support + // internationalized domain names (IDNs). + bool hostname = 13; + + // Ip specifies that the field must be a valid IP (v4 or v6) address. + // Valid IPv6 addresses should not include surrounding square brackets. + bool ip = 14; + + // Ipv4 specifies that the field must be a valid IPv4 address. + bool ipv4 = 15; + + // Ipv6 specifies that the field must be a valid IPv6 address. Valid + // IPv6 addresses should not include surrounding square brackets. + bool ipv6 = 16; + + // Uri specifies that the field must be a valid, absolute URI as defined + // by RFC 3986 + bool uri = 17; + + // UriRef specifies that the field must be a valid URI as defined by RFC + // 3986 and may be relative or absolute. + bool uri_ref = 18; + + // Address specifies that the field must be either a valid hostname as + // defined by RFC 1034 (which does not support internationalized domain + // names or IDNs), or it can be a valid IP (v4 or v6). + bool address = 21; + + // Uuid specifies that the field must be a valid UUID as defined by + // RFC 4122 + bool uuid = 22; + + // WellKnownRegex specifies a common well known pattern defined as a regex. + KnownRegex well_known_regex = 24; + } + + // This applies to regexes HTTP_HEADER_NAME and HTTP_HEADER_VALUE to enable + // strict header validation. + // By default, this is true, and HTTP header validations are RFC-compliant. + // Setting to false will enable a looser validations that only disallows + // \r\n\0 characters, which can be used to bypass header matching rules. + optional bool strict = 25 [default = true]; +} + +// WellKnownRegex contain some well-known patterns. +enum KnownRegex { + UNKNOWN = 0; + + // HTTP header name as defined by RFC 7230. + HTTP_HEADER_NAME = 1; + + // HTTP header value as defined by RFC 7230. + HTTP_HEADER_VALUE = 2; +} + +// BytesRules describe the constraints applied to `bytes` values +message BytesRules { + // Const specifies that this field must be exactly the specified value + optional bytes const = 1; + + // Len specifies that this field must be the specified number of bytes + optional uint64 len = 13; + + // MinLen specifies that this field must be the specified number of bytes + // at a minimum + optional uint64 min_len = 2; + + // MaxLen specifies that this field must be the specified number of bytes + // at a maximum + optional uint64 max_len = 3; + + // Pattern specifes that this field must match against the specified + // regular expression (RE2 syntax). The included expression should elide + // any delimiters. + optional string pattern = 4; + + // Prefix specifies that this field must have the specified bytes at the + // beginning of the string. + optional bytes prefix = 5; + + // Suffix specifies that this field must have the specified bytes at the + // end of the string. + optional bytes suffix = 6; + + // Contains specifies that this field must have the specified bytes + // anywhere in the string. + optional bytes contains = 7; + + // In specifies that this field must be equal to one of the specified + // values + repeated bytes in = 8; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated bytes not_in = 9; + + // WellKnown rules provide advanced constraints against common byte + // patterns + oneof well_known { + // Ip specifies that the field must be a valid IP (v4 or v6) address in + // byte format + bool ip = 10; + + // Ipv4 specifies that the field must be a valid IPv4 address in byte + // format + bool ipv4 = 11; + + // Ipv6 specifies that the field must be a valid IPv6 address in byte + // format + bool ipv6 = 12; + } +} + +// EnumRules describe the constraints applied to enum values +message EnumRules { + // Const specifies that this field must be exactly the specified value + optional int32 const = 1; + + // DefinedOnly specifies that this field must be only one of the defined + // values for this enum, failing on any undefined value. + optional bool defined_only = 2; + + // In specifies that this field must be equal to one of the specified + // values + repeated int32 in = 3; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated int32 not_in = 4; +} + +// MessageRules describe the constraints applied to embedded message values. +// For message-type fields, validation is performed recursively. +message MessageRules { + // Skip specifies that the validation rules of this field should not be + // evaluated + optional bool skip = 1; + + // Required specifies that this field must be set + optional bool required = 2; +} + +// RepeatedRules describe the constraints applied to `repeated` values +message RepeatedRules { + // MinItems specifies that this field must have the specified number of + // items at a minimum + optional uint64 min_items = 1; + + // MaxItems specifies that this field must have the specified number of + // items at a maximum + optional uint64 max_items = 2; + + // Unique specifies that all elements in this field must be unique. This + // contraint is only applicable to scalar and enum types (messages are not + // supported). + optional bool unique = 3; + + // Items specifies the contraints to be applied to each item in the field. + // Repeated message fields will still execute validation against each item + // unless skip is specified here. + optional FieldRules items = 4; +} + +// MapRules describe the constraints applied to `map` values +message MapRules { + // MinPairs specifies that this field must have the specified number of + // KVs at a minimum + optional uint64 min_pairs = 1; + + // MaxPairs specifies that this field must have the specified number of + // KVs at a maximum + optional uint64 max_pairs = 2; + + // NoSparse specifies values in this field cannot be unset. This only + // applies to map's with message value types. + optional bool no_sparse = 3; + + // Keys specifies the constraints to be applied to each key in the field. + optional FieldRules keys = 4; + + // Values specifies the constraints to be applied to the value of each key + // in the field. Message values will still have their validations evaluated + // unless skip is specified here. + optional FieldRules values = 5; +} + +// AnyRules describe constraints applied exclusively to the +// `google.protobuf.Any` well-known type +message AnyRules { + // Required specifies that this field must be set + optional bool required = 1; + + // In specifies that this field's `type_url` must be equal to one of the + // specified values. + repeated string in = 2; + + // NotIn specifies that this field's `type_url` must not be equal to any of + // the specified values. + repeated string not_in = 3; +} + +// DurationRules describe the constraints applied exclusively to the +// `google.protobuf.Duration` well-known type +message DurationRules { + // Required specifies that this field must be set + optional bool required = 1; + + // Const specifies that this field must be exactly the specified value + optional google.protobuf.Duration const = 2; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional google.protobuf.Duration lt = 3; + + // Lt specifies that this field must be less than the specified value, + // inclusive + optional google.protobuf.Duration lte = 4; + + // Gt specifies that this field must be greater than the specified value, + // exclusive + optional google.protobuf.Duration gt = 5; + + // Gte specifies that this field must be greater than the specified value, + // inclusive + optional google.protobuf.Duration gte = 6; + + // In specifies that this field must be equal to one of the specified + // values + repeated google.protobuf.Duration in = 7; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated google.protobuf.Duration not_in = 8; +} + +// TimestampRules describe the constraints applied exclusively to the +// `google.protobuf.Timestamp` well-known type +message TimestampRules { + // Required specifies that this field must be set + optional bool required = 1; + + // Const specifies that this field must be exactly the specified value + optional google.protobuf.Timestamp const = 2; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional google.protobuf.Timestamp lt = 3; + + // Lte specifies that this field must be less than the specified value, + // inclusive + optional google.protobuf.Timestamp lte = 4; + + // Gt specifies that this field must be greater than the specified value, + // exclusive + optional google.protobuf.Timestamp gt = 5; + + // Gte specifies that this field must be greater than the specified value, + // inclusive + optional google.protobuf.Timestamp gte = 6; + + // LtNow specifies that this must be less than the current time. LtNow + // can only be used with the Within rule. + optional bool lt_now = 7; + + // GtNow specifies that this must be greater than the current time. GtNow + // can only be used with the Within rule. + optional bool gt_now = 8; + + // Within specifies that this field must be within this duration of the + // current time. This constraint can be used alone or with the LtNow and + // GtNow rules. + optional google.protobuf.Duration within = 9; +} diff --git a/node_modules/@grpc/grpc-js/proto/xds/LICENSE b/node_modules/@grpc/grpc-js/proto/xds/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/proto/xds/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@grpc/grpc-js/proto/xds/xds/data/orca/v3/orca_load_report.proto b/node_modules/@grpc/grpc-js/proto/xds/xds/data/orca/v3/orca_load_report.proto new file mode 100644 index 0000000..53da75f --- /dev/null +++ b/node_modules/@grpc/grpc-js/proto/xds/xds/data/orca/v3/orca_load_report.proto @@ -0,0 +1,58 @@ +syntax = "proto3"; + +package xds.data.orca.v3; + +option java_outer_classname = "OrcaLoadReportProto"; +option java_multiple_files = true; +option java_package = "com.github.xds.data.orca.v3"; +option go_package = "github.com/cncf/xds/go/xds/data/orca/v3"; + +import "validate/validate.proto"; + +// See section `ORCA load report format` of the design document in +// :ref:`https://github.com/envoyproxy/envoy/issues/6614`. + +message OrcaLoadReport { + // CPU utilization expressed as a fraction of available CPU resources. This + // should be derived from the latest sample or measurement. The value may be + // larger than 1.0 when the usage exceeds the reporter dependent notion of + // soft limits. + double cpu_utilization = 1 [(validate.rules).double.gte = 0]; + + // Memory utilization expressed as a fraction of available memory + // resources. This should be derived from the latest sample or measurement. + double mem_utilization = 2 [(validate.rules).double.gte = 0, (validate.rules).double.lte = 1]; + + // Total RPS being served by an endpoint. This should cover all services that an endpoint is + // responsible for. + // Deprecated -- use ``rps_fractional`` field instead. + uint64 rps = 3 [deprecated = true]; + + // Application specific requests costs. Each value is an absolute cost (e.g. 3487 bytes of + // storage) associated with the request. + map request_cost = 4; + + // Resource utilization values. Each value is expressed as a fraction of total resources + // available, derived from the latest sample or measurement. + map utilization = 5 + [(validate.rules).map.values.double.gte = 0, (validate.rules).map.values.double.lte = 1]; + + // Total RPS being served by an endpoint. This should cover all services that an endpoint is + // responsible for. + double rps_fractional = 6 [(validate.rules).double.gte = 0]; + + // Total EPS (errors/second) being served by an endpoint. This should cover + // all services that an endpoint is responsible for. + double eps = 7 [(validate.rules).double.gte = 0]; + + // Application specific opaque metrics. + map named_metrics = 8; + + // Application specific utilization expressed as a fraction of available + // resources. For example, an application may report the max of CPU and memory + // utilization for better load balancing if it is both CPU and memory bound. + // This should be derived from the latest sample or measurement. + // The value may be larger than 1.0 when the usage exceeds the reporter + // dependent notion of soft limits. + double application_utilization = 9 [(validate.rules).double.gte = 0]; +} diff --git a/node_modules/@grpc/grpc-js/proto/xds/xds/service/orca/v3/orca.proto b/node_modules/@grpc/grpc-js/proto/xds/xds/service/orca/v3/orca.proto new file mode 100644 index 0000000..03126cd --- /dev/null +++ b/node_modules/@grpc/grpc-js/proto/xds/xds/service/orca/v3/orca.proto @@ -0,0 +1,36 @@ +syntax = "proto3"; + +package xds.service.orca.v3; + +option java_outer_classname = "OrcaProto"; +option java_multiple_files = true; +option java_package = "com.github.xds.service.orca.v3"; +option go_package = "github.com/cncf/xds/go/xds/service/orca/v3"; + +import "xds/data/orca/v3/orca_load_report.proto"; + +import "google/protobuf/duration.proto"; + +// See section `Out-of-band (OOB) reporting` of the design document in +// :ref:`https://github.com/envoyproxy/envoy/issues/6614`. + +// Out-of-band (OOB) load reporting service for the additional load reporting +// agent that does not sit in the request path. Reports are periodically sampled +// with sufficient frequency to provide temporal association with requests. +// OOB reporting compensates the limitation of in-band reporting in revealing +// costs for backends that do not provide a steady stream of telemetry such as +// long running stream operations and zero QPS services. This is a server +// streaming service, client needs to terminate current RPC and initiate +// a new call to change backend reporting frequency. +service OpenRcaService { + rpc StreamCoreMetrics(OrcaLoadReportRequest) returns (stream xds.data.orca.v3.OrcaLoadReport); +} + +message OrcaLoadReportRequest { + // Interval for generating Open RCA core metric responses. + google.protobuf.Duration report_interval = 1; + // Request costs to collect. If this is empty, all known requests costs tracked by + // the load reporting agent will be returned. This provides an opportunity for + // the client to selectively obtain a subset of tracked costs. + repeated string request_cost_names = 2; +} diff --git a/node_modules/@grpc/grpc-js/src/admin.ts b/node_modules/@grpc/grpc-js/src/admin.ts new file mode 100644 index 0000000..4d26b89 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/admin.ts @@ -0,0 +1,45 @@ +/* + * Copyright 2021 gRPC authors. + * + * 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. + * + */ + +import { ServiceDefinition } from './make-client'; +import { Server, UntypedServiceImplementation } from './server'; + +interface GetServiceDefinition { + (): ServiceDefinition; +} + +interface GetHandlers { + (): UntypedServiceImplementation; +} + +const registeredAdminServices: { + getServiceDefinition: GetServiceDefinition; + getHandlers: GetHandlers; +}[] = []; + +export function registerAdminService( + getServiceDefinition: GetServiceDefinition, + getHandlers: GetHandlers +) { + registeredAdminServices.push({ getServiceDefinition, getHandlers }); +} + +export function addAdminServicesToServer(server: Server): void { + for (const { getServiceDefinition, getHandlers } of registeredAdminServices) { + server.addService(getServiceDefinition(), getHandlers()); + } +} diff --git a/node_modules/@grpc/grpc-js/src/auth-context.ts b/node_modules/@grpc/grpc-js/src/auth-context.ts new file mode 100644 index 0000000..4fc110d --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/auth-context.ts @@ -0,0 +1,23 @@ +/* + * Copyright 2025 gRPC authors. + * + * 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. + * + */ + +import { PeerCertificate } from "tls"; + +export interface AuthContext { + transportSecurityType?: string; + sslPeerCertificate?: PeerCertificate; +} diff --git a/node_modules/@grpc/grpc-js/src/backoff-timeout.ts b/node_modules/@grpc/grpc-js/src/backoff-timeout.ts new file mode 100644 index 0000000..8be560d --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/backoff-timeout.ts @@ -0,0 +1,222 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { LogVerbosity } from './constants'; +import * as logging from './logging'; + +const TRACER_NAME = 'backoff'; + +const INITIAL_BACKOFF_MS = 1000; +const BACKOFF_MULTIPLIER = 1.6; +const MAX_BACKOFF_MS = 120000; +const BACKOFF_JITTER = 0.2; + +/** + * Get a number uniformly at random in the range [min, max) + * @param min + * @param max + */ +function uniformRandom(min: number, max: number) { + return Math.random() * (max - min) + min; +} + +export interface BackoffOptions { + initialDelay?: number; + multiplier?: number; + jitter?: number; + maxDelay?: number; +} + +export class BackoffTimeout { + /** + * The delay time at the start, and after each reset. + */ + private readonly initialDelay: number = INITIAL_BACKOFF_MS; + /** + * The exponential backoff multiplier. + */ + private readonly multiplier: number = BACKOFF_MULTIPLIER; + /** + * The maximum delay time + */ + private readonly maxDelay: number = MAX_BACKOFF_MS; + /** + * The maximum fraction by which the delay time can randomly vary after + * applying the multiplier. + */ + private readonly jitter: number = BACKOFF_JITTER; + /** + * The delay time for the next time the timer runs. + */ + private nextDelay: number; + /** + * The handle of the underlying timer. If running is false, this value refers + * to an object representing a timer that has ended, but it can still be + * interacted with without error. + */ + private timerId: NodeJS.Timeout; + /** + * Indicates whether the timer is currently running. + */ + private running = false; + /** + * Indicates whether the timer should keep the Node process running if no + * other async operation is doing so. + */ + private hasRef = true; + /** + * The time that the currently running timer was started. Only valid if + * running is true. + */ + private startTime: Date = new Date(); + /** + * The approximate time that the currently running timer will end. Only valid + * if running is true. + */ + private endTime: Date = new Date(); + + private id: number; + + private static nextId = 0; + + constructor(private callback: () => void, options?: BackoffOptions) { + this.id = BackoffTimeout.getNextId(); + if (options) { + if (options.initialDelay) { + this.initialDelay = options.initialDelay; + } + if (options.multiplier) { + this.multiplier = options.multiplier; + } + if (options.jitter) { + this.jitter = options.jitter; + } + if (options.maxDelay) { + this.maxDelay = options.maxDelay; + } + } + this.trace('constructed initialDelay=' + this.initialDelay + ' multiplier=' + this.multiplier + ' jitter=' + this.jitter + ' maxDelay=' + this.maxDelay); + this.nextDelay = this.initialDelay; + this.timerId = setTimeout(() => {}, 0); + clearTimeout(this.timerId); + } + + private static getNextId() { + return this.nextId++; + } + + private trace(text: string) { + logging.trace(LogVerbosity.DEBUG, TRACER_NAME, '{' + this.id + '} ' + text); + } + + private runTimer(delay: number) { + this.trace('runTimer(delay=' + delay + ')'); + this.endTime = this.startTime; + this.endTime.setMilliseconds( + this.endTime.getMilliseconds() + delay + ); + clearTimeout(this.timerId); + this.timerId = setTimeout(() => { + this.trace('timer fired'); + this.running = false; + this.callback(); + }, delay); + if (!this.hasRef) { + this.timerId.unref?.(); + } + } + + /** + * Call the callback after the current amount of delay time + */ + runOnce() { + this.trace('runOnce()'); + this.running = true; + this.startTime = new Date(); + this.runTimer(this.nextDelay); + const nextBackoff = Math.min( + this.nextDelay * this.multiplier, + this.maxDelay + ); + const jitterMagnitude = nextBackoff * this.jitter; + this.nextDelay = + nextBackoff + uniformRandom(-jitterMagnitude, jitterMagnitude); + } + + /** + * Stop the timer. The callback will not be called until `runOnce` is called + * again. + */ + stop() { + this.trace('stop()'); + clearTimeout(this.timerId); + this.running = false; + } + + /** + * Reset the delay time to its initial value. If the timer is still running, + * retroactively apply that reset to the current timer. + */ + reset() { + this.trace('reset() running=' + this.running); + this.nextDelay = this.initialDelay; + if (this.running) { + const now = new Date(); + const newEndTime = this.startTime; + newEndTime.setMilliseconds(newEndTime.getMilliseconds() + this.nextDelay); + clearTimeout(this.timerId); + if (now < newEndTime) { + this.runTimer(newEndTime.getTime() - now.getTime()); + } else { + this.running = false; + } + } + } + + /** + * Check whether the timer is currently running. + */ + isRunning() { + return this.running; + } + + /** + * Set that while the timer is running, it should keep the Node process + * running. + */ + ref() { + this.hasRef = true; + this.timerId.ref?.(); + } + + /** + * Set that while the timer is running, it should not keep the Node process + * running. + */ + unref() { + this.hasRef = false; + this.timerId.unref?.(); + } + + /** + * Get the approximate timestamp of when the timer will fire. Only valid if + * this.isRunning() is true. + */ + getEndTime() { + return this.endTime; + } +} diff --git a/node_modules/@grpc/grpc-js/src/call-credentials.ts b/node_modules/@grpc/grpc-js/src/call-credentials.ts new file mode 100644 index 0000000..a9afe4a --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/call-credentials.ts @@ -0,0 +1,227 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { Metadata } from './metadata'; + +export interface CallMetadataOptions { + method_name: string; + service_url: string; +} + +export type CallMetadataGenerator = ( + options: CallMetadataOptions, + cb: (err: Error | null, metadata?: Metadata) => void +) => void; + +// google-auth-library pre-v2.0.0 does not have getRequestHeaders +// but has getRequestMetadata, which is deprecated in v2.0.0 +export interface OldOAuth2Client { + getRequestMetadata: ( + url: string, + callback: ( + err: Error | null, + headers?: { + [index: string]: string; + } + ) => void + ) => void; +} + +export interface CurrentOAuth2Client { + getRequestHeaders: (url?: string) => Promise<{ [index: string]: string }>; +} + +export type OAuth2Client = OldOAuth2Client | CurrentOAuth2Client; + +function isCurrentOauth2Client( + client: OAuth2Client +): client is CurrentOAuth2Client { + return ( + 'getRequestHeaders' in client && + typeof client.getRequestHeaders === 'function' + ); +} + +/** + * A class that represents a generic method of adding authentication-related + * metadata on a per-request basis. + */ +export abstract class CallCredentials { + /** + * Asynchronously generates a new Metadata object. + * @param options Options used in generating the Metadata object. + */ + abstract generateMetadata(options: CallMetadataOptions): Promise; + /** + * Creates a new CallCredentials object from properties of both this and + * another CallCredentials object. This object's metadata generator will be + * called first. + * @param callCredentials The other CallCredentials object. + */ + abstract compose(callCredentials: CallCredentials): CallCredentials; + + /** + * Check whether two call credentials objects are equal. Separate + * SingleCallCredentials with identical metadata generator functions are + * equal. + * @param other The other CallCredentials object to compare with. + */ + abstract _equals(other: CallCredentials): boolean; + + /** + * Creates a new CallCredentials object from a given function that generates + * Metadata objects. + * @param metadataGenerator A function that accepts a set of options, and + * generates a Metadata object based on these options, which is passed back + * to the caller via a supplied (err, metadata) callback. + */ + static createFromMetadataGenerator( + metadataGenerator: CallMetadataGenerator + ): CallCredentials { + return new SingleCallCredentials(metadataGenerator); + } + + /** + * Create a gRPC credential from a Google credential object. + * @param googleCredentials The authentication client to use. + * @return The resulting CallCredentials object. + */ + static createFromGoogleCredential( + googleCredentials: OAuth2Client + ): CallCredentials { + return CallCredentials.createFromMetadataGenerator((options, callback) => { + let getHeaders: Promise<{ [index: string]: string }>; + if (isCurrentOauth2Client(googleCredentials)) { + getHeaders = googleCredentials.getRequestHeaders(options.service_url); + } else { + getHeaders = new Promise((resolve, reject) => { + googleCredentials.getRequestMetadata( + options.service_url, + (err, headers) => { + if (err) { + reject(err); + return; + } + if (!headers) { + reject(new Error('Headers not set by metadata plugin')); + return; + } + resolve(headers); + } + ); + }); + } + getHeaders.then( + headers => { + const metadata = new Metadata(); + for (const key of Object.keys(headers)) { + metadata.add(key, headers[key]); + } + callback(null, metadata); + }, + err => { + callback(err); + } + ); + }); + } + + static createEmpty(): CallCredentials { + return new EmptyCallCredentials(); + } +} + +class ComposedCallCredentials extends CallCredentials { + constructor(private creds: CallCredentials[]) { + super(); + } + + async generateMetadata(options: CallMetadataOptions): Promise { + const base: Metadata = new Metadata(); + const generated: Metadata[] = await Promise.all( + this.creds.map(cred => cred.generateMetadata(options)) + ); + for (const gen of generated) { + base.merge(gen); + } + return base; + } + + compose(other: CallCredentials): CallCredentials { + return new ComposedCallCredentials(this.creds.concat([other])); + } + + _equals(other: CallCredentials): boolean { + if (this === other) { + return true; + } + if (other instanceof ComposedCallCredentials) { + return this.creds.every((value, index) => + value._equals(other.creds[index]) + ); + } else { + return false; + } + } +} + +class SingleCallCredentials extends CallCredentials { + constructor(private metadataGenerator: CallMetadataGenerator) { + super(); + } + + generateMetadata(options: CallMetadataOptions): Promise { + return new Promise((resolve, reject) => { + this.metadataGenerator(options, (err, metadata) => { + if (metadata !== undefined) { + resolve(metadata); + } else { + reject(err); + } + }); + }); + } + + compose(other: CallCredentials): CallCredentials { + return new ComposedCallCredentials([this, other]); + } + + _equals(other: CallCredentials): boolean { + if (this === other) { + return true; + } + if (other instanceof SingleCallCredentials) { + return this.metadataGenerator === other.metadataGenerator; + } else { + return false; + } + } +} + +class EmptyCallCredentials extends CallCredentials { + generateMetadata(options: CallMetadataOptions): Promise { + return Promise.resolve(new Metadata()); + } + + compose(other: CallCredentials): CallCredentials { + return other; + } + + _equals(other: CallCredentials): boolean { + return other instanceof EmptyCallCredentials; + } +} diff --git a/node_modules/@grpc/grpc-js/src/call-interface.ts b/node_modules/@grpc/grpc-js/src/call-interface.ts new file mode 100644 index 0000000..637228c --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/call-interface.ts @@ -0,0 +1,208 @@ +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ + +import { AuthContext } from './auth-context'; +import { CallCredentials } from './call-credentials'; +import { Status } from './constants'; +import { Deadline } from './deadline'; +import { Metadata } from './metadata'; +import { ServerSurfaceCall } from './server-call'; + +export interface CallStreamOptions { + deadline: Deadline; + flags: number; + host: string; + parentCall: ServerSurfaceCall | null; +} + +export type PartialCallStreamOptions = Partial; + +export interface StatusObject { + code: Status; + details: string; + metadata: Metadata; +} + +export type PartialStatusObject = Pick & { + metadata?: Metadata | null | undefined; +}; + +export interface StatusOrOk { + ok: true; + value: T; +} + +export interface StatusOrError { + ok: false; + error: StatusObject; +} + +export type StatusOr = StatusOrOk | StatusOrError; + +export function statusOrFromValue(value: T): StatusOr { + return { + ok: true, + value: value + }; +} + +export function statusOrFromError(error: PartialStatusObject): StatusOr { + return { + ok: false, + error: { + ...error, + metadata: error.metadata ?? new Metadata() + } + }; +} + +export const enum WriteFlags { + BufferHint = 1, + NoCompress = 2, + WriteThrough = 4, +} + +export interface WriteObject { + message: Buffer; + flags?: number; +} + +export interface MetadataListener { + (metadata: Metadata, next: (metadata: Metadata) => void): void; +} + +export interface MessageListener { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (message: any, next: (message: any) => void): void; +} + +export interface StatusListener { + (status: StatusObject, next: (status: StatusObject) => void): void; +} + +export interface FullListener { + onReceiveMetadata: MetadataListener; + onReceiveMessage: MessageListener; + onReceiveStatus: StatusListener; +} + +export type Listener = Partial; + +/** + * An object with methods for handling the responses to a call. + */ +export interface InterceptingListener { + onReceiveMetadata(metadata: Metadata): void; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message: any): void; + onReceiveStatus(status: StatusObject): void; +} + +export function isInterceptingListener( + listener: Listener | InterceptingListener +): listener is InterceptingListener { + return ( + listener.onReceiveMetadata !== undefined && + listener.onReceiveMetadata.length === 1 + ); +} + +export class InterceptingListenerImpl implements InterceptingListener { + private processingMetadata = false; + private hasPendingMessage = false; + private pendingMessage: any; + private processingMessage = false; + private pendingStatus: StatusObject | null = null; + constructor( + private listener: FullListener, + private nextListener: InterceptingListener + ) {} + + private processPendingMessage() { + if (this.hasPendingMessage) { + this.nextListener.onReceiveMessage(this.pendingMessage); + this.pendingMessage = null; + this.hasPendingMessage = false; + } + } + + private processPendingStatus() { + if (this.pendingStatus) { + this.nextListener.onReceiveStatus(this.pendingStatus); + } + } + + onReceiveMetadata(metadata: Metadata): void { + this.processingMetadata = true; + this.listener.onReceiveMetadata(metadata, metadata => { + this.processingMetadata = false; + this.nextListener.onReceiveMetadata(metadata); + this.processPendingMessage(); + this.processPendingStatus(); + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message: any): void { + /* If this listener processes messages asynchronously, the last message may + * be reordered with respect to the status */ + this.processingMessage = true; + this.listener.onReceiveMessage(message, msg => { + this.processingMessage = false; + if (this.processingMetadata) { + this.pendingMessage = msg; + this.hasPendingMessage = true; + } else { + this.nextListener.onReceiveMessage(msg); + this.processPendingStatus(); + } + }); + } + onReceiveStatus(status: StatusObject): void { + this.listener.onReceiveStatus(status, processedStatus => { + if (this.processingMetadata || this.processingMessage) { + this.pendingStatus = processedStatus; + } else { + this.nextListener.onReceiveStatus(processedStatus); + } + }); + } +} + +export interface WriteCallback { + (error?: Error | null): void; +} + +export interface MessageContext { + callback?: WriteCallback; + flags?: number; +} + +export interface Call { + cancelWithStatus(status: Status, details: string): void; + getPeer(): string; + start(metadata: Metadata, listener: InterceptingListener): void; + sendMessageWithContext(context: MessageContext, message: Buffer): void; + startRead(): void; + halfClose(): void; + getCallNumber(): number; + setCredentials(credentials: CallCredentials): void; + getAuthContext(): AuthContext | null; +} + +export interface DeadlineInfoProvider { + getDeadlineInfo(): string[]; +} diff --git a/node_modules/@grpc/grpc-js/src/call-number.ts b/node_modules/@grpc/grpc-js/src/call-number.ts new file mode 100644 index 0000000..8c37d3f --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/call-number.ts @@ -0,0 +1,22 @@ +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ + +let nextCallNumber = 0; + +export function getNextCallNumber() { + return nextCallNumber++; +} diff --git a/node_modules/@grpc/grpc-js/src/call.ts b/node_modules/@grpc/grpc-js/src/call.ts new file mode 100644 index 0000000..426deb6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/call.ts @@ -0,0 +1,218 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { EventEmitter } from 'events'; +import { Duplex, Readable, Writable } from 'stream'; + +import { StatusObject, MessageContext } from './call-interface'; +import { Status } from './constants'; +import { EmitterAugmentation1 } from './events'; +import { Metadata } from './metadata'; +import { ObjectReadable, ObjectWritable, WriteCallback } from './object-stream'; +import { InterceptingCallInterface } from './client-interceptors'; +import { AuthContext } from './auth-context'; + +/** + * A type extending the built-in Error object with additional fields. + */ +export type ServiceError = StatusObject & Error; + +/** + * A base type for all user-facing values returned by client-side method calls. + */ +export type SurfaceCall = { + call?: InterceptingCallInterface; + cancel(): void; + getPeer(): string; + getAuthContext(): AuthContext | null; +} & EmitterAugmentation1<'metadata', Metadata> & + EmitterAugmentation1<'status', StatusObject> & + EventEmitter; + +/** + * A type representing the return value of a unary method call. + */ +export type ClientUnaryCall = SurfaceCall; + +/** + * A type representing the return value of a server stream method call. + */ +export type ClientReadableStream = { + deserialize: (chunk: Buffer) => ResponseType; +} & SurfaceCall & + ObjectReadable; + +/** + * A type representing the return value of a client stream method call. + */ +export type ClientWritableStream = { + serialize: (value: RequestType) => Buffer; +} & SurfaceCall & + ObjectWritable; + +/** + * A type representing the return value of a bidirectional stream method call. + */ +export type ClientDuplexStream = + ClientWritableStream & ClientReadableStream; + +/** + * Construct a ServiceError from a StatusObject. This function exists primarily + * as an attempt to make the error stack trace clearly communicate that the + * error is not necessarily a problem in gRPC itself. + * @param status + */ +export function callErrorFromStatus( + status: StatusObject, + callerStack: string +): ServiceError { + const message = `${status.code} ${Status[status.code]}: ${status.details}`; + const error = new Error(message); + const stack = `${error.stack}\nfor call at\n${callerStack}`; + return Object.assign(new Error(message), status, { stack }); +} + +export class ClientUnaryCallImpl + extends EventEmitter + implements ClientUnaryCall +{ + public call?: InterceptingCallInterface; + constructor() { + super(); + } + + cancel(): void { + this.call?.cancelWithStatus(Status.CANCELLED, 'Cancelled on client'); + } + + getPeer(): string { + return this.call?.getPeer() ?? 'unknown'; + } + + getAuthContext(): AuthContext | null { + return this.call?.getAuthContext() ?? null; + } +} + +export class ClientReadableStreamImpl + extends Readable + implements ClientReadableStream +{ + public call?: InterceptingCallInterface; + constructor(readonly deserialize: (chunk: Buffer) => ResponseType) { + super({ objectMode: true }); + } + + cancel(): void { + this.call?.cancelWithStatus(Status.CANCELLED, 'Cancelled on client'); + } + + getPeer(): string { + return this.call?.getPeer() ?? 'unknown'; + } + + getAuthContext(): AuthContext | null { + return this.call?.getAuthContext() ?? null; + } + + _read(_size: number): void { + this.call?.startRead(); + } +} + +export class ClientWritableStreamImpl + extends Writable + implements ClientWritableStream +{ + public call?: InterceptingCallInterface; + constructor(readonly serialize: (value: RequestType) => Buffer) { + super({ objectMode: true }); + } + + cancel(): void { + this.call?.cancelWithStatus(Status.CANCELLED, 'Cancelled on client'); + } + + getPeer(): string { + return this.call?.getPeer() ?? 'unknown'; + } + + getAuthContext(): AuthContext | null { + return this.call?.getAuthContext() ?? null; + } + + _write(chunk: RequestType, encoding: string, cb: WriteCallback) { + const context: MessageContext = { + callback: cb, + }; + const flags = Number(encoding); + if (!Number.isNaN(flags)) { + context.flags = flags; + } + this.call?.sendMessageWithContext(context, chunk); + } + + _final(cb: Function) { + this.call?.halfClose(); + cb(); + } +} + +export class ClientDuplexStreamImpl + extends Duplex + implements ClientDuplexStream +{ + public call?: InterceptingCallInterface; + constructor( + readonly serialize: (value: RequestType) => Buffer, + readonly deserialize: (chunk: Buffer) => ResponseType + ) { + super({ objectMode: true }); + } + + cancel(): void { + this.call?.cancelWithStatus(Status.CANCELLED, 'Cancelled on client'); + } + + getPeer(): string { + return this.call?.getPeer() ?? 'unknown'; + } + + getAuthContext(): AuthContext | null { + return this.call?.getAuthContext() ?? null; + } + + _read(_size: number): void { + this.call?.startRead(); + } + + _write(chunk: RequestType, encoding: string, cb: WriteCallback) { + const context: MessageContext = { + callback: cb, + }; + const flags = Number(encoding); + if (!Number.isNaN(flags)) { + context.flags = flags; + } + this.call?.sendMessageWithContext(context, chunk); + } + + _final(cb: Function) { + this.call?.halfClose(); + cb(); + } +} diff --git a/node_modules/@grpc/grpc-js/src/certificate-provider.ts b/node_modules/@grpc/grpc-js/src/certificate-provider.ts new file mode 100644 index 0000000..27a2e7d --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/certificate-provider.ts @@ -0,0 +1,176 @@ +/* + * Copyright 2024 gRPC authors. + * + * 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. + * + */ + +import * as fs from 'fs'; +import * as logging from './logging'; +import { LogVerbosity } from './constants'; +import { promisify } from 'util'; + +const TRACER_NAME = 'certificate_provider'; + +function trace(text: string) { + logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text); +} + +export interface CaCertificateUpdate { + caCertificate: Buffer; +} + +export interface IdentityCertificateUpdate { + certificate: Buffer; + privateKey: Buffer; +} + +export interface CaCertificateUpdateListener { + (update: CaCertificateUpdate | null): void; +} + +export interface IdentityCertificateUpdateListener { + (update: IdentityCertificateUpdate | null) : void; +} + +export interface CertificateProvider { + addCaCertificateListener(listener: CaCertificateUpdateListener): void; + removeCaCertificateListener(listener: CaCertificateUpdateListener): void; + addIdentityCertificateListener(listener: IdentityCertificateUpdateListener): void; + removeIdentityCertificateListener(listener: IdentityCertificateUpdateListener): void; +} + +export interface FileWatcherCertificateProviderConfig { + certificateFile?: string | undefined; + privateKeyFile?: string | undefined; + caCertificateFile?: string | undefined; + refreshIntervalMs: number; +} + +const readFilePromise = promisify(fs.readFile); + +export class FileWatcherCertificateProvider implements CertificateProvider { + private refreshTimer: NodeJS.Timeout | null = null; + private fileResultPromise: Promise<[PromiseSettledResult, PromiseSettledResult, PromiseSettledResult]> | null = null; + private latestCaUpdate: CaCertificateUpdate | null | undefined = undefined; + private caListeners: Set = new Set(); + private latestIdentityUpdate: IdentityCertificateUpdate | null | undefined = undefined; + private identityListeners: Set = new Set(); + private lastUpdateTime: Date | null = null; + + constructor( + private config: FileWatcherCertificateProviderConfig + ) { + if ((config.certificateFile === undefined) !== (config.privateKeyFile === undefined)) { + throw new Error('certificateFile and privateKeyFile must be set or unset together'); + } + if (config.certificateFile === undefined && config.caCertificateFile === undefined) { + throw new Error('At least one of certificateFile and caCertificateFile must be set'); + } + trace('File watcher constructed with config ' + JSON.stringify(config)); + } + + private updateCertificates() { + if (this.fileResultPromise) { + return; + } + this.fileResultPromise = Promise.allSettled([ + this.config.certificateFile ? readFilePromise(this.config.certificateFile) : Promise.reject(), + this.config.privateKeyFile ? readFilePromise(this.config.privateKeyFile) : Promise.reject(), + this.config.caCertificateFile ? readFilePromise(this.config.caCertificateFile) : Promise.reject() + ]); + this.fileResultPromise.then(([certificateResult, privateKeyResult, caCertificateResult]) => { + if (!this.refreshTimer) { + return; + } + trace('File watcher read certificates certificate ' + certificateResult.status + ', privateKey ' + privateKeyResult.status + ', CA certificate ' + caCertificateResult.status); + this.lastUpdateTime = new Date(); + this.fileResultPromise = null; + if (certificateResult.status === 'fulfilled' && privateKeyResult.status === 'fulfilled') { + this.latestIdentityUpdate = { + certificate: certificateResult.value, + privateKey: privateKeyResult.value + }; + } else { + this.latestIdentityUpdate = null; + } + if (caCertificateResult.status === 'fulfilled') { + this.latestCaUpdate = { + caCertificate: caCertificateResult.value + }; + } else { + this.latestCaUpdate = null; + } + for (const listener of this.identityListeners) { + listener(this.latestIdentityUpdate); + } + for (const listener of this.caListeners) { + listener(this.latestCaUpdate); + } + }); + trace('File watcher initiated certificate update'); + } + + private maybeStartWatchingFiles() { + if (!this.refreshTimer) { + /* Perform the first read immediately, but only if there was not already + * a recent read, to avoid reading from the filesystem significantly more + * frequently than configured if the provider quickly switches between + * used and unused. */ + const timeSinceLastUpdate = this.lastUpdateTime ? (new Date()).getTime() - this.lastUpdateTime.getTime() : Infinity; + if (timeSinceLastUpdate > this.config.refreshIntervalMs) { + this.updateCertificates(); + } + if (timeSinceLastUpdate > this.config.refreshIntervalMs * 2) { + // Clear out old updates if they are definitely stale + this.latestCaUpdate = undefined; + this.latestIdentityUpdate = undefined; + } + this.refreshTimer = setInterval(() => this.updateCertificates(), this.config.refreshIntervalMs); + trace('File watcher started watching'); + } + } + + private maybeStopWatchingFiles() { + if (this.caListeners.size === 0 && this.identityListeners.size === 0) { + this.fileResultPromise = null; + if (this.refreshTimer) { + clearInterval(this.refreshTimer); + this.refreshTimer = null; + } + } + } + + addCaCertificateListener(listener: CaCertificateUpdateListener): void { + this.caListeners.add(listener); + this.maybeStartWatchingFiles(); + if (this.latestCaUpdate !== undefined) { + process.nextTick(listener, this.latestCaUpdate); + } + } + removeCaCertificateListener(listener: CaCertificateUpdateListener): void { + this.caListeners.delete(listener); + this.maybeStopWatchingFiles(); + } + addIdentityCertificateListener(listener: IdentityCertificateUpdateListener): void { + this.identityListeners.add(listener); + this.maybeStartWatchingFiles(); + if (this.latestIdentityUpdate !== undefined) { + process.nextTick(listener, this.latestIdentityUpdate); + } + } + removeIdentityCertificateListener(listener: IdentityCertificateUpdateListener): void { + this.identityListeners.delete(listener); + this.maybeStopWatchingFiles(); + } +} diff --git a/node_modules/@grpc/grpc-js/src/channel-credentials.ts b/node_modules/@grpc/grpc-js/src/channel-credentials.ts new file mode 100644 index 0000000..a6ded81 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/channel-credentials.ts @@ -0,0 +1,523 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { + ConnectionOptions, + createSecureContext, + PeerCertificate, + SecureContext, + checkServerIdentity, + connect as tlsConnect +} from 'tls'; + +import { CallCredentials } from './call-credentials'; +import { CIPHER_SUITES, getDefaultRootsData } from './tls-helpers'; +import { CaCertificateUpdate, CaCertificateUpdateListener, CertificateProvider, IdentityCertificateUpdate, IdentityCertificateUpdateListener } from './certificate-provider'; +import { Socket } from 'net'; +import { ChannelOptions } from './channel-options'; +import { GrpcUri, parseUri, splitHostPort } from './uri-parser'; +import { getDefaultAuthority } from './resolver'; +import { log } from './logging'; +import { LogVerbosity } from './constants'; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function verifyIsBufferOrNull(obj: any, friendlyName: string): void { + if (obj && !(obj instanceof Buffer)) { + throw new TypeError(`${friendlyName}, if provided, must be a Buffer.`); + } +} + +/** + * A callback that will receive the expected hostname and presented peer + * certificate as parameters. The callback should return an error to + * indicate that the presented certificate is considered invalid and + * otherwise returned undefined. + */ +export type CheckServerIdentityCallback = ( + hostname: string, + cert: PeerCertificate +) => Error | undefined; + +/** + * Additional peer verification options that can be set when creating + * SSL credentials. + */ +export interface VerifyOptions { + /** + * If set, this callback will be invoked after the usual hostname verification + * has been performed on the peer certificate. + */ + checkServerIdentity?: CheckServerIdentityCallback; + rejectUnauthorized?: boolean; +} + +export interface SecureConnectResult { + socket: Socket; + secure: boolean; +} + +export interface SecureConnector { + connect(socket: Socket): Promise; + waitForReady(): Promise; + getCallCredentials(): CallCredentials; + destroy(): void; +} + +/** + * A class that contains credentials for communicating over a channel, as well + * as a set of per-call credentials, which are applied to every method call made + * over a channel initialized with an instance of this class. + */ +export abstract class ChannelCredentials { + /** + * Returns a copy of this object with the included set of per-call credentials + * expanded to include callCredentials. + * @param callCredentials A CallCredentials object to associate with this + * instance. + */ + compose(callCredentials: CallCredentials): ChannelCredentials { + return new ComposedChannelCredentialsImpl(this, callCredentials); + } + + /** + * Indicates whether this credentials object creates a secure channel. + */ + abstract _isSecure(): boolean; + + /** + * Check whether two channel credentials objects are equal. Two secure + * credentials are equal if they were constructed with the same parameters. + * @param other The other ChannelCredentials Object + */ + abstract _equals(other: ChannelCredentials): boolean; + + abstract _createSecureConnector(channelTarget: GrpcUri, options: ChannelOptions, callCredentials?: CallCredentials): SecureConnector; + + /** + * Return a new ChannelCredentials instance with a given set of credentials. + * The resulting instance can be used to construct a Channel that communicates + * over TLS. + * @param rootCerts The root certificate data. + * @param privateKey The client certificate private key, if available. + * @param certChain The client certificate key chain, if available. + * @param verifyOptions Additional options to modify certificate verification + */ + static createSsl( + rootCerts?: Buffer | null, + privateKey?: Buffer | null, + certChain?: Buffer | null, + verifyOptions?: VerifyOptions + ): ChannelCredentials { + verifyIsBufferOrNull(rootCerts, 'Root certificate'); + verifyIsBufferOrNull(privateKey, 'Private key'); + verifyIsBufferOrNull(certChain, 'Certificate chain'); + if (privateKey && !certChain) { + throw new Error( + 'Private key must be given with accompanying certificate chain' + ); + } + if (!privateKey && certChain) { + throw new Error( + 'Certificate chain must be given with accompanying private key' + ); + } + const secureContext = createSecureContext({ + ca: rootCerts ?? getDefaultRootsData() ?? undefined, + key: privateKey ?? undefined, + cert: certChain ?? undefined, + ciphers: CIPHER_SUITES, + }); + return new SecureChannelCredentialsImpl(secureContext, verifyOptions ?? {}); + } + + /** + * Return a new ChannelCredentials instance with credentials created using + * the provided secureContext. The resulting instances can be used to + * construct a Channel that communicates over TLS. gRPC will not override + * anything in the provided secureContext, so the environment variables + * GRPC_SSL_CIPHER_SUITES and GRPC_DEFAULT_SSL_ROOTS_FILE_PATH will + * not be applied. + * @param secureContext The return value of tls.createSecureContext() + * @param verifyOptions Additional options to modify certificate verification + */ + static createFromSecureContext( + secureContext: SecureContext, + verifyOptions?: VerifyOptions + ): ChannelCredentials { + return new SecureChannelCredentialsImpl(secureContext, verifyOptions ?? {}); + } + + /** + * Return a new ChannelCredentials instance with no credentials. + */ + static createInsecure(): ChannelCredentials { + return new InsecureChannelCredentialsImpl(); + } +} + +class InsecureChannelCredentialsImpl extends ChannelCredentials { + constructor() { + super(); + } + + override compose(callCredentials: CallCredentials): never { + throw new Error('Cannot compose insecure credentials'); + } + _isSecure(): boolean { + return false; + } + _equals(other: ChannelCredentials): boolean { + return other instanceof InsecureChannelCredentialsImpl; + } + _createSecureConnector(channelTarget: GrpcUri, options: ChannelOptions, callCredentials?: CallCredentials): SecureConnector { + return { + connect(socket) { + return Promise.resolve({ + socket, + secure: false + }); + }, + waitForReady: () => { + return Promise.resolve(); + }, + getCallCredentials: () => { + return callCredentials ?? CallCredentials.createEmpty(); + }, + destroy() {} + } + } +} + +function getConnectionOptions(secureContext: SecureContext, verifyOptions: VerifyOptions, channelTarget: GrpcUri, options: ChannelOptions): ConnectionOptions { + const connectionOptions: ConnectionOptions = { + secureContext: secureContext + }; + let realTarget: GrpcUri = channelTarget; + if ('grpc.http_connect_target' in options) { + const parsedTarget = parseUri(options['grpc.http_connect_target']!); + if (parsedTarget) { + realTarget = parsedTarget; + } + } + const targetPath = getDefaultAuthority(realTarget); + const hostPort = splitHostPort(targetPath); + const remoteHost = hostPort?.host ?? targetPath; + connectionOptions.host = remoteHost; + + if (verifyOptions.checkServerIdentity) { + connectionOptions.checkServerIdentity = verifyOptions.checkServerIdentity; + } + if (verifyOptions.rejectUnauthorized !== undefined) { + connectionOptions.rejectUnauthorized = verifyOptions.rejectUnauthorized; + } + connectionOptions.ALPNProtocols = ['h2']; + if (options['grpc.ssl_target_name_override']) { + const sslTargetNameOverride = options['grpc.ssl_target_name_override']!; + const originalCheckServerIdentity = + connectionOptions.checkServerIdentity ?? checkServerIdentity; + connectionOptions.checkServerIdentity = ( + host: string, + cert: PeerCertificate + ): Error | undefined => { + return originalCheckServerIdentity(sslTargetNameOverride, cert); + }; + connectionOptions.servername = sslTargetNameOverride; + } else { + connectionOptions.servername = remoteHost; + } + if (options['grpc-node.tls_enable_trace']) { + connectionOptions.enableTrace = true; + } + return connectionOptions; +} + +class SecureConnectorImpl implements SecureConnector { + constructor(private connectionOptions: ConnectionOptions, private callCredentials: CallCredentials) { + } + connect(socket: Socket): Promise { + const tlsConnectOptions: ConnectionOptions = { + socket: socket, + ...this.connectionOptions + }; + return new Promise((resolve, reject) => { + const tlsSocket = tlsConnect(tlsConnectOptions, () => { + if ((this.connectionOptions.rejectUnauthorized ?? true) && !tlsSocket.authorized) { + reject(tlsSocket.authorizationError); + return; + } + resolve({ + socket: tlsSocket, + secure: true + }) + }); + tlsSocket.on('error', (error: Error) => { + reject(error); + }); + }); + } + waitForReady(): Promise { + return Promise.resolve(); + } + getCallCredentials(): CallCredentials { + return this.callCredentials; + } + destroy() {} +} + +class SecureChannelCredentialsImpl extends ChannelCredentials { + constructor( + private secureContext: SecureContext, + private verifyOptions: VerifyOptions + ) { + super(); + } + + _isSecure(): boolean { + return true; + } + _equals(other: ChannelCredentials): boolean { + if (this === other) { + return true; + } + if (other instanceof SecureChannelCredentialsImpl) { + return ( + this.secureContext === other.secureContext && + this.verifyOptions.checkServerIdentity === + other.verifyOptions.checkServerIdentity + ); + } else { + return false; + } + } + _createSecureConnector(channelTarget: GrpcUri, options: ChannelOptions, callCredentials?: CallCredentials): SecureConnector { + const connectionOptions = getConnectionOptions(this.secureContext, this.verifyOptions, channelTarget, options); + return new SecureConnectorImpl(connectionOptions, callCredentials ?? CallCredentials.createEmpty()); + } +} + +class CertificateProviderChannelCredentialsImpl extends ChannelCredentials { + private refcount: number = 0; + /** + * `undefined` means that the certificates have not yet been loaded. `null` + * means that an attempt to load them has completed, and has failed. + */ + private latestCaUpdate: CaCertificateUpdate | null | undefined = undefined; + /** + * `undefined` means that the certificates have not yet been loaded. `null` + * means that an attempt to load them has completed, and has failed. + */ + private latestIdentityUpdate: IdentityCertificateUpdate | null | undefined = undefined; + private caCertificateUpdateListener: CaCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this); + private identityCertificateUpdateListener: IdentityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this); + private secureContextWatchers: ((context: SecureContext | null) => void)[] = []; + private static SecureConnectorImpl = class implements SecureConnector { + constructor(private parent: CertificateProviderChannelCredentialsImpl, private channelTarget: GrpcUri, private options: ChannelOptions, private callCredentials: CallCredentials) {} + + connect(socket: Socket): Promise { + return new Promise((resolve, reject) => { + const secureContext = this.parent.getLatestSecureContext(); + if (!secureContext) { + reject(new Error('Failed to load credentials')); + return; + } + if (socket.closed) { + reject(new Error('Socket closed while loading credentials')); + } + const connnectionOptions = getConnectionOptions(secureContext, this.parent.verifyOptions, this.channelTarget, this.options); + const tlsConnectOptions: ConnectionOptions = { + socket: socket, + ...connnectionOptions + } + const closeCallback = () => { + reject(new Error('Socket closed')); + }; + const errorCallback = (error: Error) => { + reject(error); + } + const tlsSocket = tlsConnect(tlsConnectOptions, () => { + tlsSocket.removeListener('close', closeCallback); + tlsSocket.removeListener('error', errorCallback); + if ((this.parent.verifyOptions.rejectUnauthorized ?? true) && !tlsSocket.authorized) { + reject(tlsSocket.authorizationError); + return; + } + resolve({ + socket: tlsSocket, + secure: true + }); + }); + tlsSocket.once('close', closeCallback); + tlsSocket.once('error', errorCallback); + }); + } + + async waitForReady(): Promise { + await this.parent.getSecureContext(); + } + + getCallCredentials(): CallCredentials { + return this.callCredentials; + } + + destroy() { + this.parent.unref(); + } + } + constructor( + private caCertificateProvider: CertificateProvider, + private identityCertificateProvider: CertificateProvider | null, + private verifyOptions: VerifyOptions + ) { + super(); + } + _isSecure(): boolean { + return true; + } + _equals(other: ChannelCredentials): boolean { + if (this === other) { + return true; + } + if (other instanceof CertificateProviderChannelCredentialsImpl) { + return this.caCertificateProvider === other.caCertificateProvider && + this.identityCertificateProvider === other.identityCertificateProvider && + this.verifyOptions?.checkServerIdentity === other.verifyOptions?.checkServerIdentity; + } else { + return false; + } + } + private ref(): void { + if (this.refcount === 0) { + this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener); + this.identityCertificateProvider?.addIdentityCertificateListener(this.identityCertificateUpdateListener); + } + this.refcount += 1; + } + private unref(): void { + this.refcount -= 1; + if (this.refcount === 0) { + this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener); + this.identityCertificateProvider?.removeIdentityCertificateListener(this.identityCertificateUpdateListener); + } + } + _createSecureConnector(channelTarget: GrpcUri, options: ChannelOptions, callCredentials?: CallCredentials): SecureConnector { + this.ref(); + return new CertificateProviderChannelCredentialsImpl.SecureConnectorImpl(this, channelTarget, options, callCredentials ?? CallCredentials.createEmpty()); + } + + private maybeUpdateWatchers() { + if (this.hasReceivedUpdates()) { + for (const watcher of this.secureContextWatchers) { + watcher(this.getLatestSecureContext()); + } + this.secureContextWatchers = []; + } + } + + private handleCaCertificateUpdate(update: CaCertificateUpdate | null) { + this.latestCaUpdate = update; + this.maybeUpdateWatchers(); + } + + private handleIdentityCertitificateUpdate(update: IdentityCertificateUpdate | null) { + this.latestIdentityUpdate = update; + this.maybeUpdateWatchers(); + } + + private hasReceivedUpdates(): boolean { + if (this.latestCaUpdate === undefined) { + return false; + } + if (this.identityCertificateProvider && this.latestIdentityUpdate === undefined) { + return false; + } + return true; + } + + private getSecureContext(): Promise { + if (this.hasReceivedUpdates()) { + return Promise.resolve(this.getLatestSecureContext()); + } else { + return new Promise(resolve => { + this.secureContextWatchers.push(resolve); + }); + } + } + + private getLatestSecureContext(): SecureContext | null { + if (!this.latestCaUpdate) { + return null; + } + if (this.identityCertificateProvider !== null && !this.latestIdentityUpdate) { + return null; + } + try { + return createSecureContext({ + ca: this.latestCaUpdate.caCertificate, + key: this.latestIdentityUpdate?.privateKey, + cert: this.latestIdentityUpdate?.certificate, + ciphers: CIPHER_SUITES + }); + } catch (e) { + log(LogVerbosity.ERROR, 'Failed to createSecureContext with error ' + (e as Error).message); + return null; + } + } +} + +export function createCertificateProviderChannelCredentials(caCertificateProvider: CertificateProvider, identityCertificateProvider: CertificateProvider | null, verifyOptions?: VerifyOptions) { + return new CertificateProviderChannelCredentialsImpl(caCertificateProvider, identityCertificateProvider, verifyOptions ?? {}); +} + +class ComposedChannelCredentialsImpl extends ChannelCredentials { + constructor( + private channelCredentials: ChannelCredentials, + private callCredentials: CallCredentials + ) { + super(); + if (!channelCredentials._isSecure()) { + throw new Error('Cannot compose insecure credentials'); + } + } + compose(callCredentials: CallCredentials) { + const combinedCallCredentials = + this.callCredentials.compose(callCredentials); + return new ComposedChannelCredentialsImpl( + this.channelCredentials, + combinedCallCredentials + ); + } + _isSecure(): boolean { + return true; + } + _equals(other: ChannelCredentials): boolean { + if (this === other) { + return true; + } + if (other instanceof ComposedChannelCredentialsImpl) { + return ( + this.channelCredentials._equals(other.channelCredentials) && + this.callCredentials._equals(other.callCredentials) + ); + } else { + return false; + } + } + _createSecureConnector(channelTarget: GrpcUri, options: ChannelOptions, callCredentials?: CallCredentials): SecureConnector { + const combinedCallCredentials = this.callCredentials.compose(callCredentials ?? CallCredentials.createEmpty()); + return this.channelCredentials._createSecureConnector(channelTarget, options, combinedCallCredentials); + } +} diff --git a/node_modules/@grpc/grpc-js/src/channel-options.ts b/node_modules/@grpc/grpc-js/src/channel-options.ts new file mode 100644 index 0000000..41bd26d --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/channel-options.ts @@ -0,0 +1,128 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { CompressionAlgorithms } from './compression-algorithms'; + +/** + * An interface that contains options used when initializing a Channel instance. + */ +export interface ChannelOptions { + 'grpc.ssl_target_name_override'?: string; + 'grpc.primary_user_agent'?: string; + 'grpc.secondary_user_agent'?: string; + 'grpc.default_authority'?: string; + 'grpc.keepalive_time_ms'?: number; + 'grpc.keepalive_timeout_ms'?: number; + 'grpc.keepalive_permit_without_calls'?: number; + 'grpc.service_config'?: string; + 'grpc.max_concurrent_streams'?: number; + 'grpc.initial_reconnect_backoff_ms'?: number; + 'grpc.max_reconnect_backoff_ms'?: number; + 'grpc.use_local_subchannel_pool'?: number; + 'grpc.max_send_message_length'?: number; + 'grpc.max_receive_message_length'?: number; + 'grpc.enable_http_proxy'?: number; + /* http_connect_target and http_connect_creds are used for passing data + * around internally, and should not be documented as public-facing options + */ + 'grpc.http_connect_target'?: string; + 'grpc.http_connect_creds'?: string; + 'grpc.default_compression_algorithm'?: CompressionAlgorithms; + 'grpc.enable_channelz'?: number; + 'grpc.dns_min_time_between_resolutions_ms'?: number; + 'grpc.enable_retries'?: number; + 'grpc.per_rpc_retry_buffer_size'?: number; + /* This option is pattered like a core option, but the core does not have + * this option. It is closely related to the option + * grpc.per_rpc_retry_buffer_size, which is in the core. The core will likely + * implement this functionality using the ResourceQuota mechanism, so there + * will probably not be any collision or other inconsistency. */ + 'grpc.retry_buffer_size'?: number; + 'grpc.max_connection_age_ms'?: number; + 'grpc.max_connection_age_grace_ms'?: number; + 'grpc.max_connection_idle_ms'?: number; + 'grpc-node.max_session_memory'?: number; + 'grpc.service_config_disable_resolution'?: number; + 'grpc.client_idle_timeout_ms'?: number; + /** + * Set the enableTrace option in TLS clients and servers + */ + 'grpc-node.tls_enable_trace'?: number; + 'grpc.lb.ring_hash.ring_size_cap'?: number; + 'grpc-node.retry_max_attempts_limit'?: number; + 'grpc-node.flow_control_window'?: number; + 'grpc.server_call_metric_recording'?: number; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + [key: string]: any; +} + +/** + * This is for checking provided options at runtime. This is an object for + * easier membership checking. + */ +export const recognizedOptions = { + 'grpc.ssl_target_name_override': true, + 'grpc.primary_user_agent': true, + 'grpc.secondary_user_agent': true, + 'grpc.default_authority': true, + 'grpc.keepalive_time_ms': true, + 'grpc.keepalive_timeout_ms': true, + 'grpc.keepalive_permit_without_calls': true, + 'grpc.service_config': true, + 'grpc.max_concurrent_streams': true, + 'grpc.initial_reconnect_backoff_ms': true, + 'grpc.max_reconnect_backoff_ms': true, + 'grpc.use_local_subchannel_pool': true, + 'grpc.max_send_message_length': true, + 'grpc.max_receive_message_length': true, + 'grpc.enable_http_proxy': true, + 'grpc.enable_channelz': true, + 'grpc.dns_min_time_between_resolutions_ms': true, + 'grpc.enable_retries': true, + 'grpc.per_rpc_retry_buffer_size': true, + 'grpc.retry_buffer_size': true, + 'grpc.max_connection_age_ms': true, + 'grpc.max_connection_age_grace_ms': true, + 'grpc-node.max_session_memory': true, + 'grpc.service_config_disable_resolution': true, + 'grpc.client_idle_timeout_ms': true, + 'grpc-node.tls_enable_trace': true, + 'grpc.lb.ring_hash.ring_size_cap': true, + 'grpc-node.retry_max_attempts_limit': true, + 'grpc-node.flow_control_window': true, + 'grpc.server_call_metric_recording': true +}; + +export function channelOptionsEqual( + options1: ChannelOptions, + options2: ChannelOptions +) { + const keys1 = Object.keys(options1).sort(); + const keys2 = Object.keys(options2).sort(); + if (keys1.length !== keys2.length) { + return false; + } + for (let i = 0; i < keys1.length; i += 1) { + if (keys1[i] !== keys2[i]) { + return false; + } + if (options1[keys1[i]] !== options2[keys2[i]]) { + return false; + } + } + return true; +} diff --git a/node_modules/@grpc/grpc-js/src/channel.ts b/node_modules/@grpc/grpc-js/src/channel.ts new file mode 100644 index 0000000..514920c --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/channel.ts @@ -0,0 +1,174 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { ChannelCredentials } from './channel-credentials'; +import { ChannelOptions } from './channel-options'; +import { ServerSurfaceCall } from './server-call'; + +import { ConnectivityState } from './connectivity-state'; +import type { ChannelRef } from './channelz'; +import { Call } from './call-interface'; +import { InternalChannel } from './internal-channel'; +import { Deadline } from './deadline'; + +/** + * An interface that represents a communication channel to a server specified + * by a given address. + */ +export interface Channel { + /** + * Close the channel. This has the same functionality as the existing + * grpc.Client.prototype.close + */ + close(): void; + /** + * Return the target that this channel connects to + */ + getTarget(): string; + /** + * Get the channel's current connectivity state. This method is here mainly + * because it is in the existing internal Channel class, and there isn't + * another good place to put it. + * @param tryToConnect If true, the channel will start connecting if it is + * idle. Otherwise, idle channels will only start connecting when a + * call starts. + */ + getConnectivityState(tryToConnect: boolean): ConnectivityState; + /** + * Watch for connectivity state changes. This is also here mainly because + * it is in the existing external Channel class. + * @param currentState The state to watch for transitions from. This should + * always be populated by calling getConnectivityState immediately + * before. + * @param deadline A deadline for waiting for a state change + * @param callback Called with no error when a state change, or with an + * error if the deadline passes without a state change. + */ + watchConnectivityState( + currentState: ConnectivityState, + deadline: Date | number, + callback: (error?: Error) => void + ): void; + /** + * Get the channelz reference object for this channel. A request to the + * channelz service for the id in this object will provide information + * about this channel. + */ + getChannelzRef(): ChannelRef; + /** + * Create a call object. Call is an opaque type that is used by the Client + * class. This function is called by the gRPC library when starting a + * request. Implementers should return an instance of Call that is returned + * from calling createCall on an instance of the provided Channel class. + * @param method The full method string to request. + * @param deadline The call deadline + * @param host A host string override for making the request + * @param parentCall A server call to propagate some information from + * @param propagateFlags A bitwise combination of elements of grpc.propagate + * that indicates what information to propagate from parentCall. + */ + createCall( + method: string, + deadline: Deadline, + host: string | null | undefined, + parentCall: ServerSurfaceCall | null, + propagateFlags: number | null | undefined + ): Call; +} + +export class ChannelImplementation implements Channel { + private internalChannel: InternalChannel; + + constructor( + target: string, + credentials: ChannelCredentials, + options: ChannelOptions + ) { + if (typeof target !== 'string') { + throw new TypeError('Channel target must be a string'); + } + if (!(credentials instanceof ChannelCredentials)) { + throw new TypeError( + 'Channel credentials must be a ChannelCredentials object' + ); + } + if (options) { + if (typeof options !== 'object') { + throw new TypeError('Channel options must be an object'); + } + } + + this.internalChannel = new InternalChannel(target, credentials, options); + } + + close() { + this.internalChannel.close(); + } + + getTarget() { + return this.internalChannel.getTarget(); + } + + getConnectivityState(tryToConnect: boolean) { + return this.internalChannel.getConnectivityState(tryToConnect); + } + + watchConnectivityState( + currentState: ConnectivityState, + deadline: Date | number, + callback: (error?: Error) => void + ): void { + this.internalChannel.watchConnectivityState( + currentState, + deadline, + callback + ); + } + + /** + * Get the channelz reference object for this channel. The returned value is + * garbage if channelz is disabled for this channel. + * @returns + */ + getChannelzRef() { + return this.internalChannel.getChannelzRef(); + } + + createCall( + method: string, + deadline: Deadline, + host: string | null | undefined, + parentCall: ServerSurfaceCall | null, + propagateFlags: number | null | undefined + ): Call { + if (typeof method !== 'string') { + throw new TypeError('Channel#createCall: method must be a string'); + } + if (!(typeof deadline === 'number' || deadline instanceof Date)) { + throw new TypeError( + 'Channel#createCall: deadline must be a number or Date' + ); + } + return this.internalChannel.createCall( + method, + deadline, + host, + parentCall, + propagateFlags + ); + } +} diff --git a/node_modules/@grpc/grpc-js/src/channelz.ts b/node_modules/@grpc/grpc-js/src/channelz.ts new file mode 100644 index 0000000..7242d71 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/channelz.ts @@ -0,0 +1,909 @@ +/* + * Copyright 2021 gRPC authors. + * + * 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. + * + */ + +import { isIPv4, isIPv6 } from 'net'; +import { OrderedMap, type OrderedMapIterator } from '@js-sdsl/ordered-map'; +import { ConnectivityState } from './connectivity-state'; +import { Status } from './constants'; +import { Timestamp } from './generated/google/protobuf/Timestamp'; +import { Channel as ChannelMessage } from './generated/grpc/channelz/v1/Channel'; +import { ChannelConnectivityState__Output } from './generated/grpc/channelz/v1/ChannelConnectivityState'; +import { ChannelRef as ChannelRefMessage } from './generated/grpc/channelz/v1/ChannelRef'; +import { ChannelTrace } from './generated/grpc/channelz/v1/ChannelTrace'; +import { GetChannelRequest__Output } from './generated/grpc/channelz/v1/GetChannelRequest'; +import { GetChannelResponse } from './generated/grpc/channelz/v1/GetChannelResponse'; +import { sendUnaryData, ServerUnaryCall } from './server-call'; +import { ServerRef as ServerRefMessage } from './generated/grpc/channelz/v1/ServerRef'; +import { SocketRef as SocketRefMessage } from './generated/grpc/channelz/v1/SocketRef'; +import { + isTcpSubchannelAddress, + SubchannelAddress, +} from './subchannel-address'; +import { SubchannelRef as SubchannelRefMessage } from './generated/grpc/channelz/v1/SubchannelRef'; +import { GetServerRequest__Output } from './generated/grpc/channelz/v1/GetServerRequest'; +import { GetServerResponse } from './generated/grpc/channelz/v1/GetServerResponse'; +import { Server as ServerMessage } from './generated/grpc/channelz/v1/Server'; +import { GetServersRequest__Output } from './generated/grpc/channelz/v1/GetServersRequest'; +import { GetServersResponse } from './generated/grpc/channelz/v1/GetServersResponse'; +import { GetTopChannelsRequest__Output } from './generated/grpc/channelz/v1/GetTopChannelsRequest'; +import { GetTopChannelsResponse } from './generated/grpc/channelz/v1/GetTopChannelsResponse'; +import { GetSubchannelRequest__Output } from './generated/grpc/channelz/v1/GetSubchannelRequest'; +import { GetSubchannelResponse } from './generated/grpc/channelz/v1/GetSubchannelResponse'; +import { Subchannel as SubchannelMessage } from './generated/grpc/channelz/v1/Subchannel'; +import { GetSocketRequest__Output } from './generated/grpc/channelz/v1/GetSocketRequest'; +import { GetSocketResponse } from './generated/grpc/channelz/v1/GetSocketResponse'; +import { Socket as SocketMessage } from './generated/grpc/channelz/v1/Socket'; +import { Address } from './generated/grpc/channelz/v1/Address'; +import { Security } from './generated/grpc/channelz/v1/Security'; +import { GetServerSocketsRequest__Output } from './generated/grpc/channelz/v1/GetServerSocketsRequest'; +import { GetServerSocketsResponse } from './generated/grpc/channelz/v1/GetServerSocketsResponse'; +import { + ChannelzDefinition, + ChannelzHandlers, +} from './generated/grpc/channelz/v1/Channelz'; +import { ProtoGrpcType as ChannelzProtoGrpcType } from './generated/channelz'; +import type { loadSync } from '@grpc/proto-loader'; +import { registerAdminService } from './admin'; +import { loadPackageDefinition } from './make-client'; + +export type TraceSeverity = + | 'CT_UNKNOWN' + | 'CT_INFO' + | 'CT_WARNING' + | 'CT_ERROR'; + +interface Ref { + kind: EntityTypes; + id: number; + name: string; +} + +export interface ChannelRef extends Ref { + kind: EntityTypes.channel; +} + +export interface SubchannelRef extends Ref { + kind: EntityTypes.subchannel; +} + +export interface ServerRef extends Ref { + kind: EntityTypes.server; +} + +export interface SocketRef extends Ref { + kind: EntityTypes.socket; +} + +function channelRefToMessage(ref: ChannelRef): ChannelRefMessage { + return { + channel_id: ref.id, + name: ref.name, + }; +} + +function subchannelRefToMessage(ref: SubchannelRef): SubchannelRefMessage { + return { + subchannel_id: ref.id, + name: ref.name, + }; +} + +function serverRefToMessage(ref: ServerRef): ServerRefMessage { + return { + server_id: ref.id, + }; +} + +function socketRefToMessage(ref: SocketRef): SocketRefMessage { + return { + socket_id: ref.id, + name: ref.name, + }; +} + +interface TraceEvent { + description: string; + severity: TraceSeverity; + timestamp: Date; + childChannel?: ChannelRef; + childSubchannel?: SubchannelRef; +} + +/** + * The loose upper bound on the number of events that should be retained in a + * trace. This may be exceeded by up to a factor of 2. Arbitrarily chosen as a + * number that should be large enough to contain the recent relevant + * information, but small enough to not use excessive memory. + */ +const TARGET_RETAINED_TRACES = 32; + +/** + * Default number of sockets/servers/channels/subchannels to return + */ +const DEFAULT_MAX_RESULTS = 100; + +export class ChannelzTraceStub { + readonly events: TraceEvent[] = []; + readonly creationTimestamp: Date = new Date(); + readonly eventsLogged = 0; + + addTrace(): void {} + getTraceMessage(): ChannelTrace { + return { + creation_timestamp: dateToProtoTimestamp(this.creationTimestamp), + num_events_logged: this.eventsLogged, + events: [], + }; + } +} + +export class ChannelzTrace { + events: TraceEvent[] = []; + creationTimestamp: Date; + eventsLogged = 0; + + constructor() { + this.creationTimestamp = new Date(); + } + + addTrace( + severity: TraceSeverity, + description: string, + child?: ChannelRef | SubchannelRef + ) { + const timestamp = new Date(); + this.events.push({ + description: description, + severity: severity, + timestamp: timestamp, + childChannel: child?.kind === 'channel' ? child : undefined, + childSubchannel: child?.kind === 'subchannel' ? child : undefined, + }); + // Whenever the trace array gets too large, discard the first half + if (this.events.length >= TARGET_RETAINED_TRACES * 2) { + this.events = this.events.slice(TARGET_RETAINED_TRACES); + } + this.eventsLogged += 1; + } + + getTraceMessage(): ChannelTrace { + return { + creation_timestamp: dateToProtoTimestamp(this.creationTimestamp), + num_events_logged: this.eventsLogged, + events: this.events.map(event => { + return { + description: event.description, + severity: event.severity, + timestamp: dateToProtoTimestamp(event.timestamp), + channel_ref: event.childChannel + ? channelRefToMessage(event.childChannel) + : null, + subchannel_ref: event.childSubchannel + ? subchannelRefToMessage(event.childSubchannel) + : null, + }; + }), + }; + } +} + +type RefOrderedMap = OrderedMap< + number, + { ref: { id: number; kind: EntityTypes; name: string }; count: number } +>; + +export class ChannelzChildrenTracker { + private channelChildren: RefOrderedMap = new OrderedMap(); + private subchannelChildren: RefOrderedMap = new OrderedMap(); + private socketChildren: RefOrderedMap = new OrderedMap(); + private trackerMap = { + [EntityTypes.channel]: this.channelChildren, + [EntityTypes.subchannel]: this.subchannelChildren, + [EntityTypes.socket]: this.socketChildren, + } as const; + + refChild(child: ChannelRef | SubchannelRef | SocketRef) { + const tracker = this.trackerMap[child.kind]; + const trackedChild = tracker.find(child.id); + + if (trackedChild.equals(tracker.end())) { + tracker.setElement( + child.id, + { + ref: child, + count: 1, + }, + trackedChild + ); + } else { + trackedChild.pointer[1].count += 1; + } + } + + unrefChild(child: ChannelRef | SubchannelRef | SocketRef) { + const tracker = this.trackerMap[child.kind]; + const trackedChild = tracker.getElementByKey(child.id); + if (trackedChild !== undefined) { + trackedChild.count -= 1; + if (trackedChild.count === 0) { + tracker.eraseElementByKey(child.id); + } + } + } + + getChildLists(): ChannelzChildren { + return { + channels: this.channelChildren as ChannelzChildren['channels'], + subchannels: this.subchannelChildren as ChannelzChildren['subchannels'], + sockets: this.socketChildren as ChannelzChildren['sockets'], + }; + } +} + +export class ChannelzChildrenTrackerStub extends ChannelzChildrenTracker { + override refChild(): void {} + override unrefChild(): void {} +} + +export class ChannelzCallTracker { + callsStarted = 0; + callsSucceeded = 0; + callsFailed = 0; + lastCallStartedTimestamp: Date | null = null; + + addCallStarted() { + this.callsStarted += 1; + this.lastCallStartedTimestamp = new Date(); + } + addCallSucceeded() { + this.callsSucceeded += 1; + } + addCallFailed() { + this.callsFailed += 1; + } +} + +export class ChannelzCallTrackerStub extends ChannelzCallTracker { + override addCallStarted() {} + override addCallSucceeded() {} + override addCallFailed() {} +} + +export interface ChannelzChildren { + channels: OrderedMap; + subchannels: OrderedMap; + sockets: OrderedMap; +} + +export interface ChannelInfo { + target: string; + state: ConnectivityState; + trace: ChannelzTrace | ChannelzTraceStub; + callTracker: ChannelzCallTracker | ChannelzCallTrackerStub; + children: ChannelzChildren; +} + +export type SubchannelInfo = ChannelInfo; + +export interface ServerInfo { + trace: ChannelzTrace; + callTracker: ChannelzCallTracker; + listenerChildren: ChannelzChildren; + sessionChildren: ChannelzChildren; +} + +export interface TlsInfo { + cipherSuiteStandardName: string | null; + cipherSuiteOtherName: string | null; + localCertificate: Buffer | null; + remoteCertificate: Buffer | null; +} + +export interface SocketInfo { + localAddress: SubchannelAddress | null; + remoteAddress: SubchannelAddress | null; + security: TlsInfo | null; + remoteName: string | null; + streamsStarted: number; + streamsSucceeded: number; + streamsFailed: number; + messagesSent: number; + messagesReceived: number; + keepAlivesSent: number; + lastLocalStreamCreatedTimestamp: Date | null; + lastRemoteStreamCreatedTimestamp: Date | null; + lastMessageSentTimestamp: Date | null; + lastMessageReceivedTimestamp: Date | null; + localFlowControlWindow: number | null; + remoteFlowControlWindow: number | null; +} + +interface ChannelEntry { + ref: ChannelRef; + getInfo(): ChannelInfo; +} + +interface SubchannelEntry { + ref: SubchannelRef; + getInfo(): SubchannelInfo; +} + +interface ServerEntry { + ref: ServerRef; + getInfo(): ServerInfo; +} + +interface SocketEntry { + ref: SocketRef; + getInfo(): SocketInfo; +} + +export const enum EntityTypes { + channel = 'channel', + subchannel = 'subchannel', + server = 'server', + socket = 'socket', +} + +type EntryOrderedMap = OrderedMap any }>; + +const entityMaps = { + [EntityTypes.channel]: new OrderedMap(), + [EntityTypes.subchannel]: new OrderedMap(), + [EntityTypes.server]: new OrderedMap(), + [EntityTypes.socket]: new OrderedMap(), +} as const; + +export type RefByType = T extends EntityTypes.channel + ? ChannelRef + : T extends EntityTypes.server + ? ServerRef + : T extends EntityTypes.socket + ? SocketRef + : T extends EntityTypes.subchannel + ? SubchannelRef + : never; + +export type EntryByType = T extends EntityTypes.channel + ? ChannelEntry + : T extends EntityTypes.server + ? ServerEntry + : T extends EntityTypes.socket + ? SocketEntry + : T extends EntityTypes.subchannel + ? SubchannelEntry + : never; + +export type InfoByType = T extends EntityTypes.channel + ? ChannelInfo + : T extends EntityTypes.subchannel + ? SubchannelInfo + : T extends EntityTypes.server + ? ServerInfo + : T extends EntityTypes.socket + ? SocketInfo + : never; + +const generateRegisterFn = (kind: R) => { + let nextId = 1; + function getNextId(): number { + return nextId++; + } + + const entityMap: EntryOrderedMap = entityMaps[kind]; + + return ( + name: string, + getInfo: () => InfoByType, + channelzEnabled: boolean + ): RefByType => { + const id = getNextId(); + const ref = { id, name, kind } as RefByType; + if (channelzEnabled) { + entityMap.setElement(id, { ref, getInfo }); + } + return ref; + }; +}; + +export const registerChannelzChannel = generateRegisterFn(EntityTypes.channel); +export const registerChannelzSubchannel = generateRegisterFn( + EntityTypes.subchannel +); +export const registerChannelzServer = generateRegisterFn(EntityTypes.server); +export const registerChannelzSocket = generateRegisterFn(EntityTypes.socket); + +export function unregisterChannelzRef( + ref: ChannelRef | SubchannelRef | ServerRef | SocketRef +) { + entityMaps[ref.kind].eraseElementByKey(ref.id); +} + +/** + * Parse a single section of an IPv6 address as two bytes + * @param addressSection A hexadecimal string of length up to 4 + * @returns The pair of bytes representing this address section + */ +function parseIPv6Section(addressSection: string): [number, number] { + const numberValue = Number.parseInt(addressSection, 16); + return [(numberValue / 256) | 0, numberValue % 256]; +} + +/** + * Parse a chunk of an IPv6 address string to some number of bytes + * @param addressChunk Some number of segments of up to 4 hexadecimal + * characters each, joined by colons. + * @returns The list of bytes representing this address chunk + */ +function parseIPv6Chunk(addressChunk: string): number[] { + if (addressChunk === '') { + return []; + } + const bytePairs = addressChunk + .split(':') + .map(section => parseIPv6Section(section)); + const result: number[] = []; + return result.concat(...bytePairs); +} + +function isIPv6MappedIPv4(ipAddress: string) { + return isIPv6(ipAddress) && ipAddress.toLowerCase().startsWith('::ffff:') && isIPv4(ipAddress.substring(7)); +} + +/** + * Prerequisite: isIPv4(ipAddress) + * @param ipAddress + * @returns + */ +function ipv4AddressStringToBuffer(ipAddress: string): Buffer { + return Buffer.from( + Uint8Array.from( + ipAddress.split('.').map(segment => Number.parseInt(segment)) + ) + ); +} + +/** + * Converts an IPv4 or IPv6 address from string representation to binary + * representation + * @param ipAddress an IP address in standard IPv4 or IPv6 text format + * @returns + */ +function ipAddressStringToBuffer(ipAddress: string): Buffer | null { + if (isIPv4(ipAddress)) { + return ipv4AddressStringToBuffer(ipAddress); + } else if (isIPv6MappedIPv4(ipAddress)) { + return ipv4AddressStringToBuffer(ipAddress.substring(7)); + } else if (isIPv6(ipAddress)) { + let leftSection: string; + let rightSection: string; + const doubleColonIndex = ipAddress.indexOf('::'); + if (doubleColonIndex === -1) { + leftSection = ipAddress; + rightSection = ''; + } else { + leftSection = ipAddress.substring(0, doubleColonIndex); + rightSection = ipAddress.substring(doubleColonIndex + 2); + } + const leftBuffer = Buffer.from(parseIPv6Chunk(leftSection)); + const rightBuffer = Buffer.from(parseIPv6Chunk(rightSection)); + const middleBuffer = Buffer.alloc( + 16 - leftBuffer.length - rightBuffer.length, + 0 + ); + return Buffer.concat([leftBuffer, middleBuffer, rightBuffer]); + } else { + return null; + } +} + +function connectivityStateToMessage( + state: ConnectivityState +): ChannelConnectivityState__Output { + switch (state) { + case ConnectivityState.CONNECTING: + return { + state: 'CONNECTING', + }; + case ConnectivityState.IDLE: + return { + state: 'IDLE', + }; + case ConnectivityState.READY: + return { + state: 'READY', + }; + case ConnectivityState.SHUTDOWN: + return { + state: 'SHUTDOWN', + }; + case ConnectivityState.TRANSIENT_FAILURE: + return { + state: 'TRANSIENT_FAILURE', + }; + default: + return { + state: 'UNKNOWN', + }; + } +} + +function dateToProtoTimestamp(date?: Date | null): Timestamp | null { + if (!date) { + return null; + } + const millisSinceEpoch = date.getTime(); + return { + seconds: (millisSinceEpoch / 1000) | 0, + nanos: (millisSinceEpoch % 1000) * 1_000_000, + }; +} + +function getChannelMessage(channelEntry: ChannelEntry): ChannelMessage { + const resolvedInfo = channelEntry.getInfo(); + const channelRef: ChannelRefMessage[] = []; + const subchannelRef: SubchannelRefMessage[] = []; + + resolvedInfo.children.channels.forEach(el => { + channelRef.push(channelRefToMessage(el[1].ref)); + }); + + resolvedInfo.children.subchannels.forEach(el => { + subchannelRef.push(subchannelRefToMessage(el[1].ref)); + }); + + return { + ref: channelRefToMessage(channelEntry.ref), + data: { + target: resolvedInfo.target, + state: connectivityStateToMessage(resolvedInfo.state), + calls_started: resolvedInfo.callTracker.callsStarted, + calls_succeeded: resolvedInfo.callTracker.callsSucceeded, + calls_failed: resolvedInfo.callTracker.callsFailed, + last_call_started_timestamp: dateToProtoTimestamp( + resolvedInfo.callTracker.lastCallStartedTimestamp + ), + trace: resolvedInfo.trace.getTraceMessage(), + }, + channel_ref: channelRef, + subchannel_ref: subchannelRef, + }; +} + +function GetChannel( + call: ServerUnaryCall, + callback: sendUnaryData +): void { + const channelId = parseInt(call.request.channel_id, 10); + const channelEntry = + entityMaps[EntityTypes.channel].getElementByKey(channelId); + if (channelEntry === undefined) { + callback({ + code: Status.NOT_FOUND, + details: 'No channel data found for id ' + channelId, + }); + return; + } + callback(null, { channel: getChannelMessage(channelEntry) }); +} + +function GetTopChannels( + call: ServerUnaryCall, + callback: sendUnaryData +): void { + const maxResults = + parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; + const resultList: ChannelMessage[] = []; + const startId = parseInt(call.request.start_channel_id, 10); + const channelEntries = entityMaps[EntityTypes.channel]; + + let i: OrderedMapIterator; + for ( + i = channelEntries.lowerBound(startId); + !i.equals(channelEntries.end()) && resultList.length < maxResults; + i = i.next() + ) { + resultList.push(getChannelMessage(i.pointer[1])); + } + + callback(null, { + channel: resultList, + end: i.equals(channelEntries.end()), + }); +} + +function getServerMessage(serverEntry: ServerEntry): ServerMessage { + const resolvedInfo = serverEntry.getInfo(); + const listenSocket: SocketRefMessage[] = []; + + resolvedInfo.listenerChildren.sockets.forEach(el => { + listenSocket.push(socketRefToMessage(el[1].ref)); + }); + + return { + ref: serverRefToMessage(serverEntry.ref), + data: { + calls_started: resolvedInfo.callTracker.callsStarted, + calls_succeeded: resolvedInfo.callTracker.callsSucceeded, + calls_failed: resolvedInfo.callTracker.callsFailed, + last_call_started_timestamp: dateToProtoTimestamp( + resolvedInfo.callTracker.lastCallStartedTimestamp + ), + trace: resolvedInfo.trace.getTraceMessage(), + }, + listen_socket: listenSocket, + }; +} + +function GetServer( + call: ServerUnaryCall, + callback: sendUnaryData +): void { + const serverId = parseInt(call.request.server_id, 10); + const serverEntries = entityMaps[EntityTypes.server]; + const serverEntry = serverEntries.getElementByKey(serverId); + if (serverEntry === undefined) { + callback({ + code: Status.NOT_FOUND, + details: 'No server data found for id ' + serverId, + }); + return; + } + callback(null, { server: getServerMessage(serverEntry) }); +} + +function GetServers( + call: ServerUnaryCall, + callback: sendUnaryData +): void { + const maxResults = + parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; + const startId = parseInt(call.request.start_server_id, 10); + const serverEntries = entityMaps[EntityTypes.server]; + const resultList: ServerMessage[] = []; + + let i: OrderedMapIterator; + for ( + i = serverEntries.lowerBound(startId); + !i.equals(serverEntries.end()) && resultList.length < maxResults; + i = i.next() + ) { + resultList.push(getServerMessage(i.pointer[1])); + } + + callback(null, { + server: resultList, + end: i.equals(serverEntries.end()), + }); +} + +function GetSubchannel( + call: ServerUnaryCall, + callback: sendUnaryData +): void { + const subchannelId = parseInt(call.request.subchannel_id, 10); + const subchannelEntry = + entityMaps[EntityTypes.subchannel].getElementByKey(subchannelId); + if (subchannelEntry === undefined) { + callback({ + code: Status.NOT_FOUND, + details: 'No subchannel data found for id ' + subchannelId, + }); + return; + } + const resolvedInfo = subchannelEntry.getInfo(); + const listenSocket: SocketRefMessage[] = []; + + resolvedInfo.children.sockets.forEach(el => { + listenSocket.push(socketRefToMessage(el[1].ref)); + }); + + const subchannelMessage: SubchannelMessage = { + ref: subchannelRefToMessage(subchannelEntry.ref), + data: { + target: resolvedInfo.target, + state: connectivityStateToMessage(resolvedInfo.state), + calls_started: resolvedInfo.callTracker.callsStarted, + calls_succeeded: resolvedInfo.callTracker.callsSucceeded, + calls_failed: resolvedInfo.callTracker.callsFailed, + last_call_started_timestamp: dateToProtoTimestamp( + resolvedInfo.callTracker.lastCallStartedTimestamp + ), + trace: resolvedInfo.trace.getTraceMessage(), + }, + socket_ref: listenSocket, + }; + callback(null, { subchannel: subchannelMessage }); +} + +function subchannelAddressToAddressMessage( + subchannelAddress: SubchannelAddress +): Address { + if (isTcpSubchannelAddress(subchannelAddress)) { + return { + address: 'tcpip_address', + tcpip_address: { + ip_address: + ipAddressStringToBuffer(subchannelAddress.host) ?? undefined, + port: subchannelAddress.port, + }, + }; + } else { + return { + address: 'uds_address', + uds_address: { + filename: subchannelAddress.path, + }, + }; + } +} + +function GetSocket( + call: ServerUnaryCall, + callback: sendUnaryData +): void { + const socketId = parseInt(call.request.socket_id, 10); + const socketEntry = entityMaps[EntityTypes.socket].getElementByKey(socketId); + if (socketEntry === undefined) { + callback({ + code: Status.NOT_FOUND, + details: 'No socket data found for id ' + socketId, + }); + return; + } + const resolvedInfo = socketEntry.getInfo(); + const securityMessage: Security | null = resolvedInfo.security + ? { + model: 'tls', + tls: { + cipher_suite: resolvedInfo.security.cipherSuiteStandardName + ? 'standard_name' + : 'other_name', + standard_name: + resolvedInfo.security.cipherSuiteStandardName ?? undefined, + other_name: resolvedInfo.security.cipherSuiteOtherName ?? undefined, + local_certificate: + resolvedInfo.security.localCertificate ?? undefined, + remote_certificate: + resolvedInfo.security.remoteCertificate ?? undefined, + }, + } + : null; + const socketMessage: SocketMessage = { + ref: socketRefToMessage(socketEntry.ref), + local: resolvedInfo.localAddress + ? subchannelAddressToAddressMessage(resolvedInfo.localAddress) + : null, + remote: resolvedInfo.remoteAddress + ? subchannelAddressToAddressMessage(resolvedInfo.remoteAddress) + : null, + remote_name: resolvedInfo.remoteName ?? undefined, + security: securityMessage, + data: { + keep_alives_sent: resolvedInfo.keepAlivesSent, + streams_started: resolvedInfo.streamsStarted, + streams_succeeded: resolvedInfo.streamsSucceeded, + streams_failed: resolvedInfo.streamsFailed, + last_local_stream_created_timestamp: dateToProtoTimestamp( + resolvedInfo.lastLocalStreamCreatedTimestamp + ), + last_remote_stream_created_timestamp: dateToProtoTimestamp( + resolvedInfo.lastRemoteStreamCreatedTimestamp + ), + messages_received: resolvedInfo.messagesReceived, + messages_sent: resolvedInfo.messagesSent, + last_message_received_timestamp: dateToProtoTimestamp( + resolvedInfo.lastMessageReceivedTimestamp + ), + last_message_sent_timestamp: dateToProtoTimestamp( + resolvedInfo.lastMessageSentTimestamp + ), + local_flow_control_window: resolvedInfo.localFlowControlWindow + ? { value: resolvedInfo.localFlowControlWindow } + : null, + remote_flow_control_window: resolvedInfo.remoteFlowControlWindow + ? { value: resolvedInfo.remoteFlowControlWindow } + : null, + }, + }; + callback(null, { socket: socketMessage }); +} + +function GetServerSockets( + call: ServerUnaryCall< + GetServerSocketsRequest__Output, + GetServerSocketsResponse + >, + callback: sendUnaryData +): void { + const serverId = parseInt(call.request.server_id, 10); + const serverEntry = entityMaps[EntityTypes.server].getElementByKey(serverId); + + if (serverEntry === undefined) { + callback({ + code: Status.NOT_FOUND, + details: 'No server data found for id ' + serverId, + }); + return; + } + + const startId = parseInt(call.request.start_socket_id, 10); + const maxResults = + parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; + const resolvedInfo = serverEntry.getInfo(); + // If we wanted to include listener sockets in the result, this line would + // instead say + // const allSockets = resolvedInfo.listenerChildren.sockets.concat(resolvedInfo.sessionChildren.sockets).sort((ref1, ref2) => ref1.id - ref2.id); + const allSockets = resolvedInfo.sessionChildren.sockets; + const resultList: SocketRefMessage[] = []; + + let i: OrderedMapIterator; + for ( + i = allSockets.lowerBound(startId); + !i.equals(allSockets.end()) && resultList.length < maxResults; + i = i.next() + ) { + resultList.push(socketRefToMessage(i.pointer[1].ref)); + } + + callback(null, { + socket_ref: resultList, + end: i.equals(allSockets.end()), + }); +} + +export function getChannelzHandlers(): ChannelzHandlers { + return { + GetChannel, + GetTopChannels, + GetServer, + GetServers, + GetSubchannel, + GetSocket, + GetServerSockets, + }; +} + +let loadedChannelzDefinition: ChannelzDefinition | null = null; + +export function getChannelzServiceDefinition(): ChannelzDefinition { + if (loadedChannelzDefinition) { + return loadedChannelzDefinition; + } + /* The purpose of this complexity is to avoid loading @grpc/proto-loader at + * runtime for users who will not use/enable channelz. */ + const loaderLoadSync = require('@grpc/proto-loader') + .loadSync as typeof loadSync; + const loadedProto = loaderLoadSync('channelz.proto', { + keepCase: true, + longs: String, + enums: String, + defaults: true, + oneofs: true, + includeDirs: [`${__dirname}/../../proto`], + }); + const channelzGrpcObject = loadPackageDefinition( + loadedProto + ) as unknown as ChannelzProtoGrpcType; + loadedChannelzDefinition = + channelzGrpcObject.grpc.channelz.v1.Channelz.service; + return loadedChannelzDefinition; +} + +export function setup() { + registerAdminService(getChannelzServiceDefinition, getChannelzHandlers); +} diff --git a/node_modules/@grpc/grpc-js/src/client-interceptors.ts b/node_modules/@grpc/grpc-js/src/client-interceptors.ts new file mode 100644 index 0000000..90c850e --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/client-interceptors.ts @@ -0,0 +1,585 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { Metadata } from './metadata'; +import { + StatusObject, + Listener, + MetadataListener, + MessageListener, + StatusListener, + FullListener, + InterceptingListener, + InterceptingListenerImpl, + isInterceptingListener, + MessageContext, + Call, +} from './call-interface'; +import { Status } from './constants'; +import { Channel } from './channel'; +import { CallOptions } from './client'; +import { ClientMethodDefinition } from './make-client'; +import { getErrorMessage } from './error'; +import { AuthContext } from './auth-context'; + +/** + * Error class associated with passing both interceptors and interceptor + * providers to a client constructor or as call options. + */ +export class InterceptorConfigurationError extends Error { + constructor(message: string) { + super(message); + this.name = 'InterceptorConfigurationError'; + Error.captureStackTrace(this, InterceptorConfigurationError); + } +} + +export interface MetadataRequester { + ( + metadata: Metadata, + listener: InterceptingListener, + next: ( + metadata: Metadata, + listener: InterceptingListener | Listener + ) => void + ): void; +} + +export interface MessageRequester { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (message: any, next: (message: any) => void): void; +} + +export interface CloseRequester { + (next: () => void): void; +} + +export interface CancelRequester { + (next: () => void): void; +} + +/** + * An object with methods for intercepting and modifying outgoing call operations. + */ +export interface FullRequester { + start: MetadataRequester; + sendMessage: MessageRequester; + halfClose: CloseRequester; + cancel: CancelRequester; +} + +export type Requester = Partial; + +export class ListenerBuilder { + private metadata: MetadataListener | undefined = undefined; + private message: MessageListener | undefined = undefined; + private status: StatusListener | undefined = undefined; + + withOnReceiveMetadata(onReceiveMetadata: MetadataListener): this { + this.metadata = onReceiveMetadata; + return this; + } + + withOnReceiveMessage(onReceiveMessage: MessageListener): this { + this.message = onReceiveMessage; + return this; + } + + withOnReceiveStatus(onReceiveStatus: StatusListener): this { + this.status = onReceiveStatus; + return this; + } + + build(): Listener { + return { + onReceiveMetadata: this.metadata, + onReceiveMessage: this.message, + onReceiveStatus: this.status, + }; + } +} + +export class RequesterBuilder { + private start: MetadataRequester | undefined = undefined; + private message: MessageRequester | undefined = undefined; + private halfClose: CloseRequester | undefined = undefined; + private cancel: CancelRequester | undefined = undefined; + + withStart(start: MetadataRequester): this { + this.start = start; + return this; + } + + withSendMessage(sendMessage: MessageRequester): this { + this.message = sendMessage; + return this; + } + + withHalfClose(halfClose: CloseRequester): this { + this.halfClose = halfClose; + return this; + } + + withCancel(cancel: CancelRequester): this { + this.cancel = cancel; + return this; + } + + build(): Requester { + return { + start: this.start, + sendMessage: this.message, + halfClose: this.halfClose, + cancel: this.cancel, + }; + } +} + +/** + * A Listener with a default pass-through implementation of each method. Used + * for filling out Listeners with some methods omitted. + */ +const defaultListener: FullListener = { + onReceiveMetadata: (metadata, next) => { + next(metadata); + }, + onReceiveMessage: (message, next) => { + next(message); + }, + onReceiveStatus: (status, next) => { + next(status); + }, +}; + +/** + * A Requester with a default pass-through implementation of each method. Used + * for filling out Requesters with some methods omitted. + */ +const defaultRequester: FullRequester = { + start: (metadata, listener, next) => { + next(metadata, listener); + }, + sendMessage: (message, next) => { + next(message); + }, + halfClose: next => { + next(); + }, + cancel: next => { + next(); + }, +}; + +export interface InterceptorOptions extends CallOptions { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + method_definition: ClientMethodDefinition; +} + +export interface InterceptingCallInterface { + cancelWithStatus(status: Status, details: string): void; + getPeer(): string; + start(metadata: Metadata, listener?: Partial): void; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessageWithContext(context: MessageContext, message: any): void; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessage(message: any): void; + startRead(): void; + halfClose(): void; + getAuthContext(): AuthContext | null; +} + +export class InterceptingCall implements InterceptingCallInterface { + /** + * The requester that this InterceptingCall uses to modify outgoing operations + */ + private requester: FullRequester; + /** + * Indicates that metadata has been passed to the requester's start + * method but it has not been passed to the corresponding next callback + */ + private processingMetadata = false; + /** + * Message context for a pending message that is waiting for + */ + private pendingMessageContext: MessageContext | null = null; + private pendingMessage: any; + /** + * Indicates that a message has been passed to the requester's sendMessage + * method but it has not been passed to the corresponding next callback + */ + private processingMessage = false; + /** + * Indicates that a status was received but could not be propagated because + * a message was still being processed. + */ + private pendingHalfClose = false; + constructor( + private nextCall: InterceptingCallInterface, + requester?: Requester + ) { + if (requester) { + this.requester = { + start: requester.start ?? defaultRequester.start, + sendMessage: requester.sendMessage ?? defaultRequester.sendMessage, + halfClose: requester.halfClose ?? defaultRequester.halfClose, + cancel: requester.cancel ?? defaultRequester.cancel, + }; + } else { + this.requester = defaultRequester; + } + } + + cancelWithStatus(status: Status, details: string) { + this.requester.cancel(() => { + this.nextCall.cancelWithStatus(status, details); + }); + } + + getPeer() { + return this.nextCall.getPeer(); + } + + private processPendingMessage() { + if (this.pendingMessageContext) { + this.nextCall.sendMessageWithContext( + this.pendingMessageContext, + this.pendingMessage + ); + this.pendingMessageContext = null; + this.pendingMessage = null; + } + } + + private processPendingHalfClose() { + if (this.pendingHalfClose) { + this.nextCall.halfClose(); + } + } + + start( + metadata: Metadata, + interceptingListener?: Partial + ): void { + const fullInterceptingListener: InterceptingListener = { + onReceiveMetadata: + interceptingListener?.onReceiveMetadata?.bind(interceptingListener) ?? + (metadata => {}), + onReceiveMessage: + interceptingListener?.onReceiveMessage?.bind(interceptingListener) ?? + (message => {}), + onReceiveStatus: + interceptingListener?.onReceiveStatus?.bind(interceptingListener) ?? + (status => {}), + }; + this.processingMetadata = true; + this.requester.start(metadata, fullInterceptingListener, (md, listener) => { + this.processingMetadata = false; + let finalInterceptingListener: InterceptingListener; + if (isInterceptingListener(listener)) { + finalInterceptingListener = listener; + } else { + const fullListener: FullListener = { + onReceiveMetadata: + listener.onReceiveMetadata ?? defaultListener.onReceiveMetadata, + onReceiveMessage: + listener.onReceiveMessage ?? defaultListener.onReceiveMessage, + onReceiveStatus: + listener.onReceiveStatus ?? defaultListener.onReceiveStatus, + }; + finalInterceptingListener = new InterceptingListenerImpl( + fullListener, + fullInterceptingListener + ); + } + this.nextCall.start(md, finalInterceptingListener); + this.processPendingMessage(); + this.processPendingHalfClose(); + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessageWithContext(context: MessageContext, message: any): void { + this.processingMessage = true; + this.requester.sendMessage(message, finalMessage => { + this.processingMessage = false; + if (this.processingMetadata) { + this.pendingMessageContext = context; + this.pendingMessage = message; + } else { + this.nextCall.sendMessageWithContext(context, finalMessage); + this.processPendingHalfClose(); + } + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessage(message: any): void { + this.sendMessageWithContext({}, message); + } + startRead(): void { + this.nextCall.startRead(); + } + halfClose(): void { + this.requester.halfClose(() => { + if (this.processingMetadata || this.processingMessage) { + this.pendingHalfClose = true; + } else { + this.nextCall.halfClose(); + } + }); + } + getAuthContext(): AuthContext | null { + return this.nextCall.getAuthContext(); + } +} + +function getCall(channel: Channel, path: string, options: CallOptions): Call { + const deadline = options.deadline ?? Infinity; + const host = options.host; + const parent = options.parent ?? null; + const propagateFlags = options.propagate_flags; + const credentials = options.credentials; + const call = channel.createCall(path, deadline, host, parent, propagateFlags); + if (credentials) { + call.setCredentials(credentials); + } + return call; +} + +/** + * InterceptingCall implementation that directly owns the underlying Call + * object and handles serialization and deseraizliation. + */ +class BaseInterceptingCall implements InterceptingCallInterface { + constructor( + protected call: Call, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + protected methodDefinition: ClientMethodDefinition + ) {} + cancelWithStatus(status: Status, details: string): void { + this.call.cancelWithStatus(status, details); + } + getPeer(): string { + return this.call.getPeer(); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessageWithContext(context: MessageContext, message: any): void { + let serialized: Buffer; + try { + serialized = this.methodDefinition.requestSerialize(message); + } catch (e) { + this.call.cancelWithStatus( + Status.INTERNAL, + `Request message serialization failure: ${getErrorMessage(e)}` + ); + return; + } + this.call.sendMessageWithContext(context, serialized); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessage(message: any) { + this.sendMessageWithContext({}, message); + } + start( + metadata: Metadata, + interceptingListener?: Partial + ): void { + let readError: StatusObject | null = null; + this.call.start(metadata, { + onReceiveMetadata: metadata => { + interceptingListener?.onReceiveMetadata?.(metadata); + }, + onReceiveMessage: message => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let deserialized: any; + try { + deserialized = this.methodDefinition.responseDeserialize(message); + } catch (e) { + readError = { + code: Status.INTERNAL, + details: `Response message parsing error: ${getErrorMessage(e)}`, + metadata: new Metadata(), + }; + this.call.cancelWithStatus(readError.code, readError.details); + return; + } + interceptingListener?.onReceiveMessage?.(deserialized); + }, + onReceiveStatus: status => { + if (readError) { + interceptingListener?.onReceiveStatus?.(readError); + } else { + interceptingListener?.onReceiveStatus?.(status); + } + }, + }); + } + startRead() { + this.call.startRead(); + } + halfClose(): void { + this.call.halfClose(); + } + getAuthContext(): AuthContext | null { + return this.call.getAuthContext(); + } +} + +/** + * BaseInterceptingCall with special-cased behavior for methods with unary + * responses. + */ +class BaseUnaryInterceptingCall + extends BaseInterceptingCall + implements InterceptingCallInterface +{ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + constructor(call: Call, methodDefinition: ClientMethodDefinition) { + super(call, methodDefinition); + } + start(metadata: Metadata, listener?: Partial): void { + let receivedMessage = false; + const wrapperListener: InterceptingListener = { + onReceiveMetadata: + listener?.onReceiveMetadata?.bind(listener) ?? (metadata => {}), + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage: (message: any) => { + receivedMessage = true; + listener?.onReceiveMessage?.(message); + }, + onReceiveStatus: (status: StatusObject) => { + if (!receivedMessage) { + listener?.onReceiveMessage?.(null); + } + listener?.onReceiveStatus?.(status); + }, + }; + super.start(metadata, wrapperListener); + this.call.startRead(); + } +} + +/** + * BaseInterceptingCall with special-cased behavior for methods with streaming + * responses. + */ +class BaseStreamingInterceptingCall + extends BaseInterceptingCall + implements InterceptingCallInterface {} + +function getBottomInterceptingCall( + channel: Channel, + options: InterceptorOptions, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + methodDefinition: ClientMethodDefinition +) { + const call = getCall(channel, methodDefinition.path, options); + if (methodDefinition.responseStream) { + return new BaseStreamingInterceptingCall(call, methodDefinition); + } else { + return new BaseUnaryInterceptingCall(call, methodDefinition); + } +} + +export interface NextCall { + (options: InterceptorOptions): InterceptingCallInterface; +} + +export interface Interceptor { + (options: InterceptorOptions, nextCall: NextCall): InterceptingCall; +} + +export interface InterceptorProvider { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (methodDefinition: ClientMethodDefinition): Interceptor; +} + +export interface InterceptorArguments { + clientInterceptors: Interceptor[]; + clientInterceptorProviders: InterceptorProvider[]; + callInterceptors: Interceptor[]; + callInterceptorProviders: InterceptorProvider[]; +} + +export function getInterceptingCall( + interceptorArgs: InterceptorArguments, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + methodDefinition: ClientMethodDefinition, + options: CallOptions, + channel: Channel +): InterceptingCallInterface { + if ( + interceptorArgs.clientInterceptors.length > 0 && + interceptorArgs.clientInterceptorProviders.length > 0 + ) { + throw new InterceptorConfigurationError( + 'Both interceptors and interceptor_providers were passed as options ' + + 'to the client constructor. Only one of these is allowed.' + ); + } + if ( + interceptorArgs.callInterceptors.length > 0 && + interceptorArgs.callInterceptorProviders.length > 0 + ) { + throw new InterceptorConfigurationError( + 'Both interceptors and interceptor_providers were passed as call ' + + 'options. Only one of these is allowed.' + ); + } + let interceptors: Interceptor[] = []; + // Interceptors passed to the call override interceptors passed to the client constructor + if ( + interceptorArgs.callInterceptors.length > 0 || + interceptorArgs.callInterceptorProviders.length > 0 + ) { + interceptors = ([] as Interceptor[]) + .concat( + interceptorArgs.callInterceptors, + interceptorArgs.callInterceptorProviders.map(provider => + provider(methodDefinition) + ) + ) + .filter(interceptor => interceptor); + // Filter out falsy values when providers return nothing + } else { + interceptors = ([] as Interceptor[]) + .concat( + interceptorArgs.clientInterceptors, + interceptorArgs.clientInterceptorProviders.map(provider => + provider(methodDefinition) + ) + ) + .filter(interceptor => interceptor); + // Filter out falsy values when providers return nothing + } + const interceptorOptions = Object.assign({}, options, { + method_definition: methodDefinition, + }); + /* For each interceptor in the list, the nextCall function passed to it is + * based on the next interceptor in the list, using a nextCall function + * constructed with the following interceptor in the list, and so on. The + * initialValue, which is effectively at the end of the list, is a nextCall + * function that invokes getBottomInterceptingCall, the result of which + * handles (de)serialization and also gets the underlying call from the + * channel. */ + const getCall: NextCall = interceptors.reduceRight( + (nextCall: NextCall, nextInterceptor: Interceptor) => { + return currentOptions => nextInterceptor(currentOptions, nextCall); + }, + (finalOptions: InterceptorOptions) => + getBottomInterceptingCall(channel, finalOptions, methodDefinition) + ); + return getCall(interceptorOptions); +} diff --git a/node_modules/@grpc/grpc-js/src/client.ts b/node_modules/@grpc/grpc-js/src/client.ts new file mode 100644 index 0000000..dc75ac4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/client.ts @@ -0,0 +1,716 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { + ClientDuplexStream, + ClientDuplexStreamImpl, + ClientReadableStream, + ClientReadableStreamImpl, + ClientUnaryCall, + ClientUnaryCallImpl, + ClientWritableStream, + ClientWritableStreamImpl, + ServiceError, + callErrorFromStatus, + SurfaceCall, +} from './call'; +import { CallCredentials } from './call-credentials'; +import { StatusObject } from './call-interface'; +import { Channel, ChannelImplementation } from './channel'; +import { ConnectivityState } from './connectivity-state'; +import { ChannelCredentials } from './channel-credentials'; +import { ChannelOptions } from './channel-options'; +import { Status } from './constants'; +import { Metadata } from './metadata'; +import { ClientMethodDefinition } from './make-client'; +import { + getInterceptingCall, + Interceptor, + InterceptorProvider, + InterceptorArguments, + InterceptingCallInterface, +} from './client-interceptors'; +import { + ServerUnaryCall, + ServerReadableStream, + ServerWritableStream, + ServerDuplexStream, +} from './server-call'; +import { Deadline } from './deadline'; + +const CHANNEL_SYMBOL = Symbol(); +const INTERCEPTOR_SYMBOL = Symbol(); +const INTERCEPTOR_PROVIDER_SYMBOL = Symbol(); +const CALL_INVOCATION_TRANSFORMER_SYMBOL = Symbol(); + +function isFunction( + arg: Metadata | CallOptions | UnaryCallback | undefined +): arg is UnaryCallback { + return typeof arg === 'function'; +} + +export interface UnaryCallback { + (err: ServiceError | null, value?: ResponseType): void; +} + +/* eslint-disable @typescript-eslint/no-explicit-any */ +export interface CallOptions { + deadline?: Deadline; + host?: string; + parent?: + | ServerUnaryCall + | ServerReadableStream + | ServerWritableStream + | ServerDuplexStream; + propagate_flags?: number; + credentials?: CallCredentials; + interceptors?: Interceptor[]; + interceptor_providers?: InterceptorProvider[]; +} +/* eslint-enable @typescript-eslint/no-explicit-any */ + +export interface CallProperties { + argument?: RequestType; + metadata: Metadata; + call: SurfaceCall; + channel: Channel; + methodDefinition: ClientMethodDefinition; + callOptions: CallOptions; + callback?: UnaryCallback; +} + +export interface CallInvocationTransformer { + (callProperties: CallProperties): CallProperties; // eslint-disable-line @typescript-eslint/no-explicit-any +} + +export type ClientOptions = Partial & { + channelOverride?: Channel; + channelFactoryOverride?: ( + address: string, + credentials: ChannelCredentials, + options: ClientOptions + ) => Channel; + interceptors?: Interceptor[]; + interceptor_providers?: InterceptorProvider[]; + callInvocationTransformer?: CallInvocationTransformer; +}; + +function getErrorStackString(error: Error): string { + return error.stack?.split('\n').slice(1).join('\n') || 'no stack trace available'; +} + +/** + * A generic gRPC client. Primarily useful as a base class for all generated + * clients. + */ +export class Client { + private readonly [CHANNEL_SYMBOL]: Channel; + private readonly [INTERCEPTOR_SYMBOL]: Interceptor[]; + private readonly [INTERCEPTOR_PROVIDER_SYMBOL]: InterceptorProvider[]; + private readonly [CALL_INVOCATION_TRANSFORMER_SYMBOL]?: CallInvocationTransformer; + constructor( + address: string, + credentials: ChannelCredentials, + options: ClientOptions = {} + ) { + options = Object.assign({}, options); + this[INTERCEPTOR_SYMBOL] = options.interceptors ?? []; + delete options.interceptors; + this[INTERCEPTOR_PROVIDER_SYMBOL] = options.interceptor_providers ?? []; + delete options.interceptor_providers; + if ( + this[INTERCEPTOR_SYMBOL].length > 0 && + this[INTERCEPTOR_PROVIDER_SYMBOL].length > 0 + ) { + throw new Error( + 'Both interceptors and interceptor_providers were passed as options ' + + 'to the client constructor. Only one of these is allowed.' + ); + } + this[CALL_INVOCATION_TRANSFORMER_SYMBOL] = + options.callInvocationTransformer; + delete options.callInvocationTransformer; + if (options.channelOverride) { + this[CHANNEL_SYMBOL] = options.channelOverride; + } else if (options.channelFactoryOverride) { + const channelFactoryOverride = options.channelFactoryOverride; + delete options.channelFactoryOverride; + this[CHANNEL_SYMBOL] = channelFactoryOverride( + address, + credentials, + options + ); + } else { + this[CHANNEL_SYMBOL] = new ChannelImplementation( + address, + credentials, + options + ); + } + } + + close(): void { + this[CHANNEL_SYMBOL].close(); + } + + getChannel(): Channel { + return this[CHANNEL_SYMBOL]; + } + + waitForReady(deadline: Deadline, callback: (error?: Error) => void): void { + const checkState = (err?: Error) => { + if (err) { + callback(new Error('Failed to connect before the deadline')); + return; + } + let newState; + try { + newState = this[CHANNEL_SYMBOL].getConnectivityState(true); + } catch (e) { + callback(new Error('The channel has been closed')); + return; + } + if (newState === ConnectivityState.READY) { + callback(); + } else { + try { + this[CHANNEL_SYMBOL].watchConnectivityState( + newState, + deadline, + checkState + ); + } catch (e) { + callback(new Error('The channel has been closed')); + } + } + }; + setImmediate(checkState); + } + + private checkOptionalUnaryResponseArguments( + arg1: Metadata | CallOptions | UnaryCallback, + arg2?: CallOptions | UnaryCallback, + arg3?: UnaryCallback + ): { + metadata: Metadata; + options: CallOptions; + callback: UnaryCallback; + } { + if (isFunction(arg1)) { + return { metadata: new Metadata(), options: {}, callback: arg1 }; + } else if (isFunction(arg2)) { + if (arg1 instanceof Metadata) { + return { metadata: arg1, options: {}, callback: arg2 }; + } else { + return { metadata: new Metadata(), options: arg1, callback: arg2 }; + } + } else { + if ( + !( + arg1 instanceof Metadata && + arg2 instanceof Object && + isFunction(arg3) + ) + ) { + throw new Error('Incorrect arguments passed'); + } + return { metadata: arg1, options: arg2, callback: arg3 }; + } + } + + makeUnaryRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + argument: RequestType, + metadata: Metadata, + options: CallOptions, + callback: UnaryCallback + ): ClientUnaryCall; + makeUnaryRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + argument: RequestType, + metadata: Metadata, + callback: UnaryCallback + ): ClientUnaryCall; + makeUnaryRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + argument: RequestType, + options: CallOptions, + callback: UnaryCallback + ): ClientUnaryCall; + makeUnaryRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + argument: RequestType, + callback: UnaryCallback + ): ClientUnaryCall; + makeUnaryRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + argument: RequestType, + metadata: Metadata | CallOptions | UnaryCallback, + options?: CallOptions | UnaryCallback, + callback?: UnaryCallback + ): ClientUnaryCall { + const checkedArguments = + this.checkOptionalUnaryResponseArguments( + metadata, + options, + callback + ); + const methodDefinition: ClientMethodDefinition = + { + path: method, + requestStream: false, + responseStream: false, + requestSerialize: serialize, + responseDeserialize: deserialize, + }; + let callProperties: CallProperties = { + argument: argument, + metadata: checkedArguments.metadata, + call: new ClientUnaryCallImpl(), + channel: this[CHANNEL_SYMBOL], + methodDefinition: methodDefinition, + callOptions: checkedArguments.options, + callback: checkedArguments.callback, + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL]!( + callProperties + ) as CallProperties; + } + const emitter: ClientUnaryCall = callProperties.call; + const interceptorArgs: InterceptorArguments = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: callProperties.callOptions.interceptors ?? [], + callInterceptorProviders: + callProperties.callOptions.interceptor_providers ?? [], + }; + const call: InterceptingCallInterface = getInterceptingCall( + interceptorArgs, + callProperties.methodDefinition, + callProperties.callOptions, + callProperties.channel + ); + /* This needs to happen before the emitter is used. Unfortunately we can't + * enforce this with the type system. We need to construct this emitter + * before calling the CallInvocationTransformer, and we need to create the + * call after that. */ + emitter.call = call; + let responseMessage: ResponseType | null = null; + let receivedStatus = false; + let callerStackError: Error | null = new Error(); + call.start(callProperties.metadata, { + onReceiveMetadata: metadata => { + emitter.emit('metadata', metadata); + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message: any) { + if (responseMessage !== null) { + call.cancelWithStatus(Status.UNIMPLEMENTED, 'Too many responses received'); + } + responseMessage = message; + }, + onReceiveStatus(status: StatusObject) { + if (receivedStatus) { + return; + } + receivedStatus = true; + if (status.code === Status.OK) { + if (responseMessage === null) { + const callerStack = getErrorStackString(callerStackError!); + callProperties.callback!( + callErrorFromStatus( + { + code: Status.UNIMPLEMENTED, + details: 'No message received', + metadata: status.metadata, + }, + callerStack + ) + ); + } else { + callProperties.callback!(null, responseMessage); + } + } else { + const callerStack = getErrorStackString(callerStackError!); + callProperties.callback!(callErrorFromStatus(status, callerStack)); + } + /* Avoid retaining the callerStackError object in the call context of + * the status event handler. */ + callerStackError = null; + emitter.emit('status', status); + }, + }); + call.sendMessage(argument); + call.halfClose(); + return emitter; + } + + makeClientStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + metadata: Metadata, + options: CallOptions, + callback: UnaryCallback + ): ClientWritableStream; + makeClientStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + metadata: Metadata, + callback: UnaryCallback + ): ClientWritableStream; + makeClientStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + options: CallOptions, + callback: UnaryCallback + ): ClientWritableStream; + makeClientStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + callback: UnaryCallback + ): ClientWritableStream; + makeClientStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + metadata: Metadata | CallOptions | UnaryCallback, + options?: CallOptions | UnaryCallback, + callback?: UnaryCallback + ): ClientWritableStream { + const checkedArguments = + this.checkOptionalUnaryResponseArguments( + metadata, + options, + callback + ); + const methodDefinition: ClientMethodDefinition = + { + path: method, + requestStream: true, + responseStream: false, + requestSerialize: serialize, + responseDeserialize: deserialize, + }; + let callProperties: CallProperties = { + metadata: checkedArguments.metadata, + call: new ClientWritableStreamImpl(serialize), + channel: this[CHANNEL_SYMBOL], + methodDefinition: methodDefinition, + callOptions: checkedArguments.options, + callback: checkedArguments.callback, + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL]!( + callProperties + ) as CallProperties; + } + const emitter: ClientWritableStream = + callProperties.call as ClientWritableStream; + const interceptorArgs: InterceptorArguments = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: callProperties.callOptions.interceptors ?? [], + callInterceptorProviders: + callProperties.callOptions.interceptor_providers ?? [], + }; + const call: InterceptingCallInterface = getInterceptingCall( + interceptorArgs, + callProperties.methodDefinition, + callProperties.callOptions, + callProperties.channel + ); + /* This needs to happen before the emitter is used. Unfortunately we can't + * enforce this with the type system. We need to construct this emitter + * before calling the CallInvocationTransformer, and we need to create the + * call after that. */ + emitter.call = call; + let responseMessage: ResponseType | null = null; + let receivedStatus = false; + let callerStackError: Error | null = new Error(); + call.start(callProperties.metadata, { + onReceiveMetadata: metadata => { + emitter.emit('metadata', metadata); + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message: any) { + if (responseMessage !== null) { + call.cancelWithStatus(Status.UNIMPLEMENTED, 'Too many responses received'); + } + responseMessage = message; + call.startRead(); + }, + onReceiveStatus(status: StatusObject) { + if (receivedStatus) { + return; + } + receivedStatus = true; + if (status.code === Status.OK) { + if (responseMessage === null) { + const callerStack = getErrorStackString(callerStackError!); + callProperties.callback!( + callErrorFromStatus( + { + code: Status.UNIMPLEMENTED, + details: 'No message received', + metadata: status.metadata, + }, + callerStack + ) + ); + } else { + callProperties.callback!(null, responseMessage); + } + } else { + const callerStack = getErrorStackString(callerStackError!); + callProperties.callback!(callErrorFromStatus(status, callerStack)); + } + /* Avoid retaining the callerStackError object in the call context of + * the status event handler. */ + callerStackError = null; + emitter.emit('status', status); + }, + }); + return emitter; + } + + private checkMetadataAndOptions( + arg1?: Metadata | CallOptions, + arg2?: CallOptions + ): { metadata: Metadata; options: CallOptions } { + let metadata: Metadata; + let options: CallOptions; + if (arg1 instanceof Metadata) { + metadata = arg1; + if (arg2) { + options = arg2; + } else { + options = {}; + } + } else { + if (arg1) { + options = arg1; + } else { + options = {}; + } + metadata = new Metadata(); + } + return { metadata, options }; + } + + makeServerStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + argument: RequestType, + metadata: Metadata, + options?: CallOptions + ): ClientReadableStream; + makeServerStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + argument: RequestType, + options?: CallOptions + ): ClientReadableStream; + makeServerStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + argument: RequestType, + metadata?: Metadata | CallOptions, + options?: CallOptions + ): ClientReadableStream { + const checkedArguments = this.checkMetadataAndOptions(metadata, options); + const methodDefinition: ClientMethodDefinition = + { + path: method, + requestStream: false, + responseStream: true, + requestSerialize: serialize, + responseDeserialize: deserialize, + }; + let callProperties: CallProperties = { + argument: argument, + metadata: checkedArguments.metadata, + call: new ClientReadableStreamImpl(deserialize), + channel: this[CHANNEL_SYMBOL], + methodDefinition: methodDefinition, + callOptions: checkedArguments.options, + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL]!( + callProperties + ) as CallProperties; + } + const stream: ClientReadableStream = + callProperties.call as ClientReadableStream; + const interceptorArgs: InterceptorArguments = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: callProperties.callOptions.interceptors ?? [], + callInterceptorProviders: + callProperties.callOptions.interceptor_providers ?? [], + }; + const call: InterceptingCallInterface = getInterceptingCall( + interceptorArgs, + callProperties.methodDefinition, + callProperties.callOptions, + callProperties.channel + ); + /* This needs to happen before the emitter is used. Unfortunately we can't + * enforce this with the type system. We need to construct this emitter + * before calling the CallInvocationTransformer, and we need to create the + * call after that. */ + stream.call = call; + let receivedStatus = false; + let callerStackError: Error | null = new Error(); + call.start(callProperties.metadata, { + onReceiveMetadata(metadata: Metadata) { + stream.emit('metadata', metadata); + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message: any) { + stream.push(message); + }, + onReceiveStatus(status: StatusObject) { + if (receivedStatus) { + return; + } + receivedStatus = true; + stream.push(null); + if (status.code !== Status.OK) { + const callerStack = getErrorStackString(callerStackError!); + stream.emit('error', callErrorFromStatus(status, callerStack)); + } + /* Avoid retaining the callerStackError object in the call context of + * the status event handler. */ + callerStackError = null; + stream.emit('status', status); + }, + }); + call.sendMessage(argument); + call.halfClose(); + return stream; + } + + makeBidiStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + metadata: Metadata, + options?: CallOptions + ): ClientDuplexStream; + makeBidiStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + options?: CallOptions + ): ClientDuplexStream; + makeBidiStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + metadata?: Metadata | CallOptions, + options?: CallOptions + ): ClientDuplexStream { + const checkedArguments = this.checkMetadataAndOptions(metadata, options); + const methodDefinition: ClientMethodDefinition = + { + path: method, + requestStream: true, + responseStream: true, + requestSerialize: serialize, + responseDeserialize: deserialize, + }; + let callProperties: CallProperties = { + metadata: checkedArguments.metadata, + call: new ClientDuplexStreamImpl( + serialize, + deserialize + ), + channel: this[CHANNEL_SYMBOL], + methodDefinition: methodDefinition, + callOptions: checkedArguments.options, + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL]!( + callProperties + ) as CallProperties; + } + const stream: ClientDuplexStream = + callProperties.call as ClientDuplexStream; + const interceptorArgs: InterceptorArguments = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: callProperties.callOptions.interceptors ?? [], + callInterceptorProviders: + callProperties.callOptions.interceptor_providers ?? [], + }; + const call: InterceptingCallInterface = getInterceptingCall( + interceptorArgs, + callProperties.methodDefinition, + callProperties.callOptions, + callProperties.channel + ); + /* This needs to happen before the emitter is used. Unfortunately we can't + * enforce this with the type system. We need to construct this emitter + * before calling the CallInvocationTransformer, and we need to create the + * call after that. */ + stream.call = call; + let receivedStatus = false; + let callerStackError: Error | null = new Error(); + call.start(callProperties.metadata, { + onReceiveMetadata(metadata: Metadata) { + stream.emit('metadata', metadata); + }, + onReceiveMessage(message: Buffer) { + stream.push(message); + }, + onReceiveStatus(status: StatusObject) { + if (receivedStatus) { + return; + } + receivedStatus = true; + stream.push(null); + if (status.code !== Status.OK) { + const callerStack = getErrorStackString(callerStackError!); + stream.emit('error', callErrorFromStatus(status, callerStack)); + } + /* Avoid retaining the callerStackError object in the call context of + * the status event handler. */ + callerStackError = null; + stream.emit('status', status); + }, + }); + return stream; + } +} diff --git a/node_modules/@grpc/grpc-js/src/compression-algorithms.ts b/node_modules/@grpc/grpc-js/src/compression-algorithms.ts new file mode 100644 index 0000000..67fdcf1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/compression-algorithms.ts @@ -0,0 +1,22 @@ +/* + * Copyright 2021 gRPC authors. + * + * 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. + * + */ + +export enum CompressionAlgorithms { + identity = 0, + deflate = 1, + gzip = 2, +} diff --git a/node_modules/@grpc/grpc-js/src/compression-filter.ts b/node_modules/@grpc/grpc-js/src/compression-filter.ts new file mode 100644 index 0000000..e4428a1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/compression-filter.ts @@ -0,0 +1,358 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import * as zlib from 'zlib'; + +import { WriteObject, WriteFlags } from './call-interface'; +import { Channel } from './channel'; +import { ChannelOptions } from './channel-options'; +import { CompressionAlgorithms } from './compression-algorithms'; +import { DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH, DEFAULT_MAX_SEND_MESSAGE_LENGTH, LogVerbosity, Status } from './constants'; +import { BaseFilter, Filter, FilterFactory } from './filter'; +import * as logging from './logging'; +import { Metadata, MetadataValue } from './metadata'; + +const isCompressionAlgorithmKey = ( + key: number +): key is CompressionAlgorithms => { + return ( + typeof key === 'number' && typeof CompressionAlgorithms[key] === 'string' + ); +}; + +type CompressionAlgorithm = keyof typeof CompressionAlgorithms; + +type SharedCompressionFilterConfig = { + serverSupportedEncodingHeader?: string; +}; + +abstract class CompressionHandler { + protected abstract compressMessage(message: Buffer): Promise; + protected abstract decompressMessage(data: Buffer): Promise; + /** + * @param message Raw uncompressed message bytes + * @param compress Indicates whether the message should be compressed + * @return Framed message, compressed if applicable + */ + async writeMessage(message: Buffer, compress: boolean): Promise { + let messageBuffer = message; + if (compress) { + messageBuffer = await this.compressMessage(messageBuffer); + } + const output = Buffer.allocUnsafe(messageBuffer.length + 5); + output.writeUInt8(compress ? 1 : 0, 0); + output.writeUInt32BE(messageBuffer.length, 1); + messageBuffer.copy(output, 5); + return output; + } + /** + * @param data Framed message, possibly compressed + * @return Uncompressed message + */ + async readMessage(data: Buffer): Promise { + const compressed = data.readUInt8(0) === 1; + let messageBuffer: Buffer = data.slice(5); + if (compressed) { + messageBuffer = await this.decompressMessage(messageBuffer); + } + return messageBuffer; + } +} + +class IdentityHandler extends CompressionHandler { + async compressMessage(message: Buffer) { + return message; + } + + async writeMessage(message: Buffer, compress: boolean): Promise { + const output = Buffer.allocUnsafe(message.length + 5); + /* With "identity" compression, messages should always be marked as + * uncompressed */ + output.writeUInt8(0, 0); + output.writeUInt32BE(message.length, 1); + message.copy(output, 5); + return output; + } + + decompressMessage(message: Buffer): Promise { + return Promise.reject( + new Error( + 'Received compressed message but "grpc-encoding" header was identity' + ) + ); + } +} + +class DeflateHandler extends CompressionHandler { + constructor(private maxRecvMessageLength: number) { + super(); + } + + compressMessage(message: Buffer) { + return new Promise((resolve, reject) => { + zlib.deflate(message, (err, output) => { + if (err) { + reject(err); + } else { + resolve(output); + } + }); + }); + } + + decompressMessage(message: Buffer) { + return new Promise((resolve, reject) => { + let totalLength = 0; + const messageParts: Buffer[] = []; + const decompresser = zlib.createInflate(); + decompresser.on('data', (chunk: Buffer) => { + messageParts.push(chunk); + totalLength += chunk.byteLength; + if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) { + decompresser.destroy(); + reject({ + code: Status.RESOURCE_EXHAUSTED, + details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}` + }); + } + }); + decompresser.on('end', () => { + resolve(Buffer.concat(messageParts)); + }); + decompresser.write(message); + decompresser.end(); + }); + } +} + +class GzipHandler extends CompressionHandler { + constructor(private maxRecvMessageLength: number) { + super(); + } + + compressMessage(message: Buffer) { + return new Promise((resolve, reject) => { + zlib.gzip(message, (err, output) => { + if (err) { + reject(err); + } else { + resolve(output); + } + }); + }); + } + + decompressMessage(message: Buffer) { + return new Promise((resolve, reject) => { + let totalLength = 0; + const messageParts: Buffer[] = []; + const decompresser = zlib.createGunzip(); + decompresser.on('data', (chunk: Buffer) => { + messageParts.push(chunk); + totalLength += chunk.byteLength; + if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) { + decompresser.destroy(); + reject({ + code: Status.RESOURCE_EXHAUSTED, + details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}` + }); + } + }); + decompresser.on('end', () => { + resolve(Buffer.concat(messageParts)); + }); + decompresser.write(message); + decompresser.end(); + }); + } +} + +class UnknownHandler extends CompressionHandler { + constructor(private readonly compressionName: string) { + super(); + } + compressMessage(message: Buffer): Promise { + return Promise.reject( + new Error( + `Received message compressed with unsupported compression method ${this.compressionName}` + ) + ); + } + + decompressMessage(message: Buffer): Promise { + // This should be unreachable + return Promise.reject( + new Error(`Compression method not supported: ${this.compressionName}`) + ); + } +} + +function getCompressionHandler(compressionName: string, maxReceiveMessageSize: number): CompressionHandler { + switch (compressionName) { + case 'identity': + return new IdentityHandler(); + case 'deflate': + return new DeflateHandler(maxReceiveMessageSize); + case 'gzip': + return new GzipHandler(maxReceiveMessageSize); + default: + return new UnknownHandler(compressionName); + } +} + +export class CompressionFilter extends BaseFilter implements Filter { + private sendCompression: CompressionHandler = new IdentityHandler(); + private receiveCompression: CompressionHandler = new IdentityHandler(); + private currentCompressionAlgorithm: CompressionAlgorithm = 'identity'; + private maxReceiveMessageLength: number; + private maxSendMessageLength: number; + + constructor( + channelOptions: ChannelOptions, + private sharedFilterConfig: SharedCompressionFilterConfig + ) { + super(); + + const compressionAlgorithmKey = + channelOptions['grpc.default_compression_algorithm']; + this.maxReceiveMessageLength = channelOptions['grpc.max_receive_message_length'] ?? DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; + this.maxSendMessageLength = channelOptions['grpc.max_send_message_length'] ?? DEFAULT_MAX_SEND_MESSAGE_LENGTH; + if (compressionAlgorithmKey !== undefined) { + if (isCompressionAlgorithmKey(compressionAlgorithmKey)) { + const clientSelectedEncoding = CompressionAlgorithms[ + compressionAlgorithmKey + ] as CompressionAlgorithm; + const serverSupportedEncodings = + sharedFilterConfig.serverSupportedEncodingHeader?.split(','); + /** + * There are two possible situations here: + * 1) We don't have any info yet from the server about what compression it supports + * In that case we should just use what the client tells us to use + * 2) We've previously received a response from the server including a grpc-accept-encoding header + * In that case we only want to use the encoding chosen by the client if the server supports it + */ + if ( + !serverSupportedEncodings || + serverSupportedEncodings.includes(clientSelectedEncoding) + ) { + this.currentCompressionAlgorithm = clientSelectedEncoding; + this.sendCompression = getCompressionHandler( + this.currentCompressionAlgorithm, + -1 + ); + } + } else { + logging.log( + LogVerbosity.ERROR, + `Invalid value provided for grpc.default_compression_algorithm option: ${compressionAlgorithmKey}` + ); + } + } + } + + async sendMetadata(metadata: Promise): Promise { + const headers: Metadata = await metadata; + headers.set('grpc-accept-encoding', 'identity,deflate,gzip'); + headers.set('accept-encoding', 'identity'); + + // No need to send the header if it's "identity" - behavior is identical; save the bandwidth + if (this.currentCompressionAlgorithm === 'identity') { + headers.remove('grpc-encoding'); + } else { + headers.set('grpc-encoding', this.currentCompressionAlgorithm); + } + + return headers; + } + + receiveMetadata(metadata: Metadata): Metadata { + const receiveEncoding: MetadataValue[] = metadata.get('grpc-encoding'); + if (receiveEncoding.length > 0) { + const encoding: MetadataValue = receiveEncoding[0]; + if (typeof encoding === 'string') { + this.receiveCompression = getCompressionHandler(encoding, this.maxReceiveMessageLength); + } + } + metadata.remove('grpc-encoding'); + + /* Check to see if the compression we're using to send messages is supported by the server + * If not, reset the sendCompression filter and have it use the default IdentityHandler */ + const serverSupportedEncodingsHeader = metadata.get( + 'grpc-accept-encoding' + )[0] as string | undefined; + if (serverSupportedEncodingsHeader) { + this.sharedFilterConfig.serverSupportedEncodingHeader = + serverSupportedEncodingsHeader; + const serverSupportedEncodings = + serverSupportedEncodingsHeader.split(','); + + if ( + !serverSupportedEncodings.includes(this.currentCompressionAlgorithm) + ) { + this.sendCompression = new IdentityHandler(); + this.currentCompressionAlgorithm = 'identity'; + } + } + metadata.remove('grpc-accept-encoding'); + return metadata; + } + + async sendMessage(message: Promise): Promise { + /* This filter is special. The input message is the bare message bytes, + * and the output is a framed and possibly compressed message. For this + * reason, this filter should be at the bottom of the filter stack */ + const resolvedMessage: WriteObject = await message; + if (this.maxSendMessageLength !== -1 && resolvedMessage.message.length > this.maxSendMessageLength) { + throw { + code: Status.RESOURCE_EXHAUSTED, + details: `Attempted to send message with a size larger than ${this.maxSendMessageLength}` + }; + } + let compress: boolean; + if (this.sendCompression instanceof IdentityHandler) { + compress = false; + } else { + compress = ((resolvedMessage.flags ?? 0) & WriteFlags.NoCompress) === 0; + } + + return { + message: await this.sendCompression.writeMessage( + resolvedMessage.message, + compress + ), + flags: resolvedMessage.flags, + }; + } + + async receiveMessage(message: Promise) { + /* This filter is also special. The input message is framed and possibly + * compressed, and the output message is deframed and uncompressed. So + * this is another reason that this filter should be at the bottom of the + * filter stack. */ + return this.receiveCompression.readMessage(await message); + } +} + +export class CompressionFilterFactory + implements FilterFactory +{ + private sharedFilterConfig: SharedCompressionFilterConfig = {}; + constructor(channel: Channel, private readonly options: ChannelOptions) {} + createFilter(): CompressionFilter { + return new CompressionFilter(this.options, this.sharedFilterConfig); + } +} diff --git a/node_modules/@grpc/grpc-js/src/connectivity-state.ts b/node_modules/@grpc/grpc-js/src/connectivity-state.ts new file mode 100644 index 0000000..560ab9c --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/connectivity-state.ts @@ -0,0 +1,24 @@ +/* + * Copyright 2021 gRPC authors. + * + * 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. + * + */ + +export enum ConnectivityState { + IDLE, + CONNECTING, + READY, + TRANSIENT_FAILURE, + SHUTDOWN, +} diff --git a/node_modules/@grpc/grpc-js/src/constants.ts b/node_modules/@grpc/grpc-js/src/constants.ts new file mode 100644 index 0000000..865b24c --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/constants.ts @@ -0,0 +1,66 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +export enum Status { + OK = 0, + CANCELLED, + UNKNOWN, + INVALID_ARGUMENT, + DEADLINE_EXCEEDED, + NOT_FOUND, + ALREADY_EXISTS, + PERMISSION_DENIED, + RESOURCE_EXHAUSTED, + FAILED_PRECONDITION, + ABORTED, + OUT_OF_RANGE, + UNIMPLEMENTED, + INTERNAL, + UNAVAILABLE, + DATA_LOSS, + UNAUTHENTICATED, +} + +export enum LogVerbosity { + DEBUG = 0, + INFO, + ERROR, + NONE, +} + +/** + * NOTE: This enum is not currently used in any implemented API in this + * library. It is included only for type parity with the other implementation. + */ +export enum Propagate { + DEADLINE = 1, + CENSUS_STATS_CONTEXT = 2, + CENSUS_TRACING_CONTEXT = 4, + CANCELLATION = 8, + // https://github.com/grpc/grpc/blob/master/include/grpc/impl/codegen/propagation_bits.h#L43 + DEFAULTS = 0xffff | + Propagate.DEADLINE | + Propagate.CENSUS_STATS_CONTEXT | + Propagate.CENSUS_TRACING_CONTEXT | + Propagate.CANCELLATION, +} + +// -1 means unlimited +export const DEFAULT_MAX_SEND_MESSAGE_LENGTH = -1; + +// 4 MB default +export const DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = 4 * 1024 * 1024; diff --git a/node_modules/@grpc/grpc-js/src/control-plane-status.ts b/node_modules/@grpc/grpc-js/src/control-plane-status.ts new file mode 100644 index 0000000..1d10cb3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/control-plane-status.ts @@ -0,0 +1,43 @@ +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ + +import { Status } from './constants'; + +const INAPPROPRIATE_CONTROL_PLANE_CODES: Status[] = [ + Status.OK, + Status.INVALID_ARGUMENT, + Status.NOT_FOUND, + Status.ALREADY_EXISTS, + Status.FAILED_PRECONDITION, + Status.ABORTED, + Status.OUT_OF_RANGE, + Status.DATA_LOSS, +]; + +export function restrictControlPlaneStatusCode( + code: Status, + details: string +): { code: Status; details: string } { + if (INAPPROPRIATE_CONTROL_PLANE_CODES.includes(code)) { + return { + code: Status.INTERNAL, + details: `Invalid status from control plane: ${code} ${Status[code]} ${details}`, + }; + } else { + return { code, details }; + } +} diff --git a/node_modules/@grpc/grpc-js/src/deadline.ts b/node_modules/@grpc/grpc-js/src/deadline.ts new file mode 100644 index 0000000..de05e38 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/deadline.ts @@ -0,0 +1,106 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +export type Deadline = Date | number; + +export function minDeadline(...deadlineList: Deadline[]): Deadline { + let minValue = Infinity; + for (const deadline of deadlineList) { + const deadlineMsecs = + deadline instanceof Date ? deadline.getTime() : deadline; + if (deadlineMsecs < minValue) { + minValue = deadlineMsecs; + } + } + return minValue; +} + +const units: Array<[string, number]> = [ + ['m', 1], + ['S', 1000], + ['M', 60 * 1000], + ['H', 60 * 60 * 1000], +]; + +export function getDeadlineTimeoutString(deadline: Deadline) { + const now = new Date().getTime(); + if (deadline instanceof Date) { + deadline = deadline.getTime(); + } + const timeoutMs = Math.max(deadline - now, 0); + for (const [unit, factor] of units) { + const amount = timeoutMs / factor; + if (amount < 1e8) { + return String(Math.ceil(amount)) + unit; + } + } + throw new Error('Deadline is too far in the future'); +} + +/** + * See https://nodejs.org/api/timers.html#settimeoutcallback-delay-args + * In particular, "When delay is larger than 2147483647 or less than 1, the + * delay will be set to 1. Non-integer delays are truncated to an integer." + * This number of milliseconds is almost 25 days. + */ +const MAX_TIMEOUT_TIME = 2147483647; + +/** + * Get the timeout value that should be passed to setTimeout now for the timer + * to end at the deadline. For any deadline before now, the timer should end + * immediately, represented by a value of 0. For any deadline more than + * MAX_TIMEOUT_TIME milliseconds in the future, a timer cannot be set that will + * end at that time, so it is treated as infinitely far in the future. + * @param deadline + * @returns + */ +export function getRelativeTimeout(deadline: Deadline) { + const deadlineMs = deadline instanceof Date ? deadline.getTime() : deadline; + const now = new Date().getTime(); + const timeout = deadlineMs - now; + if (timeout < 0) { + return 0; + } else if (timeout > MAX_TIMEOUT_TIME) { + return Infinity; + } else { + return timeout; + } +} + +export function deadlineToString(deadline: Deadline): string { + if (deadline instanceof Date) { + return deadline.toISOString(); + } else { + const dateDeadline = new Date(deadline); + if (Number.isNaN(dateDeadline.getTime())) { + return '' + deadline; + } else { + return dateDeadline.toISOString(); + } + } +} + +/** + * Calculate the difference between two dates as a number of seconds and format + * it as a string. + * @param startDate + * @param endDate + * @returns + */ +export function formatDateDifference(startDate: Date, endDate: Date): string { + return ((endDate.getTime() - startDate.getTime()) / 1000).toFixed(3) + 's'; +} diff --git a/node_modules/@grpc/grpc-js/src/duration.ts b/node_modules/@grpc/grpc-js/src/duration.ts new file mode 100644 index 0000000..05a43da --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/duration.ts @@ -0,0 +1,79 @@ +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ + +export interface Duration { + seconds: number; + nanos: number; +} + +export interface DurationMessage { + seconds: string; + nanos: number; +} + +export function durationMessageToDuration(message: DurationMessage): Duration { + return { + seconds: Number.parseInt(message.seconds), + nanos: message.nanos + }; +} + +export function msToDuration(millis: number): Duration { + return { + seconds: (millis / 1000) | 0, + nanos: ((millis % 1000) * 1_000_000) | 0, + }; +} + +export function durationToMs(duration: Duration): number { + return (duration.seconds * 1000 + duration.nanos / 1_000_000) | 0; +} + +export function isDuration(value: any): value is Duration { + return typeof value.seconds === 'number' && typeof value.nanos === 'number'; +} + +export function isDurationMessage(value: any): value is DurationMessage { + return typeof value.seconds === 'string' && typeof value.nanos === 'number'; +} + +const durationRegex = /^(\d+)(?:\.(\d+))?s$/; +export function parseDuration(value: string): Duration | null { + const match = value.match(durationRegex); + if (!match) { + return null; + } + return { + seconds: Number.parseInt(match[1], 10), + nanos: match[2] ? Number.parseInt(match[2].padEnd(9, '0'), 10) : 0 + }; +} + +export function durationToString(duration: Duration): string { + if (duration.nanos === 0) { + return `${duration.seconds}s`; + } + let scaleFactor: number; + if (duration.nanos % 1_000_000 === 0) { + scaleFactor = 1_000_000; + } else if (duration.nanos % 1_000 === 0) { + scaleFactor = 1_000; + } else { + scaleFactor = 1; + } + return `${duration.seconds}.${duration.nanos/scaleFactor}s`; +} diff --git a/node_modules/@grpc/grpc-js/src/environment.ts b/node_modules/@grpc/grpc-js/src/environment.ts new file mode 100644 index 0000000..d2927a3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/environment.ts @@ -0,0 +1,19 @@ +/* + * Copyright 2024 gRPC authors. + * + * 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. + * + */ + +export const GRPC_NODE_USE_ALTERNATIVE_RESOLVER = + (process.env.GRPC_NODE_USE_ALTERNATIVE_RESOLVER ?? 'false') === 'true'; diff --git a/node_modules/@grpc/grpc-js/src/error.ts b/node_modules/@grpc/grpc-js/src/error.ts new file mode 100644 index 0000000..105a3ee --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/error.ts @@ -0,0 +1,37 @@ +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ + +export function getErrorMessage(error: unknown): string { + if (error instanceof Error) { + return error.message; + } else { + return String(error); + } +} + +export function getErrorCode(error: unknown): number | null { + if ( + typeof error === 'object' && + error !== null && + 'code' in error && + typeof (error as Record).code === 'number' + ) { + return (error as Record).code; + } else { + return null; + } +} diff --git a/node_modules/@grpc/grpc-js/src/events.ts b/node_modules/@grpc/grpc-js/src/events.ts new file mode 100644 index 0000000..7718746 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/events.ts @@ -0,0 +1,26 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +export interface EmitterAugmentation1 { + addListener(event: Name, listener: (arg1: Arg) => void): this; + emit(event: Name, arg1: Arg): boolean; + on(event: Name, listener: (arg1: Arg) => void): this; + once(event: Name, listener: (arg1: Arg) => void): this; + prependListener(event: Name, listener: (arg1: Arg) => void): this; + prependOnceListener(event: Name, listener: (arg1: Arg) => void): this; + removeListener(event: Name, listener: (arg1: Arg) => void): this; +} diff --git a/node_modules/@grpc/grpc-js/src/experimental.ts b/node_modules/@grpc/grpc-js/src/experimental.ts new file mode 100644 index 0000000..b8f7766 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/experimental.ts @@ -0,0 +1,73 @@ +export { trace, log } from './logging'; +export { + Resolver, + ResolverListener, + registerResolver, + ConfigSelector, + createResolver, + CHANNEL_ARGS_CONFIG_SELECTOR_KEY, +} from './resolver'; +export { GrpcUri, uriToString, splitHostPort, HostPort } from './uri-parser'; +export { Duration, durationToMs, parseDuration } from './duration'; +export { BackoffTimeout } from './backoff-timeout'; +export { + LoadBalancer, + TypedLoadBalancingConfig, + ChannelControlHelper, + createChildChannelControlHelper, + registerLoadBalancerType, + selectLbConfigFromList, + parseLoadBalancingConfig, + isLoadBalancerNameRegistered, +} from './load-balancer'; +export { LeafLoadBalancer } from './load-balancer-pick-first'; +export { + SubchannelAddress, + subchannelAddressToString, + Endpoint, + endpointToString, + endpointHasAddress, + EndpointMap, +} from './subchannel-address'; +export { ChildLoadBalancerHandler } from './load-balancer-child-handler'; +export { + Picker, + UnavailablePicker, + QueuePicker, + PickResult, + PickArgs, + PickResultType, +} from './picker'; +export { + Call as CallStream, + StatusOr, + statusOrFromValue, + statusOrFromError +} from './call-interface'; +export { Filter, BaseFilter, FilterFactory } from './filter'; +export { FilterStackFactory } from './filter-stack'; +export { registerAdminService } from './admin'; +export { + SubchannelInterface, + BaseSubchannelWrapper, + ConnectivityStateListener, + HealthListener, +} from './subchannel-interface'; +export { + OutlierDetectionRawConfig, + SuccessRateEjectionConfig, + FailurePercentageEjectionConfig, +} from './load-balancer-outlier-detection'; + +export { createServerCredentialsWithInterceptors, createCertificateProviderServerCredentials } from './server-credentials'; +export { + CaCertificateUpdate, + CaCertificateUpdateListener, + IdentityCertificateUpdate, + IdentityCertificateUpdateListener, + CertificateProvider, + FileWatcherCertificateProvider, + FileWatcherCertificateProviderConfig +} from './certificate-provider'; +export { createCertificateProviderChannelCredentials, SecureConnector, SecureConnectResult } from './channel-credentials'; +export { SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX } from './internal-channel'; diff --git a/node_modules/@grpc/grpc-js/src/filter-stack.ts b/node_modules/@grpc/grpc-js/src/filter-stack.ts new file mode 100644 index 0000000..910f5aa --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/filter-stack.ts @@ -0,0 +1,100 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { StatusObject, WriteObject } from './call-interface'; +import { Filter, FilterFactory } from './filter'; +import { Metadata } from './metadata'; + +export class FilterStack implements Filter { + constructor(private readonly filters: Filter[]) {} + + sendMetadata(metadata: Promise): Promise { + let result: Promise = metadata; + + for (let i = 0; i < this.filters.length; i++) { + result = this.filters[i].sendMetadata(result); + } + + return result; + } + + receiveMetadata(metadata: Metadata) { + let result: Metadata = metadata; + + for (let i = this.filters.length - 1; i >= 0; i--) { + result = this.filters[i].receiveMetadata(result); + } + + return result; + } + + sendMessage(message: Promise): Promise { + let result: Promise = message; + + for (let i = 0; i < this.filters.length; i++) { + result = this.filters[i].sendMessage(result); + } + + return result; + } + + receiveMessage(message: Promise): Promise { + let result: Promise = message; + + for (let i = this.filters.length - 1; i >= 0; i--) { + result = this.filters[i].receiveMessage(result); + } + + return result; + } + + receiveTrailers(status: StatusObject): StatusObject { + let result: StatusObject = status; + + for (let i = this.filters.length - 1; i >= 0; i--) { + result = this.filters[i].receiveTrailers(result); + } + + return result; + } + + push(filters: Filter[]) { + this.filters.unshift(...filters); + } + + getFilters(): Filter[] { + return this.filters; + } +} + +export class FilterStackFactory implements FilterFactory { + constructor(private readonly factories: Array>) {} + + push(filterFactories: FilterFactory[]) { + this.factories.unshift(...filterFactories); + } + + clone(): FilterStackFactory { + return new FilterStackFactory([...this.factories]); + } + + createFilter(): FilterStack { + return new FilterStack( + this.factories.map(factory => factory.createFilter()) + ); + } +} diff --git a/node_modules/@grpc/grpc-js/src/filter.ts b/node_modules/@grpc/grpc-js/src/filter.ts new file mode 100644 index 0000000..5313f91 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/filter.ts @@ -0,0 +1,63 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { StatusObject, WriteObject } from './call-interface'; +import { Metadata } from './metadata'; + +/** + * Filter classes represent related per-call logic and state that is primarily + * used to modify incoming and outgoing data. All async filters can be + * rejected. The rejection error must be a StatusObject, and a rejection will + * cause the call to end with that status. + */ +export interface Filter { + sendMetadata(metadata: Promise): Promise; + + receiveMetadata(metadata: Metadata): Metadata; + + sendMessage(message: Promise): Promise; + + receiveMessage(message: Promise): Promise; + + receiveTrailers(status: StatusObject): StatusObject; +} + +export abstract class BaseFilter implements Filter { + async sendMetadata(metadata: Promise): Promise { + return metadata; + } + + receiveMetadata(metadata: Metadata): Metadata { + return metadata; + } + + async sendMessage(message: Promise): Promise { + return message; + } + + async receiveMessage(message: Promise): Promise { + return message; + } + + receiveTrailers(status: StatusObject): StatusObject { + return status; + } +} + +export interface FilterFactory { + createFilter(): T; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/channelz.ts b/node_modules/@grpc/grpc-js/src/generated/channelz.ts new file mode 100644 index 0000000..fcfab4b --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/channelz.ts @@ -0,0 +1,119 @@ +import type * as grpc from '../index'; +import type { MessageTypeDefinition } from '@grpc/proto-loader'; + +import type { Any as _google_protobuf_Any, Any__Output as _google_protobuf_Any__Output } from './google/protobuf/Any'; +import type { BoolValue as _google_protobuf_BoolValue, BoolValue__Output as _google_protobuf_BoolValue__Output } from './google/protobuf/BoolValue'; +import type { BytesValue as _google_protobuf_BytesValue, BytesValue__Output as _google_protobuf_BytesValue__Output } from './google/protobuf/BytesValue'; +import type { DoubleValue as _google_protobuf_DoubleValue, DoubleValue__Output as _google_protobuf_DoubleValue__Output } from './google/protobuf/DoubleValue'; +import type { Duration as _google_protobuf_Duration, Duration__Output as _google_protobuf_Duration__Output } from './google/protobuf/Duration'; +import type { FloatValue as _google_protobuf_FloatValue, FloatValue__Output as _google_protobuf_FloatValue__Output } from './google/protobuf/FloatValue'; +import type { Int32Value as _google_protobuf_Int32Value, Int32Value__Output as _google_protobuf_Int32Value__Output } from './google/protobuf/Int32Value'; +import type { Int64Value as _google_protobuf_Int64Value, Int64Value__Output as _google_protobuf_Int64Value__Output } from './google/protobuf/Int64Value'; +import type { StringValue as _google_protobuf_StringValue, StringValue__Output as _google_protobuf_StringValue__Output } from './google/protobuf/StringValue'; +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from './google/protobuf/Timestamp'; +import type { UInt32Value as _google_protobuf_UInt32Value, UInt32Value__Output as _google_protobuf_UInt32Value__Output } from './google/protobuf/UInt32Value'; +import type { UInt64Value as _google_protobuf_UInt64Value, UInt64Value__Output as _google_protobuf_UInt64Value__Output } from './google/protobuf/UInt64Value'; +import type { Address as _grpc_channelz_v1_Address, Address__Output as _grpc_channelz_v1_Address__Output } from './grpc/channelz/v1/Address'; +import type { Channel as _grpc_channelz_v1_Channel, Channel__Output as _grpc_channelz_v1_Channel__Output } from './grpc/channelz/v1/Channel'; +import type { ChannelConnectivityState as _grpc_channelz_v1_ChannelConnectivityState, ChannelConnectivityState__Output as _grpc_channelz_v1_ChannelConnectivityState__Output } from './grpc/channelz/v1/ChannelConnectivityState'; +import type { ChannelData as _grpc_channelz_v1_ChannelData, ChannelData__Output as _grpc_channelz_v1_ChannelData__Output } from './grpc/channelz/v1/ChannelData'; +import type { ChannelRef as _grpc_channelz_v1_ChannelRef, ChannelRef__Output as _grpc_channelz_v1_ChannelRef__Output } from './grpc/channelz/v1/ChannelRef'; +import type { ChannelTrace as _grpc_channelz_v1_ChannelTrace, ChannelTrace__Output as _grpc_channelz_v1_ChannelTrace__Output } from './grpc/channelz/v1/ChannelTrace'; +import type { ChannelTraceEvent as _grpc_channelz_v1_ChannelTraceEvent, ChannelTraceEvent__Output as _grpc_channelz_v1_ChannelTraceEvent__Output } from './grpc/channelz/v1/ChannelTraceEvent'; +import type { ChannelzClient as _grpc_channelz_v1_ChannelzClient, ChannelzDefinition as _grpc_channelz_v1_ChannelzDefinition } from './grpc/channelz/v1/Channelz'; +import type { GetChannelRequest as _grpc_channelz_v1_GetChannelRequest, GetChannelRequest__Output as _grpc_channelz_v1_GetChannelRequest__Output } from './grpc/channelz/v1/GetChannelRequest'; +import type { GetChannelResponse as _grpc_channelz_v1_GetChannelResponse, GetChannelResponse__Output as _grpc_channelz_v1_GetChannelResponse__Output } from './grpc/channelz/v1/GetChannelResponse'; +import type { GetServerRequest as _grpc_channelz_v1_GetServerRequest, GetServerRequest__Output as _grpc_channelz_v1_GetServerRequest__Output } from './grpc/channelz/v1/GetServerRequest'; +import type { GetServerResponse as _grpc_channelz_v1_GetServerResponse, GetServerResponse__Output as _grpc_channelz_v1_GetServerResponse__Output } from './grpc/channelz/v1/GetServerResponse'; +import type { GetServerSocketsRequest as _grpc_channelz_v1_GetServerSocketsRequest, GetServerSocketsRequest__Output as _grpc_channelz_v1_GetServerSocketsRequest__Output } from './grpc/channelz/v1/GetServerSocketsRequest'; +import type { GetServerSocketsResponse as _grpc_channelz_v1_GetServerSocketsResponse, GetServerSocketsResponse__Output as _grpc_channelz_v1_GetServerSocketsResponse__Output } from './grpc/channelz/v1/GetServerSocketsResponse'; +import type { GetServersRequest as _grpc_channelz_v1_GetServersRequest, GetServersRequest__Output as _grpc_channelz_v1_GetServersRequest__Output } from './grpc/channelz/v1/GetServersRequest'; +import type { GetServersResponse as _grpc_channelz_v1_GetServersResponse, GetServersResponse__Output as _grpc_channelz_v1_GetServersResponse__Output } from './grpc/channelz/v1/GetServersResponse'; +import type { GetSocketRequest as _grpc_channelz_v1_GetSocketRequest, GetSocketRequest__Output as _grpc_channelz_v1_GetSocketRequest__Output } from './grpc/channelz/v1/GetSocketRequest'; +import type { GetSocketResponse as _grpc_channelz_v1_GetSocketResponse, GetSocketResponse__Output as _grpc_channelz_v1_GetSocketResponse__Output } from './grpc/channelz/v1/GetSocketResponse'; +import type { GetSubchannelRequest as _grpc_channelz_v1_GetSubchannelRequest, GetSubchannelRequest__Output as _grpc_channelz_v1_GetSubchannelRequest__Output } from './grpc/channelz/v1/GetSubchannelRequest'; +import type { GetSubchannelResponse as _grpc_channelz_v1_GetSubchannelResponse, GetSubchannelResponse__Output as _grpc_channelz_v1_GetSubchannelResponse__Output } from './grpc/channelz/v1/GetSubchannelResponse'; +import type { GetTopChannelsRequest as _grpc_channelz_v1_GetTopChannelsRequest, GetTopChannelsRequest__Output as _grpc_channelz_v1_GetTopChannelsRequest__Output } from './grpc/channelz/v1/GetTopChannelsRequest'; +import type { GetTopChannelsResponse as _grpc_channelz_v1_GetTopChannelsResponse, GetTopChannelsResponse__Output as _grpc_channelz_v1_GetTopChannelsResponse__Output } from './grpc/channelz/v1/GetTopChannelsResponse'; +import type { Security as _grpc_channelz_v1_Security, Security__Output as _grpc_channelz_v1_Security__Output } from './grpc/channelz/v1/Security'; +import type { Server as _grpc_channelz_v1_Server, Server__Output as _grpc_channelz_v1_Server__Output } from './grpc/channelz/v1/Server'; +import type { ServerData as _grpc_channelz_v1_ServerData, ServerData__Output as _grpc_channelz_v1_ServerData__Output } from './grpc/channelz/v1/ServerData'; +import type { ServerRef as _grpc_channelz_v1_ServerRef, ServerRef__Output as _grpc_channelz_v1_ServerRef__Output } from './grpc/channelz/v1/ServerRef'; +import type { Socket as _grpc_channelz_v1_Socket, Socket__Output as _grpc_channelz_v1_Socket__Output } from './grpc/channelz/v1/Socket'; +import type { SocketData as _grpc_channelz_v1_SocketData, SocketData__Output as _grpc_channelz_v1_SocketData__Output } from './grpc/channelz/v1/SocketData'; +import type { SocketOption as _grpc_channelz_v1_SocketOption, SocketOption__Output as _grpc_channelz_v1_SocketOption__Output } from './grpc/channelz/v1/SocketOption'; +import type { SocketOptionLinger as _grpc_channelz_v1_SocketOptionLinger, SocketOptionLinger__Output as _grpc_channelz_v1_SocketOptionLinger__Output } from './grpc/channelz/v1/SocketOptionLinger'; +import type { SocketOptionTcpInfo as _grpc_channelz_v1_SocketOptionTcpInfo, SocketOptionTcpInfo__Output as _grpc_channelz_v1_SocketOptionTcpInfo__Output } from './grpc/channelz/v1/SocketOptionTcpInfo'; +import type { SocketOptionTimeout as _grpc_channelz_v1_SocketOptionTimeout, SocketOptionTimeout__Output as _grpc_channelz_v1_SocketOptionTimeout__Output } from './grpc/channelz/v1/SocketOptionTimeout'; +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from './grpc/channelz/v1/SocketRef'; +import type { Subchannel as _grpc_channelz_v1_Subchannel, Subchannel__Output as _grpc_channelz_v1_Subchannel__Output } from './grpc/channelz/v1/Subchannel'; +import type { SubchannelRef as _grpc_channelz_v1_SubchannelRef, SubchannelRef__Output as _grpc_channelz_v1_SubchannelRef__Output } from './grpc/channelz/v1/SubchannelRef'; + +type SubtypeConstructor any, Subtype> = { + new(...args: ConstructorParameters): Subtype; +}; + +export interface ProtoGrpcType { + google: { + protobuf: { + Any: MessageTypeDefinition<_google_protobuf_Any, _google_protobuf_Any__Output> + BoolValue: MessageTypeDefinition<_google_protobuf_BoolValue, _google_protobuf_BoolValue__Output> + BytesValue: MessageTypeDefinition<_google_protobuf_BytesValue, _google_protobuf_BytesValue__Output> + DoubleValue: MessageTypeDefinition<_google_protobuf_DoubleValue, _google_protobuf_DoubleValue__Output> + Duration: MessageTypeDefinition<_google_protobuf_Duration, _google_protobuf_Duration__Output> + FloatValue: MessageTypeDefinition<_google_protobuf_FloatValue, _google_protobuf_FloatValue__Output> + Int32Value: MessageTypeDefinition<_google_protobuf_Int32Value, _google_protobuf_Int32Value__Output> + Int64Value: MessageTypeDefinition<_google_protobuf_Int64Value, _google_protobuf_Int64Value__Output> + StringValue: MessageTypeDefinition<_google_protobuf_StringValue, _google_protobuf_StringValue__Output> + Timestamp: MessageTypeDefinition<_google_protobuf_Timestamp, _google_protobuf_Timestamp__Output> + UInt32Value: MessageTypeDefinition<_google_protobuf_UInt32Value, _google_protobuf_UInt32Value__Output> + UInt64Value: MessageTypeDefinition<_google_protobuf_UInt64Value, _google_protobuf_UInt64Value__Output> + } + } + grpc: { + channelz: { + v1: { + Address: MessageTypeDefinition<_grpc_channelz_v1_Address, _grpc_channelz_v1_Address__Output> + Channel: MessageTypeDefinition<_grpc_channelz_v1_Channel, _grpc_channelz_v1_Channel__Output> + ChannelConnectivityState: MessageTypeDefinition<_grpc_channelz_v1_ChannelConnectivityState, _grpc_channelz_v1_ChannelConnectivityState__Output> + ChannelData: MessageTypeDefinition<_grpc_channelz_v1_ChannelData, _grpc_channelz_v1_ChannelData__Output> + ChannelRef: MessageTypeDefinition<_grpc_channelz_v1_ChannelRef, _grpc_channelz_v1_ChannelRef__Output> + ChannelTrace: MessageTypeDefinition<_grpc_channelz_v1_ChannelTrace, _grpc_channelz_v1_ChannelTrace__Output> + ChannelTraceEvent: MessageTypeDefinition<_grpc_channelz_v1_ChannelTraceEvent, _grpc_channelz_v1_ChannelTraceEvent__Output> + /** + * Channelz is a service exposed by gRPC servers that provides detailed debug + * information. + */ + Channelz: SubtypeConstructor & { service: _grpc_channelz_v1_ChannelzDefinition } + GetChannelRequest: MessageTypeDefinition<_grpc_channelz_v1_GetChannelRequest, _grpc_channelz_v1_GetChannelRequest__Output> + GetChannelResponse: MessageTypeDefinition<_grpc_channelz_v1_GetChannelResponse, _grpc_channelz_v1_GetChannelResponse__Output> + GetServerRequest: MessageTypeDefinition<_grpc_channelz_v1_GetServerRequest, _grpc_channelz_v1_GetServerRequest__Output> + GetServerResponse: MessageTypeDefinition<_grpc_channelz_v1_GetServerResponse, _grpc_channelz_v1_GetServerResponse__Output> + GetServerSocketsRequest: MessageTypeDefinition<_grpc_channelz_v1_GetServerSocketsRequest, _grpc_channelz_v1_GetServerSocketsRequest__Output> + GetServerSocketsResponse: MessageTypeDefinition<_grpc_channelz_v1_GetServerSocketsResponse, _grpc_channelz_v1_GetServerSocketsResponse__Output> + GetServersRequest: MessageTypeDefinition<_grpc_channelz_v1_GetServersRequest, _grpc_channelz_v1_GetServersRequest__Output> + GetServersResponse: MessageTypeDefinition<_grpc_channelz_v1_GetServersResponse, _grpc_channelz_v1_GetServersResponse__Output> + GetSocketRequest: MessageTypeDefinition<_grpc_channelz_v1_GetSocketRequest, _grpc_channelz_v1_GetSocketRequest__Output> + GetSocketResponse: MessageTypeDefinition<_grpc_channelz_v1_GetSocketResponse, _grpc_channelz_v1_GetSocketResponse__Output> + GetSubchannelRequest: MessageTypeDefinition<_grpc_channelz_v1_GetSubchannelRequest, _grpc_channelz_v1_GetSubchannelRequest__Output> + GetSubchannelResponse: MessageTypeDefinition<_grpc_channelz_v1_GetSubchannelResponse, _grpc_channelz_v1_GetSubchannelResponse__Output> + GetTopChannelsRequest: MessageTypeDefinition<_grpc_channelz_v1_GetTopChannelsRequest, _grpc_channelz_v1_GetTopChannelsRequest__Output> + GetTopChannelsResponse: MessageTypeDefinition<_grpc_channelz_v1_GetTopChannelsResponse, _grpc_channelz_v1_GetTopChannelsResponse__Output> + Security: MessageTypeDefinition<_grpc_channelz_v1_Security, _grpc_channelz_v1_Security__Output> + Server: MessageTypeDefinition<_grpc_channelz_v1_Server, _grpc_channelz_v1_Server__Output> + ServerData: MessageTypeDefinition<_grpc_channelz_v1_ServerData, _grpc_channelz_v1_ServerData__Output> + ServerRef: MessageTypeDefinition<_grpc_channelz_v1_ServerRef, _grpc_channelz_v1_ServerRef__Output> + Socket: MessageTypeDefinition<_grpc_channelz_v1_Socket, _grpc_channelz_v1_Socket__Output> + SocketData: MessageTypeDefinition<_grpc_channelz_v1_SocketData, _grpc_channelz_v1_SocketData__Output> + SocketOption: MessageTypeDefinition<_grpc_channelz_v1_SocketOption, _grpc_channelz_v1_SocketOption__Output> + SocketOptionLinger: MessageTypeDefinition<_grpc_channelz_v1_SocketOptionLinger, _grpc_channelz_v1_SocketOptionLinger__Output> + SocketOptionTcpInfo: MessageTypeDefinition<_grpc_channelz_v1_SocketOptionTcpInfo, _grpc_channelz_v1_SocketOptionTcpInfo__Output> + SocketOptionTimeout: MessageTypeDefinition<_grpc_channelz_v1_SocketOptionTimeout, _grpc_channelz_v1_SocketOptionTimeout__Output> + SocketRef: MessageTypeDefinition<_grpc_channelz_v1_SocketRef, _grpc_channelz_v1_SocketRef__Output> + Subchannel: MessageTypeDefinition<_grpc_channelz_v1_Subchannel, _grpc_channelz_v1_Subchannel__Output> + SubchannelRef: MessageTypeDefinition<_grpc_channelz_v1_SubchannelRef, _grpc_channelz_v1_SubchannelRef__Output> + } + } + } +} + diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Any.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Any.ts new file mode 100644 index 0000000..fcaa672 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Any.ts @@ -0,0 +1,13 @@ +// Original file: null + +import type { AnyExtension } from '@grpc/proto-loader'; + +export type Any = AnyExtension | { + type_url: string; + value: Buffer | Uint8Array | string; +} + +export interface Any__Output { + 'type_url': (string); + 'value': (Buffer); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/BoolValue.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/BoolValue.ts new file mode 100644 index 0000000..86507ea --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/BoolValue.ts @@ -0,0 +1,10 @@ +// Original file: null + + +export interface BoolValue { + 'value'?: (boolean); +} + +export interface BoolValue__Output { + 'value': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/BytesValue.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/BytesValue.ts new file mode 100644 index 0000000..9cec76f --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/BytesValue.ts @@ -0,0 +1,10 @@ +// Original file: null + + +export interface BytesValue { + 'value'?: (Buffer | Uint8Array | string); +} + +export interface BytesValue__Output { + 'value': (Buffer); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/DescriptorProto.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/DescriptorProto.ts new file mode 100644 index 0000000..b316f8e --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/DescriptorProto.ts @@ -0,0 +1,59 @@ +// Original file: null + +import type { FieldDescriptorProto as _google_protobuf_FieldDescriptorProto, FieldDescriptorProto__Output as _google_protobuf_FieldDescriptorProto__Output } from '../../google/protobuf/FieldDescriptorProto'; +import type { DescriptorProto as _google_protobuf_DescriptorProto, DescriptorProto__Output as _google_protobuf_DescriptorProto__Output } from '../../google/protobuf/DescriptorProto'; +import type { EnumDescriptorProto as _google_protobuf_EnumDescriptorProto, EnumDescriptorProto__Output as _google_protobuf_EnumDescriptorProto__Output } from '../../google/protobuf/EnumDescriptorProto'; +import type { MessageOptions as _google_protobuf_MessageOptions, MessageOptions__Output as _google_protobuf_MessageOptions__Output } from '../../google/protobuf/MessageOptions'; +import type { OneofDescriptorProto as _google_protobuf_OneofDescriptorProto, OneofDescriptorProto__Output as _google_protobuf_OneofDescriptorProto__Output } from '../../google/protobuf/OneofDescriptorProto'; +import type { SymbolVisibility as _google_protobuf_SymbolVisibility, SymbolVisibility__Output as _google_protobuf_SymbolVisibility__Output } from '../../google/protobuf/SymbolVisibility'; +import type { ExtensionRangeOptions as _google_protobuf_ExtensionRangeOptions, ExtensionRangeOptions__Output as _google_protobuf_ExtensionRangeOptions__Output } from '../../google/protobuf/ExtensionRangeOptions'; + +export interface _google_protobuf_DescriptorProto_ExtensionRange { + 'start'?: (number); + 'end'?: (number); + 'options'?: (_google_protobuf_ExtensionRangeOptions | null); +} + +export interface _google_protobuf_DescriptorProto_ExtensionRange__Output { + 'start': (number); + 'end': (number); + 'options': (_google_protobuf_ExtensionRangeOptions__Output | null); +} + +export interface _google_protobuf_DescriptorProto_ReservedRange { + 'start'?: (number); + 'end'?: (number); +} + +export interface _google_protobuf_DescriptorProto_ReservedRange__Output { + 'start': (number); + 'end': (number); +} + +export interface DescriptorProto { + 'name'?: (string); + 'field'?: (_google_protobuf_FieldDescriptorProto)[]; + 'nestedType'?: (_google_protobuf_DescriptorProto)[]; + 'enumType'?: (_google_protobuf_EnumDescriptorProto)[]; + 'extensionRange'?: (_google_protobuf_DescriptorProto_ExtensionRange)[]; + 'extension'?: (_google_protobuf_FieldDescriptorProto)[]; + 'options'?: (_google_protobuf_MessageOptions | null); + 'oneofDecl'?: (_google_protobuf_OneofDescriptorProto)[]; + 'reservedRange'?: (_google_protobuf_DescriptorProto_ReservedRange)[]; + 'reservedName'?: (string)[]; + 'visibility'?: (_google_protobuf_SymbolVisibility); +} + +export interface DescriptorProto__Output { + 'name': (string); + 'field': (_google_protobuf_FieldDescriptorProto__Output)[]; + 'nestedType': (_google_protobuf_DescriptorProto__Output)[]; + 'enumType': (_google_protobuf_EnumDescriptorProto__Output)[]; + 'extensionRange': (_google_protobuf_DescriptorProto_ExtensionRange__Output)[]; + 'extension': (_google_protobuf_FieldDescriptorProto__Output)[]; + 'options': (_google_protobuf_MessageOptions__Output | null); + 'oneofDecl': (_google_protobuf_OneofDescriptorProto__Output)[]; + 'reservedRange': (_google_protobuf_DescriptorProto_ReservedRange__Output)[]; + 'reservedName': (string)[]; + 'visibility': (_google_protobuf_SymbolVisibility__Output); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/DoubleValue.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/DoubleValue.ts new file mode 100644 index 0000000..d70b303 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/DoubleValue.ts @@ -0,0 +1,10 @@ +// Original file: null + + +export interface DoubleValue { + 'value'?: (number | string); +} + +export interface DoubleValue__Output { + 'value': (number); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Duration.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Duration.ts new file mode 100644 index 0000000..8595377 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Duration.ts @@ -0,0 +1,13 @@ +// Original file: null + +import type { Long } from '@grpc/proto-loader'; + +export interface Duration { + 'seconds'?: (number | string | Long); + 'nanos'?: (number); +} + +export interface Duration__Output { + 'seconds': (string); + 'nanos': (number); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Edition.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Edition.ts new file mode 100644 index 0000000..26c71d6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Edition.ts @@ -0,0 +1,44 @@ +// Original file: null + +export const Edition = { + EDITION_UNKNOWN: 'EDITION_UNKNOWN', + EDITION_LEGACY: 'EDITION_LEGACY', + EDITION_PROTO2: 'EDITION_PROTO2', + EDITION_PROTO3: 'EDITION_PROTO3', + EDITION_2023: 'EDITION_2023', + EDITION_2024: 'EDITION_2024', + EDITION_1_TEST_ONLY: 'EDITION_1_TEST_ONLY', + EDITION_2_TEST_ONLY: 'EDITION_2_TEST_ONLY', + EDITION_99997_TEST_ONLY: 'EDITION_99997_TEST_ONLY', + EDITION_99998_TEST_ONLY: 'EDITION_99998_TEST_ONLY', + EDITION_99999_TEST_ONLY: 'EDITION_99999_TEST_ONLY', + EDITION_MAX: 'EDITION_MAX', +} as const; + +export type Edition = + | 'EDITION_UNKNOWN' + | 0 + | 'EDITION_LEGACY' + | 900 + | 'EDITION_PROTO2' + | 998 + | 'EDITION_PROTO3' + | 999 + | 'EDITION_2023' + | 1000 + | 'EDITION_2024' + | 1001 + | 'EDITION_1_TEST_ONLY' + | 1 + | 'EDITION_2_TEST_ONLY' + | 2 + | 'EDITION_99997_TEST_ONLY' + | 99997 + | 'EDITION_99998_TEST_ONLY' + | 99998 + | 'EDITION_99999_TEST_ONLY' + | 99999 + | 'EDITION_MAX' + | 2147483647 + +export type Edition__Output = typeof Edition[keyof typeof Edition] diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/EnumDescriptorProto.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/EnumDescriptorProto.ts new file mode 100644 index 0000000..6ec1a2e --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/EnumDescriptorProto.ts @@ -0,0 +1,33 @@ +// Original file: null + +import type { EnumValueDescriptorProto as _google_protobuf_EnumValueDescriptorProto, EnumValueDescriptorProto__Output as _google_protobuf_EnumValueDescriptorProto__Output } from '../../google/protobuf/EnumValueDescriptorProto'; +import type { EnumOptions as _google_protobuf_EnumOptions, EnumOptions__Output as _google_protobuf_EnumOptions__Output } from '../../google/protobuf/EnumOptions'; +import type { SymbolVisibility as _google_protobuf_SymbolVisibility, SymbolVisibility__Output as _google_protobuf_SymbolVisibility__Output } from '../../google/protobuf/SymbolVisibility'; + +export interface _google_protobuf_EnumDescriptorProto_EnumReservedRange { + 'start'?: (number); + 'end'?: (number); +} + +export interface _google_protobuf_EnumDescriptorProto_EnumReservedRange__Output { + 'start': (number); + 'end': (number); +} + +export interface EnumDescriptorProto { + 'name'?: (string); + 'value'?: (_google_protobuf_EnumValueDescriptorProto)[]; + 'options'?: (_google_protobuf_EnumOptions | null); + 'reservedRange'?: (_google_protobuf_EnumDescriptorProto_EnumReservedRange)[]; + 'reservedName'?: (string)[]; + 'visibility'?: (_google_protobuf_SymbolVisibility); +} + +export interface EnumDescriptorProto__Output { + 'name': (string); + 'value': (_google_protobuf_EnumValueDescriptorProto__Output)[]; + 'options': (_google_protobuf_EnumOptions__Output | null); + 'reservedRange': (_google_protobuf_EnumDescriptorProto_EnumReservedRange__Output)[]; + 'reservedName': (string)[]; + 'visibility': (_google_protobuf_SymbolVisibility__Output); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/EnumOptions.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/EnumOptions.ts new file mode 100644 index 0000000..b8361ba --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/EnumOptions.ts @@ -0,0 +1,26 @@ +// Original file: null + +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from '../../google/protobuf/FeatureSet'; +import type { UninterpretedOption as _google_protobuf_UninterpretedOption, UninterpretedOption__Output as _google_protobuf_UninterpretedOption__Output } from '../../google/protobuf/UninterpretedOption'; + +export interface EnumOptions { + 'allowAlias'?: (boolean); + 'deprecated'?: (boolean); + /** + * @deprecated + */ + 'deprecatedLegacyJsonFieldConflicts'?: (boolean); + 'features'?: (_google_protobuf_FeatureSet | null); + 'uninterpretedOption'?: (_google_protobuf_UninterpretedOption)[]; +} + +export interface EnumOptions__Output { + 'allowAlias': (boolean); + 'deprecated': (boolean); + /** + * @deprecated + */ + 'deprecatedLegacyJsonFieldConflicts': (boolean); + 'features': (_google_protobuf_FeatureSet__Output | null); + 'uninterpretedOption': (_google_protobuf_UninterpretedOption__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/EnumValueDescriptorProto.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/EnumValueDescriptorProto.ts new file mode 100644 index 0000000..7f8e57e --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/EnumValueDescriptorProto.ts @@ -0,0 +1,15 @@ +// Original file: null + +import type { EnumValueOptions as _google_protobuf_EnumValueOptions, EnumValueOptions__Output as _google_protobuf_EnumValueOptions__Output } from '../../google/protobuf/EnumValueOptions'; + +export interface EnumValueDescriptorProto { + 'name'?: (string); + 'number'?: (number); + 'options'?: (_google_protobuf_EnumValueOptions | null); +} + +export interface EnumValueDescriptorProto__Output { + 'name': (string); + 'number': (number); + 'options': (_google_protobuf_EnumValueOptions__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/EnumValueOptions.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/EnumValueOptions.ts new file mode 100644 index 0000000..d9290c5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/EnumValueOptions.ts @@ -0,0 +1,21 @@ +// Original file: null + +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from '../../google/protobuf/FeatureSet'; +import type { _google_protobuf_FieldOptions_FeatureSupport, _google_protobuf_FieldOptions_FeatureSupport__Output } from '../../google/protobuf/FieldOptions'; +import type { UninterpretedOption as _google_protobuf_UninterpretedOption, UninterpretedOption__Output as _google_protobuf_UninterpretedOption__Output } from '../../google/protobuf/UninterpretedOption'; + +export interface EnumValueOptions { + 'deprecated'?: (boolean); + 'features'?: (_google_protobuf_FeatureSet | null); + 'debugRedact'?: (boolean); + 'featureSupport'?: (_google_protobuf_FieldOptions_FeatureSupport | null); + 'uninterpretedOption'?: (_google_protobuf_UninterpretedOption)[]; +} + +export interface EnumValueOptions__Output { + 'deprecated': (boolean); + 'features': (_google_protobuf_FeatureSet__Output | null); + 'debugRedact': (boolean); + 'featureSupport': (_google_protobuf_FieldOptions_FeatureSupport__Output | null); + 'uninterpretedOption': (_google_protobuf_UninterpretedOption__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/ExtensionRangeOptions.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/ExtensionRangeOptions.ts new file mode 100644 index 0000000..4ca4c20 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/ExtensionRangeOptions.ts @@ -0,0 +1,49 @@ +// Original file: null + +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from '../../google/protobuf/FeatureSet'; +import type { UninterpretedOption as _google_protobuf_UninterpretedOption, UninterpretedOption__Output as _google_protobuf_UninterpretedOption__Output } from '../../google/protobuf/UninterpretedOption'; + +export interface _google_protobuf_ExtensionRangeOptions_Declaration { + 'number'?: (number); + 'fullName'?: (string); + 'type'?: (string); + 'reserved'?: (boolean); + 'repeated'?: (boolean); +} + +export interface _google_protobuf_ExtensionRangeOptions_Declaration__Output { + 'number': (number); + 'fullName': (string); + 'type': (string); + 'reserved': (boolean); + 'repeated': (boolean); +} + +// Original file: null + +export const _google_protobuf_ExtensionRangeOptions_VerificationState = { + DECLARATION: 'DECLARATION', + UNVERIFIED: 'UNVERIFIED', +} as const; + +export type _google_protobuf_ExtensionRangeOptions_VerificationState = + | 'DECLARATION' + | 0 + | 'UNVERIFIED' + | 1 + +export type _google_protobuf_ExtensionRangeOptions_VerificationState__Output = typeof _google_protobuf_ExtensionRangeOptions_VerificationState[keyof typeof _google_protobuf_ExtensionRangeOptions_VerificationState] + +export interface ExtensionRangeOptions { + 'declaration'?: (_google_protobuf_ExtensionRangeOptions_Declaration)[]; + 'verification'?: (_google_protobuf_ExtensionRangeOptions_VerificationState); + 'features'?: (_google_protobuf_FeatureSet | null); + 'uninterpretedOption'?: (_google_protobuf_UninterpretedOption)[]; +} + +export interface ExtensionRangeOptions__Output { + 'declaration': (_google_protobuf_ExtensionRangeOptions_Declaration__Output)[]; + 'verification': (_google_protobuf_ExtensionRangeOptions_VerificationState__Output); + 'features': (_google_protobuf_FeatureSet__Output | null); + 'uninterpretedOption': (_google_protobuf_UninterpretedOption__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FeatureSet.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FeatureSet.ts new file mode 100644 index 0000000..41ba7b1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FeatureSet.ts @@ -0,0 +1,183 @@ +// Original file: null + + +// Original file: null + +export const _google_protobuf_FeatureSet_VisibilityFeature_DefaultSymbolVisibility = { + DEFAULT_SYMBOL_VISIBILITY_UNKNOWN: 'DEFAULT_SYMBOL_VISIBILITY_UNKNOWN', + EXPORT_ALL: 'EXPORT_ALL', + EXPORT_TOP_LEVEL: 'EXPORT_TOP_LEVEL', + LOCAL_ALL: 'LOCAL_ALL', + STRICT: 'STRICT', +} as const; + +export type _google_protobuf_FeatureSet_VisibilityFeature_DefaultSymbolVisibility = + | 'DEFAULT_SYMBOL_VISIBILITY_UNKNOWN' + | 0 + | 'EXPORT_ALL' + | 1 + | 'EXPORT_TOP_LEVEL' + | 2 + | 'LOCAL_ALL' + | 3 + | 'STRICT' + | 4 + +export type _google_protobuf_FeatureSet_VisibilityFeature_DefaultSymbolVisibility__Output = typeof _google_protobuf_FeatureSet_VisibilityFeature_DefaultSymbolVisibility[keyof typeof _google_protobuf_FeatureSet_VisibilityFeature_DefaultSymbolVisibility] + +// Original file: null + +export const _google_protobuf_FeatureSet_EnforceNamingStyle = { + ENFORCE_NAMING_STYLE_UNKNOWN: 'ENFORCE_NAMING_STYLE_UNKNOWN', + STYLE2024: 'STYLE2024', + STYLE_LEGACY: 'STYLE_LEGACY', +} as const; + +export type _google_protobuf_FeatureSet_EnforceNamingStyle = + | 'ENFORCE_NAMING_STYLE_UNKNOWN' + | 0 + | 'STYLE2024' + | 1 + | 'STYLE_LEGACY' + | 2 + +export type _google_protobuf_FeatureSet_EnforceNamingStyle__Output = typeof _google_protobuf_FeatureSet_EnforceNamingStyle[keyof typeof _google_protobuf_FeatureSet_EnforceNamingStyle] + +// Original file: null + +export const _google_protobuf_FeatureSet_EnumType = { + ENUM_TYPE_UNKNOWN: 'ENUM_TYPE_UNKNOWN', + OPEN: 'OPEN', + CLOSED: 'CLOSED', +} as const; + +export type _google_protobuf_FeatureSet_EnumType = + | 'ENUM_TYPE_UNKNOWN' + | 0 + | 'OPEN' + | 1 + | 'CLOSED' + | 2 + +export type _google_protobuf_FeatureSet_EnumType__Output = typeof _google_protobuf_FeatureSet_EnumType[keyof typeof _google_protobuf_FeatureSet_EnumType] + +// Original file: null + +export const _google_protobuf_FeatureSet_FieldPresence = { + FIELD_PRESENCE_UNKNOWN: 'FIELD_PRESENCE_UNKNOWN', + EXPLICIT: 'EXPLICIT', + IMPLICIT: 'IMPLICIT', + LEGACY_REQUIRED: 'LEGACY_REQUIRED', +} as const; + +export type _google_protobuf_FeatureSet_FieldPresence = + | 'FIELD_PRESENCE_UNKNOWN' + | 0 + | 'EXPLICIT' + | 1 + | 'IMPLICIT' + | 2 + | 'LEGACY_REQUIRED' + | 3 + +export type _google_protobuf_FeatureSet_FieldPresence__Output = typeof _google_protobuf_FeatureSet_FieldPresence[keyof typeof _google_protobuf_FeatureSet_FieldPresence] + +// Original file: null + +export const _google_protobuf_FeatureSet_JsonFormat = { + JSON_FORMAT_UNKNOWN: 'JSON_FORMAT_UNKNOWN', + ALLOW: 'ALLOW', + LEGACY_BEST_EFFORT: 'LEGACY_BEST_EFFORT', +} as const; + +export type _google_protobuf_FeatureSet_JsonFormat = + | 'JSON_FORMAT_UNKNOWN' + | 0 + | 'ALLOW' + | 1 + | 'LEGACY_BEST_EFFORT' + | 2 + +export type _google_protobuf_FeatureSet_JsonFormat__Output = typeof _google_protobuf_FeatureSet_JsonFormat[keyof typeof _google_protobuf_FeatureSet_JsonFormat] + +// Original file: null + +export const _google_protobuf_FeatureSet_MessageEncoding = { + MESSAGE_ENCODING_UNKNOWN: 'MESSAGE_ENCODING_UNKNOWN', + LENGTH_PREFIXED: 'LENGTH_PREFIXED', + DELIMITED: 'DELIMITED', +} as const; + +export type _google_protobuf_FeatureSet_MessageEncoding = + | 'MESSAGE_ENCODING_UNKNOWN' + | 0 + | 'LENGTH_PREFIXED' + | 1 + | 'DELIMITED' + | 2 + +export type _google_protobuf_FeatureSet_MessageEncoding__Output = typeof _google_protobuf_FeatureSet_MessageEncoding[keyof typeof _google_protobuf_FeatureSet_MessageEncoding] + +// Original file: null + +export const _google_protobuf_FeatureSet_RepeatedFieldEncoding = { + REPEATED_FIELD_ENCODING_UNKNOWN: 'REPEATED_FIELD_ENCODING_UNKNOWN', + PACKED: 'PACKED', + EXPANDED: 'EXPANDED', +} as const; + +export type _google_protobuf_FeatureSet_RepeatedFieldEncoding = + | 'REPEATED_FIELD_ENCODING_UNKNOWN' + | 0 + | 'PACKED' + | 1 + | 'EXPANDED' + | 2 + +export type _google_protobuf_FeatureSet_RepeatedFieldEncoding__Output = typeof _google_protobuf_FeatureSet_RepeatedFieldEncoding[keyof typeof _google_protobuf_FeatureSet_RepeatedFieldEncoding] + +// Original file: null + +export const _google_protobuf_FeatureSet_Utf8Validation = { + UTF8_VALIDATION_UNKNOWN: 'UTF8_VALIDATION_UNKNOWN', + VERIFY: 'VERIFY', + NONE: 'NONE', +} as const; + +export type _google_protobuf_FeatureSet_Utf8Validation = + | 'UTF8_VALIDATION_UNKNOWN' + | 0 + | 'VERIFY' + | 2 + | 'NONE' + | 3 + +export type _google_protobuf_FeatureSet_Utf8Validation__Output = typeof _google_protobuf_FeatureSet_Utf8Validation[keyof typeof _google_protobuf_FeatureSet_Utf8Validation] + +export interface _google_protobuf_FeatureSet_VisibilityFeature { +} + +export interface _google_protobuf_FeatureSet_VisibilityFeature__Output { +} + +export interface FeatureSet { + 'fieldPresence'?: (_google_protobuf_FeatureSet_FieldPresence); + 'enumType'?: (_google_protobuf_FeatureSet_EnumType); + 'repeatedFieldEncoding'?: (_google_protobuf_FeatureSet_RepeatedFieldEncoding); + 'utf8Validation'?: (_google_protobuf_FeatureSet_Utf8Validation); + 'messageEncoding'?: (_google_protobuf_FeatureSet_MessageEncoding); + 'jsonFormat'?: (_google_protobuf_FeatureSet_JsonFormat); + 'enforceNamingStyle'?: (_google_protobuf_FeatureSet_EnforceNamingStyle); + 'defaultSymbolVisibility'?: (_google_protobuf_FeatureSet_VisibilityFeature_DefaultSymbolVisibility); +} + +export interface FeatureSet__Output { + 'fieldPresence': (_google_protobuf_FeatureSet_FieldPresence__Output); + 'enumType': (_google_protobuf_FeatureSet_EnumType__Output); + 'repeatedFieldEncoding': (_google_protobuf_FeatureSet_RepeatedFieldEncoding__Output); + 'utf8Validation': (_google_protobuf_FeatureSet_Utf8Validation__Output); + 'messageEncoding': (_google_protobuf_FeatureSet_MessageEncoding__Output); + 'jsonFormat': (_google_protobuf_FeatureSet_JsonFormat__Output); + 'enforceNamingStyle': (_google_protobuf_FeatureSet_EnforceNamingStyle__Output); + 'defaultSymbolVisibility': (_google_protobuf_FeatureSet_VisibilityFeature_DefaultSymbolVisibility__Output); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FeatureSetDefaults.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FeatureSetDefaults.ts new file mode 100644 index 0000000..64c55bf --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FeatureSetDefaults.ts @@ -0,0 +1,28 @@ +// Original file: null + +import type { Edition as _google_protobuf_Edition, Edition__Output as _google_protobuf_Edition__Output } from '../../google/protobuf/Edition'; +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from '../../google/protobuf/FeatureSet'; + +export interface _google_protobuf_FeatureSetDefaults_FeatureSetEditionDefault { + 'edition'?: (_google_protobuf_Edition); + 'overridableFeatures'?: (_google_protobuf_FeatureSet | null); + 'fixedFeatures'?: (_google_protobuf_FeatureSet | null); +} + +export interface _google_protobuf_FeatureSetDefaults_FeatureSetEditionDefault__Output { + 'edition': (_google_protobuf_Edition__Output); + 'overridableFeatures': (_google_protobuf_FeatureSet__Output | null); + 'fixedFeatures': (_google_protobuf_FeatureSet__Output | null); +} + +export interface FeatureSetDefaults { + 'defaults'?: (_google_protobuf_FeatureSetDefaults_FeatureSetEditionDefault)[]; + 'minimumEdition'?: (_google_protobuf_Edition); + 'maximumEdition'?: (_google_protobuf_Edition); +} + +export interface FeatureSetDefaults__Output { + 'defaults': (_google_protobuf_FeatureSetDefaults_FeatureSetEditionDefault__Output)[]; + 'minimumEdition': (_google_protobuf_Edition__Output); + 'maximumEdition': (_google_protobuf_Edition__Output); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FieldDescriptorProto.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FieldDescriptorProto.ts new file mode 100644 index 0000000..5a5687c --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FieldDescriptorProto.ts @@ -0,0 +1,112 @@ +// Original file: null + +import type { FieldOptions as _google_protobuf_FieldOptions, FieldOptions__Output as _google_protobuf_FieldOptions__Output } from '../../google/protobuf/FieldOptions'; + +// Original file: null + +export const _google_protobuf_FieldDescriptorProto_Label = { + LABEL_OPTIONAL: 'LABEL_OPTIONAL', + LABEL_REPEATED: 'LABEL_REPEATED', + LABEL_REQUIRED: 'LABEL_REQUIRED', +} as const; + +export type _google_protobuf_FieldDescriptorProto_Label = + | 'LABEL_OPTIONAL' + | 1 + | 'LABEL_REPEATED' + | 3 + | 'LABEL_REQUIRED' + | 2 + +export type _google_protobuf_FieldDescriptorProto_Label__Output = typeof _google_protobuf_FieldDescriptorProto_Label[keyof typeof _google_protobuf_FieldDescriptorProto_Label] + +// Original file: null + +export const _google_protobuf_FieldDescriptorProto_Type = { + TYPE_DOUBLE: 'TYPE_DOUBLE', + TYPE_FLOAT: 'TYPE_FLOAT', + TYPE_INT64: 'TYPE_INT64', + TYPE_UINT64: 'TYPE_UINT64', + TYPE_INT32: 'TYPE_INT32', + TYPE_FIXED64: 'TYPE_FIXED64', + TYPE_FIXED32: 'TYPE_FIXED32', + TYPE_BOOL: 'TYPE_BOOL', + TYPE_STRING: 'TYPE_STRING', + TYPE_GROUP: 'TYPE_GROUP', + TYPE_MESSAGE: 'TYPE_MESSAGE', + TYPE_BYTES: 'TYPE_BYTES', + TYPE_UINT32: 'TYPE_UINT32', + TYPE_ENUM: 'TYPE_ENUM', + TYPE_SFIXED32: 'TYPE_SFIXED32', + TYPE_SFIXED64: 'TYPE_SFIXED64', + TYPE_SINT32: 'TYPE_SINT32', + TYPE_SINT64: 'TYPE_SINT64', +} as const; + +export type _google_protobuf_FieldDescriptorProto_Type = + | 'TYPE_DOUBLE' + | 1 + | 'TYPE_FLOAT' + | 2 + | 'TYPE_INT64' + | 3 + | 'TYPE_UINT64' + | 4 + | 'TYPE_INT32' + | 5 + | 'TYPE_FIXED64' + | 6 + | 'TYPE_FIXED32' + | 7 + | 'TYPE_BOOL' + | 8 + | 'TYPE_STRING' + | 9 + | 'TYPE_GROUP' + | 10 + | 'TYPE_MESSAGE' + | 11 + | 'TYPE_BYTES' + | 12 + | 'TYPE_UINT32' + | 13 + | 'TYPE_ENUM' + | 14 + | 'TYPE_SFIXED32' + | 15 + | 'TYPE_SFIXED64' + | 16 + | 'TYPE_SINT32' + | 17 + | 'TYPE_SINT64' + | 18 + +export type _google_protobuf_FieldDescriptorProto_Type__Output = typeof _google_protobuf_FieldDescriptorProto_Type[keyof typeof _google_protobuf_FieldDescriptorProto_Type] + +export interface FieldDescriptorProto { + 'name'?: (string); + 'extendee'?: (string); + 'number'?: (number); + 'label'?: (_google_protobuf_FieldDescriptorProto_Label); + 'type'?: (_google_protobuf_FieldDescriptorProto_Type); + 'typeName'?: (string); + 'defaultValue'?: (string); + 'options'?: (_google_protobuf_FieldOptions | null); + 'oneofIndex'?: (number); + 'jsonName'?: (string); + 'proto3Optional'?: (boolean); +} + +export interface FieldDescriptorProto__Output { + 'name': (string); + 'extendee': (string); + 'number': (number); + 'label': (_google_protobuf_FieldDescriptorProto_Label__Output); + 'type': (_google_protobuf_FieldDescriptorProto_Type__Output); + 'typeName': (string); + 'defaultValue': (string); + 'options': (_google_protobuf_FieldOptions__Output | null); + 'oneofIndex': (number); + 'jsonName': (string); + 'proto3Optional': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FieldOptions.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FieldOptions.ts new file mode 100644 index 0000000..dc5d85c --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FieldOptions.ts @@ -0,0 +1,165 @@ +// Original file: null + +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from '../../google/protobuf/FeatureSet'; +import type { UninterpretedOption as _google_protobuf_UninterpretedOption, UninterpretedOption__Output as _google_protobuf_UninterpretedOption__Output } from '../../google/protobuf/UninterpretedOption'; +import type { FieldRules as _validate_FieldRules, FieldRules__Output as _validate_FieldRules__Output } from '../../validate/FieldRules'; +import type { Edition as _google_protobuf_Edition, Edition__Output as _google_protobuf_Edition__Output } from '../../google/protobuf/Edition'; + +// Original file: null + +export const _google_protobuf_FieldOptions_CType = { + STRING: 'STRING', + CORD: 'CORD', + STRING_PIECE: 'STRING_PIECE', +} as const; + +export type _google_protobuf_FieldOptions_CType = + | 'STRING' + | 0 + | 'CORD' + | 1 + | 'STRING_PIECE' + | 2 + +export type _google_protobuf_FieldOptions_CType__Output = typeof _google_protobuf_FieldOptions_CType[keyof typeof _google_protobuf_FieldOptions_CType] + +export interface _google_protobuf_FieldOptions_EditionDefault { + 'edition'?: (_google_protobuf_Edition); + 'value'?: (string); +} + +export interface _google_protobuf_FieldOptions_EditionDefault__Output { + 'edition': (_google_protobuf_Edition__Output); + 'value': (string); +} + +export interface _google_protobuf_FieldOptions_FeatureSupport { + 'editionIntroduced'?: (_google_protobuf_Edition); + 'editionDeprecated'?: (_google_protobuf_Edition); + 'deprecationWarning'?: (string); + 'editionRemoved'?: (_google_protobuf_Edition); +} + +export interface _google_protobuf_FieldOptions_FeatureSupport__Output { + 'editionIntroduced': (_google_protobuf_Edition__Output); + 'editionDeprecated': (_google_protobuf_Edition__Output); + 'deprecationWarning': (string); + 'editionRemoved': (_google_protobuf_Edition__Output); +} + +// Original file: null + +export const _google_protobuf_FieldOptions_JSType = { + JS_NORMAL: 'JS_NORMAL', + JS_STRING: 'JS_STRING', + JS_NUMBER: 'JS_NUMBER', +} as const; + +export type _google_protobuf_FieldOptions_JSType = + | 'JS_NORMAL' + | 0 + | 'JS_STRING' + | 1 + | 'JS_NUMBER' + | 2 + +export type _google_protobuf_FieldOptions_JSType__Output = typeof _google_protobuf_FieldOptions_JSType[keyof typeof _google_protobuf_FieldOptions_JSType] + +// Original file: null + +export const _google_protobuf_FieldOptions_OptionRetention = { + RETENTION_UNKNOWN: 'RETENTION_UNKNOWN', + RETENTION_RUNTIME: 'RETENTION_RUNTIME', + RETENTION_SOURCE: 'RETENTION_SOURCE', +} as const; + +export type _google_protobuf_FieldOptions_OptionRetention = + | 'RETENTION_UNKNOWN' + | 0 + | 'RETENTION_RUNTIME' + | 1 + | 'RETENTION_SOURCE' + | 2 + +export type _google_protobuf_FieldOptions_OptionRetention__Output = typeof _google_protobuf_FieldOptions_OptionRetention[keyof typeof _google_protobuf_FieldOptions_OptionRetention] + +// Original file: null + +export const _google_protobuf_FieldOptions_OptionTargetType = { + TARGET_TYPE_UNKNOWN: 'TARGET_TYPE_UNKNOWN', + TARGET_TYPE_FILE: 'TARGET_TYPE_FILE', + TARGET_TYPE_EXTENSION_RANGE: 'TARGET_TYPE_EXTENSION_RANGE', + TARGET_TYPE_MESSAGE: 'TARGET_TYPE_MESSAGE', + TARGET_TYPE_FIELD: 'TARGET_TYPE_FIELD', + TARGET_TYPE_ONEOF: 'TARGET_TYPE_ONEOF', + TARGET_TYPE_ENUM: 'TARGET_TYPE_ENUM', + TARGET_TYPE_ENUM_ENTRY: 'TARGET_TYPE_ENUM_ENTRY', + TARGET_TYPE_SERVICE: 'TARGET_TYPE_SERVICE', + TARGET_TYPE_METHOD: 'TARGET_TYPE_METHOD', +} as const; + +export type _google_protobuf_FieldOptions_OptionTargetType = + | 'TARGET_TYPE_UNKNOWN' + | 0 + | 'TARGET_TYPE_FILE' + | 1 + | 'TARGET_TYPE_EXTENSION_RANGE' + | 2 + | 'TARGET_TYPE_MESSAGE' + | 3 + | 'TARGET_TYPE_FIELD' + | 4 + | 'TARGET_TYPE_ONEOF' + | 5 + | 'TARGET_TYPE_ENUM' + | 6 + | 'TARGET_TYPE_ENUM_ENTRY' + | 7 + | 'TARGET_TYPE_SERVICE' + | 8 + | 'TARGET_TYPE_METHOD' + | 9 + +export type _google_protobuf_FieldOptions_OptionTargetType__Output = typeof _google_protobuf_FieldOptions_OptionTargetType[keyof typeof _google_protobuf_FieldOptions_OptionTargetType] + +export interface FieldOptions { + 'ctype'?: (_google_protobuf_FieldOptions_CType); + 'packed'?: (boolean); + 'deprecated'?: (boolean); + 'lazy'?: (boolean); + 'jstype'?: (_google_protobuf_FieldOptions_JSType); + /** + * @deprecated + */ + 'weak'?: (boolean); + 'unverifiedLazy'?: (boolean); + 'debugRedact'?: (boolean); + 'retention'?: (_google_protobuf_FieldOptions_OptionRetention); + 'targets'?: (_google_protobuf_FieldOptions_OptionTargetType)[]; + 'editionDefaults'?: (_google_protobuf_FieldOptions_EditionDefault)[]; + 'features'?: (_google_protobuf_FeatureSet | null); + 'featureSupport'?: (_google_protobuf_FieldOptions_FeatureSupport | null); + 'uninterpretedOption'?: (_google_protobuf_UninterpretedOption)[]; + '.validate.rules'?: (_validate_FieldRules | null); +} + +export interface FieldOptions__Output { + 'ctype': (_google_protobuf_FieldOptions_CType__Output); + 'packed': (boolean); + 'deprecated': (boolean); + 'lazy': (boolean); + 'jstype': (_google_protobuf_FieldOptions_JSType__Output); + /** + * @deprecated + */ + 'weak': (boolean); + 'unverifiedLazy': (boolean); + 'debugRedact': (boolean); + 'retention': (_google_protobuf_FieldOptions_OptionRetention__Output); + 'targets': (_google_protobuf_FieldOptions_OptionTargetType__Output)[]; + 'editionDefaults': (_google_protobuf_FieldOptions_EditionDefault__Output)[]; + 'features': (_google_protobuf_FeatureSet__Output | null); + 'featureSupport': (_google_protobuf_FieldOptions_FeatureSupport__Output | null); + 'uninterpretedOption': (_google_protobuf_UninterpretedOption__Output)[]; + '.validate.rules': (_validate_FieldRules__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FileDescriptorProto.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FileDescriptorProto.ts new file mode 100644 index 0000000..ef4c8ca --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FileDescriptorProto.ts @@ -0,0 +1,43 @@ +// Original file: null + +import type { DescriptorProto as _google_protobuf_DescriptorProto, DescriptorProto__Output as _google_protobuf_DescriptorProto__Output } from '../../google/protobuf/DescriptorProto'; +import type { EnumDescriptorProto as _google_protobuf_EnumDescriptorProto, EnumDescriptorProto__Output as _google_protobuf_EnumDescriptorProto__Output } from '../../google/protobuf/EnumDescriptorProto'; +import type { ServiceDescriptorProto as _google_protobuf_ServiceDescriptorProto, ServiceDescriptorProto__Output as _google_protobuf_ServiceDescriptorProto__Output } from '../../google/protobuf/ServiceDescriptorProto'; +import type { FieldDescriptorProto as _google_protobuf_FieldDescriptorProto, FieldDescriptorProto__Output as _google_protobuf_FieldDescriptorProto__Output } from '../../google/protobuf/FieldDescriptorProto'; +import type { FileOptions as _google_protobuf_FileOptions, FileOptions__Output as _google_protobuf_FileOptions__Output } from '../../google/protobuf/FileOptions'; +import type { SourceCodeInfo as _google_protobuf_SourceCodeInfo, SourceCodeInfo__Output as _google_protobuf_SourceCodeInfo__Output } from '../../google/protobuf/SourceCodeInfo'; +import type { Edition as _google_protobuf_Edition, Edition__Output as _google_protobuf_Edition__Output } from '../../google/protobuf/Edition'; + +export interface FileDescriptorProto { + 'name'?: (string); + 'package'?: (string); + 'dependency'?: (string)[]; + 'messageType'?: (_google_protobuf_DescriptorProto)[]; + 'enumType'?: (_google_protobuf_EnumDescriptorProto)[]; + 'service'?: (_google_protobuf_ServiceDescriptorProto)[]; + 'extension'?: (_google_protobuf_FieldDescriptorProto)[]; + 'options'?: (_google_protobuf_FileOptions | null); + 'sourceCodeInfo'?: (_google_protobuf_SourceCodeInfo | null); + 'publicDependency'?: (number)[]; + 'weakDependency'?: (number)[]; + 'syntax'?: (string); + 'edition'?: (_google_protobuf_Edition); + 'optionDependency'?: (string)[]; +} + +export interface FileDescriptorProto__Output { + 'name': (string); + 'package': (string); + 'dependency': (string)[]; + 'messageType': (_google_protobuf_DescriptorProto__Output)[]; + 'enumType': (_google_protobuf_EnumDescriptorProto__Output)[]; + 'service': (_google_protobuf_ServiceDescriptorProto__Output)[]; + 'extension': (_google_protobuf_FieldDescriptorProto__Output)[]; + 'options': (_google_protobuf_FileOptions__Output | null); + 'sourceCodeInfo': (_google_protobuf_SourceCodeInfo__Output | null); + 'publicDependency': (number)[]; + 'weakDependency': (number)[]; + 'syntax': (string); + 'edition': (_google_protobuf_Edition__Output); + 'optionDependency': (string)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FileDescriptorSet.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FileDescriptorSet.ts new file mode 100644 index 0000000..74ded24 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FileDescriptorSet.ts @@ -0,0 +1,11 @@ +// Original file: null + +import type { FileDescriptorProto as _google_protobuf_FileDescriptorProto, FileDescriptorProto__Output as _google_protobuf_FileDescriptorProto__Output } from '../../google/protobuf/FileDescriptorProto'; + +export interface FileDescriptorSet { + 'file'?: (_google_protobuf_FileDescriptorProto)[]; +} + +export interface FileDescriptorSet__Output { + 'file': (_google_protobuf_FileDescriptorProto__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FileOptions.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FileOptions.ts new file mode 100644 index 0000000..f240757 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FileOptions.ts @@ -0,0 +1,76 @@ +// Original file: null + +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from '../../google/protobuf/FeatureSet'; +import type { UninterpretedOption as _google_protobuf_UninterpretedOption, UninterpretedOption__Output as _google_protobuf_UninterpretedOption__Output } from '../../google/protobuf/UninterpretedOption'; + +// Original file: null + +export const _google_protobuf_FileOptions_OptimizeMode = { + SPEED: 'SPEED', + CODE_SIZE: 'CODE_SIZE', + LITE_RUNTIME: 'LITE_RUNTIME', +} as const; + +export type _google_protobuf_FileOptions_OptimizeMode = + | 'SPEED' + | 1 + | 'CODE_SIZE' + | 2 + | 'LITE_RUNTIME' + | 3 + +export type _google_protobuf_FileOptions_OptimizeMode__Output = typeof _google_protobuf_FileOptions_OptimizeMode[keyof typeof _google_protobuf_FileOptions_OptimizeMode] + +export interface FileOptions { + 'javaPackage'?: (string); + 'javaOuterClassname'?: (string); + 'optimizeFor'?: (_google_protobuf_FileOptions_OptimizeMode); + 'javaMultipleFiles'?: (boolean); + 'goPackage'?: (string); + 'ccGenericServices'?: (boolean); + 'javaGenericServices'?: (boolean); + 'pyGenericServices'?: (boolean); + /** + * @deprecated + */ + 'javaGenerateEqualsAndHash'?: (boolean); + 'deprecated'?: (boolean); + 'javaStringCheckUtf8'?: (boolean); + 'ccEnableArenas'?: (boolean); + 'objcClassPrefix'?: (string); + 'csharpNamespace'?: (string); + 'swiftPrefix'?: (string); + 'phpClassPrefix'?: (string); + 'phpNamespace'?: (string); + 'phpMetadataNamespace'?: (string); + 'rubyPackage'?: (string); + 'features'?: (_google_protobuf_FeatureSet | null); + 'uninterpretedOption'?: (_google_protobuf_UninterpretedOption)[]; +} + +export interface FileOptions__Output { + 'javaPackage': (string); + 'javaOuterClassname': (string); + 'optimizeFor': (_google_protobuf_FileOptions_OptimizeMode__Output); + 'javaMultipleFiles': (boolean); + 'goPackage': (string); + 'ccGenericServices': (boolean); + 'javaGenericServices': (boolean); + 'pyGenericServices': (boolean); + /** + * @deprecated + */ + 'javaGenerateEqualsAndHash': (boolean); + 'deprecated': (boolean); + 'javaStringCheckUtf8': (boolean); + 'ccEnableArenas': (boolean); + 'objcClassPrefix': (string); + 'csharpNamespace': (string); + 'swiftPrefix': (string); + 'phpClassPrefix': (string); + 'phpNamespace': (string); + 'phpMetadataNamespace': (string); + 'rubyPackage': (string); + 'features': (_google_protobuf_FeatureSet__Output | null); + 'uninterpretedOption': (_google_protobuf_UninterpretedOption__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FloatValue.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FloatValue.ts new file mode 100644 index 0000000..54a655f --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FloatValue.ts @@ -0,0 +1,10 @@ +// Original file: null + + +export interface FloatValue { + 'value'?: (number | string); +} + +export interface FloatValue__Output { + 'value': (number); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/GeneratedCodeInfo.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/GeneratedCodeInfo.ts new file mode 100644 index 0000000..55d506f --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/GeneratedCodeInfo.ts @@ -0,0 +1,44 @@ +// Original file: null + + +export interface _google_protobuf_GeneratedCodeInfo_Annotation { + 'path'?: (number)[]; + 'sourceFile'?: (string); + 'begin'?: (number); + 'end'?: (number); + 'semantic'?: (_google_protobuf_GeneratedCodeInfo_Annotation_Semantic); +} + +export interface _google_protobuf_GeneratedCodeInfo_Annotation__Output { + 'path': (number)[]; + 'sourceFile': (string); + 'begin': (number); + 'end': (number); + 'semantic': (_google_protobuf_GeneratedCodeInfo_Annotation_Semantic__Output); +} + +// Original file: null + +export const _google_protobuf_GeneratedCodeInfo_Annotation_Semantic = { + NONE: 'NONE', + SET: 'SET', + ALIAS: 'ALIAS', +} as const; + +export type _google_protobuf_GeneratedCodeInfo_Annotation_Semantic = + | 'NONE' + | 0 + | 'SET' + | 1 + | 'ALIAS' + | 2 + +export type _google_protobuf_GeneratedCodeInfo_Annotation_Semantic__Output = typeof _google_protobuf_GeneratedCodeInfo_Annotation_Semantic[keyof typeof _google_protobuf_GeneratedCodeInfo_Annotation_Semantic] + +export interface GeneratedCodeInfo { + 'annotation'?: (_google_protobuf_GeneratedCodeInfo_Annotation)[]; +} + +export interface GeneratedCodeInfo__Output { + 'annotation': (_google_protobuf_GeneratedCodeInfo_Annotation__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Int32Value.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Int32Value.ts new file mode 100644 index 0000000..ec4eeb7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Int32Value.ts @@ -0,0 +1,10 @@ +// Original file: null + + +export interface Int32Value { + 'value'?: (number); +} + +export interface Int32Value__Output { + 'value': (number); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Int64Value.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Int64Value.ts new file mode 100644 index 0000000..f737519 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Int64Value.ts @@ -0,0 +1,11 @@ +// Original file: null + +import type { Long } from '@grpc/proto-loader'; + +export interface Int64Value { + 'value'?: (number | string | Long); +} + +export interface Int64Value__Output { + 'value': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/MessageOptions.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/MessageOptions.ts new file mode 100644 index 0000000..6d6d459 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/MessageOptions.ts @@ -0,0 +1,32 @@ +// Original file: null + +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from '../../google/protobuf/FeatureSet'; +import type { UninterpretedOption as _google_protobuf_UninterpretedOption, UninterpretedOption__Output as _google_protobuf_UninterpretedOption__Output } from '../../google/protobuf/UninterpretedOption'; + +export interface MessageOptions { + 'messageSetWireFormat'?: (boolean); + 'noStandardDescriptorAccessor'?: (boolean); + 'deprecated'?: (boolean); + 'mapEntry'?: (boolean); + /** + * @deprecated + */ + 'deprecatedLegacyJsonFieldConflicts'?: (boolean); + 'features'?: (_google_protobuf_FeatureSet | null); + 'uninterpretedOption'?: (_google_protobuf_UninterpretedOption)[]; + '.validate.disabled'?: (boolean); +} + +export interface MessageOptions__Output { + 'messageSetWireFormat': (boolean); + 'noStandardDescriptorAccessor': (boolean); + 'deprecated': (boolean); + 'mapEntry': (boolean); + /** + * @deprecated + */ + 'deprecatedLegacyJsonFieldConflicts': (boolean); + 'features': (_google_protobuf_FeatureSet__Output | null); + 'uninterpretedOption': (_google_protobuf_UninterpretedOption__Output)[]; + '.validate.disabled': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/MethodDescriptorProto.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/MethodDescriptorProto.ts new file mode 100644 index 0000000..c76c0ea --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/MethodDescriptorProto.ts @@ -0,0 +1,21 @@ +// Original file: null + +import type { MethodOptions as _google_protobuf_MethodOptions, MethodOptions__Output as _google_protobuf_MethodOptions__Output } from '../../google/protobuf/MethodOptions'; + +export interface MethodDescriptorProto { + 'name'?: (string); + 'inputType'?: (string); + 'outputType'?: (string); + 'options'?: (_google_protobuf_MethodOptions | null); + 'clientStreaming'?: (boolean); + 'serverStreaming'?: (boolean); +} + +export interface MethodDescriptorProto__Output { + 'name': (string); + 'inputType': (string); + 'outputType': (string); + 'options': (_google_protobuf_MethodOptions__Output | null); + 'clientStreaming': (boolean); + 'serverStreaming': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/MethodOptions.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/MethodOptions.ts new file mode 100644 index 0000000..5e5bf2f --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/MethodOptions.ts @@ -0,0 +1,36 @@ +// Original file: null + +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from '../../google/protobuf/FeatureSet'; +import type { UninterpretedOption as _google_protobuf_UninterpretedOption, UninterpretedOption__Output as _google_protobuf_UninterpretedOption__Output } from '../../google/protobuf/UninterpretedOption'; + +// Original file: null + +export const _google_protobuf_MethodOptions_IdempotencyLevel = { + IDEMPOTENCY_UNKNOWN: 'IDEMPOTENCY_UNKNOWN', + NO_SIDE_EFFECTS: 'NO_SIDE_EFFECTS', + IDEMPOTENT: 'IDEMPOTENT', +} as const; + +export type _google_protobuf_MethodOptions_IdempotencyLevel = + | 'IDEMPOTENCY_UNKNOWN' + | 0 + | 'NO_SIDE_EFFECTS' + | 1 + | 'IDEMPOTENT' + | 2 + +export type _google_protobuf_MethodOptions_IdempotencyLevel__Output = typeof _google_protobuf_MethodOptions_IdempotencyLevel[keyof typeof _google_protobuf_MethodOptions_IdempotencyLevel] + +export interface MethodOptions { + 'deprecated'?: (boolean); + 'idempotencyLevel'?: (_google_protobuf_MethodOptions_IdempotencyLevel); + 'features'?: (_google_protobuf_FeatureSet | null); + 'uninterpretedOption'?: (_google_protobuf_UninterpretedOption)[]; +} + +export interface MethodOptions__Output { + 'deprecated': (boolean); + 'idempotencyLevel': (_google_protobuf_MethodOptions_IdempotencyLevel__Output); + 'features': (_google_protobuf_FeatureSet__Output | null); + 'uninterpretedOption': (_google_protobuf_UninterpretedOption__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/OneofDescriptorProto.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/OneofDescriptorProto.ts new file mode 100644 index 0000000..636f13e --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/OneofDescriptorProto.ts @@ -0,0 +1,13 @@ +// Original file: null + +import type { OneofOptions as _google_protobuf_OneofOptions, OneofOptions__Output as _google_protobuf_OneofOptions__Output } from '../../google/protobuf/OneofOptions'; + +export interface OneofDescriptorProto { + 'name'?: (string); + 'options'?: (_google_protobuf_OneofOptions | null); +} + +export interface OneofDescriptorProto__Output { + 'name': (string); + 'options': (_google_protobuf_OneofOptions__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/OneofOptions.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/OneofOptions.ts new file mode 100644 index 0000000..a5cc624 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/OneofOptions.ts @@ -0,0 +1,16 @@ +// Original file: null + +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from '../../google/protobuf/FeatureSet'; +import type { UninterpretedOption as _google_protobuf_UninterpretedOption, UninterpretedOption__Output as _google_protobuf_UninterpretedOption__Output } from '../../google/protobuf/UninterpretedOption'; + +export interface OneofOptions { + 'features'?: (_google_protobuf_FeatureSet | null); + 'uninterpretedOption'?: (_google_protobuf_UninterpretedOption)[]; + '.validate.required'?: (boolean); +} + +export interface OneofOptions__Output { + 'features': (_google_protobuf_FeatureSet__Output | null); + 'uninterpretedOption': (_google_protobuf_UninterpretedOption__Output)[]; + '.validate.required': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/ServiceDescriptorProto.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/ServiceDescriptorProto.ts new file mode 100644 index 0000000..40c9263 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/ServiceDescriptorProto.ts @@ -0,0 +1,16 @@ +// Original file: null + +import type { MethodDescriptorProto as _google_protobuf_MethodDescriptorProto, MethodDescriptorProto__Output as _google_protobuf_MethodDescriptorProto__Output } from '../../google/protobuf/MethodDescriptorProto'; +import type { ServiceOptions as _google_protobuf_ServiceOptions, ServiceOptions__Output as _google_protobuf_ServiceOptions__Output } from '../../google/protobuf/ServiceOptions'; + +export interface ServiceDescriptorProto { + 'name'?: (string); + 'method'?: (_google_protobuf_MethodDescriptorProto)[]; + 'options'?: (_google_protobuf_ServiceOptions | null); +} + +export interface ServiceDescriptorProto__Output { + 'name': (string); + 'method': (_google_protobuf_MethodDescriptorProto__Output)[]; + 'options': (_google_protobuf_ServiceOptions__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/ServiceOptions.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/ServiceOptions.ts new file mode 100644 index 0000000..5e99f2b --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/ServiceOptions.ts @@ -0,0 +1,16 @@ +// Original file: null + +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from '../../google/protobuf/FeatureSet'; +import type { UninterpretedOption as _google_protobuf_UninterpretedOption, UninterpretedOption__Output as _google_protobuf_UninterpretedOption__Output } from '../../google/protobuf/UninterpretedOption'; + +export interface ServiceOptions { + 'deprecated'?: (boolean); + 'features'?: (_google_protobuf_FeatureSet | null); + 'uninterpretedOption'?: (_google_protobuf_UninterpretedOption)[]; +} + +export interface ServiceOptions__Output { + 'deprecated': (boolean); + 'features': (_google_protobuf_FeatureSet__Output | null); + 'uninterpretedOption': (_google_protobuf_UninterpretedOption__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/SourceCodeInfo.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/SourceCodeInfo.ts new file mode 100644 index 0000000..d30e59b --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/SourceCodeInfo.ts @@ -0,0 +1,26 @@ +// Original file: null + + +export interface _google_protobuf_SourceCodeInfo_Location { + 'path'?: (number)[]; + 'span'?: (number)[]; + 'leadingComments'?: (string); + 'trailingComments'?: (string); + 'leadingDetachedComments'?: (string)[]; +} + +export interface _google_protobuf_SourceCodeInfo_Location__Output { + 'path': (number)[]; + 'span': (number)[]; + 'leadingComments': (string); + 'trailingComments': (string); + 'leadingDetachedComments': (string)[]; +} + +export interface SourceCodeInfo { + 'location'?: (_google_protobuf_SourceCodeInfo_Location)[]; +} + +export interface SourceCodeInfo__Output { + 'location': (_google_protobuf_SourceCodeInfo_Location__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/StringValue.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/StringValue.ts new file mode 100644 index 0000000..673090e --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/StringValue.ts @@ -0,0 +1,10 @@ +// Original file: null + + +export interface StringValue { + 'value'?: (string); +} + +export interface StringValue__Output { + 'value': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/SymbolVisibility.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/SymbolVisibility.ts new file mode 100644 index 0000000..9ece164 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/SymbolVisibility.ts @@ -0,0 +1,17 @@ +// Original file: null + +export const SymbolVisibility = { + VISIBILITY_UNSET: 'VISIBILITY_UNSET', + VISIBILITY_LOCAL: 'VISIBILITY_LOCAL', + VISIBILITY_EXPORT: 'VISIBILITY_EXPORT', +} as const; + +export type SymbolVisibility = + | 'VISIBILITY_UNSET' + | 0 + | 'VISIBILITY_LOCAL' + | 1 + | 'VISIBILITY_EXPORT' + | 2 + +export type SymbolVisibility__Output = typeof SymbolVisibility[keyof typeof SymbolVisibility] diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Timestamp.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Timestamp.ts new file mode 100644 index 0000000..ceaa32b --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Timestamp.ts @@ -0,0 +1,13 @@ +// Original file: null + +import type { Long } from '@grpc/proto-loader'; + +export interface Timestamp { + 'seconds'?: (number | string | Long); + 'nanos'?: (number); +} + +export interface Timestamp__Output { + 'seconds': (string); + 'nanos': (number); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/UInt32Value.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/UInt32Value.ts new file mode 100644 index 0000000..973ab34 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/UInt32Value.ts @@ -0,0 +1,10 @@ +// Original file: null + + +export interface UInt32Value { + 'value'?: (number); +} + +export interface UInt32Value__Output { + 'value': (number); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/UInt64Value.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/UInt64Value.ts new file mode 100644 index 0000000..7a85c39 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/UInt64Value.ts @@ -0,0 +1,11 @@ +// Original file: null + +import type { Long } from '@grpc/proto-loader'; + +export interface UInt64Value { + 'value'?: (number | string | Long); +} + +export interface UInt64Value__Output { + 'value': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/UninterpretedOption.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/UninterpretedOption.ts new file mode 100644 index 0000000..6e9fc27 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/UninterpretedOption.ts @@ -0,0 +1,33 @@ +// Original file: null + +import type { Long } from '@grpc/proto-loader'; + +export interface _google_protobuf_UninterpretedOption_NamePart { + 'namePart'?: (string); + 'isExtension'?: (boolean); +} + +export interface _google_protobuf_UninterpretedOption_NamePart__Output { + 'namePart': (string); + 'isExtension': (boolean); +} + +export interface UninterpretedOption { + 'name'?: (_google_protobuf_UninterpretedOption_NamePart)[]; + 'identifierValue'?: (string); + 'positiveIntValue'?: (number | string | Long); + 'negativeIntValue'?: (number | string | Long); + 'doubleValue'?: (number | string); + 'stringValue'?: (Buffer | Uint8Array | string); + 'aggregateValue'?: (string); +} + +export interface UninterpretedOption__Output { + 'name': (_google_protobuf_UninterpretedOption_NamePart__Output)[]; + 'identifierValue': (string); + 'positiveIntValue': (string); + 'negativeIntValue': (string); + 'doubleValue': (number); + 'stringValue': (Buffer); + 'aggregateValue': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Address.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Address.ts new file mode 100644 index 0000000..01cf32b --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Address.ts @@ -0,0 +1,89 @@ +// Original file: proto/channelz.proto + +import type { Any as _google_protobuf_Any, Any__Output as _google_protobuf_Any__Output } from '../../../google/protobuf/Any'; + +/** + * An address type not included above. + */ +export interface _grpc_channelz_v1_Address_OtherAddress { + /** + * The human readable version of the value. This value should be set. + */ + 'name'?: (string); + /** + * The actual address message. + */ + 'value'?: (_google_protobuf_Any | null); +} + +/** + * An address type not included above. + */ +export interface _grpc_channelz_v1_Address_OtherAddress__Output { + /** + * The human readable version of the value. This value should be set. + */ + 'name': (string); + /** + * The actual address message. + */ + 'value': (_google_protobuf_Any__Output | null); +} + +export interface _grpc_channelz_v1_Address_TcpIpAddress { + /** + * Either the IPv4 or IPv6 address in bytes. Will be either 4 bytes or 16 + * bytes in length. + */ + 'ip_address'?: (Buffer | Uint8Array | string); + /** + * 0-64k, or -1 if not appropriate. + */ + 'port'?: (number); +} + +export interface _grpc_channelz_v1_Address_TcpIpAddress__Output { + /** + * Either the IPv4 or IPv6 address in bytes. Will be either 4 bytes or 16 + * bytes in length. + */ + 'ip_address': (Buffer); + /** + * 0-64k, or -1 if not appropriate. + */ + 'port': (number); +} + +/** + * A Unix Domain Socket address. + */ +export interface _grpc_channelz_v1_Address_UdsAddress { + 'filename'?: (string); +} + +/** + * A Unix Domain Socket address. + */ +export interface _grpc_channelz_v1_Address_UdsAddress__Output { + 'filename': (string); +} + +/** + * Address represents the address used to create the socket. + */ +export interface Address { + 'tcpip_address'?: (_grpc_channelz_v1_Address_TcpIpAddress | null); + 'uds_address'?: (_grpc_channelz_v1_Address_UdsAddress | null); + 'other_address'?: (_grpc_channelz_v1_Address_OtherAddress | null); + 'address'?: "tcpip_address"|"uds_address"|"other_address"; +} + +/** + * Address represents the address used to create the socket. + */ +export interface Address__Output { + 'tcpip_address'?: (_grpc_channelz_v1_Address_TcpIpAddress__Output | null); + 'uds_address'?: (_grpc_channelz_v1_Address_UdsAddress__Output | null); + 'other_address'?: (_grpc_channelz_v1_Address_OtherAddress__Output | null); + 'address'?: "tcpip_address"|"uds_address"|"other_address"; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Channel.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Channel.ts new file mode 100644 index 0000000..93b4a26 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Channel.ts @@ -0,0 +1,68 @@ +// Original file: proto/channelz.proto + +import type { ChannelRef as _grpc_channelz_v1_ChannelRef, ChannelRef__Output as _grpc_channelz_v1_ChannelRef__Output } from '../../../grpc/channelz/v1/ChannelRef'; +import type { ChannelData as _grpc_channelz_v1_ChannelData, ChannelData__Output as _grpc_channelz_v1_ChannelData__Output } from '../../../grpc/channelz/v1/ChannelData'; +import type { SubchannelRef as _grpc_channelz_v1_SubchannelRef, SubchannelRef__Output as _grpc_channelz_v1_SubchannelRef__Output } from '../../../grpc/channelz/v1/SubchannelRef'; +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from '../../../grpc/channelz/v1/SocketRef'; + +/** + * Channel is a logical grouping of channels, subchannels, and sockets. + */ +export interface Channel { + /** + * The identifier for this channel. This should bet set. + */ + 'ref'?: (_grpc_channelz_v1_ChannelRef | null); + /** + * Data specific to this channel. + */ + 'data'?: (_grpc_channelz_v1_ChannelData | null); + /** + * There are no ordering guarantees on the order of channel refs. + * There may not be cycles in the ref graph. + * A channel ref may be present in more than one channel or subchannel. + */ + 'channel_ref'?: (_grpc_channelz_v1_ChannelRef)[]; + /** + * At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + * There are no ordering guarantees on the order of subchannel refs. + * There may not be cycles in the ref graph. + * A sub channel ref may be present in more than one channel or subchannel. + */ + 'subchannel_ref'?: (_grpc_channelz_v1_SubchannelRef)[]; + /** + * There are no ordering guarantees on the order of sockets. + */ + 'socket_ref'?: (_grpc_channelz_v1_SocketRef)[]; +} + +/** + * Channel is a logical grouping of channels, subchannels, and sockets. + */ +export interface Channel__Output { + /** + * The identifier for this channel. This should bet set. + */ + 'ref': (_grpc_channelz_v1_ChannelRef__Output | null); + /** + * Data specific to this channel. + */ + 'data': (_grpc_channelz_v1_ChannelData__Output | null); + /** + * There are no ordering guarantees on the order of channel refs. + * There may not be cycles in the ref graph. + * A channel ref may be present in more than one channel or subchannel. + */ + 'channel_ref': (_grpc_channelz_v1_ChannelRef__Output)[]; + /** + * At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + * There are no ordering guarantees on the order of subchannel refs. + * There may not be cycles in the ref graph. + * A sub channel ref may be present in more than one channel or subchannel. + */ + 'subchannel_ref': (_grpc_channelz_v1_SubchannelRef__Output)[]; + /** + * There are no ordering guarantees on the order of sockets. + */ + 'socket_ref': (_grpc_channelz_v1_SocketRef__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelConnectivityState.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelConnectivityState.ts new file mode 100644 index 0000000..78fb069 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelConnectivityState.ts @@ -0,0 +1,45 @@ +// Original file: proto/channelz.proto + + +// Original file: proto/channelz.proto + +export const _grpc_channelz_v1_ChannelConnectivityState_State = { + UNKNOWN: 'UNKNOWN', + IDLE: 'IDLE', + CONNECTING: 'CONNECTING', + READY: 'READY', + TRANSIENT_FAILURE: 'TRANSIENT_FAILURE', + SHUTDOWN: 'SHUTDOWN', +} as const; + +export type _grpc_channelz_v1_ChannelConnectivityState_State = + | 'UNKNOWN' + | 0 + | 'IDLE' + | 1 + | 'CONNECTING' + | 2 + | 'READY' + | 3 + | 'TRANSIENT_FAILURE' + | 4 + | 'SHUTDOWN' + | 5 + +export type _grpc_channelz_v1_ChannelConnectivityState_State__Output = typeof _grpc_channelz_v1_ChannelConnectivityState_State[keyof typeof _grpc_channelz_v1_ChannelConnectivityState_State] + +/** + * These come from the specified states in this document: + * https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md + */ +export interface ChannelConnectivityState { + 'state'?: (_grpc_channelz_v1_ChannelConnectivityState_State); +} + +/** + * These come from the specified states in this document: + * https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md + */ +export interface ChannelConnectivityState__Output { + 'state': (_grpc_channelz_v1_ChannelConnectivityState_State__Output); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelData.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelData.ts new file mode 100644 index 0000000..6d6824a --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelData.ts @@ -0,0 +1,76 @@ +// Original file: proto/channelz.proto + +import type { ChannelConnectivityState as _grpc_channelz_v1_ChannelConnectivityState, ChannelConnectivityState__Output as _grpc_channelz_v1_ChannelConnectivityState__Output } from '../../../grpc/channelz/v1/ChannelConnectivityState'; +import type { ChannelTrace as _grpc_channelz_v1_ChannelTrace, ChannelTrace__Output as _grpc_channelz_v1_ChannelTrace__Output } from '../../../grpc/channelz/v1/ChannelTrace'; +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../../../google/protobuf/Timestamp'; +import type { Long } from '@grpc/proto-loader'; + +/** + * Channel data is data related to a specific Channel or Subchannel. + */ +export interface ChannelData { + /** + * The connectivity state of the channel or subchannel. Implementations + * should always set this. + */ + 'state'?: (_grpc_channelz_v1_ChannelConnectivityState | null); + /** + * The target this channel originally tried to connect to. May be absent + */ + 'target'?: (string); + /** + * A trace of recent events on the channel. May be absent. + */ + 'trace'?: (_grpc_channelz_v1_ChannelTrace | null); + /** + * The number of calls started on the channel + */ + 'calls_started'?: (number | string | Long); + /** + * The number of calls that have completed with an OK status + */ + 'calls_succeeded'?: (number | string | Long); + /** + * The number of calls that have completed with a non-OK status + */ + 'calls_failed'?: (number | string | Long); + /** + * The last time a call was started on the channel. + */ + 'last_call_started_timestamp'?: (_google_protobuf_Timestamp | null); +} + +/** + * Channel data is data related to a specific Channel or Subchannel. + */ +export interface ChannelData__Output { + /** + * The connectivity state of the channel or subchannel. Implementations + * should always set this. + */ + 'state': (_grpc_channelz_v1_ChannelConnectivityState__Output | null); + /** + * The target this channel originally tried to connect to. May be absent + */ + 'target': (string); + /** + * A trace of recent events on the channel. May be absent. + */ + 'trace': (_grpc_channelz_v1_ChannelTrace__Output | null); + /** + * The number of calls started on the channel + */ + 'calls_started': (string); + /** + * The number of calls that have completed with an OK status + */ + 'calls_succeeded': (string); + /** + * The number of calls that have completed with a non-OK status + */ + 'calls_failed': (string); + /** + * The last time a call was started on the channel. + */ + 'last_call_started_timestamp': (_google_protobuf_Timestamp__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelRef.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelRef.ts new file mode 100644 index 0000000..231d008 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelRef.ts @@ -0,0 +1,31 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +/** + * ChannelRef is a reference to a Channel. + */ +export interface ChannelRef { + /** + * The globally unique id for this channel. Must be a positive number. + */ + 'channel_id'?: (number | string | Long); + /** + * An optional name associated with the channel. + */ + 'name'?: (string); +} + +/** + * ChannelRef is a reference to a Channel. + */ +export interface ChannelRef__Output { + /** + * The globally unique id for this channel. Must be a positive number. + */ + 'channel_id': (string); + /** + * An optional name associated with the channel. + */ + 'name': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelTrace.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelTrace.ts new file mode 100644 index 0000000..7dbc8d9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelTrace.ts @@ -0,0 +1,45 @@ +// Original file: proto/channelz.proto + +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../../../google/protobuf/Timestamp'; +import type { ChannelTraceEvent as _grpc_channelz_v1_ChannelTraceEvent, ChannelTraceEvent__Output as _grpc_channelz_v1_ChannelTraceEvent__Output } from '../../../grpc/channelz/v1/ChannelTraceEvent'; +import type { Long } from '@grpc/proto-loader'; + +/** + * ChannelTrace represents the recent events that have occurred on the channel. + */ +export interface ChannelTrace { + /** + * Number of events ever logged in this tracing object. This can differ from + * events.size() because events can be overwritten or garbage collected by + * implementations. + */ + 'num_events_logged'?: (number | string | Long); + /** + * Time that this channel was created. + */ + 'creation_timestamp'?: (_google_protobuf_Timestamp | null); + /** + * List of events that have occurred on this channel. + */ + 'events'?: (_grpc_channelz_v1_ChannelTraceEvent)[]; +} + +/** + * ChannelTrace represents the recent events that have occurred on the channel. + */ +export interface ChannelTrace__Output { + /** + * Number of events ever logged in this tracing object. This can differ from + * events.size() because events can be overwritten or garbage collected by + * implementations. + */ + 'num_events_logged': (string); + /** + * Time that this channel was created. + */ + 'creation_timestamp': (_google_protobuf_Timestamp__Output | null); + /** + * List of events that have occurred on this channel. + */ + 'events': (_grpc_channelz_v1_ChannelTraceEvent__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelTraceEvent.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelTraceEvent.ts new file mode 100644 index 0000000..e1af289 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelTraceEvent.ts @@ -0,0 +1,91 @@ +// Original file: proto/channelz.proto + +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../../../google/protobuf/Timestamp'; +import type { ChannelRef as _grpc_channelz_v1_ChannelRef, ChannelRef__Output as _grpc_channelz_v1_ChannelRef__Output } from '../../../grpc/channelz/v1/ChannelRef'; +import type { SubchannelRef as _grpc_channelz_v1_SubchannelRef, SubchannelRef__Output as _grpc_channelz_v1_SubchannelRef__Output } from '../../../grpc/channelz/v1/SubchannelRef'; + +// Original file: proto/channelz.proto + +/** + * The supported severity levels of trace events. + */ +export const _grpc_channelz_v1_ChannelTraceEvent_Severity = { + CT_UNKNOWN: 'CT_UNKNOWN', + CT_INFO: 'CT_INFO', + CT_WARNING: 'CT_WARNING', + CT_ERROR: 'CT_ERROR', +} as const; + +/** + * The supported severity levels of trace events. + */ +export type _grpc_channelz_v1_ChannelTraceEvent_Severity = + | 'CT_UNKNOWN' + | 0 + | 'CT_INFO' + | 1 + | 'CT_WARNING' + | 2 + | 'CT_ERROR' + | 3 + +/** + * The supported severity levels of trace events. + */ +export type _grpc_channelz_v1_ChannelTraceEvent_Severity__Output = typeof _grpc_channelz_v1_ChannelTraceEvent_Severity[keyof typeof _grpc_channelz_v1_ChannelTraceEvent_Severity] + +/** + * A trace event is an interesting thing that happened to a channel or + * subchannel, such as creation, address resolution, subchannel creation, etc. + */ +export interface ChannelTraceEvent { + /** + * High level description of the event. + */ + 'description'?: (string); + /** + * the severity of the trace event + */ + 'severity'?: (_grpc_channelz_v1_ChannelTraceEvent_Severity); + /** + * When this event occurred. + */ + 'timestamp'?: (_google_protobuf_Timestamp | null); + 'channel_ref'?: (_grpc_channelz_v1_ChannelRef | null); + 'subchannel_ref'?: (_grpc_channelz_v1_SubchannelRef | null); + /** + * ref of referenced channel or subchannel. + * Optional, only present if this event refers to a child object. For example, + * this field would be filled if this trace event was for a subchannel being + * created. + */ + 'child_ref'?: "channel_ref"|"subchannel_ref"; +} + +/** + * A trace event is an interesting thing that happened to a channel or + * subchannel, such as creation, address resolution, subchannel creation, etc. + */ +export interface ChannelTraceEvent__Output { + /** + * High level description of the event. + */ + 'description': (string); + /** + * the severity of the trace event + */ + 'severity': (_grpc_channelz_v1_ChannelTraceEvent_Severity__Output); + /** + * When this event occurred. + */ + 'timestamp': (_google_protobuf_Timestamp__Output | null); + 'channel_ref'?: (_grpc_channelz_v1_ChannelRef__Output | null); + 'subchannel_ref'?: (_grpc_channelz_v1_SubchannelRef__Output | null); + /** + * ref of referenced channel or subchannel. + * Optional, only present if this event refers to a child object. For example, + * this field would be filled if this trace event was for a subchannel being + * created. + */ + 'child_ref'?: "channel_ref"|"subchannel_ref"; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Channelz.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Channelz.ts new file mode 100644 index 0000000..4c8c18a --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Channelz.ts @@ -0,0 +1,178 @@ +// Original file: proto/channelz.proto + +import type * as grpc from '../../../../index' +import type { MethodDefinition } from '@grpc/proto-loader' +import type { GetChannelRequest as _grpc_channelz_v1_GetChannelRequest, GetChannelRequest__Output as _grpc_channelz_v1_GetChannelRequest__Output } from '../../../grpc/channelz/v1/GetChannelRequest'; +import type { GetChannelResponse as _grpc_channelz_v1_GetChannelResponse, GetChannelResponse__Output as _grpc_channelz_v1_GetChannelResponse__Output } from '../../../grpc/channelz/v1/GetChannelResponse'; +import type { GetServerRequest as _grpc_channelz_v1_GetServerRequest, GetServerRequest__Output as _grpc_channelz_v1_GetServerRequest__Output } from '../../../grpc/channelz/v1/GetServerRequest'; +import type { GetServerResponse as _grpc_channelz_v1_GetServerResponse, GetServerResponse__Output as _grpc_channelz_v1_GetServerResponse__Output } from '../../../grpc/channelz/v1/GetServerResponse'; +import type { GetServerSocketsRequest as _grpc_channelz_v1_GetServerSocketsRequest, GetServerSocketsRequest__Output as _grpc_channelz_v1_GetServerSocketsRequest__Output } from '../../../grpc/channelz/v1/GetServerSocketsRequest'; +import type { GetServerSocketsResponse as _grpc_channelz_v1_GetServerSocketsResponse, GetServerSocketsResponse__Output as _grpc_channelz_v1_GetServerSocketsResponse__Output } from '../../../grpc/channelz/v1/GetServerSocketsResponse'; +import type { GetServersRequest as _grpc_channelz_v1_GetServersRequest, GetServersRequest__Output as _grpc_channelz_v1_GetServersRequest__Output } from '../../../grpc/channelz/v1/GetServersRequest'; +import type { GetServersResponse as _grpc_channelz_v1_GetServersResponse, GetServersResponse__Output as _grpc_channelz_v1_GetServersResponse__Output } from '../../../grpc/channelz/v1/GetServersResponse'; +import type { GetSocketRequest as _grpc_channelz_v1_GetSocketRequest, GetSocketRequest__Output as _grpc_channelz_v1_GetSocketRequest__Output } from '../../../grpc/channelz/v1/GetSocketRequest'; +import type { GetSocketResponse as _grpc_channelz_v1_GetSocketResponse, GetSocketResponse__Output as _grpc_channelz_v1_GetSocketResponse__Output } from '../../../grpc/channelz/v1/GetSocketResponse'; +import type { GetSubchannelRequest as _grpc_channelz_v1_GetSubchannelRequest, GetSubchannelRequest__Output as _grpc_channelz_v1_GetSubchannelRequest__Output } from '../../../grpc/channelz/v1/GetSubchannelRequest'; +import type { GetSubchannelResponse as _grpc_channelz_v1_GetSubchannelResponse, GetSubchannelResponse__Output as _grpc_channelz_v1_GetSubchannelResponse__Output } from '../../../grpc/channelz/v1/GetSubchannelResponse'; +import type { GetTopChannelsRequest as _grpc_channelz_v1_GetTopChannelsRequest, GetTopChannelsRequest__Output as _grpc_channelz_v1_GetTopChannelsRequest__Output } from '../../../grpc/channelz/v1/GetTopChannelsRequest'; +import type { GetTopChannelsResponse as _grpc_channelz_v1_GetTopChannelsResponse, GetTopChannelsResponse__Output as _grpc_channelz_v1_GetTopChannelsResponse__Output } from '../../../grpc/channelz/v1/GetTopChannelsResponse'; + +/** + * Channelz is a service exposed by gRPC servers that provides detailed debug + * information. + */ +export interface ChannelzClient extends grpc.Client { + /** + * Returns a single Channel, or else a NOT_FOUND code. + */ + GetChannel(argument: _grpc_channelz_v1_GetChannelRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetChannelResponse__Output>): grpc.ClientUnaryCall; + GetChannel(argument: _grpc_channelz_v1_GetChannelRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetChannelResponse__Output>): grpc.ClientUnaryCall; + GetChannel(argument: _grpc_channelz_v1_GetChannelRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetChannelResponse__Output>): grpc.ClientUnaryCall; + GetChannel(argument: _grpc_channelz_v1_GetChannelRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetChannelResponse__Output>): grpc.ClientUnaryCall; + + /** + * Returns a single Server, or else a NOT_FOUND code. + */ + GetServer(argument: _grpc_channelz_v1_GetServerRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + GetServer(argument: _grpc_channelz_v1_GetServerRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + GetServer(argument: _grpc_channelz_v1_GetServerRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + GetServer(argument: _grpc_channelz_v1_GetServerRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + /** + * Returns a single Server, or else a NOT_FOUND code. + */ + getServer(argument: _grpc_channelz_v1_GetServerRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + getServer(argument: _grpc_channelz_v1_GetServerRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + getServer(argument: _grpc_channelz_v1_GetServerRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + getServer(argument: _grpc_channelz_v1_GetServerRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + + /** + * Gets all server sockets that exist in the process. + */ + GetServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + GetServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + GetServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + GetServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + /** + * Gets all server sockets that exist in the process. + */ + getServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + getServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + getServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + getServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + + /** + * Gets all servers that exist in the process. + */ + GetServers(argument: _grpc_channelz_v1_GetServersRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + GetServers(argument: _grpc_channelz_v1_GetServersRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + GetServers(argument: _grpc_channelz_v1_GetServersRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + GetServers(argument: _grpc_channelz_v1_GetServersRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + /** + * Gets all servers that exist in the process. + */ + getServers(argument: _grpc_channelz_v1_GetServersRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + getServers(argument: _grpc_channelz_v1_GetServersRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + getServers(argument: _grpc_channelz_v1_GetServersRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + getServers(argument: _grpc_channelz_v1_GetServersRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + + /** + * Returns a single Socket or else a NOT_FOUND code. + */ + GetSocket(argument: _grpc_channelz_v1_GetSocketRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + GetSocket(argument: _grpc_channelz_v1_GetSocketRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + GetSocket(argument: _grpc_channelz_v1_GetSocketRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + GetSocket(argument: _grpc_channelz_v1_GetSocketRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + /** + * Returns a single Socket or else a NOT_FOUND code. + */ + getSocket(argument: _grpc_channelz_v1_GetSocketRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + getSocket(argument: _grpc_channelz_v1_GetSocketRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + getSocket(argument: _grpc_channelz_v1_GetSocketRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + getSocket(argument: _grpc_channelz_v1_GetSocketRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + + /** + * Returns a single Subchannel, or else a NOT_FOUND code. + */ + GetSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + GetSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + GetSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + GetSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + /** + * Returns a single Subchannel, or else a NOT_FOUND code. + */ + getSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + getSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + getSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + getSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + + /** + * Gets all root channels (i.e. channels the application has directly + * created). This does not include subchannels nor non-top level channels. + */ + GetTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + GetTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + GetTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + GetTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + /** + * Gets all root channels (i.e. channels the application has directly + * created). This does not include subchannels nor non-top level channels. + */ + getTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + getTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + getTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + getTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + +} + +/** + * Channelz is a service exposed by gRPC servers that provides detailed debug + * information. + */ +export interface ChannelzHandlers extends grpc.UntypedServiceImplementation { + /** + * Returns a single Channel, or else a NOT_FOUND code. + */ + GetChannel: grpc.handleUnaryCall<_grpc_channelz_v1_GetChannelRequest__Output, _grpc_channelz_v1_GetChannelResponse>; + + /** + * Returns a single Server, or else a NOT_FOUND code. + */ + GetServer: grpc.handleUnaryCall<_grpc_channelz_v1_GetServerRequest__Output, _grpc_channelz_v1_GetServerResponse>; + + /** + * Gets all server sockets that exist in the process. + */ + GetServerSockets: grpc.handleUnaryCall<_grpc_channelz_v1_GetServerSocketsRequest__Output, _grpc_channelz_v1_GetServerSocketsResponse>; + + /** + * Gets all servers that exist in the process. + */ + GetServers: grpc.handleUnaryCall<_grpc_channelz_v1_GetServersRequest__Output, _grpc_channelz_v1_GetServersResponse>; + + /** + * Returns a single Socket or else a NOT_FOUND code. + */ + GetSocket: grpc.handleUnaryCall<_grpc_channelz_v1_GetSocketRequest__Output, _grpc_channelz_v1_GetSocketResponse>; + + /** + * Returns a single Subchannel, or else a NOT_FOUND code. + */ + GetSubchannel: grpc.handleUnaryCall<_grpc_channelz_v1_GetSubchannelRequest__Output, _grpc_channelz_v1_GetSubchannelResponse>; + + /** + * Gets all root channels (i.e. channels the application has directly + * created). This does not include subchannels nor non-top level channels. + */ + GetTopChannels: grpc.handleUnaryCall<_grpc_channelz_v1_GetTopChannelsRequest__Output, _grpc_channelz_v1_GetTopChannelsResponse>; + +} + +export interface ChannelzDefinition extends grpc.ServiceDefinition { + GetChannel: MethodDefinition<_grpc_channelz_v1_GetChannelRequest, _grpc_channelz_v1_GetChannelResponse, _grpc_channelz_v1_GetChannelRequest__Output, _grpc_channelz_v1_GetChannelResponse__Output> + GetServer: MethodDefinition<_grpc_channelz_v1_GetServerRequest, _grpc_channelz_v1_GetServerResponse, _grpc_channelz_v1_GetServerRequest__Output, _grpc_channelz_v1_GetServerResponse__Output> + GetServerSockets: MethodDefinition<_grpc_channelz_v1_GetServerSocketsRequest, _grpc_channelz_v1_GetServerSocketsResponse, _grpc_channelz_v1_GetServerSocketsRequest__Output, _grpc_channelz_v1_GetServerSocketsResponse__Output> + GetServers: MethodDefinition<_grpc_channelz_v1_GetServersRequest, _grpc_channelz_v1_GetServersResponse, _grpc_channelz_v1_GetServersRequest__Output, _grpc_channelz_v1_GetServersResponse__Output> + GetSocket: MethodDefinition<_grpc_channelz_v1_GetSocketRequest, _grpc_channelz_v1_GetSocketResponse, _grpc_channelz_v1_GetSocketRequest__Output, _grpc_channelz_v1_GetSocketResponse__Output> + GetSubchannel: MethodDefinition<_grpc_channelz_v1_GetSubchannelRequest, _grpc_channelz_v1_GetSubchannelResponse, _grpc_channelz_v1_GetSubchannelRequest__Output, _grpc_channelz_v1_GetSubchannelResponse__Output> + GetTopChannels: MethodDefinition<_grpc_channelz_v1_GetTopChannelsRequest, _grpc_channelz_v1_GetTopChannelsResponse, _grpc_channelz_v1_GetTopChannelsRequest__Output, _grpc_channelz_v1_GetTopChannelsResponse__Output> +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetChannelRequest.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetChannelRequest.ts new file mode 100644 index 0000000..437e2d6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetChannelRequest.ts @@ -0,0 +1,17 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +export interface GetChannelRequest { + /** + * channel_id is the identifier of the specific channel to get. + */ + 'channel_id'?: (number | string | Long); +} + +export interface GetChannelRequest__Output { + /** + * channel_id is the identifier of the specific channel to get. + */ + 'channel_id': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetChannelResponse.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetChannelResponse.ts new file mode 100644 index 0000000..2e967a4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetChannelResponse.ts @@ -0,0 +1,19 @@ +// Original file: proto/channelz.proto + +import type { Channel as _grpc_channelz_v1_Channel, Channel__Output as _grpc_channelz_v1_Channel__Output } from '../../../grpc/channelz/v1/Channel'; + +export interface GetChannelResponse { + /** + * The Channel that corresponds to the requested channel_id. This field + * should be set. + */ + 'channel'?: (_grpc_channelz_v1_Channel | null); +} + +export interface GetChannelResponse__Output { + /** + * The Channel that corresponds to the requested channel_id. This field + * should be set. + */ + 'channel': (_grpc_channelz_v1_Channel__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerRequest.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerRequest.ts new file mode 100644 index 0000000..f5d4a29 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerRequest.ts @@ -0,0 +1,17 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +export interface GetServerRequest { + /** + * server_id is the identifier of the specific server to get. + */ + 'server_id'?: (number | string | Long); +} + +export interface GetServerRequest__Output { + /** + * server_id is the identifier of the specific server to get. + */ + 'server_id': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerResponse.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerResponse.ts new file mode 100644 index 0000000..fe00782 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerResponse.ts @@ -0,0 +1,19 @@ +// Original file: proto/channelz.proto + +import type { Server as _grpc_channelz_v1_Server, Server__Output as _grpc_channelz_v1_Server__Output } from '../../../grpc/channelz/v1/Server'; + +export interface GetServerResponse { + /** + * The Server that corresponds to the requested server_id. This field + * should be set. + */ + 'server'?: (_grpc_channelz_v1_Server | null); +} + +export interface GetServerResponse__Output { + /** + * The Server that corresponds to the requested server_id. This field + * should be set. + */ + 'server': (_grpc_channelz_v1_Server__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerSocketsRequest.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerSocketsRequest.ts new file mode 100644 index 0000000..c33056e --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerSocketsRequest.ts @@ -0,0 +1,39 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +export interface GetServerSocketsRequest { + 'server_id'?: (number | string | Long); + /** + * start_socket_id indicates that only sockets at or above this id should be + * included in the results. + * To request the first page, this must be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_socket_id'?: (number | string | Long); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results'?: (number | string | Long); +} + +export interface GetServerSocketsRequest__Output { + 'server_id': (string); + /** + * start_socket_id indicates that only sockets at or above this id should be + * included in the results. + * To request the first page, this must be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_socket_id': (string); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerSocketsResponse.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerSocketsResponse.ts new file mode 100644 index 0000000..112f277 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerSocketsResponse.ts @@ -0,0 +1,33 @@ +// Original file: proto/channelz.proto + +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from '../../../grpc/channelz/v1/SocketRef'; + +export interface GetServerSocketsResponse { + /** + * list of socket refs that the connection detail service knows about. Sorted in + * ascending socket_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'socket_ref'?: (_grpc_channelz_v1_SocketRef)[]; + /** + * If set, indicates that the list of sockets is the final list. Requesting + * more sockets will only return more if they are created after this RPC + * completes. + */ + 'end'?: (boolean); +} + +export interface GetServerSocketsResponse__Output { + /** + * list of socket refs that the connection detail service knows about. Sorted in + * ascending socket_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'socket_ref': (_grpc_channelz_v1_SocketRef__Output)[]; + /** + * If set, indicates that the list of sockets is the final list. Requesting + * more sockets will only return more if they are created after this RPC + * completes. + */ + 'end': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServersRequest.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServersRequest.ts new file mode 100644 index 0000000..2defea6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServersRequest.ts @@ -0,0 +1,37 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +export interface GetServersRequest { + /** + * start_server_id indicates that only servers at or above this id should be + * included in the results. + * To request the first page, this must be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_server_id'?: (number | string | Long); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results'?: (number | string | Long); +} + +export interface GetServersRequest__Output { + /** + * start_server_id indicates that only servers at or above this id should be + * included in the results. + * To request the first page, this must be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_server_id': (string); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServersResponse.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServersResponse.ts new file mode 100644 index 0000000..b07893b --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServersResponse.ts @@ -0,0 +1,33 @@ +// Original file: proto/channelz.proto + +import type { Server as _grpc_channelz_v1_Server, Server__Output as _grpc_channelz_v1_Server__Output } from '../../../grpc/channelz/v1/Server'; + +export interface GetServersResponse { + /** + * list of servers that the connection detail service knows about. Sorted in + * ascending server_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'server'?: (_grpc_channelz_v1_Server)[]; + /** + * If set, indicates that the list of servers is the final list. Requesting + * more servers will only return more if they are created after this RPC + * completes. + */ + 'end'?: (boolean); +} + +export interface GetServersResponse__Output { + /** + * list of servers that the connection detail service knows about. Sorted in + * ascending server_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'server': (_grpc_channelz_v1_Server__Output)[]; + /** + * If set, indicates that the list of servers is the final list. Requesting + * more servers will only return more if they are created after this RPC + * completes. + */ + 'end': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSocketRequest.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSocketRequest.ts new file mode 100644 index 0000000..b3dc160 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSocketRequest.ts @@ -0,0 +1,29 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +export interface GetSocketRequest { + /** + * socket_id is the identifier of the specific socket to get. + */ + 'socket_id'?: (number | string | Long); + /** + * If true, the response will contain only high level information + * that is inexpensive to obtain. Fields thay may be omitted are + * documented. + */ + 'summary'?: (boolean); +} + +export interface GetSocketRequest__Output { + /** + * socket_id is the identifier of the specific socket to get. + */ + 'socket_id': (string); + /** + * If true, the response will contain only high level information + * that is inexpensive to obtain. Fields thay may be omitted are + * documented. + */ + 'summary': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSocketResponse.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSocketResponse.ts new file mode 100644 index 0000000..b6304b7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSocketResponse.ts @@ -0,0 +1,19 @@ +// Original file: proto/channelz.proto + +import type { Socket as _grpc_channelz_v1_Socket, Socket__Output as _grpc_channelz_v1_Socket__Output } from '../../../grpc/channelz/v1/Socket'; + +export interface GetSocketResponse { + /** + * The Socket that corresponds to the requested socket_id. This field + * should be set. + */ + 'socket'?: (_grpc_channelz_v1_Socket | null); +} + +export interface GetSocketResponse__Output { + /** + * The Socket that corresponds to the requested socket_id. This field + * should be set. + */ + 'socket': (_grpc_channelz_v1_Socket__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSubchannelRequest.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSubchannelRequest.ts new file mode 100644 index 0000000..f481a81 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSubchannelRequest.ts @@ -0,0 +1,17 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +export interface GetSubchannelRequest { + /** + * subchannel_id is the identifier of the specific subchannel to get. + */ + 'subchannel_id'?: (number | string | Long); +} + +export interface GetSubchannelRequest__Output { + /** + * subchannel_id is the identifier of the specific subchannel to get. + */ + 'subchannel_id': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSubchannelResponse.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSubchannelResponse.ts new file mode 100644 index 0000000..57d2bf2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSubchannelResponse.ts @@ -0,0 +1,19 @@ +// Original file: proto/channelz.proto + +import type { Subchannel as _grpc_channelz_v1_Subchannel, Subchannel__Output as _grpc_channelz_v1_Subchannel__Output } from '../../../grpc/channelz/v1/Subchannel'; + +export interface GetSubchannelResponse { + /** + * The Subchannel that corresponds to the requested subchannel_id. This + * field should be set. + */ + 'subchannel'?: (_grpc_channelz_v1_Subchannel | null); +} + +export interface GetSubchannelResponse__Output { + /** + * The Subchannel that corresponds to the requested subchannel_id. This + * field should be set. + */ + 'subchannel': (_grpc_channelz_v1_Subchannel__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetTopChannelsRequest.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetTopChannelsRequest.ts new file mode 100644 index 0000000..a122d7a --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetTopChannelsRequest.ts @@ -0,0 +1,37 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +export interface GetTopChannelsRequest { + /** + * start_channel_id indicates that only channels at or above this id should be + * included in the results. + * To request the first page, this should be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_channel_id'?: (number | string | Long); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results'?: (number | string | Long); +} + +export interface GetTopChannelsRequest__Output { + /** + * start_channel_id indicates that only channels at or above this id should be + * included in the results. + * To request the first page, this should be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_channel_id': (string); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetTopChannelsResponse.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetTopChannelsResponse.ts new file mode 100644 index 0000000..d96e636 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetTopChannelsResponse.ts @@ -0,0 +1,33 @@ +// Original file: proto/channelz.proto + +import type { Channel as _grpc_channelz_v1_Channel, Channel__Output as _grpc_channelz_v1_Channel__Output } from '../../../grpc/channelz/v1/Channel'; + +export interface GetTopChannelsResponse { + /** + * list of channels that the connection detail service knows about. Sorted in + * ascending channel_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'channel'?: (_grpc_channelz_v1_Channel)[]; + /** + * If set, indicates that the list of channels is the final list. Requesting + * more channels can only return more if they are created after this RPC + * completes. + */ + 'end'?: (boolean); +} + +export interface GetTopChannelsResponse__Output { + /** + * list of channels that the connection detail service knows about. Sorted in + * ascending channel_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'channel': (_grpc_channelz_v1_Channel__Output)[]; + /** + * If set, indicates that the list of channels is the final list. Requesting + * more channels can only return more if they are created after this RPC + * completes. + */ + 'end': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Security.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Security.ts new file mode 100644 index 0000000..55b2594 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Security.ts @@ -0,0 +1,87 @@ +// Original file: proto/channelz.proto + +import type { Any as _google_protobuf_Any, Any__Output as _google_protobuf_Any__Output } from '../../../google/protobuf/Any'; + +export interface _grpc_channelz_v1_Security_OtherSecurity { + /** + * The human readable version of the value. + */ + 'name'?: (string); + /** + * The actual security details message. + */ + 'value'?: (_google_protobuf_Any | null); +} + +export interface _grpc_channelz_v1_Security_OtherSecurity__Output { + /** + * The human readable version of the value. + */ + 'name': (string); + /** + * The actual security details message. + */ + 'value': (_google_protobuf_Any__Output | null); +} + +export interface _grpc_channelz_v1_Security_Tls { + /** + * The cipher suite name in the RFC 4346 format: + * https://tools.ietf.org/html/rfc4346#appendix-C + */ + 'standard_name'?: (string); + /** + * Some other way to describe the cipher suite if + * the RFC 4346 name is not available. + */ + 'other_name'?: (string); + /** + * the certificate used by this endpoint. + */ + 'local_certificate'?: (Buffer | Uint8Array | string); + /** + * the certificate used by the remote endpoint. + */ + 'remote_certificate'?: (Buffer | Uint8Array | string); + 'cipher_suite'?: "standard_name"|"other_name"; +} + +export interface _grpc_channelz_v1_Security_Tls__Output { + /** + * The cipher suite name in the RFC 4346 format: + * https://tools.ietf.org/html/rfc4346#appendix-C + */ + 'standard_name'?: (string); + /** + * Some other way to describe the cipher suite if + * the RFC 4346 name is not available. + */ + 'other_name'?: (string); + /** + * the certificate used by this endpoint. + */ + 'local_certificate': (Buffer); + /** + * the certificate used by the remote endpoint. + */ + 'remote_certificate': (Buffer); + 'cipher_suite'?: "standard_name"|"other_name"; +} + +/** + * Security represents details about how secure the socket is. + */ +export interface Security { + 'tls'?: (_grpc_channelz_v1_Security_Tls | null); + 'other'?: (_grpc_channelz_v1_Security_OtherSecurity | null); + 'model'?: "tls"|"other"; +} + +/** + * Security represents details about how secure the socket is. + */ +export interface Security__Output { + 'tls'?: (_grpc_channelz_v1_Security_Tls__Output | null); + 'other'?: (_grpc_channelz_v1_Security_OtherSecurity__Output | null); + 'model'?: "tls"|"other"; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Server.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Server.ts new file mode 100644 index 0000000..9583433 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Server.ts @@ -0,0 +1,45 @@ +// Original file: proto/channelz.proto + +import type { ServerRef as _grpc_channelz_v1_ServerRef, ServerRef__Output as _grpc_channelz_v1_ServerRef__Output } from '../../../grpc/channelz/v1/ServerRef'; +import type { ServerData as _grpc_channelz_v1_ServerData, ServerData__Output as _grpc_channelz_v1_ServerData__Output } from '../../../grpc/channelz/v1/ServerData'; +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from '../../../grpc/channelz/v1/SocketRef'; + +/** + * Server represents a single server. There may be multiple servers in a single + * program. + */ +export interface Server { + /** + * The identifier for a Server. This should be set. + */ + 'ref'?: (_grpc_channelz_v1_ServerRef | null); + /** + * The associated data of the Server. + */ + 'data'?: (_grpc_channelz_v1_ServerData | null); + /** + * The sockets that the server is listening on. There are no ordering + * guarantees. This may be absent. + */ + 'listen_socket'?: (_grpc_channelz_v1_SocketRef)[]; +} + +/** + * Server represents a single server. There may be multiple servers in a single + * program. + */ +export interface Server__Output { + /** + * The identifier for a Server. This should be set. + */ + 'ref': (_grpc_channelz_v1_ServerRef__Output | null); + /** + * The associated data of the Server. + */ + 'data': (_grpc_channelz_v1_ServerData__Output | null); + /** + * The sockets that the server is listening on. There are no ordering + * guarantees. This may be absent. + */ + 'listen_socket': (_grpc_channelz_v1_SocketRef__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ServerData.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ServerData.ts new file mode 100644 index 0000000..ce48e36 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ServerData.ts @@ -0,0 +1,57 @@ +// Original file: proto/channelz.proto + +import type { ChannelTrace as _grpc_channelz_v1_ChannelTrace, ChannelTrace__Output as _grpc_channelz_v1_ChannelTrace__Output } from '../../../grpc/channelz/v1/ChannelTrace'; +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../../../google/protobuf/Timestamp'; +import type { Long } from '@grpc/proto-loader'; + +/** + * ServerData is data for a specific Server. + */ +export interface ServerData { + /** + * A trace of recent events on the server. May be absent. + */ + 'trace'?: (_grpc_channelz_v1_ChannelTrace | null); + /** + * The number of incoming calls started on the server + */ + 'calls_started'?: (number | string | Long); + /** + * The number of incoming calls that have completed with an OK status + */ + 'calls_succeeded'?: (number | string | Long); + /** + * The number of incoming calls that have a completed with a non-OK status + */ + 'calls_failed'?: (number | string | Long); + /** + * The last time a call was started on the server. + */ + 'last_call_started_timestamp'?: (_google_protobuf_Timestamp | null); +} + +/** + * ServerData is data for a specific Server. + */ +export interface ServerData__Output { + /** + * A trace of recent events on the server. May be absent. + */ + 'trace': (_grpc_channelz_v1_ChannelTrace__Output | null); + /** + * The number of incoming calls started on the server + */ + 'calls_started': (string); + /** + * The number of incoming calls that have completed with an OK status + */ + 'calls_succeeded': (string); + /** + * The number of incoming calls that have a completed with a non-OK status + */ + 'calls_failed': (string); + /** + * The last time a call was started on the server. + */ + 'last_call_started_timestamp': (_google_protobuf_Timestamp__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ServerRef.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ServerRef.ts new file mode 100644 index 0000000..389183b --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ServerRef.ts @@ -0,0 +1,31 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +/** + * ServerRef is a reference to a Server. + */ +export interface ServerRef { + /** + * A globally unique identifier for this server. Must be a positive number. + */ + 'server_id'?: (number | string | Long); + /** + * An optional name associated with the server. + */ + 'name'?: (string); +} + +/** + * ServerRef is a reference to a Server. + */ +export interface ServerRef__Output { + /** + * A globally unique identifier for this server. Must be a positive number. + */ + 'server_id': (string); + /** + * An optional name associated with the server. + */ + 'name': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Socket.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Socket.ts new file mode 100644 index 0000000..5829afe --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Socket.ts @@ -0,0 +1,70 @@ +// Original file: proto/channelz.proto + +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from '../../../grpc/channelz/v1/SocketRef'; +import type { SocketData as _grpc_channelz_v1_SocketData, SocketData__Output as _grpc_channelz_v1_SocketData__Output } from '../../../grpc/channelz/v1/SocketData'; +import type { Address as _grpc_channelz_v1_Address, Address__Output as _grpc_channelz_v1_Address__Output } from '../../../grpc/channelz/v1/Address'; +import type { Security as _grpc_channelz_v1_Security, Security__Output as _grpc_channelz_v1_Security__Output } from '../../../grpc/channelz/v1/Security'; + +/** + * Information about an actual connection. Pronounced "sock-ay". + */ +export interface Socket { + /** + * The identifier for the Socket. + */ + 'ref'?: (_grpc_channelz_v1_SocketRef | null); + /** + * Data specific to this Socket. + */ + 'data'?: (_grpc_channelz_v1_SocketData | null); + /** + * The locally bound address. + */ + 'local'?: (_grpc_channelz_v1_Address | null); + /** + * The remote bound address. May be absent. + */ + 'remote'?: (_grpc_channelz_v1_Address | null); + /** + * Security details for this socket. May be absent if not available, or + * there is no security on the socket. + */ + 'security'?: (_grpc_channelz_v1_Security | null); + /** + * Optional, represents the name of the remote endpoint, if different than + * the original target name. + */ + 'remote_name'?: (string); +} + +/** + * Information about an actual connection. Pronounced "sock-ay". + */ +export interface Socket__Output { + /** + * The identifier for the Socket. + */ + 'ref': (_grpc_channelz_v1_SocketRef__Output | null); + /** + * Data specific to this Socket. + */ + 'data': (_grpc_channelz_v1_SocketData__Output | null); + /** + * The locally bound address. + */ + 'local': (_grpc_channelz_v1_Address__Output | null); + /** + * The remote bound address. May be absent. + */ + 'remote': (_grpc_channelz_v1_Address__Output | null); + /** + * Security details for this socket. May be absent if not available, or + * there is no security on the socket. + */ + 'security': (_grpc_channelz_v1_Security__Output | null); + /** + * Optional, represents the name of the remote endpoint, if different than + * the original target name. + */ + 'remote_name': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketData.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketData.ts new file mode 100644 index 0000000..c62d4d1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketData.ts @@ -0,0 +1,150 @@ +// Original file: proto/channelz.proto + +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../../../google/protobuf/Timestamp'; +import type { Int64Value as _google_protobuf_Int64Value, Int64Value__Output as _google_protobuf_Int64Value__Output } from '../../../google/protobuf/Int64Value'; +import type { SocketOption as _grpc_channelz_v1_SocketOption, SocketOption__Output as _grpc_channelz_v1_SocketOption__Output } from '../../../grpc/channelz/v1/SocketOption'; +import type { Long } from '@grpc/proto-loader'; + +/** + * SocketData is data associated for a specific Socket. The fields present + * are specific to the implementation, so there may be minor differences in + * the semantics. (e.g. flow control windows) + */ +export interface SocketData { + /** + * The number of streams that have been started. + */ + 'streams_started'?: (number | string | Long); + /** + * The number of streams that have ended successfully: + * On client side, received frame with eos bit set; + * On server side, sent frame with eos bit set. + */ + 'streams_succeeded'?: (number | string | Long); + /** + * The number of streams that have ended unsuccessfully: + * On client side, ended without receiving frame with eos bit set; + * On server side, ended without sending frame with eos bit set. + */ + 'streams_failed'?: (number | string | Long); + /** + * The number of grpc messages successfully sent on this socket. + */ + 'messages_sent'?: (number | string | Long); + /** + * The number of grpc messages received on this socket. + */ + 'messages_received'?: (number | string | Long); + /** + * The number of keep alives sent. This is typically implemented with HTTP/2 + * ping messages. + */ + 'keep_alives_sent'?: (number | string | Long); + /** + * The last time a stream was created by this endpoint. Usually unset for + * servers. + */ + 'last_local_stream_created_timestamp'?: (_google_protobuf_Timestamp | null); + /** + * The last time a stream was created by the remote endpoint. Usually unset + * for clients. + */ + 'last_remote_stream_created_timestamp'?: (_google_protobuf_Timestamp | null); + /** + * The last time a message was sent by this endpoint. + */ + 'last_message_sent_timestamp'?: (_google_protobuf_Timestamp | null); + /** + * The last time a message was received by this endpoint. + */ + 'last_message_received_timestamp'?: (_google_protobuf_Timestamp | null); + /** + * The amount of window, granted to the local endpoint by the remote endpoint. + * This may be slightly out of date due to network latency. This does NOT + * include stream level or TCP level flow control info. + */ + 'local_flow_control_window'?: (_google_protobuf_Int64Value | null); + /** + * The amount of window, granted to the remote endpoint by the local endpoint. + * This may be slightly out of date due to network latency. This does NOT + * include stream level or TCP level flow control info. + */ + 'remote_flow_control_window'?: (_google_protobuf_Int64Value | null); + /** + * Socket options set on this socket. May be absent if 'summary' is set + * on GetSocketRequest. + */ + 'option'?: (_grpc_channelz_v1_SocketOption)[]; +} + +/** + * SocketData is data associated for a specific Socket. The fields present + * are specific to the implementation, so there may be minor differences in + * the semantics. (e.g. flow control windows) + */ +export interface SocketData__Output { + /** + * The number of streams that have been started. + */ + 'streams_started': (string); + /** + * The number of streams that have ended successfully: + * On client side, received frame with eos bit set; + * On server side, sent frame with eos bit set. + */ + 'streams_succeeded': (string); + /** + * The number of streams that have ended unsuccessfully: + * On client side, ended without receiving frame with eos bit set; + * On server side, ended without sending frame with eos bit set. + */ + 'streams_failed': (string); + /** + * The number of grpc messages successfully sent on this socket. + */ + 'messages_sent': (string); + /** + * The number of grpc messages received on this socket. + */ + 'messages_received': (string); + /** + * The number of keep alives sent. This is typically implemented with HTTP/2 + * ping messages. + */ + 'keep_alives_sent': (string); + /** + * The last time a stream was created by this endpoint. Usually unset for + * servers. + */ + 'last_local_stream_created_timestamp': (_google_protobuf_Timestamp__Output | null); + /** + * The last time a stream was created by the remote endpoint. Usually unset + * for clients. + */ + 'last_remote_stream_created_timestamp': (_google_protobuf_Timestamp__Output | null); + /** + * The last time a message was sent by this endpoint. + */ + 'last_message_sent_timestamp': (_google_protobuf_Timestamp__Output | null); + /** + * The last time a message was received by this endpoint. + */ + 'last_message_received_timestamp': (_google_protobuf_Timestamp__Output | null); + /** + * The amount of window, granted to the local endpoint by the remote endpoint. + * This may be slightly out of date due to network latency. This does NOT + * include stream level or TCP level flow control info. + */ + 'local_flow_control_window': (_google_protobuf_Int64Value__Output | null); + /** + * The amount of window, granted to the remote endpoint by the local endpoint. + * This may be slightly out of date due to network latency. This does NOT + * include stream level or TCP level flow control info. + */ + 'remote_flow_control_window': (_google_protobuf_Int64Value__Output | null); + /** + * Socket options set on this socket. May be absent if 'summary' is set + * on GetSocketRequest. + */ + 'option': (_grpc_channelz_v1_SocketOption__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOption.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOption.ts new file mode 100644 index 0000000..115b36a --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOption.ts @@ -0,0 +1,47 @@ +// Original file: proto/channelz.proto + +import type { Any as _google_protobuf_Any, Any__Output as _google_protobuf_Any__Output } from '../../../google/protobuf/Any'; + +/** + * SocketOption represents socket options for a socket. Specifically, these + * are the options returned by getsockopt(). + */ +export interface SocketOption { + /** + * The full name of the socket option. Typically this will be the upper case + * name, such as "SO_REUSEPORT". + */ + 'name'?: (string); + /** + * The human readable value of this socket option. At least one of value or + * additional will be set. + */ + 'value'?: (string); + /** + * Additional data associated with the socket option. At least one of value + * or additional will be set. + */ + 'additional'?: (_google_protobuf_Any | null); +} + +/** + * SocketOption represents socket options for a socket. Specifically, these + * are the options returned by getsockopt(). + */ +export interface SocketOption__Output { + /** + * The full name of the socket option. Typically this will be the upper case + * name, such as "SO_REUSEPORT". + */ + 'name': (string); + /** + * The human readable value of this socket option. At least one of value or + * additional will be set. + */ + 'value': (string); + /** + * Additional data associated with the socket option. At least one of value + * or additional will be set. + */ + 'additional': (_google_protobuf_Any__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionLinger.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionLinger.ts new file mode 100644 index 0000000..d83fa32 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionLinger.ts @@ -0,0 +1,33 @@ +// Original file: proto/channelz.proto + +import type { Duration as _google_protobuf_Duration, Duration__Output as _google_protobuf_Duration__Output } from '../../../google/protobuf/Duration'; + +/** + * For use with SocketOption's additional field. This is primarily used for + * SO_LINGER. + */ +export interface SocketOptionLinger { + /** + * active maps to `struct linger.l_onoff` + */ + 'active'?: (boolean); + /** + * duration maps to `struct linger.l_linger` + */ + 'duration'?: (_google_protobuf_Duration | null); +} + +/** + * For use with SocketOption's additional field. This is primarily used for + * SO_LINGER. + */ +export interface SocketOptionLinger__Output { + /** + * active maps to `struct linger.l_onoff` + */ + 'active': (boolean); + /** + * duration maps to `struct linger.l_linger` + */ + 'duration': (_google_protobuf_Duration__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.ts new file mode 100644 index 0000000..2f8affe --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.ts @@ -0,0 +1,74 @@ +// Original file: proto/channelz.proto + + +/** + * For use with SocketOption's additional field. Tcp info for + * SOL_TCP and TCP_INFO. + */ +export interface SocketOptionTcpInfo { + 'tcpi_state'?: (number); + 'tcpi_ca_state'?: (number); + 'tcpi_retransmits'?: (number); + 'tcpi_probes'?: (number); + 'tcpi_backoff'?: (number); + 'tcpi_options'?: (number); + 'tcpi_snd_wscale'?: (number); + 'tcpi_rcv_wscale'?: (number); + 'tcpi_rto'?: (number); + 'tcpi_ato'?: (number); + 'tcpi_snd_mss'?: (number); + 'tcpi_rcv_mss'?: (number); + 'tcpi_unacked'?: (number); + 'tcpi_sacked'?: (number); + 'tcpi_lost'?: (number); + 'tcpi_retrans'?: (number); + 'tcpi_fackets'?: (number); + 'tcpi_last_data_sent'?: (number); + 'tcpi_last_ack_sent'?: (number); + 'tcpi_last_data_recv'?: (number); + 'tcpi_last_ack_recv'?: (number); + 'tcpi_pmtu'?: (number); + 'tcpi_rcv_ssthresh'?: (number); + 'tcpi_rtt'?: (number); + 'tcpi_rttvar'?: (number); + 'tcpi_snd_ssthresh'?: (number); + 'tcpi_snd_cwnd'?: (number); + 'tcpi_advmss'?: (number); + 'tcpi_reordering'?: (number); +} + +/** + * For use with SocketOption's additional field. Tcp info for + * SOL_TCP and TCP_INFO. + */ +export interface SocketOptionTcpInfo__Output { + 'tcpi_state': (number); + 'tcpi_ca_state': (number); + 'tcpi_retransmits': (number); + 'tcpi_probes': (number); + 'tcpi_backoff': (number); + 'tcpi_options': (number); + 'tcpi_snd_wscale': (number); + 'tcpi_rcv_wscale': (number); + 'tcpi_rto': (number); + 'tcpi_ato': (number); + 'tcpi_snd_mss': (number); + 'tcpi_rcv_mss': (number); + 'tcpi_unacked': (number); + 'tcpi_sacked': (number); + 'tcpi_lost': (number); + 'tcpi_retrans': (number); + 'tcpi_fackets': (number); + 'tcpi_last_data_sent': (number); + 'tcpi_last_ack_sent': (number); + 'tcpi_last_data_recv': (number); + 'tcpi_last_ack_recv': (number); + 'tcpi_pmtu': (number); + 'tcpi_rcv_ssthresh': (number); + 'tcpi_rtt': (number); + 'tcpi_rttvar': (number); + 'tcpi_snd_ssthresh': (number); + 'tcpi_snd_cwnd': (number); + 'tcpi_advmss': (number); + 'tcpi_reordering': (number); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionTimeout.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionTimeout.ts new file mode 100644 index 0000000..185839b --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionTimeout.ts @@ -0,0 +1,19 @@ +// Original file: proto/channelz.proto + +import type { Duration as _google_protobuf_Duration, Duration__Output as _google_protobuf_Duration__Output } from '../../../google/protobuf/Duration'; + +/** + * For use with SocketOption's additional field. This is primarily used for + * SO_RCVTIMEO and SO_SNDTIMEO + */ +export interface SocketOptionTimeout { + 'duration'?: (_google_protobuf_Duration | null); +} + +/** + * For use with SocketOption's additional field. This is primarily used for + * SO_RCVTIMEO and SO_SNDTIMEO + */ +export interface SocketOptionTimeout__Output { + 'duration': (_google_protobuf_Duration__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketRef.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketRef.ts new file mode 100644 index 0000000..52fdb2b --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketRef.ts @@ -0,0 +1,31 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +/** + * SocketRef is a reference to a Socket. + */ +export interface SocketRef { + /** + * The globally unique id for this socket. Must be a positive number. + */ + 'socket_id'?: (number | string | Long); + /** + * An optional name associated with the socket. + */ + 'name'?: (string); +} + +/** + * SocketRef is a reference to a Socket. + */ +export interface SocketRef__Output { + /** + * The globally unique id for this socket. Must be a positive number. + */ + 'socket_id': (string); + /** + * An optional name associated with the socket. + */ + 'name': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Subchannel.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Subchannel.ts new file mode 100644 index 0000000..7122fac --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Subchannel.ts @@ -0,0 +1,70 @@ +// Original file: proto/channelz.proto + +import type { SubchannelRef as _grpc_channelz_v1_SubchannelRef, SubchannelRef__Output as _grpc_channelz_v1_SubchannelRef__Output } from '../../../grpc/channelz/v1/SubchannelRef'; +import type { ChannelData as _grpc_channelz_v1_ChannelData, ChannelData__Output as _grpc_channelz_v1_ChannelData__Output } from '../../../grpc/channelz/v1/ChannelData'; +import type { ChannelRef as _grpc_channelz_v1_ChannelRef, ChannelRef__Output as _grpc_channelz_v1_ChannelRef__Output } from '../../../grpc/channelz/v1/ChannelRef'; +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from '../../../grpc/channelz/v1/SocketRef'; + +/** + * Subchannel is a logical grouping of channels, subchannels, and sockets. + * A subchannel is load balanced over by it's ancestor + */ +export interface Subchannel { + /** + * The identifier for this channel. + */ + 'ref'?: (_grpc_channelz_v1_SubchannelRef | null); + /** + * Data specific to this channel. + */ + 'data'?: (_grpc_channelz_v1_ChannelData | null); + /** + * There are no ordering guarantees on the order of channel refs. + * There may not be cycles in the ref graph. + * A channel ref may be present in more than one channel or subchannel. + */ + 'channel_ref'?: (_grpc_channelz_v1_ChannelRef)[]; + /** + * At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + * There are no ordering guarantees on the order of subchannel refs. + * There may not be cycles in the ref graph. + * A sub channel ref may be present in more than one channel or subchannel. + */ + 'subchannel_ref'?: (_grpc_channelz_v1_SubchannelRef)[]; + /** + * There are no ordering guarantees on the order of sockets. + */ + 'socket_ref'?: (_grpc_channelz_v1_SocketRef)[]; +} + +/** + * Subchannel is a logical grouping of channels, subchannels, and sockets. + * A subchannel is load balanced over by it's ancestor + */ +export interface Subchannel__Output { + /** + * The identifier for this channel. + */ + 'ref': (_grpc_channelz_v1_SubchannelRef__Output | null); + /** + * Data specific to this channel. + */ + 'data': (_grpc_channelz_v1_ChannelData__Output | null); + /** + * There are no ordering guarantees on the order of channel refs. + * There may not be cycles in the ref graph. + * A channel ref may be present in more than one channel or subchannel. + */ + 'channel_ref': (_grpc_channelz_v1_ChannelRef__Output)[]; + /** + * At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + * There are no ordering guarantees on the order of subchannel refs. + * There may not be cycles in the ref graph. + * A sub channel ref may be present in more than one channel or subchannel. + */ + 'subchannel_ref': (_grpc_channelz_v1_SubchannelRef__Output)[]; + /** + * There are no ordering guarantees on the order of sockets. + */ + 'socket_ref': (_grpc_channelz_v1_SocketRef__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SubchannelRef.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SubchannelRef.ts new file mode 100644 index 0000000..b6911c7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SubchannelRef.ts @@ -0,0 +1,31 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +/** + * SubchannelRef is a reference to a Subchannel. + */ +export interface SubchannelRef { + /** + * The globally unique id for this subchannel. Must be a positive number. + */ + 'subchannel_id'?: (number | string | Long); + /** + * An optional name associated with the subchannel. + */ + 'name'?: (string); +} + +/** + * SubchannelRef is a reference to a Subchannel. + */ +export interface SubchannelRef__Output { + /** + * The globally unique id for this subchannel. Must be a positive number. + */ + 'subchannel_id': (string); + /** + * An optional name associated with the subchannel. + */ + 'name': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/orca.ts b/node_modules/@grpc/grpc-js/src/generated/orca.ts new file mode 100644 index 0000000..d57dc75 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/orca.ts @@ -0,0 +1,146 @@ +import type * as grpc from '../index'; +import type { EnumTypeDefinition, MessageTypeDefinition } from '@grpc/proto-loader'; + +import type { DescriptorProto as _google_protobuf_DescriptorProto, DescriptorProto__Output as _google_protobuf_DescriptorProto__Output } from './google/protobuf/DescriptorProto'; +import type { Duration as _google_protobuf_Duration, Duration__Output as _google_protobuf_Duration__Output } from './google/protobuf/Duration'; +import type { EnumDescriptorProto as _google_protobuf_EnumDescriptorProto, EnumDescriptorProto__Output as _google_protobuf_EnumDescriptorProto__Output } from './google/protobuf/EnumDescriptorProto'; +import type { EnumOptions as _google_protobuf_EnumOptions, EnumOptions__Output as _google_protobuf_EnumOptions__Output } from './google/protobuf/EnumOptions'; +import type { EnumValueDescriptorProto as _google_protobuf_EnumValueDescriptorProto, EnumValueDescriptorProto__Output as _google_protobuf_EnumValueDescriptorProto__Output } from './google/protobuf/EnumValueDescriptorProto'; +import type { EnumValueOptions as _google_protobuf_EnumValueOptions, EnumValueOptions__Output as _google_protobuf_EnumValueOptions__Output } from './google/protobuf/EnumValueOptions'; +import type { ExtensionRangeOptions as _google_protobuf_ExtensionRangeOptions, ExtensionRangeOptions__Output as _google_protobuf_ExtensionRangeOptions__Output } from './google/protobuf/ExtensionRangeOptions'; +import type { FeatureSet as _google_protobuf_FeatureSet, FeatureSet__Output as _google_protobuf_FeatureSet__Output } from './google/protobuf/FeatureSet'; +import type { FeatureSetDefaults as _google_protobuf_FeatureSetDefaults, FeatureSetDefaults__Output as _google_protobuf_FeatureSetDefaults__Output } from './google/protobuf/FeatureSetDefaults'; +import type { FieldDescriptorProto as _google_protobuf_FieldDescriptorProto, FieldDescriptorProto__Output as _google_protobuf_FieldDescriptorProto__Output } from './google/protobuf/FieldDescriptorProto'; +import type { FieldOptions as _google_protobuf_FieldOptions, FieldOptions__Output as _google_protobuf_FieldOptions__Output } from './google/protobuf/FieldOptions'; +import type { FileDescriptorProto as _google_protobuf_FileDescriptorProto, FileDescriptorProto__Output as _google_protobuf_FileDescriptorProto__Output } from './google/protobuf/FileDescriptorProto'; +import type { FileDescriptorSet as _google_protobuf_FileDescriptorSet, FileDescriptorSet__Output as _google_protobuf_FileDescriptorSet__Output } from './google/protobuf/FileDescriptorSet'; +import type { FileOptions as _google_protobuf_FileOptions, FileOptions__Output as _google_protobuf_FileOptions__Output } from './google/protobuf/FileOptions'; +import type { GeneratedCodeInfo as _google_protobuf_GeneratedCodeInfo, GeneratedCodeInfo__Output as _google_protobuf_GeneratedCodeInfo__Output } from './google/protobuf/GeneratedCodeInfo'; +import type { MessageOptions as _google_protobuf_MessageOptions, MessageOptions__Output as _google_protobuf_MessageOptions__Output } from './google/protobuf/MessageOptions'; +import type { MethodDescriptorProto as _google_protobuf_MethodDescriptorProto, MethodDescriptorProto__Output as _google_protobuf_MethodDescriptorProto__Output } from './google/protobuf/MethodDescriptorProto'; +import type { MethodOptions as _google_protobuf_MethodOptions, MethodOptions__Output as _google_protobuf_MethodOptions__Output } from './google/protobuf/MethodOptions'; +import type { OneofDescriptorProto as _google_protobuf_OneofDescriptorProto, OneofDescriptorProto__Output as _google_protobuf_OneofDescriptorProto__Output } from './google/protobuf/OneofDescriptorProto'; +import type { OneofOptions as _google_protobuf_OneofOptions, OneofOptions__Output as _google_protobuf_OneofOptions__Output } from './google/protobuf/OneofOptions'; +import type { ServiceDescriptorProto as _google_protobuf_ServiceDescriptorProto, ServiceDescriptorProto__Output as _google_protobuf_ServiceDescriptorProto__Output } from './google/protobuf/ServiceDescriptorProto'; +import type { ServiceOptions as _google_protobuf_ServiceOptions, ServiceOptions__Output as _google_protobuf_ServiceOptions__Output } from './google/protobuf/ServiceOptions'; +import type { SourceCodeInfo as _google_protobuf_SourceCodeInfo, SourceCodeInfo__Output as _google_protobuf_SourceCodeInfo__Output } from './google/protobuf/SourceCodeInfo'; +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from './google/protobuf/Timestamp'; +import type { UninterpretedOption as _google_protobuf_UninterpretedOption, UninterpretedOption__Output as _google_protobuf_UninterpretedOption__Output } from './google/protobuf/UninterpretedOption'; +import type { AnyRules as _validate_AnyRules, AnyRules__Output as _validate_AnyRules__Output } from './validate/AnyRules'; +import type { BoolRules as _validate_BoolRules, BoolRules__Output as _validate_BoolRules__Output } from './validate/BoolRules'; +import type { BytesRules as _validate_BytesRules, BytesRules__Output as _validate_BytesRules__Output } from './validate/BytesRules'; +import type { DoubleRules as _validate_DoubleRules, DoubleRules__Output as _validate_DoubleRules__Output } from './validate/DoubleRules'; +import type { DurationRules as _validate_DurationRules, DurationRules__Output as _validate_DurationRules__Output } from './validate/DurationRules'; +import type { EnumRules as _validate_EnumRules, EnumRules__Output as _validate_EnumRules__Output } from './validate/EnumRules'; +import type { FieldRules as _validate_FieldRules, FieldRules__Output as _validate_FieldRules__Output } from './validate/FieldRules'; +import type { Fixed32Rules as _validate_Fixed32Rules, Fixed32Rules__Output as _validate_Fixed32Rules__Output } from './validate/Fixed32Rules'; +import type { Fixed64Rules as _validate_Fixed64Rules, Fixed64Rules__Output as _validate_Fixed64Rules__Output } from './validate/Fixed64Rules'; +import type { FloatRules as _validate_FloatRules, FloatRules__Output as _validate_FloatRules__Output } from './validate/FloatRules'; +import type { Int32Rules as _validate_Int32Rules, Int32Rules__Output as _validate_Int32Rules__Output } from './validate/Int32Rules'; +import type { Int64Rules as _validate_Int64Rules, Int64Rules__Output as _validate_Int64Rules__Output } from './validate/Int64Rules'; +import type { MapRules as _validate_MapRules, MapRules__Output as _validate_MapRules__Output } from './validate/MapRules'; +import type { MessageRules as _validate_MessageRules, MessageRules__Output as _validate_MessageRules__Output } from './validate/MessageRules'; +import type { RepeatedRules as _validate_RepeatedRules, RepeatedRules__Output as _validate_RepeatedRules__Output } from './validate/RepeatedRules'; +import type { SFixed32Rules as _validate_SFixed32Rules, SFixed32Rules__Output as _validate_SFixed32Rules__Output } from './validate/SFixed32Rules'; +import type { SFixed64Rules as _validate_SFixed64Rules, SFixed64Rules__Output as _validate_SFixed64Rules__Output } from './validate/SFixed64Rules'; +import type { SInt32Rules as _validate_SInt32Rules, SInt32Rules__Output as _validate_SInt32Rules__Output } from './validate/SInt32Rules'; +import type { SInt64Rules as _validate_SInt64Rules, SInt64Rules__Output as _validate_SInt64Rules__Output } from './validate/SInt64Rules'; +import type { StringRules as _validate_StringRules, StringRules__Output as _validate_StringRules__Output } from './validate/StringRules'; +import type { TimestampRules as _validate_TimestampRules, TimestampRules__Output as _validate_TimestampRules__Output } from './validate/TimestampRules'; +import type { UInt32Rules as _validate_UInt32Rules, UInt32Rules__Output as _validate_UInt32Rules__Output } from './validate/UInt32Rules'; +import type { UInt64Rules as _validate_UInt64Rules, UInt64Rules__Output as _validate_UInt64Rules__Output } from './validate/UInt64Rules'; +import type { OrcaLoadReport as _xds_data_orca_v3_OrcaLoadReport, OrcaLoadReport__Output as _xds_data_orca_v3_OrcaLoadReport__Output } from './xds/data/orca/v3/OrcaLoadReport'; +import type { OpenRcaServiceClient as _xds_service_orca_v3_OpenRcaServiceClient, OpenRcaServiceDefinition as _xds_service_orca_v3_OpenRcaServiceDefinition } from './xds/service/orca/v3/OpenRcaService'; +import type { OrcaLoadReportRequest as _xds_service_orca_v3_OrcaLoadReportRequest, OrcaLoadReportRequest__Output as _xds_service_orca_v3_OrcaLoadReportRequest__Output } from './xds/service/orca/v3/OrcaLoadReportRequest'; + +type SubtypeConstructor any, Subtype> = { + new(...args: ConstructorParameters): Subtype; +}; + +export interface ProtoGrpcType { + google: { + protobuf: { + DescriptorProto: MessageTypeDefinition<_google_protobuf_DescriptorProto, _google_protobuf_DescriptorProto__Output> + Duration: MessageTypeDefinition<_google_protobuf_Duration, _google_protobuf_Duration__Output> + Edition: EnumTypeDefinition + EnumDescriptorProto: MessageTypeDefinition<_google_protobuf_EnumDescriptorProto, _google_protobuf_EnumDescriptorProto__Output> + EnumOptions: MessageTypeDefinition<_google_protobuf_EnumOptions, _google_protobuf_EnumOptions__Output> + EnumValueDescriptorProto: MessageTypeDefinition<_google_protobuf_EnumValueDescriptorProto, _google_protobuf_EnumValueDescriptorProto__Output> + EnumValueOptions: MessageTypeDefinition<_google_protobuf_EnumValueOptions, _google_protobuf_EnumValueOptions__Output> + ExtensionRangeOptions: MessageTypeDefinition<_google_protobuf_ExtensionRangeOptions, _google_protobuf_ExtensionRangeOptions__Output> + FeatureSet: MessageTypeDefinition<_google_protobuf_FeatureSet, _google_protobuf_FeatureSet__Output> + FeatureSetDefaults: MessageTypeDefinition<_google_protobuf_FeatureSetDefaults, _google_protobuf_FeatureSetDefaults__Output> + FieldDescriptorProto: MessageTypeDefinition<_google_protobuf_FieldDescriptorProto, _google_protobuf_FieldDescriptorProto__Output> + FieldOptions: MessageTypeDefinition<_google_protobuf_FieldOptions, _google_protobuf_FieldOptions__Output> + FileDescriptorProto: MessageTypeDefinition<_google_protobuf_FileDescriptorProto, _google_protobuf_FileDescriptorProto__Output> + FileDescriptorSet: MessageTypeDefinition<_google_protobuf_FileDescriptorSet, _google_protobuf_FileDescriptorSet__Output> + FileOptions: MessageTypeDefinition<_google_protobuf_FileOptions, _google_protobuf_FileOptions__Output> + GeneratedCodeInfo: MessageTypeDefinition<_google_protobuf_GeneratedCodeInfo, _google_protobuf_GeneratedCodeInfo__Output> + MessageOptions: MessageTypeDefinition<_google_protobuf_MessageOptions, _google_protobuf_MessageOptions__Output> + MethodDescriptorProto: MessageTypeDefinition<_google_protobuf_MethodDescriptorProto, _google_protobuf_MethodDescriptorProto__Output> + MethodOptions: MessageTypeDefinition<_google_protobuf_MethodOptions, _google_protobuf_MethodOptions__Output> + OneofDescriptorProto: MessageTypeDefinition<_google_protobuf_OneofDescriptorProto, _google_protobuf_OneofDescriptorProto__Output> + OneofOptions: MessageTypeDefinition<_google_protobuf_OneofOptions, _google_protobuf_OneofOptions__Output> + ServiceDescriptorProto: MessageTypeDefinition<_google_protobuf_ServiceDescriptorProto, _google_protobuf_ServiceDescriptorProto__Output> + ServiceOptions: MessageTypeDefinition<_google_protobuf_ServiceOptions, _google_protobuf_ServiceOptions__Output> + SourceCodeInfo: MessageTypeDefinition<_google_protobuf_SourceCodeInfo, _google_protobuf_SourceCodeInfo__Output> + SymbolVisibility: EnumTypeDefinition + Timestamp: MessageTypeDefinition<_google_protobuf_Timestamp, _google_protobuf_Timestamp__Output> + UninterpretedOption: MessageTypeDefinition<_google_protobuf_UninterpretedOption, _google_protobuf_UninterpretedOption__Output> + } + } + validate: { + AnyRules: MessageTypeDefinition<_validate_AnyRules, _validate_AnyRules__Output> + BoolRules: MessageTypeDefinition<_validate_BoolRules, _validate_BoolRules__Output> + BytesRules: MessageTypeDefinition<_validate_BytesRules, _validate_BytesRules__Output> + DoubleRules: MessageTypeDefinition<_validate_DoubleRules, _validate_DoubleRules__Output> + DurationRules: MessageTypeDefinition<_validate_DurationRules, _validate_DurationRules__Output> + EnumRules: MessageTypeDefinition<_validate_EnumRules, _validate_EnumRules__Output> + FieldRules: MessageTypeDefinition<_validate_FieldRules, _validate_FieldRules__Output> + Fixed32Rules: MessageTypeDefinition<_validate_Fixed32Rules, _validate_Fixed32Rules__Output> + Fixed64Rules: MessageTypeDefinition<_validate_Fixed64Rules, _validate_Fixed64Rules__Output> + FloatRules: MessageTypeDefinition<_validate_FloatRules, _validate_FloatRules__Output> + Int32Rules: MessageTypeDefinition<_validate_Int32Rules, _validate_Int32Rules__Output> + Int64Rules: MessageTypeDefinition<_validate_Int64Rules, _validate_Int64Rules__Output> + KnownRegex: EnumTypeDefinition + MapRules: MessageTypeDefinition<_validate_MapRules, _validate_MapRules__Output> + MessageRules: MessageTypeDefinition<_validate_MessageRules, _validate_MessageRules__Output> + RepeatedRules: MessageTypeDefinition<_validate_RepeatedRules, _validate_RepeatedRules__Output> + SFixed32Rules: MessageTypeDefinition<_validate_SFixed32Rules, _validate_SFixed32Rules__Output> + SFixed64Rules: MessageTypeDefinition<_validate_SFixed64Rules, _validate_SFixed64Rules__Output> + SInt32Rules: MessageTypeDefinition<_validate_SInt32Rules, _validate_SInt32Rules__Output> + SInt64Rules: MessageTypeDefinition<_validate_SInt64Rules, _validate_SInt64Rules__Output> + StringRules: MessageTypeDefinition<_validate_StringRules, _validate_StringRules__Output> + TimestampRules: MessageTypeDefinition<_validate_TimestampRules, _validate_TimestampRules__Output> + UInt32Rules: MessageTypeDefinition<_validate_UInt32Rules, _validate_UInt32Rules__Output> + UInt64Rules: MessageTypeDefinition<_validate_UInt64Rules, _validate_UInt64Rules__Output> + } + xds: { + data: { + orca: { + v3: { + OrcaLoadReport: MessageTypeDefinition<_xds_data_orca_v3_OrcaLoadReport, _xds_data_orca_v3_OrcaLoadReport__Output> + } + } + } + service: { + orca: { + v3: { + /** + * Out-of-band (OOB) load reporting service for the additional load reporting + * agent that does not sit in the request path. Reports are periodically sampled + * with sufficient frequency to provide temporal association with requests. + * OOB reporting compensates the limitation of in-band reporting in revealing + * costs for backends that do not provide a steady stream of telemetry such as + * long running stream operations and zero QPS services. This is a server + * streaming service, client needs to terminate current RPC and initiate + * a new call to change backend reporting frequency. + */ + OpenRcaService: SubtypeConstructor & { service: _xds_service_orca_v3_OpenRcaServiceDefinition } + OrcaLoadReportRequest: MessageTypeDefinition<_xds_service_orca_v3_OrcaLoadReportRequest, _xds_service_orca_v3_OrcaLoadReportRequest__Output> + } + } + } + } +} + diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/AnyRules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/AnyRules.ts new file mode 100644 index 0000000..f7b34d8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/AnyRules.ts @@ -0,0 +1,44 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + + +/** + * AnyRules describe constraints applied exclusively to the + * `google.protobuf.Any` well-known type + */ +export interface AnyRules { + /** + * Required specifies that this field must be set + */ + 'required'?: (boolean); + /** + * In specifies that this field's `type_url` must be equal to one of the + * specified values. + */ + 'in'?: (string)[]; + /** + * NotIn specifies that this field's `type_url` must not be equal to any of + * the specified values. + */ + 'not_in'?: (string)[]; +} + +/** + * AnyRules describe constraints applied exclusively to the + * `google.protobuf.Any` well-known type + */ +export interface AnyRules__Output { + /** + * Required specifies that this field must be set + */ + 'required': (boolean); + /** + * In specifies that this field's `type_url` must be equal to one of the + * specified values. + */ + 'in': (string)[]; + /** + * NotIn specifies that this field's `type_url` must not be equal to any of + * the specified values. + */ + 'not_in': (string)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/BoolRules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/BoolRules.ts new file mode 100644 index 0000000..2174f4a --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/BoolRules.ts @@ -0,0 +1,22 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + + +/** + * BoolRules describes the constraints applied to `bool` values + */ +export interface BoolRules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (boolean); +} + +/** + * BoolRules describes the constraints applied to `bool` values + */ +export interface BoolRules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/BytesRules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/BytesRules.ts new file mode 100644 index 0000000..ebfabd3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/BytesRules.ts @@ -0,0 +1,153 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + +import type { Long } from '@grpc/proto-loader'; + +/** + * BytesRules describe the constraints applied to `bytes` values + */ +export interface BytesRules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (Buffer | Uint8Array | string); + /** + * MinLen specifies that this field must be the specified number of bytes + * at a minimum + */ + 'min_len'?: (number | string | Long); + /** + * MaxLen specifies that this field must be the specified number of bytes + * at a maximum + */ + 'max_len'?: (number | string | Long); + /** + * Pattern specifes that this field must match against the specified + * regular expression (RE2 syntax). The included expression should elide + * any delimiters. + */ + 'pattern'?: (string); + /** + * Prefix specifies that this field must have the specified bytes at the + * beginning of the string. + */ + 'prefix'?: (Buffer | Uint8Array | string); + /** + * Suffix specifies that this field must have the specified bytes at the + * end of the string. + */ + 'suffix'?: (Buffer | Uint8Array | string); + /** + * Contains specifies that this field must have the specified bytes + * anywhere in the string. + */ + 'contains'?: (Buffer | Uint8Array | string); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (Buffer | Uint8Array | string)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (Buffer | Uint8Array | string)[]; + /** + * Ip specifies that the field must be a valid IP (v4 or v6) address in + * byte format + */ + 'ip'?: (boolean); + /** + * Ipv4 specifies that the field must be a valid IPv4 address in byte + * format + */ + 'ipv4'?: (boolean); + /** + * Ipv6 specifies that the field must be a valid IPv6 address in byte + * format + */ + 'ipv6'?: (boolean); + /** + * Len specifies that this field must be the specified number of bytes + */ + 'len'?: (number | string | Long); + /** + * WellKnown rules provide advanced constraints against common byte + * patterns + */ + 'well_known'?: "ip"|"ipv4"|"ipv6"; +} + +/** + * BytesRules describe the constraints applied to `bytes` values + */ +export interface BytesRules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (Buffer); + /** + * MinLen specifies that this field must be the specified number of bytes + * at a minimum + */ + 'min_len': (string); + /** + * MaxLen specifies that this field must be the specified number of bytes + * at a maximum + */ + 'max_len': (string); + /** + * Pattern specifes that this field must match against the specified + * regular expression (RE2 syntax). The included expression should elide + * any delimiters. + */ + 'pattern': (string); + /** + * Prefix specifies that this field must have the specified bytes at the + * beginning of the string. + */ + 'prefix': (Buffer); + /** + * Suffix specifies that this field must have the specified bytes at the + * end of the string. + */ + 'suffix': (Buffer); + /** + * Contains specifies that this field must have the specified bytes + * anywhere in the string. + */ + 'contains': (Buffer); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (Buffer)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (Buffer)[]; + /** + * Ip specifies that the field must be a valid IP (v4 or v6) address in + * byte format + */ + 'ip'?: (boolean); + /** + * Ipv4 specifies that the field must be a valid IPv4 address in byte + * format + */ + 'ipv4'?: (boolean); + /** + * Ipv6 specifies that the field must be a valid IPv6 address in byte + * format + */ + 'ipv6'?: (boolean); + /** + * Len specifies that this field must be the specified number of bytes + */ + 'len': (string); + /** + * WellKnown rules provide advanced constraints against common byte + * patterns + */ + 'well_known'?: "ip"|"ipv4"|"ipv6"; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/DoubleRules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/DoubleRules.ts new file mode 100644 index 0000000..fbf4181 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/DoubleRules.ts @@ -0,0 +1,86 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + + +/** + * DoubleRules describes the constraints applied to `double` values + */ +export interface DoubleRules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number | string); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number | string); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number | string); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number | string); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number | string); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number | string)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number | string)[]; +} + +/** + * DoubleRules describes the constraints applied to `double` values + */ +export interface DoubleRules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (number)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/DurationRules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/DurationRules.ts new file mode 100644 index 0000000..c73d71d --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/DurationRules.ts @@ -0,0 +1,93 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + +import type { Duration as _google_protobuf_Duration, Duration__Output as _google_protobuf_Duration__Output } from '../google/protobuf/Duration'; + +/** + * DurationRules describe the constraints applied exclusively to the + * `google.protobuf.Duration` well-known type + */ +export interface DurationRules { + /** + * Required specifies that this field must be set + */ + 'required'?: (boolean); + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (_google_protobuf_Duration | null); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (_google_protobuf_Duration | null); + /** + * Lt specifies that this field must be less than the specified value, + * inclusive + */ + 'lte'?: (_google_protobuf_Duration | null); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive + */ + 'gt'?: (_google_protobuf_Duration | null); + /** + * Gte specifies that this field must be greater than the specified value, + * inclusive + */ + 'gte'?: (_google_protobuf_Duration | null); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (_google_protobuf_Duration)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (_google_protobuf_Duration)[]; +} + +/** + * DurationRules describe the constraints applied exclusively to the + * `google.protobuf.Duration` well-known type + */ +export interface DurationRules__Output { + /** + * Required specifies that this field must be set + */ + 'required': (boolean); + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (_google_protobuf_Duration__Output | null); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (_google_protobuf_Duration__Output | null); + /** + * Lt specifies that this field must be less than the specified value, + * inclusive + */ + 'lte': (_google_protobuf_Duration__Output | null); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive + */ + 'gt': (_google_protobuf_Duration__Output | null); + /** + * Gte specifies that this field must be greater than the specified value, + * inclusive + */ + 'gte': (_google_protobuf_Duration__Output | null); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (_google_protobuf_Duration__Output)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (_google_protobuf_Duration__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/EnumRules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/EnumRules.ts new file mode 100644 index 0000000..9d996c7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/EnumRules.ts @@ -0,0 +1,52 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + + +/** + * EnumRules describe the constraints applied to enum values + */ +export interface EnumRules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number); + /** + * DefinedOnly specifies that this field must be only one of the defined + * values for this enum, failing on any undefined value. + */ + 'defined_only'?: (boolean); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number)[]; +} + +/** + * EnumRules describe the constraints applied to enum values + */ +export interface EnumRules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (number); + /** + * DefinedOnly specifies that this field must be only one of the defined + * values for this enum, failing on any undefined value. + */ + 'defined_only': (boolean); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (number)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/FieldRules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/FieldRules.ts new file mode 100644 index 0000000..c1ab3c8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/FieldRules.ts @@ -0,0 +1,102 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + +import type { FloatRules as _validate_FloatRules, FloatRules__Output as _validate_FloatRules__Output } from '../validate/FloatRules'; +import type { DoubleRules as _validate_DoubleRules, DoubleRules__Output as _validate_DoubleRules__Output } from '../validate/DoubleRules'; +import type { Int32Rules as _validate_Int32Rules, Int32Rules__Output as _validate_Int32Rules__Output } from '../validate/Int32Rules'; +import type { Int64Rules as _validate_Int64Rules, Int64Rules__Output as _validate_Int64Rules__Output } from '../validate/Int64Rules'; +import type { UInt32Rules as _validate_UInt32Rules, UInt32Rules__Output as _validate_UInt32Rules__Output } from '../validate/UInt32Rules'; +import type { UInt64Rules as _validate_UInt64Rules, UInt64Rules__Output as _validate_UInt64Rules__Output } from '../validate/UInt64Rules'; +import type { SInt32Rules as _validate_SInt32Rules, SInt32Rules__Output as _validate_SInt32Rules__Output } from '../validate/SInt32Rules'; +import type { SInt64Rules as _validate_SInt64Rules, SInt64Rules__Output as _validate_SInt64Rules__Output } from '../validate/SInt64Rules'; +import type { Fixed32Rules as _validate_Fixed32Rules, Fixed32Rules__Output as _validate_Fixed32Rules__Output } from '../validate/Fixed32Rules'; +import type { Fixed64Rules as _validate_Fixed64Rules, Fixed64Rules__Output as _validate_Fixed64Rules__Output } from '../validate/Fixed64Rules'; +import type { SFixed32Rules as _validate_SFixed32Rules, SFixed32Rules__Output as _validate_SFixed32Rules__Output } from '../validate/SFixed32Rules'; +import type { SFixed64Rules as _validate_SFixed64Rules, SFixed64Rules__Output as _validate_SFixed64Rules__Output } from '../validate/SFixed64Rules'; +import type { BoolRules as _validate_BoolRules, BoolRules__Output as _validate_BoolRules__Output } from '../validate/BoolRules'; +import type { StringRules as _validate_StringRules, StringRules__Output as _validate_StringRules__Output } from '../validate/StringRules'; +import type { BytesRules as _validate_BytesRules, BytesRules__Output as _validate_BytesRules__Output } from '../validate/BytesRules'; +import type { EnumRules as _validate_EnumRules, EnumRules__Output as _validate_EnumRules__Output } from '../validate/EnumRules'; +import type { MessageRules as _validate_MessageRules, MessageRules__Output as _validate_MessageRules__Output } from '../validate/MessageRules'; +import type { RepeatedRules as _validate_RepeatedRules, RepeatedRules__Output as _validate_RepeatedRules__Output } from '../validate/RepeatedRules'; +import type { MapRules as _validate_MapRules, MapRules__Output as _validate_MapRules__Output } from '../validate/MapRules'; +import type { AnyRules as _validate_AnyRules, AnyRules__Output as _validate_AnyRules__Output } from '../validate/AnyRules'; +import type { DurationRules as _validate_DurationRules, DurationRules__Output as _validate_DurationRules__Output } from '../validate/DurationRules'; +import type { TimestampRules as _validate_TimestampRules, TimestampRules__Output as _validate_TimestampRules__Output } from '../validate/TimestampRules'; + +/** + * FieldRules encapsulates the rules for each type of field. Depending on the + * field, the correct set should be used to ensure proper validations. + */ +export interface FieldRules { + /** + * Scalar Field Types + */ + 'float'?: (_validate_FloatRules | null); + 'double'?: (_validate_DoubleRules | null); + 'int32'?: (_validate_Int32Rules | null); + 'int64'?: (_validate_Int64Rules | null); + 'uint32'?: (_validate_UInt32Rules | null); + 'uint64'?: (_validate_UInt64Rules | null); + 'sint32'?: (_validate_SInt32Rules | null); + 'sint64'?: (_validate_SInt64Rules | null); + 'fixed32'?: (_validate_Fixed32Rules | null); + 'fixed64'?: (_validate_Fixed64Rules | null); + 'sfixed32'?: (_validate_SFixed32Rules | null); + 'sfixed64'?: (_validate_SFixed64Rules | null); + 'bool'?: (_validate_BoolRules | null); + 'string'?: (_validate_StringRules | null); + 'bytes'?: (_validate_BytesRules | null); + /** + * Complex Field Types + */ + 'enum'?: (_validate_EnumRules | null); + 'message'?: (_validate_MessageRules | null); + 'repeated'?: (_validate_RepeatedRules | null); + 'map'?: (_validate_MapRules | null); + /** + * Well-Known Field Types + */ + 'any'?: (_validate_AnyRules | null); + 'duration'?: (_validate_DurationRules | null); + 'timestamp'?: (_validate_TimestampRules | null); + 'type'?: "float"|"double"|"int32"|"int64"|"uint32"|"uint64"|"sint32"|"sint64"|"fixed32"|"fixed64"|"sfixed32"|"sfixed64"|"bool"|"string"|"bytes"|"enum"|"repeated"|"map"|"any"|"duration"|"timestamp"; +} + +/** + * FieldRules encapsulates the rules for each type of field. Depending on the + * field, the correct set should be used to ensure proper validations. + */ +export interface FieldRules__Output { + /** + * Scalar Field Types + */ + 'float'?: (_validate_FloatRules__Output | null); + 'double'?: (_validate_DoubleRules__Output | null); + 'int32'?: (_validate_Int32Rules__Output | null); + 'int64'?: (_validate_Int64Rules__Output | null); + 'uint32'?: (_validate_UInt32Rules__Output | null); + 'uint64'?: (_validate_UInt64Rules__Output | null); + 'sint32'?: (_validate_SInt32Rules__Output | null); + 'sint64'?: (_validate_SInt64Rules__Output | null); + 'fixed32'?: (_validate_Fixed32Rules__Output | null); + 'fixed64'?: (_validate_Fixed64Rules__Output | null); + 'sfixed32'?: (_validate_SFixed32Rules__Output | null); + 'sfixed64'?: (_validate_SFixed64Rules__Output | null); + 'bool'?: (_validate_BoolRules__Output | null); + 'string'?: (_validate_StringRules__Output | null); + 'bytes'?: (_validate_BytesRules__Output | null); + /** + * Complex Field Types + */ + 'enum'?: (_validate_EnumRules__Output | null); + 'message': (_validate_MessageRules__Output | null); + 'repeated'?: (_validate_RepeatedRules__Output | null); + 'map'?: (_validate_MapRules__Output | null); + /** + * Well-Known Field Types + */ + 'any'?: (_validate_AnyRules__Output | null); + 'duration'?: (_validate_DurationRules__Output | null); + 'timestamp'?: (_validate_TimestampRules__Output | null); + 'type'?: "float"|"double"|"int32"|"int64"|"uint32"|"uint64"|"sint32"|"sint64"|"fixed32"|"fixed64"|"sfixed32"|"sfixed64"|"bool"|"string"|"bytes"|"enum"|"repeated"|"map"|"any"|"duration"|"timestamp"; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/Fixed32Rules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/Fixed32Rules.ts new file mode 100644 index 0000000..070e6cf --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/Fixed32Rules.ts @@ -0,0 +1,86 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + + +/** + * Fixed32Rules describes the constraints applied to `fixed32` values + */ +export interface Fixed32Rules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number)[]; +} + +/** + * Fixed32Rules describes the constraints applied to `fixed32` values + */ +export interface Fixed32Rules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (number)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/Fixed64Rules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/Fixed64Rules.ts new file mode 100644 index 0000000..43717ab --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/Fixed64Rules.ts @@ -0,0 +1,87 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + +import type { Long } from '@grpc/proto-loader'; + +/** + * Fixed64Rules describes the constraints applied to `fixed64` values + */ +export interface Fixed64Rules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number | string | Long); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number | string | Long); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number | string | Long); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number | string | Long); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number | string | Long); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number | string | Long)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number | string | Long)[]; +} + +/** + * Fixed64Rules describes the constraints applied to `fixed64` values + */ +export interface Fixed64Rules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (string); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (string); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (string); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (string); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (string); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (string)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (string)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/FloatRules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/FloatRules.ts new file mode 100644 index 0000000..35038f0 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/FloatRules.ts @@ -0,0 +1,86 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + + +/** + * FloatRules describes the constraints applied to `float` values + */ +export interface FloatRules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number | string); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number | string); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number | string); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number | string); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number | string); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number | string)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number | string)[]; +} + +/** + * FloatRules describes the constraints applied to `float` values + */ +export interface FloatRules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (number)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/Int32Rules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/Int32Rules.ts new file mode 100644 index 0000000..dfe10ea --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/Int32Rules.ts @@ -0,0 +1,86 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + + +/** + * Int32Rules describes the constraints applied to `int32` values + */ +export interface Int32Rules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number)[]; +} + +/** + * Int32Rules describes the constraints applied to `int32` values + */ +export interface Int32Rules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (number)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/Int64Rules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/Int64Rules.ts new file mode 100644 index 0000000..edfecd5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/Int64Rules.ts @@ -0,0 +1,87 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + +import type { Long } from '@grpc/proto-loader'; + +/** + * Int64Rules describes the constraints applied to `int64` values + */ +export interface Int64Rules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number | string | Long); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number | string | Long); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number | string | Long); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number | string | Long); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number | string | Long); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number | string | Long)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number | string | Long)[]; +} + +/** + * Int64Rules describes the constraints applied to `int64` values + */ +export interface Int64Rules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (string); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (string); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (string); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (string); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (string); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (string)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (string)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/KnownRegex.ts b/node_modules/@grpc/grpc-js/src/generated/validate/KnownRegex.ts new file mode 100644 index 0000000..b33d1bb --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/KnownRegex.ts @@ -0,0 +1,38 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + +/** + * WellKnownRegex contain some well-known patterns. + */ +export const KnownRegex = { + UNKNOWN: 'UNKNOWN', + /** + * HTTP header name as defined by RFC 7230. + */ + HTTP_HEADER_NAME: 'HTTP_HEADER_NAME', + /** + * HTTP header value as defined by RFC 7230. + */ + HTTP_HEADER_VALUE: 'HTTP_HEADER_VALUE', +} as const; + +/** + * WellKnownRegex contain some well-known patterns. + */ +export type KnownRegex = + | 'UNKNOWN' + | 0 + /** + * HTTP header name as defined by RFC 7230. + */ + | 'HTTP_HEADER_NAME' + | 1 + /** + * HTTP header value as defined by RFC 7230. + */ + | 'HTTP_HEADER_VALUE' + | 2 + +/** + * WellKnownRegex contain some well-known patterns. + */ +export type KnownRegex__Output = typeof KnownRegex[keyof typeof KnownRegex] diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/MapRules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/MapRules.ts new file mode 100644 index 0000000..d7c7766 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/MapRules.ts @@ -0,0 +1,66 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + +import type { FieldRules as _validate_FieldRules, FieldRules__Output as _validate_FieldRules__Output } from '../validate/FieldRules'; +import type { Long } from '@grpc/proto-loader'; + +/** + * MapRules describe the constraints applied to `map` values + */ +export interface MapRules { + /** + * MinPairs specifies that this field must have the specified number of + * KVs at a minimum + */ + 'min_pairs'?: (number | string | Long); + /** + * MaxPairs specifies that this field must have the specified number of + * KVs at a maximum + */ + 'max_pairs'?: (number | string | Long); + /** + * NoSparse specifies values in this field cannot be unset. This only + * applies to map's with message value types. + */ + 'no_sparse'?: (boolean); + /** + * Keys specifies the constraints to be applied to each key in the field. + */ + 'keys'?: (_validate_FieldRules | null); + /** + * Values specifies the constraints to be applied to the value of each key + * in the field. Message values will still have their validations evaluated + * unless skip is specified here. + */ + 'values'?: (_validate_FieldRules | null); +} + +/** + * MapRules describe the constraints applied to `map` values + */ +export interface MapRules__Output { + /** + * MinPairs specifies that this field must have the specified number of + * KVs at a minimum + */ + 'min_pairs': (string); + /** + * MaxPairs specifies that this field must have the specified number of + * KVs at a maximum + */ + 'max_pairs': (string); + /** + * NoSparse specifies values in this field cannot be unset. This only + * applies to map's with message value types. + */ + 'no_sparse': (boolean); + /** + * Keys specifies the constraints to be applied to each key in the field. + */ + 'keys': (_validate_FieldRules__Output | null); + /** + * Values specifies the constraints to be applied to the value of each key + * in the field. Message values will still have their validations evaluated + * unless skip is specified here. + */ + 'values': (_validate_FieldRules__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/MessageRules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/MessageRules.ts new file mode 100644 index 0000000..6a56ef1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/MessageRules.ts @@ -0,0 +1,34 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + + +/** + * MessageRules describe the constraints applied to embedded message values. + * For message-type fields, validation is performed recursively. + */ +export interface MessageRules { + /** + * Skip specifies that the validation rules of this field should not be + * evaluated + */ + 'skip'?: (boolean); + /** + * Required specifies that this field must be set + */ + 'required'?: (boolean); +} + +/** + * MessageRules describe the constraints applied to embedded message values. + * For message-type fields, validation is performed recursively. + */ +export interface MessageRules__Output { + /** + * Skip specifies that the validation rules of this field should not be + * evaluated + */ + 'skip': (boolean); + /** + * Required specifies that this field must be set + */ + 'required': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/RepeatedRules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/RepeatedRules.ts new file mode 100644 index 0000000..d045fa8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/RepeatedRules.ts @@ -0,0 +1,60 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + +import type { FieldRules as _validate_FieldRules, FieldRules__Output as _validate_FieldRules__Output } from '../validate/FieldRules'; +import type { Long } from '@grpc/proto-loader'; + +/** + * RepeatedRules describe the constraints applied to `repeated` values + */ +export interface RepeatedRules { + /** + * MinItems specifies that this field must have the specified number of + * items at a minimum + */ + 'min_items'?: (number | string | Long); + /** + * MaxItems specifies that this field must have the specified number of + * items at a maximum + */ + 'max_items'?: (number | string | Long); + /** + * Unique specifies that all elements in this field must be unique. This + * contraint is only applicable to scalar and enum types (messages are not + * supported). + */ + 'unique'?: (boolean); + /** + * Items specifies the contraints to be applied to each item in the field. + * Repeated message fields will still execute validation against each item + * unless skip is specified here. + */ + 'items'?: (_validate_FieldRules | null); +} + +/** + * RepeatedRules describe the constraints applied to `repeated` values + */ +export interface RepeatedRules__Output { + /** + * MinItems specifies that this field must have the specified number of + * items at a minimum + */ + 'min_items': (string); + /** + * MaxItems specifies that this field must have the specified number of + * items at a maximum + */ + 'max_items': (string); + /** + * Unique specifies that all elements in this field must be unique. This + * contraint is only applicable to scalar and enum types (messages are not + * supported). + */ + 'unique': (boolean); + /** + * Items specifies the contraints to be applied to each item in the field. + * Repeated message fields will still execute validation against each item + * unless skip is specified here. + */ + 'items': (_validate_FieldRules__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/SFixed32Rules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/SFixed32Rules.ts new file mode 100644 index 0000000..cbed6f2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/SFixed32Rules.ts @@ -0,0 +1,86 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + + +/** + * SFixed32Rules describes the constraints applied to `sfixed32` values + */ +export interface SFixed32Rules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number)[]; +} + +/** + * SFixed32Rules describes the constraints applied to `sfixed32` values + */ +export interface SFixed32Rules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (number)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/SFixed64Rules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/SFixed64Rules.ts new file mode 100644 index 0000000..7d0bbf1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/SFixed64Rules.ts @@ -0,0 +1,87 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + +import type { Long } from '@grpc/proto-loader'; + +/** + * SFixed64Rules describes the constraints applied to `sfixed64` values + */ +export interface SFixed64Rules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number | string | Long); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number | string | Long); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number | string | Long); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number | string | Long); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number | string | Long); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number | string | Long)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number | string | Long)[]; +} + +/** + * SFixed64Rules describes the constraints applied to `sfixed64` values + */ +export interface SFixed64Rules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (string); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (string); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (string); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (string); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (string); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (string)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (string)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/SInt32Rules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/SInt32Rules.ts new file mode 100644 index 0000000..f35ed41 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/SInt32Rules.ts @@ -0,0 +1,86 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + + +/** + * SInt32Rules describes the constraints applied to `sint32` values + */ +export interface SInt32Rules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number)[]; +} + +/** + * SInt32Rules describes the constraints applied to `sint32` values + */ +export interface SInt32Rules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (number)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/SInt64Rules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/SInt64Rules.ts new file mode 100644 index 0000000..68b7ea6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/SInt64Rules.ts @@ -0,0 +1,87 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + +import type { Long } from '@grpc/proto-loader'; + +/** + * SInt64Rules describes the constraints applied to `sint64` values + */ +export interface SInt64Rules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number | string | Long); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number | string | Long); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number | string | Long); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number | string | Long); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number | string | Long); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number | string | Long)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number | string | Long)[]; +} + +/** + * SInt64Rules describes the constraints applied to `sint64` values + */ +export interface SInt64Rules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (string); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (string); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (string); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (string); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (string); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (string)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (string)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/StringRules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/StringRules.ts new file mode 100644 index 0000000..2989d6f --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/StringRules.ts @@ -0,0 +1,288 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + +import type { KnownRegex as _validate_KnownRegex, KnownRegex__Output as _validate_KnownRegex__Output } from '../validate/KnownRegex'; +import type { Long } from '@grpc/proto-loader'; + +/** + * StringRules describe the constraints applied to `string` values + */ +export interface StringRules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (string); + /** + * MinLen specifies that this field must be the specified number of + * characters (Unicode code points) at a minimum. Note that the number of + * characters may differ from the number of bytes in the string. + */ + 'min_len'?: (number | string | Long); + /** + * MaxLen specifies that this field must be the specified number of + * characters (Unicode code points) at a maximum. Note that the number of + * characters may differ from the number of bytes in the string. + */ + 'max_len'?: (number | string | Long); + /** + * MinBytes specifies that this field must be the specified number of bytes + * at a minimum + */ + 'min_bytes'?: (number | string | Long); + /** + * MaxBytes specifies that this field must be the specified number of bytes + * at a maximum + */ + 'max_bytes'?: (number | string | Long); + /** + * Pattern specifes that this field must match against the specified + * regular expression (RE2 syntax). The included expression should elide + * any delimiters. + */ + 'pattern'?: (string); + /** + * Prefix specifies that this field must have the specified substring at + * the beginning of the string. + */ + 'prefix'?: (string); + /** + * Suffix specifies that this field must have the specified substring at + * the end of the string. + */ + 'suffix'?: (string); + /** + * Contains specifies that this field must have the specified substring + * anywhere in the string. + */ + 'contains'?: (string); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (string)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (string)[]; + /** + * Email specifies that the field must be a valid email address as + * defined by RFC 5322 + */ + 'email'?: (boolean); + /** + * Hostname specifies that the field must be a valid hostname as + * defined by RFC 1034. This constraint does not support + * internationalized domain names (IDNs). + */ + 'hostname'?: (boolean); + /** + * Ip specifies that the field must be a valid IP (v4 or v6) address. + * Valid IPv6 addresses should not include surrounding square brackets. + */ + 'ip'?: (boolean); + /** + * Ipv4 specifies that the field must be a valid IPv4 address. + */ + 'ipv4'?: (boolean); + /** + * Ipv6 specifies that the field must be a valid IPv6 address. Valid + * IPv6 addresses should not include surrounding square brackets. + */ + 'ipv6'?: (boolean); + /** + * Uri specifies that the field must be a valid, absolute URI as defined + * by RFC 3986 + */ + 'uri'?: (boolean); + /** + * UriRef specifies that the field must be a valid URI as defined by RFC + * 3986 and may be relative or absolute. + */ + 'uri_ref'?: (boolean); + /** + * Len specifies that this field must be the specified number of + * characters (Unicode code points). Note that the number of + * characters may differ from the number of bytes in the string. + */ + 'len'?: (number | string | Long); + /** + * LenBytes specifies that this field must be the specified number of bytes + * at a minimum + */ + 'len_bytes'?: (number | string | Long); + /** + * Address specifies that the field must be either a valid hostname as + * defined by RFC 1034 (which does not support internationalized domain + * names or IDNs), or it can be a valid IP (v4 or v6). + */ + 'address'?: (boolean); + /** + * Uuid specifies that the field must be a valid UUID as defined by + * RFC 4122 + */ + 'uuid'?: (boolean); + /** + * NotContains specifies that this field cannot have the specified substring + * anywhere in the string. + */ + 'not_contains'?: (string); + /** + * WellKnownRegex specifies a common well known pattern defined as a regex. + */ + 'well_known_regex'?: (_validate_KnownRegex); + /** + * This applies to regexes HTTP_HEADER_NAME and HTTP_HEADER_VALUE to enable + * strict header validation. + * By default, this is true, and HTTP header validations are RFC-compliant. + * Setting to false will enable a looser validations that only disallows + * \r\n\0 characters, which can be used to bypass header matching rules. + */ + 'strict'?: (boolean); + /** + * WellKnown rules provide advanced constraints against common string + * patterns + */ + 'well_known'?: "email"|"hostname"|"ip"|"ipv4"|"ipv6"|"uri"|"uri_ref"|"address"|"uuid"|"well_known_regex"; +} + +/** + * StringRules describe the constraints applied to `string` values + */ +export interface StringRules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (string); + /** + * MinLen specifies that this field must be the specified number of + * characters (Unicode code points) at a minimum. Note that the number of + * characters may differ from the number of bytes in the string. + */ + 'min_len': (string); + /** + * MaxLen specifies that this field must be the specified number of + * characters (Unicode code points) at a maximum. Note that the number of + * characters may differ from the number of bytes in the string. + */ + 'max_len': (string); + /** + * MinBytes specifies that this field must be the specified number of bytes + * at a minimum + */ + 'min_bytes': (string); + /** + * MaxBytes specifies that this field must be the specified number of bytes + * at a maximum + */ + 'max_bytes': (string); + /** + * Pattern specifes that this field must match against the specified + * regular expression (RE2 syntax). The included expression should elide + * any delimiters. + */ + 'pattern': (string); + /** + * Prefix specifies that this field must have the specified substring at + * the beginning of the string. + */ + 'prefix': (string); + /** + * Suffix specifies that this field must have the specified substring at + * the end of the string. + */ + 'suffix': (string); + /** + * Contains specifies that this field must have the specified substring + * anywhere in the string. + */ + 'contains': (string); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (string)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (string)[]; + /** + * Email specifies that the field must be a valid email address as + * defined by RFC 5322 + */ + 'email'?: (boolean); + /** + * Hostname specifies that the field must be a valid hostname as + * defined by RFC 1034. This constraint does not support + * internationalized domain names (IDNs). + */ + 'hostname'?: (boolean); + /** + * Ip specifies that the field must be a valid IP (v4 or v6) address. + * Valid IPv6 addresses should not include surrounding square brackets. + */ + 'ip'?: (boolean); + /** + * Ipv4 specifies that the field must be a valid IPv4 address. + */ + 'ipv4'?: (boolean); + /** + * Ipv6 specifies that the field must be a valid IPv6 address. Valid + * IPv6 addresses should not include surrounding square brackets. + */ + 'ipv6'?: (boolean); + /** + * Uri specifies that the field must be a valid, absolute URI as defined + * by RFC 3986 + */ + 'uri'?: (boolean); + /** + * UriRef specifies that the field must be a valid URI as defined by RFC + * 3986 and may be relative or absolute. + */ + 'uri_ref'?: (boolean); + /** + * Len specifies that this field must be the specified number of + * characters (Unicode code points). Note that the number of + * characters may differ from the number of bytes in the string. + */ + 'len': (string); + /** + * LenBytes specifies that this field must be the specified number of bytes + * at a minimum + */ + 'len_bytes': (string); + /** + * Address specifies that the field must be either a valid hostname as + * defined by RFC 1034 (which does not support internationalized domain + * names or IDNs), or it can be a valid IP (v4 or v6). + */ + 'address'?: (boolean); + /** + * Uuid specifies that the field must be a valid UUID as defined by + * RFC 4122 + */ + 'uuid'?: (boolean); + /** + * NotContains specifies that this field cannot have the specified substring + * anywhere in the string. + */ + 'not_contains': (string); + /** + * WellKnownRegex specifies a common well known pattern defined as a regex. + */ + 'well_known_regex'?: (_validate_KnownRegex__Output); + /** + * This applies to regexes HTTP_HEADER_NAME and HTTP_HEADER_VALUE to enable + * strict header validation. + * By default, this is true, and HTTP header validations are RFC-compliant. + * Setting to false will enable a looser validations that only disallows + * \r\n\0 characters, which can be used to bypass header matching rules. + */ + 'strict': (boolean); + /** + * WellKnown rules provide advanced constraints against common string + * patterns + */ + 'well_known'?: "email"|"hostname"|"ip"|"ipv4"|"ipv6"|"uri"|"uri_ref"|"address"|"uuid"|"well_known_regex"; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/TimestampRules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/TimestampRules.ts new file mode 100644 index 0000000..098da41 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/TimestampRules.ts @@ -0,0 +1,106 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../google/protobuf/Timestamp'; +import type { Duration as _google_protobuf_Duration, Duration__Output as _google_protobuf_Duration__Output } from '../google/protobuf/Duration'; + +/** + * TimestampRules describe the constraints applied exclusively to the + * `google.protobuf.Timestamp` well-known type + */ +export interface TimestampRules { + /** + * Required specifies that this field must be set + */ + 'required'?: (boolean); + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (_google_protobuf_Timestamp | null); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (_google_protobuf_Timestamp | null); + /** + * Lte specifies that this field must be less than the specified value, + * inclusive + */ + 'lte'?: (_google_protobuf_Timestamp | null); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive + */ + 'gt'?: (_google_protobuf_Timestamp | null); + /** + * Gte specifies that this field must be greater than the specified value, + * inclusive + */ + 'gte'?: (_google_protobuf_Timestamp | null); + /** + * LtNow specifies that this must be less than the current time. LtNow + * can only be used with the Within rule. + */ + 'lt_now'?: (boolean); + /** + * GtNow specifies that this must be greater than the current time. GtNow + * can only be used with the Within rule. + */ + 'gt_now'?: (boolean); + /** + * Within specifies that this field must be within this duration of the + * current time. This constraint can be used alone or with the LtNow and + * GtNow rules. + */ + 'within'?: (_google_protobuf_Duration | null); +} + +/** + * TimestampRules describe the constraints applied exclusively to the + * `google.protobuf.Timestamp` well-known type + */ +export interface TimestampRules__Output { + /** + * Required specifies that this field must be set + */ + 'required': (boolean); + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (_google_protobuf_Timestamp__Output | null); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (_google_protobuf_Timestamp__Output | null); + /** + * Lte specifies that this field must be less than the specified value, + * inclusive + */ + 'lte': (_google_protobuf_Timestamp__Output | null); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive + */ + 'gt': (_google_protobuf_Timestamp__Output | null); + /** + * Gte specifies that this field must be greater than the specified value, + * inclusive + */ + 'gte': (_google_protobuf_Timestamp__Output | null); + /** + * LtNow specifies that this must be less than the current time. LtNow + * can only be used with the Within rule. + */ + 'lt_now': (boolean); + /** + * GtNow specifies that this must be greater than the current time. GtNow + * can only be used with the Within rule. + */ + 'gt_now': (boolean); + /** + * Within specifies that this field must be within this duration of the + * current time. This constraint can be used alone or with the LtNow and + * GtNow rules. + */ + 'within': (_google_protobuf_Duration__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/UInt32Rules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/UInt32Rules.ts new file mode 100644 index 0000000..e095c55 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/UInt32Rules.ts @@ -0,0 +1,86 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + + +/** + * UInt32Rules describes the constraints applied to `uint32` values + */ +export interface UInt32Rules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number)[]; +} + +/** + * UInt32Rules describes the constraints applied to `uint32` values + */ +export interface UInt32Rules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (number); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (number); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (number); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (number); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (number); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (number)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (number)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/validate/UInt64Rules.ts b/node_modules/@grpc/grpc-js/src/generated/validate/UInt64Rules.ts new file mode 100644 index 0000000..95fa783 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/validate/UInt64Rules.ts @@ -0,0 +1,87 @@ +// Original file: proto/protoc-gen-validate/validate/validate.proto + +import type { Long } from '@grpc/proto-loader'; + +/** + * UInt64Rules describes the constraints applied to `uint64` values + */ +export interface UInt64Rules { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const'?: (number | string | Long); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt'?: (number | string | Long); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte'?: (number | string | Long); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt'?: (number | string | Long); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte'?: (number | string | Long); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in'?: (number | string | Long)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in'?: (number | string | Long)[]; +} + +/** + * UInt64Rules describes the constraints applied to `uint64` values + */ +export interface UInt64Rules__Output { + /** + * Const specifies that this field must be exactly the specified value + */ + 'const': (string); + /** + * Lt specifies that this field must be less than the specified value, + * exclusive + */ + 'lt': (string); + /** + * Lte specifies that this field must be less than or equal to the + * specified value, inclusive + */ + 'lte': (string); + /** + * Gt specifies that this field must be greater than the specified value, + * exclusive. If the value of Gt is larger than a specified Lt or Lte, the + * range is reversed. + */ + 'gt': (string); + /** + * Gte specifies that this field must be greater than or equal to the + * specified value, inclusive. If the value of Gte is larger than a + * specified Lt or Lte, the range is reversed. + */ + 'gte': (string); + /** + * In specifies that this field must be equal to one of the specified + * values + */ + 'in': (string)[]; + /** + * NotIn specifies that this field cannot be equal to one of the specified + * values + */ + 'not_in': (string)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/xds/data/orca/v3/OrcaLoadReport.ts b/node_modules/@grpc/grpc-js/src/generated/xds/data/orca/v3/OrcaLoadReport.ts new file mode 100644 index 0000000..155da79 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/xds/data/orca/v3/OrcaLoadReport.ts @@ -0,0 +1,113 @@ +// Original file: proto/xds/xds/data/orca/v3/orca_load_report.proto + +import type { Long } from '@grpc/proto-loader'; + +export interface OrcaLoadReport { + /** + * CPU utilization expressed as a fraction of available CPU resources. This + * should be derived from the latest sample or measurement. The value may be + * larger than 1.0 when the usage exceeds the reporter dependent notion of + * soft limits. + */ + 'cpu_utilization'?: (number | string); + /** + * Memory utilization expressed as a fraction of available memory + * resources. This should be derived from the latest sample or measurement. + */ + 'mem_utilization'?: (number | string); + /** + * Total RPS being served by an endpoint. This should cover all services that an endpoint is + * responsible for. + * Deprecated -- use ``rps_fractional`` field instead. + * @deprecated + */ + 'rps'?: (number | string | Long); + /** + * Application specific requests costs. Each value is an absolute cost (e.g. 3487 bytes of + * storage) associated with the request. + */ + 'request_cost'?: ({[key: string]: number | string}); + /** + * Resource utilization values. Each value is expressed as a fraction of total resources + * available, derived from the latest sample or measurement. + */ + 'utilization'?: ({[key: string]: number | string}); + /** + * Total RPS being served by an endpoint. This should cover all services that an endpoint is + * responsible for. + */ + 'rps_fractional'?: (number | string); + /** + * Total EPS (errors/second) being served by an endpoint. This should cover + * all services that an endpoint is responsible for. + */ + 'eps'?: (number | string); + /** + * Application specific opaque metrics. + */ + 'named_metrics'?: ({[key: string]: number | string}); + /** + * Application specific utilization expressed as a fraction of available + * resources. For example, an application may report the max of CPU and memory + * utilization for better load balancing if it is both CPU and memory bound. + * This should be derived from the latest sample or measurement. + * The value may be larger than 1.0 when the usage exceeds the reporter + * dependent notion of soft limits. + */ + 'application_utilization'?: (number | string); +} + +export interface OrcaLoadReport__Output { + /** + * CPU utilization expressed as a fraction of available CPU resources. This + * should be derived from the latest sample or measurement. The value may be + * larger than 1.0 when the usage exceeds the reporter dependent notion of + * soft limits. + */ + 'cpu_utilization': (number); + /** + * Memory utilization expressed as a fraction of available memory + * resources. This should be derived from the latest sample or measurement. + */ + 'mem_utilization': (number); + /** + * Total RPS being served by an endpoint. This should cover all services that an endpoint is + * responsible for. + * Deprecated -- use ``rps_fractional`` field instead. + * @deprecated + */ + 'rps': (string); + /** + * Application specific requests costs. Each value is an absolute cost (e.g. 3487 bytes of + * storage) associated with the request. + */ + 'request_cost': ({[key: string]: number}); + /** + * Resource utilization values. Each value is expressed as a fraction of total resources + * available, derived from the latest sample or measurement. + */ + 'utilization': ({[key: string]: number}); + /** + * Total RPS being served by an endpoint. This should cover all services that an endpoint is + * responsible for. + */ + 'rps_fractional': (number); + /** + * Total EPS (errors/second) being served by an endpoint. This should cover + * all services that an endpoint is responsible for. + */ + 'eps': (number); + /** + * Application specific opaque metrics. + */ + 'named_metrics': ({[key: string]: number}); + /** + * Application specific utilization expressed as a fraction of available + * resources. For example, an application may report the max of CPU and memory + * utilization for better load balancing if it is both CPU and memory bound. + * This should be derived from the latest sample or measurement. + * The value may be larger than 1.0 when the usage exceeds the reporter + * dependent notion of soft limits. + */ + 'application_utilization': (number); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/xds/service/orca/v3/OpenRcaService.ts b/node_modules/@grpc/grpc-js/src/generated/xds/service/orca/v3/OpenRcaService.ts new file mode 100644 index 0000000..f111da8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/xds/service/orca/v3/OpenRcaService.ts @@ -0,0 +1,43 @@ +// Original file: proto/xds/xds/service/orca/v3/orca.proto + +import type * as grpc from '../../../../../index' +import type { MethodDefinition } from '@grpc/proto-loader' +import type { OrcaLoadReport as _xds_data_orca_v3_OrcaLoadReport, OrcaLoadReport__Output as _xds_data_orca_v3_OrcaLoadReport__Output } from '../../../../xds/data/orca/v3/OrcaLoadReport'; +import type { OrcaLoadReportRequest as _xds_service_orca_v3_OrcaLoadReportRequest, OrcaLoadReportRequest__Output as _xds_service_orca_v3_OrcaLoadReportRequest__Output } from '../../../../xds/service/orca/v3/OrcaLoadReportRequest'; + +/** + * Out-of-band (OOB) load reporting service for the additional load reporting + * agent that does not sit in the request path. Reports are periodically sampled + * with sufficient frequency to provide temporal association with requests. + * OOB reporting compensates the limitation of in-band reporting in revealing + * costs for backends that do not provide a steady stream of telemetry such as + * long running stream operations and zero QPS services. This is a server + * streaming service, client needs to terminate current RPC and initiate + * a new call to change backend reporting frequency. + */ +export interface OpenRcaServiceClient extends grpc.Client { + StreamCoreMetrics(argument: _xds_service_orca_v3_OrcaLoadReportRequest, metadata: grpc.Metadata, options?: grpc.CallOptions): grpc.ClientReadableStream<_xds_data_orca_v3_OrcaLoadReport__Output>; + StreamCoreMetrics(argument: _xds_service_orca_v3_OrcaLoadReportRequest, options?: grpc.CallOptions): grpc.ClientReadableStream<_xds_data_orca_v3_OrcaLoadReport__Output>; + streamCoreMetrics(argument: _xds_service_orca_v3_OrcaLoadReportRequest, metadata: grpc.Metadata, options?: grpc.CallOptions): grpc.ClientReadableStream<_xds_data_orca_v3_OrcaLoadReport__Output>; + streamCoreMetrics(argument: _xds_service_orca_v3_OrcaLoadReportRequest, options?: grpc.CallOptions): grpc.ClientReadableStream<_xds_data_orca_v3_OrcaLoadReport__Output>; + +} + +/** + * Out-of-band (OOB) load reporting service for the additional load reporting + * agent that does not sit in the request path. Reports are periodically sampled + * with sufficient frequency to provide temporal association with requests. + * OOB reporting compensates the limitation of in-band reporting in revealing + * costs for backends that do not provide a steady stream of telemetry such as + * long running stream operations and zero QPS services. This is a server + * streaming service, client needs to terminate current RPC and initiate + * a new call to change backend reporting frequency. + */ +export interface OpenRcaServiceHandlers extends grpc.UntypedServiceImplementation { + StreamCoreMetrics: grpc.handleServerStreamingCall<_xds_service_orca_v3_OrcaLoadReportRequest__Output, _xds_data_orca_v3_OrcaLoadReport>; + +} + +export interface OpenRcaServiceDefinition extends grpc.ServiceDefinition { + StreamCoreMetrics: MethodDefinition<_xds_service_orca_v3_OrcaLoadReportRequest, _xds_data_orca_v3_OrcaLoadReport, _xds_service_orca_v3_OrcaLoadReportRequest__Output, _xds_data_orca_v3_OrcaLoadReport__Output> +} diff --git a/node_modules/@grpc/grpc-js/src/generated/xds/service/orca/v3/OrcaLoadReportRequest.ts b/node_modules/@grpc/grpc-js/src/generated/xds/service/orca/v3/OrcaLoadReportRequest.ts new file mode 100644 index 0000000..f1fb3c2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/xds/service/orca/v3/OrcaLoadReportRequest.ts @@ -0,0 +1,29 @@ +// Original file: proto/xds/xds/service/orca/v3/orca.proto + +import type { Duration as _google_protobuf_Duration, Duration__Output as _google_protobuf_Duration__Output } from '../../../../google/protobuf/Duration'; + +export interface OrcaLoadReportRequest { + /** + * Interval for generating Open RCA core metric responses. + */ + 'report_interval'?: (_google_protobuf_Duration | null); + /** + * Request costs to collect. If this is empty, all known requests costs tracked by + * the load reporting agent will be returned. This provides an opportunity for + * the client to selectively obtain a subset of tracked costs. + */ + 'request_cost_names'?: (string)[]; +} + +export interface OrcaLoadReportRequest__Output { + /** + * Interval for generating Open RCA core metric responses. + */ + 'report_interval': (_google_protobuf_Duration__Output | null); + /** + * Request costs to collect. If this is empty, all known requests costs tracked by + * the load reporting agent will be returned. This provides an opportunity for + * the client to selectively obtain a subset of tracked costs. + */ + 'request_cost_names': (string)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/http_proxy.ts b/node_modules/@grpc/grpc-js/src/http_proxy.ts new file mode 100644 index 0000000..c40d207 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/http_proxy.ts @@ -0,0 +1,315 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { log } from './logging'; +import { LogVerbosity } from './constants'; +import { isIPv4, Socket } from 'net'; +import * as http from 'http'; +import * as logging from './logging'; +import { + SubchannelAddress, + isTcpSubchannelAddress, + subchannelAddressToString, +} from './subchannel-address'; +import { ChannelOptions } from './channel-options'; +import { GrpcUri, parseUri, splitHostPort, uriToString } from './uri-parser'; +import { URL } from 'url'; +import { DEFAULT_PORT } from './resolver-dns'; + +const TRACER_NAME = 'proxy'; + +function trace(text: string): void { + logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text); +} + +interface ProxyInfo { + address?: string; + creds?: string; +} + +function getProxyInfo(): ProxyInfo { + let proxyEnv = ''; + let envVar = ''; + /* Prefer using 'grpc_proxy'. Fallback on 'http_proxy' if it is not set. + * Also prefer using 'https_proxy' with fallback on 'http_proxy'. The + * fallback behavior can be removed if there's a demand for it. + */ + if (process.env.grpc_proxy) { + envVar = 'grpc_proxy'; + proxyEnv = process.env.grpc_proxy; + } else if (process.env.https_proxy) { + envVar = 'https_proxy'; + proxyEnv = process.env.https_proxy; + } else if (process.env.http_proxy) { + envVar = 'http_proxy'; + proxyEnv = process.env.http_proxy; + } else { + return {}; + } + let proxyUrl: URL; + try { + proxyUrl = new URL(proxyEnv); + } catch (e) { + log(LogVerbosity.ERROR, `cannot parse value of "${envVar}" env var`); + return {}; + } + if (proxyUrl.protocol !== 'http:') { + log( + LogVerbosity.ERROR, + `"${proxyUrl.protocol}" scheme not supported in proxy URI` + ); + return {}; + } + let userCred: string | null = null; + if (proxyUrl.username) { + if (proxyUrl.password) { + log(LogVerbosity.INFO, 'userinfo found in proxy URI'); + userCred = decodeURIComponent(`${proxyUrl.username}:${proxyUrl.password}`); + } else { + userCred = proxyUrl.username; + } + } + const hostname = proxyUrl.hostname; + let port = proxyUrl.port; + /* The proxy URL uses the scheme "http:", which has a default port number of + * 80. We need to set that explicitly here if it is omitted because otherwise + * it will use gRPC's default port 443. */ + if (port === '') { + port = '80'; + } + const result: ProxyInfo = { + address: `${hostname}:${port}`, + }; + if (userCred) { + result.creds = userCred; + } + trace( + 'Proxy server ' + result.address + ' set by environment variable ' + envVar + ); + return result; +} + +function getNoProxyHostList(): string[] { + /* Prefer using 'no_grpc_proxy'. Fallback on 'no_proxy' if it is not set. */ + let noProxyStr: string | undefined = process.env.no_grpc_proxy; + let envVar = 'no_grpc_proxy'; + if (!noProxyStr) { + noProxyStr = process.env.no_proxy; + envVar = 'no_proxy'; + } + if (noProxyStr) { + trace('No proxy server list set by environment variable ' + envVar); + return noProxyStr.split(','); + } else { + return []; + } +} + +interface CIDRNotation { + ip: number; + prefixLength: number; +} + +/* + * The groups correspond to CIDR parts as follows: + * 1. ip + * 2. prefixLength + */ + +export function parseCIDR(cidrString: string): CIDRNotation | null { + const splitRange = cidrString.split('/'); + if (splitRange.length !== 2) { + return null; + } + const prefixLength = parseInt(splitRange[1], 10); + if (!isIPv4(splitRange[0]) || Number.isNaN(prefixLength) || prefixLength < 0 || prefixLength > 32) { + return null; + } + return { + ip: ipToInt(splitRange[0]), + prefixLength: prefixLength + }; +} + +function ipToInt(ip: string) { + return ip.split(".").reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0); +} + +function isIpInCIDR(cidr: CIDRNotation, serverHost: string) { + const ip = cidr.ip; + const mask = -1 << (32 - cidr.prefixLength); + const hostIP = ipToInt(serverHost); + + return (hostIP & mask) === (ip & mask); +} + +function hostMatchesNoProxyList(serverHost: string): boolean { + for (const host of getNoProxyHostList()) { + const parsedCIDR = parseCIDR(host); + // host is a CIDR and serverHost is an IP address + if (isIPv4(serverHost) && parsedCIDR && isIpInCIDR(parsedCIDR, serverHost)) { + return true; + } else if (serverHost.endsWith(host)) { + // host is a single IP or a domain name suffix + return true; + } + } + return false; +} + +export interface ProxyMapResult { + target: GrpcUri; + extraOptions: ChannelOptions; +} + +export function mapProxyName( + target: GrpcUri, + options: ChannelOptions +): ProxyMapResult { + const noProxyResult: ProxyMapResult = { + target: target, + extraOptions: {}, + }; + if ((options['grpc.enable_http_proxy'] ?? 1) === 0) { + return noProxyResult; + } + if (target.scheme === 'unix') { + return noProxyResult; + } + const proxyInfo = getProxyInfo(); + if (!proxyInfo.address) { + return noProxyResult; + } + const hostPort = splitHostPort(target.path); + if (!hostPort) { + return noProxyResult; + } + const serverHost = hostPort.host; + if (hostMatchesNoProxyList(serverHost)) { + trace('Not using proxy for target in no_proxy list: ' + uriToString(target)); + return noProxyResult; + } + const extraOptions: ChannelOptions = { + 'grpc.http_connect_target': uriToString(target), + }; + if (proxyInfo.creds) { + extraOptions['grpc.http_connect_creds'] = proxyInfo.creds; + } + return { + target: { + scheme: 'dns', + path: proxyInfo.address, + }, + extraOptions: extraOptions, + }; +} + +export function getProxiedConnection( + address: SubchannelAddress, + channelOptions: ChannelOptions +): Promise { + if (!('grpc.http_connect_target' in channelOptions)) { + return Promise.resolve(null); + } + const realTarget = channelOptions['grpc.http_connect_target'] as string; + const parsedTarget = parseUri(realTarget); + if (parsedTarget === null) { + return Promise.resolve(null); + } + const splitHostPost = splitHostPort(parsedTarget.path); + if (splitHostPost === null) { + return Promise.resolve(null); + } + const hostPort = `${splitHostPost.host}:${ + splitHostPost.port ?? DEFAULT_PORT + }`; + const options: http.RequestOptions = { + method: 'CONNECT', + path: hostPort, + }; + const headers: http.OutgoingHttpHeaders = { + Host: hostPort, + }; + // Connect to the subchannel address as a proxy + if (isTcpSubchannelAddress(address)) { + options.host = address.host; + options.port = address.port; + } else { + options.socketPath = address.path; + } + if ('grpc.http_connect_creds' in channelOptions) { + headers['Proxy-Authorization'] = + 'Basic ' + + Buffer.from(channelOptions['grpc.http_connect_creds'] as string).toString( + 'base64' + ); + } + options.headers = headers; + const proxyAddressString = subchannelAddressToString(address); + trace('Using proxy ' + proxyAddressString + ' to connect to ' + options.path); + return new Promise((resolve, reject) => { + const request = http.request(options); + request.once('connect', (res, socket, head) => { + request.removeAllListeners(); + socket.removeAllListeners(); + if (res.statusCode === 200) { + trace( + 'Successfully connected to ' + + options.path + + ' through proxy ' + + proxyAddressString + ); + // The HTTP client may have already read a few bytes of the proxied + // connection. If that's the case, put them back into the socket. + // See https://github.com/grpc/grpc-node/issues/2744. + if (head.length > 0) { + socket.unshift(head); + } + trace( + 'Successfully established a plaintext connection to ' + + options.path + + ' through proxy ' + + proxyAddressString + ); + resolve(socket); + } else { + log( + LogVerbosity.ERROR, + 'Failed to connect to ' + + options.path + + ' through proxy ' + + proxyAddressString + + ' with status ' + + res.statusCode + ); + reject(); + } + }); + request.once('error', err => { + request.removeAllListeners(); + log( + LogVerbosity.ERROR, + 'Failed to connect to proxy ' + + proxyAddressString + + ' with error ' + + err.message + ); + reject(); + }); + request.end(); + }); +} diff --git a/node_modules/@grpc/grpc-js/src/index.ts b/node_modules/@grpc/grpc-js/src/index.ts new file mode 100644 index 0000000..f26f65a --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/index.ts @@ -0,0 +1,312 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { + ClientDuplexStream, + ClientReadableStream, + ClientUnaryCall, + ClientWritableStream, + ServiceError, +} from './call'; +import { CallCredentials, OAuth2Client } from './call-credentials'; +import { StatusObject } from './call-interface'; +import { Channel, ChannelImplementation } from './channel'; +import { CompressionAlgorithms } from './compression-algorithms'; +import { ConnectivityState } from './connectivity-state'; +import { ChannelCredentials, VerifyOptions } from './channel-credentials'; +import { + CallOptions, + Client, + ClientOptions, + CallInvocationTransformer, + CallProperties, + UnaryCallback, +} from './client'; +import { LogVerbosity, Status, Propagate } from './constants'; +import * as logging from './logging'; +import { + Deserialize, + loadPackageDefinition, + makeClientConstructor, + MethodDefinition, + Serialize, + ServerMethodDefinition, + ServiceDefinition, +} from './make-client'; +import { Metadata, MetadataOptions, MetadataValue } from './metadata'; +import { + ConnectionInjector, + Server, + ServerOptions, + UntypedHandleCall, + UntypedServiceImplementation, +} from './server'; +import { KeyCertPair, ServerCredentials } from './server-credentials'; +import { StatusBuilder } from './status-builder'; +import { + handleBidiStreamingCall, + handleServerStreamingCall, + handleClientStreamingCall, + handleUnaryCall, + sendUnaryData, + ServerUnaryCall, + ServerReadableStream, + ServerWritableStream, + ServerDuplexStream, + ServerErrorResponse, +} from './server-call'; + +export { OAuth2Client }; + +/**** Client Credentials ****/ + +// Using assign only copies enumerable properties, which is what we want +export const credentials = { + /** + * Combine a ChannelCredentials with any number of CallCredentials into a + * single ChannelCredentials object. + * @param channelCredentials The ChannelCredentials object. + * @param callCredentials Any number of CallCredentials objects. + * @return The resulting ChannelCredentials object. + */ + combineChannelCredentials: ( + channelCredentials: ChannelCredentials, + ...callCredentials: CallCredentials[] + ): ChannelCredentials => { + return callCredentials.reduce( + (acc, other) => acc.compose(other), + channelCredentials + ); + }, + + /** + * Combine any number of CallCredentials into a single CallCredentials + * object. + * @param first The first CallCredentials object. + * @param additional Any number of additional CallCredentials objects. + * @return The resulting CallCredentials object. + */ + combineCallCredentials: ( + first: CallCredentials, + ...additional: CallCredentials[] + ): CallCredentials => { + return additional.reduce((acc, other) => acc.compose(other), first); + }, + + // from channel-credentials.ts + createInsecure: ChannelCredentials.createInsecure, + createSsl: ChannelCredentials.createSsl, + createFromSecureContext: ChannelCredentials.createFromSecureContext, + + // from call-credentials.ts + createFromMetadataGenerator: CallCredentials.createFromMetadataGenerator, + createFromGoogleCredential: CallCredentials.createFromGoogleCredential, + createEmpty: CallCredentials.createEmpty, +}; + +/**** Metadata ****/ + +export { Metadata, MetadataOptions, MetadataValue }; + +/**** Constants ****/ + +export { + LogVerbosity as logVerbosity, + Status as status, + ConnectivityState as connectivityState, + Propagate as propagate, + CompressionAlgorithms as compressionAlgorithms, + // TODO: Other constants as well +}; + +/**** Client ****/ + +export { + Client, + ClientOptions, + loadPackageDefinition, + makeClientConstructor, + makeClientConstructor as makeGenericClientConstructor, + CallProperties, + CallInvocationTransformer, + ChannelImplementation as Channel, + Channel as ChannelInterface, + UnaryCallback as requestCallback, +}; + +/** + * Close a Client object. + * @param client The client to close. + */ +export const closeClient = (client: Client) => client.close(); + +export const waitForClientReady = ( + client: Client, + deadline: Date | number, + callback: (error?: Error) => void +) => client.waitForReady(deadline, callback); + +/* Interfaces */ + +export { + sendUnaryData, + ChannelCredentials, + CallCredentials, + Deadline, + Serialize as serialize, + Deserialize as deserialize, + ClientUnaryCall, + ClientReadableStream, + ClientWritableStream, + ClientDuplexStream, + CallOptions, + MethodDefinition, + StatusObject, + ServiceError, + ServerUnaryCall, + ServerReadableStream, + ServerWritableStream, + ServerDuplexStream, + ServerErrorResponse, + ServerMethodDefinition, + ServiceDefinition, + UntypedHandleCall, + UntypedServiceImplementation, + VerifyOptions, +}; + +/**** Server ****/ + +export { + handleBidiStreamingCall, + handleServerStreamingCall, + handleUnaryCall, + handleClientStreamingCall, +}; + +/* eslint-disable @typescript-eslint/no-explicit-any */ +export type Call = + | ClientUnaryCall + | ClientReadableStream + | ClientWritableStream + | ClientDuplexStream; +/* eslint-enable @typescript-eslint/no-explicit-any */ + +/**** Unimplemented function stubs ****/ + +/* eslint-disable @typescript-eslint/no-explicit-any */ + +export const loadObject = (value: any, options: any): never => { + throw new Error( + 'Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead' + ); +}; + +export const load = (filename: any, format: any, options: any): never => { + throw new Error( + 'Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead' + ); +}; + +export const setLogger = (logger: Partial): void => { + logging.setLogger(logger); +}; + +export const setLogVerbosity = (verbosity: LogVerbosity): void => { + logging.setLoggerVerbosity(verbosity); +}; + +export { ConnectionInjector, Server, ServerOptions }; +export { ServerCredentials }; +export { KeyCertPair }; + +export const getClientChannel = (client: Client) => { + return Client.prototype.getChannel.call(client); +}; + +export { StatusBuilder }; + +export { Listener, InterceptingListener } from './call-interface'; + +export { + Requester, + ListenerBuilder, + RequesterBuilder, + Interceptor, + InterceptorOptions, + InterceptorProvider, + InterceptingCall, + InterceptorConfigurationError, + NextCall, +} from './client-interceptors'; + +export { + GrpcObject, + ServiceClientConstructor, + ProtobufTypeDefinition, +} from './make-client'; + +export { ChannelOptions } from './channel-options'; + +export { getChannelzServiceDefinition, getChannelzHandlers } from './channelz'; + +export { addAdminServicesToServer } from './admin'; + +export { + ServiceConfig, + LoadBalancingConfig, + MethodConfig, + RetryPolicy, +} from './service-config'; + +export { + ServerListener, + FullServerListener, + ServerListenerBuilder, + Responder, + FullResponder, + ResponderBuilder, + ServerInterceptingCallInterface, + ServerInterceptingCall, + ServerInterceptor, +} from './server-interceptors'; + +export { ServerMetricRecorder } from './orca'; + +import * as experimental from './experimental'; +export { experimental }; + +import * as resolver_dns from './resolver-dns'; +import * as resolver_uds from './resolver-uds'; +import * as resolver_ip from './resolver-ip'; +import * as load_balancer_pick_first from './load-balancer-pick-first'; +import * as load_balancer_round_robin from './load-balancer-round-robin'; +import * as load_balancer_outlier_detection from './load-balancer-outlier-detection'; +import * as load_balancer_weighted_round_robin from './load-balancer-weighted-round-robin'; +import * as channelz from './channelz'; +import { Deadline } from './deadline'; + +(() => { + resolver_dns.setup(); + resolver_uds.setup(); + resolver_ip.setup(); + load_balancer_pick_first.setup(); + load_balancer_round_robin.setup(); + load_balancer_outlier_detection.setup(); + load_balancer_weighted_round_robin.setup(); + channelz.setup(); +})(); diff --git a/node_modules/@grpc/grpc-js/src/internal-channel.ts b/node_modules/@grpc/grpc-js/src/internal-channel.ts new file mode 100644 index 0000000..db3827f --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/internal-channel.ts @@ -0,0 +1,878 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { ChannelCredentials } from './channel-credentials'; +import { ChannelOptions } from './channel-options'; +import { ResolvingLoadBalancer } from './resolving-load-balancer'; +import { SubchannelPool, getSubchannelPool } from './subchannel-pool'; +import { ChannelControlHelper } from './load-balancer'; +import { UnavailablePicker, Picker, QueuePicker, PickArgs, PickResult, PickResultType } from './picker'; +import { Metadata } from './metadata'; +import { Status, LogVerbosity, Propagate } from './constants'; +import { FilterStackFactory } from './filter-stack'; +import { CompressionFilterFactory } from './compression-filter'; +import { + CallConfig, + ConfigSelector, + getDefaultAuthority, + mapUriDefaultScheme, +} from './resolver'; +import { trace, isTracerEnabled } from './logging'; +import { SubchannelAddress } from './subchannel-address'; +import { mapProxyName } from './http_proxy'; +import { GrpcUri, parseUri, uriToString } from './uri-parser'; +import { ServerSurfaceCall } from './server-call'; + +import { ConnectivityState } from './connectivity-state'; +import { + ChannelInfo, + ChannelRef, + ChannelzCallTracker, + ChannelzChildrenTracker, + ChannelzTrace, + registerChannelzChannel, + SubchannelRef, + unregisterChannelzRef, +} from './channelz'; +import { LoadBalancingCall } from './load-balancing-call'; +import { CallCredentials } from './call-credentials'; +import { Call, CallStreamOptions, StatusObject } from './call-interface'; +import { Deadline, deadlineToString } from './deadline'; +import { ResolvingCall } from './resolving-call'; +import { getNextCallNumber } from './call-number'; +import { restrictControlPlaneStatusCode } from './control-plane-status'; +import { + MessageBufferTracker, + RetryingCall, + RetryThrottler, +} from './retrying-call'; +import { + BaseSubchannelWrapper, + ConnectivityStateListener, + SubchannelInterface, +} from './subchannel-interface'; + +/** + * See https://nodejs.org/api/timers.html#timers_setinterval_callback_delay_args + */ +const MAX_TIMEOUT_TIME = 2147483647; + +const MIN_IDLE_TIMEOUT_MS = 1000; + +// 30 minutes +const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000; + +interface ConnectivityStateWatcher { + currentState: ConnectivityState; + timer: NodeJS.Timeout | null; + callback: (error?: Error) => void; +} + +interface NoneConfigResult { + type: 'NONE'; +} + +interface SuccessConfigResult { + type: 'SUCCESS'; + config: CallConfig; +} + +interface ErrorConfigResult { + type: 'ERROR'; + error: StatusObject; +} + +type GetConfigResult = + | NoneConfigResult + | SuccessConfigResult + | ErrorConfigResult; + +const RETRY_THROTTLER_MAP: Map = new Map(); + +const DEFAULT_RETRY_BUFFER_SIZE_BYTES = 1 << 24; // 16 MB +const DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES = 1 << 20; // 1 MB + +class ChannelSubchannelWrapper + extends BaseSubchannelWrapper + implements SubchannelInterface +{ + private refCount = 0; + private subchannelStateListener: ConnectivityStateListener; + constructor( + childSubchannel: SubchannelInterface, + private channel: InternalChannel + ) { + super(childSubchannel); + this.subchannelStateListener = ( + subchannel, + previousState, + newState, + keepaliveTime + ) => { + channel.throttleKeepalive(keepaliveTime); + }; + } + + ref(): void { + if (this.refCount === 0) { + this.child.addConnectivityStateListener(this.subchannelStateListener); + this.channel.addWrappedSubchannel(this); + } + this.child.ref(); + this.refCount += 1; + } + + unref(): void { + this.child.unref(); + this.refCount -= 1; + if (this.refCount <= 0) { + this.child.removeConnectivityStateListener(this.subchannelStateListener); + this.channel.removeWrappedSubchannel(this); + } + } +} + +class ShutdownPicker implements Picker { + pick(pickArgs: PickArgs): PickResult { + return { + pickResultType: PickResultType.DROP, + status: { + code: Status.UNAVAILABLE, + details: 'Channel closed before call started', + metadata: new Metadata() + }, + subchannel: null, + onCallStarted: null, + onCallEnded: null + } + } +} + +export const SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = 'grpc.internal.no_subchannel'; +class ChannelzInfoTracker { + readonly trace = new ChannelzTrace(); + readonly callTracker = new ChannelzCallTracker(); + readonly childrenTracker = new ChannelzChildrenTracker(); + state: ConnectivityState = ConnectivityState.IDLE; + constructor(private target: string) {} + + getChannelzInfoCallback(): () => ChannelInfo { + return () => { + return { + target: this.target, + state: this.state, + trace: this.trace, + callTracker: this.callTracker, + children: this.childrenTracker.getChildLists() + }; + }; + } +} + +export class InternalChannel { + private readonly resolvingLoadBalancer: ResolvingLoadBalancer; + private readonly subchannelPool: SubchannelPool; + private connectivityState: ConnectivityState = ConnectivityState.IDLE; + private currentPicker: Picker = new UnavailablePicker(); + /** + * Calls queued up to get a call config. Should only be populated before the + * first time the resolver returns a result, which includes the ConfigSelector. + */ + private configSelectionQueue: ResolvingCall[] = []; + private pickQueue: LoadBalancingCall[] = []; + private connectivityStateWatchers: ConnectivityStateWatcher[] = []; + private readonly defaultAuthority: string; + private readonly filterStackFactory: FilterStackFactory; + private readonly target: GrpcUri; + /** + * This timer does not do anything on its own. Its purpose is to hold the + * event loop open while there are any pending calls for the channel that + * have not yet been assigned to specific subchannels. In other words, + * the invariant is that callRefTimer is reffed if and only if pickQueue + * is non-empty. In addition, the timer is null while the state is IDLE or + * SHUTDOWN and there are no pending calls. + */ + private callRefTimer: NodeJS.Timeout | null = null; + private configSelector: ConfigSelector | null = null; + /** + * This is the error from the name resolver if it failed most recently. It + * is only used to end calls that start while there is no config selector + * and the name resolver is in backoff, so it should be nulled if + * configSelector becomes set or the channel state becomes anything other + * than TRANSIENT_FAILURE. + */ + private currentResolutionError: StatusObject | null = null; + private readonly retryBufferTracker: MessageBufferTracker; + private keepaliveTime: number; + private readonly wrappedSubchannels: Set = + new Set(); + + private callCount = 0; + private idleTimer: NodeJS.Timeout | null = null; + private readonly idleTimeoutMs: number; + private lastActivityTimestamp: Date; + + // Channelz info + private readonly channelzEnabled: boolean = true; + private readonly channelzRef: ChannelRef; + private readonly channelzInfoTracker: ChannelzInfoTracker; + + /** + * Randomly generated ID to be passed to the config selector, for use by + * ring_hash in xDS. An integer distributed approximately uniformly between + * 0 and MAX_SAFE_INTEGER. + */ + private readonly randomChannelId = Math.floor( + Math.random() * Number.MAX_SAFE_INTEGER + ); + + constructor( + target: string, + private readonly credentials: ChannelCredentials, + private readonly options: ChannelOptions + ) { + if (typeof target !== 'string') { + throw new TypeError('Channel target must be a string'); + } + if (!(credentials instanceof ChannelCredentials)) { + throw new TypeError( + 'Channel credentials must be a ChannelCredentials object' + ); + } + if (options) { + if (typeof options !== 'object') { + throw new TypeError('Channel options must be an object'); + } + } + this.channelzInfoTracker = new ChannelzInfoTracker(target); + const originalTargetUri = parseUri(target); + if (originalTargetUri === null) { + throw new Error(`Could not parse target name "${target}"`); + } + /* This ensures that the target has a scheme that is registered with the + * resolver */ + const defaultSchemeMapResult = mapUriDefaultScheme(originalTargetUri); + if (defaultSchemeMapResult === null) { + throw new Error( + `Could not find a default scheme for target name "${target}"` + ); + } + + if (this.options['grpc.enable_channelz'] === 0) { + this.channelzEnabled = false; + } + + this.channelzRef = registerChannelzChannel( + target, + this.channelzInfoTracker.getChannelzInfoCallback(), + this.channelzEnabled + ); + if (this.channelzEnabled) { + this.channelzInfoTracker.trace.addTrace('CT_INFO', 'Channel created'); + } + + if (this.options['grpc.default_authority']) { + this.defaultAuthority = this.options['grpc.default_authority'] as string; + } else { + this.defaultAuthority = getDefaultAuthority(defaultSchemeMapResult); + } + const proxyMapResult = mapProxyName(defaultSchemeMapResult, options); + this.target = proxyMapResult.target; + this.options = Object.assign({}, this.options, proxyMapResult.extraOptions); + + /* The global boolean parameter to getSubchannelPool has the inverse meaning to what + * the grpc.use_local_subchannel_pool channel option means. */ + this.subchannelPool = getSubchannelPool( + (this.options['grpc.use_local_subchannel_pool'] ?? 0) === 0 + ); + this.retryBufferTracker = new MessageBufferTracker( + this.options['grpc.retry_buffer_size'] ?? DEFAULT_RETRY_BUFFER_SIZE_BYTES, + this.options['grpc.per_rpc_retry_buffer_size'] ?? + DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES + ); + this.keepaliveTime = this.options['grpc.keepalive_time_ms'] ?? -1; + this.idleTimeoutMs = Math.max( + this.options['grpc.client_idle_timeout_ms'] ?? DEFAULT_IDLE_TIMEOUT_MS, + MIN_IDLE_TIMEOUT_MS + ); + const channelControlHelper: ChannelControlHelper = { + createSubchannel: ( + subchannelAddress: SubchannelAddress, + subchannelArgs: ChannelOptions + ) => { + const finalSubchannelArgs: ChannelOptions = {}; + for (const [key, value] of Object.entries(subchannelArgs)) { + if (!key.startsWith(SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX)) { + finalSubchannelArgs[key] = value; + } + } + const subchannel = this.subchannelPool.getOrCreateSubchannel( + this.target, + subchannelAddress, + finalSubchannelArgs, + this.credentials + ); + subchannel.throttleKeepalive(this.keepaliveTime); + if (this.channelzEnabled) { + this.channelzInfoTracker.trace.addTrace( + 'CT_INFO', + 'Created subchannel or used existing subchannel', + subchannel.getChannelzRef() + ); + } + const wrappedSubchannel = new ChannelSubchannelWrapper( + subchannel, + this + ); + return wrappedSubchannel; + }, + updateState: (connectivityState: ConnectivityState, picker: Picker) => { + this.currentPicker = picker; + const queueCopy = this.pickQueue.slice(); + this.pickQueue = []; + if (queueCopy.length > 0) { + this.callRefTimerUnref(); + } + for (const call of queueCopy) { + call.doPick(); + } + this.updateState(connectivityState); + }, + requestReresolution: () => { + // This should never be called. + throw new Error( + 'Resolving load balancer should never call requestReresolution' + ); + }, + addChannelzChild: (child: ChannelRef | SubchannelRef) => { + if (this.channelzEnabled) { + this.channelzInfoTracker.childrenTracker.refChild(child); + } + }, + removeChannelzChild: (child: ChannelRef | SubchannelRef) => { + if (this.channelzEnabled) { + this.channelzInfoTracker.childrenTracker.unrefChild(child); + } + }, + }; + this.resolvingLoadBalancer = new ResolvingLoadBalancer( + this.target, + channelControlHelper, + this.options, + (serviceConfig, configSelector) => { + if (serviceConfig.retryThrottling) { + RETRY_THROTTLER_MAP.set( + this.getTarget(), + new RetryThrottler( + serviceConfig.retryThrottling.maxTokens, + serviceConfig.retryThrottling.tokenRatio, + RETRY_THROTTLER_MAP.get(this.getTarget()) + ) + ); + } else { + RETRY_THROTTLER_MAP.delete(this.getTarget()); + } + if (this.channelzEnabled) { + this.channelzInfoTracker.trace.addTrace( + 'CT_INFO', + 'Address resolution succeeded' + ); + } + this.configSelector?.unref(); + this.configSelector = configSelector; + this.currentResolutionError = null; + /* We process the queue asynchronously to ensure that the corresponding + * load balancer update has completed. */ + process.nextTick(() => { + const localQueue = this.configSelectionQueue; + this.configSelectionQueue = []; + if (localQueue.length > 0) { + this.callRefTimerUnref(); + } + for (const call of localQueue) { + call.getConfig(); + } + }); + }, + status => { + if (this.channelzEnabled) { + this.channelzInfoTracker.trace.addTrace( + 'CT_WARNING', + 'Address resolution failed with code ' + + status.code + + ' and details "' + + status.details + + '"' + ); + } + if (this.configSelectionQueue.length > 0) { + this.trace( + 'Name resolution failed with calls queued for config selection' + ); + } + if (this.configSelector === null) { + this.currentResolutionError = { + ...restrictControlPlaneStatusCode(status.code, status.details), + metadata: status.metadata, + }; + } + const localQueue = this.configSelectionQueue; + this.configSelectionQueue = []; + if (localQueue.length > 0) { + this.callRefTimerUnref(); + } + for (const call of localQueue) { + call.reportResolverError(status); + } + } + ); + this.filterStackFactory = new FilterStackFactory([ + new CompressionFilterFactory(this, this.options), + ]); + this.trace( + 'Channel constructed with options ' + + JSON.stringify(options, undefined, 2) + ); + const error = new Error(); + if (isTracerEnabled('channel_stacktrace')){ + trace( + LogVerbosity.DEBUG, + 'channel_stacktrace', + '(' + + this.channelzRef.id + + ') ' + + 'Channel constructed \n' + + error.stack?.substring(error.stack.indexOf('\n') + 1) + ); + } + this.lastActivityTimestamp = new Date(); + } + + private trace(text: string, verbosityOverride?: LogVerbosity) { + trace( + verbosityOverride ?? LogVerbosity.DEBUG, + 'channel', + '(' + this.channelzRef.id + ') ' + uriToString(this.target) + ' ' + text + ); + } + + private callRefTimerRef() { + if (!this.callRefTimer) { + this.callRefTimer = setInterval(() => {}, MAX_TIMEOUT_TIME) + } + // If the hasRef function does not exist, always run the code + if (!this.callRefTimer.hasRef?.()) { + this.trace( + 'callRefTimer.ref | configSelectionQueue.length=' + + this.configSelectionQueue.length + + ' pickQueue.length=' + + this.pickQueue.length + ); + this.callRefTimer.ref?.(); + } + } + + private callRefTimerUnref() { + // If the timer or the hasRef function does not exist, always run the code + if (!this.callRefTimer?.hasRef || this.callRefTimer.hasRef()) { + this.trace( + 'callRefTimer.unref | configSelectionQueue.length=' + + this.configSelectionQueue.length + + ' pickQueue.length=' + + this.pickQueue.length + ); + this.callRefTimer?.unref?.(); + } + } + + private removeConnectivityStateWatcher( + watcherObject: ConnectivityStateWatcher + ) { + const watcherIndex = this.connectivityStateWatchers.findIndex( + value => value === watcherObject + ); + if (watcherIndex >= 0) { + this.connectivityStateWatchers.splice(watcherIndex, 1); + } + } + + private updateState(newState: ConnectivityState): void { + trace( + LogVerbosity.DEBUG, + 'connectivity_state', + '(' + + this.channelzRef.id + + ') ' + + uriToString(this.target) + + ' ' + + ConnectivityState[this.connectivityState] + + ' -> ' + + ConnectivityState[newState] + ); + if (this.channelzEnabled) { + this.channelzInfoTracker.trace.addTrace( + 'CT_INFO', + 'Connectivity state change to ' + ConnectivityState[newState] + ); + } + this.connectivityState = newState; + this.channelzInfoTracker.state = newState; + const watchersCopy = this.connectivityStateWatchers.slice(); + for (const watcherObject of watchersCopy) { + if (newState !== watcherObject.currentState) { + if (watcherObject.timer) { + clearTimeout(watcherObject.timer); + } + this.removeConnectivityStateWatcher(watcherObject); + watcherObject.callback(); + } + } + if (newState !== ConnectivityState.TRANSIENT_FAILURE) { + this.currentResolutionError = null; + } + } + + throttleKeepalive(newKeepaliveTime: number) { + if (newKeepaliveTime > this.keepaliveTime) { + this.keepaliveTime = newKeepaliveTime; + for (const wrappedSubchannel of this.wrappedSubchannels) { + wrappedSubchannel.throttleKeepalive(newKeepaliveTime); + } + } + } + + addWrappedSubchannel(wrappedSubchannel: ChannelSubchannelWrapper) { + this.wrappedSubchannels.add(wrappedSubchannel); + } + + removeWrappedSubchannel(wrappedSubchannel: ChannelSubchannelWrapper) { + this.wrappedSubchannels.delete(wrappedSubchannel); + } + + doPick(metadata: Metadata, extraPickInfo: { [key: string]: string }) { + return this.currentPicker.pick({ + metadata: metadata, + extraPickInfo: extraPickInfo, + }); + } + + queueCallForPick(call: LoadBalancingCall) { + this.pickQueue.push(call); + this.callRefTimerRef(); + } + + getConfig(method: string, metadata: Metadata): GetConfigResult { + if (this.connectivityState !== ConnectivityState.SHUTDOWN) { + this.resolvingLoadBalancer.exitIdle(); + } + if (this.configSelector) { + return { + type: 'SUCCESS', + config: this.configSelector.invoke(method, metadata, this.randomChannelId), + }; + } else { + if (this.currentResolutionError) { + return { + type: 'ERROR', + error: this.currentResolutionError, + }; + } else { + return { + type: 'NONE', + }; + } + } + } + + queueCallForConfig(call: ResolvingCall) { + this.configSelectionQueue.push(call); + this.callRefTimerRef(); + } + + private enterIdle() { + this.resolvingLoadBalancer.destroy(); + this.updateState(ConnectivityState.IDLE); + this.currentPicker = new QueuePicker(this.resolvingLoadBalancer); + if (this.idleTimer) { + clearTimeout(this.idleTimer); + this.idleTimer = null; + } + if (this.callRefTimer) { + clearInterval(this.callRefTimer); + this.callRefTimer = null; + } + } + + private startIdleTimeout(timeoutMs: number) { + this.idleTimer = setTimeout(() => { + if (this.callCount > 0) { + /* If there is currently a call, the channel will not go idle for a + * period of at least idleTimeoutMs, so check again after that time. + */ + this.startIdleTimeout(this.idleTimeoutMs); + return; + } + const now = new Date(); + const timeSinceLastActivity = + now.valueOf() - this.lastActivityTimestamp.valueOf(); + if (timeSinceLastActivity >= this.idleTimeoutMs) { + this.trace( + 'Idle timer triggered after ' + + this.idleTimeoutMs + + 'ms of inactivity' + ); + this.enterIdle(); + } else { + /* Whenever the timer fires with the latest activity being too recent, + * set the timer again for the time when the time since the last + * activity is equal to the timeout. This should result in the timer + * firing no more than once every idleTimeoutMs/2 on average. */ + this.startIdleTimeout(this.idleTimeoutMs - timeSinceLastActivity); + } + }, timeoutMs); + this.idleTimer.unref?.(); + } + + private maybeStartIdleTimer() { + if ( + this.connectivityState !== ConnectivityState.SHUTDOWN && + !this.idleTimer + ) { + this.startIdleTimeout(this.idleTimeoutMs); + } + } + + private onCallStart() { + if (this.channelzEnabled) { + this.channelzInfoTracker.callTracker.addCallStarted(); + } + this.callCount += 1; + } + + private onCallEnd(status: StatusObject) { + if (this.channelzEnabled) { + if (status.code === Status.OK) { + this.channelzInfoTracker.callTracker.addCallSucceeded(); + } else { + this.channelzInfoTracker.callTracker.addCallFailed(); + } + } + this.callCount -= 1; + this.lastActivityTimestamp = new Date(); + this.maybeStartIdleTimer(); + } + + createLoadBalancingCall( + callConfig: CallConfig, + method: string, + host: string, + credentials: CallCredentials, + deadline: Deadline + ): LoadBalancingCall { + const callNumber = getNextCallNumber(); + this.trace( + 'createLoadBalancingCall [' + callNumber + '] method="' + method + '"' + ); + return new LoadBalancingCall( + this, + callConfig, + method, + host, + credentials, + deadline, + callNumber + ); + } + + createRetryingCall( + callConfig: CallConfig, + method: string, + host: string, + credentials: CallCredentials, + deadline: Deadline + ): RetryingCall { + const callNumber = getNextCallNumber(); + this.trace( + 'createRetryingCall [' + callNumber + '] method="' + method + '"' + ); + return new RetryingCall( + this, + callConfig, + method, + host, + credentials, + deadline, + callNumber, + this.retryBufferTracker, + RETRY_THROTTLER_MAP.get(this.getTarget()) + ); + } + + createResolvingCall( + method: string, + deadline: Deadline, + host: string | null | undefined, + parentCall: ServerSurfaceCall | null, + propagateFlags: number | null | undefined + ): ResolvingCall { + const callNumber = getNextCallNumber(); + this.trace( + 'createResolvingCall [' + + callNumber + + '] method="' + + method + + '", deadline=' + + deadlineToString(deadline) + ); + const finalOptions: CallStreamOptions = { + deadline: deadline, + flags: propagateFlags ?? Propagate.DEFAULTS, + host: host ?? this.defaultAuthority, + parentCall: parentCall, + }; + + const call = new ResolvingCall( + this, + method, + finalOptions, + this.filterStackFactory.clone(), + callNumber + ); + + this.onCallStart(); + call.addStatusWatcher(status => { + this.onCallEnd(status); + }); + return call; + } + + close() { + this.resolvingLoadBalancer.destroy(); + this.updateState(ConnectivityState.SHUTDOWN); + this.currentPicker = new ShutdownPicker(); + for (const call of this.configSelectionQueue) { + call.cancelWithStatus(Status.UNAVAILABLE, 'Channel closed before call started'); + } + this.configSelectionQueue = []; + for (const call of this.pickQueue) { + call.cancelWithStatus(Status.UNAVAILABLE, 'Channel closed before call started'); + } + this.pickQueue = []; + if (this.callRefTimer) { + clearInterval(this.callRefTimer); + } + if (this.idleTimer) { + clearTimeout(this.idleTimer); + } + if (this.channelzEnabled) { + unregisterChannelzRef(this.channelzRef); + } + + this.subchannelPool.unrefUnusedSubchannels(); + this.configSelector?.unref(); + this.configSelector = null; + } + + getTarget() { + return uriToString(this.target); + } + + getConnectivityState(tryToConnect: boolean) { + const connectivityState = this.connectivityState; + if (tryToConnect) { + this.resolvingLoadBalancer.exitIdle(); + this.lastActivityTimestamp = new Date(); + this.maybeStartIdleTimer(); + } + return connectivityState; + } + + watchConnectivityState( + currentState: ConnectivityState, + deadline: Date | number, + callback: (error?: Error) => void + ): void { + if (this.connectivityState === ConnectivityState.SHUTDOWN) { + throw new Error('Channel has been shut down'); + } + let timer = null; + if (deadline !== Infinity) { + const deadlineDate: Date = + deadline instanceof Date ? deadline : new Date(deadline); + const now = new Date(); + if (deadline === -Infinity || deadlineDate <= now) { + process.nextTick( + callback, + new Error('Deadline passed without connectivity state change') + ); + return; + } + timer = setTimeout(() => { + this.removeConnectivityStateWatcher(watcherObject); + callback( + new Error('Deadline passed without connectivity state change') + ); + }, deadlineDate.getTime() - now.getTime()); + } + const watcherObject = { + currentState, + callback, + timer, + }; + this.connectivityStateWatchers.push(watcherObject); + } + + /** + * Get the channelz reference object for this channel. The returned value is + * garbage if channelz is disabled for this channel. + * @returns + */ + getChannelzRef() { + return this.channelzRef; + } + + createCall( + method: string, + deadline: Deadline, + host: string | null | undefined, + parentCall: ServerSurfaceCall | null, + propagateFlags: number | null | undefined + ): Call { + if (typeof method !== 'string') { + throw new TypeError('Channel#createCall: method must be a string'); + } + if (!(typeof deadline === 'number' || deadline instanceof Date)) { + throw new TypeError( + 'Channel#createCall: deadline must be a number or Date' + ); + } + if (this.connectivityState === ConnectivityState.SHUTDOWN) { + throw new Error('Channel has been shut down'); + } + return this.createResolvingCall( + method, + deadline, + host, + parentCall, + propagateFlags + ); + } + + getOptions() { + return this.options; + } +} diff --git a/node_modules/@grpc/grpc-js/src/load-balancer-child-handler.ts b/node_modules/@grpc/grpc-js/src/load-balancer-child-handler.ts new file mode 100644 index 0000000..0257808 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/load-balancer-child-handler.ts @@ -0,0 +1,173 @@ +/* + * Copyright 2020 gRPC authors. + * + * 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. + * + */ + +import { + LoadBalancer, + ChannelControlHelper, + TypedLoadBalancingConfig, + createLoadBalancer, +} from './load-balancer'; +import { Endpoint, SubchannelAddress } from './subchannel-address'; +import { ChannelOptions } from './channel-options'; +import { ConnectivityState } from './connectivity-state'; +import { Picker } from './picker'; +import type { ChannelRef, SubchannelRef } from './channelz'; +import { SubchannelInterface } from './subchannel-interface'; +import { StatusOr } from './call-interface'; + +const TYPE_NAME = 'child_load_balancer_helper'; + +export class ChildLoadBalancerHandler { + private currentChild: LoadBalancer | null = null; + private pendingChild: LoadBalancer | null = null; + private latestConfig: TypedLoadBalancingConfig | null = null; + + private ChildPolicyHelper = class { + private child: LoadBalancer | null = null; + constructor(private parent: ChildLoadBalancerHandler) {} + createSubchannel( + subchannelAddress: SubchannelAddress, + subchannelArgs: ChannelOptions + ): SubchannelInterface { + return this.parent.channelControlHelper.createSubchannel( + subchannelAddress, + subchannelArgs + ); + } + updateState(connectivityState: ConnectivityState, picker: Picker, errorMessage: string | null): void { + if (this.calledByPendingChild()) { + if (connectivityState === ConnectivityState.CONNECTING) { + return; + } + this.parent.currentChild?.destroy(); + this.parent.currentChild = this.parent.pendingChild; + this.parent.pendingChild = null; + } else if (!this.calledByCurrentChild()) { + return; + } + this.parent.channelControlHelper.updateState(connectivityState, picker, errorMessage); + } + requestReresolution(): void { + const latestChild = this.parent.pendingChild ?? this.parent.currentChild; + if (this.child === latestChild) { + this.parent.channelControlHelper.requestReresolution(); + } + } + setChild(newChild: LoadBalancer) { + this.child = newChild; + } + addChannelzChild(child: ChannelRef | SubchannelRef) { + this.parent.channelControlHelper.addChannelzChild(child); + } + removeChannelzChild(child: ChannelRef | SubchannelRef) { + this.parent.channelControlHelper.removeChannelzChild(child); + } + + private calledByPendingChild(): boolean { + return this.child === this.parent.pendingChild; + } + private calledByCurrentChild(): boolean { + return this.child === this.parent.currentChild; + } + }; + + constructor( + private readonly channelControlHelper: ChannelControlHelper + ) {} + + protected configUpdateRequiresNewPolicyInstance( + oldConfig: TypedLoadBalancingConfig, + newConfig: TypedLoadBalancingConfig + ): boolean { + return oldConfig.getLoadBalancerName() !== newConfig.getLoadBalancerName(); + } + + /** + * Prerequisites: lbConfig !== null and lbConfig.name is registered + * @param endpointList + * @param lbConfig + * @param attributes + */ + updateAddressList( + endpointList: StatusOr, + lbConfig: TypedLoadBalancingConfig, + options: ChannelOptions, + resolutionNote: string + ): boolean { + let childToUpdate: LoadBalancer; + if ( + this.currentChild === null || + this.latestConfig === null || + this.configUpdateRequiresNewPolicyInstance(this.latestConfig, lbConfig) + ) { + const newHelper = new this.ChildPolicyHelper(this); + const newChild = createLoadBalancer(lbConfig, newHelper)!; + newHelper.setChild(newChild); + if (this.currentChild === null) { + this.currentChild = newChild; + childToUpdate = this.currentChild; + } else { + if (this.pendingChild) { + this.pendingChild.destroy(); + } + this.pendingChild = newChild; + childToUpdate = this.pendingChild; + } + } else { + if (this.pendingChild === null) { + childToUpdate = this.currentChild; + } else { + childToUpdate = this.pendingChild; + } + } + this.latestConfig = lbConfig; + return childToUpdate.updateAddressList(endpointList, lbConfig, options, resolutionNote); + } + exitIdle(): void { + if (this.currentChild) { + this.currentChild.exitIdle(); + if (this.pendingChild) { + this.pendingChild.exitIdle(); + } + } + } + resetBackoff(): void { + if (this.currentChild) { + this.currentChild.resetBackoff(); + if (this.pendingChild) { + this.pendingChild.resetBackoff(); + } + } + } + destroy(): void { + /* Note: state updates are only propagated from the child balancer if that + * object is equal to this.currentChild or this.pendingChild. Since this + * function sets both of those to null, no further state updates will + * occur after this function returns. */ + if (this.currentChild) { + this.currentChild.destroy(); + this.currentChild = null; + } + if (this.pendingChild) { + this.pendingChild.destroy(); + this.pendingChild = null; + } + } + getTypeName(): string { + return TYPE_NAME; + } +} diff --git a/node_modules/@grpc/grpc-js/src/load-balancer-outlier-detection.ts b/node_modules/@grpc/grpc-js/src/load-balancer-outlier-detection.ts new file mode 100644 index 0000000..4fa4b42 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/load-balancer-outlier-detection.ts @@ -0,0 +1,840 @@ +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ + +import { ChannelOptions } from './channel-options'; +import { ConnectivityState } from './connectivity-state'; +import { LogVerbosity, Status } from './constants'; +import { Duration, durationToMs, isDuration, msToDuration } from './duration'; +import { + ChannelControlHelper, + createChildChannelControlHelper, + registerLoadBalancerType, +} from './experimental'; +import { + selectLbConfigFromList, + LoadBalancer, + TypedLoadBalancingConfig, +} from './load-balancer'; +import { ChildLoadBalancerHandler } from './load-balancer-child-handler'; +import { PickArgs, Picker, PickResult, PickResultType } from './picker'; +import { + Endpoint, + EndpointMap, + SubchannelAddress, + endpointToString, +} from './subchannel-address'; +import { + BaseSubchannelWrapper, + SubchannelInterface, +} from './subchannel-interface'; +import * as logging from './logging'; +import { LoadBalancingConfig } from './service-config'; +import { StatusOr } from './call-interface'; + +const TRACER_NAME = 'outlier_detection'; + +function trace(text: string): void { + logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text); +} + +const TYPE_NAME = 'outlier_detection'; + +const OUTLIER_DETECTION_ENABLED = + (process.env.GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION ?? 'true') === 'true'; + +export interface SuccessRateEjectionConfig { + readonly stdev_factor: number; + readonly enforcement_percentage: number; + readonly minimum_hosts: number; + readonly request_volume: number; +} + +export interface FailurePercentageEjectionConfig { + readonly threshold: number; + readonly enforcement_percentage: number; + readonly minimum_hosts: number; + readonly request_volume: number; +} + +export interface OutlierDetectionRawConfig { + interval?: Duration; + base_ejection_time?: Duration; + max_ejection_time?: Duration; + max_ejection_percent?: number; + success_rate_ejection?: Partial; + failure_percentage_ejection?: Partial; + child_policy: LoadBalancingConfig[]; +} + +const defaultSuccessRateEjectionConfig: SuccessRateEjectionConfig = { + stdev_factor: 1900, + enforcement_percentage: 100, + minimum_hosts: 5, + request_volume: 100, +}; + +const defaultFailurePercentageEjectionConfig: FailurePercentageEjectionConfig = + { + threshold: 85, + enforcement_percentage: 100, + minimum_hosts: 5, + request_volume: 50, + }; + +type TypeofValues = + | 'object' + | 'boolean' + | 'function' + | 'number' + | 'string' + | 'undefined'; + +function validateFieldType( + obj: any, + fieldName: string, + expectedType: TypeofValues, + objectName?: string +) { + if ( + fieldName in obj && + obj[fieldName] !== undefined && + typeof obj[fieldName] !== expectedType + ) { + const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; + throw new Error( + `outlier detection config ${fullFieldName} parse error: expected ${expectedType}, got ${typeof obj[ + fieldName + ]}` + ); + } +} + +function validatePositiveDuration( + obj: any, + fieldName: string, + objectName?: string +) { + const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; + if (fieldName in obj && obj[fieldName] !== undefined) { + if (!isDuration(obj[fieldName])) { + throw new Error( + `outlier detection config ${fullFieldName} parse error: expected Duration, got ${typeof obj[ + fieldName + ]}` + ); + } + if ( + !( + obj[fieldName].seconds >= 0 && + obj[fieldName].seconds <= 315_576_000_000 && + obj[fieldName].nanos >= 0 && + obj[fieldName].nanos <= 999_999_999 + ) + ) { + throw new Error( + `outlier detection config ${fullFieldName} parse error: values out of range for non-negative Duaration` + ); + } + } +} + +function validatePercentage(obj: any, fieldName: string, objectName?: string) { + const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; + validateFieldType(obj, fieldName, 'number', objectName); + if ( + fieldName in obj && + obj[fieldName] !== undefined && + !(obj[fieldName] >= 0 && obj[fieldName] <= 100) + ) { + throw new Error( + `outlier detection config ${fullFieldName} parse error: value out of range for percentage (0-100)` + ); + } +} + +export class OutlierDetectionLoadBalancingConfig + implements TypedLoadBalancingConfig +{ + private readonly intervalMs: number; + private readonly baseEjectionTimeMs: number; + private readonly maxEjectionTimeMs: number; + private readonly maxEjectionPercent: number; + private readonly successRateEjection: SuccessRateEjectionConfig | null; + private readonly failurePercentageEjection: FailurePercentageEjectionConfig | null; + + constructor( + intervalMs: number | null, + baseEjectionTimeMs: number | null, + maxEjectionTimeMs: number | null, + maxEjectionPercent: number | null, + successRateEjection: Partial | null, + failurePercentageEjection: Partial | null, + private readonly childPolicy: TypedLoadBalancingConfig + ) { + if (childPolicy.getLoadBalancerName() === 'pick_first') { + throw new Error( + 'outlier_detection LB policy cannot have a pick_first child policy' + ); + } + this.intervalMs = intervalMs ?? 10_000; + this.baseEjectionTimeMs = baseEjectionTimeMs ?? 30_000; + this.maxEjectionTimeMs = maxEjectionTimeMs ?? 300_000; + this.maxEjectionPercent = maxEjectionPercent ?? 10; + this.successRateEjection = successRateEjection + ? { ...defaultSuccessRateEjectionConfig, ...successRateEjection } + : null; + this.failurePercentageEjection = failurePercentageEjection + ? { + ...defaultFailurePercentageEjectionConfig, + ...failurePercentageEjection, + } + : null; + } + getLoadBalancerName(): string { + return TYPE_NAME; + } + toJsonObject(): object { + return { + outlier_detection: { + interval: msToDuration(this.intervalMs), + base_ejection_time: msToDuration(this.baseEjectionTimeMs), + max_ejection_time: msToDuration(this.maxEjectionTimeMs), + max_ejection_percent: this.maxEjectionPercent, + success_rate_ejection: this.successRateEjection ?? undefined, + failure_percentage_ejection: + this.failurePercentageEjection ?? undefined, + child_policy: [this.childPolicy.toJsonObject()], + }, + }; + } + + getIntervalMs(): number { + return this.intervalMs; + } + getBaseEjectionTimeMs(): number { + return this.baseEjectionTimeMs; + } + getMaxEjectionTimeMs(): number { + return this.maxEjectionTimeMs; + } + getMaxEjectionPercent(): number { + return this.maxEjectionPercent; + } + getSuccessRateEjectionConfig(): SuccessRateEjectionConfig | null { + return this.successRateEjection; + } + getFailurePercentageEjectionConfig(): FailurePercentageEjectionConfig | null { + return this.failurePercentageEjection; + } + getChildPolicy(): TypedLoadBalancingConfig { + return this.childPolicy; + } + + static createFromJson(obj: any): OutlierDetectionLoadBalancingConfig { + validatePositiveDuration(obj, 'interval'); + validatePositiveDuration(obj, 'base_ejection_time'); + validatePositiveDuration(obj, 'max_ejection_time'); + validatePercentage(obj, 'max_ejection_percent'); + if ( + 'success_rate_ejection' in obj && + obj.success_rate_ejection !== undefined + ) { + if (typeof obj.success_rate_ejection !== 'object') { + throw new Error( + 'outlier detection config success_rate_ejection must be an object' + ); + } + validateFieldType( + obj.success_rate_ejection, + 'stdev_factor', + 'number', + 'success_rate_ejection' + ); + validatePercentage( + obj.success_rate_ejection, + 'enforcement_percentage', + 'success_rate_ejection' + ); + validateFieldType( + obj.success_rate_ejection, + 'minimum_hosts', + 'number', + 'success_rate_ejection' + ); + validateFieldType( + obj.success_rate_ejection, + 'request_volume', + 'number', + 'success_rate_ejection' + ); + } + if ( + 'failure_percentage_ejection' in obj && + obj.failure_percentage_ejection !== undefined + ) { + if (typeof obj.failure_percentage_ejection !== 'object') { + throw new Error( + 'outlier detection config failure_percentage_ejection must be an object' + ); + } + validatePercentage( + obj.failure_percentage_ejection, + 'threshold', + 'failure_percentage_ejection' + ); + validatePercentage( + obj.failure_percentage_ejection, + 'enforcement_percentage', + 'failure_percentage_ejection' + ); + validateFieldType( + obj.failure_percentage_ejection, + 'minimum_hosts', + 'number', + 'failure_percentage_ejection' + ); + validateFieldType( + obj.failure_percentage_ejection, + 'request_volume', + 'number', + 'failure_percentage_ejection' + ); + } + + if (!('child_policy' in obj) || !Array.isArray(obj.child_policy)) { + throw new Error('outlier detection config child_policy must be an array'); + } + const childPolicy = selectLbConfigFromList(obj.child_policy); + if (!childPolicy) { + throw new Error( + 'outlier detection config child_policy: no valid recognized policy found' + ); + } + + return new OutlierDetectionLoadBalancingConfig( + obj.interval ? durationToMs(obj.interval) : null, + obj.base_ejection_time ? durationToMs(obj.base_ejection_time) : null, + obj.max_ejection_time ? durationToMs(obj.max_ejection_time) : null, + obj.max_ejection_percent ?? null, + obj.success_rate_ejection, + obj.failure_percentage_ejection, + childPolicy + ); + } +} + +class OutlierDetectionSubchannelWrapper + extends BaseSubchannelWrapper + implements SubchannelInterface +{ + private refCount = 0; + constructor( + childSubchannel: SubchannelInterface, + private mapEntry?: MapEntry + ) { + super(childSubchannel); + } + + ref() { + this.child.ref(); + this.refCount += 1; + } + + unref() { + this.child.unref(); + this.refCount -= 1; + if (this.refCount <= 0) { + if (this.mapEntry) { + const index = this.mapEntry.subchannelWrappers.indexOf(this); + if (index >= 0) { + this.mapEntry.subchannelWrappers.splice(index, 1); + } + } + } + } + + eject() { + this.setHealthy(false); + } + + uneject() { + this.setHealthy(true); + } + + getMapEntry(): MapEntry | undefined { + return this.mapEntry; + } + + getWrappedSubchannel(): SubchannelInterface { + return this.child; + } +} + +interface CallCountBucket { + success: number; + failure: number; +} + +function createEmptyBucket(): CallCountBucket { + return { + success: 0, + failure: 0, + }; +} + +class CallCounter { + private activeBucket: CallCountBucket = createEmptyBucket(); + private inactiveBucket: CallCountBucket = createEmptyBucket(); + addSuccess() { + this.activeBucket.success += 1; + } + addFailure() { + this.activeBucket.failure += 1; + } + switchBuckets() { + this.inactiveBucket = this.activeBucket; + this.activeBucket = createEmptyBucket(); + } + getLastSuccesses() { + return this.inactiveBucket.success; + } + getLastFailures() { + return this.inactiveBucket.failure; + } +} + +class OutlierDetectionPicker implements Picker { + constructor(private wrappedPicker: Picker, private countCalls: boolean) {} + pick(pickArgs: PickArgs): PickResult { + const wrappedPick = this.wrappedPicker.pick(pickArgs); + if (wrappedPick.pickResultType === PickResultType.COMPLETE) { + const subchannelWrapper = + wrappedPick.subchannel as OutlierDetectionSubchannelWrapper; + const mapEntry = subchannelWrapper.getMapEntry(); + if (mapEntry) { + let onCallEnded = wrappedPick.onCallEnded; + if (this.countCalls) { + onCallEnded = (statusCode, details, metadata) => { + if (statusCode === Status.OK) { + mapEntry.counter.addSuccess(); + } else { + mapEntry.counter.addFailure(); + } + wrappedPick.onCallEnded?.(statusCode, details, metadata); + }; + } + return { + ...wrappedPick, + subchannel: subchannelWrapper.getWrappedSubchannel(), + onCallEnded: onCallEnded, + }; + } else { + return { + ...wrappedPick, + subchannel: subchannelWrapper.getWrappedSubchannel(), + }; + } + } else { + return wrappedPick; + } + } +} + +interface MapEntry { + counter: CallCounter; + currentEjectionTimestamp: Date | null; + ejectionTimeMultiplier: number; + subchannelWrappers: OutlierDetectionSubchannelWrapper[]; +} + +export class OutlierDetectionLoadBalancer implements LoadBalancer { + private childBalancer: ChildLoadBalancerHandler; + private entryMap = new EndpointMap(); + private latestConfig: OutlierDetectionLoadBalancingConfig | null = null; + private ejectionTimer: NodeJS.Timeout; + private timerStartTime: Date | null = null; + + constructor( + channelControlHelper: ChannelControlHelper + ) { + this.childBalancer = new ChildLoadBalancerHandler( + createChildChannelControlHelper(channelControlHelper, { + createSubchannel: ( + subchannelAddress: SubchannelAddress, + subchannelArgs: ChannelOptions + ) => { + const originalSubchannel = channelControlHelper.createSubchannel( + subchannelAddress, + subchannelArgs + ); + const mapEntry = + this.entryMap.getForSubchannelAddress(subchannelAddress); + const subchannelWrapper = new OutlierDetectionSubchannelWrapper( + originalSubchannel, + mapEntry + ); + if (mapEntry?.currentEjectionTimestamp !== null) { + // If the address is ejected, propagate that to the new subchannel wrapper + subchannelWrapper.eject(); + } + mapEntry?.subchannelWrappers.push(subchannelWrapper); + return subchannelWrapper; + }, + updateState: (connectivityState: ConnectivityState, picker: Picker, errorMessage: string) => { + if (connectivityState === ConnectivityState.READY) { + channelControlHelper.updateState( + connectivityState, + new OutlierDetectionPicker(picker, this.isCountingEnabled()), + errorMessage + ); + } else { + channelControlHelper.updateState(connectivityState, picker, errorMessage); + } + }, + }) + ); + this.ejectionTimer = setInterval(() => {}, 0); + clearInterval(this.ejectionTimer); + } + + private isCountingEnabled(): boolean { + return ( + this.latestConfig !== null && + (this.latestConfig.getSuccessRateEjectionConfig() !== null || + this.latestConfig.getFailurePercentageEjectionConfig() !== null) + ); + } + + private getCurrentEjectionPercent() { + let ejectionCount = 0; + for (const mapEntry of this.entryMap.values()) { + if (mapEntry.currentEjectionTimestamp !== null) { + ejectionCount += 1; + } + } + return (ejectionCount * 100) / this.entryMap.size; + } + + private runSuccessRateCheck(ejectionTimestamp: Date) { + if (!this.latestConfig) { + return; + } + const successRateConfig = this.latestConfig.getSuccessRateEjectionConfig(); + if (!successRateConfig) { + return; + } + trace('Running success rate check'); + // Step 1 + const targetRequestVolume = successRateConfig.request_volume; + let addresesWithTargetVolume = 0; + const successRates: number[] = []; + for (const [endpoint, mapEntry] of this.entryMap.entries()) { + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + trace( + 'Stats for ' + + endpointToString(endpoint) + + ': successes=' + + successes + + ' failures=' + + failures + + ' targetRequestVolume=' + + targetRequestVolume + ); + if (successes + failures >= targetRequestVolume) { + addresesWithTargetVolume += 1; + successRates.push(successes / (successes + failures)); + } + } + trace( + 'Found ' + + addresesWithTargetVolume + + ' success rate candidates; currentEjectionPercent=' + + this.getCurrentEjectionPercent() + + ' successRates=[' + + successRates + + ']' + ); + if (addresesWithTargetVolume < successRateConfig.minimum_hosts) { + return; + } + + // Step 2 + const successRateMean = + successRates.reduce((a, b) => a + b) / successRates.length; + let successRateDeviationSum = 0; + for (const rate of successRates) { + const deviation = rate - successRateMean; + successRateDeviationSum += deviation * deviation; + } + const successRateVariance = successRateDeviationSum / successRates.length; + const successRateStdev = Math.sqrt(successRateVariance); + const ejectionThreshold = + successRateMean - + successRateStdev * (successRateConfig.stdev_factor / 1000); + trace( + 'stdev=' + successRateStdev + ' ejectionThreshold=' + ejectionThreshold + ); + + // Step 3 + for (const [address, mapEntry] of this.entryMap.entries()) { + // Step 3.i + if ( + this.getCurrentEjectionPercent() >= + this.latestConfig.getMaxEjectionPercent() + ) { + break; + } + // Step 3.ii + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + if (successes + failures < targetRequestVolume) { + continue; + } + // Step 3.iii + const successRate = successes / (successes + failures); + trace('Checking candidate ' + address + ' successRate=' + successRate); + if (successRate < ejectionThreshold) { + const randomNumber = Math.random() * 100; + trace( + 'Candidate ' + + address + + ' randomNumber=' + + randomNumber + + ' enforcement_percentage=' + + successRateConfig.enforcement_percentage + ); + if (randomNumber < successRateConfig.enforcement_percentage) { + trace('Ejecting candidate ' + address); + this.eject(mapEntry, ejectionTimestamp); + } + } + } + } + + private runFailurePercentageCheck(ejectionTimestamp: Date) { + if (!this.latestConfig) { + return; + } + const failurePercentageConfig = + this.latestConfig.getFailurePercentageEjectionConfig(); + if (!failurePercentageConfig) { + return; + } + trace( + 'Running failure percentage check. threshold=' + + failurePercentageConfig.threshold + + ' request volume threshold=' + + failurePercentageConfig.request_volume + ); + // Step 1 + let addressesWithTargetVolume = 0; + for (const mapEntry of this.entryMap.values()) { + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + if (successes + failures >= failurePercentageConfig.request_volume) { + addressesWithTargetVolume += 1; + } + } + if (addressesWithTargetVolume < failurePercentageConfig.minimum_hosts) { + return; + } + + // Step 2 + for (const [address, mapEntry] of this.entryMap.entries()) { + // Step 2.i + if ( + this.getCurrentEjectionPercent() >= + this.latestConfig.getMaxEjectionPercent() + ) { + break; + } + // Step 2.ii + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + trace('Candidate successes=' + successes + ' failures=' + failures); + if (successes + failures < failurePercentageConfig.request_volume) { + continue; + } + // Step 2.iii + const failurePercentage = (failures * 100) / (failures + successes); + if (failurePercentage > failurePercentageConfig.threshold) { + const randomNumber = Math.random() * 100; + trace( + 'Candidate ' + + address + + ' randomNumber=' + + randomNumber + + ' enforcement_percentage=' + + failurePercentageConfig.enforcement_percentage + ); + if (randomNumber < failurePercentageConfig.enforcement_percentage) { + trace('Ejecting candidate ' + address); + this.eject(mapEntry, ejectionTimestamp); + } + } + } + } + + private eject(mapEntry: MapEntry, ejectionTimestamp: Date) { + mapEntry.currentEjectionTimestamp = new Date(); + mapEntry.ejectionTimeMultiplier += 1; + for (const subchannelWrapper of mapEntry.subchannelWrappers) { + subchannelWrapper.eject(); + } + } + + private uneject(mapEntry: MapEntry) { + mapEntry.currentEjectionTimestamp = null; + for (const subchannelWrapper of mapEntry.subchannelWrappers) { + subchannelWrapper.uneject(); + } + } + + private switchAllBuckets() { + for (const mapEntry of this.entryMap.values()) { + mapEntry.counter.switchBuckets(); + } + } + + private startTimer(delayMs: number) { + this.ejectionTimer = setTimeout(() => this.runChecks(), delayMs); + this.ejectionTimer.unref?.(); + } + + private runChecks() { + const ejectionTimestamp = new Date(); + trace('Ejection timer running'); + + this.switchAllBuckets(); + + if (!this.latestConfig) { + return; + } + this.timerStartTime = ejectionTimestamp; + this.startTimer(this.latestConfig.getIntervalMs()); + + this.runSuccessRateCheck(ejectionTimestamp); + this.runFailurePercentageCheck(ejectionTimestamp); + + for (const [address, mapEntry] of this.entryMap.entries()) { + if (mapEntry.currentEjectionTimestamp === null) { + if (mapEntry.ejectionTimeMultiplier > 0) { + mapEntry.ejectionTimeMultiplier -= 1; + } + } else { + const baseEjectionTimeMs = this.latestConfig.getBaseEjectionTimeMs(); + const maxEjectionTimeMs = this.latestConfig.getMaxEjectionTimeMs(); + const returnTime = new Date( + mapEntry.currentEjectionTimestamp.getTime() + ); + returnTime.setMilliseconds( + returnTime.getMilliseconds() + + Math.min( + baseEjectionTimeMs * mapEntry.ejectionTimeMultiplier, + Math.max(baseEjectionTimeMs, maxEjectionTimeMs) + ) + ); + if (returnTime < new Date()) { + trace('Unejecting ' + address); + this.uneject(mapEntry); + } + } + } + } + + updateAddressList( + endpointList: StatusOr, + lbConfig: TypedLoadBalancingConfig, + options: ChannelOptions, + resolutionNote: string + ): boolean { + if (!(lbConfig instanceof OutlierDetectionLoadBalancingConfig)) { + return false; + } + trace('Received update with config: ' + JSON.stringify(lbConfig.toJsonObject(), undefined, 2)); + if (endpointList.ok) { + for (const endpoint of endpointList.value) { + if (!this.entryMap.has(endpoint)) { + trace('Adding map entry for ' + endpointToString(endpoint)); + this.entryMap.set(endpoint, { + counter: new CallCounter(), + currentEjectionTimestamp: null, + ejectionTimeMultiplier: 0, + subchannelWrappers: [], + }); + } + } + this.entryMap.deleteMissing(endpointList.value); + } + const childPolicy = lbConfig.getChildPolicy(); + this.childBalancer.updateAddressList(endpointList, childPolicy, options, resolutionNote); + + if ( + lbConfig.getSuccessRateEjectionConfig() || + lbConfig.getFailurePercentageEjectionConfig() + ) { + if (this.timerStartTime) { + trace('Previous timer existed. Replacing timer'); + clearTimeout(this.ejectionTimer); + const remainingDelay = + lbConfig.getIntervalMs() - + (new Date().getTime() - this.timerStartTime.getTime()); + this.startTimer(remainingDelay); + } else { + trace('Starting new timer'); + this.timerStartTime = new Date(); + this.startTimer(lbConfig.getIntervalMs()); + this.switchAllBuckets(); + } + } else { + trace('Counting disabled. Cancelling timer.'); + this.timerStartTime = null; + clearTimeout(this.ejectionTimer); + for (const mapEntry of this.entryMap.values()) { + this.uneject(mapEntry); + mapEntry.ejectionTimeMultiplier = 0; + } + } + + this.latestConfig = lbConfig; + return true; + } + exitIdle(): void { + this.childBalancer.exitIdle(); + } + resetBackoff(): void { + this.childBalancer.resetBackoff(); + } + destroy(): void { + clearTimeout(this.ejectionTimer); + this.childBalancer.destroy(); + } + getTypeName(): string { + return TYPE_NAME; + } +} + +export function setup() { + if (OUTLIER_DETECTION_ENABLED) { + registerLoadBalancerType( + TYPE_NAME, + OutlierDetectionLoadBalancer, + OutlierDetectionLoadBalancingConfig + ); + } +} diff --git a/node_modules/@grpc/grpc-js/src/load-balancer-pick-first.ts b/node_modules/@grpc/grpc-js/src/load-balancer-pick-first.ts new file mode 100644 index 0000000..f0df79d --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/load-balancer-pick-first.ts @@ -0,0 +1,662 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { + LoadBalancer, + ChannelControlHelper, + TypedLoadBalancingConfig, + registerDefaultLoadBalancerType, + registerLoadBalancerType, + createChildChannelControlHelper, +} from './load-balancer'; +import { ConnectivityState } from './connectivity-state'; +import { + QueuePicker, + Picker, + PickArgs, + CompletePickResult, + PickResultType, + UnavailablePicker, +} from './picker'; +import { Endpoint, SubchannelAddress, subchannelAddressToString } from './subchannel-address'; +import * as logging from './logging'; +import { LogVerbosity } from './constants'; +import { + SubchannelInterface, + ConnectivityStateListener, + HealthListener, +} from './subchannel-interface'; +import { isTcpSubchannelAddress } from './subchannel-address'; +import { isIPv6 } from 'net'; +import { ChannelOptions } from './channel-options'; +import { StatusOr, statusOrFromValue } from './call-interface'; + +const TRACER_NAME = 'pick_first'; + +function trace(text: string): void { + logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text); +} + +const TYPE_NAME = 'pick_first'; + +/** + * Delay after starting a connection on a subchannel before starting a + * connection on the next subchannel in the list, for Happy Eyeballs algorithm. + */ +const CONNECTION_DELAY_INTERVAL_MS = 250; + +export class PickFirstLoadBalancingConfig implements TypedLoadBalancingConfig { + constructor(private readonly shuffleAddressList: boolean) {} + + getLoadBalancerName(): string { + return TYPE_NAME; + } + + toJsonObject(): object { + return { + [TYPE_NAME]: { + shuffleAddressList: this.shuffleAddressList, + }, + }; + } + + getShuffleAddressList() { + return this.shuffleAddressList; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static createFromJson(obj: any) { + if ( + 'shuffleAddressList' in obj && + !(typeof obj.shuffleAddressList === 'boolean') + ) { + throw new Error( + 'pick_first config field shuffleAddressList must be a boolean if provided' + ); + } + return new PickFirstLoadBalancingConfig(obj.shuffleAddressList === true); + } +} + +/** + * Picker for a `PickFirstLoadBalancer` in the READY state. Always returns the + * picked subchannel. + */ +class PickFirstPicker implements Picker { + constructor(private subchannel: SubchannelInterface) {} + + pick(pickArgs: PickArgs): CompletePickResult { + return { + pickResultType: PickResultType.COMPLETE, + subchannel: this.subchannel, + status: null, + onCallStarted: null, + onCallEnded: null, + }; + } +} + +interface SubchannelChild { + subchannel: SubchannelInterface; + hasReportedTransientFailure: boolean; +} + +/** + * Return a new array with the elements of the input array in a random order + * @param list The input array + * @returns A shuffled array of the elements of list + */ +export function shuffled(list: T[]): T[] { + const result = list.slice(); + for (let i = result.length - 1; i > 1; i--) { + const j = Math.floor(Math.random() * (i + 1)); + const temp = result[i]; + result[i] = result[j]; + result[j] = temp; + } + return result; +} + +/** + * Interleave addresses in addressList by family in accordance with RFC-8304 section 4 + * @param addressList + * @returns + */ +function interleaveAddressFamilies( + addressList: SubchannelAddress[] +): SubchannelAddress[] { + if (addressList.length === 0) { + return []; + } + const result: SubchannelAddress[] = []; + const ipv6Addresses: SubchannelAddress[] = []; + const ipv4Addresses: SubchannelAddress[] = []; + const ipv6First = + isTcpSubchannelAddress(addressList[0]) && isIPv6(addressList[0].host); + for (const address of addressList) { + if (isTcpSubchannelAddress(address) && isIPv6(address.host)) { + ipv6Addresses.push(address); + } else { + ipv4Addresses.push(address); + } + } + const firstList = ipv6First ? ipv6Addresses : ipv4Addresses; + const secondList = ipv6First ? ipv4Addresses : ipv6Addresses; + for (let i = 0; i < Math.max(firstList.length, secondList.length); i++) { + if (i < firstList.length) { + result.push(firstList[i]); + } + if (i < secondList.length) { + result.push(secondList[i]); + } + } + return result; +} + +const REPORT_HEALTH_STATUS_OPTION_NAME = + 'grpc-node.internal.pick-first.report_health_status'; + +export class PickFirstLoadBalancer implements LoadBalancer { + /** + * The list of subchannels this load balancer is currently attempting to + * connect to. + */ + private children: SubchannelChild[] = []; + /** + * The current connectivity state of the load balancer. + */ + private currentState: ConnectivityState = ConnectivityState.IDLE; + /** + * The index within the `subchannels` array of the subchannel with the most + * recently started connection attempt. + */ + private currentSubchannelIndex = 0; + /** + * The currently picked subchannel used for making calls. Populated if + * and only if the load balancer's current state is READY. In that case, + * the subchannel's current state is also READY. + */ + private currentPick: SubchannelInterface | null = null; + /** + * Listener callback attached to each subchannel in the `subchannels` list + * while establishing a connection. + */ + private subchannelStateListener: ConnectivityStateListener = ( + subchannel, + previousState, + newState, + keepaliveTime, + errorMessage + ) => { + this.onSubchannelStateUpdate( + subchannel, + previousState, + newState, + errorMessage + ); + }; + + private pickedSubchannelHealthListener: HealthListener = () => + this.calculateAndReportNewState(); + /** + * Timer reference for the timer tracking when to start + */ + private connectionDelayTimeout: NodeJS.Timeout; + + /** + * The LB policy enters sticky TRANSIENT_FAILURE mode when all + * subchannels have failed to connect at least once, and it stays in that + * mode until a connection attempt is successful. While in sticky TF mode, + * the LB policy continuously attempts to connect to all of its subchannels. + */ + private stickyTransientFailureMode = false; + + private reportHealthStatus: boolean = false; + + /** + * The most recent error reported by any subchannel as it transitioned to + * TRANSIENT_FAILURE. + */ + private lastError: string | null = null; + + private latestAddressList: SubchannelAddress[] | null = null; + + private latestOptions: ChannelOptions = {}; + + private latestResolutionNote: string = ''; + + /** + * Load balancer that attempts to connect to each backend in the address list + * in order, and picks the first one that connects, using it for every + * request. + * @param channelControlHelper `ChannelControlHelper` instance provided by + * this load balancer's owner. + */ + constructor( + private readonly channelControlHelper: ChannelControlHelper + ) { + this.connectionDelayTimeout = setTimeout(() => {}, 0); + clearTimeout(this.connectionDelayTimeout); + } + + private allChildrenHaveReportedTF(): boolean { + return this.children.every(child => child.hasReportedTransientFailure); + } + + private resetChildrenReportedTF() { + this.children.every(child => child.hasReportedTransientFailure = false); + } + + private calculateAndReportNewState() { + if (this.currentPick) { + if (this.reportHealthStatus && !this.currentPick.isHealthy()) { + const errorMessage = `Picked subchannel ${this.currentPick.getAddress()} is unhealthy`; + this.updateState( + ConnectivityState.TRANSIENT_FAILURE, + new UnavailablePicker({ + details: errorMessage, + }), + errorMessage + ); + } else { + this.updateState( + ConnectivityState.READY, + new PickFirstPicker(this.currentPick), + null + ); + } + } else if (this.latestAddressList?.length === 0) { + const errorMessage = `No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`; + this.updateState( + ConnectivityState.TRANSIENT_FAILURE, + new UnavailablePicker({ + details: errorMessage, + }), + errorMessage + ); + } else if (this.children.length === 0) { + this.updateState(ConnectivityState.IDLE, new QueuePicker(this), null); + } else { + if (this.stickyTransientFailureMode) { + const errorMessage = `No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`; + this.updateState( + ConnectivityState.TRANSIENT_FAILURE, + new UnavailablePicker({ + details: errorMessage, + }), + errorMessage + ); + } else { + this.updateState(ConnectivityState.CONNECTING, new QueuePicker(this), null); + } + } + } + + private requestReresolution() { + this.channelControlHelper.requestReresolution(); + } + + private maybeEnterStickyTransientFailureMode() { + if (!this.allChildrenHaveReportedTF()) { + return; + } + this.requestReresolution(); + this.resetChildrenReportedTF(); + if (this.stickyTransientFailureMode) { + this.calculateAndReportNewState(); + return; + } + this.stickyTransientFailureMode = true; + for (const { subchannel } of this.children) { + subchannel.startConnecting(); + } + this.calculateAndReportNewState(); + } + + private removeCurrentPick() { + if (this.currentPick !== null) { + this.currentPick.removeConnectivityStateListener(this.subchannelStateListener); + this.channelControlHelper.removeChannelzChild( + this.currentPick.getChannelzRef() + ); + this.currentPick.removeHealthStateWatcher( + this.pickedSubchannelHealthListener + ); + // Unref last, to avoid triggering listeners + this.currentPick.unref(); + this.currentPick = null; + } + } + + private onSubchannelStateUpdate( + subchannel: SubchannelInterface, + previousState: ConnectivityState, + newState: ConnectivityState, + errorMessage?: string + ) { + if (this.currentPick?.realSubchannelEquals(subchannel)) { + if (newState !== ConnectivityState.READY) { + this.removeCurrentPick(); + this.calculateAndReportNewState(); + } + return; + } + for (const [index, child] of this.children.entries()) { + if (subchannel.realSubchannelEquals(child.subchannel)) { + if (newState === ConnectivityState.READY) { + this.pickSubchannel(child.subchannel); + } + if (newState === ConnectivityState.TRANSIENT_FAILURE) { + child.hasReportedTransientFailure = true; + if (errorMessage) { + this.lastError = errorMessage; + } + this.maybeEnterStickyTransientFailureMode(); + if (index === this.currentSubchannelIndex) { + this.startNextSubchannelConnecting(index + 1); + } + } + child.subchannel.startConnecting(); + return; + } + } + } + + private startNextSubchannelConnecting(startIndex: number) { + clearTimeout(this.connectionDelayTimeout); + for (const [index, child] of this.children.entries()) { + if (index >= startIndex) { + const subchannelState = child.subchannel.getConnectivityState(); + if ( + subchannelState === ConnectivityState.IDLE || + subchannelState === ConnectivityState.CONNECTING + ) { + this.startConnecting(index); + return; + } + } + } + this.maybeEnterStickyTransientFailureMode(); + } + + /** + * Have a single subchannel in the `subchannels` list start connecting. + * @param subchannelIndex The index into the `subchannels` list. + */ + private startConnecting(subchannelIndex: number) { + clearTimeout(this.connectionDelayTimeout); + this.currentSubchannelIndex = subchannelIndex; + if ( + this.children[subchannelIndex].subchannel.getConnectivityState() === + ConnectivityState.IDLE + ) { + trace( + 'Start connecting to subchannel with address ' + + this.children[subchannelIndex].subchannel.getAddress() + ); + process.nextTick(() => { + this.children[subchannelIndex]?.subchannel.startConnecting(); + }); + } + this.connectionDelayTimeout = setTimeout(() => { + this.startNextSubchannelConnecting(subchannelIndex + 1); + }, CONNECTION_DELAY_INTERVAL_MS); + this.connectionDelayTimeout.unref?.(); + } + + /** + * Declare that the specified subchannel should be used to make requests. + * This functions the same independent of whether subchannel is a member of + * this.children and whether it is equal to this.currentPick. + * Prerequisite: subchannel.getConnectivityState() === READY. + * @param subchannel + */ + private pickSubchannel(subchannel: SubchannelInterface) { + trace('Pick subchannel with address ' + subchannel.getAddress()); + this.stickyTransientFailureMode = false; + /* Ref before removeCurrentPick and resetSubchannelList to avoid the + * refcount dropping to 0 during this process. */ + subchannel.ref(); + this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef()); + this.removeCurrentPick(); + this.resetSubchannelList(); + subchannel.addConnectivityStateListener(this.subchannelStateListener); + subchannel.addHealthStateWatcher(this.pickedSubchannelHealthListener); + this.currentPick = subchannel; + clearTimeout(this.connectionDelayTimeout); + this.calculateAndReportNewState(); + } + + private updateState(newState: ConnectivityState, picker: Picker, errorMessage: string | null) { + trace( + ConnectivityState[this.currentState] + + ' -> ' + + ConnectivityState[newState] + ); + this.currentState = newState; + this.channelControlHelper.updateState(newState, picker, errorMessage); + } + + private resetSubchannelList() { + for (const child of this.children) { + /* Always remoev the connectivity state listener. If the subchannel is + getting picked, it will be re-added then. */ + child.subchannel.removeConnectivityStateListener( + this.subchannelStateListener + ); + /* Refs are counted independently for the children list and the + * currentPick, so we call unref whether or not the child is the + * currentPick. Channelz child references are also refcounted, so + * removeChannelzChild can be handled the same way. */ + child.subchannel.unref(); + this.channelControlHelper.removeChannelzChild( + child.subchannel.getChannelzRef() + ); + } + this.currentSubchannelIndex = 0; + this.children = []; + } + + private connectToAddressList(addressList: SubchannelAddress[], options: ChannelOptions) { + trace('connectToAddressList([' + addressList.map(address => subchannelAddressToString(address)) + '])'); + const newChildrenList = addressList.map(address => ({ + subchannel: this.channelControlHelper.createSubchannel(address, options), + hasReportedTransientFailure: false, + })); + for (const { subchannel } of newChildrenList) { + if (subchannel.getConnectivityState() === ConnectivityState.READY) { + this.pickSubchannel(subchannel); + return; + } + } + /* Ref each subchannel before resetting the list, to ensure that + * subchannels shared between the list don't drop to 0 refs during the + * transition. */ + for (const { subchannel } of newChildrenList) { + subchannel.ref(); + this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef()); + } + this.resetSubchannelList(); + this.children = newChildrenList; + for (const { subchannel } of this.children) { + subchannel.addConnectivityStateListener(this.subchannelStateListener); + } + for (const child of this.children) { + if ( + child.subchannel.getConnectivityState() === + ConnectivityState.TRANSIENT_FAILURE + ) { + child.hasReportedTransientFailure = true; + } + } + this.startNextSubchannelConnecting(0); + this.calculateAndReportNewState(); + } + + updateAddressList( + maybeEndpointList: StatusOr, + lbConfig: TypedLoadBalancingConfig, + options: ChannelOptions, + resolutionNote: string + ): boolean { + if (!(lbConfig instanceof PickFirstLoadBalancingConfig)) { + return false; + } + if (!maybeEndpointList.ok) { + if (this.children.length === 0 && this.currentPick === null) { + this.channelControlHelper.updateState( + ConnectivityState.TRANSIENT_FAILURE, + new UnavailablePicker(maybeEndpointList.error), + maybeEndpointList.error.details + ); + } + return true; + } + let endpointList = maybeEndpointList.value; + this.reportHealthStatus = options[REPORT_HEALTH_STATUS_OPTION_NAME]; + /* Previously, an update would be discarded if it was identical to the + * previous update, to minimize churn. Now the DNS resolver is + * rate-limited, so that is less of a concern. */ + if (lbConfig.getShuffleAddressList()) { + endpointList = shuffled(endpointList); + } + const rawAddressList = ([] as SubchannelAddress[]).concat( + ...endpointList.map(endpoint => endpoint.addresses) + ); + trace('updateAddressList([' + rawAddressList.map(address => subchannelAddressToString(address)) + '])'); + const addressList = interleaveAddressFamilies(rawAddressList); + this.latestAddressList = addressList; + this.latestOptions = options; + this.connectToAddressList(addressList, options); + this.latestResolutionNote = resolutionNote; + if (rawAddressList.length > 0) { + return true; + } else { + this.lastError = 'No addresses resolved'; + return false; + } + } + + exitIdle() { + if ( + this.currentState === ConnectivityState.IDLE && + this.latestAddressList + ) { + this.connectToAddressList(this.latestAddressList, this.latestOptions); + } + } + + resetBackoff() { + /* The pick first load balancer does not have a connection backoff, so this + * does nothing */ + } + + destroy() { + this.resetSubchannelList(); + this.removeCurrentPick(); + } + + getTypeName(): string { + return TYPE_NAME; + } +} + +const LEAF_CONFIG = new PickFirstLoadBalancingConfig(false); + +/** + * This class handles the leaf load balancing operations for a single endpoint. + * It is a thin wrapper around a PickFirstLoadBalancer with a different API + * that more closely reflects how it will be used as a leaf balancer. + */ +export class LeafLoadBalancer { + private pickFirstBalancer: PickFirstLoadBalancer; + private latestState: ConnectivityState = ConnectivityState.IDLE; + private latestPicker: Picker; + constructor( + private endpoint: Endpoint, + channelControlHelper: ChannelControlHelper, + private options: ChannelOptions, + private resolutionNote: string + ) { + const childChannelControlHelper = createChildChannelControlHelper( + channelControlHelper, + { + updateState: (connectivityState, picker, errorMessage) => { + this.latestState = connectivityState; + this.latestPicker = picker; + channelControlHelper.updateState(connectivityState, picker, errorMessage); + }, + } + ); + this.pickFirstBalancer = new PickFirstLoadBalancer( + childChannelControlHelper + ); + this.latestPicker = new QueuePicker(this.pickFirstBalancer); + } + + startConnecting() { + this.pickFirstBalancer.updateAddressList( + statusOrFromValue([this.endpoint]), + LEAF_CONFIG, + { ...this.options, [REPORT_HEALTH_STATUS_OPTION_NAME]: true }, + this.resolutionNote + ); + } + + /** + * Update the endpoint associated with this LeafLoadBalancer to a new + * endpoint. Does not trigger connection establishment if a connection + * attempt is not already in progress. + * @param newEndpoint + */ + updateEndpoint(newEndpoint: Endpoint, newOptions: ChannelOptions) { + this.options = newOptions; + this.endpoint = newEndpoint; + if (this.latestState !== ConnectivityState.IDLE) { + this.startConnecting(); + } + } + + getConnectivityState() { + return this.latestState; + } + + getPicker() { + return this.latestPicker; + } + + getEndpoint() { + return this.endpoint; + } + + exitIdle() { + this.pickFirstBalancer.exitIdle(); + } + + destroy() { + this.pickFirstBalancer.destroy(); + } +} + +export function setup(): void { + registerLoadBalancerType( + TYPE_NAME, + PickFirstLoadBalancer, + PickFirstLoadBalancingConfig + ); + registerDefaultLoadBalancerType(TYPE_NAME); +} diff --git a/node_modules/@grpc/grpc-js/src/load-balancer-round-robin.ts b/node_modules/@grpc/grpc-js/src/load-balancer-round-robin.ts new file mode 100644 index 0000000..17756b4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/load-balancer-round-robin.ts @@ -0,0 +1,287 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { + LoadBalancer, + ChannelControlHelper, + TypedLoadBalancingConfig, + registerLoadBalancerType, + createChildChannelControlHelper, +} from './load-balancer'; +import { ConnectivityState } from './connectivity-state'; +import { + QueuePicker, + Picker, + PickArgs, + UnavailablePicker, + PickResult, +} from './picker'; +import * as logging from './logging'; +import { LogVerbosity } from './constants'; +import { + Endpoint, + endpointEqual, + endpointToString, +} from './subchannel-address'; +import { LeafLoadBalancer } from './load-balancer-pick-first'; +import { ChannelOptions } from './channel-options'; +import { StatusOr } from './call-interface'; + +const TRACER_NAME = 'round_robin'; + +function trace(text: string): void { + logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text); +} + +const TYPE_NAME = 'round_robin'; + +class RoundRobinLoadBalancingConfig implements TypedLoadBalancingConfig { + getLoadBalancerName(): string { + return TYPE_NAME; + } + + constructor() {} + + toJsonObject(): object { + return { + [TYPE_NAME]: {}, + }; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static createFromJson(obj: any) { + return new RoundRobinLoadBalancingConfig(); + } +} + +class RoundRobinPicker implements Picker { + constructor( + private readonly children: { endpoint: Endpoint; picker: Picker }[], + private nextIndex = 0 + ) {} + + pick(pickArgs: PickArgs): PickResult { + const childPicker = this.children[this.nextIndex].picker; + this.nextIndex = (this.nextIndex + 1) % this.children.length; + return childPicker.pick(pickArgs); + } + + /** + * Check what the next subchannel returned would be. Used by the load + * balancer implementation to preserve this part of the picker state if + * possible when a subchannel connects or disconnects. + */ + peekNextEndpoint(): Endpoint { + return this.children[this.nextIndex].endpoint; + } +} + +function rotateArray(list: T[], startIndex: number) { + return [...list.slice(startIndex), ...list.slice(0, startIndex)]; +} + +export class RoundRobinLoadBalancer implements LoadBalancer { + private children: LeafLoadBalancer[] = []; + + private currentState: ConnectivityState = ConnectivityState.IDLE; + + private currentReadyPicker: RoundRobinPicker | null = null; + + private updatesPaused = false; + + private childChannelControlHelper: ChannelControlHelper; + + private lastError: string | null = null; + + constructor( + private readonly channelControlHelper: ChannelControlHelper + ) { + this.childChannelControlHelper = createChildChannelControlHelper( + channelControlHelper, + { + updateState: (connectivityState, picker, errorMessage) => { + /* Ensure that name resolution is requested again after active + * connections are dropped. This is more aggressive than necessary to + * accomplish that, so we are counting on resolvers to have + * reasonable rate limits. */ + if (this.currentState === ConnectivityState.READY && connectivityState !== ConnectivityState.READY) { + this.channelControlHelper.requestReresolution(); + } + if (errorMessage) { + this.lastError = errorMessage; + } + this.calculateAndUpdateState(); + }, + } + ); + } + + private countChildrenWithState(state: ConnectivityState) { + return this.children.filter(child => child.getConnectivityState() === state) + .length; + } + + private calculateAndUpdateState() { + if (this.updatesPaused) { + return; + } + if (this.countChildrenWithState(ConnectivityState.READY) > 0) { + const readyChildren = this.children.filter( + child => child.getConnectivityState() === ConnectivityState.READY + ); + let index = 0; + if (this.currentReadyPicker !== null) { + const nextPickedEndpoint = this.currentReadyPicker.peekNextEndpoint(); + index = readyChildren.findIndex(child => + endpointEqual(child.getEndpoint(), nextPickedEndpoint) + ); + if (index < 0) { + index = 0; + } + } + this.updateState( + ConnectivityState.READY, + new RoundRobinPicker( + readyChildren.map(child => ({ + endpoint: child.getEndpoint(), + picker: child.getPicker(), + })), + index + ), + null + ); + } else if (this.countChildrenWithState(ConnectivityState.CONNECTING) > 0) { + this.updateState(ConnectivityState.CONNECTING, new QueuePicker(this), null); + } else if ( + this.countChildrenWithState(ConnectivityState.TRANSIENT_FAILURE) > 0 + ) { + const errorMessage = `round_robin: No connection established. Last error: ${this.lastError}`; + this.updateState( + ConnectivityState.TRANSIENT_FAILURE, + new UnavailablePicker({ + details: errorMessage, + }), + errorMessage + ); + } else { + this.updateState(ConnectivityState.IDLE, new QueuePicker(this), null); + } + /* round_robin should keep all children connected, this is how we do that. + * We can't do this more efficiently in the individual child's updateState + * callback because that doesn't have a reference to which child the state + * change is associated with. */ + for (const child of this.children) { + if (child.getConnectivityState() === ConnectivityState.IDLE) { + child.exitIdle(); + } + } + } + + private updateState(newState: ConnectivityState, picker: Picker, errorMessage: string | null) { + trace( + ConnectivityState[this.currentState] + + ' -> ' + + ConnectivityState[newState] + ); + if (newState === ConnectivityState.READY) { + this.currentReadyPicker = picker as RoundRobinPicker; + } else { + this.currentReadyPicker = null; + } + this.currentState = newState; + this.channelControlHelper.updateState(newState, picker, errorMessage); + } + + private resetSubchannelList() { + for (const child of this.children) { + child.destroy(); + } + this.children = []; + } + + updateAddressList( + maybeEndpointList: StatusOr, + lbConfig: TypedLoadBalancingConfig, + options: ChannelOptions, + resolutionNote: string + ): boolean { + if (!(lbConfig instanceof RoundRobinLoadBalancingConfig)) { + return false; + } + if (!maybeEndpointList.ok) { + if (this.children.length === 0) { + this.updateState( + ConnectivityState.TRANSIENT_FAILURE, + new UnavailablePicker(maybeEndpointList.error), + maybeEndpointList.error.details + ); + } + return true; + } + const startIndex = (Math.random() * maybeEndpointList.value.length) | 0; + const endpointList = rotateArray(maybeEndpointList.value, startIndex); + this.resetSubchannelList(); + if (endpointList.length === 0) { + const errorMessage = `No addresses resolved. Resolution note: ${resolutionNote}`; + this.updateState( + ConnectivityState.TRANSIENT_FAILURE, + new UnavailablePicker({details: errorMessage}), + errorMessage + ); + } + trace('Connect to endpoint list ' + endpointList.map(endpointToString)); + this.updatesPaused = true; + this.children = endpointList.map( + endpoint => + new LeafLoadBalancer( + endpoint, + this.childChannelControlHelper, + options, + resolutionNote + ) + ); + for (const child of this.children) { + child.startConnecting(); + } + this.updatesPaused = false; + this.calculateAndUpdateState(); + return true; + } + + exitIdle(): void { + /* The round_robin LB policy is only in the IDLE state if it has no + * addresses to try to connect to and it has no picked subchannel. + * In that case, there is no meaningful action that can be taken here. */ + } + resetBackoff(): void { + // This LB policy has no backoff to reset + } + destroy(): void { + this.resetSubchannelList(); + } + getTypeName(): string { + return TYPE_NAME; + } +} + +export function setup() { + registerLoadBalancerType( + TYPE_NAME, + RoundRobinLoadBalancer, + RoundRobinLoadBalancingConfig + ); +} diff --git a/node_modules/@grpc/grpc-js/src/load-balancer-weighted-round-robin.ts b/node_modules/@grpc/grpc-js/src/load-balancer-weighted-round-robin.ts new file mode 100644 index 0000000..cdeabc3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/load-balancer-weighted-round-robin.ts @@ -0,0 +1,494 @@ +/* + * Copyright 2025 gRPC authors. + * + * 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. + * + */ + +import { StatusOr } from './call-interface'; +import { ChannelOptions } from './channel-options'; +import { ConnectivityState } from './connectivity-state'; +import { LogVerbosity } from './constants'; +import { Duration, durationMessageToDuration, durationToMs, durationToString, isDuration, isDurationMessage, msToDuration, parseDuration } from './duration'; +import { OrcaLoadReport__Output } from './generated/xds/data/orca/v3/OrcaLoadReport'; +import { ChannelControlHelper, createChildChannelControlHelper, LoadBalancer, registerLoadBalancerType, TypedLoadBalancingConfig } from './load-balancer'; +import { LeafLoadBalancer } from './load-balancer-pick-first'; +import * as logging from './logging'; +import { createMetricsReader, MetricsListener, OrcaOobMetricsSubchannelWrapper } from './orca'; +import { PickArgs, Picker, PickResult, PickResultType, QueuePicker, UnavailablePicker } from './picker'; +import { PriorityQueue } from './priority-queue'; +import { Endpoint, endpointToString } from './subchannel-address'; + +const TRACER_NAME = 'weighted_round_robin'; + +function trace(text: string): void { + logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text); +} + +const TYPE_NAME = 'weighted_round_robin'; + +const DEFAULT_OOB_REPORTING_PERIOD_MS = 10_000; +const DEFAULT_BLACKOUT_PERIOD_MS = 10_000; +const DEFAULT_WEIGHT_EXPIRATION_PERIOD_MS = 3 * 60_000; +const DEFAULT_WEIGHT_UPDATE_PERIOD_MS = 1_000; +const DEFAULT_ERROR_UTILIZATION_PENALTY = 1; + +type TypeofValues = + | 'object' + | 'boolean' + | 'function' + | 'number' + | 'string' + | 'undefined'; + +function validateFieldType( + obj: any, + fieldName: string, + expectedType: TypeofValues +) { + if ( + fieldName in obj && + obj[fieldName] !== undefined && + typeof obj[fieldName] !== expectedType + ) { + throw new Error( + `weighted round robin config ${fieldName} parse error: expected ${expectedType}, got ${typeof obj[ + fieldName + ]}` + ); + } +} + +function parseDurationField(obj: any, fieldName: string): number | null { + if (fieldName in obj && obj[fieldName] !== undefined && obj[fieldName] !== null) { + let durationObject: Duration; + if (isDuration(obj[fieldName])) { + durationObject = obj[fieldName]; + } else if (isDurationMessage(obj[fieldName])) { + durationObject = durationMessageToDuration(obj[fieldName]); + } else if (typeof obj[fieldName] === 'string') { + const parsedDuration = parseDuration(obj[fieldName]); + if (!parsedDuration) { + throw new Error(`weighted round robin config ${fieldName}: failed to parse duration string ${obj[fieldName]}`); + } + durationObject = parsedDuration; + } else { + throw new Error(`weighted round robin config ${fieldName}: expected duration, got ${typeof obj[fieldName]}`); + } + return durationToMs(durationObject); + } + return null; +} + +export class WeightedRoundRobinLoadBalancingConfig implements TypedLoadBalancingConfig { + private readonly enableOobLoadReport: boolean; + private readonly oobLoadReportingPeriodMs: number; + private readonly blackoutPeriodMs: number; + private readonly weightExpirationPeriodMs: number; + private readonly weightUpdatePeriodMs: number; + private readonly errorUtilizationPenalty: number; + + constructor( + enableOobLoadReport: boolean | null, + oobLoadReportingPeriodMs: number | null, + blackoutPeriodMs: number | null, + weightExpirationPeriodMs: number | null, + weightUpdatePeriodMs: number | null, + errorUtilizationPenalty: number | null + ) { + this.enableOobLoadReport = enableOobLoadReport ?? false; + this.oobLoadReportingPeriodMs = oobLoadReportingPeriodMs ?? DEFAULT_OOB_REPORTING_PERIOD_MS; + this.blackoutPeriodMs = blackoutPeriodMs ?? DEFAULT_BLACKOUT_PERIOD_MS; + this.weightExpirationPeriodMs = weightExpirationPeriodMs ?? DEFAULT_WEIGHT_EXPIRATION_PERIOD_MS; + this.weightUpdatePeriodMs = Math.max(weightUpdatePeriodMs ?? DEFAULT_WEIGHT_UPDATE_PERIOD_MS, 100); + this.errorUtilizationPenalty = errorUtilizationPenalty ?? DEFAULT_ERROR_UTILIZATION_PENALTY; + } + + getLoadBalancerName(): string { + return TYPE_NAME; + } + toJsonObject(): object { + return { + enable_oob_load_report: this.enableOobLoadReport, + oob_load_reporting_period: durationToString(msToDuration(this.oobLoadReportingPeriodMs)), + blackout_period: durationToString(msToDuration(this.blackoutPeriodMs)), + weight_expiration_period: durationToString(msToDuration(this.weightExpirationPeriodMs)), + weight_update_period: durationToString(msToDuration(this.weightUpdatePeriodMs)), + error_utilization_penalty: this.errorUtilizationPenalty + }; + } + static createFromJson(obj: any): WeightedRoundRobinLoadBalancingConfig { + validateFieldType(obj, 'enable_oob_load_report', 'boolean'); + validateFieldType(obj, 'error_utilization_penalty', 'number'); + if (obj.error_utilization_penalty < 0) { + throw new Error('weighted round robin config error_utilization_penalty < 0'); + } + return new WeightedRoundRobinLoadBalancingConfig( + obj.enable_oob_load_report, + parseDurationField(obj, 'oob_load_reporting_period'), + parseDurationField(obj, 'blackout_period'), + parseDurationField(obj, 'weight_expiration_period'), + parseDurationField(obj, 'weight_update_period'), + obj.error_utilization_penalty + ) + } + + getEnableOobLoadReport() { + return this.enableOobLoadReport; + } + getOobLoadReportingPeriodMs() { + return this.oobLoadReportingPeriodMs; + } + getBlackoutPeriodMs() { + return this.blackoutPeriodMs; + } + getWeightExpirationPeriodMs() { + return this.weightExpirationPeriodMs; + } + getWeightUpdatePeriodMs() { + return this.weightUpdatePeriodMs; + } + getErrorUtilizationPenalty() { + return this.errorUtilizationPenalty; + } +} + +interface WeightedPicker { + endpointName: string; + picker: Picker; + weight: number; +} + +interface QueueEntry { + endpointName: string; + picker: Picker; + period: number; + deadline: number; +} + +type MetricsHandler = (loadReport: OrcaLoadReport__Output, endpointName: string) => void; + +class WeightedRoundRobinPicker implements Picker { + private queue: PriorityQueue = new PriorityQueue((a, b) => a.deadline < b.deadline); + constructor(children: WeightedPicker[], private readonly metricsHandler: MetricsHandler | null) { + const positiveWeight = children.filter(picker => picker.weight > 0); + let averageWeight: number; + if (positiveWeight.length < 2) { + averageWeight = 1; + } else { + let weightSum: number = 0; + for (const { weight } of positiveWeight) { + weightSum += weight; + } + averageWeight = weightSum / positiveWeight.length; + } + for (const child of children) { + const period = child.weight > 0 ? 1 / child.weight : averageWeight; + this.queue.push({ + endpointName: child.endpointName, + picker: child.picker, + period: period, + deadline: Math.random() * period + }); + } + } + pick(pickArgs: PickArgs): PickResult { + const entry = this.queue.pop()!; + this.queue.push({ + ...entry, + deadline: entry.deadline + entry.period + }) + const childPick = entry.picker.pick(pickArgs); + if (childPick.pickResultType === PickResultType.COMPLETE) { + if (this.metricsHandler) { + return { + ...childPick, + onCallEnded: createMetricsReader(loadReport => this.metricsHandler!(loadReport, entry.endpointName), childPick.onCallEnded) + }; + } else { + const subchannelWrapper = childPick.subchannel as OrcaOobMetricsSubchannelWrapper; + return { + ...childPick, + subchannel: subchannelWrapper.getWrappedSubchannel() + } + } + } else { + return childPick; + } + } +} + +interface ChildEntry { + child: LeafLoadBalancer; + lastUpdated: Date; + nonEmptySince: Date | null; + weight: number; + oobMetricsListener: MetricsListener | null; +} + +class WeightedRoundRobinLoadBalancer implements LoadBalancer { + private latestConfig: WeightedRoundRobinLoadBalancingConfig | null = null; + + private children: Map = new Map(); + + private currentState: ConnectivityState = ConnectivityState.IDLE; + + private updatesPaused = false; + + private lastError: string | null = null; + + private weightUpdateTimer: NodeJS.Timeout | null = null; + + constructor(private readonly channelControlHelper: ChannelControlHelper) {} + + private countChildrenWithState(state: ConnectivityState) { + let count = 0; + for (const entry of this.children.values()) { + if (entry.child.getConnectivityState() === state) { + count += 1; + } + } + return count; + } + + updateWeight(entry: ChildEntry, loadReport: OrcaLoadReport__Output): void { + const qps = loadReport.rps_fractional; + let utilization = loadReport.application_utilization; + if (utilization > 0 && qps > 0) { + utilization += (loadReport.eps / qps) * (this.latestConfig?.getErrorUtilizationPenalty() ?? 0); + } + const newWeight = utilization === 0 ? 0 : qps / utilization; + if (newWeight === 0) { + return; + } + const now = new Date(); + if (entry.nonEmptySince === null) { + entry.nonEmptySince = now; + } + entry.lastUpdated = now; + entry.weight = newWeight; + } + + getWeight(entry: ChildEntry): number { + if (!this.latestConfig) { + return 0; + } + const now = new Date().getTime(); + if (now - entry.lastUpdated.getTime() >= this.latestConfig.getWeightExpirationPeriodMs()) { + entry.nonEmptySince = null; + return 0; + } + const blackoutPeriod = this.latestConfig.getBlackoutPeriodMs(); + if (blackoutPeriod > 0 && (entry.nonEmptySince === null || now - entry.nonEmptySince.getTime() < blackoutPeriod)) { + return 0; + } + return entry.weight; + } + + private calculateAndUpdateState() { + if (this.updatesPaused || !this.latestConfig) { + return; + } + if (this.countChildrenWithState(ConnectivityState.READY) > 0) { + const weightedPickers: WeightedPicker[] = []; + for (const [endpoint, entry] of this.children) { + if (entry.child.getConnectivityState() !== ConnectivityState.READY) { + continue; + } + weightedPickers.push({ + endpointName: endpoint, + picker: entry.child.getPicker(), + weight: this.getWeight(entry) + }); + } + trace('Created picker with weights: ' + weightedPickers.map(entry => entry.endpointName + ':' + entry.weight).join(',')); + let metricsHandler: MetricsHandler | null; + if (!this.latestConfig.getEnableOobLoadReport()) { + metricsHandler = (loadReport, endpointName) => { + const childEntry = this.children.get(endpointName); + if (childEntry) { + this.updateWeight(childEntry, loadReport); + } + }; + } else { + metricsHandler = null; + } + this.updateState( + ConnectivityState.READY, + new WeightedRoundRobinPicker( + weightedPickers, + metricsHandler + ), + null + ); + } else if (this.countChildrenWithState(ConnectivityState.CONNECTING) > 0) { + this.updateState(ConnectivityState.CONNECTING, new QueuePicker(this), null); + } else if ( + this.countChildrenWithState(ConnectivityState.TRANSIENT_FAILURE) > 0 + ) { + const errorMessage = `weighted_round_robin: No connection established. Last error: ${this.lastError}`; + this.updateState( + ConnectivityState.TRANSIENT_FAILURE, + new UnavailablePicker({ + details: errorMessage, + }), + errorMessage + ); + } else { + this.updateState(ConnectivityState.IDLE, new QueuePicker(this), null); + } + /* round_robin should keep all children connected, this is how we do that. + * We can't do this more efficiently in the individual child's updateState + * callback because that doesn't have a reference to which child the state + * change is associated with. */ + for (const {child} of this.children.values()) { + if (child.getConnectivityState() === ConnectivityState.IDLE) { + child.exitIdle(); + } + } + } + + private updateState(newState: ConnectivityState, picker: Picker, errorMessage: string | null) { + trace( + ConnectivityState[this.currentState] + + ' -> ' + + ConnectivityState[newState] + ); + this.currentState = newState; + this.channelControlHelper.updateState(newState, picker, errorMessage); + } + + updateAddressList(maybeEndpointList: StatusOr, lbConfig: TypedLoadBalancingConfig, options: ChannelOptions, resolutionNote: string): boolean { + if (!(lbConfig instanceof WeightedRoundRobinLoadBalancingConfig)) { + return false; + } + if (!maybeEndpointList.ok) { + if (this.children.size === 0) { + this.updateState( + ConnectivityState.TRANSIENT_FAILURE, + new UnavailablePicker(maybeEndpointList.error), + maybeEndpointList.error.details + ); + } + return true; + } + if (maybeEndpointList.value.length === 0) { + const errorMessage = `No addresses resolved. Resolution note: ${resolutionNote}`; + this.updateState( + ConnectivityState.TRANSIENT_FAILURE, + new UnavailablePicker({details: errorMessage}), + errorMessage + ); + return false; + } + trace('Connect to endpoint list ' + maybeEndpointList.value.map(endpointToString)); + const now = new Date(); + const seenEndpointNames = new Set(); + this.updatesPaused = true; + this.latestConfig = lbConfig; + for (const endpoint of maybeEndpointList.value) { + const name = endpointToString(endpoint); + seenEndpointNames.add(name); + let entry = this.children.get(name); + if (!entry) { + entry = { + child: new LeafLoadBalancer(endpoint, createChildChannelControlHelper(this.channelControlHelper, { + updateState: (connectivityState, picker, errorMessage) => { + /* Ensure that name resolution is requested again after active + * connections are dropped. This is more aggressive than necessary to + * accomplish that, so we are counting on resolvers to have + * reasonable rate limits. */ + if (this.currentState === ConnectivityState.READY && connectivityState !== ConnectivityState.READY) { + this.channelControlHelper.requestReresolution(); + } + if (connectivityState === ConnectivityState.READY) { + entry!.nonEmptySince = null; + } + if (errorMessage) { + this.lastError = errorMessage; + } + this.calculateAndUpdateState(); + }, + createSubchannel: (subchannelAddress, subchannelArgs) => { + const subchannel = this.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); + if (entry?.oobMetricsListener) { + return new OrcaOobMetricsSubchannelWrapper(subchannel, entry.oobMetricsListener, this.latestConfig!.getOobLoadReportingPeriodMs()); + } else { + return subchannel; + } + } + }), options, resolutionNote), + lastUpdated: now, + nonEmptySince: null, + weight: 0, + oobMetricsListener: null + }; + this.children.set(name, entry); + } + if (lbConfig.getEnableOobLoadReport()) { + entry.oobMetricsListener = loadReport => { + this.updateWeight(entry!, loadReport); + }; + } else { + entry.oobMetricsListener = null; + } + } + for (const [endpointName, entry] of this.children) { + if (seenEndpointNames.has(endpointName)) { + entry.child.startConnecting(); + } else { + entry.child.destroy(); + this.children.delete(endpointName); + } + } + this.updatesPaused = false; + this.calculateAndUpdateState(); + if (this.weightUpdateTimer) { + clearInterval(this.weightUpdateTimer); + } + this.weightUpdateTimer = setInterval(() => { + if (this.currentState === ConnectivityState.READY) { + this.calculateAndUpdateState(); + } + }, lbConfig.getWeightUpdatePeriodMs()).unref?.(); + return true; + } + exitIdle(): void { + /* The weighted_round_robin LB policy is only in the IDLE state if it has + * no addresses to try to connect to and it has no picked subchannel. + * In that case, there is no meaningful action that can be taken here. */ + } + resetBackoff(): void { + // This LB policy has no backoff to reset + } + destroy(): void { + for (const entry of this.children.values()) { + entry.child.destroy(); + } + this.children.clear(); + if (this.weightUpdateTimer) { + clearInterval(this.weightUpdateTimer); + } + } + getTypeName(): string { + return TYPE_NAME; + } +} + +export function setup() { + registerLoadBalancerType( + TYPE_NAME, + WeightedRoundRobinLoadBalancer, + WeightedRoundRobinLoadBalancingConfig + ); +} diff --git a/node_modules/@grpc/grpc-js/src/load-balancer.ts b/node_modules/@grpc/grpc-js/src/load-balancer.ts new file mode 100644 index 0000000..18f762e --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/load-balancer.ts @@ -0,0 +1,258 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { ChannelOptions } from './channel-options'; +import { Endpoint, SubchannelAddress } from './subchannel-address'; +import { ConnectivityState } from './connectivity-state'; +import { Picker } from './picker'; +import type { ChannelRef, SubchannelRef } from './channelz'; +import { SubchannelInterface } from './subchannel-interface'; +import { LoadBalancingConfig } from './service-config'; +import { log } from './logging'; +import { LogVerbosity } from './constants'; +import { StatusOr } from './call-interface'; + +/** + * A collection of functions associated with a channel that a load balancer + * can call as necessary. + */ +export interface ChannelControlHelper { + /** + * Returns a subchannel connected to the specified address. + * @param subchannelAddress The address to connect to + * @param subchannelArgs Channel arguments to use to construct the subchannel + */ + createSubchannel( + subchannelAddress: SubchannelAddress, + subchannelArgs: ChannelOptions + ): SubchannelInterface; + /** + * Passes a new subchannel picker up to the channel. This is called if either + * the connectivity state changes or if a different picker is needed for any + * other reason. + * @param connectivityState New connectivity state + * @param picker New picker + */ + updateState( + connectivityState: ConnectivityState, + picker: Picker, + errorMessage: string | null + ): void; + /** + * Request new data from the resolver. + */ + requestReresolution(): void; + addChannelzChild(child: ChannelRef | SubchannelRef): void; + removeChannelzChild(child: ChannelRef | SubchannelRef): void; +} + +/** + * Create a child ChannelControlHelper that overrides some methods of the + * parent while letting others pass through to the parent unmodified. This + * allows other code to create these children without needing to know about + * all of the methods to be passed through. + * @param parent + * @param overrides + */ +export function createChildChannelControlHelper( + parent: ChannelControlHelper, + overrides: Partial +): ChannelControlHelper { + return { + createSubchannel: + overrides.createSubchannel?.bind(overrides) ?? + parent.createSubchannel.bind(parent), + updateState: + overrides.updateState?.bind(overrides) ?? parent.updateState.bind(parent), + requestReresolution: + overrides.requestReresolution?.bind(overrides) ?? + parent.requestReresolution.bind(parent), + addChannelzChild: + overrides.addChannelzChild?.bind(overrides) ?? + parent.addChannelzChild.bind(parent), + removeChannelzChild: + overrides.removeChannelzChild?.bind(overrides) ?? + parent.removeChannelzChild.bind(parent), + }; +} + +/** + * Tracks one or more connected subchannels and determines which subchannel + * each request should use. + */ +export interface LoadBalancer { + /** + * Gives the load balancer a new list of addresses to start connecting to. + * The load balancer will start establishing connections with the new list, + * but will continue using any existing connections until the new connections + * are established + * @param endpointList The new list of addresses to connect to + * @param lbConfig The load balancing config object from the service config, + * if one was provided + * @param channelOptions Channel options from the channel, plus resolver + * attributes + * @param resolutionNote A not from the resolver to include in errors + */ + updateAddressList( + endpointList: StatusOr, + lbConfig: TypedLoadBalancingConfig, + channelOptions: ChannelOptions, + resolutionNote: string + ): boolean; + /** + * If the load balancer is currently in the IDLE state, start connecting. + */ + exitIdle(): void; + /** + * If the load balancer is currently in the CONNECTING or TRANSIENT_FAILURE + * state, reset the current connection backoff timeout to its base value and + * transition to CONNECTING if in TRANSIENT_FAILURE. + */ + resetBackoff(): void; + /** + * The load balancer unrefs all of its subchannels and stops calling methods + * of its channel control helper. + */ + destroy(): void; + /** + * Get the type name for this load balancer type. Must be constant across an + * entire load balancer implementation class and must match the name that the + * balancer implementation class was registered with. + */ + getTypeName(): string; +} + +export interface LoadBalancerConstructor { + new ( + channelControlHelper: ChannelControlHelper + ): LoadBalancer; +} + +export interface TypedLoadBalancingConfig { + getLoadBalancerName(): string; + toJsonObject(): object; +} + +export interface TypedLoadBalancingConfigConstructor { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + new (...args: any): TypedLoadBalancingConfig; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + createFromJson(obj: any): TypedLoadBalancingConfig; +} + +const registeredLoadBalancerTypes: { + [name: string]: { + LoadBalancer: LoadBalancerConstructor; + LoadBalancingConfig: TypedLoadBalancingConfigConstructor; + }; +} = {}; + +let defaultLoadBalancerType: string | null = null; + +export function registerLoadBalancerType( + typeName: string, + loadBalancerType: LoadBalancerConstructor, + loadBalancingConfigType: TypedLoadBalancingConfigConstructor +) { + registeredLoadBalancerTypes[typeName] = { + LoadBalancer: loadBalancerType, + LoadBalancingConfig: loadBalancingConfigType, + }; +} + +export function registerDefaultLoadBalancerType(typeName: string) { + defaultLoadBalancerType = typeName; +} + +export function createLoadBalancer( + config: TypedLoadBalancingConfig, + channelControlHelper: ChannelControlHelper +): LoadBalancer | null { + const typeName = config.getLoadBalancerName(); + if (typeName in registeredLoadBalancerTypes) { + return new registeredLoadBalancerTypes[typeName].LoadBalancer( + channelControlHelper + ); + } else { + return null; + } +} + +export function isLoadBalancerNameRegistered(typeName: string): boolean { + return typeName in registeredLoadBalancerTypes; +} + +export function parseLoadBalancingConfig( + rawConfig: LoadBalancingConfig +): TypedLoadBalancingConfig { + const keys = Object.keys(rawConfig); + if (keys.length !== 1) { + throw new Error( + 'Provided load balancing config has multiple conflicting entries' + ); + } + const typeName = keys[0]; + if (typeName in registeredLoadBalancerTypes) { + try { + return registeredLoadBalancerTypes[ + typeName + ].LoadBalancingConfig.createFromJson(rawConfig[typeName]); + } catch (e) { + throw new Error(`${typeName}: ${(e as Error).message}`); + } + } else { + throw new Error(`Unrecognized load balancing config name ${typeName}`); + } +} + +export function getDefaultConfig() { + if (!defaultLoadBalancerType) { + throw new Error('No default load balancer type registered'); + } + return new registeredLoadBalancerTypes[ + defaultLoadBalancerType + ]!.LoadBalancingConfig(); +} + +export function selectLbConfigFromList( + configs: LoadBalancingConfig[], + fallbackTodefault = false +): TypedLoadBalancingConfig | null { + for (const config of configs) { + try { + return parseLoadBalancingConfig(config); + } catch (e) { + log( + LogVerbosity.DEBUG, + 'Config parsing failed with error', + (e as Error).message + ); + continue; + } + } + if (fallbackTodefault) { + if (defaultLoadBalancerType) { + return new registeredLoadBalancerTypes[ + defaultLoadBalancerType + ]!.LoadBalancingConfig(); + } else { + return null; + } + } else { + return null; + } +} diff --git a/node_modules/@grpc/grpc-js/src/load-balancing-call.ts b/node_modules/@grpc/grpc-js/src/load-balancing-call.ts new file mode 100644 index 0000000..3ff7289 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/load-balancing-call.ts @@ -0,0 +1,387 @@ +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ + +import { CallCredentials } from './call-credentials'; +import { + Call, + DeadlineInfoProvider, + InterceptingListener, + MessageContext, + StatusObject, +} from './call-interface'; +import { SubchannelCall } from './subchannel-call'; +import { ConnectivityState } from './connectivity-state'; +import { LogVerbosity, Status } from './constants'; +import { Deadline, formatDateDifference, getDeadlineTimeoutString } from './deadline'; +import { InternalChannel } from './internal-channel'; +import { Metadata } from './metadata'; +import { OnCallEnded, PickResultType } from './picker'; +import { CallConfig } from './resolver'; +import { splitHostPort } from './uri-parser'; +import * as logging from './logging'; +import { restrictControlPlaneStatusCode } from './control-plane-status'; +import * as http2 from 'http2'; +import { AuthContext } from './auth-context'; + +const TRACER_NAME = 'load_balancing_call'; + +export type RpcProgress = 'NOT_STARTED' | 'DROP' | 'REFUSED' | 'PROCESSED'; + +export interface StatusObjectWithProgress extends StatusObject { + progress: RpcProgress; +} + +export interface LoadBalancingCallInterceptingListener + extends InterceptingListener { + onReceiveStatus(status: StatusObjectWithProgress): void; +} + +export class LoadBalancingCall implements Call, DeadlineInfoProvider { + private child: SubchannelCall | null = null; + private readPending = false; + private pendingMessage: { context: MessageContext; message: Buffer } | null = + null; + private pendingHalfClose = false; + private ended = false; + private serviceUrl: string; + private metadata: Metadata | null = null; + private listener: InterceptingListener | null = null; + private onCallEnded: OnCallEnded | null = null; + private startTime: Date; + private childStartTime: Date | null = null; + constructor( + private readonly channel: InternalChannel, + private readonly callConfig: CallConfig, + private readonly methodName: string, + private readonly host: string, + private readonly credentials: CallCredentials, + private readonly deadline: Deadline, + private readonly callNumber: number + ) { + const splitPath: string[] = this.methodName.split('/'); + let serviceName = ''; + /* The standard path format is "/{serviceName}/{methodName}", so if we split + * by '/', the first item should be empty and the second should be the + * service name */ + if (splitPath.length >= 2) { + serviceName = splitPath[1]; + } + const hostname = splitHostPort(this.host)?.host ?? 'localhost'; + /* Currently, call credentials are only allowed on HTTPS connections, so we + * can assume that the scheme is "https" */ + this.serviceUrl = `https://${hostname}/${serviceName}`; + this.startTime = new Date(); + } + getDeadlineInfo(): string[] { + const deadlineInfo: string[] = []; + if (this.childStartTime) { + if (this.childStartTime > this.startTime) { + if (this.metadata?.getOptions().waitForReady) { + deadlineInfo.push('wait_for_ready'); + } + deadlineInfo.push(`LB pick: ${formatDateDifference(this.startTime, this.childStartTime)}`); + } + deadlineInfo.push(...this.child!.getDeadlineInfo()); + return deadlineInfo; + } else { + if (this.metadata?.getOptions().waitForReady) { + deadlineInfo.push('wait_for_ready'); + } + deadlineInfo.push('Waiting for LB pick'); + } + return deadlineInfo; + } + + private trace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + TRACER_NAME, + '[' + this.callNumber + '] ' + text + ); + } + + private outputStatus(status: StatusObject, progress: RpcProgress) { + if (!this.ended) { + this.ended = true; + this.trace( + 'ended with status: code=' + + status.code + + ' details="' + + status.details + + '" start time=' + + this.startTime.toISOString() + ); + const finalStatus = { ...status, progress }; + this.listener?.onReceiveStatus(finalStatus); + this.onCallEnded?.(finalStatus.code, finalStatus.details, finalStatus.metadata); + } + } + + doPick() { + if (this.ended) { + return; + } + if (!this.metadata) { + throw new Error('doPick called before start'); + } + this.trace('Pick called'); + const finalMetadata = this.metadata.clone(); + const pickResult = this.channel.doPick( + finalMetadata, + this.callConfig.pickInformation + ); + const subchannelString = pickResult.subchannel + ? '(' + + pickResult.subchannel.getChannelzRef().id + + ') ' + + pickResult.subchannel.getAddress() + : '' + pickResult.subchannel; + this.trace( + 'Pick result: ' + + PickResultType[pickResult.pickResultType] + + ' subchannel: ' + + subchannelString + + ' status: ' + + pickResult.status?.code + + ' ' + + pickResult.status?.details + ); + switch (pickResult.pickResultType) { + case PickResultType.COMPLETE: + const combinedCallCredentials = this.credentials.compose(pickResult.subchannel!.getCallCredentials()); + combinedCallCredentials + .generateMetadata({ method_name: this.methodName, service_url: this.serviceUrl }) + .then( + credsMetadata => { + /* If this call was cancelled (e.g. by the deadline) before + * metadata generation finished, we shouldn't do anything with + * it. */ + if (this.ended) { + this.trace( + 'Credentials metadata generation finished after call ended' + ); + return; + } + finalMetadata.merge(credsMetadata); + if (finalMetadata.get('authorization').length > 1) { + this.outputStatus( + { + code: Status.INTERNAL, + details: + '"authorization" metadata cannot have multiple values', + metadata: new Metadata(), + }, + 'PROCESSED' + ); + } + if ( + pickResult.subchannel!.getConnectivityState() !== + ConnectivityState.READY + ) { + this.trace( + 'Picked subchannel ' + + subchannelString + + ' has state ' + + ConnectivityState[ + pickResult.subchannel!.getConnectivityState() + ] + + ' after getting credentials metadata. Retrying pick' + ); + this.doPick(); + return; + } + + if (this.deadline !== Infinity) { + finalMetadata.set( + 'grpc-timeout', + getDeadlineTimeoutString(this.deadline) + ); + } + try { + this.child = pickResult + .subchannel!.getRealSubchannel() + .createCall(finalMetadata, this.host, this.methodName, { + onReceiveMetadata: metadata => { + this.trace('Received metadata'); + this.listener!.onReceiveMetadata(metadata); + }, + onReceiveMessage: message => { + this.trace('Received message'); + this.listener!.onReceiveMessage(message); + }, + onReceiveStatus: status => { + this.trace('Received status'); + if ( + status.rstCode === + http2.constants.NGHTTP2_REFUSED_STREAM + ) { + this.outputStatus(status, 'REFUSED'); + } else { + this.outputStatus(status, 'PROCESSED'); + } + }, + }); + this.childStartTime = new Date(); + } catch (error) { + this.trace( + 'Failed to start call on picked subchannel ' + + subchannelString + + ' with error ' + + (error as Error).message + ); + this.outputStatus( + { + code: Status.INTERNAL, + details: + 'Failed to start HTTP/2 stream with error ' + + (error as Error).message, + metadata: new Metadata(), + }, + 'NOT_STARTED' + ); + return; + } + pickResult.onCallStarted?.(); + this.onCallEnded = pickResult.onCallEnded; + this.trace( + 'Created child call [' + this.child.getCallNumber() + ']' + ); + if (this.readPending) { + this.child.startRead(); + } + if (this.pendingMessage) { + this.child.sendMessageWithContext( + this.pendingMessage.context, + this.pendingMessage.message + ); + } + if (this.pendingHalfClose) { + this.child.halfClose(); + } + }, + (error: Error & { code: number }) => { + // We assume the error code isn't 0 (Status.OK) + const { code, details } = restrictControlPlaneStatusCode( + typeof error.code === 'number' ? error.code : Status.UNKNOWN, + `Getting metadata from plugin failed with error: ${error.message}` + ); + this.outputStatus( + { + code: code, + details: details, + metadata: new Metadata(), + }, + 'PROCESSED' + ); + } + ); + break; + case PickResultType.DROP: + const { code, details } = restrictControlPlaneStatusCode( + pickResult.status!.code, + pickResult.status!.details + ); + setImmediate(() => { + this.outputStatus( + { code, details, metadata: pickResult.status!.metadata }, + 'DROP' + ); + }); + break; + case PickResultType.TRANSIENT_FAILURE: + if (this.metadata.getOptions().waitForReady) { + this.channel.queueCallForPick(this); + } else { + const { code, details } = restrictControlPlaneStatusCode( + pickResult.status!.code, + pickResult.status!.details + ); + setImmediate(() => { + this.outputStatus( + { code, details, metadata: pickResult.status!.metadata }, + 'PROCESSED' + ); + }); + } + break; + case PickResultType.QUEUE: + this.channel.queueCallForPick(this); + } + } + + cancelWithStatus(status: Status, details: string): void { + this.trace( + 'cancelWithStatus code: ' + status + ' details: "' + details + '"' + ); + this.child?.cancelWithStatus(status, details); + this.outputStatus( + { code: status, details: details, metadata: new Metadata() }, + 'PROCESSED' + ); + } + getPeer(): string { + return this.child?.getPeer() ?? this.channel.getTarget(); + } + start( + metadata: Metadata, + listener: LoadBalancingCallInterceptingListener + ): void { + this.trace('start called'); + this.listener = listener; + this.metadata = metadata; + this.doPick(); + } + sendMessageWithContext(context: MessageContext, message: Buffer): void { + this.trace('write() called with message of length ' + message.length); + if (this.child) { + this.child.sendMessageWithContext(context, message); + } else { + this.pendingMessage = { context, message }; + } + } + startRead(): void { + this.trace('startRead called'); + if (this.child) { + this.child.startRead(); + } else { + this.readPending = true; + } + } + halfClose(): void { + this.trace('halfClose called'); + if (this.child) { + this.child.halfClose(); + } else { + this.pendingHalfClose = true; + } + } + setCredentials(credentials: CallCredentials): void { + throw new Error('Method not implemented.'); + } + + getCallNumber(): number { + return this.callNumber; + } + + getAuthContext(): AuthContext | null { + if (this.child) { + return this.child.getAuthContext(); + } else { + return null; + } + } +} diff --git a/node_modules/@grpc/grpc-js/src/logging.ts b/node_modules/@grpc/grpc-js/src/logging.ts new file mode 100644 index 0000000..2279d3b --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/logging.ts @@ -0,0 +1,134 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { LogVerbosity } from './constants'; +import { pid } from 'process'; + +const clientVersion = require('../../package.json').version; + +const DEFAULT_LOGGER: Partial = { + error: (message?: any, ...optionalParams: any[]) => { + console.error('E ' + message, ...optionalParams); + }, + info: (message?: any, ...optionalParams: any[]) => { + console.error('I ' + message, ...optionalParams); + }, + debug: (message?: any, ...optionalParams: any[]) => { + console.error('D ' + message, ...optionalParams); + }, +}; + +let _logger: Partial = DEFAULT_LOGGER; +let _logVerbosity: LogVerbosity = LogVerbosity.ERROR; + +const verbosityString = + process.env.GRPC_NODE_VERBOSITY ?? process.env.GRPC_VERBOSITY ?? ''; + +switch (verbosityString.toUpperCase()) { + case 'DEBUG': + _logVerbosity = LogVerbosity.DEBUG; + break; + case 'INFO': + _logVerbosity = LogVerbosity.INFO; + break; + case 'ERROR': + _logVerbosity = LogVerbosity.ERROR; + break; + case 'NONE': + _logVerbosity = LogVerbosity.NONE; + break; + default: + // Ignore any other values +} + +export const getLogger = (): Partial => { + return _logger; +}; + +export const setLogger = (logger: Partial): void => { + _logger = logger; +}; + +export const setLoggerVerbosity = (verbosity: LogVerbosity): void => { + _logVerbosity = verbosity; +}; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export const log = (severity: LogVerbosity, ...args: any[]): void => { + let logFunction: typeof DEFAULT_LOGGER.error; + if (severity >= _logVerbosity) { + switch (severity) { + case LogVerbosity.DEBUG: + logFunction = _logger.debug; + break; + case LogVerbosity.INFO: + logFunction = _logger.info; + break; + case LogVerbosity.ERROR: + logFunction = _logger.error; + break; + } + /* Fall back to _logger.error when other methods are not available for + * compatiblity with older behavior that always logged to _logger.error */ + if (!logFunction) { + logFunction = _logger.error; + } + if (logFunction) { + logFunction.bind(_logger)(...args); + } + } +}; + +const tracersString = + process.env.GRPC_NODE_TRACE ?? process.env.GRPC_TRACE ?? ''; +const enabledTracers = new Set(); +const disabledTracers = new Set(); +for (const tracerName of tracersString.split(',')) { + if (tracerName.startsWith('-')) { + disabledTracers.add(tracerName.substring(1)); + } else { + enabledTracers.add(tracerName); + } +} +const allEnabled = enabledTracers.has('all'); + +export function trace( + severity: LogVerbosity, + tracer: string, + text: string +): void { + if (isTracerEnabled(tracer)) { + log( + severity, + new Date().toISOString() + + ' | v' + + clientVersion + + ' ' + + pid + + ' | ' + + tracer + + ' | ' + + text + ); + } +} + +export function isTracerEnabled(tracer: string): boolean { + return ( + !disabledTracers.has(tracer) && (allEnabled || enabledTracers.has(tracer)) + ); +} diff --git a/node_modules/@grpc/grpc-js/src/make-client.ts b/node_modules/@grpc/grpc-js/src/make-client.ts new file mode 100644 index 0000000..10d1e95 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/make-client.ts @@ -0,0 +1,238 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { ChannelCredentials } from './channel-credentials'; +import { ChannelOptions } from './channel-options'; +import { Client } from './client'; +import { UntypedServiceImplementation } from './server'; + +export interface Serialize { + (value: T): Buffer; +} + +export interface Deserialize { + (bytes: Buffer): T; +} + +export interface ClientMethodDefinition { + path: string; + requestStream: boolean; + responseStream: boolean; + requestSerialize: Serialize; + responseDeserialize: Deserialize; + originalName?: string; +} + +export interface ServerMethodDefinition { + path: string; + requestStream: boolean; + responseStream: boolean; + responseSerialize: Serialize; + requestDeserialize: Deserialize; + originalName?: string; +} + +export interface MethodDefinition + extends ClientMethodDefinition, + ServerMethodDefinition {} + +/* eslint-disable @typescript-eslint/no-explicit-any */ +export type ServiceDefinition< + ImplementationType = UntypedServiceImplementation +> = { + readonly [index in keyof ImplementationType]: MethodDefinition; +}; +/* eslint-enable @typescript-eslint/no-explicit-any */ + +export interface ProtobufTypeDefinition { + format: string; + type: object; + fileDescriptorProtos: Buffer[]; +} + +export interface PackageDefinition { + [index: string]: ServiceDefinition | ProtobufTypeDefinition; +} + +/** + * Map with short names for each of the requester maker functions. Used in + * makeClientConstructor + * @private + */ +const requesterFuncs = { + unary: Client.prototype.makeUnaryRequest, + server_stream: Client.prototype.makeServerStreamRequest, + client_stream: Client.prototype.makeClientStreamRequest, + bidi: Client.prototype.makeBidiStreamRequest, +}; + +export interface ServiceClient extends Client { + [methodName: string]: Function; +} + +export interface ServiceClientConstructor { + new ( + address: string, + credentials: ChannelCredentials, + options?: Partial + ): ServiceClient; + service: ServiceDefinition; + serviceName: string; +} + +/** + * Returns true, if given key is included in the blacklisted + * keys. + * @param key key for check, string. + */ +function isPrototypePolluted(key: string): boolean { + return ['__proto__', 'prototype', 'constructor'].includes(key); +} + +/** + * Creates a constructor for a client with the given methods, as specified in + * the methods argument. The resulting class will have an instance method for + * each method in the service, which is a partial application of one of the + * [Client]{@link grpc.Client} request methods, depending on `requestSerialize` + * and `responseSerialize`, with the `method`, `serialize`, and `deserialize` + * arguments predefined. + * @param methods An object mapping method names to + * method attributes + * @param serviceName The fully qualified name of the service + * @param classOptions An options object. + * @return New client constructor, which is a subclass of + * {@link grpc.Client}, and has the same arguments as that constructor. + */ +export function makeClientConstructor( + methods: ServiceDefinition, + serviceName: string, + classOptions?: {} +): ServiceClientConstructor { + if (!classOptions) { + classOptions = {}; + } + + class ServiceClientImpl extends Client implements ServiceClient { + static service: ServiceDefinition; + static serviceName: string; + [methodName: string]: Function; + } + + Object.keys(methods).forEach(name => { + if (isPrototypePolluted(name)) { + return; + } + const attrs = methods[name]; + let methodType: keyof typeof requesterFuncs; + // TODO(murgatroid99): Verify that we don't need this anymore + if (typeof name === 'string' && name.charAt(0) === '$') { + throw new Error('Method names cannot start with $'); + } + if (attrs.requestStream) { + if (attrs.responseStream) { + methodType = 'bidi'; + } else { + methodType = 'client_stream'; + } + } else { + if (attrs.responseStream) { + methodType = 'server_stream'; + } else { + methodType = 'unary'; + } + } + const serialize = attrs.requestSerialize; + const deserialize = attrs.responseDeserialize; + const methodFunc = partial( + requesterFuncs[methodType], + attrs.path, + serialize, + deserialize + ); + ServiceClientImpl.prototype[name] = methodFunc; + // Associate all provided attributes with the method + Object.assign(ServiceClientImpl.prototype[name], attrs); + if (attrs.originalName && !isPrototypePolluted(attrs.originalName)) { + ServiceClientImpl.prototype[attrs.originalName] = + ServiceClientImpl.prototype[name]; + } + }); + + ServiceClientImpl.service = methods; + ServiceClientImpl.serviceName = serviceName; + + return ServiceClientImpl; +} + +function partial( + fn: Function, + path: string, + serialize: Function, + deserialize: Function +): Function { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return function (this: any, ...args: any[]) { + return fn.call(this, path, serialize, deserialize, ...args); + }; +} + +export interface GrpcObject { + [index: string]: + | GrpcObject + | ServiceClientConstructor + | ProtobufTypeDefinition; +} + +function isProtobufTypeDefinition( + obj: ServiceDefinition | ProtobufTypeDefinition +): obj is ProtobufTypeDefinition { + return 'format' in obj; +} + +/** + * Load a gRPC package definition as a gRPC object hierarchy. + * @param packageDef The package definition object. + * @return The resulting gRPC object. + */ +export function loadPackageDefinition( + packageDef: PackageDefinition +): GrpcObject { + const result: GrpcObject = {}; + for (const serviceFqn in packageDef) { + if (Object.prototype.hasOwnProperty.call(packageDef, serviceFqn)) { + const service = packageDef[serviceFqn]; + const nameComponents = serviceFqn.split('.'); + if (nameComponents.some((comp: string) => isPrototypePolluted(comp))) { + continue; + } + const serviceName = nameComponents[nameComponents.length - 1]; + let current = result; + for (const packageName of nameComponents.slice(0, -1)) { + if (!current[packageName]) { + current[packageName] = {}; + } + current = current[packageName] as GrpcObject; + } + if (isProtobufTypeDefinition(service)) { + current[serviceName] = service; + } else { + current[serviceName] = makeClientConstructor(service, serviceName, {}); + } + } + } + return result; +} diff --git a/node_modules/@grpc/grpc-js/src/metadata.ts b/node_modules/@grpc/grpc-js/src/metadata.ts new file mode 100644 index 0000000..7ae68ba --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/metadata.ts @@ -0,0 +1,323 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import * as http2 from 'http2'; +import { log } from './logging'; +import { LogVerbosity } from './constants'; +import { getErrorMessage } from './error'; +const LEGAL_KEY_REGEX = /^[:0-9a-z_.-]+$/; +const LEGAL_NON_BINARY_VALUE_REGEX = /^[ -~]*$/; + +export type MetadataValue = string | Buffer; +export type MetadataObject = Map; + +function isLegalKey(key: string): boolean { + return LEGAL_KEY_REGEX.test(key); +} + +function isLegalNonBinaryValue(value: string): boolean { + return LEGAL_NON_BINARY_VALUE_REGEX.test(value); +} + +function isBinaryKey(key: string): boolean { + return key.endsWith('-bin'); +} + +function isCustomMetadata(key: string): boolean { + return !key.startsWith('grpc-'); +} + +function normalizeKey(key: string): string { + return key.toLowerCase(); +} + +function validate(key: string, value?: MetadataValue): void { + if (!isLegalKey(key)) { + throw new Error('Metadata key "' + key + '" contains illegal characters'); + } + + if (value !== null && value !== undefined) { + if (isBinaryKey(key)) { + if (!Buffer.isBuffer(value)) { + throw new Error("keys that end with '-bin' must have Buffer values"); + } + } else { + if (Buffer.isBuffer(value)) { + throw new Error( + "keys that don't end with '-bin' must have String values" + ); + } + if (!isLegalNonBinaryValue(value)) { + throw new Error( + 'Metadata string value "' + value + '" contains illegal characters' + ); + } + } + } +} + +export interface MetadataOptions { + /* Signal that the request is idempotent. Defaults to false */ + idempotentRequest?: boolean; + /* Signal that the call should not return UNAVAILABLE before it has + * started. Defaults to false. */ + waitForReady?: boolean; + /* Signal that the call is cacheable. GRPC is free to use GET verb. + * Defaults to false */ + cacheableRequest?: boolean; + /* Signal that the initial metadata should be corked. Defaults to false. */ + corked?: boolean; +} + +/** + * A class for storing metadata. Keys are normalized to lowercase ASCII. + */ +export class Metadata { + protected internalRepr: MetadataObject = new Map(); + private options: MetadataOptions; + private opaqueData: Map = new Map(); + + constructor(options: MetadataOptions = {}) { + this.options = options; + } + + /** + * Sets the given value for the given key by replacing any other values + * associated with that key. Normalizes the key. + * @param key The key to whose value should be set. + * @param value The value to set. Must be a buffer if and only + * if the normalized key ends with '-bin'. + */ + set(key: string, value: MetadataValue): void { + key = normalizeKey(key); + validate(key, value); + this.internalRepr.set(key, [value]); + } + + /** + * Adds the given value for the given key by appending to a list of previous + * values associated with that key. Normalizes the key. + * @param key The key for which a new value should be appended. + * @param value The value to add. Must be a buffer if and only + * if the normalized key ends with '-bin'. + */ + add(key: string, value: MetadataValue): void { + key = normalizeKey(key); + validate(key, value); + + const existingValue: MetadataValue[] | undefined = + this.internalRepr.get(key); + + if (existingValue === undefined) { + this.internalRepr.set(key, [value]); + } else { + existingValue.push(value); + } + } + + /** + * Removes the given key and any associated values. Normalizes the key. + * @param key The key whose values should be removed. + */ + remove(key: string): void { + key = normalizeKey(key); + // validate(key); + this.internalRepr.delete(key); + } + + /** + * Gets a list of all values associated with the key. Normalizes the key. + * @param key The key whose value should be retrieved. + * @return A list of values associated with the given key. + */ + get(key: string): MetadataValue[] { + key = normalizeKey(key); + // validate(key); + return this.internalRepr.get(key) || []; + } + + /** + * Gets a plain object mapping each key to the first value associated with it. + * This reflects the most common way that people will want to see metadata. + * @return A key/value mapping of the metadata. + */ + getMap(): { [key: string]: MetadataValue } { + const result: { [key: string]: MetadataValue } = {}; + + for (const [key, values] of this.internalRepr) { + if (values.length > 0) { + const v = values[0]; + result[key] = Buffer.isBuffer(v) ? Buffer.from(v) : v; + } + } + return result; + } + + /** + * Clones the metadata object. + * @return The newly cloned object. + */ + clone(): Metadata { + const newMetadata = new Metadata(this.options); + const newInternalRepr = newMetadata.internalRepr; + + for (const [key, value] of this.internalRepr) { + const clonedValue: MetadataValue[] = value.map(v => { + if (Buffer.isBuffer(v)) { + return Buffer.from(v); + } else { + return v; + } + }); + + newInternalRepr.set(key, clonedValue); + } + + return newMetadata; + } + + /** + * Merges all key-value pairs from a given Metadata object into this one. + * If both this object and the given object have values in the same key, + * values from the other Metadata object will be appended to this object's + * values. + * @param other A Metadata object. + */ + merge(other: Metadata): void { + for (const [key, values] of other.internalRepr) { + const mergedValue: MetadataValue[] = ( + this.internalRepr.get(key) || [] + ).concat(values); + + this.internalRepr.set(key, mergedValue); + } + } + + setOptions(options: MetadataOptions) { + this.options = options; + } + + getOptions(): MetadataOptions { + return this.options; + } + + /** + * Creates an OutgoingHttpHeaders object that can be used with the http2 API. + */ + toHttp2Headers(): http2.OutgoingHttpHeaders { + // NOTE: Node <8.9 formats http2 headers incorrectly. + const result: http2.OutgoingHttpHeaders = {}; + + for (const [key, values] of this.internalRepr) { + if (key.startsWith(':')) { + continue; + } + // We assume that the user's interaction with this object is limited to + // through its public API (i.e. keys and values are already validated). + result[key] = values.map(bufToString); + } + + return result; + } + + /** + * This modifies the behavior of JSON.stringify to show an object + * representation of the metadata map. + */ + toJSON() { + const result: { [key: string]: MetadataValue[] } = {}; + for (const [key, values] of this.internalRepr) { + result[key] = values; + } + return result; + } + + /** + * Attach additional data of any type to the metadata object, which will not + * be included when sending headers. The data can later be retrieved with + * `getOpaque`. Keys with the prefix `grpc` are reserved for use by this + * library. + * @param key + * @param value + */ + setOpaque(key: string, value: unknown) { + this.opaqueData.set(key, value); + } + + /** + * Retrieve data previously added with `setOpaque`. + * @param key + * @returns + */ + getOpaque(key: string) { + return this.opaqueData.get(key); + } + + /** + * Returns a new Metadata object based fields in a given IncomingHttpHeaders + * object. + * @param headers An IncomingHttpHeaders object. + */ + static fromHttp2Headers(headers: http2.IncomingHttpHeaders): Metadata { + const result = new Metadata(); + for (const key of Object.keys(headers)) { + // Reserved headers (beginning with `:`) are not valid keys. + if (key.charAt(0) === ':') { + continue; + } + + const values = headers[key]; + + try { + if (isBinaryKey(key)) { + if (Array.isArray(values)) { + values.forEach(value => { + result.add(key, Buffer.from(value, 'base64')); + }); + } else if (values !== undefined) { + if (isCustomMetadata(key)) { + values.split(',').forEach(v => { + result.add(key, Buffer.from(v.trim(), 'base64')); + }); + } else { + result.add(key, Buffer.from(values, 'base64')); + } + } + } else { + if (Array.isArray(values)) { + values.forEach(value => { + result.add(key, value); + }); + } else if (values !== undefined) { + result.add(key, values); + } + } + } catch (error) { + const message = `Failed to add metadata entry ${key}: ${values}. ${getErrorMessage( + error + )}. For more information see https://github.com/grpc/grpc-node/issues/1173`; + log(LogVerbosity.ERROR, message); + } + } + + return result; + } +} + +const bufToString = (val: string | Buffer): string => { + return Buffer.isBuffer(val) ? val.toString('base64') : val; +}; diff --git a/node_modules/@grpc/grpc-js/src/object-stream.ts b/node_modules/@grpc/grpc-js/src/object-stream.ts new file mode 100644 index 0000000..49ef1f3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/object-stream.ts @@ -0,0 +1,66 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { Readable, Writable } from 'stream'; +import { EmitterAugmentation1 } from './events'; + +/* eslint-disable @typescript-eslint/no-explicit-any */ + +export type WriteCallback = (error: Error | null | undefined) => void; + +export interface IntermediateObjectReadable extends Readable { + read(size?: number): any & T; +} + +export type ObjectReadable = { + read(size?: number): T; +} & EmitterAugmentation1<'data', T> & + IntermediateObjectReadable; + +export interface IntermediateObjectWritable extends Writable { + _write(chunk: any & T, encoding: string, callback: Function): void; + write(chunk: any & T, cb?: WriteCallback): boolean; + write(chunk: any & T, encoding?: any, cb?: WriteCallback): boolean; + setDefaultEncoding(encoding: string): this; + end(): ReturnType extends Writable ? this : void; + end( + chunk: any & T, + cb?: Function + ): ReturnType extends Writable ? this : void; + end( + chunk: any & T, + encoding?: any, + cb?: Function + ): ReturnType extends Writable ? this : void; +} + +export interface ObjectWritable extends IntermediateObjectWritable { + _write(chunk: T, encoding: string, callback: Function): void; + write(chunk: T, cb?: Function): boolean; + write(chunk: T, encoding?: any, cb?: Function): boolean; + setDefaultEncoding(encoding: string): this; + end(): ReturnType extends Writable ? this : void; + end( + chunk: T, + cb?: Function + ): ReturnType extends Writable ? this : void; + end( + chunk: T, + encoding?: any, + cb?: Function + ): ReturnType extends Writable ? this : void; +} diff --git a/node_modules/@grpc/grpc-js/src/orca.ts b/node_modules/@grpc/grpc-js/src/orca.ts new file mode 100644 index 0000000..2349073 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/orca.ts @@ -0,0 +1,349 @@ +/* + * Copyright 2025 gRPC authors. + * + * 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. + * + */ + +import { OrcaLoadReport, OrcaLoadReport__Output } from "./generated/xds/data/orca/v3/OrcaLoadReport"; + +import type { loadSync } from '@grpc/proto-loader'; +import { ProtoGrpcType as OrcaProtoGrpcType } from "./generated/orca"; +import { loadPackageDefinition } from "./make-client"; +import { OpenRcaServiceClient, OpenRcaServiceHandlers } from "./generated/xds/service/orca/v3/OpenRcaService"; +import { durationMessageToDuration, durationToMs, msToDuration } from "./duration"; +import { Server } from "./server"; +import { ChannelCredentials } from "./channel-credentials"; +import { Channel } from "./channel"; +import { OnCallEnded } from "./picker"; +import { DataProducer, Subchannel } from "./subchannel"; +import { BaseSubchannelWrapper, DataWatcher, SubchannelInterface } from "./subchannel-interface"; +import { ClientReadableStream, ServiceError } from "./call"; +import { Status } from "./constants"; +import { BackoffTimeout } from "./backoff-timeout"; +import { ConnectivityState } from "./connectivity-state"; + +const loadedOrcaProto: OrcaProtoGrpcType | null = null; +function loadOrcaProto(): OrcaProtoGrpcType { + if (loadedOrcaProto) { + return loadedOrcaProto; + } + /* The purpose of this complexity is to avoid loading @grpc/proto-loader at + * runtime for users who will not use/enable ORCA. */ + const loaderLoadSync = require('@grpc/proto-loader') + .loadSync as typeof loadSync; + const loadedProto = loaderLoadSync('xds/service/orca/v3/orca.proto', { + keepCase: true, + longs: String, + enums: String, + defaults: true, + oneofs: true, + includeDirs: [ + `${__dirname}/../../proto/xds`, + `${__dirname}/../../proto/protoc-gen-validate` + ], + }); + return loadPackageDefinition(loadedProto) as unknown as OrcaProtoGrpcType; +} + +/** + * ORCA metrics recorder for a single request + */ +export class PerRequestMetricRecorder { + private message: OrcaLoadReport = {}; + + /** + * Records a request cost metric measurement for the call. + * @param name + * @param value + */ + recordRequestCostMetric(name: string, value: number) { + if (!this.message.request_cost) { + this.message.request_cost = {}; + } + this.message.request_cost[name] = value; + } + + /** + * Records a request cost metric measurement for the call. + * @param name + * @param value + */ + recordUtilizationMetric(name: string, value: number) { + if (!this.message.utilization) { + this.message.utilization = {}; + } + this.message.utilization[name] = value; + } + + /** + * Records an opaque named metric measurement for the call. + * @param name + * @param value + */ + recordNamedMetric(name: string, value: number) { + if (!this.message.named_metrics) { + this.message.named_metrics = {}; + } + this.message.named_metrics[name] = value; + } + + /** + * Records the CPU utilization metric measurement for the call. + * @param value + */ + recordCPUUtilizationMetric(value: number) { + this.message.cpu_utilization = value; + } + + /** + * Records the memory utilization metric measurement for the call. + * @param value + */ + recordMemoryUtilizationMetric(value: number) { + this.message.mem_utilization = value; + } + + /** + * Records the memory utilization metric measurement for the call. + * @param value + */ + recordApplicationUtilizationMetric(value: number) { + this.message.application_utilization = value; + } + + /** + * Records the queries per second measurement. + * @param value + */ + recordQpsMetric(value: number) { + this.message.rps_fractional = value; + } + + /** + * Records the errors per second measurement. + * @param value + */ + recordEpsMetric(value: number) { + this.message.eps = value; + } + + serialize(): Buffer { + const orcaProto = loadOrcaProto(); + return orcaProto.xds.data.orca.v3.OrcaLoadReport.serialize(this.message); + } +} + +const DEFAULT_REPORT_INTERVAL_MS = 30_000; + +export class ServerMetricRecorder { + private message: OrcaLoadReport = {}; + + private serviceImplementation: OpenRcaServiceHandlers = { + StreamCoreMetrics: call => { + const reportInterval = call.request.report_interval ? + durationToMs(durationMessageToDuration(call.request.report_interval)) : + DEFAULT_REPORT_INTERVAL_MS; + const reportTimer = setInterval(() => { + call.write(this.message); + }, reportInterval); + call.on('cancelled', () => { + clearInterval(reportTimer); + }) + } + } + + putUtilizationMetric(name: string, value: number) { + if (!this.message.utilization) { + this.message.utilization = {}; + } + this.message.utilization[name] = value; + } + + setAllUtilizationMetrics(metrics: {[name: string]: number}) { + this.message.utilization = {...metrics}; + } + + deleteUtilizationMetric(name: string) { + delete this.message.utilization?.[name]; + } + + setCpuUtilizationMetric(value: number) { + this.message.cpu_utilization = value; + } + + deleteCpuUtilizationMetric() { + delete this.message.cpu_utilization; + } + + setApplicationUtilizationMetric(value: number) { + this.message.application_utilization = value; + } + + deleteApplicationUtilizationMetric() { + delete this.message.application_utilization; + } + + setQpsMetric(value: number) { + this.message.rps_fractional = value; + } + + deleteQpsMetric() { + delete this.message.rps_fractional; + } + + setEpsMetric(value: number) { + this.message.eps = value; + } + + deleteEpsMetric() { + delete this.message.eps; + } + + addToServer(server: Server) { + const serviceDefinition = loadOrcaProto().xds.service.orca.v3.OpenRcaService.service; + server.addService(serviceDefinition, this.serviceImplementation); + } +} + +export function createOrcaClient(channel: Channel): OpenRcaServiceClient { + const ClientClass = loadOrcaProto().xds.service.orca.v3.OpenRcaService; + return new ClientClass('unused', ChannelCredentials.createInsecure(), {channelOverride: channel}); +} + +export type MetricsListener = (loadReport: OrcaLoadReport__Output) => void; + +export const GRPC_METRICS_HEADER = 'endpoint-load-metrics-bin'; +const PARSED_LOAD_REPORT_KEY = 'grpc_orca_load_report'; + +/** + * Create an onCallEnded callback for use in a picker. + * @param listener The listener to handle metrics, whenever they are provided. + * @param previousOnCallEnded The previous onCallEnded callback to propagate + * to, if applicable. + * @returns + */ +export function createMetricsReader(listener: MetricsListener, previousOnCallEnded: OnCallEnded | null): OnCallEnded { + return (code, details, metadata) => { + let parsedLoadReport = metadata.getOpaque(PARSED_LOAD_REPORT_KEY) as (OrcaLoadReport__Output | undefined); + if (parsedLoadReport) { + listener(parsedLoadReport); + } else { + const serializedLoadReport = metadata.get(GRPC_METRICS_HEADER); + if (serializedLoadReport.length > 0) { + const orcaProto = loadOrcaProto(); + parsedLoadReport = orcaProto.xds.data.orca.v3.OrcaLoadReport.deserialize(serializedLoadReport[0] as Buffer); + listener(parsedLoadReport); + metadata.setOpaque(PARSED_LOAD_REPORT_KEY, parsedLoadReport); + } + } + if (previousOnCallEnded) { + previousOnCallEnded(code, details, metadata); + } + } +} + +const DATA_PRODUCER_KEY = 'orca_oob_metrics'; + +class OobMetricsDataWatcher implements DataWatcher { + private dataProducer: DataProducer | null = null; + constructor(private metricsListener: MetricsListener, private intervalMs: number) {} + setSubchannel(subchannel: Subchannel): void { + const producer = subchannel.getOrCreateDataProducer(DATA_PRODUCER_KEY, createOobMetricsDataProducer); + this.dataProducer = producer; + producer.addDataWatcher(this); + } + destroy(): void { + this.dataProducer?.removeDataWatcher(this); + } + getInterval(): number { + return this.intervalMs; + } + onMetricsUpdate(metrics: OrcaLoadReport__Output) { + this.metricsListener(metrics); + } +} + +class OobMetricsDataProducer implements DataProducer { + private dataWatchers: Set = new Set(); + private orcaSupported = true; + private client: OpenRcaServiceClient; + private metricsCall: ClientReadableStream | null = null; + private currentInterval = Infinity; + private backoffTimer = new BackoffTimeout(() => this.updateMetricsSubscription()); + private subchannelStateListener = () => this.updateMetricsSubscription(); + constructor(private subchannel: Subchannel) { + const channel = subchannel.getChannel(); + this.client = createOrcaClient(channel); + subchannel.addConnectivityStateListener(this.subchannelStateListener); + } + addDataWatcher(dataWatcher: OobMetricsDataWatcher): void { + this.dataWatchers.add(dataWatcher); + this.updateMetricsSubscription(); + } + removeDataWatcher(dataWatcher: OobMetricsDataWatcher): void { + this.dataWatchers.delete(dataWatcher); + if (this.dataWatchers.size === 0) { + this.subchannel.removeDataProducer(DATA_PRODUCER_KEY); + this.metricsCall?.cancel(); + this.metricsCall = null; + this.client.close(); + this.subchannel.removeConnectivityStateListener(this.subchannelStateListener); + } else { + this.updateMetricsSubscription(); + } + } + private updateMetricsSubscription() { + if (this.dataWatchers.size === 0 || !this.orcaSupported || this.subchannel.getConnectivityState() !== ConnectivityState.READY) { + return; + } + const newInterval = Math.min(...Array.from(this.dataWatchers).map(watcher => watcher.getInterval())); + if (!this.metricsCall || newInterval !== this.currentInterval) { + this.metricsCall?.cancel(); + this.currentInterval = newInterval; + const metricsCall = this.client.streamCoreMetrics({report_interval: msToDuration(newInterval)}); + this.metricsCall = metricsCall; + metricsCall.on('data', (report: OrcaLoadReport__Output) => { + this.dataWatchers.forEach(watcher => { + watcher.onMetricsUpdate(report); + }); + }); + metricsCall.on('error', (error: ServiceError) => { + this.metricsCall = null; + if (error.code === Status.UNIMPLEMENTED) { + this.orcaSupported = false; + return; + } + if (error.code === Status.CANCELLED) { + return; + } + this.backoffTimer.runOnce(); + }); + } + } +} + +export class OrcaOobMetricsSubchannelWrapper extends BaseSubchannelWrapper { + constructor(child: SubchannelInterface, metricsListener: MetricsListener, intervalMs: number) { + super(child); + this.addDataWatcher(new OobMetricsDataWatcher(metricsListener, intervalMs)); + } + + getWrappedSubchannel(): SubchannelInterface { + return this.child; + } +} + +function createOobMetricsDataProducer(subchannel: Subchannel) { + return new OobMetricsDataProducer(subchannel); +} diff --git a/node_modules/@grpc/grpc-js/src/picker.ts b/node_modules/@grpc/grpc-js/src/picker.ts new file mode 100644 index 0000000..fdf42fc --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/picker.ts @@ -0,0 +1,157 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { StatusObject } from './call-interface'; +import { Metadata } from './metadata'; +import { Status } from './constants'; +import { LoadBalancer } from './load-balancer'; +import { SubchannelInterface } from './subchannel-interface'; + +export enum PickResultType { + COMPLETE, + QUEUE, + TRANSIENT_FAILURE, + DROP, +} + +export type OnCallEnded = (statusCode: Status, details: string, metadata: Metadata) => void; + +export interface PickResult { + pickResultType: PickResultType; + /** + * The subchannel to use as the transport for the call. Only meaningful if + * `pickResultType` is COMPLETE. If null, indicates that the call should be + * dropped. + */ + subchannel: SubchannelInterface | null; + /** + * The status object to end the call with. Populated if and only if + * `pickResultType` is TRANSIENT_FAILURE. + */ + status: StatusObject | null; + onCallStarted: (() => void) | null; + onCallEnded: OnCallEnded | null; +} + +export interface CompletePickResult extends PickResult { + pickResultType: PickResultType.COMPLETE; + subchannel: SubchannelInterface | null; + status: null; + onCallStarted: (() => void) | null; + onCallEnded: OnCallEnded | null; +} + +export interface QueuePickResult extends PickResult { + pickResultType: PickResultType.QUEUE; + subchannel: null; + status: null; + onCallStarted: null; + onCallEnded: null; +} + +export interface TransientFailurePickResult extends PickResult { + pickResultType: PickResultType.TRANSIENT_FAILURE; + subchannel: null; + status: StatusObject; + onCallStarted: null; + onCallEnded: null; +} + +export interface DropCallPickResult extends PickResult { + pickResultType: PickResultType.DROP; + subchannel: null; + status: StatusObject; + onCallStarted: null; + onCallEnded: null; +} + +export interface PickArgs { + metadata: Metadata; + extraPickInfo: { [key: string]: string }; +} + +/** + * A proxy object representing the momentary state of a load balancer. Picks + * subchannels or returns other information based on that state. Should be + * replaced every time the load balancer changes state. + */ +export interface Picker { + pick(pickArgs: PickArgs): PickResult; +} + +/** + * A standard picker representing a load balancer in the TRANSIENT_FAILURE + * state. Always responds to every pick request with an UNAVAILABLE status. + */ +export class UnavailablePicker implements Picker { + private status: StatusObject; + constructor(status?: Partial) { + this.status = { + code: Status.UNAVAILABLE, + details: 'No connection established', + metadata: new Metadata(), + ...status, + }; + } + pick(pickArgs: PickArgs): TransientFailurePickResult { + return { + pickResultType: PickResultType.TRANSIENT_FAILURE, + subchannel: null, + status: this.status, + onCallStarted: null, + onCallEnded: null, + }; + } +} + +/** + * A standard picker representing a load balancer in the IDLE or CONNECTING + * state. Always responds to every pick request with a QUEUE pick result + * indicating that the pick should be tried again with the next `Picker`. Also + * reports back to the load balancer that a connection should be established + * once any pick is attempted. + * If the childPicker is provided, delegate to it instead of returning the + * hardcoded QUEUE pick result, but still calls exitIdle. + */ +export class QueuePicker { + private calledExitIdle = false; + // Constructed with a load balancer. Calls exitIdle on it the first time pick is called + constructor( + private loadBalancer: LoadBalancer, + private childPicker?: Picker + ) {} + + pick(pickArgs: PickArgs): PickResult { + if (!this.calledExitIdle) { + process.nextTick(() => { + this.loadBalancer.exitIdle(); + }); + this.calledExitIdle = true; + } + if (this.childPicker) { + return this.childPicker.pick(pickArgs); + } else { + return { + pickResultType: PickResultType.QUEUE, + subchannel: null, + status: null, + onCallStarted: null, + onCallEnded: null, + }; + } + } +} diff --git a/node_modules/@grpc/grpc-js/src/priority-queue.ts b/node_modules/@grpc/grpc-js/src/priority-queue.ts new file mode 100644 index 0000000..3ddf8f8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/priority-queue.ts @@ -0,0 +1,118 @@ +/* + * Copyright 2025 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +const top = 0; +const parent = (i: number) => Math.floor(i / 2); +const left = (i: number) => i * 2 + 1; +const right = (i: number) => i * 2 + 2; + +/** + * A generic priority queue implemented as an array-based binary heap. + * Adapted from https://stackoverflow.com/a/42919752/159388 + */ +export class PriorityQueue { + private readonly heap: T[] = []; + /** + * + * @param comparator Returns true if the first argument should precede the + * second in the queue. Defaults to `(a, b) => a > b` + */ + constructor(private readonly comparator = (a: T, b: T) => a > b) {} + + /** + * @returns The number of items currently in the queue + */ + size(): number { + return this.heap.length; + } + /** + * @returns True if there are no items in the queue, false otherwise + */ + isEmpty(): boolean { + return this.size() == 0; + } + /** + * Look at the front item that would be popped, without modifying the contents + * of the queue + * @returns The front item in the queue, or undefined if the queue is empty + */ + peek(): T | undefined { + return this.heap[top]; + } + /** + * Add the items to the queue + * @param values The items to add + * @returns The new size of the queue after adding the items + */ + push(...values: T[]): number { + values.forEach(value => { + this.heap.push(value); + this.siftUp(); + }); + return this.size(); + } + /** + * Remove the front item in the queue and return it + * @returns The front item in the queue, or undefined if the queue is empty + */ + pop(): T | undefined { + const poppedValue = this.peek(); + const bottom = this.size() - 1; + if (bottom > top) { + this.swap(top, bottom); + } + this.heap.pop(); + this.siftDown(); + return poppedValue; + } + /** + * Simultaneously remove the front item in the queue and add the provided + * item. + * @param value The item to add + * @returns The front item in the queue, or undefined if the queue is empty + */ + replace(value: T): T | undefined { + const replacedValue = this.peek(); + this.heap[top] = value; + this.siftDown(); + return replacedValue; + } + private greater(i: number, j: number): boolean { + return this.comparator(this.heap[i], this.heap[j]); + } + private swap(i: number, j: number): void { + [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]]; + } + private siftUp(): void { + let node = this.size() - 1; + while (node > top && this.greater(node, parent(node))) { + this.swap(node, parent(node)); + node = parent(node); + } + } + private siftDown(): void { + let node = top; + while ( + (left(node) < this.size() && this.greater(left(node), node)) || + (right(node) < this.size() && this.greater(right(node), node)) + ) { + let maxChild = (right(node) < this.size() && this.greater(right(node), left(node))) ? right(node) : left(node); + this.swap(node, maxChild); + node = maxChild; + } + } +} diff --git a/node_modules/@grpc/grpc-js/src/resolver-dns.ts b/node_modules/@grpc/grpc-js/src/resolver-dns.ts new file mode 100644 index 0000000..5245fe1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/resolver-dns.ts @@ -0,0 +1,449 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + */ + +import { + Resolver, + ResolverListener, + registerResolver, + registerDefaultScheme, +} from './resolver'; +import { promises as dns } from 'dns'; +import { extractAndSelectServiceConfig, ServiceConfig } from './service-config'; +import { Status } from './constants'; +import { StatusObject, StatusOr, statusOrFromError, statusOrFromValue } from './call-interface'; +import { Metadata } from './metadata'; +import * as logging from './logging'; +import { LogVerbosity } from './constants'; +import { Endpoint, TcpSubchannelAddress } from './subchannel-address'; +import { GrpcUri, uriToString, splitHostPort } from './uri-parser'; +import { isIPv6, isIPv4 } from 'net'; +import { ChannelOptions } from './channel-options'; +import { BackoffOptions, BackoffTimeout } from './backoff-timeout'; +import { GRPC_NODE_USE_ALTERNATIVE_RESOLVER } from './environment'; + +const TRACER_NAME = 'dns_resolver'; + +function trace(text: string): void { + logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text); +} + +/** + * The default TCP port to connect to if not explicitly specified in the target. + */ +export const DEFAULT_PORT = 443; + +const DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS = 30_000; + +/** + * Resolver implementation that handles DNS names and IP addresses. + */ +class DnsResolver implements Resolver { + private readonly ipResult: Endpoint[] | null; + private readonly dnsHostname: string | null; + private readonly port: number | null; + /** + * Minimum time between resolutions, measured as the time between starting + * successive resolution requests. Only applies to successful resolutions. + * Failures are handled by the backoff timer. + */ + private readonly minTimeBetweenResolutionsMs: number; + private pendingLookupPromise: Promise | null = null; + private pendingTxtPromise: Promise | null = null; + private latestLookupResult: StatusOr | null = null; + private latestServiceConfigResult: StatusOr | null = null; + private percentage: number; + private defaultResolutionError: StatusObject; + private backoff: BackoffTimeout; + private continueResolving = false; + private nextResolutionTimer: NodeJS.Timeout; + private isNextResolutionTimerRunning = false; + private isServiceConfigEnabled = true; + private returnedIpResult = false; + private alternativeResolver = new dns.Resolver(); + + constructor( + private target: GrpcUri, + private listener: ResolverListener, + channelOptions: ChannelOptions + ) { + trace('Resolver constructed for target ' + uriToString(target)); + if (target.authority) { + this.alternativeResolver.setServers([target.authority]); + } + const hostPort = splitHostPort(target.path); + if (hostPort === null) { + this.ipResult = null; + this.dnsHostname = null; + this.port = null; + } else { + if (isIPv4(hostPort.host) || isIPv6(hostPort.host)) { + this.ipResult = [ + { + addresses: [ + { + host: hostPort.host, + port: hostPort.port ?? DEFAULT_PORT, + }, + ], + }, + ]; + this.dnsHostname = null; + this.port = null; + } else { + this.ipResult = null; + this.dnsHostname = hostPort.host; + this.port = hostPort.port ?? DEFAULT_PORT; + } + } + this.percentage = Math.random() * 100; + + if (channelOptions['grpc.service_config_disable_resolution'] === 1) { + this.isServiceConfigEnabled = false; + } + + this.defaultResolutionError = { + code: Status.UNAVAILABLE, + details: `Name resolution failed for target ${uriToString(this.target)}`, + metadata: new Metadata(), + }; + + const backoffOptions: BackoffOptions = { + initialDelay: channelOptions['grpc.initial_reconnect_backoff_ms'], + maxDelay: channelOptions['grpc.max_reconnect_backoff_ms'], + }; + + this.backoff = new BackoffTimeout(() => { + if (this.continueResolving) { + this.startResolutionWithBackoff(); + } + }, backoffOptions); + this.backoff.unref(); + + this.minTimeBetweenResolutionsMs = + channelOptions['grpc.dns_min_time_between_resolutions_ms'] ?? + DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS; + this.nextResolutionTimer = setTimeout(() => {}, 0); + clearTimeout(this.nextResolutionTimer); + } + + /** + * If the target is an IP address, just provide that address as a result. + * Otherwise, initiate A, AAAA, and TXT lookups + */ + private startResolution() { + if (this.ipResult !== null) { + if (!this.returnedIpResult) { + trace('Returning IP address for target ' + uriToString(this.target)); + setImmediate(() => { + this.listener( + statusOrFromValue(this.ipResult!), + {}, + null, + '' + ) + }); + this.returnedIpResult = true; + } + this.backoff.stop(); + this.backoff.reset(); + this.stopNextResolutionTimer(); + return; + } + if (this.dnsHostname === null) { + trace('Failed to parse DNS address ' + uriToString(this.target)); + setImmediate(() => { + this.listener( + statusOrFromError({ + code: Status.UNAVAILABLE, + details: `Failed to parse DNS address ${uriToString(this.target)}` + }), + {}, + null, + '' + ); + }); + this.stopNextResolutionTimer(); + } else { + if (this.pendingLookupPromise !== null) { + return; + } + trace('Looking up DNS hostname ' + this.dnsHostname); + /* We clear out latestLookupResult here to ensure that it contains the + * latest result since the last time we started resolving. That way, the + * TXT resolution handler can use it, but only if it finishes second. We + * don't clear out any previous service config results because it's + * better to use a service config that's slightly out of date than to + * revert to an effectively blank one. */ + this.latestLookupResult = null; + const hostname: string = this.dnsHostname; + this.pendingLookupPromise = this.lookup(hostname); + this.pendingLookupPromise.then( + addressList => { + if (this.pendingLookupPromise === null) { + return; + } + this.pendingLookupPromise = null; + this.latestLookupResult = statusOrFromValue(addressList.map(address => ({ + addresses: [address], + }))); + const allAddressesString: string = + '[' + + addressList.map(addr => addr.host + ':' + addr.port).join(',') + + ']'; + trace( + 'Resolved addresses for target ' + + uriToString(this.target) + + ': ' + + allAddressesString + ); + /* If the TXT lookup has not yet finished, both of the last two + * arguments will be null, which is the equivalent of getting an + * empty TXT response. When the TXT lookup does finish, its handler + * can update the service config by using the same address list */ + const healthStatus = this.listener( + this.latestLookupResult, + {}, + this.latestServiceConfigResult, + '' + ); + this.handleHealthStatus(healthStatus); + }, + err => { + if (this.pendingLookupPromise === null) { + return; + } + trace( + 'Resolution error for target ' + + uriToString(this.target) + + ': ' + + (err as Error).message + ); + this.pendingLookupPromise = null; + this.stopNextResolutionTimer(); + this.listener( + statusOrFromError(this.defaultResolutionError), + {}, + this.latestServiceConfigResult, + '' + ) + } + ); + /* If there already is a still-pending TXT resolution, we can just use + * that result when it comes in */ + if (this.isServiceConfigEnabled && this.pendingTxtPromise === null) { + /* We handle the TXT query promise differently than the others because + * the name resolution attempt as a whole is a success even if the TXT + * lookup fails */ + this.pendingTxtPromise = this.resolveTxt(hostname); + this.pendingTxtPromise.then( + txtRecord => { + if (this.pendingTxtPromise === null) { + return; + } + this.pendingTxtPromise = null; + let serviceConfig: ServiceConfig | null; + try { + serviceConfig = extractAndSelectServiceConfig( + txtRecord, + this.percentage + ); + if (serviceConfig) { + this.latestServiceConfigResult = statusOrFromValue(serviceConfig); + } else { + this.latestServiceConfigResult = null; + } + } catch (err) { + this.latestServiceConfigResult = statusOrFromError({ + code: Status.UNAVAILABLE, + details: `Parsing service config failed with error ${ + (err as Error).message + }` + }); + } + if (this.latestLookupResult !== null) { + /* We rely here on the assumption that calling this function with + * identical parameters will be essentialy idempotent, and calling + * it with the same address list and a different service config + * should result in a fast and seamless switchover. */ + this.listener( + this.latestLookupResult, + {}, + this.latestServiceConfigResult, + '' + ); + } + }, + err => { + /* If TXT lookup fails we should do nothing, which means that we + * continue to use the result of the most recent successful lookup, + * or the default null config object if there has never been a + * successful lookup. We do not set the latestServiceConfigError + * here because that is specifically used for response validation + * errors. We still need to handle this error so that it does not + * bubble up as an unhandled promise rejection. */ + } + ); + } + } + } + + /** + * The ResolverListener returns a boolean indicating whether the LB policy + * accepted the resolution result. A false result on an otherwise successful + * resolution should be treated as a resolution failure. + * @param healthStatus + */ + private handleHealthStatus(healthStatus: boolean) { + if (healthStatus) { + this.backoff.stop(); + this.backoff.reset(); + } else { + this.continueResolving = true; + } + } + + private async lookup(hostname: string): Promise { + if (GRPC_NODE_USE_ALTERNATIVE_RESOLVER) { + trace('Using alternative DNS resolver.'); + + const records = await Promise.allSettled([ + this.alternativeResolver.resolve4(hostname), + this.alternativeResolver.resolve6(hostname), + ]); + + if (records.every(result => result.status === 'rejected')) { + throw new Error((records[0] as PromiseRejectedResult).reason); + } + + return records + .reduce((acc, result) => { + return result.status === 'fulfilled' + ? [...acc, ...result.value] + : acc; + }, []) + .map(addr => ({ + host: addr, + port: +this.port!, + })); + } + + /* We lookup both address families here and then split them up later + * because when looking up a single family, dns.lookup outputs an error + * if the name exists but there are no records for that family, and that + * error is indistinguishable from other kinds of errors */ + const addressList = await dns.lookup(hostname, { all: true }); + return addressList.map(addr => ({ host: addr.address, port: +this.port! })); + } + + private async resolveTxt(hostname: string): Promise { + if (GRPC_NODE_USE_ALTERNATIVE_RESOLVER) { + trace('Using alternative DNS resolver.'); + return this.alternativeResolver.resolveTxt(hostname); + } + + return dns.resolveTxt(hostname); + } + + private startNextResolutionTimer() { + clearTimeout(this.nextResolutionTimer); + this.nextResolutionTimer = setTimeout(() => { + this.stopNextResolutionTimer(); + if (this.continueResolving) { + this.startResolutionWithBackoff(); + } + }, this.minTimeBetweenResolutionsMs); + this.nextResolutionTimer.unref?.(); + this.isNextResolutionTimerRunning = true; + } + + private stopNextResolutionTimer() { + clearTimeout(this.nextResolutionTimer); + this.isNextResolutionTimerRunning = false; + } + + private startResolutionWithBackoff() { + if (this.pendingLookupPromise === null) { + this.continueResolving = false; + this.backoff.runOnce(); + this.startNextResolutionTimer(); + this.startResolution(); + } + } + + updateResolution() { + /* If there is a pending lookup, just let it finish. Otherwise, if the + * nextResolutionTimer or backoff timer is running, set the + * continueResolving flag to resolve when whichever of those timers + * fires. Otherwise, start resolving immediately. */ + if (this.pendingLookupPromise === null) { + if (this.isNextResolutionTimerRunning || this.backoff.isRunning()) { + if (this.isNextResolutionTimerRunning) { + trace( + 'resolution update delayed by "min time between resolutions" rate limit' + ); + } else { + trace( + 'resolution update delayed by backoff timer until ' + + this.backoff.getEndTime().toISOString() + ); + } + this.continueResolving = true; + } else { + this.startResolutionWithBackoff(); + } + } + } + + /** + * Reset the resolver to the same state it had when it was created. In-flight + * DNS requests cannot be cancelled, but they are discarded and their results + * will be ignored. + */ + destroy() { + this.continueResolving = false; + this.backoff.reset(); + this.backoff.stop(); + this.stopNextResolutionTimer(); + this.pendingLookupPromise = null; + this.pendingTxtPromise = null; + this.latestLookupResult = null; + this.latestServiceConfigResult = null; + this.returnedIpResult = false; + } + + /** + * Get the default authority for the given target. For IP targets, that is + * the IP address. For DNS targets, it is the hostname. + * @param target + */ + static getDefaultAuthority(target: GrpcUri): string { + return target.path; + } +} + +/** + * Set up the DNS resolver class by registering it as the handler for the + * "dns:" prefix and as the default resolver. + */ +export function setup(): void { + registerResolver('dns', DnsResolver); + registerDefaultScheme('dns'); +} + +export interface DnsUrl { + host: string; + port?: string; +} diff --git a/node_modules/@grpc/grpc-js/src/resolver-ip.ts b/node_modules/@grpc/grpc-js/src/resolver-ip.ts new file mode 100644 index 0000000..76e13e3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/resolver-ip.ts @@ -0,0 +1,124 @@ +/* + * Copyright 2021 gRPC authors. + * + * 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. + */ + +import { isIPv4, isIPv6 } from 'net'; +import { StatusObject, statusOrFromError, statusOrFromValue } from './call-interface'; +import { ChannelOptions } from './channel-options'; +import { LogVerbosity, Status } from './constants'; +import { Metadata } from './metadata'; +import { registerResolver, Resolver, ResolverListener } from './resolver'; +import { Endpoint, SubchannelAddress, subchannelAddressToString } from './subchannel-address'; +import { GrpcUri, splitHostPort, uriToString } from './uri-parser'; +import * as logging from './logging'; + +const TRACER_NAME = 'ip_resolver'; + +function trace(text: string): void { + logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text); +} + +const IPV4_SCHEME = 'ipv4'; +const IPV6_SCHEME = 'ipv6'; + +/** + * The default TCP port to connect to if not explicitly specified in the target. + */ +const DEFAULT_PORT = 443; + +class IpResolver implements Resolver { + private endpoints: Endpoint[] = []; + private error: StatusObject | null = null; + private hasReturnedResult = false; + constructor( + target: GrpcUri, + private listener: ResolverListener, + channelOptions: ChannelOptions + ) { + trace('Resolver constructed for target ' + uriToString(target)); + const addresses: SubchannelAddress[] = []; + if (!(target.scheme === IPV4_SCHEME || target.scheme === IPV6_SCHEME)) { + this.error = { + code: Status.UNAVAILABLE, + details: `Unrecognized scheme ${target.scheme} in IP resolver`, + metadata: new Metadata(), + }; + return; + } + const pathList = target.path.split(','); + for (const path of pathList) { + const hostPort = splitHostPort(path); + if (hostPort === null) { + this.error = { + code: Status.UNAVAILABLE, + details: `Failed to parse ${target.scheme} address ${path}`, + metadata: new Metadata(), + }; + return; + } + if ( + (target.scheme === IPV4_SCHEME && !isIPv4(hostPort.host)) || + (target.scheme === IPV6_SCHEME && !isIPv6(hostPort.host)) + ) { + this.error = { + code: Status.UNAVAILABLE, + details: `Failed to parse ${target.scheme} address ${path}`, + metadata: new Metadata(), + }; + return; + } + addresses.push({ + host: hostPort.host, + port: hostPort.port ?? DEFAULT_PORT, + }); + } + this.endpoints = addresses.map(address => ({ addresses: [address] })); + trace('Parsed ' + target.scheme + ' address list ' + addresses.map(subchannelAddressToString)); + } + updateResolution(): void { + if (!this.hasReturnedResult) { + this.hasReturnedResult = true; + process.nextTick(() => { + if (this.error) { + this.listener( + statusOrFromError(this.error), + {}, + null, + '' + ); + } else { + this.listener( + statusOrFromValue(this.endpoints), + {}, + null, + '' + ); + } + }); + } + } + destroy(): void { + this.hasReturnedResult = false; + } + + static getDefaultAuthority(target: GrpcUri): string { + return target.path.split(',')[0]; + } +} + +export function setup() { + registerResolver(IPV4_SCHEME, IpResolver); + registerResolver(IPV6_SCHEME, IpResolver); +} diff --git a/node_modules/@grpc/grpc-js/src/resolver-uds.ts b/node_modules/@grpc/grpc-js/src/resolver-uds.ts new file mode 100644 index 0000000..5ef8c07 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/resolver-uds.ts @@ -0,0 +1,63 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + */ + +import { Resolver, ResolverListener, registerResolver } from './resolver'; +import { Endpoint } from './subchannel-address'; +import { GrpcUri } from './uri-parser'; +import { ChannelOptions } from './channel-options'; +import { statusOrFromValue } from './call-interface'; + +class UdsResolver implements Resolver { + private hasReturnedResult = false; + private endpoints: Endpoint[] = []; + constructor( + target: GrpcUri, + private listener: ResolverListener, + channelOptions: ChannelOptions + ) { + let path: string; + if (target.authority === '') { + path = '/' + target.path; + } else { + path = target.path; + } + this.endpoints = [{ addresses: [{ path }] }]; + } + updateResolution(): void { + if (!this.hasReturnedResult) { + this.hasReturnedResult = true; + process.nextTick( + this.listener, + statusOrFromValue(this.endpoints), + {}, + null, + '' + ); + } + } + + destroy() { + this.hasReturnedResult = false; + } + + static getDefaultAuthority(target: GrpcUri): string { + return 'localhost'; + } +} + +export function setup() { + registerResolver('unix', UdsResolver); +} diff --git a/node_modules/@grpc/grpc-js/src/resolver.ts b/node_modules/@grpc/grpc-js/src/resolver.ts new file mode 100644 index 0000000..28cc987 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/resolver.ts @@ -0,0 +1,176 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { MethodConfig, ServiceConfig } from './service-config'; +import { StatusOr } from './call-interface'; +import { Endpoint } from './subchannel-address'; +import { GrpcUri, uriToString } from './uri-parser'; +import { ChannelOptions } from './channel-options'; +import { Metadata } from './metadata'; +import { Status } from './constants'; +import { Filter, FilterFactory } from './filter'; + +export const CHANNEL_ARGS_CONFIG_SELECTOR_KEY = 'grpc.internal.config_selector'; + +export interface CallConfig { + methodConfig: MethodConfig; + onCommitted?: () => void; + pickInformation: { [key: string]: string }; + status: Status; + dynamicFilterFactories: FilterFactory[]; +} + +/** + * Selects a configuration for a method given the name and metadata. Defined in + * https://github.com/grpc/proposal/blob/master/A31-xds-timeout-support-and-config-selector.md#new-functionality-in-grpc + */ +export interface ConfigSelector { + invoke(methodName: string, metadata: Metadata, channelId: number): CallConfig; + unref(): void; +} + +export interface ResolverListener { + /** + * Called whenever the resolver has new name resolution results or an error to + * report. + * @param endpointList The list of endpoints, or an error if resolution failed + * @param attributes Arbitrary key/value pairs to pass along to load balancing + * policies + * @param serviceConfig The service service config for the endpoint list, or an + * error if the retrieved service config is invalid, or null if there is no + * service config + * @param resolutionNote Provides additional context to RPC failure status + * messages generated by the load balancing policy. + * @returns Whether or not the load balancing policy accepted the result. + */ + ( + endpointList: StatusOr, + attributes: { [key: string]: unknown }, + serviceConfig: StatusOr | null, + resolutionNote: string + ): boolean; +} +/** + * A resolver class that handles one or more of the name syntax schemes defined + * in the [gRPC Name Resolution document](https://github.com/grpc/grpc/blob/master/doc/naming.md) + */ +export interface Resolver { + /** + * Indicates that the caller wants new name resolution data. Calling this + * function may eventually result in calling one of the `ResolverListener` + * functions, but that is not guaranteed. Those functions will never be + * called synchronously with the constructor or updateResolution. + */ + updateResolution(): void; + + /** + * Discard all resources owned by the resolver. A later call to + * `updateResolution` should reinitialize those resources. No + * `ResolverListener` callbacks should be called after `destroy` is called + * until `updateResolution` is called again. + */ + destroy(): void; +} + +export interface ResolverConstructor { + new ( + target: GrpcUri, + listener: ResolverListener, + channelOptions: ChannelOptions + ): Resolver; + /** + * Get the default authority for a target. This loosely corresponds to that + * target's hostname. Throws an error if this resolver class cannot parse the + * `target`. + * @param target + */ + getDefaultAuthority(target: GrpcUri): string; +} + +const registeredResolvers: { [scheme: string]: ResolverConstructor } = {}; +let defaultScheme: string | null = null; + +/** + * Register a resolver class to handle target names prefixed with the `prefix` + * string. This prefix should correspond to a URI scheme name listed in the + * [gRPC Name Resolution document](https://github.com/grpc/grpc/blob/master/doc/naming.md) + * @param prefix + * @param resolverClass + */ +export function registerResolver( + scheme: string, + resolverClass: ResolverConstructor +) { + registeredResolvers[scheme] = resolverClass; +} + +/** + * Register a default resolver to handle target names that do not start with + * any registered prefix. + * @param resolverClass + */ +export function registerDefaultScheme(scheme: string) { + defaultScheme = scheme; +} + +/** + * Create a name resolver for the specified target, if possible. Throws an + * error if no such name resolver can be created. + * @param target + * @param listener + */ +export function createResolver( + target: GrpcUri, + listener: ResolverListener, + options: ChannelOptions +): Resolver { + if (target.scheme !== undefined && target.scheme in registeredResolvers) { + return new registeredResolvers[target.scheme](target, listener, options); + } else { + throw new Error( + `No resolver could be created for target ${uriToString(target)}` + ); + } +} + +/** + * Get the default authority for the specified target, if possible. Throws an + * error if no registered name resolver can parse that target string. + * @param target + */ +export function getDefaultAuthority(target: GrpcUri): string { + if (target.scheme !== undefined && target.scheme in registeredResolvers) { + return registeredResolvers[target.scheme].getDefaultAuthority(target); + } else { + throw new Error(`Invalid target ${uriToString(target)}`); + } +} + +export function mapUriDefaultScheme(target: GrpcUri): GrpcUri | null { + if (target.scheme === undefined || !(target.scheme in registeredResolvers)) { + if (defaultScheme !== null) { + return { + scheme: defaultScheme, + authority: undefined, + path: uriToString(target), + }; + } else { + return null; + } + } + return target; +} diff --git a/node_modules/@grpc/grpc-js/src/resolving-call.ts b/node_modules/@grpc/grpc-js/src/resolving-call.ts new file mode 100644 index 0000000..d328978 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/resolving-call.ts @@ -0,0 +1,379 @@ +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ + +import { CallCredentials } from './call-credentials'; +import { + Call, + CallStreamOptions, + DeadlineInfoProvider, + InterceptingListener, + MessageContext, + StatusObject, +} from './call-interface'; +import { LogVerbosity, Propagate, Status } from './constants'; +import { + Deadline, + deadlineToString, + formatDateDifference, + getRelativeTimeout, + minDeadline, +} from './deadline'; +import { FilterStack, FilterStackFactory } from './filter-stack'; +import { InternalChannel } from './internal-channel'; +import { Metadata } from './metadata'; +import * as logging from './logging'; +import { restrictControlPlaneStatusCode } from './control-plane-status'; +import { AuthContext } from './auth-context'; + +const TRACER_NAME = 'resolving_call'; + +export class ResolvingCall implements Call { + private child: (Call & DeadlineInfoProvider) | null = null; + private readPending = false; + private pendingMessage: { context: MessageContext; message: Buffer } | null = + null; + private pendingHalfClose = false; + private ended = false; + private readFilterPending = false; + private writeFilterPending = false; + private pendingChildStatus: StatusObject | null = null; + private metadata: Metadata | null = null; + private listener: InterceptingListener | null = null; + private deadline: Deadline; + private host: string; + private statusWatchers: ((status: StatusObject) => void)[] = []; + private deadlineTimer: NodeJS.Timeout = setTimeout(() => {}, 0); + private filterStack: FilterStack | null = null; + + private deadlineStartTime: Date | null = null; + private configReceivedTime: Date | null = null; + private childStartTime: Date | null = null; + + /** + * Credentials configured for this specific call. Does not include + * call credentials associated with the channel credentials used to create + * the channel. + */ + private credentials: CallCredentials = CallCredentials.createEmpty(); + + constructor( + private readonly channel: InternalChannel, + private readonly method: string, + options: CallStreamOptions, + private readonly filterStackFactory: FilterStackFactory, + private callNumber: number + ) { + this.deadline = options.deadline; + this.host = options.host; + if (options.parentCall) { + if (options.flags & Propagate.CANCELLATION) { + options.parentCall.on('cancelled', () => { + this.cancelWithStatus(Status.CANCELLED, 'Cancelled by parent call'); + }); + } + if (options.flags & Propagate.DEADLINE) { + this.trace( + 'Propagating deadline from parent: ' + + options.parentCall.getDeadline() + ); + this.deadline = minDeadline( + this.deadline, + options.parentCall.getDeadline() + ); + } + } + this.trace('Created'); + this.runDeadlineTimer(); + } + + private trace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + TRACER_NAME, + '[' + this.callNumber + '] ' + text + ); + } + + private runDeadlineTimer() { + clearTimeout(this.deadlineTimer); + this.deadlineStartTime = new Date(); + this.trace('Deadline: ' + deadlineToString(this.deadline)); + const timeout = getRelativeTimeout(this.deadline); + if (timeout !== Infinity) { + this.trace('Deadline will be reached in ' + timeout + 'ms'); + const handleDeadline = () => { + if (!this.deadlineStartTime) { + this.cancelWithStatus(Status.DEADLINE_EXCEEDED, 'Deadline exceeded'); + return; + } + const deadlineInfo: string[] = []; + const deadlineEndTime = new Date(); + deadlineInfo.push(`Deadline exceeded after ${formatDateDifference(this.deadlineStartTime, deadlineEndTime)}`); + if (this.configReceivedTime) { + if (this.configReceivedTime > this.deadlineStartTime) { + deadlineInfo.push(`name resolution: ${formatDateDifference(this.deadlineStartTime, this.configReceivedTime)}`); + } + if (this.childStartTime) { + if (this.childStartTime > this.configReceivedTime) { + deadlineInfo.push(`metadata filters: ${formatDateDifference(this.configReceivedTime, this.childStartTime)}`); + } + } else { + deadlineInfo.push('waiting for metadata filters'); + } + } else { + deadlineInfo.push('waiting for name resolution'); + } + if (this.child) { + deadlineInfo.push(...this.child.getDeadlineInfo()); + } + this.cancelWithStatus(Status.DEADLINE_EXCEEDED, deadlineInfo.join(',')); + }; + if (timeout <= 0) { + process.nextTick(handleDeadline); + } else { + this.deadlineTimer = setTimeout(handleDeadline, timeout); + } + } + } + + private outputStatus(status: StatusObject) { + if (!this.ended) { + this.ended = true; + if (!this.filterStack) { + this.filterStack = this.filterStackFactory.createFilter(); + } + clearTimeout(this.deadlineTimer); + const filteredStatus = this.filterStack.receiveTrailers(status); + this.trace( + 'ended with status: code=' + + filteredStatus.code + + ' details="' + + filteredStatus.details + + '"' + ); + this.statusWatchers.forEach(watcher => watcher(filteredStatus)); + process.nextTick(() => { + this.listener?.onReceiveStatus(filteredStatus); + }); + } + } + + private sendMessageOnChild(context: MessageContext, message: Buffer): void { + if (!this.child) { + throw new Error('sendMessageonChild called with child not populated'); + } + const child = this.child; + this.writeFilterPending = true; + this.filterStack!.sendMessage( + Promise.resolve({ message: message, flags: context.flags }) + ).then( + filteredMessage => { + this.writeFilterPending = false; + child.sendMessageWithContext(context, filteredMessage.message); + if (this.pendingHalfClose) { + child.halfClose(); + } + }, + (status: StatusObject) => { + this.cancelWithStatus(status.code, status.details); + } + ); + } + + getConfig(): void { + if (this.ended) { + return; + } + if (!this.metadata || !this.listener) { + throw new Error('getConfig called before start'); + } + const configResult = this.channel.getConfig(this.method, this.metadata); + if (configResult.type === 'NONE') { + this.channel.queueCallForConfig(this); + return; + } else if (configResult.type === 'ERROR') { + if (this.metadata.getOptions().waitForReady) { + this.channel.queueCallForConfig(this); + } else { + this.outputStatus(configResult.error); + } + return; + } + // configResult.type === 'SUCCESS' + this.configReceivedTime = new Date(); + const config = configResult.config; + if (config.status !== Status.OK) { + const { code, details } = restrictControlPlaneStatusCode( + config.status, + 'Failed to route call to method ' + this.method + ); + this.outputStatus({ + code: code, + details: details, + metadata: new Metadata(), + }); + return; + } + + if (config.methodConfig.timeout) { + const configDeadline = new Date(); + configDeadline.setSeconds( + configDeadline.getSeconds() + config.methodConfig.timeout.seconds + ); + configDeadline.setMilliseconds( + configDeadline.getMilliseconds() + + config.methodConfig.timeout.nanos / 1_000_000 + ); + this.deadline = minDeadline(this.deadline, configDeadline); + this.runDeadlineTimer(); + } + + this.filterStackFactory.push(config.dynamicFilterFactories); + this.filterStack = this.filterStackFactory.createFilter(); + this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then( + filteredMetadata => { + this.child = this.channel.createRetryingCall( + config, + this.method, + this.host, + this.credentials, + this.deadline + ); + this.trace('Created child [' + this.child.getCallNumber() + ']'); + this.childStartTime = new Date(); + this.child.start(filteredMetadata, { + onReceiveMetadata: metadata => { + this.trace('Received metadata'); + this.listener!.onReceiveMetadata( + this.filterStack!.receiveMetadata(metadata) + ); + }, + onReceiveMessage: message => { + this.trace('Received message'); + this.readFilterPending = true; + this.filterStack!.receiveMessage(message).then( + filteredMesssage => { + this.trace('Finished filtering received message'); + this.readFilterPending = false; + this.listener!.onReceiveMessage(filteredMesssage); + if (this.pendingChildStatus) { + this.outputStatus(this.pendingChildStatus); + } + }, + (status: StatusObject) => { + this.cancelWithStatus(status.code, status.details); + } + ); + }, + onReceiveStatus: status => { + this.trace('Received status'); + if (this.readFilterPending) { + this.pendingChildStatus = status; + } else { + this.outputStatus(status); + } + }, + }); + if (this.readPending) { + this.child.startRead(); + } + if (this.pendingMessage) { + this.sendMessageOnChild( + this.pendingMessage.context, + this.pendingMessage.message + ); + } else if (this.pendingHalfClose) { + this.child.halfClose(); + } + }, + (status: StatusObject) => { + this.outputStatus(status); + } + ); + } + + reportResolverError(status: StatusObject) { + if (this.metadata?.getOptions().waitForReady) { + this.channel.queueCallForConfig(this); + } else { + this.outputStatus(status); + } + } + cancelWithStatus(status: Status, details: string): void { + this.trace( + 'cancelWithStatus code: ' + status + ' details: "' + details + '"' + ); + this.child?.cancelWithStatus(status, details); + this.outputStatus({ + code: status, + details: details, + metadata: new Metadata(), + }); + } + getPeer(): string { + return this.child?.getPeer() ?? this.channel.getTarget(); + } + start(metadata: Metadata, listener: InterceptingListener): void { + this.trace('start called'); + this.metadata = metadata.clone(); + this.listener = listener; + this.getConfig(); + } + sendMessageWithContext(context: MessageContext, message: Buffer): void { + this.trace('write() called with message of length ' + message.length); + if (this.child) { + this.sendMessageOnChild(context, message); + } else { + this.pendingMessage = { context, message }; + } + } + startRead(): void { + this.trace('startRead called'); + if (this.child) { + this.child.startRead(); + } else { + this.readPending = true; + } + } + halfClose(): void { + this.trace('halfClose called'); + if (this.child && !this.writeFilterPending) { + this.child.halfClose(); + } else { + this.pendingHalfClose = true; + } + } + setCredentials(credentials: CallCredentials): void { + this.credentials = credentials; + } + + addStatusWatcher(watcher: (status: StatusObject) => void) { + this.statusWatchers.push(watcher); + } + + getCallNumber(): number { + return this.callNumber; + } + + getAuthContext(): AuthContext | null { + if (this.child) { + return this.child.getAuthContext(); + } else { + return null; + } + } +} diff --git a/node_modules/@grpc/grpc-js/src/resolving-load-balancer.ts b/node_modules/@grpc/grpc-js/src/resolving-load-balancer.ts new file mode 100644 index 0000000..c117e94 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/resolving-load-balancer.ts @@ -0,0 +1,407 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { + ChannelControlHelper, + LoadBalancer, + TypedLoadBalancingConfig, + selectLbConfigFromList, +} from './load-balancer'; +import { + MethodConfig, + ServiceConfig, + validateServiceConfig, +} from './service-config'; +import { ConnectivityState } from './connectivity-state'; +import { CHANNEL_ARGS_CONFIG_SELECTOR_KEY, ConfigSelector, createResolver, Resolver } from './resolver'; +import { Picker, UnavailablePicker, QueuePicker } from './picker'; +import { BackoffOptions, BackoffTimeout } from './backoff-timeout'; +import { Status } from './constants'; +import { StatusObject, StatusOr } from './call-interface'; +import { Metadata } from './metadata'; +import * as logging from './logging'; +import { LogVerbosity } from './constants'; +import { Endpoint } from './subchannel-address'; +import { GrpcUri, uriToString } from './uri-parser'; +import { ChildLoadBalancerHandler } from './load-balancer-child-handler'; +import { ChannelOptions } from './channel-options'; + +const TRACER_NAME = 'resolving_load_balancer'; + +function trace(text: string): void { + logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text); +} + +type NameMatchLevel = 'EMPTY' | 'SERVICE' | 'SERVICE_AND_METHOD'; + +/** + * Name match levels in order from most to least specific. This is the order in + * which searches will be performed. + */ +const NAME_MATCH_LEVEL_ORDER: NameMatchLevel[] = [ + 'SERVICE_AND_METHOD', + 'SERVICE', + 'EMPTY', +]; + +function hasMatchingName( + service: string, + method: string, + methodConfig: MethodConfig, + matchLevel: NameMatchLevel +): boolean { + for (const name of methodConfig.name) { + switch (matchLevel) { + case 'EMPTY': + if (!name.service && !name.method) { + return true; + } + break; + case 'SERVICE': + if (name.service === service && !name.method) { + return true; + } + break; + case 'SERVICE_AND_METHOD': + if (name.service === service && name.method === method) { + return true; + } + } + } + return false; +} + +function findMatchingConfig( + service: string, + method: string, + methodConfigs: MethodConfig[], + matchLevel: NameMatchLevel +): MethodConfig | null { + for (const config of methodConfigs) { + if (hasMatchingName(service, method, config, matchLevel)) { + return config; + } + } + return null; +} + +function getDefaultConfigSelector( + serviceConfig: ServiceConfig | null +): ConfigSelector { + return { + invoke( + methodName: string, + metadata: Metadata + ) { + const splitName = methodName.split('/').filter(x => x.length > 0); + const service = splitName[0] ?? ''; + const method = splitName[1] ?? ''; + if (serviceConfig && serviceConfig.methodConfig) { + /* Check for the following in order, and return the first method + * config that matches: + * 1. A name that exactly matches the service and method + * 2. A name with no method set that matches the service + * 3. An empty name + */ + for (const matchLevel of NAME_MATCH_LEVEL_ORDER) { + const matchingConfig = findMatchingConfig( + service, + method, + serviceConfig.methodConfig, + matchLevel + ); + if (matchingConfig) { + return { + methodConfig: matchingConfig, + pickInformation: {}, + status: Status.OK, + dynamicFilterFactories: [], + }; + } + } + } + return { + methodConfig: { name: [] }, + pickInformation: {}, + status: Status.OK, + dynamicFilterFactories: [], + }; + }, + unref() {} + }; +} + +export interface ResolutionCallback { + (serviceConfig: ServiceConfig, configSelector: ConfigSelector): void; +} + +export interface ResolutionFailureCallback { + (status: StatusObject): void; +} + +export class ResolvingLoadBalancer implements LoadBalancer { + /** + * The resolver class constructed for the target address. + */ + private readonly innerResolver: Resolver; + + private readonly childLoadBalancer: ChildLoadBalancerHandler; + private latestChildState: ConnectivityState = ConnectivityState.IDLE; + private latestChildPicker: Picker = new QueuePicker(this); + private latestChildErrorMessage: string | null = null; + /** + * This resolving load balancer's current connectivity state. + */ + private currentState: ConnectivityState = ConnectivityState.IDLE; + private readonly defaultServiceConfig: ServiceConfig; + /** + * The service config object from the last successful resolution, if + * available. A value of null indicates that we have not yet received a valid + * service config from the resolver. + */ + private previousServiceConfig: ServiceConfig | null = null; + + /** + * The backoff timer for handling name resolution failures. + */ + private readonly backoffTimeout: BackoffTimeout; + + /** + * Indicates whether we should attempt to resolve again after the backoff + * timer runs out. + */ + private continueResolving = false; + + /** + * Wrapper class that behaves like a `LoadBalancer` and also handles name + * resolution internally. + * @param target The address of the backend to connect to. + * @param channelControlHelper `ChannelControlHelper` instance provided by + * this load balancer's owner. + * @param defaultServiceConfig The default service configuration to be used + * if none is provided by the name resolver. A `null` value indicates + * that the default behavior should be the default unconfigured behavior. + * In practice, that means using the "pick first" load balancer + * implmentation + */ + constructor( + private readonly target: GrpcUri, + private readonly channelControlHelper: ChannelControlHelper, + private readonly channelOptions: ChannelOptions, + private readonly onSuccessfulResolution: ResolutionCallback, + private readonly onFailedResolution: ResolutionFailureCallback + ) { + if (channelOptions['grpc.service_config']) { + this.defaultServiceConfig = validateServiceConfig( + JSON.parse(channelOptions['grpc.service_config']!) + ); + } else { + this.defaultServiceConfig = { + loadBalancingConfig: [], + methodConfig: [], + }; + } + + this.updateState(ConnectivityState.IDLE, new QueuePicker(this), null); + this.childLoadBalancer = new ChildLoadBalancerHandler( + { + createSubchannel: + channelControlHelper.createSubchannel.bind(channelControlHelper), + requestReresolution: () => { + /* If the backoffTimeout is running, we're still backing off from + * making resolve requests, so we shouldn't make another one here. + * In that case, the backoff timer callback will call + * updateResolution */ + if (this.backoffTimeout.isRunning()) { + trace( + 'requestReresolution delayed by backoff timer until ' + + this.backoffTimeout.getEndTime().toISOString() + ); + this.continueResolving = true; + } else { + this.updateResolution(); + } + }, + updateState: (newState: ConnectivityState, picker: Picker, errorMessage: string | null) => { + this.latestChildState = newState; + this.latestChildPicker = picker; + this.latestChildErrorMessage = errorMessage; + this.updateState(newState, picker, errorMessage); + }, + addChannelzChild: + channelControlHelper.addChannelzChild.bind(channelControlHelper), + removeChannelzChild: + channelControlHelper.removeChannelzChild.bind(channelControlHelper), + } + ); + this.innerResolver = createResolver( + target, + this.handleResolverResult.bind(this), + channelOptions + ); + const backoffOptions: BackoffOptions = { + initialDelay: channelOptions['grpc.initial_reconnect_backoff_ms'], + maxDelay: channelOptions['grpc.max_reconnect_backoff_ms'], + }; + this.backoffTimeout = new BackoffTimeout(() => { + if (this.continueResolving) { + this.updateResolution(); + this.continueResolving = false; + } else { + this.updateState(this.latestChildState, this.latestChildPicker, this.latestChildErrorMessage); + } + }, backoffOptions); + this.backoffTimeout.unref(); + } + + private handleResolverResult( + endpointList: StatusOr, + attributes: { [key: string]: unknown }, + serviceConfig: StatusOr | null, + resolutionNote: string + ): boolean { + this.backoffTimeout.stop(); + this.backoffTimeout.reset(); + let resultAccepted = true; + let workingServiceConfig: ServiceConfig | null = null; + if (serviceConfig === null) { + workingServiceConfig = this.defaultServiceConfig; + } else if (serviceConfig.ok) { + workingServiceConfig = serviceConfig.value; + } else { + if (this.previousServiceConfig !== null) { + workingServiceConfig = this.previousServiceConfig; + } else { + resultAccepted = false; + this.handleResolutionFailure(serviceConfig.error); + } + } + + if (workingServiceConfig !== null) { + const workingConfigList = + workingServiceConfig?.loadBalancingConfig ?? []; + const loadBalancingConfig = selectLbConfigFromList( + workingConfigList, + true + ); + if (loadBalancingConfig === null) { + resultAccepted = false; + this.handleResolutionFailure({ + code: Status.UNAVAILABLE, + details: + 'All load balancer options in service config are not compatible', + metadata: new Metadata(), + }); + } else { + resultAccepted = this.childLoadBalancer.updateAddressList( + endpointList, + loadBalancingConfig, + {...this.channelOptions, ...attributes}, + resolutionNote + ); + } + } + if (resultAccepted) { + this.onSuccessfulResolution( + workingServiceConfig!, + attributes[CHANNEL_ARGS_CONFIG_SELECTOR_KEY] as ConfigSelector ?? getDefaultConfigSelector(workingServiceConfig!) + ); + } + return resultAccepted; + } + + private updateResolution() { + this.innerResolver.updateResolution(); + if (this.currentState === ConnectivityState.IDLE) { + /* this.latestChildPicker is initialized as new QueuePicker(this), which + * is an appropriate value here if the child LB policy is unset. + * Otherwise, we want to delegate to the child here, in case that + * triggers something. */ + this.updateState(ConnectivityState.CONNECTING, this.latestChildPicker, this.latestChildErrorMessage); + } + this.backoffTimeout.runOnce(); + } + + private updateState(connectivityState: ConnectivityState, picker: Picker, errorMessage: string | null) { + trace( + uriToString(this.target) + + ' ' + + ConnectivityState[this.currentState] + + ' -> ' + + ConnectivityState[connectivityState] + ); + // Ensure that this.exitIdle() is called by the picker + if (connectivityState === ConnectivityState.IDLE) { + picker = new QueuePicker(this, picker); + } + this.currentState = connectivityState; + this.channelControlHelper.updateState(connectivityState, picker, errorMessage); + } + + private handleResolutionFailure(error: StatusObject) { + if (this.latestChildState === ConnectivityState.IDLE) { + this.updateState( + ConnectivityState.TRANSIENT_FAILURE, + new UnavailablePicker(error), + error.details + ); + this.onFailedResolution(error); + } + } + + exitIdle() { + if ( + this.currentState === ConnectivityState.IDLE || + this.currentState === ConnectivityState.TRANSIENT_FAILURE + ) { + if (this.backoffTimeout.isRunning()) { + this.continueResolving = true; + } else { + this.updateResolution(); + } + } + this.childLoadBalancer.exitIdle(); + } + + updateAddressList( + endpointList: StatusOr, + lbConfig: TypedLoadBalancingConfig | null + ): never { + throw new Error('updateAddressList not supported on ResolvingLoadBalancer'); + } + + resetBackoff() { + this.backoffTimeout.reset(); + this.childLoadBalancer.resetBackoff(); + } + + destroy() { + this.childLoadBalancer.destroy(); + this.innerResolver.destroy(); + this.backoffTimeout.reset(); + this.backoffTimeout.stop(); + this.latestChildState = ConnectivityState.IDLE; + this.latestChildPicker = new QueuePicker(this); + this.currentState = ConnectivityState.IDLE; + this.previousServiceConfig = null; + this.continueResolving = false; + } + + getTypeName() { + return 'resolving_load_balancer'; + } +} diff --git a/node_modules/@grpc/grpc-js/src/retrying-call.ts b/node_modules/@grpc/grpc-js/src/retrying-call.ts new file mode 100644 index 0000000..1d49ad3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/retrying-call.ts @@ -0,0 +1,898 @@ +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ + +import { CallCredentials } from './call-credentials'; +import { LogVerbosity, Status } from './constants'; +import { Deadline, formatDateDifference } from './deadline'; +import { Metadata } from './metadata'; +import { CallConfig } from './resolver'; +import * as logging from './logging'; +import { + Call, + DeadlineInfoProvider, + InterceptingListener, + MessageContext, + StatusObject, + WriteCallback, + WriteObject, +} from './call-interface'; +import { + LoadBalancingCall, + StatusObjectWithProgress, +} from './load-balancing-call'; +import { InternalChannel } from './internal-channel'; +import { AuthContext } from './auth-context'; + +const TRACER_NAME = 'retrying_call'; + +export class RetryThrottler { + private tokens: number; + constructor( + private readonly maxTokens: number, + private readonly tokenRatio: number, + previousRetryThrottler?: RetryThrottler + ) { + if (previousRetryThrottler) { + /* When carrying over tokens from a previous config, rescale them to the + * new max value */ + this.tokens = + previousRetryThrottler.tokens * + (maxTokens / previousRetryThrottler.maxTokens); + } else { + this.tokens = maxTokens; + } + } + + addCallSucceeded() { + this.tokens = Math.min(this.tokens + this.tokenRatio, this.maxTokens); + } + + addCallFailed() { + this.tokens = Math.max(this.tokens - 1, 0); + } + + canRetryCall() { + return this.tokens > (this.maxTokens / 2); + } +} + +export class MessageBufferTracker { + private totalAllocated = 0; + private allocatedPerCall: Map = new Map(); + + constructor(private totalLimit: number, private limitPerCall: number) {} + + allocate(size: number, callId: number): boolean { + const currentPerCall = this.allocatedPerCall.get(callId) ?? 0; + if ( + this.limitPerCall - currentPerCall < size || + this.totalLimit - this.totalAllocated < size + ) { + return false; + } + this.allocatedPerCall.set(callId, currentPerCall + size); + this.totalAllocated += size; + return true; + } + + free(size: number, callId: number) { + if (this.totalAllocated < size) { + throw new Error( + `Invalid buffer allocation state: call ${callId} freed ${size} > total allocated ${this.totalAllocated}` + ); + } + this.totalAllocated -= size; + const currentPerCall = this.allocatedPerCall.get(callId) ?? 0; + if (currentPerCall < size) { + throw new Error( + `Invalid buffer allocation state: call ${callId} freed ${size} > allocated for call ${currentPerCall}` + ); + } + this.allocatedPerCall.set(callId, currentPerCall - size); + } + + freeAll(callId: number) { + const currentPerCall = this.allocatedPerCall.get(callId) ?? 0; + if (this.totalAllocated < currentPerCall) { + throw new Error( + `Invalid buffer allocation state: call ${callId} allocated ${currentPerCall} > total allocated ${this.totalAllocated}` + ); + } + this.totalAllocated -= currentPerCall; + this.allocatedPerCall.delete(callId); + } +} + +type UnderlyingCallState = 'ACTIVE' | 'COMPLETED'; + +interface UnderlyingCall { + state: UnderlyingCallState; + call: LoadBalancingCall; + nextMessageToSend: number; + startTime: Date; +} + +/** + * A retrying call can be in one of these states: + * RETRY: Retries are configured and new attempts may be sent + * HEDGING: Hedging is configured and new attempts may be sent + * TRANSPARENT_ONLY: Neither retries nor hedging are configured, and + * transparent retry attempts may still be sent + * COMMITTED: One attempt is committed, and no new attempts will be + * sent + * NO_RETRY: Retries are disabled. Exists to track the transition to COMMITTED + */ +type RetryingCallState = + | 'RETRY' + | 'HEDGING' + | 'TRANSPARENT_ONLY' + | 'COMMITTED' + | 'NO_RETRY'; + +/** + * The different types of objects that can be stored in the write buffer, with + * the following meanings: + * MESSAGE: This is a message to be sent. + * HALF_CLOSE: When this entry is reached, the calls should send a half-close. + * FREED: This slot previously contained a message that has been sent on all + * child calls and is no longer needed. + */ +type WriteBufferEntryType = 'MESSAGE' | 'HALF_CLOSE' | 'FREED'; + +/** + * Entry in the buffer of messages to send to the remote end. + */ +interface WriteBufferEntry { + entryType: WriteBufferEntryType; + /** + * Message to send. + * Only populated if entryType is MESSAGE. + */ + message?: WriteObject; + /** + * Callback to call after sending the message. + * Only populated if entryType is MESSAGE and the call is in the COMMITTED + * state. + */ + callback?: WriteCallback; + /** + * Indicates whether the message is allocated in the buffer tracker. Ignored + * if entryType is not MESSAGE. Should be the return value of + * bufferTracker.allocate. + */ + allocated: boolean; +} + +const PREVIONS_RPC_ATTEMPTS_METADATA_KEY = 'grpc-previous-rpc-attempts'; + +const DEFAULT_MAX_ATTEMPTS_LIMIT = 5; + +export class RetryingCall implements Call, DeadlineInfoProvider { + private state: RetryingCallState; + private listener: InterceptingListener | null = null; + private initialMetadata: Metadata | null = null; + private underlyingCalls: UnderlyingCall[] = []; + private writeBuffer: WriteBufferEntry[] = []; + /** + * The offset of message indices in the writeBuffer. For example, if + * writeBufferOffset is 10, message 10 is in writeBuffer[0] and message 15 + * is in writeBuffer[5]. + */ + private writeBufferOffset = 0; + /** + * Tracks whether a read has been started, so that we know whether to start + * reads on new child calls. This only matters for the first read, because + * once a message comes in the child call becomes committed and there will + * be no new child calls. + */ + private readStarted = false; + private transparentRetryUsed = false; + /** + * Number of attempts so far + */ + private attempts = 0; + private hedgingTimer: NodeJS.Timeout | null = null; + private committedCallIndex: number | null = null; + private initialRetryBackoffSec = 0; + private nextRetryBackoffSec = 0; + private startTime: Date; + private maxAttempts: number; + constructor( + private readonly channel: InternalChannel, + private readonly callConfig: CallConfig, + private readonly methodName: string, + private readonly host: string, + private readonly credentials: CallCredentials, + private readonly deadline: Deadline, + private readonly callNumber: number, + private readonly bufferTracker: MessageBufferTracker, + private readonly retryThrottler?: RetryThrottler + ) { + const maxAttemptsLimit = + channel.getOptions()['grpc-node.retry_max_attempts_limit'] ?? + DEFAULT_MAX_ATTEMPTS_LIMIT; + if (channel.getOptions()['grpc.enable_retries'] === 0) { + this.state = 'NO_RETRY'; + this.maxAttempts = 1; + } else if (callConfig.methodConfig.retryPolicy) { + this.state = 'RETRY'; + const retryPolicy = callConfig.methodConfig.retryPolicy; + this.nextRetryBackoffSec = this.initialRetryBackoffSec = Number( + retryPolicy.initialBackoff.substring( + 0, + retryPolicy.initialBackoff.length - 1 + ) + ); + this.maxAttempts = Math.min(retryPolicy.maxAttempts, maxAttemptsLimit); + } else if (callConfig.methodConfig.hedgingPolicy) { + this.state = 'HEDGING'; + this.maxAttempts = Math.min( + callConfig.methodConfig.hedgingPolicy.maxAttempts, + maxAttemptsLimit + ); + } else { + this.state = 'TRANSPARENT_ONLY'; + this.maxAttempts = 1; + } + this.startTime = new Date(); + } + getDeadlineInfo(): string[] { + if (this.underlyingCalls.length === 0) { + return []; + } + const deadlineInfo: string[] = []; + const latestCall = this.underlyingCalls[this.underlyingCalls.length - 1]; + if (this.underlyingCalls.length > 1) { + deadlineInfo.push( + `previous attempts: ${this.underlyingCalls.length - 1}` + ); + } + if (latestCall.startTime > this.startTime) { + deadlineInfo.push( + `time to current attempt start: ${formatDateDifference( + this.startTime, + latestCall.startTime + )}` + ); + } + deadlineInfo.push(...latestCall.call.getDeadlineInfo()); + return deadlineInfo; + } + getCallNumber(): number { + return this.callNumber; + } + + private trace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + TRACER_NAME, + '[' + this.callNumber + '] ' + text + ); + } + + private reportStatus(statusObject: StatusObject) { + this.trace( + 'ended with status: code=' + + statusObject.code + + ' details="' + + statusObject.details + + '" start time=' + + this.startTime.toISOString() + ); + this.bufferTracker.freeAll(this.callNumber); + this.writeBufferOffset = this.writeBufferOffset + this.writeBuffer.length; + this.writeBuffer = []; + process.nextTick(() => { + // Explicitly construct status object to remove progress field + this.listener?.onReceiveStatus({ + code: statusObject.code, + details: statusObject.details, + metadata: statusObject.metadata, + }); + }); + } + + cancelWithStatus(status: Status, details: string): void { + this.trace( + 'cancelWithStatus code: ' + status + ' details: "' + details + '"' + ); + this.reportStatus({ code: status, details, metadata: new Metadata() }); + for (const { call } of this.underlyingCalls) { + call.cancelWithStatus(status, details); + } + } + getPeer(): string { + if (this.committedCallIndex !== null) { + return this.underlyingCalls[this.committedCallIndex].call.getPeer(); + } else { + return 'unknown'; + } + } + + private getBufferEntry(messageIndex: number): WriteBufferEntry { + return ( + this.writeBuffer[messageIndex - this.writeBufferOffset] ?? { + entryType: 'FREED', + allocated: false, + } + ); + } + + private getNextBufferIndex() { + return this.writeBufferOffset + this.writeBuffer.length; + } + + private clearSentMessages() { + if (this.state !== 'COMMITTED') { + return; + } + let earliestNeededMessageIndex: number; + if (this.underlyingCalls[this.committedCallIndex!].state === 'COMPLETED') { + /* If the committed call is completed, clear all messages, even if some + * have not been sent. */ + earliestNeededMessageIndex = this.getNextBufferIndex(); + } else { + earliestNeededMessageIndex = + this.underlyingCalls[this.committedCallIndex!].nextMessageToSend; + } + for ( + let messageIndex = this.writeBufferOffset; + messageIndex < earliestNeededMessageIndex; + messageIndex++ + ) { + const bufferEntry = this.getBufferEntry(messageIndex); + if (bufferEntry.allocated) { + this.bufferTracker.free( + bufferEntry.message!.message.length, + this.callNumber + ); + } + } + this.writeBuffer = this.writeBuffer.slice( + earliestNeededMessageIndex - this.writeBufferOffset + ); + this.writeBufferOffset = earliestNeededMessageIndex; + } + + private commitCall(index: number) { + if (this.state === 'COMMITTED') { + return; + } + this.trace( + 'Committing call [' + + this.underlyingCalls[index].call.getCallNumber() + + '] at index ' + + index + ); + this.state = 'COMMITTED'; + this.callConfig.onCommitted?.(); + this.committedCallIndex = index; + for (let i = 0; i < this.underlyingCalls.length; i++) { + if (i === index) { + continue; + } + if (this.underlyingCalls[i].state === 'COMPLETED') { + continue; + } + this.underlyingCalls[i].state = 'COMPLETED'; + this.underlyingCalls[i].call.cancelWithStatus( + Status.CANCELLED, + 'Discarded in favor of other hedged attempt' + ); + } + this.clearSentMessages(); + } + + private commitCallWithMostMessages() { + if (this.state === 'COMMITTED') { + return; + } + let mostMessages = -1; + let callWithMostMessages = -1; + for (const [index, childCall] of this.underlyingCalls.entries()) { + if ( + childCall.state === 'ACTIVE' && + childCall.nextMessageToSend > mostMessages + ) { + mostMessages = childCall.nextMessageToSend; + callWithMostMessages = index; + } + } + if (callWithMostMessages === -1) { + /* There are no active calls, disable retries to force the next call that + * is started to be committed. */ + this.state = 'TRANSPARENT_ONLY'; + } else { + this.commitCall(callWithMostMessages); + } + } + + private isStatusCodeInList(list: (Status | string)[], code: Status) { + return list.some( + value => + value === code || + value.toString().toLowerCase() === Status[code]?.toLowerCase() + ); + } + + private getNextRetryJitter() { + /* Jitter of +-20% is applied: https://github.com/grpc/proposal/blob/master/A6-client-retries.md#exponential-backoff */ + return Math.random() * (1.2 - 0.8) + 0.8; + } + + private getNextRetryBackoffMs() { + const retryPolicy = this.callConfig?.methodConfig.retryPolicy; + if (!retryPolicy) { + return 0; + } + const jitter = this.getNextRetryJitter(); + const nextBackoffMs = jitter * this.nextRetryBackoffSec * 1000; + const maxBackoffSec = Number( + retryPolicy.maxBackoff.substring(0, retryPolicy.maxBackoff.length - 1) + ); + this.nextRetryBackoffSec = Math.min( + this.nextRetryBackoffSec * retryPolicy.backoffMultiplier, + maxBackoffSec + ); + return nextBackoffMs; + } + + private maybeRetryCall( + pushback: number | null, + callback: (retried: boolean) => void + ) { + if (this.state !== 'RETRY') { + callback(false); + return; + } + if (this.attempts >= this.maxAttempts) { + callback(false); + return; + } + let retryDelayMs: number; + if (pushback === null) { + retryDelayMs = this.getNextRetryBackoffMs(); + } else if (pushback < 0) { + this.state = 'TRANSPARENT_ONLY'; + callback(false); + return; + } else { + retryDelayMs = pushback; + this.nextRetryBackoffSec = this.initialRetryBackoffSec; + } + setTimeout(() => { + if (this.state !== 'RETRY') { + callback(false); + return; + } + if (this.retryThrottler?.canRetryCall() ?? true) { + callback(true); + this.attempts += 1; + this.startNewAttempt(); + } else { + this.trace('Retry attempt denied by throttling policy'); + callback(false); + } + }, retryDelayMs); + } + + private countActiveCalls(): number { + let count = 0; + for (const call of this.underlyingCalls) { + if (call?.state === 'ACTIVE') { + count += 1; + } + } + return count; + } + + private handleProcessedStatus( + status: StatusObject, + callIndex: number, + pushback: number | null + ) { + switch (this.state) { + case 'COMMITTED': + case 'NO_RETRY': + case 'TRANSPARENT_ONLY': + this.commitCall(callIndex); + this.reportStatus(status); + break; + case 'HEDGING': + if ( + this.isStatusCodeInList( + this.callConfig!.methodConfig.hedgingPolicy!.nonFatalStatusCodes ?? + [], + status.code + ) + ) { + this.retryThrottler?.addCallFailed(); + let delayMs: number; + if (pushback === null) { + delayMs = 0; + } else if (pushback < 0) { + this.state = 'TRANSPARENT_ONLY'; + this.commitCall(callIndex); + this.reportStatus(status); + return; + } else { + delayMs = pushback; + } + setTimeout(() => { + this.maybeStartHedgingAttempt(); + // If after trying to start a call there are no active calls, this was the last one + if (this.countActiveCalls() === 0) { + this.commitCall(callIndex); + this.reportStatus(status); + } + }, delayMs); + } else { + this.commitCall(callIndex); + this.reportStatus(status); + } + break; + case 'RETRY': + if ( + this.isStatusCodeInList( + this.callConfig!.methodConfig.retryPolicy!.retryableStatusCodes, + status.code + ) + ) { + this.retryThrottler?.addCallFailed(); + this.maybeRetryCall(pushback, retried => { + if (!retried) { + this.commitCall(callIndex); + this.reportStatus(status); + } + }); + } else { + this.commitCall(callIndex); + this.reportStatus(status); + } + break; + } + } + + private getPushback(metadata: Metadata): number | null { + const mdValue = metadata.get('grpc-retry-pushback-ms'); + if (mdValue.length === 0) { + return null; + } + try { + return parseInt(mdValue[0] as string); + } catch (e) { + return -1; + } + } + + private handleChildStatus( + status: StatusObjectWithProgress, + callIndex: number + ) { + if (this.underlyingCalls[callIndex].state === 'COMPLETED') { + return; + } + this.trace( + 'state=' + + this.state + + ' handling status with progress ' + + status.progress + + ' from child [' + + this.underlyingCalls[callIndex].call.getCallNumber() + + '] in state ' + + this.underlyingCalls[callIndex].state + ); + this.underlyingCalls[callIndex].state = 'COMPLETED'; + if (status.code === Status.OK) { + this.retryThrottler?.addCallSucceeded(); + this.commitCall(callIndex); + this.reportStatus(status); + return; + } + if (this.state === 'NO_RETRY') { + this.commitCall(callIndex); + this.reportStatus(status); + return; + } + if (this.state === 'COMMITTED') { + this.reportStatus(status); + return; + } + const pushback = this.getPushback(status.metadata); + switch (status.progress) { + case 'NOT_STARTED': + // RPC never leaves the client, always safe to retry + this.startNewAttempt(); + break; + case 'REFUSED': + // RPC reaches the server library, but not the server application logic + if (this.transparentRetryUsed) { + this.handleProcessedStatus(status, callIndex, pushback); + } else { + this.transparentRetryUsed = true; + this.startNewAttempt(); + } + break; + case 'DROP': + this.commitCall(callIndex); + this.reportStatus(status); + break; + case 'PROCESSED': + this.handleProcessedStatus(status, callIndex, pushback); + break; + } + } + + private maybeStartHedgingAttempt() { + if (this.state !== 'HEDGING') { + return; + } + if (!this.callConfig.methodConfig.hedgingPolicy) { + return; + } + if (this.attempts >= this.maxAttempts) { + return; + } + this.attempts += 1; + this.startNewAttempt(); + this.maybeStartHedgingTimer(); + } + + private maybeStartHedgingTimer() { + if (this.hedgingTimer) { + clearTimeout(this.hedgingTimer); + } + if (this.state !== 'HEDGING') { + return; + } + if (!this.callConfig.methodConfig.hedgingPolicy) { + return; + } + const hedgingPolicy = this.callConfig.methodConfig.hedgingPolicy; + if (this.attempts >= this.maxAttempts) { + return; + } + const hedgingDelayString = hedgingPolicy.hedgingDelay ?? '0s'; + const hedgingDelaySec = Number( + hedgingDelayString.substring(0, hedgingDelayString.length - 1) + ); + this.hedgingTimer = setTimeout(() => { + this.maybeStartHedgingAttempt(); + }, hedgingDelaySec * 1000); + this.hedgingTimer.unref?.(); + } + + private startNewAttempt() { + const child = this.channel.createLoadBalancingCall( + this.callConfig, + this.methodName, + this.host, + this.credentials, + this.deadline + ); + this.trace( + 'Created child call [' + + child.getCallNumber() + + '] for attempt ' + + this.attempts + ); + const index = this.underlyingCalls.length; + this.underlyingCalls.push({ + state: 'ACTIVE', + call: child, + nextMessageToSend: 0, + startTime: new Date(), + }); + const previousAttempts = this.attempts - 1; + const initialMetadata = this.initialMetadata!.clone(); + if (previousAttempts > 0) { + initialMetadata.set( + PREVIONS_RPC_ATTEMPTS_METADATA_KEY, + `${previousAttempts}` + ); + } + let receivedMetadata = false; + child.start(initialMetadata, { + onReceiveMetadata: metadata => { + this.trace( + 'Received metadata from child [' + child.getCallNumber() + ']' + ); + this.commitCall(index); + receivedMetadata = true; + if (previousAttempts > 0) { + metadata.set( + PREVIONS_RPC_ATTEMPTS_METADATA_KEY, + `${previousAttempts}` + ); + } + if (this.underlyingCalls[index].state === 'ACTIVE') { + this.listener!.onReceiveMetadata(metadata); + } + }, + onReceiveMessage: message => { + this.trace( + 'Received message from child [' + child.getCallNumber() + ']' + ); + this.commitCall(index); + if (this.underlyingCalls[index].state === 'ACTIVE') { + this.listener!.onReceiveMessage(message); + } + }, + onReceiveStatus: status => { + this.trace( + 'Received status from child [' + child.getCallNumber() + ']' + ); + if (!receivedMetadata && previousAttempts > 0) { + status.metadata.set( + PREVIONS_RPC_ATTEMPTS_METADATA_KEY, + `${previousAttempts}` + ); + } + this.handleChildStatus(status, index); + }, + }); + this.sendNextChildMessage(index); + if (this.readStarted) { + child.startRead(); + } + } + + start(metadata: Metadata, listener: InterceptingListener): void { + this.trace('start called'); + this.listener = listener; + this.initialMetadata = metadata; + this.attempts += 1; + this.startNewAttempt(); + this.maybeStartHedgingTimer(); + } + + private handleChildWriteCompleted(childIndex: number) { + const childCall = this.underlyingCalls[childIndex]; + const messageIndex = childCall.nextMessageToSend; + this.getBufferEntry(messageIndex).callback?.(); + this.clearSentMessages(); + childCall.nextMessageToSend += 1; + this.sendNextChildMessage(childIndex); + } + + private sendNextChildMessage(childIndex: number) { + const childCall = this.underlyingCalls[childIndex]; + if (childCall.state === 'COMPLETED') { + return; + } + if (this.getBufferEntry(childCall.nextMessageToSend)) { + const bufferEntry = this.getBufferEntry(childCall.nextMessageToSend); + switch (bufferEntry.entryType) { + case 'MESSAGE': + childCall.call.sendMessageWithContext( + { + callback: error => { + // Ignore error + this.handleChildWriteCompleted(childIndex); + }, + }, + bufferEntry.message!.message + ); + break; + case 'HALF_CLOSE': + childCall.nextMessageToSend += 1; + childCall.call.halfClose(); + break; + case 'FREED': + // Should not be possible + break; + } + } + } + + sendMessageWithContext(context: MessageContext, message: Buffer): void { + this.trace('write() called with message of length ' + message.length); + const writeObj: WriteObject = { + message, + flags: context.flags, + }; + const messageIndex = this.getNextBufferIndex(); + const bufferEntry: WriteBufferEntry = { + entryType: 'MESSAGE', + message: writeObj, + allocated: this.bufferTracker.allocate(message.length, this.callNumber), + }; + this.writeBuffer.push(bufferEntry); + if (bufferEntry.allocated) { + context.callback?.(); + for (const [callIndex, call] of this.underlyingCalls.entries()) { + if ( + call.state === 'ACTIVE' && + call.nextMessageToSend === messageIndex + ) { + call.call.sendMessageWithContext( + { + callback: error => { + // Ignore error + this.handleChildWriteCompleted(callIndex); + }, + }, + message + ); + } + } + } else { + this.commitCallWithMostMessages(); + // commitCallWithMostMessages can fail if we are between ping attempts + if (this.committedCallIndex === null) { + return; + } + const call = this.underlyingCalls[this.committedCallIndex]; + bufferEntry.callback = context.callback; + if (call.state === 'ACTIVE' && call.nextMessageToSend === messageIndex) { + call.call.sendMessageWithContext( + { + callback: error => { + // Ignore error + this.handleChildWriteCompleted(this.committedCallIndex!); + }, + }, + message + ); + } + } + } + startRead(): void { + this.trace('startRead called'); + this.readStarted = true; + for (const underlyingCall of this.underlyingCalls) { + if (underlyingCall?.state === 'ACTIVE') { + underlyingCall.call.startRead(); + } + } + } + halfClose(): void { + this.trace('halfClose called'); + const halfCloseIndex = this.getNextBufferIndex(); + this.writeBuffer.push({ + entryType: 'HALF_CLOSE', + allocated: false, + }); + for (const call of this.underlyingCalls) { + if ( + call?.state === 'ACTIVE' && + call.nextMessageToSend === halfCloseIndex + ) { + call.nextMessageToSend += 1; + call.call.halfClose(); + } + } + } + setCredentials(newCredentials: CallCredentials): void { + throw new Error('Method not implemented.'); + } + getMethod(): string { + return this.methodName; + } + getHost(): string { + return this.host; + } + getAuthContext(): AuthContext | null { + if (this.committedCallIndex !== null) { + return this.underlyingCalls[ + this.committedCallIndex + ].call.getAuthContext(); + } else { + return null; + } + } +} diff --git a/node_modules/@grpc/grpc-js/src/server-call.ts b/node_modules/@grpc/grpc-js/src/server-call.ts new file mode 100644 index 0000000..670cf62 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/server-call.ts @@ -0,0 +1,420 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { EventEmitter } from 'events'; +import { Duplex, Readable, Writable } from 'stream'; + +import { Status } from './constants'; +import type { Deserialize, Serialize } from './make-client'; +import { Metadata } from './metadata'; +import type { ObjectReadable, ObjectWritable } from './object-stream'; +import type { StatusObject, PartialStatusObject } from './call-interface'; +import type { Deadline } from './deadline'; +import type { ServerInterceptingCallInterface } from './server-interceptors'; +import { AuthContext } from './auth-context'; +import { PerRequestMetricRecorder } from './orca'; + +export type ServerStatusResponse = Partial; + +export type ServerErrorResponse = ServerStatusResponse & Error; + +export type ServerSurfaceCall = { + cancelled: boolean; + readonly metadata: Metadata; + getPeer(): string; + sendMetadata(responseMetadata: Metadata): void; + getDeadline(): Deadline; + getPath(): string; + getHost(): string; + getAuthContext(): AuthContext; + getMetricsRecorder(): PerRequestMetricRecorder; +} & EventEmitter; + +export type ServerUnaryCall = ServerSurfaceCall & { + request: RequestType; +}; +export type ServerReadableStream = + ServerSurfaceCall & ObjectReadable; +export type ServerWritableStream = + ServerSurfaceCall & + ObjectWritable & { + request: RequestType; + end: (metadata?: Metadata) => void; + }; +export type ServerDuplexStream = ServerSurfaceCall & + ObjectReadable & + ObjectWritable & { end: (metadata?: Metadata) => void }; + +export function serverErrorToStatus( + error: ServerErrorResponse | ServerStatusResponse, + overrideTrailers?: Metadata | undefined +): PartialStatusObject { + const status: PartialStatusObject = { + code: Status.UNKNOWN, + details: 'message' in error ? error.message : 'Unknown Error', + metadata: overrideTrailers ?? error.metadata ?? null, + }; + + if ( + 'code' in error && + typeof error.code === 'number' && + Number.isInteger(error.code) + ) { + status.code = error.code; + + if ('details' in error && typeof error.details === 'string') { + status.details = error.details!; + } + } + return status; +} + +export class ServerUnaryCallImpl + extends EventEmitter + implements ServerUnaryCall +{ + cancelled: boolean; + + constructor( + private path: string, + private call: ServerInterceptingCallInterface, + public metadata: Metadata, + public request: RequestType + ) { + super(); + this.cancelled = false; + } + + getPeer(): string { + return this.call.getPeer(); + } + + sendMetadata(responseMetadata: Metadata): void { + this.call.sendMetadata(responseMetadata); + } + + getDeadline(): Deadline { + return this.call.getDeadline(); + } + + getPath(): string { + return this.path; + } + + getHost(): string { + return this.call.getHost(); + } + + getAuthContext(): AuthContext { + return this.call.getAuthContext(); + } + + getMetricsRecorder(): PerRequestMetricRecorder { + return this.call.getMetricsRecorder(); + } +} + +export class ServerReadableStreamImpl + extends Readable + implements ServerReadableStream +{ + cancelled: boolean; + + constructor( + private path: string, + private call: ServerInterceptingCallInterface, + public metadata: Metadata + ) { + super({ objectMode: true }); + this.cancelled = false; + } + + _read(size: number) { + this.call.startRead(); + } + + getPeer(): string { + return this.call.getPeer(); + } + + sendMetadata(responseMetadata: Metadata): void { + this.call.sendMetadata(responseMetadata); + } + + getDeadline(): Deadline { + return this.call.getDeadline(); + } + + getPath(): string { + return this.path; + } + + getHost(): string { + return this.call.getHost(); + } + + getAuthContext(): AuthContext { + return this.call.getAuthContext(); + } + + getMetricsRecorder(): PerRequestMetricRecorder { + return this.call.getMetricsRecorder(); + } +} + +export class ServerWritableStreamImpl + extends Writable + implements ServerWritableStream +{ + cancelled: boolean; + private trailingMetadata: Metadata; + private pendingStatus: PartialStatusObject = { + code: Status.OK, + details: 'OK', + }; + + constructor( + private path: string, + private call: ServerInterceptingCallInterface, + public metadata: Metadata, + public request: RequestType + ) { + super({ objectMode: true }); + this.cancelled = false; + this.trailingMetadata = new Metadata(); + + this.on('error', err => { + this.pendingStatus = serverErrorToStatus(err); + this.end(); + }); + } + + getPeer(): string { + return this.call.getPeer(); + } + + sendMetadata(responseMetadata: Metadata): void { + this.call.sendMetadata(responseMetadata); + } + + getDeadline(): Deadline { + return this.call.getDeadline(); + } + + getPath(): string { + return this.path; + } + + getHost(): string { + return this.call.getHost(); + } + + getAuthContext(): AuthContext { + return this.call.getAuthContext(); + } + + getMetricsRecorder(): PerRequestMetricRecorder { + return this.call.getMetricsRecorder(); + } + + _write( + chunk: ResponseType, + encoding: string, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callback: (...args: any[]) => void + ) { + this.call.sendMessage(chunk, callback); + } + + _final(callback: Function): void { + callback(null); + this.call.sendStatus({ + ...this.pendingStatus, + metadata: this.pendingStatus.metadata ?? this.trailingMetadata, + }); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + end(metadata?: any) { + if (metadata) { + this.trailingMetadata = metadata; + } + + return super.end(); + } +} + +export class ServerDuplexStreamImpl + extends Duplex + implements ServerDuplexStream +{ + cancelled: boolean; + private trailingMetadata: Metadata; + private pendingStatus: PartialStatusObject = { + code: Status.OK, + details: 'OK', + }; + + constructor( + private path: string, + private call: ServerInterceptingCallInterface, + public metadata: Metadata + ) { + super({ objectMode: true }); + this.cancelled = false; + this.trailingMetadata = new Metadata(); + + this.on('error', err => { + this.pendingStatus = serverErrorToStatus(err); + this.end(); + }); + } + + getPeer(): string { + return this.call.getPeer(); + } + + sendMetadata(responseMetadata: Metadata): void { + this.call.sendMetadata(responseMetadata); + } + + getDeadline(): Deadline { + return this.call.getDeadline(); + } + + getPath(): string { + return this.path; + } + + getHost(): string { + return this.call.getHost(); + } + + getAuthContext(): AuthContext { + return this.call.getAuthContext(); + } + + getMetricsRecorder(): PerRequestMetricRecorder { + return this.call.getMetricsRecorder(); + } + + _read(size: number) { + this.call.startRead(); + } + + _write( + chunk: ResponseType, + encoding: string, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callback: (...args: any[]) => void + ) { + this.call.sendMessage(chunk, callback); + } + + _final(callback: Function): void { + callback(null); + this.call.sendStatus({ + ...this.pendingStatus, + metadata: this.pendingStatus.metadata ?? this.trailingMetadata, + }); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + end(metadata?: any) { + if (metadata) { + this.trailingMetadata = metadata; + } + + return super.end(); + } +} + +// Unary response callback signature. +export type sendUnaryData = ( + error: ServerErrorResponse | ServerStatusResponse | null, + value?: ResponseType | null, + trailer?: Metadata, + flags?: number +) => void; + +// User provided handler for unary calls. +export type handleUnaryCall = ( + call: ServerUnaryCall, + callback: sendUnaryData +) => void; + +// User provided handler for client streaming calls. +export type handleClientStreamingCall = ( + call: ServerReadableStream, + callback: sendUnaryData +) => void; + +// User provided handler for server streaming calls. +export type handleServerStreamingCall = ( + call: ServerWritableStream +) => void; + +// User provided handler for bidirectional streaming calls. +export type handleBidiStreamingCall = ( + call: ServerDuplexStream +) => void; + +export type HandleCall = + | handleUnaryCall + | handleClientStreamingCall + | handleServerStreamingCall + | handleBidiStreamingCall; + +export interface UnaryHandler { + func: handleUnaryCall; + serialize: Serialize; + deserialize: Deserialize; + type: 'unary'; + path: string; +} + +export interface ClientStreamingHandler { + func: handleClientStreamingCall; + serialize: Serialize; + deserialize: Deserialize; + type: 'clientStream'; + path: string; +} + +export interface ServerStreamingHandler { + func: handleServerStreamingCall; + serialize: Serialize; + deserialize: Deserialize; + type: 'serverStream'; + path: string; +} + +export interface BidiStreamingHandler { + func: handleBidiStreamingCall; + serialize: Serialize; + deserialize: Deserialize; + type: 'bidi'; + path: string; +} + +export type Handler = + | UnaryHandler + | ClientStreamingHandler + | ServerStreamingHandler + | BidiStreamingHandler; + +export type HandlerType = 'bidi' | 'clientStream' | 'serverStream' | 'unary'; diff --git a/node_modules/@grpc/grpc-js/src/server-credentials.ts b/node_modules/@grpc/grpc-js/src/server-credentials.ts new file mode 100644 index 0000000..5a61add --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/server-credentials.ts @@ -0,0 +1,352 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { SecureServerOptions } from 'http2'; +import { CIPHER_SUITES, getDefaultRootsData } from './tls-helpers'; +import { SecureContextOptions } from 'tls'; +import { ServerInterceptor } from '.'; +import { CaCertificateUpdate, CaCertificateUpdateListener, CertificateProvider, IdentityCertificateUpdate, IdentityCertificateUpdateListener } from './certificate-provider'; + +export interface KeyCertPair { + private_key: Buffer; + cert_chain: Buffer; +} + +export interface SecureContextWatcher { + (context: SecureContextOptions | null): void; +} + +export abstract class ServerCredentials { + private watchers: Set = new Set(); + private latestContextOptions: SecureContextOptions | null = null; + constructor(private serverConstructorOptions: SecureServerOptions | null, contextOptions?: SecureContextOptions) { + this.latestContextOptions = contextOptions ?? null; + } + + _addWatcher(watcher: SecureContextWatcher) { + this.watchers.add(watcher); + } + _removeWatcher(watcher: SecureContextWatcher) { + this.watchers.delete(watcher); + } + protected getWatcherCount() { + return this.watchers.size; + } + protected updateSecureContextOptions(options: SecureContextOptions | null) { + this.latestContextOptions = options; + for (const watcher of this.watchers) { + watcher(this.latestContextOptions); + } + } + _isSecure(): boolean { + return this.serverConstructorOptions !== null; + } + _getSecureContextOptions(): SecureContextOptions | null { + return this.latestContextOptions; + } + _getConstructorOptions(): SecureServerOptions | null { + return this.serverConstructorOptions; + } + _getInterceptors(): ServerInterceptor[] { + return []; + } + abstract _equals(other: ServerCredentials): boolean; + + static createInsecure(): ServerCredentials { + return new InsecureServerCredentials(); + } + + static createSsl( + rootCerts: Buffer | null, + keyCertPairs: KeyCertPair[], + checkClientCertificate = false + ): ServerCredentials { + if (rootCerts !== null && !Buffer.isBuffer(rootCerts)) { + throw new TypeError('rootCerts must be null or a Buffer'); + } + + if (!Array.isArray(keyCertPairs)) { + throw new TypeError('keyCertPairs must be an array'); + } + + if (typeof checkClientCertificate !== 'boolean') { + throw new TypeError('checkClientCertificate must be a boolean'); + } + + const cert: Buffer[] = []; + const key: Buffer[] = []; + + for (let i = 0; i < keyCertPairs.length; i++) { + const pair = keyCertPairs[i]; + + if (pair === null || typeof pair !== 'object') { + throw new TypeError(`keyCertPair[${i}] must be an object`); + } + + if (!Buffer.isBuffer(pair.private_key)) { + throw new TypeError(`keyCertPair[${i}].private_key must be a Buffer`); + } + + if (!Buffer.isBuffer(pair.cert_chain)) { + throw new TypeError(`keyCertPair[${i}].cert_chain must be a Buffer`); + } + + cert.push(pair.cert_chain); + key.push(pair.private_key); + } + + return new SecureServerCredentials({ + requestCert: checkClientCertificate, + ciphers: CIPHER_SUITES, + }, { + ca: rootCerts ?? getDefaultRootsData() ?? undefined, + cert, + key, + }); + } +} + +class InsecureServerCredentials extends ServerCredentials { + constructor() { + super(null); + } + + _getSettings(): null { + return null; + } + + _equals(other: ServerCredentials): boolean { + return other instanceof InsecureServerCredentials; + } +} + +class SecureServerCredentials extends ServerCredentials { + private options: SecureServerOptions; + + constructor(constructorOptions: SecureServerOptions, contextOptions: SecureContextOptions) { + super(constructorOptions, contextOptions); + this.options = {...constructorOptions, ...contextOptions}; + } + + /** + * Checks equality by checking the options that are actually set by + * createSsl. + * @param other + * @returns + */ + _equals(other: ServerCredentials): boolean { + if (this === other) { + return true; + } + if (!(other instanceof SecureServerCredentials)) { + return false; + } + // options.ca equality check + if (Buffer.isBuffer(this.options.ca) && Buffer.isBuffer(other.options.ca)) { + if (!this.options.ca.equals(other.options.ca)) { + return false; + } + } else { + if (this.options.ca !== other.options.ca) { + return false; + } + } + // options.cert equality check + if (Array.isArray(this.options.cert) && Array.isArray(other.options.cert)) { + if (this.options.cert.length !== other.options.cert.length) { + return false; + } + for (let i = 0; i < this.options.cert.length; i++) { + const thisCert = this.options.cert[i]; + const otherCert = other.options.cert[i]; + if (Buffer.isBuffer(thisCert) && Buffer.isBuffer(otherCert)) { + if (!thisCert.equals(otherCert)) { + return false; + } + } else { + if (thisCert !== otherCert) { + return false; + } + } + } + } else { + if (this.options.cert !== other.options.cert) { + return false; + } + } + // options.key equality check + if (Array.isArray(this.options.key) && Array.isArray(other.options.key)) { + if (this.options.key.length !== other.options.key.length) { + return false; + } + for (let i = 0; i < this.options.key.length; i++) { + const thisKey = this.options.key[i]; + const otherKey = other.options.key[i]; + if (Buffer.isBuffer(thisKey) && Buffer.isBuffer(otherKey)) { + if (!thisKey.equals(otherKey)) { + return false; + } + } else { + if (thisKey !== otherKey) { + return false; + } + } + } + } else { + if (this.options.key !== other.options.key) { + return false; + } + } + // options.requestCert equality check + if (this.options.requestCert !== other.options.requestCert) { + return false; + } + /* ciphers is derived from a value that is constant for the process, so no + * equality check is needed. */ + return true; + } +} + +class CertificateProviderServerCredentials extends ServerCredentials { + private latestCaUpdate: CaCertificateUpdate | null = null; + private latestIdentityUpdate: IdentityCertificateUpdate | null = null; + private caCertificateUpdateListener: CaCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this); + private identityCertificateUpdateListener: IdentityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this); + constructor( + private identityCertificateProvider: CertificateProvider, + private caCertificateProvider: CertificateProvider | null, + private requireClientCertificate: boolean + ) { + super({ + requestCert: caCertificateProvider !== null, + rejectUnauthorized: requireClientCertificate, + ciphers: CIPHER_SUITES + }); + } + _addWatcher(watcher: SecureContextWatcher): void { + if (this.getWatcherCount() === 0) { + this.caCertificateProvider?.addCaCertificateListener(this.caCertificateUpdateListener); + this.identityCertificateProvider.addIdentityCertificateListener(this.identityCertificateUpdateListener); + } + super._addWatcher(watcher); + } + _removeWatcher(watcher: SecureContextWatcher): void { + super._removeWatcher(watcher); + if (this.getWatcherCount() === 0) { + this.caCertificateProvider?.removeCaCertificateListener(this.caCertificateUpdateListener); + this.identityCertificateProvider.removeIdentityCertificateListener(this.identityCertificateUpdateListener); + } + } + _equals(other: ServerCredentials): boolean { + if (this === other) { + return true; + } + if (!(other instanceof CertificateProviderServerCredentials)) { + return false; + } + return ( + this.caCertificateProvider === other.caCertificateProvider && + this.identityCertificateProvider === other.identityCertificateProvider && + this.requireClientCertificate === other.requireClientCertificate + ) + } + + private calculateSecureContextOptions(): SecureContextOptions | null { + if (this.latestIdentityUpdate === null) { + return null; + } + if (this.caCertificateProvider !== null && this.latestCaUpdate === null) { + return null; + } + return { + ca: this.latestCaUpdate?.caCertificate, + cert: [this.latestIdentityUpdate.certificate], + key: [this.latestIdentityUpdate.privateKey], + }; + } + + private finalizeUpdate() { + const secureContextOptions = this.calculateSecureContextOptions(); + this.updateSecureContextOptions(secureContextOptions); + } + + private handleCaCertificateUpdate(update: CaCertificateUpdate | null) { + this.latestCaUpdate = update; + this.finalizeUpdate(); + } + + private handleIdentityCertitificateUpdate(update: IdentityCertificateUpdate | null) { + this.latestIdentityUpdate = update; + this.finalizeUpdate(); + } +} + +export function createCertificateProviderServerCredentials( + caCertificateProvider: CertificateProvider, + identityCertificateProvider: CertificateProvider | null, + requireClientCertificate: boolean +) { + return new CertificateProviderServerCredentials( + caCertificateProvider, + identityCertificateProvider, + requireClientCertificate); +} + +class InterceptorServerCredentials extends ServerCredentials { + constructor(private readonly childCredentials: ServerCredentials, private readonly interceptors: ServerInterceptor[]) { + super({}); + } + _isSecure(): boolean { + return this.childCredentials._isSecure(); + } + _equals(other: ServerCredentials): boolean { + if (!(other instanceof InterceptorServerCredentials)) { + return false; + } + if (!(this.childCredentials._equals(other.childCredentials))) { + return false; + } + if (this.interceptors.length !== other.interceptors.length) { + return false; + } + for (let i = 0; i < this.interceptors.length; i++) { + if (this.interceptors[i] !== other.interceptors[i]) { + return false; + } + } + return true; + } + override _getInterceptors(): ServerInterceptor[] { + return this.interceptors; + } + override _addWatcher(watcher: SecureContextWatcher): void { + this.childCredentials._addWatcher(watcher); + } + override _removeWatcher(watcher: SecureContextWatcher): void { + this.childCredentials._removeWatcher(watcher); + } + override _getConstructorOptions(): SecureServerOptions | null { + return this.childCredentials._getConstructorOptions(); + } + override _getSecureContextOptions(): SecureContextOptions | null { + return this.childCredentials._getSecureContextOptions(); + } +} + +export function createServerCredentialsWithInterceptors(credentials: ServerCredentials, interceptors: ServerInterceptor[]): ServerCredentials { + return new InterceptorServerCredentials(credentials, interceptors); +} diff --git a/node_modules/@grpc/grpc-js/src/server-interceptors.ts b/node_modules/@grpc/grpc-js/src/server-interceptors.ts new file mode 100644 index 0000000..a7cddd9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/server-interceptors.ts @@ -0,0 +1,1071 @@ +/* + * Copyright 2024 gRPC authors. + * + * 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. + * + */ + +import { PartialStatusObject } from './call-interface'; +import { ServerMethodDefinition } from './make-client'; +import { Metadata } from './metadata'; +import { ChannelOptions } from './channel-options'; +import { Handler, ServerErrorResponse } from './server-call'; +import { Deadline } from './deadline'; +import { + DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH, + DEFAULT_MAX_SEND_MESSAGE_LENGTH, + LogVerbosity, + Status, +} from './constants'; +import * as http2 from 'http2'; +import { getErrorMessage } from './error'; +import * as zlib from 'zlib'; +import { StreamDecoder } from './stream-decoder'; +import { CallEventTracker } from './transport'; +import * as logging from './logging'; +import { AuthContext } from './auth-context'; +import { TLSSocket } from 'tls'; +import { GRPC_METRICS_HEADER, PerRequestMetricRecorder } from './orca'; + +const TRACER_NAME = 'server_call'; + +function trace(text: string) { + logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text); +} + +export interface ServerMetadataListener { + (metadata: Metadata, next: (metadata: Metadata) => void): void; +} + +export interface ServerMessageListener { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (message: any, next: (message: any) => void): void; +} + +export interface ServerHalfCloseListener { + (next: () => void): void; +} + +export interface ServerCancelListener { + (): void; +} + +export interface FullServerListener { + onReceiveMetadata: ServerMetadataListener; + onReceiveMessage: ServerMessageListener; + onReceiveHalfClose: ServerHalfCloseListener; + onCancel: ServerCancelListener; +} + +export type ServerListener = Partial; + +export class ServerListenerBuilder { + private metadata: ServerMetadataListener | undefined = undefined; + private message: ServerMessageListener | undefined = undefined; + private halfClose: ServerHalfCloseListener | undefined = undefined; + private cancel: ServerCancelListener | undefined = undefined; + + withOnReceiveMetadata(onReceiveMetadata: ServerMetadataListener): this { + this.metadata = onReceiveMetadata; + return this; + } + + withOnReceiveMessage(onReceiveMessage: ServerMessageListener): this { + this.message = onReceiveMessage; + return this; + } + + withOnReceiveHalfClose(onReceiveHalfClose: ServerHalfCloseListener): this { + this.halfClose = onReceiveHalfClose; + return this; + } + + withOnCancel(onCancel: ServerCancelListener): this { + this.cancel = onCancel; + return this; + } + + build(): ServerListener { + return { + onReceiveMetadata: this.metadata, + onReceiveMessage: this.message, + onReceiveHalfClose: this.halfClose, + onCancel: this.cancel, + }; + } +} + +export interface InterceptingServerListener { + onReceiveMetadata(metadata: Metadata): void; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message: any): void; + onReceiveHalfClose(): void; + onCancel(): void; +} + +export function isInterceptingServerListener( + listener: ServerListener | InterceptingServerListener +): listener is InterceptingServerListener { + return ( + listener.onReceiveMetadata !== undefined && + listener.onReceiveMetadata.length === 1 + ); +} + +class InterceptingServerListenerImpl implements InterceptingServerListener { + /** + * Once the call is cancelled, ignore all other events. + */ + private cancelled = false; + private processingMetadata = false; + private hasPendingMessage = false; + private pendingMessage: any = null; + private processingMessage = false; + private hasPendingHalfClose = false; + + constructor( + private listener: FullServerListener, + private nextListener: InterceptingServerListener + ) {} + + private processPendingMessage() { + if (this.hasPendingMessage) { + this.nextListener.onReceiveMessage(this.pendingMessage); + this.pendingMessage = null; + this.hasPendingMessage = false; + } + } + + private processPendingHalfClose() { + if (this.hasPendingHalfClose) { + this.nextListener.onReceiveHalfClose(); + this.hasPendingHalfClose = false; + } + } + + onReceiveMetadata(metadata: Metadata): void { + if (this.cancelled) { + return; + } + this.processingMetadata = true; + this.listener.onReceiveMetadata(metadata, interceptedMetadata => { + this.processingMetadata = false; + if (this.cancelled) { + return; + } + this.nextListener.onReceiveMetadata(interceptedMetadata); + this.processPendingMessage(); + this.processPendingHalfClose(); + }); + } + onReceiveMessage(message: any): void { + if (this.cancelled) { + return; + } + this.processingMessage = true; + this.listener.onReceiveMessage(message, msg => { + this.processingMessage = false; + if (this.cancelled) { + return; + } + if (this.processingMetadata) { + this.pendingMessage = msg; + this.hasPendingMessage = true; + } else { + this.nextListener.onReceiveMessage(msg); + this.processPendingHalfClose(); + } + }); + } + onReceiveHalfClose(): void { + if (this.cancelled) { + return; + } + this.listener.onReceiveHalfClose(() => { + if (this.cancelled) { + return; + } + if (this.processingMetadata || this.processingMessage) { + this.hasPendingHalfClose = true; + } else { + this.nextListener.onReceiveHalfClose(); + } + }); + } + onCancel(): void { + this.cancelled = true; + this.listener.onCancel(); + this.nextListener.onCancel(); + } +} + +export interface StartResponder { + (next: (listener?: ServerListener) => void): void; +} + +export interface MetadataResponder { + (metadata: Metadata, next: (metadata: Metadata) => void): void; +} + +export interface MessageResponder { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (message: any, next: (message: any) => void): void; +} + +export interface StatusResponder { + ( + status: PartialStatusObject, + next: (status: PartialStatusObject) => void + ): void; +} + +export interface FullResponder { + start: StartResponder; + sendMetadata: MetadataResponder; + sendMessage: MessageResponder; + sendStatus: StatusResponder; +} + +export type Responder = Partial; + +export class ResponderBuilder { + private start: StartResponder | undefined = undefined; + private metadata: MetadataResponder | undefined = undefined; + private message: MessageResponder | undefined = undefined; + private status: StatusResponder | undefined = undefined; + + withStart(start: StartResponder): this { + this.start = start; + return this; + } + + withSendMetadata(sendMetadata: MetadataResponder): this { + this.metadata = sendMetadata; + return this; + } + + withSendMessage(sendMessage: MessageResponder): this { + this.message = sendMessage; + return this; + } + + withSendStatus(sendStatus: StatusResponder): this { + this.status = sendStatus; + return this; + } + + build(): Responder { + return { + start: this.start, + sendMetadata: this.metadata, + sendMessage: this.message, + sendStatus: this.status, + }; + } +} + +const defaultServerListener: FullServerListener = { + onReceiveMetadata: (metadata, next) => { + next(metadata); + }, + onReceiveMessage: (message, next) => { + next(message); + }, + onReceiveHalfClose: next => { + next(); + }, + onCancel: () => {}, +}; + +const defaultResponder: FullResponder = { + start: next => { + next(); + }, + sendMetadata: (metadata, next) => { + next(metadata); + }, + sendMessage: (message, next) => { + next(message); + }, + sendStatus: (status, next) => { + next(status); + }, +}; + +export interface ConnectionInfo { + localAddress?: string | undefined; + localPort?: number | undefined; + remoteAddress?: string | undefined; + remotePort?: number | undefined; +} + +export interface ServerInterceptingCallInterface { + /** + * Register the listener to handle inbound events. + */ + start(listener: InterceptingServerListener): void; + /** + * Send response metadata. + */ + sendMetadata(metadata: Metadata): void; + /** + * Send a response message. + */ + sendMessage(message: any, callback: () => void): void; + /** + * End the call by sending this status. + */ + sendStatus(status: PartialStatusObject): void; + /** + * Start a single read, eventually triggering either listener.onReceiveMessage or listener.onReceiveHalfClose. + */ + startRead(): void; + /** + * Return the peer address of the client making the request, if known, or "unknown" otherwise + */ + getPeer(): string; + /** + * Return the call deadline set by the client. The value is Infinity if there is no deadline. + */ + getDeadline(): Deadline; + /** + * Return the host requested by the client in the ":authority" header. + */ + getHost(): string; + /** + * Return the auth context of the connection the call is associated with. + */ + getAuthContext(): AuthContext; + /** + * Return information about the connection used to make the call. + */ + getConnectionInfo(): ConnectionInfo; + /** + * Get the metrics recorder for this call. Metrics will not be sent unless + * the server was constructed with the `grpc.server_call_metric_recording` + * option. + */ + getMetricsRecorder(): PerRequestMetricRecorder; +} + +export class ServerInterceptingCall implements ServerInterceptingCallInterface { + private responder: FullResponder; + private processingMetadata = false; + private sentMetadata = false; + private processingMessage = false; + private pendingMessage: any = null; + private pendingMessageCallback: (() => void) | null = null; + private pendingStatus: PartialStatusObject | null = null; + constructor( + private nextCall: ServerInterceptingCallInterface, + responder?: Responder + ) { + this.responder = { + start: responder?.start ?? defaultResponder.start, + sendMetadata: responder?.sendMetadata ?? defaultResponder.sendMetadata, + sendMessage: responder?.sendMessage ?? defaultResponder.sendMessage, + sendStatus: responder?.sendStatus ?? defaultResponder.sendStatus, + }; + } + + private processPendingMessage() { + if (this.pendingMessageCallback) { + this.nextCall.sendMessage( + this.pendingMessage, + this.pendingMessageCallback + ); + this.pendingMessage = null; + this.pendingMessageCallback = null; + } + } + + private processPendingStatus() { + if (this.pendingStatus) { + this.nextCall.sendStatus(this.pendingStatus); + this.pendingStatus = null; + } + } + + start(listener: InterceptingServerListener): void { + this.responder.start(interceptedListener => { + const fullInterceptedListener: FullServerListener = { + onReceiveMetadata: + interceptedListener?.onReceiveMetadata ?? + defaultServerListener.onReceiveMetadata, + onReceiveMessage: + interceptedListener?.onReceiveMessage ?? + defaultServerListener.onReceiveMessage, + onReceiveHalfClose: + interceptedListener?.onReceiveHalfClose ?? + defaultServerListener.onReceiveHalfClose, + onCancel: + interceptedListener?.onCancel ?? defaultServerListener.onCancel, + }; + const finalInterceptingListener = new InterceptingServerListenerImpl( + fullInterceptedListener, + listener + ); + this.nextCall.start(finalInterceptingListener); + }); + } + sendMetadata(metadata: Metadata): void { + this.processingMetadata = true; + this.sentMetadata = true; + this.responder.sendMetadata(metadata, interceptedMetadata => { + this.processingMetadata = false; + this.nextCall.sendMetadata(interceptedMetadata); + this.processPendingMessage(); + this.processPendingStatus(); + }); + } + sendMessage(message: any, callback: () => void): void { + this.processingMessage = true; + if (!this.sentMetadata) { + this.sendMetadata(new Metadata()); + } + this.responder.sendMessage(message, interceptedMessage => { + this.processingMessage = false; + if (this.processingMetadata) { + this.pendingMessage = interceptedMessage; + this.pendingMessageCallback = callback; + } else { + this.nextCall.sendMessage(interceptedMessage, callback); + } + }); + } + sendStatus(status: PartialStatusObject): void { + this.responder.sendStatus(status, interceptedStatus => { + if (this.processingMetadata || this.processingMessage) { + this.pendingStatus = interceptedStatus; + } else { + this.nextCall.sendStatus(interceptedStatus); + } + }); + } + startRead(): void { + this.nextCall.startRead(); + } + getPeer(): string { + return this.nextCall.getPeer(); + } + getDeadline(): Deadline { + return this.nextCall.getDeadline(); + } + getHost(): string { + return this.nextCall.getHost(); + } + getAuthContext(): AuthContext { + return this.nextCall.getAuthContext(); + } + getConnectionInfo(): ConnectionInfo { + return this.nextCall.getConnectionInfo(); + } + getMetricsRecorder(): PerRequestMetricRecorder { + return this.nextCall.getMetricsRecorder(); + } +} + +export interface ServerInterceptor { + ( + methodDescriptor: ServerMethodDefinition, + call: ServerInterceptingCallInterface + ): ServerInterceptingCall; +} + +interface DeadlineUnitIndexSignature { + [name: string]: number; +} + +const GRPC_ACCEPT_ENCODING_HEADER = 'grpc-accept-encoding'; +const GRPC_ENCODING_HEADER = 'grpc-encoding'; +const GRPC_MESSAGE_HEADER = 'grpc-message'; +const GRPC_STATUS_HEADER = 'grpc-status'; +const GRPC_TIMEOUT_HEADER = 'grpc-timeout'; +const DEADLINE_REGEX = /(\d{1,8})\s*([HMSmun])/; +const deadlineUnitsToMs: DeadlineUnitIndexSignature = { + H: 3600000, + M: 60000, + S: 1000, + m: 1, + u: 0.001, + n: 0.000001, +}; + +const defaultCompressionHeaders = { + // TODO(cjihrig): Remove these encoding headers from the default response + // once compression is integrated. + [GRPC_ACCEPT_ENCODING_HEADER]: 'identity,deflate,gzip', + [GRPC_ENCODING_HEADER]: 'identity', +}; +const defaultResponseHeaders = { + [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, + [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: 'application/grpc+proto', +}; +const defaultResponseOptions = { + waitForTrailers: true, +} as http2.ServerStreamResponseOptions; + +type ReadQueueEntryType = 'COMPRESSED' | 'READABLE' | 'HALF_CLOSE'; + +interface ReadQueueEntry { + type: ReadQueueEntryType; + compressedMessage: Buffer | null; + parsedMessage: any; +} + +export class BaseServerInterceptingCall + implements ServerInterceptingCallInterface +{ + private listener: InterceptingServerListener | null = null; + private metadata: Metadata; + private deadlineTimer: NodeJS.Timeout | null = null; + private deadline: Deadline = Infinity; + private maxSendMessageSize: number = DEFAULT_MAX_SEND_MESSAGE_LENGTH; + private maxReceiveMessageSize: number = DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; + private cancelled = false; + private metadataSent = false; + private wantTrailers = false; + private cancelNotified = false; + private incomingEncoding = 'identity'; + private decoder: StreamDecoder; + private readQueue: ReadQueueEntry[] = []; + private isReadPending = false; + private receivedHalfClose = false; + private streamEnded = false; + private host: string; + private connectionInfo: ConnectionInfo; + private metricsRecorder = new PerRequestMetricRecorder(); + private shouldSendMetrics: boolean; + + constructor( + private readonly stream: http2.ServerHttp2Stream, + headers: http2.IncomingHttpHeaders, + private readonly callEventTracker: CallEventTracker | null, + private readonly handler: Handler, + options: ChannelOptions + ) { + this.stream.once('error', (err: ServerErrorResponse) => { + /* We need an error handler to avoid uncaught error event exceptions, but + * there is nothing we can reasonably do here. Any error event should + * have a corresponding close event, which handles emitting the cancelled + * event. And the stream is now in a bad state, so we can't reasonably + * expect to be able to send an error over it. */ + }); + + this.stream.once('close', () => { + trace( + 'Request to method ' + + this.handler?.path + + ' stream closed with rstCode ' + + this.stream.rstCode + ); + + if (this.callEventTracker && !this.streamEnded) { + this.streamEnded = true; + this.callEventTracker.onStreamEnd(false); + this.callEventTracker.onCallEnd({ + code: Status.CANCELLED, + details: 'Stream closed before sending status', + metadata: null, + }); + } + + this.notifyOnCancel(); + }); + + this.stream.on('data', (data: Buffer) => { + this.handleDataFrame(data); + }); + this.stream.pause(); + + this.stream.on('end', () => { + this.handleEndEvent(); + }); + + if ('grpc.max_send_message_length' in options) { + this.maxSendMessageSize = options['grpc.max_send_message_length']!; + } + if ('grpc.max_receive_message_length' in options) { + this.maxReceiveMessageSize = options['grpc.max_receive_message_length']!; + } + + this.host = headers[':authority'] ?? headers.host!; + this.decoder = new StreamDecoder(this.maxReceiveMessageSize); + + const metadata = Metadata.fromHttp2Headers(headers); + + if (logging.isTracerEnabled(TRACER_NAME)) { + trace( + 'Request to ' + + this.handler.path + + ' received headers ' + + JSON.stringify(metadata.toJSON()) + ); + } + + const timeoutHeader = metadata.get(GRPC_TIMEOUT_HEADER); + + if (timeoutHeader.length > 0) { + this.handleTimeoutHeader(timeoutHeader[0] as string); + } + + const encodingHeader = metadata.get(GRPC_ENCODING_HEADER); + + if (encodingHeader.length > 0) { + this.incomingEncoding = encodingHeader[0] as string; + } + + // Remove several headers that should not be propagated to the application + metadata.remove(GRPC_TIMEOUT_HEADER); + metadata.remove(GRPC_ENCODING_HEADER); + metadata.remove(GRPC_ACCEPT_ENCODING_HEADER); + metadata.remove(http2.constants.HTTP2_HEADER_ACCEPT_ENCODING); + metadata.remove(http2.constants.HTTP2_HEADER_TE); + metadata.remove(http2.constants.HTTP2_HEADER_CONTENT_TYPE); + this.metadata = metadata; + + const socket = stream.session?.socket; + this.connectionInfo = { + localAddress: socket?.localAddress, + localPort: socket?.localPort, + remoteAddress: socket?.remoteAddress, + remotePort: socket?.remotePort + }; + this.shouldSendMetrics = !!options['grpc.server_call_metric_recording']; + } + + private handleTimeoutHeader(timeoutHeader: string) { + const match = timeoutHeader.toString().match(DEADLINE_REGEX); + + if (match === null) { + const status: PartialStatusObject = { + code: Status.INTERNAL, + details: `Invalid ${GRPC_TIMEOUT_HEADER} value "${timeoutHeader}"`, + metadata: null, + }; + // Wait for the constructor to complete before sending the error. + process.nextTick(() => { + this.sendStatus(status); + }); + return; + } + + const timeout = (+match[1] * deadlineUnitsToMs[match[2]]) | 0; + + const now = new Date(); + this.deadline = now.setMilliseconds(now.getMilliseconds() + timeout); + this.deadlineTimer = setTimeout(() => { + const status: PartialStatusObject = { + code: Status.DEADLINE_EXCEEDED, + details: 'Deadline exceeded', + metadata: null, + }; + this.sendStatus(status); + }, timeout); + } + + private checkCancelled(): boolean { + /* In some cases the stream can become destroyed before the close event + * fires. That creates a race condition that this check works around */ + if (!this.cancelled && (this.stream.destroyed || this.stream.closed)) { + this.notifyOnCancel(); + this.cancelled = true; + } + return this.cancelled; + } + private notifyOnCancel() { + if (this.cancelNotified) { + return; + } + this.cancelNotified = true; + this.cancelled = true; + process.nextTick(() => { + this.listener?.onCancel(); + }); + if (this.deadlineTimer) { + clearTimeout(this.deadlineTimer); + } + // Flush incoming data frames + this.stream.resume(); + } + + /** + * A server handler can start sending messages without explicitly sending + * metadata. In that case, we need to send headers before sending any + * messages. This function does that if necessary. + */ + private maybeSendMetadata() { + if (!this.metadataSent) { + this.sendMetadata(new Metadata()); + } + } + + /** + * Serialize a message to a length-delimited byte string. + * @param value + * @returns + */ + private serializeMessage(value: any) { + const messageBuffer = this.handler.serialize(value); + const byteLength = messageBuffer.byteLength; + const output = Buffer.allocUnsafe(byteLength + 5); + /* Note: response compression is currently not supported, so this + * compressed bit is always 0. */ + output.writeUInt8(0, 0); + output.writeUInt32BE(byteLength, 1); + messageBuffer.copy(output, 5); + return output; + } + + private decompressMessage( + message: Buffer, + encoding: string + ): Buffer | Promise { + const messageContents = message.subarray(5); + if (encoding === 'identity') { + return messageContents; + } else if (encoding === 'deflate' || encoding === 'gzip') { + let decompresser: zlib.Gunzip | zlib.Deflate; + if (encoding === 'deflate') { + decompresser = zlib.createInflate(); + } else { + decompresser = zlib.createGunzip(); + } + return new Promise((resolve, reject) => { + let totalLength = 0 + const messageParts: Buffer[] = []; + decompresser.on('data', (chunk: Buffer) => { + messageParts.push(chunk); + totalLength += chunk.byteLength; + if (this.maxReceiveMessageSize !== -1 && totalLength > this.maxReceiveMessageSize) { + decompresser.destroy(); + reject({ + code: Status.RESOURCE_EXHAUSTED, + details: `Received message that decompresses to a size larger than ${this.maxReceiveMessageSize}` + }); + } + }); + decompresser.on('end', () => { + resolve(Buffer.concat(messageParts)); + }); + decompresser.write(messageContents); + decompresser.end(); + }); + } else { + return Promise.reject({ + code: Status.UNIMPLEMENTED, + details: `Received message compressed with unsupported encoding "${encoding}"`, + }); + } + } + + private async decompressAndMaybePush(queueEntry: ReadQueueEntry) { + if (queueEntry.type !== 'COMPRESSED') { + throw new Error(`Invalid queue entry type: ${queueEntry.type}`); + } + + const compressed = queueEntry.compressedMessage!.readUInt8(0) === 1; + const compressedMessageEncoding = compressed + ? this.incomingEncoding + : 'identity'; + let decompressedMessage: Buffer; + try { + decompressedMessage = await this.decompressMessage( + queueEntry.compressedMessage!, + compressedMessageEncoding + ); + } catch (err) { + this.sendStatus(err as PartialStatusObject); + return; + } + try { + queueEntry.parsedMessage = this.handler.deserialize(decompressedMessage); + } catch (err) { + this.sendStatus({ + code: Status.INTERNAL, + details: `Error deserializing request: ${(err as Error).message}`, + }); + return; + } + queueEntry.type = 'READABLE'; + this.maybePushNextMessage(); + } + + private maybePushNextMessage() { + if ( + this.listener && + this.isReadPending && + this.readQueue.length > 0 && + this.readQueue[0].type !== 'COMPRESSED' + ) { + this.isReadPending = false; + const nextQueueEntry = this.readQueue.shift()!; + if (nextQueueEntry.type === 'READABLE') { + this.listener.onReceiveMessage(nextQueueEntry.parsedMessage); + } else { + // nextQueueEntry.type === 'HALF_CLOSE' + this.listener.onReceiveHalfClose(); + } + } + } + + private handleDataFrame(data: Buffer) { + if (this.checkCancelled()) { + return; + } + trace( + 'Request to ' + + this.handler.path + + ' received data frame of size ' + + data.length + ); + let rawMessages: Buffer[]; + try { + rawMessages = this.decoder.write(data); + } catch (e) { + this.sendStatus({ code: Status.RESOURCE_EXHAUSTED, details: (e as Error).message }); + return; + } + + for (const messageBytes of rawMessages) { + this.stream.pause(); + const queueEntry: ReadQueueEntry = { + type: 'COMPRESSED', + compressedMessage: messageBytes, + parsedMessage: null, + }; + this.readQueue.push(queueEntry); + this.decompressAndMaybePush(queueEntry); + this.callEventTracker?.addMessageReceived(); + } + } + private handleEndEvent() { + this.readQueue.push({ + type: 'HALF_CLOSE', + compressedMessage: null, + parsedMessage: null, + }); + this.receivedHalfClose = true; + this.maybePushNextMessage(); + } + start(listener: InterceptingServerListener): void { + trace('Request to ' + this.handler.path + ' start called'); + if (this.checkCancelled()) { + return; + } + this.listener = listener; + listener.onReceiveMetadata(this.metadata); + } + sendMetadata(metadata: Metadata): void { + if (this.checkCancelled()) { + return; + } + + if (this.metadataSent) { + return; + } + + this.metadataSent = true; + const custom = metadata ? metadata.toHttp2Headers() : null; + const headers = { + ...defaultResponseHeaders, + ...defaultCompressionHeaders, + ...custom, + }; + this.stream.respond(headers, defaultResponseOptions); + } + sendMessage(message: any, callback: () => void): void { + if (this.checkCancelled()) { + return; + } + let response: Buffer; + try { + response = this.serializeMessage(message); + } catch (e) { + this.sendStatus({ + code: Status.INTERNAL, + details: `Error serializing response: ${getErrorMessage(e)}`, + metadata: null, + }); + return; + } + + if ( + this.maxSendMessageSize !== -1 && + response.length - 5 > this.maxSendMessageSize + ) { + this.sendStatus({ + code: Status.RESOURCE_EXHAUSTED, + details: `Sent message larger than max (${response.length} vs. ${this.maxSendMessageSize})`, + metadata: null, + }); + return; + } + this.maybeSendMetadata(); + trace( + 'Request to ' + + this.handler.path + + ' sent data frame of size ' + + response.length + ); + this.stream.write(response, error => { + if (error) { + this.sendStatus({ + code: Status.INTERNAL, + details: `Error writing message: ${getErrorMessage(error)}`, + metadata: null, + }); + return; + } + this.callEventTracker?.addMessageSent(); + callback(); + }); + } + sendStatus(status: PartialStatusObject): void { + if (this.checkCancelled()) { + return; + } + + trace( + 'Request to method ' + + this.handler?.path + + ' ended with status code: ' + + Status[status.code] + + ' details: ' + + status.details + ); + + const statusMetadata = status.metadata?.clone() ?? new Metadata(); + if (this.shouldSendMetrics) { + statusMetadata.set(GRPC_METRICS_HEADER, this.metricsRecorder.serialize()); + } + + if (this.metadataSent) { + if (!this.wantTrailers) { + this.wantTrailers = true; + this.stream.once('wantTrailers', () => { + if (this.callEventTracker && !this.streamEnded) { + this.streamEnded = true; + this.callEventTracker.onStreamEnd(true); + this.callEventTracker.onCallEnd(status); + } + const trailersToSend: http2.OutgoingHttpHeaders = { + [GRPC_STATUS_HEADER]: status.code, + [GRPC_MESSAGE_HEADER]: encodeURI(status.details), + ...statusMetadata.toHttp2Headers(), + }; + + this.stream.sendTrailers(trailersToSend); + this.notifyOnCancel(); + }); + this.stream.end(); + } else { + this.notifyOnCancel(); + } + } else { + if (this.callEventTracker && !this.streamEnded) { + this.streamEnded = true; + this.callEventTracker.onStreamEnd(true); + this.callEventTracker.onCallEnd(status); + } + // Trailers-only response + const trailersToSend: http2.OutgoingHttpHeaders = { + [GRPC_STATUS_HEADER]: status.code, + [GRPC_MESSAGE_HEADER]: encodeURI(status.details), + ...defaultResponseHeaders, + ...statusMetadata.toHttp2Headers(), + }; + this.stream.respond(trailersToSend, { endStream: true }); + this.notifyOnCancel(); + } + } + startRead(): void { + trace('Request to ' + this.handler.path + ' startRead called'); + if (this.checkCancelled()) { + return; + } + this.isReadPending = true; + if (this.readQueue.length === 0) { + if (!this.receivedHalfClose) { + this.stream.resume(); + } + } else { + this.maybePushNextMessage(); + } + } + getPeer(): string { + const socket = this.stream.session?.socket; + if (socket?.remoteAddress) { + if (socket.remotePort) { + return `${socket.remoteAddress}:${socket.remotePort}`; + } else { + return socket.remoteAddress; + } + } else { + return 'unknown'; + } + } + getDeadline(): Deadline { + return this.deadline; + } + getHost(): string { + return this.host; + } + getAuthContext(): AuthContext { + if (this.stream.session?.socket instanceof TLSSocket) { + const peerCertificate = this.stream.session.socket.getPeerCertificate(); + return { + transportSecurityType: 'ssl', + sslPeerCertificate: peerCertificate.raw ? peerCertificate : undefined + } + } else { + return {}; + } + } + getConnectionInfo(): ConnectionInfo { + return this.connectionInfo; + } + getMetricsRecorder(): PerRequestMetricRecorder { + return this.metricsRecorder; + } +} + +export function getServerInterceptingCall( + interceptors: ServerInterceptor[], + stream: http2.ServerHttp2Stream, + headers: http2.IncomingHttpHeaders, + callEventTracker: CallEventTracker | null, + handler: Handler, + options: ChannelOptions +) { + const methodDefinition: ServerMethodDefinition = { + path: handler.path, + requestStream: handler.type === 'clientStream' || handler.type === 'bidi', + responseStream: handler.type === 'serverStream' || handler.type === 'bidi', + requestDeserialize: handler.deserialize, + responseSerialize: handler.serialize, + }; + const baseCall = new BaseServerInterceptingCall( + stream, + headers, + callEventTracker, + handler, + options + ); + return interceptors.reduce( + (call: ServerInterceptingCallInterface, interceptor: ServerInterceptor) => { + return interceptor(methodDefinition, call); + }, + baseCall + ); +} diff --git a/node_modules/@grpc/grpc-js/src/server.ts b/node_modules/@grpc/grpc-js/src/server.ts new file mode 100644 index 0000000..73d84b7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/server.ts @@ -0,0 +1,2212 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import * as http2 from 'http2'; +import * as util from 'util'; + +import { ServiceError } from './call'; +import { Status, LogVerbosity } from './constants'; +import { Deserialize, Serialize, ServiceDefinition } from './make-client'; +import { Metadata } from './metadata'; +import { + BidiStreamingHandler, + ClientStreamingHandler, + HandleCall, + Handler, + HandlerType, + sendUnaryData, + ServerDuplexStream, + ServerDuplexStreamImpl, + ServerReadableStream, + ServerStreamingHandler, + ServerUnaryCall, + ServerWritableStream, + ServerWritableStreamImpl, + UnaryHandler, + ServerErrorResponse, + ServerStatusResponse, + serverErrorToStatus, +} from './server-call'; +import { SecureContextWatcher, ServerCredentials } from './server-credentials'; +import { ChannelOptions } from './channel-options'; +import { + createResolver, + ResolverListener, + mapUriDefaultScheme, +} from './resolver'; +import * as logging from './logging'; +import { + SubchannelAddress, + isTcpSubchannelAddress, + subchannelAddressToString, + stringToSubchannelAddress, +} from './subchannel-address'; +import { + GrpcUri, + combineHostPort, + parseUri, + splitHostPort, + uriToString, +} from './uri-parser'; +import { + ChannelzCallTracker, + ChannelzCallTrackerStub, + ChannelzChildrenTracker, + ChannelzChildrenTrackerStub, + ChannelzTrace, + ChannelzTraceStub, + registerChannelzServer, + registerChannelzSocket, + ServerInfo, + ServerRef, + SocketInfo, + SocketRef, + TlsInfo, + unregisterChannelzRef, +} from './channelz'; +import { CipherNameAndProtocol, TLSSocket } from 'tls'; +import { + ServerInterceptingCallInterface, + ServerInterceptor, + getServerInterceptingCall, +} from './server-interceptors'; +import { PartialStatusObject } from './call-interface'; +import { CallEventTracker } from './transport'; +import { Socket } from 'net'; +import { Duplex } from 'stream'; + +const UNLIMITED_CONNECTION_AGE_MS = ~(1 << 31); +const KEEPALIVE_MAX_TIME_MS = ~(1 << 31); +const KEEPALIVE_TIMEOUT_MS = 20000; +const MAX_CONNECTION_IDLE_MS = ~(1 << 31); + +const { HTTP2_HEADER_PATH } = http2.constants; + +const TRACER_NAME = 'server'; +const kMaxAge = Buffer.from('max_age'); + +function serverCallTrace(text: string) { + logging.trace(LogVerbosity.DEBUG, 'server_call', text); +} + +type AnyHttp2Server = http2.Http2Server | http2.Http2SecureServer; + +interface BindResult { + port: number; + count: number; + errors: string[]; +} + +interface SingleAddressBindResult { + port: number; + error?: string; +} + +function noop(): void {} + +/** + * Decorator to wrap a class method with util.deprecate + * @param message The message to output if the deprecated method is called + * @returns + */ +function deprecate(message: string) { + return function ( + target: (this: This, ...args: Args) => Return, + context: ClassMethodDecoratorContext< + This, + (this: This, ...args: Args) => Return + > + ) { + return util.deprecate(target, message); + }; +} + +function getUnimplementedStatusResponse( + methodName: string +): PartialStatusObject { + return { + code: Status.UNIMPLEMENTED, + details: `The server does not implement the method ${methodName}`, + }; +} + +/* eslint-disable @typescript-eslint/no-explicit-any */ +type UntypedUnaryHandler = UnaryHandler; +type UntypedClientStreamingHandler = ClientStreamingHandler; +type UntypedServerStreamingHandler = ServerStreamingHandler; +type UntypedBidiStreamingHandler = BidiStreamingHandler; +export type UntypedHandleCall = HandleCall; +type UntypedHandler = Handler; +export interface UntypedServiceImplementation { + [name: string]: UntypedHandleCall; +} + +function getDefaultHandler(handlerType: HandlerType, methodName: string) { + const unimplementedStatusResponse = + getUnimplementedStatusResponse(methodName); + switch (handlerType) { + case 'unary': + return ( + call: ServerUnaryCall, + callback: sendUnaryData + ) => { + callback(unimplementedStatusResponse as ServiceError, null); + }; + case 'clientStream': + return ( + call: ServerReadableStream, + callback: sendUnaryData + ) => { + callback(unimplementedStatusResponse as ServiceError, null); + }; + case 'serverStream': + return (call: ServerWritableStream) => { + call.emit('error', unimplementedStatusResponse); + }; + case 'bidi': + return (call: ServerDuplexStream) => { + call.emit('error', unimplementedStatusResponse); + }; + default: + throw new Error(`Invalid handlerType ${handlerType}`); + } +} + +interface ChannelzSessionInfo { + ref: SocketRef; + streamTracker: ChannelzCallTracker | ChannelzCallTrackerStub; + messagesSent: number; + messagesReceived: number; + keepAlivesSent: number; + lastMessageSentTimestamp: Date | null; + lastMessageReceivedTimestamp: Date | null; +} + +/** + * Information related to a single invocation of bindAsync. This should be + * tracked in a map keyed by target string, normalized with a pass through + * parseUri -> mapUriDefaultScheme -> uriToString. If the target has a port + * number and the port number is 0, the target string is modified with the + * concrete bound port. + */ +interface BoundPort { + /** + * The key used to refer to this object in the boundPorts map. + */ + mapKey: string; + /** + * The target string, passed through parseUri -> mapUriDefaultScheme. Used + * to determine the final key when the port number is 0. + */ + originalUri: GrpcUri; + /** + * If there is a pending bindAsync operation, this is a promise that resolves + * with the port number when that operation succeeds. If there is no such + * operation pending, this is null. + */ + completionPromise: Promise | null; + /** + * The port number that was actually bound. Populated only after + * completionPromise resolves. + */ + portNumber: number; + /** + * Set by unbind if called while pending is true. + */ + cancelled: boolean; + /** + * The credentials object passed to the original bindAsync call. + */ + credentials: ServerCredentials; + /** + * The set of servers associated with this listening port. A target string + * that expands to multiple addresses will result in multiple listening + * servers. + */ + listeningServers: Set; +} + +/** + * Should be in a map keyed by AnyHttp2Server. + */ +interface Http2ServerInfo { + channelzRef: SocketRef; + sessions: Set; + ownsChannelzRef: boolean; +} + +interface SessionIdleTimeoutTracker { + activeStreams: number; + lastIdle: number; + timeout: NodeJS.Timeout; + onClose: (session: http2.ServerHttp2Session) => void | null; +} + +export interface ServerOptions extends ChannelOptions { + interceptors?: ServerInterceptor[]; +} + +export interface ConnectionInjector { + injectConnection(connection: Duplex): void; + drain(graceTimeMs: number): void; + destroy(): void; +} + +export class Server { + private boundPorts: Map = new Map(); + private http2Servers: Map = new Map(); + private sessionIdleTimeouts = new Map< + http2.ServerHttp2Session, + SessionIdleTimeoutTracker + >(); + + private handlers: Map = new Map< + string, + UntypedHandler + >(); + private sessions = new Map(); + /** + * This field only exists to ensure that the start method throws an error if + * it is called twice, as it did previously. + */ + private started = false; + private shutdown = false; + private options: ServerOptions; + private serverAddressString = 'null'; + + // Channelz Info + private readonly channelzEnabled: boolean = true; + private channelzRef: ServerRef; + private channelzTrace: ChannelzTrace | ChannelzTraceStub; + private callTracker: ChannelzCallTracker | ChannelzCallTrackerStub; + private listenerChildrenTracker: + | ChannelzChildrenTracker + | ChannelzChildrenTrackerStub; + private sessionChildrenTracker: + | ChannelzChildrenTracker + | ChannelzChildrenTrackerStub; + + private readonly maxConnectionAgeMs: number; + private readonly maxConnectionAgeGraceMs: number; + + private readonly keepaliveTimeMs: number; + private readonly keepaliveTimeoutMs: number; + + private readonly sessionIdleTimeout: number; + + private readonly interceptors: ServerInterceptor[]; + + /** + * Options that will be used to construct all Http2Server instances for this + * Server. + */ + private commonServerOptions: http2.ServerOptions; + + constructor(options?: ServerOptions) { + this.options = options ?? {}; + if (this.options['grpc.enable_channelz'] === 0) { + this.channelzEnabled = false; + this.channelzTrace = new ChannelzTraceStub(); + this.callTracker = new ChannelzCallTrackerStub(); + this.listenerChildrenTracker = new ChannelzChildrenTrackerStub(); + this.sessionChildrenTracker = new ChannelzChildrenTrackerStub(); + } else { + this.channelzTrace = new ChannelzTrace(); + this.callTracker = new ChannelzCallTracker(); + this.listenerChildrenTracker = new ChannelzChildrenTracker(); + this.sessionChildrenTracker = new ChannelzChildrenTracker(); + } + + this.channelzRef = registerChannelzServer( + 'server', + () => this.getChannelzInfo(), + this.channelzEnabled + ); + + this.channelzTrace.addTrace('CT_INFO', 'Server created'); + this.maxConnectionAgeMs = + this.options['grpc.max_connection_age_ms'] ?? UNLIMITED_CONNECTION_AGE_MS; + this.maxConnectionAgeGraceMs = + this.options['grpc.max_connection_age_grace_ms'] ?? + UNLIMITED_CONNECTION_AGE_MS; + this.keepaliveTimeMs = + this.options['grpc.keepalive_time_ms'] ?? KEEPALIVE_MAX_TIME_MS; + this.keepaliveTimeoutMs = + this.options['grpc.keepalive_timeout_ms'] ?? KEEPALIVE_TIMEOUT_MS; + this.sessionIdleTimeout = + this.options['grpc.max_connection_idle_ms'] ?? MAX_CONNECTION_IDLE_MS; + + this.commonServerOptions = { + maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER, + }; + if ('grpc-node.max_session_memory' in this.options) { + this.commonServerOptions.maxSessionMemory = + this.options['grpc-node.max_session_memory']; + } else { + /* By default, set a very large max session memory limit, to effectively + * disable enforcement of the limit. Some testing indicates that Node's + * behavior degrades badly when this limit is reached, so we solve that + * by disabling the check entirely. */ + this.commonServerOptions.maxSessionMemory = Number.MAX_SAFE_INTEGER; + } + if ('grpc.max_concurrent_streams' in this.options) { + this.commonServerOptions.settings = { + maxConcurrentStreams: this.options['grpc.max_concurrent_streams'], + }; + } + this.interceptors = this.options.interceptors ?? []; + this.trace('Server constructed'); + } + + private getChannelzInfo(): ServerInfo { + return { + trace: this.channelzTrace, + callTracker: this.callTracker, + listenerChildren: this.listenerChildrenTracker.getChildLists(), + sessionChildren: this.sessionChildrenTracker.getChildLists(), + }; + } + + private getChannelzSessionInfo( + session: http2.ServerHttp2Session + ): SocketInfo { + const sessionInfo = this.sessions.get(session)!; + const sessionSocket = session.socket; + const remoteAddress = sessionSocket.remoteAddress + ? stringToSubchannelAddress( + sessionSocket.remoteAddress, + sessionSocket.remotePort + ) + : null; + const localAddress = sessionSocket.localAddress + ? stringToSubchannelAddress( + sessionSocket.localAddress!, + sessionSocket.localPort + ) + : null; + let tlsInfo: TlsInfo | null; + if (session.encrypted) { + const tlsSocket: TLSSocket = sessionSocket as TLSSocket; + const cipherInfo: CipherNameAndProtocol & { standardName?: string } = + tlsSocket.getCipher(); + const certificate = tlsSocket.getCertificate(); + const peerCertificate = tlsSocket.getPeerCertificate(); + tlsInfo = { + cipherSuiteStandardName: cipherInfo.standardName ?? null, + cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, + localCertificate: + certificate && 'raw' in certificate ? certificate.raw : null, + remoteCertificate: + peerCertificate && 'raw' in peerCertificate + ? peerCertificate.raw + : null, + }; + } else { + tlsInfo = null; + } + const socketInfo: SocketInfo = { + remoteAddress: remoteAddress, + localAddress: localAddress, + security: tlsInfo, + remoteName: null, + streamsStarted: sessionInfo.streamTracker.callsStarted, + streamsSucceeded: sessionInfo.streamTracker.callsSucceeded, + streamsFailed: sessionInfo.streamTracker.callsFailed, + messagesSent: sessionInfo.messagesSent, + messagesReceived: sessionInfo.messagesReceived, + keepAlivesSent: sessionInfo.keepAlivesSent, + lastLocalStreamCreatedTimestamp: null, + lastRemoteStreamCreatedTimestamp: + sessionInfo.streamTracker.lastCallStartedTimestamp, + lastMessageSentTimestamp: sessionInfo.lastMessageSentTimestamp, + lastMessageReceivedTimestamp: sessionInfo.lastMessageReceivedTimestamp, + localFlowControlWindow: session.state.localWindowSize ?? null, + remoteFlowControlWindow: session.state.remoteWindowSize ?? null, + }; + return socketInfo; + } + + private trace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + TRACER_NAME, + '(' + this.channelzRef.id + ') ' + text + ); + } + + private keepaliveTrace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + 'keepalive', + '(' + this.channelzRef.id + ') ' + text + ); + } + + addProtoService(): never { + throw new Error('Not implemented. Use addService() instead'); + } + + addService( + service: ServiceDefinition, + implementation: UntypedServiceImplementation + ): void { + if ( + service === null || + typeof service !== 'object' || + implementation === null || + typeof implementation !== 'object' + ) { + throw new Error('addService() requires two objects as arguments'); + } + + const serviceKeys = Object.keys(service); + + if (serviceKeys.length === 0) { + throw new Error('Cannot add an empty service to a server'); + } + + serviceKeys.forEach(name => { + const attrs = service[name]; + let methodType: HandlerType; + + if (attrs.requestStream) { + if (attrs.responseStream) { + methodType = 'bidi'; + } else { + methodType = 'clientStream'; + } + } else { + if (attrs.responseStream) { + methodType = 'serverStream'; + } else { + methodType = 'unary'; + } + } + + let implFn = implementation[name]; + let impl; + + if (implFn === undefined && typeof attrs.originalName === 'string') { + implFn = implementation[attrs.originalName]; + } + + if (implFn !== undefined) { + impl = implFn.bind(implementation); + } else { + impl = getDefaultHandler(methodType, name); + } + + const success = this.register( + attrs.path, + impl as UntypedHandleCall, + attrs.responseSerialize, + attrs.requestDeserialize, + methodType + ); + + if (success === false) { + throw new Error(`Method handler for ${attrs.path} already provided.`); + } + }); + } + + removeService(service: ServiceDefinition): void { + if (service === null || typeof service !== 'object') { + throw new Error('removeService() requires object as argument'); + } + + const serviceKeys = Object.keys(service); + serviceKeys.forEach(name => { + const attrs = service[name]; + this.unregister(attrs.path); + }); + } + + bind(port: string, creds: ServerCredentials): never { + throw new Error('Not implemented. Use bindAsync() instead'); + } + + /** + * This API is experimental, so API stability is not guaranteed across minor versions. + * @param boundAddress + * @returns + */ + protected experimentalRegisterListenerToChannelz(boundAddress: SubchannelAddress) { + return registerChannelzSocket( + subchannelAddressToString(boundAddress), + () => { + return { + localAddress: boundAddress, + remoteAddress: null, + security: null, + remoteName: null, + streamsStarted: 0, + streamsSucceeded: 0, + streamsFailed: 0, + messagesSent: 0, + messagesReceived: 0, + keepAlivesSent: 0, + lastLocalStreamCreatedTimestamp: null, + lastRemoteStreamCreatedTimestamp: null, + lastMessageSentTimestamp: null, + lastMessageReceivedTimestamp: null, + localFlowControlWindow: null, + remoteFlowControlWindow: null, + }; + }, + this.channelzEnabled + ); + } + + protected experimentalUnregisterListenerFromChannelz(channelzRef: SocketRef) { + unregisterChannelzRef(channelzRef); + } + + private createHttp2Server(credentials: ServerCredentials) { + let http2Server: http2.Http2Server | http2.Http2SecureServer; + if (credentials._isSecure()) { + const constructorOptions = credentials._getConstructorOptions(); + const contextOptions = credentials._getSecureContextOptions(); + const secureServerOptions: http2.SecureServerOptions = { + ...this.commonServerOptions, + ...constructorOptions, + ...contextOptions, + enableTrace: this.options['grpc-node.tls_enable_trace'] === 1 + }; + let areCredentialsValid = contextOptions !== null; + this.trace('Initial credentials valid: ' + areCredentialsValid); + http2Server = http2.createSecureServer(secureServerOptions); + http2Server.prependListener('connection', (socket: Socket) => { + if (!areCredentialsValid) { + this.trace('Dropped connection from ' + JSON.stringify(socket.address()) + ' due to unloaded credentials'); + socket.destroy(); + } + }); + http2Server.on('secureConnection', (socket: TLSSocket) => { + /* These errors need to be handled by the user of Http2SecureServer, + * according to https://github.com/nodejs/node/issues/35824 */ + socket.on('error', (e: Error) => { + this.trace( + 'An incoming TLS connection closed with error: ' + e.message + ); + }); + }); + const credsWatcher: SecureContextWatcher = options => { + if (options) { + const secureServer = http2Server as http2.Http2SecureServer; + try { + secureServer.setSecureContext(options); + } catch (e) { + logging.log(LogVerbosity.ERROR, 'Failed to set secure context with error ' + (e as Error).message); + options = null; + } + } + areCredentialsValid = options !== null; + this.trace('Post-update credentials valid: ' + areCredentialsValid); + } + credentials._addWatcher(credsWatcher); + http2Server.on('close', () => { + credentials._removeWatcher(credsWatcher); + }); + } else { + http2Server = http2.createServer(this.commonServerOptions); + } + + http2Server.setTimeout(0, noop); + this._setupHandlers(http2Server, credentials._getInterceptors()); + return http2Server; + } + + private bindOneAddress( + address: SubchannelAddress, + boundPortObject: BoundPort + ): Promise { + this.trace('Attempting to bind ' + subchannelAddressToString(address)); + const http2Server = this.createHttp2Server(boundPortObject.credentials); + return new Promise((resolve, reject) => { + const onError = (err: Error) => { + this.trace( + 'Failed to bind ' + + subchannelAddressToString(address) + + ' with error ' + + err.message + ); + resolve({ + port: 'port' in address ? address.port : 1, + error: err.message, + }); + }; + + http2Server.once('error', onError); + + http2Server.listen(address, () => { + const boundAddress = http2Server.address()!; + let boundSubchannelAddress: SubchannelAddress; + if (typeof boundAddress === 'string') { + boundSubchannelAddress = { + path: boundAddress, + }; + } else { + boundSubchannelAddress = { + host: boundAddress.address, + port: boundAddress.port, + }; + } + + const channelzRef = this.experimentalRegisterListenerToChannelz( + boundSubchannelAddress + ); + this.listenerChildrenTracker.refChild(channelzRef); + + this.http2Servers.set(http2Server, { + channelzRef: channelzRef, + sessions: new Set(), + ownsChannelzRef: true + }); + boundPortObject.listeningServers.add(http2Server); + this.trace( + 'Successfully bound ' + + subchannelAddressToString(boundSubchannelAddress) + ); + resolve({ + port: + 'port' in boundSubchannelAddress ? boundSubchannelAddress.port : 1, + }); + http2Server.removeListener('error', onError); + }); + }); + } + + private async bindManyPorts( + addressList: SubchannelAddress[], + boundPortObject: BoundPort + ): Promise { + if (addressList.length === 0) { + return { + count: 0, + port: 0, + errors: [], + }; + } + if (isTcpSubchannelAddress(addressList[0]) && addressList[0].port === 0) { + /* If binding to port 0, first try to bind the first address, then bind + * the rest of the address list to the specific port that it binds. */ + const firstAddressResult = await this.bindOneAddress( + addressList[0], + boundPortObject + ); + if (firstAddressResult.error) { + /* If the first address fails to bind, try the same operation starting + * from the second item in the list. */ + const restAddressResult = await this.bindManyPorts( + addressList.slice(1), + boundPortObject + ); + return { + ...restAddressResult, + errors: [firstAddressResult.error, ...restAddressResult.errors], + }; + } else { + const restAddresses = addressList + .slice(1) + .map(address => + isTcpSubchannelAddress(address) + ? { host: address.host, port: firstAddressResult.port } + : address + ); + const restAddressResult = await Promise.all( + restAddresses.map(address => + this.bindOneAddress(address, boundPortObject) + ) + ); + const allResults = [firstAddressResult, ...restAddressResult]; + return { + count: allResults.filter(result => result.error === undefined).length, + port: firstAddressResult.port, + errors: allResults + .filter(result => result.error) + .map(result => result.error!), + }; + } + } else { + const allResults = await Promise.all( + addressList.map(address => + this.bindOneAddress(address, boundPortObject) + ) + ); + return { + count: allResults.filter(result => result.error === undefined).length, + port: allResults[0].port, + errors: allResults + .filter(result => result.error) + .map(result => result.error!), + }; + } + } + + private async bindAddressList( + addressList: SubchannelAddress[], + boundPortObject: BoundPort + ): Promise { + const bindResult = await this.bindManyPorts(addressList, boundPortObject); + if (bindResult.count > 0) { + if (bindResult.count < addressList.length) { + logging.log( + LogVerbosity.INFO, + `WARNING Only ${bindResult.count} addresses added out of total ${addressList.length} resolved` + ); + } + return bindResult.port; + } else { + const errorString = `No address added out of total ${addressList.length} resolved`; + logging.log(LogVerbosity.ERROR, errorString); + throw new Error( + `${errorString} errors: [${bindResult.errors.join(',')}]` + ); + } + } + + private resolvePort(port: GrpcUri): Promise { + return new Promise((resolve, reject) => { + let seenResolution = false; + const resolverListener: ResolverListener = ( + endpointList, + attributes, + serviceConfig, + resolutionNote + ) => { + if (seenResolution) { + return true; + } + seenResolution = true; + if (!endpointList.ok) { + reject(new Error(endpointList.error.details)); + return true; + } + const addressList = ([] as SubchannelAddress[]).concat( + ...endpointList.value.map(endpoint => endpoint.addresses) + ); + if (addressList.length === 0) { + reject(new Error(`No addresses resolved for port ${port}`)); + return true; + } + resolve(addressList); + return true; + } + const resolver = createResolver(port, resolverListener, this.options); + resolver.updateResolution(); + }); + } + + private async bindPort( + port: GrpcUri, + boundPortObject: BoundPort + ): Promise { + const addressList = await this.resolvePort(port); + if (boundPortObject.cancelled) { + this.completeUnbind(boundPortObject); + throw new Error('bindAsync operation cancelled by unbind call'); + } + const portNumber = await this.bindAddressList(addressList, boundPortObject); + if (boundPortObject.cancelled) { + this.completeUnbind(boundPortObject); + throw new Error('bindAsync operation cancelled by unbind call'); + } + return portNumber; + } + + private normalizePort(port: string): GrpcUri { + const initialPortUri = parseUri(port); + if (initialPortUri === null) { + throw new Error(`Could not parse port "${port}"`); + } + const portUri = mapUriDefaultScheme(initialPortUri); + if (portUri === null) { + throw new Error(`Could not get a default scheme for port "${port}"`); + } + return portUri; + } + + bindAsync( + port: string, + creds: ServerCredentials, + callback: (error: Error | null, port: number) => void + ): void { + if (this.shutdown) { + throw new Error('bindAsync called after shutdown'); + } + if (typeof port !== 'string') { + throw new TypeError('port must be a string'); + } + + if (creds === null || !(creds instanceof ServerCredentials)) { + throw new TypeError('creds must be a ServerCredentials object'); + } + + if (typeof callback !== 'function') { + throw new TypeError('callback must be a function'); + } + + this.trace('bindAsync port=' + port); + + const portUri = this.normalizePort(port); + + const deferredCallback = (error: Error | null, port: number) => { + process.nextTick(() => callback(error, port)); + }; + + /* First, if this port is already bound or that bind operation is in + * progress, use that result. */ + let boundPortObject = this.boundPorts.get(uriToString(portUri)); + if (boundPortObject) { + if (!creds._equals(boundPortObject.credentials)) { + deferredCallback( + new Error(`${port} already bound with incompatible credentials`), + 0 + ); + return; + } + /* If that operation has previously been cancelled by an unbind call, + * uncancel it. */ + boundPortObject.cancelled = false; + if (boundPortObject.completionPromise) { + boundPortObject.completionPromise.then( + portNum => callback(null, portNum), + error => callback(error as Error, 0) + ); + } else { + deferredCallback(null, boundPortObject.portNumber); + } + return; + } + boundPortObject = { + mapKey: uriToString(portUri), + originalUri: portUri, + completionPromise: null, + cancelled: false, + portNumber: 0, + credentials: creds, + listeningServers: new Set(), + }; + const splitPort = splitHostPort(portUri.path); + const completionPromise = this.bindPort(portUri, boundPortObject); + boundPortObject.completionPromise = completionPromise; + /* If the port number is 0, defer populating the map entry until after the + * bind operation completes and we have a specific port number. Otherwise, + * populate it immediately. */ + if (splitPort?.port === 0) { + completionPromise.then( + portNum => { + const finalUri: GrpcUri = { + scheme: portUri.scheme, + authority: portUri.authority, + path: combineHostPort({ host: splitPort.host, port: portNum }), + }; + boundPortObject!.mapKey = uriToString(finalUri); + boundPortObject!.completionPromise = null; + boundPortObject!.portNumber = portNum; + this.boundPorts.set(boundPortObject!.mapKey, boundPortObject!); + callback(null, portNum); + }, + error => { + callback(error, 0); + } + ); + } else { + this.boundPorts.set(boundPortObject.mapKey, boundPortObject); + completionPromise.then( + portNum => { + boundPortObject!.completionPromise = null; + boundPortObject!.portNumber = portNum; + callback(null, portNum); + }, + error => { + callback(error, 0); + } + ); + } + } + + private registerInjectorToChannelz() { + return registerChannelzSocket( + 'injector', + () => { + return { + localAddress: null, + remoteAddress: null, + security: null, + remoteName: null, + streamsStarted: 0, + streamsSucceeded: 0, + streamsFailed: 0, + messagesSent: 0, + messagesReceived: 0, + keepAlivesSent: 0, + lastLocalStreamCreatedTimestamp: null, + lastRemoteStreamCreatedTimestamp: null, + lastMessageSentTimestamp: null, + lastMessageReceivedTimestamp: null, + localFlowControlWindow: null, + remoteFlowControlWindow: null, + }; + }, + this.channelzEnabled + ); + } + + /** + * This API is experimental, so API stability is not guaranteed across minor versions. + * @param credentials + * @param channelzRef + * @returns + */ + protected experimentalCreateConnectionInjectorWithChannelzRef(credentials: ServerCredentials, channelzRef: SocketRef, ownsChannelzRef=false) { + if (credentials === null || !(credentials instanceof ServerCredentials)) { + throw new TypeError('creds must be a ServerCredentials object'); + } + if (this.channelzEnabled) { + this.listenerChildrenTracker.refChild(channelzRef); + } + const server = this.createHttp2Server(credentials); + const sessionsSet: Set = new Set(); + this.http2Servers.set(server, { + channelzRef: channelzRef, + sessions: sessionsSet, + ownsChannelzRef + }); + return { + injectConnection: (connection: Duplex) => { + server.emit('connection', connection); + }, + drain: (graceTimeMs: number) => { + for (const session of sessionsSet) { + this.closeSession(session); + } + setTimeout(() => { + for (const session of sessionsSet) { + session.destroy(http2.constants.NGHTTP2_CANCEL as any); + } + }, graceTimeMs).unref?.(); + }, + destroy: () => { + this.closeServer(server) + for (const session of sessionsSet) { + this.closeSession(session); + } + } + }; + } + + createConnectionInjector(credentials: ServerCredentials): ConnectionInjector { + if (credentials === null || !(credentials instanceof ServerCredentials)) { + throw new TypeError('creds must be a ServerCredentials object'); + } + const channelzRef = this.registerInjectorToChannelz(); + return this.experimentalCreateConnectionInjectorWithChannelzRef(credentials, channelzRef, true); + } + + private closeServer(server: AnyHttp2Server, callback?: () => void) { + this.trace( + 'Closing server with address ' + JSON.stringify(server.address()) + ); + const serverInfo = this.http2Servers.get(server); + server.close(() => { + if (serverInfo && serverInfo.ownsChannelzRef) { + this.listenerChildrenTracker.unrefChild(serverInfo.channelzRef); + unregisterChannelzRef(serverInfo.channelzRef); + } + this.http2Servers.delete(server); + callback?.(); + }); + } + + private closeSession( + session: http2.ServerHttp2Session, + callback?: () => void + ) { + this.trace('Closing session initiated by ' + session.socket?.remoteAddress); + const sessionInfo = this.sessions.get(session); + const closeCallback = () => { + if (sessionInfo) { + this.sessionChildrenTracker.unrefChild(sessionInfo.ref); + unregisterChannelzRef(sessionInfo.ref); + } + callback?.(); + }; + if (session.closed) { + queueMicrotask(closeCallback); + } else { + session.close(closeCallback); + } + } + + private completeUnbind(boundPortObject: BoundPort) { + for (const server of boundPortObject.listeningServers) { + const serverInfo = this.http2Servers.get(server); + this.closeServer(server, () => { + boundPortObject.listeningServers.delete(server); + }); + if (serverInfo) { + for (const session of serverInfo.sessions) { + this.closeSession(session); + } + } + } + this.boundPorts.delete(boundPortObject.mapKey); + } + + /** + * Unbind a previously bound port, or cancel an in-progress bindAsync + * operation. If port 0 was bound, only the actual bound port can be + * unbound. For example, if bindAsync was called with "localhost:0" and the + * bound port result was 54321, it can be unbound as "localhost:54321". + * @param port + */ + unbind(port: string): void { + this.trace('unbind port=' + port); + const portUri = this.normalizePort(port); + const splitPort = splitHostPort(portUri.path); + if (splitPort?.port === 0) { + throw new Error('Cannot unbind port 0'); + } + const boundPortObject = this.boundPorts.get(uriToString(portUri)); + if (boundPortObject) { + this.trace( + 'unbinding ' + + boundPortObject.mapKey + + ' originally bound as ' + + uriToString(boundPortObject.originalUri) + ); + /* If the bind operation is pending, the cancelled flag will trigger + * the unbind operation later. */ + if (boundPortObject.completionPromise) { + boundPortObject.cancelled = true; + } else { + this.completeUnbind(boundPortObject); + } + } + } + + /** + * Gracefully close all connections associated with a previously bound port. + * After the grace time, forcefully close all remaining open connections. + * + * If port 0 was bound, only the actual bound port can be + * drained. For example, if bindAsync was called with "localhost:0" and the + * bound port result was 54321, it can be drained as "localhost:54321". + * @param port + * @param graceTimeMs + * @returns + */ + drain(port: string, graceTimeMs: number): void { + this.trace('drain port=' + port + ' graceTimeMs=' + graceTimeMs); + const portUri = this.normalizePort(port); + const splitPort = splitHostPort(portUri.path); + if (splitPort?.port === 0) { + throw new Error('Cannot drain port 0'); + } + const boundPortObject = this.boundPorts.get(uriToString(portUri)); + if (!boundPortObject) { + return; + } + const allSessions: Set = new Set(); + for (const http2Server of boundPortObject.listeningServers) { + const serverEntry = this.http2Servers.get(http2Server); + if (serverEntry) { + for (const session of serverEntry.sessions) { + allSessions.add(session); + this.closeSession(session, () => { + allSessions.delete(session); + }); + } + } + } + /* After the grace time ends, send another goaway to all remaining sessions + * with the CANCEL code. */ + setTimeout(() => { + for (const session of allSessions) { + session.destroy(http2.constants.NGHTTP2_CANCEL as any); + } + }, graceTimeMs).unref?.(); + } + + forceShutdown(): void { + for (const boundPortObject of this.boundPorts.values()) { + boundPortObject.cancelled = true; + } + this.boundPorts.clear(); + // Close the server if it is still running. + for (const server of this.http2Servers.keys()) { + this.closeServer(server); + } + + // Always destroy any available sessions. It's possible that one or more + // tryShutdown() calls are in progress. Don't wait on them to finish. + this.sessions.forEach((channelzInfo, session) => { + this.closeSession(session); + // Cast NGHTTP2_CANCEL to any because TypeScript doesn't seem to + // recognize destroy(code) as a valid signature. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + session.destroy(http2.constants.NGHTTP2_CANCEL as any); + }); + this.sessions.clear(); + unregisterChannelzRef(this.channelzRef); + + this.shutdown = true; + } + + register( + name: string, + handler: HandleCall, + serialize: Serialize, + deserialize: Deserialize, + type: string + ): boolean { + if (this.handlers.has(name)) { + return false; + } + + this.handlers.set(name, { + func: handler, + serialize, + deserialize, + type, + path: name, + } as UntypedHandler); + return true; + } + + unregister(name: string): boolean { + return this.handlers.delete(name); + } + + /** + * @deprecated No longer needed as of version 1.10.x + */ + @deprecate( + 'Calling start() is no longer necessary. It can be safely omitted.' + ) + start(): void { + if ( + this.http2Servers.size === 0 || + [...this.http2Servers.keys()].every(server => !server.listening) + ) { + throw new Error('server must be bound in order to start'); + } + + if (this.started === true) { + throw new Error('server is already started'); + } + this.started = true; + } + + tryShutdown(callback: (error?: Error) => void): void { + const wrappedCallback = (error?: Error) => { + unregisterChannelzRef(this.channelzRef); + callback(error); + }; + let pendingChecks = 0; + + function maybeCallback(): void { + pendingChecks--; + + if (pendingChecks === 0) { + wrappedCallback(); + } + } + this.shutdown = true; + + for (const [serverKey, server] of this.http2Servers.entries()) { + pendingChecks++; + const serverString = server.channelzRef.name; + this.trace('Waiting for server ' + serverString + ' to close'); + this.closeServer(serverKey, () => { + this.trace('Server ' + serverString + ' finished closing'); + maybeCallback(); + }); + + for (const session of server.sessions.keys()) { + pendingChecks++; + const sessionString = session.socket?.remoteAddress; + this.trace('Waiting for session ' + sessionString + ' to close'); + this.closeSession(session, () => { + this.trace('Session ' + sessionString + ' finished closing'); + maybeCallback(); + }); + } + } + + if (pendingChecks === 0) { + wrappedCallback(); + } + } + + addHttp2Port(): never { + throw new Error('Not yet implemented'); + } + + /** + * Get the channelz reference object for this server. The returned value is + * garbage if channelz is disabled for this server. + * @returns + */ + getChannelzRef() { + return this.channelzRef; + } + + private _verifyContentType( + stream: http2.ServerHttp2Stream, + headers: http2.IncomingHttpHeaders + ): boolean { + const contentType = headers[http2.constants.HTTP2_HEADER_CONTENT_TYPE]; + + if ( + typeof contentType !== 'string' || + !contentType.startsWith('application/grpc') + ) { + stream.respond( + { + [http2.constants.HTTP2_HEADER_STATUS]: + http2.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, + }, + { endStream: true } + ); + return false; + } + + return true; + } + + private _retrieveHandler(path: string): Handler | null { + serverCallTrace( + 'Received call to method ' + + path + + ' at address ' + + this.serverAddressString + ); + + const handler = this.handlers.get(path); + + if (handler === undefined) { + serverCallTrace( + 'No handler registered for method ' + + path + + '. Sending UNIMPLEMENTED status.' + ); + return null; + } + + return handler; + } + + private _respondWithError( + err: PartialStatusObject, + stream: http2.ServerHttp2Stream, + channelzSessionInfo: ChannelzSessionInfo | null = null + ) { + const trailersToSend = { + 'grpc-status': err.code ?? Status.INTERNAL, + 'grpc-message': err.details, + [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, + [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: 'application/grpc+proto', + ...err.metadata?.toHttp2Headers(), + }; + stream.respond(trailersToSend, { endStream: true }); + + this.callTracker.addCallFailed(); + channelzSessionInfo?.streamTracker.addCallFailed(); + } + + private _channelzHandler( + extraInterceptors: ServerInterceptor[], + stream: http2.ServerHttp2Stream, + headers: http2.IncomingHttpHeaders + ) { + // for handling idle timeout + this.onStreamOpened(stream); + + const channelzSessionInfo = this.sessions.get( + stream.session as http2.ServerHttp2Session + ); + + this.callTracker.addCallStarted(); + channelzSessionInfo?.streamTracker.addCallStarted(); + + if (!this._verifyContentType(stream, headers)) { + this.callTracker.addCallFailed(); + channelzSessionInfo?.streamTracker.addCallFailed(); + return; + } + + const path = headers[HTTP2_HEADER_PATH] as string; + + const handler = this._retrieveHandler(path); + if (!handler) { + this._respondWithError( + getUnimplementedStatusResponse(path), + stream, + channelzSessionInfo + ); + return; + } + + const callEventTracker: CallEventTracker = { + addMessageSent: () => { + if (channelzSessionInfo) { + channelzSessionInfo.messagesSent += 1; + channelzSessionInfo.lastMessageSentTimestamp = new Date(); + } + }, + addMessageReceived: () => { + if (channelzSessionInfo) { + channelzSessionInfo.messagesReceived += 1; + channelzSessionInfo.lastMessageReceivedTimestamp = new Date(); + } + }, + onCallEnd: status => { + if (status.code === Status.OK) { + this.callTracker.addCallSucceeded(); + } else { + this.callTracker.addCallFailed(); + } + }, + onStreamEnd: success => { + if (channelzSessionInfo) { + if (success) { + channelzSessionInfo.streamTracker.addCallSucceeded(); + } else { + channelzSessionInfo.streamTracker.addCallFailed(); + } + } + }, + }; + + const call = getServerInterceptingCall( + [...extraInterceptors, ...this.interceptors], + stream, + headers, + callEventTracker, + handler, + this.options + ); + + if (!this._runHandlerForCall(call, handler)) { + this.callTracker.addCallFailed(); + channelzSessionInfo?.streamTracker.addCallFailed(); + + call.sendStatus({ + code: Status.INTERNAL, + details: `Unknown handler type: ${handler.type}`, + }); + } + } + + private _streamHandler( + extraInterceptors: ServerInterceptor[], + stream: http2.ServerHttp2Stream, + headers: http2.IncomingHttpHeaders + ) { + // for handling idle timeout + this.onStreamOpened(stream); + + if (this._verifyContentType(stream, headers) !== true) { + return; + } + + const path = headers[HTTP2_HEADER_PATH] as string; + + const handler = this._retrieveHandler(path); + if (!handler) { + this._respondWithError( + getUnimplementedStatusResponse(path), + stream, + null + ); + return; + } + + const call = getServerInterceptingCall( + [...extraInterceptors, ...this.interceptors], + stream, + headers, + null, + handler, + this.options + ); + + if (!this._runHandlerForCall(call, handler)) { + call.sendStatus({ + code: Status.INTERNAL, + details: `Unknown handler type: ${handler.type}`, + }); + } + } + + private _runHandlerForCall( + call: ServerInterceptingCallInterface, + handler: + | UntypedUnaryHandler + | UntypedClientStreamingHandler + | UntypedServerStreamingHandler + | UntypedBidiStreamingHandler + ): boolean { + const { type } = handler; + if (type === 'unary') { + handleUnary(call, handler); + } else if (type === 'clientStream') { + handleClientStreaming(call, handler); + } else if (type === 'serverStream') { + handleServerStreaming(call, handler); + } else if (type === 'bidi') { + handleBidiStreaming(call, handler); + } else { + return false; + } + + return true; + } + + private _setupHandlers( + http2Server: http2.Http2Server | http2.Http2SecureServer, + extraInterceptors: ServerInterceptor[] + ): void { + if (http2Server === null) { + return; + } + + const serverAddress = http2Server.address(); + let serverAddressString = 'null'; + if (serverAddress) { + if (typeof serverAddress === 'string') { + serverAddressString = serverAddress; + } else { + serverAddressString = serverAddress.address + ':' + serverAddress.port; + } + } + this.serverAddressString = serverAddressString; + + const handler = this.channelzEnabled + ? this._channelzHandler + : this._streamHandler; + + const sessionHandler = this.channelzEnabled + ? this._channelzSessionHandler(http2Server) + : this._sessionHandler(http2Server); + + http2Server.on('stream', handler.bind(this, extraInterceptors)); + http2Server.on('session', sessionHandler); + } + + private _sessionHandler( + http2Server: http2.Http2Server | http2.Http2SecureServer + ) { + return (session: http2.ServerHttp2Session) => { + this.http2Servers.get(http2Server)?.sessions.add(session); + + let connectionAgeTimer: NodeJS.Timeout | null = null; + let connectionAgeGraceTimer: NodeJS.Timeout | null = null; + let keepaliveTimer: NodeJS.Timeout | null = null; + let sessionClosedByServer = false; + + const idleTimeoutObj = this.enableIdleTimeout(session); + + if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) { + // Apply a random jitter within a +/-10% range + const jitterMagnitude = this.maxConnectionAgeMs / 10; + const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude; + + connectionAgeTimer = setTimeout(() => { + sessionClosedByServer = true; + + this.trace( + 'Connection dropped by max connection age: ' + + session.socket?.remoteAddress + ); + + try { + session.goaway( + http2.constants.NGHTTP2_NO_ERROR, + ~(1 << 31), + kMaxAge + ); + } catch (e) { + // The goaway can't be sent because the session is already closed + session.destroy(); + return; + } + session.close(); + + /* Allow a grace period after sending the GOAWAY before forcibly + * closing the connection. */ + if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) { + connectionAgeGraceTimer = setTimeout(() => { + session.destroy(); + }, this.maxConnectionAgeGraceMs); + connectionAgeGraceTimer.unref?.(); + } + }, this.maxConnectionAgeMs + jitter); + connectionAgeTimer.unref?.(); + } + + const clearKeepaliveTimeout = () => { + if (keepaliveTimer) { + clearTimeout(keepaliveTimer); + keepaliveTimer = null; + } + }; + + const canSendPing = () => { + return ( + !session.destroyed && + this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && + this.keepaliveTimeMs > 0 + ); + }; + + /* eslint-disable-next-line prefer-const */ + let sendPing: () => void; // hoisted for use in maybeStartKeepalivePingTimer + + const maybeStartKeepalivePingTimer = () => { + if (!canSendPing()) { + return; + } + this.keepaliveTrace( + 'Starting keepalive timer for ' + this.keepaliveTimeMs + 'ms' + ); + keepaliveTimer = setTimeout(() => { + clearKeepaliveTimeout(); + sendPing(); + }, this.keepaliveTimeMs); + keepaliveTimer.unref?.(); + }; + + sendPing = () => { + if (!canSendPing()) { + return; + } + this.keepaliveTrace( + 'Sending ping with timeout ' + this.keepaliveTimeoutMs + 'ms' + ); + let pingSendError = ''; + try { + const pingSentSuccessfully = session.ping( + (err: Error | null, duration: number, payload: Buffer) => { + clearKeepaliveTimeout(); + if (err) { + this.keepaliveTrace('Ping failed with error: ' + err.message); + sessionClosedByServer = true; + session.destroy(); + } else { + this.keepaliveTrace('Received ping response'); + maybeStartKeepalivePingTimer(); + } + } + ); + if (!pingSentSuccessfully) { + pingSendError = 'Ping returned false'; + } + } catch (e) { + // grpc/grpc-node#2139 + pingSendError = + (e instanceof Error ? e.message : '') || 'Unknown error'; + } + + if (pingSendError) { + this.keepaliveTrace('Ping send failed: ' + pingSendError); + this.trace( + 'Connection dropped due to ping send error: ' + pingSendError + ); + sessionClosedByServer = true; + session.destroy(); + return; + } + + keepaliveTimer = setTimeout(() => { + clearKeepaliveTimeout(); + this.keepaliveTrace('Ping timeout passed without response'); + this.trace('Connection dropped by keepalive timeout'); + sessionClosedByServer = true; + session.destroy(); + }, this.keepaliveTimeoutMs); + keepaliveTimer.unref?.(); + }; + + maybeStartKeepalivePingTimer(); + + session.on('close', () => { + if (!sessionClosedByServer) { + this.trace( + `Connection dropped by client ${session.socket?.remoteAddress}` + ); + } + + if (connectionAgeTimer) { + clearTimeout(connectionAgeTimer); + } + + if (connectionAgeGraceTimer) { + clearTimeout(connectionAgeGraceTimer); + } + + clearKeepaliveTimeout(); + + if (idleTimeoutObj !== null) { + clearTimeout(idleTimeoutObj.timeout); + this.sessionIdleTimeouts.delete(session); + } + + this.http2Servers.get(http2Server)?.sessions.delete(session); + }); + }; + } + + private _channelzSessionHandler( + http2Server: http2.Http2Server | http2.Http2SecureServer + ) { + return (session: http2.ServerHttp2Session) => { + const channelzRef = registerChannelzSocket( + session.socket?.remoteAddress ?? 'unknown', + this.getChannelzSessionInfo.bind(this, session), + this.channelzEnabled + ); + + const channelzSessionInfo: ChannelzSessionInfo = { + ref: channelzRef, + streamTracker: new ChannelzCallTracker(), + messagesSent: 0, + messagesReceived: 0, + keepAlivesSent: 0, + lastMessageSentTimestamp: null, + lastMessageReceivedTimestamp: null, + }; + + this.http2Servers.get(http2Server)?.sessions.add(session); + this.sessions.set(session, channelzSessionInfo); + const clientAddress = `${session.socket.remoteAddress}:${session.socket.remotePort}`; + + this.channelzTrace.addTrace( + 'CT_INFO', + 'Connection established by client ' + clientAddress + ); + this.trace('Connection established by client ' + clientAddress); + this.sessionChildrenTracker.refChild(channelzRef); + + let connectionAgeTimer: NodeJS.Timeout | null = null; + let connectionAgeGraceTimer: NodeJS.Timeout | null = null; + let keepaliveTimeout: NodeJS.Timeout | null = null; + let sessionClosedByServer = false; + + const idleTimeoutObj = this.enableIdleTimeout(session); + + if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) { + // Apply a random jitter within a +/-10% range + const jitterMagnitude = this.maxConnectionAgeMs / 10; + const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude; + + connectionAgeTimer = setTimeout(() => { + sessionClosedByServer = true; + this.channelzTrace.addTrace( + 'CT_INFO', + 'Connection dropped by max connection age from ' + clientAddress + ); + + try { + session.goaway( + http2.constants.NGHTTP2_NO_ERROR, + ~(1 << 31), + kMaxAge + ); + } catch (e) { + // The goaway can't be sent because the session is already closed + session.destroy(); + return; + } + session.close(); + + /* Allow a grace period after sending the GOAWAY before forcibly + * closing the connection. */ + if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) { + connectionAgeGraceTimer = setTimeout(() => { + session.destroy(); + }, this.maxConnectionAgeGraceMs); + connectionAgeGraceTimer.unref?.(); + } + }, this.maxConnectionAgeMs + jitter); + connectionAgeTimer.unref?.(); + } + + const clearKeepaliveTimeout = () => { + if (keepaliveTimeout) { + clearTimeout(keepaliveTimeout); + keepaliveTimeout = null; + } + }; + + const canSendPing = () => { + return ( + !session.destroyed && + this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && + this.keepaliveTimeMs > 0 + ); + }; + + /* eslint-disable-next-line prefer-const */ + let sendPing: () => void; // hoisted for use in maybeStartKeepalivePingTimer + + const maybeStartKeepalivePingTimer = () => { + if (!canSendPing()) { + return; + } + this.keepaliveTrace( + 'Starting keepalive timer for ' + this.keepaliveTimeMs + 'ms' + ); + keepaliveTimeout = setTimeout(() => { + clearKeepaliveTimeout(); + sendPing(); + }, this.keepaliveTimeMs); + keepaliveTimeout.unref?.(); + }; + + sendPing = () => { + if (!canSendPing()) { + return; + } + this.keepaliveTrace( + 'Sending ping with timeout ' + this.keepaliveTimeoutMs + 'ms' + ); + let pingSendError = ''; + try { + const pingSentSuccessfully = session.ping( + (err: Error | null, duration: number, payload: Buffer) => { + clearKeepaliveTimeout(); + if (err) { + this.keepaliveTrace('Ping failed with error: ' + err.message); + this.channelzTrace.addTrace( + 'CT_INFO', + 'Connection dropped due to error of a ping frame ' + + err.message + + ' return in ' + + duration + ); + sessionClosedByServer = true; + session.destroy(); + } else { + this.keepaliveTrace('Received ping response'); + maybeStartKeepalivePingTimer(); + } + } + ); + if (!pingSentSuccessfully) { + pingSendError = 'Ping returned false'; + } + } catch (e) { + // grpc/grpc-node#2139 + pingSendError = + (e instanceof Error ? e.message : '') || 'Unknown error'; + } + + if (pingSendError) { + this.keepaliveTrace('Ping send failed: ' + pingSendError); + this.channelzTrace.addTrace( + 'CT_INFO', + 'Connection dropped due to ping send error: ' + pingSendError + ); + sessionClosedByServer = true; + session.destroy(); + return; + } + + channelzSessionInfo.keepAlivesSent += 1; + + keepaliveTimeout = setTimeout(() => { + clearKeepaliveTimeout(); + this.keepaliveTrace('Ping timeout passed without response'); + this.channelzTrace.addTrace( + 'CT_INFO', + 'Connection dropped by keepalive timeout from ' + clientAddress + ); + sessionClosedByServer = true; + session.destroy(); + }, this.keepaliveTimeoutMs); + keepaliveTimeout.unref?.(); + }; + + maybeStartKeepalivePingTimer(); + + session.on('close', () => { + if (!sessionClosedByServer) { + this.channelzTrace.addTrace( + 'CT_INFO', + 'Connection dropped by client ' + clientAddress + ); + } + + this.sessionChildrenTracker.unrefChild(channelzRef); + unregisterChannelzRef(channelzRef); + + if (connectionAgeTimer) { + clearTimeout(connectionAgeTimer); + } + + if (connectionAgeGraceTimer) { + clearTimeout(connectionAgeGraceTimer); + } + + clearKeepaliveTimeout(); + + if (idleTimeoutObj !== null) { + clearTimeout(idleTimeoutObj.timeout); + this.sessionIdleTimeouts.delete(session); + } + + this.http2Servers.get(http2Server)?.sessions.delete(session); + this.sessions.delete(session); + }); + }; + } + + private enableIdleTimeout( + session: http2.ServerHttp2Session + ): SessionIdleTimeoutTracker | null { + if (this.sessionIdleTimeout >= MAX_CONNECTION_IDLE_MS) { + return null; + } + + const idleTimeoutObj: SessionIdleTimeoutTracker = { + activeStreams: 0, + lastIdle: Date.now(), + onClose: this.onStreamClose.bind(this, session), + timeout: setTimeout( + this.onIdleTimeout, + this.sessionIdleTimeout, + this, + session + ), + }; + idleTimeoutObj.timeout.unref?.(); + this.sessionIdleTimeouts.set(session, idleTimeoutObj); + + const { socket } = session; + this.trace( + 'Enable idle timeout for ' + + socket.remoteAddress + + ':' + + socket.remotePort + ); + + return idleTimeoutObj; + } + + private onIdleTimeout( + this: undefined, + ctx: Server, + session: http2.ServerHttp2Session + ) { + const { socket } = session; + const sessionInfo = ctx.sessionIdleTimeouts.get(session); + + // if it is called while we have activeStreams - timer will not be rescheduled + // until last active stream is closed, then it will call .refresh() on the timer + // important part is to not clearTimeout(timer) or it becomes unusable + // for future refreshes + if ( + sessionInfo !== undefined && + sessionInfo.activeStreams === 0 + ) { + if (Date.now() - sessionInfo.lastIdle >= ctx.sessionIdleTimeout) { + ctx.trace( + 'Session idle timeout triggered for ' + + socket?.remoteAddress + + ':' + + socket?.remotePort + + ' last idle at ' + + sessionInfo.lastIdle + ); + + ctx.closeSession(session); + } else { + sessionInfo.timeout.refresh(); + } + } + } + + private onStreamOpened(stream: http2.ServerHttp2Stream) { + const session = stream.session as http2.ServerHttp2Session; + + const idleTimeoutObj = this.sessionIdleTimeouts.get(session); + if (idleTimeoutObj) { + idleTimeoutObj.activeStreams += 1; + stream.once('close', idleTimeoutObj.onClose); + } + } + + private onStreamClose(session: http2.ServerHttp2Session) { + const idleTimeoutObj = this.sessionIdleTimeouts.get(session); + + if (idleTimeoutObj) { + idleTimeoutObj.activeStreams -= 1; + if (idleTimeoutObj.activeStreams === 0) { + idleTimeoutObj.lastIdle = Date.now(); + idleTimeoutObj.timeout.refresh(); + + this.trace( + 'Session onStreamClose' + + session.socket?.remoteAddress + + ':' + + session.socket?.remotePort + + ' at ' + + idleTimeoutObj.lastIdle + ); + } + } + } +} + +async function handleUnary( + call: ServerInterceptingCallInterface, + handler: UnaryHandler +): Promise { + let stream: ServerUnaryCall; + + function respond( + err: ServerErrorResponse | ServerStatusResponse | null, + value?: ResponseType | null, + trailer?: Metadata, + flags?: number + ) { + if (err) { + call.sendStatus(serverErrorToStatus(err, trailer)); + return; + } + call.sendMessage(value, () => { + call.sendStatus({ + code: Status.OK, + details: 'OK', + metadata: trailer ?? null, + }); + }); + } + + let requestMetadata: Metadata; + let requestMessage: RequestType | null = null; + call.start({ + onReceiveMetadata(metadata) { + requestMetadata = metadata; + call.startRead(); + }, + onReceiveMessage(message) { + if (requestMessage) { + call.sendStatus({ + code: Status.UNIMPLEMENTED, + details: `Received a second request message for server streaming method ${handler.path}`, + metadata: null, + }); + return; + } + requestMessage = message; + call.startRead(); + }, + onReceiveHalfClose() { + if (!requestMessage) { + call.sendStatus({ + code: Status.UNIMPLEMENTED, + details: `Received no request message for server streaming method ${handler.path}`, + metadata: null, + }); + return; + } + stream = new ServerWritableStreamImpl( + handler.path, + call, + requestMetadata, + requestMessage + ); + try { + handler.func(stream, respond); + } catch (err) { + call.sendStatus({ + code: Status.UNKNOWN, + details: `Server method handler threw error ${ + (err as Error).message + }`, + metadata: null, + }); + } + }, + onCancel() { + if (stream) { + stream.cancelled = true; + stream.emit('cancelled', 'cancelled'); + } + }, + }); +} + +function handleClientStreaming( + call: ServerInterceptingCallInterface, + handler: ClientStreamingHandler +): void { + let stream: ServerReadableStream; + + function respond( + err: ServerErrorResponse | ServerStatusResponse | null, + value?: ResponseType | null, + trailer?: Metadata, + flags?: number + ) { + if (err) { + call.sendStatus(serverErrorToStatus(err, trailer)); + return; + } + call.sendMessage(value, () => { + call.sendStatus({ + code: Status.OK, + details: 'OK', + metadata: trailer ?? null, + }); + }); + } + + call.start({ + onReceiveMetadata(metadata) { + stream = new ServerDuplexStreamImpl(handler.path, call, metadata); + try { + handler.func(stream, respond); + } catch (err) { + call.sendStatus({ + code: Status.UNKNOWN, + details: `Server method handler threw error ${ + (err as Error).message + }`, + metadata: null, + }); + } + }, + onReceiveMessage(message) { + stream.push(message); + }, + onReceiveHalfClose() { + stream.push(null); + }, + onCancel() { + if (stream) { + stream.cancelled = true; + stream.emit('cancelled', 'cancelled'); + stream.destroy(); + } + }, + }); +} + +function handleServerStreaming( + call: ServerInterceptingCallInterface, + handler: ServerStreamingHandler +): void { + let stream: ServerWritableStream; + + let requestMetadata: Metadata; + let requestMessage: RequestType | null = null; + call.start({ + onReceiveMetadata(metadata) { + requestMetadata = metadata; + call.startRead(); + }, + onReceiveMessage(message) { + if (requestMessage) { + call.sendStatus({ + code: Status.UNIMPLEMENTED, + details: `Received a second request message for server streaming method ${handler.path}`, + metadata: null, + }); + return; + } + requestMessage = message; + call.startRead(); + }, + onReceiveHalfClose() { + if (!requestMessage) { + call.sendStatus({ + code: Status.UNIMPLEMENTED, + details: `Received no request message for server streaming method ${handler.path}`, + metadata: null, + }); + return; + } + stream = new ServerWritableStreamImpl( + handler.path, + call, + requestMetadata, + requestMessage + ); + try { + handler.func(stream); + } catch (err) { + call.sendStatus({ + code: Status.UNKNOWN, + details: `Server method handler threw error ${ + (err as Error).message + }`, + metadata: null, + }); + } + }, + onCancel() { + if (stream) { + stream.cancelled = true; + stream.emit('cancelled', 'cancelled'); + stream.destroy(); + } + }, + }); +} + +function handleBidiStreaming( + call: ServerInterceptingCallInterface, + handler: BidiStreamingHandler +): void { + let stream: ServerDuplexStream; + + call.start({ + onReceiveMetadata(metadata) { + stream = new ServerDuplexStreamImpl(handler.path, call, metadata); + try { + handler.func(stream); + } catch (err) { + call.sendStatus({ + code: Status.UNKNOWN, + details: `Server method handler threw error ${ + (err as Error).message + }`, + metadata: null, + }); + } + }, + onReceiveMessage(message) { + stream.push(message); + }, + onReceiveHalfClose() { + stream.push(null); + }, + onCancel() { + if (stream) { + stream.cancelled = true; + stream.emit('cancelled', 'cancelled'); + stream.destroy(); + } + }, + }); +} diff --git a/node_modules/@grpc/grpc-js/src/service-config.ts b/node_modules/@grpc/grpc-js/src/service-config.ts new file mode 100644 index 0000000..db1e30e --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/service-config.ts @@ -0,0 +1,564 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +/* This file implements gRFC A2 and the service config spec: + * https://github.com/grpc/proposal/blob/master/A2-service-configs-in-dns.md + * https://github.com/grpc/grpc/blob/master/doc/service_config.md. Each + * function here takes an object with unknown structure and returns its + * specific object type if the input has the right structure, and throws an + * error otherwise. */ + +/* The any type is purposely used here. All functions validate their input at + * runtime */ +/* eslint-disable @typescript-eslint/no-explicit-any */ + +import * as os from 'os'; +import { Status } from './constants'; +import { Duration } from './duration'; + +export interface MethodConfigName { + service?: string; + method?: string; +} + +export interface RetryPolicy { + maxAttempts: number; + initialBackoff: string; + maxBackoff: string; + backoffMultiplier: number; + retryableStatusCodes: (Status | string)[]; +} + +export interface HedgingPolicy { + maxAttempts: number; + hedgingDelay?: string; + nonFatalStatusCodes?: (Status | string)[]; +} + +export interface MethodConfig { + name: MethodConfigName[]; + waitForReady?: boolean; + timeout?: Duration; + maxRequestBytes?: number; + maxResponseBytes?: number; + retryPolicy?: RetryPolicy; + hedgingPolicy?: HedgingPolicy; +} + +export interface RetryThrottling { + maxTokens: number; + tokenRatio: number; +} + +export interface LoadBalancingConfig { + [key: string]: object; +} + +export interface ServiceConfig { + loadBalancingPolicy?: string; + loadBalancingConfig: LoadBalancingConfig[]; + methodConfig: MethodConfig[]; + retryThrottling?: RetryThrottling; +} + +export interface ServiceConfigCanaryConfig { + clientLanguage?: string[]; + percentage?: number; + clientHostname?: string[]; + serviceConfig: ServiceConfig; +} + +/** + * Recognizes a number with up to 9 digits after the decimal point, followed by + * an "s", representing a number of seconds. + */ +const DURATION_REGEX = /^\d+(\.\d{1,9})?s$/; + +/** + * Client language name used for determining whether this client matches a + * `ServiceConfigCanaryConfig`'s `clientLanguage` list. + */ +const CLIENT_LANGUAGE_STRING = 'node'; + +function validateName(obj: any): MethodConfigName { + // In this context, and unset field and '' are considered the same + if ('service' in obj && obj.service !== '') { + if (typeof obj.service !== 'string') { + throw new Error( + `Invalid method config name: invalid service: expected type string, got ${typeof obj.service}` + ); + } + if ('method' in obj && obj.method !== '') { + if (typeof obj.method !== 'string') { + throw new Error( + `Invalid method config name: invalid method: expected type string, got ${typeof obj.service}` + ); + } + return { + service: obj.service, + method: obj.method, + }; + } else { + return { + service: obj.service, + }; + } + } else { + if ('method' in obj && obj.method !== undefined) { + throw new Error( + `Invalid method config name: method set with empty or unset service` + ); + } + return {}; + } +} + +function validateRetryPolicy(obj: any): RetryPolicy { + if ( + !('maxAttempts' in obj) || + !Number.isInteger(obj.maxAttempts) || + obj.maxAttempts < 2 + ) { + throw new Error( + 'Invalid method config retry policy: maxAttempts must be an integer at least 2' + ); + } + if ( + !('initialBackoff' in obj) || + typeof obj.initialBackoff !== 'string' || + !DURATION_REGEX.test(obj.initialBackoff) + ) { + throw new Error( + 'Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer or decimal followed by s' + ); + } + if ( + !('maxBackoff' in obj) || + typeof obj.maxBackoff !== 'string' || + !DURATION_REGEX.test(obj.maxBackoff) + ) { + throw new Error( + 'Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer or decimal followed by s' + ); + } + if ( + !('backoffMultiplier' in obj) || + typeof obj.backoffMultiplier !== 'number' || + obj.backoffMultiplier <= 0 + ) { + throw new Error( + 'Invalid method config retry policy: backoffMultiplier must be a number greater than 0' + ); + } + if ( + !('retryableStatusCodes' in obj && Array.isArray(obj.retryableStatusCodes)) + ) { + throw new Error( + 'Invalid method config retry policy: retryableStatusCodes is required' + ); + } + if (obj.retryableStatusCodes.length === 0) { + throw new Error( + 'Invalid method config retry policy: retryableStatusCodes must be non-empty' + ); + } + for (const value of obj.retryableStatusCodes) { + if (typeof value === 'number') { + if (!Object.values(Status).includes(value)) { + throw new Error( + 'Invalid method config retry policy: retryableStatusCodes value not in status code range' + ); + } + } else if (typeof value === 'string') { + if (!Object.values(Status).includes(value.toUpperCase())) { + throw new Error( + 'Invalid method config retry policy: retryableStatusCodes value not a status code name' + ); + } + } else { + throw new Error( + 'Invalid method config retry policy: retryableStatusCodes value must be a string or number' + ); + } + } + return { + maxAttempts: obj.maxAttempts, + initialBackoff: obj.initialBackoff, + maxBackoff: obj.maxBackoff, + backoffMultiplier: obj.backoffMultiplier, + retryableStatusCodes: obj.retryableStatusCodes, + }; +} + +function validateHedgingPolicy(obj: any): HedgingPolicy { + if ( + !('maxAttempts' in obj) || + !Number.isInteger(obj.maxAttempts) || + obj.maxAttempts < 2 + ) { + throw new Error( + 'Invalid method config hedging policy: maxAttempts must be an integer at least 2' + ); + } + if ( + 'hedgingDelay' in obj && + (typeof obj.hedgingDelay !== 'string' || + !DURATION_REGEX.test(obj.hedgingDelay)) + ) { + throw new Error( + 'Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s' + ); + } + if ('nonFatalStatusCodes' in obj && Array.isArray(obj.nonFatalStatusCodes)) { + for (const value of obj.nonFatalStatusCodes) { + if (typeof value === 'number') { + if (!Object.values(Status).includes(value)) { + throw new Error( + 'Invalid method config hedging policy: nonFatalStatusCodes value not in status code range' + ); + } + } else if (typeof value === 'string') { + if (!Object.values(Status).includes(value.toUpperCase())) { + throw new Error( + 'Invalid method config hedging policy: nonFatalStatusCodes value not a status code name' + ); + } + } else { + throw new Error( + 'Invalid method config hedging policy: nonFatalStatusCodes value must be a string or number' + ); + } + } + } + const result: HedgingPolicy = { + maxAttempts: obj.maxAttempts, + }; + if (obj.hedgingDelay) { + result.hedgingDelay = obj.hedgingDelay; + } + if (obj.nonFatalStatusCodes) { + result.nonFatalStatusCodes = obj.nonFatalStatusCodes; + } + return result; +} + +function validateMethodConfig(obj: any): MethodConfig { + const result: MethodConfig = { + name: [], + }; + if (!('name' in obj) || !Array.isArray(obj.name)) { + throw new Error('Invalid method config: invalid name array'); + } + for (const name of obj.name) { + result.name.push(validateName(name)); + } + if ('waitForReady' in obj) { + if (typeof obj.waitForReady !== 'boolean') { + throw new Error('Invalid method config: invalid waitForReady'); + } + result.waitForReady = obj.waitForReady; + } + if ('timeout' in obj) { + if (typeof obj.timeout === 'object') { + if ( + !('seconds' in obj.timeout) || + !(typeof obj.timeout.seconds === 'number') + ) { + throw new Error('Invalid method config: invalid timeout.seconds'); + } + if ( + !('nanos' in obj.timeout) || + !(typeof obj.timeout.nanos === 'number') + ) { + throw new Error('Invalid method config: invalid timeout.nanos'); + } + result.timeout = obj.timeout; + } else if ( + typeof obj.timeout === 'string' && + DURATION_REGEX.test(obj.timeout) + ) { + const timeoutParts = obj.timeout + .substring(0, obj.timeout.length - 1) + .split('.'); + result.timeout = { + seconds: timeoutParts[0] | 0, + nanos: (timeoutParts[1] ?? 0) | 0, + }; + } else { + throw new Error('Invalid method config: invalid timeout'); + } + } + if ('maxRequestBytes' in obj) { + if (typeof obj.maxRequestBytes !== 'number') { + throw new Error('Invalid method config: invalid maxRequestBytes'); + } + result.maxRequestBytes = obj.maxRequestBytes; + } + if ('maxResponseBytes' in obj) { + if (typeof obj.maxResponseBytes !== 'number') { + throw new Error('Invalid method config: invalid maxRequestBytes'); + } + result.maxResponseBytes = obj.maxResponseBytes; + } + if ('retryPolicy' in obj) { + if ('hedgingPolicy' in obj) { + throw new Error( + 'Invalid method config: retryPolicy and hedgingPolicy cannot both be specified' + ); + } else { + result.retryPolicy = validateRetryPolicy(obj.retryPolicy); + } + } else if ('hedgingPolicy' in obj) { + result.hedgingPolicy = validateHedgingPolicy(obj.hedgingPolicy); + } + return result; +} + +export function validateRetryThrottling(obj: any): RetryThrottling { + if ( + !('maxTokens' in obj) || + typeof obj.maxTokens !== 'number' || + obj.maxTokens <= 0 || + obj.maxTokens > 1000 + ) { + throw new Error( + 'Invalid retryThrottling: maxTokens must be a number in (0, 1000]' + ); + } + if ( + !('tokenRatio' in obj) || + typeof obj.tokenRatio !== 'number' || + obj.tokenRatio <= 0 + ) { + throw new Error( + 'Invalid retryThrottling: tokenRatio must be a number greater than 0' + ); + } + return { + maxTokens: +(obj.maxTokens as number).toFixed(3), + tokenRatio: +(obj.tokenRatio as number).toFixed(3), + }; +} + +function validateLoadBalancingConfig(obj: any): LoadBalancingConfig { + if (!(typeof obj === 'object' && obj !== null)) { + throw new Error( + `Invalid loadBalancingConfig: unexpected type ${typeof obj}` + ); + } + const keys = Object.keys(obj); + if (keys.length > 1) { + throw new Error( + `Invalid loadBalancingConfig: unexpected multiple keys ${keys}` + ); + } + if (keys.length === 0) { + throw new Error( + 'Invalid loadBalancingConfig: load balancing policy name required' + ); + } + return { + [keys[0]]: obj[keys[0]], + }; +} + +export function validateServiceConfig(obj: any): ServiceConfig { + const result: ServiceConfig = { + loadBalancingConfig: [], + methodConfig: [], + }; + if ('loadBalancingPolicy' in obj) { + if (typeof obj.loadBalancingPolicy === 'string') { + result.loadBalancingPolicy = obj.loadBalancingPolicy; + } else { + throw new Error('Invalid service config: invalid loadBalancingPolicy'); + } + } + if ('loadBalancingConfig' in obj) { + if (Array.isArray(obj.loadBalancingConfig)) { + for (const config of obj.loadBalancingConfig) { + result.loadBalancingConfig.push(validateLoadBalancingConfig(config)); + } + } else { + throw new Error('Invalid service config: invalid loadBalancingConfig'); + } + } + if ('methodConfig' in obj) { + if (Array.isArray(obj.methodConfig)) { + for (const methodConfig of obj.methodConfig) { + result.methodConfig.push(validateMethodConfig(methodConfig)); + } + } + } + if ('retryThrottling' in obj) { + result.retryThrottling = validateRetryThrottling(obj.retryThrottling); + } + // Validate method name uniqueness + const seenMethodNames: MethodConfigName[] = []; + for (const methodConfig of result.methodConfig) { + for (const name of methodConfig.name) { + for (const seenName of seenMethodNames) { + if ( + name.service === seenName.service && + name.method === seenName.method + ) { + throw new Error( + `Invalid service config: duplicate name ${name.service}/${name.method}` + ); + } + } + seenMethodNames.push(name); + } + } + return result; +} + +function validateCanaryConfig(obj: any): ServiceConfigCanaryConfig { + if (!('serviceConfig' in obj)) { + throw new Error('Invalid service config choice: missing service config'); + } + const result: ServiceConfigCanaryConfig = { + serviceConfig: validateServiceConfig(obj.serviceConfig), + }; + if ('clientLanguage' in obj) { + if (Array.isArray(obj.clientLanguage)) { + result.clientLanguage = []; + for (const lang of obj.clientLanguage) { + if (typeof lang === 'string') { + result.clientLanguage.push(lang); + } else { + throw new Error( + 'Invalid service config choice: invalid clientLanguage' + ); + } + } + } else { + throw new Error('Invalid service config choice: invalid clientLanguage'); + } + } + if ('clientHostname' in obj) { + if (Array.isArray(obj.clientHostname)) { + result.clientHostname = []; + for (const lang of obj.clientHostname) { + if (typeof lang === 'string') { + result.clientHostname.push(lang); + } else { + throw new Error( + 'Invalid service config choice: invalid clientHostname' + ); + } + } + } else { + throw new Error('Invalid service config choice: invalid clientHostname'); + } + } + if ('percentage' in obj) { + if ( + typeof obj.percentage === 'number' && + 0 <= obj.percentage && + obj.percentage <= 100 + ) { + result.percentage = obj.percentage; + } else { + throw new Error('Invalid service config choice: invalid percentage'); + } + } + // Validate that no unexpected fields are present + const allowedFields = [ + 'clientLanguage', + 'percentage', + 'clientHostname', + 'serviceConfig', + ]; + for (const field in obj) { + if (!allowedFields.includes(field)) { + throw new Error( + `Invalid service config choice: unexpected field ${field}` + ); + } + } + return result; +} + +function validateAndSelectCanaryConfig( + obj: any, + percentage: number +): ServiceConfig { + if (!Array.isArray(obj)) { + throw new Error('Invalid service config list'); + } + for (const config of obj) { + const validatedConfig = validateCanaryConfig(config); + /* For each field, we check if it is present, then only discard the + * config if the field value does not match the current client */ + if ( + typeof validatedConfig.percentage === 'number' && + percentage > validatedConfig.percentage + ) { + continue; + } + if (Array.isArray(validatedConfig.clientHostname)) { + let hostnameMatched = false; + for (const hostname of validatedConfig.clientHostname) { + if (hostname === os.hostname()) { + hostnameMatched = true; + } + } + if (!hostnameMatched) { + continue; + } + } + if (Array.isArray(validatedConfig.clientLanguage)) { + let languageMatched = false; + for (const language of validatedConfig.clientLanguage) { + if (language === CLIENT_LANGUAGE_STRING) { + languageMatched = true; + } + } + if (!languageMatched) { + continue; + } + } + return validatedConfig.serviceConfig; + } + throw new Error('No matching service config found'); +} + +/** + * Find the "grpc_config" record among the TXT records, parse its value as JSON, validate its contents, + * and select a service config with selection fields that all match this client. Most of these steps + * can fail with an error; the caller must handle any errors thrown this way. + * @param txtRecord The TXT record array that is output from a successful call to dns.resolveTxt + * @param percentage A number chosen from the range [0, 100) that is used to select which config to use + * @return The service configuration to use, given the percentage value, or null if the service config + * data has a valid format but none of the options match the current client. + */ +export function extractAndSelectServiceConfig( + txtRecord: string[][], + percentage: number +): ServiceConfig | null { + for (const record of txtRecord) { + if (record.length > 0 && record[0].startsWith('grpc_config=')) { + /* Treat the list of strings in this record as a single string and remove + * "grpc_config=" from the beginning. The rest should be a JSON string */ + const recordString = record.join('').substring('grpc_config='.length); + const recordJson: any = JSON.parse(recordString); + return validateAndSelectCanaryConfig(recordJson, percentage); + } + } + return null; +} diff --git a/node_modules/@grpc/grpc-js/src/single-subchannel-channel.ts b/node_modules/@grpc/grpc-js/src/single-subchannel-channel.ts new file mode 100644 index 0000000..c1a1fd1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/single-subchannel-channel.ts @@ -0,0 +1,248 @@ +/* + * Copyright 2025 gRPC authors. + * + * 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. + * + */ + +import { AuthContext } from "./auth-context"; +import { CallCredentials } from "./call-credentials"; +import { Call, CallStreamOptions, InterceptingListener, MessageContext, StatusObject } from "./call-interface"; +import { getNextCallNumber } from "./call-number"; +import { Channel } from "./channel"; +import { ChannelOptions } from "./channel-options"; +import { ChannelRef, ChannelzCallTracker, ChannelzChildrenTracker, ChannelzTrace, registerChannelzChannel, unregisterChannelzRef } from "./channelz"; +import { CompressionFilterFactory } from "./compression-filter"; +import { ConnectivityState } from "./connectivity-state"; +import { Propagate, Status } from "./constants"; +import { restrictControlPlaneStatusCode } from "./control-plane-status"; +import { Deadline, getRelativeTimeout } from "./deadline"; +import { FilterStack, FilterStackFactory } from "./filter-stack"; +import { Metadata } from "./metadata"; +import { getDefaultAuthority } from "./resolver"; +import { Subchannel } from "./subchannel"; +import { SubchannelCall } from "./subchannel-call"; +import { GrpcUri, splitHostPort, uriToString } from "./uri-parser"; + +class SubchannelCallWrapper implements Call { + private childCall: SubchannelCall | null = null; + private pendingMessage: { context: MessageContext; message: Buffer } | null = + null; + private readPending = false; + private halfClosePending = false; + private pendingStatus: StatusObject | null = null; + private serviceUrl: string; + private filterStack: FilterStack; + private readFilterPending = false; + private writeFilterPending = false; + constructor(private subchannel: Subchannel, private method: string, filterStackFactory: FilterStackFactory, private options: CallStreamOptions, private callNumber: number) { + const splitPath: string[] = this.method.split('/'); + let serviceName = ''; + /* The standard path format is "/{serviceName}/{methodName}", so if we split + * by '/', the first item should be empty and the second should be the + * service name */ + if (splitPath.length >= 2) { + serviceName = splitPath[1]; + } + const hostname = splitHostPort(this.options.host)?.host ?? 'localhost'; + /* Currently, call credentials are only allowed on HTTPS connections, so we + * can assume that the scheme is "https" */ + this.serviceUrl = `https://${hostname}/${serviceName}`; + const timeout = getRelativeTimeout(options.deadline); + if (timeout !== Infinity) { + if (timeout <= 0) { + this.cancelWithStatus(Status.DEADLINE_EXCEEDED, 'Deadline exceeded'); + } else { + setTimeout(() => { + this.cancelWithStatus(Status.DEADLINE_EXCEEDED, 'Deadline exceeded'); + }, timeout); + } + } + this.filterStack = filterStackFactory.createFilter(); + } + + cancelWithStatus(status: Status, details: string): void { + if (this.childCall) { + this.childCall.cancelWithStatus(status, details); + } else { + this.pendingStatus = { + code: status, + details: details, + metadata: new Metadata() + }; + } + + } + getPeer(): string { + return this.childCall?.getPeer() ?? this.subchannel.getAddress(); + } + async start(metadata: Metadata, listener: InterceptingListener): Promise { + if (this.pendingStatus) { + listener.onReceiveStatus(this.pendingStatus); + return; + } + if (this.subchannel.getConnectivityState() !== ConnectivityState.READY) { + listener.onReceiveStatus({ + code: Status.UNAVAILABLE, + details: 'Subchannel not ready', + metadata: new Metadata() + }); + return; + } + const filteredMetadata = await this.filterStack.sendMetadata(Promise.resolve(metadata)); + let credsMetadata: Metadata; + try { + credsMetadata = await this.subchannel.getCallCredentials() + .generateMetadata({method_name: this.method, service_url: this.serviceUrl}); + } catch (e) { + const error = e as (Error & { code: number }); + const { code, details } = restrictControlPlaneStatusCode( + typeof error.code === 'number' ? error.code : Status.UNKNOWN, + `Getting metadata from plugin failed with error: ${error.message}` + ); + listener.onReceiveStatus( + { + code: code, + details: details, + metadata: new Metadata(), + } + ); + return; + } + credsMetadata.merge(filteredMetadata); + const childListener: InterceptingListener = { + onReceiveMetadata: async metadata => { + listener.onReceiveMetadata(await this.filterStack.receiveMetadata(metadata)); + }, + onReceiveMessage: async message => { + this.readFilterPending = true; + const filteredMessage = await this.filterStack.receiveMessage(message); + this.readFilterPending = false; + listener.onReceiveMessage(filteredMessage); + if (this.pendingStatus) { + listener.onReceiveStatus(this.pendingStatus); + } + }, + onReceiveStatus: async status => { + const filteredStatus = await this.filterStack.receiveTrailers(status); + if (this.readFilterPending) { + this.pendingStatus = filteredStatus; + } else { + listener.onReceiveStatus(filteredStatus); + } + } + } + this.childCall = this.subchannel.createCall(credsMetadata, this.options.host, this.method, childListener); + if (this.readPending) { + this.childCall.startRead(); + } + if (this.pendingMessage) { + this.childCall.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message); + } + if (this.halfClosePending && !this.writeFilterPending) { + this.childCall.halfClose(); + } + } + async sendMessageWithContext(context: MessageContext, message: Buffer): Promise { + this.writeFilterPending = true; + const filteredMessage = await this.filterStack.sendMessage(Promise.resolve({message: message, flags: context.flags})); + this.writeFilterPending = false; + if (this.childCall) { + this.childCall.sendMessageWithContext(context, filteredMessage.message); + if (this.halfClosePending) { + this.childCall.halfClose(); + } + } else { + this.pendingMessage = { context, message: filteredMessage.message }; + } + } + startRead(): void { + if (this.childCall) { + this.childCall.startRead(); + } else { + this.readPending = true; + } + } + halfClose(): void { + if (this.childCall && !this.writeFilterPending) { + this.childCall.halfClose(); + } else { + this.halfClosePending = true; + } + } + getCallNumber(): number { + return this.callNumber; + } + setCredentials(credentials: CallCredentials): void { + throw new Error("Method not implemented."); + } + getAuthContext(): AuthContext | null { + if (this.childCall) { + return this.childCall.getAuthContext(); + } else { + return null; + } + } +} + +export class SingleSubchannelChannel implements Channel { + private channelzRef: ChannelRef; + private channelzEnabled = false; + private channelzTrace = new ChannelzTrace(); + private callTracker = new ChannelzCallTracker(); + private childrenTracker = new ChannelzChildrenTracker(); + private filterStackFactory: FilterStackFactory; + constructor(private subchannel: Subchannel, private target: GrpcUri, options: ChannelOptions) { + this.channelzEnabled = options['grpc.enable_channelz'] !== 0; + this.channelzRef = registerChannelzChannel(uriToString(target), () => ({ + target: `${uriToString(target)} (${subchannel.getAddress()})`, + state: this.subchannel.getConnectivityState(), + trace: this.channelzTrace, + callTracker: this.callTracker, + children: this.childrenTracker.getChildLists() + }), this.channelzEnabled); + if (this.channelzEnabled) { + this.childrenTracker.refChild(subchannel.getChannelzRef()); + } + this.filterStackFactory = new FilterStackFactory([new CompressionFilterFactory(this, options)]); + } + + close(): void { + if (this.channelzEnabled) { + this.childrenTracker.unrefChild(this.subchannel.getChannelzRef()); + } + unregisterChannelzRef(this.channelzRef); + } + + getTarget(): string { + return uriToString(this.target); + } + getConnectivityState(tryToConnect: boolean): ConnectivityState { + throw new Error("Method not implemented."); + } + watchConnectivityState(currentState: ConnectivityState, deadline: Date | number, callback: (error?: Error) => void): void { + throw new Error("Method not implemented."); + } + getChannelzRef(): ChannelRef { + return this.channelzRef; + } + createCall(method: string, deadline: Deadline): Call { + const callOptions: CallStreamOptions = { + deadline: deadline, + host: getDefaultAuthority(this.target), + flags: Propagate.DEFAULTS, + parentCall: null + }; + return new SubchannelCallWrapper(this.subchannel, method, this.filterStackFactory, callOptions, getNextCallNumber()); + } +} diff --git a/node_modules/@grpc/grpc-js/src/status-builder.ts b/node_modules/@grpc/grpc-js/src/status-builder.ts new file mode 100644 index 0000000..78e2ea3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/status-builder.ts @@ -0,0 +1,80 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { StatusObject } from './call-interface'; +import { Status } from './constants'; +import { Metadata } from './metadata'; + +/** + * A builder for gRPC status objects. + */ +export class StatusBuilder { + private code: Status | null; + private details: string | null; + private metadata: Metadata | null; + + constructor() { + this.code = null; + this.details = null; + this.metadata = null; + } + + /** + * Adds a status code to the builder. + */ + withCode(code: Status): this { + this.code = code; + return this; + } + + /** + * Adds details to the builder. + */ + withDetails(details: string): this { + this.details = details; + return this; + } + + /** + * Adds metadata to the builder. + */ + withMetadata(metadata: Metadata): this { + this.metadata = metadata; + return this; + } + + /** + * Builds the status object. + */ + build(): Partial { + const status: Partial = {}; + + if (this.code !== null) { + status.code = this.code; + } + + if (this.details !== null) { + status.details = this.details; + } + + if (this.metadata !== null) { + status.metadata = this.metadata; + } + + return status; + } +} diff --git a/node_modules/@grpc/grpc-js/src/stream-decoder.ts b/node_modules/@grpc/grpc-js/src/stream-decoder.ts new file mode 100644 index 0000000..ea669d1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/stream-decoder.ts @@ -0,0 +1,110 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +enum ReadState { + NO_DATA, + READING_SIZE, + READING_MESSAGE, +} + +export class StreamDecoder { + private readState: ReadState = ReadState.NO_DATA; + private readCompressFlag: Buffer = Buffer.alloc(1); + private readPartialSize: Buffer = Buffer.alloc(4); + private readSizeRemaining = 4; + private readMessageSize = 0; + private readPartialMessage: Buffer[] = []; + private readMessageRemaining = 0; + + constructor(private maxReadMessageLength: number) {} + + write(data: Buffer): Buffer[] { + let readHead = 0; + let toRead: number; + const result: Buffer[] = []; + + while (readHead < data.length) { + switch (this.readState) { + case ReadState.NO_DATA: + this.readCompressFlag = data.slice(readHead, readHead + 1); + readHead += 1; + this.readState = ReadState.READING_SIZE; + this.readPartialSize.fill(0); + this.readSizeRemaining = 4; + this.readMessageSize = 0; + this.readMessageRemaining = 0; + this.readPartialMessage = []; + break; + case ReadState.READING_SIZE: + toRead = Math.min(data.length - readHead, this.readSizeRemaining); + data.copy( + this.readPartialSize, + 4 - this.readSizeRemaining, + readHead, + readHead + toRead + ); + this.readSizeRemaining -= toRead; + readHead += toRead; + // readSizeRemaining >=0 here + if (this.readSizeRemaining === 0) { + this.readMessageSize = this.readPartialSize.readUInt32BE(0); + if (this.maxReadMessageLength !== -1 && this.readMessageSize > this.maxReadMessageLength) { + throw new Error(`Received message larger than max (${this.readMessageSize} vs ${this.maxReadMessageLength})`); + } + this.readMessageRemaining = this.readMessageSize; + if (this.readMessageRemaining > 0) { + this.readState = ReadState.READING_MESSAGE; + } else { + const message = Buffer.concat( + [this.readCompressFlag, this.readPartialSize], + 5 + ); + + this.readState = ReadState.NO_DATA; + result.push(message); + } + } + break; + case ReadState.READING_MESSAGE: + toRead = Math.min(data.length - readHead, this.readMessageRemaining); + this.readPartialMessage.push(data.slice(readHead, readHead + toRead)); + this.readMessageRemaining -= toRead; + readHead += toRead; + // readMessageRemaining >=0 here + if (this.readMessageRemaining === 0) { + // At this point, we have read a full message + const framedMessageBuffers = [ + this.readCompressFlag, + this.readPartialSize, + ].concat(this.readPartialMessage); + const framedMessage = Buffer.concat( + framedMessageBuffers, + this.readMessageSize + 5 + ); + + this.readState = ReadState.NO_DATA; + result.push(framedMessage); + } + break; + default: + throw new Error('Unexpected read state'); + } + } + + return result; + } +} diff --git a/node_modules/@grpc/grpc-js/src/subchannel-address.ts b/node_modules/@grpc/grpc-js/src/subchannel-address.ts new file mode 100644 index 0000000..7e4f3e4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/subchannel-address.ts @@ -0,0 +1,252 @@ +/* + * Copyright 2021 gRPC authors. + * + * 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. + * + */ + +import { isIP, isIPv6 } from 'net'; + +export interface TcpSubchannelAddress { + port: number; + host: string; +} + +export interface IpcSubchannelAddress { + path: string; +} +/** + * This represents a single backend address to connect to. This interface is a + * subset of net.SocketConnectOpts, i.e. the options described at + * https://nodejs.org/api/net.html#net_socket_connect_options_connectlistener. + * Those are in turn a subset of the options that can be passed to http2.connect. + */ + +export type SubchannelAddress = TcpSubchannelAddress | IpcSubchannelAddress; + +export function isTcpSubchannelAddress( + address: SubchannelAddress +): address is TcpSubchannelAddress { + return 'port' in address; +} + +export function subchannelAddressEqual( + address1?: SubchannelAddress, + address2?: SubchannelAddress +): boolean { + if (!address1 && !address2) { + return true; + } + if (!address1 || !address2) { + return false; + } + if (isTcpSubchannelAddress(address1)) { + return ( + isTcpSubchannelAddress(address2) && + address1.host === address2.host && + address1.port === address2.port + ); + } else { + return !isTcpSubchannelAddress(address2) && address1.path === address2.path; + } +} + +export function subchannelAddressToString(address: SubchannelAddress): string { + if (isTcpSubchannelAddress(address)) { + if (isIPv6(address.host)) { + return '[' + address.host + ']:' + address.port; + } else { + return address.host + ':' + address.port; + } + } else { + return address.path; + } +} + +const DEFAULT_PORT = 443; + +export function stringToSubchannelAddress( + addressString: string, + port?: number +): SubchannelAddress { + if (isIP(addressString)) { + return { + host: addressString, + port: port ?? DEFAULT_PORT, + }; + } else { + return { + path: addressString, + }; + } +} + +export interface Endpoint { + addresses: SubchannelAddress[]; +} + +export function endpointEqual(endpoint1: Endpoint, endpoint2: Endpoint) { + if (endpoint1.addresses.length !== endpoint2.addresses.length) { + return false; + } + for (let i = 0; i < endpoint1.addresses.length; i++) { + if ( + !subchannelAddressEqual(endpoint1.addresses[i], endpoint2.addresses[i]) + ) { + return false; + } + } + return true; +} + +export function endpointToString(endpoint: Endpoint): string { + return ( + '[' + endpoint.addresses.map(subchannelAddressToString).join(', ') + ']' + ); +} + +export function endpointHasAddress( + endpoint: Endpoint, + expectedAddress: SubchannelAddress +): boolean { + for (const address of endpoint.addresses) { + if (subchannelAddressEqual(address, expectedAddress)) { + return true; + } + } + return false; +} + +interface EndpointMapEntry { + key: Endpoint; + value: ValueType; +} + +function endpointEqualUnordered( + endpoint1: Endpoint, + endpoint2: Endpoint +): boolean { + if (endpoint1.addresses.length !== endpoint2.addresses.length) { + return false; + } + for (const address1 of endpoint1.addresses) { + let matchFound = false; + for (const address2 of endpoint2.addresses) { + if (subchannelAddressEqual(address1, address2)) { + matchFound = true; + break; + } + } + if (!matchFound) { + return false; + } + } + return true; +} + +export class EndpointMap { + private map: Set> = new Set(); + + get size() { + return this.map.size; + } + + getForSubchannelAddress(address: SubchannelAddress): ValueType | undefined { + for (const entry of this.map) { + if (endpointHasAddress(entry.key, address)) { + return entry.value; + } + } + return undefined; + } + + /** + * Delete any entries in this map with keys that are not in endpoints + * @param endpoints + */ + deleteMissing(endpoints: Endpoint[]): ValueType[] { + const removedValues: ValueType[] = []; + for (const entry of this.map) { + let foundEntry = false; + for (const endpoint of endpoints) { + if (endpointEqualUnordered(endpoint, entry.key)) { + foundEntry = true; + } + } + if (!foundEntry) { + removedValues.push(entry.value); + this.map.delete(entry); + } + } + return removedValues; + } + + get(endpoint: Endpoint): ValueType | undefined { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint, entry.key)) { + return entry.value; + } + } + return undefined; + } + + set(endpoint: Endpoint, mapEntry: ValueType) { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint, entry.key)) { + entry.value = mapEntry; + return; + } + } + this.map.add({ key: endpoint, value: mapEntry }); + } + + delete(endpoint: Endpoint) { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint, entry.key)) { + this.map.delete(entry); + return; + } + } + } + + has(endpoint: Endpoint): boolean { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint, entry.key)) { + return true; + } + } + return false; + } + + clear() { + this.map.clear(); + } + + *keys(): IterableIterator { + for (const entry of this.map) { + yield entry.key; + } + } + + *values(): IterableIterator { + for (const entry of this.map) { + yield entry.value; + } + } + + *entries(): IterableIterator<[Endpoint, ValueType]> { + for (const entry of this.map) { + yield [entry.key, entry.value]; + } + } +} diff --git a/node_modules/@grpc/grpc-js/src/subchannel-call.ts b/node_modules/@grpc/grpc-js/src/subchannel-call.ts new file mode 100644 index 0000000..207b781 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/subchannel-call.ts @@ -0,0 +1,622 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import * as http2 from 'http2'; +import * as os from 'os'; + +import { DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH, Status } from './constants'; +import { Metadata } from './metadata'; +import { StreamDecoder } from './stream-decoder'; +import * as logging from './logging'; +import { LogVerbosity } from './constants'; +import { + InterceptingListener, + MessageContext, + StatusObject, + WriteCallback, +} from './call-interface'; +import { CallEventTracker, Transport } from './transport'; +import { AuthContext } from './auth-context'; + +const TRACER_NAME = 'subchannel_call'; + +/** + * https://nodejs.org/api/errors.html#errors_class_systemerror + */ +interface SystemError extends Error { + address?: string; + code: string; + dest?: string; + errno: number; + info?: object; + message: string; + path?: string; + port?: number; + syscall: string; +} + +/** + * Should do approximately the same thing as util.getSystemErrorName but the + * TypeScript types don't have that function for some reason so I just made my + * own. + * @param errno + */ +function getSystemErrorName(errno: number): string { + for (const [name, num] of Object.entries(os.constants.errno)) { + if (num === errno) { + return name; + } + } + return 'Unknown system error ' + errno; +} + +export interface SubchannelCall { + cancelWithStatus(status: Status, details: string): void; + getPeer(): string; + sendMessageWithContext(context: MessageContext, message: Buffer): void; + startRead(): void; + halfClose(): void; + getCallNumber(): number; + getDeadlineInfo(): string[]; + getAuthContext(): AuthContext; +} + +export interface StatusObjectWithRstCode extends StatusObject { + rstCode?: number; +} + +export interface SubchannelCallInterceptingListener + extends InterceptingListener { + onReceiveStatus(status: StatusObjectWithRstCode): void; +} + +function mapHttpStatusCode(code: number): StatusObject { + const details = `Received HTTP status code ${code}`; + let mappedStatusCode: number; + switch (code) { + // TODO(murgatroid99): handle 100 and 101 + case 400: + mappedStatusCode = Status.INTERNAL; + break; + case 401: + mappedStatusCode = Status.UNAUTHENTICATED; + break; + case 403: + mappedStatusCode = Status.PERMISSION_DENIED; + break; + case 404: + mappedStatusCode = Status.UNIMPLEMENTED; + break; + case 429: + case 502: + case 503: + case 504: + mappedStatusCode = Status.UNAVAILABLE; + break; + default: + mappedStatusCode = Status.UNKNOWN; + } + return { + code: mappedStatusCode, + details: details, + metadata: new Metadata() + }; +} + +export class Http2SubchannelCall implements SubchannelCall { + private decoder: StreamDecoder; + + private isReadFilterPending = false; + private isPushPending = false; + private canPush = false; + /** + * Indicates that an 'end' event has come from the http2 stream, so there + * will be no more data events. + */ + private readsClosed = false; + + private statusOutput = false; + + private unpushedReadMessages: Buffer[] = []; + + private httpStatusCode: number | undefined; + + // This is populated (non-null) if and only if the call has ended + private finalStatus: StatusObject | null = null; + + private internalError: SystemError | null = null; + + private serverEndedCall = false; + + private connectionDropped = false; + + constructor( + private readonly http2Stream: http2.ClientHttp2Stream, + private readonly callEventTracker: CallEventTracker, + private readonly listener: SubchannelCallInterceptingListener, + private readonly transport: Transport, + private readonly callId: number + ) { + const maxReceiveMessageLength = transport.getOptions()['grpc.max_receive_message_length'] ?? DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; + this.decoder = new StreamDecoder(maxReceiveMessageLength); + http2Stream.on('response', (headers, flags) => { + let headersString = ''; + for (const header of Object.keys(headers)) { + headersString += '\t\t' + header + ': ' + headers[header] + '\n'; + } + this.trace('Received server headers:\n' + headersString); + this.httpStatusCode = headers[':status']; + + if (flags & http2.constants.NGHTTP2_FLAG_END_STREAM) { + this.handleTrailers(headers); + } else { + let metadata: Metadata; + try { + metadata = Metadata.fromHttp2Headers(headers); + } catch (error) { + this.endCall({ + code: Status.UNKNOWN, + details: (error as Error).message, + metadata: new Metadata(), + }); + return; + } + this.listener.onReceiveMetadata(metadata); + } + }); + http2Stream.on('trailers', (headers: http2.IncomingHttpHeaders) => { + this.handleTrailers(headers); + }); + http2Stream.on('data', (data: Buffer) => { + /* If the status has already been output, allow the http2 stream to + * drain without processing the data. */ + if (this.statusOutput) { + return; + } + this.trace('receive HTTP/2 data frame of length ' + data.length); + let messages: Buffer[]; + try { + messages = this.decoder.write(data); + } catch (e) { + /* Some servers send HTML error pages along with HTTP status codes. + * When the client attempts to parse this as a length-delimited + * message, the parsed message size is greater than the default limit, + * resulting in a message decoding error. In that situation, the HTTP + * error code information is more useful to the user than the + * RESOURCE_EXHAUSTED error is, so we report that instead. Normally, + * we delay processing the HTTP status until after the stream ends, to + * prioritize reporting the gRPC status from trailers if it is present, + * but when there is a message parsing error we end the stream early + * before processing trailers. */ + if (this.httpStatusCode !== undefined && this.httpStatusCode !== 200) { + const mappedStatus = mapHttpStatusCode(this.httpStatusCode); + this.cancelWithStatus(mappedStatus.code, mappedStatus.details); + } else { + this.cancelWithStatus(Status.RESOURCE_EXHAUSTED, (e as Error).message); + } + return; + } + + for (const message of messages) { + this.trace('parsed message of length ' + message.length); + this.callEventTracker!.addMessageReceived(); + this.tryPush(message); + } + }); + http2Stream.on('end', () => { + this.readsClosed = true; + this.maybeOutputStatus(); + }); + http2Stream.on('close', () => { + this.serverEndedCall = true; + /* Use process.next tick to ensure that this code happens after any + * "error" event that may be emitted at about the same time, so that + * we can bubble up the error message from that event. */ + process.nextTick(() => { + this.trace('HTTP/2 stream closed with code ' + http2Stream.rstCode); + /* If we have a final status with an OK status code, that means that + * we have received all of the messages and we have processed the + * trailers and the call completed successfully, so it doesn't matter + * how the stream ends after that */ + if (this.finalStatus?.code === Status.OK) { + return; + } + let code: Status; + let details = ''; + switch (http2Stream.rstCode) { + case http2.constants.NGHTTP2_NO_ERROR: + /* If we get a NO_ERROR code and we already have a status, the + * stream completed properly and we just haven't fully processed + * it yet */ + if (this.finalStatus !== null) { + return; + } + if (this.httpStatusCode && this.httpStatusCode !== 200) { + const mappedStatus = mapHttpStatusCode(this.httpStatusCode); + code = mappedStatus.code; + details = mappedStatus.details; + } else { + code = Status.INTERNAL; + details = `Received RST_STREAM with code ${http2Stream.rstCode} (Call ended without gRPC status)`; + } + break; + case http2.constants.NGHTTP2_REFUSED_STREAM: + code = Status.UNAVAILABLE; + details = 'Stream refused by server'; + break; + case http2.constants.NGHTTP2_CANCEL: + /* Bug reports indicate that Node synthesizes a NGHTTP2_CANCEL + * code from connection drops. We want to prioritize reporting + * an unavailable status when that happens. */ + if (this.connectionDropped) { + code = Status.UNAVAILABLE; + details = 'Connection dropped'; + } else { + code = Status.CANCELLED; + details = 'Call cancelled'; + } + break; + case http2.constants.NGHTTP2_ENHANCE_YOUR_CALM: + code = Status.RESOURCE_EXHAUSTED; + details = 'Bandwidth exhausted or memory limit exceeded'; + break; + case http2.constants.NGHTTP2_INADEQUATE_SECURITY: + code = Status.PERMISSION_DENIED; + details = 'Protocol not secure enough'; + break; + case http2.constants.NGHTTP2_INTERNAL_ERROR: + code = Status.INTERNAL; + if (this.internalError === null) { + /* This error code was previously handled in the default case, and + * there are several instances of it online, so I wanted to + * preserve the original error message so that people find existing + * information in searches, but also include the more recognizable + * "Internal server error" message. */ + details = `Received RST_STREAM with code ${http2Stream.rstCode} (Internal server error)`; + } else { + if ( + this.internalError.code === 'ECONNRESET' || + this.internalError.code === 'ETIMEDOUT' + ) { + code = Status.UNAVAILABLE; + details = this.internalError.message; + } else { + /* The "Received RST_STREAM with code ..." error is preserved + * here for continuity with errors reported online, but the + * error message at the end will probably be more relevant in + * most cases. */ + details = `Received RST_STREAM with code ${http2Stream.rstCode} triggered by internal client error: ${this.internalError.message}`; + } + } + break; + default: + code = Status.INTERNAL; + details = `Received RST_STREAM with code ${http2Stream.rstCode}`; + } + // This is a no-op if trailers were received at all. + // This is OK, because status codes emitted here correspond to more + // catastrophic issues that prevent us from receiving trailers in the + // first place. + this.endCall({ + code, + details, + metadata: new Metadata(), + rstCode: http2Stream.rstCode, + }); + }); + }); + http2Stream.on('error', (err: SystemError) => { + /* We need an error handler here to stop "Uncaught Error" exceptions + * from bubbling up. However, errors here should all correspond to + * "close" events, where we will handle the error more granularly */ + /* Specifically looking for stream errors that were *not* constructed + * from a RST_STREAM response here: + * https://github.com/nodejs/node/blob/8b8620d580314050175983402dfddf2674e8e22a/lib/internal/http2/core.js#L2267 + */ + if (err.code !== 'ERR_HTTP2_STREAM_ERROR') { + this.trace( + 'Node error event: message=' + + err.message + + ' code=' + + err.code + + ' errno=' + + getSystemErrorName(err.errno) + + ' syscall=' + + err.syscall + ); + this.internalError = err; + } + this.callEventTracker.onStreamEnd(false); + }); + } + getDeadlineInfo(): string[] { + return [`remote_addr=${this.getPeer()}`]; + } + + public onDisconnect() { + this.connectionDropped = true; + /* Give the call an event loop cycle to finish naturally before reporting + * the disconnection as an error. */ + setImmediate(() => { + this.endCall({ + code: Status.UNAVAILABLE, + details: 'Connection dropped', + metadata: new Metadata(), + }); + }); + } + + private outputStatus() { + /* Precondition: this.finalStatus !== null */ + if (!this.statusOutput) { + this.statusOutput = true; + this.trace( + 'ended with status: code=' + + this.finalStatus!.code + + ' details="' + + this.finalStatus!.details + + '"' + ); + this.callEventTracker.onCallEnd(this.finalStatus!); + /* We delay the actual action of bubbling up the status to insulate the + * cleanup code in this class from any errors that may be thrown in the + * upper layers as a result of bubbling up the status. In particular, + * if the status is not OK, the "error" event may be emitted + * synchronously at the top level, which will result in a thrown error if + * the user does not handle that event. */ + process.nextTick(() => { + this.listener.onReceiveStatus(this.finalStatus!); + }); + /* Leave the http2 stream in flowing state to drain incoming messages, to + * ensure that the stream closure completes. The call stream already does + * not push more messages after the status is output, so the messages go + * nowhere either way. */ + this.http2Stream.resume(); + } + } + + private trace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + TRACER_NAME, + '[' + this.callId + '] ' + text + ); + } + + /** + * On first call, emits a 'status' event with the given StatusObject. + * Subsequent calls are no-ops. + * @param status The status of the call. + */ + private endCall(status: StatusObjectWithRstCode): void { + /* If the status is OK and a new status comes in (e.g. from a + * deserialization failure), that new status takes priority */ + if (this.finalStatus === null || this.finalStatus.code === Status.OK) { + this.finalStatus = status; + this.maybeOutputStatus(); + } + this.destroyHttp2Stream(); + } + + private maybeOutputStatus() { + if (this.finalStatus !== null) { + /* The combination check of readsClosed and that the two message buffer + * arrays are empty checks that there all incoming data has been fully + * processed */ + if ( + this.finalStatus.code !== Status.OK || + (this.readsClosed && + this.unpushedReadMessages.length === 0 && + !this.isReadFilterPending && + !this.isPushPending) + ) { + this.outputStatus(); + } + } + } + + private push(message: Buffer): void { + this.trace( + 'pushing to reader message of length ' + + (message instanceof Buffer ? message.length : null) + ); + this.canPush = false; + this.isPushPending = true; + process.nextTick(() => { + this.isPushPending = false; + /* If we have already output the status any later messages should be + * ignored, and can cause out-of-order operation errors higher up in the + * stack. Checking as late as possible here to avoid any race conditions. + */ + if (this.statusOutput) { + return; + } + this.listener.onReceiveMessage(message); + this.maybeOutputStatus(); + }); + } + + private tryPush(messageBytes: Buffer): void { + if (this.canPush) { + this.http2Stream!.pause(); + this.push(messageBytes); + } else { + this.trace( + 'unpushedReadMessages.push message of length ' + messageBytes.length + ); + this.unpushedReadMessages.push(messageBytes); + } + } + + private handleTrailers(headers: http2.IncomingHttpHeaders) { + this.serverEndedCall = true; + this.callEventTracker.onStreamEnd(true); + let headersString = ''; + for (const header of Object.keys(headers)) { + headersString += '\t\t' + header + ': ' + headers[header] + '\n'; + } + this.trace('Received server trailers:\n' + headersString); + let metadata: Metadata; + try { + metadata = Metadata.fromHttp2Headers(headers); + } catch (e) { + metadata = new Metadata(); + } + const metadataMap = metadata.getMap(); + let status: StatusObject; + if (typeof metadataMap['grpc-status'] === 'string') { + const receivedStatus: Status = Number(metadataMap['grpc-status']); + this.trace('received status code ' + receivedStatus + ' from server'); + metadata.remove('grpc-status'); + let details = ''; + if (typeof metadataMap['grpc-message'] === 'string') { + try { + details = decodeURI(metadataMap['grpc-message']); + } catch (e) { + details = metadataMap['grpc-message']; + } + metadata.remove('grpc-message'); + this.trace( + 'received status details string "' + details + '" from server' + ); + } + status = { + code: receivedStatus, + details: details, + metadata: metadata + }; + } else if (this.httpStatusCode) { + status = mapHttpStatusCode(this.httpStatusCode); + status.metadata = metadata; + } else { + status = { + code: Status.UNKNOWN, + details: 'No status information received', + metadata: metadata + }; + } + // This is a no-op if the call was already ended when handling headers. + this.endCall(status); + } + + private destroyHttp2Stream() { + // The http2 stream could already have been destroyed if cancelWithStatus + // is called in response to an internal http2 error. + if (this.http2Stream.destroyed) { + return; + } + /* If the server ended the call, sending an RST_STREAM is redundant, so we + * just half close on the client side instead to finish closing the stream. + */ + if (this.serverEndedCall) { + this.http2Stream.end(); + } else { + /* If the call has ended with an OK status, communicate that when closing + * the stream, partly to avoid a situation in which we detect an error + * RST_STREAM as a result after we have the status */ + let code: number; + if (this.finalStatus?.code === Status.OK) { + code = http2.constants.NGHTTP2_NO_ERROR; + } else { + code = http2.constants.NGHTTP2_CANCEL; + } + this.trace('close http2 stream with code ' + code); + this.http2Stream.close(code); + } + } + + cancelWithStatus(status: Status, details: string): void { + this.trace( + 'cancelWithStatus code: ' + status + ' details: "' + details + '"' + ); + this.endCall({ code: status, details, metadata: new Metadata() }); + } + + getStatus(): StatusObject | null { + return this.finalStatus; + } + + getPeer(): string { + return this.transport.getPeerName(); + } + + getCallNumber(): number { + return this.callId; + } + + getAuthContext(): AuthContext { + return this.transport.getAuthContext(); + } + + startRead() { + /* If the stream has ended with an error, we should not emit any more + * messages and we should communicate that the stream has ended */ + if (this.finalStatus !== null && this.finalStatus.code !== Status.OK) { + this.readsClosed = true; + this.maybeOutputStatus(); + return; + } + this.canPush = true; + if (this.unpushedReadMessages.length > 0) { + const nextMessage: Buffer = this.unpushedReadMessages.shift()!; + this.push(nextMessage); + return; + } + /* Only resume reading from the http2Stream if we don't have any pending + * messages to emit */ + this.http2Stream.resume(); + } + + sendMessageWithContext(context: MessageContext, message: Buffer) { + this.trace('write() called with message of length ' + message.length); + const cb: WriteCallback = (error?: Error | null) => { + /* nextTick here ensures that no stream action can be taken in the call + * stack of the write callback, in order to hopefully work around + * https://github.com/nodejs/node/issues/49147 */ + process.nextTick(() => { + let code: Status = Status.UNAVAILABLE; + if ( + (error as NodeJS.ErrnoException)?.code === + 'ERR_STREAM_WRITE_AFTER_END' + ) { + code = Status.INTERNAL; + } + if (error) { + this.cancelWithStatus(code, `Write error: ${error.message}`); + } + context.callback?.(); + }); + }; + this.trace('sending data chunk of length ' + message.length); + this.callEventTracker.addMessageSent(); + try { + this.http2Stream!.write(message, cb); + } catch (error) { + this.endCall({ + code: Status.UNAVAILABLE, + details: `Write failed with error ${(error as Error).message}`, + metadata: new Metadata(), + }); + } + } + + halfClose() { + this.trace('end() called'); + this.trace('calling end() on HTTP/2 stream'); + this.http2Stream.end(); + } +} diff --git a/node_modules/@grpc/grpc-js/src/subchannel-interface.ts b/node_modules/@grpc/grpc-js/src/subchannel-interface.ts new file mode 100644 index 0000000..d25e91c --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/subchannel-interface.ts @@ -0,0 +1,176 @@ +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ + +import { CallCredentials } from './call-credentials'; +import { Channel } from './channel'; +import type { SubchannelRef } from './channelz'; +import { ConnectivityState } from './connectivity-state'; +import { Subchannel } from './subchannel'; + +export type ConnectivityStateListener = ( + subchannel: SubchannelInterface, + previousState: ConnectivityState, + newState: ConnectivityState, + keepaliveTime: number, + errorMessage?: string +) => void; + +export type HealthListener = (healthy: boolean) => void; + +export interface DataWatcher { + setSubchannel(subchannel: Subchannel): void; + destroy(): void; +} + +/** + * This is an interface for load balancing policies to use to interact with + * subchannels. This allows load balancing policies to wrap and unwrap + * subchannels. + * + * Any load balancing policy that wraps subchannels must unwrap the subchannel + * in the picker, so that other load balancing policies consistently have + * access to their own wrapper objects. + */ +export interface SubchannelInterface { + getConnectivityState(): ConnectivityState; + addConnectivityStateListener(listener: ConnectivityStateListener): void; + removeConnectivityStateListener(listener: ConnectivityStateListener): void; + startConnecting(): void; + getAddress(): string; + throttleKeepalive(newKeepaliveTime: number): void; + ref(): void; + unref(): void; + getChannelzRef(): SubchannelRef; + isHealthy(): boolean; + addHealthStateWatcher(listener: HealthListener): void; + removeHealthStateWatcher(listener: HealthListener): void; + addDataWatcher(dataWatcher: DataWatcher): void; + /** + * If this is a wrapper, return the wrapped subchannel, otherwise return this + */ + getRealSubchannel(): Subchannel; + /** + * Returns true if this and other both proxy the same underlying subchannel. + * Can be used instead of directly accessing getRealSubchannel to allow mocks + * to avoid implementing getRealSubchannel + */ + realSubchannelEquals(other: SubchannelInterface): boolean; + /** + * Get the call credentials associated with the channel credentials for this + * subchannel. + */ + getCallCredentials(): CallCredentials; + /** + * Get a channel that can be used to make requests with just this + */ + getChannel(): Channel; +} + +export abstract class BaseSubchannelWrapper implements SubchannelInterface { + private healthy = true; + private healthListeners: Set = new Set(); + private refcount = 0; + private dataWatchers: Set = new Set(); + constructor(protected child: SubchannelInterface) { + child.addHealthStateWatcher(childHealthy => { + /* A change to the child health state only affects this wrapper's overall + * health state if this wrapper is reporting healthy. */ + if (this.healthy) { + this.updateHealthListeners(); + } + }); + } + + private updateHealthListeners(): void { + for (const listener of this.healthListeners) { + listener(this.isHealthy()); + } + } + + getConnectivityState(): ConnectivityState { + return this.child.getConnectivityState(); + } + addConnectivityStateListener(listener: ConnectivityStateListener): void { + this.child.addConnectivityStateListener(listener); + } + removeConnectivityStateListener(listener: ConnectivityStateListener): void { + this.child.removeConnectivityStateListener(listener); + } + startConnecting(): void { + this.child.startConnecting(); + } + getAddress(): string { + return this.child.getAddress(); + } + throttleKeepalive(newKeepaliveTime: number): void { + this.child.throttleKeepalive(newKeepaliveTime); + } + ref(): void { + this.child.ref(); + this.refcount += 1; + } + unref(): void { + this.child.unref(); + this.refcount -= 1; + if (this.refcount === 0) { + this.destroy(); + } + } + protected destroy() { + for (const watcher of this.dataWatchers) { + watcher.destroy(); + } + } + getChannelzRef(): SubchannelRef { + return this.child.getChannelzRef(); + } + isHealthy(): boolean { + return this.healthy && this.child.isHealthy(); + } + addHealthStateWatcher(listener: HealthListener): void { + this.healthListeners.add(listener); + } + removeHealthStateWatcher(listener: HealthListener): void { + this.healthListeners.delete(listener); + } + addDataWatcher(dataWatcher: DataWatcher): void { + dataWatcher.setSubchannel(this.getRealSubchannel()); + this.dataWatchers.add(dataWatcher); + } + protected setHealthy(healthy: boolean): void { + if (healthy !== this.healthy) { + this.healthy = healthy; + /* A change to this wrapper's health state only affects the overall + * reported health state if the child is healthy. */ + if (this.child.isHealthy()) { + this.updateHealthListeners(); + } + } + } + getRealSubchannel(): Subchannel { + return this.child.getRealSubchannel(); + } + realSubchannelEquals(other: SubchannelInterface): boolean { + return this.getRealSubchannel() === other.getRealSubchannel(); + } + getCallCredentials(): CallCredentials { + return this.child.getCallCredentials(); + } + getChannel(): Channel { + return this.child.getChannel(); + } +} diff --git a/node_modules/@grpc/grpc-js/src/subchannel-pool.ts b/node_modules/@grpc/grpc-js/src/subchannel-pool.ts new file mode 100644 index 0000000..a5dec72 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/subchannel-pool.ts @@ -0,0 +1,176 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { ChannelOptions, channelOptionsEqual } from './channel-options'; +import { Subchannel } from './subchannel'; +import { + SubchannelAddress, + subchannelAddressEqual, +} from './subchannel-address'; +import { ChannelCredentials } from './channel-credentials'; +import { GrpcUri, uriToString } from './uri-parser'; +import { Http2SubchannelConnector } from './transport'; + +// 10 seconds in milliseconds. This value is arbitrary. +/** + * The amount of time in between checks for dropping subchannels that have no + * other references + */ +const REF_CHECK_INTERVAL = 10_000; + +export class SubchannelPool { + private pool: { + [channelTarget: string]: Array<{ + subchannelAddress: SubchannelAddress; + channelArguments: ChannelOptions; + channelCredentials: ChannelCredentials; + subchannel: Subchannel; + }>; + } = Object.create(null); + + /** + * A timer of a task performing a periodic subchannel cleanup. + */ + private cleanupTimer: NodeJS.Timeout | null = null; + + /** + * A pool of subchannels use for making connections. Subchannels with the + * exact same parameters will be reused. + */ + constructor() {} + + /** + * Unrefs all unused subchannels and cancels the cleanup task if all + * subchannels have been unrefed. + */ + unrefUnusedSubchannels(): void { + let allSubchannelsUnrefed = true; + + /* These objects are created with Object.create(null), so they do not + * have a prototype, which means that for (... in ...) loops over them + * do not need to be filtered */ + // eslint-disable-disable-next-line:forin + for (const channelTarget in this.pool) { + const subchannelObjArray = this.pool[channelTarget]; + + const refedSubchannels = subchannelObjArray.filter( + value => !value.subchannel.unrefIfOneRef() + ); + + if (refedSubchannels.length > 0) { + allSubchannelsUnrefed = false; + } + + /* For each subchannel in the pool, try to unref it if it has + * exactly one ref (which is the ref from the pool itself). If that + * does happen, remove the subchannel from the pool */ + this.pool[channelTarget] = refedSubchannels; + } + /* Currently we do not delete keys with empty values. If that results + * in significant memory usage we should change it. */ + + // Cancel the cleanup task if all subchannels have been unrefed. + if (allSubchannelsUnrefed && this.cleanupTimer !== null) { + clearInterval(this.cleanupTimer); + this.cleanupTimer = null; + } + } + + /** + * Ensures that the cleanup task is spawned. + */ + ensureCleanupTask(): void { + if (this.cleanupTimer === null) { + this.cleanupTimer = setInterval(() => { + this.unrefUnusedSubchannels(); + }, REF_CHECK_INTERVAL); + + // Unref because this timer should not keep the event loop running. + // Call unref only if it exists to address electron/electron#21162 + this.cleanupTimer.unref?.(); + } + } + + /** + * Get a subchannel if one already exists with exactly matching parameters. + * Otherwise, create and save a subchannel with those parameters. + * @param channelTarget + * @param subchannelTarget + * @param channelArguments + * @param channelCredentials + */ + getOrCreateSubchannel( + channelTargetUri: GrpcUri, + subchannelTarget: SubchannelAddress, + channelArguments: ChannelOptions, + channelCredentials: ChannelCredentials + ): Subchannel { + this.ensureCleanupTask(); + const channelTarget = uriToString(channelTargetUri); + if (channelTarget in this.pool) { + const subchannelObjArray = this.pool[channelTarget]; + for (const subchannelObj of subchannelObjArray) { + if ( + subchannelAddressEqual( + subchannelTarget, + subchannelObj.subchannelAddress + ) && + channelOptionsEqual( + channelArguments, + subchannelObj.channelArguments + ) && + channelCredentials._equals(subchannelObj.channelCredentials) + ) { + return subchannelObj.subchannel; + } + } + } + // If we get here, no matching subchannel was found + const subchannel = new Subchannel( + channelTargetUri, + subchannelTarget, + channelArguments, + channelCredentials, + new Http2SubchannelConnector(channelTargetUri) + ); + if (!(channelTarget in this.pool)) { + this.pool[channelTarget] = []; + } + this.pool[channelTarget].push({ + subchannelAddress: subchannelTarget, + channelArguments, + channelCredentials, + subchannel, + }); + subchannel.ref(); + return subchannel; + } +} + +const globalSubchannelPool = new SubchannelPool(); + +/** + * Get either the global subchannel pool, or a new subchannel pool. + * @param global + */ +export function getSubchannelPool(global: boolean): SubchannelPool { + if (global) { + return globalSubchannelPool; + } else { + return new SubchannelPool(); + } +} diff --git a/node_modules/@grpc/grpc-js/src/subchannel.ts b/node_modules/@grpc/grpc-js/src/subchannel.ts new file mode 100644 index 0000000..1156a0c --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/subchannel.ts @@ -0,0 +1,559 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { ChannelCredentials, SecureConnector } from './channel-credentials'; +import { Metadata } from './metadata'; +import { ChannelOptions } from './channel-options'; +import { ConnectivityState } from './connectivity-state'; +import { BackoffTimeout, BackoffOptions } from './backoff-timeout'; +import * as logging from './logging'; +import { LogVerbosity, Status } from './constants'; +import { GrpcUri, uriToString } from './uri-parser'; +import { + SubchannelAddress, + subchannelAddressToString, +} from './subchannel-address'; +import { + SubchannelRef, + ChannelzTrace, + ChannelzChildrenTracker, + ChannelzChildrenTrackerStub, + SubchannelInfo, + registerChannelzSubchannel, + ChannelzCallTracker, + ChannelzCallTrackerStub, + unregisterChannelzRef, + ChannelzTraceStub, +} from './channelz'; +import { + ConnectivityStateListener, + DataWatcher, + SubchannelInterface, +} from './subchannel-interface'; +import { SubchannelCallInterceptingListener } from './subchannel-call'; +import { SubchannelCall } from './subchannel-call'; +import { CallEventTracker, SubchannelConnector, Transport } from './transport'; +import { CallCredentials } from './call-credentials'; +import { SingleSubchannelChannel } from './single-subchannel-channel'; +import { Channel } from './channel'; + +const TRACER_NAME = 'subchannel'; + +/* setInterval and setTimeout only accept signed 32 bit integers. JS doesn't + * have a constant for the max signed 32 bit integer, so this is a simple way + * to calculate it */ +const KEEPALIVE_MAX_TIME_MS = ~(1 << 31); + +export interface DataProducer { + addDataWatcher(dataWatcher: DataWatcher): void; + removeDataWatcher(dataWatcher: DataWatcher): void; +} + +export class Subchannel implements SubchannelInterface { + /** + * The subchannel's current connectivity state. Invariant: `session` === `null` + * if and only if `connectivityState` is IDLE or TRANSIENT_FAILURE. + */ + private connectivityState: ConnectivityState = ConnectivityState.IDLE; + /** + * The underlying http2 session used to make requests. + */ + private transport: Transport | null = null; + /** + * Indicates that the subchannel should transition from TRANSIENT_FAILURE to + * CONNECTING instead of IDLE when the backoff timeout ends. + */ + private continueConnecting = false; + /** + * A list of listener functions that will be called whenever the connectivity + * state changes. Will be modified by `addConnectivityStateListener` and + * `removeConnectivityStateListener` + */ + private stateListeners: Set = new Set(); + + private backoffTimeout: BackoffTimeout; + + private keepaliveTime: number; + /** + * Tracks channels and subchannel pools with references to this subchannel + */ + private refcount = 0; + + /** + * A string representation of the subchannel address, for logging/tracing + */ + private subchannelAddressString: string; + + // Channelz info + private readonly channelzEnabled: boolean = true; + private channelzRef: SubchannelRef; + + private channelzTrace: ChannelzTrace | ChannelzTraceStub; + private callTracker: ChannelzCallTracker | ChannelzCallTrackerStub; + private childrenTracker: + | ChannelzChildrenTracker + | ChannelzChildrenTrackerStub; + + // Channelz socket info + private streamTracker: ChannelzCallTracker | ChannelzCallTrackerStub; + + private secureConnector: SecureConnector; + + private dataProducers: Map = new Map(); + + private subchannelChannel: Channel | null = null; + + /** + * A class representing a connection to a single backend. + * @param channelTarget The target string for the channel as a whole + * @param subchannelAddress The address for the backend that this subchannel + * will connect to + * @param options The channel options, plus any specific subchannel options + * for this subchannel + * @param credentials The channel credentials used to establish this + * connection + */ + constructor( + private channelTarget: GrpcUri, + private subchannelAddress: SubchannelAddress, + private options: ChannelOptions, + credentials: ChannelCredentials, + private connector: SubchannelConnector + ) { + const backoffOptions: BackoffOptions = { + initialDelay: options['grpc.initial_reconnect_backoff_ms'], + maxDelay: options['grpc.max_reconnect_backoff_ms'], + }; + this.backoffTimeout = new BackoffTimeout(() => { + this.handleBackoffTimer(); + }, backoffOptions); + this.backoffTimeout.unref(); + this.subchannelAddressString = subchannelAddressToString(subchannelAddress); + + this.keepaliveTime = options['grpc.keepalive_time_ms'] ?? -1; + + if (options['grpc.enable_channelz'] === 0) { + this.channelzEnabled = false; + this.channelzTrace = new ChannelzTraceStub(); + this.callTracker = new ChannelzCallTrackerStub(); + this.childrenTracker = new ChannelzChildrenTrackerStub(); + this.streamTracker = new ChannelzCallTrackerStub(); + } else { + this.channelzTrace = new ChannelzTrace(); + this.callTracker = new ChannelzCallTracker(); + this.childrenTracker = new ChannelzChildrenTracker(); + this.streamTracker = new ChannelzCallTracker(); + } + + this.channelzRef = registerChannelzSubchannel( + this.subchannelAddressString, + () => this.getChannelzInfo(), + this.channelzEnabled + ); + + this.channelzTrace.addTrace('CT_INFO', 'Subchannel created'); + this.trace( + 'Subchannel constructed with options ' + + JSON.stringify(options, undefined, 2) + ); + this.secureConnector = credentials._createSecureConnector(channelTarget, options); + } + + private getChannelzInfo(): SubchannelInfo { + return { + state: this.connectivityState, + trace: this.channelzTrace, + callTracker: this.callTracker, + children: this.childrenTracker.getChildLists(), + target: this.subchannelAddressString, + }; + } + + private trace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + TRACER_NAME, + '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text + ); + } + + private refTrace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + 'subchannel_refcount', + '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text + ); + } + + private handleBackoffTimer() { + if (this.continueConnecting) { + this.transitionToState( + [ConnectivityState.TRANSIENT_FAILURE], + ConnectivityState.CONNECTING + ); + } else { + this.transitionToState( + [ConnectivityState.TRANSIENT_FAILURE], + ConnectivityState.IDLE + ); + } + } + + /** + * Start a backoff timer with the current nextBackoff timeout + */ + private startBackoff() { + this.backoffTimeout.runOnce(); + } + + private stopBackoff() { + this.backoffTimeout.stop(); + this.backoffTimeout.reset(); + } + + private startConnectingInternal() { + let options = this.options; + if (options['grpc.keepalive_time_ms']) { + const adjustedKeepaliveTime = Math.min( + this.keepaliveTime, + KEEPALIVE_MAX_TIME_MS + ); + options = { ...options, 'grpc.keepalive_time_ms': adjustedKeepaliveTime }; + } + this.connector + .connect(this.subchannelAddress, this.secureConnector, options) + .then( + transport => { + if ( + this.transitionToState( + [ConnectivityState.CONNECTING], + ConnectivityState.READY + ) + ) { + this.transport = transport; + if (this.channelzEnabled) { + this.childrenTracker.refChild(transport.getChannelzRef()); + } + transport.addDisconnectListener(tooManyPings => { + this.transitionToState( + [ConnectivityState.READY], + ConnectivityState.IDLE + ); + if (tooManyPings && this.keepaliveTime > 0) { + this.keepaliveTime *= 2; + logging.log( + LogVerbosity.ERROR, + `Connection to ${uriToString(this.channelTarget)} at ${ + this.subchannelAddressString + } rejected by server because of excess pings. Increasing ping interval to ${ + this.keepaliveTime + } ms` + ); + } + }); + } else { + /* If we can't transition from CONNECTING to READY here, we will + * not be using this transport, so release its resources. */ + transport.shutdown(); + } + }, + error => { + this.transitionToState( + [ConnectivityState.CONNECTING], + ConnectivityState.TRANSIENT_FAILURE, + `${error}` + ); + } + ); + } + + /** + * Initiate a state transition from any element of oldStates to the new + * state. If the current connectivityState is not in oldStates, do nothing. + * @param oldStates The set of states to transition from + * @param newState The state to transition to + * @returns True if the state changed, false otherwise + */ + private transitionToState( + oldStates: ConnectivityState[], + newState: ConnectivityState, + errorMessage?: string + ): boolean { + if (oldStates.indexOf(this.connectivityState) === -1) { + return false; + } + if (errorMessage) { + this.trace( + ConnectivityState[this.connectivityState] + + ' -> ' + + ConnectivityState[newState] + + ' with error "' + errorMessage + '"' + ); + + } else { + this.trace( + ConnectivityState[this.connectivityState] + + ' -> ' + + ConnectivityState[newState] + ); + } + if (this.channelzEnabled) { + this.channelzTrace.addTrace( + 'CT_INFO', + 'Connectivity state change to ' + ConnectivityState[newState] + ); + } + const previousState = this.connectivityState; + this.connectivityState = newState; + switch (newState) { + case ConnectivityState.READY: + this.stopBackoff(); + break; + case ConnectivityState.CONNECTING: + this.startBackoff(); + this.startConnectingInternal(); + this.continueConnecting = false; + break; + case ConnectivityState.TRANSIENT_FAILURE: + if (this.channelzEnabled && this.transport) { + this.childrenTracker.unrefChild(this.transport.getChannelzRef()); + } + this.transport?.shutdown(); + this.transport = null; + /* If the backoff timer has already ended by the time we get to the + * TRANSIENT_FAILURE state, we want to immediately transition out of + * TRANSIENT_FAILURE as though the backoff timer is ending right now */ + if (!this.backoffTimeout.isRunning()) { + process.nextTick(() => { + this.handleBackoffTimer(); + }); + } + break; + case ConnectivityState.IDLE: + if (this.channelzEnabled && this.transport) { + this.childrenTracker.unrefChild(this.transport.getChannelzRef()); + } + this.transport?.shutdown(); + this.transport = null; + break; + default: + throw new Error(`Invalid state: unknown ConnectivityState ${newState}`); + } + for (const listener of this.stateListeners) { + listener(this, previousState, newState, this.keepaliveTime, errorMessage); + } + return true; + } + + ref() { + this.refTrace('refcount ' + this.refcount + ' -> ' + (this.refcount + 1)); + this.refcount += 1; + } + + unref() { + this.refTrace('refcount ' + this.refcount + ' -> ' + (this.refcount - 1)); + this.refcount -= 1; + if (this.refcount === 0) { + this.channelzTrace.addTrace('CT_INFO', 'Shutting down'); + unregisterChannelzRef(this.channelzRef); + this.secureConnector.destroy(); + process.nextTick(() => { + this.transitionToState( + [ConnectivityState.CONNECTING, ConnectivityState.READY], + ConnectivityState.IDLE + ); + }); + } + } + + unrefIfOneRef(): boolean { + if (this.refcount === 1) { + this.unref(); + return true; + } + return false; + } + + createCall( + metadata: Metadata, + host: string, + method: string, + listener: SubchannelCallInterceptingListener + ): SubchannelCall { + if (!this.transport) { + throw new Error('Cannot create call, subchannel not READY'); + } + let statsTracker: Partial; + if (this.channelzEnabled) { + this.callTracker.addCallStarted(); + this.streamTracker.addCallStarted(); + statsTracker = { + onCallEnd: status => { + if (status.code === Status.OK) { + this.callTracker.addCallSucceeded(); + } else { + this.callTracker.addCallFailed(); + } + }, + }; + } else { + statsTracker = {}; + } + return this.transport.createCall( + metadata, + host, + method, + listener, + statsTracker + ); + } + + /** + * If the subchannel is currently IDLE, start connecting and switch to the + * CONNECTING state. If the subchannel is current in TRANSIENT_FAILURE, + * the next time it would transition to IDLE, start connecting again instead. + * Otherwise, do nothing. + */ + startConnecting() { + process.nextTick(() => { + /* First, try to transition from IDLE to connecting. If that doesn't happen + * because the state is not currently IDLE, check if it is + * TRANSIENT_FAILURE, and if so indicate that it should go back to + * connecting after the backoff timer ends. Otherwise do nothing */ + if ( + !this.transitionToState( + [ConnectivityState.IDLE], + ConnectivityState.CONNECTING + ) + ) { + if (this.connectivityState === ConnectivityState.TRANSIENT_FAILURE) { + this.continueConnecting = true; + } + } + }); + } + + /** + * Get the subchannel's current connectivity state. + */ + getConnectivityState() { + return this.connectivityState; + } + + /** + * Add a listener function to be called whenever the subchannel's + * connectivity state changes. + * @param listener + */ + addConnectivityStateListener(listener: ConnectivityStateListener) { + this.stateListeners.add(listener); + } + + /** + * Remove a listener previously added with `addConnectivityStateListener` + * @param listener A reference to a function previously passed to + * `addConnectivityStateListener` + */ + removeConnectivityStateListener(listener: ConnectivityStateListener) { + this.stateListeners.delete(listener); + } + + /** + * Reset the backoff timeout, and immediately start connecting if in backoff. + */ + resetBackoff() { + process.nextTick(() => { + this.backoffTimeout.reset(); + this.transitionToState( + [ConnectivityState.TRANSIENT_FAILURE], + ConnectivityState.CONNECTING + ); + }); + } + + getAddress(): string { + return this.subchannelAddressString; + } + + getChannelzRef(): SubchannelRef { + return this.channelzRef; + } + + isHealthy(): boolean { + return true; + } + + addHealthStateWatcher(listener: (healthy: boolean) => void): void { + // Do nothing with the listener + } + + removeHealthStateWatcher(listener: (healthy: boolean) => void): void { + // Do nothing with the listener + } + + getRealSubchannel(): this { + return this; + } + + realSubchannelEquals(other: SubchannelInterface): boolean { + return other.getRealSubchannel() === this; + } + + throttleKeepalive(newKeepaliveTime: number) { + if (newKeepaliveTime > this.keepaliveTime) { + this.keepaliveTime = newKeepaliveTime; + } + } + getCallCredentials(): CallCredentials { + return this.secureConnector.getCallCredentials(); + } + + getChannel(): Channel { + if (!this.subchannelChannel) { + this.subchannelChannel = new SingleSubchannelChannel(this, this.channelTarget, this.options); + } + return this.subchannelChannel; + } + + addDataWatcher(dataWatcher: DataWatcher): void { + throw new Error('Not implemented'); + } + + getOrCreateDataProducer(name: string, createDataProducer: (subchannel: Subchannel) => DataProducer): DataProducer { + const existingProducer = this.dataProducers.get(name); + if (existingProducer){ + return existingProducer; + } + const newProducer = createDataProducer(this); + this.dataProducers.set(name, newProducer); + return newProducer; + } + + removeDataProducer(name: string) { + this.dataProducers.delete(name); + } +} diff --git a/node_modules/@grpc/grpc-js/src/tls-helpers.ts b/node_modules/@grpc/grpc-js/src/tls-helpers.ts new file mode 100644 index 0000000..3f7a62e --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/tls-helpers.ts @@ -0,0 +1,35 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import * as fs from 'fs'; + +export const CIPHER_SUITES: string | undefined = + process.env.GRPC_SSL_CIPHER_SUITES; + +const DEFAULT_ROOTS_FILE_PATH = process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH; + +let defaultRootsData: Buffer | null = null; + +export function getDefaultRootsData(): Buffer | null { + if (DEFAULT_ROOTS_FILE_PATH) { + if (defaultRootsData === null) { + defaultRootsData = fs.readFileSync(DEFAULT_ROOTS_FILE_PATH); + } + return defaultRootsData; + } + return null; +} diff --git a/node_modules/@grpc/grpc-js/src/transport.ts b/node_modules/@grpc/grpc-js/src/transport.ts new file mode 100644 index 0000000..a1cca59 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/transport.ts @@ -0,0 +1,825 @@ +/* + * Copyright 2023 gRPC authors. + * + * 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. + * + */ + +import * as http2 from 'http2'; +import { + CipherNameAndProtocol, + TLSSocket, +} from 'tls'; +import { PartialStatusObject } from './call-interface'; +import { SecureConnector, SecureConnectResult } from './channel-credentials'; +import { ChannelOptions } from './channel-options'; +import { + ChannelzCallTracker, + ChannelzCallTrackerStub, + registerChannelzSocket, + SocketInfo, + SocketRef, + TlsInfo, + unregisterChannelzRef, +} from './channelz'; +import { LogVerbosity } from './constants'; +import { getProxiedConnection } from './http_proxy'; +import * as logging from './logging'; +import { getDefaultAuthority } from './resolver'; +import { + stringToSubchannelAddress, + SubchannelAddress, + subchannelAddressToString, +} from './subchannel-address'; +import { GrpcUri, parseUri, uriToString } from './uri-parser'; +import * as net from 'net'; +import { + Http2SubchannelCall, + SubchannelCall, + SubchannelCallInterceptingListener, +} from './subchannel-call'; +import { Metadata } from './metadata'; +import { getNextCallNumber } from './call-number'; +import { Socket } from 'net'; +import { AuthContext } from './auth-context'; + +const TRACER_NAME = 'transport'; +const FLOW_CONTROL_TRACER_NAME = 'transport_flowctrl'; + +const clientVersion = require('../../package.json').version; + +const { + HTTP2_HEADER_AUTHORITY, + HTTP2_HEADER_CONTENT_TYPE, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_PATH, + HTTP2_HEADER_TE, + HTTP2_HEADER_USER_AGENT, +} = http2.constants; + +const KEEPALIVE_TIMEOUT_MS = 20000; + +export interface CallEventTracker { + addMessageSent(): void; + addMessageReceived(): void; + onCallEnd(status: PartialStatusObject): void; + onStreamEnd(success: boolean): void; +} + +export interface TransportDisconnectListener { + (tooManyPings: boolean): void; +} + +export interface Transport { + getChannelzRef(): SocketRef; + getPeerName(): string; + getOptions(): ChannelOptions; + getAuthContext(): AuthContext; + createCall( + metadata: Metadata, + host: string, + method: string, + listener: SubchannelCallInterceptingListener, + subchannelCallStatsTracker: Partial + ): SubchannelCall; + addDisconnectListener(listener: TransportDisconnectListener): void; + shutdown(): void; +} + +const tooManyPingsData: Buffer = Buffer.from('too_many_pings', 'ascii'); + +class Http2Transport implements Transport { + /** + * The amount of time in between sending pings + */ + private readonly keepaliveTimeMs: number; + /** + * The amount of time to wait for an acknowledgement after sending a ping + */ + private readonly keepaliveTimeoutMs: number; + /** + * Indicates whether keepalive pings should be sent without any active calls + */ + private readonly keepaliveWithoutCalls: boolean; + /** + * Timer reference indicating when to send the next ping or when the most recent ping will be considered lost. + */ + private keepaliveTimer: NodeJS.Timeout | null = null; + /** + * Indicates that the keepalive timer ran out while there were no active + * calls, and a ping should be sent the next time a call starts. + */ + private pendingSendKeepalivePing = false; + + private userAgent: string; + + private activeCalls: Set = new Set(); + + private subchannelAddressString: string; + + private disconnectListeners: TransportDisconnectListener[] = []; + + private disconnectHandled = false; + + private authContext: AuthContext; + + // Channelz info + private channelzRef: SocketRef; + private readonly channelzEnabled: boolean = true; + private streamTracker: ChannelzCallTracker | ChannelzCallTrackerStub; + private keepalivesSent = 0; + private messagesSent = 0; + private messagesReceived = 0; + private lastMessageSentTimestamp: Date | null = null; + private lastMessageReceivedTimestamp: Date | null = null; + + constructor( + private session: http2.ClientHttp2Session, + subchannelAddress: SubchannelAddress, + private options: ChannelOptions, + /** + * Name of the remote server, if it is not the same as the subchannel + * address, i.e. if connecting through an HTTP CONNECT proxy. + */ + private remoteName: string | null + ) { + /* Populate subchannelAddressString and channelzRef before doing anything + * else, because they are used in the trace methods. */ + this.subchannelAddressString = subchannelAddressToString(subchannelAddress); + + if (options['grpc.enable_channelz'] === 0) { + this.channelzEnabled = false; + this.streamTracker = new ChannelzCallTrackerStub(); + } else { + this.streamTracker = new ChannelzCallTracker(); + } + + this.channelzRef = registerChannelzSocket( + this.subchannelAddressString, + () => this.getChannelzInfo(), + this.channelzEnabled + ); + + // Build user-agent string. + this.userAgent = [ + options['grpc.primary_user_agent'], + `grpc-node-js/${clientVersion}`, + options['grpc.secondary_user_agent'], + ] + .filter(e => e) + .join(' '); // remove falsey values first + + if ('grpc.keepalive_time_ms' in options) { + this.keepaliveTimeMs = options['grpc.keepalive_time_ms']!; + } else { + this.keepaliveTimeMs = -1; + } + if ('grpc.keepalive_timeout_ms' in options) { + this.keepaliveTimeoutMs = options['grpc.keepalive_timeout_ms']!; + } else { + this.keepaliveTimeoutMs = KEEPALIVE_TIMEOUT_MS; + } + if ('grpc.keepalive_permit_without_calls' in options) { + this.keepaliveWithoutCalls = + options['grpc.keepalive_permit_without_calls'] === 1; + } else { + this.keepaliveWithoutCalls = false; + } + + session.once('close', () => { + this.trace('session closed'); + this.handleDisconnect(); + }); + + session.once( + 'goaway', + (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => { + let tooManyPings = false; + /* See the last paragraph of + * https://github.com/grpc/proposal/blob/master/A8-client-side-keepalive.md#basic-keepalive */ + if ( + errorCode === http2.constants.NGHTTP2_ENHANCE_YOUR_CALM && + opaqueData && + opaqueData.equals(tooManyPingsData) + ) { + tooManyPings = true; + } + this.trace( + 'connection closed by GOAWAY with code ' + + errorCode + + ' and data ' + + opaqueData?.toString() + ); + this.reportDisconnectToOwner(tooManyPings); + } + ); + + session.once('error', error => { + this.trace('connection closed with error ' + (error as Error).message); + this.handleDisconnect(); + }); + + session.socket.once('close', (hadError) => { + this.trace('connection closed. hadError=' + hadError); + this.handleDisconnect(); + }); + + if (logging.isTracerEnabled(TRACER_NAME)) { + session.on('remoteSettings', (settings: http2.Settings) => { + this.trace( + 'new settings received' + + (this.session !== session ? ' on the old connection' : '') + + ': ' + + JSON.stringify(settings) + ); + }); + session.on('localSettings', (settings: http2.Settings) => { + this.trace( + 'local settings acknowledged by remote' + + (this.session !== session ? ' on the old connection' : '') + + ': ' + + JSON.stringify(settings) + ); + }); + } + + /* Start the keepalive timer last, because this can trigger trace logs, + * which should only happen after everything else is set up. */ + if (this.keepaliveWithoutCalls) { + this.maybeStartKeepalivePingTimer(); + } + + if (session.socket instanceof TLSSocket) { + this.authContext = { + transportSecurityType: 'ssl', + sslPeerCertificate: session.socket.getPeerCertificate() + }; + } else { + this.authContext = {}; + } + } + + private getChannelzInfo(): SocketInfo { + const sessionSocket = this.session.socket; + const remoteAddress = sessionSocket.remoteAddress + ? stringToSubchannelAddress( + sessionSocket.remoteAddress, + sessionSocket.remotePort + ) + : null; + const localAddress = sessionSocket.localAddress + ? stringToSubchannelAddress( + sessionSocket.localAddress, + sessionSocket.localPort + ) + : null; + let tlsInfo: TlsInfo | null; + if (this.session.encrypted) { + const tlsSocket: TLSSocket = sessionSocket as TLSSocket; + const cipherInfo: CipherNameAndProtocol & { standardName?: string } = + tlsSocket.getCipher(); + const certificate = tlsSocket.getCertificate(); + const peerCertificate = tlsSocket.getPeerCertificate(); + tlsInfo = { + cipherSuiteStandardName: cipherInfo.standardName ?? null, + cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, + localCertificate: + certificate && 'raw' in certificate ? certificate.raw : null, + remoteCertificate: + peerCertificate && 'raw' in peerCertificate + ? peerCertificate.raw + : null, + }; + } else { + tlsInfo = null; + } + const socketInfo: SocketInfo = { + remoteAddress: remoteAddress, + localAddress: localAddress, + security: tlsInfo, + remoteName: this.remoteName, + streamsStarted: this.streamTracker.callsStarted, + streamsSucceeded: this.streamTracker.callsSucceeded, + streamsFailed: this.streamTracker.callsFailed, + messagesSent: this.messagesSent, + messagesReceived: this.messagesReceived, + keepAlivesSent: this.keepalivesSent, + lastLocalStreamCreatedTimestamp: + this.streamTracker.lastCallStartedTimestamp, + lastRemoteStreamCreatedTimestamp: null, + lastMessageSentTimestamp: this.lastMessageSentTimestamp, + lastMessageReceivedTimestamp: this.lastMessageReceivedTimestamp, + localFlowControlWindow: this.session.state.localWindowSize ?? null, + remoteFlowControlWindow: this.session.state.remoteWindowSize ?? null, + }; + return socketInfo; + } + + private trace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + TRACER_NAME, + '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text + ); + } + + private keepaliveTrace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + 'keepalive', + '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text + ); + } + + private flowControlTrace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + FLOW_CONTROL_TRACER_NAME, + '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text + ); + } + + private internalsTrace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + 'transport_internals', + '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text + ); + } + + /** + * Indicate to the owner of this object that this transport should no longer + * be used. That happens if the connection drops, or if the server sends a + * GOAWAY. + * @param tooManyPings If true, this was triggered by a GOAWAY with data + * indicating that the session was closed becaues the client sent too many + * pings. + * @returns + */ + private reportDisconnectToOwner(tooManyPings: boolean) { + if (this.disconnectHandled) { + return; + } + this.disconnectHandled = true; + this.disconnectListeners.forEach(listener => listener(tooManyPings)); + } + + /** + * Handle connection drops, but not GOAWAYs. + */ + private handleDisconnect() { + this.clearKeepaliveTimeout(); + this.reportDisconnectToOwner(false); + for (const call of this.activeCalls) { + call.onDisconnect(); + } + // Wait an event loop cycle before destroying the connection + setImmediate(() => { + this.session.destroy(); + }); + } + + addDisconnectListener(listener: TransportDisconnectListener): void { + this.disconnectListeners.push(listener); + } + + private canSendPing() { + return ( + !this.session.destroyed && + this.keepaliveTimeMs > 0 && + (this.keepaliveWithoutCalls || this.activeCalls.size > 0) + ); + } + + private maybeSendPing() { + if (!this.canSendPing()) { + this.pendingSendKeepalivePing = true; + return; + } + if (this.keepaliveTimer) { + console.error('keepaliveTimeout is not null'); + return; + } + if (this.channelzEnabled) { + this.keepalivesSent += 1; + } + this.keepaliveTrace( + 'Sending ping with timeout ' + this.keepaliveTimeoutMs + 'ms' + ); + this.keepaliveTimer = setTimeout(() => { + this.keepaliveTimer = null; + this.keepaliveTrace('Ping timeout passed without response'); + this.handleDisconnect(); + }, this.keepaliveTimeoutMs); + this.keepaliveTimer.unref?.(); + let pingSendError = ''; + try { + const pingSentSuccessfully = this.session.ping( + (err: Error | null, duration: number, payload: Buffer) => { + this.clearKeepaliveTimeout(); + if (err) { + this.keepaliveTrace('Ping failed with error ' + err.message); + this.handleDisconnect(); + } else { + this.keepaliveTrace('Received ping response'); + this.maybeStartKeepalivePingTimer(); + } + } + ); + if (!pingSentSuccessfully) { + pingSendError = 'Ping returned false'; + } + } catch (e) { + // grpc/grpc-node#2139 + pingSendError = (e instanceof Error ? e.message : '') || 'Unknown error'; + } + if (pingSendError) { + this.keepaliveTrace('Ping send failed: ' + pingSendError); + this.handleDisconnect(); + } + } + + /** + * Starts the keepalive ping timer if appropriate. If the timer already ran + * out while there were no active requests, instead send a ping immediately. + * If the ping timer is already running or a ping is currently in flight, + * instead do nothing and wait for them to resolve. + */ + private maybeStartKeepalivePingTimer() { + if (!this.canSendPing()) { + return; + } + if (this.pendingSendKeepalivePing) { + this.pendingSendKeepalivePing = false; + this.maybeSendPing(); + } else if (!this.keepaliveTimer) { + this.keepaliveTrace( + 'Starting keepalive timer for ' + this.keepaliveTimeMs + 'ms' + ); + this.keepaliveTimer = setTimeout(() => { + this.keepaliveTimer = null; + this.maybeSendPing(); + }, this.keepaliveTimeMs); + this.keepaliveTimer.unref?.(); + } + /* Otherwise, there is already either a keepalive timer or a ping pending, + * wait for those to resolve. */ + } + + /** + * Clears whichever keepalive timeout is currently active, if any. + */ + private clearKeepaliveTimeout() { + if (this.keepaliveTimer) { + clearTimeout(this.keepaliveTimer); + this.keepaliveTimer = null; + } + } + + private removeActiveCall(call: Http2SubchannelCall) { + this.activeCalls.delete(call); + if (this.activeCalls.size === 0) { + this.session.unref(); + } + } + + private addActiveCall(call: Http2SubchannelCall) { + this.activeCalls.add(call); + if (this.activeCalls.size === 1) { + this.session.ref(); + if (!this.keepaliveWithoutCalls) { + this.maybeStartKeepalivePingTimer(); + } + } + } + + createCall( + metadata: Metadata, + host: string, + method: string, + listener: SubchannelCallInterceptingListener, + subchannelCallStatsTracker: Partial + ): Http2SubchannelCall { + const headers = metadata.toHttp2Headers(); + headers[HTTP2_HEADER_AUTHORITY] = host; + headers[HTTP2_HEADER_USER_AGENT] = this.userAgent; + headers[HTTP2_HEADER_CONTENT_TYPE] = 'application/grpc'; + headers[HTTP2_HEADER_METHOD] = 'POST'; + headers[HTTP2_HEADER_PATH] = method; + headers[HTTP2_HEADER_TE] = 'trailers'; + let http2Stream: http2.ClientHttp2Stream; + /* In theory, if an error is thrown by session.request because session has + * become unusable (e.g. because it has received a goaway), this subchannel + * should soon see the corresponding close or goaway event anyway and leave + * READY. But we have seen reports that this does not happen + * (https://github.com/googleapis/nodejs-firestore/issues/1023#issuecomment-653204096) + * so for defense in depth, we just discard the session when we see an + * error here. + */ + try { + http2Stream = this.session.request(headers); + } catch (e) { + this.handleDisconnect(); + throw e; + } + this.flowControlTrace( + 'local window size: ' + + this.session.state.localWindowSize + + ' remote window size: ' + + this.session.state.remoteWindowSize + ); + this.internalsTrace( + 'session.closed=' + + this.session.closed + + ' session.destroyed=' + + this.session.destroyed + + ' session.socket.destroyed=' + + this.session.socket.destroyed + ); + let eventTracker: CallEventTracker; + // eslint-disable-next-line prefer-const + let call: Http2SubchannelCall; + if (this.channelzEnabled) { + this.streamTracker.addCallStarted(); + eventTracker = { + addMessageSent: () => { + this.messagesSent += 1; + this.lastMessageSentTimestamp = new Date(); + subchannelCallStatsTracker.addMessageSent?.(); + }, + addMessageReceived: () => { + this.messagesReceived += 1; + this.lastMessageReceivedTimestamp = new Date(); + subchannelCallStatsTracker.addMessageReceived?.(); + }, + onCallEnd: status => { + subchannelCallStatsTracker.onCallEnd?.(status); + this.removeActiveCall(call); + }, + onStreamEnd: success => { + if (success) { + this.streamTracker.addCallSucceeded(); + } else { + this.streamTracker.addCallFailed(); + } + subchannelCallStatsTracker.onStreamEnd?.(success); + }, + }; + } else { + eventTracker = { + addMessageSent: () => { + subchannelCallStatsTracker.addMessageSent?.(); + }, + addMessageReceived: () => { + subchannelCallStatsTracker.addMessageReceived?.(); + }, + onCallEnd: status => { + subchannelCallStatsTracker.onCallEnd?.(status); + this.removeActiveCall(call); + }, + onStreamEnd: success => { + subchannelCallStatsTracker.onStreamEnd?.(success); + }, + }; + } + call = new Http2SubchannelCall( + http2Stream, + eventTracker, + listener, + this, + getNextCallNumber() + ); + this.addActiveCall(call); + return call; + } + + getChannelzRef(): SocketRef { + return this.channelzRef; + } + + getPeerName() { + return this.subchannelAddressString; + } + + getOptions() { + return this.options; + } + + getAuthContext(): AuthContext { + return this.authContext; + } + + shutdown() { + this.session.close(); + unregisterChannelzRef(this.channelzRef); + } +} + +export interface SubchannelConnector { + connect( + address: SubchannelAddress, + secureConnector: SecureConnector, + options: ChannelOptions + ): Promise; + shutdown(): void; +} + +export class Http2SubchannelConnector implements SubchannelConnector { + private session: http2.ClientHttp2Session | null = null; + private isShutdown = false; + constructor(private channelTarget: GrpcUri) {} + + private trace(text: string) { + logging.trace( + LogVerbosity.DEBUG, + TRACER_NAME, + uriToString(this.channelTarget) + ' ' + text + ); + } + + private createSession( + secureConnectResult: SecureConnectResult, + address: SubchannelAddress, + options: ChannelOptions + ): Promise { + if (this.isShutdown) { + return Promise.reject(); + } + + if (secureConnectResult.socket.closed) { + return Promise.reject('Connection closed before starting HTTP/2 handshake'); + } + + return new Promise((resolve, reject) => { + let remoteName: string | null = null; + let realTarget: GrpcUri = this.channelTarget; + if ('grpc.http_connect_target' in options) { + const parsedTarget = parseUri(options['grpc.http_connect_target']!); + if (parsedTarget) { + realTarget = parsedTarget; + remoteName = uriToString(parsedTarget); + } + } + const scheme = secureConnectResult.secure ? 'https' : 'http'; + const targetPath = getDefaultAuthority(realTarget); + const closeHandler = () => { + this.session?.destroy(); + this.session = null; + // Leave time for error event to happen before rejecting + setImmediate(() => { + if (!reportedError) { + reportedError = true; + reject(`${errorMessage.trim()} (${new Date().toISOString()})`); + } + }); + }; + const errorHandler = (error: Error) => { + this.session?.destroy(); + errorMessage = (error as Error).message; + this.trace('connection failed with error ' + errorMessage); + if (!reportedError) { + reportedError = true; + reject(`${errorMessage} (${new Date().toISOString()})`); + } + }; + const sessionOptions: http2.ClientSessionOptions = { + createConnection: (authority, option) => { + return secureConnectResult.socket; + }, + settings: { + initialWindowSize: + options['grpc-node.flow_control_window'] ?? + http2.getDefaultSettings?.()?.initialWindowSize ?? 65535, + }, + maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER, + /* By default, set a very large max session memory limit, to effectively + * disable enforcement of the limit. Some testing indicates that Node's + * behavior degrades badly when this limit is reached, so we solve that + * by disabling the check entirely. */ + maxSessionMemory: options['grpc-node.max_session_memory'] ?? Number.MAX_SAFE_INTEGER + }; + const session = http2.connect(`${scheme}://${targetPath}`, sessionOptions); + // Prepare window size configuration for remoteSettings handler + const defaultWin = http2.getDefaultSettings?.()?.initialWindowSize ?? 65535; // 65 535 B + const connWin = options[ + 'grpc-node.flow_control_window' + ] as number | undefined; + + this.session = session; + let errorMessage = 'Failed to connect'; + let reportedError = false; + session.unref(); + session.once('remoteSettings', () => { + // Send WINDOW_UPDATE now to avoid 65 KB start-window stall. + if (connWin && connWin > defaultWin) { + try { + // Node ≥ 14.18 + (session as any).setLocalWindowSize(connWin); + } catch { + // Older Node: bump by the delta + const delta = connWin - (session.state.localWindowSize ?? defaultWin); + if (delta > 0) (session as any).incrementWindowSize(delta); + } + } + + session.removeAllListeners(); + secureConnectResult.socket.removeListener('close', closeHandler); + secureConnectResult.socket.removeListener('error', errorHandler); + resolve(new Http2Transport(session, address, options, remoteName)); + this.session = null; + }); + session.once('close', closeHandler); + session.once('error', errorHandler); + secureConnectResult.socket.once('close', closeHandler); + secureConnectResult.socket.once('error', errorHandler); + }); + } + + private tcpConnect(address: SubchannelAddress, options: ChannelOptions): Promise { + return getProxiedConnection(address, options).then(proxiedSocket => { + if (proxiedSocket) { + return proxiedSocket; + } else { + return new Promise((resolve, reject) => { + const closeCallback = () => { + reject(new Error('Socket closed')); + }; + const errorCallback = (error: Error) => { + reject(error); + } + const socket = net.connect(address, () => { + socket.removeListener('close', closeCallback); + socket.removeListener('error', errorCallback); + resolve(socket); + }); + socket.once('close', closeCallback); + socket.once('error', errorCallback); + }); + } + }); + } + + async connect( + address: SubchannelAddress, + secureConnector: SecureConnector, + options: ChannelOptions + ): Promise { + if (this.isShutdown) { + return Promise.reject(); + } + let tcpConnection: net.Socket | null = null; + let secureConnectResult: SecureConnectResult | null = null; + const addressString = subchannelAddressToString(address); + try { + this.trace(addressString + ' Waiting for secureConnector to be ready'); + await secureConnector.waitForReady(); + this.trace(addressString + ' secureConnector is ready'); + tcpConnection = await this.tcpConnect(address, options); + tcpConnection.setNoDelay(); + this.trace(addressString + ' Established TCP connection'); + secureConnectResult = await secureConnector.connect(tcpConnection); + this.trace(addressString + ' Established secure connection'); + return this.createSession(secureConnectResult, address, options); + } catch (e) { + tcpConnection?.destroy(); + secureConnectResult?.socket.destroy(); + throw e; + } + } + + shutdown(): void { + this.isShutdown = true; + this.session?.close(); + this.session = null; + } +} diff --git a/node_modules/@grpc/grpc-js/src/uri-parser.ts b/node_modules/@grpc/grpc-js/src/uri-parser.ts new file mode 100644 index 0000000..2b2efec --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/uri-parser.ts @@ -0,0 +1,127 @@ +/* + * Copyright 2020 gRPC authors. + * + * 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. + * + */ + +export interface GrpcUri { + scheme?: string; + authority?: string; + path: string; +} + +/* + * The groups correspond to URI parts as follows: + * 1. scheme + * 2. authority + * 3. path + */ +const URI_REGEX = /^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/; + +export function parseUri(uriString: string): GrpcUri | null { + const parsedUri = URI_REGEX.exec(uriString); + if (parsedUri === null) { + return null; + } + return { + scheme: parsedUri[1], + authority: parsedUri[2], + path: parsedUri[3], + }; +} + +export interface HostPort { + host: string; + port?: number; +} + +const NUMBER_REGEX = /^\d+$/; + +export function splitHostPort(path: string): HostPort | null { + if (path.startsWith('[')) { + const hostEnd = path.indexOf(']'); + if (hostEnd === -1) { + return null; + } + const host = path.substring(1, hostEnd); + /* Only an IPv6 address should be in bracketed notation, and an IPv6 + * address should have at least one colon */ + if (host.indexOf(':') === -1) { + return null; + } + if (path.length > hostEnd + 1) { + if (path[hostEnd + 1] === ':') { + const portString = path.substring(hostEnd + 2); + if (NUMBER_REGEX.test(portString)) { + return { + host: host, + port: +portString, + }; + } else { + return null; + } + } else { + return null; + } + } else { + return { + host, + }; + } + } else { + const splitPath = path.split(':'); + /* Exactly one colon means that this is host:port. Zero colons means that + * there is no port. And multiple colons means that this is a bare IPv6 + * address with no port */ + if (splitPath.length === 2) { + if (NUMBER_REGEX.test(splitPath[1])) { + return { + host: splitPath[0], + port: +splitPath[1], + }; + } else { + return null; + } + } else { + return { + host: path, + }; + } + } +} + +export function combineHostPort(hostPort: HostPort): string { + if (hostPort.port === undefined) { + return hostPort.host; + } else { + // Only an IPv6 host should include a colon + if (hostPort.host.includes(':')) { + return `[${hostPort.host}]:${hostPort.port}`; + } else { + return `${hostPort.host}:${hostPort.port}`; + } + } +} + +export function uriToString(uri: GrpcUri): string { + let result = ''; + if (uri.scheme !== undefined) { + result += uri.scheme + ':'; + } + if (uri.authority !== undefined) { + result += '//' + uri.authority + '/'; + } + result += uri.path; + return result; +} diff --git a/node_modules/@grpc/proto-loader/LICENSE b/node_modules/@grpc/proto-loader/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/node_modules/@grpc/proto-loader/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@grpc/proto-loader/README.md b/node_modules/@grpc/proto-loader/README.md new file mode 100644 index 0000000..935c100 --- /dev/null +++ b/node_modules/@grpc/proto-loader/README.md @@ -0,0 +1,140 @@ +# gRPC Protobuf Loader + +A utility package for loading `.proto` files for use with gRPC, using the latest Protobuf.js package. +Please refer to [protobuf.js' documentation](https://github.com/dcodeIO/protobuf.js/blob/master/README.md) +to understands its features and limitations. + +## Installation + +```sh +npm install @grpc/proto-loader +``` + +## Usage + +```js +const protoLoader = require('@grpc/proto-loader'); +const grpcLibrary = require('grpc'); +// OR +const grpcLibrary = require('@grpc/grpc-js'); + +protoLoader.load(protoFileName, options).then(packageDefinition => { + const packageObject = grpcLibrary.loadPackageDefinition(packageDefinition); +}); +// OR +const packageDefinition = protoLoader.loadSync(protoFileName, options); +const packageObject = grpcLibrary.loadPackageDefinition(packageDefinition); +``` + +The options parameter is an object that can have the following optional properties: + +| Field name | Valid values | Description +|------------|--------------|------------ +| `keepCase` | `true` or `false` | Preserve field names. The default is to change them to camel case. +| `longs` | `String` or `Number` | The type to use to represent `long` values. Defaults to a `Long` object type. +| `enums` | `String` | The type to use to represent `enum` values. Defaults to the numeric value. +| `bytes` | `Array` or `String` | The type to use to represent `bytes` values. Defaults to `Buffer`. +| `defaults` | `true` or `false` | Set default values on output objects. Defaults to `false`. +| `arrays` | `true` or `false` | Set empty arrays for missing array values even if `defaults` is `false` Defaults to `false`. +| `objects` | `true` or `false` | Set empty objects for missing object values even if `defaults` is `false` Defaults to `false`. +| `oneofs` | `true` or `false` | Set virtual oneof properties to the present field's name. Defaults to `false`. +| `json` | `true` or `false` | Represent `Infinity` and `NaN` as strings in `float` fields, and automatically decode `google.protobuf.Any` values. Defaults to `false` +| `includeDirs` | An array of strings | A list of search paths for imported `.proto` files. + +The following options object closely approximates the existing behavior of `grpc.load`: + +```js +const options = { + keepCase: true, + longs: String, + enums: String, + defaults: true, + oneofs: true +} +``` + +## Generating TypeScript types + +The `proto-loader-gen-types` script distributed with this package can be used to generate TypeScript type information for the objects loaded at runtime. More information about how to use it can be found in [the *@grpc/proto-loader TypeScript Type Generator CLI Tool* proposal document](https://github.com/grpc/proposal/blob/master/L70-node-proto-loader-type-generator.md). The arguments mostly match the `load` function's options; the full usage information is as follows: + +```console +proto-loader-gen-types.js [options] filenames... + +Options: + --help Show help [boolean] + --version Show version number [boolean] + --keepCase Preserve the case of field names + [boolean] [default: false] + --longs The type that should be used to output 64 bit + integer values. Can be String, Number + [string] [default: "Long"] + --enums The type that should be used to output enum fields. + Can be String [string] [default: "number"] + --bytes The type that should be used to output bytes + fields. Can be String, Array + [string] [default: "Buffer"] + --defaults Output default values for omitted fields + [boolean] [default: false] + --arrays Output default values for omitted repeated fields + even if --defaults is not set + [boolean] [default: false] + --objects Output default values for omitted message fields + even if --defaults is not set + [boolean] [default: false] + --oneofs Output virtual oneof fields set to the present + field's name [boolean] [default: false] + --json Represent Infinity and NaN as strings in float + fields. Also decode google.protobuf.Any + automatically [boolean] [default: false] + --includeComments Generate doc comments from comments in the original + files [boolean] [default: false] + -I, --includeDirs Directories to search for included files [array] + -O, --outDir Directory in which to output files + [string] [required] + --grpcLib The gRPC implementation library that these types + will be used with. If not provided, some types will + not be generated [string] + --inputTemplate Template for mapping input or "permissive" type + names [string] [default: "%s"] + --outputTemplate Template for mapping output or "restricted" type + names [string] [default: "%s__Output"] + --inputBranded Output property for branded type for "permissive" + types with fullName of the Message as its value + [boolean] [default: false] + --outputBranded Output property for branded type for "restricted" + types with fullName of the Message as its value + [boolean] [default: false] + --targetFileExtension File extension for generated files. + [string] [default: ".ts"] + --importFileExtension File extension for import specifiers in generated + code. [string] [default: ""] +``` + +### Example Usage + +Generate the types: + +```sh +$(npm bin)/proto-loader-gen-types --longs=String --enums=String --defaults --oneofs --grpcLib=@grpc/grpc-js --outDir=proto/ proto/*.proto +``` + +Consume the types: + +```ts +import * as grpc from '@grpc/grpc-js'; +import * as protoLoader from '@grpc/proto-loader'; +import type { ProtoGrpcType } from './proto/example.ts'; +import type { ExampleHandlers } from './proto/example_package/Example.ts'; + +const exampleServer: ExampleHandlers = { + // server handlers implementation... +}; + +const packageDefinition = protoLoader.loadSync('./proto/example.proto'); +const proto = (grpc.loadPackageDefinition( + packageDefinition +) as unknown) as ProtoGrpcType; + +const server = new grpc.Server(); +server.addService(proto.example_package.Example.service, exampleServer); +``` diff --git a/node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js b/node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js new file mode 100644 index 0000000..1df55f7 --- /dev/null +++ b/node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js @@ -0,0 +1,913 @@ +#!/usr/bin/env node +"use strict"; +/** + * @license + * Copyright 2020 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const fs = require("fs"); +const path = require("path"); +const Protobuf = require("protobufjs"); +const yargs = require("yargs"); +const camelCase = require("lodash.camelcase"); +const util_1 = require("../src/util"); +const templateStr = "%s"; +const useNameFmter = ({ outputTemplate, inputTemplate }) => { + if (outputTemplate === inputTemplate) { + throw new Error('inputTemplate and outputTemplate must differ'); + } + return { + outputName: (n) => outputTemplate.replace(templateStr, n), + inputName: (n) => inputTemplate.replace(templateStr, n) + }; +}; +class TextFormatter { + constructor() { + this.indentText = ' '; + this.indentValue = 0; + this.textParts = []; + } + indent() { + this.indentValue += 1; + } + unindent() { + this.indentValue -= 1; + } + writeLine(line) { + for (let i = 0; i < this.indentValue; i += 1) { + this.textParts.push(this.indentText); + } + this.textParts.push(line); + this.textParts.push('\n'); + } + getFullText() { + return this.textParts.join(''); + } +} +// GENERATOR UTILITY FUNCTIONS +function compareName(x, y) { + if (x.name < y.name) { + return -1; + } + else if (x.name > y.name) { + return 1; + } + else { + return 0; + } +} +function isNamespaceBase(obj) { + return Array.isArray(obj.nestedArray); +} +function stripLeadingPeriod(name) { + return name.startsWith('.') ? name.substring(1) : name; +} +function getImportPath(to) { + /* If the thing we are importing is defined in a message, it is generated in + * the same file as that message. */ + if (to.parent instanceof Protobuf.Type) { + return getImportPath(to.parent); + } + return stripLeadingPeriod(to.fullName).replace(/\./g, '/'); +} +function getPath(to, options) { + return stripLeadingPeriod(to.fullName).replace(/\./g, '/') + options.targetFileExtension; +} +function getPathToRoot(from) { + const depth = stripLeadingPeriod(from.fullName).split('.').length - 1; + if (depth === 0) { + return './'; + } + let path = ''; + for (let i = 0; i < depth; i++) { + path += '../'; + } + return path; +} +function getRelativeImportPath(from, to) { + return getPathToRoot(from) + getImportPath(to); +} +function getTypeInterfaceName(type) { + return type.fullName.replace(/\./g, '_'); +} +function getImportLine(dependency, from, options) { + const filePath = from === undefined ? './' + getImportPath(dependency) : getRelativeImportPath(from, dependency); + const { outputName, inputName } = useNameFmter(options); + const typeInterfaceName = getTypeInterfaceName(dependency); + let importedTypes; + /* If the dependency is defined within a message, it will be generated in that + * message's file and exported using its typeInterfaceName. */ + if (dependency.parent instanceof Protobuf.Type) { + if (dependency instanceof Protobuf.Type || dependency instanceof Protobuf.Enum) { + importedTypes = `${inputName(typeInterfaceName)}, ${outputName(typeInterfaceName)}`; + } + else if (dependency instanceof Protobuf.Service) { + importedTypes = `${typeInterfaceName}Client, ${typeInterfaceName}Definition`; + } + else { + throw new Error('Invalid object passed to getImportLine'); + } + } + else { + if (dependency instanceof Protobuf.Type || dependency instanceof Protobuf.Enum) { + importedTypes = `${inputName(dependency.name)} as ${inputName(typeInterfaceName)}, ${outputName(dependency.name)} as ${outputName(typeInterfaceName)}`; + } + else if (dependency instanceof Protobuf.Service) { + importedTypes = `${dependency.name}Client as ${typeInterfaceName}Client, ${dependency.name}Definition as ${typeInterfaceName}Definition`; + } + else { + throw new Error('Invalid object passed to getImportLine'); + } + } + return `import type { ${importedTypes} } from '${filePath}${options.importFileExtension}';`; +} +function getChildMessagesAndEnums(namespace) { + const messageList = []; + for (const nested of namespace.nestedArray) { + if (nested instanceof Protobuf.Type || nested instanceof Protobuf.Enum) { + messageList.push(nested); + } + if (isNamespaceBase(nested)) { + messageList.push(...getChildMessagesAndEnums(nested)); + } + } + return messageList; +} +function formatComment(formatter, comment, options) { + if (!comment && !(options === null || options === void 0 ? void 0 : options.deprecated)) { + return; + } + formatter.writeLine('/**'); + if (comment) { + for (const line of comment.split('\n')) { + formatter.writeLine(` * ${line.replace(/\*\//g, '* /')}`); + } + } + if (options === null || options === void 0 ? void 0 : options.deprecated) { + formatter.writeLine(' * @deprecated'); + } + formatter.writeLine(' */'); +} +const typeBrandHint = `This field is a type brand and is not populated at runtime. Instances of this type should be created using type assertions. +https://github.com/grpc/grpc-node/pull/2281`; +function formatTypeBrand(formatter, messageType) { + formatComment(formatter, typeBrandHint); + formatter.writeLine(`__type: '${messageType.fullName}'`); +} +// GENERATOR FUNCTIONS +function getTypeNamePermissive(fieldType, resolvedType, repeated, map, options) { + const { inputName } = useNameFmter(options); + switch (fieldType) { + case 'double': + case 'float': + return 'number | string'; + case 'int32': + case 'uint32': + case 'sint32': + case 'fixed32': + case 'sfixed32': + return 'number'; + case 'int64': + case 'uint64': + case 'sint64': + case 'fixed64': + case 'sfixed64': + return 'number | string | Long'; + case 'bool': + return 'boolean'; + case 'string': + return 'string'; + case 'bytes': + return 'Buffer | Uint8Array | string'; + default: + if (resolvedType === null) { + throw new Error('Found field with no usable type'); + } + const typeInterfaceName = getTypeInterfaceName(resolvedType); + if (resolvedType instanceof Protobuf.Type) { + if (repeated || map) { + return inputName(typeInterfaceName); + } + else { + return `${inputName(typeInterfaceName)} | null`; + } + } + else { + // Enum + return inputName(typeInterfaceName); + } + } +} +function getFieldTypePermissive(field, options) { + const valueType = getTypeNamePermissive(field.type, field.resolvedType, field.repeated, field.map, options); + if (field instanceof Protobuf.MapField) { + const keyType = field.keyType === 'string' ? 'string' : 'number'; + return `{[key: ${keyType}]: ${valueType}}`; + } + else { + return valueType; + } +} +function generatePermissiveMessageInterface(formatter, messageType, options, nameOverride) { + const { inputName } = useNameFmter(options); + if (options.includeComments) { + formatComment(formatter, messageType.comment, messageType.options); + } + if (messageType.fullName === '.google.protobuf.Any') { + /* This describes the behavior of the Protobuf.js Any wrapper fromObject + * replacement function */ + formatter.writeLine(`export type ${inputName('Any')} = AnyExtension | {`); + formatter.writeLine(' type_url: string;'); + formatter.writeLine(' value: Buffer | Uint8Array | string;'); + formatter.writeLine('}'); + return; + } + formatter.writeLine(`export interface ${inputName(nameOverride !== null && nameOverride !== void 0 ? nameOverride : messageType.name)} {`); + formatter.indent(); + for (const field of messageType.fieldsArray) { + const repeatedString = field.repeated ? '[]' : ''; + const type = getFieldTypePermissive(field, options); + if (options.includeComments) { + formatComment(formatter, field.comment, field.options); + } + formatter.writeLine(`'${field.name}'?: (${type})${repeatedString};`); + } + for (const oneof of messageType.oneofsArray) { + const typeString = oneof.fieldsArray.map(field => `"${field.name}"`).join('|'); + if (options.includeComments) { + formatComment(formatter, oneof.comment, oneof.options); + } + formatter.writeLine(`'${oneof.name}'?: ${typeString};`); + } + if (options.inputBranded) { + formatTypeBrand(formatter, messageType); + } + formatter.unindent(); + formatter.writeLine('}'); +} +function getTypeNameRestricted(fieldType, resolvedType, repeated, map, options) { + const { outputName } = useNameFmter(options); + switch (fieldType) { + case 'double': + case 'float': + if (options.json) { + return 'number | string'; + } + else { + return 'number'; + } + case 'int32': + case 'uint32': + case 'sint32': + case 'fixed32': + case 'sfixed32': + return 'number'; + case 'int64': + case 'uint64': + case 'sint64': + case 'fixed64': + case 'sfixed64': + if (options.longs === Number) { + return 'number'; + } + else if (options.longs === String) { + return 'string'; + } + else { + return 'Long'; + } + case 'bool': + return 'boolean'; + case 'string': + return 'string'; + case 'bytes': + if (options.bytes === Array) { + return 'Uint8Array'; + } + else if (options.bytes === String) { + return 'string'; + } + else { + return 'Buffer'; + } + default: + if (resolvedType === null) { + throw new Error('Found field with no usable type'); + } + const typeInterfaceName = getTypeInterfaceName(resolvedType); + if (resolvedType instanceof Protobuf.Type) { + /* null is only used to represent absent message values if the defaults + * option is set, and only for non-repeated, non-map fields. */ + if (options.defaults && !repeated && !map) { + return `${outputName(typeInterfaceName)} | null`; + } + else { + return `${outputName(typeInterfaceName)}`; + } + } + else { + // Enum + return outputName(typeInterfaceName); + } + } +} +function getFieldTypeRestricted(field, options) { + const valueType = getTypeNameRestricted(field.type, field.resolvedType, field.repeated, field.map, options); + if (field instanceof Protobuf.MapField) { + const keyType = field.keyType === 'string' ? 'string' : 'number'; + return `{[key: ${keyType}]: ${valueType}}`; + } + else { + return valueType; + } +} +function generateRestrictedMessageInterface(formatter, messageType, options, nameOverride) { + var _a, _b, _c; + const { outputName } = useNameFmter(options); + if (options.includeComments) { + formatComment(formatter, messageType.comment, messageType.options); + } + if (messageType.fullName === '.google.protobuf.Any' && options.json) { + /* This describes the behavior of the Protobuf.js Any wrapper toObject + * replacement function */ + let optionalString = options.defaults ? '' : '?'; + formatter.writeLine(`export type ${outputName('Any')} = AnyExtension | {`); + formatter.writeLine(` type_url${optionalString}: string;`); + formatter.writeLine(` value${optionalString}: ${getTypeNameRestricted('bytes', null, false, false, options)};`); + formatter.writeLine('}'); + return; + } + formatter.writeLine(`export interface ${outputName(nameOverride !== null && nameOverride !== void 0 ? nameOverride : messageType.name)} {`); + formatter.indent(); + for (const field of messageType.fieldsArray) { + let fieldGuaranteed; + if (field.partOf) { + // The field is not guaranteed populated if it is part of a oneof + fieldGuaranteed = false; + } + else if (field.repeated) { + fieldGuaranteed = (_a = (options.defaults || options.arrays)) !== null && _a !== void 0 ? _a : false; + } + else if (field.map) { + fieldGuaranteed = (_b = (options.defaults || options.objects)) !== null && _b !== void 0 ? _b : false; + } + else { + fieldGuaranteed = (_c = options.defaults) !== null && _c !== void 0 ? _c : false; + } + const optionalString = fieldGuaranteed ? '' : '?'; + const repeatedString = field.repeated ? '[]' : ''; + const type = getFieldTypeRestricted(field, options); + if (options.includeComments) { + formatComment(formatter, field.comment, field.options); + } + formatter.writeLine(`'${field.name}'${optionalString}: (${type})${repeatedString};`); + } + if (options.oneofs) { + for (const oneof of messageType.oneofsArray) { + const typeString = oneof.fieldsArray.map(field => `"${field.name}"`).join('|'); + if (options.includeComments) { + formatComment(formatter, oneof.comment, oneof.options); + } + formatter.writeLine(`'${oneof.name}'?: ${typeString};`); + } + } + if (options.outputBranded) { + formatTypeBrand(formatter, messageType); + } + formatter.unindent(); + formatter.writeLine('}'); +} +function generateMessageInterfaces(formatter, messageType, options) { + var _a, _b; + let usesLong = false; + let seenDeps = new Set(); + const childTypes = getChildMessagesAndEnums(messageType); + formatter.writeLine(`// Original file: ${(_b = ((_a = messageType.filename) !== null && _a !== void 0 ? _a : 'null')) === null || _b === void 0 ? void 0 : _b.replace(/\\/g, '/')}`); + formatter.writeLine(''); + const isLongField = (field) => ['int64', 'uint64', 'sint64', 'fixed64', 'sfixed64'].includes(field.type); + messageType.fieldsArray.sort((fieldA, fieldB) => fieldA.id - fieldB.id); + for (const field of messageType.fieldsArray) { + if (field.resolvedType && childTypes.indexOf(field.resolvedType) < 0) { + const dependency = field.resolvedType; + if (seenDeps.has(dependency.fullName)) { + continue; + } + seenDeps.add(dependency.fullName); + formatter.writeLine(getImportLine(dependency, messageType, options)); + } + if (isLongField(field)) { + usesLong = true; + } + } + for (const childType of childTypes) { + if (childType instanceof Protobuf.Type) { + for (const field of childType.fieldsArray) { + if (field.resolvedType && childTypes.indexOf(field.resolvedType) < 0) { + const dependency = field.resolvedType; + if (seenDeps.has(dependency.fullName)) { + continue; + } + seenDeps.add(dependency.fullName); + formatter.writeLine(getImportLine(dependency, messageType, options)); + } + if (isLongField(field)) { + usesLong = true; + } + } + } + } + if (usesLong) { + formatter.writeLine("import type { Long } from '@grpc/proto-loader';"); + } + if (messageType.fullName === '.google.protobuf.Any') { + formatter.writeLine("import type { AnyExtension } from '@grpc/proto-loader';"); + } + formatter.writeLine(''); + for (const childType of childTypes.sort(compareName)) { + const nameOverride = getTypeInterfaceName(childType); + if (childType instanceof Protobuf.Type) { + generatePermissiveMessageInterface(formatter, childType, options, nameOverride); + formatter.writeLine(''); + generateRestrictedMessageInterface(formatter, childType, options, nameOverride); + } + else { + generateEnumInterface(formatter, childType, options, nameOverride); + } + formatter.writeLine(''); + } + generatePermissiveMessageInterface(formatter, messageType, options); + formatter.writeLine(''); + generateRestrictedMessageInterface(formatter, messageType, options); +} +function generateEnumInterface(formatter, enumType, options, nameOverride) { + var _a, _b, _c; + const { inputName, outputName } = useNameFmter(options); + const name = nameOverride !== null && nameOverride !== void 0 ? nameOverride : enumType.name; + formatter.writeLine(`// Original file: ${(_b = ((_a = enumType.filename) !== null && _a !== void 0 ? _a : 'null')) === null || _b === void 0 ? void 0 : _b.replace(/\\/g, '/')}`); + formatter.writeLine(''); + if (options.includeComments) { + formatComment(formatter, enumType.comment, enumType.options); + } + formatter.writeLine(`export const ${name} = {`); + formatter.indent(); + for (const key of Object.keys(enumType.values)) { + if (options.includeComments) { + formatComment(formatter, enumType.comments[key], ((_c = enumType.valuesOptions) !== null && _c !== void 0 ? _c : {})[key]); + } + formatter.writeLine(`${key}: ${options.enums == String ? `'${key}'` : enumType.values[key]},`); + } + formatter.unindent(); + formatter.writeLine('} as const;'); + // Permissive Type + formatter.writeLine(''); + if (options.includeComments) { + formatComment(formatter, enumType.comment, enumType.options); + } + formatter.writeLine(`export type ${inputName(name)} =`); + formatter.indent(); + for (const key of Object.keys(enumType.values)) { + if (options.includeComments) { + formatComment(formatter, enumType.comments[key]); + } + formatter.writeLine(`| '${key}'`); + formatter.writeLine(`| ${enumType.values[key]}`); + } + formatter.unindent(); + // Restrictive Type + formatter.writeLine(''); + if (options.includeComments) { + formatComment(formatter, enumType.comment, enumType.options); + } + formatter.writeLine(`export type ${outputName(name)} = typeof ${name}[keyof typeof ${name}]`); +} +/** + * This is a list of methods that are exist in the generic Client class in the + * gRPC libraries. TypeScript has a problem with methods in subclasses with the + * same names as methods in the superclass, but with mismatched APIs. So, we + * avoid generating methods with these names in the service client interfaces. + * We always generate two service client methods per service method: one camel + * cased, and one with the original casing. So we will still generate one + * service client method for any conflicting name. + * + * Technically, at runtime conflicting name in the service client method + * actually shadows the original method, but TypeScript does not have a good + * way to represent that. So this change is not 100% accurate, but it gets the + * generated code to compile. + * + * This is just a list of the methods in the Client class definitions in + * grpc@1.24.11 and @grpc/grpc-js@1.4.0. + */ +const CLIENT_RESERVED_METHOD_NAMES = new Set([ + 'close', + 'getChannel', + 'waitForReady', + 'makeUnaryRequest', + 'makeClientStreamRequest', + 'makeServerStreamRequest', + 'makeBidiStreamRequest', + 'resolveCallInterceptors', + /* These methods are private, but TypeScript is not happy with overriding even + * private methods with mismatched APIs. */ + 'checkOptionalUnaryResponseArguments', + 'checkMetadataAndOptions' +]); +function generateServiceClientInterface(formatter, serviceType, options) { + const { outputName, inputName } = useNameFmter(options); + if (options.includeComments) { + formatComment(formatter, serviceType.comment, serviceType.options); + } + formatter.writeLine(`export interface ${serviceType.name}Client extends grpc.Client {`); + formatter.indent(); + for (const methodName of Object.keys(serviceType.methods).sort()) { + const method = serviceType.methods[methodName]; + for (const name of new Set([methodName, camelCase(methodName)])) { + if (CLIENT_RESERVED_METHOD_NAMES.has(name)) { + continue; + } + if (options.includeComments) { + formatComment(formatter, method.comment, method.options); + } + const requestType = inputName(getTypeInterfaceName(method.resolvedRequestType)); + const responseType = outputName(getTypeInterfaceName(method.resolvedResponseType)); + const callbackType = `grpc.requestCallback<${responseType}>`; + if (method.requestStream) { + if (method.responseStream) { + // Bidi streaming + const callType = `grpc.ClientDuplexStream<${requestType}, ${responseType}>`; + formatter.writeLine(`${name}(metadata: grpc.Metadata, options?: grpc.CallOptions): ${callType};`); + formatter.writeLine(`${name}(options?: grpc.CallOptions): ${callType};`); + } + else { + // Client streaming + const callType = `grpc.ClientWritableStream<${requestType}>`; + formatter.writeLine(`${name}(metadata: grpc.Metadata, options: grpc.CallOptions, callback: ${callbackType}): ${callType};`); + formatter.writeLine(`${name}(metadata: grpc.Metadata, callback: ${callbackType}): ${callType};`); + formatter.writeLine(`${name}(options: grpc.CallOptions, callback: ${callbackType}): ${callType};`); + formatter.writeLine(`${name}(callback: ${callbackType}): ${callType};`); + } + } + else { + if (method.responseStream) { + // Server streaming + const callType = `grpc.ClientReadableStream<${responseType}>`; + formatter.writeLine(`${name}(argument: ${requestType}, metadata: grpc.Metadata, options?: grpc.CallOptions): ${callType};`); + formatter.writeLine(`${name}(argument: ${requestType}, options?: grpc.CallOptions): ${callType};`); + } + else { + // Unary + const callType = 'grpc.ClientUnaryCall'; + formatter.writeLine(`${name}(argument: ${requestType}, metadata: grpc.Metadata, options: grpc.CallOptions, callback: ${callbackType}): ${callType};`); + formatter.writeLine(`${name}(argument: ${requestType}, metadata: grpc.Metadata, callback: ${callbackType}): ${callType};`); + formatter.writeLine(`${name}(argument: ${requestType}, options: grpc.CallOptions, callback: ${callbackType}): ${callType};`); + formatter.writeLine(`${name}(argument: ${requestType}, callback: ${callbackType}): ${callType};`); + } + } + } + formatter.writeLine(''); + } + formatter.unindent(); + formatter.writeLine('}'); +} +function generateServiceHandlerInterface(formatter, serviceType, options) { + const { inputName, outputName } = useNameFmter(options); + if (options.includeComments) { + formatComment(formatter, serviceType.comment, serviceType.options); + } + formatter.writeLine(`export interface ${serviceType.name}Handlers extends grpc.UntypedServiceImplementation {`); + formatter.indent(); + for (const methodName of Object.keys(serviceType.methods).sort()) { + const method = serviceType.methods[methodName]; + if (options.includeComments) { + formatComment(formatter, method.comment, serviceType.options); + } + const requestType = outputName(getTypeInterfaceName(method.resolvedRequestType)); + const responseType = inputName(getTypeInterfaceName(method.resolvedResponseType)); + if (method.requestStream) { + if (method.responseStream) { + // Bidi streaming + formatter.writeLine(`${methodName}: grpc.handleBidiStreamingCall<${requestType}, ${responseType}>;`); + } + else { + // Client streaming + formatter.writeLine(`${methodName}: grpc.handleClientStreamingCall<${requestType}, ${responseType}>;`); + } + } + else { + if (method.responseStream) { + // Server streaming + formatter.writeLine(`${methodName}: grpc.handleServerStreamingCall<${requestType}, ${responseType}>;`); + } + else { + // Unary + formatter.writeLine(`${methodName}: grpc.handleUnaryCall<${requestType}, ${responseType}>;`); + } + } + formatter.writeLine(''); + } + formatter.unindent(); + formatter.writeLine('}'); +} +function generateServiceDefinitionInterface(formatter, serviceType, options) { + const { inputName, outputName } = useNameFmter(options); + if (options.grpcLib) { + formatter.writeLine(`export interface ${serviceType.name}Definition extends grpc.ServiceDefinition {`); + } + else { + formatter.writeLine(`export interface ${serviceType.name}Definition {`); + } + formatter.indent(); + for (const methodName of Object.keys(serviceType.methods).sort()) { + const method = serviceType.methods[methodName]; + const requestType = getTypeInterfaceName(method.resolvedRequestType); + const responseType = getTypeInterfaceName(method.resolvedResponseType); + formatter.writeLine(`${methodName}: MethodDefinition<${inputName(requestType)}, ${inputName(responseType)}, ${outputName(requestType)}, ${outputName(responseType)}>`); + } + formatter.unindent(); + formatter.writeLine('}'); +} +function generateServiceInterfaces(formatter, serviceType, options) { + var _a, _b; + formatter.writeLine(`// Original file: ${(_b = ((_a = serviceType.filename) !== null && _a !== void 0 ? _a : 'null')) === null || _b === void 0 ? void 0 : _b.replace(/\\/g, '/')}`); + formatter.writeLine(''); + if (options.grpcLib) { + const grpcImportPath = options.grpcLib.startsWith('.') ? getPathToRoot(serviceType) + options.grpcLib : options.grpcLib; + formatter.writeLine(`import type * as grpc from '${grpcImportPath}'`); + } + formatter.writeLine(`import type { MethodDefinition } from '@grpc/proto-loader'`); + const dependencies = new Set(); + for (const method of serviceType.methodsArray) { + dependencies.add(method.resolvedRequestType); + dependencies.add(method.resolvedResponseType); + } + for (const dep of Array.from(dependencies.values()).sort(compareName)) { + formatter.writeLine(getImportLine(dep, serviceType, options)); + } + formatter.writeLine(''); + if (options.grpcLib) { + generateServiceClientInterface(formatter, serviceType, options); + formatter.writeLine(''); + generateServiceHandlerInterface(formatter, serviceType, options); + formatter.writeLine(''); + } + generateServiceDefinitionInterface(formatter, serviceType, options); +} +function containsDefinition(definitionType, namespace) { + for (const nested of namespace.nestedArray.sort(compareName)) { + if (nested instanceof definitionType) { + return true; + } + else if (isNamespaceBase(nested) && !(nested instanceof Protobuf.Type) && !(nested instanceof Protobuf.Enum) && containsDefinition(definitionType, nested)) { + return true; + } + } + return false; +} +function generateDefinitionImports(formatter, namespace, options) { + const imports = []; + if (containsDefinition(Protobuf.Enum, namespace)) { + imports.push('EnumTypeDefinition'); + } + if (containsDefinition(Protobuf.Type, namespace)) { + imports.push('MessageTypeDefinition'); + } + if (imports.length) { + formatter.writeLine(`import type { ${imports.join(', ')} } from '@grpc/proto-loader';`); + } +} +function generateServiceImports(formatter, namespace, options) { + for (const nested of namespace.nestedArray.sort(compareName)) { + if (nested instanceof Protobuf.Service) { + formatter.writeLine(getImportLine(nested, undefined, options)); + } + else if (isNamespaceBase(nested) && !(nested instanceof Protobuf.Type) && !(nested instanceof Protobuf.Enum)) { + generateServiceImports(formatter, nested, options); + } + } +} +function generateSingleLoadedDefinitionType(formatter, nested, options) { + if (nested instanceof Protobuf.Service) { + if (options.includeComments) { + formatComment(formatter, nested.comment, nested.options); + } + const typeInterfaceName = getTypeInterfaceName(nested); + formatter.writeLine(`${nested.name}: SubtypeConstructor & { service: ${typeInterfaceName}Definition }`); + } + else if (nested instanceof Protobuf.Enum) { + formatter.writeLine(`${nested.name}: EnumTypeDefinition`); + } + else if (nested instanceof Protobuf.Type) { + formatter.writeLine(`${nested.name}: MessageTypeDefinition`); + } + else if (isNamespaceBase(nested)) { + generateLoadedDefinitionTypes(formatter, nested, options); + } +} +function generateLoadedDefinitionTypes(formatter, namespace, options) { + formatter.writeLine(`${namespace.name}: {`); + formatter.indent(); + for (const nested of namespace.nestedArray.sort(compareName)) { + generateSingleLoadedDefinitionType(formatter, nested, options); + } + formatter.unindent(); + formatter.writeLine('}'); +} +function generateRootFile(formatter, root, options) { + if (!options.grpcLib) { + return; + } + formatter.writeLine(`import type * as grpc from '${options.grpcLib}';`); + generateDefinitionImports(formatter, root, options); + formatter.writeLine(''); + generateServiceImports(formatter, root, options); + formatter.writeLine(''); + formatter.writeLine('type SubtypeConstructor any, Subtype> = {'); + formatter.writeLine(' new(...args: ConstructorParameters): Subtype;'); + formatter.writeLine('};'); + formatter.writeLine(''); + formatter.writeLine('export interface ProtoGrpcType {'); + formatter.indent(); + for (const nested of root.nestedArray) { + generateSingleLoadedDefinitionType(formatter, nested, options); + } + formatter.unindent(); + formatter.writeLine('}'); + formatter.writeLine(''); +} +async function writeFile(filename, contents) { + await fs.promises.mkdir(path.dirname(filename), { recursive: true }); + return fs.promises.writeFile(filename, contents); +} +function generateFilesForNamespace(namespace, options) { + const filePromises = []; + for (const nested of namespace.nestedArray) { + const fileFormatter = new TextFormatter(); + if (nested instanceof Protobuf.Type) { + generateMessageInterfaces(fileFormatter, nested, options); + if (options.verbose) { + console.log(`Writing ${options.outDir}/${getPath(nested, options)} from file ${nested.filename}`); + } + filePromises.push(writeFile(`${options.outDir}/${getPath(nested, options)}`, fileFormatter.getFullText())); + } + else if (nested instanceof Protobuf.Enum) { + generateEnumInterface(fileFormatter, nested, options); + if (options.verbose) { + console.log(`Writing ${options.outDir}/${getPath(nested, options)} from file ${nested.filename}`); + } + filePromises.push(writeFile(`${options.outDir}/${getPath(nested, options)}`, fileFormatter.getFullText())); + } + else if (nested instanceof Protobuf.Service) { + generateServiceInterfaces(fileFormatter, nested, options); + if (options.verbose) { + console.log(`Writing ${options.outDir}/${getPath(nested, options)} from file ${nested.filename}`); + } + filePromises.push(writeFile(`${options.outDir}/${getPath(nested, options)}`, fileFormatter.getFullText())); + } + else if (isNamespaceBase(nested)) { + filePromises.push(...generateFilesForNamespace(nested, options)); + } + } + return filePromises; +} +function writeFilesForRoot(root, masterFileName, options) { + const filePromises = []; + const masterFileFormatter = new TextFormatter(); + if (options.grpcLib) { + generateRootFile(masterFileFormatter, root, options); + if (options.verbose) { + console.log(`Writing ${options.outDir}/${masterFileName}`); + } + filePromises.push(writeFile(`${options.outDir}/${masterFileName}`, masterFileFormatter.getFullText())); + } + filePromises.push(...generateFilesForNamespace(root, options)); + return filePromises; +} +async function writeAllFiles(protoFiles, options) { + await fs.promises.mkdir(options.outDir, { recursive: true }); + const basenameMap = new Map(); + for (const filename of protoFiles) { + const basename = path.basename(filename).replace(/\.proto$/, options.targetFileExtension); + if (basenameMap.has(basename)) { + basenameMap.get(basename).push(filename); + } + else { + basenameMap.set(basename, [filename]); + } + } + for (const [basename, filenames] of basenameMap.entries()) { + const loadedRoot = await (0, util_1.loadProtosWithOptions)(filenames, options); + writeFilesForRoot(loadedRoot, basename, options); + } +} +async function runScript() { + const boolDefaultFalseOption = { + boolean: true, + default: false, + }; + const argv = await yargs + .parserConfiguration({ + 'parse-positional-numbers': false + }) + .option('keepCase', boolDefaultFalseOption) + .option('longs', { string: true, default: 'Long' }) + .option('enums', { string: true, default: 'number' }) + .option('bytes', { string: true, default: 'Buffer' }) + .option('defaults', boolDefaultFalseOption) + .option('arrays', boolDefaultFalseOption) + .option('objects', boolDefaultFalseOption) + .option('oneofs', boolDefaultFalseOption) + .option('json', boolDefaultFalseOption) + .boolean('verbose') + .option('includeComments', boolDefaultFalseOption) + .option('includeDirs', { + normalize: true, + array: true, + alias: 'I' + }) + .option('outDir', { + alias: 'O', + normalize: true, + }) + .option('grpcLib', { string: true }) + .option('inputTemplate', { string: true, default: `${templateStr}` }) + .option('outputTemplate', { string: true, default: `${templateStr}__Output` }) + .option('inputBranded', boolDefaultFalseOption) + .option('outputBranded', boolDefaultFalseOption) + .option('targetFileExtension', { string: true, default: '.ts' }) + .option('importFileExtension', { string: true, default: '' }) + .coerce('longs', value => { + switch (value) { + case 'String': return String; + case 'Number': return Number; + default: return undefined; + } + }).coerce('enums', value => { + if (value === 'String') { + return String; + } + else { + return undefined; + } + }).coerce('bytes', value => { + switch (value) { + case 'Array': return Array; + case 'String': return String; + default: return undefined; + } + }) + .alias({ + verbose: 'v' + }).describe({ + keepCase: 'Preserve the case of field names', + longs: 'The type that should be used to output 64 bit integer values. Can be String, Number', + enums: 'The type that should be used to output enum fields. Can be String', + bytes: 'The type that should be used to output bytes fields. Can be String, Array', + defaults: 'Output default values for omitted fields', + arrays: 'Output default values for omitted repeated fields even if --defaults is not set', + objects: 'Output default values for omitted message fields even if --defaults is not set', + oneofs: 'Output virtual oneof fields set to the present field\'s name', + json: 'Represent Infinity and NaN as strings in float fields. Also decode google.protobuf.Any automatically', + includeComments: 'Generate doc comments from comments in the original files', + includeDirs: 'Directories to search for included files', + outDir: 'Directory in which to output files', + grpcLib: 'The gRPC implementation library that these types will be used with. If not provided, some types will not be generated', + inputTemplate: 'Template for mapping input or "permissive" type names', + outputTemplate: 'Template for mapping output or "restricted" type names', + inputBranded: 'Output property for branded type for "permissive" types with fullName of the Message as its value', + outputBranded: 'Output property for branded type for "restricted" types with fullName of the Message as its value', + targetFileExtension: 'File extension for generated files.', + importFileExtension: 'File extension for import specifiers in generated code.' + }).demandOption(['outDir']) + .demand(1) + .usage('$0 [options] filenames...') + .epilogue('WARNING: This tool is in alpha. The CLI and generated code are subject to change') + .argv; + if (argv.verbose) { + console.log('Parsed arguments:', argv); + } + (0, util_1.addCommonProtos)(); + writeAllFiles(argv._, Object.assign(Object.assign({}, argv), { alternateCommentMode: true })).then(() => { + if (argv.verbose) { + console.log('Success'); + } + }, (error) => { + console.error(error); + process.exit(1); + }); +} +if (require.main === module) { + runScript(); +} +//# sourceMappingURL=proto-loader-gen-types.js.map \ No newline at end of file diff --git a/node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js.map b/node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js.map new file mode 100644 index 0000000..229cd48 --- /dev/null +++ b/node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"proto-loader-gen-types.js","sourceRoot":"","sources":["../../bin/proto-loader-gen-types.ts"],"names":[],"mappings":";;AACA;;;;;;;;;;;;;;;;GAgBG;;AAEH,yBAAyB;AACzB,6BAA6B;AAE7B,uCAAuC;AACvC,+BAA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AE,oGAAoG;QACnH,mBAAmB,EAAE,qCAAqC;QAC1D,mBAAmB,EAAE,yDAAyD;KAC/E,CAAC,CAAC,YAAY,CAAC,CAAC,QAAQ,CAAC,CAAC;SAC1B,MAAM,CAAC,CAAC,CAAC;SACT,KAAK,CAAC,2BAA2B,CAAC;SAClC,QAAQ,CAAC,kFAAkF,CAAC;SAC5F,IAAI,CAAC;IACR,IAAI,IAAI,CAAC,OAAO,EAAE;QAChB,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,IAAI,CAAC,CAAC;KACxC;IACD,IAAA,sBAAe,GAAE,CAAC;IAClB,aAAa,CAAC,IAAI,CAAC,CAAa,kCAAM,IAAI,KAAE,oBAAoB,EAAE,IAAI,IAAE,CAAC,IAAI,CAAC,GAAG,EAAE;QACjF,IAAI,IAAI,CAAC,OAAO,EAAE;YAChB,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;SACxB;IACH,CAAC,EAAE,CAAC,KAAK,EAAE,EAAE;QACX,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;QACpB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE;IAC3B,SAAS,EAAE,CAAC;CACb"} \ No newline at end of file diff --git a/node_modules/@grpc/proto-loader/build/src/index.d.ts b/node_modules/@grpc/proto-loader/build/src/index.d.ts new file mode 100644 index 0000000..ff575c0 --- /dev/null +++ b/node_modules/@grpc/proto-loader/build/src/index.d.ts @@ -0,0 +1,160 @@ +/** + * @license + * Copyright 2018 gRPC authors. + * + * 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. + * + */ +/// +import * as Protobuf from 'protobufjs'; +import * as descriptor from 'protobufjs/ext/descriptor'; +import { Options } from './util'; +import Long = require('long'); +export { Options, Long }; +/** + * This type exists for use with code generated by the proto-loader-gen-types + * tool. This type should be used with another interface, e.g. + * MessageType & AnyExtension for an object that is converted to or from a + * google.protobuf.Any message. + * For example, when processing an Any message: + * + * ```ts + * if (isAnyExtension(message)) { + * switch (message['@type']) { + * case TYPE1_URL: + * handleType1(message as AnyExtension & Type1); + * break; + * case TYPE2_URL: + * handleType2(message as AnyExtension & Type2); + * break; + * // ... + * } + * } + * ``` + */ +export interface AnyExtension { + /** + * The fully qualified name of the message type that this object represents, + * possibly including a URL prefix. + */ + '@type': string; +} +export declare function isAnyExtension(obj: object): obj is AnyExtension; +declare module 'protobufjs' { + interface Type { + toDescriptor(protoVersion: string): Protobuf.Message & descriptor.IDescriptorProto; + } + interface RootConstructor { + new (options?: Options): Root; + fromDescriptor(descriptorSet: descriptor.IFileDescriptorSet | Protobuf.Reader | Uint8Array): Root; + fromJSON(json: Protobuf.INamespace, root?: Root): Root; + } + interface Root { + toDescriptor(protoVersion: string): Protobuf.Message & descriptor.IFileDescriptorSet; + } + interface Enum { + toDescriptor(protoVersion: string): Protobuf.Message & descriptor.IEnumDescriptorProto; + } +} +export interface Serialize { + (value: T): Buffer; +} +export interface Deserialize { + (bytes: Buffer): T; +} +export interface ProtobufTypeDefinition { + format: string; + type: object; + fileDescriptorProtos: Buffer[]; +} +export interface MessageTypeDefinition extends ProtobufTypeDefinition { + format: 'Protocol Buffer 3 DescriptorProto'; +} +export interface EnumTypeDefinition extends ProtobufTypeDefinition { + format: 'Protocol Buffer 3 EnumDescriptorProto'; +} +export declare enum IdempotencyLevel { + IDEMPOTENCY_UNKNOWN = "IDEMPOTENCY_UNKNOWN", + NO_SIDE_EFFECTS = "NO_SIDE_EFFECTS", + IDEMPOTENT = "IDEMPOTENT" +} +export interface NamePart { + name_part: string; + is_extension: boolean; +} +export interface UninterpretedOption { + name?: NamePart[]; + identifier_value?: string; + positive_int_value?: number; + negative_int_value?: number; + double_value?: number; + string_value?: string; + aggregate_value?: string; +} +export interface MethodOptions { + deprecated: boolean; + idempotency_level: IdempotencyLevel; + uninterpreted_option: UninterpretedOption[]; + [k: string]: unknown; +} +export interface MethodDefinition { + path: string; + requestStream: boolean; + responseStream: boolean; + requestSerialize: Serialize; + responseSerialize: Serialize; + requestDeserialize: Deserialize; + responseDeserialize: Deserialize; + originalName?: string; + requestType: MessageTypeDefinition; + responseType: MessageTypeDefinition; + options: MethodOptions; +} +export interface ServiceDefinition { + [index: string]: MethodDefinition; +} +export declare type AnyDefinition = ServiceDefinition | MessageTypeDefinition | EnumTypeDefinition; +export interface PackageDefinition { + [index: string]: AnyDefinition; +} +/** + * Load a .proto file with the specified options. + * @param filename One or multiple file paths to load. Can be an absolute path + * or relative to an include path. + * @param options.keepCase Preserve field names. The default is to change them + * to camel case. + * @param options.longs The type that should be used to represent `long` values. + * Valid options are `Number` and `String`. Defaults to a `Long` object type + * from a library. + * @param options.enums The type that should be used to represent `enum` values. + * The only valid option is `String`. Defaults to the numeric value. + * @param options.bytes The type that should be used to represent `bytes` + * values. Valid options are `Array` and `String`. The default is to use + * `Buffer`. + * @param options.defaults Set default values on output objects. Defaults to + * `false`. + * @param options.arrays Set empty arrays for missing array values even if + * `defaults` is `false`. Defaults to `false`. + * @param options.objects Set empty objects for missing object values even if + * `defaults` is `false`. Defaults to `false`. + * @param options.oneofs Set virtual oneof properties to the present field's + * name + * @param options.json Represent Infinity and NaN as strings in float fields, + * and automatically decode google.protobuf.Any values. + * @param options.includeDirs Paths to search for imported `.proto` files. + */ +export declare function load(filename: string | string[], options?: Options): Promise; +export declare function loadSync(filename: string | string[], options?: Options): PackageDefinition; +export declare function fromJSON(json: Protobuf.INamespace, options?: Options): PackageDefinition; +export declare function loadFileDescriptorSetFromBuffer(descriptorSet: Buffer, options?: Options): PackageDefinition; +export declare function loadFileDescriptorSetFromObject(descriptorSet: Parameters[0], options?: Options): PackageDefinition; diff --git a/node_modules/@grpc/proto-loader/build/src/index.js b/node_modules/@grpc/proto-loader/build/src/index.js new file mode 100644 index 0000000..1d86395 --- /dev/null +++ b/node_modules/@grpc/proto-loader/build/src/index.js @@ -0,0 +1,244 @@ +"use strict"; +/** + * @license + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.loadFileDescriptorSetFromObject = exports.loadFileDescriptorSetFromBuffer = exports.fromJSON = exports.loadSync = exports.load = exports.IdempotencyLevel = exports.isAnyExtension = exports.Long = void 0; +const camelCase = require("lodash.camelcase"); +const Protobuf = require("protobufjs"); +const descriptor = require("protobufjs/ext/descriptor"); +const util_1 = require("./util"); +const Long = require("long"); +exports.Long = Long; +function isAnyExtension(obj) { + return ('@type' in obj) && (typeof obj['@type'] === 'string'); +} +exports.isAnyExtension = isAnyExtension; +var IdempotencyLevel; +(function (IdempotencyLevel) { + IdempotencyLevel["IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN"; + IdempotencyLevel["NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS"; + IdempotencyLevel["IDEMPOTENT"] = "IDEMPOTENT"; +})(IdempotencyLevel = exports.IdempotencyLevel || (exports.IdempotencyLevel = {})); +const descriptorOptions = { + longs: String, + enums: String, + bytes: String, + defaults: true, + oneofs: true, + json: true, +}; +function joinName(baseName, name) { + if (baseName === '') { + return name; + } + else { + return baseName + '.' + name; + } +} +function isHandledReflectionObject(obj) { + return (obj instanceof Protobuf.Service || + obj instanceof Protobuf.Type || + obj instanceof Protobuf.Enum); +} +function isNamespaceBase(obj) { + return obj instanceof Protobuf.Namespace || obj instanceof Protobuf.Root; +} +function getAllHandledReflectionObjects(obj, parentName) { + const objName = joinName(parentName, obj.name); + if (isHandledReflectionObject(obj)) { + return [[objName, obj]]; + } + else { + if (isNamespaceBase(obj) && typeof obj.nested !== 'undefined') { + return Object.keys(obj.nested) + .map(name => { + return getAllHandledReflectionObjects(obj.nested[name], objName); + }) + .reduce((accumulator, currentValue) => accumulator.concat(currentValue), []); + } + } + return []; +} +function createDeserializer(cls, options) { + return function deserialize(argBuf) { + return cls.toObject(cls.decode(argBuf), options); + }; +} +function createSerializer(cls) { + return function serialize(arg) { + if (Array.isArray(arg)) { + throw new Error(`Failed to serialize message: expected object with ${cls.name} structure, got array instead`); + } + const message = cls.fromObject(arg); + return cls.encode(message).finish(); + }; +} +function mapMethodOptions(options) { + return (options || []).reduce((obj, item) => { + for (const [key, value] of Object.entries(item)) { + switch (key) { + case 'uninterpreted_option': + obj.uninterpreted_option.push(item.uninterpreted_option); + break; + default: + obj[key] = value; + } + } + return obj; + }, { + deprecated: false, + idempotency_level: IdempotencyLevel.IDEMPOTENCY_UNKNOWN, + uninterpreted_option: [], + }); +} +function createMethodDefinition(method, serviceName, options, fileDescriptors) { + /* This is only ever called after the corresponding root.resolveAll(), so we + * can assume that the resolved request and response types are non-null */ + const requestType = method.resolvedRequestType; + const responseType = method.resolvedResponseType; + return { + path: '/' + serviceName + '/' + method.name, + requestStream: !!method.requestStream, + responseStream: !!method.responseStream, + requestSerialize: createSerializer(requestType), + requestDeserialize: createDeserializer(requestType, options), + responseSerialize: createSerializer(responseType), + responseDeserialize: createDeserializer(responseType, options), + // TODO(murgatroid99): Find a better way to handle this + originalName: camelCase(method.name), + requestType: createMessageDefinition(requestType, fileDescriptors), + responseType: createMessageDefinition(responseType, fileDescriptors), + options: mapMethodOptions(method.parsedOptions), + }; +} +function createServiceDefinition(service, name, options, fileDescriptors) { + const def = {}; + for (const method of service.methodsArray) { + def[method.name] = createMethodDefinition(method, name, options, fileDescriptors); + } + return def; +} +function createMessageDefinition(message, fileDescriptors) { + const messageDescriptor = message.toDescriptor('proto3'); + return { + format: 'Protocol Buffer 3 DescriptorProto', + type: messageDescriptor.$type.toObject(messageDescriptor, descriptorOptions), + fileDescriptorProtos: fileDescriptors, + }; +} +function createEnumDefinition(enumType, fileDescriptors) { + const enumDescriptor = enumType.toDescriptor('proto3'); + return { + format: 'Protocol Buffer 3 EnumDescriptorProto', + type: enumDescriptor.$type.toObject(enumDescriptor, descriptorOptions), + fileDescriptorProtos: fileDescriptors, + }; +} +/** + * function createDefinition(obj: Protobuf.Service, name: string, options: + * Options): ServiceDefinition; function createDefinition(obj: Protobuf.Type, + * name: string, options: Options): MessageTypeDefinition; function + * createDefinition(obj: Protobuf.Enum, name: string, options: Options): + * EnumTypeDefinition; + */ +function createDefinition(obj, name, options, fileDescriptors) { + if (obj instanceof Protobuf.Service) { + return createServiceDefinition(obj, name, options, fileDescriptors); + } + else if (obj instanceof Protobuf.Type) { + return createMessageDefinition(obj, fileDescriptors); + } + else if (obj instanceof Protobuf.Enum) { + return createEnumDefinition(obj, fileDescriptors); + } + else { + throw new Error('Type mismatch in reflection object handling'); + } +} +function createPackageDefinition(root, options) { + const def = {}; + root.resolveAll(); + const descriptorList = root.toDescriptor('proto3').file; + const bufferList = descriptorList.map(value => Buffer.from(descriptor.FileDescriptorProto.encode(value).finish())); + for (const [name, obj] of getAllHandledReflectionObjects(root, '')) { + def[name] = createDefinition(obj, name, options, bufferList); + } + return def; +} +function createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options) { + options = options || {}; + const root = Protobuf.Root.fromDescriptor(decodedDescriptorSet); + root.resolveAll(); + return createPackageDefinition(root, options); +} +/** + * Load a .proto file with the specified options. + * @param filename One or multiple file paths to load. Can be an absolute path + * or relative to an include path. + * @param options.keepCase Preserve field names. The default is to change them + * to camel case. + * @param options.longs The type that should be used to represent `long` values. + * Valid options are `Number` and `String`. Defaults to a `Long` object type + * from a library. + * @param options.enums The type that should be used to represent `enum` values. + * The only valid option is `String`. Defaults to the numeric value. + * @param options.bytes The type that should be used to represent `bytes` + * values. Valid options are `Array` and `String`. The default is to use + * `Buffer`. + * @param options.defaults Set default values on output objects. Defaults to + * `false`. + * @param options.arrays Set empty arrays for missing array values even if + * `defaults` is `false`. Defaults to `false`. + * @param options.objects Set empty objects for missing object values even if + * `defaults` is `false`. Defaults to `false`. + * @param options.oneofs Set virtual oneof properties to the present field's + * name + * @param options.json Represent Infinity and NaN as strings in float fields, + * and automatically decode google.protobuf.Any values. + * @param options.includeDirs Paths to search for imported `.proto` files. + */ +function load(filename, options) { + return (0, util_1.loadProtosWithOptions)(filename, options).then(loadedRoot => { + return createPackageDefinition(loadedRoot, options); + }); +} +exports.load = load; +function loadSync(filename, options) { + const loadedRoot = (0, util_1.loadProtosWithOptionsSync)(filename, options); + return createPackageDefinition(loadedRoot, options); +} +exports.loadSync = loadSync; +function fromJSON(json, options) { + options = options || {}; + const loadedRoot = Protobuf.Root.fromJSON(json); + loadedRoot.resolveAll(); + return createPackageDefinition(loadedRoot, options); +} +exports.fromJSON = fromJSON; +function loadFileDescriptorSetFromBuffer(descriptorSet, options) { + const decodedDescriptorSet = descriptor.FileDescriptorSet.decode(descriptorSet); + return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); +} +exports.loadFileDescriptorSetFromBuffer = loadFileDescriptorSetFromBuffer; +function loadFileDescriptorSetFromObject(descriptorSet, options) { + const decodedDescriptorSet = descriptor.FileDescriptorSet.fromObject(descriptorSet); + return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); +} +exports.loadFileDescriptorSetFromObject = loadFileDescriptorSetFromObject; +(0, util_1.addCommonProtos)(); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@grpc/proto-loader/build/src/index.js.map b/node_modules/@grpc/proto-loader/build/src/index.js.map new file mode 100644 index 0000000..8ba05f1 --- /dev/null +++ b/node_modules/@grpc/proto-loader/build/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;GAgBG;;;AAEH,8CAA+C;AAC/C,uCAAuC;AACvC,wDAAwD;AAExD,iCAAoG;AAEpG,6BAA8B;AAEZ,oBAAI;AA+BtB,SAAgB,cAAc,CAAC,GAAW;IACxC,OAAO,CAAC,OAAO,IAAI,GAAG,CAAC,IAAI,CAAC,OAAQ,GAAoB,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC;AAClF,CAAC;AAFD,wCAEC;AA0DD,IAAY,gBAIX;AAJD,WAAY,gBAAgB;IAC1B,+DAA2C,CAAA;IAC3C,uDAAmC,CAAA;IACnC,6CAAyB,CAAA;AAC3B,CAAC,EAJW,gBAAgB,GAAhB,wBAAgB,KAAhB,wBAAgB,QAI3B;AAsDD,MAAM,iBAAiB,GAAgC;IACrD,KAAK,EAAE,MAAM;IACb,KAAK,EAAE,MAAM;IACb,KAAK,EAAE,MAAM;IACb,QAAQ,EAAE,IAAI;IACd,MAAM,EAAE,IAAI;IACZ,IAAI,EAAE,IAAI;CACX,CAAC;AAEF,SAAS,QAAQ,CAAC,QAAgB,EAAE,IAAY;IAC9C,IAAI,QAAQ,KAAK,EAAE,EAAE;QACnB,OAAO,IAAI,CAAC;KACb;SAAM;QACL,OAAO,QAAQ,GAAG,GAAG,GAAG,IAAI,CAAC;KAC9B;AACH,CAAC;AAID,SAAS,yBAAyB,CAChC,GAA8B;IAE9B,OAAO,CACL,GAAG,YAAY,QAAQ,CAAC,OAAO;QAC/B,GAAG,YAAY,QAAQ,CAAC,IAAI;QAC5B,GAAG,YAAY,QAAQ,CAAC,IAAI,CAC7B,CAAC;AACJ,CAAC;AAED,SAAS,eAAe,CACtB,GAA8B;IAE9B,OAAO,GAAG,YAAY,QAAQ,CAAC,SAAS,IAAI,GAAG,YAAY,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,GAAG,UAAU,CAAC,iBAAiB,CAAC,UAAU,CAClE,aAAa,CACU,CAAC;IAE1B,OAAO,wCAAwC,CAC7C,oBAAoB,EACpB,OAAO,CACR,CAAC;AACJ,CAAC;AAZD,0EAYC;AAED,IAAA,sBAAe,GAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/proto-loader/build/src/util.d.ts b/node_modules/@grpc/proto-loader/build/src/util.d.ts new file mode 100644 index 0000000..d0b13d9 --- /dev/null +++ b/node_modules/@grpc/proto-loader/build/src/util.d.ts @@ -0,0 +1,27 @@ +/** + * @license + * Copyright 2018 gRPC authors. + * + * 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. + * + */ +import * as Protobuf from 'protobufjs'; +export declare type Options = Protobuf.IParseOptions & Protobuf.IConversionOptions & { + includeDirs?: string[]; +}; +export declare function loadProtosWithOptions(filename: string | string[], options?: Options): Promise; +export declare function loadProtosWithOptionsSync(filename: string | string[], options?: Options): Protobuf.Root; +/** + * Load Google's well-known proto files that aren't exposed by Protobuf.js. + */ +export declare function addCommonProtos(): void; diff --git a/node_modules/@grpc/proto-loader/build/src/util.js b/node_modules/@grpc/proto-loader/build/src/util.js new file mode 100644 index 0000000..7ade36b --- /dev/null +++ b/node_modules/@grpc/proto-loader/build/src/util.js @@ -0,0 +1,89 @@ +"use strict"; +/** + * @license + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.addCommonProtos = exports.loadProtosWithOptionsSync = exports.loadProtosWithOptions = void 0; +const fs = require("fs"); +const path = require("path"); +const Protobuf = require("protobufjs"); +function addIncludePathResolver(root, includePaths) { + const originalResolvePath = root.resolvePath; + root.resolvePath = (origin, target) => { + if (path.isAbsolute(target)) { + return target; + } + for (const directory of includePaths) { + const fullPath = path.join(directory, target); + try { + fs.accessSync(fullPath, fs.constants.R_OK); + return fullPath; + } + catch (err) { + continue; + } + } + process.emitWarning(`${target} not found in any of the include paths ${includePaths}`); + return originalResolvePath(origin, target); + }; +} +async function loadProtosWithOptions(filename, options) { + const root = new Protobuf.Root(); + options = options || {}; + if (!!options.includeDirs) { + if (!Array.isArray(options.includeDirs)) { + return Promise.reject(new Error('The includeDirs option must be an array')); + } + addIncludePathResolver(root, options.includeDirs); + } + const loadedRoot = await root.load(filename, options); + loadedRoot.resolveAll(); + return loadedRoot; +} +exports.loadProtosWithOptions = loadProtosWithOptions; +function loadProtosWithOptionsSync(filename, options) { + const root = new Protobuf.Root(); + options = options || {}; + if (!!options.includeDirs) { + if (!Array.isArray(options.includeDirs)) { + throw new Error('The includeDirs option must be an array'); + } + addIncludePathResolver(root, options.includeDirs); + } + const loadedRoot = root.loadSync(filename, options); + loadedRoot.resolveAll(); + return loadedRoot; +} +exports.loadProtosWithOptionsSync = loadProtosWithOptionsSync; +/** + * Load Google's well-known proto files that aren't exposed by Protobuf.js. + */ +function addCommonProtos() { + // Protobuf.js exposes: any, duration, empty, field_mask, struct, timestamp, + // and wrappers. compiler/plugin is excluded in Protobuf.js and here. + // Using constant strings for compatibility with tools like Webpack + const apiDescriptor = require('protobufjs/google/protobuf/api.json'); + const descriptorDescriptor = require('protobufjs/google/protobuf/descriptor.json'); + const sourceContextDescriptor = require('protobufjs/google/protobuf/source_context.json'); + const typeDescriptor = require('protobufjs/google/protobuf/type.json'); + Protobuf.common('api', apiDescriptor.nested.google.nested.protobuf.nested); + Protobuf.common('descriptor', descriptorDescriptor.nested.google.nested.protobuf.nested); + Protobuf.common('source_context', sourceContextDescriptor.nested.google.nested.protobuf.nested); + Protobuf.common('type', typeDescriptor.nested.google.nested.protobuf.nested); +} +exports.addCommonProtos = addCommonProtos; +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/node_modules/@grpc/proto-loader/build/src/util.js.map b/node_modules/@grpc/proto-loader/build/src/util.js.map new file mode 100644 index 0000000..bb517f7 --- /dev/null +++ b/node_modules/@grpc/proto-loader/build/src/util.js.map @@ -0,0 +1 @@ +{"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/util.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;GAgBG;;;AAEH,yBAAyB;AACzB,6BAA6B;AAC7B,uCAAuC;AAEvC,SAAS,sBAAsB,CAAC,IAAmB,EAAE,YAAsB;IACzE,MAAM,mBAAmB,GAAG,IAAI,CAAC,WAAW,CAAC;IAC7C,IAAI,CAAC,WAAW,GAAG,CAAC,MAAc,EAAE,MAAc,EAAE,EAAE;QACpD,IAAI,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE;YAC3B,OAAO,MAAM,CAAC;SACf;QACD,KAAK,MAAM,SAAS,IAAI,YAAY,EAAE;YACpC,MAAM,QAAQ,GAAW,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;YACtD,IAAI;gBACF,EAAE,CAAC,UAAU,CAAC,QAAQ,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;gBAC3C,OAAO,QAAQ,CAAC;aACjB;YAAC,OAAO,GAAG,EAAE;gBACZ,SAAS;aACV;SACF;QACD,OAAO,CAAC,WAAW,CAAC,GAAG,MAAM,0CAA0C,YAAY,EAAE,CAAC,CAAC;QACvF,OAAO,mBAAmB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7C,CAA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4EAA4E;IAC5E,qEAAqE;IAErE,mEAAmE;IACnE,MAAM,aAAa,GAAG,OAAO,CAAC,qCAAqC,CAAC,CAAC;IACrE,MAAM,oBAAoB,GAAG,OAAO,CAAC,4CAA4C,CAAC,CAAC;IACnF,MAAM,uBAAuB,GAAG,OAAO,CAAC,gDAAgD,CAAC,CAAC;IAC1F,MAAM,cAAc,GAAG,OAAO,CAAC,sCAAsC,CAAC,CAAC;IAEvE,QAAQ,CAAC,MAAM,CACb,KAAK,EACL,aAAa,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CACnD,CAAC;IACF,QAAQ,CAAC,MAAM,CACb,YAAY,EACZ,oBAAoB,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAC1D,CAAC;IACF,QAAQ,CAAC,MAAM,CACb,gBAAgB,EAChB,uBAAuB,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAC7D,CAAC;IACF,QAAQ,CAAC,MAAM,CACb,MAAM,EACN,cAAc,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CACpD,CAAC;AACJ,CAAC;AA1BD,0CA0BC"} \ No newline at end of file diff --git a/node_modules/@grpc/proto-loader/package.json b/node_modules/@grpc/proto-loader/package.json new file mode 100644 index 0000000..d9da2f7 --- /dev/null +++ b/node_modules/@grpc/proto-loader/package.json @@ -0,0 +1,69 @@ +{ + "name": "@grpc/proto-loader", + "version": "0.7.15", + "author": "Google Inc.", + "contributors": [ + { + "name": "Michael Lumish", + "email": "mlumish@google.com" + } + ], + "description": "gRPC utility library for loading .proto files", + "homepage": "https://grpc.io/", + "main": "build/src/index.js", + "typings": "build/src/index.d.ts", + "scripts": { + "build": "npm run compile", + "clean": "rimraf ./build", + "compile": "tsc -p .", + "format": "clang-format -i -style=\"{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}\" src/*.ts test/*.ts", + "lint": "tslint -c node_modules/google-ts-style/tslint.json -p . -t codeFrame --type-check", + "prepare": "npm run compile", + "test": "gulp test", + "check": "gts check", + "fix": "gts fix", + "pretest": "npm run compile", + "posttest": "npm run check", + "generate-golden": "node ./build/bin/proto-loader-gen-types.js --keepCase --longs=String --enums=String --defaults --oneofs --json --includeComments --inputTemplate=I%s --outputTemplate=O%s -I deps/gapic-showcase/schema/ deps/googleapis/ -O ./golden-generated --grpcLib @grpc/grpc-js google/showcase/v1beta1/echo.proto", + "validate-golden": "rm -rf ./golden-generated-old && mv ./golden-generated/ ./golden-generated-old && npm run generate-golden && diff -rb ./golden-generated ./golden-generated-old" + }, + "repository": { + "type": "git", + "url": "https://github.com/grpc/grpc-node.git" + }, + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/grpc/grpc-node/issues" + }, + "files": [ + "LICENSE", + "build/src/*.d.ts", + "build/src/*.{js,js.map}", + "build/bin/*.{js,js.map}" + ], + "bin": { + "proto-loader-gen-types": "./build/bin/proto-loader-gen-types.js" + }, + "dependencies": { + "lodash.camelcase": "^4.3.0", + "long": "^5.0.0", + "protobufjs": "^7.2.5", + "yargs": "^17.7.2" + }, + "devDependencies": { + "@types/lodash.camelcase": "^4.3.4", + "@types/mkdirp": "^1.0.1", + "@types/mocha": "^5.2.7", + "@types/node": "^10.17.26", + "@types/yargs": "^17.0.24", + "clang-format": "^1.2.2", + "google-proto-files": "^3.0.2", + "gts": "^3.1.0", + "rimraf": "^3.0.2", + "ts-node": "^10.9.2", + "typescript": "~4.7.4" + }, + "engines": { + "node": ">=6" + } +} diff --git a/node_modules/@js-sdsl/ordered-map/CHANGELOG.md b/node_modules/@js-sdsl/ordered-map/CHANGELOG.md new file mode 100644 index 0000000..4bd804b --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/CHANGELOG.md @@ -0,0 +1,237 @@ +# Change Log + +All notable changes to this project will be documented in this file. + +The format is based on Keep a Changelog and this project adheres to Semantic Versioning. + +## [4.4.2] - 2023.07.21 + +### Fixed + +- The pointer of Adapter container's iterator cannot as array to be deconstructed. + +### Added + +- Add `isAccessible` function to iterators for iterable containers. + +## [4.4.1] - 2023.06.05 + +### Fixed + +- Tree container with less than 3 items reverse iteration infinite loop + +## [4.4.0] - 2023.03.17 + +### Changed + +- Optimized inOrder travel function for tree container. +- Optimized `Symbol.iterator` function. +- Optimized `TreeContainer` `erase` function. +- Optimized some details of deque. +- Change `reverse` and `sort` returned value to `this`. + +## [4.3.0] - 2023.01.20 + +### Added + +- Add public member `container` to `Iterator` which means the container that the iterator pointed to. + +### Changed + +- Reimplement `Queue`, separate `Queue` from `Deque`. + +## [4.2.0] - 2022.11.20 + +### Changed + +- Optimized the structure of class `TreeNodeEnableIndex`. +- Change the `iterator access denied` error message to reduce the packing size. +- Change the internal storage of the hash container to the form of a linked list, traversing in insertion order. +- Standardize hash container. Make it extends from `Container` and add general functions. +- Refactor `LinkList` to do optimization. + +### Added + +- Add public `length` property to all the container. +- Add returned value to `pop` function including `popBack` and `popFront` to all the container which has such function. +- Add returned value to `eraseElementByKey` which means whether erase successfully. +- Add returned value to `push` or `insert` function which means the size of the container. + +### Fixed + +- Fixed wrong error type when `updateKeyByIterator`. +- Fixed wrong iterator was returned when erase tree reverse iterator. + +## [4.2.0-beta.1] - 2022.11.06 + +### Changed + +- Remove all the arrow function to optimize. +- Modify `HashContainer` implementation to optimize. + +## [4.2.0-beta.0] - 2022.10.30 + +### Added + +- Add `ts` sourcemap for debug mode. +- Add `this` param for `forEach` function. +- Support single package umd build. + +### Changed + +- Changed the packaging method of isolation packages release and the method of the member export. + +## [4.1.5] - 2022.09.30 + +### Added + +- Add `find`, `remove`, `updateItem` and `toArray` functions to `PriorityQueue`. +- Support single package release (use scope @js-sdsl). + +## [4.1.5-beta.1] - 2022.09.23 + +### Fixed + +- Get wrong tree index when size is 0. + +## [4.1.5-beta.0] - 2022.09.23 + +### Added + +- Add `index` property to tree iterator which represents the sequential index of the iterator in the tree. + +### Changed + +- Minimal optimization with private properties mangling, macro inlining and const enum. +- Private properties are now mangled. +- Remove `checkWithinAccessParams` function. +- Constants of `HashContainer` are moved to `HashContainerConst` const enum. +- The iteratorType parameter in the constructor now changed from `boolean` type to `IteratorType` const enum type. +- The type of `TreeNode.color` is now changed from `boolean` to `TreeNodeColor` const enum. +- Turn some member exports into export-only types. + +### Fixed + +- Fixed wrong iterator error message. + +## [4.1.4] - 2022.09.07 + +### Added + +- Add some notes. + +### Changed + +- Optimize hash container. +- Abstracting out the hash container. + +### Fixed + +- Fixed tree get height function return one larger than the real height. +- Tree-shaking not work in ES module. +- `Queue` and `Deque` should return `undefined` when container is empty. + +## [4.1.4-beta.0] - 2022.08.31 + +### Added + +- Add function update key by iterator. +- Add iterator copy function to get a copy of itself. +- Add insert by iterator hint function in tree container. + +### Changed + +- Changed OrderedMap's iterator pointer get from `Object.defineProperty'` to `Proxy`. +- Improve iterator performance by remove some judgment. +- Change iterator type description from `normal` and `reverse` to boolean. + +## [4.1.2-beta.0] - 2022.08.27 + +### Added + +- Make `SequentialContainer` and `TreeBaseContainer` export in the index. + +### Changed + +- Change rbTree binary search from recursive to loop implementation (don't effect using). +- Reduce memory waste during deque initialization. + +### Fixed + +- Fixed priority queue not dereference on pop. + +## [4.1.1] - 2022.08.23 + +### Fixed + +- Forgot to reset root node on rotation in red-black tree delete operation. +- Fix iterator invalidation after tree container removes iterator. + +## [4.1.0] - 2022.08.21 + +### Changed + +- Change some functions from recursive to loop implementation (don't effect using). +- Change some iterator function parameter type. +- Change commonjs target to `es6`. +- Change `Deque` from sequential queue to circular queue. +- Optimize so many places (don't affect using). + +### Fixed + +- Fix `Vector` length bugs. + +## [4.0.3] - 2022-08-13 + +### Changed + +- Change `if (this.empty())` to `if (!this.length)`. +- Change some unit test. +- Change class type and optimized type design. + +### Fixed + +- Fix can push undefined to deque. + +## [4.0.0] - 2022-07-30 + +### Changed + +- Remove InternalError error as much as possible (don't affect using). +- Change `HashSet` api `eraseElementByValue`'s name to `eraseElementByKey`. +- Change some unit tests to improve coverage (don't affect using). + +## [4.0.0-beta.0] - 2022-07-24 + +### Added + +- Complete test examples (don't effect using). +- The error thrown is standardized, you can catch it according to the error type. + +### Changed + +- Refactor all container from function to class (don't affect using). +- Abstracting tree containers and hash containers, change `Set`'s and `Map`'s name to `OrderedSet` and `OrderedMap` to distinguish it from the official container. +- Change `OrderedSet` api `eraseElementByValue`'s name to `eraseElementByKey`. + +### Fixed + +- Fixed so many bugs. + +## [3.0.0-beta.0] - 2022-04-29 + +### Added + +- Bidirectional iterator is provided for all containers except Stack, Queue, HashSet and HashMap. +- Added begin, end, rBegin and rEnd functions to some containers for using iterator. +- Added `eraseElementByIterator` function. + +### Changed + +- Changed Pair type `T, K` to `K, V` (don't affect using). +- Changed `find`, `lowerBound`, `upperBound`, `reverseLowerBound` and `reverseUpperBound` function's returned value to `Iterator`. + +### Fixed + +- Fixed an error when the insert value was 0. +- Fixed the problem that the lower version browser does not recognize symbol Compilation error caused by iterator. diff --git a/node_modules/@js-sdsl/ordered-map/LICENSE b/node_modules/@js-sdsl/ordered-map/LICENSE new file mode 100644 index 0000000..d46bd7e --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Zilong Yao + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@js-sdsl/ordered-map/README.md b/node_modules/@js-sdsl/ordered-map/README.md new file mode 100644 index 0000000..5b68d20 --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/README.md @@ -0,0 +1,270 @@ +

+ + js-sdsl logo + +

+ +

A javascript standard data structure library which benchmark against C++ STL

+ +

+ NPM Version + Build Status + Coverage Status + GITHUB Star + NPM Downloads + Gzip Size + Rate this package + MIT-license + GITHUB-language +

+ +

English | 简体中文

+ +## ✨ Included data structures + +- **Stack** - first in last out stack. +- **Queue** - first in first out queue. +- **PriorityQueue** - heap-implemented priority queue. +- **Vector** - protected array, cannot to operate properties like `length` directly. +- **LinkList** - linked list of non-contiguous memory addresses. +- **Deque** - double-ended-queue, O(1) time complexity to `unshift` or getting elements by index. +- **OrderedSet** - sorted set which implemented by red black tree. +- **OrderedMap** - sorted map which implemented by red black tree. +- **HashSet** - refer to the [polyfill of ES6 Set](https://github.com/rousan/collections-es6). +- **HashMap** - refer to the [polyfill of ES6 Map](https://github.com/rousan/collections-es6). + +## ⚔️ Benchmark + +We are benchmarking against other popular data structure libraries. In some ways we're better than the best library. See [benchmark](https://js-sdsl.org/#/test/benchmark-analyze). + +## 🖥 Supported platforms + +| ![][Edge-Icon]
IE / Edge | ![][Firefox-Icon]
Firefox | ![][Chrome-Icon]
Chrome | ![][Safari-Icon]
Safari | ![][Opera-Icon]
Opera | ![][NodeJs-Icon]
NodeJs | +|:----------------------------:|:-----------------------------:|:---------------------------:|:---------------------------:|:-------------------------:|:---------------------------:| +| Edge 12 | 36 | 49 | 10 | 36 | 10 | + +## 📦 Download + +Download directly by cdn: + +- [js-sdsl.js](https://unpkg.com/js-sdsl/dist/umd/js-sdsl.js) (for development) +- [js-sdsl.min.js](https://unpkg.com/js-sdsl/dist/umd/js-sdsl.min.js) (for production) + +Or install js-sdsl using npm: + +```bash +npm install js-sdsl +``` + +Or you can download the isolation packages containing only the containers you want: + +| package | npm | size | docs | +|---------------------------------------------------|-----------------------------------------------------------------------|------------------------------------------------------------------|-----------------------------| +| [@js-sdsl/stack][stack-package] | [![NPM Package][stack-npm-version]][stack-npm-link] | [![GZIP Size][stack-umd-size]][stack-umd-link] | [link][stack-docs] | +| [@js-sdsl/queue][queue-package] | [![NPM Package][queue-npm-version]][queue-npm-link] | [![GZIP Size][queue-umd-size]][queue-umd-link] | [link][queue-docs] | +| [@js-sdsl/priority-queue][priority-queue-package] | [![NPM Package][priority-queue-npm-version]][priority-queue-npm-link] | [![GZIP Size][priority-queue-umd-size]][priority-queue-umd-link] | [link][priority-queue-docs] | +| [@js-sdsl/vector][vector-package] | [![NPM Package][vector-npm-version]][vector-npm-link] | [![GZIP Size][vector-umd-size]][vector-umd-link] | [link][vector-docs] | +| [@js-sdsl/link-list][link-list-package] | [![NPM Package][link-list-npm-version]][link-list-npm-link] | [![GZIP Size][link-list-umd-size]][link-list-umd-link] | [link][link-list-docs] | +| [@js-sdsl/deque][deque-package] | [![NPM Package][deque-npm-version]][deque-npm-link] | [![GZIP Size][deque-umd-size]][deque-umd-link] | [link][deque-docs] | +| [@js-sdsl/ordered-set][ordered-set-package] | [![NPM Package][ordered-set-npm-version]][ordered-set-npm-link] | [![GZIP Size][ordered-set-umd-size]][ordered-set-umd-link] | [link][ordered-set-docs] | +| [@js-sdsl/ordered-map][ordered-map-package] | [![NPM Package][ordered-map-npm-version]][ordered-map-npm-link] | [![GZIP Size][ordered-map-umd-size]][ordered-map-umd-link] | [link][ordered-map-docs] | +| [@js-sdsl/hash-set][hash-set-package] | [![NPM Package][hash-set-npm-version]][hash-set-npm-link] | [![GZIP Size][hash-set-umd-size]][hash-set-umd-link] | [link][hash-set-docs] | +| [@js-sdsl/hash-map][hash-map-package] | [![NPM Package][hash-map-npm-version]][hash-map-npm-link] | [![GZIP Size][hash-map-umd-size]][hash-map-umd-link] | [link][hash-map-docs] | + +## 🪒 Usage + +You can visit our [official website](https://js-sdsl.org/) to get more information. + +To help you have a better use, we also provide this [API document](https://js-sdsl.org/js-sdsl/index.html). + +For previous versions of the documentation, please visit: + +`https://js-sdsl.org/js-sdsl/previous/v${version}/index.html` + +E.g. + +[https://js-sdsl.org/js-sdsl/previous/v4.1.5/index.html](https://js-sdsl.org/js-sdsl/previous/v4.1.5/index.html) + +### For browser + +```html + + +``` + +### For npm + +```javascript +// esModule +import { OrderedMap } from 'js-sdsl'; +// commonJs +const { OrderedMap } = require('js-sdsl'); +const myOrderedMap = new OrderedMap(); +myOrderedMap.setElement(1, 2); +console.log(myOrderedMap.getElementByKey(1)); // 2 +``` + +## 🛠 Test + +### Unit test + +We use [karma](https://karma-runner.github.io/) and [mocha](https://mochajs.org/) frame to do unit tests and synchronize to [coveralls](https://coveralls.io/github/js-sdsl/js-sdsl). You can run `yarn test:unit` command to reproduce it. + +### For performance + +We tested most of the functions for efficiency. You can go to [`gh-pages/performance.md`](https://github.com/js-sdsl/js-sdsl/blob/gh-pages/performance.md) to see our running results or reproduce it with `yarn test:performance` command. + +You can also visit [here](https://js-sdsl.org/#/test/performance-test) to get the result. + +## ⌨️ Development + +Use Gitpod, a free online dev environment for GitHub. + +[![Open in Gippod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/js-sdsl/js-sdsl) + +Or clone locally: + +```bash +$ git clone https://github.com/js-sdsl/js-sdsl.git +$ cd js-sdsl +$ npm install +$ npm run dev # development mode +``` + +Then you can see the output in `dist/cjs` folder. + +## 🤝 Contributing + +Feel free to dive in! Open an issue or submit PRs. It may be helpful to read the [Contributor Guide](https://github.com/js-sdsl/js-sdsl/blob/main/.github/CONTRIBUTING.md). + +### Contributors + +Thanks goes to these wonderful people: + + + + + + + + + + + +

Takatoshi Kondo

💻 ⚠️

noname

💻
+ + + + + + +This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! + +## ❤️ Sponsors and Backers + +The special thanks to these sponsors or backers because they provided support at a very early stage: + +eslint logo + +Thanks also give to these sponsors or backers: + +[![sponsors](https://opencollective.com/js-sdsl/tiers/sponsors.svg?avatarHeight=36)](https://opencollective.com/js-sdsl#support) + +[![backers](https://opencollective.com/js-sdsl/tiers/backers.svg?avatarHeight=36)](https://opencollective.com/js-sdsl#support) + +## 🪪 License + +[MIT](https://github.com/js-sdsl/js-sdsl/blob/main/LICENSE) © [ZLY201](https://github.com/zly201) + +[Edge-Icon]: https://js-sdsl.org/assets/image/platform/edge.png +[Firefox-Icon]: https://js-sdsl.org/assets/image/platform/firefox.png +[Chrome-Icon]: https://js-sdsl.org/assets/image/platform/chrome.png +[Safari-Icon]: https://js-sdsl.org/assets/image/platform/safari.png +[Opera-Icon]: https://js-sdsl.org/assets/image/platform/opera.png +[NodeJs-Icon]: https://js-sdsl.org/assets/image/platform/nodejs.png + +[stack-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/OtherContainer/Stack.ts +[stack-npm-version]: https://img.shields.io/npm/v/@js-sdsl/stack +[stack-npm-link]: https://www.npmjs.com/package/@js-sdsl/stack +[stack-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/stack/dist/umd/stack.min.js?compression=gzip&style=flat-square/ +[stack-umd-link]: https://unpkg.com/@js-sdsl/stack/dist/umd/stack.min.js +[stack-docs]: https://js-sdsl.org/js-sdsl/classes/Stack.html + +[queue-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/OtherContainer/Queue.ts +[queue-npm-version]: https://img.shields.io/npm/v/@js-sdsl/queue +[queue-npm-link]: https://www.npmjs.com/package/@js-sdsl/queue +[queue-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/queue/dist/umd/queue.min.js?compression=gzip&style=flat-square/ +[queue-umd-link]: https://unpkg.com/@js-sdsl/queue/dist/umd/queue.min.js +[queue-docs]: https://js-sdsl.org/js-sdsl/classes/Queue.html + +[priority-queue-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/OtherContainer/PriorityQueue.ts +[priority-queue-npm-version]: https://img.shields.io/npm/v/@js-sdsl/priority-queue +[priority-queue-npm-link]: https://www.npmjs.com/package/@js-sdsl/priority-queue +[priority-queue-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/priority-queue/dist/umd/priority-queue.min.js?compression=gzip&style=flat-square/ +[priority-queue-umd-link]: https://unpkg.com/@js-sdsl/priority-queue/dist/umd/priority-queue.min.js +[priority-queue-docs]: https://js-sdsl.org/js-sdsl/classes/PriorityQueue.html + +[vector-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/SequentialContainer/Vector.ts +[vector-npm-version]: https://img.shields.io/npm/v/@js-sdsl/vector +[vector-npm-link]: https://www.npmjs.com/package/@js-sdsl/vector +[vector-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/vector/dist/umd/vector.min.js?compression=gzip&style=flat-square/ +[vector-umd-link]: https://unpkg.com/@js-sdsl/vector/dist/umd/vector.min.js +[vector-docs]: https://js-sdsl.org/js-sdsl/classes/Vector.html + +[link-list-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/SequentialContainer/LinkList.ts +[link-list-npm-version]: https://img.shields.io/npm/v/@js-sdsl/link-list +[link-list-npm-link]: https://www.npmjs.com/package/@js-sdsl/link-list +[link-list-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/link-list/dist/umd/link-list.min.js?compression=gzip&style=flat-square/ +[link-list-umd-link]: https://unpkg.com/@js-sdsl/link-list/dist/umd/link-list.min.js +[link-list-docs]: https://js-sdsl.org/js-sdsl/classes/LinkList.html + +[deque-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/SequentialContainer/Deque.ts +[deque-npm-version]: https://img.shields.io/npm/v/@js-sdsl/deque +[deque-npm-link]: https://www.npmjs.com/package/@js-sdsl/deque +[deque-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/deque/dist/umd/deque.min.js?compression=gzip&style=flat-square/ +[deque-umd-link]: https://unpkg.com/@js-sdsl/deque/dist/umd/deque.min.js +[deque-docs]: https://js-sdsl.org/js-sdsl/classes/Deque.html + +[ordered-set-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/TreeContainer/OrderedSet.ts +[ordered-set-npm-version]: https://img.shields.io/npm/v/@js-sdsl/ordered-set +[ordered-set-npm-link]: https://www.npmjs.com/package/@js-sdsl/ordered-set +[ordered-set-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/ordered-set/dist/umd/ordered-set.min.js?compression=gzip&style=flat-square/ +[ordered-set-umd-link]: https://unpkg.com/@js-sdsl/ordered-set/dist/umd/ordered-set.min.js +[ordered-set-docs]: https://js-sdsl.org/js-sdsl/classes/OrderedSet.html + +[ordered-map-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/TreeContainer/OrderedMap.ts +[ordered-map-npm-version]: https://img.shields.io/npm/v/@js-sdsl/ordered-map +[ordered-map-npm-link]: https://www.npmjs.com/package/@js-sdsl/ordered-map +[ordered-map-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/ordered-map/dist/umd/ordered-map.min.js?compression=gzip&style=flat-square/ +[ordered-map-umd-link]: https://unpkg.com/@js-sdsl/ordered-map/dist/umd/ordered-map.min.js +[ordered-map-docs]: https://js-sdsl.org/js-sdsl/classes/OrderedMap.html + +[hash-set-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/HashContainer/HashSet.ts +[hash-set-npm-version]: https://img.shields.io/npm/v/@js-sdsl/hash-set +[hash-set-npm-link]: https://www.npmjs.com/package/@js-sdsl/hash-set +[hash-set-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/hash-set/dist/umd/hash-set.min.js?compression=gzip&style=flat-square/ +[hash-set-umd-link]: https://unpkg.com/@js-sdsl/hash-set/dist/umd/hash-set.min.js +[hash-set-docs]: https://js-sdsl.org/js-sdsl/classes/HashSet.html + +[hash-map-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/HashContainer/HashMap.ts +[hash-map-npm-version]: https://img.shields.io/npm/v/@js-sdsl/hash-map +[hash-map-npm-link]: https://www.npmjs.com/package/@js-sdsl/hash-map +[hash-map-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/hash-map/dist/umd/hash-map.min.js?compression=gzip&style=flat-square/ +[hash-map-umd-link]: https://unpkg.com/@js-sdsl/hash-map/dist/umd/hash-map.min.js +[hash-map-docs]: https://js-sdsl.org/js-sdsl/classes/HashMap.html diff --git a/node_modules/@js-sdsl/ordered-map/README.zh-CN.md b/node_modules/@js-sdsl/ordered-map/README.zh-CN.md new file mode 100644 index 0000000..a10ef17 --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/README.zh-CN.md @@ -0,0 +1,272 @@ +

+ + js-sdsl logo + +

+ +

一款参考 C++ STL 实现的 JavaScript 标准数据结构库

+ +

+ NPM Version + Build Status + Coverage Status + GITHUB Star + NPM Downloads + Gzip Size + Rate this package + MIT-license + GITHUB-language +

+ +

English | 简体中文

+ +## ✨ 包含的数据结构 + +- **Stack** - 先进后出的堆栈 +- **Queue** - 先进先出的队列 +- **PriorityQueue** - 堆实现的优先级队列 +- **Vector** - 受保护的数组,不能直接操作像 `length` 这样的属性 +- **LinkList** - 非连续内存地址的链表 +- **Deque** - 双端队列,向前和向后插入元素或按索引获取元素的时间复杂度为 O(1) +- **OrderedSet** - 由红黑树实现的排序集合 +- **OrderedMap** - 由红黑树实现的排序字典 +- **HashSet** - 参考 [ES6 Set polyfill](https://github.com/rousan/collections-es6) 实现的哈希集合 +- **HashMap** - 参考 [ES6 Set polyfill](https://github.com/rousan/collections-es6) 实现的哈希字典 + +## ⚔️ 基准测试 + +我们和其他数据结构库进行了基准测试,在某些场景我们甚至超过了当前最流行的库 + +查看 [benchmark](https://js-sdsl.org/#/zh-cn/test/benchmark-analyze) 以获取更多信息 + +## 🖥 支持的平台 + +| ![][Edge-Icon]
IE / Edge | ![][Firefox-Icon]
Firefox | ![][Chrome-Icon]
Chrome | ![][Safari-Icon]
Safari | ![][Opera-Icon]
Opera | ![][NodeJs-Icon]
NodeJs | +|:----------------------------:|:-----------------------------:|:---------------------------:|:---------------------------:|:-------------------------:|:---------------------------:| +| Edge 12 | 36 | 49 | 10 | 36 | 10 | + +## 📦 下载 + +使用 cdn 直接引入 + +- [js-sdsl.js](https://unpkg.com/js-sdsl/dist/umd/js-sdsl.js) (for development) +- [js-sdsl.min.js](https://unpkg.com/js-sdsl/dist/umd/js-sdsl.min.js) (for production) + +使用 npm 下载 + +```bash +npm install js-sdsl +``` + +或者根据需要安装以下任意单个包 + +| package | npm | size | docs | +|---------------------------------------------------|-----------------------------------------------------------------------|------------------------------------------------------------------|-----------------------------| +| [@js-sdsl/stack][stack-package] | [![NPM Package][stack-npm-version]][stack-npm-link] | [![GZIP Size][stack-umd-size]][stack-umd-link] | [link][stack-docs] | +| [@js-sdsl/queue][queue-package] | [![NPM Package][queue-npm-version]][queue-npm-link] | [![GZIP Size][queue-umd-size]][queue-umd-link] | [link][queue-docs] | +| [@js-sdsl/priority-queue][priority-queue-package] | [![NPM Package][priority-queue-npm-version]][priority-queue-npm-link] | [![GZIP Size][priority-queue-umd-size]][priority-queue-umd-link] | [link][priority-queue-docs] | +| [@js-sdsl/vector][vector-package] | [![NPM Package][vector-npm-version]][vector-npm-link] | [![GZIP Size][vector-umd-size]][vector-umd-link] | [link][vector-docs] | +| [@js-sdsl/link-list][link-list-package] | [![NPM Package][link-list-npm-version]][link-list-npm-link] | [![GZIP Size][link-list-umd-size]][link-list-umd-link] | [link][link-list-docs] | +| [@js-sdsl/deque][deque-package] | [![NPM Package][deque-npm-version]][deque-npm-link] | [![GZIP Size][deque-umd-size]][deque-umd-link] | [link][deque-docs] | +| [@js-sdsl/ordered-set][ordered-set-package] | [![NPM Package][ordered-set-npm-version]][ordered-set-npm-link] | [![GZIP Size][ordered-set-umd-size]][ordered-set-umd-link] | [link][ordered-set-docs] | +| [@js-sdsl/ordered-map][ordered-map-package] | [![NPM Package][ordered-map-npm-version]][ordered-map-npm-link] | [![GZIP Size][ordered-map-umd-size]][ordered-map-umd-link] | [link][ordered-map-docs] | +| [@js-sdsl/hash-set][hash-set-package] | [![NPM Package][hash-set-npm-version]][hash-set-npm-link] | [![GZIP Size][hash-set-umd-size]][hash-set-umd-link] | [link][hash-set-docs] | +| [@js-sdsl/hash-map][hash-map-package] | [![NPM Package][hash-map-npm-version]][hash-map-npm-link] | [![GZIP Size][hash-map-umd-size]][hash-map-umd-link] | [link][hash-map-docs] | + +## 🪒 使用说明 + +您可以[访问我们的主页](https://js-sdsl.org/)获取更多信息 + +并且我们提供了完整的 [API 文档](https://js-sdsl.org/js-sdsl/index.html)供您参考 + +想要查看从前版本的文档,请访问: + +`https://js-sdsl.org/js-sdsl/previous/v${version}/index.html` + +例如: + +[https://js-sdsl.org/js-sdsl/previous/v4.1.5/index.html](https://js-sdsl.org/js-sdsl/previous/v4.1.5/index.html) + +### 在浏览器中使用 + +```html + + +``` + +### npm 引入 + +```javascript +// esModule +import { OrderedMap } from 'js-sdsl'; +// commonJs +const { OrderedMap } = require('js-sdsl'); +const myOrderedMap = new OrderedMap(); +myOrderedMap.setElement(1, 2); +console.log(myOrderedMap.getElementByKey(1)); // 2 +``` + +## 🛠 测试 + +### 单元测试 + +我们使用 [karma](https://karma-runner.github.io/) 和 [mocha](https://mochajs.org/) 框架进行单元测试,并同步到 [coveralls](https://coveralls.io/github/js-sdsl/js-sdsl) 上,你可以使用 `yarn test:unit` 命令来重建它 + +### 对于性能的校验 + +我们对于编写的所有 API 进行了性能测试,并将结果同步到了 [`gh-pages/performance.md`](https://github.com/js-sdsl/js-sdsl/blob/gh-pages/performance.md) 中,你可以通过 `yarn test:performance` 命令来重现它 + +您也可以访问[我们的网站](https://js-sdsl.org/#/zh-cn/test/performance-test)来获取结果 + +## ⌨️ 开发 + +可以使用 Gitpod 进行在线编辑: + +[![Open in Gippod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/js-sdsl/js-sdsl) + +或者在本地使用以下命令获取源码进行开发: + +```bash +$ git clone https://github.com/js-sdsl/js-sdsl.git +$ cd js-sdsl +$ npm install +$ npm run dev # development mode +``` + +之后您在 `dist/cjs` 文件夹中可以看到在 `dev` 模式下打包生成的产物 + +## 🤝 贡献 + +我们欢迎所有的开发人员提交 issue 或 pull request,阅读[贡献者指南](https://github.com/js-sdsl/js-sdsl/blob/main/.github/CONTRIBUTING.md)可能会有所帮助 + +### 贡献者 + +感谢对本项目做出贡献的开发者们: + + + + + + + + + + + +

Takatoshi Kondo

💻 ⚠️

noname

💻
+ + + + + + +本项目遵循 [all-contributors](https://github.com/all-contributors/all-contributors) 规范。 欢迎任何形式的贡献! + +## ❤️ 赞助者 + +特别鸣谢下列赞助商和支持者们,他们在非常早期的时候为我们提供了支持: + +eslint logo + +同样感谢这些赞助商和支持者们: + +[![sponsors](https://opencollective.com/js-sdsl/tiers/sponsors.svg?avatarHeight=36)](https://opencollective.com/js-sdsl#support) + +[![backers](https://opencollective.com/js-sdsl/tiers/backers.svg?avatarHeight=36)](https://opencollective.com/js-sdsl#support) + +## 🪪 许可证 + +[MIT](https://github.com/js-sdsl/js-sdsl/blob/main/LICENSE) © [ZLY201](https://github.com/zly201) + +[Edge-Icon]: https://js-sdsl.org/assets/image/platform/edge.png +[Firefox-Icon]: https://js-sdsl.org/assets/image/platform/firefox.png +[Chrome-Icon]: https://js-sdsl.org/assets/image/platform/chrome.png +[Safari-Icon]: https://js-sdsl.org/assets/image/platform/safari.png +[Opera-Icon]: https://js-sdsl.org/assets/image/platform/opera.png +[NodeJs-Icon]: https://js-sdsl.org/assets/image/platform/nodejs.png + +[stack-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/OtherContainer/Stack.ts +[stack-npm-version]: https://img.shields.io/npm/v/@js-sdsl/stack +[stack-npm-link]: https://www.npmjs.com/package/@js-sdsl/stack +[stack-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/stack/dist/umd/stack.min.js?compression=gzip&style=flat-square/ +[stack-umd-link]: https://unpkg.com/@js-sdsl/stack/dist/umd/stack.min.js +[stack-docs]: https://js-sdsl.org/js-sdsl/classes/Stack.html + +[queue-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/OtherContainer/Queue.ts +[queue-npm-version]: https://img.shields.io/npm/v/@js-sdsl/queue +[queue-npm-link]: https://www.npmjs.com/package/@js-sdsl/queue +[queue-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/queue/dist/umd/queue.min.js?compression=gzip&style=flat-square/ +[queue-umd-link]: https://unpkg.com/@js-sdsl/queue/dist/umd/queue.min.js +[queue-docs]: https://js-sdsl.org/js-sdsl/classes/Queue.html + +[priority-queue-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/OtherContainer/PriorityQueue.ts +[priority-queue-npm-version]: https://img.shields.io/npm/v/@js-sdsl/priority-queue +[priority-queue-npm-link]: https://www.npmjs.com/package/@js-sdsl/priority-queue +[priority-queue-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/priority-queue/dist/umd/priority-queue.min.js?compression=gzip&style=flat-square/ +[priority-queue-umd-link]: https://unpkg.com/@js-sdsl/priority-queue/dist/umd/priority-queue.min.js +[priority-queue-docs]: https://js-sdsl.org/js-sdsl/classes/PriorityQueue.html + +[vector-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/SequentialContainer/Vector.ts +[vector-npm-version]: https://img.shields.io/npm/v/@js-sdsl/vector +[vector-npm-link]: https://www.npmjs.com/package/@js-sdsl/vector +[vector-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/vector/dist/umd/vector.min.js?compression=gzip&style=flat-square/ +[vector-umd-link]: https://unpkg.com/@js-sdsl/vector/dist/umd/vector.min.js +[vector-docs]: https://js-sdsl.org/js-sdsl/classes/Vector.html + +[link-list-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/SequentialContainer/LinkList.ts +[link-list-npm-version]: https://img.shields.io/npm/v/@js-sdsl/link-list +[link-list-npm-link]: https://www.npmjs.com/package/@js-sdsl/link-list +[link-list-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/link-list/dist/umd/link-list.min.js?compression=gzip&style=flat-square/ +[link-list-umd-link]: https://unpkg.com/@js-sdsl/link-list/dist/umd/link-list.min.js +[link-list-docs]: https://js-sdsl.org/js-sdsl/classes/LinkList.html + +[deque-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/SequentialContainer/Deque.ts +[deque-npm-version]: https://img.shields.io/npm/v/@js-sdsl/deque +[deque-npm-link]: https://www.npmjs.com/package/@js-sdsl/deque +[deque-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/deque/dist/umd/deque.min.js?compression=gzip&style=flat-square/ +[deque-umd-link]: https://unpkg.com/@js-sdsl/deque/dist/umd/deque.min.js +[deque-docs]: https://js-sdsl.org/js-sdsl/classes/Deque.html + +[ordered-set-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/TreeContainer/OrderedSet.ts +[ordered-set-npm-version]: https://img.shields.io/npm/v/@js-sdsl/ordered-set +[ordered-set-npm-link]: https://www.npmjs.com/package/@js-sdsl/ordered-set +[ordered-set-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/ordered-set/dist/umd/ordered-set.min.js?compression=gzip&style=flat-square/ +[ordered-set-umd-link]: https://unpkg.com/@js-sdsl/ordered-set/dist/umd/ordered-set.min.js +[ordered-set-docs]: https://js-sdsl.org/js-sdsl/classes/OrderedSet.html + +[ordered-map-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/TreeContainer/OrderedMap.ts +[ordered-map-npm-version]: https://img.shields.io/npm/v/@js-sdsl/ordered-map +[ordered-map-npm-link]: https://www.npmjs.com/package/@js-sdsl/ordered-map +[ordered-map-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/ordered-map/dist/umd/ordered-map.min.js?compression=gzip&style=flat-square/ +[ordered-map-umd-link]: https://unpkg.com/@js-sdsl/ordered-map/dist/umd/ordered-map.min.js +[ordered-map-docs]: https://js-sdsl.org/js-sdsl/classes/OrderedMap.html + +[hash-set-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/HashContainer/HashSet.ts +[hash-set-npm-version]: https://img.shields.io/npm/v/@js-sdsl/hash-set +[hash-set-npm-link]: https://www.npmjs.com/package/@js-sdsl/hash-set +[hash-set-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/hash-set/dist/umd/hash-set.min.js?compression=gzip&style=flat-square/ +[hash-set-umd-link]: https://unpkg.com/@js-sdsl/hash-set/dist/umd/hash-set.min.js +[hash-set-docs]: https://js-sdsl.org/js-sdsl/classes/HashSet.html + +[hash-map-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/HashContainer/HashMap.ts +[hash-map-npm-version]: https://img.shields.io/npm/v/@js-sdsl/hash-map +[hash-map-npm-link]: https://www.npmjs.com/package/@js-sdsl/hash-map +[hash-map-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/hash-map/dist/umd/hash-map.min.js?compression=gzip&style=flat-square/ +[hash-map-umd-link]: https://unpkg.com/@js-sdsl/hash-map/dist/umd/hash-map.min.js +[hash-map-docs]: https://js-sdsl.org/js-sdsl/classes/HashMap.html diff --git a/node_modules/@js-sdsl/ordered-map/dist/cjs/index.d.ts b/node_modules/@js-sdsl/ordered-map/dist/cjs/index.d.ts new file mode 100644 index 0000000..8615f37 --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/dist/cjs/index.d.ts @@ -0,0 +1,402 @@ +/** + * @description The iterator type including `NORMAL` and `REVERSE`. + */ +declare const enum IteratorType { + NORMAL = 0, + REVERSE = 1 +} +declare abstract class ContainerIterator { + /** + * @description The container pointed to by the iterator. + */ + abstract readonly container: Container; + /** + * @description Iterator's type. + * @example + * console.log(container.end().iteratorType === IteratorType.NORMAL); // true + */ + readonly iteratorType: IteratorType; + /** + * @param iter - The other iterator you want to compare. + * @returns Whether this equals to obj. + * @example + * container.find(1).equals(container.end()); + */ + equals(iter: ContainerIterator): boolean; + /** + * @description Pointers to element. + * @returns The value of the pointer's element. + * @example + * const val = container.begin().pointer; + */ + abstract get pointer(): T; + /** + * @description Set pointer's value (some containers are unavailable). + * @param newValue - The new value you want to set. + * @example + * (>container).begin().pointer = 1; + */ + abstract set pointer(newValue: T); + /** + * @description Move `this` iterator to pre. + * @returns The iterator's self. + * @example + * const iter = container.find(1); // container = [0, 1] + * const pre = iter.pre(); + * console.log(pre === iter); // true + * console.log(pre.equals(iter)); // true + * console.log(pre.pointer, iter.pointer); // 0, 0 + */ + abstract pre(): this; + /** + * @description Move `this` iterator to next. + * @returns The iterator's self. + * @example + * const iter = container.find(1); // container = [1, 2] + * const next = iter.next(); + * console.log(next === iter); // true + * console.log(next.equals(iter)); // true + * console.log(next.pointer, iter.pointer); // 2, 2 + */ + abstract next(): this; + /** + * @description Get a copy of itself. + * @returns The copy of self. + * @example + * const iter = container.find(1); // container = [1, 2] + * const next = iter.copy().next(); + * console.log(next === iter); // false + * console.log(next.equals(iter)); // false + * console.log(next.pointer, iter.pointer); // 2, 1 + */ + abstract copy(): ContainerIterator; + abstract isAccessible(): boolean; +} +declare abstract class Base { + /** + * @returns The size of the container. + * @example + * const container = new Vector([1, 2]); + * console.log(container.length); // 2 + */ + get length(): number; + /** + * @returns The size of the container. + * @example + * const container = new Vector([1, 2]); + * console.log(container.size()); // 2 + */ + size(): number; + /** + * @returns Whether the container is empty. + * @example + * container.clear(); + * console.log(container.empty()); // true + */ + empty(): boolean; + /** + * @description Clear the container. + * @example + * container.clear(); + * console.log(container.empty()); // true + */ + abstract clear(): void; +} +declare abstract class Container extends Base { + /** + * @returns Iterator pointing to the beginning element. + * @example + * const begin = container.begin(); + * const end = container.end(); + * for (const it = begin; !it.equals(end); it.next()) { + * doSomething(it.pointer); + * } + */ + abstract begin(): ContainerIterator; + /** + * @returns Iterator pointing to the super end like c++. + * @example + * const begin = container.begin(); + * const end = container.end(); + * for (const it = begin; !it.equals(end); it.next()) { + * doSomething(it.pointer); + * } + */ + abstract end(): ContainerIterator; + /** + * @returns Iterator pointing to the end element. + * @example + * const rBegin = container.rBegin(); + * const rEnd = container.rEnd(); + * for (const it = rBegin; !it.equals(rEnd); it.next()) { + * doSomething(it.pointer); + * } + */ + abstract rBegin(): ContainerIterator; + /** + * @returns Iterator pointing to the super begin like c++. + * @example + * const rBegin = container.rBegin(); + * const rEnd = container.rEnd(); + * for (const it = rBegin; !it.equals(rEnd); it.next()) { + * doSomething(it.pointer); + * } + */ + abstract rEnd(): ContainerIterator; + /** + * @returns The first element of the container. + */ + abstract front(): T | undefined; + /** + * @returns The last element of the container. + */ + abstract back(): T | undefined; + /** + * @param element - The element you want to find. + * @returns An iterator pointing to the element if found, or super end if not found. + * @example + * container.find(1).equals(container.end()); + */ + abstract find(element: T): ContainerIterator; + /** + * @description Iterate over all elements in the container. + * @param callback - Callback function like Array.forEach. + * @example + * container.forEach((element, index) => console.log(element, index)); + */ + abstract forEach(callback: (element: T, index: number, container: Container) => void): void; + /** + * @description Gets the value of the element at the specified position. + * @example + * const val = container.getElementByPos(-1); // throw a RangeError + */ + abstract getElementByPos(pos: number): T; + /** + * @description Removes the element at the specified position. + * @param pos - The element's position you want to remove. + * @returns The container length after erasing. + * @example + * container.eraseElementByPos(-1); // throw a RangeError + */ + abstract eraseElementByPos(pos: number): number; + /** + * @description Removes element by iterator and move `iter` to next. + * @param iter - The iterator you want to erase. + * @returns The next iterator. + * @example + * container.eraseElementByIterator(container.begin()); + * container.eraseElementByIterator(container.end()); // throw a RangeError + */ + abstract eraseElementByIterator(iter: ContainerIterator): ContainerIterator; + /** + * @description Using for `for...of` syntax like Array. + * @example + * for (const element of container) { + * console.log(element); + * } + */ + abstract [Symbol.iterator](): Generator; +} +/** + * @description The initial data type passed in when initializing the container. + */ +type initContainer = { + size?: number | (() => number); + length?: number; + forEach: (callback: (el: T) => void) => void; +}; +declare abstract class TreeIterator extends ContainerIterator { + abstract readonly container: TreeContainer; + /** + * @description Get the sequential index of the iterator in the tree container.
+ * Note: + * This function only takes effect when the specified tree container `enableIndex = true`. + * @returns The index subscript of the node in the tree. + * @example + * const st = new OrderedSet([1, 2, 3], true); + * console.log(st.begin().next().index); // 1 + */ + get index(): number; + isAccessible(): boolean; + // @ts-ignore + pre(): this; + // @ts-ignore + next(): this; +} +declare const enum TreeNodeColor { + RED = 1, + BLACK = 0 +} +declare class TreeNode { + _color: TreeNodeColor; + _key: K | undefined; + _value: V | undefined; + _left: TreeNode | undefined; + _right: TreeNode | undefined; + _parent: TreeNode | undefined; + constructor(key?: K, value?: V, color?: TreeNodeColor); + /** + * @description Get the pre node. + * @returns TreeNode about the pre node. + */ + _pre(): TreeNode; + /** + * @description Get the next node. + * @returns TreeNode about the next node. + */ + _next(): TreeNode; + /** + * @description Rotate left. + * @returns TreeNode about moved to original position after rotation. + */ + _rotateLeft(): TreeNode; + /** + * @description Rotate right. + * @returns TreeNode about moved to original position after rotation. + */ + _rotateRight(): TreeNode; +} +declare abstract class TreeContainer extends Container { + enableIndex: boolean; + protected _inOrderTraversal(): TreeNode[]; + protected _inOrderTraversal(pos: number): TreeNode; + protected _inOrderTraversal(callback: (node: TreeNode, index: number, map: this) => void): TreeNode; + clear(): void; + /** + * @description Update node's key by iterator. + * @param iter - The iterator you want to change. + * @param key - The key you want to update. + * @returns Whether the modification is successful. + * @example + * const st = new orderedSet([1, 2, 5]); + * const iter = st.find(2); + * st.updateKeyByIterator(iter, 3); // then st will become [1, 3, 5] + */ + updateKeyByIterator(iter: TreeIterator, key: K): boolean; + eraseElementByPos(pos: number): number; + /** + * @description Remove the element of the specified key. + * @param key - The key you want to remove. + * @returns Whether erase successfully. + */ + eraseElementByKey(key: K): boolean; + eraseElementByIterator(iter: TreeIterator): TreeIterator; + /** + * @description Get the height of the tree. + * @returns Number about the height of the RB-tree. + */ + getHeight(): number; + /** + * @param key - The given key you want to compare. + * @returns An iterator to the first element less than the given key. + */ + abstract reverseUpperBound(key: K): TreeIterator; + /** + * @description Union the other tree to self. + * @param other - The other tree container you want to merge. + * @returns The size of the tree after union. + */ + abstract union(other: TreeContainer): number; + /** + * @param key - The given key you want to compare. + * @returns An iterator to the first element not greater than the given key. + */ + abstract reverseLowerBound(key: K): TreeIterator; + /** + * @param key - The given key you want to compare. + * @returns An iterator to the first element not less than the given key. + */ + abstract lowerBound(key: K): TreeIterator; + /** + * @param key - The given key you want to compare. + * @returns An iterator to the first element greater than the given key. + */ + abstract upperBound(key: K): TreeIterator; +} +declare class OrderedMapIterator extends TreeIterator { + container: OrderedMap; + constructor(node: TreeNode, header: TreeNode, container: OrderedMap, iteratorType?: IteratorType); + get pointer(): [ + K, + V + ]; + copy(): OrderedMapIterator; + // @ts-ignore + equals(iter: OrderedMapIterator): boolean; +} +declare class OrderedMap extends TreeContainer { + /** + * @param container - The initialization container. + * @param cmp - The compare function. + * @param enableIndex - Whether to enable iterator indexing function. + * @example + * new OrderedMap(); + * new OrderedMap([[0, 1], [2, 1]]); + * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y); + * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y, true); + */ + constructor(container?: initContainer<[ + K, + V + ]>, cmp?: (x: K, y: K) => number, enableIndex?: boolean); + begin(): OrderedMapIterator; + end(): OrderedMapIterator; + rBegin(): OrderedMapIterator; + rEnd(): OrderedMapIterator; + front(): [ + K, + V + ] | undefined; + back(): [ + K, + V + ] | undefined; + lowerBound(key: K): OrderedMapIterator; + upperBound(key: K): OrderedMapIterator; + reverseLowerBound(key: K): OrderedMapIterator; + reverseUpperBound(key: K): OrderedMapIterator; + forEach(callback: (element: [ + K, + V + ], index: number, map: OrderedMap) => void): void; + /** + * @description Insert a key-value pair or set value by the given key. + * @param key - The key want to insert. + * @param value - The value want to set. + * @param hint - You can give an iterator hint to improve insertion efficiency. + * @return The size of container after setting. + * @example + * const mp = new OrderedMap([[2, 0], [4, 0], [5, 0]]); + * const iter = mp.begin(); + * mp.setElement(1, 0); + * mp.setElement(3, 0, iter); // give a hint will be faster. + */ + setElement(key: K, value: V, hint?: OrderedMapIterator): number; + getElementByPos(pos: number): [ + K, + V + ]; + find(key: K): OrderedMapIterator; + /** + * @description Get the value of the element of the specified key. + * @param key - The specified key you want to get. + * @example + * const val = container.getElementByKey(1); + */ + getElementByKey(key: K): V | undefined; + union(other: OrderedMap): number; + [Symbol.iterator](): Generator<[ + K, + V + ], void, unknown>; + // @ts-ignore + eraseElementByIterator(iter: OrderedMapIterator): OrderedMapIterator; +} +export { OrderedMap }; +export type { OrderedMapIterator, IteratorType, Container, ContainerIterator, TreeContainer }; diff --git a/node_modules/@js-sdsl/ordered-map/dist/cjs/index.js b/node_modules/@js-sdsl/ordered-map/dist/cjs/index.js new file mode 100644 index 0000000..575a7fa --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/dist/cjs/index.js @@ -0,0 +1,795 @@ +"use strict"; + +Object.defineProperty(exports, "t", { + value: true +}); + +class TreeNode { + constructor(t, e, s = 1) { + this.i = undefined; + this.h = undefined; + this.o = undefined; + this.u = t; + this.l = e; + this.p = s; + } + I() { + let t = this; + const e = t.o.o === t; + if (e && t.p === 1) { + t = t.h; + } else if (t.i) { + t = t.i; + while (t.h) { + t = t.h; + } + } else { + if (e) { + return t.o; + } + let s = t.o; + while (s.i === t) { + t = s; + s = t.o; + } + t = s; + } + return t; + } + B() { + let t = this; + if (t.h) { + t = t.h; + while (t.i) { + t = t.i; + } + return t; + } else { + let e = t.o; + while (e.h === t) { + t = e; + e = t.o; + } + if (t.h !== e) { + return e; + } else return t; + } + } + _() { + const t = this.o; + const e = this.h; + const s = e.i; + if (t.o === this) t.o = e; else if (t.i === this) t.i = e; else t.h = e; + e.o = t; + e.i = this; + this.o = e; + this.h = s; + if (s) s.o = this; + return e; + } + g() { + const t = this.o; + const e = this.i; + const s = e.h; + if (t.o === this) t.o = e; else if (t.i === this) t.i = e; else t.h = e; + e.o = t; + e.h = this; + this.o = e; + this.i = s; + if (s) s.o = this; + return e; + } +} + +class TreeNodeEnableIndex extends TreeNode { + constructor() { + super(...arguments); + this.M = 1; + } + _() { + const t = super._(); + this.O(); + t.O(); + return t; + } + g() { + const t = super.g(); + this.O(); + t.O(); + return t; + } + O() { + this.M = 1; + if (this.i) { + this.M += this.i.M; + } + if (this.h) { + this.M += this.h.M; + } + } +} + +class ContainerIterator { + constructor(t = 0) { + this.iteratorType = t; + } + equals(t) { + return this.T === t.T; + } +} + +class Base { + constructor() { + this.m = 0; + } + get length() { + return this.m; + } + size() { + return this.m; + } + empty() { + return this.m === 0; + } +} + +class Container extends Base {} + +function throwIteratorAccessError() { + throw new RangeError("Iterator access denied!"); +} + +class TreeContainer extends Container { + constructor(t = function(t, e) { + if (t < e) return -1; + if (t > e) return 1; + return 0; + }, e = false) { + super(); + this.v = undefined; + this.A = t; + this.enableIndex = e; + this.N = e ? TreeNodeEnableIndex : TreeNode; + this.C = new this.N; + } + R(t, e) { + let s = this.C; + while (t) { + const i = this.A(t.u, e); + if (i < 0) { + t = t.h; + } else if (i > 0) { + s = t; + t = t.i; + } else return t; + } + return s; + } + K(t, e) { + let s = this.C; + while (t) { + const i = this.A(t.u, e); + if (i <= 0) { + t = t.h; + } else { + s = t; + t = t.i; + } + } + return s; + } + L(t, e) { + let s = this.C; + while (t) { + const i = this.A(t.u, e); + if (i < 0) { + s = t; + t = t.h; + } else if (i > 0) { + t = t.i; + } else return t; + } + return s; + } + k(t, e) { + let s = this.C; + while (t) { + const i = this.A(t.u, e); + if (i < 0) { + s = t; + t = t.h; + } else { + t = t.i; + } + } + return s; + } + P(t) { + while (true) { + const e = t.o; + if (e === this.C) return; + if (t.p === 1) { + t.p = 0; + return; + } + if (t === e.i) { + const s = e.h; + if (s.p === 1) { + s.p = 0; + e.p = 1; + if (e === this.v) { + this.v = e._(); + } else e._(); + } else { + if (s.h && s.h.p === 1) { + s.p = e.p; + e.p = 0; + s.h.p = 0; + if (e === this.v) { + this.v = e._(); + } else e._(); + return; + } else if (s.i && s.i.p === 1) { + s.p = 1; + s.i.p = 0; + s.g(); + } else { + s.p = 1; + t = e; + } + } + } else { + const s = e.i; + if (s.p === 1) { + s.p = 0; + e.p = 1; + if (e === this.v) { + this.v = e.g(); + } else e.g(); + } else { + if (s.i && s.i.p === 1) { + s.p = e.p; + e.p = 0; + s.i.p = 0; + if (e === this.v) { + this.v = e.g(); + } else e.g(); + return; + } else if (s.h && s.h.p === 1) { + s.p = 1; + s.h.p = 0; + s._(); + } else { + s.p = 1; + t = e; + } + } + } + } + } + S(t) { + if (this.m === 1) { + this.clear(); + return; + } + let e = t; + while (e.i || e.h) { + if (e.h) { + e = e.h; + while (e.i) e = e.i; + } else { + e = e.i; + } + const s = t.u; + t.u = e.u; + e.u = s; + const i = t.l; + t.l = e.l; + e.l = i; + t = e; + } + if (this.C.i === e) { + this.C.i = e.o; + } else if (this.C.h === e) { + this.C.h = e.o; + } + this.P(e); + let s = e.o; + if (e === s.i) { + s.i = undefined; + } else s.h = undefined; + this.m -= 1; + this.v.p = 0; + if (this.enableIndex) { + while (s !== this.C) { + s.M -= 1; + s = s.o; + } + } + } + U(t) { + const e = typeof t === "number" ? t : undefined; + const s = typeof t === "function" ? t : undefined; + const i = typeof t === "undefined" ? [] : undefined; + let r = 0; + let n = this.v; + const h = []; + while (h.length || n) { + if (n) { + h.push(n); + n = n.i; + } else { + n = h.pop(); + if (r === e) return n; + i && i.push(n); + s && s(n, r, this); + r += 1; + n = n.h; + } + } + return i; + } + j(t) { + while (true) { + const e = t.o; + if (e.p === 0) return; + const s = e.o; + if (e === s.i) { + const i = s.h; + if (i && i.p === 1) { + i.p = e.p = 0; + if (s === this.v) return; + s.p = 1; + t = s; + continue; + } else if (t === e.h) { + t.p = 0; + if (t.i) { + t.i.o = e; + } + if (t.h) { + t.h.o = s; + } + e.h = t.i; + s.i = t.h; + t.i = e; + t.h = s; + if (s === this.v) { + this.v = t; + this.C.o = t; + } else { + const e = s.o; + if (e.i === s) { + e.i = t; + } else e.h = t; + } + t.o = s.o; + e.o = t; + s.o = t; + s.p = 1; + } else { + e.p = 0; + if (s === this.v) { + this.v = s.g(); + } else s.g(); + s.p = 1; + return; + } + } else { + const i = s.i; + if (i && i.p === 1) { + i.p = e.p = 0; + if (s === this.v) return; + s.p = 1; + t = s; + continue; + } else if (t === e.i) { + t.p = 0; + if (t.i) { + t.i.o = s; + } + if (t.h) { + t.h.o = e; + } + s.h = t.i; + e.i = t.h; + t.i = s; + t.h = e; + if (s === this.v) { + this.v = t; + this.C.o = t; + } else { + const e = s.o; + if (e.i === s) { + e.i = t; + } else e.h = t; + } + t.o = s.o; + e.o = t; + s.o = t; + s.p = 1; + } else { + e.p = 0; + if (s === this.v) { + this.v = s._(); + } else s._(); + s.p = 1; + return; + } + } + if (this.enableIndex) { + e.O(); + s.O(); + t.O(); + } + return; + } + } + q(t, e, s) { + if (this.v === undefined) { + this.m += 1; + this.v = new this.N(t, e, 0); + this.v.o = this.C; + this.C.o = this.C.i = this.C.h = this.v; + return this.m; + } + let i; + const r = this.C.i; + const n = this.A(r.u, t); + if (n === 0) { + r.l = e; + return this.m; + } else if (n > 0) { + r.i = new this.N(t, e); + r.i.o = r; + i = r.i; + this.C.i = i; + } else { + const r = this.C.h; + const n = this.A(r.u, t); + if (n === 0) { + r.l = e; + return this.m; + } else if (n < 0) { + r.h = new this.N(t, e); + r.h.o = r; + i = r.h; + this.C.h = i; + } else { + if (s !== undefined) { + const r = s.T; + if (r !== this.C) { + const s = this.A(r.u, t); + if (s === 0) { + r.l = e; + return this.m; + } else if (s > 0) { + const s = r.I(); + const n = this.A(s.u, t); + if (n === 0) { + s.l = e; + return this.m; + } else if (n < 0) { + i = new this.N(t, e); + if (s.h === undefined) { + s.h = i; + i.o = s; + } else { + r.i = i; + i.o = r; + } + } + } + } + } + if (i === undefined) { + i = this.v; + while (true) { + const s = this.A(i.u, t); + if (s > 0) { + if (i.i === undefined) { + i.i = new this.N(t, e); + i.i.o = i; + i = i.i; + break; + } + i = i.i; + } else if (s < 0) { + if (i.h === undefined) { + i.h = new this.N(t, e); + i.h.o = i; + i = i.h; + break; + } + i = i.h; + } else { + i.l = e; + return this.m; + } + } + } + } + } + if (this.enableIndex) { + let t = i.o; + while (t !== this.C) { + t.M += 1; + t = t.o; + } + } + this.j(i); + this.m += 1; + return this.m; + } + H(t, e) { + while (t) { + const s = this.A(t.u, e); + if (s < 0) { + t = t.h; + } else if (s > 0) { + t = t.i; + } else return t; + } + return t || this.C; + } + clear() { + this.m = 0; + this.v = undefined; + this.C.o = undefined; + this.C.i = this.C.h = undefined; + } + updateKeyByIterator(t, e) { + const s = t.T; + if (s === this.C) { + throwIteratorAccessError(); + } + if (this.m === 1) { + s.u = e; + return true; + } + const i = s.B().u; + if (s === this.C.i) { + if (this.A(i, e) > 0) { + s.u = e; + return true; + } + return false; + } + const r = s.I().u; + if (s === this.C.h) { + if (this.A(r, e) < 0) { + s.u = e; + return true; + } + return false; + } + if (this.A(r, e) >= 0 || this.A(i, e) <= 0) return false; + s.u = e; + return true; + } + eraseElementByPos(t) { + if (t < 0 || t > this.m - 1) { + throw new RangeError; + } + const e = this.U(t); + this.S(e); + return this.m; + } + eraseElementByKey(t) { + if (this.m === 0) return false; + const e = this.H(this.v, t); + if (e === this.C) return false; + this.S(e); + return true; + } + eraseElementByIterator(t) { + const e = t.T; + if (e === this.C) { + throwIteratorAccessError(); + } + const s = e.h === undefined; + const i = t.iteratorType === 0; + if (i) { + if (s) t.next(); + } else { + if (!s || e.i === undefined) t.next(); + } + this.S(e); + return t; + } + getHeight() { + if (this.m === 0) return 0; + function traversal(t) { + if (!t) return 0; + return Math.max(traversal(t.i), traversal(t.h)) + 1; + } + return traversal(this.v); + } +} + +class TreeIterator extends ContainerIterator { + constructor(t, e, s) { + super(s); + this.T = t; + this.C = e; + if (this.iteratorType === 0) { + this.pre = function() { + if (this.T === this.C.i) { + throwIteratorAccessError(); + } + this.T = this.T.I(); + return this; + }; + this.next = function() { + if (this.T === this.C) { + throwIteratorAccessError(); + } + this.T = this.T.B(); + return this; + }; + } else { + this.pre = function() { + if (this.T === this.C.h) { + throwIteratorAccessError(); + } + this.T = this.T.B(); + return this; + }; + this.next = function() { + if (this.T === this.C) { + throwIteratorAccessError(); + } + this.T = this.T.I(); + return this; + }; + } + } + get index() { + let t = this.T; + const e = this.C.o; + if (t === this.C) { + if (e) { + return e.M - 1; + } + return 0; + } + let s = 0; + if (t.i) { + s += t.i.M; + } + while (t !== e) { + const e = t.o; + if (t === e.h) { + s += 1; + if (e.i) { + s += e.i.M; + } + } + t = e; + } + return s; + } + isAccessible() { + return this.T !== this.C; + } +} + +class OrderedMapIterator extends TreeIterator { + constructor(t, e, s, i) { + super(t, e, i); + this.container = s; + } + get pointer() { + if (this.T === this.C) { + throwIteratorAccessError(); + } + const t = this; + return new Proxy([], { + get(e, s) { + if (s === "0") return t.T.u; else if (s === "1") return t.T.l; + e[0] = t.T.u; + e[1] = t.T.l; + return e[s]; + }, + set(e, s, i) { + if (s !== "1") { + throw new TypeError("prop must be 1"); + } + t.T.l = i; + return true; + } + }); + } + copy() { + return new OrderedMapIterator(this.T, this.C, this.container, this.iteratorType); + } +} + +class OrderedMap extends TreeContainer { + constructor(t = [], e, s) { + super(e, s); + const i = this; + t.forEach((function(t) { + i.setElement(t[0], t[1]); + })); + } + begin() { + return new OrderedMapIterator(this.C.i || this.C, this.C, this); + } + end() { + return new OrderedMapIterator(this.C, this.C, this); + } + rBegin() { + return new OrderedMapIterator(this.C.h || this.C, this.C, this, 1); + } + rEnd() { + return new OrderedMapIterator(this.C, this.C, this, 1); + } + front() { + if (this.m === 0) return; + const t = this.C.i; + return [ t.u, t.l ]; + } + back() { + if (this.m === 0) return; + const t = this.C.h; + return [ t.u, t.l ]; + } + lowerBound(t) { + const e = this.R(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + upperBound(t) { + const e = this.K(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + reverseLowerBound(t) { + const e = this.L(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + reverseUpperBound(t) { + const e = this.k(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + forEach(t) { + this.U((function(e, s, i) { + t([ e.u, e.l ], s, i); + })); + } + setElement(t, e, s) { + return this.q(t, e, s); + } + getElementByPos(t) { + if (t < 0 || t > this.m - 1) { + throw new RangeError; + } + const e = this.U(t); + return [ e.u, e.l ]; + } + find(t) { + const e = this.H(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + getElementByKey(t) { + const e = this.H(this.v, t); + return e.l; + } + union(t) { + const e = this; + t.forEach((function(t) { + e.setElement(t[0], t[1]); + })); + return this.m; + } + * [Symbol.iterator]() { + const t = this.m; + const e = this.U(); + for (let s = 0; s < t; ++s) { + const t = e[s]; + yield [ t.u, t.l ]; + } + } +} + +exports.OrderedMap = OrderedMap; +//# sourceMappingURL=index.js.map diff --git a/node_modules/@js-sdsl/ordered-map/dist/cjs/index.js.map b/node_modules/@js-sdsl/ordered-map/dist/cjs/index.js.map new file mode 100644 index 0000000..36400a9 --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/dist/cjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["index.js","../../../.build-data/copied-source/src/container/TreeContainer/Base/TreeNode.ts","../../../.build-data/copied-source/src/container/ContainerBase/index.ts","../../../.build-data/copied-source/src/utils/throwError.ts","../../../.build-data/copied-source/src/container/TreeContainer/Base/index.ts","../../../.build-data/copied-source/src/container/TreeContainer/Base/TreeIterator.ts","../../../.build-data/copied-source/src/container/TreeContainer/OrderedMap.ts"],"names":["Object","defineProperty","exports","value","TreeNode","constructor","key","color","this","_left","undefined","_right","_parent","_key","_value","_color","_pre","preNode","isRootOrHeader","pre","_next","nextNode","_rotateLeft","PP","V","R","_rotateRight","F","K","TreeNodeEnableIndex","super","arguments","_subTreeSize","parent","_recount","ContainerIterator","iteratorType","equals","iter","_node","Base","_length","length","size","empty","Container","throwIteratorAccessError","RangeError","TreeContainer","cmp","x","y","enableIndex","_root","_cmp","_TreeNodeClass","_header","_lowerBound","curNode","resNode","cmpResult","_upperBound","_reverseLowerBound","_reverseUpperBound","_eraseNodeSelfBalance","parentNode","brother","_eraseNode","clear","swapNode","_inOrderTraversal","param","pos","callback","nodeList","index","stack","push","pop","_insertNodeSelfBalance","grandParent","uncle","GP","_set","hint","minNode","compareToMin","maxNode","compareToMax","iterNode","iterCmpRes","preCmpRes","_getTreeNodeByKey","updateKeyByIterator","node","nextKey","preKey","eraseElementByPos","eraseElementByKey","eraseElementByIterator","hasNoRight","isNormal","next","getHeight","traversal","Math","max","TreeIterator","header","root","isAccessible","OrderedMapIterator","container","pointer","self","Proxy","get","target","prop","set","_","newValue","TypeError","copy","OrderedMap","forEach","el","setElement","begin","end","rBegin","rEnd","front","back","lowerBound","upperBound","reverseLowerBound","reverseUpperBound","map","getElementByPos","find","getElementByKey","union","other","Symbol","iterator","i"],"mappings":"AAAA;;AAEAA,OAAOC,eAAeC,SAAS,KAAc;IAAEC,OAAO;;;AAEtD,MCCaC;IAOXC,WAAAA,CACEC,GACAH,GACAI,IAAwC;QAN1CC,KAAKC,IAA+BC;QACpCF,KAAMG,IAA+BD;QACrCF,KAAOI,IAA+BF;QAMpCF,KAAKK,IAAOP;QACZE,KAAKM,IAASX;QACdK,KAAKO,IAASR;AACf;IAKDS,CAAAA;QACE,IAAIC,IAA0BT;QAC9B,MAAMU,IAAiBD,EAAQL,EAASA,MAAYK;QACpD,IAAIC,KAAkBD,EAAQF,MAAM,GAAwB;YAC1DE,IAAUA,EAAQN;AACnB,eAAM,IAAIM,EAAQR,GAAO;YACxBQ,IAAUA,EAAQR;YAClB,OAAOQ,EAAQN,GAAQ;gBACrBM,IAAUA,EAAQN;AACnB;AACF,eAAM;YAEL,IAAIO,GAAgB;gBAClB,OAAOD,EAAQL;AAChB;YACD,IAAIO,IAAMF,EAA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AAKhF;AAChC;AACF;;;ANwwBHZ,QAAQ0H,aAAaA","file":"index.js","sourcesContent":["'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nclass TreeNode {\n constructor(key, value, color = 1 /* TreeNodeColor.RED */) {\n this._left = undefined;\n this._right = undefined;\n this._parent = undefined;\n this._key = key;\n this._value = value;\n this._color = color;\n }\n /**\n * @description Get the pre node.\n * @returns TreeNode about the pre node.\n */\n _pre() {\n let preNode = this;\n const isRootOrHeader = preNode._parent._parent === preNode;\n if (isRootOrHeader && preNode._color === 1 /* TreeNodeColor.RED */) {\n preNode = preNode._right;\n } else if (preNode._left) {\n preNode = preNode._left;\n while (preNode._right) {\n preNode = preNode._right;\n }\n } else {\n // Must be root and left is null\n if (isRootOrHeader) {\n return preNode._parent;\n }\n let pre = preNode._parent;\n while (pre._left === preNode) {\n preNode = pre;\n pre = preNode._parent;\n }\n preNode = pre;\n }\n return preNode;\n }\n /**\n * @description Get the next node.\n * @returns TreeNode about the next node.\n */\n _next() {\n let nextNode = this;\n if (nextNode._right) {\n nextNode = nextNode._right;\n while (nextNode._left) {\n nextNode = nextNode._left;\n }\n return nextNode;\n } else {\n let pre = nextNode._parent;\n while (pre._right === nextNode) {\n nextNode = pre;\n pre = nextNode._parent;\n }\n if (nextNode._right !== pre) {\n return pre;\n } else return nextNode;\n }\n }\n /**\n * @description Rotate left.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateLeft() {\n const PP = this._parent;\n const V = this._right;\n const R = V._left;\n if (PP._parent === this) PP._parent = V;else if (PP._left === this) PP._left = V;else PP._right = V;\n V._parent = PP;\n V._left = this;\n this._parent = V;\n this._right = R;\n if (R) R._parent = this;\n return V;\n }\n /**\n * @description Rotate right.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateRight() {\n const PP = this._parent;\n const F = this._left;\n const K = F._right;\n if (PP._parent === this) PP._parent = F;else if (PP._left === this) PP._left = F;else PP._right = F;\n F._parent = PP;\n F._right = this;\n this._parent = F;\n this._left = K;\n if (K) K._parent = this;\n return F;\n }\n}\nclass TreeNodeEnableIndex extends TreeNode {\n constructor() {\n super(...arguments);\n this._subTreeSize = 1;\n }\n /**\n * @description Rotate left and do recount.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateLeft() {\n const parent = super._rotateLeft();\n this._recount();\n parent._recount();\n return parent;\n }\n /**\n * @description Rotate right and do recount.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateRight() {\n const parent = super._rotateRight();\n this._recount();\n parent._recount();\n return parent;\n }\n _recount() {\n this._subTreeSize = 1;\n if (this._left) {\n this._subTreeSize += this._left._subTreeSize;\n }\n if (this._right) {\n this._subTreeSize += this._right._subTreeSize;\n }\n }\n}\n\nclass ContainerIterator {\n /**\n * @internal\n */\n constructor(iteratorType = 0 /* IteratorType.NORMAL */) {\n this.iteratorType = iteratorType;\n }\n /**\n * @param iter - The other iterator you want to compare.\n * @returns Whether this equals to obj.\n * @example\n * container.find(1).equals(container.end());\n */\n equals(iter) {\n return this._node === iter._node;\n }\n}\nclass Base {\n constructor() {\n /**\n * @description Container's size.\n * @internal\n */\n this._length = 0;\n }\n /**\n * @returns The size of the container.\n * @example\n * const container = new Vector([1, 2]);\n * console.log(container.length); // 2\n */\n get length() {\n return this._length;\n }\n /**\n * @returns The size of the container.\n * @example\n * const container = new Vector([1, 2]);\n * console.log(container.size()); // 2\n */\n size() {\n return this._length;\n }\n /**\n * @returns Whether the container is empty.\n * @example\n * container.clear();\n * console.log(container.empty()); // true\n */\n empty() {\n return this._length === 0;\n }\n}\nclass Container extends Base {}\n\n/**\n * @description Throw an iterator access error.\n * @internal\n */\nfunction throwIteratorAccessError() {\n throw new RangeError('Iterator access denied!');\n}\n\nclass TreeContainer extends Container {\n /**\n * @internal\n */\n constructor(cmp = function (x, y) {\n if (x < y) return -1;\n if (x > y) return 1;\n return 0;\n }, enableIndex = false) {\n super();\n /**\n * @internal\n */\n this._root = undefined;\n this._cmp = cmp;\n this.enableIndex = enableIndex;\n this._TreeNodeClass = enableIndex ? TreeNodeEnableIndex : TreeNode;\n this._header = new this._TreeNodeClass();\n }\n /**\n * @internal\n */\n _lowerBound(curNode, key) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key, key);\n if (cmpResult < 0) {\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n resNode = curNode;\n curNode = curNode._left;\n } else return curNode;\n }\n return resNode;\n }\n /**\n * @internal\n */\n _upperBound(curNode, key) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key, key);\n if (cmpResult <= 0) {\n curNode = curNode._right;\n } else {\n resNode = curNode;\n curNode = curNode._left;\n }\n }\n return resNode;\n }\n /**\n * @internal\n */\n _reverseLowerBound(curNode, key) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key, key);\n if (cmpResult < 0) {\n resNode = curNode;\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n curNode = curNode._left;\n } else return curNode;\n }\n return resNode;\n }\n /**\n * @internal\n */\n _reverseUpperBound(curNode, key) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key, key);\n if (cmpResult < 0) {\n resNode = curNode;\n curNode = curNode._right;\n } else {\n curNode = curNode._left;\n }\n }\n return resNode;\n }\n /**\n * @internal\n */\n _eraseNodeSelfBalance(curNode) {\n while (true) {\n const parentNode = curNode._parent;\n if (parentNode === this._header) return;\n if (curNode._color === 1 /* TreeNodeColor.RED */) {\n curNode._color = 0 /* TreeNodeColor.BLACK */;\n return;\n }\n if (curNode === parentNode._left) {\n const brother = parentNode._right;\n if (brother._color === 1 /* TreeNodeColor.RED */) {\n brother._color = 0 /* TreeNodeColor.BLACK */;\n parentNode._color = 1 /* TreeNodeColor.RED */;\n if (parentNode === this._root) {\n this._root = parentNode._rotateLeft();\n } else parentNode._rotateLeft();\n } else {\n if (brother._right && brother._right._color === 1 /* TreeNodeColor.RED */) {\n brother._color = parentNode._color;\n parentNode._color = 0 /* TreeNodeColor.BLACK */;\n brother._right._color = 0 /* TreeNodeColor.BLACK */;\n if (parentNode === this._root) {\n this._root = parentNode._rotateLeft();\n } else parentNode._rotateLeft();\n return;\n } else if (brother._left && brother._left._color === 1 /* TreeNodeColor.RED */) {\n brother._color = 1 /* TreeNodeColor.RED */;\n brother._left._color = 0 /* TreeNodeColor.BLACK */;\n brother._rotateRight();\n } else {\n brother._color = 1 /* TreeNodeColor.RED */;\n curNode = parentNode;\n }\n }\n } else {\n const brother = parentNode._left;\n if (brother._color === 1 /* TreeNodeColor.RED */) {\n brother._color = 0 /* TreeNodeColor.BLACK */;\n parentNode._color = 1 /* TreeNodeColor.RED */;\n if (parentNode === this._root) {\n this._root = parentNode._rotateRight();\n } else parentNode._rotateRight();\n } else {\n if (brother._left && brother._left._color === 1 /* TreeNodeColor.RED */) {\n brother._color = parentNode._color;\n parentNode._color = 0 /* TreeNodeColor.BLACK */;\n brother._left._color = 0 /* TreeNodeColor.BLACK */;\n if (parentNode === this._root) {\n this._root = parentNode._rotateRight();\n } else parentNode._rotateRight();\n return;\n } else if (brother._right && brother._right._color === 1 /* TreeNodeColor.RED */) {\n brother._color = 1 /* TreeNodeColor.RED */;\n brother._right._color = 0 /* TreeNodeColor.BLACK */;\n brother._rotateLeft();\n } else {\n brother._color = 1 /* TreeNodeColor.RED */;\n curNode = parentNode;\n }\n }\n }\n }\n }\n /**\n * @internal\n */\n _eraseNode(curNode) {\n if (this._length === 1) {\n this.clear();\n return;\n }\n let swapNode = curNode;\n while (swapNode._left || swapNode._right) {\n if (swapNode._right) {\n swapNode = swapNode._right;\n while (swapNode._left) swapNode = swapNode._left;\n } else {\n swapNode = swapNode._left;\n }\n const key = curNode._key;\n curNode._key = swapNode._key;\n swapNode._key = key;\n const value = curNode._value;\n curNode._value = swapNode._value;\n swapNode._value = value;\n curNode = swapNode;\n }\n if (this._header._left === swapNode) {\n this._header._left = swapNode._parent;\n } else if (this._header._right === swapNode) {\n this._header._right = swapNode._parent;\n }\n this._eraseNodeSelfBalance(swapNode);\n let _parent = swapNode._parent;\n if (swapNode === _parent._left) {\n _parent._left = undefined;\n } else _parent._right = undefined;\n this._length -= 1;\n this._root._color = 0 /* TreeNodeColor.BLACK */;\n if (this.enableIndex) {\n while (_parent !== this._header) {\n _parent._subTreeSize -= 1;\n _parent = _parent._parent;\n }\n }\n }\n /**\n * @internal\n */\n _inOrderTraversal(param) {\n const pos = typeof param === 'number' ? param : undefined;\n const callback = typeof param === 'function' ? param : undefined;\n const nodeList = typeof param === 'undefined' ? [] : undefined;\n let index = 0;\n let curNode = this._root;\n const stack = [];\n while (stack.length || curNode) {\n if (curNode) {\n stack.push(curNode);\n curNode = curNode._left;\n } else {\n curNode = stack.pop();\n if (index === pos) return curNode;\n nodeList && nodeList.push(curNode);\n callback && callback(curNode, index, this);\n index += 1;\n curNode = curNode._right;\n }\n }\n return nodeList;\n }\n /**\n * @internal\n */\n _insertNodeSelfBalance(curNode) {\n while (true) {\n const parentNode = curNode._parent;\n if (parentNode._color === 0 /* TreeNodeColor.BLACK */) return;\n const grandParent = parentNode._parent;\n if (parentNode === grandParent._left) {\n const uncle = grandParent._right;\n if (uncle && uncle._color === 1 /* TreeNodeColor.RED */) {\n uncle._color = parentNode._color = 0 /* TreeNodeColor.BLACK */;\n if (grandParent === this._root) return;\n grandParent._color = 1 /* TreeNodeColor.RED */;\n curNode = grandParent;\n continue;\n } else if (curNode === parentNode._right) {\n curNode._color = 0 /* TreeNodeColor.BLACK */;\n if (curNode._left) {\n curNode._left._parent = parentNode;\n }\n if (curNode._right) {\n curNode._right._parent = grandParent;\n }\n parentNode._right = curNode._left;\n grandParent._left = curNode._right;\n curNode._left = parentNode;\n curNode._right = grandParent;\n if (grandParent === this._root) {\n this._root = curNode;\n this._header._parent = curNode;\n } else {\n const GP = grandParent._parent;\n if (GP._left === grandParent) {\n GP._left = curNode;\n } else GP._right = curNode;\n }\n curNode._parent = grandParent._parent;\n parentNode._parent = curNode;\n grandParent._parent = curNode;\n grandParent._color = 1 /* TreeNodeColor.RED */;\n } else {\n parentNode._color = 0 /* TreeNodeColor.BLACK */;\n if (grandParent === this._root) {\n this._root = grandParent._rotateRight();\n } else grandParent._rotateRight();\n grandParent._color = 1 /* TreeNodeColor.RED */;\n return;\n }\n } else {\n const uncle = grandParent._left;\n if (uncle && uncle._color === 1 /* TreeNodeColor.RED */) {\n uncle._color = parentNode._color = 0 /* TreeNodeColor.BLACK */;\n if (grandParent === this._root) return;\n grandParent._color = 1 /* TreeNodeColor.RED */;\n curNode = grandParent;\n continue;\n } else if (curNode === parentNode._left) {\n curNode._color = 0 /* TreeNodeColor.BLACK */;\n if (curNode._left) {\n curNode._left._parent = grandParent;\n }\n if (curNode._right) {\n curNode._right._parent = parentNode;\n }\n grandParent._right = curNode._left;\n parentNode._left = curNode._right;\n curNode._left = grandParent;\n curNode._right = parentNode;\n if (grandParent === this._root) {\n this._root = curNode;\n this._header._parent = curNode;\n } else {\n const GP = grandParent._parent;\n if (GP._left === grandParent) {\n GP._left = curNode;\n } else GP._right = curNode;\n }\n curNode._parent = grandParent._parent;\n parentNode._parent = curNode;\n grandParent._parent = curNode;\n grandParent._color = 1 /* TreeNodeColor.RED */;\n } else {\n parentNode._color = 0 /* TreeNodeColor.BLACK */;\n if (grandParent === this._root) {\n this._root = grandParent._rotateLeft();\n } else grandParent._rotateLeft();\n grandParent._color = 1 /* TreeNodeColor.RED */;\n return;\n }\n }\n if (this.enableIndex) {\n parentNode._recount();\n grandParent._recount();\n curNode._recount();\n }\n return;\n }\n }\n /**\n * @internal\n */\n _set(key, value, hint) {\n if (this._root === undefined) {\n this._length += 1;\n this._root = new this._TreeNodeClass(key, value, 0 /* TreeNodeColor.BLACK */);\n this._root._parent = this._header;\n this._header._parent = this._header._left = this._header._right = this._root;\n return this._length;\n }\n let curNode;\n const minNode = this._header._left;\n const compareToMin = this._cmp(minNode._key, key);\n if (compareToMin === 0) {\n minNode._value = value;\n return this._length;\n } else if (compareToMin > 0) {\n minNode._left = new this._TreeNodeClass(key, value);\n minNode._left._parent = minNode;\n curNode = minNode._left;\n this._header._left = curNode;\n } else {\n const maxNode = this._header._right;\n const compareToMax = this._cmp(maxNode._key, key);\n if (compareToMax === 0) {\n maxNode._value = value;\n return this._length;\n } else if (compareToMax < 0) {\n maxNode._right = new this._TreeNodeClass(key, value);\n maxNode._right._parent = maxNode;\n curNode = maxNode._right;\n this._header._right = curNode;\n } else {\n if (hint !== undefined) {\n const iterNode = hint._node;\n if (iterNode !== this._header) {\n const iterCmpRes = this._cmp(iterNode._key, key);\n if (iterCmpRes === 0) {\n iterNode._value = value;\n return this._length;\n } else /* istanbul ignore else */if (iterCmpRes > 0) {\n const preNode = iterNode._pre();\n const preCmpRes = this._cmp(preNode._key, key);\n if (preCmpRes === 0) {\n preNode._value = value;\n return this._length;\n } else if (preCmpRes < 0) {\n curNode = new this._TreeNodeClass(key, value);\n if (preNode._right === undefined) {\n preNode._right = curNode;\n curNode._parent = preNode;\n } else {\n iterNode._left = curNode;\n curNode._parent = iterNode;\n }\n }\n }\n }\n }\n if (curNode === undefined) {\n curNode = this._root;\n while (true) {\n const cmpResult = this._cmp(curNode._key, key);\n if (cmpResult > 0) {\n if (curNode._left === undefined) {\n curNode._left = new this._TreeNodeClass(key, value);\n curNode._left._parent = curNode;\n curNode = curNode._left;\n break;\n }\n curNode = curNode._left;\n } else if (cmpResult < 0) {\n if (curNode._right === undefined) {\n curNode._right = new this._TreeNodeClass(key, value);\n curNode._right._parent = curNode;\n curNode = curNode._right;\n break;\n }\n curNode = curNode._right;\n } else {\n curNode._value = value;\n return this._length;\n }\n }\n }\n }\n }\n if (this.enableIndex) {\n let parent = curNode._parent;\n while (parent !== this._header) {\n parent._subTreeSize += 1;\n parent = parent._parent;\n }\n }\n this._insertNodeSelfBalance(curNode);\n this._length += 1;\n return this._length;\n }\n /**\n * @internal\n */\n _getTreeNodeByKey(curNode, key) {\n while (curNode) {\n const cmpResult = this._cmp(curNode._key, key);\n if (cmpResult < 0) {\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n curNode = curNode._left;\n } else return curNode;\n }\n return curNode || this._header;\n }\n clear() {\n this._length = 0;\n this._root = undefined;\n this._header._parent = undefined;\n this._header._left = this._header._right = undefined;\n }\n /**\n * @description Update node's key by iterator.\n * @param iter - The iterator you want to change.\n * @param key - The key you want to update.\n * @returns Whether the modification is successful.\n * @example\n * const st = new orderedSet([1, 2, 5]);\n * const iter = st.find(2);\n * st.updateKeyByIterator(iter, 3); // then st will become [1, 3, 5]\n */\n updateKeyByIterator(iter, key) {\n const node = iter._node;\n if (node === this._header) {\n throwIteratorAccessError();\n }\n if (this._length === 1) {\n node._key = key;\n return true;\n }\n const nextKey = node._next()._key;\n if (node === this._header._left) {\n if (this._cmp(nextKey, key) > 0) {\n node._key = key;\n return true;\n }\n return false;\n }\n const preKey = node._pre()._key;\n if (node === this._header._right) {\n if (this._cmp(preKey, key) < 0) {\n node._key = key;\n return true;\n }\n return false;\n }\n if (this._cmp(preKey, key) >= 0 || this._cmp(nextKey, key) <= 0) return false;\n node._key = key;\n return true;\n }\n eraseElementByPos(pos) {\n if (pos < 0 || pos > this._length - 1) {\n throw new RangeError();\n }\n const node = this._inOrderTraversal(pos);\n this._eraseNode(node);\n return this._length;\n }\n /**\n * @description Remove the element of the specified key.\n * @param key - The key you want to remove.\n * @returns Whether erase successfully.\n */\n eraseElementByKey(key) {\n if (this._length === 0) return false;\n const curNode = this._getTreeNodeByKey(this._root, key);\n if (curNode === this._header) return false;\n this._eraseNode(curNode);\n return true;\n }\n eraseElementByIterator(iter) {\n const node = iter._node;\n if (node === this._header) {\n throwIteratorAccessError();\n }\n const hasNoRight = node._right === undefined;\n const isNormal = iter.iteratorType === 0 /* IteratorType.NORMAL */;\n // For the normal iterator, the `next` node will be swapped to `this` node when has right.\n if (isNormal) {\n // So we should move it to next when it's right is null.\n if (hasNoRight) iter.next();\n } else {\n // For the reverse iterator, only when it doesn't have right and has left the `next` node will be swapped.\n // So when it has right, or it is a leaf node we should move it to `next`.\n if (!hasNoRight || node._left === undefined) iter.next();\n }\n this._eraseNode(node);\n return iter;\n }\n /**\n * @description Get the height of the tree.\n * @returns Number about the height of the RB-tree.\n */\n getHeight() {\n if (this._length === 0) return 0;\n function traversal(curNode) {\n if (!curNode) return 0;\n return Math.max(traversal(curNode._left), traversal(curNode._right)) + 1;\n }\n return traversal(this._root);\n }\n}\n\nclass TreeIterator extends ContainerIterator {\n /**\n * @internal\n */\n constructor(node, header, iteratorType) {\n super(iteratorType);\n this._node = node;\n this._header = header;\n if (this.iteratorType === 0 /* IteratorType.NORMAL */) {\n this.pre = function () {\n if (this._node === this._header._left) {\n throwIteratorAccessError();\n }\n this._node = this._node._pre();\n return this;\n };\n this.next = function () {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n this._node = this._node._next();\n return this;\n };\n } else {\n this.pre = function () {\n if (this._node === this._header._right) {\n throwIteratorAccessError();\n }\n this._node = this._node._next();\n return this;\n };\n this.next = function () {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n this._node = this._node._pre();\n return this;\n };\n }\n }\n /**\n * @description Get the sequential index of the iterator in the tree container.
\n * Note:\n * This function only takes effect when the specified tree container `enableIndex = true`.\n * @returns The index subscript of the node in the tree.\n * @example\n * const st = new OrderedSet([1, 2, 3], true);\n * console.log(st.begin().next().index); // 1\n */\n get index() {\n let _node = this._node;\n const root = this._header._parent;\n if (_node === this._header) {\n if (root) {\n return root._subTreeSize - 1;\n }\n return 0;\n }\n let index = 0;\n if (_node._left) {\n index += _node._left._subTreeSize;\n }\n while (_node !== root) {\n const _parent = _node._parent;\n if (_node === _parent._right) {\n index += 1;\n if (_parent._left) {\n index += _parent._left._subTreeSize;\n }\n }\n _node = _parent;\n }\n return index;\n }\n isAccessible() {\n return this._node !== this._header;\n }\n}\n\nclass OrderedMapIterator extends TreeIterator {\n constructor(node, header, container, iteratorType) {\n super(node, header, iteratorType);\n this.container = container;\n }\n get pointer() {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n const self = this;\n return new Proxy([], {\n get(target, prop) {\n if (prop === '0') return self._node._key;else if (prop === '1') return self._node._value;\n target[0] = self._node._key;\n target[1] = self._node._value;\n return target[prop];\n },\n set(_, prop, newValue) {\n if (prop !== '1') {\n throw new TypeError('prop must be 1');\n }\n self._node._value = newValue;\n return true;\n }\n });\n }\n copy() {\n return new OrderedMapIterator(this._node, this._header, this.container, this.iteratorType);\n }\n}\nclass OrderedMap extends TreeContainer {\n /**\n * @param container - The initialization container.\n * @param cmp - The compare function.\n * @param enableIndex - Whether to enable iterator indexing function.\n * @example\n * new OrderedMap();\n * new OrderedMap([[0, 1], [2, 1]]);\n * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y);\n * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y, true);\n */\n constructor(container = [], cmp, enableIndex) {\n super(cmp, enableIndex);\n const self = this;\n container.forEach(function (el) {\n self.setElement(el[0], el[1]);\n });\n }\n begin() {\n return new OrderedMapIterator(this._header._left || this._header, this._header, this);\n }\n end() {\n return new OrderedMapIterator(this._header, this._header, this);\n }\n rBegin() {\n return new OrderedMapIterator(this._header._right || this._header, this._header, this, 1 /* IteratorType.REVERSE */);\n }\n\n rEnd() {\n return new OrderedMapIterator(this._header, this._header, this, 1 /* IteratorType.REVERSE */);\n }\n\n front() {\n if (this._length === 0) return;\n const minNode = this._header._left;\n return [minNode._key, minNode._value];\n }\n back() {\n if (this._length === 0) return;\n const maxNode = this._header._right;\n return [maxNode._key, maxNode._value];\n }\n lowerBound(key) {\n const resNode = this._lowerBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n upperBound(key) {\n const resNode = this._upperBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n reverseLowerBound(key) {\n const resNode = this._reverseLowerBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n reverseUpperBound(key) {\n const resNode = this._reverseUpperBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n forEach(callback) {\n this._inOrderTraversal(function (node, index, map) {\n callback([node._key, node._value], index, map);\n });\n }\n /**\n * @description Insert a key-value pair or set value by the given key.\n * @param key - The key want to insert.\n * @param value - The value want to set.\n * @param hint - You can give an iterator hint to improve insertion efficiency.\n * @return The size of container after setting.\n * @example\n * const mp = new OrderedMap([[2, 0], [4, 0], [5, 0]]);\n * const iter = mp.begin();\n * mp.setElement(1, 0);\n * mp.setElement(3, 0, iter); // give a hint will be faster.\n */\n setElement(key, value, hint) {\n return this._set(key, value, hint);\n }\n getElementByPos(pos) {\n if (pos < 0 || pos > this._length - 1) {\n throw new RangeError();\n }\n const node = this._inOrderTraversal(pos);\n return [node._key, node._value];\n }\n find(key) {\n const curNode = this._getTreeNodeByKey(this._root, key);\n return new OrderedMapIterator(curNode, this._header, this);\n }\n /**\n * @description Get the value of the element of the specified key.\n * @param key - The specified key you want to get.\n * @example\n * const val = container.getElementByKey(1);\n */\n getElementByKey(key) {\n const curNode = this._getTreeNodeByKey(this._root, key);\n return curNode._value;\n }\n union(other) {\n const self = this;\n other.forEach(function (el) {\n self.setElement(el[0], el[1]);\n });\n return this._length;\n }\n *[Symbol.iterator]() {\n const length = this._length;\n const nodeList = this._inOrderTraversal();\n for (let i = 0; i < length; ++i) {\n const node = nodeList[i];\n yield [node._key, node._value];\n }\n }\n}\n\nexports.OrderedMap = OrderedMap;\n//# sourceMappingURL=index.js.map\n","export const enum TreeNodeColor {\n RED = 1,\n BLACK = 0\n}\n\nexport class TreeNode {\n _color: TreeNodeColor;\n _key: K | undefined;\n _value: V | undefined;\n _left: TreeNode | undefined = undefined;\n _right: TreeNode | undefined = undefined;\n _parent: TreeNode | undefined = undefined;\n constructor(\n key?: K,\n value?: V,\n color: TreeNodeColor = TreeNodeColor.RED\n ) {\n this._key = key;\n this._value = value;\n this._color = color;\n }\n /**\n * @description Get the pre node.\n * @returns TreeNode about the pre node.\n */\n _pre() {\n let preNode: TreeNode = this;\n const isRootOrHeader = preNode._parent!._parent === preNode;\n if (isRootOrHeader && preNode._color === TreeNodeColor.RED) {\n preNode = preNode._right!;\n } else if (preNode._left) {\n preNode = preNode._left;\n while (preNode._right) {\n preNode = preNode._right;\n }\n } else {\n // Must be root and left is null\n if (isRootOrHeader) {\n return preNode._parent!;\n }\n let pre = preNode._parent!;\n while (pre._left === preNode) {\n preNode = pre;\n pre = preNode._parent!;\n }\n preNode = pre;\n }\n return preNode;\n }\n /**\n * @description Get the next node.\n * @returns TreeNode about the next node.\n */\n _next() {\n let nextNode: TreeNode = this;\n if (nextNode._right) {\n nextNode = nextNode._right;\n while (nextNode._left) {\n nextNode = nextNode._left;\n }\n return nextNode;\n } else {\n let pre = nextNode._parent!;\n while (pre._right === nextNode) {\n nextNode = pre;\n pre = nextNode._parent!;\n }\n if (nextNode._right !== pre) {\n return pre;\n } else return nextNode;\n }\n }\n /**\n * @description Rotate left.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateLeft() {\n const PP = this._parent!;\n const V = this._right!;\n const R = V._left;\n\n if (PP._parent === this) PP._parent = V;\n else if (PP._left === this) PP._left = V;\n else PP._right = V;\n\n V._parent = PP;\n V._left = this;\n\n this._parent = V;\n this._right = R;\n\n if (R) R._parent = this;\n\n return V;\n }\n /**\n * @description Rotate right.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateRight() {\n const PP = this._parent!;\n const F = this._left!;\n const K = F._right;\n\n if (PP._parent === this) PP._parent = F;\n else if (PP._left === this) PP._left = F;\n else PP._right = F;\n\n F._parent = PP;\n F._right = this;\n\n this._parent = F;\n this._left = K;\n\n if (K) K._parent = this;\n\n return F;\n }\n}\n\nexport class TreeNodeEnableIndex extends TreeNode {\n _subTreeSize = 1;\n /**\n * @description Rotate left and do recount.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateLeft() {\n const parent = super._rotateLeft() as TreeNodeEnableIndex;\n this._recount();\n parent._recount();\n return parent;\n }\n /**\n * @description Rotate right and do recount.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateRight() {\n const parent = super._rotateRight() as TreeNodeEnableIndex;\n this._recount();\n parent._recount();\n return parent;\n }\n _recount() {\n this._subTreeSize = 1;\n if (this._left) {\n this._subTreeSize += (this._left as TreeNodeEnableIndex)._subTreeSize;\n }\n if (this._right) {\n this._subTreeSize += (this._right as TreeNodeEnableIndex)._subTreeSize;\n }\n }\n}\n","/**\n * @description The iterator type including `NORMAL` and `REVERSE`.\n */\nexport const enum IteratorType {\n NORMAL = 0,\n REVERSE = 1\n}\n\nexport abstract class ContainerIterator {\n /**\n * @description The container pointed to by the iterator.\n */\n abstract readonly container: Container;\n /**\n * @internal\n */\n abstract _node: unknown;\n /**\n * @description Iterator's type.\n * @example\n * console.log(container.end().iteratorType === IteratorType.NORMAL); // true\n */\n readonly iteratorType: IteratorType;\n /**\n * @internal\n */\n protected constructor(iteratorType = IteratorType.NORMAL) {\n this.iteratorType = iteratorType;\n }\n /**\n * @param iter - The other iterator you want to compare.\n * @returns Whether this equals to obj.\n * @example\n * container.find(1).equals(container.end());\n */\n equals(iter: ContainerIterator) {\n return this._node === iter._node;\n }\n /**\n * @description Pointers to element.\n * @returns The value of the pointer's element.\n * @example\n * const val = container.begin().pointer;\n */\n abstract get pointer(): T;\n /**\n * @description Set pointer's value (some containers are unavailable).\n * @param newValue - The new value you want to set.\n * @example\n * (>container).begin().pointer = 1;\n */\n abstract set pointer(newValue: T);\n /**\n * @description Move `this` iterator to pre.\n * @returns The iterator's self.\n * @example\n * const iter = container.find(1); // container = [0, 1]\n * const pre = iter.pre();\n * console.log(pre === iter); // true\n * console.log(pre.equals(iter)); // true\n * console.log(pre.pointer, iter.pointer); // 0, 0\n */\n abstract pre(): this;\n /**\n * @description Move `this` iterator to next.\n * @returns The iterator's self.\n * @example\n * const iter = container.find(1); // container = [1, 2]\n * const next = iter.next();\n * console.log(next === iter); // true\n * console.log(next.equals(iter)); // true\n * console.log(next.pointer, iter.pointer); // 2, 2\n */\n abstract next(): this;\n /**\n * @description Get a copy of itself.\n * @returns The copy of self.\n * @example\n * const iter = container.find(1); // container = [1, 2]\n * const next = iter.copy().next();\n * console.log(next === iter); // false\n * console.log(next.equals(iter)); // false\n * console.log(next.pointer, iter.pointer); // 2, 1\n */\n abstract copy(): ContainerIterator;\n abstract isAccessible(): boolean;\n}\n\nexport abstract class Base {\n /**\n * @description Container's size.\n * @internal\n */\n protected _length = 0;\n /**\n * @returns The size of the container.\n * @example\n * const container = new Vector([1, 2]);\n * console.log(container.length); // 2\n */\n get length() {\n return this._length;\n }\n /**\n * @returns The size of the container.\n * @example\n * const container = new Vector([1, 2]);\n * console.log(container.size()); // 2\n */\n size() {\n return this._length;\n }\n /**\n * @returns Whether the container is empty.\n * @example\n * container.clear();\n * console.log(container.empty()); // true\n */\n empty() {\n return this._length === 0;\n }\n /**\n * @description Clear the container.\n * @example\n * container.clear();\n * console.log(container.empty()); // true\n */\n abstract clear(): void;\n}\n\nexport abstract class Container extends Base {\n /**\n * @returns Iterator pointing to the beginning element.\n * @example\n * const begin = container.begin();\n * const end = container.end();\n * for (const it = begin; !it.equals(end); it.next()) {\n * doSomething(it.pointer);\n * }\n */\n abstract begin(): ContainerIterator;\n /**\n * @returns Iterator pointing to the super end like c++.\n * @example\n * const begin = container.begin();\n * const end = container.end();\n * for (const it = begin; !it.equals(end); it.next()) {\n * doSomething(it.pointer);\n * }\n */\n abstract end(): ContainerIterator;\n /**\n * @returns Iterator pointing to the end element.\n * @example\n * const rBegin = container.rBegin();\n * const rEnd = container.rEnd();\n * for (const it = rBegin; !it.equals(rEnd); it.next()) {\n * doSomething(it.pointer);\n * }\n */\n abstract rBegin(): ContainerIterator;\n /**\n * @returns Iterator pointing to the super begin like c++.\n * @example\n * const rBegin = container.rBegin();\n * const rEnd = container.rEnd();\n * for (const it = rBegin; !it.equals(rEnd); it.next()) {\n * doSomething(it.pointer);\n * }\n */\n abstract rEnd(): ContainerIterator;\n /**\n * @returns The first element of the container.\n */\n abstract front(): T | undefined;\n /**\n * @returns The last element of the container.\n */\n abstract back(): T | undefined;\n /**\n * @param element - The element you want to find.\n * @returns An iterator pointing to the element if found, or super end if not found.\n * @example\n * container.find(1).equals(container.end());\n */\n abstract find(element: T): ContainerIterator;\n /**\n * @description Iterate over all elements in the container.\n * @param callback - Callback function like Array.forEach.\n * @example\n * container.forEach((element, index) => console.log(element, index));\n */\n abstract forEach(callback: (element: T, index: number, container: Container) => void): void;\n /**\n * @description Gets the value of the element at the specified position.\n * @example\n * const val = container.getElementByPos(-1); // throw a RangeError\n */\n abstract getElementByPos(pos: number): T;\n /**\n * @description Removes the element at the specified position.\n * @param pos - The element's position you want to remove.\n * @returns The container length after erasing.\n * @example\n * container.eraseElementByPos(-1); // throw a RangeError\n */\n abstract eraseElementByPos(pos: number): number;\n /**\n * @description Removes element by iterator and move `iter` to next.\n * @param iter - The iterator you want to erase.\n * @returns The next iterator.\n * @example\n * container.eraseElementByIterator(container.begin());\n * container.eraseElementByIterator(container.end()); // throw a RangeError\n */\n abstract eraseElementByIterator(\n iter: ContainerIterator\n ): ContainerIterator;\n /**\n * @description Using for `for...of` syntax like Array.\n * @example\n * for (const element of container) {\n * console.log(element);\n * }\n */\n abstract [Symbol.iterator](): Generator;\n}\n\n/**\n * @description The initial data type passed in when initializing the container.\n */\nexport type initContainer = {\n size?: number | (() => number);\n length?: number;\n forEach: (callback: (el: T) => void) => void;\n}\n","/**\n * @description Throw an iterator access error.\n * @internal\n */\nexport function throwIteratorAccessError() {\n throw new RangeError('Iterator access denied!');\n}\n","import type TreeIterator from './TreeIterator';\nimport { TreeNode, TreeNodeColor, TreeNodeEnableIndex } from './TreeNode';\nimport { Container, IteratorType } from '@/container/ContainerBase';\nimport $checkWithinAccessParams from '@/utils/checkParams.macro';\nimport { throwIteratorAccessError } from '@/utils/throwError';\n\nabstract class TreeContainer extends Container {\n enableIndex: boolean;\n /**\n * @internal\n */\n protected _header: TreeNode;\n /**\n * @internal\n */\n protected _root: TreeNode | undefined = undefined;\n /**\n * @internal\n */\n protected readonly _cmp: (x: K, y: K) => number;\n /**\n * @internal\n */\n protected readonly _TreeNodeClass: typeof TreeNode | typeof TreeNodeEnableIndex;\n /**\n * @internal\n */\n protected constructor(\n cmp: (x: K, y: K) => number =\n function (x: K, y: K) {\n if (x < y) return -1;\n if (x > y) return 1;\n return 0;\n },\n enableIndex = false\n ) {\n super();\n this._cmp = cmp;\n this.enableIndex = enableIndex;\n this._TreeNodeClass = enableIndex ? TreeNodeEnableIndex : TreeNode;\n this._header = new this._TreeNodeClass();\n }\n /**\n * @internal\n */\n protected _lowerBound(curNode: TreeNode | undefined, key: K) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult < 0) {\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n resNode = curNode;\n curNode = curNode._left;\n } else return curNode;\n }\n return resNode;\n }\n /**\n * @internal\n */\n protected _upperBound(curNode: TreeNode | undefined, key: K) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult <= 0) {\n curNode = curNode._right;\n } else {\n resNode = curNode;\n curNode = curNode._left;\n }\n }\n return resNode;\n }\n /**\n * @internal\n */\n protected _reverseLowerBound(curNode: TreeNode | undefined, key: K) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult < 0) {\n resNode = curNode;\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n curNode = curNode._left;\n } else return curNode;\n }\n return resNode;\n }\n /**\n * @internal\n */\n protected _reverseUpperBound(curNode: TreeNode | undefined, key: K) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult < 0) {\n resNode = curNode;\n curNode = curNode._right;\n } else {\n curNode = curNode._left;\n }\n }\n return resNode;\n }\n /**\n * @internal\n */\n protected _eraseNodeSelfBalance(curNode: TreeNode) {\n while (true) {\n const parentNode = curNode._parent!;\n if (parentNode === this._header) return;\n if (curNode._color === TreeNodeColor.RED) {\n curNode._color = TreeNodeColor.BLACK;\n return;\n }\n if (curNode === parentNode._left) {\n const brother = parentNode._right!;\n if (brother._color === TreeNodeColor.RED) {\n brother._color = TreeNodeColor.BLACK;\n parentNode._color = TreeNodeColor.RED;\n if (parentNode === this._root) {\n this._root = parentNode._rotateLeft();\n } else parentNode._rotateLeft();\n } else {\n if (brother._right && brother._right._color === TreeNodeColor.RED) {\n brother._color = parentNode._color;\n parentNode._color = TreeNodeColor.BLACK;\n brother._right._color = TreeNodeColor.BLACK;\n if (parentNode === this._root) {\n this._root = parentNode._rotateLeft();\n } else parentNode._rotateLeft();\n return;\n } else if (brother._left && brother._left._color === TreeNodeColor.RED) {\n brother._color = TreeNodeColor.RED;\n brother._left._color = TreeNodeColor.BLACK;\n brother._rotateRight();\n } else {\n brother._color = TreeNodeColor.RED;\n curNode = parentNode;\n }\n }\n } else {\n const brother = parentNode._left!;\n if (brother._color === TreeNodeColor.RED) {\n brother._color = TreeNodeColor.BLACK;\n parentNode._color = TreeNodeColor.RED;\n if (parentNode === this._root) {\n this._root = parentNode._rotateRight();\n } else parentNode._rotateRight();\n } else {\n if (brother._left && brother._left._color === TreeNodeColor.RED) {\n brother._color = parentNode._color;\n parentNode._color = TreeNodeColor.BLACK;\n brother._left._color = TreeNodeColor.BLACK;\n if (parentNode === this._root) {\n this._root = parentNode._rotateRight();\n } else parentNode._rotateRight();\n return;\n } else if (brother._right && brother._right._color === TreeNodeColor.RED) {\n brother._color = TreeNodeColor.RED;\n brother._right._color = TreeNodeColor.BLACK;\n brother._rotateLeft();\n } else {\n brother._color = TreeNodeColor.RED;\n curNode = parentNode;\n }\n }\n }\n }\n }\n /**\n * @internal\n */\n protected _eraseNode(curNode: TreeNode) {\n if (this._length === 1) {\n this.clear();\n return;\n }\n let swapNode = curNode;\n while (swapNode._left || swapNode._right) {\n if (swapNode._right) {\n swapNode = swapNode._right;\n while (swapNode._left) swapNode = swapNode._left;\n } else {\n swapNode = swapNode._left!;\n }\n const key = curNode._key;\n curNode._key = swapNode._key;\n swapNode._key = key;\n const value = curNode._value;\n curNode._value = swapNode._value;\n swapNode._value = value;\n curNode = swapNode;\n }\n if (this._header._left === swapNode) {\n this._header._left = swapNode._parent;\n } else if (this._header._right === swapNode) {\n this._header._right = swapNode._parent;\n }\n this._eraseNodeSelfBalance(swapNode);\n let _parent = swapNode._parent as TreeNodeEnableIndex;\n if (swapNode === _parent._left) {\n _parent._left = undefined;\n } else _parent._right = undefined;\n this._length -= 1;\n this._root!._color = TreeNodeColor.BLACK;\n if (this.enableIndex) {\n while (_parent !== this._header) {\n _parent._subTreeSize -= 1;\n _parent = _parent._parent as TreeNodeEnableIndex;\n }\n }\n }\n protected _inOrderTraversal(): TreeNode[];\n protected _inOrderTraversal(pos: number): TreeNode;\n protected _inOrderTraversal(\n callback: (node: TreeNode, index: number, map: this) => void\n ): TreeNode;\n /**\n * @internal\n */\n protected _inOrderTraversal(\n param?: number | ((node: TreeNode, index: number, map: this) => void)\n ) {\n const pos = typeof param === 'number' ? param : undefined;\n const callback = typeof param === 'function' ? param : undefined;\n const nodeList = typeof param === 'undefined' ? []>[] : undefined;\n let index = 0;\n let curNode = this._root;\n const stack: TreeNode[] = [];\n while (stack.length || curNode) {\n if (curNode) {\n stack.push(curNode);\n curNode = curNode._left;\n } else {\n curNode = stack.pop()!;\n if (index === pos) return curNode;\n nodeList && nodeList.push(curNode);\n callback && callback(curNode, index, this);\n index += 1;\n curNode = curNode._right;\n }\n }\n return nodeList;\n }\n /**\n * @internal\n */\n protected _insertNodeSelfBalance(curNode: TreeNode) {\n while (true) {\n const parentNode = curNode._parent!;\n if (parentNode._color === TreeNodeColor.BLACK) return;\n const grandParent = parentNode._parent!;\n if (parentNode === grandParent._left) {\n const uncle = grandParent._right;\n if (uncle && uncle._color === TreeNodeColor.RED) {\n uncle._color = parentNode._color = TreeNodeColor.BLACK;\n if (grandParent === this._root) return;\n grandParent._color = TreeNodeColor.RED;\n curNode = grandParent;\n continue;\n } else if (curNode === parentNode._right) {\n curNode._color = TreeNodeColor.BLACK;\n if (curNode._left) {\n curNode._left._parent = parentNode;\n }\n if (curNode._right) {\n curNode._right._parent = grandParent;\n }\n parentNode._right = curNode._left;\n grandParent._left = curNode._right;\n curNode._left = parentNode;\n curNode._right = grandParent;\n if (grandParent === this._root) {\n this._root = curNode;\n this._header._parent = curNode;\n } else {\n const GP = grandParent._parent!;\n if (GP._left === grandParent) {\n GP._left = curNode;\n } else GP._right = curNode;\n }\n curNode._parent = grandParent._parent;\n parentNode._parent = curNode;\n grandParent._parent = curNode;\n grandParent._color = TreeNodeColor.RED;\n } else {\n parentNode._color = TreeNodeColor.BLACK;\n if (grandParent === this._root) {\n this._root = grandParent._rotateRight();\n } else grandParent._rotateRight();\n grandParent._color = TreeNodeColor.RED;\n return;\n }\n } else {\n const uncle = grandParent._left;\n if (uncle && uncle._color === TreeNodeColor.RED) {\n uncle._color = parentNode._color = TreeNodeColor.BLACK;\n if (grandParent === this._root) return;\n grandParent._color = TreeNodeColor.RED;\n curNode = grandParent;\n continue;\n } else if (curNode === parentNode._left) {\n curNode._color = TreeNodeColor.BLACK;\n if (curNode._left) {\n curNode._left._parent = grandParent;\n }\n if (curNode._right) {\n curNode._right._parent = parentNode;\n }\n grandParent._right = curNode._left;\n parentNode._left = curNode._right;\n curNode._left = grandParent;\n curNode._right = parentNode;\n if (grandParent === this._root) {\n this._root = curNode;\n this._header._parent = curNode;\n } else {\n const GP = grandParent._parent!;\n if (GP._left === grandParent) {\n GP._left = curNode;\n } else GP._right = curNode;\n }\n curNode._parent = grandParent._parent;\n parentNode._parent = curNode;\n grandParent._parent = curNode;\n grandParent._color = TreeNodeColor.RED;\n } else {\n parentNode._color = TreeNodeColor.BLACK;\n if (grandParent === this._root) {\n this._root = grandParent._rotateLeft();\n } else grandParent._rotateLeft();\n grandParent._color = TreeNodeColor.RED;\n return;\n }\n }\n if (this.enableIndex) {\n (>parentNode)._recount();\n (>grandParent)._recount();\n (>curNode)._recount();\n }\n return;\n }\n }\n /**\n * @internal\n */\n protected _set(key: K, value?: V, hint?: TreeIterator) {\n if (this._root === undefined) {\n this._length += 1;\n this._root = new this._TreeNodeClass(key, value, TreeNodeColor.BLACK);\n this._root._parent = this._header;\n this._header._parent = this._header._left = this._header._right = this._root;\n return this._length;\n }\n let curNode;\n const minNode = this._header._left!;\n const compareToMin = this._cmp(minNode._key!, key);\n if (compareToMin === 0) {\n minNode._value = value;\n return this._length;\n } else if (compareToMin > 0) {\n minNode._left = new this._TreeNodeClass(key, value);\n minNode._left._parent = minNode;\n curNode = minNode._left;\n this._header._left = curNode;\n } else {\n const maxNode = this._header._right!;\n const compareToMax = this._cmp(maxNode._key!, key);\n if (compareToMax === 0) {\n maxNode._value = value;\n return this._length;\n } else if (compareToMax < 0) {\n maxNode._right = new this._TreeNodeClass(key, value);\n maxNode._right._parent = maxNode;\n curNode = maxNode._right;\n this._header._right = curNode;\n } else {\n if (hint !== undefined) {\n const iterNode = hint._node;\n if (iterNode !== this._header) {\n const iterCmpRes = this._cmp(iterNode._key!, key);\n if (iterCmpRes === 0) {\n iterNode._value = value;\n return this._length;\n } else /* istanbul ignore else */ if (iterCmpRes > 0) {\n const preNode = iterNode._pre();\n const preCmpRes = this._cmp(preNode._key!, key);\n if (preCmpRes === 0) {\n preNode._value = value;\n return this._length;\n } else if (preCmpRes < 0) {\n curNode = new this._TreeNodeClass(key, value);\n if (preNode._right === undefined) {\n preNode._right = curNode;\n curNode._parent = preNode;\n } else {\n iterNode._left = curNode;\n curNode._parent = iterNode;\n }\n }\n }\n }\n }\n if (curNode === undefined) {\n curNode = this._root;\n while (true) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult > 0) {\n if (curNode._left === undefined) {\n curNode._left = new this._TreeNodeClass(key, value);\n curNode._left._parent = curNode;\n curNode = curNode._left;\n break;\n }\n curNode = curNode._left;\n } else if (cmpResult < 0) {\n if (curNode._right === undefined) {\n curNode._right = new this._TreeNodeClass(key, value);\n curNode._right._parent = curNode;\n curNode = curNode._right;\n break;\n }\n curNode = curNode._right;\n } else {\n curNode._value = value;\n return this._length;\n }\n }\n }\n }\n }\n if (this.enableIndex) {\n let parent = curNode._parent as TreeNodeEnableIndex;\n while (parent !== this._header) {\n parent._subTreeSize += 1;\n parent = parent._parent as TreeNodeEnableIndex;\n }\n }\n this._insertNodeSelfBalance(curNode);\n this._length += 1;\n return this._length;\n }\n /**\n * @internal\n */\n protected _getTreeNodeByKey(curNode: TreeNode | undefined, key: K) {\n while (curNode) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult < 0) {\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n curNode = curNode._left;\n } else return curNode;\n }\n return curNode || this._header;\n }\n clear() {\n this._length = 0;\n this._root = undefined;\n this._header._parent = undefined;\n this._header._left = this._header._right = undefined;\n }\n /**\n * @description Update node's key by iterator.\n * @param iter - The iterator you want to change.\n * @param key - The key you want to update.\n * @returns Whether the modification is successful.\n * @example\n * const st = new orderedSet([1, 2, 5]);\n * const iter = st.find(2);\n * st.updateKeyByIterator(iter, 3); // then st will become [1, 3, 5]\n */\n updateKeyByIterator(iter: TreeIterator, key: K): boolean {\n const node = iter._node;\n if (node === this._header) {\n throwIteratorAccessError();\n }\n if (this._length === 1) {\n node._key = key;\n return true;\n }\n const nextKey = node._next()._key!;\n if (node === this._header._left) {\n if (this._cmp(nextKey, key) > 0) {\n node._key = key;\n return true;\n }\n return false;\n }\n const preKey = node._pre()._key!;\n if (node === this._header._right) {\n if (this._cmp(preKey, key) < 0) {\n node._key = key;\n return true;\n }\n return false;\n }\n if (\n this._cmp(preKey, key) >= 0 ||\n this._cmp(nextKey, key) <= 0\n ) return false;\n node._key = key;\n return true;\n }\n eraseElementByPos(pos: number) {\n $checkWithinAccessParams!(pos, 0, this._length - 1);\n const node = this._inOrderTraversal(pos);\n this._eraseNode(node);\n return this._length;\n }\n /**\n * @description Remove the element of the specified key.\n * @param key - The key you want to remove.\n * @returns Whether erase successfully.\n */\n eraseElementByKey(key: K) {\n if (this._length === 0) return false;\n const curNode = this._getTreeNodeByKey(this._root, key);\n if (curNode === this._header) return false;\n this._eraseNode(curNode);\n return true;\n }\n eraseElementByIterator(iter: TreeIterator) {\n const node = iter._node;\n if (node === this._header) {\n throwIteratorAccessError();\n }\n const hasNoRight = node._right === undefined;\n const isNormal = iter.iteratorType === IteratorType.NORMAL;\n // For the normal iterator, the `next` node will be swapped to `this` node when has right.\n if (isNormal) {\n // So we should move it to next when it's right is null.\n if (hasNoRight) iter.next();\n } else {\n // For the reverse iterator, only when it doesn't have right and has left the `next` node will be swapped.\n // So when it has right, or it is a leaf node we should move it to `next`.\n if (!hasNoRight || node._left === undefined) iter.next();\n }\n this._eraseNode(node);\n return iter;\n }\n /**\n * @description Get the height of the tree.\n * @returns Number about the height of the RB-tree.\n */\n getHeight() {\n if (this._length === 0) return 0;\n function traversal(curNode: TreeNode | undefined): number {\n if (!curNode) return 0;\n return Math.max(traversal(curNode._left), traversal(curNode._right)) + 1;\n }\n return traversal(this._root);\n }\n /**\n * @param key - The given key you want to compare.\n * @returns An iterator to the first element less than the given key.\n */\n abstract reverseUpperBound(key: K): TreeIterator;\n /**\n * @description Union the other tree to self.\n * @param other - The other tree container you want to merge.\n * @returns The size of the tree after union.\n */\n abstract union(other: TreeContainer): number;\n /**\n * @param key - The given key you want to compare.\n * @returns An iterator to the first element not greater than the given key.\n */\n abstract reverseLowerBound(key: K): TreeIterator;\n /**\n * @param key - The given key you want to compare.\n * @returns An iterator to the first element not less than the given key.\n */\n abstract lowerBound(key: K): TreeIterator;\n /**\n * @param key - The given key you want to compare.\n * @returns An iterator to the first element greater than the given key.\n */\n abstract upperBound(key: K): TreeIterator;\n}\n\nexport default TreeContainer;\n","import { TreeNode } from './TreeNode';\nimport type { TreeNodeEnableIndex } from './TreeNode';\nimport { ContainerIterator, IteratorType } from '@/container/ContainerBase';\nimport TreeContainer from '@/container/TreeContainer/Base/index';\nimport { throwIteratorAccessError } from '@/utils/throwError';\n\nabstract class TreeIterator extends ContainerIterator {\n abstract readonly container: TreeContainer;\n /**\n * @internal\n */\n _node: TreeNode;\n /**\n * @internal\n */\n protected _header: TreeNode;\n /**\n * @internal\n */\n protected constructor(\n node: TreeNode,\n header: TreeNode,\n iteratorType?: IteratorType\n ) {\n super(iteratorType);\n this._node = node;\n this._header = header;\n if (this.iteratorType === IteratorType.NORMAL) {\n this.pre = function () {\n if (this._node === this._header._left) {\n throwIteratorAccessError();\n }\n this._node = this._node._pre();\n return this;\n };\n\n this.next = function () {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n this._node = this._node._next();\n return this;\n };\n } else {\n this.pre = function () {\n if (this._node === this._header._right) {\n throwIteratorAccessError();\n }\n this._node = this._node._next();\n return this;\n };\n\n this.next = function () {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n this._node = this._node._pre();\n return this;\n };\n }\n }\n /**\n * @description Get the sequential index of the iterator in the tree container.
\n * Note:\n * This function only takes effect when the specified tree container `enableIndex = true`.\n * @returns The index subscript of the node in the tree.\n * @example\n * const st = new OrderedSet([1, 2, 3], true);\n * console.log(st.begin().next().index); // 1\n */\n get index() {\n let _node = this._node as TreeNodeEnableIndex;\n const root = this._header._parent as TreeNodeEnableIndex;\n if (_node === this._header) {\n if (root) {\n return root._subTreeSize - 1;\n }\n return 0;\n }\n let index = 0;\n if (_node._left) {\n index += (_node._left as TreeNodeEnableIndex)._subTreeSize;\n }\n while (_node !== root) {\n const _parent = _node._parent as TreeNodeEnableIndex;\n if (_node === _parent._right) {\n index += 1;\n if (_parent._left) {\n index += (_parent._left as TreeNodeEnableIndex)._subTreeSize;\n }\n }\n _node = _parent;\n }\n return index;\n }\n isAccessible() {\n return this._node !== this._header;\n }\n // @ts-ignore\n pre(): this;\n // @ts-ignore\n next(): this;\n}\n\nexport default TreeIterator;\n","import TreeContainer from './Base';\nimport TreeIterator from './Base/TreeIterator';\nimport { TreeNode } from './Base/TreeNode';\nimport { initContainer, IteratorType } from '@/container/ContainerBase';\nimport $checkWithinAccessParams from '@/utils/checkParams.macro';\nimport { throwIteratorAccessError } from '@/utils/throwError';\n\nclass OrderedMapIterator extends TreeIterator {\n container: OrderedMap;\n constructor(\n node: TreeNode,\n header: TreeNode,\n container: OrderedMap,\n iteratorType?: IteratorType\n ) {\n super(node, header, iteratorType);\n this.container = container;\n }\n get pointer() {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n const self = this;\n return new Proxy(<[K, V]>[], {\n get(target, prop: '0' | '1') {\n if (prop === '0') return self._node._key!;\n else if (prop === '1') return self._node._value!;\n target[0] = self._node._key!;\n target[1] = self._node._value!;\n return target[prop];\n },\n set(_, prop: '1', newValue: V) {\n if (prop !== '1') {\n throw new TypeError('prop must be 1');\n }\n self._node._value = newValue;\n return true;\n }\n });\n }\n copy() {\n return new OrderedMapIterator(\n this._node,\n this._header,\n this.container,\n this.iteratorType\n );\n }\n // @ts-ignore\n equals(iter: OrderedMapIterator): boolean;\n}\n\nexport type { OrderedMapIterator };\n\nclass OrderedMap extends TreeContainer {\n /**\n * @param container - The initialization container.\n * @param cmp - The compare function.\n * @param enableIndex - Whether to enable iterator indexing function.\n * @example\n * new OrderedMap();\n * new OrderedMap([[0, 1], [2, 1]]);\n * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y);\n * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y, true);\n */\n constructor(\n container: initContainer<[K, V]> = [],\n cmp?: (x: K, y: K) => number,\n enableIndex?: boolean\n ) {\n super(cmp, enableIndex);\n const self = this;\n container.forEach(function (el) {\n self.setElement(el[0], el[1]);\n });\n }\n begin() {\n return new OrderedMapIterator(this._header._left || this._header, this._header, this);\n }\n end() {\n return new OrderedMapIterator(this._header, this._header, this);\n }\n rBegin() {\n return new OrderedMapIterator(\n this._header._right || this._header,\n this._header,\n this,\n IteratorType.REVERSE\n );\n }\n rEnd() {\n return new OrderedMapIterator(this._header, this._header, this, IteratorType.REVERSE);\n }\n front() {\n if (this._length === 0) return;\n const minNode = this._header._left!;\n return <[K, V]>[minNode._key, minNode._value];\n }\n back() {\n if (this._length === 0) return;\n const maxNode = this._header._right!;\n return <[K, V]>[maxNode._key, maxNode._value];\n }\n lowerBound(key: K) {\n const resNode = this._lowerBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n upperBound(key: K) {\n const resNode = this._upperBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n reverseLowerBound(key: K) {\n const resNode = this._reverseLowerBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n reverseUpperBound(key: K) {\n const resNode = this._reverseUpperBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n forEach(callback: (element: [K, V], index: number, map: OrderedMap) => void) {\n this._inOrderTraversal(function (node, index, map) {\n callback(<[K, V]>[node._key, node._value], index, map);\n });\n }\n /**\n * @description Insert a key-value pair or set value by the given key.\n * @param key - The key want to insert.\n * @param value - The value want to set.\n * @param hint - You can give an iterator hint to improve insertion efficiency.\n * @return The size of container after setting.\n * @example\n * const mp = new OrderedMap([[2, 0], [4, 0], [5, 0]]);\n * const iter = mp.begin();\n * mp.setElement(1, 0);\n * mp.setElement(3, 0, iter); // give a hint will be faster.\n */\n setElement(key: K, value: V, hint?: OrderedMapIterator) {\n return this._set(key, value, hint);\n }\n getElementByPos(pos: number) {\n $checkWithinAccessParams!(pos, 0, this._length - 1);\n const node = this._inOrderTraversal(pos);\n return <[K, V]>[node._key, node._value];\n }\n find(key: K) {\n const curNode = this._getTreeNodeByKey(this._root, key);\n return new OrderedMapIterator(curNode, this._header, this);\n }\n /**\n * @description Get the value of the element of the specified key.\n * @param key - The specified key you want to get.\n * @example\n * const val = container.getElementByKey(1);\n */\n getElementByKey(key: K) {\n const curNode = this._getTreeNodeByKey(this._root, key);\n return curNode._value;\n }\n union(other: OrderedMap) {\n const self = this;\n other.forEach(function (el) {\n self.setElement(el[0], el[1]);\n });\n return this._length;\n }\n * [Symbol.iterator]() {\n const length = this._length;\n const nodeList = this._inOrderTraversal();\n for (let i = 0; i < length; ++i) {\n const node = nodeList[i];\n yield <[K, V]>[node._key, node._value];\n }\n }\n // @ts-ignore\n eraseElementByIterator(iter: OrderedMapIterator): OrderedMapIterator;\n}\n\nexport default OrderedMap;\n"]} \ No newline at end of file diff --git a/node_modules/@js-sdsl/ordered-map/dist/esm/index.d.ts b/node_modules/@js-sdsl/ordered-map/dist/esm/index.d.ts new file mode 100644 index 0000000..8615f37 --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/dist/esm/index.d.ts @@ -0,0 +1,402 @@ +/** + * @description The iterator type including `NORMAL` and `REVERSE`. + */ +declare const enum IteratorType { + NORMAL = 0, + REVERSE = 1 +} +declare abstract class ContainerIterator { + /** + * @description The container pointed to by the iterator. + */ + abstract readonly container: Container; + /** + * @description Iterator's type. + * @example + * console.log(container.end().iteratorType === IteratorType.NORMAL); // true + */ + readonly iteratorType: IteratorType; + /** + * @param iter - The other iterator you want to compare. + * @returns Whether this equals to obj. + * @example + * container.find(1).equals(container.end()); + */ + equals(iter: ContainerIterator): boolean; + /** + * @description Pointers to element. + * @returns The value of the pointer's element. + * @example + * const val = container.begin().pointer; + */ + abstract get pointer(): T; + /** + * @description Set pointer's value (some containers are unavailable). + * @param newValue - The new value you want to set. + * @example + * (>container).begin().pointer = 1; + */ + abstract set pointer(newValue: T); + /** + * @description Move `this` iterator to pre. + * @returns The iterator's self. + * @example + * const iter = container.find(1); // container = [0, 1] + * const pre = iter.pre(); + * console.log(pre === iter); // true + * console.log(pre.equals(iter)); // true + * console.log(pre.pointer, iter.pointer); // 0, 0 + */ + abstract pre(): this; + /** + * @description Move `this` iterator to next. + * @returns The iterator's self. + * @example + * const iter = container.find(1); // container = [1, 2] + * const next = iter.next(); + * console.log(next === iter); // true + * console.log(next.equals(iter)); // true + * console.log(next.pointer, iter.pointer); // 2, 2 + */ + abstract next(): this; + /** + * @description Get a copy of itself. + * @returns The copy of self. + * @example + * const iter = container.find(1); // container = [1, 2] + * const next = iter.copy().next(); + * console.log(next === iter); // false + * console.log(next.equals(iter)); // false + * console.log(next.pointer, iter.pointer); // 2, 1 + */ + abstract copy(): ContainerIterator; + abstract isAccessible(): boolean; +} +declare abstract class Base { + /** + * @returns The size of the container. + * @example + * const container = new Vector([1, 2]); + * console.log(container.length); // 2 + */ + get length(): number; + /** + * @returns The size of the container. + * @example + * const container = new Vector([1, 2]); + * console.log(container.size()); // 2 + */ + size(): number; + /** + * @returns Whether the container is empty. + * @example + * container.clear(); + * console.log(container.empty()); // true + */ + empty(): boolean; + /** + * @description Clear the container. + * @example + * container.clear(); + * console.log(container.empty()); // true + */ + abstract clear(): void; +} +declare abstract class Container extends Base { + /** + * @returns Iterator pointing to the beginning element. + * @example + * const begin = container.begin(); + * const end = container.end(); + * for (const it = begin; !it.equals(end); it.next()) { + * doSomething(it.pointer); + * } + */ + abstract begin(): ContainerIterator; + /** + * @returns Iterator pointing to the super end like c++. + * @example + * const begin = container.begin(); + * const end = container.end(); + * for (const it = begin; !it.equals(end); it.next()) { + * doSomething(it.pointer); + * } + */ + abstract end(): ContainerIterator; + /** + * @returns Iterator pointing to the end element. + * @example + * const rBegin = container.rBegin(); + * const rEnd = container.rEnd(); + * for (const it = rBegin; !it.equals(rEnd); it.next()) { + * doSomething(it.pointer); + * } + */ + abstract rBegin(): ContainerIterator; + /** + * @returns Iterator pointing to the super begin like c++. + * @example + * const rBegin = container.rBegin(); + * const rEnd = container.rEnd(); + * for (const it = rBegin; !it.equals(rEnd); it.next()) { + * doSomething(it.pointer); + * } + */ + abstract rEnd(): ContainerIterator; + /** + * @returns The first element of the container. + */ + abstract front(): T | undefined; + /** + * @returns The last element of the container. + */ + abstract back(): T | undefined; + /** + * @param element - The element you want to find. + * @returns An iterator pointing to the element if found, or super end if not found. + * @example + * container.find(1).equals(container.end()); + */ + abstract find(element: T): ContainerIterator; + /** + * @description Iterate over all elements in the container. + * @param callback - Callback function like Array.forEach. + * @example + * container.forEach((element, index) => console.log(element, index)); + */ + abstract forEach(callback: (element: T, index: number, container: Container) => void): void; + /** + * @description Gets the value of the element at the specified position. + * @example + * const val = container.getElementByPos(-1); // throw a RangeError + */ + abstract getElementByPos(pos: number): T; + /** + * @description Removes the element at the specified position. + * @param pos - The element's position you want to remove. + * @returns The container length after erasing. + * @example + * container.eraseElementByPos(-1); // throw a RangeError + */ + abstract eraseElementByPos(pos: number): number; + /** + * @description Removes element by iterator and move `iter` to next. + * @param iter - The iterator you want to erase. + * @returns The next iterator. + * @example + * container.eraseElementByIterator(container.begin()); + * container.eraseElementByIterator(container.end()); // throw a RangeError + */ + abstract eraseElementByIterator(iter: ContainerIterator): ContainerIterator; + /** + * @description Using for `for...of` syntax like Array. + * @example + * for (const element of container) { + * console.log(element); + * } + */ + abstract [Symbol.iterator](): Generator; +} +/** + * @description The initial data type passed in when initializing the container. + */ +type initContainer = { + size?: number | (() => number); + length?: number; + forEach: (callback: (el: T) => void) => void; +}; +declare abstract class TreeIterator extends ContainerIterator { + abstract readonly container: TreeContainer; + /** + * @description Get the sequential index of the iterator in the tree container.
+ * Note: + * This function only takes effect when the specified tree container `enableIndex = true`. + * @returns The index subscript of the node in the tree. + * @example + * const st = new OrderedSet([1, 2, 3], true); + * console.log(st.begin().next().index); // 1 + */ + get index(): number; + isAccessible(): boolean; + // @ts-ignore + pre(): this; + // @ts-ignore + next(): this; +} +declare const enum TreeNodeColor { + RED = 1, + BLACK = 0 +} +declare class TreeNode { + _color: TreeNodeColor; + _key: K | undefined; + _value: V | undefined; + _left: TreeNode | undefined; + _right: TreeNode | undefined; + _parent: TreeNode | undefined; + constructor(key?: K, value?: V, color?: TreeNodeColor); + /** + * @description Get the pre node. + * @returns TreeNode about the pre node. + */ + _pre(): TreeNode; + /** + * @description Get the next node. + * @returns TreeNode about the next node. + */ + _next(): TreeNode; + /** + * @description Rotate left. + * @returns TreeNode about moved to original position after rotation. + */ + _rotateLeft(): TreeNode; + /** + * @description Rotate right. + * @returns TreeNode about moved to original position after rotation. + */ + _rotateRight(): TreeNode; +} +declare abstract class TreeContainer extends Container { + enableIndex: boolean; + protected _inOrderTraversal(): TreeNode[]; + protected _inOrderTraversal(pos: number): TreeNode; + protected _inOrderTraversal(callback: (node: TreeNode, index: number, map: this) => void): TreeNode; + clear(): void; + /** + * @description Update node's key by iterator. + * @param iter - The iterator you want to change. + * @param key - The key you want to update. + * @returns Whether the modification is successful. + * @example + * const st = new orderedSet([1, 2, 5]); + * const iter = st.find(2); + * st.updateKeyByIterator(iter, 3); // then st will become [1, 3, 5] + */ + updateKeyByIterator(iter: TreeIterator, key: K): boolean; + eraseElementByPos(pos: number): number; + /** + * @description Remove the element of the specified key. + * @param key - The key you want to remove. + * @returns Whether erase successfully. + */ + eraseElementByKey(key: K): boolean; + eraseElementByIterator(iter: TreeIterator): TreeIterator; + /** + * @description Get the height of the tree. + * @returns Number about the height of the RB-tree. + */ + getHeight(): number; + /** + * @param key - The given key you want to compare. + * @returns An iterator to the first element less than the given key. + */ + abstract reverseUpperBound(key: K): TreeIterator; + /** + * @description Union the other tree to self. + * @param other - The other tree container you want to merge. + * @returns The size of the tree after union. + */ + abstract union(other: TreeContainer): number; + /** + * @param key - The given key you want to compare. + * @returns An iterator to the first element not greater than the given key. + */ + abstract reverseLowerBound(key: K): TreeIterator; + /** + * @param key - The given key you want to compare. + * @returns An iterator to the first element not less than the given key. + */ + abstract lowerBound(key: K): TreeIterator; + /** + * @param key - The given key you want to compare. + * @returns An iterator to the first element greater than the given key. + */ + abstract upperBound(key: K): TreeIterator; +} +declare class OrderedMapIterator extends TreeIterator { + container: OrderedMap; + constructor(node: TreeNode, header: TreeNode, container: OrderedMap, iteratorType?: IteratorType); + get pointer(): [ + K, + V + ]; + copy(): OrderedMapIterator; + // @ts-ignore + equals(iter: OrderedMapIterator): boolean; +} +declare class OrderedMap extends TreeContainer { + /** + * @param container - The initialization container. + * @param cmp - The compare function. + * @param enableIndex - Whether to enable iterator indexing function. + * @example + * new OrderedMap(); + * new OrderedMap([[0, 1], [2, 1]]); + * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y); + * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y, true); + */ + constructor(container?: initContainer<[ + K, + V + ]>, cmp?: (x: K, y: K) => number, enableIndex?: boolean); + begin(): OrderedMapIterator; + end(): OrderedMapIterator; + rBegin(): OrderedMapIterator; + rEnd(): OrderedMapIterator; + front(): [ + K, + V + ] | undefined; + back(): [ + K, + V + ] | undefined; + lowerBound(key: K): OrderedMapIterator; + upperBound(key: K): OrderedMapIterator; + reverseLowerBound(key: K): OrderedMapIterator; + reverseUpperBound(key: K): OrderedMapIterator; + forEach(callback: (element: [ + K, + V + ], index: number, map: OrderedMap) => void): void; + /** + * @description Insert a key-value pair or set value by the given key. + * @param key - The key want to insert. + * @param value - The value want to set. + * @param hint - You can give an iterator hint to improve insertion efficiency. + * @return The size of container after setting. + * @example + * const mp = new OrderedMap([[2, 0], [4, 0], [5, 0]]); + * const iter = mp.begin(); + * mp.setElement(1, 0); + * mp.setElement(3, 0, iter); // give a hint will be faster. + */ + setElement(key: K, value: V, hint?: OrderedMapIterator): number; + getElementByPos(pos: number): [ + K, + V + ]; + find(key: K): OrderedMapIterator; + /** + * @description Get the value of the element of the specified key. + * @param key - The specified key you want to get. + * @example + * const val = container.getElementByKey(1); + */ + getElementByKey(key: K): V | undefined; + union(other: OrderedMap): number; + [Symbol.iterator](): Generator<[ + K, + V + ], void, unknown>; + // @ts-ignore + eraseElementByIterator(iter: OrderedMapIterator): OrderedMapIterator; +} +export { OrderedMap }; +export type { OrderedMapIterator, IteratorType, Container, ContainerIterator, TreeContainer }; diff --git a/node_modules/@js-sdsl/ordered-map/dist/esm/index.js b/node_modules/@js-sdsl/ordered-map/dist/esm/index.js new file mode 100644 index 0000000..1504ce8 --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/dist/esm/index.js @@ -0,0 +1,975 @@ +var extendStatics = function(e, r) { + extendStatics = Object.setPrototypeOf || { + __proto__: [] + } instanceof Array && function(e, r) { + e.__proto__ = r; + } || function(e, r) { + for (var t in r) if (Object.prototype.hasOwnProperty.call(r, t)) e[t] = r[t]; + }; + return extendStatics(e, r); +}; + +function __extends(e, r) { + if (typeof r !== "function" && r !== null) throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + extendStatics(e, r); + function __() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (__.prototype = r.prototype, new __); +} + +function __generator(e, r) { + var t = { + label: 0, + sent: function() { + if (s[0] & 1) throw s[1]; + return s[1]; + }, + trys: [], + ops: [] + }, i, n, s, h; + return h = { + next: verb(0), + throw: verb(1), + return: verb(2) + }, typeof Symbol === "function" && (h[Symbol.iterator] = function() { + return this; + }), h; + function verb(e) { + return function(r) { + return step([ e, r ]); + }; + } + function step(a) { + if (i) throw new TypeError("Generator is already executing."); + while (h && (h = 0, a[0] && (t = 0)), t) try { + if (i = 1, n && (s = a[0] & 2 ? n["return"] : a[0] ? n["throw"] || ((s = n["return"]) && s.call(n), + 0) : n.next) && !(s = s.call(n, a[1])).done) return s; + if (n = 0, s) a = [ a[0] & 2, s.value ]; + switch (a[0]) { + case 0: + case 1: + s = a; + break; + + case 4: + t.label++; + return { + value: a[1], + done: false + }; + + case 5: + t.label++; + n = a[1]; + a = [ 0 ]; + continue; + + case 7: + a = t.ops.pop(); + t.trys.pop(); + continue; + + default: + if (!(s = t.trys, s = s.length > 0 && s[s.length - 1]) && (a[0] === 6 || a[0] === 2)) { + t = 0; + continue; + } + if (a[0] === 3 && (!s || a[1] > s[0] && a[1] < s[3])) { + t.label = a[1]; + break; + } + if (a[0] === 6 && t.label < s[1]) { + t.label = s[1]; + s = a; + break; + } + if (s && t.label < s[2]) { + t.label = s[2]; + t.ops.push(a); + break; + } + if (s[2]) t.ops.pop(); + t.trys.pop(); + continue; + } + a = r.call(e, t); + } catch (e) { + a = [ 6, e ]; + n = 0; + } finally { + i = s = 0; + } + if (a[0] & 5) throw a[1]; + return { + value: a[0] ? a[1] : void 0, + done: true + }; + } +} + +typeof SuppressedError === "function" ? SuppressedError : function(e, r, t) { + var i = new Error(t); + return i.name = "SuppressedError", i.error = e, i.suppressed = r, i; +}; + +var TreeNode = function() { + function TreeNode(e, r, t) { + if (t === void 0) { + t = 1; + } + this.t = undefined; + this.i = undefined; + this.h = undefined; + this.u = e; + this.o = r; + this.l = t; + } + TreeNode.prototype.v = function() { + var e = this; + var r = e.h.h === e; + if (r && e.l === 1) { + e = e.i; + } else if (e.t) { + e = e.t; + while (e.i) { + e = e.i; + } + } else { + if (r) { + return e.h; + } + var t = e.h; + while (t.t === e) { + e = t; + t = e.h; + } + e = t; + } + return e; + }; + TreeNode.prototype.p = function() { + var e = this; + if (e.i) { + e = e.i; + while (e.t) { + e = e.t; + } + return e; + } else { + var r = e.h; + while (r.i === e) { + e = r; + r = e.h; + } + if (e.i !== r) { + return r; + } else return e; + } + }; + TreeNode.prototype.T = function() { + var e = this.h; + var r = this.i; + var t = r.t; + if (e.h === this) e.h = r; else if (e.t === this) e.t = r; else e.i = r; + r.h = e; + r.t = this; + this.h = r; + this.i = t; + if (t) t.h = this; + return r; + }; + TreeNode.prototype.I = function() { + var e = this.h; + var r = this.t; + var t = r.i; + if (e.h === this) e.h = r; else if (e.t === this) e.t = r; else e.i = r; + r.h = e; + r.i = this; + this.h = r; + this.t = t; + if (t) t.h = this; + return r; + }; + return TreeNode; +}(); + +var TreeNodeEnableIndex = function(e) { + __extends(TreeNodeEnableIndex, e); + function TreeNodeEnableIndex() { + var r = e !== null && e.apply(this, arguments) || this; + r.O = 1; + return r; + } + TreeNodeEnableIndex.prototype.T = function() { + var r = e.prototype.T.call(this); + this.M(); + r.M(); + return r; + }; + TreeNodeEnableIndex.prototype.I = function() { + var r = e.prototype.I.call(this); + this.M(); + r.M(); + return r; + }; + TreeNodeEnableIndex.prototype.M = function() { + this.O = 1; + if (this.t) { + this.O += this.t.O; + } + if (this.i) { + this.O += this.i.O; + } + }; + return TreeNodeEnableIndex; +}(TreeNode); + +var ContainerIterator = function() { + function ContainerIterator(e) { + if (e === void 0) { + e = 0; + } + this.iteratorType = e; + } + ContainerIterator.prototype.equals = function(e) { + return this.C === e.C; + }; + return ContainerIterator; +}(); + +var Base = function() { + function Base() { + this._ = 0; + } + Object.defineProperty(Base.prototype, "length", { + get: function() { + return this._; + }, + enumerable: false, + configurable: true + }); + Base.prototype.size = function() { + return this._; + }; + Base.prototype.empty = function() { + return this._ === 0; + }; + return Base; +}(); + +var Container = function(e) { + __extends(Container, e); + function Container() { + return e !== null && e.apply(this, arguments) || this; + } + return Container; +}(Base); + +function throwIteratorAccessError() { + throw new RangeError("Iterator access denied!"); +} + +var TreeContainer = function(e) { + __extends(TreeContainer, e); + function TreeContainer(r, t) { + if (r === void 0) { + r = function(e, r) { + if (e < r) return -1; + if (e > r) return 1; + return 0; + }; + } + if (t === void 0) { + t = false; + } + var i = e.call(this) || this; + i.N = undefined; + i.g = r; + i.enableIndex = t; + i.S = t ? TreeNodeEnableIndex : TreeNode; + i.A = new i.S; + return i; + } + TreeContainer.prototype.m = function(e, r) { + var t = this.A; + while (e) { + var i = this.g(e.u, r); + if (i < 0) { + e = e.i; + } else if (i > 0) { + t = e; + e = e.t; + } else return e; + } + return t; + }; + TreeContainer.prototype.B = function(e, r) { + var t = this.A; + while (e) { + var i = this.g(e.u, r); + if (i <= 0) { + e = e.i; + } else { + t = e; + e = e.t; + } + } + return t; + }; + TreeContainer.prototype.j = function(e, r) { + var t = this.A; + while (e) { + var i = this.g(e.u, r); + if (i < 0) { + t = e; + e = e.i; + } else if (i > 0) { + e = e.t; + } else return e; + } + return t; + }; + TreeContainer.prototype.k = function(e, r) { + var t = this.A; + while (e) { + var i = this.g(e.u, r); + if (i < 0) { + t = e; + e = e.i; + } else { + e = e.t; + } + } + return t; + }; + TreeContainer.prototype.R = function(e) { + while (true) { + var r = e.h; + if (r === this.A) return; + if (e.l === 1) { + e.l = 0; + return; + } + if (e === r.t) { + var t = r.i; + if (t.l === 1) { + t.l = 0; + r.l = 1; + if (r === this.N) { + this.N = r.T(); + } else r.T(); + } else { + if (t.i && t.i.l === 1) { + t.l = r.l; + r.l = 0; + t.i.l = 0; + if (r === this.N) { + this.N = r.T(); + } else r.T(); + return; + } else if (t.t && t.t.l === 1) { + t.l = 1; + t.t.l = 0; + t.I(); + } else { + t.l = 1; + e = r; + } + } + } else { + var t = r.t; + if (t.l === 1) { + t.l = 0; + r.l = 1; + if (r === this.N) { + this.N = r.I(); + } else r.I(); + } else { + if (t.t && t.t.l === 1) { + t.l = r.l; + r.l = 0; + t.t.l = 0; + if (r === this.N) { + this.N = r.I(); + } else r.I(); + return; + } else if (t.i && t.i.l === 1) { + t.l = 1; + t.i.l = 0; + t.T(); + } else { + t.l = 1; + e = r; + } + } + } + } + }; + TreeContainer.prototype.G = function(e) { + if (this._ === 1) { + this.clear(); + return; + } + var r = e; + while (r.t || r.i) { + if (r.i) { + r = r.i; + while (r.t) r = r.t; + } else { + r = r.t; + } + var t = e.u; + e.u = r.u; + r.u = t; + var i = e.o; + e.o = r.o; + r.o = i; + e = r; + } + if (this.A.t === r) { + this.A.t = r.h; + } else if (this.A.i === r) { + this.A.i = r.h; + } + this.R(r); + var n = r.h; + if (r === n.t) { + n.t = undefined; + } else n.i = undefined; + this._ -= 1; + this.N.l = 0; + if (this.enableIndex) { + while (n !== this.A) { + n.O -= 1; + n = n.h; + } + } + }; + TreeContainer.prototype.P = function(e) { + var r = typeof e === "number" ? e : undefined; + var t = typeof e === "function" ? e : undefined; + var i = typeof e === "undefined" ? [] : undefined; + var n = 0; + var s = this.N; + var h = []; + while (h.length || s) { + if (s) { + h.push(s); + s = s.t; + } else { + s = h.pop(); + if (n === r) return s; + i && i.push(s); + t && t(s, n, this); + n += 1; + s = s.i; + } + } + return i; + }; + TreeContainer.prototype.q = function(e) { + while (true) { + var r = e.h; + if (r.l === 0) return; + var t = r.h; + if (r === t.t) { + var i = t.i; + if (i && i.l === 1) { + i.l = r.l = 0; + if (t === this.N) return; + t.l = 1; + e = t; + continue; + } else if (e === r.i) { + e.l = 0; + if (e.t) { + e.t.h = r; + } + if (e.i) { + e.i.h = t; + } + r.i = e.t; + t.t = e.i; + e.t = r; + e.i = t; + if (t === this.N) { + this.N = e; + this.A.h = e; + } else { + var n = t.h; + if (n.t === t) { + n.t = e; + } else n.i = e; + } + e.h = t.h; + r.h = e; + t.h = e; + t.l = 1; + } else { + r.l = 0; + if (t === this.N) { + this.N = t.I(); + } else t.I(); + t.l = 1; + return; + } + } else { + var i = t.t; + if (i && i.l === 1) { + i.l = r.l = 0; + if (t === this.N) return; + t.l = 1; + e = t; + continue; + } else if (e === r.t) { + e.l = 0; + if (e.t) { + e.t.h = t; + } + if (e.i) { + e.i.h = r; + } + t.i = e.t; + r.t = e.i; + e.t = t; + e.i = r; + if (t === this.N) { + this.N = e; + this.A.h = e; + } else { + var n = t.h; + if (n.t === t) { + n.t = e; + } else n.i = e; + } + e.h = t.h; + r.h = e; + t.h = e; + t.l = 1; + } else { + r.l = 0; + if (t === this.N) { + this.N = t.T(); + } else t.T(); + t.l = 1; + return; + } + } + if (this.enableIndex) { + r.M(); + t.M(); + e.M(); + } + return; + } + }; + TreeContainer.prototype.D = function(e, r, t) { + if (this.N === undefined) { + this._ += 1; + this.N = new this.S(e, r, 0); + this.N.h = this.A; + this.A.h = this.A.t = this.A.i = this.N; + return this._; + } + var i; + var n = this.A.t; + var s = this.g(n.u, e); + if (s === 0) { + n.o = r; + return this._; + } else if (s > 0) { + n.t = new this.S(e, r); + n.t.h = n; + i = n.t; + this.A.t = i; + } else { + var h = this.A.i; + var a = this.g(h.u, e); + if (a === 0) { + h.o = r; + return this._; + } else if (a < 0) { + h.i = new this.S(e, r); + h.i.h = h; + i = h.i; + this.A.i = i; + } else { + if (t !== undefined) { + var u = t.C; + if (u !== this.A) { + var f = this.g(u.u, e); + if (f === 0) { + u.o = r; + return this._; + } else if (f > 0) { + var o = u.v(); + var d = this.g(o.u, e); + if (d === 0) { + o.o = r; + return this._; + } else if (d < 0) { + i = new this.S(e, r); + if (o.i === undefined) { + o.i = i; + i.h = o; + } else { + u.t = i; + i.h = u; + } + } + } + } + } + if (i === undefined) { + i = this.N; + while (true) { + var c = this.g(i.u, e); + if (c > 0) { + if (i.t === undefined) { + i.t = new this.S(e, r); + i.t.h = i; + i = i.t; + break; + } + i = i.t; + } else if (c < 0) { + if (i.i === undefined) { + i.i = new this.S(e, r); + i.i.h = i; + i = i.i; + break; + } + i = i.i; + } else { + i.o = r; + return this._; + } + } + } + } + } + if (this.enableIndex) { + var l = i.h; + while (l !== this.A) { + l.O += 1; + l = l.h; + } + } + this.q(i); + this._ += 1; + return this._; + }; + TreeContainer.prototype.F = function(e, r) { + while (e) { + var t = this.g(e.u, r); + if (t < 0) { + e = e.i; + } else if (t > 0) { + e = e.t; + } else return e; + } + return e || this.A; + }; + TreeContainer.prototype.clear = function() { + this._ = 0; + this.N = undefined; + this.A.h = undefined; + this.A.t = this.A.i = undefined; + }; + TreeContainer.prototype.updateKeyByIterator = function(e, r) { + var t = e.C; + if (t === this.A) { + throwIteratorAccessError(); + } + if (this._ === 1) { + t.u = r; + return true; + } + var i = t.p().u; + if (t === this.A.t) { + if (this.g(i, r) > 0) { + t.u = r; + return true; + } + return false; + } + var n = t.v().u; + if (t === this.A.i) { + if (this.g(n, r) < 0) { + t.u = r; + return true; + } + return false; + } + if (this.g(n, r) >= 0 || this.g(i, r) <= 0) return false; + t.u = r; + return true; + }; + TreeContainer.prototype.eraseElementByPos = function(e) { + if (e < 0 || e > this._ - 1) { + throw new RangeError; + } + var r = this.P(e); + this.G(r); + return this._; + }; + TreeContainer.prototype.eraseElementByKey = function(e) { + if (this._ === 0) return false; + var r = this.F(this.N, e); + if (r === this.A) return false; + this.G(r); + return true; + }; + TreeContainer.prototype.eraseElementByIterator = function(e) { + var r = e.C; + if (r === this.A) { + throwIteratorAccessError(); + } + var t = r.i === undefined; + var i = e.iteratorType === 0; + if (i) { + if (t) e.next(); + } else { + if (!t || r.t === undefined) e.next(); + } + this.G(r); + return e; + }; + TreeContainer.prototype.getHeight = function() { + if (this._ === 0) return 0; + function traversal(e) { + if (!e) return 0; + return Math.max(traversal(e.t), traversal(e.i)) + 1; + } + return traversal(this.N); + }; + return TreeContainer; +}(Container); + +var TreeIterator = function(e) { + __extends(TreeIterator, e); + function TreeIterator(r, t, i) { + var n = e.call(this, i) || this; + n.C = r; + n.A = t; + if (n.iteratorType === 0) { + n.pre = function() { + if (this.C === this.A.t) { + throwIteratorAccessError(); + } + this.C = this.C.v(); + return this; + }; + n.next = function() { + if (this.C === this.A) { + throwIteratorAccessError(); + } + this.C = this.C.p(); + return this; + }; + } else { + n.pre = function() { + if (this.C === this.A.i) { + throwIteratorAccessError(); + } + this.C = this.C.p(); + return this; + }; + n.next = function() { + if (this.C === this.A) { + throwIteratorAccessError(); + } + this.C = this.C.v(); + return this; + }; + } + return n; + } + Object.defineProperty(TreeIterator.prototype, "index", { + get: function() { + var e = this.C; + var r = this.A.h; + if (e === this.A) { + if (r) { + return r.O - 1; + } + return 0; + } + var t = 0; + if (e.t) { + t += e.t.O; + } + while (e !== r) { + var i = e.h; + if (e === i.i) { + t += 1; + if (i.t) { + t += i.t.O; + } + } + e = i; + } + return t; + }, + enumerable: false, + configurable: true + }); + TreeIterator.prototype.isAccessible = function() { + return this.C !== this.A; + }; + return TreeIterator; +}(ContainerIterator); + +var OrderedMapIterator = function(e) { + __extends(OrderedMapIterator, e); + function OrderedMapIterator(r, t, i, n) { + var s = e.call(this, r, t, n) || this; + s.container = i; + return s; + } + Object.defineProperty(OrderedMapIterator.prototype, "pointer", { + get: function() { + if (this.C === this.A) { + throwIteratorAccessError(); + } + var e = this; + return new Proxy([], { + get: function(r, t) { + if (t === "0") return e.C.u; else if (t === "1") return e.C.o; + r[0] = e.C.u; + r[1] = e.C.o; + return r[t]; + }, + set: function(r, t, i) { + if (t !== "1") { + throw new TypeError("prop must be 1"); + } + e.C.o = i; + return true; + } + }); + }, + enumerable: false, + configurable: true + }); + OrderedMapIterator.prototype.copy = function() { + return new OrderedMapIterator(this.C, this.A, this.container, this.iteratorType); + }; + return OrderedMapIterator; +}(TreeIterator); + +var OrderedMap = function(e) { + __extends(OrderedMap, e); + function OrderedMap(r, t, i) { + if (r === void 0) { + r = []; + } + var n = e.call(this, t, i) || this; + var s = n; + r.forEach((function(e) { + s.setElement(e[0], e[1]); + })); + return n; + } + OrderedMap.prototype.begin = function() { + return new OrderedMapIterator(this.A.t || this.A, this.A, this); + }; + OrderedMap.prototype.end = function() { + return new OrderedMapIterator(this.A, this.A, this); + }; + OrderedMap.prototype.rBegin = function() { + return new OrderedMapIterator(this.A.i || this.A, this.A, this, 1); + }; + OrderedMap.prototype.rEnd = function() { + return new OrderedMapIterator(this.A, this.A, this, 1); + }; + OrderedMap.prototype.front = function() { + if (this._ === 0) return; + var e = this.A.t; + return [ e.u, e.o ]; + }; + OrderedMap.prototype.back = function() { + if (this._ === 0) return; + var e = this.A.i; + return [ e.u, e.o ]; + }; + OrderedMap.prototype.lowerBound = function(e) { + var r = this.m(this.N, e); + return new OrderedMapIterator(r, this.A, this); + }; + OrderedMap.prototype.upperBound = function(e) { + var r = this.B(this.N, e); + return new OrderedMapIterator(r, this.A, this); + }; + OrderedMap.prototype.reverseLowerBound = function(e) { + var r = this.j(this.N, e); + return new OrderedMapIterator(r, this.A, this); + }; + OrderedMap.prototype.reverseUpperBound = function(e) { + var r = this.k(this.N, e); + return new OrderedMapIterator(r, this.A, this); + }; + OrderedMap.prototype.forEach = function(e) { + this.P((function(r, t, i) { + e([ r.u, r.o ], t, i); + })); + }; + OrderedMap.prototype.setElement = function(e, r, t) { + return this.D(e, r, t); + }; + OrderedMap.prototype.getElementByPos = function(e) { + if (e < 0 || e > this._ - 1) { + throw new RangeError; + } + var r = this.P(e); + return [ r.u, r.o ]; + }; + OrderedMap.prototype.find = function(e) { + var r = this.F(this.N, e); + return new OrderedMapIterator(r, this.A, this); + }; + OrderedMap.prototype.getElementByKey = function(e) { + var r = this.F(this.N, e); + return r.o; + }; + OrderedMap.prototype.union = function(e) { + var r = this; + e.forEach((function(e) { + r.setElement(e[0], e[1]); + })); + return this._; + }; + OrderedMap.prototype[Symbol.iterator] = function() { + var e, r, t, i; + return __generator(this, (function(n) { + switch (n.label) { + case 0: + e = this._; + r = this.P(); + t = 0; + n.label = 1; + + case 1: + if (!(t < e)) return [ 3, 4 ]; + i = r[t]; + return [ 4, [ i.u, i.o ] ]; + + case 2: + n.sent(); + n.label = 3; + + case 3: + ++t; + return [ 3, 1 ]; + + case 4: + return [ 2 ]; + } + })); + }; + return OrderedMap; +}(TreeContainer); + +export { OrderedMap }; +//# sourceMappingURL=index.js.map diff --git a/node_modules/@js-sdsl/ordered-map/dist/esm/index.js.map b/node_modules/@js-sdsl/ordered-map/dist/esm/index.js.map new file mode 100644 index 0000000..3b8a588 --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../node_modules/tslib/tslib.es6.js","index.js","../../../.build-data/copied-source/src/container/TreeContainer/Base/TreeNode.ts","../../../.build-data/copied-source/src/container/ContainerBase/index.ts","../../../.build-data/copied-source/src/utils/throwError.ts","../../../.build-data/copied-source/src/container/TreeContainer/Base/index.ts","../../../.build-data/copied-source/src/container/TreeContainer/Base/TreeIterator.ts","../../../.build-data/copied-source/src/container/TreeContainer/OrderedMap.ts"],"names":["extendStatics","d","b","Object","setPrototypeOf","__proto__","Array","p","prototype","hasOwnProperty","call","__extends","TypeError","String","__","this","constructor","create","__generator","thisArg","body","_","label","sent","t","trys","ops","f","y","g","next","verb","throw","return","Symbol","iterator","n","v","step","op","done","value","pop","length","push","e","SuppressedError","error","suppressed","message","Error","name","TreeNode","key","color","_left","undefined","_right","_parent","_key","_value","_color","_pre","preNode","isRootOrHeader","pre","_next","nextNode","_rotateLeft","PP","V","R","_rotateRight","F","K","TreeNodeEnableIndex","_super","_this","apply","arguments","_subTreeSize","parent","_recount","ContainerIterator","iteratorType","equals","iter","_node","Base","_length","defineProperty","get","enumerable","configurable","size","empty","Container","throwIteratorAccessError","RangeError","TreeContainer","cmp","enableIndex","x","_root","_cmp","_TreeNodeClass","_header","_lowerBound","curNode","resNode","cmpResult","_upperBound","_reverseLowerBound","_reverseUpperBound","_eraseNodeSelfBalance","parentNode","brother","_eraseNode","clear","swapNode","_inOrderTraversal","param","pos","callback","nodeList","index","stack","_insertNodeSelfBalance","grandParent","uncle","GP","_set","hint","minNode","compareToMin","maxNode","compareToMax","iterNode","iterCmpRes","preCmpRes","parent_1","_getTreeNodeByKey","updateKeyByIterator","node","nextKey","preKey","eraseElementByPos","eraseElementByKey","eraseElementByIterator","hasNoRight","isNormal","getHeight","traversal","Math","max","TreeIterator","header","root","isAccessible","OrderedMapIterator","container","self","Proxy","target","prop","set","newValue","copy","OrderedMap","forEach","el","setElement","begin","end","rBegin","rEnd","front","back","lowerBound","upperBound","reverseLowerBound","reverseUpperBound","map","getElementByPos","find","getElementByKey","union","other","i","_a"],"mappings":"AAgBA,IAAIA,gBAAgB,SAASC,GAAGC;IAC5BF,gBAAgBG,OAAOC,kBAClB;QAAEC,WAAW;iBAAgBC,SAAS,SAAUL,GAAGC;QAAKD,EAAEI,YAAYH;AAAG,SAC1E,SAAUD,GAAGC;QAAK,KAAK,IAAIK,KAAKL,GAAG,IAAIC,OAAOK,UAAUC,eAAeC,KAAKR,GAAGK,IAAIN,EAAEM,KAAKL,EAAEK;ACIlG;IDHE,OAAOP,cAAcC,GAAGC;AAC5B;;AAEO,SAASS,UAAUV,GAAGC;IACzB,WAAWA,MAAM,cAAcA,MAAM,MACjC,MAAM,IAAIU,UAAU,yBAAyBC,OAAOX,KAAK;IAC7DF,cAAcC,GAAGC;IACjB,SAASY;QAAOC,KAAKC,cAAcf;AAAG;IACtCA,EAAEO,YAAYN,MAAM,OAAOC,OAAOc,OAAOf,MAAM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J,KAAK0E;ANm7Bd;IMj7BE+E,WAAAhK,UAAC0B,OAAOC,YAAV;QNm7BE,IAAIQ,GAAQiF,GAAUgE,GAAG7C;QACzB,OAAO7H,YAAYH,OAAM,SAAU8K;YACjC,QAAQA,EAAGvK;cACT,KAAK;gBMr7BHqB,IAAS5B,KAAK0E;gBACdmC,IAAW7G,KAAKyG;gBACboE,IAAI;gBNu7BPC,EAAGvK,QAAQ;;cACb,KAAK;gBACH,MMz7BUsK,IAAIjJ,IAAM,OAAA,EAAA,GAAA;gBAClBoG,IAAOnB,EAASgE;gBACtB,OAAc,EAAA,GAAA,EAAC7C,EAAKpF,GAAMoF,EAAKnF;;cN07B7B,KAAK;gBM17BPiI,EAAAtK;gBN47BIsK,EAAGvK,QAAQ;;cACb,KAAK;kBM/7BqBsK;gBNi8BxB,OAAO,EAAC,GAAa;;cACvB,KAAK;gBACH,OAAO,EAAC;;AAEd;AACF;IM/7BF,OAACpB;AAAD,CAzHA,CAA+BrE;;SN6jCtBqE","file":"index.js","sourcesContent":["/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends,\r\n __assign,\r\n __rest,\r\n __decorate,\r\n __param,\r\n __metadata,\r\n __awaiter,\r\n __generator,\r\n __createBinding,\r\n __exportStar,\r\n __values,\r\n __read,\r\n __spread,\r\n __spreadArrays,\r\n __spreadArray,\r\n __await,\r\n __asyncGenerator,\r\n __asyncDelegator,\r\n __asyncValues,\r\n __makeTemplateObject,\r\n __importStar,\r\n __importDefault,\r\n __classPrivateFieldGet,\r\n __classPrivateFieldSet,\r\n __classPrivateFieldIn,\r\n __addDisposableResource,\r\n __disposeResources,\r\n};\r\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol */\n\nvar extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf || {\n __proto__: []\n } instanceof Array && function (d, b) {\n d.__proto__ = b;\n } || function (d, b) {\n for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];\n };\n return extendStatics(d, b);\n};\nfunction __extends(d, b) {\n if (typeof b !== \"function\" && b !== null) throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() {\n this.constructor = d;\n }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\nfunction __generator(thisArg, body) {\n var _ = {\n label: 0,\n sent: function () {\n if (t[0] & 1) throw t[1];\n return t[1];\n },\n trys: [],\n ops: []\n },\n f,\n y,\n t,\n g;\n return g = {\n next: verb(0),\n \"throw\": verb(1),\n \"return\": verb(2)\n }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function () {\n return this;\n }), g;\n function verb(n) {\n return function (v) {\n return step([n, v]);\n };\n }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0:\n case 1:\n t = op;\n break;\n case 4:\n _.label++;\n return {\n value: op[1],\n done: false\n };\n case 5:\n _.label++;\n y = op[1];\n op = [0];\n continue;\n case 7:\n op = _.ops.pop();\n _.trys.pop();\n continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {\n _ = 0;\n continue;\n }\n if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {\n _.label = op[1];\n break;\n }\n if (op[0] === 6 && _.label < t[1]) {\n _.label = t[1];\n t = op;\n break;\n }\n if (t && _.label < t[2]) {\n _.label = t[2];\n _.ops.push(op);\n break;\n }\n if (t[2]) _.ops.pop();\n _.trys.pop();\n continue;\n }\n op = body.call(thisArg, _);\n } catch (e) {\n op = [6, e];\n y = 0;\n } finally {\n f = t = 0;\n }\n if (op[0] & 5) throw op[1];\n return {\n value: op[0] ? op[1] : void 0,\n done: true\n };\n }\n}\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nvar TreeNode = /** @class */function () {\n function TreeNode(key, value, color) {\n if (color === void 0) {\n color = 1 /* TreeNodeColor.RED */;\n }\n this._left = undefined;\n this._right = undefined;\n this._parent = undefined;\n this._key = key;\n this._value = value;\n this._color = color;\n }\n /**\n * @description Get the pre node.\n * @returns TreeNode about the pre node.\n */\n TreeNode.prototype._pre = function () {\n var preNode = this;\n var isRootOrHeader = preNode._parent._parent === preNode;\n if (isRootOrHeader && preNode._color === 1 /* TreeNodeColor.RED */) {\n preNode = preNode._right;\n } else if (preNode._left) {\n preNode = preNode._left;\n while (preNode._right) {\n preNode = preNode._right;\n }\n } else {\n // Must be root and left is null\n if (isRootOrHeader) {\n return preNode._parent;\n }\n var pre = preNode._parent;\n while (pre._left === preNode) {\n preNode = pre;\n pre = preNode._parent;\n }\n preNode = pre;\n }\n return preNode;\n };\n /**\n * @description Get the next node.\n * @returns TreeNode about the next node.\n */\n TreeNode.prototype._next = function () {\n var nextNode = this;\n if (nextNode._right) {\n nextNode = nextNode._right;\n while (nextNode._left) {\n nextNode = nextNode._left;\n }\n return nextNode;\n } else {\n var pre = nextNode._parent;\n while (pre._right === nextNode) {\n nextNode = pre;\n pre = nextNode._parent;\n }\n if (nextNode._right !== pre) {\n return pre;\n } else return nextNode;\n }\n };\n /**\n * @description Rotate left.\n * @returns TreeNode about moved to original position after rotation.\n */\n TreeNode.prototype._rotateLeft = function () {\n var PP = this._parent;\n var V = this._right;\n var R = V._left;\n if (PP._parent === this) PP._parent = V;else if (PP._left === this) PP._left = V;else PP._right = V;\n V._parent = PP;\n V._left = this;\n this._parent = V;\n this._right = R;\n if (R) R._parent = this;\n return V;\n };\n /**\n * @description Rotate right.\n * @returns TreeNode about moved to original position after rotation.\n */\n TreeNode.prototype._rotateRight = function () {\n var PP = this._parent;\n var F = this._left;\n var K = F._right;\n if (PP._parent === this) PP._parent = F;else if (PP._left === this) PP._left = F;else PP._right = F;\n F._parent = PP;\n F._right = this;\n this._parent = F;\n this._left = K;\n if (K) K._parent = this;\n return F;\n };\n return TreeNode;\n}();\nvar TreeNodeEnableIndex = /** @class */function (_super) {\n __extends(TreeNodeEnableIndex, _super);\n function TreeNodeEnableIndex() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this._subTreeSize = 1;\n return _this;\n }\n /**\n * @description Rotate left and do recount.\n * @returns TreeNode about moved to original position after rotation.\n */\n TreeNodeEnableIndex.prototype._rotateLeft = function () {\n var parent = _super.prototype._rotateLeft.call(this);\n this._recount();\n parent._recount();\n return parent;\n };\n /**\n * @description Rotate right and do recount.\n * @returns TreeNode about moved to original position after rotation.\n */\n TreeNodeEnableIndex.prototype._rotateRight = function () {\n var parent = _super.prototype._rotateRight.call(this);\n this._recount();\n parent._recount();\n return parent;\n };\n TreeNodeEnableIndex.prototype._recount = function () {\n this._subTreeSize = 1;\n if (this._left) {\n this._subTreeSize += this._left._subTreeSize;\n }\n if (this._right) {\n this._subTreeSize += this._right._subTreeSize;\n }\n };\n return TreeNodeEnableIndex;\n}(TreeNode);\n\nvar ContainerIterator = /** @class */function () {\n /**\n * @internal\n */\n function ContainerIterator(iteratorType) {\n if (iteratorType === void 0) {\n iteratorType = 0 /* IteratorType.NORMAL */;\n }\n this.iteratorType = iteratorType;\n }\n /**\n * @param iter - The other iterator you want to compare.\n * @returns Whether this equals to obj.\n * @example\n * container.find(1).equals(container.end());\n */\n ContainerIterator.prototype.equals = function (iter) {\n return this._node === iter._node;\n };\n return ContainerIterator;\n}();\nvar Base = /** @class */function () {\n function Base() {\n /**\n * @description Container's size.\n * @internal\n */\n this._length = 0;\n }\n Object.defineProperty(Base.prototype, \"length\", {\n /**\n * @returns The size of the container.\n * @example\n * const container = new Vector([1, 2]);\n * console.log(container.length); // 2\n */\n get: function () {\n return this._length;\n },\n enumerable: false,\n configurable: true\n });\n /**\n * @returns The size of the container.\n * @example\n * const container = new Vector([1, 2]);\n * console.log(container.size()); // 2\n */\n Base.prototype.size = function () {\n return this._length;\n };\n /**\n * @returns Whether the container is empty.\n * @example\n * container.clear();\n * console.log(container.empty()); // true\n */\n Base.prototype.empty = function () {\n return this._length === 0;\n };\n return Base;\n}();\nvar Container = /** @class */function (_super) {\n __extends(Container, _super);\n function Container() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n return Container;\n}(Base);\n\n/**\n * @description Throw an iterator access error.\n * @internal\n */\nfunction throwIteratorAccessError() {\n throw new RangeError('Iterator access denied!');\n}\n\nvar TreeContainer = /** @class */function (_super) {\n __extends(TreeContainer, _super);\n /**\n * @internal\n */\n function TreeContainer(cmp, enableIndex) {\n if (cmp === void 0) {\n cmp = function (x, y) {\n if (x < y) return -1;\n if (x > y) return 1;\n return 0;\n };\n }\n if (enableIndex === void 0) {\n enableIndex = false;\n }\n var _this = _super.call(this) || this;\n /**\n * @internal\n */\n _this._root = undefined;\n _this._cmp = cmp;\n _this.enableIndex = enableIndex;\n _this._TreeNodeClass = enableIndex ? TreeNodeEnableIndex : TreeNode;\n _this._header = new _this._TreeNodeClass();\n return _this;\n }\n /**\n * @internal\n */\n TreeContainer.prototype._lowerBound = function (curNode, key) {\n var resNode = this._header;\n while (curNode) {\n var cmpResult = this._cmp(curNode._key, key);\n if (cmpResult < 0) {\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n resNode = curNode;\n curNode = curNode._left;\n } else return curNode;\n }\n return resNode;\n };\n /**\n * @internal\n */\n TreeContainer.prototype._upperBound = function (curNode, key) {\n var resNode = this._header;\n while (curNode) {\n var cmpResult = this._cmp(curNode._key, key);\n if (cmpResult <= 0) {\n curNode = curNode._right;\n } else {\n resNode = curNode;\n curNode = curNode._left;\n }\n }\n return resNode;\n };\n /**\n * @internal\n */\n TreeContainer.prototype._reverseLowerBound = function (curNode, key) {\n var resNode = this._header;\n while (curNode) {\n var cmpResult = this._cmp(curNode._key, key);\n if (cmpResult < 0) {\n resNode = curNode;\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n curNode = curNode._left;\n } else return curNode;\n }\n return resNode;\n };\n /**\n * @internal\n */\n TreeContainer.prototype._reverseUpperBound = function (curNode, key) {\n var resNode = this._header;\n while (curNode) {\n var cmpResult = this._cmp(curNode._key, key);\n if (cmpResult < 0) {\n resNode = curNode;\n curNode = curNode._right;\n } else {\n curNode = curNode._left;\n }\n }\n return resNode;\n };\n /**\n * @internal\n */\n TreeContainer.prototype._eraseNodeSelfBalance = function (curNode) {\n while (true) {\n var parentNode = curNode._parent;\n if (parentNode === this._header) return;\n if (curNode._color === 1 /* TreeNodeColor.RED */) {\n curNode._color = 0 /* TreeNodeColor.BLACK */;\n return;\n }\n if (curNode === parentNode._left) {\n var brother = parentNode._right;\n if (brother._color === 1 /* TreeNodeColor.RED */) {\n brother._color = 0 /* TreeNodeColor.BLACK */;\n parentNode._color = 1 /* TreeNodeColor.RED */;\n if (parentNode === this._root) {\n this._root = parentNode._rotateLeft();\n } else parentNode._rotateLeft();\n } else {\n if (brother._right && brother._right._color === 1 /* TreeNodeColor.RED */) {\n brother._color = parentNode._color;\n parentNode._color = 0 /* TreeNodeColor.BLACK */;\n brother._right._color = 0 /* TreeNodeColor.BLACK */;\n if (parentNode === this._root) {\n this._root = parentNode._rotateLeft();\n } else parentNode._rotateLeft();\n return;\n } else if (brother._left && brother._left._color === 1 /* TreeNodeColor.RED */) {\n brother._color = 1 /* TreeNodeColor.RED */;\n brother._left._color = 0 /* TreeNodeColor.BLACK */;\n brother._rotateRight();\n } else {\n brother._color = 1 /* TreeNodeColor.RED */;\n curNode = parentNode;\n }\n }\n } else {\n var brother = parentNode._left;\n if (brother._color === 1 /* TreeNodeColor.RED */) {\n brother._color = 0 /* TreeNodeColor.BLACK */;\n parentNode._color = 1 /* TreeNodeColor.RED */;\n if (parentNode === this._root) {\n this._root = parentNode._rotateRight();\n } else parentNode._rotateRight();\n } else {\n if (brother._left && brother._left._color === 1 /* TreeNodeColor.RED */) {\n brother._color = parentNode._color;\n parentNode._color = 0 /* TreeNodeColor.BLACK */;\n brother._left._color = 0 /* TreeNodeColor.BLACK */;\n if (parentNode === this._root) {\n this._root = parentNode._rotateRight();\n } else parentNode._rotateRight();\n return;\n } else if (brother._right && brother._right._color === 1 /* TreeNodeColor.RED */) {\n brother._color = 1 /* TreeNodeColor.RED */;\n brother._right._color = 0 /* TreeNodeColor.BLACK */;\n brother._rotateLeft();\n } else {\n brother._color = 1 /* TreeNodeColor.RED */;\n curNode = parentNode;\n }\n }\n }\n }\n };\n /**\n * @internal\n */\n TreeContainer.prototype._eraseNode = function (curNode) {\n if (this._length === 1) {\n this.clear();\n return;\n }\n var swapNode = curNode;\n while (swapNode._left || swapNode._right) {\n if (swapNode._right) {\n swapNode = swapNode._right;\n while (swapNode._left) swapNode = swapNode._left;\n } else {\n swapNode = swapNode._left;\n }\n var key = curNode._key;\n curNode._key = swapNode._key;\n swapNode._key = key;\n var value = curNode._value;\n curNode._value = swapNode._value;\n swapNode._value = value;\n curNode = swapNode;\n }\n if (this._header._left === swapNode) {\n this._header._left = swapNode._parent;\n } else if (this._header._right === swapNode) {\n this._header._right = swapNode._parent;\n }\n this._eraseNodeSelfBalance(swapNode);\n var _parent = swapNode._parent;\n if (swapNode === _parent._left) {\n _parent._left = undefined;\n } else _parent._right = undefined;\n this._length -= 1;\n this._root._color = 0 /* TreeNodeColor.BLACK */;\n if (this.enableIndex) {\n while (_parent !== this._header) {\n _parent._subTreeSize -= 1;\n _parent = _parent._parent;\n }\n }\n };\n /**\n * @internal\n */\n TreeContainer.prototype._inOrderTraversal = function (param) {\n var pos = typeof param === 'number' ? param : undefined;\n var callback = typeof param === 'function' ? param : undefined;\n var nodeList = typeof param === 'undefined' ? [] : undefined;\n var index = 0;\n var curNode = this._root;\n var stack = [];\n while (stack.length || curNode) {\n if (curNode) {\n stack.push(curNode);\n curNode = curNode._left;\n } else {\n curNode = stack.pop();\n if (index === pos) return curNode;\n nodeList && nodeList.push(curNode);\n callback && callback(curNode, index, this);\n index += 1;\n curNode = curNode._right;\n }\n }\n return nodeList;\n };\n /**\n * @internal\n */\n TreeContainer.prototype._insertNodeSelfBalance = function (curNode) {\n while (true) {\n var parentNode = curNode._parent;\n if (parentNode._color === 0 /* TreeNodeColor.BLACK */) return;\n var grandParent = parentNode._parent;\n if (parentNode === grandParent._left) {\n var uncle = grandParent._right;\n if (uncle && uncle._color === 1 /* TreeNodeColor.RED */) {\n uncle._color = parentNode._color = 0 /* TreeNodeColor.BLACK */;\n if (grandParent === this._root) return;\n grandParent._color = 1 /* TreeNodeColor.RED */;\n curNode = grandParent;\n continue;\n } else if (curNode === parentNode._right) {\n curNode._color = 0 /* TreeNodeColor.BLACK */;\n if (curNode._left) {\n curNode._left._parent = parentNode;\n }\n if (curNode._right) {\n curNode._right._parent = grandParent;\n }\n parentNode._right = curNode._left;\n grandParent._left = curNode._right;\n curNode._left = parentNode;\n curNode._right = grandParent;\n if (grandParent === this._root) {\n this._root = curNode;\n this._header._parent = curNode;\n } else {\n var GP = grandParent._parent;\n if (GP._left === grandParent) {\n GP._left = curNode;\n } else GP._right = curNode;\n }\n curNode._parent = grandParent._parent;\n parentNode._parent = curNode;\n grandParent._parent = curNode;\n grandParent._color = 1 /* TreeNodeColor.RED */;\n } else {\n parentNode._color = 0 /* TreeNodeColor.BLACK */;\n if (grandParent === this._root) {\n this._root = grandParent._rotateRight();\n } else grandParent._rotateRight();\n grandParent._color = 1 /* TreeNodeColor.RED */;\n return;\n }\n } else {\n var uncle = grandParent._left;\n if (uncle && uncle._color === 1 /* TreeNodeColor.RED */) {\n uncle._color = parentNode._color = 0 /* TreeNodeColor.BLACK */;\n if (grandParent === this._root) return;\n grandParent._color = 1 /* TreeNodeColor.RED */;\n curNode = grandParent;\n continue;\n } else if (curNode === parentNode._left) {\n curNode._color = 0 /* TreeNodeColor.BLACK */;\n if (curNode._left) {\n curNode._left._parent = grandParent;\n }\n if (curNode._right) {\n curNode._right._parent = parentNode;\n }\n grandParent._right = curNode._left;\n parentNode._left = curNode._right;\n curNode._left = grandParent;\n curNode._right = parentNode;\n if (grandParent === this._root) {\n this._root = curNode;\n this._header._parent = curNode;\n } else {\n var GP = grandParent._parent;\n if (GP._left === grandParent) {\n GP._left = curNode;\n } else GP._right = curNode;\n }\n curNode._parent = grandParent._parent;\n parentNode._parent = curNode;\n grandParent._parent = curNode;\n grandParent._color = 1 /* TreeNodeColor.RED */;\n } else {\n parentNode._color = 0 /* TreeNodeColor.BLACK */;\n if (grandParent === this._root) {\n this._root = grandParent._rotateLeft();\n } else grandParent._rotateLeft();\n grandParent._color = 1 /* TreeNodeColor.RED */;\n return;\n }\n }\n if (this.enableIndex) {\n parentNode._recount();\n grandParent._recount();\n curNode._recount();\n }\n return;\n }\n };\n /**\n * @internal\n */\n TreeContainer.prototype._set = function (key, value, hint) {\n if (this._root === undefined) {\n this._length += 1;\n this._root = new this._TreeNodeClass(key, value, 0 /* TreeNodeColor.BLACK */);\n this._root._parent = this._header;\n this._header._parent = this._header._left = this._header._right = this._root;\n return this._length;\n }\n var curNode;\n var minNode = this._header._left;\n var compareToMin = this._cmp(minNode._key, key);\n if (compareToMin === 0) {\n minNode._value = value;\n return this._length;\n } else if (compareToMin > 0) {\n minNode._left = new this._TreeNodeClass(key, value);\n minNode._left._parent = minNode;\n curNode = minNode._left;\n this._header._left = curNode;\n } else {\n var maxNode = this._header._right;\n var compareToMax = this._cmp(maxNode._key, key);\n if (compareToMax === 0) {\n maxNode._value = value;\n return this._length;\n } else if (compareToMax < 0) {\n maxNode._right = new this._TreeNodeClass(key, value);\n maxNode._right._parent = maxNode;\n curNode = maxNode._right;\n this._header._right = curNode;\n } else {\n if (hint !== undefined) {\n var iterNode = hint._node;\n if (iterNode !== this._header) {\n var iterCmpRes = this._cmp(iterNode._key, key);\n if (iterCmpRes === 0) {\n iterNode._value = value;\n return this._length;\n } else /* istanbul ignore else */if (iterCmpRes > 0) {\n var preNode = iterNode._pre();\n var preCmpRes = this._cmp(preNode._key, key);\n if (preCmpRes === 0) {\n preNode._value = value;\n return this._length;\n } else if (preCmpRes < 0) {\n curNode = new this._TreeNodeClass(key, value);\n if (preNode._right === undefined) {\n preNode._right = curNode;\n curNode._parent = preNode;\n } else {\n iterNode._left = curNode;\n curNode._parent = iterNode;\n }\n }\n }\n }\n }\n if (curNode === undefined) {\n curNode = this._root;\n while (true) {\n var cmpResult = this._cmp(curNode._key, key);\n if (cmpResult > 0) {\n if (curNode._left === undefined) {\n curNode._left = new this._TreeNodeClass(key, value);\n curNode._left._parent = curNode;\n curNode = curNode._left;\n break;\n }\n curNode = curNode._left;\n } else if (cmpResult < 0) {\n if (curNode._right === undefined) {\n curNode._right = new this._TreeNodeClass(key, value);\n curNode._right._parent = curNode;\n curNode = curNode._right;\n break;\n }\n curNode = curNode._right;\n } else {\n curNode._value = value;\n return this._length;\n }\n }\n }\n }\n }\n if (this.enableIndex) {\n var parent_1 = curNode._parent;\n while (parent_1 !== this._header) {\n parent_1._subTreeSize += 1;\n parent_1 = parent_1._parent;\n }\n }\n this._insertNodeSelfBalance(curNode);\n this._length += 1;\n return this._length;\n };\n /**\n * @internal\n */\n TreeContainer.prototype._getTreeNodeByKey = function (curNode, key) {\n while (curNode) {\n var cmpResult = this._cmp(curNode._key, key);\n if (cmpResult < 0) {\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n curNode = curNode._left;\n } else return curNode;\n }\n return curNode || this._header;\n };\n TreeContainer.prototype.clear = function () {\n this._length = 0;\n this._root = undefined;\n this._header._parent = undefined;\n this._header._left = this._header._right = undefined;\n };\n /**\n * @description Update node's key by iterator.\n * @param iter - The iterator you want to change.\n * @param key - The key you want to update.\n * @returns Whether the modification is successful.\n * @example\n * const st = new orderedSet([1, 2, 5]);\n * const iter = st.find(2);\n * st.updateKeyByIterator(iter, 3); // then st will become [1, 3, 5]\n */\n TreeContainer.prototype.updateKeyByIterator = function (iter, key) {\n var node = iter._node;\n if (node === this._header) {\n throwIteratorAccessError();\n }\n if (this._length === 1) {\n node._key = key;\n return true;\n }\n var nextKey = node._next()._key;\n if (node === this._header._left) {\n if (this._cmp(nextKey, key) > 0) {\n node._key = key;\n return true;\n }\n return false;\n }\n var preKey = node._pre()._key;\n if (node === this._header._right) {\n if (this._cmp(preKey, key) < 0) {\n node._key = key;\n return true;\n }\n return false;\n }\n if (this._cmp(preKey, key) >= 0 || this._cmp(nextKey, key) <= 0) return false;\n node._key = key;\n return true;\n };\n TreeContainer.prototype.eraseElementByPos = function (pos) {\n if (pos < 0 || pos > this._length - 1) {\n throw new RangeError();\n }\n var node = this._inOrderTraversal(pos);\n this._eraseNode(node);\n return this._length;\n };\n /**\n * @description Remove the element of the specified key.\n * @param key - The key you want to remove.\n * @returns Whether erase successfully.\n */\n TreeContainer.prototype.eraseElementByKey = function (key) {\n if (this._length === 0) return false;\n var curNode = this._getTreeNodeByKey(this._root, key);\n if (curNode === this._header) return false;\n this._eraseNode(curNode);\n return true;\n };\n TreeContainer.prototype.eraseElementByIterator = function (iter) {\n var node = iter._node;\n if (node === this._header) {\n throwIteratorAccessError();\n }\n var hasNoRight = node._right === undefined;\n var isNormal = iter.iteratorType === 0 /* IteratorType.NORMAL */;\n // For the normal iterator, the `next` node will be swapped to `this` node when has right.\n if (isNormal) {\n // So we should move it to next when it's right is null.\n if (hasNoRight) iter.next();\n } else {\n // For the reverse iterator, only when it doesn't have right and has left the `next` node will be swapped.\n // So when it has right, or it is a leaf node we should move it to `next`.\n if (!hasNoRight || node._left === undefined) iter.next();\n }\n this._eraseNode(node);\n return iter;\n };\n /**\n * @description Get the height of the tree.\n * @returns Number about the height of the RB-tree.\n */\n TreeContainer.prototype.getHeight = function () {\n if (this._length === 0) return 0;\n function traversal(curNode) {\n if (!curNode) return 0;\n return Math.max(traversal(curNode._left), traversal(curNode._right)) + 1;\n }\n return traversal(this._root);\n };\n return TreeContainer;\n}(Container);\n\nvar TreeIterator = /** @class */function (_super) {\n __extends(TreeIterator, _super);\n /**\n * @internal\n */\n function TreeIterator(node, header, iteratorType) {\n var _this = _super.call(this, iteratorType) || this;\n _this._node = node;\n _this._header = header;\n if (_this.iteratorType === 0 /* IteratorType.NORMAL */) {\n _this.pre = function () {\n if (this._node === this._header._left) {\n throwIteratorAccessError();\n }\n this._node = this._node._pre();\n return this;\n };\n _this.next = function () {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n this._node = this._node._next();\n return this;\n };\n } else {\n _this.pre = function () {\n if (this._node === this._header._right) {\n throwIteratorAccessError();\n }\n this._node = this._node._next();\n return this;\n };\n _this.next = function () {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n this._node = this._node._pre();\n return this;\n };\n }\n return _this;\n }\n Object.defineProperty(TreeIterator.prototype, \"index\", {\n /**\n * @description Get the sequential index of the iterator in the tree container.
\n * Note:\n * This function only takes effect when the specified tree container `enableIndex = true`.\n * @returns The index subscript of the node in the tree.\n * @example\n * const st = new OrderedSet([1, 2, 3], true);\n * console.log(st.begin().next().index); // 1\n */\n get: function () {\n var _node = this._node;\n var root = this._header._parent;\n if (_node === this._header) {\n if (root) {\n return root._subTreeSize - 1;\n }\n return 0;\n }\n var index = 0;\n if (_node._left) {\n index += _node._left._subTreeSize;\n }\n while (_node !== root) {\n var _parent = _node._parent;\n if (_node === _parent._right) {\n index += 1;\n if (_parent._left) {\n index += _parent._left._subTreeSize;\n }\n }\n _node = _parent;\n }\n return index;\n },\n enumerable: false,\n configurable: true\n });\n TreeIterator.prototype.isAccessible = function () {\n return this._node !== this._header;\n };\n return TreeIterator;\n}(ContainerIterator);\n\nvar OrderedMapIterator = /** @class */function (_super) {\n __extends(OrderedMapIterator, _super);\n function OrderedMapIterator(node, header, container, iteratorType) {\n var _this = _super.call(this, node, header, iteratorType) || this;\n _this.container = container;\n return _this;\n }\n Object.defineProperty(OrderedMapIterator.prototype, \"pointer\", {\n get: function () {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n var self = this;\n return new Proxy([], {\n get: function (target, prop) {\n if (prop === '0') return self._node._key;else if (prop === '1') return self._node._value;\n target[0] = self._node._key;\n target[1] = self._node._value;\n return target[prop];\n },\n set: function (_, prop, newValue) {\n if (prop !== '1') {\n throw new TypeError('prop must be 1');\n }\n self._node._value = newValue;\n return true;\n }\n });\n },\n enumerable: false,\n configurable: true\n });\n OrderedMapIterator.prototype.copy = function () {\n return new OrderedMapIterator(this._node, this._header, this.container, this.iteratorType);\n };\n return OrderedMapIterator;\n}(TreeIterator);\nvar OrderedMap = /** @class */function (_super) {\n __extends(OrderedMap, _super);\n /**\n * @param container - The initialization container.\n * @param cmp - The compare function.\n * @param enableIndex - Whether to enable iterator indexing function.\n * @example\n * new OrderedMap();\n * new OrderedMap([[0, 1], [2, 1]]);\n * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y);\n * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y, true);\n */\n function OrderedMap(container, cmp, enableIndex) {\n if (container === void 0) {\n container = [];\n }\n var _this = _super.call(this, cmp, enableIndex) || this;\n var self = _this;\n container.forEach(function (el) {\n self.setElement(el[0], el[1]);\n });\n return _this;\n }\n OrderedMap.prototype.begin = function () {\n return new OrderedMapIterator(this._header._left || this._header, this._header, this);\n };\n OrderedMap.prototype.end = function () {\n return new OrderedMapIterator(this._header, this._header, this);\n };\n OrderedMap.prototype.rBegin = function () {\n return new OrderedMapIterator(this._header._right || this._header, this._header, this, 1 /* IteratorType.REVERSE */);\n };\n\n OrderedMap.prototype.rEnd = function () {\n return new OrderedMapIterator(this._header, this._header, this, 1 /* IteratorType.REVERSE */);\n };\n\n OrderedMap.prototype.front = function () {\n if (this._length === 0) return;\n var minNode = this._header._left;\n return [minNode._key, minNode._value];\n };\n OrderedMap.prototype.back = function () {\n if (this._length === 0) return;\n var maxNode = this._header._right;\n return [maxNode._key, maxNode._value];\n };\n OrderedMap.prototype.lowerBound = function (key) {\n var resNode = this._lowerBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n };\n OrderedMap.prototype.upperBound = function (key) {\n var resNode = this._upperBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n };\n OrderedMap.prototype.reverseLowerBound = function (key) {\n var resNode = this._reverseLowerBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n };\n OrderedMap.prototype.reverseUpperBound = function (key) {\n var resNode = this._reverseUpperBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n };\n OrderedMap.prototype.forEach = function (callback) {\n this._inOrderTraversal(function (node, index, map) {\n callback([node._key, node._value], index, map);\n });\n };\n /**\n * @description Insert a key-value pair or set value by the given key.\n * @param key - The key want to insert.\n * @param value - The value want to set.\n * @param hint - You can give an iterator hint to improve insertion efficiency.\n * @return The size of container after setting.\n * @example\n * const mp = new OrderedMap([[2, 0], [4, 0], [5, 0]]);\n * const iter = mp.begin();\n * mp.setElement(1, 0);\n * mp.setElement(3, 0, iter); // give a hint will be faster.\n */\n OrderedMap.prototype.setElement = function (key, value, hint) {\n return this._set(key, value, hint);\n };\n OrderedMap.prototype.getElementByPos = function (pos) {\n if (pos < 0 || pos > this._length - 1) {\n throw new RangeError();\n }\n var node = this._inOrderTraversal(pos);\n return [node._key, node._value];\n };\n OrderedMap.prototype.find = function (key) {\n var curNode = this._getTreeNodeByKey(this._root, key);\n return new OrderedMapIterator(curNode, this._header, this);\n };\n /**\n * @description Get the value of the element of the specified key.\n * @param key - The specified key you want to get.\n * @example\n * const val = container.getElementByKey(1);\n */\n OrderedMap.prototype.getElementByKey = function (key) {\n var curNode = this._getTreeNodeByKey(this._root, key);\n return curNode._value;\n };\n OrderedMap.prototype.union = function (other) {\n var self = this;\n other.forEach(function (el) {\n self.setElement(el[0], el[1]);\n });\n return this._length;\n };\n OrderedMap.prototype[Symbol.iterator] = function () {\n var length, nodeList, i, node;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n length = this._length;\n nodeList = this._inOrderTraversal();\n i = 0;\n _a.label = 1;\n case 1:\n if (!(i < length)) return [3 /*break*/, 4];\n node = nodeList[i];\n return [4 /*yield*/, [node._key, node._value]];\n case 2:\n _a.sent();\n _a.label = 3;\n case 3:\n ++i;\n return [3 /*break*/, 1];\n case 4:\n return [2 /*return*/];\n }\n });\n };\n\n return OrderedMap;\n}(TreeContainer);\n\nexport { OrderedMap };\n//# sourceMappingURL=index.js.map\n","export const enum TreeNodeColor {\n RED = 1,\n BLACK = 0\n}\n\nexport class TreeNode {\n _color: TreeNodeColor;\n _key: K | undefined;\n _value: V | undefined;\n _left: TreeNode | undefined = undefined;\n _right: TreeNode | undefined = undefined;\n _parent: TreeNode | undefined = undefined;\n constructor(\n key?: K,\n value?: V,\n color: TreeNodeColor = TreeNodeColor.RED\n ) {\n this._key = key;\n this._value = value;\n this._color = color;\n }\n /**\n * @description Get the pre node.\n * @returns TreeNode about the pre node.\n */\n _pre() {\n let preNode: TreeNode = this;\n const isRootOrHeader = preNode._parent!._parent === preNode;\n if (isRootOrHeader && preNode._color === TreeNodeColor.RED) {\n preNode = preNode._right!;\n } else if (preNode._left) {\n preNode = preNode._left;\n while (preNode._right) {\n preNode = preNode._right;\n }\n } else {\n // Must be root and left is null\n if (isRootOrHeader) {\n return preNode._parent!;\n }\n let pre = preNode._parent!;\n while (pre._left === preNode) {\n preNode = pre;\n pre = preNode._parent!;\n }\n preNode = pre;\n }\n return preNode;\n }\n /**\n * @description Get the next node.\n * @returns TreeNode about the next node.\n */\n _next() {\n let nextNode: TreeNode = this;\n if (nextNode._right) {\n nextNode = nextNode._right;\n while (nextNode._left) {\n nextNode = nextNode._left;\n }\n return nextNode;\n } else {\n let pre = nextNode._parent!;\n while (pre._right === nextNode) {\n nextNode = pre;\n pre = nextNode._parent!;\n }\n if (nextNode._right !== pre) {\n return pre;\n } else return nextNode;\n }\n }\n /**\n * @description Rotate left.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateLeft() {\n const PP = this._parent!;\n const V = this._right!;\n const R = V._left;\n\n if (PP._parent === this) PP._parent = V;\n else if (PP._left === this) PP._left = V;\n else PP._right = V;\n\n V._parent = PP;\n V._left = this;\n\n this._parent = V;\n this._right = R;\n\n if (R) R._parent = this;\n\n return V;\n }\n /**\n * @description Rotate right.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateRight() {\n const PP = this._parent!;\n const F = this._left!;\n const K = F._right;\n\n if (PP._parent === this) PP._parent = F;\n else if (PP._left === this) PP._left = F;\n else PP._right = F;\n\n F._parent = PP;\n F._right = this;\n\n this._parent = F;\n this._left = K;\n\n if (K) K._parent = this;\n\n return F;\n }\n}\n\nexport class TreeNodeEnableIndex extends TreeNode {\n _subTreeSize = 1;\n /**\n * @description Rotate left and do recount.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateLeft() {\n const parent = super._rotateLeft() as TreeNodeEnableIndex;\n this._recount();\n parent._recount();\n return parent;\n }\n /**\n * @description Rotate right and do recount.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateRight() {\n const parent = super._rotateRight() as TreeNodeEnableIndex;\n this._recount();\n parent._recount();\n return parent;\n }\n _recount() {\n this._subTreeSize = 1;\n if (this._left) {\n this._subTreeSize += (this._left as TreeNodeEnableIndex)._subTreeSize;\n }\n if (this._right) {\n this._subTreeSize += (this._right as TreeNodeEnableIndex)._subTreeSize;\n }\n }\n}\n","/**\n * @description The iterator type including `NORMAL` and `REVERSE`.\n */\nexport const enum IteratorType {\n NORMAL = 0,\n REVERSE = 1\n}\n\nexport abstract class ContainerIterator {\n /**\n * @description The container pointed to by the iterator.\n */\n abstract readonly container: Container;\n /**\n * @internal\n */\n abstract _node: unknown;\n /**\n * @description Iterator's type.\n * @example\n * console.log(container.end().iteratorType === IteratorType.NORMAL); // true\n */\n readonly iteratorType: IteratorType;\n /**\n * @internal\n */\n protected constructor(iteratorType = IteratorType.NORMAL) {\n this.iteratorType = iteratorType;\n }\n /**\n * @param iter - The other iterator you want to compare.\n * @returns Whether this equals to obj.\n * @example\n * container.find(1).equals(container.end());\n */\n equals(iter: ContainerIterator) {\n return this._node === iter._node;\n }\n /**\n * @description Pointers to element.\n * @returns The value of the pointer's element.\n * @example\n * const val = container.begin().pointer;\n */\n abstract get pointer(): T;\n /**\n * @description Set pointer's value (some containers are unavailable).\n * @param newValue - The new value you want to set.\n * @example\n * (>container).begin().pointer = 1;\n */\n abstract set pointer(newValue: T);\n /**\n * @description Move `this` iterator to pre.\n * @returns The iterator's self.\n * @example\n * const iter = container.find(1); // container = [0, 1]\n * const pre = iter.pre();\n * console.log(pre === iter); // true\n * console.log(pre.equals(iter)); // true\n * console.log(pre.pointer, iter.pointer); // 0, 0\n */\n abstract pre(): this;\n /**\n * @description Move `this` iterator to next.\n * @returns The iterator's self.\n * @example\n * const iter = container.find(1); // container = [1, 2]\n * const next = iter.next();\n * console.log(next === iter); // true\n * console.log(next.equals(iter)); // true\n * console.log(next.pointer, iter.pointer); // 2, 2\n */\n abstract next(): this;\n /**\n * @description Get a copy of itself.\n * @returns The copy of self.\n * @example\n * const iter = container.find(1); // container = [1, 2]\n * const next = iter.copy().next();\n * console.log(next === iter); // false\n * console.log(next.equals(iter)); // false\n * console.log(next.pointer, iter.pointer); // 2, 1\n */\n abstract copy(): ContainerIterator;\n abstract isAccessible(): boolean;\n}\n\nexport abstract class Base {\n /**\n * @description Container's size.\n * @internal\n */\n protected _length = 0;\n /**\n * @returns The size of the container.\n * @example\n * const container = new Vector([1, 2]);\n * console.log(container.length); // 2\n */\n get length() {\n return this._length;\n }\n /**\n * @returns The size of the container.\n * @example\n * const container = new Vector([1, 2]);\n * console.log(container.size()); // 2\n */\n size() {\n return this._length;\n }\n /**\n * @returns Whether the container is empty.\n * @example\n * container.clear();\n * console.log(container.empty()); // true\n */\n empty() {\n return this._length === 0;\n }\n /**\n * @description Clear the container.\n * @example\n * container.clear();\n * console.log(container.empty()); // true\n */\n abstract clear(): void;\n}\n\nexport abstract class Container extends Base {\n /**\n * @returns Iterator pointing to the beginning element.\n * @example\n * const begin = container.begin();\n * const end = container.end();\n * for (const it = begin; !it.equals(end); it.next()) {\n * doSomething(it.pointer);\n * }\n */\n abstract begin(): ContainerIterator;\n /**\n * @returns Iterator pointing to the super end like c++.\n * @example\n * const begin = container.begin();\n * const end = container.end();\n * for (const it = begin; !it.equals(end); it.next()) {\n * doSomething(it.pointer);\n * }\n */\n abstract end(): ContainerIterator;\n /**\n * @returns Iterator pointing to the end element.\n * @example\n * const rBegin = container.rBegin();\n * const rEnd = container.rEnd();\n * for (const it = rBegin; !it.equals(rEnd); it.next()) {\n * doSomething(it.pointer);\n * }\n */\n abstract rBegin(): ContainerIterator;\n /**\n * @returns Iterator pointing to the super begin like c++.\n * @example\n * const rBegin = container.rBegin();\n * const rEnd = container.rEnd();\n * for (const it = rBegin; !it.equals(rEnd); it.next()) {\n * doSomething(it.pointer);\n * }\n */\n abstract rEnd(): ContainerIterator;\n /**\n * @returns The first element of the container.\n */\n abstract front(): T | undefined;\n /**\n * @returns The last element of the container.\n */\n abstract back(): T | undefined;\n /**\n * @param element - The element you want to find.\n * @returns An iterator pointing to the element if found, or super end if not found.\n * @example\n * container.find(1).equals(container.end());\n */\n abstract find(element: T): ContainerIterator;\n /**\n * @description Iterate over all elements in the container.\n * @param callback - Callback function like Array.forEach.\n * @example\n * container.forEach((element, index) => console.log(element, index));\n */\n abstract forEach(callback: (element: T, index: number, container: Container) => void): void;\n /**\n * @description Gets the value of the element at the specified position.\n * @example\n * const val = container.getElementByPos(-1); // throw a RangeError\n */\n abstract getElementByPos(pos: number): T;\n /**\n * @description Removes the element at the specified position.\n * @param pos - The element's position you want to remove.\n * @returns The container length after erasing.\n * @example\n * container.eraseElementByPos(-1); // throw a RangeError\n */\n abstract eraseElementByPos(pos: number): number;\n /**\n * @description Removes element by iterator and move `iter` to next.\n * @param iter - The iterator you want to erase.\n * @returns The next iterator.\n * @example\n * container.eraseElementByIterator(container.begin());\n * container.eraseElementByIterator(container.end()); // throw a RangeError\n */\n abstract eraseElementByIterator(\n iter: ContainerIterator\n ): ContainerIterator;\n /**\n * @description Using for `for...of` syntax like Array.\n * @example\n * for (const element of container) {\n * console.log(element);\n * }\n */\n abstract [Symbol.iterator](): Generator;\n}\n\n/**\n * @description The initial data type passed in when initializing the container.\n */\nexport type initContainer = {\n size?: number | (() => number);\n length?: number;\n forEach: (callback: (el: T) => void) => void;\n}\n","/**\n * @description Throw an iterator access error.\n * @internal\n */\nexport function throwIteratorAccessError() {\n throw new RangeError('Iterator access denied!');\n}\n","import type TreeIterator from './TreeIterator';\nimport { TreeNode, TreeNodeColor, TreeNodeEnableIndex } from './TreeNode';\nimport { Container, IteratorType } from '@/container/ContainerBase';\nimport $checkWithinAccessParams from '@/utils/checkParams.macro';\nimport { throwIteratorAccessError } from '@/utils/throwError';\n\nabstract class TreeContainer extends Container {\n enableIndex: boolean;\n /**\n * @internal\n */\n protected _header: TreeNode;\n /**\n * @internal\n */\n protected _root: TreeNode | undefined = undefined;\n /**\n * @internal\n */\n protected readonly _cmp: (x: K, y: K) => number;\n /**\n * @internal\n */\n protected readonly _TreeNodeClass: typeof TreeNode | typeof TreeNodeEnableIndex;\n /**\n * @internal\n */\n protected constructor(\n cmp: (x: K, y: K) => number =\n function (x: K, y: K) {\n if (x < y) return -1;\n if (x > y) return 1;\n return 0;\n },\n enableIndex = false\n ) {\n super();\n this._cmp = cmp;\n this.enableIndex = enableIndex;\n this._TreeNodeClass = enableIndex ? TreeNodeEnableIndex : TreeNode;\n this._header = new this._TreeNodeClass();\n }\n /**\n * @internal\n */\n protected _lowerBound(curNode: TreeNode | undefined, key: K) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult < 0) {\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n resNode = curNode;\n curNode = curNode._left;\n } else return curNode;\n }\n return resNode;\n }\n /**\n * @internal\n */\n protected _upperBound(curNode: TreeNode | undefined, key: K) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult <= 0) {\n curNode = curNode._right;\n } else {\n resNode = curNode;\n curNode = curNode._left;\n }\n }\n return resNode;\n }\n /**\n * @internal\n */\n protected _reverseLowerBound(curNode: TreeNode | undefined, key: K) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult < 0) {\n resNode = curNode;\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n curNode = curNode._left;\n } else return curNode;\n }\n return resNode;\n }\n /**\n * @internal\n */\n protected _reverseUpperBound(curNode: TreeNode | undefined, key: K) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult < 0) {\n resNode = curNode;\n curNode = curNode._right;\n } else {\n curNode = curNode._left;\n }\n }\n return resNode;\n }\n /**\n * @internal\n */\n protected _eraseNodeSelfBalance(curNode: TreeNode) {\n while (true) {\n const parentNode = curNode._parent!;\n if (parentNode === this._header) return;\n if (curNode._color === TreeNodeColor.RED) {\n curNode._color = TreeNodeColor.BLACK;\n return;\n }\n if (curNode === parentNode._left) {\n const brother = parentNode._right!;\n if (brother._color === TreeNodeColor.RED) {\n brother._color = TreeNodeColor.BLACK;\n parentNode._color = TreeNodeColor.RED;\n if (parentNode === this._root) {\n this._root = parentNode._rotateLeft();\n } else parentNode._rotateLeft();\n } else {\n if (brother._right && brother._right._color === TreeNodeColor.RED) {\n brother._color = parentNode._color;\n parentNode._color = TreeNodeColor.BLACK;\n brother._right._color = TreeNodeColor.BLACK;\n if (parentNode === this._root) {\n this._root = parentNode._rotateLeft();\n } else parentNode._rotateLeft();\n return;\n } else if (brother._left && brother._left._color === TreeNodeColor.RED) {\n brother._color = TreeNodeColor.RED;\n brother._left._color = TreeNodeColor.BLACK;\n brother._rotateRight();\n } else {\n brother._color = TreeNodeColor.RED;\n curNode = parentNode;\n }\n }\n } else {\n const brother = parentNode._left!;\n if (brother._color === TreeNodeColor.RED) {\n brother._color = TreeNodeColor.BLACK;\n parentNode._color = TreeNodeColor.RED;\n if (parentNode === this._root) {\n this._root = parentNode._rotateRight();\n } else parentNode._rotateRight();\n } else {\n if (brother._left && brother._left._color === TreeNodeColor.RED) {\n brother._color = parentNode._color;\n parentNode._color = TreeNodeColor.BLACK;\n brother._left._color = TreeNodeColor.BLACK;\n if (parentNode === this._root) {\n this._root = parentNode._rotateRight();\n } else parentNode._rotateRight();\n return;\n } else if (brother._right && brother._right._color === TreeNodeColor.RED) {\n brother._color = TreeNodeColor.RED;\n brother._right._color = TreeNodeColor.BLACK;\n brother._rotateLeft();\n } else {\n brother._color = TreeNodeColor.RED;\n curNode = parentNode;\n }\n }\n }\n }\n }\n /**\n * @internal\n */\n protected _eraseNode(curNode: TreeNode) {\n if (this._length === 1) {\n this.clear();\n return;\n }\n let swapNode = curNode;\n while (swapNode._left || swapNode._right) {\n if (swapNode._right) {\n swapNode = swapNode._right;\n while (swapNode._left) swapNode = swapNode._left;\n } else {\n swapNode = swapNode._left!;\n }\n const key = curNode._key;\n curNode._key = swapNode._key;\n swapNode._key = key;\n const value = curNode._value;\n curNode._value = swapNode._value;\n swapNode._value = value;\n curNode = swapNode;\n }\n if (this._header._left === swapNode) {\n this._header._left = swapNode._parent;\n } else if (this._header._right === swapNode) {\n this._header._right = swapNode._parent;\n }\n this._eraseNodeSelfBalance(swapNode);\n let _parent = swapNode._parent as TreeNodeEnableIndex;\n if (swapNode === _parent._left) {\n _parent._left = undefined;\n } else _parent._right = undefined;\n this._length -= 1;\n this._root!._color = TreeNodeColor.BLACK;\n if (this.enableIndex) {\n while (_parent !== this._header) {\n _parent._subTreeSize -= 1;\n _parent = _parent._parent as TreeNodeEnableIndex;\n }\n }\n }\n protected _inOrderTraversal(): TreeNode[];\n protected _inOrderTraversal(pos: number): TreeNode;\n protected _inOrderTraversal(\n callback: (node: TreeNode, index: number, map: this) => void\n ): TreeNode;\n /**\n * @internal\n */\n protected _inOrderTraversal(\n param?: number | ((node: TreeNode, index: number, map: this) => void)\n ) {\n const pos = typeof param === 'number' ? param : undefined;\n const callback = typeof param === 'function' ? param : undefined;\n const nodeList = typeof param === 'undefined' ? []>[] : undefined;\n let index = 0;\n let curNode = this._root;\n const stack: TreeNode[] = [];\n while (stack.length || curNode) {\n if (curNode) {\n stack.push(curNode);\n curNode = curNode._left;\n } else {\n curNode = stack.pop()!;\n if (index === pos) return curNode;\n nodeList && nodeList.push(curNode);\n callback && callback(curNode, index, this);\n index += 1;\n curNode = curNode._right;\n }\n }\n return nodeList;\n }\n /**\n * @internal\n */\n protected _insertNodeSelfBalance(curNode: TreeNode) {\n while (true) {\n const parentNode = curNode._parent!;\n if (parentNode._color === TreeNodeColor.BLACK) return;\n const grandParent = parentNode._parent!;\n if (parentNode === grandParent._left) {\n const uncle = grandParent._right;\n if (uncle && uncle._color === TreeNodeColor.RED) {\n uncle._color = parentNode._color = TreeNodeColor.BLACK;\n if (grandParent === this._root) return;\n grandParent._color = TreeNodeColor.RED;\n curNode = grandParent;\n continue;\n } else if (curNode === parentNode._right) {\n curNode._color = TreeNodeColor.BLACK;\n if (curNode._left) {\n curNode._left._parent = parentNode;\n }\n if (curNode._right) {\n curNode._right._parent = grandParent;\n }\n parentNode._right = curNode._left;\n grandParent._left = curNode._right;\n curNode._left = parentNode;\n curNode._right = grandParent;\n if (grandParent === this._root) {\n this._root = curNode;\n this._header._parent = curNode;\n } else {\n const GP = grandParent._parent!;\n if (GP._left === grandParent) {\n GP._left = curNode;\n } else GP._right = curNode;\n }\n curNode._parent = grandParent._parent;\n parentNode._parent = curNode;\n grandParent._parent = curNode;\n grandParent._color = TreeNodeColor.RED;\n } else {\n parentNode._color = TreeNodeColor.BLACK;\n if (grandParent === this._root) {\n this._root = grandParent._rotateRight();\n } else grandParent._rotateRight();\n grandParent._color = TreeNodeColor.RED;\n return;\n }\n } else {\n const uncle = grandParent._left;\n if (uncle && uncle._color === TreeNodeColor.RED) {\n uncle._color = parentNode._color = TreeNodeColor.BLACK;\n if (grandParent === this._root) return;\n grandParent._color = TreeNodeColor.RED;\n curNode = grandParent;\n continue;\n } else if (curNode === parentNode._left) {\n curNode._color = TreeNodeColor.BLACK;\n if (curNode._left) {\n curNode._left._parent = grandParent;\n }\n if (curNode._right) {\n curNode._right._parent = parentNode;\n }\n grandParent._right = curNode._left;\n parentNode._left = curNode._right;\n curNode._left = grandParent;\n curNode._right = parentNode;\n if (grandParent === this._root) {\n this._root = curNode;\n this._header._parent = curNode;\n } else {\n const GP = grandParent._parent!;\n if (GP._left === grandParent) {\n GP._left = curNode;\n } else GP._right = curNode;\n }\n curNode._parent = grandParent._parent;\n parentNode._parent = curNode;\n grandParent._parent = curNode;\n grandParent._color = TreeNodeColor.RED;\n } else {\n parentNode._color = TreeNodeColor.BLACK;\n if (grandParent === this._root) {\n this._root = grandParent._rotateLeft();\n } else grandParent._rotateLeft();\n grandParent._color = TreeNodeColor.RED;\n return;\n }\n }\n if (this.enableIndex) {\n (>parentNode)._recount();\n (>grandParent)._recount();\n (>curNode)._recount();\n }\n return;\n }\n }\n /**\n * @internal\n */\n protected _set(key: K, value?: V, hint?: TreeIterator) {\n if (this._root === undefined) {\n this._length += 1;\n this._root = new this._TreeNodeClass(key, value, TreeNodeColor.BLACK);\n this._root._parent = this._header;\n this._header._parent = this._header._left = this._header._right = this._root;\n return this._length;\n }\n let curNode;\n const minNode = this._header._left!;\n const compareToMin = this._cmp(minNode._key!, key);\n if (compareToMin === 0) {\n minNode._value = value;\n return this._length;\n } else if (compareToMin > 0) {\n minNode._left = new this._TreeNodeClass(key, value);\n minNode._left._parent = minNode;\n curNode = minNode._left;\n this._header._left = curNode;\n } else {\n const maxNode = this._header._right!;\n const compareToMax = this._cmp(maxNode._key!, key);\n if (compareToMax === 0) {\n maxNode._value = value;\n return this._length;\n } else if (compareToMax < 0) {\n maxNode._right = new this._TreeNodeClass(key, value);\n maxNode._right._parent = maxNode;\n curNode = maxNode._right;\n this._header._right = curNode;\n } else {\n if (hint !== undefined) {\n const iterNode = hint._node;\n if (iterNode !== this._header) {\n const iterCmpRes = this._cmp(iterNode._key!, key);\n if (iterCmpRes === 0) {\n iterNode._value = value;\n return this._length;\n } else /* istanbul ignore else */ if (iterCmpRes > 0) {\n const preNode = iterNode._pre();\n const preCmpRes = this._cmp(preNode._key!, key);\n if (preCmpRes === 0) {\n preNode._value = value;\n return this._length;\n } else if (preCmpRes < 0) {\n curNode = new this._TreeNodeClass(key, value);\n if (preNode._right === undefined) {\n preNode._right = curNode;\n curNode._parent = preNode;\n } else {\n iterNode._left = curNode;\n curNode._parent = iterNode;\n }\n }\n }\n }\n }\n if (curNode === undefined) {\n curNode = this._root;\n while (true) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult > 0) {\n if (curNode._left === undefined) {\n curNode._left = new this._TreeNodeClass(key, value);\n curNode._left._parent = curNode;\n curNode = curNode._left;\n break;\n }\n curNode = curNode._left;\n } else if (cmpResult < 0) {\n if (curNode._right === undefined) {\n curNode._right = new this._TreeNodeClass(key, value);\n curNode._right._parent = curNode;\n curNode = curNode._right;\n break;\n }\n curNode = curNode._right;\n } else {\n curNode._value = value;\n return this._length;\n }\n }\n }\n }\n }\n if (this.enableIndex) {\n let parent = curNode._parent as TreeNodeEnableIndex;\n while (parent !== this._header) {\n parent._subTreeSize += 1;\n parent = parent._parent as TreeNodeEnableIndex;\n }\n }\n this._insertNodeSelfBalance(curNode);\n this._length += 1;\n return this._length;\n }\n /**\n * @internal\n */\n protected _getTreeNodeByKey(curNode: TreeNode | undefined, key: K) {\n while (curNode) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult < 0) {\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n curNode = curNode._left;\n } else return curNode;\n }\n return curNode || this._header;\n }\n clear() {\n this._length = 0;\n this._root = undefined;\n this._header._parent = undefined;\n this._header._left = this._header._right = undefined;\n }\n /**\n * @description Update node's key by iterator.\n * @param iter - The iterator you want to change.\n * @param key - The key you want to update.\n * @returns Whether the modification is successful.\n * @example\n * const st = new orderedSet([1, 2, 5]);\n * const iter = st.find(2);\n * st.updateKeyByIterator(iter, 3); // then st will become [1, 3, 5]\n */\n updateKeyByIterator(iter: TreeIterator, key: K): boolean {\n const node = iter._node;\n if (node === this._header) {\n throwIteratorAccessError();\n }\n if (this._length === 1) {\n node._key = key;\n return true;\n }\n const nextKey = node._next()._key!;\n if (node === this._header._left) {\n if (this._cmp(nextKey, key) > 0) {\n node._key = key;\n return true;\n }\n return false;\n }\n const preKey = node._pre()._key!;\n if (node === this._header._right) {\n if (this._cmp(preKey, key) < 0) {\n node._key = key;\n return true;\n }\n return false;\n }\n if (\n this._cmp(preKey, key) >= 0 ||\n this._cmp(nextKey, key) <= 0\n ) return false;\n node._key = key;\n return true;\n }\n eraseElementByPos(pos: number) {\n $checkWithinAccessParams!(pos, 0, this._length - 1);\n const node = this._inOrderTraversal(pos);\n this._eraseNode(node);\n return this._length;\n }\n /**\n * @description Remove the element of the specified key.\n * @param key - The key you want to remove.\n * @returns Whether erase successfully.\n */\n eraseElementByKey(key: K) {\n if (this._length === 0) return false;\n const curNode = this._getTreeNodeByKey(this._root, key);\n if (curNode === this._header) return false;\n this._eraseNode(curNode);\n return true;\n }\n eraseElementByIterator(iter: TreeIterator) {\n const node = iter._node;\n if (node === this._header) {\n throwIteratorAccessError();\n }\n const hasNoRight = node._right === undefined;\n const isNormal = iter.iteratorType === IteratorType.NORMAL;\n // For the normal iterator, the `next` node will be swapped to `this` node when has right.\n if (isNormal) {\n // So we should move it to next when it's right is null.\n if (hasNoRight) iter.next();\n } else {\n // For the reverse iterator, only when it doesn't have right and has left the `next` node will be swapped.\n // So when it has right, or it is a leaf node we should move it to `next`.\n if (!hasNoRight || node._left === undefined) iter.next();\n }\n this._eraseNode(node);\n return iter;\n }\n /**\n * @description Get the height of the tree.\n * @returns Number about the height of the RB-tree.\n */\n getHeight() {\n if (this._length === 0) return 0;\n function traversal(curNode: TreeNode | undefined): number {\n if (!curNode) return 0;\n return Math.max(traversal(curNode._left), traversal(curNode._right)) + 1;\n }\n return traversal(this._root);\n }\n /**\n * @param key - The given key you want to compare.\n * @returns An iterator to the first element less than the given key.\n */\n abstract reverseUpperBound(key: K): TreeIterator;\n /**\n * @description Union the other tree to self.\n * @param other - The other tree container you want to merge.\n * @returns The size of the tree after union.\n */\n abstract union(other: TreeContainer): number;\n /**\n * @param key - The given key you want to compare.\n * @returns An iterator to the first element not greater than the given key.\n */\n abstract reverseLowerBound(key: K): TreeIterator;\n /**\n * @param key - The given key you want to compare.\n * @returns An iterator to the first element not less than the given key.\n */\n abstract lowerBound(key: K): TreeIterator;\n /**\n * @param key - The given key you want to compare.\n * @returns An iterator to the first element greater than the given key.\n */\n abstract upperBound(key: K): TreeIterator;\n}\n\nexport default TreeContainer;\n","import { TreeNode } from './TreeNode';\nimport type { TreeNodeEnableIndex } from './TreeNode';\nimport { ContainerIterator, IteratorType } from '@/container/ContainerBase';\nimport TreeContainer from '@/container/TreeContainer/Base/index';\nimport { throwIteratorAccessError } from '@/utils/throwError';\n\nabstract class TreeIterator extends ContainerIterator {\n abstract readonly container: TreeContainer;\n /**\n * @internal\n */\n _node: TreeNode;\n /**\n * @internal\n */\n protected _header: TreeNode;\n /**\n * @internal\n */\n protected constructor(\n node: TreeNode,\n header: TreeNode,\n iteratorType?: IteratorType\n ) {\n super(iteratorType);\n this._node = node;\n this._header = header;\n if (this.iteratorType === IteratorType.NORMAL) {\n this.pre = function () {\n if (this._node === this._header._left) {\n throwIteratorAccessError();\n }\n this._node = this._node._pre();\n return this;\n };\n\n this.next = function () {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n this._node = this._node._next();\n return this;\n };\n } else {\n this.pre = function () {\n if (this._node === this._header._right) {\n throwIteratorAccessError();\n }\n this._node = this._node._next();\n return this;\n };\n\n this.next = function () {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n this._node = this._node._pre();\n return this;\n };\n }\n }\n /**\n * @description Get the sequential index of the iterator in the tree container.
\n * Note:\n * This function only takes effect when the specified tree container `enableIndex = true`.\n * @returns The index subscript of the node in the tree.\n * @example\n * const st = new OrderedSet([1, 2, 3], true);\n * console.log(st.begin().next().index); // 1\n */\n get index() {\n let _node = this._node as TreeNodeEnableIndex;\n const root = this._header._parent as TreeNodeEnableIndex;\n if (_node === this._header) {\n if (root) {\n return root._subTreeSize - 1;\n }\n return 0;\n }\n let index = 0;\n if (_node._left) {\n index += (_node._left as TreeNodeEnableIndex)._subTreeSize;\n }\n while (_node !== root) {\n const _parent = _node._parent as TreeNodeEnableIndex;\n if (_node === _parent._right) {\n index += 1;\n if (_parent._left) {\n index += (_parent._left as TreeNodeEnableIndex)._subTreeSize;\n }\n }\n _node = _parent;\n }\n return index;\n }\n isAccessible() {\n return this._node !== this._header;\n }\n // @ts-ignore\n pre(): this;\n // @ts-ignore\n next(): this;\n}\n\nexport default TreeIterator;\n","import TreeContainer from './Base';\nimport TreeIterator from './Base/TreeIterator';\nimport { TreeNode } from './Base/TreeNode';\nimport { initContainer, IteratorType } from '@/container/ContainerBase';\nimport $checkWithinAccessParams from '@/utils/checkParams.macro';\nimport { throwIteratorAccessError } from '@/utils/throwError';\n\nclass OrderedMapIterator extends TreeIterator {\n container: OrderedMap;\n constructor(\n node: TreeNode,\n header: TreeNode,\n container: OrderedMap,\n iteratorType?: IteratorType\n ) {\n super(node, header, iteratorType);\n this.container = container;\n }\n get pointer() {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n const self = this;\n return new Proxy(<[K, V]>[], {\n get(target, prop: '0' | '1') {\n if (prop === '0') return self._node._key!;\n else if (prop === '1') return self._node._value!;\n target[0] = self._node._key!;\n target[1] = self._node._value!;\n return target[prop];\n },\n set(_, prop: '1', newValue: V) {\n if (prop !== '1') {\n throw new TypeError('prop must be 1');\n }\n self._node._value = newValue;\n return true;\n }\n });\n }\n copy() {\n return new OrderedMapIterator(\n this._node,\n this._header,\n this.container,\n this.iteratorType\n );\n }\n // @ts-ignore\n equals(iter: OrderedMapIterator): boolean;\n}\n\nexport type { OrderedMapIterator };\n\nclass OrderedMap extends TreeContainer {\n /**\n * @param container - The initialization container.\n * @param cmp - The compare function.\n * @param enableIndex - Whether to enable iterator indexing function.\n * @example\n * new OrderedMap();\n * new OrderedMap([[0, 1], [2, 1]]);\n * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y);\n * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y, true);\n */\n constructor(\n container: initContainer<[K, V]> = [],\n cmp?: (x: K, y: K) => number,\n enableIndex?: boolean\n ) {\n super(cmp, enableIndex);\n const self = this;\n container.forEach(function (el) {\n self.setElement(el[0], el[1]);\n });\n }\n begin() {\n return new OrderedMapIterator(this._header._left || this._header, this._header, this);\n }\n end() {\n return new OrderedMapIterator(this._header, this._header, this);\n }\n rBegin() {\n return new OrderedMapIterator(\n this._header._right || this._header,\n this._header,\n this,\n IteratorType.REVERSE\n );\n }\n rEnd() {\n return new OrderedMapIterator(this._header, this._header, this, IteratorType.REVERSE);\n }\n front() {\n if (this._length === 0) return;\n const minNode = this._header._left!;\n return <[K, V]>[minNode._key, minNode._value];\n }\n back() {\n if (this._length === 0) return;\n const maxNode = this._header._right!;\n return <[K, V]>[maxNode._key, maxNode._value];\n }\n lowerBound(key: K) {\n const resNode = this._lowerBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n upperBound(key: K) {\n const resNode = this._upperBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n reverseLowerBound(key: K) {\n const resNode = this._reverseLowerBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n reverseUpperBound(key: K) {\n const resNode = this._reverseUpperBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n forEach(callback: (element: [K, V], index: number, map: OrderedMap) => void) {\n this._inOrderTraversal(function (node, index, map) {\n callback(<[K, V]>[node._key, node._value], index, map);\n });\n }\n /**\n * @description Insert a key-value pair or set value by the given key.\n * @param key - The key want to insert.\n * @param value - The value want to set.\n * @param hint - You can give an iterator hint to improve insertion efficiency.\n * @return The size of container after setting.\n * @example\n * const mp = new OrderedMap([[2, 0], [4, 0], [5, 0]]);\n * const iter = mp.begin();\n * mp.setElement(1, 0);\n * mp.setElement(3, 0, iter); // give a hint will be faster.\n */\n setElement(key: K, value: V, hint?: OrderedMapIterator) {\n return this._set(key, value, hint);\n }\n getElementByPos(pos: number) {\n $checkWithinAccessParams!(pos, 0, this._length - 1);\n const node = this._inOrderTraversal(pos);\n return <[K, V]>[node._key, node._value];\n }\n find(key: K) {\n const curNode = this._getTreeNodeByKey(this._root, key);\n return new OrderedMapIterator(curNode, this._header, this);\n }\n /**\n * @description Get the value of the element of the specified key.\n * @param key - The specified key you want to get.\n * @example\n * const val = container.getElementByKey(1);\n */\n getElementByKey(key: K) {\n const curNode = this._getTreeNodeByKey(this._root, key);\n return curNode._value;\n }\n union(other: OrderedMap) {\n const self = this;\n other.forEach(function (el) {\n self.setElement(el[0], el[1]);\n });\n return this._length;\n }\n * [Symbol.iterator]() {\n const length = this._length;\n const nodeList = this._inOrderTraversal();\n for (let i = 0; i < length; ++i) {\n const node = nodeList[i];\n yield <[K, V]>[node._key, node._value];\n }\n }\n // @ts-ignore\n eraseElementByIterator(iter: OrderedMapIterator): OrderedMapIterator;\n}\n\nexport default OrderedMap;\n"]} \ No newline at end of file diff --git a/node_modules/@js-sdsl/ordered-map/dist/umd/ordered-map.js b/node_modules/@js-sdsl/ordered-map/dist/umd/ordered-map.js new file mode 100644 index 0000000..84ae512 --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/dist/umd/ordered-map.js @@ -0,0 +1,1157 @@ +/*! + * @js-sdsl/ordered-map v4.4.2 + * https://github.com/js-sdsl/js-sdsl + * (c) 2021-present ZLY201 + * MIT license + */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.sdsl = {})); +})(this, (function (exports) { 'use strict'; + + /****************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise, SuppressedError, Symbol */ + + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || { + __proto__: [] + } instanceof Array && function (d, b) { + d.__proto__ = b; + } || function (d, b) { + for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; + }; + return extendStatics(d, b); + }; + function __extends(d, b) { + if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + function __generator(thisArg, body) { + var _ = { + label: 0, + sent: function () { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [] + }, + f, + y, + t, + g; + return g = { + next: verb(0), + "throw": verb(1), + "return": verb(2) + }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { + value: op[1], + done: false + }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0; + continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { + value: op[0] ? op[1] : void 0, + done: true + }; + } + } + typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + var TreeNode = /** @class */function () { + function TreeNode(key, value, color) { + if (color === void 0) { + color = 1 /* TreeNodeColor.RED */; + } + this._left = undefined; + this._right = undefined; + this._parent = undefined; + this._key = key; + this._value = value; + this._color = color; + } + /** + * @description Get the pre node. + * @returns TreeNode about the pre node. + */ + TreeNode.prototype._pre = function () { + var preNode = this; + var isRootOrHeader = preNode._parent._parent === preNode; + if (isRootOrHeader && preNode._color === 1 /* TreeNodeColor.RED */) { + preNode = preNode._right; + } else if (preNode._left) { + preNode = preNode._left; + while (preNode._right) { + preNode = preNode._right; + } + } else { + // Must be root and left is null + if (isRootOrHeader) { + return preNode._parent; + } + var pre = preNode._parent; + while (pre._left === preNode) { + preNode = pre; + pre = preNode._parent; + } + preNode = pre; + } + return preNode; + }; + /** + * @description Get the next node. + * @returns TreeNode about the next node. + */ + TreeNode.prototype._next = function () { + var nextNode = this; + if (nextNode._right) { + nextNode = nextNode._right; + while (nextNode._left) { + nextNode = nextNode._left; + } + return nextNode; + } else { + var pre = nextNode._parent; + while (pre._right === nextNode) { + nextNode = pre; + pre = nextNode._parent; + } + if (nextNode._right !== pre) { + return pre; + } else return nextNode; + } + }; + /** + * @description Rotate left. + * @returns TreeNode about moved to original position after rotation. + */ + TreeNode.prototype._rotateLeft = function () { + var PP = this._parent; + var V = this._right; + var R = V._left; + if (PP._parent === this) PP._parent = V;else if (PP._left === this) PP._left = V;else PP._right = V; + V._parent = PP; + V._left = this; + this._parent = V; + this._right = R; + if (R) R._parent = this; + return V; + }; + /** + * @description Rotate right. + * @returns TreeNode about moved to original position after rotation. + */ + TreeNode.prototype._rotateRight = function () { + var PP = this._parent; + var F = this._left; + var K = F._right; + if (PP._parent === this) PP._parent = F;else if (PP._left === this) PP._left = F;else PP._right = F; + F._parent = PP; + F._right = this; + this._parent = F; + this._left = K; + if (K) K._parent = this; + return F; + }; + return TreeNode; + }(); + var TreeNodeEnableIndex = /** @class */function (_super) { + __extends(TreeNodeEnableIndex, _super); + function TreeNodeEnableIndex() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this._subTreeSize = 1; + return _this; + } + /** + * @description Rotate left and do recount. + * @returns TreeNode about moved to original position after rotation. + */ + TreeNodeEnableIndex.prototype._rotateLeft = function () { + var parent = _super.prototype._rotateLeft.call(this); + this._recount(); + parent._recount(); + return parent; + }; + /** + * @description Rotate right and do recount. + * @returns TreeNode about moved to original position after rotation. + */ + TreeNodeEnableIndex.prototype._rotateRight = function () { + var parent = _super.prototype._rotateRight.call(this); + this._recount(); + parent._recount(); + return parent; + }; + TreeNodeEnableIndex.prototype._recount = function () { + this._subTreeSize = 1; + if (this._left) { + this._subTreeSize += this._left._subTreeSize; + } + if (this._right) { + this._subTreeSize += this._right._subTreeSize; + } + }; + return TreeNodeEnableIndex; + }(TreeNode); + + var ContainerIterator = /** @class */function () { + /** + * @internal + */ + function ContainerIterator(iteratorType) { + if (iteratorType === void 0) { + iteratorType = 0 /* IteratorType.NORMAL */; + } + this.iteratorType = iteratorType; + } + /** + * @param iter - The other iterator you want to compare. + * @returns Whether this equals to obj. + * @example + * container.find(1).equals(container.end()); + */ + ContainerIterator.prototype.equals = function (iter) { + return this._node === iter._node; + }; + return ContainerIterator; + }(); + var Base = /** @class */function () { + function Base() { + /** + * @description Container's size. + * @internal + */ + this._length = 0; + } + Object.defineProperty(Base.prototype, "length", { + /** + * @returns The size of the container. + * @example + * const container = new Vector([1, 2]); + * console.log(container.length); // 2 + */ + get: function () { + return this._length; + }, + enumerable: false, + configurable: true + }); + /** + * @returns The size of the container. + * @example + * const container = new Vector([1, 2]); + * console.log(container.size()); // 2 + */ + Base.prototype.size = function () { + return this._length; + }; + /** + * @returns Whether the container is empty. + * @example + * container.clear(); + * console.log(container.empty()); // true + */ + Base.prototype.empty = function () { + return this._length === 0; + }; + return Base; + }(); + var Container = /** @class */function (_super) { + __extends(Container, _super); + function Container() { + return _super !== null && _super.apply(this, arguments) || this; + } + return Container; + }(Base); + + /** + * @description Throw an iterator access error. + * @internal + */ + function throwIteratorAccessError() { + throw new RangeError('Iterator access denied!'); + } + + var TreeContainer = /** @class */function (_super) { + __extends(TreeContainer, _super); + /** + * @internal + */ + function TreeContainer(cmp, enableIndex) { + if (cmp === void 0) { + cmp = function (x, y) { + if (x < y) return -1; + if (x > y) return 1; + return 0; + }; + } + if (enableIndex === void 0) { + enableIndex = false; + } + var _this = _super.call(this) || this; + /** + * @internal + */ + _this._root = undefined; + _this._cmp = cmp; + _this.enableIndex = enableIndex; + _this._TreeNodeClass = enableIndex ? TreeNodeEnableIndex : TreeNode; + _this._header = new _this._TreeNodeClass(); + return _this; + } + /** + * @internal + */ + TreeContainer.prototype._lowerBound = function (curNode, key) { + var resNode = this._header; + while (curNode) { + var cmpResult = this._cmp(curNode._key, key); + if (cmpResult < 0) { + curNode = curNode._right; + } else if (cmpResult > 0) { + resNode = curNode; + curNode = curNode._left; + } else return curNode; + } + return resNode; + }; + /** + * @internal + */ + TreeContainer.prototype._upperBound = function (curNode, key) { + var resNode = this._header; + while (curNode) { + var cmpResult = this._cmp(curNode._key, key); + if (cmpResult <= 0) { + curNode = curNode._right; + } else { + resNode = curNode; + curNode = curNode._left; + } + } + return resNode; + }; + /** + * @internal + */ + TreeContainer.prototype._reverseLowerBound = function (curNode, key) { + var resNode = this._header; + while (curNode) { + var cmpResult = this._cmp(curNode._key, key); + if (cmpResult < 0) { + resNode = curNode; + curNode = curNode._right; + } else if (cmpResult > 0) { + curNode = curNode._left; + } else return curNode; + } + return resNode; + }; + /** + * @internal + */ + TreeContainer.prototype._reverseUpperBound = function (curNode, key) { + var resNode = this._header; + while (curNode) { + var cmpResult = this._cmp(curNode._key, key); + if (cmpResult < 0) { + resNode = curNode; + curNode = curNode._right; + } else { + curNode = curNode._left; + } + } + return resNode; + }; + /** + * @internal + */ + TreeContainer.prototype._eraseNodeSelfBalance = function (curNode) { + while (true) { + var parentNode = curNode._parent; + if (parentNode === this._header) return; + if (curNode._color === 1 /* TreeNodeColor.RED */) { + curNode._color = 0 /* TreeNodeColor.BLACK */; + return; + } + if (curNode === parentNode._left) { + var brother = parentNode._right; + if (brother._color === 1 /* TreeNodeColor.RED */) { + brother._color = 0 /* TreeNodeColor.BLACK */; + parentNode._color = 1 /* TreeNodeColor.RED */; + if (parentNode === this._root) { + this._root = parentNode._rotateLeft(); + } else parentNode._rotateLeft(); + } else { + if (brother._right && brother._right._color === 1 /* TreeNodeColor.RED */) { + brother._color = parentNode._color; + parentNode._color = 0 /* TreeNodeColor.BLACK */; + brother._right._color = 0 /* TreeNodeColor.BLACK */; + if (parentNode === this._root) { + this._root = parentNode._rotateLeft(); + } else parentNode._rotateLeft(); + return; + } else if (brother._left && brother._left._color === 1 /* TreeNodeColor.RED */) { + brother._color = 1 /* TreeNodeColor.RED */; + brother._left._color = 0 /* TreeNodeColor.BLACK */; + brother._rotateRight(); + } else { + brother._color = 1 /* TreeNodeColor.RED */; + curNode = parentNode; + } + } + } else { + var brother = parentNode._left; + if (brother._color === 1 /* TreeNodeColor.RED */) { + brother._color = 0 /* TreeNodeColor.BLACK */; + parentNode._color = 1 /* TreeNodeColor.RED */; + if (parentNode === this._root) { + this._root = parentNode._rotateRight(); + } else parentNode._rotateRight(); + } else { + if (brother._left && brother._left._color === 1 /* TreeNodeColor.RED */) { + brother._color = parentNode._color; + parentNode._color = 0 /* TreeNodeColor.BLACK */; + brother._left._color = 0 /* TreeNodeColor.BLACK */; + if (parentNode === this._root) { + this._root = parentNode._rotateRight(); + } else parentNode._rotateRight(); + return; + } else if (brother._right && brother._right._color === 1 /* TreeNodeColor.RED */) { + brother._color = 1 /* TreeNodeColor.RED */; + brother._right._color = 0 /* TreeNodeColor.BLACK */; + brother._rotateLeft(); + } else { + brother._color = 1 /* TreeNodeColor.RED */; + curNode = parentNode; + } + } + } + } + }; + /** + * @internal + */ + TreeContainer.prototype._eraseNode = function (curNode) { + if (this._length === 1) { + this.clear(); + return; + } + var swapNode = curNode; + while (swapNode._left || swapNode._right) { + if (swapNode._right) { + swapNode = swapNode._right; + while (swapNode._left) swapNode = swapNode._left; + } else { + swapNode = swapNode._left; + } + var key = curNode._key; + curNode._key = swapNode._key; + swapNode._key = key; + var value = curNode._value; + curNode._value = swapNode._value; + swapNode._value = value; + curNode = swapNode; + } + if (this._header._left === swapNode) { + this._header._left = swapNode._parent; + } else if (this._header._right === swapNode) { + this._header._right = swapNode._parent; + } + this._eraseNodeSelfBalance(swapNode); + var _parent = swapNode._parent; + if (swapNode === _parent._left) { + _parent._left = undefined; + } else _parent._right = undefined; + this._length -= 1; + this._root._color = 0 /* TreeNodeColor.BLACK */; + if (this.enableIndex) { + while (_parent !== this._header) { + _parent._subTreeSize -= 1; + _parent = _parent._parent; + } + } + }; + /** + * @internal + */ + TreeContainer.prototype._inOrderTraversal = function (param) { + var pos = typeof param === 'number' ? param : undefined; + var callback = typeof param === 'function' ? param : undefined; + var nodeList = typeof param === 'undefined' ? [] : undefined; + var index = 0; + var curNode = this._root; + var stack = []; + while (stack.length || curNode) { + if (curNode) { + stack.push(curNode); + curNode = curNode._left; + } else { + curNode = stack.pop(); + if (index === pos) return curNode; + nodeList && nodeList.push(curNode); + callback && callback(curNode, index, this); + index += 1; + curNode = curNode._right; + } + } + return nodeList; + }; + /** + * @internal + */ + TreeContainer.prototype._insertNodeSelfBalance = function (curNode) { + while (true) { + var parentNode = curNode._parent; + if (parentNode._color === 0 /* TreeNodeColor.BLACK */) return; + var grandParent = parentNode._parent; + if (parentNode === grandParent._left) { + var uncle = grandParent._right; + if (uncle && uncle._color === 1 /* TreeNodeColor.RED */) { + uncle._color = parentNode._color = 0 /* TreeNodeColor.BLACK */; + if (grandParent === this._root) return; + grandParent._color = 1 /* TreeNodeColor.RED */; + curNode = grandParent; + continue; + } else if (curNode === parentNode._right) { + curNode._color = 0 /* TreeNodeColor.BLACK */; + if (curNode._left) { + curNode._left._parent = parentNode; + } + if (curNode._right) { + curNode._right._parent = grandParent; + } + parentNode._right = curNode._left; + grandParent._left = curNode._right; + curNode._left = parentNode; + curNode._right = grandParent; + if (grandParent === this._root) { + this._root = curNode; + this._header._parent = curNode; + } else { + var GP = grandParent._parent; + if (GP._left === grandParent) { + GP._left = curNode; + } else GP._right = curNode; + } + curNode._parent = grandParent._parent; + parentNode._parent = curNode; + grandParent._parent = curNode; + grandParent._color = 1 /* TreeNodeColor.RED */; + } else { + parentNode._color = 0 /* TreeNodeColor.BLACK */; + if (grandParent === this._root) { + this._root = grandParent._rotateRight(); + } else grandParent._rotateRight(); + grandParent._color = 1 /* TreeNodeColor.RED */; + return; + } + } else { + var uncle = grandParent._left; + if (uncle && uncle._color === 1 /* TreeNodeColor.RED */) { + uncle._color = parentNode._color = 0 /* TreeNodeColor.BLACK */; + if (grandParent === this._root) return; + grandParent._color = 1 /* TreeNodeColor.RED */; + curNode = grandParent; + continue; + } else if (curNode === parentNode._left) { + curNode._color = 0 /* TreeNodeColor.BLACK */; + if (curNode._left) { + curNode._left._parent = grandParent; + } + if (curNode._right) { + curNode._right._parent = parentNode; + } + grandParent._right = curNode._left; + parentNode._left = curNode._right; + curNode._left = grandParent; + curNode._right = parentNode; + if (grandParent === this._root) { + this._root = curNode; + this._header._parent = curNode; + } else { + var GP = grandParent._parent; + if (GP._left === grandParent) { + GP._left = curNode; + } else GP._right = curNode; + } + curNode._parent = grandParent._parent; + parentNode._parent = curNode; + grandParent._parent = curNode; + grandParent._color = 1 /* TreeNodeColor.RED */; + } else { + parentNode._color = 0 /* TreeNodeColor.BLACK */; + if (grandParent === this._root) { + this._root = grandParent._rotateLeft(); + } else grandParent._rotateLeft(); + grandParent._color = 1 /* TreeNodeColor.RED */; + return; + } + } + if (this.enableIndex) { + parentNode._recount(); + grandParent._recount(); + curNode._recount(); + } + return; + } + }; + /** + * @internal + */ + TreeContainer.prototype._set = function (key, value, hint) { + if (this._root === undefined) { + this._length += 1; + this._root = new this._TreeNodeClass(key, value, 0 /* TreeNodeColor.BLACK */); + this._root._parent = this._header; + this._header._parent = this._header._left = this._header._right = this._root; + return this._length; + } + var curNode; + var minNode = this._header._left; + var compareToMin = this._cmp(minNode._key, key); + if (compareToMin === 0) { + minNode._value = value; + return this._length; + } else if (compareToMin > 0) { + minNode._left = new this._TreeNodeClass(key, value); + minNode._left._parent = minNode; + curNode = minNode._left; + this._header._left = curNode; + } else { + var maxNode = this._header._right; + var compareToMax = this._cmp(maxNode._key, key); + if (compareToMax === 0) { + maxNode._value = value; + return this._length; + } else if (compareToMax < 0) { + maxNode._right = new this._TreeNodeClass(key, value); + maxNode._right._parent = maxNode; + curNode = maxNode._right; + this._header._right = curNode; + } else { + if (hint !== undefined) { + var iterNode = hint._node; + if (iterNode !== this._header) { + var iterCmpRes = this._cmp(iterNode._key, key); + if (iterCmpRes === 0) { + iterNode._value = value; + return this._length; + } else /* istanbul ignore else */if (iterCmpRes > 0) { + var preNode = iterNode._pre(); + var preCmpRes = this._cmp(preNode._key, key); + if (preCmpRes === 0) { + preNode._value = value; + return this._length; + } else if (preCmpRes < 0) { + curNode = new this._TreeNodeClass(key, value); + if (preNode._right === undefined) { + preNode._right = curNode; + curNode._parent = preNode; + } else { + iterNode._left = curNode; + curNode._parent = iterNode; + } + } + } + } + } + if (curNode === undefined) { + curNode = this._root; + while (true) { + var cmpResult = this._cmp(curNode._key, key); + if (cmpResult > 0) { + if (curNode._left === undefined) { + curNode._left = new this._TreeNodeClass(key, value); + curNode._left._parent = curNode; + curNode = curNode._left; + break; + } + curNode = curNode._left; + } else if (cmpResult < 0) { + if (curNode._right === undefined) { + curNode._right = new this._TreeNodeClass(key, value); + curNode._right._parent = curNode; + curNode = curNode._right; + break; + } + curNode = curNode._right; + } else { + curNode._value = value; + return this._length; + } + } + } + } + } + if (this.enableIndex) { + var parent_1 = curNode._parent; + while (parent_1 !== this._header) { + parent_1._subTreeSize += 1; + parent_1 = parent_1._parent; + } + } + this._insertNodeSelfBalance(curNode); + this._length += 1; + return this._length; + }; + /** + * @internal + */ + TreeContainer.prototype._getTreeNodeByKey = function (curNode, key) { + while (curNode) { + var cmpResult = this._cmp(curNode._key, key); + if (cmpResult < 0) { + curNode = curNode._right; + } else if (cmpResult > 0) { + curNode = curNode._left; + } else return curNode; + } + return curNode || this._header; + }; + TreeContainer.prototype.clear = function () { + this._length = 0; + this._root = undefined; + this._header._parent = undefined; + this._header._left = this._header._right = undefined; + }; + /** + * @description Update node's key by iterator. + * @param iter - The iterator you want to change. + * @param key - The key you want to update. + * @returns Whether the modification is successful. + * @example + * const st = new orderedSet([1, 2, 5]); + * const iter = st.find(2); + * st.updateKeyByIterator(iter, 3); // then st will become [1, 3, 5] + */ + TreeContainer.prototype.updateKeyByIterator = function (iter, key) { + var node = iter._node; + if (node === this._header) { + throwIteratorAccessError(); + } + if (this._length === 1) { + node._key = key; + return true; + } + var nextKey = node._next()._key; + if (node === this._header._left) { + if (this._cmp(nextKey, key) > 0) { + node._key = key; + return true; + } + return false; + } + var preKey = node._pre()._key; + if (node === this._header._right) { + if (this._cmp(preKey, key) < 0) { + node._key = key; + return true; + } + return false; + } + if (this._cmp(preKey, key) >= 0 || this._cmp(nextKey, key) <= 0) return false; + node._key = key; + return true; + }; + TreeContainer.prototype.eraseElementByPos = function (pos) { + if (pos < 0 || pos > this._length - 1) { + throw new RangeError(); + } + var node = this._inOrderTraversal(pos); + this._eraseNode(node); + return this._length; + }; + /** + * @description Remove the element of the specified key. + * @param key - The key you want to remove. + * @returns Whether erase successfully. + */ + TreeContainer.prototype.eraseElementByKey = function (key) { + if (this._length === 0) return false; + var curNode = this._getTreeNodeByKey(this._root, key); + if (curNode === this._header) return false; + this._eraseNode(curNode); + return true; + }; + TreeContainer.prototype.eraseElementByIterator = function (iter) { + var node = iter._node; + if (node === this._header) { + throwIteratorAccessError(); + } + var hasNoRight = node._right === undefined; + var isNormal = iter.iteratorType === 0 /* IteratorType.NORMAL */; + // For the normal iterator, the `next` node will be swapped to `this` node when has right. + if (isNormal) { + // So we should move it to next when it's right is null. + if (hasNoRight) iter.next(); + } else { + // For the reverse iterator, only when it doesn't have right and has left the `next` node will be swapped. + // So when it has right, or it is a leaf node we should move it to `next`. + if (!hasNoRight || node._left === undefined) iter.next(); + } + this._eraseNode(node); + return iter; + }; + /** + * @description Get the height of the tree. + * @returns Number about the height of the RB-tree. + */ + TreeContainer.prototype.getHeight = function () { + if (this._length === 0) return 0; + function traversal(curNode) { + if (!curNode) return 0; + return Math.max(traversal(curNode._left), traversal(curNode._right)) + 1; + } + return traversal(this._root); + }; + return TreeContainer; + }(Container); + + var TreeIterator = /** @class */function (_super) { + __extends(TreeIterator, _super); + /** + * @internal + */ + function TreeIterator(node, header, iteratorType) { + var _this = _super.call(this, iteratorType) || this; + _this._node = node; + _this._header = header; + if (_this.iteratorType === 0 /* IteratorType.NORMAL */) { + _this.pre = function () { + if (this._node === this._header._left) { + throwIteratorAccessError(); + } + this._node = this._node._pre(); + return this; + }; + _this.next = function () { + if (this._node === this._header) { + throwIteratorAccessError(); + } + this._node = this._node._next(); + return this; + }; + } else { + _this.pre = function () { + if (this._node === this._header._right) { + throwIteratorAccessError(); + } + this._node = this._node._next(); + return this; + }; + _this.next = function () { + if (this._node === this._header) { + throwIteratorAccessError(); + } + this._node = this._node._pre(); + return this; + }; + } + return _this; + } + Object.defineProperty(TreeIterator.prototype, "index", { + /** + * @description Get the sequential index of the iterator in the tree container.
+ * Note: + * This function only takes effect when the specified tree container `enableIndex = true`. + * @returns The index subscript of the node in the tree. + * @example + * const st = new OrderedSet([1, 2, 3], true); + * console.log(st.begin().next().index); // 1 + */ + get: function () { + var _node = this._node; + var root = this._header._parent; + if (_node === this._header) { + if (root) { + return root._subTreeSize - 1; + } + return 0; + } + var index = 0; + if (_node._left) { + index += _node._left._subTreeSize; + } + while (_node !== root) { + var _parent = _node._parent; + if (_node === _parent._right) { + index += 1; + if (_parent._left) { + index += _parent._left._subTreeSize; + } + } + _node = _parent; + } + return index; + }, + enumerable: false, + configurable: true + }); + TreeIterator.prototype.isAccessible = function () { + return this._node !== this._header; + }; + return TreeIterator; + }(ContainerIterator); + + var OrderedMapIterator = /** @class */function (_super) { + __extends(OrderedMapIterator, _super); + function OrderedMapIterator(node, header, container, iteratorType) { + var _this = _super.call(this, node, header, iteratorType) || this; + _this.container = container; + return _this; + } + Object.defineProperty(OrderedMapIterator.prototype, "pointer", { + get: function () { + if (this._node === this._header) { + throwIteratorAccessError(); + } + var self = this; + return new Proxy([], { + get: function (target, prop) { + if (prop === '0') return self._node._key;else if (prop === '1') return self._node._value; + target[0] = self._node._key; + target[1] = self._node._value; + return target[prop]; + }, + set: function (_, prop, newValue) { + if (prop !== '1') { + throw new TypeError('prop must be 1'); + } + self._node._value = newValue; + return true; + } + }); + }, + enumerable: false, + configurable: true + }); + OrderedMapIterator.prototype.copy = function () { + return new OrderedMapIterator(this._node, this._header, this.container, this.iteratorType); + }; + return OrderedMapIterator; + }(TreeIterator); + var OrderedMap = /** @class */function (_super) { + __extends(OrderedMap, _super); + /** + * @param container - The initialization container. + * @param cmp - The compare function. + * @param enableIndex - Whether to enable iterator indexing function. + * @example + * new OrderedMap(); + * new OrderedMap([[0, 1], [2, 1]]); + * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y); + * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y, true); + */ + function OrderedMap(container, cmp, enableIndex) { + if (container === void 0) { + container = []; + } + var _this = _super.call(this, cmp, enableIndex) || this; + var self = _this; + container.forEach(function (el) { + self.setElement(el[0], el[1]); + }); + return _this; + } + OrderedMap.prototype.begin = function () { + return new OrderedMapIterator(this._header._left || this._header, this._header, this); + }; + OrderedMap.prototype.end = function () { + return new OrderedMapIterator(this._header, this._header, this); + }; + OrderedMap.prototype.rBegin = function () { + return new OrderedMapIterator(this._header._right || this._header, this._header, this, 1 /* IteratorType.REVERSE */); + }; + + OrderedMap.prototype.rEnd = function () { + return new OrderedMapIterator(this._header, this._header, this, 1 /* IteratorType.REVERSE */); + }; + + OrderedMap.prototype.front = function () { + if (this._length === 0) return; + var minNode = this._header._left; + return [minNode._key, minNode._value]; + }; + OrderedMap.prototype.back = function () { + if (this._length === 0) return; + var maxNode = this._header._right; + return [maxNode._key, maxNode._value]; + }; + OrderedMap.prototype.lowerBound = function (key) { + var resNode = this._lowerBound(this._root, key); + return new OrderedMapIterator(resNode, this._header, this); + }; + OrderedMap.prototype.upperBound = function (key) { + var resNode = this._upperBound(this._root, key); + return new OrderedMapIterator(resNode, this._header, this); + }; + OrderedMap.prototype.reverseLowerBound = function (key) { + var resNode = this._reverseLowerBound(this._root, key); + return new OrderedMapIterator(resNode, this._header, this); + }; + OrderedMap.prototype.reverseUpperBound = function (key) { + var resNode = this._reverseUpperBound(this._root, key); + return new OrderedMapIterator(resNode, this._header, this); + }; + OrderedMap.prototype.forEach = function (callback) { + this._inOrderTraversal(function (node, index, map) { + callback([node._key, node._value], index, map); + }); + }; + /** + * @description Insert a key-value pair or set value by the given key. + * @param key - The key want to insert. + * @param value - The value want to set. + * @param hint - You can give an iterator hint to improve insertion efficiency. + * @return The size of container after setting. + * @example + * const mp = new OrderedMap([[2, 0], [4, 0], [5, 0]]); + * const iter = mp.begin(); + * mp.setElement(1, 0); + * mp.setElement(3, 0, iter); // give a hint will be faster. + */ + OrderedMap.prototype.setElement = function (key, value, hint) { + return this._set(key, value, hint); + }; + OrderedMap.prototype.getElementByPos = function (pos) { + if (pos < 0 || pos > this._length - 1) { + throw new RangeError(); + } + var node = this._inOrderTraversal(pos); + return [node._key, node._value]; + }; + OrderedMap.prototype.find = function (key) { + var curNode = this._getTreeNodeByKey(this._root, key); + return new OrderedMapIterator(curNode, this._header, this); + }; + /** + * @description Get the value of the element of the specified key. + * @param key - The specified key you want to get. + * @example + * const val = container.getElementByKey(1); + */ + OrderedMap.prototype.getElementByKey = function (key) { + var curNode = this._getTreeNodeByKey(this._root, key); + return curNode._value; + }; + OrderedMap.prototype.union = function (other) { + var self = this; + other.forEach(function (el) { + self.setElement(el[0], el[1]); + }); + return this._length; + }; + OrderedMap.prototype[Symbol.iterator] = function () { + var length, nodeList, i, node; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + length = this._length; + nodeList = this._inOrderTraversal(); + i = 0; + _a.label = 1; + case 1: + if (!(i < length)) return [3 /*break*/, 4]; + node = nodeList[i]; + return [4 /*yield*/, [node._key, node._value]]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + ++i; + return [3 /*break*/, 1]; + case 4: + return [2 /*return*/]; + } + }); + }; + + return OrderedMap; + }(TreeContainer); + + exports.OrderedMap = OrderedMap; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); diff --git a/node_modules/@js-sdsl/ordered-map/dist/umd/ordered-map.min.js b/node_modules/@js-sdsl/ordered-map/dist/umd/ordered-map.min.js new file mode 100644 index 0000000..3c9dbf4 --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/dist/umd/ordered-map.min.js @@ -0,0 +1,8 @@ +/*! + * @js-sdsl/ordered-map v4.4.2 + * https://github.com/js-sdsl/js-sdsl + * (c) 2021-present ZLY201 + * MIT license + */ +!function(t,i){"object"==typeof exports&&"undefined"!=typeof module?i(exports):"function"==typeof define&&define.amd?define(["exports"],i):i((t="undefined"!=typeof globalThis?globalThis:t||self).sdsl={})}(this,function(t){"use strict";var r=function(t,i){return(r=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(t,i){t.__proto__=i}:function(t,i){for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e])}))(t,i)};function i(t,i){if("function"!=typeof i&&null!==i)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");function e(){this.constructor=t}r(t,i),t.prototype=null===i?Object.create(i):(e.prototype=i.prototype,new e)}function o(r,n){var o,s,h,u={label:0,sent:function(){if(1&h[0])throw h[1];return h[1]},trys:[],ops:[]},f={next:t(0),throw:t(1),return:t(2)};return"function"==typeof Symbol&&(f[Symbol.iterator]=function(){return this}),f;function t(e){return function(t){var i=[e,t];if(o)throw new TypeError("Generator is already executing.");for(;u=f&&i[f=0]?0:u;)try{if(o=1,s&&(h=2&i[0]?s.return:i[0]?s.throw||((h=s.return)&&h.call(s),0):s.next)&&!(h=h.call(s,i[1])).done)return h;switch(s=0,(i=h?[2&i[0],h.value]:i)[0]){case 0:case 1:h=i;break;case 4:return u.label++,{value:i[1],done:!1};case 5:u.label++,s=i[1],i=[0];continue;case 7:i=u.ops.pop(),u.trys.pop();continue;default:if(!(h=0<(h=u.trys).length&&h[h.length-1])&&(6===i[0]||2===i[0])){u=0;continue}if(3===i[0]&&(!h||i[1]>h[0]&&i[1]this.C-1)throw new RangeError;t=this.P(t);return this.G(t),this.C},A.prototype.eraseElementByKey=function(t){return 0!==this.C&&(t=this.F(this.g,t))!==this.A&&(this.G(t),!0)},A.prototype.eraseElementByIterator=function(t){var i=t.M,e=(i===this.A&&v(),void 0===i.i);return 0===t.iteratorType?e&&t.next():e&&void 0!==i.t||t.next(),this.G(i),t},A.prototype.getHeight=function(){return 0===this.C?0:function t(i){return i?Math.max(t(i.t),t(i.i))+1:0}(this.g)};var d,a=A;function A(t,i){void 0===t&&(t=function(t,i){return tthis.C-1)throw new RangeError;t=this.P(t);return[t.h,t.o]},O.prototype.find=function(t){t=this.F(this.g,t);return new M(t,this.A,this)},O.prototype.getElementByKey=function(t){return this.F(this.g,t).o},O.prototype.union=function(t){var i=this;return t.forEach(function(t){i.setElement(t[0],t[1])}),this.C},O.prototype[Symbol.iterator]=function(){var i,e,r,n;return o(this,function(t){switch(t.label){case 0:i=this.C,e=this.P(),r=0,t.label=1;case 1:return r + +API Reference +  •   +Documentation +
+ + NPM Release + +
+

+ +This package provides everything needed to interact with the OpenTelemetry API, including all TypeScript interfaces, enums, and no-op implementations. It is intended for use both on the server and in the browser. + +The methods in this package perform no operations by default. This means they can be safely called by a library or end-user application whether there is an SDK registered or not. In order to generate and export telemetry data, you will also need an SDK such as the [OpenTelemetry JS SDK][opentelemetry-js]. + +## Tracing Quick Start + +### You Will Need + +- An application you wish to instrument +- [OpenTelemetry JS SDK][opentelemetry-js] +- Node.js >=8.5.0 (14+ is preferred) or an ECMAScript 5+ compatible browser + +**Note:** ECMAScript 5+ compatibility is for this package only. Please refer to the documentation for the SDK you are using to determine its minimum ECMAScript version. + +**Note for library authors:** Only your end users will need an OpenTelemetry SDK. If you wish to support OpenTelemetry in your library, you only need to use the OpenTelemetry API. For more information, please read the [tracing documentation][docs-tracing]. + +### Install Dependencies + +```sh +npm install @opentelemetry/api @opentelemetry/sdk-trace-base +``` + +### Trace Your Application + +In order to get started with tracing, you will need to first register an SDK. The SDK you are using may provide a convenience method which calls the registration methods for you, but if you would like to call them directly they are documented here: [SDK registration methods][docs-sdk-registration]. + +Once you have registered an SDK, you can start and end spans. A simple example of basic SDK registration and tracing a simple operation is below. The example should export spans to the console once per second. For more information, see the [tracing documentation][docs-tracing]. + +```javascript +const { trace } = require("@opentelemetry/api"); +const { BasicTracerProvider, ConsoleSpanExporter, SimpleSpanProcessor } = require("@opentelemetry/sdk-trace-base"); + +// Create and register an SDK +const provider = new BasicTracerProvider(); +provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter())); +trace.setGlobalTracerProvider(provider); + +// Acquire a tracer from the global tracer provider which will be used to trace the application +const name = 'my-application-name'; +const version = '0.1.0'; +const tracer = trace.getTracer(name, version); + +// Trace your application by creating spans +async function operation() { + const span = tracer.startSpan("do operation"); + + // mock some work by sleeping 1 second + await new Promise((resolve, reject) => { + setTimeout(resolve, 1000); + }) + + span.end(); +} + +async function main() { + while (true) { + await operation(); + } +} + +main(); +``` + +## Version Compatibility + +Because the npm installer and node module resolution algorithm could potentially allow two or more copies of any given package to exist within the same `node_modules` structure, the OpenTelemetry API takes advantage of a variable on the `global` object to store the global API. When an API method in the API package is called, it checks if this `global` API exists and proxies calls to it if and only if it is a compatible API version. This means if a package has a dependency on an OpenTelemetry API version which is not compatible with the API used by the end user, the package will receive a no-op implementation of the API. + +## Upgrade Guidelines + +### 0.21.0 to 1.0.0 + +No breaking changes + +### 0.20.0 to 0.21.0 + +- [#78](https://github.com/open-telemetry/opentelemetry-js-api/issues/78) `api.context.bind` arguments reversed and `context` is now a required argument. +- [#46](https://github.com/open-telemetry/opentelemetry-js-api/issues/46) Noop classes and singletons are no longer exported. To create a noop span it is recommended to use `api.trace.wrapSpanContext` with `INVALID_SPAN_CONTEXT` instead of using the `NOOP_TRACER`. + +### 1.0.0-rc.3 to 0.20.0 + +- Removing `TimedEvent` which was not part of spec +- `HttpBaggage` renamed to `HttpBaggagePropagator` +- [#45](https://github.com/open-telemetry/opentelemetry-js-api/pull/45) `Span#context` renamed to `Span#spanContext` +- [#47](https://github.com/open-telemetry/opentelemetry-js-api/pull/47) `getSpan`/`setSpan`/`getSpanContext`/`setSpanContext` moved to `trace` namespace +- [#55](https://github.com/open-telemetry/opentelemetry-js-api/pull/55) `getBaggage`/`setBaggage`/`createBaggage` moved to `propagation` namespace + +## Useful links + +- For more information on OpenTelemetry, visit: +- For more about OpenTelemetry JavaScript: +- For help or feedback on this project, join us in [GitHub Discussions][discussions-url] + +## License + +Apache 2.0 - See [LICENSE][license-url] for more information. + +[opentelemetry-js]: https://github.com/open-telemetry/opentelemetry-js + +[discussions-url]: https://github.com/open-telemetry/opentelemetry-js/discussions +[license-url]: https://github.com/open-telemetry/opentelemetry-js/blob/main/api/LICENSE +[docs-tracing]: https://github.com/open-telemetry/opentelemetry-js/blob/main/doc/tracing.md +[docs-sdk-registration]: https://github.com/open-telemetry/opentelemetry-js/blob/main/doc/sdk-registration.md diff --git a/node_modules/@opentelemetry/api/build/esm/api/context.d.ts b/node_modules/@opentelemetry/api/build/esm/api/context.d.ts new file mode 100644 index 0000000..61caee8 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/api/context.d.ts @@ -0,0 +1,41 @@ +import { Context, ContextManager } from '../context/types'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Context API + */ +export declare class ContextAPI { + private static _instance?; + /** Empty private constructor prevents end users from constructing a new instance of the API */ + private constructor(); + /** Get the singleton instance of the Context API */ + static getInstance(): ContextAPI; + /** + * Set the current context manager. + * + * @returns true if the context manager was successfully registered, else false + */ + setGlobalContextManager(contextManager: ContextManager): boolean; + /** + * Get the currently active context + */ + active(): Context; + /** + * Execute a function with an active context + * + * @param context context to be active during function execution + * @param fn function to execute in a context + * @param thisArg optional receiver to be used for calling fn + * @param args optional arguments forwarded to fn + */ + with ReturnType>(context: Context, fn: F, thisArg?: ThisParameterType, ...args: A): ReturnType; + /** + * Bind a context to a target function or event emitter + * + * @param context context to bind to the event emitter or function. Defaults to the currently active context + * @param target function or event emitter to bind + */ + bind(context: Context, target: T): T; + private _getContextManager; + /** Disable and remove the global context manager */ + disable(): void; +} +//# sourceMappingURL=context.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/api/context.js b/node_modules/@opentelemetry/api/build/esm/api/context.js new file mode 100644 index 0000000..0d02f97 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/api/context.js @@ -0,0 +1,110 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __read = (this && this.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +}; +var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +}; +import { NoopContextManager } from '../context/NoopContextManager'; +import { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils'; +import { DiagAPI } from './diag'; +var API_NAME = 'context'; +var NOOP_CONTEXT_MANAGER = new NoopContextManager(); +/** + * Singleton object which represents the entry point to the OpenTelemetry Context API + */ +var ContextAPI = /** @class */ (function () { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + function ContextAPI() { + } + /** Get the singleton instance of the Context API */ + ContextAPI.getInstance = function () { + if (!this._instance) { + this._instance = new ContextAPI(); + } + return this._instance; + }; + /** + * Set the current context manager. + * + * @returns true if the context manager was successfully registered, else false + */ + ContextAPI.prototype.setGlobalContextManager = function (contextManager) { + return registerGlobal(API_NAME, contextManager, DiagAPI.instance()); + }; + /** + * Get the currently active context + */ + ContextAPI.prototype.active = function () { + return this._getContextManager().active(); + }; + /** + * Execute a function with an active context + * + * @param context context to be active during function execution + * @param fn function to execute in a context + * @param thisArg optional receiver to be used for calling fn + * @param args optional arguments forwarded to fn + */ + ContextAPI.prototype.with = function (context, fn, thisArg) { + var _a; + var args = []; + for (var _i = 3; _i < arguments.length; _i++) { + args[_i - 3] = arguments[_i]; + } + return (_a = this._getContextManager()).with.apply(_a, __spreadArray([context, fn, thisArg], __read(args), false)); + }; + /** + * Bind a context to a target function or event emitter + * + * @param context context to bind to the event emitter or function. Defaults to the currently active context + * @param target function or event emitter to bind + */ + ContextAPI.prototype.bind = function (context, target) { + return this._getContextManager().bind(context, target); + }; + ContextAPI.prototype._getContextManager = function () { + return getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER; + }; + /** Disable and remove the global context manager */ + ContextAPI.prototype.disable = function () { + this._getContextManager().disable(); + unregisterGlobal(API_NAME, DiagAPI.instance()); + }; + return ContextAPI; +}()); +export { ContextAPI }; +//# sourceMappingURL=context.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/api/context.js.map b/node_modules/@opentelemetry/api/build/esm/api/context.js.map new file mode 100644 index 0000000..6938b71 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/api/context.js.map @@ -0,0 +1 @@ +{"version":3,"file":"context.js","sourceRoot":"","sources":["../../../src/api/context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAEnE,OAAO,EACL,SAAS,EACT,cAAc,EACd,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAEjC,IAAM,QAAQ,GAAG,SAAS,CAAC;AAC3B,IAAM,oBAAoB,GAAG,IAAI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AnED,IAmEC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NoopContextManager } from '../context/NoopContextManager';\nimport { Context, ContextManager } from '../context/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'context';\nconst NOOP_CONTEXT_MANAGER = new NoopContextManager();\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Context API\n */\nexport class ContextAPI {\n private static _instance?: ContextAPI;\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Context API */\n public static getInstance(): ContextAPI {\n if (!this._instance) {\n this._instance = new ContextAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current context manager.\n *\n * @returns true if the context manager was successfully registered, else false\n */\n public setGlobalContextManager(contextManager: ContextManager): boolean {\n return registerGlobal(API_NAME, contextManager, DiagAPI.instance());\n }\n\n /**\n * Get the currently active context\n */\n public active(): Context {\n return this._getContextManager().active();\n }\n\n /**\n * Execute a function with an active context\n *\n * @param context context to be active during function execution\n * @param fn function to execute in a context\n * @param thisArg optional receiver to be used for calling fn\n * @param args optional arguments forwarded to fn\n */\n public with ReturnType>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType,\n ...args: A\n ): ReturnType {\n return this._getContextManager().with(context, fn, thisArg, ...args);\n }\n\n /**\n * Bind a context to a target function or event emitter\n *\n * @param context context to bind to the event emitter or function. Defaults to the currently active context\n * @param target function or event emitter to bind\n */\n public bind(context: Context, target: T): T {\n return this._getContextManager().bind(context, target);\n }\n\n private _getContextManager(): ContextManager {\n return getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER;\n }\n\n /** Disable and remove the global context manager */\n public disable() {\n this._getContextManager().disable();\n unregisterGlobal(API_NAME, DiagAPI.instance());\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/api/diag.d.ts b/node_modules/@opentelemetry/api/build/esm/api/diag.d.ts new file mode 100644 index 0000000..131db17 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/api/diag.d.ts @@ -0,0 +1,30 @@ +import { ComponentLoggerOptions, DiagLogFunction, DiagLogger, DiagLoggerApi } from '../diag/types'; +/** + * Singleton object which represents the entry point to the OpenTelemetry internal + * diagnostic API + */ +export declare class DiagAPI implements DiagLogger, DiagLoggerApi { + private static _instance?; + /** Get the singleton instance of the DiagAPI API */ + static instance(): DiagAPI; + /** + * Private internal constructor + * @private + */ + private constructor(); + setLogger: DiagLoggerApi['setLogger']; + /** + * + */ + createComponentLogger: (options: ComponentLoggerOptions) => DiagLogger; + verbose: DiagLogFunction; + debug: DiagLogFunction; + info: DiagLogFunction; + warn: DiagLogFunction; + error: DiagLogFunction; + /** + * Unregister the global logger and return to Noop + */ + disable: () => void; +} +//# sourceMappingURL=diag.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/api/diag.js b/node_modules/@opentelemetry/api/build/esm/api/diag.js new file mode 100644 index 0000000..25eb9af --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/api/diag.js @@ -0,0 +1,121 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __read = (this && this.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +}; +var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +}; +import { DiagComponentLogger } from '../diag/ComponentLogger'; +import { createLogLevelDiagLogger } from '../diag/internal/logLevelLogger'; +import { DiagLogLevel, } from '../diag/types'; +import { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils'; +var API_NAME = 'diag'; +/** + * Singleton object which represents the entry point to the OpenTelemetry internal + * diagnostic API + */ +var DiagAPI = /** @class */ (function () { + /** + * Private internal constructor + * @private + */ + function DiagAPI() { + function _logProxy(funcName) { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var logger = getGlobal('diag'); + // shortcut if logger not set + if (!logger) + return; + return logger[funcName].apply(logger, __spreadArray([], __read(args), false)); + }; + } + // Using self local variable for minification purposes as 'this' cannot be minified + var self = this; + // DiagAPI specific functions + var setLogger = function (logger, optionsOrLogLevel) { + var _a, _b, _c; + if (optionsOrLogLevel === void 0) { optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }; } + if (logger === self) { + // There isn't much we can do here. + // Logging to the console might break the user application. + // Try to log to self. If a logger was previously registered it will receive the log. + var err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); + self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message); + return false; + } + if (typeof optionsOrLogLevel === 'number') { + optionsOrLogLevel = { + logLevel: optionsOrLogLevel, + }; + } + var oldLogger = getGlobal('diag'); + var newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger); + // There already is an logger registered. We'll let it know before overwriting it. + if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { + var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ''; + oldLogger.warn("Current logger will be overwritten from " + stack); + newLogger.warn("Current logger will overwrite one already registered from " + stack); + } + return registerGlobal('diag', newLogger, self, true); + }; + self.setLogger = setLogger; + self.disable = function () { + unregisterGlobal(API_NAME, self); + }; + self.createComponentLogger = function (options) { + return new DiagComponentLogger(options); + }; + self.verbose = _logProxy('verbose'); + self.debug = _logProxy('debug'); + self.info = _logProxy('info'); + self.warn = _logProxy('warn'); + self.error = _logProxy('error'); + } + /** Get the singleton instance of the DiagAPI API */ + DiagAPI.instance = function () { + if (!this._instance) { + this._instance = new DiagAPI(); + } + return this._instance; + }; + return DiagAPI; +}()); +export { DiagAPI }; +//# sourceMappingURL=diag.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/api/diag.js.map b/node_modules/@opentelemetry/api/build/esm/api/diag.js.map new file mode 100644 index 0000000..380ed2d --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/api/diag.js.map @@ -0,0 +1 @@ +{"version":3,"file":"diag.js","sourceRoot":"","sources":["../../../src/api/diag.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAC9D,OAAO,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AAC3E,OAAO,EAKL,YAAY,GACb,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,SAAS,EACT,cAAc,EACd,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAElC,IAAM,QA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KAAK,EAAE,CAAC,KAAK,mCAAI,iCAAiC,CAAC;gBACrE,SAAS,CAAC,IAAI,CAAC,6CAA2C,KAAO,CAAC,CAAC;gBACnE,SAAS,CAAC,IAAI,CACZ,+DAA6D,KAAO,CACrE,CAAC;aACH;YAED,OAAO,cAAc,CAAC,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;QACvD,CAAC,CAAC;QAEF,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAE3B,IAAI,CAAC,OAAO,GAAG;YACb,gBAAgB,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QACnC,CAAC,CAAC;QAEF,IAAI,CAAC,qBAAqB,GAAG,UAAC,OAA+B;YAC3D,OAAO,IAAI,mBAAmB,CAAC,OAAO,CAAC,CAAC;QAC1C,CAAC,CAAC;QAEF,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC,SAAS,CAAC,CAAC;QACpC,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;QAChC,IAAI,CAAC,IAAI,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;QAC9B,IAAI,CAAC,IAAI,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;QAC9B,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;IAClC,CAAC;IAjFD,oDAAoD;IACtC,gBAAQ,GAAtB;QACE,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;YACnB,IAAI,CAAC,SAAS,GAAG,IAAI,OAAO,EAAE,CAAC;SAChC;QAED,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IA+FH,cAAC;AAAD,CAAC,AAzGD,IAyGC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagComponentLogger } from '../diag/ComponentLogger';\nimport { createLogLevelDiagLogger } from '../diag/internal/logLevelLogger';\nimport {\n ComponentLoggerOptions,\n DiagLogFunction,\n DiagLogger,\n DiagLoggerApi,\n DiagLogLevel,\n} from '../diag/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\n\nconst API_NAME = 'diag';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry internal\n * diagnostic API\n */\nexport class DiagAPI implements DiagLogger, DiagLoggerApi {\n private static _instance?: DiagAPI;\n\n /** Get the singleton instance of the DiagAPI API */\n public static instance(): DiagAPI {\n if (!this._instance) {\n this._instance = new DiagAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Private internal constructor\n * @private\n */\n private constructor() {\n function _logProxy(funcName: keyof DiagLogger): DiagLogFunction {\n return function (...args) {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) return;\n return logger[funcName](...args);\n };\n }\n\n // Using self local variable for minification purposes as 'this' cannot be minified\n const self = this;\n\n // DiagAPI specific functions\n\n const setLogger: DiagLoggerApi['setLogger'] = (\n logger,\n optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }\n ) => {\n if (logger === self) {\n // There isn't much we can do here.\n // Logging to the console might break the user application.\n // Try to log to self. If a logger was previously registered it will receive the log.\n const err = new Error(\n 'Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'\n );\n self.error(err.stack ?? err.message);\n return false;\n }\n\n if (typeof optionsOrLogLevel === 'number') {\n optionsOrLogLevel = {\n logLevel: optionsOrLogLevel,\n };\n }\n\n const oldLogger = getGlobal('diag');\n const newLogger = createLogLevelDiagLogger(\n optionsOrLogLevel.logLevel ?? DiagLogLevel.INFO,\n logger\n );\n // There already is an logger registered. We'll let it know before overwriting it.\n if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {\n const stack = new Error().stack ?? '';\n oldLogger.warn(`Current logger will be overwritten from ${stack}`);\n newLogger.warn(\n `Current logger will overwrite one already registered from ${stack}`\n );\n }\n\n return registerGlobal('diag', newLogger, self, true);\n };\n\n self.setLogger = setLogger;\n\n self.disable = () => {\n unregisterGlobal(API_NAME, self);\n };\n\n self.createComponentLogger = (options: ComponentLoggerOptions) => {\n return new DiagComponentLogger(options);\n };\n\n self.verbose = _logProxy('verbose');\n self.debug = _logProxy('debug');\n self.info = _logProxy('info');\n self.warn = _logProxy('warn');\n self.error = _logProxy('error');\n }\n\n public setLogger!: DiagLoggerApi['setLogger'];\n /**\n *\n */\n public createComponentLogger!: (\n options: ComponentLoggerOptions\n ) => DiagLogger;\n\n // DiagLogger implementation\n public verbose!: DiagLogFunction;\n public debug!: DiagLogFunction;\n public info!: DiagLogFunction;\n public warn!: DiagLogFunction;\n public error!: DiagLogFunction;\n\n /**\n * Unregister the global logger and return to Noop\n */\n public disable!: () => void;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/api/metrics.d.ts b/node_modules/@opentelemetry/api/build/esm/api/metrics.d.ts new file mode 100644 index 0000000..5adc145 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/api/metrics.d.ts @@ -0,0 +1,28 @@ +import { Meter, MeterOptions } from '../metrics/Meter'; +import { MeterProvider } from '../metrics/MeterProvider'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Metrics API + */ +export declare class MetricsAPI { + private static _instance?; + /** Empty private constructor prevents end users from constructing a new instance of the API */ + private constructor(); + /** Get the singleton instance of the Metrics API */ + static getInstance(): MetricsAPI; + /** + * Set the current global meter provider. + * Returns true if the meter provider was successfully registered, else false. + */ + setGlobalMeterProvider(provider: MeterProvider): boolean; + /** + * Returns the global meter provider. + */ + getMeterProvider(): MeterProvider; + /** + * Returns a meter from the global meter provider. + */ + getMeter(name: string, version?: string, options?: MeterOptions): Meter; + /** Remove the global meter provider */ + disable(): void; +} +//# sourceMappingURL=metrics.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/api/metrics.js b/node_modules/@opentelemetry/api/build/esm/api/metrics.js new file mode 100644 index 0000000..92c575a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/api/metrics.js @@ -0,0 +1,60 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NOOP_METER_PROVIDER } from '../metrics/NoopMeterProvider'; +import { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils'; +import { DiagAPI } from './diag'; +var API_NAME = 'metrics'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Metrics API + */ +var MetricsAPI = /** @class */ (function () { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + function MetricsAPI() { + } + /** Get the singleton instance of the Metrics API */ + MetricsAPI.getInstance = function () { + if (!this._instance) { + this._instance = new MetricsAPI(); + } + return this._instance; + }; + /** + * Set the current global meter provider. + * Returns true if the meter provider was successfully registered, else false. + */ + MetricsAPI.prototype.setGlobalMeterProvider = function (provider) { + return registerGlobal(API_NAME, provider, DiagAPI.instance()); + }; + /** + * Returns the global meter provider. + */ + MetricsAPI.prototype.getMeterProvider = function () { + return getGlobal(API_NAME) || NOOP_METER_PROVIDER; + }; + /** + * Returns a meter from the global meter provider. + */ + MetricsAPI.prototype.getMeter = function (name, version, options) { + return this.getMeterProvider().getMeter(name, version, options); + }; + /** Remove the global meter provider */ + MetricsAPI.prototype.disable = function () { + unregisterGlobal(API_NAME, DiagAPI.instance()); + }; + return MetricsAPI; +}()); +export { MetricsAPI }; +//# sourceMappingURL=metrics.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/api/metrics.js.map b/node_modules/@opentelemetry/api/build/esm/api/metrics.js.map new file mode 100644 index 0000000..39c6955 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/api/metrics.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metrics.js","sourceRoot":"","sources":["../../../src/api/metrics.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EACL,SAAS,EACT,cAAc,EACd,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAEjC,IAAM,QAAQ,GAAG,SAAS,CAAC;AAE3B;;GAEG;AACH;IAGE,+FAA+F;IAC/F;IAAuB,CAAC;IAExB,oDAAoD;IACtC,sBAAW,GAAzB;QACE,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;YACnB,IAAI,CAAC,SAAS,GAAG,IAAI,UAAU,EAAE,CAAC;SACnC;QAED,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAED;;;OAGG;IACI,2CAAsB,GAA7B,UAA8B,QAAuB;QACnD,OAAO,cAAc,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;IAChE,CAAC;IAED;;OAEG;IACI,qCAAgB,GAAvB;QACE,OAAO,SAAS,CAAC,QAAQ,CAAC,IAAI,mBAAmB,CAAC;IACpD,CAAC;IAED;;OAEG;IACI,6BAAQ,GAAf,UACE,IAAY,EACZ,OAAgB,EAChB,OAAsB;QAEtB,OAAO,IAAI,CAAC,gBAAgB,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;IAED,uCAAuC;IAChC,4BAAO,GAAd;QACE,gBAAgB,CAAC,QAAQ,EAAE,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;IACjD,CAAC;IACH,iBAAC;AAAD,CAAC,AA7CD,IA6CC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Meter, MeterOptions } from '../metrics/Meter';\nimport { MeterProvider } from '../metrics/MeterProvider';\nimport { NOOP_METER_PROVIDER } from '../metrics/NoopMeterProvider';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'metrics';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Metrics API\n */\nexport class MetricsAPI {\n private static _instance?: MetricsAPI;\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Metrics API */\n public static getInstance(): MetricsAPI {\n if (!this._instance) {\n this._instance = new MetricsAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current global meter provider.\n * Returns true if the meter provider was successfully registered, else false.\n */\n public setGlobalMeterProvider(provider: MeterProvider): boolean {\n return registerGlobal(API_NAME, provider, DiagAPI.instance());\n }\n\n /**\n * Returns the global meter provider.\n */\n public getMeterProvider(): MeterProvider {\n return getGlobal(API_NAME) || NOOP_METER_PROVIDER;\n }\n\n /**\n * Returns a meter from the global meter provider.\n */\n public getMeter(\n name: string,\n version?: string,\n options?: MeterOptions\n ): Meter {\n return this.getMeterProvider().getMeter(name, version, options);\n }\n\n /** Remove the global meter provider */\n public disable(): void {\n unregisterGlobal(API_NAME, DiagAPI.instance());\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/api/propagation.d.ts b/node_modules/@opentelemetry/api/build/esm/api/propagation.d.ts new file mode 100644 index 0000000..a22d24d --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/api/propagation.d.ts @@ -0,0 +1,49 @@ +import { Context } from '../context/types'; +import { TextMapGetter, TextMapPropagator, TextMapSetter } from '../propagation/TextMapPropagator'; +import { getBaggage, getActiveBaggage, setBaggage, deleteBaggage } from '../baggage/context-helpers'; +import { createBaggage } from '../baggage/utils'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Propagation API + */ +export declare class PropagationAPI { + private static _instance?; + /** Empty private constructor prevents end users from constructing a new instance of the API */ + private constructor(); + /** Get the singleton instance of the Propagator API */ + static getInstance(): PropagationAPI; + /** + * Set the current propagator. + * + * @returns true if the propagator was successfully registered, else false + */ + setGlobalPropagator(propagator: TextMapPropagator): boolean; + /** + * Inject context into a carrier to be propagated inter-process + * + * @param context Context carrying tracing data to inject + * @param carrier carrier to inject context into + * @param setter Function used to set values on the carrier + */ + inject(context: Context, carrier: Carrier, setter?: TextMapSetter): void; + /** + * Extract context from a carrier + * + * @param context Context which the newly created context will inherit from + * @param carrier Carrier to extract context from + * @param getter Function used to extract keys from a carrier + */ + extract(context: Context, carrier: Carrier, getter?: TextMapGetter): Context; + /** + * Return a list of all fields which may be used by the propagator. + */ + fields(): string[]; + /** Remove the global propagator */ + disable(): void; + createBaggage: typeof createBaggage; + getBaggage: typeof getBaggage; + getActiveBaggage: typeof getActiveBaggage; + setBaggage: typeof setBaggage; + deleteBaggage: typeof deleteBaggage; + private _getGlobalPropagator; +} +//# sourceMappingURL=propagation.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/api/propagation.js b/node_modules/@opentelemetry/api/build/esm/api/propagation.js new file mode 100644 index 0000000..d3f6f83 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/api/propagation.js @@ -0,0 +1,89 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils'; +import { NoopTextMapPropagator } from '../propagation/NoopTextMapPropagator'; +import { defaultTextMapGetter, defaultTextMapSetter, } from '../propagation/TextMapPropagator'; +import { getBaggage, getActiveBaggage, setBaggage, deleteBaggage, } from '../baggage/context-helpers'; +import { createBaggage } from '../baggage/utils'; +import { DiagAPI } from './diag'; +var API_NAME = 'propagation'; +var NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator(); +/** + * Singleton object which represents the entry point to the OpenTelemetry Propagation API + */ +var PropagationAPI = /** @class */ (function () { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + function PropagationAPI() { + this.createBaggage = createBaggage; + this.getBaggage = getBaggage; + this.getActiveBaggage = getActiveBaggage; + this.setBaggage = setBaggage; + this.deleteBaggage = deleteBaggage; + } + /** Get the singleton instance of the Propagator API */ + PropagationAPI.getInstance = function () { + if (!this._instance) { + this._instance = new PropagationAPI(); + } + return this._instance; + }; + /** + * Set the current propagator. + * + * @returns true if the propagator was successfully registered, else false + */ + PropagationAPI.prototype.setGlobalPropagator = function (propagator) { + return registerGlobal(API_NAME, propagator, DiagAPI.instance()); + }; + /** + * Inject context into a carrier to be propagated inter-process + * + * @param context Context carrying tracing data to inject + * @param carrier carrier to inject context into + * @param setter Function used to set values on the carrier + */ + PropagationAPI.prototype.inject = function (context, carrier, setter) { + if (setter === void 0) { setter = defaultTextMapSetter; } + return this._getGlobalPropagator().inject(context, carrier, setter); + }; + /** + * Extract context from a carrier + * + * @param context Context which the newly created context will inherit from + * @param carrier Carrier to extract context from + * @param getter Function used to extract keys from a carrier + */ + PropagationAPI.prototype.extract = function (context, carrier, getter) { + if (getter === void 0) { getter = defaultTextMapGetter; } + return this._getGlobalPropagator().extract(context, carrier, getter); + }; + /** + * Return a list of all fields which may be used by the propagator. + */ + PropagationAPI.prototype.fields = function () { + return this._getGlobalPropagator().fields(); + }; + /** Remove the global propagator */ + PropagationAPI.prototype.disable = function () { + unregisterGlobal(API_NAME, DiagAPI.instance()); + }; + PropagationAPI.prototype._getGlobalPropagator = function () { + return getGlobal(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; + }; + return PropagationAPI; +}()); +export { PropagationAPI }; +//# sourceMappingURL=propagation.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/api/propagation.js.map b/node_modules/@opentelemetry/api/build/esm/api/propagation.js.map new file mode 100644 index 0000000..1cad8f8 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/api/propagation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"propagation.js","sourceRoot":"","sources":["../../../src/api/propagation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EACL,SAAS,EACT,cAAc,EACd,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EACL,oBAAoB,EACpB,oBAAoB,GAIrB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,UAAU,EACV,gBAAgB,EAChB,UAAU,EACV,aAAa,GACd,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAEjC,IAAM,QAAQ,GAAG,aAAa,CAAC;AAC/B,IAAM,wBAAwB,GAAG,IAAI,qBAAqB,EAAE,CAAC;AAE7D;;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,CAAC,IAAI,wBAAwB,CAAC;IACzD,CAAC;IACH,qBAAC;AAAD,CAAC,AA/ED,IA+EC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { NoopTextMapPropagator } from '../propagation/NoopTextMapPropagator';\nimport {\n defaultTextMapGetter,\n defaultTextMapSetter,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n} from '../propagation/TextMapPropagator';\nimport {\n getBaggage,\n getActiveBaggage,\n setBaggage,\n deleteBaggage,\n} from '../baggage/context-helpers';\nimport { createBaggage } from '../baggage/utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'propagation';\nconst NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator();\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Propagation API\n */\nexport class PropagationAPI {\n private static _instance?: PropagationAPI;\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Propagator API */\n public static getInstance(): PropagationAPI {\n if (!this._instance) {\n this._instance = new PropagationAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current propagator.\n *\n * @returns true if the propagator was successfully registered, else false\n */\n public setGlobalPropagator(propagator: TextMapPropagator): boolean {\n return registerGlobal(API_NAME, propagator, DiagAPI.instance());\n }\n\n /**\n * Inject context into a carrier to be propagated inter-process\n *\n * @param context Context carrying tracing data to inject\n * @param carrier carrier to inject context into\n * @param setter Function used to set values on the carrier\n */\n public inject(\n context: Context,\n carrier: Carrier,\n setter: TextMapSetter = defaultTextMapSetter\n ): void {\n return this._getGlobalPropagator().inject(context, carrier, setter);\n }\n\n /**\n * Extract context from a carrier\n *\n * @param context Context which the newly created context will inherit from\n * @param carrier Carrier to extract context from\n * @param getter Function used to extract keys from a carrier\n */\n public extract(\n context: Context,\n carrier: Carrier,\n getter: TextMapGetter = defaultTextMapGetter\n ): Context {\n return this._getGlobalPropagator().extract(context, carrier, getter);\n }\n\n /**\n * Return a list of all fields which may be used by the propagator.\n */\n public fields(): string[] {\n return this._getGlobalPropagator().fields();\n }\n\n /** Remove the global propagator */\n public disable() {\n unregisterGlobal(API_NAME, DiagAPI.instance());\n }\n\n public createBaggage = createBaggage;\n\n public getBaggage = getBaggage;\n\n public getActiveBaggage = getActiveBaggage;\n\n public setBaggage = setBaggage;\n\n public deleteBaggage = deleteBaggage;\n\n private _getGlobalPropagator(): TextMapPropagator {\n return getGlobal(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR;\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/api/trace.d.ts b/node_modules/@opentelemetry/api/build/esm/api/trace.d.ts new file mode 100644 index 0000000..df59fd2 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/api/trace.d.ts @@ -0,0 +1,40 @@ +import { isSpanContextValid, wrapSpanContext } from '../trace/spancontext-utils'; +import { Tracer } from '../trace/tracer'; +import { TracerProvider } from '../trace/tracer_provider'; +import { deleteSpan, getActiveSpan, getSpan, getSpanContext, setSpan, setSpanContext } from '../trace/context-utils'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Tracing API + */ +export declare class TraceAPI { + private static _instance?; + private _proxyTracerProvider; + /** Empty private constructor prevents end users from constructing a new instance of the API */ + private constructor(); + /** Get the singleton instance of the Trace API */ + static getInstance(): TraceAPI; + /** + * Set the current global tracer. + * + * @returns true if the tracer provider was successfully registered, else false + */ + setGlobalTracerProvider(provider: TracerProvider): boolean; + /** + * Returns the global tracer provider. + */ + getTracerProvider(): TracerProvider; + /** + * Returns a tracer from the global tracer provider. + */ + getTracer(name: string, version?: string): Tracer; + /** Remove the global tracer provider */ + disable(): void; + wrapSpanContext: typeof wrapSpanContext; + isSpanContextValid: typeof isSpanContextValid; + deleteSpan: typeof deleteSpan; + getSpan: typeof getSpan; + getActiveSpan: typeof getActiveSpan; + getSpanContext: typeof getSpanContext; + setSpan: typeof setSpan; + setSpanContext: typeof setSpanContext; +} +//# sourceMappingURL=trace.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/api/trace.js b/node_modules/@opentelemetry/api/build/esm/api/trace.js new file mode 100644 index 0000000..a4aa6e6 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/api/trace.js @@ -0,0 +1,77 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils'; +import { ProxyTracerProvider } from '../trace/ProxyTracerProvider'; +import { isSpanContextValid, wrapSpanContext, } from '../trace/spancontext-utils'; +import { deleteSpan, getActiveSpan, getSpan, getSpanContext, setSpan, setSpanContext, } from '../trace/context-utils'; +import { DiagAPI } from './diag'; +var API_NAME = 'trace'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Tracing API + */ +var TraceAPI = /** @class */ (function () { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + function TraceAPI() { + this._proxyTracerProvider = new ProxyTracerProvider(); + this.wrapSpanContext = wrapSpanContext; + this.isSpanContextValid = isSpanContextValid; + this.deleteSpan = deleteSpan; + this.getSpan = getSpan; + this.getActiveSpan = getActiveSpan; + this.getSpanContext = getSpanContext; + this.setSpan = setSpan; + this.setSpanContext = setSpanContext; + } + /** Get the singleton instance of the Trace API */ + TraceAPI.getInstance = function () { + if (!this._instance) { + this._instance = new TraceAPI(); + } + return this._instance; + }; + /** + * Set the current global tracer. + * + * @returns true if the tracer provider was successfully registered, else false + */ + TraceAPI.prototype.setGlobalTracerProvider = function (provider) { + var success = registerGlobal(API_NAME, this._proxyTracerProvider, DiagAPI.instance()); + if (success) { + this._proxyTracerProvider.setDelegate(provider); + } + return success; + }; + /** + * Returns the global tracer provider. + */ + TraceAPI.prototype.getTracerProvider = function () { + return getGlobal(API_NAME) || this._proxyTracerProvider; + }; + /** + * Returns a tracer from the global tracer provider. + */ + TraceAPI.prototype.getTracer = function (name, version) { + return this.getTracerProvider().getTracer(name, version); + }; + /** Remove the global tracer provider */ + TraceAPI.prototype.disable = function () { + unregisterGlobal(API_NAME, DiagAPI.instance()); + this._proxyTracerProvider = new ProxyTracerProvider(); + }; + return TraceAPI; +}()); +export { TraceAPI }; +//# sourceMappingURL=trace.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/api/trace.js.map b/node_modules/@opentelemetry/api/build/esm/api/trace.js.map new file mode 100644 index 0000000..122b7e2 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/api/trace.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trace.js","sourceRoot":"","sources":["../../../src/api/trace.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EACL,SAAS,EACT,cAAc,EACd,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EACL,kBAAkB,EAClB,eAAe,GAChB,MAAM,4BAA4B,CAAC;AAGpC,OAAO,EACL,UAAU,EACV,aAAa,EACb,OAAO,EACP,cAAc,EACd,OAAO,EACP,cAAc,GACf,MAAM,wBAAwB,C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E,gBAAgB,CAAC,QAAQ,EAAE,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;QAC/C,IAAI,CAAC,oBAAoB,GAAG,IAAI,mBAAmB,EAAE,CAAC;IACxD,CAAC;IAiBH,eAAC;AAAD,CAAC,AArED,IAqEC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { ProxyTracerProvider } from '../trace/ProxyTracerProvider';\nimport {\n isSpanContextValid,\n wrapSpanContext,\n} from '../trace/spancontext-utils';\nimport { Tracer } from '../trace/tracer';\nimport { TracerProvider } from '../trace/tracer_provider';\nimport {\n deleteSpan,\n getActiveSpan,\n getSpan,\n getSpanContext,\n setSpan,\n setSpanContext,\n} from '../trace/context-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'trace';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Tracing API\n */\nexport class TraceAPI {\n private static _instance?: TraceAPI;\n\n private _proxyTracerProvider = new ProxyTracerProvider();\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Trace API */\n public static getInstance(): TraceAPI {\n if (!this._instance) {\n this._instance = new TraceAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current global tracer.\n *\n * @returns true if the tracer provider was successfully registered, else false\n */\n public setGlobalTracerProvider(provider: TracerProvider): boolean {\n const success = registerGlobal(\n API_NAME,\n this._proxyTracerProvider,\n DiagAPI.instance()\n );\n if (success) {\n this._proxyTracerProvider.setDelegate(provider);\n }\n return success;\n }\n\n /**\n * Returns the global tracer provider.\n */\n public getTracerProvider(): TracerProvider {\n return getGlobal(API_NAME) || this._proxyTracerProvider;\n }\n\n /**\n * Returns a tracer from the global tracer provider.\n */\n public getTracer(name: string, version?: string): Tracer {\n return this.getTracerProvider().getTracer(name, version);\n }\n\n /** Remove the global tracer provider */\n public disable() {\n unregisterGlobal(API_NAME, DiagAPI.instance());\n this._proxyTracerProvider = new ProxyTracerProvider();\n }\n\n public wrapSpanContext = wrapSpanContext;\n\n public isSpanContextValid = isSpanContextValid;\n\n public deleteSpan = deleteSpan;\n\n public getSpan = getSpan;\n\n public getActiveSpan = getActiveSpan;\n\n public getSpanContext = getSpanContext;\n\n public setSpan = setSpan;\n\n public setSpanContext = setSpanContext;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.d.ts b/node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.d.ts new file mode 100644 index 0000000..23750eb --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.d.ts @@ -0,0 +1,29 @@ +import { Context } from '../context/types'; +import { Baggage } from './types'; +/** + * Retrieve the current baggage from the given context + * + * @param {Context} Context that manage all context values + * @returns {Baggage} Extracted baggage from the context + */ +export declare function getBaggage(context: Context): Baggage | undefined; +/** + * Retrieve the current baggage from the active/current context + * + * @returns {Baggage} Extracted baggage from the context + */ +export declare function getActiveBaggage(): Baggage | undefined; +/** + * Store a baggage in the given context + * + * @param {Context} Context that manage all context values + * @param {Baggage} baggage that will be set in the actual context + */ +export declare function setBaggage(context: Context, baggage: Baggage): Context; +/** + * Delete the baggage stored in the given context + * + * @param {Context} Context that manage all context values + */ +export declare function deleteBaggage(context: Context): Context; +//# sourceMappingURL=context-helpers.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.js b/node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.js new file mode 100644 index 0000000..6911334 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.js @@ -0,0 +1,56 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ContextAPI } from '../api/context'; +import { createContextKey } from '../context/context'; +/** + * Baggage key + */ +var BAGGAGE_KEY = createContextKey('OpenTelemetry Baggage Key'); +/** + * Retrieve the current baggage from the given context + * + * @param {Context} Context that manage all context values + * @returns {Baggage} Extracted baggage from the context + */ +export function getBaggage(context) { + return context.getValue(BAGGAGE_KEY) || undefined; +} +/** + * Retrieve the current baggage from the active/current context + * + * @returns {Baggage} Extracted baggage from the context + */ +export function getActiveBaggage() { + return getBaggage(ContextAPI.getInstance().active()); +} +/** + * Store a baggage in the given context + * + * @param {Context} Context that manage all context values + * @param {Baggage} baggage that will be set in the actual context + */ +export function setBaggage(context, baggage) { + return context.setValue(BAGGAGE_KEY, baggage); +} +/** + * Delete the baggage stored in the given context + * + * @param {Context} Context that manage all context values + */ +export function deleteBaggage(context) { + return context.deleteValue(BAGGAGE_KEY); +} +//# sourceMappingURL=context-helpers.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.js.map b/node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.js.map new file mode 100644 index 0000000..8670ebd --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"context-helpers.js","sourceRoot":"","sources":["../../../src/baggage/context-helpers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAItD;;GAEG;AACH,IAAM,WAAW,GAAG,gBAAgB,CAAC,2BAA2B,CAAC,CAAC;AAElE;;;;;GAKG;AACH,MAAM,UAAU,UAAU,CAAC,OAAgB;IACzC,OAAQ,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAa,IAAI,SAAS,CAAC;AACjE,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,gBAAgB;IAC9B,OAAO,UAAU,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC;AACvD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,UAAU,CAAC,OAAgB,EAAE,OAAgB;IAC3D,OAAO,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;AAChD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,OAAgB;IAC5C,OAAO,OAAO,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ContextAPI } from '../api/context';\nimport { createContextKey } from '../context/context';\nimport { Context } from '../context/types';\nimport { Baggage } from './types';\n\n/**\n * Baggage key\n */\nconst BAGGAGE_KEY = createContextKey('OpenTelemetry Baggage Key');\n\n/**\n * Retrieve the current baggage from the given context\n *\n * @param {Context} Context that manage all context values\n * @returns {Baggage} Extracted baggage from the context\n */\nexport function getBaggage(context: Context): Baggage | undefined {\n return (context.getValue(BAGGAGE_KEY) as Baggage) || undefined;\n}\n\n/**\n * Retrieve the current baggage from the active/current context\n *\n * @returns {Baggage} Extracted baggage from the context\n */\nexport function getActiveBaggage(): Baggage | undefined {\n return getBaggage(ContextAPI.getInstance().active());\n}\n\n/**\n * Store a baggage in the given context\n *\n * @param {Context} Context that manage all context values\n * @param {Baggage} baggage that will be set in the actual context\n */\nexport function setBaggage(context: Context, baggage: Baggage): Context {\n return context.setValue(BAGGAGE_KEY, baggage);\n}\n\n/**\n * Delete the baggage stored in the given context\n *\n * @param {Context} Context that manage all context values\n */\nexport function deleteBaggage(context: Context): Context {\n return context.deleteValue(BAGGAGE_KEY);\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.d.ts b/node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.d.ts new file mode 100644 index 0000000..e6b4554 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.d.ts @@ -0,0 +1,12 @@ +import type { Baggage, BaggageEntry } from '../types'; +export declare class BaggageImpl implements Baggage { + private _entries; + constructor(entries?: Map); + getEntry(key: string): BaggageEntry | undefined; + getAllEntries(): [string, BaggageEntry][]; + setEntry(key: string, entry: BaggageEntry): BaggageImpl; + removeEntry(key: string): BaggageImpl; + removeEntries(...keys: string[]): BaggageImpl; + clear(): BaggageImpl; +} +//# sourceMappingURL=baggage-impl.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.js b/node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.js new file mode 100644 index 0000000..c29d685 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.js @@ -0,0 +1,98 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __read = (this && this.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +}; +var __values = (this && this.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +}; +var BaggageImpl = /** @class */ (function () { + function BaggageImpl(entries) { + this._entries = entries ? new Map(entries) : new Map(); + } + BaggageImpl.prototype.getEntry = function (key) { + var entry = this._entries.get(key); + if (!entry) { + return undefined; + } + return Object.assign({}, entry); + }; + BaggageImpl.prototype.getAllEntries = function () { + return Array.from(this._entries.entries()).map(function (_a) { + var _b = __read(_a, 2), k = _b[0], v = _b[1]; + return [k, v]; + }); + }; + BaggageImpl.prototype.setEntry = function (key, entry) { + var newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.set(key, entry); + return newBaggage; + }; + BaggageImpl.prototype.removeEntry = function (key) { + var newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.delete(key); + return newBaggage; + }; + BaggageImpl.prototype.removeEntries = function () { + var e_1, _a; + var keys = []; + for (var _i = 0; _i < arguments.length; _i++) { + keys[_i] = arguments[_i]; + } + var newBaggage = new BaggageImpl(this._entries); + try { + for (var keys_1 = __values(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) { + var key = keys_1_1.value; + newBaggage._entries.delete(key); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return)) _a.call(keys_1); + } + finally { if (e_1) throw e_1.error; } + } + return newBaggage; + }; + BaggageImpl.prototype.clear = function () { + return new BaggageImpl(); + }; + return BaggageImpl; +}()); +export { BaggageImpl }; +//# sourceMappingURL=baggage-impl.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.js.map b/node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.js.map new file mode 100644 index 0000000..1f3d95a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.js.map @@ -0,0 +1 @@ +{"version":3,"file":"baggage-impl.js","sourceRoot":"","sources":["../../../../src/baggage/internal/baggage-impl.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIH;IAGE,qBAAY,OAAmC;QAC7C,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,EAAE,CAAC;IACzD,CAAC;IAED,8BAAQ,GAAR,UAAS,GAAW;QAClB,IAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACrC,IAAI,CAAC,KAAK,EAAE;YACV,OAAO,SAAS,CAAC;SAClB;QAED,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;IAClC,CAAC;IAED,mCAAa,GAAb;QACE,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC,GAAG,CAAC,UAAC,EAAM;gBAAN,KAAA,aAAM,EAAL,CAAC,QAAA,EAAE,CAAC,QAAA;YAAM,OAAA,CAAC,CAAC,EAAE,CAAC,CAAC;QAAN,CAAM,CAAC,CAAC;IACrE,CAAC;IAED,8BAAQ,GAAR,UAAS,GAAW,EAAE,KAAmB;QACvC,IAAM,UAAU,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAClD,UAAU,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACpC,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,iCAAW,GAAX,UAAY,GAAW;QACrB,IAAM,UAAU,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAClD,UAAU,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAChC,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,mCAAa,GAAb;;QAAc,cAAiB;aAAjB,UAAiB,EAAjB,qBAAiB,EAAjB,IAAiB;YAAjB,yBAAiB;;QAC7B,IAAM,UAAU,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;;YAClD,KAAkB,IAAA,SAAA,SAAA,IAAI,CAAA,0BAAA,4CAAE;gBAAnB,IAAM,GAAG,iBAAA;gBACZ,UAAU,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;aACjC;;;;;;;;;QACD,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,2BAAK,GAAL;QACE,OAAO,IAAI,WAAW,EAAE,CAAC;IAC3B,CAAC;IACH,kBAAC;AAAD,CAAC,AA3CD,IA2CC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Baggage, BaggageEntry } from '../types';\n\nexport class BaggageImpl implements Baggage {\n private _entries: Map;\n\n constructor(entries?: Map) {\n this._entries = entries ? new Map(entries) : new Map();\n }\n\n getEntry(key: string): BaggageEntry | undefined {\n const entry = this._entries.get(key);\n if (!entry) {\n return undefined;\n }\n\n return Object.assign({}, entry);\n }\n\n getAllEntries(): [string, BaggageEntry][] {\n return Array.from(this._entries.entries()).map(([k, v]) => [k, v]);\n }\n\n setEntry(key: string, entry: BaggageEntry): BaggageImpl {\n const newBaggage = new BaggageImpl(this._entries);\n newBaggage._entries.set(key, entry);\n return newBaggage;\n }\n\n removeEntry(key: string): BaggageImpl {\n const newBaggage = new BaggageImpl(this._entries);\n newBaggage._entries.delete(key);\n return newBaggage;\n }\n\n removeEntries(...keys: string[]): BaggageImpl {\n const newBaggage = new BaggageImpl(this._entries);\n for (const key of keys) {\n newBaggage._entries.delete(key);\n }\n return newBaggage;\n }\n\n clear(): BaggageImpl {\n return new BaggageImpl();\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.d.ts b/node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.d.ts new file mode 100644 index 0000000..9cd991c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.d.ts @@ -0,0 +1,5 @@ +/** + * Symbol used to make BaggageEntryMetadata an opaque type + */ +export declare const baggageEntryMetadataSymbol: unique symbol; +//# sourceMappingURL=symbol.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.js b/node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.js new file mode 100644 index 0000000..0e7dc36 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.js @@ -0,0 +1,20 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Symbol used to make BaggageEntryMetadata an opaque type + */ +export var baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); +//# sourceMappingURL=symbol.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.js.map b/node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.js.map new file mode 100644 index 0000000..f074866 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.js.map @@ -0,0 +1 @@ +{"version":3,"file":"symbol.js","sourceRoot":"","sources":["../../../../src/baggage/internal/symbol.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;GAEG;AACH,MAAM,CAAC,IAAM,0BAA0B,GAAG,MAAM,CAAC,sBAAsB,CAAC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Symbol used to make BaggageEntryMetadata an opaque type\n */\nexport const baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata');\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/baggage/types.d.ts b/node_modules/@opentelemetry/api/build/esm/baggage/types.d.ts new file mode 100644 index 0000000..32fa0ec --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/baggage/types.d.ts @@ -0,0 +1,60 @@ +import { baggageEntryMetadataSymbol } from './internal/symbol'; +export interface BaggageEntry { + /** `String` value of the `BaggageEntry`. */ + value: string; + /** + * Metadata is an optional string property defined by the W3C baggage specification. + * It currently has no special meaning defined by the specification. + */ + metadata?: BaggageEntryMetadata; +} +/** + * Serializable Metadata defined by the W3C baggage specification. + * It currently has no special meaning defined by the OpenTelemetry or W3C. + */ +export declare type BaggageEntryMetadata = { + toString(): string; +} & { + __TYPE__: typeof baggageEntryMetadataSymbol; +}; +/** + * Baggage represents collection of key-value pairs with optional metadata. + * Each key of Baggage is associated with exactly one value. + * Baggage may be used to annotate and enrich telemetry data. + */ +export interface Baggage { + /** + * Get an entry from Baggage if it exists + * + * @param key The key which identifies the BaggageEntry + */ + getEntry(key: string): BaggageEntry | undefined; + /** + * Get a list of all entries in the Baggage + */ + getAllEntries(): [string, BaggageEntry][]; + /** + * Returns a new baggage with the entries from the current bag and the specified entry + * + * @param key string which identifies the baggage entry + * @param entry BaggageEntry for the given key + */ + setEntry(key: string, entry: BaggageEntry): Baggage; + /** + * Returns a new baggage with the entries from the current bag except the removed entry + * + * @param key key identifying the entry to be removed + */ + removeEntry(key: string): Baggage; + /** + * Returns a new baggage with the entries from the current bag except the removed entries + * + * @param key keys identifying the entries to be removed + */ + removeEntries(...key: string[]): Baggage; + /** + * Returns a new baggage with no entries + */ + clear(): Baggage; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/baggage/types.js b/node_modules/@opentelemetry/api/build/esm/baggage/types.js new file mode 100644 index 0000000..928faad --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/baggage/types.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/baggage/types.js.map b/node_modules/@opentelemetry/api/build/esm/baggage/types.js.map new file mode 100644 index 0000000..ae80c19 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/baggage/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/baggage/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { baggageEntryMetadataSymbol } from './internal/symbol';\n\n/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface BaggageEntry {\n /** `String` value of the `BaggageEntry`. */\n value: string;\n /**\n * Metadata is an optional string property defined by the W3C baggage specification.\n * It currently has no special meaning defined by the specification.\n */\n metadata?: BaggageEntryMetadata;\n}\n\n/**\n * Serializable Metadata defined by the W3C baggage specification.\n * It currently has no special meaning defined by the OpenTelemetry or W3C.\n */\nexport type BaggageEntryMetadata = { toString(): string } & {\n __TYPE__: typeof baggageEntryMetadataSymbol;\n};\n\n/**\n * Baggage represents collection of key-value pairs with optional metadata.\n * Each key of Baggage is associated with exactly one value.\n * Baggage may be used to annotate and enrich telemetry data.\n */\nexport interface Baggage {\n /**\n * Get an entry from Baggage if it exists\n *\n * @param key The key which identifies the BaggageEntry\n */\n getEntry(key: string): BaggageEntry | undefined;\n\n /**\n * Get a list of all entries in the Baggage\n */\n getAllEntries(): [string, BaggageEntry][];\n\n /**\n * Returns a new baggage with the entries from the current bag and the specified entry\n *\n * @param key string which identifies the baggage entry\n * @param entry BaggageEntry for the given key\n */\n setEntry(key: string, entry: BaggageEntry): Baggage;\n\n /**\n * Returns a new baggage with the entries from the current bag except the removed entry\n *\n * @param key key identifying the entry to be removed\n */\n removeEntry(key: string): Baggage;\n\n /**\n * Returns a new baggage with the entries from the current bag except the removed entries\n *\n * @param key keys identifying the entries to be removed\n */\n removeEntries(...key: string[]): Baggage;\n\n /**\n * Returns a new baggage with no entries\n */\n clear(): Baggage;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/baggage/utils.d.ts b/node_modules/@opentelemetry/api/build/esm/baggage/utils.d.ts new file mode 100644 index 0000000..9955d9e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/baggage/utils.d.ts @@ -0,0 +1,15 @@ +import { Baggage, BaggageEntry, BaggageEntryMetadata } from './types'; +/** + * Create a new Baggage with optional entries + * + * @param entries An array of baggage entries the new baggage should contain + */ +export declare function createBaggage(entries?: Record): Baggage; +/** + * Create a serializable BaggageEntryMetadata object from a string. + * + * @param str string metadata. Format is currently not defined by the spec and has no special meaning. + * + */ +export declare function baggageEntryMetadataFromString(str: string): BaggageEntryMetadata; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/baggage/utils.js b/node_modules/@opentelemetry/api/build/esm/baggage/utils.js new file mode 100644 index 0000000..3cc2716 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/baggage/utils.js @@ -0,0 +1,47 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DiagAPI } from '../api/diag'; +import { BaggageImpl } from './internal/baggage-impl'; +import { baggageEntryMetadataSymbol } from './internal/symbol'; +var diag = DiagAPI.instance(); +/** + * Create a new Baggage with optional entries + * + * @param entries An array of baggage entries the new baggage should contain + */ +export function createBaggage(entries) { + if (entries === void 0) { entries = {}; } + return new BaggageImpl(new Map(Object.entries(entries))); +} +/** + * Create a serializable BaggageEntryMetadata object from a string. + * + * @param str string metadata. Format is currently not defined by the spec and has no special meaning. + * + */ +export function baggageEntryMetadataFromString(str) { + if (typeof str !== 'string') { + diag.error("Cannot create baggage metadata from unknown type: " + typeof str); + str = ''; + } + return { + __TYPE__: baggageEntryMetadataSymbol, + toString: function () { + return str; + }, + }; +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/baggage/utils.js.map b/node_modules/@opentelemetry/api/build/esm/baggage/utils.js.map new file mode 100644 index 0000000..f5a00f5 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/baggage/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/baggage/utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAG/D,IAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC;AAEhC;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAC3B,OAA0C;IAA1C,wBAAA,EAAA,YAA0C;IAE1C,OAAO,IAAI,WAAW,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;AAC3D,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,8BAA8B,CAC5C,GAAW;IAEX,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;QAC3B,IAAI,CAAC,KAAK,CACR,uDAAqD,OAAO,GAAK,CAClE,CAAC;QACF,GAAG,GAAG,EAAE,CAAC;KACV;IAED,OAAO;QACL,QAAQ,EAAE,0BAA0B;QACpC,QAAQ;YACN,OAAO,GAAG,CAAC;QACb,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagAPI } from '../api/diag';\nimport { BaggageImpl } from './internal/baggage-impl';\nimport { baggageEntryMetadataSymbol } from './internal/symbol';\nimport { Baggage, BaggageEntry, BaggageEntryMetadata } from './types';\n\nconst diag = DiagAPI.instance();\n\n/**\n * Create a new Baggage with optional entries\n *\n * @param entries An array of baggage entries the new baggage should contain\n */\nexport function createBaggage(\n entries: Record = {}\n): Baggage {\n return new BaggageImpl(new Map(Object.entries(entries)));\n}\n\n/**\n * Create a serializable BaggageEntryMetadata object from a string.\n *\n * @param str string metadata. Format is currently not defined by the spec and has no special meaning.\n *\n */\nexport function baggageEntryMetadataFromString(\n str: string\n): BaggageEntryMetadata {\n if (typeof str !== 'string') {\n diag.error(\n `Cannot create baggage metadata from unknown type: ${typeof str}`\n );\n str = '';\n }\n\n return {\n __TYPE__: baggageEntryMetadataSymbol,\n toString() {\n return str;\n },\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/common/Attributes.d.ts b/node_modules/@opentelemetry/api/build/esm/common/Attributes.d.ts new file mode 100644 index 0000000..19994fb --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/common/Attributes.d.ts @@ -0,0 +1,15 @@ +/** + * Attributes is a map from string to attribute values. + * + * Note: only the own enumerable keys are counted as valid attribute keys. + */ +export interface Attributes { + [attributeKey: string]: AttributeValue | undefined; +} +/** + * Attribute values may be any non-nullish primitive value except an object. + * + * null or undefined attribute values are invalid and will result in undefined behavior. + */ +export declare type AttributeValue = string | number | boolean | Array | Array | Array; +//# sourceMappingURL=Attributes.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/common/Attributes.js b/node_modules/@opentelemetry/api/build/esm/common/Attributes.js new file mode 100644 index 0000000..dbb1e49 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/common/Attributes.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=Attributes.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/common/Attributes.js.map b/node_modules/@opentelemetry/api/build/esm/common/Attributes.js.map new file mode 100644 index 0000000..2649c94 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/common/Attributes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Attributes.js","sourceRoot":"","sources":["../../../src/common/Attributes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Attributes is a map from string to attribute values.\n *\n * Note: only the own enumerable keys are counted as valid attribute keys.\n */\nexport interface Attributes {\n [attributeKey: string]: AttributeValue | undefined;\n}\n\n/**\n * Attribute values may be any non-nullish primitive value except an object.\n *\n * null or undefined attribute values are invalid and will result in undefined behavior.\n */\nexport type AttributeValue =\n | string\n | number\n | boolean\n | Array\n | Array\n | Array;\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/common/Exception.d.ts b/node_modules/@opentelemetry/api/build/esm/common/Exception.d.ts new file mode 100644 index 0000000..e175a7f --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/common/Exception.d.ts @@ -0,0 +1,26 @@ +interface ExceptionWithCode { + code: string | number; + name?: string; + message?: string; + stack?: string; +} +interface ExceptionWithMessage { + code?: string | number; + message: string; + name?: string; + stack?: string; +} +interface ExceptionWithName { + code?: string | number; + message?: string; + name: string; + stack?: string; +} +/** + * Defines Exception. + * + * string or an object with one of (message or name or code) and optional stack + */ +export declare type Exception = ExceptionWithCode | ExceptionWithMessage | ExceptionWithName | string; +export {}; +//# sourceMappingURL=Exception.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/common/Exception.js b/node_modules/@opentelemetry/api/build/esm/common/Exception.js new file mode 100644 index 0000000..6522a8e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/common/Exception.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=Exception.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/common/Exception.js.map b/node_modules/@opentelemetry/api/build/esm/common/Exception.js.map new file mode 100644 index 0000000..989dd3d --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/common/Exception.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Exception.js","sourceRoot":"","sources":["../../../src/common/Exception.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\ninterface ExceptionWithCode {\n code: string | number;\n name?: string;\n message?: string;\n stack?: string;\n}\n\ninterface ExceptionWithMessage {\n code?: string | number;\n message: string;\n name?: string;\n stack?: string;\n}\n\ninterface ExceptionWithName {\n code?: string | number;\n message?: string;\n name: string;\n stack?: string;\n}\n\n/**\n * Defines Exception.\n *\n * string or an object with one of (message or name or code) and optional stack\n */\nexport type Exception =\n | ExceptionWithCode\n | ExceptionWithMessage\n | ExceptionWithName\n | string;\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/common/Time.d.ts b/node_modules/@opentelemetry/api/build/esm/common/Time.d.ts new file mode 100644 index 0000000..cc3c502 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/common/Time.d.ts @@ -0,0 +1,20 @@ +/** + * Defines High-Resolution Time. + * + * The first number, HrTime[0], is UNIX Epoch time in seconds since 00:00:00 UTC on 1 January 1970. + * The second number, HrTime[1], represents the partial second elapsed since Unix Epoch time represented by first number in nanoseconds. + * For example, 2021-01-01T12:30:10.150Z in UNIX Epoch time in milliseconds is represented as 1609504210150. + * The first number is calculated by converting and truncating the Epoch time in milliseconds to seconds: + * HrTime[0] = Math.trunc(1609504210150 / 1000) = 1609504210. + * The second number is calculated by converting the digits after the decimal point of the subtraction, (1609504210150 / 1000) - HrTime[0], to nanoseconds: + * HrTime[1] = Number((1609504210.150 - HrTime[0]).toFixed(9)) * 1e9 = 150000000. + * This is represented in HrTime format as [1609504210, 150000000]. + */ +export declare type HrTime = [number, number]; +/** + * Defines TimeInput. + * + * hrtime, epoch milliseconds, performance.now() or Date + */ +export declare type TimeInput = HrTime | number | Date; +//# sourceMappingURL=Time.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/common/Time.js b/node_modules/@opentelemetry/api/build/esm/common/Time.js new file mode 100644 index 0000000..2abdf58 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/common/Time.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=Time.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/common/Time.js.map b/node_modules/@opentelemetry/api/build/esm/common/Time.js.map new file mode 100644 index 0000000..ae124f0 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/common/Time.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Time.js","sourceRoot":"","sources":["../../../src/common/Time.ts"],"names":[],"mappings":"","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Defines High-Resolution Time.\n *\n * The first number, HrTime[0], is UNIX Epoch time in seconds since 00:00:00 UTC on 1 January 1970.\n * The second number, HrTime[1], represents the partial second elapsed since Unix Epoch time represented by first number in nanoseconds.\n * For example, 2021-01-01T12:30:10.150Z in UNIX Epoch time in milliseconds is represented as 1609504210150.\n * The first number is calculated by converting and truncating the Epoch time in milliseconds to seconds:\n * HrTime[0] = Math.trunc(1609504210150 / 1000) = 1609504210.\n * The second number is calculated by converting the digits after the decimal point of the subtraction, (1609504210150 / 1000) - HrTime[0], to nanoseconds:\n * HrTime[1] = Number((1609504210.150 - HrTime[0]).toFixed(9)) * 1e9 = 150000000.\n * This is represented in HrTime format as [1609504210, 150000000].\n */\nexport type HrTime = [number, number];\n\n/**\n * Defines TimeInput.\n *\n * hrtime, epoch milliseconds, performance.now() or Date\n */\nexport type TimeInput = HrTime | number | Date;\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/context-api.d.ts b/node_modules/@opentelemetry/api/build/esm/context-api.d.ts new file mode 100644 index 0000000..650f4ee --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/context-api.d.ts @@ -0,0 +1,4 @@ +import { ContextAPI } from './api/context'; +/** Entrypoint for context API */ +export declare const context: ContextAPI; +//# sourceMappingURL=context-api.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/context-api.js b/node_modules/@opentelemetry/api/build/esm/context-api.js new file mode 100644 index 0000000..b89fb25 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/context-api.js @@ -0,0 +1,21 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +import { ContextAPI } from './api/context'; +/** Entrypoint for context API */ +export var context = ContextAPI.getInstance(); +//# sourceMappingURL=context-api.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/context-api.js.map b/node_modules/@opentelemetry/api/build/esm/context-api.js.map new file mode 100644 index 0000000..a59bfc1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/context-api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"context-api.js","sourceRoot":"","sources":["../../src/context-api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,sEAAsE;AACtE,qCAAqC;AACrC,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,iCAAiC;AACjC,MAAM,CAAC,IAAM,OAAO,GAAG,UAAU,CAAC,WAAW,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { ContextAPI } from './api/context';\n/** Entrypoint for context API */\nexport const context = ContextAPI.getInstance();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.d.ts b/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.d.ts new file mode 100644 index 0000000..48a1659 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.d.ts @@ -0,0 +1,9 @@ +import * as types from './types'; +export declare class NoopContextManager implements types.ContextManager { + active(): types.Context; + with ReturnType>(_context: types.Context, fn: F, thisArg?: ThisParameterType, ...args: A): ReturnType; + bind(_context: types.Context, target: T): T; + enable(): this; + disable(): this; +} +//# sourceMappingURL=NoopContextManager.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js b/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js new file mode 100644 index 0000000..9794eff --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js @@ -0,0 +1,67 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __read = (this && this.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +}; +var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +}; +import { ROOT_CONTEXT } from './context'; +var NoopContextManager = /** @class */ (function () { + function NoopContextManager() { + } + NoopContextManager.prototype.active = function () { + return ROOT_CONTEXT; + }; + NoopContextManager.prototype.with = function (_context, fn, thisArg) { + var args = []; + for (var _i = 3; _i < arguments.length; _i++) { + args[_i - 3] = arguments[_i]; + } + return fn.call.apply(fn, __spreadArray([thisArg], __read(args), false)); + }; + NoopContextManager.prototype.bind = function (_context, target) { + return target; + }; + NoopContextManager.prototype.enable = function () { + return this; + }; + NoopContextManager.prototype.disable = function () { + return this; + }; + return NoopContextManager; +}()); +export { NoopContextManager }; +//# sourceMappingURL=NoopContextManager.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js.map b/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js.map new file mode 100644 index 0000000..045925e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NoopContextManager.js","sourceRoot":"","sources":["../../../src/context/NoopContextManager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAGzC;IAAA;IAyBA,CAAC;IAxBC,mCAAM,GAAN;QACE,OAAO,YAAY,CAAC;IACtB,CAAC;IAED,iCAAI,GAAJ,UACE,QAAuB,EACvB,EAAK,EACL,OAA8B;QAC9B,cAAU;aAAV,UAAU,EAAV,qBAAU,EAAV,IAAU;YAAV,6BAAU;;QAEV,OAAO,EAAE,CAAC,IAAI,OAAP,EAAE,iBAAM,OAAO,UAAK,IAAI,WAAE;IACnC,CAAC;IAED,iCAAI,GAAJ,UAAQ,QAAuB,EAAE,MAAS;QACxC,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,mCAAM,GAAN;QACE,OAAO,IAAI,CAAC;IACd,CAAC;IAED,oCAAO,GAAP;QACE,OAAO,IAAI,CAAC;IACd,CAAC;IACH,yBAAC;AAAD,CAAC,AAzBD,IAyBC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ROOT_CONTEXT } from './context';\nimport * as types from './types';\n\nexport class NoopContextManager implements types.ContextManager {\n active(): types.Context {\n return ROOT_CONTEXT;\n }\n\n with ReturnType>(\n _context: types.Context,\n fn: F,\n thisArg?: ThisParameterType,\n ...args: A\n ): ReturnType {\n return fn.call(thisArg, ...args);\n }\n\n bind(_context: types.Context, target: T): T {\n return target;\n }\n\n enable(): this {\n return this;\n }\n\n disable(): this {\n return this;\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/context/context.d.ts b/node_modules/@opentelemetry/api/build/esm/context/context.d.ts new file mode 100644 index 0000000..8be0259 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/context/context.d.ts @@ -0,0 +1,6 @@ +import { Context } from './types'; +/** Get a key to uniquely identify a context value */ +export declare function createContextKey(description: string): symbol; +/** The root context is used as the default parent context when there is no active context */ +export declare const ROOT_CONTEXT: Context; +//# sourceMappingURL=context.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/context/context.js b/node_modules/@opentelemetry/api/build/esm/context/context.js new file mode 100644 index 0000000..f8909de --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/context/context.js @@ -0,0 +1,52 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Get a key to uniquely identify a context value */ +export function createContextKey(description) { + // The specification states that for the same input, multiple calls should + // return different keys. Due to the nature of the JS dependency management + // system, this creates problems where multiple versions of some package + // could hold different keys for the same property. + // + // Therefore, we use Symbol.for which returns the same key for the same input. + return Symbol.for(description); +} +var BaseContext = /** @class */ (function () { + /** + * Construct a new context which inherits values from an optional parent context. + * + * @param parentContext a context from which to inherit values + */ + function BaseContext(parentContext) { + // for minification + var self = this; + self._currentContext = parentContext ? new Map(parentContext) : new Map(); + self.getValue = function (key) { return self._currentContext.get(key); }; + self.setValue = function (key, value) { + var context = new BaseContext(self._currentContext); + context._currentContext.set(key, value); + return context; + }; + self.deleteValue = function (key) { + var context = new BaseContext(self._currentContext); + context._currentContext.delete(key); + return context; + }; + } + return BaseContext; +}()); +/** The root context is used as the default parent context when there is no active context */ +export var ROOT_CONTEXT = new BaseContext(); +//# sourceMappingURL=context.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/context/context.js.map b/node_modules/@opentelemetry/api/build/esm/context/context.js.map new file mode 100644 index 0000000..7a7affd --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/context/context.js.map @@ -0,0 +1 @@ +{"version":3,"file":"context.js","sourceRoot":"","sources":["../../../src/context/context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,qDAAqD;AACrD,MAAM,UAAU,gBAAgB,CAAC,WAAmB;IAClD,0EAA0E;IAC1E,2EAA2E;IAC3E,wEAAwE;IACxE,mDAAmD;IACnD,EAAE;IACF,8EAA8E;IAC9E,OAAO,MAAM,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;AACjC,CAAC;AAED;IAGE;;;;OAIG;IACH,qBAAY,aAAoC;QAC9C,mBAAmB;QACnB,IAAM,IAAI,GAAG,IAAI,CAAC;QAElB,IAAI,CAAC,eAAe,GAAG,aAAa,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,EAAE,CAAC;QAE1E,IAAI,CAAC,QAAQ,GAAG,UAAC,GAAW,IAAK,OAAA,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,GAAG,CAAC,EAA7B,CAA6B,CAAC;QAE/D,IAAI,CAAC,QAAQ,GAAG,UAAC,GAAW,EAAE,KAAc;YAC1C,IAAM,OAAO,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;YACtD,OAAO,CAAC,eAAe,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;YACxC,OAAO,OAAO,CAAC;QACjB,CAAC,CAAC;QAEF,IAAI,CAAC,WAAW,GAAG,UAAC,GAAW;YAC7B,IAAM,OAAO,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;YACtD,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YACpC,OAAO,OAAO,CAAC;QACjB,CAAC,CAAC;IACJ,CAAC;IAyBH,kBAAC;AAAD,CAAC,AApDD,IAoDC;AAED,6FAA6F;AAC7F,MAAM,CAAC,IAAM,YAAY,GAAY,IAAI,WAAW,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from './types';\n\n/** Get a key to uniquely identify a context value */\nexport function createContextKey(description: string) {\n // The specification states that for the same input, multiple calls should\n // return different keys. Due to the nature of the JS dependency management\n // system, this creates problems where multiple versions of some package\n // could hold different keys for the same property.\n //\n // Therefore, we use Symbol.for which returns the same key for the same input.\n return Symbol.for(description);\n}\n\nclass BaseContext implements Context {\n private _currentContext!: Map;\n\n /**\n * Construct a new context which inherits values from an optional parent context.\n *\n * @param parentContext a context from which to inherit values\n */\n constructor(parentContext?: Map) {\n // for minification\n const self = this;\n\n self._currentContext = parentContext ? new Map(parentContext) : new Map();\n\n self.getValue = (key: symbol) => self._currentContext.get(key);\n\n self.setValue = (key: symbol, value: unknown): Context => {\n const context = new BaseContext(self._currentContext);\n context._currentContext.set(key, value);\n return context;\n };\n\n self.deleteValue = (key: symbol): Context => {\n const context = new BaseContext(self._currentContext);\n context._currentContext.delete(key);\n return context;\n };\n }\n\n /**\n * Get a value from the context.\n *\n * @param key key which identifies a context value\n */\n public getValue!: (key: symbol) => unknown;\n\n /**\n * Create a new context which inherits from this context and has\n * the given key set to the given value.\n *\n * @param key context key for which to set the value\n * @param value value to set for the given key\n */\n public setValue!: (key: symbol, value: unknown) => Context;\n\n /**\n * Return a new context which inherits from this context but does\n * not contain a value for the given key.\n *\n * @param key context key for which to clear a value\n */\n public deleteValue!: (key: symbol) => Context;\n}\n\n/** The root context is used as the default parent context when there is no active context */\nexport const ROOT_CONTEXT: Context = new BaseContext();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/context/types.d.ts b/node_modules/@opentelemetry/api/build/esm/context/types.d.ts new file mode 100644 index 0000000..7e86632 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/context/types.d.ts @@ -0,0 +1,52 @@ +export interface Context { + /** + * Get a value from the context. + * + * @param key key which identifies a context value + */ + getValue(key: symbol): unknown; + /** + * Create a new context which inherits from this context and has + * the given key set to the given value. + * + * @param key context key for which to set the value + * @param value value to set for the given key + */ + setValue(key: symbol, value: unknown): Context; + /** + * Return a new context which inherits from this context but does + * not contain a value for the given key. + * + * @param key context key for which to clear a value + */ + deleteValue(key: symbol): Context; +} +export interface ContextManager { + /** + * Get the current active context + */ + active(): Context; + /** + * Run the fn callback with object set as the current active context + * @param context Any object to set as the current active context + * @param fn A callback to be immediately run within a specific context + * @param thisArg optional receiver to be used for calling fn + * @param args optional arguments forwarded to fn + */ + with ReturnType>(context: Context, fn: F, thisArg?: ThisParameterType, ...args: A): ReturnType; + /** + * Bind an object as the current context (or a specific one) + * @param [context] Optionally specify the context which you want to assign + * @param target Any object to which a context need to be set + */ + bind(context: Context, target: T): T; + /** + * Enable context management + */ + enable(): this; + /** + * Disable context management + */ + disable(): this; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/context/types.js b/node_modules/@opentelemetry/api/build/esm/context/types.js new file mode 100644 index 0000000..928faad --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/context/types.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/context/types.js.map b/node_modules/@opentelemetry/api/build/esm/context/types.js.map new file mode 100644 index 0000000..d438aa3 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/context/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/context/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Context {\n /**\n * Get a value from the context.\n *\n * @param key key which identifies a context value\n */\n getValue(key: symbol): unknown;\n\n /**\n * Create a new context which inherits from this context and has\n * the given key set to the given value.\n *\n * @param key context key for which to set the value\n * @param value value to set for the given key\n */\n setValue(key: symbol, value: unknown): Context;\n\n /**\n * Return a new context which inherits from this context but does\n * not contain a value for the given key.\n *\n * @param key context key for which to clear a value\n */\n deleteValue(key: symbol): Context;\n}\n\nexport interface ContextManager {\n /**\n * Get the current active context\n */\n active(): Context;\n\n /**\n * Run the fn callback with object set as the current active context\n * @param context Any object to set as the current active context\n * @param fn A callback to be immediately run within a specific context\n * @param thisArg optional receiver to be used for calling fn\n * @param args optional arguments forwarded to fn\n */\n with ReturnType>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType,\n ...args: A\n ): ReturnType;\n\n /**\n * Bind an object as the current context (or a specific one)\n * @param [context] Optionally specify the context which you want to assign\n * @param target Any object to which a context need to be set\n */\n bind(context: Context, target: T): T;\n\n /**\n * Enable context management\n */\n enable(): this;\n\n /**\n * Disable context management\n */\n disable(): this;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/diag-api.d.ts b/node_modules/@opentelemetry/api/build/esm/diag-api.d.ts new file mode 100644 index 0000000..d82fdb1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/diag-api.d.ts @@ -0,0 +1,9 @@ +import { DiagAPI } from './api/diag'; +/** + * Entrypoint for Diag API. + * Defines Diagnostic handler used for internal diagnostic logging operations. + * The default provides a Noop DiagLogger implementation which may be changed via the + * diag.setLogger(logger: DiagLogger) function. + */ +export declare const diag: DiagAPI; +//# sourceMappingURL=diag-api.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/diag-api.js b/node_modules/@opentelemetry/api/build/esm/diag-api.js new file mode 100644 index 0000000..9f85c1b --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/diag-api.js @@ -0,0 +1,26 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +import { DiagAPI } from './api/diag'; +/** + * Entrypoint for Diag API. + * Defines Diagnostic handler used for internal diagnostic logging operations. + * The default provides a Noop DiagLogger implementation which may be changed via the + * diag.setLogger(logger: DiagLogger) function. + */ +export var diag = DiagAPI.instance(); +//# sourceMappingURL=diag-api.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/diag-api.js.map b/node_modules/@opentelemetry/api/build/esm/diag-api.js.map new file mode 100644 index 0000000..6b09a0c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/diag-api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"diag-api.js","sourceRoot":"","sources":["../../src/diag-api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,sEAAsE;AACtE,qCAAqC;AACrC,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC;;;;;GAKG;AACH,MAAM,CAAC,IAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { DiagAPI } from './api/diag';\n/**\n * Entrypoint for Diag API.\n * Defines Diagnostic handler used for internal diagnostic logging operations.\n * The default provides a Noop DiagLogger implementation which may be changed via the\n * diag.setLogger(logger: DiagLogger) function.\n */\nexport const diag = DiagAPI.instance();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.d.ts b/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.d.ts new file mode 100644 index 0000000..f060950 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.d.ts @@ -0,0 +1,20 @@ +import { ComponentLoggerOptions, DiagLogger } from './types'; +/** + * Component Logger which is meant to be used as part of any component which + * will add automatically additional namespace in front of the log message. + * It will then forward all message to global diag logger + * @example + * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' }); + * cLogger.debug('test'); + * // @opentelemetry/instrumentation-http test + */ +export declare class DiagComponentLogger implements DiagLogger { + private _namespace; + constructor(props: ComponentLoggerOptions); + debug(...args: any[]): void; + error(...args: any[]): void; + info(...args: any[]): void; + warn(...args: any[]): void; + verbose(...args: any[]): void; +} +//# sourceMappingURL=ComponentLogger.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js b/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js new file mode 100644 index 0000000..44bc8be --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js @@ -0,0 +1,102 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __read = (this && this.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +}; +var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +}; +import { getGlobal } from '../internal/global-utils'; +/** + * Component Logger which is meant to be used as part of any component which + * will add automatically additional namespace in front of the log message. + * It will then forward all message to global diag logger + * @example + * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' }); + * cLogger.debug('test'); + * // @opentelemetry/instrumentation-http test + */ +var DiagComponentLogger = /** @class */ (function () { + function DiagComponentLogger(props) { + this._namespace = props.namespace || 'DiagComponentLogger'; + } + DiagComponentLogger.prototype.debug = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return logProxy('debug', this._namespace, args); + }; + DiagComponentLogger.prototype.error = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return logProxy('error', this._namespace, args); + }; + DiagComponentLogger.prototype.info = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return logProxy('info', this._namespace, args); + }; + DiagComponentLogger.prototype.warn = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return logProxy('warn', this._namespace, args); + }; + DiagComponentLogger.prototype.verbose = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return logProxy('verbose', this._namespace, args); + }; + return DiagComponentLogger; +}()); +export { DiagComponentLogger }; +function logProxy(funcName, namespace, args) { + var logger = getGlobal('diag'); + // shortcut if logger not set + if (!logger) { + return; + } + args.unshift(namespace); + return logger[funcName].apply(logger, __spreadArray([], __read(args), false)); +} +//# sourceMappingURL=ComponentLogger.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js.map b/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js.map new file mode 100644 index 0000000..8671613 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ComponentLogger.js","sourceRoot":"","sources":["../../../src/diag/ComponentLogger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAGrD;;;;;;;;GAQG;AACH;IAGE,6BAAY,KAA6B;QACvC,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC,SAAS,IAAI,qBAAqB,CAAC;IAC7D,CAAC;IAEM,mCAAK,GAAZ;QAAa,cAAc;aAAd,UAAc,EAAd,qBAAc,EAAd,IAAc;YAAd,yBAAc;;QACzB,OAAO,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IAClD,CAAC;IAEM,mCAAK,GAAZ;QAAa,cAAc;aAAd,UAAc,EAAd,qBAAc,EAAd,IAAc;YAAd,yBAAc;;QACzB,OAAO,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IAClD,CAAC;IAEM,kCAAI,GAAX;QAAY,cAAc;aAAd,UAAc,EAAd,qBAAc,EAAd,IAAc;YAAd,yBAAc;;QACxB,OAAO,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IACjD,CAAC;IAEM,kCAAI,GAAX;QAAY,cAAc;aAAd,UAAc,EAAd,qBAAc,EAAd,IAAc;YAAd,yBAAc;;QACxB,OAAO,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IACjD,CAAC;IAEM,qCAAO,GAAd;QAAe,cAAc;aAAd,UAAc,EAAd,qBAAc,EAAd,IAAc;YAAd,yBAAc;;QAC3B,OAAO,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IACpD,CAAC;IACH,0BAAC;AAAD,CAAC,AA1BD,IA0BC;;AAED,SAAS,QAAQ,CACf,QAA0B,EAC1B,SAAiB,EACjB,IAAS;IAET,IAAM,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;IACjC,6BAA6B;IAC7B,IAAI,CAAC,MAAM,EAAE;QACX,OAAO;KACR;IAED,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACxB,OAAO,MAAM,CAAC,QAAQ,CAAC,OAAhB,MAAM,2BAAe,IAAoC,WAAE;AACpE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobal } from '../internal/global-utils';\nimport { ComponentLoggerOptions, DiagLogger, DiagLogFunction } from './types';\n\n/**\n * Component Logger which is meant to be used as part of any component which\n * will add automatically additional namespace in front of the log message.\n * It will then forward all message to global diag logger\n * @example\n * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });\n * cLogger.debug('test');\n * // @opentelemetry/instrumentation-http test\n */\nexport class DiagComponentLogger implements DiagLogger {\n private _namespace: string;\n\n constructor(props: ComponentLoggerOptions) {\n this._namespace = props.namespace || 'DiagComponentLogger';\n }\n\n public debug(...args: any[]): void {\n return logProxy('debug', this._namespace, args);\n }\n\n public error(...args: any[]): void {\n return logProxy('error', this._namespace, args);\n }\n\n public info(...args: any[]): void {\n return logProxy('info', this._namespace, args);\n }\n\n public warn(...args: any[]): void {\n return logProxy('warn', this._namespace, args);\n }\n\n public verbose(...args: any[]): void {\n return logProxy('verbose', this._namespace, args);\n }\n}\n\nfunction logProxy(\n funcName: keyof DiagLogger,\n namespace: string,\n args: any\n): void {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) {\n return;\n }\n\n args.unshift(namespace);\n return logger[funcName](...(args as Parameters));\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/diag/consoleLogger.d.ts b/node_modules/@opentelemetry/api/build/esm/diag/consoleLogger.d.ts new file mode 100644 index 0000000..fa3db1e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/diag/consoleLogger.d.ts @@ -0,0 +1,38 @@ +import { DiagLogger, DiagLogFunction } from './types'; +/** + * A simple Immutable Console based diagnostic logger which will output any messages to the Console. + * If you want to limit the amount of logging to a specific level or lower use the + * {@link createLogLevelDiagLogger} + */ +export declare class DiagConsoleLogger implements DiagLogger { + constructor(); + /** Log an error scenario that was not expected and caused the requested operation to fail. */ + error: DiagLogFunction; + /** + * Log a warning scenario to inform the developer of an issues that should be investigated. + * The requested operation may or may not have succeeded or completed. + */ + warn: DiagLogFunction; + /** + * Log a general informational message, this should not affect functionality. + * This is also the default logging level so this should NOT be used for logging + * debugging level information. + */ + info: DiagLogFunction; + /** + * Log a general debug message that can be useful for identifying a failure. + * Information logged at this level may include diagnostic details that would + * help identify a failure scenario. Useful scenarios would be to log the execution + * order of async operations + */ + debug: DiagLogFunction; + /** + * Log a detailed (verbose) trace level logging that can be used to identify failures + * where debug level logging would be insufficient, this level of tracing can include + * input and output parameters and as such may include PII information passing through + * the API. As such it is recommended that this level of tracing should not be enabled + * in a production environment. + */ + verbose: DiagLogFunction; +} +//# sourceMappingURL=consoleLogger.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/diag/consoleLogger.js b/node_modules/@opentelemetry/api/build/esm/diag/consoleLogger.js new file mode 100644 index 0000000..5965b8a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/diag/consoleLogger.js @@ -0,0 +1,59 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var consoleMap = [ + { n: 'error', c: 'error' }, + { n: 'warn', c: 'warn' }, + { n: 'info', c: 'info' }, + { n: 'debug', c: 'debug' }, + { n: 'verbose', c: 'trace' }, +]; +/** + * A simple Immutable Console based diagnostic logger which will output any messages to the Console. + * If you want to limit the amount of logging to a specific level or lower use the + * {@link createLogLevelDiagLogger} + */ +var DiagConsoleLogger = /** @class */ (function () { + function DiagConsoleLogger() { + function _consoleFunc(funcName) { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (console) { + // Some environments only expose the console when the F12 developer console is open + // eslint-disable-next-line no-console + var theFunc = console[funcName]; + if (typeof theFunc !== 'function') { + // Not all environments support all functions + // eslint-disable-next-line no-console + theFunc = console.log; + } + // One last final check + if (typeof theFunc === 'function') { + return theFunc.apply(console, args); + } + } + }; + } + for (var i = 0; i < consoleMap.length; i++) { + this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); + } + } + return DiagConsoleLogger; +}()); +export { DiagConsoleLogger }; +//# sourceMappingURL=consoleLogger.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/diag/consoleLogger.js.map b/node_modules/@opentelemetry/api/build/esm/diag/consoleLogger.js.map new file mode 100644 index 0000000..fbfd0cf --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/diag/consoleLogger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"consoleLogger.js","sourceRoot":"","sources":["../../../src/diag/consoleLogger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAKH,IAAM,UAAU,GAAiD;IAC/D,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO,EAAE;IAC1B,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE;IACxB,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE;IACxB,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO,EAAE;IAC1B,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,OAAO,EAAE;CAC7B,CAAC;AAEF;;;;GAIG;AACH;IACE;QACE,SAAS,YAAY,CAAC,QAAwB;YAC5C,OAAO;gBAAU,cAAO;qBAAP,UAAO,EAAP,qBAAO,EAAP,IAAO;oBAAP,yBAAO;;gBACtB,IAAI,OAAO,EAAE;oBACX,mFAAmF;oBACnF,sCAAsC;oBACtC,IAAI,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;oBAChC,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE;wBACjC,6CAA6C;wBAC7C,sCAAsC;wBACtC,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC;qBACvB;oBAED,uBAAuB;oBACvB,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE;wBACjC,OAAO,OAAO,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;qBACrC;iBACF;YACH,CAAC,CAAC;QACJ,CAAC;QAED,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,UAAU,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YAC1C,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,YAAY,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;SACvD;IACH,CAAC;IAkCH,wBAAC;AAAD,CAAC,AA3DD,IA2DC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogger, DiagLogFunction } from './types';\n\ntype ConsoleMapKeys = 'error' | 'warn' | 'info' | 'debug' | 'trace';\nconst consoleMap: { n: keyof DiagLogger; c: ConsoleMapKeys }[] = [\n { n: 'error', c: 'error' },\n { n: 'warn', c: 'warn' },\n { n: 'info', c: 'info' },\n { n: 'debug', c: 'debug' },\n { n: 'verbose', c: 'trace' },\n];\n\n/**\n * A simple Immutable Console based diagnostic logger which will output any messages to the Console.\n * If you want to limit the amount of logging to a specific level or lower use the\n * {@link createLogLevelDiagLogger}\n */\nexport class DiagConsoleLogger implements DiagLogger {\n constructor() {\n function _consoleFunc(funcName: ConsoleMapKeys): DiagLogFunction {\n return function (...args) {\n if (console) {\n // Some environments only expose the console when the F12 developer console is open\n // eslint-disable-next-line no-console\n let theFunc = console[funcName];\n if (typeof theFunc !== 'function') {\n // Not all environments support all functions\n // eslint-disable-next-line no-console\n theFunc = console.log;\n }\n\n // One last final check\n if (typeof theFunc === 'function') {\n return theFunc.apply(console, args);\n }\n }\n };\n }\n\n for (let i = 0; i < consoleMap.length; i++) {\n this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c);\n }\n }\n\n /** Log an error scenario that was not expected and caused the requested operation to fail. */\n public error!: DiagLogFunction;\n\n /**\n * Log a warning scenario to inform the developer of an issues that should be investigated.\n * The requested operation may or may not have succeeded or completed.\n */\n public warn!: DiagLogFunction;\n\n /**\n * Log a general informational message, this should not affect functionality.\n * This is also the default logging level so this should NOT be used for logging\n * debugging level information.\n */\n public info!: DiagLogFunction;\n\n /**\n * Log a general debug message that can be useful for identifying a failure.\n * Information logged at this level may include diagnostic details that would\n * help identify a failure scenario. Useful scenarios would be to log the execution\n * order of async operations\n */\n public debug!: DiagLogFunction;\n\n /**\n * Log a detailed (verbose) trace level logging that can be used to identify failures\n * where debug level logging would be insufficient, this level of tracing can include\n * input and output parameters and as such may include PII information passing through\n * the API. As such it is recommended that this level of tracing should not be enabled\n * in a production environment.\n */\n public verbose!: DiagLogFunction;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.d.ts b/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.d.ts new file mode 100644 index 0000000..890b9f1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.d.ts @@ -0,0 +1,3 @@ +import { DiagLogger, DiagLogLevel } from '../types'; +export declare function createLogLevelDiagLogger(maxLevel: DiagLogLevel, logger: DiagLogger): DiagLogger; +//# sourceMappingURL=logLevelLogger.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js b/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js new file mode 100644 index 0000000..aedab38 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js @@ -0,0 +1,41 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DiagLogLevel } from '../types'; +export function createLogLevelDiagLogger(maxLevel, logger) { + if (maxLevel < DiagLogLevel.NONE) { + maxLevel = DiagLogLevel.NONE; + } + else if (maxLevel > DiagLogLevel.ALL) { + maxLevel = DiagLogLevel.ALL; + } + // In case the logger is null or undefined + logger = logger || {}; + function _filterFunc(funcName, theLevel) { + var theFunc = logger[funcName]; + if (typeof theFunc === 'function' && maxLevel >= theLevel) { + return theFunc.bind(logger); + } + return function () { }; + } + return { + error: _filterFunc('error', DiagLogLevel.ERROR), + warn: _filterFunc('warn', DiagLogLevel.WARN), + info: _filterFunc('info', DiagLogLevel.INFO), + debug: _filterFunc('debug', DiagLogLevel.DEBUG), + verbose: _filterFunc('verbose', DiagLogLevel.VERBOSE), + }; +} +//# sourceMappingURL=logLevelLogger.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js.map b/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js.map new file mode 100644 index 0000000..7f9fafd --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"logLevelLogger.js","sourceRoot":"","sources":["../../../../src/diag/internal/logLevelLogger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAA+B,YAAY,EAAE,MAAM,UAAU,CAAC;AAErE,MAAM,UAAU,wBAAwB,CACtC,QAAsB,EACtB,MAAkB;IAElB,IAAI,QAAQ,GAAG,YAAY,CAAC,IAAI,EAAE;QAChC,QAAQ,GAAG,YAAY,CAAC,IAAI,CAAC;KAC9B;SAAM,IAAI,QAAQ,GAAG,YAAY,CAAC,GAAG,EAAE;QACtC,QAAQ,GAAG,YAAY,CAAC,GAAG,CAAC;KAC7B;IAED,0CAA0C;IAC1C,MAAM,GAAG,MAAM,IAAI,EAAE,CAAC;IAEtB,SAAS,WAAW,CAClB,QAA0B,EAC1B,QAAsB;QAEtB,IAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;QAEjC,IAAI,OAAO,OAAO,KAAK,UAAU,IAAI,QAAQ,IAAI,QAAQ,EAAE;YACzD,OAAO,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;SAC7B;QACD,OAAO,cAAa,CAAC,CAAC;IACxB,CAAC;IAED,OAAO;QACL,KAAK,EAAE,WAAW,CAAC,OAAO,EAAE,YAAY,CAAC,KAAK,CAAC;QAC/C,IAAI,EAAE,WAAW,CAAC,MAAM,EAAE,YAAY,CAAC,IAAI,CAAC;QAC5C,IAAI,EAAE,WAAW,CAAC,MAAM,EAAE,YAAY,CAAC,IAAI,CAAC;QAC5C,KAAK,EAAE,WAAW,CAAC,OAAO,EAAE,YAAY,CAAC,KAAK,CAAC;QAC/C,OAAO,EAAE,WAAW,CAAC,SAAS,EAAE,YAAY,CAAC,OAAO,CAAC;KACtD,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogFunction, DiagLogger, DiagLogLevel } from '../types';\n\nexport function createLogLevelDiagLogger(\n maxLevel: DiagLogLevel,\n logger: DiagLogger\n): DiagLogger {\n if (maxLevel < DiagLogLevel.NONE) {\n maxLevel = DiagLogLevel.NONE;\n } else if (maxLevel > DiagLogLevel.ALL) {\n maxLevel = DiagLogLevel.ALL;\n }\n\n // In case the logger is null or undefined\n logger = logger || {};\n\n function _filterFunc(\n funcName: keyof DiagLogger,\n theLevel: DiagLogLevel\n ): DiagLogFunction {\n const theFunc = logger[funcName];\n\n if (typeof theFunc === 'function' && maxLevel >= theLevel) {\n return theFunc.bind(logger);\n }\n return function () {};\n }\n\n return {\n error: _filterFunc('error', DiagLogLevel.ERROR),\n warn: _filterFunc('warn', DiagLogLevel.WARN),\n info: _filterFunc('info', DiagLogLevel.INFO),\n debug: _filterFunc('debug', DiagLogLevel.DEBUG),\n verbose: _filterFunc('verbose', DiagLogLevel.VERBOSE),\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/diag/internal/noopLogger.d.ts b/node_modules/@opentelemetry/api/build/esm/diag/internal/noopLogger.d.ts new file mode 100644 index 0000000..ac71ee3 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/diag/internal/noopLogger.d.ts @@ -0,0 +1,8 @@ +import { DiagLogger } from '../types'; +/** + * Returns a No-Op Diagnostic logger where all messages do nothing. + * @implements {@link DiagLogger} + * @returns {DiagLogger} + */ +export declare function createNoopDiagLogger(): DiagLogger; +//# sourceMappingURL=noopLogger.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/diag/internal/noopLogger.js b/node_modules/@opentelemetry/api/build/esm/diag/internal/noopLogger.js new file mode 100644 index 0000000..7d5ba63 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/diag/internal/noopLogger.js @@ -0,0 +1,31 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function noopLogFunction() { } +/** + * Returns a No-Op Diagnostic logger where all messages do nothing. + * @implements {@link DiagLogger} + * @returns {DiagLogger} + */ +export function createNoopDiagLogger() { + return { + verbose: noopLogFunction, + debug: noopLogFunction, + info: noopLogFunction, + warn: noopLogFunction, + error: noopLogFunction, + }; +} +//# sourceMappingURL=noopLogger.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/diag/internal/noopLogger.js.map b/node_modules/@opentelemetry/api/build/esm/diag/internal/noopLogger.js.map new file mode 100644 index 0000000..bf20aea --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/diag/internal/noopLogger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"noopLogger.js","sourceRoot":"","sources":["../../../../src/diag/internal/noopLogger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,SAAS,eAAe,KAAI,CAAC;AAE7B;;;;GAIG;AACH,MAAM,UAAU,oBAAoB;IAClC,OAAO;QACL,OAAO,EAAE,eAAe;QACxB,KAAK,EAAE,eAAe;QACtB,IAAI,EAAE,eAAe;QACrB,IAAI,EAAE,eAAe;QACrB,KAAK,EAAE,eAAe;KACvB,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogger } from '../types';\n\nfunction noopLogFunction() {}\n\n/**\n * Returns a No-Op Diagnostic logger where all messages do nothing.\n * @implements {@link DiagLogger}\n * @returns {DiagLogger}\n */\nexport function createNoopDiagLogger(): DiagLogger {\n return {\n verbose: noopLogFunction,\n debug: noopLogFunction,\n info: noopLogFunction,\n warn: noopLogFunction,\n error: noopLogFunction,\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/diag/types.d.ts b/node_modules/@opentelemetry/api/build/esm/diag/types.d.ts new file mode 100644 index 0000000..e992cc5 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/diag/types.d.ts @@ -0,0 +1,100 @@ +export declare type DiagLogFunction = (message: string, ...args: unknown[]) => void; +/** + * Defines an internal diagnostic logger interface which is used to log internal diagnostic + * messages, you can set the default diagnostic logger via the {@link DiagAPI} setLogger function. + * API provided implementations include :- + * - a No-Op {@link createNoopDiagLogger} + * - a {@link DiagLogLevel} filtering wrapper {@link createLogLevelDiagLogger} + * - a general Console {@link DiagConsoleLogger} version. + */ +export interface DiagLogger { + /** Log an error scenario that was not expected and caused the requested operation to fail. */ + error: DiagLogFunction; + /** + * Log a warning scenario to inform the developer of an issues that should be investigated. + * The requested operation may or may not have succeeded or completed. + */ + warn: DiagLogFunction; + /** + * Log a general informational message, this should not affect functionality. + * This is also the default logging level so this should NOT be used for logging + * debugging level information. + */ + info: DiagLogFunction; + /** + * Log a general debug message that can be useful for identifying a failure. + * Information logged at this level may include diagnostic details that would + * help identify a failure scenario. + * For example: Logging the order of execution of async operations. + */ + debug: DiagLogFunction; + /** + * Log a detailed (verbose) trace level logging that can be used to identify failures + * where debug level logging would be insufficient, this level of tracing can include + * input and output parameters and as such may include PII information passing through + * the API. As such it is recommended that this level of tracing should not be enabled + * in a production environment. + */ + verbose: DiagLogFunction; +} +/** + * Defines the available internal logging levels for the diagnostic logger, the numeric values + * of the levels are defined to match the original values from the initial LogLevel to avoid + * compatibility/migration issues for any implementation that assume the numeric ordering. + */ +export declare enum DiagLogLevel { + /** Diagnostic Logging level setting to disable all logging (except and forced logs) */ + NONE = 0, + /** Identifies an error scenario */ + ERROR = 30, + /** Identifies a warning scenario */ + WARN = 50, + /** General informational log message */ + INFO = 60, + /** General debug log message */ + DEBUG = 70, + /** + * Detailed trace level logging should only be used for development, should only be set + * in a development environment. + */ + VERBOSE = 80, + /** Used to set the logging level to include all logging */ + ALL = 9999 +} +/** + * Defines options for ComponentLogger + */ +export interface ComponentLoggerOptions { + namespace: string; +} +export interface DiagLoggerOptions { + /** + * The {@link DiagLogLevel} used to filter logs sent to the logger. + * + * @defaultValue DiagLogLevel.INFO + */ + logLevel?: DiagLogLevel; + /** + * Setting this value to `true` will suppress the warning message normally emitted when registering a logger when another logger is already registered. + */ + suppressOverrideMessage?: boolean; +} +export interface DiagLoggerApi { + /** + * Set the global DiagLogger and DiagLogLevel. + * If a global diag logger is already set, this will override it. + * + * @param logger - The {@link DiagLogger} instance to set as the default logger. + * @param options - A {@link DiagLoggerOptions} object. If not provided, default values will be set. + * @returns `true` if the logger was successfully registered, else `false` + */ + setLogger(logger: DiagLogger, options?: DiagLoggerOptions): boolean; + /** + * + * @param logger - The {@link DiagLogger} instance to set as the default logger. + * @param logLevel - The {@link DiagLogLevel} used to filter logs sent to the logger. If not provided it will default to {@link DiagLogLevel.INFO}. + * @returns `true` if the logger was successfully registered, else `false` + */ + setLogger(logger: DiagLogger, logLevel?: DiagLogLevel): boolean; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/diag/types.js b/node_modules/@opentelemetry/api/build/esm/diag/types.js new file mode 100644 index 0000000..306585e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/diag/types.js @@ -0,0 +1,41 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Defines the available internal logging levels for the diagnostic logger, the numeric values + * of the levels are defined to match the original values from the initial LogLevel to avoid + * compatibility/migration issues for any implementation that assume the numeric ordering. + */ +export var DiagLogLevel; +(function (DiagLogLevel) { + /** Diagnostic Logging level setting to disable all logging (except and forced logs) */ + DiagLogLevel[DiagLogLevel["NONE"] = 0] = "NONE"; + /** Identifies an error scenario */ + DiagLogLevel[DiagLogLevel["ERROR"] = 30] = "ERROR"; + /** Identifies a warning scenario */ + DiagLogLevel[DiagLogLevel["WARN"] = 50] = "WARN"; + /** General informational log message */ + DiagLogLevel[DiagLogLevel["INFO"] = 60] = "INFO"; + /** General debug log message */ + DiagLogLevel[DiagLogLevel["DEBUG"] = 70] = "DEBUG"; + /** + * Detailed trace level logging should only be used for development, should only be set + * in a development environment. + */ + DiagLogLevel[DiagLogLevel["VERBOSE"] = 80] = "VERBOSE"; + /** Used to set the logging level to include all logging */ + DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL"; +})(DiagLogLevel || (DiagLogLevel = {})); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/diag/types.js.map b/node_modules/@opentelemetry/api/build/esm/diag/types.js.map new file mode 100644 index 0000000..6578cce --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/diag/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/diag/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AA+CH;;;;GAIG;AACH,MAAM,CAAN,IAAY,YAwBX;AAxBD,WAAY,YAAY;IACtB,uFAAuF;IACvF,+CAAQ,CAAA;IAER,mCAAmC;IACnC,kDAAU,CAAA;IAEV,oCAAoC;IACpC,gDAAS,CAAA;IAET,wCAAwC;IACxC,gDAAS,CAAA;IAET,gCAAgC;IAChC,kDAAU,CAAA;IAEV;;;OAGG;IACH,sDAAY,CAAA;IAEZ,2DAA2D;IAC3D,gDAAU,CAAA;AACZ,CAAC,EAxBW,YAAY,KAAZ,YAAY,QAwBvB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type DiagLogFunction = (message: string, ...args: unknown[]) => void;\n\n/**\n * Defines an internal diagnostic logger interface which is used to log internal diagnostic\n * messages, you can set the default diagnostic logger via the {@link DiagAPI} setLogger function.\n * API provided implementations include :-\n * - a No-Op {@link createNoopDiagLogger}\n * - a {@link DiagLogLevel} filtering wrapper {@link createLogLevelDiagLogger}\n * - a general Console {@link DiagConsoleLogger} version.\n */\nexport interface DiagLogger {\n /** Log an error scenario that was not expected and caused the requested operation to fail. */\n error: DiagLogFunction;\n\n /**\n * Log a warning scenario to inform the developer of an issues that should be investigated.\n * The requested operation may or may not have succeeded or completed.\n */\n warn: DiagLogFunction;\n\n /**\n * Log a general informational message, this should not affect functionality.\n * This is also the default logging level so this should NOT be used for logging\n * debugging level information.\n */\n info: DiagLogFunction;\n\n /**\n * Log a general debug message that can be useful for identifying a failure.\n * Information logged at this level may include diagnostic details that would\n * help identify a failure scenario.\n * For example: Logging the order of execution of async operations.\n */\n debug: DiagLogFunction;\n\n /**\n * Log a detailed (verbose) trace level logging that can be used to identify failures\n * where debug level logging would be insufficient, this level of tracing can include\n * input and output parameters and as such may include PII information passing through\n * the API. As such it is recommended that this level of tracing should not be enabled\n * in a production environment.\n */\n verbose: DiagLogFunction;\n}\n\n/**\n * Defines the available internal logging levels for the diagnostic logger, the numeric values\n * of the levels are defined to match the original values from the initial LogLevel to avoid\n * compatibility/migration issues for any implementation that assume the numeric ordering.\n */\nexport enum DiagLogLevel {\n /** Diagnostic Logging level setting to disable all logging (except and forced logs) */\n NONE = 0,\n\n /** Identifies an error scenario */\n ERROR = 30,\n\n /** Identifies a warning scenario */\n WARN = 50,\n\n /** General informational log message */\n INFO = 60,\n\n /** General debug log message */\n DEBUG = 70,\n\n /**\n * Detailed trace level logging should only be used for development, should only be set\n * in a development environment.\n */\n VERBOSE = 80,\n\n /** Used to set the logging level to include all logging */\n ALL = 9999,\n}\n\n/**\n * Defines options for ComponentLogger\n */\nexport interface ComponentLoggerOptions {\n namespace: string;\n}\n\nexport interface DiagLoggerOptions {\n /**\n * The {@link DiagLogLevel} used to filter logs sent to the logger.\n *\n * @defaultValue DiagLogLevel.INFO\n */\n logLevel?: DiagLogLevel;\n\n /**\n * Setting this value to `true` will suppress the warning message normally emitted when registering a logger when another logger is already registered.\n */\n suppressOverrideMessage?: boolean;\n}\n\nexport interface DiagLoggerApi {\n /**\n * Set the global DiagLogger and DiagLogLevel.\n * If a global diag logger is already set, this will override it.\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param options - A {@link DiagLoggerOptions} object. If not provided, default values will be set.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, options?: DiagLoggerOptions): boolean;\n\n /**\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param logLevel - The {@link DiagLogLevel} used to filter logs sent to the logger. If not provided it will default to {@link DiagLogLevel.INFO}.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, logLevel?: DiagLogLevel): boolean;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/experimental/index.d.ts b/node_modules/@opentelemetry/api/build/esm/experimental/index.d.ts new file mode 100644 index 0000000..bec3965 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/experimental/index.d.ts @@ -0,0 +1,3 @@ +export { wrapTracer, SugaredTracer } from './trace/SugaredTracer'; +export { SugaredSpanOptions } from './trace/SugaredOptions'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/experimental/index.js b/node_modules/@opentelemetry/api/build/esm/experimental/index.js new file mode 100644 index 0000000..8400e49 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/experimental/index.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { wrapTracer, SugaredTracer } from './trace/SugaredTracer'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/experimental/index.js.map b/node_modules/@opentelemetry/api/build/esm/experimental/index.js.map new file mode 100644 index 0000000..d1699d9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/experimental/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/experimental/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport { wrapTracer, SugaredTracer } from './trace/SugaredTracer';\nexport { SugaredSpanOptions } from './trace/SugaredOptions';\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredOptions.d.ts b/node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredOptions.d.ts new file mode 100644 index 0000000..89040af --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredOptions.d.ts @@ -0,0 +1,13 @@ +import { Span, SpanOptions } from '../../'; +/** + * Options needed for span creation + */ +export interface SugaredSpanOptions extends SpanOptions { + /** + * function to overwrite default exception behavior to record the exception. No exceptions should be thrown in the function. + * @param e Error which triggered this exception + * @param span current span from context + */ + onException?: (e: Error, span: Span) => void; +} +//# sourceMappingURL=SugaredOptions.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredOptions.js b/node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredOptions.js new file mode 100644 index 0000000..0c6a2bd --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredOptions.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=SugaredOptions.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredOptions.js.map b/node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredOptions.js.map new file mode 100644 index 0000000..2a18a56 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredOptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SugaredOptions.js","sourceRoot":"","sources":["../../../../src/experimental/trace/SugaredOptions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Span, SpanOptions } from '../../';\n\n/**\n * Options needed for span creation\n */\nexport interface SugaredSpanOptions extends SpanOptions {\n /**\n * function to overwrite default exception behavior to record the exception. No exceptions should be thrown in the function.\n * @param e Error which triggered this exception\n * @param span current span from context\n */\n onException?: (e: Error, span: Span) => void;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredTracer.d.ts b/node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredTracer.d.ts new file mode 100644 index 0000000..1ba7da9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredTracer.d.ts @@ -0,0 +1,64 @@ +import { SugaredSpanOptions } from './SugaredOptions'; +import { Context, Span, Tracer } from '../../'; +/** + * return a new SugaredTracer created from the supplied one + * @param tracer + */ +export declare function wrapTracer(tracer: Tracer): SugaredTracer; +export declare class SugaredTracer implements Tracer { + private readonly _tracer; + constructor(tracer: Tracer); + startActiveSpan: Tracer['startActiveSpan']; + startSpan: Tracer['startSpan']; + /** + * Starts a new {@link Span} and calls the given function passing it the + * created span as first argument. + * Additionally, the new span gets set in context and this context is activated + * for the duration of the function call. + * The span will be closed after the function has executed. + * If an exception occurs, it is recorded, the status is set to ERROR and the exception is rethrown. + * + * @param name The name of the span + * @param [options] SugaredSpanOptions used for span creation + * @param [context] Context to use to extract parent + * @param fn function called in the context of the span and receives the newly created span as an argument + * @returns return value of fn + * @example + * const something = tracer.withActiveSpan('op', span => { + * // do some work + * }); + * @example + * const something = await tracer.withActiveSpan('op', span => { + * // do some async work + * }); + */ + withActiveSpan ReturnType>(name: string, fn: F): ReturnType; + withActiveSpan ReturnType>(name: string, options: SugaredSpanOptions, fn: F): ReturnType; + withActiveSpan ReturnType>(name: string, options: SugaredSpanOptions, context: Context, fn: F): ReturnType; + /** + * Starts a new {@link Span} and ends it after execution of fn without setting it on context. + * The span will be closed after the function has executed. + * If an exception occurs, it is recorded, the status is et to ERROR and rethrown. + * + * This method does NOT modify the current Context. + * + * @param name The name of the span + * @param [options] SugaredSpanOptions used for span creation + * @param [context] Context to use to extract parent + * @param fn function called in the context of the span and receives the newly created span as an argument + * @returns Span The newly created span + * @example + * const something = tracer.withSpan('op', span => { + * // do some work + * }); + * @example + * const something = await tracer.withSpan('op', span => { + * // do some async work + * }); + */ + withSpan ReturnType>(name: string, fn: F): ReturnType; + withSpan ReturnType>(name: string, options: SugaredSpanOptions, fn: F): ReturnType; + withSpan ReturnType>(name: string, options: SugaredSpanOptions, context: Context, fn: F): ReturnType; + withSpan ReturnType>(name: string, options: SugaredSpanOptions, context: Context, fn: F): ReturnType; +} +//# sourceMappingURL=SugaredTracer.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredTracer.js b/node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredTracer.js new file mode 100644 index 0000000..6fb98de --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredTracer.js @@ -0,0 +1,92 @@ +import { context, SpanStatusCode } from '../../'; +var defaultOnException = function (e, span) { + span.recordException(e); + span.setStatus({ + code: SpanStatusCode.ERROR, + }); +}; +/** + * return a new SugaredTracer created from the supplied one + * @param tracer + */ +export function wrapTracer(tracer) { + return new SugaredTracer(tracer); +} +var SugaredTracer = /** @class */ (function () { + function SugaredTracer(tracer) { + this._tracer = tracer; + this.startSpan = tracer.startSpan.bind(this._tracer); + this.startActiveSpan = tracer.startActiveSpan.bind(this._tracer); + } + SugaredTracer.prototype.withActiveSpan = function (name, arg2, arg3, arg4) { + var _a = massageParams(arg2, arg3, arg4), opts = _a.opts, ctx = _a.ctx, fn = _a.fn; + return this._tracer.startActiveSpan(name, opts, ctx, function (span) { + return handleFn(span, opts, fn); + }); + }; + SugaredTracer.prototype.withSpan = function (name, arg2, arg3, arg4) { + var _a = massageParams(arg2, arg3, arg4), opts = _a.opts, ctx = _a.ctx, fn = _a.fn; + var span = this._tracer.startSpan(name, opts, ctx); + return handleFn(span, opts, fn); + }; + return SugaredTracer; +}()); +export { SugaredTracer }; +/** + * Massages parameters of withSpan and withActiveSpan to allow signature overwrites + * @param arg + * @param arg2 + * @param arg3 + */ +function massageParams(arg, arg2, arg3) { + var opts; + var ctx; + var fn; + if (!arg2 && !arg3) { + fn = arg; + } + else if (!arg3) { + opts = arg; + fn = arg2; + } + else { + opts = arg; + ctx = arg2; + fn = arg3; + } + opts = opts !== null && opts !== void 0 ? opts : {}; + ctx = ctx !== null && ctx !== void 0 ? ctx : context.active(); + return { opts: opts, ctx: ctx, fn: fn }; +} +/** + * Executes fn, returns results and runs onException in the case of exception to allow overwriting of error handling + * @param span + * @param opts + * @param fn + */ +function handleFn(span, opts, fn) { + var _a; + var onException = (_a = opts.onException) !== null && _a !== void 0 ? _a : defaultOnException; + var errorHandler = function (e) { + onException(e, span); + span.end(); + throw e; + }; + try { + var ret = fn(span); + // if fn is an async function, attach a recordException and spanEnd callback to the promise + if (typeof (ret === null || ret === void 0 ? void 0 : ret.then) === 'function') { + return ret.then(function (val) { + span.end(); + return val; + }, errorHandler); + } + span.end(); + return ret; + } + catch (e) { + // add throw to signal the compiler that this will throw in the inner scope + throw errorHandler(e); + } +} +//# sourceMappingURL=SugaredTracer.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredTracer.js.map b/node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredTracer.js.map new file mode 100644 index 0000000..d9bac44 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredTracer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SugaredTracer.js","sourceRoot":"","sources":["../../../../src/experimental/trace/SugaredTracer.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,OAAO,EAAiB,cAAc,EAAU,MAAM,QAAQ,CAAC;AAExE,IAAM,kBAAkB,GAAG,UAAC,CAAQ,EAAE,IAAU;IAC9C,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC;IACxB,IAAI,CAAC,SAAS,CAAC;QACb,IAAI,EAAE,cAAc,CAAC,KAAK;KAC3B,CAAC,CAAC;AACL,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAC,MAAc;IACvC,OAAO,IAAI,aAAa,CAAC,MAAM,CAAC,CAAC;AACnC,CAAC;AAED;IAGE,uBAAY,MAAc;QACxB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACrD,IAAI,CAAC,eAAe,GAAG,MAAM,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACnE,CAAC;IA0CD,sCAAc,GAAd,UACE,IAAY,EACZ,IAA4B,EAC5B,IAAkB,EAClB,IAAQ;QAEF,IAAA,KAAoB,aAAa,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,EAAjD,IAAI,UAAA,EAAE,GAAG,SAAA,EAAE,EAAE,QAAoC,CAAC;QAE1D,OAAO,IAAI,CAAC,OAAO,CAAC,eAAe,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,UAAC,IAAU;YAC9D,OAAA,QAAQ,CAAC,IAAI,EAAE,IAAI,E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,IAAM,WAAW,GAAG,MAAA,IAAI,CAAC,WAAW,mCAAI,kBAAkB,CAAC;IAC3D,IAAM,YAAY,GAAG,UAAC,CAAQ;QAC5B,WAAW,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;QACrB,IAAI,CAAC,GAAG,EAAE,CAAC;QACX,MAAM,CAAC,CAAC;IACV,CAAC,CAAC;IAEF,IAAI;QACF,IAAM,GAAG,GAAG,EAAE,CAAC,IAAI,CAA2B,CAAC;QAC/C,2FAA2F;QAC3F,IAAI,OAAO,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,IAAI,CAAA,KAAK,UAAU,EAAE;YACnC,OAAO,GAAG,CAAC,IAAI,CAAC,UAAA,GAAG;gBACjB,IAAI,CAAC,GAAG,EAAE,CAAC;gBACX,OAAO,GAAG,CAAC;YACb,CAAC,EAAE,YAAY,CAAkB,CAAC;SACnC;QACD,IAAI,CAAC,GAAG,EAAE,CAAC;QACX,OAAO,GAAoB,CAAC;KAC7B;IAAC,OAAO,CAAC,EAAE;QACV,2EAA2E;QAC3E,MAAM,YAAY,CAAC,CAAC,CAAC,CAAC;KACvB;AACH,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { SugaredSpanOptions } from './SugaredOptions';\nimport { context, Context, Span, SpanStatusCode, Tracer } from '../../';\n\nconst defaultOnException = (e: Error, span: Span) => {\n span.recordException(e);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n });\n};\n\n/**\n * return a new SugaredTracer created from the supplied one\n * @param tracer\n */\nexport function wrapTracer(tracer: Tracer): SugaredTracer {\n return new SugaredTracer(tracer);\n}\n\nexport class SugaredTracer implements Tracer {\n private readonly _tracer: Tracer;\n\n constructor(tracer: Tracer) {\n this._tracer = tracer;\n this.startSpan = tracer.startSpan.bind(this._tracer);\n this.startActiveSpan = tracer.startActiveSpan.bind(this._tracer);\n }\n\n startActiveSpan: Tracer['startActiveSpan'];\n startSpan: Tracer['startSpan'];\n\n /**\n * Starts a new {@link Span} and calls the given function passing it the\n * created span as first argument.\n * Additionally, the new span gets set in context and this context is activated\n * for the duration of the function call.\n * The span will be closed after the function has executed.\n * If an exception occurs, it is recorded, the status is set to ERROR and the exception is rethrown.\n *\n * @param name The name of the span\n * @param [options] SugaredSpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns return value of fn\n * @example\n * const something = tracer.withActiveSpan('op', span => {\n * // do some work\n * });\n * @example\n * const something = await tracer.withActiveSpan('op', span => {\n * // do some async work\n * });\n */\n withActiveSpan ReturnType>(\n name: string,\n fn: F\n ): ReturnType;\n withActiveSpan ReturnType>(\n name: string,\n options: SugaredSpanOptions,\n fn: F\n ): ReturnType;\n withActiveSpan ReturnType>(\n name: string,\n options: SugaredSpanOptions,\n context: Context,\n fn: F\n ): ReturnType;\n withActiveSpan ReturnType>(\n name: string,\n arg2: F | SugaredSpanOptions,\n arg3?: F | Context,\n arg4?: F\n ): ReturnType {\n const { opts, ctx, fn } = massageParams(arg2, arg3, arg4);\n\n return this._tracer.startActiveSpan(name, opts, ctx, (span: Span) =>\n handleFn(span, opts, fn)\n ) as ReturnType;\n }\n\n /**\n * Starts a new {@link Span} and ends it after execution of fn without setting it on context.\n * The span will be closed after the function has executed.\n * If an exception occurs, it is recorded, the status is et to ERROR and rethrown.\n *\n * This method does NOT modify the current Context.\n *\n * @param name The name of the span\n * @param [options] SugaredSpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns Span The newly created span\n * @example\n * const something = tracer.withSpan('op', span => {\n * // do some work\n * });\n * @example\n * const something = await tracer.withSpan('op', span => {\n * // do some async work\n * });\n */\n withSpan ReturnType>(\n name: string,\n fn: F\n ): ReturnType;\n withSpan ReturnType>(\n name: string,\n options: SugaredSpanOptions,\n fn: F\n ): ReturnType;\n withSpan ReturnType>(\n name: string,\n options: SugaredSpanOptions,\n context: Context,\n fn: F\n ): ReturnType;\n withSpan ReturnType>(\n name: string,\n options: SugaredSpanOptions,\n context: Context,\n fn: F\n ): ReturnType;\n withSpan ReturnType>(\n name: string,\n arg2: SugaredSpanOptions | F,\n arg3?: Context | F,\n arg4?: F\n ): ReturnType {\n const { opts, ctx, fn } = massageParams(arg2, arg3, arg4);\n\n const span = this._tracer.startSpan(name, opts, ctx);\n return handleFn(span, opts, fn) as ReturnType;\n }\n}\n\n/**\n * Massages parameters of withSpan and withActiveSpan to allow signature overwrites\n * @param arg\n * @param arg2\n * @param arg3\n */\nfunction massageParams ReturnType>(\n arg: F | SugaredSpanOptions,\n arg2?: F | Context,\n arg3?: F\n) {\n let opts: SugaredSpanOptions | undefined;\n let ctx: Context | undefined;\n let fn: F;\n\n if (!arg2 && !arg3) {\n fn = arg as F;\n } else if (!arg3) {\n opts = arg as SugaredSpanOptions;\n fn = arg2 as F;\n } else {\n opts = arg as SugaredSpanOptions;\n ctx = arg2 as Context;\n fn = arg3 as F;\n }\n opts = opts ?? {};\n ctx = ctx ?? context.active();\n\n return { opts, ctx, fn };\n}\n\n/**\n * Executes fn, returns results and runs onException in the case of exception to allow overwriting of error handling\n * @param span\n * @param opts\n * @param fn\n */\nfunction handleFn ReturnType>(\n span: Span,\n opts: SugaredSpanOptions,\n fn: F\n): ReturnType {\n const onException = opts.onException ?? defaultOnException;\n const errorHandler = (e: Error) => {\n onException(e, span);\n span.end();\n throw e;\n };\n\n try {\n const ret = fn(span) as Promise>;\n // if fn is an async function, attach a recordException and spanEnd callback to the promise\n if (typeof ret?.then === 'function') {\n return ret.then(val => {\n span.end();\n return val;\n }, errorHandler) as ReturnType;\n }\n span.end();\n return ret as ReturnType;\n } catch (e) {\n // add throw to signal the compiler that this will throw in the inner scope\n throw errorHandler(e);\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/index.d.ts b/node_modules/@opentelemetry/api/build/esm/index.d.ts new file mode 100644 index 0000000..eea88f2 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/index.d.ts @@ -0,0 +1,54 @@ +export { BaggageEntry, BaggageEntryMetadata, Baggage } from './baggage/types'; +export { baggageEntryMetadataFromString } from './baggage/utils'; +export { Exception } from './common/Exception'; +export { HrTime, TimeInput } from './common/Time'; +export { Attributes, AttributeValue } from './common/Attributes'; +export { createContextKey, ROOT_CONTEXT } from './context/context'; +export { Context, ContextManager } from './context/types'; +export type { ContextAPI } from './api/context'; +export { DiagConsoleLogger } from './diag/consoleLogger'; +export { DiagLogFunction, DiagLogger, DiagLogLevel, ComponentLoggerOptions, DiagLoggerOptions, } from './diag/types'; +export type { DiagAPI } from './api/diag'; +export { createNoopMeter } from './metrics/NoopMeter'; +export { MeterOptions, Meter } from './metrics/Meter'; +export { MeterProvider } from './metrics/MeterProvider'; +export { ValueType, Counter, Gauge, Histogram, MetricOptions, Observable, ObservableCounter, ObservableGauge, ObservableUpDownCounter, UpDownCounter, BatchObservableCallback, MetricAdvice, MetricAttributes, MetricAttributeValue, ObservableCallback, } from './metrics/Metric'; +export { BatchObservableResult, ObservableResult, } from './metrics/ObservableResult'; +export type { MetricsAPI } from './api/metrics'; +export { TextMapPropagator, TextMapSetter, TextMapGetter, defaultTextMapGetter, defaultTextMapSetter, } from './propagation/TextMapPropagator'; +export type { PropagationAPI } from './api/propagation'; +export { SpanAttributes, SpanAttributeValue } from './trace/attributes'; +export { Link } from './trace/link'; +export { ProxyTracer, TracerDelegator } from './trace/ProxyTracer'; +export { ProxyTracerProvider } from './trace/ProxyTracerProvider'; +export { Sampler } from './trace/Sampler'; +export { SamplingDecision, SamplingResult } from './trace/SamplingResult'; +export { SpanContext } from './trace/span_context'; +export { SpanKind } from './trace/span_kind'; +export { Span } from './trace/span'; +export { SpanOptions } from './trace/SpanOptions'; +export { SpanStatus, SpanStatusCode } from './trace/status'; +export { TraceFlags } from './trace/trace_flags'; +export { TraceState } from './trace/trace_state'; +export { createTraceState } from './trace/internal/utils'; +export { TracerProvider } from './trace/tracer_provider'; +export { Tracer } from './trace/tracer'; +export { TracerOptions } from './trace/tracer_options'; +export { isSpanContextValid, isValidTraceId, isValidSpanId, } from './trace/spancontext-utils'; +export { INVALID_SPANID, INVALID_TRACEID, INVALID_SPAN_CONTEXT, } from './trace/invalid-span-constants'; +export type { TraceAPI } from './api/trace'; +import { context } from './context-api'; +import { diag } from './diag-api'; +import { metrics } from './metrics-api'; +import { propagation } from './propagation-api'; +import { trace } from './trace-api'; +export { context, diag, metrics, propagation, trace }; +declare const _default: { + context: import("./api/context").ContextAPI; + diag: import("./api/diag").DiagAPI; + metrics: import("./api/metrics").MetricsAPI; + propagation: import("./api/propagation").PropagationAPI; + trace: import("./api/trace").TraceAPI; +}; +export default _default; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/index.js b/node_modules/@opentelemetry/api/build/esm/index.js new file mode 100644 index 0000000..70cd870 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/index.js @@ -0,0 +1,53 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { baggageEntryMetadataFromString } from './baggage/utils'; +// Context APIs +export { createContextKey, ROOT_CONTEXT } from './context/context'; +// Diag APIs +export { DiagConsoleLogger } from './diag/consoleLogger'; +export { DiagLogLevel, } from './diag/types'; +// Metrics APIs +export { createNoopMeter } from './metrics/NoopMeter'; +export { ValueType, } from './metrics/Metric'; +// Propagation APIs +export { defaultTextMapGetter, defaultTextMapSetter, } from './propagation/TextMapPropagator'; +export { ProxyTracer } from './trace/ProxyTracer'; +export { ProxyTracerProvider } from './trace/ProxyTracerProvider'; +export { SamplingDecision } from './trace/SamplingResult'; +export { SpanKind } from './trace/span_kind'; +export { SpanStatusCode } from './trace/status'; +export { TraceFlags } from './trace/trace_flags'; +export { createTraceState } from './trace/internal/utils'; +export { isSpanContextValid, isValidTraceId, isValidSpanId, } from './trace/spancontext-utils'; +export { INVALID_SPANID, INVALID_TRACEID, INVALID_SPAN_CONTEXT, } from './trace/invalid-span-constants'; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +import { context } from './context-api'; +import { diag } from './diag-api'; +import { metrics } from './metrics-api'; +import { propagation } from './propagation-api'; +import { trace } from './trace-api'; +// Named export. +export { context, diag, metrics, propagation, trace }; +// Default export. +export default { + context: context, + diag: diag, + metrics: metrics, + propagation: propagation, + trace: trace, +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/index.js.map b/node_modules/@opentelemetry/api/build/esm/index.js.map new file mode 100644 index 0000000..b4fec2f --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,8BAA8B,EAAE,MAAM,iBAAiB,CAAC;AAKjE,eAAe;AACf,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAInE,YAAY;AACZ,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAGL,YAAY,GAGb,MAAM,cAAc,CAAC;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OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { BaggageEntry, BaggageEntryMetadata, Baggage } from './baggage/types';\nexport { baggageEntryMetadataFromString } from './baggage/utils';\nexport { Exception } from './common/Exception';\nexport { HrTime, TimeInput } from './common/Time';\nexport { Attributes, AttributeValue } from './common/Attributes';\n\n// Context APIs\nexport { createContextKey, ROOT_CONTEXT } from './context/context';\nexport { Context, ContextManager } from './context/types';\nexport type { ContextAPI } from './api/context';\n\n// Diag APIs\nexport { DiagConsoleLogger } from './diag/consoleLogger';\nexport {\n DiagLogFunction,\n DiagLogger,\n DiagLogLevel,\n ComponentLoggerOptions,\n DiagLoggerOptions,\n} from './diag/types';\nexport type { DiagAPI } from './api/diag';\n\n// Metrics APIs\nexport { createNoopMeter } from './metrics/NoopMeter';\nexport { MeterOptions, Meter } from './metrics/Meter';\nexport { MeterProvider } from './metrics/MeterProvider';\nexport {\n ValueType,\n Counter,\n Gauge,\n Histogram,\n MetricOptions,\n Observable,\n ObservableCounter,\n ObservableGauge,\n ObservableUpDownCounter,\n UpDownCounter,\n BatchObservableCallback,\n MetricAdvice,\n MetricAttributes,\n MetricAttributeValue,\n ObservableCallback,\n} from './metrics/Metric';\nexport {\n BatchObservableResult,\n ObservableResult,\n} from './metrics/ObservableResult';\nexport type { MetricsAPI } from './api/metrics';\n\n// Propagation APIs\nexport {\n TextMapPropagator,\n TextMapSetter,\n TextMapGetter,\n defaultTextMapGetter,\n defaultTextMapSetter,\n} from './propagation/TextMapPropagator';\nexport type { PropagationAPI } from './api/propagation';\n\n// Trace APIs\nexport { SpanAttributes, SpanAttributeValue } from './trace/attributes';\nexport { Link } from './trace/link';\nexport { ProxyTracer, TracerDelegator } from './trace/ProxyTracer';\nexport { ProxyTracerProvider } from './trace/ProxyTracerProvider';\nexport { Sampler } from './trace/Sampler';\nexport { SamplingDecision, SamplingResult } from './trace/SamplingResult';\nexport { SpanContext } from './trace/span_context';\nexport { SpanKind } from './trace/span_kind';\nexport { Span } from './trace/span';\nexport { SpanOptions } from './trace/SpanOptions';\nexport { SpanStatus, SpanStatusCode } from './trace/status';\nexport { TraceFlags } from './trace/trace_flags';\nexport { TraceState } from './trace/trace_state';\nexport { createTraceState } from './trace/internal/utils';\nexport { TracerProvider } from './trace/tracer_provider';\nexport { Tracer } from './trace/tracer';\nexport { TracerOptions } from './trace/tracer_options';\nexport {\n isSpanContextValid,\n isValidTraceId,\n isValidSpanId,\n} from './trace/spancontext-utils';\nexport {\n INVALID_SPANID,\n INVALID_TRACEID,\n INVALID_SPAN_CONTEXT,\n} from './trace/invalid-span-constants';\nexport type { TraceAPI } from './api/trace';\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { context } from './context-api';\nimport { diag } from './diag-api';\nimport { metrics } from './metrics-api';\nimport { propagation } from './propagation-api';\nimport { trace } from './trace-api';\n\n// Named export.\nexport { context, diag, metrics, propagation, trace };\n// Default export.\nexport default {\n context,\n diag,\n metrics,\n propagation,\n trace,\n};\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/internal/global-utils.d.ts b/node_modules/@opentelemetry/api/build/esm/internal/global-utils.d.ts new file mode 100644 index 0000000..320db97 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/internal/global-utils.d.ts @@ -0,0 +1,18 @@ +import { MeterProvider } from '../metrics/MeterProvider'; +import { ContextManager } from '../context/types'; +import { DiagLogger } from '../diag/types'; +import { TextMapPropagator } from '../propagation/TextMapPropagator'; +import type { TracerProvider } from '../trace/tracer_provider'; +export declare function registerGlobal(type: Type, instance: OTelGlobalAPI[Type], diag: DiagLogger, allowOverride?: boolean): boolean; +export declare function getGlobal(type: Type): OTelGlobalAPI[Type] | undefined; +export declare function unregisterGlobal(type: keyof OTelGlobalAPI, diag: DiagLogger): void; +declare type OTelGlobalAPI = { + version: string; + diag?: DiagLogger; + trace?: TracerProvider; + context?: ContextManager; + metrics?: MeterProvider; + propagation?: TextMapPropagator; +}; +export {}; +//# sourceMappingURL=global-utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js b/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js new file mode 100644 index 0000000..88e82a1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js @@ -0,0 +1,59 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { _globalThis } from '../platform'; +import { VERSION } from '../version'; +import { isCompatible } from './semver'; +var major = VERSION.split('.')[0]; +var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major); +var _global = _globalThis; +export function registerGlobal(type, instance, diag, allowOverride) { + var _a; + if (allowOverride === void 0) { allowOverride = false; } + var api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { + version: VERSION, + }); + if (!allowOverride && api[type]) { + // already registered an API of this type + var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type); + diag.error(err.stack || err.message); + return false; + } + if (api.version !== VERSION) { + // All registered APIs must be of the same version exactly + var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION); + diag.error(err.stack || err.message); + return false; + } + api[type] = instance; + diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION + "."); + return true; +} +export function getGlobal(type) { + var _a, _b; + var globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; + if (!globalVersion || !isCompatible(globalVersion)) { + return; + } + return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; +} +export function unregisterGlobal(type, diag) { + diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION + "."); + var api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; + if (api) { + delete api[type]; + } +} +//# sourceMappingURL=global-utils.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js.map b/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js.map new file mode 100644 index 0000000..41420b9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"global-utils.js","sourceRoot":"","sources":["../../../src/internal/global-utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAKH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAG1C,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAExC,IAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AACpC,IAAM,4BAA4B,GAAG,MAAM,CAAC,GAAG,CAC7C,0BAAwB,KAAO,CAChC,CAAC;AAEF,IAAM,OAAO,GAAG,WAAyB,CAAC;AAE1C,MAAM,UAAU,cAAc,CAC5B,IAAU,EACV,QAA6B,EAC7B,IAAgB,EAChB,aAAqB;;IAArB,8BAAA,EAAA,qBAAqB;IAErB,IAAM,GAAG,GAAG,CAAC,OAAO,CAAC,4BAA4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4BAA4B,CAAC,CAAC;IAElD,IAAI,GAAG,EAAE;QACP,OAAO,GAAG,CAAC,IAAI,CAAC,CAAC;KAClB;AACH,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MeterProvider } from '../metrics/MeterProvider';\nimport { ContextManager } from '../context/types';\nimport { DiagLogger } from '../diag/types';\nimport { _globalThis } from '../platform';\nimport { TextMapPropagator } from '../propagation/TextMapPropagator';\nimport type { TracerProvider } from '../trace/tracer_provider';\nimport { VERSION } from '../version';\nimport { isCompatible } from './semver';\n\nconst major = VERSION.split('.')[0];\nconst GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(\n `opentelemetry.js.api.${major}`\n);\n\nconst _global = _globalThis as OTelGlobal;\n\nexport function registerGlobal(\n type: Type,\n instance: OTelGlobalAPI[Type],\n diag: DiagLogger,\n allowOverride = false\n): boolean {\n const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = _global[\n GLOBAL_OPENTELEMETRY_API_KEY\n ] ?? {\n version: VERSION,\n });\n\n if (!allowOverride && api[type]) {\n // already registered an API of this type\n const err = new Error(\n `@opentelemetry/api: Attempted duplicate registration of API: ${type}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n if (api.version !== VERSION) {\n // All registered APIs must be of the same version exactly\n const err = new Error(\n `@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n api[type] = instance;\n diag.debug(\n `@opentelemetry/api: Registered a global for ${type} v${VERSION}.`\n );\n\n return true;\n}\n\nexport function getGlobal(\n type: Type\n): OTelGlobalAPI[Type] | undefined {\n const globalVersion = _global[GLOBAL_OPENTELEMETRY_API_KEY]?.version;\n if (!globalVersion || !isCompatible(globalVersion)) {\n return;\n }\n return _global[GLOBAL_OPENTELEMETRY_API_KEY]?.[type];\n}\n\nexport function unregisterGlobal(type: keyof OTelGlobalAPI, diag: DiagLogger) {\n diag.debug(\n `@opentelemetry/api: Unregistering a global for ${type} v${VERSION}.`\n );\n const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];\n\n if (api) {\n delete api[type];\n }\n}\n\ntype OTelGlobal = {\n [GLOBAL_OPENTELEMETRY_API_KEY]?: OTelGlobalAPI;\n};\n\ntype OTelGlobalAPI = {\n version: string;\n\n diag?: DiagLogger;\n trace?: TracerProvider;\n context?: ContextManager;\n metrics?: MeterProvider;\n propagation?: TextMapPropagator;\n};\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/internal/semver.d.ts b/node_modules/@opentelemetry/api/build/esm/internal/semver.d.ts new file mode 100644 index 0000000..d9f4259 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/internal/semver.d.ts @@ -0,0 +1,34 @@ +/** + * Create a function to test an API version to see if it is compatible with the provided ownVersion. + * + * The returned function has the following semantics: + * - Exact match is always compatible + * - Major versions must match exactly + * - 1.x package cannot use global 2.x package + * - 2.x package cannot use global 1.x package + * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API + * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects + * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 + * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor + * - Patch and build tag differences are not considered at this time + * + * @param ownVersion version which should be checked against + */ +export declare function _makeCompatibilityCheck(ownVersion: string): (globalVersion: string) => boolean; +/** + * Test an API version to see if it is compatible with this API. + * + * - Exact match is always compatible + * - Major versions must match exactly + * - 1.x package cannot use global 2.x package + * - 2.x package cannot use global 1.x package + * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API + * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects + * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 + * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor + * - Patch and build tag differences are not considered at this time + * + * @param version version of the API requesting an instance of the global API + */ +export declare const isCompatible: (globalVersion: string) => boolean; +//# sourceMappingURL=semver.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/internal/semver.js b/node_modules/@opentelemetry/api/build/esm/internal/semver.js new file mode 100644 index 0000000..2a788a0 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/internal/semver.js @@ -0,0 +1,118 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { VERSION } from '../version'; +var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; +/** + * Create a function to test an API version to see if it is compatible with the provided ownVersion. + * + * The returned function has the following semantics: + * - Exact match is always compatible + * - Major versions must match exactly + * - 1.x package cannot use global 2.x package + * - 2.x package cannot use global 1.x package + * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API + * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects + * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 + * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor + * - Patch and build tag differences are not considered at this time + * + * @param ownVersion version which should be checked against + */ +export function _makeCompatibilityCheck(ownVersion) { + var acceptedVersions = new Set([ownVersion]); + var rejectedVersions = new Set(); + var myVersionMatch = ownVersion.match(re); + if (!myVersionMatch) { + // we cannot guarantee compatibility so we always return noop + return function () { return false; }; + } + var ownVersionParsed = { + major: +myVersionMatch[1], + minor: +myVersionMatch[2], + patch: +myVersionMatch[3], + prerelease: myVersionMatch[4], + }; + // if ownVersion has a prerelease tag, versions must match exactly + if (ownVersionParsed.prerelease != null) { + return function isExactmatch(globalVersion) { + return globalVersion === ownVersion; + }; + } + function _reject(v) { + rejectedVersions.add(v); + return false; + } + function _accept(v) { + acceptedVersions.add(v); + return true; + } + return function isCompatible(globalVersion) { + if (acceptedVersions.has(globalVersion)) { + return true; + } + if (rejectedVersions.has(globalVersion)) { + return false; + } + var globalVersionMatch = globalVersion.match(re); + if (!globalVersionMatch) { + // cannot parse other version + // we cannot guarantee compatibility so we always noop + return _reject(globalVersion); + } + var globalVersionParsed = { + major: +globalVersionMatch[1], + minor: +globalVersionMatch[2], + patch: +globalVersionMatch[3], + prerelease: globalVersionMatch[4], + }; + // if globalVersion has a prerelease tag, versions must match exactly + if (globalVersionParsed.prerelease != null) { + return _reject(globalVersion); + } + // major versions must match + if (ownVersionParsed.major !== globalVersionParsed.major) { + return _reject(globalVersion); + } + if (ownVersionParsed.major === 0) { + if (ownVersionParsed.minor === globalVersionParsed.minor && + ownVersionParsed.patch <= globalVersionParsed.patch) { + return _accept(globalVersion); + } + return _reject(globalVersion); + } + if (ownVersionParsed.minor <= globalVersionParsed.minor) { + return _accept(globalVersion); + } + return _reject(globalVersion); + }; +} +/** + * Test an API version to see if it is compatible with this API. + * + * - Exact match is always compatible + * - Major versions must match exactly + * - 1.x package cannot use global 2.x package + * - 2.x package cannot use global 1.x package + * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API + * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects + * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 + * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor + * - Patch and build tag differences are not considered at this time + * + * @param version version of the API requesting an instance of the global API + */ +export var isCompatible = _makeCompatibilityCheck(VERSION); +//# sourceMappingURL=semver.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/internal/semver.js.map b/node_modules/@opentelemetry/api/build/esm/internal/semver.js.map new file mode 100644 index 0000000..75579a4 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/internal/semver.js.map @@ -0,0 +1 @@ +{"version":3,"file":"semver.js","sourceRoot":"","sources":["../../../src/internal/semver.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,IAAM,EAAE,GAAG,+BAA+B,CAAC;AAE3C;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,uBAAuB,CACrC,UAAkB;IAElB,IAAM,gBAAgB,GAAG,IAAI,GAAG,CAAS,CAAC,UAAU,CAAC,CAAC,CAAC;IACvD,IAAM,gBAAgB,GAAG,IAAI,GAAG,EAAU,CAAC;IAE3C,IAAM,cAAc,GAAG,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAC5C,IAAI,CAAC,cAAc,EAAE;QACnB,6DAA6D;QAC7D,OAAO,cAAM,OAAA,KAAK,EAAL,CAAK,CAAC;KACpB;IAED,IAAM,gBAAgB,GAAG;QACvB,KAAK,EAAE,CAAC,cAAc,CAAC,CAAC,CAAC;QACzB,KAAK,EAAE,CAAC,cAAc,CAAC,CAAC,CAAC;QACzB,KAAK,EAAE,CAAC,cAAc,CAAC,CAAC,CAAC;QACzB,UAAU,EAAE,cAAc,CAAC,CAAC,CAAC;KAC9B,CAAC;IAEF,kEAAkE;IAClE,IAAI,gBAAgB,CAAC,UAAU,IAAI,IAAI,EAAE;QACvC,OAAO,SAAS,YAAY,CAAC,aAAqB;YAChD,OAAO,aAAa,KAAK,UAAU,CAAC;QACtC,CAAC,CAAC;KACH;IAED,SAAS,OAAO,CAAC,CAAS;QACxB,gBAAgB,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QACxB,OAAO,KAAK,CAAC;IACf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a,CAAC,CAAC;SAC/B;QAED,IAAI,gBAAgB,CAAC,KAAK,IAAI,mBAAmB,CAAC,KAAK,EAAE;YACvD,OAAO,OAAO,CAAC,aAAa,CAAC,CAAC;SAC/B;QAED,OAAO,OAAO,CAAC,aAAa,CAAC,CAAC;IAChC,CAAC,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,IAAM,YAAY,GAAG,uBAAuB,CAAC,OAAO,CAAC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { VERSION } from '../version';\n\nconst re = /^(\\d+)\\.(\\d+)\\.(\\d+)(-(.+))?$/;\n\n/**\n * Create a function to test an API version to see if it is compatible with the provided ownVersion.\n *\n * The returned function has the following semantics:\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param ownVersion version which should be checked against\n */\nexport function _makeCompatibilityCheck(\n ownVersion: string\n): (globalVersion: string) => boolean {\n const acceptedVersions = new Set([ownVersion]);\n const rejectedVersions = new Set();\n\n const myVersionMatch = ownVersion.match(re);\n if (!myVersionMatch) {\n // we cannot guarantee compatibility so we always return noop\n return () => false;\n }\n\n const ownVersionParsed = {\n major: +myVersionMatch[1],\n minor: +myVersionMatch[2],\n patch: +myVersionMatch[3],\n prerelease: myVersionMatch[4],\n };\n\n // if ownVersion has a prerelease tag, versions must match exactly\n if (ownVersionParsed.prerelease != null) {\n return function isExactmatch(globalVersion: string): boolean {\n return globalVersion === ownVersion;\n };\n }\n\n function _reject(v: string) {\n rejectedVersions.add(v);\n return false;\n }\n\n function _accept(v: string) {\n acceptedVersions.add(v);\n return true;\n }\n\n return function isCompatible(globalVersion: string): boolean {\n if (acceptedVersions.has(globalVersion)) {\n return true;\n }\n\n if (rejectedVersions.has(globalVersion)) {\n return false;\n }\n\n const globalVersionMatch = globalVersion.match(re);\n if (!globalVersionMatch) {\n // cannot parse other version\n // we cannot guarantee compatibility so we always noop\n return _reject(globalVersion);\n }\n\n const globalVersionParsed = {\n major: +globalVersionMatch[1],\n minor: +globalVersionMatch[2],\n patch: +globalVersionMatch[3],\n prerelease: globalVersionMatch[4],\n };\n\n // if globalVersion has a prerelease tag, versions must match exactly\n if (globalVersionParsed.prerelease != null) {\n return _reject(globalVersion);\n }\n\n // major versions must match\n if (ownVersionParsed.major !== globalVersionParsed.major) {\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.major === 0) {\n if (\n ownVersionParsed.minor === globalVersionParsed.minor &&\n ownVersionParsed.patch <= globalVersionParsed.patch\n ) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.minor <= globalVersionParsed.minor) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n };\n}\n\n/**\n * Test an API version to see if it is compatible with this API.\n *\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param version version of the API requesting an instance of the global API\n */\nexport const isCompatible = _makeCompatibilityCheck(VERSION);\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics-api.d.ts b/node_modules/@opentelemetry/api/build/esm/metrics-api.d.ts new file mode 100644 index 0000000..26d539c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics-api.d.ts @@ -0,0 +1,4 @@ +import { MetricsAPI } from './api/metrics'; +/** Entrypoint for metrics API */ +export declare const metrics: MetricsAPI; +//# sourceMappingURL=metrics-api.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics-api.js b/node_modules/@opentelemetry/api/build/esm/metrics-api.js new file mode 100644 index 0000000..145087f --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics-api.js @@ -0,0 +1,21 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +import { MetricsAPI } from './api/metrics'; +/** Entrypoint for metrics API */ +export var metrics = MetricsAPI.getInstance(); +//# sourceMappingURL=metrics-api.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics-api.js.map b/node_modules/@opentelemetry/api/build/esm/metrics-api.js.map new file mode 100644 index 0000000..69dd3e2 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics-api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metrics-api.js","sourceRoot":"","sources":["../../src/metrics-api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,sEAAsE;AACtE,qCAAqC;AACrC,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,iCAAiC;AACjC,MAAM,CAAC,IAAM,OAAO,GAAG,UAAU,CAAC,WAAW,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { MetricsAPI } from './api/metrics';\n/** Entrypoint for metrics API */\nexport const metrics = MetricsAPI.getInstance();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics/Meter.d.ts b/node_modules/@opentelemetry/api/build/esm/metrics/Meter.d.ts new file mode 100644 index 0000000..5e3926b --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics/Meter.d.ts @@ -0,0 +1,110 @@ +import { BatchObservableCallback, Counter, Gauge, Histogram, MetricAttributes, MetricOptions, Observable, ObservableCounter, ObservableGauge, ObservableUpDownCounter, UpDownCounter } from './Metric'; +/** + * An interface describes additional metadata of a meter. + */ +export interface MeterOptions { + /** + * The schemaUrl of the meter or instrumentation library + */ + schemaUrl?: string; +} +/** + * An interface to allow the recording metrics. + * + * {@link Metric}s are used for recording pre-defined aggregation (`Counter`), + * or raw values (`Histogram`) in which the aggregation and attributes + * for the exported metric are deferred. + */ +export interface Meter { + /** + * Creates and returns a new `Gauge`. + * @param name the name of the metric. + * @param [options] the metric options. + */ + createGauge(name: string, options?: MetricOptions): Gauge; + /** + * Creates and returns a new `Histogram`. + * @param name the name of the metric. + * @param [options] the metric options. + */ + createHistogram(name: string, options?: MetricOptions): Histogram; + /** + * Creates a new `Counter` metric. Generally, this kind of metric when the + * value is a quantity, the sum is of primary interest, and the event count + * and value distribution are not of primary interest. + * @param name the name of the metric. + * @param [options] the metric options. + */ + createCounter(name: string, options?: MetricOptions): Counter; + /** + * Creates a new `UpDownCounter` metric. UpDownCounter is a synchronous + * instrument and very similar to Counter except that Add(increment) + * supports negative increments. It is generally useful for capturing changes + * in an amount of resources used, or any quantity that rises and falls + * during a request. + * Example uses for UpDownCounter: + *
    + *
  1. count the number of active requests.
  2. + *
  3. count memory in use by instrumenting new and delete.
  4. + *
  5. count queue size by instrumenting enqueue and dequeue.
  6. + *
  7. count semaphore up and down operations.
  8. + *
+ * + * @param name the name of the metric. + * @param [options] the metric options. + */ + createUpDownCounter(name: string, options?: MetricOptions): UpDownCounter; + /** + * Creates a new `ObservableGauge` metric. + * + * The callback SHOULD be safe to be invoked concurrently. + * + * @param name the name of the metric. + * @param [options] the metric options. + */ + createObservableGauge(name: string, options?: MetricOptions): ObservableGauge; + /** + * Creates a new `ObservableCounter` metric. + * + * The callback SHOULD be safe to be invoked concurrently. + * + * @param name the name of the metric. + * @param [options] the metric options. + */ + createObservableCounter(name: string, options?: MetricOptions): ObservableCounter; + /** + * Creates a new `ObservableUpDownCounter` metric. + * + * The callback SHOULD be safe to be invoked concurrently. + * + * @param name the name of the metric. + * @param [options] the metric options. + */ + createObservableUpDownCounter(name: string, options?: MetricOptions): ObservableUpDownCounter; + /** + * Sets up a function that will be called whenever a metric collection is + * initiated. + * + * If the function is already in the list of callbacks for this Observable, + * the function is not added a second time. + * + * Only the associated observables can be observed in the callback. + * Measurements of observables that are not associated observed in the + * callback are dropped. + * + * @param callback the batch observable callback + * @param observables the observables associated with this batch observable callback + */ + addBatchObservableCallback(callback: BatchObservableCallback, observables: Observable[]): void; + /** + * Removes a callback previously registered with {@link Meter.addBatchObservableCallback}. + * + * The callback to be removed is identified using a combination of the callback itself, + * and the set of the observables associated with it. + * + * @param callback the batch observable callback + * @param observables the observables associated with this batch observable callback + */ + removeBatchObservableCallback(callback: BatchObservableCallback, observables: Observable[]): void; +} +//# sourceMappingURL=Meter.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics/Meter.js b/node_modules/@opentelemetry/api/build/esm/metrics/Meter.js new file mode 100644 index 0000000..f1d0754 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics/Meter.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=Meter.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics/Meter.js.map b/node_modules/@opentelemetry/api/build/esm/metrics/Meter.js.map new file mode 100644 index 0000000..c4b0aaf --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics/Meter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Meter.js","sourceRoot":"","sources":["../../../src/metrics/Meter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BatchObservableCallback,\n Counter,\n Gauge,\n Histogram,\n MetricAttributes,\n MetricOptions,\n Observable,\n ObservableCounter,\n ObservableGauge,\n ObservableUpDownCounter,\n UpDownCounter,\n} from './Metric';\n\n/**\n * An interface describes additional metadata of a meter.\n */\nexport interface MeterOptions {\n /**\n * The schemaUrl of the meter or instrumentation library\n */\n schemaUrl?: string;\n}\n\n/**\n * An interface to allow the recording metrics.\n *\n * {@link Metric}s are used for recording pre-defined aggregation (`Counter`),\n * or raw values (`Histogram`) in which the aggregation and attributes\n * for the exported metric are deferred.\n */\nexport interface Meter {\n /**\n * Creates and returns a new `Gauge`.\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createGauge(\n name: string,\n options?: MetricOptions\n ): Gauge;\n\n /**\n * Creates and returns a new `Histogram`.\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createHistogram(\n name: string,\n options?: MetricOptions\n ): Histogram;\n\n /**\n * Creates a new `Counter` metric. Generally, this kind of metric when the\n * value is a quantity, the sum is of primary interest, and the event count\n * and value distribution are not of primary interest.\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createCounter(\n name: string,\n options?: MetricOptions\n ): Counter;\n\n /**\n * Creates a new `UpDownCounter` metric. UpDownCounter is a synchronous\n * instrument and very similar to Counter except that Add(increment)\n * supports negative increments. It is generally useful for capturing changes\n * in an amount of resources used, or any quantity that rises and falls\n * during a request.\n * Example uses for UpDownCounter:\n *
    \n *
  1. count the number of active requests.
  2. \n *
  3. count memory in use by instrumenting new and delete.
  4. \n *
  5. count queue size by instrumenting enqueue and dequeue.
  6. \n *
  7. count semaphore up and down operations.
  8. \n *
\n *\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createUpDownCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n >(\n name: string,\n options?: MetricOptions\n ): UpDownCounter;\n\n /**\n * Creates a new `ObservableGauge` metric.\n *\n * The callback SHOULD be safe to be invoked concurrently.\n *\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createObservableGauge<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n >(\n name: string,\n options?: MetricOptions\n ): ObservableGauge;\n\n /**\n * Creates a new `ObservableCounter` metric.\n *\n * The callback SHOULD be safe to be invoked concurrently.\n *\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createObservableCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n >(\n name: string,\n options?: MetricOptions\n ): ObservableCounter;\n\n /**\n * Creates a new `ObservableUpDownCounter` metric.\n *\n * The callback SHOULD be safe to be invoked concurrently.\n *\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createObservableUpDownCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n >(\n name: string,\n options?: MetricOptions\n ): ObservableUpDownCounter;\n\n /**\n * Sets up a function that will be called whenever a metric collection is\n * initiated.\n *\n * If the function is already in the list of callbacks for this Observable,\n * the function is not added a second time.\n *\n * Only the associated observables can be observed in the callback.\n * Measurements of observables that are not associated observed in the\n * callback are dropped.\n *\n * @param callback the batch observable callback\n * @param observables the observables associated with this batch observable callback\n */\n addBatchObservableCallback<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n >(\n callback: BatchObservableCallback,\n observables: Observable[]\n ): void;\n\n /**\n * Removes a callback previously registered with {@link Meter.addBatchObservableCallback}.\n *\n * The callback to be removed is identified using a combination of the callback itself,\n * and the set of the observables associated with it.\n *\n * @param callback the batch observable callback\n * @param observables the observables associated with this batch observable callback\n */\n removeBatchObservableCallback<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n >(\n callback: BatchObservableCallback,\n observables: Observable[]\n ): void;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics/MeterProvider.d.ts b/node_modules/@opentelemetry/api/build/esm/metrics/MeterProvider.d.ts new file mode 100644 index 0000000..6c08cc3 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics/MeterProvider.d.ts @@ -0,0 +1,17 @@ +import { Meter, MeterOptions } from './Meter'; +/** + * A registry for creating named {@link Meter}s. + */ +export interface MeterProvider { + /** + * Returns a Meter, creating one if one with the given name, version, and + * schemaUrl pair is not already created. + * + * @param name The name of the meter or instrumentation library. + * @param version The version of the meter or instrumentation library. + * @param options The options of the meter or instrumentation library. + * @returns Meter A Meter with the given name and version + */ + getMeter(name: string, version?: string, options?: MeterOptions): Meter; +} +//# sourceMappingURL=MeterProvider.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics/MeterProvider.js b/node_modules/@opentelemetry/api/build/esm/metrics/MeterProvider.js new file mode 100644 index 0000000..3051712 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics/MeterProvider.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=MeterProvider.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics/MeterProvider.js.map b/node_modules/@opentelemetry/api/build/esm/metrics/MeterProvider.js.map new file mode 100644 index 0000000..8f96d90 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics/MeterProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MeterProvider.js","sourceRoot":"","sources":["../../../src/metrics/MeterProvider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Meter, MeterOptions } from './Meter';\n\n/**\n * A registry for creating named {@link Meter}s.\n */\nexport interface MeterProvider {\n /**\n * Returns a Meter, creating one if one with the given name, version, and\n * schemaUrl pair is not already created.\n *\n * @param name The name of the meter or instrumentation library.\n * @param version The version of the meter or instrumentation library.\n * @param options The options of the meter or instrumentation library.\n * @returns Meter A Meter with the given name and version\n */\n getMeter(name: string, version?: string, options?: MeterOptions): Meter;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics/Metric.d.ts b/node_modules/@opentelemetry/api/build/esm/metrics/Metric.d.ts new file mode 100644 index 0000000..607b637 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics/Metric.d.ts @@ -0,0 +1,115 @@ +import { Attributes, AttributeValue } from '../common/Attributes'; +import { Context } from '../context/types'; +import { BatchObservableResult, ObservableResult } from './ObservableResult'; +/** + * Advisory options influencing aggregation configuration parameters. + * @experimental + */ +export interface MetricAdvice { + /** + * Hint the explicit bucket boundaries for SDK if the metric is been + * aggregated with a HistogramAggregator. + */ + explicitBucketBoundaries?: number[]; +} +/** + * Options needed for metric creation + */ +export interface MetricOptions { + /** + * The description of the Metric. + * @default '' + */ + description?: string; + /** + * The unit of the Metric values. + * @default '' + */ + unit?: string; + /** + * Indicates the type of the recorded value. + * @default {@link ValueType.DOUBLE} + */ + valueType?: ValueType; + /** + * The advice influencing aggregation configuration parameters. + * @experimental + */ + advice?: MetricAdvice; +} +/** The Type of value. It describes how the data is reported. */ +export declare enum ValueType { + INT = 0, + DOUBLE = 1 +} +/** + * Counter is the most common synchronous instrument. This instrument supports + * an `Add(increment)` function for reporting a sum, and is restricted to + * non-negative increments. The default aggregation is Sum, as for any additive + * instrument. + * + * Example uses for Counter: + *
    + *
  1. count the number of bytes received.
  2. + *
  3. count the number of requests completed.
  4. + *
  5. count the number of accounts created.
  6. + *
  7. count the number of checkpoints run.
  8. + *
  9. count the number of 5xx errors.
  10. + *
      + */ +export interface Counter { + /** + * Increment value of counter by the input. Inputs must not be negative. + */ + add(value: number, attributes?: AttributesTypes, context?: Context): void; +} +export interface UpDownCounter { + /** + * Increment value of counter by the input. Inputs may be negative. + */ + add(value: number, attributes?: AttributesTypes, context?: Context): void; +} +export interface Gauge { + /** + * Records a measurement. + */ + record(value: number, attributes?: AttributesTypes, context?: Context): void; +} +export interface Histogram { + /** + * Records a measurement. Value of the measurement must not be negative. + */ + record(value: number, attributes?: AttributesTypes, context?: Context): void; +} +/** + * @deprecated please use {@link Attributes} + */ +export declare type MetricAttributes = Attributes; +/** + * @deprecated please use {@link AttributeValue} + */ +export declare type MetricAttributeValue = AttributeValue; +/** + * The observable callback for Observable instruments. + */ +export declare type ObservableCallback = (observableResult: ObservableResult) => void | Promise; +/** + * The observable callback for a batch of Observable instruments. + */ +export declare type BatchObservableCallback = (observableResult: BatchObservableResult) => void | Promise; +export interface Observable { + /** + * Sets up a function that will be called whenever a metric collection is initiated. + * + * If the function is already in the list of callbacks for this Observable, the function is not added a second time. + */ + addCallback(callback: ObservableCallback): void; + /** + * Removes a callback previously registered with {@link Observable.addCallback}. + */ + removeCallback(callback: ObservableCallback): void; +} +export declare type ObservableCounter = Observable; +export declare type ObservableUpDownCounter = Observable; +export declare type ObservableGauge = Observable; +//# sourceMappingURL=Metric.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics/Metric.js b/node_modules/@opentelemetry/api/build/esm/metrics/Metric.js new file mode 100644 index 0000000..6df1374 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics/Metric.js @@ -0,0 +1,22 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Type of value. It describes how the data is reported. */ +export var ValueType; +(function (ValueType) { + ValueType[ValueType["INT"] = 0] = "INT"; + ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE"; +})(ValueType || (ValueType = {})); +//# sourceMappingURL=Metric.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics/Metric.js.map b/node_modules/@opentelemetry/api/build/esm/metrics/Metric.js.map new file mode 100644 index 0000000..a115430 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics/Metric.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Metric.js","sourceRoot":"","sources":["../../../src/metrics/Metric.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AA+CH,gEAAgE;AAChE,MAAM,CAAN,IAAY,SAGX;AAHD,WAAY,SAAS;IACnB,uCAAG,CAAA;IACH,6CAAM,CAAA;AACR,CAAC,EAHW,SAAS,KAAT,SAAS,QAGpB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Attributes, AttributeValue } from '../common/Attributes';\nimport { Context } from '../context/types';\nimport { BatchObservableResult, ObservableResult } from './ObservableResult';\n\n/**\n * Advisory options influencing aggregation configuration parameters.\n * @experimental\n */\nexport interface MetricAdvice {\n /**\n * Hint the explicit bucket boundaries for SDK if the metric is been\n * aggregated with a HistogramAggregator.\n */\n explicitBucketBoundaries?: number[];\n}\n\n/**\n * Options needed for metric creation\n */\nexport interface MetricOptions {\n /**\n * The description of the Metric.\n * @default ''\n */\n description?: string;\n\n /**\n * The unit of the Metric values.\n * @default ''\n */\n unit?: string;\n\n /**\n * Indicates the type of the recorded value.\n * @default {@link ValueType.DOUBLE}\n */\n valueType?: ValueType;\n\n /**\n * The advice influencing aggregation configuration parameters.\n * @experimental\n */\n advice?: MetricAdvice;\n}\n\n/** The Type of value. It describes how the data is reported. */\nexport enum ValueType {\n INT,\n DOUBLE,\n}\n\n/**\n * Counter is the most common synchronous instrument. This instrument supports\n * an `Add(increment)` function for reporting a sum, and is restricted to\n * non-negative increments. The default aggregation is Sum, as for any additive\n * instrument.\n *\n * Example uses for Counter:\n *
        \n *
      1. count the number of bytes received.
      2. \n *
      3. count the number of requests completed.
      4. \n *
      5. count the number of accounts created.
      6. \n *
      7. count the number of checkpoints run.
      8. \n *
      9. count the number of 5xx errors.
      10. \n *
          \n */\nexport interface Counter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Increment value of counter by the input. Inputs must not be negative.\n */\n add(value: number, attributes?: AttributesTypes, context?: Context): void;\n}\n\nexport interface UpDownCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Increment value of counter by the input. Inputs may be negative.\n */\n add(value: number, attributes?: AttributesTypes, context?: Context): void;\n}\n\nexport interface Gauge<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Records a measurement.\n */\n record(value: number, attributes?: AttributesTypes, context?: Context): void;\n}\n\nexport interface Histogram<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Records a measurement. Value of the measurement must not be negative.\n */\n record(value: number, attributes?: AttributesTypes, context?: Context): void;\n}\n\n/**\n * @deprecated please use {@link Attributes}\n */\nexport type MetricAttributes = Attributes;\n\n/**\n * @deprecated please use {@link AttributeValue}\n */\nexport type MetricAttributeValue = AttributeValue;\n\n/**\n * The observable callback for Observable instruments.\n */\nexport type ObservableCallback<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> = (\n observableResult: ObservableResult\n) => void | Promise;\n\n/**\n * The observable callback for a batch of Observable instruments.\n */\nexport type BatchObservableCallback<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> = (\n observableResult: BatchObservableResult\n) => void | Promise;\n\nexport interface Observable<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Sets up a function that will be called whenever a metric collection is initiated.\n *\n * If the function is already in the list of callbacks for this Observable, the function is not added a second time.\n */\n addCallback(callback: ObservableCallback): void;\n\n /**\n * Removes a callback previously registered with {@link Observable.addCallback}.\n */\n removeCallback(callback: ObservableCallback): void;\n}\n\nexport type ObservableCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> = Observable;\nexport type ObservableUpDownCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> = Observable;\nexport type ObservableGauge<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> = Observable;\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.d.ts b/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.d.ts new file mode 100644 index 0000000..bbefa9a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.d.ts @@ -0,0 +1,82 @@ +import { Meter } from './Meter'; +import { BatchObservableCallback, Counter, Gauge, Histogram, MetricAttributes, MetricOptions, Observable, ObservableCallback, ObservableCounter, ObservableGauge, ObservableUpDownCounter, UpDownCounter } from './Metric'; +/** + * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses + * constant NoopMetrics for all of its methods. + */ +export declare class NoopMeter implements Meter { + constructor(); + /** + * @see {@link Meter.createGauge} + */ + createGauge(_name: string, _options?: MetricOptions): Gauge; + /** + * @see {@link Meter.createHistogram} + */ + createHistogram(_name: string, _options?: MetricOptions): Histogram; + /** + * @see {@link Meter.createCounter} + */ + createCounter(_name: string, _options?: MetricOptions): Counter; + /** + * @see {@link Meter.createUpDownCounter} + */ + createUpDownCounter(_name: string, _options?: MetricOptions): UpDownCounter; + /** + * @see {@link Meter.createObservableGauge} + */ + createObservableGauge(_name: string, _options?: MetricOptions): ObservableGauge; + /** + * @see {@link Meter.createObservableCounter} + */ + createObservableCounter(_name: string, _options?: MetricOptions): ObservableCounter; + /** + * @see {@link Meter.createObservableUpDownCounter} + */ + createObservableUpDownCounter(_name: string, _options?: MetricOptions): ObservableUpDownCounter; + /** + * @see {@link Meter.addBatchObservableCallback} + */ + addBatchObservableCallback(_callback: BatchObservableCallback, _observables: Observable[]): void; + /** + * @see {@link Meter.removeBatchObservableCallback} + */ + removeBatchObservableCallback(_callback: BatchObservableCallback): void; +} +export declare class NoopMetric { +} +export declare class NoopCounterMetric extends NoopMetric implements Counter { + add(_value: number, _attributes: MetricAttributes): void; +} +export declare class NoopUpDownCounterMetric extends NoopMetric implements UpDownCounter { + add(_value: number, _attributes: MetricAttributes): void; +} +export declare class NoopGaugeMetric extends NoopMetric implements Gauge { + record(_value: number, _attributes: MetricAttributes): void; +} +export declare class NoopHistogramMetric extends NoopMetric implements Histogram { + record(_value: number, _attributes: MetricAttributes): void; +} +export declare class NoopObservableMetric { + addCallback(_callback: ObservableCallback): void; + removeCallback(_callback: ObservableCallback): void; +} +export declare class NoopObservableCounterMetric extends NoopObservableMetric implements ObservableCounter { +} +export declare class NoopObservableGaugeMetric extends NoopObservableMetric implements ObservableGauge { +} +export declare class NoopObservableUpDownCounterMetric extends NoopObservableMetric implements ObservableUpDownCounter { +} +export declare const NOOP_METER: NoopMeter; +export declare const NOOP_COUNTER_METRIC: NoopCounterMetric; +export declare const NOOP_GAUGE_METRIC: NoopGaugeMetric; +export declare const NOOP_HISTOGRAM_METRIC: NoopHistogramMetric; +export declare const NOOP_UP_DOWN_COUNTER_METRIC: NoopUpDownCounterMetric; +export declare const NOOP_OBSERVABLE_COUNTER_METRIC: NoopObservableCounterMetric; +export declare const NOOP_OBSERVABLE_GAUGE_METRIC: NoopObservableGaugeMetric; +export declare const NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC: NoopObservableUpDownCounterMetric; +/** + * Create a no-op Meter + */ +export declare function createNoopMeter(): Meter; +//# sourceMappingURL=NoopMeter.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js b/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js new file mode 100644 index 0000000..8d03e40 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js @@ -0,0 +1,181 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +/** + * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses + * constant NoopMetrics for all of its methods. + */ +var NoopMeter = /** @class */ (function () { + function NoopMeter() { + } + /** + * @see {@link Meter.createGauge} + */ + NoopMeter.prototype.createGauge = function (_name, _options) { + return NOOP_GAUGE_METRIC; + }; + /** + * @see {@link Meter.createHistogram} + */ + NoopMeter.prototype.createHistogram = function (_name, _options) { + return NOOP_HISTOGRAM_METRIC; + }; + /** + * @see {@link Meter.createCounter} + */ + NoopMeter.prototype.createCounter = function (_name, _options) { + return NOOP_COUNTER_METRIC; + }; + /** + * @see {@link Meter.createUpDownCounter} + */ + NoopMeter.prototype.createUpDownCounter = function (_name, _options) { + return NOOP_UP_DOWN_COUNTER_METRIC; + }; + /** + * @see {@link Meter.createObservableGauge} + */ + NoopMeter.prototype.createObservableGauge = function (_name, _options) { + return NOOP_OBSERVABLE_GAUGE_METRIC; + }; + /** + * @see {@link Meter.createObservableCounter} + */ + NoopMeter.prototype.createObservableCounter = function (_name, _options) { + return NOOP_OBSERVABLE_COUNTER_METRIC; + }; + /** + * @see {@link Meter.createObservableUpDownCounter} + */ + NoopMeter.prototype.createObservableUpDownCounter = function (_name, _options) { + return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; + }; + /** + * @see {@link Meter.addBatchObservableCallback} + */ + NoopMeter.prototype.addBatchObservableCallback = function (_callback, _observables) { }; + /** + * @see {@link Meter.removeBatchObservableCallback} + */ + NoopMeter.prototype.removeBatchObservableCallback = function (_callback) { }; + return NoopMeter; +}()); +export { NoopMeter }; +var NoopMetric = /** @class */ (function () { + function NoopMetric() { + } + return NoopMetric; +}()); +export { NoopMetric }; +var NoopCounterMetric = /** @class */ (function (_super) { + __extends(NoopCounterMetric, _super); + function NoopCounterMetric() { + return _super !== null && _super.apply(this, arguments) || this; + } + NoopCounterMetric.prototype.add = function (_value, _attributes) { }; + return NoopCounterMetric; +}(NoopMetric)); +export { NoopCounterMetric }; +var NoopUpDownCounterMetric = /** @class */ (function (_super) { + __extends(NoopUpDownCounterMetric, _super); + function NoopUpDownCounterMetric() { + return _super !== null && _super.apply(this, arguments) || this; + } + NoopUpDownCounterMetric.prototype.add = function (_value, _attributes) { }; + return NoopUpDownCounterMetric; +}(NoopMetric)); +export { NoopUpDownCounterMetric }; +var NoopGaugeMetric = /** @class */ (function (_super) { + __extends(NoopGaugeMetric, _super); + function NoopGaugeMetric() { + return _super !== null && _super.apply(this, arguments) || this; + } + NoopGaugeMetric.prototype.record = function (_value, _attributes) { }; + return NoopGaugeMetric; +}(NoopMetric)); +export { NoopGaugeMetric }; +var NoopHistogramMetric = /** @class */ (function (_super) { + __extends(NoopHistogramMetric, _super); + function NoopHistogramMetric() { + return _super !== null && _super.apply(this, arguments) || this; + } + NoopHistogramMetric.prototype.record = function (_value, _attributes) { }; + return NoopHistogramMetric; +}(NoopMetric)); +export { NoopHistogramMetric }; +var NoopObservableMetric = /** @class */ (function () { + function NoopObservableMetric() { + } + NoopObservableMetric.prototype.addCallback = function (_callback) { }; + NoopObservableMetric.prototype.removeCallback = function (_callback) { }; + return NoopObservableMetric; +}()); +export { NoopObservableMetric }; +var NoopObservableCounterMetric = /** @class */ (function (_super) { + __extends(NoopObservableCounterMetric, _super); + function NoopObservableCounterMetric() { + return _super !== null && _super.apply(this, arguments) || this; + } + return NoopObservableCounterMetric; +}(NoopObservableMetric)); +export { NoopObservableCounterMetric }; +var NoopObservableGaugeMetric = /** @class */ (function (_super) { + __extends(NoopObservableGaugeMetric, _super); + function NoopObservableGaugeMetric() { + return _super !== null && _super.apply(this, arguments) || this; + } + return NoopObservableGaugeMetric; +}(NoopObservableMetric)); +export { NoopObservableGaugeMetric }; +var NoopObservableUpDownCounterMetric = /** @class */ (function (_super) { + __extends(NoopObservableUpDownCounterMetric, _super); + function NoopObservableUpDownCounterMetric() { + return _super !== null && _super.apply(this, arguments) || this; + } + return NoopObservableUpDownCounterMetric; +}(NoopObservableMetric)); +export { NoopObservableUpDownCounterMetric }; +export var NOOP_METER = new NoopMeter(); +// Synchronous instruments +export var NOOP_COUNTER_METRIC = new NoopCounterMetric(); +export var NOOP_GAUGE_METRIC = new NoopGaugeMetric(); +export var NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric(); +export var NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric(); +// Asynchronous instruments +export var NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric(); +export var NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric(); +export var NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric(); +/** + * Create a no-op Meter + */ +export function createNoopMeter() { + return NOOP_METER; +} +//# sourceMappingURL=NoopMeter.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js.map b/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js.map new file mode 100644 index 0000000..e1dc0e0 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NoopMeter.js","sourceRoot":"","sources":["../../../src/metrics/NoopMeter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;AAkBH;;;GAGG;AACH;IACE;IAAe,CAAC;IAEhB;;OAEG;IACH,+BAAW,GAAX,UAAY,KAAa,EAAE,QAAwB;QACjD,OAAO,iBAAiB,CAAC;IAC3B,CAAC;IAED;;OAEG;IACH,mCAAe,GAAf,UAAgB,KAAa,EAAE,QAAwB;QACrD,OAAO,qBAAqB,CAAC;IAC/B,CAAC;IAED;;OAEG;IACH,iCAAa,GAAb,UAAc,KAAa,EAAE,QAAwB;QACnD,OAAO,mBAAmB,CAAC;IAC7B,CAAC;IAED;;OAEG;IACH,uCAAmB,GAAnB,UAAoB,KAAa,EAAE,QAAwB;QACzD,OAAO,2BAA2B,CAAC;IACrC,CAAC;IAED;;OAEG;IACH,yCAAqB,GAArB,UACE,KAAa,EACb,QAAwB;QAExB,OAAO,4BAA4B,CAAC;IACtC,CAAC;IAED;;OAEG;IACH,2CAAuB,GAAvB,UACE,KAAa,EACb,QAAwB;QAExB,OAAO,8BAA8B,CAAC;IACxC,CAAC;IAED;;OAEG;IACH,iDAA6B,GAA7B,UACE,KAAa,EACb,QAAwB;QAExB,OAAO,sCAAsC,CAAC;IAChD,CAAC;IAED;;OAEG;IACH,8CAA0B,GAA1B,UACE,SAAkC,EA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UAAU,GAAG,IAAI,SAAS,EAAE,CAAC;AAE1C,0BAA0B;AAC1B,MAAM,CAAC,IAAM,mBAAmB,GAAG,IAAI,iBAAiB,EAAE,CAAC;AAC3D,MAAM,CAAC,IAAM,iBAAiB,GAAG,IAAI,eAAe,EAAE,CAAC;AACvD,MAAM,CAAC,IAAM,qBAAqB,GAAG,IAAI,mBAAmB,EAAE,CAAC;AAC/D,MAAM,CAAC,IAAM,2BAA2B,GAAG,IAAI,uBAAuB,EAAE,CAAC;AAEzE,2BAA2B;AAC3B,MAAM,CAAC,IAAM,8BAA8B,GAAG,IAAI,2BAA2B,EAAE,CAAC;AAChF,MAAM,CAAC,IAAM,4BAA4B,GAAG,IAAI,yBAAyB,EAAE,CAAC;AAC5E,MAAM,CAAC,IAAM,sCAAsC,GACjD,IAAI,iCAAiC,EAAE,CAAC;AAE1C;;GAEG;AACH,MAAM,UAAU,eAAe;IAC7B,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Meter } from './Meter';\nimport {\n BatchObservableCallback,\n Counter,\n Gauge,\n Histogram,\n MetricAttributes,\n MetricOptions,\n Observable,\n ObservableCallback,\n ObservableCounter,\n ObservableGauge,\n ObservableUpDownCounter,\n UpDownCounter,\n} from './Metric';\n\n/**\n * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses\n * constant NoopMetrics for all of its methods.\n */\nexport class NoopMeter implements Meter {\n constructor() {}\n\n /**\n * @see {@link Meter.createGauge}\n */\n createGauge(_name: string, _options?: MetricOptions): Gauge {\n return NOOP_GAUGE_METRIC;\n }\n\n /**\n * @see {@link Meter.createHistogram}\n */\n createHistogram(_name: string, _options?: MetricOptions): Histogram {\n return NOOP_HISTOGRAM_METRIC;\n }\n\n /**\n * @see {@link Meter.createCounter}\n */\n createCounter(_name: string, _options?: MetricOptions): Counter {\n return NOOP_COUNTER_METRIC;\n }\n\n /**\n * @see {@link Meter.createUpDownCounter}\n */\n createUpDownCounter(_name: string, _options?: MetricOptions): UpDownCounter {\n return NOOP_UP_DOWN_COUNTER_METRIC;\n }\n\n /**\n * @see {@link Meter.createObservableGauge}\n */\n createObservableGauge(\n _name: string,\n _options?: MetricOptions\n ): ObservableGauge {\n return NOOP_OBSERVABLE_GAUGE_METRIC;\n }\n\n /**\n * @see {@link Meter.createObservableCounter}\n */\n createObservableCounter(\n _name: string,\n _options?: MetricOptions\n ): ObservableCounter {\n return NOOP_OBSERVABLE_COUNTER_METRIC;\n }\n\n /**\n * @see {@link Meter.createObservableUpDownCounter}\n */\n createObservableUpDownCounter(\n _name: string,\n _options?: MetricOptions\n ): ObservableUpDownCounter {\n return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;\n }\n\n /**\n * @see {@link Meter.addBatchObservableCallback}\n */\n addBatchObservableCallback(\n _callback: BatchObservableCallback,\n _observables: Observable[]\n ): void {}\n\n /**\n * @see {@link Meter.removeBatchObservableCallback}\n */\n removeBatchObservableCallback(_callback: BatchObservableCallback): void {}\n}\n\nexport class NoopMetric {}\n\nexport class NoopCounterMetric extends NoopMetric implements Counter {\n add(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopUpDownCounterMetric\n extends NoopMetric\n implements UpDownCounter\n{\n add(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopGaugeMetric extends NoopMetric implements Gauge {\n record(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopHistogramMetric extends NoopMetric implements Histogram {\n record(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopObservableMetric {\n addCallback(_callback: ObservableCallback) {}\n\n removeCallback(_callback: ObservableCallback) {}\n}\n\nexport class NoopObservableCounterMetric\n extends NoopObservableMetric\n implements ObservableCounter {}\n\nexport class NoopObservableGaugeMetric\n extends NoopObservableMetric\n implements ObservableGauge {}\n\nexport class NoopObservableUpDownCounterMetric\n extends NoopObservableMetric\n implements ObservableUpDownCounter {}\n\nexport const NOOP_METER = new NoopMeter();\n\n// Synchronous instruments\nexport const NOOP_COUNTER_METRIC = new NoopCounterMetric();\nexport const NOOP_GAUGE_METRIC = new NoopGaugeMetric();\nexport const NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric();\nexport const NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric();\n\n// Asynchronous instruments\nexport const NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric();\nexport const NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric();\nexport const NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC =\n new NoopObservableUpDownCounterMetric();\n\n/**\n * Create a no-op Meter\n */\nexport function createNoopMeter(): Meter {\n return NOOP_METER;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.d.ts b/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.d.ts new file mode 100644 index 0000000..8b51bc5 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.d.ts @@ -0,0 +1,11 @@ +import { Meter, MeterOptions } from './Meter'; +import { MeterProvider } from './MeterProvider'; +/** + * An implementation of the {@link MeterProvider} which returns an impotent Meter + * for all calls to `getMeter` + */ +export declare class NoopMeterProvider implements MeterProvider { + getMeter(_name: string, _version?: string, _options?: MeterOptions): Meter; +} +export declare const NOOP_METER_PROVIDER: NoopMeterProvider; +//# sourceMappingURL=NoopMeterProvider.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.js b/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.js new file mode 100644 index 0000000..75de3c0 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.js @@ -0,0 +1,31 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NOOP_METER } from './NoopMeter'; +/** + * An implementation of the {@link MeterProvider} which returns an impotent Meter + * for all calls to `getMeter` + */ +var NoopMeterProvider = /** @class */ (function () { + function NoopMeterProvider() { + } + NoopMeterProvider.prototype.getMeter = function (_name, _version, _options) { + return NOOP_METER; + }; + return NoopMeterProvider; +}()); +export { NoopMeterProvider }; +export var NOOP_METER_PROVIDER = new NoopMeterProvider(); +//# sourceMappingURL=NoopMeterProvider.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.js.map b/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.js.map new file mode 100644 index 0000000..28b3120 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NoopMeterProvider.js","sourceRoot":"","sources":["../../../src/metrics/NoopMeterProvider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC;;;GAGG;AACH;IAAA;IAIA,CAAC;IAHC,oCAAQ,GAAR,UAAS,KAAa,EAAE,QAAiB,EAAE,QAAuB;QAChE,OAAO,UAAU,CAAC;IACpB,CAAC;IACH,wBAAC;AAAD,CAAC,AAJD,IAIC;;AAED,MAAM,CAAC,IAAM,mBAAmB,GAAG,IAAI,iBAAiB,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Meter, MeterOptions } from './Meter';\nimport { MeterProvider } from './MeterProvider';\nimport { NOOP_METER } from './NoopMeter';\n\n/**\n * An implementation of the {@link MeterProvider} which returns an impotent Meter\n * for all calls to `getMeter`\n */\nexport class NoopMeterProvider implements MeterProvider {\n getMeter(_name: string, _version?: string, _options?: MeterOptions): Meter {\n return NOOP_METER;\n }\n}\n\nexport const NOOP_METER_PROVIDER = new NoopMeterProvider();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics/ObservableResult.d.ts b/node_modules/@opentelemetry/api/build/esm/metrics/ObservableResult.d.ts new file mode 100644 index 0000000..26563f9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics/ObservableResult.d.ts @@ -0,0 +1,31 @@ +import { MetricAttributes, Observable } from './Metric'; +/** + * Interface that is being used in callback function for Observable Metric. + */ +export interface ObservableResult { + /** + * Observe a measurement of the value associated with the given attributes. + * + * @param value The value to be observed. + * @param attributes The attributes associated with the value. If more than + * one values associated with the same attributes values, SDK may pick the + * last one or simply drop the entire observable result. + */ + observe(this: ObservableResult, value: number, attributes?: AttributesTypes): void; +} +/** + * Interface that is being used in batch observable callback function. + */ +export interface BatchObservableResult { + /** + * Observe a measurement of the value associated with the given attributes. + * + * @param metric The observable metric to be observed. + * @param value The value to be observed. + * @param attributes The attributes associated with the value. If more than + * one values associated with the same attributes values, SDK may pick the + * last one or simply drop the entire observable result. + */ + observe(this: BatchObservableResult, metric: Observable, value: number, attributes?: AttributesTypes): void; +} +//# sourceMappingURL=ObservableResult.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics/ObservableResult.js b/node_modules/@opentelemetry/api/build/esm/metrics/ObservableResult.js new file mode 100644 index 0000000..7985d26 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics/ObservableResult.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=ObservableResult.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/metrics/ObservableResult.js.map b/node_modules/@opentelemetry/api/build/esm/metrics/ObservableResult.js.map new file mode 100644 index 0000000..b6b0c7c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/metrics/ObservableResult.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ObservableResult.js","sourceRoot":"","sources":["../../../src/metrics/ObservableResult.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MetricAttributes, Observable } from './Metric';\n\n/**\n * Interface that is being used in callback function for Observable Metric.\n */\nexport interface ObservableResult<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Observe a measurement of the value associated with the given attributes.\n *\n * @param value The value to be observed.\n * @param attributes The attributes associated with the value. If more than\n * one values associated with the same attributes values, SDK may pick the\n * last one or simply drop the entire observable result.\n */\n observe(\n this: ObservableResult,\n value: number,\n attributes?: AttributesTypes\n ): void;\n}\n\n/**\n * Interface that is being used in batch observable callback function.\n */\nexport interface BatchObservableResult<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Observe a measurement of the value associated with the given attributes.\n *\n * @param metric The observable metric to be observed.\n * @param value The value to be observed.\n * @param attributes The attributes associated with the value. If more than\n * one values associated with the same attributes values, SDK may pick the\n * last one or simply drop the entire observable result.\n */\n observe(\n this: BatchObservableResult,\n metric: Observable,\n value: number,\n attributes?: AttributesTypes\n ): void;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/platform/browser/globalThis.d.ts b/node_modules/@opentelemetry/api/build/esm/platform/browser/globalThis.d.ts new file mode 100644 index 0000000..e73fd73 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/platform/browser/globalThis.d.ts @@ -0,0 +1,10 @@ +/** + * - globalThis (New standard) + * - self (Will return the current window instance for supported browsers) + * - window (fallback for older browser implementations) + * - global (NodeJS implementation) + * - (When all else fails) + */ +/** only globals that common to node and browsers are allowed */ +export declare const _globalThis: typeof globalThis; +//# sourceMappingURL=globalThis.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/platform/browser/globalThis.js b/node_modules/@opentelemetry/api/build/esm/platform/browser/globalThis.js new file mode 100644 index 0000000..52f985e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/platform/browser/globalThis.js @@ -0,0 +1,35 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Updates to this file should also be replicated to @opentelemetry/core too. +/** + * - globalThis (New standard) + * - self (Will return the current window instance for supported browsers) + * - window (fallback for older browser implementations) + * - global (NodeJS implementation) + * - (When all else fails) + */ +/** only globals that common to node and browsers are allowed */ +// eslint-disable-next-line node/no-unsupported-features/es-builtins, no-undef +export var _globalThis = typeof globalThis === 'object' + ? globalThis + : typeof self === 'object' + ? self + : typeof window === 'object' + ? window + : typeof global === 'object' + ? global + : {}; +//# sourceMappingURL=globalThis.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/platform/browser/globalThis.js.map b/node_modules/@opentelemetry/api/build/esm/platform/browser/globalThis.js.map new file mode 100644 index 0000000..665e3fc --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/platform/browser/globalThis.js.map @@ -0,0 +1 @@ +{"version":3,"file":"globalThis.js","sourceRoot":"","sources":["../../../../src/platform/browser/globalThis.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,6EAA6E;AAE7E;;;;;;GAMG;AAEH,gEAAgE;AAChE,8EAA8E;AAC9E,MAAM,CAAC,IAAM,WAAW,GACtB,OAAO,UAAU,KAAK,QAAQ;IAC5B,CAAC,CAAC,UAAU;IACZ,CAAC,CAAC,OAAO,IAAI,KAAK,QAAQ;QAC1B,CAAC,CAAC,IAAI;QACN,CAAC,CAAC,OAAO,MAAM,KAAK,QAAQ;YAC5B,CAAC,CAAC,MAAM;YACR,CAAC,CAAC,OAAO,MAAM,KAAK,QAAQ;gBAC5B,CAAC,CAAC,MAAM;gBACR,CAAC,CAAE,EAAwB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Updates to this file should also be replicated to @opentelemetry/core too.\n\n/**\n * - globalThis (New standard)\n * - self (Will return the current window instance for supported browsers)\n * - window (fallback for older browser implementations)\n * - global (NodeJS implementation)\n * - (When all else fails)\n */\n\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins, no-undef\nexport const _globalThis: typeof globalThis =\n typeof globalThis === 'object'\n ? globalThis\n : typeof self === 'object'\n ? self\n : typeof window === 'object'\n ? window\n : typeof global === 'object'\n ? global\n : ({} as typeof globalThis);\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/platform/browser/index.d.ts b/node_modules/@opentelemetry/api/build/esm/platform/browser/index.d.ts new file mode 100644 index 0000000..ba20e12 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/platform/browser/index.d.ts @@ -0,0 +1,2 @@ +export * from './globalThis'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/platform/browser/index.js b/node_modules/@opentelemetry/api/build/esm/platform/browser/index.js new file mode 100644 index 0000000..efcad2e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/platform/browser/index.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './globalThis'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/platform/browser/index.js.map b/node_modules/@opentelemetry/api/build/esm/platform/browser/index.js.map new file mode 100644 index 0000000..07adcd9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/platform/browser/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/browser/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,cAAc,cAAc,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './globalThis';\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/platform/index.d.ts b/node_modules/@opentelemetry/api/build/esm/platform/index.d.ts new file mode 100644 index 0000000..90595da --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/platform/index.d.ts @@ -0,0 +1,2 @@ +export * from './node'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/platform/index.js b/node_modules/@opentelemetry/api/build/esm/platform/index.js new file mode 100644 index 0000000..c0df125 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/platform/index.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './node'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/platform/index.js.map b/node_modules/@opentelemetry/api/build/esm/platform/index.js.map new file mode 100644 index 0000000..9494c53 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/platform/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/platform/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,cAAc,QAAQ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './node';\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.d.ts b/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.d.ts new file mode 100644 index 0000000..e3c83e5 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.d.ts @@ -0,0 +1,3 @@ +/** only globals that common to node and browsers are allowed */ +export declare const _globalThis: typeof globalThis; +//# sourceMappingURL=globalThis.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js b/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js new file mode 100644 index 0000000..feb9700 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js @@ -0,0 +1,19 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** only globals that common to node and browsers are allowed */ +// eslint-disable-next-line node/no-unsupported-features/es-builtins +export var _globalThis = typeof globalThis === 'object' ? globalThis : global; +//# sourceMappingURL=globalThis.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js.map b/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js.map new file mode 100644 index 0000000..5911136 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js.map @@ -0,0 +1 @@ +{"version":3,"file":"globalThis.js","sourceRoot":"","sources":["../../../../src/platform/node/globalThis.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,gEAAgE;AAChE,oEAAoE;AACpE,MAAM,CAAC,IAAM,WAAW,GAAG,OAAO,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/platform/node/index.d.ts b/node_modules/@opentelemetry/api/build/esm/platform/node/index.d.ts new file mode 100644 index 0000000..ba20e12 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/platform/node/index.d.ts @@ -0,0 +1,2 @@ +export * from './globalThis'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/platform/node/index.js b/node_modules/@opentelemetry/api/build/esm/platform/node/index.js new file mode 100644 index 0000000..efcad2e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/platform/node/index.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './globalThis'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/platform/node/index.js.map b/node_modules/@opentelemetry/api/build/esm/platform/node/index.js.map new file mode 100644 index 0000000..f279718 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/platform/node/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/node/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,cAAc,cAAc,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './globalThis';\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/propagation-api.d.ts b/node_modules/@opentelemetry/api/build/esm/propagation-api.d.ts new file mode 100644 index 0000000..e12b51b --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/propagation-api.d.ts @@ -0,0 +1,4 @@ +import { PropagationAPI } from './api/propagation'; +/** Entrypoint for propagation API */ +export declare const propagation: PropagationAPI; +//# sourceMappingURL=propagation-api.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/propagation-api.js b/node_modules/@opentelemetry/api/build/esm/propagation-api.js new file mode 100644 index 0000000..df8d5b9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/propagation-api.js @@ -0,0 +1,21 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +import { PropagationAPI } from './api/propagation'; +/** Entrypoint for propagation API */ +export var propagation = PropagationAPI.getInstance(); +//# sourceMappingURL=propagation-api.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/propagation-api.js.map b/node_modules/@opentelemetry/api/build/esm/propagation-api.js.map new file mode 100644 index 0000000..2375317 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/propagation-api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"propagation-api.js","sourceRoot":"","sources":["../../src/propagation-api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,sEAAsE;AACtE,qCAAqC;AACrC,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,qCAAqC;AACrC,MAAM,CAAC,IAAM,WAAW,GAAG,cAAc,CAAC,WAAW,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { PropagationAPI } from './api/propagation';\n/** Entrypoint for propagation API */\nexport const propagation = PropagationAPI.getInstance();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.d.ts b/node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.d.ts new file mode 100644 index 0000000..398021f --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.d.ts @@ -0,0 +1,13 @@ +import { Context } from '../context/types'; +import { TextMapPropagator } from './TextMapPropagator'; +/** + * No-op implementations of {@link TextMapPropagator}. + */ +export declare class NoopTextMapPropagator implements TextMapPropagator { + /** Noop inject function does nothing */ + inject(_context: Context, _carrier: unknown): void; + /** Noop extract function does nothing and returns the input context */ + extract(context: Context, _carrier: unknown): Context; + fields(): string[]; +} +//# sourceMappingURL=NoopTextMapPropagator.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.js b/node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.js new file mode 100644 index 0000000..8e62901 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.js @@ -0,0 +1,34 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * No-op implementations of {@link TextMapPropagator}. + */ +var NoopTextMapPropagator = /** @class */ (function () { + function NoopTextMapPropagator() { + } + /** Noop inject function does nothing */ + NoopTextMapPropagator.prototype.inject = function (_context, _carrier) { }; + /** Noop extract function does nothing and returns the input context */ + NoopTextMapPropagator.prototype.extract = function (context, _carrier) { + return context; + }; + NoopTextMapPropagator.prototype.fields = function () { + return []; + }; + return NoopTextMapPropagator; +}()); +export { NoopTextMapPropagator }; +//# sourceMappingURL=NoopTextMapPropagator.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.js.map b/node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.js.map new file mode 100644 index 0000000..40be566 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NoopTextMapPropagator.js","sourceRoot":"","sources":["../../../src/propagation/NoopTextMapPropagator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAKH;;GAEG;AACH;IAAA;IAUA,CAAC;IATC,wCAAwC;IACxC,sCAAM,GAAN,UAAO,QAAiB,EAAE,QAAiB,IAAS,CAAC;IACrD,uEAAuE;IACvE,uCAAO,GAAP,UAAQ,OAAgB,EAAE,QAAiB;QACzC,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,sCAAM,GAAN;QACE,OAAO,EAAE,CAAC;IACZ,CAAC;IACH,4BAAC;AAAD,CAAC,AAVD,IAUC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport { TextMapPropagator } from './TextMapPropagator';\n\n/**\n * No-op implementations of {@link TextMapPropagator}.\n */\nexport class NoopTextMapPropagator implements TextMapPropagator {\n /** Noop inject function does nothing */\n inject(_context: Context, _carrier: unknown): void {}\n /** Noop extract function does nothing and returns the input context */\n extract(context: Context, _carrier: unknown): Context {\n return context;\n }\n fields(): string[] {\n return [];\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.d.ts b/node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.d.ts new file mode 100644 index 0000000..dc39367 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.d.ts @@ -0,0 +1,84 @@ +import { Context } from '../context/types'; +/** + * Injects `Context` into and extracts it from carriers that travel + * in-band across process boundaries. Encoding is expected to conform to the + * HTTP Header Field semantics. Values are often encoded as RPC/HTTP request + * headers. + * + * The carrier of propagated data on both the client (injector) and server + * (extractor) side is usually an object such as http headers. Propagation is + * usually implemented via library-specific request interceptors, where the + * client-side injects values and the server-side extracts them. + */ +export interface TextMapPropagator { + /** + * Injects values from a given `Context` into a carrier. + * + * OpenTelemetry defines a common set of format values (TextMapPropagator), + * and each has an expected `carrier` type. + * + * @param context the Context from which to extract values to transmit over + * the wire. + * @param carrier the carrier of propagation fields, such as http request + * headers. + * @param setter an optional {@link TextMapSetter}. If undefined, values will be + * set by direct object assignment. + */ + inject(context: Context, carrier: Carrier, setter: TextMapSetter): void; + /** + * Given a `Context` and a carrier, extract context values from a + * carrier and return a new context, created from the old context, with the + * extracted values. + * + * @param context the Context from which to extract values to transmit over + * the wire. + * @param carrier the carrier of propagation fields, such as http request + * headers. + * @param getter an optional {@link TextMapGetter}. If undefined, keys will be all + * own properties, and keys will be accessed by direct object access. + */ + extract(context: Context, carrier: Carrier, getter: TextMapGetter): Context; + /** + * Return a list of all fields which may be used by the propagator. + */ + fields(): string[]; +} +/** + * A setter is specified by the caller to define a specific method + * to set key/value pairs on the carrier within a propagator. + */ +export interface TextMapSetter { + /** + * Callback used to set a key/value pair on an object. + * + * Should be called by the propagator each time a key/value pair + * should be set, and should set that key/value pair on the propagator. + * + * @param carrier object or class which carries key/value pairs + * @param key string key to modify + * @param value value to be set to the key on the carrier + */ + set(carrier: Carrier, key: string, value: string): void; +} +/** + * A getter is specified by the caller to define a specific method + * to get the value of a key from a carrier. + */ +export interface TextMapGetter { + /** + * Get a list of all keys available on the carrier. + * + * @param carrier + */ + keys(carrier: Carrier): string[]; + /** + * Get the value of a specific key from the carrier. + * + * @param carrier + * @param key + */ + get(carrier: Carrier, key: string): undefined | string | string[]; +} +export declare const defaultTextMapGetter: TextMapGetter; +export declare const defaultTextMapSetter: TextMapSetter; +//# sourceMappingURL=TextMapPropagator.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.js b/node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.js new file mode 100644 index 0000000..c5f5311 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.js @@ -0,0 +1,38 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export var defaultTextMapGetter = { + get: function (carrier, key) { + if (carrier == null) { + return undefined; + } + return carrier[key]; + }, + keys: function (carrier) { + if (carrier == null) { + return []; + } + return Object.keys(carrier); + }, +}; +export var defaultTextMapSetter = { + set: function (carrier, key, value) { + if (carrier == null) { + return; + } + carrier[key] = value; + }, +}; +//# sourceMappingURL=TextMapPropagator.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.js.map b/node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.js.map new file mode 100644 index 0000000..9de7d06 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"TextMapPropagator.js","sourceRoot":"","sources":["../../../src/propagation/TextMapPropagator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAkGH,MAAM,CAAC,IAAM,oBAAoB,GAAkB;IACjD,GAAG,YAAC,OAAO,EAAE,GAAG;QACd,IAAI,OAAO,IAAI,IAAI,EAAE;YACnB,OAAO,SAAS,CAAC;SAClB;QACD,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC;IACtB,CAAC;IAED,IAAI,YAAC,OAAO;QACV,IAAI,OAAO,IAAI,IAAI,EAAE;YACnB,OAAO,EAAE,CAAC;SACX;QACD,OAAO,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC9B,CAAC;CACF,CAAC;AAEF,MAAM,CAAC,IAAM,oBAAoB,GAAkB;IACjD,GAAG,YAAC,OAAO,EAAE,GAAG,EAAE,KAAK;QACrB,IAAI,OAAO,IAAI,IAAI,EAAE;YACnB,OAAO;SACR;QAED,OAAO,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IACvB,CAAC;CACF,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\n\n/**\n * Injects `Context` into and extracts it from carriers that travel\n * in-band across process boundaries. Encoding is expected to conform to the\n * HTTP Header Field semantics. Values are often encoded as RPC/HTTP request\n * headers.\n *\n * The carrier of propagated data on both the client (injector) and server\n * (extractor) side is usually an object such as http headers. Propagation is\n * usually implemented via library-specific request interceptors, where the\n * client-side injects values and the server-side extracts them.\n */\nexport interface TextMapPropagator {\n /**\n * Injects values from a given `Context` into a carrier.\n *\n * OpenTelemetry defines a common set of format values (TextMapPropagator),\n * and each has an expected `carrier` type.\n *\n * @param context the Context from which to extract values to transmit over\n * the wire.\n * @param carrier the carrier of propagation fields, such as http request\n * headers.\n * @param setter an optional {@link TextMapSetter}. If undefined, values will be\n * set by direct object assignment.\n */\n inject(\n context: Context,\n carrier: Carrier,\n setter: TextMapSetter\n ): void;\n\n /**\n * Given a `Context` and a carrier, extract context values from a\n * carrier and return a new context, created from the old context, with the\n * extracted values.\n *\n * @param context the Context from which to extract values to transmit over\n * the wire.\n * @param carrier the carrier of propagation fields, such as http request\n * headers.\n * @param getter an optional {@link TextMapGetter}. If undefined, keys will be all\n * own properties, and keys will be accessed by direct object access.\n */\n extract(\n context: Context,\n carrier: Carrier,\n getter: TextMapGetter\n ): Context;\n\n /**\n * Return a list of all fields which may be used by the propagator.\n */\n fields(): string[];\n}\n\n/**\n * A setter is specified by the caller to define a specific method\n * to set key/value pairs on the carrier within a propagator.\n */\nexport interface TextMapSetter {\n /**\n * Callback used to set a key/value pair on an object.\n *\n * Should be called by the propagator each time a key/value pair\n * should be set, and should set that key/value pair on the propagator.\n *\n * @param carrier object or class which carries key/value pairs\n * @param key string key to modify\n * @param value value to be set to the key on the carrier\n */\n set(carrier: Carrier, key: string, value: string): void;\n}\n\n/**\n * A getter is specified by the caller to define a specific method\n * to get the value of a key from a carrier.\n */\nexport interface TextMapGetter {\n /**\n * Get a list of all keys available on the carrier.\n *\n * @param carrier\n */\n keys(carrier: Carrier): string[];\n\n /**\n * Get the value of a specific key from the carrier.\n *\n * @param carrier\n * @param key\n */\n get(carrier: Carrier, key: string): undefined | string | string[];\n}\n\nexport const defaultTextMapGetter: TextMapGetter = {\n get(carrier, key) {\n if (carrier == null) {\n return undefined;\n }\n return carrier[key];\n },\n\n keys(carrier) {\n if (carrier == null) {\n return [];\n }\n return Object.keys(carrier);\n },\n};\n\nexport const defaultTextMapSetter: TextMapSetter = {\n set(carrier, key, value) {\n if (carrier == null) {\n return;\n }\n\n carrier[key] = value;\n },\n};\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace-api.d.ts b/node_modules/@opentelemetry/api/build/esm/trace-api.d.ts new file mode 100644 index 0000000..b4751a7 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace-api.d.ts @@ -0,0 +1,4 @@ +import { TraceAPI } from './api/trace'; +/** Entrypoint for trace API */ +export declare const trace: TraceAPI; +//# sourceMappingURL=trace-api.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace-api.js b/node_modules/@opentelemetry/api/build/esm/trace-api.js new file mode 100644 index 0000000..57506e5 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace-api.js @@ -0,0 +1,21 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +import { TraceAPI } from './api/trace'; +/** Entrypoint for trace API */ +export var trace = TraceAPI.getInstance(); +//# sourceMappingURL=trace-api.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace-api.js.map b/node_modules/@opentelemetry/api/build/esm/trace-api.js.map new file mode 100644 index 0000000..bd11c06 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace-api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-api.js","sourceRoot":"","sources":["../../src/trace-api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,sEAAsE;AACtE,qCAAqC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,+BAA+B;AAC/B,MAAM,CAAC,IAAM,KAAK,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { TraceAPI } from './api/trace';\n/** Entrypoint for trace API */\nexport const trace = TraceAPI.getInstance();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.d.ts new file mode 100644 index 0000000..ce569f0 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.d.ts @@ -0,0 +1,28 @@ +import { Exception } from '../common/Exception'; +import { TimeInput } from '../common/Time'; +import { SpanAttributes } from './attributes'; +import { Span } from './span'; +import { SpanContext } from './span_context'; +import { SpanStatus } from './status'; +import { Link } from './link'; +/** + * The NonRecordingSpan is the default {@link Span} that is used when no Span + * implementation is available. All operations are no-op including context + * propagation. + */ +export declare class NonRecordingSpan implements Span { + private readonly _spanContext; + constructor(_spanContext?: SpanContext); + spanContext(): SpanContext; + setAttribute(_key: string, _value: unknown): this; + setAttributes(_attributes: SpanAttributes): this; + addEvent(_name: string, _attributes?: SpanAttributes): this; + addLink(_link: Link): this; + addLinks(_links: Link[]): this; + setStatus(_status: SpanStatus): this; + updateName(_name: string): this; + end(_endTime?: TimeInput): void; + isRecording(): boolean; + recordException(_exception: Exception, _time?: TimeInput): void; +} +//# sourceMappingURL=NonRecordingSpan.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js b/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js new file mode 100644 index 0000000..ec6dd75 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js @@ -0,0 +1,68 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { INVALID_SPAN_CONTEXT } from './invalid-span-constants'; +/** + * The NonRecordingSpan is the default {@link Span} that is used when no Span + * implementation is available. All operations are no-op including context + * propagation. + */ +var NonRecordingSpan = /** @class */ (function () { + function NonRecordingSpan(_spanContext) { + if (_spanContext === void 0) { _spanContext = INVALID_SPAN_CONTEXT; } + this._spanContext = _spanContext; + } + // Returns a SpanContext. + NonRecordingSpan.prototype.spanContext = function () { + return this._spanContext; + }; + // By default does nothing + NonRecordingSpan.prototype.setAttribute = function (_key, _value) { + return this; + }; + // By default does nothing + NonRecordingSpan.prototype.setAttributes = function (_attributes) { + return this; + }; + // By default does nothing + NonRecordingSpan.prototype.addEvent = function (_name, _attributes) { + return this; + }; + NonRecordingSpan.prototype.addLink = function (_link) { + return this; + }; + NonRecordingSpan.prototype.addLinks = function (_links) { + return this; + }; + // By default does nothing + NonRecordingSpan.prototype.setStatus = function (_status) { + return this; + }; + // By default does nothing + NonRecordingSpan.prototype.updateName = function (_name) { + return this; + }; + // By default does nothing + NonRecordingSpan.prototype.end = function (_endTime) { }; + // isRecording always returns false for NonRecordingSpan. + NonRecordingSpan.prototype.isRecording = function () { + return false; + }; + // By default does nothing + NonRecordingSpan.prototype.recordException = function (_exception, _time) { }; + return NonRecordingSpan; +}()); +export { NonRecordingSpan }; +//# sourceMappingURL=NonRecordingSpan.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js.map b/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js.map new file mode 100644 index 0000000..15f932e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NonRecordingSpan.js","sourceRoot":"","sources":["../../../src/trace/NonRecordingSpan.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAKH,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAMhE;;;;GAIG;AACH;IACE,0BACmB,YAAgD;QAAhD,6BAAA,EAAA,mCAAgD;QAAhD,iBAAY,GAAZ,YAAY,CAAoC;IAChE,CAAC;IAEJ,yBAAyB;IACzB,sCAAW,GAAX;QACE,OAAO,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;IAED,0BAA0B;IAC1B,uCAAY,GAAZ,UAAa,IAAY,EAAE,MAAe;QACxC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,0BAA0B;IAC1B,wCAAa,GAAb,UAAc,WAA2B;QACvC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,0BAA0B;IAC1B,mCAAQ,GAAR,UAAS,KAAa,EAAE,WAA4B;QAClD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,kCAAO,GAAP,UAAQ,KAAW;QACjB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,mCAAQ,GAAR,UAAS,MAAc;QACrB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,0BAA0B;IAC1B,oCAAS,GAAT,UAAU,OAAmB;QAC3B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,0BAA0B;IAC1B,qCAAU,GAAV,UAAW,KAAa;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,0BAA0B;IAC1B,8BAAG,GAAH,UAAI,QAAoB,IAAS,CAAC;IAElC,yDAAyD;IACzD,sCAAW,GAAX;QACE,OAAO,KAAK,CAAC;IACf,CAAC;IAED,0BAA0B;IAC1B,0CAAe,GAAf,UAAgB,UAAqB,EAAE,KAAiB,IAAS,CAAC;IACpE,uBAAC;AAAD,CAAC,AArDD,IAqDC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '../common/Exception';\nimport { TimeInput } from '../common/Time';\nimport { SpanAttributes } from './attributes';\nimport { INVALID_SPAN_CONTEXT } from './invalid-span-constants';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\nimport { SpanStatus } from './status';\nimport { Link } from './link';\n\n/**\n * The NonRecordingSpan is the default {@link Span} that is used when no Span\n * implementation is available. All operations are no-op including context\n * propagation.\n */\nexport class NonRecordingSpan implements Span {\n constructor(\n private readonly _spanContext: SpanContext = INVALID_SPAN_CONTEXT\n ) {}\n\n // Returns a SpanContext.\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n // By default does nothing\n setAttribute(_key: string, _value: unknown): this {\n return this;\n }\n\n // By default does nothing\n setAttributes(_attributes: SpanAttributes): this {\n return this;\n }\n\n // By default does nothing\n addEvent(_name: string, _attributes?: SpanAttributes): this {\n return this;\n }\n\n addLink(_link: Link): this {\n return this;\n }\n\n addLinks(_links: Link[]): this {\n return this;\n }\n\n // By default does nothing\n setStatus(_status: SpanStatus): this {\n return this;\n }\n\n // By default does nothing\n updateName(_name: string): this {\n return this;\n }\n\n // By default does nothing\n end(_endTime?: TimeInput): void {}\n\n // isRecording always returns false for NonRecordingSpan.\n isRecording(): boolean {\n return false;\n }\n\n // By default does nothing\n recordException(_exception: Exception, _time?: TimeInput): void {}\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.d.ts new file mode 100644 index 0000000..0e059c9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.d.ts @@ -0,0 +1,14 @@ +import { Context } from '../context/types'; +import { Span } from './span'; +import { SpanOptions } from './SpanOptions'; +import { Tracer } from './tracer'; +/** + * No-op implementations of {@link Tracer}. + */ +export declare class NoopTracer implements Tracer { + startSpan(name: string, options?: SpanOptions, context?: Context): Span; + startActiveSpan ReturnType>(name: string, fn: F): ReturnType; + startActiveSpan ReturnType>(name: string, opts: SpanOptions | undefined, fn: F): ReturnType; + startActiveSpan ReturnType>(name: string, opts: SpanOptions | undefined, ctx: Context | undefined, fn: F): ReturnType; +} +//# sourceMappingURL=NoopTracer.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js b/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js new file mode 100644 index 0000000..5a3a969 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js @@ -0,0 +1,76 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ContextAPI } from '../api/context'; +import { getSpanContext, setSpan } from '../trace/context-utils'; +import { NonRecordingSpan } from './NonRecordingSpan'; +import { isSpanContextValid } from './spancontext-utils'; +var contextApi = ContextAPI.getInstance(); +/** + * No-op implementations of {@link Tracer}. + */ +var NoopTracer = /** @class */ (function () { + function NoopTracer() { + } + // startSpan starts a noop span. + NoopTracer.prototype.startSpan = function (name, options, context) { + if (context === void 0) { context = contextApi.active(); } + var root = Boolean(options === null || options === void 0 ? void 0 : options.root); + if (root) { + return new NonRecordingSpan(); + } + var parentFromContext = context && getSpanContext(context); + if (isSpanContext(parentFromContext) && + isSpanContextValid(parentFromContext)) { + return new NonRecordingSpan(parentFromContext); + } + else { + return new NonRecordingSpan(); + } + }; + NoopTracer.prototype.startActiveSpan = function (name, arg2, arg3, arg4) { + var opts; + var ctx; + var fn; + if (arguments.length < 2) { + return; + } + else if (arguments.length === 2) { + fn = arg2; + } + else if (arguments.length === 3) { + opts = arg2; + fn = arg3; + } + else { + opts = arg2; + ctx = arg3; + fn = arg4; + } + var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); + var span = this.startSpan(name, opts, parentContext); + var contextWithSpanSet = setSpan(parentContext, span); + return contextApi.with(contextWithSpanSet, fn, undefined, span); + }; + return NoopTracer; +}()); +export { NoopTracer }; +function isSpanContext(spanContext) { + return (typeof spanContext === 'object' && + typeof spanContext['spanId'] === 'string' && + typeof spanContext['traceId'] === 'string' && + typeof spanContext['traceFlags'] === 'number'); +} +//# sourceMappingURL=NoopTracer.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js.map b/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js.map new file mode 100644 index 0000000..ae82938 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NoopTracer.js","sourceRoot":"","sources":["../../../src/trace/NoopTracer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAKzD,IAAM,UAAU,GAAG,UAAU,CAAC,WAAW,EAAE,CAAC;AAE5C;;GAEG;AACH;IAAA;IAoEA,CAAC;IAnEC,gCAAgC;IAChC,8BAAS,GAAT,UACE,IAAY,EACZ,OAAqB,EACrB,OAA6B;QAA7B,wBAAA,EAAA,UAAU,UAAU,CAAC,MAAM,EAAE;QAE7B,IAAM,IAAI,GAAG,OAAO,CAAC,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,IAAI,CAAC,CAAC;QACpC,IAAI,IAAI,EAAE;YACR,OAAO,IAAI,gBAAgB,EAAE,CAAC;SAC/B;QAED,IAAM,iBAAiB,GAAG,OAAO,IAAI,cAAc,CAAC,OAAO,CAAC,CAAC;QAE7D,IACE,aAAa,CAAC,iBAAiB,CAAC;YAChC,kBAAkB,CAAC,iBAAiB,CAAC,EACrC;YACA,OAAO,IAAI,gBAAgB,CAAC,iBAAiB,CAAC,CAAC;SAChD;aAAM;YACL,OAAO,IAAI,gBAAgB,EAAE,CAAC;SAC/B;IACH,CAAC;IAiBD,oCAAe,GAAf,UACE,IAAY,EACZ,IAAsB,EACtB,IAAkB,EAClB,IAAQ;QAER,IAAI,IAA6B,CAAC;QAClC,IAAI,GAAwB,CAAC;QAC7B,IAAI,EAAK,CAAC;QAEV,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE;YACxB,OAAO;SACR;aAAM,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE;YACjC,EAAE,GAAG,IAAS,CAAC;SAChB;aAAM,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE;YACjC,IAAI,GAAG,IAA+B,CAAC;YACvC,EAAE,GAAG,IAAS,CAAC;SAChB;aAAM;YACL,IAAI,GAAG,IAA+B,CAAC;YACvC,GAAG,GAAG,IAA2B,CAAC;YAClC,EAAE,GAAG,IAAS,CAAC;SAChB;QAED,IAAM,aAAa,GAAG,GAAG,aAAH,GAAG,cAAH,GAAG,GAAI,UAAU,CAAC,MAAM,EAAE,CAAC;QACjD,IAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,aAAa,CAAC,CAAC;QACvD,IAAM,kBAAkB,GAAG,OAAO,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC;QAExD,OAAO,UAAU,CAAC,IAAI,CAAC,kBAAkB,EAAE,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;IAClE,CAAC;IACH,iBAAC;AAAD,CAAC,AApED,IAoEC;;AAED,SAAS,aAAa,CAAC,WAAgB;IACrC,OAAO,CACL,OAAO,WAAW,KAAK,QAAQ;QAC/B,OAAO,WAAW,CAAC,QAAQ,CAAC,KAAK,QAAQ;QACzC,OAAO,WAAW,CAAC,SAAS,CAAC,KAAK,QAAQ;QAC1C,OAAO,WAAW,CAAC,YAAY,CAAC,KAAK,QAAQ,CAC9C,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ContextAPI } from '../api/context';\nimport { Context } from '../context/types';\nimport { getSpanContext, setSpan } from '../trace/context-utils';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { Span } from './span';\nimport { isSpanContextValid } from './spancontext-utils';\nimport { SpanOptions } from './SpanOptions';\nimport { SpanContext } from './span_context';\nimport { Tracer } from './tracer';\n\nconst contextApi = ContextAPI.getInstance();\n\n/**\n * No-op implementations of {@link Tracer}.\n */\nexport class NoopTracer implements Tracer {\n // startSpan starts a noop span.\n startSpan(\n name: string,\n options?: SpanOptions,\n context = contextApi.active()\n ): Span {\n const root = Boolean(options?.root);\n if (root) {\n return new NonRecordingSpan();\n }\n\n const parentFromContext = context && getSpanContext(context);\n\n if (\n isSpanContext(parentFromContext) &&\n isSpanContextValid(parentFromContext)\n ) {\n return new NonRecordingSpan(parentFromContext);\n } else {\n return new NonRecordingSpan();\n }\n }\n\n startActiveSpan ReturnType>(\n name: string,\n fn: F\n ): ReturnType;\n startActiveSpan ReturnType>(\n name: string,\n opts: SpanOptions | undefined,\n fn: F\n ): ReturnType;\n startActiveSpan ReturnType>(\n name: string,\n opts: SpanOptions | undefined,\n ctx: Context | undefined,\n fn: F\n ): ReturnType;\n startActiveSpan ReturnType>(\n name: string,\n arg2?: F | SpanOptions,\n arg3?: F | Context,\n arg4?: F\n ): ReturnType | undefined {\n let opts: SpanOptions | undefined;\n let ctx: Context | undefined;\n let fn: F;\n\n if (arguments.length < 2) {\n return;\n } else if (arguments.length === 2) {\n fn = arg2 as F;\n } else if (arguments.length === 3) {\n opts = arg2 as SpanOptions | undefined;\n fn = arg3 as F;\n } else {\n opts = arg2 as SpanOptions | undefined;\n ctx = arg3 as Context | undefined;\n fn = arg4 as F;\n }\n\n const parentContext = ctx ?? contextApi.active();\n const span = this.startSpan(name, opts, parentContext);\n const contextWithSpanSet = setSpan(parentContext, span);\n\n return contextApi.with(contextWithSpanSet, fn, undefined, span);\n }\n}\n\nfunction isSpanContext(spanContext: any): spanContext is SpanContext {\n return (\n typeof spanContext === 'object' &&\n typeof spanContext['spanId'] === 'string' &&\n typeof spanContext['traceId'] === 'string' &&\n typeof spanContext['traceFlags'] === 'number'\n );\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.d.ts new file mode 100644 index 0000000..ec0fe79 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.d.ts @@ -0,0 +1,13 @@ +import { Tracer } from './tracer'; +import { TracerOptions } from './tracer_options'; +import { TracerProvider } from './tracer_provider'; +/** + * An implementation of the {@link TracerProvider} which returns an impotent + * Tracer for all calls to `getTracer`. + * + * All operations are no-op. + */ +export declare class NoopTracerProvider implements TracerProvider { + getTracer(_name?: string, _version?: string, _options?: TracerOptions): Tracer; +} +//# sourceMappingURL=NoopTracerProvider.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js b/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js new file mode 100644 index 0000000..14d44c2 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js @@ -0,0 +1,32 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NoopTracer } from './NoopTracer'; +/** + * An implementation of the {@link TracerProvider} which returns an impotent + * Tracer for all calls to `getTracer`. + * + * All operations are no-op. + */ +var NoopTracerProvider = /** @class */ (function () { + function NoopTracerProvider() { + } + NoopTracerProvider.prototype.getTracer = function (_name, _version, _options) { + return new NoopTracer(); + }; + return NoopTracerProvider; +}()); +export { NoopTracerProvider }; +//# sourceMappingURL=NoopTracerProvider.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js.map b/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js.map new file mode 100644 index 0000000..2705ab4 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NoopTracerProvider.js","sourceRoot":"","sources":["../../../src/trace/NoopTracerProvider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAK1C;;;;;GAKG;AACH;IAAA;IAQA,CAAC;IAPC,sCAAS,GAAT,UACE,KAAc,EACd,QAAiB,EACjB,QAAwB;QAExB,OAAO,IAAI,UAAU,EAAE,CAAC;IAC1B,CAAC;IACH,yBAAC;AAAD,CAAC,AARD,IAQC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NoopTracer } from './NoopTracer';\nimport { Tracer } from './tracer';\nimport { TracerOptions } from './tracer_options';\nimport { TracerProvider } from './tracer_provider';\n\n/**\n * An implementation of the {@link TracerProvider} which returns an impotent\n * Tracer for all calls to `getTracer`.\n *\n * All operations are no-op.\n */\nexport class NoopTracerProvider implements TracerProvider {\n getTracer(\n _name?: string,\n _version?: string,\n _options?: TracerOptions\n ): Tracer {\n return new NoopTracer();\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.d.ts new file mode 100644 index 0000000..116cc5c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.d.ts @@ -0,0 +1,27 @@ +import { Context } from '../context/types'; +import { Span } from './span'; +import { SpanOptions } from './SpanOptions'; +import { Tracer } from './tracer'; +import { TracerOptions } from './tracer_options'; +/** + * Proxy tracer provided by the proxy tracer provider + */ +export declare class ProxyTracer implements Tracer { + private _provider; + readonly name: string; + readonly version?: string | undefined; + readonly options?: TracerOptions | undefined; + private _delegate?; + constructor(_provider: TracerDelegator, name: string, version?: string | undefined, options?: TracerOptions | undefined); + startSpan(name: string, options?: SpanOptions, context?: Context): Span; + startActiveSpan unknown>(_name: string, _options: F | SpanOptions, _context?: F | Context, _fn?: F): ReturnType; + /** + * Try to get a tracer from the proxy tracer provider. + * If the proxy tracer provider has no delegate, return a noop tracer. + */ + private _getTracer; +} +export interface TracerDelegator { + getDelegateTracer(name: string, version?: string, options?: TracerOptions): Tracer | undefined; +} +//# sourceMappingURL=ProxyTracer.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js b/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js new file mode 100644 index 0000000..341991b --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js @@ -0,0 +1,53 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NoopTracer } from './NoopTracer'; +var NOOP_TRACER = new NoopTracer(); +/** + * Proxy tracer provided by the proxy tracer provider + */ +var ProxyTracer = /** @class */ (function () { + function ProxyTracer(_provider, name, version, options) { + this._provider = _provider; + this.name = name; + this.version = version; + this.options = options; + } + ProxyTracer.prototype.startSpan = function (name, options, context) { + return this._getTracer().startSpan(name, options, context); + }; + ProxyTracer.prototype.startActiveSpan = function (_name, _options, _context, _fn) { + var tracer = this._getTracer(); + return Reflect.apply(tracer.startActiveSpan, tracer, arguments); + }; + /** + * Try to get a tracer from the proxy tracer provider. + * If the proxy tracer provider has no delegate, return a noop tracer. + */ + ProxyTracer.prototype._getTracer = function () { + if (this._delegate) { + return this._delegate; + } + var tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); + if (!tracer) { + return NOOP_TRACER; + } + this._delegate = tracer; + return this._delegate; + }; + return ProxyTracer; +}()); +export { ProxyTracer }; +//# sourceMappingURL=ProxyTracer.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js.map b/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js.map new file mode 100644 index 0000000..0511ae8 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ProxyTracer.js","sourceRoot":"","sources":["../../../src/trace/ProxyTracer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAM1C,IAAM,WAAW,GAAG,IAAI,UAAU,EAAE,CAAC;AAErC;;GAEG;AACH;IAIE,qBACU,SAA0B,EAClB,IAAY,EACZ,OAAgB,EAChB,OAAuB;QAH/B,cAAS,GAAT,SAAS,CAAiB;QAClB,SAAI,GAAJ,IAAI,CAAQ;QACZ,YAAO,GAAP,OAAO,CAAS;QAChB,YAAO,GAAP,OAAO,CAAgB;IACtC,CAAC;IAEJ,+BAAS,GAAT,UAAU,IAAY,EAAE,OAAqB,EAAE,OAAiB;QAC9D,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAC7D,CAAC;IAED,qCAAe,GAAf,UACE,KAAa,EACb,QAAyB,EACzB,QAAsB,EACtB,GAAO;QAEP,IAAM,MAAM,GAAG,IAAI,CAAC,UAAU,EAAE,CAAC;QACjC,OAAO,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,eAAe,EAAE,MAAM,EAAE,SAAS,CAAC,CAAC;IAClE,CAAC;IAED;;;OAGG;IACK,gCAAU,GAAlB;QACE,IAAI,IAAI,CAAC,SAAS,EAAE;YAClB,OAAO,IAAI,CAAC,SAAS,CAAC;SACvB;QAED,IAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,iBAAiB,CAC7C,IAAI,CAAC,IAAI,EACT,IAAI,CAAC,OAAO,EACZ,IAAI,CAAC,OAAO,CACb,CAAC;QAEF,IAAI,CAAC,MAAM,EAAE;YACX,OAAO,WAAW,CAAC;SACpB;QAED,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC;QACxB,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IACH,kBAAC;AAAD,CAAC,AA/CD,IA+CC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport { NoopTracer } from './NoopTracer';\nimport { Span } from './span';\nimport { SpanOptions } from './SpanOptions';\nimport { Tracer } from './tracer';\nimport { TracerOptions } from './tracer_options';\n\nconst NOOP_TRACER = new NoopTracer();\n\n/**\n * Proxy tracer provided by the proxy tracer provider\n */\nexport class ProxyTracer implements Tracer {\n // When a real implementation is provided, this will be it\n private _delegate?: Tracer;\n\n constructor(\n private _provider: TracerDelegator,\n public readonly name: string,\n public readonly version?: string,\n public readonly options?: TracerOptions\n ) {}\n\n startSpan(name: string, options?: SpanOptions, context?: Context): Span {\n return this._getTracer().startSpan(name, options, context);\n }\n\n startActiveSpan unknown>(\n _name: string,\n _options: F | SpanOptions,\n _context?: F | Context,\n _fn?: F\n ): ReturnType {\n const tracer = this._getTracer();\n return Reflect.apply(tracer.startActiveSpan, tracer, arguments);\n }\n\n /**\n * Try to get a tracer from the proxy tracer provider.\n * If the proxy tracer provider has no delegate, return a noop tracer.\n */\n private _getTracer() {\n if (this._delegate) {\n return this._delegate;\n }\n\n const tracer = this._provider.getDelegateTracer(\n this.name,\n this.version,\n this.options\n );\n\n if (!tracer) {\n return NOOP_TRACER;\n }\n\n this._delegate = tracer;\n return this._delegate;\n }\n}\n\nexport interface TracerDelegator {\n getDelegateTracer(\n name: string,\n version?: string,\n options?: TracerOptions\n ): Tracer | undefined;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.d.ts new file mode 100644 index 0000000..ee7eafa --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.d.ts @@ -0,0 +1,25 @@ +import { Tracer } from './tracer'; +import { TracerProvider } from './tracer_provider'; +import { TracerOptions } from './tracer_options'; +/** + * Tracer provider which provides {@link ProxyTracer}s. + * + * Before a delegate is set, tracers provided are NoOp. + * When a delegate is set, traces are provided from the delegate. + * When a delegate is set after tracers have already been provided, + * all tracers already provided will use the provided delegate implementation. + */ +export declare class ProxyTracerProvider implements TracerProvider { + private _delegate?; + /** + * Get a {@link ProxyTracer} + */ + getTracer(name: string, version?: string, options?: TracerOptions): Tracer; + getDelegate(): TracerProvider; + /** + * Set the delegate tracer provider + */ + setDelegate(delegate: TracerProvider): void; + getDelegateTracer(name: string, version?: string, options?: TracerOptions): Tracer | undefined; +} +//# sourceMappingURL=ProxyTracerProvider.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js b/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js new file mode 100644 index 0000000..3cc735c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js @@ -0,0 +1,54 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ProxyTracer } from './ProxyTracer'; +import { NoopTracerProvider } from './NoopTracerProvider'; +var NOOP_TRACER_PROVIDER = new NoopTracerProvider(); +/** + * Tracer provider which provides {@link ProxyTracer}s. + * + * Before a delegate is set, tracers provided are NoOp. + * When a delegate is set, traces are provided from the delegate. + * When a delegate is set after tracers have already been provided, + * all tracers already provided will use the provided delegate implementation. + */ +var ProxyTracerProvider = /** @class */ (function () { + function ProxyTracerProvider() { + } + /** + * Get a {@link ProxyTracer} + */ + ProxyTracerProvider.prototype.getTracer = function (name, version, options) { + var _a; + return ((_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer(this, name, version, options)); + }; + ProxyTracerProvider.prototype.getDelegate = function () { + var _a; + return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER; + }; + /** + * Set the delegate tracer provider + */ + ProxyTracerProvider.prototype.setDelegate = function (delegate) { + this._delegate = delegate; + }; + ProxyTracerProvider.prototype.getDelegateTracer = function (name, version, options) { + var _a; + return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options); + }; + return ProxyTracerProvider; +}()); +export { ProxyTracerProvider }; +//# sourceMappingURL=ProxyTracerProvider.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js.map b/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js.map new file mode 100644 index 0000000..fc9179b --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ProxyTracerProvider.js","sourceRoot":"","sources":["../../../src/trace/ProxyTracerProvider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAG1D,IAAM,oBAAoB,GAAG,IAAI,kBAAkB,EAAE,CAAC;AAEtD;;;;;;;GAOG;AACH;IAAA;IA+BA,CAAC;IA5BC;;OAEG;IACH,uCAAS,GAAT,UAAU,IAAY,EAAE,OAAgB,EAAE,OAAuB;;QAC/D,OAAO,CACL,MAAA,IAAI,CAAC,iBAAiB,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,mCAC9C,IAAI,WAAW,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAC9C,CAAC;IACJ,CAAC;IAED,yCAAW,GAAX;;QACE,OAAO,MAAA,IAAI,CAAC,SAAS,mCAAI,oBAAoB,CAAC;IAChD,CAAC;IAED;;OAEG;IACH,yCAAW,GAAX,UAAY,QAAwB;QAClC,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;IAC5B,CAAC;IAED,+CAAiB,GAAjB,UACE,IAAY,EACZ,OAAgB,EAChB,OAAuB;;QAEvB,OAAO,MAAA,IAAI,CAAC,SAAS,0CAAE,SAAS,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAC3D,CAAC;IACH,0BAAC;AAAD,CAAC,AA/BD,IA+BC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Tracer } from './tracer';\nimport { TracerProvider } from './tracer_provider';\nimport { ProxyTracer } from './ProxyTracer';\nimport { NoopTracerProvider } from './NoopTracerProvider';\nimport { TracerOptions } from './tracer_options';\n\nconst NOOP_TRACER_PROVIDER = new NoopTracerProvider();\n\n/**\n * Tracer provider which provides {@link ProxyTracer}s.\n *\n * Before a delegate is set, tracers provided are NoOp.\n * When a delegate is set, traces are provided from the delegate.\n * When a delegate is set after tracers have already been provided,\n * all tracers already provided will use the provided delegate implementation.\n */\nexport class ProxyTracerProvider implements TracerProvider {\n private _delegate?: TracerProvider;\n\n /**\n * Get a {@link ProxyTracer}\n */\n getTracer(name: string, version?: string, options?: TracerOptions): Tracer {\n return (\n this.getDelegateTracer(name, version, options) ??\n new ProxyTracer(this, name, version, options)\n );\n }\n\n getDelegate(): TracerProvider {\n return this._delegate ?? NOOP_TRACER_PROVIDER;\n }\n\n /**\n * Set the delegate tracer provider\n */\n setDelegate(delegate: TracerProvider) {\n this._delegate = delegate;\n }\n\n getDelegateTracer(\n name: string,\n version?: string,\n options?: TracerOptions\n ): Tracer | undefined {\n return this._delegate?.getTracer(name, version, options);\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/Sampler.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/Sampler.d.ts new file mode 100644 index 0000000..c847eaf --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/Sampler.d.ts @@ -0,0 +1,31 @@ +import { Context } from '../context/types'; +import { SpanAttributes } from './attributes'; +import { Link } from './link'; +import { SamplingResult } from './SamplingResult'; +import { SpanKind } from './span_kind'; +/** + * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. + * This interface represent a sampler. Sampling is a mechanism to control the + * noise and overhead introduced by OpenTelemetry by reducing the number of + * samples of traces collected and sent to the backend. + */ +export interface Sampler { + /** + * Checks whether span needs to be created and tracked. + * + * @param context Parent Context which may contain a span. + * @param traceId of the span to be created. It can be different from the + * traceId in the {@link SpanContext}. Typically in situations when the + * span to be created starts a new trace. + * @param spanName of the span to be created. + * @param spanKind of the span to be created. + * @param attributes Initial set of SpanAttributes for the Span being constructed. + * @param links Collection of links that will be associated with the Span to + * be created. Typically useful for batch operations. + * @returns a {@link SamplingResult}. + */ + shouldSample(context: Context, traceId: string, spanName: string, spanKind: SpanKind, attributes: SpanAttributes, links: Link[]): SamplingResult; + /** Returns the sampler name or short description with the configuration. */ + toString(): string; +} +//# sourceMappingURL=Sampler.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/Sampler.js b/node_modules/@opentelemetry/api/build/esm/trace/Sampler.js new file mode 100644 index 0000000..22a60a1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/Sampler.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=Sampler.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/Sampler.js.map b/node_modules/@opentelemetry/api/build/esm/trace/Sampler.js.map new file mode 100644 index 0000000..66719b1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/Sampler.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Sampler.js","sourceRoot":"","sources":["../../../src/trace/Sampler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport { SpanAttributes } from './attributes';\nimport { Link } from './link';\nimport { SamplingResult } from './SamplingResult';\nimport { SpanKind } from './span_kind';\n\n/**\n * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead.\n * This interface represent a sampler. Sampling is a mechanism to control the\n * noise and overhead introduced by OpenTelemetry by reducing the number of\n * samples of traces collected and sent to the backend.\n */\nexport interface Sampler {\n /**\n * Checks whether span needs to be created and tracked.\n *\n * @param context Parent Context which may contain a span.\n * @param traceId of the span to be created. It can be different from the\n * traceId in the {@link SpanContext}. Typically in situations when the\n * span to be created starts a new trace.\n * @param spanName of the span to be created.\n * @param spanKind of the span to be created.\n * @param attributes Initial set of SpanAttributes for the Span being constructed.\n * @param links Collection of links that will be associated with the Span to\n * be created. Typically useful for batch operations.\n * @returns a {@link SamplingResult}.\n */\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: SpanAttributes,\n links: Link[]\n ): SamplingResult;\n\n /** Returns the sampler name or short description with the configuration. */\n toString(): string;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.d.ts new file mode 100644 index 0000000..f2bb495 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.d.ts @@ -0,0 +1,49 @@ +import { SpanAttributes } from './attributes'; +import { TraceState } from './trace_state'; +/** + * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. + * A sampling decision that determines how a {@link Span} will be recorded + * and collected. + */ +export declare enum SamplingDecision { + /** + * `Span.isRecording() === false`, span will not be recorded and all events + * and attributes will be dropped. + */ + NOT_RECORD = 0, + /** + * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} + * MUST NOT be set. + */ + RECORD = 1, + /** + * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} + * MUST be set. + */ + RECORD_AND_SAMPLED = 2 +} +/** + * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. + * A sampling result contains a decision for a {@link Span} and additional + * attributes the sampler would like to added to the Span. + */ +export interface SamplingResult { + /** + * A sampling decision, refer to {@link SamplingDecision} for details. + */ + decision: SamplingDecision; + /** + * The list of attributes returned by SamplingResult MUST be immutable. + * Caller may call {@link Sampler}.shouldSample any number of times and + * can safely cache the returned value. + */ + attributes?: Readonly; + /** + * A {@link TraceState} that will be associated with the {@link Span} through + * the new {@link SpanContext}. Samplers SHOULD return the TraceState from + * the passed-in {@link Context} if they do not intend to change it. Leaving + * the value undefined will also leave the TraceState unchanged. + */ + traceState?: TraceState; +} +//# sourceMappingURL=SamplingResult.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.js b/node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.js new file mode 100644 index 0000000..be65741 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.js @@ -0,0 +1,39 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. + * A sampling decision that determines how a {@link Span} will be recorded + * and collected. + */ +export var SamplingDecision; +(function (SamplingDecision) { + /** + * `Span.isRecording() === false`, span will not be recorded and all events + * and attributes will be dropped. + */ + SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD"; + /** + * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} + * MUST NOT be set. + */ + SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD"; + /** + * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} + * MUST be set. + */ + SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; +})(SamplingDecision || (SamplingDecision = {})); +//# sourceMappingURL=SamplingResult.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.js.map b/node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.js.map new file mode 100644 index 0000000..fd549c8 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SamplingResult.js","sourceRoot":"","sources":["../../../src/trace/SamplingResult.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAKH;;;;GAIG;AACH,MAAM,CAAN,IAAY,gBAgBX;AAhBD,WAAY,gBAAgB;IAC1B;;;OAGG;IACH,mEAAU,CAAA;IACV;;;OAGG;IACH,2DAAM,CAAA;IACN;;;OAGG;IACH,mFAAkB,CAAA;AACpB,CAAC,EAhBW,gBAAgB,KAAhB,gBAAgB,QAgB3B","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SpanAttributes } from './attributes';\nimport { TraceState } from './trace_state';\n\n/**\n * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead.\n * A sampling decision that determines how a {@link Span} will be recorded\n * and collected.\n */\nexport enum SamplingDecision {\n /**\n * `Span.isRecording() === false`, span will not be recorded and all events\n * and attributes will be dropped.\n */\n NOT_RECORD,\n /**\n * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}\n * MUST NOT be set.\n */\n RECORD,\n /**\n * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}\n * MUST be set.\n */\n RECORD_AND_SAMPLED,\n}\n\n/**\n * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead.\n * A sampling result contains a decision for a {@link Span} and additional\n * attributes the sampler would like to added to the Span.\n */\nexport interface SamplingResult {\n /**\n * A sampling decision, refer to {@link SamplingDecision} for details.\n */\n decision: SamplingDecision;\n /**\n * The list of attributes returned by SamplingResult MUST be immutable.\n * Caller may call {@link Sampler}.shouldSample any number of times and\n * can safely cache the returned value.\n */\n attributes?: Readonly;\n /**\n * A {@link TraceState} that will be associated with the {@link Span} through\n * the new {@link SpanContext}. Samplers SHOULD return the TraceState from\n * the passed-in {@link Context} if they do not intend to change it. Leaving\n * the value undefined will also leave the TraceState unchanged.\n */\n traceState?: TraceState;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/SpanOptions.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/SpanOptions.d.ts new file mode 100644 index 0000000..c804568 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/SpanOptions.d.ts @@ -0,0 +1,23 @@ +import { TimeInput } from '../common/Time'; +import { SpanAttributes } from './attributes'; +import { Link } from './link'; +import { SpanKind } from './span_kind'; +/** + * Options needed for span creation + */ +export interface SpanOptions { + /** + * The SpanKind of a span + * @default {@link SpanKind.INTERNAL} + */ + kind?: SpanKind; + /** A span's attributes */ + attributes?: SpanAttributes; + /** {@link Link}s span to other spans */ + links?: Link[]; + /** A manually specified start time for the created `Span` object. */ + startTime?: TimeInput; + /** The new span should be a root span. (Ignore parent from context). */ + root?: boolean; +} +//# sourceMappingURL=SpanOptions.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/SpanOptions.js b/node_modules/@opentelemetry/api/build/esm/trace/SpanOptions.js new file mode 100644 index 0000000..06b42b1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/SpanOptions.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=SpanOptions.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/SpanOptions.js.map b/node_modules/@opentelemetry/api/build/esm/trace/SpanOptions.js.map new file mode 100644 index 0000000..9132a33 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/SpanOptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SpanOptions.js","sourceRoot":"","sources":["../../../src/trace/SpanOptions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TimeInput } from '../common/Time';\nimport { SpanAttributes } from './attributes';\nimport { Link } from './link';\nimport { SpanKind } from './span_kind';\n\n/**\n * Options needed for span creation\n */\nexport interface SpanOptions {\n /**\n * The SpanKind of a span\n * @default {@link SpanKind.INTERNAL}\n */\n kind?: SpanKind;\n\n /** A span's attributes */\n attributes?: SpanAttributes;\n\n /** {@link Link}s span to other spans */\n links?: Link[];\n\n /** A manually specified start time for the created `Span` object. */\n startTime?: TimeInput;\n\n /** The new span should be a root span. (Ignore parent from context). */\n root?: boolean;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/attributes.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/attributes.d.ts new file mode 100644 index 0000000..a2a5d2a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/attributes.d.ts @@ -0,0 +1,10 @@ +import { Attributes, AttributeValue } from '../common/Attributes'; +/** + * @deprecated please use {@link Attributes} + */ +export declare type SpanAttributes = Attributes; +/** + * @deprecated please use {@link AttributeValue} + */ +export declare type SpanAttributeValue = AttributeValue; +//# sourceMappingURL=attributes.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/attributes.js b/node_modules/@opentelemetry/api/build/esm/trace/attributes.js new file mode 100644 index 0000000..6f1b9a3 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/attributes.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=attributes.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/attributes.js.map b/node_modules/@opentelemetry/api/build/esm/trace/attributes.js.map new file mode 100644 index 0000000..2b02be7 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/attributes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"attributes.js","sourceRoot":"","sources":["../../../src/trace/attributes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Attributes, AttributeValue } from '../common/Attributes';\n\n/**\n * @deprecated please use {@link Attributes}\n */\nexport type SpanAttributes = Attributes;\n\n/**\n * @deprecated please use {@link AttributeValue}\n */\nexport type SpanAttributeValue = AttributeValue;\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/context-utils.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/context-utils.d.ts new file mode 100644 index 0000000..f35f794 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/context-utils.d.ts @@ -0,0 +1,41 @@ +import { Context } from '../context/types'; +import { Span } from './span'; +import { SpanContext } from './span_context'; +/** + * Return the span if one exists + * + * @param context context to get span from + */ +export declare function getSpan(context: Context): Span | undefined; +/** + * Gets the span from the current context, if one exists. + */ +export declare function getActiveSpan(): Span | undefined; +/** + * Set the span on a context + * + * @param context context to use as parent + * @param span span to set active + */ +export declare function setSpan(context: Context, span: Span): Context; +/** + * Remove current span stored in the context + * + * @param context context to delete span from + */ +export declare function deleteSpan(context: Context): Context; +/** + * Wrap span context in a NoopSpan and set as span in a new + * context + * + * @param context context to set active span on + * @param spanContext span context to be wrapped + */ +export declare function setSpanContext(context: Context, spanContext: SpanContext): Context; +/** + * Get the span context of the span if it exists. + * + * @param context context to get values from + */ +export declare function getSpanContext(context: Context): SpanContext | undefined; +//# sourceMappingURL=context-utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js b/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js new file mode 100644 index 0000000..4d776c3 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js @@ -0,0 +1,73 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { createContextKey } from '../context/context'; +import { NonRecordingSpan } from './NonRecordingSpan'; +import { ContextAPI } from '../api/context'; +/** + * span key + */ +var SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN'); +/** + * Return the span if one exists + * + * @param context context to get span from + */ +export function getSpan(context) { + return context.getValue(SPAN_KEY) || undefined; +} +/** + * Gets the span from the current context, if one exists. + */ +export function getActiveSpan() { + return getSpan(ContextAPI.getInstance().active()); +} +/** + * Set the span on a context + * + * @param context context to use as parent + * @param span span to set active + */ +export function setSpan(context, span) { + return context.setValue(SPAN_KEY, span); +} +/** + * Remove current span stored in the context + * + * @param context context to delete span from + */ +export function deleteSpan(context) { + return context.deleteValue(SPAN_KEY); +} +/** + * Wrap span context in a NoopSpan and set as span in a new + * context + * + * @param context context to set active span on + * @param spanContext span context to be wrapped + */ +export function setSpanContext(context, spanContext) { + return setSpan(context, new NonRecordingSpan(spanContext)); +} +/** + * Get the span context of the span if it exists. + * + * @param context context to get values from + */ +export function getSpanContext(context) { + var _a; + return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext(); +} +//# sourceMappingURL=context-utils.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js.map b/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js.map new file mode 100644 index 0000000..86103d1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"context-utils.js","sourceRoot":"","sources":["../../../src/trace/context-utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAItD,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C;;GAEG;AACH,IAAM,QAAQ,GAAG,gBAAgB,CAAC,gCAAgC,CAAC,CAAC;AAEpE;;;;GAIG;AACH,MAAM,UAAU,OAAO,CAAC,OAAgB;IACtC,OAAQ,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAU,IAAI,SAAS,CAAC;AAC3D,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,aAAa;IAC3B,OAAO,OAAO,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC;AACpD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,OAAO,CAAC,OAAgB,EAAE,IAAU;IAClD,OAAO,OAAO,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;AAC1C,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,UAAU,CAAC,OAAgB;IACzC,OAAO,OAAO,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;AACvC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,cAAc,CAC5B,OAAgB,EAChB,WAAwB;IAExB,OAAO,OAAO,CAAC,OAAO,EAAE,IAAI,gBAAgB,CAAC,WAAW,CAAC,CAAC,CAAC;AAC7D,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,OAAgB;;IAC7C,OAAO,MAAA,OAAO,CAAC,OAAO,CAAC,0CAAE,WAAW,EAAE,CAAC;AACzC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createContextKey } from '../context/context';\nimport { Context } from '../context/types';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { ContextAPI } from '../api/context';\n\n/**\n * span key\n */\nconst SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN');\n\n/**\n * Return the span if one exists\n *\n * @param context context to get span from\n */\nexport function getSpan(context: Context): Span | undefined {\n return (context.getValue(SPAN_KEY) as Span) || undefined;\n}\n\n/**\n * Gets the span from the current context, if one exists.\n */\nexport function getActiveSpan(): Span | undefined {\n return getSpan(ContextAPI.getInstance().active());\n}\n\n/**\n * Set the span on a context\n *\n * @param context context to use as parent\n * @param span span to set active\n */\nexport function setSpan(context: Context, span: Span): Context {\n return context.setValue(SPAN_KEY, span);\n}\n\n/**\n * Remove current span stored in the context\n *\n * @param context context to delete span from\n */\nexport function deleteSpan(context: Context): Context {\n return context.deleteValue(SPAN_KEY);\n}\n\n/**\n * Wrap span context in a NoopSpan and set as span in a new\n * context\n *\n * @param context context to set active span on\n * @param spanContext span context to be wrapped\n */\nexport function setSpanContext(\n context: Context,\n spanContext: SpanContext\n): Context {\n return setSpan(context, new NonRecordingSpan(spanContext));\n}\n\n/**\n * Get the span context of the span if it exists.\n *\n * @param context context to get values from\n */\nexport function getSpanContext(context: Context): SpanContext | undefined {\n return getSpan(context)?.spanContext();\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-impl.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-impl.d.ts new file mode 100644 index 0000000..9ed5ecb --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-impl.d.ts @@ -0,0 +1,22 @@ +import { TraceState } from '../trace_state'; +/** + * TraceState must be a class and not a simple object type because of the spec + * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). + * + * Here is the list of allowed mutations: + * - New key-value pair should be added into the beginning of the list + * - The value of any key can be updated. Modified keys MUST be moved to the + * beginning of the list. + */ +export declare class TraceStateImpl implements TraceState { + private _internalState; + constructor(rawTraceState?: string); + set(key: string, value: string): TraceStateImpl; + unset(key: string): TraceStateImpl; + get(key: string): string | undefined; + serialize(): string; + private _parse; + private _keys; + private _clone; +} +//# sourceMappingURL=tracestate-impl.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-impl.js b/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-impl.js new file mode 100644 index 0000000..7514069 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-impl.js @@ -0,0 +1,102 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { validateKey, validateValue } from './tracestate-validators'; +var MAX_TRACE_STATE_ITEMS = 32; +var MAX_TRACE_STATE_LEN = 512; +var LIST_MEMBERS_SEPARATOR = ','; +var LIST_MEMBER_KEY_VALUE_SPLITTER = '='; +/** + * TraceState must be a class and not a simple object type because of the spec + * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). + * + * Here is the list of allowed mutations: + * - New key-value pair should be added into the beginning of the list + * - The value of any key can be updated. Modified keys MUST be moved to the + * beginning of the list. + */ +var TraceStateImpl = /** @class */ (function () { + function TraceStateImpl(rawTraceState) { + this._internalState = new Map(); + if (rawTraceState) + this._parse(rawTraceState); + } + TraceStateImpl.prototype.set = function (key, value) { + // TODO: Benchmark the different approaches(map vs list) and + // use the faster one. + var traceState = this._clone(); + if (traceState._internalState.has(key)) { + traceState._internalState.delete(key); + } + traceState._internalState.set(key, value); + return traceState; + }; + TraceStateImpl.prototype.unset = function (key) { + var traceState = this._clone(); + traceState._internalState.delete(key); + return traceState; + }; + TraceStateImpl.prototype.get = function (key) { + return this._internalState.get(key); + }; + TraceStateImpl.prototype.serialize = function () { + var _this = this; + return this._keys() + .reduce(function (agg, key) { + agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + _this.get(key)); + return agg; + }, []) + .join(LIST_MEMBERS_SEPARATOR); + }; + TraceStateImpl.prototype._parse = function (rawTraceState) { + if (rawTraceState.length > MAX_TRACE_STATE_LEN) + return; + this._internalState = rawTraceState + .split(LIST_MEMBERS_SEPARATOR) + .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning + .reduce(function (agg, part) { + var listMember = part.trim(); // Optional Whitespace (OWS) handling + var i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); + if (i !== -1) { + var key = listMember.slice(0, i); + var value = listMember.slice(i + 1, part.length); + if (validateKey(key) && validateValue(value)) { + agg.set(key, value); + } + else { + // TODO: Consider to add warning log + } + } + return agg; + }, new Map()); + // Because of the reverse() requirement, trunc must be done after map is created + if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { + this._internalState = new Map(Array.from(this._internalState.entries()) + .reverse() // Use reverse same as original tracestate parse chain + .slice(0, MAX_TRACE_STATE_ITEMS)); + } + }; + TraceStateImpl.prototype._keys = function () { + return Array.from(this._internalState.keys()).reverse(); + }; + TraceStateImpl.prototype._clone = function () { + var traceState = new TraceStateImpl(); + traceState._internalState = new Map(this._internalState); + return traceState; + }; + return TraceStateImpl; +}()); +export { TraceStateImpl }; +//# sourceMappingURL=tracestate-impl.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-impl.js.map b/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-impl.js.map new file mode 100644 index 0000000..102cb4f --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-impl.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tracestate-impl.js","sourceRoot":"","sources":["../../../../src/trace/internal/tracestate-impl.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAErE,IAAM,qBAAqB,GAAG,EAAE,CAAC;AACjC,IAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,IAAM,sBAAsB,GAAG,GAAG,CAAC;AACnC,IAAM,8BAA8B,GAAG,GAAG,CAAC;AAE3C;;;;;;;;GAQG;AACH;IAGE,wBAAY,aAAsB;QAF1B,mBAAc,GAAwB,IAAI,GAAG,EAAE,CAAC;QAGtD,IAAI,aAAa;YAAE,IAAI,CAAC,MAAM,C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C;IACH,qBAAC;AAAD,CAAC,AA5ED,IA4EC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TraceState } from '../trace_state';\nimport { validateKey, validateValue } from './tracestate-validators';\n\nconst MAX_TRACE_STATE_ITEMS = 32;\nconst MAX_TRACE_STATE_LEN = 512;\nconst LIST_MEMBERS_SEPARATOR = ',';\nconst LIST_MEMBER_KEY_VALUE_SPLITTER = '=';\n\n/**\n * TraceState must be a class and not a simple object type because of the spec\n * requirement (https://www.w3.org/TR/trace-context/#tracestate-field).\n *\n * Here is the list of allowed mutations:\n * - New key-value pair should be added into the beginning of the list\n * - The value of any key can be updated. Modified keys MUST be moved to the\n * beginning of the list.\n */\nexport class TraceStateImpl implements TraceState {\n private _internalState: Map = new Map();\n\n constructor(rawTraceState?: string) {\n if (rawTraceState) this._parse(rawTraceState);\n }\n\n set(key: string, value: string): TraceStateImpl {\n // TODO: Benchmark the different approaches(map vs list) and\n // use the faster one.\n const traceState = this._clone();\n if (traceState._internalState.has(key)) {\n traceState._internalState.delete(key);\n }\n traceState._internalState.set(key, value);\n return traceState;\n }\n\n unset(key: string): TraceStateImpl {\n const traceState = this._clone();\n traceState._internalState.delete(key);\n return traceState;\n }\n\n get(key: string): string | undefined {\n return this._internalState.get(key);\n }\n\n serialize(): string {\n return this._keys()\n .reduce((agg: string[], key) => {\n agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));\n return agg;\n }, [])\n .join(LIST_MEMBERS_SEPARATOR);\n }\n\n private _parse(rawTraceState: string) {\n if (rawTraceState.length > MAX_TRACE_STATE_LEN) return;\n this._internalState = rawTraceState\n .split(LIST_MEMBERS_SEPARATOR)\n .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning\n .reduce((agg: Map, part: string) => {\n const listMember = part.trim(); // Optional Whitespace (OWS) handling\n const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);\n if (i !== -1) {\n const key = listMember.slice(0, i);\n const value = listMember.slice(i + 1, part.length);\n if (validateKey(key) && validateValue(value)) {\n agg.set(key, value);\n } else {\n // TODO: Consider to add warning log\n }\n }\n return agg;\n }, new Map());\n\n // Because of the reverse() requirement, trunc must be done after map is created\n if (this._internalState.size > MAX_TRACE_STATE_ITEMS) {\n this._internalState = new Map(\n Array.from(this._internalState.entries())\n .reverse() // Use reverse same as original tracestate parse chain\n .slice(0, MAX_TRACE_STATE_ITEMS)\n );\n }\n }\n\n private _keys(): string[] {\n return Array.from(this._internalState.keys()).reverse();\n }\n\n private _clone(): TraceStateImpl {\n const traceState = new TraceStateImpl();\n traceState._internalState = new Map(this._internalState);\n return traceState;\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-validators.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-validators.d.ts new file mode 100644 index 0000000..4917f99 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-validators.d.ts @@ -0,0 +1,15 @@ +/** + * Key is opaque string up to 256 characters printable. It MUST begin with a + * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, + * underscores _, dashes -, asterisks *, and forward slashes /. + * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the + * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. + * see https://www.w3.org/TR/trace-context/#key + */ +export declare function validateKey(key: string): boolean; +/** + * Value is opaque string up to 256 characters printable ASCII RFC0020 + * characters (i.e., the range 0x20 to 0x7E) except comma , and =. + */ +export declare function validateValue(value: string): boolean; +//# sourceMappingURL=tracestate-validators.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-validators.js b/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-validators.js new file mode 100644 index 0000000..1d3f14b --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-validators.js @@ -0,0 +1,41 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]'; +var VALID_KEY = "[a-z]" + VALID_KEY_CHAR_RANGE + "{0,255}"; +var VALID_VENDOR_KEY = "[a-z0-9]" + VALID_KEY_CHAR_RANGE + "{0,240}@[a-z]" + VALID_KEY_CHAR_RANGE + "{0,13}"; +var VALID_KEY_REGEX = new RegExp("^(?:" + VALID_KEY + "|" + VALID_VENDOR_KEY + ")$"); +var VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; +var INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; +/** + * Key is opaque string up to 256 characters printable. It MUST begin with a + * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, + * underscores _, dashes -, asterisks *, and forward slashes /. + * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the + * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. + * see https://www.w3.org/TR/trace-context/#key + */ +export function validateKey(key) { + return VALID_KEY_REGEX.test(key); +} +/** + * Value is opaque string up to 256 characters printable ASCII RFC0020 + * characters (i.e., the range 0x20 to 0x7E) except comma , and =. + */ +export function validateValue(value) { + return (VALID_VALUE_BASE_REGEX.test(value) && + !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)); +} +//# sourceMappingURL=tracestate-validators.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-validators.js.map b/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-validators.js.map new file mode 100644 index 0000000..72899fc --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-validators.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tracestate-validators.js","sourceRoot":"","sources":["../../../../src/trace/internal/tracestate-validators.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,IAAM,oBAAoB,GAAG,cAAc,CAAC;AAC5C,IAAM,SAAS,GAAG,UAAQ,oBAAoB,YAAS,CAAC;AACxD,IAAM,gBAAgB,GAAG,aAAW,oBAAoB,qBAAgB,oBAAoB,WAAQ,CAAC;AACrG,IAAM,eAAe,GAAG,IAAI,MAAM,CAAC,SAAO,SAAS,SAAI,gBAAgB,OAAI,CAAC,CAAC;AAC7E,IAAM,sBAAsB,GAAG,qBAAqB,CAAC;AACrD,IAAM,+BAA+B,GAAG,KAAK,CAAC;AAE9C;;;;;;;GAOG;AACH,MAAM,UAAU,WAAW,CAAC,GAAW;IACrC,OAAO,eAAe,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACnC,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,KAAa;IACzC,OAAO,CACL,sBAAsB,CAAC,IAAI,CAAC,KAAK,CAAC;QAClC,CAAC,+BAA+B,CAAC,IAAI,CAAC,KAAK,CAAC,CAC7C,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]';\nconst VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;\nconst VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;\nconst VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);\nconst VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;\nconst INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;\n\n/**\n * Key is opaque string up to 256 characters printable. It MUST begin with a\n * lowercase letter, and can only contain lowercase letters a-z, digits 0-9,\n * underscores _, dashes -, asterisks *, and forward slashes /.\n * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the\n * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key.\n * see https://www.w3.org/TR/trace-context/#key\n */\nexport function validateKey(key: string): boolean {\n return VALID_KEY_REGEX.test(key);\n}\n\n/**\n * Value is opaque string up to 256 characters printable ASCII RFC0020\n * characters (i.e., the range 0x20 to 0x7E) except comma , and =.\n */\nexport function validateValue(value: string): boolean {\n return (\n VALID_VALUE_BASE_REGEX.test(value) &&\n !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)\n );\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/internal/utils.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/internal/utils.d.ts new file mode 100644 index 0000000..e3b51fe --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/internal/utils.d.ts @@ -0,0 +1,3 @@ +import { TraceState } from '../trace_state'; +export declare function createTraceState(rawTraceState?: string): TraceState; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/internal/utils.js b/node_modules/@opentelemetry/api/build/esm/trace/internal/utils.js new file mode 100644 index 0000000..feea469 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/internal/utils.js @@ -0,0 +1,20 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { TraceStateImpl } from './tracestate-impl'; +export function createTraceState(rawTraceState) { + return new TraceStateImpl(rawTraceState); +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/internal/utils.js.map b/node_modules/@opentelemetry/api/build/esm/trace/internal/utils.js.map new file mode 100644 index 0000000..91ba3d1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/internal/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/trace/internal/utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEnD,MAAM,UAAU,gBAAgB,CAAC,aAAsB;IACrD,OAAO,IAAI,cAAc,CAAC,aAAa,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TraceState } from '../trace_state';\nimport { TraceStateImpl } from './tracestate-impl';\n\nexport function createTraceState(rawTraceState?: string): TraceState {\n return new TraceStateImpl(rawTraceState);\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.d.ts new file mode 100644 index 0000000..e32dab9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.d.ts @@ -0,0 +1,5 @@ +import { SpanContext } from './span_context'; +export declare const INVALID_SPANID = "0000000000000000"; +export declare const INVALID_TRACEID = "00000000000000000000000000000000"; +export declare const INVALID_SPAN_CONTEXT: SpanContext; +//# sourceMappingURL=invalid-span-constants.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js b/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js new file mode 100644 index 0000000..36dc1d6 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js @@ -0,0 +1,24 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { TraceFlags } from './trace_flags'; +export var INVALID_SPANID = '0000000000000000'; +export var INVALID_TRACEID = '00000000000000000000000000000000'; +export var INVALID_SPAN_CONTEXT = { + traceId: INVALID_TRACEID, + spanId: INVALID_SPANID, + traceFlags: TraceFlags.NONE, +}; +//# sourceMappingURL=invalid-span-constants.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js.map b/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js.map new file mode 100644 index 0000000..970a3f4 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"invalid-span-constants.js","sourceRoot":"","sources":["../../../src/trace/invalid-span-constants.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,MAAM,CAAC,IAAM,cAAc,GAAG,kBAAkB,CAAC;AACjD,MAAM,CAAC,IAAM,eAAe,GAAG,kCAAkC,CAAC;AAClE,MAAM,CAAC,IAAM,oBAAoB,GAAgB;IAC/C,OAAO,EAAE,eAAe;IACxB,MAAM,EAAE,cAAc;IACtB,UAAU,EAAE,UAAU,CAAC,IAAI;CAC5B,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SpanContext } from './span_context';\nimport { TraceFlags } from './trace_flags';\n\nexport const INVALID_SPANID = '0000000000000000';\nexport const INVALID_TRACEID = '00000000000000000000000000000000';\nexport const INVALID_SPAN_CONTEXT: SpanContext = {\n traceId: INVALID_TRACEID,\n spanId: INVALID_SPANID,\n traceFlags: TraceFlags.NONE,\n};\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/link.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/link.d.ts new file mode 100644 index 0000000..8fc0106 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/link.d.ts @@ -0,0 +1,26 @@ +import { SpanAttributes } from './attributes'; +import { SpanContext } from './span_context'; +/** + * A pointer from the current {@link Span} to another span in the same trace or + * in a different trace. + * Few examples of Link usage. + * 1. Batch Processing: A batch of elements may contain elements associated + * with one or more traces/spans. Since there can only be one parent + * SpanContext, Link is used to keep reference to SpanContext of all + * elements in the batch. + * 2. Public Endpoint: A SpanContext in incoming client request on a public + * endpoint is untrusted from service provider perspective. In such case it + * is advisable to start a new trace with appropriate sampling decision. + * However, it is desirable to associate incoming SpanContext to new trace + * initiated on service provider side so two traces (from Client and from + * Service Provider) can be correlated. + */ +export interface Link { + /** The {@link SpanContext} of a linked span. */ + context: SpanContext; + /** A set of {@link SpanAttributes} on the link. */ + attributes?: SpanAttributes; + /** Count of attributes of the link that were dropped due to collection limits */ + droppedAttributesCount?: number; +} +//# sourceMappingURL=link.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/link.js b/node_modules/@opentelemetry/api/build/esm/trace/link.js new file mode 100644 index 0000000..7c8accb --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/link.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=link.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/link.js.map b/node_modules/@opentelemetry/api/build/esm/trace/link.js.map new file mode 100644 index 0000000..c10b714 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/link.js.map @@ -0,0 +1 @@ +{"version":3,"file":"link.js","sourceRoot":"","sources":["../../../src/trace/link.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SpanAttributes } from './attributes';\nimport { SpanContext } from './span_context';\n\n/**\n * A pointer from the current {@link Span} to another span in the same trace or\n * in a different trace.\n * Few examples of Link usage.\n * 1. Batch Processing: A batch of elements may contain elements associated\n * with one or more traces/spans. Since there can only be one parent\n * SpanContext, Link is used to keep reference to SpanContext of all\n * elements in the batch.\n * 2. Public Endpoint: A SpanContext in incoming client request on a public\n * endpoint is untrusted from service provider perspective. In such case it\n * is advisable to start a new trace with appropriate sampling decision.\n * However, it is desirable to associate incoming SpanContext to new trace\n * initiated on service provider side so two traces (from Client and from\n * Service Provider) can be correlated.\n */\nexport interface Link {\n /** The {@link SpanContext} of a linked span. */\n context: SpanContext;\n /** A set of {@link SpanAttributes} on the link. */\n attributes?: SpanAttributes;\n /** Count of attributes of the link that were dropped due to collection limits */\n droppedAttributesCount?: number;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/span.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/span.d.ts new file mode 100644 index 0000000..28c6442 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/span.d.ts @@ -0,0 +1,120 @@ +import { Exception } from '../common/Exception'; +import { TimeInput } from '../common/Time'; +import { SpanAttributes, SpanAttributeValue } from './attributes'; +import { SpanContext } from './span_context'; +import { SpanStatus } from './status'; +import { Link } from './link'; +/** + * An interface that represents a span. A span represents a single operation + * within a trace. Examples of span might include remote procedure calls or a + * in-process function calls to sub-components. A Trace has a single, top-level + * "root" Span that in turn may have zero or more child Spans, which in turn + * may have children. + * + * Spans are created by the {@link Tracer.startSpan} method. + */ +export interface Span { + /** + * Returns the {@link SpanContext} object associated with this Span. + * + * Get an immutable, serializable identifier for this span that can be used + * to create new child spans. Returned SpanContext is usable even after the + * span ends. + * + * @returns the SpanContext object associated with this Span. + */ + spanContext(): SpanContext; + /** + * Sets an attribute to the span. + * + * Sets a single Attribute with the key and value passed as arguments. + * + * @param key the key for this attribute. + * @param value the value for this attribute. Setting a value null or + * undefined is invalid and will result in undefined behavior. + */ + setAttribute(key: string, value: SpanAttributeValue): this; + /** + * Sets attributes to the span. + * + * @param attributes the attributes that will be added. + * null or undefined attribute values + * are invalid and will result in undefined behavior. + */ + setAttributes(attributes: SpanAttributes): this; + /** + * Adds an event to the Span. + * + * @param name the name of the event. + * @param [attributesOrStartTime] the attributes that will be added; these are + * associated with this event. Can be also a start time + * if type is {@type TimeInput} and 3rd param is undefined + * @param [startTime] start time of the event. + */ + addEvent(name: string, attributesOrStartTime?: SpanAttributes | TimeInput, startTime?: TimeInput): this; + /** + * Adds a single link to the span. + * + * Links added after the creation will not affect the sampling decision. + * It is preferred span links be added at span creation. + * + * @param link the link to add. + */ + addLink(link: Link): this; + /** + * Adds multiple links to the span. + * + * Links added after the creation will not affect the sampling decision. + * It is preferred span links be added at span creation. + * + * @param links the links to add. + */ + addLinks(links: Link[]): this; + /** + * Sets a status to the span. If used, this will override the default Span + * status. Default is {@link SpanStatusCode.UNSET}. SetStatus overrides the value + * of previous calls to SetStatus on the Span. + * + * @param status the SpanStatus to set. + */ + setStatus(status: SpanStatus): this; + /** + * Updates the Span name. + * + * This will override the name provided via {@link Tracer.startSpan}. + * + * Upon this update, any sampling behavior based on Span name will depend on + * the implementation. + * + * @param name the Span name. + */ + updateName(name: string): this; + /** + * Marks the end of Span execution. + * + * Call to End of a Span MUST not have any effects on child spans. Those may + * still be running and can be ended later. + * + * Do not return `this`. The Span generally should not be used after it + * is ended so chaining is not desired in this context. + * + * @param [endTime] the time to set as Span's end time. If not provided, + * use the current time as the span's end time. + */ + end(endTime?: TimeInput): void; + /** + * Returns the flag whether this span will be recorded. + * + * @returns true if this Span is active and recording information like events + * with the `AddEvent` operation and attributes using `setAttributes`. + */ + isRecording(): boolean; + /** + * Sets exception as a span event + * @param exception the exception the only accepted values are string or Error + * @param [time] the time to set as Span's event time. If not provided, + * use the current time. + */ + recordException(exception: Exception, time?: TimeInput): void; +} +//# sourceMappingURL=span.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/span.js b/node_modules/@opentelemetry/api/build/esm/trace/span.js new file mode 100644 index 0000000..f41c7f6 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/span.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=span.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/span.js.map b/node_modules/@opentelemetry/api/build/esm/trace/span.js.map new file mode 100644 index 0000000..f9a1e32 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/span.js.map @@ -0,0 +1 @@ +{"version":3,"file":"span.js","sourceRoot":"","sources":["../../../src/trace/span.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '../common/Exception';\nimport { TimeInput } from '../common/Time';\nimport { SpanAttributes, SpanAttributeValue } from './attributes';\nimport { SpanContext } from './span_context';\nimport { SpanStatus } from './status';\nimport { Link } from './link';\n\n/**\n * An interface that represents a span. A span represents a single operation\n * within a trace. Examples of span might include remote procedure calls or a\n * in-process function calls to sub-components. A Trace has a single, top-level\n * \"root\" Span that in turn may have zero or more child Spans, which in turn\n * may have children.\n *\n * Spans are created by the {@link Tracer.startSpan} method.\n */\nexport interface Span {\n /**\n * Returns the {@link SpanContext} object associated with this Span.\n *\n * Get an immutable, serializable identifier for this span that can be used\n * to create new child spans. Returned SpanContext is usable even after the\n * span ends.\n *\n * @returns the SpanContext object associated with this Span.\n */\n spanContext(): SpanContext;\n\n /**\n * Sets an attribute to the span.\n *\n * Sets a single Attribute with the key and value passed as arguments.\n *\n * @param key the key for this attribute.\n * @param value the value for this attribute. Setting a value null or\n * undefined is invalid and will result in undefined behavior.\n */\n setAttribute(key: string, value: SpanAttributeValue): this;\n\n /**\n * Sets attributes to the span.\n *\n * @param attributes the attributes that will be added.\n * null or undefined attribute values\n * are invalid and will result in undefined behavior.\n */\n setAttributes(attributes: SpanAttributes): this;\n\n /**\n * Adds an event to the Span.\n *\n * @param name the name of the event.\n * @param [attributesOrStartTime] the attributes that will be added; these are\n * associated with this event. Can be also a start time\n * if type is {@type TimeInput} and 3rd param is undefined\n * @param [startTime] start time of the event.\n */\n addEvent(\n name: string,\n attributesOrStartTime?: SpanAttributes | TimeInput,\n startTime?: TimeInput\n ): this;\n\n /**\n * Adds a single link to the span.\n *\n * Links added after the creation will not affect the sampling decision.\n * It is preferred span links be added at span creation.\n *\n * @param link the link to add.\n */\n addLink(link: Link): this;\n\n /**\n * Adds multiple links to the span.\n *\n * Links added after the creation will not affect the sampling decision.\n * It is preferred span links be added at span creation.\n *\n * @param links the links to add.\n */\n addLinks(links: Link[]): this;\n\n /**\n * Sets a status to the span. If used, this will override the default Span\n * status. Default is {@link SpanStatusCode.UNSET}. SetStatus overrides the value\n * of previous calls to SetStatus on the Span.\n *\n * @param status the SpanStatus to set.\n */\n setStatus(status: SpanStatus): this;\n\n /**\n * Updates the Span name.\n *\n * This will override the name provided via {@link Tracer.startSpan}.\n *\n * Upon this update, any sampling behavior based on Span name will depend on\n * the implementation.\n *\n * @param name the Span name.\n */\n updateName(name: string): this;\n\n /**\n * Marks the end of Span execution.\n *\n * Call to End of a Span MUST not have any effects on child spans. Those may\n * still be running and can be ended later.\n *\n * Do not return `this`. The Span generally should not be used after it\n * is ended so chaining is not desired in this context.\n *\n * @param [endTime] the time to set as Span's end time. If not provided,\n * use the current time as the span's end time.\n */\n end(endTime?: TimeInput): void;\n\n /**\n * Returns the flag whether this span will be recorded.\n *\n * @returns true if this Span is active and recording information like events\n * with the `AddEvent` operation and attributes using `setAttributes`.\n */\n isRecording(): boolean;\n\n /**\n * Sets exception as a span event\n * @param exception the exception the only accepted values are string or Error\n * @param [time] the time to set as Span's event time. If not provided,\n * use the current time.\n */\n recordException(exception: Exception, time?: TimeInput): void;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/span_context.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/span_context.d.ts new file mode 100644 index 0000000..f30933a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/span_context.d.ts @@ -0,0 +1,53 @@ +import { TraceState } from './trace_state'; +/** + * A SpanContext represents the portion of a {@link Span} which must be + * serialized and propagated along side of a {@link Baggage}. + */ +export interface SpanContext { + /** + * The ID of the trace that this span belongs to. It is worldwide unique + * with practically sufficient probability by being made as 16 randomly + * generated bytes, encoded as a 32 lowercase hex characters corresponding to + * 128 bits. + */ + traceId: string; + /** + * The ID of the Span. It is globally unique with practically sufficient + * probability by being made as 8 randomly generated bytes, encoded as a 16 + * lowercase hex characters corresponding to 64 bits. + */ + spanId: string; + /** + * Only true if the SpanContext was propagated from a remote parent. + */ + isRemote?: boolean; + /** + * Trace flags to propagate. + * + * It is represented as 1 byte (bitmap). Bit to represent whether trace is + * sampled or not. When set, the least significant bit documents that the + * caller may have recorded trace data. A caller who does not record trace + * data out-of-band leaves this flag unset. + * + * see {@link TraceFlags} for valid flag values. + */ + traceFlags: number; + /** + * Tracing-system-specific info to propagate. + * + * The tracestate field value is a `list` as defined below. The `list` is a + * series of `list-members` separated by commas `,`, and a list-member is a + * key/value pair separated by an equals sign `=`. Spaces and horizontal tabs + * surrounding `list-members` are ignored. There can be a maximum of 32 + * `list-members` in a `list`. + * More Info: https://www.w3.org/TR/trace-context/#tracestate-field + * + * Examples: + * Single tracing system (generic format): + * tracestate: rojo=00f067aa0ba902b7 + * Multiple tracing systems (with different formatting): + * tracestate: rojo=00f067aa0ba902b7,congo=t61rcWkgMzE + */ + traceState?: TraceState; +} +//# sourceMappingURL=span_context.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/span_context.js b/node_modules/@opentelemetry/api/build/esm/trace/span_context.js new file mode 100644 index 0000000..1bb88b0 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/span_context.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=span_context.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/span_context.js.map b/node_modules/@opentelemetry/api/build/esm/trace/span_context.js.map new file mode 100644 index 0000000..dbf0bfe --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/span_context.js.map @@ -0,0 +1 @@ +{"version":3,"file":"span_context.js","sourceRoot":"","sources":["../../../src/trace/span_context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TraceState } from './trace_state';\n\n/**\n * A SpanContext represents the portion of a {@link Span} which must be\n * serialized and propagated along side of a {@link Baggage}.\n */\nexport interface SpanContext {\n /**\n * The ID of the trace that this span belongs to. It is worldwide unique\n * with practically sufficient probability by being made as 16 randomly\n * generated bytes, encoded as a 32 lowercase hex characters corresponding to\n * 128 bits.\n */\n traceId: string;\n /**\n * The ID of the Span. It is globally unique with practically sufficient\n * probability by being made as 8 randomly generated bytes, encoded as a 16\n * lowercase hex characters corresponding to 64 bits.\n */\n spanId: string;\n /**\n * Only true if the SpanContext was propagated from a remote parent.\n */\n isRemote?: boolean;\n /**\n * Trace flags to propagate.\n *\n * It is represented as 1 byte (bitmap). Bit to represent whether trace is\n * sampled or not. When set, the least significant bit documents that the\n * caller may have recorded trace data. A caller who does not record trace\n * data out-of-band leaves this flag unset.\n *\n * see {@link TraceFlags} for valid flag values.\n */\n traceFlags: number;\n /**\n * Tracing-system-specific info to propagate.\n *\n * The tracestate field value is a `list` as defined below. The `list` is a\n * series of `list-members` separated by commas `,`, and a list-member is a\n * key/value pair separated by an equals sign `=`. Spaces and horizontal tabs\n * surrounding `list-members` are ignored. There can be a maximum of 32\n * `list-members` in a `list`.\n * More Info: https://www.w3.org/TR/trace-context/#tracestate-field\n *\n * Examples:\n * Single tracing system (generic format):\n * tracestate: rojo=00f067aa0ba902b7\n * Multiple tracing systems (with different formatting):\n * tracestate: rojo=00f067aa0ba902b7,congo=t61rcWkgMzE\n */\n traceState?: TraceState;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/span_kind.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/span_kind.d.ts new file mode 100644 index 0000000..a89846f --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/span_kind.d.ts @@ -0,0 +1,27 @@ +export declare enum SpanKind { + /** Default value. Indicates that the span is used internally. */ + INTERNAL = 0, + /** + * Indicates that the span covers server-side handling of an RPC or other + * remote request. + */ + SERVER = 1, + /** + * Indicates that the span covers the client-side wrapper around an RPC or + * other remote request. + */ + CLIENT = 2, + /** + * Indicates that the span describes producer sending a message to a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + PRODUCER = 3, + /** + * Indicates that the span describes consumer receiving a message from a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + CONSUMER = 4 +} +//# sourceMappingURL=span_kind.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js b/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js new file mode 100644 index 0000000..1119df9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js @@ -0,0 +1,43 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export var SpanKind; +(function (SpanKind) { + /** Default value. Indicates that the span is used internally. */ + SpanKind[SpanKind["INTERNAL"] = 0] = "INTERNAL"; + /** + * Indicates that the span covers server-side handling of an RPC or other + * remote request. + */ + SpanKind[SpanKind["SERVER"] = 1] = "SERVER"; + /** + * Indicates that the span covers the client-side wrapper around an RPC or + * other remote request. + */ + SpanKind[SpanKind["CLIENT"] = 2] = "CLIENT"; + /** + * Indicates that the span describes producer sending a message to a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + SpanKind[SpanKind["PRODUCER"] = 3] = "PRODUCER"; + /** + * Indicates that the span describes consumer receiving a message from a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + SpanKind[SpanKind["CONSUMER"] = 4] = "CONSUMER"; +})(SpanKind || (SpanKind = {})); +//# sourceMappingURL=span_kind.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js.map b/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js.map new file mode 100644 index 0000000..deb6be7 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js.map @@ -0,0 +1 @@ +{"version":3,"file":"span_kind.js","sourceRoot":"","sources":["../../../src/trace/span_kind.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAN,IAAY,QA6BX;AA7BD,WAAY,QAAQ;IAClB,iEAAiE;IACjE,+CAAY,CAAA;IAEZ;;;OAGG;IACH,2CAAU,CAAA;IAEV;;;OAGG;IACH,2CAAU,CAAA;IAEV;;;;OAIG;IACH,+CAAY,CAAA;IAEZ;;;;OAIG;IACH,+CAAY,CAAA;AACd,CAAC,EA7BW,QAAQ,KAAR,QAAQ,QA6BnB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport enum SpanKind {\n /** Default value. Indicates that the span is used internally. */\n INTERNAL = 0,\n\n /**\n * Indicates that the span covers server-side handling of an RPC or other\n * remote request.\n */\n SERVER = 1,\n\n /**\n * Indicates that the span covers the client-side wrapper around an RPC or\n * other remote request.\n */\n CLIENT = 2,\n\n /**\n * Indicates that the span describes producer sending a message to a\n * broker. Unlike client and server, there is no direct critical path latency\n * relationship between producer and consumer spans.\n */\n PRODUCER = 3,\n\n /**\n * Indicates that the span describes consumer receiving a message from a\n * broker. Unlike client and server, there is no direct critical path latency\n * relationship between producer and consumer spans.\n */\n CONSUMER = 4,\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.d.ts new file mode 100644 index 0000000..f191111 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.d.ts @@ -0,0 +1,17 @@ +import { Span } from './span'; +import { SpanContext } from './span_context'; +export declare function isValidTraceId(traceId: string): boolean; +export declare function isValidSpanId(spanId: string): boolean; +/** + * Returns true if this {@link SpanContext} is valid. + * @return true if this {@link SpanContext} is valid. + */ +export declare function isSpanContextValid(spanContext: SpanContext): boolean; +/** + * Wrap the given {@link SpanContext} in a new non-recording {@link Span} + * + * @param spanContext span context to be wrapped + * @returns a new non-recording {@link Span} with the provided context + */ +export declare function wrapSpanContext(spanContext: SpanContext): Span; +//# sourceMappingURL=spancontext-utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js b/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js new file mode 100644 index 0000000..88545bb --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js @@ -0,0 +1,42 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { INVALID_SPANID, INVALID_TRACEID } from './invalid-span-constants'; +import { NonRecordingSpan } from './NonRecordingSpan'; +var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; +var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; +export function isValidTraceId(traceId) { + return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID; +} +export function isValidSpanId(spanId) { + return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID; +} +/** + * Returns true if this {@link SpanContext} is valid. + * @return true if this {@link SpanContext} is valid. + */ +export function isSpanContextValid(spanContext) { + return (isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)); +} +/** + * Wrap the given {@link SpanContext} in a new non-recording {@link Span} + * + * @param spanContext span context to be wrapped + * @returns a new non-recording {@link Span} with the provided context + */ +export function wrapSpanContext(spanContext) { + return new NonRecordingSpan(spanContext); +} +//# sourceMappingURL=spancontext-utils.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js.map b/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js.map new file mode 100644 index 0000000..a4dc6c2 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"spancontext-utils.js","sourceRoot":"","sources":["../../../src/trace/spancontext-utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAItD,IAAM,mBAAmB,GAAG,mBAAmB,CAAC;AAChD,IAAM,kBAAkB,GAAG,iBAAiB,CAAC;AAE7C,MAAM,UAAU,cAAc,CAAC,OAAe;IAC5C,OAAO,mBAAmB,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,OAAO,KAAK,eAAe,CAAC;AAC1E,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,MAAc;IAC1C,OAAO,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,MAAM,KAAK,cAAc,CAAC;AACtE,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAAC,WAAwB;IACzD,OAAO,CACL,cAAc,CAAC,WAAW,CAAC,OAAO,CAAC,IAAI,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,CACzE,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,eAAe,CAAC,WAAwB;IACtD,OAAO,IAAI,gBAAgB,CAAC,WAAW,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { INVALID_SPANID, INVALID_TRACEID } from './invalid-span-constants';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\n\nconst VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;\nconst VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;\n\nexport function isValidTraceId(traceId: string): boolean {\n return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID;\n}\n\nexport function isValidSpanId(spanId: string): boolean {\n return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID;\n}\n\n/**\n * Returns true if this {@link SpanContext} is valid.\n * @return true if this {@link SpanContext} is valid.\n */\nexport function isSpanContextValid(spanContext: SpanContext): boolean {\n return (\n isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)\n );\n}\n\n/**\n * Wrap the given {@link SpanContext} in a new non-recording {@link Span}\n *\n * @param spanContext span context to be wrapped\n * @returns a new non-recording {@link Span} with the provided context\n */\nexport function wrapSpanContext(spanContext: SpanContext): Span {\n return new NonRecordingSpan(spanContext);\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/status.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/status.d.ts new file mode 100644 index 0000000..ab19a68 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/status.d.ts @@ -0,0 +1,25 @@ +export interface SpanStatus { + /** The status code of this message. */ + code: SpanStatusCode; + /** A developer-facing error message. */ + message?: string; +} +/** + * An enumeration of status codes. + */ +export declare enum SpanStatusCode { + /** + * The default status. + */ + UNSET = 0, + /** + * The operation has been validated by an Application developer or + * Operator to have completed successfully. + */ + OK = 1, + /** + * The operation contains an error. + */ + ERROR = 2 +} +//# sourceMappingURL=status.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/status.js b/node_modules/@opentelemetry/api/build/esm/trace/status.js new file mode 100644 index 0000000..5ee55e4 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/status.js @@ -0,0 +1,20 @@ +/** + * An enumeration of status codes. + */ +export var SpanStatusCode; +(function (SpanStatusCode) { + /** + * The default status. + */ + SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET"; + /** + * The operation has been validated by an Application developer or + * Operator to have completed successfully. + */ + SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK"; + /** + * The operation contains an error. + */ + SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR"; +})(SpanStatusCode || (SpanStatusCode = {})); +//# sourceMappingURL=status.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/status.js.map b/node_modules/@opentelemetry/api/build/esm/trace/status.js.map new file mode 100644 index 0000000..af7e7d7 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/status.js.map @@ -0,0 +1 @@ +{"version":3,"file":"status.js","sourceRoot":"","sources":["../../../src/trace/status.ts"],"names":[],"mappings":"AAsBA;;GAEG;AACH,MAAM,CAAN,IAAY,cAcX;AAdD,WAAY,cAAc;IACxB;;OAEG;IACH,qDAAS,CAAA;IACT;;;OAGG;IACH,+CAAM,CAAA;IACN;;OAEG;IACH,qDAAS,CAAA;AACX,CAAC,EAdW,cAAc,KAAd,cAAc,QAczB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport interface SpanStatus {\n /** The status code of this message. */\n code: SpanStatusCode;\n /** A developer-facing error message. */\n message?: string;\n}\n\n/**\n * An enumeration of status codes.\n */\nexport enum SpanStatusCode {\n /**\n * The default status.\n */\n UNSET = 0,\n /**\n * The operation has been validated by an Application developer or\n * Operator to have completed successfully.\n */\n OK = 1,\n /**\n * The operation contains an error.\n */\n ERROR = 2,\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.d.ts new file mode 100644 index 0000000..11288ba --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.d.ts @@ -0,0 +1,7 @@ +export declare enum TraceFlags { + /** Represents no flag set. */ + NONE = 0, + /** Bit to represent whether trace is sampled in trace flags. */ + SAMPLED = 1 +} +//# sourceMappingURL=trace_flags.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js b/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js new file mode 100644 index 0000000..8a7b000 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js @@ -0,0 +1,23 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export var TraceFlags; +(function (TraceFlags) { + /** Represents no flag set. */ + TraceFlags[TraceFlags["NONE"] = 0] = "NONE"; + /** Bit to represent whether trace is sampled in trace flags. */ + TraceFlags[TraceFlags["SAMPLED"] = 1] = "SAMPLED"; +})(TraceFlags || (TraceFlags = {})); +//# sourceMappingURL=trace_flags.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js.map b/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js.map new file mode 100644 index 0000000..2ea8680 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trace_flags.js","sourceRoot":"","sources":["../../../src/trace/trace_flags.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAN,IAAY,UAKX;AALD,WAAY,UAAU;IACpB,8BAA8B;IAC9B,2CAAU,CAAA;IACV,gEAAgE;IAChE,iDAAkB,CAAA;AACpB,CAAC,EALW,UAAU,KAAV,UAAU,QAKrB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport enum TraceFlags {\n /** Represents no flag set. */\n NONE = 0x0,\n /** Bit to represent whether trace is sampled in trace flags. */\n SAMPLED = 0x1 << 0,\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/trace_state.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/trace_state.d.ts new file mode 100644 index 0000000..f275b8b --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/trace_state.d.ts @@ -0,0 +1,38 @@ +export interface TraceState { + /** + * Create a new TraceState which inherits from this TraceState and has the + * given key set. + * The new entry will always be added in the front of the list of states. + * + * @param key key of the TraceState entry. + * @param value value of the TraceState entry. + */ + set(key: string, value: string): TraceState; + /** + * Return a new TraceState which inherits from this TraceState but does not + * contain the given key. + * + * @param key the key for the TraceState entry to be removed. + */ + unset(key: string): TraceState; + /** + * Returns the value to which the specified key is mapped, or `undefined` if + * this map contains no mapping for the key. + * + * @param key with which the specified value is to be associated. + * @returns the value to which the specified key is mapped, or `undefined` if + * this map contains no mapping for the key. + */ + get(key: string): string | undefined; + /** + * Serializes the TraceState to a `list` as defined below. The `list` is a + * series of `list-members` separated by commas `,`, and a list-member is a + * key/value pair separated by an equals sign `=`. Spaces and horizontal tabs + * surrounding `list-members` are ignored. There can be a maximum of 32 + * `list-members` in a `list`. + * + * @returns the serialized string. + */ + serialize(): string; +} +//# sourceMappingURL=trace_state.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/trace_state.js b/node_modules/@opentelemetry/api/build/esm/trace/trace_state.js new file mode 100644 index 0000000..a6c368f --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/trace_state.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=trace_state.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/trace_state.js.map b/node_modules/@opentelemetry/api/build/esm/trace/trace_state.js.map new file mode 100644 index 0000000..64a3d7a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/trace_state.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trace_state.js","sourceRoot":"","sources":["../../../src/trace/trace_state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface TraceState {\n /**\n * Create a new TraceState which inherits from this TraceState and has the\n * given key set.\n * The new entry will always be added in the front of the list of states.\n *\n * @param key key of the TraceState entry.\n * @param value value of the TraceState entry.\n */\n set(key: string, value: string): TraceState;\n\n /**\n * Return a new TraceState which inherits from this TraceState but does not\n * contain the given key.\n *\n * @param key the key for the TraceState entry to be removed.\n */\n unset(key: string): TraceState;\n\n /**\n * Returns the value to which the specified key is mapped, or `undefined` if\n * this map contains no mapping for the key.\n *\n * @param key with which the specified value is to be associated.\n * @returns the value to which the specified key is mapped, or `undefined` if\n * this map contains no mapping for the key.\n */\n get(key: string): string | undefined;\n\n // TODO: Consider to add support for merging an object as well by also\n // accepting a single internalTraceState argument similar to the constructor.\n\n /**\n * Serializes the TraceState to a `list` as defined below. The `list` is a\n * series of `list-members` separated by commas `,`, and a list-member is a\n * key/value pair separated by an equals sign `=`. Spaces and horizontal tabs\n * surrounding `list-members` are ignored. There can be a maximum of 32\n * `list-members` in a `list`.\n *\n * @returns the serialized string.\n */\n serialize(): string;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/tracer.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/tracer.d.ts new file mode 100644 index 0000000..2509089 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/tracer.d.ts @@ -0,0 +1,71 @@ +import { Context } from '../context/types'; +import { Span } from './span'; +import { SpanOptions } from './SpanOptions'; +/** + * Tracer provides an interface for creating {@link Span}s. + */ +export interface Tracer { + /** + * Starts a new {@link Span}. Start the span without setting it on context. + * + * This method do NOT modify the current Context. + * + * @param name The name of the span + * @param [options] SpanOptions used for span creation + * @param [context] Context to use to extract parent + * @returns Span The newly created span + * @example + * const span = tracer.startSpan('op'); + * span.setAttribute('key', 'value'); + * span.end(); + */ + startSpan(name: string, options?: SpanOptions, context?: Context): Span; + /** + * Starts a new {@link Span} and calls the given function passing it the + * created span as first argument. + * Additionally the new span gets set in context and this context is activated + * for the duration of the function call. + * + * @param name The name of the span + * @param [options] SpanOptions used for span creation + * @param [context] Context to use to extract parent + * @param fn function called in the context of the span and receives the newly created span as an argument + * @returns return value of fn + * @example + * const something = tracer.startActiveSpan('op', span => { + * try { + * do some work + * span.setStatus({code: SpanStatusCode.OK}); + * return something; + * } catch (err) { + * span.setStatus({ + * code: SpanStatusCode.ERROR, + * message: err.message, + * }); + * throw err; + * } finally { + * span.end(); + * } + * }); + * + * @example + * const span = tracer.startActiveSpan('op', span => { + * try { + * do some work + * return span; + * } catch (err) { + * span.setStatus({ + * code: SpanStatusCode.ERROR, + * message: err.message, + * }); + * throw err; + * } + * }); + * do some more work + * span.end(); + */ + startActiveSpan unknown>(name: string, fn: F): ReturnType; + startActiveSpan unknown>(name: string, options: SpanOptions, fn: F): ReturnType; + startActiveSpan unknown>(name: string, options: SpanOptions, context: Context, fn: F): ReturnType; +} +//# sourceMappingURL=tracer.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/tracer.js b/node_modules/@opentelemetry/api/build/esm/trace/tracer.js new file mode 100644 index 0000000..ad066dc --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/tracer.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=tracer.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/tracer.js.map b/node_modules/@opentelemetry/api/build/esm/trace/tracer.js.map new file mode 100644 index 0000000..77f6ae9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/tracer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tracer.js","sourceRoot":"","sources":["../../../src/trace/tracer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport { Span } from './span';\nimport { SpanOptions } from './SpanOptions';\n\n/**\n * Tracer provides an interface for creating {@link Span}s.\n */\nexport interface Tracer {\n /**\n * Starts a new {@link Span}. Start the span without setting it on context.\n *\n * This method do NOT modify the current Context.\n *\n * @param name The name of the span\n * @param [options] SpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @returns Span The newly created span\n * @example\n * const span = tracer.startSpan('op');\n * span.setAttribute('key', 'value');\n * span.end();\n */\n startSpan(name: string, options?: SpanOptions, context?: Context): Span;\n\n /**\n * Starts a new {@link Span} and calls the given function passing it the\n * created span as first argument.\n * Additionally the new span gets set in context and this context is activated\n * for the duration of the function call.\n *\n * @param name The name of the span\n * @param [options] SpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns return value of fn\n * @example\n * const something = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * span.setStatus({code: SpanStatusCode.OK});\n * return something;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * } finally {\n * span.end();\n * }\n * });\n *\n * @example\n * const span = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * return span;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * }\n * });\n * do some more work\n * span.end();\n */\n startActiveSpan unknown>(\n name: string,\n fn: F\n ): ReturnType;\n startActiveSpan unknown>(\n name: string,\n options: SpanOptions,\n fn: F\n ): ReturnType;\n startActiveSpan unknown>(\n name: string,\n options: SpanOptions,\n context: Context,\n fn: F\n ): ReturnType;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/tracer_options.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/tracer_options.d.ts new file mode 100644 index 0000000..f3bbccf --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/tracer_options.d.ts @@ -0,0 +1,10 @@ +/** + * An interface describes additional metadata of a tracer. + */ +export interface TracerOptions { + /** + * The schemaUrl of the tracer or instrumentation library + */ + schemaUrl?: string; +} +//# sourceMappingURL=tracer_options.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/tracer_options.js b/node_modules/@opentelemetry/api/build/esm/trace/tracer_options.js new file mode 100644 index 0000000..470a3a7 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/tracer_options.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=tracer_options.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/tracer_options.js.map b/node_modules/@opentelemetry/api/build/esm/trace/tracer_options.js.map new file mode 100644 index 0000000..70365af --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/tracer_options.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tracer_options.js","sourceRoot":"","sources":["../../../src/trace/tracer_options.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An interface describes additional metadata of a tracer.\n */\nexport interface TracerOptions {\n /**\n * The schemaUrl of the tracer or instrumentation library\n */\n schemaUrl?: string;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/tracer_provider.d.ts b/node_modules/@opentelemetry/api/build/esm/trace/tracer_provider.d.ts new file mode 100644 index 0000000..9b2f7a9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/tracer_provider.d.ts @@ -0,0 +1,21 @@ +import { Tracer } from './tracer'; +import { TracerOptions } from './tracer_options'; +/** + * A registry for creating named {@link Tracer}s. + */ +export interface TracerProvider { + /** + * Returns a Tracer, creating one if one with the given name and version is + * not already created. + * + * This function may return different Tracer types (e.g. + * {@link NoopTracerProvider} vs. a functional tracer). + * + * @param name The name of the tracer or instrumentation library. + * @param version The version of the tracer or instrumentation library. + * @param options The options of the tracer or instrumentation library. + * @returns Tracer A Tracer with the given name and version + */ + getTracer(name: string, version?: string, options?: TracerOptions): Tracer; +} +//# sourceMappingURL=tracer_provider.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/tracer_provider.js b/node_modules/@opentelemetry/api/build/esm/trace/tracer_provider.js new file mode 100644 index 0000000..adf432a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/tracer_provider.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=tracer_provider.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/trace/tracer_provider.js.map b/node_modules/@opentelemetry/api/build/esm/trace/tracer_provider.js.map new file mode 100644 index 0000000..bfc1cbd --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/trace/tracer_provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tracer_provider.js","sourceRoot":"","sources":["../../../src/trace/tracer_provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Tracer } from './tracer';\nimport { TracerOptions } from './tracer_options';\n\n/**\n * A registry for creating named {@link Tracer}s.\n */\nexport interface TracerProvider {\n /**\n * Returns a Tracer, creating one if one with the given name and version is\n * not already created.\n *\n * This function may return different Tracer types (e.g.\n * {@link NoopTracerProvider} vs. a functional tracer).\n *\n * @param name The name of the tracer or instrumentation library.\n * @param version The version of the tracer or instrumentation library.\n * @param options The options of the tracer or instrumentation library.\n * @returns Tracer A Tracer with the given name and version\n */\n getTracer(name: string, version?: string, options?: TracerOptions): Tracer;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/version.d.ts b/node_modules/@opentelemetry/api/build/esm/version.d.ts new file mode 100644 index 0000000..40f0365 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/version.d.ts @@ -0,0 +1,2 @@ +export declare const VERSION = "1.9.0"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/version.js b/node_modules/@opentelemetry/api/build/esm/version.js new file mode 100644 index 0000000..b0e29e5 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/version.js @@ -0,0 +1,18 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// this is autogenerated file, see scripts/version-update.js +export var VERSION = '1.9.0'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esm/version.js.map b/node_modules/@opentelemetry/api/build/esm/version.js.map new file mode 100644 index 0000000..36b10eb --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esm/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,4DAA4D;AAC5D,MAAM,CAAC,IAAM,OAAO,GAAG,OAAO,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.9.0';\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/api/context.d.ts b/node_modules/@opentelemetry/api/build/esnext/api/context.d.ts new file mode 100644 index 0000000..61caee8 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/api/context.d.ts @@ -0,0 +1,41 @@ +import { Context, ContextManager } from '../context/types'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Context API + */ +export declare class ContextAPI { + private static _instance?; + /** Empty private constructor prevents end users from constructing a new instance of the API */ + private constructor(); + /** Get the singleton instance of the Context API */ + static getInstance(): ContextAPI; + /** + * Set the current context manager. + * + * @returns true if the context manager was successfully registered, else false + */ + setGlobalContextManager(contextManager: ContextManager): boolean; + /** + * Get the currently active context + */ + active(): Context; + /** + * Execute a function with an active context + * + * @param context context to be active during function execution + * @param fn function to execute in a context + * @param thisArg optional receiver to be used for calling fn + * @param args optional arguments forwarded to fn + */ + with ReturnType>(context: Context, fn: F, thisArg?: ThisParameterType, ...args: A): ReturnType; + /** + * Bind a context to a target function or event emitter + * + * @param context context to bind to the event emitter or function. Defaults to the currently active context + * @param target function or event emitter to bind + */ + bind(context: Context, target: T): T; + private _getContextManager; + /** Disable and remove the global context manager */ + disable(): void; +} +//# sourceMappingURL=context.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/api/context.js b/node_modules/@opentelemetry/api/build/esnext/api/context.js new file mode 100644 index 0000000..c672a41 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/api/context.js @@ -0,0 +1,77 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NoopContextManager } from '../context/NoopContextManager'; +import { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils'; +import { DiagAPI } from './diag'; +const API_NAME = 'context'; +const NOOP_CONTEXT_MANAGER = new NoopContextManager(); +/** + * Singleton object which represents the entry point to the OpenTelemetry Context API + */ +export class ContextAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { } + /** Get the singleton instance of the Context API */ + static getInstance() { + if (!this._instance) { + this._instance = new ContextAPI(); + } + return this._instance; + } + /** + * Set the current context manager. + * + * @returns true if the context manager was successfully registered, else false + */ + setGlobalContextManager(contextManager) { + return registerGlobal(API_NAME, contextManager, DiagAPI.instance()); + } + /** + * Get the currently active context + */ + active() { + return this._getContextManager().active(); + } + /** + * Execute a function with an active context + * + * @param context context to be active during function execution + * @param fn function to execute in a context + * @param thisArg optional receiver to be used for calling fn + * @param args optional arguments forwarded to fn + */ + with(context, fn, thisArg, ...args) { + return this._getContextManager().with(context, fn, thisArg, ...args); + } + /** + * Bind a context to a target function or event emitter + * + * @param context context to bind to the event emitter or function. Defaults to the currently active context + * @param target function or event emitter to bind + */ + bind(context, target) { + return this._getContextManager().bind(context, target); + } + _getContextManager() { + return getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER; + } + /** Disable and remove the global context manager */ + disable() { + this._getContextManager().disable(); + unregisterGlobal(API_NAME, DiagAPI.instance()); + } +} +//# sourceMappingURL=context.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/api/context.js.map b/node_modules/@opentelemetry/api/build/esnext/api/context.js.map new file mode 100644 index 0000000..5ad9a01 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/api/context.js.map @@ -0,0 +1 @@ +{"version":3,"file":"context.js","sourceRoot":"","sources":["../../../src/api/context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAEnE,OAAO,EACL,SAAS,EACT,cAAc,EACd,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAEjC,MAAM,QAAQ,GAAG,SAAS,CAAC;AAC3B,MAAM,oBAAoB,GAAG,IAAI,kBAAkB,EAAE,CAAC;AAEtD;;GAEG;AACH,MAAM,OAAO,UAAU;IAGrB,+FAA+F;IAC/F,gBAAuB,CAAC;IAExB,oDAAoD;IAC7C,MAAM,CAAC,WAAW;QACvB,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;YACnB,IAAI,CAAC,SAAS,GAAG,IAAI,UAAU,EAAE,CAAC;SACnC;QAED,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAED;;;;OAIG;IACI,uBAAuB,CAAC,cAA8B;QAC3D,OAAO,cAAc,CAAC,QAAQ,EAAE,cAAc,EAAE,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;IACtE,CAAC;IAED;;OAEG;IACI,MAAM;QACX,OAAO,IAAI,CAAC,kBAAkB,EAAE,CAAC,MAAM,EAAE,CAAC;IAC5C,CAAC;IAED;;;;;;;OAOG;IACI,IAAI,CACT,OAAgB,EAChB,EAAK,EACL,OAA8B,EAC9B,GAAG,IAAO;QAEV,OAAO,IAAI,CAAC,kBAAkB,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC,CAAC;IACvE,CAAC;IAED;;;;;OAKG;IACI,IAAI,CAAI,OAAgB,EAAE,MAAS;QACxC,OAAO,IAAI,CAAC,kBAAkB,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IACzD,CAAC;IAEO,kBAAkB;QACxB,OAAO,SAAS,CAAC,QAAQ,CAAC,IAAI,oBAAoB,CAAC;IACrD,CAAC;IAED,oDAAoD;IAC7C,OAAO;QACZ,IAAI,CAAC,kBAAkB,EAAE,CAAC,OAAO,EAAE,CAAC;QACpC,gBAAgB,CAAC,QAAQ,EAAE,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;IACjD,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NoopContextManager } from '../context/NoopContextManager';\nimport { Context, ContextManager } from '../context/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'context';\nconst NOOP_CONTEXT_MANAGER = new NoopContextManager();\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Context API\n */\nexport class ContextAPI {\n private static _instance?: ContextAPI;\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Context API */\n public static getInstance(): ContextAPI {\n if (!this._instance) {\n this._instance = new ContextAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current context manager.\n *\n * @returns true if the context manager was successfully registered, else false\n */\n public setGlobalContextManager(contextManager: ContextManager): boolean {\n return registerGlobal(API_NAME, contextManager, DiagAPI.instance());\n }\n\n /**\n * Get the currently active context\n */\n public active(): Context {\n return this._getContextManager().active();\n }\n\n /**\n * Execute a function with an active context\n *\n * @param context context to be active during function execution\n * @param fn function to execute in a context\n * @param thisArg optional receiver to be used for calling fn\n * @param args optional arguments forwarded to fn\n */\n public with ReturnType>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType,\n ...args: A\n ): ReturnType {\n return this._getContextManager().with(context, fn, thisArg, ...args);\n }\n\n /**\n * Bind a context to a target function or event emitter\n *\n * @param context context to bind to the event emitter or function. Defaults to the currently active context\n * @param target function or event emitter to bind\n */\n public bind(context: Context, target: T): T {\n return this._getContextManager().bind(context, target);\n }\n\n private _getContextManager(): ContextManager {\n return getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER;\n }\n\n /** Disable and remove the global context manager */\n public disable() {\n this._getContextManager().disable();\n unregisterGlobal(API_NAME, DiagAPI.instance());\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/api/diag.d.ts b/node_modules/@opentelemetry/api/build/esnext/api/diag.d.ts new file mode 100644 index 0000000..131db17 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/api/diag.d.ts @@ -0,0 +1,30 @@ +import { ComponentLoggerOptions, DiagLogFunction, DiagLogger, DiagLoggerApi } from '../diag/types'; +/** + * Singleton object which represents the entry point to the OpenTelemetry internal + * diagnostic API + */ +export declare class DiagAPI implements DiagLogger, DiagLoggerApi { + private static _instance?; + /** Get the singleton instance of the DiagAPI API */ + static instance(): DiagAPI; + /** + * Private internal constructor + * @private + */ + private constructor(); + setLogger: DiagLoggerApi['setLogger']; + /** + * + */ + createComponentLogger: (options: ComponentLoggerOptions) => DiagLogger; + verbose: DiagLogFunction; + debug: DiagLogFunction; + info: DiagLogFunction; + warn: DiagLogFunction; + error: DiagLogFunction; + /** + * Unregister the global logger and return to Noop + */ + disable: () => void; +} +//# sourceMappingURL=diag.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/api/diag.js b/node_modules/@opentelemetry/api/build/esnext/api/diag.js new file mode 100644 index 0000000..8798a39 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/api/diag.js @@ -0,0 +1,89 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DiagComponentLogger } from '../diag/ComponentLogger'; +import { createLogLevelDiagLogger } from '../diag/internal/logLevelLogger'; +import { DiagLogLevel, } from '../diag/types'; +import { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils'; +const API_NAME = 'diag'; +/** + * Singleton object which represents the entry point to the OpenTelemetry internal + * diagnostic API + */ +export class DiagAPI { + /** + * Private internal constructor + * @private + */ + constructor() { + function _logProxy(funcName) { + return function (...args) { + const logger = getGlobal('diag'); + // shortcut if logger not set + if (!logger) + return; + return logger[funcName](...args); + }; + } + // Using self local variable for minification purposes as 'this' cannot be minified + const self = this; + // DiagAPI specific functions + const setLogger = (logger, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => { + var _a, _b, _c; + if (logger === self) { + // There isn't much we can do here. + // Logging to the console might break the user application. + // Try to log to self. If a logger was previously registered it will receive the log. + const err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); + self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message); + return false; + } + if (typeof optionsOrLogLevel === 'number') { + optionsOrLogLevel = { + logLevel: optionsOrLogLevel, + }; + } + const oldLogger = getGlobal('diag'); + const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger); + // There already is an logger registered. We'll let it know before overwriting it. + if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { + const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ''; + oldLogger.warn(`Current logger will be overwritten from ${stack}`); + newLogger.warn(`Current logger will overwrite one already registered from ${stack}`); + } + return registerGlobal('diag', newLogger, self, true); + }; + self.setLogger = setLogger; + self.disable = () => { + unregisterGlobal(API_NAME, self); + }; + self.createComponentLogger = (options) => { + return new DiagComponentLogger(options); + }; + self.verbose = _logProxy('verbose'); + self.debug = _logProxy('debug'); + self.info = _logProxy('info'); + self.warn = _logProxy('warn'); + self.error = _logProxy('error'); + } + /** Get the singleton instance of the DiagAPI API */ + static instance() { + if (!this._instance) { + this._instance = new DiagAPI(); + } + return this._instance; + } +} +//# sourceMappingURL=diag.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/api/diag.js.map b/node_modules/@opentelemetry/api/build/esnext/api/diag.js.map new file mode 100644 index 0000000..448d05c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/api/diag.js.map @@ -0,0 +1 @@ +{"version":3,"file":"diag.js","sourceRoot":"","sources":["../../../src/api/diag.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAC9D,OAAO,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AAC3E,OAAO,EAKL,YAAY,GACb,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,SAAS,EACT,cAAc,EACd,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAElC,MAAM,QAAQ,GAAG,MAAM,CAAC;AAExB;;;GAGG;AACH,MAAM,OAAO,OAAO;IAYlB;;;OAGG;IACH;QACE,SAAS,SAAS,CAAC,QAA0B;YAC3C,OAAO,UAAU,GAAG,IAAI;gBACtB,MAAM,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;gBACjC,6BAA6B;gBAC7B,IAAI,CAAC,MAAM;oBAAE,OAAO;gBACpB,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;YACnC,CAAC,CAAC;QACJ,CAAC;QAED,mFAAmF;QACnF,MAAM,IAAI,GAAG,IAAI,CAAC;QAElB,6BAA6B;QAE7B,MAAM,SAAS,GAA+B,CAC5C,MAAM,EACN,iBAAiB,GAAG,EAAE,QAAQ,EAAE,YAAY,CAAC,IAAI,EAAE,EACnD,EAAE;;YACF,IAAI,MAAM,KAAK,IAAI,EAAE;gBACnB,mCAAmC;gBACnC,2DAA2D;gBAC3D,qFAAqF;gBACrF,MAAM,GAAG,GAAG,IAAI,KAAK,CACnB,oIAAoI,CACrI,CAAC;gBACF,IAAI,CAAC,KAAK,CAAC,MAAA,GAAG,CAAC,KAAK,m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S,CAAC,MAAM,CAAC,CAAC;QAC9B,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;IAClC,CAAC;IAjFD,oDAAoD;IAC7C,MAAM,CAAC,QAAQ;QACpB,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;YACnB,IAAI,CAAC,SAAS,GAAG,IAAI,OAAO,EAAE,CAAC;SAChC;QAED,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;CA+FF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagComponentLogger } from '../diag/ComponentLogger';\nimport { createLogLevelDiagLogger } from '../diag/internal/logLevelLogger';\nimport {\n ComponentLoggerOptions,\n DiagLogFunction,\n DiagLogger,\n DiagLoggerApi,\n DiagLogLevel,\n} from '../diag/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\n\nconst API_NAME = 'diag';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry internal\n * diagnostic API\n */\nexport class DiagAPI implements DiagLogger, DiagLoggerApi {\n private static _instance?: DiagAPI;\n\n /** Get the singleton instance of the DiagAPI API */\n public static instance(): DiagAPI {\n if (!this._instance) {\n this._instance = new DiagAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Private internal constructor\n * @private\n */\n private constructor() {\n function _logProxy(funcName: keyof DiagLogger): DiagLogFunction {\n return function (...args) {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) return;\n return logger[funcName](...args);\n };\n }\n\n // Using self local variable for minification purposes as 'this' cannot be minified\n const self = this;\n\n // DiagAPI specific functions\n\n const setLogger: DiagLoggerApi['setLogger'] = (\n logger,\n optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }\n ) => {\n if (logger === self) {\n // There isn't much we can do here.\n // Logging to the console might break the user application.\n // Try to log to self. If a logger was previously registered it will receive the log.\n const err = new Error(\n 'Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'\n );\n self.error(err.stack ?? err.message);\n return false;\n }\n\n if (typeof optionsOrLogLevel === 'number') {\n optionsOrLogLevel = {\n logLevel: optionsOrLogLevel,\n };\n }\n\n const oldLogger = getGlobal('diag');\n const newLogger = createLogLevelDiagLogger(\n optionsOrLogLevel.logLevel ?? DiagLogLevel.INFO,\n logger\n );\n // There already is an logger registered. We'll let it know before overwriting it.\n if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {\n const stack = new Error().stack ?? '';\n oldLogger.warn(`Current logger will be overwritten from ${stack}`);\n newLogger.warn(\n `Current logger will overwrite one already registered from ${stack}`\n );\n }\n\n return registerGlobal('diag', newLogger, self, true);\n };\n\n self.setLogger = setLogger;\n\n self.disable = () => {\n unregisterGlobal(API_NAME, self);\n };\n\n self.createComponentLogger = (options: ComponentLoggerOptions) => {\n return new DiagComponentLogger(options);\n };\n\n self.verbose = _logProxy('verbose');\n self.debug = _logProxy('debug');\n self.info = _logProxy('info');\n self.warn = _logProxy('warn');\n self.error = _logProxy('error');\n }\n\n public setLogger!: DiagLoggerApi['setLogger'];\n /**\n *\n */\n public createComponentLogger!: (\n options: ComponentLoggerOptions\n ) => DiagLogger;\n\n // DiagLogger implementation\n public verbose!: DiagLogFunction;\n public debug!: DiagLogFunction;\n public info!: DiagLogFunction;\n public warn!: DiagLogFunction;\n public error!: DiagLogFunction;\n\n /**\n * Unregister the global logger and return to Noop\n */\n public disable!: () => void;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/api/metrics.d.ts b/node_modules/@opentelemetry/api/build/esnext/api/metrics.d.ts new file mode 100644 index 0000000..5adc145 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/api/metrics.d.ts @@ -0,0 +1,28 @@ +import { Meter, MeterOptions } from '../metrics/Meter'; +import { MeterProvider } from '../metrics/MeterProvider'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Metrics API + */ +export declare class MetricsAPI { + private static _instance?; + /** Empty private constructor prevents end users from constructing a new instance of the API */ + private constructor(); + /** Get the singleton instance of the Metrics API */ + static getInstance(): MetricsAPI; + /** + * Set the current global meter provider. + * Returns true if the meter provider was successfully registered, else false. + */ + setGlobalMeterProvider(provider: MeterProvider): boolean; + /** + * Returns the global meter provider. + */ + getMeterProvider(): MeterProvider; + /** + * Returns a meter from the global meter provider. + */ + getMeter(name: string, version?: string, options?: MeterOptions): Meter; + /** Remove the global meter provider */ + disable(): void; +} +//# sourceMappingURL=metrics.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/api/metrics.js b/node_modules/@opentelemetry/api/build/esnext/api/metrics.js new file mode 100644 index 0000000..7864926 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/api/metrics.js @@ -0,0 +1,57 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NOOP_METER_PROVIDER } from '../metrics/NoopMeterProvider'; +import { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils'; +import { DiagAPI } from './diag'; +const API_NAME = 'metrics'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Metrics API + */ +export class MetricsAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { } + /** Get the singleton instance of the Metrics API */ + static getInstance() { + if (!this._instance) { + this._instance = new MetricsAPI(); + } + return this._instance; + } + /** + * Set the current global meter provider. + * Returns true if the meter provider was successfully registered, else false. + */ + setGlobalMeterProvider(provider) { + return registerGlobal(API_NAME, provider, DiagAPI.instance()); + } + /** + * Returns the global meter provider. + */ + getMeterProvider() { + return getGlobal(API_NAME) || NOOP_METER_PROVIDER; + } + /** + * Returns a meter from the global meter provider. + */ + getMeter(name, version, options) { + return this.getMeterProvider().getMeter(name, version, options); + } + /** Remove the global meter provider */ + disable() { + unregisterGlobal(API_NAME, DiagAPI.instance()); + } +} +//# sourceMappingURL=metrics.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/api/metrics.js.map b/node_modules/@opentelemetry/api/build/esnext/api/metrics.js.map new file mode 100644 index 0000000..03c2872 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/api/metrics.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metrics.js","sourceRoot":"","sources":["../../../src/api/metrics.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EACL,SAAS,EACT,cAAc,EACd,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAEjC,MAAM,QAAQ,GAAG,SAAS,CAAC;AAE3B;;GAEG;AACH,MAAM,OAAO,UAAU;IAGrB,+FAA+F;IAC/F,gBAAuB,CAAC;IAExB,oDAAoD;IAC7C,MAAM,CAAC,WAAW;QACvB,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;YACnB,IAAI,CAAC,SAAS,GAAG,IAAI,UAAU,EAAE,CAAC;SACnC;QAED,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAED;;;OAGG;IACI,sBAAsB,CAAC,QAAuB;QACnD,OAAO,cAAc,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;IAChE,CAAC;IAED;;OAEG;IACI,gBAAgB;QACrB,OAAO,SAAS,CAAC,QAAQ,CAAC,IAAI,mBAAmB,CAAC;IACpD,CAAC;IAED;;OAEG;IACI,QAAQ,CACb,IAAY,EACZ,OAAgB,EAChB,OAAsB;QAEtB,OAAO,IAAI,CAAC,gBAAgB,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;IAED,uCAAuC;IAChC,OAAO;QACZ,gBAAgB,CAAC,QAAQ,EAAE,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;IACjD,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Meter, MeterOptions } from '../metrics/Meter';\nimport { MeterProvider } from '../metrics/MeterProvider';\nimport { NOOP_METER_PROVIDER } from '../metrics/NoopMeterProvider';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'metrics';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Metrics API\n */\nexport class MetricsAPI {\n private static _instance?: MetricsAPI;\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Metrics API */\n public static getInstance(): MetricsAPI {\n if (!this._instance) {\n this._instance = new MetricsAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current global meter provider.\n * Returns true if the meter provider was successfully registered, else false.\n */\n public setGlobalMeterProvider(provider: MeterProvider): boolean {\n return registerGlobal(API_NAME, provider, DiagAPI.instance());\n }\n\n /**\n * Returns the global meter provider.\n */\n public getMeterProvider(): MeterProvider {\n return getGlobal(API_NAME) || NOOP_METER_PROVIDER;\n }\n\n /**\n * Returns a meter from the global meter provider.\n */\n public getMeter(\n name: string,\n version?: string,\n options?: MeterOptions\n ): Meter {\n return this.getMeterProvider().getMeter(name, version, options);\n }\n\n /** Remove the global meter provider */\n public disable(): void {\n unregisterGlobal(API_NAME, DiagAPI.instance());\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/api/propagation.d.ts b/node_modules/@opentelemetry/api/build/esnext/api/propagation.d.ts new file mode 100644 index 0000000..a22d24d --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/api/propagation.d.ts @@ -0,0 +1,49 @@ +import { Context } from '../context/types'; +import { TextMapGetter, TextMapPropagator, TextMapSetter } from '../propagation/TextMapPropagator'; +import { getBaggage, getActiveBaggage, setBaggage, deleteBaggage } from '../baggage/context-helpers'; +import { createBaggage } from '../baggage/utils'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Propagation API + */ +export declare class PropagationAPI { + private static _instance?; + /** Empty private constructor prevents end users from constructing a new instance of the API */ + private constructor(); + /** Get the singleton instance of the Propagator API */ + static getInstance(): PropagationAPI; + /** + * Set the current propagator. + * + * @returns true if the propagator was successfully registered, else false + */ + setGlobalPropagator(propagator: TextMapPropagator): boolean; + /** + * Inject context into a carrier to be propagated inter-process + * + * @param context Context carrying tracing data to inject + * @param carrier carrier to inject context into + * @param setter Function used to set values on the carrier + */ + inject(context: Context, carrier: Carrier, setter?: TextMapSetter): void; + /** + * Extract context from a carrier + * + * @param context Context which the newly created context will inherit from + * @param carrier Carrier to extract context from + * @param getter Function used to extract keys from a carrier + */ + extract(context: Context, carrier: Carrier, getter?: TextMapGetter): Context; + /** + * Return a list of all fields which may be used by the propagator. + */ + fields(): string[]; + /** Remove the global propagator */ + disable(): void; + createBaggage: typeof createBaggage; + getBaggage: typeof getBaggage; + getActiveBaggage: typeof getActiveBaggage; + setBaggage: typeof setBaggage; + deleteBaggage: typeof deleteBaggage; + private _getGlobalPropagator; +} +//# sourceMappingURL=propagation.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/api/propagation.js b/node_modules/@opentelemetry/api/build/esnext/api/propagation.js new file mode 100644 index 0000000..93507eb --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/api/propagation.js @@ -0,0 +1,85 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils'; +import { NoopTextMapPropagator } from '../propagation/NoopTextMapPropagator'; +import { defaultTextMapGetter, defaultTextMapSetter, } from '../propagation/TextMapPropagator'; +import { getBaggage, getActiveBaggage, setBaggage, deleteBaggage, } from '../baggage/context-helpers'; +import { createBaggage } from '../baggage/utils'; +import { DiagAPI } from './diag'; +const API_NAME = 'propagation'; +const NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator(); +/** + * Singleton object which represents the entry point to the OpenTelemetry Propagation API + */ +export class PropagationAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + this.createBaggage = createBaggage; + this.getBaggage = getBaggage; + this.getActiveBaggage = getActiveBaggage; + this.setBaggage = setBaggage; + this.deleteBaggage = deleteBaggage; + } + /** Get the singleton instance of the Propagator API */ + static getInstance() { + if (!this._instance) { + this._instance = new PropagationAPI(); + } + return this._instance; + } + /** + * Set the current propagator. + * + * @returns true if the propagator was successfully registered, else false + */ + setGlobalPropagator(propagator) { + return registerGlobal(API_NAME, propagator, DiagAPI.instance()); + } + /** + * Inject context into a carrier to be propagated inter-process + * + * @param context Context carrying tracing data to inject + * @param carrier carrier to inject context into + * @param setter Function used to set values on the carrier + */ + inject(context, carrier, setter = defaultTextMapSetter) { + return this._getGlobalPropagator().inject(context, carrier, setter); + } + /** + * Extract context from a carrier + * + * @param context Context which the newly created context will inherit from + * @param carrier Carrier to extract context from + * @param getter Function used to extract keys from a carrier + */ + extract(context, carrier, getter = defaultTextMapGetter) { + return this._getGlobalPropagator().extract(context, carrier, getter); + } + /** + * Return a list of all fields which may be used by the propagator. + */ + fields() { + return this._getGlobalPropagator().fields(); + } + /** Remove the global propagator */ + disable() { + unregisterGlobal(API_NAME, DiagAPI.instance()); + } + _getGlobalPropagator() { + return getGlobal(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; + } +} +//# sourceMappingURL=propagation.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/api/propagation.js.map b/node_modules/@opentelemetry/api/build/esnext/api/propagation.js.map new file mode 100644 index 0000000..a0673fe --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/api/propagation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"propagation.js","sourceRoot":"","sources":["../../../src/api/propagation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EACL,SAAS,EACT,cAAc,EACd,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EACL,oBAAoB,EACpB,oBAAoB,GAIrB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,UAAU,EACV,gBAAgB,EAChB,UAAU,EACV,aAAa,GACd,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,M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,CAAC;IACjD,CAAC;IAYO,oBAAoB;QAC1B,OAAO,SAAS,CAAC,QAAQ,CAAC,IAAI,wBAAwB,CAAC;IACzD,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { NoopTextMapPropagator } from '../propagation/NoopTextMapPropagator';\nimport {\n defaultTextMapGetter,\n defaultTextMapSetter,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n} from '../propagation/TextMapPropagator';\nimport {\n getBaggage,\n getActiveBaggage,\n setBaggage,\n deleteBaggage,\n} from '../baggage/context-helpers';\nimport { createBaggage } from '../baggage/utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'propagation';\nconst NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator();\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Propagation API\n */\nexport class PropagationAPI {\n private static _instance?: PropagationAPI;\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Propagator API */\n public static getInstance(): PropagationAPI {\n if (!this._instance) {\n this._instance = new PropagationAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current propagator.\n *\n * @returns true if the propagator was successfully registered, else false\n */\n public setGlobalPropagator(propagator: TextMapPropagator): boolean {\n return registerGlobal(API_NAME, propagator, DiagAPI.instance());\n }\n\n /**\n * Inject context into a carrier to be propagated inter-process\n *\n * @param context Context carrying tracing data to inject\n * @param carrier carrier to inject context into\n * @param setter Function used to set values on the carrier\n */\n public inject(\n context: Context,\n carrier: Carrier,\n setter: TextMapSetter = defaultTextMapSetter\n ): void {\n return this._getGlobalPropagator().inject(context, carrier, setter);\n }\n\n /**\n * Extract context from a carrier\n *\n * @param context Context which the newly created context will inherit from\n * @param carrier Carrier to extract context from\n * @param getter Function used to extract keys from a carrier\n */\n public extract(\n context: Context,\n carrier: Carrier,\n getter: TextMapGetter = defaultTextMapGetter\n ): Context {\n return this._getGlobalPropagator().extract(context, carrier, getter);\n }\n\n /**\n * Return a list of all fields which may be used by the propagator.\n */\n public fields(): string[] {\n return this._getGlobalPropagator().fields();\n }\n\n /** Remove the global propagator */\n public disable() {\n unregisterGlobal(API_NAME, DiagAPI.instance());\n }\n\n public createBaggage = createBaggage;\n\n public getBaggage = getBaggage;\n\n public getActiveBaggage = getActiveBaggage;\n\n public setBaggage = setBaggage;\n\n public deleteBaggage = deleteBaggage;\n\n private _getGlobalPropagator(): TextMapPropagator {\n return getGlobal(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR;\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/api/trace.d.ts b/node_modules/@opentelemetry/api/build/esnext/api/trace.d.ts new file mode 100644 index 0000000..df59fd2 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/api/trace.d.ts @@ -0,0 +1,40 @@ +import { isSpanContextValid, wrapSpanContext } from '../trace/spancontext-utils'; +import { Tracer } from '../trace/tracer'; +import { TracerProvider } from '../trace/tracer_provider'; +import { deleteSpan, getActiveSpan, getSpan, getSpanContext, setSpan, setSpanContext } from '../trace/context-utils'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Tracing API + */ +export declare class TraceAPI { + private static _instance?; + private _proxyTracerProvider; + /** Empty private constructor prevents end users from constructing a new instance of the API */ + private constructor(); + /** Get the singleton instance of the Trace API */ + static getInstance(): TraceAPI; + /** + * Set the current global tracer. + * + * @returns true if the tracer provider was successfully registered, else false + */ + setGlobalTracerProvider(provider: TracerProvider): boolean; + /** + * Returns the global tracer provider. + */ + getTracerProvider(): TracerProvider; + /** + * Returns a tracer from the global tracer provider. + */ + getTracer(name: string, version?: string): Tracer; + /** Remove the global tracer provider */ + disable(): void; + wrapSpanContext: typeof wrapSpanContext; + isSpanContextValid: typeof isSpanContextValid; + deleteSpan: typeof deleteSpan; + getSpan: typeof getSpan; + getActiveSpan: typeof getActiveSpan; + getSpanContext: typeof getSpanContext; + setSpan: typeof setSpan; + setSpanContext: typeof setSpanContext; +} +//# sourceMappingURL=trace.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/api/trace.js b/node_modules/@opentelemetry/api/build/esnext/api/trace.js new file mode 100644 index 0000000..6003620 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/api/trace.js @@ -0,0 +1,75 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils'; +import { ProxyTracerProvider } from '../trace/ProxyTracerProvider'; +import { isSpanContextValid, wrapSpanContext, } from '../trace/spancontext-utils'; +import { deleteSpan, getActiveSpan, getSpan, getSpanContext, setSpan, setSpanContext, } from '../trace/context-utils'; +import { DiagAPI } from './diag'; +const API_NAME = 'trace'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Tracing API + */ +export class TraceAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + this._proxyTracerProvider = new ProxyTracerProvider(); + this.wrapSpanContext = wrapSpanContext; + this.isSpanContextValid = isSpanContextValid; + this.deleteSpan = deleteSpan; + this.getSpan = getSpan; + this.getActiveSpan = getActiveSpan; + this.getSpanContext = getSpanContext; + this.setSpan = setSpan; + this.setSpanContext = setSpanContext; + } + /** Get the singleton instance of the Trace API */ + static getInstance() { + if (!this._instance) { + this._instance = new TraceAPI(); + } + return this._instance; + } + /** + * Set the current global tracer. + * + * @returns true if the tracer provider was successfully registered, else false + */ + setGlobalTracerProvider(provider) { + const success = registerGlobal(API_NAME, this._proxyTracerProvider, DiagAPI.instance()); + if (success) { + this._proxyTracerProvider.setDelegate(provider); + } + return success; + } + /** + * Returns the global tracer provider. + */ + getTracerProvider() { + return getGlobal(API_NAME) || this._proxyTracerProvider; + } + /** + * Returns a tracer from the global tracer provider. + */ + getTracer(name, version) { + return this.getTracerProvider().getTracer(name, version); + } + /** Remove the global tracer provider */ + disable() { + unregisterGlobal(API_NAME, DiagAPI.instance()); + this._proxyTracerProvider = new ProxyTracerProvider(); + } +} +//# sourceMappingURL=trace.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/api/trace.js.map b/node_modules/@opentelemetry/api/build/esnext/api/trace.js.map new file mode 100644 index 0000000..1521877 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/api/trace.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trace.js","sourceRoot":"","sources":["../../../src/api/trace.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EACL,SAAS,EACT,cAAc,EACd,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EACL,kBAAkB,EAClB,eAAe,GAChB,MAAM,4BAA4B,CAAC;AAGpC,OAAO,EACL,UAAU,EACV,aAAa,EACb,OAAO,EACP,cAAc,EACd,OAAO,EACP,cAAc,GACf,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAEjC,MAAM,QAAQ,GAAG,OAAO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AAoB,GAAG,IAAI,mBAAmB,EAAE,CAAC;IACxD,CAAC;CAiBF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { ProxyTracerProvider } from '../trace/ProxyTracerProvider';\nimport {\n isSpanContextValid,\n wrapSpanContext,\n} from '../trace/spancontext-utils';\nimport { Tracer } from '../trace/tracer';\nimport { TracerProvider } from '../trace/tracer_provider';\nimport {\n deleteSpan,\n getActiveSpan,\n getSpan,\n getSpanContext,\n setSpan,\n setSpanContext,\n} from '../trace/context-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'trace';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Tracing API\n */\nexport class TraceAPI {\n private static _instance?: TraceAPI;\n\n private _proxyTracerProvider = new ProxyTracerProvider();\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Trace API */\n public static getInstance(): TraceAPI {\n if (!this._instance) {\n this._instance = new TraceAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current global tracer.\n *\n * @returns true if the tracer provider was successfully registered, else false\n */\n public setGlobalTracerProvider(provider: TracerProvider): boolean {\n const success = registerGlobal(\n API_NAME,\n this._proxyTracerProvider,\n DiagAPI.instance()\n );\n if (success) {\n this._proxyTracerProvider.setDelegate(provider);\n }\n return success;\n }\n\n /**\n * Returns the global tracer provider.\n */\n public getTracerProvider(): TracerProvider {\n return getGlobal(API_NAME) || this._proxyTracerProvider;\n }\n\n /**\n * Returns a tracer from the global tracer provider.\n */\n public getTracer(name: string, version?: string): Tracer {\n return this.getTracerProvider().getTracer(name, version);\n }\n\n /** Remove the global tracer provider */\n public disable() {\n unregisterGlobal(API_NAME, DiagAPI.instance());\n this._proxyTracerProvider = new ProxyTracerProvider();\n }\n\n public wrapSpanContext = wrapSpanContext;\n\n public isSpanContextValid = isSpanContextValid;\n\n public deleteSpan = deleteSpan;\n\n public getSpan = getSpan;\n\n public getActiveSpan = getActiveSpan;\n\n public getSpanContext = getSpanContext;\n\n public setSpan = setSpan;\n\n public setSpanContext = setSpanContext;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/baggage/context-helpers.d.ts b/node_modules/@opentelemetry/api/build/esnext/baggage/context-helpers.d.ts new file mode 100644 index 0000000..23750eb --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/baggage/context-helpers.d.ts @@ -0,0 +1,29 @@ +import { Context } from '../context/types'; +import { Baggage } from './types'; +/** + * Retrieve the current baggage from the given context + * + * @param {Context} Context that manage all context values + * @returns {Baggage} Extracted baggage from the context + */ +export declare function getBaggage(context: Context): Baggage | undefined; +/** + * Retrieve the current baggage from the active/current context + * + * @returns {Baggage} Extracted baggage from the context + */ +export declare function getActiveBaggage(): Baggage | undefined; +/** + * Store a baggage in the given context + * + * @param {Context} Context that manage all context values + * @param {Baggage} baggage that will be set in the actual context + */ +export declare function setBaggage(context: Context, baggage: Baggage): Context; +/** + * Delete the baggage stored in the given context + * + * @param {Context} Context that manage all context values + */ +export declare function deleteBaggage(context: Context): Context; +//# sourceMappingURL=context-helpers.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/baggage/context-helpers.js b/node_modules/@opentelemetry/api/build/esnext/baggage/context-helpers.js new file mode 100644 index 0000000..9cd0fe7 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/baggage/context-helpers.js @@ -0,0 +1,56 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ContextAPI } from '../api/context'; +import { createContextKey } from '../context/context'; +/** + * Baggage key + */ +const BAGGAGE_KEY = createContextKey('OpenTelemetry Baggage Key'); +/** + * Retrieve the current baggage from the given context + * + * @param {Context} Context that manage all context values + * @returns {Baggage} Extracted baggage from the context + */ +export function getBaggage(context) { + return context.getValue(BAGGAGE_KEY) || undefined; +} +/** + * Retrieve the current baggage from the active/current context + * + * @returns {Baggage} Extracted baggage from the context + */ +export function getActiveBaggage() { + return getBaggage(ContextAPI.getInstance().active()); +} +/** + * Store a baggage in the given context + * + * @param {Context} Context that manage all context values + * @param {Baggage} baggage that will be set in the actual context + */ +export function setBaggage(context, baggage) { + return context.setValue(BAGGAGE_KEY, baggage); +} +/** + * Delete the baggage stored in the given context + * + * @param {Context} Context that manage all context values + */ +export function deleteBaggage(context) { + return context.deleteValue(BAGGAGE_KEY); +} +//# sourceMappingURL=context-helpers.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/baggage/context-helpers.js.map b/node_modules/@opentelemetry/api/build/esnext/baggage/context-helpers.js.map new file mode 100644 index 0000000..c39d666 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/baggage/context-helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"context-helpers.js","sourceRoot":"","sources":["../../../src/baggage/context-helpers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAItD;;GAEG;AACH,MAAM,WAAW,GAAG,gBAAgB,CAAC,2BAA2B,CAAC,CAAC;AAElE;;;;;GAKG;AACH,MAAM,UAAU,UAAU,CAAC,OAAgB;IACzC,OAAQ,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAa,IAAI,SAAS,CAAC;AACjE,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,gBAAgB;IAC9B,OAAO,UAAU,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC;AACvD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,UAAU,CAAC,OAAgB,EAAE,OAAgB;IAC3D,OAAO,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;AAChD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,OAAgB;IAC5C,OAAO,OAAO,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ContextAPI } from '../api/context';\nimport { createContextKey } from '../context/context';\nimport { Context } from '../context/types';\nimport { Baggage } from './types';\n\n/**\n * Baggage key\n */\nconst BAGGAGE_KEY = createContextKey('OpenTelemetry Baggage Key');\n\n/**\n * Retrieve the current baggage from the given context\n *\n * @param {Context} Context that manage all context values\n * @returns {Baggage} Extracted baggage from the context\n */\nexport function getBaggage(context: Context): Baggage | undefined {\n return (context.getValue(BAGGAGE_KEY) as Baggage) || undefined;\n}\n\n/**\n * Retrieve the current baggage from the active/current context\n *\n * @returns {Baggage} Extracted baggage from the context\n */\nexport function getActiveBaggage(): Baggage | undefined {\n return getBaggage(ContextAPI.getInstance().active());\n}\n\n/**\n * Store a baggage in the given context\n *\n * @param {Context} Context that manage all context values\n * @param {Baggage} baggage that will be set in the actual context\n */\nexport function setBaggage(context: Context, baggage: Baggage): Context {\n return context.setValue(BAGGAGE_KEY, baggage);\n}\n\n/**\n * Delete the baggage stored in the given context\n *\n * @param {Context} Context that manage all context values\n */\nexport function deleteBaggage(context: Context): Context {\n return context.deleteValue(BAGGAGE_KEY);\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/baggage/internal/baggage-impl.d.ts b/node_modules/@opentelemetry/api/build/esnext/baggage/internal/baggage-impl.d.ts new file mode 100644 index 0000000..e6b4554 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/baggage/internal/baggage-impl.d.ts @@ -0,0 +1,12 @@ +import type { Baggage, BaggageEntry } from '../types'; +export declare class BaggageImpl implements Baggage { + private _entries; + constructor(entries?: Map); + getEntry(key: string): BaggageEntry | undefined; + getAllEntries(): [string, BaggageEntry][]; + setEntry(key: string, entry: BaggageEntry): BaggageImpl; + removeEntry(key: string): BaggageImpl; + removeEntries(...keys: string[]): BaggageImpl; + clear(): BaggageImpl; +} +//# sourceMappingURL=baggage-impl.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/baggage/internal/baggage-impl.js b/node_modules/@opentelemetry/api/build/esnext/baggage/internal/baggage-impl.js new file mode 100644 index 0000000..774d1f8 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/baggage/internal/baggage-impl.js @@ -0,0 +1,51 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export class BaggageImpl { + constructor(entries) { + this._entries = entries ? new Map(entries) : new Map(); + } + getEntry(key) { + const entry = this._entries.get(key); + if (!entry) { + return undefined; + } + return Object.assign({}, entry); + } + getAllEntries() { + return Array.from(this._entries.entries()).map(([k, v]) => [k, v]); + } + setEntry(key, entry) { + const newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.set(key, entry); + return newBaggage; + } + removeEntry(key) { + const newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.delete(key); + return newBaggage; + } + removeEntries(...keys) { + const newBaggage = new BaggageImpl(this._entries); + for (const key of keys) { + newBaggage._entries.delete(key); + } + return newBaggage; + } + clear() { + return new BaggageImpl(); + } +} +//# sourceMappingURL=baggage-impl.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/baggage/internal/baggage-impl.js.map b/node_modules/@opentelemetry/api/build/esnext/baggage/internal/baggage-impl.js.map new file mode 100644 index 0000000..74c6a4c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/baggage/internal/baggage-impl.js.map @@ -0,0 +1 @@ +{"version":3,"file":"baggage-impl.js","sourceRoot":"","sources":["../../../../src/baggage/internal/baggage-impl.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,MAAM,OAAO,WAAW;IAGtB,YAAY,OAAmC;QAC7C,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,EAAE,CAAC;IACzD,CAAC;IAED,QAAQ,CAAC,GAAW;QAClB,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACrC,IAAI,CAAC,KAAK,EAAE;YACV,OAAO,SAAS,CAAC;SAClB;QAED,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;IAClC,CAAC;IAED,aAAa;QACX,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IACrE,CAAC;IAED,QAAQ,CAAC,GAAW,EAAE,KAAmB;QACvC,MAAM,UAAU,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAClD,UAAU,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACpC,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,WAAW,CAAC,GAAW;QACrB,MAAM,UAAU,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAClD,UAAU,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAChC,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,aAAa,CAAC,GAAG,IAAc;QAC7B,MAAM,UAAU,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAClD,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE;YACtB,UAAU,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;SACjC;QACD,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,KAAK;QACH,OAAO,IAAI,WAAW,EAAE,CAAC;IAC3B,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Baggage, BaggageEntry } from '../types';\n\nexport class BaggageImpl implements Baggage {\n private _entries: Map;\n\n constructor(entries?: Map) {\n this._entries = entries ? new Map(entries) : new Map();\n }\n\n getEntry(key: string): BaggageEntry | undefined {\n const entry = this._entries.get(key);\n if (!entry) {\n return undefined;\n }\n\n return Object.assign({}, entry);\n }\n\n getAllEntries(): [string, BaggageEntry][] {\n return Array.from(this._entries.entries()).map(([k, v]) => [k, v]);\n }\n\n setEntry(key: string, entry: BaggageEntry): BaggageImpl {\n const newBaggage = new BaggageImpl(this._entries);\n newBaggage._entries.set(key, entry);\n return newBaggage;\n }\n\n removeEntry(key: string): BaggageImpl {\n const newBaggage = new BaggageImpl(this._entries);\n newBaggage._entries.delete(key);\n return newBaggage;\n }\n\n removeEntries(...keys: string[]): BaggageImpl {\n const newBaggage = new BaggageImpl(this._entries);\n for (const key of keys) {\n newBaggage._entries.delete(key);\n }\n return newBaggage;\n }\n\n clear(): BaggageImpl {\n return new BaggageImpl();\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/baggage/internal/symbol.d.ts b/node_modules/@opentelemetry/api/build/esnext/baggage/internal/symbol.d.ts new file mode 100644 index 0000000..9cd991c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/baggage/internal/symbol.d.ts @@ -0,0 +1,5 @@ +/** + * Symbol used to make BaggageEntryMetadata an opaque type + */ +export declare const baggageEntryMetadataSymbol: unique symbol; +//# sourceMappingURL=symbol.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/baggage/internal/symbol.js b/node_modules/@opentelemetry/api/build/esnext/baggage/internal/symbol.js new file mode 100644 index 0000000..22f5b25 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/baggage/internal/symbol.js @@ -0,0 +1,20 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Symbol used to make BaggageEntryMetadata an opaque type + */ +export const baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); +//# sourceMappingURL=symbol.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/baggage/internal/symbol.js.map b/node_modules/@opentelemetry/api/build/esnext/baggage/internal/symbol.js.map new file mode 100644 index 0000000..0cc1abd --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/baggage/internal/symbol.js.map @@ -0,0 +1 @@ +{"version":3,"file":"symbol.js","sourceRoot":"","sources":["../../../../src/baggage/internal/symbol.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;GAEG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,MAAM,CAAC,sBAAsB,CAAC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Symbol used to make BaggageEntryMetadata an opaque type\n */\nexport const baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata');\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/baggage/types.d.ts b/node_modules/@opentelemetry/api/build/esnext/baggage/types.d.ts new file mode 100644 index 0000000..32fa0ec --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/baggage/types.d.ts @@ -0,0 +1,60 @@ +import { baggageEntryMetadataSymbol } from './internal/symbol'; +export interface BaggageEntry { + /** `String` value of the `BaggageEntry`. */ + value: string; + /** + * Metadata is an optional string property defined by the W3C baggage specification. + * It currently has no special meaning defined by the specification. + */ + metadata?: BaggageEntryMetadata; +} +/** + * Serializable Metadata defined by the W3C baggage specification. + * It currently has no special meaning defined by the OpenTelemetry or W3C. + */ +export declare type BaggageEntryMetadata = { + toString(): string; +} & { + __TYPE__: typeof baggageEntryMetadataSymbol; +}; +/** + * Baggage represents collection of key-value pairs with optional metadata. + * Each key of Baggage is associated with exactly one value. + * Baggage may be used to annotate and enrich telemetry data. + */ +export interface Baggage { + /** + * Get an entry from Baggage if it exists + * + * @param key The key which identifies the BaggageEntry + */ + getEntry(key: string): BaggageEntry | undefined; + /** + * Get a list of all entries in the Baggage + */ + getAllEntries(): [string, BaggageEntry][]; + /** + * Returns a new baggage with the entries from the current bag and the specified entry + * + * @param key string which identifies the baggage entry + * @param entry BaggageEntry for the given key + */ + setEntry(key: string, entry: BaggageEntry): Baggage; + /** + * Returns a new baggage with the entries from the current bag except the removed entry + * + * @param key key identifying the entry to be removed + */ + removeEntry(key: string): Baggage; + /** + * Returns a new baggage with the entries from the current bag except the removed entries + * + * @param key keys identifying the entries to be removed + */ + removeEntries(...key: string[]): Baggage; + /** + * Returns a new baggage with no entries + */ + clear(): Baggage; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/baggage/types.js b/node_modules/@opentelemetry/api/build/esnext/baggage/types.js new file mode 100644 index 0000000..928faad --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/baggage/types.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/baggage/types.js.map b/node_modules/@opentelemetry/api/build/esnext/baggage/types.js.map new file mode 100644 index 0000000..ae80c19 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/baggage/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/baggage/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { baggageEntryMetadataSymbol } from './internal/symbol';\n\n/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface BaggageEntry {\n /** `String` value of the `BaggageEntry`. */\n value: string;\n /**\n * Metadata is an optional string property defined by the W3C baggage specification.\n * It currently has no special meaning defined by the specification.\n */\n metadata?: BaggageEntryMetadata;\n}\n\n/**\n * Serializable Metadata defined by the W3C baggage specification.\n * It currently has no special meaning defined by the OpenTelemetry or W3C.\n */\nexport type BaggageEntryMetadata = { toString(): string } & {\n __TYPE__: typeof baggageEntryMetadataSymbol;\n};\n\n/**\n * Baggage represents collection of key-value pairs with optional metadata.\n * Each key of Baggage is associated with exactly one value.\n * Baggage may be used to annotate and enrich telemetry data.\n */\nexport interface Baggage {\n /**\n * Get an entry from Baggage if it exists\n *\n * @param key The key which identifies the BaggageEntry\n */\n getEntry(key: string): BaggageEntry | undefined;\n\n /**\n * Get a list of all entries in the Baggage\n */\n getAllEntries(): [string, BaggageEntry][];\n\n /**\n * Returns a new baggage with the entries from the current bag and the specified entry\n *\n * @param key string which identifies the baggage entry\n * @param entry BaggageEntry for the given key\n */\n setEntry(key: string, entry: BaggageEntry): Baggage;\n\n /**\n * Returns a new baggage with the entries from the current bag except the removed entry\n *\n * @param key key identifying the entry to be removed\n */\n removeEntry(key: string): Baggage;\n\n /**\n * Returns a new baggage with the entries from the current bag except the removed entries\n *\n * @param key keys identifying the entries to be removed\n */\n removeEntries(...key: string[]): Baggage;\n\n /**\n * Returns a new baggage with no entries\n */\n clear(): Baggage;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/baggage/utils.d.ts b/node_modules/@opentelemetry/api/build/esnext/baggage/utils.d.ts new file mode 100644 index 0000000..9955d9e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/baggage/utils.d.ts @@ -0,0 +1,15 @@ +import { Baggage, BaggageEntry, BaggageEntryMetadata } from './types'; +/** + * Create a new Baggage with optional entries + * + * @param entries An array of baggage entries the new baggage should contain + */ +export declare function createBaggage(entries?: Record): Baggage; +/** + * Create a serializable BaggageEntryMetadata object from a string. + * + * @param str string metadata. Format is currently not defined by the spec and has no special meaning. + * + */ +export declare function baggageEntryMetadataFromString(str: string): BaggageEntryMetadata; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/baggage/utils.js b/node_modules/@opentelemetry/api/build/esnext/baggage/utils.js new file mode 100644 index 0000000..b444883 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/baggage/utils.js @@ -0,0 +1,46 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DiagAPI } from '../api/diag'; +import { BaggageImpl } from './internal/baggage-impl'; +import { baggageEntryMetadataSymbol } from './internal/symbol'; +const diag = DiagAPI.instance(); +/** + * Create a new Baggage with optional entries + * + * @param entries An array of baggage entries the new baggage should contain + */ +export function createBaggage(entries = {}) { + return new BaggageImpl(new Map(Object.entries(entries))); +} +/** + * Create a serializable BaggageEntryMetadata object from a string. + * + * @param str string metadata. Format is currently not defined by the spec and has no special meaning. + * + */ +export function baggageEntryMetadataFromString(str) { + if (typeof str !== 'string') { + diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`); + str = ''; + } + return { + __TYPE__: baggageEntryMetadataSymbol, + toString() { + return str; + }, + }; +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/baggage/utils.js.map b/node_modules/@opentelemetry/api/build/esnext/baggage/utils.js.map new file mode 100644 index 0000000..0a0228d --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/baggage/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/baggage/utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAG/D,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC;AAEhC;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAC3B,UAAwC,EAAE;IAE1C,OAAO,IAAI,WAAW,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;AAC3D,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,8BAA8B,CAC5C,GAAW;IAEX,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;QAC3B,IAAI,CAAC,KAAK,CACR,qDAAqD,OAAO,GAAG,EAAE,CAClE,CAAC;QACF,GAAG,GAAG,EAAE,CAAC;KACV;IAED,OAAO;QACL,QAAQ,EAAE,0BAA0B;QACpC,QAAQ;YACN,OAAO,GAAG,CAAC;QACb,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagAPI } from '../api/diag';\nimport { BaggageImpl } from './internal/baggage-impl';\nimport { baggageEntryMetadataSymbol } from './internal/symbol';\nimport { Baggage, BaggageEntry, BaggageEntryMetadata } from './types';\n\nconst diag = DiagAPI.instance();\n\n/**\n * Create a new Baggage with optional entries\n *\n * @param entries An array of baggage entries the new baggage should contain\n */\nexport function createBaggage(\n entries: Record = {}\n): Baggage {\n return new BaggageImpl(new Map(Object.entries(entries)));\n}\n\n/**\n * Create a serializable BaggageEntryMetadata object from a string.\n *\n * @param str string metadata. Format is currently not defined by the spec and has no special meaning.\n *\n */\nexport function baggageEntryMetadataFromString(\n str: string\n): BaggageEntryMetadata {\n if (typeof str !== 'string') {\n diag.error(\n `Cannot create baggage metadata from unknown type: ${typeof str}`\n );\n str = '';\n }\n\n return {\n __TYPE__: baggageEntryMetadataSymbol,\n toString() {\n return str;\n },\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/common/Attributes.d.ts b/node_modules/@opentelemetry/api/build/esnext/common/Attributes.d.ts new file mode 100644 index 0000000..19994fb --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/common/Attributes.d.ts @@ -0,0 +1,15 @@ +/** + * Attributes is a map from string to attribute values. + * + * Note: only the own enumerable keys are counted as valid attribute keys. + */ +export interface Attributes { + [attributeKey: string]: AttributeValue | undefined; +} +/** + * Attribute values may be any non-nullish primitive value except an object. + * + * null or undefined attribute values are invalid and will result in undefined behavior. + */ +export declare type AttributeValue = string | number | boolean | Array | Array | Array; +//# sourceMappingURL=Attributes.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/common/Attributes.js b/node_modules/@opentelemetry/api/build/esnext/common/Attributes.js new file mode 100644 index 0000000..dbb1e49 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/common/Attributes.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=Attributes.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/common/Attributes.js.map b/node_modules/@opentelemetry/api/build/esnext/common/Attributes.js.map new file mode 100644 index 0000000..2649c94 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/common/Attributes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Attributes.js","sourceRoot":"","sources":["../../../src/common/Attributes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Attributes is a map from string to attribute values.\n *\n * Note: only the own enumerable keys are counted as valid attribute keys.\n */\nexport interface Attributes {\n [attributeKey: string]: AttributeValue | undefined;\n}\n\n/**\n * Attribute values may be any non-nullish primitive value except an object.\n *\n * null or undefined attribute values are invalid and will result in undefined behavior.\n */\nexport type AttributeValue =\n | string\n | number\n | boolean\n | Array\n | Array\n | Array;\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/common/Exception.d.ts b/node_modules/@opentelemetry/api/build/esnext/common/Exception.d.ts new file mode 100644 index 0000000..e175a7f --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/common/Exception.d.ts @@ -0,0 +1,26 @@ +interface ExceptionWithCode { + code: string | number; + name?: string; + message?: string; + stack?: string; +} +interface ExceptionWithMessage { + code?: string | number; + message: string; + name?: string; + stack?: string; +} +interface ExceptionWithName { + code?: string | number; + message?: string; + name: string; + stack?: string; +} +/** + * Defines Exception. + * + * string or an object with one of (message or name or code) and optional stack + */ +export declare type Exception = ExceptionWithCode | ExceptionWithMessage | ExceptionWithName | string; +export {}; +//# sourceMappingURL=Exception.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/common/Exception.js b/node_modules/@opentelemetry/api/build/esnext/common/Exception.js new file mode 100644 index 0000000..6522a8e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/common/Exception.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=Exception.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/common/Exception.js.map b/node_modules/@opentelemetry/api/build/esnext/common/Exception.js.map new file mode 100644 index 0000000..989dd3d --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/common/Exception.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Exception.js","sourceRoot":"","sources":["../../../src/common/Exception.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\ninterface ExceptionWithCode {\n code: string | number;\n name?: string;\n message?: string;\n stack?: string;\n}\n\ninterface ExceptionWithMessage {\n code?: string | number;\n message: string;\n name?: string;\n stack?: string;\n}\n\ninterface ExceptionWithName {\n code?: string | number;\n message?: string;\n name: string;\n stack?: string;\n}\n\n/**\n * Defines Exception.\n *\n * string or an object with one of (message or name or code) and optional stack\n */\nexport type Exception =\n | ExceptionWithCode\n | ExceptionWithMessage\n | ExceptionWithName\n | string;\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/common/Time.d.ts b/node_modules/@opentelemetry/api/build/esnext/common/Time.d.ts new file mode 100644 index 0000000..cc3c502 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/common/Time.d.ts @@ -0,0 +1,20 @@ +/** + * Defines High-Resolution Time. + * + * The first number, HrTime[0], is UNIX Epoch time in seconds since 00:00:00 UTC on 1 January 1970. + * The second number, HrTime[1], represents the partial second elapsed since Unix Epoch time represented by first number in nanoseconds. + * For example, 2021-01-01T12:30:10.150Z in UNIX Epoch time in milliseconds is represented as 1609504210150. + * The first number is calculated by converting and truncating the Epoch time in milliseconds to seconds: + * HrTime[0] = Math.trunc(1609504210150 / 1000) = 1609504210. + * The second number is calculated by converting the digits after the decimal point of the subtraction, (1609504210150 / 1000) - HrTime[0], to nanoseconds: + * HrTime[1] = Number((1609504210.150 - HrTime[0]).toFixed(9)) * 1e9 = 150000000. + * This is represented in HrTime format as [1609504210, 150000000]. + */ +export declare type HrTime = [number, number]; +/** + * Defines TimeInput. + * + * hrtime, epoch milliseconds, performance.now() or Date + */ +export declare type TimeInput = HrTime | number | Date; +//# sourceMappingURL=Time.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/common/Time.js b/node_modules/@opentelemetry/api/build/esnext/common/Time.js new file mode 100644 index 0000000..2abdf58 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/common/Time.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=Time.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/common/Time.js.map b/node_modules/@opentelemetry/api/build/esnext/common/Time.js.map new file mode 100644 index 0000000..ae124f0 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/common/Time.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Time.js","sourceRoot":"","sources":["../../../src/common/Time.ts"],"names":[],"mappings":"","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Defines High-Resolution Time.\n *\n * The first number, HrTime[0], is UNIX Epoch time in seconds since 00:00:00 UTC on 1 January 1970.\n * The second number, HrTime[1], represents the partial second elapsed since Unix Epoch time represented by first number in nanoseconds.\n * For example, 2021-01-01T12:30:10.150Z in UNIX Epoch time in milliseconds is represented as 1609504210150.\n * The first number is calculated by converting and truncating the Epoch time in milliseconds to seconds:\n * HrTime[0] = Math.trunc(1609504210150 / 1000) = 1609504210.\n * The second number is calculated by converting the digits after the decimal point of the subtraction, (1609504210150 / 1000) - HrTime[0], to nanoseconds:\n * HrTime[1] = Number((1609504210.150 - HrTime[0]).toFixed(9)) * 1e9 = 150000000.\n * This is represented in HrTime format as [1609504210, 150000000].\n */\nexport type HrTime = [number, number];\n\n/**\n * Defines TimeInput.\n *\n * hrtime, epoch milliseconds, performance.now() or Date\n */\nexport type TimeInput = HrTime | number | Date;\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/context-api.d.ts b/node_modules/@opentelemetry/api/build/esnext/context-api.d.ts new file mode 100644 index 0000000..650f4ee --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/context-api.d.ts @@ -0,0 +1,4 @@ +import { ContextAPI } from './api/context'; +/** Entrypoint for context API */ +export declare const context: ContextAPI; +//# sourceMappingURL=context-api.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/context-api.js b/node_modules/@opentelemetry/api/build/esnext/context-api.js new file mode 100644 index 0000000..5827043 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/context-api.js @@ -0,0 +1,21 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +import { ContextAPI } from './api/context'; +/** Entrypoint for context API */ +export const context = ContextAPI.getInstance(); +//# sourceMappingURL=context-api.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/context-api.js.map b/node_modules/@opentelemetry/api/build/esnext/context-api.js.map new file mode 100644 index 0000000..fc655d3 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/context-api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"context-api.js","sourceRoot":"","sources":["../../src/context-api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,sEAAsE;AACtE,qCAAqC;AACrC,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,iCAAiC;AACjC,MAAM,CAAC,MAAM,OAAO,GAAG,UAAU,CAAC,WAAW,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { ContextAPI } from './api/context';\n/** Entrypoint for context API */\nexport const context = ContextAPI.getInstance();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/context/NoopContextManager.d.ts b/node_modules/@opentelemetry/api/build/esnext/context/NoopContextManager.d.ts new file mode 100644 index 0000000..48a1659 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/context/NoopContextManager.d.ts @@ -0,0 +1,9 @@ +import * as types from './types'; +export declare class NoopContextManager implements types.ContextManager { + active(): types.Context; + with ReturnType>(_context: types.Context, fn: F, thisArg?: ThisParameterType, ...args: A): ReturnType; + bind(_context: types.Context, target: T): T; + enable(): this; + disable(): this; +} +//# sourceMappingURL=NoopContextManager.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/context/NoopContextManager.js b/node_modules/@opentelemetry/api/build/esnext/context/NoopContextManager.js new file mode 100644 index 0000000..14824a6 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/context/NoopContextManager.js @@ -0,0 +1,34 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ROOT_CONTEXT } from './context'; +export class NoopContextManager { + active() { + return ROOT_CONTEXT; + } + with(_context, fn, thisArg, ...args) { + return fn.call(thisArg, ...args); + } + bind(_context, target) { + return target; + } + enable() { + return this; + } + disable() { + return this; + } +} +//# sourceMappingURL=NoopContextManager.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/context/NoopContextManager.js.map b/node_modules/@opentelemetry/api/build/esnext/context/NoopContextManager.js.map new file mode 100644 index 0000000..8ee9f8f --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/context/NoopContextManager.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NoopContextManager.js","sourceRoot":"","sources":["../../../src/context/NoopContextManager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAGzC,MAAM,OAAO,kBAAkB;IAC7B,MAAM;QACJ,OAAO,YAAY,CAAC;IACtB,CAAC;IAED,IAAI,CACF,QAAuB,EACvB,EAAK,EACL,OAA8B,EAC9B,GAAG,IAAO;QAEV,OAAO,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,CAAC;IACnC,CAAC;IAED,IAAI,CAAI,QAAuB,EAAE,MAAS;QACxC,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,MAAM;QACJ,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ROOT_CONTEXT } from './context';\nimport * as types from './types';\n\nexport class NoopContextManager implements types.ContextManager {\n active(): types.Context {\n return ROOT_CONTEXT;\n }\n\n with ReturnType>(\n _context: types.Context,\n fn: F,\n thisArg?: ThisParameterType,\n ...args: A\n ): ReturnType {\n return fn.call(thisArg, ...args);\n }\n\n bind(_context: types.Context, target: T): T {\n return target;\n }\n\n enable(): this {\n return this;\n }\n\n disable(): this {\n return this;\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/context/context.d.ts b/node_modules/@opentelemetry/api/build/esnext/context/context.d.ts new file mode 100644 index 0000000..8be0259 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/context/context.d.ts @@ -0,0 +1,6 @@ +import { Context } from './types'; +/** Get a key to uniquely identify a context value */ +export declare function createContextKey(description: string): symbol; +/** The root context is used as the default parent context when there is no active context */ +export declare const ROOT_CONTEXT: Context; +//# sourceMappingURL=context.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/context/context.js b/node_modules/@opentelemetry/api/build/esnext/context/context.js new file mode 100644 index 0000000..a95ecf0 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/context/context.js @@ -0,0 +1,51 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Get a key to uniquely identify a context value */ +export function createContextKey(description) { + // The specification states that for the same input, multiple calls should + // return different keys. Due to the nature of the JS dependency management + // system, this creates problems where multiple versions of some package + // could hold different keys for the same property. + // + // Therefore, we use Symbol.for which returns the same key for the same input. + return Symbol.for(description); +} +class BaseContext { + /** + * Construct a new context which inherits values from an optional parent context. + * + * @param parentContext a context from which to inherit values + */ + constructor(parentContext) { + // for minification + const self = this; + self._currentContext = parentContext ? new Map(parentContext) : new Map(); + self.getValue = (key) => self._currentContext.get(key); + self.setValue = (key, value) => { + const context = new BaseContext(self._currentContext); + context._currentContext.set(key, value); + return context; + }; + self.deleteValue = (key) => { + const context = new BaseContext(self._currentContext); + context._currentContext.delete(key); + return context; + }; + } +} +/** The root context is used as the default parent context when there is no active context */ +export const ROOT_CONTEXT = new BaseContext(); +//# sourceMappingURL=context.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/context/context.js.map b/node_modules/@opentelemetry/api/build/esnext/context/context.js.map new file mode 100644 index 0000000..a35b9a7 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/context/context.js.map @@ -0,0 +1 @@ +{"version":3,"file":"context.js","sourceRoot":"","sources":["../../../src/context/context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,qDAAqD;AACrD,MAAM,UAAU,gBAAgB,CAAC,WAAmB;IAClD,0EAA0E;IAC1E,2EAA2E;IAC3E,wEAAwE;IACxE,mDAAmD;IACnD,EAAE;IACF,8EAA8E;IAC9E,OAAO,MAAM,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;AACjC,CAAC;AAED,MAAM,WAAW;IAGf;;;;OAIG;IACH,YAAY,aAAoC;QAC9C,mBAAmB;QACnB,MAAM,IAAI,GAAG,IAAI,CAAC;QAElB,IAAI,CAAC,eAAe,GAAG,aAAa,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,EAAE,CAAC;QAE1E,IAAI,CAAC,QAAQ,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAE/D,IAAI,CAAC,QAAQ,GAAG,CAAC,GAAW,EAAE,KAAc,EAAW,EAAE;YACvD,MAAM,OAAO,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;YACtD,OAAO,CAAC,eAAe,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;YACxC,OAAO,OAAO,CAAC;QACjB,CAAC,CAAC;QAEF,IAAI,CAAC,WAAW,GAAG,CAAC,GAAW,EAAW,EAAE;YAC1C,MAAM,OAAO,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;YACtD,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YACpC,OAAO,OAAO,CAAC;QACjB,CAAC,CAAC;IACJ,CAAC;CAyBF;AAED,6FAA6F;AAC7F,MAAM,CAAC,MAAM,YAAY,GAAY,IAAI,WAAW,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from './types';\n\n/** Get a key to uniquely identify a context value */\nexport function createContextKey(description: string) {\n // The specification states that for the same input, multiple calls should\n // return different keys. Due to the nature of the JS dependency management\n // system, this creates problems where multiple versions of some package\n // could hold different keys for the same property.\n //\n // Therefore, we use Symbol.for which returns the same key for the same input.\n return Symbol.for(description);\n}\n\nclass BaseContext implements Context {\n private _currentContext!: Map;\n\n /**\n * Construct a new context which inherits values from an optional parent context.\n *\n * @param parentContext a context from which to inherit values\n */\n constructor(parentContext?: Map) {\n // for minification\n const self = this;\n\n self._currentContext = parentContext ? new Map(parentContext) : new Map();\n\n self.getValue = (key: symbol) => self._currentContext.get(key);\n\n self.setValue = (key: symbol, value: unknown): Context => {\n const context = new BaseContext(self._currentContext);\n context._currentContext.set(key, value);\n return context;\n };\n\n self.deleteValue = (key: symbol): Context => {\n const context = new BaseContext(self._currentContext);\n context._currentContext.delete(key);\n return context;\n };\n }\n\n /**\n * Get a value from the context.\n *\n * @param key key which identifies a context value\n */\n public getValue!: (key: symbol) => unknown;\n\n /**\n * Create a new context which inherits from this context and has\n * the given key set to the given value.\n *\n * @param key context key for which to set the value\n * @param value value to set for the given key\n */\n public setValue!: (key: symbol, value: unknown) => Context;\n\n /**\n * Return a new context which inherits from this context but does\n * not contain a value for the given key.\n *\n * @param key context key for which to clear a value\n */\n public deleteValue!: (key: symbol) => Context;\n}\n\n/** The root context is used as the default parent context when there is no active context */\nexport const ROOT_CONTEXT: Context = new BaseContext();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/context/types.d.ts b/node_modules/@opentelemetry/api/build/esnext/context/types.d.ts new file mode 100644 index 0000000..7e86632 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/context/types.d.ts @@ -0,0 +1,52 @@ +export interface Context { + /** + * Get a value from the context. + * + * @param key key which identifies a context value + */ + getValue(key: symbol): unknown; + /** + * Create a new context which inherits from this context and has + * the given key set to the given value. + * + * @param key context key for which to set the value + * @param value value to set for the given key + */ + setValue(key: symbol, value: unknown): Context; + /** + * Return a new context which inherits from this context but does + * not contain a value for the given key. + * + * @param key context key for which to clear a value + */ + deleteValue(key: symbol): Context; +} +export interface ContextManager { + /** + * Get the current active context + */ + active(): Context; + /** + * Run the fn callback with object set as the current active context + * @param context Any object to set as the current active context + * @param fn A callback to be immediately run within a specific context + * @param thisArg optional receiver to be used for calling fn + * @param args optional arguments forwarded to fn + */ + with ReturnType>(context: Context, fn: F, thisArg?: ThisParameterType, ...args: A): ReturnType; + /** + * Bind an object as the current context (or a specific one) + * @param [context] Optionally specify the context which you want to assign + * @param target Any object to which a context need to be set + */ + bind(context: Context, target: T): T; + /** + * Enable context management + */ + enable(): this; + /** + * Disable context management + */ + disable(): this; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/context/types.js b/node_modules/@opentelemetry/api/build/esnext/context/types.js new file mode 100644 index 0000000..928faad --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/context/types.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/context/types.js.map b/node_modules/@opentelemetry/api/build/esnext/context/types.js.map new file mode 100644 index 0000000..d438aa3 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/context/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/context/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Context {\n /**\n * Get a value from the context.\n *\n * @param key key which identifies a context value\n */\n getValue(key: symbol): unknown;\n\n /**\n * Create a new context which inherits from this context and has\n * the given key set to the given value.\n *\n * @param key context key for which to set the value\n * @param value value to set for the given key\n */\n setValue(key: symbol, value: unknown): Context;\n\n /**\n * Return a new context which inherits from this context but does\n * not contain a value for the given key.\n *\n * @param key context key for which to clear a value\n */\n deleteValue(key: symbol): Context;\n}\n\nexport interface ContextManager {\n /**\n * Get the current active context\n */\n active(): Context;\n\n /**\n * Run the fn callback with object set as the current active context\n * @param context Any object to set as the current active context\n * @param fn A callback to be immediately run within a specific context\n * @param thisArg optional receiver to be used for calling fn\n * @param args optional arguments forwarded to fn\n */\n with ReturnType>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType,\n ...args: A\n ): ReturnType;\n\n /**\n * Bind an object as the current context (or a specific one)\n * @param [context] Optionally specify the context which you want to assign\n * @param target Any object to which a context need to be set\n */\n bind(context: Context, target: T): T;\n\n /**\n * Enable context management\n */\n enable(): this;\n\n /**\n * Disable context management\n */\n disable(): this;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/diag-api.d.ts b/node_modules/@opentelemetry/api/build/esnext/diag-api.d.ts new file mode 100644 index 0000000..d82fdb1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/diag-api.d.ts @@ -0,0 +1,9 @@ +import { DiagAPI } from './api/diag'; +/** + * Entrypoint for Diag API. + * Defines Diagnostic handler used for internal diagnostic logging operations. + * The default provides a Noop DiagLogger implementation which may be changed via the + * diag.setLogger(logger: DiagLogger) function. + */ +export declare const diag: DiagAPI; +//# sourceMappingURL=diag-api.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/diag-api.js b/node_modules/@opentelemetry/api/build/esnext/diag-api.js new file mode 100644 index 0000000..41d2658 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/diag-api.js @@ -0,0 +1,26 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +import { DiagAPI } from './api/diag'; +/** + * Entrypoint for Diag API. + * Defines Diagnostic handler used for internal diagnostic logging operations. + * The default provides a Noop DiagLogger implementation which may be changed via the + * diag.setLogger(logger: DiagLogger) function. + */ +export const diag = DiagAPI.instance(); +//# sourceMappingURL=diag-api.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/diag-api.js.map b/node_modules/@opentelemetry/api/build/esnext/diag-api.js.map new file mode 100644 index 0000000..d0be8cb --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/diag-api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"diag-api.js","sourceRoot":"","sources":["../../src/diag-api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,sEAAsE;AACtE,qCAAqC;AACrC,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC;;;;;GAKG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { DiagAPI } from './api/diag';\n/**\n * Entrypoint for Diag API.\n * Defines Diagnostic handler used for internal diagnostic logging operations.\n * The default provides a Noop DiagLogger implementation which may be changed via the\n * diag.setLogger(logger: DiagLogger) function.\n */\nexport const diag = DiagAPI.instance();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/diag/ComponentLogger.d.ts b/node_modules/@opentelemetry/api/build/esnext/diag/ComponentLogger.d.ts new file mode 100644 index 0000000..f060950 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/diag/ComponentLogger.d.ts @@ -0,0 +1,20 @@ +import { ComponentLoggerOptions, DiagLogger } from './types'; +/** + * Component Logger which is meant to be used as part of any component which + * will add automatically additional namespace in front of the log message. + * It will then forward all message to global diag logger + * @example + * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' }); + * cLogger.debug('test'); + * // @opentelemetry/instrumentation-http test + */ +export declare class DiagComponentLogger implements DiagLogger { + private _namespace; + constructor(props: ComponentLoggerOptions); + debug(...args: any[]): void; + error(...args: any[]): void; + info(...args: any[]): void; + warn(...args: any[]): void; + verbose(...args: any[]): void; +} +//# sourceMappingURL=ComponentLogger.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/diag/ComponentLogger.js b/node_modules/@opentelemetry/api/build/esnext/diag/ComponentLogger.js new file mode 100644 index 0000000..1e21dbe --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/diag/ComponentLogger.js @@ -0,0 +1,55 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { getGlobal } from '../internal/global-utils'; +/** + * Component Logger which is meant to be used as part of any component which + * will add automatically additional namespace in front of the log message. + * It will then forward all message to global diag logger + * @example + * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' }); + * cLogger.debug('test'); + * // @opentelemetry/instrumentation-http test + */ +export class DiagComponentLogger { + constructor(props) { + this._namespace = props.namespace || 'DiagComponentLogger'; + } + debug(...args) { + return logProxy('debug', this._namespace, args); + } + error(...args) { + return logProxy('error', this._namespace, args); + } + info(...args) { + return logProxy('info', this._namespace, args); + } + warn(...args) { + return logProxy('warn', this._namespace, args); + } + verbose(...args) { + return logProxy('verbose', this._namespace, args); + } +} +function logProxy(funcName, namespace, args) { + const logger = getGlobal('diag'); + // shortcut if logger not set + if (!logger) { + return; + } + args.unshift(namespace); + return logger[funcName](...args); +} +//# sourceMappingURL=ComponentLogger.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/diag/ComponentLogger.js.map b/node_modules/@opentelemetry/api/build/esnext/diag/ComponentLogger.js.map new file mode 100644 index 0000000..c65f5ff --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/diag/ComponentLogger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ComponentLogger.js","sourceRoot":"","sources":["../../../src/diag/ComponentLogger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAGrD;;;;;;;;GAQG;AACH,MAAM,OAAO,mBAAmB;IAG9B,YAAY,KAA6B;QACvC,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC,SAAS,IAAI,qBAAqB,CAAC;IAC7D,CAAC;IAEM,KAAK,CAAC,GAAG,IAAW;QACzB,OAAO,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IAClD,CAAC;IAEM,KAAK,CAAC,GAAG,IAAW;QACzB,OAAO,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IAClD,CAAC;IAEM,IAAI,CAAC,GAAG,IAAW;QACxB,OAAO,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IACjD,CAAC;IAEM,IAAI,CAAC,GAAG,IAAW;QACxB,OAAO,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IACjD,CAAC;IAEM,OAAO,CAAC,GAAG,IAAW;QAC3B,OAAO,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IACpD,CAAC;CACF;AAED,SAAS,QAAQ,CACf,QAA0B,EAC1B,SAAiB,EACjB,IAAS;IAET,MAAM,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;IACjC,6BAA6B;IAC7B,IAAI,CAAC,MAAM,EAAE;QACX,OAAO;KACR;IAED,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACxB,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC,GAAI,IAAoC,CAAC,CAAC;AACpE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobal } from '../internal/global-utils';\nimport { ComponentLoggerOptions, DiagLogger, DiagLogFunction } from './types';\n\n/**\n * Component Logger which is meant to be used as part of any component which\n * will add automatically additional namespace in front of the log message.\n * It will then forward all message to global diag logger\n * @example\n * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });\n * cLogger.debug('test');\n * // @opentelemetry/instrumentation-http test\n */\nexport class DiagComponentLogger implements DiagLogger {\n private _namespace: string;\n\n constructor(props: ComponentLoggerOptions) {\n this._namespace = props.namespace || 'DiagComponentLogger';\n }\n\n public debug(...args: any[]): void {\n return logProxy('debug', this._namespace, args);\n }\n\n public error(...args: any[]): void {\n return logProxy('error', this._namespace, args);\n }\n\n public info(...args: any[]): void {\n return logProxy('info', this._namespace, args);\n }\n\n public warn(...args: any[]): void {\n return logProxy('warn', this._namespace, args);\n }\n\n public verbose(...args: any[]): void {\n return logProxy('verbose', this._namespace, args);\n }\n}\n\nfunction logProxy(\n funcName: keyof DiagLogger,\n namespace: string,\n args: any\n): void {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) {\n return;\n }\n\n args.unshift(namespace);\n return logger[funcName](...(args as Parameters));\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/diag/consoleLogger.d.ts b/node_modules/@opentelemetry/api/build/esnext/diag/consoleLogger.d.ts new file mode 100644 index 0000000..fa3db1e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/diag/consoleLogger.d.ts @@ -0,0 +1,38 @@ +import { DiagLogger, DiagLogFunction } from './types'; +/** + * A simple Immutable Console based diagnostic logger which will output any messages to the Console. + * If you want to limit the amount of logging to a specific level or lower use the + * {@link createLogLevelDiagLogger} + */ +export declare class DiagConsoleLogger implements DiagLogger { + constructor(); + /** Log an error scenario that was not expected and caused the requested operation to fail. */ + error: DiagLogFunction; + /** + * Log a warning scenario to inform the developer of an issues that should be investigated. + * The requested operation may or may not have succeeded or completed. + */ + warn: DiagLogFunction; + /** + * Log a general informational message, this should not affect functionality. + * This is also the default logging level so this should NOT be used for logging + * debugging level information. + */ + info: DiagLogFunction; + /** + * Log a general debug message that can be useful for identifying a failure. + * Information logged at this level may include diagnostic details that would + * help identify a failure scenario. Useful scenarios would be to log the execution + * order of async operations + */ + debug: DiagLogFunction; + /** + * Log a detailed (verbose) trace level logging that can be used to identify failures + * where debug level logging would be insufficient, this level of tracing can include + * input and output parameters and as such may include PII information passing through + * the API. As such it is recommended that this level of tracing should not be enabled + * in a production environment. + */ + verbose: DiagLogFunction; +} +//# sourceMappingURL=consoleLogger.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/diag/consoleLogger.js b/node_modules/@opentelemetry/api/build/esnext/diag/consoleLogger.js new file mode 100644 index 0000000..d81ea30 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/diag/consoleLogger.js @@ -0,0 +1,53 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const consoleMap = [ + { n: 'error', c: 'error' }, + { n: 'warn', c: 'warn' }, + { n: 'info', c: 'info' }, + { n: 'debug', c: 'debug' }, + { n: 'verbose', c: 'trace' }, +]; +/** + * A simple Immutable Console based diagnostic logger which will output any messages to the Console. + * If you want to limit the amount of logging to a specific level or lower use the + * {@link createLogLevelDiagLogger} + */ +export class DiagConsoleLogger { + constructor() { + function _consoleFunc(funcName) { + return function (...args) { + if (console) { + // Some environments only expose the console when the F12 developer console is open + // eslint-disable-next-line no-console + let theFunc = console[funcName]; + if (typeof theFunc !== 'function') { + // Not all environments support all functions + // eslint-disable-next-line no-console + theFunc = console.log; + } + // One last final check + if (typeof theFunc === 'function') { + return theFunc.apply(console, args); + } + } + }; + } + for (let i = 0; i < consoleMap.length; i++) { + this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); + } + } +} +//# sourceMappingURL=consoleLogger.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/diag/consoleLogger.js.map b/node_modules/@opentelemetry/api/build/esnext/diag/consoleLogger.js.map new file mode 100644 index 0000000..7498dd0 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/diag/consoleLogger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"consoleLogger.js","sourceRoot":"","sources":["../../../src/diag/consoleLogger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAKH,MAAM,UAAU,GAAiD;IAC/D,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO,EAAE;IAC1B,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE;IACxB,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE;IACxB,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO,EAAE;IAC1B,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,OAAO,EAAE;CAC7B,CAAC;AAEF;;;;GAIG;AACH,MAAM,OAAO,iBAAiB;IAC5B;QACE,SAAS,YAAY,CAAC,QAAwB;YAC5C,OAAO,UAAU,GAAG,IAAI;gBACtB,IAAI,OAAO,EAAE;oBACX,mFAAmF;oBACnF,sCAAsC;oBACtC,IAAI,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;oBAChC,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE;wBACjC,6CAA6C;wBAC7C,sCAAsC;wBACtC,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC;qBACvB;oBAED,uBAAuB;oBACvB,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE;wBACjC,OAAO,OAAO,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;qBACrC;iBACF;YACH,CAAC,CAAC;QACJ,CAAC;QAED,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,UAAU,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YAC1C,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,YAAY,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;SACvD;IACH,CAAC;CAkCF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogger, DiagLogFunction } from './types';\n\ntype ConsoleMapKeys = 'error' | 'warn' | 'info' | 'debug' | 'trace';\nconst consoleMap: { n: keyof DiagLogger; c: ConsoleMapKeys }[] = [\n { n: 'error', c: 'error' },\n { n: 'warn', c: 'warn' },\n { n: 'info', c: 'info' },\n { n: 'debug', c: 'debug' },\n { n: 'verbose', c: 'trace' },\n];\n\n/**\n * A simple Immutable Console based diagnostic logger which will output any messages to the Console.\n * If you want to limit the amount of logging to a specific level or lower use the\n * {@link createLogLevelDiagLogger}\n */\nexport class DiagConsoleLogger implements DiagLogger {\n constructor() {\n function _consoleFunc(funcName: ConsoleMapKeys): DiagLogFunction {\n return function (...args) {\n if (console) {\n // Some environments only expose the console when the F12 developer console is open\n // eslint-disable-next-line no-console\n let theFunc = console[funcName];\n if (typeof theFunc !== 'function') {\n // Not all environments support all functions\n // eslint-disable-next-line no-console\n theFunc = console.log;\n }\n\n // One last final check\n if (typeof theFunc === 'function') {\n return theFunc.apply(console, args);\n }\n }\n };\n }\n\n for (let i = 0; i < consoleMap.length; i++) {\n this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c);\n }\n }\n\n /** Log an error scenario that was not expected and caused the requested operation to fail. */\n public error!: DiagLogFunction;\n\n /**\n * Log a warning scenario to inform the developer of an issues that should be investigated.\n * The requested operation may or may not have succeeded or completed.\n */\n public warn!: DiagLogFunction;\n\n /**\n * Log a general informational message, this should not affect functionality.\n * This is also the default logging level so this should NOT be used for logging\n * debugging level information.\n */\n public info!: DiagLogFunction;\n\n /**\n * Log a general debug message that can be useful for identifying a failure.\n * Information logged at this level may include diagnostic details that would\n * help identify a failure scenario. Useful scenarios would be to log the execution\n * order of async operations\n */\n public debug!: DiagLogFunction;\n\n /**\n * Log a detailed (verbose) trace level logging that can be used to identify failures\n * where debug level logging would be insufficient, this level of tracing can include\n * input and output parameters and as such may include PII information passing through\n * the API. As such it is recommended that this level of tracing should not be enabled\n * in a production environment.\n */\n public verbose!: DiagLogFunction;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/diag/internal/logLevelLogger.d.ts b/node_modules/@opentelemetry/api/build/esnext/diag/internal/logLevelLogger.d.ts new file mode 100644 index 0000000..890b9f1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/diag/internal/logLevelLogger.d.ts @@ -0,0 +1,3 @@ +import { DiagLogger, DiagLogLevel } from '../types'; +export declare function createLogLevelDiagLogger(maxLevel: DiagLogLevel, logger: DiagLogger): DiagLogger; +//# sourceMappingURL=logLevelLogger.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/diag/internal/logLevelLogger.js b/node_modules/@opentelemetry/api/build/esnext/diag/internal/logLevelLogger.js new file mode 100644 index 0000000..6abf21b --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/diag/internal/logLevelLogger.js @@ -0,0 +1,41 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DiagLogLevel } from '../types'; +export function createLogLevelDiagLogger(maxLevel, logger) { + if (maxLevel < DiagLogLevel.NONE) { + maxLevel = DiagLogLevel.NONE; + } + else if (maxLevel > DiagLogLevel.ALL) { + maxLevel = DiagLogLevel.ALL; + } + // In case the logger is null or undefined + logger = logger || {}; + function _filterFunc(funcName, theLevel) { + const theFunc = logger[funcName]; + if (typeof theFunc === 'function' && maxLevel >= theLevel) { + return theFunc.bind(logger); + } + return function () { }; + } + return { + error: _filterFunc('error', DiagLogLevel.ERROR), + warn: _filterFunc('warn', DiagLogLevel.WARN), + info: _filterFunc('info', DiagLogLevel.INFO), + debug: _filterFunc('debug', DiagLogLevel.DEBUG), + verbose: _filterFunc('verbose', DiagLogLevel.VERBOSE), + }; +} +//# sourceMappingURL=logLevelLogger.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/diag/internal/logLevelLogger.js.map b/node_modules/@opentelemetry/api/build/esnext/diag/internal/logLevelLogger.js.map new file mode 100644 index 0000000..ac34251 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/diag/internal/logLevelLogger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"logLevelLogger.js","sourceRoot":"","sources":["../../../../src/diag/internal/logLevelLogger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAA+B,YAAY,EAAE,MAAM,UAAU,CAAC;AAErE,MAAM,UAAU,wBAAwB,CACtC,QAAsB,EACtB,MAAkB;IAElB,IAAI,QAAQ,GAAG,YAAY,CAAC,IAAI,EAAE;QAChC,QAAQ,GAAG,YAAY,CAAC,IAAI,CAAC;KAC9B;SAAM,IAAI,QAAQ,GAAG,YAAY,CAAC,GAAG,EAAE;QACtC,QAAQ,GAAG,YAAY,CAAC,GAAG,CAAC;KAC7B;IAED,0CAA0C;IAC1C,MAAM,GAAG,MAAM,IAAI,EAAE,CAAC;IAEtB,SAAS,WAAW,CAClB,QAA0B,EAC1B,QAAsB;QAEtB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;QAEjC,IAAI,OAAO,OAAO,KAAK,UAAU,IAAI,QAAQ,IAAI,QAAQ,EAAE;YACzD,OAAO,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;SAC7B;QACD,OAAO,cAAa,CAAC,CAAC;IACxB,CAAC;IAED,OAAO;QACL,KAAK,EAAE,WAAW,CAAC,OAAO,EAAE,YAAY,CAAC,KAAK,CAAC;QAC/C,IAAI,EAAE,WAAW,CAAC,MAAM,EAAE,YAAY,CAAC,IAAI,CAAC;QAC5C,IAAI,EAAE,WAAW,CAAC,MAAM,EAAE,YAAY,CAAC,IAAI,CAAC;QAC5C,KAAK,EAAE,WAAW,CAAC,OAAO,EAAE,YAAY,CAAC,KAAK,CAAC;QAC/C,OAAO,EAAE,WAAW,CAAC,SAAS,EAAE,YAAY,CAAC,OAAO,CAAC;KACtD,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogFunction, DiagLogger, DiagLogLevel } from '../types';\n\nexport function createLogLevelDiagLogger(\n maxLevel: DiagLogLevel,\n logger: DiagLogger\n): DiagLogger {\n if (maxLevel < DiagLogLevel.NONE) {\n maxLevel = DiagLogLevel.NONE;\n } else if (maxLevel > DiagLogLevel.ALL) {\n maxLevel = DiagLogLevel.ALL;\n }\n\n // In case the logger is null or undefined\n logger = logger || {};\n\n function _filterFunc(\n funcName: keyof DiagLogger,\n theLevel: DiagLogLevel\n ): DiagLogFunction {\n const theFunc = logger[funcName];\n\n if (typeof theFunc === 'function' && maxLevel >= theLevel) {\n return theFunc.bind(logger);\n }\n return function () {};\n }\n\n return {\n error: _filterFunc('error', DiagLogLevel.ERROR),\n warn: _filterFunc('warn', DiagLogLevel.WARN),\n info: _filterFunc('info', DiagLogLevel.INFO),\n debug: _filterFunc('debug', DiagLogLevel.DEBUG),\n verbose: _filterFunc('verbose', DiagLogLevel.VERBOSE),\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/diag/internal/noopLogger.d.ts b/node_modules/@opentelemetry/api/build/esnext/diag/internal/noopLogger.d.ts new file mode 100644 index 0000000..ac71ee3 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/diag/internal/noopLogger.d.ts @@ -0,0 +1,8 @@ +import { DiagLogger } from '../types'; +/** + * Returns a No-Op Diagnostic logger where all messages do nothing. + * @implements {@link DiagLogger} + * @returns {DiagLogger} + */ +export declare function createNoopDiagLogger(): DiagLogger; +//# sourceMappingURL=noopLogger.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/diag/internal/noopLogger.js b/node_modules/@opentelemetry/api/build/esnext/diag/internal/noopLogger.js new file mode 100644 index 0000000..7d5ba63 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/diag/internal/noopLogger.js @@ -0,0 +1,31 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function noopLogFunction() { } +/** + * Returns a No-Op Diagnostic logger where all messages do nothing. + * @implements {@link DiagLogger} + * @returns {DiagLogger} + */ +export function createNoopDiagLogger() { + return { + verbose: noopLogFunction, + debug: noopLogFunction, + info: noopLogFunction, + warn: noopLogFunction, + error: noopLogFunction, + }; +} +//# sourceMappingURL=noopLogger.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/diag/internal/noopLogger.js.map b/node_modules/@opentelemetry/api/build/esnext/diag/internal/noopLogger.js.map new file mode 100644 index 0000000..bf20aea --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/diag/internal/noopLogger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"noopLogger.js","sourceRoot":"","sources":["../../../../src/diag/internal/noopLogger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,SAAS,eAAe,KAAI,CAAC;AAE7B;;;;GAIG;AACH,MAAM,UAAU,oBAAoB;IAClC,OAAO;QACL,OAAO,EAAE,eAAe;QACxB,KAAK,EAAE,eAAe;QACtB,IAAI,EAAE,eAAe;QACrB,IAAI,EAAE,eAAe;QACrB,KAAK,EAAE,eAAe;KACvB,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogger } from '../types';\n\nfunction noopLogFunction() {}\n\n/**\n * Returns a No-Op Diagnostic logger where all messages do nothing.\n * @implements {@link DiagLogger}\n * @returns {DiagLogger}\n */\nexport function createNoopDiagLogger(): DiagLogger {\n return {\n verbose: noopLogFunction,\n debug: noopLogFunction,\n info: noopLogFunction,\n warn: noopLogFunction,\n error: noopLogFunction,\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/diag/types.d.ts b/node_modules/@opentelemetry/api/build/esnext/diag/types.d.ts new file mode 100644 index 0000000..e992cc5 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/diag/types.d.ts @@ -0,0 +1,100 @@ +export declare type DiagLogFunction = (message: string, ...args: unknown[]) => void; +/** + * Defines an internal diagnostic logger interface which is used to log internal diagnostic + * messages, you can set the default diagnostic logger via the {@link DiagAPI} setLogger function. + * API provided implementations include :- + * - a No-Op {@link createNoopDiagLogger} + * - a {@link DiagLogLevel} filtering wrapper {@link createLogLevelDiagLogger} + * - a general Console {@link DiagConsoleLogger} version. + */ +export interface DiagLogger { + /** Log an error scenario that was not expected and caused the requested operation to fail. */ + error: DiagLogFunction; + /** + * Log a warning scenario to inform the developer of an issues that should be investigated. + * The requested operation may or may not have succeeded or completed. + */ + warn: DiagLogFunction; + /** + * Log a general informational message, this should not affect functionality. + * This is also the default logging level so this should NOT be used for logging + * debugging level information. + */ + info: DiagLogFunction; + /** + * Log a general debug message that can be useful for identifying a failure. + * Information logged at this level may include diagnostic details that would + * help identify a failure scenario. + * For example: Logging the order of execution of async operations. + */ + debug: DiagLogFunction; + /** + * Log a detailed (verbose) trace level logging that can be used to identify failures + * where debug level logging would be insufficient, this level of tracing can include + * input and output parameters and as such may include PII information passing through + * the API. As such it is recommended that this level of tracing should not be enabled + * in a production environment. + */ + verbose: DiagLogFunction; +} +/** + * Defines the available internal logging levels for the diagnostic logger, the numeric values + * of the levels are defined to match the original values from the initial LogLevel to avoid + * compatibility/migration issues for any implementation that assume the numeric ordering. + */ +export declare enum DiagLogLevel { + /** Diagnostic Logging level setting to disable all logging (except and forced logs) */ + NONE = 0, + /** Identifies an error scenario */ + ERROR = 30, + /** Identifies a warning scenario */ + WARN = 50, + /** General informational log message */ + INFO = 60, + /** General debug log message */ + DEBUG = 70, + /** + * Detailed trace level logging should only be used for development, should only be set + * in a development environment. + */ + VERBOSE = 80, + /** Used to set the logging level to include all logging */ + ALL = 9999 +} +/** + * Defines options for ComponentLogger + */ +export interface ComponentLoggerOptions { + namespace: string; +} +export interface DiagLoggerOptions { + /** + * The {@link DiagLogLevel} used to filter logs sent to the logger. + * + * @defaultValue DiagLogLevel.INFO + */ + logLevel?: DiagLogLevel; + /** + * Setting this value to `true` will suppress the warning message normally emitted when registering a logger when another logger is already registered. + */ + suppressOverrideMessage?: boolean; +} +export interface DiagLoggerApi { + /** + * Set the global DiagLogger and DiagLogLevel. + * If a global diag logger is already set, this will override it. + * + * @param logger - The {@link DiagLogger} instance to set as the default logger. + * @param options - A {@link DiagLoggerOptions} object. If not provided, default values will be set. + * @returns `true` if the logger was successfully registered, else `false` + */ + setLogger(logger: DiagLogger, options?: DiagLoggerOptions): boolean; + /** + * + * @param logger - The {@link DiagLogger} instance to set as the default logger. + * @param logLevel - The {@link DiagLogLevel} used to filter logs sent to the logger. If not provided it will default to {@link DiagLogLevel.INFO}. + * @returns `true` if the logger was successfully registered, else `false` + */ + setLogger(logger: DiagLogger, logLevel?: DiagLogLevel): boolean; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/diag/types.js b/node_modules/@opentelemetry/api/build/esnext/diag/types.js new file mode 100644 index 0000000..306585e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/diag/types.js @@ -0,0 +1,41 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Defines the available internal logging levels for the diagnostic logger, the numeric values + * of the levels are defined to match the original values from the initial LogLevel to avoid + * compatibility/migration issues for any implementation that assume the numeric ordering. + */ +export var DiagLogLevel; +(function (DiagLogLevel) { + /** Diagnostic Logging level setting to disable all logging (except and forced logs) */ + DiagLogLevel[DiagLogLevel["NONE"] = 0] = "NONE"; + /** Identifies an error scenario */ + DiagLogLevel[DiagLogLevel["ERROR"] = 30] = "ERROR"; + /** Identifies a warning scenario */ + DiagLogLevel[DiagLogLevel["WARN"] = 50] = "WARN"; + /** General informational log message */ + DiagLogLevel[DiagLogLevel["INFO"] = 60] = "INFO"; + /** General debug log message */ + DiagLogLevel[DiagLogLevel["DEBUG"] = 70] = "DEBUG"; + /** + * Detailed trace level logging should only be used for development, should only be set + * in a development environment. + */ + DiagLogLevel[DiagLogLevel["VERBOSE"] = 80] = "VERBOSE"; + /** Used to set the logging level to include all logging */ + DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL"; +})(DiagLogLevel || (DiagLogLevel = {})); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/diag/types.js.map b/node_modules/@opentelemetry/api/build/esnext/diag/types.js.map new file mode 100644 index 0000000..6578cce --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/diag/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/diag/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AA+CH;;;;GAIG;AACH,MAAM,CAAN,IAAY,YAwBX;AAxBD,WAAY,YAAY;IACtB,uFAAuF;IACvF,+CAAQ,CAAA;IAER,mCAAmC;IACnC,kDAAU,CAAA;IAEV,oCAAoC;IACpC,gDAAS,CAAA;IAET,wCAAwC;IACxC,gDAAS,CAAA;IAET,gCAAgC;IAChC,kDAAU,CAAA;IAEV;;;OAGG;IACH,sDAAY,CAAA;IAEZ,2DAA2D;IAC3D,gDAAU,CAAA;AACZ,CAAC,EAxBW,YAAY,KAAZ,YAAY,QAwBvB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type DiagLogFunction = (message: string, ...args: unknown[]) => void;\n\n/**\n * Defines an internal diagnostic logger interface which is used to log internal diagnostic\n * messages, you can set the default diagnostic logger via the {@link DiagAPI} setLogger function.\n * API provided implementations include :-\n * - a No-Op {@link createNoopDiagLogger}\n * - a {@link DiagLogLevel} filtering wrapper {@link createLogLevelDiagLogger}\n * - a general Console {@link DiagConsoleLogger} version.\n */\nexport interface DiagLogger {\n /** Log an error scenario that was not expected and caused the requested operation to fail. */\n error: DiagLogFunction;\n\n /**\n * Log a warning scenario to inform the developer of an issues that should be investigated.\n * The requested operation may or may not have succeeded or completed.\n */\n warn: DiagLogFunction;\n\n /**\n * Log a general informational message, this should not affect functionality.\n * This is also the default logging level so this should NOT be used for logging\n * debugging level information.\n */\n info: DiagLogFunction;\n\n /**\n * Log a general debug message that can be useful for identifying a failure.\n * Information logged at this level may include diagnostic details that would\n * help identify a failure scenario.\n * For example: Logging the order of execution of async operations.\n */\n debug: DiagLogFunction;\n\n /**\n * Log a detailed (verbose) trace level logging that can be used to identify failures\n * where debug level logging would be insufficient, this level of tracing can include\n * input and output parameters and as such may include PII information passing through\n * the API. As such it is recommended that this level of tracing should not be enabled\n * in a production environment.\n */\n verbose: DiagLogFunction;\n}\n\n/**\n * Defines the available internal logging levels for the diagnostic logger, the numeric values\n * of the levels are defined to match the original values from the initial LogLevel to avoid\n * compatibility/migration issues for any implementation that assume the numeric ordering.\n */\nexport enum DiagLogLevel {\n /** Diagnostic Logging level setting to disable all logging (except and forced logs) */\n NONE = 0,\n\n /** Identifies an error scenario */\n ERROR = 30,\n\n /** Identifies a warning scenario */\n WARN = 50,\n\n /** General informational log message */\n INFO = 60,\n\n /** General debug log message */\n DEBUG = 70,\n\n /**\n * Detailed trace level logging should only be used for development, should only be set\n * in a development environment.\n */\n VERBOSE = 80,\n\n /** Used to set the logging level to include all logging */\n ALL = 9999,\n}\n\n/**\n * Defines options for ComponentLogger\n */\nexport interface ComponentLoggerOptions {\n namespace: string;\n}\n\nexport interface DiagLoggerOptions {\n /**\n * The {@link DiagLogLevel} used to filter logs sent to the logger.\n *\n * @defaultValue DiagLogLevel.INFO\n */\n logLevel?: DiagLogLevel;\n\n /**\n * Setting this value to `true` will suppress the warning message normally emitted when registering a logger when another logger is already registered.\n */\n suppressOverrideMessage?: boolean;\n}\n\nexport interface DiagLoggerApi {\n /**\n * Set the global DiagLogger and DiagLogLevel.\n * If a global diag logger is already set, this will override it.\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param options - A {@link DiagLoggerOptions} object. If not provided, default values will be set.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, options?: DiagLoggerOptions): boolean;\n\n /**\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param logLevel - The {@link DiagLogLevel} used to filter logs sent to the logger. If not provided it will default to {@link DiagLogLevel.INFO}.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, logLevel?: DiagLogLevel): boolean;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/experimental/index.d.ts b/node_modules/@opentelemetry/api/build/esnext/experimental/index.d.ts new file mode 100644 index 0000000..bec3965 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/experimental/index.d.ts @@ -0,0 +1,3 @@ +export { wrapTracer, SugaredTracer } from './trace/SugaredTracer'; +export { SugaredSpanOptions } from './trace/SugaredOptions'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/experimental/index.js b/node_modules/@opentelemetry/api/build/esnext/experimental/index.js new file mode 100644 index 0000000..8400e49 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/experimental/index.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { wrapTracer, SugaredTracer } from './trace/SugaredTracer'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/experimental/index.js.map b/node_modules/@opentelemetry/api/build/esnext/experimental/index.js.map new file mode 100644 index 0000000..d1699d9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/experimental/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/experimental/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport { wrapTracer, SugaredTracer } from './trace/SugaredTracer';\nexport { SugaredSpanOptions } from './trace/SugaredOptions';\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredOptions.d.ts b/node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredOptions.d.ts new file mode 100644 index 0000000..89040af --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredOptions.d.ts @@ -0,0 +1,13 @@ +import { Span, SpanOptions } from '../../'; +/** + * Options needed for span creation + */ +export interface SugaredSpanOptions extends SpanOptions { + /** + * function to overwrite default exception behavior to record the exception. No exceptions should be thrown in the function. + * @param e Error which triggered this exception + * @param span current span from context + */ + onException?: (e: Error, span: Span) => void; +} +//# sourceMappingURL=SugaredOptions.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredOptions.js b/node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredOptions.js new file mode 100644 index 0000000..0c6a2bd --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredOptions.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=SugaredOptions.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredOptions.js.map b/node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredOptions.js.map new file mode 100644 index 0000000..2a18a56 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredOptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SugaredOptions.js","sourceRoot":"","sources":["../../../../src/experimental/trace/SugaredOptions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Span, SpanOptions } from '../../';\n\n/**\n * Options needed for span creation\n */\nexport interface SugaredSpanOptions extends SpanOptions {\n /**\n * function to overwrite default exception behavior to record the exception. No exceptions should be thrown in the function.\n * @param e Error which triggered this exception\n * @param span current span from context\n */\n onException?: (e: Error, span: Span) => void;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredTracer.d.ts b/node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredTracer.d.ts new file mode 100644 index 0000000..1ba7da9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredTracer.d.ts @@ -0,0 +1,64 @@ +import { SugaredSpanOptions } from './SugaredOptions'; +import { Context, Span, Tracer } from '../../'; +/** + * return a new SugaredTracer created from the supplied one + * @param tracer + */ +export declare function wrapTracer(tracer: Tracer): SugaredTracer; +export declare class SugaredTracer implements Tracer { + private readonly _tracer; + constructor(tracer: Tracer); + startActiveSpan: Tracer['startActiveSpan']; + startSpan: Tracer['startSpan']; + /** + * Starts a new {@link Span} and calls the given function passing it the + * created span as first argument. + * Additionally, the new span gets set in context and this context is activated + * for the duration of the function call. + * The span will be closed after the function has executed. + * If an exception occurs, it is recorded, the status is set to ERROR and the exception is rethrown. + * + * @param name The name of the span + * @param [options] SugaredSpanOptions used for span creation + * @param [context] Context to use to extract parent + * @param fn function called in the context of the span and receives the newly created span as an argument + * @returns return value of fn + * @example + * const something = tracer.withActiveSpan('op', span => { + * // do some work + * }); + * @example + * const something = await tracer.withActiveSpan('op', span => { + * // do some async work + * }); + */ + withActiveSpan ReturnType>(name: string, fn: F): ReturnType; + withActiveSpan ReturnType>(name: string, options: SugaredSpanOptions, fn: F): ReturnType; + withActiveSpan ReturnType>(name: string, options: SugaredSpanOptions, context: Context, fn: F): ReturnType; + /** + * Starts a new {@link Span} and ends it after execution of fn without setting it on context. + * The span will be closed after the function has executed. + * If an exception occurs, it is recorded, the status is et to ERROR and rethrown. + * + * This method does NOT modify the current Context. + * + * @param name The name of the span + * @param [options] SugaredSpanOptions used for span creation + * @param [context] Context to use to extract parent + * @param fn function called in the context of the span and receives the newly created span as an argument + * @returns Span The newly created span + * @example + * const something = tracer.withSpan('op', span => { + * // do some work + * }); + * @example + * const something = await tracer.withSpan('op', span => { + * // do some async work + * }); + */ + withSpan ReturnType>(name: string, fn: F): ReturnType; + withSpan ReturnType>(name: string, options: SugaredSpanOptions, fn: F): ReturnType; + withSpan ReturnType>(name: string, options: SugaredSpanOptions, context: Context, fn: F): ReturnType; + withSpan ReturnType>(name: string, options: SugaredSpanOptions, context: Context, fn: F): ReturnType; +} +//# sourceMappingURL=SugaredTracer.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredTracer.js b/node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredTracer.js new file mode 100644 index 0000000..a1edc7f --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredTracer.js @@ -0,0 +1,88 @@ +import { context, SpanStatusCode } from '../../'; +const defaultOnException = (e, span) => { + span.recordException(e); + span.setStatus({ + code: SpanStatusCode.ERROR, + }); +}; +/** + * return a new SugaredTracer created from the supplied one + * @param tracer + */ +export function wrapTracer(tracer) { + return new SugaredTracer(tracer); +} +export class SugaredTracer { + constructor(tracer) { + this._tracer = tracer; + this.startSpan = tracer.startSpan.bind(this._tracer); + this.startActiveSpan = tracer.startActiveSpan.bind(this._tracer); + } + withActiveSpan(name, arg2, arg3, arg4) { + const { opts, ctx, fn } = massageParams(arg2, arg3, arg4); + return this._tracer.startActiveSpan(name, opts, ctx, (span) => handleFn(span, opts, fn)); + } + withSpan(name, arg2, arg3, arg4) { + const { opts, ctx, fn } = massageParams(arg2, arg3, arg4); + const span = this._tracer.startSpan(name, opts, ctx); + return handleFn(span, opts, fn); + } +} +/** + * Massages parameters of withSpan and withActiveSpan to allow signature overwrites + * @param arg + * @param arg2 + * @param arg3 + */ +function massageParams(arg, arg2, arg3) { + let opts; + let ctx; + let fn; + if (!arg2 && !arg3) { + fn = arg; + } + else if (!arg3) { + opts = arg; + fn = arg2; + } + else { + opts = arg; + ctx = arg2; + fn = arg3; + } + opts = opts !== null && opts !== void 0 ? opts : {}; + ctx = ctx !== null && ctx !== void 0 ? ctx : context.active(); + return { opts, ctx, fn }; +} +/** + * Executes fn, returns results and runs onException in the case of exception to allow overwriting of error handling + * @param span + * @param opts + * @param fn + */ +function handleFn(span, opts, fn) { + var _a; + const onException = (_a = opts.onException) !== null && _a !== void 0 ? _a : defaultOnException; + const errorHandler = (e) => { + onException(e, span); + span.end(); + throw e; + }; + try { + const ret = fn(span); + // if fn is an async function, attach a recordException and spanEnd callback to the promise + if (typeof (ret === null || ret === void 0 ? void 0 : ret.then) === 'function') { + return ret.then(val => { + span.end(); + return val; + }, errorHandler); + } + span.end(); + return ret; + } + catch (e) { + // add throw to signal the compiler that this will throw in the inner scope + throw errorHandler(e); + } +} +//# sourceMappingURL=SugaredTracer.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredTracer.js.map b/node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredTracer.js.map new file mode 100644 index 0000000..600ea54 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/experimental/trace/SugaredTracer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SugaredTracer.js","sourceRoot":"","sources":["../../../../src/experimental/trace/SugaredTracer.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,OAAO,EAAiB,cAAc,EAAU,MAAM,QAAQ,CAAC;AAExE,MAAM,kBAAkB,GAAG,CAAC,CAAQ,EAAE,IAAU,EAAE,EAAE;IAClD,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC;IACxB,IAAI,CAAC,SAAS,CAAC;QACb,IAAI,EAAE,cAAc,CAAC,KAAK;KAC3B,CAAC,CAAC;AACL,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAC,MAAc;IACvC,OAAO,IAAI,aAAa,CAAC,MAAM,CAAC,CAAC;AACnC,CAAC;AAED,MAAM,OAAO,aAAa;IAGxB,YAAY,MAAc;QACxB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACrD,IAAI,CAAC,eAAe,GAAG,MAAM,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACnE,CAAC;IA0CD,cAAc,CACZ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G,GAAG,aAAH,GAAG,cAAH,GAAG,GAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IAE9B,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC;AAC3B,CAAC;AAED;;;;;GAKG;AACH,SAAS,QAAQ,CACf,IAAU,EACV,IAAwB,EACxB,EAAK;;IAEL,MAAM,WAAW,GAAG,MAAA,IAAI,CAAC,WAAW,mCAAI,kBAAkB,CAAC;IAC3D,MAAM,YAAY,GAAG,CAAC,CAAQ,EAAE,EAAE;QAChC,WAAW,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;QACrB,IAAI,CAAC,GAAG,EAAE,CAAC;QACX,MAAM,CAAC,CAAC;IACV,CAAC,CAAC;IAEF,IAAI;QACF,MAAM,GAAG,GAAG,EAAE,CAAC,IAAI,CAA2B,CAAC;QAC/C,2FAA2F;QAC3F,IAAI,OAAO,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,IAAI,CAAA,KAAK,UAAU,EAAE;YACnC,OAAO,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;gBACpB,IAAI,CAAC,GAAG,EAAE,CAAC;gBACX,OAAO,GAAG,CAAC;YACb,CAAC,EAAE,YAAY,CAAkB,CAAC;SACnC;QACD,IAAI,CAAC,GAAG,EAAE,CAAC;QACX,OAAO,GAAoB,CAAC;KAC7B;IAAC,OAAO,CAAC,EAAE;QACV,2EAA2E;QAC3E,MAAM,YAAY,CAAC,CAAC,CAAC,CAAC;KACvB;AACH,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { SugaredSpanOptions } from './SugaredOptions';\nimport { context, Context, Span, SpanStatusCode, Tracer } from '../../';\n\nconst defaultOnException = (e: Error, span: Span) => {\n span.recordException(e);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n });\n};\n\n/**\n * return a new SugaredTracer created from the supplied one\n * @param tracer\n */\nexport function wrapTracer(tracer: Tracer): SugaredTracer {\n return new SugaredTracer(tracer);\n}\n\nexport class SugaredTracer implements Tracer {\n private readonly _tracer: Tracer;\n\n constructor(tracer: Tracer) {\n this._tracer = tracer;\n this.startSpan = tracer.startSpan.bind(this._tracer);\n this.startActiveSpan = tracer.startActiveSpan.bind(this._tracer);\n }\n\n startActiveSpan: Tracer['startActiveSpan'];\n startSpan: Tracer['startSpan'];\n\n /**\n * Starts a new {@link Span} and calls the given function passing it the\n * created span as first argument.\n * Additionally, the new span gets set in context and this context is activated\n * for the duration of the function call.\n * The span will be closed after the function has executed.\n * If an exception occurs, it is recorded, the status is set to ERROR and the exception is rethrown.\n *\n * @param name The name of the span\n * @param [options] SugaredSpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns return value of fn\n * @example\n * const something = tracer.withActiveSpan('op', span => {\n * // do some work\n * });\n * @example\n * const something = await tracer.withActiveSpan('op', span => {\n * // do some async work\n * });\n */\n withActiveSpan ReturnType>(\n name: string,\n fn: F\n ): ReturnType;\n withActiveSpan ReturnType>(\n name: string,\n options: SugaredSpanOptions,\n fn: F\n ): ReturnType;\n withActiveSpan ReturnType>(\n name: string,\n options: SugaredSpanOptions,\n context: Context,\n fn: F\n ): ReturnType;\n withActiveSpan ReturnType>(\n name: string,\n arg2: F | SugaredSpanOptions,\n arg3?: F | Context,\n arg4?: F\n ): ReturnType {\n const { opts, ctx, fn } = massageParams(arg2, arg3, arg4);\n\n return this._tracer.startActiveSpan(name, opts, ctx, (span: Span) =>\n handleFn(span, opts, fn)\n ) as ReturnType;\n }\n\n /**\n * Starts a new {@link Span} and ends it after execution of fn without setting it on context.\n * The span will be closed after the function has executed.\n * If an exception occurs, it is recorded, the status is et to ERROR and rethrown.\n *\n * This method does NOT modify the current Context.\n *\n * @param name The name of the span\n * @param [options] SugaredSpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns Span The newly created span\n * @example\n * const something = tracer.withSpan('op', span => {\n * // do some work\n * });\n * @example\n * const something = await tracer.withSpan('op', span => {\n * // do some async work\n * });\n */\n withSpan ReturnType>(\n name: string,\n fn: F\n ): ReturnType;\n withSpan ReturnType>(\n name: string,\n options: SugaredSpanOptions,\n fn: F\n ): ReturnType;\n withSpan ReturnType>(\n name: string,\n options: SugaredSpanOptions,\n context: Context,\n fn: F\n ): ReturnType;\n withSpan ReturnType>(\n name: string,\n options: SugaredSpanOptions,\n context: Context,\n fn: F\n ): ReturnType;\n withSpan ReturnType>(\n name: string,\n arg2: SugaredSpanOptions | F,\n arg3?: Context | F,\n arg4?: F\n ): ReturnType {\n const { opts, ctx, fn } = massageParams(arg2, arg3, arg4);\n\n const span = this._tracer.startSpan(name, opts, ctx);\n return handleFn(span, opts, fn) as ReturnType;\n }\n}\n\n/**\n * Massages parameters of withSpan and withActiveSpan to allow signature overwrites\n * @param arg\n * @param arg2\n * @param arg3\n */\nfunction massageParams ReturnType>(\n arg: F | SugaredSpanOptions,\n arg2?: F | Context,\n arg3?: F\n) {\n let opts: SugaredSpanOptions | undefined;\n let ctx: Context | undefined;\n let fn: F;\n\n if (!arg2 && !arg3) {\n fn = arg as F;\n } else if (!arg3) {\n opts = arg as SugaredSpanOptions;\n fn = arg2 as F;\n } else {\n opts = arg as SugaredSpanOptions;\n ctx = arg2 as Context;\n fn = arg3 as F;\n }\n opts = opts ?? {};\n ctx = ctx ?? context.active();\n\n return { opts, ctx, fn };\n}\n\n/**\n * Executes fn, returns results and runs onException in the case of exception to allow overwriting of error handling\n * @param span\n * @param opts\n * @param fn\n */\nfunction handleFn ReturnType>(\n span: Span,\n opts: SugaredSpanOptions,\n fn: F\n): ReturnType {\n const onException = opts.onException ?? defaultOnException;\n const errorHandler = (e: Error) => {\n onException(e, span);\n span.end();\n throw e;\n };\n\n try {\n const ret = fn(span) as Promise>;\n // if fn is an async function, attach a recordException and spanEnd callback to the promise\n if (typeof ret?.then === 'function') {\n return ret.then(val => {\n span.end();\n return val;\n }, errorHandler) as ReturnType;\n }\n span.end();\n return ret as ReturnType;\n } catch (e) {\n // add throw to signal the compiler that this will throw in the inner scope\n throw errorHandler(e);\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/index.d.ts b/node_modules/@opentelemetry/api/build/esnext/index.d.ts new file mode 100644 index 0000000..eea88f2 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/index.d.ts @@ -0,0 +1,54 @@ +export { BaggageEntry, BaggageEntryMetadata, Baggage } from './baggage/types'; +export { baggageEntryMetadataFromString } from './baggage/utils'; +export { Exception } from './common/Exception'; +export { HrTime, TimeInput } from './common/Time'; +export { Attributes, AttributeValue } from './common/Attributes'; +export { createContextKey, ROOT_CONTEXT } from './context/context'; +export { Context, ContextManager } from './context/types'; +export type { ContextAPI } from './api/context'; +export { DiagConsoleLogger } from './diag/consoleLogger'; +export { DiagLogFunction, DiagLogger, DiagLogLevel, ComponentLoggerOptions, DiagLoggerOptions, } from './diag/types'; +export type { DiagAPI } from './api/diag'; +export { createNoopMeter } from './metrics/NoopMeter'; +export { MeterOptions, Meter } from './metrics/Meter'; +export { MeterProvider } from './metrics/MeterProvider'; +export { ValueType, Counter, Gauge, Histogram, MetricOptions, Observable, ObservableCounter, ObservableGauge, ObservableUpDownCounter, UpDownCounter, BatchObservableCallback, MetricAdvice, MetricAttributes, MetricAttributeValue, ObservableCallback, } from './metrics/Metric'; +export { BatchObservableResult, ObservableResult, } from './metrics/ObservableResult'; +export type { MetricsAPI } from './api/metrics'; +export { TextMapPropagator, TextMapSetter, TextMapGetter, defaultTextMapGetter, defaultTextMapSetter, } from './propagation/TextMapPropagator'; +export type { PropagationAPI } from './api/propagation'; +export { SpanAttributes, SpanAttributeValue } from './trace/attributes'; +export { Link } from './trace/link'; +export { ProxyTracer, TracerDelegator } from './trace/ProxyTracer'; +export { ProxyTracerProvider } from './trace/ProxyTracerProvider'; +export { Sampler } from './trace/Sampler'; +export { SamplingDecision, SamplingResult } from './trace/SamplingResult'; +export { SpanContext } from './trace/span_context'; +export { SpanKind } from './trace/span_kind'; +export { Span } from './trace/span'; +export { SpanOptions } from './trace/SpanOptions'; +export { SpanStatus, SpanStatusCode } from './trace/status'; +export { TraceFlags } from './trace/trace_flags'; +export { TraceState } from './trace/trace_state'; +export { createTraceState } from './trace/internal/utils'; +export { TracerProvider } from './trace/tracer_provider'; +export { Tracer } from './trace/tracer'; +export { TracerOptions } from './trace/tracer_options'; +export { isSpanContextValid, isValidTraceId, isValidSpanId, } from './trace/spancontext-utils'; +export { INVALID_SPANID, INVALID_TRACEID, INVALID_SPAN_CONTEXT, } from './trace/invalid-span-constants'; +export type { TraceAPI } from './api/trace'; +import { context } from './context-api'; +import { diag } from './diag-api'; +import { metrics } from './metrics-api'; +import { propagation } from './propagation-api'; +import { trace } from './trace-api'; +export { context, diag, metrics, propagation, trace }; +declare const _default: { + context: import("./api/context").ContextAPI; + diag: import("./api/diag").DiagAPI; + metrics: import("./api/metrics").MetricsAPI; + propagation: import("./api/propagation").PropagationAPI; + trace: import("./api/trace").TraceAPI; +}; +export default _default; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/index.js b/node_modules/@opentelemetry/api/build/esnext/index.js new file mode 100644 index 0000000..123dc4d --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/index.js @@ -0,0 +1,53 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { baggageEntryMetadataFromString } from './baggage/utils'; +// Context APIs +export { createContextKey, ROOT_CONTEXT } from './context/context'; +// Diag APIs +export { DiagConsoleLogger } from './diag/consoleLogger'; +export { DiagLogLevel, } from './diag/types'; +// Metrics APIs +export { createNoopMeter } from './metrics/NoopMeter'; +export { ValueType, } from './metrics/Metric'; +// Propagation APIs +export { defaultTextMapGetter, defaultTextMapSetter, } from './propagation/TextMapPropagator'; +export { ProxyTracer } from './trace/ProxyTracer'; +export { ProxyTracerProvider } from './trace/ProxyTracerProvider'; +export { SamplingDecision } from './trace/SamplingResult'; +export { SpanKind } from './trace/span_kind'; +export { SpanStatusCode } from './trace/status'; +export { TraceFlags } from './trace/trace_flags'; +export { createTraceState } from './trace/internal/utils'; +export { isSpanContextValid, isValidTraceId, isValidSpanId, } from './trace/spancontext-utils'; +export { INVALID_SPANID, INVALID_TRACEID, INVALID_SPAN_CONTEXT, } from './trace/invalid-span-constants'; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +import { context } from './context-api'; +import { diag } from './diag-api'; +import { metrics } from './metrics-api'; +import { propagation } from './propagation-api'; +import { trace } from './trace-api'; +// Named export. +export { context, diag, metrics, propagation, trace }; +// Default export. +export default { + context, + diag, + metrics, + propagation, + trace, +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/index.js.map b/node_modules/@opentelemetry/api/build/esnext/index.js.map new file mode 100644 index 0000000..d53dae4 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE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ChB,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,CAAC;AACtD,kBAAkB;AAClB,eAAe;IACb,OAAO;IACP,IAAI;IACJ,OAAO;IACP,WAAW;IACX,KAAK;CACN,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { BaggageEntry, BaggageEntryMetadata, Baggage } from './baggage/types';\nexport { baggageEntryMetadataFromString } from './baggage/utils';\nexport { Exception } from './common/Exception';\nexport { HrTime, TimeInput } from './common/Time';\nexport { Attributes, AttributeValue } from './common/Attributes';\n\n// Context APIs\nexport { createContextKey, ROOT_CONTEXT } from './context/context';\nexport { Context, ContextManager } from './context/types';\nexport type { ContextAPI } from './api/context';\n\n// Diag APIs\nexport { DiagConsoleLogger } from './diag/consoleLogger';\nexport {\n DiagLogFunction,\n DiagLogger,\n DiagLogLevel,\n ComponentLoggerOptions,\n DiagLoggerOptions,\n} from './diag/types';\nexport type { DiagAPI } from './api/diag';\n\n// Metrics APIs\nexport { createNoopMeter } from './metrics/NoopMeter';\nexport { MeterOptions, Meter } from './metrics/Meter';\nexport { MeterProvider } from './metrics/MeterProvider';\nexport {\n ValueType,\n Counter,\n Gauge,\n Histogram,\n MetricOptions,\n Observable,\n ObservableCounter,\n ObservableGauge,\n ObservableUpDownCounter,\n UpDownCounter,\n BatchObservableCallback,\n MetricAdvice,\n MetricAttributes,\n MetricAttributeValue,\n ObservableCallback,\n} from './metrics/Metric';\nexport {\n BatchObservableResult,\n ObservableResult,\n} from './metrics/ObservableResult';\nexport type { MetricsAPI } from './api/metrics';\n\n// Propagation APIs\nexport {\n TextMapPropagator,\n TextMapSetter,\n TextMapGetter,\n defaultTextMapGetter,\n defaultTextMapSetter,\n} from './propagation/TextMapPropagator';\nexport type { PropagationAPI } from './api/propagation';\n\n// Trace APIs\nexport { SpanAttributes, SpanAttributeValue } from './trace/attributes';\nexport { Link } from './trace/link';\nexport { ProxyTracer, TracerDelegator } from './trace/ProxyTracer';\nexport { ProxyTracerProvider } from './trace/ProxyTracerProvider';\nexport { Sampler } from './trace/Sampler';\nexport { SamplingDecision, SamplingResult } from './trace/SamplingResult';\nexport { SpanContext } from './trace/span_context';\nexport { SpanKind } from './trace/span_kind';\nexport { Span } from './trace/span';\nexport { SpanOptions } from './trace/SpanOptions';\nexport { SpanStatus, SpanStatusCode } from './trace/status';\nexport { TraceFlags } from './trace/trace_flags';\nexport { TraceState } from './trace/trace_state';\nexport { createTraceState } from './trace/internal/utils';\nexport { TracerProvider } from './trace/tracer_provider';\nexport { Tracer } from './trace/tracer';\nexport { TracerOptions } from './trace/tracer_options';\nexport {\n isSpanContextValid,\n isValidTraceId,\n isValidSpanId,\n} from './trace/spancontext-utils';\nexport {\n INVALID_SPANID,\n INVALID_TRACEID,\n INVALID_SPAN_CONTEXT,\n} from './trace/invalid-span-constants';\nexport type { TraceAPI } from './api/trace';\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { context } from './context-api';\nimport { diag } from './diag-api';\nimport { metrics } from './metrics-api';\nimport { propagation } from './propagation-api';\nimport { trace } from './trace-api';\n\n// Named export.\nexport { context, diag, metrics, propagation, trace };\n// Default export.\nexport default {\n context,\n diag,\n metrics,\n propagation,\n trace,\n};\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/internal/global-utils.d.ts b/node_modules/@opentelemetry/api/build/esnext/internal/global-utils.d.ts new file mode 100644 index 0000000..320db97 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/internal/global-utils.d.ts @@ -0,0 +1,18 @@ +import { MeterProvider } from '../metrics/MeterProvider'; +import { ContextManager } from '../context/types'; +import { DiagLogger } from '../diag/types'; +import { TextMapPropagator } from '../propagation/TextMapPropagator'; +import type { TracerProvider } from '../trace/tracer_provider'; +export declare function registerGlobal(type: Type, instance: OTelGlobalAPI[Type], diag: DiagLogger, allowOverride?: boolean): boolean; +export declare function getGlobal(type: Type): OTelGlobalAPI[Type] | undefined; +export declare function unregisterGlobal(type: keyof OTelGlobalAPI, diag: DiagLogger): void; +declare type OTelGlobalAPI = { + version: string; + diag?: DiagLogger; + trace?: TracerProvider; + context?: ContextManager; + metrics?: MeterProvider; + propagation?: TextMapPropagator; +}; +export {}; +//# sourceMappingURL=global-utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/internal/global-utils.js b/node_modules/@opentelemetry/api/build/esnext/internal/global-utils.js new file mode 100644 index 0000000..acdd185 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/internal/global-utils.js @@ -0,0 +1,58 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { _globalThis } from '../platform'; +import { VERSION } from '../version'; +import { isCompatible } from './semver'; +const major = VERSION.split('.')[0]; +const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); +const _global = _globalThis; +export function registerGlobal(type, instance, diag, allowOverride = false) { + var _a; + const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { + version: VERSION, + }); + if (!allowOverride && api[type]) { + // already registered an API of this type + const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`); + diag.error(err.stack || err.message); + return false; + } + if (api.version !== VERSION) { + // All registered APIs must be of the same version exactly + const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION}`); + diag.error(err.stack || err.message); + return false; + } + api[type] = instance; + diag.debug(`@opentelemetry/api: Registered a global for ${type} v${VERSION}.`); + return true; +} +export function getGlobal(type) { + var _a, _b; + const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; + if (!globalVersion || !isCompatible(globalVersion)) { + return; + } + return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; +} +export function unregisterGlobal(type, diag) { + diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${VERSION}.`); + const api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; + if (api) { + delete api[type]; + } +} +//# sourceMappingURL=global-utils.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/internal/global-utils.js.map b/node_modules/@opentelemetry/api/build/esnext/internal/global-utils.js.map new file mode 100644 index 0000000..6c95b12 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/internal/global-utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"global-utils.js","sourceRoot":"","sources":["../../../src/internal/global-utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAKH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAG1C,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAExC,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AACpC,MAAM,4BAA4B,GAAG,MAAM,CAAC,GAAG,CAC7C,wBAAwB,KAAK,EAAE,CAChC,CAAC;A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,CAAC,CAAC;AACvD,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,IAAyB,EAAE,IAAgB;IAC1E,IAAI,CAAC,KAAK,CACR,kDAAkD,IAAI,KAAK,OAAO,GAAG,CACtE,CAAC;IACF,MAAM,GAAG,GAAG,OAAO,CAAC,4BAA4B,CAAC,CAAC;IAElD,IAAI,GAAG,EAAE;QACP,OAAO,GAAG,CAAC,IAAI,CAAC,CAAC;KAClB;AACH,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MeterProvider } from '../metrics/MeterProvider';\nimport { ContextManager } from '../context/types';\nimport { DiagLogger } from '../diag/types';\nimport { _globalThis } from '../platform';\nimport { TextMapPropagator } from '../propagation/TextMapPropagator';\nimport type { TracerProvider } from '../trace/tracer_provider';\nimport { VERSION } from '../version';\nimport { isCompatible } from './semver';\n\nconst major = VERSION.split('.')[0];\nconst GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(\n `opentelemetry.js.api.${major}`\n);\n\nconst _global = _globalThis as OTelGlobal;\n\nexport function registerGlobal(\n type: Type,\n instance: OTelGlobalAPI[Type],\n diag: DiagLogger,\n allowOverride = false\n): boolean {\n const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = _global[\n GLOBAL_OPENTELEMETRY_API_KEY\n ] ?? {\n version: VERSION,\n });\n\n if (!allowOverride && api[type]) {\n // already registered an API of this type\n const err = new Error(\n `@opentelemetry/api: Attempted duplicate registration of API: ${type}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n if (api.version !== VERSION) {\n // All registered APIs must be of the same version exactly\n const err = new Error(\n `@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n api[type] = instance;\n diag.debug(\n `@opentelemetry/api: Registered a global for ${type} v${VERSION}.`\n );\n\n return true;\n}\n\nexport function getGlobal(\n type: Type\n): OTelGlobalAPI[Type] | undefined {\n const globalVersion = _global[GLOBAL_OPENTELEMETRY_API_KEY]?.version;\n if (!globalVersion || !isCompatible(globalVersion)) {\n return;\n }\n return _global[GLOBAL_OPENTELEMETRY_API_KEY]?.[type];\n}\n\nexport function unregisterGlobal(type: keyof OTelGlobalAPI, diag: DiagLogger) {\n diag.debug(\n `@opentelemetry/api: Unregistering a global for ${type} v${VERSION}.`\n );\n const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];\n\n if (api) {\n delete api[type];\n }\n}\n\ntype OTelGlobal = {\n [GLOBAL_OPENTELEMETRY_API_KEY]?: OTelGlobalAPI;\n};\n\ntype OTelGlobalAPI = {\n version: string;\n\n diag?: DiagLogger;\n trace?: TracerProvider;\n context?: ContextManager;\n metrics?: MeterProvider;\n propagation?: TextMapPropagator;\n};\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/internal/semver.d.ts b/node_modules/@opentelemetry/api/build/esnext/internal/semver.d.ts new file mode 100644 index 0000000..d9f4259 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/internal/semver.d.ts @@ -0,0 +1,34 @@ +/** + * Create a function to test an API version to see if it is compatible with the provided ownVersion. + * + * The returned function has the following semantics: + * - Exact match is always compatible + * - Major versions must match exactly + * - 1.x package cannot use global 2.x package + * - 2.x package cannot use global 1.x package + * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API + * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects + * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 + * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor + * - Patch and build tag differences are not considered at this time + * + * @param ownVersion version which should be checked against + */ +export declare function _makeCompatibilityCheck(ownVersion: string): (globalVersion: string) => boolean; +/** + * Test an API version to see if it is compatible with this API. + * + * - Exact match is always compatible + * - Major versions must match exactly + * - 1.x package cannot use global 2.x package + * - 2.x package cannot use global 1.x package + * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API + * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects + * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 + * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor + * - Patch and build tag differences are not considered at this time + * + * @param version version of the API requesting an instance of the global API + */ +export declare const isCompatible: (globalVersion: string) => boolean; +//# sourceMappingURL=semver.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/internal/semver.js b/node_modules/@opentelemetry/api/build/esnext/internal/semver.js new file mode 100644 index 0000000..85e5980 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/internal/semver.js @@ -0,0 +1,118 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { VERSION } from '../version'; +const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; +/** + * Create a function to test an API version to see if it is compatible with the provided ownVersion. + * + * The returned function has the following semantics: + * - Exact match is always compatible + * - Major versions must match exactly + * - 1.x package cannot use global 2.x package + * - 2.x package cannot use global 1.x package + * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API + * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects + * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 + * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor + * - Patch and build tag differences are not considered at this time + * + * @param ownVersion version which should be checked against + */ +export function _makeCompatibilityCheck(ownVersion) { + const acceptedVersions = new Set([ownVersion]); + const rejectedVersions = new Set(); + const myVersionMatch = ownVersion.match(re); + if (!myVersionMatch) { + // we cannot guarantee compatibility so we always return noop + return () => false; + } + const ownVersionParsed = { + major: +myVersionMatch[1], + minor: +myVersionMatch[2], + patch: +myVersionMatch[3], + prerelease: myVersionMatch[4], + }; + // if ownVersion has a prerelease tag, versions must match exactly + if (ownVersionParsed.prerelease != null) { + return function isExactmatch(globalVersion) { + return globalVersion === ownVersion; + }; + } + function _reject(v) { + rejectedVersions.add(v); + return false; + } + function _accept(v) { + acceptedVersions.add(v); + return true; + } + return function isCompatible(globalVersion) { + if (acceptedVersions.has(globalVersion)) { + return true; + } + if (rejectedVersions.has(globalVersion)) { + return false; + } + const globalVersionMatch = globalVersion.match(re); + if (!globalVersionMatch) { + // cannot parse other version + // we cannot guarantee compatibility so we always noop + return _reject(globalVersion); + } + const globalVersionParsed = { + major: +globalVersionMatch[1], + minor: +globalVersionMatch[2], + patch: +globalVersionMatch[3], + prerelease: globalVersionMatch[4], + }; + // if globalVersion has a prerelease tag, versions must match exactly + if (globalVersionParsed.prerelease != null) { + return _reject(globalVersion); + } + // major versions must match + if (ownVersionParsed.major !== globalVersionParsed.major) { + return _reject(globalVersion); + } + if (ownVersionParsed.major === 0) { + if (ownVersionParsed.minor === globalVersionParsed.minor && + ownVersionParsed.patch <= globalVersionParsed.patch) { + return _accept(globalVersion); + } + return _reject(globalVersion); + } + if (ownVersionParsed.minor <= globalVersionParsed.minor) { + return _accept(globalVersion); + } + return _reject(globalVersion); + }; +} +/** + * Test an API version to see if it is compatible with this API. + * + * - Exact match is always compatible + * - Major versions must match exactly + * - 1.x package cannot use global 2.x package + * - 2.x package cannot use global 1.x package + * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API + * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects + * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 + * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor + * - Patch and build tag differences are not considered at this time + * + * @param version version of the API requesting an instance of the global API + */ +export const isCompatible = _makeCompatibilityCheck(VERSION); +//# sourceMappingURL=semver.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/internal/semver.js.map b/node_modules/@opentelemetry/api/build/esnext/internal/semver.js.map new file mode 100644 index 0000000..45cc4a3 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/internal/semver.js.map @@ -0,0 +1 @@ +{"version":3,"file":"semver.js","sourceRoot":"","sources":["../../../src/internal/semver.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,MAAM,EAAE,GAAG,+BAA+B,CAAC;AAE3C;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,uBAAuB,CACrC,UAAkB;IAElB,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAS,CAAC,UAAU,CAAC,CAAC,CAAC;IACvD,MAAM,gBAAgB,GAAG,IAAI,GAAG,EAAU,CAAC;IAE3C,MAAM,cAAc,GAAG,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAC5C,IAAI,CAAC,cAAc,EAAE;QACnB,6DAA6D;QAC7D,OAAO,GAAG,EAAE,CAAC,KAAK,CAAC;KACpB;IAED,MAAM,gBAAgB,GAAG;QACvB,KAAK,EAAE,CAAC,cAAc,CAAC,CAAC,CAAC;QACzB,KAAK,EAAE,CAAC,cAAc,CAAC,CAAC,CAAC;QACzB,KAAK,EAAE,CAAC,cAAc,CAAC,CAAC,CAAC;QACzB,UAAU,EAAE,cAAc,CAAC,CAAC,CAAC;KAC9B,CAAC;IAEF,kEAAkE;IAClE,IAAI,gBAAgB,CAAC,UAAU,IAAI,IAAI,EAAE;QACvC,OAAO,SAA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IACE,gBAAgB,CAAC,KAAK,KAAK,mBAAmB,CAAC,KAAK;gBACpD,gBAAgB,CAAC,KAAK,IAAI,mBAAmB,CAAC,KAAK,EACnD;gBACA,OAAO,OAAO,CAAC,aAAa,CAAC,CAAC;aAC/B;YAED,OAAO,OAAO,CAAC,aAAa,CAAC,CAAC;SAC/B;QAED,IAAI,gBAAgB,CAAC,KAAK,IAAI,mBAAmB,CAAC,KAAK,EAAE;YACvD,OAAO,OAAO,CAAC,aAAa,CAAC,CAAC;SAC/B;QAED,OAAO,OAAO,CAAC,aAAa,CAAC,CAAC;IAChC,CAAC,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,uBAAuB,CAAC,OAAO,CAAC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { VERSION } from '../version';\n\nconst re = /^(\\d+)\\.(\\d+)\\.(\\d+)(-(.+))?$/;\n\n/**\n * Create a function to test an API version to see if it is compatible with the provided ownVersion.\n *\n * The returned function has the following semantics:\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param ownVersion version which should be checked against\n */\nexport function _makeCompatibilityCheck(\n ownVersion: string\n): (globalVersion: string) => boolean {\n const acceptedVersions = new Set([ownVersion]);\n const rejectedVersions = new Set();\n\n const myVersionMatch = ownVersion.match(re);\n if (!myVersionMatch) {\n // we cannot guarantee compatibility so we always return noop\n return () => false;\n }\n\n const ownVersionParsed = {\n major: +myVersionMatch[1],\n minor: +myVersionMatch[2],\n patch: +myVersionMatch[3],\n prerelease: myVersionMatch[4],\n };\n\n // if ownVersion has a prerelease tag, versions must match exactly\n if (ownVersionParsed.prerelease != null) {\n return function isExactmatch(globalVersion: string): boolean {\n return globalVersion === ownVersion;\n };\n }\n\n function _reject(v: string) {\n rejectedVersions.add(v);\n return false;\n }\n\n function _accept(v: string) {\n acceptedVersions.add(v);\n return true;\n }\n\n return function isCompatible(globalVersion: string): boolean {\n if (acceptedVersions.has(globalVersion)) {\n return true;\n }\n\n if (rejectedVersions.has(globalVersion)) {\n return false;\n }\n\n const globalVersionMatch = globalVersion.match(re);\n if (!globalVersionMatch) {\n // cannot parse other version\n // we cannot guarantee compatibility so we always noop\n return _reject(globalVersion);\n }\n\n const globalVersionParsed = {\n major: +globalVersionMatch[1],\n minor: +globalVersionMatch[2],\n patch: +globalVersionMatch[3],\n prerelease: globalVersionMatch[4],\n };\n\n // if globalVersion has a prerelease tag, versions must match exactly\n if (globalVersionParsed.prerelease != null) {\n return _reject(globalVersion);\n }\n\n // major versions must match\n if (ownVersionParsed.major !== globalVersionParsed.major) {\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.major === 0) {\n if (\n ownVersionParsed.minor === globalVersionParsed.minor &&\n ownVersionParsed.patch <= globalVersionParsed.patch\n ) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.minor <= globalVersionParsed.minor) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n };\n}\n\n/**\n * Test an API version to see if it is compatible with this API.\n *\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param version version of the API requesting an instance of the global API\n */\nexport const isCompatible = _makeCompatibilityCheck(VERSION);\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics-api.d.ts b/node_modules/@opentelemetry/api/build/esnext/metrics-api.d.ts new file mode 100644 index 0000000..26d539c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics-api.d.ts @@ -0,0 +1,4 @@ +import { MetricsAPI } from './api/metrics'; +/** Entrypoint for metrics API */ +export declare const metrics: MetricsAPI; +//# sourceMappingURL=metrics-api.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics-api.js b/node_modules/@opentelemetry/api/build/esnext/metrics-api.js new file mode 100644 index 0000000..624c886 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics-api.js @@ -0,0 +1,21 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +import { MetricsAPI } from './api/metrics'; +/** Entrypoint for metrics API */ +export const metrics = MetricsAPI.getInstance(); +//# sourceMappingURL=metrics-api.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics-api.js.map b/node_modules/@opentelemetry/api/build/esnext/metrics-api.js.map new file mode 100644 index 0000000..eb011b6 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics-api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metrics-api.js","sourceRoot":"","sources":["../../src/metrics-api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,sEAAsE;AACtE,qCAAqC;AACrC,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,iCAAiC;AACjC,MAAM,CAAC,MAAM,OAAO,GAAG,UAAU,CAAC,WAAW,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { MetricsAPI } from './api/metrics';\n/** Entrypoint for metrics API */\nexport const metrics = MetricsAPI.getInstance();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics/Meter.d.ts b/node_modules/@opentelemetry/api/build/esnext/metrics/Meter.d.ts new file mode 100644 index 0000000..5e3926b --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics/Meter.d.ts @@ -0,0 +1,110 @@ +import { BatchObservableCallback, Counter, Gauge, Histogram, MetricAttributes, MetricOptions, Observable, ObservableCounter, ObservableGauge, ObservableUpDownCounter, UpDownCounter } from './Metric'; +/** + * An interface describes additional metadata of a meter. + */ +export interface MeterOptions { + /** + * The schemaUrl of the meter or instrumentation library + */ + schemaUrl?: string; +} +/** + * An interface to allow the recording metrics. + * + * {@link Metric}s are used for recording pre-defined aggregation (`Counter`), + * or raw values (`Histogram`) in which the aggregation and attributes + * for the exported metric are deferred. + */ +export interface Meter { + /** + * Creates and returns a new `Gauge`. + * @param name the name of the metric. + * @param [options] the metric options. + */ + createGauge(name: string, options?: MetricOptions): Gauge; + /** + * Creates and returns a new `Histogram`. + * @param name the name of the metric. + * @param [options] the metric options. + */ + createHistogram(name: string, options?: MetricOptions): Histogram; + /** + * Creates a new `Counter` metric. Generally, this kind of metric when the + * value is a quantity, the sum is of primary interest, and the event count + * and value distribution are not of primary interest. + * @param name the name of the metric. + * @param [options] the metric options. + */ + createCounter(name: string, options?: MetricOptions): Counter; + /** + * Creates a new `UpDownCounter` metric. UpDownCounter is a synchronous + * instrument and very similar to Counter except that Add(increment) + * supports negative increments. It is generally useful for capturing changes + * in an amount of resources used, or any quantity that rises and falls + * during a request. + * Example uses for UpDownCounter: + *
            + *
          1. count the number of active requests.
          2. + *
          3. count memory in use by instrumenting new and delete.
          4. + *
          5. count queue size by instrumenting enqueue and dequeue.
          6. + *
          7. count semaphore up and down operations.
          8. + *
          + * + * @param name the name of the metric. + * @param [options] the metric options. + */ + createUpDownCounter(name: string, options?: MetricOptions): UpDownCounter; + /** + * Creates a new `ObservableGauge` metric. + * + * The callback SHOULD be safe to be invoked concurrently. + * + * @param name the name of the metric. + * @param [options] the metric options. + */ + createObservableGauge(name: string, options?: MetricOptions): ObservableGauge; + /** + * Creates a new `ObservableCounter` metric. + * + * The callback SHOULD be safe to be invoked concurrently. + * + * @param name the name of the metric. + * @param [options] the metric options. + */ + createObservableCounter(name: string, options?: MetricOptions): ObservableCounter; + /** + * Creates a new `ObservableUpDownCounter` metric. + * + * The callback SHOULD be safe to be invoked concurrently. + * + * @param name the name of the metric. + * @param [options] the metric options. + */ + createObservableUpDownCounter(name: string, options?: MetricOptions): ObservableUpDownCounter; + /** + * Sets up a function that will be called whenever a metric collection is + * initiated. + * + * If the function is already in the list of callbacks for this Observable, + * the function is not added a second time. + * + * Only the associated observables can be observed in the callback. + * Measurements of observables that are not associated observed in the + * callback are dropped. + * + * @param callback the batch observable callback + * @param observables the observables associated with this batch observable callback + */ + addBatchObservableCallback(callback: BatchObservableCallback, observables: Observable[]): void; + /** + * Removes a callback previously registered with {@link Meter.addBatchObservableCallback}. + * + * The callback to be removed is identified using a combination of the callback itself, + * and the set of the observables associated with it. + * + * @param callback the batch observable callback + * @param observables the observables associated with this batch observable callback + */ + removeBatchObservableCallback(callback: BatchObservableCallback, observables: Observable[]): void; +} +//# sourceMappingURL=Meter.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics/Meter.js b/node_modules/@opentelemetry/api/build/esnext/metrics/Meter.js new file mode 100644 index 0000000..f1d0754 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics/Meter.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=Meter.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics/Meter.js.map b/node_modules/@opentelemetry/api/build/esnext/metrics/Meter.js.map new file mode 100644 index 0000000..c4b0aaf --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics/Meter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Meter.js","sourceRoot":"","sources":["../../../src/metrics/Meter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BatchObservableCallback,\n Counter,\n Gauge,\n Histogram,\n MetricAttributes,\n MetricOptions,\n Observable,\n ObservableCounter,\n ObservableGauge,\n ObservableUpDownCounter,\n UpDownCounter,\n} from './Metric';\n\n/**\n * An interface describes additional metadata of a meter.\n */\nexport interface MeterOptions {\n /**\n * The schemaUrl of the meter or instrumentation library\n */\n schemaUrl?: string;\n}\n\n/**\n * An interface to allow the recording metrics.\n *\n * {@link Metric}s are used for recording pre-defined aggregation (`Counter`),\n * or raw values (`Histogram`) in which the aggregation and attributes\n * for the exported metric are deferred.\n */\nexport interface Meter {\n /**\n * Creates and returns a new `Gauge`.\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createGauge(\n name: string,\n options?: MetricOptions\n ): Gauge;\n\n /**\n * Creates and returns a new `Histogram`.\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createHistogram(\n name: string,\n options?: MetricOptions\n ): Histogram;\n\n /**\n * Creates a new `Counter` metric. Generally, this kind of metric when the\n * value is a quantity, the sum is of primary interest, and the event count\n * and value distribution are not of primary interest.\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createCounter(\n name: string,\n options?: MetricOptions\n ): Counter;\n\n /**\n * Creates a new `UpDownCounter` metric. UpDownCounter is a synchronous\n * instrument and very similar to Counter except that Add(increment)\n * supports negative increments. It is generally useful for capturing changes\n * in an amount of resources used, or any quantity that rises and falls\n * during a request.\n * Example uses for UpDownCounter:\n *
            \n *
          1. count the number of active requests.
          2. \n *
          3. count memory in use by instrumenting new and delete.
          4. \n *
          5. count queue size by instrumenting enqueue and dequeue.
          6. \n *
          7. count semaphore up and down operations.
          8. \n *
          \n *\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createUpDownCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n >(\n name: string,\n options?: MetricOptions\n ): UpDownCounter;\n\n /**\n * Creates a new `ObservableGauge` metric.\n *\n * The callback SHOULD be safe to be invoked concurrently.\n *\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createObservableGauge<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n >(\n name: string,\n options?: MetricOptions\n ): ObservableGauge;\n\n /**\n * Creates a new `ObservableCounter` metric.\n *\n * The callback SHOULD be safe to be invoked concurrently.\n *\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createObservableCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n >(\n name: string,\n options?: MetricOptions\n ): ObservableCounter;\n\n /**\n * Creates a new `ObservableUpDownCounter` metric.\n *\n * The callback SHOULD be safe to be invoked concurrently.\n *\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createObservableUpDownCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n >(\n name: string,\n options?: MetricOptions\n ): ObservableUpDownCounter;\n\n /**\n * Sets up a function that will be called whenever a metric collection is\n * initiated.\n *\n * If the function is already in the list of callbacks for this Observable,\n * the function is not added a second time.\n *\n * Only the associated observables can be observed in the callback.\n * Measurements of observables that are not associated observed in the\n * callback are dropped.\n *\n * @param callback the batch observable callback\n * @param observables the observables associated with this batch observable callback\n */\n addBatchObservableCallback<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n >(\n callback: BatchObservableCallback,\n observables: Observable[]\n ): void;\n\n /**\n * Removes a callback previously registered with {@link Meter.addBatchObservableCallback}.\n *\n * The callback to be removed is identified using a combination of the callback itself,\n * and the set of the observables associated with it.\n *\n * @param callback the batch observable callback\n * @param observables the observables associated with this batch observable callback\n */\n removeBatchObservableCallback<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n >(\n callback: BatchObservableCallback,\n observables: Observable[]\n ): void;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics/MeterProvider.d.ts b/node_modules/@opentelemetry/api/build/esnext/metrics/MeterProvider.d.ts new file mode 100644 index 0000000..6c08cc3 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics/MeterProvider.d.ts @@ -0,0 +1,17 @@ +import { Meter, MeterOptions } from './Meter'; +/** + * A registry for creating named {@link Meter}s. + */ +export interface MeterProvider { + /** + * Returns a Meter, creating one if one with the given name, version, and + * schemaUrl pair is not already created. + * + * @param name The name of the meter or instrumentation library. + * @param version The version of the meter or instrumentation library. + * @param options The options of the meter or instrumentation library. + * @returns Meter A Meter with the given name and version + */ + getMeter(name: string, version?: string, options?: MeterOptions): Meter; +} +//# sourceMappingURL=MeterProvider.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics/MeterProvider.js b/node_modules/@opentelemetry/api/build/esnext/metrics/MeterProvider.js new file mode 100644 index 0000000..3051712 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics/MeterProvider.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=MeterProvider.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics/MeterProvider.js.map b/node_modules/@opentelemetry/api/build/esnext/metrics/MeterProvider.js.map new file mode 100644 index 0000000..8f96d90 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics/MeterProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MeterProvider.js","sourceRoot":"","sources":["../../../src/metrics/MeterProvider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Meter, MeterOptions } from './Meter';\n\n/**\n * A registry for creating named {@link Meter}s.\n */\nexport interface MeterProvider {\n /**\n * Returns a Meter, creating one if one with the given name, version, and\n * schemaUrl pair is not already created.\n *\n * @param name The name of the meter or instrumentation library.\n * @param version The version of the meter or instrumentation library.\n * @param options The options of the meter or instrumentation library.\n * @returns Meter A Meter with the given name and version\n */\n getMeter(name: string, version?: string, options?: MeterOptions): Meter;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics/Metric.d.ts b/node_modules/@opentelemetry/api/build/esnext/metrics/Metric.d.ts new file mode 100644 index 0000000..607b637 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics/Metric.d.ts @@ -0,0 +1,115 @@ +import { Attributes, AttributeValue } from '../common/Attributes'; +import { Context } from '../context/types'; +import { BatchObservableResult, ObservableResult } from './ObservableResult'; +/** + * Advisory options influencing aggregation configuration parameters. + * @experimental + */ +export interface MetricAdvice { + /** + * Hint the explicit bucket boundaries for SDK if the metric is been + * aggregated with a HistogramAggregator. + */ + explicitBucketBoundaries?: number[]; +} +/** + * Options needed for metric creation + */ +export interface MetricOptions { + /** + * The description of the Metric. + * @default '' + */ + description?: string; + /** + * The unit of the Metric values. + * @default '' + */ + unit?: string; + /** + * Indicates the type of the recorded value. + * @default {@link ValueType.DOUBLE} + */ + valueType?: ValueType; + /** + * The advice influencing aggregation configuration parameters. + * @experimental + */ + advice?: MetricAdvice; +} +/** The Type of value. It describes how the data is reported. */ +export declare enum ValueType { + INT = 0, + DOUBLE = 1 +} +/** + * Counter is the most common synchronous instrument. This instrument supports + * an `Add(increment)` function for reporting a sum, and is restricted to + * non-negative increments. The default aggregation is Sum, as for any additive + * instrument. + * + * Example uses for Counter: + *
            + *
          1. count the number of bytes received.
          2. + *
          3. count the number of requests completed.
          4. + *
          5. count the number of accounts created.
          6. + *
          7. count the number of checkpoints run.
          8. + *
          9. count the number of 5xx errors.
          10. + *
              + */ +export interface Counter { + /** + * Increment value of counter by the input. Inputs must not be negative. + */ + add(value: number, attributes?: AttributesTypes, context?: Context): void; +} +export interface UpDownCounter { + /** + * Increment value of counter by the input. Inputs may be negative. + */ + add(value: number, attributes?: AttributesTypes, context?: Context): void; +} +export interface Gauge { + /** + * Records a measurement. + */ + record(value: number, attributes?: AttributesTypes, context?: Context): void; +} +export interface Histogram { + /** + * Records a measurement. Value of the measurement must not be negative. + */ + record(value: number, attributes?: AttributesTypes, context?: Context): void; +} +/** + * @deprecated please use {@link Attributes} + */ +export declare type MetricAttributes = Attributes; +/** + * @deprecated please use {@link AttributeValue} + */ +export declare type MetricAttributeValue = AttributeValue; +/** + * The observable callback for Observable instruments. + */ +export declare type ObservableCallback = (observableResult: ObservableResult) => void | Promise; +/** + * The observable callback for a batch of Observable instruments. + */ +export declare type BatchObservableCallback = (observableResult: BatchObservableResult) => void | Promise; +export interface Observable { + /** + * Sets up a function that will be called whenever a metric collection is initiated. + * + * If the function is already in the list of callbacks for this Observable, the function is not added a second time. + */ + addCallback(callback: ObservableCallback): void; + /** + * Removes a callback previously registered with {@link Observable.addCallback}. + */ + removeCallback(callback: ObservableCallback): void; +} +export declare type ObservableCounter = Observable; +export declare type ObservableUpDownCounter = Observable; +export declare type ObservableGauge = Observable; +//# sourceMappingURL=Metric.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics/Metric.js b/node_modules/@opentelemetry/api/build/esnext/metrics/Metric.js new file mode 100644 index 0000000..6df1374 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics/Metric.js @@ -0,0 +1,22 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Type of value. It describes how the data is reported. */ +export var ValueType; +(function (ValueType) { + ValueType[ValueType["INT"] = 0] = "INT"; + ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE"; +})(ValueType || (ValueType = {})); +//# sourceMappingURL=Metric.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics/Metric.js.map b/node_modules/@opentelemetry/api/build/esnext/metrics/Metric.js.map new file mode 100644 index 0000000..a115430 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics/Metric.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Metric.js","sourceRoot":"","sources":["../../../src/metrics/Metric.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AA+CH,gEAAgE;AAChE,MAAM,CAAN,IAAY,SAGX;AAHD,WAAY,SAAS;IACnB,uCAAG,CAAA;IACH,6CAAM,CAAA;AACR,CAAC,EAHW,SAAS,KAAT,SAAS,QAGpB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Attributes, AttributeValue } from '../common/Attributes';\nimport { Context } from '../context/types';\nimport { BatchObservableResult, ObservableResult } from './ObservableResult';\n\n/**\n * Advisory options influencing aggregation configuration parameters.\n * @experimental\n */\nexport interface MetricAdvice {\n /**\n * Hint the explicit bucket boundaries for SDK if the metric is been\n * aggregated with a HistogramAggregator.\n */\n explicitBucketBoundaries?: number[];\n}\n\n/**\n * Options needed for metric creation\n */\nexport interface MetricOptions {\n /**\n * The description of the Metric.\n * @default ''\n */\n description?: string;\n\n /**\n * The unit of the Metric values.\n * @default ''\n */\n unit?: string;\n\n /**\n * Indicates the type of the recorded value.\n * @default {@link ValueType.DOUBLE}\n */\n valueType?: ValueType;\n\n /**\n * The advice influencing aggregation configuration parameters.\n * @experimental\n */\n advice?: MetricAdvice;\n}\n\n/** The Type of value. It describes how the data is reported. */\nexport enum ValueType {\n INT,\n DOUBLE,\n}\n\n/**\n * Counter is the most common synchronous instrument. This instrument supports\n * an `Add(increment)` function for reporting a sum, and is restricted to\n * non-negative increments. The default aggregation is Sum, as for any additive\n * instrument.\n *\n * Example uses for Counter:\n *
                \n *
              1. count the number of bytes received.
              2. \n *
              3. count the number of requests completed.
              4. \n *
              5. count the number of accounts created.
              6. \n *
              7. count the number of checkpoints run.
              8. \n *
              9. count the number of 5xx errors.
              10. \n *
                  \n */\nexport interface Counter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Increment value of counter by the input. Inputs must not be negative.\n */\n add(value: number, attributes?: AttributesTypes, context?: Context): void;\n}\n\nexport interface UpDownCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Increment value of counter by the input. Inputs may be negative.\n */\n add(value: number, attributes?: AttributesTypes, context?: Context): void;\n}\n\nexport interface Gauge<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Records a measurement.\n */\n record(value: number, attributes?: AttributesTypes, context?: Context): void;\n}\n\nexport interface Histogram<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Records a measurement. Value of the measurement must not be negative.\n */\n record(value: number, attributes?: AttributesTypes, context?: Context): void;\n}\n\n/**\n * @deprecated please use {@link Attributes}\n */\nexport type MetricAttributes = Attributes;\n\n/**\n * @deprecated please use {@link AttributeValue}\n */\nexport type MetricAttributeValue = AttributeValue;\n\n/**\n * The observable callback for Observable instruments.\n */\nexport type ObservableCallback<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> = (\n observableResult: ObservableResult\n) => void | Promise;\n\n/**\n * The observable callback for a batch of Observable instruments.\n */\nexport type BatchObservableCallback<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> = (\n observableResult: BatchObservableResult\n) => void | Promise;\n\nexport interface Observable<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Sets up a function that will be called whenever a metric collection is initiated.\n *\n * If the function is already in the list of callbacks for this Observable, the function is not added a second time.\n */\n addCallback(callback: ObservableCallback): void;\n\n /**\n * Removes a callback previously registered with {@link Observable.addCallback}.\n */\n removeCallback(callback: ObservableCallback): void;\n}\n\nexport type ObservableCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> = Observable;\nexport type ObservableUpDownCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> = Observable;\nexport type ObservableGauge<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> = Observable;\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeter.d.ts b/node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeter.d.ts new file mode 100644 index 0000000..bbefa9a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeter.d.ts @@ -0,0 +1,82 @@ +import { Meter } from './Meter'; +import { BatchObservableCallback, Counter, Gauge, Histogram, MetricAttributes, MetricOptions, Observable, ObservableCallback, ObservableCounter, ObservableGauge, ObservableUpDownCounter, UpDownCounter } from './Metric'; +/** + * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses + * constant NoopMetrics for all of its methods. + */ +export declare class NoopMeter implements Meter { + constructor(); + /** + * @see {@link Meter.createGauge} + */ + createGauge(_name: string, _options?: MetricOptions): Gauge; + /** + * @see {@link Meter.createHistogram} + */ + createHistogram(_name: string, _options?: MetricOptions): Histogram; + /** + * @see {@link Meter.createCounter} + */ + createCounter(_name: string, _options?: MetricOptions): Counter; + /** + * @see {@link Meter.createUpDownCounter} + */ + createUpDownCounter(_name: string, _options?: MetricOptions): UpDownCounter; + /** + * @see {@link Meter.createObservableGauge} + */ + createObservableGauge(_name: string, _options?: MetricOptions): ObservableGauge; + /** + * @see {@link Meter.createObservableCounter} + */ + createObservableCounter(_name: string, _options?: MetricOptions): ObservableCounter; + /** + * @see {@link Meter.createObservableUpDownCounter} + */ + createObservableUpDownCounter(_name: string, _options?: MetricOptions): ObservableUpDownCounter; + /** + * @see {@link Meter.addBatchObservableCallback} + */ + addBatchObservableCallback(_callback: BatchObservableCallback, _observables: Observable[]): void; + /** + * @see {@link Meter.removeBatchObservableCallback} + */ + removeBatchObservableCallback(_callback: BatchObservableCallback): void; +} +export declare class NoopMetric { +} +export declare class NoopCounterMetric extends NoopMetric implements Counter { + add(_value: number, _attributes: MetricAttributes): void; +} +export declare class NoopUpDownCounterMetric extends NoopMetric implements UpDownCounter { + add(_value: number, _attributes: MetricAttributes): void; +} +export declare class NoopGaugeMetric extends NoopMetric implements Gauge { + record(_value: number, _attributes: MetricAttributes): void; +} +export declare class NoopHistogramMetric extends NoopMetric implements Histogram { + record(_value: number, _attributes: MetricAttributes): void; +} +export declare class NoopObservableMetric { + addCallback(_callback: ObservableCallback): void; + removeCallback(_callback: ObservableCallback): void; +} +export declare class NoopObservableCounterMetric extends NoopObservableMetric implements ObservableCounter { +} +export declare class NoopObservableGaugeMetric extends NoopObservableMetric implements ObservableGauge { +} +export declare class NoopObservableUpDownCounterMetric extends NoopObservableMetric implements ObservableUpDownCounter { +} +export declare const NOOP_METER: NoopMeter; +export declare const NOOP_COUNTER_METRIC: NoopCounterMetric; +export declare const NOOP_GAUGE_METRIC: NoopGaugeMetric; +export declare const NOOP_HISTOGRAM_METRIC: NoopHistogramMetric; +export declare const NOOP_UP_DOWN_COUNTER_METRIC: NoopUpDownCounterMetric; +export declare const NOOP_OBSERVABLE_COUNTER_METRIC: NoopObservableCounterMetric; +export declare const NOOP_OBSERVABLE_GAUGE_METRIC: NoopObservableGaugeMetric; +export declare const NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC: NoopObservableUpDownCounterMetric; +/** + * Create a no-op Meter + */ +export declare function createNoopMeter(): Meter; +//# sourceMappingURL=NoopMeter.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeter.js b/node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeter.js new file mode 100644 index 0000000..1f966ba --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeter.js @@ -0,0 +1,113 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses + * constant NoopMetrics for all of its methods. + */ +export class NoopMeter { + constructor() { } + /** + * @see {@link Meter.createGauge} + */ + createGauge(_name, _options) { + return NOOP_GAUGE_METRIC; + } + /** + * @see {@link Meter.createHistogram} + */ + createHistogram(_name, _options) { + return NOOP_HISTOGRAM_METRIC; + } + /** + * @see {@link Meter.createCounter} + */ + createCounter(_name, _options) { + return NOOP_COUNTER_METRIC; + } + /** + * @see {@link Meter.createUpDownCounter} + */ + createUpDownCounter(_name, _options) { + return NOOP_UP_DOWN_COUNTER_METRIC; + } + /** + * @see {@link Meter.createObservableGauge} + */ + createObservableGauge(_name, _options) { + return NOOP_OBSERVABLE_GAUGE_METRIC; + } + /** + * @see {@link Meter.createObservableCounter} + */ + createObservableCounter(_name, _options) { + return NOOP_OBSERVABLE_COUNTER_METRIC; + } + /** + * @see {@link Meter.createObservableUpDownCounter} + */ + createObservableUpDownCounter(_name, _options) { + return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; + } + /** + * @see {@link Meter.addBatchObservableCallback} + */ + addBatchObservableCallback(_callback, _observables) { } + /** + * @see {@link Meter.removeBatchObservableCallback} + */ + removeBatchObservableCallback(_callback) { } +} +export class NoopMetric { +} +export class NoopCounterMetric extends NoopMetric { + add(_value, _attributes) { } +} +export class NoopUpDownCounterMetric extends NoopMetric { + add(_value, _attributes) { } +} +export class NoopGaugeMetric extends NoopMetric { + record(_value, _attributes) { } +} +export class NoopHistogramMetric extends NoopMetric { + record(_value, _attributes) { } +} +export class NoopObservableMetric { + addCallback(_callback) { } + removeCallback(_callback) { } +} +export class NoopObservableCounterMetric extends NoopObservableMetric { +} +export class NoopObservableGaugeMetric extends NoopObservableMetric { +} +export class NoopObservableUpDownCounterMetric extends NoopObservableMetric { +} +export const NOOP_METER = new NoopMeter(); +// Synchronous instruments +export const NOOP_COUNTER_METRIC = new NoopCounterMetric(); +export const NOOP_GAUGE_METRIC = new NoopGaugeMetric(); +export const NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric(); +export const NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric(); +// Asynchronous instruments +export const NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric(); +export const NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric(); +export const NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric(); +/** + * Create a no-op Meter + */ +export function createNoopMeter() { + return NOOP_METER; +} +//# sourceMappingURL=NoopMeter.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeter.js.map b/node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeter.js.map new file mode 100644 index 0000000..ca6e904 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NoopMeter.js","sourceRoot":"","sources":["../../../src/metrics/NoopMeter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAkBH;;;GAGG;AACH,MAAM,OAAO,SAAS;IACpB,gBAAe,CAAC;IAEhB;;OAEG;IACH,WAAW,CAAC,KAAa,EAAE,QAAwB;QACjD,OAAO,iBAAiB,CAAC;IAC3B,CAAC;IAED;;OAEG;IACH,eAAe,CAAC,KAAa,EAAE,QAAwB;QACrD,OAAO,qBAAqB,CAAC;IAC/B,CAAC;IAED;;OAEG;IACH,aAAa,CAAC,KAAa,EAAE,QAAwB;QACnD,OAAO,mBAAmB,CAAC;IAC7B,CAAC;IAED;;OAEG;IACH,mBAAmB,CAAC,KAAa,EAAE,QAAwB;QACzD,OAAO,2BAA2B,CAAC;IACrC,CAAC;IAED;;OAEG;IACH,qBAAqB,CACnB,KAAa,EACb,QAAwB;QAExB,OAAO,4BAA4B,CAAC;IACtC,CAAC;IAED;;OAEG;IACH,uBAAuB,CACrB,KAAa,EACb,QAAwB;QAExB,OAAO,8BAA8B,CAAC;IACxC,CAAC;IAED;;OAEG;IACH,6BAA6B,CAC3B,KAAa,EACb,QAAwB;QAExB,OAAO,sCAAsC,CAAC;IAChD,CAAC;IAED;;OAEG;IACH,0BAA0B,CACxB,SAAkC,EAClC,YAA0B,IACnB,CAAC;IAEV;;OAEG;IACH,6BAA6B,CAAC,SAAkC,IAAS,CAAC;CAC3E;AAED,MAAM,OAAO,UAAU;CAAG;AAE1B,MAAM,OAAO,iBAAkB,SAAQ,UAAU;IAC/C,GAAG,CAAC,MAAc,EAAE,WAA6B,IAAS,CAAC;CAC5D;AAED,MAAM,OAAO,uBACX,SAAQ,UAAU;IAGlB,GAAG,CAAC,MAAc,EAAE,WAA6B,IAAS,CAAC;CAC5D;AAED,MAAM,OAAO,eAAgB,SAAQ,UAAU;IAC7C,MAAM,CAAC,MAAc,EAAE,WAA6B,IAAS,CAAC;CAC/D;AAED,MAAM,OAAO,mBAAoB,SAAQ,UAAU;IACjD,MAAM,CAAC,MAAc,EAAE,WAA6B,IAAS,CAAC;CAC/D;AAED,MAAM,OAAO,oBAAoB;IAC/B,WAAW,CAAC,SAA6B,IAAG,CAAC;IAE7C,cAAc,CAAC,SAA6B,IAAG,CAAC;CACjD;AAED,MAAM,OAAO,2BACX,SAAQ,oBAAoB;CACG;AAEjC,MAAM,OAAO,yBACX,SAAQ,oBAAoB;CACC;AAE/B,MAAM,OAAO,iCACX,SAAQ,oBAAoB;CACS;AAEvC,MAAM,CAAC,MAAM,UAAU,GAAG,IAAI,SAAS,EAAE,CAAC;AAE1C,0BAA0B;AAC1B,MAAM,CAAC,MAAM,mBAAmB,GAAG,IAAI,iBAAiB,EAAE,CAAC;AAC3D,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,eAAe,EAAE,CAAC;AACvD,MAAM,CAAC,MAAM,qBAAqB,GAAG,IAAI,mBAAmB,EAAE,CAAC;AAC/D,MAAM,CAAC,MAAM,2BAA2B,GAAG,IAAI,uBAAuB,EAAE,CAAC;AAEzE,2BAA2B;AAC3B,MAAM,CAAC,MAAM,8BAA8B,GAAG,IAAI,2BAA2B,EAAE,CAAC;AAChF,MAAM,CAAC,MAAM,4BAA4B,GAAG,IAAI,yBAAyB,EAAE,CAAC;AAC5E,MAAM,CAAC,MAAM,sCAAsC,GACjD,IAAI,iCAAiC,EAAE,CAAC;AAE1C;;GAEG;AACH,MAAM,UAAU,eAAe;IAC7B,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Meter } from './Meter';\nimport {\n BatchObservableCallback,\n Counter,\n Gauge,\n Histogram,\n MetricAttributes,\n MetricOptions,\n Observable,\n ObservableCallback,\n ObservableCounter,\n ObservableGauge,\n ObservableUpDownCounter,\n UpDownCounter,\n} from './Metric';\n\n/**\n * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses\n * constant NoopMetrics for all of its methods.\n */\nexport class NoopMeter implements Meter {\n constructor() {}\n\n /**\n * @see {@link Meter.createGauge}\n */\n createGauge(_name: string, _options?: MetricOptions): Gauge {\n return NOOP_GAUGE_METRIC;\n }\n\n /**\n * @see {@link Meter.createHistogram}\n */\n createHistogram(_name: string, _options?: MetricOptions): Histogram {\n return NOOP_HISTOGRAM_METRIC;\n }\n\n /**\n * @see {@link Meter.createCounter}\n */\n createCounter(_name: string, _options?: MetricOptions): Counter {\n return NOOP_COUNTER_METRIC;\n }\n\n /**\n * @see {@link Meter.createUpDownCounter}\n */\n createUpDownCounter(_name: string, _options?: MetricOptions): UpDownCounter {\n return NOOP_UP_DOWN_COUNTER_METRIC;\n }\n\n /**\n * @see {@link Meter.createObservableGauge}\n */\n createObservableGauge(\n _name: string,\n _options?: MetricOptions\n ): ObservableGauge {\n return NOOP_OBSERVABLE_GAUGE_METRIC;\n }\n\n /**\n * @see {@link Meter.createObservableCounter}\n */\n createObservableCounter(\n _name: string,\n _options?: MetricOptions\n ): ObservableCounter {\n return NOOP_OBSERVABLE_COUNTER_METRIC;\n }\n\n /**\n * @see {@link Meter.createObservableUpDownCounter}\n */\n createObservableUpDownCounter(\n _name: string,\n _options?: MetricOptions\n ): ObservableUpDownCounter {\n return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;\n }\n\n /**\n * @see {@link Meter.addBatchObservableCallback}\n */\n addBatchObservableCallback(\n _callback: BatchObservableCallback,\n _observables: Observable[]\n ): void {}\n\n /**\n * @see {@link Meter.removeBatchObservableCallback}\n */\n removeBatchObservableCallback(_callback: BatchObservableCallback): void {}\n}\n\nexport class NoopMetric {}\n\nexport class NoopCounterMetric extends NoopMetric implements Counter {\n add(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopUpDownCounterMetric\n extends NoopMetric\n implements UpDownCounter\n{\n add(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopGaugeMetric extends NoopMetric implements Gauge {\n record(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopHistogramMetric extends NoopMetric implements Histogram {\n record(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopObservableMetric {\n addCallback(_callback: ObservableCallback) {}\n\n removeCallback(_callback: ObservableCallback) {}\n}\n\nexport class NoopObservableCounterMetric\n extends NoopObservableMetric\n implements ObservableCounter {}\n\nexport class NoopObservableGaugeMetric\n extends NoopObservableMetric\n implements ObservableGauge {}\n\nexport class NoopObservableUpDownCounterMetric\n extends NoopObservableMetric\n implements ObservableUpDownCounter {}\n\nexport const NOOP_METER = new NoopMeter();\n\n// Synchronous instruments\nexport const NOOP_COUNTER_METRIC = new NoopCounterMetric();\nexport const NOOP_GAUGE_METRIC = new NoopGaugeMetric();\nexport const NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric();\nexport const NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric();\n\n// Asynchronous instruments\nexport const NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric();\nexport const NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric();\nexport const NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC =\n new NoopObservableUpDownCounterMetric();\n\n/**\n * Create a no-op Meter\n */\nexport function createNoopMeter(): Meter {\n return NOOP_METER;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeterProvider.d.ts b/node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeterProvider.d.ts new file mode 100644 index 0000000..8b51bc5 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeterProvider.d.ts @@ -0,0 +1,11 @@ +import { Meter, MeterOptions } from './Meter'; +import { MeterProvider } from './MeterProvider'; +/** + * An implementation of the {@link MeterProvider} which returns an impotent Meter + * for all calls to `getMeter` + */ +export declare class NoopMeterProvider implements MeterProvider { + getMeter(_name: string, _version?: string, _options?: MeterOptions): Meter; +} +export declare const NOOP_METER_PROVIDER: NoopMeterProvider; +//# sourceMappingURL=NoopMeterProvider.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeterProvider.js b/node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeterProvider.js new file mode 100644 index 0000000..075f5c6 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeterProvider.js @@ -0,0 +1,27 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NOOP_METER } from './NoopMeter'; +/** + * An implementation of the {@link MeterProvider} which returns an impotent Meter + * for all calls to `getMeter` + */ +export class NoopMeterProvider { + getMeter(_name, _version, _options) { + return NOOP_METER; + } +} +export const NOOP_METER_PROVIDER = new NoopMeterProvider(); +//# sourceMappingURL=NoopMeterProvider.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeterProvider.js.map b/node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeterProvider.js.map new file mode 100644 index 0000000..c68783a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics/NoopMeterProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NoopMeterProvider.js","sourceRoot":"","sources":["../../../src/metrics/NoopMeterProvider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC;;;GAGG;AACH,MAAM,OAAO,iBAAiB;IAC5B,QAAQ,CAAC,KAAa,EAAE,QAAiB,EAAE,QAAuB;QAChE,OAAO,UAAU,CAAC;IACpB,CAAC;CACF;AAED,MAAM,CAAC,MAAM,mBAAmB,GAAG,IAAI,iBAAiB,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Meter, MeterOptions } from './Meter';\nimport { MeterProvider } from './MeterProvider';\nimport { NOOP_METER } from './NoopMeter';\n\n/**\n * An implementation of the {@link MeterProvider} which returns an impotent Meter\n * for all calls to `getMeter`\n */\nexport class NoopMeterProvider implements MeterProvider {\n getMeter(_name: string, _version?: string, _options?: MeterOptions): Meter {\n return NOOP_METER;\n }\n}\n\nexport const NOOP_METER_PROVIDER = new NoopMeterProvider();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics/ObservableResult.d.ts b/node_modules/@opentelemetry/api/build/esnext/metrics/ObservableResult.d.ts new file mode 100644 index 0000000..26563f9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics/ObservableResult.d.ts @@ -0,0 +1,31 @@ +import { MetricAttributes, Observable } from './Metric'; +/** + * Interface that is being used in callback function for Observable Metric. + */ +export interface ObservableResult { + /** + * Observe a measurement of the value associated with the given attributes. + * + * @param value The value to be observed. + * @param attributes The attributes associated with the value. If more than + * one values associated with the same attributes values, SDK may pick the + * last one or simply drop the entire observable result. + */ + observe(this: ObservableResult, value: number, attributes?: AttributesTypes): void; +} +/** + * Interface that is being used in batch observable callback function. + */ +export interface BatchObservableResult { + /** + * Observe a measurement of the value associated with the given attributes. + * + * @param metric The observable metric to be observed. + * @param value The value to be observed. + * @param attributes The attributes associated with the value. If more than + * one values associated with the same attributes values, SDK may pick the + * last one or simply drop the entire observable result. + */ + observe(this: BatchObservableResult, metric: Observable, value: number, attributes?: AttributesTypes): void; +} +//# sourceMappingURL=ObservableResult.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics/ObservableResult.js b/node_modules/@opentelemetry/api/build/esnext/metrics/ObservableResult.js new file mode 100644 index 0000000..7985d26 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics/ObservableResult.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=ObservableResult.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/metrics/ObservableResult.js.map b/node_modules/@opentelemetry/api/build/esnext/metrics/ObservableResult.js.map new file mode 100644 index 0000000..b6b0c7c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/metrics/ObservableResult.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ObservableResult.js","sourceRoot":"","sources":["../../../src/metrics/ObservableResult.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MetricAttributes, Observable } from './Metric';\n\n/**\n * Interface that is being used in callback function for Observable Metric.\n */\nexport interface ObservableResult<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Observe a measurement of the value associated with the given attributes.\n *\n * @param value The value to be observed.\n * @param attributes The attributes associated with the value. If more than\n * one values associated with the same attributes values, SDK may pick the\n * last one or simply drop the entire observable result.\n */\n observe(\n this: ObservableResult,\n value: number,\n attributes?: AttributesTypes\n ): void;\n}\n\n/**\n * Interface that is being used in batch observable callback function.\n */\nexport interface BatchObservableResult<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Observe a measurement of the value associated with the given attributes.\n *\n * @param metric The observable metric to be observed.\n * @param value The value to be observed.\n * @param attributes The attributes associated with the value. If more than\n * one values associated with the same attributes values, SDK may pick the\n * last one or simply drop the entire observable result.\n */\n observe(\n this: BatchObservableResult,\n metric: Observable,\n value: number,\n attributes?: AttributesTypes\n ): void;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/platform/browser/globalThis.d.ts b/node_modules/@opentelemetry/api/build/esnext/platform/browser/globalThis.d.ts new file mode 100644 index 0000000..e73fd73 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/platform/browser/globalThis.d.ts @@ -0,0 +1,10 @@ +/** + * - globalThis (New standard) + * - self (Will return the current window instance for supported browsers) + * - window (fallback for older browser implementations) + * - global (NodeJS implementation) + * - (When all else fails) + */ +/** only globals that common to node and browsers are allowed */ +export declare const _globalThis: typeof globalThis; +//# sourceMappingURL=globalThis.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/platform/browser/globalThis.js b/node_modules/@opentelemetry/api/build/esnext/platform/browser/globalThis.js new file mode 100644 index 0000000..e9d58b3 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/platform/browser/globalThis.js @@ -0,0 +1,35 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Updates to this file should also be replicated to @opentelemetry/core too. +/** + * - globalThis (New standard) + * - self (Will return the current window instance for supported browsers) + * - window (fallback for older browser implementations) + * - global (NodeJS implementation) + * - (When all else fails) + */ +/** only globals that common to node and browsers are allowed */ +// eslint-disable-next-line node/no-unsupported-features/es-builtins, no-undef +export const _globalThis = typeof globalThis === 'object' + ? globalThis + : typeof self === 'object' + ? self + : typeof window === 'object' + ? window + : typeof global === 'object' + ? global + : {}; +//# sourceMappingURL=globalThis.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/platform/browser/globalThis.js.map b/node_modules/@opentelemetry/api/build/esnext/platform/browser/globalThis.js.map new file mode 100644 index 0000000..c01e2ab --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/platform/browser/globalThis.js.map @@ -0,0 +1 @@ +{"version":3,"file":"globalThis.js","sourceRoot":"","sources":["../../../../src/platform/browser/globalThis.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,6EAA6E;AAE7E;;;;;;GAMG;AAEH,gEAAgE;AAChE,8EAA8E;AAC9E,MAAM,CAAC,MAAM,WAAW,GACtB,OAAO,UAAU,KAAK,QAAQ;IAC5B,CAAC,CAAC,UAAU;IACZ,CAAC,CAAC,OAAO,IAAI,KAAK,QAAQ;QAC1B,CAAC,CAAC,IAAI;QACN,CAAC,CAAC,OAAO,MAAM,KAAK,QAAQ;YAC5B,CAAC,CAAC,MAAM;YACR,CAAC,CAAC,OAAO,MAAM,KAAK,QAAQ;gBAC5B,CAAC,CAAC,MAAM;gBACR,CAAC,CAAE,EAAwB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Updates to this file should also be replicated to @opentelemetry/core too.\n\n/**\n * - globalThis (New standard)\n * - self (Will return the current window instance for supported browsers)\n * - window (fallback for older browser implementations)\n * - global (NodeJS implementation)\n * - (When all else fails)\n */\n\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins, no-undef\nexport const _globalThis: typeof globalThis =\n typeof globalThis === 'object'\n ? globalThis\n : typeof self === 'object'\n ? self\n : typeof window === 'object'\n ? window\n : typeof global === 'object'\n ? global\n : ({} as typeof globalThis);\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/platform/browser/index.d.ts b/node_modules/@opentelemetry/api/build/esnext/platform/browser/index.d.ts new file mode 100644 index 0000000..ba20e12 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/platform/browser/index.d.ts @@ -0,0 +1,2 @@ +export * from './globalThis'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/platform/browser/index.js b/node_modules/@opentelemetry/api/build/esnext/platform/browser/index.js new file mode 100644 index 0000000..efcad2e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/platform/browser/index.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './globalThis'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/platform/browser/index.js.map b/node_modules/@opentelemetry/api/build/esnext/platform/browser/index.js.map new file mode 100644 index 0000000..07adcd9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/platform/browser/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/browser/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,cAAc,cAAc,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './globalThis';\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/platform/index.d.ts b/node_modules/@opentelemetry/api/build/esnext/platform/index.d.ts new file mode 100644 index 0000000..90595da --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/platform/index.d.ts @@ -0,0 +1,2 @@ +export * from './node'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/platform/index.js b/node_modules/@opentelemetry/api/build/esnext/platform/index.js new file mode 100644 index 0000000..c0df125 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/platform/index.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './node'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/platform/index.js.map b/node_modules/@opentelemetry/api/build/esnext/platform/index.js.map new file mode 100644 index 0000000..9494c53 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/platform/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/platform/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,cAAc,QAAQ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './node';\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/platform/node/globalThis.d.ts b/node_modules/@opentelemetry/api/build/esnext/platform/node/globalThis.d.ts new file mode 100644 index 0000000..e3c83e5 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/platform/node/globalThis.d.ts @@ -0,0 +1,3 @@ +/** only globals that common to node and browsers are allowed */ +export declare const _globalThis: typeof globalThis; +//# sourceMappingURL=globalThis.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/platform/node/globalThis.js b/node_modules/@opentelemetry/api/build/esnext/platform/node/globalThis.js new file mode 100644 index 0000000..7daa45d --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/platform/node/globalThis.js @@ -0,0 +1,19 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** only globals that common to node and browsers are allowed */ +// eslint-disable-next-line node/no-unsupported-features/es-builtins +export const _globalThis = typeof globalThis === 'object' ? globalThis : global; +//# sourceMappingURL=globalThis.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/platform/node/globalThis.js.map b/node_modules/@opentelemetry/api/build/esnext/platform/node/globalThis.js.map new file mode 100644 index 0000000..7d8366c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/platform/node/globalThis.js.map @@ -0,0 +1 @@ +{"version":3,"file":"globalThis.js","sourceRoot":"","sources":["../../../../src/platform/node/globalThis.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,gEAAgE;AAChE,oEAAoE;AACpE,MAAM,CAAC,MAAM,WAAW,GAAG,OAAO,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/platform/node/index.d.ts b/node_modules/@opentelemetry/api/build/esnext/platform/node/index.d.ts new file mode 100644 index 0000000..ba20e12 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/platform/node/index.d.ts @@ -0,0 +1,2 @@ +export * from './globalThis'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/platform/node/index.js b/node_modules/@opentelemetry/api/build/esnext/platform/node/index.js new file mode 100644 index 0000000..efcad2e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/platform/node/index.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './globalThis'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/platform/node/index.js.map b/node_modules/@opentelemetry/api/build/esnext/platform/node/index.js.map new file mode 100644 index 0000000..f279718 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/platform/node/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/node/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,cAAc,cAAc,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './globalThis';\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/propagation-api.d.ts b/node_modules/@opentelemetry/api/build/esnext/propagation-api.d.ts new file mode 100644 index 0000000..e12b51b --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/propagation-api.d.ts @@ -0,0 +1,4 @@ +import { PropagationAPI } from './api/propagation'; +/** Entrypoint for propagation API */ +export declare const propagation: PropagationAPI; +//# sourceMappingURL=propagation-api.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/propagation-api.js b/node_modules/@opentelemetry/api/build/esnext/propagation-api.js new file mode 100644 index 0000000..7964ed9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/propagation-api.js @@ -0,0 +1,21 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +import { PropagationAPI } from './api/propagation'; +/** Entrypoint for propagation API */ +export const propagation = PropagationAPI.getInstance(); +//# sourceMappingURL=propagation-api.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/propagation-api.js.map b/node_modules/@opentelemetry/api/build/esnext/propagation-api.js.map new file mode 100644 index 0000000..401c0bc --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/propagation-api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"propagation-api.js","sourceRoot":"","sources":["../../src/propagation-api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,sEAAsE;AACtE,qCAAqC;AACrC,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,qCAAqC;AACrC,MAAM,CAAC,MAAM,WAAW,GAAG,cAAc,CAAC,WAAW,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { PropagationAPI } from './api/propagation';\n/** Entrypoint for propagation API */\nexport const propagation = PropagationAPI.getInstance();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/propagation/NoopTextMapPropagator.d.ts b/node_modules/@opentelemetry/api/build/esnext/propagation/NoopTextMapPropagator.d.ts new file mode 100644 index 0000000..398021f --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/propagation/NoopTextMapPropagator.d.ts @@ -0,0 +1,13 @@ +import { Context } from '../context/types'; +import { TextMapPropagator } from './TextMapPropagator'; +/** + * No-op implementations of {@link TextMapPropagator}. + */ +export declare class NoopTextMapPropagator implements TextMapPropagator { + /** Noop inject function does nothing */ + inject(_context: Context, _carrier: unknown): void; + /** Noop extract function does nothing and returns the input context */ + extract(context: Context, _carrier: unknown): Context; + fields(): string[]; +} +//# sourceMappingURL=NoopTextMapPropagator.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/propagation/NoopTextMapPropagator.js b/node_modules/@opentelemetry/api/build/esnext/propagation/NoopTextMapPropagator.js new file mode 100644 index 0000000..642b84e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/propagation/NoopTextMapPropagator.js @@ -0,0 +1,30 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * No-op implementations of {@link TextMapPropagator}. + */ +export class NoopTextMapPropagator { + /** Noop inject function does nothing */ + inject(_context, _carrier) { } + /** Noop extract function does nothing and returns the input context */ + extract(context, _carrier) { + return context; + } + fields() { + return []; + } +} +//# sourceMappingURL=NoopTextMapPropagator.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/propagation/NoopTextMapPropagator.js.map b/node_modules/@opentelemetry/api/build/esnext/propagation/NoopTextMapPropagator.js.map new file mode 100644 index 0000000..29ce493 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/propagation/NoopTextMapPropagator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NoopTextMapPropagator.js","sourceRoot":"","sources":["../../../src/propagation/NoopTextMapPropagator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAKH;;GAEG;AACH,MAAM,OAAO,qBAAqB;IAChC,wCAAwC;IACxC,MAAM,CAAC,QAAiB,EAAE,QAAiB,IAAS,CAAC;IACrD,uEAAuE;IACvE,OAAO,CAAC,OAAgB,EAAE,QAAiB;QACzC,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,MAAM;QACJ,OAAO,EAAE,CAAC;IACZ,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport { TextMapPropagator } from './TextMapPropagator';\n\n/**\n * No-op implementations of {@link TextMapPropagator}.\n */\nexport class NoopTextMapPropagator implements TextMapPropagator {\n /** Noop inject function does nothing */\n inject(_context: Context, _carrier: unknown): void {}\n /** Noop extract function does nothing and returns the input context */\n extract(context: Context, _carrier: unknown): Context {\n return context;\n }\n fields(): string[] {\n return [];\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/propagation/TextMapPropagator.d.ts b/node_modules/@opentelemetry/api/build/esnext/propagation/TextMapPropagator.d.ts new file mode 100644 index 0000000..dc39367 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/propagation/TextMapPropagator.d.ts @@ -0,0 +1,84 @@ +import { Context } from '../context/types'; +/** + * Injects `Context` into and extracts it from carriers that travel + * in-band across process boundaries. Encoding is expected to conform to the + * HTTP Header Field semantics. Values are often encoded as RPC/HTTP request + * headers. + * + * The carrier of propagated data on both the client (injector) and server + * (extractor) side is usually an object such as http headers. Propagation is + * usually implemented via library-specific request interceptors, where the + * client-side injects values and the server-side extracts them. + */ +export interface TextMapPropagator { + /** + * Injects values from a given `Context` into a carrier. + * + * OpenTelemetry defines a common set of format values (TextMapPropagator), + * and each has an expected `carrier` type. + * + * @param context the Context from which to extract values to transmit over + * the wire. + * @param carrier the carrier of propagation fields, such as http request + * headers. + * @param setter an optional {@link TextMapSetter}. If undefined, values will be + * set by direct object assignment. + */ + inject(context: Context, carrier: Carrier, setter: TextMapSetter): void; + /** + * Given a `Context` and a carrier, extract context values from a + * carrier and return a new context, created from the old context, with the + * extracted values. + * + * @param context the Context from which to extract values to transmit over + * the wire. + * @param carrier the carrier of propagation fields, such as http request + * headers. + * @param getter an optional {@link TextMapGetter}. If undefined, keys will be all + * own properties, and keys will be accessed by direct object access. + */ + extract(context: Context, carrier: Carrier, getter: TextMapGetter): Context; + /** + * Return a list of all fields which may be used by the propagator. + */ + fields(): string[]; +} +/** + * A setter is specified by the caller to define a specific method + * to set key/value pairs on the carrier within a propagator. + */ +export interface TextMapSetter { + /** + * Callback used to set a key/value pair on an object. + * + * Should be called by the propagator each time a key/value pair + * should be set, and should set that key/value pair on the propagator. + * + * @param carrier object or class which carries key/value pairs + * @param key string key to modify + * @param value value to be set to the key on the carrier + */ + set(carrier: Carrier, key: string, value: string): void; +} +/** + * A getter is specified by the caller to define a specific method + * to get the value of a key from a carrier. + */ +export interface TextMapGetter { + /** + * Get a list of all keys available on the carrier. + * + * @param carrier + */ + keys(carrier: Carrier): string[]; + /** + * Get the value of a specific key from the carrier. + * + * @param carrier + * @param key + */ + get(carrier: Carrier, key: string): undefined | string | string[]; +} +export declare const defaultTextMapGetter: TextMapGetter; +export declare const defaultTextMapSetter: TextMapSetter; +//# sourceMappingURL=TextMapPropagator.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/propagation/TextMapPropagator.js b/node_modules/@opentelemetry/api/build/esnext/propagation/TextMapPropagator.js new file mode 100644 index 0000000..4c36995 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/propagation/TextMapPropagator.js @@ -0,0 +1,38 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export const defaultTextMapGetter = { + get(carrier, key) { + if (carrier == null) { + return undefined; + } + return carrier[key]; + }, + keys(carrier) { + if (carrier == null) { + return []; + } + return Object.keys(carrier); + }, +}; +export const defaultTextMapSetter = { + set(carrier, key, value) { + if (carrier == null) { + return; + } + carrier[key] = value; + }, +}; +//# sourceMappingURL=TextMapPropagator.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/propagation/TextMapPropagator.js.map b/node_modules/@opentelemetry/api/build/esnext/propagation/TextMapPropagator.js.map new file mode 100644 index 0000000..d46019b --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/propagation/TextMapPropagator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"TextMapPropagator.js","sourceRoot":"","sources":["../../../src/propagation/TextMapPropagator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAkGH,MAAM,CAAC,MAAM,oBAAoB,GAAkB;IACjD,GAAG,CAAC,OAAO,EAAE,GAAG;QACd,IAAI,OAAO,IAAI,IAAI,EAAE;YACnB,OAAO,SAAS,CAAC;SAClB;QACD,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC;IACtB,CAAC;IAED,IAAI,CAAC,OAAO;QACV,IAAI,OAAO,IAAI,IAAI,EAAE;YACnB,OAAO,EAAE,CAAC;SACX;QACD,OAAO,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC9B,CAAC;CACF,CAAC;AAEF,MAAM,CAAC,MAAM,oBAAoB,GAAkB;IACjD,GAAG,CAAC,OAAO,EAAE,GAAG,EAAE,KAAK;QACrB,IAAI,OAAO,IAAI,IAAI,EAAE;YACnB,OAAO;SACR;QAED,OAAO,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IACvB,CAAC;CACF,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\n\n/**\n * Injects `Context` into and extracts it from carriers that travel\n * in-band across process boundaries. Encoding is expected to conform to the\n * HTTP Header Field semantics. Values are often encoded as RPC/HTTP request\n * headers.\n *\n * The carrier of propagated data on both the client (injector) and server\n * (extractor) side is usually an object such as http headers. Propagation is\n * usually implemented via library-specific request interceptors, where the\n * client-side injects values and the server-side extracts them.\n */\nexport interface TextMapPropagator {\n /**\n * Injects values from a given `Context` into a carrier.\n *\n * OpenTelemetry defines a common set of format values (TextMapPropagator),\n * and each has an expected `carrier` type.\n *\n * @param context the Context from which to extract values to transmit over\n * the wire.\n * @param carrier the carrier of propagation fields, such as http request\n * headers.\n * @param setter an optional {@link TextMapSetter}. If undefined, values will be\n * set by direct object assignment.\n */\n inject(\n context: Context,\n carrier: Carrier,\n setter: TextMapSetter\n ): void;\n\n /**\n * Given a `Context` and a carrier, extract context values from a\n * carrier and return a new context, created from the old context, with the\n * extracted values.\n *\n * @param context the Context from which to extract values to transmit over\n * the wire.\n * @param carrier the carrier of propagation fields, such as http request\n * headers.\n * @param getter an optional {@link TextMapGetter}. If undefined, keys will be all\n * own properties, and keys will be accessed by direct object access.\n */\n extract(\n context: Context,\n carrier: Carrier,\n getter: TextMapGetter\n ): Context;\n\n /**\n * Return a list of all fields which may be used by the propagator.\n */\n fields(): string[];\n}\n\n/**\n * A setter is specified by the caller to define a specific method\n * to set key/value pairs on the carrier within a propagator.\n */\nexport interface TextMapSetter {\n /**\n * Callback used to set a key/value pair on an object.\n *\n * Should be called by the propagator each time a key/value pair\n * should be set, and should set that key/value pair on the propagator.\n *\n * @param carrier object or class which carries key/value pairs\n * @param key string key to modify\n * @param value value to be set to the key on the carrier\n */\n set(carrier: Carrier, key: string, value: string): void;\n}\n\n/**\n * A getter is specified by the caller to define a specific method\n * to get the value of a key from a carrier.\n */\nexport interface TextMapGetter {\n /**\n * Get a list of all keys available on the carrier.\n *\n * @param carrier\n */\n keys(carrier: Carrier): string[];\n\n /**\n * Get the value of a specific key from the carrier.\n *\n * @param carrier\n * @param key\n */\n get(carrier: Carrier, key: string): undefined | string | string[];\n}\n\nexport const defaultTextMapGetter: TextMapGetter = {\n get(carrier, key) {\n if (carrier == null) {\n return undefined;\n }\n return carrier[key];\n },\n\n keys(carrier) {\n if (carrier == null) {\n return [];\n }\n return Object.keys(carrier);\n },\n};\n\nexport const defaultTextMapSetter: TextMapSetter = {\n set(carrier, key, value) {\n if (carrier == null) {\n return;\n }\n\n carrier[key] = value;\n },\n};\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace-api.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace-api.d.ts new file mode 100644 index 0000000..b4751a7 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace-api.d.ts @@ -0,0 +1,4 @@ +import { TraceAPI } from './api/trace'; +/** Entrypoint for trace API */ +export declare const trace: TraceAPI; +//# sourceMappingURL=trace-api.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace-api.js b/node_modules/@opentelemetry/api/build/esnext/trace-api.js new file mode 100644 index 0000000..3a0b9b0 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace-api.js @@ -0,0 +1,21 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +import { TraceAPI } from './api/trace'; +/** Entrypoint for trace API */ +export const trace = TraceAPI.getInstance(); +//# sourceMappingURL=trace-api.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace-api.js.map b/node_modules/@opentelemetry/api/build/esnext/trace-api.js.map new file mode 100644 index 0000000..3982312 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace-api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-api.js","sourceRoot":"","sources":["../../src/trace-api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,sEAAsE;AACtE,qCAAqC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,+BAA+B;AAC/B,MAAM,CAAC,MAAM,KAAK,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { TraceAPI } from './api/trace';\n/** Entrypoint for trace API */\nexport const trace = TraceAPI.getInstance();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/NonRecordingSpan.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/NonRecordingSpan.d.ts new file mode 100644 index 0000000..ce569f0 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/NonRecordingSpan.d.ts @@ -0,0 +1,28 @@ +import { Exception } from '../common/Exception'; +import { TimeInput } from '../common/Time'; +import { SpanAttributes } from './attributes'; +import { Span } from './span'; +import { SpanContext } from './span_context'; +import { SpanStatus } from './status'; +import { Link } from './link'; +/** + * The NonRecordingSpan is the default {@link Span} that is used when no Span + * implementation is available. All operations are no-op including context + * propagation. + */ +export declare class NonRecordingSpan implements Span { + private readonly _spanContext; + constructor(_spanContext?: SpanContext); + spanContext(): SpanContext; + setAttribute(_key: string, _value: unknown): this; + setAttributes(_attributes: SpanAttributes): this; + addEvent(_name: string, _attributes?: SpanAttributes): this; + addLink(_link: Link): this; + addLinks(_links: Link[]): this; + setStatus(_status: SpanStatus): this; + updateName(_name: string): this; + end(_endTime?: TimeInput): void; + isRecording(): boolean; + recordException(_exception: Exception, _time?: TimeInput): void; +} +//# sourceMappingURL=NonRecordingSpan.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/NonRecordingSpan.js b/node_modules/@opentelemetry/api/build/esnext/trace/NonRecordingSpan.js new file mode 100644 index 0000000..51157cc --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/NonRecordingSpan.js @@ -0,0 +1,65 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { INVALID_SPAN_CONTEXT } from './invalid-span-constants'; +/** + * The NonRecordingSpan is the default {@link Span} that is used when no Span + * implementation is available. All operations are no-op including context + * propagation. + */ +export class NonRecordingSpan { + constructor(_spanContext = INVALID_SPAN_CONTEXT) { + this._spanContext = _spanContext; + } + // Returns a SpanContext. + spanContext() { + return this._spanContext; + } + // By default does nothing + setAttribute(_key, _value) { + return this; + } + // By default does nothing + setAttributes(_attributes) { + return this; + } + // By default does nothing + addEvent(_name, _attributes) { + return this; + } + addLink(_link) { + return this; + } + addLinks(_links) { + return this; + } + // By default does nothing + setStatus(_status) { + return this; + } + // By default does nothing + updateName(_name) { + return this; + } + // By default does nothing + end(_endTime) { } + // isRecording always returns false for NonRecordingSpan. + isRecording() { + return false; + } + // By default does nothing + recordException(_exception, _time) { } +} +//# sourceMappingURL=NonRecordingSpan.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/NonRecordingSpan.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/NonRecordingSpan.js.map new file mode 100644 index 0000000..55dd10b --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/NonRecordingSpan.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NonRecordingSpan.js","sourceRoot":"","sources":["../../../src/trace/NonRecordingSpan.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAKH,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAMhE;;;;GAIG;AACH,MAAM,OAAO,gBAAgB;IAC3B,YACmB,eAA4B,oBAAoB;QAAhD,iBAAY,GAAZ,YAAY,CAAoC;IAChE,CAAC;IAEJ,yBAAyB;IACzB,WAAW;QACT,OAAO,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;IAED,0BAA0B;IAC1B,YAAY,CAAC,IAAY,EAAE,MAAe;QACxC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,0BAA0B;IAC1B,aAAa,CAAC,WAA2B;QACvC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,0BAA0B;IAC1B,QAAQ,CAAC,KAAa,EAAE,WAA4B;QAClD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,CAAC,KAAW;QACjB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,QAAQ,CAAC,MAAc;QACrB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,0BAA0B;IAC1B,SAAS,CAAC,OAAmB;QAC3B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,0BAA0B;IAC1B,UAAU,CAAC,KAAa;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,0BAA0B;IAC1B,GAAG,CAAC,QAAoB,IAAS,CAAC;IAElC,yDAAyD;IACzD,WAAW;QACT,OAAO,KAAK,CAAC;IACf,CAAC;IAED,0BAA0B;IAC1B,eAAe,CAAC,UAAqB,EAAE,KAAiB,IAAS,CAAC;CACnE","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '../common/Exception';\nimport { TimeInput } from '../common/Time';\nimport { SpanAttributes } from './attributes';\nimport { INVALID_SPAN_CONTEXT } from './invalid-span-constants';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\nimport { SpanStatus } from './status';\nimport { Link } from './link';\n\n/**\n * The NonRecordingSpan is the default {@link Span} that is used when no Span\n * implementation is available. All operations are no-op including context\n * propagation.\n */\nexport class NonRecordingSpan implements Span {\n constructor(\n private readonly _spanContext: SpanContext = INVALID_SPAN_CONTEXT\n ) {}\n\n // Returns a SpanContext.\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n // By default does nothing\n setAttribute(_key: string, _value: unknown): this {\n return this;\n }\n\n // By default does nothing\n setAttributes(_attributes: SpanAttributes): this {\n return this;\n }\n\n // By default does nothing\n addEvent(_name: string, _attributes?: SpanAttributes): this {\n return this;\n }\n\n addLink(_link: Link): this {\n return this;\n }\n\n addLinks(_links: Link[]): this {\n return this;\n }\n\n // By default does nothing\n setStatus(_status: SpanStatus): this {\n return this;\n }\n\n // By default does nothing\n updateName(_name: string): this {\n return this;\n }\n\n // By default does nothing\n end(_endTime?: TimeInput): void {}\n\n // isRecording always returns false for NonRecordingSpan.\n isRecording(): boolean {\n return false;\n }\n\n // By default does nothing\n recordException(_exception: Exception, _time?: TimeInput): void {}\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/NoopTracer.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/NoopTracer.d.ts new file mode 100644 index 0000000..0e059c9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/NoopTracer.d.ts @@ -0,0 +1,14 @@ +import { Context } from '../context/types'; +import { Span } from './span'; +import { SpanOptions } from './SpanOptions'; +import { Tracer } from './tracer'; +/** + * No-op implementations of {@link Tracer}. + */ +export declare class NoopTracer implements Tracer { + startSpan(name: string, options?: SpanOptions, context?: Context): Span; + startActiveSpan ReturnType>(name: string, fn: F): ReturnType; + startActiveSpan ReturnType>(name: string, opts: SpanOptions | undefined, fn: F): ReturnType; + startActiveSpan ReturnType>(name: string, opts: SpanOptions | undefined, ctx: Context | undefined, fn: F): ReturnType; +} +//# sourceMappingURL=NoopTracer.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/NoopTracer.js b/node_modules/@opentelemetry/api/build/esnext/trace/NoopTracer.js new file mode 100644 index 0000000..ddc7760 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/NoopTracer.js @@ -0,0 +1,71 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ContextAPI } from '../api/context'; +import { getSpanContext, setSpan } from '../trace/context-utils'; +import { NonRecordingSpan } from './NonRecordingSpan'; +import { isSpanContextValid } from './spancontext-utils'; +const contextApi = ContextAPI.getInstance(); +/** + * No-op implementations of {@link Tracer}. + */ +export class NoopTracer { + // startSpan starts a noop span. + startSpan(name, options, context = contextApi.active()) { + const root = Boolean(options === null || options === void 0 ? void 0 : options.root); + if (root) { + return new NonRecordingSpan(); + } + const parentFromContext = context && getSpanContext(context); + if (isSpanContext(parentFromContext) && + isSpanContextValid(parentFromContext)) { + return new NonRecordingSpan(parentFromContext); + } + else { + return new NonRecordingSpan(); + } + } + startActiveSpan(name, arg2, arg3, arg4) { + let opts; + let ctx; + let fn; + if (arguments.length < 2) { + return; + } + else if (arguments.length === 2) { + fn = arg2; + } + else if (arguments.length === 3) { + opts = arg2; + fn = arg3; + } + else { + opts = arg2; + ctx = arg3; + fn = arg4; + } + const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); + const span = this.startSpan(name, opts, parentContext); + const contextWithSpanSet = setSpan(parentContext, span); + return contextApi.with(contextWithSpanSet, fn, undefined, span); + } +} +function isSpanContext(spanContext) { + return (typeof spanContext === 'object' && + typeof spanContext['spanId'] === 'string' && + typeof spanContext['traceId'] === 'string' && + typeof spanContext['traceFlags'] === 'number'); +} +//# sourceMappingURL=NoopTracer.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/NoopTracer.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/NoopTracer.js.map new file mode 100644 index 0000000..d2f96c7 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/NoopTracer.js.map @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C;SAChB;aAAM,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE;YACjC,IAAI,GAAG,IAA+B,CAAC;YACvC,EAAE,GAAG,IAAS,CAAC;SAChB;aAAM;YACL,IAAI,GAAG,IAA+B,CAAC;YACvC,GAAG,GAAG,IAA2B,CAAC;YAClC,EAAE,GAAG,IAAS,CAAC;SAChB;QAED,MAAM,aAAa,GAAG,GAAG,aAAH,GAAG,cAAH,GAAG,GAAI,UAAU,CAAC,MAAM,EAAE,CAAC;QACjD,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,aAAa,CAAC,CAAC;QACvD,MAAM,kBAAkB,GAAG,OAAO,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC;QAExD,OAAO,UAAU,CAAC,IAAI,CAAC,kBAAkB,EAAE,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;IAClE,CAAC;CACF;AAED,SAAS,aAAa,CAAC,WAAgB;IACrC,OAAO,CACL,OAAO,WAAW,KAAK,QAAQ;QAC/B,OAAO,WAAW,CAAC,QAAQ,CAAC,KAAK,QAAQ;QACzC,OAAO,WAAW,CAAC,SAAS,CAAC,KAAK,QAAQ;QAC1C,OAAO,WAAW,CAAC,YAAY,CAAC,KAAK,QAAQ,CAC9C,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ContextAPI } from '../api/context';\nimport { Context } from '../context/types';\nimport { getSpanContext, setSpan } from '../trace/context-utils';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { Span } from './span';\nimport { isSpanContextValid } from './spancontext-utils';\nimport { SpanOptions } from './SpanOptions';\nimport { SpanContext } from './span_context';\nimport { Tracer } from './tracer';\n\nconst contextApi = ContextAPI.getInstance();\n\n/**\n * No-op implementations of {@link Tracer}.\n */\nexport class NoopTracer implements Tracer {\n // startSpan starts a noop span.\n startSpan(\n name: string,\n options?: SpanOptions,\n context = contextApi.active()\n ): Span {\n const root = Boolean(options?.root);\n if (root) {\n return new NonRecordingSpan();\n }\n\n const parentFromContext = context && getSpanContext(context);\n\n if (\n isSpanContext(parentFromContext) &&\n isSpanContextValid(parentFromContext)\n ) {\n return new NonRecordingSpan(parentFromContext);\n } else {\n return new NonRecordingSpan();\n }\n }\n\n startActiveSpan ReturnType>(\n name: string,\n fn: F\n ): ReturnType;\n startActiveSpan ReturnType>(\n name: string,\n opts: SpanOptions | undefined,\n fn: F\n ): ReturnType;\n startActiveSpan ReturnType>(\n name: string,\n opts: SpanOptions | undefined,\n ctx: Context | undefined,\n fn: F\n ): ReturnType;\n startActiveSpan ReturnType>(\n name: string,\n arg2?: F | SpanOptions,\n arg3?: F | Context,\n arg4?: F\n ): ReturnType | undefined {\n let opts: SpanOptions | undefined;\n let ctx: Context | undefined;\n let fn: F;\n\n if (arguments.length < 2) {\n return;\n } else if (arguments.length === 2) {\n fn = arg2 as F;\n } else if (arguments.length === 3) {\n opts = arg2 as SpanOptions | undefined;\n fn = arg3 as F;\n } else {\n opts = arg2 as SpanOptions | undefined;\n ctx = arg3 as Context | undefined;\n fn = arg4 as F;\n }\n\n const parentContext = ctx ?? contextApi.active();\n const span = this.startSpan(name, opts, parentContext);\n const contextWithSpanSet = setSpan(parentContext, span);\n\n return contextApi.with(contextWithSpanSet, fn, undefined, span);\n }\n}\n\nfunction isSpanContext(spanContext: any): spanContext is SpanContext {\n return (\n typeof spanContext === 'object' &&\n typeof spanContext['spanId'] === 'string' &&\n typeof spanContext['traceId'] === 'string' &&\n typeof spanContext['traceFlags'] === 'number'\n );\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/NoopTracerProvider.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/NoopTracerProvider.d.ts new file mode 100644 index 0000000..ec0fe79 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/NoopTracerProvider.d.ts @@ -0,0 +1,13 @@ +import { Tracer } from './tracer'; +import { TracerOptions } from './tracer_options'; +import { TracerProvider } from './tracer_provider'; +/** + * An implementation of the {@link TracerProvider} which returns an impotent + * Tracer for all calls to `getTracer`. + * + * All operations are no-op. + */ +export declare class NoopTracerProvider implements TracerProvider { + getTracer(_name?: string, _version?: string, _options?: TracerOptions): Tracer; +} +//# sourceMappingURL=NoopTracerProvider.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/NoopTracerProvider.js b/node_modules/@opentelemetry/api/build/esnext/trace/NoopTracerProvider.js new file mode 100644 index 0000000..b542b7d --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/NoopTracerProvider.js @@ -0,0 +1,28 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NoopTracer } from './NoopTracer'; +/** + * An implementation of the {@link TracerProvider} which returns an impotent + * Tracer for all calls to `getTracer`. + * + * All operations are no-op. + */ +export class NoopTracerProvider { + getTracer(_name, _version, _options) { + return new NoopTracer(); + } +} +//# sourceMappingURL=NoopTracerProvider.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/NoopTracerProvider.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/NoopTracerProvider.js.map new file mode 100644 index 0000000..6380d2c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/NoopTracerProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NoopTracerProvider.js","sourceRoot":"","sources":["../../../src/trace/NoopTracerProvider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAK1C;;;;;GAKG;AACH,MAAM,OAAO,kBAAkB;IAC7B,SAAS,CACP,KAAc,EACd,QAAiB,EACjB,QAAwB;QAExB,OAAO,IAAI,UAAU,EAAE,CAAC;IAC1B,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NoopTracer } from './NoopTracer';\nimport { Tracer } from './tracer';\nimport { TracerOptions } from './tracer_options';\nimport { TracerProvider } from './tracer_provider';\n\n/**\n * An implementation of the {@link TracerProvider} which returns an impotent\n * Tracer for all calls to `getTracer`.\n *\n * All operations are no-op.\n */\nexport class NoopTracerProvider implements TracerProvider {\n getTracer(\n _name?: string,\n _version?: string,\n _options?: TracerOptions\n ): Tracer {\n return new NoopTracer();\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracer.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracer.d.ts new file mode 100644 index 0000000..116cc5c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracer.d.ts @@ -0,0 +1,27 @@ +import { Context } from '../context/types'; +import { Span } from './span'; +import { SpanOptions } from './SpanOptions'; +import { Tracer } from './tracer'; +import { TracerOptions } from './tracer_options'; +/** + * Proxy tracer provided by the proxy tracer provider + */ +export declare class ProxyTracer implements Tracer { + private _provider; + readonly name: string; + readonly version?: string | undefined; + readonly options?: TracerOptions | undefined; + private _delegate?; + constructor(_provider: TracerDelegator, name: string, version?: string | undefined, options?: TracerOptions | undefined); + startSpan(name: string, options?: SpanOptions, context?: Context): Span; + startActiveSpan unknown>(_name: string, _options: F | SpanOptions, _context?: F | Context, _fn?: F): ReturnType; + /** + * Try to get a tracer from the proxy tracer provider. + * If the proxy tracer provider has no delegate, return a noop tracer. + */ + private _getTracer; +} +export interface TracerDelegator { + getDelegateTracer(name: string, version?: string, options?: TracerOptions): Tracer | undefined; +} +//# sourceMappingURL=ProxyTracer.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracer.js b/node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracer.js new file mode 100644 index 0000000..94dcb02 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracer.js @@ -0,0 +1,51 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NoopTracer } from './NoopTracer'; +const NOOP_TRACER = new NoopTracer(); +/** + * Proxy tracer provided by the proxy tracer provider + */ +export class ProxyTracer { + constructor(_provider, name, version, options) { + this._provider = _provider; + this.name = name; + this.version = version; + this.options = options; + } + startSpan(name, options, context) { + return this._getTracer().startSpan(name, options, context); + } + startActiveSpan(_name, _options, _context, _fn) { + const tracer = this._getTracer(); + return Reflect.apply(tracer.startActiveSpan, tracer, arguments); + } + /** + * Try to get a tracer from the proxy tracer provider. + * If the proxy tracer provider has no delegate, return a noop tracer. + */ + _getTracer() { + if (this._delegate) { + return this._delegate; + } + const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); + if (!tracer) { + return NOOP_TRACER; + } + this._delegate = tracer; + return this._delegate; + } +} +//# sourceMappingURL=ProxyTracer.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracer.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracer.js.map new file mode 100644 index 0000000..e946938 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ProxyTracer.js","sourceRoot":"","sources":["../../../src/trace/ProxyTracer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAM1C,MAAM,WAAW,GAAG,IAAI,UAAU,EAAE,CAAC;AAErC;;GAEG;AACH,MAAM,OAAO,WAAW;IAItB,YACU,SAA0B,EAClB,IAAY,EACZ,OAAgB,EAChB,OAAuB;QAH/B,cAAS,GAAT,SAAS,CAAiB;QAClB,SAAI,GAAJ,IAAI,CAAQ;QACZ,YAAO,GAAP,OAAO,CAAS;QAChB,YAAO,GAAP,OAAO,CAAgB;IACtC,CAAC;IAEJ,SAAS,CAAC,IAAY,EAAE,OAAqB,EAAE,OAAiB;QAC9D,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAC7D,CAAC;IAED,eAAe,CACb,KAAa,EACb,QAAyB,EACzB,QAAsB,EACtB,GAAO;QAEP,MAAM,MAAM,GAAG,IAAI,CAAC,UAAU,EAAE,CAAC;QACjC,OAAO,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,eAAe,EAAE,MAAM,EAAE,SAAS,CAAC,CAAC;IAClE,CAAC;IAED;;;OAGG;IACK,UAAU;QAChB,IAAI,IAAI,CAAC,SAAS,EAAE;YAClB,OAAO,IAAI,CAAC,SAAS,CAAC;SACvB;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,iBAAiB,CAC7C,IAAI,CAAC,IAAI,EACT,IAAI,CAAC,OAAO,EACZ,IAAI,CAAC,OAAO,CACb,CAAC;QAEF,IAAI,CAAC,MAAM,EAAE;YACX,OAAO,WAAW,CAAC;SACpB;QAED,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC;QACxB,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport { NoopTracer } from './NoopTracer';\nimport { Span } from './span';\nimport { SpanOptions } from './SpanOptions';\nimport { Tracer } from './tracer';\nimport { TracerOptions } from './tracer_options';\n\nconst NOOP_TRACER = new NoopTracer();\n\n/**\n * Proxy tracer provided by the proxy tracer provider\n */\nexport class ProxyTracer implements Tracer {\n // When a real implementation is provided, this will be it\n private _delegate?: Tracer;\n\n constructor(\n private _provider: TracerDelegator,\n public readonly name: string,\n public readonly version?: string,\n public readonly options?: TracerOptions\n ) {}\n\n startSpan(name: string, options?: SpanOptions, context?: Context): Span {\n return this._getTracer().startSpan(name, options, context);\n }\n\n startActiveSpan unknown>(\n _name: string,\n _options: F | SpanOptions,\n _context?: F | Context,\n _fn?: F\n ): ReturnType {\n const tracer = this._getTracer();\n return Reflect.apply(tracer.startActiveSpan, tracer, arguments);\n }\n\n /**\n * Try to get a tracer from the proxy tracer provider.\n * If the proxy tracer provider has no delegate, return a noop tracer.\n */\n private _getTracer() {\n if (this._delegate) {\n return this._delegate;\n }\n\n const tracer = this._provider.getDelegateTracer(\n this.name,\n this.version,\n this.options\n );\n\n if (!tracer) {\n return NOOP_TRACER;\n }\n\n this._delegate = tracer;\n return this._delegate;\n }\n}\n\nexport interface TracerDelegator {\n getDelegateTracer(\n name: string,\n version?: string,\n options?: TracerOptions\n ): Tracer | undefined;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracerProvider.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracerProvider.d.ts new file mode 100644 index 0000000..ee7eafa --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracerProvider.d.ts @@ -0,0 +1,25 @@ +import { Tracer } from './tracer'; +import { TracerProvider } from './tracer_provider'; +import { TracerOptions } from './tracer_options'; +/** + * Tracer provider which provides {@link ProxyTracer}s. + * + * Before a delegate is set, tracers provided are NoOp. + * When a delegate is set, traces are provided from the delegate. + * When a delegate is set after tracers have already been provided, + * all tracers already provided will use the provided delegate implementation. + */ +export declare class ProxyTracerProvider implements TracerProvider { + private _delegate?; + /** + * Get a {@link ProxyTracer} + */ + getTracer(name: string, version?: string, options?: TracerOptions): Tracer; + getDelegate(): TracerProvider; + /** + * Set the delegate tracer provider + */ + setDelegate(delegate: TracerProvider): void; + getDelegateTracer(name: string, version?: string, options?: TracerOptions): Tracer | undefined; +} +//# sourceMappingURL=ProxyTracerProvider.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracerProvider.js b/node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracerProvider.js new file mode 100644 index 0000000..b62fb81 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracerProvider.js @@ -0,0 +1,50 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ProxyTracer } from './ProxyTracer'; +import { NoopTracerProvider } from './NoopTracerProvider'; +const NOOP_TRACER_PROVIDER = new NoopTracerProvider(); +/** + * Tracer provider which provides {@link ProxyTracer}s. + * + * Before a delegate is set, tracers provided are NoOp. + * When a delegate is set, traces are provided from the delegate. + * When a delegate is set after tracers have already been provided, + * all tracers already provided will use the provided delegate implementation. + */ +export class ProxyTracerProvider { + /** + * Get a {@link ProxyTracer} + */ + getTracer(name, version, options) { + var _a; + return ((_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer(this, name, version, options)); + } + getDelegate() { + var _a; + return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER; + } + /** + * Set the delegate tracer provider + */ + setDelegate(delegate) { + this._delegate = delegate; + } + getDelegateTracer(name, version, options) { + var _a; + return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options); + } +} +//# sourceMappingURL=ProxyTracerProvider.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracerProvider.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracerProvider.js.map new file mode 100644 index 0000000..fc11723 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/ProxyTracerProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ProxyTracerProvider.js","sourceRoot":"","sources":["../../../src/trace/ProxyTracerProvider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAG1D,MAAM,oBAAoB,GAAG,IAAI,kBAAkB,EAAE,CAAC;AAEtD;;;;;;;GAOG;AACH,MAAM,OAAO,mBAAmB;IAG9B;;OAEG;IACH,SAAS,CAAC,IAAY,EAAE,OAAgB,EAAE,OAAuB;;QAC/D,OAAO,CACL,MAAA,IAAI,CAAC,iBAAiB,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,mCAC9C,IAAI,WAAW,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAC9C,CAAC;IACJ,CAAC;IAED,WAAW;;QACT,OAAO,MAAA,IAAI,CAAC,SAAS,mCAAI,oBAAoB,CAAC;IAChD,CAAC;IAED;;OAEG;IACH,WAAW,CAAC,QAAwB;QAClC,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;IAC5B,CAAC;IAED,iBAAiB,CACf,IAAY,EACZ,OAAgB,EAChB,OAAuB;;QAEvB,OAAO,MAAA,IAAI,CAAC,SAAS,0CAAE,SAAS,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAC3D,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Tracer } from './tracer';\nimport { TracerProvider } from './tracer_provider';\nimport { ProxyTracer } from './ProxyTracer';\nimport { NoopTracerProvider } from './NoopTracerProvider';\nimport { TracerOptions } from './tracer_options';\n\nconst NOOP_TRACER_PROVIDER = new NoopTracerProvider();\n\n/**\n * Tracer provider which provides {@link ProxyTracer}s.\n *\n * Before a delegate is set, tracers provided are NoOp.\n * When a delegate is set, traces are provided from the delegate.\n * When a delegate is set after tracers have already been provided,\n * all tracers already provided will use the provided delegate implementation.\n */\nexport class ProxyTracerProvider implements TracerProvider {\n private _delegate?: TracerProvider;\n\n /**\n * Get a {@link ProxyTracer}\n */\n getTracer(name: string, version?: string, options?: TracerOptions): Tracer {\n return (\n this.getDelegateTracer(name, version, options) ??\n new ProxyTracer(this, name, version, options)\n );\n }\n\n getDelegate(): TracerProvider {\n return this._delegate ?? NOOP_TRACER_PROVIDER;\n }\n\n /**\n * Set the delegate tracer provider\n */\n setDelegate(delegate: TracerProvider) {\n this._delegate = delegate;\n }\n\n getDelegateTracer(\n name: string,\n version?: string,\n options?: TracerOptions\n ): Tracer | undefined {\n return this._delegate?.getTracer(name, version, options);\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/Sampler.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/Sampler.d.ts new file mode 100644 index 0000000..c847eaf --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/Sampler.d.ts @@ -0,0 +1,31 @@ +import { Context } from '../context/types'; +import { SpanAttributes } from './attributes'; +import { Link } from './link'; +import { SamplingResult } from './SamplingResult'; +import { SpanKind } from './span_kind'; +/** + * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. + * This interface represent a sampler. Sampling is a mechanism to control the + * noise and overhead introduced by OpenTelemetry by reducing the number of + * samples of traces collected and sent to the backend. + */ +export interface Sampler { + /** + * Checks whether span needs to be created and tracked. + * + * @param context Parent Context which may contain a span. + * @param traceId of the span to be created. It can be different from the + * traceId in the {@link SpanContext}. Typically in situations when the + * span to be created starts a new trace. + * @param spanName of the span to be created. + * @param spanKind of the span to be created. + * @param attributes Initial set of SpanAttributes for the Span being constructed. + * @param links Collection of links that will be associated with the Span to + * be created. Typically useful for batch operations. + * @returns a {@link SamplingResult}. + */ + shouldSample(context: Context, traceId: string, spanName: string, spanKind: SpanKind, attributes: SpanAttributes, links: Link[]): SamplingResult; + /** Returns the sampler name or short description with the configuration. */ + toString(): string; +} +//# sourceMappingURL=Sampler.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/Sampler.js b/node_modules/@opentelemetry/api/build/esnext/trace/Sampler.js new file mode 100644 index 0000000..22a60a1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/Sampler.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=Sampler.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/Sampler.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/Sampler.js.map new file mode 100644 index 0000000..66719b1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/Sampler.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Sampler.js","sourceRoot":"","sources":["../../../src/trace/Sampler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport { SpanAttributes } from './attributes';\nimport { Link } from './link';\nimport { SamplingResult } from './SamplingResult';\nimport { SpanKind } from './span_kind';\n\n/**\n * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead.\n * This interface represent a sampler. Sampling is a mechanism to control the\n * noise and overhead introduced by OpenTelemetry by reducing the number of\n * samples of traces collected and sent to the backend.\n */\nexport interface Sampler {\n /**\n * Checks whether span needs to be created and tracked.\n *\n * @param context Parent Context which may contain a span.\n * @param traceId of the span to be created. It can be different from the\n * traceId in the {@link SpanContext}. Typically in situations when the\n * span to be created starts a new trace.\n * @param spanName of the span to be created.\n * @param spanKind of the span to be created.\n * @param attributes Initial set of SpanAttributes for the Span being constructed.\n * @param links Collection of links that will be associated with the Span to\n * be created. Typically useful for batch operations.\n * @returns a {@link SamplingResult}.\n */\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: SpanAttributes,\n links: Link[]\n ): SamplingResult;\n\n /** Returns the sampler name or short description with the configuration. */\n toString(): string;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/SamplingResult.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/SamplingResult.d.ts new file mode 100644 index 0000000..f2bb495 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/SamplingResult.d.ts @@ -0,0 +1,49 @@ +import { SpanAttributes } from './attributes'; +import { TraceState } from './trace_state'; +/** + * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. + * A sampling decision that determines how a {@link Span} will be recorded + * and collected. + */ +export declare enum SamplingDecision { + /** + * `Span.isRecording() === false`, span will not be recorded and all events + * and attributes will be dropped. + */ + NOT_RECORD = 0, + /** + * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} + * MUST NOT be set. + */ + RECORD = 1, + /** + * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} + * MUST be set. + */ + RECORD_AND_SAMPLED = 2 +} +/** + * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. + * A sampling result contains a decision for a {@link Span} and additional + * attributes the sampler would like to added to the Span. + */ +export interface SamplingResult { + /** + * A sampling decision, refer to {@link SamplingDecision} for details. + */ + decision: SamplingDecision; + /** + * The list of attributes returned by SamplingResult MUST be immutable. + * Caller may call {@link Sampler}.shouldSample any number of times and + * can safely cache the returned value. + */ + attributes?: Readonly; + /** + * A {@link TraceState} that will be associated with the {@link Span} through + * the new {@link SpanContext}. Samplers SHOULD return the TraceState from + * the passed-in {@link Context} if they do not intend to change it. Leaving + * the value undefined will also leave the TraceState unchanged. + */ + traceState?: TraceState; +} +//# sourceMappingURL=SamplingResult.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/SamplingResult.js b/node_modules/@opentelemetry/api/build/esnext/trace/SamplingResult.js new file mode 100644 index 0000000..be65741 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/SamplingResult.js @@ -0,0 +1,39 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. + * A sampling decision that determines how a {@link Span} will be recorded + * and collected. + */ +export var SamplingDecision; +(function (SamplingDecision) { + /** + * `Span.isRecording() === false`, span will not be recorded and all events + * and attributes will be dropped. + */ + SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD"; + /** + * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} + * MUST NOT be set. + */ + SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD"; + /** + * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} + * MUST be set. + */ + SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; +})(SamplingDecision || (SamplingDecision = {})); +//# sourceMappingURL=SamplingResult.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/SamplingResult.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/SamplingResult.js.map new file mode 100644 index 0000000..fd549c8 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/SamplingResult.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SamplingResult.js","sourceRoot":"","sources":["../../../src/trace/SamplingResult.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAKH;;;;GAIG;AACH,MAAM,CAAN,IAAY,gBAgBX;AAhBD,WAAY,gBAAgB;IAC1B;;;OAGG;IACH,mEAAU,CAAA;IACV;;;OAGG;IACH,2DAAM,CAAA;IACN;;;OAGG;IACH,mFAAkB,CAAA;AACpB,CAAC,EAhBW,gBAAgB,KAAhB,gBAAgB,QAgB3B","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SpanAttributes } from './attributes';\nimport { TraceState } from './trace_state';\n\n/**\n * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead.\n * A sampling decision that determines how a {@link Span} will be recorded\n * and collected.\n */\nexport enum SamplingDecision {\n /**\n * `Span.isRecording() === false`, span will not be recorded and all events\n * and attributes will be dropped.\n */\n NOT_RECORD,\n /**\n * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}\n * MUST NOT be set.\n */\n RECORD,\n /**\n * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}\n * MUST be set.\n */\n RECORD_AND_SAMPLED,\n}\n\n/**\n * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead.\n * A sampling result contains a decision for a {@link Span} and additional\n * attributes the sampler would like to added to the Span.\n */\nexport interface SamplingResult {\n /**\n * A sampling decision, refer to {@link SamplingDecision} for details.\n */\n decision: SamplingDecision;\n /**\n * The list of attributes returned by SamplingResult MUST be immutable.\n * Caller may call {@link Sampler}.shouldSample any number of times and\n * can safely cache the returned value.\n */\n attributes?: Readonly;\n /**\n * A {@link TraceState} that will be associated with the {@link Span} through\n * the new {@link SpanContext}. Samplers SHOULD return the TraceState from\n * the passed-in {@link Context} if they do not intend to change it. Leaving\n * the value undefined will also leave the TraceState unchanged.\n */\n traceState?: TraceState;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/SpanOptions.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/SpanOptions.d.ts new file mode 100644 index 0000000..c804568 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/SpanOptions.d.ts @@ -0,0 +1,23 @@ +import { TimeInput } from '../common/Time'; +import { SpanAttributes } from './attributes'; +import { Link } from './link'; +import { SpanKind } from './span_kind'; +/** + * Options needed for span creation + */ +export interface SpanOptions { + /** + * The SpanKind of a span + * @default {@link SpanKind.INTERNAL} + */ + kind?: SpanKind; + /** A span's attributes */ + attributes?: SpanAttributes; + /** {@link Link}s span to other spans */ + links?: Link[]; + /** A manually specified start time for the created `Span` object. */ + startTime?: TimeInput; + /** The new span should be a root span. (Ignore parent from context). */ + root?: boolean; +} +//# sourceMappingURL=SpanOptions.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/SpanOptions.js b/node_modules/@opentelemetry/api/build/esnext/trace/SpanOptions.js new file mode 100644 index 0000000..06b42b1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/SpanOptions.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=SpanOptions.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/SpanOptions.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/SpanOptions.js.map new file mode 100644 index 0000000..9132a33 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/SpanOptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SpanOptions.js","sourceRoot":"","sources":["../../../src/trace/SpanOptions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TimeInput } from '../common/Time';\nimport { SpanAttributes } from './attributes';\nimport { Link } from './link';\nimport { SpanKind } from './span_kind';\n\n/**\n * Options needed for span creation\n */\nexport interface SpanOptions {\n /**\n * The SpanKind of a span\n * @default {@link SpanKind.INTERNAL}\n */\n kind?: SpanKind;\n\n /** A span's attributes */\n attributes?: SpanAttributes;\n\n /** {@link Link}s span to other spans */\n links?: Link[];\n\n /** A manually specified start time for the created `Span` object. */\n startTime?: TimeInput;\n\n /** The new span should be a root span. (Ignore parent from context). */\n root?: boolean;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/attributes.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/attributes.d.ts new file mode 100644 index 0000000..a2a5d2a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/attributes.d.ts @@ -0,0 +1,10 @@ +import { Attributes, AttributeValue } from '../common/Attributes'; +/** + * @deprecated please use {@link Attributes} + */ +export declare type SpanAttributes = Attributes; +/** + * @deprecated please use {@link AttributeValue} + */ +export declare type SpanAttributeValue = AttributeValue; +//# sourceMappingURL=attributes.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/attributes.js b/node_modules/@opentelemetry/api/build/esnext/trace/attributes.js new file mode 100644 index 0000000..6f1b9a3 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/attributes.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=attributes.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/attributes.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/attributes.js.map new file mode 100644 index 0000000..2b02be7 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/attributes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"attributes.js","sourceRoot":"","sources":["../../../src/trace/attributes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Attributes, AttributeValue } from '../common/Attributes';\n\n/**\n * @deprecated please use {@link Attributes}\n */\nexport type SpanAttributes = Attributes;\n\n/**\n * @deprecated please use {@link AttributeValue}\n */\nexport type SpanAttributeValue = AttributeValue;\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/context-utils.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/context-utils.d.ts new file mode 100644 index 0000000..f35f794 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/context-utils.d.ts @@ -0,0 +1,41 @@ +import { Context } from '../context/types'; +import { Span } from './span'; +import { SpanContext } from './span_context'; +/** + * Return the span if one exists + * + * @param context context to get span from + */ +export declare function getSpan(context: Context): Span | undefined; +/** + * Gets the span from the current context, if one exists. + */ +export declare function getActiveSpan(): Span | undefined; +/** + * Set the span on a context + * + * @param context context to use as parent + * @param span span to set active + */ +export declare function setSpan(context: Context, span: Span): Context; +/** + * Remove current span stored in the context + * + * @param context context to delete span from + */ +export declare function deleteSpan(context: Context): Context; +/** + * Wrap span context in a NoopSpan and set as span in a new + * context + * + * @param context context to set active span on + * @param spanContext span context to be wrapped + */ +export declare function setSpanContext(context: Context, spanContext: SpanContext): Context; +/** + * Get the span context of the span if it exists. + * + * @param context context to get values from + */ +export declare function getSpanContext(context: Context): SpanContext | undefined; +//# sourceMappingURL=context-utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/context-utils.js b/node_modules/@opentelemetry/api/build/esnext/trace/context-utils.js new file mode 100644 index 0000000..5d113f1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/context-utils.js @@ -0,0 +1,73 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { createContextKey } from '../context/context'; +import { NonRecordingSpan } from './NonRecordingSpan'; +import { ContextAPI } from '../api/context'; +/** + * span key + */ +const SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN'); +/** + * Return the span if one exists + * + * @param context context to get span from + */ +export function getSpan(context) { + return context.getValue(SPAN_KEY) || undefined; +} +/** + * Gets the span from the current context, if one exists. + */ +export function getActiveSpan() { + return getSpan(ContextAPI.getInstance().active()); +} +/** + * Set the span on a context + * + * @param context context to use as parent + * @param span span to set active + */ +export function setSpan(context, span) { + return context.setValue(SPAN_KEY, span); +} +/** + * Remove current span stored in the context + * + * @param context context to delete span from + */ +export function deleteSpan(context) { + return context.deleteValue(SPAN_KEY); +} +/** + * Wrap span context in a NoopSpan and set as span in a new + * context + * + * @param context context to set active span on + * @param spanContext span context to be wrapped + */ +export function setSpanContext(context, spanContext) { + return setSpan(context, new NonRecordingSpan(spanContext)); +} +/** + * Get the span context of the span if it exists. + * + * @param context context to get values from + */ +export function getSpanContext(context) { + var _a; + return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext(); +} +//# sourceMappingURL=context-utils.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/context-utils.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/context-utils.js.map new file mode 100644 index 0000000..a8917a4 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/context-utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"context-utils.js","sourceRoot":"","sources":["../../../src/trace/context-utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAItD,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C;;GAEG;AACH,MAAM,QAAQ,GAAG,gBAAgB,CAAC,gCAAgC,CAAC,CAAC;AAEpE;;;;GAIG;AACH,MAAM,UAAU,OAAO,CAAC,OAAgB;IACtC,OAAQ,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAU,IAAI,SAAS,CAAC;AAC3D,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,aAAa;IAC3B,OAAO,OAAO,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC;AACpD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,OAAO,CAAC,OAAgB,EAAE,IAAU;IAClD,OAAO,OAAO,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;AAC1C,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,UAAU,CAAC,OAAgB;IACzC,OAAO,OAAO,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;AACvC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,cAAc,CAC5B,OAAgB,EAChB,WAAwB;IAExB,OAAO,OAAO,CAAC,OAAO,EAAE,IAAI,gBAAgB,CAAC,WAAW,CAAC,CAAC,CAAC;AAC7D,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,OAAgB;;IAC7C,OAAO,MAAA,OAAO,CAAC,OAAO,CAAC,0CAAE,WAAW,EAAE,CAAC;AACzC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createContextKey } from '../context/context';\nimport { Context } from '../context/types';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { ContextAPI } from '../api/context';\n\n/**\n * span key\n */\nconst SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN');\n\n/**\n * Return the span if one exists\n *\n * @param context context to get span from\n */\nexport function getSpan(context: Context): Span | undefined {\n return (context.getValue(SPAN_KEY) as Span) || undefined;\n}\n\n/**\n * Gets the span from the current context, if one exists.\n */\nexport function getActiveSpan(): Span | undefined {\n return getSpan(ContextAPI.getInstance().active());\n}\n\n/**\n * Set the span on a context\n *\n * @param context context to use as parent\n * @param span span to set active\n */\nexport function setSpan(context: Context, span: Span): Context {\n return context.setValue(SPAN_KEY, span);\n}\n\n/**\n * Remove current span stored in the context\n *\n * @param context context to delete span from\n */\nexport function deleteSpan(context: Context): Context {\n return context.deleteValue(SPAN_KEY);\n}\n\n/**\n * Wrap span context in a NoopSpan and set as span in a new\n * context\n *\n * @param context context to set active span on\n * @param spanContext span context to be wrapped\n */\nexport function setSpanContext(\n context: Context,\n spanContext: SpanContext\n): Context {\n return setSpan(context, new NonRecordingSpan(spanContext));\n}\n\n/**\n * Get the span context of the span if it exists.\n *\n * @param context context to get values from\n */\nexport function getSpanContext(context: Context): SpanContext | undefined {\n return getSpan(context)?.spanContext();\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-impl.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-impl.d.ts new file mode 100644 index 0000000..9ed5ecb --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-impl.d.ts @@ -0,0 +1,22 @@ +import { TraceState } from '../trace_state'; +/** + * TraceState must be a class and not a simple object type because of the spec + * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). + * + * Here is the list of allowed mutations: + * - New key-value pair should be added into the beginning of the list + * - The value of any key can be updated. Modified keys MUST be moved to the + * beginning of the list. + */ +export declare class TraceStateImpl implements TraceState { + private _internalState; + constructor(rawTraceState?: string); + set(key: string, value: string): TraceStateImpl; + unset(key: string): TraceStateImpl; + get(key: string): string | undefined; + serialize(): string; + private _parse; + private _keys; + private _clone; +} +//# sourceMappingURL=tracestate-impl.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-impl.js b/node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-impl.js new file mode 100644 index 0000000..3be2ea3 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-impl.js @@ -0,0 +1,99 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { validateKey, validateValue } from './tracestate-validators'; +const MAX_TRACE_STATE_ITEMS = 32; +const MAX_TRACE_STATE_LEN = 512; +const LIST_MEMBERS_SEPARATOR = ','; +const LIST_MEMBER_KEY_VALUE_SPLITTER = '='; +/** + * TraceState must be a class and not a simple object type because of the spec + * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). + * + * Here is the list of allowed mutations: + * - New key-value pair should be added into the beginning of the list + * - The value of any key can be updated. Modified keys MUST be moved to the + * beginning of the list. + */ +export class TraceStateImpl { + constructor(rawTraceState) { + this._internalState = new Map(); + if (rawTraceState) + this._parse(rawTraceState); + } + set(key, value) { + // TODO: Benchmark the different approaches(map vs list) and + // use the faster one. + const traceState = this._clone(); + if (traceState._internalState.has(key)) { + traceState._internalState.delete(key); + } + traceState._internalState.set(key, value); + return traceState; + } + unset(key) { + const traceState = this._clone(); + traceState._internalState.delete(key); + return traceState; + } + get(key) { + return this._internalState.get(key); + } + serialize() { + return this._keys() + .reduce((agg, key) => { + agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); + return agg; + }, []) + .join(LIST_MEMBERS_SEPARATOR); + } + _parse(rawTraceState) { + if (rawTraceState.length > MAX_TRACE_STATE_LEN) + return; + this._internalState = rawTraceState + .split(LIST_MEMBERS_SEPARATOR) + .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning + .reduce((agg, part) => { + const listMember = part.trim(); // Optional Whitespace (OWS) handling + const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); + if (i !== -1) { + const key = listMember.slice(0, i); + const value = listMember.slice(i + 1, part.length); + if (validateKey(key) && validateValue(value)) { + agg.set(key, value); + } + else { + // TODO: Consider to add warning log + } + } + return agg; + }, new Map()); + // Because of the reverse() requirement, trunc must be done after map is created + if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { + this._internalState = new Map(Array.from(this._internalState.entries()) + .reverse() // Use reverse same as original tracestate parse chain + .slice(0, MAX_TRACE_STATE_ITEMS)); + } + } + _keys() { + return Array.from(this._internalState.keys()).reverse(); + } + _clone() { + const traceState = new TraceStateImpl(); + traceState._internalState = new Map(this._internalState); + return traceState; + } +} +//# sourceMappingURL=tracestate-impl.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-impl.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-impl.js.map new file mode 100644 index 0000000..90f35e6 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-impl.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tracestate-impl.js","sourceRoot":"","sources":["../../../../src/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AO,EAAE,CAAC,sDAAsD;iBAChE,KAAK,CAAC,CAAC,EAAE,qBAAqB,CAAC,CACnC,CAAC;SACH;IACH,CAAC;IAEO,KAAK;QACX,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC;IAC1D,CAAC;IAEO,MAAM;QACZ,MAAM,UAAU,GAAG,IAAI,cAAc,EAAE,CAAC;QACxC,UAAU,CAAC,cAAc,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QACzD,OAAO,UAAU,CAAC;IACpB,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TraceState } from '../trace_state';\nimport { validateKey, validateValue } from './tracestate-validators';\n\nconst MAX_TRACE_STATE_ITEMS = 32;\nconst MAX_TRACE_STATE_LEN = 512;\nconst LIST_MEMBERS_SEPARATOR = ',';\nconst LIST_MEMBER_KEY_VALUE_SPLITTER = '=';\n\n/**\n * TraceState must be a class and not a simple object type because of the spec\n * requirement (https://www.w3.org/TR/trace-context/#tracestate-field).\n *\n * Here is the list of allowed mutations:\n * - New key-value pair should be added into the beginning of the list\n * - The value of any key can be updated. Modified keys MUST be moved to the\n * beginning of the list.\n */\nexport class TraceStateImpl implements TraceState {\n private _internalState: Map = new Map();\n\n constructor(rawTraceState?: string) {\n if (rawTraceState) this._parse(rawTraceState);\n }\n\n set(key: string, value: string): TraceStateImpl {\n // TODO: Benchmark the different approaches(map vs list) and\n // use the faster one.\n const traceState = this._clone();\n if (traceState._internalState.has(key)) {\n traceState._internalState.delete(key);\n }\n traceState._internalState.set(key, value);\n return traceState;\n }\n\n unset(key: string): TraceStateImpl {\n const traceState = this._clone();\n traceState._internalState.delete(key);\n return traceState;\n }\n\n get(key: string): string | undefined {\n return this._internalState.get(key);\n }\n\n serialize(): string {\n return this._keys()\n .reduce((agg: string[], key) => {\n agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));\n return agg;\n }, [])\n .join(LIST_MEMBERS_SEPARATOR);\n }\n\n private _parse(rawTraceState: string) {\n if (rawTraceState.length > MAX_TRACE_STATE_LEN) return;\n this._internalState = rawTraceState\n .split(LIST_MEMBERS_SEPARATOR)\n .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning\n .reduce((agg: Map, part: string) => {\n const listMember = part.trim(); // Optional Whitespace (OWS) handling\n const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);\n if (i !== -1) {\n const key = listMember.slice(0, i);\n const value = listMember.slice(i + 1, part.length);\n if (validateKey(key) && validateValue(value)) {\n agg.set(key, value);\n } else {\n // TODO: Consider to add warning log\n }\n }\n return agg;\n }, new Map());\n\n // Because of the reverse() requirement, trunc must be done after map is created\n if (this._internalState.size > MAX_TRACE_STATE_ITEMS) {\n this._internalState = new Map(\n Array.from(this._internalState.entries())\n .reverse() // Use reverse same as original tracestate parse chain\n .slice(0, MAX_TRACE_STATE_ITEMS)\n );\n }\n }\n\n private _keys(): string[] {\n return Array.from(this._internalState.keys()).reverse();\n }\n\n private _clone(): TraceStateImpl {\n const traceState = new TraceStateImpl();\n traceState._internalState = new Map(this._internalState);\n return traceState;\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-validators.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-validators.d.ts new file mode 100644 index 0000000..4917f99 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-validators.d.ts @@ -0,0 +1,15 @@ +/** + * Key is opaque string up to 256 characters printable. It MUST begin with a + * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, + * underscores _, dashes -, asterisks *, and forward slashes /. + * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the + * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. + * see https://www.w3.org/TR/trace-context/#key + */ +export declare function validateKey(key: string): boolean; +/** + * Value is opaque string up to 256 characters printable ASCII RFC0020 + * characters (i.e., the range 0x20 to 0x7E) except comma , and =. + */ +export declare function validateValue(value: string): boolean; +//# sourceMappingURL=tracestate-validators.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-validators.js b/node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-validators.js new file mode 100644 index 0000000..3a4f95f --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-validators.js @@ -0,0 +1,41 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]'; +const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; +const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; +const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); +const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; +const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; +/** + * Key is opaque string up to 256 characters printable. It MUST begin with a + * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, + * underscores _, dashes -, asterisks *, and forward slashes /. + * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the + * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. + * see https://www.w3.org/TR/trace-context/#key + */ +export function validateKey(key) { + return VALID_KEY_REGEX.test(key); +} +/** + * Value is opaque string up to 256 characters printable ASCII RFC0020 + * characters (i.e., the range 0x20 to 0x7E) except comma , and =. + */ +export function validateValue(value) { + return (VALID_VALUE_BASE_REGEX.test(value) && + !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)); +} +//# sourceMappingURL=tracestate-validators.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-validators.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-validators.js.map new file mode 100644 index 0000000..20d02b8 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/internal/tracestate-validators.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tracestate-validators.js","sourceRoot":"","sources":["../../../../src/trace/internal/tracestate-validators.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,MAAM,oBAAoB,GAAG,cAAc,CAAC;AAC5C,MAAM,SAAS,GAAG,QAAQ,oBAAoB,SAAS,CAAC;AACxD,MAAM,gBAAgB,GAAG,WAAW,oBAAoB,gBAAgB,oBAAoB,QAAQ,CAAC;AACrG,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,OAAO,SAAS,IAAI,gBAAgB,IAAI,CAAC,CAAC;AAC7E,MAAM,sBAAsB,GAAG,qBAAqB,CAAC;AACrD,MAAM,+BAA+B,GAAG,KAAK,CAAC;AAE9C;;;;;;;GAOG;AACH,MAAM,UAAU,WAAW,CAAC,GAAW;IACrC,OAAO,eAAe,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACnC,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,KAAa;IACzC,OAAO,CACL,sBAAsB,CAAC,IAAI,CAAC,KAAK,CAAC;QAClC,CAAC,+BAA+B,CAAC,IAAI,CAAC,KAAK,CAAC,CAC7C,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]';\nconst VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;\nconst VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;\nconst VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);\nconst VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;\nconst INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;\n\n/**\n * Key is opaque string up to 256 characters printable. It MUST begin with a\n * lowercase letter, and can only contain lowercase letters a-z, digits 0-9,\n * underscores _, dashes -, asterisks *, and forward slashes /.\n * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the\n * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key.\n * see https://www.w3.org/TR/trace-context/#key\n */\nexport function validateKey(key: string): boolean {\n return VALID_KEY_REGEX.test(key);\n}\n\n/**\n * Value is opaque string up to 256 characters printable ASCII RFC0020\n * characters (i.e., the range 0x20 to 0x7E) except comma , and =.\n */\nexport function validateValue(value: string): boolean {\n return (\n VALID_VALUE_BASE_REGEX.test(value) &&\n !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)\n );\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/internal/utils.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/internal/utils.d.ts new file mode 100644 index 0000000..e3b51fe --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/internal/utils.d.ts @@ -0,0 +1,3 @@ +import { TraceState } from '../trace_state'; +export declare function createTraceState(rawTraceState?: string): TraceState; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/internal/utils.js b/node_modules/@opentelemetry/api/build/esnext/trace/internal/utils.js new file mode 100644 index 0000000..feea469 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/internal/utils.js @@ -0,0 +1,20 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { TraceStateImpl } from './tracestate-impl'; +export function createTraceState(rawTraceState) { + return new TraceStateImpl(rawTraceState); +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/internal/utils.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/internal/utils.js.map new file mode 100644 index 0000000..91ba3d1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/internal/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/trace/internal/utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEnD,MAAM,UAAU,gBAAgB,CAAC,aAAsB;IACrD,OAAO,IAAI,cAAc,CAAC,aAAa,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TraceState } from '../trace_state';\nimport { TraceStateImpl } from './tracestate-impl';\n\nexport function createTraceState(rawTraceState?: string): TraceState {\n return new TraceStateImpl(rawTraceState);\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/invalid-span-constants.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/invalid-span-constants.d.ts new file mode 100644 index 0000000..e32dab9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/invalid-span-constants.d.ts @@ -0,0 +1,5 @@ +import { SpanContext } from './span_context'; +export declare const INVALID_SPANID = "0000000000000000"; +export declare const INVALID_TRACEID = "00000000000000000000000000000000"; +export declare const INVALID_SPAN_CONTEXT: SpanContext; +//# sourceMappingURL=invalid-span-constants.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/invalid-span-constants.js b/node_modules/@opentelemetry/api/build/esnext/trace/invalid-span-constants.js new file mode 100644 index 0000000..bd912f4 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/invalid-span-constants.js @@ -0,0 +1,24 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { TraceFlags } from './trace_flags'; +export const INVALID_SPANID = '0000000000000000'; +export const INVALID_TRACEID = '00000000000000000000000000000000'; +export const INVALID_SPAN_CONTEXT = { + traceId: INVALID_TRACEID, + spanId: INVALID_SPANID, + traceFlags: TraceFlags.NONE, +}; +//# sourceMappingURL=invalid-span-constants.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/invalid-span-constants.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/invalid-span-constants.js.map new file mode 100644 index 0000000..9c337c4 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/invalid-span-constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"invalid-span-constants.js","sourceRoot":"","sources":["../../../src/trace/invalid-span-constants.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,MAAM,CAAC,MAAM,cAAc,GAAG,kBAAkB,CAAC;AACjD,MAAM,CAAC,MAAM,eAAe,GAAG,kCAAkC,CAAC;AAClE,MAAM,CAAC,MAAM,oBAAoB,GAAgB;IAC/C,OAAO,EAAE,eAAe;IACxB,MAAM,EAAE,cAAc;IACtB,UAAU,EAAE,UAAU,CAAC,IAAI;CAC5B,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SpanContext } from './span_context';\nimport { TraceFlags } from './trace_flags';\n\nexport const INVALID_SPANID = '0000000000000000';\nexport const INVALID_TRACEID = '00000000000000000000000000000000';\nexport const INVALID_SPAN_CONTEXT: SpanContext = {\n traceId: INVALID_TRACEID,\n spanId: INVALID_SPANID,\n traceFlags: TraceFlags.NONE,\n};\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/link.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/link.d.ts new file mode 100644 index 0000000..8fc0106 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/link.d.ts @@ -0,0 +1,26 @@ +import { SpanAttributes } from './attributes'; +import { SpanContext } from './span_context'; +/** + * A pointer from the current {@link Span} to another span in the same trace or + * in a different trace. + * Few examples of Link usage. + * 1. Batch Processing: A batch of elements may contain elements associated + * with one or more traces/spans. Since there can only be one parent + * SpanContext, Link is used to keep reference to SpanContext of all + * elements in the batch. + * 2. Public Endpoint: A SpanContext in incoming client request on a public + * endpoint is untrusted from service provider perspective. In such case it + * is advisable to start a new trace with appropriate sampling decision. + * However, it is desirable to associate incoming SpanContext to new trace + * initiated on service provider side so two traces (from Client and from + * Service Provider) can be correlated. + */ +export interface Link { + /** The {@link SpanContext} of a linked span. */ + context: SpanContext; + /** A set of {@link SpanAttributes} on the link. */ + attributes?: SpanAttributes; + /** Count of attributes of the link that were dropped due to collection limits */ + droppedAttributesCount?: number; +} +//# sourceMappingURL=link.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/link.js b/node_modules/@opentelemetry/api/build/esnext/trace/link.js new file mode 100644 index 0000000..7c8accb --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/link.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=link.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/link.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/link.js.map new file mode 100644 index 0000000..c10b714 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/link.js.map @@ -0,0 +1 @@ +{"version":3,"file":"link.js","sourceRoot":"","sources":["../../../src/trace/link.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SpanAttributes } from './attributes';\nimport { SpanContext } from './span_context';\n\n/**\n * A pointer from the current {@link Span} to another span in the same trace or\n * in a different trace.\n * Few examples of Link usage.\n * 1. Batch Processing: A batch of elements may contain elements associated\n * with one or more traces/spans. Since there can only be one parent\n * SpanContext, Link is used to keep reference to SpanContext of all\n * elements in the batch.\n * 2. Public Endpoint: A SpanContext in incoming client request on a public\n * endpoint is untrusted from service provider perspective. In such case it\n * is advisable to start a new trace with appropriate sampling decision.\n * However, it is desirable to associate incoming SpanContext to new trace\n * initiated on service provider side so two traces (from Client and from\n * Service Provider) can be correlated.\n */\nexport interface Link {\n /** The {@link SpanContext} of a linked span. */\n context: SpanContext;\n /** A set of {@link SpanAttributes} on the link. */\n attributes?: SpanAttributes;\n /** Count of attributes of the link that were dropped due to collection limits */\n droppedAttributesCount?: number;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/span.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/span.d.ts new file mode 100644 index 0000000..28c6442 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/span.d.ts @@ -0,0 +1,120 @@ +import { Exception } from '../common/Exception'; +import { TimeInput } from '../common/Time'; +import { SpanAttributes, SpanAttributeValue } from './attributes'; +import { SpanContext } from './span_context'; +import { SpanStatus } from './status'; +import { Link } from './link'; +/** + * An interface that represents a span. A span represents a single operation + * within a trace. Examples of span might include remote procedure calls or a + * in-process function calls to sub-components. A Trace has a single, top-level + * "root" Span that in turn may have zero or more child Spans, which in turn + * may have children. + * + * Spans are created by the {@link Tracer.startSpan} method. + */ +export interface Span { + /** + * Returns the {@link SpanContext} object associated with this Span. + * + * Get an immutable, serializable identifier for this span that can be used + * to create new child spans. Returned SpanContext is usable even after the + * span ends. + * + * @returns the SpanContext object associated with this Span. + */ + spanContext(): SpanContext; + /** + * Sets an attribute to the span. + * + * Sets a single Attribute with the key and value passed as arguments. + * + * @param key the key for this attribute. + * @param value the value for this attribute. Setting a value null or + * undefined is invalid and will result in undefined behavior. + */ + setAttribute(key: string, value: SpanAttributeValue): this; + /** + * Sets attributes to the span. + * + * @param attributes the attributes that will be added. + * null or undefined attribute values + * are invalid and will result in undefined behavior. + */ + setAttributes(attributes: SpanAttributes): this; + /** + * Adds an event to the Span. + * + * @param name the name of the event. + * @param [attributesOrStartTime] the attributes that will be added; these are + * associated with this event. Can be also a start time + * if type is {@type TimeInput} and 3rd param is undefined + * @param [startTime] start time of the event. + */ + addEvent(name: string, attributesOrStartTime?: SpanAttributes | TimeInput, startTime?: TimeInput): this; + /** + * Adds a single link to the span. + * + * Links added after the creation will not affect the sampling decision. + * It is preferred span links be added at span creation. + * + * @param link the link to add. + */ + addLink(link: Link): this; + /** + * Adds multiple links to the span. + * + * Links added after the creation will not affect the sampling decision. + * It is preferred span links be added at span creation. + * + * @param links the links to add. + */ + addLinks(links: Link[]): this; + /** + * Sets a status to the span. If used, this will override the default Span + * status. Default is {@link SpanStatusCode.UNSET}. SetStatus overrides the value + * of previous calls to SetStatus on the Span. + * + * @param status the SpanStatus to set. + */ + setStatus(status: SpanStatus): this; + /** + * Updates the Span name. + * + * This will override the name provided via {@link Tracer.startSpan}. + * + * Upon this update, any sampling behavior based on Span name will depend on + * the implementation. + * + * @param name the Span name. + */ + updateName(name: string): this; + /** + * Marks the end of Span execution. + * + * Call to End of a Span MUST not have any effects on child spans. Those may + * still be running and can be ended later. + * + * Do not return `this`. The Span generally should not be used after it + * is ended so chaining is not desired in this context. + * + * @param [endTime] the time to set as Span's end time. If not provided, + * use the current time as the span's end time. + */ + end(endTime?: TimeInput): void; + /** + * Returns the flag whether this span will be recorded. + * + * @returns true if this Span is active and recording information like events + * with the `AddEvent` operation and attributes using `setAttributes`. + */ + isRecording(): boolean; + /** + * Sets exception as a span event + * @param exception the exception the only accepted values are string or Error + * @param [time] the time to set as Span's event time. If not provided, + * use the current time. + */ + recordException(exception: Exception, time?: TimeInput): void; +} +//# sourceMappingURL=span.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/span.js b/node_modules/@opentelemetry/api/build/esnext/trace/span.js new file mode 100644 index 0000000..f41c7f6 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/span.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=span.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/span.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/span.js.map new file mode 100644 index 0000000..f9a1e32 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/span.js.map @@ -0,0 +1 @@ +{"version":3,"file":"span.js","sourceRoot":"","sources":["../../../src/trace/span.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '../common/Exception';\nimport { TimeInput } from '../common/Time';\nimport { SpanAttributes, SpanAttributeValue } from './attributes';\nimport { SpanContext } from './span_context';\nimport { SpanStatus } from './status';\nimport { Link } from './link';\n\n/**\n * An interface that represents a span. A span represents a single operation\n * within a trace. Examples of span might include remote procedure calls or a\n * in-process function calls to sub-components. A Trace has a single, top-level\n * \"root\" Span that in turn may have zero or more child Spans, which in turn\n * may have children.\n *\n * Spans are created by the {@link Tracer.startSpan} method.\n */\nexport interface Span {\n /**\n * Returns the {@link SpanContext} object associated with this Span.\n *\n * Get an immutable, serializable identifier for this span that can be used\n * to create new child spans. Returned SpanContext is usable even after the\n * span ends.\n *\n * @returns the SpanContext object associated with this Span.\n */\n spanContext(): SpanContext;\n\n /**\n * Sets an attribute to the span.\n *\n * Sets a single Attribute with the key and value passed as arguments.\n *\n * @param key the key for this attribute.\n * @param value the value for this attribute. Setting a value null or\n * undefined is invalid and will result in undefined behavior.\n */\n setAttribute(key: string, value: SpanAttributeValue): this;\n\n /**\n * Sets attributes to the span.\n *\n * @param attributes the attributes that will be added.\n * null or undefined attribute values\n * are invalid and will result in undefined behavior.\n */\n setAttributes(attributes: SpanAttributes): this;\n\n /**\n * Adds an event to the Span.\n *\n * @param name the name of the event.\n * @param [attributesOrStartTime] the attributes that will be added; these are\n * associated with this event. Can be also a start time\n * if type is {@type TimeInput} and 3rd param is undefined\n * @param [startTime] start time of the event.\n */\n addEvent(\n name: string,\n attributesOrStartTime?: SpanAttributes | TimeInput,\n startTime?: TimeInput\n ): this;\n\n /**\n * Adds a single link to the span.\n *\n * Links added after the creation will not affect the sampling decision.\n * It is preferred span links be added at span creation.\n *\n * @param link the link to add.\n */\n addLink(link: Link): this;\n\n /**\n * Adds multiple links to the span.\n *\n * Links added after the creation will not affect the sampling decision.\n * It is preferred span links be added at span creation.\n *\n * @param links the links to add.\n */\n addLinks(links: Link[]): this;\n\n /**\n * Sets a status to the span. If used, this will override the default Span\n * status. Default is {@link SpanStatusCode.UNSET}. SetStatus overrides the value\n * of previous calls to SetStatus on the Span.\n *\n * @param status the SpanStatus to set.\n */\n setStatus(status: SpanStatus): this;\n\n /**\n * Updates the Span name.\n *\n * This will override the name provided via {@link Tracer.startSpan}.\n *\n * Upon this update, any sampling behavior based on Span name will depend on\n * the implementation.\n *\n * @param name the Span name.\n */\n updateName(name: string): this;\n\n /**\n * Marks the end of Span execution.\n *\n * Call to End of a Span MUST not have any effects on child spans. Those may\n * still be running and can be ended later.\n *\n * Do not return `this`. The Span generally should not be used after it\n * is ended so chaining is not desired in this context.\n *\n * @param [endTime] the time to set as Span's end time. If not provided,\n * use the current time as the span's end time.\n */\n end(endTime?: TimeInput): void;\n\n /**\n * Returns the flag whether this span will be recorded.\n *\n * @returns true if this Span is active and recording information like events\n * with the `AddEvent` operation and attributes using `setAttributes`.\n */\n isRecording(): boolean;\n\n /**\n * Sets exception as a span event\n * @param exception the exception the only accepted values are string or Error\n * @param [time] the time to set as Span's event time. If not provided,\n * use the current time.\n */\n recordException(exception: Exception, time?: TimeInput): void;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/span_context.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/span_context.d.ts new file mode 100644 index 0000000..f30933a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/span_context.d.ts @@ -0,0 +1,53 @@ +import { TraceState } from './trace_state'; +/** + * A SpanContext represents the portion of a {@link Span} which must be + * serialized and propagated along side of a {@link Baggage}. + */ +export interface SpanContext { + /** + * The ID of the trace that this span belongs to. It is worldwide unique + * with practically sufficient probability by being made as 16 randomly + * generated bytes, encoded as a 32 lowercase hex characters corresponding to + * 128 bits. + */ + traceId: string; + /** + * The ID of the Span. It is globally unique with practically sufficient + * probability by being made as 8 randomly generated bytes, encoded as a 16 + * lowercase hex characters corresponding to 64 bits. + */ + spanId: string; + /** + * Only true if the SpanContext was propagated from a remote parent. + */ + isRemote?: boolean; + /** + * Trace flags to propagate. + * + * It is represented as 1 byte (bitmap). Bit to represent whether trace is + * sampled or not. When set, the least significant bit documents that the + * caller may have recorded trace data. A caller who does not record trace + * data out-of-band leaves this flag unset. + * + * see {@link TraceFlags} for valid flag values. + */ + traceFlags: number; + /** + * Tracing-system-specific info to propagate. + * + * The tracestate field value is a `list` as defined below. The `list` is a + * series of `list-members` separated by commas `,`, and a list-member is a + * key/value pair separated by an equals sign `=`. Spaces and horizontal tabs + * surrounding `list-members` are ignored. There can be a maximum of 32 + * `list-members` in a `list`. + * More Info: https://www.w3.org/TR/trace-context/#tracestate-field + * + * Examples: + * Single tracing system (generic format): + * tracestate: rojo=00f067aa0ba902b7 + * Multiple tracing systems (with different formatting): + * tracestate: rojo=00f067aa0ba902b7,congo=t61rcWkgMzE + */ + traceState?: TraceState; +} +//# sourceMappingURL=span_context.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/span_context.js b/node_modules/@opentelemetry/api/build/esnext/trace/span_context.js new file mode 100644 index 0000000..1bb88b0 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/span_context.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=span_context.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/span_context.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/span_context.js.map new file mode 100644 index 0000000..dbf0bfe --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/span_context.js.map @@ -0,0 +1 @@ +{"version":3,"file":"span_context.js","sourceRoot":"","sources":["../../../src/trace/span_context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TraceState } from './trace_state';\n\n/**\n * A SpanContext represents the portion of a {@link Span} which must be\n * serialized and propagated along side of a {@link Baggage}.\n */\nexport interface SpanContext {\n /**\n * The ID of the trace that this span belongs to. It is worldwide unique\n * with practically sufficient probability by being made as 16 randomly\n * generated bytes, encoded as a 32 lowercase hex characters corresponding to\n * 128 bits.\n */\n traceId: string;\n /**\n * The ID of the Span. It is globally unique with practically sufficient\n * probability by being made as 8 randomly generated bytes, encoded as a 16\n * lowercase hex characters corresponding to 64 bits.\n */\n spanId: string;\n /**\n * Only true if the SpanContext was propagated from a remote parent.\n */\n isRemote?: boolean;\n /**\n * Trace flags to propagate.\n *\n * It is represented as 1 byte (bitmap). Bit to represent whether trace is\n * sampled or not. When set, the least significant bit documents that the\n * caller may have recorded trace data. A caller who does not record trace\n * data out-of-band leaves this flag unset.\n *\n * see {@link TraceFlags} for valid flag values.\n */\n traceFlags: number;\n /**\n * Tracing-system-specific info to propagate.\n *\n * The tracestate field value is a `list` as defined below. The `list` is a\n * series of `list-members` separated by commas `,`, and a list-member is a\n * key/value pair separated by an equals sign `=`. Spaces and horizontal tabs\n * surrounding `list-members` are ignored. There can be a maximum of 32\n * `list-members` in a `list`.\n * More Info: https://www.w3.org/TR/trace-context/#tracestate-field\n *\n * Examples:\n * Single tracing system (generic format):\n * tracestate: rojo=00f067aa0ba902b7\n * Multiple tracing systems (with different formatting):\n * tracestate: rojo=00f067aa0ba902b7,congo=t61rcWkgMzE\n */\n traceState?: TraceState;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/span_kind.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/span_kind.d.ts new file mode 100644 index 0000000..a89846f --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/span_kind.d.ts @@ -0,0 +1,27 @@ +export declare enum SpanKind { + /** Default value. Indicates that the span is used internally. */ + INTERNAL = 0, + /** + * Indicates that the span covers server-side handling of an RPC or other + * remote request. + */ + SERVER = 1, + /** + * Indicates that the span covers the client-side wrapper around an RPC or + * other remote request. + */ + CLIENT = 2, + /** + * Indicates that the span describes producer sending a message to a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + PRODUCER = 3, + /** + * Indicates that the span describes consumer receiving a message from a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + CONSUMER = 4 +} +//# sourceMappingURL=span_kind.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/span_kind.js b/node_modules/@opentelemetry/api/build/esnext/trace/span_kind.js new file mode 100644 index 0000000..1119df9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/span_kind.js @@ -0,0 +1,43 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export var SpanKind; +(function (SpanKind) { + /** Default value. Indicates that the span is used internally. */ + SpanKind[SpanKind["INTERNAL"] = 0] = "INTERNAL"; + /** + * Indicates that the span covers server-side handling of an RPC or other + * remote request. + */ + SpanKind[SpanKind["SERVER"] = 1] = "SERVER"; + /** + * Indicates that the span covers the client-side wrapper around an RPC or + * other remote request. + */ + SpanKind[SpanKind["CLIENT"] = 2] = "CLIENT"; + /** + * Indicates that the span describes producer sending a message to a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + SpanKind[SpanKind["PRODUCER"] = 3] = "PRODUCER"; + /** + * Indicates that the span describes consumer receiving a message from a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + SpanKind[SpanKind["CONSUMER"] = 4] = "CONSUMER"; +})(SpanKind || (SpanKind = {})); +//# sourceMappingURL=span_kind.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/span_kind.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/span_kind.js.map new file mode 100644 index 0000000..deb6be7 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/span_kind.js.map @@ -0,0 +1 @@ +{"version":3,"file":"span_kind.js","sourceRoot":"","sources":["../../../src/trace/span_kind.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAN,IAAY,QA6BX;AA7BD,WAAY,QAAQ;IAClB,iEAAiE;IACjE,+CAAY,CAAA;IAEZ;;;OAGG;IACH,2CAAU,CAAA;IAEV;;;OAGG;IACH,2CAAU,CAAA;IAEV;;;;OAIG;IACH,+CAAY,CAAA;IAEZ;;;;OAIG;IACH,+CAAY,CAAA;AACd,CAAC,EA7BW,QAAQ,KAAR,QAAQ,QA6BnB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport enum SpanKind {\n /** Default value. Indicates that the span is used internally. */\n INTERNAL = 0,\n\n /**\n * Indicates that the span covers server-side handling of an RPC or other\n * remote request.\n */\n SERVER = 1,\n\n /**\n * Indicates that the span covers the client-side wrapper around an RPC or\n * other remote request.\n */\n CLIENT = 2,\n\n /**\n * Indicates that the span describes producer sending a message to a\n * broker. Unlike client and server, there is no direct critical path latency\n * relationship between producer and consumer spans.\n */\n PRODUCER = 3,\n\n /**\n * Indicates that the span describes consumer receiving a message from a\n * broker. Unlike client and server, there is no direct critical path latency\n * relationship between producer and consumer spans.\n */\n CONSUMER = 4,\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/spancontext-utils.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/spancontext-utils.d.ts new file mode 100644 index 0000000..f191111 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/spancontext-utils.d.ts @@ -0,0 +1,17 @@ +import { Span } from './span'; +import { SpanContext } from './span_context'; +export declare function isValidTraceId(traceId: string): boolean; +export declare function isValidSpanId(spanId: string): boolean; +/** + * Returns true if this {@link SpanContext} is valid. + * @return true if this {@link SpanContext} is valid. + */ +export declare function isSpanContextValid(spanContext: SpanContext): boolean; +/** + * Wrap the given {@link SpanContext} in a new non-recording {@link Span} + * + * @param spanContext span context to be wrapped + * @returns a new non-recording {@link Span} with the provided context + */ +export declare function wrapSpanContext(spanContext: SpanContext): Span; +//# sourceMappingURL=spancontext-utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/spancontext-utils.js b/node_modules/@opentelemetry/api/build/esnext/trace/spancontext-utils.js new file mode 100644 index 0000000..a51187a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/spancontext-utils.js @@ -0,0 +1,42 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { INVALID_SPANID, INVALID_TRACEID } from './invalid-span-constants'; +import { NonRecordingSpan } from './NonRecordingSpan'; +const VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; +const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; +export function isValidTraceId(traceId) { + return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID; +} +export function isValidSpanId(spanId) { + return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID; +} +/** + * Returns true if this {@link SpanContext} is valid. + * @return true if this {@link SpanContext} is valid. + */ +export function isSpanContextValid(spanContext) { + return (isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)); +} +/** + * Wrap the given {@link SpanContext} in a new non-recording {@link Span} + * + * @param spanContext span context to be wrapped + * @returns a new non-recording {@link Span} with the provided context + */ +export function wrapSpanContext(spanContext) { + return new NonRecordingSpan(spanContext); +} +//# sourceMappingURL=spancontext-utils.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/spancontext-utils.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/spancontext-utils.js.map new file mode 100644 index 0000000..9730fc7 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/spancontext-utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"spancontext-utils.js","sourceRoot":"","sources":["../../../src/trace/spancontext-utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAItD,MAAM,mBAAmB,GAAG,mBAAmB,CAAC;AAChD,MAAM,kBAAkB,GAAG,iBAAiB,CAAC;AAE7C,MAAM,UAAU,cAAc,CAAC,OAAe;IAC5C,OAAO,mBAAmB,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,OAAO,KAAK,eAAe,CAAC;AAC1E,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,MAAc;IAC1C,OAAO,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,MAAM,KAAK,cAAc,CAAC;AACtE,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAAC,WAAwB;IACzD,OAAO,CACL,cAAc,CAAC,WAAW,CAAC,OAAO,CAAC,IAAI,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,CACzE,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,eAAe,CAAC,WAAwB;IACtD,OAAO,IAAI,gBAAgB,CAAC,WAAW,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { INVALID_SPANID, INVALID_TRACEID } from './invalid-span-constants';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\n\nconst VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;\nconst VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;\n\nexport function isValidTraceId(traceId: string): boolean {\n return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID;\n}\n\nexport function isValidSpanId(spanId: string): boolean {\n return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID;\n}\n\n/**\n * Returns true if this {@link SpanContext} is valid.\n * @return true if this {@link SpanContext} is valid.\n */\nexport function isSpanContextValid(spanContext: SpanContext): boolean {\n return (\n isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)\n );\n}\n\n/**\n * Wrap the given {@link SpanContext} in a new non-recording {@link Span}\n *\n * @param spanContext span context to be wrapped\n * @returns a new non-recording {@link Span} with the provided context\n */\nexport function wrapSpanContext(spanContext: SpanContext): Span {\n return new NonRecordingSpan(spanContext);\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/status.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/status.d.ts new file mode 100644 index 0000000..ab19a68 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/status.d.ts @@ -0,0 +1,25 @@ +export interface SpanStatus { + /** The status code of this message. */ + code: SpanStatusCode; + /** A developer-facing error message. */ + message?: string; +} +/** + * An enumeration of status codes. + */ +export declare enum SpanStatusCode { + /** + * The default status. + */ + UNSET = 0, + /** + * The operation has been validated by an Application developer or + * Operator to have completed successfully. + */ + OK = 1, + /** + * The operation contains an error. + */ + ERROR = 2 +} +//# sourceMappingURL=status.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/status.js b/node_modules/@opentelemetry/api/build/esnext/trace/status.js new file mode 100644 index 0000000..5ee55e4 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/status.js @@ -0,0 +1,20 @@ +/** + * An enumeration of status codes. + */ +export var SpanStatusCode; +(function (SpanStatusCode) { + /** + * The default status. + */ + SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET"; + /** + * The operation has been validated by an Application developer or + * Operator to have completed successfully. + */ + SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK"; + /** + * The operation contains an error. + */ + SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR"; +})(SpanStatusCode || (SpanStatusCode = {})); +//# sourceMappingURL=status.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/status.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/status.js.map new file mode 100644 index 0000000..af7e7d7 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/status.js.map @@ -0,0 +1 @@ +{"version":3,"file":"status.js","sourceRoot":"","sources":["../../../src/trace/status.ts"],"names":[],"mappings":"AAsBA;;GAEG;AACH,MAAM,CAAN,IAAY,cAcX;AAdD,WAAY,cAAc;IACxB;;OAEG;IACH,qDAAS,CAAA;IACT;;;OAGG;IACH,+CAAM,CAAA;IACN;;OAEG;IACH,qDAAS,CAAA;AACX,CAAC,EAdW,cAAc,KAAd,cAAc,QAczB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport interface SpanStatus {\n /** The status code of this message. */\n code: SpanStatusCode;\n /** A developer-facing error message. */\n message?: string;\n}\n\n/**\n * An enumeration of status codes.\n */\nexport enum SpanStatusCode {\n /**\n * The default status.\n */\n UNSET = 0,\n /**\n * The operation has been validated by an Application developer or\n * Operator to have completed successfully.\n */\n OK = 1,\n /**\n * The operation contains an error.\n */\n ERROR = 2,\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/trace_flags.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/trace_flags.d.ts new file mode 100644 index 0000000..11288ba --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/trace_flags.d.ts @@ -0,0 +1,7 @@ +export declare enum TraceFlags { + /** Represents no flag set. */ + NONE = 0, + /** Bit to represent whether trace is sampled in trace flags. */ + SAMPLED = 1 +} +//# sourceMappingURL=trace_flags.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/trace_flags.js b/node_modules/@opentelemetry/api/build/esnext/trace/trace_flags.js new file mode 100644 index 0000000..8a7b000 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/trace_flags.js @@ -0,0 +1,23 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export var TraceFlags; +(function (TraceFlags) { + /** Represents no flag set. */ + TraceFlags[TraceFlags["NONE"] = 0] = "NONE"; + /** Bit to represent whether trace is sampled in trace flags. */ + TraceFlags[TraceFlags["SAMPLED"] = 1] = "SAMPLED"; +})(TraceFlags || (TraceFlags = {})); +//# sourceMappingURL=trace_flags.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/trace_flags.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/trace_flags.js.map new file mode 100644 index 0000000..2ea8680 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/trace_flags.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trace_flags.js","sourceRoot":"","sources":["../../../src/trace/trace_flags.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAN,IAAY,UAKX;AALD,WAAY,UAAU;IACpB,8BAA8B;IAC9B,2CAAU,CAAA;IACV,gEAAgE;IAChE,iDAAkB,CAAA;AACpB,CAAC,EALW,UAAU,KAAV,UAAU,QAKrB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport enum TraceFlags {\n /** Represents no flag set. */\n NONE = 0x0,\n /** Bit to represent whether trace is sampled in trace flags. */\n SAMPLED = 0x1 << 0,\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/trace_state.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/trace_state.d.ts new file mode 100644 index 0000000..f275b8b --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/trace_state.d.ts @@ -0,0 +1,38 @@ +export interface TraceState { + /** + * Create a new TraceState which inherits from this TraceState and has the + * given key set. + * The new entry will always be added in the front of the list of states. + * + * @param key key of the TraceState entry. + * @param value value of the TraceState entry. + */ + set(key: string, value: string): TraceState; + /** + * Return a new TraceState which inherits from this TraceState but does not + * contain the given key. + * + * @param key the key for the TraceState entry to be removed. + */ + unset(key: string): TraceState; + /** + * Returns the value to which the specified key is mapped, or `undefined` if + * this map contains no mapping for the key. + * + * @param key with which the specified value is to be associated. + * @returns the value to which the specified key is mapped, or `undefined` if + * this map contains no mapping for the key. + */ + get(key: string): string | undefined; + /** + * Serializes the TraceState to a `list` as defined below. The `list` is a + * series of `list-members` separated by commas `,`, and a list-member is a + * key/value pair separated by an equals sign `=`. Spaces and horizontal tabs + * surrounding `list-members` are ignored. There can be a maximum of 32 + * `list-members` in a `list`. + * + * @returns the serialized string. + */ + serialize(): string; +} +//# sourceMappingURL=trace_state.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/trace_state.js b/node_modules/@opentelemetry/api/build/esnext/trace/trace_state.js new file mode 100644 index 0000000..a6c368f --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/trace_state.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=trace_state.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/trace_state.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/trace_state.js.map new file mode 100644 index 0000000..64a3d7a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/trace_state.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trace_state.js","sourceRoot":"","sources":["../../../src/trace/trace_state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface TraceState {\n /**\n * Create a new TraceState which inherits from this TraceState and has the\n * given key set.\n * The new entry will always be added in the front of the list of states.\n *\n * @param key key of the TraceState entry.\n * @param value value of the TraceState entry.\n */\n set(key: string, value: string): TraceState;\n\n /**\n * Return a new TraceState which inherits from this TraceState but does not\n * contain the given key.\n *\n * @param key the key for the TraceState entry to be removed.\n */\n unset(key: string): TraceState;\n\n /**\n * Returns the value to which the specified key is mapped, or `undefined` if\n * this map contains no mapping for the key.\n *\n * @param key with which the specified value is to be associated.\n * @returns the value to which the specified key is mapped, or `undefined` if\n * this map contains no mapping for the key.\n */\n get(key: string): string | undefined;\n\n // TODO: Consider to add support for merging an object as well by also\n // accepting a single internalTraceState argument similar to the constructor.\n\n /**\n * Serializes the TraceState to a `list` as defined below. The `list` is a\n * series of `list-members` separated by commas `,`, and a list-member is a\n * key/value pair separated by an equals sign `=`. Spaces and horizontal tabs\n * surrounding `list-members` are ignored. There can be a maximum of 32\n * `list-members` in a `list`.\n *\n * @returns the serialized string.\n */\n serialize(): string;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/tracer.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/tracer.d.ts new file mode 100644 index 0000000..2509089 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/tracer.d.ts @@ -0,0 +1,71 @@ +import { Context } from '../context/types'; +import { Span } from './span'; +import { SpanOptions } from './SpanOptions'; +/** + * Tracer provides an interface for creating {@link Span}s. + */ +export interface Tracer { + /** + * Starts a new {@link Span}. Start the span without setting it on context. + * + * This method do NOT modify the current Context. + * + * @param name The name of the span + * @param [options] SpanOptions used for span creation + * @param [context] Context to use to extract parent + * @returns Span The newly created span + * @example + * const span = tracer.startSpan('op'); + * span.setAttribute('key', 'value'); + * span.end(); + */ + startSpan(name: string, options?: SpanOptions, context?: Context): Span; + /** + * Starts a new {@link Span} and calls the given function passing it the + * created span as first argument. + * Additionally the new span gets set in context and this context is activated + * for the duration of the function call. + * + * @param name The name of the span + * @param [options] SpanOptions used for span creation + * @param [context] Context to use to extract parent + * @param fn function called in the context of the span and receives the newly created span as an argument + * @returns return value of fn + * @example + * const something = tracer.startActiveSpan('op', span => { + * try { + * do some work + * span.setStatus({code: SpanStatusCode.OK}); + * return something; + * } catch (err) { + * span.setStatus({ + * code: SpanStatusCode.ERROR, + * message: err.message, + * }); + * throw err; + * } finally { + * span.end(); + * } + * }); + * + * @example + * const span = tracer.startActiveSpan('op', span => { + * try { + * do some work + * return span; + * } catch (err) { + * span.setStatus({ + * code: SpanStatusCode.ERROR, + * message: err.message, + * }); + * throw err; + * } + * }); + * do some more work + * span.end(); + */ + startActiveSpan unknown>(name: string, fn: F): ReturnType; + startActiveSpan unknown>(name: string, options: SpanOptions, fn: F): ReturnType; + startActiveSpan unknown>(name: string, options: SpanOptions, context: Context, fn: F): ReturnType; +} +//# sourceMappingURL=tracer.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/tracer.js b/node_modules/@opentelemetry/api/build/esnext/trace/tracer.js new file mode 100644 index 0000000..ad066dc --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/tracer.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=tracer.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/tracer.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/tracer.js.map new file mode 100644 index 0000000..77f6ae9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/tracer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tracer.js","sourceRoot":"","sources":["../../../src/trace/tracer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport { Span } from './span';\nimport { SpanOptions } from './SpanOptions';\n\n/**\n * Tracer provides an interface for creating {@link Span}s.\n */\nexport interface Tracer {\n /**\n * Starts a new {@link Span}. Start the span without setting it on context.\n *\n * This method do NOT modify the current Context.\n *\n * @param name The name of the span\n * @param [options] SpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @returns Span The newly created span\n * @example\n * const span = tracer.startSpan('op');\n * span.setAttribute('key', 'value');\n * span.end();\n */\n startSpan(name: string, options?: SpanOptions, context?: Context): Span;\n\n /**\n * Starts a new {@link Span} and calls the given function passing it the\n * created span as first argument.\n * Additionally the new span gets set in context and this context is activated\n * for the duration of the function call.\n *\n * @param name The name of the span\n * @param [options] SpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns return value of fn\n * @example\n * const something = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * span.setStatus({code: SpanStatusCode.OK});\n * return something;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * } finally {\n * span.end();\n * }\n * });\n *\n * @example\n * const span = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * return span;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * }\n * });\n * do some more work\n * span.end();\n */\n startActiveSpan unknown>(\n name: string,\n fn: F\n ): ReturnType;\n startActiveSpan unknown>(\n name: string,\n options: SpanOptions,\n fn: F\n ): ReturnType;\n startActiveSpan unknown>(\n name: string,\n options: SpanOptions,\n context: Context,\n fn: F\n ): ReturnType;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/tracer_options.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/tracer_options.d.ts new file mode 100644 index 0000000..f3bbccf --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/tracer_options.d.ts @@ -0,0 +1,10 @@ +/** + * An interface describes additional metadata of a tracer. + */ +export interface TracerOptions { + /** + * The schemaUrl of the tracer or instrumentation library + */ + schemaUrl?: string; +} +//# sourceMappingURL=tracer_options.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/tracer_options.js b/node_modules/@opentelemetry/api/build/esnext/trace/tracer_options.js new file mode 100644 index 0000000..470a3a7 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/tracer_options.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=tracer_options.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/tracer_options.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/tracer_options.js.map new file mode 100644 index 0000000..70365af --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/tracer_options.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tracer_options.js","sourceRoot":"","sources":["../../../src/trace/tracer_options.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An interface describes additional metadata of a tracer.\n */\nexport interface TracerOptions {\n /**\n * The schemaUrl of the tracer or instrumentation library\n */\n schemaUrl?: string;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/tracer_provider.d.ts b/node_modules/@opentelemetry/api/build/esnext/trace/tracer_provider.d.ts new file mode 100644 index 0000000..9b2f7a9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/tracer_provider.d.ts @@ -0,0 +1,21 @@ +import { Tracer } from './tracer'; +import { TracerOptions } from './tracer_options'; +/** + * A registry for creating named {@link Tracer}s. + */ +export interface TracerProvider { + /** + * Returns a Tracer, creating one if one with the given name and version is + * not already created. + * + * This function may return different Tracer types (e.g. + * {@link NoopTracerProvider} vs. a functional tracer). + * + * @param name The name of the tracer or instrumentation library. + * @param version The version of the tracer or instrumentation library. + * @param options The options of the tracer or instrumentation library. + * @returns Tracer A Tracer with the given name and version + */ + getTracer(name: string, version?: string, options?: TracerOptions): Tracer; +} +//# sourceMappingURL=tracer_provider.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/tracer_provider.js b/node_modules/@opentelemetry/api/build/esnext/trace/tracer_provider.js new file mode 100644 index 0000000..adf432a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/tracer_provider.js @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; +//# sourceMappingURL=tracer_provider.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/trace/tracer_provider.js.map b/node_modules/@opentelemetry/api/build/esnext/trace/tracer_provider.js.map new file mode 100644 index 0000000..bfc1cbd --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/trace/tracer_provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tracer_provider.js","sourceRoot":"","sources":["../../../src/trace/tracer_provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Tracer } from './tracer';\nimport { TracerOptions } from './tracer_options';\n\n/**\n * A registry for creating named {@link Tracer}s.\n */\nexport interface TracerProvider {\n /**\n * Returns a Tracer, creating one if one with the given name and version is\n * not already created.\n *\n * This function may return different Tracer types (e.g.\n * {@link NoopTracerProvider} vs. a functional tracer).\n *\n * @param name The name of the tracer or instrumentation library.\n * @param version The version of the tracer or instrumentation library.\n * @param options The options of the tracer or instrumentation library.\n * @returns Tracer A Tracer with the given name and version\n */\n getTracer(name: string, version?: string, options?: TracerOptions): Tracer;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/version.d.ts b/node_modules/@opentelemetry/api/build/esnext/version.d.ts new file mode 100644 index 0000000..40f0365 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/version.d.ts @@ -0,0 +1,2 @@ +export declare const VERSION = "1.9.0"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/version.js b/node_modules/@opentelemetry/api/build/esnext/version.js new file mode 100644 index 0000000..2a86ecf --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/version.js @@ -0,0 +1,18 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// this is autogenerated file, see scripts/version-update.js +export const VERSION = '1.9.0'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/esnext/version.js.map b/node_modules/@opentelemetry/api/build/esnext/version.js.map new file mode 100644 index 0000000..c5ea902 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/esnext/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,4DAA4D;AAC5D,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.9.0';\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/api/context.d.ts b/node_modules/@opentelemetry/api/build/src/api/context.d.ts new file mode 100644 index 0000000..61caee8 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/api/context.d.ts @@ -0,0 +1,41 @@ +import { Context, ContextManager } from '../context/types'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Context API + */ +export declare class ContextAPI { + private static _instance?; + /** Empty private constructor prevents end users from constructing a new instance of the API */ + private constructor(); + /** Get the singleton instance of the Context API */ + static getInstance(): ContextAPI; + /** + * Set the current context manager. + * + * @returns true if the context manager was successfully registered, else false + */ + setGlobalContextManager(contextManager: ContextManager): boolean; + /** + * Get the currently active context + */ + active(): Context; + /** + * Execute a function with an active context + * + * @param context context to be active during function execution + * @param fn function to execute in a context + * @param thisArg optional receiver to be used for calling fn + * @param args optional arguments forwarded to fn + */ + with ReturnType>(context: Context, fn: F, thisArg?: ThisParameterType, ...args: A): ReturnType; + /** + * Bind a context to a target function or event emitter + * + * @param context context to bind to the event emitter or function. Defaults to the currently active context + * @param target function or event emitter to bind + */ + bind(context: Context, target: T): T; + private _getContextManager; + /** Disable and remove the global context manager */ + disable(): void; +} +//# sourceMappingURL=context.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/api/context.js b/node_modules/@opentelemetry/api/build/src/api/context.js new file mode 100644 index 0000000..8af551f --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/api/context.js @@ -0,0 +1,81 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ContextAPI = void 0; +const NoopContextManager_1 = require("../context/NoopContextManager"); +const global_utils_1 = require("../internal/global-utils"); +const diag_1 = require("./diag"); +const API_NAME = 'context'; +const NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); +/** + * Singleton object which represents the entry point to the OpenTelemetry Context API + */ +class ContextAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { } + /** Get the singleton instance of the Context API */ + static getInstance() { + if (!this._instance) { + this._instance = new ContextAPI(); + } + return this._instance; + } + /** + * Set the current context manager. + * + * @returns true if the context manager was successfully registered, else false + */ + setGlobalContextManager(contextManager) { + return (0, global_utils_1.registerGlobal)(API_NAME, contextManager, diag_1.DiagAPI.instance()); + } + /** + * Get the currently active context + */ + active() { + return this._getContextManager().active(); + } + /** + * Execute a function with an active context + * + * @param context context to be active during function execution + * @param fn function to execute in a context + * @param thisArg optional receiver to be used for calling fn + * @param args optional arguments forwarded to fn + */ + with(context, fn, thisArg, ...args) { + return this._getContextManager().with(context, fn, thisArg, ...args); + } + /** + * Bind a context to a target function or event emitter + * + * @param context context to bind to the event emitter or function. Defaults to the currently active context + * @param target function or event emitter to bind + */ + bind(context, target) { + return this._getContextManager().bind(context, target); + } + _getContextManager() { + return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_CONTEXT_MANAGER; + } + /** Disable and remove the global context manager */ + disable() { + this._getContextManager().disable(); + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } +} +exports.ContextAPI = ContextAPI; +//# sourceMappingURL=context.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/api/context.js.map b/node_modules/@opentelemetry/api/build/src/api/context.js.map new file mode 100644 index 0000000..78c56c1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/api/context.js.map @@ -0,0 +1 @@ +{"version":3,"file":"context.js","sourceRoot":"","sources":["../../../src/api/context.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,sEAAmE;AAEnE,2DAIkC;AAClC,iCAAiC;AAEjC,MAAM,QAAQ,GAAG,SAAS,CAAC;AAC3B,MAAM,oBAAoB,GAAG,IAAI,uCAAkB,EAAE,CAAC;AAEtD;;GAEG;AACH,MAAa,UAAU;IAGrB,+FAA+F;IAC/F,gBAAuB,CAAC;IAExB,oDAAoD;IAC7C,MAAM,CAAC,WAAW;QACvB,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;YACnB,IAAI,CAAC,SAAS,GAAG,IAAI,UAAU,EAAE,CAAC;SACnC;QAED,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAED;;;;OAIG;IACI,uBAAuB,CAAC,cAA8B;QAC3D,OAAO,IAAA,6BAAc,EAAC,QAAQ,EAAE,cAAc,EAAE,cAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;IACtE,CAAC;IAED;;OAEG;IACI,MAAM;QACX,OAAO,IAAI,CAAC,kBAAkB,EAAE,CAAC,MAAM,EAAE,CAAC;IAC5C,CAAC;IAED;;;;;;;OAOG;IACI,IAAI,CACT,OAAgB,EAChB,EAAK,EACL,OAA8B,EAC9B,GAAG,IAAO;QAEV,OAAO,IAAI,CAAC,kBAAkB,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC,CAAC;IACvE,CAAC;IAED;;;;;OAKG;IACI,IAAI,CAAI,OAAgB,EAAE,MAAS;QACxC,OAAO,IAAI,CAAC,kBAAkB,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IACzD,CAAC;IAEO,kBAAkB;QACxB,OAAO,IAAA,wBAAS,EAAC,QAAQ,CAAC,IAAI,oBAAoB,CAAC;IACrD,CAAC;IAED,oDAAoD;IAC7C,OAAO;QACZ,IAAI,CAAC,kBAAkB,EAAE,CAAC,OAAO,EAAE,CAAC;QACpC,IAAA,+BAAgB,EAAC,QAAQ,EAAE,cAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;IACjD,CAAC;CACF;AAnED,gCAmEC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NoopContextManager } from '../context/NoopContextManager';\nimport { Context, ContextManager } from '../context/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'context';\nconst NOOP_CONTEXT_MANAGER = new NoopContextManager();\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Context API\n */\nexport class ContextAPI {\n private static _instance?: ContextAPI;\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Context API */\n public static getInstance(): ContextAPI {\n if (!this._instance) {\n this._instance = new ContextAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current context manager.\n *\n * @returns true if the context manager was successfully registered, else false\n */\n public setGlobalContextManager(contextManager: ContextManager): boolean {\n return registerGlobal(API_NAME, contextManager, DiagAPI.instance());\n }\n\n /**\n * Get the currently active context\n */\n public active(): Context {\n return this._getContextManager().active();\n }\n\n /**\n * Execute a function with an active context\n *\n * @param context context to be active during function execution\n * @param fn function to execute in a context\n * @param thisArg optional receiver to be used for calling fn\n * @param args optional arguments forwarded to fn\n */\n public with ReturnType>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType,\n ...args: A\n ): ReturnType {\n return this._getContextManager().with(context, fn, thisArg, ...args);\n }\n\n /**\n * Bind a context to a target function or event emitter\n *\n * @param context context to bind to the event emitter or function. Defaults to the currently active context\n * @param target function or event emitter to bind\n */\n public bind(context: Context, target: T): T {\n return this._getContextManager().bind(context, target);\n }\n\n private _getContextManager(): ContextManager {\n return getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER;\n }\n\n /** Disable and remove the global context manager */\n public disable() {\n this._getContextManager().disable();\n unregisterGlobal(API_NAME, DiagAPI.instance());\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/api/diag.d.ts b/node_modules/@opentelemetry/api/build/src/api/diag.d.ts new file mode 100644 index 0000000..131db17 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/api/diag.d.ts @@ -0,0 +1,30 @@ +import { ComponentLoggerOptions, DiagLogFunction, DiagLogger, DiagLoggerApi } from '../diag/types'; +/** + * Singleton object which represents the entry point to the OpenTelemetry internal + * diagnostic API + */ +export declare class DiagAPI implements DiagLogger, DiagLoggerApi { + private static _instance?; + /** Get the singleton instance of the DiagAPI API */ + static instance(): DiagAPI; + /** + * Private internal constructor + * @private + */ + private constructor(); + setLogger: DiagLoggerApi['setLogger']; + /** + * + */ + createComponentLogger: (options: ComponentLoggerOptions) => DiagLogger; + verbose: DiagLogFunction; + debug: DiagLogFunction; + info: DiagLogFunction; + warn: DiagLogFunction; + error: DiagLogFunction; + /** + * Unregister the global logger and return to Noop + */ + disable: () => void; +} +//# sourceMappingURL=diag.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/api/diag.js b/node_modules/@opentelemetry/api/build/src/api/diag.js new file mode 100644 index 0000000..9456923 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/api/diag.js @@ -0,0 +1,93 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DiagAPI = void 0; +const ComponentLogger_1 = require("../diag/ComponentLogger"); +const logLevelLogger_1 = require("../diag/internal/logLevelLogger"); +const types_1 = require("../diag/types"); +const global_utils_1 = require("../internal/global-utils"); +const API_NAME = 'diag'; +/** + * Singleton object which represents the entry point to the OpenTelemetry internal + * diagnostic API + */ +class DiagAPI { + /** + * Private internal constructor + * @private + */ + constructor() { + function _logProxy(funcName) { + return function (...args) { + const logger = (0, global_utils_1.getGlobal)('diag'); + // shortcut if logger not set + if (!logger) + return; + return logger[funcName](...args); + }; + } + // Using self local variable for minification purposes as 'this' cannot be minified + const self = this; + // DiagAPI specific functions + const setLogger = (logger, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => { + var _a, _b, _c; + if (logger === self) { + // There isn't much we can do here. + // Logging to the console might break the user application. + // Try to log to self. If a logger was previously registered it will receive the log. + const err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); + self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message); + return false; + } + if (typeof optionsOrLogLevel === 'number') { + optionsOrLogLevel = { + logLevel: optionsOrLogLevel, + }; + } + const oldLogger = (0, global_utils_1.getGlobal)('diag'); + const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : types_1.DiagLogLevel.INFO, logger); + // There already is an logger registered. We'll let it know before overwriting it. + if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { + const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ''; + oldLogger.warn(`Current logger will be overwritten from ${stack}`); + newLogger.warn(`Current logger will overwrite one already registered from ${stack}`); + } + return (0, global_utils_1.registerGlobal)('diag', newLogger, self, true); + }; + self.setLogger = setLogger; + self.disable = () => { + (0, global_utils_1.unregisterGlobal)(API_NAME, self); + }; + self.createComponentLogger = (options) => { + return new ComponentLogger_1.DiagComponentLogger(options); + }; + self.verbose = _logProxy('verbose'); + self.debug = _logProxy('debug'); + self.info = _logProxy('info'); + self.warn = _logProxy('warn'); + self.error = _logProxy('error'); + } + /** Get the singleton instance of the DiagAPI API */ + static instance() { + if (!this._instance) { + this._instance = new DiagAPI(); + } + return this._instance; + } +} +exports.DiagAPI = DiagAPI; +//# sourceMappingURL=diag.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/api/diag.js.map b/node_modules/@opentelemetry/api/build/src/api/diag.js.map new file mode 100644 index 0000000..868e19c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/api/diag.js.map @@ -0,0 +1 @@ +{"version":3,"file":"diag.js","sourceRoot":"","sources":["../../../src/api/diag.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,6DAA8D;AAC9D,oEAA2E;AAC3E,yCAMuB;AACvB,2DAIkC;AAElC,MAAM,QAAQ,GAAG,MAAM,CAAC;AAExB;;;GAGG;AACH,MAAa,OAAO;IAYlB;;;OAGG;IACH;QACE,SAAS,SAAS,CAAC,QAA0B;YAC3C,OAAO,UAAU,GAAG,IAAI;gBACtB,MAAM,MAAM,GAAG,IAAA,wBAAS,EAAC,MAAM,CAAC,CAAC;gBACjC,6BAA6B;gBAC7B,IAAI,CAAC,MAAM;oBAAE,OAAO;gBACpB,OAAO,MAAM,C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,SAAS,GAAG,SAAS,CAAC;QAE3B,IAAI,CAAC,OAAO,GAAG,GAAG,EAAE;YAClB,IAAA,+BAAgB,EAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QACnC,CAAC,CAAC;QAEF,IAAI,CAAC,qBAAqB,GAAG,CAAC,OAA+B,EAAE,EAAE;YAC/D,OAAO,IAAI,qCAAmB,CAAC,OAAO,CAAC,CAAC;QAC1C,CAAC,CAAC;QAEF,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC,SAAS,CAAC,CAAC;QACpC,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;QAChC,IAAI,CAAC,IAAI,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;QAC9B,IAAI,CAAC,IAAI,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;QAC9B,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;IAClC,CAAC;IAjFD,oDAAoD;IAC7C,MAAM,CAAC,QAAQ;QACpB,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;YACnB,IAAI,CAAC,SAAS,GAAG,IAAI,OAAO,EAAE,CAAC;SAChC;QAED,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;CA+FF;AAzGD,0BAyGC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagComponentLogger } from '../diag/ComponentLogger';\nimport { createLogLevelDiagLogger } from '../diag/internal/logLevelLogger';\nimport {\n ComponentLoggerOptions,\n DiagLogFunction,\n DiagLogger,\n DiagLoggerApi,\n DiagLogLevel,\n} from '../diag/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\n\nconst API_NAME = 'diag';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry internal\n * diagnostic API\n */\nexport class DiagAPI implements DiagLogger, DiagLoggerApi {\n private static _instance?: DiagAPI;\n\n /** Get the singleton instance of the DiagAPI API */\n public static instance(): DiagAPI {\n if (!this._instance) {\n this._instance = new DiagAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Private internal constructor\n * @private\n */\n private constructor() {\n function _logProxy(funcName: keyof DiagLogger): DiagLogFunction {\n return function (...args) {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) return;\n return logger[funcName](...args);\n };\n }\n\n // Using self local variable for minification purposes as 'this' cannot be minified\n const self = this;\n\n // DiagAPI specific functions\n\n const setLogger: DiagLoggerApi['setLogger'] = (\n logger,\n optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }\n ) => {\n if (logger === self) {\n // There isn't much we can do here.\n // Logging to the console might break the user application.\n // Try to log to self. If a logger was previously registered it will receive the log.\n const err = new Error(\n 'Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'\n );\n self.error(err.stack ?? err.message);\n return false;\n }\n\n if (typeof optionsOrLogLevel === 'number') {\n optionsOrLogLevel = {\n logLevel: optionsOrLogLevel,\n };\n }\n\n const oldLogger = getGlobal('diag');\n const newLogger = createLogLevelDiagLogger(\n optionsOrLogLevel.logLevel ?? DiagLogLevel.INFO,\n logger\n );\n // There already is an logger registered. We'll let it know before overwriting it.\n if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {\n const stack = new Error().stack ?? '';\n oldLogger.warn(`Current logger will be overwritten from ${stack}`);\n newLogger.warn(\n `Current logger will overwrite one already registered from ${stack}`\n );\n }\n\n return registerGlobal('diag', newLogger, self, true);\n };\n\n self.setLogger = setLogger;\n\n self.disable = () => {\n unregisterGlobal(API_NAME, self);\n };\n\n self.createComponentLogger = (options: ComponentLoggerOptions) => {\n return new DiagComponentLogger(options);\n };\n\n self.verbose = _logProxy('verbose');\n self.debug = _logProxy('debug');\n self.info = _logProxy('info');\n self.warn = _logProxy('warn');\n self.error = _logProxy('error');\n }\n\n public setLogger!: DiagLoggerApi['setLogger'];\n /**\n *\n */\n public createComponentLogger!: (\n options: ComponentLoggerOptions\n ) => DiagLogger;\n\n // DiagLogger implementation\n public verbose!: DiagLogFunction;\n public debug!: DiagLogFunction;\n public info!: DiagLogFunction;\n public warn!: DiagLogFunction;\n public error!: DiagLogFunction;\n\n /**\n * Unregister the global logger and return to Noop\n */\n public disable!: () => void;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/api/metrics.d.ts b/node_modules/@opentelemetry/api/build/src/api/metrics.d.ts new file mode 100644 index 0000000..5adc145 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/api/metrics.d.ts @@ -0,0 +1,28 @@ +import { Meter, MeterOptions } from '../metrics/Meter'; +import { MeterProvider } from '../metrics/MeterProvider'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Metrics API + */ +export declare class MetricsAPI { + private static _instance?; + /** Empty private constructor prevents end users from constructing a new instance of the API */ + private constructor(); + /** Get the singleton instance of the Metrics API */ + static getInstance(): MetricsAPI; + /** + * Set the current global meter provider. + * Returns true if the meter provider was successfully registered, else false. + */ + setGlobalMeterProvider(provider: MeterProvider): boolean; + /** + * Returns the global meter provider. + */ + getMeterProvider(): MeterProvider; + /** + * Returns a meter from the global meter provider. + */ + getMeter(name: string, version?: string, options?: MeterOptions): Meter; + /** Remove the global meter provider */ + disable(): void; +} +//# sourceMappingURL=metrics.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/api/metrics.js b/node_modules/@opentelemetry/api/build/src/api/metrics.js new file mode 100644 index 0000000..4bbc433 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/api/metrics.js @@ -0,0 +1,61 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MetricsAPI = void 0; +const NoopMeterProvider_1 = require("../metrics/NoopMeterProvider"); +const global_utils_1 = require("../internal/global-utils"); +const diag_1 = require("./diag"); +const API_NAME = 'metrics'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Metrics API + */ +class MetricsAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { } + /** Get the singleton instance of the Metrics API */ + static getInstance() { + if (!this._instance) { + this._instance = new MetricsAPI(); + } + return this._instance; + } + /** + * Set the current global meter provider. + * Returns true if the meter provider was successfully registered, else false. + */ + setGlobalMeterProvider(provider) { + return (0, global_utils_1.registerGlobal)(API_NAME, provider, diag_1.DiagAPI.instance()); + } + /** + * Returns the global meter provider. + */ + getMeterProvider() { + return (0, global_utils_1.getGlobal)(API_NAME) || NoopMeterProvider_1.NOOP_METER_PROVIDER; + } + /** + * Returns a meter from the global meter provider. + */ + getMeter(name, version, options) { + return this.getMeterProvider().getMeter(name, version, options); + } + /** Remove the global meter provider */ + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } +} +exports.MetricsAPI = MetricsAPI; +//# sourceMappingURL=metrics.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/api/metrics.js.map b/node_modules/@opentelemetry/api/build/src/api/metrics.js.map new file mode 100644 index 0000000..3431094 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/api/metrics.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metrics.js","sourceRoot":"","sources":["../../../src/api/metrics.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAIH,oEAAmE;AACnE,2DAIkC;AAClC,iCAAiC;AAEjC,MAAM,QAAQ,GAAG,SAAS,CAAC;AAE3B;;GAEG;AACH,MAAa,UAAU;IAGrB,+FAA+F;IAC/F,gBAAuB,CAAC;IAExB,oDAAoD;IAC7C,MAAM,CAAC,WAAW;QACvB,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;YACnB,IAAI,CAAC,SAAS,GAAG,IAAI,UAAU,EAAE,CAAC;SACnC;QAED,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAED;;;OAGG;IACI,sBAAsB,CAAC,QAAuB;QACnD,OAAO,IAAA,6BAAc,EAAC,QAAQ,EAAE,QAAQ,EAAE,cAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;IAChE,CAAC;IAED;;OAEG;IACI,gBAAgB;QACrB,OAAO,IAAA,wBAAS,EAAC,QAAQ,CAAC,IAAI,uCAAmB,CAAC;IACpD,CAAC;IAED;;OAEG;IACI,QAAQ,CACb,IAAY,EACZ,OAAgB,EAChB,OAAsB;QAEtB,OAAO,IAAI,CAAC,gBAAgB,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;IAED,uCAAuC;IAChC,OAAO;QACZ,IAAA,+BAAgB,EAAC,QAAQ,EAAE,cAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;IACjD,CAAC;CACF;AA7CD,gCA6CC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Meter, MeterOptions } from '../metrics/Meter';\nimport { MeterProvider } from '../metrics/MeterProvider';\nimport { NOOP_METER_PROVIDER } from '../metrics/NoopMeterProvider';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'metrics';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Metrics API\n */\nexport class MetricsAPI {\n private static _instance?: MetricsAPI;\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Metrics API */\n public static getInstance(): MetricsAPI {\n if (!this._instance) {\n this._instance = new MetricsAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current global meter provider.\n * Returns true if the meter provider was successfully registered, else false.\n */\n public setGlobalMeterProvider(provider: MeterProvider): boolean {\n return registerGlobal(API_NAME, provider, DiagAPI.instance());\n }\n\n /**\n * Returns the global meter provider.\n */\n public getMeterProvider(): MeterProvider {\n return getGlobal(API_NAME) || NOOP_METER_PROVIDER;\n }\n\n /**\n * Returns a meter from the global meter provider.\n */\n public getMeter(\n name: string,\n version?: string,\n options?: MeterOptions\n ): Meter {\n return this.getMeterProvider().getMeter(name, version, options);\n }\n\n /** Remove the global meter provider */\n public disable(): void {\n unregisterGlobal(API_NAME, DiagAPI.instance());\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/api/propagation.d.ts b/node_modules/@opentelemetry/api/build/src/api/propagation.d.ts new file mode 100644 index 0000000..a22d24d --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/api/propagation.d.ts @@ -0,0 +1,49 @@ +import { Context } from '../context/types'; +import { TextMapGetter, TextMapPropagator, TextMapSetter } from '../propagation/TextMapPropagator'; +import { getBaggage, getActiveBaggage, setBaggage, deleteBaggage } from '../baggage/context-helpers'; +import { createBaggage } from '../baggage/utils'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Propagation API + */ +export declare class PropagationAPI { + private static _instance?; + /** Empty private constructor prevents end users from constructing a new instance of the API */ + private constructor(); + /** Get the singleton instance of the Propagator API */ + static getInstance(): PropagationAPI; + /** + * Set the current propagator. + * + * @returns true if the propagator was successfully registered, else false + */ + setGlobalPropagator(propagator: TextMapPropagator): boolean; + /** + * Inject context into a carrier to be propagated inter-process + * + * @param context Context carrying tracing data to inject + * @param carrier carrier to inject context into + * @param setter Function used to set values on the carrier + */ + inject(context: Context, carrier: Carrier, setter?: TextMapSetter): void; + /** + * Extract context from a carrier + * + * @param context Context which the newly created context will inherit from + * @param carrier Carrier to extract context from + * @param getter Function used to extract keys from a carrier + */ + extract(context: Context, carrier: Carrier, getter?: TextMapGetter): Context; + /** + * Return a list of all fields which may be used by the propagator. + */ + fields(): string[]; + /** Remove the global propagator */ + disable(): void; + createBaggage: typeof createBaggage; + getBaggage: typeof getBaggage; + getActiveBaggage: typeof getActiveBaggage; + setBaggage: typeof setBaggage; + deleteBaggage: typeof deleteBaggage; + private _getGlobalPropagator; +} +//# sourceMappingURL=propagation.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/api/propagation.js b/node_modules/@opentelemetry/api/build/src/api/propagation.js new file mode 100644 index 0000000..7f03df8 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/api/propagation.js @@ -0,0 +1,89 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PropagationAPI = void 0; +const global_utils_1 = require("../internal/global-utils"); +const NoopTextMapPropagator_1 = require("../propagation/NoopTextMapPropagator"); +const TextMapPropagator_1 = require("../propagation/TextMapPropagator"); +const context_helpers_1 = require("../baggage/context-helpers"); +const utils_1 = require("../baggage/utils"); +const diag_1 = require("./diag"); +const API_NAME = 'propagation'; +const NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); +/** + * Singleton object which represents the entry point to the OpenTelemetry Propagation API + */ +class PropagationAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + this.createBaggage = utils_1.createBaggage; + this.getBaggage = context_helpers_1.getBaggage; + this.getActiveBaggage = context_helpers_1.getActiveBaggage; + this.setBaggage = context_helpers_1.setBaggage; + this.deleteBaggage = context_helpers_1.deleteBaggage; + } + /** Get the singleton instance of the Propagator API */ + static getInstance() { + if (!this._instance) { + this._instance = new PropagationAPI(); + } + return this._instance; + } + /** + * Set the current propagator. + * + * @returns true if the propagator was successfully registered, else false + */ + setGlobalPropagator(propagator) { + return (0, global_utils_1.registerGlobal)(API_NAME, propagator, diag_1.DiagAPI.instance()); + } + /** + * Inject context into a carrier to be propagated inter-process + * + * @param context Context carrying tracing data to inject + * @param carrier carrier to inject context into + * @param setter Function used to set values on the carrier + */ + inject(context, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) { + return this._getGlobalPropagator().inject(context, carrier, setter); + } + /** + * Extract context from a carrier + * + * @param context Context which the newly created context will inherit from + * @param carrier Carrier to extract context from + * @param getter Function used to extract keys from a carrier + */ + extract(context, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) { + return this._getGlobalPropagator().extract(context, carrier, getter); + } + /** + * Return a list of all fields which may be used by the propagator. + */ + fields() { + return this._getGlobalPropagator().fields(); + } + /** Remove the global propagator */ + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } + _getGlobalPropagator() { + return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; + } +} +exports.PropagationAPI = PropagationAPI; +//# sourceMappingURL=propagation.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/api/propagation.js.map b/node_modules/@opentelemetry/api/build/src/api/propagation.js.map new file mode 100644 index 0000000..bb3b7e1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/api/propagation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"propagation.js","sourceRoot":"","sources":["../../../src/api/propagation.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAGH,2DAIkC;AAClC,gFAA6E;AAC7E,wEAM0C;AAC1C,gEAKoC;AACpC,4CAAiD;AACjD,iCAAiC;AAEjC,MAAM,QAAQ,GAAG,aAAa,CAAC;AAC/B,MAAM,wBAAwB,GAAG,IAAI,6CAAqB,EAAE,CAAC;AAE7D;;GAEG;AACH,MAAa,cAAc;IAGzB,+FAA+F;IAC/F;QA8DO,kBAAa,GAAG,qBAAa,CAAC;QAE9B,eAAU,GAAG,4BAAU,CAAC;QAExB,qBAAgB,GAAG,kCAAgB,CAAC;QAEpC,eAAU,GAAG,4BAAU,CAAC;QAExB,kBAAa,GAAG,+BAAa,CAAC;IAtEd,CAAC;IAExB,uDAAuD;IAChD,MAAM,CAAC,WAAW;QACvB,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;YACnB,IAAI,CAAC,SAAS,GAAG,IAAI,cAAc,EAAE,CAAC;SACvC;QAED,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAED;;;;OAIG;IACI,mBAAmB,CAAC,UAA6B;QACtD,OAAO,IAAA,6BAAc,EAAC,QAAQ,EAAE,UAAU,EAAE,cAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;IAClE,CAAC;IAED;;;;;;OAMG;IACI,MAAM,CACX,OAAgB,EAChB,OAAgB,EAChB,SAAiC,wCAAoB;QAErD,OAAO,IAAI,CAAC,oBAAoB,EAAE,CAAC,MAAM,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;IACtE,CAAC;IAED;;;;;;OAMG;IACI,OAAO,CACZ,OAAgB,EAChB,OAAgB,EAChB,SAAiC,wCAAoB;QAErD,OAAO,IAAI,CAAC,oBAAoB,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;IACvE,CAAC;IAED;;OAEG;IACI,MAAM;QACX,OAAO,IAAI,CAAC,oBAAoB,EAAE,CAAC,MAAM,EAAE,CAAC;IAC9C,CAAC;IAED,mCAAmC;IAC5B,OAAO;QACZ,IAAA,+BAAgB,EAAC,QAAQ,EAAE,cAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;IACjD,CAAC;IAYO,oBAAoB;QAC1B,OAAO,IAAA,wBAAS,EAAC,QAAQ,CAAC,IAAI,wBAAwB,CAAC;IACzD,CAAC;CACF;AA/ED,wCA+EC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { NoopTextMapPropagator } from '../propagation/NoopTextMapPropagator';\nimport {\n defaultTextMapGetter,\n defaultTextMapSetter,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n} from '../propagation/TextMapPropagator';\nimport {\n getBaggage,\n getActiveBaggage,\n setBaggage,\n deleteBaggage,\n} from '../baggage/context-helpers';\nimport { createBaggage } from '../baggage/utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'propagation';\nconst NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator();\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Propagation API\n */\nexport class PropagationAPI {\n private static _instance?: PropagationAPI;\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Propagator API */\n public static getInstance(): PropagationAPI {\n if (!this._instance) {\n this._instance = new PropagationAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current propagator.\n *\n * @returns true if the propagator was successfully registered, else false\n */\n public setGlobalPropagator(propagator: TextMapPropagator): boolean {\n return registerGlobal(API_NAME, propagator, DiagAPI.instance());\n }\n\n /**\n * Inject context into a carrier to be propagated inter-process\n *\n * @param context Context carrying tracing data to inject\n * @param carrier carrier to inject context into\n * @param setter Function used to set values on the carrier\n */\n public inject(\n context: Context,\n carrier: Carrier,\n setter: TextMapSetter = defaultTextMapSetter\n ): void {\n return this._getGlobalPropagator().inject(context, carrier, setter);\n }\n\n /**\n * Extract context from a carrier\n *\n * @param context Context which the newly created context will inherit from\n * @param carrier Carrier to extract context from\n * @param getter Function used to extract keys from a carrier\n */\n public extract(\n context: Context,\n carrier: Carrier,\n getter: TextMapGetter = defaultTextMapGetter\n ): Context {\n return this._getGlobalPropagator().extract(context, carrier, getter);\n }\n\n /**\n * Return a list of all fields which may be used by the propagator.\n */\n public fields(): string[] {\n return this._getGlobalPropagator().fields();\n }\n\n /** Remove the global propagator */\n public disable() {\n unregisterGlobal(API_NAME, DiagAPI.instance());\n }\n\n public createBaggage = createBaggage;\n\n public getBaggage = getBaggage;\n\n public getActiveBaggage = getActiveBaggage;\n\n public setBaggage = setBaggage;\n\n public deleteBaggage = deleteBaggage;\n\n private _getGlobalPropagator(): TextMapPropagator {\n return getGlobal(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR;\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/api/trace.d.ts b/node_modules/@opentelemetry/api/build/src/api/trace.d.ts new file mode 100644 index 0000000..df59fd2 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/api/trace.d.ts @@ -0,0 +1,40 @@ +import { isSpanContextValid, wrapSpanContext } from '../trace/spancontext-utils'; +import { Tracer } from '../trace/tracer'; +import { TracerProvider } from '../trace/tracer_provider'; +import { deleteSpan, getActiveSpan, getSpan, getSpanContext, setSpan, setSpanContext } from '../trace/context-utils'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Tracing API + */ +export declare class TraceAPI { + private static _instance?; + private _proxyTracerProvider; + /** Empty private constructor prevents end users from constructing a new instance of the API */ + private constructor(); + /** Get the singleton instance of the Trace API */ + static getInstance(): TraceAPI; + /** + * Set the current global tracer. + * + * @returns true if the tracer provider was successfully registered, else false + */ + setGlobalTracerProvider(provider: TracerProvider): boolean; + /** + * Returns the global tracer provider. + */ + getTracerProvider(): TracerProvider; + /** + * Returns a tracer from the global tracer provider. + */ + getTracer(name: string, version?: string): Tracer; + /** Remove the global tracer provider */ + disable(): void; + wrapSpanContext: typeof wrapSpanContext; + isSpanContextValid: typeof isSpanContextValid; + deleteSpan: typeof deleteSpan; + getSpan: typeof getSpan; + getActiveSpan: typeof getActiveSpan; + getSpanContext: typeof getSpanContext; + setSpan: typeof setSpan; + setSpanContext: typeof setSpanContext; +} +//# sourceMappingURL=trace.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/api/trace.js b/node_modules/@opentelemetry/api/build/src/api/trace.js new file mode 100644 index 0000000..aa7a9da --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/api/trace.js @@ -0,0 +1,79 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TraceAPI = void 0; +const global_utils_1 = require("../internal/global-utils"); +const ProxyTracerProvider_1 = require("../trace/ProxyTracerProvider"); +const spancontext_utils_1 = require("../trace/spancontext-utils"); +const context_utils_1 = require("../trace/context-utils"); +const diag_1 = require("./diag"); +const API_NAME = 'trace'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Tracing API + */ +class TraceAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); + this.wrapSpanContext = spancontext_utils_1.wrapSpanContext; + this.isSpanContextValid = spancontext_utils_1.isSpanContextValid; + this.deleteSpan = context_utils_1.deleteSpan; + this.getSpan = context_utils_1.getSpan; + this.getActiveSpan = context_utils_1.getActiveSpan; + this.getSpanContext = context_utils_1.getSpanContext; + this.setSpan = context_utils_1.setSpan; + this.setSpanContext = context_utils_1.setSpanContext; + } + /** Get the singleton instance of the Trace API */ + static getInstance() { + if (!this._instance) { + this._instance = new TraceAPI(); + } + return this._instance; + } + /** + * Set the current global tracer. + * + * @returns true if the tracer provider was successfully registered, else false + */ + setGlobalTracerProvider(provider) { + const success = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); + if (success) { + this._proxyTracerProvider.setDelegate(provider); + } + return success; + } + /** + * Returns the global tracer provider. + */ + getTracerProvider() { + return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider; + } + /** + * Returns a tracer from the global tracer provider. + */ + getTracer(name, version) { + return this.getTracerProvider().getTracer(name, version); + } + /** Remove the global tracer provider */ + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); + } +} +exports.TraceAPI = TraceAPI; +//# sourceMappingURL=trace.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/api/trace.js.map b/node_modules/@opentelemetry/api/build/src/api/trace.js.map new file mode 100644 index 0000000..9bd3112 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/api/trace.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trace.js","sourceRoot":"","sources":["../../../src/api/trace.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,2DAIkC;AAClC,sEAAmE;AACnE,kEAGoC;AAGpC,0DAOgC;AAChC,iCAAiC;AAEjC,MAAM,QAAQ,GAAG,OAAO,CAAC;AAEzB;;GAEG;AACH,MAAa,QAAQ;IAKnB,+FAA+F;IAC/F;QAHQ,yBAAoB,GAAG,IAAI,yCAAmB,EAAE,CAAC;QAmDlD,oBAAe,GAAG,mCAAe,CAAC;QAElC,uBAAkB,GAAG,sCAAkB,CAAC;QAExC,eAAU,GAAG,0BAAU,CAAC;QAExB,YAAO,GAAG,uBAAO,CAAC;QAElB,kBAAa,GAAG,6BAAa,CAAC;QAE9B,mBAAc,GAAG,8BAAc,CAAC;QAEhC,YAAO,GAAG,uBAAO,CAAC;QAElB,mBAAc,GAAG,8BAAc,CAAC;IA9DhB,CAAC;IAExB,kDAAkD;IAC3C,MAAM,CAAC,WAAW;QACvB,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;YACnB,IAAI,CAAC,SAAS,GAAG,IAAI,QAAQ,EAAE,CAAC;SACjC;QAED,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAED;;;;OAIG;IACI,uBAAuB,CAAC,QAAwB;QACrD,MAAM,OAAO,GAAG,IAAA,6BAAc,EAC5B,QAAQ,EACR,IAAI,CAAC,oBAAoB,EACzB,cAAO,CAAC,QAAQ,EAAE,CACnB,CAAC;QACF,IAAI,OAAO,EAAE;YACX,IAAI,CAAC,oBAAoB,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;SACjD;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;IAED;;OAEG;IACI,iBAAiB;QACtB,OAAO,IAAA,wBAAS,EAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,oBAAoB,CAAC;IAC1D,CAAC;IAED;;OAEG;IACI,SAAS,CAAC,IAAY,EAAE,OAAgB;QAC7C,OAAO,IAAI,CAAC,iBAAiB,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IAC3D,CAAC;IAED,wCAAwC;IACjC,OAAO;QACZ,IAAA,+BAAgB,EAAC,QAAQ,EAAE,cAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;QAC/C,IAAI,CAAC,oBAAoB,GAAG,IAAI,yCAAmB,EAAE,CAAC;IACxD,CAAC;CAiBF;AArED,4BAqEC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { ProxyTracerProvider } from '../trace/ProxyTracerProvider';\nimport {\n isSpanContextValid,\n wrapSpanContext,\n} from '../trace/spancontext-utils';\nimport { Tracer } from '../trace/tracer';\nimport { TracerProvider } from '../trace/tracer_provider';\nimport {\n deleteSpan,\n getActiveSpan,\n getSpan,\n getSpanContext,\n setSpan,\n setSpanContext,\n} from '../trace/context-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'trace';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Tracing API\n */\nexport class TraceAPI {\n private static _instance?: TraceAPI;\n\n private _proxyTracerProvider = new ProxyTracerProvider();\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Trace API */\n public static getInstance(): TraceAPI {\n if (!this._instance) {\n this._instance = new TraceAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current global tracer.\n *\n * @returns true if the tracer provider was successfully registered, else false\n */\n public setGlobalTracerProvider(provider: TracerProvider): boolean {\n const success = registerGlobal(\n API_NAME,\n this._proxyTracerProvider,\n DiagAPI.instance()\n );\n if (success) {\n this._proxyTracerProvider.setDelegate(provider);\n }\n return success;\n }\n\n /**\n * Returns the global tracer provider.\n */\n public getTracerProvider(): TracerProvider {\n return getGlobal(API_NAME) || this._proxyTracerProvider;\n }\n\n /**\n * Returns a tracer from the global tracer provider.\n */\n public getTracer(name: string, version?: string): Tracer {\n return this.getTracerProvider().getTracer(name, version);\n }\n\n /** Remove the global tracer provider */\n public disable() {\n unregisterGlobal(API_NAME, DiagAPI.instance());\n this._proxyTracerProvider = new ProxyTracerProvider();\n }\n\n public wrapSpanContext = wrapSpanContext;\n\n public isSpanContextValid = isSpanContextValid;\n\n public deleteSpan = deleteSpan;\n\n public getSpan = getSpan;\n\n public getActiveSpan = getActiveSpan;\n\n public getSpanContext = getSpanContext;\n\n public setSpan = setSpan;\n\n public setSpanContext = setSpanContext;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/baggage/context-helpers.d.ts b/node_modules/@opentelemetry/api/build/src/baggage/context-helpers.d.ts new file mode 100644 index 0000000..23750eb --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/baggage/context-helpers.d.ts @@ -0,0 +1,29 @@ +import { Context } from '../context/types'; +import { Baggage } from './types'; +/** + * Retrieve the current baggage from the given context + * + * @param {Context} Context that manage all context values + * @returns {Baggage} Extracted baggage from the context + */ +export declare function getBaggage(context: Context): Baggage | undefined; +/** + * Retrieve the current baggage from the active/current context + * + * @returns {Baggage} Extracted baggage from the context + */ +export declare function getActiveBaggage(): Baggage | undefined; +/** + * Store a baggage in the given context + * + * @param {Context} Context that manage all context values + * @param {Baggage} baggage that will be set in the actual context + */ +export declare function setBaggage(context: Context, baggage: Baggage): Context; +/** + * Delete the baggage stored in the given context + * + * @param {Context} Context that manage all context values + */ +export declare function deleteBaggage(context: Context): Context; +//# sourceMappingURL=context-helpers.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js b/node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js new file mode 100644 index 0000000..cc0f00b --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js @@ -0,0 +1,63 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.deleteBaggage = exports.setBaggage = exports.getActiveBaggage = exports.getBaggage = void 0; +const context_1 = require("../api/context"); +const context_2 = require("../context/context"); +/** + * Baggage key + */ +const BAGGAGE_KEY = (0, context_2.createContextKey)('OpenTelemetry Baggage Key'); +/** + * Retrieve the current baggage from the given context + * + * @param {Context} Context that manage all context values + * @returns {Baggage} Extracted baggage from the context + */ +function getBaggage(context) { + return context.getValue(BAGGAGE_KEY) || undefined; +} +exports.getBaggage = getBaggage; +/** + * Retrieve the current baggage from the active/current context + * + * @returns {Baggage} Extracted baggage from the context + */ +function getActiveBaggage() { + return getBaggage(context_1.ContextAPI.getInstance().active()); +} +exports.getActiveBaggage = getActiveBaggage; +/** + * Store a baggage in the given context + * + * @param {Context} Context that manage all context values + * @param {Baggage} baggage that will be set in the actual context + */ +function setBaggage(context, baggage) { + return context.setValue(BAGGAGE_KEY, baggage); +} +exports.setBaggage = setBaggage; +/** + * Delete the baggage stored in the given context + * + * @param {Context} Context that manage all context values + */ +function deleteBaggage(context) { + return context.deleteValue(BAGGAGE_KEY); +} +exports.deleteBaggage = deleteBaggage; +//# sourceMappingURL=context-helpers.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js.map b/node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js.map new file mode 100644 index 0000000..ba60094 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"context-helpers.js","sourceRoot":"","sources":["../../../src/baggage/context-helpers.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4CAA4C;AAC5C,gDAAsD;AAItD;;GAEG;AACH,MAAM,WAAW,GAAG,IAAA,0BAAgB,EAAC,2BAA2B,CAAC,CAAC;AAElE;;;;;GAKG;AACH,SAAgB,UAAU,CAAC,OAAgB;IACzC,OAAQ,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAa,IAAI,SAAS,CAAC;AACjE,CAAC;AAFD,gCAEC;AAED;;;;GAIG;AACH,SAAgB,gBAAgB;IAC9B,OAAO,UAAU,CAAC,oBAAU,CAAC,WAAW,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC;AACvD,CAAC;AAFD,4CAEC;AAED;;;;;GAKG;AACH,SAAgB,UAAU,CAAC,OAAgB,EAAE,OAAgB;IAC3D,OAAO,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;AAChD,CAAC;AAFD,gCAEC;AAED;;;;GAIG;AACH,SAAgB,aAAa,CAAC,OAAgB;IAC5C,OAAO,OAAO,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC;AAC1C,CAAC;AAFD,sCAEC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ContextAPI } from '../api/context';\nimport { createContextKey } from '../context/context';\nimport { Context } from '../context/types';\nimport { Baggage } from './types';\n\n/**\n * Baggage key\n */\nconst BAGGAGE_KEY = createContextKey('OpenTelemetry Baggage Key');\n\n/**\n * Retrieve the current baggage from the given context\n *\n * @param {Context} Context that manage all context values\n * @returns {Baggage} Extracted baggage from the context\n */\nexport function getBaggage(context: Context): Baggage | undefined {\n return (context.getValue(BAGGAGE_KEY) as Baggage) || undefined;\n}\n\n/**\n * Retrieve the current baggage from the active/current context\n *\n * @returns {Baggage} Extracted baggage from the context\n */\nexport function getActiveBaggage(): Baggage | undefined {\n return getBaggage(ContextAPI.getInstance().active());\n}\n\n/**\n * Store a baggage in the given context\n *\n * @param {Context} Context that manage all context values\n * @param {Baggage} baggage that will be set in the actual context\n */\nexport function setBaggage(context: Context, baggage: Baggage): Context {\n return context.setValue(BAGGAGE_KEY, baggage);\n}\n\n/**\n * Delete the baggage stored in the given context\n *\n * @param {Context} Context that manage all context values\n */\nexport function deleteBaggage(context: Context): Context {\n return context.deleteValue(BAGGAGE_KEY);\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.d.ts b/node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.d.ts new file mode 100644 index 0000000..e6b4554 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.d.ts @@ -0,0 +1,12 @@ +import type { Baggage, BaggageEntry } from '../types'; +export declare class BaggageImpl implements Baggage { + private _entries; + constructor(entries?: Map); + getEntry(key: string): BaggageEntry | undefined; + getAllEntries(): [string, BaggageEntry][]; + setEntry(key: string, entry: BaggageEntry): BaggageImpl; + removeEntry(key: string): BaggageImpl; + removeEntries(...keys: string[]): BaggageImpl; + clear(): BaggageImpl; +} +//# sourceMappingURL=baggage-impl.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js b/node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js new file mode 100644 index 0000000..6f04d4a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js @@ -0,0 +1,55 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BaggageImpl = void 0; +class BaggageImpl { + constructor(entries) { + this._entries = entries ? new Map(entries) : new Map(); + } + getEntry(key) { + const entry = this._entries.get(key); + if (!entry) { + return undefined; + } + return Object.assign({}, entry); + } + getAllEntries() { + return Array.from(this._entries.entries()).map(([k, v]) => [k, v]); + } + setEntry(key, entry) { + const newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.set(key, entry); + return newBaggage; + } + removeEntry(key) { + const newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.delete(key); + return newBaggage; + } + removeEntries(...keys) { + const newBaggage = new BaggageImpl(this._entries); + for (const key of keys) { + newBaggage._entries.delete(key); + } + return newBaggage; + } + clear() { + return new BaggageImpl(); + } +} +exports.BaggageImpl = BaggageImpl; +//# sourceMappingURL=baggage-impl.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js.map b/node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js.map new file mode 100644 index 0000000..e95c4bc --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js.map @@ -0,0 +1 @@ +{"version":3,"file":"baggage-impl.js","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,CAAC;QAClD,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE;YACtB,UAAU,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;SACjC;QACD,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,KAAK;QACH,OAAO,IAAI,WAAW,EAAE,CAAC;IAC3B,CAAC;CACF;AA3CD,kCA2CC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Baggage, BaggageEntry } from '../types';\n\nexport class BaggageImpl implements Baggage {\n private _entries: Map;\n\n constructor(entries?: Map) {\n this._entries = entries ? new Map(entries) : new Map();\n }\n\n getEntry(key: string): BaggageEntry | undefined {\n const entry = this._entries.get(key);\n if (!entry) {\n return undefined;\n }\n\n return Object.assign({}, entry);\n }\n\n getAllEntries(): [string, BaggageEntry][] {\n return Array.from(this._entries.entries()).map(([k, v]) => [k, v]);\n }\n\n setEntry(key: string, entry: BaggageEntry): BaggageImpl {\n const newBaggage = new BaggageImpl(this._entries);\n newBaggage._entries.set(key, entry);\n return newBaggage;\n }\n\n removeEntry(key: string): BaggageImpl {\n const newBaggage = new BaggageImpl(this._entries);\n newBaggage._entries.delete(key);\n return newBaggage;\n }\n\n removeEntries(...keys: string[]): BaggageImpl {\n const newBaggage = new BaggageImpl(this._entries);\n for (const key of keys) {\n newBaggage._entries.delete(key);\n }\n return newBaggage;\n }\n\n clear(): BaggageImpl {\n return new BaggageImpl();\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.d.ts b/node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.d.ts new file mode 100644 index 0000000..9cd991c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.d.ts @@ -0,0 +1,5 @@ +/** + * Symbol used to make BaggageEntryMetadata an opaque type + */ +export declare const baggageEntryMetadataSymbol: unique symbol; +//# sourceMappingURL=symbol.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js b/node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js new file mode 100644 index 0000000..324c216 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js @@ -0,0 +1,23 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.baggageEntryMetadataSymbol = void 0; +/** + * Symbol used to make BaggageEntryMetadata an opaque type + */ +exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); +//# sourceMappingURL=symbol.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js.map b/node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js.map new file mode 100644 index 0000000..497f362 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js.map @@ -0,0 +1 @@ +{"version":3,"file":"symbol.js","sourceRoot":"","sources":["../../../../src/baggage/internal/symbol.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH;;GAEG;AACU,QAAA,0BAA0B,GAAG,MAAM,CAAC,sBAAsB,CAAC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Symbol used to make BaggageEntryMetadata an opaque type\n */\nexport const baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata');\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/baggage/types.d.ts b/node_modules/@opentelemetry/api/build/src/baggage/types.d.ts new file mode 100644 index 0000000..32fa0ec --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/baggage/types.d.ts @@ -0,0 +1,60 @@ +import { baggageEntryMetadataSymbol } from './internal/symbol'; +export interface BaggageEntry { + /** `String` value of the `BaggageEntry`. */ + value: string; + /** + * Metadata is an optional string property defined by the W3C baggage specification. + * It currently has no special meaning defined by the specification. + */ + metadata?: BaggageEntryMetadata; +} +/** + * Serializable Metadata defined by the W3C baggage specification. + * It currently has no special meaning defined by the OpenTelemetry or W3C. + */ +export declare type BaggageEntryMetadata = { + toString(): string; +} & { + __TYPE__: typeof baggageEntryMetadataSymbol; +}; +/** + * Baggage represents collection of key-value pairs with optional metadata. + * Each key of Baggage is associated with exactly one value. + * Baggage may be used to annotate and enrich telemetry data. + */ +export interface Baggage { + /** + * Get an entry from Baggage if it exists + * + * @param key The key which identifies the BaggageEntry + */ + getEntry(key: string): BaggageEntry | undefined; + /** + * Get a list of all entries in the Baggage + */ + getAllEntries(): [string, BaggageEntry][]; + /** + * Returns a new baggage with the entries from the current bag and the specified entry + * + * @param key string which identifies the baggage entry + * @param entry BaggageEntry for the given key + */ + setEntry(key: string, entry: BaggageEntry): Baggage; + /** + * Returns a new baggage with the entries from the current bag except the removed entry + * + * @param key key identifying the entry to be removed + */ + removeEntry(key: string): Baggage; + /** + * Returns a new baggage with the entries from the current bag except the removed entries + * + * @param key keys identifying the entries to be removed + */ + removeEntries(...key: string[]): Baggage; + /** + * Returns a new baggage with no entries + */ + clear(): Baggage; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/baggage/types.js b/node_modules/@opentelemetry/api/build/src/baggage/types.js new file mode 100644 index 0000000..c428c6d --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/baggage/types.js @@ -0,0 +1,18 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/baggage/types.js.map b/node_modules/@opentelemetry/api/build/src/baggage/types.js.map new file mode 100644 index 0000000..2a00da4 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/baggage/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/baggage/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { baggageEntryMetadataSymbol } from './internal/symbol';\n\n/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface BaggageEntry {\n /** `String` value of the `BaggageEntry`. */\n value: string;\n /**\n * Metadata is an optional string property defined by the W3C baggage specification.\n * It currently has no special meaning defined by the specification.\n */\n metadata?: BaggageEntryMetadata;\n}\n\n/**\n * Serializable Metadata defined by the W3C baggage specification.\n * It currently has no special meaning defined by the OpenTelemetry or W3C.\n */\nexport type BaggageEntryMetadata = { toString(): string } & {\n __TYPE__: typeof baggageEntryMetadataSymbol;\n};\n\n/**\n * Baggage represents collection of key-value pairs with optional metadata.\n * Each key of Baggage is associated with exactly one value.\n * Baggage may be used to annotate and enrich telemetry data.\n */\nexport interface Baggage {\n /**\n * Get an entry from Baggage if it exists\n *\n * @param key The key which identifies the BaggageEntry\n */\n getEntry(key: string): BaggageEntry | undefined;\n\n /**\n * Get a list of all entries in the Baggage\n */\n getAllEntries(): [string, BaggageEntry][];\n\n /**\n * Returns a new baggage with the entries from the current bag and the specified entry\n *\n * @param key string which identifies the baggage entry\n * @param entry BaggageEntry for the given key\n */\n setEntry(key: string, entry: BaggageEntry): Baggage;\n\n /**\n * Returns a new baggage with the entries from the current bag except the removed entry\n *\n * @param key key identifying the entry to be removed\n */\n removeEntry(key: string): Baggage;\n\n /**\n * Returns a new baggage with the entries from the current bag except the removed entries\n *\n * @param key keys identifying the entries to be removed\n */\n removeEntries(...key: string[]): Baggage;\n\n /**\n * Returns a new baggage with no entries\n */\n clear(): Baggage;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/baggage/utils.d.ts b/node_modules/@opentelemetry/api/build/src/baggage/utils.d.ts new file mode 100644 index 0000000..9955d9e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/baggage/utils.d.ts @@ -0,0 +1,15 @@ +import { Baggage, BaggageEntry, BaggageEntryMetadata } from './types'; +/** + * Create a new Baggage with optional entries + * + * @param entries An array of baggage entries the new baggage should contain + */ +export declare function createBaggage(entries?: Record): Baggage; +/** + * Create a serializable BaggageEntryMetadata object from a string. + * + * @param str string metadata. Format is currently not defined by the spec and has no special meaning. + * + */ +export declare function baggageEntryMetadataFromString(str: string): BaggageEntryMetadata; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/baggage/utils.js b/node_modules/@opentelemetry/api/build/src/baggage/utils.js new file mode 100644 index 0000000..a0bfbf6 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/baggage/utils.js @@ -0,0 +1,51 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.baggageEntryMetadataFromString = exports.createBaggage = void 0; +const diag_1 = require("../api/diag"); +const baggage_impl_1 = require("./internal/baggage-impl"); +const symbol_1 = require("./internal/symbol"); +const diag = diag_1.DiagAPI.instance(); +/** + * Create a new Baggage with optional entries + * + * @param entries An array of baggage entries the new baggage should contain + */ +function createBaggage(entries = {}) { + return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries))); +} +exports.createBaggage = createBaggage; +/** + * Create a serializable BaggageEntryMetadata object from a string. + * + * @param str string metadata. Format is currently not defined by the spec and has no special meaning. + * + */ +function baggageEntryMetadataFromString(str) { + if (typeof str !== 'string') { + diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`); + str = ''; + } + return { + __TYPE__: symbol_1.baggageEntryMetadataSymbol, + toString() { + return str; + }, + }; +} +exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/baggage/utils.js.map b/node_modules/@opentelemetry/api/build/src/baggage/utils.js.map new file mode 100644 index 0000000..d3e6ee8 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/baggage/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/baggage/utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,sCAAsC;AACtC,0DAAsD;AACtD,8CAA+D;AAG/D,MAAM,IAAI,GAAG,cAAO,CAAC,QAAQ,EAAE,CAAC;AAEhC;;;;GAIG;AACH,SAAgB,aAAa,CAC3B,UAAwC,EAAE;IAE1C,OAAO,IAAI,0BAAW,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;AAC3D,CAAC;AAJD,sCAIC;AAED;;;;;GAKG;AACH,SAAgB,8BAA8B,CAC5C,GAAW;IAEX,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;QAC3B,IAAI,CAAC,KAAK,CACR,qDAAqD,OAAO,GAAG,EAAE,CAClE,CAAC;QACF,GAAG,GAAG,EAAE,CAAC;KACV;IAED,OAAO;QACL,QAAQ,EAAE,mCAA0B;QACpC,QAAQ;YACN,OAAO,GAAG,CAAC;QACb,CAAC;KACF,CAAC;AACJ,CAAC;AAhBD,wEAgBC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagAPI } from '../api/diag';\nimport { BaggageImpl } from './internal/baggage-impl';\nimport { baggageEntryMetadataSymbol } from './internal/symbol';\nimport { Baggage, BaggageEntry, BaggageEntryMetadata } from './types';\n\nconst diag = DiagAPI.instance();\n\n/**\n * Create a new Baggage with optional entries\n *\n * @param entries An array of baggage entries the new baggage should contain\n */\nexport function createBaggage(\n entries: Record = {}\n): Baggage {\n return new BaggageImpl(new Map(Object.entries(entries)));\n}\n\n/**\n * Create a serializable BaggageEntryMetadata object from a string.\n *\n * @param str string metadata. Format is currently not defined by the spec and has no special meaning.\n *\n */\nexport function baggageEntryMetadataFromString(\n str: string\n): BaggageEntryMetadata {\n if (typeof str !== 'string') {\n diag.error(\n `Cannot create baggage metadata from unknown type: ${typeof str}`\n );\n str = '';\n }\n\n return {\n __TYPE__: baggageEntryMetadataSymbol,\n toString() {\n return str;\n },\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/common/Attributes.d.ts b/node_modules/@opentelemetry/api/build/src/common/Attributes.d.ts new file mode 100644 index 0000000..19994fb --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/common/Attributes.d.ts @@ -0,0 +1,15 @@ +/** + * Attributes is a map from string to attribute values. + * + * Note: only the own enumerable keys are counted as valid attribute keys. + */ +export interface Attributes { + [attributeKey: string]: AttributeValue | undefined; +} +/** + * Attribute values may be any non-nullish primitive value except an object. + * + * null or undefined attribute values are invalid and will result in undefined behavior. + */ +export declare type AttributeValue = string | number | boolean | Array | Array | Array; +//# sourceMappingURL=Attributes.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/common/Attributes.js b/node_modules/@opentelemetry/api/build/src/common/Attributes.js new file mode 100644 index 0000000..684c93d --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/common/Attributes.js @@ -0,0 +1,18 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Attributes.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/common/Attributes.js.map b/node_modules/@opentelemetry/api/build/src/common/Attributes.js.map new file mode 100644 index 0000000..81b1168 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/common/Attributes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Attributes.js","sourceRoot":"","sources":["../../../src/common/Attributes.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Attributes is a map from string to attribute values.\n *\n * Note: only the own enumerable keys are counted as valid attribute keys.\n */\nexport interface Attributes {\n [attributeKey: string]: AttributeValue | undefined;\n}\n\n/**\n * Attribute values may be any non-nullish primitive value except an object.\n *\n * null or undefined attribute values are invalid and will result in undefined behavior.\n */\nexport type AttributeValue =\n | string\n | number\n | boolean\n | Array\n | Array\n | Array;\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/common/Exception.d.ts b/node_modules/@opentelemetry/api/build/src/common/Exception.d.ts new file mode 100644 index 0000000..e175a7f --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/common/Exception.d.ts @@ -0,0 +1,26 @@ +interface ExceptionWithCode { + code: string | number; + name?: string; + message?: string; + stack?: string; +} +interface ExceptionWithMessage { + code?: string | number; + message: string; + name?: string; + stack?: string; +} +interface ExceptionWithName { + code?: string | number; + message?: string; + name: string; + stack?: string; +} +/** + * Defines Exception. + * + * string or an object with one of (message or name or code) and optional stack + */ +export declare type Exception = ExceptionWithCode | ExceptionWithMessage | ExceptionWithName | string; +export {}; +//# sourceMappingURL=Exception.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/common/Exception.js b/node_modules/@opentelemetry/api/build/src/common/Exception.js new file mode 100644 index 0000000..ed450ae --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/common/Exception.js @@ -0,0 +1,18 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Exception.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/common/Exception.js.map b/node_modules/@opentelemetry/api/build/src/common/Exception.js.map new file mode 100644 index 0000000..459c350 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/common/Exception.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Exception.js","sourceRoot":"","sources":["../../../src/common/Exception.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\ninterface ExceptionWithCode {\n code: string | number;\n name?: string;\n message?: string;\n stack?: string;\n}\n\ninterface ExceptionWithMessage {\n code?: string | number;\n message: string;\n name?: string;\n stack?: string;\n}\n\ninterface ExceptionWithName {\n code?: string | number;\n message?: string;\n name: string;\n stack?: string;\n}\n\n/**\n * Defines Exception.\n *\n * string or an object with one of (message or name or code) and optional stack\n */\nexport type Exception =\n | ExceptionWithCode\n | ExceptionWithMessage\n | ExceptionWithName\n | string;\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/common/Time.d.ts b/node_modules/@opentelemetry/api/build/src/common/Time.d.ts new file mode 100644 index 0000000..cc3c502 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/common/Time.d.ts @@ -0,0 +1,20 @@ +/** + * Defines High-Resolution Time. + * + * The first number, HrTime[0], is UNIX Epoch time in seconds since 00:00:00 UTC on 1 January 1970. + * The second number, HrTime[1], represents the partial second elapsed since Unix Epoch time represented by first number in nanoseconds. + * For example, 2021-01-01T12:30:10.150Z in UNIX Epoch time in milliseconds is represented as 1609504210150. + * The first number is calculated by converting and truncating the Epoch time in milliseconds to seconds: + * HrTime[0] = Math.trunc(1609504210150 / 1000) = 1609504210. + * The second number is calculated by converting the digits after the decimal point of the subtraction, (1609504210150 / 1000) - HrTime[0], to nanoseconds: + * HrTime[1] = Number((1609504210.150 - HrTime[0]).toFixed(9)) * 1e9 = 150000000. + * This is represented in HrTime format as [1609504210, 150000000]. + */ +export declare type HrTime = [number, number]; +/** + * Defines TimeInput. + * + * hrtime, epoch milliseconds, performance.now() or Date + */ +export declare type TimeInput = HrTime | number | Date; +//# sourceMappingURL=Time.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/common/Time.js b/node_modules/@opentelemetry/api/build/src/common/Time.js new file mode 100644 index 0000000..1faaf69 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/common/Time.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Time.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/common/Time.js.map b/node_modules/@opentelemetry/api/build/src/common/Time.js.map new file mode 100644 index 0000000..ae124f0 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/common/Time.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Time.js","sourceRoot":"","sources":["../../../src/common/Time.ts"],"names":[],"mappings":"","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Defines High-Resolution Time.\n *\n * The first number, HrTime[0], is UNIX Epoch time in seconds since 00:00:00 UTC on 1 January 1970.\n * The second number, HrTime[1], represents the partial second elapsed since Unix Epoch time represented by first number in nanoseconds.\n * For example, 2021-01-01T12:30:10.150Z in UNIX Epoch time in milliseconds is represented as 1609504210150.\n * The first number is calculated by converting and truncating the Epoch time in milliseconds to seconds:\n * HrTime[0] = Math.trunc(1609504210150 / 1000) = 1609504210.\n * The second number is calculated by converting the digits after the decimal point of the subtraction, (1609504210150 / 1000) - HrTime[0], to nanoseconds:\n * HrTime[1] = Number((1609504210.150 - HrTime[0]).toFixed(9)) * 1e9 = 150000000.\n * This is represented in HrTime format as [1609504210, 150000000].\n */\nexport type HrTime = [number, number];\n\n/**\n * Defines TimeInput.\n *\n * hrtime, epoch milliseconds, performance.now() or Date\n */\nexport type TimeInput = HrTime | number | Date;\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/context-api.d.ts b/node_modules/@opentelemetry/api/build/src/context-api.d.ts new file mode 100644 index 0000000..650f4ee --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/context-api.d.ts @@ -0,0 +1,4 @@ +import { ContextAPI } from './api/context'; +/** Entrypoint for context API */ +export declare const context: ContextAPI; +//# sourceMappingURL=context-api.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/context-api.js b/node_modules/@opentelemetry/api/build/src/context-api.js new file mode 100644 index 0000000..b9aeea9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/context-api.js @@ -0,0 +1,24 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.context = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const context_1 = require("./api/context"); +/** Entrypoint for context API */ +exports.context = context_1.ContextAPI.getInstance(); +//# sourceMappingURL=context-api.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/context-api.js.map b/node_modules/@opentelemetry/api/build/src/context-api.js.map new file mode 100644 index 0000000..e8e3f92 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/context-api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"context-api.js","sourceRoot":"","sources":["../../src/context-api.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,sEAAsE;AACtE,qCAAqC;AACrC,2CAA2C;AAC3C,iCAAiC;AACpB,QAAA,OAAO,GAAG,oBAAU,CAAC,WAAW,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { ContextAPI } from './api/context';\n/** Entrypoint for context API */\nexport const context = ContextAPI.getInstance();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/context/NoopContextManager.d.ts b/node_modules/@opentelemetry/api/build/src/context/NoopContextManager.d.ts new file mode 100644 index 0000000..48a1659 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/context/NoopContextManager.d.ts @@ -0,0 +1,9 @@ +import * as types from './types'; +export declare class NoopContextManager implements types.ContextManager { + active(): types.Context; + with ReturnType>(_context: types.Context, fn: F, thisArg?: ThisParameterType, ...args: A): ReturnType; + bind(_context: types.Context, target: T): T; + enable(): this; + disable(): this; +} +//# sourceMappingURL=NoopContextManager.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js b/node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js new file mode 100644 index 0000000..10c6ae1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js @@ -0,0 +1,38 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NoopContextManager = void 0; +const context_1 = require("./context"); +class NoopContextManager { + active() { + return context_1.ROOT_CONTEXT; + } + with(_context, fn, thisArg, ...args) { + return fn.call(thisArg, ...args); + } + bind(_context, target) { + return target; + } + enable() { + return this; + } + disable() { + return this; + } +} +exports.NoopContextManager = NoopContextManager; +//# sourceMappingURL=NoopContextManager.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js.map b/node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js.map new file mode 100644 index 0000000..46b0612 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NoopContextManager.js","sourceRoot":"","sources":["../../../src/context/NoopContextManager.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,uCAAyC;AAGzC,MAAa,kBAAkB;IAC7B,MAAM;QACJ,OAAO,sBAAY,CAAC;IACtB,CAAC;IAED,IAAI,CACF,QAAuB,EACvB,EAAK,EACL,OAA8B,EAC9B,GAAG,IAAO;QAEV,OAAO,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,CAAC;IACnC,CAAC;IAED,IAAI,CAAI,QAAuB,EAAE,MAAS;QACxC,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,MAAM;QACJ,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAzBD,gDAyBC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ROOT_CONTEXT } from './context';\nimport * as types from './types';\n\nexport class NoopContextManager implements types.ContextManager {\n active(): types.Context {\n return ROOT_CONTEXT;\n }\n\n with ReturnType>(\n _context: types.Context,\n fn: F,\n thisArg?: ThisParameterType,\n ...args: A\n ): ReturnType {\n return fn.call(thisArg, ...args);\n }\n\n bind(_context: types.Context, target: T): T {\n return target;\n }\n\n enable(): this {\n return this;\n }\n\n disable(): this {\n return this;\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/context/context.d.ts b/node_modules/@opentelemetry/api/build/src/context/context.d.ts new file mode 100644 index 0000000..8be0259 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/context/context.d.ts @@ -0,0 +1,6 @@ +import { Context } from './types'; +/** Get a key to uniquely identify a context value */ +export declare function createContextKey(description: string): symbol; +/** The root context is used as the default parent context when there is no active context */ +export declare const ROOT_CONTEXT: Context; +//# sourceMappingURL=context.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/context/context.js b/node_modules/@opentelemetry/api/build/src/context/context.js new file mode 100644 index 0000000..eecc159 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/context/context.js @@ -0,0 +1,55 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ROOT_CONTEXT = exports.createContextKey = void 0; +/** Get a key to uniquely identify a context value */ +function createContextKey(description) { + // The specification states that for the same input, multiple calls should + // return different keys. Due to the nature of the JS dependency management + // system, this creates problems where multiple versions of some package + // could hold different keys for the same property. + // + // Therefore, we use Symbol.for which returns the same key for the same input. + return Symbol.for(description); +} +exports.createContextKey = createContextKey; +class BaseContext { + /** + * Construct a new context which inherits values from an optional parent context. + * + * @param parentContext a context from which to inherit values + */ + constructor(parentContext) { + // for minification + const self = this; + self._currentContext = parentContext ? new Map(parentContext) : new Map(); + self.getValue = (key) => self._currentContext.get(key); + self.setValue = (key, value) => { + const context = new BaseContext(self._currentContext); + context._currentContext.set(key, value); + return context; + }; + self.deleteValue = (key) => { + const context = new BaseContext(self._currentContext); + context._currentContext.delete(key); + return context; + }; + } +} +/** The root context is used as the default parent context when there is no active context */ +exports.ROOT_CONTEXT = new BaseContext(); +//# sourceMappingURL=context.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/context/context.js.map b/node_modules/@opentelemetry/api/build/src/context/context.js.map new file mode 100644 index 0000000..e46cf8d --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/context/context.js.map @@ -0,0 +1 @@ +{"version":3,"file":"context.js","sourceRoot":"","sources":["../../../src/context/context.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAIH,qDAAqD;AACrD,SAAgB,gBAAgB,CAAC,WAAmB;IAClD,0EAA0E;IAC1E,2EAA2E;IAC3E,wEAAwE;IACxE,mDAAmD;IACnD,EAAE;IACF,8EAA8E;IAC9E,OAAO,MAAM,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;AACjC,CAAC;AARD,4CAQC;AAED,MAAM,WAAW;IAGf;;;;OAIG;IACH,YAAY,aAAoC;QAC9C,mBAAmB;QACnB,MAAM,IAAI,GAAG,IAAI,CAAC;QAElB,IAAI,CAAC,eAAe,GAAG,aAAa,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,EAAE,CAAC;QAE1E,IAAI,CAAC,QAAQ,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAE/D,IAAI,CAAC,QAAQ,GAAG,CAAC,GAAW,EAAE,KAAc,EAAW,EAAE;YACvD,MAAM,OAAO,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;YACtD,OAAO,CAAC,eAAe,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;YACxC,OAAO,OAAO,CAAC;QACjB,CAAC,CAAC;QAEF,IAAI,CAAC,WAAW,GAAG,CAAC,GAAW,EAAW,EAAE;YAC1C,MAAM,OAAO,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;YACtD,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YACpC,OAAO,OAAO,CAAC;QACjB,CAAC,CAAC;IACJ,CAAC;CAyBF;AAED,6FAA6F;AAChF,QAAA,YAAY,GAAY,IAAI,WAAW,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from './types';\n\n/** Get a key to uniquely identify a context value */\nexport function createContextKey(description: string) {\n // The specification states that for the same input, multiple calls should\n // return different keys. Due to the nature of the JS dependency management\n // system, this creates problems where multiple versions of some package\n // could hold different keys for the same property.\n //\n // Therefore, we use Symbol.for which returns the same key for the same input.\n return Symbol.for(description);\n}\n\nclass BaseContext implements Context {\n private _currentContext!: Map;\n\n /**\n * Construct a new context which inherits values from an optional parent context.\n *\n * @param parentContext a context from which to inherit values\n */\n constructor(parentContext?: Map) {\n // for minification\n const self = this;\n\n self._currentContext = parentContext ? new Map(parentContext) : new Map();\n\n self.getValue = (key: symbol) => self._currentContext.get(key);\n\n self.setValue = (key: symbol, value: unknown): Context => {\n const context = new BaseContext(self._currentContext);\n context._currentContext.set(key, value);\n return context;\n };\n\n self.deleteValue = (key: symbol): Context => {\n const context = new BaseContext(self._currentContext);\n context._currentContext.delete(key);\n return context;\n };\n }\n\n /**\n * Get a value from the context.\n *\n * @param key key which identifies a context value\n */\n public getValue!: (key: symbol) => unknown;\n\n /**\n * Create a new context which inherits from this context and has\n * the given key set to the given value.\n *\n * @param key context key for which to set the value\n * @param value value to set for the given key\n */\n public setValue!: (key: symbol, value: unknown) => Context;\n\n /**\n * Return a new context which inherits from this context but does\n * not contain a value for the given key.\n *\n * @param key context key for which to clear a value\n */\n public deleteValue!: (key: symbol) => Context;\n}\n\n/** The root context is used as the default parent context when there is no active context */\nexport const ROOT_CONTEXT: Context = new BaseContext();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/context/types.d.ts b/node_modules/@opentelemetry/api/build/src/context/types.d.ts new file mode 100644 index 0000000..7e86632 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/context/types.d.ts @@ -0,0 +1,52 @@ +export interface Context { + /** + * Get a value from the context. + * + * @param key key which identifies a context value + */ + getValue(key: symbol): unknown; + /** + * Create a new context which inherits from this context and has + * the given key set to the given value. + * + * @param key context key for which to set the value + * @param value value to set for the given key + */ + setValue(key: symbol, value: unknown): Context; + /** + * Return a new context which inherits from this context but does + * not contain a value for the given key. + * + * @param key context key for which to clear a value + */ + deleteValue(key: symbol): Context; +} +export interface ContextManager { + /** + * Get the current active context + */ + active(): Context; + /** + * Run the fn callback with object set as the current active context + * @param context Any object to set as the current active context + * @param fn A callback to be immediately run within a specific context + * @param thisArg optional receiver to be used for calling fn + * @param args optional arguments forwarded to fn + */ + with ReturnType>(context: Context, fn: F, thisArg?: ThisParameterType, ...args: A): ReturnType; + /** + * Bind an object as the current context (or a specific one) + * @param [context] Optionally specify the context which you want to assign + * @param target Any object to which a context need to be set + */ + bind(context: Context, target: T): T; + /** + * Enable context management + */ + enable(): this; + /** + * Disable context management + */ + disable(): this; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/context/types.js b/node_modules/@opentelemetry/api/build/src/context/types.js new file mode 100644 index 0000000..c428c6d --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/context/types.js @@ -0,0 +1,18 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/context/types.js.map b/node_modules/@opentelemetry/api/build/src/context/types.js.map new file mode 100644 index 0000000..8bde9ce --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/context/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/context/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Context {\n /**\n * Get a value from the context.\n *\n * @param key key which identifies a context value\n */\n getValue(key: symbol): unknown;\n\n /**\n * Create a new context which inherits from this context and has\n * the given key set to the given value.\n *\n * @param key context key for which to set the value\n * @param value value to set for the given key\n */\n setValue(key: symbol, value: unknown): Context;\n\n /**\n * Return a new context which inherits from this context but does\n * not contain a value for the given key.\n *\n * @param key context key for which to clear a value\n */\n deleteValue(key: symbol): Context;\n}\n\nexport interface ContextManager {\n /**\n * Get the current active context\n */\n active(): Context;\n\n /**\n * Run the fn callback with object set as the current active context\n * @param context Any object to set as the current active context\n * @param fn A callback to be immediately run within a specific context\n * @param thisArg optional receiver to be used for calling fn\n * @param args optional arguments forwarded to fn\n */\n with ReturnType>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType,\n ...args: A\n ): ReturnType;\n\n /**\n * Bind an object as the current context (or a specific one)\n * @param [context] Optionally specify the context which you want to assign\n * @param target Any object to which a context need to be set\n */\n bind(context: Context, target: T): T;\n\n /**\n * Enable context management\n */\n enable(): this;\n\n /**\n * Disable context management\n */\n disable(): this;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/diag-api.d.ts b/node_modules/@opentelemetry/api/build/src/diag-api.d.ts new file mode 100644 index 0000000..d82fdb1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/diag-api.d.ts @@ -0,0 +1,9 @@ +import { DiagAPI } from './api/diag'; +/** + * Entrypoint for Diag API. + * Defines Diagnostic handler used for internal diagnostic logging operations. + * The default provides a Noop DiagLogger implementation which may be changed via the + * diag.setLogger(logger: DiagLogger) function. + */ +export declare const diag: DiagAPI; +//# sourceMappingURL=diag-api.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/diag-api.js b/node_modules/@opentelemetry/api/build/src/diag-api.js new file mode 100644 index 0000000..cbf28db --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/diag-api.js @@ -0,0 +1,29 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.diag = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const diag_1 = require("./api/diag"); +/** + * Entrypoint for Diag API. + * Defines Diagnostic handler used for internal diagnostic logging operations. + * The default provides a Noop DiagLogger implementation which may be changed via the + * diag.setLogger(logger: DiagLogger) function. + */ +exports.diag = diag_1.DiagAPI.instance(); +//# sourceMappingURL=diag-api.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/diag-api.js.map b/node_modules/@opentelemetry/api/build/src/diag-api.js.map new file mode 100644 index 0000000..f87b0fb --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/diag-api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"diag-api.js","sourceRoot":"","sources":["../../src/diag-api.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,sEAAsE;AACtE,qCAAqC;AACrC,qCAAqC;AACrC;;;;;GAKG;AACU,QAAA,IAAI,GAAG,cAAO,CAAC,QAAQ,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { DiagAPI } from './api/diag';\n/**\n * Entrypoint for Diag API.\n * Defines Diagnostic handler used for internal diagnostic logging operations.\n * The default provides a Noop DiagLogger implementation which may be changed via the\n * diag.setLogger(logger: DiagLogger) function.\n */\nexport const diag = DiagAPI.instance();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.d.ts b/node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.d.ts new file mode 100644 index 0000000..f060950 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.d.ts @@ -0,0 +1,20 @@ +import { ComponentLoggerOptions, DiagLogger } from './types'; +/** + * Component Logger which is meant to be used as part of any component which + * will add automatically additional namespace in front of the log message. + * It will then forward all message to global diag logger + * @example + * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' }); + * cLogger.debug('test'); + * // @opentelemetry/instrumentation-http test + */ +export declare class DiagComponentLogger implements DiagLogger { + private _namespace; + constructor(props: ComponentLoggerOptions); + debug(...args: any[]): void; + error(...args: any[]): void; + info(...args: any[]): void; + warn(...args: any[]): void; + verbose(...args: any[]): void; +} +//# sourceMappingURL=ComponentLogger.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js b/node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js new file mode 100644 index 0000000..579b7e6 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js @@ -0,0 +1,59 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DiagComponentLogger = void 0; +const global_utils_1 = require("../internal/global-utils"); +/** + * Component Logger which is meant to be used as part of any component which + * will add automatically additional namespace in front of the log message. + * It will then forward all message to global diag logger + * @example + * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' }); + * cLogger.debug('test'); + * // @opentelemetry/instrumentation-http test + */ +class DiagComponentLogger { + constructor(props) { + this._namespace = props.namespace || 'DiagComponentLogger'; + } + debug(...args) { + return logProxy('debug', this._namespace, args); + } + error(...args) { + return logProxy('error', this._namespace, args); + } + info(...args) { + return logProxy('info', this._namespace, args); + } + warn(...args) { + return logProxy('warn', this._namespace, args); + } + verbose(...args) { + return logProxy('verbose', this._namespace, args); + } +} +exports.DiagComponentLogger = DiagComponentLogger; +function logProxy(funcName, namespace, args) { + const logger = (0, global_utils_1.getGlobal)('diag'); + // shortcut if logger not set + if (!logger) { + return; + } + args.unshift(namespace); + return logger[funcName](...args); +} +//# sourceMappingURL=ComponentLogger.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js.map b/node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js.map new file mode 100644 index 0000000..c1b8504 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ComponentLogger.js","sourceRoot":"","sources":["../../../src/diag/ComponentLogger.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,2DAAqD;AAGrD;;;;;;;;GAQG;AACH,MAAa,mBAAmB;IAG9B,YAAY,KAA6B;QACvC,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC,SAAS,IAAI,qBAAqB,CAAC;IAC7D,CAAC;IAEM,KAAK,CAAC,GAAG,IAAW;QACzB,OAAO,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IAClD,CAAC;IAEM,KAAK,CAAC,GAAG,IAAW;QACzB,OAAO,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IAClD,CAAC;IAEM,IAAI,CAAC,GAAG,IAAW;QACxB,OAAO,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IACjD,CAAC;IAEM,IAAI,CAAC,GAAG,IAAW;QACxB,OAAO,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IACjD,CAAC;IAEM,OAAO,CAAC,GAAG,IAAW;QAC3B,OAAO,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IACpD,CAAC;CACF;AA1BD,kDA0BC;AAED,SAAS,QAAQ,CACf,QAA0B,EAC1B,SAAiB,EACjB,IAAS;IAET,MAAM,MAAM,GAAG,IAAA,wBAAS,EAAC,MAAM,CAAC,CAAC;IACjC,6BAA6B;IAC7B,IAAI,CAAC,MAAM,EAAE;QACX,OAAO;KACR;IAED,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACxB,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC,GAAI,IAAoC,CAAC,CAAC;AACpE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobal } from '../internal/global-utils';\nimport { ComponentLoggerOptions, DiagLogger, DiagLogFunction } from './types';\n\n/**\n * Component Logger which is meant to be used as part of any component which\n * will add automatically additional namespace in front of the log message.\n * It will then forward all message to global diag logger\n * @example\n * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });\n * cLogger.debug('test');\n * // @opentelemetry/instrumentation-http test\n */\nexport class DiagComponentLogger implements DiagLogger {\n private _namespace: string;\n\n constructor(props: ComponentLoggerOptions) {\n this._namespace = props.namespace || 'DiagComponentLogger';\n }\n\n public debug(...args: any[]): void {\n return logProxy('debug', this._namespace, args);\n }\n\n public error(...args: any[]): void {\n return logProxy('error', this._namespace, args);\n }\n\n public info(...args: any[]): void {\n return logProxy('info', this._namespace, args);\n }\n\n public warn(...args: any[]): void {\n return logProxy('warn', this._namespace, args);\n }\n\n public verbose(...args: any[]): void {\n return logProxy('verbose', this._namespace, args);\n }\n}\n\nfunction logProxy(\n funcName: keyof DiagLogger,\n namespace: string,\n args: any\n): void {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) {\n return;\n }\n\n args.unshift(namespace);\n return logger[funcName](...(args as Parameters));\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/diag/consoleLogger.d.ts b/node_modules/@opentelemetry/api/build/src/diag/consoleLogger.d.ts new file mode 100644 index 0000000..fa3db1e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/diag/consoleLogger.d.ts @@ -0,0 +1,38 @@ +import { DiagLogger, DiagLogFunction } from './types'; +/** + * A simple Immutable Console based diagnostic logger which will output any messages to the Console. + * If you want to limit the amount of logging to a specific level or lower use the + * {@link createLogLevelDiagLogger} + */ +export declare class DiagConsoleLogger implements DiagLogger { + constructor(); + /** Log an error scenario that was not expected and caused the requested operation to fail. */ + error: DiagLogFunction; + /** + * Log a warning scenario to inform the developer of an issues that should be investigated. + * The requested operation may or may not have succeeded or completed. + */ + warn: DiagLogFunction; + /** + * Log a general informational message, this should not affect functionality. + * This is also the default logging level so this should NOT be used for logging + * debugging level information. + */ + info: DiagLogFunction; + /** + * Log a general debug message that can be useful for identifying a failure. + * Information logged at this level may include diagnostic details that would + * help identify a failure scenario. Useful scenarios would be to log the execution + * order of async operations + */ + debug: DiagLogFunction; + /** + * Log a detailed (verbose) trace level logging that can be used to identify failures + * where debug level logging would be insufficient, this level of tracing can include + * input and output parameters and as such may include PII information passing through + * the API. As such it is recommended that this level of tracing should not be enabled + * in a production environment. + */ + verbose: DiagLogFunction; +} +//# sourceMappingURL=consoleLogger.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js b/node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js new file mode 100644 index 0000000..1962275 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js @@ -0,0 +1,57 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DiagConsoleLogger = void 0; +const consoleMap = [ + { n: 'error', c: 'error' }, + { n: 'warn', c: 'warn' }, + { n: 'info', c: 'info' }, + { n: 'debug', c: 'debug' }, + { n: 'verbose', c: 'trace' }, +]; +/** + * A simple Immutable Console based diagnostic logger which will output any messages to the Console. + * If you want to limit the amount of logging to a specific level or lower use the + * {@link createLogLevelDiagLogger} + */ +class DiagConsoleLogger { + constructor() { + function _consoleFunc(funcName) { + return function (...args) { + if (console) { + // Some environments only expose the console when the F12 developer console is open + // eslint-disable-next-line no-console + let theFunc = console[funcName]; + if (typeof theFunc !== 'function') { + // Not all environments support all functions + // eslint-disable-next-line no-console + theFunc = console.log; + } + // One last final check + if (typeof theFunc === 'function') { + return theFunc.apply(console, args); + } + } + }; + } + for (let i = 0; i < consoleMap.length; i++) { + this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); + } + } +} +exports.DiagConsoleLogger = DiagConsoleLogger; +//# sourceMappingURL=consoleLogger.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js.map b/node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js.map new file mode 100644 index 0000000..d57fe77 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"consoleLogger.js","sourceRoot":"","sources":["../../../src/diag/consoleLogger.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAKH,MAAM,UAAU,GAAiD;IAC/D,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO,EAAE;IAC1B,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE;IACxB,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE;IACxB,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO,EAAE;IAC1B,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,OAAO,EAAE;CAC7B,CAAC;AAEF;;;;GAIG;AACH,MAAa,iBAAiB;IAC5B;QACE,SAAS,YAAY,CAAC,QAAwB;YAC5C,OAAO,UAAU,GAAG,IAAI;gBACtB,IAAI,OAAO,EAAE;oBACX,mFAAmF;oBACnF,sCAAsC;oBACtC,IAAI,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;oBAChC,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE;wBACjC,6CAA6C;wBAC7C,sCAAsC;wBACtC,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC;qBACvB;oBAED,uBAAuB;oBACvB,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE;wBACjC,OAAO,OAAO,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;qBACrC;iBACF;YACH,CAAC,CAAC;QACJ,CAAC;QAED,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,UAAU,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YAC1C,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,YAAY,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;SACvD;IACH,CAAC;CAkCF;AA3DD,8CA2DC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogger, DiagLogFunction } from './types';\n\ntype ConsoleMapKeys = 'error' | 'warn' | 'info' | 'debug' | 'trace';\nconst consoleMap: { n: keyof DiagLogger; c: ConsoleMapKeys }[] = [\n { n: 'error', c: 'error' },\n { n: 'warn', c: 'warn' },\n { n: 'info', c: 'info' },\n { n: 'debug', c: 'debug' },\n { n: 'verbose', c: 'trace' },\n];\n\n/**\n * A simple Immutable Console based diagnostic logger which will output any messages to the Console.\n * If you want to limit the amount of logging to a specific level or lower use the\n * {@link createLogLevelDiagLogger}\n */\nexport class DiagConsoleLogger implements DiagLogger {\n constructor() {\n function _consoleFunc(funcName: ConsoleMapKeys): DiagLogFunction {\n return function (...args) {\n if (console) {\n // Some environments only expose the console when the F12 developer console is open\n // eslint-disable-next-line no-console\n let theFunc = console[funcName];\n if (typeof theFunc !== 'function') {\n // Not all environments support all functions\n // eslint-disable-next-line no-console\n theFunc = console.log;\n }\n\n // One last final check\n if (typeof theFunc === 'function') {\n return theFunc.apply(console, args);\n }\n }\n };\n }\n\n for (let i = 0; i < consoleMap.length; i++) {\n this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c);\n }\n }\n\n /** Log an error scenario that was not expected and caused the requested operation to fail. */\n public error!: DiagLogFunction;\n\n /**\n * Log a warning scenario to inform the developer of an issues that should be investigated.\n * The requested operation may or may not have succeeded or completed.\n */\n public warn!: DiagLogFunction;\n\n /**\n * Log a general informational message, this should not affect functionality.\n * This is also the default logging level so this should NOT be used for logging\n * debugging level information.\n */\n public info!: DiagLogFunction;\n\n /**\n * Log a general debug message that can be useful for identifying a failure.\n * Information logged at this level may include diagnostic details that would\n * help identify a failure scenario. Useful scenarios would be to log the execution\n * order of async operations\n */\n public debug!: DiagLogFunction;\n\n /**\n * Log a detailed (verbose) trace level logging that can be used to identify failures\n * where debug level logging would be insufficient, this level of tracing can include\n * input and output parameters and as such may include PII information passing through\n * the API. As such it is recommended that this level of tracing should not be enabled\n * in a production environment.\n */\n public verbose!: DiagLogFunction;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.d.ts b/node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.d.ts new file mode 100644 index 0000000..890b9f1 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.d.ts @@ -0,0 +1,3 @@ +import { DiagLogger, DiagLogLevel } from '../types'; +export declare function createLogLevelDiagLogger(maxLevel: DiagLogLevel, logger: DiagLogger): DiagLogger; +//# sourceMappingURL=logLevelLogger.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js b/node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js new file mode 100644 index 0000000..ee1702e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js @@ -0,0 +1,45 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createLogLevelDiagLogger = void 0; +const types_1 = require("../types"); +function createLogLevelDiagLogger(maxLevel, logger) { + if (maxLevel < types_1.DiagLogLevel.NONE) { + maxLevel = types_1.DiagLogLevel.NONE; + } + else if (maxLevel > types_1.DiagLogLevel.ALL) { + maxLevel = types_1.DiagLogLevel.ALL; + } + // In case the logger is null or undefined + logger = logger || {}; + function _filterFunc(funcName, theLevel) { + const theFunc = logger[funcName]; + if (typeof theFunc === 'function' && maxLevel >= theLevel) { + return theFunc.bind(logger); + } + return function () { }; + } + return { + error: _filterFunc('error', types_1.DiagLogLevel.ERROR), + warn: _filterFunc('warn', types_1.DiagLogLevel.WARN), + info: _filterFunc('info', types_1.DiagLogLevel.INFO), + debug: _filterFunc('debug', types_1.DiagLogLevel.DEBUG), + verbose: _filterFunc('verbose', types_1.DiagLogLevel.VERBOSE), + }; +} +exports.createLogLevelDiagLogger = createLogLevelDiagLogger; +//# sourceMappingURL=logLevelLogger.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js.map b/node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js.map new file mode 100644 index 0000000..1148835 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"logLevelLogger.js","sourceRoot":"","sources":["../../../../src/diag/internal/logLevelLogger.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,oCAAqE;AAErE,SAAgB,wBAAwB,CACtC,QAAsB,EACtB,MAAkB;IAElB,IAAI,QAAQ,GAAG,oBAAY,CAAC,IAAI,EAAE;QAChC,QAAQ,GAAG,oBAAY,CAAC,IAAI,CAAC;KAC9B;SAAM,IAAI,QAAQ,GAAG,oBAAY,CAAC,GAAG,EAAE;QACtC,QAAQ,GAAG,oBAAY,CAAC,GAAG,CAAC;KAC7B;IAED,0CAA0C;IAC1C,MAAM,GAAG,MAAM,IAAI,EAAE,CAAC;IAEtB,SAAS,WAAW,CAClB,QAA0B,EAC1B,QAAsB;QAEtB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;QAEjC,IAAI,OAAO,OAAO,KAAK,UAAU,IAAI,QAAQ,IAAI,QAAQ,EAAE;YACzD,OAAO,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;SAC7B;QACD,OAAO,cAAa,CAAC,CAAC;IACxB,CAAC;IAED,OAAO;QACL,KAAK,EAAE,WAAW,CAAC,OAAO,EAAE,oBAAY,CAAC,KAAK,CAAC;QAC/C,IAAI,EAAE,WAAW,CAAC,MAAM,EAAE,oBAAY,CAAC,IAAI,CAAC;QAC5C,IAAI,EAAE,WAAW,CAAC,MAAM,EAAE,oBAAY,CAAC,IAAI,CAAC;QAC5C,KAAK,EAAE,WAAW,CAAC,OAAO,EAAE,oBAAY,CAAC,KAAK,CAAC;QAC/C,OAAO,EAAE,WAAW,CAAC,SAAS,EAAE,oBAAY,CAAC,OAAO,CAAC;KACtD,CAAC;AACJ,CAAC;AAhCD,4DAgCC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogFunction, DiagLogger, DiagLogLevel } from '../types';\n\nexport function createLogLevelDiagLogger(\n maxLevel: DiagLogLevel,\n logger: DiagLogger\n): DiagLogger {\n if (maxLevel < DiagLogLevel.NONE) {\n maxLevel = DiagLogLevel.NONE;\n } else if (maxLevel > DiagLogLevel.ALL) {\n maxLevel = DiagLogLevel.ALL;\n }\n\n // In case the logger is null or undefined\n logger = logger || {};\n\n function _filterFunc(\n funcName: keyof DiagLogger,\n theLevel: DiagLogLevel\n ): DiagLogFunction {\n const theFunc = logger[funcName];\n\n if (typeof theFunc === 'function' && maxLevel >= theLevel) {\n return theFunc.bind(logger);\n }\n return function () {};\n }\n\n return {\n error: _filterFunc('error', DiagLogLevel.ERROR),\n warn: _filterFunc('warn', DiagLogLevel.WARN),\n info: _filterFunc('info', DiagLogLevel.INFO),\n debug: _filterFunc('debug', DiagLogLevel.DEBUG),\n verbose: _filterFunc('verbose', DiagLogLevel.VERBOSE),\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/diag/internal/noopLogger.d.ts b/node_modules/@opentelemetry/api/build/src/diag/internal/noopLogger.d.ts new file mode 100644 index 0000000..ac71ee3 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/diag/internal/noopLogger.d.ts @@ -0,0 +1,8 @@ +import { DiagLogger } from '../types'; +/** + * Returns a No-Op Diagnostic logger where all messages do nothing. + * @implements {@link DiagLogger} + * @returns {DiagLogger} + */ +export declare function createNoopDiagLogger(): DiagLogger; +//# sourceMappingURL=noopLogger.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/diag/internal/noopLogger.js b/node_modules/@opentelemetry/api/build/src/diag/internal/noopLogger.js new file mode 100644 index 0000000..4091631 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/diag/internal/noopLogger.js @@ -0,0 +1,35 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createNoopDiagLogger = void 0; +function noopLogFunction() { } +/** + * Returns a No-Op Diagnostic logger where all messages do nothing. + * @implements {@link DiagLogger} + * @returns {DiagLogger} + */ +function createNoopDiagLogger() { + return { + verbose: noopLogFunction, + debug: noopLogFunction, + info: noopLogFunction, + warn: noopLogFunction, + error: noopLogFunction, + }; +} +exports.createNoopDiagLogger = createNoopDiagLogger; +//# sourceMappingURL=noopLogger.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/diag/internal/noopLogger.js.map b/node_modules/@opentelemetry/api/build/src/diag/internal/noopLogger.js.map new file mode 100644 index 0000000..20e0e81 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/diag/internal/noopLogger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"noopLogger.js","sourceRoot":"","sources":["../../../../src/diag/internal/noopLogger.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAIH,SAAS,eAAe,KAAI,CAAC;AAE7B;;;;GAIG;AACH,SAAgB,oBAAoB;IAClC,OAAO;QACL,OAAO,EAAE,eAAe;QACxB,KAAK,EAAE,eAAe;QACtB,IAAI,EAAE,eAAe;QACrB,IAAI,EAAE,eAAe;QACrB,KAAK,EAAE,eAAe;KACvB,CAAC;AACJ,CAAC;AARD,oDAQC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogger } from '../types';\n\nfunction noopLogFunction() {}\n\n/**\n * Returns a No-Op Diagnostic logger where all messages do nothing.\n * @implements {@link DiagLogger}\n * @returns {DiagLogger}\n */\nexport function createNoopDiagLogger(): DiagLogger {\n return {\n verbose: noopLogFunction,\n debug: noopLogFunction,\n info: noopLogFunction,\n warn: noopLogFunction,\n error: noopLogFunction,\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/diag/types.d.ts b/node_modules/@opentelemetry/api/build/src/diag/types.d.ts new file mode 100644 index 0000000..e992cc5 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/diag/types.d.ts @@ -0,0 +1,100 @@ +export declare type DiagLogFunction = (message: string, ...args: unknown[]) => void; +/** + * Defines an internal diagnostic logger interface which is used to log internal diagnostic + * messages, you can set the default diagnostic logger via the {@link DiagAPI} setLogger function. + * API provided implementations include :- + * - a No-Op {@link createNoopDiagLogger} + * - a {@link DiagLogLevel} filtering wrapper {@link createLogLevelDiagLogger} + * - a general Console {@link DiagConsoleLogger} version. + */ +export interface DiagLogger { + /** Log an error scenario that was not expected and caused the requested operation to fail. */ + error: DiagLogFunction; + /** + * Log a warning scenario to inform the developer of an issues that should be investigated. + * The requested operation may or may not have succeeded or completed. + */ + warn: DiagLogFunction; + /** + * Log a general informational message, this should not affect functionality. + * This is also the default logging level so this should NOT be used for logging + * debugging level information. + */ + info: DiagLogFunction; + /** + * Log a general debug message that can be useful for identifying a failure. + * Information logged at this level may include diagnostic details that would + * help identify a failure scenario. + * For example: Logging the order of execution of async operations. + */ + debug: DiagLogFunction; + /** + * Log a detailed (verbose) trace level logging that can be used to identify failures + * where debug level logging would be insufficient, this level of tracing can include + * input and output parameters and as such may include PII information passing through + * the API. As such it is recommended that this level of tracing should not be enabled + * in a production environment. + */ + verbose: DiagLogFunction; +} +/** + * Defines the available internal logging levels for the diagnostic logger, the numeric values + * of the levels are defined to match the original values from the initial LogLevel to avoid + * compatibility/migration issues for any implementation that assume the numeric ordering. + */ +export declare enum DiagLogLevel { + /** Diagnostic Logging level setting to disable all logging (except and forced logs) */ + NONE = 0, + /** Identifies an error scenario */ + ERROR = 30, + /** Identifies a warning scenario */ + WARN = 50, + /** General informational log message */ + INFO = 60, + /** General debug log message */ + DEBUG = 70, + /** + * Detailed trace level logging should only be used for development, should only be set + * in a development environment. + */ + VERBOSE = 80, + /** Used to set the logging level to include all logging */ + ALL = 9999 +} +/** + * Defines options for ComponentLogger + */ +export interface ComponentLoggerOptions { + namespace: string; +} +export interface DiagLoggerOptions { + /** + * The {@link DiagLogLevel} used to filter logs sent to the logger. + * + * @defaultValue DiagLogLevel.INFO + */ + logLevel?: DiagLogLevel; + /** + * Setting this value to `true` will suppress the warning message normally emitted when registering a logger when another logger is already registered. + */ + suppressOverrideMessage?: boolean; +} +export interface DiagLoggerApi { + /** + * Set the global DiagLogger and DiagLogLevel. + * If a global diag logger is already set, this will override it. + * + * @param logger - The {@link DiagLogger} instance to set as the default logger. + * @param options - A {@link DiagLoggerOptions} object. If not provided, default values will be set. + * @returns `true` if the logger was successfully registered, else `false` + */ + setLogger(logger: DiagLogger, options?: DiagLoggerOptions): boolean; + /** + * + * @param logger - The {@link DiagLogger} instance to set as the default logger. + * @param logLevel - The {@link DiagLogLevel} used to filter logs sent to the logger. If not provided it will default to {@link DiagLogLevel.INFO}. + * @returns `true` if the logger was successfully registered, else `false` + */ + setLogger(logger: DiagLogger, logLevel?: DiagLogLevel): boolean; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/diag/types.js b/node_modules/@opentelemetry/api/build/src/diag/types.js new file mode 100644 index 0000000..c195e45 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/diag/types.js @@ -0,0 +1,44 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DiagLogLevel = void 0; +/** + * Defines the available internal logging levels for the diagnostic logger, the numeric values + * of the levels are defined to match the original values from the initial LogLevel to avoid + * compatibility/migration issues for any implementation that assume the numeric ordering. + */ +var DiagLogLevel; +(function (DiagLogLevel) { + /** Diagnostic Logging level setting to disable all logging (except and forced logs) */ + DiagLogLevel[DiagLogLevel["NONE"] = 0] = "NONE"; + /** Identifies an error scenario */ + DiagLogLevel[DiagLogLevel["ERROR"] = 30] = "ERROR"; + /** Identifies a warning scenario */ + DiagLogLevel[DiagLogLevel["WARN"] = 50] = "WARN"; + /** General informational log message */ + DiagLogLevel[DiagLogLevel["INFO"] = 60] = "INFO"; + /** General debug log message */ + DiagLogLevel[DiagLogLevel["DEBUG"] = 70] = "DEBUG"; + /** + * Detailed trace level logging should only be used for development, should only be set + * in a development environment. + */ + DiagLogLevel[DiagLogLevel["VERBOSE"] = 80] = "VERBOSE"; + /** Used to set the logging level to include all logging */ + DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL"; +})(DiagLogLevel = exports.DiagLogLevel || (exports.DiagLogLevel = {})); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/diag/types.js.map b/node_modules/@opentelemetry/api/build/src/diag/types.js.map new file mode 100644 index 0000000..ee8afca --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/diag/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/diag/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AA+CH;;;;GAIG;AACH,IAAY,YAwBX;AAxBD,WAAY,YAAY;IACtB,uFAAuF;IACvF,+CAAQ,CAAA;IAER,mCAAmC;IACnC,kDAAU,CAAA;IAEV,oCAAoC;IACpC,gDAAS,CAAA;IAET,wCAAwC;IACxC,gDAAS,CAAA;IAET,gCAAgC;IAChC,kDAAU,CAAA;IAEV;;;OAGG;IACH,sDAAY,CAAA;IAEZ,2DAA2D;IAC3D,gDAAU,CAAA;AACZ,CAAC,EAxBW,YAAY,GAAZ,oBAAY,KAAZ,oBAAY,QAwBvB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type DiagLogFunction = (message: string, ...args: unknown[]) => void;\n\n/**\n * Defines an internal diagnostic logger interface which is used to log internal diagnostic\n * messages, you can set the default diagnostic logger via the {@link DiagAPI} setLogger function.\n * API provided implementations include :-\n * - a No-Op {@link createNoopDiagLogger}\n * - a {@link DiagLogLevel} filtering wrapper {@link createLogLevelDiagLogger}\n * - a general Console {@link DiagConsoleLogger} version.\n */\nexport interface DiagLogger {\n /** Log an error scenario that was not expected and caused the requested operation to fail. */\n error: DiagLogFunction;\n\n /**\n * Log a warning scenario to inform the developer of an issues that should be investigated.\n * The requested operation may or may not have succeeded or completed.\n */\n warn: DiagLogFunction;\n\n /**\n * Log a general informational message, this should not affect functionality.\n * This is also the default logging level so this should NOT be used for logging\n * debugging level information.\n */\n info: DiagLogFunction;\n\n /**\n * Log a general debug message that can be useful for identifying a failure.\n * Information logged at this level may include diagnostic details that would\n * help identify a failure scenario.\n * For example: Logging the order of execution of async operations.\n */\n debug: DiagLogFunction;\n\n /**\n * Log a detailed (verbose) trace level logging that can be used to identify failures\n * where debug level logging would be insufficient, this level of tracing can include\n * input and output parameters and as such may include PII information passing through\n * the API. As such it is recommended that this level of tracing should not be enabled\n * in a production environment.\n */\n verbose: DiagLogFunction;\n}\n\n/**\n * Defines the available internal logging levels for the diagnostic logger, the numeric values\n * of the levels are defined to match the original values from the initial LogLevel to avoid\n * compatibility/migration issues for any implementation that assume the numeric ordering.\n */\nexport enum DiagLogLevel {\n /** Diagnostic Logging level setting to disable all logging (except and forced logs) */\n NONE = 0,\n\n /** Identifies an error scenario */\n ERROR = 30,\n\n /** Identifies a warning scenario */\n WARN = 50,\n\n /** General informational log message */\n INFO = 60,\n\n /** General debug log message */\n DEBUG = 70,\n\n /**\n * Detailed trace level logging should only be used for development, should only be set\n * in a development environment.\n */\n VERBOSE = 80,\n\n /** Used to set the logging level to include all logging */\n ALL = 9999,\n}\n\n/**\n * Defines options for ComponentLogger\n */\nexport interface ComponentLoggerOptions {\n namespace: string;\n}\n\nexport interface DiagLoggerOptions {\n /**\n * The {@link DiagLogLevel} used to filter logs sent to the logger.\n *\n * @defaultValue DiagLogLevel.INFO\n */\n logLevel?: DiagLogLevel;\n\n /**\n * Setting this value to `true` will suppress the warning message normally emitted when registering a logger when another logger is already registered.\n */\n suppressOverrideMessage?: boolean;\n}\n\nexport interface DiagLoggerApi {\n /**\n * Set the global DiagLogger and DiagLogLevel.\n * If a global diag logger is already set, this will override it.\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param options - A {@link DiagLoggerOptions} object. If not provided, default values will be set.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, options?: DiagLoggerOptions): boolean;\n\n /**\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param logLevel - The {@link DiagLogLevel} used to filter logs sent to the logger. If not provided it will default to {@link DiagLogLevel.INFO}.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, logLevel?: DiagLogLevel): boolean;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/experimental/index.d.ts b/node_modules/@opentelemetry/api/build/src/experimental/index.d.ts new file mode 100644 index 0000000..bec3965 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/experimental/index.d.ts @@ -0,0 +1,3 @@ +export { wrapTracer, SugaredTracer } from './trace/SugaredTracer'; +export { SugaredSpanOptions } from './trace/SugaredOptions'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/experimental/index.js b/node_modules/@opentelemetry/api/build/src/experimental/index.js new file mode 100644 index 0000000..bd611ec --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/experimental/index.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SugaredTracer = exports.wrapTracer = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var SugaredTracer_1 = require("./trace/SugaredTracer"); +Object.defineProperty(exports, "wrapTracer", { enumerable: true, get: function () { return SugaredTracer_1.wrapTracer; } }); +Object.defineProperty(exports, "SugaredTracer", { enumerable: true, get: function () { return SugaredTracer_1.SugaredTracer; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/experimental/index.js.map b/node_modules/@opentelemetry/api/build/src/experimental/index.js.map new file mode 100644 index 0000000..f0ed983 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/experimental/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/experimental/index.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,uDAAkE;AAAzD,2GAAA,UAAU,OAAA;AAAE,8GAAA,aAAa,OAAA","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport { wrapTracer, SugaredTracer } from './trace/SugaredTracer';\nexport { SugaredSpanOptions } from './trace/SugaredOptions';\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredOptions.d.ts b/node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredOptions.d.ts new file mode 100644 index 0000000..89040af --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredOptions.d.ts @@ -0,0 +1,13 @@ +import { Span, SpanOptions } from '../../'; +/** + * Options needed for span creation + */ +export interface SugaredSpanOptions extends SpanOptions { + /** + * function to overwrite default exception behavior to record the exception. No exceptions should be thrown in the function. + * @param e Error which triggered this exception + * @param span current span from context + */ + onException?: (e: Error, span: Span) => void; +} +//# sourceMappingURL=SugaredOptions.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredOptions.js b/node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredOptions.js new file mode 100644 index 0000000..a18d65b --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredOptions.js @@ -0,0 +1,18 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SugaredOptions.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredOptions.js.map b/node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredOptions.js.map new file mode 100644 index 0000000..19ded54 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredOptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SugaredOptions.js","sourceRoot":"","sources":["../../../../src/experimental/trace/SugaredOptions.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Span, SpanOptions } from '../../';\n\n/**\n * Options needed for span creation\n */\nexport interface SugaredSpanOptions extends SpanOptions {\n /**\n * function to overwrite default exception behavior to record the exception. No exceptions should be thrown in the function.\n * @param e Error which triggered this exception\n * @param span current span from context\n */\n onException?: (e: Error, span: Span) => void;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredTracer.d.ts b/node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredTracer.d.ts new file mode 100644 index 0000000..1ba7da9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredTracer.d.ts @@ -0,0 +1,64 @@ +import { SugaredSpanOptions } from './SugaredOptions'; +import { Context, Span, Tracer } from '../../'; +/** + * return a new SugaredTracer created from the supplied one + * @param tracer + */ +export declare function wrapTracer(tracer: Tracer): SugaredTracer; +export declare class SugaredTracer implements Tracer { + private readonly _tracer; + constructor(tracer: Tracer); + startActiveSpan: Tracer['startActiveSpan']; + startSpan: Tracer['startSpan']; + /** + * Starts a new {@link Span} and calls the given function passing it the + * created span as first argument. + * Additionally, the new span gets set in context and this context is activated + * for the duration of the function call. + * The span will be closed after the function has executed. + * If an exception occurs, it is recorded, the status is set to ERROR and the exception is rethrown. + * + * @param name The name of the span + * @param [options] SugaredSpanOptions used for span creation + * @param [context] Context to use to extract parent + * @param fn function called in the context of the span and receives the newly created span as an argument + * @returns return value of fn + * @example + * const something = tracer.withActiveSpan('op', span => { + * // do some work + * }); + * @example + * const something = await tracer.withActiveSpan('op', span => { + * // do some async work + * }); + */ + withActiveSpan ReturnType>(name: string, fn: F): ReturnType; + withActiveSpan ReturnType>(name: string, options: SugaredSpanOptions, fn: F): ReturnType; + withActiveSpan ReturnType>(name: string, options: SugaredSpanOptions, context: Context, fn: F): ReturnType; + /** + * Starts a new {@link Span} and ends it after execution of fn without setting it on context. + * The span will be closed after the function has executed. + * If an exception occurs, it is recorded, the status is et to ERROR and rethrown. + * + * This method does NOT modify the current Context. + * + * @param name The name of the span + * @param [options] SugaredSpanOptions used for span creation + * @param [context] Context to use to extract parent + * @param fn function called in the context of the span and receives the newly created span as an argument + * @returns Span The newly created span + * @example + * const something = tracer.withSpan('op', span => { + * // do some work + * }); + * @example + * const something = await tracer.withSpan('op', span => { + * // do some async work + * }); + */ + withSpan ReturnType>(name: string, fn: F): ReturnType; + withSpan ReturnType>(name: string, options: SugaredSpanOptions, fn: F): ReturnType; + withSpan ReturnType>(name: string, options: SugaredSpanOptions, context: Context, fn: F): ReturnType; + withSpan ReturnType>(name: string, options: SugaredSpanOptions, context: Context, fn: F): ReturnType; +} +//# sourceMappingURL=SugaredTracer.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredTracer.js b/node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredTracer.js new file mode 100644 index 0000000..aae6249 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredTracer.js @@ -0,0 +1,93 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SugaredTracer = exports.wrapTracer = void 0; +const __1 = require("../../"); +const defaultOnException = (e, span) => { + span.recordException(e); + span.setStatus({ + code: __1.SpanStatusCode.ERROR, + }); +}; +/** + * return a new SugaredTracer created from the supplied one + * @param tracer + */ +function wrapTracer(tracer) { + return new SugaredTracer(tracer); +} +exports.wrapTracer = wrapTracer; +class SugaredTracer { + constructor(tracer) { + this._tracer = tracer; + this.startSpan = tracer.startSpan.bind(this._tracer); + this.startActiveSpan = tracer.startActiveSpan.bind(this._tracer); + } + withActiveSpan(name, arg2, arg3, arg4) { + const { opts, ctx, fn } = massageParams(arg2, arg3, arg4); + return this._tracer.startActiveSpan(name, opts, ctx, (span) => handleFn(span, opts, fn)); + } + withSpan(name, arg2, arg3, arg4) { + const { opts, ctx, fn } = massageParams(arg2, arg3, arg4); + const span = this._tracer.startSpan(name, opts, ctx); + return handleFn(span, opts, fn); + } +} +exports.SugaredTracer = SugaredTracer; +/** + * Massages parameters of withSpan and withActiveSpan to allow signature overwrites + * @param arg + * @param arg2 + * @param arg3 + */ +function massageParams(arg, arg2, arg3) { + let opts; + let ctx; + let fn; + if (!arg2 && !arg3) { + fn = arg; + } + else if (!arg3) { + opts = arg; + fn = arg2; + } + else { + opts = arg; + ctx = arg2; + fn = arg3; + } + opts = opts !== null && opts !== void 0 ? opts : {}; + ctx = ctx !== null && ctx !== void 0 ? ctx : __1.context.active(); + return { opts, ctx, fn }; +} +/** + * Executes fn, returns results and runs onException in the case of exception to allow overwriting of error handling + * @param span + * @param opts + * @param fn + */ +function handleFn(span, opts, fn) { + var _a; + const onException = (_a = opts.onException) !== null && _a !== void 0 ? _a : defaultOnException; + const errorHandler = (e) => { + onException(e, span); + span.end(); + throw e; + }; + try { + const ret = fn(span); + // if fn is an async function, attach a recordException and spanEnd callback to the promise + if (typeof (ret === null || ret === void 0 ? void 0 : ret.then) === 'function') { + return ret.then(val => { + span.end(); + return val; + }, errorHandler); + } + span.end(); + return ret; + } + catch (e) { + // add throw to signal the compiler that this will throw in the inner scope + throw errorHandler(e); + } +} +//# sourceMappingURL=SugaredTracer.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredTracer.js.map b/node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredTracer.js.map new file mode 100644 index 0000000..b7abda9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/experimental/trace/SugaredTracer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SugaredTracer.js","sourceRoot":"","sources":["../../../../src/experimental/trace/SugaredTracer.ts"],"names":[],"mappings":";;;AAgBA,8BAAwE;AAExE,MAAM,kBAAkB,GAAG,CAAC,CAAQ,EAAE,IAAU,EAAE,EAAE;IAClD,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC;IACxB,IAAI,CAAC,SAAS,CAAC;QACb,IAAI,EAAE,kBAAc,CAAC,KAAK;KAC3B,CAAC,CAAC;AACL,CAAC,CAAC;AAEF;;;GAGG;AACH,SAAgB,UAAU,CAAC,MAAc;IACvC,OAAO,IAAI,aAAa,CAAC,MAAM,CAAC,CAAC;AACnC,CAAC;AAFD,gCAEC;AAED,MAAa,aAAa;IAGxB,YAAY,MAAc;QACxB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAA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,GAAG,GAAG,IAAe,CAAC;QACtB,EAAE,GAAG,IAAS,CAAC;KAChB;IACD,IAAI,GAAG,IAAI,aAAJ,IAAI,cAAJ,IAAI,GAAI,EAAE,CAAC;IAClB,GAAG,GAAG,GAAG,aAAH,GAAG,cAAH,GAAG,GAAI,WAAO,CAAC,MAAM,EAAE,CAAC;IAE9B,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC;AAC3B,CAAC;AAED;;;;;GAKG;AACH,SAAS,QAAQ,CACf,IAAU,EACV,IAAwB,EACxB,EAAK;;IAEL,MAAM,WAAW,GAAG,MAAA,IAAI,CAAC,WAAW,mCAAI,kBAAkB,CAAC;IAC3D,MAAM,YAAY,GAAG,CAAC,CAAQ,EAAE,EAAE;QAChC,WAAW,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;QACrB,IAAI,CAAC,GAAG,EAAE,CAAC;QACX,MAAM,CAAC,CAAC;IACV,CAAC,CAAC;IAEF,IAAI;QACF,MAAM,GAAG,GAAG,EAAE,CAAC,IAAI,CAA2B,CAAC;QAC/C,2FAA2F;QAC3F,IAAI,OAAO,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,IAAI,CAAA,KAAK,UAAU,EAAE;YACnC,OAAO,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;gBACpB,IAAI,CAAC,GAAG,EAAE,CAAC;gBACX,OAAO,GAAG,CAAC;YACb,CAAC,EAAE,YAAY,CAAkB,CAAC;SACnC;QACD,IAAI,CAAC,GAAG,EAAE,CAAC;QACX,OAAO,GAAoB,CAAC;KAC7B;IAAC,OAAO,CAAC,EAAE;QACV,2EAA2E;QAC3E,MAAM,YAAY,CAAC,CAAC,CAAC,CAAC;KACvB;AACH,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { SugaredSpanOptions } from './SugaredOptions';\nimport { context, Context, Span, SpanStatusCode, Tracer } from '../../';\n\nconst defaultOnException = (e: Error, span: Span) => {\n span.recordException(e);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n });\n};\n\n/**\n * return a new SugaredTracer created from the supplied one\n * @param tracer\n */\nexport function wrapTracer(tracer: Tracer): SugaredTracer {\n return new SugaredTracer(tracer);\n}\n\nexport class SugaredTracer implements Tracer {\n private readonly _tracer: Tracer;\n\n constructor(tracer: Tracer) {\n this._tracer = tracer;\n this.startSpan = tracer.startSpan.bind(this._tracer);\n this.startActiveSpan = tracer.startActiveSpan.bind(this._tracer);\n }\n\n startActiveSpan: Tracer['startActiveSpan'];\n startSpan: Tracer['startSpan'];\n\n /**\n * Starts a new {@link Span} and calls the given function passing it the\n * created span as first argument.\n * Additionally, the new span gets set in context and this context is activated\n * for the duration of the function call.\n * The span will be closed after the function has executed.\n * If an exception occurs, it is recorded, the status is set to ERROR and the exception is rethrown.\n *\n * @param name The name of the span\n * @param [options] SugaredSpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns return value of fn\n * @example\n * const something = tracer.withActiveSpan('op', span => {\n * // do some work\n * });\n * @example\n * const something = await tracer.withActiveSpan('op', span => {\n * // do some async work\n * });\n */\n withActiveSpan ReturnType>(\n name: string,\n fn: F\n ): ReturnType;\n withActiveSpan ReturnType>(\n name: string,\n options: SugaredSpanOptions,\n fn: F\n ): ReturnType;\n withActiveSpan ReturnType>(\n name: string,\n options: SugaredSpanOptions,\n context: Context,\n fn: F\n ): ReturnType;\n withActiveSpan ReturnType>(\n name: string,\n arg2: F | SugaredSpanOptions,\n arg3?: F | Context,\n arg4?: F\n ): ReturnType {\n const { opts, ctx, fn } = massageParams(arg2, arg3, arg4);\n\n return this._tracer.startActiveSpan(name, opts, ctx, (span: Span) =>\n handleFn(span, opts, fn)\n ) as ReturnType;\n }\n\n /**\n * Starts a new {@link Span} and ends it after execution of fn without setting it on context.\n * The span will be closed after the function has executed.\n * If an exception occurs, it is recorded, the status is et to ERROR and rethrown.\n *\n * This method does NOT modify the current Context.\n *\n * @param name The name of the span\n * @param [options] SugaredSpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns Span The newly created span\n * @example\n * const something = tracer.withSpan('op', span => {\n * // do some work\n * });\n * @example\n * const something = await tracer.withSpan('op', span => {\n * // do some async work\n * });\n */\n withSpan ReturnType>(\n name: string,\n fn: F\n ): ReturnType;\n withSpan ReturnType>(\n name: string,\n options: SugaredSpanOptions,\n fn: F\n ): ReturnType;\n withSpan ReturnType>(\n name: string,\n options: SugaredSpanOptions,\n context: Context,\n fn: F\n ): ReturnType;\n withSpan ReturnType>(\n name: string,\n options: SugaredSpanOptions,\n context: Context,\n fn: F\n ): ReturnType;\n withSpan ReturnType>(\n name: string,\n arg2: SugaredSpanOptions | F,\n arg3?: Context | F,\n arg4?: F\n ): ReturnType {\n const { opts, ctx, fn } = massageParams(arg2, arg3, arg4);\n\n const span = this._tracer.startSpan(name, opts, ctx);\n return handleFn(span, opts, fn) as ReturnType;\n }\n}\n\n/**\n * Massages parameters of withSpan and withActiveSpan to allow signature overwrites\n * @param arg\n * @param arg2\n * @param arg3\n */\nfunction massageParams ReturnType>(\n arg: F | SugaredSpanOptions,\n arg2?: F | Context,\n arg3?: F\n) {\n let opts: SugaredSpanOptions | undefined;\n let ctx: Context | undefined;\n let fn: F;\n\n if (!arg2 && !arg3) {\n fn = arg as F;\n } else if (!arg3) {\n opts = arg as SugaredSpanOptions;\n fn = arg2 as F;\n } else {\n opts = arg as SugaredSpanOptions;\n ctx = arg2 as Context;\n fn = arg3 as F;\n }\n opts = opts ?? {};\n ctx = ctx ?? context.active();\n\n return { opts, ctx, fn };\n}\n\n/**\n * Executes fn, returns results and runs onException in the case of exception to allow overwriting of error handling\n * @param span\n * @param opts\n * @param fn\n */\nfunction handleFn ReturnType>(\n span: Span,\n opts: SugaredSpanOptions,\n fn: F\n): ReturnType {\n const onException = opts.onException ?? defaultOnException;\n const errorHandler = (e: Error) => {\n onException(e, span);\n span.end();\n throw e;\n };\n\n try {\n const ret = fn(span) as Promise>;\n // if fn is an async function, attach a recordException and spanEnd callback to the promise\n if (typeof ret?.then === 'function') {\n return ret.then(val => {\n span.end();\n return val;\n }, errorHandler) as ReturnType;\n }\n span.end();\n return ret as ReturnType;\n } catch (e) {\n // add throw to signal the compiler that this will throw in the inner scope\n throw errorHandler(e);\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/index.d.ts b/node_modules/@opentelemetry/api/build/src/index.d.ts new file mode 100644 index 0000000..eea88f2 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/index.d.ts @@ -0,0 +1,54 @@ +export { BaggageEntry, BaggageEntryMetadata, Baggage } from './baggage/types'; +export { baggageEntryMetadataFromString } from './baggage/utils'; +export { Exception } from './common/Exception'; +export { HrTime, TimeInput } from './common/Time'; +export { Attributes, AttributeValue } from './common/Attributes'; +export { createContextKey, ROOT_CONTEXT } from './context/context'; +export { Context, ContextManager } from './context/types'; +export type { ContextAPI } from './api/context'; +export { DiagConsoleLogger } from './diag/consoleLogger'; +export { DiagLogFunction, DiagLogger, DiagLogLevel, ComponentLoggerOptions, DiagLoggerOptions, } from './diag/types'; +export type { DiagAPI } from './api/diag'; +export { createNoopMeter } from './metrics/NoopMeter'; +export { MeterOptions, Meter } from './metrics/Meter'; +export { MeterProvider } from './metrics/MeterProvider'; +export { ValueType, Counter, Gauge, Histogram, MetricOptions, Observable, ObservableCounter, ObservableGauge, ObservableUpDownCounter, UpDownCounter, BatchObservableCallback, MetricAdvice, MetricAttributes, MetricAttributeValue, ObservableCallback, } from './metrics/Metric'; +export { BatchObservableResult, ObservableResult, } from './metrics/ObservableResult'; +export type { MetricsAPI } from './api/metrics'; +export { TextMapPropagator, TextMapSetter, TextMapGetter, defaultTextMapGetter, defaultTextMapSetter, } from './propagation/TextMapPropagator'; +export type { PropagationAPI } from './api/propagation'; +export { SpanAttributes, SpanAttributeValue } from './trace/attributes'; +export { Link } from './trace/link'; +export { ProxyTracer, TracerDelegator } from './trace/ProxyTracer'; +export { ProxyTracerProvider } from './trace/ProxyTracerProvider'; +export { Sampler } from './trace/Sampler'; +export { SamplingDecision, SamplingResult } from './trace/SamplingResult'; +export { SpanContext } from './trace/span_context'; +export { SpanKind } from './trace/span_kind'; +export { Span } from './trace/span'; +export { SpanOptions } from './trace/SpanOptions'; +export { SpanStatus, SpanStatusCode } from './trace/status'; +export { TraceFlags } from './trace/trace_flags'; +export { TraceState } from './trace/trace_state'; +export { createTraceState } from './trace/internal/utils'; +export { TracerProvider } from './trace/tracer_provider'; +export { Tracer } from './trace/tracer'; +export { TracerOptions } from './trace/tracer_options'; +export { isSpanContextValid, isValidTraceId, isValidSpanId, } from './trace/spancontext-utils'; +export { INVALID_SPANID, INVALID_TRACEID, INVALID_SPAN_CONTEXT, } from './trace/invalid-span-constants'; +export type { TraceAPI } from './api/trace'; +import { context } from './context-api'; +import { diag } from './diag-api'; +import { metrics } from './metrics-api'; +import { propagation } from './propagation-api'; +import { trace } from './trace-api'; +export { context, diag, metrics, propagation, trace }; +declare const _default: { + context: import("./api/context").ContextAPI; + diag: import("./api/diag").DiagAPI; + metrics: import("./api/metrics").MetricsAPI; + propagation: import("./api/propagation").PropagationAPI; + trace: import("./api/trace").TraceAPI; +}; +export default _default; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/index.js b/node_modules/@opentelemetry/api/build/src/index.js new file mode 100644 index 0000000..cb0a872 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/index.js @@ -0,0 +1,81 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = void 0; +var utils_1 = require("./baggage/utils"); +Object.defineProperty(exports, "baggageEntryMetadataFromString", { enumerable: true, get: function () { return utils_1.baggageEntryMetadataFromString; } }); +// Context APIs +var context_1 = require("./context/context"); +Object.defineProperty(exports, "createContextKey", { enumerable: true, get: function () { return context_1.createContextKey; } }); +Object.defineProperty(exports, "ROOT_CONTEXT", { enumerable: true, get: function () { return context_1.ROOT_CONTEXT; } }); +// Diag APIs +var consoleLogger_1 = require("./diag/consoleLogger"); +Object.defineProperty(exports, "DiagConsoleLogger", { enumerable: true, get: function () { return consoleLogger_1.DiagConsoleLogger; } }); +var types_1 = require("./diag/types"); +Object.defineProperty(exports, "DiagLogLevel", { enumerable: true, get: function () { return types_1.DiagLogLevel; } }); +// Metrics APIs +var NoopMeter_1 = require("./metrics/NoopMeter"); +Object.defineProperty(exports, "createNoopMeter", { enumerable: true, get: function () { return NoopMeter_1.createNoopMeter; } }); +var Metric_1 = require("./metrics/Metric"); +Object.defineProperty(exports, "ValueType", { enumerable: true, get: function () { return Metric_1.ValueType; } }); +// Propagation APIs +var TextMapPropagator_1 = require("./propagation/TextMapPropagator"); +Object.defineProperty(exports, "defaultTextMapGetter", { enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapGetter; } }); +Object.defineProperty(exports, "defaultTextMapSetter", { enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapSetter; } }); +var ProxyTracer_1 = require("./trace/ProxyTracer"); +Object.defineProperty(exports, "ProxyTracer", { enumerable: true, get: function () { return ProxyTracer_1.ProxyTracer; } }); +var ProxyTracerProvider_1 = require("./trace/ProxyTracerProvider"); +Object.defineProperty(exports, "ProxyTracerProvider", { enumerable: true, get: function () { return ProxyTracerProvider_1.ProxyTracerProvider; } }); +var SamplingResult_1 = require("./trace/SamplingResult"); +Object.defineProperty(exports, "SamplingDecision", { enumerable: true, get: function () { return SamplingResult_1.SamplingDecision; } }); +var span_kind_1 = require("./trace/span_kind"); +Object.defineProperty(exports, "SpanKind", { enumerable: true, get: function () { return span_kind_1.SpanKind; } }); +var status_1 = require("./trace/status"); +Object.defineProperty(exports, "SpanStatusCode", { enumerable: true, get: function () { return status_1.SpanStatusCode; } }); +var trace_flags_1 = require("./trace/trace_flags"); +Object.defineProperty(exports, "TraceFlags", { enumerable: true, get: function () { return trace_flags_1.TraceFlags; } }); +var utils_2 = require("./trace/internal/utils"); +Object.defineProperty(exports, "createTraceState", { enumerable: true, get: function () { return utils_2.createTraceState; } }); +var spancontext_utils_1 = require("./trace/spancontext-utils"); +Object.defineProperty(exports, "isSpanContextValid", { enumerable: true, get: function () { return spancontext_utils_1.isSpanContextValid; } }); +Object.defineProperty(exports, "isValidTraceId", { enumerable: true, get: function () { return spancontext_utils_1.isValidTraceId; } }); +Object.defineProperty(exports, "isValidSpanId", { enumerable: true, get: function () { return spancontext_utils_1.isValidSpanId; } }); +var invalid_span_constants_1 = require("./trace/invalid-span-constants"); +Object.defineProperty(exports, "INVALID_SPANID", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPANID; } }); +Object.defineProperty(exports, "INVALID_TRACEID", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_TRACEID; } }); +Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPAN_CONTEXT; } }); +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const context_api_1 = require("./context-api"); +Object.defineProperty(exports, "context", { enumerable: true, get: function () { return context_api_1.context; } }); +const diag_api_1 = require("./diag-api"); +Object.defineProperty(exports, "diag", { enumerable: true, get: function () { return diag_api_1.diag; } }); +const metrics_api_1 = require("./metrics-api"); +Object.defineProperty(exports, "metrics", { enumerable: true, get: function () { return metrics_api_1.metrics; } }); +const propagation_api_1 = require("./propagation-api"); +Object.defineProperty(exports, "propagation", { enumerable: true, get: function () { return propagation_api_1.propagation; } }); +const trace_api_1 = require("./trace-api"); +Object.defineProperty(exports, "trace", { enumerable: true, get: function () { return trace_api_1.trace; } }); +// Default export. +exports.default = { + context: context_api_1.context, + diag: diag_api_1.diag, + metrics: metrics_api_1.metrics, + propagation: propagation_api_1.propagation, + trace: trace_api_1.trace, +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/index.js.map b/node_modules/@opentelemetry/api/build/src/index.js.map new file mode 100644 index 0000000..2ff3ff6 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAGH,yCAAiE;AAAxD,uHAAA,8BAA8B,OAAA;AAKvC,eAAe;AACf,6CAAmE;AAA1D,2GAAA,gBAAgB,OAAA;AAAE,uGAAA,YAAY,OAAA;AAIvC,YAAY;AACZ,sDAAyD;AAAhD,kHAAA,iBAAiB,OAAA;AAC1B,sCAMsB;AAHpB,qGAAA,YAAY,OAAA;AAMd,eAAe;AACf,iDAAsD;AAA7C,4GAAA,eAAe,OAAA;AAGxB,2CAgB0B;AAfxB,mGAAA,SAAS,OAAA;AAsBX,mBAAmB;AACnB,qEAMyC;AAFvC,yHAAA,oBAAoB,OAAA;AACpB,yHAAA,oBAAoB,OAAA;AAOtB,mDAAmE;AAA1D,0GAAA,WAAW,OAAA;AACpB,mEAAkE;AAAzD,0HAAA,mBAAmB,OAAA;AAE5B,yDAA0E;AAAjE,kHAAA,gBAAgB,OAAA;AAEzB,+CAA6C;AAApC,qGAAA,QAAQ,OAAA;AAGjB,yCAA4D;AAAvC,wGAAA,cAAc,OAAA;AACnC,mDAAiD;AAAxC,yGAAA,UAAU,OAAA;AAEnB,gDAA0D;AAAjD,yGAAA,gBAAgB,OAAA;AAIzB,+DAImC;AAHjC,uHAAA,kBAAkB,OAAA;AAClB,mHAAA,cAAc,OAAA;AACd,kHAAA,aAAa,OAAA;AAEf,yEAIwC;AAHtC,wHAAA,cAAc,OAAA;AACd,yHAAA,eAAe,OAAA;AACf,8HAAA,oBAAoB,OAAA;AAItB,sEAAsE;AACtE,qCAAqC;AACrC,+CAAwC;AAO/B,wFAPA,qBAAO,OAOA;AANhB,yCAAkC;AAMhB,qFANT,eAAI,OAMS;AALtB,+CAAwC;AAKhB,wFALf,qBAAO,OAKe;AAJ/B,uDAAgD;AAIf,4FAJxB,6BAAW,OAIwB;AAH5C,2CAAoC;AAGU,sFAHrC,iBAAK,OAGqC;AACnD,kBAAkB;AAClB,kBAAe;IACb,OAAO,EAAP,qBAAO;IACP,IAAI,EAAJ,eAAI;IACJ,OAAO,EAAP,qBAAO;IACP,WAAW,EAAX,6BAAW;IACX,KAAK,EAAL,iBAAK;CACN,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { BaggageEntry, BaggageEntryMetadata, Baggage } from './baggage/types';\nexport { baggageEntryMetadataFromString } from './baggage/utils';\nexport { Exception } from './common/Exception';\nexport { HrTime, TimeInput } from './common/Time';\nexport { Attributes, AttributeValue } from './common/Attributes';\n\n// Context APIs\nexport { createContextKey, ROOT_CONTEXT } from './context/context';\nexport { Context, ContextManager } from './context/types';\nexport type { ContextAPI } from './api/context';\n\n// Diag APIs\nexport { DiagConsoleLogger } from './diag/consoleLogger';\nexport {\n DiagLogFunction,\n DiagLogger,\n DiagLogLevel,\n ComponentLoggerOptions,\n DiagLoggerOptions,\n} from './diag/types';\nexport type { DiagAPI } from './api/diag';\n\n// Metrics APIs\nexport { createNoopMeter } from './metrics/NoopMeter';\nexport { MeterOptions, Meter } from './metrics/Meter';\nexport { MeterProvider } from './metrics/MeterProvider';\nexport {\n ValueType,\n Counter,\n Gauge,\n Histogram,\n MetricOptions,\n Observable,\n ObservableCounter,\n ObservableGauge,\n ObservableUpDownCounter,\n UpDownCounter,\n BatchObservableCallback,\n MetricAdvice,\n MetricAttributes,\n MetricAttributeValue,\n ObservableCallback,\n} from './metrics/Metric';\nexport {\n BatchObservableResult,\n ObservableResult,\n} from './metrics/ObservableResult';\nexport type { MetricsAPI } from './api/metrics';\n\n// Propagation APIs\nexport {\n TextMapPropagator,\n TextMapSetter,\n TextMapGetter,\n defaultTextMapGetter,\n defaultTextMapSetter,\n} from './propagation/TextMapPropagator';\nexport type { PropagationAPI } from './api/propagation';\n\n// Trace APIs\nexport { SpanAttributes, SpanAttributeValue } from './trace/attributes';\nexport { Link } from './trace/link';\nexport { ProxyTracer, TracerDelegator } from './trace/ProxyTracer';\nexport { ProxyTracerProvider } from './trace/ProxyTracerProvider';\nexport { Sampler } from './trace/Sampler';\nexport { SamplingDecision, SamplingResult } from './trace/SamplingResult';\nexport { SpanContext } from './trace/span_context';\nexport { SpanKind } from './trace/span_kind';\nexport { Span } from './trace/span';\nexport { SpanOptions } from './trace/SpanOptions';\nexport { SpanStatus, SpanStatusCode } from './trace/status';\nexport { TraceFlags } from './trace/trace_flags';\nexport { TraceState } from './trace/trace_state';\nexport { createTraceState } from './trace/internal/utils';\nexport { TracerProvider } from './trace/tracer_provider';\nexport { Tracer } from './trace/tracer';\nexport { TracerOptions } from './trace/tracer_options';\nexport {\n isSpanContextValid,\n isValidTraceId,\n isValidSpanId,\n} from './trace/spancontext-utils';\nexport {\n INVALID_SPANID,\n INVALID_TRACEID,\n INVALID_SPAN_CONTEXT,\n} from './trace/invalid-span-constants';\nexport type { TraceAPI } from './api/trace';\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { context } from './context-api';\nimport { diag } from './diag-api';\nimport { metrics } from './metrics-api';\nimport { propagation } from './propagation-api';\nimport { trace } from './trace-api';\n\n// Named export.\nexport { context, diag, metrics, propagation, trace };\n// Default export.\nexport default {\n context,\n diag,\n metrics,\n propagation,\n trace,\n};\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/internal/global-utils.d.ts b/node_modules/@opentelemetry/api/build/src/internal/global-utils.d.ts new file mode 100644 index 0000000..320db97 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/internal/global-utils.d.ts @@ -0,0 +1,18 @@ +import { MeterProvider } from '../metrics/MeterProvider'; +import { ContextManager } from '../context/types'; +import { DiagLogger } from '../diag/types'; +import { TextMapPropagator } from '../propagation/TextMapPropagator'; +import type { TracerProvider } from '../trace/tracer_provider'; +export declare function registerGlobal(type: Type, instance: OTelGlobalAPI[Type], diag: DiagLogger, allowOverride?: boolean): boolean; +export declare function getGlobal(type: Type): OTelGlobalAPI[Type] | undefined; +export declare function unregisterGlobal(type: keyof OTelGlobalAPI, diag: DiagLogger): void; +declare type OTelGlobalAPI = { + version: string; + diag?: DiagLogger; + trace?: TracerProvider; + context?: ContextManager; + metrics?: MeterProvider; + propagation?: TextMapPropagator; +}; +export {}; +//# sourceMappingURL=global-utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/internal/global-utils.js b/node_modules/@opentelemetry/api/build/src/internal/global-utils.js new file mode 100644 index 0000000..11a1a44 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/internal/global-utils.js @@ -0,0 +1,64 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0; +const platform_1 = require("../platform"); +const version_1 = require("../version"); +const semver_1 = require("./semver"); +const major = version_1.VERSION.split('.')[0]; +const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); +const _global = platform_1._globalThis; +function registerGlobal(type, instance, diag, allowOverride = false) { + var _a; + const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { + version: version_1.VERSION, + }); + if (!allowOverride && api[type]) { + // already registered an API of this type + const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`); + diag.error(err.stack || err.message); + return false; + } + if (api.version !== version_1.VERSION) { + // All registered APIs must be of the same version exactly + const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`); + diag.error(err.stack || err.message); + return false; + } + api[type] = instance; + diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`); + return true; +} +exports.registerGlobal = registerGlobal; +function getGlobal(type) { + var _a, _b; + const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; + if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) { + return; + } + return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; +} +exports.getGlobal = getGlobal; +function unregisterGlobal(type, diag) { + diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`); + const api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; + if (api) { + delete api[type]; + } +} +exports.unregisterGlobal = unregisterGlobal; +//# sourceMappingURL=global-utils.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/internal/global-utils.js.map b/node_modules/@opentelemetry/api/build/src/internal/global-utils.js.map new file mode 100644 index 0000000..ddca637 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/internal/global-utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"global-utils.js","sourceRoot":"","sources":["../../../src/internal/global-utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAKH,0CAA0C;AAG1C,wCAAqC;AACrC,qCAAwC;AAExC,MAAM,KAAK,GAAG,iBAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AACpC,MAAM,4BAA4B,GAAG,MAAM,CAAC,GAAG,CAC7C,wBAAwB,KAAK,EAAE,CAChC,CAAC;AAEF,MAAM,OAAO,GAAG,sBAAyB,CAAC;AAE1C,SAAgB,cAAc,CAC5B,IAAU,EACV,QAA6B,EAC7B,IAAgB,EAChB,aAAa,GAAG,KAAK;;IAErB,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,4BAA4B,CAAC,GAAG,MAAA,OAAO,CAC1D,4BAA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AC,4BAA4B,CAAC,CAAC;IAElD,IAAI,GAAG,EAAE;QACP,OAAO,GAAG,CAAC,IAAI,CAAC,CAAC;KAClB;AACH,CAAC;AATD,4CASC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MeterProvider } from '../metrics/MeterProvider';\nimport { ContextManager } from '../context/types';\nimport { DiagLogger } from '../diag/types';\nimport { _globalThis } from '../platform';\nimport { TextMapPropagator } from '../propagation/TextMapPropagator';\nimport type { TracerProvider } from '../trace/tracer_provider';\nimport { VERSION } from '../version';\nimport { isCompatible } from './semver';\n\nconst major = VERSION.split('.')[0];\nconst GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(\n `opentelemetry.js.api.${major}`\n);\n\nconst _global = _globalThis as OTelGlobal;\n\nexport function registerGlobal(\n type: Type,\n instance: OTelGlobalAPI[Type],\n diag: DiagLogger,\n allowOverride = false\n): boolean {\n const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = _global[\n GLOBAL_OPENTELEMETRY_API_KEY\n ] ?? {\n version: VERSION,\n });\n\n if (!allowOverride && api[type]) {\n // already registered an API of this type\n const err = new Error(\n `@opentelemetry/api: Attempted duplicate registration of API: ${type}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n if (api.version !== VERSION) {\n // All registered APIs must be of the same version exactly\n const err = new Error(\n `@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n api[type] = instance;\n diag.debug(\n `@opentelemetry/api: Registered a global for ${type} v${VERSION}.`\n );\n\n return true;\n}\n\nexport function getGlobal(\n type: Type\n): OTelGlobalAPI[Type] | undefined {\n const globalVersion = _global[GLOBAL_OPENTELEMETRY_API_KEY]?.version;\n if (!globalVersion || !isCompatible(globalVersion)) {\n return;\n }\n return _global[GLOBAL_OPENTELEMETRY_API_KEY]?.[type];\n}\n\nexport function unregisterGlobal(type: keyof OTelGlobalAPI, diag: DiagLogger) {\n diag.debug(\n `@opentelemetry/api: Unregistering a global for ${type} v${VERSION}.`\n );\n const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];\n\n if (api) {\n delete api[type];\n }\n}\n\ntype OTelGlobal = {\n [GLOBAL_OPENTELEMETRY_API_KEY]?: OTelGlobalAPI;\n};\n\ntype OTelGlobalAPI = {\n version: string;\n\n diag?: DiagLogger;\n trace?: TracerProvider;\n context?: ContextManager;\n metrics?: MeterProvider;\n propagation?: TextMapPropagator;\n};\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/internal/semver.d.ts b/node_modules/@opentelemetry/api/build/src/internal/semver.d.ts new file mode 100644 index 0000000..d9f4259 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/internal/semver.d.ts @@ -0,0 +1,34 @@ +/** + * Create a function to test an API version to see if it is compatible with the provided ownVersion. + * + * The returned function has the following semantics: + * - Exact match is always compatible + * - Major versions must match exactly + * - 1.x package cannot use global 2.x package + * - 2.x package cannot use global 1.x package + * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API + * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects + * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 + * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor + * - Patch and build tag differences are not considered at this time + * + * @param ownVersion version which should be checked against + */ +export declare function _makeCompatibilityCheck(ownVersion: string): (globalVersion: string) => boolean; +/** + * Test an API version to see if it is compatible with this API. + * + * - Exact match is always compatible + * - Major versions must match exactly + * - 1.x package cannot use global 2.x package + * - 2.x package cannot use global 1.x package + * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API + * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects + * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 + * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor + * - Patch and build tag differences are not considered at this time + * + * @param version version of the API requesting an instance of the global API + */ +export declare const isCompatible: (globalVersion: string) => boolean; +//# sourceMappingURL=semver.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/internal/semver.js b/node_modules/@opentelemetry/api/build/src/internal/semver.js new file mode 100644 index 0000000..7a073b2 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/internal/semver.js @@ -0,0 +1,122 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isCompatible = exports._makeCompatibilityCheck = void 0; +const version_1 = require("../version"); +const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; +/** + * Create a function to test an API version to see if it is compatible with the provided ownVersion. + * + * The returned function has the following semantics: + * - Exact match is always compatible + * - Major versions must match exactly + * - 1.x package cannot use global 2.x package + * - 2.x package cannot use global 1.x package + * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API + * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects + * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 + * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor + * - Patch and build tag differences are not considered at this time + * + * @param ownVersion version which should be checked against + */ +function _makeCompatibilityCheck(ownVersion) { + const acceptedVersions = new Set([ownVersion]); + const rejectedVersions = new Set(); + const myVersionMatch = ownVersion.match(re); + if (!myVersionMatch) { + // we cannot guarantee compatibility so we always return noop + return () => false; + } + const ownVersionParsed = { + major: +myVersionMatch[1], + minor: +myVersionMatch[2], + patch: +myVersionMatch[3], + prerelease: myVersionMatch[4], + }; + // if ownVersion has a prerelease tag, versions must match exactly + if (ownVersionParsed.prerelease != null) { + return function isExactmatch(globalVersion) { + return globalVersion === ownVersion; + }; + } + function _reject(v) { + rejectedVersions.add(v); + return false; + } + function _accept(v) { + acceptedVersions.add(v); + return true; + } + return function isCompatible(globalVersion) { + if (acceptedVersions.has(globalVersion)) { + return true; + } + if (rejectedVersions.has(globalVersion)) { + return false; + } + const globalVersionMatch = globalVersion.match(re); + if (!globalVersionMatch) { + // cannot parse other version + // we cannot guarantee compatibility so we always noop + return _reject(globalVersion); + } + const globalVersionParsed = { + major: +globalVersionMatch[1], + minor: +globalVersionMatch[2], + patch: +globalVersionMatch[3], + prerelease: globalVersionMatch[4], + }; + // if globalVersion has a prerelease tag, versions must match exactly + if (globalVersionParsed.prerelease != null) { + return _reject(globalVersion); + } + // major versions must match + if (ownVersionParsed.major !== globalVersionParsed.major) { + return _reject(globalVersion); + } + if (ownVersionParsed.major === 0) { + if (ownVersionParsed.minor === globalVersionParsed.minor && + ownVersionParsed.patch <= globalVersionParsed.patch) { + return _accept(globalVersion); + } + return _reject(globalVersion); + } + if (ownVersionParsed.minor <= globalVersionParsed.minor) { + return _accept(globalVersion); + } + return _reject(globalVersion); + }; +} +exports._makeCompatibilityCheck = _makeCompatibilityCheck; +/** + * Test an API version to see if it is compatible with this API. + * + * - Exact match is always compatible + * - Major versions must match exactly + * - 1.x package cannot use global 2.x package + * - 2.x package cannot use global 1.x package + * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API + * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects + * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 + * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor + * - Patch and build tag differences are not considered at this time + * + * @param version version of the API requesting an instance of the global API + */ +exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION); +//# sourceMappingURL=semver.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/internal/semver.js.map b/node_modules/@opentelemetry/api/build/src/internal/semver.js.map new file mode 100644 index 0000000..d58dc78 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/internal/semver.js.map @@ -0,0 +1 @@ +{"version":3,"file":"semver.js","sourceRoot":"","sources":["../../../src/internal/semver.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,wCAAqC;AAErC,MAAM,EAAE,GAAG,+BAA+B,CAAC;AAE3C;;;;;;;;;;;;;;;GAeG;AACH,SAAgB,uBAAuB,CACrC,UAAkB;IAElB,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAS,CAAC,UAAU,CAAC,CAAC,CAAC;IACvD,MAAM,gBAAgB,GAAG,IAAI,GAAG,EAAU,CAAC;IAE3C,MAAM,cAAc,GAAG,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAC5C,IAAI,CAAC,cAAc,EAAE;QACnB,6DAA6D;QAC7D,OAAO,GAAG,EAAE,CAAC,KAAK,CAAC;KACpB;IAED,MAAM,gBAAgB,GAAG;QACvB,KAAK,EAAE,CAAC,cAAc,CAAC,CAAC,CAAC;QACzB,KAAK,EAAE,CAAC,cAAc,CAAC,CAAC,CAAC;QACzB,KAAK,EAAE,CAAC,cAAc,CAAC,CAAC,CAAC;QACzB,UAAU,EAAE,cAAc,CAAC,CAAC,CAAC;KAC9B,CAAC;IAEF,kEAAkE;IAClE,IAAI,gBAAgB,CAAC,UAAU,IAAI,IAAI,EAAE;QACvC,OAAO,SAAS,YAAY,CAAC,aAAqB;YAChD,OAAO,aAAa,KAAK,UAAU,CAAC;QACtC,CAAC,CAAC;KACH;IAED,SAAS,OAAO,CAAC,CAAS;QACxB,gB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OAAO,OAAO,CAAC,aAAa,CAAC,CAAC;aAC/B;YAED,OAAO,OAAO,CAAC,aAAa,CAAC,CAAC;SAC/B;QAED,IAAI,gBAAgB,CAAC,KAAK,IAAI,mBAAmB,CAAC,KAAK,EAAE;YACvD,OAAO,OAAO,CAAC,aAAa,CAAC,CAAC;SAC/B;QAED,OAAO,OAAO,CAAC,aAAa,CAAC,CAAC;IAChC,CAAC,CAAC;AACJ,CAAC;AAtFD,0DAsFC;AAED;;;;;;;;;;;;;;GAcG;AACU,QAAA,YAAY,GAAG,uBAAuB,CAAC,iBAAO,CAAC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { VERSION } from '../version';\n\nconst re = /^(\\d+)\\.(\\d+)\\.(\\d+)(-(.+))?$/;\n\n/**\n * Create a function to test an API version to see if it is compatible with the provided ownVersion.\n *\n * The returned function has the following semantics:\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param ownVersion version which should be checked against\n */\nexport function _makeCompatibilityCheck(\n ownVersion: string\n): (globalVersion: string) => boolean {\n const acceptedVersions = new Set([ownVersion]);\n const rejectedVersions = new Set();\n\n const myVersionMatch = ownVersion.match(re);\n if (!myVersionMatch) {\n // we cannot guarantee compatibility so we always return noop\n return () => false;\n }\n\n const ownVersionParsed = {\n major: +myVersionMatch[1],\n minor: +myVersionMatch[2],\n patch: +myVersionMatch[3],\n prerelease: myVersionMatch[4],\n };\n\n // if ownVersion has a prerelease tag, versions must match exactly\n if (ownVersionParsed.prerelease != null) {\n return function isExactmatch(globalVersion: string): boolean {\n return globalVersion === ownVersion;\n };\n }\n\n function _reject(v: string) {\n rejectedVersions.add(v);\n return false;\n }\n\n function _accept(v: string) {\n acceptedVersions.add(v);\n return true;\n }\n\n return function isCompatible(globalVersion: string): boolean {\n if (acceptedVersions.has(globalVersion)) {\n return true;\n }\n\n if (rejectedVersions.has(globalVersion)) {\n return false;\n }\n\n const globalVersionMatch = globalVersion.match(re);\n if (!globalVersionMatch) {\n // cannot parse other version\n // we cannot guarantee compatibility so we always noop\n return _reject(globalVersion);\n }\n\n const globalVersionParsed = {\n major: +globalVersionMatch[1],\n minor: +globalVersionMatch[2],\n patch: +globalVersionMatch[3],\n prerelease: globalVersionMatch[4],\n };\n\n // if globalVersion has a prerelease tag, versions must match exactly\n if (globalVersionParsed.prerelease != null) {\n return _reject(globalVersion);\n }\n\n // major versions must match\n if (ownVersionParsed.major !== globalVersionParsed.major) {\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.major === 0) {\n if (\n ownVersionParsed.minor === globalVersionParsed.minor &&\n ownVersionParsed.patch <= globalVersionParsed.patch\n ) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.minor <= globalVersionParsed.minor) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n };\n}\n\n/**\n * Test an API version to see if it is compatible with this API.\n *\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param version version of the API requesting an instance of the global API\n */\nexport const isCompatible = _makeCompatibilityCheck(VERSION);\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics-api.d.ts b/node_modules/@opentelemetry/api/build/src/metrics-api.d.ts new file mode 100644 index 0000000..26d539c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics-api.d.ts @@ -0,0 +1,4 @@ +import { MetricsAPI } from './api/metrics'; +/** Entrypoint for metrics API */ +export declare const metrics: MetricsAPI; +//# sourceMappingURL=metrics-api.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics-api.js b/node_modules/@opentelemetry/api/build/src/metrics-api.js new file mode 100644 index 0000000..987f7c2 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics-api.js @@ -0,0 +1,24 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.metrics = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const metrics_1 = require("./api/metrics"); +/** Entrypoint for metrics API */ +exports.metrics = metrics_1.MetricsAPI.getInstance(); +//# sourceMappingURL=metrics-api.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics-api.js.map b/node_modules/@opentelemetry/api/build/src/metrics-api.js.map new file mode 100644 index 0000000..26e1802 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics-api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metrics-api.js","sourceRoot":"","sources":["../../src/metrics-api.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,sEAAsE;AACtE,qCAAqC;AACrC,2CAA2C;AAC3C,iCAAiC;AACpB,QAAA,OAAO,GAAG,oBAAU,CAAC,WAAW,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { MetricsAPI } from './api/metrics';\n/** Entrypoint for metrics API */\nexport const metrics = MetricsAPI.getInstance();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics/Meter.d.ts b/node_modules/@opentelemetry/api/build/src/metrics/Meter.d.ts new file mode 100644 index 0000000..5e3926b --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics/Meter.d.ts @@ -0,0 +1,110 @@ +import { BatchObservableCallback, Counter, Gauge, Histogram, MetricAttributes, MetricOptions, Observable, ObservableCounter, ObservableGauge, ObservableUpDownCounter, UpDownCounter } from './Metric'; +/** + * An interface describes additional metadata of a meter. + */ +export interface MeterOptions { + /** + * The schemaUrl of the meter or instrumentation library + */ + schemaUrl?: string; +} +/** + * An interface to allow the recording metrics. + * + * {@link Metric}s are used for recording pre-defined aggregation (`Counter`), + * or raw values (`Histogram`) in which the aggregation and attributes + * for the exported metric are deferred. + */ +export interface Meter { + /** + * Creates and returns a new `Gauge`. + * @param name the name of the metric. + * @param [options] the metric options. + */ + createGauge(name: string, options?: MetricOptions): Gauge; + /** + * Creates and returns a new `Histogram`. + * @param name the name of the metric. + * @param [options] the metric options. + */ + createHistogram(name: string, options?: MetricOptions): Histogram; + /** + * Creates a new `Counter` metric. Generally, this kind of metric when the + * value is a quantity, the sum is of primary interest, and the event count + * and value distribution are not of primary interest. + * @param name the name of the metric. + * @param [options] the metric options. + */ + createCounter(name: string, options?: MetricOptions): Counter; + /** + * Creates a new `UpDownCounter` metric. UpDownCounter is a synchronous + * instrument and very similar to Counter except that Add(increment) + * supports negative increments. It is generally useful for capturing changes + * in an amount of resources used, or any quantity that rises and falls + * during a request. + * Example uses for UpDownCounter: + *
                    + *
                  1. count the number of active requests.
                  2. + *
                  3. count memory in use by instrumenting new and delete.
                  4. + *
                  5. count queue size by instrumenting enqueue and dequeue.
                  6. + *
                  7. count semaphore up and down operations.
                  8. + *
                  + * + * @param name the name of the metric. + * @param [options] the metric options. + */ + createUpDownCounter(name: string, options?: MetricOptions): UpDownCounter; + /** + * Creates a new `ObservableGauge` metric. + * + * The callback SHOULD be safe to be invoked concurrently. + * + * @param name the name of the metric. + * @param [options] the metric options. + */ + createObservableGauge(name: string, options?: MetricOptions): ObservableGauge; + /** + * Creates a new `ObservableCounter` metric. + * + * The callback SHOULD be safe to be invoked concurrently. + * + * @param name the name of the metric. + * @param [options] the metric options. + */ + createObservableCounter(name: string, options?: MetricOptions): ObservableCounter; + /** + * Creates a new `ObservableUpDownCounter` metric. + * + * The callback SHOULD be safe to be invoked concurrently. + * + * @param name the name of the metric. + * @param [options] the metric options. + */ + createObservableUpDownCounter(name: string, options?: MetricOptions): ObservableUpDownCounter; + /** + * Sets up a function that will be called whenever a metric collection is + * initiated. + * + * If the function is already in the list of callbacks for this Observable, + * the function is not added a second time. + * + * Only the associated observables can be observed in the callback. + * Measurements of observables that are not associated observed in the + * callback are dropped. + * + * @param callback the batch observable callback + * @param observables the observables associated with this batch observable callback + */ + addBatchObservableCallback(callback: BatchObservableCallback, observables: Observable[]): void; + /** + * Removes a callback previously registered with {@link Meter.addBatchObservableCallback}. + * + * The callback to be removed is identified using a combination of the callback itself, + * and the set of the observables associated with it. + * + * @param callback the batch observable callback + * @param observables the observables associated with this batch observable callback + */ + removeBatchObservableCallback(callback: BatchObservableCallback, observables: Observable[]): void; +} +//# sourceMappingURL=Meter.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics/Meter.js b/node_modules/@opentelemetry/api/build/src/metrics/Meter.js new file mode 100644 index 0000000..56b930c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics/Meter.js @@ -0,0 +1,18 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Meter.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics/Meter.js.map b/node_modules/@opentelemetry/api/build/src/metrics/Meter.js.map new file mode 100644 index 0000000..c5e2ced --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics/Meter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Meter.js","sourceRoot":"","sources":["../../../src/metrics/Meter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BatchObservableCallback,\n Counter,\n Gauge,\n Histogram,\n MetricAttributes,\n MetricOptions,\n Observable,\n ObservableCounter,\n ObservableGauge,\n ObservableUpDownCounter,\n UpDownCounter,\n} from './Metric';\n\n/**\n * An interface describes additional metadata of a meter.\n */\nexport interface MeterOptions {\n /**\n * The schemaUrl of the meter or instrumentation library\n */\n schemaUrl?: string;\n}\n\n/**\n * An interface to allow the recording metrics.\n *\n * {@link Metric}s are used for recording pre-defined aggregation (`Counter`),\n * or raw values (`Histogram`) in which the aggregation and attributes\n * for the exported metric are deferred.\n */\nexport interface Meter {\n /**\n * Creates and returns a new `Gauge`.\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createGauge(\n name: string,\n options?: MetricOptions\n ): Gauge;\n\n /**\n * Creates and returns a new `Histogram`.\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createHistogram(\n name: string,\n options?: MetricOptions\n ): Histogram;\n\n /**\n * Creates a new `Counter` metric. Generally, this kind of metric when the\n * value is a quantity, the sum is of primary interest, and the event count\n * and value distribution are not of primary interest.\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createCounter(\n name: string,\n options?: MetricOptions\n ): Counter;\n\n /**\n * Creates a new `UpDownCounter` metric. UpDownCounter is a synchronous\n * instrument and very similar to Counter except that Add(increment)\n * supports negative increments. It is generally useful for capturing changes\n * in an amount of resources used, or any quantity that rises and falls\n * during a request.\n * Example uses for UpDownCounter:\n *
                    \n *
                  1. count the number of active requests.
                  2. \n *
                  3. count memory in use by instrumenting new and delete.
                  4. \n *
                  5. count queue size by instrumenting enqueue and dequeue.
                  6. \n *
                  7. count semaphore up and down operations.
                  8. \n *
                  \n *\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createUpDownCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n >(\n name: string,\n options?: MetricOptions\n ): UpDownCounter;\n\n /**\n * Creates a new `ObservableGauge` metric.\n *\n * The callback SHOULD be safe to be invoked concurrently.\n *\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createObservableGauge<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n >(\n name: string,\n options?: MetricOptions\n ): ObservableGauge;\n\n /**\n * Creates a new `ObservableCounter` metric.\n *\n * The callback SHOULD be safe to be invoked concurrently.\n *\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createObservableCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n >(\n name: string,\n options?: MetricOptions\n ): ObservableCounter;\n\n /**\n * Creates a new `ObservableUpDownCounter` metric.\n *\n * The callback SHOULD be safe to be invoked concurrently.\n *\n * @param name the name of the metric.\n * @param [options] the metric options.\n */\n createObservableUpDownCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n >(\n name: string,\n options?: MetricOptions\n ): ObservableUpDownCounter;\n\n /**\n * Sets up a function that will be called whenever a metric collection is\n * initiated.\n *\n * If the function is already in the list of callbacks for this Observable,\n * the function is not added a second time.\n *\n * Only the associated observables can be observed in the callback.\n * Measurements of observables that are not associated observed in the\n * callback are dropped.\n *\n * @param callback the batch observable callback\n * @param observables the observables associated with this batch observable callback\n */\n addBatchObservableCallback<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n >(\n callback: BatchObservableCallback,\n observables: Observable[]\n ): void;\n\n /**\n * Removes a callback previously registered with {@link Meter.addBatchObservableCallback}.\n *\n * The callback to be removed is identified using a combination of the callback itself,\n * and the set of the observables associated with it.\n *\n * @param callback the batch observable callback\n * @param observables the observables associated with this batch observable callback\n */\n removeBatchObservableCallback<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n >(\n callback: BatchObservableCallback,\n observables: Observable[]\n ): void;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics/MeterProvider.d.ts b/node_modules/@opentelemetry/api/build/src/metrics/MeterProvider.d.ts new file mode 100644 index 0000000..6c08cc3 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics/MeterProvider.d.ts @@ -0,0 +1,17 @@ +import { Meter, MeterOptions } from './Meter'; +/** + * A registry for creating named {@link Meter}s. + */ +export interface MeterProvider { + /** + * Returns a Meter, creating one if one with the given name, version, and + * schemaUrl pair is not already created. + * + * @param name The name of the meter or instrumentation library. + * @param version The version of the meter or instrumentation library. + * @param options The options of the meter or instrumentation library. + * @returns Meter A Meter with the given name and version + */ + getMeter(name: string, version?: string, options?: MeterOptions): Meter; +} +//# sourceMappingURL=MeterProvider.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics/MeterProvider.js b/node_modules/@opentelemetry/api/build/src/metrics/MeterProvider.js new file mode 100644 index 0000000..e94205e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics/MeterProvider.js @@ -0,0 +1,18 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=MeterProvider.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics/MeterProvider.js.map b/node_modules/@opentelemetry/api/build/src/metrics/MeterProvider.js.map new file mode 100644 index 0000000..80c07b7 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics/MeterProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MeterProvider.js","sourceRoot":"","sources":["../../../src/metrics/MeterProvider.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Meter, MeterOptions } from './Meter';\n\n/**\n * A registry for creating named {@link Meter}s.\n */\nexport interface MeterProvider {\n /**\n * Returns a Meter, creating one if one with the given name, version, and\n * schemaUrl pair is not already created.\n *\n * @param name The name of the meter or instrumentation library.\n * @param version The version of the meter or instrumentation library.\n * @param options The options of the meter or instrumentation library.\n * @returns Meter A Meter with the given name and version\n */\n getMeter(name: string, version?: string, options?: MeterOptions): Meter;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics/Metric.d.ts b/node_modules/@opentelemetry/api/build/src/metrics/Metric.d.ts new file mode 100644 index 0000000..607b637 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics/Metric.d.ts @@ -0,0 +1,115 @@ +import { Attributes, AttributeValue } from '../common/Attributes'; +import { Context } from '../context/types'; +import { BatchObservableResult, ObservableResult } from './ObservableResult'; +/** + * Advisory options influencing aggregation configuration parameters. + * @experimental + */ +export interface MetricAdvice { + /** + * Hint the explicit bucket boundaries for SDK if the metric is been + * aggregated with a HistogramAggregator. + */ + explicitBucketBoundaries?: number[]; +} +/** + * Options needed for metric creation + */ +export interface MetricOptions { + /** + * The description of the Metric. + * @default '' + */ + description?: string; + /** + * The unit of the Metric values. + * @default '' + */ + unit?: string; + /** + * Indicates the type of the recorded value. + * @default {@link ValueType.DOUBLE} + */ + valueType?: ValueType; + /** + * The advice influencing aggregation configuration parameters. + * @experimental + */ + advice?: MetricAdvice; +} +/** The Type of value. It describes how the data is reported. */ +export declare enum ValueType { + INT = 0, + DOUBLE = 1 +} +/** + * Counter is the most common synchronous instrument. This instrument supports + * an `Add(increment)` function for reporting a sum, and is restricted to + * non-negative increments. The default aggregation is Sum, as for any additive + * instrument. + * + * Example uses for Counter: + *
                    + *
                  1. count the number of bytes received.
                  2. + *
                  3. count the number of requests completed.
                  4. + *
                  5. count the number of accounts created.
                  6. + *
                  7. count the number of checkpoints run.
                  8. + *
                  9. count the number of 5xx errors.
                  10. + *
                      + */ +export interface Counter { + /** + * Increment value of counter by the input. Inputs must not be negative. + */ + add(value: number, attributes?: AttributesTypes, context?: Context): void; +} +export interface UpDownCounter { + /** + * Increment value of counter by the input. Inputs may be negative. + */ + add(value: number, attributes?: AttributesTypes, context?: Context): void; +} +export interface Gauge { + /** + * Records a measurement. + */ + record(value: number, attributes?: AttributesTypes, context?: Context): void; +} +export interface Histogram { + /** + * Records a measurement. Value of the measurement must not be negative. + */ + record(value: number, attributes?: AttributesTypes, context?: Context): void; +} +/** + * @deprecated please use {@link Attributes} + */ +export declare type MetricAttributes = Attributes; +/** + * @deprecated please use {@link AttributeValue} + */ +export declare type MetricAttributeValue = AttributeValue; +/** + * The observable callback for Observable instruments. + */ +export declare type ObservableCallback = (observableResult: ObservableResult) => void | Promise; +/** + * The observable callback for a batch of Observable instruments. + */ +export declare type BatchObservableCallback = (observableResult: BatchObservableResult) => void | Promise; +export interface Observable { + /** + * Sets up a function that will be called whenever a metric collection is initiated. + * + * If the function is already in the list of callbacks for this Observable, the function is not added a second time. + */ + addCallback(callback: ObservableCallback): void; + /** + * Removes a callback previously registered with {@link Observable.addCallback}. + */ + removeCallback(callback: ObservableCallback): void; +} +export declare type ObservableCounter = Observable; +export declare type ObservableUpDownCounter = Observable; +export declare type ObservableGauge = Observable; +//# sourceMappingURL=Metric.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics/Metric.js b/node_modules/@opentelemetry/api/build/src/metrics/Metric.js new file mode 100644 index 0000000..4966c3d --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics/Metric.js @@ -0,0 +1,25 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValueType = void 0; +/** The Type of value. It describes how the data is reported. */ +var ValueType; +(function (ValueType) { + ValueType[ValueType["INT"] = 0] = "INT"; + ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE"; +})(ValueType = exports.ValueType || (exports.ValueType = {})); +//# sourceMappingURL=Metric.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics/Metric.js.map b/node_modules/@opentelemetry/api/build/src/metrics/Metric.js.map new file mode 100644 index 0000000..db16884 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics/Metric.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Metric.js","sourceRoot":"","sources":["../../../src/metrics/Metric.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AA+CH,gEAAgE;AAChE,IAAY,SAGX;AAHD,WAAY,SAAS;IACnB,uCAAG,CAAA;IACH,6CAAM,CAAA;AACR,CAAC,EAHW,SAAS,GAAT,iBAAS,KAAT,iBAAS,QAGpB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Attributes, AttributeValue } from '../common/Attributes';\nimport { Context } from '../context/types';\nimport { BatchObservableResult, ObservableResult } from './ObservableResult';\n\n/**\n * Advisory options influencing aggregation configuration parameters.\n * @experimental\n */\nexport interface MetricAdvice {\n /**\n * Hint the explicit bucket boundaries for SDK if the metric is been\n * aggregated with a HistogramAggregator.\n */\n explicitBucketBoundaries?: number[];\n}\n\n/**\n * Options needed for metric creation\n */\nexport interface MetricOptions {\n /**\n * The description of the Metric.\n * @default ''\n */\n description?: string;\n\n /**\n * The unit of the Metric values.\n * @default ''\n */\n unit?: string;\n\n /**\n * Indicates the type of the recorded value.\n * @default {@link ValueType.DOUBLE}\n */\n valueType?: ValueType;\n\n /**\n * The advice influencing aggregation configuration parameters.\n * @experimental\n */\n advice?: MetricAdvice;\n}\n\n/** The Type of value. It describes how the data is reported. */\nexport enum ValueType {\n INT,\n DOUBLE,\n}\n\n/**\n * Counter is the most common synchronous instrument. This instrument supports\n * an `Add(increment)` function for reporting a sum, and is restricted to\n * non-negative increments. The default aggregation is Sum, as for any additive\n * instrument.\n *\n * Example uses for Counter:\n *
                        \n *
                      1. count the number of bytes received.
                      2. \n *
                      3. count the number of requests completed.
                      4. \n *
                      5. count the number of accounts created.
                      6. \n *
                      7. count the number of checkpoints run.
                      8. \n *
                      9. count the number of 5xx errors.
                      10. \n *
                          \n */\nexport interface Counter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Increment value of counter by the input. Inputs must not be negative.\n */\n add(value: number, attributes?: AttributesTypes, context?: Context): void;\n}\n\nexport interface UpDownCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Increment value of counter by the input. Inputs may be negative.\n */\n add(value: number, attributes?: AttributesTypes, context?: Context): void;\n}\n\nexport interface Gauge<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Records a measurement.\n */\n record(value: number, attributes?: AttributesTypes, context?: Context): void;\n}\n\nexport interface Histogram<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Records a measurement. Value of the measurement must not be negative.\n */\n record(value: number, attributes?: AttributesTypes, context?: Context): void;\n}\n\n/**\n * @deprecated please use {@link Attributes}\n */\nexport type MetricAttributes = Attributes;\n\n/**\n * @deprecated please use {@link AttributeValue}\n */\nexport type MetricAttributeValue = AttributeValue;\n\n/**\n * The observable callback for Observable instruments.\n */\nexport type ObservableCallback<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> = (\n observableResult: ObservableResult\n) => void | Promise;\n\n/**\n * The observable callback for a batch of Observable instruments.\n */\nexport type BatchObservableCallback<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> = (\n observableResult: BatchObservableResult\n) => void | Promise;\n\nexport interface Observable<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Sets up a function that will be called whenever a metric collection is initiated.\n *\n * If the function is already in the list of callbacks for this Observable, the function is not added a second time.\n */\n addCallback(callback: ObservableCallback): void;\n\n /**\n * Removes a callback previously registered with {@link Observable.addCallback}.\n */\n removeCallback(callback: ObservableCallback): void;\n}\n\nexport type ObservableCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> = Observable;\nexport type ObservableUpDownCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> = Observable;\nexport type ObservableGauge<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> = Observable;\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.d.ts b/node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.d.ts new file mode 100644 index 0000000..bbefa9a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.d.ts @@ -0,0 +1,82 @@ +import { Meter } from './Meter'; +import { BatchObservableCallback, Counter, Gauge, Histogram, MetricAttributes, MetricOptions, Observable, ObservableCallback, ObservableCounter, ObservableGauge, ObservableUpDownCounter, UpDownCounter } from './Metric'; +/** + * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses + * constant NoopMetrics for all of its methods. + */ +export declare class NoopMeter implements Meter { + constructor(); + /** + * @see {@link Meter.createGauge} + */ + createGauge(_name: string, _options?: MetricOptions): Gauge; + /** + * @see {@link Meter.createHistogram} + */ + createHistogram(_name: string, _options?: MetricOptions): Histogram; + /** + * @see {@link Meter.createCounter} + */ + createCounter(_name: string, _options?: MetricOptions): Counter; + /** + * @see {@link Meter.createUpDownCounter} + */ + createUpDownCounter(_name: string, _options?: MetricOptions): UpDownCounter; + /** + * @see {@link Meter.createObservableGauge} + */ + createObservableGauge(_name: string, _options?: MetricOptions): ObservableGauge; + /** + * @see {@link Meter.createObservableCounter} + */ + createObservableCounter(_name: string, _options?: MetricOptions): ObservableCounter; + /** + * @see {@link Meter.createObservableUpDownCounter} + */ + createObservableUpDownCounter(_name: string, _options?: MetricOptions): ObservableUpDownCounter; + /** + * @see {@link Meter.addBatchObservableCallback} + */ + addBatchObservableCallback(_callback: BatchObservableCallback, _observables: Observable[]): void; + /** + * @see {@link Meter.removeBatchObservableCallback} + */ + removeBatchObservableCallback(_callback: BatchObservableCallback): void; +} +export declare class NoopMetric { +} +export declare class NoopCounterMetric extends NoopMetric implements Counter { + add(_value: number, _attributes: MetricAttributes): void; +} +export declare class NoopUpDownCounterMetric extends NoopMetric implements UpDownCounter { + add(_value: number, _attributes: MetricAttributes): void; +} +export declare class NoopGaugeMetric extends NoopMetric implements Gauge { + record(_value: number, _attributes: MetricAttributes): void; +} +export declare class NoopHistogramMetric extends NoopMetric implements Histogram { + record(_value: number, _attributes: MetricAttributes): void; +} +export declare class NoopObservableMetric { + addCallback(_callback: ObservableCallback): void; + removeCallback(_callback: ObservableCallback): void; +} +export declare class NoopObservableCounterMetric extends NoopObservableMetric implements ObservableCounter { +} +export declare class NoopObservableGaugeMetric extends NoopObservableMetric implements ObservableGauge { +} +export declare class NoopObservableUpDownCounterMetric extends NoopObservableMetric implements ObservableUpDownCounter { +} +export declare const NOOP_METER: NoopMeter; +export declare const NOOP_COUNTER_METRIC: NoopCounterMetric; +export declare const NOOP_GAUGE_METRIC: NoopGaugeMetric; +export declare const NOOP_HISTOGRAM_METRIC: NoopHistogramMetric; +export declare const NOOP_UP_DOWN_COUNTER_METRIC: NoopUpDownCounterMetric; +export declare const NOOP_OBSERVABLE_COUNTER_METRIC: NoopObservableCounterMetric; +export declare const NOOP_OBSERVABLE_GAUGE_METRIC: NoopObservableGaugeMetric; +export declare const NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC: NoopObservableUpDownCounterMetric; +/** + * Create a no-op Meter + */ +export declare function createNoopMeter(): Meter; +//# sourceMappingURL=NoopMeter.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js b/node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js new file mode 100644 index 0000000..d40ef03 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js @@ -0,0 +1,127 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createNoopMeter = exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports.NOOP_OBSERVABLE_GAUGE_METRIC = exports.NOOP_OBSERVABLE_COUNTER_METRIC = exports.NOOP_UP_DOWN_COUNTER_METRIC = exports.NOOP_HISTOGRAM_METRIC = exports.NOOP_GAUGE_METRIC = exports.NOOP_COUNTER_METRIC = exports.NOOP_METER = exports.NoopObservableUpDownCounterMetric = exports.NoopObservableGaugeMetric = exports.NoopObservableCounterMetric = exports.NoopObservableMetric = exports.NoopHistogramMetric = exports.NoopGaugeMetric = exports.NoopUpDownCounterMetric = exports.NoopCounterMetric = exports.NoopMetric = exports.NoopMeter = void 0; +/** + * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses + * constant NoopMetrics for all of its methods. + */ +class NoopMeter { + constructor() { } + /** + * @see {@link Meter.createGauge} + */ + createGauge(_name, _options) { + return exports.NOOP_GAUGE_METRIC; + } + /** + * @see {@link Meter.createHistogram} + */ + createHistogram(_name, _options) { + return exports.NOOP_HISTOGRAM_METRIC; + } + /** + * @see {@link Meter.createCounter} + */ + createCounter(_name, _options) { + return exports.NOOP_COUNTER_METRIC; + } + /** + * @see {@link Meter.createUpDownCounter} + */ + createUpDownCounter(_name, _options) { + return exports.NOOP_UP_DOWN_COUNTER_METRIC; + } + /** + * @see {@link Meter.createObservableGauge} + */ + createObservableGauge(_name, _options) { + return exports.NOOP_OBSERVABLE_GAUGE_METRIC; + } + /** + * @see {@link Meter.createObservableCounter} + */ + createObservableCounter(_name, _options) { + return exports.NOOP_OBSERVABLE_COUNTER_METRIC; + } + /** + * @see {@link Meter.createObservableUpDownCounter} + */ + createObservableUpDownCounter(_name, _options) { + return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; + } + /** + * @see {@link Meter.addBatchObservableCallback} + */ + addBatchObservableCallback(_callback, _observables) { } + /** + * @see {@link Meter.removeBatchObservableCallback} + */ + removeBatchObservableCallback(_callback) { } +} +exports.NoopMeter = NoopMeter; +class NoopMetric { +} +exports.NoopMetric = NoopMetric; +class NoopCounterMetric extends NoopMetric { + add(_value, _attributes) { } +} +exports.NoopCounterMetric = NoopCounterMetric; +class NoopUpDownCounterMetric extends NoopMetric { + add(_value, _attributes) { } +} +exports.NoopUpDownCounterMetric = NoopUpDownCounterMetric; +class NoopGaugeMetric extends NoopMetric { + record(_value, _attributes) { } +} +exports.NoopGaugeMetric = NoopGaugeMetric; +class NoopHistogramMetric extends NoopMetric { + record(_value, _attributes) { } +} +exports.NoopHistogramMetric = NoopHistogramMetric; +class NoopObservableMetric { + addCallback(_callback) { } + removeCallback(_callback) { } +} +exports.NoopObservableMetric = NoopObservableMetric; +class NoopObservableCounterMetric extends NoopObservableMetric { +} +exports.NoopObservableCounterMetric = NoopObservableCounterMetric; +class NoopObservableGaugeMetric extends NoopObservableMetric { +} +exports.NoopObservableGaugeMetric = NoopObservableGaugeMetric; +class NoopObservableUpDownCounterMetric extends NoopObservableMetric { +} +exports.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric; +exports.NOOP_METER = new NoopMeter(); +// Synchronous instruments +exports.NOOP_COUNTER_METRIC = new NoopCounterMetric(); +exports.NOOP_GAUGE_METRIC = new NoopGaugeMetric(); +exports.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric(); +exports.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric(); +// Asynchronous instruments +exports.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric(); +exports.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric(); +exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric(); +/** + * Create a no-op Meter + */ +function createNoopMeter() { + return exports.NOOP_METER; +} +exports.createNoopMeter = createNoopMeter; +//# sourceMappingURL=NoopMeter.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js.map b/node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js.map new file mode 100644 index 0000000..512d5fe --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NoopMeter.js","sourceRoot":"","sources":["../../../src/metrics/NoopMeter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAkBH;;;GAGG;AACH,MAAa,SAAS;IACpB,gBAAe,CAAC;IAEhB;;OAEG;IACH,WAAW,CAAC,KAAa,EAAE,QAAwB;QACjD,OAAO,yBAAiB,CAAC;IAC3B,CAAC;IAED;;OAEG;IACH,eAA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,oBAAoB;CACG;AAFjC,kEAEiC;AAEjC,MAAa,yBACX,SAAQ,oBAAoB;CACC;AAF/B,8DAE+B;AAE/B,MAAa,iCACX,SAAQ,oBAAoB;CACS;AAFvC,8EAEuC;AAE1B,QAAA,UAAU,GAAG,IAAI,SAAS,EAAE,CAAC;AAE1C,0BAA0B;AACb,QAAA,mBAAmB,GAAG,IAAI,iBAAiB,EAAE,CAAC;AAC9C,QAAA,iBAAiB,GAAG,IAAI,eAAe,EAAE,CAAC;AAC1C,QAAA,qBAAqB,GAAG,IAAI,mBAAmB,EAAE,CAAC;AAClD,QAAA,2BAA2B,GAAG,IAAI,uBAAuB,EAAE,CAAC;AAEzE,2BAA2B;AACd,QAAA,8BAA8B,GAAG,IAAI,2BAA2B,EAAE,CAAC;AACnE,QAAA,4BAA4B,GAAG,IAAI,yBAAyB,EAAE,CAAC;AAC/D,QAAA,sCAAsC,GACjD,IAAI,iCAAiC,EAAE,CAAC;AAE1C;;GAEG;AACH,SAAgB,eAAe;IAC7B,OAAO,kBAAU,CAAC;AACpB,CAAC;AAFD,0CAEC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Meter } from './Meter';\nimport {\n BatchObservableCallback,\n Counter,\n Gauge,\n Histogram,\n MetricAttributes,\n MetricOptions,\n Observable,\n ObservableCallback,\n ObservableCounter,\n ObservableGauge,\n ObservableUpDownCounter,\n UpDownCounter,\n} from './Metric';\n\n/**\n * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses\n * constant NoopMetrics for all of its methods.\n */\nexport class NoopMeter implements Meter {\n constructor() {}\n\n /**\n * @see {@link Meter.createGauge}\n */\n createGauge(_name: string, _options?: MetricOptions): Gauge {\n return NOOP_GAUGE_METRIC;\n }\n\n /**\n * @see {@link Meter.createHistogram}\n */\n createHistogram(_name: string, _options?: MetricOptions): Histogram {\n return NOOP_HISTOGRAM_METRIC;\n }\n\n /**\n * @see {@link Meter.createCounter}\n */\n createCounter(_name: string, _options?: MetricOptions): Counter {\n return NOOP_COUNTER_METRIC;\n }\n\n /**\n * @see {@link Meter.createUpDownCounter}\n */\n createUpDownCounter(_name: string, _options?: MetricOptions): UpDownCounter {\n return NOOP_UP_DOWN_COUNTER_METRIC;\n }\n\n /**\n * @see {@link Meter.createObservableGauge}\n */\n createObservableGauge(\n _name: string,\n _options?: MetricOptions\n ): ObservableGauge {\n return NOOP_OBSERVABLE_GAUGE_METRIC;\n }\n\n /**\n * @see {@link Meter.createObservableCounter}\n */\n createObservableCounter(\n _name: string,\n _options?: MetricOptions\n ): ObservableCounter {\n return NOOP_OBSERVABLE_COUNTER_METRIC;\n }\n\n /**\n * @see {@link Meter.createObservableUpDownCounter}\n */\n createObservableUpDownCounter(\n _name: string,\n _options?: MetricOptions\n ): ObservableUpDownCounter {\n return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;\n }\n\n /**\n * @see {@link Meter.addBatchObservableCallback}\n */\n addBatchObservableCallback(\n _callback: BatchObservableCallback,\n _observables: Observable[]\n ): void {}\n\n /**\n * @see {@link Meter.removeBatchObservableCallback}\n */\n removeBatchObservableCallback(_callback: BatchObservableCallback): void {}\n}\n\nexport class NoopMetric {}\n\nexport class NoopCounterMetric extends NoopMetric implements Counter {\n add(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopUpDownCounterMetric\n extends NoopMetric\n implements UpDownCounter\n{\n add(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopGaugeMetric extends NoopMetric implements Gauge {\n record(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopHistogramMetric extends NoopMetric implements Histogram {\n record(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopObservableMetric {\n addCallback(_callback: ObservableCallback) {}\n\n removeCallback(_callback: ObservableCallback) {}\n}\n\nexport class NoopObservableCounterMetric\n extends NoopObservableMetric\n implements ObservableCounter {}\n\nexport class NoopObservableGaugeMetric\n extends NoopObservableMetric\n implements ObservableGauge {}\n\nexport class NoopObservableUpDownCounterMetric\n extends NoopObservableMetric\n implements ObservableUpDownCounter {}\n\nexport const NOOP_METER = new NoopMeter();\n\n// Synchronous instruments\nexport const NOOP_COUNTER_METRIC = new NoopCounterMetric();\nexport const NOOP_GAUGE_METRIC = new NoopGaugeMetric();\nexport const NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric();\nexport const NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric();\n\n// Asynchronous instruments\nexport const NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric();\nexport const NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric();\nexport const NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC =\n new NoopObservableUpDownCounterMetric();\n\n/**\n * Create a no-op Meter\n */\nexport function createNoopMeter(): Meter {\n return NOOP_METER;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.d.ts b/node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.d.ts new file mode 100644 index 0000000..8b51bc5 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.d.ts @@ -0,0 +1,11 @@ +import { Meter, MeterOptions } from './Meter'; +import { MeterProvider } from './MeterProvider'; +/** + * An implementation of the {@link MeterProvider} which returns an impotent Meter + * for all calls to `getMeter` + */ +export declare class NoopMeterProvider implements MeterProvider { + getMeter(_name: string, _version?: string, _options?: MeterOptions): Meter; +} +export declare const NOOP_METER_PROVIDER: NoopMeterProvider; +//# sourceMappingURL=NoopMeterProvider.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js b/node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js new file mode 100644 index 0000000..b1c1cc0 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js @@ -0,0 +1,31 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NOOP_METER_PROVIDER = exports.NoopMeterProvider = void 0; +const NoopMeter_1 = require("./NoopMeter"); +/** + * An implementation of the {@link MeterProvider} which returns an impotent Meter + * for all calls to `getMeter` + */ +class NoopMeterProvider { + getMeter(_name, _version, _options) { + return NoopMeter_1.NOOP_METER; + } +} +exports.NoopMeterProvider = NoopMeterProvider; +exports.NOOP_METER_PROVIDER = new NoopMeterProvider(); +//# sourceMappingURL=NoopMeterProvider.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js.map b/node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js.map new file mode 100644 index 0000000..66117d0 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NoopMeterProvider.js","sourceRoot":"","sources":["../../../src/metrics/NoopMeterProvider.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAIH,2CAAyC;AAEzC;;;GAGG;AACH,MAAa,iBAAiB;IAC5B,QAAQ,CAAC,KAAa,EAAE,QAAiB,EAAE,QAAuB;QAChE,OAAO,sBAAU,CAAC;IACpB,CAAC;CACF;AAJD,8CAIC;AAEY,QAAA,mBAAmB,GAAG,IAAI,iBAAiB,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Meter, MeterOptions } from './Meter';\nimport { MeterProvider } from './MeterProvider';\nimport { NOOP_METER } from './NoopMeter';\n\n/**\n * An implementation of the {@link MeterProvider} which returns an impotent Meter\n * for all calls to `getMeter`\n */\nexport class NoopMeterProvider implements MeterProvider {\n getMeter(_name: string, _version?: string, _options?: MeterOptions): Meter {\n return NOOP_METER;\n }\n}\n\nexport const NOOP_METER_PROVIDER = new NoopMeterProvider();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics/ObservableResult.d.ts b/node_modules/@opentelemetry/api/build/src/metrics/ObservableResult.d.ts new file mode 100644 index 0000000..26563f9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics/ObservableResult.d.ts @@ -0,0 +1,31 @@ +import { MetricAttributes, Observable } from './Metric'; +/** + * Interface that is being used in callback function for Observable Metric. + */ +export interface ObservableResult { + /** + * Observe a measurement of the value associated with the given attributes. + * + * @param value The value to be observed. + * @param attributes The attributes associated with the value. If more than + * one values associated with the same attributes values, SDK may pick the + * last one or simply drop the entire observable result. + */ + observe(this: ObservableResult, value: number, attributes?: AttributesTypes): void; +} +/** + * Interface that is being used in batch observable callback function. + */ +export interface BatchObservableResult { + /** + * Observe a measurement of the value associated with the given attributes. + * + * @param metric The observable metric to be observed. + * @param value The value to be observed. + * @param attributes The attributes associated with the value. If more than + * one values associated with the same attributes values, SDK may pick the + * last one or simply drop the entire observable result. + */ + observe(this: BatchObservableResult, metric: Observable, value: number, attributes?: AttributesTypes): void; +} +//# sourceMappingURL=ObservableResult.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics/ObservableResult.js b/node_modules/@opentelemetry/api/build/src/metrics/ObservableResult.js new file mode 100644 index 0000000..7e5cbd0 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics/ObservableResult.js @@ -0,0 +1,18 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=ObservableResult.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/metrics/ObservableResult.js.map b/node_modules/@opentelemetry/api/build/src/metrics/ObservableResult.js.map new file mode 100644 index 0000000..450ef74 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/metrics/ObservableResult.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ObservableResult.js","sourceRoot":"","sources":["../../../src/metrics/ObservableResult.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MetricAttributes, Observable } from './Metric';\n\n/**\n * Interface that is being used in callback function for Observable Metric.\n */\nexport interface ObservableResult<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Observe a measurement of the value associated with the given attributes.\n *\n * @param value The value to be observed.\n * @param attributes The attributes associated with the value. If more than\n * one values associated with the same attributes values, SDK may pick the\n * last one or simply drop the entire observable result.\n */\n observe(\n this: ObservableResult,\n value: number,\n attributes?: AttributesTypes\n ): void;\n}\n\n/**\n * Interface that is being used in batch observable callback function.\n */\nexport interface BatchObservableResult<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Observe a measurement of the value associated with the given attributes.\n *\n * @param metric The observable metric to be observed.\n * @param value The value to be observed.\n * @param attributes The attributes associated with the value. If more than\n * one values associated with the same attributes values, SDK may pick the\n * last one or simply drop the entire observable result.\n */\n observe(\n this: BatchObservableResult,\n metric: Observable,\n value: number,\n attributes?: AttributesTypes\n ): void;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/platform/browser/globalThis.d.ts b/node_modules/@opentelemetry/api/build/src/platform/browser/globalThis.d.ts new file mode 100644 index 0000000..e73fd73 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/platform/browser/globalThis.d.ts @@ -0,0 +1,10 @@ +/** + * - globalThis (New standard) + * - self (Will return the current window instance for supported browsers) + * - window (fallback for older browser implementations) + * - global (NodeJS implementation) + * - (When all else fails) + */ +/** only globals that common to node and browsers are allowed */ +export declare const _globalThis: typeof globalThis; +//# sourceMappingURL=globalThis.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/platform/browser/globalThis.js b/node_modules/@opentelemetry/api/build/src/platform/browser/globalThis.js new file mode 100644 index 0000000..15c8d21 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/platform/browser/globalThis.js @@ -0,0 +1,38 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports._globalThis = void 0; +// Updates to this file should also be replicated to @opentelemetry/core too. +/** + * - globalThis (New standard) + * - self (Will return the current window instance for supported browsers) + * - window (fallback for older browser implementations) + * - global (NodeJS implementation) + * - (When all else fails) + */ +/** only globals that common to node and browsers are allowed */ +// eslint-disable-next-line node/no-unsupported-features/es-builtins, no-undef +exports._globalThis = typeof globalThis === 'object' + ? globalThis + : typeof self === 'object' + ? self + : typeof window === 'object' + ? window + : typeof global === 'object' + ? global + : {}; +//# sourceMappingURL=globalThis.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/platform/browser/globalThis.js.map b/node_modules/@opentelemetry/api/build/src/platform/browser/globalThis.js.map new file mode 100644 index 0000000..1c02509 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/platform/browser/globalThis.js.map @@ -0,0 +1 @@ +{"version":3,"file":"globalThis.js","sourceRoot":"","sources":["../../../../src/platform/browser/globalThis.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,6EAA6E;AAE7E;;;;;;GAMG;AAEH,gEAAgE;AAChE,8EAA8E;AACjE,QAAA,WAAW,GACtB,OAAO,UAAU,KAAK,QAAQ;IAC5B,CAAC,CAAC,UAAU;IACZ,CAAC,CAAC,OAAO,IAAI,KAAK,QAAQ;QAC1B,CAAC,CAAC,IAAI;QACN,CAAC,CAAC,OAAO,MAAM,KAAK,QAAQ;YAC5B,CAAC,CAAC,MAAM;YACR,CAAC,CAAC,OAAO,MAAM,KAAK,QAAQ;gBAC5B,CAAC,CAAC,MAAM;gBACR,CAAC,CAAE,EAAwB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Updates to this file should also be replicated to @opentelemetry/core too.\n\n/**\n * - globalThis (New standard)\n * - self (Will return the current window instance for supported browsers)\n * - window (fallback for older browser implementations)\n * - global (NodeJS implementation)\n * - (When all else fails)\n */\n\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins, no-undef\nexport const _globalThis: typeof globalThis =\n typeof globalThis === 'object'\n ? globalThis\n : typeof self === 'object'\n ? self\n : typeof window === 'object'\n ? window\n : typeof global === 'object'\n ? global\n : ({} as typeof globalThis);\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/platform/browser/index.d.ts b/node_modules/@opentelemetry/api/build/src/platform/browser/index.d.ts new file mode 100644 index 0000000..ba20e12 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/platform/browser/index.d.ts @@ -0,0 +1,2 @@ +export * from './globalThis'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/platform/browser/index.js b/node_modules/@opentelemetry/api/build/src/platform/browser/index.js new file mode 100644 index 0000000..99fd57c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/platform/browser/index.js @@ -0,0 +1,29 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./globalThis"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/platform/browser/index.js.map b/node_modules/@opentelemetry/api/build/src/platform/browser/index.js.map new file mode 100644 index 0000000..5a406a9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/platform/browser/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/browser/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;AAEH,+CAA6B","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './globalThis';\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/platform/index.d.ts b/node_modules/@opentelemetry/api/build/src/platform/index.d.ts new file mode 100644 index 0000000..90595da --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/platform/index.d.ts @@ -0,0 +1,2 @@ +export * from './node'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/platform/index.js b/node_modules/@opentelemetry/api/build/src/platform/index.js new file mode 100644 index 0000000..33b834d --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/platform/index.js @@ -0,0 +1,29 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./node"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/platform/index.js.map b/node_modules/@opentelemetry/api/build/src/platform/index.js.map new file mode 100644 index 0000000..bc13701 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/platform/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/platform/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;AAEH,yCAAuB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './node';\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/platform/node/globalThis.d.ts b/node_modules/@opentelemetry/api/build/src/platform/node/globalThis.d.ts new file mode 100644 index 0000000..e3c83e5 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/platform/node/globalThis.d.ts @@ -0,0 +1,3 @@ +/** only globals that common to node and browsers are allowed */ +export declare const _globalThis: typeof globalThis; +//# sourceMappingURL=globalThis.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/platform/node/globalThis.js b/node_modules/@opentelemetry/api/build/src/platform/node/globalThis.js new file mode 100644 index 0000000..82c4e39 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/platform/node/globalThis.js @@ -0,0 +1,22 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports._globalThis = void 0; +/** only globals that common to node and browsers are allowed */ +// eslint-disable-next-line node/no-unsupported-features/es-builtins +exports._globalThis = typeof globalThis === 'object' ? globalThis : global; +//# sourceMappingURL=globalThis.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/platform/node/globalThis.js.map b/node_modules/@opentelemetry/api/build/src/platform/node/globalThis.js.map new file mode 100644 index 0000000..2f2ca82 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/platform/node/globalThis.js.map @@ -0,0 +1 @@ +{"version":3,"file":"globalThis.js","sourceRoot":"","sources":["../../../../src/platform/node/globalThis.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,gEAAgE;AAChE,oEAAoE;AACvD,QAAA,WAAW,GAAG,OAAO,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/platform/node/index.d.ts b/node_modules/@opentelemetry/api/build/src/platform/node/index.d.ts new file mode 100644 index 0000000..ba20e12 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/platform/node/index.d.ts @@ -0,0 +1,2 @@ +export * from './globalThis'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/platform/node/index.js b/node_modules/@opentelemetry/api/build/src/platform/node/index.js new file mode 100644 index 0000000..99fd57c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/platform/node/index.js @@ -0,0 +1,29 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./globalThis"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/platform/node/index.js.map b/node_modules/@opentelemetry/api/build/src/platform/node/index.js.map new file mode 100644 index 0000000..95561e9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/platform/node/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/node/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;AAEH,+CAA6B","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './globalThis';\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/propagation-api.d.ts b/node_modules/@opentelemetry/api/build/src/propagation-api.d.ts new file mode 100644 index 0000000..e12b51b --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/propagation-api.d.ts @@ -0,0 +1,4 @@ +import { PropagationAPI } from './api/propagation'; +/** Entrypoint for propagation API */ +export declare const propagation: PropagationAPI; +//# sourceMappingURL=propagation-api.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/propagation-api.js b/node_modules/@opentelemetry/api/build/src/propagation-api.js new file mode 100644 index 0000000..f014fb4 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/propagation-api.js @@ -0,0 +1,24 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.propagation = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const propagation_1 = require("./api/propagation"); +/** Entrypoint for propagation API */ +exports.propagation = propagation_1.PropagationAPI.getInstance(); +//# sourceMappingURL=propagation-api.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/propagation-api.js.map b/node_modules/@opentelemetry/api/build/src/propagation-api.js.map new file mode 100644 index 0000000..ff17b74 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/propagation-api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"propagation-api.js","sourceRoot":"","sources":["../../src/propagation-api.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,sEAAsE;AACtE,qCAAqC;AACrC,mDAAmD;AACnD,qCAAqC;AACxB,QAAA,WAAW,GAAG,4BAAc,CAAC,WAAW,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { PropagationAPI } from './api/propagation';\n/** Entrypoint for propagation API */\nexport const propagation = PropagationAPI.getInstance();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.d.ts b/node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.d.ts new file mode 100644 index 0000000..398021f --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.d.ts @@ -0,0 +1,13 @@ +import { Context } from '../context/types'; +import { TextMapPropagator } from './TextMapPropagator'; +/** + * No-op implementations of {@link TextMapPropagator}. + */ +export declare class NoopTextMapPropagator implements TextMapPropagator { + /** Noop inject function does nothing */ + inject(_context: Context, _carrier: unknown): void; + /** Noop extract function does nothing and returns the input context */ + extract(context: Context, _carrier: unknown): Context; + fields(): string[]; +} +//# sourceMappingURL=NoopTextMapPropagator.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js b/node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js new file mode 100644 index 0000000..3f39582 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js @@ -0,0 +1,34 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NoopTextMapPropagator = void 0; +/** + * No-op implementations of {@link TextMapPropagator}. + */ +class NoopTextMapPropagator { + /** Noop inject function does nothing */ + inject(_context, _carrier) { } + /** Noop extract function does nothing and returns the input context */ + extract(context, _carrier) { + return context; + } + fields() { + return []; + } +} +exports.NoopTextMapPropagator = NoopTextMapPropagator; +//# sourceMappingURL=NoopTextMapPropagator.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js.map b/node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js.map new file mode 100644 index 0000000..dfd01aa --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NoopTextMapPropagator.js","sourceRoot":"","sources":["../../../src/propagation/NoopTextMapPropagator.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAKH;;GAEG;AACH,MAAa,qBAAqB;IAChC,wCAAwC;IACxC,MAAM,CAAC,QAAiB,EAAE,QAAiB,IAAS,CAAC;IACrD,uEAAuE;IACvE,OAAO,CAAC,OAAgB,EAAE,QAAiB;QACzC,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,MAAM;QACJ,OAAO,EAAE,CAAC;IACZ,CAAC;CACF;AAVD,sDAUC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport { TextMapPropagator } from './TextMapPropagator';\n\n/**\n * No-op implementations of {@link TextMapPropagator}.\n */\nexport class NoopTextMapPropagator implements TextMapPropagator {\n /** Noop inject function does nothing */\n inject(_context: Context, _carrier: unknown): void {}\n /** Noop extract function does nothing and returns the input context */\n extract(context: Context, _carrier: unknown): Context {\n return context;\n }\n fields(): string[] {\n return [];\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.d.ts b/node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.d.ts new file mode 100644 index 0000000..dc39367 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.d.ts @@ -0,0 +1,84 @@ +import { Context } from '../context/types'; +/** + * Injects `Context` into and extracts it from carriers that travel + * in-band across process boundaries. Encoding is expected to conform to the + * HTTP Header Field semantics. Values are often encoded as RPC/HTTP request + * headers. + * + * The carrier of propagated data on both the client (injector) and server + * (extractor) side is usually an object such as http headers. Propagation is + * usually implemented via library-specific request interceptors, where the + * client-side injects values and the server-side extracts them. + */ +export interface TextMapPropagator { + /** + * Injects values from a given `Context` into a carrier. + * + * OpenTelemetry defines a common set of format values (TextMapPropagator), + * and each has an expected `carrier` type. + * + * @param context the Context from which to extract values to transmit over + * the wire. + * @param carrier the carrier of propagation fields, such as http request + * headers. + * @param setter an optional {@link TextMapSetter}. If undefined, values will be + * set by direct object assignment. + */ + inject(context: Context, carrier: Carrier, setter: TextMapSetter): void; + /** + * Given a `Context` and a carrier, extract context values from a + * carrier and return a new context, created from the old context, with the + * extracted values. + * + * @param context the Context from which to extract values to transmit over + * the wire. + * @param carrier the carrier of propagation fields, such as http request + * headers. + * @param getter an optional {@link TextMapGetter}. If undefined, keys will be all + * own properties, and keys will be accessed by direct object access. + */ + extract(context: Context, carrier: Carrier, getter: TextMapGetter): Context; + /** + * Return a list of all fields which may be used by the propagator. + */ + fields(): string[]; +} +/** + * A setter is specified by the caller to define a specific method + * to set key/value pairs on the carrier within a propagator. + */ +export interface TextMapSetter { + /** + * Callback used to set a key/value pair on an object. + * + * Should be called by the propagator each time a key/value pair + * should be set, and should set that key/value pair on the propagator. + * + * @param carrier object or class which carries key/value pairs + * @param key string key to modify + * @param value value to be set to the key on the carrier + */ + set(carrier: Carrier, key: string, value: string): void; +} +/** + * A getter is specified by the caller to define a specific method + * to get the value of a key from a carrier. + */ +export interface TextMapGetter { + /** + * Get a list of all keys available on the carrier. + * + * @param carrier + */ + keys(carrier: Carrier): string[]; + /** + * Get the value of a specific key from the carrier. + * + * @param carrier + * @param key + */ + get(carrier: Carrier, key: string): undefined | string | string[]; +} +export declare const defaultTextMapGetter: TextMapGetter; +export declare const defaultTextMapSetter: TextMapSetter; +//# sourceMappingURL=TextMapPropagator.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js b/node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js new file mode 100644 index 0000000..513f33c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js @@ -0,0 +1,41 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultTextMapSetter = exports.defaultTextMapGetter = void 0; +exports.defaultTextMapGetter = { + get(carrier, key) { + if (carrier == null) { + return undefined; + } + return carrier[key]; + }, + keys(carrier) { + if (carrier == null) { + return []; + } + return Object.keys(carrier); + }, +}; +exports.defaultTextMapSetter = { + set(carrier, key, value) { + if (carrier == null) { + return; + } + carrier[key] = value; + }, +}; +//# sourceMappingURL=TextMapPropagator.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js.map b/node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js.map new file mode 100644 index 0000000..f233435 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"TextMapPropagator.js","sourceRoot":"","sources":["../../../src/propagation/TextMapPropagator.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAkGU,QAAA,oBAAoB,GAAkB;IACjD,GAAG,CAAC,OAAO,EAAE,GAAG;QACd,IAAI,OAAO,IAAI,IAAI,EAAE;YACnB,OAAO,SAAS,CAAC;SAClB;QACD,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC;IACtB,CAAC;IAED,IAAI,CAAC,OAAO;QACV,IAAI,OAAO,IAAI,IAAI,EAAE;YACnB,OAAO,EAAE,CAAC;SACX;QACD,OAAO,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC9B,CAAC;CACF,CAAC;AAEW,QAAA,oBAAoB,GAAkB;IACjD,GAAG,CAAC,OAAO,EAAE,GAAG,EAAE,KAAK;QACrB,IAAI,OAAO,IAAI,IAAI,EAAE;YACnB,OAAO;SACR;QAED,OAAO,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IACvB,CAAC;CACF,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\n\n/**\n * Injects `Context` into and extracts it from carriers that travel\n * in-band across process boundaries. Encoding is expected to conform to the\n * HTTP Header Field semantics. Values are often encoded as RPC/HTTP request\n * headers.\n *\n * The carrier of propagated data on both the client (injector) and server\n * (extractor) side is usually an object such as http headers. Propagation is\n * usually implemented via library-specific request interceptors, where the\n * client-side injects values and the server-side extracts them.\n */\nexport interface TextMapPropagator {\n /**\n * Injects values from a given `Context` into a carrier.\n *\n * OpenTelemetry defines a common set of format values (TextMapPropagator),\n * and each has an expected `carrier` type.\n *\n * @param context the Context from which to extract values to transmit over\n * the wire.\n * @param carrier the carrier of propagation fields, such as http request\n * headers.\n * @param setter an optional {@link TextMapSetter}. If undefined, values will be\n * set by direct object assignment.\n */\n inject(\n context: Context,\n carrier: Carrier,\n setter: TextMapSetter\n ): void;\n\n /**\n * Given a `Context` and a carrier, extract context values from a\n * carrier and return a new context, created from the old context, with the\n * extracted values.\n *\n * @param context the Context from which to extract values to transmit over\n * the wire.\n * @param carrier the carrier of propagation fields, such as http request\n * headers.\n * @param getter an optional {@link TextMapGetter}. If undefined, keys will be all\n * own properties, and keys will be accessed by direct object access.\n */\n extract(\n context: Context,\n carrier: Carrier,\n getter: TextMapGetter\n ): Context;\n\n /**\n * Return a list of all fields which may be used by the propagator.\n */\n fields(): string[];\n}\n\n/**\n * A setter is specified by the caller to define a specific method\n * to set key/value pairs on the carrier within a propagator.\n */\nexport interface TextMapSetter {\n /**\n * Callback used to set a key/value pair on an object.\n *\n * Should be called by the propagator each time a key/value pair\n * should be set, and should set that key/value pair on the propagator.\n *\n * @param carrier object or class which carries key/value pairs\n * @param key string key to modify\n * @param value value to be set to the key on the carrier\n */\n set(carrier: Carrier, key: string, value: string): void;\n}\n\n/**\n * A getter is specified by the caller to define a specific method\n * to get the value of a key from a carrier.\n */\nexport interface TextMapGetter {\n /**\n * Get a list of all keys available on the carrier.\n *\n * @param carrier\n */\n keys(carrier: Carrier): string[];\n\n /**\n * Get the value of a specific key from the carrier.\n *\n * @param carrier\n * @param key\n */\n get(carrier: Carrier, key: string): undefined | string | string[];\n}\n\nexport const defaultTextMapGetter: TextMapGetter = {\n get(carrier, key) {\n if (carrier == null) {\n return undefined;\n }\n return carrier[key];\n },\n\n keys(carrier) {\n if (carrier == null) {\n return [];\n }\n return Object.keys(carrier);\n },\n};\n\nexport const defaultTextMapSetter: TextMapSetter = {\n set(carrier, key, value) {\n if (carrier == null) {\n return;\n }\n\n carrier[key] = value;\n },\n};\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace-api.d.ts b/node_modules/@opentelemetry/api/build/src/trace-api.d.ts new file mode 100644 index 0000000..b4751a7 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace-api.d.ts @@ -0,0 +1,4 @@ +import { TraceAPI } from './api/trace'; +/** Entrypoint for trace API */ +export declare const trace: TraceAPI; +//# sourceMappingURL=trace-api.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace-api.js b/node_modules/@opentelemetry/api/build/src/trace-api.js new file mode 100644 index 0000000..c8bbe93 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace-api.js @@ -0,0 +1,24 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.trace = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const trace_1 = require("./api/trace"); +/** Entrypoint for trace API */ +exports.trace = trace_1.TraceAPI.getInstance(); +//# sourceMappingURL=trace-api.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace-api.js.map b/node_modules/@opentelemetry/api/build/src/trace-api.js.map new file mode 100644 index 0000000..2475b59 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace-api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-api.js","sourceRoot":"","sources":["../../src/trace-api.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,sEAAsE;AACtE,qCAAqC;AACrC,uCAAuC;AACvC,+BAA+B;AAClB,QAAA,KAAK,GAAG,gBAAQ,CAAC,WAAW,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { TraceAPI } from './api/trace';\n/** Entrypoint for trace API */\nexport const trace = TraceAPI.getInstance();\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.d.ts b/node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.d.ts new file mode 100644 index 0000000..ce569f0 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.d.ts @@ -0,0 +1,28 @@ +import { Exception } from '../common/Exception'; +import { TimeInput } from '../common/Time'; +import { SpanAttributes } from './attributes'; +import { Span } from './span'; +import { SpanContext } from './span_context'; +import { SpanStatus } from './status'; +import { Link } from './link'; +/** + * The NonRecordingSpan is the default {@link Span} that is used when no Span + * implementation is available. All operations are no-op including context + * propagation. + */ +export declare class NonRecordingSpan implements Span { + private readonly _spanContext; + constructor(_spanContext?: SpanContext); + spanContext(): SpanContext; + setAttribute(_key: string, _value: unknown): this; + setAttributes(_attributes: SpanAttributes): this; + addEvent(_name: string, _attributes?: SpanAttributes): this; + addLink(_link: Link): this; + addLinks(_links: Link[]): this; + setStatus(_status: SpanStatus): this; + updateName(_name: string): this; + end(_endTime?: TimeInput): void; + isRecording(): boolean; + recordException(_exception: Exception, _time?: TimeInput): void; +} +//# sourceMappingURL=NonRecordingSpan.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js b/node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js new file mode 100644 index 0000000..6d3e6ee --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js @@ -0,0 +1,69 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NonRecordingSpan = void 0; +const invalid_span_constants_1 = require("./invalid-span-constants"); +/** + * The NonRecordingSpan is the default {@link Span} that is used when no Span + * implementation is available. All operations are no-op including context + * propagation. + */ +class NonRecordingSpan { + constructor(_spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT) { + this._spanContext = _spanContext; + } + // Returns a SpanContext. + spanContext() { + return this._spanContext; + } + // By default does nothing + setAttribute(_key, _value) { + return this; + } + // By default does nothing + setAttributes(_attributes) { + return this; + } + // By default does nothing + addEvent(_name, _attributes) { + return this; + } + addLink(_link) { + return this; + } + addLinks(_links) { + return this; + } + // By default does nothing + setStatus(_status) { + return this; + } + // By default does nothing + updateName(_name) { + return this; + } + // By default does nothing + end(_endTime) { } + // isRecording always returns false for NonRecordingSpan. + isRecording() { + return false; + } + // By default does nothing + recordException(_exception, _time) { } +} +exports.NonRecordingSpan = NonRecordingSpan; +//# sourceMappingURL=NonRecordingSpan.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js.map b/node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js.map new file mode 100644 index 0000000..4465327 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NonRecordingSpan.js","sourceRoot":"","sources":["../../../src/trace/NonRecordingSpan.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAKH,qEAAgE;AAMhE;;;;GAIG;AACH,MAAa,gBAAgB;IAC3B,YACmB,eAA4B,6CAAoB;QAAhD,iBAAY,GAAZ,YAAY,CAAoC;IAChE,CAAC;IAEJ,yBAAyB;IACzB,WAAW;QACT,OAAO,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;IAED,0BAA0B;IAC1B,YAAY,CAAC,IAAY,EAAE,MAAe;QACxC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,0BAA0B;IAC1B,aAAa,CAAC,WAA2B;QACvC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,0BAA0B;IAC1B,QAAQ,CAAC,KAAa,EAAE,WAA4B;QAClD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,CAAC,KAAW;QACjB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,QAAQ,CAAC,MAAc;QACrB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,0BAA0B;IAC1B,SAAS,CAAC,OAAmB;QAC3B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,0BAA0B;IAC1B,UAAU,CAAC,KAAa;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,0BAA0B;IAC1B,GAAG,CAAC,QAAoB,IAAS,CAAC;IAElC,yDAAyD;IACzD,WAAW;QACT,OAAO,KAAK,CAAC;IACf,CAAC;IAED,0BAA0B;IAC1B,eAAe,CAAC,UAAqB,EAAE,KAAiB,IAAS,CAAC;CACnE;AArDD,4CAqDC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '../common/Exception';\nimport { TimeInput } from '../common/Time';\nimport { SpanAttributes } from './attributes';\nimport { INVALID_SPAN_CONTEXT } from './invalid-span-constants';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\nimport { SpanStatus } from './status';\nimport { Link } from './link';\n\n/**\n * The NonRecordingSpan is the default {@link Span} that is used when no Span\n * implementation is available. All operations are no-op including context\n * propagation.\n */\nexport class NonRecordingSpan implements Span {\n constructor(\n private readonly _spanContext: SpanContext = INVALID_SPAN_CONTEXT\n ) {}\n\n // Returns a SpanContext.\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n // By default does nothing\n setAttribute(_key: string, _value: unknown): this {\n return this;\n }\n\n // By default does nothing\n setAttributes(_attributes: SpanAttributes): this {\n return this;\n }\n\n // By default does nothing\n addEvent(_name: string, _attributes?: SpanAttributes): this {\n return this;\n }\n\n addLink(_link: Link): this {\n return this;\n }\n\n addLinks(_links: Link[]): this {\n return this;\n }\n\n // By default does nothing\n setStatus(_status: SpanStatus): this {\n return this;\n }\n\n // By default does nothing\n updateName(_name: string): this {\n return this;\n }\n\n // By default does nothing\n end(_endTime?: TimeInput): void {}\n\n // isRecording always returns false for NonRecordingSpan.\n isRecording(): boolean {\n return false;\n }\n\n // By default does nothing\n recordException(_exception: Exception, _time?: TimeInput): void {}\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/NoopTracer.d.ts b/node_modules/@opentelemetry/api/build/src/trace/NoopTracer.d.ts new file mode 100644 index 0000000..0e059c9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/NoopTracer.d.ts @@ -0,0 +1,14 @@ +import { Context } from '../context/types'; +import { Span } from './span'; +import { SpanOptions } from './SpanOptions'; +import { Tracer } from './tracer'; +/** + * No-op implementations of {@link Tracer}. + */ +export declare class NoopTracer implements Tracer { + startSpan(name: string, options?: SpanOptions, context?: Context): Span; + startActiveSpan ReturnType>(name: string, fn: F): ReturnType; + startActiveSpan ReturnType>(name: string, opts: SpanOptions | undefined, fn: F): ReturnType; + startActiveSpan ReturnType>(name: string, opts: SpanOptions | undefined, ctx: Context | undefined, fn: F): ReturnType; +} +//# sourceMappingURL=NoopTracer.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js b/node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js new file mode 100644 index 0000000..0a823aa --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js @@ -0,0 +1,75 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NoopTracer = void 0; +const context_1 = require("../api/context"); +const context_utils_1 = require("../trace/context-utils"); +const NonRecordingSpan_1 = require("./NonRecordingSpan"); +const spancontext_utils_1 = require("./spancontext-utils"); +const contextApi = context_1.ContextAPI.getInstance(); +/** + * No-op implementations of {@link Tracer}. + */ +class NoopTracer { + // startSpan starts a noop span. + startSpan(name, options, context = contextApi.active()) { + const root = Boolean(options === null || options === void 0 ? void 0 : options.root); + if (root) { + return new NonRecordingSpan_1.NonRecordingSpan(); + } + const parentFromContext = context && (0, context_utils_1.getSpanContext)(context); + if (isSpanContext(parentFromContext) && + (0, spancontext_utils_1.isSpanContextValid)(parentFromContext)) { + return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext); + } + else { + return new NonRecordingSpan_1.NonRecordingSpan(); + } + } + startActiveSpan(name, arg2, arg3, arg4) { + let opts; + let ctx; + let fn; + if (arguments.length < 2) { + return; + } + else if (arguments.length === 2) { + fn = arg2; + } + else if (arguments.length === 3) { + opts = arg2; + fn = arg3; + } + else { + opts = arg2; + ctx = arg3; + fn = arg4; + } + const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); + const span = this.startSpan(name, opts, parentContext); + const contextWithSpanSet = (0, context_utils_1.setSpan)(parentContext, span); + return contextApi.with(contextWithSpanSet, fn, undefined, span); + } +} +exports.NoopTracer = NoopTracer; +function isSpanContext(spanContext) { + return (typeof spanContext === 'object' && + typeof spanContext['spanId'] === 'string' && + typeof spanContext['traceId'] === 'string' && + typeof spanContext['traceFlags'] === 'number'); +} +//# sourceMappingURL=NoopTracer.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js.map b/node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js.map new file mode 100644 index 0000000..7fde17d --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NoopTracer.js","sourceRoot":"","sources":["../../../src/trace/NoopTracer.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4CAA4C;AAE5C,0DAAiE;AACjE,yDAAsD;AAEtD,2DAAyD;AAKzD,MAAM,UAAU,GAAG,oBAAU,CAAC,WAAW,EAAE,CAAC;AAE5C;;GAEG;AACH,MAAa,UAAU;IACrB,gCAAgC;IAChC,SAAS,CACP,IAAY,EACZ,OAA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AI,CAAC,CAAC;QAExD,OAAO,UAAU,CAAC,IAAI,CAAC,kBAAkB,EAAE,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;IAClE,CAAC;CACF;AApED,gCAoEC;AAED,SAAS,aAAa,CAAC,WAAgB;IACrC,OAAO,CACL,OAAO,WAAW,KAAK,QAAQ;QAC/B,OAAO,WAAW,CAAC,QAAQ,CAAC,KAAK,QAAQ;QACzC,OAAO,WAAW,CAAC,SAAS,CAAC,KAAK,QAAQ;QAC1C,OAAO,WAAW,CAAC,YAAY,CAAC,KAAK,QAAQ,CAC9C,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ContextAPI } from '../api/context';\nimport { Context } from '../context/types';\nimport { getSpanContext, setSpan } from '../trace/context-utils';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { Span } from './span';\nimport { isSpanContextValid } from './spancontext-utils';\nimport { SpanOptions } from './SpanOptions';\nimport { SpanContext } from './span_context';\nimport { Tracer } from './tracer';\n\nconst contextApi = ContextAPI.getInstance();\n\n/**\n * No-op implementations of {@link Tracer}.\n */\nexport class NoopTracer implements Tracer {\n // startSpan starts a noop span.\n startSpan(\n name: string,\n options?: SpanOptions,\n context = contextApi.active()\n ): Span {\n const root = Boolean(options?.root);\n if (root) {\n return new NonRecordingSpan();\n }\n\n const parentFromContext = context && getSpanContext(context);\n\n if (\n isSpanContext(parentFromContext) &&\n isSpanContextValid(parentFromContext)\n ) {\n return new NonRecordingSpan(parentFromContext);\n } else {\n return new NonRecordingSpan();\n }\n }\n\n startActiveSpan ReturnType>(\n name: string,\n fn: F\n ): ReturnType;\n startActiveSpan ReturnType>(\n name: string,\n opts: SpanOptions | undefined,\n fn: F\n ): ReturnType;\n startActiveSpan ReturnType>(\n name: string,\n opts: SpanOptions | undefined,\n ctx: Context | undefined,\n fn: F\n ): ReturnType;\n startActiveSpan ReturnType>(\n name: string,\n arg2?: F | SpanOptions,\n arg3?: F | Context,\n arg4?: F\n ): ReturnType | undefined {\n let opts: SpanOptions | undefined;\n let ctx: Context | undefined;\n let fn: F;\n\n if (arguments.length < 2) {\n return;\n } else if (arguments.length === 2) {\n fn = arg2 as F;\n } else if (arguments.length === 3) {\n opts = arg2 as SpanOptions | undefined;\n fn = arg3 as F;\n } else {\n opts = arg2 as SpanOptions | undefined;\n ctx = arg3 as Context | undefined;\n fn = arg4 as F;\n }\n\n const parentContext = ctx ?? contextApi.active();\n const span = this.startSpan(name, opts, parentContext);\n const contextWithSpanSet = setSpan(parentContext, span);\n\n return contextApi.with(contextWithSpanSet, fn, undefined, span);\n }\n}\n\nfunction isSpanContext(spanContext: any): spanContext is SpanContext {\n return (\n typeof spanContext === 'object' &&\n typeof spanContext['spanId'] === 'string' &&\n typeof spanContext['traceId'] === 'string' &&\n typeof spanContext['traceFlags'] === 'number'\n );\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.d.ts b/node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.d.ts new file mode 100644 index 0000000..ec0fe79 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.d.ts @@ -0,0 +1,13 @@ +import { Tracer } from './tracer'; +import { TracerOptions } from './tracer_options'; +import { TracerProvider } from './tracer_provider'; +/** + * An implementation of the {@link TracerProvider} which returns an impotent + * Tracer for all calls to `getTracer`. + * + * All operations are no-op. + */ +export declare class NoopTracerProvider implements TracerProvider { + getTracer(_name?: string, _version?: string, _options?: TracerOptions): Tracer; +} +//# sourceMappingURL=NoopTracerProvider.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js b/node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js new file mode 100644 index 0000000..c9e08d6 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js @@ -0,0 +1,32 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NoopTracerProvider = void 0; +const NoopTracer_1 = require("./NoopTracer"); +/** + * An implementation of the {@link TracerProvider} which returns an impotent + * Tracer for all calls to `getTracer`. + * + * All operations are no-op. + */ +class NoopTracerProvider { + getTracer(_name, _version, _options) { + return new NoopTracer_1.NoopTracer(); + } +} +exports.NoopTracerProvider = NoopTracerProvider; +//# sourceMappingURL=NoopTracerProvider.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js.map b/node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js.map new file mode 100644 index 0000000..c47b350 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NoopTracerProvider.js","sourceRoot":"","sources":["../../../src/trace/NoopTracerProvider.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,6CAA0C;AAK1C;;;;;GAKG;AACH,MAAa,kBAAkB;IAC7B,SAAS,CACP,KAAc,EACd,QAAiB,EACjB,QAAwB;QAExB,OAAO,IAAI,uBAAU,EAAE,CAAC;IAC1B,CAAC;CACF;AARD,gDAQC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NoopTracer } from './NoopTracer';\nimport { Tracer } from './tracer';\nimport { TracerOptions } from './tracer_options';\nimport { TracerProvider } from './tracer_provider';\n\n/**\n * An implementation of the {@link TracerProvider} which returns an impotent\n * Tracer for all calls to `getTracer`.\n *\n * All operations are no-op.\n */\nexport class NoopTracerProvider implements TracerProvider {\n getTracer(\n _name?: string,\n _version?: string,\n _options?: TracerOptions\n ): Tracer {\n return new NoopTracer();\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.d.ts b/node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.d.ts new file mode 100644 index 0000000..116cc5c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.d.ts @@ -0,0 +1,27 @@ +import { Context } from '../context/types'; +import { Span } from './span'; +import { SpanOptions } from './SpanOptions'; +import { Tracer } from './tracer'; +import { TracerOptions } from './tracer_options'; +/** + * Proxy tracer provided by the proxy tracer provider + */ +export declare class ProxyTracer implements Tracer { + private _provider; + readonly name: string; + readonly version?: string | undefined; + readonly options?: TracerOptions | undefined; + private _delegate?; + constructor(_provider: TracerDelegator, name: string, version?: string | undefined, options?: TracerOptions | undefined); + startSpan(name: string, options?: SpanOptions, context?: Context): Span; + startActiveSpan unknown>(_name: string, _options: F | SpanOptions, _context?: F | Context, _fn?: F): ReturnType; + /** + * Try to get a tracer from the proxy tracer provider. + * If the proxy tracer provider has no delegate, return a noop tracer. + */ + private _getTracer; +} +export interface TracerDelegator { + getDelegateTracer(name: string, version?: string, options?: TracerOptions): Tracer | undefined; +} +//# sourceMappingURL=ProxyTracer.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js b/node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js new file mode 100644 index 0000000..6677680 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js @@ -0,0 +1,55 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProxyTracer = void 0; +const NoopTracer_1 = require("./NoopTracer"); +const NOOP_TRACER = new NoopTracer_1.NoopTracer(); +/** + * Proxy tracer provided by the proxy tracer provider + */ +class ProxyTracer { + constructor(_provider, name, version, options) { + this._provider = _provider; + this.name = name; + this.version = version; + this.options = options; + } + startSpan(name, options, context) { + return this._getTracer().startSpan(name, options, context); + } + startActiveSpan(_name, _options, _context, _fn) { + const tracer = this._getTracer(); + return Reflect.apply(tracer.startActiveSpan, tracer, arguments); + } + /** + * Try to get a tracer from the proxy tracer provider. + * If the proxy tracer provider has no delegate, return a noop tracer. + */ + _getTracer() { + if (this._delegate) { + return this._delegate; + } + const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); + if (!tracer) { + return NOOP_TRACER; + } + this._delegate = tracer; + return this._delegate; + } +} +exports.ProxyTracer = ProxyTracer; +//# sourceMappingURL=ProxyTracer.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js.map b/node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js.map new file mode 100644 index 0000000..941125c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ProxyTracer.js","sourceRoot":"","sources":["../../../src/trace/ProxyTracer.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAGH,6CAA0C;AAM1C,MAAM,WAAW,GAAG,IAAI,uBAAU,EAAE,CAAC;AAErC;;GAEG;AACH,MAAa,WAAW;IAItB,YACU,SAA0B,EAClB,IAAY,EACZ,OAAgB,EAChB,OAAuB;QAH/B,cAAS,GAAT,SAAS,CAAiB;QAClB,SAAI,GAAJ,IAAI,CAAQ;QACZ,YAAO,GAAP,OAAO,CAAS;QAChB,YAAO,GAAP,OAAO,CAAgB;IACtC,CAAC;IAEJ,SAAS,CAAC,IAAY,EAAE,OAAqB,EAAE,OAAiB;QAC9D,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAC7D,CAAC;IAED,eAAe,CACb,KAAa,EACb,QAAyB,EACzB,QAAsB,EACtB,GAAO;QAEP,MAAM,MAAM,GAAG,IAAI,CAAC,UAAU,EAAE,CAAC;QACjC,OAAO,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,eAAe,EAAE,MAAM,EAAE,SAAS,CAAC,CAAC;IAClE,CAAC;IAED;;;OAGG;IACK,UAAU;QAChB,IAAI,IAAI,CAAC,SAAS,EAAE;YAClB,OAAO,IAAI,CAAC,SAAS,CAAC;SACvB;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,iBAAiB,CAC7C,IAAI,CAAC,IAAI,EACT,IAAI,CAAC,OAAO,EACZ,IAAI,CAAC,OAAO,CACb,CAAC;QAEF,IAAI,CAAC,MAAM,EAAE;YACX,OAAO,WAAW,CAAC;SACpB;QAED,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC;QACxB,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;CACF;AA/CD,kCA+CC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport { NoopTracer } from './NoopTracer';\nimport { Span } from './span';\nimport { SpanOptions } from './SpanOptions';\nimport { Tracer } from './tracer';\nimport { TracerOptions } from './tracer_options';\n\nconst NOOP_TRACER = new NoopTracer();\n\n/**\n * Proxy tracer provided by the proxy tracer provider\n */\nexport class ProxyTracer implements Tracer {\n // When a real implementation is provided, this will be it\n private _delegate?: Tracer;\n\n constructor(\n private _provider: TracerDelegator,\n public readonly name: string,\n public readonly version?: string,\n public readonly options?: TracerOptions\n ) {}\n\n startSpan(name: string, options?: SpanOptions, context?: Context): Span {\n return this._getTracer().startSpan(name, options, context);\n }\n\n startActiveSpan unknown>(\n _name: string,\n _options: F | SpanOptions,\n _context?: F | Context,\n _fn?: F\n ): ReturnType {\n const tracer = this._getTracer();\n return Reflect.apply(tracer.startActiveSpan, tracer, arguments);\n }\n\n /**\n * Try to get a tracer from the proxy tracer provider.\n * If the proxy tracer provider has no delegate, return a noop tracer.\n */\n private _getTracer() {\n if (this._delegate) {\n return this._delegate;\n }\n\n const tracer = this._provider.getDelegateTracer(\n this.name,\n this.version,\n this.options\n );\n\n if (!tracer) {\n return NOOP_TRACER;\n }\n\n this._delegate = tracer;\n return this._delegate;\n }\n}\n\nexport interface TracerDelegator {\n getDelegateTracer(\n name: string,\n version?: string,\n options?: TracerOptions\n ): Tracer | undefined;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.d.ts b/node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.d.ts new file mode 100644 index 0000000..ee7eafa --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.d.ts @@ -0,0 +1,25 @@ +import { Tracer } from './tracer'; +import { TracerProvider } from './tracer_provider'; +import { TracerOptions } from './tracer_options'; +/** + * Tracer provider which provides {@link ProxyTracer}s. + * + * Before a delegate is set, tracers provided are NoOp. + * When a delegate is set, traces are provided from the delegate. + * When a delegate is set after tracers have already been provided, + * all tracers already provided will use the provided delegate implementation. + */ +export declare class ProxyTracerProvider implements TracerProvider { + private _delegate?; + /** + * Get a {@link ProxyTracer} + */ + getTracer(name: string, version?: string, options?: TracerOptions): Tracer; + getDelegate(): TracerProvider; + /** + * Set the delegate tracer provider + */ + setDelegate(delegate: TracerProvider): void; + getDelegateTracer(name: string, version?: string, options?: TracerOptions): Tracer | undefined; +} +//# sourceMappingURL=ProxyTracerProvider.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js b/node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js new file mode 100644 index 0000000..75ec910 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js @@ -0,0 +1,54 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProxyTracerProvider = void 0; +const ProxyTracer_1 = require("./ProxyTracer"); +const NoopTracerProvider_1 = require("./NoopTracerProvider"); +const NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); +/** + * Tracer provider which provides {@link ProxyTracer}s. + * + * Before a delegate is set, tracers provided are NoOp. + * When a delegate is set, traces are provided from the delegate. + * When a delegate is set after tracers have already been provided, + * all tracers already provided will use the provided delegate implementation. + */ +class ProxyTracerProvider { + /** + * Get a {@link ProxyTracer} + */ + getTracer(name, version, options) { + var _a; + return ((_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer_1.ProxyTracer(this, name, version, options)); + } + getDelegate() { + var _a; + return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER; + } + /** + * Set the delegate tracer provider + */ + setDelegate(delegate) { + this._delegate = delegate; + } + getDelegateTracer(name, version, options) { + var _a; + return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options); + } +} +exports.ProxyTracerProvider = ProxyTracerProvider; +//# sourceMappingURL=ProxyTracerProvider.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js.map b/node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js.map new file mode 100644 index 0000000..682c255 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ProxyTracerProvider.js","sourceRoot":"","sources":["../../../src/trace/ProxyTracerProvider.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAIH,+CAA4C;AAC5C,6DAA0D;AAG1D,MAAM,oBAAoB,GAAG,IAAI,uCAAkB,EAAE,CAAC;AAEtD;;;;;;;GAOG;AACH,MAAa,mBAAmB;IAG9B;;OAEG;IACH,SAAS,CAAC,IAAY,EAAE,OAAgB,EAAE,OAAuB;;QAC/D,OAAO,CACL,MAAA,IAAI,CAAC,iBAAiB,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,mCAC9C,IAAI,yBAAW,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAC9C,CAAC;IACJ,CAAC;IAED,WAAW;;QACT,OAAO,MAAA,IAAI,CAAC,SAAS,mCAAI,oBAAoB,CAAC;IAChD,CAAC;IAED;;OAEG;IACH,WAAW,CAAC,QAAwB;QAClC,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;IAC5B,CAAC;IAED,iBAAiB,CACf,IAAY,EACZ,OAAgB,EAChB,OAAuB;;QAEvB,OAAO,MAAA,IAAI,CAAC,SAAS,0CAAE,SAAS,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAC3D,CAAC;CACF;AA/BD,kDA+BC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Tracer } from './tracer';\nimport { TracerProvider } from './tracer_provider';\nimport { ProxyTracer } from './ProxyTracer';\nimport { NoopTracerProvider } from './NoopTracerProvider';\nimport { TracerOptions } from './tracer_options';\n\nconst NOOP_TRACER_PROVIDER = new NoopTracerProvider();\n\n/**\n * Tracer provider which provides {@link ProxyTracer}s.\n *\n * Before a delegate is set, tracers provided are NoOp.\n * When a delegate is set, traces are provided from the delegate.\n * When a delegate is set after tracers have already been provided,\n * all tracers already provided will use the provided delegate implementation.\n */\nexport class ProxyTracerProvider implements TracerProvider {\n private _delegate?: TracerProvider;\n\n /**\n * Get a {@link ProxyTracer}\n */\n getTracer(name: string, version?: string, options?: TracerOptions): Tracer {\n return (\n this.getDelegateTracer(name, version, options) ??\n new ProxyTracer(this, name, version, options)\n );\n }\n\n getDelegate(): TracerProvider {\n return this._delegate ?? NOOP_TRACER_PROVIDER;\n }\n\n /**\n * Set the delegate tracer provider\n */\n setDelegate(delegate: TracerProvider) {\n this._delegate = delegate;\n }\n\n getDelegateTracer(\n name: string,\n version?: string,\n options?: TracerOptions\n ): Tracer | undefined {\n return this._delegate?.getTracer(name, version, options);\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/Sampler.d.ts b/node_modules/@opentelemetry/api/build/src/trace/Sampler.d.ts new file mode 100644 index 0000000..c847eaf --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/Sampler.d.ts @@ -0,0 +1,31 @@ +import { Context } from '../context/types'; +import { SpanAttributes } from './attributes'; +import { Link } from './link'; +import { SamplingResult } from './SamplingResult'; +import { SpanKind } from './span_kind'; +/** + * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. + * This interface represent a sampler. Sampling is a mechanism to control the + * noise and overhead introduced by OpenTelemetry by reducing the number of + * samples of traces collected and sent to the backend. + */ +export interface Sampler { + /** + * Checks whether span needs to be created and tracked. + * + * @param context Parent Context which may contain a span. + * @param traceId of the span to be created. It can be different from the + * traceId in the {@link SpanContext}. Typically in situations when the + * span to be created starts a new trace. + * @param spanName of the span to be created. + * @param spanKind of the span to be created. + * @param attributes Initial set of SpanAttributes for the Span being constructed. + * @param links Collection of links that will be associated with the Span to + * be created. Typically useful for batch operations. + * @returns a {@link SamplingResult}. + */ + shouldSample(context: Context, traceId: string, spanName: string, spanKind: SpanKind, attributes: SpanAttributes, links: Link[]): SamplingResult; + /** Returns the sampler name or short description with the configuration. */ + toString(): string; +} +//# sourceMappingURL=Sampler.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/Sampler.js b/node_modules/@opentelemetry/api/build/src/trace/Sampler.js new file mode 100644 index 0000000..6034482 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/Sampler.js @@ -0,0 +1,18 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Sampler.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/Sampler.js.map b/node_modules/@opentelemetry/api/build/src/trace/Sampler.js.map new file mode 100644 index 0000000..83ae054 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/Sampler.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Sampler.js","sourceRoot":"","sources":["../../../src/trace/Sampler.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport { SpanAttributes } from './attributes';\nimport { Link } from './link';\nimport { SamplingResult } from './SamplingResult';\nimport { SpanKind } from './span_kind';\n\n/**\n * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead.\n * This interface represent a sampler. Sampling is a mechanism to control the\n * noise and overhead introduced by OpenTelemetry by reducing the number of\n * samples of traces collected and sent to the backend.\n */\nexport interface Sampler {\n /**\n * Checks whether span needs to be created and tracked.\n *\n * @param context Parent Context which may contain a span.\n * @param traceId of the span to be created. It can be different from the\n * traceId in the {@link SpanContext}. Typically in situations when the\n * span to be created starts a new trace.\n * @param spanName of the span to be created.\n * @param spanKind of the span to be created.\n * @param attributes Initial set of SpanAttributes for the Span being constructed.\n * @param links Collection of links that will be associated with the Span to\n * be created. Typically useful for batch operations.\n * @returns a {@link SamplingResult}.\n */\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: SpanAttributes,\n links: Link[]\n ): SamplingResult;\n\n /** Returns the sampler name or short description with the configuration. */\n toString(): string;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/SamplingResult.d.ts b/node_modules/@opentelemetry/api/build/src/trace/SamplingResult.d.ts new file mode 100644 index 0000000..f2bb495 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/SamplingResult.d.ts @@ -0,0 +1,49 @@ +import { SpanAttributes } from './attributes'; +import { TraceState } from './trace_state'; +/** + * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. + * A sampling decision that determines how a {@link Span} will be recorded + * and collected. + */ +export declare enum SamplingDecision { + /** + * `Span.isRecording() === false`, span will not be recorded and all events + * and attributes will be dropped. + */ + NOT_RECORD = 0, + /** + * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} + * MUST NOT be set. + */ + RECORD = 1, + /** + * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} + * MUST be set. + */ + RECORD_AND_SAMPLED = 2 +} +/** + * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. + * A sampling result contains a decision for a {@link Span} and additional + * attributes the sampler would like to added to the Span. + */ +export interface SamplingResult { + /** + * A sampling decision, refer to {@link SamplingDecision} for details. + */ + decision: SamplingDecision; + /** + * The list of attributes returned by SamplingResult MUST be immutable. + * Caller may call {@link Sampler}.shouldSample any number of times and + * can safely cache the returned value. + */ + attributes?: Readonly; + /** + * A {@link TraceState} that will be associated with the {@link Span} through + * the new {@link SpanContext}. Samplers SHOULD return the TraceState from + * the passed-in {@link Context} if they do not intend to change it. Leaving + * the value undefined will also leave the TraceState unchanged. + */ + traceState?: TraceState; +} +//# sourceMappingURL=SamplingResult.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js b/node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js new file mode 100644 index 0000000..6df6b3b --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js @@ -0,0 +1,42 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SamplingDecision = void 0; +/** + * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. + * A sampling decision that determines how a {@link Span} will be recorded + * and collected. + */ +var SamplingDecision; +(function (SamplingDecision) { + /** + * `Span.isRecording() === false`, span will not be recorded and all events + * and attributes will be dropped. + */ + SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD"; + /** + * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} + * MUST NOT be set. + */ + SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD"; + /** + * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} + * MUST be set. + */ + SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; +})(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {})); +//# sourceMappingURL=SamplingResult.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js.map b/node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js.map new file mode 100644 index 0000000..6e4ed4b --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SamplingResult.js","sourceRoot":"","sources":["../../../src/trace/SamplingResult.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAKH;;;;GAIG;AACH,IAAY,gBAgBX;AAhBD,WAAY,gBAAgB;IAC1B;;;OAGG;IACH,mEAAU,CAAA;IACV;;;OAGG;IACH,2DAAM,CAAA;IACN;;;OAGG;IACH,mFAAkB,CAAA;AACpB,CAAC,EAhBW,gBAAgB,GAAhB,wBAAgB,KAAhB,wBAAgB,QAgB3B","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SpanAttributes } from './attributes';\nimport { TraceState } from './trace_state';\n\n/**\n * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead.\n * A sampling decision that determines how a {@link Span} will be recorded\n * and collected.\n */\nexport enum SamplingDecision {\n /**\n * `Span.isRecording() === false`, span will not be recorded and all events\n * and attributes will be dropped.\n */\n NOT_RECORD,\n /**\n * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}\n * MUST NOT be set.\n */\n RECORD,\n /**\n * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}\n * MUST be set.\n */\n RECORD_AND_SAMPLED,\n}\n\n/**\n * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead.\n * A sampling result contains a decision for a {@link Span} and additional\n * attributes the sampler would like to added to the Span.\n */\nexport interface SamplingResult {\n /**\n * A sampling decision, refer to {@link SamplingDecision} for details.\n */\n decision: SamplingDecision;\n /**\n * The list of attributes returned by SamplingResult MUST be immutable.\n * Caller may call {@link Sampler}.shouldSample any number of times and\n * can safely cache the returned value.\n */\n attributes?: Readonly;\n /**\n * A {@link TraceState} that will be associated with the {@link Span} through\n * the new {@link SpanContext}. Samplers SHOULD return the TraceState from\n * the passed-in {@link Context} if they do not intend to change it. Leaving\n * the value undefined will also leave the TraceState unchanged.\n */\n traceState?: TraceState;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/SpanOptions.d.ts b/node_modules/@opentelemetry/api/build/src/trace/SpanOptions.d.ts new file mode 100644 index 0000000..c804568 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/SpanOptions.d.ts @@ -0,0 +1,23 @@ +import { TimeInput } from '../common/Time'; +import { SpanAttributes } from './attributes'; +import { Link } from './link'; +import { SpanKind } from './span_kind'; +/** + * Options needed for span creation + */ +export interface SpanOptions { + /** + * The SpanKind of a span + * @default {@link SpanKind.INTERNAL} + */ + kind?: SpanKind; + /** A span's attributes */ + attributes?: SpanAttributes; + /** {@link Link}s span to other spans */ + links?: Link[]; + /** A manually specified start time for the created `Span` object. */ + startTime?: TimeInput; + /** The new span should be a root span. (Ignore parent from context). */ + root?: boolean; +} +//# sourceMappingURL=SpanOptions.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/SpanOptions.js b/node_modules/@opentelemetry/api/build/src/trace/SpanOptions.js new file mode 100644 index 0000000..cb58230 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/SpanOptions.js @@ -0,0 +1,18 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SpanOptions.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/SpanOptions.js.map b/node_modules/@opentelemetry/api/build/src/trace/SpanOptions.js.map new file mode 100644 index 0000000..049f685 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/SpanOptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SpanOptions.js","sourceRoot":"","sources":["../../../src/trace/SpanOptions.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TimeInput } from '../common/Time';\nimport { SpanAttributes } from './attributes';\nimport { Link } from './link';\nimport { SpanKind } from './span_kind';\n\n/**\n * Options needed for span creation\n */\nexport interface SpanOptions {\n /**\n * The SpanKind of a span\n * @default {@link SpanKind.INTERNAL}\n */\n kind?: SpanKind;\n\n /** A span's attributes */\n attributes?: SpanAttributes;\n\n /** {@link Link}s span to other spans */\n links?: Link[];\n\n /** A manually specified start time for the created `Span` object. */\n startTime?: TimeInput;\n\n /** The new span should be a root span. (Ignore parent from context). */\n root?: boolean;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/attributes.d.ts b/node_modules/@opentelemetry/api/build/src/trace/attributes.d.ts new file mode 100644 index 0000000..a2a5d2a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/attributes.d.ts @@ -0,0 +1,10 @@ +import { Attributes, AttributeValue } from '../common/Attributes'; +/** + * @deprecated please use {@link Attributes} + */ +export declare type SpanAttributes = Attributes; +/** + * @deprecated please use {@link AttributeValue} + */ +export declare type SpanAttributeValue = AttributeValue; +//# sourceMappingURL=attributes.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/attributes.js b/node_modules/@opentelemetry/api/build/src/trace/attributes.js new file mode 100644 index 0000000..c6eb97a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/attributes.js @@ -0,0 +1,18 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=attributes.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/attributes.js.map b/node_modules/@opentelemetry/api/build/src/trace/attributes.js.map new file mode 100644 index 0000000..4de58c4 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/attributes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"attributes.js","sourceRoot":"","sources":["../../../src/trace/attributes.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Attributes, AttributeValue } from '../common/Attributes';\n\n/**\n * @deprecated please use {@link Attributes}\n */\nexport type SpanAttributes = Attributes;\n\n/**\n * @deprecated please use {@link AttributeValue}\n */\nexport type SpanAttributeValue = AttributeValue;\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/context-utils.d.ts b/node_modules/@opentelemetry/api/build/src/trace/context-utils.d.ts new file mode 100644 index 0000000..f35f794 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/context-utils.d.ts @@ -0,0 +1,41 @@ +import { Context } from '../context/types'; +import { Span } from './span'; +import { SpanContext } from './span_context'; +/** + * Return the span if one exists + * + * @param context context to get span from + */ +export declare function getSpan(context: Context): Span | undefined; +/** + * Gets the span from the current context, if one exists. + */ +export declare function getActiveSpan(): Span | undefined; +/** + * Set the span on a context + * + * @param context context to use as parent + * @param span span to set active + */ +export declare function setSpan(context: Context, span: Span): Context; +/** + * Remove current span stored in the context + * + * @param context context to delete span from + */ +export declare function deleteSpan(context: Context): Context; +/** + * Wrap span context in a NoopSpan and set as span in a new + * context + * + * @param context context to set active span on + * @param spanContext span context to be wrapped + */ +export declare function setSpanContext(context: Context, spanContext: SpanContext): Context; +/** + * Get the span context of the span if it exists. + * + * @param context context to get values from + */ +export declare function getSpanContext(context: Context): SpanContext | undefined; +//# sourceMappingURL=context-utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/context-utils.js b/node_modules/@opentelemetry/api/build/src/trace/context-utils.js new file mode 100644 index 0000000..d7e9c3a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/context-utils.js @@ -0,0 +1,82 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = void 0; +const context_1 = require("../context/context"); +const NonRecordingSpan_1 = require("./NonRecordingSpan"); +const context_2 = require("../api/context"); +/** + * span key + */ +const SPAN_KEY = (0, context_1.createContextKey)('OpenTelemetry Context Key SPAN'); +/** + * Return the span if one exists + * + * @param context context to get span from + */ +function getSpan(context) { + return context.getValue(SPAN_KEY) || undefined; +} +exports.getSpan = getSpan; +/** + * Gets the span from the current context, if one exists. + */ +function getActiveSpan() { + return getSpan(context_2.ContextAPI.getInstance().active()); +} +exports.getActiveSpan = getActiveSpan; +/** + * Set the span on a context + * + * @param context context to use as parent + * @param span span to set active + */ +function setSpan(context, span) { + return context.setValue(SPAN_KEY, span); +} +exports.setSpan = setSpan; +/** + * Remove current span stored in the context + * + * @param context context to delete span from + */ +function deleteSpan(context) { + return context.deleteValue(SPAN_KEY); +} +exports.deleteSpan = deleteSpan; +/** + * Wrap span context in a NoopSpan and set as span in a new + * context + * + * @param context context to set active span on + * @param spanContext span context to be wrapped + */ +function setSpanContext(context, spanContext) { + return setSpan(context, new NonRecordingSpan_1.NonRecordingSpan(spanContext)); +} +exports.setSpanContext = setSpanContext; +/** + * Get the span context of the span if it exists. + * + * @param context context to get values from + */ +function getSpanContext(context) { + var _a; + return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext(); +} +exports.getSpanContext = getSpanContext; +//# sourceMappingURL=context-utils.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/context-utils.js.map b/node_modules/@opentelemetry/api/build/src/trace/context-utils.js.map new file mode 100644 index 0000000..5fa8126 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/context-utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"context-utils.js","sourceRoot":"","sources":["../../../src/trace/context-utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,gDAAsD;AAItD,yDAAsD;AACtD,4CAA4C;AAE5C;;GAEG;AACH,MAAM,QAAQ,GAAG,IAAA,0BAAgB,EAAC,gCAAgC,CAAC,CAAC;AAEpE;;;;GAIG;AACH,SAAgB,OAAO,CAAC,OAAgB;IACtC,OAAQ,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAU,IAAI,SAAS,CAAC;AAC3D,CAAC;AAFD,0BAEC;AAED;;GAEG;AACH,SAAgB,aAAa;IAC3B,OAAO,OAAO,CAAC,oBAAU,CAAC,WAAW,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC;AACpD,CAAC;AAFD,sCAEC;AAED;;;;;GAKG;AACH,SAAgB,OAAO,CAAC,OAAgB,EAAE,IAAU;IAClD,OAAO,OAAO,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;AAC1C,CAAC;AAFD,0BAEC;AAED;;;;GAIG;AACH,SAAgB,UAAU,CAAC,OAAgB;IACzC,OAAO,OAAO,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;AACvC,CAAC;AAFD,gCAEC;AAED;;;;;;GAMG;AACH,SAAgB,cAAc,CAC5B,OAAgB,EAChB,WAAwB;IAExB,OAAO,OAAO,CAAC,OAAO,EAAE,IAAI,mCAAgB,CAAC,WAAW,CAAC,CAAC,CAAC;AAC7D,CAAC;AALD,wCAKC;AAED;;;;GAIG;AACH,SAAgB,cAAc,CAAC,OAAgB;;IAC7C,OAAO,MAAA,OAAO,CAAC,OAAO,CAAC,0CAAE,WAAW,EAAE,CAAC;AACzC,CAAC;AAFD,wCAEC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createContextKey } from '../context/context';\nimport { Context } from '../context/types';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { ContextAPI } from '../api/context';\n\n/**\n * span key\n */\nconst SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN');\n\n/**\n * Return the span if one exists\n *\n * @param context context to get span from\n */\nexport function getSpan(context: Context): Span | undefined {\n return (context.getValue(SPAN_KEY) as Span) || undefined;\n}\n\n/**\n * Gets the span from the current context, if one exists.\n */\nexport function getActiveSpan(): Span | undefined {\n return getSpan(ContextAPI.getInstance().active());\n}\n\n/**\n * Set the span on a context\n *\n * @param context context to use as parent\n * @param span span to set active\n */\nexport function setSpan(context: Context, span: Span): Context {\n return context.setValue(SPAN_KEY, span);\n}\n\n/**\n * Remove current span stored in the context\n *\n * @param context context to delete span from\n */\nexport function deleteSpan(context: Context): Context {\n return context.deleteValue(SPAN_KEY);\n}\n\n/**\n * Wrap span context in a NoopSpan and set as span in a new\n * context\n *\n * @param context context to set active span on\n * @param spanContext span context to be wrapped\n */\nexport function setSpanContext(\n context: Context,\n spanContext: SpanContext\n): Context {\n return setSpan(context, new NonRecordingSpan(spanContext));\n}\n\n/**\n * Get the span context of the span if it exists.\n *\n * @param context context to get values from\n */\nexport function getSpanContext(context: Context): SpanContext | undefined {\n return getSpan(context)?.spanContext();\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.d.ts b/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.d.ts new file mode 100644 index 0000000..9ed5ecb --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.d.ts @@ -0,0 +1,22 @@ +import { TraceState } from '../trace_state'; +/** + * TraceState must be a class and not a simple object type because of the spec + * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). + * + * Here is the list of allowed mutations: + * - New key-value pair should be added into the beginning of the list + * - The value of any key can be updated. Modified keys MUST be moved to the + * beginning of the list. + */ +export declare class TraceStateImpl implements TraceState { + private _internalState; + constructor(rawTraceState?: string); + set(key: string, value: string): TraceStateImpl; + unset(key: string): TraceStateImpl; + get(key: string): string | undefined; + serialize(): string; + private _parse; + private _keys; + private _clone; +} +//# sourceMappingURL=tracestate-impl.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js b/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js new file mode 100644 index 0000000..93c0289 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js @@ -0,0 +1,103 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TraceStateImpl = void 0; +const tracestate_validators_1 = require("./tracestate-validators"); +const MAX_TRACE_STATE_ITEMS = 32; +const MAX_TRACE_STATE_LEN = 512; +const LIST_MEMBERS_SEPARATOR = ','; +const LIST_MEMBER_KEY_VALUE_SPLITTER = '='; +/** + * TraceState must be a class and not a simple object type because of the spec + * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). + * + * Here is the list of allowed mutations: + * - New key-value pair should be added into the beginning of the list + * - The value of any key can be updated. Modified keys MUST be moved to the + * beginning of the list. + */ +class TraceStateImpl { + constructor(rawTraceState) { + this._internalState = new Map(); + if (rawTraceState) + this._parse(rawTraceState); + } + set(key, value) { + // TODO: Benchmark the different approaches(map vs list) and + // use the faster one. + const traceState = this._clone(); + if (traceState._internalState.has(key)) { + traceState._internalState.delete(key); + } + traceState._internalState.set(key, value); + return traceState; + } + unset(key) { + const traceState = this._clone(); + traceState._internalState.delete(key); + return traceState; + } + get(key) { + return this._internalState.get(key); + } + serialize() { + return this._keys() + .reduce((agg, key) => { + agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); + return agg; + }, []) + .join(LIST_MEMBERS_SEPARATOR); + } + _parse(rawTraceState) { + if (rawTraceState.length > MAX_TRACE_STATE_LEN) + return; + this._internalState = rawTraceState + .split(LIST_MEMBERS_SEPARATOR) + .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning + .reduce((agg, part) => { + const listMember = part.trim(); // Optional Whitespace (OWS) handling + const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); + if (i !== -1) { + const key = listMember.slice(0, i); + const value = listMember.slice(i + 1, part.length); + if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) { + agg.set(key, value); + } + else { + // TODO: Consider to add warning log + } + } + return agg; + }, new Map()); + // Because of the reverse() requirement, trunc must be done after map is created + if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { + this._internalState = new Map(Array.from(this._internalState.entries()) + .reverse() // Use reverse same as original tracestate parse chain + .slice(0, MAX_TRACE_STATE_ITEMS)); + } + } + _keys() { + return Array.from(this._internalState.keys()).reverse(); + } + _clone() { + const traceState = new TraceStateImpl(); + traceState._internalState = new Map(this._internalState); + return traceState; + } +} +exports.TraceStateImpl = TraceStateImpl; +//# sourceMappingURL=tracestate-impl.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js.map b/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js.map new file mode 100644 index 0000000..83eacbe --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js.map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OAAO,EAAE,CAAC;iBACtC,OAAO,EAAE,CAAC,sDAAsD;iBAChE,KAAK,CAAC,CAAC,EAAE,qBAAqB,CAAC,CACnC,CAAC;SACH;IACH,CAAC;IAEO,KAAK;QACX,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC;IAC1D,CAAC;IAEO,MAAM;QACZ,MAAM,UAAU,GAAG,IAAI,cAAc,EAAE,CAAC;QACxC,UAAU,CAAC,cAAc,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QACzD,OAAO,UAAU,CAAC;IACpB,CAAC;CACF;AA5ED,wCA4EC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TraceState } from '../trace_state';\nimport { validateKey, validateValue } from './tracestate-validators';\n\nconst MAX_TRACE_STATE_ITEMS = 32;\nconst MAX_TRACE_STATE_LEN = 512;\nconst LIST_MEMBERS_SEPARATOR = ',';\nconst LIST_MEMBER_KEY_VALUE_SPLITTER = '=';\n\n/**\n * TraceState must be a class and not a simple object type because of the spec\n * requirement (https://www.w3.org/TR/trace-context/#tracestate-field).\n *\n * Here is the list of allowed mutations:\n * - New key-value pair should be added into the beginning of the list\n * - The value of any key can be updated. Modified keys MUST be moved to the\n * beginning of the list.\n */\nexport class TraceStateImpl implements TraceState {\n private _internalState: Map = new Map();\n\n constructor(rawTraceState?: string) {\n if (rawTraceState) this._parse(rawTraceState);\n }\n\n set(key: string, value: string): TraceStateImpl {\n // TODO: Benchmark the different approaches(map vs list) and\n // use the faster one.\n const traceState = this._clone();\n if (traceState._internalState.has(key)) {\n traceState._internalState.delete(key);\n }\n traceState._internalState.set(key, value);\n return traceState;\n }\n\n unset(key: string): TraceStateImpl {\n const traceState = this._clone();\n traceState._internalState.delete(key);\n return traceState;\n }\n\n get(key: string): string | undefined {\n return this._internalState.get(key);\n }\n\n serialize(): string {\n return this._keys()\n .reduce((agg: string[], key) => {\n agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));\n return agg;\n }, [])\n .join(LIST_MEMBERS_SEPARATOR);\n }\n\n private _parse(rawTraceState: string) {\n if (rawTraceState.length > MAX_TRACE_STATE_LEN) return;\n this._internalState = rawTraceState\n .split(LIST_MEMBERS_SEPARATOR)\n .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning\n .reduce((agg: Map, part: string) => {\n const listMember = part.trim(); // Optional Whitespace (OWS) handling\n const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);\n if (i !== -1) {\n const key = listMember.slice(0, i);\n const value = listMember.slice(i + 1, part.length);\n if (validateKey(key) && validateValue(value)) {\n agg.set(key, value);\n } else {\n // TODO: Consider to add warning log\n }\n }\n return agg;\n }, new Map());\n\n // Because of the reverse() requirement, trunc must be done after map is created\n if (this._internalState.size > MAX_TRACE_STATE_ITEMS) {\n this._internalState = new Map(\n Array.from(this._internalState.entries())\n .reverse() // Use reverse same as original tracestate parse chain\n .slice(0, MAX_TRACE_STATE_ITEMS)\n );\n }\n }\n\n private _keys(): string[] {\n return Array.from(this._internalState.keys()).reverse();\n }\n\n private _clone(): TraceStateImpl {\n const traceState = new TraceStateImpl();\n traceState._internalState = new Map(this._internalState);\n return traceState;\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.d.ts b/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.d.ts new file mode 100644 index 0000000..4917f99 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.d.ts @@ -0,0 +1,15 @@ +/** + * Key is opaque string up to 256 characters printable. It MUST begin with a + * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, + * underscores _, dashes -, asterisks *, and forward slashes /. + * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the + * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. + * see https://www.w3.org/TR/trace-context/#key + */ +export declare function validateKey(key: string): boolean; +/** + * Value is opaque string up to 256 characters printable ASCII RFC0020 + * characters (i.e., the range 0x20 to 0x7E) except comma , and =. + */ +export declare function validateValue(value: string): boolean; +//# sourceMappingURL=tracestate-validators.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.js b/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.js new file mode 100644 index 0000000..3e37044 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.js @@ -0,0 +1,46 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateValue = exports.validateKey = void 0; +const VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]'; +const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; +const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; +const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); +const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; +const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; +/** + * Key is opaque string up to 256 characters printable. It MUST begin with a + * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, + * underscores _, dashes -, asterisks *, and forward slashes /. + * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the + * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. + * see https://www.w3.org/TR/trace-context/#key + */ +function validateKey(key) { + return VALID_KEY_REGEX.test(key); +} +exports.validateKey = validateKey; +/** + * Value is opaque string up to 256 characters printable ASCII RFC0020 + * characters (i.e., the range 0x20 to 0x7E) except comma , and =. + */ +function validateValue(value) { + return (VALID_VALUE_BASE_REGEX.test(value) && + !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)); +} +exports.validateValue = validateValue; +//# sourceMappingURL=tracestate-validators.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.js.map b/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.js.map new file mode 100644 index 0000000..498abce --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tracestate-validators.js","sourceRoot":"","sources":["../../../../src/trace/internal/tracestate-validators.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,MAAM,oBAAoB,GAAG,cAAc,CAAC;AAC5C,MAAM,SAAS,GAAG,QAAQ,oBAAoB,SAAS,CAAC;AACxD,MAAM,gBAAgB,GAAG,WAAW,oBAAoB,gBAAgB,oBAAoB,QAAQ,CAAC;AACrG,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,OAAO,SAAS,IAAI,gBAAgB,IAAI,CAAC,CAAC;AAC7E,MAAM,sBAAsB,GAAG,qBAAqB,CAAC;AACrD,MAAM,+BAA+B,GAAG,KAAK,CAAC;AAE9C;;;;;;;GAOG;AACH,SAAgB,WAAW,CAAC,GAAW;IACrC,OAAO,eAAe,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACnC,CAAC;AAFD,kCAEC;AAED;;;GAGG;AACH,SAAgB,aAAa,CAAC,KAAa;IACzC,OAAO,CACL,sBAAsB,CAAC,IAAI,CAAC,KAAK,CAAC;QAClC,CAAC,+BAA+B,CAAC,IAAI,CAAC,KAAK,CAAC,CAC7C,CAAC;AACJ,CAAC;AALD,sCAKC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]';\nconst VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;\nconst VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;\nconst VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);\nconst VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;\nconst INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;\n\n/**\n * Key is opaque string up to 256 characters printable. It MUST begin with a\n * lowercase letter, and can only contain lowercase letters a-z, digits 0-9,\n * underscores _, dashes -, asterisks *, and forward slashes /.\n * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the\n * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key.\n * see https://www.w3.org/TR/trace-context/#key\n */\nexport function validateKey(key: string): boolean {\n return VALID_KEY_REGEX.test(key);\n}\n\n/**\n * Value is opaque string up to 256 characters printable ASCII RFC0020\n * characters (i.e., the range 0x20 to 0x7E) except comma , and =.\n */\nexport function validateValue(value: string): boolean {\n return (\n VALID_VALUE_BASE_REGEX.test(value) &&\n !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)\n );\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/internal/utils.d.ts b/node_modules/@opentelemetry/api/build/src/trace/internal/utils.d.ts new file mode 100644 index 0000000..e3b51fe --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/internal/utils.d.ts @@ -0,0 +1,3 @@ +import { TraceState } from '../trace_state'; +export declare function createTraceState(rawTraceState?: string): TraceState; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/internal/utils.js b/node_modules/@opentelemetry/api/build/src/trace/internal/utils.js new file mode 100644 index 0000000..3d95419 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/internal/utils.js @@ -0,0 +1,24 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createTraceState = void 0; +const tracestate_impl_1 = require("./tracestate-impl"); +function createTraceState(rawTraceState) { + return new tracestate_impl_1.TraceStateImpl(rawTraceState); +} +exports.createTraceState = createTraceState; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/internal/utils.js.map b/node_modules/@opentelemetry/api/build/src/trace/internal/utils.js.map new file mode 100644 index 0000000..19cd87c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/internal/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/trace/internal/utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAGH,uDAAmD;AAEnD,SAAgB,gBAAgB,CAAC,aAAsB;IACrD,OAAO,IAAI,gCAAc,CAAC,aAAa,CAAC,CAAC;AAC3C,CAAC;AAFD,4CAEC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TraceState } from '../trace_state';\nimport { TraceStateImpl } from './tracestate-impl';\n\nexport function createTraceState(rawTraceState?: string): TraceState {\n return new TraceStateImpl(rawTraceState);\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.d.ts b/node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.d.ts new file mode 100644 index 0000000..e32dab9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.d.ts @@ -0,0 +1,5 @@ +import { SpanContext } from './span_context'; +export declare const INVALID_SPANID = "0000000000000000"; +export declare const INVALID_TRACEID = "00000000000000000000000000000000"; +export declare const INVALID_SPAN_CONTEXT: SpanContext; +//# sourceMappingURL=invalid-span-constants.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js b/node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js new file mode 100644 index 0000000..77fb79e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js @@ -0,0 +1,27 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; +const trace_flags_1 = require("./trace_flags"); +exports.INVALID_SPANID = '0000000000000000'; +exports.INVALID_TRACEID = '00000000000000000000000000000000'; +exports.INVALID_SPAN_CONTEXT = { + traceId: exports.INVALID_TRACEID, + spanId: exports.INVALID_SPANID, + traceFlags: trace_flags_1.TraceFlags.NONE, +}; +//# sourceMappingURL=invalid-span-constants.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js.map b/node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js.map new file mode 100644 index 0000000..54da537 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"invalid-span-constants.js","sourceRoot":"","sources":["../../../src/trace/invalid-span-constants.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAGH,+CAA2C;AAE9B,QAAA,cAAc,GAAG,kBAAkB,CAAC;AACpC,QAAA,eAAe,GAAG,kCAAkC,CAAC;AACrD,QAAA,oBAAoB,GAAgB;IAC/C,OAAO,EAAE,uBAAe;IACxB,MAAM,EAAE,sBAAc;IACtB,UAAU,EAAE,wBAAU,CAAC,IAAI;CAC5B,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SpanContext } from './span_context';\nimport { TraceFlags } from './trace_flags';\n\nexport const INVALID_SPANID = '0000000000000000';\nexport const INVALID_TRACEID = '00000000000000000000000000000000';\nexport const INVALID_SPAN_CONTEXT: SpanContext = {\n traceId: INVALID_TRACEID,\n spanId: INVALID_SPANID,\n traceFlags: TraceFlags.NONE,\n};\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/link.d.ts b/node_modules/@opentelemetry/api/build/src/trace/link.d.ts new file mode 100644 index 0000000..8fc0106 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/link.d.ts @@ -0,0 +1,26 @@ +import { SpanAttributes } from './attributes'; +import { SpanContext } from './span_context'; +/** + * A pointer from the current {@link Span} to another span in the same trace or + * in a different trace. + * Few examples of Link usage. + * 1. Batch Processing: A batch of elements may contain elements associated + * with one or more traces/spans. Since there can only be one parent + * SpanContext, Link is used to keep reference to SpanContext of all + * elements in the batch. + * 2. Public Endpoint: A SpanContext in incoming client request on a public + * endpoint is untrusted from service provider perspective. In such case it + * is advisable to start a new trace with appropriate sampling decision. + * However, it is desirable to associate incoming SpanContext to new trace + * initiated on service provider side so two traces (from Client and from + * Service Provider) can be correlated. + */ +export interface Link { + /** The {@link SpanContext} of a linked span. */ + context: SpanContext; + /** A set of {@link SpanAttributes} on the link. */ + attributes?: SpanAttributes; + /** Count of attributes of the link that were dropped due to collection limits */ + droppedAttributesCount?: number; +} +//# sourceMappingURL=link.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/link.js b/node_modules/@opentelemetry/api/build/src/trace/link.js new file mode 100644 index 0000000..8036a63 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/link.js @@ -0,0 +1,18 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=link.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/link.js.map b/node_modules/@opentelemetry/api/build/src/trace/link.js.map new file mode 100644 index 0000000..34fae43 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/link.js.map @@ -0,0 +1 @@ +{"version":3,"file":"link.js","sourceRoot":"","sources":["../../../src/trace/link.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SpanAttributes } from './attributes';\nimport { SpanContext } from './span_context';\n\n/**\n * A pointer from the current {@link Span} to another span in the same trace or\n * in a different trace.\n * Few examples of Link usage.\n * 1. Batch Processing: A batch of elements may contain elements associated\n * with one or more traces/spans. Since there can only be one parent\n * SpanContext, Link is used to keep reference to SpanContext of all\n * elements in the batch.\n * 2. Public Endpoint: A SpanContext in incoming client request on a public\n * endpoint is untrusted from service provider perspective. In such case it\n * is advisable to start a new trace with appropriate sampling decision.\n * However, it is desirable to associate incoming SpanContext to new trace\n * initiated on service provider side so two traces (from Client and from\n * Service Provider) can be correlated.\n */\nexport interface Link {\n /** The {@link SpanContext} of a linked span. */\n context: SpanContext;\n /** A set of {@link SpanAttributes} on the link. */\n attributes?: SpanAttributes;\n /** Count of attributes of the link that were dropped due to collection limits */\n droppedAttributesCount?: number;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/span.d.ts b/node_modules/@opentelemetry/api/build/src/trace/span.d.ts new file mode 100644 index 0000000..28c6442 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/span.d.ts @@ -0,0 +1,120 @@ +import { Exception } from '../common/Exception'; +import { TimeInput } from '../common/Time'; +import { SpanAttributes, SpanAttributeValue } from './attributes'; +import { SpanContext } from './span_context'; +import { SpanStatus } from './status'; +import { Link } from './link'; +/** + * An interface that represents a span. A span represents a single operation + * within a trace. Examples of span might include remote procedure calls or a + * in-process function calls to sub-components. A Trace has a single, top-level + * "root" Span that in turn may have zero or more child Spans, which in turn + * may have children. + * + * Spans are created by the {@link Tracer.startSpan} method. + */ +export interface Span { + /** + * Returns the {@link SpanContext} object associated with this Span. + * + * Get an immutable, serializable identifier for this span that can be used + * to create new child spans. Returned SpanContext is usable even after the + * span ends. + * + * @returns the SpanContext object associated with this Span. + */ + spanContext(): SpanContext; + /** + * Sets an attribute to the span. + * + * Sets a single Attribute with the key and value passed as arguments. + * + * @param key the key for this attribute. + * @param value the value for this attribute. Setting a value null or + * undefined is invalid and will result in undefined behavior. + */ + setAttribute(key: string, value: SpanAttributeValue): this; + /** + * Sets attributes to the span. + * + * @param attributes the attributes that will be added. + * null or undefined attribute values + * are invalid and will result in undefined behavior. + */ + setAttributes(attributes: SpanAttributes): this; + /** + * Adds an event to the Span. + * + * @param name the name of the event. + * @param [attributesOrStartTime] the attributes that will be added; these are + * associated with this event. Can be also a start time + * if type is {@type TimeInput} and 3rd param is undefined + * @param [startTime] start time of the event. + */ + addEvent(name: string, attributesOrStartTime?: SpanAttributes | TimeInput, startTime?: TimeInput): this; + /** + * Adds a single link to the span. + * + * Links added after the creation will not affect the sampling decision. + * It is preferred span links be added at span creation. + * + * @param link the link to add. + */ + addLink(link: Link): this; + /** + * Adds multiple links to the span. + * + * Links added after the creation will not affect the sampling decision. + * It is preferred span links be added at span creation. + * + * @param links the links to add. + */ + addLinks(links: Link[]): this; + /** + * Sets a status to the span. If used, this will override the default Span + * status. Default is {@link SpanStatusCode.UNSET}. SetStatus overrides the value + * of previous calls to SetStatus on the Span. + * + * @param status the SpanStatus to set. + */ + setStatus(status: SpanStatus): this; + /** + * Updates the Span name. + * + * This will override the name provided via {@link Tracer.startSpan}. + * + * Upon this update, any sampling behavior based on Span name will depend on + * the implementation. + * + * @param name the Span name. + */ + updateName(name: string): this; + /** + * Marks the end of Span execution. + * + * Call to End of a Span MUST not have any effects on child spans. Those may + * still be running and can be ended later. + * + * Do not return `this`. The Span generally should not be used after it + * is ended so chaining is not desired in this context. + * + * @param [endTime] the time to set as Span's end time. If not provided, + * use the current time as the span's end time. + */ + end(endTime?: TimeInput): void; + /** + * Returns the flag whether this span will be recorded. + * + * @returns true if this Span is active and recording information like events + * with the `AddEvent` operation and attributes using `setAttributes`. + */ + isRecording(): boolean; + /** + * Sets exception as a span event + * @param exception the exception the only accepted values are string or Error + * @param [time] the time to set as Span's event time. If not provided, + * use the current time. + */ + recordException(exception: Exception, time?: TimeInput): void; +} +//# sourceMappingURL=span.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/span.js b/node_modules/@opentelemetry/api/build/src/trace/span.js new file mode 100644 index 0000000..b50af46 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/span.js @@ -0,0 +1,18 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=span.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/span.js.map b/node_modules/@opentelemetry/api/build/src/trace/span.js.map new file mode 100644 index 0000000..f32cb28 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/span.js.map @@ -0,0 +1 @@ +{"version":3,"file":"span.js","sourceRoot":"","sources":["../../../src/trace/span.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '../common/Exception';\nimport { TimeInput } from '../common/Time';\nimport { SpanAttributes, SpanAttributeValue } from './attributes';\nimport { SpanContext } from './span_context';\nimport { SpanStatus } from './status';\nimport { Link } from './link';\n\n/**\n * An interface that represents a span. A span represents a single operation\n * within a trace. Examples of span might include remote procedure calls or a\n * in-process function calls to sub-components. A Trace has a single, top-level\n * \"root\" Span that in turn may have zero or more child Spans, which in turn\n * may have children.\n *\n * Spans are created by the {@link Tracer.startSpan} method.\n */\nexport interface Span {\n /**\n * Returns the {@link SpanContext} object associated with this Span.\n *\n * Get an immutable, serializable identifier for this span that can be used\n * to create new child spans. Returned SpanContext is usable even after the\n * span ends.\n *\n * @returns the SpanContext object associated with this Span.\n */\n spanContext(): SpanContext;\n\n /**\n * Sets an attribute to the span.\n *\n * Sets a single Attribute with the key and value passed as arguments.\n *\n * @param key the key for this attribute.\n * @param value the value for this attribute. Setting a value null or\n * undefined is invalid and will result in undefined behavior.\n */\n setAttribute(key: string, value: SpanAttributeValue): this;\n\n /**\n * Sets attributes to the span.\n *\n * @param attributes the attributes that will be added.\n * null or undefined attribute values\n * are invalid and will result in undefined behavior.\n */\n setAttributes(attributes: SpanAttributes): this;\n\n /**\n * Adds an event to the Span.\n *\n * @param name the name of the event.\n * @param [attributesOrStartTime] the attributes that will be added; these are\n * associated with this event. Can be also a start time\n * if type is {@type TimeInput} and 3rd param is undefined\n * @param [startTime] start time of the event.\n */\n addEvent(\n name: string,\n attributesOrStartTime?: SpanAttributes | TimeInput,\n startTime?: TimeInput\n ): this;\n\n /**\n * Adds a single link to the span.\n *\n * Links added after the creation will not affect the sampling decision.\n * It is preferred span links be added at span creation.\n *\n * @param link the link to add.\n */\n addLink(link: Link): this;\n\n /**\n * Adds multiple links to the span.\n *\n * Links added after the creation will not affect the sampling decision.\n * It is preferred span links be added at span creation.\n *\n * @param links the links to add.\n */\n addLinks(links: Link[]): this;\n\n /**\n * Sets a status to the span. If used, this will override the default Span\n * status. Default is {@link SpanStatusCode.UNSET}. SetStatus overrides the value\n * of previous calls to SetStatus on the Span.\n *\n * @param status the SpanStatus to set.\n */\n setStatus(status: SpanStatus): this;\n\n /**\n * Updates the Span name.\n *\n * This will override the name provided via {@link Tracer.startSpan}.\n *\n * Upon this update, any sampling behavior based on Span name will depend on\n * the implementation.\n *\n * @param name the Span name.\n */\n updateName(name: string): this;\n\n /**\n * Marks the end of Span execution.\n *\n * Call to End of a Span MUST not have any effects on child spans. Those may\n * still be running and can be ended later.\n *\n * Do not return `this`. The Span generally should not be used after it\n * is ended so chaining is not desired in this context.\n *\n * @param [endTime] the time to set as Span's end time. If not provided,\n * use the current time as the span's end time.\n */\n end(endTime?: TimeInput): void;\n\n /**\n * Returns the flag whether this span will be recorded.\n *\n * @returns true if this Span is active and recording information like events\n * with the `AddEvent` operation and attributes using `setAttributes`.\n */\n isRecording(): boolean;\n\n /**\n * Sets exception as a span event\n * @param exception the exception the only accepted values are string or Error\n * @param [time] the time to set as Span's event time. If not provided,\n * use the current time.\n */\n recordException(exception: Exception, time?: TimeInput): void;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/span_context.d.ts b/node_modules/@opentelemetry/api/build/src/trace/span_context.d.ts new file mode 100644 index 0000000..f30933a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/span_context.d.ts @@ -0,0 +1,53 @@ +import { TraceState } from './trace_state'; +/** + * A SpanContext represents the portion of a {@link Span} which must be + * serialized and propagated along side of a {@link Baggage}. + */ +export interface SpanContext { + /** + * The ID of the trace that this span belongs to. It is worldwide unique + * with practically sufficient probability by being made as 16 randomly + * generated bytes, encoded as a 32 lowercase hex characters corresponding to + * 128 bits. + */ + traceId: string; + /** + * The ID of the Span. It is globally unique with practically sufficient + * probability by being made as 8 randomly generated bytes, encoded as a 16 + * lowercase hex characters corresponding to 64 bits. + */ + spanId: string; + /** + * Only true if the SpanContext was propagated from a remote parent. + */ + isRemote?: boolean; + /** + * Trace flags to propagate. + * + * It is represented as 1 byte (bitmap). Bit to represent whether trace is + * sampled or not. When set, the least significant bit documents that the + * caller may have recorded trace data. A caller who does not record trace + * data out-of-band leaves this flag unset. + * + * see {@link TraceFlags} for valid flag values. + */ + traceFlags: number; + /** + * Tracing-system-specific info to propagate. + * + * The tracestate field value is a `list` as defined below. The `list` is a + * series of `list-members` separated by commas `,`, and a list-member is a + * key/value pair separated by an equals sign `=`. Spaces and horizontal tabs + * surrounding `list-members` are ignored. There can be a maximum of 32 + * `list-members` in a `list`. + * More Info: https://www.w3.org/TR/trace-context/#tracestate-field + * + * Examples: + * Single tracing system (generic format): + * tracestate: rojo=00f067aa0ba902b7 + * Multiple tracing systems (with different formatting): + * tracestate: rojo=00f067aa0ba902b7,congo=t61rcWkgMzE + */ + traceState?: TraceState; +} +//# sourceMappingURL=span_context.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/span_context.js b/node_modules/@opentelemetry/api/build/src/trace/span_context.js new file mode 100644 index 0000000..4b7976c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/span_context.js @@ -0,0 +1,18 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=span_context.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/span_context.js.map b/node_modules/@opentelemetry/api/build/src/trace/span_context.js.map new file mode 100644 index 0000000..005386d --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/span_context.js.map @@ -0,0 +1 @@ +{"version":3,"file":"span_context.js","sourceRoot":"","sources":["../../../src/trace/span_context.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TraceState } from './trace_state';\n\n/**\n * A SpanContext represents the portion of a {@link Span} which must be\n * serialized and propagated along side of a {@link Baggage}.\n */\nexport interface SpanContext {\n /**\n * The ID of the trace that this span belongs to. It is worldwide unique\n * with practically sufficient probability by being made as 16 randomly\n * generated bytes, encoded as a 32 lowercase hex characters corresponding to\n * 128 bits.\n */\n traceId: string;\n /**\n * The ID of the Span. It is globally unique with practically sufficient\n * probability by being made as 8 randomly generated bytes, encoded as a 16\n * lowercase hex characters corresponding to 64 bits.\n */\n spanId: string;\n /**\n * Only true if the SpanContext was propagated from a remote parent.\n */\n isRemote?: boolean;\n /**\n * Trace flags to propagate.\n *\n * It is represented as 1 byte (bitmap). Bit to represent whether trace is\n * sampled or not. When set, the least significant bit documents that the\n * caller may have recorded trace data. A caller who does not record trace\n * data out-of-band leaves this flag unset.\n *\n * see {@link TraceFlags} for valid flag values.\n */\n traceFlags: number;\n /**\n * Tracing-system-specific info to propagate.\n *\n * The tracestate field value is a `list` as defined below. The `list` is a\n * series of `list-members` separated by commas `,`, and a list-member is a\n * key/value pair separated by an equals sign `=`. Spaces and horizontal tabs\n * surrounding `list-members` are ignored. There can be a maximum of 32\n * `list-members` in a `list`.\n * More Info: https://www.w3.org/TR/trace-context/#tracestate-field\n *\n * Examples:\n * Single tracing system (generic format):\n * tracestate: rojo=00f067aa0ba902b7\n * Multiple tracing systems (with different formatting):\n * tracestate: rojo=00f067aa0ba902b7,congo=t61rcWkgMzE\n */\n traceState?: TraceState;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/span_kind.d.ts b/node_modules/@opentelemetry/api/build/src/trace/span_kind.d.ts new file mode 100644 index 0000000..a89846f --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/span_kind.d.ts @@ -0,0 +1,27 @@ +export declare enum SpanKind { + /** Default value. Indicates that the span is used internally. */ + INTERNAL = 0, + /** + * Indicates that the span covers server-side handling of an RPC or other + * remote request. + */ + SERVER = 1, + /** + * Indicates that the span covers the client-side wrapper around an RPC or + * other remote request. + */ + CLIENT = 2, + /** + * Indicates that the span describes producer sending a message to a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + PRODUCER = 3, + /** + * Indicates that the span describes consumer receiving a message from a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + CONSUMER = 4 +} +//# sourceMappingURL=span_kind.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/span_kind.js b/node_modules/@opentelemetry/api/build/src/trace/span_kind.js new file mode 100644 index 0000000..9c06e2c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/span_kind.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SpanKind = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var SpanKind; +(function (SpanKind) { + /** Default value. Indicates that the span is used internally. */ + SpanKind[SpanKind["INTERNAL"] = 0] = "INTERNAL"; + /** + * Indicates that the span covers server-side handling of an RPC or other + * remote request. + */ + SpanKind[SpanKind["SERVER"] = 1] = "SERVER"; + /** + * Indicates that the span covers the client-side wrapper around an RPC or + * other remote request. + */ + SpanKind[SpanKind["CLIENT"] = 2] = "CLIENT"; + /** + * Indicates that the span describes producer sending a message to a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + SpanKind[SpanKind["PRODUCER"] = 3] = "PRODUCER"; + /** + * Indicates that the span describes consumer receiving a message from a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + SpanKind[SpanKind["CONSUMER"] = 4] = "CONSUMER"; +})(SpanKind = exports.SpanKind || (exports.SpanKind = {})); +//# sourceMappingURL=span_kind.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/span_kind.js.map b/node_modules/@opentelemetry/api/build/src/trace/span_kind.js.map new file mode 100644 index 0000000..c0ba360 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/span_kind.js.map @@ -0,0 +1 @@ +{"version":3,"file":"span_kind.js","sourceRoot":"","sources":["../../../src/trace/span_kind.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,IAAY,QA6BX;AA7BD,WAAY,QAAQ;IAClB,iEAAiE;IACjE,+CAAY,CAAA;IAEZ;;;OAGG;IACH,2CAAU,CAAA;IAEV;;;OAGG;IACH,2CAAU,CAAA;IAEV;;;;OAIG;IACH,+CAAY,CAAA;IAEZ;;;;OAIG;IACH,+CAAY,CAAA;AACd,CAAC,EA7BW,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QA6BnB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport enum SpanKind {\n /** Default value. Indicates that the span is used internally. */\n INTERNAL = 0,\n\n /**\n * Indicates that the span covers server-side handling of an RPC or other\n * remote request.\n */\n SERVER = 1,\n\n /**\n * Indicates that the span covers the client-side wrapper around an RPC or\n * other remote request.\n */\n CLIENT = 2,\n\n /**\n * Indicates that the span describes producer sending a message to a\n * broker. Unlike client and server, there is no direct critical path latency\n * relationship between producer and consumer spans.\n */\n PRODUCER = 3,\n\n /**\n * Indicates that the span describes consumer receiving a message from a\n * broker. Unlike client and server, there is no direct critical path latency\n * relationship between producer and consumer spans.\n */\n CONSUMER = 4,\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.d.ts b/node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.d.ts new file mode 100644 index 0000000..f191111 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.d.ts @@ -0,0 +1,17 @@ +import { Span } from './span'; +import { SpanContext } from './span_context'; +export declare function isValidTraceId(traceId: string): boolean; +export declare function isValidSpanId(spanId: string): boolean; +/** + * Returns true if this {@link SpanContext} is valid. + * @return true if this {@link SpanContext} is valid. + */ +export declare function isSpanContextValid(spanContext: SpanContext): boolean; +/** + * Wrap the given {@link SpanContext} in a new non-recording {@link Span} + * + * @param spanContext span context to be wrapped + * @returns a new non-recording {@link Span} with the provided context + */ +export declare function wrapSpanContext(spanContext: SpanContext): Span; +//# sourceMappingURL=spancontext-utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js b/node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js new file mode 100644 index 0000000..dc88f5e --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js @@ -0,0 +1,49 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = exports.isValidTraceId = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const invalid_span_constants_1 = require("./invalid-span-constants"); +const NonRecordingSpan_1 = require("./NonRecordingSpan"); +const VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; +const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; +function isValidTraceId(traceId) { + return VALID_TRACEID_REGEX.test(traceId) && traceId !== invalid_span_constants_1.INVALID_TRACEID; +} +exports.isValidTraceId = isValidTraceId; +function isValidSpanId(spanId) { + return VALID_SPANID_REGEX.test(spanId) && spanId !== invalid_span_constants_1.INVALID_SPANID; +} +exports.isValidSpanId = isValidSpanId; +/** + * Returns true if this {@link SpanContext} is valid. + * @return true if this {@link SpanContext} is valid. + */ +function isSpanContextValid(spanContext) { + return (isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)); +} +exports.isSpanContextValid = isSpanContextValid; +/** + * Wrap the given {@link SpanContext} in a new non-recording {@link Span} + * + * @param spanContext span context to be wrapped + * @returns a new non-recording {@link Span} with the provided context + */ +function wrapSpanContext(spanContext) { + return new NonRecordingSpan_1.NonRecordingSpan(spanContext); +} +exports.wrapSpanContext = wrapSpanContext; +//# sourceMappingURL=spancontext-utils.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js.map b/node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js.map new file mode 100644 index 0000000..58358a0 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"spancontext-utils.js","sourceRoot":"","sources":["../../../src/trace/spancontext-utils.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,qEAA2E;AAC3E,yDAAsD;AAItD,MAAM,mBAAmB,GAAG,mBAAmB,CAAC;AAChD,MAAM,kBAAkB,GAAG,iBAAiB,CAAC;AAE7C,SAAgB,cAAc,CAAC,OAAe;IAC5C,OAAO,mBAAmB,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,OAAO,KAAK,wCAAe,CAAC;AAC1E,CAAC;AAFD,wCAEC;AAED,SAAgB,aAAa,CAAC,MAAc;IAC1C,OAAO,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,MAAM,KAAK,uCAAc,CAAC;AACtE,CAAC;AAFD,sCAEC;AAED;;;GAGG;AACH,SAAgB,kBAAkB,CAAC,WAAwB;IACzD,OAAO,CACL,cAAc,CAAC,WAAW,CAAC,OAAO,CAAC,IAAI,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,CACzE,CAAC;AACJ,CAAC;AAJD,gDAIC;AAED;;;;;GAKG;AACH,SAAgB,eAAe,CAAC,WAAwB;IACtD,OAAO,IAAI,mCAAgB,CAAC,WAAW,CAAC,CAAC;AAC3C,CAAC;AAFD,0CAEC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { INVALID_SPANID, INVALID_TRACEID } from './invalid-span-constants';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\n\nconst VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;\nconst VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;\n\nexport function isValidTraceId(traceId: string): boolean {\n return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID;\n}\n\nexport function isValidSpanId(spanId: string): boolean {\n return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID;\n}\n\n/**\n * Returns true if this {@link SpanContext} is valid.\n * @return true if this {@link SpanContext} is valid.\n */\nexport function isSpanContextValid(spanContext: SpanContext): boolean {\n return (\n isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)\n );\n}\n\n/**\n * Wrap the given {@link SpanContext} in a new non-recording {@link Span}\n *\n * @param spanContext span context to be wrapped\n * @returns a new non-recording {@link Span} with the provided context\n */\nexport function wrapSpanContext(spanContext: SpanContext): Span {\n return new NonRecordingSpan(spanContext);\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/status.d.ts b/node_modules/@opentelemetry/api/build/src/trace/status.d.ts new file mode 100644 index 0000000..ab19a68 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/status.d.ts @@ -0,0 +1,25 @@ +export interface SpanStatus { + /** The status code of this message. */ + code: SpanStatusCode; + /** A developer-facing error message. */ + message?: string; +} +/** + * An enumeration of status codes. + */ +export declare enum SpanStatusCode { + /** + * The default status. + */ + UNSET = 0, + /** + * The operation has been validated by an Application developer or + * Operator to have completed successfully. + */ + OK = 1, + /** + * The operation contains an error. + */ + ERROR = 2 +} +//# sourceMappingURL=status.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/status.js b/node_modules/@opentelemetry/api/build/src/trace/status.js new file mode 100644 index 0000000..50cbdef --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/status.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SpanStatusCode = void 0; +/** + * An enumeration of status codes. + */ +var SpanStatusCode; +(function (SpanStatusCode) { + /** + * The default status. + */ + SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET"; + /** + * The operation has been validated by an Application developer or + * Operator to have completed successfully. + */ + SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK"; + /** + * The operation contains an error. + */ + SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR"; +})(SpanStatusCode = exports.SpanStatusCode || (exports.SpanStatusCode = {})); +//# sourceMappingURL=status.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/status.js.map b/node_modules/@opentelemetry/api/build/src/trace/status.js.map new file mode 100644 index 0000000..b921cae --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/status.js.map @@ -0,0 +1 @@ +{"version":3,"file":"status.js","sourceRoot":"","sources":["../../../src/trace/status.ts"],"names":[],"mappings":";;;AAsBA;;GAEG;AACH,IAAY,cAcX;AAdD,WAAY,cAAc;IACxB;;OAEG;IACH,qDAAS,CAAA;IACT;;;OAGG;IACH,+CAAM,CAAA;IACN;;OAEG;IACH,qDAAS,CAAA;AACX,CAAC,EAdW,cAAc,GAAd,sBAAc,KAAd,sBAAc,QAczB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport interface SpanStatus {\n /** The status code of this message. */\n code: SpanStatusCode;\n /** A developer-facing error message. */\n message?: string;\n}\n\n/**\n * An enumeration of status codes.\n */\nexport enum SpanStatusCode {\n /**\n * The default status.\n */\n UNSET = 0,\n /**\n * The operation has been validated by an Application developer or\n * Operator to have completed successfully.\n */\n OK = 1,\n /**\n * The operation contains an error.\n */\n ERROR = 2,\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/trace_flags.d.ts b/node_modules/@opentelemetry/api/build/src/trace/trace_flags.d.ts new file mode 100644 index 0000000..11288ba --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/trace_flags.d.ts @@ -0,0 +1,7 @@ +export declare enum TraceFlags { + /** Represents no flag set. */ + NONE = 0, + /** Bit to represent whether trace is sampled in trace flags. */ + SAMPLED = 1 +} +//# sourceMappingURL=trace_flags.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/trace_flags.js b/node_modules/@opentelemetry/api/build/src/trace/trace_flags.js new file mode 100644 index 0000000..f8d4dd8 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/trace_flags.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TraceFlags = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var TraceFlags; +(function (TraceFlags) { + /** Represents no flag set. */ + TraceFlags[TraceFlags["NONE"] = 0] = "NONE"; + /** Bit to represent whether trace is sampled in trace flags. */ + TraceFlags[TraceFlags["SAMPLED"] = 1] = "SAMPLED"; +})(TraceFlags = exports.TraceFlags || (exports.TraceFlags = {})); +//# sourceMappingURL=trace_flags.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/trace_flags.js.map b/node_modules/@opentelemetry/api/build/src/trace/trace_flags.js.map new file mode 100644 index 0000000..965ce79 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/trace_flags.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trace_flags.js","sourceRoot":"","sources":["../../../src/trace/trace_flags.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,IAAY,UAKX;AALD,WAAY,UAAU;IACpB,8BAA8B;IAC9B,2CAAU,CAAA;IACV,gEAAgE;IAChE,iDAAkB,CAAA;AACpB,CAAC,EALW,UAAU,GAAV,kBAAU,KAAV,kBAAU,QAKrB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport enum TraceFlags {\n /** Represents no flag set. */\n NONE = 0x0,\n /** Bit to represent whether trace is sampled in trace flags. */\n SAMPLED = 0x1 << 0,\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/trace_state.d.ts b/node_modules/@opentelemetry/api/build/src/trace/trace_state.d.ts new file mode 100644 index 0000000..f275b8b --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/trace_state.d.ts @@ -0,0 +1,38 @@ +export interface TraceState { + /** + * Create a new TraceState which inherits from this TraceState and has the + * given key set. + * The new entry will always be added in the front of the list of states. + * + * @param key key of the TraceState entry. + * @param value value of the TraceState entry. + */ + set(key: string, value: string): TraceState; + /** + * Return a new TraceState which inherits from this TraceState but does not + * contain the given key. + * + * @param key the key for the TraceState entry to be removed. + */ + unset(key: string): TraceState; + /** + * Returns the value to which the specified key is mapped, or `undefined` if + * this map contains no mapping for the key. + * + * @param key with which the specified value is to be associated. + * @returns the value to which the specified key is mapped, or `undefined` if + * this map contains no mapping for the key. + */ + get(key: string): string | undefined; + /** + * Serializes the TraceState to a `list` as defined below. The `list` is a + * series of `list-members` separated by commas `,`, and a list-member is a + * key/value pair separated by an equals sign `=`. Spaces and horizontal tabs + * surrounding `list-members` are ignored. There can be a maximum of 32 + * `list-members` in a `list`. + * + * @returns the serialized string. + */ + serialize(): string; +} +//# sourceMappingURL=trace_state.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/trace_state.js b/node_modules/@opentelemetry/api/build/src/trace/trace_state.js new file mode 100644 index 0000000..1397038 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/trace_state.js @@ -0,0 +1,18 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=trace_state.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/trace_state.js.map b/node_modules/@opentelemetry/api/build/src/trace/trace_state.js.map new file mode 100644 index 0000000..267f2e8 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/trace_state.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trace_state.js","sourceRoot":"","sources":["../../../src/trace/trace_state.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface TraceState {\n /**\n * Create a new TraceState which inherits from this TraceState and has the\n * given key set.\n * The new entry will always be added in the front of the list of states.\n *\n * @param key key of the TraceState entry.\n * @param value value of the TraceState entry.\n */\n set(key: string, value: string): TraceState;\n\n /**\n * Return a new TraceState which inherits from this TraceState but does not\n * contain the given key.\n *\n * @param key the key for the TraceState entry to be removed.\n */\n unset(key: string): TraceState;\n\n /**\n * Returns the value to which the specified key is mapped, or `undefined` if\n * this map contains no mapping for the key.\n *\n * @param key with which the specified value is to be associated.\n * @returns the value to which the specified key is mapped, or `undefined` if\n * this map contains no mapping for the key.\n */\n get(key: string): string | undefined;\n\n // TODO: Consider to add support for merging an object as well by also\n // accepting a single internalTraceState argument similar to the constructor.\n\n /**\n * Serializes the TraceState to a `list` as defined below. The `list` is a\n * series of `list-members` separated by commas `,`, and a list-member is a\n * key/value pair separated by an equals sign `=`. Spaces and horizontal tabs\n * surrounding `list-members` are ignored. There can be a maximum of 32\n * `list-members` in a `list`.\n *\n * @returns the serialized string.\n */\n serialize(): string;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/tracer.d.ts b/node_modules/@opentelemetry/api/build/src/trace/tracer.d.ts new file mode 100644 index 0000000..2509089 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/tracer.d.ts @@ -0,0 +1,71 @@ +import { Context } from '../context/types'; +import { Span } from './span'; +import { SpanOptions } from './SpanOptions'; +/** + * Tracer provides an interface for creating {@link Span}s. + */ +export interface Tracer { + /** + * Starts a new {@link Span}. Start the span without setting it on context. + * + * This method do NOT modify the current Context. + * + * @param name The name of the span + * @param [options] SpanOptions used for span creation + * @param [context] Context to use to extract parent + * @returns Span The newly created span + * @example + * const span = tracer.startSpan('op'); + * span.setAttribute('key', 'value'); + * span.end(); + */ + startSpan(name: string, options?: SpanOptions, context?: Context): Span; + /** + * Starts a new {@link Span} and calls the given function passing it the + * created span as first argument. + * Additionally the new span gets set in context and this context is activated + * for the duration of the function call. + * + * @param name The name of the span + * @param [options] SpanOptions used for span creation + * @param [context] Context to use to extract parent + * @param fn function called in the context of the span and receives the newly created span as an argument + * @returns return value of fn + * @example + * const something = tracer.startActiveSpan('op', span => { + * try { + * do some work + * span.setStatus({code: SpanStatusCode.OK}); + * return something; + * } catch (err) { + * span.setStatus({ + * code: SpanStatusCode.ERROR, + * message: err.message, + * }); + * throw err; + * } finally { + * span.end(); + * } + * }); + * + * @example + * const span = tracer.startActiveSpan('op', span => { + * try { + * do some work + * return span; + * } catch (err) { + * span.setStatus({ + * code: SpanStatusCode.ERROR, + * message: err.message, + * }); + * throw err; + * } + * }); + * do some more work + * span.end(); + */ + startActiveSpan unknown>(name: string, fn: F): ReturnType; + startActiveSpan unknown>(name: string, options: SpanOptions, fn: F): ReturnType; + startActiveSpan unknown>(name: string, options: SpanOptions, context: Context, fn: F): ReturnType; +} +//# sourceMappingURL=tracer.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/tracer.js b/node_modules/@opentelemetry/api/build/src/trace/tracer.js new file mode 100644 index 0000000..d710ef9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/tracer.js @@ -0,0 +1,18 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=tracer.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/tracer.js.map b/node_modules/@opentelemetry/api/build/src/trace/tracer.js.map new file mode 100644 index 0000000..3c3c591 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/tracer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tracer.js","sourceRoot":"","sources":["../../../src/trace/tracer.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport { Span } from './span';\nimport { SpanOptions } from './SpanOptions';\n\n/**\n * Tracer provides an interface for creating {@link Span}s.\n */\nexport interface Tracer {\n /**\n * Starts a new {@link Span}. Start the span without setting it on context.\n *\n * This method do NOT modify the current Context.\n *\n * @param name The name of the span\n * @param [options] SpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @returns Span The newly created span\n * @example\n * const span = tracer.startSpan('op');\n * span.setAttribute('key', 'value');\n * span.end();\n */\n startSpan(name: string, options?: SpanOptions, context?: Context): Span;\n\n /**\n * Starts a new {@link Span} and calls the given function passing it the\n * created span as first argument.\n * Additionally the new span gets set in context and this context is activated\n * for the duration of the function call.\n *\n * @param name The name of the span\n * @param [options] SpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns return value of fn\n * @example\n * const something = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * span.setStatus({code: SpanStatusCode.OK});\n * return something;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * } finally {\n * span.end();\n * }\n * });\n *\n * @example\n * const span = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * return span;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * }\n * });\n * do some more work\n * span.end();\n */\n startActiveSpan unknown>(\n name: string,\n fn: F\n ): ReturnType;\n startActiveSpan unknown>(\n name: string,\n options: SpanOptions,\n fn: F\n ): ReturnType;\n startActiveSpan unknown>(\n name: string,\n options: SpanOptions,\n context: Context,\n fn: F\n ): ReturnType;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/tracer_options.d.ts b/node_modules/@opentelemetry/api/build/src/trace/tracer_options.d.ts new file mode 100644 index 0000000..f3bbccf --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/tracer_options.d.ts @@ -0,0 +1,10 @@ +/** + * An interface describes additional metadata of a tracer. + */ +export interface TracerOptions { + /** + * The schemaUrl of the tracer or instrumentation library + */ + schemaUrl?: string; +} +//# sourceMappingURL=tracer_options.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/tracer_options.js b/node_modules/@opentelemetry/api/build/src/trace/tracer_options.js new file mode 100644 index 0000000..3547251 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/tracer_options.js @@ -0,0 +1,18 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=tracer_options.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/tracer_options.js.map b/node_modules/@opentelemetry/api/build/src/trace/tracer_options.js.map new file mode 100644 index 0000000..a743252 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/tracer_options.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tracer_options.js","sourceRoot":"","sources":["../../../src/trace/tracer_options.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An interface describes additional metadata of a tracer.\n */\nexport interface TracerOptions {\n /**\n * The schemaUrl of the tracer or instrumentation library\n */\n schemaUrl?: string;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/tracer_provider.d.ts b/node_modules/@opentelemetry/api/build/src/trace/tracer_provider.d.ts new file mode 100644 index 0000000..9b2f7a9 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/tracer_provider.d.ts @@ -0,0 +1,21 @@ +import { Tracer } from './tracer'; +import { TracerOptions } from './tracer_options'; +/** + * A registry for creating named {@link Tracer}s. + */ +export interface TracerProvider { + /** + * Returns a Tracer, creating one if one with the given name and version is + * not already created. + * + * This function may return different Tracer types (e.g. + * {@link NoopTracerProvider} vs. a functional tracer). + * + * @param name The name of the tracer or instrumentation library. + * @param version The version of the tracer or instrumentation library. + * @param options The options of the tracer or instrumentation library. + * @returns Tracer A Tracer with the given name and version + */ + getTracer(name: string, version?: string, options?: TracerOptions): Tracer; +} +//# sourceMappingURL=tracer_provider.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/tracer_provider.js b/node_modules/@opentelemetry/api/build/src/trace/tracer_provider.js new file mode 100644 index 0000000..4c511db --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/tracer_provider.js @@ -0,0 +1,18 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=tracer_provider.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/trace/tracer_provider.js.map b/node_modules/@opentelemetry/api/build/src/trace/tracer_provider.js.map new file mode 100644 index 0000000..31f334a --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/trace/tracer_provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tracer_provider.js","sourceRoot":"","sources":["../../../src/trace/tracer_provider.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Tracer } from './tracer';\nimport { TracerOptions } from './tracer_options';\n\n/**\n * A registry for creating named {@link Tracer}s.\n */\nexport interface TracerProvider {\n /**\n * Returns a Tracer, creating one if one with the given name and version is\n * not already created.\n *\n * This function may return different Tracer types (e.g.\n * {@link NoopTracerProvider} vs. a functional tracer).\n *\n * @param name The name of the tracer or instrumentation library.\n * @param version The version of the tracer or instrumentation library.\n * @param options The options of the tracer or instrumentation library.\n * @returns Tracer A Tracer with the given name and version\n */\n getTracer(name: string, version?: string, options?: TracerOptions): Tracer;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/version.d.ts b/node_modules/@opentelemetry/api/build/src/version.d.ts new file mode 100644 index 0000000..40f0365 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/version.d.ts @@ -0,0 +1,2 @@ +export declare const VERSION = "1.9.0"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/version.js b/node_modules/@opentelemetry/api/build/src/version.js new file mode 100644 index 0000000..3c71794 --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/version.js @@ -0,0 +1,21 @@ +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.VERSION = void 0; +// this is autogenerated file, see scripts/version-update.js +exports.VERSION = '1.9.0'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/build/src/version.js.map b/node_modules/@opentelemetry/api/build/src/version.js.map new file mode 100644 index 0000000..ee3c12c --- /dev/null +++ b/node_modules/@opentelemetry/api/build/src/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4DAA4D;AAC/C,QAAA,OAAO,GAAG,OAAO,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.9.0';\n"]} \ No newline at end of file diff --git a/node_modules/@opentelemetry/api/package.json b/node_modules/@opentelemetry/api/package.json new file mode 100644 index 0000000..f7ba45f --- /dev/null +++ b/node_modules/@opentelemetry/api/package.json @@ -0,0 +1,113 @@ +{ + "name": "@opentelemetry/api", + "version": "1.9.0", + "description": "Public API for OpenTelemetry", + "main": "build/src/index.js", + "module": "build/esm/index.js", + "esnext": "build/esnext/index.js", + "types": "build/src/index.d.ts", + "browser": { + "./src/platform/index.ts": "./src/platform/browser/index.ts", + "./build/esm/platform/index.js": "./build/esm/platform/browser/index.js", + "./build/esnext/platform/index.js": "./build/esnext/platform/browser/index.js", + "./build/src/platform/index.js": "./build/src/platform/browser/index.js" + }, + "exports": { + ".": { + "module": "./build/esm/index.js", + "esnext": "./build/esnext/index.js", + "types": "./build/src/index.d.ts", + "default": "./build/src/index.js" + }, + "./experimental": { + "module": "./build/esm/experimental/index.js", + "esnext": "./build/esnext/experimental/index.js", + "types": "./build/src/experimental/index.d.ts", + "default": "./build/src/experimental/index.js" + } + }, + "repository": "open-telemetry/opentelemetry-js", + "scripts": { + "clean": "tsc --build --clean tsconfig.json tsconfig.esm.json tsconfig.esnext.json", + "codecov:browser": "nyc report --reporter=json && codecov -f coverage/*.json -p ../", + "codecov:webworker": "nyc report --reporter=json && codecov -f coverage/*.json -p ../", + "codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../", + "precompile": "cross-var lerna run version --scope $npm_package_name --include-dependencies", + "compile": "tsc --build tsconfig.json tsconfig.esm.json tsconfig.esnext.json", + "docs": "typedoc", + "docs:deploy": "gh-pages --dist docs/out", + "docs:test": "linkinator docs/out --silent && linkinator docs/*.md *.md --markdown --silent", + "lint:fix": "eslint . --ext .ts --fix", + "lint": "eslint . --ext .ts", + "test:browser": "karma start --single-run", + "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.test.ts'", + "test:eol": "ts-mocha -p tsconfig.json 'test/**/*.test.ts'", + "test:webworker": "karma start karma.worker.js --single-run", + "cycle-check": "dpdm --exit-code circular:1 src/index.ts", + "version": "node ../scripts/version-update.js", + "prewatch": "npm run precompile", + "watch": "tsc --build --watch tsconfig.json tsconfig.esm.json tsconfig.esnext.json", + "peer-api-check": "node ../scripts/peer-api-check.js" + }, + "keywords": [ + "opentelemetry", + "nodejs", + "browser", + "tracing", + "profiling", + "stats", + "monitoring" + ], + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + }, + "files": [ + "build/esm/**/*.js", + "build/esm/**/*.js.map", + "build/esm/**/*.d.ts", + "build/esnext/**/*.js", + "build/esnext/**/*.js.map", + "build/esnext/**/*.d.ts", + "build/src/**/*.js", + "build/src/**/*.js.map", + "build/src/**/*.d.ts", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "@types/mocha": "10.0.6", + "@types/node": "18.6.5", + "@types/sinon": "17.0.3", + "@types/webpack": "5.28.5", + "@types/webpack-env": "1.16.3", + "babel-plugin-istanbul": "6.1.1", + "codecov": "3.8.3", + "cross-var": "1.1.0", + "dpdm": "3.13.1", + "karma": "6.4.3", + "karma-chrome-launcher": "3.1.0", + "karma-coverage": "2.2.1", + "karma-mocha": "2.0.1", + "karma-mocha-webworker": "1.3.0", + "karma-spec-reporter": "0.0.36", + "karma-webpack": "5.0.1", + "lerna": "6.6.2", + "memfs": "3.5.3", + "mocha": "10.2.0", + "nyc": "15.1.0", + "sinon": "15.1.2", + "ts-loader": "9.5.1", + "ts-mocha": "10.0.0", + "typescript": "4.4.4", + "unionfs": "4.5.4", + "webpack": "5.89.0" + }, + "homepage": "https://github.com/open-telemetry/opentelemetry-js/tree/main/api", + "sideEffects": false, + "gitHead": "c4d3351b6b3f5593c8d7cbfec97b45cea9fe1511" +} diff --git a/node_modules/@protobufjs/aspromise/LICENSE b/node_modules/@protobufjs/aspromise/LICENSE new file mode 100644 index 0000000..be2b397 --- /dev/null +++ b/node_modules/@protobufjs/aspromise/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@protobufjs/aspromise/README.md b/node_modules/@protobufjs/aspromise/README.md new file mode 100644 index 0000000..c7ae36f --- /dev/null +++ b/node_modules/@protobufjs/aspromise/README.md @@ -0,0 +1,13 @@ +@protobufjs/aspromise +===================== +[![npm](https://img.shields.io/npm/v/@protobufjs/aspromise.svg)](https://www.npmjs.com/package/@protobufjs/aspromise) + +Returns a promise from a node-style callback function. + +API +--- + +* **asPromise(fn: `function`, ctx: `Object`, ...params: `*`): `Promise<*>`**
                          + Returns a promise from a node-style callback function. + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/@protobufjs/aspromise/index.d.ts b/node_modules/@protobufjs/aspromise/index.d.ts new file mode 100644 index 0000000..3db03db --- /dev/null +++ b/node_modules/@protobufjs/aspromise/index.d.ts @@ -0,0 +1,13 @@ +export = asPromise; + +type asPromiseCallback = (error: Error | null, ...params: any[]) => {}; + +/** + * Returns a promise from a node-style callback function. + * @memberof util + * @param {asPromiseCallback} fn Function to call + * @param {*} ctx Function context + * @param {...*} params Function arguments + * @returns {Promise<*>} Promisified function + */ +declare function asPromise(fn: asPromiseCallback, ctx: any, ...params: any[]): Promise; diff --git a/node_modules/@protobufjs/aspromise/index.js b/node_modules/@protobufjs/aspromise/index.js new file mode 100644 index 0000000..d6f642c --- /dev/null +++ b/node_modules/@protobufjs/aspromise/index.js @@ -0,0 +1,52 @@ +"use strict"; +module.exports = asPromise; + +/** + * Callback as used by {@link util.asPromise}. + * @typedef asPromiseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {...*} params Additional arguments + * @returns {undefined} + */ + +/** + * Returns a promise from a node-style callback function. + * @memberof util + * @param {asPromiseCallback} fn Function to call + * @param {*} ctx Function context + * @param {...*} params Function arguments + * @returns {Promise<*>} Promisified function + */ +function asPromise(fn, ctx/*, varargs */) { + var params = new Array(arguments.length - 1), + offset = 0, + index = 2, + pending = true; + while (index < arguments.length) + params[offset++] = arguments[index++]; + return new Promise(function executor(resolve, reject) { + params[offset] = function callback(err/*, varargs */) { + if (pending) { + pending = false; + if (err) + reject(err); + else { + var params = new Array(arguments.length - 1), + offset = 0; + while (offset < params.length) + params[offset++] = arguments[offset]; + resolve.apply(null, params); + } + } + }; + try { + fn.apply(ctx || null, params); + } catch (err) { + if (pending) { + pending = false; + reject(err); + } + } + }); +} diff --git a/node_modules/@protobufjs/aspromise/package.json b/node_modules/@protobufjs/aspromise/package.json new file mode 100644 index 0000000..aa8eaef --- /dev/null +++ b/node_modules/@protobufjs/aspromise/package.json @@ -0,0 +1,21 @@ +{ + "name": "@protobufjs/aspromise", + "description": "Returns a promise from a node-style callback function.", + "version": "1.1.2", + "author": "Daniel Wirtz ", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/protobuf.js.git" + }, + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "devDependencies": { + "istanbul": "^0.4.5", + "tape": "^4.6.3" + }, + "scripts": { + "test": "tape tests/*.js", + "coverage": "istanbul cover node_modules/tape/bin/tape tests/*.js" + } +} \ No newline at end of file diff --git a/node_modules/@protobufjs/aspromise/tests/index.js b/node_modules/@protobufjs/aspromise/tests/index.js new file mode 100644 index 0000000..cfdb258 --- /dev/null +++ b/node_modules/@protobufjs/aspromise/tests/index.js @@ -0,0 +1,130 @@ +var tape = require("tape"); + +var asPromise = require(".."); + +tape.test("aspromise", function(test) { + + test.test(this.name + " - resolve", function(test) { + + function fn(arg1, arg2, callback) { + test.equal(this, ctx, "function should be called with this = ctx"); + test.equal(arg1, 1, "function should be called with arg1 = 1"); + test.equal(arg2, 2, "function should be called with arg2 = 2"); + callback(null, arg2); + } + + var ctx = {}; + + var promise = asPromise(fn, ctx, 1, 2); + promise.then(function(arg2) { + test.equal(arg2, 2, "promise should be resolved with arg2 = 2"); + test.end(); + }).catch(function(err) { + test.fail("promise should not be rejected (" + err + ")"); + }); + }); + + test.test(this.name + " - reject", function(test) { + + function fn(arg1, arg2, callback) { + test.equal(this, ctx, "function should be called with this = ctx"); + test.equal(arg1, 1, "function should be called with arg1 = 1"); + test.equal(arg2, 2, "function should be called with arg2 = 2"); + callback(arg1); + } + + var ctx = {}; + + var promise = asPromise(fn, ctx, 1, 2); + promise.then(function() { + test.fail("promise should not be resolved"); + }).catch(function(err) { + test.equal(err, 1, "promise should be rejected with err = 1"); + test.end(); + }); + }); + + test.test(this.name + " - resolve twice", function(test) { + + function fn(arg1, arg2, callback) { + test.equal(this, ctx, "function should be called with this = ctx"); + test.equal(arg1, 1, "function should be called with arg1 = 1"); + test.equal(arg2, 2, "function should be called with arg2 = 2"); + callback(null, arg2); + callback(null, arg1); + } + + var ctx = {}; + var count = 0; + + var promise = asPromise(fn, ctx, 1, 2); + promise.then(function(arg2) { + test.equal(arg2, 2, "promise should be resolved with arg2 = 2"); + if (++count > 1) + test.fail("promise should not be resolved twice"); + test.end(); + }).catch(function(err) { + test.fail("promise should not be rejected (" + err + ")"); + }); + }); + + test.test(this.name + " - reject twice", function(test) { + + function fn(arg1, arg2, callback) { + test.equal(this, ctx, "function should be called with this = ctx"); + test.equal(arg1, 1, "function should be called with arg1 = 1"); + test.equal(arg2, 2, "function should be called with arg2 = 2"); + callback(arg1); + callback(arg2); + } + + var ctx = {}; + var count = 0; + + var promise = asPromise(fn, ctx, 1, 2); + promise.then(function() { + test.fail("promise should not be resolved"); + }).catch(function(err) { + test.equal(err, 1, "promise should be rejected with err = 1"); + if (++count > 1) + test.fail("promise should not be rejected twice"); + test.end(); + }); + }); + + test.test(this.name + " - reject error", function(test) { + + function fn(callback) { + test.ok(arguments.length === 1 && typeof callback === "function", "function should be called with just a callback"); + throw 3; + } + + var promise = asPromise(fn, null); + promise.then(function() { + test.fail("promise should not be resolved"); + }).catch(function(err) { + test.equal(err, 3, "promise should be rejected with err = 3"); + test.end(); + }); + }); + + test.test(this.name + " - reject and error", function(test) { + + function fn(callback) { + callback(3); + throw 4; + } + + var count = 0; + + var promise = asPromise(fn, null); + promise.then(function() { + test.fail("promise should not be resolved"); + }).catch(function(err) { + test.equal(err, 3, "promise should be rejected with err = 3"); + if (++count > 1) + test.fail("promise should not be rejected twice"); + test.end(); + }); + }); +}); diff --git a/node_modules/@protobufjs/base64/LICENSE b/node_modules/@protobufjs/base64/LICENSE new file mode 100644 index 0000000..be2b397 --- /dev/null +++ b/node_modules/@protobufjs/base64/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@protobufjs/base64/README.md b/node_modules/@protobufjs/base64/README.md new file mode 100644 index 0000000..b06cb0a --- /dev/null +++ b/node_modules/@protobufjs/base64/README.md @@ -0,0 +1,19 @@ +@protobufjs/base64 +================== +[![npm](https://img.shields.io/npm/v/@protobufjs/base64.svg)](https://www.npmjs.com/package/@protobufjs/base64) + +A minimal base64 implementation for number arrays. + +API +--- + +* **base64.length(string: `string`): `number`**
                          + Calculates the byte length of a base64 encoded string. + +* **base64.encode(buffer: `Uint8Array`, start: `number`, end: `number`): `string`**
                          + Encodes a buffer to a base64 encoded string. + +* **base64.decode(string: `string`, buffer: `Uint8Array`, offset: `number`): `number`**
                          + Decodes a base64 encoded string to a buffer. + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/@protobufjs/base64/index.d.ts b/node_modules/@protobufjs/base64/index.d.ts new file mode 100644 index 0000000..085d0a7 --- /dev/null +++ b/node_modules/@protobufjs/base64/index.d.ts @@ -0,0 +1,32 @@ +/** + * Calculates the byte length of a base64 encoded string. + * @param {string} string Base64 encoded string + * @returns {number} Byte length + */ +export function length(string: string): number; + +/** + * Encodes a buffer to a base64 encoded string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} Base64 encoded string + */ +export function encode(buffer: Uint8Array, start: number, end: number): string; + +/** + * Decodes a base64 encoded string to a buffer. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Number of bytes written + * @throws {Error} If encoding is invalid + */ +export function decode(string: string, buffer: Uint8Array, offset: number): number; + +/** + * Tests if the specified string appears to be base64 encoded. + * @param {string} string String to test + * @returns {boolean} `true` if it appears to be base64 encoded, otherwise false + */ +export function test(string: string): boolean; diff --git a/node_modules/@protobufjs/base64/index.js b/node_modules/@protobufjs/base64/index.js new file mode 100644 index 0000000..6146f54 --- /dev/null +++ b/node_modules/@protobufjs/base64/index.js @@ -0,0 +1,139 @@ +"use strict"; + +/** + * A minimal base64 implementation for number arrays. + * @memberof util + * @namespace + */ +var base64 = exports; + +/** + * Calculates the byte length of a base64 encoded string. + * @param {string} string Base64 encoded string + * @returns {number} Byte length + */ +base64.length = function length(string) { + var p = string.length; + if (!p) + return 0; + var n = 0; + while (--p % 4 > 1 && string.charAt(p) === "=") + ++n; + return Math.ceil(string.length * 3) / 4 - n; +}; + +// Base64 encoding table +var b64 = new Array(64); + +// Base64 decoding table +var s64 = new Array(123); + +// 65..90, 97..122, 48..57, 43, 47 +for (var i = 0; i < 64;) + s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; + +/** + * Encodes a buffer to a base64 encoded string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} Base64 encoded string + */ +base64.encode = function encode(buffer, start, end) { + var parts = null, + chunk = []; + var i = 0, // output index + j = 0, // goto index + t; // temporary + while (start < end) { + var b = buffer[start++]; + switch (j) { + case 0: + chunk[i++] = b64[b >> 2]; + t = (b & 3) << 4; + j = 1; + break; + case 1: + chunk[i++] = b64[t | b >> 4]; + t = (b & 15) << 2; + j = 2; + break; + case 2: + chunk[i++] = b64[t | b >> 6]; + chunk[i++] = b64[b & 63]; + j = 0; + break; + } + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i = 0; + } + } + if (j) { + chunk[i++] = b64[t]; + chunk[i++] = 61; + if (j === 1) + chunk[i++] = 61; + } + if (parts) { + if (i) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i)); +}; + +var invalidEncoding = "invalid encoding"; + +/** + * Decodes a base64 encoded string to a buffer. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Number of bytes written + * @throws {Error} If encoding is invalid + */ +base64.decode = function decode(string, buffer, offset) { + var start = offset; + var j = 0, // goto index + t; // temporary + for (var i = 0; i < string.length;) { + var c = string.charCodeAt(i++); + if (c === 61 && j > 1) + break; + if ((c = s64[c]) === undefined) + throw Error(invalidEncoding); + switch (j) { + case 0: + t = c; + j = 1; + break; + case 1: + buffer[offset++] = t << 2 | (c & 48) >> 4; + t = c; + j = 2; + break; + case 2: + buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; + t = c; + j = 3; + break; + case 3: + buffer[offset++] = (t & 3) << 6 | c; + j = 0; + break; + } + } + if (j === 1) + throw Error(invalidEncoding); + return offset - start; +}; + +/** + * Tests if the specified string appears to be base64 encoded. + * @param {string} string String to test + * @returns {boolean} `true` if probably base64 encoded, otherwise false + */ +base64.test = function test(string) { + return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string); +}; diff --git a/node_modules/@protobufjs/base64/package.json b/node_modules/@protobufjs/base64/package.json new file mode 100644 index 0000000..f119811 --- /dev/null +++ b/node_modules/@protobufjs/base64/package.json @@ -0,0 +1,21 @@ +{ + "name": "@protobufjs/base64", + "description": "A minimal base64 implementation for number arrays.", + "version": "1.1.2", + "author": "Daniel Wirtz ", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/protobuf.js.git" + }, + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "devDependencies": { + "istanbul": "^0.4.5", + "tape": "^4.6.3" + }, + "scripts": { + "test": "tape tests/*.js", + "coverage": "istanbul cover node_modules/tape/bin/tape tests/*.js" + } +} \ No newline at end of file diff --git a/node_modules/@protobufjs/base64/tests/index.js b/node_modules/@protobufjs/base64/tests/index.js new file mode 100644 index 0000000..6ede32c --- /dev/null +++ b/node_modules/@protobufjs/base64/tests/index.js @@ -0,0 +1,46 @@ +var tape = require("tape"); + +var base64 = require(".."); + +var strings = { + "": "", + "a": "YQ==", + "ab": "YWI=", + "abcdefg": "YWJjZGVmZw==", + "abcdefgh": "YWJjZGVmZ2g=", + "abcdefghi": "YWJjZGVmZ2hp" +}; + +tape.test("base64", function(test) { + + Object.keys(strings).forEach(function(str) { + var enc = strings[str]; + + test.equal(base64.test(enc), true, "should detect '" + enc + "' to be base64 encoded"); + + var len = base64.length(enc); + test.equal(len, str.length, "should calculate '" + enc + "' as " + str.length + " bytes"); + + var buf = new Array(len); + var len2 = base64.decode(enc, buf, 0); + test.equal(len2, len, "should decode '" + enc + "' to " + len + " bytes"); + + test.equal(String.fromCharCode.apply(String, buf), str, "should decode '" + enc + "' to '" + str + "'"); + + var enc2 = base64.encode(buf, 0, buf.length); + test.equal(enc2, enc, "should encode '" + str + "' to '" + enc + "'"); + + }); + + test.throws(function() { + var buf = new Array(10); + base64.decode("YQ!", buf, 0); + }, Error, "should throw if encoding is invalid"); + + test.throws(function() { + var buf = new Array(10); + base64.decode("Y", buf, 0); + }, Error, "should throw if string is truncated"); + + test.end(); +}); diff --git a/node_modules/@protobufjs/codegen/LICENSE b/node_modules/@protobufjs/codegen/LICENSE new file mode 100644 index 0000000..be2b397 --- /dev/null +++ b/node_modules/@protobufjs/codegen/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@protobufjs/codegen/README.md b/node_modules/@protobufjs/codegen/README.md new file mode 100644 index 0000000..577c43e --- /dev/null +++ b/node_modules/@protobufjs/codegen/README.md @@ -0,0 +1,49 @@ +@protobufjs/codegen +=================== +[![npm](https://img.shields.io/npm/v/@protobufjs/codegen.svg)](https://www.npmjs.com/package/@protobufjs/codegen) + +A minimalistic code generation utility. + +API +--- + +* **codegen([functionParams: `string[]`], [functionName: string]): `Codegen`**
                          + Begins generating a function. + +* **codegen.verbose = `false`**
                          + When set to true, codegen will log generated code to console. Useful for debugging. + +Invoking **codegen** returns an appender function that appends code to the function's body and returns itself: + +* **Codegen(formatString: `string`, [...formatParams: `any`]): Codegen**
                          + Appends code to the function's body. The format string can contain placeholders specifying the types of inserted format parameters: + + * `%d`: Number (integer or floating point value) + * `%f`: Floating point value + * `%i`: Integer value + * `%j`: JSON.stringify'ed value + * `%s`: String value + * `%%`: Percent sign
                          + +* **Codegen([scope: `Object.`]): `Function`**
                          + Finishes the function and returns it. + +* **Codegen.toString([functionNameOverride: `string`]): `string`**
                          + Returns the function as a string. + +Example +------- + +```js +var codegen = require("@protobufjs/codegen"); + +var add = codegen(["a", "b"], "add") // A function with parameters "a" and "b" named "add" + ("// awesome comment") // adds the line to the function's body + ("return a + b - c + %d", 1) // replaces %d with 1 and adds the line to the body + ({ c: 1 }); // adds "c" with a value of 1 to the function's scope + +console.log(add.toString()); // function add(a, b) { return a + b - c + 1 } +console.log(add(1, 2)); // calculates 1 + 2 - 1 + 1 = 3 +``` + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/@protobufjs/codegen/index.d.ts b/node_modules/@protobufjs/codegen/index.d.ts new file mode 100644 index 0000000..f8ed908 --- /dev/null +++ b/node_modules/@protobufjs/codegen/index.d.ts @@ -0,0 +1,31 @@ +export = codegen; + +/** + * Appends code to the function's body. + * @param [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any + * @param [formatParams] Format parameters + * @returns Itself or the generated function if finished + * @throws {Error} If format parameter counts do not match + */ +type Codegen = (formatStringOrScope?: (string|{ [k: string]: any }), ...formatParams: any[]) => (Codegen|Function); + +/** + * Begins generating a function. + * @param functionParams Function parameter names + * @param [functionName] Function name if not anonymous + * @returns Appender that appends code to the function's body + */ +declare function codegen(functionParams: string[], functionName?: string): Codegen; + +/** + * Begins generating a function. + * @param [functionName] Function name if not anonymous + * @returns Appender that appends code to the function's body + */ +declare function codegen(functionName?: string): Codegen; + +declare namespace codegen { + + /** When set to `true`, codegen will log generated code to console. Useful for debugging. */ + let verbose: boolean; +} diff --git a/node_modules/@protobufjs/codegen/index.js b/node_modules/@protobufjs/codegen/index.js new file mode 100644 index 0000000..af005cb --- /dev/null +++ b/node_modules/@protobufjs/codegen/index.js @@ -0,0 +1,99 @@ +"use strict"; +module.exports = codegen; + +/** + * Begins generating a function. + * @memberof util + * @param {string[]} functionParams Function parameter names + * @param {string} [functionName] Function name if not anonymous + * @returns {Codegen} Appender that appends code to the function's body + */ +function codegen(functionParams, functionName) { + + /* istanbul ignore if */ + if (typeof functionParams === "string") { + functionName = functionParams; + functionParams = undefined; + } + + var body = []; + + /** + * Appends code to the function's body or finishes generation. + * @typedef Codegen + * @type {function} + * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any + * @param {...*} [formatParams] Format parameters + * @returns {Codegen|Function} Itself or the generated function if finished + * @throws {Error} If format parameter counts do not match + */ + + function Codegen(formatStringOrScope) { + // note that explicit array handling below makes this ~50% faster + + // finish the function + if (typeof formatStringOrScope !== "string") { + var source = toString(); + if (codegen.verbose) + console.log("codegen: " + source); // eslint-disable-line no-console + source = "return " + source; + if (formatStringOrScope) { + var scopeKeys = Object.keys(formatStringOrScope), + scopeParams = new Array(scopeKeys.length + 1), + scopeValues = new Array(scopeKeys.length), + scopeOffset = 0; + while (scopeOffset < scopeKeys.length) { + scopeParams[scopeOffset] = scopeKeys[scopeOffset]; + scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]]; + } + scopeParams[scopeOffset] = source; + return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func + } + return Function(source)(); // eslint-disable-line no-new-func + } + + // otherwise append to body + var formatParams = new Array(arguments.length - 1), + formatOffset = 0; + while (formatOffset < formatParams.length) + formatParams[formatOffset] = arguments[++formatOffset]; + formatOffset = 0; + formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) { + var value = formatParams[formatOffset++]; + switch ($1) { + case "d": case "f": return String(Number(value)); + case "i": return String(Math.floor(value)); + case "j": return JSON.stringify(value); + case "s": return String(value); + } + return "%"; + }); + if (formatOffset !== formatParams.length) + throw Error("parameter count mismatch"); + body.push(formatStringOrScope); + return Codegen; + } + + function toString(functionNameOverride) { + return "function " + (functionNameOverride || functionName || "") + "(" + (functionParams && functionParams.join(",") || "") + "){\n " + body.join("\n ") + "\n}"; + } + + Codegen.toString = toString; + return Codegen; +} + +/** + * Begins generating a function. + * @memberof util + * @function codegen + * @param {string} [functionName] Function name if not anonymous + * @returns {Codegen} Appender that appends code to the function's body + * @variation 2 + */ + +/** + * When set to `true`, codegen will log generated code to console. Useful for debugging. + * @name util.codegen.verbose + * @type {boolean} + */ +codegen.verbose = false; diff --git a/node_modules/@protobufjs/codegen/package.json b/node_modules/@protobufjs/codegen/package.json new file mode 100644 index 0000000..4e82f95 --- /dev/null +++ b/node_modules/@protobufjs/codegen/package.json @@ -0,0 +1,13 @@ +{ + "name": "@protobufjs/codegen", + "description": "A minimalistic code generation utility.", + "version": "2.0.4", + "author": "Daniel Wirtz ", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/protobuf.js.git" + }, + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts" +} \ No newline at end of file diff --git a/node_modules/@protobufjs/codegen/tests/index.js b/node_modules/@protobufjs/codegen/tests/index.js new file mode 100644 index 0000000..b189117 --- /dev/null +++ b/node_modules/@protobufjs/codegen/tests/index.js @@ -0,0 +1,13 @@ +var codegen = require(".."); + +// new require("benchmark").Suite().add("add", function() { + +var add = codegen(["a", "b"], "add") + ("// awesome comment") + ("return a + b - c + %d", 1) + ({ c: 1 }); + +if (add(1, 2) !== 3) + throw Error("failed"); + +// }).on("cycle", function(event) { process.stdout.write(String(event.target) + "\n"); }).run(); diff --git a/node_modules/@protobufjs/eventemitter/LICENSE b/node_modules/@protobufjs/eventemitter/LICENSE new file mode 100644 index 0000000..be2b397 --- /dev/null +++ b/node_modules/@protobufjs/eventemitter/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@protobufjs/eventemitter/README.md b/node_modules/@protobufjs/eventemitter/README.md new file mode 100644 index 0000000..528e725 --- /dev/null +++ b/node_modules/@protobufjs/eventemitter/README.md @@ -0,0 +1,22 @@ +@protobufjs/eventemitter +======================== +[![npm](https://img.shields.io/npm/v/@protobufjs/eventemitter.svg)](https://www.npmjs.com/package/@protobufjs/eventemitter) + +A minimal event emitter. + +API +--- + +* **new EventEmitter()**
                          + Constructs a new event emitter instance. + +* **EventEmitter#on(evt: `string`, fn: `function`, [ctx: `Object`]): `EventEmitter`**
                          + Registers an event listener. + +* **EventEmitter#off([evt: `string`], [fn: `function`]): `EventEmitter`**
                          + Removes an event listener or any matching listeners if arguments are omitted. + +* **EventEmitter#emit(evt: `string`, ...args: `*`): `EventEmitter`**
                          + Emits an event by calling its listeners with the specified arguments. + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/@protobufjs/eventemitter/index.d.ts b/node_modules/@protobufjs/eventemitter/index.d.ts new file mode 100644 index 0000000..f177823 --- /dev/null +++ b/node_modules/@protobufjs/eventemitter/index.d.ts @@ -0,0 +1,43 @@ +export = EventEmitter; + +/** + * Constructs a new event emitter instance. + * @classdesc A minimal event emitter. + * @memberof util + * @constructor + */ +declare class EventEmitter { + + /** + * Constructs a new event emitter instance. + * @classdesc A minimal event emitter. + * @memberof util + * @constructor + */ + constructor(); + + /** + * Registers an event listener. + * @param {string} evt Event name + * @param {function} fn Listener + * @param {*} [ctx] Listener context + * @returns {util.EventEmitter} `this` + */ + on(evt: string, fn: () => any, ctx?: any): EventEmitter; + + /** + * Removes an event listener or any matching listeners if arguments are omitted. + * @param {string} [evt] Event name. Removes all listeners if omitted. + * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted. + * @returns {util.EventEmitter} `this` + */ + off(evt?: string, fn?: () => any): EventEmitter; + + /** + * Emits an event by calling its listeners with the specified arguments. + * @param {string} evt Event name + * @param {...*} args Arguments + * @returns {util.EventEmitter} `this` + */ + emit(evt: string, ...args: any[]): EventEmitter; +} diff --git a/node_modules/@protobufjs/eventemitter/index.js b/node_modules/@protobufjs/eventemitter/index.js new file mode 100644 index 0000000..f766fd0 --- /dev/null +++ b/node_modules/@protobufjs/eventemitter/index.js @@ -0,0 +1,76 @@ +"use strict"; +module.exports = EventEmitter; + +/** + * Constructs a new event emitter instance. + * @classdesc A minimal event emitter. + * @memberof util + * @constructor + */ +function EventEmitter() { + + /** + * Registered listeners. + * @type {Object.} + * @private + */ + this._listeners = {}; +} + +/** + * Registers an event listener. + * @param {string} evt Event name + * @param {function} fn Listener + * @param {*} [ctx] Listener context + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.on = function on(evt, fn, ctx) { + (this._listeners[evt] || (this._listeners[evt] = [])).push({ + fn : fn, + ctx : ctx || this + }); + return this; +}; + +/** + * Removes an event listener or any matching listeners if arguments are omitted. + * @param {string} [evt] Event name. Removes all listeners if omitted. + * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted. + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.off = function off(evt, fn) { + if (evt === undefined) + this._listeners = {}; + else { + if (fn === undefined) + this._listeners[evt] = []; + else { + var listeners = this._listeners[evt]; + for (var i = 0; i < listeners.length;) + if (listeners[i].fn === fn) + listeners.splice(i, 1); + else + ++i; + } + } + return this; +}; + +/** + * Emits an event by calling its listeners with the specified arguments. + * @param {string} evt Event name + * @param {...*} args Arguments + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.emit = function emit(evt) { + var listeners = this._listeners[evt]; + if (listeners) { + var args = [], + i = 1; + for (; i < arguments.length;) + args.push(arguments[i++]); + for (i = 0; i < listeners.length;) + listeners[i].fn.apply(listeners[i++].ctx, args); + } + return this; +}; diff --git a/node_modules/@protobufjs/eventemitter/package.json b/node_modules/@protobufjs/eventemitter/package.json new file mode 100644 index 0000000..b333e99 --- /dev/null +++ b/node_modules/@protobufjs/eventemitter/package.json @@ -0,0 +1,21 @@ +{ + "name": "@protobufjs/eventemitter", + "description": "A minimal event emitter.", + "version": "1.1.0", + "author": "Daniel Wirtz ", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/protobuf.js.git" + }, + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "devDependencies": { + "istanbul": "^0.4.5", + "tape": "^4.6.3" + }, + "scripts": { + "test": "tape tests/*.js", + "coverage": "istanbul cover node_modules/tape/bin/tape tests/*.js" + } +} \ No newline at end of file diff --git a/node_modules/@protobufjs/eventemitter/tests/index.js b/node_modules/@protobufjs/eventemitter/tests/index.js new file mode 100644 index 0000000..390958f --- /dev/null +++ b/node_modules/@protobufjs/eventemitter/tests/index.js @@ -0,0 +1,47 @@ +var tape = require("tape"); + +var EventEmitter = require(".."); + +tape.test("eventemitter", function(test) { + + var ee = new EventEmitter(); + var fn; + var ctx = {}; + + test.doesNotThrow(function() { + ee.emit("a", 1); + ee.off(); + ee.off("a"); + ee.off("a", function() {}); + }, "should not throw if no listeners are registered"); + + test.equal(ee.on("a", function(arg1) { + test.equal(this, ctx, "should be called with this = ctx"); + test.equal(arg1, 1, "should be called with arg1 = 1"); + }, ctx), ee, "should return itself when registering events"); + ee.emit("a", 1); + + ee.off("a"); + test.same(ee._listeners, { a: [] }, "should remove all listeners of the respective event when calling off(evt)"); + + ee.off(); + test.same(ee._listeners, {}, "should remove all listeners when just calling off()"); + + ee.on("a", fn = function(arg1) { + test.equal(this, ctx, "should be called with this = ctx"); + test.equal(arg1, 1, "should be called with arg1 = 1"); + }, ctx).emit("a", 1); + + ee.off("a", fn); + test.same(ee._listeners, { a: [] }, "should remove the exact listener when calling off(evt, fn)"); + + ee.on("a", function() { + test.equal(this, ee, "should be called with this = ee"); + }).emit("a"); + + test.doesNotThrow(function() { + ee.off("a", fn); + }, "should not throw if no such listener is found"); + + test.end(); +}); diff --git a/node_modules/@protobufjs/fetch/LICENSE b/node_modules/@protobufjs/fetch/LICENSE new file mode 100644 index 0000000..be2b397 --- /dev/null +++ b/node_modules/@protobufjs/fetch/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@protobufjs/fetch/README.md b/node_modules/@protobufjs/fetch/README.md new file mode 100644 index 0000000..1ebf4d4 --- /dev/null +++ b/node_modules/@protobufjs/fetch/README.md @@ -0,0 +1,13 @@ +@protobufjs/fetch +================= +[![npm](https://img.shields.io/npm/v/@protobufjs/fetch.svg)](https://www.npmjs.com/package/@protobufjs/fetch) + +Fetches the contents of a file accross node and browsers. + +API +--- + +* **fetch(path: `string`, [options: { binary: boolean } ], [callback: `function(error: ?Error, [contents: string])`]): `Promise|undefined`** + Fetches the contents of a file. + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/@protobufjs/fetch/index.d.ts b/node_modules/@protobufjs/fetch/index.d.ts new file mode 100644 index 0000000..ab0820c --- /dev/null +++ b/node_modules/@protobufjs/fetch/index.d.ts @@ -0,0 +1,56 @@ +export = fetch; + +/** + * Node-style callback as used by {@link util.fetch}. + * @typedef FetchCallback + * @type {function} + * @param {?Error} error Error, if any, otherwise `null` + * @param {string} [contents] File contents, if there hasn't been an error + * @returns {undefined} + */ +type FetchCallback = (error: Error, contents?: string) => void; + +/** + * Options as used by {@link util.fetch}. + * @typedef FetchOptions + * @type {Object} + * @property {boolean} [binary=false] Whether expecting a binary response + * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest + */ + +interface FetchOptions { + binary?: boolean; + xhr?: boolean +} + +/** + * Fetches the contents of a file. + * @memberof util + * @param {string} filename File path or url + * @param {FetchOptions} options Fetch options + * @param {FetchCallback} callback Callback function + * @returns {undefined} + */ +declare function fetch(filename: string, options: FetchOptions, callback: FetchCallback): void; + +/** + * Fetches the contents of a file. + * @name util.fetch + * @function + * @param {string} path File path or url + * @param {FetchCallback} callback Callback function + * @returns {undefined} + * @variation 2 + */ +declare function fetch(path: string, callback: FetchCallback): void; + +/** + * Fetches the contents of a file. + * @name util.fetch + * @function + * @param {string} path File path or url + * @param {FetchOptions} [options] Fetch options + * @returns {Promise} Promise + * @variation 3 + */ +declare function fetch(path: string, options?: FetchOptions): Promise<(string|Uint8Array)>; diff --git a/node_modules/@protobufjs/fetch/index.js b/node_modules/@protobufjs/fetch/index.js new file mode 100644 index 0000000..d92aa68 --- /dev/null +++ b/node_modules/@protobufjs/fetch/index.js @@ -0,0 +1,115 @@ +"use strict"; +module.exports = fetch; + +var asPromise = require("@protobufjs/aspromise"), + inquire = require("@protobufjs/inquire"); + +var fs = inquire("fs"); + +/** + * Node-style callback as used by {@link util.fetch}. + * @typedef FetchCallback + * @type {function} + * @param {?Error} error Error, if any, otherwise `null` + * @param {string} [contents] File contents, if there hasn't been an error + * @returns {undefined} + */ + +/** + * Options as used by {@link util.fetch}. + * @typedef FetchOptions + * @type {Object} + * @property {boolean} [binary=false] Whether expecting a binary response + * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest + */ + +/** + * Fetches the contents of a file. + * @memberof util + * @param {string} filename File path or url + * @param {FetchOptions} options Fetch options + * @param {FetchCallback} callback Callback function + * @returns {undefined} + */ +function fetch(filename, options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; + } else if (!options) + options = {}; + + if (!callback) + return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this + + // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found. + if (!options.xhr && fs && fs.readFile) + return fs.readFile(filename, function fetchReadFileCallback(err, contents) { + return err && typeof XMLHttpRequest !== "undefined" + ? fetch.xhr(filename, options, callback) + : err + ? callback(err) + : callback(null, options.binary ? contents : contents.toString("utf8")); + }); + + // use the XHR version otherwise. + return fetch.xhr(filename, options, callback); +} + +/** + * Fetches the contents of a file. + * @name util.fetch + * @function + * @param {string} path File path or url + * @param {FetchCallback} callback Callback function + * @returns {undefined} + * @variation 2 + */ + +/** + * Fetches the contents of a file. + * @name util.fetch + * @function + * @param {string} path File path or url + * @param {FetchOptions} [options] Fetch options + * @returns {Promise} Promise + * @variation 3 + */ + +/**/ +fetch.xhr = function fetch_xhr(filename, options, callback) { + var xhr = new XMLHttpRequest(); + xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() { + + if (xhr.readyState !== 4) + return undefined; + + // local cors security errors return status 0 / empty string, too. afaik this cannot be + // reliably distinguished from an actually empty file for security reasons. feel free + // to send a pull request if you are aware of a solution. + if (xhr.status !== 0 && xhr.status !== 200) + return callback(Error("status " + xhr.status)); + + // if binary data is expected, make sure that some sort of array is returned, even if + // ArrayBuffers are not supported. the binary string fallback, however, is unsafe. + if (options.binary) { + var buffer = xhr.response; + if (!buffer) { + buffer = []; + for (var i = 0; i < xhr.responseText.length; ++i) + buffer.push(xhr.responseText.charCodeAt(i) & 255); + } + return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer); + } + return callback(null, xhr.responseText); + }; + + if (options.binary) { + // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers + if ("overrideMimeType" in xhr) + xhr.overrideMimeType("text/plain; charset=x-user-defined"); + xhr.responseType = "arraybuffer"; + } + + xhr.open("GET", filename); + xhr.send(); +}; diff --git a/node_modules/@protobufjs/fetch/package.json b/node_modules/@protobufjs/fetch/package.json new file mode 100644 index 0000000..14ee25f --- /dev/null +++ b/node_modules/@protobufjs/fetch/package.json @@ -0,0 +1,25 @@ +{ + "name": "@protobufjs/fetch", + "description": "Fetches the contents of a file accross node and browsers.", + "version": "1.1.0", + "author": "Daniel Wirtz ", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/protobuf.js.git" + }, + "dependencies": { + "@protobufjs/aspromise": "^1.1.1", + "@protobufjs/inquire": "^1.1.0" + }, + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "devDependencies": { + "istanbul": "^0.4.5", + "tape": "^4.6.3" + }, + "scripts": { + "test": "tape tests/*.js", + "coverage": "istanbul cover node_modules/tape/bin/tape tests/*.js" + } +} \ No newline at end of file diff --git a/node_modules/@protobufjs/fetch/tests/index.js b/node_modules/@protobufjs/fetch/tests/index.js new file mode 100644 index 0000000..b7fbf81 --- /dev/null +++ b/node_modules/@protobufjs/fetch/tests/index.js @@ -0,0 +1,16 @@ +var tape = require("tape"); + +var fetch = require(".."); + +tape.test("fetch", function(test) { + + if (typeof Promise !== "undefined") { + var promise = fetch("NOTFOUND"); + promise.catch(function() {}); + test.ok(promise instanceof Promise, "should return a promise if callback has been omitted"); + } + + // TODO - some way to test this properly? + + test.end(); +}); diff --git a/node_modules/@protobufjs/float/LICENSE b/node_modules/@protobufjs/float/LICENSE new file mode 100644 index 0000000..be2b397 --- /dev/null +++ b/node_modules/@protobufjs/float/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@protobufjs/float/README.md b/node_modules/@protobufjs/float/README.md new file mode 100644 index 0000000..e475fc9 --- /dev/null +++ b/node_modules/@protobufjs/float/README.md @@ -0,0 +1,102 @@ +@protobufjs/float +================= +[![npm](https://img.shields.io/npm/v/@protobufjs/float.svg)](https://www.npmjs.com/package/@protobufjs/float) + +Reads / writes floats / doubles from / to buffers in both modern and ancient browsers. Fast. + +API +--- + +* **writeFloatLE(val: `number`, buf: `Uint8Array`, pos: `number`)**
                          + Writes a 32 bit float to a buffer using little endian byte order. + +* **writeFloatBE(val: `number`, buf: `Uint8Array`, pos: `number`)**
                          + Writes a 32 bit float to a buffer using big endian byte order. + +* **readFloatLE(buf: `Uint8Array`, pos: `number`): `number`**
                          + Reads a 32 bit float from a buffer using little endian byte order. + +* **readFloatBE(buf: `Uint8Array`, pos: `number`): `number`**
                          + Reads a 32 bit float from a buffer using big endian byte order. + +* **writeDoubleLE(val: `number`, buf: `Uint8Array`, pos: `number`)**
                          + Writes a 64 bit double to a buffer using little endian byte order. + +* **writeDoubleBE(val: `number`, buf: `Uint8Array`, pos: `number`)**
                          + Writes a 64 bit double to a buffer using big endian byte order. + +* **readDoubleLE(buf: `Uint8Array`, pos: `number`): `number`**
                          + Reads a 64 bit double from a buffer using little endian byte order. + +* **readDoubleBE(buf: `Uint8Array`, pos: `number`): `number`**
                          + Reads a 64 bit double from a buffer using big endian byte order. + +Performance +----------- +There is a simple benchmark included comparing raw read/write performance of this library (float), float's fallback for old browsers, the [ieee754](https://www.npmjs.com/package/ieee754) module and node's [buffer](https://nodejs.org/api/buffer.html). On an i7-2600k running node 6.9.1 it yields: + +``` +benchmarking writeFloat performance ... + +float x 42,741,625 ops/sec ±1.75% (81 runs sampled) +float (fallback) x 11,272,532 ops/sec ±1.12% (85 runs sampled) +ieee754 x 8,653,337 ops/sec ±1.18% (84 runs sampled) +buffer x 12,412,414 ops/sec ±1.41% (83 runs sampled) +buffer (noAssert) x 13,471,149 ops/sec ±1.09% (84 runs sampled) + + float was fastest + float (fallback) was 73.5% slower + ieee754 was 79.6% slower + buffer was 70.9% slower + buffer (noAssert) was 68.3% slower + +benchmarking readFloat performance ... + +float x 44,382,729 ops/sec ±1.70% (84 runs sampled) +float (fallback) x 20,925,938 ops/sec ±0.86% (87 runs sampled) +ieee754 x 17,189,009 ops/sec ±1.01% (87 runs sampled) +buffer x 10,518,437 ops/sec ±1.04% (83 runs sampled) +buffer (noAssert) x 11,031,636 ops/sec ±1.15% (87 runs sampled) + + float was fastest + float (fallback) was 52.5% slower + ieee754 was 61.0% slower + buffer was 76.1% slower + buffer (noAssert) was 75.0% slower + +benchmarking writeDouble performance ... + +float x 38,624,906 ops/sec ±0.93% (83 runs sampled) +float (fallback) x 10,457,811 ops/sec ±1.54% (85 runs sampled) +ieee754 x 7,681,130 ops/sec ±1.11% (83 runs sampled) +buffer x 12,657,876 ops/sec ±1.03% (83 runs sampled) +buffer (noAssert) x 13,372,795 ops/sec ±0.84% (85 runs sampled) + + float was fastest + float (fallback) was 73.1% slower + ieee754 was 80.1% slower + buffer was 67.3% slower + buffer (noAssert) was 65.3% slower + +benchmarking readDouble performance ... + +float x 40,527,888 ops/sec ±1.05% (84 runs sampled) +float (fallback) x 18,696,480 ops/sec ±0.84% (86 runs sampled) +ieee754 x 14,074,028 ops/sec ±1.04% (87 runs sampled) +buffer x 10,092,367 ops/sec ±1.15% (84 runs sampled) +buffer (noAssert) x 10,623,793 ops/sec ±0.96% (84 runs sampled) + + float was fastest + float (fallback) was 53.8% slower + ieee754 was 65.3% slower + buffer was 75.1% slower + buffer (noAssert) was 73.8% slower +``` + +To run it yourself: + +``` +$> npm run bench +``` + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/@protobufjs/float/bench/index.js b/node_modules/@protobufjs/float/bench/index.js new file mode 100644 index 0000000..911f461 --- /dev/null +++ b/node_modules/@protobufjs/float/bench/index.js @@ -0,0 +1,87 @@ +"use strict"; + +var float = require(".."), + ieee754 = require("ieee754"), + newSuite = require("./suite"); + +var F32 = Float32Array; +var F64 = Float64Array; +delete global.Float32Array; +delete global.Float64Array; +var floatFallback = float({}); +global.Float32Array = F32; +global.Float64Array = F64; + +var buf = new Buffer(8); + +newSuite("writeFloat") +.add("float", function() { + float.writeFloatLE(0.1, buf, 0); +}) +.add("float (fallback)", function() { + floatFallback.writeFloatLE(0.1, buf, 0); +}) +.add("ieee754", function() { + ieee754.write(buf, 0.1, 0, true, 23, 4); +}) +.add("buffer", function() { + buf.writeFloatLE(0.1, 0); +}) +.add("buffer (noAssert)", function() { + buf.writeFloatLE(0.1, 0, true); +}) +.run(); + +newSuite("readFloat") +.add("float", function() { + float.readFloatLE(buf, 0); +}) +.add("float (fallback)", function() { + floatFallback.readFloatLE(buf, 0); +}) +.add("ieee754", function() { + ieee754.read(buf, 0, true, 23, 4); +}) +.add("buffer", function() { + buf.readFloatLE(0); +}) +.add("buffer (noAssert)", function() { + buf.readFloatLE(0, true); +}) +.run(); + +newSuite("writeDouble") +.add("float", function() { + float.writeDoubleLE(0.1, buf, 0); +}) +.add("float (fallback)", function() { + floatFallback.writeDoubleLE(0.1, buf, 0); +}) +.add("ieee754", function() { + ieee754.write(buf, 0.1, 0, true, 52, 8); +}) +.add("buffer", function() { + buf.writeDoubleLE(0.1, 0); +}) +.add("buffer (noAssert)", function() { + buf.writeDoubleLE(0.1, 0, true); +}) +.run(); + +newSuite("readDouble") +.add("float", function() { + float.readDoubleLE(buf, 0); +}) +.add("float (fallback)", function() { + floatFallback.readDoubleLE(buf, 0); +}) +.add("ieee754", function() { + ieee754.read(buf, 0, true, 52, 8); +}) +.add("buffer", function() { + buf.readDoubleLE(0); +}) +.add("buffer (noAssert)", function() { + buf.readDoubleLE(0, true); +}) +.run(); diff --git a/node_modules/@protobufjs/float/bench/suite.js b/node_modules/@protobufjs/float/bench/suite.js new file mode 100644 index 0000000..e8016d2 --- /dev/null +++ b/node_modules/@protobufjs/float/bench/suite.js @@ -0,0 +1,46 @@ +"use strict"; +module.exports = newSuite; + +var benchmark = require("benchmark"), + chalk = require("chalk"); + +var padSize = 27; + +function newSuite(name) { + var benches = []; + return new benchmark.Suite(name) + .on("add", function(event) { + benches.push(event.target); + }) + .on("start", function() { + process.stdout.write("benchmarking " + name + " performance ...\n\n"); + }) + .on("cycle", function(event) { + process.stdout.write(String(event.target) + "\n"); + }) + .on("complete", function() { + if (benches.length > 1) { + var fastest = this.filter("fastest"), // eslint-disable-line no-invalid-this + fastestHz = getHz(fastest[0]); + process.stdout.write("\n" + chalk.white(pad(fastest[0].name, padSize)) + " was " + chalk.green("fastest") + "\n"); + benches.forEach(function(bench) { + if (fastest.indexOf(bench) === 0) + return; + var hz = hz = getHz(bench); + var percent = (1 - hz / fastestHz) * 100; + process.stdout.write(chalk.white(pad(bench.name, padSize)) + " was " + chalk.red(percent.toFixed(1) + "% slower") + "\n"); + }); + } + process.stdout.write("\n"); + }); +} + +function getHz(bench) { + return 1 / (bench.stats.mean + bench.stats.moe); +} + +function pad(str, len, l) { + while (str.length < len) + str = l ? str + " " : " " + str; + return str; +} diff --git a/node_modules/@protobufjs/float/index.d.ts b/node_modules/@protobufjs/float/index.d.ts new file mode 100644 index 0000000..ab05de3 --- /dev/null +++ b/node_modules/@protobufjs/float/index.d.ts @@ -0,0 +1,83 @@ +/** + * Writes a 32 bit float to a buffer using little endian byte order. + * @name writeFloatLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ +export function writeFloatLE(val: number, buf: Uint8Array, pos: number): void; + +/** + * Writes a 32 bit float to a buffer using big endian byte order. + * @name writeFloatBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ +export function writeFloatBE(val: number, buf: Uint8Array, pos: number): void; + +/** + * Reads a 32 bit float from a buffer using little endian byte order. + * @name readFloatLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ +export function readFloatLE(buf: Uint8Array, pos: number): number; + +/** + * Reads a 32 bit float from a buffer using big endian byte order. + * @name readFloatBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ +export function readFloatBE(buf: Uint8Array, pos: number): number; + +/** + * Writes a 64 bit double to a buffer using little endian byte order. + * @name writeDoubleLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ +export function writeDoubleLE(val: number, buf: Uint8Array, pos: number): void; + +/** + * Writes a 64 bit double to a buffer using big endian byte order. + * @name writeDoubleBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ +export function writeDoubleBE(val: number, buf: Uint8Array, pos: number): void; + +/** + * Reads a 64 bit double from a buffer using little endian byte order. + * @name readDoubleLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ +export function readDoubleLE(buf: Uint8Array, pos: number): number; + +/** + * Reads a 64 bit double from a buffer using big endian byte order. + * @name readDoubleBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ +export function readDoubleBE(buf: Uint8Array, pos: number): number; diff --git a/node_modules/@protobufjs/float/index.js b/node_modules/@protobufjs/float/index.js new file mode 100644 index 0000000..52ba3aa --- /dev/null +++ b/node_modules/@protobufjs/float/index.js @@ -0,0 +1,335 @@ +"use strict"; + +module.exports = factory(factory); + +/** + * Reads / writes floats / doubles from / to buffers. + * @name util.float + * @namespace + */ + +/** + * Writes a 32 bit float to a buffer using little endian byte order. + * @name util.float.writeFloatLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Writes a 32 bit float to a buffer using big endian byte order. + * @name util.float.writeFloatBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Reads a 32 bit float from a buffer using little endian byte order. + * @name util.float.readFloatLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Reads a 32 bit float from a buffer using big endian byte order. + * @name util.float.readFloatBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Writes a 64 bit double to a buffer using little endian byte order. + * @name util.float.writeDoubleLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Writes a 64 bit double to a buffer using big endian byte order. + * @name util.float.writeDoubleBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Reads a 64 bit double from a buffer using little endian byte order. + * @name util.float.readDoubleLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Reads a 64 bit double from a buffer using big endian byte order. + * @name util.float.readDoubleBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +// Factory function for the purpose of node-based testing in modified global environments +function factory(exports) { + + // float: typed array + if (typeof Float32Array !== "undefined") (function() { + + var f32 = new Float32Array([ -0 ]), + f8b = new Uint8Array(f32.buffer), + le = f8b[3] === 128; + + function writeFloat_f32_cpy(val, buf, pos) { + f32[0] = val; + buf[pos ] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + } + + function writeFloat_f32_rev(val, buf, pos) { + f32[0] = val; + buf[pos ] = f8b[3]; + buf[pos + 1] = f8b[2]; + buf[pos + 2] = f8b[1]; + buf[pos + 3] = f8b[0]; + } + + /* istanbul ignore next */ + exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; + /* istanbul ignore next */ + exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; + + function readFloat_f32_cpy(buf, pos) { + f8b[0] = buf[pos ]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + return f32[0]; + } + + function readFloat_f32_rev(buf, pos) { + f8b[3] = buf[pos ]; + f8b[2] = buf[pos + 1]; + f8b[1] = buf[pos + 2]; + f8b[0] = buf[pos + 3]; + return f32[0]; + } + + /* istanbul ignore next */ + exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; + /* istanbul ignore next */ + exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; + + // float: ieee754 + })(); else (function() { + + function writeFloat_ieee754(writeUint, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) + writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos); + else if (isNaN(val)) + writeUint(2143289344, buf, pos); + else if (val > 3.4028234663852886e+38) // +-Infinity + writeUint((sign << 31 | 2139095040) >>> 0, buf, pos); + else if (val < 1.1754943508222875e-38) // denormal + writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos); + else { + var exponent = Math.floor(Math.log(val) / Math.LN2), + mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; + writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); + } + } + + exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); + exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); + + function readFloat_ieee754(readUint, buf, pos) { + var uint = readUint(buf, pos), + sign = (uint >> 31) * 2 + 1, + exponent = uint >>> 23 & 255, + mantissa = uint & 8388607; + return exponent === 255 + ? mantissa + ? NaN + : sign * Infinity + : exponent === 0 // denormal + ? sign * 1.401298464324817e-45 * mantissa + : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); + } + + exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE); + exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE); + + })(); + + // double: typed array + if (typeof Float64Array !== "undefined") (function() { + + var f64 = new Float64Array([-0]), + f8b = new Uint8Array(f64.buffer), + le = f8b[7] === 128; + + function writeDouble_f64_cpy(val, buf, pos) { + f64[0] = val; + buf[pos ] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + buf[pos + 4] = f8b[4]; + buf[pos + 5] = f8b[5]; + buf[pos + 6] = f8b[6]; + buf[pos + 7] = f8b[7]; + } + + function writeDouble_f64_rev(val, buf, pos) { + f64[0] = val; + buf[pos ] = f8b[7]; + buf[pos + 1] = f8b[6]; + buf[pos + 2] = f8b[5]; + buf[pos + 3] = f8b[4]; + buf[pos + 4] = f8b[3]; + buf[pos + 5] = f8b[2]; + buf[pos + 6] = f8b[1]; + buf[pos + 7] = f8b[0]; + } + + /* istanbul ignore next */ + exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; + /* istanbul ignore next */ + exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; + + function readDouble_f64_cpy(buf, pos) { + f8b[0] = buf[pos ]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + f8b[4] = buf[pos + 4]; + f8b[5] = buf[pos + 5]; + f8b[6] = buf[pos + 6]; + f8b[7] = buf[pos + 7]; + return f64[0]; + } + + function readDouble_f64_rev(buf, pos) { + f8b[7] = buf[pos ]; + f8b[6] = buf[pos + 1]; + f8b[5] = buf[pos + 2]; + f8b[4] = buf[pos + 3]; + f8b[3] = buf[pos + 4]; + f8b[2] = buf[pos + 5]; + f8b[1] = buf[pos + 6]; + f8b[0] = buf[pos + 7]; + return f64[0]; + } + + /* istanbul ignore next */ + exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; + /* istanbul ignore next */ + exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; + + // double: ieee754 + })(); else (function() { + + function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) { + writeUint(0, buf, pos + off0); + writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1); + } else if (isNaN(val)) { + writeUint(0, buf, pos + off0); + writeUint(2146959360, buf, pos + off1); + } else if (val > 1.7976931348623157e+308) { // +-Infinity + writeUint(0, buf, pos + off0); + writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1); + } else { + var mantissa; + if (val < 2.2250738585072014e-308) { // denormal + mantissa = val / 5e-324; + writeUint(mantissa >>> 0, buf, pos + off0); + writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); + } else { + var exponent = Math.floor(Math.log(val) / Math.LN2); + if (exponent === 1024) + exponent = 1023; + mantissa = val * Math.pow(2, -exponent); + writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); + writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); + } + } + } + + exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); + exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); + + function readDouble_ieee754(readUint, off0, off1, buf, pos) { + var lo = readUint(buf, pos + off0), + hi = readUint(buf, pos + off1); + var sign = (hi >> 31) * 2 + 1, + exponent = hi >>> 20 & 2047, + mantissa = 4294967296 * (hi & 1048575) + lo; + return exponent === 2047 + ? mantissa + ? NaN + : sign * Infinity + : exponent === 0 // denormal + ? sign * 5e-324 * mantissa + : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); + } + + exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); + exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); + + })(); + + return exports; +} + +// uint helpers + +function writeUintLE(val, buf, pos) { + buf[pos ] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; +} + +function writeUintBE(val, buf, pos) { + buf[pos ] = val >>> 24; + buf[pos + 1] = val >>> 16 & 255; + buf[pos + 2] = val >>> 8 & 255; + buf[pos + 3] = val & 255; +} + +function readUintLE(buf, pos) { + return (buf[pos ] + | buf[pos + 1] << 8 + | buf[pos + 2] << 16 + | buf[pos + 3] << 24) >>> 0; +} + +function readUintBE(buf, pos) { + return (buf[pos ] << 24 + | buf[pos + 1] << 16 + | buf[pos + 2] << 8 + | buf[pos + 3]) >>> 0; +} diff --git a/node_modules/@protobufjs/float/package.json b/node_modules/@protobufjs/float/package.json new file mode 100644 index 0000000..aaebccf --- /dev/null +++ b/node_modules/@protobufjs/float/package.json @@ -0,0 +1,26 @@ +{ + "name": "@protobufjs/float", + "description": "Reads / writes floats / doubles from / to buffers in both modern and ancient browsers.", + "version": "1.0.2", + "author": "Daniel Wirtz ", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/protobuf.js.git" + }, + "dependencies": {}, + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "devDependencies": { + "benchmark": "^2.1.4", + "chalk": "^1.1.3", + "ieee754": "^1.1.8", + "istanbul": "^0.4.5", + "tape": "^4.6.3" + }, + "scripts": { + "test": "tape tests/*.js", + "coverage": "istanbul cover node_modules/tape/bin/tape tests/*.js", + "bench": "node bench" + } +} \ No newline at end of file diff --git a/node_modules/@protobufjs/float/tests/index.js b/node_modules/@protobufjs/float/tests/index.js new file mode 100644 index 0000000..62f0827 --- /dev/null +++ b/node_modules/@protobufjs/float/tests/index.js @@ -0,0 +1,100 @@ +var tape = require("tape"); + +var float = require(".."); + +tape.test("float", function(test) { + + // default + test.test(test.name + " - typed array", function(test) { + runTest(float, test); + }); + + // ieee754 + test.test(test.name + " - fallback", function(test) { + var F32 = global.Float32Array, + F64 = global.Float64Array; + delete global.Float32Array; + delete global.Float64Array; + runTest(float({}), test); + global.Float32Array = F32; + global.Float64Array = F64; + }); +}); + +function runTest(float, test) { + + var common = [ + 0, + -0, + Infinity, + -Infinity, + 0.125, + 1024.5, + -4096.5, + NaN + ]; + + test.test(test.name + " - using 32 bits", function(test) { + common.concat([ + 3.4028234663852886e+38, + 1.1754943508222875e-38, + 1.1754946310819804e-39 + ]) + .forEach(function(value) { + var strval = value === 0 && 1 / value < 0 ? "-0" : value.toString(); + test.ok( + checkValue(value, 4, float.readFloatLE, float.writeFloatLE, Buffer.prototype.writeFloatLE), + "should write and read back " + strval + " (32 bit LE)" + ); + test.ok( + checkValue(value, 4, float.readFloatBE, float.writeFloatBE, Buffer.prototype.writeFloatBE), + "should write and read back " + strval + " (32 bit BE)" + ); + }); + test.end(); + }); + + test.test(test.name + " - using 64 bits", function(test) { + common.concat([ + 1.7976931348623157e+308, + 2.2250738585072014e-308, + 2.2250738585072014e-309 + ]) + .forEach(function(value) { + var strval = value === 0 && 1 / value < 0 ? "-0" : value.toString(); + test.ok( + checkValue(value, 8, float.readDoubleLE, float.writeDoubleLE, Buffer.prototype.writeDoubleLE), + "should write and read back " + strval + " (64 bit LE)" + ); + test.ok( + checkValue(value, 8, float.readDoubleBE, float.writeDoubleBE, Buffer.prototype.writeDoubleBE), + "should write and read back " + strval + " (64 bit BE)" + ); + }); + test.end(); + }); + + test.end(); +} + +function checkValue(value, size, read, write, write_comp) { + var buffer = new Buffer(size); + write(value, buffer, 0); + var value_comp = read(buffer, 0); + var strval = value === 0 && 1 / value < 0 ? "-0" : value.toString(); + if (value !== value) { + if (value_comp === value_comp) + return false; + } else if (value_comp !== value) + return false; + + var buffer_comp = new Buffer(size); + write_comp.call(buffer_comp, value, 0); + for (var i = 0; i < size; ++i) + if (buffer[i] !== buffer_comp[i]) { + console.error(">", buffer, buffer_comp); + return false; + } + + return true; +} \ No newline at end of file diff --git a/node_modules/@protobufjs/inquire/.npmignore b/node_modules/@protobufjs/inquire/.npmignore new file mode 100644 index 0000000..c3fc82e --- /dev/null +++ b/node_modules/@protobufjs/inquire/.npmignore @@ -0,0 +1,3 @@ +npm-debug.* +node_modules/ +coverage/ diff --git a/node_modules/@protobufjs/inquire/LICENSE b/node_modules/@protobufjs/inquire/LICENSE new file mode 100644 index 0000000..be2b397 --- /dev/null +++ b/node_modules/@protobufjs/inquire/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@protobufjs/inquire/README.md b/node_modules/@protobufjs/inquire/README.md new file mode 100644 index 0000000..3eabd86 --- /dev/null +++ b/node_modules/@protobufjs/inquire/README.md @@ -0,0 +1,13 @@ +@protobufjs/inquire +=================== +[![npm](https://img.shields.io/npm/v/@protobufjs/inquire.svg)](https://www.npmjs.com/package/@protobufjs/inquire) + +Requires a module only if available and hides the require call from bundlers. + +API +--- + +* **inquire(moduleName: `string`): `?Object`**
                          + Requires a module only if available. + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/@protobufjs/inquire/index.d.ts b/node_modules/@protobufjs/inquire/index.d.ts new file mode 100644 index 0000000..1f5a865 --- /dev/null +++ b/node_modules/@protobufjs/inquire/index.d.ts @@ -0,0 +1,9 @@ +export = inquire; + +/** + * Requires a module only if available. + * @memberof util + * @param {string} moduleName Module to require + * @returns {?Object} Required module if available and not empty, otherwise `null` + */ +declare function inquire(moduleName: string): Object; diff --git a/node_modules/@protobufjs/inquire/index.js b/node_modules/@protobufjs/inquire/index.js new file mode 100644 index 0000000..1a1f238 --- /dev/null +++ b/node_modules/@protobufjs/inquire/index.js @@ -0,0 +1,17 @@ +"use strict"; +module.exports = inquire; + +/** + * Requires a module only if available. + * @memberof util + * @param {string} moduleName Module to require + * @returns {?Object} Required module if available and not empty, otherwise `null` + */ +function inquire(moduleName) { + try { + var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval + if (mod && (mod.length || Object.keys(mod).length)) + return mod; + } catch (e) {} // eslint-disable-line no-empty + return null; +} diff --git a/node_modules/@protobufjs/inquire/package.json b/node_modules/@protobufjs/inquire/package.json new file mode 100644 index 0000000..6a64d66 --- /dev/null +++ b/node_modules/@protobufjs/inquire/package.json @@ -0,0 +1,21 @@ +{ + "name": "@protobufjs/inquire", + "description": "Requires a module only if available and hides the require call from bundlers.", + "version": "1.1.0", + "author": "Daniel Wirtz ", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/protobuf.js.git" + }, + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "devDependencies": { + "istanbul": "^0.4.5", + "tape": "^4.6.3" + }, + "scripts": { + "test": "tape tests/*.js", + "coverage": "istanbul cover node_modules/tape/bin/tape tests/*.js" + } +} \ No newline at end of file diff --git a/node_modules/@protobufjs/inquire/tests/data/array.js b/node_modules/@protobufjs/inquire/tests/data/array.js new file mode 100644 index 0000000..0847b28 --- /dev/null +++ b/node_modules/@protobufjs/inquire/tests/data/array.js @@ -0,0 +1 @@ +module.exports = [1]; diff --git a/node_modules/@protobufjs/inquire/tests/data/emptyArray.js b/node_modules/@protobufjs/inquire/tests/data/emptyArray.js new file mode 100644 index 0000000..e0a30c5 --- /dev/null +++ b/node_modules/@protobufjs/inquire/tests/data/emptyArray.js @@ -0,0 +1 @@ +module.exports = []; diff --git a/node_modules/@protobufjs/inquire/tests/data/emptyObject.js b/node_modules/@protobufjs/inquire/tests/data/emptyObject.js new file mode 100644 index 0000000..f053ebf --- /dev/null +++ b/node_modules/@protobufjs/inquire/tests/data/emptyObject.js @@ -0,0 +1 @@ +module.exports = {}; diff --git a/node_modules/@protobufjs/inquire/tests/data/object.js b/node_modules/@protobufjs/inquire/tests/data/object.js new file mode 100644 index 0000000..3b75bca --- /dev/null +++ b/node_modules/@protobufjs/inquire/tests/data/object.js @@ -0,0 +1 @@ +module.exports = { a: 1 }; diff --git a/node_modules/@protobufjs/inquire/tests/index.js b/node_modules/@protobufjs/inquire/tests/index.js new file mode 100644 index 0000000..4a555ca --- /dev/null +++ b/node_modules/@protobufjs/inquire/tests/index.js @@ -0,0 +1,20 @@ +var tape = require("tape"); + +var inquire = require(".."); + +tape.test("inquire", function(test) { + + test.equal(inquire("buffer").Buffer, Buffer, "should be able to require \"buffer\""); + + test.equal(inquire("%invalid"), null, "should not be able to require \"%invalid\""); + + test.equal(inquire("./tests/data/emptyObject"), null, "should return null when requiring a module exporting an empty object"); + + test.equal(inquire("./tests/data/emptyArray"), null, "should return null when requiring a module exporting an empty array"); + + test.same(inquire("./tests/data/object"), { a: 1 }, "should return the object if a non-empty object"); + + test.same(inquire("./tests/data/array"), [ 1 ], "should return the module if a non-empty array"); + + test.end(); +}); diff --git a/node_modules/@protobufjs/path/LICENSE b/node_modules/@protobufjs/path/LICENSE new file mode 100644 index 0000000..be2b397 --- /dev/null +++ b/node_modules/@protobufjs/path/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@protobufjs/path/README.md b/node_modules/@protobufjs/path/README.md new file mode 100644 index 0000000..1c1a2ba --- /dev/null +++ b/node_modules/@protobufjs/path/README.md @@ -0,0 +1,19 @@ +@protobufjs/path +================ +[![npm](https://img.shields.io/npm/v/@protobufjs/path.svg)](https://www.npmjs.com/package/@protobufjs/path) + +A minimal path module to resolve Unix, Windows and URL paths alike. + +API +--- + +* **path.isAbsolute(path: `string`): `boolean`**
                          + Tests if the specified path is absolute. + +* **path.normalize(path: `string`): `string`**
                          + Normalizes the specified path. + +* **path.resolve(originPath: `string`, includePath: `string`, [alreadyNormalized=false: `boolean`]): `string`**
                          + Resolves the specified include path against the specified origin path. + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/@protobufjs/path/index.d.ts b/node_modules/@protobufjs/path/index.d.ts new file mode 100644 index 0000000..b664d81 --- /dev/null +++ b/node_modules/@protobufjs/path/index.d.ts @@ -0,0 +1,22 @@ +/** + * Tests if the specified path is absolute. + * @param {string} path Path to test + * @returns {boolean} `true` if path is absolute + */ +export function isAbsolute(path: string): boolean; + +/** + * Normalizes the specified path. + * @param {string} path Path to normalize + * @returns {string} Normalized path + */ +export function normalize(path: string): string; + +/** + * Resolves the specified include path against the specified origin path. + * @param {string} originPath Path to the origin file + * @param {string} includePath Include path relative to origin path + * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized + * @returns {string} Path to the include file + */ +export function resolve(originPath: string, includePath: string, alreadyNormalized?: boolean): string; diff --git a/node_modules/@protobufjs/path/index.js b/node_modules/@protobufjs/path/index.js new file mode 100644 index 0000000..7c7fb72 --- /dev/null +++ b/node_modules/@protobufjs/path/index.js @@ -0,0 +1,65 @@ +"use strict"; + +/** + * A minimal path module to resolve Unix, Windows and URL paths alike. + * @memberof util + * @namespace + */ +var path = exports; + +var isAbsolute = +/** + * Tests if the specified path is absolute. + * @param {string} path Path to test + * @returns {boolean} `true` if path is absolute + */ +path.isAbsolute = function isAbsolute(path) { + return /^(?:\/|\w+:)/.test(path); +}; + +var normalize = +/** + * Normalizes the specified path. + * @param {string} path Path to normalize + * @returns {string} Normalized path + */ +path.normalize = function normalize(path) { + path = path.replace(/\\/g, "/") + .replace(/\/{2,}/g, "/"); + var parts = path.split("/"), + absolute = isAbsolute(path), + prefix = ""; + if (absolute) + prefix = parts.shift() + "/"; + for (var i = 0; i < parts.length;) { + if (parts[i] === "..") { + if (i > 0 && parts[i - 1] !== "..") + parts.splice(--i, 2); + else if (absolute) + parts.splice(i, 1); + else + ++i; + } else if (parts[i] === ".") + parts.splice(i, 1); + else + ++i; + } + return prefix + parts.join("/"); +}; + +/** + * Resolves the specified include path against the specified origin path. + * @param {string} originPath Path to the origin file + * @param {string} includePath Include path relative to origin path + * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized + * @returns {string} Path to the include file + */ +path.resolve = function resolve(originPath, includePath, alreadyNormalized) { + if (!alreadyNormalized) + includePath = normalize(includePath); + if (isAbsolute(includePath)) + return includePath; + if (!alreadyNormalized) + originPath = normalize(originPath); + return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath; +}; diff --git a/node_modules/@protobufjs/path/package.json b/node_modules/@protobufjs/path/package.json new file mode 100644 index 0000000..2262e01 --- /dev/null +++ b/node_modules/@protobufjs/path/package.json @@ -0,0 +1,21 @@ +{ + "name": "@protobufjs/path", + "description": "A minimal path module to resolve Unix, Windows and URL paths alike.", + "version": "1.1.2", + "author": "Daniel Wirtz ", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/protobuf.js.git" + }, + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "devDependencies": { + "istanbul": "^0.4.5", + "tape": "^4.6.3" + }, + "scripts": { + "test": "tape tests/*.js", + "coverage": "istanbul cover node_modules/tape/bin/tape tests/*.js" + } +} \ No newline at end of file diff --git a/node_modules/@protobufjs/path/tests/index.js b/node_modules/@protobufjs/path/tests/index.js new file mode 100644 index 0000000..9c23bc9 --- /dev/null +++ b/node_modules/@protobufjs/path/tests/index.js @@ -0,0 +1,60 @@ +var tape = require("tape"); + +var path = require(".."); + +tape.test("path", function(test) { + + test.ok(path.isAbsolute("X:\\some\\path\\file.js"), "should identify absolute windows paths"); + test.ok(path.isAbsolute("/some/path/file.js"), "should identify absolute unix paths"); + + test.notOk(path.isAbsolute("some\\path\\file.js"), "should identify relative windows paths"); + test.notOk(path.isAbsolute("some/path/file.js"), "should identify relative unix paths"); + + var paths = [ + { + actual: "X:\\some\\..\\.\\path\\\\file.js", + normal: "X:/path/file.js", + resolve: { + origin: "X:/path/origin.js", + expected: "X:/path/file.js" + } + }, { + actual: "some\\..\\.\\path\\\\file.js", + normal: "path/file.js", + resolve: { + origin: "X:/path/origin.js", + expected: "X:/path/path/file.js" + } + }, { + actual: "/some/.././path//file.js", + normal: "/path/file.js", + resolve: { + origin: "/path/origin.js", + expected: "/path/file.js" + } + }, { + actual: "some/.././path//file.js", + normal: "path/file.js", + resolve: { + origin: "", + expected: "path/file.js" + } + }, { + actual: ".././path//file.js", + normal: "../path/file.js" + }, { + actual: "/.././path//file.js", + normal: "/path/file.js" + } + ]; + + paths.forEach(function(p) { + test.equal(path.normalize(p.actual), p.normal, "should normalize " + p.actual); + if (p.resolve) { + test.equal(path.resolve(p.resolve.origin, p.actual), p.resolve.expected, "should resolve " + p.actual); + test.equal(path.resolve(p.resolve.origin, p.normal, true), p.resolve.expected, "should resolve " + p.normal + " (already normalized)"); + } + }); + + test.end(); +}); diff --git a/node_modules/@protobufjs/pool/.npmignore b/node_modules/@protobufjs/pool/.npmignore new file mode 100644 index 0000000..c3fc82e --- /dev/null +++ b/node_modules/@protobufjs/pool/.npmignore @@ -0,0 +1,3 @@ +npm-debug.* +node_modules/ +coverage/ diff --git a/node_modules/@protobufjs/pool/LICENSE b/node_modules/@protobufjs/pool/LICENSE new file mode 100644 index 0000000..be2b397 --- /dev/null +++ b/node_modules/@protobufjs/pool/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@protobufjs/pool/README.md b/node_modules/@protobufjs/pool/README.md new file mode 100644 index 0000000..9fb0e97 --- /dev/null +++ b/node_modules/@protobufjs/pool/README.md @@ -0,0 +1,13 @@ +@protobufjs/pool +================ +[![npm](https://img.shields.io/npm/v/@protobufjs/pool.svg)](https://www.npmjs.com/package/@protobufjs/pool) + +A general purpose buffer pool. + +API +--- + +* **pool(alloc: `function(size: number): Uint8Array`, slice: `function(this: Uint8Array, start: number, end: number): Uint8Array`, [size=8192: `number`]): `function(size: number): Uint8Array`**
                          + Creates a pooled allocator. + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/@protobufjs/pool/index.d.ts b/node_modules/@protobufjs/pool/index.d.ts new file mode 100644 index 0000000..23fe38c --- /dev/null +++ b/node_modules/@protobufjs/pool/index.d.ts @@ -0,0 +1,32 @@ +export = pool; + +/** + * An allocator as used by {@link util.pool}. + * @typedef PoolAllocator + * @type {function} + * @param {number} size Buffer size + * @returns {Uint8Array} Buffer + */ +type PoolAllocator = (size: number) => Uint8Array; + +/** + * A slicer as used by {@link util.pool}. + * @typedef PoolSlicer + * @type {function} + * @param {number} start Start offset + * @param {number} end End offset + * @returns {Uint8Array} Buffer slice + * @this {Uint8Array} + */ +type PoolSlicer = (this: Uint8Array, start: number, end: number) => Uint8Array; + +/** + * A general purpose buffer pool. + * @memberof util + * @function + * @param {PoolAllocator} alloc Allocator + * @param {PoolSlicer} slice Slicer + * @param {number} [size=8192] Slab size + * @returns {PoolAllocator} Pooled allocator + */ +declare function pool(alloc: PoolAllocator, slice: PoolSlicer, size?: number): PoolAllocator; diff --git a/node_modules/@protobufjs/pool/index.js b/node_modules/@protobufjs/pool/index.js new file mode 100644 index 0000000..6c666f6 --- /dev/null +++ b/node_modules/@protobufjs/pool/index.js @@ -0,0 +1,48 @@ +"use strict"; +module.exports = pool; + +/** + * An allocator as used by {@link util.pool}. + * @typedef PoolAllocator + * @type {function} + * @param {number} size Buffer size + * @returns {Uint8Array} Buffer + */ + +/** + * A slicer as used by {@link util.pool}. + * @typedef PoolSlicer + * @type {function} + * @param {number} start Start offset + * @param {number} end End offset + * @returns {Uint8Array} Buffer slice + * @this {Uint8Array} + */ + +/** + * A general purpose buffer pool. + * @memberof util + * @function + * @param {PoolAllocator} alloc Allocator + * @param {PoolSlicer} slice Slicer + * @param {number} [size=8192] Slab size + * @returns {PoolAllocator} Pooled allocator + */ +function pool(alloc, slice, size) { + var SIZE = size || 8192; + var MAX = SIZE >>> 1; + var slab = null; + var offset = SIZE; + return function pool_alloc(size) { + if (size < 1 || size > MAX) + return alloc(size); + if (offset + size > SIZE) { + slab = alloc(SIZE); + offset = 0; + } + var buf = slice.call(slab, offset, offset += size); + if (offset & 7) // align to 32 bit + offset = (offset | 7) + 1; + return buf; + }; +} diff --git a/node_modules/@protobufjs/pool/package.json b/node_modules/@protobufjs/pool/package.json new file mode 100644 index 0000000..f025e03 --- /dev/null +++ b/node_modules/@protobufjs/pool/package.json @@ -0,0 +1,21 @@ +{ + "name": "@protobufjs/pool", + "description": "A general purpose buffer pool.", + "version": "1.1.0", + "author": "Daniel Wirtz ", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/protobuf.js.git" + }, + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "devDependencies": { + "istanbul": "^0.4.5", + "tape": "^4.6.3" + }, + "scripts": { + "test": "tape tests/*.js", + "coverage": "istanbul cover node_modules/tape/bin/tape tests/*.js" + } +} diff --git a/node_modules/@protobufjs/pool/tests/index.js b/node_modules/@protobufjs/pool/tests/index.js new file mode 100644 index 0000000..5d1a921 --- /dev/null +++ b/node_modules/@protobufjs/pool/tests/index.js @@ -0,0 +1,33 @@ +var tape = require("tape"); + +var pool = require(".."); + +if (typeof Uint8Array !== "undefined") +tape.test("pool", function(test) { + + var alloc = pool(function(size) { return new Uint8Array(size); }, Uint8Array.prototype.subarray); + + var buf1 = alloc(0); + test.equal(buf1.length, 0, "should allocate a buffer of size 0"); + + var buf2 = alloc(1); + test.equal(buf2.length, 1, "should allocate a buffer of size 1 (initializes slab)"); + + test.notEqual(buf2.buffer, buf1.buffer, "should not reference the same backing buffer if previous buffer had size 0"); + test.equal(buf2.byteOffset, 0, "should allocate at byteOffset 0 when using a new slab"); + + buf1 = alloc(1); + test.equal(buf1.buffer, buf2.buffer, "should reference the same backing buffer when allocating a chunk fitting into the slab"); + test.equal(buf1.byteOffset, 8, "should align slices to 32 bit and this allocate at byteOffset 8"); + + var buf3 = alloc(4097); + test.notEqual(buf3.buffer, buf2.buffer, "should not reference the same backing buffer when allocating a buffer larger than half the backing buffer's size"); + + buf2 = alloc(4096); + test.equal(buf2.buffer, buf1.buffer, "should reference the same backing buffer when allocating a buffer smaller or equal than half the backing buffer's size"); + + buf1 = alloc(4096); + test.notEqual(buf1.buffer, buf2.buffer, "should not reference the same backing buffer when the slab is exhausted (initializes new slab)"); + + test.end(); +}); \ No newline at end of file diff --git a/node_modules/@protobufjs/utf8/.npmignore b/node_modules/@protobufjs/utf8/.npmignore new file mode 100644 index 0000000..c3fc82e --- /dev/null +++ b/node_modules/@protobufjs/utf8/.npmignore @@ -0,0 +1,3 @@ +npm-debug.* +node_modules/ +coverage/ diff --git a/node_modules/@protobufjs/utf8/LICENSE b/node_modules/@protobufjs/utf8/LICENSE new file mode 100644 index 0000000..be2b397 --- /dev/null +++ b/node_modules/@protobufjs/utf8/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@protobufjs/utf8/README.md b/node_modules/@protobufjs/utf8/README.md new file mode 100644 index 0000000..c936d9b --- /dev/null +++ b/node_modules/@protobufjs/utf8/README.md @@ -0,0 +1,20 @@ +@protobufjs/utf8 +================ +[![npm](https://img.shields.io/npm/v/@protobufjs/utf8.svg)](https://www.npmjs.com/package/@protobufjs/utf8) + +A minimal UTF8 implementation for number arrays. + +API +--- + +* **utf8.length(string: `string`): `number`**
                          + Calculates the UTF8 byte length of a string. + +* **utf8.read(buffer: `Uint8Array`, start: `number`, end: `number`): `string`**
                          + Reads UTF8 bytes as a string. + +* **utf8.write(string: `string`, buffer: `Uint8Array`, offset: `number`): `number`**
                          + Writes a string as UTF8 bytes. + + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/@protobufjs/utf8/index.d.ts b/node_modules/@protobufjs/utf8/index.d.ts new file mode 100644 index 0000000..2f1d0ab --- /dev/null +++ b/node_modules/@protobufjs/utf8/index.d.ts @@ -0,0 +1,24 @@ +/** + * Calculates the UTF8 byte length of a string. + * @param {string} string String + * @returns {number} Byte length + */ +export function length(string: string): number; + +/** + * Reads UTF8 bytes as a string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} String read + */ +export function read(buffer: Uint8Array, start: number, end: number): string; + +/** + * Writes a string as UTF8 bytes. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Bytes written + */ +export function write(string: string, buffer: Uint8Array, offset: number): number; diff --git a/node_modules/@protobufjs/utf8/index.js b/node_modules/@protobufjs/utf8/index.js new file mode 100644 index 0000000..43c5298 --- /dev/null +++ b/node_modules/@protobufjs/utf8/index.js @@ -0,0 +1,105 @@ +"use strict"; + +/** + * A minimal UTF8 implementation for number arrays. + * @memberof util + * @namespace + */ +var utf8 = exports; + +/** + * Calculates the UTF8 byte length of a string. + * @param {string} string String + * @returns {number} Byte length + */ +utf8.length = function utf8_length(string) { + var len = 0, + c = 0; + for (var i = 0; i < string.length; ++i) { + c = string.charCodeAt(i); + if (c < 128) + len += 1; + else if (c < 2048) + len += 2; + else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) { + ++i; + len += 4; + } else + len += 3; + } + return len; +}; + +/** + * Reads UTF8 bytes as a string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} String read + */ +utf8.read = function utf8_read(buffer, start, end) { + var len = end - start; + if (len < 1) + return ""; + var parts = null, + chunk = [], + i = 0, // char offset + t; // temporary + while (start < end) { + t = buffer[start++]; + if (t < 128) + chunk[i++] = t; + else if (t > 191 && t < 224) + chunk[i++] = (t & 31) << 6 | buffer[start++] & 63; + else if (t > 239 && t < 365) { + t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000; + chunk[i++] = 0xD800 + (t >> 10); + chunk[i++] = 0xDC00 + (t & 1023); + } else + chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i = 0; + } + } + if (parts) { + if (i) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i)); +}; + +/** + * Writes a string as UTF8 bytes. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Bytes written + */ +utf8.write = function utf8_write(string, buffer, offset) { + var start = offset, + c1, // character 1 + c2; // character 2 + for (var i = 0; i < string.length; ++i) { + c1 = string.charCodeAt(i); + if (c1 < 128) { + buffer[offset++] = c1; + } else if (c1 < 2048) { + buffer[offset++] = c1 >> 6 | 192; + buffer[offset++] = c1 & 63 | 128; + } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) { + c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF); + ++i; + buffer[offset++] = c1 >> 18 | 240; + buffer[offset++] = c1 >> 12 & 63 | 128; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } else { + buffer[offset++] = c1 >> 12 | 224; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } + } + return offset - start; +}; diff --git a/node_modules/@protobufjs/utf8/package.json b/node_modules/@protobufjs/utf8/package.json new file mode 100644 index 0000000..80881c5 --- /dev/null +++ b/node_modules/@protobufjs/utf8/package.json @@ -0,0 +1,21 @@ +{ + "name": "@protobufjs/utf8", + "description": "A minimal UTF8 implementation for number arrays.", + "version": "1.1.0", + "author": "Daniel Wirtz ", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/protobuf.js.git" + }, + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "devDependencies": { + "istanbul": "^0.4.5", + "tape": "^4.6.3" + }, + "scripts": { + "test": "tape tests/*.js", + "coverage": "istanbul cover node_modules/tape/bin/tape tests/*.js" + } +} diff --git a/node_modules/@protobufjs/utf8/tests/data/utf8.txt b/node_modules/@protobufjs/utf8/tests/data/utf8.txt new file mode 100644 index 0000000..580b4c4 --- /dev/null +++ b/node_modules/@protobufjs/utf8/tests/data/utf8.txt @@ -0,0 +1,216 @@ +UTF-8 encoded sample plain-text file +‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ + +Markus Kuhn [ˈmaʳkʊs kuːn] — 2002-07-25 CC BY + + +The ASCII compatible UTF-8 encoding used in this plain-text file +is defined in Unicode, ISO 10646-1, and RFC 2279. + + +Using Unicode/UTF-8, you can write in emails and source code things such as + +Mathematics and sciences: + + ∮ E⋅da = Q, n → ∞, ∑ f(i) = ∏ g(i), ⎧⎡⎛┌─────┐⎞⎤⎫ + ⎪⎢⎜│a²+b³ ⎟⎥⎪ + ∀x∈ℝ: ⌈x⌉ = −⌊−x⌋, α ∧ ¬β = ¬(¬α ∨ β), ⎪⎢⎜│───── ⎟⎥⎪ + ⎪⎢⎜⎷ c₈ ⎟⎥⎪ + ℕ ⊆ ℕ₀ ⊂ ℤ ⊂ ℚ ⊂ ℝ ⊂ ℂ, ⎨⎢⎜ ⎟⎥⎬ + ⎪⎢⎜ ∞ ⎟⎥⎪ + ⊥ < a ≠ b ≡ c ≤ d ≪ ⊤ ⇒ (⟦A⟧ ⇔ ⟪B⟫), ⎪⎢⎜ ⎲ ⎟⎥⎪ + ⎪⎢⎜ ⎳aⁱ-bⁱ⎟⎥⎪ + 2H₂ + O₂ ⇌ 2H₂O, R = 4.7 kΩ, ⌀ 200 mm ⎩⎣⎝i=1 ⎠⎦⎭ + +Linguistics and dictionaries: + + ði ıntəˈnæʃənəl fəˈnɛtık əsoʊsiˈeıʃn + Y [ˈʏpsilɔn], Yen [jɛn], Yoga [ˈjoːgɑ] + +APL: + + ((V⍳V)=⍳⍴V)/V←,V ⌷←⍳→⍴∆∇⊃‾⍎⍕⌈ + +Nicer typography in plain text files: + + ╔══════════════════════════════════════════╗ + ║ ║ + ║ • ‘single’ and “double” quotes ║ + ║ ║ + ║ • Curly apostrophes: “We’ve been here” ║ + ║ ║ + ║ • Latin-1 apostrophe and accents: '´` ║ + ║ ║ + ║ • ‚deutsche‘ „Anführungszeichen“ ║ + ║ ║ + ║ • †, ‡, ‰, •, 3–4, —, −5/+5, ™, … ║ + ║ ║ + ║ • ASCII safety test: 1lI|, 0OD, 8B ║ + ║ ╭─────────╮ ║ + ║ • the euro symbol: │ 14.95 € │ ║ + ║ ╰─────────╯ ║ + ╚══════════════════════════════════════════╝ + +Combining characters: + + STARGΛ̊TE SG-1, a = v̇ = r̈, a⃑ ⊥ b⃑ + +Greek (in Polytonic): + + The Greek anthem: + + Σὲ γνωρίζω ἀπὸ τὴν κόψη + τοῦ σπαθιοῦ τὴν τρομερή, + σὲ γνωρίζω ἀπὸ τὴν ὄψη + ποὺ μὲ βία μετράει τὴ γῆ. + + ᾿Απ᾿ τὰ κόκκαλα βγαλμένη + τῶν ῾Ελλήνων τὰ ἱερά + καὶ σὰν πρῶτα ἀνδρειωμένη + χαῖρε, ὦ χαῖρε, ᾿Ελευθεριά! + + From a speech of Demosthenes in the 4th century BC: + + Οὐχὶ ταὐτὰ παρίσταταί μοι γιγνώσκειν, ὦ ἄνδρες ᾿Αθηναῖοι, + ὅταν τ᾿ εἰς τὰ πράγματα ἀποβλέψω καὶ ὅταν πρὸς τοὺς + λόγους οὓς ἀκούω· τοὺς μὲν γὰρ λόγους περὶ τοῦ + τιμωρήσασθαι Φίλιππον ὁρῶ γιγνομένους, τὰ δὲ πράγματ᾿ + εἰς τοῦτο προήκοντα, ὥσθ᾿ ὅπως μὴ πεισόμεθ᾿ αὐτοὶ + πρότερον κακῶς σκέψασθαι δέον. οὐδέν οὖν ἄλλο μοι δοκοῦσιν + οἱ τὰ τοιαῦτα λέγοντες ἢ τὴν ὑπόθεσιν, περὶ ἧς βουλεύεσθαι, + οὐχὶ τὴν οὖσαν παριστάντες ὑμῖν ἁμαρτάνειν. ἐγὼ δέ, ὅτι μέν + ποτ᾿ ἐξῆν τῇ πόλει καὶ τὰ αὑτῆς ἔχειν ἀσφαλῶς καὶ Φίλιππον + τιμωρήσασθαι, καὶ μάλ᾿ ἀκριβῶς οἶδα· ἐπ᾿ ἐμοῦ γάρ, οὐ πάλαι + γέγονεν ταῦτ᾿ ἀμφότερα· νῦν μέντοι πέπεισμαι τοῦθ᾿ ἱκανὸν + προλαβεῖν ἡμῖν εἶναι τὴν πρώτην, ὅπως τοὺς συμμάχους + σώσομεν. ἐὰν γὰρ τοῦτο βεβαίως ὑπάρξῃ, τότε καὶ περὶ τοῦ + τίνα τιμωρήσεταί τις καὶ ὃν τρόπον ἐξέσται σκοπεῖν· πρὶν δὲ + τὴν ἀρχὴν ὀρθῶς ὑποθέσθαι, μάταιον ἡγοῦμαι περὶ τῆς + τελευτῆς ὁντινοῦν ποιεῖσθαι λόγον. + + Δημοσθένους, Γ´ ᾿Ολυνθιακὸς + +Georgian: + + From a Unicode conference invitation: + + გთხოვთ ახლავე გაიაროთ რეგისტრაცია Unicode-ის მეათე საერთაშორისო + კონფერენციაზე დასასწრებად, რომელიც გაიმართება 10-12 მარტს, + ქ. მაინცში, გერმანიაში. კონფერენცია შეჰკრებს ერთად მსოფლიოს + ექსპერტებს ისეთ დარგებში როგორიცაა ინტერნეტი და Unicode-ი, + ინტერნაციონალიზაცია და ლოკალიზაცია, Unicode-ის გამოყენება + ოპერაციულ სისტემებსა, და გამოყენებით პროგრამებში, შრიფტებში, + ტექსტების დამუშავებასა და მრავალენოვან კომპიუტერულ სისტემებში. + +Russian: + + From a Unicode conference invitation: + + Зарегистрируйтесь сейчас на Десятую Международную Конференцию по + Unicode, которая состоится 10-12 марта 1997 года в Майнце в Германии. + Конференция соберет широкий круг экспертов по вопросам глобального + Интернета и Unicode, локализации и интернационализации, воплощению и + применению Unicode в различных операционных системах и программных + приложениях, шрифтах, верстке и многоязычных компьютерных системах. + +Thai (UCS Level 2): + + Excerpt from a poetry on The Romance of The Three Kingdoms (a Chinese + classic 'San Gua'): + + [----------------------------|------------------------] + ๏ แผ่นดินฮั่นเสื่อมโทรมแสนสังเวช พระปกเกศกองบู๊กู้ขึ้นใหม่ + สิบสองกษัตริย์ก่อนหน้าแลถัดไป สององค์ไซร้โง่เขลาเบาปัญญา + ทรงนับถือขันทีเป็นที่พึ่ง บ้านเมืองจึงวิปริตเป็นนักหนา + โฮจิ๋นเรียกทัพทั่วหัวเมืองมา หมายจะฆ่ามดชั่วตัวสำคัญ + เหมือนขับไสไล่เสือจากเคหา รับหมาป่าเข้ามาเลยอาสัญ + ฝ่ายอ้องอุ้นยุแยกให้แตกกัน ใช้สาวนั้นเป็นชนวนชื่นชวนใจ + พลันลิฉุยกุยกีกลับก่อเหตุ ช่างอาเพศจริงหนาฟ้าร้องไห้ + ต้องรบราฆ่าฟันจนบรรลัย ฤๅหาใครค้ำชูกู้บรรลังก์ ฯ + + (The above is a two-column text. If combining characters are handled + correctly, the lines of the second column should be aligned with the + | character above.) + +Ethiopian: + + Proverbs in the Amharic language: + + ሰማይ አይታረስ ንጉሥ አይከሰስ። + ብላ ካለኝ እንደአባቴ በቆመጠኝ። + ጌጥ ያለቤቱ ቁምጥና ነው። + ደሀ በሕልሙ ቅቤ ባይጠጣ ንጣት በገደለው። + የአፍ ወለምታ በቅቤ አይታሽም። + አይጥ በበላ ዳዋ ተመታ። + ሲተረጉሙ ይደረግሙ። + ቀስ በቀስ፥ ዕንቁላል በእግሩ ይሄዳል። + ድር ቢያብር አንበሳ ያስር። + ሰው እንደቤቱ እንጅ እንደ ጉረቤቱ አይተዳደርም። + እግዜር የከፈተውን ጉሮሮ ሳይዘጋው አይድርም። + የጎረቤት ሌባ፥ ቢያዩት ይስቅ ባያዩት ያጠልቅ። + ሥራ ከመፍታት ልጄን ላፋታት። + ዓባይ ማደሪያ የለው፥ ግንድ ይዞ ይዞራል። + የእስላም አገሩ መካ የአሞራ አገሩ ዋርካ። + ተንጋሎ ቢተፉ ተመልሶ ባፉ። + ወዳጅህ ማር ቢሆን ጨርስህ አትላሰው። + እግርህን በፍራሽህ ልክ ዘርጋ። + +Runes: + + ᚻᛖ ᚳᚹᚫᚦ ᚦᚫᛏ ᚻᛖ ᛒᚢᛞᛖ ᚩᚾ ᚦᚫᛗ ᛚᚪᚾᛞᛖ ᚾᚩᚱᚦᚹᛖᚪᚱᛞᚢᛗ ᚹᛁᚦ ᚦᚪ ᚹᛖᛥᚫ + + (Old English, which transcribed into Latin reads 'He cwaeth that he + bude thaem lande northweardum with tha Westsae.' and means 'He said + that he lived in the northern land near the Western Sea.') + +Braille: + + ⡌⠁⠧⠑ ⠼⠁⠒ ⡍⠜⠇⠑⠹⠰⠎ ⡣⠕⠌ + + ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠙⠑⠁⠙⠒ ⠞⠕ ⠃⠑⠛⠔ ⠺⠊⠹⠲ ⡹⠻⠑ ⠊⠎ ⠝⠕ ⠙⠳⠃⠞ + ⠱⠁⠞⠑⠧⠻ ⠁⠃⠳⠞ ⠹⠁⠞⠲ ⡹⠑ ⠗⠑⠛⠊⠌⠻ ⠕⠋ ⠙⠊⠎ ⠃⠥⠗⠊⠁⠇ ⠺⠁⠎ + ⠎⠊⠛⠝⠫ ⠃⠹ ⠹⠑ ⠊⠇⠻⠛⠹⠍⠁⠝⠂ ⠹⠑ ⠊⠇⠻⠅⠂ ⠹⠑ ⠥⠝⠙⠻⠞⠁⠅⠻⠂ + ⠁⠝⠙ ⠹⠑ ⠡⠊⠑⠋ ⠍⠳⠗⠝⠻⠲ ⡎⠊⠗⠕⠕⠛⠑ ⠎⠊⠛⠝⠫ ⠊⠞⠲ ⡁⠝⠙ + ⡎⠊⠗⠕⠕⠛⠑⠰⠎ ⠝⠁⠍⠑ ⠺⠁⠎ ⠛⠕⠕⠙ ⠥⠏⠕⠝ ⠰⡡⠁⠝⠛⠑⠂ ⠋⠕⠗ ⠁⠝⠹⠹⠔⠛ ⠙⠑ + ⠡⠕⠎⠑ ⠞⠕ ⠏⠥⠞ ⠙⠊⠎ ⠙⠁⠝⠙ ⠞⠕⠲ + + ⡕⠇⠙ ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠁⠎ ⠙⠑⠁⠙ ⠁⠎ ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲ + + ⡍⠔⠙⠖ ⡊ ⠙⠕⠝⠰⠞ ⠍⠑⠁⠝ ⠞⠕ ⠎⠁⠹ ⠹⠁⠞ ⡊ ⠅⠝⠪⠂ ⠕⠋ ⠍⠹ + ⠪⠝ ⠅⠝⠪⠇⠫⠛⠑⠂ ⠱⠁⠞ ⠹⠻⠑ ⠊⠎ ⠏⠜⠞⠊⠊⠥⠇⠜⠇⠹ ⠙⠑⠁⠙ ⠁⠃⠳⠞ + ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲ ⡊ ⠍⠊⠣⠞ ⠙⠁⠧⠑ ⠃⠑⠲ ⠔⠊⠇⠔⠫⠂ ⠍⠹⠎⠑⠇⠋⠂ ⠞⠕ + ⠗⠑⠛⠜⠙ ⠁ ⠊⠕⠋⠋⠔⠤⠝⠁⠊⠇ ⠁⠎ ⠹⠑ ⠙⠑⠁⠙⠑⠌ ⠏⠊⠑⠊⠑ ⠕⠋ ⠊⠗⠕⠝⠍⠕⠝⠛⠻⠹ + ⠔ ⠹⠑ ⠞⠗⠁⠙⠑⠲ ⡃⠥⠞ ⠹⠑ ⠺⠊⠎⠙⠕⠍ ⠕⠋ ⠳⠗ ⠁⠝⠊⠑⠌⠕⠗⠎ + ⠊⠎ ⠔ ⠹⠑ ⠎⠊⠍⠊⠇⠑⠆ ⠁⠝⠙ ⠍⠹ ⠥⠝⠙⠁⠇⠇⠪⠫ ⠙⠁⠝⠙⠎ + ⠩⠁⠇⠇ ⠝⠕⠞ ⠙⠊⠌⠥⠗⠃ ⠊⠞⠂ ⠕⠗ ⠹⠑ ⡊⠳⠝⠞⠗⠹⠰⠎ ⠙⠕⠝⠑ ⠋⠕⠗⠲ ⡹⠳ + ⠺⠊⠇⠇ ⠹⠻⠑⠋⠕⠗⠑ ⠏⠻⠍⠊⠞ ⠍⠑ ⠞⠕ ⠗⠑⠏⠑⠁⠞⠂ ⠑⠍⠏⠙⠁⠞⠊⠊⠁⠇⠇⠹⠂ ⠹⠁⠞ + ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠁⠎ ⠙⠑⠁⠙ ⠁⠎ ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲ + + (The first couple of paragraphs of "A Christmas Carol" by Dickens) + +Compact font selection example text: + + ABCDEFGHIJKLMNOPQRSTUVWXYZ /0123456789 + abcdefghijklmnopqrstuvwxyz £©µÀÆÖÞßéöÿ + –—‘“”„†•…‰™œŠŸž€ ΑΒΓΔΩαβγδω АБВГДабвгд + ∀∂∈ℝ∧∪≡∞ ↑↗↨↻⇣ ┐┼╔╘░►☺♀ fi�⑀₂ἠḂӥẄɐː⍎אԱა + +Greetings in various languages: + + Hello world, Καλημέρα κόσμε, コンニチハ + +Box drawing alignment tests: █ + ▉ + ╔══╦══╗ ┌──┬──┐ ╭──┬──╮ ╭──┬──╮ ┏━━┳━━┓ ┎┒┏┑ ╷ ╻ ┏┯┓ ┌┰┐ ▊ ╱╲╱╲╳╳╳ + ║┌─╨─┐║ │╔═╧═╗│ │╒═╪═╕│ │╓─╁─╖│ ┃┌─╂─┐┃ ┗╃╄┙ ╶┼╴╺╋╸┠┼┨ ┝╋┥ ▋ ╲╱╲╱╳╳╳ + ║│╲ ╱│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╿ │┃ ┍╅╆┓ ╵ ╹ ┗┷┛ └┸┘ ▌ ╱╲╱╲╳╳╳ + ╠╡ ╳ ╞╣ ├╢ ╟┤ ├┼─┼─┼┤ ├╫─╂─╫┤ ┣┿╾┼╼┿┫ ┕┛┖┚ ┌┄┄┐ ╎ ┏┅┅┓ ┋ ▍ ╲╱╲╱╳╳╳ + ║│╱ ╲│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╽ │┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▎ + ║└─╥─┘║ │╚═╤═╝│ │╘═╪═╛│ │╙─╀─╜│ ┃└─╂─┘┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▏ + ╚══╩══╝ └──┴──┘ ╰──┴──╯ ╰──┴──╯ ┗━━┻━━┛ ▗▄▖▛▀▜ └╌╌┘ ╎ ┗╍╍┛ ┋ ▁▂▃▄▅▆▇█ + ▝▀▘▙▄▟ + +Surrogates: + +𠜎 𠜱 𠝹 𠱓 𠱸 𠲖 𠳏 𠳕 𠴕 𠵼 𠵿 𠸎 𠸏 𠹷 𠺝 𠺢 𠻗 𠻹 𠻺 𠼭 𠼮 𠽌 𠾴 𠾼 𠿪 𡁜 𡁯 𡁵 𡁶 𡁻 𡃁 +𡃉 𡇙 𢃇 𢞵 𢫕 𢭃 𢯊 𢱑 𢱕 𢳂 𢴈 𢵌 𢵧 𢺳 𣲷 𤓓 𤶸 𤷪 𥄫 𦉘 𦟌 𦧲 𦧺 𧨾 𨅝 𨈇 𨋢 𨳊 𨳍 𨳒 𩶘 diff --git a/node_modules/@protobufjs/utf8/tests/index.js b/node_modules/@protobufjs/utf8/tests/index.js new file mode 100644 index 0000000..16d169e --- /dev/null +++ b/node_modules/@protobufjs/utf8/tests/index.js @@ -0,0 +1,57 @@ +var tape = require("tape"); + +var utf8 = require(".."); + +var data = require("fs").readFileSync(require.resolve("./data/utf8.txt")), + dataStr = data.toString("utf8"); + +tape.test("utf8", function(test) { + + test.test(test.name + " - length", function(test) { + test.equal(utf8.length(""), 0, "should return a byte length of zero for an empty string"); + + test.equal(utf8.length(dataStr), Buffer.byteLength(dataStr), "should return the same byte length as node buffers"); + + test.end(); + }); + + test.test(test.name + " - read", function(test) { + var comp = utf8.read([], 0, 0); + test.equal(comp, "", "should decode an empty buffer to an empty string"); + + comp = utf8.read(data, 0, data.length); + test.equal(comp, data.toString("utf8"), "should decode to the same byte data as node buffers"); + + var longData = Buffer.concat([data, data, data, data]); + comp = utf8.read(longData, 0, longData.length); + test.equal(comp, longData.toString("utf8"), "should decode to the same byte data as node buffers (long)"); + + var chunkData = new Buffer(data.toString("utf8").substring(0, 8192)); + comp = utf8.read(chunkData, 0, chunkData.length); + test.equal(comp, chunkData.toString("utf8"), "should decode to the same byte data as node buffers (chunk size)"); + + test.end(); + }); + + test.test(test.name + " - write", function(test) { + var buf = new Buffer(0); + test.equal(utf8.write("", buf, 0), 0, "should encode an empty string to an empty buffer"); + + var len = utf8.length(dataStr); + buf = new Buffer(len); + test.equal(utf8.write(dataStr, buf, 0), len, "should encode to exactly " + len + " bytes"); + + test.equal(buf.length, data.length, "should encode to a buffer length equal to that of node buffers"); + + for (var i = 0; i < buf.length; ++i) { + if (buf[i] !== data[i]) { + test.fail("should encode to the same buffer data as node buffers (offset " + i + ")"); + return; + } + } + test.pass("should encode to the same buffer data as node buffers"); + + test.end(); + }); + +}); diff --git a/node_modules/@tootallnate/once/LICENSE b/node_modules/@tootallnate/once/LICENSE new file mode 100644 index 0000000..c4c56a2 --- /dev/null +++ b/node_modules/@tootallnate/once/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Nathan Rajlich + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@tootallnate/once/README.md b/node_modules/@tootallnate/once/README.md new file mode 100644 index 0000000..bc980fd --- /dev/null +++ b/node_modules/@tootallnate/once/README.md @@ -0,0 +1,93 @@ +# @tootallnate/once + +### Creates a Promise that waits for a single event + +## Installation + +Install with `npm`: + +```bash +$ npm install @tootallnate/once +``` + +## API + +### once(emitter: EventEmitter, name: string, opts?: OnceOptions): Promise<[...Args]> + +Creates a Promise that waits for event `name` to occur on `emitter`, and resolves +the promise with an array of the values provided to the event handler. If an +`error` event occurs before the event specified by `name`, then the Promise is +rejected with the error argument. + +```typescript +import once from '@tootallnate/once'; +import { EventEmitter } from 'events'; + +const emitter = new EventEmitter(); + +setTimeout(() => { + emitter.emit('foo', 'bar'); +}, 100); + +const [result] = await once(emitter, 'foo'); +console.log({ result }); +// { result: 'bar' } +``` + +#### Promise Strong Typing + +The main feature that this module provides over other "once" implementations is that +the Promise that is returned is _**strongly typed**_ based on the type of `emitter` +and the `name` of the event. Some examples are shown below. + +_The process "exit" event contains a single number for exit code:_ + +```typescript +const [code] = await once(process, 'exit'); +// ^ number +``` +_A child process "exit" event contains either an exit code or a signal:_ + +```typescript +const child = spawn('echo', []); +const [code, signal] = await once(child, 'exit'); +// ^ number | null +// ^ string | null +``` + +_A forked child process "message" event is type `any`, so you can cast the Promise directly:_ + +```typescript +const child = fork('file.js'); + +// With `await` +const [message, _]: [WorkerPayload, unknown] = await once(child, 'message'); + +// With Promise +const messagePromise: Promise<[WorkerPayload, unknown]> = once(child, 'message'); + +// Better yet would be to leave it as `any`, and validate the payload +// at runtime with i.e. `ajv` + `json-schema-to-typescript` +``` + +_If the TypeScript definition does not contain an overload for the specified event name, then the Promise will have type `unknown[]` and your code will need to narrow the result manually:_ + +```typescript +interface CustomEmitter extends EventEmitter { + on(name: 'foo', listener: (a: string, b: number) => void): this; +} + +const emitter: CustomEmitter = new EventEmitter(); + +// "foo" event is a defined overload, so it's properly typed +const fooPromise = once(emitter, 'foo'); +// ^ Promise<[a: string, b: number]> + +// "bar" event in not a defined overload, so it gets `unknown[]` +const barPromise = once(emitter, 'bar'); +// ^ Promise +``` + +### OnceOptions + +- `signal` - `AbortSignal` instance to unbind event handlers before the Promise has been fulfilled. diff --git a/node_modules/@tootallnate/once/dist/index.d.ts b/node_modules/@tootallnate/once/dist/index.d.ts new file mode 100644 index 0000000..93d02a9 --- /dev/null +++ b/node_modules/@tootallnate/once/dist/index.d.ts @@ -0,0 +1,7 @@ +/// +import { EventEmitter } from 'events'; +import { EventNames, EventListenerParameters, AbortSignal } from './types'; +export interface OnceOptions { + signal?: AbortSignal; +} +export default function once>(emitter: Emitter, name: Event, { signal }?: OnceOptions): Promise>; diff --git a/node_modules/@tootallnate/once/dist/index.js b/node_modules/@tootallnate/once/dist/index.js new file mode 100644 index 0000000..ca6385b --- /dev/null +++ b/node_modules/@tootallnate/once/dist/index.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +function once(emitter, name, { signal } = {}) { + return new Promise((resolve, reject) => { + function cleanup() { + signal === null || signal === void 0 ? void 0 : signal.removeEventListener('abort', cleanup); + emitter.removeListener(name, onEvent); + emitter.removeListener('error', onError); + } + function onEvent(...args) { + cleanup(); + resolve(args); + } + function onError(err) { + cleanup(); + reject(err); + } + signal === null || signal === void 0 ? void 0 : signal.addEventListener('abort', cleanup); + emitter.on(name, onEvent); + emitter.on('error', onError); + }); +} +exports.default = once; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@tootallnate/once/dist/index.js.map b/node_modules/@tootallnate/once/dist/index.js.map new file mode 100644 index 0000000..61708ca --- /dev/null +++ b/node_modules/@tootallnate/once/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;AAOA,SAAwB,IAAI,CAI3B,OAAgB,EAChB,IAAW,EACX,EAAE,MAAM,KAAkB,EAAE;IAE5B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACtC,SAAS,OAAO;YACf,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC9C,OAAO,CAAC,cAAc,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;YACtC,OAAO,CAAC,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC1C,CAAC;QACD,SAAS,OAAO,CAAC,GAAG,IAAW;YAC9B,OAAO,EAAE,CAAC;YACV,OAAO,CAAC,IAA+C,CAAC,CAAC;QAC1D,CAAC;QACD,SAAS,OAAO,CAAC,GAAU;YAC1B,OAAO,EAAE,CAAC;YACV,MAAM,CAAC,GAAG,CAAC,CAAC;QACb,CAAC;QACD,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,gBAAgB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC3C,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC1B,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC9B,CAAC,CAAC,CAAC;AACJ,CAAC;AA1BD,uBA0BC"} \ No newline at end of file diff --git a/node_modules/@tootallnate/once/dist/overloaded-parameters.d.ts b/node_modules/@tootallnate/once/dist/overloaded-parameters.d.ts new file mode 100644 index 0000000..eb2bbc6 --- /dev/null +++ b/node_modules/@tootallnate/once/dist/overloaded-parameters.d.ts @@ -0,0 +1,231 @@ +export declare type OverloadedParameters = T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; + (...args: infer A11): any; + (...args: infer A12): any; + (...args: infer A13): any; + (...args: infer A14): any; + (...args: infer A15): any; + (...args: infer A16): any; + (...args: infer A17): any; + (...args: infer A18): any; + (...args: infer A19): any; + (...args: infer A20): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 | A12 | A13 | A14 | A15 | A16 | A17 | A18 | A19 | A20 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; + (...args: infer A11): any; + (...args: infer A12): any; + (...args: infer A13): any; + (...args: infer A14): any; + (...args: infer A15): any; + (...args: infer A16): any; + (...args: infer A17): any; + (...args: infer A18): any; + (...args: infer A19): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 | A12 | A13 | A14 | A15 | A16 | A17 | A18 | A19 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; + (...args: infer A11): any; + (...args: infer A12): any; + (...args: infer A13): any; + (...args: infer A14): any; + (...args: infer A15): any; + (...args: infer A16): any; + (...args: infer A17): any; + (...args: infer A18): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 | A12 | A13 | A14 | A15 | A16 | A17 | A18 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; + (...args: infer A11): any; + (...args: infer A12): any; + (...args: infer A13): any; + (...args: infer A14): any; + (...args: infer A15): any; + (...args: infer A16): any; + (...args: infer A17): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 | A12 | A13 | A14 | A15 | A16 | A17 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; + (...args: infer A11): any; + (...args: infer A12): any; + (...args: infer A13): any; + (...args: infer A14): any; + (...args: infer A15): any; + (...args: infer A16): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 | A12 | A13 | A14 | A15 | A16 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; + (...args: infer A11): any; + (...args: infer A12): any; + (...args: infer A13): any; + (...args: infer A14): any; + (...args: infer A15): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 | A12 | A13 | A14 | A15 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; + (...args: infer A11): any; + (...args: infer A12): any; + (...args: infer A13): any; + (...args: infer A14): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 | A12 | A13 | A14 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; + (...args: infer A11): any; + (...args: infer A12): any; + (...args: infer A13): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 | A12 | A13 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; + (...args: infer A11): any; + (...args: infer A12): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 | A12 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; + (...args: infer A11): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; +} ? A1 | A2 | A3 | A4 | A5 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; +} ? A1 | A2 | A3 | A4 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; +} ? A1 | A2 | A3 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; +} ? A1 | A2 : T extends { + (...args: infer A1): any; +} ? A1 : any; diff --git a/node_modules/@tootallnate/once/dist/overloaded-parameters.js b/node_modules/@tootallnate/once/dist/overloaded-parameters.js new file mode 100644 index 0000000..207186d --- /dev/null +++ b/node_modules/@tootallnate/once/dist/overloaded-parameters.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=overloaded-parameters.js.map \ No newline at end of file diff --git a/node_modules/@tootallnate/once/dist/overloaded-parameters.js.map b/node_modules/@tootallnate/once/dist/overloaded-parameters.js.map new file mode 100644 index 0000000..863f146 --- /dev/null +++ b/node_modules/@tootallnate/once/dist/overloaded-parameters.js.map @@ -0,0 +1 @@ +{"version":3,"file":"overloaded-parameters.js","sourceRoot":"","sources":["../src/overloaded-parameters.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@tootallnate/once/dist/types.d.ts b/node_modules/@tootallnate/once/dist/types.d.ts new file mode 100644 index 0000000..58be828 --- /dev/null +++ b/node_modules/@tootallnate/once/dist/types.d.ts @@ -0,0 +1,17 @@ +/// +import { EventEmitter } from 'events'; +import { OverloadedParameters } from './overloaded-parameters'; +export declare type FirstParameter = T extends [infer R, ...any[]] ? R : never; +export declare type EventListener = F extends [ + T, + infer R, + ...any[] +] ? R : never; +export declare type EventParameters = OverloadedParameters; +export declare type EventNames = FirstParameter>; +export declare type EventListenerParameters> = WithDefault, Event>>, unknown[]>; +export declare type WithDefault = [T] extends [never] ? D : T; +export interface AbortSignal { + addEventListener: (name: string, listener: (...args: any[]) => any) => void; + removeEventListener: (name: string, listener: (...args: any[]) => any) => void; +} diff --git a/node_modules/@tootallnate/once/dist/types.js b/node_modules/@tootallnate/once/dist/types.js new file mode 100644 index 0000000..11e638d --- /dev/null +++ b/node_modules/@tootallnate/once/dist/types.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@tootallnate/once/dist/types.js.map b/node_modules/@tootallnate/once/dist/types.js.map new file mode 100644 index 0000000..c768b79 --- /dev/null +++ b/node_modules/@tootallnate/once/dist/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@tootallnate/once/package.json b/node_modules/@tootallnate/once/package.json new file mode 100644 index 0000000..69ce947 --- /dev/null +++ b/node_modules/@tootallnate/once/package.json @@ -0,0 +1,52 @@ +{ + "name": "@tootallnate/once", + "version": "2.0.0", + "description": "Creates a Promise that waits for a single event", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "scripts": { + "prebuild": "rimraf dist", + "build": "tsc", + "test": "jest", + "prepublishOnly": "npm run build" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/once.git" + }, + "keywords": [], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/once/issues" + }, + "devDependencies": { + "@types/jest": "^27.0.2", + "@types/node": "^12.12.11", + "abort-controller": "^3.0.0", + "jest": "^27.2.1", + "rimraf": "^3.0.0", + "ts-jest": "^27.0.5", + "typescript": "^4.4.3" + }, + "engines": { + "node": ">= 10" + }, + "jest": { + "preset": "ts-jest", + "globals": { + "ts-jest": { + "diagnostics": false, + "isolatedModules": true + } + }, + "verbose": false, + "testEnvironment": "node", + "testMatch": [ + "/test/**/*.test.ts" + ] + } +} diff --git a/node_modules/@types/body-parser/LICENSE b/node_modules/@types/body-parser/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/body-parser/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/body-parser/README.md b/node_modules/@types/body-parser/README.md new file mode 100644 index 0000000..e801582 --- /dev/null +++ b/node_modules/@types/body-parser/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/body-parser` + +# Summary +This package contains type definitions for body-parser (https://github.com/expressjs/body-parser). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/body-parser. + +### Additional Details + * Last updated: Sat, 07 Jun 2025 02:15:25 GMT + * Dependencies: [@types/connect](https://npmjs.com/package/@types/connect), [@types/node](https://npmjs.com/package/@types/node) + +# Credits +These definitions were written by [Santi Albo](https://github.com/santialbo), [Vilic Vane](https://github.com/vilic), [Jonathan Häberle](https://github.com/dreampulse), [Gevik Babakhani](https://github.com/blendsdk), [Tomasz Łaziuk](https://github.com/tlaziuk), [Jason Walton](https://github.com/jwalton), [Piotr Błażejewicz](https://github.com/peterblazejewicz), and [Sebastian Beltran](https://github.com/bjohansebas). diff --git a/node_modules/@types/body-parser/index.d.ts b/node_modules/@types/body-parser/index.d.ts new file mode 100644 index 0000000..96feda8 --- /dev/null +++ b/node_modules/@types/body-parser/index.d.ts @@ -0,0 +1,95 @@ +/// + +import { NextHandleFunction } from "connect"; +import * as http from "http"; + +// for docs go to https://github.com/expressjs/body-parser/tree/1.19.0#body-parser + +declare namespace bodyParser { + interface BodyParser { + /** + * @deprecated use individual json/urlencoded middlewares + */ + (options?: OptionsJson & OptionsText & OptionsUrlencoded): NextHandleFunction; + /** + * Returns middleware that only parses json and only looks at requests + * where the Content-Type header matches the type option. + */ + json(options?: OptionsJson): NextHandleFunction; + /** + * Returns middleware that parses all bodies as a Buffer and only looks at requests + * where the Content-Type header matches the type option. + */ + raw(options?: Options): NextHandleFunction; + + /** + * Returns middleware that parses all bodies as a string and only looks at requests + * where the Content-Type header matches the type option. + */ + text(options?: OptionsText): NextHandleFunction; + /** + * Returns middleware that only parses urlencoded bodies and only looks at requests + * where the Content-Type header matches the type option + */ + urlencoded(options?: OptionsUrlencoded): NextHandleFunction; + } + + interface Options { + /** When set to true, then deflated (compressed) bodies will be inflated; when false, deflated bodies are rejected. Defaults to true. */ + inflate?: boolean | undefined; + /** + * Controls the maximum request body size. If this is a number, + * then the value specifies the number of bytes; if it is a string, + * the value is passed to the bytes library for parsing. Defaults to '100kb'. + */ + limit?: number | string | undefined; + /** + * The type option is used to determine what media type the middleware will parse + */ + type?: string | string[] | ((req: http.IncomingMessage) => any) | undefined; + /** + * The verify option, if supplied, is called as verify(req, res, buf, encoding), + * where buf is a Buffer of the raw request body and encoding is the encoding of the request. + */ + verify?(req: http.IncomingMessage, res: http.ServerResponse, buf: Buffer, encoding: string): void; + } + + interface OptionsJson extends Options { + /** + * The reviver option is passed directly to JSON.parse as the second argument. + */ + reviver?(key: string, value: any): any; + /** + * When set to `true`, will only accept arrays and objects; + * when `false` will accept anything JSON.parse accepts. Defaults to `true`. + */ + strict?: boolean | undefined; + } + + interface OptionsText extends Options { + /** + * Specify the default character set for the text content if the charset + * is not specified in the Content-Type header of the request. + * Defaults to `utf-8`. + */ + defaultCharset?: string | undefined; + } + + interface OptionsUrlencoded extends Options { + /** + * The extended option allows to choose between parsing the URL-encoded data + * with the querystring library (when `false`) or the qs library (when `true`). + */ + extended?: boolean | undefined; + /** + * The parameterLimit option controls the maximum number of parameters + * that are allowed in the URL-encoded data. If a request contains more parameters than this value, + * a 413 will be returned to the client. Defaults to 1000. + */ + parameterLimit?: number | undefined; + } +} + +declare const bodyParser: bodyParser.BodyParser; + +export = bodyParser; diff --git a/node_modules/@types/body-parser/package.json b/node_modules/@types/body-parser/package.json new file mode 100644 index 0000000..15e2dd6 --- /dev/null +++ b/node_modules/@types/body-parser/package.json @@ -0,0 +1,64 @@ +{ + "name": "@types/body-parser", + "version": "1.19.6", + "description": "TypeScript definitions for body-parser", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/body-parser", + "license": "MIT", + "contributors": [ + { + "name": "Santi Albo", + "githubUsername": "santialbo", + "url": "https://github.com/santialbo" + }, + { + "name": "Vilic Vane", + "githubUsername": "vilic", + "url": "https://github.com/vilic" + }, + { + "name": "Jonathan Häberle", + "githubUsername": "dreampulse", + "url": "https://github.com/dreampulse" + }, + { + "name": "Gevik Babakhani", + "githubUsername": "blendsdk", + "url": "https://github.com/blendsdk" + }, + { + "name": "Tomasz Łaziuk", + "githubUsername": "tlaziuk", + "url": "https://github.com/tlaziuk" + }, + { + "name": "Jason Walton", + "githubUsername": "jwalton", + "url": "https://github.com/jwalton" + }, + { + "name": "Piotr Błażejewicz", + "githubUsername": "peterblazejewicz", + "url": "https://github.com/peterblazejewicz" + }, + { + "name": "Sebastian Beltran", + "githubUsername": "bjohansebas", + "url": "https://github.com/bjohansebas" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/body-parser" + }, + "scripts": {}, + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "d788c843f427d6ca19640ee90eb433324a18f23aed05402a82c4e47e6d60b29d", + "typeScriptVersion": "5.1" +} \ No newline at end of file diff --git a/node_modules/@types/caseless/LICENSE b/node_modules/@types/caseless/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/caseless/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/caseless/README.md b/node_modules/@types/caseless/README.md new file mode 100644 index 0000000..b7e6d16 --- /dev/null +++ b/node_modules/@types/caseless/README.md @@ -0,0 +1,48 @@ +# Installation +> `npm install --save @types/caseless` + +# Summary +This package contains type definitions for caseless (https://github.com/mikeal/caseless). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/caseless. +## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/caseless/index.d.ts) +````ts +type KeyType = string; +type ValueType = any; +type RawDict = object; + +declare function caseless(dict?: RawDict): caseless.Caseless; + +declare namespace caseless { + function httpify(resp: object, headers: RawDict): Caseless; + + interface Caseless { + set(name: KeyType, value: ValueType, clobber?: boolean): KeyType | false; + set(dict: RawDict): void; + has(name: KeyType): KeyType | false; + get(name: KeyType): ValueType | undefined; + swap(name: KeyType): void; + del(name: KeyType): boolean; + } + + interface Httpified { + headers: RawDict; + setHeader(name: KeyType, value: ValueType, clobber?: boolean): KeyType | false; + setHeader(dict: RawDict): void; + hasHeader(name: KeyType): KeyType | false; + getHeader(name: KeyType): ValueType | undefined; + removeHeader(name: KeyType): boolean; + } +} + +export = caseless; + +```` + +### Additional Details + * Last updated: Mon, 06 Nov 2023 22:41:05 GMT + * Dependencies: none + +# Credits +These definitions were written by [downace](https://github.com/downace), [Matt R. Wilson](https://github.com/mastermatt), and [Emily Klassen](https://github.com/forivall). diff --git a/node_modules/@types/caseless/index.d.ts b/node_modules/@types/caseless/index.d.ts new file mode 100644 index 0000000..c0fa44c --- /dev/null +++ b/node_modules/@types/caseless/index.d.ts @@ -0,0 +1,29 @@ +type KeyType = string; +type ValueType = any; +type RawDict = object; + +declare function caseless(dict?: RawDict): caseless.Caseless; + +declare namespace caseless { + function httpify(resp: object, headers: RawDict): Caseless; + + interface Caseless { + set(name: KeyType, value: ValueType, clobber?: boolean): KeyType | false; + set(dict: RawDict): void; + has(name: KeyType): KeyType | false; + get(name: KeyType): ValueType | undefined; + swap(name: KeyType): void; + del(name: KeyType): boolean; + } + + interface Httpified { + headers: RawDict; + setHeader(name: KeyType, value: ValueType, clobber?: boolean): KeyType | false; + setHeader(dict: RawDict): void; + hasHeader(name: KeyType): KeyType | false; + getHeader(name: KeyType): ValueType | undefined; + removeHeader(name: KeyType): boolean; + } +} + +export = caseless; diff --git a/node_modules/@types/caseless/package.json b/node_modules/@types/caseless/package.json new file mode 100644 index 0000000..b50c59f --- /dev/null +++ b/node_modules/@types/caseless/package.json @@ -0,0 +1,35 @@ +{ + "name": "@types/caseless", + "version": "0.12.5", + "description": "TypeScript definitions for caseless", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/caseless", + "license": "MIT", + "contributors": [ + { + "name": "downace", + "githubUsername": "downace", + "url": "https://github.com/downace" + }, + { + "name": "Matt R. Wilson", + "githubUsername": "mastermatt", + "url": "https://github.com/mastermatt" + }, + { + "name": "Emily Klassen", + "githubUsername": "forivall", + "url": "https://github.com/forivall" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/caseless" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "89139c26e367c4adc78c0db606bf3e7b208f60498430b2c167551f7169d0b81c", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/node_modules/@types/connect/LICENSE b/node_modules/@types/connect/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/connect/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/connect/README.md b/node_modules/@types/connect/README.md new file mode 100644 index 0000000..e229a83 --- /dev/null +++ b/node_modules/@types/connect/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/connect` + +# Summary +This package contains type definitions for connect (https://github.com/senchalabs/connect). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/connect. + +### Additional Details + * Last updated: Mon, 06 Nov 2023 22:41:05 GMT + * Dependencies: [@types/node](https://npmjs.com/package/@types/node) + +# Credits +These definitions were written by [Maxime LUCE](https://github.com/SomaticIT), and [Evan Hahn](https://github.com/EvanHahn). diff --git a/node_modules/@types/connect/index.d.ts b/node_modules/@types/connect/index.d.ts new file mode 100644 index 0000000..8355d78 --- /dev/null +++ b/node_modules/@types/connect/index.d.ts @@ -0,0 +1,91 @@ +/// + +import * as http from "http"; + +/** + * Create a new connect server. + */ +declare function createServer(): createServer.Server; + +declare namespace createServer { + export type ServerHandle = HandleFunction | http.Server; + + export class IncomingMessage extends http.IncomingMessage { + originalUrl?: http.IncomingMessage["url"] | undefined; + } + + type NextFunction = (err?: any) => void; + + export type SimpleHandleFunction = (req: IncomingMessage, res: http.ServerResponse) => void; + export type NextHandleFunction = (req: IncomingMessage, res: http.ServerResponse, next: NextFunction) => void; + export type ErrorHandleFunction = ( + err: any, + req: IncomingMessage, + res: http.ServerResponse, + next: NextFunction, + ) => void; + export type HandleFunction = SimpleHandleFunction | NextHandleFunction | ErrorHandleFunction; + + export interface ServerStackItem { + route: string; + handle: ServerHandle; + } + + export interface Server extends NodeJS.EventEmitter { + (req: http.IncomingMessage, res: http.ServerResponse, next?: Function): void; + + route: string; + stack: ServerStackItem[]; + + /** + * Utilize the given middleware `handle` to the given `route`, + * defaulting to _/_. This "route" is the mount-point for the + * middleware, when given a value other than _/_ the middleware + * is only effective when that segment is present in the request's + * pathname. + * + * For example if we were to mount a function at _/admin_, it would + * be invoked on _/admin_, and _/admin/settings_, however it would + * not be invoked for _/_, or _/posts_. + */ + use(fn: NextHandleFunction): Server; + use(fn: HandleFunction): Server; + use(route: string, fn: NextHandleFunction): Server; + use(route: string, fn: HandleFunction): Server; + + /** + * Handle server requests, punting them down + * the middleware stack. + */ + handle(req: http.IncomingMessage, res: http.ServerResponse, next: Function): void; + + /** + * Listen for connections. + * + * This method takes the same arguments + * as node's `http.Server#listen()`. + * + * HTTP and HTTPS: + * + * If you run your application both as HTTP + * and HTTPS you may wrap them individually, + * since your Connect "server" is really just + * a JavaScript `Function`. + * + * var connect = require('connect') + * , http = require('http') + * , https = require('https'); + * + * var app = connect(); + * + * http.createServer(app).listen(80); + * https.createServer(options, app).listen(443); + */ + listen(port: number, hostname?: string, backlog?: number, callback?: Function): http.Server; + listen(port: number, hostname?: string, callback?: Function): http.Server; + listen(path: string, callback?: Function): http.Server; + listen(handle: any, listeningListener?: Function): http.Server; + } +} + +export = createServer; diff --git a/node_modules/@types/connect/package.json b/node_modules/@types/connect/package.json new file mode 100644 index 0000000..207078e --- /dev/null +++ b/node_modules/@types/connect/package.json @@ -0,0 +1,32 @@ +{ + "name": "@types/connect", + "version": "3.4.38", + "description": "TypeScript definitions for connect", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/connect", + "license": "MIT", + "contributors": [ + { + "name": "Maxime LUCE", + "githubUsername": "SomaticIT", + "url": "https://github.com/SomaticIT" + }, + { + "name": "Evan Hahn", + "githubUsername": "EvanHahn", + "url": "https://github.com/EvanHahn" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/connect" + }, + "scripts": {}, + "dependencies": { + "@types/node": "*" + }, + "typesPublisherContentHash": "8990242237504bdec53088b79e314b94bec69286df9de56db31f22de403b4092", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/node_modules/@types/express-serve-static-core/LICENSE b/node_modules/@types/express-serve-static-core/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/express-serve-static-core/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/express-serve-static-core/README.md b/node_modules/@types/express-serve-static-core/README.md new file mode 100644 index 0000000..2d22d12 --- /dev/null +++ b/node_modules/@types/express-serve-static-core/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/express-serve-static-core` + +# Summary +This package contains type definitions for express-serve-static-core (http://expressjs.com). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/express-serve-static-core/v4. + +### Additional Details + * Last updated: Mon, 06 Oct 2025 21:02:40 GMT + * Dependencies: [@types/node](https://npmjs.com/package/@types/node), [@types/qs](https://npmjs.com/package/@types/qs), [@types/range-parser](https://npmjs.com/package/@types/range-parser), [@types/send](https://npmjs.com/package/@types/send) + +# Credits +These definitions were written by [Boris Yankov](https://github.com/borisyankov), [Satana Charuwichitratana](https://github.com/micksatana), [Jose Luis Leon](https://github.com/JoseLion), [David Stephens](https://github.com/dwrss), and [Shin Ando](https://github.com/andoshin11). diff --git a/node_modules/@types/express-serve-static-core/index.d.ts b/node_modules/@types/express-serve-static-core/index.d.ts new file mode 100644 index 0000000..9e3d250 --- /dev/null +++ b/node_modules/@types/express-serve-static-core/index.d.ts @@ -0,0 +1,1295 @@ +// This extracts the core definitions from express to prevent a circular dependency between express and serve-static +/// + +import { SendOptions } from "send"; + +declare global { + namespace Express { + // These open interfaces may be extended in an application-specific manner via declaration merging. + // See for example method-override.d.ts (https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/method-override/index.d.ts) + interface Request {} + interface Response {} + interface Locals {} + interface Application {} + } +} + +import { EventEmitter } from "events"; +import * as http from "http"; +import { ParsedQs } from "qs"; +import { Options as RangeParserOptions, Ranges as RangeParserRanges, Result as RangeParserResult } from "range-parser"; + +export {}; + +export type Query = ParsedQs; + +export interface NextFunction { + (err?: any): void; + /** + * "Break-out" of a router by calling {next('router')}; + * @see {https://expressjs.com/en/guide/using-middleware.html#middleware.router} + */ + (deferToNext: "router"): void; + /** + * "Break-out" of a route by calling {next('route')}; + * @see {https://expressjs.com/en/guide/using-middleware.html#middleware.application} + */ + (deferToNext: "route"): void; +} + +export interface Dictionary { + [key: string]: T; +} + +export interface ParamsDictionary { + [key: string]: string; +} +export type ParamsArray = string[]; +export type Params = ParamsDictionary | ParamsArray; + +export interface Locals extends Express.Locals {} + +export interface RequestHandler< + P = ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, +> { + // tslint:disable-next-line callable-types (This is extended from and can't extend from a type alias in ts<2.2) + ( + req: Request, + res: Response, + next: NextFunction, + ): void; +} + +export type ErrorRequestHandler< + P = ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, +> = ( + err: any, + req: Request, + res: Response, + next: NextFunction, +) => void; + +export type PathParams = string | RegExp | Array; + +export type RequestHandlerParams< + P = ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, +> = + | RequestHandler + | ErrorRequestHandler + | Array | ErrorRequestHandler

                          >; + +type RemoveTail = S extends `${infer P}${Tail}` ? P : S; +type GetRouteParameter = RemoveTail< + RemoveTail, `-${string}`>, + `.${string}` +>; + +// prettier-ignore +export type RouteParameters = string extends Route ? ParamsDictionary + : Route extends `${string}(${string}` ? ParamsDictionary // TODO: handling for regex parameters + : Route extends `${string}:${infer Rest}` ? + & ( + GetRouteParameter extends never ? ParamsDictionary + : GetRouteParameter extends `${infer ParamName}?` ? { [P in ParamName]?: string } + : { [P in GetRouteParameter]: string } + ) + & (Rest extends `${GetRouteParameter}${infer Next}` ? RouteParameters : unknown) + : {}; + +/* eslint-disable @definitelytyped/no-unnecessary-generics */ +export interface IRouterMatcher< + T, + Method extends "all" | "get" | "post" | "put" | "delete" | "patch" | "options" | "head" = any, +> { + < + Route extends string, + P = RouteParameters, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, + >( + // (it's used as the default type parameter for P) + path: Route, + // (This generic is meant to be passed explicitly.) + ...handlers: Array> + ): T; + < + Path extends string, + P = RouteParameters, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, + >( + // (it's used as the default type parameter for P) + path: Path, + // (This generic is meant to be passed explicitly.) + ...handlers: Array> + ): T; + < + P = ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, + >( + path: PathParams, + // (This generic is meant to be passed explicitly.) + ...handlers: Array> + ): T; + < + P = ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, + >( + path: PathParams, + // (This generic is meant to be passed explicitly.) + ...handlers: Array> + ): T; + (path: PathParams, subApplication: Application): T; +} + +export interface IRouterHandler { + (...handlers: Array>>): T; + (...handlers: Array>>): T; + < + P = RouteParameters, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, + >( + // (This generic is meant to be passed explicitly.) + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + ...handlers: Array> + ): T; + < + P = RouteParameters, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, + >( + // (This generic is meant to be passed explicitly.) + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + ...handlers: Array> + ): T; + < + P = ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, + >( + // (This generic is meant to be passed explicitly.) + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + ...handlers: Array> + ): T; + < + P = ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, + >( + // (This generic is meant to be passed explicitly.) + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + ...handlers: Array> + ): T; +} +/* eslint-enable @definitelytyped/no-unnecessary-generics */ + +export interface IRouter extends RequestHandler { + /** + * Map the given param placeholder `name`(s) to the given callback(s). + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the samesignature as middleware, the only differencing + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * next(err); + * } else if (user) { + * req.user = user; + * next(); + * } else { + * next(new Error('failed to load user')); + * } + * }); + * }); + */ + param(name: string, handler: RequestParamHandler): this; + + /** + * Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() + * + * @deprecated since version 4.11 + */ + param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; + + /** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + */ + all: IRouterMatcher; + get: IRouterMatcher; + post: IRouterMatcher; + put: IRouterMatcher; + delete: IRouterMatcher; + patch: IRouterMatcher; + options: IRouterMatcher; + head: IRouterMatcher; + + checkout: IRouterMatcher; + connect: IRouterMatcher; + copy: IRouterMatcher; + lock: IRouterMatcher; + merge: IRouterMatcher; + mkactivity: IRouterMatcher; + mkcol: IRouterMatcher; + move: IRouterMatcher; + "m-search": IRouterMatcher; + notify: IRouterMatcher; + propfind: IRouterMatcher; + proppatch: IRouterMatcher; + purge: IRouterMatcher; + report: IRouterMatcher; + search: IRouterMatcher; + subscribe: IRouterMatcher; + trace: IRouterMatcher; + unlock: IRouterMatcher; + unsubscribe: IRouterMatcher; + link: IRouterMatcher; + unlink: IRouterMatcher; + + use: IRouterHandler & IRouterMatcher; + + route(prefix: T): IRoute; + route(prefix: PathParams): IRoute; + /** + * Stack of configured routes + */ + stack: ILayer[]; +} + +export interface ILayer { + route?: IRoute; + name: string | ""; + params?: Record; + keys: string[]; + path?: string; + method: string; + regexp: RegExp; + handle: (req: Request, res: Response, next: NextFunction) => any; +} + +export interface IRoute { + path: string; + stack: ILayer[]; + all: IRouterHandler; + get: IRouterHandler; + post: IRouterHandler; + put: IRouterHandler; + delete: IRouterHandler; + patch: IRouterHandler; + options: IRouterHandler; + head: IRouterHandler; + + checkout: IRouterHandler; + copy: IRouterHandler; + lock: IRouterHandler; + merge: IRouterHandler; + mkactivity: IRouterHandler; + mkcol: IRouterHandler; + move: IRouterHandler; + "m-search": IRouterHandler; + notify: IRouterHandler; + purge: IRouterHandler; + report: IRouterHandler; + search: IRouterHandler; + subscribe: IRouterHandler; + trace: IRouterHandler; + unlock: IRouterHandler; + unsubscribe: IRouterHandler; +} + +export interface Router extends IRouter {} + +/** + * Options passed down into `res.cookie` + * @link https://expressjs.com/en/api.html#res.cookie + */ +export interface CookieOptions { + /** Convenient option for setting the expiry time relative to the current time in **milliseconds**. */ + maxAge?: number | undefined; + /** Indicates if the cookie should be signed. */ + signed?: boolean | undefined; + /** Expiry date of the cookie in GMT. If not specified or set to 0, creates a session cookie. */ + expires?: Date | undefined; + /** Flags the cookie to be accessible only by the web server. */ + httpOnly?: boolean | undefined; + /** Path for the cookie. Defaults to “/”. */ + path?: string | undefined; + /** Domain name for the cookie. Defaults to the domain name of the app. */ + domain?: string | undefined; + /** Marks the cookie to be used with HTTPS only. */ + secure?: boolean | undefined; + /** A synchronous function used for cookie value encoding. Defaults to encodeURIComponent. */ + encode?: ((val: string) => string) | undefined; + /** + * Value of the “SameSite” Set-Cookie attribute. + * @link https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1.1. + */ + sameSite?: boolean | "lax" | "strict" | "none" | undefined; + /** + * Value of the “Priority” Set-Cookie attribute. + * @link https://datatracker.ietf.org/doc/html/draft-west-cookie-priority-00#section-4.3 + */ + priority?: "low" | "medium" | "high"; + /** Marks the cookie to use partioned storage. */ + partitioned?: boolean | undefined; +} + +export interface ByteRange { + start: number; + end: number; +} + +export interface RequestRanges extends RangeParserRanges {} + +export type Errback = (err: Error) => void; + +/** + * @param P For most requests, this should be `ParamsDictionary`, but if you're + * using this in a route handler for a route that uses a `RegExp` or a wildcard + * `string` path (e.g. `'/user/*'`), then `req.params` will be an array, in + * which case you should use `ParamsArray` instead. + * + * @see https://expressjs.com/en/api.html#req.params + * + * @example + * app.get('/user/:id', (req, res) => res.send(req.params.id)); // implicitly `ParamsDictionary` + * app.get(/user\/(.*)/, (req, res) => res.send(req.params[0])); + * app.get('/user/*', (req, res) => res.send(req.params[0])); + */ +export interface Request< + P = ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, +> extends http.IncomingMessage, Express.Request { + /** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + */ + get(name: "set-cookie"): string[] | undefined; + get(name: string): string | undefined; + + header(name: "set-cookie"): string[] | undefined; + header(name: string): string | undefined; + + /** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json", a comma-delimted list such as "json, html, text/plain", + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => false + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html, json'); + * // => "json" + */ + accepts(): string[]; + accepts(type: string): string | false; + accepts(type: string[]): string | false; + accepts(...type: string[]): string | false; + + /** + * Returns the first accepted charset of the specified character sets, + * based on the request's Accept-Charset HTTP header field. + * If none of the specified charsets is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + */ + acceptsCharsets(): string[]; + acceptsCharsets(charset: string): string | false; + acceptsCharsets(charset: string[]): string | false; + acceptsCharsets(...charset: string[]): string | false; + + /** + * Returns the first accepted encoding of the specified encodings, + * based on the request's Accept-Encoding HTTP header field. + * If none of the specified encodings is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + */ + acceptsEncodings(): string[]; + acceptsEncodings(encoding: string): string | false; + acceptsEncodings(encoding: string[]): string | false; + acceptsEncodings(...encoding: string[]): string | false; + + /** + * Returns the first accepted language of the specified languages, + * based on the request's Accept-Language HTTP header field. + * If none of the specified languages is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + */ + acceptsLanguages(): string[]; + acceptsLanguages(lang: string): string | false; + acceptsLanguages(lang: string[]): string | false; + acceptsLanguages(...lang: string[]): string | false; + + /** + * Parse Range header field, capping to the given `size`. + * + * Unspecified ranges such as "0-" require knowledge of your resource length. In + * the case of a byte range this is of course the total number of bytes. + * If the Range header field is not given `undefined` is returned. + * If the Range header field is given, return value is a result of range-parser. + * See more ./types/range-parser/index.d.ts + * + * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" + * should respond with 4 users when available, not 3. + */ + range(size: number, options?: RangeParserOptions): RangeParserRanges | RangeParserResult | undefined; + + /** + * Return an array of Accepted media types + * ordered from highest quality to lowest. + */ + accepted: MediaType[]; + + /** + * @deprecated since 4.11 Use either req.params, req.body or req.query, as applicable. + * + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `connect.bodyParser()` middleware. + */ + param(name: string, defaultValue?: any): string; + + /** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + */ + is(type: string | string[]): string | false | null; + + /** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting is enabled the "X-Forwarded-Proto" header + * field will be trusted. If you're running behind + * a reverse proxy that supplies https for you this + * may be enabled. + */ + readonly protocol: string; + + /** + * Short-hand for: + * + * req.protocol == 'https' + */ + readonly secure: boolean; + + /** + * Return the remote address, or when + * "trust proxy" is `true` return + * the upstream addr. + * + * Value may be undefined if the `req.socket` is destroyed + * (for example, if the client disconnected). + */ + readonly ip: string | undefined; + + /** + * When "trust proxy" is `true`, parse + * the "X-Forwarded-For" ip address list. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream. + */ + readonly ips: string[]; + + /** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + */ + readonly subdomains: string[]; + + /** + * Short-hand for `url.parse(req.url).pathname`. + */ + readonly path: string; + + /** + * Parse the "Host" header field hostname. + */ + readonly hostname: string; + + /** + * @deprecated Use hostname instead. + */ + readonly host: string; + + /** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + */ + readonly fresh: boolean; + + /** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + */ + readonly stale: boolean; + + /** + * Check if the request was an _XMLHttpRequest_. + */ + readonly xhr: boolean; + + // body: { username: string; password: string; remember: boolean; title: string; }; + body: ReqBody; + + // cookies: { string; remember: boolean; }; + cookies: any; + + method: string; + + params: P; + + query: ReqQuery; + + route: any; + + signedCookies: any; + + originalUrl: string; + + url: string; + + baseUrl: string; + + app: Application; + + /** + * After middleware.init executed, Request will contain res and next properties + * See: express/lib/middleware/init.js + */ + res?: Response | undefined; + next?: NextFunction | undefined; +} + +export interface MediaType { + value: string; + quality: number; + type: string; + subtype: string; +} + +export type Send> = (body?: ResBody) => T; + +export interface SendFileOptions extends SendOptions { + /** Object containing HTTP headers to serve with the file. */ + headers?: Record; +} + +export interface DownloadOptions extends SendOptions { + /** Object containing HTTP headers to serve with the file. The header `Content-Disposition` will be overridden by the filename argument. */ + headers?: Record; +} + +export interface Response< + ResBody = any, + LocalsObj extends Record = Record, + StatusCode extends number = number, +> extends http.ServerResponse, Express.Response { + /** + * Set status `code`. + */ + status(code: StatusCode): this; + + /** + * Set the response HTTP status code to `statusCode` and send its string representation as the response body. + * @link http://expressjs.com/4x/api.html#res.sendStatus + * + * Examples: + * + * res.sendStatus(200); // equivalent to res.status(200).send('OK') + * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') + * res.sendStatus(404); // equivalent to res.status(404).send('Not Found') + * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error') + */ + sendStatus(code: StatusCode): this; + + /** + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + */ + links(links: any): this; + + /** + * Send a response. + * + * Examples: + * + * res.send(new Buffer('wahoo')); + * res.send({ some: 'json' }); + * res.send('

                          some html

                          '); + * res.status(404).send('Sorry, cant find that'); + */ + send: Send; + + /** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * res.status(500).json('oh noes!'); + * res.status(404).json('I dont have that'); + */ + json: Send; + + /** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * res.status(500).jsonp('oh noes!'); + * res.status(404).jsonp('I dont have that'); + */ + jsonp: Send; + + /** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `fn(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.headersSent` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @api public + */ + sendFile(path: string, fn?: Errback): void; + sendFile(path: string, options: SendFileOptions, fn?: Errback): void; + + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string): void; + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string, options: SendFileOptions): void; + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string, fn: Errback): void; + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string, options: SendFileOptions, fn: Errback): void; + + /** + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `fn(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headersSent` if you plan to respond. + * + * The optional options argument passes through to the underlying + * res.sendFile() call, and takes the exact same parameters. + * + * This method uses `res.sendfile()`. + */ + download(path: string, fn?: Errback): void; + download(path: string, filename: string, fn?: Errback): void; + download(path: string, filename: string, options: DownloadOptions, fn?: Errback): void; + + /** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + */ + contentType(type: string): this; + + /** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + */ + type(type: string): this; + + /** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

                          hey

                          '); + * }, + * + * 'appliation/json': function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * In addition to canonicalized MIME types you may + * also use extnames mapped to these types: + * + * res.format({ + * text: function(){ + * res.send('hey'); + * }, + * + * html: function(){ + * res.send('

                          hey

                          '); + * }, + * + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. + */ + format(obj: any): this; + + /** + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + */ + attachment(filename?: string): this; + + /** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + */ + set(field: any): this; + set(field: string, value?: string | string[]): this; + + header(field: any): this; + header(field: string, value?: string | string[]): this; + + // Property indicating if HTTP headers has been sent for the response. + headersSent: boolean; + + /** Get value for header `field`. */ + get(field: string): string | undefined; + + /** Clear cookie `name`. */ + clearCookie(name: string, options?: CookieOptions): this; + + /** + * Set cookie `name` to `val`, with the given `options`. + * + * Options: + * + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // save as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + */ + cookie(name: string, val: string, options: CookieOptions): this; + cookie(name: string, val: any, options: CookieOptions): this; + cookie(name: string, val: any): this; + + /** + * Set the location header to `url`. + * + * The given `url` can also be the name of a mapped url, for + * example by default express supports "back" which redirects + * to the _Referrer_ or _Referer_ headers or "/". + * + * Examples: + * + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); // /blog/post/1 -> /blog/login + * + * Mounting: + * + * When an application is mounted and `res.location()` + * is given a path that does _not_ lead with "/" it becomes + * relative to the mount-point. For example if the application + * is mounted at "/blog", the following would become "/blog/login". + * + * res.location('login'); + * + * While the leading slash would result in a location of "/login": + * + * res.location('/login'); + */ + location(url: string): this; + + /** + * Redirect to the given `url` with optional response `status` + * defaulting to 302. + * + * The resulting `url` is determined by `res.location()`, so + * it will play nicely with mounted apps, relative paths, + * `"back"` etc. + * + * Examples: + * + * res.redirect('back'); + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('http://example.com', 301); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + */ + redirect(url: string): void; + redirect(status: number, url: string): void; + /** @deprecated use res.redirect(status, url) instead */ + redirect(url: string, status: number): void; + + /** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + */ + render(view: string, options?: object, callback?: (err: Error, html: string) => void): void; + render(view: string, callback?: (err: Error, html: string) => void): void; + + locals: LocalsObj & Locals; + + charset: string; + + /** + * Adds the field to the Vary response header, if it is not there already. + * Examples: + * + * res.vary('User-Agent').render('docs'); + */ + vary(field: string): this; + + app: Application; + + /** + * Appends the specified value to the HTTP response header field. + * If the header is not already set, it creates the header with the specified value. + * The value parameter can be a string or an array. + * + * Note: calling res.set() after res.append() will reset the previously-set header value. + * + * @since 4.11.0 + */ + append(field: string, value?: string[] | string): this; + + /** + * After middleware.init executed, Response will contain req property + * See: express/lib/middleware/init.js + */ + req: Request; +} + +export interface Handler extends RequestHandler {} + +export type RequestParamHandler = (req: Request, res: Response, next: NextFunction, value: any, name: string) => any; + +export type ApplicationRequestHandler = + & IRouterHandler + & IRouterMatcher + & ((...handlers: RequestHandlerParams[]) => T); + +export interface Application< + LocalsObj extends Record = Record, +> extends EventEmitter, IRouter, Express.Application { + /** + * Express instance itself is a request handler, which could be invoked without + * third argument. + */ + (req: Request | http.IncomingMessage, res: Response | http.ServerResponse): any; + + /** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + */ + init(): void; + + /** + * Initialize application configuration. + */ + defaultConfiguration(): void; + + /** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.jade" file Express will invoke the following internally: + * + * app.engine('jade', require('jade').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/visionmedia/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + */ + engine( + ext: string, + fn: (path: string, options: object, callback: (e: any, rendered?: string) => void) => void, + ): this; + + /** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.get('foo'); + * // => "bar" + * app.set('foo', ['bar', 'baz']); + * app.get('foo'); + * // => ["bar", "baz"] + * + * Mounted servers inherit their parent server's settings. + */ + set(setting: string, val: any): this; + get: ((name: string) => any) & IRouterMatcher; + + param(name: string | string[], handler: RequestParamHandler): this; + + /** + * Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() + * + * @deprecated since version 4.11 + */ + param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; + + /** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + */ + path(): string; + + /** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + */ + enabled(setting: string): boolean; + + /** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + */ + disabled(setting: string): boolean; + + /** Enable `setting`. */ + enable(setting: string): this; + + /** Disable `setting`. */ + disable(setting: string): this; + + /** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + */ + render(name: string, options?: object, callback?: (err: Error, html: string) => void): void; + render(name: string, callback: (err: Error, html: string) => void): void; + + /** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + */ + listen(port: number, hostname: string, backlog: number, callback?: () => void): http.Server; + listen(port: number, hostname: string, callback?: () => void): http.Server; + listen(port: number, callback?: () => void): http.Server; + listen(callback?: () => void): http.Server; + listen(path: string, callback?: () => void): http.Server; + listen(handle: any, listeningListener?: () => void): http.Server; + + router: string; + + settings: any; + + resource: any; + + map: any; + + locals: LocalsObj & Locals; + + /** + * The app.routes object houses all of the routes defined mapped by the + * associated HTTP verb. This object may be used for introspection + * capabilities, for example Express uses this internally not only for + * routing but to provide default OPTIONS behaviour unless app.options() + * is used. Your application or framework may also remove routes by + * simply by removing them from this object. + */ + routes: any; + + /** + * Used to get all registered routes in Express Application + */ + _router: any; + + use: ApplicationRequestHandler; + + /** + * The mount event is fired on a sub-app, when it is mounted on a parent app. + * The parent app is passed to the callback function. + * + * NOTE: + * Sub-apps will: + * - Not inherit the value of settings that have a default value. You must set the value in the sub-app. + * - Inherit the value of settings with no default value. + */ + on: (event: "mount", callback: (parent: Application) => void) => this; + + /** + * The app.mountpath property contains one or more path patterns on which a sub-app was mounted. + */ + mountpath: string | string[]; +} + +export interface Express extends Application { + request: Request; + response: Response; +} diff --git a/node_modules/@types/express-serve-static-core/package.json b/node_modules/@types/express-serve-static-core/package.json new file mode 100644 index 0000000..127106a --- /dev/null +++ b/node_modules/@types/express-serve-static-core/package.json @@ -0,0 +1,51 @@ +{ + "name": "@types/express-serve-static-core", + "version": "4.19.7", + "description": "TypeScript definitions for express-serve-static-core", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/express-serve-static-core", + "license": "MIT", + "contributors": [ + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "Satana Charuwichitratana", + "githubUsername": "micksatana", + "url": "https://github.com/micksatana" + }, + { + "name": "Jose Luis Leon", + "githubUsername": "JoseLion", + "url": "https://github.com/JoseLion" + }, + { + "name": "David Stephens", + "githubUsername": "dwrss", + "url": "https://github.com/dwrss" + }, + { + "name": "Shin Ando", + "githubUsername": "andoshin11", + "url": "https://github.com/andoshin11" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/express-serve-static-core" + }, + "scripts": {}, + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "a4797d651510430b6b53a07eb01d86881a113b9ca00290eadb6d46d91e8cedf2", + "typeScriptVersion": "5.2" +} \ No newline at end of file diff --git a/node_modules/@types/express/LICENSE b/node_modules/@types/express/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/express/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/express/README.md b/node_modules/@types/express/README.md new file mode 100644 index 0000000..6e0e31e --- /dev/null +++ b/node_modules/@types/express/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/express` + +# Summary +This package contains type definitions for express (http://expressjs.com). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/express/v4. + +### Additional Details + * Last updated: Mon, 27 Oct 2025 20:34:59 GMT + * Dependencies: [@types/body-parser](https://npmjs.com/package/@types/body-parser), [@types/express-serve-static-core](https://npmjs.com/package/@types/express-serve-static-core), [@types/qs](https://npmjs.com/package/@types/qs), [@types/serve-static](https://npmjs.com/package/@types/serve-static) + +# Credits +These definitions were written by [Boris Yankov](https://github.com/borisyankov), [Puneet Arora](https://github.com/puneetar), [Dylan Frankland](https://github.com/dfrankland), and [Sebastian Beltran](https://github.com/bjohansebas). diff --git a/node_modules/@types/express/index.d.ts b/node_modules/@types/express/index.d.ts new file mode 100644 index 0000000..dc2934d --- /dev/null +++ b/node_modules/@types/express/index.d.ts @@ -0,0 +1,128 @@ +/* =================== USAGE =================== + + import express = require("express"); + var app = express(); + + =============================================== */ + +/// +/// + +import bodyParser = require("body-parser"); +import * as core from "express-serve-static-core"; +import * as qs from "qs"; +import serveStatic = require("serve-static"); + +/** + * Creates an Express application. The express() function is a top-level function exported by the express module. + */ +declare function e(): core.Express; + +declare namespace e { + /** + * This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser. + * @since 4.16.0 + */ + var json: typeof bodyParser.json; + + /** + * This is a built-in middleware function in Express. It parses incoming requests with Buffer payloads and is based on body-parser. + * @since 4.17.0 + */ + var raw: typeof bodyParser.raw; + + /** + * This is a built-in middleware function in Express. It parses incoming requests with text payloads and is based on body-parser. + * @since 4.17.0 + */ + var text: typeof bodyParser.text; + + /** + * These are the exposed prototypes. + */ + var application: Application; + var request: Request; + var response: Response; + + /** + * This is a built-in middleware function in Express. It serves static files and is based on serve-static. + */ + var static: serveStatic.RequestHandlerConstructor; + + /** + * This is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on body-parser. + * @since 4.16.0 + */ + var urlencoded: typeof bodyParser.urlencoded; + + /** + * This is a built-in middleware function in Express. It parses incoming request query parameters. + */ + export function query(options: qs.IParseOptions | typeof qs.parse): Handler; + + export function Router(options?: RouterOptions): core.Router; + + interface RouterOptions { + /** + * Enable case sensitivity. + */ + caseSensitive?: boolean | undefined; + + /** + * Preserve the req.params values from the parent router. + * If the parent and the child have conflicting param names, the child’s value take precedence. + * + * @default false + * @since 4.5.0 + */ + mergeParams?: boolean | undefined; + + /** + * Enable strict routing. + */ + strict?: boolean | undefined; + } + + interface Application extends core.Application {} + interface CookieOptions extends core.CookieOptions {} + interface Errback extends core.Errback {} + interface ErrorRequestHandler< + P = core.ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = core.Query, + Locals extends Record = Record, + > extends core.ErrorRequestHandler {} + interface Express extends core.Express {} + interface Handler extends core.Handler {} + interface IRoute extends core.IRoute {} + interface IRouter extends core.IRouter {} + interface IRouterHandler extends core.IRouterHandler {} + interface IRouterMatcher extends core.IRouterMatcher {} + interface MediaType extends core.MediaType {} + interface NextFunction extends core.NextFunction {} + interface Locals extends core.Locals {} + interface Request< + P = core.ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = core.Query, + Locals extends Record = Record, + > extends core.Request {} + interface RequestHandler< + P = core.ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = core.Query, + Locals extends Record = Record, + > extends core.RequestHandler {} + interface RequestParamHandler extends core.RequestParamHandler {} + interface Response< + ResBody = any, + Locals extends Record = Record, + > extends core.Response {} + interface Router extends core.Router {} + interface Send extends core.Send {} +} + +export = e; diff --git a/node_modules/@types/express/package.json b/node_modules/@types/express/package.json new file mode 100644 index 0000000..9fc06fb --- /dev/null +++ b/node_modules/@types/express/package.json @@ -0,0 +1,46 @@ +{ + "name": "@types/express", + "version": "4.17.25", + "description": "TypeScript definitions for express", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/express", + "license": "MIT", + "contributors": [ + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "Puneet Arora", + "githubUsername": "puneetar", + "url": "https://github.com/puneetar" + }, + { + "name": "Dylan Frankland", + "githubUsername": "dfrankland", + "url": "https://github.com/dfrankland" + }, + { + "name": "Sebastian Beltran", + "githubUsername": "bjohansebas", + "url": "https://github.com/bjohansebas" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/express" + }, + "scripts": {}, + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "^1" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "875cd41acf5e799aefe604cb91b2b033db9e38e44df52044870814402a054994", + "typeScriptVersion": "5.2" +} \ No newline at end of file diff --git a/node_modules/@types/http-errors/LICENSE b/node_modules/@types/http-errors/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/http-errors/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/http-errors/README.md b/node_modules/@types/http-errors/README.md new file mode 100644 index 0000000..d64e3dc --- /dev/null +++ b/node_modules/@types/http-errors/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/http-errors` + +# Summary +This package contains type definitions for http-errors (https://github.com/jshttp/http-errors). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/http-errors. + +### Additional Details + * Last updated: Sat, 07 Jun 2025 02:15:25 GMT + * Dependencies: none + +# Credits +These definitions were written by [Tanguy Krotoff](https://github.com/tkrotoff), [BendingBender](https://github.com/BendingBender), and [Sebastian Beltran](https://github.com/bjohansebas). diff --git a/node_modules/@types/http-errors/index.d.ts b/node_modules/@types/http-errors/index.d.ts new file mode 100644 index 0000000..e7fb2a8 --- /dev/null +++ b/node_modules/@types/http-errors/index.d.ts @@ -0,0 +1,77 @@ +export = createHttpError; + +declare const createHttpError: createHttpError.CreateHttpError & createHttpError.NamedConstructors & { + isHttpError: createHttpError.IsHttpError; +}; + +declare namespace createHttpError { + interface HttpError extends Error { + status: N; + statusCode: N; + expose: boolean; + headers?: { + [key: string]: string; + } | undefined; + [key: string]: any; + } + + type UnknownError = Error | string | { [key: string]: any }; + + interface HttpErrorConstructor { + (msg?: string): HttpError; + new(msg?: string): HttpError; + } + + interface CreateHttpError { + (arg: N, ...rest: UnknownError[]): HttpError; + (...rest: UnknownError[]): HttpError; + } + + type IsHttpError = (error: unknown) => error is HttpError; + + type NamedConstructors = + & { + HttpError: HttpErrorConstructor; + } + & Record<"BadRequest" | "400", HttpErrorConstructor<400>> + & Record<"Unauthorized" | "401", HttpErrorConstructor<401>> + & Record<"PaymentRequired" | "402", HttpErrorConstructor<402>> + & Record<"Forbidden" | "403", HttpErrorConstructor<403>> + & Record<"NotFound" | "404", HttpErrorConstructor<404>> + & Record<"MethodNotAllowed" | "405", HttpErrorConstructor<405>> + & Record<"NotAcceptable" | "406", HttpErrorConstructor<406>> + & Record<"ProxyAuthenticationRequired" | "407", HttpErrorConstructor<407>> + & Record<"RequestTimeout" | "408", HttpErrorConstructor<408>> + & Record<"Conflict" | "409", HttpErrorConstructor<409>> + & Record<"Gone" | "410", HttpErrorConstructor<410>> + & Record<"LengthRequired" | "411", HttpErrorConstructor<411>> + & Record<"PreconditionFailed" | "412", HttpErrorConstructor<412>> + & Record<"PayloadTooLarge" | "413", HttpErrorConstructor<413>> + & Record<"URITooLong" | "414", HttpErrorConstructor<414>> + & Record<"UnsupportedMediaType" | "415", HttpErrorConstructor<415>> + & Record<"RangeNotSatisfiable" | "416", HttpErrorConstructor<416>> + & Record<"ExpectationFailed" | "417", HttpErrorConstructor<417>> + & Record<"ImATeapot" | "418", HttpErrorConstructor<418>> + & Record<"MisdirectedRequest" | "421", HttpErrorConstructor<421>> + & Record<"UnprocessableEntity" | "422", HttpErrorConstructor<422>> + & Record<"Locked" | "423", HttpErrorConstructor<423>> + & Record<"FailedDependency" | "424", HttpErrorConstructor<424>> + & Record<"TooEarly" | "425", HttpErrorConstructor<425>> + & Record<"UpgradeRequired" | "426", HttpErrorConstructor<426>> + & Record<"PreconditionRequired" | "428", HttpErrorConstructor<428>> + & Record<"TooManyRequests" | "429", HttpErrorConstructor<429>> + & Record<"RequestHeaderFieldsTooLarge" | "431", HttpErrorConstructor<431>> + & Record<"UnavailableForLegalReasons" | "451", HttpErrorConstructor<451>> + & Record<"InternalServerError" | "500", HttpErrorConstructor<500>> + & Record<"NotImplemented" | "501", HttpErrorConstructor<501>> + & Record<"BadGateway" | "502", HttpErrorConstructor<502>> + & Record<"ServiceUnavailable" | "503", HttpErrorConstructor<503>> + & Record<"GatewayTimeout" | "504", HttpErrorConstructor<504>> + & Record<"HTTPVersionNotSupported" | "505", HttpErrorConstructor<505>> + & Record<"VariantAlsoNegotiates" | "506", HttpErrorConstructor<506>> + & Record<"InsufficientStorage" | "507", HttpErrorConstructor<507>> + & Record<"LoopDetected" | "508", HttpErrorConstructor<508>> + & Record<"BandwidthLimitExceeded" | "509", HttpErrorConstructor<509>> + & Record<"NotExtended" | "510", HttpErrorConstructor<510>> + & Record<"NetworkAuthenticationRequire" | "511", HttpErrorConstructor<511>>; +} diff --git a/node_modules/@types/http-errors/package.json b/node_modules/@types/http-errors/package.json new file mode 100644 index 0000000..91d49cf --- /dev/null +++ b/node_modules/@types/http-errors/package.json @@ -0,0 +1,36 @@ +{ + "name": "@types/http-errors", + "version": "2.0.5", + "description": "TypeScript definitions for http-errors", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/http-errors", + "license": "MIT", + "contributors": [ + { + "name": "Tanguy Krotoff", + "githubUsername": "tkrotoff", + "url": "https://github.com/tkrotoff" + }, + { + "name": "BendingBender", + "githubUsername": "BendingBender", + "url": "https://github.com/BendingBender" + }, + { + "name": "Sebastian Beltran", + "githubUsername": "bjohansebas", + "url": "https://github.com/bjohansebas" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/http-errors" + }, + "scripts": {}, + "dependencies": {}, + "peerDependencies": {}, + "typesPublisherContentHash": "621b9125a6493a2fa928b9150e335cb57429fb00e3bc0257426f1173903f7a4a", + "typeScriptVersion": "5.1" +} \ No newline at end of file diff --git a/node_modules/@types/jsonwebtoken/LICENSE b/node_modules/@types/jsonwebtoken/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/jsonwebtoken/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/jsonwebtoken/README.md b/node_modules/@types/jsonwebtoken/README.md new file mode 100644 index 0000000..79dea4d --- /dev/null +++ b/node_modules/@types/jsonwebtoken/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/jsonwebtoken` + +# Summary +This package contains type definitions for jsonwebtoken (https://github.com/auth0/node-jsonwebtoken). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jsonwebtoken. + +### Additional Details + * Last updated: Mon, 16 Jun 2025 07:35:37 GMT + * Dependencies: [@types/ms](https://npmjs.com/package/@types/ms), [@types/node](https://npmjs.com/package/@types/node) + +# Credits +These definitions were written by [Maxime LUCE](https://github.com/SomaticIT), [Daniel Heim](https://github.com/danielheim), [Brice BERNARD](https://github.com/brikou), [Veli-Pekka Kestilä](https://github.com/vpk), [Daniel Parker](https://github.com/GeneralistDev), [Kjell Dießel](https://github.com/kettil), [Robert Gajda](https://github.com/RunAge), [Nico Flaig](https://github.com/nflaig), [Linus Unnebäck](https://github.com/LinusU), [Ivan Sieder](https://github.com/ivansieder), [Piotr Błażejewicz](https://github.com/peterblazejewicz), and [Nandor Kraszlan](https://github.com/nandi95). diff --git a/node_modules/@types/jsonwebtoken/index.d.ts b/node_modules/@types/jsonwebtoken/index.d.ts new file mode 100644 index 0000000..accb78c --- /dev/null +++ b/node_modules/@types/jsonwebtoken/index.d.ts @@ -0,0 +1,271 @@ +/// + +import type { createPrivateKey, createPublicKey, KeyObject } from "crypto"; +import type { StringValue } from "ms"; + +export class JsonWebTokenError extends Error { + inner: Error; + + constructor(message: string, error?: Error); +} + +export class TokenExpiredError extends JsonWebTokenError { + expiredAt: Date; + + constructor(message: string, expiredAt: Date); +} + +/** + * Thrown if current time is before the nbf claim. + */ +export class NotBeforeError extends JsonWebTokenError { + date: Date; + + constructor(message: string, date: Date); +} + +export interface SignOptions { + /** + * Signature algorithm. Could be one of these values : + * - HS256: HMAC using SHA-256 hash algorithm (default) + * - HS384: HMAC using SHA-384 hash algorithm + * - HS512: HMAC using SHA-512 hash algorithm + * - RS256: RSASSA using SHA-256 hash algorithm + * - RS384: RSASSA using SHA-384 hash algorithm + * - RS512: RSASSA using SHA-512 hash algorithm + * - ES256: ECDSA using P-256 curve and SHA-256 hash algorithm + * - ES384: ECDSA using P-384 curve and SHA-384 hash algorithm + * - ES512: ECDSA using P-521 curve and SHA-512 hash algorithm + * - none: No digital signature or MAC value included + */ + algorithm?: Algorithm | undefined; + keyid?: string | undefined; + expiresIn?: StringValue | number; + notBefore?: StringValue | number | undefined; + audience?: string | string[] | undefined; + subject?: string | undefined; + issuer?: string | undefined; + jwtid?: string | undefined; + mutatePayload?: boolean | undefined; + noTimestamp?: boolean | undefined; + header?: JwtHeader | undefined; + encoding?: string | undefined; + allowInsecureKeySizes?: boolean | undefined; + allowInvalidAsymmetricKeyTypes?: boolean | undefined; +} + +export interface VerifyOptions { + algorithms?: Algorithm[] | undefined; + audience?: string | RegExp | [string | RegExp, ...(string | RegExp)[]] | undefined; + clockTimestamp?: number | undefined; + clockTolerance?: number | undefined; + /** return an object with the decoded `{ payload, header, signature }` instead of only the usual content of the payload. */ + complete?: boolean | undefined; + issuer?: string | [string, ...(string[])] | undefined; + ignoreExpiration?: boolean | undefined; + ignoreNotBefore?: boolean | undefined; + jwtid?: string | undefined; + /** + * If you want to check `nonce` claim, provide a string value here. + * It is used on Open ID for the ID Tokens. ([Open ID implementation notes](https://openid.net/specs/openid-connect-core-1_0.html#NonceNotes)) + */ + nonce?: string | undefined; + subject?: string | undefined; + maxAge?: string | number | undefined; + allowInvalidAsymmetricKeyTypes?: boolean | undefined; +} + +export interface DecodeOptions { + complete?: boolean | undefined; + json?: boolean | undefined; +} +export type VerifyErrors = + | JsonWebTokenError + | NotBeforeError + | TokenExpiredError; +export type VerifyCallback = ( + error: VerifyErrors | null, + decoded?: T | undefined, +) => void; + +export type SignCallback = ( + error: Error | null, + encoded?: string | undefined, +) => void; + +// standard names https://www.rfc-editor.org/rfc/rfc7515.html#section-4.1 +export interface JwtHeader { + alg: string | Algorithm; + typ?: string | undefined; + cty?: string | undefined; + crit?: Array> | undefined; + kid?: string | undefined; + jku?: string | undefined; + x5u?: string | string[] | undefined; + "x5t#S256"?: string | undefined; + x5t?: string | undefined; + x5c?: string | string[] | undefined; +} + +// standard claims https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 +export interface JwtPayload { + [key: string]: any; + iss?: string | undefined; + sub?: string | undefined; + aud?: string | string[] | undefined; + exp?: number | undefined; + nbf?: number | undefined; + iat?: number | undefined; + jti?: string | undefined; +} + +export interface Jwt { + header: JwtHeader; + payload: JwtPayload | string; + signature: string; +} + +// https://github.com/auth0/node-jsonwebtoken#algorithms-supported +export type Algorithm = + | "HS256" + | "HS384" + | "HS512" + | "RS256" + | "RS384" + | "RS512" + | "ES256" + | "ES384" + | "ES512" + | "PS256" + | "PS384" + | "PS512" + | "none"; + +export type SigningKeyCallback = ( + error: Error | null, + signingKey?: Secret | PublicKey, +) => void; + +export type GetPublicKeyOrSecret = ( + header: JwtHeader, + callback: SigningKeyCallback, +) => void; + +export type PublicKey = Parameters[0]; + +export type PrivateKey = Parameters[0]; + +export type Secret = + | string + | Buffer + | KeyObject + | { key: string | Buffer; passphrase: string }; + +/** + * Synchronously sign the given payload into a JSON Web Token string + * payload - Payload to sign, could be an literal, buffer or string + * secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. + * [options] - Options for the signature + * returns - The JSON Web Token string + */ +export function sign( + payload: string | Buffer | object, + secretOrPrivateKey: Secret | PrivateKey, + options?: SignOptions, +): string; +export function sign( + payload: string | Buffer | object, + secretOrPrivateKey: null, + options?: SignOptions & { algorithm: "none" }, +): string; + +/** + * Sign the given payload into a JSON Web Token string + * payload - Payload to sign, could be an literal, buffer or string + * secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. + * [options] - Options for the signature + * callback - Callback to get the encoded token on + */ +export function sign( + payload: string | Buffer | object, + secretOrPrivateKey: Secret | PrivateKey, + callback: SignCallback, +): void; +export function sign( + payload: string | Buffer | object, + secretOrPrivateKey: Secret | PrivateKey, + options: SignOptions, + callback: SignCallback, +): void; +export function sign( + payload: string | Buffer | object, + secretOrPrivateKey: null, + options: SignOptions & { algorithm: "none" }, + callback: SignCallback, +): void; + +/** + * Synchronously verify given token using a secret or a public key to get a decoded token + * token - JWT string to verify + * secretOrPublicKey - Either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. + * [options] - Options for the verification + * returns - The decoded token. + */ +export function verify( + token: string, + secretOrPublicKey: Secret | PublicKey, + options: VerifyOptions & { complete: true }, +): Jwt; +export function verify( + token: string, + secretOrPublicKey: Secret | PublicKey, + options?: VerifyOptions & { complete?: false }, +): JwtPayload | string; +export function verify( + token: string, + secretOrPublicKey: Secret | PublicKey, + options?: VerifyOptions, +): Jwt | JwtPayload | string; + +/** + * Asynchronously verify given token using a secret or a public key to get a decoded token + * token - JWT string to verify + * secretOrPublicKey - A string or buffer containing either the secret for HMAC algorithms, + * or the PEM encoded public key for RSA and ECDSA. If jwt.verify is called asynchronous, + * secretOrPublicKey can be a function that should fetch the secret or public key + * [options] - Options for the verification + * callback - Callback to get the decoded token on + */ +export function verify( + token: string, + secretOrPublicKey: Secret | PublicKey | GetPublicKeyOrSecret, + callback?: VerifyCallback, +): void; +export function verify( + token: string, + secretOrPublicKey: Secret | PublicKey | GetPublicKeyOrSecret, + options: VerifyOptions & { complete: true }, + callback?: VerifyCallback, +): void; +export function verify( + token: string, + secretOrPublicKey: Secret | PublicKey | GetPublicKeyOrSecret, + options?: VerifyOptions & { complete?: false }, + callback?: VerifyCallback, +): void; +export function verify( + token: string, + secretOrPublicKey: Secret | PublicKey | GetPublicKeyOrSecret, + options?: VerifyOptions, + callback?: VerifyCallback, +): void; + +/** + * Returns the decoded payload without verifying if the signature is valid. + * token - JWT string to decode + * [options] - Options for decoding + * returns - The decoded Token + */ +export function decode(token: string, options: DecodeOptions & { complete: true }): null | Jwt; +export function decode(token: string, options: DecodeOptions & { json: true }): null | JwtPayload; +export function decode(token: string, options?: DecodeOptions): null | JwtPayload | string; diff --git a/node_modules/@types/jsonwebtoken/package.json b/node_modules/@types/jsonwebtoken/package.json new file mode 100644 index 0000000..cd5f33d --- /dev/null +++ b/node_modules/@types/jsonwebtoken/package.json @@ -0,0 +1,84 @@ +{ + "name": "@types/jsonwebtoken", + "version": "9.0.10", + "description": "TypeScript definitions for jsonwebtoken", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jsonwebtoken", + "license": "MIT", + "contributors": [ + { + "name": "Maxime LUCE", + "githubUsername": "SomaticIT", + "url": "https://github.com/SomaticIT" + }, + { + "name": "Daniel Heim", + "githubUsername": "danielheim", + "url": "https://github.com/danielheim" + }, + { + "name": "Brice BERNARD", + "githubUsername": "brikou", + "url": "https://github.com/brikou" + }, + { + "name": "Veli-Pekka Kestilä", + "githubUsername": "vpk", + "url": "https://github.com/vpk" + }, + { + "name": "Daniel Parker", + "githubUsername": "GeneralistDev", + "url": "https://github.com/GeneralistDev" + }, + { + "name": "Kjell Dießel", + "githubUsername": "kettil", + "url": "https://github.com/kettil" + }, + { + "name": "Robert Gajda", + "githubUsername": "RunAge", + "url": "https://github.com/RunAge" + }, + { + "name": "Nico Flaig", + "githubUsername": "nflaig", + "url": "https://github.com/nflaig" + }, + { + "name": "Linus Unnebäck", + "githubUsername": "LinusU", + "url": "https://github.com/LinusU" + }, + { + "name": "Ivan Sieder", + "githubUsername": "ivansieder", + "url": "https://github.com/ivansieder" + }, + { + "name": "Piotr Błażejewicz", + "githubUsername": "peterblazejewicz", + "url": "https://github.com/peterblazejewicz" + }, + { + "name": "Nandor Kraszlan", + "githubUsername": "nandi95", + "url": "https://github.com/nandi95" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/jsonwebtoken" + }, + "scripts": {}, + "dependencies": { + "@types/ms": "*", + "@types/node": "*" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "d51483f13412c41d8e77e914b45268c47b0cde11c20fa17f2dee720012292dca", + "typeScriptVersion": "5.1" +} \ No newline at end of file diff --git a/node_modules/@types/long/LICENSE b/node_modules/@types/long/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/long/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/long/README.md b/node_modules/@types/long/README.md new file mode 100644 index 0000000..78faab2 --- /dev/null +++ b/node_modules/@types/long/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/long` + +# Summary +This package contains type definitions for long.js (https://github.com/dcodeIO/long.js). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/long. + +### Additional Details + * Last updated: Tue, 26 Apr 2022 19:31:52 GMT + * Dependencies: none + * Global values: `Long` + +# Credits +These definitions were written by [Peter Kooijmans](https://github.com/peterkooijmans). diff --git a/node_modules/@types/long/index.d.ts b/node_modules/@types/long/index.d.ts new file mode 100644 index 0000000..3a95005 --- /dev/null +++ b/node_modules/@types/long/index.d.ts @@ -0,0 +1,389 @@ +// Type definitions for long.js 4.0.0 +// Project: https://github.com/dcodeIO/long.js +// Definitions by: Peter Kooijmans +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Definitions by: Denis Cappellin + +export = Long; +export as namespace Long; + +declare const Long: Long.LongConstructor; +type Long = Long.Long; +declare namespace Long { + interface LongConstructor { + /** + * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as signed integers. See the from* functions below for more convenient ways of constructing Longs. + */ + new( low: number, high?: number, unsigned?: boolean ): Long; + prototype: Long; + /** + * Maximum unsigned value. + */ + MAX_UNSIGNED_VALUE: Long; + + /** + * Maximum signed value. + */ + MAX_VALUE: Long; + + /** + * Minimum signed value. + */ + MIN_VALUE: Long; + + /** + * Signed negative one. + */ + NEG_ONE: Long; + + /** + * Signed one. + */ + ONE: Long; + + /** + * Unsigned one. + */ + UONE: Long; + + /** + * Unsigned zero. + */ + UZERO: Long; + + /** + * Signed zero + */ + ZERO: Long; + + /** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is assumed to use 32 bits. + */ + fromBits( lowBits:number, highBits:number, unsigned?:boolean ): Long; + + /** + * Returns a Long representing the given 32 bit integer value. + */ + fromInt( value: number, unsigned?: boolean ): Long; + + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + */ + fromNumber( value: number, unsigned?: boolean ): Long; + + /** + * Returns a Long representation of the given string, written using the specified radix. + */ + fromString( str: string, unsigned?: boolean | number, radix?: number ): Long; + + /** + * Creates a Long from its byte representation. + */ + fromBytes( bytes: number[], unsigned?: boolean, le?: boolean ): Long; + + /** + * Creates a Long from its little endian byte representation. + */ + fromBytesLE( bytes: number[], unsigned?: boolean ): Long; + + /** + * Creates a Long from its little endian byte representation. + */ + fromBytesBE( bytes: number[], unsigned?: boolean ): Long; + + /** + * Tests if the specified object is a Long. + */ + isLong( obj: any ): obj is Long; + + /** + * Converts the specified value to a Long. + */ + fromValue( val: Long | number | string | {low: number, high: number, unsigned: boolean}, unsigned?: boolean ): Long; + } + interface Long + { + /** + * The high 32 bits as a signed value. + */ + high: number; + + /** + * The low 32 bits as a signed value. + */ + low: number; + + /** + * Whether unsigned or not. + */ + unsigned: boolean; + + /** + * Returns the sum of this and the specified Long. + */ + add( addend: number | Long | string ): Long; + + /** + * Returns the bitwise AND of this Long and the specified. + */ + and( other: Long | number | string ): Long; + + /** + * Compares this Long's value with the specified's. + */ + compare( other: Long | number | string ): number; + + /** + * Compares this Long's value with the specified's. + */ + comp( other: Long | number | string ): number; + + /** + * Returns this Long divided by the specified. + */ + divide( divisor: Long | number | string ): Long; + + /** + * Returns this Long divided by the specified. + */ + div( divisor: Long | number | string ): Long; + + /** + * Tests if this Long's value equals the specified's. + */ + equals( other: Long | number | string ): boolean; + + /** + * Tests if this Long's value equals the specified's. + */ + eq( other: Long | number | string ): boolean; + + /** + * Gets the high 32 bits as a signed integer. + */ + getHighBits(): number; + + /** + * Gets the high 32 bits as an unsigned integer. + */ + getHighBitsUnsigned(): number; + + /** + * Gets the low 32 bits as a signed integer. + */ + getLowBits(): number; + + /** + * Gets the low 32 bits as an unsigned integer. + */ + getLowBitsUnsigned(): number; + + /** + * Gets the number of bits needed to represent the absolute value of this Long. + */ + getNumBitsAbs(): number; + + /** + * Tests if this Long's value is greater than the specified's. + */ + greaterThan( other: Long | number | string ): boolean; + + /** + * Tests if this Long's value is greater than the specified's. + */ + gt( other: Long | number | string ): boolean; + + /** + * Tests if this Long's value is greater than or equal the specified's. + */ + greaterThanOrEqual( other: Long | number | string ): boolean; + + /** + * Tests if this Long's value is greater than or equal the specified's. + */ + gte( other: Long | number | string ): boolean; + + /** + * Tests if this Long's value is even. + */ + isEven(): boolean; + + /** + * Tests if this Long's value is negative. + */ + isNegative(): boolean; + + /** + * Tests if this Long's value is odd. + */ + isOdd(): boolean; + + /** + * Tests if this Long's value is positive. + */ + isPositive(): boolean; + + /** + * Tests if this Long's value equals zero. + */ + isZero(): boolean; + + /** + * Tests if this Long's value is less than the specified's. + */ + lessThan( other: Long | number | string ): boolean; + + /** + * Tests if this Long's value is less than the specified's. + */ + lt( other: Long | number | string ): boolean; + + /** + * Tests if this Long's value is less than or equal the specified's. + */ + lessThanOrEqual( other: Long | number | string ): boolean; + + /** + * Tests if this Long's value is less than or equal the specified's. + */ + lte( other: Long | number | string ): boolean; + + /** + * Returns this Long modulo the specified. + */ + modulo( other: Long | number | string ): Long; + + /** + * Returns this Long modulo the specified. + */ + mod( other: Long | number | string ): Long; + + /** + * Returns the product of this and the specified Long. + */ + multiply( multiplier: Long | number | string ): Long; + + /** + * Returns the product of this and the specified Long. + */ + mul( multiplier: Long | number | string ): Long; + + /** + * Negates this Long's value. + */ + negate(): Long; + + /** + * Negates this Long's value. + */ + neg(): Long; + + /** + * Returns the bitwise NOT of this Long. + */ + not(): Long; + + /** + * Tests if this Long's value differs from the specified's. + */ + notEquals( other: Long | number | string ): boolean; + + /** + * Tests if this Long's value differs from the specified's. + */ + neq( other: Long | number | string ): boolean; + + /** + * Returns the bitwise OR of this Long and the specified. + */ + or( other: Long | number | string ): Long; + + /** + * Returns this Long with bits shifted to the left by the given amount. + */ + shiftLeft( numBits: number | Long ): Long; + + /** + * Returns this Long with bits shifted to the left by the given amount. + */ + shl( numBits: number | Long ): Long; + + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + */ + shiftRight( numBits: number | Long ): Long; + + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + */ + shr( numBits: number | Long ): Long; + + /** + * Returns this Long with bits logically shifted to the right by the given amount. + */ + shiftRightUnsigned( numBits: number | Long ): Long; + + /** + * Returns this Long with bits logically shifted to the right by the given amount. + */ + shru( numBits: number | Long ): Long; + + /** + * Returns the difference of this and the specified Long. + */ + subtract( subtrahend: number | Long | string ): Long; + + /** + * Returns the difference of this and the specified Long. + */ + sub( subtrahend: number | Long |string ): Long; + + /** + * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. + */ + toInt(): number; + + /** + * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). + */ + toNumber(): number; + + /** + * Converts this Long to its byte representation. + */ + + toBytes( le?: boolean ): number[]; + + /** + * Converts this Long to its little endian byte representation. + */ + + toBytesLE(): number[]; + + /** + * Converts this Long to its big endian byte representation. + */ + + toBytesBE(): number[]; + + /** + * Converts this Long to signed. + */ + toSigned(): Long; + + /** + * Converts the Long to a string written in the specified radix. + */ + toString( radix?: number ): string; + + /** + * Converts this Long to unsigned. + */ + toUnsigned(): Long; + + /** + * Returns the bitwise XOR of this Long and the given one. + */ + xor( other: Long | number | string ): Long; + } +} diff --git a/node_modules/@types/long/package.json b/node_modules/@types/long/package.json new file mode 100644 index 0000000..35b1e75 --- /dev/null +++ b/node_modules/@types/long/package.json @@ -0,0 +1,25 @@ +{ + "name": "@types/long", + "version": "4.0.2", + "description": "TypeScript definitions for long.js", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/long", + "license": "MIT", + "contributors": [ + { + "name": "Peter Kooijmans", + "url": "https://github.com/peterkooijmans", + "githubUsername": "peterkooijmans" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/long" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "ce51a9fcaeb3f15cee5396e1c4f4b5ca2986a066f9bbe885a51dcdc6dbb22fd5", + "typeScriptVersion": "3.9" +} \ No newline at end of file diff --git a/node_modules/@types/mime/LICENSE b/node_modules/@types/mime/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/mime/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/mime/Mime.d.ts b/node_modules/@types/mime/Mime.d.ts new file mode 100644 index 0000000..a516bd4 --- /dev/null +++ b/node_modules/@types/mime/Mime.d.ts @@ -0,0 +1,10 @@ +import { TypeMap } from "./index"; + +export default class Mime { + constructor(mimes: TypeMap); + + lookup(path: string, fallback?: string): string; + extension(mime: string): string | undefined; + load(filepath: string): void; + define(mimes: TypeMap): void; +} diff --git a/node_modules/@types/mime/README.md b/node_modules/@types/mime/README.md new file mode 100644 index 0000000..ab21c24 --- /dev/null +++ b/node_modules/@types/mime/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/mime` + +# Summary +This package contains type definitions for mime (https://github.com/broofa/node-mime). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mime/v1. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 20:08:00 GMT + * Dependencies: none + +# Credits +These definitions were written by [Jeff Goddard](https://github.com/jedigo), and [Daniel Hritzkiv](https://github.com/dhritzkiv). diff --git a/node_modules/@types/mime/index.d.ts b/node_modules/@types/mime/index.d.ts new file mode 100644 index 0000000..93e8259 --- /dev/null +++ b/node_modules/@types/mime/index.d.ts @@ -0,0 +1,31 @@ +// Originally imported from: https://github.com/soywiz/typescript-node-definitions/mime.d.ts + +export as namespace mime; + +export interface TypeMap { + [key: string]: string[]; +} + +/** + * Look up a mime type based on extension. + * + * If not found, uses the fallback argument if provided, and otherwise + * uses `default_type`. + */ +export function lookup(path: string, fallback?: string): string; +/** + * Return a file extensions associated with a mime type. + */ +export function extension(mime: string): string | undefined; +/** + * Load an Apache2-style ".types" file. + */ +export function load(filepath: string): void; +export function define(mimes: TypeMap): void; + +export interface Charsets { + lookup(mime: string, fallback: string): string; +} + +export const charsets: Charsets; +export const default_type: string; diff --git a/node_modules/@types/mime/lite.d.ts b/node_modules/@types/mime/lite.d.ts new file mode 100644 index 0000000..ffebaec --- /dev/null +++ b/node_modules/@types/mime/lite.d.ts @@ -0,0 +1,7 @@ +import { default as Mime } from "./Mime"; + +declare const mimelite: Mime; + +export as namespace mimelite; + +export = mimelite; diff --git a/node_modules/@types/mime/package.json b/node_modules/@types/mime/package.json new file mode 100644 index 0000000..98a29ff --- /dev/null +++ b/node_modules/@types/mime/package.json @@ -0,0 +1,30 @@ +{ + "name": "@types/mime", + "version": "1.3.5", + "description": "TypeScript definitions for mime", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mime", + "license": "MIT", + "contributors": [ + { + "name": "Jeff Goddard", + "githubUsername": "jedigo", + "url": "https://github.com/jedigo" + }, + { + "name": "Daniel Hritzkiv", + "githubUsername": "dhritzkiv", + "url": "https://github.com/dhritzkiv" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/mime" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "2ad7ee9a549e6721825e733c6a1a7e8bee0ca7ba93d9ab922c8f4558def52d77", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/node_modules/@types/ms/LICENSE b/node_modules/@types/ms/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/ms/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/ms/README.md b/node_modules/@types/ms/README.md new file mode 100644 index 0000000..8b7446f --- /dev/null +++ b/node_modules/@types/ms/README.md @@ -0,0 +1,82 @@ +# Installation +> `npm install --save @types/ms` + +# Summary +This package contains type definitions for ms (https://github.com/vercel/ms). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/ms. +## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/ms/index.d.ts) +````ts +/** + * Short/Long format for `value`. + * + * @param {Number} value + * @param {{long: boolean}} options + * @return {String} + */ +declare function ms(value: number, options?: { long: boolean }): string; + +/** + * Parse the given `value` and return milliseconds. + * + * @param {ms.StringValue} value + * @return {Number} + */ +declare function ms(value: ms.StringValue): number; + +declare namespace ms { + // Unit, UnitAnyCase, and StringValue are backported from ms@3 + // https://github.com/vercel/ms/blob/8b5923d1d86c84a9f6aba8022d416dcf2361aa8d/src/index.ts + + type Unit = + | "Years" + | "Year" + | "Yrs" + | "Yr" + | "Y" + | "Weeks" + | "Week" + | "W" + | "Days" + | "Day" + | "D" + | "Hours" + | "Hour" + | "Hrs" + | "Hr" + | "H" + | "Minutes" + | "Minute" + | "Mins" + | "Min" + | "M" + | "Seconds" + | "Second" + | "Secs" + | "Sec" + | "s" + | "Milliseconds" + | "Millisecond" + | "Msecs" + | "Msec" + | "Ms"; + + type UnitAnyCase = Unit | Uppercase | Lowercase; + + type StringValue = + | `${number}` + | `${number}${UnitAnyCase}` + | `${number} ${UnitAnyCase}`; +} + +export = ms; + +```` + +### Additional Details + * Last updated: Thu, 16 Jan 2025 21:02:45 GMT + * Dependencies: none + +# Credits +These definitions were written by [Zhiyuan Wang](https://github.com/danny8002). diff --git a/node_modules/@types/ms/index.d.ts b/node_modules/@types/ms/index.d.ts new file mode 100644 index 0000000..b1b1f51 --- /dev/null +++ b/node_modules/@types/ms/index.d.ts @@ -0,0 +1,63 @@ +/** + * Short/Long format for `value`. + * + * @param {Number} value + * @param {{long: boolean}} options + * @return {String} + */ +declare function ms(value: number, options?: { long: boolean }): string; + +/** + * Parse the given `value` and return milliseconds. + * + * @param {ms.StringValue} value + * @return {Number} + */ +declare function ms(value: ms.StringValue): number; + +declare namespace ms { + // Unit, UnitAnyCase, and StringValue are backported from ms@3 + // https://github.com/vercel/ms/blob/8b5923d1d86c84a9f6aba8022d416dcf2361aa8d/src/index.ts + + type Unit = + | "Years" + | "Year" + | "Yrs" + | "Yr" + | "Y" + | "Weeks" + | "Week" + | "W" + | "Days" + | "Day" + | "D" + | "Hours" + | "Hour" + | "Hrs" + | "Hr" + | "H" + | "Minutes" + | "Minute" + | "Mins" + | "Min" + | "M" + | "Seconds" + | "Second" + | "Secs" + | "Sec" + | "s" + | "Milliseconds" + | "Millisecond" + | "Msecs" + | "Msec" + | "Ms"; + + type UnitAnyCase = Unit | Uppercase | Lowercase; + + type StringValue = + | `${number}` + | `${number}${UnitAnyCase}` + | `${number} ${UnitAnyCase}`; +} + +export = ms; diff --git a/node_modules/@types/ms/package.json b/node_modules/@types/ms/package.json new file mode 100644 index 0000000..0f547d0 --- /dev/null +++ b/node_modules/@types/ms/package.json @@ -0,0 +1,26 @@ +{ + "name": "@types/ms", + "version": "2.1.0", + "description": "TypeScript definitions for ms", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/ms", + "license": "MIT", + "contributors": [ + { + "name": "Zhiyuan Wang", + "githubUsername": "danny8002", + "url": "https://github.com/danny8002" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/ms" + }, + "scripts": {}, + "dependencies": {}, + "peerDependencies": {}, + "typesPublisherContentHash": "2c8651ce1714fdc6bcbc0f262c93a790f1d127fb1c2dc8edbb583decef56fd39", + "typeScriptVersion": "5.0" +} \ No newline at end of file diff --git a/node_modules/@types/node/LICENSE b/node_modules/@types/node/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/node/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/node/README.md b/node_modules/@types/node/README.md new file mode 100644 index 0000000..49848f4 --- /dev/null +++ b/node_modules/@types/node/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for node (https://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node/v22. + +### Additional Details + * Last updated: Mon, 08 Dec 2025 22:36:14 GMT + * Dependencies: [undici-types](https://npmjs.com/package/undici-types) + +# Credits +These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [Alberto Schiabel](https://github.com/jkomyno), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [David Junger](https://github.com/touffy), [Mohsen Azimi](https://github.com/mohsen1), [Nikita Galkin](https://github.com/galkin), [Sebastian Silbermann](https://github.com/eps1lon), [Wilco Bakker](https://github.com/WilcoBakker), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), [Dmitry Semigradsky](https://github.com/Semigradsky), and [René](https://github.com/Renegade334). diff --git a/node_modules/@types/node/assert.d.ts b/node_modules/@types/node/assert.d.ts new file mode 100644 index 0000000..330d860 --- /dev/null +++ b/node_modules/@types/node/assert.d.ts @@ -0,0 +1,1078 @@ +/** + * The `node:assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/assert.js) + */ +declare module "assert" { + import strict = require("assert/strict"); + /** + * An alias of {@link assert.ok}. + * @since v0.5.9 + * @param value The input that is checked for being truthy. + */ + function assert(value: unknown, message?: string | Error): asserts value; + const kOptions: unique symbol; + namespace assert { + type AssertMethodNames = + | "deepEqual" + | "deepStrictEqual" + | "doesNotMatch" + | "doesNotReject" + | "doesNotThrow" + | "equal" + | "fail" + | "ifError" + | "match" + | "notDeepEqual" + | "notDeepStrictEqual" + | "notEqual" + | "notStrictEqual" + | "ok" + | "partialDeepStrictEqual" + | "rejects" + | "strictEqual" + | "throws"; + interface AssertOptions { + /** + * If set to `'full'`, shows the full diff in assertion errors. + * @default 'simple' + */ + diff?: "simple" | "full" | undefined; + /** + * If set to `true`, non-strict methods behave like their + * corresponding strict methods. + * @default true + */ + strict?: boolean | undefined; + } + interface Assert extends Pick { + readonly [kOptions]: AssertOptions & { strict: false }; + } + interface AssertStrict extends Pick { + readonly [kOptions]: AssertOptions & { strict: true }; + } + /** + * The `Assert` class allows creating independent assertion instances with custom options. + * @since v22.19.0 + */ + var Assert: { + /** + * Creates a new assertion instance. The `diff` option controls the verbosity of diffs in assertion error messages. + * + * ```js + * const { Assert } = require('node:assert'); + * const assertInstance = new Assert({ diff: 'full' }); + * assertInstance.deepStrictEqual({ a: 1 }, { a: 2 }); + * // Shows a full diff in the error message. + * ``` + * + * **Important**: When destructuring assertion methods from an `Assert` instance, + * the methods lose their connection to the instance's configuration options (such as `diff` and `strict` settings). + * The destructured methods will fall back to default behavior instead. + * + * ```js + * const myAssert = new Assert({ diff: 'full' }); + * + * // This works as expected - uses 'full' diff + * myAssert.strictEqual({ a: 1 }, { b: { c: 1 } }); + * + * // This loses the 'full' diff setting - falls back to default 'simple' diff + * const { strictEqual } = myAssert; + * strictEqual({ a: 1 }, { b: { c: 1 } }); + * ``` + * + * When destructured, methods lose access to the instance's `this` context and revert to default assertion behavior + * (diff: 'simple', non-strict mode). + * To maintain custom options when using destructured methods, avoid + * destructuring and call methods directly on the instance. + * @since v22.19.0 + */ + new( + options?: AssertOptions & { strict?: true }, + ): AssertStrict; + new( + options: AssertOptions, + ): Assert; + }; + interface AssertionErrorOptions { + /** + * If provided, the error message is set to this value. + */ + message?: string | undefined; + /** + * The `actual` property on the error instance. + */ + actual?: unknown; + /** + * The `expected` property on the error instance. + */ + expected?: unknown; + /** + * The `operator` property on the error instance. + */ + operator?: string | undefined; + /** + * If provided, the generated stack trace omits frames before this function. + */ + stackStartFn?: Function | undefined; + /** + * If set to `'full'`, shows the full diff in assertion errors. + * @default 'simple' + */ + diff?: "simple" | "full" | undefined; + } + /** + * Indicates the failure of an assertion. All errors thrown by the `node:assert` module will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + constructor(options: AssertionErrorOptions); + /** + * Set to the `actual` argument for methods such as {@link assert.strictEqual()}. + */ + actual: unknown; + /** + * Set to the `expected` argument for methods such as {@link assert.strictEqual()}. + */ + expected: unknown; + /** + * Indicates if the message was auto-generated (`true`) or not. + */ + generatedMessage: boolean; + /** + * Value is always `ERR_ASSERTION` to show that the error is an assertion error. + */ + code: "ERR_ASSERTION"; + /** + * Set to the passed in operator value. + */ + operator: string; + } + /** + * This feature is deprecated and will be removed in a future version. + * Please consider using alternatives such as the `mock` helper function. + * @since v14.2.0, v12.19.0 + * @deprecated Deprecated + */ + class CallTracker { + /** + * The wrapper function is expected to be called exactly `exact` times. If the + * function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an + * error. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func); + * ``` + * @since v14.2.0, v12.19.0 + * @param [fn='A no-op function'] + * @param [exact=1] + * @return A function that wraps `fn`. + */ + calls(exact?: number): () => void; + calls any>(fn?: Func, exact?: number): Func; + /** + * Example: + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * callsfunc(1, 2, 3); + * + * assert.deepStrictEqual(tracker.getCalls(callsfunc), + * [{ thisArg: undefined, arguments: [1, 2, 3] }]); + * ``` + * @since v18.8.0, v16.18.0 + * @return An array with all the calls to a tracked function. + */ + getCalls(fn: Function): CallTrackerCall[]; + /** + * The arrays contains information about the expected and actual number of calls of + * the functions that have not been called the expected number of times. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * // Returns an array containing information on callsfunc() + * console.log(tracker.report()); + * // [ + * // { + * // message: 'Expected the func function to be executed 2 time(s) but was + * // executed 0 time(s).', + * // actual: 0, + * // expected: 2, + * // operator: 'func', + * // stack: stack trace + * // } + * // ] + * ``` + * @since v14.2.0, v12.19.0 + * @return An array of objects containing information about the wrapper functions returned by {@link tracker.calls()}. + */ + report(): CallTrackerReportInformation[]; + /** + * Reset calls of the call tracker. If a tracked function is passed as an argument, the calls will be reset for it. + * If no arguments are passed, all tracked functions will be reset. + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * + * callsfunc(); + * // Tracker was called once + * assert.strictEqual(tracker.getCalls(callsfunc).length, 1); + * + * tracker.reset(callsfunc); + * assert.strictEqual(tracker.getCalls(callsfunc).length, 0); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn a tracked function to reset. + */ + reset(fn?: Function): void; + /** + * Iterates through the list of functions passed to {@link tracker.calls()} and will throw an error for functions that + * have not been called the expected number of times. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * callsfunc(); + * + * // Will throw an error since callsfunc() was only called once. + * tracker.verify(); + * ``` + * @since v14.2.0, v12.19.0 + */ + verify(): void; + } + interface CallTrackerCall { + thisArg: object; + arguments: unknown[]; + } + interface CallTrackerReportInformation { + message: string; + /** The actual number of times the function was called. */ + actual: number; + /** The number of times the function was expected to be called. */ + expected: number; + /** The name of the function that is wrapped. */ + operator: string; + /** A stack trace of the function. */ + stack: object; + } + type AssertPredicate = RegExp | (new() => object) | ((thrown: unknown) => boolean) | object | Error; + /** + * Throws an `AssertionError` with the provided error message or a default + * error message. If the `message` parameter is an instance of an `Error` then + * it will be thrown instead of the `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.fail(); + * // AssertionError [ERR_ASSERTION]: Failed + * + * assert.fail('boom'); + * // AssertionError [ERR_ASSERTION]: boom + * + * assert.fail(new TypeError('need array')); + * // TypeError: need array + * ``` + * + * Using `assert.fail()` with more than two arguments is possible but deprecated. + * See below for further details. + * @since v0.1.21 + * @param [message='Failed'] + */ + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: unknown, + expected: unknown, + message?: string | Error, + operator?: string, + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + stackStartFn?: Function, + ): never; + /** + * Tests if `value` is truthy. It is equivalent to `assert.equal(!!value, true, message)`. + * + * If `value` is not truthy, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is `undefined`, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. + * + * Be aware that in the `repl` the error message will be different to the one + * thrown in a file! See below for further details. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ok(true); + * // OK + * assert.ok(1); + * // OK + * + * assert.ok(); + * // AssertionError: No value argument passed to `assert.ok()` + * + * assert.ok(false, 'it\'s false'); + * // AssertionError: it's false + * + * // In the repl: + * assert.ok(typeof 123 === 'string'); + * // AssertionError: false == true + * + * // In a file (e.g. test.js): + * assert.ok(typeof 123 === 'string'); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(typeof 123 === 'string') + * + * assert.ok(false); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(false) + * + * assert.ok(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(0) + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * // Using `assert()` works the same: + * assert(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert(0) + * ``` + * @since v0.1.21 + */ + function ok(value: unknown, message?: string | Error): asserts value; + /** + * **Strict assertion mode** + * + * An alias of {@link strictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link strictEqual} instead. + * + * Tests shallow, coercive equality between the `actual` and `expected` parameters + * using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled + * and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.equal(1, 1); + * // OK, 1 == 1 + * assert.equal(1, '1'); + * // OK, 1 == '1' + * assert.equal(NaN, NaN); + * // OK + * + * assert.equal(1, 2); + * // AssertionError: 1 == 2 + * assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); + * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } + * ``` + * + * If the values are not equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v0.1.21 + */ + function equal(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. + * + * Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is + * specially handled and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.notEqual(1, 2); + * // OK + * + * assert.notEqual(1, 1); + * // AssertionError: 1 != 1 + * + * assert.notEqual(1, '1'); + * // AssertionError: 1 != '1' + * ``` + * + * If the values are equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default error + * message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v0.1.21 + */ + function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link deepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. + * + * Tests for deep equality between the `actual` and `expected` parameters. Consider + * using {@link deepStrictEqual} instead. {@link deepEqual} can have + * surprising results. + * + * _Deep equality_ means that the enumerable "own" properties of child objects + * are also recursively evaluated by the following rules. + * @since v0.1.21 + */ + function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notDeepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. + * + * Tests for any deep inequality. Opposite of {@link deepEqual}. + * + * ```js + * import assert from 'node:assert'; + * + * const obj1 = { + * a: { + * b: 1, + * }, + * }; + * const obj2 = { + * a: { + * b: 2, + * }, + * }; + * const obj3 = { + * a: { + * b: 1, + * }, + * }; + * const obj4 = { __proto__: obj1 }; + * + * assert.notDeepEqual(obj1, obj1); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj2); + * // OK + * + * assert.notDeepEqual(obj1, obj3); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj4); + * // OK + * ``` + * + * If the values are deeply equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests strict equality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.strictEqual(1, 2); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + * // 1 !== 2 + * + * assert.strictEqual(1, 1); + * // OK + * + * assert.strictEqual('Hello foobar', 'Hello World!'); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + actual - expected + * // + * // + 'Hello foobar' + * // - 'Hello World!' + * // ^ + * + * const apples = 1; + * const oranges = 2; + * assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); + * // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 + * + * assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); + * // TypeError: Inputs are not identical + * ``` + * + * If the values are not strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a + * default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function strictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests strict inequality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notStrictEqual(1, 2); + * // OK + * + * assert.notStrictEqual(1, 1); + * // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: + * // + * // 1 + * + * assert.notStrictEqual(1, '1'); + * // OK + * ``` + * + * If the values are strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a + * default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests for deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. + * @since v1.2.0 + */ + function deepStrictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); + * // OK + * ``` + * + * If the values are deeply and strictly equal, an `AssertionError` is thrown + * with a `message` property set equal to the value of the `message` parameter. If + * the `message` parameter is undefined, a default error message is assigned. If + * the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v1.2.0 + */ + function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Expects the function `fn` to throw an error. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * a validation object where each property will be tested for strict deep equality, + * or an instance of error where each property will be tested for strict deep + * equality including the non-enumerable `message` and `name` properties. When + * using an object, it is also possible to use a regular expression, when + * validating against a string property. See below for examples. + * + * If specified, `message` will be appended to the message provided by the `AssertionError` if the `fn` call fails to throw or in case the error validation + * fails. + * + * Custom validation object/error instance: + * + * ```js + * import assert from 'node:assert/strict'; + * + * const err = new TypeError('Wrong value'); + * err.code = 404; + * err.foo = 'bar'; + * err.info = { + * nested: true, + * baz: 'text', + * }; + * err.reg = /abc/i; + * + * assert.throws( + * () => { + * throw err; + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * info: { + * nested: true, + * baz: 'text', + * }, + * // Only properties on the validation object will be tested for. + * // Using nested objects requires all properties to be present. Otherwise + * // the validation is going to fail. + * }, + * ); + * + * // Using regular expressions to validate error properties: + * assert.throws( + * () => { + * throw err; + * }, + * { + * // The `name` and `message` properties are strings and using regular + * // expressions on those will match against the string. If they fail, an + * // error is thrown. + * name: /^TypeError$/, + * message: /Wrong/, + * foo: 'bar', + * info: { + * nested: true, + * // It is not possible to use regular expressions for nested properties! + * baz: 'text', + * }, + * // The `reg` property contains a regular expression and only if the + * // validation object contains an identical regular expression, it is going + * // to pass. + * reg: /abc/i, + * }, + * ); + * + * // Fails due to the different `message` and `name` properties: + * assert.throws( + * () => { + * const otherErr = new Error('Not found'); + * // Copy all enumerable properties from `err` to `otherErr`. + * for (const [key, value] of Object.entries(err)) { + * otherErr[key] = value; + * } + * throw otherErr; + * }, + * // The error's `message` and `name` properties will also be checked when using + * // an error as validation object. + * err, + * ); + * ``` + * + * Validate instanceof using constructor: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * Error, + * ); + * ``` + * + * Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): + * + * Using a regular expression runs `.toString` on the error object, and will + * therefore also include the error name. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * /^Error: Wrong value$/, + * ); + * ``` + * + * Custom error validation: + * + * The function must return `true` to indicate all internal validations passed. + * It will otherwise fail with an `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * (err) => { + * assert(err instanceof Error); + * assert(/value/.test(err)); + * // Avoid returning anything from validation functions besides `true`. + * // Otherwise, it's not clear what part of the validation failed. Instead, + * // throw an error about the specific validation that failed (as done in this + * // example) and add as much helpful debugging information to that error as + * // possible. + * return true; + * }, + * 'unexpected error', + * ); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Using the same + * message as the thrown error message is going to result in an `ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using + * a string as the second argument gets considered: + * + * ```js + * import assert from 'node:assert/strict'; + * + * function throwingFirst() { + * throw new Error('First'); + * } + * + * function throwingSecond() { + * throw new Error('Second'); + * } + * + * function notThrowing() {} + * + * // The second argument is a string and the input function threw an Error. + * // The first case will not throw as it does not match for the error message + * // thrown by the input function! + * assert.throws(throwingFirst, 'Second'); + * // In the next example the message has no benefit over the message from the + * // error and since it is not clear if the user intended to actually match + * // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. + * assert.throws(throwingSecond, 'Second'); + * // TypeError [ERR_AMBIGUOUS_ARGUMENT] + * + * // The string is only used (as message) in case the function does not throw: + * assert.throws(notThrowing, 'Second'); + * // AssertionError [ERR_ASSERTION]: Missing expected exception: Second + * + * // If it was intended to match for the error message do this instead: + * // It does not throw because the error messages match. + * assert.throws(throwingSecond, /Second$/); + * + * // If the error message does not match, an AssertionError is thrown. + * assert.throws(throwingFirst, /Second$/); + * // AssertionError [ERR_ASSERTION] + * ``` + * + * Due to the confusing error-prone notation, avoid a string as the second + * argument. + * @since v0.1.21 + */ + function throws(block: () => unknown, message?: string | Error): void; + function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Asserts that the function `fn` does not throw an error. + * + * Using `assert.doesNotThrow()` is actually not useful because there + * is no benefit in catching an error and then rethrowing it. Instead, consider + * adding a comment next to the specific code path that should not throw and keep + * error messages as expressive as possible. + * + * When `assert.doesNotThrow()` is called, it will immediately call the `fn` function. + * + * If an error is thrown and it is the same type as that specified by the `error` parameter, then an `AssertionError` is thrown. If the error is of a + * different type, or if the `error` parameter is undefined, the error is + * propagated back to the caller. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * The following, for instance, will throw the `TypeError` because there is no + * matching error type in the assertion: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * However, the following will result in an `AssertionError` with the message + * 'Got unwanted exception...': + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * TypeError, + * ); + * ``` + * + * If an `AssertionError` is thrown and a value is provided for the `message` parameter, the value of `message` will be appended to the `AssertionError` message: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * /Wrong value/, + * 'Whoops', + * ); + * // Throws: AssertionError: Got unwanted exception: Whoops + * ``` + * @since v0.1.21 + */ + function doesNotThrow(block: () => unknown, message?: string | Error): void; + function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Throws `value` if `value` is not `undefined` or `null`. This is useful when + * testing the `error` argument in callbacks. The stack trace contains all frames + * from the error passed to `ifError()` including the potential new frames for `ifError()` itself. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ifError(null); + * // OK + * assert.ifError(0); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 + * assert.ifError('error'); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' + * assert.ifError(new Error()); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error + * + * // Create some random error frames. + * let err; + * (function errorFrame() { + * err = new Error('test error'); + * })(); + * + * (function ifErrorFrame() { + * assert.ifError(err); + * })(); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error + * // at ifErrorFrame + * // at errorFrame + * ``` + * @since v0.1.97 + */ + function ifError(value: unknown): asserts value is null | undefined; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is rejected. + * + * If `asyncFn` is a function and it throws an error synchronously, `assert.rejects()` will return a rejected `Promise` with that error. If the + * function does not return a promise, `assert.rejects()` will return a rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v22.x/api/errors.html#err_invalid_return_value) + * error. In both cases the error handler is skipped. + * + * Besides the async nature to await the completion behaves identically to {@link throws}. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * an object where each property will be tested for, or an instance of error where + * each property will be tested for including the non-enumerable `message` and `name` properties. + * + * If specified, `message` will be the message provided by the `{@link AssertionError}` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * (err) => { + * assert.strictEqual(err.name, 'TypeError'); + * assert.strictEqual(err.message, 'Wrong value'); + * return true; + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.rejects( + * Promise.reject(new Error('Wrong value')), + * Error, + * ).then(() => { + * // ... + * }); + * ``` + * + * `error` cannot be a string. If a string is provided as the second argument, then `error` is assumed to + * be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Please read the + * example in {@link throws} carefully if using a string as the second argument gets considered. + * @since v10.0.0 + */ + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is not rejected. + * + * If `asyncFn` is a function and it throws an error synchronously, `assert.doesNotReject()` will return a rejected `Promise` with that error. If + * the function does not return a promise, `assert.doesNotReject()` will return a + * rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v22.x/api/errors.html#err_invalid_return_value) error. In both cases + * the error handler is skipped. + * + * Using `assert.doesNotReject()` is actually not useful because there is little + * benefit in catching a rejection and then rejecting it again. Instead, consider + * adding a comment next to the specific code path that should not reject and keep + * error messages as expressive as possible. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) + * .then(() => { + * // ... + * }); + * ``` + * @since v10.0.0 + */ + function doesNotReject( + block: (() => Promise) | Promise, + message?: string | Error, + ): Promise; + function doesNotReject( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Expects the `string` input to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.match('I will fail', /pass/); + * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... + * + * assert.match(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.match('I will pass', /pass/); + * // OK + * ``` + * + * If the values do not match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an [Error](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. + * @since v13.6.0, v12.16.0 + */ + function match(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Expects the `string` input not to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotMatch('I will fail', /fail/); + * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... + * + * assert.doesNotMatch(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.doesNotMatch('I will pass', /different/); + * // OK + * ``` + * + * If the values do match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an [Error](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. + * @since v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Tests for partial deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. "Partial" equality means + * that only properties that exist on the `expected` parameter are going to be + * compared. + * + * This method always passes the same test cases as `assert.deepStrictEqual()`, + * behaving as a super set of it. + * @since v22.13.0 + */ + function partialDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + } + namespace assert { + export { strict }; + } + export = assert; +} +declare module "node:assert" { + import assert = require("assert"); + export = assert; +} diff --git a/node_modules/@types/node/assert/strict.d.ts b/node_modules/@types/node/assert/strict.d.ts new file mode 100644 index 0000000..83ce1fe --- /dev/null +++ b/node_modules/@types/node/assert/strict.d.ts @@ -0,0 +1,111 @@ +/** + * In strict assertion mode, non-strict methods behave like their corresponding + * strict methods. For example, `assert.deepEqual()` will behave like + * `assert.deepStrictEqual()`. + * + * In strict assertion mode, error messages for objects display a diff. In legacy + * assertion mode, error messages for objects display the objects, often truncated. + * + * To use strict assertion mode: + * + * ```js + * import { strict as assert } from 'node:assert'; + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * ``` + * + * Example error diff: + * + * ```js + * import { strict as assert } from 'node:assert'; + * + * assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]); + * // AssertionError: Expected inputs to be strictly deep-equal: + * // + actual - expected ... Lines skipped + * // + * // [ + * // [ + * // ... + * // 2, + * // + 3 + * // - '3' + * // ], + * // ... + * // 5 + * // ] + * ``` + * + * To deactivate the colors, use the `NO_COLOR` or `NODE_DISABLE_COLORS` + * environment variables. This will also deactivate the colors in the REPL. For + * more on color support in terminal environments, read the tty + * [`getColorDepth()`](https://nodejs.org/docs/latest-v22.x/api/tty.html#writestreamgetcolordepthenv) documentation. + * @since v15.0.0 + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/assert/strict.js) + */ +declare module "assert/strict" { + import { + Assert, + AssertionError, + AssertionErrorOptions, + AssertOptions, + AssertPredicate, + AssertStrict, + CallTracker, + CallTrackerCall, + CallTrackerReportInformation, + deepStrictEqual, + doesNotMatch, + doesNotReject, + doesNotThrow, + fail, + ifError, + match, + notDeepStrictEqual, + notStrictEqual, + ok, + partialDeepStrictEqual, + rejects, + strictEqual, + throws, + } from "node:assert"; + function strict(value: unknown, message?: string | Error): asserts value; + namespace strict { + export { + Assert, + AssertionError, + AssertionErrorOptions, + AssertOptions, + AssertPredicate, + AssertStrict, + CallTracker, + CallTrackerCall, + CallTrackerReportInformation, + deepStrictEqual, + deepStrictEqual as deepEqual, + doesNotMatch, + doesNotReject, + doesNotThrow, + fail, + ifError, + match, + notDeepStrictEqual, + notDeepStrictEqual as notDeepEqual, + notStrictEqual, + notStrictEqual as notEqual, + ok, + partialDeepStrictEqual, + rejects, + strict, + strictEqual, + strictEqual as equal, + throws, + }; + } + export = strict; +} +declare module "node:assert/strict" { + import strict = require("assert/strict"); + export = strict; +} diff --git a/node_modules/@types/node/async_hooks.d.ts b/node_modules/@types/node/async_hooks.d.ts new file mode 100644 index 0000000..01d21d4 --- /dev/null +++ b/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,603 @@ +/** + * We strongly discourage the use of the `async_hooks` API. + * Other APIs that can cover most of its use cases include: + * + * * [`AsyncLocalStorage`](https://nodejs.org/docs/latest-v22.x/api/async_context.html#class-asynclocalstorage) tracks async context + * * [`process.getActiveResourcesInfo()`](https://nodejs.org/docs/latest-v22.x/api/process.html#processgetactiveresourcesinfo) tracks active resources + * + * The `node:async_hooks` module provides an API to track asynchronous resources. + * It can be accessed using: + * + * ```js + * import async_hooks from 'node:async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/async_hooks.js) + */ +declare module "async_hooks" { + /** + * ```js + * import { executionAsyncId } from 'node:async_hooks'; + * import fs from 'node:fs'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * const path = '.'; + * fs.open(path, 'r', (err, fd) => { + * console.log(executionAsyncId()); // 6 - open() + * }); + * ``` + * + * The ID returned from `executionAsyncId()` is related to execution timing, not + * causality (which is covered by `triggerAsyncId()`): + * + * ```js + * const server = net.createServer((conn) => { + * // Returns the ID of the server, not of the new connection, because the + * // callback runs in the execution scope of the server's MakeCallback(). + * async_hooks.executionAsyncId(); + * + * }).listen(port, () => { + * // Returns the ID of a TickObject (process.nextTick()) because all + * // callbacks passed to .listen() are wrapped in a nextTick(). + * async_hooks.executionAsyncId(); + * }); + * ``` + * + * Promise contexts may not get precise `executionAsyncIds` by default. + * See the section on [promise execution tracking](https://nodejs.org/docs/latest-v22.x/api/async_hooks.html#promise-execution-tracking). + * @since v8.1.0 + * @return The `asyncId` of the current execution context. Useful to track when something calls. + */ + function executionAsyncId(): number; + /** + * Resource objects returned by `executionAsyncResource()` are most often internal + * Node.js handle objects with undocumented APIs. Using any functions or properties + * on the object is likely to crash your application and should be avoided. + * + * Using `executionAsyncResource()` in the top-level execution context will + * return an empty object as there is no handle or request object to use, + * but having an object representing the top-level can be helpful. + * + * ```js + * import { open } from 'node:fs'; + * import { executionAsyncId, executionAsyncResource } from 'node:async_hooks'; + * + * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} + * open(new URL(import.meta.url), 'r', (err, fd) => { + * console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap + * }); + * ``` + * + * This can be used to implement continuation local storage without the + * use of a tracking `Map` to store the metadata: + * + * ```js + * import { createServer } from 'node:http'; + * import { + * executionAsyncId, + * executionAsyncResource, + * createHook, + * } from 'node:async_hooks'; + * const sym = Symbol('state'); // Private symbol to avoid pollution + * + * createHook({ + * init(asyncId, type, triggerAsyncId, resource) { + * const cr = executionAsyncResource(); + * if (cr) { + * resource[sym] = cr[sym]; + * } + * }, + * }).enable(); + * + * const server = createServer((req, res) => { + * executionAsyncResource()[sym] = { state: req.url }; + * setTimeout(function() { + * res.end(JSON.stringify(executionAsyncResource()[sym])); + * }, 100); + * }).listen(3000); + * ``` + * @since v13.9.0, v12.17.0 + * @return The resource representing the current execution. Useful to store data within the resource. + */ + function executionAsyncResource(): object; + /** + * ```js + * const server = net.createServer((conn) => { + * // The resource that caused (or triggered) this callback to be called + * // was that of the new connection. Thus the return value of triggerAsyncId() + * // is the asyncId of "conn". + * async_hooks.triggerAsyncId(); + * + * }).listen(port, () => { + * // Even though all callbacks passed to .listen() are wrapped in a nextTick() + * // the callback itself exists because the call to the server's .listen() + * // was made. So the return value would be the ID of the server. + * async_hooks.triggerAsyncId(); + * }); + * ``` + * + * Promise contexts may not get valid `triggerAsyncId`s by default. See + * the section on [promise execution tracking](https://nodejs.org/docs/latest-v22.x/api/async_hooks.html#promise-execution-tracking). + * @return The ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId A unique ID for the async resource + * @param type The type of the async resource + * @param triggerAsyncId The unique ID of the async resource in whose execution context this async resource was created + * @param resource Reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + /** + * Called immediately after the callback specified in `before` is completed. + * + * If an uncaught exception occurs during execution of the callback, then `after` will run after the `'uncaughtException'` event is emitted or a `domain`'s handler runs. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + /** + * Registers functions to be called for different lifetime events of each async + * operation. + * + * The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the + * respective asynchronous event during a resource's lifetime. + * + * All callbacks are optional. For example, if only resource cleanup needs to + * be tracked, then only the `destroy` callback needs to be passed. The + * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. + * + * ```js + * import { createHook } from 'node:async_hooks'; + * + * const asyncHook = createHook({ + * init(asyncId, type, triggerAsyncId, resource) { }, + * destroy(asyncId) { }, + * }); + * ``` + * + * The callbacks will be inherited via the prototype chain: + * + * ```js + * class MyAsyncCallbacks { + * init(asyncId, type, triggerAsyncId, resource) { } + * destroy(asyncId) {} + * } + * + * class MyAddedCallbacks extends MyAsyncCallbacks { + * before(asyncId) { } + * after(asyncId) { } + * } + * + * const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); + * ``` + * + * Because promises are asynchronous resources whose lifecycle is tracked + * via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. + * @since v8.1.0 + * @param callbacks The `Hook Callbacks` to register + * @return Instance used for disabling and enabling hooks + */ + function createHook(callbacks: HookCallbacks): AsyncHook; + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * @default executionAsyncId() + */ + triggerAsyncId?: number | undefined; + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * @default false + */ + requireManualDestroy?: boolean | undefined; + } + /** + * The class `AsyncResource` is designed to be extended by the embedder's async + * resources. Using this, users can easily trigger the lifetime events of their + * own resources. + * + * The `init` hook will trigger when an `AsyncResource` is instantiated. + * + * The following is an overview of the `AsyncResource` API. + * + * ```js + * import { AsyncResource, executionAsyncId } from 'node:async_hooks'; + * + * // AsyncResource() is meant to be extended. Instantiating a + * // new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * // async_hook.executionAsyncId() is used. + * const asyncResource = new AsyncResource( + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }, + * ); + * + * // Run a function in the execution context of the resource. This will + * // * establish the context of the resource + * // * trigger the AsyncHooks before callbacks + * // * call the provided function `fn` with the supplied arguments + * // * trigger the AsyncHooks after callbacks + * // * restore the original execution context + * asyncResource.runInAsyncScope(fn, thisArg, ...args); + * + * // Call AsyncHooks destroy callbacks. + * asyncResource.emitDestroy(); + * + * // Return the unique ID assigned to the AsyncResource instance. + * asyncResource.asyncId(); + * + * // Return the trigger ID for the AsyncResource instance. + * asyncResource.triggerAsyncId(); + * ``` + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since v9.3.0) + */ + constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); + /** + * Binds the given function to the current execution context. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current execution context. + * @param type An optional name to associate with the underlying `AsyncResource`. + */ + static bind any, ThisArg>( + fn: Func, + type?: string, + thisArg?: ThisArg, + ): Func; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>(fn: Func): Func; + /** + * Call the provided function with the provided arguments in the execution context + * of the async resource. This will establish the context, trigger the AsyncHooks + * before callbacks, call the function, trigger the AsyncHooks after callbacks, and + * then restore the original execution context. + * @since v9.6.0 + * @param fn The function to call in the execution context of this async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope( + fn: (this: This, ...args: any[]) => Result, + thisArg?: This, + ...args: any[] + ): Result; + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + * @return A reference to `asyncResource`. + */ + emitDestroy(): this; + /** + * @return The unique `asyncId` assigned to the resource. + */ + asyncId(): number; + /** + * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. + */ + triggerAsyncId(): number; + } + /** + * This class creates stores that stay coherent through asynchronous operations. + * + * While you can create your own implementation on top of the `node:async_hooks` module, `AsyncLocalStorage` should be preferred as it is a performant and memory + * safe implementation that involves significant optimizations that are non-obvious + * to implement. + * + * The following example uses `AsyncLocalStorage` to build a simple logger + * that assigns IDs to incoming HTTP requests and includes them in messages + * logged within each request. + * + * ```js + * import http from 'node:http'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const asyncLocalStorage = new AsyncLocalStorage(); + * + * function logWithId(msg) { + * const id = asyncLocalStorage.getStore(); + * console.log(`${id !== undefined ? id : '-'}:`, msg); + * } + * + * let idSeq = 0; + * http.createServer((req, res) => { + * asyncLocalStorage.run(idSeq++, () => { + * logWithId('start'); + * // Imagine any chain of async operations here + * setImmediate(() => { + * logWithId('finish'); + * res.end(); + * }); + * }); + * }).listen(8080); + * + * http.get('http://localhost:8080'); + * http.get('http://localhost:8080'); + * // Prints: + * // 0: start + * // 0: finish + * // 1: start + * // 1: finish + * ``` + * + * Each instance of `AsyncLocalStorage` maintains an independent storage context. + * Multiple instances can safely exist simultaneously without risk of interfering + * with each other's data. + * @since v13.10.0, v12.17.0 + */ + class AsyncLocalStorage { + /** + * Binds the given function to the current execution context. + * @since v19.8.0 + * @param fn The function to bind to the current execution context. + * @return A new function that calls `fn` within the captured execution context. + */ + static bind any>(fn: Func): Func; + /** + * Captures the current execution context and returns a function that accepts a + * function as an argument. Whenever the returned function is called, it + * calls the function passed to it within the captured context. + * + * ```js + * const asyncLocalStorage = new AsyncLocalStorage(); + * const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot()); + * const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); + * console.log(result); // returns 123 + * ``` + * + * AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple + * async context tracking purposes, for example: + * + * ```js + * class Foo { + * #runInAsyncScope = AsyncLocalStorage.snapshot(); + * + * get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } + * } + * + * const foo = asyncLocalStorage.run(123, () => new Foo()); + * console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 + * ``` + * @since v19.8.0 + * @return A new function with the signature `(fn: (...args) : R, ...args) : R`. + */ + static snapshot(): (fn: (...args: TArgs) => R, ...args: TArgs) => R; + /** + * Disables the instance of `AsyncLocalStorage`. All subsequent calls + * to `asyncLocalStorage.getStore()` will return `undefined` until `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. + * + * When calling `asyncLocalStorage.disable()`, all current contexts linked to the + * instance will be exited. + * + * Calling `asyncLocalStorage.disable()` is required before the `asyncLocalStorage` can be garbage collected. This does not apply to stores + * provided by the `asyncLocalStorage`, as those objects are garbage collected + * along with the corresponding async resources. + * + * Use this method when the `asyncLocalStorage` is not in use anymore + * in the current process. + * @since v13.10.0, v12.17.0 + * @experimental + */ + disable(): void; + /** + * Returns the current store. + * If called outside of an asynchronous context initialized by + * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it + * returns `undefined`. + * @since v13.10.0, v12.17.0 + */ + getStore(): T | undefined; + /** + * Runs a function synchronously within a context and returns its + * return value. The store is not accessible outside of the callback function. + * The store is accessible to any asynchronous operations created within the + * callback. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `run()` too. + * The stacktrace is not impacted by this call and the context is exited. + * + * Example: + * + * ```js + * const store = { id: 2 }; + * try { + * asyncLocalStorage.run(store, () => { + * asyncLocalStorage.getStore(); // Returns the store object + * setTimeout(() => { + * asyncLocalStorage.getStore(); // Returns the store object + * }, 200); + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns undefined + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + */ + run(store: T, callback: () => R): R; + run(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Runs a function synchronously outside of a context and returns its + * return value. The store is not accessible within the callback function or + * the asynchronous operations created within the callback. Any `getStore()` call done within the callback function will always return `undefined`. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `exit()` too. + * The stacktrace is not impacted by this call and the context is re-entered. + * + * Example: + * + * ```js + * // Within a call to run + * try { + * asyncLocalStorage.getStore(); // Returns the store object or value + * asyncLocalStorage.exit(() => { + * asyncLocalStorage.getStore(); // Returns undefined + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns the same object or value + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + * @experimental + */ + exit(callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Transitions into the context for the remainder of the current + * synchronous execution and then persists the store through any following + * asynchronous calls. + * + * Example: + * + * ```js + * const store = { id: 1 }; + * // Replaces previous store with the given store object + * asyncLocalStorage.enterWith(store); + * asyncLocalStorage.getStore(); // Returns the store object + * someAsyncOperation(() => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * ``` + * + * This transition will continue for the _entire_ synchronous execution. + * This means that if, for example, the context is entered within an event + * handler subsequent event handlers will also run within that context unless + * specifically bound to another context with an `AsyncResource`. That is why `run()` should be preferred over `enterWith()` unless there are strong reasons + * to use the latter method. + * + * ```js + * const store = { id: 1 }; + * + * emitter.on('my-event', () => { + * asyncLocalStorage.enterWith(store); + * }); + * emitter.on('my-event', () => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * + * asyncLocalStorage.getStore(); // Returns undefined + * emitter.emit('my-event'); + * asyncLocalStorage.getStore(); // Returns the same object + * ``` + * @since v13.11.0, v12.17.0 + * @experimental + */ + enterWith(store: T): void; + } + /** + * @since v17.2.0, v16.14.0 + * @return A map of provider types to the corresponding numeric id. + * This map contains all the event types that might be emitted by the `async_hooks.init()` event. + */ + namespace asyncWrapProviders { + const NONE: number; + const DIRHANDLE: number; + const DNSCHANNEL: number; + const ELDHISTOGRAM: number; + const FILEHANDLE: number; + const FILEHANDLECLOSEREQ: number; + const FIXEDSIZEBLOBCOPY: number; + const FSEVENTWRAP: number; + const FSREQCALLBACK: number; + const FSREQPROMISE: number; + const GETADDRINFOREQWRAP: number; + const GETNAMEINFOREQWRAP: number; + const HEAPSNAPSHOT: number; + const HTTP2SESSION: number; + const HTTP2STREAM: number; + const HTTP2PING: number; + const HTTP2SETTINGS: number; + const HTTPINCOMINGMESSAGE: number; + const HTTPCLIENTREQUEST: number; + const JSSTREAM: number; + const JSUDPWRAP: number; + const MESSAGEPORT: number; + const PIPECONNECTWRAP: number; + const PIPESERVERWRAP: number; + const PIPEWRAP: number; + const PROCESSWRAP: number; + const PROMISE: number; + const QUERYWRAP: number; + const SHUTDOWNWRAP: number; + const SIGNALWRAP: number; + const STATWATCHER: number; + const STREAMPIPE: number; + const TCPCONNECTWRAP: number; + const TCPSERVERWRAP: number; + const TCPWRAP: number; + const TTYWRAP: number; + const UDPSENDWRAP: number; + const UDPWRAP: number; + const SIGINTWATCHDOG: number; + const WORKER: number; + const WORKERHEAPSNAPSHOT: number; + const WRITEWRAP: number; + const ZLIB: number; + const CHECKPRIMEREQUEST: number; + const PBKDF2REQUEST: number; + const KEYPAIRGENREQUEST: number; + const KEYGENREQUEST: number; + const KEYEXPORTREQUEST: number; + const CIPHERREQUEST: number; + const DERIVEBITSREQUEST: number; + const HASHREQUEST: number; + const RANDOMBYTESREQUEST: number; + const RANDOMPRIMEREQUEST: number; + const SCRYPTREQUEST: number; + const SIGNREQUEST: number; + const TLSWRAP: number; + const VERIFYREQUEST: number; + } +} +declare module "node:async_hooks" { + export * from "async_hooks"; +} diff --git a/node_modules/@types/node/buffer.buffer.d.ts b/node_modules/@types/node/buffer.buffer.d.ts new file mode 100644 index 0000000..8823dee --- /dev/null +++ b/node_modules/@types/node/buffer.buffer.d.ts @@ -0,0 +1,472 @@ +declare module "buffer" { + type ImplicitArrayBuffer> = T extends + { valueOf(): infer V extends ArrayBufferLike } ? V : T; + global { + interface BufferConstructor { + // see buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: ArrayLike): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: TArrayBuffer): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * If `array` is an `Array`-like object (that is, one with a `length` property of + * type `number`), it is treated as if it is an array, unless it is a `Buffer` or + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an + * `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use + * `Buffer.copyBytesFrom()`. + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal + * `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from(array: WithImplicitCoercion>): Buffer; + /** + * This creates a view of the `ArrayBuffer` without copying the underlying + * memory. For example, when passed a reference to the `.buffer` property of a + * `TypedArray` instance, the newly created `Buffer` will share the same + * allocated memory as the `TypedArray`'s underlying `ArrayBuffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arr = new Uint16Array(2); + * + * arr[0] = 5000; + * arr[1] = 4000; + * + * // Shares memory with `arr`. + * const buf = Buffer.from(arr.buffer); + * + * console.log(buf); + * // Prints: + * + * // Changing the original Uint16Array changes the Buffer also. + * arr[1] = 6000; + * + * console.log(buf); + * // Prints: + * ``` + * + * The optional `byteOffset` and `length` arguments specify a memory range within + * the `arrayBuffer` that will be shared by the `Buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const ab = new ArrayBuffer(10); + * const buf = Buffer.from(ab, 0, 2); + * + * console.log(buf.length); + * // Prints: 2 + * ``` + * + * A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer` or a + * `SharedArrayBuffer` or another type appropriate for `Buffer.from()` + * variants. + * + * It is important to remember that a backing `ArrayBuffer` can cover a range + * of memory that extends beyond the bounds of a `TypedArray` view. A new + * `Buffer` created using the `buffer` property of a `TypedArray` may extend + * beyond the range of the `TypedArray`: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements + * const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements + * console.log(arrA.buffer === arrB.buffer); // true + * + * const buf = Buffer.from(arrB.buffer); + * console.log(buf); + * // Prints: + * ``` + * @since v5.10.0 + * @param arrayBuffer An `ArrayBuffer`, `SharedArrayBuffer`, for example the + * `.buffer` property of a `TypedArray`. + * @param byteOffset Index of first byte to expose. **Default:** `0`. + * @param length Number of bytes to expose. **Default:** + * `arrayBuffer.byteLength - byteOffset`. + */ + from>( + arrayBuffer: TArrayBuffer, + byteOffset?: number, + length?: number, + ): Buffer>; + /** + * Creates a new `Buffer` containing `string`. The `encoding` parameter identifies + * the character encoding to be used when converting `string` into bytes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('this is a tést'); + * const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); + * + * console.log(buf1.toString()); + * // Prints: this is a tést + * console.log(buf2.toString()); + * // Prints: this is a tést + * console.log(buf1.toString('latin1')); + * // Prints: this is a tést + * ``` + * + * A `TypeError` will be thrown if `string` is not a string or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(string)` may also use the internal `Buffer` pool like + * `Buffer.allocUnsafe()` does. + * @since v5.10.0 + * @param string A string to encode. + * @param encoding The encoding of `string`. **Default:** `'utf8'`. + */ + from(string: WithImplicitCoercion, encoding?: BufferEncoding): Buffer; + from(arrayOrString: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. If the combined length of the `Buffer`s in `list` is + * less than `totalLength`, the remaining space is filled with zeros. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: readonly Uint8Array[], totalLength?: number): Buffer; + /** + * Copies the underlying memory of `view` into a new `Buffer`. + * + * ```js + * const u16 = new Uint16Array([0, 0xffff]); + * const buf = Buffer.copyBytesFrom(u16, 1, 1); + * u16[1] = 0; + * console.log(buf.length); // 2 + * console.log(buf[0]); // 255 + * console.log(buf[1]); // 255 + * ``` + * @since v19.8.0 + * @param view The {TypedArray} to copy. + * @param [offset=0] The starting offset within `view`. + * @param [length=view.length - offset] The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if + * `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + } + interface Buffer extends Uint8Array { + // see buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + } + // TODO: remove globals in future version + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedBuffer = Buffer; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type AllowSharedBuffer = Buffer; + } + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + var SlowBuffer: { + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + new(size: number): Buffer; + prototype: Buffer; + }; +} diff --git a/node_modules/@types/node/buffer.d.ts b/node_modules/@types/node/buffer.d.ts new file mode 100644 index 0000000..354e08a --- /dev/null +++ b/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,1934 @@ +// If lib.dom.d.ts or lib.webworker.d.ts is loaded, then use the global types. +// Otherwise, use the types from node. +type _Blob = typeof globalThis extends { onmessage: any; Blob: any } ? {} : import("buffer").Blob; +type _File = typeof globalThis extends { onmessage: any; File: any } ? {} : import("buffer").File; + +/** + * `Buffer` objects are used to represent a fixed-length sequence of bytes. Many + * Node.js APIs support `Buffer`s. + * + * The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and + * extends it with methods that cover additional use cases. Node.js APIs accept + * plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) s wherever `Buffer`s are supported as well. + * + * While the `Buffer` class is available within the global scope, it is still + * recommended to explicitly reference it via an import or require statement. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a zero-filled Buffer of length 10. + * const buf1 = Buffer.alloc(10); + * + * // Creates a Buffer of length 10, + * // filled with bytes which all have the value `1`. + * const buf2 = Buffer.alloc(10, 1); + * + * // Creates an uninitialized buffer of length 10. + * // This is faster than calling Buffer.alloc() but the returned + * // Buffer instance might contain old data that needs to be + * // overwritten using fill(), write(), or other functions that fill the Buffer's + * // contents. + * const buf3 = Buffer.allocUnsafe(10); + * + * // Creates a Buffer containing the bytes [1, 2, 3]. + * const buf4 = Buffer.from([1, 2, 3]); + * + * // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries + * // are all truncated using `(value & 255)` to fit into the range 0–255. + * const buf5 = Buffer.from([257, 257.5, -255, '1']); + * + * // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': + * // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) + * // [116, 195, 169, 115, 116] (in decimal notation) + * const buf6 = Buffer.from('tést'); + * + * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. + * const buf7 = Buffer.from('tést', 'latin1'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/buffer.js) + */ +declare module "buffer" { + import { BinaryLike } from "node:crypto"; + import { ReadableStream as WebReadableStream } from "node:stream/web"; + /** + * This function returns `true` if `input` contains only valid UTF-8-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.4.0, v18.14.0 + * @param input The input to validate. + */ + export function isUtf8(input: ArrayBuffer | NodeJS.TypedArray): boolean; + /** + * This function returns `true` if `input` contains only valid ASCII-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.6.0, v18.15.0 + * @param input The input to validate. + */ + export function isAscii(input: ArrayBuffer | NodeJS.TypedArray): boolean; + export let INSPECT_MAX_BYTES: number; + export const kMaxLength: number; + export const kStringMaxLength: number; + export const constants: { + MAX_LENGTH: number; + MAX_STRING_LENGTH: number; + }; + export type TranscodeEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "latin1" + | "binary"; + /** + * Re-encodes the given `Buffer` or `Uint8Array` instance from one character + * encoding to another. Returns a new `Buffer` instance. + * + * Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if + * conversion from `fromEnc` to `toEnc` is not permitted. + * + * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`, `'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. + * + * The transcoding process will use substitution characters if a given byte + * sequence cannot be adequately represented in the target encoding. For instance: + * + * ```js + * import { Buffer, transcode } from 'node:buffer'; + * + * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); + * console.log(newBuf.toString('ascii')); + * // Prints: '?' + * ``` + * + * Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced + * with `?` in the transcoded `Buffer`. + * @since v7.1.0 + * @param source A `Buffer` or `Uint8Array` instance. + * @param fromEnc The current encoding. + * @param toEnc To target encoding. + */ + export function transcode( + source: Uint8Array, + fromEnc: TranscodeEncoding, + toEnc: TranscodeEncoding, + ): NonSharedBuffer; + /** + * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using + * a prior call to `URL.createObjectURL()`. + * @since v16.7.0 + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + export function resolveObjectURL(id: string): Blob | undefined; + export { type AllowSharedBuffer, Buffer, type NonSharedBuffer }; + /** + * @experimental + */ + export interface BlobOptions { + /** + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts + * will be converted to the platform native line-ending as specified by `import { EOL } from 'node:os'`. + */ + endings?: "transparent" | "native"; + /** + * The Blob content-type. The intent is for `type` to convey + * the MIME media type of the data, however no validation of the type format + * is performed. + */ + type?: string | undefined; + } + /** + * A `Blob` encapsulates immutable, raw data that can be safely shared across + * multiple worker threads. + * @since v15.7.0, v14.18.0 + */ + export class Blob { + /** + * The total size of the `Blob` in bytes. + * @since v15.7.0, v14.18.0 + */ + readonly size: number; + /** + * The content-type of the `Blob`. + * @since v15.7.0, v14.18.0 + */ + readonly type: string; + /** + * Creates a new `Blob` object containing a concatenation of the given sources. + * + * {ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into + * the 'Blob' and can therefore be safely modified after the 'Blob' is created. + * + * String sources are also copied into the `Blob`. + */ + constructor(sources: Array, options?: BlobOptions); + /** + * Returns a promise that fulfills with an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of + * the `Blob` data. + * @since v15.7.0, v14.18.0 + */ + arrayBuffer(): Promise; + /** + * The `blob.bytes()` method returns the byte of the `Blob` object as a `Promise`. + * + * ```js + * const blob = new Blob(['hello']); + * blob.bytes().then((bytes) => { + * console.log(bytes); // Outputs: Uint8Array(5) [ 104, 101, 108, 108, 111 ] + * }); + * ``` + */ + bytes(): Promise; + /** + * Creates and returns a new `Blob` containing a subset of this `Blob` objects + * data. The original `Blob` is not altered. + * @since v15.7.0, v14.18.0 + * @param start The starting index. + * @param end The ending index. + * @param type The content-type for the new `Blob` + */ + slice(start?: number, end?: number, type?: string): Blob; + /** + * Returns a promise that fulfills with the contents of the `Blob` decoded as a + * UTF-8 string. + * @since v15.7.0, v14.18.0 + */ + text(): Promise; + /** + * Returns a new `ReadableStream` that allows the content of the `Blob` to be read. + * @since v16.7.0 + */ + stream(): WebReadableStream; + } + export interface FileOptions { + /** + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be + * converted to the platform native line-ending as specified by `import { EOL } from 'node:os'`. + */ + endings?: "native" | "transparent"; + /** The File content-type. */ + type?: string; + /** The last modified date of the file. `Default`: Date.now(). */ + lastModified?: number; + } + /** + * A [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) provides information about files. + * @since v19.2.0, v18.13.0 + */ + export class File extends Blob { + constructor(sources: Array, fileName: string, options?: FileOptions); + /** + * The name of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly name: string; + /** + * The last modified date of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly lastModified: number; + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + export type WithImplicitCoercion = + | T + | { valueOf(): T } + | (T extends string ? { [Symbol.toPrimitive](hint: "string"): T } : never); + global { + namespace NodeJS { + export { BufferEncoding }; + } + // Buffer class + type BufferEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex"; + /** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex' + */ + interface BufferConstructor { + // see buffer.buffer.d.ts for implementation specific to TypeScript 5.7 and later + // see ts5.6/buffer.buffer.d.ts for implementation specific to TypeScript 5.6 and earlier + + /** + * Returns `true` if `obj` is a `Buffer`, `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * Buffer.isBuffer(Buffer.alloc(10)); // true + * Buffer.isBuffer(Buffer.from('foo')); // true + * Buffer.isBuffer('a string'); // false + * Buffer.isBuffer([]); // false + * Buffer.isBuffer(new Uint8Array(1024)); // false + * ``` + * @since v0.1.101 + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns `true` if `encoding` is the name of a supported character encoding, + * or `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * console.log(Buffer.isEncoding('utf8')); + * // Prints: true + * + * console.log(Buffer.isEncoding('hex')); + * // Prints: true + * + * console.log(Buffer.isEncoding('utf/8')); + * // Prints: false + * + * console.log(Buffer.isEncoding('')); + * // Prints: false + * ``` + * @since v0.9.1 + * @param encoding A character encoding name to check. + */ + isEncoding(encoding: string): encoding is BufferEncoding; + /** + * Returns the byte length of a string when encoded using `encoding`. + * This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account + * for the encoding that is used to convert the string into bytes. + * + * For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input. + * For strings that contain non-base64/hex-encoded data (e.g. whitespace), the + * return value might be greater than the length of a `Buffer` created from the + * string. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const str = '\u00bd + \u00bc = \u00be'; + * + * console.log(`${str}: ${str.length} characters, ` + + * `${Buffer.byteLength(str, 'utf8')} bytes`); + * // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes + * ``` + * + * When `string` is a + * `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- + * Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop- + * er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned. + * @since v0.1.90 + * @param string A value to calculate the length of. + * @param [encoding='utf8'] If `string` is a string, this is its encoding. + * @return The number of bytes contained within `string`. + */ + byteLength( + string: string | NodeJS.ArrayBufferView | ArrayBufferLike, + encoding?: BufferEncoding, + ): number; + /** + * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of `Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('1234'); + * const buf2 = Buffer.from('0123'); + * const arr = [buf1, buf2]; + * + * console.log(arr.sort(Buffer.compare)); + * // Prints: [ , ] + * // (This result is equal to: [buf2, buf1].) + * ``` + * @since v0.11.13 + * @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details. + */ + compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1; + /** + * This is the size (in bytes) of pre-allocated internal `Buffer` instances used + * for pooling. This value may be modified. + * @since v0.11.3 + */ + poolSize: number; + } + interface Buffer { + // see buffer.buffer.d.ts for implementation specific to TypeScript 5.7 and later + // see ts5.6/buffer.buffer.d.ts for implementation specific to TypeScript 5.6 and earlier + + /** + * Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did + * not contain enough space to fit the entire string, only part of `string` will be + * written. However, partially encoded characters will not be written. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(256); + * + * const len = buf.write('\u00bd + \u00bc = \u00be', 0); + * + * console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); + * // Prints: 12 bytes: ½ + ¼ = ¾ + * + * const buffer = Buffer.alloc(10); + * + * const length = buffer.write('abcd', 8); + * + * console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); + * // Prints: 2 bytes : ab + * ``` + * @since v0.1.90 + * @param string String to write to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write `string`. + * @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). + * @param [encoding='utf8'] The character encoding of `string`. + * @return Number of bytes written. + */ + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + /** + * Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`. + * + * If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, + * then each invalid byte is replaced with the replacement character `U+FFFD`. + * + * The maximum length of a string instance (in UTF-16 code units) is available + * as {@link constants.MAX_STRING_LENGTH}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * console.log(buf1.toString('utf8')); + * // Prints: abcdefghijklmnopqrstuvwxyz + * console.log(buf1.toString('utf8', 0, 5)); + * // Prints: abcde + * + * const buf2 = Buffer.from('tést'); + * + * console.log(buf2.toString('hex')); + * // Prints: 74c3a97374 + * console.log(buf2.toString('utf8', 0, 3)); + * // Prints: té + * console.log(buf2.toString(undefined, 0, 3)); + * // Prints: té + * ``` + * @since v0.1.90 + * @param [encoding='utf8'] The character encoding to use. + * @param [start=0] The byte offset to start decoding at. + * @param [end=buf.length] The byte offset to stop decoding at (not inclusive). + */ + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + /** + * Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls + * this function when stringifying a `Buffer` instance. + * + * `Buffer.from()` accepts objects in the format returned from this method. + * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); + * const json = JSON.stringify(buf); + * + * console.log(json); + * // Prints: {"type":"Buffer","data":[1,2,3,4,5]} + * + * const copy = JSON.parse(json, (key, value) => { + * return value && value.type === 'Buffer' ? + * Buffer.from(value) : + * value; + * }); + * + * console.log(copy); + * // Prints: + * ``` + * @since v0.9.2 + */ + toJSON(): { + type: "Buffer"; + data: number[]; + }; + /** + * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('414243', 'hex'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.equals(buf2)); + * // Prints: true + * console.log(buf1.equals(buf3)); + * // Prints: false + * ``` + * @since v0.11.13 + * @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`. + */ + equals(otherBuffer: Uint8Array): boolean; + /** + * Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. + * Comparison is based on the actual sequence of bytes in each `Buffer`. + * + * * `0` is returned if `target` is the same as `buf` + * * `1` is returned if `target` should come _before_`buf` when sorted. + * * `-1` is returned if `target` should come _after_`buf` when sorted. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('BCD'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.compare(buf1)); + * // Prints: 0 + * console.log(buf1.compare(buf2)); + * // Prints: -1 + * console.log(buf1.compare(buf3)); + * // Prints: -1 + * console.log(buf2.compare(buf1)); + * // Prints: 1 + * console.log(buf2.compare(buf3)); + * // Prints: 1 + * console.log([buf1, buf2, buf3].sort(Buffer.compare)); + * // Prints: [ , , ] + * // (This result is equal to: [buf1, buf3, buf2].) + * ``` + * + * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd` arguments can be used to limit the comparison to specific ranges within `target` and `buf` respectively. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); + * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + * + * console.log(buf1.compare(buf2, 5, 9, 0, 4)); + * // Prints: 0 + * console.log(buf1.compare(buf2, 0, 6, 4)); + * // Prints: -1 + * console.log(buf1.compare(buf2, 5, 6, 5)); + * // Prints: 1 + * ``` + * + * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`, `targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * @since v0.11.13 + * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. + * @param [targetStart=0] The offset within `target` at which to begin comparison. + * @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive). + * @param [sourceStart=0] The offset within `buf` at which to begin comparison. + * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). + */ + compare( + target: Uint8Array, + targetStart?: number, + targetEnd?: number, + sourceStart?: number, + sourceEnd?: number, + ): -1 | 0 | 1; + /** + * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. + * + * [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available + * for all TypedArrays, including Node.js `Buffer`s, although it takes + * different function arguments. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create two `Buffer` instances. + * const buf1 = Buffer.allocUnsafe(26); + * const buf2 = Buffer.allocUnsafe(26).fill('!'); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. + * buf1.copy(buf2, 8, 16, 20); + * // This is equivalent to: + * // buf2.set(buf1.subarray(16, 20), 8); + * + * console.log(buf2.toString('ascii', 0, 25)); + * // Prints: !!!!!!!!qrst!!!!!!!!!!!!! + * ``` + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` and copy data from one region to an overlapping region + * // within the same `Buffer`. + * + * const buf = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf[i] = i + 97; + * } + * + * buf.copy(buf, 0, 4, 10); + * + * console.log(buf.toString()); + * // Prints: efghijghijklmnopqrstuvwxyz + * ``` + * @since v0.1.90 + * @param target A `Buffer` or {@link Uint8Array} to copy into. + * @param [targetStart=0] The offset within `target` at which to begin writing. + * @param [sourceStart=0] The offset within `buf` from which to begin copying. + * @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive). + * @return The number of bytes copied. + */ + copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64BE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64LE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64LE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * This function is also available under the `writeBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64BE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64LE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * + * This function is also available under the `writeBigUint64LE` alias. + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64LE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64LE(value: bigint, offset?: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntLE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntLE + * @since v14.9.0, v12.19.0 + */ + writeUintLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntBE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntBE + * @since v14.9.0, v12.19.0 + */ + writeUintBE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than a signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a + * signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntBE(value: number, offset: number, byteLength: number): number; + /** + * Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64BE(0)); + * // Prints: 4294967295n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64BE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + readBigUint64BE(offset?: number): bigint; + /** + * Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64LE(0)); + * // Prints: 18446744069414584320n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64LE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + readBigUint64LE(offset?: number): bigint; + /** + * Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64BE(offset?: number): bigint; + /** + * Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64LE(offset?: number): bigint; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an unsigned, little-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntLE(0, 6).toString(16)); + * // Prints: ab9078563412 + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntLE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntLE + * @since v14.9.0, v12.19.0 + */ + readUintLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an unsigned big-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readUIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntBE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntBE + * @since v14.9.0, v12.19.0 + */ + readUintBE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a little-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntLE(0, 6).toString(16)); + * // Prints: -546f87a9cbee + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a big-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * console.log(buf.readIntBE(1, 0).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntBE(offset: number, byteLength: number): number; + /** + * Reads an unsigned 8-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, -2]); + * + * console.log(buf.readUInt8(0)); + * // Prints: 1 + * console.log(buf.readUInt8(1)); + * // Prints: 254 + * console.log(buf.readUInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readUInt8(offset?: number): number; + /** + * @alias Buffer.readUInt8 + * @since v14.9.0, v12.19.0 + */ + readUint8(offset?: number): number; + /** + * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16LE(0).toString(16)); + * // Prints: 3412 + * console.log(buf.readUInt16LE(1).toString(16)); + * // Prints: 5634 + * console.log(buf.readUInt16LE(2).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16LE(offset?: number): number; + /** + * @alias Buffer.readUInt16LE + * @since v14.9.0, v12.19.0 + */ + readUint16LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16BE(0).toString(16)); + * // Prints: 1234 + * console.log(buf.readUInt16BE(1).toString(16)); + * // Prints: 3456 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16BE(offset?: number): number; + /** + * @alias Buffer.readUInt16BE + * @since v14.9.0, v12.19.0 + */ + readUint16BE(offset?: number): number; + /** + * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32LE(0).toString(16)); + * // Prints: 78563412 + * console.log(buf.readUInt32LE(1).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32LE(offset?: number): number; + /** + * @alias Buffer.readUInt32LE + * @since v14.9.0, v12.19.0 + */ + readUint32LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32BE(0).toString(16)); + * // Prints: 12345678 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32BE(offset?: number): number; + /** + * @alias Buffer.readUInt32BE + * @since v14.9.0, v12.19.0 + */ + readUint32BE(offset?: number): number; + /** + * Reads a signed 8-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([-1, 5]); + * + * console.log(buf.readInt8(0)); + * // Prints: -1 + * console.log(buf.readInt8(1)); + * // Prints: 5 + * console.log(buf.readInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readInt8(offset?: number): number; + /** + * Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16LE(0)); + * // Prints: 1280 + * console.log(buf.readInt16LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16LE(offset?: number): number; + /** + * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16BE(offset?: number): number; + /** + * Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32LE(0)); + * // Prints: 83886080 + * console.log(buf.readInt32LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32LE(offset?: number): number; + /** + * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32BE(offset?: number): number; + /** + * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatLE(0)); + * // Prints: 1.539989614439558e-36 + * console.log(buf.readFloatLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatLE(offset?: number): number; + /** + * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatBE(0)); + * // Prints: 2.387939260590663e-38 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatBE(offset?: number): number; + /** + * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleLE(0)); + * // Prints: 5.447603722011605e-270 + * console.log(buf.readDoubleLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleLE(offset?: number): number; + /** + * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleBE(0)); + * // Prints: 8.20788039913184e-304 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleBE(offset?: number): number; + reverse(): this; + /** + * Interprets `buf` as an array of unsigned 16-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap16(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap16(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * + * One convenient use of `buf.swap16()` is to perform a fast in-place conversion + * between UTF-16 little-endian and UTF-16 big-endian: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); + * buf.swap16(); // Convert to big-endian UTF-16 text. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap16(): this; + /** + * Interprets `buf` as an array of unsigned 32-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap32(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap32(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap32(): this; + /** + * Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. + * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap64(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap64(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v6.3.0 + * @return A reference to `buf`. + */ + swap64(): this; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a + * valid unsigned 8-bit integer. Behavior is undefined when `value` is anything + * other than an unsigned 8-bit integer. + * + * This function is also available under the `writeUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt8(0x3, 0); + * buf.writeUInt8(0x4, 1); + * buf.writeUInt8(0x23, 2); + * buf.writeUInt8(0x42, 3); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeUInt8(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt8 + * @since v14.9.0, v12.19.0 + */ + writeUint8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 16-bit integer. + * + * This function is also available under the `writeUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16LE(0xdead, 0); + * buf.writeUInt16LE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16LE + * @since v14.9.0, v12.19.0 + */ + writeUint16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 16-bit integer. + * + * This function is also available under the `writeUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16BE(0xdead, 0); + * buf.writeUInt16BE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16BE + * @since v14.9.0, v12.19.0 + */ + writeUint16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 32-bit integer. + * + * This function is also available under the `writeUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32LE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32LE + * @since v14.9.0, v12.19.0 + */ + writeUint32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 32-bit integer. + * + * This function is also available under the `writeUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32BE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32BE + * @since v14.9.0, v12.19.0 + */ + writeUint32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a valid + * signed 8-bit integer. Behavior is undefined when `value` is anything other than + * a signed 8-bit integer. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt8(2, 0); + * buf.writeInt8(-2, 1); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16LE(0x0304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16BE(0x0102, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32LE(0x05060708, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32BE(0x01020304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatLE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatBE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatBE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleLE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleBE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleBE(value: number, offset?: number): number; + /** + * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, + * the entire `buf` will be filled: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * + * // Fill a buffer with empty string + * const c = Buffer.allocUnsafe(5).fill(''); + * + * console.log(c.fill('')); + * // Prints: + * ``` + * + * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or + * integer. If the resulting integer is greater than `255` (decimal), `buf` will be + * filled with `value & 255`. + * + * If the final write of a `fill()` operation falls on a multi-byte character, + * then only the bytes of that character that fit into `buf` are written: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with character that takes up two bytes in UTF-8. + * + * console.log(Buffer.allocUnsafe(5).fill('\u0222')); + * // Prints: + * ``` + * + * If `value` contains invalid characters, it is truncated; if no valid + * fill data remains, an exception is thrown: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(5); + * + * console.log(buf.fill('a')); + * // Prints: + * console.log(buf.fill('aazz', 'hex')); + * // Prints: + * console.log(buf.fill('zz', 'hex')); + * // Throws an exception. + * ``` + * @since v0.5.0 + * @param value The value with which to fill `buf`. Empty value (string, Uint8Array, Buffer) is coerced to `0`. + * @param [offset=0] Number of bytes to skip before starting to fill `buf`. + * @param [end=buf.length] Where to stop filling `buf` (not inclusive). + * @param [encoding='utf8'] The encoding for `value` if `value` is a string. + * @return A reference to `buf`. + */ + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + fill(value: string | Uint8Array | number, offset: number, encoding: BufferEncoding): this; + fill(value: string | Uint8Array | number, encoding: BufferEncoding): this; + /** + * If `value` is: + * + * * a string, `value` is interpreted according to the character encoding in `encoding`. + * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. + * To compare a partial `Buffer`, use `buf.subarray`. + * * a number, `value` will be interpreted as an unsigned 8-bit integer + * value between `0` and `255`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.indexOf('this')); + * // Prints: 0 + * console.log(buf.indexOf('is')); + * // Prints: 2 + * console.log(buf.indexOf(Buffer.from('a buffer'))); + * // Prints: 8 + * console.log(buf.indexOf(97)); + * // Prints: 8 (97 is the decimal ASCII value for 'a') + * console.log(buf.indexOf(Buffer.from('a buffer example'))); + * // Prints: -1 + * console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: 8 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); + * // Prints: 4 + * console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); + * // Prints: 6 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a `TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. If the result + * of coercion is `NaN` or `0`, then the entire buffer will be searched. This + * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.indexOf(99.9)); + * console.log(b.indexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN or 0. + * // Prints: 1, searching the whole buffer. + * console.log(b.indexOf('b', undefined)); + * console.log(b.indexOf('b', {})); + * console.log(b.indexOf('b', null)); + * console.log(b.indexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer` and `byteOffset` is less + * than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. + * @since v1.5.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + indexOf(value: string | number | Uint8Array, encoding: BufferEncoding): number; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this buffer is a buffer'); + * + * console.log(buf.lastIndexOf('this')); + * // Prints: 0 + * console.log(buf.lastIndexOf('buffer')); + * // Prints: 17 + * console.log(buf.lastIndexOf(Buffer.from('buffer'))); + * // Prints: 17 + * console.log(buf.lastIndexOf(97)); + * // Prints: 15 (97 is the decimal ASCII value for 'a') + * console.log(buf.lastIndexOf(Buffer.from('yolo'))); + * // Prints: -1 + * console.log(buf.lastIndexOf('buffer', 5)); + * // Prints: 5 + * console.log(buf.lastIndexOf('buffer', 4)); + * // Prints: -1 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); + * // Prints: 6 + * console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); + * // Prints: 4 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a `TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. Any arguments + * that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. + * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.lastIndexOf(99.9)); + * console.log(b.lastIndexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN. + * // Prints: 1, searching the whole buffer. + * console.log(b.lastIndexOf('b', undefined)); + * console.log(b.lastIndexOf('b', {})); + * + * // Passing a byteOffset that coerces to 0. + * // Prints: -1, equivalent to passing 0. + * console.log(b.lastIndexOf('b', null)); + * console.log(b.lastIndexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. + * @since v6.0.0 + * @param value What to search for. + * @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + lastIndexOf(value: string | number | Uint8Array, encoding: BufferEncoding): number; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.includes('this')); + * // Prints: true + * console.log(buf.includes('is')); + * // Prints: true + * console.log(buf.includes(Buffer.from('a buffer'))); + * // Prints: true + * console.log(buf.includes(97)); + * // Prints: true (97 is the decimal ASCII value for 'a') + * console.log(buf.includes(Buffer.from('a buffer example'))); + * // Prints: false + * console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: true + * console.log(buf.includes('this', 4)); + * // Prints: false + * ``` + * @since v5.3.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is its encoding. + * @return `true` if `value` was found in `buf`, `false` otherwise. + */ + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + includes(value: string | number | Buffer, encoding: BufferEncoding): boolean; + } + var Buffer: BufferConstructor; + /** + * Decodes a string of Base64-encoded data into bytes, and encodes those bytes + * into a string using Latin-1 (ISO-8859-1). + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @legacy Use `Buffer.from(data, 'base64')` instead. + * @param data The Base64-encoded input string. + */ + function atob(data: string): string; + /** + * Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes + * into a string using Base64. + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @legacy Use `buf.toString('base64')` instead. + * @param data An ASCII (Latin1) string. + */ + function btoa(data: string): string; + interface Blob extends _Blob {} + /** + * `Blob` class is a global reference for `import { Blob } from 'node:buffer'` + * https://nodejs.org/api/buffer.html#class-blob + * @since v18.0.0 + */ + var Blob: typeof globalThis extends { onmessage: any; Blob: infer T } ? T + : typeof import("buffer").Blob; + interface File extends _File {} + /** + * `File` class is a global reference for `import { File } from 'node:buffer'` + * https://nodejs.org/api/buffer.html#class-file + * @since v20.0.0 + */ + var File: typeof globalThis extends { onmessage: any; File: infer T } ? T + : typeof import("buffer").File; + } +} +declare module "node:buffer" { + export * from "buffer"; +} diff --git a/node_modules/@types/node/child_process.d.ts b/node_modules/@types/node/child_process.d.ts new file mode 100644 index 0000000..313c33c --- /dev/null +++ b/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,1476 @@ +/** + * The `node:child_process` module provides the ability to spawn subprocesses in + * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability + * is primarily provided by the {@link spawn} function: + * + * ```js + * import { spawn } from 'node:child_process'; + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * By default, pipes for `stdin`, `stdout`, and `stderr` are established between + * the parent Node.js process and the spawned subprocess. These pipes have + * limited (and platform-specific) capacity. If the subprocess writes to + * stdout in excess of that limit without the output being captured, the + * subprocess blocks, waiting for the pipe buffer to accept more data. This is + * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }` option if the output will not be consumed. + * + * The command lookup is performed using the `options.env.PATH` environment + * variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is + * used. If `options.env` is set without `PATH`, lookup on Unix is performed + * on a default search path search of `/usr/bin:/bin` (see your operating system's + * manual for execvpe/execvp), on Windows the current processes environment + * variable `PATH` is used. + * + * On Windows, environment variables are case-insensitive. Node.js + * lexicographically sorts the `env` keys and uses the first one that + * case-insensitively matches. Only first (in lexicographic order) entry will be + * passed to the subprocess. This might lead to issues on Windows when passing + * objects to the `env` option that have multiple variants of the same key, such as `PATH` and `Path`. + * + * The {@link spawn} method spawns the child process asynchronously, + * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks + * the event loop until the spawned process either exits or is terminated. + * + * For convenience, the `node:child_process` module provides a handful of + * synchronous and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * top of {@link spawn} or {@link spawnSync}. + * + * * {@link exec}: spawns a shell and runs a command within that + * shell, passing the `stdout` and `stderr` to a callback function when + * complete. + * * {@link execFile}: similar to {@link exec} except + * that it spawns the command directly without first spawning a shell by + * default. + * * {@link fork}: spawns a new Node.js process and invokes a + * specified module with an IPC communication channel established that allows + * sending messages between parent and child. + * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop. + * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop. + * + * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, + * the synchronous methods can have significant impact on performance due to + * stalling the event loop while spawned processes complete. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/child_process.js) + */ +declare module "child_process" { + import { NonSharedBuffer } from "node:buffer"; + import { Abortable, EventEmitter } from "node:events"; + import * as dgram from "node:dgram"; + import * as net from "node:net"; + import { Readable, Stream, Writable } from "node:stream"; + import { URL } from "node:url"; + type Serializable = string | object | number | boolean | bigint; + type SendHandle = net.Socket | net.Server | dgram.Socket | undefined; + /** + * Instances of the `ChildProcess` represent spawned child processes. + * + * Instances of `ChildProcess` are not intended to be created directly. Rather, + * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create + * instances of `ChildProcess`. + * @since v2.2.0 + */ + class ChildProcess extends EventEmitter { + /** + * A `Writable Stream` that represents the child process's `stdin`. + * + * If a child process waits to read all of its input, the child will not continue + * until this stream has been closed via `end()`. + * + * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will + * refer to the same value. + * + * The `subprocess.stdin` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdin: Writable | null; + /** + * A `Readable Stream` that represents the child process's `stdout`. + * + * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will + * refer to the same value. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdout: Readable | null; + /** + * A `Readable Stream` that represents the child process's `stderr`. + * + * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will + * refer to the same value. + * + * The `subprocess.stderr` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stderr: Readable | null; + /** + * The `subprocess.channel` property is a reference to the child's IPC channel. If + * no IPC channel exists, this property is `undefined`. + * @since v7.1.0 + */ + readonly channel?: Control | null; + /** + * A sparse array of pipes to the child process, corresponding with positions in + * the `stdio` option passed to {@link spawn} that have been set + * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and `subprocess.stdio[2]` are also available as `subprocess.stdin`, `subprocess.stdout`, and `subprocess.stderr`, + * respectively. + * + * In the following example, only the child's fd `1` (stdout) is configured as a + * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values + * in the array are `null`. + * + * ```js + * import assert from 'node:assert'; + * import fs from 'node:fs'; + * import child_process from 'node:child_process'; + * + * const subprocess = child_process.spawn('ls', { + * stdio: [ + * 0, // Use parent's stdin for child. + * 'pipe', // Pipe child's stdout to parent. + * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. + * ], + * }); + * + * assert.strictEqual(subprocess.stdio[0], null); + * assert.strictEqual(subprocess.stdio[0], subprocess.stdin); + * + * assert(subprocess.stdout); + * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); + * + * assert.strictEqual(subprocess.stdio[2], null); + * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); + * ``` + * + * The `subprocess.stdio` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.7.10 + */ + readonly stdio: [ + Writable | null, + // stdin + Readable | null, + // stdout + Readable | null, + // stderr + Readable | Writable | null | undefined, + // extra + Readable | Writable | null | undefined, // extra + ]; + /** + * The `subprocess.killed` property indicates whether the child process + * successfully received a signal from `subprocess.kill()`. The `killed` property + * does not indicate that the child process has been terminated. + * @since v0.5.10 + */ + readonly killed: boolean; + /** + * Returns the process identifier (PID) of the child process. If the child process + * fails to spawn due to errors, then the value is `undefined` and `error` is + * emitted. + * + * ```js + * import { spawn } from 'node:child_process'; + * const grep = spawn('grep', ['ssh']); + * + * console.log(`Spawned child pid: ${grep.pid}`); + * grep.stdin.end(); + * ``` + * @since v0.1.90 + */ + readonly pid?: number | undefined; + /** + * The `subprocess.connected` property indicates whether it is still possible to + * send and receive messages from a child process. When `subprocess.connected` is `false`, it is no longer possible to send or receive messages. + * @since v0.7.2 + */ + readonly connected: boolean; + /** + * The `subprocess.exitCode` property indicates the exit code of the child process. + * If the child process is still running, the field will be `null`. + */ + readonly exitCode: number | null; + /** + * The `subprocess.signalCode` property indicates the signal received by + * the child process if any, else `null`. + */ + readonly signalCode: NodeJS.Signals | null; + /** + * The `subprocess.spawnargs` property represents the full list of command-line + * arguments the child process was launched with. + */ + readonly spawnargs: string[]; + /** + * The `subprocess.spawnfile` property indicates the executable file name of + * the child process that is launched. + * + * For {@link fork}, its value will be equal to `process.execPath`. + * For {@link spawn}, its value will be the name of + * the executable file. + * For {@link exec}, its value will be the name of the shell + * in which the child process is launched. + */ + readonly spawnfile: string; + /** + * The `subprocess.kill()` method sends a signal to the child process. If no + * argument is given, the process will be sent the `'SIGTERM'` signal. See [`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function + * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. + * + * ```js + * import { spawn } from 'node:child_process'; + * const grep = spawn('grep', ['ssh']); + * + * grep.on('close', (code, signal) => { + * console.log( + * `child process terminated due to receipt of signal ${signal}`); + * }); + * + * // Send SIGHUP to process. + * grep.kill('SIGHUP'); + * ``` + * + * The `ChildProcess` object may emit an `'error'` event if the signal + * cannot be delivered. Sending a signal to a child process that has already exited + * is not an error but may have unforeseen consequences. Specifically, if the + * process identifier (PID) has been reassigned to another process, the signal will + * be delivered to that process instead which can have unexpected results. + * + * While the function is called `kill`, the signal delivered to the child process + * may not actually terminate the process. + * + * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. + * + * On Windows, where POSIX signals do not exist, the `signal` argument will be + * ignored, and the process will be killed forcefully and abruptly (similar to `'SIGKILL'`). + * See `Signal Events` for more details. + * + * On Linux, child processes of child processes will not be terminated + * when attempting to kill their parent. This is likely to happen when running a + * new process in a shell or with the use of the `shell` option of `ChildProcess`: + * + * ```js + * 'use strict'; + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn( + * 'sh', + * [ + * '-c', + * `node -e "setInterval(() => { + * console.log(process.pid, 'is alive') + * }, 500);"`, + * ], { + * stdio: ['inherit', 'inherit', 'inherit'], + * }, + * ); + * + * setTimeout(() => { + * subprocess.kill(); // Does not terminate the Node.js process in the shell. + * }, 2000); + * ``` + * @since v0.1.90 + */ + kill(signal?: NodeJS.Signals | number): boolean; + /** + * Calls {@link ChildProcess.kill} with `'SIGTERM'`. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + /** + * When an IPC channel has been established between the parent and child ( + * i.e. when using {@link fork}), the `subprocess.send()` method can + * be used to send messages to the child process. When the child process is a + * Node.js instance, these messages can be received via the `'message'` event. + * + * The message goes through serialization and parsing. The resulting + * message might not be the same as what is originally sent. + * + * For example, in the parent script: + * + * ```js + * import cp from 'node:child_process'; + * const n = cp.fork(`${__dirname}/sub.js`); + * + * n.on('message', (m) => { + * console.log('PARENT got message:', m); + * }); + * + * // Causes the child to print: CHILD got message: { hello: 'world' } + * n.send({ hello: 'world' }); + * ``` + * + * And then the child script, `'sub.js'` might look like this: + * + * ```js + * process.on('message', (m) => { + * console.log('CHILD got message:', m); + * }); + * + * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } + * process.send({ foo: 'bar', baz: NaN }); + * ``` + * + * Child Node.js processes will have a `process.send()` method of their own + * that allows the child to send messages back to the parent. + * + * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages + * containing a `NODE_` prefix in the `cmd` property are reserved for use within + * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the `'internalMessage'` event and are consumed internally by Node.js. + * Applications should avoid using such messages or listening for `'internalMessage'` events as it is subject to change without notice. + * + * The optional `sendHandle` argument that may be passed to `subprocess.send()` is + * for passing a TCP server or socket object to the child process. The child will + * receive the object as the second argument passed to the callback function + * registered on the `'message'` event. Any data that is received and buffered in + * the socket will not be sent to the child. Sending IPC sockets is not supported on Windows. + * + * The optional `callback` is a function that is invoked after the message is + * sent but before the child may have received it. The function is called with a + * single argument: `null` on success, or an `Error` object on failure. + * + * If no `callback` function is provided and the message cannot be sent, an `'error'` event will be emitted by the `ChildProcess` object. This can + * happen, for instance, when the child process has already exited. + * + * `subprocess.send()` will return `false` if the channel has closed or when the + * backlog of unsent messages exceeds a threshold that makes it unwise to send + * more. Otherwise, the method returns `true`. The `callback` function can be + * used to implement flow control. + * + * #### Example: sending a server object + * + * The `sendHandle` argument can be used, for instance, to pass the handle of + * a TCP server object to the child process as illustrated in the example below: + * + * ```js + * import { createServer } from 'node:net'; + * import { fork } from 'node:child_process'; + * const subprocess = fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = createServer(); + * server.on('connection', (socket) => { + * socket.end('handled by parent'); + * }); + * server.listen(1337, () => { + * subprocess.send('server', server); + * }); + * ``` + * + * The child would then receive the server object as: + * + * ```js + * process.on('message', (m, server) => { + * if (m === 'server') { + * server.on('connection', (socket) => { + * socket.end('handled by child'); + * }); + * } + * }); + * ``` + * + * Once the server is now shared between the parent and child, some connections + * can be handled by the parent and some by the child. + * + * While the example above uses a server created using the `node:net` module, `node:dgram` module servers use exactly the same workflow with the exceptions of + * listening on a `'message'` event instead of `'connection'` and using `server.bind()` instead of `server.listen()`. This is, however, only + * supported on Unix platforms. + * + * #### Example: sending a socket object + * + * Similarly, the `sendHandler` argument can be used to pass the handle of a + * socket to the child process. The example below spawns two children that each + * handle connections with "normal" or "special" priority: + * + * ```js + * import { createServer } from 'node:net'; + * import { fork } from 'node:child_process'; + * const normal = fork('subprocess.js', ['normal']); + * const special = fork('subprocess.js', ['special']); + * + * // Open up the server and send sockets to child. Use pauseOnConnect to prevent + * // the sockets from being read before they are sent to the child process. + * const server = createServer({ pauseOnConnect: true }); + * server.on('connection', (socket) => { + * + * // If this is special priority... + * if (socket.remoteAddress === '74.125.127.100') { + * special.send('socket', socket); + * return; + * } + * // This is normal priority. + * normal.send('socket', socket); + * }); + * server.listen(1337); + * ``` + * + * The `subprocess.js` would receive the socket handle as the second argument + * passed to the event callback function: + * + * ```js + * process.on('message', (m, socket) => { + * if (m === 'socket') { + * if (socket) { + * // Check that the client socket exists. + * // It is possible for the socket to be closed between the time it is + * // sent and the time it is received in the child process. + * socket.end(`Request handled with ${process.argv[2]} priority`); + * } + * } + * }); + * ``` + * + * Do not use `.maxConnections` on a socket that has been passed to a subprocess. + * The parent cannot track when the socket is destroyed. + * + * Any `'message'` handlers in the subprocess should verify that `socket` exists, + * as the connection may have been closed during the time it takes to send the + * connection to the child. + * @since v0.5.9 + * @param sendHandle `undefined`, or a [`net.Socket`](https://nodejs.org/docs/latest-v22.x/api/net.html#class-netsocket), [`net.Server`](https://nodejs.org/docs/latest-v22.x/api/net.html#class-netserver), or [`dgram.Socket`](https://nodejs.org/docs/latest-v22.x/api/dgram.html#class-dgramsocket) object. + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: Serializable, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; + send( + message: Serializable, + sendHandle?: SendHandle, + options?: MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * Closes the IPC channel between parent and child, allowing the child to exit + * gracefully once there are no other connections keeping it alive. After calling + * this method the `subprocess.connected` and `process.connected` properties in + * both the parent and child (respectively) will be set to `false`, and it will be + * no longer possible to pass messages between the processes. + * + * The `'disconnect'` event will be emitted when there are no messages in the + * process of being received. This will most often be triggered immediately after + * calling `subprocess.disconnect()`. + * + * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked + * within the child process to close the IPC channel as well. + * @since v0.7.2 + */ + disconnect(): void; + /** + * By default, the parent will wait for the detached child to exit. To prevent the + * parent from waiting for a given `subprocess` to exit, use the `subprocess.unref()` method. Doing so will cause the parent's event loop to not + * include the child in its reference count, allowing the parent to exit + * independently of the child, unless there is an established IPC channel between + * the child and the parent. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * ``` + * @since v0.7.10 + */ + unref(): void; + /** + * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will + * restore the removed reference count for the child process, forcing the parent + * to wait for the child to exit before exiting itself. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * subprocess.ref(); + * ``` + * @since v0.7.10 + */ + ref(): void; + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + * 6. spawn + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + addListener(event: "spawn", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "message", message: Serializable, sendHandle: SendHandle): boolean; + emit(event: "spawn", listener: () => void): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + on(event: "spawn", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + once(event: "spawn", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependListener(event: "spawn", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "close", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "exit", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependOnceListener(event: "spawn", listener: () => void): this; + } + // return this object when stdio option is undefined or not specified + interface ChildProcessWithoutNullStreams extends ChildProcess { + stdin: Writable; + stdout: Readable; + stderr: Readable; + readonly stdio: [ + Writable, + Readable, + Readable, + // stderr + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + // return this object when stdio option is a tuple of 3 + interface ChildProcessByStdio + extends ChildProcess + { + stdin: I; + stdout: O; + stderr: E; + readonly stdio: [ + I, + O, + E, + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + interface Control extends EventEmitter { + ref(): void; + unref(): void; + } + interface MessageOptions { + keepOpen?: boolean | undefined; + } + type IOType = "overlapped" | "pipe" | "ignore" | "inherit"; + type StdioOptions = IOType | Array; + type SerializationType = "json" | "advanced"; + interface MessagingOptions extends Abortable { + /** + * Specify the kind of serialization used for sending messages between processes. + * @default 'json' + */ + serialization?: SerializationType | undefined; + /** + * The signal value to be used when the spawned process will be killed by the abort signal. + * @default 'SIGTERM' + */ + killSignal?: NodeJS.Signals | number | undefined; + /** + * In milliseconds the maximum amount of time the process is allowed to run. + */ + timeout?: number | undefined; + } + interface ProcessEnvOptions { + uid?: number | undefined; + gid?: number | undefined; + cwd?: string | URL | undefined; + env?: NodeJS.ProcessEnv | undefined; + } + interface CommonOptions extends ProcessEnvOptions { + /** + * @default false + */ + windowsHide?: boolean | undefined; + /** + * @default 0 + */ + timeout?: number | undefined; + } + interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { + argv0?: string | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + shell?: boolean | string | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + interface SpawnOptions extends CommonSpawnOptions { + detached?: boolean | undefined; + } + interface SpawnOptionsWithoutStdio extends SpawnOptions { + stdio?: StdioPipeNamed | StdioPipe[] | undefined; + } + type StdioNull = "inherit" | "ignore" | Stream; + type StdioPipeNamed = "pipe" | "overlapped"; + type StdioPipe = undefined | null | StdioPipeNamed; + interface SpawnOptionsWithStdioTuple< + Stdin extends StdioNull | StdioPipe, + Stdout extends StdioNull | StdioPipe, + Stderr extends StdioNull | StdioPipe, + > extends SpawnOptions { + stdio: [Stdin, Stdout, Stderr]; + } + /** + * The `child_process.spawn()` method spawns a new process using the given `command`, with command-line arguments in `args`. If omitted, `args` defaults + * to an empty array. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * A third argument may be used to specify additional options, with these defaults: + * + * ```js + * const defaults = { + * cwd: undefined, + * env: process.env, + * }; + * ``` + * + * Use `cwd` to specify the working directory from which the process is spawned. + * If not given, the default is to inherit the current working directory. If given, + * but the path does not exist, the child process emits an `ENOENT` error + * and exits immediately. `ENOENT` is also emitted when the command + * does not exist. + * + * Use `env` to specify environment variables that will be visible to the new + * process, the default is `process.env`. + * + * `undefined` values in `env` will be ignored. + * + * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the + * exit code: + * + * ```js + * import { spawn } from 'node:child_process'; + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * Example: A very elaborate way to run `ps ax | grep ssh` + * + * ```js + * import { spawn } from 'node:child_process'; + * const ps = spawn('ps', ['ax']); + * const grep = spawn('grep', ['ssh']); + * + * ps.stdout.on('data', (data) => { + * grep.stdin.write(data); + * }); + * + * ps.stderr.on('data', (data) => { + * console.error(`ps stderr: ${data}`); + * }); + * + * ps.on('close', (code) => { + * if (code !== 0) { + * console.log(`ps process exited with code ${code}`); + * } + * grep.stdin.end(); + * }); + * + * grep.stdout.on('data', (data) => { + * console.log(data.toString()); + * }); + * + * grep.stderr.on('data', (data) => { + * console.error(`grep stderr: ${data}`); + * }); + * + * grep.on('close', (code) => { + * if (code !== 0) { + * console.log(`grep process exited with code ${code}`); + * } + * }); + * ``` + * + * Example of checking for failed `spawn`: + * + * ```js + * import { spawn } from 'node:child_process'; + * const subprocess = spawn('bad_command'); + * + * subprocess.on('error', (err) => { + * console.error('Failed to start subprocess.'); + * }); + * ``` + * + * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process + * title while others (Windows, SunOS) will use `command`. + * + * Node.js overwrites `argv[0]` with `process.execPath` on startup, so `process.argv[0]` in a Node.js child process will not match the `argv0` parameter passed to `spawn` from the parent. Retrieve + * it with the `process.argv0` property instead. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { spawn } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const grep = spawn('grep', ['ssh'], { signal }); + * grep.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * ``` + * @since v0.1.90 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptions): ChildProcess; + // overloads of spawn with 'args' + function spawn( + command: string, + args?: readonly string[], + options?: SpawnOptionsWithoutStdio, + ): ChildProcessWithoutNullStreams; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, args: readonly string[], options: SpawnOptions): ChildProcess; + interface ExecOptions extends CommonOptions { + shell?: string | undefined; + signal?: AbortSignal | undefined; + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + encoding?: string | null | undefined; + } + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding?: BufferEncoding | undefined; + } + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: "buffer" | null; // specify `null`. + } + // TODO: Just Plain Wrong™ (see also nodejs/node#57392) + interface ExecException extends Error { + cmd?: string; + killed?: boolean; + code?: number; + signal?: NodeJS.Signals; + stdout?: string; + stderr?: string; + } + /** + * Spawns a shell then executes the `command` within that shell, buffering any + * generated output. The `command` string passed to the exec function is processed + * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) + * need to be dealt with accordingly: + * + * ```js + * import { exec } from 'node:child_process'; + * + * exec('"/path/to/test file/test.sh" arg1 arg2'); + * // Double quotes are used so that the space in the path is not interpreted as + * // a delimiter of multiple arguments. + * + * exec('echo "The \\$HOME variable is $HOME"'); + * // The $HOME variable is escaped in the first instance, but not in the second. + * ``` + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * + * If a `callback` function is provided, it is called with the arguments `(error, stdout, stderr)`. On success, `error` will be `null`. On error, `error` will be an instance of `Error`. The + * `error.code` property will be + * the exit code of the process. By convention, any exit code other than `0` indicates an error. `error.signal` will be the signal that terminated the + * process. + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * ```js + * import { exec } from 'node:child_process'; + * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { + * if (error) { + * console.error(`exec error: ${error}`); + * return; + * } + * console.log(`stdout: ${stdout}`); + * console.error(`stderr: ${stderr}`); + * }); + * ``` + * + * If `timeout` is greater than `0`, the parent will send the signal + * identified by the `killSignal` property (the default is `'SIGTERM'`) if the + * child runs longer than `timeout` milliseconds. + * + * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace + * the existing process and uses a shell to execute the command. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * import util from 'node:util'; + * import child_process from 'node:child_process'; + * const exec = util.promisify(child_process.exec); + * + * async function lsExample() { + * const { stdout, stderr } = await exec('ls'); + * console.log('stdout:', stdout); + * console.error('stderr:', stderr); + * } + * lsExample(); + * ``` + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { exec } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.90 + * @param command The command to run, with space-separated arguments. + * @param callback called with the output when process terminates. + */ + function exec( + command: string, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec( + command: string, + options: ExecOptionsWithBufferEncoding, + callback?: (error: ExecException | null, stdout: NonSharedBuffer, stderr: NonSharedBuffer) => void, + ): ChildProcess; + // `options` with well-known or absent `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: ExecOptionsWithStringEncoding, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: ExecOptions | undefined | null, + callback?: ( + error: ExecException | null, + stdout: string | NonSharedBuffer, + stderr: string | NonSharedBuffer, + ) => void, + ): ChildProcess; + interface PromiseWithChild extends Promise { + child: ChildProcess; + } + namespace exec { + function __promisify__(command: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: NonSharedBuffer; + stderr: NonSharedBuffer; + }>; + function __promisify__( + command: string, + options: ExecOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | NonSharedBuffer; + stderr: string | NonSharedBuffer; + }>; + } + interface ExecFileOptions extends CommonOptions, Abortable { + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + windowsVerbatimArguments?: boolean | undefined; + shell?: boolean | string | undefined; + signal?: AbortSignal | undefined; + encoding?: string | null | undefined; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding?: BufferEncoding | undefined; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: "buffer" | null; + } + /** @deprecated Use `ExecFileOptions` instead. */ + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions {} + // TODO: execFile exceptions can take many forms... this accurately describes none of them + type ExecFileException = + & Omit + & Omit + & { code?: string | number | null }; + /** + * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified + * executable `file` is spawned directly as a new process making it slightly more + * efficient than {@link exec}. + * + * The same options as {@link exec} are supported. Since a shell is + * not spawned, behaviors such as I/O redirection and file globbing are not + * supported. + * + * ```js + * import { execFile } from 'node:child_process'; + * const child = execFile('node', ['--version'], (error, stdout, stderr) => { + * if (error) { + * throw error; + * } + * console.log(stdout); + * }); + * ``` + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * import util from 'node:util'; + * import child_process from 'node:child_process'; + * const execFile = util.promisify(child_process.execFile); + * async function getVersion() { + * const { stdout } = await execFile('node', ['--version']); + * console.log(stdout); + * } + * getVersion(); + * ``` + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { execFile } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.91 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @param callback Called with the output when process terminates. + */ + // no `options` definitely means stdout/stderr are `string`. + function execFile( + file: string, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile( + file: string, + options: ExecFileOptionsWithBufferEncoding, + callback?: (error: ExecFileException | null, stdout: NonSharedBuffer, stderr: NonSharedBuffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback?: (error: ExecFileException | null, stdout: NonSharedBuffer, stderr: NonSharedBuffer) => void, + ): ChildProcess; + // `options` with well-known or absent `encoding` means stdout/stderr are definitely `string`. + function execFile( + file: string, + options: ExecFileOptionsWithStringEncoding, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: ExecFileOptions | undefined | null, + callback: + | (( + error: ExecFileException | null, + stdout: string | NonSharedBuffer, + stderr: string | NonSharedBuffer, + ) => void) + | undefined + | null, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions | undefined | null, + callback: + | (( + error: ExecFileException | null, + stdout: string | NonSharedBuffer, + stderr: string | NonSharedBuffer, + ) => void) + | undefined + | null, + ): ChildProcess; + namespace execFile { + function __promisify__(file: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: NonSharedBuffer; + stderr: NonSharedBuffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: NonSharedBuffer; + stderr: NonSharedBuffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | NonSharedBuffer; + stderr: string | NonSharedBuffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | NonSharedBuffer; + stderr: string | NonSharedBuffer; + }>; + } + interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { + execPath?: string | undefined; + execArgv?: string[] | undefined; + silent?: boolean | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + detached?: boolean | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + /** + * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. + * Like {@link spawn}, a `ChildProcess` object is returned. The + * returned `ChildProcess` will have an additional communication channel + * built-in that allows messages to be passed back and forth between the parent and + * child. See `subprocess.send()` for details. + * + * Keep in mind that spawned Node.js child processes are + * independent of the parent with exception of the IPC communication channel + * that is established between the two. Each process has its own memory, with + * their own V8 instances. Because of the additional resource allocations + * required, spawning a large number of child Node.js processes is not + * recommended. + * + * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the `options` object allows for an alternative + * execution path to be used. + * + * Node.js processes launched with a custom `execPath` will communicate with the + * parent process using the file descriptor (fd) identified using the + * environment variable `NODE_CHANNEL_FD` on the child process. + * + * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the + * current process. + * + * The `shell` option available in {@link spawn} is not supported by `child_process.fork()` and will be ignored if set. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * if (process.argv[2] === 'child') { + * setTimeout(() => { + * console.log(`Hello from ${process.argv[2]}!`); + * }, 1_000); + * } else { + * import { fork } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = fork(__filename, ['child'], { signal }); + * child.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * } + * ``` + * @since v0.5.0 + * @param modulePath The module to run in the child. + * @param args List of string arguments. + */ + function fork(modulePath: string | URL, options?: ForkOptions): ChildProcess; + function fork(modulePath: string | URL, args?: readonly string[], options?: ForkOptions): ChildProcess; + interface SpawnSyncOptions extends CommonSpawnOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding?: "buffer" | null | undefined; + } + interface SpawnSyncReturns { + pid: number; + output: Array; + stdout: T; + stderr: T; + status: number | null; + signal: NodeJS.Signals | null; + error?: Error; + } + /** + * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the process intercepts and handles the `SIGTERM` signal + * and doesn't exit, the parent process will wait until the child process has + * exited. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args: readonly string[]): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithStringEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithBufferEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args?: readonly string[], + options?: SpawnSyncOptions, + ): SpawnSyncReturns; + interface CommonExecOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + /** + * Can be set to 'pipe', 'inherit, or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + killSignal?: NodeJS.Signals | number | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface ExecSyncOptions extends CommonExecOptions { + shell?: string | undefined; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding?: "buffer" | null | undefined; + } + /** + * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the child process intercepts and handles the `SIGTERM` signal and doesn't exit, the parent process will wait until the child process + * has exited. + * + * If the process times out or has a non-zero exit code, this method will throw. + * The `Error` object will contain the entire result from {@link spawnSync}. + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @return The stdout from the command. + */ + function execSync(command: string): NonSharedBuffer; + function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): NonSharedBuffer; + function execSync(command: string, options?: ExecSyncOptions): string | NonSharedBuffer; + interface ExecFileSyncOptions extends CommonExecOptions { + shell?: boolean | string | undefined; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding?: "buffer" | null | undefined; // specify `null`. + } + /** + * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not + * return until the child process has fully closed. When a timeout has been + * encountered and `killSignal` is sent, the method won't return until the process + * has completely exited. + * + * If the child process intercepts and handles the `SIGTERM` signal and + * does not exit, the parent process will still wait until the child process has + * exited. + * + * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @return The stdout from the command. + */ + function execFileSync(file: string): NonSharedBuffer; + function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): NonSharedBuffer; + function execFileSync(file: string, options?: ExecFileSyncOptions): string | NonSharedBuffer; + function execFileSync(file: string, args: readonly string[]): NonSharedBuffer; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithStringEncoding, + ): string; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithBufferEncoding, + ): NonSharedBuffer; + function execFileSync( + file: string, + args?: readonly string[], + options?: ExecFileSyncOptions, + ): string | NonSharedBuffer; +} +declare module "node:child_process" { + export * from "child_process"; +} diff --git a/node_modules/@types/node/cluster.d.ts b/node_modules/@types/node/cluster.d.ts new file mode 100644 index 0000000..eab9783 --- /dev/null +++ b/node_modules/@types/node/cluster.d.ts @@ -0,0 +1,578 @@ +/** + * Clusters of Node.js processes can be used to run multiple instances of Node.js + * that can distribute workloads among their application threads. When process isolation + * is not needed, use the [`worker_threads`](https://nodejs.org/docs/latest-v22.x/api/worker_threads.html) + * module instead, which allows running multiple application threads within a single Node.js instance. + * + * The cluster module allows easy creation of child processes that all share + * server ports. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('exit', (worker, code, signal) => { + * console.log(`worker ${worker.process.pid} died`); + * }); + * } else { + * // Workers can share any TCP connection + * // In this case it is an HTTP server + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * + * console.log(`Worker ${process.pid} started`); + * } + * ``` + * + * Running Node.js will now share port 8000 between the workers: + * + * ```console + * $ node server.js + * Primary 3596 is running + * Worker 4324 started + * Worker 4520 started + * Worker 6056 started + * Worker 5644 started + * ``` + * + * On Windows, it is not yet possible to set up a named pipe server in a worker. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/cluster.js) + */ +declare module "cluster" { + import * as child from "node:child_process"; + import EventEmitter = require("node:events"); + import * as net from "node:net"; + type SerializationType = "json" | "advanced"; + export interface ClusterSettings { + /** + * List of string arguments passed to the Node.js executable. + * @default process.execArgv + */ + execArgv?: string[] | undefined; + /** + * File path to worker file. + * @default process.argv[1] + */ + exec?: string | undefined; + /** + * String arguments passed to worker. + * @default process.argv.slice(2) + */ + args?: readonly string[] | undefined; + /** + * Whether or not to send output to parent's stdio. + * @default false + */ + silent?: boolean | undefined; + /** + * Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must + * contain an `'ipc'` entry. When this option is provided, it overrides `silent`. See [`child_prcess.spawn()`](https://nodejs.org/docs/latest-v22.x/api/child_process.html#child_processspawncommand-args-options)'s + * [`stdio`](https://nodejs.org/docs/latest-v22.x/api/child_process.html#optionsstdio). + */ + stdio?: any[] | undefined; + /** + * Sets the user identity of the process. (See [`setuid(2)`](https://man7.org/linux/man-pages/man2/setuid.2.html).) + */ + uid?: number | undefined; + /** + * Sets the group identity of the process. (See [`setgid(2)`](https://man7.org/linux/man-pages/man2/setgid.2.html).) + */ + gid?: number | undefined; + /** + * Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. + * By default each worker gets its own port, incremented from the primary's `process.debugPort`. + */ + inspectPort?: number | (() => number) | undefined; + /** + * Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. + * See [Advanced serialization for `child_process`](https://nodejs.org/docs/latest-v22.x/api/child_process.html#advanced-serialization) for more details. + * @default false + */ + serialization?: SerializationType | undefined; + /** + * Current working directory of the worker process. + * @default undefined (inherits from parent process) + */ + cwd?: string | undefined; + /** + * Hide the forked processes console window that would normally be created on Windows systems. + * @default false + */ + windowsHide?: boolean | undefined; + } + export interface Address { + address: string; + port: number; + /** + * The `addressType` is one of: + * + * * `4` (TCPv4) + * * `6` (TCPv6) + * * `-1` (Unix domain socket) + * * `'udp4'` or `'udp6'` (UDPv4 or UDPv6) + */ + addressType: 4 | 6 | -1 | "udp4" | "udp6"; + } + /** + * A `Worker` object contains all public information and method about a worker. + * In the primary it can be obtained using `cluster.workers`. In a worker + * it can be obtained using `cluster.worker`. + * @since v0.7.0 + */ + export class Worker extends EventEmitter { + /** + * Each new worker is given its own unique id, this id is stored in the `id`. + * + * While a worker is alive, this is the key that indexes it in `cluster.workers`. + * @since v0.8.0 + */ + id: number; + /** + * All workers are created using [`child_process.fork()`](https://nodejs.org/docs/latest-v22.x/api/child_process.html#child_processforkmodulepath-args-options), the returned object + * from this function is stored as `.process`. In a worker, the global `process` is stored. + * + * See: [Child Process module](https://nodejs.org/docs/latest-v22.x/api/child_process.html#child_processforkmodulepath-args-options). + * + * Workers will call `process.exit(0)` if the `'disconnect'` event occurs + * on `process` and `.exitedAfterDisconnect` is not `true`. This protects against + * accidental disconnection. + * @since v0.7.0 + */ + process: child.ChildProcess; + /** + * Send a message to a worker or primary, optionally with a handle. + * + * In the primary, this sends a message to a specific worker. It is identical to [`ChildProcess.send()`](https://nodejs.org/docs/latest-v22.x/api/child_process.html#subprocesssendmessage-sendhandle-options-callback). + * + * In a worker, this sends a message to the primary. It is identical to `process.send()`. + * + * This example will echo back all messages from the primary: + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * worker.send('hi there'); + * + * } else if (cluster.isWorker) { + * process.on('message', (msg) => { + * process.send(msg); + * }); + * } + * ``` + * @since v0.7.0 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. + */ + send(message: child.Serializable, callback?: (error: Error | null) => void): boolean; + send( + message: child.Serializable, + sendHandle: child.SendHandle, + callback?: (error: Error | null) => void, + ): boolean; + send( + message: child.Serializable, + sendHandle: child.SendHandle, + options?: child.MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * This function will kill the worker. In the primary worker, it does this by + * disconnecting the `worker.process`, and once disconnected, killing with `signal`. In the worker, it does it by killing the process with `signal`. + * + * The `kill()` function kills the worker process without waiting for a graceful + * disconnect, it has the same behavior as `worker.process.kill()`. + * + * This method is aliased as `worker.destroy()` for backwards compatibility. + * + * In a worker, `process.kill()` exists, but it is not this function; + * it is [`kill()`](https://nodejs.org/docs/latest-v22.x/api/process.html#processkillpid-signal). + * @since v0.9.12 + * @param [signal='SIGTERM'] Name of the kill signal to send to the worker process. + */ + kill(signal?: string): void; + destroy(signal?: string): void; + /** + * In a worker, this function will close all servers, wait for the `'close'` event + * on those servers, and then disconnect the IPC channel. + * + * In the primary, an internal message is sent to the worker causing it to call `.disconnect()` on itself. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * After a server is closed, it will no longer accept new connections, + * but connections may be accepted by any other listening worker. Existing + * connections will be allowed to close as usual. When no more connections exist, + * see `server.close()`, the IPC channel to the worker will close allowing it + * to die gracefully. + * + * The above applies _only_ to server connections, client connections are not + * automatically closed by workers, and disconnect does not wait for them to close + * before exiting. + * + * In a worker, `process.disconnect` exists, but it is not this function; + * it is `disconnect()`. + * + * Because long living server connections may block workers from disconnecting, it + * may be useful to send a message, so application specific actions may be taken to + * close them. It also may be useful to implement a timeout, killing a worker if + * the `'disconnect'` event has not been emitted after some time. + * + * ```js + * import net from 'node:net'; + * + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * let timeout; + * + * worker.on('listening', (address) => { + * worker.send('shutdown'); + * worker.disconnect(); + * timeout = setTimeout(() => { + * worker.kill(); + * }, 2000); + * }); + * + * worker.on('disconnect', () => { + * clearTimeout(timeout); + * }); + * + * } else if (cluster.isWorker) { + * const server = net.createServer((socket) => { + * // Connections never end + * }); + * + * server.listen(8000); + * + * process.on('message', (msg) => { + * if (msg === 'shutdown') { + * // Initiate graceful close of any connections to server + * } + * }); + * } + * ``` + * @since v0.7.7 + * @return A reference to `worker`. + */ + disconnect(): this; + /** + * This function returns `true` if the worker is connected to its primary via its + * IPC channel, `false` otherwise. A worker is connected to its primary after it + * has been created. It is disconnected after the `'disconnect'` event is emitted. + * @since v0.11.14 + */ + isConnected(): boolean; + /** + * This function returns `true` if the worker's process has terminated (either + * because of exiting or being signaled). Otherwise, it returns `false`. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('fork', (worker) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * + * cluster.on('exit', (worker, code, signal) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * } else { + * // Workers can share any TCP connection. In this case, it is an HTTP server. + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end(`Current process\n ${process.pid}`); + * process.kill(process.pid); + * }).listen(8000); + * } + * ``` + * @since v0.11.14 + */ + isDead(): boolean; + /** + * This property is `true` if the worker exited due to `.disconnect()`. + * If the worker exited any other way, it is `false`. If the + * worker has not exited, it is `undefined`. + * + * The boolean `worker.exitedAfterDisconnect` allows distinguishing between + * voluntary and accidental exit, the primary may choose not to respawn a worker + * based on this value. + * + * ```js + * cluster.on('exit', (worker, code, signal) => { + * if (worker.exitedAfterDisconnect === true) { + * console.log('Oh, it was just voluntary – no need to worry'); + * } + * }); + * + * // kill worker + * worker.kill(); + * ``` + * @since v6.0.0 + */ + exitedAfterDisconnect: boolean; + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "listening", address: Address): boolean; + emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; + } + export interface Cluster extends EventEmitter { + disconnect(callback?: () => void): void; + /** + * Spawn a new worker process. + * + * This can only be called from the primary process. + * @param env Key/value pairs to add to worker process environment. + * @since v0.6.0 + */ + fork(env?: any): Worker; + /** @deprecated since v16.0.0 - use isPrimary. */ + readonly isMaster: boolean; + /** + * True if the process is a primary. This is determined by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` + * is undefined, then `isPrimary` is `true`. + * @since v16.0.0 + */ + readonly isPrimary: boolean; + /** + * True if the process is not a primary (it is the negation of `cluster.isPrimary`). + * @since v0.6.0 + */ + readonly isWorker: boolean; + /** + * The scheduling policy, either `cluster.SCHED_RR` for round-robin or `cluster.SCHED_NONE` to leave it to the operating system. This is a + * global setting and effectively frozen once either the first worker is spawned, or [`.setupPrimary()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clustersetupprimarysettings) + * is called, whichever comes first. + * + * `SCHED_RR` is the default on all operating systems except Windows. Windows will change to `SCHED_RR` once libuv is able to effectively distribute + * IOCP handles without incurring a large performance hit. + * + * `cluster.schedulingPolicy` can also be set through the `NODE_CLUSTER_SCHED_POLICY` environment variable. Valid values are `'rr'` and `'none'`. + * @since v0.11.2 + */ + schedulingPolicy: number; + /** + * After calling [`.setupPrimary()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clustersetupprimarysettings) + * (or [`.fork()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clusterforkenv)) this settings object will contain + * the settings, including the default values. + * + * This object is not intended to be changed or set manually. + * @since v0.7.1 + */ + readonly settings: ClusterSettings; + /** @deprecated since v16.0.0 - use [`.setupPrimary()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clustersetupprimarysettings) instead. */ + setupMaster(settings?: ClusterSettings): void; + /** + * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in `cluster.settings`. + * + * Any settings changes only affect future calls to [`.fork()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clusterforkenv) + * and have no effect on workers that are already running. + * + * The only attribute of a worker that cannot be set via `.setupPrimary()` is the `env` passed to + * [`.fork()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clusterforkenv). + * + * The defaults above apply to the first call only; the defaults for later calls are the current values at the time of + * `cluster.setupPrimary()` is called. + * + * ```js + * import cluster from 'node:cluster'; + * + * cluster.setupPrimary({ + * exec: 'worker.js', + * args: ['--use', 'https'], + * silent: true, + * }); + * cluster.fork(); // https worker + * cluster.setupPrimary({ + * exec: 'worker.js', + * args: ['--use', 'http'], + * }); + * cluster.fork(); // http worker + * ``` + * + * This can only be called from the primary process. + * @since v16.0.0 + */ + setupPrimary(settings?: ClusterSettings): void; + /** + * A reference to the current worker object. Not available in the primary process. + * + * ```js + * import cluster from 'node:cluster'; + * + * if (cluster.isPrimary) { + * console.log('I am primary'); + * cluster.fork(); + * cluster.fork(); + * } else if (cluster.isWorker) { + * console.log(`I am worker #${cluster.worker.id}`); + * } + * ``` + * @since v0.7.0 + */ + readonly worker?: Worker; + /** + * A hash that stores the active worker objects, keyed by `id` field. This makes it easy to loop through all the workers. It is only available in the primary process. + * + * A worker is removed from `cluster.workers` after the worker has disconnected _and_ exited. The order between these two events cannot be determined in advance. However, it + * is guaranteed that the removal from the `cluster.workers` list happens before the last `'disconnect'` or `'exit'` event is emitted. + * + * ```js + * import cluster from 'node:cluster'; + * + * for (const worker of Object.values(cluster.workers)) { + * worker.send('big announcement to all workers'); + * } + * ``` + * @since v0.7.0 + */ + readonly workers?: NodeJS.Dict; + readonly SCHED_NONE: number; + readonly SCHED_RR: number; + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect", worker: Worker): boolean; + emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + emit(event: "fork", worker: Worker): boolean; + emit(event: "listening", worker: Worker, address: Address): boolean; + emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online", worker: Worker): boolean; + emit(event: "setup", settings: ClusterSettings): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: ClusterSettings) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: ClusterSettings) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + } + const cluster: Cluster; + export default cluster; +} +declare module "node:cluster" { + export * from "cluster"; + export { default as default } from "cluster"; +} diff --git a/node_modules/@types/node/compatibility/disposable.d.ts b/node_modules/@types/node/compatibility/disposable.d.ts new file mode 100644 index 0000000..e23d5a7 --- /dev/null +++ b/node_modules/@types/node/compatibility/disposable.d.ts @@ -0,0 +1,14 @@ +// Polyfills for the explicit resource management types added in TypeScript 5.2. + +interface SymbolConstructor { + readonly dispose: unique symbol; + readonly asyncDispose: unique symbol; +} + +interface Disposable { + [Symbol.dispose](): void; +} + +interface AsyncDisposable { + [Symbol.asyncDispose](): PromiseLike; +} diff --git a/node_modules/@types/node/compatibility/index.d.ts b/node_modules/@types/node/compatibility/index.d.ts new file mode 100644 index 0000000..5c41e37 --- /dev/null +++ b/node_modules/@types/node/compatibility/index.d.ts @@ -0,0 +1,9 @@ +// Declaration files in this directory contain types relating to TypeScript library features +// that are not included in all TypeScript versions supported by DefinitelyTyped, but +// which can be made backwards-compatible without needing `typesVersions`. +// If adding declarations to this directory, please specify which versions of TypeScript require them, +// so that they can be removed when no longer needed. + +/// +/// +/// diff --git a/node_modules/@types/node/compatibility/indexable.d.ts b/node_modules/@types/node/compatibility/indexable.d.ts new file mode 100644 index 0000000..262ba09 --- /dev/null +++ b/node_modules/@types/node/compatibility/indexable.d.ts @@ -0,0 +1,20 @@ +// Polyfill for ES2022's .at() method on string/array prototypes, added to TypeScript in 4.6. + +interface RelativeIndexable { + at(index: number): T | undefined; +} + +interface String extends RelativeIndexable {} +interface Array extends RelativeIndexable {} +interface ReadonlyArray extends RelativeIndexable {} +interface Int8Array extends RelativeIndexable {} +interface Uint8Array extends RelativeIndexable {} +interface Uint8ClampedArray extends RelativeIndexable {} +interface Int16Array extends RelativeIndexable {} +interface Uint16Array extends RelativeIndexable {} +interface Int32Array extends RelativeIndexable {} +interface Uint32Array extends RelativeIndexable {} +interface Float32Array extends RelativeIndexable {} +interface Float64Array extends RelativeIndexable {} +interface BigInt64Array extends RelativeIndexable {} +interface BigUint64Array extends RelativeIndexable {} diff --git a/node_modules/@types/node/compatibility/iterators.d.ts b/node_modules/@types/node/compatibility/iterators.d.ts new file mode 100644 index 0000000..2f9be9c --- /dev/null +++ b/node_modules/@types/node/compatibility/iterators.d.ts @@ -0,0 +1,20 @@ +// Backwards-compatible iterator interfaces, augmented with iterator helper methods by lib.esnext.iterator in TypeScript 5.6. +// The IterableIterator interface does not contain these methods, which creates assignability issues in places where IteratorObjects +// are expected (eg. DOM-compatible APIs) if lib.esnext.iterator is loaded. +// Also ensures that iterators returned by the Node API, which inherit from Iterator.prototype, correctly expose the iterator helper methods +// if lib.esnext.iterator is loaded. + +// Placeholders for TS <5.6 +interface IteratorObject {} +interface AsyncIteratorObject {} + +declare namespace NodeJS { + // Populate iterator methods for TS <5.6 + interface Iterator extends globalThis.Iterator {} + interface AsyncIterator extends globalThis.AsyncIterator {} + + // Polyfill for TS 5.6's instrinsic BuiltinIteratorReturn type, required for DOM-compatible iterators + type BuiltinIteratorReturn = ReturnType extends + globalThis.Iterator ? TReturn + : any; +} diff --git a/node_modules/@types/node/console.d.ts b/node_modules/@types/node/console.d.ts new file mode 100644 index 0000000..3e4c2d9 --- /dev/null +++ b/node_modules/@types/node/console.d.ts @@ -0,0 +1,452 @@ +/** + * The `node:console` module provides a simple debugging console that is similar to + * the JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()`, and `console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/console.js) + */ +declare module "console" { + import console = require("node:console"); + export = console; +} +declare module "node:console" { + import { InspectOptions } from "node:util"; + global { + // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build + interface Console { + Console: console.ConsoleConstructor; + /** + * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only + * writes a message and does not otherwise affect execution. The output always + * starts with `"Assertion failed"`. If provided, `message` is formatted using + * [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args). + * + * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens. + * + * ```js + * console.assert(true, 'does nothing'); + * + * console.assert(false, 'Whoops %s work', 'didn\'t'); + * // Assertion failed: Whoops didn't work + * + * console.assert(); + * // Assertion failed + * ``` + * @since v0.1.101 + * @param value The value tested for being truthy. + * @param message All arguments besides `value` are used as error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the + * TTY. When `stdout` is not a TTY, this method does nothing. + * + * The specific operation of `console.clear()` can vary across operating systems + * and terminal types. For most Linux operating systems, `console.clear()` operates similarly to the `clear` shell command. On Windows, `console.clear()` will clear only the output in the + * current terminal viewport for the Node.js + * binary. + * @since v8.3.0 + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the + * number of times `console.count()` has been called with the given `label`. + * + * ```js + * > console.count() + * default: 1 + * undefined + * > console.count('default') + * default: 2 + * undefined + * > console.count('abc') + * abc: 1 + * undefined + * > console.count('xyz') + * xyz: 1 + * undefined + * > console.count('abc') + * abc: 2 + * undefined + * > console.count() + * default: 3 + * undefined + * > + * ``` + * @since v8.3.0 + * @param [label='default'] The display label for the counter. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + * + * ```js + * > console.count('abc'); + * abc: 1 + * undefined + * > console.countReset('abc'); + * undefined + * > console.count('abc'); + * abc: 1 + * undefined + * > + * ``` + * @since v8.3.0 + * @param [label='default'] The display label for the counter. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link log}. + * @since v8.0.0 + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses [`util.inspect()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilinspectobject-options) on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + * @since v0.1.101 + */ + dir(obj: any, options?: InspectOptions): void; + /** + * This method calls `console.log()` passing it the arguments received. + * This method does not produce any XML formatting. + * @since v8.0.0 + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) + * (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). + * + * ```js + * const code = 5; + * console.error('error #%d', code); + * // Prints: error #5, to stderr + * console.error('error', code); + * // Prints: error 5, to stderr + * ``` + * + * If formatting elements (e.g. `%d`) are not found in the first string then + * [`util.inspect()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilinspectobject-options) is called on each argument and the + * resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) + * for more information. + * @since v0.1.100 + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by spaces for `groupIndentation` length. + * + * If one or more `label`s are provided, those are printed first without the + * additional indentation. + * @since v8.5.0 + */ + group(...label: any[]): void; + /** + * An alias for {@link group}. + * @since v8.5.0 + */ + groupCollapsed(...label: any[]): void; + /** + * Decreases indentation of subsequent lines by spaces for `groupIndentation` length. + * @since v8.5.0 + */ + groupEnd(): void; + /** + * The `console.info()` function is an alias for {@link log}. + * @since v0.1.100 + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) + * (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). + * + * ```js + * const count = 5; + * console.log('count: %d', count); + * // Prints: count: 5, to stdout + * console.log('count:', count); + * // Prints: count: 5, to stdout + * ``` + * + * See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information. + * @since v0.1.100 + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * Try to construct a table with the columns of the properties of `tabularData` (or use `properties`) and rows of `tabularData` and log it. Falls back to just + * logging the argument if it can't be parsed as tabular. + * + * ```js + * // These can't be parsed as tabular data + * console.table(Symbol()); + * // Symbol() + * + * console.table(undefined); + * // undefined + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); + * // ┌─────────┬─────┬─────┐ + * // │ (index) │ a │ b │ + * // ├─────────┼─────┼─────┤ + * // │ 0 │ 1 │ 'Y' │ + * // │ 1 │ 'Z' │ 2 │ + * // └─────────┴─────┴─────┘ + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); + * // ┌─────────┬─────┐ + * // │ (index) │ a │ + * // ├─────────┼─────┤ + * // │ 0 │ 1 │ + * // │ 1 │ 'Z' │ + * // └─────────┴─────┘ + * ``` + * @since v10.0.0 + * @param properties Alternate properties for constructing the table. + */ + table(tabularData: any, properties?: readonly string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers + * are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in + * suitable time units to `stdout`. For example, if the elapsed + * time is 3869ms, `console.timeEnd()` displays "3.869s". + * @since v0.1.104 + * @param [label='default'] + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link time} and + * prints the result to `stdout`: + * + * ```js + * console.time('bunch-of-stuff'); + * // Do a bunch of stuff. + * console.timeEnd('bunch-of-stuff'); + * // Prints: bunch-of-stuff: 225.438ms + * ``` + * @since v0.1.104 + * @param [label='default'] + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link time}, prints + * the elapsed time and other `data` arguments to `stdout`: + * + * ```js + * console.time('process'); + * const value = expensiveProcess1(); // Returns 42 + * console.timeLog('process', value); + * // Prints "process: 365.227ms 42". + * doExpensiveProcess2(value); + * console.timeEnd('process'); + * ``` + * @since v10.7.0 + * @param [label='default'] + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string `'Trace: '`, followed by the [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) + * formatted message and stack trace to the current position in the code. + * + * ```js + * console.trace('Show me'); + * // Prints: (stack trace will vary based on where trace is called) + * // Trace: Show me + * // at repl:2:9 + * // at REPLServer.defaultEval (repl.js:248:27) + * // at bound (domain.js:287:14) + * // at REPLServer.runBound [as eval] (domain.js:300:12) + * // at REPLServer. (repl.js:412:12) + * // at emitOne (events.js:82:20) + * // at REPLServer.emit (events.js:169:7) + * // at REPLServer.Interface._onLine (readline.js:210:10) + * // at REPLServer.Interface._line (readline.js:549:8) + * // at REPLServer.Interface._ttyWrite (readline.js:826:14) + * ``` + * @since v0.1.104 + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The `console.warn()` function is an alias for {@link error}. + * @since v0.1.100 + */ + warn(message?: any, ...optionalParams: any[]): void; + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. The `console.profile()` + * method starts a JavaScript CPU profile with an optional label until {@link profileEnd} + * is called. The profile is then added to the Profile panel of the inspector. + * + * ```js + * console.profile('MyLabel'); + * // Some code + * console.profileEnd('MyLabel'); + * // Adds the profile 'MyLabel' to the Profiles panel of the inspector. + * ``` + * @since v8.0.0 + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. Stops the current + * JavaScript CPU profiling session if one has been started and prints the report to the + * Profiles panel of the inspector. See {@link profile} for an example. + * + * If this method is called without a label, the most recently started profile is stopped. + * @since v8.0.0 + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. The `console.timeStamp()` + * method adds an event with the label `'label'` to the Timeline panel of the inspector. + * @since v8.0.0 + */ + timeStamp(label?: string): void; + } + /** + * The `console` module provides a simple debugging console that is similar to the + * JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/console.js) + */ + namespace console { + interface ConsoleConstructorOptions { + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; + /** + * Ignore errors when writing to the underlying streams. + * @default true + */ + ignoreErrors?: boolean | undefined; + /** + * Set color support for this `Console` instance. Setting to true enables coloring while inspecting + * values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color + * support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the + * respective stream. This option can not be used, if `inspectOptions.colors` is set as well. + * @default auto + */ + colorMode?: boolean | "auto" | undefined; + /** + * Specifies options that are passed along to + * [`util.inspect()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilinspectobject-options). + */ + inspectOptions?: InspectOptions | undefined; + /** + * Set group indentation. + * @default 2 + */ + groupIndentation?: number | undefined; + } + interface ConsoleConstructor { + prototype: Console; + new(stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; + } + } + var console: Console; + } + export = globalThis.console; +} diff --git a/node_modules/@types/node/constants.d.ts b/node_modules/@types/node/constants.d.ts new file mode 100644 index 0000000..5685a9d --- /dev/null +++ b/node_modules/@types/node/constants.d.ts @@ -0,0 +1,21 @@ +/** + * @deprecated The `node:constants` module is deprecated. When requiring access to constants + * relevant to specific Node.js builtin modules, developers should instead refer + * to the `constants` property exposed by the relevant module. For instance, + * `require('node:fs').constants` and `require('node:os').constants`. + */ +declare module "constants" { + const constants: + & typeof import("node:os").constants.dlopen + & typeof import("node:os").constants.errno + & typeof import("node:os").constants.priority + & typeof import("node:os").constants.signals + & typeof import("node:fs").constants + & typeof import("node:crypto").constants; + export = constants; +} + +declare module "node:constants" { + import constants = require("constants"); + export = constants; +} diff --git a/node_modules/@types/node/crypto.d.ts b/node_modules/@types/node/crypto.d.ts new file mode 100644 index 0000000..9023805 --- /dev/null +++ b/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,4545 @@ +/** + * The `node:crypto` module provides cryptographic functionality that includes a + * set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify + * functions. + * + * ```js + * const { createHmac } = await import('node:crypto'); + * + * const secret = 'abcdefg'; + * const hash = createHmac('sha256', secret) + * .update('I love cupcakes') + * .digest('hex'); + * console.log(hash); + * // Prints: + * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/crypto.js) + */ +declare module "crypto" { + import { NonSharedBuffer } from "node:buffer"; + import * as stream from "node:stream"; + import { PeerCertificate } from "node:tls"; + /** + * SPKAC is a Certificate Signing Request mechanism originally implemented by + * Netscape and was specified formally as part of HTML5's `keygen` element. + * + * `` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects + * should not use this element anymore. + * + * The `node:crypto` module provides the `Certificate` class for working with SPKAC + * data. The most common usage is handling output generated by the HTML5 `` element. Node.js uses [OpenSSL's SPKAC + * implementation](https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html) internally. + * @since v0.11.8 + */ + class Certificate { + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const challenge = Certificate.exportChallenge(spkac); + * console.log(challenge.toString('utf8')); + * // Prints: the challenge as a UTF8 string + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The challenge component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportChallenge(spkac: BinaryLike): NonSharedBuffer; + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const publicKey = Certificate.exportPublicKey(spkac); + * console.log(publicKey); + * // Prints: the public key as + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The public key component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportPublicKey(spkac: BinaryLike, encoding?: string): NonSharedBuffer; + /** + * ```js + * import { Buffer } from 'node:buffer'; + * const { Certificate } = await import('node:crypto'); + * + * const spkac = getSpkacSomehow(); + * console.log(Certificate.verifySpkac(Buffer.from(spkac))); + * // Prints: true or false + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return `true` if the given `spkac` data structure is valid, `false` otherwise. + */ + static verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + /** + * @deprecated + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): NonSharedBuffer; + /** + * @deprecated + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): NonSharedBuffer; + /** + * @deprecated + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + } + namespace constants { + // https://nodejs.org/dist/latest-v22.x/docs/api/crypto.html#crypto-constants + const OPENSSL_VERSION_NUMBER: number; + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode for TLS v1.3 */ + const SSL_OP_ALLOW_NO_DHE_KEX: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's version identifier of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + /** Instructs OpenSSL to disable encrypt-then-MAC. */ + const SSL_OP_NO_ENCRYPT_THEN_MAC: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to disable renegotiation. */ + const SSL_OP_NO_RENEGOTIATION: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + /** Instructs OpenSSL to turn off SSL v2 */ + const SSL_OP_NO_SSLv2: number; + /** Instructs OpenSSL to turn off SSL v3 */ + const SSL_OP_NO_SSLv3: number; + /** Instructs OpenSSL to disable use of RFC4507bis tickets. */ + const SSL_OP_NO_TICKET: number; + /** Instructs OpenSSL to turn off TLS v1 */ + const SSL_OP_NO_TLSv1: number; + /** Instructs OpenSSL to turn off TLS v1.1 */ + const SSL_OP_NO_TLSv1_1: number; + /** Instructs OpenSSL to turn off TLS v1.2 */ + const SSL_OP_NO_TLSv1_2: number; + /** Instructs OpenSSL to turn off TLS v1.3 */ + const SSL_OP_NO_TLSv1_3: number; + /** Instructs OpenSSL server to prioritize ChaCha20-Poly1305 when the client does. This option has no effect if `SSL_OP_CIPHER_SERVER_PREFERENCE` is not enabled. */ + const SSL_OP_PRIORITIZE_CHACHA: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + interface HashOptions extends stream.TransformOptions { + /** + * For XOF hash functions such as `shake256`, the + * outputLength option can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + /** @deprecated since v10.0.0 */ + const fips: boolean; + /** + * Creates and returns a `Hash` object that can be used to generate hash digests + * using the given `algorithm`. Optional `options` argument controls stream + * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option + * can be used to specify the desired output length in bytes. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * Example: generating the sha256 sum of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHash, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hash = createHash('sha256'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hash.update(data); + * else { + * console.log(`${hash.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.92 + * @param options `stream.transform` options + */ + function createHash(algorithm: string, options?: HashOptions): Hash; + /** + * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. + * Optional `options` argument controls stream behavior. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is + * a `KeyObject`, its type must be `secret`. If it is a string, please consider `caveats when using strings as inputs to cryptographic APIs`. If it was + * obtained from a cryptographically secure source of entropy, such as {@link randomBytes} or {@link generateKey}, its length should not + * exceed the block size of `algorithm` (e.g., 512 bits for SHA-256). + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hmac.update(data); + * else { + * console.log(`${hmac.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; + // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings + type BinaryToTextEncoding = "base64" | "base64url" | "hex" | "binary"; + type CharacterEncoding = "utf8" | "utf-8" | "utf16le" | "utf-16le" | "latin1"; + type LegacyCharacterEncoding = "ascii" | "binary" | "ucs2" | "ucs-2"; + type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + /** + * The `Hash` class is a utility for creating hash digests of data. It can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed hash digest on the readable side, or + * * Using the `hash.update()` and `hash.digest()` methods to produce the + * computed hash. + * + * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hash` objects as streams: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hash.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * } + * }); + * + * hash.write('some data to hash'); + * hash.end(); + * ``` + * + * Example: Using `Hash` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { createHash } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * const input = createReadStream('test.js'); + * input.pipe(hash).setEncoding('hex').pipe(stdout); + * ``` + * + * Example: Using the `hash.update()` and `hash.digest()` methods: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('some data to hash'); + * console.log(hash.digest('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * ``` + * @since v0.1.92 + */ + class Hash extends stream.Transform { + private constructor(); + /** + * Creates a new `Hash` object that contains a deep copy of the internal state + * of the current `Hash` object. + * + * The optional `options` argument controls stream behavior. For XOF hash + * functions such as `'shake256'`, the `outputLength` option can be used to + * specify the desired output length in bytes. + * + * An error is thrown when an attempt is made to copy the `Hash` object after + * its `hash.digest()` method has been called. + * + * ```js + * // Calculate a rolling hash. + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('one'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('two'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('three'); + * console.log(hash.copy().digest('hex')); + * + * // Etc. + * ``` + * @since v13.1.0 + * @param options `stream.transform` options + */ + copy(options?: HashOptions): Hash; + /** + * Updates the hash content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hash; + update(data: string, inputEncoding: Encoding): Hash; + /** + * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method). + * If `encoding` is provided a string will be returned; otherwise + * a `Buffer` is returned. + * + * The `Hash` object can not be used again after `hash.digest()` method has been + * called. Multiple calls will cause an error to be thrown. + * @since v0.1.92 + * @param encoding The `encoding` of the return value. + */ + digest(): NonSharedBuffer; + digest(encoding: BinaryToTextEncoding): string; + } + /** + * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can + * be used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed HMAC digest on the readable side, or + * * Using the `hmac.update()` and `hmac.digest()` methods to produce the + * computed HMAC digest. + * + * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hmac` objects as streams: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hmac.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * } + * }); + * + * hmac.write('some data to hash'); + * hmac.end(); + * ``` + * + * Example: Using `Hmac` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream('test.js'); + * input.pipe(hmac).pipe(stdout); + * ``` + * + * Example: Using the `hmac.update()` and `hmac.digest()` methods: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + * @deprecated Since v20.13.0 Calling `Hmac` class directly with `Hmac()` or `new Hmac()` is deprecated due to being internals, not intended for public use. Please use the {@link createHmac} method to create Hmac instances. + */ + class Hmac extends stream.Transform { + private constructor(); + /** + * Updates the `Hmac` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hmac; + update(data: string, inputEncoding: Encoding): Hmac; + /** + * Calculates the HMAC digest of all of the data passed using `hmac.update()`. + * If `encoding` is + * provided a string is returned; otherwise a `Buffer` is returned; + * + * The `Hmac` object can not be used again after `hmac.digest()` has been + * called. Multiple calls to `hmac.digest()` will result in an error being thrown. + * @since v0.1.94 + * @param encoding The `encoding` of the return value. + */ + digest(): NonSharedBuffer; + digest(encoding: BinaryToTextEncoding): string; + } + type KeyObjectType = "secret" | "public" | "private"; + interface KeyExportOptions { + type: "pkcs1" | "spki" | "pkcs8" | "sec1"; + format: T; + cipher?: string | undefined; + passphrase?: string | Buffer | undefined; + } + interface JwkKeyExportOptions { + format: "jwk"; + } + interface JsonWebKey { + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + k?: string; + kty?: string; + n?: string; + p?: string; + q?: string; + qi?: string; + x?: string; + y?: string; + [key: string]: unknown; + } + interface AsymmetricKeyDetails { + /** + * Key size in bits (RSA, DSA). + */ + modulusLength?: number; + /** + * Public exponent (RSA). + */ + publicExponent?: bigint; + /** + * Name of the message digest (RSA-PSS). + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 (RSA-PSS). + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes (RSA-PSS). + */ + saltLength?: number; + /** + * Size of q in bits (DSA). + */ + divisorLength?: number; + /** + * Name of the curve (EC). + */ + namedCurve?: string; + } + /** + * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, + * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject` + * objects are not to be created directly using the `new`keyword. + * + * Most applications should consider using the new `KeyObject` API instead of + * passing keys as strings or `Buffer`s due to improved security features. + * + * `KeyObject` instances can be passed to other threads via `postMessage()`. + * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to + * be listed in the `transferList` argument. + * @since v11.6.0 + */ + class KeyObject { + private constructor(); + /** + * Example: Converting a `CryptoKey` instance to a `KeyObject`: + * + * ```js + * const { KeyObject } = await import('node:crypto'); + * const { subtle } = globalThis.crypto; + * + * const key = await subtle.generateKey({ + * name: 'HMAC', + * hash: 'SHA-256', + * length: 256, + * }, true, ['sign', 'verify']); + * + * const keyObject = KeyObject.from(key); + * console.log(keyObject.symmetricKeySize); + * // Prints: 32 (symmetric key size in bytes) + * ``` + * @since v15.0.0 + */ + static from(key: webcrypto.CryptoKey): KeyObject; + /** + * For asymmetric keys, this property represents the type of the key. Supported key + * types are: + * + * * `'rsa'` (OID 1.2.840.113549.1.1.1) + * * `'rsa-pss'` (OID 1.2.840.113549.1.1.10) + * * `'dsa'` (OID 1.2.840.10040.4.1) + * * `'ec'` (OID 1.2.840.10045.2.1) + * * `'x25519'` (OID 1.3.101.110) + * * `'x448'` (OID 1.3.101.111) + * * `'ed25519'` (OID 1.3.101.112) + * * `'ed448'` (OID 1.3.101.113) + * * `'dh'` (OID 1.2.840.113549.1.3.1) + * + * This property is `undefined` for unrecognized `KeyObject` types and symmetric + * keys. + * @since v11.6.0 + */ + asymmetricKeyType?: KeyType; + /** + * This property exists only on asymmetric keys. Depending on the type of the key, + * this object contains information about the key. None of the information obtained + * through this property can be used to uniquely identify a key or to compromise + * the security of the key. + * + * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence, + * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be + * set. + * + * Other key details might be exposed via this API using additional attributes. + * @since v15.7.0 + */ + asymmetricKeyDetails?: AsymmetricKeyDetails; + /** + * For symmetric keys, the following encoding options can be used: + * + * For public keys, the following encoding options can be used: + * + * For private keys, the following encoding options can be used: + * + * The result type depends on the selected encoding format, when PEM the + * result is a string, when DER it will be a buffer containing the data + * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. + * + * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are + * ignored. + * + * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of + * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be + * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for + * encrypted private keys. Since PKCS#8 defines its own + * encryption mechanism, PEM-level encryption is not supported when encrypting + * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for + * PKCS#1 and SEC1 encryption. + * @since v11.6.0 + */ + export(options: KeyExportOptions<"pem">): string | NonSharedBuffer; + export(options?: KeyExportOptions<"der">): NonSharedBuffer; + export(options?: JwkKeyExportOptions): JsonWebKey; + /** + * Returns `true` or `false` depending on whether the keys have exactly the same + * type, value, and parameters. This method is not [constant time](https://en.wikipedia.org/wiki/Timing_attack). + * @since v17.7.0, v16.15.0 + * @param otherKeyObject A `KeyObject` with which to compare `keyObject`. + */ + equals(otherKeyObject: KeyObject): boolean; + /** + * For secret keys, this property represents the size of the key in bytes. This + * property is `undefined` for asymmetric keys. + * @since v11.6.0 + */ + symmetricKeySize?: number; + /** + * Converts a `KeyObject` instance to a `CryptoKey`. + * @since 22.10.0 + */ + toCryptoKey( + algorithm: + | webcrypto.AlgorithmIdentifier + | webcrypto.RsaHashedImportParams + | webcrypto.EcKeyImportParams + | webcrypto.HmacImportParams, + extractable: boolean, + keyUsages: readonly webcrypto.KeyUsage[], + ): webcrypto.CryptoKey; + /** + * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys + * or `'private'` for private (asymmetric) keys. + * @since v11.6.0 + */ + type: KeyObjectType; + } + type CipherCCMTypes = "aes-128-ccm" | "aes-192-ccm" | "aes-256-ccm"; + type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"; + type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb"; + type CipherChaCha20Poly1305Types = "chacha20-poly1305"; + type BinaryLike = string | NodeJS.ArrayBufferView; + type CipherKey = BinaryLike | KeyObject; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number | undefined; + } + interface CipherOCBOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherChaCha20Poly1305Options extends stream.TransformOptions { + /** @default 16 */ + authTagLength?: number | undefined; + } + /** + * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and + * initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a + * given IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createCipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): CipherCCM; + function createCipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): CipherOCB; + function createCipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): CipherGCM; + function createCipheriv( + algorithm: CipherChaCha20Poly1305Types, + key: CipherKey, + iv: BinaryLike, + options?: CipherChaCha20Poly1305Options, + ): CipherChaCha20Poly1305; + function createCipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Cipher; + /** + * Instances of the `Cipher` class are used to encrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain unencrypted + * data is written to produce encrypted data on the readable side, or + * * Using the `cipher.update()` and `cipher.final()` methods to produce + * the encrypted data. + * + * The {@link createCipheriv} method is + * used to create `Cipher` instances. `Cipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipher` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * // Once we have the key and iv, we can create and use the cipher... + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = ''; + * cipher.setEncoding('hex'); + * + * cipher.on('data', (chunk) => encrypted += chunk); + * cipher.on('end', () => console.log(encrypted)); + * + * cipher.write('some clear text data'); + * cipher.end(); + * }); + * }); + * ``` + * + * Example: Using `Cipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * + * import { + * pipeline, + * } from 'node:stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.js'); + * const output = createWriteStream('test.enc'); + * + * pipeline(input, cipher, output, (err) => { + * if (err) throw err; + * }); + * }); + * }); + * ``` + * + * Example: Using the `cipher.update()` and `cipher.final()` methods: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); + * encrypted += cipher.final('hex'); + * console.log(encrypted); + * }); + * }); + * ``` + * @since v0.1.94 + */ + class Cipher extends stream.Transform { + private constructor(); + /** + * Updates the cipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or `DataView`. If `data` is a `Buffer`, + * `TypedArray`, or `DataView`, then `inputEncoding` is ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being + * thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the data. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: BinaryLike): NonSharedBuffer; + update(data: string, inputEncoding: Encoding): NonSharedBuffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `cipher.final()` method has been called, the `Cipher` object can no + * longer be used to encrypt data. Attempts to call `cipher.final()` more than + * once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): NonSharedBuffer; + final(outputEncoding: BufferEncoding): string; + /** + * When using block encryption algorithms, the `Cipher` class will automatically + * add padding to the input data to the appropriate block size. To disable the + * default padding call `cipher.setAutoPadding(false)`. + * + * When `autoPadding` is `false`, the length of the entire input data must be a + * multiple of the cipher's block size or `cipher.final()` will throw an error. + * Disabling automatic padding is useful for non-standard padding, for instance + * using `0x0` instead of PKCS padding. + * + * The `cipher.setAutoPadding()` method must be called before `cipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(autoPadding?: boolean): this; + } + interface CipherCCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): NonSharedBuffer; + } + interface CipherGCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): NonSharedBuffer; + } + interface CipherOCB extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): NonSharedBuffer; + } + interface CipherChaCha20Poly1305 extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): NonSharedBuffer; + } + /** + * Creates and returns a `Decipher` object that uses the given `algorithm`, `key` and initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the `authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength` option is not required but can be used to restrict accepted authentication tags + * to those with the specified length. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a given + * IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createDecipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): DecipherCCM; + function createDecipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): DecipherOCB; + function createDecipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): DecipherGCM; + function createDecipheriv( + algorithm: CipherChaCha20Poly1305Types, + key: CipherKey, + iv: BinaryLike, + options?: CipherChaCha20Poly1305Options, + ): DecipherChaCha20Poly1305; + function createDecipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Decipher; + /** + * Instances of the `Decipher` class are used to decrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain encrypted + * data is written to produce unencrypted data on the readable side, or + * * Using the `decipher.update()` and `decipher.final()` methods to + * produce the unencrypted data. + * + * The {@link createDecipheriv} method is + * used to create `Decipher` instances. `Decipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipher` objects as streams: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Key length is dependent on the algorithm. In this case for aes192, it is + * // 24 bytes (192 bits). + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * let decrypted = ''; + * decipher.on('readable', () => { + * let chunk; + * while (null !== (chunk = decipher.read())) { + * decrypted += chunk.toString('utf8'); + * } + * }); + * decipher.on('end', () => { + * console.log(decrypted); + * // Prints: some clear text data + * }); + * + * // Encrypted with same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * decipher.write(encrypted, 'hex'); + * decipher.end(); + * ``` + * + * Example: Using `Decipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.enc'); + * const output = createWriteStream('test.js'); + * + * input.pipe(decipher).pipe(output); + * ``` + * + * Example: Using the `decipher.update()` and `decipher.final()` methods: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * // Encrypted using same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * let decrypted = decipher.update(encrypted, 'hex', 'utf8'); + * decrypted += decipher.final('utf8'); + * console.log(decrypted); + * // Prints: some clear text data + * ``` + * @since v0.1.94 + */ + class Decipher extends stream.Transform { + private constructor(); + /** + * Updates the decipher with `data`. If the `inputEncoding` argument is given, + * the `data` argument is a string using the specified encoding. If the `inputEncoding` argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is + * ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding` is specified, a string using the specified encoding is returned. If no `outputEncoding` is provided, a `Buffer` is returned. + * + * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error + * being thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: NodeJS.ArrayBufferView): NonSharedBuffer; + update(data: string, inputEncoding: Encoding): NonSharedBuffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `decipher.final()` method has been called, the `Decipher` object can + * no longer be used to decrypt data. Attempts to call `decipher.final()` more + * than once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): NonSharedBuffer; + final(outputEncoding: BufferEncoding): string; + /** + * When data has been encrypted without standard block padding, calling `decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and + * removing padding. + * + * Turning auto padding off will only work if the input data's length is a + * multiple of the ciphers block size. + * + * The `decipher.setAutoPadding()` method must be called before `decipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(auto_padding?: boolean): this; + } + interface DecipherCCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface DecipherGCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherOCB extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherChaCha20Poly1305 extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "pkcs8" | "sec1" | undefined; + passphrase?: string | Buffer | undefined; + encoding?: string | undefined; + } + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "spki" | undefined; + encoding?: string | undefined; + } + /** + * Asynchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKey, + * } = await import('node:crypto'); + * + * generateKey('hmac', { length: 512 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKey( + type: "hmac" | "aes", + options: { + length: number; + }, + callback: (err: Error | null, key: KeyObject) => void, + ): void; + /** + * Synchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKeySync, + * } = await import('node:crypto'); + * + * const key = generateKeySync('hmac', { length: 512 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKeySync( + type: "hmac" | "aes", + options: { + length: number; + }, + ): KeyObject; + interface JsonWebKeyInput { + key: JsonWebKey; + format: "jwk"; + } + /** + * Creates and returns a new key object containing a private key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key` must be an object with the properties described above. + * + * If the private key is encrypted, a `passphrase` must be specified. The length + * of the passphrase is limited to 1024 bytes. + * @since v11.6.0 + */ + function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a public key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject` with type `'private'`, the public key is derived from the given private key; + * otherwise, `key` must be an object with the properties described above. + * + * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. + * + * Because public keys can be derived from private keys, a private key may be + * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the + * returned `KeyObject` will be `'public'` and that the private key cannot be + * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type `'private'` is given, a new `KeyObject` with type `'public'` will be returned + * and it will be impossible to extract the private key from the returned object. + * @since v11.6.0 + */ + function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a secret key for symmetric + * encryption or `Hmac`. + * @since v11.6.0 + * @param encoding The string encoding when `key` is a string. + */ + function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; + function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; + /** + * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms. + * Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Sign` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createSign(algorithm: string, options?: stream.WritableOptions): Sign; + type DSAEncoding = "der" | "ieee-p1363"; + interface SigningOptions { + /** + * @see crypto.constants.RSA_PKCS1_PADDING + */ + padding?: number | undefined; + saltLength?: number | undefined; + dsaEncoding?: DSAEncoding | undefined; + } + interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} + interface SignKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface SignJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} + interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} + interface VerifyKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} + type KeyLike = string | Buffer | KeyObject; + /** + * The `Sign` class is a utility for generating signatures. It can be used in one + * of two ways: + * + * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or + * * Using the `sign.update()` and `sign.sign()` methods to produce the + * signature. + * + * The {@link createSign} method is used to create `Sign` instances. The + * argument is the string name of the hash function to use. `Sign` objects are not + * to be created directly using the `new` keyword. + * + * Example: Using `Sign` and `Verify` objects as streams: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('ec', { + * namedCurve: 'sect239k1', + * }); + * + * const sign = createSign('SHA256'); + * sign.write('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey, 'hex'); + * + * const verify = createVerify('SHA256'); + * verify.write('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature, 'hex')); + * // Prints: true + * ``` + * + * Example: Using the `sign.update()` and `verify.update()` methods: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('rsa', { + * modulusLength: 2048, + * }); + * + * const sign = createSign('SHA256'); + * sign.update('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey); + * + * const verify = createVerify('SHA256'); + * verify.update('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature)); + * // Prints: true + * ``` + * @since v0.1.92 + */ + class Sign extends stream.Writable { + private constructor(); + /** + * Updates the `Sign` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): this; + update(data: string, inputEncoding: Encoding): this; + /** + * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the following additional properties can be passed: + * + * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * The `Sign` object can not be again used after `sign.sign()` method has been + * called. Multiple calls to `sign.sign()` will result in an error being thrown. + * @since v0.1.92 + */ + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput): NonSharedBuffer; + sign( + privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + outputFormat: BinaryToTextEncoding, + ): string; + } + /** + * Creates and returns a `Verify` object that uses the given algorithm. + * Use {@link getHashes} to obtain an array of names of the available + * signing algorithms. Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Verify` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; + /** + * The `Verify` class is a utility for verifying signatures. It can be used in one + * of two ways: + * + * * As a writable `stream` where written data is used to validate against the + * supplied signature, or + * * Using the `verify.update()` and `verify.verify()` methods to verify + * the signature. + * + * The {@link createVerify} method is used to create `Verify` instances. `Verify` objects are not to be created directly using the `new` keyword. + * + * See `Sign` for examples. + * @since v0.1.92 + */ + class Verify extends stream.Writable { + private constructor(); + /** + * Updates the `Verify` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `inputEncoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or `DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Verify; + update(data: string, inputEncoding: Encoding): Verify; + /** + * Verifies the provided data using the given `object` and `signature`. + * + * If `object` is not a `KeyObject`, this function behaves as if `object` had been passed to {@link createPublicKey}. If it is an + * object, the following additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the data, in + * the `signatureEncoding`. + * If a `signatureEncoding` is specified, the `signature` is expected to be a + * string; otherwise `signature` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * The `verify` object can not be used again after `verify.verify()` has been + * called. Multiple calls to `verify.verify()` will result in an error being + * thrown. + * + * Because public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.1.92 + */ + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: string, + signature_format?: BinaryToTextEncoding, + ): boolean; + } + /** + * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an + * optional specific `generator`. + * + * The `generator` argument can be a number, string, or `Buffer`. If `generator` is not specified, the value `2` is used. + * + * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise + * a `Buffer`, `TypedArray`, or `DataView` is expected. + * + * If `generatorEncoding` is specified, `generator` is expected to be a string; + * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected. + * @since v0.11.12 + * @param primeEncoding The `encoding` of the `prime` string. + * @param [generator=2] + * @param generatorEncoding The `encoding` of the `generator` string. + */ + function createDiffieHellman(primeLength: number, generator?: number): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + /** + * The `DiffieHellman` class is a utility for creating Diffie-Hellman key + * exchanges. + * + * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createDiffieHellman, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createDiffieHellman(2048); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * // OK + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * ``` + * @since v0.5.0 + */ + class DiffieHellman { + private constructor(); + /** + * Generates private and public Diffie-Hellman key values unless they have been + * generated or computed already, and returns + * the public key in the specified `encoding`. This key should be + * transferred to the other party. + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * This function is a thin wrapper around [`DH_generate_key()`](https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html). In particular, + * once a private key has been generated or set, calling this function only updates + * the public key but does not generate a new private key. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + generateKeys(): NonSharedBuffer; + generateKeys(encoding: BinaryToTextEncoding): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using the specified `inputEncoding`, and secret is + * encoded using specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. + * @since v0.5.0 + * @param inputEncoding The `encoding` of an `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret( + otherPublicKey: NodeJS.ArrayBufferView, + inputEncoding?: null, + outputEncoding?: null, + ): NonSharedBuffer; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding?: null, + ): NonSharedBuffer; + computeSecret( + otherPublicKey: NodeJS.ArrayBufferView, + inputEncoding: null, + outputEncoding: BinaryToTextEncoding, + ): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * Returns the Diffie-Hellman prime in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrime(): NonSharedBuffer; + getPrime(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman generator in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getGenerator(): NonSharedBuffer; + getGenerator(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman public key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPublicKey(): NonSharedBuffer; + getPublicKey(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman private key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrivateKey(): NonSharedBuffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * Sets the Diffie-Hellman public key. If the `encoding` argument is provided, `publicKey` is expected + * to be a string. If no `encoding` is provided, `publicKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `publicKey` string. + */ + setPublicKey(publicKey: NodeJS.ArrayBufferView): void; + setPublicKey(publicKey: string, encoding: BufferEncoding): void; + /** + * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected + * to be a string. If no `encoding` is provided, `privateKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * + * This function does not automatically compute the associated public key. Either `diffieHellman.setPublicKey()` or `diffieHellman.generateKeys()` can be + * used to manually provide the public key or to automatically derive it. + * @since v0.5.0 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BufferEncoding): void; + /** + * A bit field containing any warnings and/or errors resulting from a check + * performed during initialization of the `DiffieHellman` object. + * + * The following values are valid for this property (as defined in `node:constants` module): + * + * * `DH_CHECK_P_NOT_SAFE_PRIME` + * * `DH_CHECK_P_NOT_PRIME` + * * `DH_UNABLE_TO_CHECK_GENERATOR` + * * `DH_NOT_SUITABLE_GENERATOR` + * @since v0.11.12 + */ + verifyError: number; + } + /** + * The `DiffieHellmanGroup` class takes a well-known modp group as its argument. + * It works the same as `DiffieHellman`, except that it does not allow changing its keys after creation. + * In other words, it does not implement `setPublicKey()` or `setPrivateKey()` methods. + * + * ```js + * const { createDiffieHellmanGroup } = await import('node:crypto'); + * const dh = createDiffieHellmanGroup('modp1'); + * ``` + * The name (e.g. `'modp1'`) is taken from [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt) (modp1 and 2) and [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt): + * ```bash + * $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h + * modp1 # 768 bits + * modp2 # 1024 bits + * modp5 # 1536 bits + * modp14 # 2048 bits + * modp15 # etc. + * modp16 + * modp17 + * modp18 + * ``` + * @since v0.7.5 + */ + const DiffieHellmanGroup: DiffieHellmanGroupConstructor; + interface DiffieHellmanGroupConstructor { + new(name: string): DiffieHellmanGroup; + (name: string): DiffieHellmanGroup; + readonly prototype: DiffieHellmanGroup; + } + type DiffieHellmanGroup = Omit; + /** + * Creates a predefined `DiffieHellmanGroup` key exchange object. The + * supported groups are listed in the documentation for `DiffieHellmanGroup`. + * + * The returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * the keys (with `diffieHellman.setPublicKey()`, for example). The + * advantage of using this method is that the parties do not have to + * generate nor exchange a group modulus beforehand, saving both processor + * and communication time. + * + * Example (obtaining a shared secret): + * + * ```js + * const { + * getDiffieHellman, + * } = await import('node:crypto'); + * const alice = getDiffieHellman('modp14'); + * const bob = getDiffieHellman('modp14'); + * + * alice.generateKeys(); + * bob.generateKeys(); + * + * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); + * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); + * + * // aliceSecret and bobSecret should be the same + * console.log(aliceSecret === bobSecret); + * ``` + * @since v0.7.5 + */ + function getDiffieHellman(groupName: string): DiffieHellmanGroup; + /** + * An alias for {@link getDiffieHellman} + * @since v0.9.3 + */ + function createDiffieHellmanGroup(name: string): DiffieHellmanGroup; + /** + * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. + * + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated `derivedKey` will be passed to the callback as a `Buffer`. An error will be + * thrown if any of the input arguments specify invalid values or types. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2, + * } = await import('node:crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * @since v0.5.5 + */ + function pbkdf2( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + callback: (err: Error | null, derivedKey: NonSharedBuffer) => void, + ): void; + /** + * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. + * + * If an error occurs an `Error` will be thrown, otherwise the derived key will be + * returned as a `Buffer`. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2Sync, + * } = await import('node:crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * @since v0.9.3 + */ + function pbkdf2Sync( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + ): NonSharedBuffer; + /** + * Generates cryptographically strong pseudorandom data. The `size` argument + * is a number indicating the number of bytes to generate. + * + * If a `callback` function is provided, the bytes are generated asynchronously + * and the `callback` function is invoked with two arguments: `err` and `buf`. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The `buf` argument is a `Buffer` containing the generated bytes. + * + * ```js + * // Asynchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * randomBytes(256, (err, buf) => { + * if (err) throw err; + * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); + * }); + * ``` + * + * If the `callback` function is not provided, the random bytes are generated + * synchronously and returned as a `Buffer`. An error will be thrown if + * there is a problem generating the bytes. + * + * ```js + * // Synchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * const buf = randomBytes(256); + * console.log( + * `${buf.length} bytes of random data: ${buf.toString('hex')}`); + * ``` + * + * The `crypto.randomBytes()` method will not complete until there is + * sufficient entropy available. + * This should normally never take longer than a few milliseconds. The only time + * when generating the random bytes may conceivably block for a longer period of + * time is right after boot, when the whole system is still low on entropy. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomBytes()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomBytes` requests when doing so as part of fulfilling a client + * request. + * @since v0.5.8 + * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. + * @return if the `callback` function is not provided. + */ + function randomBytes(size: number): NonSharedBuffer; + function randomBytes(size: number, callback: (err: Error | null, buf: NonSharedBuffer) => void): void; + function pseudoRandomBytes(size: number): NonSharedBuffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: NonSharedBuffer) => void): void; + /** + * Return a random integer `n` such that `min <= n < max`. This + * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). + * + * The range (`max - min`) must be less than 2**48. `min` and `max` must + * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + * + * If the `callback` function is not provided, the random integer is + * generated synchronously. + * + * ```js + * // Asynchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * randomInt(3, (err, n) => { + * if (err) throw err; + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * }); + * ``` + * + * ```js + * // Synchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(1, 7); + * console.log(`The dice rolled: ${n}`); + * ``` + * @since v14.10.0, v12.19.0 + * @param [min=0] Start of random range (inclusive). + * @param max End of random range (exclusive). + * @param callback `function(err, n) {}`. + */ + function randomInt(max: number): number; + function randomInt(min: number, max: number): number; + function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; + function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; + /** + * Synchronous version of {@link randomFill}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * console.log(randomFillSync(buf).toString('hex')); + * + * randomFillSync(buf, 5); + * console.log(buf.toString('hex')); + * + * // The above is equivalent to the following: + * randomFillSync(buf, 5, 5); + * console.log(buf.toString('hex')); + * ``` + * + * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * console.log(Buffer.from(randomFillSync(a).buffer, + * a.byteOffset, a.byteLength).toString('hex')); + * + * const b = new DataView(new ArrayBuffer(10)); + * console.log(Buffer.from(randomFillSync(b).buffer, + * b.byteOffset, b.byteLength).toString('hex')); + * + * const c = new ArrayBuffer(10); + * console.log(Buffer.from(randomFillSync(c)).toString('hex')); + * ``` + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @return The object passed as `buffer` argument. + */ + function randomFillSync(buffer: T, offset?: number, size?: number): T; + /** + * This function is similar to {@link randomBytes} but requires the first + * argument to be a `Buffer` that will be filled. It also + * requires that a callback is passed in. + * + * If the `callback` function is not provided, an error will be thrown. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * randomFill(buf, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * randomFill(buf, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * // The above is equivalent to the following: + * randomFill(buf, 5, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * ``` + * + * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as `buffer`. + * + * While this includes instances of `Float32Array` and `Float64Array`, this + * function should not be used to generate random floating-point numbers. The + * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array + * contains finite numbers only, they are not drawn from a uniform random + * distribution and have no meaningful lower or upper bounds. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * randomFill(a, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const b = new DataView(new ArrayBuffer(10)); + * randomFill(b, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const c = new ArrayBuffer(10); + * randomFill(c, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf).toString('hex')); + * }); + * ``` + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomFill()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomFill` requests when doing so as part of fulfilling a client + * request. + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @param callback `function(err, buf) {}`. + */ + function randomFill( + buffer: T, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + size: number, + callback: (err: Error | null, buf: T) => void, + ): void; + interface ScryptOptions { + cost?: number | undefined; + blockSize?: number | undefined; + parallelization?: number | undefined; + N?: number | undefined; + r?: number | undefined; + p?: number | undefined; + maxmem?: number | undefined; + } + /** + * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * The `callback` function is called with two arguments: `err` and `derivedKey`. `err` is an exception object when key derivation fails, otherwise `err` is `null`. `derivedKey` is passed to the + * callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scrypt, + * } = await import('node:crypto'); + * + * // Using the factory defaults. + * scrypt('password', 'salt', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * // Using a custom N parameter. Must be a power of two. + * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' + * }); + * ``` + * @since v10.5.0 + */ + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: NonSharedBuffer) => void, + ): void; + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options: ScryptOptions, + callback: (err: Error | null, derivedKey: NonSharedBuffer) => void, + ): void; + /** + * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scryptSync, + * } = await import('node:crypto'); + * // Using the factory defaults. + * + * const key1 = scryptSync('password', 'salt', 64); + * console.log(key1.toString('hex')); // '3745e48...08d59ae' + * // Using a custom N parameter. Must be a power of two. + * const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); + * console.log(key2.toString('hex')); // '3745e48...aa39b34' + * ``` + * @since v10.5.0 + */ + function scryptSync( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options?: ScryptOptions, + ): NonSharedBuffer; + interface RsaPublicKey { + key: KeyLike; + padding?: number | undefined; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string | undefined; + /** + * @default 'sha1' + */ + oaepHash?: string | undefined; + oaepLabel?: NodeJS.TypedArray | undefined; + padding?: number | undefined; + } + /** + * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using + * the corresponding private key, for example using {@link privateDecrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.11.14 + */ + function publicEncrypt( + key: RsaPublicKey | RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): NonSharedBuffer; + /** + * Decrypts `buffer` with `key`.`buffer` was previously encrypted using + * the corresponding private key, for example using {@link privateEncrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v1.1.0 + */ + function publicDecrypt( + key: RsaPublicKey | RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): NonSharedBuffer; + /** + * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using + * the corresponding public key, for example using {@link publicEncrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. + * @since v0.11.14 + */ + function privateDecrypt( + privateKey: RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): NonSharedBuffer; + /** + * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using + * the corresponding public key, for example using {@link publicDecrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. + * @since v1.1.0 + */ + function privateEncrypt( + privateKey: RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): NonSharedBuffer; + /** + * ```js + * const { + * getCiphers, + * } = await import('node:crypto'); + * + * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] + * ``` + * @since v0.9.3 + * @return An array with the names of the supported cipher algorithms. + */ + function getCiphers(): string[]; + /** + * ```js + * const { + * getCurves, + * } = await import('node:crypto'); + * + * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] + * ``` + * @since v2.3.0 + * @return An array with the names of the supported elliptic curves. + */ + function getCurves(): string[]; + /** + * @since v10.0.0 + * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}. + */ + function getFips(): 1 | 0; + /** + * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. + * Throws an error if FIPS mode is not available. + * @since v10.0.0 + * @param bool `true` to enable FIPS mode. + */ + function setFips(bool: boolean): void; + /** + * ```js + * const { + * getHashes, + * } = await import('node:crypto'); + * + * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] + * ``` + * @since v0.9.3 + * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. + */ + function getHashes(): string[]; + /** + * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) + * key exchanges. + * + * Instances of the `ECDH` class can be created using the {@link createECDH} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createECDH, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createECDH('secp521r1'); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createECDH('secp521r1'); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * // OK + * ``` + * @since v0.11.14 + */ + class ECDH { + private constructor(); + /** + * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the + * format specified by `format`. The `format` argument specifies point encoding + * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is + * interpreted using the specified `inputEncoding`, and the returned key is encoded + * using the specified `outputEncoding`. + * + * Use {@link getCurves} to obtain a list of available curve names. + * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display + * the name and description of each available elliptic curve. + * + * If `format` is not specified the point will be returned in `'uncompressed'` format. + * + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * Example (uncompressing a key): + * + * ```js + * const { + * createECDH, + * ECDH, + * } = await import('node:crypto'); + * + * const ecdh = createECDH('secp256k1'); + * ecdh.generateKeys(); + * + * const compressedKey = ecdh.getPublicKey('hex', 'compressed'); + * + * const uncompressedKey = ECDH.convertKey(compressedKey, + * 'secp256k1', + * 'hex', + * 'hex', + * 'uncompressed'); + * + * // The converted key and the uncompressed public key should be the same + * console.log(uncompressedKey === ecdh.getPublicKey('hex')); + * ``` + * @since v10.0.0 + * @param inputEncoding The `encoding` of the `key` string. + * @param outputEncoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: BinaryToTextEncoding, + outputEncoding?: "latin1" | "hex" | "base64" | "base64url", + format?: "uncompressed" | "compressed" | "hybrid", + ): NonSharedBuffer | string; + /** + * Generates private and public EC Diffie-Hellman key values, and returns + * the public key in the specified `format` and `encoding`. This key should be + * transferred to the other party. + * + * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. + * + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + generateKeys(): NonSharedBuffer; + generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using specified `inputEncoding`, and the returned secret + * is encoded using the specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. + * + * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey` lies outside of the elliptic curve. Since `otherPublicKey` is + * usually supplied from a remote user over an insecure network, + * be sure to handle this exception accordingly. + * @since v0.11.14 + * @param inputEncoding The `encoding` of the `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): NonSharedBuffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): NonSharedBuffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @return The EC Diffie-Hellman in the specified `encoding`. + */ + getPrivateKey(): NonSharedBuffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. + * + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. + */ + getPublicKey(encoding?: null, format?: ECDHKeyFormat): NonSharedBuffer; + getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Sets the EC Diffie-Hellman private key. + * If `encoding` is provided, `privateKey` is expected + * to be a string; otherwise `privateKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `privateKey` is not valid for the curve specified when the `ECDH` object was + * created, an error is thrown. Upon setting the private key, the associated + * public point (key) is also generated and set in the `ECDH` object. + * @since v0.11.14 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; + } + /** + * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a + * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent + * OpenSSL releases, `openssl ecparam -list_curves` will also display the name + * and description of each available elliptic curve. + * @since v0.11.14 + */ + function createECDH(curveName: string): ECDH; + /** + * This function compares the underlying bytes that represent the given `ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time + * algorithm. + * + * This function does not leak timing information that + * would allow an attacker to guess one of the values. This is suitable for + * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/). + * + * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they + * must have the same byte length. An error is thrown if `a` and `b` have + * different byte lengths. + * + * If at least one of `a` and `b` is a `TypedArray` with more than one byte per + * entry, such as `Uint16Array`, the result will be computed using the platform + * byte order. + * + * **When both of the inputs are `Float32Array`s or `Float64Array`s, this function might return unexpected results due to IEEE 754** + * **encoding of floating-point numbers. In particular, neither `x === y` nor `Object.is(x, y)` implies that the byte representations of two floating-point** + * **numbers `x` and `y` are equal.** + * + * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code + * is timing-safe. Care should be taken to ensure that the surrounding code does + * not introduce timing vulnerabilities. + * @since v6.6.0 + */ + function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; + type KeyType = "rsa" | "rsa-pss" | "dsa" | "ec" | "ed25519" | "ed448" | "x25519" | "x448"; + type KeyFormat = "pem" | "der" | "jwk"; + interface BasePrivateKeyEncodingOptions { + format: T; + cipher?: string | undefined; + passphrase?: string | undefined; + } + interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + interface ED25519KeyPairKeyObjectOptions {} + interface ED448KeyPairKeyObjectOptions {} + interface X25519KeyPairKeyObjectOptions {} + interface X448KeyPairKeyObjectOptions {} + interface ECKeyPairKeyObjectOptions { + /** + * Name of the curve to use + */ + namedCurve: string; + /** + * Must be `'named'` or `'explicit'`. Default: `'named'`. + */ + paramEncoding?: "explicit" | "named" | undefined; + } + interface RSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + } + interface RSAPSSKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes + */ + saltLength?: string | undefined; + } + interface DSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + } + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs1" | "pkcs8"; + }; + } + interface RSAPSSKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes + */ + saltLength?: string | undefined; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface ECKeyPairOptions extends ECKeyPairKeyObjectOptions { + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "sec1" | "pkcs8"; + }; + } + interface ED25519KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface ED448KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface X25519KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface X448KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * When encoding public keys, it is recommended to use `'spki'`. When encoding + * private keys, it is recommended to use `'pkcs8'` with a strong passphrase, + * and to keep the passphrase confidential. + * + * ```js + * const { + * generateKeyPairSync, + * } = await import('node:crypto'); + * + * const { + * publicKey, + * privateKey, + * } = generateKeyPairSync('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }); + * ``` + * + * The return value `{ publicKey, privateKey }` represents the generated key pair. + * When PEM encoding was selected, the respective key will be a string, otherwise + * it will be a buffer containing the data encoded as DER. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "rsa", options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "rsa-pss", options: RSAPSSKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "dsa", options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ec", options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ed25519", options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ed448", options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "x25519", options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "x448", options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * It is recommended to encode public keys as `'spki'` and private keys as `'pkcs8'` with encryption for long-term storage: + * + * ```js + * const { + * generateKeyPair, + * } = await import('node:crypto'); + * + * generateKeyPair('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }, (err, publicKey, privateKey) => { + * // Handle errors and use the generated key pair. + * }); + * ``` + * + * On completion, `callback` will be called with `err` set to `undefined` and `publicKey` / `privateKey` representing the generated key pair. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + namespace generateKeyPair { + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "ed25519", + options?: ED25519KeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__(type: "ed448", options?: ED448KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "x25519", + options?: X25519KeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__(type: "x448", options?: X448KeyPairKeyObjectOptions): Promise; + } + /** + * Calculates and returns the signature for `data` using the given private key and + * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is + * dependent upon the key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPrivateKey}. If it is an object, the following + * additional properties can be passed: + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + ): NonSharedBuffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + callback: (error: Error | null, data: NonSharedBuffer) => void, + ): void; + /** + * Verifies the given signature for `data` using the given key and algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPublicKey}. If it is an object, the following + * additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the `data`. + * + * Because public keys can be derived from private keys, a private key or a public + * key may be passed for `key`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + callback: (error: Error | null, result: boolean) => void, + ): void; + /** + * Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. + * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'` (for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). + * @since v13.9.0, v12.17.0 + */ + function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): NonSharedBuffer; + /** + * A utility for creating one-shot hash digests of data. It can be faster than the object-based `crypto.createHash()` when hashing a smaller amount of data + * (<= 5MB) that's readily available. If the data can be big or if it is streamed, it's still recommended to use `crypto.createHash()` instead. The `algorithm` + * is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. On recent releases + * of OpenSSL, `openssl list -digest-algorithms` will display the available digest algorithms. + * + * Example: + * + * ```js + * import crypto from 'node:crypto'; + * import { Buffer } from 'node:buffer'; + * + * // Hashing a string and return the result as a hex-encoded string. + * const string = 'Node.js'; + * // 10b3493287f831e81a438811a1ffba01f8cec4b7 + * console.log(crypto.hash('sha1', string)); + * + * // Encode a base64-encoded string into a Buffer, hash it and return + * // the result as a buffer. + * const base64 = 'Tm9kZS5qcw=='; + * // + * console.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer')); + * ``` + * @since v21.7.0, v20.12.0 + * @param data When `data` is a string, it will be encoded as UTF-8 before being hashed. If a different input encoding is desired for a string input, user + * could encode the string into a `TypedArray` using either `TextEncoder` or `Buffer.from()` and passing the encoded `TypedArray` into this API instead. + * @param [outputEncoding='hex'] [Encoding](https://nodejs.org/docs/latest-v22.x/api/buffer.html#buffers-and-character-encodings) used to encode the returned digest. + */ + function hash(algorithm: string, data: BinaryLike, outputEncoding?: BinaryToTextEncoding): string; + function hash(algorithm: string, data: BinaryLike, outputEncoding: "buffer"): NonSharedBuffer; + function hash( + algorithm: string, + data: BinaryLike, + outputEncoding?: BinaryToTextEncoding | "buffer", + ): string | NonSharedBuffer; + type CipherMode = "cbc" | "ccm" | "cfb" | "ctr" | "ecb" | "gcm" | "ocb" | "ofb" | "stream" | "wrap" | "xts"; + interface CipherInfoOptions { + /** + * A test key length. + */ + keyLength?: number | undefined; + /** + * A test IV length. + */ + ivLength?: number | undefined; + } + interface CipherInfo { + /** + * The name of the cipher. + */ + name: string; + /** + * The nid of the cipher. + */ + nid: number; + /** + * The block size of the cipher in bytes. + * This property is omitted when mode is 'stream'. + */ + blockSize?: number | undefined; + /** + * The expected or default initialization vector length in bytes. + * This property is omitted if the cipher does not use an initialization vector. + */ + ivLength?: number | undefined; + /** + * The expected or default key length in bytes. + */ + keyLength: number; + /** + * The cipher mode. + */ + mode: CipherMode; + } + /** + * Returns information about a given cipher. + * + * Some ciphers accept variable length keys and initialization vectors. By default, + * the `crypto.getCipherInfo()` method will return the default values for these + * ciphers. To test if a given key length or iv length is acceptable for given + * cipher, use the `keyLength` and `ivLength` options. If the given values are + * unacceptable, `undefined` will be returned. + * @since v15.0.0 + * @param nameOrNid The name or nid of the cipher to query. + */ + function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; + /** + * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an errors occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. The successfully generated `derivedKey` will + * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any + * of the input arguments specify invalid values or types. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdf, + * } = await import('node:crypto'); + * + * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * }); + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdf( + digest: string, + irm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: ArrayBuffer) => void, + ): void; + /** + * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The + * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + * + * An error will be thrown if any of the input arguments specify invalid values or + * types, or if the derived key cannot be generated. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdfSync, + * } = await import('node:crypto'); + * + * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdfSync( + digest: string, + ikm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + ): ArrayBuffer; + interface SecureHeapUsage { + /** + * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. + */ + total: number; + /** + * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. + */ + min: number; + /** + * The total number of bytes currently allocated from the secure heap. + */ + used: number; + /** + * The calculated ratio of `used` to `total` allocated bytes. + */ + utilization: number; + } + /** + * @since v15.6.0 + */ + function secureHeapUsed(): SecureHeapUsage; + interface RandomUUIDOptions { + /** + * By default, to improve performance, + * Node.js will pre-emptively generate and persistently cache enough + * random data to generate up to 128 random UUIDs. To generate a UUID + * without using the cache, set `disableEntropyCache` to `true`. + * + * @default `false` + */ + disableEntropyCache?: boolean | undefined; + } + type UUID = `${string}-${string}-${string}-${string}-${string}`; + /** + * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a + * cryptographic pseudorandom number generator. + * @since v15.6.0, v14.17.0 + */ + function randomUUID(options?: RandomUUIDOptions): UUID; + interface X509CheckOptions { + /** + * @default 'always' + */ + subject?: "always" | "default" | "never" | undefined; + /** + * @default true + */ + wildcards?: boolean | undefined; + /** + * @default true + */ + partialWildcards?: boolean | undefined; + /** + * @default false + */ + multiLabelWildcards?: boolean | undefined; + /** + * @default false + */ + singleLabelSubdomains?: boolean | undefined; + } + /** + * Encapsulates an X509 certificate and provides read-only access to + * its information. + * + * ```js + * const { X509Certificate } = await import('node:crypto'); + * + * const x509 = new X509Certificate('{... pem encoded cert ...}'); + * + * console.log(x509.subject); + * ``` + * @since v15.6.0 + */ + class X509Certificate { + /** + * Will be \`true\` if this is a Certificate Authority (CA) certificate. + * @since v15.6.0 + */ + readonly ca: boolean; + /** + * The SHA-1 fingerprint of this certificate. + * + * Because SHA-1 is cryptographically broken and because the security of SHA-1 is + * significantly worse than that of algorithms that are commonly used to sign + * certificates, consider using `x509.fingerprint256` instead. + * @since v15.6.0 + */ + readonly fingerprint: string; + /** + * The SHA-256 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint256: string; + /** + * The SHA-512 fingerprint of this certificate. + * + * Because computing the SHA-256 fingerprint is usually faster and because it is + * only half the size of the SHA-512 fingerprint, `x509.fingerprint256` may be + * a better choice. While SHA-512 presumably provides a higher level of security in + * general, the security of SHA-256 matches that of most algorithms that are + * commonly used to sign certificates. + * @since v17.2.0, v16.14.0 + */ + readonly fingerprint512: string; + /** + * The complete subject of this certificate. + * @since v15.6.0 + */ + readonly subject: string; + /** + * The subject alternative name specified for this certificate. + * + * This is a comma-separated list of subject alternative names. Each entry begins + * with a string identifying the kind of the subject alternative name followed by + * a colon and the value associated with the entry. + * + * Earlier versions of Node.js incorrectly assumed that it is safe to split this + * property at the two-character sequence `', '` (see [CVE-2021-44532](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44532)). However, + * both malicious and legitimate certificates can contain subject alternative names + * that include this sequence when represented as a string. + * + * After the prefix denoting the type of the entry, the remainder of each entry + * might be enclosed in quotes to indicate that the value is a JSON string literal. + * For backward compatibility, Node.js only uses JSON string literals within this + * property when necessary to avoid ambiguity. Third-party code should be prepared + * to handle both possible entry formats. + * @since v15.6.0 + */ + readonly subjectAltName: string | undefined; + /** + * A textual representation of the certificate's authority information access + * extension. + * + * This is a line feed separated list of access descriptions. Each line begins with + * the access method and the kind of the access location, followed by a colon and + * the value associated with the access location. + * + * After the prefix denoting the access method and the kind of the access location, + * the remainder of each line might be enclosed in quotes to indicate that the + * value is a JSON string literal. For backward compatibility, Node.js only uses + * JSON string literals within this property when necessary to avoid ambiguity. + * Third-party code should be prepared to handle both possible entry formats. + * @since v15.6.0 + */ + readonly infoAccess: string | undefined; + /** + * An array detailing the key usages for this certificate. + * @since v15.6.0 + */ + readonly keyUsage: string[]; + /** + * The issuer identification included in this certificate. + * @since v15.6.0 + */ + readonly issuer: string; + /** + * The issuer certificate or `undefined` if the issuer certificate is not + * available. + * @since v15.9.0 + */ + readonly issuerCertificate: X509Certificate | undefined; + /** + * The public key `KeyObject` for this certificate. + * @since v15.6.0 + */ + readonly publicKey: KeyObject; + /** + * A `Buffer` containing the DER encoding of this certificate. + * @since v15.6.0 + */ + readonly raw: NonSharedBuffer; + /** + * The serial number of this certificate. + * + * Serial numbers are assigned by certificate authorities and do not uniquely + * identify certificates. Consider using `x509.fingerprint256` as a unique + * identifier instead. + * @since v15.6.0 + */ + readonly serialNumber: string; + /** + * The date/time from which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validFrom: string; + /** + * The date/time from which this certificate is valid, encapsulated in a `Date` object. + * @since v22.10.0 + */ + readonly validFromDate: Date; + /** + * The date/time until which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validTo: string; + /** + * The date/time until which this certificate is valid, encapsulated in a `Date` object. + * @since v22.10.0 + */ + readonly validToDate: Date; + constructor(buffer: BinaryLike); + /** + * Checks whether the certificate matches the given email address. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any email addresses. + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching email + * address, the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns `email` if the certificate matches, `undefined` if it does not. + */ + checkEmail(email: string, options?: Pick): string | undefined; + /** + * Checks whether the certificate matches the given host name. + * + * If the certificate matches the given host name, the matching subject name is + * returned. The returned name might be an exact match (e.g., `foo.example.com`) + * or it might contain wildcards (e.g., `*.example.com`). Because host name + * comparisons are case-insensitive, the returned subject name might also differ + * from the given `name` in capitalization. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any DNS names. This behavior is consistent with [RFC 2818](https://www.rfc-editor.org/rfc/rfc2818.txt) ("HTTP Over TLS"). + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching DNS name, + * the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns a subject name that matches `name`, or `undefined` if no subject name matches `name`. + */ + checkHost(name: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given IP address (IPv4 or IPv6). + * + * Only [RFC 5280](https://www.rfc-editor.org/rfc/rfc5280.txt) `iPAddress` subject alternative names are considered, and they + * must match the given `ip` address exactly. Other subject alternative names as + * well as the subject field of the certificate are ignored. + * @since v15.6.0 + * @return Returns `ip` if the certificate matches, `undefined` if it does not. + */ + checkIP(ip: string): string | undefined; + /** + * Checks whether this certificate was potentially issued by the given `otherCert` + * by comparing the certificate metadata. + * + * This is useful for pruning a list of possible issuer certificates which have been + * selected using a more rudimentary filtering routine, i.e. just based on subject + * and issuer names. + * + * Finally, to verify that this certificate's signature was produced by a private key + * corresponding to `otherCert`'s public key use `x509.verify(publicKey)` + * with `otherCert`'s public key represented as a `KeyObject` + * like so + * + * ```js + * if (!x509.verify(otherCert.publicKey)) { + * throw new Error('otherCert did not issue x509'); + * } + * ``` + * @since v15.6.0 + */ + checkIssued(otherCert: X509Certificate): boolean; + /** + * Checks whether the public key for this certificate is consistent with + * the given private key. + * @since v15.6.0 + * @param privateKey A private key. + */ + checkPrivateKey(privateKey: KeyObject): boolean; + /** + * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded + * certificate. + * @since v15.6.0 + */ + toJSON(): string; + /** + * Returns information about this certificate using the legacy `certificate object` encoding. + * @since v15.6.0 + */ + toLegacyObject(): PeerCertificate; + /** + * Returns the PEM-encoded certificate. + * @since v15.6.0 + */ + toString(): string; + /** + * Verifies that this certificate was signed by the given public key. + * Does not perform any other validation checks on the certificate. + * @since v15.6.0 + * @param publicKey A public key. + */ + verify(publicKey: KeyObject): boolean; + } + type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; + interface GeneratePrimeOptions { + add?: LargeNumberLike | undefined; + rem?: LargeNumberLike | undefined; + /** + * @default false + */ + safe?: boolean | undefined; + bigint?: boolean | undefined; + } + interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false | undefined; + } + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsBigInt, + callback: (err: Error | null, prime: bigint) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsArrayBuffer, + callback: (err: Error | null, prime: ArrayBuffer) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptions, + callback: (err: Error | null, prime: ArrayBuffer | bigint) => void, + ): void; + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrimeSync(size: number): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint; + interface CheckPrimeOptions { + /** + * The number of Miller-Rabin probabilistic primality iterations to perform. + * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most `2**-64` for random input. + * Care must be used when selecting a number of checks. + * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. + * + * @default 0 + */ + checks?: number | undefined; + } + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + */ + function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void; + function checkPrime( + value: LargeNumberLike, + options: CheckPrimeOptions, + callback: (err: Error | null, result: boolean) => void, + ): void; + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`. + */ + function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean; + /** + * Load and set the `engine` for some or all OpenSSL functions (selected by flags). + * + * `engine` could be either an id or a path to the engine's shared library. + * + * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags` is a bit field taking one of or a mix of the following flags (defined in `crypto.constants`): + * + * * `crypto.constants.ENGINE_METHOD_RSA` + * * `crypto.constants.ENGINE_METHOD_DSA` + * * `crypto.constants.ENGINE_METHOD_DH` + * * `crypto.constants.ENGINE_METHOD_RAND` + * * `crypto.constants.ENGINE_METHOD_EC` + * * `crypto.constants.ENGINE_METHOD_CIPHERS` + * * `crypto.constants.ENGINE_METHOD_DIGESTS` + * * `crypto.constants.ENGINE_METHOD_PKEY_METHS` + * * `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` + * * `crypto.constants.ENGINE_METHOD_ALL` + * * `crypto.constants.ENGINE_METHOD_NONE` + * @since v0.11.11 + * @param flags + */ + function setEngine(engine: string, flags?: number): void; + /** + * A convenient alias for {@link webcrypto.getRandomValues}. This + * implementation is not compliant with the Web Crypto spec, to write + * web-compatible code use {@link webcrypto.getRandomValues} instead. + * @since v17.4.0 + * @return Returns `typedArray`. + */ + function getRandomValues(typedArray: T): T; + /** + * A convenient alias for `crypto.webcrypto.subtle`. + * @since v17.4.0 + */ + const subtle: webcrypto.SubtleCrypto; + /** + * An implementation of the Web Crypto API standard. + * + * See the {@link https://nodejs.org/docs/latest/api/webcrypto.html Web Crypto API documentation} for details. + * @since v15.0.0 + */ + const webcrypto: webcrypto.Crypto; + namespace webcrypto { + type BufferSource = ArrayBufferView | ArrayBuffer; + type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki"; + type KeyType = "private" | "public" | "secret"; + type KeyUsage = + | "decrypt" + | "deriveBits" + | "deriveKey" + | "encrypt" + | "sign" + | "unwrapKey" + | "verify" + | "wrapKey"; + type AlgorithmIdentifier = Algorithm | string; + type HashAlgorithmIdentifier = AlgorithmIdentifier; + type NamedCurve = string; + type BigInteger = Uint8Array; + interface AesCbcParams extends Algorithm { + iv: BufferSource; + } + interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; + } + interface AesDerivedKeyParams extends Algorithm { + length: number; + } + interface AesGcmParams extends Algorithm { + additionalData?: BufferSource; + iv: BufferSource; + tagLength?: number; + } + interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; + } + interface AesKeyGenParams extends Algorithm { + length: number; + } + interface Algorithm { + name: string; + } + interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: NamedCurve; + } + interface EcKeyGenParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcKeyImportParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; + } + interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface Ed448Params extends Algorithm { + context?: BufferSource; + } + interface HkdfParams extends Algorithm { + hash: HashAlgorithmIdentifier; + info: BufferSource; + salt: BufferSource; + } + interface HmacImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; + } + interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; + } + interface KeyAlgorithm { + name: string; + } + interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: BufferSource; + } + interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; + } + interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: HashAlgorithmIdentifier; + } + interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaOaepParams extends Algorithm { + label?: BufferSource; + } + interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; + } + interface RsaPssParams extends Algorithm { + saltLength: number; + } + /** + * Importing the `webcrypto` object (`import { webcrypto } from 'node:crypto'`) gives an instance of the `Crypto` class. + * `Crypto` is a singleton that provides access to the remainder of the crypto API. + * @since v15.0.0 + */ + interface Crypto { + /** + * Provides access to the `SubtleCrypto` API. + * @since v15.0.0 + */ + readonly subtle: SubtleCrypto; + /** + * Generates cryptographically strong random values. + * The given `typedArray` is filled with random values, and a reference to `typedArray` is returned. + * + * The given `typedArray` must be an integer-based instance of {@link NodeJS.TypedArray}, i.e. `Float32Array` and `Float64Array` are not accepted. + * + * An error will be thrown if the given `typedArray` is larger than 65,536 bytes. + * @since v15.0.0 + */ + getRandomValues>(typedArray: T): T; + /** + * Generates a random {@link https://www.rfc-editor.org/rfc/rfc4122.txt RFC 4122} version 4 UUID. + * The UUID is generated using a cryptographic pseudorandom number generator. + * @since v16.7.0 + */ + randomUUID(): UUID; + CryptoKey: CryptoKeyConstructor; + } + // This constructor throws ILLEGAL_CONSTRUCTOR so it should not be newable. + interface CryptoKeyConstructor { + /** Illegal constructor */ + (_: { readonly _: unique symbol }): never; // Allows instanceof to work but not be callable by the user. + readonly length: 0; + readonly name: "CryptoKey"; + readonly prototype: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface CryptoKey { + /** + * An object detailing the algorithm for which the key can be used along with additional algorithm-specific parameters. + * @since v15.0.0 + */ + readonly algorithm: KeyAlgorithm; + /** + * When `true`, the {@link CryptoKey} can be extracted using either `subtleCrypto.exportKey()` or `subtleCrypto.wrapKey()`. + * @since v15.0.0 + */ + readonly extractable: boolean; + /** + * A string identifying whether the key is a symmetric (`'secret'`) or asymmetric (`'private'` or `'public'`) key. + * @since v15.0.0 + */ + readonly type: KeyType; + /** + * An array of strings identifying the operations for which the key may be used. + * + * The possible usages are: + * - `'encrypt'` - The key may be used to encrypt data. + * - `'decrypt'` - The key may be used to decrypt data. + * - `'sign'` - The key may be used to generate digital signatures. + * - `'verify'` - The key may be used to verify digital signatures. + * - `'deriveKey'` - The key may be used to derive a new key. + * - `'deriveBits'` - The key may be used to derive bits. + * - `'wrapKey'` - The key may be used to wrap another key. + * - `'unwrapKey'` - The key may be used to unwrap another key. + * + * Valid key usages depend on the key algorithm (identified by `cryptokey.algorithm.name`). + * @since v15.0.0 + */ + readonly usages: KeyUsage[]; + } + /** + * The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair. + * @since v15.0.0 + */ + interface CryptoKeyPair { + /** + * A {@link CryptoKey} whose type will be `'private'`. + * @since v15.0.0 + */ + privateKey: CryptoKey; + /** + * A {@link CryptoKey} whose type will be `'public'`. + * @since v15.0.0 + */ + publicKey: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface SubtleCrypto { + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `key`, + * `subtle.decrypt()` attempts to decipher the provided `data`. If successful, + * the returned promise will be resolved with an `` containing the plaintext result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + decrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `baseKey`, + * `subtle.deriveBits()` attempts to generate `length` bits. + * The Node.js implementation requires that when `length` is a number it must be multiple of `8`. + * When `length` is `null` the maximum number of bits for a given algorithm is generated. This is allowed + * for the `'ECDH'`, `'X25519'`, and `'X448'` algorithms. + * If successful, the returned promise will be resolved with an `` containing the generated data. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @since v15.0.0 + */ + deriveBits( + algorithm: EcdhKeyDeriveParams, + baseKey: CryptoKey, + length?: number | null, + ): Promise; + deriveBits( + algorithm: EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + length: number, + ): Promise; + /** + * Using the method and parameters specified in `algorithm`, and the keying material provided by `baseKey`, + * `subtle.deriveKey()` attempts to generate a new ` based on the method and parameters in `derivedKeyAlgorithm`. + * + * Calling `subtle.deriveKey()` is equivalent to calling `subtle.deriveBits()` to generate raw keying material, + * then passing the result into the `subtle.importKey()` method using the `deriveKeyAlgorithm`, `extractable`, and `keyUsages` parameters as input. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + deriveKey( + algorithm: EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + derivedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | AesDerivedKeyParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + /** + * Using the method identified by `algorithm`, `subtle.digest()` attempts to generate a digest of `data`. + * If successful, the returned promise is resolved with an `` containing the computed digest. + * + * If `algorithm` is provided as a ``, it must be one of: + * + * - `'SHA-1'` + * - `'SHA-256'` + * - `'SHA-384'` + * - `'SHA-512'` + * + * If `algorithm` is provided as an ``, it must have a `name` property whose value is one of the above. + * @since v15.0.0 + */ + digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise; + /** + * Using the method and parameters specified by `algorithm` and the keying material provided by `key`, + * `subtle.encrypt()` attempts to encipher `data`. If successful, + * the returned promise is resolved with an `` containing the encrypted result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + encrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * Exports the given key into the specified format, if supported. + * + * If the `` is not extractable, the returned promise will reject. + * + * When `format` is either `'pkcs8'` or `'spki'` and the export is successful, + * the returned promise will be resolved with an `` containing the exported key data. + * + * When `format` is `'jwk'` and the export is successful, the returned promise will be resolved with a + * JavaScript object conforming to the {@link https://tools.ietf.org/html/rfc7517 JSON Web Key} specification. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @returns `` containing ``. + * @since v15.0.0 + */ + exportKey(format: "jwk", key: CryptoKey): Promise; + exportKey(format: Exclude, key: CryptoKey): Promise; + /** + * Using the method and parameters provided in `algorithm`, + * `subtle.generateKey()` attempts to generate new keying material. + * Depending the method used, the method may generate either a single `` or a ``. + * + * The `` (public and private key) generating algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * The `` (secret key) generating algorithms supported include: + * + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + generateKey( + algorithm: RsaHashedKeyGenParams | EcKeyGenParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AlgorithmIdentifier, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * The `subtle.importKey()` method attempts to interpret the provided `keyData` as the given `format` + * to create a `` instance using the provided `algorithm`, `extractable`, and `keyUsages` arguments. + * If the import is successful, the returned promise will be resolved with the created ``. + * + * If importing a `'PBKDF2'` key, `extractable` must be `false`. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + importKey( + format: "jwk", + keyData: JsonWebKey, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + importKey( + format: Exclude, + keyData: BufferSource, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters given by `algorithm` and the keying material provided by `key`, + * `subtle.sign()` attempts to generate a cryptographic signature of `data`. If successful, + * the returned promise is resolved with an `` containing the generated signature. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + sign( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.unwrapKey()` method attempts to decrypt a wrapped key and create a `` instance. + * It is equivalent to calling `subtle.decrypt()` first on the encrypted key data (using the `wrappedKey`, `unwrapAlgo`, and `unwrappingKey` arguments as input) + * then passing the results in to the `subtle.importKey()` method using the `unwrappedKeyAlgo`, `extractable`, and `keyUsages` arguments as inputs. + * If successful, the returned promise is resolved with a `` object. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * + * The unwrapped key algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + unwrapKey( + format: KeyFormat, + wrappedKey: BufferSource, + unwrappingKey: CryptoKey, + unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + unwrappedKeyAlgorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters given in `algorithm` and the keying material provided by `key`, + * `subtle.verify()` attempts to verify that `signature` is a valid cryptographic signature of `data`. + * The returned promise is resolved with either `true` or `false`. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + verify( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, + key: CryptoKey, + signature: BufferSource, + data: BufferSource, + ): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.wrapKey()` method exports the keying material into the format identified by `format`, + * then encrypts it using the method and parameters specified by `wrapAlgo` and the keying material provided by `wrappingKey`. + * It is the equivalent to calling `subtle.exportKey()` using `format` and `key` as the arguments, + * then passing the result to the `subtle.encrypt()` method using `wrappingKey` and `wrapAlgo` as inputs. + * If successful, the returned promise will be resolved with an `` containing the encrypted key data. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @since v15.0.0 + */ + wrapKey( + format: KeyFormat, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + ): Promise; + } + } + + global { + var crypto: typeof globalThis extends { + crypto: infer T; + onmessage: any; + } ? T + : webcrypto.Crypto; + } +} +declare module "node:crypto" { + export * from "crypto"; +} diff --git a/node_modules/@types/node/dgram.d.ts b/node_modules/@types/node/dgram.d.ts new file mode 100644 index 0000000..9776de0 --- /dev/null +++ b/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,600 @@ +/** + * The `node:dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/dgram.js) + */ +declare module "dgram" { + import { NonSharedBuffer } from "node:buffer"; + import { AddressInfo, BlockList } from "node:net"; + import * as dns from "node:dns"; + import { Abortable, EventEmitter } from "node:events"; + interface RemoteInfo { + address: string; + family: "IPv4" | "IPv6"; + port: number; + size: number; + } + interface BindOptions { + port?: number | undefined; + address?: string | undefined; + exclusive?: boolean | undefined; + fd?: number | undefined; + } + type SocketType = "udp4" | "udp6"; + interface SocketOptions extends Abortable { + type: SocketType; + reuseAddr?: boolean | undefined; + reusePort?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + recvBufferSize?: number | undefined; + sendBufferSize?: number | undefined; + lookup?: + | (( + hostname: string, + options: dns.LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ) => void) + | undefined; + receiveBlockList?: BlockList | undefined; + sendBlockList?: BlockList | undefined; + } + /** + * Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram + * messages. When `address` and `port` are not passed to `socket.bind()` the + * method will bind the socket to the "all interfaces" address on a random port + * (it does the right thing for both `udp4` and `udp6` sockets). The bound address + * and port can be retrieved using `socket.address().address` and `socket.address().port`. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.close()` on the socket: + * + * ```js + * const controller = new AbortController(); + * const { signal } = controller; + * const server = dgram.createSocket({ type: 'udp4', signal }); + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * // Later, when you want to close the server. + * controller.abort(); + * ``` + * @since v0.11.13 + * @param options Available options are: + * @param callback Attached as a listener for `'message'` events. Optional. + */ + function createSocket(type: SocketType, callback?: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): Socket; + /** + * Encapsulates the datagram functionality. + * + * New instances of `dgram.Socket` are created using {@link createSocket}. + * The `new` keyword is not to be used to create `dgram.Socket` instances. + * @since v0.1.99 + */ + class Socket extends EventEmitter { + /** + * Tells the kernel to join a multicast group at the given `multicastAddress` and `multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the `multicastInterface` argument is not + * specified, the operating system will choose + * one interface and will add membership to it. To add membership to every + * available interface, call `addMembership` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * + * When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur: + * + * ```js + * import cluster from 'node:cluster'; + * import dgram from 'node:dgram'; + * + * if (cluster.isPrimary) { + * cluster.fork(); // Works ok. + * cluster.fork(); // Fails with EADDRINUSE. + * } else { + * const s = dgram.createSocket('udp4'); + * s.bind(1234, () => { + * s.addMembership('224.0.0.114'); + * }); + * } + * ``` + * @since v0.6.9 + */ + addMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * Returns an object containing the address information for a socket. + * For UDP sockets, this object will contain `address`, `family`, and `port` properties. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.99 + */ + address(): AddressInfo; + /** + * For UDP sockets, causes the `dgram.Socket` to listen for datagram + * messages on a named `port` and optional `address`. If `port` is not + * specified or is `0`, the operating system will attempt to bind to a + * random port. If `address` is not specified, the operating system will + * attempt to listen on all addresses. Once binding is complete, a `'listening'` event is emitted and the optional `callback` function is + * called. + * + * Specifying both a `'listening'` event listener and passing a `callback` to the `socket.bind()` method is not harmful but not very + * useful. + * + * A bound datagram socket keeps the Node.js process running to receive + * datagram messages. + * + * If binding fails, an `'error'` event is generated. In rare case (e.g. + * attempting to bind with a closed socket), an `Error` may be thrown. + * + * Example of a UDP server listening on port 41234: + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @since v0.1.99 + * @param callback with no parameters. Called when binding is complete. + */ + bind(port?: number, address?: string, callback?: () => void): this; + bind(port?: number, callback?: () => void): this; + bind(callback?: () => void): this; + bind(options: BindOptions, callback?: () => void): this; + /** + * Close the underlying socket and stop listening for data on it. If a callback is + * provided, it is added as a listener for the `'close'` event. + * @since v0.1.99 + * @param callback Called when the socket has been closed. + */ + close(callback?: () => void): this; + /** + * Associates the `dgram.Socket` to a remote address and port. Every + * message sent by this handle is automatically sent to that destination. Also, + * the socket will only receive messages from that remote peer. + * Trying to call `connect()` on an already connected socket will result + * in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not + * provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) + * will be used by default. Once the connection is complete, a `'connect'` event + * is emitted and the optional `callback` function is called. In case of failure, + * the `callback` is called or, failing this, an `'error'` event is emitted. + * @since v12.0.0 + * @param callback Called when the connection is completed or on error. + */ + connect(port: number, address?: string, callback?: () => void): void; + connect(port: number, callback: () => void): void; + /** + * A synchronous function that disassociates a connected `dgram.Socket` from + * its remote address. Trying to call `disconnect()` on an unbound or already + * disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception. + * @since v12.0.0 + */ + disconnect(): void; + /** + * Instructs the kernel to leave a multicast group at `multicastAddress` using the `IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the + * kernel when the socket is closed or the process terminates, so most apps will + * never have reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v0.6.9 + */ + dropMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_RCVBUF` socket receive buffer size in bytes. + */ + getRecvBufferSize(): number; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_SNDBUF` socket send buffer size in bytes. + */ + getSendBufferSize(): number; + /** + * @since v18.8.0, v16.19.0 + * @return Number of bytes queued for sending. + */ + getSendQueueSize(): number; + /** + * @since v18.8.0, v16.19.0 + * @return Number of send requests currently in the queue awaiting to be processed. + */ + getSendQueueCount(): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active. The `socket.ref()` method adds the socket back to the reference + * counting and restores the default behavior. + * + * Calling `socket.ref()` multiples times will have no additional effect. + * + * The `socket.ref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + ref(): this; + /** + * Returns an object containing the `address`, `family`, and `port` of the remote + * endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception + * if the socket is not connected. + * @since v12.0.0 + */ + remoteAddress(): AddressInfo; + /** + * Broadcasts a datagram on the socket. + * For connectionless sockets, the destination `port` and `address` must be + * specified. Connected sockets, on the other hand, will use their associated + * remote endpoint, so the `port` and `address` arguments must not be set. + * + * The `msg` argument contains the message to be sent. + * Depending on its type, different behavior can apply. If `msg` is a `Buffer`, + * any `TypedArray` or a `DataView`, + * the `offset` and `length` specify the offset within the `Buffer` where the + * message begins and the number of bytes in the message, respectively. + * If `msg` is a `String`, then it is automatically converted to a `Buffer` with `'utf8'` encoding. With messages that + * contain multi-byte characters, `offset` and `length` will be calculated with + * respect to `byte length` and not the character position. + * If `msg` is an array, `offset` and `length` must not be specified. + * + * The `address` argument is a string. If the value of `address` is a host name, + * DNS will be used to resolve the address of the host. If `address` is not + * provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) will be used by default. + * + * If the socket has not been previously bound with a call to `bind`, the socket + * is assigned a random port number and is bound to the "all interfaces" address + * (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) + * + * An optional `callback` function may be specified to as a way of reporting + * DNS errors or for determining when it is safe to reuse the `buf` object. + * DNS lookups delay the time to send for at least one tick of the + * Node.js event loop. + * + * The only way to know for sure that the datagram has been sent is by using a `callback`. If an error occurs and a `callback` is given, the error will be + * passed as the first argument to the `callback`. If a `callback` is not given, + * the error is emitted as an `'error'` event on the `socket` object. + * + * Offset and length are optional but both _must_ be set if either are used. + * They are supported only when the first argument is a `Buffer`, a `TypedArray`, + * or a `DataView`. + * + * This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket. + * + * Example of sending a UDP packet to a port on `localhost`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.send(message, 41234, 'localhost', (err) => { + * client.close(); + * }); + * ``` + * + * Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('Some '); + * const buf2 = Buffer.from('bytes'); + * const client = dgram.createSocket('udp4'); + * client.send([buf1, buf2], 41234, (err) => { + * client.close(); + * }); + * ``` + * + * Sending multiple buffers might be faster or slower depending on the + * application and operating system. Run benchmarks to + * determine the optimal strategy on a case-by-case basis. Generally speaking, + * however, sending multiple buffers is faster. + * + * Example of sending a UDP packet using a socket connected to a port on `localhost`: + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.connect(41234, 'localhost', (err) => { + * client.send(message, (err) => { + * client.close(); + * }); + * }); + * ``` + * @since v0.1.99 + * @param msg Message to be sent. + * @param offset Offset in the buffer where the message starts. + * @param length Number of bytes in the message. + * @param port Destination port. + * @param address Destination host name or IP address. + * @param callback Called when the message has been sent. + */ + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + /** + * Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP + * packets may be sent to a local interface's broadcast address. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.6.9 + */ + setBroadcast(flag: boolean): void; + /** + * _All references to scope in this section are referring to [IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC + * 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_ + * _with a scope index is written as `'IP%scope'` where scope is an interface name_ + * _or interface number._ + * + * Sets the default outgoing multicast interface of the socket to a chosen + * interface or back to system interface selection. The `multicastInterface` must + * be a valid string representation of an IP from the socket's family. + * + * For IPv4 sockets, this should be the IP configured for the desired physical + * interface. All packets sent to multicast on the socket will be sent on the + * interface determined by the most recent successful use of this call. + * + * For IPv6 sockets, `multicastInterface` should include a scope to indicate the + * interface as in the examples that follow. In IPv6, individual `send` calls can + * also use explicit scope in addresses, so only packets sent to a multicast + * address without specifying an explicit scope are affected by the most recent + * successful use of this call. + * + * This method throws `EBADF` if called on an unbound socket. + * + * #### Example: IPv6 outgoing multicast interface + * + * On most systems, where scope format uses the interface name: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%eth1'); + * }); + * ``` + * + * On Windows, where scope format uses an interface number: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%2'); + * }); + * ``` + * + * #### Example: IPv4 outgoing multicast interface + * + * All systems use an IP of the host on the desired physical interface: + * + * ```js + * const socket = dgram.createSocket('udp4'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('10.0.0.2'); + * }); + * ``` + * @since v8.6.0 + */ + setMulticastInterface(multicastInterface: string): void; + /** + * Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`, + * multicast packets will also be received on the local interface. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastLoopback(flag: boolean): boolean; + /** + * Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for + * "Time to Live", in this context it specifies the number of IP hops that a + * packet is allowed to travel through, specifically for multicast traffic. Each + * router or gateway that forwards a packet decrements the TTL. If the TTL is + * decremented to 0 by a router, it will not be forwarded. + * + * The `ttl` argument may be between 0 and 255\. The default on most systems is `1`. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastTTL(ttl: number): number; + /** + * Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setRecvBufferSize(size: number): void; + /** + * Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setSendBufferSize(size: number): void; + /** + * Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live", + * in this context it specifies the number of IP hops that a packet is allowed to + * travel through. Each router or gateway that forwards a packet decrements the + * TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. + * Changing TTL values is typically done for network probes or when multicasting. + * + * The `ttl` argument may be between 1 and 255\. The default on most systems + * is 64. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.101 + */ + setTTL(ttl: number): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active, allowing the process to exit even if the socket is still + * listening. + * + * Calling `socket.unref()` multiple times will have no additional effect. + * + * The `socket.unref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + unref(): this; + /** + * Tells the kernel to join a source-specific multicast channel at the given `sourceAddress` and `groupAddress`, using the `multicastInterface` with the `IP_ADD_SOURCE_MEMBERSHIP` socket + * option. If the `multicastInterface` argument + * is not specified, the operating system will choose one interface and will add + * membership to it. To add membership to every available interface, call `socket.addSourceSpecificMembership()` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * @since v13.1.0, v12.16.0 + */ + addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * Instructs the kernel to leave a source-specific multicast channel at the given `sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP` socket option. This method is + * automatically called by the kernel when the + * socket is closed or the process terminates, so most apps will never have + * reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v13.1.0, v12.16.0 + */ + dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. error + * 4. listening + * 5. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: NonSharedBuffer, rinfo: RemoteInfo): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this; + /** + * Calls `socket.close()` and returns a promise that fulfills when the socket has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } +} +declare module "node:dgram" { + export * from "dgram"; +} diff --git a/node_modules/@types/node/diagnostics_channel.d.ts b/node_modules/@types/node/diagnostics_channel.d.ts new file mode 100644 index 0000000..f3bac52 --- /dev/null +++ b/node_modules/@types/node/diagnostics_channel.d.ts @@ -0,0 +1,578 @@ +/** + * The `node:diagnostics_channel` module provides an API to create named channels + * to report arbitrary message data for diagnostics purposes. + * + * It can be accessed using: + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * ``` + * + * It is intended that a module writer wanting to report diagnostics messages + * will create one or many top-level channels to report messages through. + * Channels may also be acquired at runtime but it is not encouraged + * due to the additional overhead of doing so. Channels may be exported for + * convenience, but as long as the name is known it can be acquired anywhere. + * + * If you intend for your module to produce diagnostics data for others to + * consume it is recommended that you include documentation of what named + * channels are used along with the shape of the message data. Channel names + * should generally include the module name to avoid collisions with data from + * other modules. + * @since v15.1.0, v14.17.0 + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/diagnostics_channel.js) + */ +declare module "diagnostics_channel" { + import { AsyncLocalStorage } from "node:async_hooks"; + /** + * Check if there are active subscribers to the named channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * if (diagnostics_channel.hasSubscribers('my-channel')) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return If there are active subscribers + */ + function hasSubscribers(name: string | symbol): boolean; + /** + * This is the primary entry-point for anyone wanting to publish to a named + * channel. It produces a channel object which is optimized to reduce overhead at + * publish time as much as possible. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return The named channel object + */ + function channel(name: string | symbol): Channel; + type ChannelListener = (message: unknown, name: string | symbol) => void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * diagnostics_channel.subscribe('my-channel', (message, name) => { + * // Received data + * }); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The handler to receive channel messages + */ + function subscribe(name: string | symbol, onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with {@link subscribe}. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * function onMessage(message, name) { + * // Received data + * } + * + * diagnostics_channel.subscribe('my-channel', onMessage); + * + * diagnostics_channel.unsubscribe('my-channel', onMessage); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean; + /** + * Creates a `TracingChannel` wrapper for the given `TracingChannel Channels`. If a name is given, the corresponding tracing + * channels will be created in the form of `tracing:${name}:${eventType}` where `eventType` corresponds to the types of `TracingChannel Channels`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channelsByName = diagnostics_channel.tracingChannel('my-channel'); + * + * // or... + * + * const channelsByCollection = diagnostics_channel.tracingChannel({ + * start: diagnostics_channel.channel('tracing:my-channel:start'), + * end: diagnostics_channel.channel('tracing:my-channel:end'), + * asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'), + * asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'), + * error: diagnostics_channel.channel('tracing:my-channel:error'), + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param nameOrChannels Channel name or object containing all the `TracingChannel Channels` + * @return Collection of channels to trace with + */ + function tracingChannel< + StoreType = unknown, + ContextType extends object = StoreType extends object ? StoreType : object, + >( + nameOrChannels: string | TracingChannelCollection, + ): TracingChannel; + /** + * The class `Channel` represents an individual named channel within the data + * pipeline. It is used to track subscribers and to publish messages when there + * are subscribers present. It exists as a separate object to avoid channel + * lookups at publish time, enabling very fast publish speeds and allowing + * for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly + * with `new Channel(name)` is not supported. + * @since v15.1.0, v14.17.0 + */ + class Channel { + readonly name: string | symbol; + /** + * Check if there are active subscribers to this channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * if (channel.hasSubscribers) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + */ + readonly hasSubscribers: boolean; + private constructor(name: string | symbol); + /** + * Publish a message to any subscribers to the channel. This will trigger + * message handlers synchronously so they will execute within the same context. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.publish({ + * some: 'message', + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param message The message to send to the channel subscribers + */ + publish(message: unknown): void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link subscribe(name, onMessage)} + * @param onMessage The handler to receive channel messages + */ + subscribe(onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * function onMessage(message, name) { + * // Received data + * } + * + * channel.subscribe(onMessage); + * + * channel.unsubscribe(onMessage); + * ``` + * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link unsubscribe(name, onMessage)} + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + unsubscribe(onMessage: ChannelListener): void; + /** + * When `channel.runStores(context, ...)` is called, the given context data + * will be applied to any store bound to the channel. If the store has already been + * bound the previous `transform` function will be replaced with the new one. + * The `transform` function may be omitted to set the given context data as the + * context directly. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store, (data) => { + * return { data }; + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param store The store to which to bind the context data + * @param transform Transform context data before setting the store context + */ + bindStore(store: AsyncLocalStorage, transform?: (context: ContextType) => StoreType): void; + /** + * Remove a message handler previously registered to this channel with `channel.bindStore(store)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store); + * channel.unbindStore(store); + * ``` + * @since v19.9.0 + * @experimental + * @param store The store to unbind from the channel. + * @return `true` if the store was found, `false` otherwise. + */ + unbindStore(store: AsyncLocalStorage): boolean; + /** + * Applies the given data to any AsyncLocalStorage instances bound to the channel + * for the duration of the given function, then publishes to the channel within + * the scope of that data is applied to the stores. + * + * If a transform function was given to `channel.bindStore(store)` it will be + * applied to transform the message data before it becomes the context value for + * the store. The prior storage context is accessible from within the transform + * function in cases where context linking is required. + * + * The context applied to the store should be accessible in any async code which + * continues from execution which began during the given function, however + * there are some situations in which `context loss` may occur. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store, (message) => { + * const parent = store.getStore(); + * return new Span(message, parent); + * }); + * channel.runStores({ some: 'message' }, () => { + * store.getStore(); // Span({ some: 'message' }) + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param context Message to send to subscribers and bind to stores + * @param fn Handler to run within the entered storage context + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runStores( + context: ContextType, + fn: (this: ThisArg, ...args: Args) => Result, + thisArg?: ThisArg, + ...args: Args + ): Result; + } + interface TracingChannelSubscribers { + start: (message: ContextType) => void; + end: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + asyncStart: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + asyncEnd: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + error: ( + message: ContextType & { + error: unknown; + }, + ) => void; + } + interface TracingChannelCollection { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + } + /** + * The class `TracingChannel` is a collection of `TracingChannel Channels` which + * together express a single traceable action. It is used to formalize and + * simplify the process of producing events for tracing application flow. {@link tracingChannel} is used to construct a `TracingChannel`. As with `Channel` it is recommended to create and reuse a + * single `TracingChannel` at the top-level of the file rather than creating them + * dynamically. + * @since v19.9.0 + * @experimental + */ + class TracingChannel implements TracingChannelCollection { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + /** + * Helper to subscribe a collection of functions to the corresponding channels. + * This is the same as calling `channel.subscribe(onMessage)` on each channel + * individually. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.subscribe({ + * start(message) { + * // Handle start message + * }, + * end(message) { + * // Handle end message + * }, + * asyncStart(message) { + * // Handle asyncStart message + * }, + * asyncEnd(message) { + * // Handle asyncEnd message + * }, + * error(message) { + * // Handle error message + * }, + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param subscribers Set of `TracingChannel Channels` subscribers + */ + subscribe(subscribers: TracingChannelSubscribers): void; + /** + * Helper to unsubscribe a collection of functions from the corresponding channels. + * This is the same as calling `channel.unsubscribe(onMessage)` on each channel + * individually. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.unsubscribe({ + * start(message) { + * // Handle start message + * }, + * end(message) { + * // Handle end message + * }, + * asyncStart(message) { + * // Handle asyncStart message + * }, + * asyncEnd(message) { + * // Handle asyncEnd message + * }, + * error(message) { + * // Handle error message + * }, + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param subscribers Set of `TracingChannel Channels` subscribers + * @return `true` if all handlers were successfully unsubscribed, and `false` otherwise. + */ + unsubscribe(subscribers: TracingChannelSubscribers): void; + /** + * Trace a synchronous function call. This will always produce a `start event` and `end event` around the execution and may produce an `error event` if the given function throws an error. + * This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceSync(() => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn Function to wrap a trace around + * @param context Shared object to correlate events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return The return value of the given function + */ + traceSync( + fn: (this: ThisArg, ...args: Args) => Result, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Result; + /** + * Trace a promise-returning function call. This will always produce a `start event` and `end event` around the synchronous portion of the + * function execution, and will produce an `asyncStart event` and `asyncEnd event` when a promise continuation is reached. It may also + * produce an `error event` if the given function throws an error or the + * returned promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.tracePromise(async () => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn Promise-returning function to wrap a trace around + * @param context Shared object to correlate trace events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return Chained from promise returned by the given function + */ + tracePromise( + fn: (this: ThisArg, ...args: Args) => Promise, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Promise; + /** + * Trace a callback-receiving function call. This will always produce a `start event` and `end event` around the synchronous portion of the + * function execution, and will produce a `asyncStart event` and `asyncEnd event` around the callback execution. It may also produce an `error event` if the given function throws an error or + * the returned + * promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * The `position` will be -1 by default to indicate the final argument should + * be used as the callback. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceCallback((arg1, callback) => { + * // Do something + * callback(null, 'result'); + * }, 1, { + * some: 'thing', + * }, thisArg, arg1, callback); + * ``` + * + * The callback will also be run with `channel.runStores(context, ...)` which + * enables context loss recovery in some cases. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * const myStore = new AsyncLocalStorage(); + * + * // The start channel sets the initial store data to something + * // and stores that store data value on the trace context object + * channels.start.bindStore(myStore, (data) => { + * const span = new Span(data); + * data.span = span; + * return span; + * }); + * + * // Then asyncStart can restore from that data it stored previously + * channels.asyncStart.bindStore(myStore, (data) => { + * return data.span; + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn callback using function to wrap a trace around + * @param position Zero-indexed argument position of expected callback + * @param context Shared object to correlate trace events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return The return value of the given function + */ + traceCallback( + fn: (this: ThisArg, ...args: Args) => Result, + position?: number, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Result; + /** + * `true` if any of the individual channels has a subscriber, `false` if not. + * + * This is a helper method available on a {@link TracingChannel} instance to check + * if any of the [TracingChannel Channels](https://nodejs.org/api/diagnostics_channel.html#tracingchannel-channels) have subscribers. + * A `true` is returned if any of them have at least one subscriber, a `false` is returned otherwise. + * + * ```js + * const diagnostics_channel = require('node:diagnostics_channel'); + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * if (channels.hasSubscribers) { + * // Do something + * } + * ``` + * @since v22.0.0, v20.13.0 + */ + readonly hasSubscribers: boolean; + } +} +declare module "node:diagnostics_channel" { + export * from "diagnostics_channel"; +} diff --git a/node_modules/@types/node/dns.d.ts b/node_modules/@types/node/dns.d.ts new file mode 100644 index 0000000..9cb2055 --- /dev/null +++ b/node_modules/@types/node/dns.d.ts @@ -0,0 +1,923 @@ +/** + * The `node:dns` module enables name resolution. For example, use it to look up IP + * addresses of host names. + * + * Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the + * DNS protocol for lookups. {@link lookup} uses the operating system + * facilities to perform name resolution. It may not need to perform any network + * communication. To perform name resolution the way other applications on the same + * system do, use {@link lookup}. + * + * ```js + * import dns from 'node:dns'; + * + * dns.lookup('example.org', (err, address, family) => { + * console.log('address: %j family: IPv%s', address, family); + * }); + * // address: "93.184.216.34" family: IPv4 + * ``` + * + * All other functions in the `node:dns` module connect to an actual DNS server to + * perform name resolution. They will always use the network to perform DNS + * queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform + * DNS queries, bypassing other name-resolution facilities. + * + * ```js + * import dns from 'node:dns'; + * + * dns.resolve4('archive.org', (err, addresses) => { + * if (err) throw err; + * + * console.log(`addresses: ${JSON.stringify(addresses)}`); + * + * addresses.forEach((a) => { + * dns.reverse(a, (err, hostnames) => { + * if (err) { + * throw err; + * } + * console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); + * }); + * }); + * }); + * ``` + * + * See the [Implementation considerations section](https://nodejs.org/docs/latest-v22.x/api/dns.html#implementation-considerations) for more information. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/dns.js) + */ +declare module "dns" { + import * as dnsPromises from "node:dns/promises"; + // Supported getaddrinfo flags. + /** + * Limits returned address types to the types of non-loopback addresses configured on the system. For example, IPv4 addresses are + * only returned if the current system has at least one IPv4 address configured. + */ + export const ADDRCONFIG: number; + /** + * If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses. It is not supported + * on some operating systems (e.g. FreeBSD 10.1). + */ + export const V4MAPPED: number; + /** + * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as + * well as IPv4 mapped IPv6 addresses. + */ + export const ALL: number; + export interface LookupOptions { + /** + * The record family. Must be `4`, `6`, or `0`. For backward compatibility reasons, `'IPv4'` and `'IPv6'` are interpreted + * as `4` and `6` respectively. The value 0 indicates that either an IPv4 or IPv6 address is returned. If the value `0` is used + * with `{ all: true } (see below)`, both IPv4 and IPv6 addresses are returned. + * @default 0 + */ + family?: number | "IPv4" | "IPv6" | undefined; + /** + * One or more [supported `getaddrinfo`](https://nodejs.org/docs/latest-v22.x/api/dns.html#supported-getaddrinfo-flags) flags. Multiple flags may be + * passed by bitwise `OR`ing their values. + */ + hints?: number | undefined; + /** + * When `true`, the callback returns all resolved addresses in an array. Otherwise, returns a single address. + * @default false + */ + all?: boolean | undefined; + /** + * When `verbatim`, the resolved addresses are return unsorted. When `ipv4first`, the resolved addresses are sorted + * by placing IPv4 addresses before IPv6 addresses. When `ipv6first`, the resolved addresses are sorted by placing IPv6 + * addresses before IPv4 addresses. Default value is configurable using + * {@link setDefaultResultOrder} or [`--dns-result-order`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--dns-result-orderorder). + * @default `verbatim` (addresses are not reordered) + * @since v22.1.0 + */ + order?: "ipv4first" | "ipv6first" | "verbatim" | undefined; + /** + * When `true`, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 + * addresses are placed before IPv6 addresses. This option will be deprecated in favor of `order`. When both are specified, + * `order` has higher precedence. New code should only use `order`. Default value is configurable using {@link setDefaultResultOrder} + * @default true (addresses are not reordered) + * @deprecated Please use `order` option + */ + verbatim?: boolean | undefined; + } + export interface LookupOneOptions extends LookupOptions { + all?: false | undefined; + } + export interface LookupAllOptions extends LookupOptions { + all: true; + } + export interface LookupAddress { + /** + * A string representation of an IPv4 or IPv6 address. + */ + address: string; + /** + * `4` or `6`, denoting the family of `address`, or `0` if the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a + * bug in the name resolution service used by the operating system. + */ + family: number; + } + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is `0` or not provided, then + * IPv4 and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the arguments for `callback` change to `(err, addresses)`, with `addresses` being an array of objects with the + * properties `address` and `family`. + * + * On error, `err` is an `Error` object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dns.lookup()` does not necessarily have anything to do with the DNS protocol. + * The implementation uses an operating system facility that can associate names + * with addresses and vice versa. This implementation can have subtle but + * important consequences on the behavior of any Node.js program. Please take some + * time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v22.x/api/dns.html#implementation-considerations) + * before using `dns.lookup()`. + * + * Example usage: + * + * ```js + * import dns from 'node:dns'; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * dns.lookup('example.com', options, (err, address, family) => + * console.log('address: %j family: IPv%s', address, family)); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dns.lookup('example.com', options, (err, addresses) => + * console.log('addresses: %j', addresses)); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * ``` + * + * If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v22.x/api/util.html#utilpromisifyoriginal) ed + * version, and `all` is not set to `true`, it returns a `Promise` for an `Object` with `address` and `family` properties. + * @since v0.1.90 + */ + export function lookup( + hostname: string, + family: number, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export function lookup( + hostname: string, + options: LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export function lookup( + hostname: string, + options: LookupAllOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void, + ): void; + export function lookup( + hostname: string, + options: LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void, + ): void; + export function lookup( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise; + function __promisify__(hostname: string, options: LookupOptions): Promise; + } + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown. + * + * On an error, `err` is an [`Error`](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-error) object, + * where `err.code` is the error code. + * + * ```js + * import dns from 'node:dns'; + * dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { + * console.log(hostname, service); + * // Prints: localhost ssh + * }); + * ``` + * + * If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v22.x/api/util.html#utilpromisifyoriginal) ed + * version, it returns a `Promise` for an `Object` with `hostname` and `service` properties. + * @since v0.11.14 + */ + export function lookupService( + address: string, + port: number, + callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void, + ): void; + export namespace lookupService { + function __promisify__( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + } + export interface ResolveOptions { + ttl: boolean; + } + export interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + export interface RecordWithTtl { + address: string; + ttl: number; + } + /** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ + export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + export interface AnyARecord extends RecordWithTtl { + type: "A"; + } + export interface AnyAaaaRecord extends RecordWithTtl { + type: "AAAA"; + } + export interface CaaRecord { + critical: number; + issue?: string | undefined; + issuewild?: string | undefined; + iodef?: string | undefined; + contactemail?: string | undefined; + contactphone?: string | undefined; + } + export interface AnyCaaRecord extends CaaRecord { + type: "CAA"; + } + export interface MxRecord { + priority: number; + exchange: string; + } + export interface AnyMxRecord extends MxRecord { + type: "MX"; + } + export interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + export interface AnyNaptrRecord extends NaptrRecord { + type: "NAPTR"; + } + export interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + export interface AnySoaRecord extends SoaRecord { + type: "SOA"; + } + export interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + export interface AnySrvRecord extends SrvRecord { + type: "SRV"; + } + export interface TlsaRecord { + certUsage: number; + selector: number; + match: number; + data: ArrayBuffer; + } + export interface AnyTlsaRecord extends TlsaRecord { + type: "TLSA"; + } + export interface AnyTxtRecord { + type: "TXT"; + entries: string[]; + } + export interface AnyNsRecord { + type: "NS"; + value: string; + } + export interface AnyPtrRecord { + type: "PTR"; + value: string; + } + export interface AnyCnameRecord { + type: "CNAME"; + value: string; + } + export type AnyRecord = + | AnyARecord + | AnyAaaaRecord + | AnyCaaRecord + | AnyCnameRecord + | AnyMxRecord + | AnyNaptrRecord + | AnyNsRecord + | AnyPtrRecord + | AnySoaRecord + | AnySrvRecord + | AnyTlsaRecord + | AnyTxtRecord; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. The `callback` function has arguments `(err, records)`. When successful, `records` will be an array of resource + * records. The type and structure of individual results varies based on `rrtype`: + * + * + * + * On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-error) object, + * where `err.code` is one of the `DNS error codes`. + * @since v0.1.27 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + export function resolve( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "ANY", + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "CAA", + callback: (err: NodeJS.ErrnoException | null, address: CaaRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "MX", + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "NAPTR", + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "SOA", + callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "SRV", + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "TLSA", + callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "TXT", + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: string, + callback: ( + err: NodeJS.ErrnoException | null, + addresses: + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[], + ) => void, + ): void; + export namespace resolve { + function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function __promisify__(hostname: string, rrtype: "ANY"): Promise; + function __promisify__(hostname: string, rrtype: "CAA"): Promise; + function __promisify__(hostname: string, rrtype: "MX"): Promise; + function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; + function __promisify__(hostname: string, rrtype: "SOA"): Promise; + function __promisify__(hostname: string, rrtype: "SRV"): Promise; + function __promisify__(hostname: string, rrtype: "TLSA"): Promise; + function __promisify__(hostname: string, rrtype: "TXT"): Promise; + function __promisify__( + hostname: string, + rrtype: string, + ): Promise< + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[] + >; + } + /** + * Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve4( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve4( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + export function resolve4( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + export namespace resolve4 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv6 addresses. + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve6( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve6( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + export function resolve6( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + export namespace resolve6 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of canonical name records available for the `hostname` (e.g. `['bar.example.com']`). + * @since v0.3.2 + */ + export function resolveCname( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of certification authority authorization records + * available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + export function resolveCaa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void, + ): void; + export namespace resolveCaa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of objects containing both a `priority` and `exchange` property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v0.1.27 + */ + export function resolveMx( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + export namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will contain an array of + * objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v0.9.12 + */ + export function resolveNaptr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + export namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of name server records available for `hostname` (e.g. `['ns1.example.com', 'ns2.example.com']`). + * @since v0.1.90 + */ + export function resolveNs( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * be an array of strings containing the reply records. + * @since v6.0.0 + */ + export function resolvePtr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. The `address` argument passed to the `callback` function will + * be an object with the following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v0.11.10 + */ + export function resolveSoa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void, + ): void; + export namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * be an array of objects with the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v0.1.27 + */ + export function resolveSrv( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + export namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve certificate associations (`TLSA` records) for + * the `hostname`. The `records` argument passed to the `callback` function is an + * array of objects with these properties: + * + * * `certUsage` + * * `selector` + * * `match` + * * `data` + * + * ```js + * { + * certUsage: 3, + * selector: 1, + * match: 1, + * data: [ArrayBuffer] + * } + * ``` + * @since v22.15.0 + */ + export function resolveTlsa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void, + ): void; + export namespace resolveTlsa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. The `records` argument passed to the `callback` function is a + * two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v0.1.27 + */ + export function resolveTxt( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + export namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * The `ret` argument passed to the `callback` function will be an array containing + * various types of records. Each object has a property `type` that indicates the + * type of the current record. And depending on the `type`, additional properties + * will be present on the object: + * + * + * + * Here is an example of the `ret` object passed to the callback: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * + * DNS server operators may choose not to respond to `ANY` queries. It may be better to call individual methods like {@link resolve4}, {@link resolveMx}, and so on. For more details, see + * [RFC 8482](https://tools.ietf.org/html/rfc8482). + */ + export function resolveAny( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + export namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-error) object, where `err.code` is + * one of the [DNS error codes](https://nodejs.org/docs/latest-v22.x/api/dns.html#error-codes). + * @since v0.1.16 + */ + export function reverse( + ip: string, + callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void, + ): void; + /** + * Get the default value for `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v22.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: for `order` defaulting to `ipv4first`. + * * `ipv6first`: for `order` defaulting to `ipv6first`. + * * `verbatim`: for `order` defaulting to `verbatim`. + * @since v18.17.0 + */ + export function getDefaultResultOrder(): "ipv4first" | "ipv6first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dns.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dns.setServers()` method must not be called while a DNS query is in + * progress. + * + * The {@link setServers} method affects only {@link resolve}, `dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}). + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v0.11.3 + * @param servers array of [RFC 5952](https://datatracker.ietf.org/doc/html/rfc5952#section-6) formatted addresses + */ + export function setServers(servers: readonly string[]): void; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v0.11.3 + */ + export function getServers(): string[]; + /** + * Set the default value of `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v22.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: sets default `order` to `ipv4first`. + * * `ipv6first`: sets default `order` to `ipv6first`. + * * `verbatim`: sets default `order` to `verbatim`. + * + * The default is `verbatim` and {@link setDefaultResultOrder} have higher + * priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--dns-result-orderorder). When using + * [worker threads](https://nodejs.org/docs/latest-v22.x/api/worker_threads.html), {@link setDefaultResultOrder} from the main + * thread won't affect the default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`. + */ + export function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void; + // Error codes + export const NODATA: "ENODATA"; + export const FORMERR: "EFORMERR"; + export const SERVFAIL: "ESERVFAIL"; + export const NOTFOUND: "ENOTFOUND"; + export const NOTIMP: "ENOTIMP"; + export const REFUSED: "EREFUSED"; + export const BADQUERY: "EBADQUERY"; + export const BADNAME: "EBADNAME"; + export const BADFAMILY: "EBADFAMILY"; + export const BADRESP: "EBADRESP"; + export const CONNREFUSED: "ECONNREFUSED"; + export const TIMEOUT: "ETIMEOUT"; + export const EOF: "EOF"; + export const FILE: "EFILE"; + export const NOMEM: "ENOMEM"; + export const DESTRUCTION: "EDESTRUCTION"; + export const BADSTR: "EBADSTR"; + export const BADFLAGS: "EBADFLAGS"; + export const NONAME: "ENONAME"; + export const BADHINTS: "EBADHINTS"; + export const NOTINITIALIZED: "ENOTINITIALIZED"; + export const LOADIPHLPAPI: "ELOADIPHLPAPI"; + export const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS"; + export const CANCELLED: "ECANCELLED"; + export interface ResolverOptions { + /** + * Query timeout in milliseconds, or `-1` to use the default timeout. + */ + timeout?: number | undefined; + /** + * The number of tries the resolver will try contacting each name server before giving up. + * @default 4 + */ + tries?: number | undefined; + /** + * The max retry timeout, in milliseconds. + * @default 0 + */ + maxTimeout?: number | undefined; + } + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v22.x/api/dns.html#dnssetserversservers) does not affect + * other resolvers: + * + * ```js + * import { Resolver } from 'node:dns'; + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org', (err, addresses) => { + * // ... + * }); + * ``` + * + * The following methods from the `node:dns` module are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v8.3.0 + */ + export class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTlsa: typeof resolveTlsa; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } + export { dnsPromises as promises }; +} +declare module "node:dns" { + export * from "dns"; +} diff --git a/node_modules/@types/node/dns/promises.d.ts b/node_modules/@types/node/dns/promises.d.ts new file mode 100644 index 0000000..a7ba9bb --- /dev/null +++ b/node_modules/@types/node/dns/promises.d.ts @@ -0,0 +1,503 @@ +/** + * The `dns.promises` API provides an alternative set of asynchronous DNS methods + * that return `Promise` objects rather than using callbacks. The API is accessible + * via `import { promises as dnsPromises } from 'node:dns'` or `import dnsPromises from 'node:dns/promises'`. + * @since v10.6.0 + */ +declare module "dns/promises" { + import { + AnyRecord, + CaaRecord, + LookupAddress, + LookupAllOptions, + LookupOneOptions, + LookupOptions, + MxRecord, + NaptrRecord, + RecordWithTtl, + ResolveOptions, + ResolverOptions, + ResolveWithTtlOptions, + SoaRecord, + SrvRecord, + TlsaRecord, + } from "node:dns"; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v10.6.0 + */ + function getServers(): string[]; + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the `Promise` is resolved with `addresses` being an array of objects with the properties `address` and `family`. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options) does not necessarily have anything to do with the DNS + * protocol. The implementation uses an operating system facility that can + * associate names with addresses and vice versa. This implementation can have + * subtle but important consequences on the behavior of any Node.js program. Please + * take some time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v20.x/api/dns.html#implementation-considerations) before + * using `dnsPromises.lookup()`. + * + * Example usage: + * + * ```js + * import dns from 'node:dns'; + * const dnsPromises = dns.promises; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('address: %j family: IPv%s', result.address, result.family); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * }); + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('addresses: %j', result); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * }); + * ``` + * @since v10.6.0 + */ + function lookup(hostname: string, family: number): Promise; + function lookup(hostname: string, options: LookupOneOptions): Promise; + function lookup(hostname: string, options: LookupAllOptions): Promise; + function lookup(hostname: string, options: LookupOptions): Promise; + function lookup(hostname: string): Promise; + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code. + * + * ```js + * import dnsPromises from 'node:dns'; + * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { + * console.log(result.hostname, result.service); + * // Prints: localhost ssh + * }); + * ``` + * @since v10.6.0 + */ + function lookupService( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. When successful, the `Promise` is resolved with an + * array of resource records. The type and structure of individual results vary + * based on `rrtype`: + * + * + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes). + * @since v10.6.0 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + function resolve(hostname: string): Promise; + function resolve(hostname: string, rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function resolve(hostname: string, rrtype: "ANY"): Promise; + function resolve(hostname: string, rrtype: "CAA"): Promise; + function resolve(hostname: string, rrtype: "MX"): Promise; + function resolve(hostname: string, rrtype: "NAPTR"): Promise; + function resolve(hostname: string, rrtype: "SOA"): Promise; + function resolve(hostname: string, rrtype: "SRV"): Promise; + function resolve(hostname: string, rrtype: "TLSA"): Promise; + function resolve(hostname: string, rrtype: "TXT"): Promise; + function resolve(hostname: string, rrtype: string): Promise< + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[] + >; + /** + * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv4 + * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve4(hostname: string): Promise; + function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve4(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv6 + * addresses. + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve6(hostname: string): Promise; + function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve6(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * On success, the `Promise` is resolved with an array containing various types of + * records. Each object has a property `type` that indicates the type of the + * current record. And depending on the `type`, additional properties will be + * present on the object: + * + * + * + * Here is an example of the result object: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * @since v10.6.0 + */ + function resolveAny(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success, + * the `Promise` is resolved with an array of objects containing available + * certification authority authorization records available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + function resolveCaa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success, + * the `Promise` is resolved with an array of canonical name records available for + * the `hostname` (e.g. `['bar.example.com']`). + * @since v10.6.0 + */ + function resolveCname(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects + * containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v10.6.0 + */ + function resolveMx(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. On success, the `Promise` is resolved with an array + * of objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v10.6.0 + */ + function resolveNaptr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. On success, the `Promise` is resolved with an array of name server + * records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`). + * @since v10.6.0 + */ + function resolveNs(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. On success, the `Promise` is resolved with an array of strings + * containing the reply records. + * @since v10.6.0 + */ + function resolvePtr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. On success, the `Promise` is resolved with an object with the + * following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v10.6.0 + */ + function resolveSoa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects with + * the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v10.6.0 + */ + function resolveSrv(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve certificate associations (`TLSA` records) for + * the `hostname`. On success, the `Promise` is resolved with an array of objectsAdd commentMore actions + * with these properties: + * + * * `certUsage` + * * `selector` + * * `match` + * * `data` + * + * ```js + * { + * certUsage: 3, + * selector: 1, + * match: 1, + * data: [ArrayBuffer] + * } + * ``` + * @since v22.15.0 + */ + function resolveTlsa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. On success, the `Promise` is resolved with a two-dimensional array + * of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v10.6.0 + */ + function resolveTxt(hostname: string): Promise; + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes). + * @since v10.6.0 + */ + function reverse(ip: string): Promise; + /** + * Get the default value for `verbatim` in {@link lookup} and [dnsPromises.lookup()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v20.1.0 + */ + function getDefaultResultOrder(): "ipv4first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dnsPromises.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dnsPromises.setServers()` method must not be called while a DNS query is in + * progress. + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v10.6.0 + * @param servers array of `RFC 5952` formatted addresses + */ + function setServers(servers: readonly string[]): void; + /** + * Set the default value of `order` in `dns.lookup()` and `{@link lookup}`. The value could be: + * + * * `ipv4first`: sets default `order` to `ipv4first`. + * * `ipv6first`: sets default `order` to `ipv6first`. + * * `verbatim`: sets default `order` to `verbatim`. + * + * The default is `verbatim` and [dnsPromises.setDefaultResultOrder()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * have higher priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder). + * When using [worker threads](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html), [`dnsPromises.setDefaultResultOrder()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * from the main thread won't affect the default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`. + */ + function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void; + // Error codes + const NODATA: "ENODATA"; + const FORMERR: "EFORMERR"; + const SERVFAIL: "ESERVFAIL"; + const NOTFOUND: "ENOTFOUND"; + const NOTIMP: "ENOTIMP"; + const REFUSED: "EREFUSED"; + const BADQUERY: "EBADQUERY"; + const BADNAME: "EBADNAME"; + const BADFAMILY: "EBADFAMILY"; + const BADRESP: "EBADRESP"; + const CONNREFUSED: "ECONNREFUSED"; + const TIMEOUT: "ETIMEOUT"; + const EOF: "EOF"; + const FILE: "EFILE"; + const NOMEM: "ENOMEM"; + const DESTRUCTION: "EDESTRUCTION"; + const BADSTR: "EBADSTR"; + const BADFLAGS: "EBADFLAGS"; + const NONAME: "ENONAME"; + const BADHINTS: "EBADHINTS"; + const NOTINITIALIZED: "ENOTINITIALIZED"; + const LOADIPHLPAPI: "ELOADIPHLPAPI"; + const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS"; + const CANCELLED: "ECANCELLED"; + + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetserversservers) does not affect + * other resolvers: + * + * ```js + * import { promises } from 'node:dns'; + * const resolver = new promises.Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org').then((addresses) => { + * // ... + * }); + * + * // Alternatively, the same code can be written using async-await style. + * (async function() { + * const addresses = await resolver.resolve4('example.org'); + * })(); + * ``` + * + * The following methods from the `dnsPromises` API are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v10.6.0 + */ + class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTlsa: typeof resolveTlsa; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} +declare module "node:dns/promises" { + export * from "dns/promises"; +} diff --git a/node_modules/@types/node/domain.d.ts b/node_modules/@types/node/domain.d.ts new file mode 100644 index 0000000..ba8a02c --- /dev/null +++ b/node_modules/@types/node/domain.d.ts @@ -0,0 +1,170 @@ +/** + * **This module is pending deprecation.** Once a replacement API has been + * finalized, this module will be fully deprecated. Most developers should + * **not** have cause to use this module. Users who absolutely must have + * the functionality that domains provide may rely on it for the time being + * but should expect to have to migrate to a different solution + * in the future. + * + * Domains provide a way to handle multiple different IO operations as a + * single group. If any of the event emitters or callbacks registered to a + * domain emit an `'error'` event, or throw an error, then the domain object + * will be notified, rather than losing the context of the error in the `process.on('uncaughtException')` handler, or causing the program to + * exit immediately with an error code. + * @deprecated Since v1.4.2 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/domain.js) + */ +declare module "domain" { + import EventEmitter = require("node:events"); + /** + * The `Domain` class encapsulates the functionality of routing errors and + * uncaught exceptions to the active `Domain` object. + * + * To handle the errors that it catches, listen to its `'error'` event. + */ + class Domain extends EventEmitter { + /** + * An array of timers and event emitters that have been explicitly added + * to the domain. + */ + members: Array; + /** + * The `enter()` method is plumbing used by the `run()`, `bind()`, and `intercept()` methods to set the active domain. It sets `domain.active` and `process.domain` to the domain, and implicitly + * pushes the domain onto the domain + * stack managed by the domain module (see {@link exit} for details on the + * domain stack). The call to `enter()` delimits the beginning of a chain of + * asynchronous calls and I/O operations bound to a domain. + * + * Calling `enter()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + enter(): void; + /** + * The `exit()` method exits the current domain, popping it off the domain stack. + * Any time execution is going to switch to the context of a different chain of + * asynchronous calls, it's important to ensure that the current domain is exited. + * The call to `exit()` delimits either the end of or an interruption to the chain + * of asynchronous calls and I/O operations bound to a domain. + * + * If there are multiple, nested domains bound to the current execution context, `exit()` will exit any domains nested within this domain. + * + * Calling `exit()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + exit(): void; + /** + * Run the supplied function in the context of the domain, implicitly + * binding all event emitters, timers, and low-level requests that are + * created in that context. Optionally, arguments can be passed to + * the function. + * + * This is the most basic way to use a domain. + * + * ```js + * import domain from 'node:domain'; + * import fs from 'node:fs'; + * const d = domain.create(); + * d.on('error', (er) => { + * console.error('Caught error!', er); + * }); + * d.run(() => { + * process.nextTick(() => { + * setTimeout(() => { // Simulating some various async stuff + * fs.open('non-existent file', 'r', (er, fd) => { + * if (er) throw er; + * // proceed... + * }); + * }, 100); + * }); + * }); + * ``` + * + * In this example, the `d.on('error')` handler will be triggered, rather + * than crashing the program. + */ + run(fn: (...args: any[]) => T, ...args: any[]): T; + /** + * Explicitly adds an emitter to the domain. If any event handlers called by + * the emitter throw an error, or if the emitter emits an `'error'` event, it + * will be routed to the domain's `'error'` event, just like with implicit + * binding. + * + * This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by + * the domain `'error'` handler. + * + * If the Timer or `EventEmitter` was already bound to a domain, it is removed + * from that one, and bound to this one instead. + * @param emitter emitter or timer to be added to the domain + */ + add(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The opposite of {@link add}. Removes domain handling from the + * specified emitter. + * @param emitter emitter or timer to be removed from the domain + */ + remove(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The returned function will be a wrapper around the supplied callback + * function. When the returned function is called, any errors that are + * thrown will be routed to the domain's `'error'` event. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.bind((er, data) => { + * // If this throws, it will also be passed to the domain. + * return cb(er, data ? JSON.parse(data) : null); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The bound function + */ + bind(callback: T): T; + /** + * This method is almost identical to {@link bind}. However, in + * addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function. + * + * In this way, the common `if (err) return callback(err);` pattern can be replaced + * with a single error handler in a single place. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.intercept((data) => { + * // Note, the first argument is never passed to the + * // callback since it is assumed to be the 'Error' argument + * // and thus intercepted by the domain. + * + * // If this throws, it will also be passed to the domain + * // so the error-handling logic can be moved to the 'error' + * // event on the domain instead of being repeated throughout + * // the program. + * return cb(null, JSON.parse(data)); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The intercepted function + */ + intercept(callback: T): T; + } + function create(): Domain; +} +declare module "node:domain" { + export * from "domain"; +} diff --git a/node_modules/@types/node/events.d.ts b/node_modules/@types/node/events.d.ts new file mode 100644 index 0000000..c336a28 --- /dev/null +++ b/node_modules/@types/node/events.d.ts @@ -0,0 +1,976 @@ +/** + * Much of the Node.js core API is built around an idiomatic asynchronous + * event-driven architecture in which certain kinds of objects (called "emitters") + * emit named events that cause `Function` objects ("listeners") to be called. + * + * For instance: a `net.Server` object emits an event each time a peer + * connects to it; a `fs.ReadStream` emits an event when the file is opened; + * a `stream` emits an event whenever data is available to be read. + * + * All objects that emit events are instances of the `EventEmitter` class. These + * objects expose an `eventEmitter.on()` function that allows one or more + * functions to be attached to named events emitted by the object. Typically, + * event names are camel-cased strings but any valid JavaScript property key + * can be used. + * + * When the `EventEmitter` object emits an event, all of the functions attached + * to that specific event are called _synchronously_. Any values returned by the + * called listeners are _ignored_ and discarded. + * + * The following example shows a simple `EventEmitter` instance with a single + * listener. The `eventEmitter.on()` method is used to register listeners, while + * the `eventEmitter.emit()` method is used to trigger the event. + * + * ```js + * import { EventEmitter } from 'node:events'; + * + * class MyEmitter extends EventEmitter {} + * + * const myEmitter = new MyEmitter(); + * myEmitter.on('event', () => { + * console.log('an event occurred!'); + * }); + * myEmitter.emit('event'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/events.js) + */ +declare module "events" { + import { AsyncResource, AsyncResourceOptions } from "node:async_hooks"; + interface EventEmitterOptions { + /** + * Enables automatic capturing of promise rejection. + */ + captureRejections?: boolean | undefined; + } + interface StaticEventEmitterOptions { + /** + * Can be used to cancel awaiting events. + */ + signal?: AbortSignal | undefined; + } + interface StaticEventEmitterIteratorOptions extends StaticEventEmitterOptions { + /** + * Names of events that will end the iteration. + */ + close?: string[] | undefined; + /** + * The high watermark. The emitter is paused every time the size of events being buffered is higher than it. + * Supported only on emitters implementing `pause()` and `resume()` methods. + * @default Number.MAX_SAFE_INTEGER + */ + highWaterMark?: number | undefined; + /** + * The low watermark. The emitter is resumed every time the size of events being buffered is lower than it. + * Supported only on emitters implementing `pause()` and `resume()` methods. + * @default 1 + */ + lowWaterMark?: number | undefined; + } + interface EventEmitter = DefaultEventMap> extends NodeJS.EventEmitter {} + type EventMap = Record | DefaultEventMap; + type DefaultEventMap = [never]; + type AnyRest = [...args: any[]]; + type Args = T extends DefaultEventMap ? AnyRest : ( + K extends keyof T ? T[K] : never + ); + type Key = T extends DefaultEventMap ? string | symbol : K | keyof T; + type Key2 = T extends DefaultEventMap ? string | symbol : K & keyof T; + type Listener = T extends DefaultEventMap ? F : ( + K extends keyof T ? ( + T[K] extends unknown[] ? (...args: T[K]) => void : never + ) + : never + ); + type Listener1 = Listener void>; + type Listener2 = Listener; + + /** + * The `EventEmitter` class is defined and exposed by the `node:events` module: + * + * ```js + * import { EventEmitter } from 'node:events'; + * ``` + * + * All `EventEmitter`s emit the event `'newListener'` when new listeners are + * added and `'removeListener'` when existing listeners are removed. + * + * It supports the following option: + * @since v0.1.26 + */ + class EventEmitter = DefaultEventMap> { + constructor(options?: EventEmitterOptions); + + [EventEmitter.captureRejectionSymbol]?(error: Error, event: Key, ...args: Args): void; + + /** + * Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given + * event or that is rejected if the `EventEmitter` emits `'error'` while waiting. + * The `Promise` will resolve with an array of all the arguments emitted to the + * given event. + * + * This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event + * semantics and does not listen to the `'error'` event. + * + * ```js + * import { once, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * process.nextTick(() => { + * ee.emit('myevent', 42); + * }); + * + * const [value] = await once(ee, 'myevent'); + * console.log(value); + * + * const err = new Error('kaboom'); + * process.nextTick(() => { + * ee.emit('error', err); + * }); + * + * try { + * await once(ee, 'myevent'); + * } catch (err) { + * console.error('error happened', err); + * } + * ``` + * + * The special handling of the `'error'` event is only used when `events.once()` is used to wait for another event. If `events.once()` is used to wait for the + * '`error'` event itself, then it is treated as any other kind of event without + * special handling: + * + * ```js + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.error('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * const ac = new AbortController(); + * + * async function foo(emitter, event, signal) { + * try { + * await once(emitter, event, { signal }); + * console.log('event emitted!'); + * } catch (error) { + * if (error.name === 'AbortError') { + * console.error('Waiting for the event was canceled!'); + * } else { + * console.error('There was an error', error.message); + * } + * } + * } + * + * foo(ee, 'foo', ac.signal); + * ac.abort(); // Abort waiting for the event + * ee.emit('foo'); // Prints: Waiting for the event was canceled! + * ``` + * @since v11.13.0, v10.16.0 + */ + static once( + emitter: NodeJS.EventEmitter, + eventName: string | symbol, + options?: StaticEventEmitterOptions, + ): Promise; + static once(emitter: EventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + /** + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo')) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * ``` + * + * Returns an `AsyncIterator` that iterates `eventName` events. It will throw + * if the `EventEmitter` emits `'error'`. It removes all listeners when + * exiting the loop. The `value` returned by each iteration is an array + * composed of the emitted event arguments. + * + * An `AbortSignal` can be used to cancel waiting on events: + * + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ac = new AbortController(); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo', { signal: ac.signal })) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * + * process.nextTick(() => ac.abort()); + * ``` + * + * Use the `close` option to specify an array of event names that will end the iteration: + * + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * ee.emit('close'); + * }); + * + * for await (const event of on(ee, 'foo', { close: ['close'] })) { + * console.log(event); // prints ['bar'] [42] + * } + * // the loop will exit after 'close' is emitted + * console.log('done'); // prints 'done' + * ``` + * @since v13.6.0, v12.16.0 + * @return An `AsyncIterator` that iterates `eventName` events emitted by the `emitter` + */ + static on( + emitter: NodeJS.EventEmitter, + eventName: string | symbol, + options?: StaticEventEmitterIteratorOptions, + ): NodeJS.AsyncIterator; + static on( + emitter: EventTarget, + eventName: string, + options?: StaticEventEmitterIteratorOptions, + ): NodeJS.AsyncIterator; + /** + * A class method that returns the number of listeners for the given `eventName` registered on the given `emitter`. + * + * ```js + * import { EventEmitter, listenerCount } from 'node:events'; + * + * const myEmitter = new EventEmitter(); + * myEmitter.on('event', () => {}); + * myEmitter.on('event', () => {}); + * console.log(listenerCount(myEmitter, 'event')); + * // Prints: 2 + * ``` + * @since v0.9.12 + * @deprecated Since v3.2.0 - Use `listenerCount` instead. + * @param emitter The emitter to query + * @param eventName The event name + */ + static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * For `EventEmitter`s this behaves exactly the same as calling `.listeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the event listeners for the + * event target. This is useful for debugging and diagnostic purposes. + * + * ```js + * import { getEventListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] + * } + * ``` + * @since v15.2.0, v14.17.0 + */ + static getEventListeners(emitter: EventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; + /** + * Returns the currently set max amount of listeners. + * + * For `EventEmitter`s this behaves exactly the same as calling `.getMaxListeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the max event listeners for the + * event target. If the number of event handlers on a single EventTarget exceeds + * the max set, the EventTarget will print a warning. + * + * ```js + * import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * console.log(getMaxListeners(ee)); // 10 + * setMaxListeners(11, ee); + * console.log(getMaxListeners(ee)); // 11 + * } + * { + * const et = new EventTarget(); + * console.log(getMaxListeners(et)); // 10 + * setMaxListeners(11, et); + * console.log(getMaxListeners(et)); // 11 + * } + * ``` + * @since v19.9.0 + */ + static getMaxListeners(emitter: EventTarget | NodeJS.EventEmitter): number; + /** + * ```js + * import { setMaxListeners, EventEmitter } from 'node:events'; + * + * const target = new EventTarget(); + * const emitter = new EventEmitter(); + * + * setMaxListeners(5, target, emitter); + * ``` + * @since v15.4.0 + * @param n A non-negative number. The maximum number of listeners per `EventTarget` event. + * @param eventTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter} + * objects. + */ + static setMaxListeners(n?: number, ...eventTargets: Array): void; + /** + * Listens once to the `abort` event on the provided `signal`. + * + * Listening to the `abort` event on abort signals is unsafe and may + * lead to resource leaks since another third party with the signal can + * call `e.stopImmediatePropagation()`. Unfortunately Node.js cannot change + * this since it would violate the web standard. Additionally, the original + * API makes it easy to forget to remove listeners. + * + * This API allows safely using `AbortSignal`s in Node.js APIs by solving these + * two issues by listening to the event such that `stopImmediatePropagation` does + * not prevent the listener from running. + * + * Returns a disposable so that it may be unsubscribed from more easily. + * + * ```js + * import { addAbortListener } from 'node:events'; + * + * function example(signal) { + * let disposable; + * try { + * signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); + * disposable = addAbortListener(signal, (e) => { + * // Do something when signal is aborted. + * }); + * } finally { + * disposable?.[Symbol.dispose](); + * } + * } + * ``` + * @since v20.5.0 + * @return Disposable that removes the `abort` listener. + */ + static addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable; + /** + * This symbol shall be used to install a listener for only monitoring `'error'` events. Listeners installed using this symbol are called before the regular `'error'` listeners are called. + * + * Installing a listener using this symbol does not change the behavior once an `'error'` event is emitted. Therefore, the process will still crash if no + * regular `'error'` listener is installed. + * @since v13.6.0, v12.17.0 + */ + static readonly errorMonitor: unique symbol; + /** + * Value: `Symbol.for('nodejs.rejection')` + * + * See how to write a custom `rejection handler`. + * @since v13.4.0, v12.16.0 + */ + static readonly captureRejectionSymbol: unique symbol; + /** + * Value: [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) + * + * Change the default `captureRejections` option on all new `EventEmitter` objects. + * @since v13.4.0, v12.16.0 + */ + static captureRejections: boolean; + /** + * By default, a maximum of `10` listeners can be registered for any single + * event. This limit can be changed for individual `EventEmitter` instances + * using the `emitter.setMaxListeners(n)` method. To change the default + * for _all_`EventEmitter` instances, the `events.defaultMaxListeners` property + * can be used. If this value is not a positive number, a `RangeError` is thrown. + * + * Take caution when setting the `events.defaultMaxListeners` because the + * change affects _all_ `EventEmitter` instances, including those created before + * the change is made. However, calling `emitter.setMaxListeners(n)` still has + * precedence over `events.defaultMaxListeners`. + * + * This is not a hard limit. The `EventEmitter` instance will allow + * more listeners to be added but will output a trace warning to stderr indicating + * that a "possible EventEmitter memory leak" has been detected. For any single + * `EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()` methods can be used to + * temporarily avoid this warning: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.setMaxListeners(emitter.getMaxListeners() + 1); + * emitter.once('event', () => { + * // do stuff + * emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); + * }); + * ``` + * + * The `--trace-warnings` command-line flag can be used to display the + * stack trace for such warnings. + * + * The emitted warning can be inspected with `process.on('warning')` and will + * have the additional `emitter`, `type`, and `count` properties, referring to + * the event emitter instance, the event's name and the number of attached + * listeners, respectively. + * Its `name` property is set to `'MaxListenersExceededWarning'`. + * @since v0.11.2 + */ + static defaultMaxListeners: number; + } + import internal = require("node:events"); + namespace EventEmitter { + // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4 + export { internal as EventEmitter }; + export interface Abortable { + /** + * When provided the corresponding `AbortController` can be used to cancel an asynchronous action. + */ + signal?: AbortSignal | undefined; + } + + export interface EventEmitterReferencingAsyncResource extends AsyncResource { + readonly eventEmitter: EventEmitterAsyncResource; + } + + export interface EventEmitterAsyncResourceOptions extends AsyncResourceOptions, EventEmitterOptions { + /** + * The type of async event, this is required when instantiating `EventEmitterAsyncResource` + * directly rather than as a child class. + * @default new.target.name if instantiated as a child class. + */ + name?: string | undefined; + } + + /** + * Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that + * require manual async tracking. Specifically, all events emitted by instances + * of `events.EventEmitterAsyncResource` will run within its `async context`. + * + * ```js + * import { EventEmitterAsyncResource, EventEmitter } from 'node:events'; + * import { notStrictEqual, strictEqual } from 'node:assert'; + * import { executionAsyncId, triggerAsyncId } from 'node:async_hooks'; + * + * // Async tracking tooling will identify this as 'Q'. + * const ee1 = new EventEmitterAsyncResource({ name: 'Q' }); + * + * // 'foo' listeners will run in the EventEmitters async context. + * ee1.on('foo', () => { + * strictEqual(executionAsyncId(), ee1.asyncId); + * strictEqual(triggerAsyncId(), ee1.triggerAsyncId); + * }); + * + * const ee2 = new EventEmitter(); + * + * // 'foo' listeners on ordinary EventEmitters that do not track async + * // context, however, run in the same async context as the emit(). + * ee2.on('foo', () => { + * notStrictEqual(executionAsyncId(), ee2.asyncId); + * notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId); + * }); + * + * Promise.resolve().then(() => { + * ee1.emit('foo'); + * ee2.emit('foo'); + * }); + * ``` + * + * The `EventEmitterAsyncResource` class has the same methods and takes the + * same options as `EventEmitter` and `AsyncResource` themselves. + * @since v17.4.0, v16.14.0 + */ + export class EventEmitterAsyncResource extends EventEmitter { + /** + * @param options Only optional in child class. + */ + constructor(options?: EventEmitterAsyncResourceOptions); + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + */ + emitDestroy(): void; + /** + * The unique `asyncId` assigned to the resource. + */ + readonly asyncId: number; + /** + * The same triggerAsyncId that is passed to the AsyncResource constructor. + */ + readonly triggerAsyncId: number; + /** + * The returned `AsyncResource` object has an additional `eventEmitter` property + * that provides a reference to this `EventEmitterAsyncResource`. + */ + readonly asyncResource: EventEmitterReferencingAsyncResource; + } + /** + * The `NodeEventTarget` is a Node.js-specific extension to `EventTarget` + * that emulates a subset of the `EventEmitter` API. + * @since v14.5.0 + */ + export interface NodeEventTarget extends EventTarget { + /** + * Node.js-specific extension to the `EventTarget` class that emulates the + * equivalent `EventEmitter` API. The only difference between `addListener()` and + * `addEventListener()` is that `addListener()` will return a reference to the + * `EventTarget`. + * @since v14.5.0 + */ + addListener(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class that dispatches the + * `arg` to the list of handlers for `type`. + * @since v15.2.0 + * @returns `true` if event listeners registered for the `type` exist, + * otherwise `false`. + */ + emit(type: string, arg: any): boolean; + /** + * Node.js-specific extension to the `EventTarget` class that returns an array + * of event `type` names for which event listeners are registered. + * @since 14.5.0 + */ + eventNames(): string[]; + /** + * Node.js-specific extension to the `EventTarget` class that returns the number + * of event listeners registered for the `type`. + * @since v14.5.0 + */ + listenerCount(type: string): number; + /** + * Node.js-specific extension to the `EventTarget` class that sets the number + * of max event listeners as `n`. + * @since v14.5.0 + */ + setMaxListeners(n: number): void; + /** + * Node.js-specific extension to the `EventTarget` class that returns the number + * of max event listeners. + * @since v14.5.0 + */ + getMaxListeners(): number; + /** + * Node.js-specific alias for `eventTarget.removeEventListener()`. + * @since v14.5.0 + */ + off(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + /** + * Node.js-specific alias for `eventTarget.addEventListener()`. + * @since v14.5.0 + */ + on(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class that adds a `once` + * listener for the given event `type`. This is equivalent to calling `on` + * with the `once` option set to `true`. + * @since v14.5.0 + */ + once(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class. If `type` is specified, + * removes all registered listeners for `type`, otherwise removes all registered + * listeners. + * @since v14.5.0 + */ + removeAllListeners(type?: string): this; + /** + * Node.js-specific extension to the `EventTarget` class that removes the + * `listener` for the given `type`. The only difference between `removeListener()` + * and `removeEventListener()` is that `removeListener()` will return a reference + * to the `EventTarget`. + * @since v14.5.0 + */ + removeListener(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + } + } + global { + namespace NodeJS { + interface EventEmitter = DefaultEventMap> { + [EventEmitter.captureRejectionSymbol]?(error: Error, event: Key, ...args: Args): void; + /** + * Alias for `emitter.on(eventName, listener)`. + * @since v0.1.26 + */ + addListener(eventName: Key, listener: Listener1): this; + /** + * Adds the `listener` function to the end of the listeners array for the event + * named `eventName`. No checks are made to see if the `listener` has already + * been added. Multiple calls passing the same combination of `eventName` and + * `listener` will result in the `listener` being added, and called, multiple times. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The `emitter.prependListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEE = new EventEmitter(); + * myEE.on('foo', () => console.log('a')); + * myEE.prependListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.1.101 + * @param eventName The name of the event. + * @param listener The callback function + */ + on(eventName: Key, listener: Listener1): this; + /** + * Adds a **one-time** `listener` function for the event named `eventName`. The + * next time `eventName` is triggered, this listener is removed and then invoked. + * + * ```js + * server.once('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The `emitter.prependOnceListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEE = new EventEmitter(); + * myEE.once('foo', () => console.log('a')); + * myEE.prependOnceListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.3.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + once(eventName: Key, listener: Listener1): this; + /** + * Removes the specified `listener` from the listener array for the event named `eventName`. + * + * ```js + * const callback = (stream) => { + * console.log('someone connected!'); + * }; + * server.on('connection', callback); + * // ... + * server.removeListener('connection', callback); + * ``` + * + * `removeListener()` will remove, at most, one instance of a listener from the + * listener array. If any single listener has been added multiple times to the + * listener array for the specified `eventName`, then `removeListener()` must be + * called multiple times to remove each instance. + * + * Once an event is emitted, all listeners attached to it at the + * time of emitting are called in order. This implies that any `removeListener()` or `removeAllListeners()` calls _after_ emitting and _before_ the last listener finishes execution + * will not remove them from`emit()` in progress. Subsequent events behave as expected. + * + * ```js + * import { EventEmitter } from 'node:events'; + * class MyEmitter extends EventEmitter {} + * const myEmitter = new MyEmitter(); + * + * const callbackA = () => { + * console.log('A'); + * myEmitter.removeListener('event', callbackB); + * }; + * + * const callbackB = () => { + * console.log('B'); + * }; + * + * myEmitter.on('event', callbackA); + * + * myEmitter.on('event', callbackB); + * + * // callbackA removes listener callbackB but it will still be called. + * // Internal listener array at time of emit [callbackA, callbackB] + * myEmitter.emit('event'); + * // Prints: + * // A + * // B + * + * // callbackB is now removed. + * // Internal listener array [callbackA] + * myEmitter.emit('event'); + * // Prints: + * // A + * ``` + * + * Because listeners are managed using an internal array, calling this will + * change the position indices of any listener registered _after_ the listener + * being removed. This will not impact the order in which listeners are called, + * but it means that any copies of the listener array as returned by + * the `emitter.listeners()` method will need to be recreated. + * + * When a single function has been added as a handler multiple times for a single + * event (as in the example below), `removeListener()` will remove the most + * recently added instance. In the example the `once('ping')` listener is removed: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const ee = new EventEmitter(); + * + * function pong() { + * console.log('pong'); + * } + * + * ee.on('ping', pong); + * ee.once('ping', pong); + * ee.removeListener('ping', pong); + * + * ee.emit('ping'); + * ee.emit('ping'); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeListener(eventName: Key, listener: Listener1): this; + /** + * Alias for `emitter.removeListener()`. + * @since v10.0.0 + */ + off(eventName: Key, listener: Listener1): this; + /** + * Removes all listeners, or those of the specified `eventName`. + * + * It is bad practice to remove listeners added elsewhere in the code, + * particularly when the `EventEmitter` instance was created by some other + * component or module (e.g. sockets or file streams). + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeAllListeners(eventName?: Key): this; + /** + * By default `EventEmitter`s will print a warning if more than `10` listeners are + * added for a particular event. This is a useful default that helps finding + * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be + * modified for this specific `EventEmitter` instance. The value can be set to `Infinity` (or `0`) to indicate an unlimited number of listeners. + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.3.5 + */ + setMaxListeners(n: number): this; + /** + * Returns the current max listener value for the `EventEmitter` which is either + * set by `emitter.setMaxListeners(n)` or defaults to {@link EventEmitter.defaultMaxListeners}. + * @since v1.0.0 + */ + getMaxListeners(): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * console.log(util.inspect(server.listeners('connection'))); + * // Prints: [ [Function] ] + * ``` + * @since v0.1.26 + */ + listeners(eventName: Key): Array>; + /** + * Returns a copy of the array of listeners for the event named `eventName`, + * including any wrappers (such as those created by `.once()`). + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.once('log', () => console.log('log once')); + * + * // Returns a new Array with a function `onceWrapper` which has a property + * // `listener` which contains the original listener bound above + * const listeners = emitter.rawListeners('log'); + * const logFnWrapper = listeners[0]; + * + * // Logs "log once" to the console and does not unbind the `once` event + * logFnWrapper.listener(); + * + * // Logs "log once" to the console and removes the listener + * logFnWrapper(); + * + * emitter.on('log', () => console.log('log persistently')); + * // Will return a new Array with a single function bound by `.on()` above + * const newListeners = emitter.rawListeners('log'); + * + * // Logs "log persistently" twice + * newListeners[0](); + * emitter.emit('log'); + * ``` + * @since v9.4.0 + */ + rawListeners(eventName: Key): Array>; + /** + * Synchronously calls each of the listeners registered for the event named `eventName`, in the order they were registered, passing the supplied arguments + * to each. + * + * Returns `true` if the event had listeners, `false` otherwise. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEmitter = new EventEmitter(); + * + * // First listener + * myEmitter.on('event', function firstListener() { + * console.log('Helloooo! first listener'); + * }); + * // Second listener + * myEmitter.on('event', function secondListener(arg1, arg2) { + * console.log(`event with parameters ${arg1}, ${arg2} in second listener`); + * }); + * // Third listener + * myEmitter.on('event', function thirdListener(...args) { + * const parameters = args.join(', '); + * console.log(`event with parameters ${parameters} in third listener`); + * }); + * + * console.log(myEmitter.listeners('event')); + * + * myEmitter.emit('event', 1, 2, 3, 4, 5); + * + * // Prints: + * // [ + * // [Function: firstListener], + * // [Function: secondListener], + * // [Function: thirdListener] + * // ] + * // Helloooo! first listener + * // event with parameters 1, 2 in second listener + * // event with parameters 1, 2, 3, 4, 5 in third listener + * ``` + * @since v0.1.26 + */ + emit(eventName: Key, ...args: Args): boolean; + /** + * Returns the number of listeners listening for the event named `eventName`. + * If `listener` is provided, it will return how many times the listener is found + * in the list of the listeners of the event. + * @since v3.2.0 + * @param eventName The name of the event being listened for + * @param listener The event handler function + */ + listenerCount(eventName: Key, listener?: Listener2): number; + /** + * Adds the `listener` function to the _beginning_ of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName` + * and `listener` will result in the `listener` being added, and called, multiple times. + * + * ```js + * server.prependListener('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependListener(eventName: Key, listener: Listener1): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName` to the _beginning_ of the listeners array. The next time `eventName` is triggered, this + * listener is removed, and then invoked. + * + * ```js + * server.prependOnceListener('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependOnceListener(eventName: Key, listener: Listener1): this; + /** + * Returns an array listing the events for which the emitter has registered + * listeners. The values in the array are strings or `Symbol`s. + * + * ```js + * import { EventEmitter } from 'node:events'; + * + * const myEE = new EventEmitter(); + * myEE.on('foo', () => {}); + * myEE.on('bar', () => {}); + * + * const sym = Symbol('symbol'); + * myEE.on(sym, () => {}); + * + * console.log(myEE.eventNames()); + * // Prints: [ 'foo', 'bar', Symbol(symbol) ] + * ``` + * @since v6.0.0 + */ + eventNames(): Array<(string | symbol) & Key2>; + } + } + } + export = EventEmitter; +} +declare module "node:events" { + import events = require("events"); + export = events; +} diff --git a/node_modules/@types/node/fs.d.ts b/node_modules/@types/node/fs.d.ts new file mode 100644 index 0000000..d40515b --- /dev/null +++ b/node_modules/@types/node/fs.d.ts @@ -0,0 +1,4461 @@ +/** + * The `node:fs` module enables interacting with the file system in a + * way modeled on standard POSIX functions. + * + * To use the promise-based APIs: + * + * ```js + * import * as fs from 'node:fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from 'node:fs'; + * ``` + * + * All file system operations have synchronous, callback, and promise-based + * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/fs.js) + */ +declare module "fs" { + import { NonSharedBuffer } from "node:buffer"; + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import { URL } from "node:url"; + import * as promises from "node:fs/promises"; + export { promises }; + /** + * Valid types for path values in "fs". + */ + export type PathLike = string | Buffer | URL; + export type PathOrFileDescriptor = PathLike | number; + export type TimeLike = string | number | Date; + export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + export type BufferEncodingOption = + | "buffer" + | { + encoding: "buffer"; + }; + export interface ObjectEncodingOptions { + encoding?: BufferEncoding | null | undefined; + } + export type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; + export type OpenMode = number | string; + export type Mode = number | string; + export interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + export interface Stats extends StatsBase {} + /** + * A `fs.Stats` object provides information about a file. + * + * Objects returned from {@link stat}, {@link lstat}, {@link fstat}, and + * their synchronous counterparts are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`, and the object will contain additional + * nanosecond-precision properties suffixed with `Ns`. `Stat` objects are not to be created directly using the `new` keyword. + * + * ```console + * Stats { + * dev: 2114, + * ino: 48064969, + * mode: 33188, + * nlink: 1, + * uid: 85, + * gid: 100, + * rdev: 0, + * size: 527, + * blksize: 4096, + * blocks: 8, + * atimeMs: 1318289051000.1, + * mtimeMs: 1318289051000.1, + * ctimeMs: 1318289051000.1, + * birthtimeMs: 1318289051000.1, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * + * `bigint` version: + * + * ```console + * BigIntStats { + * dev: 2114n, + * ino: 48064969n, + * mode: 33188n, + * nlink: 1n, + * uid: 85n, + * gid: 100n, + * rdev: 0n, + * size: 527n, + * blksize: 4096n, + * blocks: 8n, + * atimeMs: 1318289051000n, + * mtimeMs: 1318289051000n, + * ctimeMs: 1318289051000n, + * birthtimeMs: 1318289051000n, + * atimeNs: 1318289051000000000n, + * mtimeNs: 1318289051000000000n, + * ctimeNs: 1318289051000000000n, + * birthtimeNs: 1318289051000000000n, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * @since v0.1.21 + */ + export class Stats { + private constructor(); + } + export interface StatsFsBase { + /** Type of file system. */ + type: T; + /** Optimal transfer block size. */ + bsize: T; + /** Total data blocks in file system. */ + blocks: T; + /** Free blocks in file system. */ + bfree: T; + /** Available blocks for unprivileged users */ + bavail: T; + /** Total file nodes in file system. */ + files: T; + /** Free file nodes in file system. */ + ffree: T; + } + export interface StatsFs extends StatsFsBase {} + /** + * Provides information about a mounted file system. + * + * Objects returned from {@link statfs} and its synchronous counterpart are of + * this type. If `bigint` in the `options` passed to those methods is `true`, the + * numeric values will be `bigint` instead of `number`. + * + * ```console + * StatFs { + * type: 1397114950, + * bsize: 4096, + * blocks: 121938943, + * bfree: 61058895, + * bavail: 61058895, + * files: 999, + * ffree: 1000000 + * } + * ``` + * + * `bigint` version: + * + * ```console + * StatFs { + * type: 1397114950n, + * bsize: 4096n, + * blocks: 121938943n, + * bfree: 61058895n, + * bavail: 61058895n, + * files: 999n, + * ffree: 1000000n + * } + * ``` + * @since v19.6.0, v18.15.0 + */ + export class StatsFs {} + export interface BigIntStatsFs extends StatsFsBase {} + export interface StatFsOptions { + bigint?: boolean | undefined; + } + /** + * A representation of a directory entry, which can be a file or a subdirectory + * within the directory, as returned by reading from an `fs.Dir`. The + * directory entry is a combination of the file name and file type pairs. + * + * Additionally, when {@link readdir} or {@link readdirSync} is called with + * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s. + * @since v10.10.0 + */ + export class Dirent { + /** + * Returns `true` if the `fs.Dirent` object describes a regular file. + * @since v10.10.0 + */ + isFile(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a file system + * directory. + * @since v10.10.0 + */ + isDirectory(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a block device. + * @since v10.10.0 + */ + isBlockDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a character device. + * @since v10.10.0 + */ + isCharacterDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a symbolic link. + * @since v10.10.0 + */ + isSymbolicLink(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a first-in-first-out + * (FIFO) pipe. + * @since v10.10.0 + */ + isFIFO(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a socket. + * @since v10.10.0 + */ + isSocket(): boolean; + /** + * The file name that this `fs.Dirent` object refers to. The type of this + * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. + * @since v10.10.0 + */ + name: Name; + /** + * The path to the parent directory of the file this `fs.Dirent` object refers to. + * @since v20.12.0, v18.20.0 + */ + parentPath: string; + /** + * Alias for `dirent.parentPath`. + * @since v20.1.0 + * @deprecated Since v20.12.0 + */ + path: string; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + */ + export class Dir implements AsyncIterable { + /** + * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or `fsPromises.opendir()`. + * @since v12.12.0 + */ + readonly path: string; + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * + * A promise is returned that will be fulfilled after the resource has been + * closed. + * @since v12.12.0 + */ + close(): Promise; + close(cb: NoParamCallback): void; + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * @since v12.12.0 + */ + closeSync(): void; + /** + * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. + * + * A promise is returned that will be fulfilled with an `fs.Dirent`, or `null` if there are no more directory entries to read. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + * @return containing {fs.Dirent|null} + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + /** + * Synchronously read the next directory entry as an `fs.Dirent`. See the + * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail. + * + * If there are no more directory entries to read, `null` will be returned. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + */ + readSync(): Dirent | null; + /** + * Calls `dir.close()` if the directory handle is open, and returns a promise that + * fulfills when disposal is complete. + * @since v22.17.0 + * @experimental + */ + [Symbol.asyncDispose](): Promise; + /** + * Calls `dir.closeSync()` if the directory handle is open, and returns + * `undefined`. + * @since v22.17.0 + * @experimental + */ + [Symbol.dispose](): void; + } + /** + * Class: fs.StatWatcher + * @since v14.3.0, v12.20.0 + * Extends `EventEmitter` + * A successful call to {@link watchFile} method will return a new fs.StatWatcher object. + */ + export interface StatWatcher extends EventEmitter { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.StatWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.StatWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.StatWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.StatWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + } + export interface FSWatcher extends EventEmitter { + /** + * Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the `fs.FSWatcher` object is no longer usable. + * @since v0.5.8 + */ + close(): void; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.FSWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.FSWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.FSWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.FSWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + /** + * events.EventEmitter + * 1. change + * 2. close + * 3. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "change", listener: (eventType: string, filename: string | NonSharedBuffer) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "change", listener: (eventType: string, filename: string | NonSharedBuffer) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "change", listener: (eventType: string, filename: string | NonSharedBuffer) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener( + event: "change", + listener: (eventType: string, filename: string | NonSharedBuffer) => void, + ): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "change", + listener: (eventType: string, filename: string | NonSharedBuffer) => void, + ): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + } + /** + * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. + * @since v0.1.93 + */ + export class ReadStream extends stream.Readable { + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes that have been read so far. + * @since v6.4.0 + */ + bytesRead: number; + /** + * The path to the file the stream is reading from as specified in the first + * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a + * `Buffer`. If `fd` is specified, then`readStream.path` will be `undefined`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0, v10.16.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: K, listener: ReadStreamEvents[K]): this; + on(event: K, listener: ReadStreamEvents[K]): this; + once(event: K, listener: ReadStreamEvents[K]): this; + prependListener(event: K, listener: ReadStreamEvents[K]): this; + prependOnceListener(event: K, listener: ReadStreamEvents[K]): this; + } + + /** + * The Keys are events of the ReadStream and the values are the functions that are called when the event is emitted. + */ + type ReadStreamEvents = { + close: () => void; + data: (chunk: Buffer | string) => void; + end: () => void; + error: (err: Error) => void; + open: (fd: number) => void; + pause: () => void; + readable: () => void; + ready: () => void; + resume: () => void; + } & CustomEvents; + + /** + * string & {} allows to allow any kind of strings for the event + * but still allows to have auto completion for the normal events. + */ + type CustomEvents = { [Key in string & {} | symbol]: (...args: any[]) => void }; + + /** + * The Keys are events of the WriteStream and the values are the functions that are called when the event is emitted. + */ + type WriteStreamEvents = { + close: () => void; + drain: () => void; + error: (err: Error) => void; + finish: () => void; + open: (fd: number) => void; + pipe: (src: stream.Readable) => void; + ready: () => void; + unpipe: (src: stream.Readable) => void; + } & CustomEvents; + /** + * * Extends `stream.Writable` + * + * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. + * @since v0.1.93 + */ + export class WriteStream extends stream.Writable { + /** + * Closes `writeStream`. Optionally accepts a + * callback that will be executed once the `writeStream`is closed. + * @since v0.9.4 + */ + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes written so far. Does not include data that is still queued + * for writing. + * @since v0.4.7 + */ + bytesWritten: number; + /** + * The path to the file the stream is writing to as specified in the first + * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a + * `Buffer`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: K, listener: WriteStreamEvents[K]): this; + on(event: K, listener: WriteStreamEvents[K]): this; + once(event: K, listener: WriteStreamEvents[K]): this; + prependListener(event: K, listener: WriteStreamEvents[K]): this; + prependOnceListener(event: K, listener: WriteStreamEvents[K]): this; + } + /** + * Asynchronously rename file at `oldPath` to the pathname provided + * as `newPath`. In the case that `newPath` already exists, it will + * be overwritten. If there is a directory at `newPath`, an error will + * be raised instead. No arguments other than a possible exception are + * given to the completion callback. + * + * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). + * + * ```js + * import { rename } from 'node:fs'; + * + * rename('oldFile.txt', 'newFile.txt', (err) => { + * if (err) throw err; + * console.log('Rename complete!'); + * }); + * ``` + * @since v0.0.2 + */ + export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + /** + * Renames the file from `oldPath` to `newPath`. Returns `undefined`. + * + * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. + * @since v0.1.21 + */ + export function renameSync(oldPath: PathLike, newPath: PathLike): void; + /** + * Truncates the file. No arguments other than a possible exception are + * given to the completion callback. A file descriptor can also be passed as the + * first argument. In this case, `fs.ftruncate()` is called. + * + * ```js + * import { truncate } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * truncate('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was truncated'); + * }); + * ``` + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * + * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. + * @since v0.8.6 + * @param [len=0] + */ + export function truncate(path: PathLike, len: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function truncate(path: PathLike, callback: NoParamCallback): void; + export namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number): Promise; + } + /** + * Truncates the file. Returns `undefined`. A file descriptor can also be + * passed as the first argument. In this case, `fs.ftruncateSync()` is called. + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * @since v0.8.6 + * @param [len=0] + */ + export function truncateSync(path: PathLike, len?: number): void; + /** + * Truncates the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. + * + * If the file referred to by the file descriptor was larger than `len` bytes, only + * the first `len` bytes will be retained in the file. + * + * For example, the following program retains only the first four bytes of the + * file: + * + * ```js + * import { open, close, ftruncate } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('temp.txt', 'r+', (err, fd) => { + * if (err) throw err; + * + * try { + * ftruncate(fd, 4, (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * if (err) throw err; + * } + * }); + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncate(fd: number, len: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + export function ftruncate(fd: number, callback: NoParamCallback): void; + export namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number): Promise; + } + /** + * Truncates the file descriptor. Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link ftruncate}. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncateSync(fd: number, len?: number): void; + /** + * Asynchronously changes owner and group of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Synchronously changes owner and group of a file. Returns `undefined`. + * This is the synchronous version of {@link chown}. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chownSync(path: PathLike, uid: number, gid: number): void; + /** + * Sets the owner of the file. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + export namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + /** + * Sets the owner of the file. Returns `undefined`. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function fchownSync(fd: number, uid: number, gid: number): void; + /** + * Set the owner of the symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. + */ + export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Set the owner for the path. Returns `undefined`. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function lchownSync(path: PathLike, uid: number, gid: number): void; + /** + * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic + * link, then the link is not dereferenced: instead, the timestamps of the + * symbolic link itself are changed. + * + * No arguments other than a possible exception are given to the completion + * callback. + * @since v14.5.0, v12.19.0 + */ + export function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace lutimes { + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, + * with the difference that if the path refers to a symbolic link, then the link is not + * dereferenced: instead, the timestamps of the symbolic link itself are changed. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Change the file system timestamps of the symbolic link referenced by `path`. + * Returns `undefined`, or throws an exception when parameters are incorrect or + * the operation fails. This is the synchronous version of {@link lutimes}. + * @since v14.5.0, v12.19.0 + */ + export function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Asynchronously changes the permissions of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * + * ```js + * import { chmod } from 'node:fs'; + * + * chmod('my_file.txt', 0o775, (err) => { + * if (err) throw err; + * console.log('The permissions for file "my_file.txt" have been changed!'); + * }); + * ``` + * @since v0.1.30 + */ + export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + export namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link chmod}. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * @since v0.6.7 + */ + export function chmodSync(path: PathLike, mode: Mode): void; + /** + * Sets the permissions on the file. No arguments other than a possible exception + * are given to the completion callback. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; + export namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: Mode): Promise; + } + /** + * Sets the permissions on the file. Returns `undefined`. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmodSync(fd: number, mode: Mode): void; + /** + * Changes the permissions on a symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + /** @deprecated */ + export namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * Changes the permissions on a symbolic link. Returns `undefined`. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmodSync(path: PathLike, mode: Mode): void; + /** + * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * + * {@link stat} follows symbolic links. Use {@link lstat} to look at the + * links themselves. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. + * Instead, user code should open/read/write the file directly and handle the + * error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, {@link access} is recommended. + * + * For example, given the following directory structure: + * + * ```text + * - txtDir + * -- file.txt + * - app.js + * ``` + * + * The next program will check for the stats of the given paths: + * + * ```js + * import { stat } from 'node:fs'; + * + * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; + * + * for (let i = 0; i < pathsToCheck.length; i++) { + * stat(pathsToCheck[i], (err, stats) => { + * console.log(stats.isDirectory()); + * console.log(stats); + * }); + * } + * ``` + * + * The resulting output will resemble: + * + * ```console + * true + * Stats { + * dev: 16777220, + * mode: 16877, + * nlink: 3, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214262, + * size: 96, + * blocks: 0, + * atimeMs: 1561174653071.963, + * mtimeMs: 1561174614583.3518, + * ctimeMs: 1561174626623.5366, + * birthtimeMs: 1561174126937.2893, + * atime: 2019-06-22T03:37:33.072Z, + * mtime: 2019-06-22T03:36:54.583Z, + * ctime: 2019-06-22T03:37:06.624Z, + * birthtime: 2019-06-22T03:28:46.937Z + * } + * false + * Stats { + * dev: 16777220, + * mode: 33188, + * nlink: 1, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214074, + * size: 8, + * blocks: 8, + * atimeMs: 1561174616618.8555, + * mtimeMs: 1561174614584, + * ctimeMs: 1561174614583.8145, + * birthtimeMs: 1561174007710.7478, + * atime: 2019-06-22T03:36:56.619Z, + * mtime: 2019-06-22T03:36:54.584Z, + * ctime: 2019-06-22T03:36:54.584Z, + * birthtime: 2019-06-22T03:26:47.711Z + * } + * ``` + * @since v0.0.2 + */ + export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function stat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + export interface StatSyncFn extends Function { + (path: PathLike, options?: undefined): Stats; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + }, + ): Stats | undefined; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry: false; + }, + ): BigIntStats | undefined; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + }, + ): Stats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + }, + ): BigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: boolean; + throwIfNoEntry?: false | undefined; + }, + ): Stats | BigIntStats; + (path: PathLike, options?: StatSyncOptions): Stats | BigIntStats | undefined; + } + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const statSync: StatSyncFn; + /** + * Invokes the callback with the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function fstat( + fd: number, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function fstat( + fd: number, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function fstat( + fd: number, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(fd: number, options?: StatOptions): Promise; + } + /** + * Retrieves the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstatSync( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Stats; + export function fstatSync( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): BigIntStats; + export function fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats; + /** + * Retrieves the `fs.Stats` for the symbolic link referred to by the path. + * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic + * link, then the link itself is stat-ed, not the file that it refers to. + * + * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. + * @since v0.1.30 + */ + export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function lstat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function lstat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function lstat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + /** + * Asynchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. The callback gets two arguments `(err, stats)` where `stats`is an `fs.StatFs` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfs(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void): void; + export function statfs( + path: PathLike, + options: + | (StatFsOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void, + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStatsFs) => void, + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs | BigIntStatsFs) => void, + ): void; + export namespace statfs { + /** + * Asynchronous statfs(2) - Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. + * @param path A path to an existing file or directory on the file system to be queried. + */ + function __promisify__( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatFsOptions): Promise; + } + /** + * Synchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfsSync( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): StatsFs; + export function statfsSync( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): BigIntStatsFs; + export function statfsSync(path: PathLike, options?: StatFsOptions): StatsFs | BigIntStatsFs; + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const lstatSync: StatSyncFn; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than + * a possible + * exception are given to the completion callback. + * @since v0.1.31 + */ + export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.31 + */ + export function linkSync(existingPath: PathLike, newPath: PathLike): void; + /** + * Creates the link called `path` pointing to `target`. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. + * + * The `type` argument is only available on Windows and ignored on other platforms. + * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is + * not a string, Node.js will autodetect `target` type and use `'file'` or `'dir'`. + * If the `target` does not exist, `'file'` will be used. Windows junction points + * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. Junction + * points on NTFS volumes can only point to directories. + * + * Relative targets are relative to the link's parent directory. + * + * ```js + * import { symlink } from 'node:fs'; + * + * symlink('./mew', './mewtwo', callback); + * ``` + * + * The above example creates a symbolic link `mewtwo` which points to `mew` in the + * same directory: + * + * ```bash + * $ tree . + * . + * ├── mew + * └── mewtwo -> ./mew + * ``` + * @since v0.1.31 + * @param [type='null'] + */ + export function symlink( + target: PathLike, + path: PathLike, + type: symlink.Type | undefined | null, + callback: NoParamCallback, + ): void; + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + export namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + type Type = "dir" | "file" | "junction"; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link symlink}. + * @since v0.1.31 + * @param [type='null'] + */ + export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + /** + * Reads the contents of the symbolic link referred to by `path`. The callback gets + * two arguments `(err, linkString)`. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path passed to the callback. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: NonSharedBuffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readlink( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + export namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + } + /** + * Returns the symbolic link's string value. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options: BufferEncodingOption): NonSharedBuffer; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string | NonSharedBuffer; + /** + * Asynchronously computes the canonical pathname by resolving `.`, `..`, and + * symbolic links. + * + * A canonical pathname is not necessarily unique. Hard links and bind mounts can + * expose a file system entity through many pathnames. + * + * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: + * + * 1. No case conversion is performed on case-insensitive file systems. + * 2. The maximum number of symbolic links is platform-independent and generally + * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. + * + * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd` to resolve relative paths. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * If `path` resolves to a socket or a pipe, the function will return a system + * dependent name for that object. + * @since v0.1.31 + */ + export function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: NonSharedBuffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function realpath( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + export namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). + * + * The `callback` gets two arguments `(err, resolvedPath)`. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v9.2.0 + */ + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + function native( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: NonSharedBuffer) => void, + ): void; + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | NonSharedBuffer) => void, + ): void; + function native( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + } + /** + * Returns the resolved pathname. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link realpath}. + * @since v0.1.31 + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options: BufferEncodingOption): NonSharedBuffer; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string | NonSharedBuffer; + export namespace realpathSync { + function native(path: PathLike, options?: EncodingOption): string; + function native(path: PathLike, options: BufferEncodingOption): NonSharedBuffer; + function native(path: PathLike, options?: EncodingOption): string | NonSharedBuffer; + } + /** + * Asynchronously removes a file or symbolic link. No arguments other than a + * possible exception are given to the completion callback. + * + * ```js + * import { unlink } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * unlink('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was deleted'); + * }); + * ``` + * + * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a + * directory, use {@link rmdir}. + * + * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. + * @since v0.0.2 + */ + export function unlink(path: PathLike, callback: NoParamCallback): void; + export namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. + * @since v0.1.21 + */ + export function unlinkSync(path: PathLike): void; + export interface RmDirOptions { + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning + * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file. + * Use `fs.rm(path, { recursive: true, force: true })` instead. + * + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given + * to the completion callback. + * + * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on + * Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. + * @since v0.0.2 + */ + export function rmdir(path: PathLike, callback: NoParamCallback): void; + export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void; + export namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: RmDirOptions): Promise; + } + /** + * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. + * + * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error + * on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. + * @since v0.1.21 + */ + export function rmdirSync(path: PathLike, options?: RmDirOptions): void; + export interface RmOptions { + /** + * When `true`, exceptions will be ignored if `path` does not exist. + * @default false + */ + force?: boolean | undefined; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). No arguments other than a possible exception are given to the + * completion callback. + * @since v14.14.0 + */ + export function rm(path: PathLike, callback: NoParamCallback): void; + export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; + export namespace rm { + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + function __promisify__(path: PathLike, options?: RmOptions): Promise; + } + /** + * Synchronously removes files and directories (modeled on the standard POSIX `rm` utility). Returns `undefined`. + * @since v14.14.0 + */ + export function rmSync(path: PathLike, options?: RmOptions): void; + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean | undefined; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode | undefined; + } + /** + * Asynchronously creates a directory. + * + * The callback is given a possible exception and, if `recursive` is `true`, the + * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was + * created (for instance, if it was previously created). + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fs.mkdir()` when `path` is a directory that + * exists results in an error only + * when `recursive` is false. If `recursive` is false and the directory exists, + * an `EEXIST` error occurs. + * + * ```js + * import { mkdir } from 'node:fs'; + * + * // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist. + * mkdir('./tmp/a/apple', { recursive: true }, (err) => { + * if (err) throw err; + * }); + * ``` + * + * On Windows, using `fs.mkdir()` on the root directory even with recursion will + * result in an error: + * + * ```js + * import { mkdir } from 'node:fs'; + * + * mkdir('/', { recursive: true }, (err) => { + * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] + * }); + * ``` + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.8 + */ + export function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + | undefined, + callback: NoParamCallback, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: Mode | MakeDirectoryOptions | null | undefined, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function mkdir(path: PathLike, callback: NoParamCallback): void; + export namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: Mode | MakeDirectoryOptions | null, + ): Promise; + } + /** + * Synchronously creates a directory. Returns `undefined`, or if `recursive` is `true`, the first directory path created. + * This is the synchronous version of {@link mkdir}. + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.21 + */ + export function mkdirSync( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): string | undefined; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): void; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. Due to platform + * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, + * notably the BSDs, can return more than six random characters, and replace + * trailing `X` characters in `prefix` with random characters. + * + * The created directory path is passed as a string to the callback's second + * parameter. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 + * }); + * ``` + * + * The `fs.mkdtemp()` method will append the six randomly selected characters + * directly to the `prefix` string. For instance, given a directory `/tmp`, if the + * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator + * (`import { sep } from 'node:path'`). + * + * ```js + * import { tmpdir } from 'node:os'; + * import { mkdtemp } from 'node:fs'; + * + * // The parent directory for the new temporary directory + * const tmpDir = tmpdir(); + * + * // This method is *INCORRECT*: + * mkdtemp(tmpDir, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmpabc123`. + * // A new temporary directory is created at the file system root + * // rather than *within* the /tmp directory. + * }); + * + * // This method is *CORRECT*: + * import { sep } from 'node:path'; + * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmp/abc123`. + * // A new temporary directory is created within + * // the /tmp directory. + * }); + * ``` + * @since v5.10.0 + */ + export function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: NonSharedBuffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + export function mkdtemp( + prefix: string, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + export namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + } + /** + * Returns the created directory path. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link mkdtemp}. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v5.10.0 + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options: BufferEncodingOption): NonSharedBuffer; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string | NonSharedBuffer; + /** + * Reads the contents of a directory. The callback gets two arguments `(err, files)` where `files` is an array of the names of the files in the directory excluding `'.'` and `'..'`. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames passed to the callback. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects. + * @since v0.1.8 + */ + export function readdir( + path: PathLike, + options: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + callback: (err: NodeJS.ErrnoException | null, files: NonSharedBuffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | NonSharedBuffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readdir( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + export function readdir( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, + ): void; + export namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options: + | "buffer" + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + function __promisify__( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise[]>; + } + /** + * Reads the contents of the directory. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames returned. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects. + * @since v0.1.21 + */ + export function readdirSync( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): string[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): NonSharedBuffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): string[] | NonSharedBuffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdirSync( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + export function readdirSync( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + /** + * Closes the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.0.2 + */ + export function close(fd: number, callback?: NoParamCallback): void; + export namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Closes the file descriptor. Returns `undefined`. + * + * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.1.21 + */ + export function closeSync(fd: number): void; + /** + * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was + * created. On Windows, only the write permission can be manipulated; see {@link chmod}. + * + * The callback gets two arguments `(err, fd)`. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * + * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. + * @since v0.0.2 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] + */ + export function open( + path: PathLike, + flags: OpenMode | undefined, + mode: Mode | undefined | null, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param [flags='r'] See `support of file system `flags``. + */ + export function open( + path: PathLike, + flags: OpenMode | undefined, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + export namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; + } + /** + * Returns an integer representing the file descriptor. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link open}. + * @since v0.1.21 + * @param [flags='r'] + * @param [mode=0o666] + */ + export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time in seconds, `Date`s, or a numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. + * @since v0.4.2 + */ + export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link utimes}. + * @since v0.4.2 + */ + export function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Change the file system timestamps of the object referenced by the supplied file + * descriptor. See {@link utimes}. + * @since v0.4.2 + */ + export function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Synchronous version of {@link futimes}. Returns `undefined`. + * @since v0.4.2 + */ + export function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other + * than a possible exception are given to the completion callback. + * @since v0.1.96 + */ + export function fsync(fd: number, callback: NoParamCallback): void; + export namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.96 + */ + export function fsyncSync(fd: number): void; + export interface WriteOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `buffer.byteLength - offset` + */ + length?: number | undefined; + /** + * @default null + */ + position?: number | null | undefined; + } + /** + * Write `buffer` to the file specified by `fd`. + * + * `offset` determines the part of the buffer to be written, and `length` is + * an integer specifying the number of bytes to write. + * + * `position` refers to the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + * + * The callback will be given three arguments `(err, bytesWritten, buffer)` where `bytesWritten` specifies how many _bytes_ were written from `buffer`. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesWritten` and `buffer` properties. + * + * It is unsafe to use `fs.write()` multiple times on the same file without waiting + * for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v0.0.2 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + export function write( + fd: number, + buffer: TBuffer, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param options An object with the following properties: + * * `offset` The part of the buffer to be written. If not supplied, defaults to `0`. + * * `length` The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * * `position` The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write( + fd: number, + buffer: TBuffer, + options: WriteOptions, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + encoding: BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + */ + export function write( + fd: number, + string: string, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + export namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param options An object with the following properties: + * * `offset` The part of the buffer to be written. If not supplied, defaults to `0`. + * * `length` The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * * `position` The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + options?: WriteOptions, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link write}. + * @since v0.1.21 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + * @return The number of bytes written. + */ + export function writeSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset?: number | null, + length?: number | null, + position?: number | null, + ): number; + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function writeSync( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): number; + export type ReadPosition = number | bigint; + export interface ReadOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `length of buffer` + */ + length?: number | undefined; + /** + * @default null + */ + position?: ReadPosition | null | undefined; + } + export interface ReadOptionsWithBuffer extends ReadOptions { + buffer?: T | undefined; + } + /** @deprecated Use `ReadOptions` instead. */ + // TODO: remove in future major + export interface ReadSyncOptions extends ReadOptions {} + /** @deprecated Use `ReadOptionsWithBuffer` instead. */ + // TODO: remove in future major + export interface ReadAsyncOptions extends ReadOptionsWithBuffer {} + /** + * Read data from the file specified by `fd`. + * + * The callback is given the three arguments, `(err, bytesRead, buffer)`. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffer` properties. + * @since v0.0.2 + * @param buffer The buffer that the data will be written to. + * @param offset The position in `buffer` to write the data to. + * @param length The number of bytes to read. + * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If + * `position` is an integer, the file position will be unchanged. + */ + export function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + /** + * Similar to the above `fs.read` function, this version takes an optional `options` object. + * If not otherwise specified in an `options` object, + * `buffer` defaults to `Buffer.alloc(16384)`, + * `offset` defaults to `0`, + * `length` defaults to `buffer.byteLength`, `- offset` as of Node 17.6.0 + * `position` defaults to `null` + * @since v12.17.0, 13.11.0 + */ + export function read( + fd: number, + options: ReadOptionsWithBuffer, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + buffer: TBuffer, + options: ReadOptions, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + buffer: TBuffer, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NonSharedBuffer) => void, + ): void; + export namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__( + fd: number, + options: ReadOptionsWithBuffer, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__(fd: number): Promise<{ + bytesRead: number; + buffer: NonSharedBuffer; + }>; + } + /** + * Returns the number of `bytesRead`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link read}. + * @since v0.1.21 + * @param [position='null'] + */ + export function readSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset: number, + length: number, + position: ReadPosition | null, + ): number; + /** + * Similar to the above `fs.readSync` function, this version takes an optional `options` object. + * If no `options` object is specified, it will default with the above values. + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadOptions): number; + /** + * Asynchronously reads the entire contents of a file. + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', (err, data) => { + * if (err) throw err; + * console.log(data); + * }); + * ``` + * + * The callback is passed two arguments `(err, data)`, where `data` is the + * contents of the file. + * + * If no encoding is specified, then the raw buffer is returned. + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', 'utf8', callback); + * ``` + * + * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an + * error will be returned. On FreeBSD, a representation of the directory's contents + * will be returned. + * + * ```js + * import { readFile } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFile('', (err, data) => { + * // => [Error: EISDIR: illegal operation on a directory, read ] + * }); + * + * // FreeBSD + * readFile('', (err, data) => { + * // => null, + * }); + * ``` + * + * It is possible to abort an ongoing request using an `AbortSignal`. If a + * request is aborted the callback is called with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs'; + * + * const controller = new AbortController(); + * const signal = controller.signal; + * readFile(fileInfo[0].name, { signal }, (err, buf) => { + * // ... + * }); + * // When you want to abort the request + * controller.abort(); + * ``` + * + * The `fs.readFile()` function buffers the entire file. To minimize memory costs, + * when possible prefer streaming via `fs.createReadStream()`. + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * @since v0.1.29 + * @param path filename or file descriptor + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: string | undefined; + } & Abortable) + | BufferEncoding, + callback: (err: NodeJS.ErrnoException | null, data: string) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | (ObjectEncodingOptions & { + flag?: string | undefined; + } & Abortable) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + export function readFile( + path: PathOrFileDescriptor, + callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void, + ): void; + export namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): Promise; + } + /** + * Returns the contents of the `path`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readFile}. + * + * If the `encoding` option is specified then this function returns a + * string. Otherwise it returns a buffer. + * + * Similar to {@link readFile}, when the path is a directory, the behavior of `fs.readFileSync()` is platform-specific. + * + * ```js + * import { readFileSync } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFileSync(''); + * // => [Error: EISDIR: illegal operation on a directory, read ] + * + * // FreeBSD + * readFileSync(''); // => + * ``` + * @since v0.1.8 + * @param path filename or file descriptor + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): NonSharedBuffer; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): string; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): string | NonSharedBuffer; + export type WriteFileOptions = + | ( + & ObjectEncodingOptions + & Abortable + & { + mode?: Mode | undefined; + flag?: string | undefined; + flush?: boolean | undefined; + } + ) + | BufferEncoding + | null; + /** + * When `file` is a filename, asynchronously writes data to the file, replacing the + * file if it already exists. `data` can be a string or a buffer. + * + * When `file` is a file descriptor, the behavior is similar to calling `fs.write()` directly (which is recommended). See the notes below on using + * a file descriptor. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, (err) => { + * if (err) throw err; + * console.log('The file has been saved!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { writeFile } from 'node:fs'; + * + * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); + * ``` + * + * It is unsafe to use `fs.writeFile()` multiple times on the same file without + * waiting for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that + * performs multiple `write` calls internally to write the buffer passed to it. + * For performance sensitive code consider using {@link createWriteStream}. + * + * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, { signal }, (err) => { + * // When a request is aborted - the callback is called with an AbortError + * }); + * // When the request should be aborted + * controller.abort(); + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFile( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function writeFile( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + callback: NoParamCallback, + ): void; + export namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): Promise; + } + /** + * Returns `undefined`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writeFile}. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFileSync( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', (err) => { + * if (err) throw err; + * console.log('The "data to append" was appended to file!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', 'utf8', callback); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { open, close, appendFile } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('message.txt', 'a', (err, fd) => { + * if (err) throw err; + * + * try { + * appendFile(fd, 'data to append', 'utf8', (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * throw err; + * } + * }); + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFile( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void; + export namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__( + file: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): Promise; + } + /** + * Synchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * try { + * appendFileSync('message.txt', 'data to append'); + * console.log('The "data to append" was appended to file!'); + * } catch (err) { + * // Handle the error + * } + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * appendFileSync('message.txt', 'data to append', 'utf8'); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { openSync, closeSync, appendFileSync } from 'node:fs'; + * + * let fd; + * + * try { + * fd = openSync('message.txt', 'a'); + * appendFileSync(fd, 'data to append', 'utf8'); + * } catch (err) { + * // Handle the error + * } finally { + * if (fd !== undefined) + * closeSync(fd); + * } + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFileSync( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): void; + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'node:fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export interface WatchFileOptions { + bigint?: boolean | undefined; + persistent?: boolean | undefined; + interval?: number | undefined; + } + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'node:fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint?: false | undefined; + }) + | undefined, + listener: StatsListener, + ): StatWatcher; + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint: true; + }) + | undefined, + listener: BigIntStatsListener, + ): StatWatcher; + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watchFile(filename: PathLike, listener: StatsListener): StatWatcher; + /** + * Stop watching for changes on `filename`. If `listener` is specified, only that + * particular listener is removed. Otherwise, _all_ listeners are removed, + * effectively stopping watching of `filename`. + * + * Calling `fs.unwatchFile()` with a filename that is not being watched is a + * no-op, not an error. + * + * Using {@link watch} is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` when possible. + * @since v0.1.31 + * @param listener Optional, a listener previously attached using `fs.watchFile()` + */ + export function unwatchFile(filename: PathLike, listener?: StatsListener): void; + export function unwatchFile(filename: PathLike, listener?: BigIntStatsListener): void; + export interface WatchOptions extends Abortable { + encoding?: BufferEncoding | "buffer" | undefined; + persistent?: boolean | undefined; + recursive?: boolean | undefined; + } + export interface WatchOptionsWithBufferEncoding extends WatchOptions { + encoding: "buffer"; + } + export interface WatchOptionsWithStringEncoding extends WatchOptions { + encoding?: BufferEncoding | undefined; + } + export type WatchEventType = "rename" | "change"; + export type WatchListener = (event: WatchEventType, filename: T | null) => void; + export type StatsListener = (curr: Stats, prev: Stats) => void; + export type BigIntStatsListener = (curr: BigIntStats, prev: BigIntStats) => void; + /** + * Watch for changes on `filename`, where `filename` is either a file or a + * directory. + * + * The second argument is optional. If `options` is provided as a string, it + * specifies the `encoding`. Otherwise `options` should be passed as an object. + * + * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file + * which triggered the event. + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of `eventType`. + * + * If a `signal` is passed, aborting the corresponding AbortController will close + * the returned `fs.FSWatcher`. + * @since v0.5.10 + * @param listener + */ + export function watch( + filename: PathLike, + options?: WatchOptionsWithStringEncoding | BufferEncoding | null, + listener?: WatchListener, + ): FSWatcher; + export function watch( + filename: PathLike, + options: WatchOptionsWithBufferEncoding | "buffer", + listener: WatchListener, + ): FSWatcher; + export function watch( + filename: PathLike, + options: WatchOptions | BufferEncoding | "buffer" | null, + listener: WatchListener, + ): FSWatcher; + export function watch(filename: PathLike, listener: WatchListener): FSWatcher; + /** + * Test whether or not the given path exists by checking with the file system. + * Then call the `callback` argument with either true or false: + * + * ```js + * import { exists } from 'node:fs'; + * + * exists('/etc/passwd', (e) => { + * console.log(e ? 'it exists' : 'no passwd!'); + * }); + * ``` + * + * **The parameters for this callback are not consistent with other Node.js** + * **callbacks.** Normally, the first parameter to a Node.js callback is an `err` parameter, optionally followed by other parameters. The `fs.exists()` callback + * has only one boolean parameter. This is one reason `fs.access()` is recommended + * instead of `fs.exists()`. + * + * Using `fs.exists()` to check for the existence of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file does not exist. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { exists, open, close } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * console.error('myfile already exists'); + * } else { + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { open, close, exists } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } else { + * console.error('myfile does not exist'); + * } + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for existence and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the existence of a file only if the file won't be + * used directly, for example when its existence is a signal from another + * process. + * @since v0.0.2 + * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead. + */ + export function exists(path: PathLike, callback: (exists: boolean) => void): void; + /** @deprecated */ + export namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Returns `true` if the path exists, `false` otherwise. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link exists}. + * + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback` parameter to `fs.exists()` accepts parameters that are inconsistent with other + * Node.js callbacks. `fs.existsSync()` does not use a callback. + * + * ```js + * import { existsSync } from 'node:fs'; + * + * if (existsSync('/etc/passwd')) + * console.log('The path exists.'); + * ``` + * @since v0.1.21 + */ + export function existsSync(path: PathLike): boolean; + export namespace constants { + // File Access Constants + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + // File Copy Constants + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + // File Open Constants + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + // File Type Constants + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + // File Mode Constants + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * The final argument, `callback`, is a callback function that is invoked with + * a possible error argument. If any of the accessibility checks fail, the error + * argument will be an `Error` object. The following examples check if `package.json` exists, and if it is readable or writable. + * + * ```js + * import { access, constants } from 'node:fs'; + * + * const file = 'package.json'; + * + * // Check if the file exists in the current directory. + * access(file, constants.F_OK, (err) => { + * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); + * }); + * + * // Check if the file is readable. + * access(file, constants.R_OK, (err) => { + * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); + * }); + * + * // Check if the file is writable. + * access(file, constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); + * }); + * + * // Check if the file is readable and writable. + * access(file, constants.R_OK | constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); + * }); + * ``` + * + * Do not use `fs.access()` to check for the accessibility of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file is not accessible. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * + * access('myfile', (err) => { + * if (!err) { + * console.error('myfile already exists'); + * return; + * } + * + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * access('myfile', (err) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for accessibility and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the accessibility of a file only if the file will not be + * used directly, for example when its accessibility is a signal from another + * process. + * + * On Windows, access-control policies (ACLs) on a directory may limit access to + * a file or directory. The `fs.access()` function, however, does not check the + * ACL and therefore may report that a path is accessible even if the ACL restricts + * the user from reading or writing to it. + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function access(path: PathLike, callback: NoParamCallback): void; + export namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + /** + * Synchronously tests a user's permissions for the file or directory specified + * by `path`. The `mode` argument is an optional integer that specifies the + * accessibility checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and + * `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, + * the method will return `undefined`. + * + * ```js + * import { accessSync, constants } from 'node:fs'; + * + * try { + * accessSync('etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can read/write'); + * } catch (err) { + * console.error('no access!'); + * } + * ``` + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function accessSync(path: PathLike, mode?: number): void; + interface StreamOptions { + flags?: string | undefined; + encoding?: BufferEncoding | undefined; + fd?: number | promises.FileHandle | undefined; + mode?: number | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + signal?: AbortSignal | null | undefined; + highWaterMark?: number | undefined; + } + interface FSImplementation { + open?: (...args: any[]) => any; + close?: (...args: any[]) => any; + } + interface CreateReadStreamFSImplementation extends FSImplementation { + read: (...args: any[]) => any; + } + interface CreateWriteStreamFSImplementation extends FSImplementation { + write: (...args: any[]) => any; + writev?: (...args: any[]) => any; + } + interface ReadStreamOptions extends StreamOptions { + fs?: CreateReadStreamFSImplementation | null | undefined; + end?: number | undefined; + } + interface WriteStreamOptions extends StreamOptions { + fs?: CreateWriteStreamFSImplementation | null | undefined; + flush?: boolean | undefined; + } + /** + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is + * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the + * current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use + * the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. + * + * If `fd` points to a character device that only supports blocking reads + * (such as keyboard or sound card), read operations do not finish until data is + * available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option, it is possible to override the corresponding `fs` implementations for `open`, `read`, and `close`. When providing the `fs` option, + * an override for `read` is required. If no `fd` is provided, an override for `open` is also required. If `autoClose` is `true`, an override for `close` is + * also required. + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * // Create a stream from some character device. + * const stream = createReadStream('/dev/input/event0'); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * `mode` sets the file mode (permission and sticky bits), but only if the + * file was created. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * createReadStream('sample.txt', { start: 90, end: 99 }); + * ``` + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` option to be set to `r+` rather than the + * default `w`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option it is possible to override the corresponding `fs` implementations for `open`, `write`, `writev`, and `close`. Overriding `write()` without `writev()` can reduce + * performance as some optimizations (`_writev()`) + * will be disabled. When providing the `fs` option, overrides for at least one of `write` and `writev` are required. If no `fd` option is supplied, an override + * for `open` is also required. If `autoClose` is `true`, an override for `close` is also required. + * + * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the `path` argument and will use the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s + * should be passed to `net.Socket`. + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createWriteStream(path: PathLike, options?: BufferEncoding | WriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other + * than a possible + * exception are given to the completion callback. + * @since v0.1.96 + */ + export function fdatasync(fd: number, callback: NoParamCallback): void; + export namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`. + * @since v0.1.96 + */ + export function fdatasyncSync(fd: number): void; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. No arguments other than a possible exception are given to the + * callback function. Node.js makes no guarantees about the atomicity of the copy + * operation. If an error occurs after the destination file has been opened for + * writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFile, constants } from 'node:fs'; + * + * function callback(err) { + * if (err) throw err; + * console.log('source.txt was copied to destination.txt'); + * } + * + * // destination.txt will be created or overwritten by default. + * copyFile('source.txt', 'destination.txt', callback); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + export function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void; + export namespace copyFile { + function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise; + } + /** + * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. Returns `undefined`. Node.js makes no guarantees about the + * atomicity of the copy operation. If an error occurs after the destination file + * has been opened for writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFileSync, constants } from 'node:fs'; + * + * // destination.txt will be created or overwritten by default. + * copyFileSync('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; + /** + * Write an array of `ArrayBufferView`s to the file specified by `fd` using `writev()`. + * + * `position` is the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. + * + * The callback will be given three arguments: `err`, `bytesWritten`, and `buffers`. `bytesWritten` is how many bytes were written from `buffers`. + * + * If this method is `util.promisify()` ed, it returns a promise for an `Object` with `bytesWritten` and `buffers` properties. + * + * It is unsafe to use `fs.writev()` multiple times on the same file without + * waiting for the callback. For this scenario, use {@link createWriteStream}. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] + */ + export function writev( + fd: number, + buffers: TBuffers, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: TBuffers) => void, + ): void; + export function writev( + fd: number, + buffers: TBuffers, + position: number | null, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: TBuffers) => void, + ): void; + // Providing a default type parameter doesn't provide true BC for userland consumers, but at least suppresses TS2314 + // TODO: remove default in future major version + export interface WriteVResult { + bytesWritten: number; + buffers: T; + } + export namespace writev { + function __promisify__( + fd: number, + buffers: TBuffers, + position?: number, + ): Promise>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writev}. + * @since v12.9.0 + * @param [position='null'] + * @return The number of bytes written. + */ + export function writevSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + /** + * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s + * using `readv()`. + * + * `position` is the offset from the beginning of the file from where data + * should be read. If `typeof position !== 'number'`, the data will be read + * from the current position. + * + * The callback will be given three arguments: `err`, `bytesRead`, and `buffers`. `bytesRead` is how many bytes were read from the file. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffers` properties. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + */ + export function readv( + fd: number, + buffers: TBuffers, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: TBuffers) => void, + ): void; + export function readv( + fd: number, + buffers: TBuffers, + position: number | null, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: TBuffers) => void, + ): void; + // Providing a default type parameter doesn't provide true BC for userland consumers, but at least suppresses TS2314 + // TODO: remove default in future major version + export interface ReadVResult { + bytesRead: number; + buffers: T; + } + export namespace readv { + function __promisify__( + fd: number, + buffers: TBuffers, + position?: number, + ): Promise>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readv}. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + * @return The number of bytes read. + */ + export function readvSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + + export interface OpenAsBlobOptions { + /** + * An optional mime type for the blob. + * + * @default 'undefined' + */ + type?: string | undefined; + } + + /** + * Returns a `Blob` whose data is backed by the given file. + * + * The file must not be modified after the `Blob` is created. Any modifications + * will cause reading the `Blob` data to fail with a `DOMException` error. + * Synchronous stat operations on the file when the `Blob` is created, and before + * each read in order to detect whether the file data has been modified on disk. + * + * ```js + * import { openAsBlob } from 'node:fs'; + * + * const blob = await openAsBlob('the.file.txt'); + * const ab = await blob.arrayBuffer(); + * blob.stream(); + * ``` + * @since v19.8.0 + */ + export function openAsBlob(path: PathLike, options?: OpenAsBlobOptions): Promise; + + export interface OpenDirOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number | undefined; + /** + * @default false + */ + recursive?: boolean | undefined; + } + /** + * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendirSync(path: PathLike, options?: OpenDirOptions): Dir; + /** + * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for + * more details. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendir(path: PathLike, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export function opendir( + path: PathLike, + options: OpenDirOptions, + cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void, + ): void; + export namespace opendir { + function __promisify__(path: PathLike, options?: OpenDirOptions): Promise; + } + export interface BigIntStats extends StatsBase { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; + } + export interface BigIntOptions { + bigint: true; + } + export interface StatOptions { + bigint?: boolean | undefined; + } + export interface StatSyncOptions extends StatOptions { + throwIfNoEntry?: boolean | undefined; + } + interface CopyOptionsBase { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean | undefined; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: boolean | undefined; + /** + * Overwrite existing file or directory. _The copy + * operation will ignore errors if you set this to false and the destination + * exists. Use the `errorOnExist` option to change this behavior. + * @default true + */ + force?: boolean | undefined; + /** + * Modifiers for copy operation. See `mode` flag of {@link copyFileSync()} + */ + mode?: number | undefined; + /** + * When `true` timestamps from `src` will + * be preserved. + * @default false + */ + preserveTimestamps?: boolean | undefined; + /** + * Copy directories recursively. + * @default false + */ + recursive?: boolean | undefined; + /** + * When true, path resolution for symlinks will be skipped + * @default false + */ + verbatimSymlinks?: boolean | undefined; + } + export interface CopyOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?: ((source: string, destination: string) => boolean | Promise) | undefined; + } + export interface CopySyncOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?: ((source: string, destination: string) => boolean) | undefined; + } + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cp( + source: string | URL, + destination: string | URL, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + export function cp( + source: string | URL, + destination: string | URL, + opts: CopyOptions, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + /** + * Synchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void; + + interface _GlobOptions { + /** + * Current working directory. + * @default process.cwd() + */ + cwd?: string | URL | undefined; + /** + * `true` if the glob should return paths as `Dirent`s, `false` otherwise. + * @default false + * @since v22.2.0 + */ + withFileTypes?: boolean | undefined; + /** + * Function to filter out files/directories or a + * list of glob patterns to be excluded. If a function is provided, return + * `true` to exclude the item, `false` to include it. + * @default undefined + */ + exclude?: ((fileName: T) => boolean) | readonly string[] | undefined; + } + export interface GlobOptions extends _GlobOptions {} + export interface GlobOptionsWithFileTypes extends _GlobOptions { + withFileTypes: true; + } + export interface GlobOptionsWithoutFileTypes extends _GlobOptions { + withFileTypes?: false | undefined; + } + + /** + * Retrieves the files matching the specified pattern. + * + * ```js + * import { glob } from 'node:fs'; + * + * glob('*.js', (err, matches) => { + * if (err) throw err; + * console.log(matches); + * }); + * ``` + * @since v22.0.0 + */ + export function glob( + pattern: string | readonly string[], + callback: (err: NodeJS.ErrnoException | null, matches: string[]) => void, + ): void; + export function glob( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + callback: ( + err: NodeJS.ErrnoException | null, + matches: Dirent[], + ) => void, + ): void; + export function glob( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + callback: ( + err: NodeJS.ErrnoException | null, + matches: string[], + ) => void, + ): void; + export function glob( + pattern: string | readonly string[], + options: GlobOptions, + callback: ( + err: NodeJS.ErrnoException | null, + matches: Dirent[] | string[], + ) => void, + ): void; + /** + * ```js + * import { globSync } from 'node:fs'; + * + * console.log(globSync('*.js')); + * ``` + * @since v22.0.0 + * @returns paths of files that match the pattern. + */ + export function globSync(pattern: string | readonly string[]): string[]; + export function globSync( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + ): Dirent[]; + export function globSync( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + ): string[]; + export function globSync( + pattern: string | readonly string[], + options: GlobOptions, + ): Dirent[] | string[]; +} +declare module "node:fs" { + export * from "fs"; +} diff --git a/node_modules/@types/node/fs/promises.d.ts b/node_modules/@types/node/fs/promises.d.ts new file mode 100644 index 0000000..051ddba --- /dev/null +++ b/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,1295 @@ +/** + * The `fs/promises` API provides asynchronous file system methods that return + * promises. + * + * The promise APIs use the underlying Node.js threadpool to perform file + * system operations off the event loop thread. These operations are not + * synchronized or threadsafe. Care must be taken when performing multiple + * concurrent modifications on the same file or data corruption may occur. + * @since v10.0.0 + */ +declare module "fs/promises" { + import { NonSharedBuffer } from "node:buffer"; + import { Abortable } from "node:events"; + import { Stream } from "node:stream"; + import { ReadableStream } from "node:stream/web"; + import { + BigIntStats, + BigIntStatsFs, + BufferEncodingOption, + constants as fsConstants, + CopyOptions, + Dir, + Dirent, + GlobOptions, + GlobOptionsWithFileTypes, + GlobOptionsWithoutFileTypes, + MakeDirectoryOptions, + Mode, + ObjectEncodingOptions, + OpenDirOptions, + OpenMode, + PathLike, + ReadOptions, + ReadOptionsWithBuffer, + ReadPosition, + ReadStream, + ReadVResult, + RmDirOptions, + RmOptions, + StatFsOptions, + StatOptions, + Stats, + StatsFs, + TimeLike, + WatchEventType, + WatchOptions as _WatchOptions, + WriteStream, + WriteVResult, + } from "node:fs"; + import { Interface as ReadlineInterface } from "node:readline"; + interface FileChangeInfo { + eventType: WatchEventType; + filename: T | null; + } + interface FlagAndOpenMode { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } + interface FileReadResult { + bytesRead: number; + buffer: T; + } + /** @deprecated This interface will be removed in a future version. Use `import { ReadOptionsWithBuffer } from "node:fs"` instead. */ + interface FileReadOptions { + /** + * @default `Buffer.alloc(0xffff)` + */ + buffer?: T; + /** + * @default 0 + */ + offset?: number | null; + /** + * @default `buffer.byteLength` + */ + length?: number | null; + position?: ReadPosition | null; + } + interface CreateReadStreamOptions extends Abortable { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + end?: number | undefined; + highWaterMark?: number | undefined; + } + interface CreateWriteStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + highWaterMark?: number | undefined; + flush?: boolean | undefined; + } + interface ReadableWebStreamOptions { + autoClose?: boolean | undefined; + } + // TODO: Add `EventEmitter` close + interface FileHandle { + /** + * The numeric file descriptor managed by the {FileHandle} object. + * @since v10.0.0 + */ + readonly fd: number; + /** + * Alias of `filehandle.writeFile()`. + * + * When operating on file handles, the mode cannot be changed from what it was set + * to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + appendFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html). + * @since v10.0.0 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + * @return Fulfills with `undefined` upon success. + */ + chown(uid: number, gid: number): Promise; + /** + * Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html). + * @since v10.0.0 + * @param mode the file mode bit mask. + * @return Fulfills with `undefined` upon success. + */ + chmod(mode: Mode): Promise; + /** + * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 KiB. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `start` is + * omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from + * the current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If the `FileHandle` points to a character device that only supports blocking + * reads (such as keyboard or sound card), read operations do not finish until data + * is available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('/dev/input/event0'); + * // Create a stream from some character device. + * const stream = fd.createReadStream(); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('sample.txt'); + * fd.createReadStream({ start: 90, end: 99 }); + * ``` + * @since v16.11.0 + */ + createReadStream(options?: CreateReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` `open` option to be set to `r+` rather than + * the default `r`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * @since v16.11.0 + */ + createWriteStream(options?: CreateWriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. + * + * Unlike `filehandle.sync` this method does not flush modified metadata. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + datasync(): Promise; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + sync(): Promise; + /** + * Reads data from the file and stores that in the given buffer. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * @since v10.0.0 + * @param buffer A buffer that will be filled with the file data read. + * @param offset The location in the buffer at which to start filling. + * @param length The number of bytes to read. + * @param position The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an + * integer, the current file position will remain unchanged. + * @return Fulfills upon success with an object with two properties: + */ + read( + buffer: T, + offset?: number | null, + length?: number | null, + position?: ReadPosition | null, + ): Promise>; + read( + buffer: T, + options?: ReadOptions, + ): Promise>; + read( + options?: ReadOptionsWithBuffer, + ): Promise>; + /** + * Returns a byte-oriented `ReadableStream` that may be used to read the file's + * contents. + * + * An error will be thrown if this method is called more than once or is called + * after the `FileHandle` is closed or closing. + * + * ```js + * import { + * open, + * } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const chunk of file.readableWebStream()) + * console.log(chunk); + * + * await file.close(); + * ``` + * + * While the `ReadableStream` will read the file to completion, it will not + * close the `FileHandle` automatically. User code must still call the`fileHandle.close()` method. + * @since v17.0.0 + */ + readableWebStream(options?: ReadableWebStreamOptions): ReadableStream; + /** + * Asynchronously reads the entire contents of a file. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support reading. + * + * If one or more `filehandle.read()` calls are made on a file handle and then a `filehandle.readFile()` call is made, the data will be read from the current + * position till the end of the file. It doesn't always read from the beginning + * of the file. + * @since v10.0.0 + * @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the + * data will be a string. + */ + readFile( + options?: + | ({ encoding?: null | undefined } & Abortable) + | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + */ + readFile( + options: + | ({ encoding: BufferEncoding } & Abortable) + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + */ + readFile( + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Convenience method to create a `readline` interface and stream over the file. + * See `filehandle.createReadStream()` for the options. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const line of file.readLines()) { + * console.log(line); + * } + * ``` + * @since v18.11.0 + */ + readLines(options?: CreateReadStreamOptions): ReadlineInterface; + /** + * @since v10.0.0 + * @return Fulfills with an {fs.Stats} for the file. + */ + stat( + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + stat( + opts: StatOptions & { + bigint: true; + }, + ): Promise; + stat(opts?: StatOptions): Promise; + /** + * Truncates the file. + * + * If the file was larger than `len` bytes, only the first `len` bytes will be + * retained in the file. + * + * The following example retains only the first four bytes of the file: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle = null; + * try { + * filehandle = await open('temp.txt', 'r+'); + * await filehandle.truncate(4); + * } finally { + * await filehandle?.close(); + * } + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + truncate(len?: number): Promise; + /** + * Change the file system timestamps of the object referenced by the `FileHandle` then fulfills the promise with no arguments upon success. + * @since v10.0.0 + */ + utimes(atime: TimeLike, mtime: TimeLike): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * The promise is fulfilled with no arguments upon success. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support writing. + * + * It is unsafe to use `filehandle.writeFile()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). + * + * If one or more `filehandle.write()` calls are made on a file handle and then a`filehandle.writeFile()` call is made, the data will be written from the + * current position till the end of the file. It doesn't always write from the + * beginning of the file. + * @since v10.0.0 + */ + writeFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Write `buffer` to the file. + * + * The promise is fulfilled with an object containing two properties: + * + * It is unsafe to use `filehandle.write()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). For this + * scenario, use `filehandle.createWriteStream()`. + * + * On Linux, positional writes do not work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v10.0.0 + * @param offset The start position from within `buffer` where the data to write begins. + * @param [length=buffer.byteLength - offset] The number of bytes from `buffer` to write. + * @param [position='null'] The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current + * position. See the POSIX pwrite(2) documentation for more detail. + */ + write( + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + buffer: TBuffer, + options?: { offset?: number; length?: number; position?: number }, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + data: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + /** + * Write an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s to the file. + * + * The promise is fulfilled with an object containing a two properties: + * + * It is unsafe to call `writev()` multiple times on the same file without waiting + * for the promise to be fulfilled (or rejected). + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current + * position. + */ + writev( + buffers: TBuffers, + position?: number, + ): Promise>; + /** + * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s + * @since v13.13.0, v12.17.0 + * @param [position='null'] The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. + * @return Fulfills upon success an object containing two properties: + */ + readv( + buffers: TBuffers, + position?: number, + ): Promise>; + /** + * Closes the file handle after waiting for any pending operation on the handle to + * complete. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle; + * try { + * filehandle = await open('thefile.txt', 'r'); + * } finally { + * await filehandle?.close(); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + close(): Promise; + /** + * Calls `filehandle.close()` and returns a promise that fulfills when the + * filehandle is closed. + * @since v20.4.0 + */ + [Symbol.asyncDispose](): Promise; + } + const constants: typeof fsConstants; + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If the accessibility check is successful, the promise is fulfilled with no + * value. If any of the accessibility checks fail, the promise is rejected + * with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and + * written by the current process. + * + * ```js + * import { access, constants } from 'node:fs/promises'; + * + * try { + * await access('/etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can access'); + * } catch { + * console.error('cannot access'); + * } + * ``` + * + * Using `fsPromises.access()` to check for the accessibility of a file before + * calling `fsPromises.open()` is not recommended. Doing so introduces a race + * condition, since other processes may change the file's state between the two + * calls. Instead, user code should open/read/write the file directly and handle + * the error raised if the file is not accessible. + * @since v10.0.0 + * @param [mode=fs.constants.F_OK] + * @return Fulfills with `undefined` upon success. + */ + function access(path: PathLike, mode?: number): Promise; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. + * + * No guarantees are made about the atomicity of the copy operation. If an + * error occurs after the destination file has been opened for writing, an attempt + * will be made to remove the destination. + * + * ```js + * import { copyFile, constants } from 'node:fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * try { + * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * ``` + * @since v10.0.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. + * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`) + * @return Fulfills with `undefined` upon success. + */ + function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise; + /** + * Opens a `FileHandle`. + * + * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * @since v10.0.0 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created. + * @return Fulfills with a {FileHandle} object. + */ + function open(path: PathLike, flags?: string | number, mode?: Mode): Promise; + /** + * Renames `oldPath` to `newPath`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + /** + * Truncates (shortens or extends the length) of the content at `path` to `len` bytes. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + function truncate(path: PathLike, len?: number): Promise; + /** + * Removes the directory identified by `path`. + * + * Using `fsPromises.rmdir()` on a file (not a directory) results in the + * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rmdir(path: PathLike, options?: RmDirOptions): Promise; + /** + * Removes files and directories (modeled on the standard POSIX `rm` utility). + * @since v14.14.0 + * @return Fulfills with `undefined` upon success. + */ + function rm(path: PathLike, options?: RmOptions): Promise; + /** + * Asynchronously creates a directory. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fsPromises.mkdir()` when `path` is a directory + * that exists results in a + * rejection only when `recursive` is false. + * + * ```js + * import { mkdir } from 'node:fs/promises'; + * + * try { + * const projectFolder = new URL('./test/project/', import.meta.url); + * const createDir = await mkdir(projectFolder, { recursive: true }); + * + * console.log(`created ${createDir}`); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * @since v10.0.0 + * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + /** + * Reads the contents of a directory. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned + * will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the returned array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from 'node:fs/promises'; + * + * try { + * const files = await readdir(path); + * for (const file of files) + * console.log(file); + * } catch (err) { + * console.error(err); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a directory. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + function readdir( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise[]>; + /** + * Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is + * fulfilled with the`linkString` upon success. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, the link path + * returned will be passed as a `Buffer` object. + * @since v10.0.0 + * @return Fulfills with the `linkString` upon success. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink( + path: PathLike, + options?: ObjectEncodingOptions | string | null, + ): Promise; + /** + * Creates a symbolic link. + * + * The `type` argument is only used on Windows platforms and can be one of `'dir'`, `'file'`, or `'junction'`. If the `type` argument is not a string, Node.js will + * autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not + * exist, `'file'` will be used. Windows junction points require the destination + * path to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. Junction points on NTFS volumes + * can only point to directories. + * @since v10.0.0 + * @param [type='null'] + * @return Fulfills with `undefined` upon success. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + /** + * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, + * in which case the link itself is stat-ed, not the file that it refers to. + * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail. + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. + */ + function lstat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function lstat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function lstat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given `path`. + */ + function stat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function stat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function stat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v19.6.0, v18.15.0 + * @return Fulfills with the {fs.StatFs} object for the given `path`. + */ + function statfs( + path: PathLike, + opts?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function statfs( + path: PathLike, + opts: StatFsOptions & { + bigint: true; + }, + ): Promise; + function statfs(path: PathLike, opts?: StatFsOptions): Promise; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + /** + * If `path` refers to a symbolic link, then the link is removed without affecting + * the file or directory to which that link refers. If the `path` refers to a file + * path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function unlink(path: PathLike): Promise; + /** + * Changes the permissions of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the permissions on a symbolic link. + * + * This method is only implemented on macOS. + * @deprecated Since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the ownership on a symbolic link. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a + * symbolic link, then the link is not dereferenced: instead, the timestamps of + * the symbolic link itself are changed. + * @since v14.5.0, v12.19.0 + * @return Fulfills with `undefined` upon success. + */ + function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Changes the ownership of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time, `Date`s, or a + * numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Determines the actual location of `path` using the same semantics as the `fs.realpath.native()` function. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path. If the `encoding` is set to `'buffer'`, the path returned will be + * passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v10.0.0 + * @return Fulfills with the resolved path upon success. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath( + path: PathLike, + options?: ObjectEncodingOptions | BufferEncoding | null, + ): Promise; + /** + * Creates a unique temporary directory. A unique directory name is generated by + * appending six random characters to the end of the provided `prefix`. Due to + * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some + * platforms, notably the BSDs, can return more than six random characters, and + * replace trailing `X` characters in `prefix` with random characters. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs/promises'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * try { + * await mkdtemp(join(tmpdir(), 'foo-')); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * The `fsPromises.mkdtemp()` method will append the six randomly selected + * characters directly to the `prefix` string. For instance, given a directory `/tmp`, if the intention is to create a temporary directory _within_ `/tmp`, the `prefix` must end with a trailing + * platform-specific path separator + * (`import { sep } from 'node:path'`). + * @since v10.0.0 + * @return Fulfills with a string containing the file system path of the newly created temporary directory. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp( + prefix: string, + options?: ObjectEncodingOptions | BufferEncoding | null, + ): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * If `options` is a string, then it specifies the encoding. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * Any specified `FileHandle` has to support writing. + * + * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file + * without waiting for the promise to be settled. + * + * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience + * method that performs multiple `write` calls internally to write the buffer + * passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`. + * + * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs/promises'; + * import { Buffer } from 'node:buffer'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * const promise = writeFile('message.txt', data, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v10.0.0 + * @param file filename or `FileHandle` + * @return Fulfills with `undefined` upon success. + */ + function writeFile( + file: PathLike | FileHandle, + data: + | string + | NodeJS.ArrayBufferView + | Iterable + | AsyncIterable + | Stream, + options?: + | (ObjectEncodingOptions & { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + /** + * If all data is successfully written to the file, and `flush` + * is `true`, `filehandle.sync()` is used to flush the data. + * @default false + */ + flush?: boolean | undefined; + } & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * The `path` may be specified as a `FileHandle` that has been opened + * for appending (using `fsPromises.open()`). + * @since v10.0.0 + * @param path filename or {FileHandle} + * @return Fulfills with `undefined` upon success. + */ + function appendFile( + path: PathLike | FileHandle, + data: string | Uint8Array, + options?: (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined }) | BufferEncoding | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * + * If no encoding is specified (using `options.encoding`), the data is returned + * as a `Buffer` object. Otherwise, the data will be a string. + * + * If `options` is a string, then it specifies the encoding. + * + * When the `path` is a directory, the behavior of `fsPromises.readFile()` is + * platform-specific. On macOS, Linux, and Windows, the promise will be rejected + * with an error. On FreeBSD, a representation of the directory's contents will be + * returned. + * + * An example of reading a `package.json` file located in the same directory of the + * running code: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * try { + * const filePath = new URL('./package.json', import.meta.url); + * const contents = await readFile(filePath, { encoding: 'utf8' }); + * console.log(contents); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * + * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a + * request is aborted the promise returned is rejected with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const promise = readFile(fileName, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * + * Any specified `FileHandle` has to support reading. + * @since v10.0.0 + * @param path filename or `FileHandle` + * @return Fulfills with the contents of the file. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ({ + encoding?: null | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options: + | ({ + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ( + & ObjectEncodingOptions + & Abortable + & { + flag?: OpenMode | undefined; + } + ) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * + * Example using async iteration: + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + * @return Fulfills with an {fs.Dir}. + */ + function opendir(path: PathLike, options?: OpenDirOptions): Promise; + interface WatchOptions extends _WatchOptions { + maxQueue?: number | undefined; + overflow?: "ignore" | "throw" | undefined; + } + interface WatchOptionsWithBufferEncoding extends WatchOptions { + encoding: "buffer"; + } + interface WatchOptionsWithStringEncoding extends WatchOptions { + encoding?: BufferEncoding | undefined; + } + /** + * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. + * + * ```js + * import { watch } from 'node:fs/promises'; + * + * const ac = new AbortController(); + * const { signal } = ac; + * setTimeout(() => ac.abort(), 10000); + * + * (async () => { + * try { + * const watcher = watch(__filename, { signal }); + * for await (const event of watcher) + * console.log(event); + * } catch (err) { + * if (err.name === 'AbortError') + * return; + * throw err; + * } + * })(); + * ``` + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. + * @since v15.9.0, v14.18.0 + * @return of objects with the properties: + */ + function watch( + filename: PathLike, + options?: WatchOptionsWithStringEncoding | BufferEncoding, + ): NodeJS.AsyncIterator>; + function watch( + filename: PathLike, + options: WatchOptionsWithBufferEncoding | "buffer", + ): NodeJS.AsyncIterator>; + function watch( + filename: PathLike, + options: WatchOptions | BufferEncoding | "buffer", + ): NodeJS.AsyncIterator>; + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + * @return Fulfills with `undefined` upon success. + */ + function cp(source: string | URL, destination: string | URL, opts?: CopyOptions): Promise; + /** + * ```js + * import { glob } from 'node:fs/promises'; + * + * for await (const entry of glob('*.js')) + * console.log(entry); + * ``` + * @since v22.0.0 + * @returns An AsyncIterator that yields the paths of files + * that match the pattern. + */ + function glob(pattern: string | readonly string[]): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + ): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + ): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptions, + ): NodeJS.AsyncIterator; +} +declare module "node:fs/promises" { + export * from "fs/promises"; +} diff --git a/node_modules/@types/node/globals.d.ts b/node_modules/@types/node/globals.d.ts new file mode 100644 index 0000000..8358597 --- /dev/null +++ b/node_modules/@types/node/globals.d.ts @@ -0,0 +1,172 @@ +declare var global: typeof globalThis; + +declare var process: NodeJS.Process; +declare var console: Console; + +interface ErrorConstructor { + /** + * Creates a `.stack` property on `targetObject`, which when accessed returns + * a string representing the location in the code at which + * `Error.captureStackTrace()` was called. + * + * ```js + * const myObject = {}; + * Error.captureStackTrace(myObject); + * myObject.stack; // Similar to `new Error().stack` + * ``` + * + * The first line of the trace will be prefixed with + * `${myObject.name}: ${myObject.message}`. + * + * The optional `constructorOpt` argument accepts a function. If given, all frames + * above `constructorOpt`, including `constructorOpt`, will be omitted from the + * generated stack trace. + * + * The `constructorOpt` argument is useful for hiding implementation + * details of error generation from the user. For instance: + * + * ```js + * function a() { + * b(); + * } + * + * function b() { + * c(); + * } + * + * function c() { + * // Create an error without stack trace to avoid calculating the stack trace twice. + * const { stackTraceLimit } = Error; + * Error.stackTraceLimit = 0; + * const error = new Error(); + * Error.stackTraceLimit = stackTraceLimit; + * + * // Capture the stack trace above function b + * Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace + * throw error; + * } + * + * a(); + * ``` + */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + /** + * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces + */ + prepareStackTrace(err: Error, stackTraces: NodeJS.CallSite[]): any; + /** + * The `Error.stackTraceLimit` property specifies the number of stack frames + * collected by a stack trace (whether generated by `new Error().stack` or + * `Error.captureStackTrace(obj)`). + * + * The default value is `10` but may be set to any valid JavaScript number. Changes + * will affect any stack trace captured _after_ the value has been changed. + * + * If set to a non-number value, or set to a negative number, stack traces will + * not capture any frames. + */ + stackTraceLimit: number; +} + +/** + * Enable this API with the `--expose-gc` CLI flag. + */ +declare var gc: NodeJS.GCFunction | undefined; + +declare namespace NodeJS { + interface CallSite { + getColumnNumber(): number | null; + getEnclosingColumnNumber(): number | null; + getEnclosingLineNumber(): number | null; + getEvalOrigin(): string | undefined; + getFileName(): string | null; + getFunction(): Function | undefined; + getFunctionName(): string | null; + getLineNumber(): number | null; + getMethodName(): string | null; + getPosition(): number; + getPromiseIndex(): number | null; + getScriptHash(): string; + getScriptNameOrSourceURL(): string | null; + getThis(): unknown; + getTypeName(): string | null; + isAsync(): boolean; + isConstructor(): boolean; + isEval(): boolean; + isNative(): boolean; + isPromiseAll(): boolean; + isToplevel(): boolean; + } + + interface ErrnoException extends Error { + errno?: number | undefined; + code?: string | undefined; + path?: string | undefined; + syscall?: string | undefined; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: BufferEncoding): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean | undefined }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): this; + end(data: string | Uint8Array, cb?: () => void): this; + end(str: string, encoding?: BufferEncoding, cb?: () => void): this; + } + + interface ReadWriteStream extends ReadableStream, WritableStream {} + + interface RefCounted { + ref(): this; + unref(): this; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } + + type PartialOptions = { [K in keyof T]?: T[K] | undefined }; + + interface GCFunction { + (minor?: boolean): void; + (options: NodeJS.GCOptions & { execution: "async" }): Promise; + (options: NodeJS.GCOptions): void; + } + + interface GCOptions { + execution?: "sync" | "async" | undefined; + flavor?: "regular" | "last-resort" | undefined; + type?: "major-snapshot" | "major" | "minor" | undefined; + filename?: string | undefined; + } + + /** An iterable iterator returned by the Node.js API. */ + // Default TReturn/TNext in v22 is `any`, for compatibility with the previously-used IterableIterator. + interface Iterator extends IteratorObject { + [Symbol.iterator](): NodeJS.Iterator; + } + + /** An async iterable iterator returned by the Node.js API. */ + // Default TReturn/TNext in v22 is `any`, for compatibility with the previously-used AsyncIterableIterator. + interface AsyncIterator extends AsyncIteratorObject { + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + } +} diff --git a/node_modules/@types/node/globals.typedarray.d.ts b/node_modules/@types/node/globals.typedarray.d.ts new file mode 100644 index 0000000..8eafc3b --- /dev/null +++ b/node_modules/@types/node/globals.typedarray.d.ts @@ -0,0 +1,38 @@ +export {}; // Make this a module + +declare global { + namespace NodeJS { + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float32Array + | Float64Array; + type ArrayBufferView = + | TypedArray + | DataView; + + // The following aliases are required to allow use of non-shared ArrayBufferViews in @types/node + // while maintaining compatibility with TS <=5.6. + type NonSharedUint8Array = Uint8Array; + type NonSharedUint8ClampedArray = Uint8ClampedArray; + type NonSharedUint16Array = Uint16Array; + type NonSharedUint32Array = Uint32Array; + type NonSharedInt8Array = Int8Array; + type NonSharedInt16Array = Int16Array; + type NonSharedInt32Array = Int32Array; + type NonSharedBigUint64Array = BigUint64Array; + type NonSharedBigInt64Array = BigInt64Array; + type NonSharedFloat32Array = Float32Array; + type NonSharedFloat64Array = Float64Array; + type NonSharedDataView = DataView; + type NonSharedTypedArray = TypedArray; + type NonSharedArrayBufferView = ArrayBufferView; + } +} diff --git a/node_modules/@types/node/http.d.ts b/node_modules/@types/node/http.d.ts new file mode 100644 index 0000000..744a19f --- /dev/null +++ b/node_modules/@types/node/http.d.ts @@ -0,0 +1,2089 @@ +/** + * To use the HTTP server and client one must import the `node:http` module. + * + * The HTTP interfaces in Node.js are designed to support many features + * of the protocol which have been traditionally difficult to use. + * In particular, large, possibly chunk-encoded, messages. The interface is + * careful to never buffer entire requests or responses, so the + * user is able to stream data. + * + * HTTP message headers are represented by an object like this: + * + * ```json + * { "content-length": "123", + * "content-type": "text/plain", + * "connection": "keep-alive", + * "host": "example.com", + * "accept": "*" } + * ``` + * + * Keys are lowercased. Values are not modified. + * + * In order to support the full spectrum of possible HTTP applications, the Node.js + * HTTP API is very low-level. It deals with stream handling and message + * parsing only. It parses a message into headers and body but it does not + * parse the actual headers or the body. + * + * See `message.headers` for details on how duplicate headers are handled. + * + * The raw headers as they were received are retained in the `rawHeaders` property, which is an array of `[key, value, key2, value2, ...]`. For + * example, the previous message header object might have a `rawHeaders` list like the following: + * + * ```js + * [ 'ConTent-Length', '123456', + * 'content-LENGTH', '123', + * 'content-type', 'text/plain', + * 'CONNECTION', 'keep-alive', + * 'Host', 'example.com', + * 'accepT', '*' ] + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/http.js) + */ +declare module "http" { + import { NonSharedBuffer } from "node:buffer"; + import * as stream from "node:stream"; + import { URL } from "node:url"; + import { LookupOptions } from "node:dns"; + import { EventEmitter } from "node:events"; + import { LookupFunction, Server as NetServer, Socket, TcpSocketConnectOpts } from "node:net"; + // incoming headers will never contain number + interface IncomingHttpHeaders extends NodeJS.Dict { + accept?: string | undefined; + "accept-encoding"?: string | undefined; + "accept-language"?: string | undefined; + "accept-patch"?: string | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + "alt-svc"?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + connection?: string | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + location?: string | undefined; + origin?: string | undefined; + pragma?: string | undefined; + "proxy-authenticate"?: string | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "retry-after"?: string | undefined; + "sec-fetch-site"?: string | undefined; + "sec-fetch-mode"?: string | undefined; + "sec-fetch-user"?: string | undefined; + "sec-fetch-dest"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | undefined; + "sec-websocket-version"?: string | undefined; + "set-cookie"?: string[] | undefined; + "strict-transport-security"?: string | undefined; + tk?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + upgrade?: string | undefined; + "user-agent"?: string | undefined; + vary?: string | undefined; + via?: string | undefined; + warning?: string | undefined; + "www-authenticate"?: string | undefined; + } + // outgoing headers allows numbers (as they are converted internally to strings) + type OutgoingHttpHeader = number | string | string[]; + interface OutgoingHttpHeaders extends NodeJS.Dict { + accept?: string | string[] | undefined; + "accept-charset"?: string | string[] | undefined; + "accept-encoding"?: string | string[] | undefined; + "accept-language"?: string | string[] | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + "cdn-cache-control"?: string | undefined; + connection?: string | string[] | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | number | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-security-policy"?: string | undefined; + "content-security-policy-report-only"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | string[] | undefined; + dav?: string | string[] | undefined; + dnt?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-range"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + link?: string | string[] | undefined; + location?: string | undefined; + "max-forwards"?: string | undefined; + origin?: string | undefined; + pragma?: string | string[] | undefined; + "proxy-authenticate"?: string | string[] | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + "public-key-pins-report-only"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "referrer-policy"?: string | undefined; + refresh?: string | undefined; + "retry-after"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | string[] | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | string[] | undefined; + "sec-websocket-version"?: string | undefined; + server?: string | undefined; + "set-cookie"?: string | string[] | undefined; + "strict-transport-security"?: string | undefined; + te?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + "user-agent"?: string | undefined; + upgrade?: string | undefined; + "upgrade-insecure-requests"?: string | undefined; + vary?: string | undefined; + via?: string | string[] | undefined; + warning?: string | undefined; + "www-authenticate"?: string | string[] | undefined; + "x-content-type-options"?: string | undefined; + "x-dns-prefetch-control"?: string | undefined; + "x-frame-options"?: string | undefined; + "x-xss-protection"?: string | undefined; + } + interface ClientRequestArgs extends Pick { + _defaultAgent?: Agent | undefined; + agent?: Agent | boolean | undefined; + auth?: string | null | undefined; + createConnection?: + | (( + options: ClientRequestArgs, + oncreate: (err: Error | null, socket: stream.Duplex) => void, + ) => stream.Duplex | null | undefined) + | undefined; + defaultPort?: number | string | undefined; + family?: number | undefined; + headers?: OutgoingHttpHeaders | readonly string[] | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + insecureHTTPParser?: boolean | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + lookup?: LookupFunction | undefined; + /** + * @default 16384 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + port?: number | string | null | undefined; + protocol?: string | null | undefined; + setDefaultHeaders?: boolean | undefined; + setHost?: boolean | undefined; + signal?: AbortSignal | undefined; + socketPath?: string | undefined; + timeout?: number | undefined; + uniqueHeaders?: Array | undefined; + joinDuplicateHeaders?: boolean | undefined; + } + interface ServerOptions< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > { + /** + * Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. + */ + IncomingMessage?: Request | undefined; + /** + * Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. + */ + ServerResponse?: Response | undefined; + /** + * Sets the timeout value in milliseconds for receiving the entire request from the client. + * @see Server.requestTimeout for more information. + * @default 300000 + * @since v18.0.0 + */ + requestTimeout?: number | undefined; + /** + * It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. + * @default false + * @since v18.14.0 + */ + joinDuplicateHeaders?: boolean | undefined; + /** + * The number of milliseconds of inactivity a server needs to wait for additional incoming data, + * after it has finished writing the last response, before a socket will be destroyed. + * @see Server.keepAliveTimeout for more information. + * @default 5000 + * @since v18.0.0 + */ + keepAliveTimeout?: number | undefined; + /** + * An additional buffer time added to the + * `server.keepAliveTimeout` to extend the internal socket timeout. + * @since 22.19.0 + * @default 1000 + */ + keepAliveTimeoutBuffer?: number | undefined; + /** + * Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests. + * @default 30000 + */ + connectionsCheckingInterval?: number | undefined; + /** + * Sets the timeout value in milliseconds for receiving the complete HTTP headers from the client. + * See {@link Server.headersTimeout} for more information. + * @default 60000 + * @since 18.0.0 + */ + headersTimeout?: number | undefined; + /** + * Optionally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. + * Default: @see stream.getDefaultHighWaterMark(). + * @since v20.1.0 + */ + highWaterMark?: number | undefined; + /** + * Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. + * Using the insecure parser should be avoided. + * See --insecure-http-parser for more information. + * @default false + */ + insecureHTTPParser?: boolean | undefined; + /** + * Optionally overrides the value of `--max-http-header-size` for requests received by + * this server, i.e. the maximum length of request headers in bytes. + * @default 16384 + * @since v13.3.0 + */ + maxHeaderSize?: number | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default true + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it forces the server to respond with a 400 (Bad Request) status code + * to any HTTP/1.1 request message that lacks a Host header (as mandated by the specification). + * @default true + * @since 20.0.0 + */ + requireHostHeader?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * A list of response headers that should be sent only once. + * If the header's value is an array, the items will be joined using `; `. + */ + uniqueHeaders?: Array | undefined; + /** + * If set to `true`, an error is thrown when writing to an HTTP response which does not have a body. + * @default false + * @since v18.17.0, v20.2.0 + */ + rejectNonStandardBodyWrites?: boolean | undefined; + } + type RequestListener< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > = (req: InstanceType, res: InstanceType & { req: InstanceType }) => void; + /** + * @since v0.1.17 + */ + class Server< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > extends NetServer { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + /** + * Sets the timeout value for sockets, and emits a `'timeout'` event on + * the Server object, passing the socket as an argument, if a timeout + * occurs. + * + * If there is a `'timeout'` event listener on the Server object, then it + * will be called with the timed-out socket as an argument. + * + * By default, the Server does not timeout sockets. However, if a callback + * is assigned to the Server's `'timeout'` event, timeouts must be handled + * explicitly. + * @since v0.9.12 + * @param [msecs=0 (no timeout)] + */ + setTimeout(msecs?: number, callback?: (socket: Socket) => void): this; + setTimeout(callback: (socket: Socket) => void): this; + /** + * Limits maximum incoming headers count. If set to 0, no limit will be applied. + * @since v0.7.0 + */ + maxHeadersCount: number | null; + /** + * The maximum number of requests socket can handle + * before closing keep alive connection. + * + * A value of `0` will disable the limit. + * + * When the limit is reached it will set the `Connection` header value to `close`, + * but will not actually close the connection, subsequent requests sent + * after the limit is reached will get `503 Service Unavailable` as a response. + * @since v16.10.0 + */ + maxRequestsPerSocket: number | null; + /** + * The number of milliseconds of inactivity before a socket is presumed + * to have timed out. + * + * A value of `0` will disable the timeout behavior on incoming connections. + * + * The socket timeout logic is set up on connection, so changing this + * value only affects new connections to the server, not any existing connections. + * @since v0.9.12 + */ + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP + * headers. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v11.3.0, v10.14.0 + */ + headersTimeout: number; + /** + * The number of milliseconds of inactivity a server needs to wait for additional + * incoming data, after it has finished writing the last response, before a socket + * will be destroyed. + * + * This timeout value is combined with the + * `server.keepAliveTimeoutBuffer` option to determine the actual socket + * timeout, calculated as: + * socketTimeout = keepAliveTimeout + keepAliveTimeoutBuffer + * If the server receives new data before the keep-alive timeout has fired, it + * will reset the regular inactivity timeout, i.e., `server.timeout`. + * + * A value of `0` will disable the keep-alive timeout behavior on incoming + * connections. + * A value of `0` makes the HTTP server behave similarly to Node.js versions prior + * to 8.0.0, which did not have a keep-alive timeout. + * + * The socket timeout logic is set up on connection, so changing this value only + * affects new connections to the server, not any existing connections. + * @since v8.0.0 + */ + keepAliveTimeout: number; + /** + * An additional buffer time added to the + * `server.keepAliveTimeout` to extend the internal socket timeout. + * + * This buffer helps reduce connection reset (`ECONNRESET`) errors by increasing + * the socket timeout slightly beyond the advertised keep-alive timeout. + * + * This option applies only to new incoming connections. + * @since v22.19.0 + * @default 1000 + */ + keepAliveTimeoutBuffer: number; + /** + * Sets the timeout value in milliseconds for receiving the entire request from + * the client. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v14.11.0 + */ + requestTimeout: number; + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request + * or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: RequestListener): this; + addListener(event: "checkExpectation", listener: RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + addListener(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + addListener(event: "request", listener: RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "clientError", err: Error, socket: stream.Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer): boolean; + emit(event: "dropRequest", req: InstanceType, socket: stream.Duplex): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: RequestListener): this; + on(event: "checkExpectation", listener: RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + on( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + on(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + on(event: "request", listener: RequestListener): this; + on( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: RequestListener): this; + once(event: "checkExpectation", listener: RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + once( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + once(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + once(event: "request", listener: RequestListener): this; + once( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: RequestListener): this; + prependListener(event: "checkExpectation", listener: RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + prependListener( + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependListener(event: "request", listener: RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + prependOnceListener( + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependOnceListener(event: "request", listener: RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + } + /** + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract outgoing message from + * the perspective of the participants of an HTTP transaction. + * @since v0.1.17 + */ + class OutgoingMessage extends stream.Writable { + readonly req: Request; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + /** + * @deprecated Use `writableEnded` instead. + */ + finished: boolean; + /** + * Read-only. `true` if the headers were sent, otherwise `false`. + * @since v0.9.3 + */ + readonly headersSent: boolean; + /** + * Alias of `outgoingMessage.socket`. + * @since v0.3.0 + * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead. + */ + readonly connection: Socket | null; + /** + * Reference to the underlying socket. Usually, users will not want to access + * this property. + * + * After calling `outgoingMessage.end()`, this property will be nulled. + * @since v0.3.0 + */ + readonly socket: Socket | null; + constructor(); + /** + * Once a socket is associated with the message and is connected, `socket.setTimeout()` will be called with `msecs` as the first parameter. + * @since v0.9.12 + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * Sets a single header value. If the header already exists in the to-be-sent + * headers, its value will be replaced. Use an array of strings to send multiple + * headers with the same name. + * @since v0.4.0 + * @param name Header name + * @param value Header value + */ + setHeader(name: string, value: number | string | readonly string[]): this; + /** + * Sets multiple header values for implicit headers. headers must be an instance of + * `Headers` or `Map`, if a header already exists in the to-be-sent headers, its + * value will be replaced. + * + * ```js + * const headers = new Headers({ foo: 'bar' }); + * outgoingMessage.setHeaders(headers); + * ``` + * + * or + * + * ```js + * const headers = new Map([['foo', 'bar']]); + * outgoingMessage.setHeaders(headers); + * ``` + * + * When headers have been set with `outgoingMessage.setHeaders()`, they will be + * merged with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * const headers = new Headers({ 'Content-Type': 'text/html' }); + * res.setHeaders(headers); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * @since v19.6.0, v18.15.0 + * @param name Header name + * @param value Header value + */ + setHeaders(headers: Headers | Map): this; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple + * times. + * + * If there were no previous values for the header, this is equivalent to calling `outgoingMessage.setHeader(name, value)`. + * + * Depending of the value of `options.uniqueHeaders` when the client request or the + * server were created, this will end up in the header being sent multiple times or + * a single time with values joined using `; `. + * @since v18.3.0, v16.17.0 + * @param name Header name + * @param value Header value + */ + appendHeader(name: string, value: string | readonly string[]): this; + /** + * Gets the value of the HTTP header with the given name. If that header is not + * set, the returned value will be `undefined`. + * @since v0.4.0 + * @param name Name of header + */ + getHeader(name: string): number | string | string[] | undefined; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow + * copy is used, array values may be mutated without additional calls to + * various header-related HTTP module methods. The keys of the returned + * object are the header names and the values are the respective header + * values. All header names are lowercase. + * + * The object returned by the `outgoingMessage.getHeaders()` method does + * not prototypically inherit from the JavaScript `Object`. This means that + * typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, + * and others are not defined and will not work. + * + * ```js + * outgoingMessage.setHeader('Foo', 'bar'); + * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = outgoingMessage.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v7.7.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All names are lowercase. + * @since v7.7.0 + */ + getHeaderNames(): string[]; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name is case-insensitive. + * + * ```js + * const hasContentType = outgoingMessage.hasHeader('content-type'); + * ``` + * @since v7.7.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that is queued for implicit sending. + * + * ```js + * outgoingMessage.removeHeader('Content-Encoding'); + * ``` + * @since v0.4.0 + * @param name Header name + */ + removeHeader(name: string): void; + /** + * Adds HTTP trailers (headers but at the end of the message) to the message. + * + * Trailers will **only** be emitted if the message is chunked encoded. If not, + * the trailers will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header field names in its value, e.g. + * + * ```js + * message.writeHead(200, { 'Content-Type': 'text/plain', + * 'Trailer': 'Content-MD5' }); + * message.write(fileData); + * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); + * message.end(); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.3.0 + */ + addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + /** + * Flushes the message headers. + * + * For efficiency reason, Node.js normally buffers the message headers + * until `outgoingMessage.end()` is called or the first chunk of message data + * is written. It then tries to pack the headers and data into a single TCP + * packet. + * + * It is usually desired (it saves a TCP round-trip), but not when the first + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()` bypasses the optimization and kickstarts the message. + * @since v1.6.0 + */ + flushHeaders(): void; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v0.1.17 + */ + class ServerResponse extends OutgoingMessage { + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v0.4.0 + */ + statusCode: number; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status message that will be sent to the client when + * the headers get flushed. If this is left as `undefined` then the standard + * message for the status code will be used. + * + * ```js + * response.statusMessage = 'Not found'; + * ``` + * + * After response header was sent to the client, this property indicates the + * status message which was sent out. + * @since v0.11.8 + */ + statusMessage: string; + /** + * If set to `true`, Node.js will check whether the `Content-Length` header value and the size of the body, in bytes, are equal. + * Mismatching the `Content-Length` header value will result + * in an `Error` being thrown, identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * @since v18.10.0, v16.18.0 + */ + strictContentLength: boolean; + constructor(req: Request); + assignSocket(socket: Socket): void; + detachSocket(socket: Socket): void; + /** + * Sends an HTTP/1.1 100 Continue message to the client, indicating that + * the request body should be sent. See the `'checkContinue'` event on `Server`. + * @since v0.3.0 + */ + writeContinue(callback?: () => void): void; + /** + * Sends an HTTP/1.1 103 Early Hints message to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. The optional `callback` argument will be called when + * the response message has been written. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * 'x-trace-id': 'id for diagnostics', + * }); + * + * const earlyHintsCallback = () => console.log('early hints message sent'); + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }, earlyHintsCallback); + * ``` + * @since v18.11.0 + * @param hints An object containing the values of headers + * @param callback Will be called when the response message has been written + */ + writeEarlyHints(hints: Record, callback?: () => void): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * Optionally one can give a human-readable `statusMessage` as the second + * argument. + * + * `headers` may be an `Array` where the keys and values are in the same list. + * It is _not_ a list of tuples. So, the even-numbered offsets are key values, + * and the odd-numbered offsets are the associated values. The array is in the same + * format as `request.rawHeaders`. + * + * Returns a reference to the `ServerResponse`, so that calls can be chained. + * + * ```js + * const body = 'hello world'; + * response + * .writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain', + * }) + * .end(body); + * ``` + * + * This method must only be called once on a message and it must + * be called before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * If this method is called and `response.setHeader()` has not been called, + * it will directly write the supplied header values onto the network channel + * without caching internally, and the `response.getHeader()` on the header + * will not yield the expected result. If progressive population of headers is + * desired with potential future retrieval and modification, use `response.setHeader()` instead. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * `Content-Length` is read in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * will check whether `Content-Length` and the length of the body which has + * been transmitted are equal or not. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a \[`Error`\]\[\] being thrown. + * @since v0.1.30 + */ + writeHead( + statusCode: number, + statusMessage?: string, + headers?: OutgoingHttpHeaders | OutgoingHttpHeader[], + ): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends a HTTP/1.1 102 Processing message to the client, indicating that + * the request body should be sent. + * @since v10.0.0 + */ + writeProcessing(callback?: () => void): void; + } + interface InformationEvent { + statusCode: number; + statusMessage: string; + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + } + /** + * This object is created internally and returned from {@link request}. It + * represents an _in-progress_ request whose header has already been queued. The + * header is still mutable using the `setHeader(name, value)`, `getHeader(name)`, `removeHeader(name)` API. The actual header will + * be sent along with the first data chunk or when calling `request.end()`. + * + * To get the response, add a listener for `'response'` to the request object. `'response'` will be emitted from the request object when the response + * headers have been received. The `'response'` event is executed with one + * argument which is an instance of {@link IncomingMessage}. + * + * During the `'response'` event, one can add listeners to the + * response object; particularly to listen for the `'data'` event. + * + * If no `'response'` handler is added, then the response will be + * entirely discarded. However, if a `'response'` event handler is added, + * then the data from the response object **must** be consumed, either by + * calling `response.read()` whenever there is a `'readable'` event, or + * by adding a `'data'` handler, or by calling the `.resume()` method. + * Until the data is consumed, the `'end'` event will not fire. Also, until + * the data is read it will consume memory that can eventually lead to a + * 'process out of memory' error. + * + * For backward compatibility, `res` will only emit `'error'` if there is an `'error'` listener registered. + * + * Set `Content-Length` header to limit the response body size. + * If `response.strictContentLength` is set to `true`, mismatching the `Content-Length` header value will result in an `Error` being thrown, + * identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * + * `Content-Length` value should be in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. + * @since v0.1.17 + */ + class ClientRequest extends OutgoingMessage { + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v0.11.14 + * @deprecated Since v17.0.0, v16.12.0 - Check `destroyed` instead. + */ + aborted: boolean; + /** + * The request host. + * @since v14.5.0, v12.19.0 + */ + host: string; + /** + * The request protocol. + * @since v14.5.0, v12.19.0 + */ + protocol: string; + /** + * When sending request through a keep-alive enabled agent, the underlying socket + * might be reused. But if server closes connection at unfortunate time, client + * may run into a 'ECONNRESET' error. + * + * ```js + * import http from 'node:http'; + * + * // Server has a 5 seconds keep-alive timeout by default + * http + * .createServer((req, res) => { + * res.write('hello\n'); + * res.end(); + * }) + * .listen(3000); + * + * setInterval(() => { + * // Adapting a keep-alive agent + * http.get('http://localhost:3000', { agent }, (res) => { + * res.on('data', (data) => { + * // Do nothing + * }); + * }); + * }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout + * ``` + * + * By marking a request whether it reused socket or not, we can do + * automatic error retry base on it. + * + * ```js + * import http from 'node:http'; + * const agent = new http.Agent({ keepAlive: true }); + * + * function retriableRequest() { + * const req = http + * .get('http://localhost:3000', { agent }, (res) => { + * // ... + * }) + * .on('error', (err) => { + * // Check if retry is needed + * if (req.reusedSocket && err.code === 'ECONNRESET') { + * retriableRequest(); + * } + * }); + * } + * + * retriableRequest(); + * ``` + * @since v13.0.0, v12.16.0 + */ + reusedSocket: boolean; + /** + * Limits maximum response headers count. If set to 0, no limit will be applied. + */ + maxHeadersCount: number; + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + /** + * The request method. + * @since v0.1.97 + */ + method: string; + /** + * The request path. + * @since v0.4.0 + */ + path: string; + /** + * Marks the request as aborting. Calling this will cause remaining data + * in the response to be dropped and the socket to be destroyed. + * @since v0.3.8 + * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. + */ + abort(): void; + onSocket(socket: Socket): void; + /** + * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. + * @since v0.5.9 + * @param timeout Milliseconds before a request times out. + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. + * @since v0.5.9 + */ + setNoDelay(noDelay?: boolean): void; + /** + * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. + * @since v0.5.9 + */ + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + /** + * Returns an array containing the unique names of the current outgoing raw + * headers. Header names are returned with their exact casing being set. + * + * ```js + * request.setHeader('Foo', 'bar'); + * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = request.getRawHeaderNames(); + * // headerNames === ['Foo', 'Set-Cookie'] + * ``` + * @since v15.13.0, v14.17.0 + */ + getRawHeaderNames(): string[]; + /** + * @deprecated + */ + addListener(event: "abort", listener: () => void): this; + addListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + addListener(event: "continue", listener: () => void): this; + addListener(event: "information", listener: (info: InformationEvent) => void): this; + addListener(event: "response", listener: (response: IncomingMessage) => void): this; + addListener(event: "socket", listener: (socket: Socket) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + on(event: "abort", listener: () => void): this; + on( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + on(event: "continue", listener: () => void): this; + on(event: "information", listener: (info: InformationEvent) => void): this; + on(event: "response", listener: (response: IncomingMessage) => void): this; + on(event: "socket", listener: (socket: Socket) => void): this; + on(event: "timeout", listener: () => void): this; + on( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + once(event: "abort", listener: () => void): this; + once( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + once(event: "continue", listener: () => void): this; + once(event: "information", listener: (info: InformationEvent) => void): this; + once(event: "response", listener: (response: IncomingMessage) => void): this; + once(event: "socket", listener: (socket: Socket) => void): this; + once(event: "timeout", listener: () => void): this; + once( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependListener(event: "abort", listener: () => void): this; + prependListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + prependListener(event: "continue", listener: () => void): this; + prependListener(event: "information", listener: (info: InformationEvent) => void): this; + prependListener(event: "response", listener: (response: IncomingMessage) => void): this; + prependListener(event: "socket", listener: (socket: Socket) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependOnceListener(event: "abort", listener: () => void): this; + prependOnceListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + prependOnceListener(event: "continue", listener: () => void): this; + prependOnceListener(event: "information", listener: (info: InformationEvent) => void): this; + prependOnceListener(event: "response", listener: (response: IncomingMessage) => void): this; + prependOnceListener(event: "socket", listener: (socket: Socket) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to + * access response + * status, headers, and data. + * + * Different from its `socket` value which is a subclass of `stream.Duplex`, the `IncomingMessage` itself extends `stream.Readable` and is created separately to + * parse and emit the incoming HTTP headers and payload, as the underlying socket + * may be reused multiple times in case of keep-alive. + * @since v0.1.17 + */ + class IncomingMessage extends stream.Readable { + constructor(socket: Socket); + /** + * The `message.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + * @deprecated Since v17.0.0,v16.12.0 - Check `message.destroyed` from stream.Readable. + */ + aborted: boolean; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. + * Probably either `'1.1'` or `'1.0'`. + * + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. + * @since v0.1.1 + */ + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + /** + * The `message.complete` property will be `true` if a complete HTTP message has + * been received and successfully parsed. + * + * This property is particularly useful as a means of determining if a client or + * server fully transmitted a message before a connection was terminated: + * + * ```js + * const req = http.request({ + * host: '127.0.0.1', + * port: 8080, + * method: 'POST', + * }, (res) => { + * res.resume(); + * res.on('end', () => { + * if (!res.complete) + * console.error( + * 'The connection was terminated while the message was still being sent'); + * }); + * }); + * ``` + * @since v0.3.0 + */ + complete: boolean; + /** + * Alias for `message.socket`. + * @since v0.1.90 + * @deprecated Since v16.0.0 - Use `socket`. + */ + connection: Socket; + /** + * The `net.Socket` object associated with the connection. + * + * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the + * client's authentication details. + * + * This property is guaranteed to be an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specified a socket + * type other than `net.Socket` or internally nulled. + * @since v0.3.0 + */ + socket: Socket; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * Duplicates in raw headers are handled in the following ways, depending on the + * header name: + * + * * Duplicates of `age`, `authorization`, `content-length`, `content-type`, `etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`, `last-modified`, `location`, + * `max-forwards`, `proxy-authorization`, `referer`, `retry-after`, `server`, or `user-agent` are discarded. + * To allow duplicate values of the headers listed above to be joined, + * use the option `joinDuplicateHeaders` in {@link request} and {@link createServer}. See RFC 9110 Section 5.3 for more + * information. + * * `set-cookie` is always an array. Duplicates are added to the array. + * * For duplicate `cookie` headers, the values are joined together with `; `. + * * For all other headers, the values are joined together with `, `. + * @since v0.1.5 + */ + headers: IncomingHttpHeaders; + /** + * Similar to `message.headers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': ['curl/7.22.0'], + * // host: ['127.0.0.1:8000'], + * // accept: ['*'] } + * console.log(request.headersDistinct); + * ``` + * @since v18.3.0, v16.17.0 + */ + headersDistinct: NodeJS.Dict; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v0.11.6 + */ + rawHeaders: string[]; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v0.3.0 + */ + trailers: NodeJS.Dict; + /** + * Similar to `message.trailers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * Only populated at the `'end'` event. + * @since v18.3.0, v16.17.0 + */ + trailersDistinct: NodeJS.Dict; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v0.11.6 + */ + rawTrailers: string[]; + /** + * Calls `message.socket.setTimeout(msecs, callback)`. + * @since v0.5.9 + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * **Only valid for request obtained from {@link Server}.** + * + * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. + * @since v0.1.1 + */ + method?: string | undefined; + /** + * **Only valid for request obtained from {@link Server}.** + * + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. Take the following request: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * To parse the URL into its parts: + * + * ```js + * new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and `process.env.HOST` is undefined: + * + * ```console + * $ node + * > new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); + * URL { + * href: 'http://localhost/status?name=ryan', + * origin: 'http://localhost', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost', + * hostname: 'localhost', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * + * Ensure that you set `process.env.HOST` to the server's host name, or consider replacing this part entirely. If using `req.headers.host`, ensure proper + * validation is used, as clients may specify a custom `Host` header. + * @since v0.1.90 + */ + url?: string | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The 3-digit HTTP response status code. E.G. `404`. + * @since v0.1.1 + */ + statusCode?: number | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + * @since v0.11.10 + */ + statusMessage?: string | undefined; + /** + * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error` is provided, an `'error'` event is emitted on the socket and `error` is passed + * as an argument to any listeners on the event. + * @since v0.3.0 + */ + destroy(error?: Error): this; + } + interface AgentOptions extends NodeJS.PartialOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean | undefined; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number | undefined; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number | undefined; + /** + * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. + */ + maxTotalSockets?: number | undefined; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number | undefined; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number | undefined; + /** + * Scheduling strategy to apply when picking the next free socket to use. + * @default `lifo` + */ + scheduling?: "fifo" | "lifo" | undefined; + } + /** + * An `Agent` is responsible for managing connection persistence + * and reuse for HTTP clients. It maintains a queue of pending requests + * for a given host and port, reusing a single socket connection for each + * until the queue is empty, at which time the socket is either destroyed + * or put into a pool where it is kept to be used again for requests to the + * same host and port. Whether it is destroyed or pooled depends on the `keepAlive` `option`. + * + * Pooled connections have TCP Keep-Alive enabled for them, but servers may + * still close idle connections, in which case they will be removed from the + * pool and a new connection will be made when a new HTTP request is made for + * that host and port. Servers may also refuse to allow multiple requests + * over the same connection, in which case the connection will have to be + * remade for every request and cannot be pooled. The `Agent` will still make + * the requests to that server, but each one will occur over a new connection. + * + * When a connection is closed by the client or the server, it is removed + * from the pool. Any unused sockets in the pool will be unrefed so as not + * to keep the Node.js process running when there are no outstanding requests. + * (see `socket.unref()`). + * + * It is good practice, to `destroy()` an `Agent` instance when it is no + * longer in use, because unused sockets consume OS resources. + * + * Sockets are removed from an agent when the socket emits either + * a `'close'` event or an `'agentRemove'` event. When intending to keep one + * HTTP request open for a long time without keeping it in the agent, something + * like the following may be done: + * + * ```js + * http.get(options, (res) => { + * // Do stuff + * }).on('socket', (socket) => { + * socket.emit('agentRemove'); + * }); + * ``` + * + * An agent may also be used for an individual request. By providing `{agent: false}` as an option to the `http.get()` or `http.request()` functions, a one-time use `Agent` with default options + * will be used + * for the client connection. + * + * `agent:false`: + * + * ```js + * http.get({ + * hostname: 'localhost', + * port: 80, + * path: '/', + * agent: false, // Create a new agent just for this one request + * }, (res) => { + * // Do stuff with response + * }); + * ``` + * + * `options` in [`socket.connect()`](https://nodejs.org/docs/latest-v22.x/api/net.html#socketconnectoptions-connectlistener) are also supported. + * + * To configure any of them, a custom {@link Agent} instance must be created. + * + * ```js + * import http from 'node:http'; + * const keepAliveAgent = new http.Agent({ keepAlive: true }); + * options.agent = keepAliveAgent; + * http.request(options, onResponseCallback) + * ``` + * @since v0.3.4 + */ + class Agent extends EventEmitter { + /** + * By default set to 256. For agents with `keepAlive` enabled, this + * sets the maximum number of sockets that will be left open in the free + * state. + * @since v0.11.7 + */ + maxFreeSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open per origin. Origin is the returned value of `agent.getName()`. + * @since v0.3.6 + */ + maxSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open. Unlike `maxSockets`, this parameter applies across all origins. + * @since v14.5.0, v12.19.0 + */ + maxTotalSockets: number; + /** + * An object which contains arrays of sockets currently awaiting use by + * the agent when `keepAlive` is enabled. Do not modify. + * + * Sockets in the `freeSockets` list will be automatically destroyed and + * removed from the array on `'timeout'`. + * @since v0.11.4 + */ + readonly freeSockets: NodeJS.ReadOnlyDict; + /** + * An object which contains arrays of sockets currently in use by the + * agent. Do not modify. + * @since v0.3.6 + */ + readonly sockets: NodeJS.ReadOnlyDict; + /** + * An object which contains queues of requests that have not yet been assigned to + * sockets. Do not modify. + * @since v0.5.9 + */ + readonly requests: NodeJS.ReadOnlyDict; + constructor(opts?: AgentOptions); + /** + * Destroy any sockets that are currently in use by the agent. + * + * It is usually not necessary to do this. However, if using an + * agent with `keepAlive` enabled, then it is best to explicitly shut down + * the agent when it is no longer needed. Otherwise, + * sockets might stay open for quite a long time before the server + * terminates them. + * @since v0.11.4 + */ + destroy(): void; + /** + * Produces a socket/stream to be used for HTTP requests. + * + * By default, this function is the same as `net.createConnection()`. However, + * custom agents may override this method in case greater flexibility is desired. + * + * A socket/stream can be supplied in one of two ways: by returning the + * socket/stream from this function, or by passing the socket/stream to `callback`. + * + * This method is guaranteed to return an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specifies a socket + * type other than `net.Socket`. + * + * `callback` has a signature of `(err, stream)`. + * @since v0.11.4 + * @param options Options containing connection details. Check `createConnection` for the format of the options + * @param callback Callback function that receives the created socket + */ + createConnection( + options: ClientRequestArgs, + callback?: (err: Error | null, stream: stream.Duplex) => void, + ): stream.Duplex | null | undefined; + /** + * Called when `socket` is detached from a request and could be persisted by the`Agent`. Default behavior is to: + * + * ```js + * socket.setKeepAlive(true, this.keepAliveMsecs); + * socket.unref(); + * return true; + * ``` + * + * This method can be overridden by a particular `Agent` subclass. If this + * method returns a falsy value, the socket will be destroyed instead of persisting + * it for use with the next request. + * + * The `socket` argument can be an instance of `net.Socket`, a subclass of `stream.Duplex`. + * @since v8.1.0 + */ + keepSocketAlive(socket: stream.Duplex): void; + /** + * Called when `socket` is attached to `request` after being persisted because of + * the keep-alive options. Default behavior is to: + * + * ```js + * socket.ref(); + * ``` + * + * This method can be overridden by a particular `Agent` subclass. + * + * The `socket` argument can be an instance of `net.Socket`, a subclass of `stream.Duplex`. + * @since v8.1.0 + */ + reuseSocket(socket: stream.Duplex, request: ClientRequest): void; + /** + * Get a unique name for a set of request options, to determine whether a + * connection can be reused. For an HTTP agent, this returns`host:port:localAddress` or `host:port:localAddress:family`. For an HTTPS agent, + * the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options + * that determine socket reusability. + * @since v0.11.4 + * @param options A set of options providing information for name generation + */ + getName(options?: ClientRequestArgs): string; + } + const METHODS: string[]; + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + /** + * Returns a new instance of {@link Server}. + * + * The `requestListener` is a function which is automatically + * added to the `'request'` event. + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer(); + * + * // Listen to the request event + * server.on('request', (request, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.1.13 + */ + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + >(requestListener?: RequestListener): Server; + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + >( + options: ServerOptions, + requestListener?: RequestListener, + ): Server; + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs {} + /** + * `options` in `socket.connect()` are also supported. + * + * Node.js maintains several connections per server to make HTTP requests. + * This function allows one to transparently issue requests. + * + * `url` can be a string or a `URL` object. If `url` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * If both `url` and `options` are specified, the objects are merged, with the `options` properties taking precedence. + * + * The optional `callback` parameter will be added as a one-time listener for + * the `'response'` event. + * + * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * import http from 'node:http'; + * import { Buffer } from 'node:buffer'; + * + * const postData = JSON.stringify({ + * 'msg': 'Hello World!', + * }); + * + * const options = { + * hostname: 'www.google.com', + * port: 80, + * path: '/upload', + * method: 'POST', + * headers: { + * 'Content-Type': 'application/json', + * 'Content-Length': Buffer.byteLength(postData), + * }, + * }; + * + * const req = http.request(options, (res) => { + * console.log(`STATUS: ${res.statusCode}`); + * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); + * res.setEncoding('utf8'); + * res.on('data', (chunk) => { + * console.log(`BODY: ${chunk}`); + * }); + * res.on('end', () => { + * console.log('No more data in response.'); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(`problem with request: ${e.message}`); + * }); + * + * // Write data to request body + * req.write(postData); + * req.end(); + * ``` + * + * In the example `req.end()` was called. With `http.request()` one + * must always call `req.end()` to signify the end of the request - + * even if there is no data being written to the request body. + * + * If any error is encountered during the request (be that with DNS resolution, + * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted + * on the returned request object. As with all `'error'` events, if no listeners + * are registered the error will be thrown. + * + * There are a few special headers that should be noted. + * + * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to + * the server should be persisted until the next request. + * * Sending a 'Content-Length' header will disable the default chunked encoding. + * * Sending an 'Expect' header will immediately send the request headers. + * Usually, when sending 'Expect: 100-continue', both a timeout and a listener + * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more + * information. + * * Sending an Authorization header will override using the `auth` option + * to compute basic authentication. + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('http://abc:xyz@example.com'); + * + * const req = http.request(options, (res) => { + * // ... + * }); + * ``` + * + * In a successful request, the following events will be emitted in the following + * order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * (`'data'` will not be emitted at all if the response body is empty, for + * instance, in most redirects) + * * `'end'` on the `res` object + * * `'close'` + * + * In the case of a connection error, the following events will be emitted: + * + * * `'socket'` + * * `'error'` + * * `'close'` + * + * In the case of a premature connection close before the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` + * * `'close'` + * + * In the case of a premature connection close after the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (connection closed here) + * * `'aborted'` on the `res` object + * * `'close'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'` + * * `'close'` on the `res` object + * + * If `req.destroy()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.destroy()` called here) + * * `'aborted'` on the `res` object + * * `'close'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` on the `res` object + * + * If `req.abort()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.abort()` called here) + * * `'abort'` + * * `'close'` + * + * If `req.abort()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.abort()` called here) + * * `'abort'` + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` + * * `'close'` + * + * If `req.abort()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.abort()` called here) + * * `'abort'` + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * Setting the `timeout` option or using the `setTimeout()` function will + * not abort the request or do anything besides add a `'timeout'` event. + * + * Passing an `AbortSignal` and then calling `abort()` on the corresponding `AbortController` will behave the same way as calling `.destroy()` on the + * request. Specifically, the `'error'` event will be emitted with an error with + * the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'` and the `cause`, if one was provided. + * @since v0.3.6 + */ + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: IncomingMessage) => void, + ): ClientRequest; + /** + * Since most requests are GET requests without bodies, Node.js provides this + * convenience method. The only difference between this method and {@link request} is that it sets the method to GET by default and calls `req.end()` automatically. The callback must take care to + * consume the response + * data for reasons stated in {@link ClientRequest} section. + * + * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. + * + * JSON fetching example: + * + * ```js + * http.get('http://localhost:8000/', (res) => { + * const { statusCode } = res; + * const contentType = res.headers['content-type']; + * + * let error; + * // Any 2xx status code signals a successful response but + * // here we're only checking for 200. + * if (statusCode !== 200) { + * error = new Error('Request Failed.\n' + + * `Status Code: ${statusCode}`); + * } else if (!/^application\/json/.test(contentType)) { + * error = new Error('Invalid content-type.\n' + + * `Expected application/json but received ${contentType}`); + * } + * if (error) { + * console.error(error.message); + * // Consume response data to free up memory + * res.resume(); + * return; + * } + * + * res.setEncoding('utf8'); + * let rawData = ''; + * res.on('data', (chunk) => { rawData += chunk; }); + * res.on('end', () => { + * try { + * const parsedData = JSON.parse(rawData); + * console.log(parsedData); + * } catch (e) { + * console.error(e.message); + * } + * }); + * }).on('error', (e) => { + * console.error(`Got error: ${e.message}`); + * }); + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the method set to GET by default. + */ + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + /** + * Performs the low-level validations on the provided `name` that are done when `res.setHeader(name, value)` is called. + * + * Passing illegal value as `name` will result in a `TypeError` being thrown, + * identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Example: + * + * ```js + * import { validateHeaderName } from 'node:http'; + * + * try { + * validateHeaderName(''); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN' + * console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' + * } + * ``` + * @since v14.3.0 + * @param [label='Header name'] Label for error message. + */ + function validateHeaderName(name: string): void; + /** + * Performs the low-level validations on the provided `value` that are done when `res.setHeader(name, value)` is called. + * + * Passing illegal value as `value` will result in a `TypeError` being thrown. + * + * * Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. + * * Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Examples: + * + * ```js + * import { validateHeaderValue } from 'node:http'; + * + * try { + * validateHeaderValue('x-my-header', undefined); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true + * console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' + * } + * + * try { + * validateHeaderValue('x-my-header', 'oʊmɪɡə'); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_INVALID_CHAR'); // --> true + * console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' + * } + * ``` + * @since v14.3.0 + * @param name Header name + * @param value Header value + */ + function validateHeaderValue(name: string, value: string): void; + /** + * Set the maximum number of idle HTTP parsers. + * @since v18.8.0, v16.18.0 + * @param [max=1000] + */ + function setMaxIdleHTTPParsers(max: number): void; + /** + * Global instance of `Agent` which is used as the default for all HTTP client + * requests. Diverges from a default `Agent` configuration by having `keepAlive` + * enabled and a `timeout` of 5 seconds. + * @since v0.5.9 + */ + let globalAgent: Agent; + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; + /** + * A browser-compatible implementation of `WebSocket`. + * @since v22.5.0 + */ + const WebSocket: typeof import("undici-types").WebSocket; + /** + * @since v22.5.0 + */ + const CloseEvent: typeof import("undici-types").CloseEvent; + /** + * @since v22.5.0 + */ + const MessageEvent: typeof import("undici-types").MessageEvent; +} +declare module "node:http" { + export * from "http"; +} diff --git a/node_modules/@types/node/http2.d.ts b/node_modules/@types/node/http2.d.ts new file mode 100644 index 0000000..0dcc1d9 --- /dev/null +++ b/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2644 @@ +/** + * The `node:http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. + * It can be accessed using: + * + * ```js + * import http2 from 'node:http2'; + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/http2.js) + */ +declare module "http2" { + import { NonSharedBuffer } from "node:buffer"; + import EventEmitter = require("node:events"); + import * as fs from "node:fs"; + import * as net from "node:net"; + import * as stream from "node:stream"; + import * as tls from "node:tls"; + import * as url from "node:url"; + import { + IncomingHttpHeaders as Http1IncomingHttpHeaders, + IncomingMessage, + OutgoingHttpHeaders, + ServerResponse, + } from "node:http"; + export { OutgoingHttpHeaders } from "node:http"; + export interface IncomingHttpStatusHeader { + ":status"?: number | undefined; + } + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ":path"?: string | undefined; + ":method"?: string | undefined; + ":authority"?: string | undefined; + ":scheme"?: string | undefined; + } + // Http2Stream + export interface StreamPriorityOptions { + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + silent?: boolean | undefined; + } + export interface StreamState { + localWindowSize?: number | undefined; + state?: number | undefined; + localClose?: number | undefined; + remoteClose?: number | undefined; + sumDependencyWeight?: number | undefined; + weight?: number | undefined; + } + export interface ServerStreamResponseOptions { + endStream?: boolean | undefined; + waitForTrailers?: boolean | undefined; + } + export interface StatOptions { + offset: number; + length: number; + } + export interface ServerStreamFileResponseOptions { + statCheck?: + | ((stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void) + | undefined; + waitForTrailers?: boolean | undefined; + offset?: number | undefined; + length?: number | undefined; + } + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?: ((err: NodeJS.ErrnoException) => void) | undefined; + } + export interface Http2Stream extends stream.Duplex { + /** + * Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, + * the `'aborted'` event will have been emitted. + * @since v8.4.0 + */ + readonly aborted: boolean; + /** + * This property shows the number of characters currently buffered to be written. + * See `net.Socket.bufferSize` for details. + * @since v11.2.0, v10.16.0 + */ + readonly bufferSize: number; + /** + * Set to `true` if the `Http2Stream` instance has been closed. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Set to `true` if the `Http2Stream` instance has been destroyed and is no longer + * usable. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Set to `true` if the `END_STREAM` flag was set in the request or response + * HEADERS frame received, indicating that no additional data should be received + * and the readable side of the `Http2Stream` will be closed. + * @since v10.11.0 + */ + readonly endAfterHeaders: boolean; + /** + * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined` if the stream identifier has not yet been assigned. + * @since v8.4.0 + */ + readonly id?: number | undefined; + /** + * Set to `true` if the `Http2Stream` instance has not yet been assigned a + * numeric stream identifier. + * @since v9.4.0 + */ + readonly pending: boolean; + /** + * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is + * destroyed after either receiving an `RST_STREAM` frame from the connected peer, + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be `undefined` if the `Http2Stream` has not been closed. + * @since v8.4.0 + */ + readonly rstCode: number; + /** + * An object containing the outbound headers sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentHeaders: OutgoingHttpHeaders; + /** + * An array of objects containing the outbound informational (additional) headers + * sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined; + /** + * An object containing the outbound trailers sent for this `HttpStream`. + * @since v9.5.0 + */ + readonly sentTrailers?: OutgoingHttpHeaders | undefined; + /** + * A reference to the `Http2Session` instance that owns this `Http2Stream`. The + * value will be `undefined` after the `Http2Stream` instance is destroyed. + * @since v8.4.0 + */ + readonly session: Http2Session | undefined; + /** + * Provides miscellaneous information about the current state of the `Http2Stream`. + * + * A current state of this `Http2Stream`. + * @since v8.4.0 + */ + readonly state: StreamState; + /** + * Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the + * connected HTTP/2 peer. + * @since v8.4.0 + * @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code. + * @param callback An optional function registered to listen for the `'close'` event. + */ + close(code?: number, callback?: () => void): void; + /** + * Updates the priority for this `Http2Stream` instance. + * @since v8.4.0 + */ + priority(options: StreamPriorityOptions): void; + /** + * ```js + * import http2 from 'node:http2'; + * const client = http2.connect('http://example.org:8000'); + * const { NGHTTP2_CANCEL } = http2.constants; + * const req = client.request({ ':path': '/' }); + * + * // Cancel the stream if there's no activity after 5 seconds + * req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); + * ``` + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method + * will cause the `Http2Stream` to be immediately closed and must only be + * called after the `'wantTrailers'` event has been emitted. When sending a + * request or sending a response, the `options.waitForTrailers` option must be set + * in order to keep the `Http2Stream` open after the final `DATA` frame so that + * trailers can be sent. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond(undefined, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ xyz: 'abc' }); + * }); + * stream.end('Hello World'); + * }); + * ``` + * + * The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header + * fields (e.g. `':method'`, `':path'`, etc). + * @since v10.0.0 + */ + sendTrailers(headers: OutgoingHttpHeaders): void; + addListener(event: "aborted", listener: () => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: "streamClosed", listener: (code: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "wantTrailers", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted"): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: NonSharedBuffer | string): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "frameError", frameType: number, errorCode: number): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: "streamClosed", code: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "wantTrailers"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: () => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: "streamClosed", listener: (code: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "wantTrailers", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: () => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: "streamClosed", listener: (code: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "wantTrailers", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: () => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "streamClosed", listener: (code: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "wantTrailers", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: () => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "wantTrailers", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: "continue", listener: () => {}): this; + addListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "continue"): boolean; + emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "continue", listener: () => {}): this; + on( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "continue", listener: () => {}): this; + once( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "continue", listener: () => {}): this; + prependListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "continue", listener: () => {}): this; + prependOnceListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ServerHttp2Stream extends Http2Stream { + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote + * client's most recent `SETTINGS` frame. Will be `true` if the remote peer + * accepts push streams, `false` otherwise. Settings are the same for every `Http2Stream` in the same `Http2Session`. + * @since v8.4.0 + */ + readonly pushAllowed: boolean; + /** + * Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. + * @since v8.4.0 + */ + additionalHeaders(headers: OutgoingHttpHeaders): void; + /** + * Initiates a push stream. The callback is invoked with the new `Http2Stream` instance created for the push stream passed as the second argument, or an `Error` passed as the first argument. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { + * if (err) throw err; + * pushStream.respond({ ':status': 200 }); + * pushStream.end('some pushed data'); + * }); + * stream.end('some data'); + * }); + * ``` + * + * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass + * a `weight` value to `http2stream.priority` with the `silent` option set to `true` to enable server-side bandwidth balancing between concurrent streams. + * + * Calling `http2stream.pushStream()` from within a pushed stream is not permitted + * and will throw an error. + * @since v8.4.0 + * @param callback Callback that is called once the push stream has been initiated. + */ + pushStream( + headers: OutgoingHttpHeaders, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + pushStream( + headers: OutgoingHttpHeaders, + options?: StreamPriorityOptions, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + /** + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * Initiates a response. When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be used to send trailing header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either `http2stream.sendTrailers()` or `http2stream.close()` to close the `Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * stream.end('some data'); + * }); + * ``` + * @since v8.4.0 + */ + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + /** + * Initiates a response whose data is read from the given file descriptor. No + * validation is performed on the given file descriptor. If an error occurs while + * attempting to read data using the file descriptor, the `Http2Stream` will be + * closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers); + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given fd. If the `statCheck` function is provided, the `http2stream.respondWithFD()` method will + * perform an `fs.fstat()` call to collect details on the provided file descriptor. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The file descriptor or `FileHandle` is not closed when the stream is closed, + * so it will need to be closed manually once it is no longer needed. + * Using the same file descriptor concurrently for multiple streams + * is not supported and may result in data loss. Re-using a file descriptor + * after a stream has finished is supported. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code _must_ call either `http2stream.sendTrailers()` + * or `http2stream.close()` to close the `Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * @since v8.4.0 + * @param fd A readable file descriptor. + */ + respondWithFD( + fd: number | fs.promises.FileHandle, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptions, + ): void; + /** + * Sends a regular file as the response. The `path` must specify a regular file + * or an `'error'` event will be emitted on the `Http2Stream` object. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given file: + * + * If an error occurs while attempting to read the file data, the `Http2Stream` will be closed using an + * `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * If the `onError` callback is defined, then it will be called. Otherwise, the stream will be destroyed. + * + * Example using a file path: + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * headers['last-modified'] = stat.mtime.toUTCString(); + * } + * + * function onError(err) { + * // stream.respond() can throw if the stream has been destroyed by + * // the other side. + * try { + * if (err.code === 'ENOENT') { + * stream.respond({ ':status': 404 }); + * } else { + * stream.respond({ ':status': 500 }); + * } + * } catch (err) { + * // Perform actual error handling. + * console.error(err); + * } + * stream.end(); + * } + * + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck, onError }); + * }); + * ``` + * + * The `options.statCheck` function may also be used to cancel the send operation + * by returning `false`. For instance, a conditional request may check the stat + * results to determine if the file has been modified to return an appropriate `304` response: + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * // Check the stat here... + * stream.respond({ ':status': 304 }); + * return false; // Cancel the send operation + * } + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck }); + * }); + * ``` + * + * The `content-length` header field will be automatically set. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The `options.onError` function may also be used to handle all the errors + * that could happen before the delivery of the file is initiated. The + * default behavior is to destroy the stream. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * }); + * ``` + * @since v8.4.0 + */ + respondWithFile( + path: string, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptionsWithError, + ): void; + } + // Http2Session + export interface Settings { + headerTableSize?: number | undefined; + enablePush?: boolean | undefined; + initialWindowSize?: number | undefined; + maxFrameSize?: number | undefined; + maxConcurrentStreams?: number | undefined; + maxHeaderListSize?: number | undefined; + enableConnectProtocol?: boolean | undefined; + } + export interface ClientSessionRequestOptions { + endStream?: boolean | undefined; + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + waitForTrailers?: boolean | undefined; + signal?: AbortSignal | undefined; + } + export interface SessionState { + effectiveLocalWindowSize?: number | undefined; + effectiveRecvDataLength?: number | undefined; + nextStreamID?: number | undefined; + localWindowSize?: number | undefined; + lastProcStreamID?: number | undefined; + remoteWindowSize?: number | undefined; + outboundQueueSize?: number | undefined; + deflateDynamicTableSize?: number | undefined; + inflateDynamicTableSize?: number | undefined; + } + export interface Http2Session extends EventEmitter { + /** + * Value will be `undefined` if the `Http2Session` is not yet connected to a + * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or + * will return the value of the connected `TLSSocket`'s own `alpnProtocol` property. + * @since v9.4.0 + */ + readonly alpnProtocol?: string | undefined; + /** + * Will be `true` if this `Http2Session` instance has been closed, otherwise `false`. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Will be `true` if this `Http2Session` instance is still connecting, will be set + * to `false` before emitting `connect` event and/or calling the `http2.connect` callback. + * @since v10.0.0 + */ + readonly connecting: boolean; + /** + * Will be `true` if this `Http2Session` instance has been destroyed and must no + * longer be used, otherwise `false`. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Value is `undefined` if the `Http2Session` session socket has not yet been + * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, + * and `false` if the `Http2Session` is connected to any other kind of socket + * or stream. + * @since v9.4.0 + */ + readonly encrypted?: boolean | undefined; + /** + * A prototype-less object describing the current local settings of this `Http2Session`. + * The local settings are local to _this_`Http2Session` instance. + * @since v8.4.0 + */ + readonly localSettings: Settings; + /** + * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property + * will return an `Array` of origins for which the `Http2Session` may be + * considered authoritative. + * + * The `originSet` property is only available when using a secure TLS connection. + * @since v9.4.0 + */ + readonly originSet?: string[] | undefined; + /** + * Indicates whether the `Http2Session` is currently waiting for acknowledgment of + * a sent `SETTINGS` frame. Will be `true` after calling the `http2session.settings()` method. + * Will be `false` once all sent `SETTINGS` frames have been acknowledged. + * @since v8.4.0 + */ + readonly pendingSettingsAck: boolean; + /** + * A prototype-less object describing the current remote settings of this`Http2Session`. + * The remote settings are set by the _connected_ HTTP/2 peer. + * @since v8.4.0 + */ + readonly remoteSettings: Settings; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * limits available methods to ones safe to use with HTTP/2. + * + * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw + * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. + * + * `setTimeout` method will be called on this `Http2Session`. + * + * All other interactions will be routed directly to the socket. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * Provides miscellaneous information about the current state of the`Http2Session`. + * + * An object describing the current status of this `Http2Session`. + * @since v8.4.0 + */ + readonly state: SessionState; + /** + * The `http2session.type` will be equal to `http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a + * client. + * @since v8.4.0 + */ + readonly type: number; + /** + * Gracefully closes the `Http2Session`, allowing any existing streams to + * complete on their own and preventing new `Http2Stream` instances from being + * created. Once closed, `http2session.destroy()`_might_ be called if there + * are no open `Http2Stream` instances. + * + * If specified, the `callback` function is registered as a handler for the`'close'` event. + * @since v9.4.0 + */ + close(callback?: () => void): void; + /** + * Immediately terminates the `Http2Session` and the associated `net.Socket` or `tls.TLSSocket`. + * + * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error` is not undefined, an `'error'` event will be emitted immediately before the `'close'` event. + * + * If there are any remaining open `Http2Streams` associated with the `Http2Session`, those will also be destroyed. + * @since v8.4.0 + * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. + * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. + */ + destroy(error?: Error, code?: number): void; + /** + * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. + * @since v9.4.0 + * @param code An HTTP/2 error code + * @param lastStreamID The numeric ID of the last processed `Http2Stream` + * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. + */ + goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; + /** + * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must + * be provided. The method will return `true` if the `PING` was sent, `false` otherwise. + * + * The maximum number of outstanding (unacknowledged) pings is determined by the `maxOutstandingPings` configuration option. The default maximum is 10. + * + * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView` containing 8 bytes of data that will be transmitted with the `PING` and + * returned with the ping acknowledgment. + * + * The callback will be invoked with three arguments: an error argument that will + * be `null` if the `PING` was successfully acknowledged, a `duration` argument + * that reports the number of milliseconds elapsed since the ping was sent and the + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING` payload. + * + * ```js + * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { + * if (!err) { + * console.log(`Ping acknowledged in ${duration} milliseconds`); + * console.log(`With payload '${payload.toString()}'`); + * } + * }); + * ``` + * + * If the `payload` argument is not specified, the default payload will be the + * 64-bit timestamp (little endian) marking the start of the `PING` duration. + * @since v8.9.3 + * @param payload Optional ping payload. + */ + ping(callback: (err: Error | null, duration: number, payload: NonSharedBuffer) => void): boolean; + ping( + payload: NodeJS.ArrayBufferView, + callback: (err: Error | null, duration: number, payload: NonSharedBuffer) => void, + ): boolean; + /** + * Calls `ref()` on this `Http2Session` instance's underlying `net.Socket`. + * @since v9.4.0 + */ + ref(): void; + /** + * Sets the local endpoint's window size. + * The `windowSize` is the total window size to set, not + * the delta. + * + * ```js + * import http2 from 'node:http2'; + * + * const server = http2.createServer(); + * const expectedWindowSize = 2 ** 20; + * server.on('connect', (session) => { + * + * // Set local window size to be 2 ** 20 + * session.setLocalWindowSize(expectedWindowSize); + * }); + * ``` + * @since v15.3.0, v14.18.0 + */ + setLocalWindowSize(windowSize: number): void; + /** + * Used to set a callback function that is called when there is no activity on + * the `Http2Session` after `msecs` milliseconds. The given `callback` is + * registered as a listener on the `'timeout'` event. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Updates the current local settings for this `Http2Session` and sends a new `SETTINGS` frame to the connected HTTP/2 peer. + * + * Once called, the `http2session.pendingSettingsAck` property will be `true` while the session is waiting for the remote peer to acknowledge the new + * settings. + * + * The new settings will not become effective until the `SETTINGS` acknowledgment + * is received and the `'localSettings'` event is emitted. It is possible to send + * multiple `SETTINGS` frames while acknowledgment is still pending. + * @since v8.4.0 + * @param callback Callback that is called once the session is connected or right away if the session is already connected. + */ + settings( + settings: Settings, + callback?: (err: Error | null, settings: Settings, duration: number) => void, + ): void; + /** + * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + unref(): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + addListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer) => void, + ): this; + addListener(event: "localSettings", listener: (settings: Settings) => void): this; + addListener(event: "ping", listener: () => void): this; + addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; + emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer): boolean; + emit(event: "localSettings", settings: Settings): boolean; + emit(event: "ping"): boolean; + emit(event: "remoteSettings", settings: Settings): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer) => void, + ): this; + on(event: "localSettings", listener: (settings: Settings) => void): this; + on(event: "ping", listener: () => void): this; + on(event: "remoteSettings", listener: (settings: Settings) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer) => void, + ): this; + once(event: "localSettings", listener: (settings: Settings) => void): this; + once(event: "ping", listener: () => void): this; + once(event: "remoteSettings", listener: (settings: Settings) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + prependListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer) => void, + ): this; + prependListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependListener(event: "ping", listener: () => void): this; + prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + prependOnceListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer) => void, + ): this; + prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "ping", listener: () => void): this; + prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Session extends Http2Session { + /** + * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()` creates and returns an `Http2Stream` instance that can be used to send an + * HTTP/2 request to the connected server. + * + * When a `ClientHttp2Session` is first created, the socket may not yet be + * connected. if `clienthttp2session.request()` is called during this time, the + * actual request will be deferred until the socket is ready to go. + * If the `session` is closed before the actual request be executed, an `ERR_HTTP2_GOAWAY_SESSION` is thrown. + * + * This method is only available if `http2session.type` is equal to `http2.constants.NGHTTP2_SESSION_CLIENT`. + * + * ```js + * import http2 from 'node:http2'; + * const clientSession = http2.connect('https://localhost:1234'); + * const { + * HTTP2_HEADER_PATH, + * HTTP2_HEADER_STATUS, + * } = http2.constants; + * + * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); + * req.on('response', (headers) => { + * console.log(headers[HTTP2_HEADER_STATUS]); + * req.on('data', (chunk) => { // .. }); + * req.on('end', () => { // .. }); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * is emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be called to send trailing + * headers to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * When `options.signal` is set with an `AbortSignal` and then `abort` on the + * corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error. + * + * The `:method` and `:path` pseudo-headers are not specified within `headers`, + * they respectively default to: + * + * * `:method` \= `'GET'` + * * `:path` \= `/` + * @since v8.4.0 + */ + request( + headers?: OutgoingHttpHeaders | readonly string[], + options?: ClientSessionRequestOptions, + ): ClientHttp2Stream; + addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: "origin", listener: (origins: string[]) => void): this; + addListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + addListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; + emit(event: "origin", origins: readonly string[]): boolean; + emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit( + event: "stream", + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + on(event: "origin", listener: (origins: string[]) => void): this; + on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + once(event: "origin", listener: (origins: string[]) => void): this; + once( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + once( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: "origin", listener: (origins: string[]) => void): this; + prependListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: "origin", listener: (origins: string[]) => void): this; + prependOnceListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependOnceListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + export interface ServerHttp2Session< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends Http2Session { + readonly server: + | Http2Server + | Http2SecureServer; + /** + * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. + * + * ```js + * import http2 from 'node:http2'; + * + * const server = http2.createServer(); + * server.on('session', (session) => { + * // Set altsvc for origin https://example.org:80 + * session.altsvc('h2=":8000"', 'https://example.org:80'); + * }); + * + * server.on('stream', (stream) => { + * // Set altsvc for a specific stream + * stream.session.altsvc('h2=":8000"', stream.id); + * }); + * ``` + * + * Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate + * service is associated with the origin of the given `Http2Stream`. + * + * The `alt` and origin string _must_ contain only ASCII bytes and are + * strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given + * domain. + * + * When a string is passed for the `originOrStream` argument, it will be parsed as + * a URL and the origin will be derived. For instance, the origin for the + * HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * @since v9.4.0 + * @param alt A description of the alternative service configuration as defined by `RFC 7838`. + * @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the + * `http2stream.id` property. + */ + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + /** + * Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client + * to advertise the set of origins for which the server is capable of providing + * authoritative responses. + * + * ```js + * import http2 from 'node:http2'; + * const options = getSecureOptionsSomehow(); + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * server.on('session', (session) => { + * session.origin('https://example.com', 'https://example.org'); + * }); + * ``` + * + * When a string is passed as an `origin`, it will be parsed as a URL and the + * origin will be derived. For instance, the origin for the HTTP URL `'https://example.org/foo/bar'` is the ASCII string` 'https://example.org'`. An error will be thrown if either the given + * string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as + * an `origin`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * + * Alternatively, the `origins` option may be used when creating a new HTTP/2 + * server using the `http2.createSecureServer()` method: + * + * ```js + * import http2 from 'node:http2'; + * const options = getSecureOptionsSomehow(); + * options.origins = ['https://example.com', 'https://example.org']; + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * ``` + * @since v10.12.0 + * @param origins One or more URL Strings passed as separate arguments. + */ + origin( + ...origins: Array< + | string + | url.URL + | { + origin: string; + } + > + ): void; + addListener( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit( + event: "connect", + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + // Http2Server + export interface SessionOptions { + /** + * Sets the maximum dynamic table size for deflating header fields. + * @default 4Kib + */ + maxDeflateDynamicTableSize?: number | undefined; + /** + * Sets the maximum number of settings entries per `SETTINGS` frame. + * The minimum value allowed is `1`. + * @default 32 + */ + maxSettings?: number | undefined; + /** + * Sets the maximum memory that the `Http2Session` is permitted to use. + * The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. + * The minimum value allowed is `1`. + * This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, + * but new `Http2Stream` instances will be rejected while this limit is exceeded. + * The current number of `Http2Stream` sessions, the current memory use of the header compression tables, + * current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit. + * @default 10 + */ + maxSessionMemory?: number | undefined; + /** + * Sets the maximum number of header entries. + * This is similar to `server.maxHeadersCount` or `request.maxHeadersCount` in the `node:http` module. + * The minimum value is `1`. + * @default 128 + */ + maxHeaderListPairs?: number | undefined; + /** + * Sets the maximum number of outstanding, unacknowledged pings. + * @default 10 + */ + maxOutstandingPings?: number | undefined; + /** + * Sets the maximum allowed size for a serialized, compressed block of headers. + * Attempts to send headers that exceed this limit will result in + * a `'frameError'` event being emitted and the stream being closed and destroyed. + */ + maxSendHeaderBlockLength?: number | undefined; + /** + * Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames. + * @default http2.constants.PADDING_STRATEGY_NONE + */ + paddingStrategy?: number | undefined; + /** + * Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. + * Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. + * @default 100 + */ + peerMaxConcurrentStreams?: number | undefined; + /** + * The initial settings to send to the remote peer upon connection. + */ + settings?: Settings | undefined; + /** + * The array of integer values determines the settings types, + * which are included in the `CustomSettings`-property of the received remoteSettings. + * Please see the `CustomSettings`-property of the `Http2Settings` object for more information, on the allowed setting types. + */ + remoteCustomSettings?: number[] | undefined; + /** + * Specifies a timeout in milliseconds that + * a server should wait when an [`'unknownProtocol'`][] is emitted. If the + * socket has not been destroyed by that time the server will destroy it. + * @default 100000 + */ + unknownProtocolTimeout?: number | undefined; + /** + * If `true`, it turns on strict leading + * and trailing whitespace validation for HTTP/2 header field names and values + * as per [RFC-9113](https://www.rfc-editor.org/rfc/rfc9113.html#section-8.2.1). + * @since v24.2.0 + * @default true + */ + strictFieldWhitespaceValidation?: boolean | undefined; + } + export interface ClientSessionOptions extends SessionOptions { + /** + * Sets the maximum number of reserved push streams the client will accept at any given time. + * Once the current number of currently reserved push streams exceeds reaches this limit, + * new push streams sent by the server will be automatically rejected. + * The minimum allowed value is 0. The maximum allowed value is 232-1. + * A negative value sets this option to the maximum allowed value. + * @default 200 + */ + maxReservedRemoteStreams?: number | undefined; + /** + * An optional callback that receives the `URL` instance passed to `connect` and the `options` object, + * and returns any `Duplex` stream that is to be used as the connection for this session. + */ + createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; + /** + * The protocol to connect with, if not set in the `authority`. + * Value may be either `'http:'` or `'https:'`. + * @default 'https:' + */ + protocol?: "http:" | "https:" | undefined; + } + export interface ServerSessionOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends SessionOptions { + streamResetBurst?: number | undefined; + streamResetRate?: number | undefined; + Http1IncomingMessage?: Http1Request | undefined; + Http1ServerResponse?: Http1Response | undefined; + Http2ServerRequest?: Http2Request | undefined; + Http2ServerResponse?: Http2Response | undefined; + } + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + export interface SecureServerSessionOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends ServerSessionOptions, tls.TlsOptions {} + export interface ServerOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends ServerSessionOptions {} + export interface SecureServerOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends SecureServerSessionOptions { + allowHTTP1?: boolean | undefined; + origins?: string[] | undefined; + } + interface HTTP2ServerCommon { + setTimeout(msec?: number, callback?: () => void): this; + /** + * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. + * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. + */ + updateSettings(settings: Settings): void; + } + export interface Http2Server< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends net.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + addListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + addListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit( + event: "checkContinue", + request: InstanceType, + response: InstanceType, + ): boolean; + emit(event: "request", request: InstanceType, response: InstanceType): boolean; + emit( + event: "session", + session: ServerHttp2Session, + ): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + on( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + on( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + once( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + once( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependOnceListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface Http2SecureServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends tls.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + addListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + addListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit( + event: "checkContinue", + request: InstanceType, + response: InstanceType, + ): boolean; + emit(event: "request", request: InstanceType, response: InstanceType): boolean; + emit( + event: "session", + session: ServerHttp2Session, + ): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + on( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + on( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + once( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + once( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependOnceListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status, + * headers, and + * data. + * @since v8.4.0 + */ + export class Http2ServerRequest extends stream.Readable { + constructor( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + options: stream.ReadableOptions, + rawHeaders: readonly string[], + ); + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ + readonly aborted: boolean; + /** + * The request authority pseudo header field. Because HTTP/2 allows requests + * to set either `:authority` or `host`, this value is derived from `req.headers[':authority']` if present. Otherwise, it is derived from `req.headers['host']`. + * @since v8.4.0 + */ + readonly authority: string; + /** + * See `request.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * The `request.complete` property will be `true` if the request has + * been completed, aborted, or destroyed. + * @since v12.10.0 + */ + readonly complete: boolean; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * See `HTTP/2 Headers Object`. + * + * In HTTP/2, the request path, host name, protocol, and method are represented as + * special headers prefixed with the `:` character (e.g. `':path'`). These special + * headers will be included in the `request.headers` object. Care must be taken not + * to inadvertently modify these special headers or errors may occur. For instance, + * removing all headers from the request will cause errors to occur: + * + * ```js + * removeAllHeaders(request.headers); + * assert(request.url); // Fails because the :path header has been removed + * ``` + * @since v8.4.0 + */ + readonly headers: IncomingHttpHeaders; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. Returns `'2.0'`. + * + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. + * @since v8.4.0 + */ + readonly httpVersion: string; + readonly httpVersionMinor: number; + readonly httpVersionMajor: number; + /** + * The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. + * @since v8.4.0 + */ + readonly method: string; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v8.4.0 + */ + readonly rawHeaders: string[]; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly rawTrailers: string[]; + /** + * The request scheme pseudo header field indicating the scheme + * portion of the target URL. + * @since v8.4.0 + */ + readonly scheme: string; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `request.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `request.stream`. + * + * `setTimeout` method will be called on `request.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. With TLS support, + * use `request.socket.getPeerCertificate()` to obtain the client's + * authentication details. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the request. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly trailers: IncomingHttpHeaders; + /** + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. If the request is: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * Then `request.url` will be: + * + * ```js + * '/status?name=ryan' + * ``` + * + * To parse the url into its parts, `new URL()` can be used: + * + * ```console + * $ node + * > new URL('/status?name=ryan', 'http://example.com') + * URL { + * href: 'http://example.com/status?name=ryan', + * origin: 'http://example.com', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'example.com', + * hostname: 'example.com', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v8.4.0 + */ + url: string; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream`s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + read(size?: number): NonSharedBuffer | string | null; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted", hadError: boolean, code: number): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: NonSharedBuffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v8.4.0 + */ + export class Http2ServerResponse extends stream.Writable { + constructor(stream: ServerHttp2Stream); + /** + * See `response.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple times. + * + * If there were no previous values for the header, this is equivalent to calling {@link setHeader}. + * + * Attempting to set a header field name or value that contains invalid characters will result in a + * [TypeError](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-typeerror) being thrown. + * + * ```js + * // Returns headers including "set-cookie: a" and "set-cookie: b" + * const server = http2.createServer((req, res) => { + * res.setHeader('set-cookie', 'a'); + * res.appendHeader('set-cookie', 'b'); + * res.writeHead(200); + * res.end('ok'); + * }); + * ``` + * @since v20.12.0 + */ + appendHeader(name: string, value: string | string[]): void; + /** + * Boolean value that indicates whether the response has completed. Starts + * as `false`. After `response.end()` executes, the value will be `true`. + * @since v8.4.0 + * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. + */ + readonly finished: boolean; + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * A reference to the original HTTP2 `request` object. + * @since v15.7.0 + */ + readonly req: Request; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `response.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `response.stream`. + * + * `setTimeout` method will be called on `response.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer((req, res) => { + * const ip = req.socket.remoteAddress; + * const port = req.socket.remotePort; + * res.end(`Your IP address is ${ip} and your source port is ${port}.`); + * }).listen(3000); + * ``` + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the response. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * When true, the Date header will be automatically generated and sent in + * the response if it is not already present in the headers. Defaults to true. + * + * This should only be disabled for testing; HTTP requires the Date header + * in responses. + * @since v8.4.0 + */ + sendDate: boolean; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v8.4.0 + */ + statusCode: number; + /** + * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns + * an empty string. + * @since v8.4.0 + */ + statusMessage: ""; + /** + * This method adds HTTP trailing headers (a header but at the end of the + * message) to the response. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + addTrailers(trailers: OutgoingHttpHeaders): void; + /** + * This method signals to the server that all of the response headers and body + * have been sent; that server should consider this message complete. + * The method, `response.end()`, MUST be called on each response. + * + * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. + * + * If `callback` is specified, it will be called when the response stream + * is finished. + * @since v8.4.0 + */ + end(callback?: () => void): this; + end(data: string | Uint8Array, callback?: () => void): this; + end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): this; + /** + * Reads out a header that has already been queued but not sent to the client. + * The name is case-insensitive. + * + * ```js + * const contentType = response.getHeader('content-type'); + * ``` + * @since v8.4.0 + */ + getHeader(name: string): string; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All header names are lowercase. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = response.getHeaderNames(); + * // headerNames === ['foo', 'set-cookie'] + * ``` + * @since v8.4.0 + */ + getHeaderNames(): string[]; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow copy + * is used, array values may be mutated without additional calls to various + * header-related http module methods. The keys of the returned object are the + * header names and the values are the respective header values. All header names + * are lowercase. + * + * The object returned by the `response.getHeaders()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = response.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.4.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name matching is case-insensitive. + * + * ```js + * const hasContentType = response.hasHeader('content-type'); + * ``` + * @since v8.4.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that has been queued for implicit sending. + * + * ```js + * response.removeHeader('Content-Encoding'); + * ``` + * @since v8.4.0 + */ + removeHeader(name: string): void; + /** + * Sets a single header value for implicit headers. If this header already exists + * in the to-be-sent headers, its value will be replaced. Use an array of strings + * here to send multiple headers with the same name. + * + * ```js + * response.setHeader('Content-Type', 'text/html; charset=utf-8'); + * ``` + * + * or + * + * ```js + * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * @since v8.4.0 + */ + setHeader(name: string, value: number | string | readonly string[]): void; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * If this method is called and `response.writeHead()` has not been called, + * it will switch to implicit header mode and flush the implicit headers. + * + * This sends a chunk of the response body. This method may + * be called multiple times to provide successive parts of the body. + * + * In the `node:http` module, the response body is omitted when the + * request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body. + * + * `chunk` can be a string or a buffer. If `chunk` is a string, + * the second parameter specifies how to encode it into a byte stream. + * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk + * of data is flushed. + * + * This is the raw HTTP body and has nothing to do with higher-level multi-part + * body encodings that may be used. + * + * The first time `response.write()` is called, it will send the buffered + * header information and the first chunk of the body to the client. The second + * time `response.write()` is called, Node.js assumes data will be streamed, + * and sends the new data separately. That is, the response is buffered up to the + * first chunk of the body. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again. + * @since v8.4.0 + */ + write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; + /** + * Sends a status `100 Continue` to the client, indicating that the request body + * should be sent. See the `'checkContinue'` event on `Http2Server` and `Http2SecureServer`. + * @since v8.4.0 + */ + writeContinue(): void; + /** + * Sends a status `103 Early Hints` to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }); + * ``` + * @since v18.11.0 + */ + writeEarlyHints(hints: Record): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * + * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. + * + * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be + * passed as the second argument. However, because the `statusMessage` has no + * meaning within HTTP/2, the argument will have no effect and a process warning + * will be emitted. + * + * ```js + * const body = 'hello world'; + * response.writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain; charset=utf-8', + * }); + * ``` + * + * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a + * given encoding. On outbound messages, Node.js does not check if Content-Length + * and the length of the body being transmitted are equal or not. However, when + * receiving messages, Node.js will automatically reject messages when the `Content-Length` does not match the actual payload size. + * + * This method may be called at most one time on a message before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; + /** + * Call `http2stream.pushStream()` with the given headers, and wrap the + * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback + * parameter if successful. When `Http2ServerRequest` is closed, the callback is + * called with an error `ERR_HTTP2_INVALID_STREAM`. + * @since v8.4.0 + * @param headers An object describing the headers + * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of + * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method + */ + createPushResponse( + headers: OutgoingHttpHeaders, + callback: (err: Error | null, res: Http2ServerResponse) => void, + ): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + /** + * This symbol can be set as a property on the HTTP/2 headers object with + * an array value in order to provide a list of headers considered sensitive. + */ + export const sensitiveHeaders: symbol; + /** + * Returns an object containing the default settings for an `Http2Session` instance. This method returns a new object instance every time it is called + * so instances returned may be safely modified for use. + * @since v8.4.0 + */ + export function getDefaultSettings(): Settings; + /** + * Returns a `Buffer` instance containing serialized representation of the given + * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended + * for use with the `HTTP2-Settings` header field. + * + * ```js + * import http2 from 'node:http2'; + * + * const packed = http2.getPackedSettings({ enablePush: false }); + * + * console.log(packed.toString('base64')); + * // Prints: AAIAAAAA + * ``` + * @since v8.4.0 + */ + export function getPackedSettings(settings: Settings): NonSharedBuffer; + /** + * Returns a `HTTP/2 Settings Object` containing the deserialized settings from + * the given `Buffer` as generated by `http2.getPackedSettings()`. + * @since v8.4.0 + * @param buf The packed settings. + */ + export function getUnpackedSettings(buf: Uint8Array): Settings; + /** + * Returns a `net.Server` instance that creates and manages `Http2Session` instances. + * + * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when + * communicating + * with browser clients. + * + * ```js + * import http2 from 'node:http2'; + * + * // Create an unencrypted HTTP/2 server. + * // Since there are no browsers known that support + * // unencrypted HTTP/2, the use of `http2.createSecureServer()` + * // is necessary when communicating with browser clients. + * const server = http2.createServer(); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

                          Hello World

                          '); + * }); + * + * server.listen(8000); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + export function createServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + options: ServerOptions, + onRequestHandler?: (request: InstanceType, response: InstanceType) => void, + ): Http2Server; + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session` instances. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * }; + * + * // Create a secure HTTP/2 server + * const server = http2.createSecureServer(options); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

                          Hello World

                          '); + * }); + * + * server.listen(8443); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createSecureServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + export function createSecureServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + options: SecureServerOptions, + onRequestHandler?: (request: InstanceType, response: InstanceType) => void, + ): Http2SecureServer; + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * import http2 from 'node:http2'; + * const client = http2.connect('https://localhost:1234'); + * + * // Use the client + * + * client.close(); + * ``` + * @since v8.4.0 + * @param authority The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port + * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. + * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. + */ + export function connect( + authority: string | url.URL, + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + /** + * Create an HTTP/2 server session from an existing socket. + * @param socket A Duplex Stream + * @param options Any `{@link createServer}` options can be provided. + * @since v20.12.0 + */ + export function performServerHandshake< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + socket: stream.Duplex, + options?: ServerOptions, + ): ServerHttp2Session; +} +declare module "node:http2" { + export * from "http2"; +} diff --git a/node_modules/@types/node/https.d.ts b/node_modules/@types/node/https.d.ts new file mode 100644 index 0000000..e050255 --- /dev/null +++ b/node_modules/@types/node/https.d.ts @@ -0,0 +1,579 @@ +/** + * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a + * separate module. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/https.js) + */ +declare module "https" { + import { NonSharedBuffer } from "node:buffer"; + import { Duplex } from "node:stream"; + import * as tls from "node:tls"; + import * as http from "node:http"; + import { URL } from "node:url"; + interface ServerOptions< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends http.ServerOptions, tls.TlsOptions {} + interface RequestOptions extends http.RequestOptions, tls.SecureContextOptions { + checkServerIdentity?: + | ((hostname: string, cert: tls.DetailedPeerCertificate) => Error | undefined) + | undefined; + rejectUnauthorized?: boolean | undefined; // Defaults to true + servername?: string | undefined; // SNI TLS Extension + } + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + maxCachedSessions?: number | undefined; + } + /** + * An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information. + * @since v0.4.5 + */ + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + createConnection( + options: RequestOptions, + callback?: (err: Error | null, stream: Duplex) => void, + ): Duplex | null | undefined; + getName(options?: RequestOptions): string; + } + interface Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends http.Server {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor( + options: ServerOptions, + requestListener?: http.RequestListener, + ); + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Duplex) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: http.RequestListener): this; + addListener(event: "checkExpectation", listener: http.RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + addListener(event: "request", listener: http.RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "keylog", line: NonSharedBuffer, tlsSocket: tls.TLSSocket): boolean; + emit( + event: "newSession", + sessionId: NonSharedBuffer, + sessionData: NonSharedBuffer, + callback: () => void, + ): boolean; + emit( + event: "OCSPRequest", + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ): boolean; + emit( + event: "resumeSession", + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ): boolean; + emit(event: "secureConnection", tlsSocket: tls.TLSSocket): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: tls.TLSSocket): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Duplex): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType, + ): boolean; + emit(event: "clientError", err: Error, socket: Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: Duplex, head: NonSharedBuffer): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: Duplex, head: NonSharedBuffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this; + on( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + on( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Duplex) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: http.RequestListener): this; + on(event: "checkExpectation", listener: http.RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + on( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + on(event: "request", listener: http.RequestListener): this; + on( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Duplex) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: http.RequestListener): this; + once(event: "checkExpectation", listener: http.RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + once( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + once(event: "request", listener: http.RequestListener): this; + once( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Duplex) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: http.RequestListener): this; + prependListener(event: "checkExpectation", listener: http.RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + prependListener(event: "request", listener: http.RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Duplex) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: http.RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: http.RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + prependOnceListener(event: "request", listener: http.RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + } + /** + * ```js + * // curl -k https://localhost:8000/ + * import https from 'node:https'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * + * Or + * + * ```js + * import https from 'node:https'; + * import fs from 'node:fs'; + * + * const options = { + * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), + * passphrase: 'sample', + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * @since v0.3.4 + * @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`. + * @param requestListener A listener to be added to the `'request'` event. + */ + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + >(requestListener?: http.RequestListener): Server; + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + >( + options: ServerOptions, + requestListener?: http.RequestListener, + ): Server; + /** + * Makes a request to a secure web server. + * + * The following additional `options` from `tls.connect()` are also accepted: `ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`, `honorCipherOrder`, `key`, `passphrase`, + * `pfx`, `rejectUnauthorized`, `secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`, `highWaterMark`. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * import https from 'node:https'; + * + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * }; + * + * const req = https.request(options, (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(e); + * }); + * req.end(); + * ``` + * + * Example using options from `tls.connect()`: + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * options.agent = new https.Agent(options); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Alternatively, opt out of connection pooling by not using an `Agent`. + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * agent: false, + * }; + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('https://abc:xyz@example.com'); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): + * + * ```js + * import tls from 'node:tls'; + * import https from 'node:https'; + * import crypto from 'node:crypto'; + * + * function sha256(s) { + * return crypto.createHash('sha256').update(s).digest('base64'); + * } + * const options = { + * hostname: 'github.com', + * port: 443, + * path: '/', + * method: 'GET', + * checkServerIdentity: function(host, cert) { + * // Make sure the certificate is issued to the host we are connected to + * const err = tls.checkServerIdentity(host, cert); + * if (err) { + * return err; + * } + * + * // Pin the public key, similar to HPKP pin-sha256 pinning + * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; + * if (sha256(cert.pubkey) !== pubkey256) { + * const msg = 'Certificate verification error: ' + + * `The public key of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // Pin the exact certificate, rather than the pub key + * const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + + * 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; + * if (cert.fingerprint256 !== cert256) { + * const msg = 'Certificate verification error: ' + + * `The certificate of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // This loop is informational only. + * // Print the certificate and public key fingerprints of all certs in the + * // chain. Its common to pin the public key of the issuer on the public + * // internet, while pinning the public key of the service in sensitive + * // environments. + * do { + * console.log('Subject Common Name:', cert.subject.CN); + * console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); + * + * hash = crypto.createHash('sha256'); + * console.log(' Public key ping-sha256:', sha256(cert.pubkey)); + * + * lastprint256 = cert.fingerprint256; + * cert = cert.issuerCertificate; + * } while (cert.fingerprint256 !== lastprint256); + * + * }, + * }; + * + * options.agent = new https.Agent(options); + * const req = https.request(options, (res) => { + * console.log('All OK. Server matched our pinned cert or public key'); + * console.log('statusCode:', res.statusCode); + * // Print the HPKP values + * console.log('headers:', res.headers['public-key-pins']); + * + * res.on('data', (d) => {}); + * }); + * + * req.on('error', (e) => { + * console.error(e.message); + * }); + * req.end(); + * ``` + * + * Outputs for example: + * + * ```text + * Subject Common Name: github.com + * Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 + * Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= + * Subject Common Name: DigiCert SHA2 Extended Validation Server CA + * Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A + * Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= + * Subject Common Name: DigiCert High Assurance EV Root CA + * Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF + * Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= + * All OK. Server matched our pinned cert or public key + * statusCode: 200 + * headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; + * pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; + * pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains + * ``` + * @since v0.3.6 + * @param options Accepts all `options` from `request`, with some differences in default values: + */ + function request( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + /** + * Like `http.get()` but for HTTPS. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * ```js + * import https from 'node:https'; + * + * https.get('https://encrypted.google.com/', (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * + * }).on('error', (e) => { + * console.error(e); + * }); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. + */ + function get( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function get( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + let globalAgent: Agent; +} +declare module "node:https" { + export * from "https"; +} diff --git a/node_modules/@types/node/index.d.ts b/node_modules/@types/node/index.d.ts new file mode 100644 index 0000000..c9edbd7 --- /dev/null +++ b/node_modules/@types/node/index.d.ts @@ -0,0 +1,97 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +// NOTE: These definitions support Node.js and TypeScript 5.7+. + +// Reference required TypeScript libs: +/// + +// TypeScript backwards-compatibility definitions: +/// + +// Definitions specific to TypeScript 5.7+: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/node_modules/@types/node/inspector.d.ts b/node_modules/@types/node/inspector.d.ts new file mode 100644 index 0000000..1f1a6fe --- /dev/null +++ b/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,253 @@ +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/inspector.js) + */ +declare module "inspector" { + import EventEmitter = require("node:events"); + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend. + */ + constructor(); + /** + * Connects a session to the inspector back-end. + */ + connect(): void; + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + * @since v12.11.0 + */ + connectToMainThread(): void; + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * `session.connect()` will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + } + /** + * Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has + * started. + * + * If wait is `true`, will block until a client has connected to the inspect port + * and flow control has been passed to the debugger client. + * + * See the [security warning](https://nodejs.org/docs/latest-v22.x/api/cli.html#warning-binding-inspector-to-a-public-ipport-combination-is-insecure) + * regarding the `host` parameter usage. + * @param port Port to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param host Host to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param wait Block until a client has connected. Defaults to what was specified on the CLI. + * @returns Disposable that calls `inspector.close()`. + */ + function open(port?: number, host?: string, wait?: boolean): Disposable; + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + /** + * Return the URL of the active inspector, or `undefined` if there is none. + * + * ```console + * $ node --inspect -p 'inspector.url()' + * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * For help, see: https://nodejs.org/en/docs/inspector + * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * + * $ node --inspect=localhost:3000 -p 'inspector.url()' + * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * For help, see: https://nodejs.org/en/docs/inspector + * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * + * $ node -p 'inspector.url()' + * undefined + * ``` + */ + function url(): string | undefined; + /** + * Blocks until a client (existing or connected later) has sent `Runtime.runIfWaitingForDebugger` command. + * + * An exception will be thrown if there is no active inspector. + * @since v12.7.0 + */ + function waitForDebugger(): void; + // These methods are exposed by the V8 inspector console API (inspector/v8-console.h). + // The method signatures differ from those of the Node.js console, and are deliberately + // typed permissively. + interface InspectorConsole { + debug(...data: any[]): void; + error(...data: any[]): void; + info(...data: any[]): void; + log(...data: any[]): void; + warn(...data: any[]): void; + dir(...data: any[]): void; + dirxml(...data: any[]): void; + table(...data: any[]): void; + trace(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(...data: any[]): void; + clear(...data: any[]): void; + count(label?: any): void; + countReset(label?: any): void; + assert(value?: any, ...data: any[]): void; + profile(label?: any): void; + profileEnd(label?: any): void; + time(label?: any): void; + timeLog(label?: any): void; + timeStamp(label?: any): void; + } + /** + * An object to send messages to the remote inspector console. + * @since v11.0.0 + */ + const console: InspectorConsole; + // DevTools protocol event broadcast methods + namespace Network { + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.requestWillBeSent` event to connected frontends. This event indicates that + * the application is about to send an HTTP request. + * @since v22.6.0 + */ + function requestWillBeSent(params: RequestWillBeSentEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.dataReceived` event to connected frontends, or buffers the data if + * `Network.streamResourceContent` command was not invoked for the given request yet. + * + * Also enables `Network.getResponseBody` command to retrieve the response data. + * @since v22.17.0 + */ + function dataReceived(params: DataReceivedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Enables `Network.getRequestPostData` command to retrieve the request data. + * @since v22.18.0 + */ + function dataSent(params: unknown): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.responseReceived` event to connected frontends. This event indicates that + * HTTP response is available. + * @since v22.6.0 + */ + function responseReceived(params: ResponseReceivedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.loadingFinished` event to connected frontends. This event indicates that + * HTTP request has finished loading. + * @since v22.6.0 + */ + function loadingFinished(params: LoadingFinishedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.loadingFailed` event to connected frontends. This event indicates that + * HTTP request has failed to load. + * @since v22.7.0 + */ + function loadingFailed(params: LoadingFailedEventDataType): void; + } + namespace NetworkResources { + /** + * This feature is only available with the `--experimental-inspector-network-resource` flag enabled. + * + * The inspector.NetworkResources.put method is used to provide a response for a loadNetworkResource + * request issued via the Chrome DevTools Protocol (CDP). + * This is typically triggered when a source map is specified by URL, and a DevTools frontend—such as + * Chrome—requests the resource to retrieve the source map. + * + * This method allows developers to predefine the resource content to be served in response to such CDP requests. + * + * ```js + * const inspector = require('node:inspector'); + * // By preemptively calling put to register the resource, a source map can be resolved when + * // a loadNetworkResource request is made from the frontend. + * async function setNetworkResources() { + * const mapUrl = 'http://localhost:3000/dist/app.js.map'; + * const tsUrl = 'http://localhost:3000/src/app.ts'; + * const distAppJsMap = await fetch(mapUrl).then((res) => res.text()); + * const srcAppTs = await fetch(tsUrl).then((res) => res.text()); + * inspector.NetworkResources.put(mapUrl, distAppJsMap); + * inspector.NetworkResources.put(tsUrl, srcAppTs); + * }; + * setNetworkResources().then(() => { + * require('./dist/app'); + * }); + * ``` + * + * For more details, see the official CDP documentation: [Network.loadNetworkResource](https://chromedevtools.github.io/devtools-protocol/tot/Network/#method-loadNetworkResource) + * @since v22.19.0 + * @experimental + */ + function put(url: string, data: string): void; + } +} + +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + */ +declare module "node:inspector" { + export * from "inspector"; +} + +/** + * The `node:inspector/promises` module provides an API for interacting with the V8 + * inspector. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/inspector/promises.js) + * @since v19.0.0 + */ +declare module "inspector/promises" { + import EventEmitter = require("node:events"); + export { close, console, NetworkResources, open, url, waitForDebugger } from "inspector"; + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + * @since v19.0.0 + */ + export class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend. + */ + constructor(); + /** + * Connects a session to the inspector back-end. + */ + connect(): void; + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + * @since v12.11.0 + */ + connectToMainThread(): void; + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * `session.connect()` will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + } +} + +/** + * The `node:inspector/promises` module provides an API for interacting with the V8 + * inspector. + * @since v19.0.0 + */ +declare module "node:inspector/promises" { + export * from "inspector/promises"; +} diff --git a/node_modules/@types/node/inspector.generated.d.ts b/node_modules/@types/node/inspector.generated.d.ts new file mode 100644 index 0000000..bcf0b3b --- /dev/null +++ b/node_modules/@types/node/inspector.generated.d.ts @@ -0,0 +1,4052 @@ +// These definitions are automatically generated by the generate-inspector script. +// Do not edit this file directly. +// See scripts/generate-inspector/README.md for information on how to update the protocol definitions. +// Changes to the module itself should be added to the generator template (scripts/generate-inspector/inspector.d.ts.template). + +declare module "inspector" { + interface InspectorNotification { + method: string; + params: T; + } + + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string | undefined; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview | undefined; + /** + * @experimental + */ + customPreview?: CustomPreview | undefined; + } + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId | undefined; + } + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[] | undefined; + } + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + } + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean | undefined; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | undefined; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject | undefined; + } + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + } + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + } + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: object | undefined; + } + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId | undefined; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string | undefined; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace | undefined; + /** + * Exception object if available. + */ + exception?: RemoteObject | undefined; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId | undefined; + } + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string | undefined; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace | undefined; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId | undefined; + } + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId | undefined; + } + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + } + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId | undefined; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string | undefined; + } + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean | undefined; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean | undefined; + } + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace | undefined; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string | undefined; + } + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: object; + } + } + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + /** + * Call frame identifier. + */ + type CallFrameId = string; + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + } + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location | undefined; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject | undefined; + } + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string | undefined; + /** + * Location in the source code where scope starts + */ + startLocation?: Location | undefined; + /** + * Location in the source code where scope ends + */ + endLocation?: Location | undefined; + } + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + type?: string | undefined; + } + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string | undefined; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string | undefined; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location | undefined; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean | undefined; + } + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string | undefined; + } + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean | undefined; + } + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean | undefined; + } + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean | undefined; + } + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean | undefined; + } + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[] | undefined; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + } + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: object | undefined; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: object | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: object | undefined; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[] | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId | undefined; + } + } + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number | undefined; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number | undefined; + } + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number | undefined; + /** + * Child node ids. + */ + children?: number[] | undefined; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string | undefined; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[] | undefined; + } + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[] | undefined; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[] | undefined; + } + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean | undefined; + /** + * Collect block-based coverage. + */ + detailed?: boolean | undefined; + } + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + } + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean | undefined; + } + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean | undefined; + } + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean | undefined; + } + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + } + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number | undefined; + } + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean | undefined; + } + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string | undefined; + /** + * Included category filters. + */ + includedCategories: string[]; + } + interface StartParameterType { + traceConfig: TraceConfig; + } + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + interface DataCollectedEventDataType { + value: object[]; + } + } + namespace NodeWorker { + type WorkerID = string; + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + interface DetachParameterType { + sessionId: SessionID; + } + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + namespace Network { + /** + * Resource type as it was perceived by the rendering engine. + */ + type ResourceType = string; + /** + * Unique request identifier. + */ + type RequestId = string; + /** + * UTC time in seconds, counted from January 1, 1970. + */ + type TimeSinceEpoch = number; + /** + * Monotonically increasing time in seconds since an arbitrary point in the past. + */ + type MonotonicTime = number; + /** + * Information about the request initiator. + */ + interface Initiator { + /** + * Type of this initiator. + */ + type: string; + /** + * Initiator JavaScript stack trace, set for Script only. + * Requires the Debugger domain to be enabled. + */ + stack?: Runtime.StackTrace | undefined; + /** + * Initiator URL, set for Parser type or for Script type (when script is importing module) or for SignedExchange type. + */ + url?: string | undefined; + /** + * Initiator line number, set for Parser type or for Script type (when script is importing + * module) (0-based). + */ + lineNumber?: number | undefined; + /** + * Initiator column number, set for Parser type or for Script type (when script is importing + * module) (0-based). + */ + columnNumber?: number | undefined; + /** + * Set if another request triggered this request (e.g. preflight). + */ + requestId?: RequestId | undefined; + } + /** + * HTTP request data. + */ + interface Request { + url: string; + method: string; + headers: Headers; + hasPostData: boolean; + } + /** + * HTTP response data. + */ + interface Response { + url: string; + status: number; + statusText: string; + headers: Headers; + mimeType: string; + charset: string; + } + /** + * Request / response headers as keys / values of JSON object. + */ + interface Headers { + } + interface LoadNetworkResourcePageResult { + success: boolean; + stream?: IO.StreamHandle | undefined; + } + interface GetRequestPostDataParameterType { + /** + * Identifier of the network request to get content for. + */ + requestId: RequestId; + } + interface GetResponseBodyParameterType { + /** + * Identifier of the network request to get content for. + */ + requestId: RequestId; + } + interface StreamResourceContentParameterType { + /** + * Identifier of the request to stream. + */ + requestId: RequestId; + } + interface LoadNetworkResourceParameterType { + /** + * URL of the resource to get content for. + */ + url: string; + } + interface GetRequestPostDataReturnType { + /** + * Request body string, omitting files from multipart requests + */ + postData: string; + } + interface GetResponseBodyReturnType { + /** + * Response body. + */ + body: string; + /** + * True, if content was sent as base64. + */ + base64Encoded: boolean; + } + interface StreamResourceContentReturnType { + /** + * Data that has been buffered until streaming is enabled. + */ + bufferedData: string; + } + interface LoadNetworkResourceReturnType { + resource: LoadNetworkResourcePageResult; + } + interface RequestWillBeSentEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Request data. + */ + request: Request; + /** + * Request initiator. + */ + initiator: Initiator; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Timestamp. + */ + wallTime: TimeSinceEpoch; + } + interface ResponseReceivedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Resource type. + */ + type: ResourceType; + /** + * Response data. + */ + response: Response; + } + interface LoadingFailedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Resource type. + */ + type: ResourceType; + /** + * Error message. + */ + errorText: string; + } + interface LoadingFinishedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + } + interface DataReceivedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Data chunk length. + */ + dataLength: number; + /** + * Actual bytes received (might be less than dataLength for compressed encodings). + */ + encodedDataLength: number; + /** + * Data that was received. + * @experimental + */ + data?: string | undefined; + } + } + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + namespace Target { + type SessionID = string; + type TargetID = string; + interface TargetInfo { + targetId: TargetID; + type: string; + title: string; + url: string; + attached: boolean; + canAccessOpener: boolean; + } + interface SetAutoAttachParameterType { + autoAttach: boolean; + waitForDebuggerOnStart: boolean; + } + interface TargetCreatedEventDataType { + targetInfo: TargetInfo; + } + interface AttachedToTargetEventDataType { + sessionId: SessionID; + targetInfo: TargetInfo; + waitingForDebugger: boolean; + } + } + namespace IO { + type StreamHandle = string; + interface ReadParameterType { + /** + * Handle of the stream to read. + */ + handle: StreamHandle; + /** + * Seek to the specified offset before reading (if not specified, proceed with offset + * following the last read). Some types of streams may only support sequential reads. + */ + offset?: number | undefined; + /** + * Maximum number of bytes to read (left upon the agent discretion if not specified). + */ + size?: number | undefined; + } + interface CloseParameterType { + /** + * Handle of the stream to close. + */ + handle: StreamHandle; + } + interface ReadReturnType { + /** + * Data that were read. + */ + data: string; + /** + * Set if the end-of-file condition occurred while reading. + */ + eof: boolean; + } + } + + interface Session { + /** + * Posts a message to the inspector back-end. `callback` will be notified when + * a response is received. `callback` is a function that accepts two optional + * arguments: error and message-specific result. + * + * ```js + * session.post('Runtime.evaluate', { expression: '2 + 2' }, + * (error, { result }) => console.log(result)); + * // Output: { type: 'number', value: 4, description: '4' } + * ``` + * + * The latest version of the V8 inspector protocol is published on the + * [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + */ + post(method: string, callback?: (err: Error | null, params?: object) => void): void; + post(method: string, params?: object, callback?: (err: Error | null, params?: object) => void): void; + /** + * Returns supported domains. + */ + post(method: "Schema.getDomains", callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Evaluates expression on global object. + */ + post(method: "Runtime.evaluate", params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: "Runtime.evaluate", callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post(method: "Runtime.awaitPromise", params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: "Runtime.awaitPromise", callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.callFunctionOn", params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: "Runtime.callFunctionOn", callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.getProperties", params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: "Runtime.getProperties", callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + /** + * Releases remote object with given id. + */ + post(method: "Runtime.releaseObject", params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObject", callback?: (err: Error | null) => void): void; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: "Runtime.releaseObjectGroup", params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObjectGroup", callback?: (err: Error | null) => void): void; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: "Runtime.runIfWaitingForDebugger", callback?: (err: Error | null) => void): void; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: "Runtime.enable", callback?: (err: Error | null) => void): void; + /** + * Disables reporting of execution contexts creation. + */ + post(method: "Runtime.disable", callback?: (err: Error | null) => void): void; + /** + * Discards collected exceptions and console API calls. + */ + post(method: "Runtime.discardConsoleEntries", callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: "Runtime.setCustomObjectFormatterEnabled", params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.setCustomObjectFormatterEnabled", callback?: (err: Error | null) => void): void; + /** + * Compiles expression. + */ + post(method: "Runtime.compileScript", params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: "Runtime.compileScript", callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + /** + * Runs script with given id in a given context. + */ + post(method: "Runtime.runScript", params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: "Runtime.runScript", callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: "Runtime.queryObjects", params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: "Runtime.queryObjects", callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: "Runtime.globalLexicalScopeNames", + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: "Runtime.globalLexicalScopeNames", callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: "Debugger.enable", callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + /** + * Disables debugger for given page. + */ + post(method: "Debugger.disable", callback?: (err: Error | null) => void): void; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: "Debugger.setBreakpointsActive", params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBreakpointsActive", callback?: (err: Error | null) => void): void; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: "Debugger.setSkipAllPauses", params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setSkipAllPauses", callback?: (err: Error | null) => void): void; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: "Debugger.setBreakpointByUrl", params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: "Debugger.setBreakpointByUrl", callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: "Debugger.setBreakpoint", params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: "Debugger.setBreakpoint", callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + /** + * Removes JavaScript breakpoint. + */ + post(method: "Debugger.removeBreakpoint", params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.removeBreakpoint", callback?: (err: Error | null) => void): void; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: "Debugger.getPossibleBreakpoints", + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: "Debugger.getPossibleBreakpoints", callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + /** + * Continues execution until specific location is reached. + */ + post(method: "Debugger.continueToLocation", params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.continueToLocation", callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: "Debugger.pauseOnAsyncCall", params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.pauseOnAsyncCall", callback?: (err: Error | null) => void): void; + /** + * Steps over the statement. + */ + post(method: "Debugger.stepOver", callback?: (err: Error | null) => void): void; + /** + * Steps into the function call. + */ + post(method: "Debugger.stepInto", params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.stepInto", callback?: (err: Error | null) => void): void; + /** + * Steps out of the function call. + */ + post(method: "Debugger.stepOut", callback?: (err: Error | null) => void): void; + /** + * Stops on the next JavaScript statement. + */ + post(method: "Debugger.pause", callback?: (err: Error | null) => void): void; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: "Debugger.scheduleStepIntoAsync", callback?: (err: Error | null) => void): void; + /** + * Resumes JavaScript execution. + */ + post(method: "Debugger.resume", callback?: (err: Error | null) => void): void; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: "Debugger.getStackTrace", params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: "Debugger.getStackTrace", callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + /** + * Searches for given string in script content. + */ + post(method: "Debugger.searchInContent", params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: "Debugger.searchInContent", callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + /** + * Edits JavaScript source live. + */ + post(method: "Debugger.setScriptSource", params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: "Debugger.setScriptSource", callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + /** + * Restarts particular call frame from the beginning. + */ + post(method: "Debugger.restartFrame", params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: "Debugger.restartFrame", callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + /** + * Returns source for the script with given id. + */ + post(method: "Debugger.getScriptSource", params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: "Debugger.getScriptSource", callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: "Debugger.setPauseOnExceptions", params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setPauseOnExceptions", callback?: (err: Error | null) => void): void; + /** + * Evaluates expression on a given call frame. + */ + post(method: "Debugger.evaluateOnCallFrame", params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: "Debugger.evaluateOnCallFrame", callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: "Debugger.setVariableValue", params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setVariableValue", callback?: (err: Error | null) => void): void; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: "Debugger.setReturnValue", params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setReturnValue", callback?: (err: Error | null) => void): void; + /** + * Enables or disables async call stacks tracking. + */ + post(method: "Debugger.setAsyncCallStackDepth", params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setAsyncCallStackDepth", callback?: (err: Error | null) => void): void; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: "Debugger.setBlackboxPatterns", params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxPatterns", callback?: (err: Error | null) => void): void; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: "Debugger.setBlackboxedRanges", params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxedRanges", callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: "Console.enable", callback?: (err: Error | null) => void): void; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: "Console.disable", callback?: (err: Error | null) => void): void; + /** + * Does nothing. + */ + post(method: "Console.clearMessages", callback?: (err: Error | null) => void): void; + post(method: "Profiler.enable", callback?: (err: Error | null) => void): void; + post(method: "Profiler.disable", callback?: (err: Error | null) => void): void; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: "Profiler.setSamplingInterval", params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.setSamplingInterval", callback?: (err: Error | null) => void): void; + post(method: "Profiler.start", callback?: (err: Error | null) => void): void; + post(method: "Profiler.stop", callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: "Profiler.startPreciseCoverage", params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.startPreciseCoverage", callback?: (err: Error | null) => void): void; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: "Profiler.stopPreciseCoverage", callback?: (err: Error | null) => void): void; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: "Profiler.takePreciseCoverage", callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: "Profiler.getBestEffortCoverage", callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + post(method: "HeapProfiler.enable", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.disable", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startTrackingHeapObjects", params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startTrackingHeapObjects", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopTrackingHeapObjects", params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopTrackingHeapObjects", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.takeHeapSnapshot", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.collectGarbage", callback?: (err: Error | null) => void): void; + post( + method: "HeapProfiler.getObjectByHeapObjectId", + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: "HeapProfiler.getObjectByHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: "HeapProfiler.addInspectedHeapObject", params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.addInspectedHeapObject", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.getHeapObjectId", params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: "HeapProfiler.getHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: "HeapProfiler.startSampling", params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startSampling", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopSampling", callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + post(method: "HeapProfiler.getSamplingProfile", callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: "NodeTracing.getCategories", callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + /** + * Start trace events collection. + */ + post(method: "NodeTracing.start", params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeTracing.start", callback?: (err: Error | null) => void): void; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: "NodeTracing.stop", callback?: (err: Error | null) => void): void; + /** + * Sends protocol message over session with given id. + */ + post(method: "NodeWorker.sendMessageToWorker", params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.sendMessageToWorker", callback?: (err: Error | null) => void): void; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: "NodeWorker.enable", params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.enable", callback?: (err: Error | null) => void): void; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: "NodeWorker.disable", callback?: (err: Error | null) => void): void; + /** + * Detached from the worker with given sessionId. + */ + post(method: "NodeWorker.detach", params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.detach", callback?: (err: Error | null) => void): void; + /** + * Disables network tracking, prevents network events from being sent to the client. + */ + post(method: "Network.disable", callback?: (err: Error | null) => void): void; + /** + * Enables network tracking, network events will now be delivered to the client. + */ + post(method: "Network.enable", callback?: (err: Error | null) => void): void; + /** + * Returns post data sent with the request. Returns an error when no data was sent with the request. + */ + post(method: "Network.getRequestPostData", params?: Network.GetRequestPostDataParameterType, callback?: (err: Error | null, params: Network.GetRequestPostDataReturnType) => void): void; + post(method: "Network.getRequestPostData", callback?: (err: Error | null, params: Network.GetRequestPostDataReturnType) => void): void; + /** + * Returns content served for the given request. + */ + post(method: "Network.getResponseBody", params?: Network.GetResponseBodyParameterType, callback?: (err: Error | null, params: Network.GetResponseBodyReturnType) => void): void; + post(method: "Network.getResponseBody", callback?: (err: Error | null, params: Network.GetResponseBodyReturnType) => void): void; + /** + * Enables streaming of the response for the given requestId. + * If enabled, the dataReceived event contains the data that was received during streaming. + * @experimental + */ + post( + method: "Network.streamResourceContent", + params?: Network.StreamResourceContentParameterType, + callback?: (err: Error | null, params: Network.StreamResourceContentReturnType) => void + ): void; + post(method: "Network.streamResourceContent", callback?: (err: Error | null, params: Network.StreamResourceContentReturnType) => void): void; + /** + * Fetches the resource and returns the content. + */ + post(method: "Network.loadNetworkResource", params?: Network.LoadNetworkResourceParameterType, callback?: (err: Error | null, params: Network.LoadNetworkResourceReturnType) => void): void; + post(method: "Network.loadNetworkResource", callback?: (err: Error | null, params: Network.LoadNetworkResourceReturnType) => void): void; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.enable", callback?: (err: Error | null) => void): void; + /** + * Disable NodeRuntime events + */ + post(method: "NodeRuntime.disable", callback?: (err: Error | null) => void): void; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.notifyWhenWaitingForDisconnect", params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeRuntime.notifyWhenWaitingForDisconnect", callback?: (err: Error | null) => void): void; + post(method: "Target.setAutoAttach", params?: Target.SetAutoAttachParameterType, callback?: (err: Error | null) => void): void; + post(method: "Target.setAutoAttach", callback?: (err: Error | null) => void): void; + /** + * Read a chunk of the stream + */ + post(method: "IO.read", params?: IO.ReadParameterType, callback?: (err: Error | null, params: IO.ReadReturnType) => void): void; + post(method: "IO.read", callback?: (err: Error | null, params: IO.ReadReturnType) => void): void; + post(method: "IO.close", params?: IO.CloseParameterType, callback?: (err: Error | null) => void): void; + post(method: "IO.close", callback?: (err: Error | null) => void): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + addListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + addListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + addListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + addListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + addListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + addListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + addListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + addListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + addListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "inspectorNotification", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextCreated", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextsCleared"): boolean; + emit(event: "Runtime.exceptionThrown", message: InspectorNotification): boolean; + emit(event: "Runtime.exceptionRevoked", message: InspectorNotification): boolean; + emit(event: "Runtime.consoleAPICalled", message: InspectorNotification): boolean; + emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptParsed", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptFailedToParse", message: InspectorNotification): boolean; + emit(event: "Debugger.breakpointResolved", message: InspectorNotification): boolean; + emit(event: "Debugger.paused", message: InspectorNotification): boolean; + emit(event: "Debugger.resumed"): boolean; + emit(event: "Console.messageAdded", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileStarted", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileFinished", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.addHeapSnapshotChunk", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.resetProfiles"): boolean; + emit(event: "HeapProfiler.reportHeapSnapshotProgress", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.lastSeenObjectId", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.heapStatsUpdate", message: InspectorNotification): boolean; + emit(event: "NodeTracing.dataCollected", message: InspectorNotification): boolean; + emit(event: "NodeTracing.tracingComplete"): boolean; + emit(event: "NodeWorker.attachedToWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.detachedFromWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification): boolean; + emit(event: "Network.requestWillBeSent", message: InspectorNotification): boolean; + emit(event: "Network.responseReceived", message: InspectorNotification): boolean; + emit(event: "Network.loadingFailed", message: InspectorNotification): boolean; + emit(event: "Network.loadingFinished", message: InspectorNotification): boolean; + emit(event: "Network.dataReceived", message: InspectorNotification): boolean; + emit(event: "NodeRuntime.waitingForDisconnect"): boolean; + emit(event: "NodeRuntime.waitingForDebugger"): boolean; + emit(event: "Target.targetCreated", message: InspectorNotification): boolean; + emit(event: "Target.attachedToTarget", message: InspectorNotification): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + on(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.resetProfiles", listener: () => void): this; + on(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + on(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + on(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + on(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + on(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + on(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + on(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + on(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + once(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.resetProfiles", listener: () => void): this; + once(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + once(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + once(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + once(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + once(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + once(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + once(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + once(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + prependListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependOnceListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependOnceListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependOnceListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependOnceListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + prependOnceListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + } +} + +declare module "inspector/promises" { + export { + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + NodeTracing, + NodeWorker, + Network, + NodeRuntime, + Target, + IO, + } from 'inspector'; +} + +declare module "inspector/promises" { + import { + InspectorNotification, + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + NodeTracing, + NodeWorker, + Network, + NodeRuntime, + Target, + IO, + } from "inspector"; + + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + * @since v19.0.0 + */ + interface Session { + /** + * Posts a message to the inspector back-end. + * + * ```js + * import { Session } from 'node:inspector/promises'; + * try { + * const session = new Session(); + * session.connect(); + * const result = await session.post('Runtime.evaluate', { expression: '2 + 2' }); + * console.log(result); + * } catch (error) { + * console.error(error); + * } + * // Output: { result: { type: 'number', value: 4, description: '4' } } + * ``` + * + * The latest version of the V8 inspector protocol is published on the + * [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + */ + post(method: string, params?: object): Promise; + /** + * Returns supported domains. + */ + post(method: "Schema.getDomains"): Promise; + /** + * Evaluates expression on global object. + */ + post(method: "Runtime.evaluate", params?: Runtime.EvaluateParameterType): Promise; + /** + * Add handler to promise with given promise object id. + */ + post(method: "Runtime.awaitPromise", params?: Runtime.AwaitPromiseParameterType): Promise; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.callFunctionOn", params?: Runtime.CallFunctionOnParameterType): Promise; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.getProperties", params?: Runtime.GetPropertiesParameterType): Promise; + /** + * Releases remote object with given id. + */ + post(method: "Runtime.releaseObject", params?: Runtime.ReleaseObjectParameterType): Promise; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: "Runtime.releaseObjectGroup", params?: Runtime.ReleaseObjectGroupParameterType): Promise; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: "Runtime.runIfWaitingForDebugger"): Promise; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: "Runtime.enable"): Promise; + /** + * Disables reporting of execution contexts creation. + */ + post(method: "Runtime.disable"): Promise; + /** + * Discards collected exceptions and console API calls. + */ + post(method: "Runtime.discardConsoleEntries"): Promise; + /** + * @experimental + */ + post(method: "Runtime.setCustomObjectFormatterEnabled", params?: Runtime.SetCustomObjectFormatterEnabledParameterType): Promise; + /** + * Compiles expression. + */ + post(method: "Runtime.compileScript", params?: Runtime.CompileScriptParameterType): Promise; + /** + * Runs script with given id in a given context. + */ + post(method: "Runtime.runScript", params?: Runtime.RunScriptParameterType): Promise; + post(method: "Runtime.queryObjects", params?: Runtime.QueryObjectsParameterType): Promise; + /** + * Returns all let, const and class variables from global scope. + */ + post(method: "Runtime.globalLexicalScopeNames", params?: Runtime.GlobalLexicalScopeNamesParameterType): Promise; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: "Debugger.enable"): Promise; + /** + * Disables debugger for given page. + */ + post(method: "Debugger.disable"): Promise; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: "Debugger.setBreakpointsActive", params?: Debugger.SetBreakpointsActiveParameterType): Promise; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: "Debugger.setSkipAllPauses", params?: Debugger.SetSkipAllPausesParameterType): Promise; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: "Debugger.setBreakpointByUrl", params?: Debugger.SetBreakpointByUrlParameterType): Promise; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: "Debugger.setBreakpoint", params?: Debugger.SetBreakpointParameterType): Promise; + /** + * Removes JavaScript breakpoint. + */ + post(method: "Debugger.removeBreakpoint", params?: Debugger.RemoveBreakpointParameterType): Promise; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post(method: "Debugger.getPossibleBreakpoints", params?: Debugger.GetPossibleBreakpointsParameterType): Promise; + /** + * Continues execution until specific location is reached. + */ + post(method: "Debugger.continueToLocation", params?: Debugger.ContinueToLocationParameterType): Promise; + /** + * @experimental + */ + post(method: "Debugger.pauseOnAsyncCall", params?: Debugger.PauseOnAsyncCallParameterType): Promise; + /** + * Steps over the statement. + */ + post(method: "Debugger.stepOver"): Promise; + /** + * Steps into the function call. + */ + post(method: "Debugger.stepInto", params?: Debugger.StepIntoParameterType): Promise; + /** + * Steps out of the function call. + */ + post(method: "Debugger.stepOut"): Promise; + /** + * Stops on the next JavaScript statement. + */ + post(method: "Debugger.pause"): Promise; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: "Debugger.scheduleStepIntoAsync"): Promise; + /** + * Resumes JavaScript execution. + */ + post(method: "Debugger.resume"): Promise; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: "Debugger.getStackTrace", params?: Debugger.GetStackTraceParameterType): Promise; + /** + * Searches for given string in script content. + */ + post(method: "Debugger.searchInContent", params?: Debugger.SearchInContentParameterType): Promise; + /** + * Edits JavaScript source live. + */ + post(method: "Debugger.setScriptSource", params?: Debugger.SetScriptSourceParameterType): Promise; + /** + * Restarts particular call frame from the beginning. + */ + post(method: "Debugger.restartFrame", params?: Debugger.RestartFrameParameterType): Promise; + /** + * Returns source for the script with given id. + */ + post(method: "Debugger.getScriptSource", params?: Debugger.GetScriptSourceParameterType): Promise; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: "Debugger.setPauseOnExceptions", params?: Debugger.SetPauseOnExceptionsParameterType): Promise; + /** + * Evaluates expression on a given call frame. + */ + post(method: "Debugger.evaluateOnCallFrame", params?: Debugger.EvaluateOnCallFrameParameterType): Promise; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: "Debugger.setVariableValue", params?: Debugger.SetVariableValueParameterType): Promise; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: "Debugger.setReturnValue", params?: Debugger.SetReturnValueParameterType): Promise; + /** + * Enables or disables async call stacks tracking. + */ + post(method: "Debugger.setAsyncCallStackDepth", params?: Debugger.SetAsyncCallStackDepthParameterType): Promise; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: "Debugger.setBlackboxPatterns", params?: Debugger.SetBlackboxPatternsParameterType): Promise; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: "Debugger.setBlackboxedRanges", params?: Debugger.SetBlackboxedRangesParameterType): Promise; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: "Console.enable"): Promise; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: "Console.disable"): Promise; + /** + * Does nothing. + */ + post(method: "Console.clearMessages"): Promise; + post(method: "Profiler.enable"): Promise; + post(method: "Profiler.disable"): Promise; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: "Profiler.setSamplingInterval", params?: Profiler.SetSamplingIntervalParameterType): Promise; + post(method: "Profiler.start"): Promise; + post(method: "Profiler.stop"): Promise; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: "Profiler.startPreciseCoverage", params?: Profiler.StartPreciseCoverageParameterType): Promise; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: "Profiler.stopPreciseCoverage"): Promise; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: "Profiler.takePreciseCoverage"): Promise; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: "Profiler.getBestEffortCoverage"): Promise; + post(method: "HeapProfiler.enable"): Promise; + post(method: "HeapProfiler.disable"): Promise; + post(method: "HeapProfiler.startTrackingHeapObjects", params?: HeapProfiler.StartTrackingHeapObjectsParameterType): Promise; + post(method: "HeapProfiler.stopTrackingHeapObjects", params?: HeapProfiler.StopTrackingHeapObjectsParameterType): Promise; + post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType): Promise; + post(method: "HeapProfiler.collectGarbage"): Promise; + post(method: "HeapProfiler.getObjectByHeapObjectId", params?: HeapProfiler.GetObjectByHeapObjectIdParameterType): Promise; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: "HeapProfiler.addInspectedHeapObject", params?: HeapProfiler.AddInspectedHeapObjectParameterType): Promise; + post(method: "HeapProfiler.getHeapObjectId", params?: HeapProfiler.GetHeapObjectIdParameterType): Promise; + post(method: "HeapProfiler.startSampling", params?: HeapProfiler.StartSamplingParameterType): Promise; + post(method: "HeapProfiler.stopSampling"): Promise; + post(method: "HeapProfiler.getSamplingProfile"): Promise; + /** + * Gets supported tracing categories. + */ + post(method: "NodeTracing.getCategories"): Promise; + /** + * Start trace events collection. + */ + post(method: "NodeTracing.start", params?: NodeTracing.StartParameterType): Promise; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: "NodeTracing.stop"): Promise; + /** + * Sends protocol message over session with given id. + */ + post(method: "NodeWorker.sendMessageToWorker", params?: NodeWorker.SendMessageToWorkerParameterType): Promise; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: "NodeWorker.enable", params?: NodeWorker.EnableParameterType): Promise; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: "NodeWorker.disable"): Promise; + /** + * Detached from the worker with given sessionId. + */ + post(method: "NodeWorker.detach", params?: NodeWorker.DetachParameterType): Promise; + /** + * Disables network tracking, prevents network events from being sent to the client. + */ + post(method: "Network.disable"): Promise; + /** + * Enables network tracking, network events will now be delivered to the client. + */ + post(method: "Network.enable"): Promise; + /** + * Returns post data sent with the request. Returns an error when no data was sent with the request. + */ + post(method: "Network.getRequestPostData", params?: Network.GetRequestPostDataParameterType): Promise; + /** + * Returns content served for the given request. + */ + post(method: "Network.getResponseBody", params?: Network.GetResponseBodyParameterType): Promise; + /** + * Enables streaming of the response for the given requestId. + * If enabled, the dataReceived event contains the data that was received during streaming. + * @experimental + */ + post(method: "Network.streamResourceContent", params?: Network.StreamResourceContentParameterType): Promise; + /** + * Fetches the resource and returns the content. + */ + post(method: "Network.loadNetworkResource", params?: Network.LoadNetworkResourceParameterType): Promise; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.enable"): Promise; + /** + * Disable NodeRuntime events + */ + post(method: "NodeRuntime.disable"): Promise; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.notifyWhenWaitingForDisconnect", params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType): Promise; + post(method: "Target.setAutoAttach", params?: Target.SetAutoAttachParameterType): Promise; + /** + * Read a chunk of the stream + */ + post(method: "IO.read", params?: IO.ReadParameterType): Promise; + post(method: "IO.close", params?: IO.CloseParameterType): Promise; + + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + addListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + addListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + addListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + addListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + addListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + addListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + addListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + addListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + addListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "inspectorNotification", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextCreated", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextsCleared"): boolean; + emit(event: "Runtime.exceptionThrown", message: InspectorNotification): boolean; + emit(event: "Runtime.exceptionRevoked", message: InspectorNotification): boolean; + emit(event: "Runtime.consoleAPICalled", message: InspectorNotification): boolean; + emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptParsed", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptFailedToParse", message: InspectorNotification): boolean; + emit(event: "Debugger.breakpointResolved", message: InspectorNotification): boolean; + emit(event: "Debugger.paused", message: InspectorNotification): boolean; + emit(event: "Debugger.resumed"): boolean; + emit(event: "Console.messageAdded", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileStarted", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileFinished", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.addHeapSnapshotChunk", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.resetProfiles"): boolean; + emit(event: "HeapProfiler.reportHeapSnapshotProgress", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.lastSeenObjectId", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.heapStatsUpdate", message: InspectorNotification): boolean; + emit(event: "NodeTracing.dataCollected", message: InspectorNotification): boolean; + emit(event: "NodeTracing.tracingComplete"): boolean; + emit(event: "NodeWorker.attachedToWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.detachedFromWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification): boolean; + emit(event: "Network.requestWillBeSent", message: InspectorNotification): boolean; + emit(event: "Network.responseReceived", message: InspectorNotification): boolean; + emit(event: "Network.loadingFailed", message: InspectorNotification): boolean; + emit(event: "Network.loadingFinished", message: InspectorNotification): boolean; + emit(event: "Network.dataReceived", message: InspectorNotification): boolean; + emit(event: "NodeRuntime.waitingForDisconnect"): boolean; + emit(event: "NodeRuntime.waitingForDebugger"): boolean; + emit(event: "Target.targetCreated", message: InspectorNotification): boolean; + emit(event: "Target.attachedToTarget", message: InspectorNotification): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + on(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.resetProfiles", listener: () => void): this; + on(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + on(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + on(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + on(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + on(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + on(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + on(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + on(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + once(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.resetProfiles", listener: () => void): this; + once(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + once(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + once(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + once(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + once(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + once(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + once(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + once(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + prependListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependOnceListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependOnceListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependOnceListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependOnceListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + prependOnceListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + } +} diff --git a/node_modules/@types/node/module.d.ts b/node_modules/@types/node/module.d.ts new file mode 100644 index 0000000..b48948e --- /dev/null +++ b/node_modules/@types/node/module.d.ts @@ -0,0 +1,891 @@ +/** + * @since v0.3.7 + */ +declare module "module" { + import { URL } from "node:url"; + class Module { + constructor(id: string, parent?: Module); + } + interface Module extends NodeJS.Module {} + namespace Module { + export { Module }; + } + namespace Module { + /** + * A list of the names of all modules provided by Node.js. Can be used to verify + * if a module is maintained by a third party or not. + * + * Note: the list doesn't contain prefix-only modules like `node:test`. + * @since v9.3.0, v8.10.0, v6.13.0 + */ + const builtinModules: readonly string[]; + /** + * @since v12.2.0 + * @param path Filename to be used to construct the require + * function. Must be a file URL object, file URL string, or absolute path + * string. + */ + function createRequire(path: string | URL): NodeJS.Require; + namespace constants { + /** + * The following constants are returned as the `status` field in the object returned by + * {@link enableCompileCache} to indicate the result of the attempt to enable the + * [module compile cache](https://nodejs.org/docs/latest-v22.x/api/module.html#module-compile-cache). + * @since v22.8.0 + */ + namespace compileCacheStatus { + /** + * Node.js has enabled the compile cache successfully. The directory used to store the + * compile cache will be returned in the `directory` field in the + * returned object. + */ + const ENABLED: number; + /** + * The compile cache has already been enabled before, either by a previous call to + * {@link enableCompileCache}, or by the `NODE_COMPILE_CACHE=dir` + * environment variable. The directory used to store the + * compile cache will be returned in the `directory` field in the + * returned object. + */ + const ALREADY_ENABLED: number; + /** + * Node.js fails to enable the compile cache. This can be caused by the lack of + * permission to use the specified directory, or various kinds of file system errors. + * The detail of the failure will be returned in the `message` field in the + * returned object. + */ + const FAILED: number; + /** + * Node.js cannot enable the compile cache because the environment variable + * `NODE_DISABLE_COMPILE_CACHE=1` has been set. + */ + const DISABLED: number; + } + } + interface EnableCompileCacheResult { + /** + * One of the {@link constants.compileCacheStatus} + */ + status: number; + /** + * If Node.js cannot enable the compile cache, this contains + * the error message. Only set if `status` is `module.constants.compileCacheStatus.FAILED`. + */ + message?: string; + /** + * If the compile cache is enabled, this contains the directory + * where the compile cache is stored. Only set if `status` is + * `module.constants.compileCacheStatus.ENABLED` or + * `module.constants.compileCacheStatus.ALREADY_ENABLED`. + */ + directory?: string; + } + /** + * Enable [module compile cache](https://nodejs.org/docs/latest-v22.x/api/module.html#module-compile-cache) + * in the current Node.js instance. + * + * If `cacheDir` is not specified, Node.js will either use the directory specified by the + * `NODE_COMPILE_CACHE=dir` environment variable if it's set, or use + * `path.join(os.tmpdir(), 'node-compile-cache')` otherwise. For general use cases, it's + * recommended to call `module.enableCompileCache()` without specifying the `cacheDir`, + * so that the directory can be overridden by the `NODE_COMPILE_CACHE` environment + * variable when necessary. + * + * Since compile cache is supposed to be a quiet optimization that is not required for the + * application to be functional, this method is designed to not throw any exception when the + * compile cache cannot be enabled. Instead, it will return an object containing an error + * message in the `message` field to aid debugging. + * If compile cache is enabled successfully, the `directory` field in the returned object + * contains the path to the directory where the compile cache is stored. The `status` + * field in the returned object would be one of the `module.constants.compileCacheStatus` + * values to indicate the result of the attempt to enable the + * [module compile cache](https://nodejs.org/docs/latest-v22.x/api/module.html#module-compile-cache). + * + * This method only affects the current Node.js instance. To enable it in child worker threads, + * either call this method in child worker threads too, or set the + * `process.env.NODE_COMPILE_CACHE` value to compile cache directory so the behavior can + * be inherited into the child workers. The directory can be obtained either from the + * `directory` field returned by this method, or with {@link getCompileCacheDir}. + * @since v22.8.0 + * @param cacheDir Optional path to specify the directory where the compile cache + * will be stored/retrieved. + */ + function enableCompileCache(cacheDir?: string): EnableCompileCacheResult; + /** + * Flush the [module compile cache](https://nodejs.org/docs/latest-v22.x/api/module.html#module-compile-cache) + * accumulated from modules already loaded + * in the current Node.js instance to disk. This returns after all the flushing + * file system operations come to an end, no matter they succeed or not. If there + * are any errors, this will fail silently, since compile cache misses should not + * interfere with the actual operation of the application. + * @since v22.10.0 + */ + function flushCompileCache(): void; + /** + * @since v22.8.0 + * @return Path to the [module compile cache](https://nodejs.org/docs/latest-v22.x/api/module.html#module-compile-cache) + * directory if it is enabled, or `undefined` otherwise. + */ + function getCompileCacheDir(): string | undefined; + /** + * ```text + * /path/to/project + * ├ packages/ + * ├ bar/ + * ├ bar.js + * └ package.json // name = '@foo/bar' + * └ qux/ + * ├ node_modules/ + * └ some-package/ + * └ package.json // name = 'some-package' + * ├ qux.js + * └ package.json // name = '@foo/qux' + * ├ main.js + * └ package.json // name = '@foo' + * ``` + * ```js + * // /path/to/project/packages/bar/bar.js + * import { findPackageJSON } from 'node:module'; + * + * findPackageJSON('..', import.meta.url); + * // '/path/to/project/package.json' + * // Same result when passing an absolute specifier instead: + * findPackageJSON(new URL('../', import.meta.url)); + * findPackageJSON(import.meta.resolve('../')); + * + * findPackageJSON('some-package', import.meta.url); + * // '/path/to/project/packages/bar/node_modules/some-package/package.json' + * // When passing an absolute specifier, you might get a different result if the + * // resolved module is inside a subfolder that has nested `package.json`. + * findPackageJSON(import.meta.resolve('some-package')); + * // '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json' + * + * findPackageJSON('@foo/qux', import.meta.url); + * // '/path/to/project/packages/qux/package.json' + * ``` + * @since v22.14.0 + * @param specifier The specifier for the module whose `package.json` to + * retrieve. When passing a _bare specifier_, the `package.json` at the root of + * the package is returned. When passing a _relative specifier_ or an _absolute specifier_, + * the closest parent `package.json` is returned. + * @param base The absolute location (`file:` URL string or FS path) of the + * containing module. For CJS, use `__filename` (not `__dirname`!); for ESM, use + * `import.meta.url`. You do not need to pass it if `specifier` is an _absolute specifier_. + * @returns A path if the `package.json` is found. When `startLocation` + * is a package, the package's root `package.json`; when a relative or unresolved, the closest + * `package.json` to the `startLocation`. + */ + function findPackageJSON(specifier: string | URL, base?: string | URL): string | undefined; + /** + * @since v18.6.0, v16.17.0 + */ + function isBuiltin(moduleName: string): boolean; + interface RegisterOptions { + /** + * If you want to resolve `specifier` relative to a + * base URL, such as `import.meta.url`, you can pass that URL here. This + * property is ignored if the `parentURL` is supplied as the second argument. + * @default 'data:' + */ + parentURL?: string | URL | undefined; + /** + * Any arbitrary, cloneable JavaScript value to pass into the + * {@link initialize} hook. + */ + data?: Data | undefined; + /** + * [Transferable objects](https://nodejs.org/docs/latest-v22.x/api/worker_threads.html#portpostmessagevalue-transferlist) + * to be passed into the `initialize` hook. + */ + transferList?: any[] | undefined; + } + /* eslint-disable @definitelytyped/no-unnecessary-generics */ + /** + * Register a module that exports hooks that customize Node.js module + * resolution and loading behavior. See + * [Customization hooks](https://nodejs.org/docs/latest-v22.x/api/module.html#customization-hooks). + * + * This feature requires `--allow-worker` if used with the + * [Permission Model](https://nodejs.org/docs/latest-v22.x/api/permissions.html#permission-model). + * @since v20.6.0, v18.19.0 + * @param specifier Customization hooks to be registered; this should be + * the same string that would be passed to `import()`, except that if it is + * relative, it is resolved relative to `parentURL`. + * @param parentURL f you want to resolve `specifier` relative to a base + * URL, such as `import.meta.url`, you can pass that URL here. + */ + function register( + specifier: string | URL, + parentURL?: string | URL, + options?: RegisterOptions, + ): void; + function register(specifier: string | URL, options?: RegisterOptions): void; + interface RegisterHooksOptions { + /** + * See [load hook](https://nodejs.org/docs/latest-v22.x/api/module.html#loadurl-context-nextload). + * @default undefined + */ + load?: LoadHookSync | undefined; + /** + * See [resolve hook](https://nodejs.org/docs/latest-v22.x/api/module.html#resolvespecifier-context-nextresolve). + * @default undefined + */ + resolve?: ResolveHookSync | undefined; + } + interface ModuleHooks { + /** + * Deregister the hook instance. + */ + deregister(): void; + } + /** + * Register [hooks](https://nodejs.org/docs/latest-v22.x/api/module.html#customization-hooks) + * that customize Node.js module resolution and loading behavior. + * @since v22.15.0 + * @experimental + */ + function registerHooks(options: RegisterHooksOptions): ModuleHooks; + interface StripTypeScriptTypesOptions { + /** + * Possible values are: + * * `'strip'` Only strip type annotations without performing the transformation of TypeScript features. + * * `'transform'` Strip type annotations and transform TypeScript features to JavaScript. + * @default 'strip' + */ + mode?: "strip" | "transform" | undefined; + /** + * Only when `mode` is `'transform'`, if `true`, a source map + * will be generated for the transformed code. + * @default false + */ + sourceMap?: boolean | undefined; + /** + * Specifies the source url used in the source map. + */ + sourceUrl?: string | undefined; + } + /** + * `module.stripTypeScriptTypes()` removes type annotations from TypeScript code. It + * can be used to strip type annotations from TypeScript code before running it + * with `vm.runInContext()` or `vm.compileFunction()`. + * By default, it will throw an error if the code contains TypeScript features + * that require transformation such as `Enums`, + * see [type-stripping](https://nodejs.org/docs/latest-v22.x/api/typescript.md#type-stripping) for more information. + * When mode is `'transform'`, it also transforms TypeScript features to JavaScript, + * see [transform TypeScript features](https://nodejs.org/docs/latest-v22.x/api/typescript.md#typescript-features) for more information. + * When mode is `'strip'`, source maps are not generated, because locations are preserved. + * If `sourceMap` is provided, when mode is `'strip'`, an error will be thrown. + * + * _WARNING_: The output of this function should not be considered stable across Node.js versions, + * due to changes in the TypeScript parser. + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = 'const a: number = 1;'; + * const strippedCode = stripTypeScriptTypes(code); + * console.log(strippedCode); + * // Prints: const a = 1; + * ``` + * + * If `sourceUrl` is provided, it will be used appended as a comment at the end of the output: + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = 'const a: number = 1;'; + * const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' }); + * console.log(strippedCode); + * // Prints: const a = 1\n\n//# sourceURL=source.ts; + * ``` + * + * When `mode` is `'transform'`, the code is transformed to JavaScript: + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = ` + * namespace MathUtil { + * export const add = (a: number, b: number) => a + b; + * }`; + * const strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true }); + * console.log(strippedCode); + * // Prints: + * // var MathUtil; + * // (function(MathUtil) { + * // MathUtil.add = (a, b)=>a + b; + * // })(MathUtil || (MathUtil = {})); + * // # sourceMappingURL=data:application/json;base64, ... + * ``` + * @since v22.13.0 + * @param code The code to strip type annotations from. + * @returns The code with type annotations stripped. + */ + function stripTypeScriptTypes(code: string, options?: StripTypeScriptTypesOptions): string; + /* eslint-enable @definitelytyped/no-unnecessary-generics */ + /** + * The `module.syncBuiltinESMExports()` method updates all the live bindings for + * builtin `ES Modules` to match the properties of the `CommonJS` exports. It + * does not add or remove exported names from the `ES Modules`. + * + * ```js + * import fs from 'node:fs'; + * import assert from 'node:assert'; + * import { syncBuiltinESMExports } from 'node:module'; + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('node:fs').then((esmFS) => { + * // It syncs the existing readFile property with the new value + * assert.strictEqual(esmFS.readFile, newAPI); + * // readFileSync has been deleted from the required fs + * assert.strictEqual('readFileSync' in fs, false); + * // syncBuiltinESMExports() does not remove readFileSync from esmFS + * assert.strictEqual('readFileSync' in esmFS, true); + * // syncBuiltinESMExports() does not add names + * assert.strictEqual(esmFS.newAPI, undefined); + * }); + * ``` + * @since v12.12.0 + */ + function syncBuiltinESMExports(): void; + interface ImportAttributes extends NodeJS.Dict { + type?: string | undefined; + } + type ModuleFormat = + | "builtin" + | "commonjs" + | "commonjs-typescript" + | "json" + | "module" + | "module-typescript" + | "wasm"; + type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray; + /** + * The `initialize` hook provides a way to define a custom function that runs in + * the hooks thread when the hooks module is initialized. Initialization happens + * when the hooks module is registered via {@link register}. + * + * This hook can receive data from a {@link register} invocation, including + * ports and other transferable objects. The return value of `initialize` can be a + * `Promise`, in which case it will be awaited before the main application thread + * execution resumes. + */ + type InitializeHook = (data: Data) => void | Promise; + interface ResolveHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + /** + * The module importing this one, or undefined if this is the Node.js entry point + */ + parentURL: string | undefined; + } + interface ResolveFnOutput { + /** + * A hint to the load hook (it might be ignored); can be an intermediary value. + */ + format?: string | null | undefined; + /** + * The import attributes to use when caching the module (optional; if excluded the input will be used) + */ + importAttributes?: ImportAttributes | undefined; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The absolute URL to which this input resolves + */ + url: string; + } + /** + * The `resolve` hook chain is responsible for telling Node.js where to find and + * how to cache a given `import` statement or expression, or `require` call. It can + * optionally return a format (such as `'module'`) as a hint to the `load` hook. If + * a format is specified, the `load` hook is ultimately responsible for providing + * the final `format` value (and it is free to ignore the hint provided by + * `resolve`); if `resolve` provides a `format`, a custom `load` hook is required + * even if only to pass the value to the Node.js default `load` hook. + */ + type ResolveHook = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: Partial, + ) => ResolveFnOutput | Promise, + ) => ResolveFnOutput | Promise; + type ResolveHookSync = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: Partial, + ) => ResolveFnOutput, + ) => ResolveFnOutput; + interface LoadHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * The format optionally supplied by the `resolve` hook chain (can be an intermediary value). + */ + format: string | null | undefined; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + } + interface LoadFnOutput { + format: string | null | undefined; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The source for Node.js to evaluate + */ + source?: ModuleSource | undefined; + } + /** + * The `load` hook provides a way to define a custom method of determining how a + * URL should be interpreted, retrieved, and parsed. It is also in charge of + * validating the import attributes. + */ + type LoadHook = ( + url: string, + context: LoadHookContext, + nextLoad: ( + url: string, + context?: Partial, + ) => LoadFnOutput | Promise, + ) => LoadFnOutput | Promise; + type LoadHookSync = ( + url: string, + context: LoadHookContext, + nextLoad: ( + url: string, + context?: Partial, + ) => LoadFnOutput, + ) => LoadFnOutput; + interface SourceMapsSupport { + /** + * If the source maps support is enabled + */ + enabled: boolean; + /** + * If the support is enabled for files in `node_modules`. + */ + nodeModules: boolean; + /** + * If the support is enabled for generated code from `eval` or `new Function`. + */ + generatedCode: boolean; + } + /** + * This method returns whether the [Source Map v3](https://tc39.es/ecma426/) support for stack + * traces is enabled. + * @since v22.14.0 + */ + function getSourceMapsSupport(): SourceMapsSupport; + /** + * `path` is the resolved path for the file for which a corresponding source map + * should be fetched. + * @since v13.7.0, v12.17.0 + * @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise. + */ + function findSourceMap(path: string): SourceMap | undefined; + interface SetSourceMapsSupportOptions { + /** + * If enabling the support for files in `node_modules`. + * @default false + */ + nodeModules?: boolean | undefined; + /** + * If enabling the support for generated code from `eval` or `new Function`. + * @default false + */ + generatedCode?: boolean | undefined; + } + /** + * This function enables or disables the [Source Map v3](https://tc39.es/ecma426/) support for + * stack traces. + * + * It provides same features as launching Node.js process with commandline options + * `--enable-source-maps`, with additional options to alter the support for files + * in `node_modules` or generated codes. + * + * Only source maps in JavaScript files that are loaded after source maps has been + * enabled will be parsed and loaded. Preferably, use the commandline options + * `--enable-source-maps` to avoid losing track of source maps of modules loaded + * before this API call. + * @since v22.14.0 + */ + function setSourceMapsSupport(enabled: boolean, options?: SetSourceMapsSupportOptions): void; + interface SourceMapConstructorOptions { + /** + * @since v21.0.0, v20.5.0 + */ + lineLengths?: readonly number[] | undefined; + } + interface SourceMapPayload { + file: string; + version: number; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + sourceRoot: string; + } + interface SourceMapping { + generatedLine: number; + generatedColumn: number; + originalSource: string; + originalLine: number; + originalColumn: number; + } + interface SourceOrigin { + /** + * The name of the range in the source map, if one was provided + */ + name: string | undefined; + /** + * The file name of the original source, as reported in the SourceMap + */ + fileName: string; + /** + * The 1-indexed lineNumber of the corresponding call site in the original source + */ + lineNumber: number; + /** + * The 1-indexed columnNumber of the corresponding call site in the original source + */ + columnNumber: number; + } + /** + * @since v13.7.0, v12.17.0 + */ + class SourceMap { + constructor(payload: SourceMapPayload, options?: SourceMapConstructorOptions); + /** + * Getter for the payload used to construct the `SourceMap` instance. + */ + readonly payload: SourceMapPayload; + /** + * Given a line offset and column offset in the generated source + * file, returns an object representing the SourceMap range in the + * original file if found, or an empty object if not. + * + * The object returned contains the following keys: + * + * The returned value represents the raw range as it appears in the + * SourceMap, based on zero-indexed offsets, _not_ 1-indexed line and + * column numbers as they appear in Error messages and CallSite + * objects. + * + * To get the corresponding 1-indexed line and column numbers from a + * lineNumber and columnNumber as they are reported by Error stacks + * and CallSite objects, use `sourceMap.findOrigin(lineNumber, columnNumber)` + * @param lineOffset The zero-indexed line number offset in the generated source + * @param columnOffset The zero-indexed column number offset in the generated source + */ + findEntry(lineOffset: number, columnOffset: number): SourceMapping | {}; + /** + * Given a 1-indexed `lineNumber` and `columnNumber` from a call site in the generated source, + * find the corresponding call site location in the original source. + * + * If the `lineNumber` and `columnNumber` provided are not found in any source map, + * then an empty object is returned. + * @param lineNumber The 1-indexed line number of the call site in the generated source + * @param columnNumber The 1-indexed column number of the call site in the generated source + */ + findOrigin(lineNumber: number, columnNumber: number): SourceOrigin | {}; + } + function runMain(main?: string): void; + function wrap(script: string): string; + } + global { + interface ImportMeta { + /** + * The directory name of the current module. + * + * This is the same as the `path.dirname()` of the `import.meta.filename`. + * + * > **Caveat**: only present on `file:` modules. + * @since v21.2.0, v20.11.0 + */ + dirname: string; + /** + * The full absolute path and filename of the current module, with + * symlinks resolved. + * + * This is the same as the `url.fileURLToPath()` of the `import.meta.url`. + * + * > **Caveat** only local modules support this property. Modules not using the + * > `file:` protocol will not provide it. + * @since v21.2.0, v20.11.0 + */ + filename: string; + /** + * The absolute `file:` URL of the module. + * + * This is defined exactly the same as it is in browsers providing the URL of the + * current module file. + * + * This enables useful patterns such as relative file loading: + * + * ```js + * import { readFileSync } from 'node:fs'; + * const buffer = readFileSync(new URL('./data.proto', import.meta.url)); + * ``` + */ + url: string; + /** + * `import.meta.resolve` is a module-relative resolution function scoped to + * each module, returning the URL string. + * + * ```js + * const dependencyAsset = import.meta.resolve('component-lib/asset.css'); + * // file:///app/node_modules/component-lib/asset.css + * import.meta.resolve('./dep.js'); + * // file:///app/dep.js + * ``` + * + * All features of the Node.js module resolution are supported. Dependency + * resolutions are subject to the permitted exports resolutions within the package. + * + * **Caveats**: + * + * * This can result in synchronous file-system operations, which + * can impact performance similarly to `require.resolve`. + * * This feature is not available within custom loaders (it would + * create a deadlock). + * @since v13.9.0, v12.16.0 + * @param specifier The module specifier to resolve relative to the + * current module. + * @param parent An optional absolute parent module URL to resolve from. + * **Default:** `import.meta.url` + * @returns The absolute URL string that the specifier would resolve to. + */ + resolve(specifier: string, parent?: string | URL): string; + /** + * `true` when the current module is the entry point of the current process; `false` otherwise. + * + * Equivalent to `require.main === module` in CommonJS. + * + * Analogous to Python's `__name__ == "__main__"`. + * + * ```js + * export function foo() { + * return 'Hello, world'; + * } + * + * function main() { + * const message = foo(); + * console.log(message); + * } + * + * if (import.meta.main) main(); + * // `foo` can be imported from another module without possible side-effects from `main` + * ``` + * @since v22.18.0 + * @experimental + */ + main: boolean; + } + namespace NodeJS { + interface Module { + /** + * The module objects required for the first time by this one. + * @since v0.1.16 + */ + children: Module[]; + /** + * The `module.exports` object is created by the `Module` system. Sometimes this is + * not acceptable; many want their module to be an instance of some class. To do + * this, assign the desired export object to `module.exports`. + * @since v0.1.16 + */ + exports: any; + /** + * The fully resolved filename of the module. + * @since v0.1.16 + */ + filename: string; + /** + * The identifier for the module. Typically this is the fully resolved + * filename. + * @since v0.1.16 + */ + id: string; + /** + * `true` if the module is running during the Node.js preload + * phase. + * @since v15.4.0, v14.17.0 + */ + isPreloading: boolean; + /** + * Whether or not the module is done loading, or is in the process of + * loading. + * @since v0.1.16 + */ + loaded: boolean; + /** + * The module that first required this one, or `null` if the current module is the + * entry point of the current process, or `undefined` if the module was loaded by + * something that is not a CommonJS module (e.g. REPL or `import`). + * @since v0.1.16 + * @deprecated Please use `require.main` and `module.children` instead. + */ + parent: Module | null | undefined; + /** + * The directory name of the module. This is usually the same as the + * `path.dirname()` of the `module.id`. + * @since v11.14.0 + */ + path: string; + /** + * The search paths for the module. + * @since v0.4.0 + */ + paths: string[]; + /** + * The `module.require()` method provides a way to load a module as if + * `require()` was called from the original module. + * @since v0.5.1 + */ + require(id: string): any; + } + interface Require { + /** + * Used to import modules, `JSON`, and local files. + * @since v0.1.13 + */ + (id: string): any; + /** + * Modules are cached in this object when they are required. By deleting a key + * value from this object, the next `require` will reload the module. + * This does not apply to + * [native addons](https://nodejs.org/docs/latest-v22.x/api/addons.html), + * for which reloading will result in an error. + * @since v0.3.0 + */ + cache: Dict; + /** + * Instruct `require` on how to handle certain file extensions. + * @since v0.3.0 + * @deprecated + */ + extensions: RequireExtensions; + /** + * The `Module` object representing the entry script loaded when the Node.js + * process launched, or `undefined` if the entry point of the program is not a + * CommonJS module. + * @since v0.1.17 + */ + main: Module | undefined; + /** + * @since v0.3.0 + */ + resolve: RequireResolve; + } + /** @deprecated */ + interface RequireExtensions extends Dict<(module: Module, filename: string) => any> { + ".js": (module: Module, filename: string) => any; + ".json": (module: Module, filename: string) => any; + ".node": (module: Module, filename: string) => any; + } + interface RequireResolveOptions { + /** + * Paths to resolve module location from. If present, these + * paths are used instead of the default resolution paths, with the exception + * of + * [GLOBAL\_FOLDERS](https://nodejs.org/docs/latest-v22.x/api/modules.html#loading-from-the-global-folders) + * like `$HOME/.node_modules`, which are + * always included. Each of these paths is used as a starting point for + * the module resolution algorithm, meaning that the `node_modules` hierarchy + * is checked from this location. + * @since v8.9.0 + */ + paths?: string[] | undefined; + } + interface RequireResolve { + /** + * Use the internal `require()` machinery to look up the location of a module, + * but rather than loading the module, just return the resolved filename. + * + * If the module can not be found, a `MODULE_NOT_FOUND` error is thrown. + * @since v0.3.0 + * @param request The module path to resolve. + */ + (request: string, options?: RequireResolveOptions): string; + /** + * Returns an array containing the paths searched during resolution of `request` or + * `null` if the `request` string references a core module, for example `http` or + * `fs`. + * @since v8.9.0 + * @param request The module path whose lookup paths are being retrieved. + */ + paths(request: string): string[] | null; + } + } + /** + * The directory name of the current module. This is the same as the + * `path.dirname()` of the `__filename`. + * @since v0.1.27 + */ + var __dirname: string; + /** + * The file name of the current module. This is the current module file's absolute + * path with symlinks resolved. + * + * For a main program this is not necessarily the same as the file name used in the + * command line. + * @since v0.0.1 + */ + var __filename: string; + /** + * The `exports` variable is available within a module's file-level scope, and is + * assigned the value of `module.exports` before the module is evaluated. + * @since v0.1.16 + */ + var exports: NodeJS.Module["exports"]; + /** + * A reference to the current module. + * @since v0.1.16 + */ + var module: NodeJS.Module; + /** + * @since v0.1.13 + */ + var require: NodeJS.Require; + // Global-scope aliases for backwards compatibility with @types/node <13.0.x + /** @deprecated Use `NodeJS.Module` instead. */ + interface NodeModule extends NodeJS.Module {} + /** @deprecated Use `NodeJS.Require` instead. */ + interface NodeRequire extends NodeJS.Require {} + /** @deprecated Use `NodeJS.RequireResolve` instead. */ + interface RequireResolve extends NodeJS.RequireResolve {} + } + export = Module; +} +declare module "node:module" { + import module = require("module"); + export = module; +} diff --git a/node_modules/@types/node/net.d.ts b/node_modules/@types/node/net.d.ts new file mode 100644 index 0000000..d29b929 --- /dev/null +++ b/node_modules/@types/node/net.d.ts @@ -0,0 +1,1057 @@ +/** + * > Stability: 2 - Stable + * + * The `node:net` module provides an asynchronous network API for creating stream-based + * TCP or `IPC` servers ({@link createServer}) and clients + * ({@link createConnection}). + * + * It can be accessed using: + * + * ```js + * import net from 'node:net'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/net.js) + */ +declare module "net" { + import { NonSharedBuffer } from "node:buffer"; + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import * as dns from "node:dns"; + type LookupFunction = ( + hostname: string, + options: dns.LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | dns.LookupAddress[], family?: number) => void, + ) => void; + interface AddressInfo { + address: string; + family: string; + port: number; + } + interface SocketConstructorOpts { + fd?: number | undefined; + allowHalfOpen?: boolean | undefined; + onread?: OnReadOpts | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + signal?: AbortSignal | undefined; + } + interface OnReadOpts { + buffer: Uint8Array | (() => Uint8Array); + /** + * This function is called for every chunk of incoming data. + * Two arguments are passed to it: the number of bytes written to `buffer` and a reference to `buffer`. + * Return `false` from this function to implicitly `pause()` the socket. + */ + callback(bytesWritten: number, buffer: Uint8Array): boolean; + } + // TODO: remove empty ConnectOpts placeholder at next major @types/node version. + /** @deprecated */ + interface ConnectOpts {} + interface TcpSocketConnectOpts { + port: number; + host?: string | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + hints?: number | undefined; + family?: number | undefined; + lookup?: LookupFunction | undefined; + noDelay?: boolean | undefined; + keepAlive?: boolean | undefined; + keepAliveInitialDelay?: number | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamily?: boolean | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamilyAttemptTimeout?: number | undefined; + blockList?: BlockList | undefined; + } + interface IpcSocketConnectOpts { + path: string; + } + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + type SocketReadyState = "opening" | "open" | "readOnly" | "writeOnly" | "closed"; + /** + * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint + * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also + * an `EventEmitter`. + * + * A `net.Socket` can be created by the user and used directly to interact with + * a server. For example, it is returned by {@link createConnection}, + * so the user can use it to talk to the server. + * + * It can also be created by Node.js and passed to the user when a connection + * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use + * it to interact with the client. + * @since v0.3.4 + */ + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + /** + * Destroys the socket after all data is written. If the `finish` event was already emitted the socket is destroyed immediately. + * If the socket is still writable it implicitly calls `socket.end()`. + * @since v0.3.4 + */ + destroySoon(): void; + /** + * Sends data on the socket. The second parameter specifies the encoding in the + * case of a string. It defaults to UTF8 encoding. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. + * + * The optional `callback` parameter will be executed when the data is finally + * written out, which may not be immediately. + * + * See `Writable` stream `write()` method for more + * information. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + */ + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + /** + * Initiate a connection on a given socket. + * + * Possible signatures: + * + * * `socket.connect(options[, connectListener])` + * * `socket.connect(path[, connectListener])` for `IPC` connections. + * * `socket.connect(port[, host][, connectListener])` for TCP connections. + * * Returns: `net.Socket` The socket itself. + * + * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, + * instead of a `'connect'` event, an `'error'` event will be emitted with + * the error passed to the `'error'` listener. + * The last parameter `connectListener`, if supplied, will be added as a listener + * for the `'connect'` event **once**. + * + * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined + * behavior. + */ + connect(options: SocketConnectOpts, connectionListener?: () => void): this; + connect(port: number, host: string, connectionListener?: () => void): this; + connect(port: number, connectionListener?: () => void): this; + connect(path: string, connectionListener?: () => void): this; + /** + * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. + * @since v0.1.90 + * @return The socket itself. + */ + setEncoding(encoding?: BufferEncoding): this; + /** + * Pauses the reading of data. That is, `'data'` events will not be emitted. + * Useful to throttle back an upload. + * @return The socket itself. + */ + pause(): this; + /** + * Close the TCP connection by sending an RST packet and destroy the stream. + * If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected. + * Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. + * If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error. + * @since v18.3.0, v16.17.0 + */ + resetAndDestroy(): this; + /** + * Resumes reading after a call to `socket.pause()`. + * @return The socket itself. + */ + resume(): this; + /** + * Sets the socket to timeout after `timeout` milliseconds of inactivity on + * the socket. By default `net.Socket` do not have a timeout. + * + * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to + * end the connection. + * + * ```js + * socket.setTimeout(3000); + * socket.on('timeout', () => { + * console.log('socket timeout'); + * socket.end(); + * }); + * ``` + * + * If `timeout` is 0, then the existing idle timeout is disabled. + * + * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. + * @since v0.1.90 + * @return The socket itself. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Enable/disable the use of Nagle's algorithm. + * + * When a TCP connection is created, it will have Nagle's algorithm enabled. + * + * Nagle's algorithm delays data before it is sent via the network. It attempts + * to optimize throughput at the expense of latency. + * + * Passing `true` for `noDelay` or not passing an argument will disable Nagle's + * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's + * algorithm. + * @since v0.1.90 + * @param [noDelay=true] + * @return The socket itself. + */ + setNoDelay(noDelay?: boolean): this; + /** + * Enable/disable keep-alive functionality, and optionally set the initial + * delay before the first keepalive probe is sent on an idle socket. + * + * Set `initialDelay` (in milliseconds) to set the delay between the last + * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default + * (or previous) setting. + * + * Enabling the keep-alive functionality will set the following socket options: + * + * * `SO_KEEPALIVE=1` + * * `TCP_KEEPIDLE=initialDelay` + * * `TCP_KEEPCNT=10` + * * `TCP_KEEPINTVL=1` + * @since v0.1.92 + * @param [enable=false] + * @param [initialDelay=0] + * @return The socket itself. + */ + setKeepAlive(enable?: boolean, initialDelay?: number): this; + /** + * Returns the bound `address`, the address `family` name and `port` of the + * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + * @since v0.1.90 + */ + address(): AddressInfo | {}; + /** + * Calling `unref()` on a socket will allow the program to exit if this is the only + * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + unref(): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior). + * If the socket is `ref`ed calling `ref` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + ref(): this; + /** + * This property is only present if the family autoselection algorithm is enabled in `socket.connect(options)` + * and it is an array of the addresses that have been attempted. + * + * Each address is a string in the form of `$IP:$PORT`. + * If the connection was successful, then the last address is the one that the socket is currently connected to. + * @since v19.4.0 + */ + readonly autoSelectFamilyAttemptedAddresses: string[]; + /** + * This property shows the number of characters buffered for writing. The buffer + * may contain strings whose length after encoding is not yet known. So this number + * is only an approximation of the number of bytes in the buffer. + * + * `net.Socket` has the property that `socket.write()` always works. This is to + * help users get up and running quickly. The computer cannot always keep up + * with the amount of data that is written to a socket. The network connection + * simply might be too slow. Node.js will internally queue up the data written to a + * socket and send it out over the wire when it is possible. + * + * The consequence of this internal buffering is that memory may grow. + * Users who experience large or growing `bufferSize` should attempt to + * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. + * @since v0.3.8 + * @deprecated Since v14.6.0 - Use `writableLength` instead. + */ + readonly bufferSize: number; + /** + * The amount of received bytes. + * @since v0.5.3 + */ + readonly bytesRead: number; + /** + * The amount of bytes sent. + * @since v0.5.3 + */ + readonly bytesWritten: number; + /** + * If `true`, `socket.connect(options[, connectListener])` was + * called and has not yet finished. It will stay `true` until the socket becomes + * connected, then it is set to `false` and the `'connect'` event is emitted. Note + * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. + * @since v6.1.0 + */ + readonly connecting: boolean; + /** + * This is `true` if the socket is not connected yet, either because `.connect()`has not yet been called or because it is still in the process of connecting + * (see `socket.connecting`). + * @since v11.2.0, v10.16.0 + */ + readonly pending: boolean; + /** + * See `writable.destroyed` for further details. + */ + readonly destroyed: boolean; + /** + * The string representation of the local IP address the remote client is + * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client + * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. + * @since v0.9.6 + */ + readonly localAddress?: string; + /** + * The numeric representation of the local port. For example, `80` or `21`. + * @since v0.9.6 + */ + readonly localPort?: number; + /** + * The string representation of the local IP family. `'IPv4'` or `'IPv6'`. + * @since v18.8.0, v16.18.0 + */ + readonly localFamily?: string; + /** + * This property represents the state of the connection as a string. + * + * * If the stream is connecting `socket.readyState` is `opening`. + * * If the stream is readable and writable, it is `open`. + * * If the stream is readable and not writable, it is `readOnly`. + * * If the stream is not readable and writable, it is `writeOnly`. + * @since v0.5.0 + */ + readonly readyState: SocketReadyState; + /** + * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remoteAddress: string | undefined; + /** + * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.11.14 + */ + readonly remoteFamily: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remotePort: number | undefined; + /** + * The socket timeout in milliseconds as set by `socket.setTimeout()`. + * It is `undefined` if a timeout has not been set. + * @since v10.7.0 + */ + readonly timeout?: number; + /** + * Half-closes the socket. i.e., it sends a FIN packet. It is possible the + * server will still send some data. + * + * See `writable.end()` for further details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(callback?: () => void): this; + end(buffer: Uint8Array | string, callback?: () => void): this; + end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. connectionAttempt + * 4. connectionAttemptFailed + * 5. connectionAttemptTimeout + * 6. data + * 7. drain + * 8. end + * 9. error + * 10. lookup + * 11. ready + * 12. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (hadError: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + addListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + addListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + addListener(event: "data", listener: (data: NonSharedBuffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "timeout", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", hadError: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "connectionAttempt", ip: string, port: number, family: number): boolean; + emit(event: "connectionAttemptFailed", ip: string, port: number, family: number, error: Error): boolean; + emit(event: "connectionAttemptTimeout", ip: string, port: number, family: number): boolean; + emit(event: "data", data: NonSharedBuffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "ready"): boolean; + emit(event: "timeout"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (hadError: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + on( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + on(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this; + on(event: "data", listener: (data: NonSharedBuffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + on(event: "ready", listener: () => void): this; + on(event: "timeout", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (hadError: boolean) => void): this; + once(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + once( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + once(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: NonSharedBuffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + once(event: "ready", listener: () => void): this; + once(event: "timeout", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (hadError: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + prependListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + prependListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependListener(event: "data", listener: (data: NonSharedBuffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (hadError: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener( + event: "connectionAttempt", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + prependOnceListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener(event: "data", listener: (data: NonSharedBuffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + interface ListenOptions extends Abortable { + backlog?: number | undefined; + exclusive?: boolean | undefined; + host?: string | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + reusePort?: boolean | undefined; + path?: string | undefined; + port?: number | undefined; + readableAll?: boolean | undefined; + writableAll?: boolean | undefined; + } + interface ServerOpts { + /** + * Indicates whether half-opened TCP connections are allowed. + * @default false + */ + allowHalfOpen?: boolean | undefined; + /** + * Indicates whether the socket should be paused on incoming connections. + * @default false + */ + pauseOnConnect?: boolean | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default false + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * Optionally overrides all `net.Socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * @default See [stream.getDefaultHighWaterMark()](https://nodejs.org/docs/latest-v22.x/api/stream.html#streamgetdefaulthighwatermarkobjectmode). + * @since v18.17.0, v20.1.0 + */ + highWaterMark?: number | undefined; + /** + * `blockList` can be used for disabling inbound + * access to specific IP addresses, IP ranges, or IP subnets. This does not + * work if the server is behind a reverse proxy, NAT, etc. because the address + * checked against the block list is the address of the proxy, or the one + * specified by the NAT. + * @since v22.13.0 + */ + blockList?: BlockList | undefined; + } + interface DropArgument { + localAddress?: string; + localPort?: number; + localFamily?: string; + remoteAddress?: string; + remotePort?: number; + remoteFamily?: string; + } + /** + * This class is used to create a TCP or `IPC` server. + * @since v0.1.90 + */ + class Server extends EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); + /** + * Start a server listening for connections. A `net.Server` can be a TCP or + * an `IPC` server depending on what it listens to. + * + * Possible signatures: + * + * * `server.listen(handle[, backlog][, callback])` + * * `server.listen(options[, callback])` + * * `server.listen(path[, backlog][, callback])` for `IPC` servers + * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + * + * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` + * event. + * + * All `listen()` methods can take a `backlog` parameter to specify the maximum + * length of the queue of pending connections. The actual length will be determined + * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn` on Linux. The default value of this parameter is 511 (not 512). + * + * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for + * details). + * + * The `server.listen()` method can be called again if and only if there was an + * error during the first `server.listen()` call or `server.close()` has been + * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + * + * One of the most common errors raised when listening is `EADDRINUSE`. + * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry + * after a certain amount of time: + * + * ```js + * server.on('error', (e) => { + * if (e.code === 'EADDRINUSE') { + * console.error('Address in use, retrying...'); + * setTimeout(() => { + * server.close(); + * server.listen(PORT, HOST); + * }, 1000); + * } + * }); + * ``` + */ + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, hostname?: string, listeningListener?: () => void): this; + listen(port?: number, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, listeningListener?: () => void): this; + listen(path: string, backlog?: number, listeningListener?: () => void): this; + listen(path: string, listeningListener?: () => void): this; + listen(options: ListenOptions, listeningListener?: () => void): this; + listen(handle: any, backlog?: number, listeningListener?: () => void): this; + listen(handle: any, listeningListener?: () => void): this; + /** + * Stops the server from accepting new connections and keeps existing + * connections. This function is asynchronous, the server is finally closed + * when all connections are ended and the server emits a `'close'` event. + * The optional `callback` will be called once the `'close'` event occurs. Unlike + * that event, it will be called with an `Error` as its only argument if the server + * was not open when it was closed. + * @since v0.1.90 + * @param callback Called when the server is closed. + */ + close(callback?: (err?: Error) => void): this; + /** + * Returns the bound `address`, the address `family` name, and `port` of the server + * as reported by the operating system if listening on an IP socket + * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. + * + * For a server listening on a pipe or Unix domain socket, the name is returned + * as a string. + * + * ```js + * const server = net.createServer((socket) => { + * socket.end('goodbye\n'); + * }).on('error', (err) => { + * // Handle errors here. + * throw err; + * }); + * + * // Grab an arbitrary unused port. + * server.listen(() => { + * console.log('opened server on', server.address()); + * }); + * ``` + * + * `server.address()` returns `null` before the `'listening'` event has been + * emitted or after calling `server.close()`. + * @since v0.1.90 + */ + address(): AddressInfo | string | null; + /** + * Asynchronously get the number of concurrent connections on the server. Works + * when sockets were sent to forks. + * + * Callback should take two arguments `err` and `count`. + * @since v0.9.7 + */ + getConnections(cb: (error: Error | null, count: number) => void): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will _not_ let the program exit if it's the only server left (the default behavior). + * If the server is `ref`ed calling `ref()` again will have no effect. + * @since v0.9.1 + */ + ref(): this; + /** + * Calling `unref()` on a server will allow the program to exit if this is the only + * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + */ + unref(): this; + /** + * Set this property to reject connections when the server's connection count gets + * high. + * + * It is not recommended to use this option once a socket has been sent to a child + * with `child_process.fork()`. + * @since v0.2.0 + */ + maxConnections: number; + connections: number; + /** + * Indicates whether or not the server is listening for connections. + * @since v5.7.0 + */ + readonly listening: boolean; + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + * 5. drop + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "drop", listener: (data?: DropArgument) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "drop", data?: DropArgument): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "drop", listener: (data?: DropArgument) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "drop", listener: (data?: DropArgument) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "drop", listener: (data?: DropArgument) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "drop", listener: (data?: DropArgument) => void): this; + /** + * Calls {@link Server.close()} and returns a promise that fulfills when the server has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } + type IPVersion = "ipv4" | "ipv6"; + /** + * The `BlockList` object can be used with some network APIs to specify rules for + * disabling inbound or outbound access to specific IP addresses, IP ranges, or + * IP subnets. + * @since v15.0.0, v14.18.0 + */ + class BlockList { + /** + * Adds a rule to block the given IP address. + * @since v15.0.0, v14.18.0 + * @param address An IPv4 or IPv6 address. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addAddress(address: string, type?: IPVersion): void; + addAddress(address: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). + * @since v15.0.0, v14.18.0 + * @param start The starting IPv4 or IPv6 address in the range. + * @param end The ending IPv4 or IPv6 address in the range. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addRange(start: string, end: string, type?: IPVersion): void; + addRange(start: SocketAddress, end: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses specified as a subnet mask. + * @since v15.0.0, v14.18.0 + * @param net The network IPv4 or IPv6 address. + * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addSubnet(net: SocketAddress, prefix: number): void; + addSubnet(net: string, prefix: number, type?: IPVersion): void; + /** + * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. + * + * ```js + * const blockList = new net.BlockList(); + * blockList.addAddress('123.123.123.123'); + * blockList.addRange('10.0.0.1', '10.0.0.10'); + * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); + * + * console.log(blockList.check('123.123.123.123')); // Prints: true + * console.log(blockList.check('10.0.0.3')); // Prints: true + * console.log(blockList.check('222.111.111.222')); // Prints: false + * + * // IPv6 notation for IPv4 addresses works: + * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true + * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true + * ``` + * @since v15.0.0, v14.18.0 + * @param address The IP address to check + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + check(address: SocketAddress): boolean; + check(address: string, type?: IPVersion): boolean; + /** + * The list of rules added to the blocklist. + * @since v15.0.0, v14.18.0 + */ + rules: readonly string[]; + /** + * Returns `true` if the `value` is a `net.BlockList`. + * @since v22.13.0 + * @param value Any JS value + */ + static isBlockList(value: unknown): value is BlockList; + /** + * ```js + * const blockList = new net.BlockList(); + * const data = [ + * 'Subnet: IPv4 192.168.1.0/24', + * 'Address: IPv4 10.0.0.5', + * 'Range: IPv4 192.168.2.1-192.168.2.10', + * 'Range: IPv4 10.0.0.1-10.0.0.10', + * ]; + * blockList.fromJSON(data); + * blockList.fromJSON(JSON.stringify(data)); + * ``` + * @since v22.19.0 + * @experimental + */ + fromJSON(data: string | readonly string[]): void; + /** + * @since v22.19.0 + * @experimental + */ + toJSON(): readonly string[]; + } + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + /** + * Creates a new TCP or `IPC` server. + * + * If `allowHalfOpen` is set to `true`, when the other end of the socket + * signals the end of transmission, the server will only send back the end of + * transmission when `socket.end()` is explicitly called. For example, in the + * context of TCP, when a FIN packed is received, a FIN packed is sent + * back only when `socket.end()` is explicitly called. Until then the + * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. + * + * If `pauseOnConnect` is set to `true`, then the socket associated with each + * incoming connection will be paused, and no data will be read from its handle. + * This allows connections to be passed between processes without any data being + * read by the original process. To begin reading data from a paused socket, call `socket.resume()`. + * + * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. + * + * Here is an example of a TCP echo server which listens for connections + * on port 8124: + * + * ```js + * import net from 'node:net'; + * const server = net.createServer((c) => { + * // 'connection' listener. + * console.log('client connected'); + * c.on('end', () => { + * console.log('client disconnected'); + * }); + * c.write('hello\r\n'); + * c.pipe(c); + * }); + * server.on('error', (err) => { + * throw err; + * }); + * server.listen(8124, () => { + * console.log('server bound'); + * }); + * ``` + * + * Test this by using `telnet`: + * + * ```bash + * telnet localhost 8124 + * ``` + * + * To listen on the socket `/tmp/echo.sock`: + * + * ```js + * server.listen('/tmp/echo.sock', () => { + * console.log('server bound'); + * }); + * ``` + * + * Use `nc` to connect to a Unix domain socket server: + * + * ```bash + * nc -U /tmp/echo.sock + * ``` + * @since v0.5.0 + * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. + */ + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; + /** + * Aliases to {@link createConnection}. + * + * Possible signatures: + * + * * {@link connect} + * * {@link connect} for `IPC` connections. + * * {@link connect} for TCP connections. + */ + function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; + function connect(port: number, host?: string, connectionListener?: () => void): Socket; + function connect(path: string, connectionListener?: () => void): Socket; + /** + * A factory function, which creates a new {@link Socket}, + * immediately initiates connection with `socket.connect()`, + * then returns the `net.Socket` that starts the connection. + * + * When the connection is established, a `'connect'` event will be emitted + * on the returned socket. The last parameter `connectListener`, if supplied, + * will be added as a listener for the `'connect'` event **once**. + * + * Possible signatures: + * + * * {@link createConnection} + * * {@link createConnection} for `IPC` connections. + * * {@link createConnection} for TCP connections. + * + * The {@link connect} function is an alias to this function. + */ + function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; + function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; + function createConnection(path: string, connectionListener?: () => void): Socket; + /** + * Gets the current default value of the `autoSelectFamily` option of `socket.connect(options)`. + * The initial default value is `true`, unless the command line option`--no-network-family-autoselection` is provided. + * @since v19.4.0 + */ + function getDefaultAutoSelectFamily(): boolean; + /** + * Sets the default value of the `autoSelectFamily` option of `socket.connect(options)`. + * @param value The new default value. + * The initial default value is `true`, unless the command line option + * `--no-network-family-autoselection` is provided. + * @since v19.4.0 + */ + function setDefaultAutoSelectFamily(value: boolean): void; + /** + * Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * The initial default value is `250` or the value specified via the command line option `--network-family-autoselection-attempt-timeout`. + * @returns The current default value of the `autoSelectFamilyAttemptTimeout` option. + * @since v19.8.0, v18.8.0 + */ + function getDefaultAutoSelectFamilyAttemptTimeout(): number; + /** + * Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * @param value The new default value, which must be a positive number. If the number is less than `10`, the value `10` is used instead. The initial default value is `250` or the value specified via the command line + * option `--network-family-autoselection-attempt-timeout`. + * @since v19.8.0, v18.8.0 + */ + function setDefaultAutoSelectFamilyAttemptTimeout(value: number): void; + /** + * Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4 + * address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`. + * + * ```js + * net.isIP('::1'); // returns 6 + * net.isIP('127.0.0.1'); // returns 4 + * net.isIP('127.000.000.001'); // returns 0 + * net.isIP('127.0.0.1/24'); // returns 0 + * net.isIP('fhqwhgads'); // returns 0 + * ``` + * @since v0.3.0 + */ + function isIP(input: string): number; + /** + * Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no + * leading zeroes. Otherwise, returns `false`. + * + * ```js + * net.isIPv4('127.0.0.1'); // returns true + * net.isIPv4('127.000.000.001'); // returns false + * net.isIPv4('127.0.0.1/24'); // returns false + * net.isIPv4('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv4(input: string): boolean; + /** + * Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`. + * + * ```js + * net.isIPv6('::1'); // returns true + * net.isIPv6('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv6(input: string): boolean; + interface SocketAddressInitOptions { + /** + * The network address as either an IPv4 or IPv6 string. + * @default 127.0.0.1 + */ + address?: string | undefined; + /** + * @default `'ipv4'` + */ + family?: IPVersion | undefined; + /** + * An IPv6 flow-label used only if `family` is `'ipv6'`. + * @default 0 + */ + flowlabel?: number | undefined; + /** + * An IP port. + * @default 0 + */ + port?: number | undefined; + } + /** + * @since v15.14.0, v14.18.0 + */ + class SocketAddress { + constructor(options: SocketAddressInitOptions); + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly address: string; + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly family: IPVersion; + /** + * @since v15.14.0, v14.18.0 + */ + readonly port: number; + /** + * @since v15.14.0, v14.18.0 + */ + readonly flowlabel: number; + /** + * @since v22.13.0 + * @param input An input string containing an IP address and optional port, + * e.g. `123.1.2.3:1234` or `[1::1]:1234`. + * @returns Returns a `SocketAddress` if parsing was successful. + * Otherwise returns `undefined`. + */ + static parse(input: string): SocketAddress | undefined; + } +} +declare module "node:net" { + export * from "net"; +} diff --git a/node_modules/@types/node/os.d.ts b/node_modules/@types/node/os.d.ts new file mode 100644 index 0000000..a40bd77 --- /dev/null +++ b/node_modules/@types/node/os.d.ts @@ -0,0 +1,506 @@ +/** + * The `node:os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * import os from 'node:os'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/os.js) + */ +declare module "os" { + import { NonSharedBuffer } from "buffer"; + interface CpuInfo { + model: string; + speed: number; + times: { + /** The number of milliseconds the CPU has spent in user mode. */ + user: number; + /** The number of milliseconds the CPU has spent in nice mode. */ + nice: number; + /** The number of milliseconds the CPU has spent in sys mode. */ + sys: number; + /** The number of milliseconds the CPU has spent in idle mode. */ + idle: number; + /** The number of milliseconds the CPU has spent in irq mode. */ + irq: number; + }; + } + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + scopeid?: number; + } + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + } + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T | null; + homedir: T; + } + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + /** + * Returns the host name of the operating system as a string. + * @since v0.3.3 + */ + function hostname(): string; + /** + * Returns an array containing the 1, 5, and 15 minute load averages. + * + * The load average is a measure of system activity calculated by the operating + * system and expressed as a fractional number. + * + * The load average is a Unix-specific concept. On Windows, the return value is + * always `[0, 0, 0]`. + * @since v0.3.3 + */ + function loadavg(): number[]; + /** + * Returns the system uptime in number of seconds. + * @since v0.3.3 + */ + function uptime(): number; + /** + * Returns the amount of free system memory in bytes as an integer. + * @since v0.3.3 + */ + function freemem(): number; + /** + * Returns the total amount of system memory in bytes as an integer. + * @since v0.3.3 + */ + function totalmem(): number; + /** + * Returns an array of objects containing information about each logical CPU core. + * The array will be empty if no CPU information is available, such as if the `/proc` file system is unavailable. + * + * The properties included on each object include: + * + * ```js + * [ + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 252020, + * nice: 0, + * sys: 30340, + * idle: 1070356870, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 306960, + * nice: 0, + * sys: 26980, + * idle: 1071569080, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 248450, + * nice: 0, + * sys: 21750, + * idle: 1070919370, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 256880, + * nice: 0, + * sys: 19430, + * idle: 1070905480, + * irq: 20, + * }, + * }, + * ] + * ``` + * + * `nice` values are POSIX-only. On Windows, the `nice` values of all processors + * are always 0. + * + * `os.cpus().length` should not be used to calculate the amount of parallelism + * available to an application. Use {@link availableParallelism} for this purpose. + * @since v0.3.3 + */ + function cpus(): CpuInfo[]; + /** + * Returns an estimate of the default amount of parallelism a program should use. + * Always returns a value greater than zero. + * + * This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism). + * @since v19.4.0, v18.14.0 + */ + function availableParallelism(): number; + /** + * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it + * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. + * + * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information + * about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. + * @since v0.3.3 + */ + function type(): string; + /** + * Returns the operating system as a string. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See + * [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v0.3.3 + */ + function release(): string; + /** + * Returns an object containing network interfaces that have been assigned a + * network address. + * + * Each key on the returned object identifies a network interface. The associated + * value is an array of objects that each describe an assigned network address. + * + * The properties available on the assigned network address object include: + * + * ```js + * { + * lo: [ + * { + * address: '127.0.0.1', + * netmask: '255.0.0.0', + * family: 'IPv4', + * mac: '00:00:00:00:00:00', + * internal: true, + * cidr: '127.0.0.1/8' + * }, + * { + * address: '::1', + * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', + * family: 'IPv6', + * mac: '00:00:00:00:00:00', + * scopeid: 0, + * internal: true, + * cidr: '::1/128' + * } + * ], + * eth0: [ + * { + * address: '192.168.1.108', + * netmask: '255.255.255.0', + * family: 'IPv4', + * mac: '01:02:03:0a:0b:0c', + * internal: false, + * cidr: '192.168.1.108/24' + * }, + * { + * address: 'fe80::a00:27ff:fe4e:66a1', + * netmask: 'ffff:ffff:ffff:ffff::', + * family: 'IPv6', + * mac: '01:02:03:0a:0b:0c', + * scopeid: 1, + * internal: false, + * cidr: 'fe80::a00:27ff:fe4e:66a1/64' + * } + * ] + * } + * ``` + * @since v0.6.0 + */ + function networkInterfaces(): NodeJS.Dict; + /** + * Returns the string path of the current user's home directory. + * + * On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it + * uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. + * + * On Windows, it uses the `USERPROFILE` environment variable if defined. + * Otherwise it uses the path to the profile directory of the current user. + * @since v2.3.0 + */ + function homedir(): string; + interface UserInfoOptions { + encoding?: BufferEncoding | "buffer" | undefined; + } + interface UserInfoOptionsWithBufferEncoding extends UserInfoOptions { + encoding: "buffer"; + } + interface UserInfoOptionsWithStringEncoding extends UserInfoOptions { + encoding?: BufferEncoding | undefined; + } + /** + * Returns information about the currently effective user. On POSIX platforms, + * this is typically a subset of the password file. The returned object includes + * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and `gid` fields are `-1`, and `shell` is `null`. + * + * The value of `homedir` returned by `os.userInfo()` is provided by the operating + * system. This differs from the result of `os.homedir()`, which queries + * environment variables for the home directory before falling back to the + * operating system response. + * + * Throws a [`SystemError`](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-systemerror) if a user has no `username` or `homedir`. + * @since v6.0.0 + */ + function userInfo(options?: UserInfoOptionsWithStringEncoding): UserInfo; + function userInfo(options: UserInfoOptionsWithBufferEncoding): UserInfo; + function userInfo(options: UserInfoOptions): UserInfo; + type SignalConstants = { + [key in NodeJS.Signals]: number; + }; + namespace constants { + const UV_UDP_REUSEADDR: number; + namespace signals {} + const signals: SignalConstants; + namespace errno { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EDQUOT: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const EMULTIHOP: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ESTALE: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + } + namespace dlopen { + const RTLD_LAZY: number; + const RTLD_NOW: number; + const RTLD_GLOBAL: number; + const RTLD_LOCAL: number; + const RTLD_DEEPBIND: number; + } + namespace priority { + const PRIORITY_LOW: number; + const PRIORITY_BELOW_NORMAL: number; + const PRIORITY_NORMAL: number; + const PRIORITY_ABOVE_NORMAL: number; + const PRIORITY_HIGH: number; + const PRIORITY_HIGHEST: number; + } + } + const devNull: string; + /** + * The operating system-specific end-of-line marker. + * * `\n` on POSIX + * * `\r\n` on Windows + */ + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, + * and `'x64'`. + * + * The return value is equivalent to [process.arch](https://nodejs.org/docs/latest-v22.x/api/process.html#processarch). + * @since v0.5.0 + */ + function arch(): string; + /** + * Returns a string identifying the kernel version. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v13.11.0, v12.17.0 + */ + function version(): string; + /** + * Returns a string identifying the operating system platform for which + * the Node.js binary was compiled. The value is set at compile time. + * Possible values are `'aix'`, `'darwin'`, `'freebsd'`, `'linux'`, `'openbsd'`, `'sunos'`, and `'win32'`. + * + * The return value is equivalent to `process.platform`. + * + * The value `'android'` may also be returned if Node.js is built on the Android + * operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.5.0 + */ + function platform(): NodeJS.Platform; + /** + * Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`, `mips`, `mips64`, `ppc64`, `ppc64le`, `s390`, `s390x`, `i386`, `i686`, `x86_64`. + * + * On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v18.9.0, v16.18.0 + */ + function machine(): string; + /** + * Returns the operating system's default directory for temporary files as a + * string. + * @since v0.9.9 + */ + function tmpdir(): string; + /** + * Returns a string identifying the endianness of the CPU for which the Node.js + * binary was compiled. + * + * Possible values are `'BE'` for big endian and `'LE'` for little endian. + * @since v0.9.4 + */ + function endianness(): "BE" | "LE"; + /** + * Returns the scheduling priority for the process specified by `pid`. If `pid` is + * not provided or is `0`, the priority of the current process is returned. + * @since v10.10.0 + * @param [pid=0] The process ID to retrieve scheduling priority for. + */ + function getPriority(pid?: number): number; + /** + * Attempts to set the scheduling priority for the process specified by `pid`. If `pid` is not provided or is `0`, the process ID of the current process is used. + * + * The `priority` input must be an integer between `-20` (high priority) and `19` (low priority). Due to differences between Unix priority levels and Windows + * priority classes, `priority` is mapped to one of six priority constants in `os.constants.priority`. When retrieving a process priority level, this range + * mapping may cause the return value to be slightly different on Windows. To avoid + * confusion, set `priority` to one of the priority constants. + * + * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user + * privileges. Otherwise the set priority will be silently reduced to `PRIORITY_HIGH`. + * @since v10.10.0 + * @param [pid=0] The process ID to set scheduling priority for. + * @param priority The scheduling priority to assign to the process. + */ + function setPriority(priority: number): void; + function setPriority(pid: number, priority: number): void; +} +declare module "node:os" { + export * from "os"; +} diff --git a/node_modules/@types/node/package.json b/node_modules/@types/node/package.json new file mode 100644 index 0000000..454fd73 --- /dev/null +++ b/node_modules/@types/node/package.json @@ -0,0 +1,145 @@ +{ + "name": "@types/node", + "version": "22.19.2", + "description": "TypeScript definitions for node", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "license": "MIT", + "contributors": [ + { + "name": "Microsoft TypeScript", + "githubUsername": "Microsoft", + "url": "https://github.com/Microsoft" + }, + { + "name": "Alberto Schiabel", + "githubUsername": "jkomyno", + "url": "https://github.com/jkomyno" + }, + { + "name": "Andrew Makarov", + "githubUsername": "r3nya", + "url": "https://github.com/r3nya" + }, + { + "name": "Benjamin Toueg", + "githubUsername": "btoueg", + "url": "https://github.com/btoueg" + }, + { + "name": "David Junger", + "githubUsername": "touffy", + "url": "https://github.com/touffy" + }, + { + "name": "Mohsen Azimi", + "githubUsername": "mohsen1", + "url": "https://github.com/mohsen1" + }, + { + "name": "Nikita Galkin", + "githubUsername": "galkin", + "url": "https://github.com/galkin" + }, + { + "name": "Sebastian Silbermann", + "githubUsername": "eps1lon", + "url": "https://github.com/eps1lon" + }, + { + "name": "Wilco Bakker", + "githubUsername": "WilcoBakker", + "url": "https://github.com/WilcoBakker" + }, + { + "name": "Marcin Kopacz", + "githubUsername": "chyzwar", + "url": "https://github.com/chyzwar" + }, + { + "name": "Trivikram Kamat", + "githubUsername": "trivikr", + "url": "https://github.com/trivikr" + }, + { + "name": "Junxiao Shi", + "githubUsername": "yoursunny", + "url": "https://github.com/yoursunny" + }, + { + "name": "Ilia Baryshnikov", + "githubUsername": "qwelias", + "url": "https://github.com/qwelias" + }, + { + "name": "ExE Boss", + "githubUsername": "ExE-Boss", + "url": "https://github.com/ExE-Boss" + }, + { + "name": "Piotr Błażejewicz", + "githubUsername": "peterblazejewicz", + "url": "https://github.com/peterblazejewicz" + }, + { + "name": "Anna Henningsen", + "githubUsername": "addaleax", + "url": "https://github.com/addaleax" + }, + { + "name": "Victor Perin", + "githubUsername": "victorperin", + "url": "https://github.com/victorperin" + }, + { + "name": "NodeJS Contributors", + "githubUsername": "NodeJS", + "url": "https://github.com/NodeJS" + }, + { + "name": "Linus Unnebäck", + "githubUsername": "LinusU", + "url": "https://github.com/LinusU" + }, + { + "name": "wafuwafu13", + "githubUsername": "wafuwafu13", + "url": "https://github.com/wafuwafu13" + }, + { + "name": "Matteo Collina", + "githubUsername": "mcollina", + "url": "https://github.com/mcollina" + }, + { + "name": "Dmitry Semigradsky", + "githubUsername": "Semigradsky", + "url": "https://github.com/Semigradsky" + }, + { + "name": "René", + "githubUsername": "Renegade334", + "url": "https://github.com/Renegade334" + } + ], + "main": "", + "types": "index.d.ts", + "typesVersions": { + "<=5.6": { + "*": [ + "ts5.6/*" + ] + } + }, + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "dependencies": { + "undici-types": "~6.21.0" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "cb67dd83f6f69ba1e456c156512686df21fb7978863408330225329e663f5c7e", + "typeScriptVersion": "5.2" +} \ No newline at end of file diff --git a/node_modules/@types/node/path.d.ts b/node_modules/@types/node/path.d.ts new file mode 100644 index 0000000..b83d8f5 --- /dev/null +++ b/node_modules/@types/node/path.d.ts @@ -0,0 +1,200 @@ +declare module "path/posix" { + import path = require("path"); + export = path; +} +declare module "path/win32" { + import path = require("path"); + export = path; +} +/** + * The `node:path` module provides utilities for working with file and directory + * paths. It can be accessed using: + * + * ```js + * import path from 'node:path'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/path.js) + */ +declare module "path" { + namespace path { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string | undefined; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string | undefined; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string | undefined; + /** + * The file extension (if any) such as '.html' + */ + ext?: string | undefined; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string | undefined; + } + interface PlatformPath { + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. If the path is a zero-length string, '.' is returned, representing the current working directory. + * + * @param path string path to normalize. + * @throws {TypeError} if `path` is not a string. + */ + normalize(path: string): string; + /** + * Join all arguments together and normalize the resulting path. + * + * @param paths paths to join. + * @throws {TypeError} if any of the path segments is not a string. + */ + join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param paths A sequence of paths or path segments. + * @throws {TypeError} if any of the arguments is not a string. + */ + resolve(...paths: string[]): string; + /** + * The `path.matchesGlob()` method determines if `path` matches the `pattern`. + * @param path The path to glob-match against. + * @param pattern The glob to check the path against. + * @returns Whether or not the `path` matched the `pattern`. + * @throws {TypeError} if `path` or `pattern` are not strings. + * @since v22.5.0 + */ + matchesGlob(path: string, pattern: string): boolean; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * If the given {path} is a zero-length string, `false` will be returned. + * + * @param path path to test. + * @throws {TypeError} if `path` is not a string. + */ + isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to} based on the current working directory. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @throws {TypeError} if either `from` or `to` is not a string. + */ + relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + dirname(path: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param path the path to evaluate. + * @param suffix optionally, an extension to remove from the result. + * @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string. + */ + basename(path: string, suffix?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + extname(path: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + readonly sep: "\\" | "/"; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + readonly delimiter: ";" | ":"; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param path path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + parse(path: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathObject path to evaluate. + */ + format(pathObject: FormatInputPathObject): string; + /** + * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. + * If path is not a string, path will be returned without modifications. + * This method is meaningful only on Windows system. + * On POSIX systems, the method is non-operational and always returns path without modifications. + */ + toNamespacedPath(path: string): string; + /** + * Posix specific pathing. + * Same as parent object on posix. + */ + readonly posix: PlatformPath; + /** + * Windows specific pathing. + * Same as parent object on windows + */ + readonly win32: PlatformPath; + } + } + const path: path.PlatformPath; + export = path; +} +declare module "node:path" { + import path = require("path"); + export = path; +} +declare module "node:path/posix" { + import path = require("path/posix"); + export = path; +} +declare module "node:path/win32" { + import path = require("path/win32"); + export = path; +} diff --git a/node_modules/@types/node/perf_hooks.d.ts b/node_modules/@types/node/perf_hooks.d.ts new file mode 100644 index 0000000..ad0785d --- /dev/null +++ b/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,968 @@ +/** + * This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for + * Node.js-specific performance measurements. + * + * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): + * + * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) + * * [Performance Timeline](https://w3c.github.io/performance-timeline/) + * * [User Timing](https://www.w3.org/TR/user-timing/) + * * [Resource Timing](https://www.w3.org/TR/resource-timing-2/) + * + * ```js + * import { PerformanceObserver, performance } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((items) => { + * console.log(items.getEntries()[0].duration); + * performance.clearMarks(); + * }); + * obs.observe({ type: 'measure' }); + * performance.measure('Start to Now'); + * + * performance.mark('A'); + * doSomeLongRunningProcess(() => { + * performance.measure('A to Now', 'A'); + * + * performance.mark('B'); + * performance.measure('A to B', 'A', 'B'); + * }); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/perf_hooks.js) + */ +declare module "perf_hooks" { + import { AsyncResource } from "node:async_hooks"; + type EntryType = + | "dns" // Node.js only + | "function" // Node.js only + | "gc" // Node.js only + | "http2" // Node.js only + | "http" // Node.js only + | "mark" // available on the Web + | "measure" // available on the Web + | "net" // Node.js only + | "node" // Node.js only + | "resource"; // available on the Web + interface NodeGCPerformanceDetail { + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.kind` property identifies + * the type of garbage collection operation that occurred. + * See perf_hooks.constants for valid values. + */ + readonly kind: number; + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` + * property contains additional information about garbage collection operation. + * See perf_hooks.constants for valid values. + */ + readonly flags: number; + } + /** + * The constructor of this class is not exposed to users directly. + * @since v8.5.0 + */ + class PerformanceEntry { + protected constructor(); + /** + * The total number of milliseconds elapsed for this entry. This value will not + * be meaningful for all Performance Entry types. + * @since v8.5.0 + */ + readonly duration: number; + /** + * The name of the performance entry. + * @since v8.5.0 + */ + readonly name: string; + /** + * The high resolution millisecond timestamp marking the starting time of the + * Performance Entry. + * @since v8.5.0 + */ + readonly startTime: number; + /** + * The type of the performance entry. It may be one of: + * + * * `'node'` (Node.js only) + * * `'mark'` (available on the Web) + * * `'measure'` (available on the Web) + * * `'gc'` (Node.js only) + * * `'function'` (Node.js only) + * * `'http2'` (Node.js only) + * * `'http'` (Node.js only) + * @since v8.5.0 + */ + readonly entryType: EntryType; + toJSON(): any; + } + /** + * Exposes marks created via the `Performance.mark()` method. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMark extends PerformanceEntry { + readonly detail: any; + readonly duration: 0; + readonly entryType: "mark"; + } + /** + * Exposes measures created via the `Performance.measure()` method. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMeasure extends PerformanceEntry { + readonly detail: any; + readonly entryType: "measure"; + } + interface UVMetrics { + /** + * Number of event loop iterations. + */ + readonly loopCount: number; + /** + * Number of events that have been processed by the event handler. + */ + readonly events: number; + /** + * Number of events that were waiting to be processed when the event provider was called. + */ + readonly eventsWaiting: number; + } + // TODO: PerformanceNodeEntry is missing + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Provides timing details for Node.js itself. The constructor of this class + * is not exposed to users. + * @since v8.5.0 + */ + class PerformanceNodeTiming extends PerformanceEntry { + readonly entryType: "node"; + /** + * The high resolution millisecond timestamp at which the Node.js process + * completed bootstrapping. If bootstrapping has not yet finished, the property + * has the value of -1. + * @since v8.5.0 + */ + readonly bootstrapComplete: number; + /** + * The high resolution millisecond timestamp at which the Node.js environment was + * initialized. + * @since v8.5.0 + */ + readonly environment: number; + /** + * The high resolution millisecond timestamp of the amount of time the event loop + * has been idle within the event loop's event provider (e.g. `epoll_wait`). This + * does not take CPU usage into consideration. If the event loop has not yet + * started (e.g., in the first tick of the main script), the property has the + * value of 0. + * @since v14.10.0, v12.19.0 + */ + readonly idleTime: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * exited. If the event loop has not yet exited, the property has the value of -1\. + * It can only have a value of not -1 in a handler of the `'exit'` event. + * @since v8.5.0 + */ + readonly loopExit: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * started. If the event loop has not yet started (e.g., in the first tick of the + * main script), the property has the value of -1. + * @since v8.5.0 + */ + readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + * @since v8.5.0 + */ + readonly nodeStart: number; + /** + * This is a wrapper to the `uv_metrics_info` function. + * It returns the current set of event loop metrics. + * + * It is recommended to use this property inside a function whose execution was + * scheduled using `setImmediate` to avoid collecting metrics before finishing all + * operations scheduled during the current loop iteration. + * @since v22.8.0, v20.18.0 + */ + readonly uvMetricsInfo: UVMetrics; + /** + * The high resolution millisecond timestamp at which the V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + /** + * @param utilization1 The result of a previous call to `eventLoopUtilization()`. + * @param utilization2 The result of a previous call to `eventLoopUtilization()` prior to `utilization1`. + */ + type EventLoopUtilityFunction = ( + utilization1?: EventLoopUtilization, + utilization2?: EventLoopUtilization, + ) => EventLoopUtilization; + interface MarkOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * An optional timestamp to be used as the mark time. + * @default `performance.now()` + */ + startTime?: number | undefined; + } + interface MeasureOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown; + /** + * Duration between start and end times. + */ + duration?: number | undefined; + /** + * Timestamp to be used as the end time, or a string identifying a previously recorded mark. + */ + end?: number | string | undefined; + /** + * Timestamp to be used as the start time, or a string identifying a previously recorded mark. + */ + start?: number | string | undefined; + } + interface TimerifyOptions { + /** + * A histogram object created using `perf_hooks.createHistogram()` that will record runtime + * durations in nanoseconds. + */ + histogram?: RecordableHistogram | undefined; + } + interface Performance { + /** + * If `name` is not provided, removes all `PerformanceMark` objects from the Performance Timeline. + * If `name` is provided, removes only the named mark. + * @since v8.5.0 + */ + clearMarks(name?: string): void; + /** + * If `name` is not provided, removes all `PerformanceMeasure` objects from the Performance Timeline. + * If `name` is provided, removes only the named measure. + * @since v16.7.0 + */ + clearMeasures(name?: string): void; + /** + * If `name` is not provided, removes all `PerformanceResourceTiming` objects from the Resource Timeline. + * If `name` is provided, removes only the named resource. + * @since v18.2.0, v16.17.0 + */ + clearResourceTimings(name?: string): void; + /** + * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. + * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). + * No other CPU idle time is taken into consideration. + */ + eventLoopUtilization: EventLoopUtilityFunction; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. + * If you are only interested in performance entries of certain types or that have certain names, see + * `performance.getEntriesByType()` and `performance.getEntriesByName()`. + * @since v16.7.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.name` is equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to `type`. + * @param name + * @param type + * @since v16.7.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.entryType` is equal to `type`. + * @param type + * @since v16.7.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + /** + * Creates a new `PerformanceMark` entry in the Performance Timeline. + * A `PerformanceMark` is a subclass of `PerformanceEntry` whose `performanceEntry.entryType` is always `'mark'`, + * and whose `performanceEntry.duration` is always `0`. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * + * The created `PerformanceMark` entry is put in the global Performance Timeline and can be queried with + * `performance.getEntries`, `performance.getEntriesByName`, and `performance.getEntriesByType`. When the observation is + * performed, the entries should be cleared from the global Performance Timeline manually with `performance.clearMarks`. + * @param name + */ + mark(name: string, options?: MarkOptions): PerformanceMark; + /** + * Creates a new `PerformanceResourceTiming` entry in the Resource Timeline. + * A `PerformanceResourceTiming` is a subclass of `PerformanceEntry` whose `performanceEntry.entryType` is always `'resource'`. + * Performance resources are used to mark moments in the Resource Timeline. + * @param timingInfo [Fetch Timing Info](https://fetch.spec.whatwg.org/#fetch-timing-info) + * @param requestedUrl The resource url + * @param initiatorType The initiator name, e.g: 'fetch' + * @param global + * @param cacheMode The cache mode must be an empty string ('') or 'local' + * @param bodyInfo [Fetch Response Body Info](https://fetch.spec.whatwg.org/#response-body-info) + * @param responseStatus The response's status code + * @param deliveryType The delivery type. Default: ''. + * @since v18.2.0, v16.17.0 + */ + markResourceTiming( + timingInfo: object, + requestedUrl: string, + initiatorType: string, + global: object, + cacheMode: "" | "local", + bodyInfo: object, + responseStatus: number, + deliveryType?: string, + ): PerformanceResourceTiming; + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + * @return The PerformanceMeasure entry that was created + */ + measure(name: string, startMark?: string, endMark?: string): PerformanceMeasure; + measure(name: string, options: MeasureOptions): PerformanceMeasure; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * An instance of the `PerformanceNodeTiming` class that provides performance metrics for specific Node.js operational milestones. + * @since v8.5.0 + */ + readonly nodeTiming: PerformanceNodeTiming; + /** + * Returns the current high resolution millisecond timestamp, where 0 represents the start of the current `node` process. + * @since v8.5.0 + */ + now(): number; + /** + * Sets the global performance resource timing buffer size to the specified number of "resource" type performance entry objects. + * + * By default the max buffer size is set to 250. + * @since v18.8.0 + */ + setResourceTimingBufferSize(maxSize: number): void; + /** + * The [`timeOrigin`](https://w3c.github.io/hr-time/#dom-performance-timeorigin) specifies the high resolution millisecond timestamp + * at which the current `node` process began, measured in Unix time. + * @since v8.5.0 + */ + readonly timeOrigin: number; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Wraps a function within a new function that measures the running time of the wrapped function. + * A `PerformanceObserver` must be subscribed to the `'function'` event type in order for the timing details to be accessed. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * function someFunction() { + * console.log('hello world'); + * } + * + * const wrapped = performance.timerify(someFunction); + * + * const obs = new PerformanceObserver((list) => { + * console.log(list.getEntries()[0].duration); + * + * performance.clearMarks(); + * performance.clearMeasures(); + * obs.disconnect(); + * }); + * obs.observe({ entryTypes: ['function'] }); + * + * // A performance timeline entry will be created + * wrapped(); + * ``` + * + * If the wrapped function returns a promise, a finally handler will be attached to the promise and the duration will be reported + * once the finally handler is invoked. + * @param fn + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + /** + * An object which is JSON representation of the performance object. It is similar to + * [`window.performance.toJSON`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/toJSON) in browsers. + * @since v16.1.0 + */ + toJSON(): any; + } + class PerformanceObserverEntryList { + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime`. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0, + * * detail: null + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is + * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ entryTypes: ['mark', 'measure'] }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType` is equal to `type`. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0, + * * detail: null + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + } + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + /** + * @since v8.5.0 + */ + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + /** + * Disconnects the `PerformanceObserver` instance from all notifications. + * @since v8.5.0 + */ + disconnect(): void; + /** + * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes` or `options.type`: + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((list, observer) => { + * // Called once asynchronously. `list` contains three items. + * }); + * obs.observe({ type: 'mark' }); + * + * for (let n = 0; n < 3; n++) + * performance.mark(`test${n}`); + * ``` + * @since v8.5.0 + */ + observe( + options: + | { + entryTypes: readonly EntryType[]; + buffered?: boolean | undefined; + } + | { + type: EntryType; + buffered?: boolean | undefined; + }, + ): void; + /** + * @since v16.0.0 + * @returns Current list of entries stored in the performance observer, emptying it out. + */ + takeRecords(): PerformanceEntry[]; + } + /** + * Provides detailed network timing data regarding the loading of an application's resources. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceResourceTiming extends PerformanceEntry { + readonly entryType: "resource"; + protected constructor(); + /** + * The high resolution millisecond timestamp at immediately before dispatching the `fetch` + * request. If the resource is not intercepted by a worker the property will always return 0. + * @since v18.2.0, v16.17.0 + */ + readonly workerStart: number; + /** + * The high resolution millisecond timestamp that represents the start time of the fetch which + * initiates the redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectStart: number; + /** + * The high resolution millisecond timestamp that will be created immediately after receiving + * the last byte of the response of the last redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectEnd: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts to fetch the resource. + * @since v18.2.0, v16.17.0 + */ + readonly fetchStart: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts the domain name lookup + * for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after the Node.js finished + * the domain name lookup for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts to + * establish the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js finishes + * establishing the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts the + * handshake process to secure the current connection. + * @since v18.2.0, v16.17.0 + */ + readonly secureConnectionStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js receives the + * first byte of the response from the server. + * @since v18.2.0, v16.17.0 + */ + readonly requestStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js receives the + * last byte of the resource or immediately before the transport connection is closed, whichever comes first. + * @since v18.2.0, v16.17.0 + */ + readonly responseEnd: number; + /** + * A number representing the size (in octets) of the fetched resource. The size includes the response header + * fields plus the response payload body. + * @since v18.2.0, v16.17.0 + */ + readonly transferSize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the payload body, before + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly encodedBodySize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the message body, after + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly decodedBodySize: number; + /** + * Returns a `object` that is the JSON representation of the `PerformanceResourceTiming` object + * @since v18.2.0, v16.17.0 + */ + toJSON(): any; + } + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + const NODE_PERFORMANCE_GC_FLAGS_NO: number; + const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; + const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; + const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; + const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; + } + const performance: Performance; + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number | undefined; + } + interface Histogram { + /** + * The number of samples recorded by the histogram. + * @since v17.4.0, v16.14.0 + */ + readonly count: number; + /** + * The number of samples recorded by the histogram. + * v17.4.0, v16.14.0 + */ + readonly countBigInt: bigint; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event + * loop delay threshold. + * @since v11.10.0 + */ + readonly exceeds: number; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold. + * @since v17.4.0, v16.14.0 + */ + readonly exceedsBigInt: bigint; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The maximum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly maxBigInt: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The minimum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly minBigInt: bigint; + /** + * Returns the value at the given percentile. + * @since v11.10.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentile(percentile: number): number; + /** + * Returns the value at the given percentile. + * @since v17.4.0, v16.14.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentileBigInt(percentile: number): bigint; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v17.4.0, v16.14.0 + */ + readonly percentilesBigInt: Map; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + } + interface IntervalHistogram extends Histogram { + /** + * Enables the update interval timer. Returns `true` if the timer was + * started, `false` if it was already started. + * @since v11.10.0 + */ + enable(): boolean; + /** + * Disables the update interval timer. Returns `true` if the timer was + * stopped, `false` if it was already stopped. + * @since v11.10.0 + */ + disable(): boolean; + } + interface RecordableHistogram extends Histogram { + /** + * @since v15.9.0, v14.18.0 + * @param val The amount to record in the histogram. + */ + record(val: number | bigint): void; + /** + * Calculates the amount of time (in nanoseconds) that has passed since the + * previous call to `recordDelta()` and records that amount in the histogram. + * @since v15.9.0, v14.18.0 + */ + recordDelta(): void; + /** + * Adds the values from `other` to this histogram. + * @since v17.4.0, v16.14.0 + */ + add(other: RecordableHistogram): void; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Creates an `IntervalHistogram` object that samples and reports the event loop + * delay over time. The delays will be reported in nanoseconds. + * + * Using a timer to detect approximate event loop delay works because the + * execution of timers is tied specifically to the lifecycle of the libuv + * event loop. That is, a delay in the loop will cause a delay in the execution + * of the timer, and those delays are specifically what this API is intended to + * detect. + * + * ```js + * import { monitorEventLoopDelay } from 'node:perf_hooks'; + * const h = monitorEventLoopDelay({ resolution: 20 }); + * h.enable(); + * // Do something. + * h.disable(); + * console.log(h.min); + * console.log(h.max); + * console.log(h.mean); + * console.log(h.stddev); + * console.log(h.percentiles); + * console.log(h.percentile(50)); + * console.log(h.percentile(99)); + * ``` + * @since v11.10.0 + */ + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + interface CreateHistogramOptions { + /** + * The minimum recordable value. Must be an integer value greater than 0. + * @default 1 + */ + lowest?: number | bigint | undefined; + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + highest?: number | bigint | undefined; + /** + * The number of accuracy digits. Must be a number between 1 and 5. + * @default 3 + */ + figures?: number | undefined; + } + /** + * Returns a `RecordableHistogram`. + * @since v15.9.0, v14.18.0 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; + import { + performance as _performance, + PerformanceEntry as _PerformanceEntry, + PerformanceMark as _PerformanceMark, + PerformanceMeasure as _PerformanceMeasure, + PerformanceObserver as _PerformanceObserver, + PerformanceObserverEntryList as _PerformanceObserverEntryList, + PerformanceResourceTiming as _PerformanceResourceTiming, + } from "perf_hooks"; + global { + /** + * `PerformanceEntry` is a global reference for `import { PerformanceEntry } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performanceentry + * @since v19.0.0 + */ + var PerformanceEntry: typeof globalThis extends { + onmessage: any; + PerformanceEntry: infer T; + } ? T + : typeof _PerformanceEntry; + /** + * `PerformanceMark` is a global reference for `import { PerformanceMark } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performancemark + * @since v19.0.0 + */ + var PerformanceMark: typeof globalThis extends { + onmessage: any; + PerformanceMark: infer T; + } ? T + : typeof _PerformanceMark; + /** + * `PerformanceMeasure` is a global reference for `import { PerformanceMeasure } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performancemeasure + * @since v19.0.0 + */ + var PerformanceMeasure: typeof globalThis extends { + onmessage: any; + PerformanceMeasure: infer T; + } ? T + : typeof _PerformanceMeasure; + /** + * `PerformanceObserver` is a global reference for `import { PerformanceObserver } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performanceobserver + * @since v19.0.0 + */ + var PerformanceObserver: typeof globalThis extends { + onmessage: any; + PerformanceObserver: infer T; + } ? T + : typeof _PerformanceObserver; + /** + * `PerformanceObserverEntryList` is a global reference for `import { PerformanceObserverEntryList } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performanceobserverentrylist + * @since v19.0.0 + */ + var PerformanceObserverEntryList: typeof globalThis extends { + onmessage: any; + PerformanceObserverEntryList: infer T; + } ? T + : typeof _PerformanceObserverEntryList; + /** + * `PerformanceResourceTiming` is a global reference for `import { PerformanceResourceTiming } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performanceresourcetiming + * @since v19.0.0 + */ + var PerformanceResourceTiming: typeof globalThis extends { + onmessage: any; + PerformanceResourceTiming: infer T; + } ? T + : typeof _PerformanceResourceTiming; + /** + * `performance` is a global reference for `import { performance } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performance + * @since v16.0.0 + */ + var performance: typeof globalThis extends { + onmessage: any; + performance: infer T; + } ? T + : typeof _performance; + } +} +declare module "node:perf_hooks" { + export * from "perf_hooks"; +} diff --git a/node_modules/@types/node/process.d.ts b/node_modules/@types/node/process.d.ts new file mode 100644 index 0000000..368da9d --- /dev/null +++ b/node_modules/@types/node/process.d.ts @@ -0,0 +1,2070 @@ +declare module "process" { + import { Control, MessageOptions, SendHandle } from "node:child_process"; + import { PathLike } from "node:fs"; + import * as tty from "node:tty"; + import { Worker } from "node:worker_threads"; + + interface BuiltInModule { + "assert": typeof import("assert"); + "node:assert": typeof import("node:assert"); + "assert/strict": typeof import("assert/strict"); + "node:assert/strict": typeof import("node:assert/strict"); + "async_hooks": typeof import("async_hooks"); + "node:async_hooks": typeof import("node:async_hooks"); + "buffer": typeof import("buffer"); + "node:buffer": typeof import("node:buffer"); + "child_process": typeof import("child_process"); + "node:child_process": typeof import("node:child_process"); + "cluster": typeof import("cluster"); + "node:cluster": typeof import("node:cluster"); + "console": typeof import("console"); + "node:console": typeof import("node:console"); + "constants": typeof import("constants"); + "node:constants": typeof import("node:constants"); + "crypto": typeof import("crypto"); + "node:crypto": typeof import("node:crypto"); + "dgram": typeof import("dgram"); + "node:dgram": typeof import("node:dgram"); + "diagnostics_channel": typeof import("diagnostics_channel"); + "node:diagnostics_channel": typeof import("node:diagnostics_channel"); + "dns": typeof import("dns"); + "node:dns": typeof import("node:dns"); + "dns/promises": typeof import("dns/promises"); + "node:dns/promises": typeof import("node:dns/promises"); + "domain": typeof import("domain"); + "node:domain": typeof import("node:domain"); + "events": typeof import("events"); + "node:events": typeof import("node:events"); + "fs": typeof import("fs"); + "node:fs": typeof import("node:fs"); + "fs/promises": typeof import("fs/promises"); + "node:fs/promises": typeof import("node:fs/promises"); + "http": typeof import("http"); + "node:http": typeof import("node:http"); + "http2": typeof import("http2"); + "node:http2": typeof import("node:http2"); + "https": typeof import("https"); + "node:https": typeof import("node:https"); + "inspector": typeof import("inspector"); + "node:inspector": typeof import("node:inspector"); + "inspector/promises": typeof import("inspector/promises"); + "node:inspector/promises": typeof import("node:inspector/promises"); + "module": typeof import("module"); + "node:module": typeof import("node:module"); + "net": typeof import("net"); + "node:net": typeof import("node:net"); + "os": typeof import("os"); + "node:os": typeof import("node:os"); + "path": typeof import("path"); + "node:path": typeof import("node:path"); + "path/posix": typeof import("path/posix"); + "node:path/posix": typeof import("node:path/posix"); + "path/win32": typeof import("path/win32"); + "node:path/win32": typeof import("node:path/win32"); + "perf_hooks": typeof import("perf_hooks"); + "node:perf_hooks": typeof import("node:perf_hooks"); + "process": typeof import("process"); + "node:process": typeof import("node:process"); + "punycode": typeof import("punycode"); + "node:punycode": typeof import("node:punycode"); + "querystring": typeof import("querystring"); + "node:querystring": typeof import("node:querystring"); + "readline": typeof import("readline"); + "node:readline": typeof import("node:readline"); + "readline/promises": typeof import("readline/promises"); + "node:readline/promises": typeof import("node:readline/promises"); + "repl": typeof import("repl"); + "node:repl": typeof import("node:repl"); + "node:sea": typeof import("node:sea"); + "node:sqlite": typeof import("node:sqlite"); + "stream": typeof import("stream"); + "node:stream": typeof import("node:stream"); + "stream/consumers": typeof import("stream/consumers"); + "node:stream/consumers": typeof import("node:stream/consumers"); + "stream/promises": typeof import("stream/promises"); + "node:stream/promises": typeof import("node:stream/promises"); + "stream/web": typeof import("stream/web"); + "node:stream/web": typeof import("node:stream/web"); + "string_decoder": typeof import("string_decoder"); + "node:string_decoder": typeof import("node:string_decoder"); + "node:test": typeof import("node:test"); + "node:test/reporters": typeof import("node:test/reporters"); + "timers": typeof import("timers"); + "node:timers": typeof import("node:timers"); + "timers/promises": typeof import("timers/promises"); + "node:timers/promises": typeof import("node:timers/promises"); + "tls": typeof import("tls"); + "node:tls": typeof import("node:tls"); + "trace_events": typeof import("trace_events"); + "node:trace_events": typeof import("node:trace_events"); + "tty": typeof import("tty"); + "node:tty": typeof import("node:tty"); + "url": typeof import("url"); + "node:url": typeof import("node:url"); + "util": typeof import("util"); + "node:util": typeof import("node:util"); + "sys": typeof import("util"); + "node:sys": typeof import("node:util"); + "util/types": typeof import("util/types"); + "node:util/types": typeof import("node:util/types"); + "v8": typeof import("v8"); + "node:v8": typeof import("node:v8"); + "vm": typeof import("vm"); + "node:vm": typeof import("node:vm"); + "wasi": typeof import("wasi"); + "node:wasi": typeof import("node:wasi"); + "worker_threads": typeof import("worker_threads"); + "node:worker_threads": typeof import("node:worker_threads"); + "zlib": typeof import("zlib"); + "node:zlib": typeof import("node:zlib"); + } + global { + var process: NodeJS.Process; + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } + interface MemoryUsage { + /** + * Resident Set Size, is the amount of space occupied in the main memory device (that is a subset of the total allocated memory) for the + * process, including all C++ and JavaScript objects and code. + */ + rss: number; + /** + * Refers to V8's memory usage. + */ + heapTotal: number; + /** + * Refers to V8's memory usage. + */ + heapUsed: number; + external: number; + /** + * Refers to memory allocated for `ArrayBuffer`s and `SharedArrayBuffer`s, including all Node.js Buffers. This is also included + * in the external value. When Node.js is used as an embedded library, this value may be `0` because allocations for `ArrayBuffer`s + * may not be tracked in that case. + */ + arrayBuffers: number; + } + interface CpuUsage { + user: number; + system: number; + } + interface ProcessRelease { + name: string; + sourceUrl?: string | undefined; + headersUrl?: string | undefined; + libUrl?: string | undefined; + lts?: string | undefined; + } + interface ProcessFeatures { + /** + * A boolean value that is `true` if the current Node.js build is caching builtin modules. + * @since v12.0.0 + */ + readonly cached_builtins: boolean; + /** + * A boolean value that is `true` if the current Node.js build is a debug build. + * @since v0.5.5 + */ + readonly debug: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes the inspector. + * @since v11.10.0 + */ + readonly inspector: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for IPv6. + * + * Since all Node.js builds have IPv6 support, this value is always `true`. + * @since v0.5.3 + * @deprecated This property is always true, and any checks based on it are redundant. + */ + readonly ipv6: boolean; + /** + * A boolean value that is `true` if the current Node.js build supports + * [loading ECMAScript modules using `require()`](https://nodejs.org/docs/latest-v22.x/api/modules.md#loading-ecmascript-modules-using-require). + * @since v22.10.0 + */ + readonly require_module: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for TLS. + * @since v0.5.3 + */ + readonly tls: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for ALPN in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional ALPN support. + * This value is therefore identical to that of `process.features.tls`. + * @since v4.8.0 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_alpn: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for OCSP in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional OCSP support. + * This value is therefore identical to that of `process.features.tls`. + * @since v0.11.13 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_ocsp: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for SNI in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional SNI support. + * This value is therefore identical to that of `process.features.tls`. + * @since v0.5.3 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_sni: boolean; + /** + * A value that is `"strip"` by default, + * `"transform"` if Node.js is run with `--experimental-transform-types`, and `false` if + * Node.js is run with `--no-experimental-strip-types`. + * @since v22.10.0 + */ + readonly typescript: "strip" | "transform" | false; + /** + * A boolean value that is `true` if the current Node.js build includes support for libuv. + * + * Since it's not possible to build Node.js without libuv, this value is always `true`. + * @since v0.5.3 + * @deprecated This property is always true, and any checks based on it are redundant. + */ + readonly uv: boolean; + } + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + type Platform = + | "aix" + | "android" + | "darwin" + | "freebsd" + | "haiku" + | "linux" + | "openbsd" + | "sunos" + | "win32" + | "cygwin" + | "netbsd"; + type Architecture = + | "arm" + | "arm64" + | "ia32" + | "loong64" + | "mips" + | "mipsel" + | "ppc" + | "ppc64" + | "riscv64" + | "s390" + | "s390x" + | "x64"; + type Signals = + | "SIGABRT" + | "SIGALRM" + | "SIGBUS" + | "SIGCHLD" + | "SIGCONT" + | "SIGFPE" + | "SIGHUP" + | "SIGILL" + | "SIGINT" + | "SIGIO" + | "SIGIOT" + | "SIGKILL" + | "SIGPIPE" + | "SIGPOLL" + | "SIGPROF" + | "SIGPWR" + | "SIGQUIT" + | "SIGSEGV" + | "SIGSTKFLT" + | "SIGSTOP" + | "SIGSYS" + | "SIGTERM" + | "SIGTRAP" + | "SIGTSTP" + | "SIGTTIN" + | "SIGTTOU" + | "SIGUNUSED" + | "SIGURG" + | "SIGUSR1" + | "SIGUSR2" + | "SIGVTALRM" + | "SIGWINCH" + | "SIGXCPU" + | "SIGXFSZ" + | "SIGBREAK" + | "SIGLOST" + | "SIGINFO"; + type UncaughtExceptionOrigin = "uncaughtException" | "unhandledRejection"; + type MultipleResolveType = "resolve" | "reject"; + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void; + /** + * Most of the time the unhandledRejection will be an Error, but this should not be relied upon + * as *anything* can be thrown/rejected, it is therefore unsafe to assume that the value is an Error. + */ + type UnhandledRejectionListener = (reason: unknown, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: unknown, sendHandle: SendHandle) => void; + type SignalsListener = (signal: Signals) => void; + type MultipleResolveListener = ( + type: MultipleResolveType, + promise: Promise, + value: unknown, + ) => void; + type WorkerListener = (worker: Worker) => void; + interface Socket extends ReadWriteStream { + isTTY?: true | undefined; + } + // Alias for compatibility + interface ProcessEnv extends Dict { + /** + * Can be used to change the default timezone at runtime + */ + TZ?: string | undefined; + } + interface HRTime { + /** + * This is the legacy version of {@link process.hrtime.bigint()} + * before bigint was introduced in JavaScript. + * + * The `process.hrtime()` method returns the current high-resolution real time in a `[seconds, nanoseconds]` tuple `Array`, + * where `nanoseconds` is the remaining part of the real time that can't be represented in second precision. + * + * `time` is an optional parameter that must be the result of a previous `process.hrtime()` call to diff with the current time. + * If the parameter passed in is not a tuple `Array`, a TypeError will be thrown. + * Passing in a user-defined array instead of the result of a previous call to `process.hrtime()` will lead to undefined behavior. + * + * These times are relative to an arbitrary time in the past, + * and not related to the time of day and therefore not subject to clock drift. + * The primary use is for measuring performance between intervals: + * ```js + * const { hrtime } = require('node:process'); + * const NS_PER_SEC = 1e9; + * const time = hrtime(); + * // [ 1800216, 25 ] + * + * setTimeout(() => { + * const diff = hrtime(time); + * // [ 1, 552 ] + * + * console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`); + * // Benchmark took 1000000552 nanoseconds + * }, 1000); + * ``` + * @since 0.7.6 + * @legacy Use {@link process.hrtime.bigint()} instead. + * @param time The result of a previous call to `process.hrtime()` + */ + (time?: [number, number]): [number, number]; + /** + * The `bigint` version of the {@link process.hrtime()} method returning the current high-resolution real time in nanoseconds as a `bigint`. + * + * Unlike {@link process.hrtime()}, it does not support an additional time argument since the difference can just be computed directly by subtraction of the two `bigint`s. + * ```js + * import { hrtime } from 'node:process'; + * + * const start = hrtime.bigint(); + * // 191051479007711n + * + * setTimeout(() => { + * const end = hrtime.bigint(); + * // 191052633396993n + * + * console.log(`Benchmark took ${end - start} nanoseconds`); + * // Benchmark took 1154389282 nanoseconds + * }, 1000); + * ``` + * @since v10.7.0 + */ + bigint(): bigint; + } + interface ProcessPermission { + /** + * Verifies that the process is able to access the given scope and reference. + * If no reference is provided, a global scope is assumed, for instance, `process.permission.has('fs.read')` + * will check if the process has ALL file system read permissions. + * + * The reference has a meaning based on the provided scope. For example, the reference when the scope is File System means files and folders. + * + * The available scopes are: + * + * * `fs` - All File System + * * `fs.read` - File System read operations + * * `fs.write` - File System write operations + * * `child` - Child process spawning operations + * * `worker` - Worker thread spawning operation + * + * ```js + * // Check if the process has permission to read the README file + * process.permission.has('fs.read', './README.md'); + * // Check if the process has read permission operations + * process.permission.has('fs.read'); + * ``` + * @since v20.0.0 + */ + has(scope: string, reference?: string): boolean; + } + interface ProcessReport { + /** + * Write reports in a compact format, single-line JSON, more easily consumable by log processing systems + * than the default multi-line format designed for human consumption. + * @since v13.12.0, v12.17.0 + */ + compact: boolean; + /** + * Directory where the report is written. + * The default value is the empty string, indicating that reports are written to the current + * working directory of the Node.js process. + */ + directory: string; + /** + * Filename where the report is written. If set to the empty string, the output filename will be comprised + * of a timestamp, PID, and sequence number. The default value is the empty string. + */ + filename: string; + /** + * Returns a JavaScript Object representation of a diagnostic report for the running process. + * The report's JavaScript stack trace is taken from `err`, if present. + */ + getReport(err?: Error): object; + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @default false + */ + reportOnSignal: boolean; + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from `err`, if present. + * + * If the value of filename is set to `'stdout'` or `'stderr'`, the report is written + * to the stdout or stderr of the process respectively. + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param err A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string, err?: Error): string; + writeReport(err?: Error): string; + } + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string | undefined; + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string | undefined; + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function | undefined; + /** + * Additional text to include with the error. + */ + detail?: string | undefined; + } + interface ProcessConfig { + readonly target_defaults: { + readonly cflags: any[]; + readonly default_configuration: string; + readonly defines: string[]; + readonly include_dirs: string[]; + readonly libraries: string[]; + }; + readonly variables: { + readonly clang: number; + readonly host_arch: string; + readonly node_install_npm: boolean; + readonly node_install_waf: boolean; + readonly node_prefix: string; + readonly node_shared_openssl: boolean; + readonly node_shared_v8: boolean; + readonly node_shared_zlib: boolean; + readonly node_use_dtrace: boolean; + readonly node_use_etw: boolean; + readonly node_use_openssl: boolean; + readonly target_arch: string; + readonly v8_no_strict_aliasing: number; + readonly v8_use_snapshot: boolean; + readonly visibility: string; + }; + } + interface Process extends EventEmitter { + /** + * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is + * a `Writable` stream. + * + * For example, to copy `process.stdin` to `process.stdout`: + * + * ```js + * import { stdin, stdout } from 'node:process'; + * + * stdin.pipe(stdout); + * ``` + * + * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is + * a `Writable` stream. + * + * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stderr: WriteStream & { + fd: 2; + }; + /** + * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is + * a `Readable` stream. + * + * For details of how to read from `stdin` see `readable.read()`. + * + * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that + * is compatible with scripts written for Node.js prior to v0.10\. + * For more information see `Stream compatibility`. + * + * In "old" streams mode the `stdin` stream is paused by default, so one + * must call `process.stdin.resume()` to read from it. Note also that calling `process.stdin.resume()` itself would switch stream to "old" mode. + */ + stdin: ReadStream & { + fd: 0; + }; + /** + * The `process.argv` property returns an array containing the command-line + * arguments passed when the Node.js process was launched. The first element will + * be {@link execPath}. See `process.argv0` if access to the original value + * of `argv[0]` is needed. The second element will be the path to the JavaScript + * file being executed. The remaining elements will be any additional command-line + * arguments. + * + * For example, assuming the following script for `process-args.js`: + * + * ```js + * import { argv } from 'node:process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```bash + * node process-args.js one two=three four + * ``` + * + * Would generate the output: + * + * ```text + * 0: /usr/local/bin/node + * 1: /Users/mjr/work/node/process-args.js + * 2: one + * 3: two=three + * 4: four + * ``` + * @since v0.1.27 + */ + argv: string[]; + /** + * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. + * + * ```console + * $ bash -c 'exec -a customArgv0 ./node' + * > process.argv[0] + * '/Volumes/code/external/node/out/Release/node' + * > process.argv0 + * 'customArgv0' + * ``` + * @since v6.4.0 + */ + argv0: string; + /** + * The `process.execArgv` property returns the set of Node.js-specific command-line + * options passed when the Node.js process was launched. These options do not + * appear in the array returned by the {@link argv} property, and do not + * include the Node.js executable, the name of the script, or any options following + * the script name. These options are useful in order to spawn child processes with + * the same execution environment as the parent. + * + * ```bash + * node --icu-data-dir=./foo --require ./bar.js script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ["--icu-data-dir=./foo", "--require", "./bar.js"] + * ``` + * + * And `process.argv`: + * + * ```js + * ['/usr/local/bin/node', 'script.js', '--version'] + * ``` + * + * Refer to `Worker constructor` for the detailed behavior of worker + * threads with this property. + * @since v0.7.7 + */ + execArgv: string[]; + /** + * The `process.execPath` property returns the absolute pathname of the executable + * that started the Node.js process. Symbolic links, if any, are resolved. + * + * ```js + * '/usr/local/bin/node' + * ``` + * @since v0.1.100 + */ + execPath: string; + /** + * The `process.abort()` method causes the Node.js process to exit immediately and + * generate a core file. + * + * This feature is not available in `Worker` threads. + * @since v0.7.0 + */ + abort(): never; + /** + * The `process.chdir()` method changes the current working directory of the + * Node.js process or throws an exception if doing so fails (for instance, if + * the specified `directory` does not exist). + * + * ```js + * import { chdir, cwd } from 'node:process'; + * + * console.log(`Starting directory: ${cwd()}`); + * try { + * chdir('/tmp'); + * console.log(`New directory: ${cwd()}`); + * } catch (err) { + * console.error(`chdir: ${err}`); + * } + * ``` + * + * This feature is not available in `Worker` threads. + * @since v0.1.17 + */ + chdir(directory: string): void; + /** + * The `process.cwd()` method returns the current working directory of the Node.js + * process. + * + * ```js + * import { cwd } from 'node:process'; + * + * console.log(`Current directory: ${cwd()}`); + * ``` + * @since v0.1.8 + */ + cwd(): string; + /** + * The port used by the Node.js debugger when enabled. + * + * ```js + * import process from 'node:process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * The `process.dlopen()` method allows dynamically loading shared objects. It is primarily used by `require()` to load C++ Addons, and + * should not be used directly, except in special cases. In other words, `require()` should be preferred over `process.dlopen()` + * unless there are specific reasons such as custom dlopen flags or loading from ES modules. + * + * The `flags` argument is an integer that allows to specify dlopen behavior. See the `[os.constants.dlopen](https://nodejs.org/docs/latest-v22.x/api/os.html#dlopen-constants)` + * documentation for details. + * + * An important requirement when calling `process.dlopen()` is that the `module` instance must be passed. Functions exported by the C++ Addon + * are then accessible via `module.exports`. + * + * The example below shows how to load a C++ Addon, named `local.node`, that exports a `foo` function. All the symbols are loaded before the call returns, by passing the `RTLD_NOW` constant. + * In this example the constant is assumed to be available. + * + * ```js + * import { dlopen } from 'node:process'; + * import { constants } from 'node:os'; + * import { fileURLToPath } from 'node:url'; + * + * const module = { exports: {} }; + * dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)), + * constants.dlopen.RTLD_NOW); + * module.exports.foo(); + * ``` + */ + dlopen(module: object, filename: string, flags?: number): void; + /** + * The `process.emitWarning()` method can be used to emit custom or application + * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string. + * emitWarning('Something happened!'); + * // Emits: (node: 56338) Warning: Something happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string and a type. + * emitWarning('Something Happened!', 'CustomWarning'); + * // Emits: (node:56338) CustomWarning: Something Happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * emitWarning('Something happened!', 'CustomWarning', 'WARN001'); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ```js + * + * In each of the previous examples, an `Error` object is generated internally by `process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'node:process'; + * + * process.on('warning', (warning) => { + * console.warn(warning.name); // 'Warning' + * console.warn(warning.message); // 'Something happened!' + * console.warn(warning.code); // 'MY_WARNING' + * console.warn(warning.stack); // Stack trace + * console.warn(warning.detail); // 'This is some additional information' + * }); + * ``` + * + * If `warning` is passed as an `Error` object, it will be passed through to the `'warning'` event handler + * unmodified (and the optional `type`, `code` and `ctor` arguments will be ignored): + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using an Error object. + * const myWarning = new Error('Something happened!'); + * // Use the Error name property to specify the type name + * myWarning.name = 'CustomWarning'; + * myWarning.code = 'WARN001'; + * + * emitWarning(myWarning); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ``` + * + * A `TypeError` is thrown if `warning` is anything other than a string or `Error` object. + * + * While process warnings use `Error` objects, the process warning mechanism is not a replacement for normal error handling mechanisms. + * + * The following additional handling is implemented if the warning `type` is `'DeprecationWarning'`: + * * If the `--throw-deprecation` command-line flag is used, the deprecation warning is thrown as an exception rather than being emitted as an event. + * * If the `--no-deprecation` command-line flag is used, the deprecation warning is suppressed. + * * If the `--trace-deprecation` command-line flag is used, the deprecation warning is printed to `stderr` along with the full stack trace. + * @since v8.0.0 + * @param warning The warning to emit. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + /** + * The `process.env` property returns an object containing the user environment. + * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). + * + * An example of this object looks like: + * + * ```js + * { + * TERM: 'xterm-256color', + * SHELL: '/usr/local/bin/bash', + * USER: 'maciej', + * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', + * PWD: '/Users/maciej', + * EDITOR: 'vim', + * SHLVL: '1', + * HOME: '/Users/maciej', + * LOGNAME: 'maciej', + * _: '/usr/local/bin/node' + * } + * ``` + * + * It is possible to modify this object, but such modifications will not be + * reflected outside the Node.js process, or (unless explicitly requested) + * to other `Worker` threads. + * In other words, the following example would not work: + * + * ```bash + * node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'node:process'; + * + * env.foo = 'bar'; + * console.log(env.foo); + * ``` + * + * Assigning a property on `process.env` will implicitly convert the value + * to a string. **This behavior is deprecated.** Future versions of Node.js may + * throw an error when the value is not a string, number, or boolean. + * + * ```js + * import { env } from 'node:process'; + * + * env.test = null; + * console.log(env.test); + * // => 'null' + * env.test = undefined; + * console.log(env.test); + * // => 'undefined' + * ``` + * + * Use `delete` to delete a property from `process.env`. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * delete env.TEST; + * console.log(env.TEST); + * // => undefined + * ``` + * + * On Windows operating systems, environment variables are case-insensitive. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * console.log(env.test); + * // => 1 + * ``` + * + * Unless explicitly specified when creating a `Worker` instance, + * each `Worker` thread has its own copy of `process.env`, based on its + * parent thread's `process.env`, or whatever was specified as the `env` option + * to the `Worker` constructor. Changes to `process.env` will not be visible + * across `Worker` threads, and only the main thread can make changes that + * are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner + * unlike the main thread. + * @since v0.1.27 + */ + env: ProcessEnv; + /** + * The `process.exit()` method instructs Node.js to terminate the process + * synchronously with an exit status of `code`. If `code` is omitted, exit uses + * either the 'success' code `0` or the value of `process.exitCode` if it has been + * set. Node.js will not terminate until all the `'exit'` event listeners are + * called. + * + * To exit with a 'failure' code: + * + * ```js + * import { exit } from 'node:process'; + * + * exit(1); + * ``` + * + * The shell that executed Node.js should see the exit code as `1`. + * + * Calling `process.exit()` will force the process to exit as quickly as possible + * even if there are still asynchronous operations pending that have not yet + * completed fully, including I/O operations to `process.stdout` and `process.stderr`. + * + * In most situations, it is not actually necessary to call `process.exit()` explicitly. The Node.js process will exit on its own _if there is no additional_ + * _work pending_ in the event loop. The `process.exitCode` property can be set to + * tell the process which exit code to use when the process exits gracefully. + * + * For instance, the following example illustrates a _misuse_ of the `process.exit()` method that could lead to data printed to stdout being + * truncated and lost: + * + * ```js + * import { exit } from 'node:process'; + * + * // This is an example of what *not* to do: + * if (someConditionNotMet()) { + * printUsageToStdout(); + * exit(1); + * } + * ``` + * + * The reason this is problematic is because writes to `process.stdout` in Node.js + * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js + * event loop. Calling `process.exit()`, however, forces the process to exit _before_ those additional writes to `stdout` can be performed. + * + * Rather than calling `process.exit()` directly, the code _should_ set the `process.exitCode` and allow the process to exit naturally by avoiding + * scheduling any additional work for the event loop: + * + * ```js + * import process from 'node:process'; + * + * // How to properly set the exit code while letting + * // the process exit gracefully. + * if (someConditionNotMet()) { + * printUsageToStdout(); + * process.exitCode = 1; + * } + * ``` + * + * If it is necessary to terminate the Node.js process due to an error condition, + * throwing an _uncaught_ error and allowing the process to terminate accordingly + * is safer than calling `process.exit()`. + * + * In `Worker` threads, this function stops the current thread rather + * than the current process. + * @since v0.1.13 + * @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed. + */ + exit(code?: number | string | null): never; + /** + * A number which will be the process exit code, when the process either + * exits gracefully, or is exited via {@link exit} without specifying + * a code. + * + * Specifying a code to {@link exit} will override any + * previous setting of `process.exitCode`. + * @default undefined + * @since v0.11.8 + */ + exitCode: number | string | null | undefined; + finalization: { + /** + * This function registers a callback to be called when the process emits the `exit` event if the `ref` object was not garbage collected. + * If the object `ref` was garbage collected before the `exit` event is emitted, the callback will be removed from the finalization registry, and it will not be called on process exit. + * + * Inside the callback you can release the resources allocated by the `ref` object. + * Be aware that all limitations applied to the `beforeExit` event are also applied to the callback function, + * this means that there is a possibility that the callback will not be called under special circumstances. + * + * The idea of ​​this function is to help you free up resources when the starts process exiting, but also let the object be garbage collected if it is no longer being used. + * @param ref The reference to the resource that is being tracked. + * @param callback The callback function to be called when the resource is finalized. + * @since v22.5.0 + * @experimental + */ + register(ref: T, callback: (ref: T, event: "exit") => void): void; + /** + * This function behaves exactly like the `register`, except that the callback will be called when the process emits the `beforeExit` event if `ref` object was not garbage collected. + * + * Be aware that all limitations applied to the `beforeExit` event are also applied to the callback function, this means that there is a possibility that the callback will not be called under special circumstances. + * @param ref The reference to the resource that is being tracked. + * @param callback The callback function to be called when the resource is finalized. + * @since v22.5.0 + * @experimental + */ + registerBeforeExit(ref: T, callback: (ref: T, event: "beforeExit") => void): void; + /** + * This function remove the register of the object from the finalization registry, so the callback will not be called anymore. + * @param ref The reference to the resource that was registered previously. + * @since v22.5.0 + * @experimental + */ + unregister(ref: object): void; + }; + /** + * The `process.getActiveResourcesInfo()` method returns an array of strings containing + * the types of the active resources that are currently keeping the event loop alive. + * + * ```js + * import { getActiveResourcesInfo } from 'node:process'; + * import { setTimeout } from 'node:timers'; + + * console.log('Before:', getActiveResourcesInfo()); + * setTimeout(() => {}, 1000); + * console.log('After:', getActiveResourcesInfo()); + * // Prints: + * // Before: [ 'TTYWrap', 'TTYWrap', 'TTYWrap' ] + * // After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ] + * ``` + * @since v17.3.0, v16.14.0 + */ + getActiveResourcesInfo(): string[]; + /** + * Provides a way to load built-in modules in a globally available function. + * @param id ID of the built-in module being requested. + */ + getBuiltinModule(id: ID): BuiltInModule[ID]; + getBuiltinModule(id: string): object | undefined; + /** + * The `process.getgid()` method returns the numerical group identity of the + * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid) { + * console.log(`Current gid: ${process.getgid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.31 + */ + getgid?: () => number; + /** + * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a + * numeric ID or a group name + * string. If a group name is specified, this method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid && process.setgid) { + * console.log(`Current gid: ${process.getgid()}`); + * try { + * process.setgid(501); + * console.log(`New gid: ${process.getgid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.31 + * @param id The group name or ID + */ + setgid?: (id: number | string) => void; + /** + * The `process.getuid()` method returns the numeric user identity of the process. + * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid) { + * console.log(`Current uid: ${process.getuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.28 + */ + getuid?: () => number; + /** + * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a + * numeric ID or a username string. + * If a username is specified, the method blocks while resolving the associated + * numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid && process.setuid) { + * console.log(`Current uid: ${process.getuid()}`); + * try { + * process.setuid(501); + * console.log(`New uid: ${process.getuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.28 + */ + setuid?: (id: number | string) => void; + /** + * The `process.geteuid()` method returns the numerical effective user identity of + * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + geteuid?: () => number; + /** + * The `process.seteuid()` method sets the effective user identity of the process. + * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username + * string. If a username is specified, the method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid && process.seteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * try { + * process.seteuid(501); + * console.log(`New uid: ${process.geteuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A user name or ID + */ + seteuid?: (id: number | string) => void; + /** + * The `process.getegid()` method returns the numerical effective group identity + * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid) { + * console.log(`Current gid: ${process.getegid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + getegid?: () => number; + /** + * The `process.setegid()` method sets the effective group identity of the process. + * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group + * name string. If a group name is specified, this method blocks while resolving + * the associated a numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid && process.setegid) { + * console.log(`Current gid: ${process.getegid()}`); + * try { + * process.setegid(501); + * console.log(`New gid: ${process.getegid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A group name or ID + */ + setegid?: (id: number | string) => void; + /** + * The `process.getgroups()` method returns an array with the supplementary group + * IDs. POSIX leaves it unspecified if the effective group ID is included but + * Node.js ensures it always is. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups) { + * console.log(process.getgroups()); // [ 16, 21, 297 ] + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.9.4 + */ + getgroups?: () => number[]; + /** + * The `process.setgroups()` method sets the supplementary group IDs for the + * Node.js process. This is a privileged operation that requires the Node.js + * process to have `root` or the `CAP_SETGID` capability. + * + * The `groups` array can contain numeric group IDs, group names, or both. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups && process.setgroups) { + * try { + * process.setgroups([501]); + * console.log(process.getgroups()); // new groups + * } catch (err) { + * console.log(`Failed to set groups: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.9.4 + */ + setgroups?: (groups: ReadonlyArray) => void; + /** + * The `process.setUncaughtExceptionCaptureCallback()` function sets a function + * that will be invoked when an uncaught exception occurs, which will receive the + * exception value itself as its first argument. + * + * If such a function is set, the `'uncaughtException'` event will + * not be emitted. If `--abort-on-uncaught-exception` was passed from the + * command line or set through `v8.setFlagsFromString()`, the process will + * not abort. Actions configured to take place on exceptions such as report + * generations will be affected too + * + * To unset the capture function, `process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * method with a non-`null` argument while another capture function is set will + * throw an error. + * + * Using this function is mutually exclusive with using the deprecated `domain` built-in module. + * @since v9.3.0 + */ + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + /** + * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. + * @since v9.3.0 + */ + hasUncaughtExceptionCaptureCallback(): boolean; + /** + * The `process.sourceMapsEnabled` property returns whether the [Source Map v3](https://sourcemaps.info/spec.html) support for stack traces is enabled. + * @since v20.7.0 + * @experimental + */ + readonly sourceMapsEnabled: boolean; + /** + * This function enables or disables the [Source Map v3](https://sourcemaps.info/spec.html) support for + * stack traces. + * + * It provides same features as launching Node.js process with commandline options `--enable-source-maps`. + * + * Only source maps in JavaScript files that are loaded after source maps has been + * enabled will be parsed and loaded. + * @since v16.6.0, v14.18.0 + * @experimental + */ + setSourceMapsEnabled(value: boolean): void; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'node:process'; + * + * console.log(`Version: ${version}`); + * // Version: v14.8.0 + * ``` + * + * To get the version string without the prepended _v_, use`process.versions.node`. + * @since v0.1.3 + */ + readonly version: string; + /** + * The `process.versions` property returns an object listing the version strings of + * Node.js and its dependencies. `process.versions.modules` indicates the current + * ABI version, which is increased whenever a C++ API changes. Node.js will refuse + * to load modules that were compiled against a different module ABI version. + * + * ```js + * import { versions } from 'node:process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '20.2.0', + * acorn: '8.8.2', + * ada: '2.4.0', + * ares: '1.19.0', + * base64: '0.5.0', + * brotli: '1.0.9', + * cjs_module_lexer: '1.2.2', + * cldr: '43.0', + * icu: '73.1', + * llhttp: '8.1.0', + * modules: '115', + * napi: '8', + * nghttp2: '1.52.0', + * nghttp3: '0.7.0', + * ngtcp2: '0.8.1', + * openssl: '3.0.8+quic', + * simdutf: '3.2.9', + * tz: '2023c', + * undici: '5.22.0', + * unicode: '15.0', + * uv: '1.44.2', + * uvwasi: '0.0.16', + * v8: '11.3.244.8-node.9', + * zlib: '1.2.13' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns a frozen `Object` containing the + * JavaScript representation of the configure options used to compile the current + * Node.js executable. This is the same as the `config.gypi` file that was produced + * when running the `./configure` script. + * + * An example of the possible output looks like: + * + * ```js + * { + * target_defaults: + * { cflags: [], + * default_configuration: 'Release', + * defines: [], + * include_dirs: [], + * libraries: [] }, + * variables: + * { + * host_arch: 'x64', + * napi_build_version: 5, + * node_install_npm: 'true', + * node_prefix: '', + * node_shared_cares: 'false', + * node_shared_http_parser: 'false', + * node_shared_libuv: 'false', + * node_shared_zlib: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * @since v0.7.7 + */ + readonly config: ProcessConfig; + /** + * The `process.kill()` method sends the `signal` to the process identified by`pid`. + * + * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. + * + * This method will throw an error if the target `pid` does not exist. As a special + * case, a signal of `0` can be used to test for the existence of a process. + * Windows platforms will throw an error if the `pid` is used to kill a process + * group. + * + * Even though the name of this function is `process.kill()`, it is really just a + * signal sender, like the `kill` system call. The signal sent may do something + * other than kill the target process. + * + * ```js + * import process, { kill } from 'node:process'; + * + * process.on('SIGHUP', () => { + * console.log('Got SIGHUP signal.'); + * }); + * + * setTimeout(() => { + * console.log('Exiting.'); + * process.exit(0); + * }, 100); + * + * kill(process.pid, 'SIGHUP'); + * ``` + * + * When `SIGUSR1` is received by a Node.js process, Node.js will start the + * debugger. See `Signal Events`. + * @since v0.0.6 + * @param pid A process ID + * @param [signal='SIGTERM'] The signal to send, either as a string or number. + */ + kill(pid: number, signal?: string | number): true; + /** + * Loads the environment configuration from a `.env` file into `process.env`. If + * the file is not found, error will be thrown. + * + * To load a specific .env file by specifying its path, use the following code: + * + * ```js + * import { loadEnvFile } from 'node:process'; + * + * loadEnvFile('./development.env') + * ``` + * @since v20.12.0 + * @param path The path to the .env file + */ + loadEnvFile(path?: PathLike): void; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'node:process'; + * + * console.log(`This process is pid ${pid}`); + * ``` + * @since v0.1.15 + */ + readonly pid: number; + /** + * The `process.ppid` property returns the PID of the parent of the + * current process. + * + * ```js + * import { ppid } from 'node:process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * The `process.threadCpuUsage()` method returns the user and system CPU time usage of + * the current worker thread, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). + * + * The result of a previous call to `process.threadCpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * @since v22.19.0 + * @param previousValue A previous return value from calling + * `process.threadCpuUsage()` + */ + threadCpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * The `process.title` property returns the current process title (i.e. returns + * the current value of `ps`). Assigning a new value to `process.title` modifies + * the current value of `ps`. + * + * When a new value is assigned, different platforms will impose different maximum + * length restrictions on the title. Usually such restrictions are quite limited. + * For instance, on Linux and macOS, `process.title` is limited to the size of the + * binary name plus the length of the command-line arguments because setting the `process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ` memory but that was potentially insecure and confusing in some (rather obscure) + * cases. + * + * Assigning a value to `process.title` might not result in an accurate label + * within process manager applications such as macOS Activity Monitor or Windows + * Services Manager. + * @since v0.1.104 + */ + title: string; + /** + * The operating system CPU architecture for which the Node.js binary was compiled. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, and `'x64'`. + * + * ```js + * import { arch } from 'node:process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: Architecture; + /** + * The `process.platform` property returns a string identifying the operating + * system platform for which the Node.js binary was compiled. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from 'node:process'; + * + * console.log(`This platform is ${platform}`); + * ``` + * + * The value `'android'` may also be returned if the Node.js is built on the + * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.1.16 + */ + readonly platform: Platform; + /** + * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at + * runtime, `require.main` may still refer to the original main module in + * modules that were required before the change occurred. Generally, it's + * safe to assume that the two refer to the same module. + * + * As with `require.main`, `process.mainModule` will be `undefined` if there + * is no entry script. + * @since v0.1.17 + * @deprecated Since v14.0.0 - Use `main` instead. + */ + mainModule?: Module; + memoryUsage: MemoryUsageFn; + /** + * Gets the amount of memory available to the process (in bytes) based on + * limits imposed by the OS. If there is no such constraint, or the constraint + * is unknown, `0` is returned. + * + * See [`uv_get_constrained_memory`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory) for more + * information. + * @since v19.6.0, v18.15.0 + */ + constrainedMemory(): number; + /** + * Gets the amount of free memory that is still available to the process (in bytes). + * See [`uv_get_available_memory`](https://nodejs.org/docs/latest-v22.x/api/process.html#processavailablememory) for more information. + * @since v20.13.0 + */ + availableMemory(): number; + /** + * The `process.cpuUsage()` method returns the user and system CPU time usage of + * the current process, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). These values measure time + * spent in user and system code respectively, and may end up being greater than + * actual elapsed time if multiple CPU cores are performing work for this process. + * + * The result of a previous call to `process.cpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * + * ```js + * import { cpuUsage } from 'node:process'; + * + * const startUsage = cpuUsage(); + * // { user: 38579, system: 6986 } + * + * // spin the CPU for 500 milliseconds + * const now = Date.now(); + * while (Date.now() - now < 500); + * + * console.log(cpuUsage(startUsage)); + * // { user: 514883, system: 11226 } + * ``` + * @since v6.1.0 + * @param previousValue A previous return value from calling `process.cpuUsage()` + */ + cpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * `process.nextTick()` adds `callback` to the "next tick queue". This queue is + * fully drained after the current operation on the JavaScript stack runs to + * completion and before the event loop is allowed to continue. It's possible to + * create an infinite loop if one were to recursively call `process.nextTick()`. + * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. + * + * ```js + * import { nextTick } from 'node:process'; + * + * console.log('start'); + * nextTick(() => { + * console.log('nextTick callback'); + * }); + * console.log('scheduled'); + * // Output: + * // start + * // scheduled + * // nextTick callback + * ``` + * + * This is important when developing APIs in order to give users the opportunity + * to assign event handlers _after_ an object has been constructed but before any + * I/O has occurred: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function MyThing(options) { + * this.setupOptions(options); + * + * nextTick(() => { + * this.startDoingStuff(); + * }); + * } + * + * const thing = new MyThing(); + * thing.getReadyForStuff(); + * + * // thing.startDoingStuff() gets called now, not before. + * ``` + * + * It is very important for APIs to be either 100% synchronous or 100% + * asynchronous. Consider this example: + * + * ```js + * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! + * function maybeSync(arg, cb) { + * if (arg) { + * cb(); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * + * This API is hazardous because in the following case: + * + * ```js + * const maybeTrue = Math.random() > 0.5; + * + * maybeSync(maybeTrue, () => { + * foo(); + * }); + * + * bar(); + * ``` + * + * It is not clear whether `foo()` or `bar()` will be called first. + * + * The following approach is much better: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function definitelyAsync(arg, cb) { + * if (arg) { + * nextTick(cb); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * @since v0.1.26 + * @param args Additional arguments to pass when invoking the `callback` + */ + nextTick(callback: Function, ...args: any[]): void; + /** + * This API is available through the [--permission](https://nodejs.org/api/cli.html#--permission) flag. + * + * `process.permission` is an object whose methods are used to manage permissions for the current process. + * Additional documentation is available in the [Permission Model](https://nodejs.org/api/permissions.html#permission-model). + * @since v20.0.0 + */ + permission: ProcessPermission; + /** + * The `process.release` property returns an `Object` containing metadata related + * to the current release, including URLs for the source tarball and headers-only + * tarball. + * + * `process.release` contains the following properties: + * + * ```js + * { + * name: 'node', + * lts: 'Hydrogen', + * sourceUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib' + * } + * ``` + * + * In custom builds from non-release versions of the source tree, only the `name` property may be present. The additional properties should not be + * relied upon to exist. + * @since v3.0.0 + */ + readonly release: ProcessRelease; + readonly features: ProcessFeatures; + /** + * `process.umask()` returns the Node.js process's file mode creation mask. Child + * processes inherit the mask from the parent process. + * @since v0.1.19 + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential + * security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: string | number): number; + /** + * The `process.uptime()` method returns the number of seconds the current Node.js + * process has been running. + * + * The return value includes fractions of a second. Use `Math.floor()` to get whole + * seconds. + * @since v0.5.0 + */ + uptime(): number; + hrtime: HRTime; + /** + * If the Node.js process was spawned with an IPC channel, the process.channel property is a reference to the IPC channel. + * If no IPC channel exists, this property is undefined. + * @since v7.1.0 + */ + channel?: Control; + /** + * If Node.js is spawned with an IPC channel, the `process.send()` method can be + * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. + * + * If Node.js was not spawned with an IPC channel, `process.send` will be `undefined`. + * + * The message goes through serialization and parsing. The resulting message might + * not be the same as what is originally sent. + * @since v0.5.9 + * @param options used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send?( + message: any, + sendHandle?: SendHandle, + options?: MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the + * IPC channel to the parent process, allowing the child process to exit gracefully + * once there are no other connections keeping it alive. + * + * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. + * + * If the Node.js process was not spawned with an IPC channel, `process.disconnect()` will be `undefined`. + * @since v0.7.2 + */ + disconnect(): void; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return `true` so long as the IPC + * channel is connected and will return `false` after `process.disconnect()` is called. + * + * Once `process.connected` is `false`, it is no longer possible to send messages + * over the IPC channel using `process.send()`. + * @since v0.7.2 + */ + connected: boolean; + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. + * + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides `Set.prototype.has` to recognize several different possible flag + * representations. `process.allowedNodeEnvironmentFlags.has()` will + * return `true` in the following cases: + * + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g., `inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags passed through to V8 (as listed in `--v8-options`) may replace + * one or more _non-leading_ dashes for an underscore, or vice-versa; + * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, + * etc. + * * Flags may contain one or more equals (`=`) characters; all + * characters after and including the first equals will be ignored; + * e.g., `--stack-trace-limit=100`. + * * Flags _must_ be allowable within `NODE_OPTIONS`. + * + * When iterating over `process.allowedNodeEnvironmentFlags`, flags will + * appear only _once_; each will begin with one or more dashes. Flags + * passed through to V8 will contain underscores instead of non-leading + * dashes: + * + * ```js + * import { allowedNodeEnvironmentFlags } from 'node:process'; + * + * allowedNodeEnvironmentFlags.forEach((flag) => { + * // -r + * // --inspect-brk + * // --abort_on_uncaught_exception + * // ... + * }); + * ``` + * + * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail + * silently. + * + * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will + * contain what _would have_ been allowable. + * @since v10.10.0 + */ + allowedNodeEnvironmentFlags: ReadonlySet; + /** + * `process.report` is an object whose methods are used to generate diagnostic reports for the current process. + * Additional documentation is available in the [report documentation](https://nodejs.org/docs/latest-v22.x/api/report.html). + * @since v11.8.0 + */ + report: ProcessReport; + /** + * ```js + * import { resourceUsage } from 'node:process'; + * + * console.log(resourceUsage()); + * /* + * Will output: + * { + * userCPUTime: 82872, + * systemCPUTime: 4143, + * maxRSS: 33164, + * sharedMemorySize: 0, + * unsharedDataSize: 0, + * unsharedStackSize: 0, + * minorPageFault: 2469, + * majorPageFault: 0, + * swappedOut: 0, + * fsRead: 0, + * fsWrite: 8, + * ipcSent: 0, + * ipcReceived: 0, + * signalsCount: 0, + * voluntaryContextSwitches: 79, + * involuntaryContextSwitches: 1 + * } + * + * ``` + * @since v12.6.0 + * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. + */ + resourceUsage(): ResourceUsage; + /** + * The initial value of `process.throwDeprecation` indicates whether the `--throw-deprecation` flag is set on the current Node.js process. `process.throwDeprecation` + * is mutable, so whether or not deprecation warnings result in errors may be altered at runtime. See the documentation for the 'warning' event and the emitWarning() + * method for more information. + * + * ```bash + * $ node --throw-deprecation -p "process.throwDeprecation" + * true + * $ node -p "process.throwDeprecation" + * undefined + * $ node + * > process.emitWarning('test', 'DeprecationWarning'); + * undefined + * > (node:26598) DeprecationWarning: test + * > process.throwDeprecation = true; + * true + * > process.emitWarning('test', 'DeprecationWarning'); + * Thrown: + * [DeprecationWarning: test] { name: 'DeprecationWarning' } + * ``` + * @since v0.9.12 + */ + throwDeprecation: boolean; + /** + * The `process.traceDeprecation` property indicates whether the `--trace-deprecation` flag is set on the current Node.js process. See the + * documentation for the `'warning' event` and the `emitWarning() method` for more information about this + * flag's behavior. + * @since v0.8.0 + */ + traceDeprecation: boolean; + /** + * An object is "refable" if it implements the Node.js "Refable protocol". + * Specifically, this means that the object implements the `Symbol.for('nodejs.ref')` + * and `Symbol.for('nodejs.unref')` methods. "Ref'd" objects will keep the Node.js + * event loop alive, while "unref'd" objects will not. Historically, this was + * implemented by using `ref()` and `unref()` methods directly on the objects. + * This pattern, however, is being deprecated in favor of the "Refable protocol" + * in order to better support Web Platform API types whose APIs cannot be modified + * to add `ref()` and `unref()` methods but still need to support that behavior. + * @since v22.14.0 + * @experimental + * @param maybeRefable An object that may be "refable". + */ + ref(maybeRefable: any): void; + /** + * An object is "unrefable" if it implements the Node.js "Refable protocol". + * Specifically, this means that the object implements the `Symbol.for('nodejs.ref')` + * and `Symbol.for('nodejs.unref')` methods. "Ref'd" objects will keep the Node.js + * event loop alive, while "unref'd" objects will not. Historically, this was + * implemented by using `ref()` and `unref()` methods directly on the objects. + * This pattern, however, is being deprecated in favor of the "Refable protocol" + * in order to better support Web Platform API types whose APIs cannot be modified + * to add `ref()` and `unref()` methods but still need to support that behavior. + * @since v22.14.0 + * @experimental + * @param maybeRefable An object that may be "unref'd". + */ + unref(maybeRefable: any): void; + /** + * Replaces the current process with a new process. + * + * This is achieved by using the `execve` POSIX function and therefore no memory or other + * resources from the current process are preserved, except for the standard input, + * standard output and standard error file descriptor. + * + * All other resources are discarded by the system when the processes are swapped, without triggering + * any exit or close events and without running any cleanup handler. + * + * This function will never return, unless an error occurred. + * + * This function is not available on Windows or IBM i. + * @since v22.15.0 + * @experimental + * @param file The name or path of the executable file to run. + * @param args List of string arguments. No argument can contain a null-byte (`\u0000`). + * @param env Environment key-value pairs. + * No key or value can contain a null-byte (`\u0000`). + * **Default:** `process.env`. + */ + execve?(file: string, args?: readonly string[], env?: ProcessEnv): never; + /* EventEmitter */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: "workerMessage", listener: (value: any, source: number) => void): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + addListener(event: "worker", listener: WorkerListener): this; + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "uncaughtExceptionMonitor", error: Error): boolean; + emit(event: "unhandledRejection", reason: unknown, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: unknown, sendHandle: SendHandle): this; + emit(event: "workerMessage", value: any, source: number): this; + emit(event: Signals, signal?: Signals): boolean; + emit( + event: "multipleResolves", + type: MultipleResolveType, + promise: Promise, + value: unknown, + ): this; + emit(event: "worker", listener: WorkerListener): this; + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + on(event: "worker", listener: WorkerListener): this; + on(event: "workerMessage", listener: (value: any, source: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + once(event: "worker", listener: WorkerListener): this; + once(event: "workerMessage", listener: (value: any, source: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: "workerMessage", listener: (value: any, source: number) => void): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependListener(event: "worker", listener: WorkerListener): this; + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: "workerMessage", listener: (value: any, source: number) => void): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependOnceListener(event: "worker", listener: WorkerListener): this; + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: "workerMessage"): ((value: any, source: number) => void)[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + listeners(event: "worker"): WorkerListener[]; + } + } + } + export = process; +} +declare module "node:process" { + import process = require("process"); + export = process; +} diff --git a/node_modules/@types/node/punycode.d.ts b/node_modules/@types/node/punycode.d.ts new file mode 100644 index 0000000..655c47b --- /dev/null +++ b/node_modules/@types/node/punycode.d.ts @@ -0,0 +1,117 @@ +/** + * **The version of the punycode module bundled in Node.js is being deprecated. **In a future major version of Node.js this module will be removed. Users + * currently depending on the `punycode` module should switch to using the + * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL + * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. + * + * The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It + * can be accessed using: + * + * ```js + * import punycode from 'node:punycode'; + * ``` + * + * [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is + * primarily intended for use in Internationalized Domain Names. Because host + * names in URLs are limited to ASCII characters only, Domain Names that contain + * non-ASCII characters must be converted into ASCII using the Punycode scheme. + * For instance, the Japanese character that translates into the English word, `'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent + * to `'example.com'`) is represented by Punycode as the ASCII string `'xn--fsq.com'`. + * + * The `punycode` module provides a simple implementation of the Punycode standard. + * + * The `punycode` module is a third-party dependency used by Node.js and + * made available to developers as a convenience. Fixes or other modifications to + * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. + * @deprecated Since v7.0.0 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/punycode.js) + */ +declare module "punycode" { + /** + * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only + * characters to the equivalent string of Unicode codepoints. + * + * ```js + * punycode.decode('maana-pta'); // 'mañana' + * punycode.decode('--dqo34k'); // '☃-⌘' + * ``` + * @since v0.5.1 + */ + function decode(string: string): string; + /** + * The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. + * + * ```js + * punycode.encode('mañana'); // 'maana-pta' + * punycode.encode('☃-⌘'); // '--dqo34k' + * ``` + * @since v0.5.1 + */ + function encode(string: string): string; + /** + * The `punycode.toUnicode()` method converts a string representing a domain name + * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be + * converted. + * + * ```js + * // decode domain names + * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + * punycode.toUnicode('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toUnicode(domain: string): string; + /** + * The `punycode.toASCII()` method converts a Unicode string representing an + * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the + * domain name will be converted. Calling `punycode.toASCII()` on a string that + * already only contains ASCII characters will have no effect. + * + * ```js + * // encode domain names + * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' + * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' + * punycode.toASCII('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toASCII(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: readonly number[]): string; + } + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} +declare module "node:punycode" { + export * from "punycode"; +} diff --git a/node_modules/@types/node/querystring.d.ts b/node_modules/@types/node/querystring.d.ts new file mode 100644 index 0000000..f0d5257 --- /dev/null +++ b/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,152 @@ +/** + * The `node:querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * import querystring from 'node:querystring'; + * ``` + * + * `querystring` is more performant than `URLSearchParams` but is not a + * standardized API. Use `URLSearchParams` when performance is not critical or + * when compatibility with browser code is desirable. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/querystring.js) + */ +declare module "querystring" { + interface StringifyOptions { + /** + * The function to use when converting URL-unsafe characters to percent-encoding in the query string. + * @default `querystring.escape()` + */ + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + /** + * Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations. + * @default 1000 + */ + maxKeys?: number | undefined; + /** + * The function to use when decoding percent-encoded characters in the query string. + * @default `querystring.unescape()` + */ + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends + NodeJS.Dict< + | string + | number + | boolean + | bigint + | ReadonlyArray + | null + > + {} + /** + * The `querystring.stringify()` method produces a URL query string from a + * given `obj` by iterating through the object's "own properties". + * + * It serializes the following types of values passed in `obj`: [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | + * [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to + * empty strings. + * + * ```js + * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); + * // Returns 'foo=bar&baz=qux&baz=quux&corge=' + * + * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); + * // Returns 'foo:bar;baz:qux' + * ``` + * + * By default, characters requiring percent-encoding within the query string will + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative `encodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkEncodeURIComponent function already exists, + * + * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + * { encodeURIComponent: gbkEncodeURIComponent }); + * ``` + * @since v0.1.25 + * @param obj The object to serialize into a URL query string + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + /** + * The `querystring.parse()` method parses a URL query string (`str`) into a + * collection of key and value pairs. + * + * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + * + * ```json + * { + * "foo": "bar", + * "abc": ["xyz", "123"] + * } + * ``` + * + * The object returned by the `querystring.parse()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * By default, percent-encoded characters within the query string will be assumed + * to use UTF-8 encoding. If an alternative character encoding is used, then an + * alternative `decodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkDecodeURIComponent function already exists... + * + * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, + * { decodeURIComponent: gbkDecodeURIComponent }); + * ``` + * @since v0.1.25 + * @param str The URL query string to parse + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] The substring used to delimit keys and values in the query string. + */ + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + /** + * The `querystring.escape()` method performs URL percent-encoding on the given `str` in a manner that is optimized for the specific requirements of URL + * query strings. + * + * The `querystring.escape()` method is used by `querystring.stringify()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement percent-encoding implementation if + * necessary by assigning `querystring.escape` to an alternative function. + * @since v0.1.25 + */ + function escape(str: string): string; + /** + * The `querystring.unescape()` method performs decoding of URL percent-encoded + * characters on the given `str`. + * + * The `querystring.unescape()` method is used by `querystring.parse()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement decoding implementation if + * necessary by assigning `querystring.unescape` to an alternative function. + * + * By default, the `querystring.unescape()` method will attempt to use the + * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, + * a safer equivalent that does not throw on malformed URLs will be used. + * @since v0.1.25 + */ + function unescape(str: string): string; +} +declare module "node:querystring" { + export * from "querystring"; +} diff --git a/node_modules/@types/node/readline.d.ts b/node_modules/@types/node/readline.d.ts new file mode 100644 index 0000000..338972e --- /dev/null +++ b/node_modules/@types/node/readline.d.ts @@ -0,0 +1,594 @@ +/** + * The `node:readline` module provides an interface for reading data from a [Readable](https://nodejs.org/docs/latest-v22.x/api/stream.html#readable-streams) stream + * (such as [`process.stdin`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdin)) one line at a time. + * + * To use the promise-based APIs: + * + * ```js + * import * as readline from 'node:readline/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as readline from 'node:readline'; + * ``` + * + * The following simple example illustrates the basic use of the `node:readline` module. + * + * ```js + * import * as readline from 'node:readline/promises'; + * import { stdin as input, stdout as output } from 'node:process'; + * + * const rl = readline.createInterface({ input, output }); + * + * const answer = await rl.question('What do you think of Node.js? '); + * + * console.log(`Thank you for your valuable feedback: ${answer}`); + * + * rl.close(); + * ``` + * + * Once this code is invoked, the Node.js application will not terminate until the `readline.Interface` is closed because the interface waits for data to be + * received on the `input` stream. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/readline.js) + */ +declare module "readline" { + import { Abortable, EventEmitter } from "node:events"; + import * as promises from "node:readline/promises"; + export { promises }; + export interface Key { + sequence?: string | undefined; + name?: string | undefined; + ctrl?: boolean | undefined; + meta?: boolean | undefined; + shift?: boolean | undefined; + } + /** + * Instances of the `readline.Interface` class are constructed using the `readline.createInterface()` method. Every instance is associated with a + * single `input` [Readable](https://nodejs.org/docs/latest-v22.x/api/stream.html#readable-streams) stream and a single `output` [Writable](https://nodejs.org/docs/latest-v22.x/api/stream.html#writable-streams) stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v0.1.104 + */ + export class Interface extends EventEmitter implements Disposable { + readonly terminal: boolean; + /** + * The current input data being processed by node. + * + * This can be used when collecting input from a TTY stream to retrieve the + * current value that has been processed thus far, prior to the `line` event + * being emitted. Once the `line` event has been emitted, this property will + * be an empty string. + * + * Be aware that modifying the value during the instance runtime may have + * unintended consequences if `rl.cursor` is not also controlled. + * + * **If not using a TTY stream for input, use the `'line'` event.** + * + * One possible use case would be as follows: + * + * ```js + * const values = ['lorem ipsum', 'dolor sit amet']; + * const rl = readline.createInterface(process.stdin); + * const showResults = debounce(() => { + * console.log( + * '\n', + * values.filter((val) => val.startsWith(rl.line)).join(' '), + * ); + * }, 300); + * process.stdin.on('keypress', (c, k) => { + * showResults(); + * }); + * ``` + * @since v0.1.98 + */ + readonly line: string; + /** + * The cursor position relative to `rl.line`. + * + * This will track where the current cursor lands in the input string, when + * reading input from a TTY stream. The position of cursor determines the + * portion of the input string that will be modified as input is processed, + * as well as the column where the terminal caret will be rendered. + * @since v0.1.98 + */ + readonly cursor: number; + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor(options: ReadLineOptions); + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.0, v14.17.0 + * @return the current prompt string + */ + getPrompt(): string; + /** + * The `rl.setPrompt()` method sets the prompt that will be written to `output` whenever `rl.prompt()` is called. + * @since v0.1.98 + */ + setPrompt(prompt: string): void; + /** + * The `rl.prompt()` method writes the `Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * location at which to provide input. + * + * When called, `rl.prompt()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the prompt is not written. + * @since v0.1.98 + * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. + */ + prompt(preserveCursor?: boolean): void; + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * The `callback` function passed to `rl.question()` does not follow the typical + * pattern of accepting an `Error` object or `null` as the first argument. + * The `callback` is called with the provided answer as the only argument. + * + * An error will be thrown if calling `rl.question()` after `rl.close()`. + * + * Example usage: + * + * ```js + * rl.question('What is your favorite food? ', (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * ``` + * + * Using an `AbortController` to cancel a question. + * + * ```js + * const ac = new AbortController(); + * const signal = ac.signal; + * + * rl.question('What is your favorite food? ', { signal }, (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * setTimeout(() => ac.abort(), 10000); + * ``` + * @since v0.3.3 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @param callback A callback function that is invoked with the user's input in response to the `query`. + */ + question(query: string, callback: (answer: string) => void): void; + question(query: string, options: Abortable, callback: (answer: string) => void): void; + /** + * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed + * later if necessary. + * + * Calling `rl.pause()` does not immediately pause other events (including `'line'`) from being emitted by the `Interface` instance. + * @since v0.3.4 + */ + pause(): this; + /** + * The `rl.resume()` method resumes the `input` stream if it has been paused. + * @since v0.3.4 + */ + resume(): this; + /** + * The `rl.close()` method closes the `Interface` instance and + * relinquishes control over the `input` and `output` streams. When called, + * the `'close'` event will be emitted. + * + * Calling `rl.close()` does not immediately stop other events (including `'line'`) + * from being emitted by the `Interface` instance. + * @since v0.1.98 + */ + close(): void; + /** + * Alias for `rl.close()`. + * @since v22.15.0 + */ + [Symbol.dispose](): void; + /** + * The `rl.write()` method will write either `data` or a key sequence identified + * by `key` to the `output`. The `key` argument is supported only if `output` is + * a `TTY` text terminal. See `TTY keybindings` for a list of key + * combinations. + * + * If `key` is specified, `data` is ignored. + * + * When called, `rl.write()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `data` and `key` are not written. + * + * ```js + * rl.write('Delete this!'); + * // Simulate Ctrl+U to delete the line written previously + * rl.write(null, { ctrl: true, name: 'u' }); + * ``` + * + * The `rl.write()` method will write the data to the `readline` `Interface`'s `input` _as if it were provided by the user_. + * @since v0.1.98 + */ + write(data: string | Buffer, key?: Key): void; + write(data: undefined | null | string | Buffer, key: Key): void; + /** + * Returns the real position of the cursor in relation to the input + * prompt + string. Long input (wrapping) strings, as well as multiple + * line prompts are included in the calculations. + * @since v13.5.0, v12.16.0 + */ + getCursorPos(): CursorPos; + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + * 8. history + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "history", listener: (history: string[]) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "history", history: string[]): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "history", listener: (history: string[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "history", listener: (history: string[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "history", listener: (history: string[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "history", listener: (history: string[]) => void): this; + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + } + export type ReadLine = Interface; // type forwarded for backwards compatibility + export type Completer = (line: string) => CompleterResult; + export type AsyncCompleter = ( + line: string, + callback: (err?: null | Error, result?: CompleterResult) => void, + ) => void; + export type CompleterResult = [string[], string]; + export interface ReadLineOptions { + /** + * The [`Readable`](https://nodejs.org/docs/latest-v22.x/api/stream.html#readable-streams) stream to listen to + */ + input: NodeJS.ReadableStream; + /** + * The [`Writable`](https://nodejs.org/docs/latest-v22.x/api/stream.html#writable-streams) stream to write readline data to. + */ + output?: NodeJS.WritableStream | undefined; + /** + * An optional function used for Tab autocompletion. + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * `true` if the `input` and `output` streams should be treated like a TTY, + * and have ANSI/VT100 escape codes written to it. + * Default: checking `isTTY` on the `output` stream upon instantiation. + */ + terminal?: boolean | undefined; + /** + * Initial list of history lines. + * This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, + * otherwise the history caching mechanism is not initialized at all. + * @default [] + */ + history?: string[] | undefined; + /** + * Maximum number of history lines retained. + * To disable the history set this value to `0`. + * This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, + * otherwise the history caching mechanism is not initialized at all. + * @default 30 + */ + historySize?: number | undefined; + /** + * If `true`, when a new input line added to the history list duplicates an older one, + * this removes the older line from the list. + * @default false + */ + removeHistoryDuplicates?: boolean | undefined; + /** + * The prompt string to use. + * @default "> " + */ + prompt?: string | undefined; + /** + * If the delay between `\r` and `\n` exceeds `crlfDelay` milliseconds, + * both `\r` and `\n` will be treated as separate end-of-line input. + * `crlfDelay` will be coerced to a number no less than `100`. + * It can be set to `Infinity`, in which case + * `\r` followed by `\n` will always be considered a single newline + * (which may be reasonable for [reading files](https://nodejs.org/docs/latest-v22.x/api/readline.html#example-read-file-stream-line-by-line) with `\r\n` line delimiter). + * @default 100 + */ + crlfDelay?: number | undefined; + /** + * The duration `readline` will wait for a character + * (when reading an ambiguous key sequence in milliseconds + * one that can both form a complete key sequence using the input read so far + * and can take additional input to complete a longer key sequence). + * @default 500 + */ + escapeCodeTimeout?: number | undefined; + /** + * The number of spaces a tab is equal to (minimum 1). + * @default 8 + */ + tabSize?: number | undefined; + /** + * Allows closing the interface using an AbortSignal. + * Aborting the signal will internally call `close` on the interface. + */ + signal?: AbortSignal | undefined; + } + /** + * The `readline.createInterface()` method creates a new `readline.Interface` instance. + * + * ```js + * import readline from 'node:readline'; + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readline.Interface` instance is created, the most common case is to + * listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * + * When creating a `readline.Interface` using `stdin` as input, the program + * will not terminate until it receives an [EOF character](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without + * waiting for user input, call `process.stdin.unref()`. + * @since v0.1.98 + */ + export function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + export function createInterface(options: ReadLineOptions): Interface; + /** + * The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. + * + * Optionally, `interface` specifies a `readline.Interface` instance for which + * autocompletion is disabled when copy-pasted input is detected. + * + * If the `stream` is a `TTY`, then it must be in raw mode. + * + * This is automatically called by any readline instance on its `input` if the `input` is a terminal. Closing the `readline` instance does not stop + * the `input` from emitting `'keypress'` events. + * + * ```js + * readline.emitKeypressEvents(process.stdin); + * if (process.stdin.isTTY) + * process.stdin.setRawMode(true); + * ``` + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * import readline from 'node:readline'; + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ', + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * import fs from 'node:fs'; + * import readline from 'node:readline'; + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity, + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * import fs from 'node:fs'; + * import readline from 'node:readline'; + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await` flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * import { once } from 'node:events'; + * import { createReadStream } from 'node:fs'; + * import { createInterface } from 'node:readline'; + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + */ + export function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + export type Direction = -1 | 0 | 1; + export interface CursorPos { + rows: number; + cols: number; + } + /** + * The `readline.clearLine()` method clears current line of given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) stream + * in a specified direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; + /** + * The `readline.clearScreenDown()` method clears the given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) stream from + * the current position of the cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; + /** + * The `readline.cursorTo()` method moves cursor to the specified position in a + * given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; + /** + * The `readline.moveCursor()` method moves the cursor _relative_ to its current + * position in a given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module "node:readline" { + export * from "readline"; +} diff --git a/node_modules/@types/node/readline/promises.d.ts b/node_modules/@types/node/readline/promises.d.ts new file mode 100644 index 0000000..5bc9a0c --- /dev/null +++ b/node_modules/@types/node/readline/promises.d.ts @@ -0,0 +1,161 @@ +/** + * @since v17.0.0 + */ +declare module "readline/promises" { + import { Abortable } from "node:events"; + import { + CompleterResult, + Direction, + Interface as _Interface, + ReadLineOptions as _ReadLineOptions, + } from "node:readline"; + /** + * Instances of the `readlinePromises.Interface` class are constructed using the `readlinePromises.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v17.0.0 + */ + class Interface extends _Interface { + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * If the question is called after `rl.close()`, it returns a rejected promise. + * + * Example usage: + * + * ```js + * const answer = await rl.question('What is your favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * Using an `AbortSignal` to cancel a question. + * + * ```js + * const signal = AbortSignal.timeout(10_000); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * const answer = await rl.question('What is your favorite food? ', { signal }); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * @since v17.0.0 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @return A promise that is fulfilled with the user's input in response to the `query`. + */ + question(query: string): Promise; + question(query: string, options: Abortable): Promise; + } + /** + * @since v17.0.0 + */ + class Readline { + /** + * @param stream A TTY stream. + */ + constructor( + stream: NodeJS.WritableStream, + options?: { + autoCommit?: boolean | undefined; + }, + ); + /** + * The `rl.clearLine()` method adds to the internal list of pending action an + * action that clears current line of the associated `stream` in a specified + * direction identified by `dir`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearLine(dir: Direction): this; + /** + * The `rl.clearScreenDown()` method adds to the internal list of pending action an + * action that clears the associated stream from the current position of the + * cursor down. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearScreenDown(): this; + /** + * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. + * @since v17.0.0 + */ + commit(): Promise; + /** + * The `rl.cursorTo()` method adds to the internal list of pending action an action + * that moves cursor to the specified position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + cursorTo(x: number, y?: number): this; + /** + * The `rl.moveCursor()` method adds to the internal list of pending action an + * action that moves the cursor _relative_ to its current position in the + * associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + moveCursor(dx: number, dy: number): this; + /** + * The `rl.rollback` methods clears the internal list of pending actions without + * sending it to the associated `stream`. + * @since v17.0.0 + * @return this + */ + rollback(): this; + } + type Completer = (line: string) => CompleterResult | Promise; + interface ReadLineOptions extends Omit<_ReadLineOptions, "completer"> { + /** + * An optional function used for Tab autocompletion. + */ + completer?: Completer | undefined; + } + /** + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. + * + * ```js + * import readlinePromises from 'node:readline/promises'; + * const rl = readlinePromises.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readlinePromises.Interface` instance is created, the most common case + * is to listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * @since v17.0.0 + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; +} +declare module "node:readline/promises" { + export * from "readline/promises"; +} diff --git a/node_modules/@types/node/repl.d.ts b/node_modules/@types/node/repl.d.ts new file mode 100644 index 0000000..fb858da --- /dev/null +++ b/node_modules/@types/node/repl.d.ts @@ -0,0 +1,428 @@ +/** + * The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation + * that is available both as a standalone program or includible in other + * applications. It can be accessed using: + * + * ```js + * import repl from 'node:repl'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/repl.js) + */ +declare module "repl" { + import { AsyncCompleter, Completer, Interface } from "node:readline"; + import { Context } from "node:vm"; + import { InspectOptions } from "node:util"; + interface ReplOptions { + /** + * The input prompt to display. + * @default "> " + */ + prompt?: string | undefined; + /** + * The `Readable` stream from which REPL input will be read. + * @default process.stdin + */ + input?: NodeJS.ReadableStream | undefined; + /** + * The `Writable` stream to which REPL output will be written. + * @default process.stdout + */ + output?: NodeJS.WritableStream | undefined; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean | undefined; + /** + * The function to be used when evaluating each given line of input. + * **Default:** an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. See the [custom evaluation functions](https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#custom-evaluation-functions) + * section for more details. + */ + eval?: REPLEval | undefined; + /** + * Defines if the repl prints output previews or not. + * @default `true` Always `false` in case `terminal` is falsy. + */ + preview?: boolean | undefined; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * @default the REPL instance's `terminal` value + */ + useColors?: boolean | undefined; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * @default false + */ + useGlobal?: boolean | undefined; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * @default false + */ + ignoreUndefined?: boolean | undefined; + /** + * The function to invoke to format the output of each command before writing to `output`. + * @default a wrapper for `util.inspect` + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter | undefined; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * @default false + */ + breakEvalOnSigint?: boolean | undefined; + } + type REPLEval = ( + this: REPLServer, + evalCmd: string, + context: Context, + file: string, + cb: (err: Error | null, result: any) => void, + ) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { + options: InspectOptions; + }; + type REPLCommandAction = (this: REPLServer, text: string) => void; + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string | undefined; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + /** + * Instances of `repl.REPLServer` are created using the {@link start} method + * or directly using the JavaScript `new` keyword. + * + * ```js + * import repl from 'node:repl'; + * + * const options = { useColors: true }; + * + * const firstInstance = repl.start(options); + * const secondInstance = new repl.REPLServer(options); + * ``` + * @since v0.1.91 + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * @deprecated since v14.3.0 - Use `input` instead. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * @deprecated since v14.3.0 - Use `output` instead. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly input: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly output: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: NodeJS.ReadOnlyDict; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + /** + * The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands + * to the REPL instance. Such commands are invoked by typing a `.` followed by the `keyword`. The `cmd` is either a `Function` or an `Object` with the following + * properties: + * + * The following example shows two new commands added to the REPL instance: + * + * ```js + * import repl from 'node:repl'; + * + * const replServer = repl.start({ prompt: '> ' }); + * replServer.defineCommand('sayhello', { + * help: 'Say hello', + * action(name) { + * this.clearBufferedCommand(); + * console.log(`Hello, ${name}!`); + * this.displayPrompt(); + * }, + * }); + * replServer.defineCommand('saybye', function saybye() { + * console.log('Goodbye!'); + * this.close(); + * }); + * ``` + * + * The new commands can then be used from within the REPL instance: + * + * ```console + * > .sayhello Node.js User + * Hello, Node.js User! + * > .saybye + * Goodbye! + * ``` + * @since v0.3.0 + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * The `replServer.displayPrompt()` method readies the REPL instance for input + * from the user, printing the configured `prompt` to a new line in the `output` and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the + * 'prompt'. + * + * When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. + * + * The `replServer.displayPrompt` method is primarily intended to be called from + * within the action function for commands registered using the `replServer.defineCommand()` method. + * @since v0.1.91 + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * The `replServer.clearBufferedCommand()` method clears any command that has been + * buffered but not yet executed. This method is primarily intended to be + * called from within the action function for commands registered using the `replServer.defineCommand()` method. + * @since v9.0.0 + */ + clearBufferedCommand(): void; + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command-line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @since v11.10.0 + * @param historyPath the path to the history file + * @param callback called when history writes are ready or upon error + */ + setupHistory(path: string, callback: (err: Error | null, repl: this) => void): void; + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: (context: Context) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: Context): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: (context: Context) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: (context: Context) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: (context: Context) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: (context: Context) => void): this; + } + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + const REPL_MODE_SLOPPY: unique symbol; + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + const REPL_MODE_STRICT: unique symbol; + /** + * The `repl.start()` method creates and starts a {@link REPLServer} instance. + * + * If `options` is a string, then it specifies the input prompt: + * + * ```js + * import repl from 'node:repl'; + * + * // a Unix style prompt + * repl.start('$ '); + * ``` + * @since v0.1.91 + */ + function start(options?: string | ReplOptions): REPLServer; + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + constructor(err: Error); + } +} +declare module "node:repl" { + export * from "repl"; +} diff --git a/node_modules/@types/node/sea.d.ts b/node_modules/@types/node/sea.d.ts new file mode 100644 index 0000000..3013074 --- /dev/null +++ b/node_modules/@types/node/sea.d.ts @@ -0,0 +1,153 @@ +/** + * This feature allows the distribution of a Node.js application conveniently to a + * system that does not have Node.js installed. + * + * Node.js supports the creation of [single executable applications](https://github.com/nodejs/single-executable) by allowing + * the injection of a blob prepared by Node.js, which can contain a bundled script, + * into the `node` binary. During start up, the program checks if anything has been + * injected. If the blob is found, it executes the script in the blob. Otherwise + * Node.js operates as it normally does. + * + * The single executable application feature currently only supports running a + * single embedded script using the `CommonJS` module system. + * + * Users can create a single executable application from their bundled script + * with the `node` binary itself and any tool which can inject resources into the + * binary. + * + * Here are the steps for creating a single executable application using one such + * tool, [postject](https://github.com/nodejs/postject): + * + * 1. Create a JavaScript file: + * ```bash + * echo 'console.log(`Hello, ${process.argv[2]}!`);' > hello.js + * ``` + * 2. Create a configuration file building a blob that can be injected into the + * single executable application (see `Generating single executable preparation blobs` for details): + * ```bash + * echo '{ "main": "hello.js", "output": "sea-prep.blob" }' > sea-config.json + * ``` + * 3. Generate the blob to be injected: + * ```bash + * node --experimental-sea-config sea-config.json + * ``` + * 4. Create a copy of the `node` executable and name it according to your needs: + * * On systems other than Windows: + * ```bash + * cp $(command -v node) hello + * ``` + * * On Windows: + * ```text + * node -e "require('fs').copyFileSync(process.execPath, 'hello.exe')" + * ``` + * The `.exe` extension is necessary. + * 5. Remove the signature of the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --remove-signature hello + * ``` + * * On Windows (optional): + * [signtool](https://learn.microsoft.com/en-us/windows/win32/seccrypto/signtool) can be used from the installed [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/). + * If this step is + * skipped, ignore any signature-related warning from postject. + * ```powershell + * signtool remove /s hello.exe + * ``` + * 6. Inject the blob into the copied binary by running `postject` with + * the following options: + * * `hello` / `hello.exe` \- The name of the copy of the `node` executable + * created in step 4. + * * `NODE_SEA_BLOB` \- The name of the resource / note / section in the binary + * where the contents of the blob will be stored. + * * `sea-prep.blob` \- The name of the blob created in step 1. + * * `--sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2` \- The [fuse](https://www.electronjs.org/docs/latest/tutorial/fuses) used by the Node.js project to detect if a file has been + * injected. + * * `--macho-segment-name NODE_SEA` (only needed on macOS) - The name of the + * segment in the binary where the contents of the blob will be + * stored. + * To summarize, here is the required command for each platform: + * * On Linux: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - PowerShell: + * ```powershell + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ` + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - Command Prompt: + * ```text + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ^ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On macOS: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \ + * --macho-segment-name NODE_SEA + * ``` + * 7. Sign the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --sign - hello + * ``` + * * On Windows (optional): + * A certificate needs to be present for this to work. However, the unsigned + * binary would still be runnable. + * ```powershell + * signtool sign /fd SHA256 hello.exe + * ``` + * 8. Run the binary: + * * On systems other than Windows + * ```console + * $ ./hello world + * Hello, world! + * ``` + * * On Windows + * ```console + * $ .\hello.exe world + * Hello, world! + * ``` + * @since v19.7.0, v18.16.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v22.x/src/node_sea.cc) + */ +declare module "node:sea" { + type AssetKey = string; + /** + * @since v20.12.0 + * @return Whether this script is running inside a single-executable application. + */ + function isSea(): boolean; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAsset(key: AssetKey): ArrayBuffer; + function getAsset(key: AssetKey, encoding: string): string; + /** + * Similar to `sea.getAsset()`, but returns the result in a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob). + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAssetAsBlob(key: AssetKey, options?: { + type: string; + }): Blob; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * + * Unlike `sea.getRawAsset()` or `sea.getAssetAsBlob()`, this method does not + * return a copy. Instead, it returns the raw asset bundled inside the executable. + * + * For now, users should avoid writing to the returned array buffer. If the + * injected section is not marked as writable or not aligned properly, + * writes to the returned array buffer is likely to result in a crash. + * @since v20.12.0 + */ + function getRawAsset(key: AssetKey): ArrayBuffer; +} diff --git a/node_modules/@types/node/sqlite.d.ts b/node_modules/@types/node/sqlite.d.ts new file mode 100644 index 0000000..19d826d --- /dev/null +++ b/node_modules/@types/node/sqlite.d.ts @@ -0,0 +1,721 @@ +/** + * The `node:sqlite` module facilitates working with SQLite databases. + * To access it: + * + * ```js + * import sqlite from 'node:sqlite'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import sqlite from 'sqlite'; + * ``` + * + * The following example shows the basic usage of the `node:sqlite` module to open + * an in-memory database, write data to the database, and then read the data back. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * const database = new DatabaseSync(':memory:'); + * + * // Execute SQL statements from strings. + * database.exec(` + * CREATE TABLE data( + * key INTEGER PRIMARY KEY, + * value TEXT + * ) STRICT + * `); + * // Create a prepared statement to insert data into the database. + * const insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)'); + * // Execute the prepared statement with bound values. + * insert.run(1, 'hello'); + * insert.run(2, 'world'); + * // Create a prepared statement to read data from the database. + * const query = database.prepare('SELECT * FROM data ORDER BY key'); + * // Execute the prepared statement and log the result set. + * console.log(query.all()); + * // Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ] + * ``` + * @since v22.5.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/sqlite.js) + */ +declare module "node:sqlite" { + import { PathLike } from "node:fs"; + type SQLInputValue = null | number | bigint | string | NodeJS.ArrayBufferView; + type SQLOutputValue = null | number | bigint | string | NodeJS.NonSharedUint8Array; + interface DatabaseSyncOptions { + /** + * If `true`, the database is opened by the constructor. When + * this value is `false`, the database must be opened via the `open()` method. + * @since v22.5.0 + * @default true + */ + open?: boolean | undefined; + /** + * If `true`, foreign key constraints + * are enabled. This is recommended but can be disabled for compatibility with + * legacy database schemas. The enforcement of foreign key constraints can be + * enabled and disabled after opening the database using + * [`PRAGMA foreign_keys`](https://www.sqlite.org/pragma.html#pragma_foreign_keys). + * @since v22.10.0 + * @default true + */ + enableForeignKeyConstraints?: boolean | undefined; + /** + * If `true`, SQLite will accept + * [double-quoted string literals](https://www.sqlite.org/quirks.html#dblquote). + * This is not recommended but can be + * enabled for compatibility with legacy database schemas. + * @since v22.10.0 + * @default false + */ + enableDoubleQuotedStringLiterals?: boolean | undefined; + /** + * If `true`, the database is opened in read-only mode. + * If the database does not exist, opening it will fail. + * @since v22.12.0 + * @default false + */ + readOnly?: boolean | undefined; + /** + * If `true`, the `loadExtension` SQL function + * and the `loadExtension()` method are enabled. + * You can call `enableLoadExtension(false)` later to disable this feature. + * @since v22.13.0 + * @default false + */ + allowExtension?: boolean | undefined; + /** + * The [busy timeout](https://sqlite.org/c3ref/busy_timeout.html) in milliseconds. This is the maximum amount of + * time that SQLite will wait for a database lock to be released before + * returning an error. + * @since v22.16.0 + * @default 0 + */ + timeout?: number | undefined; + /** + * If `true`, integer fields are read as JavaScript `BigInt` values. If `false`, + * integer fields are read as JavaScript numbers. + * @since v22.18.0 + * @default false + */ + readBigInts?: boolean | undefined; + /** + * If `true`, query results are returned as arrays instead of objects. + * @since v22.18.0 + * @default false + */ + returnArrays?: boolean | undefined; + /** + * If `true`, allows binding named parameters without the prefix + * character (e.g., `foo` instead of `:foo`). + * @since v22.18.0 + * @default true + */ + allowBareNamedParameters?: boolean | undefined; + /** + * If `true`, unknown named parameters are ignored when binding. + * If `false`, an exception is thrown for unknown named parameters. + * @since v22.18.0 + * @default false + */ + allowUnknownNamedParameters?: boolean | undefined; + } + interface CreateSessionOptions { + /** + * A specific table to track changes for. By default, changes to all tables are tracked. + * @since v22.12.0 + */ + table?: string | undefined; + /** + * Name of the database to track. This is useful when multiple databases have been added using + * [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html). + * @since v22.12.0 + * @default 'main' + */ + db?: string | undefined; + } + interface ApplyChangesetOptions { + /** + * Skip changes that, when targeted table name is supplied to this function, return a truthy value. + * By default, all changes are attempted. + * @since v22.12.0 + */ + filter?: ((tableName: string) => boolean) | undefined; + /** + * A function that determines how to handle conflicts. The function receives one argument, + * which can be one of the following values: + * + * * `SQLITE_CHANGESET_DATA`: A `DELETE` or `UPDATE` change does not contain the expected "before" values. + * * `SQLITE_CHANGESET_NOTFOUND`: A row matching the primary key of the `DELETE` or `UPDATE` change does not exist. + * * `SQLITE_CHANGESET_CONFLICT`: An `INSERT` change results in a duplicate primary key. + * * `SQLITE_CHANGESET_FOREIGN_KEY`: Applying a change would result in a foreign key violation. + * * `SQLITE_CHANGESET_CONSTRAINT`: Applying a change results in a `UNIQUE`, `CHECK`, or `NOT NULL` constraint + * violation. + * + * The function should return one of the following values: + * + * * `SQLITE_CHANGESET_OMIT`: Omit conflicting changes. + * * `SQLITE_CHANGESET_REPLACE`: Replace existing values with conflicting changes (only valid with + `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT` conflicts). + * * `SQLITE_CHANGESET_ABORT`: Abort on conflict and roll back the database. + * + * When an error is thrown in the conflict handler or when any other value is returned from the handler, + * applying the changeset is aborted and the database is rolled back. + * + * **Default**: A function that returns `SQLITE_CHANGESET_ABORT`. + * @since v22.12.0 + */ + onConflict?: ((conflictType: number) => number) | undefined; + } + interface FunctionOptions { + /** + * If `true`, the [`SQLITE_DETERMINISTIC`](https://www.sqlite.org/c3ref/c_deterministic.html) flag is + * set on the created function. + * @default false + */ + deterministic?: boolean | undefined; + /** + * If `true`, the [`SQLITE_DIRECTONLY`](https://www.sqlite.org/c3ref/c_directonly.html) flag is set on + * the created function. + * @default false + */ + directOnly?: boolean | undefined; + /** + * If `true`, integer arguments to `function` + * are converted to `BigInt`s. If `false`, integer arguments are passed as + * JavaScript numbers. + * @default false + */ + useBigIntArguments?: boolean | undefined; + /** + * If `true`, `function` may be invoked with any number of + * arguments (between zero and + * [`SQLITE_MAX_FUNCTION_ARG`](https://www.sqlite.org/limits.html#max_function_arg)). If `false`, + * `function` must be invoked with exactly `function.length` arguments. + * @default false + */ + varargs?: boolean | undefined; + } + interface AggregateOptions extends FunctionOptions { + /** + * The identity value for the aggregation function. This value is used when the aggregation + * function is initialized. When a `Function` is passed the identity will be its return value. + */ + start: T | (() => T); + /** + * The function to call for each row in the aggregation. The + * function receives the current state and the row value. The return value of + * this function should be the new state. + */ + step: (accumulator: T, ...args: SQLOutputValue[]) => T; + /** + * The function to call to get the result of the + * aggregation. The function receives the final state and should return the + * result of the aggregation. + */ + result?: ((accumulator: T) => SQLInputValue) | undefined; + /** + * When this function is provided, the `aggregate` method will work as a window function. + * The function receives the current state and the dropped row value. The return value of this function should be the + * new state. + */ + inverse?: ((accumulator: T, ...args: SQLOutputValue[]) => T) | undefined; + } + /** + * This class represents a single [connection](https://www.sqlite.org/c3ref/sqlite3.html) to a SQLite database. All APIs + * exposed by this class execute synchronously. + * @since v22.5.0 + */ + class DatabaseSync implements Disposable { + /** + * Constructs a new `DatabaseSync` instance. + * @param path The path of the database. + * A SQLite database can be stored in a file or completely [in memory](https://www.sqlite.org/inmemorydb.html). + * To use a file-backed database, the path should be a file path. + * To use an in-memory database, the path should be the special name `':memory:'`. + * @param options Configuration options for the database connection. + */ + constructor(path: PathLike, options?: DatabaseSyncOptions); + /** + * Registers a new aggregate function with the SQLite database. This method is a wrapper around + * [`sqlite3_create_window_function()`](https://www.sqlite.org/c3ref/create_function.html). + * + * When used as a window function, the `result` function will be called multiple times. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * + * const db = new DatabaseSync(':memory:'); + * db.exec(` + * CREATE TABLE t3(x, y); + * INSERT INTO t3 VALUES ('a', 4), + * ('b', 5), + * ('c', 3), + * ('d', 8), + * ('e', 1); + * `); + * + * db.aggregate('sumint', { + * start: 0, + * step: (acc, value) => acc + value, + * }); + * + * db.prepare('SELECT sumint(y) as total FROM t3').get(); // { total: 21 } + * ``` + * @since v22.16.0 + * @param name The name of the SQLite function to create. + * @param options Function configuration settings. + */ + aggregate(name: string, options: AggregateOptions): void; + aggregate(name: string, options: AggregateOptions): void; + /** + * Closes the database connection. An exception is thrown if the database is not + * open. This method is a wrapper around [`sqlite3_close_v2()`](https://www.sqlite.org/c3ref/close.html). + * @since v22.5.0 + */ + close(): void; + /** + * Loads a shared library into the database connection. This method is a wrapper + * around [`sqlite3_load_extension()`](https://www.sqlite.org/c3ref/load_extension.html). It is required to enable the + * `allowExtension` option when constructing the `DatabaseSync` instance. + * @since v22.13.0 + * @param path The path to the shared library to load. + */ + loadExtension(path: string): void; + /** + * Enables or disables the `loadExtension` SQL function, and the `loadExtension()` + * method. When `allowExtension` is `false` when constructing, you cannot enable + * loading extensions for security reasons. + * @since v22.13.0 + * @param allow Whether to allow loading extensions. + */ + enableLoadExtension(allow: boolean): void; + /** + * This method is a wrapper around [`sqlite3_db_filename()`](https://sqlite.org/c3ref/db_filename.html) + * @since v22.16.0 + * @param dbName Name of the database. This can be `'main'` (the default primary database) or any other + * database that has been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) **Default:** `'main'`. + * @returns The location of the database file. When using an in-memory database, + * this method returns null. + */ + location(dbName?: string): string | null; + /** + * This method allows one or more SQL statements to be executed without returning + * any results. This method is useful when executing SQL statements read from a + * file. This method is a wrapper around [`sqlite3_exec()`](https://www.sqlite.org/c3ref/exec.html). + * @since v22.5.0 + * @param sql A SQL string to execute. + */ + exec(sql: string): void; + /** + * This method is used to create SQLite user-defined functions. This method is a + * wrapper around [`sqlite3_create_function_v2()`](https://www.sqlite.org/c3ref/create_function.html). + * @since v22.13.0 + * @param name The name of the SQLite function to create. + * @param options Optional configuration settings for the function. + * @param func The JavaScript function to call when the SQLite + * function is invoked. The return value of this function should be a valid + * SQLite data type: see + * [Type conversion between JavaScript and SQLite](https://nodejs.org/docs/latest-v22.x/api/sqlite.html#type-conversion-between-javascript-and-sqlite). + * The result defaults to `NULL` if the return value is `undefined`. + */ + function( + name: string, + options: FunctionOptions, + func: (...args: SQLOutputValue[]) => SQLInputValue, + ): void; + function(name: string, func: (...args: SQLOutputValue[]) => SQLInputValue): void; + /** + * Whether the database is currently open or not. + * @since v22.15.0 + */ + readonly isOpen: boolean; + /** + * Whether the database is currently within a transaction. This method + * is a wrapper around [`sqlite3_get_autocommit()`](https://sqlite.org/c3ref/get_autocommit.html). + * @since v22.16.0 + */ + readonly isTransaction: boolean; + /** + * Opens the database specified in the `path` argument of the `DatabaseSync`constructor. This method should only be used when the database is not opened via + * the constructor. An exception is thrown if the database is already open. + * @since v22.5.0 + */ + open(): void; + /** + * Compiles a SQL statement into a [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This method is a wrapper + * around [`sqlite3_prepare_v2()`](https://www.sqlite.org/c3ref/prepare.html). + * @since v22.5.0 + * @param sql A SQL string to compile to a prepared statement. + * @return The prepared statement. + */ + prepare(sql: string): StatementSync; + /** + * Creates and attaches a session to the database. This method is a wrapper around + * [`sqlite3session_create()`](https://www.sqlite.org/session/sqlite3session_create.html) and + * [`sqlite3session_attach()`](https://www.sqlite.org/session/sqlite3session_attach.html). + * @param options The configuration options for the session. + * @returns A session handle. + * @since v22.12.0 + */ + createSession(options?: CreateSessionOptions): Session; + /** + * An exception is thrown if the database is not + * open. This method is a wrapper around + * [`sqlite3changeset_apply()`](https://www.sqlite.org/session/sqlite3changeset_apply.html). + * + * ```js + * const sourceDb = new DatabaseSync(':memory:'); + * const targetDb = new DatabaseSync(':memory:'); + * + * sourceDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)'); + * targetDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)'); + * + * const session = sourceDb.createSession(); + * + * const insert = sourceDb.prepare('INSERT INTO data (key, value) VALUES (?, ?)'); + * insert.run(1, 'hello'); + * insert.run(2, 'world'); + * + * const changeset = session.changeset(); + * targetDb.applyChangeset(changeset); + * // Now that the changeset has been applied, targetDb contains the same data as sourceDb. + * ``` + * @param changeset A binary changeset or patchset. + * @param options The configuration options for how the changes will be applied. + * @returns Whether the changeset was applied successfully without being aborted. + * @since v22.12.0 + */ + applyChangeset(changeset: Uint8Array, options?: ApplyChangesetOptions): boolean; + /** + * Closes the database connection. If the database connection is already closed + * then this is a no-op. + * @since v22.15.0 + * @experimental + */ + [Symbol.dispose](): void; + } + /** + * @since v22.12.0 + */ + interface Session { + /** + * Retrieves a changeset containing all changes since the changeset was created. Can be called multiple times. + * An exception is thrown if the database or the session is not open. This method is a wrapper around + * [`sqlite3session_changeset()`](https://www.sqlite.org/session/sqlite3session_changeset.html). + * @returns Binary changeset that can be applied to other databases. + * @since v22.12.0 + */ + changeset(): NodeJS.NonSharedUint8Array; + /** + * Similar to the method above, but generates a more compact patchset. See + * [Changesets and Patchsets](https://www.sqlite.org/sessionintro.html#changesets_and_patchsets) + * in the documentation of SQLite. An exception is thrown if the database or the session is not open. This method is a + * wrapper around + * [`sqlite3session_patchset()`](https://www.sqlite.org/session/sqlite3session_patchset.html). + * @returns Binary patchset that can be applied to other databases. + * @since v22.12.0 + */ + patchset(): NodeJS.NonSharedUint8Array; + /** + * Closes the session. An exception is thrown if the database or the session is not open. This method is a + * wrapper around + * [`sqlite3session_delete()`](https://www.sqlite.org/session/sqlite3session_delete.html). + */ + close(): void; + } + interface StatementColumnMetadata { + /** + * The unaliased name of the column in the origin + * table, or `null` if the column is the result of an expression or subquery. + * This property is the result of [`sqlite3_column_origin_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + column: string | null; + /** + * The unaliased name of the origin database, or + * `null` if the column is the result of an expression or subquery. This + * property is the result of [`sqlite3_column_database_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + database: string | null; + /** + * The name assigned to the column in the result set of a + * `SELECT` statement. This property is the result of + * [`sqlite3_column_name()`](https://www.sqlite.org/c3ref/column_name.html). + */ + name: string; + /** + * The unaliased name of the origin table, or `null` if + * the column is the result of an expression or subquery. This property is the + * result of [`sqlite3_column_table_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + table: string | null; + /** + * The declared data type of the column, or `null` if the + * column is the result of an expression or subquery. This property is the + * result of [`sqlite3_column_decltype()`](https://www.sqlite.org/c3ref/column_decltype.html). + */ + type: string | null; + } + interface StatementResultingChanges { + /** + * The number of rows modified, inserted, or deleted by the most recently completed `INSERT`, `UPDATE`, or `DELETE` statement. + * This field is either a number or a `BigInt` depending on the prepared statement's configuration. + * This property is the result of [`sqlite3_changes64()`](https://www.sqlite.org/c3ref/changes.html). + */ + changes: number | bigint; + /** + * The most recently inserted rowid. + * This field is either a number or a `BigInt` depending on the prepared statement's configuration. + * This property is the result of [`sqlite3_last_insert_rowid()`](https://www.sqlite.org/c3ref/last_insert_rowid.html). + */ + lastInsertRowid: number | bigint; + } + /** + * This class represents a single [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This class cannot be + * instantiated via its constructor. Instead, instances are created via the`database.prepare()` method. All APIs exposed by this class execute + * synchronously. + * + * A prepared statement is an efficient binary representation of the SQL used to + * create it. Prepared statements are parameterizable, and can be invoked multiple + * times with different bound values. Parameters also offer protection against [SQL injection](https://en.wikipedia.org/wiki/SQL_injection) attacks. For these reasons, prepared statements are + * preferred + * over hand-crafted SQL strings when handling user input. + * @since v22.5.0 + */ + class StatementSync { + private constructor(); + /** + * This method executes a prepared statement and returns all results as an array of + * objects. If the prepared statement does not return any results, this method + * returns an empty array. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using + * the values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @return An array of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of + * the row. + */ + all(...anonymousParameters: SQLInputValue[]): Record[]; + all( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): Record[]; + /** + * This method is used to retrieve information about the columns returned by the + * prepared statement. + * @since v22.16.0 + * @returns An array of objects. Each object corresponds to a column + * in the prepared statement, and contains the following properties: + */ + columns(): StatementColumnMetadata[]; + /** + * The source SQL text of the prepared statement with parameter + * placeholders replaced by the values that were used during the most recent + * execution of this prepared statement. This property is a wrapper around + * [`sqlite3_expanded_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html). + * @since v22.5.0 + */ + readonly expandedSQL: string; + /** + * This method executes a prepared statement and returns the first result as an + * object. If the prepared statement does not return any results, this method + * returns `undefined`. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the + * values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @return An object corresponding to the first row returned by executing the prepared statement. The keys and values of the object correspond to the column names and values of the row. If no + * rows were returned from the database then this method returns `undefined`. + */ + get(...anonymousParameters: SQLInputValue[]): Record | undefined; + get( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): Record | undefined; + /** + * This method executes a prepared statement and returns an iterator of + * objects. If the prepared statement does not return any results, this method + * returns an empty iterator. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using + * the values in `namedParameters` and `anonymousParameters`. + * @since v22.13.0 + * @param namedParameters An optional object used to bind named parameters. + * The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @returns An iterable iterator of objects. Each object corresponds to a row + * returned by executing the prepared statement. The keys and values of each + * object correspond to the column names and values of the row. + */ + iterate(...anonymousParameters: SQLInputValue[]): NodeJS.Iterator>; + iterate( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): NodeJS.Iterator>; + /** + * This method executes a prepared statement and returns an object summarizing the + * resulting changes. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the + * values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + */ + run(...anonymousParameters: SQLInputValue[]): StatementResultingChanges; + run( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): StatementResultingChanges; + /** + * The names of SQLite parameters begin with a prefix character. By default,`node:sqlite` requires that this prefix character is present when binding + * parameters. However, with the exception of dollar sign character, these + * prefix characters also require extra quoting when used in object keys. + * + * To improve ergonomics, this method can be used to also allow bare named + * parameters, which do not require the prefix character in JavaScript code. There + * are several caveats to be aware of when enabling bare named parameters: + * + * * The prefix character is still required in SQL. + * * The prefix character is still allowed in JavaScript. In fact, prefixed names + * will have slightly better binding performance. + * * Using ambiguous named parameters, such as `$k` and `@k`, in the same prepared + * statement will result in an exception as it cannot be determined how to bind + * a bare name. + * @since v22.5.0 + * @param enabled Enables or disables support for binding named parameters without the prefix character. + */ + setAllowBareNamedParameters(enabled: boolean): void; + /** + * By default, if an unknown name is encountered while binding parameters, an + * exception is thrown. This method allows unknown named parameters to be ignored. + * @since v22.15.0 + * @param enabled Enables or disables support for unknown named parameters. + */ + setAllowUnknownNamedParameters(enabled: boolean): void; + /** + * When enabled, query results returned by the `all()`, `get()`, and `iterate()` methods will be returned as arrays instead + * of objects. + * @since v22.16.0 + * @param enabled Enables or disables the return of query results as arrays. + */ + setReturnArrays(enabled: boolean): void; + /** + * When reading from the database, SQLite `INTEGER`s are mapped to JavaScript + * numbers by default. However, SQLite `INTEGER`s can store values larger than + * JavaScript numbers are capable of representing. In such cases, this method can + * be used to read `INTEGER` data using JavaScript `BigInt`s. This method has no + * impact on database write operations where numbers and `BigInt`s are both + * supported at all times. + * @since v22.5.0 + * @param enabled Enables or disables the use of `BigInt`s when reading `INTEGER` fields from the database. + */ + setReadBigInts(enabled: boolean): void; + /** + * The source SQL text of the prepared statement. This property is a + * wrapper around [`sqlite3_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html). + * @since v22.5.0 + */ + readonly sourceSQL: string; + } + interface BackupOptions { + /** + * Name of the source database. This can be `'main'` (the default primary database) or any other + * database that have been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) + * @default 'main' + */ + source?: string | undefined; + /** + * Name of the target database. This can be `'main'` (the default primary database) or any other + * database that have been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) + * @default 'main' + */ + target?: string | undefined; + /** + * Number of pages to be transmitted in each batch of the backup. + * @default 100 + */ + rate?: number | undefined; + /** + * Callback function that will be called with the number of pages copied and the total number of + * pages. + */ + progress?: ((progressInfo: BackupProgressInfo) => void) | undefined; + } + interface BackupProgressInfo { + totalPages: number; + remainingPages: number; + } + /** + * This method makes a database backup. This method abstracts the + * [`sqlite3_backup_init()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupinit), + * [`sqlite3_backup_step()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupstep) + * and [`sqlite3_backup_finish()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupfinish) functions. + * + * The backed-up database can be used normally during the backup process. Mutations coming from the same connection - same + * `DatabaseSync` - object will be reflected in the backup right away. However, mutations from other connections will cause + * the backup process to restart. + * + * ```js + * import { backup, DatabaseSync } from 'node:sqlite'; + * + * const sourceDb = new DatabaseSync('source.db'); + * const totalPagesTransferred = await backup(sourceDb, 'backup.db', { + * rate: 1, // Copy one page at a time. + * progress: ({ totalPages, remainingPages }) => { + * console.log('Backup in progress', { totalPages, remainingPages }); + * }, + * }); + * + * console.log('Backup completed', totalPagesTransferred); + * ``` + * @since v22.16.0 + * @param sourceDb The database to backup. The source database must be open. + * @param path The path where the backup will be created. If the file already exists, + * the contents will be overwritten. + * @param options Optional configuration for the backup. The + * following properties are supported: + * @returns A promise that resolves when the backup is completed and rejects if an error occurs. + */ + function backup(sourceDb: DatabaseSync, path: PathLike, options?: BackupOptions): Promise; + /** + * @since v22.13.0 + */ + namespace constants { + /** + * The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is present in the database, but one or more other (non primary-key) fields modified by the update do not contain the expected "before" values. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_DATA: number; + /** + * The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is not present in the database. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_NOTFOUND: number; + /** + * This constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_CONFLICT: number; + /** + * If foreign key handling is enabled, and applying a changeset leaves the database in a state containing foreign key violations, the conflict handler is invoked with this constant exactly once before the changeset is committed. If the conflict handler returns `SQLITE_CHANGESET_OMIT`, the changes, including those that caused the foreign key constraint violation, are committed. Or, if it returns `SQLITE_CHANGESET_ABORT`, the changeset is rolled back. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_FOREIGN_KEY: number; + /** + * Conflicting changes are omitted. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_OMIT: number; + /** + * Conflicting changes replace existing values. Note that this value can only be returned when the type of conflict is either `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT`. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_REPLACE: number; + /** + * Abort when a change encounters a conflict and roll back database. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_ABORT: number; + } +} diff --git a/node_modules/@types/node/stream.d.ts b/node_modules/@types/node/stream.d.ts new file mode 100644 index 0000000..5799cc0 --- /dev/null +++ b/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1664 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `node:stream` module provides an API for implementing the stream interface. + * + * There are many stream objects provided by Node.js. For instance, a [request to an HTTP server](https://nodejs.org/docs/latest-v22.x/api/http.html#class-httpincomingmessage) + * and [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of [`EventEmitter`](https://nodejs.org/docs/latest-v22.x/api/events.html#class-eventemitter). + * + * To access the `node:stream` module: + * + * ```js + * import stream from 'node:stream'; + * ``` + * + * The `node:stream` module is useful for creating new types of stream instances. + * It is usually not necessary to use the `node:stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/stream.js) + */ +declare module "stream" { + import { Abortable, EventEmitter } from "node:events"; + import { Blob as NodeBlob } from "node:buffer"; + import * as streamPromises from "node:stream/promises"; + import * as streamWeb from "node:stream/web"; + + type ComposeFnParam = (source: any) => void; + + class Stream extends EventEmitter { + pipe( + destination: T, + options?: { + end?: boolean | undefined; + }, + ): T; + compose( + stream: T | ComposeFnParam | Iterable | AsyncIterable, + options?: { signal: AbortSignal }, + ): T; + } + namespace Stream { + export { Stream, streamPromises as promises }; + } + namespace Stream { + interface StreamOptions extends Abortable { + emitClose?: boolean | undefined; + highWaterMark?: number | undefined; + objectMode?: boolean | undefined; + construct?: ((this: T, callback: (error?: Error | null) => void) => void) | undefined; + destroy?: ((this: T, error: Error | null, callback: (error?: Error | null) => void) => void) | undefined; + autoDestroy?: boolean | undefined; + } + interface ReadableOptions extends StreamOptions { + encoding?: BufferEncoding | undefined; + read?: ((this: T, size: number) => void) | undefined; + } + interface ArrayOptions { + /** + * The maximum concurrent invocations of `fn` to call on the stream at once. + * @default 1 + */ + concurrency?: number | undefined; + /** Allows destroying the stream if the signal is aborted. */ + signal?: AbortSignal | undefined; + } + /** + * @since v0.9.4 + */ + class Readable extends Stream implements NodeJS.ReadableStream { + /** + * A utility method for creating Readable Streams out of iterators. + * @since v12.3.0, v10.17.0 + * @param iterable Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed. + * @param options Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * A utility method for creating a `Readable` from a web `ReadableStream`. + * @since v17.0.0 + */ + static fromWeb( + readableStream: streamWeb.ReadableStream, + options?: Pick, + ): Readable; + /** + * A utility method for creating a web `ReadableStream` from a `Readable`. + * @since v17.0.0 + */ + static toWeb( + streamReadable: Readable, + options?: { + strategy?: streamWeb.QueuingStrategy | undefined; + }, + ): streamWeb.ReadableStream; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call {@link read}, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + * @since v11.4.0 + */ + readable: boolean; + /** + * Returns whether `'data'` has been emitted. + * @since v16.7.0, v14.18.0 + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding` property can be set using the {@link setEncoding} method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when [`'end'`](https://nodejs.org/docs/latest-v22.x/api/stream.html#event-end) event is emitted. + * @since v12.9.0 + */ + readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the [Three states](https://nodejs.org/docs/latest-v22.x/api/stream.html#three-states) section. + * @since v9.4.0 + */ + readonly readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + * @since v9.3.0 + */ + readonly readableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be read. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + * @since v12.3.0 + */ + readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + constructor(opts?: ReadableOptions); + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + /** + * The `readable.read()` method reads data out of the internal buffer and + * returns it. If no data is available to be read, `null` is returned. By default, + * the data is returned as a `Buffer` object unless an encoding has been + * specified using the `readable.setEncoding()` method or the stream is operating + * in object mode. + * + * The optional `size` argument specifies a specific number of bytes to read. If + * `size` bytes are not available to be read, `null` will be returned _unless_ the + * stream has ended, in which case all of the data remaining in the internal buffer + * will be returned. + * + * If the `size` argument is not specified, all of the data contained in the + * internal buffer will be returned. + * + * The `size` argument must be less than or equal to 1 GiB. + * + * The `readable.read()` method should only be called on `Readable` streams + * operating in paused mode. In flowing mode, `readable.read()` is called + * automatically until the internal buffer is fully drained. + * + * ```js + * const readable = getReadableStreamSomehow(); + * + * // 'readable' may be triggered multiple times as data is buffered in + * readable.on('readable', () => { + * let chunk; + * console.log('Stream is readable (new data received in buffer)'); + * // Use a loop to make sure we read all currently available data + * while (null !== (chunk = readable.read())) { + * console.log(`Read ${chunk.length} bytes of data...`); + * } + * }); + * + * // 'end' will be triggered once when there is no more data available + * readable.on('end', () => { + * console.log('Reached end of stream.'); + * }); + * ``` + * + * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks + * are not concatenated. A `while` loop is necessary to consume all data + * currently in the buffer. When reading a large file `.read()` may return `null`, + * having consumed all buffered content so far, but there is still more data to + * come not yet buffered. In this case a new `'readable'` event will be emitted + * when there is more data in the buffer. Finally the `'end'` event will be + * emitted when there is no more data to come. + * + * Therefore to read a file's whole contents from a `readable`, it is necessary + * to collect chunks across multiple `'readable'` events: + * + * ```js + * const chunks = []; + * + * readable.on('readable', () => { + * let chunk; + * while (null !== (chunk = readable.read())) { + * chunks.push(chunk); + * } + * }); + * + * readable.on('end', () => { + * const content = chunks.join(''); + * }); + * ``` + * + * A `Readable` stream in object mode will always return a single item from + * a call to `readable.read(size)`, regardless of the value of the `size` argument. + * + * If the `readable.read()` method returns a chunk of data, a `'data'` event will + * also be emitted. + * + * Calling {@link read} after the `'end'` event has + * been emitted will return `null`. No runtime error will be raised. + * @since v0.9.4 + * @param size Optional argument to specify how much data to read. + */ + read(size?: number): any; + /** + * The `readable.setEncoding()` method sets the character encoding for + * data read from the `Readable` stream. + * + * By default, no encoding is assigned and stream data will be returned as `Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer` objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling `readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * string format. + * + * The `Readable` stream will properly handle multi-byte characters delivered + * through the stream that would otherwise become improperly decoded if simply + * pulled from the stream as `Buffer` objects. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.setEncoding('utf8'); + * readable.on('data', (chunk) => { + * assert.equal(typeof chunk, 'string'); + * console.log('Got %d characters of string data:', chunk.length); + * }); + * ``` + * @since v0.9.4 + * @param encoding The encoding to use. + */ + setEncoding(encoding: BufferEncoding): this; + /** + * The `readable.pause()` method will cause a stream in flowing mode to stop + * emitting `'data'` events, switching out of flowing mode. Any data that + * becomes available will remain in the internal buffer. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.on('data', (chunk) => { + * console.log(`Received ${chunk.length} bytes of data.`); + * readable.pause(); + * console.log('There will be no additional data for 1 second.'); + * setTimeout(() => { + * console.log('Now data will start flowing again.'); + * readable.resume(); + * }, 1000); + * }); + * ``` + * + * The `readable.pause()` method has no effect if there is a `'readable'` event listener. + * @since v0.9.4 + */ + pause(): this; + /** + * The `readable.resume()` method causes an explicitly paused `Readable` stream to + * resume emitting `'data'` events, switching the stream into flowing mode. + * + * The `readable.resume()` method can be used to fully consume the data from a + * stream without actually processing any of that data: + * + * ```js + * getReadableStreamSomehow() + * .resume() + * .on('end', () => { + * console.log('Reached the end, but did not read anything.'); + * }); + * ``` + * + * The `readable.resume()` method has no effect if there is a `'readable'` event listener. + * @since v0.9.4 + */ + resume(): this; + /** + * The `readable.isPaused()` method returns the current operating state of the `Readable`. + * This is used primarily by the mechanism that underlies the `readable.pipe()` method. + * In most typical cases, there will be no reason to use this method directly. + * + * ```js + * const readable = new stream.Readable(); + * + * readable.isPaused(); // === false + * readable.pause(); + * readable.isPaused(); // === true + * readable.resume(); + * readable.isPaused(); // === false + * ``` + * @since v0.11.14 + */ + isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * import fs from 'node:fs'; + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @since v0.9.4 + * @param destination Optional specific stream to unpipe + */ + unpipe(destination?: NodeJS.WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * import { StringDecoder } from 'node:string_decoder'; + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.includes('\n\n')) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * return; + * } + * // Still reading the header. + * header += str; + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @since v0.9.11 + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must + * be a {string}, {Buffer}, {TypedArray}, {DataView} or `null`. For object mode streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ + unshift(chunk: any, encoding?: BufferEncoding): void; + /** + * Prior to Node.js 0.10, streams did not implement the entire `node:stream` module API as it is currently defined. (See `Compatibility` for more + * information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the `readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * import { OldReader } from './old-api-module.js'; + * import { Readable } from 'node:stream'; + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @since v0.9.4 + * @param stream An "old style" readable stream + */ + wrap(stream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + /** + * The iterator created by this method gives users the option to cancel the destruction + * of the stream if the `for await...of` loop is exited by `return`, `break`, or `throw`, + * or if the iterator should destroy the stream if the stream emitted an error during iteration. + * @since v16.3.0 + * @param options.destroyOnReturn When set to `false`, calling `return` on the async iterator, + * or exiting a `for await...of` iteration using a `break`, `return`, or `throw` will not destroy the stream. + * **Default: `true`**. + */ + iterator(options?: { destroyOnReturn?: boolean }): NodeJS.AsyncIterator; + /** + * This method allows mapping over the stream. The *fn* function will be called for every chunk in the stream. + * If the *fn* function returns a promise - that promise will be `await`ed before being passed to the result stream. + * @since v17.4.0, v16.14.0 + * @param fn a function to map over every chunk in the stream. Async or not. + * @returns a stream mapped with the function *fn*. + */ + map(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method allows filtering the stream. For each chunk in the stream the *fn* function will be called + * and if it returns a truthy value, the chunk will be passed to the result stream. + * If the *fn* function returns a promise - that promise will be `await`ed. + * @since v17.4.0, v16.14.0 + * @param fn a function to filter chunks from the stream. Async or not. + * @returns a stream filtered with the predicate *fn*. + */ + filter( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Readable; + /** + * This method allows iterating a stream. For each chunk in the stream the *fn* function will be called. + * If the *fn* function returns a promise - that promise will be `await`ed. + * + * This method is different from `for await...of` loops in that it can optionally process chunks concurrently. + * In addition, a `forEach` iteration can only be stopped by having passed a `signal` option + * and aborting the related AbortController while `for await...of` can be stopped with `break` or `return`. + * In either case the stream will be destroyed. + * + * This method is different from listening to the `'data'` event in that it uses the `readable` event + * in the underlying machinary and can limit the number of concurrent *fn* calls. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise for when the stream has finished. + */ + forEach( + fn: (data: any, options?: Pick) => void | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method allows easily obtaining the contents of a stream. + * + * As this method reads the entire stream into memory, it negates the benefits of streams. It's intended + * for interoperability and convenience, not as the primary way to consume streams. + * @since v17.5.0 + * @returns a promise containing an array with the contents of the stream. + */ + toArray(options?: Pick): Promise; + /** + * This method is similar to `Array.prototype.some` and calls *fn* on each chunk in the stream + * until the awaited return value is `true` (or any truthy value). Once an *fn* call on a chunk + * `await`ed return value is truthy, the stream is destroyed and the promise is fulfilled with `true`. + * If none of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `false`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for at least one of the chunks. + */ + some( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.find` and calls *fn* on each chunk in the stream + * to find a chunk with a truthy value for *fn*. Once an *fn* call's awaited return value is truthy, + * the stream is destroyed and the promise is fulfilled with value for which *fn* returned a truthy value. + * If all of the *fn* calls on the chunks return a falsy value, the promise is fulfilled with `undefined`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to the first chunk for which *fn* evaluated with a truthy value, + * or `undefined` if no element was found. + */ + find( + fn: (data: any, options?: Pick) => data is T, + options?: ArrayOptions, + ): Promise; + find( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.every` and calls *fn* on each chunk in the stream + * to check if all awaited return values are truthy value for *fn*. Once an *fn* call on a chunk + * `await`ed return value is falsy, the stream is destroyed and the promise is fulfilled with `false`. + * If all of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `true`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for every one of the chunks. + */ + every( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method returns a new stream by applying the given callback to each chunk of the stream + * and then flattening the result. + * + * It is possible to return a stream or another iterable or async iterable from *fn* and the result streams + * will be merged (flattened) into the returned stream. + * @since v17.5.0 + * @param fn a function to map over every chunk in the stream. May be async. May be a stream or generator. + * @returns a stream flat-mapped with the function *fn*. + */ + flatMap(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method returns a new stream with the first *limit* chunks dropped from the start. + * @since v17.5.0 + * @param limit the number of chunks to drop from the readable. + * @returns a stream with *limit* chunks dropped from the start. + */ + drop(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with the first *limit* chunks. + * @since v17.5.0 + * @param limit the number of chunks to take from the readable. + * @returns a stream with *limit* chunks taken. + */ + take(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with chunks of the underlying stream paired with a counter + * in the form `[index, chunk]`. The first index value is `0` and it increases by 1 for each chunk produced. + * @since v17.5.0 + * @returns a stream of indexed pairs. + */ + asIndexedPairs(options?: Pick): Readable; + /** + * This method calls *fn* on each chunk of the stream in order, passing it the result from the calculation + * on the previous element. It returns a promise for the final value of the reduction. + * + * If no *initial* value is supplied the first chunk of the stream is used as the initial value. + * If the stream is empty, the promise is rejected with a `TypeError` with the `ERR_INVALID_ARGS` code property. + * + * The reducer function iterates the stream element-by-element which means that there is no *concurrency* parameter + * or parallelism. To perform a reduce concurrently, you can extract the async function to `readable.map` method. + * @since v17.5.0 + * @param fn a reducer function to call over every chunk in the stream. Async or not. + * @param initial the initial value to use in the reduction. + * @returns a promise for the final value of the reduction. + */ + reduce( + fn: (previous: any, data: any, options?: Pick) => T, + initial?: undefined, + options?: Pick, + ): Promise; + reduce( + fn: (previous: T, data: any, options?: Pick) => T, + initial: T, + options?: Pick, + ): Promise; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()` will be ignored. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, but instead implement `readable._destroy()`. + * @since v8.0.0 + * @param error Error which will be passed as payload in `'error'` event + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. error + * 5. pause + * 6. readable + * 7. resume + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "pause"): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + /** + * Calls `readable.destroy()` with an `AbortError` and returns a promise that fulfills when the stream is finished. + * @since v20.4.0 + */ + [Symbol.asyncDispose](): Promise; + } + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean | undefined; + defaultEncoding?: BufferEncoding | undefined; + write?: + | (( + this: T, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ) => void) + | undefined; + writev?: + | (( + this: T, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ) => void) + | undefined; + final?: ((this: T, callback: (error?: Error | null) => void) => void) | undefined; + } + /** + * @since v0.9.4 + */ + class Writable extends Stream implements NodeJS.WritableStream { + /** + * A utility method for creating a `Writable` from a web `WritableStream`. + * @since v17.0.0 + */ + static fromWeb( + writableStream: streamWeb.WritableStream, + options?: Pick, + ): Writable; + /** + * A utility method for creating a web `WritableStream` from a `Writable`. + * @since v17.0.0 + */ + static toWeb(streamWritable: Writable): streamWeb.WritableStream; + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored, or ended. + * @since v11.4.0 + */ + readonly writable: boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'finish'`. + * @since v18.0.0, v16.17.0 + */ + readonly writableAborted: boolean; + /** + * Is `true` after `writable.end()` has been called. This property + * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. + * @since v12.9.0 + */ + readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + * @since v12.6.0 + */ + readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + * @since v9.3.0 + */ + readonly writableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be written. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + * @since v12.3.0 + */ + readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + * @since v13.2.0, v12.16.0 + */ + readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + /** + * Is `true` if the stream's buffer has been full and stream will emit `'drain'`. + * @since v15.2.0, v14.17.0 + */ + readonly writableNeedDrain: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + _construct?(callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + /** + * The `writable.write()` method writes some data to the stream, and calls the + * supplied `callback` once the data has been fully handled. If an error + * occurs, the `callback` will be called with the error as its + * first argument. The `callback` is called asynchronously and before `'error'` is + * emitted. + * + * The return value is `true` if the internal buffer is less than the `highWaterMark` configured when the stream was created after admitting `chunk`. + * If `false` is returned, further attempts to write data to the stream should + * stop until the `'drain'` event is emitted. + * + * While a stream is not draining, calls to `write()` will buffer `chunk`, and + * return false. Once all currently buffered chunks are drained (accepted for + * delivery by the operating system), the `'drain'` event will be emitted. + * Once `write()` returns false, do not write more chunks + * until the `'drain'` event is emitted. While calling `write()` on a stream that + * is not draining is allowed, Node.js will buffer all written chunks until + * maximum memory usage occurs, at which point it will abort unconditionally. + * Even before it aborts, high memory usage will cause poor garbage collector + * performance and high RSS (which is not typically released back to the system, + * even after the memory is no longer required). Since TCP sockets may never + * drain if the remote peer does not read the data, writing a socket that is + * not draining may lead to a remotely exploitable vulnerability. + * + * Writing data while the stream is not draining is particularly + * problematic for a `Transform`, because the `Transform` streams are paused + * by default until they are piped or a `'data'` or `'readable'` event handler + * is added. + * + * If the data to be written can be generated or fetched on demand, it is + * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is + * possible to respect backpressure and avoid memory issues using the `'drain'` event: + * + * ```js + * function write(data, cb) { + * if (!stream.write(data)) { + * stream.once('drain', cb); + * } else { + * process.nextTick(cb); + * } + * } + * + * // Wait for cb to be called before doing any other write. + * write('hello', () => { + * console.log('Write completed, do more writes now.'); + * }); + * ``` + * + * A `Writable` stream in object mode will always ignore the `encoding` argument. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param [encoding='utf8'] The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @since v0.11.15 + * @param encoding The new default encoding + */ + setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * import fs from 'node:fs'; + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param callback Callback for when the stream is finished. + */ + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()` buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing `writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + * @since v0.11.2 + */ + cork(): void; + /** + * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. + * + * When using `writable.cork()` and `writable.uncork()` to manage the buffering + * of writes to a stream, defer calls to `writable.uncork()` using `process.nextTick()`. Doing so allows batching of all `writable.write()` calls that occur within a given Node.js event + * loop phase. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.write('data '); + * process.nextTick(() => stream.uncork()); + * ``` + * + * If the `writable.cork()` method is called multiple times on a stream, the + * same number of calls to `writable.uncork()` must be called to flush the buffered + * data. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.cork(); + * stream.write('data '); + * process.nextTick(() => { + * stream.uncork(); + * // The data will not be flushed until uncork() is called a second time. + * stream.uncork(); + * }); + * ``` + * + * See also: `writable.cork()`. + * @since v0.11.2 + */ + uncork(): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the writable + * stream has ended and subsequent calls to `write()` or `end()` will result in + * an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to `write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * Use `end()` instead of destroy if data should flush before close, or wait for + * the `'drain'` event before destroying the stream. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, + * but instead implement `writable._destroy()`. + * @since v8.0.0 + * @param error Optional, an error to emit with `'error'` event. + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean | undefined; + readableObjectMode?: boolean | undefined; + writableObjectMode?: boolean | undefined; + readableHighWaterMark?: number | undefined; + writableHighWaterMark?: number | undefined; + writableCorked?: number | undefined; + } + /** + * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Duplex` streams include: + * + * * `TCP sockets` + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Duplex extends Stream implements NodeJS.ReadWriteStream { + /** + * If `false` then the stream will automatically end the writable side when the + * readable side ends. Set initially by the `allowHalfOpen` constructor option, + * which defaults to `true`. + * + * This can be changed manually to change the half-open behavior of an existing + * `Duplex` stream instance, but must be changed before the `'end'` event is emitted. + * @since v0.9.4 + */ + allowHalfOpen: boolean; + constructor(opts?: DuplexOptions); + /** + * A utility method for creating duplex streams. + * + * - `Stream` converts writable stream into writable `Duplex` and readable stream + * to `Duplex`. + * - `Blob` converts into readable `Duplex`. + * - `string` converts into readable `Duplex`. + * - `ArrayBuffer` converts into readable `Duplex`. + * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. + * - `AsyncGeneratorFunction` converts into a readable/writable transform + * `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + * `null`. + * - `AsyncFunction` converts into a writable `Duplex`. Must return + * either `null` or `undefined` + * - `Object ({ writable, readable })` converts `readable` and + * `writable` into `Stream` and then combines them into `Duplex` where the + * `Duplex` will write to the `writable` and read from the `readable`. + * - `Promise` converts into readable `Duplex`. Value `null` is ignored. + * + * @since v16.8.0 + */ + static from( + src: + | Stream + | NodeBlob + | ArrayBuffer + | string + | Iterable + | AsyncIterable + | AsyncGeneratorFunction + | Promise + | Object, + ): Duplex; + /** + * A utility method for creating a web `ReadableStream` and `WritableStream` from a `Duplex`. + * @since v17.0.0 + */ + static toWeb(streamDuplex: Duplex): { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }; + /** + * A utility method for creating a `Duplex` from a web `ReadableStream` and `WritableStream`. + * @since v17.0.0 + */ + static fromWeb( + duplexStream: { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }, + options?: Pick< + DuplexOptions, + "allowHalfOpen" | "decodeStrings" | "encoding" | "highWaterMark" | "objectMode" | "signal" + >, + ): Duplex; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. drain + * 4. end + * 5. error + * 6. finish + * 7. pause + * 8. pipe + * 9. readable + * 10. resume + * 11. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pause"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pause", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pause", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + interface Duplex extends Readable, Writable {} + /** + * The utility function `duplexPair` returns an Array with two items, + * each being a `Duplex` stream connected to the other side: + * + * ```js + * const [ sideA, sideB ] = duplexPair(); + * ``` + * + * Whatever is written to one stream is made readable on the other. It provides + * behavior analogous to a network connection, where the data written by the client + * becomes readable by the server, and vice-versa. + * + * The Duplex streams are symmetrical; one or the other may be used without any + * difference in behavior. + * @param options A value to pass to both {@link Duplex} constructors, + * to set options such as buffering. + * @since v22.6.0 + */ + function duplexPair(options?: DuplexOptions): [Duplex, Duplex]; + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + transform?: + | ((this: T, chunk: any, encoding: BufferEncoding, callback: TransformCallback) => void) + | undefined; + flush?: ((this: T, callback: TransformCallback) => void) | undefined; + } + /** + * Transform streams are `Duplex` streams where the output is in some way + * related to the input. Like all `Duplex` streams, `Transform` streams + * implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Transform` streams include: + * + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + /** + * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is + * primarily for examples and testing, but there are some use cases where `stream.PassThrough` is useful as a building block for novel sorts of streams. + */ + class PassThrough extends Transform {} + /** + * A stream to attach a signal to. + * + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed `AbortSignal` will behave the same way as calling `.destroy(new AbortError())` on the + * stream, and `controller.error(new AbortError())` for webstreams. + * + * ```js + * import fs from 'node:fs'; + * + * const controller = new AbortController(); + * const read = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * // Later, abort the operation closing the stream + * controller.abort(); + * ``` + * + * Or using an `AbortSignal` with a readable stream as an async iterable: + * + * ```js + * const controller = new AbortController(); + * setTimeout(() => controller.abort(), 10_000); // set a timeout + * const stream = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * (async () => { + * try { + * for await (const chunk of stream) { + * await process(chunk); + * } + * } catch (e) { + * if (e.name === 'AbortError') { + * // The operation was cancelled + * } else { + * throw e; + * } + * } + * })(); + * ``` + * + * Or using an `AbortSignal` with a ReadableStream: + * + * ```js + * const controller = new AbortController(); + * const rs = new ReadableStream({ + * start(controller) { + * controller.enqueue('hello'); + * controller.enqueue('world'); + * controller.close(); + * }, + * }); + * + * addAbortSignal(controller.signal, rs); + * + * finished(rs, (err) => { + * if (err) { + * if (err.name === 'AbortError') { + * // The operation was cancelled + * } + * } + * }); + * + * const reader = rs.getReader(); + * + * reader.read().then(({ value, done }) => { + * console.log(value); // hello + * console.log(done); // false + * controller.abort(); + * }); + * ``` + * @since v15.4.0 + * @param signal A signal representing possible cancellation + * @param stream A stream to attach a signal to. + */ + function addAbortSignal(signal: AbortSignal, stream: T): T; + /** + * Returns the default highWaterMark used by streams. + * Defaults to `65536` (64 KiB), or `16` for `objectMode`. + * @since v19.9.0 + */ + function getDefaultHighWaterMark(objectMode: boolean): number; + /** + * Sets the default highWaterMark used by streams. + * @since v19.9.0 + * @param value highWaterMark value + */ + function setDefaultHighWaterMark(objectMode: boolean, value: number): void; + interface FinishedOptions extends Abortable { + error?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + /** + * A readable and/or writable stream/webstream. + * + * A function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * import { finished } from 'node:stream'; + * import fs from 'node:fs'; + * + * const rs = fs.createReadStream('archive.tar'); + * + * finished(rs, (err) => { + * if (err) { + * console.error('Stream failed.', err); + * } else { + * console.log('Stream is done reading.'); + * } + * }); + * + * rs.resume(); // Drain the stream. + * ``` + * + * Especially useful in error handling scenarios where a stream is destroyed + * prematurely (like an aborted HTTP request), and will not emit `'end'` or `'finish'`. + * + * The `finished` API provides [`promise version`](https://nodejs.org/docs/latest-v22.x/api/stream.html#streamfinishedstream-options). + * + * `stream.finished()` leaves dangling event listeners (in particular `'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * invoked. The reason for this is so that unexpected `'error'` events (due to + * incorrect stream implementations) do not cause unexpected crashes. + * If this is unwanted behavior then the returned cleanup function needs to be + * invoked in the callback: + * + * ```js + * const cleanup = finished(rs, (err) => { + * cleanup(); + * // ... + * }); + * ``` + * @since v10.0.0 + * @param stream A readable and/or writable stream. + * @param callback A callback function that takes an optional error argument. + * @returns A cleanup function which removes all registered listeners. + */ + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options: FinishedOptions, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + namespace finished { + function __promisify__( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + } + type PipelineSourceFunction = () => Iterable | AsyncIterable; + type PipelineSource = Iterable | AsyncIterable | NodeJS.ReadableStream | PipelineSourceFunction; + type PipelineTransform, U> = + | NodeJS.ReadWriteStream + | (( + source: S extends (...args: any[]) => Iterable | AsyncIterable ? AsyncIterable + : S, + ) => AsyncIterable); + type PipelineTransformSource = PipelineSource | PipelineTransform; + type PipelineDestinationIterableFunction = (source: AsyncIterable) => AsyncIterable; + type PipelineDestinationPromiseFunction = (source: AsyncIterable) => Promise

                          ; + type PipelineDestination, P> = S extends + PipelineTransformSource ? + | NodeJS.WritableStream + | PipelineDestinationIterableFunction + | PipelineDestinationPromiseFunction + : never; + type PipelineCallback> = S extends + PipelineDestinationPromiseFunction ? (err: NodeJS.ErrnoException | null, value: P) => void + : (err: NodeJS.ErrnoException | null) => void; + type PipelinePromise> = S extends + PipelineDestinationPromiseFunction ? Promise

                          : Promise; + interface PipelineOptions { + signal?: AbortSignal | undefined; + end?: boolean | undefined; + } + /** + * A module method to pipe between streams and generators forwarding errors and + * properly cleaning up and provide a callback when the pipeline is complete. + * + * ```js + * import { pipeline } from 'node:stream'; + * import fs from 'node:fs'; + * import zlib from 'node:zlib'; + * + * // Use the pipeline API to easily pipe a series of streams + * // together and get notified when the pipeline is fully done. + * + * // A pipeline to gzip a potentially huge tar file efficiently: + * + * pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * (err) => { + * if (err) { + * console.error('Pipeline failed.', err); + * } else { + * console.log('Pipeline succeeded.'); + * } + * }, + * ); + * ``` + * + * The `pipeline` API provides a [`promise version`](https://nodejs.org/docs/latest-v22.x/api/stream.html#streampipelinesource-transforms-destination-options). + * + * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * + * * `Readable` streams which have emitted `'end'` or `'close'`. + * * `Writable` streams which have emitted `'finish'` or `'close'`. + * + * `stream.pipeline()` leaves dangling event listeners on the streams + * after the `callback` has been invoked. In the case of reuse of streams after + * failure, this can cause event listener leaks and swallowed errors. If the last + * stream is readable, dangling event listeners will be removed so that the last + * stream can be consumed later. + * + * `stream.pipeline()` closes all the streams when an error is raised. + * The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior + * once it would destroy the socket without sending the expected response. + * See the example below: + * + * ```js + * import fs from 'node:fs'; + * import http from 'node:http'; + * import { pipeline } from 'node:stream'; + * + * const server = http.createServer((req, res) => { + * const fileStream = fs.createReadStream('./fileNotExist.txt'); + * pipeline(fileStream, res, (err) => { + * if (err) { + * console.log(err); // No such file + * // this message can't be sent once `pipeline` already destroyed the socket + * return res.end('error!!!'); + * } + * }); + * }); + * ``` + * @since v10.0.0 + * @param callback Called when the pipeline is fully done. + */ + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline( + streams: ReadonlyArray, + callback: (err: NodeJS.ErrnoException | null) => void, + ): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array< + NodeJS.ReadWriteStream | NodeJS.WritableStream | ((err: NodeJS.ErrnoException | null) => void) + > + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; + } + // TODO: this interface never existed; remove in next major + interface Pipe { + close(): void; + hasRef(): boolean; + ref(): void; + unref(): void; + } + /** + * Returns whether the stream has encountered an error. + * @since v17.3.0, v16.14.0 + */ + function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; + /** + * Returns whether the stream is readable. + * @since v17.4.0, v16.14.0 + */ + function isReadable(stream: Readable | NodeJS.ReadableStream): boolean; + } + export = Stream; +} +declare module "node:stream" { + import stream = require("stream"); + export = stream; +} diff --git a/node_modules/@types/node/stream/consumers.d.ts b/node_modules/@types/node/stream/consumers.d.ts new file mode 100644 index 0000000..05db025 --- /dev/null +++ b/node_modules/@types/node/stream/consumers.d.ts @@ -0,0 +1,38 @@ +/** + * The utility consumer functions provide common options for consuming + * streams. + * @since v16.7.0 + */ +declare module "stream/consumers" { + import { Blob as NodeBlob, NonSharedBuffer } from "node:buffer"; + import { ReadableStream as WebReadableStream } from "node:stream/web"; + /** + * @since v16.7.0 + * @returns Fulfills with an `ArrayBuffer` containing the full contents of the stream. + */ + function arrayBuffer(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with a `Blob` containing the full contents of the stream. + */ + function blob(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with a `Buffer` containing the full contents of the stream. + */ + function buffer(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with the contents of the stream parsed as a + * UTF-8 encoded string that is then passed through `JSON.parse()`. + */ + function json(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with the contents of the stream parsed as a UTF-8 encoded string. + */ + function text(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; +} +declare module "node:stream/consumers" { + export * from "stream/consumers"; +} diff --git a/node_modules/@types/node/stream/promises.d.ts b/node_modules/@types/node/stream/promises.d.ts new file mode 100644 index 0000000..d54c14c --- /dev/null +++ b/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,90 @@ +declare module "stream/promises" { + import { + FinishedOptions as _FinishedOptions, + PipelineDestination, + PipelineOptions, + PipelinePromise, + PipelineSource, + PipelineTransform, + } from "node:stream"; + interface FinishedOptions extends _FinishedOptions { + /** + * If true, removes the listeners registered by this function before the promise is fulfilled. + * @default false + */ + cleanup?: boolean | undefined; + } + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; +} +declare module "node:stream/promises" { + export * from "stream/promises"; +} diff --git a/node_modules/@types/node/stream/web.d.ts b/node_modules/@types/node/stream/web.d.ts new file mode 100644 index 0000000..881e29c --- /dev/null +++ b/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,622 @@ +type _ByteLengthQueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ByteLengthQueuingStrategy; +type _CompressionStream = typeof globalThis extends { onmessage: any; ReportingObserver: any } ? {} + : import("stream/web").CompressionStream; +type _CountQueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").CountQueuingStrategy; +type _DecompressionStream = typeof globalThis extends { onmessage: any; ReportingObserver: any } ? {} + : import("stream/web").DecompressionStream; +type _QueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").QueuingStrategy; +type _ReadableByteStreamController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableByteStreamController; +type _ReadableStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStream; +type _ReadableStreamBYOBReader = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamBYOBReader; +type _ReadableStreamBYOBRequest = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamBYOBRequest; +type _ReadableStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamDefaultController; +type _ReadableStreamDefaultReader = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamDefaultReader; +type _TextDecoderStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TextDecoderStream; +type _TextEncoderStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TextEncoderStream; +type _TransformStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TransformStream; +type _TransformStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TransformStreamDefaultController; +type _WritableStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStream; +type _WritableStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStreamDefaultController; +type _WritableStreamDefaultWriter = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStreamDefaultWriter; + +declare module "stream/web" { + // stub module, pending copy&paste from .d.ts or manual impl + // copy from lib.dom.d.ts + interface ReadableWritablePair { + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream + * through a transform stream (or any other { writable, readable } + * pair). It simply pipes the stream into the writable side of the + * supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + */ + writable: WritableStream; + } + interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. + * The way in which the piping process behaves under various error + * conditions can be customized with a number of passed options. It + * returns a promise that fulfills when the piping process completes + * successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate + * as follows: + * + * An error in this source readable stream will abort destination, + * unless preventAbort is truthy. The returned promise will be rejected + * with the source's error, or with any error that occurs during + * aborting the destination. + * + * An error in destination will cancel this source readable stream, + * unless preventCancel is truthy. The returned promise will be rejected + * with the destination's error, or with any error that occurs during + * canceling the source. + * + * When this source readable stream closes, destination will be closed, + * unless preventClose is truthy. The returned promise will be fulfilled + * once this process completes, unless an error is encountered while + * closing the destination, in which case it will be rejected with that + * error. + * + * If destination starts out closed or closing, this source readable + * stream will be canceled, unless preventCancel is true. The returned + * promise will be rejected with an error indicating piping to a closed + * stream failed, or with any error that occurs during canceling the + * source. + * + * The signal option can be set to an AbortSignal to allow aborting an + * ongoing pipe operation via the corresponding AbortController. In this + * case, this source readable stream will be canceled, and destination + * aborted, unless the respective options preventCancel or preventAbort + * are set. + */ + preventClose?: boolean; + signal?: AbortSignal; + } + interface ReadableStreamGenericReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + } + type ReadableStreamController = ReadableStreamDefaultController; + interface ReadableStreamReadValueResult { + done: false; + value: T; + } + interface ReadableStreamReadDoneResult { + done: true; + value?: T; + } + type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; + interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; + } + interface UnderlyingSinkAbortCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSinkCloseCallback { + (): void | PromiseLike; + } + interface UnderlyingSinkStartCallback { + (controller: WritableStreamDefaultController): any; + } + interface UnderlyingSinkWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; + } + interface UnderlyingSourceCancelCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSourcePullCallback { + (controller: ReadableStreamController): void | PromiseLike; + } + interface UnderlyingSourceStartCallback { + (controller: ReadableStreamController): any; + } + interface TransformerFlushCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerStartCallback { + (controller: TransformStreamDefaultController): any; + } + interface TransformerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerCancelCallback { + (reason: any): void | PromiseLike; + } + interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: "bytes"; + } + interface UnderlyingSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback; + start?: UnderlyingSourceStartCallback; + type?: undefined; + } + interface UnderlyingSink { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined; + write?: UnderlyingSinkWriteCallback; + } + interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; + } + interface ReadableStreamAsyncIterator extends NodeJS.AsyncIterator { + [Symbol.asyncIterator](): ReadableStreamAsyncIterator; + } + /** This Streams API interface represents a readable stream of byte data. */ + interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; + getReader(): ReadableStreamDefaultReader; + getReader(options?: ReadableStreamGetReaderOptions): ReadableStreamReader; + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; + values(options?: { preventCancel?: boolean }): ReadableStreamAsyncIterator; + [Symbol.asyncIterator](): ReadableStreamAsyncIterator; + } + const ReadableStream: { + prototype: ReadableStream; + from(iterable: Iterable | AsyncIterable): ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + }; + type ReadableStreamReaderMode = "byob"; + interface ReadableStreamGetReaderOptions { + /** + * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode?: ReadableStreamReaderMode; + } + type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ + interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + options?: { + min?: number; + }, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + } + const ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new(stream: ReadableStream): ReadableStreamDefaultReader; + }; + const ReadableStreamBYOBReader: { + prototype: ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; + }; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ + interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + readonly view: ArrayBufferView | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBufferView): void; + } + const ReadableStreamBYOBRequest: { + prototype: ReadableStreamBYOBRequest; + new(): ReadableStreamBYOBRequest; + }; + interface ReadableByteStreamController { + readonly byobRequest: undefined; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; + } + const ReadableByteStreamController: { + prototype: ReadableByteStreamController; + new(): ReadableByteStreamController; + }; + interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(e?: any): void; + } + const ReadableStreamDefaultController: { + prototype: ReadableStreamDefaultController; + new(): ReadableStreamDefaultController; + }; + interface Transformer { + flush?: TransformerFlushCallback; + readableType?: undefined; + start?: TransformerStartCallback; + transform?: TransformerTransformCallback; + cancel?: TransformerCancelCallback; + writableType?: undefined; + } + interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const TransformStream: { + prototype: TransformStream; + new( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ): TransformStream; + }; + interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk?: O): void; + error(reason?: any): void; + terminate(): void; + } + const TransformStreamDefaultController: { + prototype: TransformStreamDefaultController; + new(): TransformStreamDefaultController; + }; + /** + * This Streams API interface provides a standard abstraction for writing + * streaming data to a destination, known as a sink. This object comes with + * built-in back pressure and queuing. + */ + interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + close(): Promise; + getWriter(): WritableStreamDefaultWriter; + } + const WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; + }; + /** + * This Streams API interface is the object returned by + * WritableStream.getWriter() and once created locks the < writer to the + * WritableStream ensuring that no other streams can write to the underlying + * sink. + */ + interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: W): Promise; + } + const WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(stream: WritableStream): WritableStreamDefaultWriter; + }; + /** + * This Streams API interface represents a controller allowing control of a + * WritableStream's state. When constructing a WritableStream, the + * underlying sink is given a corresponding WritableStreamDefaultController + * instance to manipulate. + */ + interface WritableStreamDefaultController { + error(e?: any): void; + } + const WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; + }; + interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySize; + } + interface QueuingStrategySize { + (chunk?: T): number; + } + interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water + * mark. + * + * Note that the provided high water mark will not be validated ahead of + * time. Instead, if it is negative, NaN, or not a number, the resulting + * ByteLengthQueuingStrategy will cause the corresponding stream + * constructor to throw. + */ + highWaterMark: number; + } + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface ByteLengthQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(init: QueuingStrategyInit): ByteLengthQueuingStrategy; + }; + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface CountQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(init: QueuingStrategyInit): CountQueuingStrategy; + }; + interface TextEncoderStream { + /** Returns "utf-8". */ + readonly encoding: "utf-8"; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextEncoderStream: { + prototype: TextEncoderStream; + new(): TextEncoderStream; + }; + interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + type BufferSource = ArrayBufferView | ArrayBuffer; + interface TextDecoderStream { + /** Returns encoding's name, lower cased. */ + readonly encoding: string; + /** Returns `true` if error mode is "fatal", and `false` otherwise. */ + readonly fatal: boolean; + /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */ + readonly ignoreBOM: boolean; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextDecoderStream: { + prototype: TextDecoderStream; + new(encoding?: string, options?: TextDecoderOptions): TextDecoderStream; + }; + interface CompressionStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const CompressionStream: { + prototype: CompressionStream; + new(format: "deflate" | "deflate-raw" | "gzip"): CompressionStream; + }; + interface DecompressionStream { + readonly writable: WritableStream; + readonly readable: ReadableStream; + } + const DecompressionStream: { + prototype: DecompressionStream; + new(format: "deflate" | "deflate-raw" | "gzip"): DecompressionStream; + }; + + global { + interface ByteLengthQueuingStrategy extends _ByteLengthQueuingStrategy {} + /** + * `ByteLengthQueuingStrategy` class is a global reference for `import { ByteLengthQueuingStrategy } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-bytelengthqueuingstrategy + * @since v18.0.0 + */ + var ByteLengthQueuingStrategy: typeof globalThis extends { onmessage: any; ByteLengthQueuingStrategy: infer T } + ? T + : typeof import("stream/web").ByteLengthQueuingStrategy; + + interface CompressionStream extends _CompressionStream {} + /** + * `CompressionStream` class is a global reference for `import { CompressionStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-compressionstream + * @since v18.0.0 + */ + var CompressionStream: typeof globalThis extends { + onmessage: any; + // CompressionStream, DecompressionStream and ReportingObserver was introduced in the same commit. + // If ReportingObserver check is removed, the type here will form a circular reference in TS5.0+lib.dom.d.ts + ReportingObserver: any; + CompressionStream: infer T; + } ? T + // TS 4.8, 4.9, 5.0 + : typeof globalThis extends { onmessage: any; TransformStream: { prototype: infer T } } ? { + prototype: T; + new(format: "deflate" | "deflate-raw" | "gzip"): T; + } + : typeof import("stream/web").CompressionStream; + + interface CountQueuingStrategy extends _CountQueuingStrategy {} + /** + * `CountQueuingStrategy` class is a global reference for `import { CountQueuingStrategy } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-countqueuingstrategy + * @since v18.0.0 + */ + var CountQueuingStrategy: typeof globalThis extends { onmessage: any; CountQueuingStrategy: infer T } ? T + : typeof import("stream/web").CountQueuingStrategy; + + interface DecompressionStream extends _DecompressionStream {} + /** + * `DecompressionStream` class is a global reference for `import { DecompressionStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-decompressionstream + * @since v18.0.0 + */ + var DecompressionStream: typeof globalThis extends { + onmessage: any; + // CompressionStream, DecompressionStream and ReportingObserver was introduced in the same commit. + // If ReportingObserver check is removed, the type here will form a circular reference in TS5.0+lib.dom.d.ts + ReportingObserver: any; + DecompressionStream: infer T extends object; + } ? T + // TS 4.8, 4.9, 5.0 + : typeof globalThis extends { onmessage: any; TransformStream: { prototype: infer T } } ? { + prototype: T; + new(format: "deflate" | "deflate-raw" | "gzip"): T; + } + : typeof import("stream/web").DecompressionStream; + + interface QueuingStrategy extends _QueuingStrategy {} + + interface ReadableByteStreamController extends _ReadableByteStreamController {} + /** + * `ReadableByteStreamController` class is a global reference for `import { ReadableByteStreamController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablebytestreamcontroller + * @since v18.0.0 + */ + var ReadableByteStreamController: typeof globalThis extends + { onmessage: any; ReadableByteStreamController: infer T } ? T + : typeof import("stream/web").ReadableByteStreamController; + + interface ReadableStream extends _ReadableStream {} + /** + * `ReadableStream` class is a global reference for `import { ReadableStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestream + * @since v18.0.0 + */ + var ReadableStream: typeof globalThis extends { onmessage: any; ReadableStream: infer T } ? T + : typeof import("stream/web").ReadableStream; + + interface ReadableStreamBYOBReader extends _ReadableStreamBYOBReader {} + /** + * `ReadableStreamBYOBReader` class is a global reference for `import { ReadableStreamBYOBReader } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreambyobreader + * @since v18.0.0 + */ + var ReadableStreamBYOBReader: typeof globalThis extends { onmessage: any; ReadableStreamBYOBReader: infer T } + ? T + : typeof import("stream/web").ReadableStreamBYOBReader; + + interface ReadableStreamBYOBRequest extends _ReadableStreamBYOBRequest {} + /** + * `ReadableStreamBYOBRequest` class is a global reference for `import { ReadableStreamBYOBRequest } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreambyobrequest + * @since v18.0.0 + */ + var ReadableStreamBYOBRequest: typeof globalThis extends { onmessage: any; ReadableStreamBYOBRequest: infer T } + ? T + : typeof import("stream/web").ReadableStreamBYOBRequest; + + interface ReadableStreamDefaultController extends _ReadableStreamDefaultController {} + /** + * `ReadableStreamDefaultController` class is a global reference for `import { ReadableStreamDefaultController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreamdefaultcontroller + * @since v18.0.0 + */ + var ReadableStreamDefaultController: typeof globalThis extends + { onmessage: any; ReadableStreamDefaultController: infer T } ? T + : typeof import("stream/web").ReadableStreamDefaultController; + + interface ReadableStreamDefaultReader extends _ReadableStreamDefaultReader {} + /** + * `ReadableStreamDefaultReader` class is a global reference for `import { ReadableStreamDefaultReader } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreamdefaultreader + * @since v18.0.0 + */ + var ReadableStreamDefaultReader: typeof globalThis extends + { onmessage: any; ReadableStreamDefaultReader: infer T } ? T + : typeof import("stream/web").ReadableStreamDefaultReader; + + interface TextDecoderStream extends _TextDecoderStream {} + /** + * `TextDecoderStream` class is a global reference for `import { TextDecoderStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-textdecoderstream + * @since v18.0.0 + */ + var TextDecoderStream: typeof globalThis extends { onmessage: any; TextDecoderStream: infer T } ? T + : typeof import("stream/web").TextDecoderStream; + + interface TextEncoderStream extends _TextEncoderStream {} + /** + * `TextEncoderStream` class is a global reference for `import { TextEncoderStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-textencoderstream + * @since v18.0.0 + */ + var TextEncoderStream: typeof globalThis extends { onmessage: any; TextEncoderStream: infer T } ? T + : typeof import("stream/web").TextEncoderStream; + + interface TransformStream extends _TransformStream {} + /** + * `TransformStream` class is a global reference for `import { TransformStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-transformstream + * @since v18.0.0 + */ + var TransformStream: typeof globalThis extends { onmessage: any; TransformStream: infer T } ? T + : typeof import("stream/web").TransformStream; + + interface TransformStreamDefaultController extends _TransformStreamDefaultController {} + /** + * `TransformStreamDefaultController` class is a global reference for `import { TransformStreamDefaultController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-transformstreamdefaultcontroller + * @since v18.0.0 + */ + var TransformStreamDefaultController: typeof globalThis extends + { onmessage: any; TransformStreamDefaultController: infer T } ? T + : typeof import("stream/web").TransformStreamDefaultController; + + interface WritableStream extends _WritableStream {} + /** + * `WritableStream` class is a global reference for `import { WritableStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-writablestream + * @since v18.0.0 + */ + var WritableStream: typeof globalThis extends { onmessage: any; WritableStream: infer T } ? T + : typeof import("stream/web").WritableStream; + + interface WritableStreamDefaultController extends _WritableStreamDefaultController {} + /** + * `WritableStreamDefaultController` class is a global reference for `import { WritableStreamDefaultController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-writablestreamdefaultcontroller + * @since v18.0.0 + */ + var WritableStreamDefaultController: typeof globalThis extends + { onmessage: any; WritableStreamDefaultController: infer T } ? T + : typeof import("stream/web").WritableStreamDefaultController; + + interface WritableStreamDefaultWriter extends _WritableStreamDefaultWriter {} + /** + * `WritableStreamDefaultWriter` class is a global reference for `import { WritableStreamDefaultWriter } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-writablestreamdefaultwriter + * @since v18.0.0 + */ + var WritableStreamDefaultWriter: typeof globalThis extends + { onmessage: any; WritableStreamDefaultWriter: infer T } ? T + : typeof import("stream/web").WritableStreamDefaultWriter; + } +} +declare module "node:stream/web" { + export * from "stream/web"; +} diff --git a/node_modules/@types/node/string_decoder.d.ts b/node_modules/@types/node/string_decoder.d.ts new file mode 100644 index 0000000..d8b9be8 --- /dev/null +++ b/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `node:string_decoder` module provides an API for decoding `Buffer` objects + * into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 + * characters. It can be accessed using: + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); // Prints: ¢ + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); // Prints: € + * ``` + * + * When a `Buffer` instance is written to the `StringDecoder` instance, an + * internal buffer is used to ensure that the decoded string does not contain + * any incomplete multibyte characters. These are held in the buffer until the + * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. + * + * In the following example, the three UTF-8 encoded bytes of the European Euro + * symbol (`€`) are written over three separate operations: + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); // Prints: € + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/string_decoder.js) + */ +declare module "string_decoder" { + class StringDecoder { + constructor(encoding?: BufferEncoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at + * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the + * returned string and stored in an internal buffer for the next call to `stringDecoder.write()` or `stringDecoder.end()`. + * @since v0.1.99 + * @param buffer The bytes to decode. + */ + write(buffer: string | NodeJS.ArrayBufferView): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes + * representing incomplete UTF-8 and UTF-16 characters will be replaced with + * substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()` is performed before returning the remaining input. + * After `end()` is called, the `stringDecoder` object can be reused for new input. + * @since v0.9.3 + * @param buffer The bytes to decode. + */ + end(buffer?: string | NodeJS.ArrayBufferView): string; + } +} +declare module "node:string_decoder" { + export * from "string_decoder"; +} diff --git a/node_modules/@types/node/test.d.ts b/node_modules/@types/node/test.d.ts new file mode 100644 index 0000000..1c173f6 --- /dev/null +++ b/node_modules/@types/node/test.d.ts @@ -0,0 +1,2162 @@ +/** + * The `node:test` module facilitates the creation of JavaScript tests. + * To access it: + * + * ```js + * import test from 'node:test'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'node:test'; + * ``` + * + * Tests created via the `test` module consist of a single function that is + * processed in one of three ways: + * + * 1. A synchronous function that is considered failing if it throws an exception, + * and is considered passing otherwise. + * 2. A function that returns a `Promise` that is considered failing if the `Promise` rejects, and is considered passing if the `Promise` fulfills. + * 3. A function that receives a callback function. If the callback receives any + * truthy value as its first argument, the test is considered failing. If a + * falsy value is passed as the first argument to the callback, the test is + * considered passing. If the test function receives a callback function and + * also returns a `Promise`, the test will fail. + * + * The following example illustrates how tests are written using the `test` module. + * + * ```js + * test('synchronous passing test', (t) => { + * // This test passes because it does not throw an exception. + * assert.strictEqual(1, 1); + * }); + * + * test('synchronous failing test', (t) => { + * // This test fails because it throws an exception. + * assert.strictEqual(1, 2); + * }); + * + * test('asynchronous passing test', async (t) => { + * // This test passes because the Promise returned by the async + * // function is settled and not rejected. + * assert.strictEqual(1, 1); + * }); + * + * test('asynchronous failing test', async (t) => { + * // This test fails because the Promise returned by the async + * // function is rejected. + * assert.strictEqual(1, 2); + * }); + * + * test('failing test using Promises', (t) => { + * // Promises can be used directly as well. + * return new Promise((resolve, reject) => { + * setImmediate(() => { + * reject(new Error('this will cause the test to fail')); + * }); + * }); + * }); + * + * test('callback passing test', (t, done) => { + * // done() is the callback function. When the setImmediate() runs, it invokes + * // done() with no arguments. + * setImmediate(done); + * }); + * + * test('callback failing test', (t, done) => { + * // When the setImmediate() runs, done() is invoked with an Error object and + * // the test fails. + * setImmediate(() => { + * done(new Error('callback failure')); + * }); + * }); + * ``` + * + * If any tests fail, the process exit code is set to `1`. + * @since v18.0.0, v16.17.0 + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/test.js) + */ +declare module "node:test" { + import { AssertMethodNames } from "node:assert"; + import { Readable } from "node:stream"; + import TestFn = test.TestFn; + import TestOptions = test.TestOptions; + /** + * The `test()` function is the value imported from the `test` module. Each + * invocation of this function results in reporting the test to the `TestsStream`. + * + * The `TestContext` object passed to the `fn` argument can be used to perform + * actions related to the current test. Examples include skipping the test, adding + * additional diagnostic information, or creating subtests. + * + * `test()` returns a `Promise` that fulfills once the test completes. + * if `test()` is called within a suite, it fulfills immediately. + * The return value can usually be discarded for top level tests. + * However, the return value from subtests should be used to prevent the parent + * test from finishing first and cancelling the subtest + * as shown in the following example. + * + * ```js + * test('top level test', async (t) => { + * // The setTimeout() in the following subtest would cause it to outlive its + * // parent test if 'await' is removed on the next line. Once the parent test + * // completes, it will cancel any outstanding subtests. + * await t.test('longer running subtest', async (t) => { + * return new Promise((resolve, reject) => { + * setTimeout(resolve, 1000); + * }); + * }); + * }); + * ``` + * + * The `timeout` option can be used to fail the test if it takes longer than `timeout` milliseconds to complete. However, it is not a reliable mechanism for + * canceling tests because a running test might block the application thread and + * thus prevent the scheduled cancellation. + * @since v18.0.0, v16.17.0 + * @param name The name of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @return Fulfilled with `undefined` once the test completes, or immediately if the test runs within a suite. + */ + function test(name?: string, fn?: TestFn): Promise; + function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function test(options?: TestOptions, fn?: TestFn): Promise; + function test(fn?: TestFn): Promise; + namespace test { + export { test }; + export { suite as describe, test as it }; + } + namespace test { + /** + * **Note:** `shard` is used to horizontally parallelize test running across + * machines or processes, ideal for large-scale executions across varied + * environments. It's incompatible with `watch` mode, tailored for rapid + * code iteration by automatically rerunning tests on file changes. + * + * ```js + * import { tap } from 'node:test/reporters'; + * import { run } from 'node:test'; + * import process from 'node:process'; + * import path from 'node:path'; + * + * run({ files: [path.resolve('./tests/test.js')] }) + * .compose(tap) + * .pipe(process.stdout); + * ``` + * @since v18.9.0, v16.19.0 + * @param options Configuration options for running tests. + */ + function run(options?: RunOptions): TestsStream; + /** + * The `suite()` function is imported from the `node:test` module. + * @param name The name of the suite, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the suite. This supports the same options as {@link test}. + * @param fn The suite function declaring nested tests and suites. The first argument to this function is a {@link SuiteContext} object. + * @return Immediately fulfilled with `undefined`. + * @since v20.13.0 + */ + function suite(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function suite(name?: string, fn?: SuiteFn): Promise; + function suite(options?: TestOptions, fn?: SuiteFn): Promise; + function suite(fn?: SuiteFn): Promise; + namespace suite { + /** + * Shorthand for skipping a suite. This is the same as calling {@link suite} with `options.skip` set to `true`. + * @since v20.13.0 + */ + function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function skip(name?: string, fn?: SuiteFn): Promise; + function skip(options?: TestOptions, fn?: SuiteFn): Promise; + function skip(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `TODO`. This is the same as calling {@link suite} with `options.todo` set to `true`. + * @since v20.13.0 + */ + function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function todo(name?: string, fn?: SuiteFn): Promise; + function todo(options?: TestOptions, fn?: SuiteFn): Promise; + function todo(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `only`. This is the same as calling {@link suite} with `options.only` set to `true`. + * @since v20.13.0 + */ + function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function only(name?: string, fn?: SuiteFn): Promise; + function only(options?: TestOptions, fn?: SuiteFn): Promise; + function only(fn?: SuiteFn): Promise; + } + /** + * Shorthand for skipping a test. This is the same as calling {@link test} with `options.skip` set to `true`. + * @since v20.2.0 + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function skip(name?: string, fn?: TestFn): Promise; + function skip(options?: TestOptions, fn?: TestFn): Promise; + function skip(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `TODO`. This is the same as calling {@link test} with `options.todo` set to `true`. + * @since v20.2.0 + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function todo(name?: string, fn?: TestFn): Promise; + function todo(options?: TestOptions, fn?: TestFn): Promise; + function todo(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `only`. This is the same as calling {@link test} with `options.only` set to `true`. + * @since v20.2.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function only(name?: string, fn?: TestFn): Promise; + function only(options?: TestOptions, fn?: TestFn): Promise; + function only(fn?: TestFn): Promise; + /** + * The type of a function passed to {@link test}. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + */ + type TestFn = (t: TestContext, done: (result?: any) => void) => void | Promise; + /** + * The type of a suite test function. The argument to this function is a {@link SuiteContext} object. + */ + type SuiteFn = (s: SuiteContext) => void | Promise; + interface TestShard { + /** + * A positive integer between 1 and `total` that specifies the index of the shard to run. + */ + index: number; + /** + * A positive integer that specifies the total number of shards to split the test files to. + */ + total: number; + } + interface RunOptions { + /** + * If a number is provided, then that many test processes would run in parallel, where each process corresponds to one test file. + * If `true`, it would run `os.availableParallelism() - 1` test files in parallel. If `false`, it would only run one test file at a time. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * An array containing the list of files to run. If omitted, files are run according to the + * [test runner execution model](https://nodejs.org/docs/latest-v22.x/api/test.html#test-runner-execution-model). + */ + files?: readonly string[] | undefined; + /** + * Configures the test runner to exit the process once all known + * tests have finished executing even if the event loop would + * otherwise remain active. + * @default false + */ + forceExit?: boolean | undefined; + /** + * An array containing the list of glob patterns to match test files. + * This option cannot be used together with `files`. If omitted, files are run according to the + * [test runner execution model](https://nodejs.org/docs/latest-v22.x/api/test.html#test-runner-execution-model). + * @since v22.6.0 + */ + globPatterns?: readonly string[] | undefined; + /** + * Sets inspector port of test child process. + * This can be a number, or a function that takes no arguments and returns a + * number. If a nullish value is provided, each process gets its own port, + * incremented from the primary's `process.debugPort`. This option is ignored + * if the `isolation` option is set to `'none'` as no child processes are + * spawned. + * @default undefined + */ + inspectPort?: number | (() => number) | undefined; + /** + * Configures the type of test isolation. If set to + * `'process'`, each test file is run in a separate child process. If set to + * `'none'`, all test files run in the current process. + * @default 'process' + * @since v22.8.0 + */ + isolation?: "process" | "none" | undefined; + /** + * If truthy, the test context will only run tests that have the `only` option set + */ + only?: boolean | undefined; + /** + * A function that accepts the `TestsStream` instance and can be used to setup listeners before any tests are run. + * @default undefined + */ + setup?: ((reporter: TestsStream) => void | Promise) | undefined; + /** + * An array of CLI flags to pass to the `node` executable when + * spawning the subprocesses. This option has no effect when `isolation` is `'none`'. + * @since v22.10.0 + * @default [] + */ + execArgv?: readonly string[] | undefined; + /** + * An array of CLI flags to pass to each test file when spawning the + * subprocesses. This option has no effect when `isolation` is `'none'`. + * @since v22.10.0 + * @default [] + */ + argv?: readonly string[] | undefined; + /** + * Allows aborting an in-progress test execution. + */ + signal?: AbortSignal | undefined; + /** + * If provided, only run tests whose name matches the provided pattern. + * Strings are interpreted as JavaScript regular expressions. + * @default undefined + */ + testNamePatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * A String, RegExp or a RegExp Array, that can be used to exclude running tests whose + * name matches the provided pattern. Test name patterns are interpreted as JavaScript + * regular expressions. For each test that is executed, any corresponding test hooks, + * such as `beforeEach()`, are also run. + * @default undefined + * @since v22.1.0 + */ + testSkipPatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * The number of milliseconds after which the test execution will fail. + * If unspecified, subtests inherit this value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + /** + * Whether to run in watch mode or not. + * @default false + */ + watch?: boolean | undefined; + /** + * Running tests in a specific shard. + * @default undefined + */ + shard?: TestShard | undefined; + /** + * enable [code coverage](https://nodejs.org/docs/latest-v22.x/api/test.html#collecting-code-coverage) collection. + * @since v22.10.0 + * @default false + */ + coverage?: boolean | undefined; + /** + * Excludes specific files from code coverage + * using a glob pattern, which can match both absolute and relative file paths. + * This property is only applicable when `coverage` was set to `true`. + * If both `coverageExcludeGlobs` and `coverageIncludeGlobs` are provided, + * files must meet **both** criteria to be included in the coverage report. + * @since v22.10.0 + * @default undefined + */ + coverageExcludeGlobs?: string | readonly string[] | undefined; + /** + * Includes specific files in code coverage + * using a glob pattern, which can match both absolute and relative file paths. + * This property is only applicable when `coverage` was set to `true`. + * If both `coverageExcludeGlobs` and `coverageIncludeGlobs` are provided, + * files must meet **both** criteria to be included in the coverage report. + * @since v22.10.0 + * @default undefined + */ + coverageIncludeGlobs?: string | readonly string[] | undefined; + /** + * Require a minimum percent of covered lines. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + lineCoverage?: number | undefined; + /** + * Require a minimum percent of covered branches. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + branchCoverage?: number | undefined; + /** + * Require a minimum percent of covered functions. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + functionCoverage?: number | undefined; + } + /** + * A successful call to `run()` will return a new `TestsStream` object, streaming a series of events representing the execution of the tests. + * + * Some of the events are guaranteed to be emitted in the same order as the tests are defined, while others are emitted in the order that the tests execute. + * @since v18.9.0, v16.19.0 + */ + interface TestsStream extends Readable { + addListener(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + addListener(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + addListener(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + addListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + addListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + addListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + addListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + addListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + addListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; + addListener(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + addListener(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + addListener(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + addListener(event: "test:watch:drained", listener: () => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + emit(event: "test:coverage", data: EventData.TestCoverage): boolean; + emit(event: "test:complete", data: EventData.TestComplete): boolean; + emit(event: "test:dequeue", data: EventData.TestDequeue): boolean; + emit(event: "test:diagnostic", data: EventData.TestDiagnostic): boolean; + emit(event: "test:enqueue", data: EventData.TestEnqueue): boolean; + emit(event: "test:fail", data: EventData.TestFail): boolean; + emit(event: "test:pass", data: EventData.TestPass): boolean; + emit(event: "test:plan", data: EventData.TestPlan): boolean; + emit(event: "test:start", data: EventData.TestStart): boolean; + emit(event: "test:stderr", data: EventData.TestStderr): boolean; + emit(event: "test:stdout", data: EventData.TestStdout): boolean; + emit(event: "test:summary", data: EventData.TestSummary): boolean; + emit(event: "test:watch:drained"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + on(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + on(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + on(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + on(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + on(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + on(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + on(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + on(event: "test:start", listener: (data: EventData.TestStart) => void): this; + on(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + on(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + on(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + on(event: "test:watch:drained", listener: () => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + once(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + once(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + once(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + once(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + once(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + once(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + once(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + once(event: "test:start", listener: (data: EventData.TestStart) => void): this; + once(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + once(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + once(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + once(event: "test:watch:drained", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + prependListener(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + prependListener(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + prependListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + prependListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + prependListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + prependListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + prependListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + prependListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; + prependListener(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + prependListener(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + prependListener(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + prependListener(event: "test:watch:drained", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + prependOnceListener(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + prependOnceListener(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + prependOnceListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + prependOnceListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + prependOnceListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + prependOnceListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + prependOnceListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + prependOnceListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; + prependOnceListener(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + prependOnceListener(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + prependOnceListener(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + prependOnceListener(event: "test:watch:drained", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + } + namespace EventData { + interface Error extends globalThis.Error { + cause: globalThis.Error; + } + interface LocationInfo { + /** + * The column number where the test is defined, or + * `undefined` if the test was run through the REPL. + */ + column?: number; + /** + * The path of the test file, `undefined` if test was run through the REPL. + */ + file?: string; + /** + * The line number where the test is defined, or `undefined` if the test was run through the REPL. + */ + line?: number; + } + interface TestDiagnostic extends LocationInfo { + /** + * The diagnostic message. + */ + message: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The severity level of the diagnostic message. + * Possible values are: + * * `'info'`: Informational messages. + * * `'warn'`: Warnings. + * * `'error'`: Errors. + */ + level: "info" | "warn" | "error"; + } + interface TestCoverage { + /** + * An object containing the coverage report. + */ + summary: { + /** + * An array of coverage reports for individual files. + */ + files: Array<{ + /** + * The absolute path of the file. + */ + path: string; + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + /** + * An array of functions representing function coverage. + */ + functions: Array<{ + /** + * The name of the function. + */ + name: string; + /** + * The line number where the function is defined. + */ + line: number; + /** + * The number of times the function was called. + */ + count: number; + }>; + /** + * An array of branches representing branch coverage. + */ + branches: Array<{ + /** + * The line number where the branch is defined. + */ + line: number; + /** + * The number of times the branch was taken. + */ + count: number; + }>; + /** + * An array of lines representing line numbers and the number of times they were covered. + */ + lines: Array<{ + /** + * The line number. + */ + line: number; + /** + * The number of times the line was covered. + */ + count: number; + }>; + }>; + /** + * An object containing whether or not the coverage for + * each coverage type. + * @since v22.9.0 + */ + thresholds: { + /** + * The function coverage threshold. + */ + function: number; + /** + * The branch coverage threshold. + */ + branch: number; + /** + * The line coverage threshold. + */ + line: number; + }; + /** + * An object containing a summary of coverage for all files. + */ + totals: { + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + }; + /** + * The working directory when code coverage began. This + * is useful for displaying relative path names in case + * the tests changed the working directory of the Node.js process. + */ + workingDirectory: string; + }; + /** + * The nesting level of the test. + */ + nesting: number; + } + interface TestComplete extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * Whether the test passed or not. + */ + passed: boolean; + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test if it did not pass. + */ + error?: Error; + /** + * The type of the test, used to denote whether this is a suite. + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestDequeue extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The test type. Either `'suite'` or `'test'`. + * @since v22.15.0 + */ + type: "suite" | "test"; + } + interface TestEnqueue extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The test type. Either `'suite'` or `'test'`. + * @since v22.15.0 + */ + type: "suite" | "test"; + } + interface TestFail extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test. + */ + error: Error; + /** + * The type of the test, used to denote whether this is a suite. + * @since v20.0.0, v19.9.0, v18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestPass extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * The type of the test, used to denote whether this is a suite. + * @since 20.0.0, 19.9.0, 18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestPlan extends LocationInfo { + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The number of subtests that have ran. + */ + count: number; + } + interface TestStart extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + } + interface TestStderr { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stderr`. + */ + message: string; + } + interface TestStdout { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stdout`. + */ + message: string; + } + interface TestSummary { + /** + * An object containing the counts of various test results. + */ + counts: { + /** + * The total number of cancelled tests. + */ + cancelled: number; + /** + * The total number of passed tests. + */ + passed: number; + /** + * The total number of skipped tests. + */ + skipped: number; + /** + * The total number of suites run. + */ + suites: number; + /** + * The total number of tests run, excluding suites. + */ + tests: number; + /** + * The total number of TODO tests. + */ + todo: number; + /** + * The total number of top level tests and suites. + */ + topLevel: number; + }; + /** + * The duration of the test run in milliseconds. + */ + duration_ms: number; + /** + * The path of the test file that generated the + * summary. If the summary corresponds to multiple files, this value is + * `undefined`. + */ + file: string | undefined; + /** + * Indicates whether or not the test run is considered + * successful or not. If any error condition occurs, such as a failing test or + * unmet coverage threshold, this value will be set to `false`. + */ + success: boolean; + } + } + /** + * An instance of `TestContext` is passed to each test function in order to + * interact with the test runner. However, the `TestContext` constructor is not + * exposed as part of the API. + * @since v18.0.0, v16.17.0 + */ + interface TestContext { + /** + * An object containing assertion methods bound to the test context. + * The top-level functions from the `node:assert` module are exposed here for the purpose of creating test plans. + * + * **Note:** Some of the functions from `node:assert` contain type assertions. If these are called via the + * TestContext `assert` object, then the context parameter in the test's function signature **must be explicitly typed** + * (ie. the parameter must have a type annotation), otherwise an error will be raised by the TypeScript compiler: + * ```ts + * import { test, type TestContext } from 'node:test'; + * + * // The test function's context parameter must have a type annotation. + * test('example', (t: TestContext) => { + * t.assert.deepStrictEqual(actual, expected); + * }); + * + * // Omitting the type annotation will result in a compilation error. + * test('example', t => { + * t.assert.deepStrictEqual(actual, expected); // Error: 't' needs an explicit type annotation. + * }); + * ``` + * @since v22.2.0, v20.15.0 + */ + readonly assert: TestContextAssert; + /** + * This function is used to create a hook running before subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v20.1.0, v18.17.0 + */ + before(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running before each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + beforeEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook that runs after the current test finishes. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.13.0 + */ + after(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + afterEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to write diagnostics to the output. Any diagnostic + * information is included at the end of the test's results. This function does + * not return a value. + * + * ```js + * test('top level test', (t) => { + * t.diagnostic('A diagnostic message'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Message to be reported. + */ + diagnostic(message: string): void; + /** + * The absolute path of the test file that created the current test. If a test file imports + * additional modules that generate tests, the imported tests will return the path of the root test file. + * @since v22.6.0 + */ + readonly filePath: string | undefined; + /** + * The name of the test and each of its ancestors, separated by `>`. + * @since v22.3.0 + */ + readonly fullName: string; + /** + * The name of the test. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * This function is used to set the number of assertions and subtests that are expected to run + * within the test. If the number of assertions and subtests that run does not match the + * expected count, the test will fail. + * + * > Note: To make sure assertions are tracked, `t.assert` must be used instead of `assert` directly. + * + * ```js + * test('top level test', (t) => { + * t.plan(2); + * t.assert.ok('some relevant assertion here'); + * t.test('subtest', () => {}); + * }); + * ``` + * + * When working with asynchronous code, the `plan` function can be used to ensure that the + * correct number of assertions are run: + * + * ```js + * test('planning with streams', (t, done) => { + * function* generate() { + * yield 'a'; + * yield 'b'; + * yield 'c'; + * } + * const expected = ['a', 'b', 'c']; + * t.plan(expected.length); + * const stream = Readable.from(generate()); + * stream.on('data', (chunk) => { + * t.assert.strictEqual(chunk, expected.shift()); + * }); + * + * stream.on('end', () => { + * done(); + * }); + * }); + * ``` + * + * When using the `wait` option, you can control how long the test will wait for the expected assertions. + * For example, setting a maximum wait time ensures that the test will wait for asynchronous assertions + * to complete within the specified timeframe: + * + * ```js + * test('plan with wait: 2000 waits for async assertions', (t) => { + * t.plan(1, { wait: 2000 }); // Waits for up to 2 seconds for the assertion to complete. + * + * const asyncActivity = () => { + * setTimeout(() => { + * * t.assert.ok(true, 'Async assertion completed within the wait time'); + * }, 1000); // Completes after 1 second, within the 2-second wait time. + * }; + * + * asyncActivity(); // The test will pass because the assertion is completed in time. + * }); + * ``` + * + * Note: If a `wait` timeout is specified, it begins counting down only after the test function finishes executing. + * @since v22.2.0 + */ + plan(count: number, options?: TestContextPlanOptions): void; + /** + * If `shouldRunOnlyTests` is truthy, the test context will only run tests that + * have the `only` option set. Otherwise, all tests are run. If Node.js was not + * started with the `--test-only` command-line option, this function is a + * no-op. + * + * ```js + * test('top level test', (t) => { + * // The test context can be set to run subtests with the 'only' option. + * t.runOnly(true); + * return Promise.all([ + * t.test('this subtest is now skipped'), + * t.test('this subtest is run', { only: true }), + * ]); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param shouldRunOnlyTests Whether or not to run `only` tests. + */ + runOnly(shouldRunOnlyTests: boolean): void; + /** + * ```js + * test('top level test', async (t) => { + * await fetch('some/uri', { signal: t.signal }); + * }); + * ``` + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + /** + * This function causes the test's output to indicate the test as skipped. If `message` is provided, it is included in the output. Calling `skip()` does + * not terminate execution of the test function. This function does not return a + * value. + * + * ```js + * test('top level test', (t) => { + * // Make sure to return here as well if the test contains additional logic. + * t.skip('this is skipped'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional skip message. + */ + skip(message?: string): void; + /** + * This function adds a `TODO` directive to the test's output. If `message` is + * provided, it is included in the output. Calling `todo()` does not terminate + * execution of the test function. This function does not return a value. + * + * ```js + * test('top level test', (t) => { + * // This test is marked as `TODO` + * t.todo('this is a todo'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional `TODO` message. + */ + todo(message?: string): void; + /** + * This function is used to create subtests under the current test. This function behaves in + * the same fashion as the top level {@link test} function. + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. This first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + test: typeof test; + /** + * This method polls a `condition` function until that function either returns + * successfully or the operation times out. + * @since v22.14.0 + * @param condition An assertion function that is invoked + * periodically until it completes successfully or the defined polling timeout + * elapses. Successful completion is defined as not throwing or rejecting. This + * function does not accept any arguments, and is allowed to return any value. + * @param options An optional configuration object for the polling operation. + * @returns Fulfilled with the value returned by `condition`. + */ + waitFor(condition: () => T, options?: TestContextWaitForOptions): Promise>; + /** + * Each test provides its own MockTracker instance. + */ + readonly mock: MockTracker; + } + interface TestContextAssert extends Pick { + /** + * This function serializes `value` and writes it to the file specified by `path`. + * + * ```js + * test('snapshot test with default serialization', (t) => { + * t.assert.fileSnapshot({ value1: 1, value2: 2 }, './snapshots/snapshot.json'); + * }); + * ``` + * + * This function differs from `context.assert.snapshot()` in the following ways: + * + * * The snapshot file path is explicitly provided by the user. + * * Each snapshot file is limited to a single snapshot value. + * * No additional escaping is performed by the test runner. + * + * These differences allow snapshot files to better support features such as syntax + * highlighting. + * @since v22.14.0 + * @param value A value to serialize to a string. If Node.js was started with + * the [`--test-update-snapshots`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--test-update-snapshots) + * flag, the serialized value is written to + * `path`. Otherwise, the serialized value is compared to the contents of the + * existing snapshot file. + * @param path The file where the serialized `value` is written. + * @param options Optional configuration options. + */ + fileSnapshot(value: any, path: string, options?: AssertSnapshotOptions): void; + /** + * This function implements assertions for snapshot testing. + * ```js + * test('snapshot test with default serialization', (t) => { + * t.assert.snapshot({ value1: 1, value2: 2 }); + * }); + * + * test('snapshot test with custom serialization', (t) => { + * t.assert.snapshot({ value3: 3, value4: 4 }, { + * serializers: [(value) => JSON.stringify(value)] + * }); + * }); + * ``` + * @since v22.3.0 + * @param value A value to serialize to a string. If Node.js was started with + * the [`--test-update-snapshots`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--test-update-snapshots) + * flag, the serialized value is written to + * the snapshot file. Otherwise, the serialized value is compared to the + * corresponding value in the existing snapshot file. + */ + snapshot(value: any, options?: AssertSnapshotOptions): void; + /** + * A custom assertion function registered with `assert.register()`. + */ + [name: string]: (...args: any[]) => void; + } + interface AssertSnapshotOptions { + /** + * An array of synchronous functions used to serialize `value` into a string. + * `value` is passed as the only argument to the first serializer function. + * The return value of each serializer is passed as input to the next serializer. + * Once all serializers have run, the resulting value is coerced to a string. + * + * If no serializers are provided, the test runner's default serializers are used. + */ + serializers?: ReadonlyArray<(value: any) => any> | undefined; + } + interface TestContextPlanOptions { + /** + * The wait time for the plan: + * * If `true`, the plan waits indefinitely for all assertions and subtests to run. + * * If `false`, the plan performs an immediate check after the test function completes, + * without waiting for any pending assertions or subtests. + * Any assertions or subtests that complete after this check will not be counted towards the plan. + * * If a number, it specifies the maximum wait time in milliseconds + * before timing out while waiting for expected assertions and subtests to be matched. + * If the timeout is reached, the test will fail. + * @default false + */ + wait?: boolean | number | undefined; + } + interface TestContextWaitForOptions { + /** + * The number of milliseconds to wait after an unsuccessful + * invocation of `condition` before trying again. + * @default 50 + */ + interval?: number | undefined; + /** + * The poll timeout in milliseconds. If `condition` has not + * succeeded by the time this elapses, an error occurs. + * @default 1000 + */ + timeout?: number | undefined; + } + /** + * An instance of `SuiteContext` is passed to each suite function in order to + * interact with the test runner. However, the `SuiteContext` constructor is not + * exposed as part of the API. + * @since v18.7.0, v16.17.0 + */ + interface SuiteContext { + /** + * The absolute path of the test file that created the current suite. If a test file imports + * additional modules that generate suites, the imported suites will return the path of the root test file. + * @since v22.6.0 + */ + readonly filePath: string | undefined; + /** + * The name of the suite. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * Can be used to abort test subtasks when the test has been aborted. + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + } + interface TestOptions { + /** + * If a number is provided, then that many tests would run in parallel. + * If truthy, it would run (number of cpu cores - 1) tests in parallel. + * For subtests, it will be `Infinity` tests in parallel. + * If falsy, it would only run one test at a time. + * If unspecified, subtests inherit this value from their parent. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * If truthy, and the test context is configured to run `only` tests, then this test will be + * run. Otherwise, the test is skipped. + * @default false + */ + only?: boolean | undefined; + /** + * Allows aborting an in-progress test. + * @since v18.8.0 + */ + signal?: AbortSignal | undefined; + /** + * If truthy, the test is skipped. If a string is provided, that string is displayed in the + * test results as the reason for skipping the test. + * @default false + */ + skip?: boolean | string | undefined; + /** + * A number of milliseconds the test will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + * @since v18.7.0 + */ + timeout?: number | undefined; + /** + * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in + * the test results as the reason why the test is `TODO`. + * @default false + */ + todo?: boolean | string | undefined; + /** + * The number of assertions and subtests expected to be run in the test. + * If the number of assertions run in the test does not match the number + * specified in the plan, the test will fail. + * @default undefined + * @since v22.2.0 + */ + plan?: number | undefined; + } + /** + * This function creates a hook that runs before executing a suite. + * + * ```js + * describe('tests', async () => { + * before(() => console.log('about to run some test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function before(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after executing a suite. + * + * ```js + * describe('tests', async () => { + * after(() => console.log('finished running tests')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function after(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs before each test in the current suite. + * + * ```js + * describe('tests', async () => { + * beforeEach(() => console.log('about to run a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function beforeEach(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after each test in the current suite. + * The `afterEach()` hook is run even if the test fails. + * + * ```js + * describe('tests', async () => { + * afterEach(() => console.log('finished running a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function afterEach(fn?: HookFn, options?: HookOptions): void; + /** + * The hook function. The first argument is the context in which the hook is called. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type HookFn = (c: TestContext | SuiteContext, done: (result?: any) => void) => any; + /** + * The hook function. The first argument is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type TestContextHookFn = (t: TestContext, done: (result?: any) => void) => any; + /** + * Configuration options for hooks. + * @since v18.8.0 + */ + interface HookOptions { + /** + * Allows aborting an in-progress hook. + */ + signal?: AbortSignal | undefined; + /** + * A number of milliseconds the hook will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + } + interface MockFunctionOptions { + /** + * The number of times that the mock will use the behavior of `implementation`. + * Once the mock function has been called `times` times, + * it will automatically restore the behavior of `original`. + * This value must be an integer greater than zero. + * @default Infinity + */ + times?: number | undefined; + } + interface MockMethodOptions extends MockFunctionOptions { + /** + * If `true`, `object[methodName]` is treated as a getter. + * This option cannot be used with the `setter` option. + */ + getter?: boolean | undefined; + /** + * If `true`, `object[methodName]` is treated as a setter. + * This option cannot be used with the `getter` option. + */ + setter?: boolean | undefined; + } + type Mock = F & { + mock: MockFunctionContext; + }; + interface MockModuleOptions { + /** + * If false, each call to `require()` or `import()` generates a new mock module. + * If true, subsequent calls will return the same module mock, and the mock module is inserted into the CommonJS cache. + * @default false + */ + cache?: boolean | undefined; + /** + * The value to use as the mocked module's default export. + * + * If this value is not provided, ESM mocks do not include a default export. + * If the mock is a CommonJS or builtin module, this setting is used as the value of `module.exports`. + * If this value is not provided, CJS and builtin mocks use an empty object as the value of `module.exports`. + */ + defaultExport?: any; + /** + * An object whose keys and values are used to create the named exports of the mock module. + * + * If the mock is a CommonJS or builtin module, these values are copied onto `module.exports`. + * Therefore, if a mock is created with both named exports and a non-object default export, + * the mock will throw an exception when used as a CJS or builtin module. + */ + namedExports?: object | undefined; + } + /** + * The `MockTracker` class is used to manage mocking functionality. The test runner + * module provides a top level `mock` export which is a `MockTracker` instance. + * Each test also provides its own `MockTracker` instance via the test context's `mock` property. + * @since v19.1.0, v18.13.0 + */ + interface MockTracker { + /** + * This function is used to create a mock function. + * + * The following example creates a mock function that increments a counter by one + * on each invocation. The `times` option is used to modify the mock behavior such + * that the first two invocations add two to the counter instead of one. + * + * ```js + * test('mocks a counting function', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne, addTwo, { times: 2 }); + * + * assert.strictEqual(fn(), 2); + * assert.strictEqual(fn(), 4); + * assert.strictEqual(fn(), 5); + * assert.strictEqual(fn(), 6); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param original An optional function to create a mock on. + * @param implementation An optional function used as the mock implementation for `original`. This is useful for creating mocks that exhibit one behavior for a specified number of calls and + * then restore the behavior of `original`. + * @param options Optional configuration options for the mock function. + * @return The mocked function. The mocked function contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked function. + */ + fn undefined>( + original?: F, + options?: MockFunctionOptions, + ): Mock; + fn undefined, Implementation extends Function = F>( + original?: F, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock; + /** + * This function is used to create a mock on an existing object method. The + * following example demonstrates how a mock is created on an existing object + * method. + * + * ```js + * test('spies on an object method', (t) => { + * const number = { + * value: 5, + * subtract(a) { + * return this.value - a; + * }, + * }; + * + * t.mock.method(number, 'subtract'); + * assert.strictEqual(number.subtract.mock.calls.length, 0); + * assert.strictEqual(number.subtract(3), 2); + * assert.strictEqual(number.subtract.mock.calls.length, 1); + * + * const call = number.subtract.mock.calls[0]; + * + * assert.deepStrictEqual(call.arguments, [3]); + * assert.strictEqual(call.result, 2); + * assert.strictEqual(call.error, undefined); + * assert.strictEqual(call.target, undefined); + * assert.strictEqual(call.this, number); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param object The object whose method is being mocked. + * @param methodName The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown. + * @param implementation An optional function used as the mock implementation for `object[methodName]`. + * @param options Optional configuration options for the mock method. + * @return The mocked method. The mocked method contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked method. + */ + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation: Implementation, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method( + object: MockedObject, + methodName: keyof MockedObject, + options: MockMethodOptions, + ): Mock; + method( + object: MockedObject, + methodName: keyof MockedObject, + implementation: Function, + options: MockMethodOptions, + ): Mock; + /** + * This function is syntax sugar for `MockTracker.method` with `options.getter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<() => MockedObject[MethodName]>; + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<(() => MockedObject[MethodName]) | Implementation>; + /** + * This function is syntax sugar for `MockTracker.method` with `options.setter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<(value: MockedObject[MethodName]) => void>; + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<((value: MockedObject[MethodName]) => void) | Implementation>; + /** + * This function is used to mock the exports of ECMAScript modules, CommonJS modules, and Node.js builtin modules. + * Any references to the original module prior to mocking are not impacted. + * + * Only available through the [--experimental-test-module-mocks](https://nodejs.org/api/cli.html#--experimental-test-module-mocks) flag. + * @since v22.3.0 + * @experimental + * @param specifier A string identifying the module to mock. + * @param options Optional configuration options for the mock module. + */ + module(specifier: string, options?: MockModuleOptions): MockModuleContext; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker` and disassociates the mocks from the `MockTracker` instance. Once disassociated, the mocks can still be used, but the `MockTracker` instance can no longer be + * used to reset their behavior or + * otherwise interact with them. + * + * After each test completes, this function is called on the test context's `MockTracker`. If the global `MockTracker` is used extensively, calling this + * function manually is recommended. + * @since v19.1.0, v18.13.0 + */ + reset(): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does + * not disassociate the mocks from the `MockTracker` instance. + * @since v19.1.0, v18.13.0 + */ + restoreAll(): void; + readonly timers: MockTimers; + } + const mock: MockTracker; + interface MockFunctionCall< + F extends Function, + ReturnType = F extends (...args: any) => infer T ? T + : F extends abstract new(...args: any) => infer T ? T + : unknown, + Args = F extends (...args: infer Y) => any ? Y + : F extends abstract new(...args: infer Y) => any ? Y + : unknown[], + > { + /** + * An array of the arguments passed to the mock function. + */ + arguments: Args; + /** + * If the mocked function threw then this property contains the thrown value. + */ + error: unknown | undefined; + /** + * The value returned by the mocked function. + * + * If the mocked function threw, it will be `undefined`. + */ + result: ReturnType | undefined; + /** + * An `Error` object whose stack can be used to determine the callsite of the mocked function invocation. + */ + stack: Error; + /** + * If the mocked function is a constructor, this field contains the class being constructed. + * Otherwise this will be `undefined`. + */ + target: F extends abstract new(...args: any) => any ? F : undefined; + /** + * The mocked function's `this` value. + */ + this: unknown; + } + /** + * The `MockFunctionContext` class is used to inspect or manipulate the behavior of + * mocks created via the `MockTracker` APIs. + * @since v19.1.0, v18.13.0 + */ + interface MockFunctionContext { + /** + * A getter that returns a copy of the internal array used to track calls to the + * mock. Each entry in the array is an object with the following properties. + * @since v19.1.0, v18.13.0 + */ + readonly calls: MockFunctionCall[]; + /** + * This function returns the number of times that this mock has been invoked. This + * function is more efficient than checking `ctx.calls.length` because `ctx.calls` is a getter that creates a copy of the internal call tracking array. + * @since v19.1.0, v18.13.0 + * @return The number of times that this mock has been invoked. + */ + callCount(): number; + /** + * This function is used to change the behavior of an existing mock. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, and then changes the mock implementation to a different function. + * + * ```js + * test('changes a mock behavior', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementation(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 5); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's new implementation. + */ + mockImplementation(implementation: F): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onCall` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, changes the mock implementation to a different function for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementationOnce(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 4); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's implementation for the invocation number specified by `onCall`. + * @param onCall The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown. + */ + mockImplementationOnce(implementation: F, onCall?: number): void; + /** + * Resets the call history of the mock function. + * @since v19.3.0, v18.13.0 + */ + resetCalls(): void; + /** + * Resets the implementation of the mock function to its original behavior. The + * mock can still be used after calling this function. + * @since v19.1.0, v18.13.0 + */ + restore(): void; + } + /** + * @since v22.3.0 + * @experimental + */ + interface MockModuleContext { + /** + * Resets the implementation of the mock module. + * @since v22.3.0 + */ + restore(): void; + } + interface MockTimersOptions { + apis: ReadonlyArray<"setInterval" | "setTimeout" | "setImmediate" | "Date">; + now?: number | Date | undefined; + } + /** + * Mocking timers is a technique commonly used in software testing to simulate and + * control the behavior of timers, such as `setInterval` and `setTimeout`, + * without actually waiting for the specified time intervals. + * + * The MockTimers API also allows for mocking of the `Date` constructor and + * `setImmediate`/`clearImmediate` functions. + * + * The `MockTracker` provides a top-level `timers` export + * which is a `MockTimers` instance. + * @since v20.4.0 + * @experimental + */ + interface MockTimers { + /** + * Enables timer mocking for the specified timers. + * + * **Note:** When you enable mocking for a specific timer, its associated + * clear function will also be implicitly mocked. + * + * **Note:** Mocking `Date` will affect the behavior of the mocked timers + * as they use the same internal clock. + * + * Example usage without setting initial time: + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1234 }); + * ``` + * + * The above example enables mocking for the `Date` constructor, `setInterval` timer and + * implicitly mocks the `clearInterval` function. Only the `Date` constructor from `globalThis`, + * `setInterval` and `clearInterval` functions from `node:timers`, `node:timers/promises`, and `globalThis` will be mocked. + * + * Example usage with initial time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: 1000 }); + * ``` + * + * Example usage with initial Date object as time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: new Date() }); + * ``` + * + * Alternatively, if you call `mock.timers.enable()` without any parameters: + * + * All timers (`'setInterval'`, `'clearInterval'`, `'Date'`, `'setImmediate'`, `'clearImmediate'`, `'setTimeout'`, and `'clearTimeout'`) + * will be mocked. + * + * The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout` functions from `node:timers`, `node:timers/promises`, + * and `globalThis` will be mocked. + * The `Date` constructor from `globalThis` will be mocked. + * + * If there is no initial epoch set, the initial date will be based on 0 in the Unix epoch. This is `January 1st, 1970, 00:00:00 UTC`. You can + * set an initial date by passing a now property to the `.enable()` method. This value will be used as the initial date for the mocked Date + * object. It can either be a positive integer, or another Date object. + * @since v20.4.0 + */ + enable(options?: MockTimersOptions): void; + /** + * You can use the `.setTime()` method to manually move the mocked date to another time. This method only accepts a positive integer. + * Note: This method will execute any mocked timers that are in the past from the new time. + * In the below example we are setting a new time for the mocked date. + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * test('sets the time of a date object', (context) => { + * // Optionally choose what to mock + * context.mock.timers.enable({ apis: ['Date'], now: 100 }); + * assert.strictEqual(Date.now(), 100); + * // Advance in time will also advance the date + * context.mock.timers.setTime(1000); + * context.mock.timers.tick(200); + * assert.strictEqual(Date.now(), 1200); + * }); + * ``` + */ + setTime(time: number): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTimers` instance and disassociates the mocks + * from the `MockTracker` instance. + * + * **Note:** After each test completes, this function is called on + * the test context's `MockTracker`. + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.reset(); + * ``` + * @since v20.4.0 + */ + reset(): void; + /** + * Advances time for all mocked timers. + * + * **Note:** This diverges from how `setTimeout` in Node.js behaves and accepts + * only positive numbers. In Node.js, `setTimeout` with negative numbers is + * only supported for web compatibility reasons. + * + * The following example mocks a `setTimeout` function and + * by using `.tick` advances in + * time triggering all pending timers. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Alternativelly, the `.tick` function can be called many times + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * const nineSecs = 9000; + * setTimeout(fn, nineSecs); + * + * const twoSeconds = 3000; + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Advancing time using `.tick` will also advance the time for any `Date` object + * created after the mock was enabled (if `Date` was also set to be mocked). + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * assert.strictEqual(Date.now(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * assert.strictEqual(fn.mock.callCount(), 1); + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * @since v20.4.0 + */ + tick(milliseconds: number): void; + /** + * Triggers all pending mocked timers immediately. If the `Date` object is also + * mocked, it will also advance the `Date` object to the furthest timer's time. + * + * The example below triggers all pending timers immediately, + * causing them to execute without any delay. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('runAll functions following the given order', (context) => { + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * const results = []; + * setTimeout(() => results.push(1), 9999); + * + * // Notice that if both timers have the same timeout, + * // the order of execution is guaranteed + * setTimeout(() => results.push(3), 8888); + * setTimeout(() => results.push(2), 8888); + * + * assert.deepStrictEqual(results, []); + * + * context.mock.timers.runAll(); + * assert.deepStrictEqual(results, [3, 2, 1]); + * // The Date object is also advanced to the furthest timer's time + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * + * **Note:** The `runAll()` function is specifically designed for + * triggering timers in the context of timer mocking. + * It does not have any effect on real-time system + * clocks or actual timers outside of the mocking environment. + * @since v20.4.0 + */ + runAll(): void; + /** + * Calls {@link MockTimers.reset()}. + */ + [Symbol.dispose](): void; + } + /** + * An object whose methods are used to configure available assertions on the + * `TestContext` objects in the current process. The methods from `node:assert` + * and snapshot testing functions are available by default. + * + * It is possible to apply the same configuration to all files by placing common + * configuration code in a module + * preloaded with `--require` or `--import`. + * @since v22.14.0 + */ + namespace assert { + /** + * Defines a new assertion function with the provided name and function. If an + * assertion already exists with the same name, it is overwritten. + * @since v22.14.0 + */ + function register(name: string, fn: (this: TestContext, ...args: any[]) => void): void; + } + /** + * @since v22.3.0 + */ + namespace snapshot { + /** + * This function is used to customize the default serialization mechanism used by the test runner. + * + * By default, the test runner performs serialization by calling `JSON.stringify(value, null, 2)` on the provided value. + * `JSON.stringify()` does have limitations regarding circular structures and supported data types. + * If a more robust serialization mechanism is required, this function should be used to specify a list of custom serializers. + * + * Serializers are called in order, with the output of the previous serializer passed as input to the next. + * The final result must be a string value. + * @since v22.3.0 + * @param serializers An array of synchronous functions used as the default serializers for snapshot tests. + */ + function setDefaultSnapshotSerializers(serializers: ReadonlyArray<(value: any) => any>): void; + /** + * This function is used to set a custom resolver for the location of the snapshot file used for snapshot testing. + * By default, the snapshot filename is the same as the entry point filename with `.snapshot` appended. + * @since v22.3.0 + * @param fn A function used to compute the location of the snapshot file. + * The function receives the path of the test file as its only argument. If the + * test is not associated with a file (for example in the REPL), the input is + * undefined. `fn()` must return a string specifying the location of the snapshot file. + */ + function setResolveSnapshotPath(fn: (path: string | undefined) => string): void; + } + } + type FunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? K : never; + }[keyof T]; + export = test; +} + +/** + * The `node:test/reporters` module exposes the builtin-reporters for `node:test`. + * To access it: + * + * ```js + * import test from 'node:test/reporters'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'node:test/reporters'; + * ``` + * @since v19.9.0 + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/test/reporters.js) + */ +declare module "node:test/reporters" { + import { Transform, TransformOptions } from "node:stream"; + import { EventData } from "node:test"; + + type TestEvent = + | { type: "test:coverage"; data: EventData.TestCoverage } + | { type: "test:complete"; data: EventData.TestComplete } + | { type: "test:dequeue"; data: EventData.TestDequeue } + | { type: "test:diagnostic"; data: EventData.TestDiagnostic } + | { type: "test:enqueue"; data: EventData.TestEnqueue } + | { type: "test:fail"; data: EventData.TestFail } + | { type: "test:pass"; data: EventData.TestPass } + | { type: "test:plan"; data: EventData.TestPlan } + | { type: "test:start"; data: EventData.TestStart } + | { type: "test:stderr"; data: EventData.TestStderr } + | { type: "test:stdout"; data: EventData.TestStdout } + | { type: "test:summary"; data: EventData.TestSummary } + | { type: "test:watch:drained"; data: undefined }; + type TestEventGenerator = AsyncGenerator; + + interface ReporterConstructorWrapper Transform> { + new(...args: ConstructorParameters): InstanceType; + (...args: ConstructorParameters): InstanceType; + } + + /** + * The `dot` reporter outputs the test results in a compact format, + * where each passing test is represented by a `.`, + * and each failing test is represented by a `X`. + * @since v20.0.0 + */ + function dot(source: TestEventGenerator): AsyncGenerator<"\n" | "." | "X", void>; + /** + * The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format. + * @since v20.0.0 + */ + function tap(source: TestEventGenerator): AsyncGenerator; + class SpecReporter extends Transform { + constructor(); + } + /** + * The `spec` reporter outputs the test results in a human-readable format. + * @since v20.0.0 + */ + const spec: ReporterConstructorWrapper; + /** + * The `junit` reporter outputs test results in a jUnit XML format. + * @since v21.0.0 + */ + function junit(source: TestEventGenerator): AsyncGenerator; + class LcovReporter extends Transform { + constructor(opts?: Omit); + } + /** + * The `lcov` reporter outputs test coverage when used with the + * [`--experimental-test-coverage`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--experimental-test-coverage) flag. + * @since v22.0.0 + */ + const lcov: LcovReporter; + + export { dot, junit, lcov, spec, tap, TestEvent }; +} diff --git a/node_modules/@types/node/timers.d.ts b/node_modules/@types/node/timers.d.ts new file mode 100644 index 0000000..44bc977 --- /dev/null +++ b/node_modules/@types/node/timers.d.ts @@ -0,0 +1,287 @@ +/** + * The `timer` module exposes a global API for scheduling functions to + * be called at some future period of time. Because the timer functions are + * globals, there is no need to import `node:timers` to use the API. + * + * The timer functions within Node.js implement a similar API as the timers API + * provided by Web Browsers but use a different internal implementation that is + * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/timers.js) + */ +declare module "timers" { + import { Abortable } from "node:events"; + import * as promises from "node:timers/promises"; + export interface TimerOptions extends Abortable { + /** + * Set to `false` to indicate that the scheduled `Timeout` + * should not require the Node.js event loop to remain active. + * @default true + */ + ref?: boolean | undefined; + } + global { + namespace NodeJS { + /** + * This object is created internally and is returned from `setImmediate()`. It + * can be passed to `clearImmediate()` in order to cancel the scheduled + * actions. + * + * By default, when an immediate is scheduled, the Node.js event loop will continue + * running as long as the immediate is active. The `Immediate` object returned by + * `setImmediate()` exports both `immediate.ref()` and `immediate.unref()` + * functions that can be used to control this default behavior. + */ + interface Immediate extends RefCounted, Disposable { + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the + * `Immediate` is active. Calling `immediate.ref()` multiple times will have no + * effect. + * + * By default, all `Immediate` objects are "ref'ed", making it normally unnecessary + * to call `immediate.ref()` unless `immediate.unref()` had been called previously. + * @since v9.7.0 + * @returns a reference to `immediate` + */ + ref(): this; + /** + * When called, the active `Immediate` object will not require the Node.js event + * loop to remain active. If there is no other activity keeping the event loop + * running, the process may exit before the `Immediate` object's callback is + * invoked. Calling `immediate.unref()` multiple times will have no effect. + * @since v9.7.0 + * @returns a reference to `immediate` + */ + unref(): this; + /** + * Cancels the immediate. This is similar to calling `clearImmediate()`. + * @since v20.5.0, v18.18.0 + * @experimental + */ + [Symbol.dispose](): void; + _onImmediate(...args: any[]): void; + } + // Legacy interface used in Node.js v9 and prior + // TODO: remove in a future major version bump + /** @deprecated Use `NodeJS.Timeout` instead. */ + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + /** + * This object is created internally and is returned from `setTimeout()` and + * `setInterval()`. It can be passed to either `clearTimeout()` or + * `clearInterval()` in order to cancel the scheduled actions. + * + * By default, when a timer is scheduled using either `setTimeout()` or + * `setInterval()`, the Node.js event loop will continue running as long as the + * timer is active. Each of the `Timeout` objects returned by these functions + * export both `timeout.ref()` and `timeout.unref()` functions that can be used to + * control this default behavior. + */ + interface Timeout extends RefCounted, Disposable, Timer { + /** + * Cancels the timeout. + * @since v0.9.1 + * @legacy Use `clearTimeout()` instead. + * @returns a reference to `timeout` + */ + close(): this; + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the + * `Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. + * + * By default, all `Timeout` objects are "ref'ed", making it normally unnecessary + * to call `timeout.ref()` unless `timeout.unref()` had been called previously. + * @since v0.9.1 + * @returns a reference to `timeout` + */ + ref(): this; + /** + * Sets the timer's start time to the current time, and reschedules the timer to + * call its callback at the previously specified duration adjusted to the current + * time. This is useful for refreshing a timer without allocating a new + * JavaScript object. + * + * Using this on a timer that has already called its callback will reactivate the + * timer. + * @since v10.2.0 + * @returns a reference to `timeout` + */ + refresh(): this; + /** + * When called, the active `Timeout` object will not require the Node.js event loop + * to remain active. If there is no other activity keeping the event loop running, + * the process may exit before the `Timeout` object's callback is invoked. Calling + * `timeout.unref()` multiple times will have no effect. + * @since v0.9.1 + * @returns a reference to `timeout` + */ + unref(): this; + /** + * Coerce a `Timeout` to a primitive. The primitive can be used to + * clear the `Timeout`. The primitive can only be used in the + * same thread where the timeout was created. Therefore, to use it + * across `worker_threads` it must first be passed to the correct + * thread. This allows enhanced compatibility with browser + * `setTimeout()` and `setInterval()` implementations. + * @since v14.9.0, v12.19.0 + */ + [Symbol.toPrimitive](): number; + /** + * Cancels the timeout. + * @since v20.5.0, v18.18.0 + * @experimental + */ + [Symbol.dispose](): void; + _onTimeout(...args: any[]): void; + } + } + /** + * Schedules the "immediate" execution of the `callback` after I/O events' + * callbacks. + * + * When multiple calls to `setImmediate()` are made, the `callback` functions are + * queued for execution in the order in which they are created. The entire callback + * queue is processed every event loop iteration. If an immediate timer is queued + * from inside an executing callback, that timer will not be triggered until the + * next event loop iteration. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using + * `timersPromises.setImmediate()`. + * @since v0.9.1 + * @param callback The function to call at the end of this turn of + * the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout) + * @param args Optional arguments to pass when the `callback` is called. + * @returns for use with `clearImmediate()` + */ + function setImmediate( + callback: (...args: TArgs) => void, + ...args: TArgs + ): NodeJS.Immediate; + // Allow a single void-accepting argument to be optional in arguments lists. + // Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258) + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setImmediate(callback: (_: void) => void): NodeJS.Immediate; + namespace setImmediate { + import __promisify__ = promises.setImmediate; + export { __promisify__ }; + } + /** + * Schedules repeated execution of `callback` every `delay` milliseconds. + * + * When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay` + * will be set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using + * `timersPromises.setInterval()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param delay The number of milliseconds to wait before calling the + * `callback`. **Default:** `1`. + * @param args Optional arguments to pass when the `callback` is called. + * @returns for use with `clearInterval()` + */ + function setInterval( + callback: (...args: TArgs) => void, + delay?: number, + ...args: TArgs + ): NodeJS.Timeout; + // Allow a single void-accepting argument to be optional in arguments lists. + // Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258) + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setInterval(callback: (_: void) => void, delay?: number): NodeJS.Timeout; + /** + * Schedules execution of a one-time `callback` after `delay` milliseconds. + * + * The `callback` will likely not be invoked in precisely `delay` milliseconds. + * Node.js makes no guarantees about the exact timing of when callbacks will fire, + * nor of their ordering. The callback will be called as close as possible to the + * time specified. + * + * When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay` + * will be set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using + * `timersPromises.setTimeout()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param delay The number of milliseconds to wait before calling the + * `callback`. **Default:** `1`. + * @param args Optional arguments to pass when the `callback` is called. + * @returns for use with `clearTimeout()` + */ + function setTimeout( + callback: (...args: TArgs) => void, + delay?: number, + ...args: TArgs + ): NodeJS.Timeout; + // Allow a single void-accepting argument to be optional in arguments lists. + // Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258) + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setTimeout(callback: (_: void) => void, delay?: number): NodeJS.Timeout; + namespace setTimeout { + import __promisify__ = promises.setTimeout; + export { __promisify__ }; + } + /** + * Cancels an `Immediate` object created by `setImmediate()`. + * @since v0.9.1 + * @param immediate An `Immediate` object as returned by `setImmediate()`. + */ + function clearImmediate(immediate: NodeJS.Immediate | undefined): void; + /** + * Cancels a `Timeout` object created by `setInterval()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by `setInterval()` + * or the primitive of the `Timeout` object as a string or a number. + */ + function clearInterval(timeout: NodeJS.Timeout | string | number | undefined): void; + /** + * Cancels a `Timeout` object created by `setTimeout()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by `setTimeout()` + * or the primitive of the `Timeout` object as a string or a number. + */ + function clearTimeout(timeout: NodeJS.Timeout | string | number | undefined): void; + /** + * The `queueMicrotask()` method queues a microtask to invoke `callback`. If + * `callback` throws an exception, the `process` object `'uncaughtException'` + * event will be emitted. + * + * The microtask queue is managed by V8 and may be used in a similar manner to + * the `process.nextTick()` queue, which is managed by Node.js. The + * `process.nextTick()` queue is always processed before the microtask queue + * within each turn of the Node.js event loop. + * @since v11.0.0 + * @param callback Function to be queued. + */ + function queueMicrotask(callback: () => void): void; + } + import clearImmediate = globalThis.clearImmediate; + import clearInterval = globalThis.clearInterval; + import clearTimeout = globalThis.clearTimeout; + import setImmediate = globalThis.setImmediate; + import setInterval = globalThis.setInterval; + import setTimeout = globalThis.setTimeout; + export { clearImmediate, clearInterval, clearTimeout, promises, setImmediate, setInterval, setTimeout }; +} +declare module "node:timers" { + export * from "timers"; +} diff --git a/node_modules/@types/node/timers/promises.d.ts b/node_modules/@types/node/timers/promises.d.ts new file mode 100644 index 0000000..05db90c --- /dev/null +++ b/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,108 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via + * `require('node:timers/promises')`. + * + * ```js + * import { + * setTimeout, + * setImmediate, + * setInterval, + * } from 'node:timers/promises'; + * ``` + * @since v15.0.0 + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/timers/promises.js) + */ +declare module "timers/promises" { + import { TimerOptions } from "node:timers"; + /** + * ```js + * import { + * setTimeout, + * } from 'node:timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param delay The number of milliseconds to wait before fulfilling the + * promise. **Default:** `1`. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from 'node:timers/promises'; + * + * const res = await setImmediate('result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param value A value with which the promise is fulfilled. + */ + function setImmediate(value?: T, options?: TimerOptions): Promise; + /** + * Returns an async iterator that generates values in an interval of `delay` ms. + * If `ref` is `true`, you need to call `next()` of async iterator explicitly + * or implicitly to keep the event loop alive. + * + * ```js + * import { + * setInterval, + * } from 'node:timers/promises'; + * + * const interval = 100; + * for await (const startTime of setInterval(interval, Date.now())) { + * const now = Date.now(); + * console.log(now); + * if ((now - startTime) > 1000) + * break; + * } + * console.log(Date.now()); + * ``` + * @since v15.9.0 + * @param delay The number of milliseconds to wait between iterations. + * **Default:** `1`. + * @param value A value with which the iterator returns. + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): NodeJS.AsyncIterator; + interface Scheduler { + /** + * An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification + * being developed as a standard Web Platform API. + * + * Calling `timersPromises.scheduler.wait(delay, options)` is roughly equivalent + * to calling `timersPromises.setTimeout(delay, undefined, options)` except that + * the `ref` option is not supported. + * + * ```js + * import { scheduler } from 'node:timers/promises'; + * + * await scheduler.wait(1000); // Wait one second before continuing + * ``` + * @since v17.3.0, v16.14.0 + * @experimental + * @param delay The number of milliseconds to wait before resolving the + * promise. + */ + wait(delay: number, options?: { signal?: AbortSignal }): Promise; + /** + * An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification + * being developed as a standard Web Platform API. + * + * Calling `timersPromises.scheduler.yield()` is equivalent to calling + * `timersPromises.setImmediate()` with no arguments. + * @since v17.3.0, v16.14.0 + * @experimental + */ + yield(): Promise; + } + const scheduler: Scheduler; +} +declare module "node:timers/promises" { + export * from "timers/promises"; +} diff --git a/node_modules/@types/node/tls.d.ts b/node_modules/@types/node/tls.d.ts new file mode 100644 index 0000000..86e96b8 --- /dev/null +++ b/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1315 @@ +/** + * The `node:tls` module provides an implementation of the Transport Layer Security + * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. + * The module can be accessed using: + * + * ```js + * import tls from 'node:tls'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/tls.js) + */ +declare module "tls" { + import { NonSharedBuffer } from "node:buffer"; + import { X509Certificate } from "node:crypto"; + import * as net from "node:net"; + import * as stream from "stream"; + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + interface PeerCertificate { + /** + * `true` if a Certificate Authority (CA), `false` otherwise. + * @since v18.13.0 + */ + ca: boolean; + /** + * The DER encoded X.509 certificate data. + */ + raw: NonSharedBuffer; + /** + * The certificate subject. + */ + subject: Certificate; + /** + * The certificate issuer, described in the same terms as the `subject`. + */ + issuer: Certificate; + /** + * The date-time the certificate is valid from. + */ + valid_from: string; + /** + * The date-time the certificate is valid to. + */ + valid_to: string; + /** + * The certificate serial number, as a hex string. + */ + serialNumber: string; + /** + * The SHA-1 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint: string; + /** + * The SHA-256 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint256: string; + /** + * The SHA-512 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint512: string; + /** + * The extended key usage, a set of OIDs. + */ + ext_key_usage?: string[]; + /** + * A string containing concatenated names for the subject, + * an alternative to the `subject` names. + */ + subjectaltname?: string; + /** + * An array describing the AuthorityInfoAccess, used with OCSP. + */ + infoAccess?: NodeJS.Dict; + /** + * For RSA keys: The RSA bit size. + * + * For EC keys: The key size in bits. + */ + bits?: number; + /** + * The RSA exponent, as a string in hexadecimal number notation. + */ + exponent?: string; + /** + * The RSA modulus, as a hexadecimal string. + */ + modulus?: string; + /** + * The public key. + */ + pubkey?: NonSharedBuffer; + /** + * The ASN.1 name of the OID of the elliptic curve. + * Well-known curves are identified by an OID. + * While it is unusual, it is possible that the curve + * is identified by its mathematical properties, + * in which case it will not have an OID. + */ + asn1Curve?: string; + /** + * The NIST name for the elliptic curve, if it has one + * (not all well-known curves have been assigned names by NIST). + */ + nistCurve?: string; + } + interface DetailedPeerCertificate extends PeerCertificate { + /** + * The issuer certificate object. + * For self-signed certificates, this may be a circular reference. + */ + issuerCertificate: DetailedPeerCertificate; + } + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + /** + * IETF name for the cipher suite. + */ + standardName: string; + } + interface EphemeralKeyInfo { + /** + * The supported types are 'DH' and 'ECDH'. + */ + type: string; + /** + * The name property is available only when type is 'ECDH'. + */ + name?: string | undefined; + /** + * The size of parameter of an ephemeral key exchange. + */ + size: number; + } + interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean | undefined; + /** + * An optional net.Server instance. + */ + server?: net.Server | undefined; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer | undefined; + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean | undefined; + } + /** + * Performs transparent encryption of written data and all required TLS + * negotiation. + * + * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. + * + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the + * connection is open. + * @since v0.11.4 + */ + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket | stream.Duplex, options?: TLSSocketOptions); + /** + * This property is `true` if the peer certificate was signed by one of the CAs + * specified when creating the `tls.TLSSocket` instance, otherwise `false`. + * @since v0.11.4 + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This + * property is set only when `tlsSocket.authorized === false`. + * @since v0.11.4 + */ + authorizationError: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. + * @since v0.11.4 + */ + encrypted: true; + /** + * String containing the selected ALPN protocol. + * Before a handshake has completed, this value is always null. + * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol: string | false | null; + /** + * Returns an object representing the local certificate. The returned object has + * some properties corresponding to the fields of the certificate. + * + * See {@link TLSSocket.getPeerCertificate} for an example of the certificate + * structure. + * + * If there is no local certificate, an empty object will be returned. If the + * socket has been destroyed, `null` will be returned. + * @since v11.2.0 + */ + getCertificate(): PeerCertificate | object | null; + /** + * Returns an object containing information on the negotiated cipher suite. + * + * For example, a TLSv1.2 protocol with AES256-SHA cipher: + * + * ```json + * { + * "name": "AES256-SHA", + * "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", + * "version": "SSLv3" + * } + * ``` + * + * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. + * @since v0.11.4 + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the type, name, and size of parameter of + * an ephemeral key exchange in `perfect forward secrecy` on a client + * connection. It returns an empty object when the key exchange is not + * ephemeral. As this is only supported on a client socket; `null` is returned + * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The `name` property is available only when type is `'ECDH'`. + * + * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. + * @since v5.0.0 + */ + getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. + */ + getFinished(): NonSharedBuffer | undefined; + /** + * Returns an object representing the peer's certificate. If the peer does not + * provide a certificate, an empty object will be returned. If the socket has been + * destroyed, `null` will be returned. + * + * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's + * certificate. + * @since v0.11.4 + * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. + * @return A certificate object. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so + * far. + */ + getPeerFinished(): NonSharedBuffer | undefined; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the + * current connection. The value `'unknown'` will be returned for connected + * sockets that have not completed the handshaking process. The value `null` will + * be returned for server sockets or disconnected client sockets. + * + * Protocol versions are: + * + * * `'SSLv3'` + * * `'TLSv1'` + * * `'TLSv1.1'` + * * `'TLSv1.2'` + * * `'TLSv1.3'` + * + * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. + * @since v5.7.0 + */ + getProtocol(): string | null; + /** + * Returns the TLS session data or `undefined` if no session was + * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful + * for debugging. + * + * See `Session Resumption` for more information. + * + * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications + * must use the `'session'` event (it also works for TLSv1.2 and below). + * @since v0.11.4 + */ + getSession(): NonSharedBuffer | undefined; + /** + * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. + * @since v12.11.0 + * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. + */ + getSharedSigalgs(): string[]; + /** + * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. + * + * It may be useful for debugging. + * + * See `Session Resumption` for more information. + * @since v0.11.4 + */ + getTLSTicket(): NonSharedBuffer | undefined; + /** + * See `Session Resumption` for more information. + * @since v0.5.6 + * @return `true` if the session was reused, `false` otherwise. + */ + isSessionReused(): boolean; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * Upon completion, the `callback` function will be passed a single argument + * that is either an `Error` (if the request failed) or `null`. + * + * This method can be used to request a peer's certificate after the secure + * connection has been established. + * + * When running as the server, the socket will be destroyed with an error after `handshakeTimeout` timeout. + * + * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the + * protocol. + * @since v0.11.8 + * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with + * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. + * @return `true` if renegotiation was initiated, `false` otherwise. + */ + renegotiate( + options: { + rejectUnauthorized?: boolean | undefined; + requestCert?: boolean | undefined; + }, + callback: (err: Error | null) => void, + ): undefined | boolean; + /** + * The `tlsSocket.setKeyCert()` method sets the private key and certificate to use for the socket. + * This is mainly useful if you wish to select a server certificate from a TLS server's `ALPNCallback`. + * @since v22.5.0, v20.17.0 + * @param context An object containing at least `key` and `cert` properties from the {@link createSecureContext()} `options`, + * or a TLS context object created with {@link createSecureContext()} itself. + */ + setKeyCert(context: SecureContextOptions | SecureContext): void; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. + * Returns `true` if setting the limit succeeded; `false` otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger + * fragments are buffered by the TLS layer until the entire fragment is received + * and its integrity is verified; large fragments can span multiple roundtrips + * and their processing can be delayed due to packet loss or reordering. However, + * smaller fragments add extra TLS framing bytes and CPU overhead, which may + * decrease overall server throughput. + * @since v0.11.11 + * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + /** + * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts + * to renegotiate will trigger an `'error'` event on the `TLSSocket`. + * @since v8.4.0 + */ + disableRenegotiation(): void; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * + * The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by + * OpenSSL's `SSL_trace()` function, the format is undocumented, can change + * without notice, and should not be relied on. + * @since v12.2.0 + */ + enableTrace(): void; + /** + * Returns the peer certificate as an `X509Certificate` object. + * + * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getPeerX509Certificate(): X509Certificate | undefined; + /** + * Returns the local certificate as an `X509Certificate` object. + * + * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getX509Certificate(): X509Certificate | undefined; + /** + * Keying material is used for validations to prevent different kind of attacks in + * network protocols, for example in the specifications of IEEE 802.1X. + * + * Example + * + * ```js + * const keyingMaterial = tlsSocket.exportKeyingMaterial( + * 128, + * 'client finished'); + * + * /* + * Example return value of keyingMaterial: + * + * + * ``` + * + * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more + * information. + * @since v13.10.0, v12.17.0 + * @param length number of bytes to retrieve from keying material + * @param label an application specific label, typically this will be a value from the [IANA Exporter Label + * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * @param context Optionally provide a context. + * @return requested bytes of the keying material + */ + exportKeyingMaterial(length: number, label: string, context: Buffer): NonSharedBuffer; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + addListener(event: "session", listener: (session: NonSharedBuffer) => void): this; + addListener(event: "keylog", listener: (line: NonSharedBuffer) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: NonSharedBuffer): boolean; + emit(event: "secureConnect"): boolean; + emit(event: "session", session: NonSharedBuffer): boolean; + emit(event: "keylog", line: NonSharedBuffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + on(event: "session", listener: (session: NonSharedBuffer) => void): this; + on(event: "keylog", listener: (line: NonSharedBuffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + once(event: "session", listener: (session: NonSharedBuffer) => void): this; + once(event: "keylog", listener: (line: NonSharedBuffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + prependListener(event: "session", listener: (session: NonSharedBuffer) => void): this; + prependListener(event: "keylog", listener: (line: NonSharedBuffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + prependOnceListener(event: "session", listener: (session: NonSharedBuffer) => void): this; + prependOnceListener(event: "keylog", listener: (line: NonSharedBuffer) => void): this; + } + interface CommonConnectionOptions { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext | undefined; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * @default false + */ + enableTrace?: boolean | undefined; + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean | undefined; + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) + */ + ALPNProtocols?: readonly string[] | NodeJS.ArrayBufferView | undefined; + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. + * @default true + */ + rejectUnauthorized?: boolean | undefined; + } + interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { + /** + * Abort the connection if the SSL/TLS handshake does not finish in the + * specified number of milliseconds. A 'tlsClientError' is emitted on + * the tls.Server object whenever a handshake times out. Default: + * 120000 (120 seconds). + */ + handshakeTimeout?: number | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + */ + ticketKeys?: Buffer | undefined; + /** + * @param socket + * @param identity identity parameter sent from the client. + * @return pre-shared key that must either be + * a buffer or `null` to stop the negotiation process. Returned PSK must be + * compatible with the selected cipher's digest. + * + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with the identity provided by the client. + * If the return value is `null` the negotiation process will stop and an + * "unknown_psk_identity" alert message will be sent to the other party. + * If the server wishes to hide the fact that the PSK identity was not known, + * the callback must provide some random data as `psk` to make the connection + * fail with "decrypt_error" before negotiation is finished. + * PSK ciphers are disabled by default, and using TLS-PSK thus + * requires explicitly specifying a cipher suite with the `ciphers` option. + * More information can be found in the RFC 4279. + */ + pskCallback?: ((socket: TLSSocket, identity: string) => NodeJS.ArrayBufferView | null) | undefined; + /** + * hint to send to a client to help + * with selecting the identity during TLS-PSK negotiation. Will be ignored + * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be + * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. + */ + pskIdentityHint?: string | undefined; + } + interface PSKCallbackNegotation { + psk: NodeJS.ArrayBufferView; + identity: string; + } + interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { + host?: string | undefined; + port?: number | undefined; + path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket + checkServerIdentity?: typeof checkServerIdentity | undefined; + servername?: string | undefined; // SNI TLS Extension + session?: Buffer | undefined; + minDHSize?: number | undefined; + lookup?: net.LookupFunction | undefined; + timeout?: number | undefined; + /** + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with optional identity `hint` provided by the server or `null` + * in case of TLS 1.3 where `hint` was removed. + * It will be necessary to provide a custom `tls.checkServerIdentity()` + * for the connection as the default one will try to check hostname/IP + * of the server against the certificate but that's not applicable for PSK + * because there won't be a certificate present. + * More information can be found in the RFC 4279. + * + * @param hint message sent from the server to help client + * decide which identity to use during negotiation. + * Always `null` if TLS 1.3 is used. + * @returns Return `null` to stop the negotiation process. `psk` must be + * compatible with the selected cipher's digest. + * `identity` must use UTF-8 encoding. + */ + pskCallback?: ((hint: string | null) => PSKCallbackNegotation | null) | undefined; + } + /** + * Accepts encrypted connections using TLS or SSL. + * @since v0.3.2 + */ + class Server extends net.Server { + constructor(secureConnectionListener?: (socket: TLSSocket) => void); + constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); + /** + * The `server.addContext()` method adds a secure context that will be used if + * the client request's SNI name matches the supplied `hostname` (or wildcard). + * + * When there are multiple matching contexts, the most recently added one is + * used. + * @since v0.5.3 + * @param hostname A SNI host name or wildcard (e.g. `'*'`) + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc), or a TLS context object created + * with {@link createSecureContext} itself. + */ + addContext(hostname: string, context: SecureContextOptions | SecureContext): void; + /** + * Returns the session ticket keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @return A 48-byte buffer containing the session ticket keys. + */ + getTicketKeys(): NonSharedBuffer; + /** + * The `server.setSecureContext()` method replaces the secure context of an + * existing server. Existing connections to the server are not interrupted. + * @since v11.0.0 + * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + setSecureContext(options: SecureContextOptions): void; + /** + * Sets the session ticket keys. + * + * Changes to the ticket keys are effective only for future server connections. + * Existing or currently pending server connections will use the previous keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @param keys A 48-byte buffer containing the session ticket keys. + */ + setTicketKeys(keys: Buffer): void; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + * 6. keylog + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + addListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit( + event: "newSession", + sessionId: NonSharedBuffer, + sessionData: NonSharedBuffer, + callback: () => void, + ): boolean; + emit( + event: "OCSPRequest", + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ): boolean; + emit( + event: "resumeSession", + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + emit(event: "keylog", line: NonSharedBuffer, tlsSocket: TLSSocket): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + on( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + on(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + once(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this; + } + /** + * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. + */ + interface SecurePair { + encrypted: TLSSocket; + cleartext: TLSSocket; + } + type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1"; + interface SecureContextOptions { + /** + * If set, this will be called when a client opens a connection using the ALPN extension. + * One argument will be passed to the callback: an object containing `servername` and `protocols` fields, + * respectively containing the server name from the SNI extension (if any) and an array of + * ALPN protocol name strings. The callback must return either one of the strings listed in `protocols`, + * which will be returned to the client as the selected ALPN protocol, or `undefined`, + * to reject the connection with a fatal alert. If a string is returned that does not match one of + * the client's ALPN protocols, an error will be thrown. + * This option cannot be used with the `ALPNProtocols` option, and setting both options will throw an error. + */ + ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined; + /** + * Treat intermediate (non-self-signed) + * certificates in the trust CA certificate list as trusted. + * @since v22.9.0, v20.18.0 + */ + allowPartialTrustChain?: boolean | undefined; + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Colon-separated list of supported signature algorithms. The list + * can contain digest algorithms (SHA256, MD5 etc.), public key + * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g + * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). + */ + sigalgs?: string | undefined; + /** + * Cipher suite specification, replacing the default. For more + * information, see modifying the default cipher suite. Permitted + * ciphers can be obtained via tls.getCiphers(). Cipher names must be + * uppercased in order for OpenSSL to accept them. + */ + ciphers?: string | undefined; + /** + * Name of an OpenSSL engine which can provide the client certificate. + * @deprecated + */ + clientCertEngine?: string | undefined; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: string | Buffer | Array | undefined; + /** + * `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. + * If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. + * ECDHE-based perfect forward secrecy will still be available. + */ + dhparam?: string | Buffer | undefined; + /** + * A string describing a named curve or a colon separated list of curve + * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key + * agreement. Set to auto to select the curve automatically. Use + * crypto.getCurves() to obtain a list of available curve names. On + * recent releases, openssl ecparam -list_curves will also display the + * name and description of each available elliptic curve. Default: + * tls.DEFAULT_ECDH_CURVE. + */ + ecdhCurve?: string | undefined; + /** + * Attempt to use the server's cipher suite preferences instead of the + * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be + * set in secureOptions + */ + honorCipherOrder?: boolean | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Name of an OpenSSL engine to get private key from. Should be used + * together with privateKeyIdentifier. + * @deprecated + */ + privateKeyEngine?: string | undefined; + /** + * Identifier of a private key managed by an OpenSSL engine. Should be + * used together with privateKeyEngine. Should not be set together with + * key, because both options define a private key in different ways. + * @deprecated + */ + privateKeyIdentifier?: string | undefined; + /** + * Optionally set the maximum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. + * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using + * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to + * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. + */ + maxVersion?: SecureVersion | undefined; + /** + * Optionally set the minimum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to + * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. + */ + minVersion?: SecureVersion | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form {buf: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted PFX will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; + /** + * Optionally affect the OpenSSL protocol behavior, which is not + * usually necessary. This should be used carefully if at all! Value is + * a numeric bitmask of the SSL_OP_* options from OpenSSL Options + */ + secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options + /** + * Legacy mechanism to select the TLS protocol version to use, it does + * not support independent control of the minimum and maximum version, + * and does not support limiting the protocol to TLSv1.3. Use + * minVersion and maxVersion instead. The possible values are listed as + * SSL_METHODS, use the function names as strings. For example, use + * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow + * any TLS protocol version up to TLSv1.3. It is not recommended to use + * TLS versions less than 1.2, but it may be required for + * interoperability. Default: none, see minVersion. + */ + secureProtocol?: string | undefined; + /** + * Opaque identifier used by servers to ensure session state is not + * shared between applications. Unused by clients. + */ + sessionIdContext?: string | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + * See Session Resumption for more information. + */ + ticketKeys?: Buffer | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + } + interface SecureContext { + context: any; + } + /** + * Verifies the certificate `cert` is issued to `hostname`. + * + * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on + * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). + * + * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as + * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead. + * + * This function can be overwritten by providing an alternative function as the `options.checkServerIdentity` option that is passed to `tls.connect()`. The + * overwriting function can call `tls.checkServerIdentity()` of course, to augment + * the checks done with additional verification. + * + * This function is only called if the certificate passed all other checks, such as + * being issued by trusted CA (`options.ca`). + * + * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name + * was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use + * a custom `options.checkServerIdentity` function that implements the desired behavior. + * @since v0.8.4 + * @param hostname The host name or IP address to verify the certificate against. + * @param cert A `certificate object` representing the peer's certificate. + */ + function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; + /** + * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is + * automatically set as a listener for the `'secureConnection'` event. + * + * The `ticketKeys` options is automatically shared between `node:cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * import tls from 'node:tls'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * + * // This is necessary only if using client certificate authentication. + * requestCert: true, + * + * // This is necessary only if the client uses a self-signed certificate. + * ca: [ fs.readFileSync('client-cert.pem') ], + * }; + * + * const server = tls.createServer(options, (socket) => { + * console.log('server connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * socket.write('welcome!\n'); + * socket.setEncoding('utf8'); + * socket.pipe(socket); + * }); + * server.listen(8000, () => { + * console.log('server bound'); + * }); + * ``` + * + * The server can be tested by connecting to it using the example client from {@link connect}. + * @since v0.3.2 + */ + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. + * + * `tls.connect()` returns a {@link TLSSocket} object. + * + * Unlike the `https` API, `tls.connect()` does not enable the + * SNI (Server Name Indication) extension by default, which may cause some + * servers to return an incorrect certificate or reject the connection + * altogether. To enable SNI, set the `servername` option in addition + * to `host`. + * + * The following illustrates a client for the echo server example from {@link createServer}: + * + * ```js + * // Assumes an echo server that is listening on port 8000. + * import tls from 'node:tls'; + * import fs from 'node:fs'; + * + * const options = { + * // Necessary only if the server requires client certificate authentication. + * key: fs.readFileSync('client-key.pem'), + * cert: fs.readFileSync('client-cert.pem'), + * + * // Necessary only if the server uses a self-signed certificate. + * ca: [ fs.readFileSync('server-cert.pem') ], + * + * // Necessary only if the server's cert isn't for "localhost". + * checkServerIdentity: () => { return null; }, + * }; + * + * const socket = tls.connect(8000, options, () => { + * console.log('client connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * process.stdin.pipe(socket); + * process.stdin.resume(); + * }); + * socket.setEncoding('utf8'); + * socket.on('data', (data) => { + * console.log(data); + * }); + * socket.on('end', () => { + * console.log('server ends connection'); + * }); + * ``` + * @since v0.11.3 + */ + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect( + port: number, + host?: string, + options?: ConnectionOptions, + secureConnectListener?: () => void, + ): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * Creates a new secure pair object with two streams, one of which reads and writes + * the encrypted data and the other of which reads and writes the cleartext data. + * Generally, the encrypted stream is piped to/from an incoming encrypted data + * stream and the cleartext one is used as a replacement for the initial encrypted + * stream. + * + * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and `encrypted` stream properties. + * + * Using `cleartext` has the same API as {@link TLSSocket}. + * + * The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code: + * + * ```js + * pair = tls.createSecurePair(// ... ); + * pair.encrypted.pipe(socket); + * socket.pipe(pair.encrypted); + * ``` + * + * can be replaced by: + * + * ```js + * secureSocket = tls.TLSSocket(socket, options); + * ``` + * + * where `secureSocket` has the same API as `pair.cleartext`. + * @since v0.3.2 + * @deprecated Since v0.11.3 - Use {@link TLSSocket} instead. + * @param context A secure context object as returned by `tls.createSecureContext()` + * @param isServer `true` to specify that this TLS connection should be opened as a server. + * @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`. + * @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`. + */ + function createSecurePair( + context?: SecureContext, + isServer?: boolean, + requestCert?: boolean, + rejectUnauthorized?: boolean, + ): SecurePair; + /** + * `{@link createServer}` sets the default value of the `honorCipherOrder` option + * to `true`, other APIs that create secure contexts leave it unset. + * + * `{@link createServer}` uses a 128 bit truncated SHA1 hash value generated + * from `process.argv` as the default value of the `sessionIdContext` option, other + * APIs that create secure contexts have no default value. + * + * The `tls.createSecureContext()` method creates a `SecureContext` object. It is + * usable as an argument to several `tls` APIs, such as `server.addContext()`, + * but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option. + * + * A key is _required_ for ciphers that use certificates. Either `key` or `pfx` can be used to provide it. + * + * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of + * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * + * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto' `option. When set to `'auto'`, well-known DHE parameters of sufficient strength + * will be selected automatically. Otherwise, if necessary, `openssl dhparam` can + * be used to create custom parameters. The key length must be greater than or + * equal to 1024 bits or else an error will be thrown. Although 1024 bits is + * permissible, use 2048 bits or larger for stronger security. + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * Returns an array containing the CA certificates from various sources, depending on `type`: + * + * * `"default"`: return the CA certificates that will be used by the Node.js TLS clients by default. + * * When `--use-bundled-ca` is enabled (default), or `--use-openssl-ca` is not enabled, + * this would include CA certificates from the bundled Mozilla CA store. + * * When `--use-system-ca` is enabled, this would also include certificates from the system's + * trusted store. + * * When `NODE_EXTRA_CA_CERTS` is used, this would also include certificates loaded from the specified + * file. + * * `"system"`: return the CA certificates that are loaded from the system's trusted store, according + * to rules set by `--use-system-ca`. This can be used to get the certificates from the system + * when `--use-system-ca` is not enabled. + * * `"bundled"`: return the CA certificates from the bundled Mozilla CA store. This would be the same + * as `tls.rootCertificates`. + * * `"extra"`: return the CA certificates loaded from `NODE_EXTRA_CA_CERTS`. It's an empty array if + * `NODE_EXTRA_CA_CERTS` is not set. + * @since v22.15.0 + * @param type The type of CA certificates that will be returned. Valid values + * are `"default"`, `"system"`, `"bundled"` and `"extra"`. + * **Default:** `"default"`. + * @returns An array of PEM-encoded certificates. The array may contain duplicates + * if the same certificate is repeatedly stored in multiple sources. + */ + function getCACertificates(type?: "default" | "system" | "bundled" | "extra"): string[]; + /** + * Returns an array with the names of the supported TLS ciphers. The names are + * lower-case for historical reasons, but must be uppercased to be used in + * the `ciphers` option of `{@link createSecureContext}`. + * + * Not all supported ciphers are enabled by default. See + * [Modifying the default TLS cipher suite](https://nodejs.org/docs/latest-v22.x/api/tls.html#modifying-the-default-tls-cipher-suite). + * + * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for + * TLSv1.2 and below. + * + * ```js + * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] + * ``` + * @since v0.10.2 + */ + function getCiphers(): string[]; + /** + * Sets the default CA certificates used by Node.js TLS clients. If the provided + * certificates are parsed successfully, they will become the default CA + * certificate list returned by {@link getCACertificates} and used + * by subsequent TLS connections that don't specify their own CA certificates. + * The certificates will be deduplicated before being set as the default. + * + * This function only affects the current Node.js thread. Previous + * sessions cached by the HTTPS agent won't be affected by this change, so + * this method should be called before any unwanted cachable TLS connections are + * made. + * + * To use system CA certificates as the default: + * + * ```js + * import tls from 'node:tls'; + * tls.setDefaultCACertificates(tls.getCACertificates('system')); + * ``` + * + * This function completely replaces the default CA certificate list. To add additional + * certificates to the existing defaults, get the current certificates and append to them: + * + * ```js + * import tls from 'node:tls'; + * const currentCerts = tls.getCACertificates('default'); + * const additionalCerts = ['-----BEGIN CERTIFICATE-----\n...']; + * tls.setDefaultCACertificates([...currentCerts, ...additionalCerts]); + * ``` + * @since v22.19.0 + * @param certs An array of CA certificates in PEM format. + */ + function setDefaultCACertificates(certs: ReadonlyArray): void; + /** + * The default curve name to use for ECDH key agreement in a tls server. + * The default value is `'auto'`. See `{@link createSecureContext()}` for further + * information. + * @since v0.11.13 + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the `maxVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.3'`, unless + * changed using CLI options. Using `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using + * `--tls-max-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the highest maximum is used. + * @since v11.4.0 + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the `minVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.2'`, unless + * changed using CLI options. Using `--tls-min-v1.0` sets the default to + * `'TLSv1'`. Using `--tls-min-v1.1` sets the default to `'TLSv1.1'`. Using + * `--tls-min-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the lowest minimum is used. + * @since v11.4.0 + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * The default value of the `ciphers` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported OpenSSL ciphers. + * Defaults to the content of `crypto.constants.defaultCoreCipherList`, unless + * changed using CLI options using `--tls-default-ciphers`. + * @since v19.8.0 + */ + let DEFAULT_CIPHERS: string; + /** + * An immutable array of strings representing the root certificates (in PEM format) + * from the bundled Mozilla CA store as supplied by the current Node.js version. + * + * The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store + * that is fixed at release time. It is identical on all supported platforms. + * @since v12.3.0 + */ + const rootCertificates: readonly string[]; +} +declare module "node:tls" { + export * from "tls"; +} diff --git a/node_modules/@types/node/trace_events.d.ts b/node_modules/@types/node/trace_events.d.ts new file mode 100644 index 0000000..f334b0b --- /dev/null +++ b/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,197 @@ +/** + * The `node:trace_events` module provides a mechanism to centralize tracing information + * generated by V8, Node.js core, and userspace code. + * + * Tracing can be enabled with the `--trace-event-categories` command-line flag + * or by using the `trace_events` module. The `--trace-event-categories` flag + * accepts a list of comma-separated category names. + * + * The available categories are: + * + * * `node`: An empty placeholder. + * * `node.async_hooks`: Enables capture of detailed [`async_hooks`](https://nodejs.org/docs/latest-v22.x/api/async_hooks.html) trace data. + * The [`async_hooks`](https://nodejs.org/docs/latest-v22.x/api/async_hooks.html) events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. + * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. + * * `node.console`: Enables capture of `console.time()` and `console.count()` output. + * * `node.threadpoolwork.sync`: Enables capture of trace data for threadpool synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.threadpoolwork.async`: Enables capture of trace data for threadpool asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.dns.native`: Enables capture of trace data for DNS queries. + * * `node.net.native`: Enables capture of trace data for network. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.fs_dir.sync`: Enables capture of trace data for file system sync directory methods. + * * `node.fs.async`: Enables capture of trace data for file system async methods. + * * `node.fs_dir.async`: Enables capture of trace data for file system async directory methods. + * * `node.perf`: Enables capture of [Performance API](https://nodejs.org/docs/latest-v22.x/api/perf_hooks.html) measurements. + * * `node.perf.usertiming`: Enables capture of only Performance API User Timing + * measures and marks. + * * `node.perf.timerify`: Enables capture of only Performance API timerify + * measurements. + * * `node.promises.rejections`: Enables capture of trace data tracking the number + * of unhandled Promise rejections and handled-after-rejections. + * * `node.vm.script`: Enables capture of trace data for the `node:vm` module's `runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The [V8](https://nodejs.org/docs/latest-v22.x/api/v8.html) events are GC, compiling, and execution related. + * * `node.http`: Enables capture of trace data for http request / response. + * + * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. + * + * ```bash + * node --trace-event-categories v8,node,node.async_hooks server.js + * ``` + * + * Prior versions of Node.js required the use of the `--trace-events-enabled` flag to enable trace events. This requirement has been removed. However, the `--trace-events-enabled` flag _may_ still be + * used and will enable the `node`, `node.async_hooks`, and `v8` trace event categories by default. + * + * ```bash + * node --trace-events-enabled + * + * # is equivalent to + * + * node --trace-event-categories v8,node,node.async_hooks + * ``` + * + * Alternatively, trace events may be enabled using the `node:trace_events` module: + * + * ```js + * import trace_events from 'node:trace_events'; + * const tracing = trace_events.createTracing({ categories: ['node.perf'] }); + * tracing.enable(); // Enable trace event capture for the 'node.perf' category + * + * // do work + * + * tracing.disable(); // Disable trace event capture for the 'node.perf' category + * ``` + * + * Running Node.js with tracing enabled will produce log files that can be opened + * in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome. + * + * The logging file is by default called `node_trace.${rotation}.log`, where `${rotation}` is an incrementing log-rotation id. The filepath pattern can + * be specified with `--trace-event-file-pattern` that accepts a template + * string that supports `${rotation}` and `${pid}`: + * + * ```bash + * node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js + * ``` + * + * To guarantee that the log file is properly generated after signal events like `SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers + * in your code, such as: + * + * ```js + * process.on('SIGINT', function onSigint() { + * console.info('Received SIGINT.'); + * process.exit(130); // Or applicable exit code depending on OS and signal + * }); + * ``` + * + * The tracing system uses the same time source + * as the one used by `process.hrtime()`. + * However the trace-event timestamps are expressed in microseconds, + * unlike `process.hrtime()` which returns nanoseconds. + * + * The features from this module are not available in [`Worker`](https://nodejs.org/docs/latest-v22.x/api/worker_threads.html#class-worker) threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/trace_events.js) + */ +declare module "trace_events" { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + * @since v10.0.0 + */ + readonly categories: string; + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + * + * ```js + * import trace_events from 'node:trace_events'; + * const t1 = trace_events.createTracing({ categories: ['node', 'v8'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] }); + * t1.enable(); + * t2.enable(); + * + * // Prints 'node,node.perf,v8' + * console.log(trace_events.getEnabledCategories()); + * + * t2.disable(); // Will only disable emission of the 'node.perf' category + * + * // Prints 'node,v8' + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + * @since v10.0.0 + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + * @since v10.0.0 + */ + readonly enabled: boolean; + } + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + /** + * Creates and returns a `Tracing` object for the given set of `categories`. + * + * ```js + * import trace_events from 'node:trace_events'; + * const categories = ['node.perf', 'node.async_hooks']; + * const tracing = trace_events.createTracing({ categories }); + * tracing.enable(); + * // do stuff + * tracing.disable(); + * ``` + * @since v10.0.0 + */ + function createTracing(options: CreateTracingOptions): Tracing; + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is determined + * by the _union_ of all currently-enabled `Tracing` objects and any categories + * enabled using the `--trace-event-categories` flag. + * + * Given the file `test.js` below, the command `node --trace-event-categories node.perf test.js` will print `'node.async_hooks,node.perf'` to the console. + * + * ```js + * import trace_events from 'node:trace_events'; + * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); + * const t3 = trace_events.createTracing({ categories: ['v8'] }); + * + * t1.enable(); + * t2.enable(); + * + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + function getEnabledCategories(): string | undefined; +} +declare module "node:trace_events" { + export * from "trace_events"; +} diff --git a/node_modules/@types/node/ts5.6/buffer.buffer.d.ts b/node_modules/@types/node/ts5.6/buffer.buffer.d.ts new file mode 100644 index 0000000..a5f67d7 --- /dev/null +++ b/node_modules/@types/node/ts5.6/buffer.buffer.d.ts @@ -0,0 +1,468 @@ +declare module "buffer" { + global { + interface BufferConstructor { + // see ../buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: ArrayLike): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: ArrayBufferLike): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * If `array` is an `Array`-like object (that is, one with a `length` property of + * type `number`), it is treated as if it is an array, unless it is a `Buffer` or + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an + * `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use + * `Buffer.copyBytesFrom()`. + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal + * `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from(array: WithImplicitCoercion>): Buffer; + /** + * This creates a view of the `ArrayBuffer` without copying the underlying + * memory. For example, when passed a reference to the `.buffer` property of a + * `TypedArray` instance, the newly created `Buffer` will share the same + * allocated memory as the `TypedArray`'s underlying `ArrayBuffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arr = new Uint16Array(2); + * + * arr[0] = 5000; + * arr[1] = 4000; + * + * // Shares memory with `arr`. + * const buf = Buffer.from(arr.buffer); + * + * console.log(buf); + * // Prints: + * + * // Changing the original Uint16Array changes the Buffer also. + * arr[1] = 6000; + * + * console.log(buf); + * // Prints: + * ``` + * + * The optional `byteOffset` and `length` arguments specify a memory range within + * the `arrayBuffer` that will be shared by the `Buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const ab = new ArrayBuffer(10); + * const buf = Buffer.from(ab, 0, 2); + * + * console.log(buf.length); + * // Prints: 2 + * ``` + * + * A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer` or a + * `SharedArrayBuffer` or another type appropriate for `Buffer.from()` + * variants. + * + * It is important to remember that a backing `ArrayBuffer` can cover a range + * of memory that extends beyond the bounds of a `TypedArray` view. A new + * `Buffer` created using the `buffer` property of a `TypedArray` may extend + * beyond the range of the `TypedArray`: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements + * const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements + * console.log(arrA.buffer === arrB.buffer); // true + * + * const buf = Buffer.from(arrB.buffer); + * console.log(buf); + * // Prints: + * ``` + * @since v5.10.0 + * @param arrayBuffer An `ArrayBuffer`, `SharedArrayBuffer`, for example the + * `.buffer` property of a `TypedArray`. + * @param byteOffset Index of first byte to expose. **Default:** `0`. + * @param length Number of bytes to expose. **Default:** + * `arrayBuffer.byteLength - byteOffset`. + */ + from( + arrayBuffer: WithImplicitCoercion, + byteOffset?: number, + length?: number, + ): Buffer; + /** + * Creates a new `Buffer` containing `string`. The `encoding` parameter identifies + * the character encoding to be used when converting `string` into bytes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('this is a tést'); + * const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); + * + * console.log(buf1.toString()); + * // Prints: this is a tést + * console.log(buf2.toString()); + * // Prints: this is a tést + * console.log(buf1.toString('latin1')); + * // Prints: this is a tést + * ``` + * + * A `TypeError` will be thrown if `string` is not a string or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(string)` may also use the internal `Buffer` pool like + * `Buffer.allocUnsafe()` does. + * @since v5.10.0 + * @param string A string to encode. + * @param encoding The encoding of `string`. **Default:** `'utf8'`. + */ + from(string: WithImplicitCoercion, encoding?: BufferEncoding): Buffer; + from(arrayOrString: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: readonly Uint8Array[], totalLength?: number): Buffer; + /** + * Copies the underlying memory of `view` into a new `Buffer`. + * + * ```js + * const u16 = new Uint16Array([0, 0xffff]); + * const buf = Buffer.copyBytesFrom(u16, 1, 1); + * u16[1] = 0; + * console.log(buf.length); // 2 + * console.log(buf[0]); // 255 + * console.log(buf[1]); // 255 + * ``` + * @since v19.8.0 + * @param view The {TypedArray} to copy. + * @param [offset=0] The starting offset within `view`. + * @param [length=view.length - offset] The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if + * `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + } + interface Buffer extends Uint8Array { + // see ../buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + } + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedBuffer = Buffer; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type AllowSharedBuffer = Buffer; + } + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + var SlowBuffer: { + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + new(size: number): Buffer; + prototype: Buffer; + }; +} diff --git a/node_modules/@types/node/ts5.6/globals.typedarray.d.ts b/node_modules/@types/node/ts5.6/globals.typedarray.d.ts new file mode 100644 index 0000000..f1c444d --- /dev/null +++ b/node_modules/@types/node/ts5.6/globals.typedarray.d.ts @@ -0,0 +1,34 @@ +export {}; // Make this a module + +declare global { + namespace NodeJS { + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float32Array + | Float64Array; + type ArrayBufferView = TypedArray | DataView; + + type NonSharedUint8Array = Uint8Array; + type NonSharedUint8ClampedArray = Uint8ClampedArray; + type NonSharedUint16Array = Uint16Array; + type NonSharedUint32Array = Uint32Array; + type NonSharedInt8Array = Int8Array; + type NonSharedInt16Array = Int16Array; + type NonSharedInt32Array = Int32Array; + type NonSharedBigUint64Array = BigUint64Array; + type NonSharedBigInt64Array = BigInt64Array; + type NonSharedFloat32Array = Float32Array; + type NonSharedFloat64Array = Float64Array; + type NonSharedDataView = DataView; + type NonSharedTypedArray = TypedArray; + type NonSharedArrayBufferView = ArrayBufferView; + } +} diff --git a/node_modules/@types/node/ts5.6/index.d.ts b/node_modules/@types/node/ts5.6/index.d.ts new file mode 100644 index 0000000..5a5af42 --- /dev/null +++ b/node_modules/@types/node/ts5.6/index.d.ts @@ -0,0 +1,97 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +// NOTE: These definitions support Node.js and TypeScript 4.9 through 5.6. + +// Reference required TypeScript libs: +/// + +// TypeScript backwards-compatibility definitions: +/// + +// Definitions specific to TypeScript 4.9 through 5.6: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/node_modules/@types/node/tty.d.ts b/node_modules/@types/node/tty.d.ts new file mode 100644 index 0000000..f567946 --- /dev/null +++ b/node_modules/@types/node/tty.d.ts @@ -0,0 +1,208 @@ +/** + * The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. In most cases, it will not be necessary or possible to use this module + * directly. However, it can be accessed using: + * + * ```js + * import tty from 'node:tty'; + * ``` + * + * When Node.js detects that it is being run with a text terminal ("TTY") + * attached, `process.stdin` will, by default, be initialized as an instance of `tty.ReadStream` and both `process.stdout` and `process.stderr` will, by + * default, be instances of `tty.WriteStream`. The preferred method of determining + * whether Node.js is being run within a TTY context is to check that the value of + * the `process.stdout.isTTY` property is `true`: + * + * ```console + * $ node -p -e "Boolean(process.stdout.isTTY)" + * true + * $ node -p -e "Boolean(process.stdout.isTTY)" | cat + * false + * ``` + * + * In most cases, there should be little to no reason for an application to + * manually create instances of the `tty.ReadStream` and `tty.WriteStream` classes. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/tty.js) + */ +declare module "tty" { + import * as net from "node:net"; + /** + * The `tty.isatty()` method returns `true` if the given `fd` is associated with + * a TTY and `false` if it is not, including whenever `fd` is not a non-negative + * integer. + * @since v0.5.8 + * @param fd A numeric file descriptor + */ + function isatty(fd: number): boolean; + /** + * Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js + * process and there should be no reason to create additional instances. + * @since v0.5.8 + */ + class ReadStream extends net.Socket { + constructor(fd: number, options?: net.SocketConstructorOpts); + /** + * A `boolean` that is `true` if the TTY is currently configured to operate as a + * raw device. + * + * This flag is always `false` when a process starts, even if the terminal is + * operating in raw mode. Its value will change with subsequent calls to `setRawMode`. + * @since v0.7.7 + */ + isRaw: boolean; + /** + * Allows configuration of `tty.ReadStream` so that it operates as a raw device. + * + * When in raw mode, input is always available character-by-character, not + * including modifiers. Additionally, all special processing of characters by the + * terminal is disabled, including echoing input + * characters. Ctrl+C will no longer cause a `SIGINT` when + * in this mode. + * @since v0.7.7 + * @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` + * property will be set to the resulting mode. + * @return The read stream instance. + */ + setRawMode(mode: boolean): this; + /** + * A `boolean` that is always `true` for `tty.ReadStream` instances. + * @since v0.5.8 + */ + isTTY: boolean; + } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; + /** + * Represents the writable side of a TTY. In normal circumstances, `process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there + * should be no reason to create additional instances. + * @since v0.5.8 + */ + class WriteStream extends net.Socket { + constructor(fd: number); + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "resize", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "resize"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "resize", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "resize", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "resize", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "resize", listener: () => void): this; + /** + * `writeStream.clearLine()` clears the current line of this `WriteStream` in a + * direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearLine(dir: Direction, callback?: () => void): boolean; + /** + * `writeStream.clearScreenDown()` clears this `WriteStream` from the current + * cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearScreenDown(callback?: () => void): boolean; + /** + * `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified + * position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + cursorTo(x: number, y?: number, callback?: () => void): boolean; + cursorTo(x: number, callback: () => void): boolean; + /** + * `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its + * current position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + moveCursor(dx: number, dy: number, callback?: () => void): boolean; + /** + * Returns: + * + * * `1` for 2, + * * `4` for 16, + * * `8` for 256, + * * `24` for 16,777,216 colors supported. + * + * Use this to determine what colors the terminal supports. Due to the nature of + * colors in terminals it is possible to either have false positives or false + * negatives. It depends on process information and the environment variables that + * may lie about what terminal is used. + * It is possible to pass in an `env` object to simulate the usage of a specific + * terminal. This can be useful to check how specific environment settings behave. + * + * To enforce a specific color support, use one of the below environment settings. + * + * * 2 colors: `FORCE_COLOR = 0` (Disables colors) + * * 16 colors: `FORCE_COLOR = 1` + * * 256 colors: `FORCE_COLOR = 2` + * * 16,777,216 colors: `FORCE_COLOR = 3` + * + * Disabling color support is also possible by using the `NO_COLOR` and `NODE_DISABLE_COLORS` environment variables. + * @since v9.9.0 + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + getColorDepth(env?: object): number; + /** + * Returns `true` if the `writeStream` supports at least as many colors as provided + * in `count`. Minimum support is 2 (black and white). + * + * This has the same false positives and negatives as described in `writeStream.getColorDepth()`. + * + * ```js + * process.stdout.hasColors(); + * // Returns true or false depending on if `stdout` supports at least 16 colors. + * process.stdout.hasColors(256); + * // Returns true or false depending on if `stdout` supports at least 256 colors. + * process.stdout.hasColors({ TMUX: '1' }); + * // Returns true. + * process.stdout.hasColors(2 ** 24, { TMUX: '1' }); + * // Returns false (the environment setting pretends to support 2 ** 8 colors). + * ``` + * @since v11.13.0, v10.16.0 + * @param [count=16] The number of colors that are requested (minimum 2). + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + hasColors(count?: number): boolean; + hasColors(env?: object): boolean; + hasColors(count: number, env?: object): boolean; + /** + * `writeStream.getWindowSize()` returns the size of the TTY + * corresponding to this `WriteStream`. The array is of the type `[numColumns, numRows]` where `numColumns` and `numRows` represent the number + * of columns and rows in the corresponding TTY. + * @since v0.7.7 + */ + getWindowSize(): [number, number]; + /** + * A `number` specifying the number of columns the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + columns: number; + /** + * A `number` specifying the number of rows the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + rows: number; + /** + * A `boolean` that is always `true`. + * @since v0.5.8 + */ + isTTY: boolean; + } +} +declare module "node:tty" { + export * from "tty"; +} diff --git a/node_modules/@types/node/url.d.ts b/node_modules/@types/node/url.d.ts new file mode 100644 index 0000000..6a0effc --- /dev/null +++ b/node_modules/@types/node/url.d.ts @@ -0,0 +1,984 @@ +/** + * The `node:url` module provides utilities for URL resolution and parsing. It can + * be accessed using: + * + * ```js + * import url from 'node:url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/url.js) + */ +declare module "url" { + import { Blob as NodeBlob, NonSharedBuffer } from "node:buffer"; + import { ClientRequestArgs } from "node:http"; + import { ParsedUrlQuery, ParsedUrlQueryInput } from "node:querystring"; + // Input to `url.format` + interface UrlObject { + auth?: string | null | undefined; + hash?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + href?: string | null | undefined; + pathname?: string | null | undefined; + protocol?: string | null | undefined; + search?: string | null | undefined; + slashes?: boolean | null | undefined; + port?: string | number | null | undefined; + query?: string | null | ParsedUrlQueryInput | undefined; + } + // Output of `url.parse` + interface Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; + } + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + interface UrlWithStringQuery extends Url { + query: string | null; + } + interface FileUrlToPathOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + * @since v22.1.0 + */ + windows?: boolean | undefined; + } + interface PathToFileUrlOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + * @since v22.1.0 + */ + windows?: boolean | undefined; + } + /** + * The `url.parse()` method takes a URL string, parses it, and returns a URL + * object. + * + * A `TypeError` is thrown if `urlString` is not a string. + * + * A `URIError` is thrown if the `auth` property is present but cannot be decoded. + * + * `url.parse()` uses a lenient, non-standard algorithm for parsing URL + * strings. It is prone to security issues such as [host name spoofing](https://hackerone.com/reports/678487) and incorrect handling of usernames and passwords. Do not use with untrusted + * input. CVEs are not issued for `url.parse()` vulnerabilities. Use the `WHATWG URL` API instead. + * @since v0.1.25 + * @deprecated Use the WHATWG URL API instead. + * @param urlString The URL string to parse. + * @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property + * on the returned URL object will be an unparsed, undecoded string. + * @param [slashesDenoteHost=false] If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the + * result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + */ + function parse(urlString: string): UrlWithStringQuery; + function parse( + urlString: string, + parseQueryString: false | undefined, + slashesDenoteHost?: boolean, + ): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * import url from 'node:url'; + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: URL, options?: URLFormatOptions): string; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * import url from 'node:url'; + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: UrlObject | string): string; + /** + * The `url.resolve()` method resolves a target URL relative to a base URL in a + * manner similar to that of a web browser resolving an anchor tag. + * + * ```js + * import url from 'node:url'; + * url.resolve('/one/two/three', 'four'); // '/one/two/four' + * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' + * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * + * To achieve the same result using the WHATWG URL API: + * + * ```js + * function resolve(from, to) { + * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); + * if (resolvedUrl.protocol === 'resolve:') { + * // `from` is a relative URL. + * const { pathname, search, hash } = resolvedUrl; + * return pathname + search + hash; + * } + * return resolvedUrl.toString(); + * } + * + * resolve('/one/two/three', 'four'); // '/one/two/four' + * resolve('http://example.com/', '/one'); // 'http://example.com/one' + * resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param from The base URL to use if `to` is a relative URL. + * @param to The target URL to resolve. + */ + function resolve(from: string, to: string): string; + /** + * Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an + * invalid domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToUnicode}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToASCII('español.com')); + * // Prints xn--espaol-zwa.com + * console.log(url.domainToASCII('中文.com')); + * // Prints xn--fiq228c.com + * console.log(url.domainToASCII('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToASCII(domain: string): string; + /** + * Returns the Unicode serialization of the `domain`. If `domain` is an invalid + * domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToASCII}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToUnicode('xn--espaol-zwa.com')); + * // Prints español.com + * console.log(url.domainToUnicode('xn--fiq228c.com')); + * // Prints 中文.com + * console.log(url.domainToUnicode('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToUnicode(domain: string): string; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * + * ```js + * import { fileURLToPath } from 'node:url'; + * + * const __filename = fileURLToPath(import.meta.url); + * + * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ + * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) + * + * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt + * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) + * + * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt + * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) + * + * new URL('file:///hello world').pathname; // Incorrect: /hello%20world + * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) + * ``` + * @since v10.12.0 + * @param url The file URL string or URL object to convert to a path. + * @return The fully-resolved platform-specific Node.js file path. + */ + function fileURLToPath(url: string | URL, options?: FileUrlToPathOptions): string; + /** + * Like `url.fileURLToPath(...)` except that instead of returning a string + * representation of the path, a `Buffer` is returned. This conversion is + * helpful when the input URL contains percent-encoded segments that are + * not valid UTF-8 / Unicode sequences. + * @since v22.18.0 + * @param url The file URL string or URL object to convert to a path. + * @returns The fully-resolved platform-specific Node.js file path + * as a `Buffer`. + */ + function fileURLToPathBuffer(url: string | URL, options?: FileUrlToPathOptions): NonSharedBuffer; + /** + * This function ensures that `path` is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * + * ```js + * import { pathToFileURL } from 'node:url'; + * + * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 + * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) + * + * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c + * pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) + * ``` + * @since v10.12.0 + * @param path The path to convert to a File URL. + * @return The file URL object. + */ + function pathToFileURL(path: string, options?: PathToFileUrlOptions): URL; + /** + * This utility function converts a URL object into an ordinary options object as + * expected by the `http.request()` and `https.request()` APIs. + * + * ```js + * import { urlToHttpOptions } from 'node:url'; + * const myURL = new URL('https://a:b@測試?abc#foo'); + * + * console.log(urlToHttpOptions(myURL)); + * /* + * { + * protocol: 'https:', + * hostname: 'xn--g6w251d', + * hash: '#foo', + * search: '?abc', + * pathname: '/', + * path: '/?abc', + * href: 'https://a:b@xn--g6w251d/?abc#foo', + * auth: 'a:b' + * } + * + * ``` + * @since v15.7.0, v14.18.0 + * @param url The `WHATWG URL` object to convert to an options object. + * @return Options object + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; + interface URLFormatOptions { + /** + * `true` if the serialized URL string should include the username and password, `false` otherwise. + * @default true + */ + auth?: boolean | undefined; + /** + * `true` if the serialized URL string should include the fragment, `false` otherwise. + * @default true + */ + fragment?: boolean | undefined; + /** + * `true` if the serialized URL string should include the search query, `false` otherwise. + * @default true + */ + search?: boolean | undefined; + /** + * `true` if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to + * being Punycode encoded. + * @default false + */ + unicode?: boolean | undefined; + } + /** + * Browser-compatible `URL` class, implemented by following the WHATWG URL + * Standard. [Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself. + * The `URL` class is also available on the global object. + * + * In accordance with browser conventions, all properties of `URL` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. Thus, unlike `legacy urlObject`s, + * using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still + * return `true`. + * @since v7.0.0, v6.13.0 + */ + class URL { + /** + * Creates a `'blob:nodedata:...'` URL string that represents the given `Blob` object and can be used to retrieve the `Blob` later. + * + * ```js + * import { + * Blob, + * resolveObjectURL, + * } from 'node:buffer'; + * + * const blob = new Blob(['hello']); + * const id = URL.createObjectURL(blob); + * + * // later... + * + * const otherBlob = resolveObjectURL(id); + * console.log(otherBlob.size); + * ``` + * + * The data stored by the registered `Blob` will be retained in memory until `URL.revokeObjectURL()` is called to remove it. + * + * `Blob` objects are registered within the current thread. If using Worker + * Threads, `Blob` objects registered within one Worker will not be available + * to other workers or the main thread. + * @since v16.7.0 + */ + static createObjectURL(blob: NodeBlob): string; + /** + * Removes the stored `Blob` identified by the given ID. Attempting to revoke a + * ID that isn't registered will silently fail. + * @since v16.7.0 + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + static revokeObjectURL(id: string): void; + /** + * Checks if an `input` relative to the `base` can be parsed to a `URL`. + * + * ```js + * const isValid = URL.canParse('/foo', 'https://example.org/'); // true + * + * const isNotValid = URL.canParse('/foo'); // false + * ``` + * @since v19.9.0 + * @param input The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored. If `input` is not a string, it is + * `converted to a string` first. + * @param base The base URL to resolve against if the `input` is not absolute. If `base` is not a string, it is `converted to a string` first. + */ + static canParse(input: string, base?: string): boolean; + /** + * Parses a string as a URL. If `base` is provided, it will be used as the base + * URL for the purpose of resolving non-absolute `input` URLs. Returns `null` + * if the parameters can't be resolved to a valid URL. + * @since v22.1.0 + * @param input The absolute or relative input URL to parse. If `input` + * is relative, then `base` is required. If `input` is absolute, the `base` + * is ignored. If `input` is not a string, it is [converted to a string](https://tc39.es/ecma262/#sec-tostring) first. + * @param base The base URL to resolve against if the `input` is not + * absolute. If `base` is not a string, it is [converted to a string](https://tc39.es/ecma262/#sec-tostring) first. + */ + static parse(input: string, base?: string): URL | null; + constructor(input: string | { toString: () => string }, base?: string | URL); + /** + * Gets and sets the fragment portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/foo#bar'); + * console.log(myURL.hash); + * // Prints #bar + * + * myURL.hash = 'baz'; + * console.log(myURL.href); + * // Prints https://example.org/foo#baz + * ``` + * + * Invalid URL characters included in the value assigned to the `hash` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + hash: string; + /** + * Gets and sets the host portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.host); + * // Prints example.org:81 + * + * myURL.host = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:82/foo + * ``` + * + * Invalid host values assigned to the `host` property are ignored. + */ + host: string; + /** + * Gets and sets the host name portion of the URL. The key difference between`url.host` and `url.hostname` is that `url.hostname` does _not_ include the + * port. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.hostname); + * // Prints example.org + * + * // Setting the hostname does not change the port + * myURL.hostname = 'example.com'; + * console.log(myURL.href); + * // Prints https://example.com:81/foo + * + * // Use myURL.host to change the hostname and port + * myURL.host = 'example.org:82'; + * console.log(myURL.href); + * // Prints https://example.org:82/foo + * ``` + * + * Invalid host name values assigned to the `hostname` property are ignored. + */ + hostname: string; + /** + * Gets and sets the serialized URL. + * + * ```js + * const myURL = new URL('https://example.org/foo'); + * console.log(myURL.href); + * // Prints https://example.org/foo + * + * myURL.href = 'https://example.com/bar'; + * console.log(myURL.href); + * // Prints https://example.com/bar + * ``` + * + * Getting the value of the `href` property is equivalent to calling {@link toString}. + * + * Setting the value of this property to a new value is equivalent to creating a + * new `URL` object using `new URL(value)`. Each of the `URL` object's properties will be modified. + * + * If the value assigned to the `href` property is not a valid URL, a `TypeError` will be thrown. + */ + href: string; + /** + * Gets the read-only serialization of the URL's origin. + * + * ```js + * const myURL = new URL('https://example.org/foo/bar?baz'); + * console.log(myURL.origin); + * // Prints https://example.org + * ``` + * + * ```js + * const idnURL = new URL('https://測試'); + * console.log(idnURL.origin); + * // Prints https://xn--g6w251d + * + * console.log(idnURL.hostname); + * // Prints xn--g6w251d + * ``` + */ + readonly origin: string; + /** + * Gets and sets the password portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.password); + * // Prints xyz + * + * myURL.password = '123'; + * console.log(myURL.href); + * // Prints https://abc:123@example.com/ + * ``` + * + * Invalid URL characters included in the value assigned to the `password` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + password: string; + /** + * Gets and sets the path portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc/xyz?123'); + * console.log(myURL.pathname); + * // Prints /abc/xyz + * + * myURL.pathname = '/abcdef'; + * console.log(myURL.href); + * // Prints https://example.org/abcdef?123 + * ``` + * + * Invalid URL characters included in the value assigned to the `pathname` property are `percent-encoded`. The selection of which characters + * to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + pathname: string; + /** + * Gets and sets the port portion of the URL. + * + * The port value may be a number or a string containing a number in the range `0` to `65535` (inclusive). Setting the value to the default port of the `URL` objects given `protocol` will + * result in the `port` value becoming + * the empty string (`''`). + * + * The port value can be an empty string in which case the port depends on + * the protocol/scheme: + * + * + * + * Upon assigning a value to the port, the value will first be converted to a + * string using `.toString()`. + * + * If that string is invalid but it begins with a number, the leading number is + * assigned to `port`. + * If the number lies outside the range denoted above, it is ignored. + * + * ```js + * const myURL = new URL('https://example.org:8888'); + * console.log(myURL.port); + * // Prints 8888 + * + * // Default ports are automatically transformed to the empty string + * // (HTTPS protocol's default port is 443) + * myURL.port = '443'; + * console.log(myURL.port); + * // Prints the empty string + * console.log(myURL.href); + * // Prints https://example.org/ + * + * myURL.port = 1234; + * console.log(myURL.port); + * // Prints 1234 + * console.log(myURL.href); + * // Prints https://example.org:1234/ + * + * // Completely invalid port strings are ignored + * myURL.port = 'abcd'; + * console.log(myURL.port); + * // Prints 1234 + * + * // Leading numbers are treated as a port number + * myURL.port = '5678abcd'; + * console.log(myURL.port); + * // Prints 5678 + * + * // Non-integers are truncated + * myURL.port = 1234.5678; + * console.log(myURL.port); + * // Prints 1234 + * + * // Out-of-range numbers which are not represented in scientific notation + * // will be ignored. + * myURL.port = 1e10; // 10000000000, will be range-checked as described below + * console.log(myURL.port); + * // Prints 1234 + * ``` + * + * Numbers which contain a decimal point, + * such as floating-point numbers or numbers in scientific notation, + * are not an exception to this rule. + * Leading numbers up to the decimal point will be set as the URL's port, + * assuming they are valid: + * + * ```js + * myURL.port = 4.567e21; + * console.log(myURL.port); + * // Prints 4 (because it is the leading number in the string '4.567e21') + * ``` + */ + port: string; + /** + * Gets and sets the protocol portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org'); + * console.log(myURL.protocol); + * // Prints https: + * + * myURL.protocol = 'ftp'; + * console.log(myURL.href); + * // Prints ftp://example.org/ + * ``` + * + * Invalid URL protocol values assigned to the `protocol` property are ignored. + */ + protocol: string; + /** + * Gets and sets the serialized query portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc?123'); + * console.log(myURL.search); + * // Prints ?123 + * + * myURL.search = 'abc=xyz'; + * console.log(myURL.href); + * // Prints https://example.org/abc?abc=xyz + * ``` + * + * Any invalid URL characters appearing in the value assigned the `search` property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + search: string; + /** + * Gets the `URLSearchParams` object representing the query parameters of the + * URL. This property is read-only but the `URLSearchParams` object it provides + * can be used to mutate the URL instance; to replace the entirety of query + * parameters of the URL, use the {@link search} setter. See `URLSearchParams` documentation for details. + * + * Use care when using `.searchParams` to modify the `URL` because, + * per the WHATWG specification, the `URLSearchParams` object uses + * different rules to determine which characters to percent-encode. For + * instance, the `URL` object will not percent encode the ASCII tilde (`~`) + * character, while `URLSearchParams` will always encode it: + * + * ```js + * const myURL = new URL('https://example.org/abc?foo=~bar'); + * + * console.log(myURL.search); // prints ?foo=~bar + * + * // Modify the URL via searchParams... + * myURL.searchParams.sort(); + * + * console.log(myURL.search); // prints ?foo=%7Ebar + * ``` + */ + readonly searchParams: URLSearchParams; + /** + * Gets and sets the username portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.username); + * // Prints abc + * + * myURL.username = '123'; + * console.log(myURL.href); + * // Prints https://123:xyz@example.com/ + * ``` + * + * Any invalid URL characters appearing in the value assigned the `username` property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + username: string; + /** + * The `toString()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toJSON}. + */ + toString(): string; + /** + * The `toJSON()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toString}. + * + * This method is automatically called when an `URL` object is serialized + * with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). + * + * ```js + * const myURLs = [ + * new URL('https://www.example.com'), + * new URL('https://test.example.org'), + * ]; + * console.log(JSON.stringify(myURLs)); + * // Prints ["https://www.example.com/","https://test.example.org/"] + * ``` + */ + toJSON(): string; + } + interface URLSearchParamsIterator extends NodeJS.Iterator { + [Symbol.iterator](): URLSearchParamsIterator; + } + /** + * The `URLSearchParams` API provides read and write access to the query of a `URL`. The `URLSearchParams` class can also be used standalone with one of the + * four following constructors. + * The `URLSearchParams` class is also available on the global object. + * + * The WHATWG `URLSearchParams` interface and the `querystring` module have + * similar purpose, but the purpose of the `querystring` module is more + * general, as it allows the customization of delimiter characters (`&` and `=`). + * On the other hand, this API is designed purely for URL query strings. + * + * ```js + * const myURL = new URL('https://example.org/?abc=123'); + * console.log(myURL.searchParams.get('abc')); + * // Prints 123 + * + * myURL.searchParams.append('abc', 'xyz'); + * console.log(myURL.href); + * // Prints https://example.org/?abc=123&abc=xyz + * + * myURL.searchParams.delete('abc'); + * myURL.searchParams.set('a', 'b'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * + * const newSearchParams = new URLSearchParams(myURL.searchParams); + * // The above is equivalent to + * // const newSearchParams = new URLSearchParams(myURL.search); + * + * newSearchParams.append('a', 'c'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * console.log(newSearchParams.toString()); + * // Prints a=b&a=c + * + * // newSearchParams.toString() is implicitly called + * myURL.search = newSearchParams; + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * newSearchParams.delete('a'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * ``` + * @since v7.5.0, v6.13.0 + */ + class URLSearchParams implements Iterable<[string, string]> { + constructor( + init?: + | URLSearchParams + | string + | Record + | Iterable<[string, string]> + | ReadonlyArray<[string, string]>, + ); + /** + * Append a new name-value pair to the query string. + */ + append(name: string, value: string): void; + /** + * If `value` is provided, removes all name-value pairs + * where name is `name` and value is `value`. + * + * If `value` is not provided, removes all name-value pairs whose name is `name`. + */ + delete(name: string, value?: string): void; + /** + * Returns an ES6 `Iterator` over each of the name-value pairs in the query. + * Each item of the iterator is a JavaScript `Array`. The first item of the `Array` is the `name`, the second item of the `Array` is the `value`. + * + * Alias for `urlSearchParams[Symbol.iterator]()`. + */ + entries(): URLSearchParamsIterator<[string, string]>; + /** + * Iterates over each name-value pair in the query and invokes the given function. + * + * ```js + * const myURL = new URL('https://example.org/?a=b&c=d'); + * myURL.searchParams.forEach((value, name, searchParams) => { + * console.log(name, value, myURL.searchParams === searchParams); + * }); + * // Prints: + * // a b true + * // c d true + * ``` + * @param fn Invoked for each name-value pair in the query + * @param thisArg To be used as `this` value for when `fn` is called + */ + forEach( + fn: (this: TThis, value: string, name: string, searchParams: URLSearchParams) => void, + thisArg?: TThis, + ): void; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns the values of all name-value pairs whose name is `name`. If there are + * no such pairs, an empty array is returned. + */ + getAll(name: string): string[]; + /** + * Checks if the `URLSearchParams` object contains key-value pair(s) based on `name` and an optional `value` argument. + * + * If `value` is provided, returns `true` when name-value pair with + * same `name` and `value` exists. + * + * If `value` is not provided, returns `true` if there is at least one name-value + * pair whose name is `name`. + */ + has(name: string, value?: string): boolean; + /** + * Returns an ES6 `Iterator` over the names of each name-value pair. + * + * ```js + * const params = new URLSearchParams('foo=bar&foo=baz'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // foo + * ``` + */ + keys(): URLSearchParamsIterator; + /** + * Sets the value in the `URLSearchParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value` and remove all others. If not, + * append the name-value pair to the query string. + * + * ```js + * const params = new URLSearchParams(); + * params.append('foo', 'bar'); + * params.append('foo', 'baz'); + * params.append('abc', 'def'); + * console.log(params.toString()); + * // Prints foo=bar&foo=baz&abc=def + * + * params.set('foo', 'def'); + * params.set('xyz', 'opq'); + * console.log(params.toString()); + * // Prints foo=def&abc=def&xyz=opq + * ``` + */ + set(name: string, value: string): void; + /** + * The total number of parameter entries. + * @since v19.8.0 + */ + readonly size: number; + /** + * Sort all existing name-value pairs in-place by their names. Sorting is done + * with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs + * with the same name is preserved. + * + * This method can be used, in particular, to increase cache hits. + * + * ```js + * const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); + * params.sort(); + * console.log(params.toString()); + * // Prints query%5B%5D=abc&query%5B%5D=123&type=search + * ``` + * @since v7.7.0, v6.13.0 + */ + sort(): void; + /** + * Returns the search parameters serialized as a string, with characters + * percent-encoded where necessary. + */ + toString(): string; + /** + * Returns an ES6 `Iterator` over the values of each name-value pair. + */ + values(): URLSearchParamsIterator; + [Symbol.iterator](): URLSearchParamsIterator<[string, string]>; + } + import { URL as _URL, URLSearchParams as _URLSearchParams } from "url"; + global { + interface URLSearchParams extends _URLSearchParams {} + interface URL extends _URL {} + interface Global { + URL: typeof _URL; + URLSearchParams: typeof _URLSearchParams; + } + /** + * `URL` class is a global reference for `import { URL } from 'url'` + * https://nodejs.org/api/url.html#the-whatwg-url-api + * @since v10.0.0 + */ + var URL: typeof globalThis extends { + onmessage: any; + URL: infer T; + } ? T + : typeof _URL; + /** + * `URLSearchParams` class is a global reference for `import { URLSearchParams } from 'node:url'` + * https://nodejs.org/api/url.html#class-urlsearchparams + * @since v10.0.0 + */ + var URLSearchParams: typeof globalThis extends { + onmessage: any; + URLSearchParams: infer T; + } ? T + : typeof _URLSearchParams; + } +} +declare module "node:url" { + export * from "url"; +} diff --git a/node_modules/@types/node/util.d.ts b/node_modules/@types/node/util.d.ts new file mode 100644 index 0000000..a171f65 --- /dev/null +++ b/node_modules/@types/node/util.d.ts @@ -0,0 +1,2606 @@ +/** + * The `node:util` module supports the needs of Node.js internal APIs. Many of the + * utilities are useful for application and module developers as well. To access + * it: + * + * ```js + * import util from 'node:util'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/util.js) + */ +declare module "util" { + import * as types from "node:util/types"; + export interface InspectOptions { + /** + * If `true`, object's non-enumerable symbols and properties are included in the formatted result. + * `WeakMap` and `WeakSet` entries are also included as well as user defined prototype properties (excluding method properties). + * @default false + */ + showHidden?: boolean | undefined; + /** + * Specifies the number of times to recurse while formatting object. + * This is useful for inspecting large objects. + * To recurse up to the maximum call stack size pass `Infinity` or `null`. + * @default 2 + */ + depth?: number | null | undefined; + /** + * If `true`, the output is styled with ANSI color codes. Colors are customizable. + */ + colors?: boolean | undefined; + /** + * If `false`, `[util.inspect.custom](depth, opts, inspect)` functions are not invoked. + * @default true + */ + customInspect?: boolean | undefined; + /** + * If `true`, `Proxy` inspection includes the target and handler objects. + * @default false + */ + showProxy?: boolean | undefined; + /** + * Specifies the maximum number of `Array`, `TypedArray`, `WeakMap`, and `WeakSet` elements + * to include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no elements. + * @default 100 + */ + maxArrayLength?: number | null | undefined; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default 10000 + */ + maxStringLength?: number | null | undefined; + /** + * The length at which input values are split across multiple lines. + * Set to `Infinity` to format the input as a single line + * (in combination with `compact` set to `true` or any number >= `1`). + * @default 80 + */ + breakLength?: number | undefined; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default true + */ + compact?: boolean | number | undefined; + /** + * If set to `true` or a function, all properties of an object, and `Set` and `Map` + * entries are sorted in the resulting string. + * If set to `true` the default sort is used. + * If set to a function, it is used as a compare function. + */ + sorted?: boolean | ((a: string, b: string) => number) | undefined; + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default false + */ + getters?: "get" | "set" | boolean | undefined; + /** + * If set to `true`, an underscore is used to separate every three digits in all bigints and numbers. + * @default false + */ + numericSeparator?: boolean | undefined; + } + export type Style = + | "special" + | "number" + | "bigint" + | "boolean" + | "undefined" + | "null" + | "string" + | "symbol" + | "date" + | "regexp" + | "module"; + export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => any; // TODO: , inspect: inspect + export interface InspectOptionsStylized extends InspectOptions { + stylize(text: string, styleType: Style): string; + } + export interface CallSiteObject { + /** + * Returns the name of the function associated with this call site. + */ + functionName: string; + /** + * Returns the name of the resource that contains the script for the + * function for this call site. + */ + scriptName: string; + /** + * Returns the unique id of the script, as in Chrome DevTools protocol + * [`Runtime.ScriptId`](https://chromedevtools.github.io/devtools-protocol/1-3/Runtime/#type-ScriptId). + * @since v22.14.0 + */ + scriptId: string; + /** + * Returns the number, 1-based, of the line for the associate function call. + */ + lineNumber: number; + /** + * Returns the 1-based column offset on the line for the associated function call. + */ + columnNumber: number; + } + export type DiffEntry = [operation: -1 | 0 | 1, value: string]; + /** + * `util.diff()` compares two string or array values and returns an array of difference entries. + * It uses the Myers diff algorithm to compute minimal differences, which is the same algorithm + * used internally by assertion error messages. + * + * If the values are equal, an empty array is returned. + * + * ```js + * const { diff } = require('node:util'); + * + * // Comparing strings + * const actualString = '12345678'; + * const expectedString = '12!!5!7!'; + * console.log(diff(actualString, expectedString)); + * // [ + * // [0, '1'], + * // [0, '2'], + * // [1, '3'], + * // [1, '4'], + * // [-1, '!'], + * // [-1, '!'], + * // [0, '5'], + * // [1, '6'], + * // [-1, '!'], + * // [0, '7'], + * // [1, '8'], + * // [-1, '!'], + * // ] + * // Comparing arrays + * const actualArray = ['1', '2', '3']; + * const expectedArray = ['1', '3', '4']; + * console.log(diff(actualArray, expectedArray)); + * // [ + * // [0, '1'], + * // [1, '2'], + * // [0, '3'], + * // [-1, '4'], + * // ] + * // Equal values return empty array + * console.log(diff('same', 'same')); + * // [] + * ``` + * @since v22.15.0 + * @experimental + * @param actual The first value to compare + * @param expected The second value to compare + * @returns An array of difference entries. Each entry is an array with two elements: + * * Index 0: `number` Operation code: `-1` for delete, `0` for no-op/unchanged, `1` for insert + * * Index 1: `string` The value associated with the operation + */ + export function diff(actual: string | readonly string[], expected: string | readonly string[]): DiffEntry[]; + /** + * The `util.format()` method returns a formatted string using the first argument + * as a `printf`-like format string which can contain zero or more format + * specifiers. Each specifier is replaced with the converted value from the + * corresponding argument. Supported specifiers are: + * + * If a specifier does not have a corresponding argument, it is not replaced: + * + * ```js + * util.format('%s:%s', 'foo'); + * // Returns: 'foo:%s' + * ``` + * + * Values that are not part of the format string are formatted using `util.inspect()` if their type is not `string`. + * + * If there are more arguments passed to the `util.format()` method than the + * number of specifiers, the extra arguments are concatenated to the returned + * string, separated by spaces: + * + * ```js + * util.format('%s:%s', 'foo', 'bar', 'baz'); + * // Returns: 'foo:bar baz' + * ``` + * + * If the first argument does not contain a valid format specifier, `util.format()` returns a string that is the concatenation of all arguments separated by spaces: + * + * ```js + * util.format(1, 2, 3); + * // Returns: '1 2 3' + * ``` + * + * If only one argument is passed to `util.format()`, it is returned as it is + * without any formatting: + * + * ```js + * util.format('%% %s'); + * // Returns: '%% %s' + * ``` + * + * `util.format()` is a synchronous method that is intended as a debugging tool. + * Some input values can have a significant performance overhead that can block the + * event loop. Use this function with care and never in a hot code path. + * @since v0.5.3 + * @param format A `printf`-like format string. + */ + export function format(format?: any, ...param: any[]): string; + /** + * This function is identical to {@link format}, except in that it takes + * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}. + * + * ```js + * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + * // Returns 'See object { foo: 42 }', where `42` is colored as a number + * // when printed to a terminal. + * ``` + * @since v10.0.0 + */ + export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; + interface GetCallSitesOptions { + /** + * Reconstruct the original location in the stacktrace from the source-map. + * Enabled by default with the flag `--enable-source-maps`. + */ + sourceMap?: boolean | undefined; + } + /** + * Returns an array of call site objects containing the stack of + * the caller function. + * + * ```js + * import { getCallSites } from 'node:util'; + * + * function exampleFunction() { + * const callSites = getCallSites(); + * + * console.log('Call Sites:'); + * callSites.forEach((callSite, index) => { + * console.log(`CallSite ${index + 1}:`); + * console.log(`Function Name: ${callSite.functionName}`); + * console.log(`Script Name: ${callSite.scriptName}`); + * console.log(`Line Number: ${callSite.lineNumber}`); + * console.log(`Column Number: ${callSite.column}`); + * }); + * // CallSite 1: + * // Function Name: exampleFunction + * // Script Name: /home/example.js + * // Line Number: 5 + * // Column Number: 26 + * + * // CallSite 2: + * // Function Name: anotherFunction + * // Script Name: /home/example.js + * // Line Number: 22 + * // Column Number: 3 + * + * // ... + * } + * + * // A function to simulate another stack layer + * function anotherFunction() { + * exampleFunction(); + * } + * + * anotherFunction(); + * ``` + * + * It is possible to reconstruct the original locations by setting the option `sourceMap` to `true`. + * If the source map is not available, the original location will be the same as the current location. + * When the `--enable-source-maps` flag is enabled, for example when using `--experimental-transform-types`, + * `sourceMap` will be true by default. + * + * ```ts + * import { getCallSites } from 'node:util'; + * + * interface Foo { + * foo: string; + * } + * + * const callSites = getCallSites({ sourceMap: true }); + * + * // With sourceMap: + * // Function Name: '' + * // Script Name: example.js + * // Line Number: 7 + * // Column Number: 26 + * + * // Without sourceMap: + * // Function Name: '' + * // Script Name: example.js + * // Line Number: 2 + * // Column Number: 26 + * ``` + * @param frameCount Number of frames to capture as call site objects. + * **Default:** `10`. Allowable range is between 1 and 200. + * @return An array of call site objects + * @since v22.9.0 + */ + export function getCallSites(frameCount?: number, options?: GetCallSitesOptions): CallSiteObject[]; + export function getCallSites(options: GetCallSitesOptions): CallSiteObject[]; + /** + * Returns the string name for a numeric error code that comes from a Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const name = util.getSystemErrorName(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v9.7.0 + */ + export function getSystemErrorName(err: number): string; + /** + * Enable or disable printing a stack trace on `SIGINT`. The API is only available on the main thread. + * @since 22.19.0 + */ + export function setTraceSigInt(enable: boolean): void; + /** + * Returns a Map of all system error codes available from the Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const errorMap = util.getSystemErrorMap(); + * const name = errorMap.get(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v16.0.0, v14.17.0 + */ + export function getSystemErrorMap(): Map; + /** + * Returns the string message for a numeric error code that comes from a Node.js + * API. + * The mapping between error codes and string messages is platform-dependent. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const message = util.getSystemErrorMessage(err.errno); + * console.error(message); // no such file or directory + * }); + * ``` + * @since v22.12.0 + */ + export function getSystemErrorMessage(err: number): string; + /** + * The `util.log()` method prints the given `string` to `stdout` with an included + * timestamp. + * + * ```js + * import util from 'node:util'; + * + * util.log('Timestamped message.'); + * ``` + * @since v0.3.0 + * @deprecated Since v6.0.0 - Use a third party module instead. + */ + export function log(string: string): void; + /** + * Returns the `string` after replacing any surrogate code points + * (or equivalently, any unpaired surrogate code units) with the + * Unicode "replacement character" U+FFFD. + * @since v16.8.0, v14.18.0 + */ + export function toUSVString(string: string): string; + /** + * Creates and returns an `AbortController` instance whose `AbortSignal` is marked + * as transferable and can be used with `structuredClone()` or `postMessage()`. + * @since v18.11.0 + * @returns A transferable AbortController + */ + export function transferableAbortController(): AbortController; + /** + * Marks the given `AbortSignal` as transferable so that it can be used with`structuredClone()` and `postMessage()`. + * + * ```js + * const signal = transferableAbortSignal(AbortSignal.timeout(100)); + * const channel = new MessageChannel(); + * channel.port2.postMessage(signal, [signal]); + * ``` + * @since v18.11.0 + * @param signal The AbortSignal + * @returns The same AbortSignal + */ + export function transferableAbortSignal(signal: AbortSignal): AbortSignal; + /** + * Listens to abort event on the provided `signal` and returns a promise that resolves when the `signal` is aborted. + * If `resource` is provided, it weakly references the operation's associated object, + * so if `resource` is garbage collected before the `signal` aborts, + * then returned promise shall remain pending. + * This prevents memory leaks in long-running or non-cancelable operations. + * + * ```js + * import { aborted } from 'node:util'; + * + * // Obtain an object with an abortable signal, like a custom resource or operation. + * const dependent = obtainSomethingAbortable(); + * + * // Pass `dependent` as the resource, indicating the promise should only resolve + * // if `dependent` is still in memory when the signal is aborted. + * aborted(dependent.signal, dependent).then(() => { + * // This code runs when `dependent` is aborted. + * console.log('Dependent resource was aborted.'); + * }); + * + * // Simulate an event that triggers the abort. + * dependent.on('event', () => { + * dependent.abort(); // This will cause the `aborted` promise to resolve. + * }); + * ``` + * @since v19.7.0 + * @param resource Any non-null object tied to the abortable operation and held weakly. + * If `resource` is garbage collected before the `signal` aborts, the promise remains pending, + * allowing Node.js to stop tracking it. + * This helps prevent memory leaks in long-running or non-cancelable operations. + */ + export function aborted(signal: AbortSignal, resource: any): Promise; + /** + * The `util.inspect()` method returns a string representation of `object` that is + * intended for debugging. The output of `util.inspect` may change at any time + * and should not be depended upon programmatically. Additional `options` may be + * passed that alter the result. + * `util.inspect()` will use the constructor's name and/or `Symbol.toStringTag` + * property to make an identifiable tag for an inspected value. + * + * ```js + * class Foo { + * get [Symbol.toStringTag]() { + * return 'bar'; + * } + * } + * + * class Bar {} + * + * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); + * + * util.inspect(new Foo()); // 'Foo [bar] {}' + * util.inspect(new Bar()); // 'Bar {}' + * util.inspect(baz); // '[foo] {}' + * ``` + * + * Circular references point to their anchor by using a reference index: + * + * ```js + * import { inspect } from 'node:util'; + * + * const obj = {}; + * obj.a = [obj]; + * obj.b = {}; + * obj.b.inner = obj.b; + * obj.b.obj = obj; + * + * console.log(inspect(obj)); + * // { + * // a: [ [Circular *1] ], + * // b: { inner: [Circular *2], obj: [Circular *1] } + * // } + * ``` + * + * The following example inspects all properties of the `util` object: + * + * ```js + * import util from 'node:util'; + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * import { inspect } from 'node:util'; + * + * const o = { + * a: [1, 2, [[ + * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + + * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', + * 'test', + * 'foo']], 4], + * b: new Map([['za', 1], ['zb', 'test']]), + * }; + * console.log(inspect(o, { compact: true, depth: 5, breakLength: 80 })); + * + * // { a: + * // [ 1, + * // 2, + * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line + * // 'test', + * // 'foo' ] ], + * // 4 ], + * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } + * + * // Setting `compact` to false or an integer creates more reader friendly output. + * console.log(inspect(o, { compact: false, depth: 5, breakLength: 80 })); + * + * // { + * // a: [ + * // 1, + * // 2, + * // [ + * // [ + * // 'Lorem ipsum dolor sit amet,\n' + + * // 'consectetur adipiscing elit, sed do eiusmod \n' + + * // 'tempor incididunt ut labore et dolore magna aliqua.', + * // 'test', + * // 'foo' + * // ] + * // ], + * // 4 + * // ], + * // b: Map(2) { + * // 'za' => 1, + * // 'zb' => 'test' + * // } + * // } + * + * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a + * // single line. + * ``` + * + * The `showHidden` option allows `WeakMap` and `WeakSet` entries to be + * inspected. If there are more entries than `maxArrayLength`, there is no + * guarantee which entries are displayed. That means retrieving the same + * `WeakSet` entries twice may result in different output. Furthermore, entries + * with no remaining strong references may be garbage collected at any time. + * + * ```js + * import { inspect } from 'node:util'; + * + * const obj = { a: 1 }; + * const obj2 = { b: 2 }; + * const weakSet = new WeakSet([obj, obj2]); + * + * console.log(inspect(weakSet, { showHidden: true })); + * // WeakSet { { a: 1 }, { b: 2 } } + * ``` + * + * The `sorted` option ensures that an object's property insertion order does not + * impact the result of `util.inspect()`. + * + * ```js + * import { inspect } from 'node:util'; + * import assert from 'node:assert'; + * + * const o1 = { + * b: [2, 3, 1], + * a: '`a` comes before `b`', + * c: new Set([2, 3, 1]), + * }; + * console.log(inspect(o1, { sorted: true })); + * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } + * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); + * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } + * + * const o2 = { + * c: new Set([2, 1, 3]), + * a: '`a` comes before `b`', + * b: [2, 3, 1], + * }; + * assert.strict.equal( + * inspect(o1, { sorted: true }), + * inspect(o2, { sorted: true }), + * ); + * ``` + * + * The `numericSeparator` option adds an underscore every three digits to all + * numbers. + * + * ```js + * import { inspect } from 'node:util'; + * + * const thousand = 1000; + * const million = 1000000; + * const bigNumber = 123456789n; + * const bigDecimal = 1234.12345; + * + * console.log(inspect(thousand, { numericSeparator: true })); + * // 1_000 + * console.log(inspect(million, { numericSeparator: true })); + * // 1_000_000 + * console.log(inspect(bigNumber, { numericSeparator: true })); + * // 123_456_789n + * console.log(inspect(bigDecimal, { numericSeparator: true })); + * // 1_234.123_45 + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MiB. Inputs that result in longer output will + * be truncated. + * @since v0.3.0 + * @param object Any JavaScript primitive or `Object`. + * @return The representation of `object`. + */ + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options?: InspectOptions): string; + export namespace inspect { + let colors: NodeJS.Dict<[number, number]>; + let styles: { + [K in Style]: string; + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; + /** + * That can be used to declare custom inspect functions. + */ + const custom: unique symbol; + } + /** + * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). + * + * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isArray([]); + * // Returns: true + * util.isArray(new Array()); + * // Returns: true + * util.isArray({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use `isArray` instead. + */ + export function isArray(object: unknown): object is unknown[]; + /** + * Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isRegExp(/some regexp/); + * // Returns: true + * util.isRegExp(new RegExp('another regexp')); + * // Returns: true + * util.isRegExp({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Deprecated + */ + export function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isDate(new Date()); + * // Returns: true + * util.isDate(Date()); + * // false (without 'new' returns a String) + * util.isDate({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isDate} instead. + */ + export function isDate(object: unknown): object is Date; + /** + * Returns `true` if the given `object` is an `Error`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isError(new Error()); + * // Returns: true + * util.isError(new TypeError()); + * // Returns: true + * util.isError({ name: 'Error', message: 'an error occurred' }); + * // Returns: false + * ``` + * + * This method relies on `Object.prototype.toString()` behavior. It is + * possible to obtain an incorrect result when the `object` argument manipulates `@@toStringTag`. + * + * ```js + * import util from 'node:util'; + * const obj = { name: 'Error', message: 'an error occurred' }; + * + * util.isError(obj); + * // Returns: false + * obj[Symbol.toStringTag] = 'Error'; + * util.isError(obj); + * // Returns: true + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isNativeError} instead. + */ + export function isError(object: unknown): object is Error; + /** + * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and + * `extends` keywords to get language level inheritance support. Also note + * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). + * + * Inherit the prototype methods from one + * [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The + * prototype of `constructor` will be set to a new object created from + * `superConstructor`. + * + * This mainly adds some input validation on top of + * `Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. + * As an additional convenience, `superConstructor` will be accessible + * through the `constructor.super_` property. + * + * ```js + * const util = require('node:util'); + * const EventEmitter = require('node:events'); + * + * function MyStream() { + * EventEmitter.call(this); + * } + * + * util.inherits(MyStream, EventEmitter); + * + * MyStream.prototype.write = function(data) { + * this.emit('data', data); + * }; + * + * const stream = new MyStream(); + * + * console.log(stream instanceof EventEmitter); // true + * console.log(MyStream.super_ === EventEmitter); // true + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('It works!'); // Received data: "It works!" + * ``` + * + * ES6 example using `class` and `extends`: + * + * ```js + * import EventEmitter from 'node:events'; + * + * class MyStream extends EventEmitter { + * write(data) { + * this.emit('data', data); + * } + * } + * + * const stream = new MyStream(); + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('With ES6'); + * ``` + * @since v0.3.0 + * @legacy Use ES2015 class syntax and `extends` keyword instead. + */ + export function inherits(constructor: unknown, superConstructor: unknown): void; + export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; + export interface DebugLogger extends DebugLoggerFunction { + /** + * The `util.debuglog().enabled` getter is used to create a test that can be used + * in conditionals based on the existence of the `NODE_DEBUG` environment variable. + * If the `section` name appears within the value of that environment variable, + * then the returned value will be `true`. If not, then the returned value will be + * `false`. + * + * ```js + * import { debuglog } from 'node:util'; + * const enabled = debuglog('foo').enabled; + * if (enabled) { + * console.log('hello from foo [%d]', 123); + * } + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then it will + * output something like: + * + * ```console + * hello from foo [123] + * ``` + */ + enabled: boolean; + } + /** + * The `util.debuglog()` method is used to create a function that conditionally + * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG` + * environment variable. If the `section` name appears within the value of that + * environment variable, then the returned function operates similar to + * `console.error()`. If not, then the returned function is a no-op. + * + * ```js + * import { debuglog } from 'node:util'; + * const log = debuglog('foo'); + * + * log('hello from foo [%d]', 123); + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then + * it will output something like: + * + * ```console + * FOO 3245: hello from foo [123] + * ``` + * + * where `3245` is the process id. If it is not run with that + * environment variable set, then it will not print anything. + * + * The `section` supports wildcard also: + * + * ```js + * import { debuglog } from 'node:util'; + * const log = debuglog('foo'); + * + * log('hi there, it\'s foo-bar [%d]', 2333); + * ``` + * + * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output + * something like: + * + * ```console + * FOO-BAR 3257: hi there, it's foo-bar [2333] + * ``` + * + * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG` + * environment variable: `NODE_DEBUG=fs,net,tls`. + * + * The optional `callback` argument can be used to replace the logging function + * with a different function that doesn't have any initialization or + * unnecessary wrapping. + * + * ```js + * import { debuglog } from 'node:util'; + * let log = debuglog('internals', (debug) => { + * // Replace with a logging function that optimizes out + * // testing if the section is enabled + * log = debug; + * }); + * ``` + * @since v0.11.3 + * @param section A string identifying the portion of the application for which the `debuglog` function is being created. + * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function. + * @return The logging function + */ + export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; + export { debuglog as debug }; + /** + * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isBoolean(1); + * // Returns: false + * util.isBoolean(0); + * // Returns: false + * util.isBoolean(false); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'boolean'` instead. + */ + export function isBoolean(object: unknown): object is boolean; + /** + * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isBuffer({ length: 0 }); + * // Returns: false + * util.isBuffer([]); + * // Returns: false + * util.isBuffer(Buffer.from('hello world')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `isBuffer` instead. + */ + export function isBuffer(object: unknown): object is Buffer; + /** + * Returns `true` if the given `object` is a `Function`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * function Foo() {} + * const Bar = () => {}; + * + * util.isFunction({}); + * // Returns: false + * util.isFunction(Foo); + * // Returns: true + * util.isFunction(Bar); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'function'` instead. + */ + export function isFunction(object: unknown): boolean; + /** + * Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`. + * + * ```js + * import util from 'node:util'; + * + * util.isNull(0); + * // Returns: false + * util.isNull(undefined); + * // Returns: false + * util.isNull(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === null` instead. + */ + export function isNull(object: unknown): object is null; + /** + * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, + * returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isNullOrUndefined(0); + * // Returns: false + * util.isNullOrUndefined(undefined); + * // Returns: true + * util.isNullOrUndefined(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined || value === null` instead. + */ + export function isNullOrUndefined(object: unknown): object is null | undefined; + /** + * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isNumber(false); + * // Returns: false + * util.isNumber(Infinity); + * // Returns: true + * util.isNumber(0); + * // Returns: true + * util.isNumber(NaN); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'number'` instead. + */ + export function isNumber(object: unknown): object is number; + /** + * Returns `true` if the given `object` is strictly an `Object`**and** not a`Function` (even though functions are objects in JavaScript). + * Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isObject(5); + * // Returns: false + * util.isObject(null); + * // Returns: false + * util.isObject({}); + * // Returns: true + * util.isObject(() => {}); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value !== null && typeof value === 'object'` instead. + */ + export function isObject(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a primitive type. Otherwise, returns`false`. + * + * ```js + * import util from 'node:util'; + * + * util.isPrimitive(5); + * // Returns: true + * util.isPrimitive('foo'); + * // Returns: true + * util.isPrimitive(false); + * // Returns: true + * util.isPrimitive(null); + * // Returns: true + * util.isPrimitive(undefined); + * // Returns: true + * util.isPrimitive({}); + * // Returns: false + * util.isPrimitive(() => {}); + * // Returns: false + * util.isPrimitive(/^$/); + * // Returns: false + * util.isPrimitive(new Date()); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. + */ + export function isPrimitive(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isString(''); + * // Returns: true + * util.isString('foo'); + * // Returns: true + * util.isString(String('foo')); + * // Returns: true + * util.isString(5); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'string'` instead. + */ + export function isString(object: unknown): object is string; + /** + * Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isSymbol(5); + * // Returns: false + * util.isSymbol('foo'); + * // Returns: false + * util.isSymbol(Symbol('foo')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'symbol'` instead. + */ + export function isSymbol(object: unknown): object is symbol; + /** + * Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * const foo = undefined; + * util.isUndefined(5); + * // Returns: false + * util.isUndefined(foo); + * // Returns: true + * util.isUndefined(null); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined` instead. + */ + export function isUndefined(object: unknown): object is undefined; + /** + * The `util.deprecate()` method wraps `fn` (which may be a function or class) in + * such a way that it is marked as deprecated. + * + * ```js + * import { deprecate } from 'node:util'; + * + * export const obsoleteFunction = deprecate(() => { + * // Do something here. + * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); + * ``` + * + * When called, `util.deprecate()` will return a function that will emit a + * `DeprecationWarning` using the `'warning'` event. The warning will + * be emitted and printed to `stderr` the first time the returned function is + * called. After the warning is emitted, the wrapped function is called without + * emitting a warning. + * + * If the same optional `code` is supplied in multiple calls to `util.deprecate()`, + * the warning will be emitted only once for that `code`. + * + * ```js + * import { deprecate } from 'node:util'; + * + * const fn1 = deprecate( + * () => 'a value', + * 'deprecation message', + * 'DEP0001', + * ); + * const fn2 = deprecate( + * () => 'a different value', + * 'other dep message', + * 'DEP0001', + * ); + * fn1(); // Emits a deprecation warning with code DEP0001 + * fn2(); // Does not emit a deprecation warning because it has the same code + * ``` + * + * If either the `--no-deprecation` or `--no-warnings` command-line flags are + * used, or if the `process.noDeprecation` property is set to `true` _prior_ to + * the first deprecation warning, the `util.deprecate()` method does nothing. + * + * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, + * or the `process.traceDeprecation` property is set to `true`, a warning and a + * stack trace are printed to `stderr` the first time the deprecated function is + * called. + * + * If the `--throw-deprecation` command-line flag is set, or the + * `process.throwDeprecation` property is set to `true`, then an exception will be + * thrown when the deprecated function is called. + * + * The `--throw-deprecation` command-line flag and `process.throwDeprecation` + * property take precedence over `--trace-deprecation` and + * `process.traceDeprecation`. + * @since v0.8.0 + * @param fn The function that is being deprecated. + * @param msg A warning message to display when the deprecated function is invoked. + * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes. + * @return The deprecated function wrapped to emit a warning. + */ + export function deprecate(fn: T, msg: string, code?: string): T; + /** + * Returns `true` if there is deep strict equality between `val1` and `val2`. + * Otherwise, returns `false`. + * + * See `assert.deepStrictEqual()` for more information about deep strict + * equality. + * @since v9.0.0 + */ + export function isDeepStrictEqual(val1: unknown, val2: unknown): boolean; + /** + * Returns `str` with any ANSI escape codes removed. + * + * ```js + * console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); + * // Prints "value" + * ``` + * @since v16.11.0 + */ + export function stripVTControlCharacters(str: string): string; + /** + * Takes an `async` function (or a function that returns a `Promise`) and returns a + * function following the error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument. In the callback, the + * first argument will be the rejection reason (or `null` if the `Promise` + * resolved), and the second argument will be the resolved value. + * + * ```js + * import { callbackify } from 'node:util'; + * + * async function fn() { + * return 'hello world'; + * } + * const callbackFunction = callbackify(fn); + * + * callbackFunction((err, ret) => { + * if (err) throw err; + * console.log(ret); + * }); + * ``` + * + * Will print: + * + * ```text + * hello world + * ``` + * + * The callback is executed asynchronously, and will have a limited stack trace. + * If the callback throws, the process will emit an `'uncaughtException'` + * event, and if not handled will exit. + * + * Since `null` has a special meaning as the first argument to a callback, if a + * wrapped function rejects a `Promise` with a falsy value as a reason, the value + * is wrapped in an `Error` with the original value stored in a field named + * `reason`. + * + * ```js + * function fn() { + * return Promise.reject(null); + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * // When the Promise was rejected with `null` it is wrapped with an Error and + * // the original value is stored in `reason`. + * err && Object.hasOwn(err, 'reason') && err.reason === null; // true + * }); + * ``` + * @since v8.2.0 + * @param fn An `async` function + * @return a callback style function + */ + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: () => Promise, + ): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export interface CustomPromisifyLegacy extends Function { + __promisify__: TCustom; + } + export interface CustomPromisifySymbol extends Function { + [promisify.custom]: TCustom; + } + export type CustomPromisify = + | CustomPromisifySymbol + | CustomPromisifyLegacy; + /** + * Takes a function following the common error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument, and returns a version + * that returns promises. + * + * ```js + * import { promisify } from 'node:util'; + * import { stat } from 'node:fs'; + * + * const promisifiedStat = promisify(stat); + * promisifiedStat('.').then((stats) => { + * // Do something with `stats` + * }).catch((error) => { + * // Handle the error. + * }); + * ``` + * + * Or, equivalently using `async function`s: + * + * ```js + * import { promisify } from 'node:util'; + * import { stat } from 'node:fs'; + * + * const promisifiedStat = promisify(stat); + * + * async function callStat() { + * const stats = await promisifiedStat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * + * callStat(); + * ``` + * + * If there is an `original[util.promisify.custom]` property present, `promisify` + * will return its value, see [Custom promisified functions](https://nodejs.org/docs/latest-v22.x/api/util.html#custom-promisified-functions). + * + * `promisify()` assumes that `original` is a function taking a callback as its + * final argument in all cases. If `original` is not a function, `promisify()` + * will throw an error. If `original` is a function but its last argument is not + * an error-first callback, it will still be passed an error-first + * callback as its last argument. + * + * Using `promisify()` on class methods or other methods that use `this` may not + * work as expected unless handled specially: + * + * ```js + * import { promisify } from 'node:util'; + * + * class Foo { + * constructor() { + * this.a = 42; + * } + * + * bar(callback) { + * callback(null, this.a); + * } + * } + * + * const foo = new Foo(); + * + * const naiveBar = promisify(foo.bar); + * // TypeError: Cannot read properties of undefined (reading 'a') + * // naiveBar().then(a => console.log(a)); + * + * naiveBar.call(foo).then((a) => console.log(a)); // '42' + * + * const bindBar = naiveBar.bind(foo); + * bindBar().then((a) => console.log(a)); // '42' + * ``` + * @since v8.0.0 + */ + export function promisify(fn: CustomPromisify): TCustom; + export function promisify( + fn: (callback: (err: any, result: TResult) => void) => void, + ): () => Promise; + export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + export function promisify( + fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: Function): Function; + export namespace promisify { + /** + * That can be used to declare custom promisified variants of functions. + */ + const custom: unique symbol; + } + /** + * Stability: 1.1 - Active development + * Given an example `.env` file: + * + * ```js + * import { parseEnv } from 'node:util'; + * + * parseEnv('HELLO=world\nHELLO=oh my\n'); + * // Returns: { HELLO: 'oh my' } + * ``` + * @param content The raw contents of a `.env` file. + * @since v20.12.0 + */ + export function parseEnv(content: string): NodeJS.Dict; + // https://nodejs.org/docs/latest/api/util.html#foreground-colors + type ForegroundColors = + | "black" + | "blackBright" + | "blue" + | "blueBright" + | "cyan" + | "cyanBright" + | "gray" + | "green" + | "greenBright" + | "grey" + | "magenta" + | "magentaBright" + | "red" + | "redBright" + | "white" + | "whiteBright" + | "yellow" + | "yellowBright"; + // https://nodejs.org/docs/latest/api/util.html#background-colors + type BackgroundColors = + | "bgBlack" + | "bgBlackBright" + | "bgBlue" + | "bgBlueBright" + | "bgCyan" + | "bgCyanBright" + | "bgGray" + | "bgGreen" + | "bgGreenBright" + | "bgGrey" + | "bgMagenta" + | "bgMagentaBright" + | "bgRed" + | "bgRedBright" + | "bgWhite" + | "bgWhiteBright" + | "bgYellow" + | "bgYellowBright"; + // https://nodejs.org/docs/latest/api/util.html#modifiers + type Modifiers = + | "blink" + | "bold" + | "dim" + | "doubleunderline" + | "framed" + | "hidden" + | "inverse" + | "italic" + | "none" + | "overlined" + | "reset" + | "strikethrough" + | "underline"; + export interface StyleTextOptions { + /** + * When true, `stream` is checked to see if it can handle colors. + * @default true + */ + validateStream?: boolean | undefined; + /** + * A stream that will be validated if it can be colored. + * @default process.stdout + */ + stream?: NodeJS.WritableStream | undefined; + } + /** + * This function returns a formatted text considering the `format` passed + * for printing in a terminal. It is aware of the terminal's capabilities + * and acts according to the configuration set via `NO_COLOR`, + * `NODE_DISABLE_COLORS` and `FORCE_COLOR` environment variables. + * + * ```js + * import { styleText } from 'node:util'; + * import { stderr } from 'node:process'; + * + * const successMessage = styleText('green', 'Success!'); + * console.log(successMessage); + * + * const errorMessage = styleText( + * 'red', + * 'Error! Error!', + * // Validate if process.stderr has TTY + * { stream: stderr }, + * ); + * console.error(errorMessage); + * ``` + * + * `util.inspect.colors` also provides text formats such as `italic`, and + * `underline` and you can combine both: + * + * ```js + * console.log( + * util.styleText(['underline', 'italic'], 'My italic underlined message'), + * ); + * ``` + * + * When passing an array of formats, the order of the format applied + * is left to right so the following style might overwrite the previous one. + * + * ```js + * console.log( + * util.styleText(['red', 'green'], 'text'), // green + * ); + * ``` + * + * The special format value `none` applies no additional styling to the text. + * + * The full list of formats can be found in [modifiers](https://nodejs.org/docs/latest-v22.x/api/util.html#modifiers). + * @param format A text format or an Array of text formats defined in `util.inspect.colors`. + * @param text The text to to be formatted. + * @since v20.12.0 + */ + export function styleText( + format: + | ForegroundColors + | BackgroundColors + | Modifiers + | Array, + text: string, + options?: StyleTextOptions, + ): string; + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. + * + * ```js + * const decoder = new TextDecoder(); + * const u8arr = new Uint8Array([72, 101, 108, 108, 111]); + * console.log(decoder.decode(u8arr)); // Hello + * ``` + * @since v8.3.0 + */ + export class TextDecoder { + /** + * The encoding supported by the `TextDecoder` instance. + */ + readonly encoding: string; + /** + * The value will be `true` if decoding errors result in a `TypeError` being + * thrown. + */ + readonly fatal: boolean; + /** + * The value will be `true` if the decoding result will include the byte order + * mark. + */ + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { + fatal?: boolean | undefined; + ignoreBOM?: boolean | undefined; + }, + ); + /** + * Decodes the `input` and returns a string. If `options.stream` is `true`, any + * incomplete byte sequences occurring at the end of the `input` are buffered + * internally and emitted after the next call to `textDecoder.decode()`. + * + * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a `TypeError` being thrown. + * @param input An `ArrayBuffer`, `DataView`, or `TypedArray` instance containing the encoded data. + */ + decode( + input?: NodeJS.ArrayBufferView | ArrayBuffer | null, + options?: { + stream?: boolean | undefined; + }, + ): string; + } + export interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; + } + export { types }; + + //// TextEncoder/Decoder + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All + * instances of `TextEncoder` only support UTF-8 encoding. + * + * ```js + * const encoder = new TextEncoder(); + * const uint8array = encoder.encode('this is some data'); + * ``` + * + * The `TextEncoder` class is also available on the global object. + * @since v8.3.0 + */ + export class TextEncoder { + /** + * The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. + */ + readonly encoding: string; + /** + * UTF-8 encodes the `input` string and returns a `Uint8Array` containing the + * encoded bytes. + * @param [input='an empty string'] The text to encode. + */ + encode(input?: string): NodeJS.NonSharedUint8Array; + /** + * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object + * containing the read Unicode code units and written UTF-8 bytes. + * + * ```js + * const encoder = new TextEncoder(); + * const src = 'this is some data'; + * const dest = new Uint8Array(10); + * const { read, written } = encoder.encodeInto(src, dest); + * ``` + * @param src The text to encode. + * @param dest The array to hold the encode result. + */ + encodeInto(src: string, dest: Uint8Array): EncodeIntoResult; + } + import { TextDecoder as _TextDecoder, TextEncoder as _TextEncoder } from "util"; + global { + /** + * `TextDecoder` class is a global reference for `import { TextDecoder } from 'node:util'` + * https://nodejs.org/api/globals.html#textdecoder + * @since v11.0.0 + */ + var TextDecoder: typeof globalThis extends { + onmessage: any; + TextDecoder: infer TextDecoder; + } ? TextDecoder + : typeof _TextDecoder; + /** + * `TextEncoder` class is a global reference for `import { TextEncoder } from 'node:util'` + * https://nodejs.org/api/globals.html#textencoder + * @since v11.0.0 + */ + var TextEncoder: typeof globalThis extends { + onmessage: any; + TextEncoder: infer TextEncoder; + } ? TextEncoder + : typeof _TextEncoder; + } + + //// parseArgs + /** + * Provides a higher level API for command-line argument parsing than interacting + * with `process.argv` directly. Takes a specification for the expected arguments + * and returns a structured object with the parsed options and positionals. + * + * ```js + * import { parseArgs } from 'node:util'; + * const args = ['-f', '--bar', 'b']; + * const options = { + * foo: { + * type: 'boolean', + * short: 'f', + * }, + * bar: { + * type: 'string', + * }, + * }; + * const { + * values, + * positionals, + * } = parseArgs({ args, options }); + * console.log(values, positionals); + * // Prints: [Object: null prototype] { foo: true, bar: 'b' } [] + * ``` + * @since v18.3.0, v16.17.0 + * @param config Used to provide arguments for parsing and to configure the parser. `config` supports the following properties: + * @return The parsed command line arguments: + */ + export function parseArgs(config?: T): ParsedResults; + + /** + * Type of argument used in {@link parseArgs}. + */ + export type ParseArgsOptionsType = "boolean" | "string"; + + export interface ParseArgsOptionDescriptor { + /** + * Type of argument. + */ + type: ParseArgsOptionsType; + /** + * Whether this option can be provided multiple times. + * If `true`, all values will be collected in an array. + * If `false`, values for the option are last-wins. + * @default false. + */ + multiple?: boolean | undefined; + /** + * A single character alias for the option. + */ + short?: string | undefined; + /** + * The value to assign to + * the option if it does not appear in the arguments to be parsed. The value + * must match the type specified by the `type` property. If `multiple` is + * `true`, it must be an array. No default value is applied when the option + * does appear in the arguments to be parsed, even if the provided value + * is falsy. + * @since v18.11.0 + */ + default?: string | boolean | string[] | boolean[] | undefined; + } + export interface ParseArgsOptionsConfig { + [longOption: string]: ParseArgsOptionDescriptor; + } + export interface ParseArgsConfig { + /** + * Array of argument strings. + */ + args?: readonly string[] | undefined; + /** + * Used to describe arguments known to the parser. + */ + options?: ParseArgsOptionsConfig | undefined; + /** + * Should an error be thrown when unknown arguments are encountered, + * or when arguments are passed that do not match the `type` configured in `options`. + * @default true + */ + strict?: boolean | undefined; + /** + * Whether this command accepts positional arguments. + */ + allowPositionals?: boolean | undefined; + /** + * If `true`, allows explicitly setting boolean options to `false` by prefixing the option name with `--no-`. + * @default false + * @since v22.4.0 + */ + allowNegative?: boolean | undefined; + /** + * Return the parsed tokens. This is useful for extending the built-in behavior, + * from adding additional checks through to reprocessing the tokens in different ways. + * @default false + */ + tokens?: boolean | undefined; + } + /* + IfDefaultsTrue and IfDefaultsFalse are helpers to handle default values for missing boolean properties. + TypeScript does not have exact types for objects: https://github.com/microsoft/TypeScript/issues/12936 + This means it is impossible to distinguish between "field X is definitely not present" and "field X may or may not be present". + But we expect users to generally provide their config inline or `as const`, which means TS will always know whether a given field is present. + So this helper treats "not definitely present" (i.e., not `extends boolean`) as being "definitely not present", i.e. it should have its default value. + This is technically incorrect but is a much nicer UX for the common case. + The IfDefaultsTrue version is for things which default to true; the IfDefaultsFalse version is for things which default to false. + */ + type IfDefaultsTrue = T extends true ? IfTrue + : T extends false ? IfFalse + : IfTrue; + + // we put the `extends false` condition first here because `undefined` compares like `any` when `strictNullChecks: false` + type IfDefaultsFalse = T extends false ? IfFalse + : T extends true ? IfTrue + : IfFalse; + + type ExtractOptionValue = IfDefaultsTrue< + T["strict"], + O["type"] extends "string" ? string : O["type"] extends "boolean" ? boolean : string | boolean, + string | boolean + >; + + type ApplyOptionalModifiers> = ( + & { -readonly [LongOption in keyof O]?: V[LongOption] } + & { [LongOption in keyof O as O[LongOption]["default"] extends {} ? LongOption : never]: V[LongOption] } + ) extends infer P ? { [K in keyof P]: P[K] } : never; // resolve intersection to object + + type ParsedValues = + & IfDefaultsTrue + & (T["options"] extends ParseArgsOptionsConfig ? ApplyOptionalModifiers< + T["options"], + { + [LongOption in keyof T["options"]]: IfDefaultsFalse< + T["options"][LongOption]["multiple"], + Array>, + ExtractOptionValue + >; + } + > + : {}); + + type ParsedPositionals = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type PreciseTokenForOptions< + K extends string, + O extends ParseArgsOptionDescriptor, + > = O["type"] extends "string" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: string; + inlineValue: boolean; + } + : O["type"] extends "boolean" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: undefined; + inlineValue: undefined; + } + : OptionToken & { name: K }; + + type TokenForOptions< + T extends ParseArgsConfig, + K extends keyof T["options"] = keyof T["options"], + > = K extends unknown + ? T["options"] extends ParseArgsOptionsConfig ? PreciseTokenForOptions + : OptionToken + : never; + + type ParsedOptionToken = IfDefaultsTrue, OptionToken>; + + type ParsedPositionalToken = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type ParsedTokens = Array< + ParsedOptionToken | ParsedPositionalToken | { kind: "option-terminator"; index: number } + >; + + type PreciseParsedResults = IfDefaultsFalse< + T["tokens"], + { + values: ParsedValues; + positionals: ParsedPositionals; + tokens: ParsedTokens; + }, + { + values: ParsedValues; + positionals: ParsedPositionals; + } + >; + + type OptionToken = + | { kind: "option"; index: number; name: string; rawName: string; value: string; inlineValue: boolean } + | { + kind: "option"; + index: number; + name: string; + rawName: string; + value: undefined; + inlineValue: undefined; + }; + + type Token = + | OptionToken + | { kind: "positional"; index: number; value: string } + | { kind: "option-terminator"; index: number }; + + // If ParseArgsConfig extends T, then the user passed config constructed elsewhere. + // So we can't rely on the `"not definitely present" implies "definitely not present"` assumption mentioned above. + type ParsedResults = ParseArgsConfig extends T ? { + values: { + [longOption: string]: undefined | string | boolean | Array; + }; + positionals: string[]; + tokens?: Token[]; + } + : PreciseParsedResults; + + /** + * An implementation of [the MIMEType class](https://bmeck.github.io/node-proposal-mime-api/). + * + * In accordance with browser conventions, all properties of `MIMEType` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. + * + * A MIME string is a structured string containing multiple meaningful + * components. When parsed, a `MIMEType` object is returned containing + * properties for each of these components. + * @since v19.1.0, v18.13.0 + */ + export class MIMEType { + /** + * Creates a new MIMEType object by parsing the input. + * + * A `TypeError` will be thrown if the `input` is not a valid MIME. + * Note that an effort will be made to coerce the given values into strings. + * @param input The input MIME to parse. + */ + constructor(input: string | { toString: () => string }); + + /** + * Gets and sets the type portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript'); + * console.log(myMIME.type); + * // Prints: text + * myMIME.type = 'application'; + * console.log(myMIME.type); + * // Prints: application + * console.log(String(myMIME)); + * // Prints: application/javascript + * ``` + */ + type: string; + /** + * Gets and sets the subtype portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/ecmascript'); + * console.log(myMIME.subtype); + * // Prints: ecmascript + * myMIME.subtype = 'javascript'; + * console.log(myMIME.subtype); + * // Prints: javascript + * console.log(String(myMIME)); + * // Prints: text/javascript + * ``` + */ + subtype: string; + /** + * Gets the essence of the MIME. This property is read only. + * Use `mime.type` or `mime.subtype` to alter the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript;key=value'); + * console.log(myMIME.essence); + * // Prints: text/javascript + * myMIME.type = 'application'; + * console.log(myMIME.essence); + * // Prints: application/javascript + * console.log(String(myMIME)); + * // Prints: application/javascript;key=value + * ``` + */ + readonly essence: string; + /** + * Gets the `MIMEParams` object representing the + * parameters of the MIME. This property is read-only. See `MIMEParams` documentation for details. + */ + readonly params: MIMEParams; + /** + * The `toString()` method on the `MIMEType` object returns the serialized MIME. + * + * Because of the need for standard compliance, this method does not allow users + * to customize the serialization process of the MIME. + */ + toString(): string; + } + /** + * The `MIMEParams` API provides read and write access to the parameters of a `MIMEType`. + * @since v19.1.0, v18.13.0 + */ + export class MIMEParams { + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: string): void; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + * Each item of the iterator is a JavaScript `Array`. The first item of the array + * is the `name`, the second item of the array is the `value`. + */ + entries(): NodeJS.Iterator<[name: string, value: string]>; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: string): boolean; + /** + * Returns an iterator over the names of each name-value pair. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // bar + * ``` + */ + keys(): NodeJS.Iterator; + /** + * Sets the value in the `MIMEParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value`. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * params.set('foo', 'def'); + * params.set('baz', 'xyz'); + * console.log(params.toString()); + * // Prints: foo=def;bar=1;baz=xyz + * ``` + */ + set(name: string, value: string): void; + /** + * Returns an iterator over the values of each name-value pair. + */ + values(): NodeJS.Iterator; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + */ + [Symbol.iterator](): NodeJS.Iterator<[name: string, value: string]>; + } +} +declare module "util/types" { + import { KeyObject, webcrypto } from "node:crypto"; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or + * [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * + * See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`. + * + * ```js + * util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isAnyArrayBuffer(object: unknown): object is ArrayBufferLike; + /** + * Returns `true` if the value is an `arguments` object. + * + * ```js + * function foo() { + * util.types.isArgumentsObject(arguments); // Returns true + * } + * ``` + * @since v10.0.0 + */ + function isArgumentsObject(object: unknown): object is IArguments; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance. + * This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false + * ``` + * @since v10.0.0 + */ + function isArrayBuffer(object: unknown): object is ArrayBuffer; + /** + * Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) views, such as typed + * array objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent to + * [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * + * ```js + * util.types.isArrayBufferView(new Int8Array()); // true + * util.types.isArrayBufferView(Buffer.from('hello world')); // true + * util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true + * util.types.isArrayBufferView(new ArrayBuffer()); // false + * ``` + * @since v10.0.0 + */ + function isArrayBufferView(object: unknown): object is NodeJS.ArrayBufferView; + /** + * Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isAsyncFunction(function foo() {}); // Returns false + * util.types.isAsyncFunction(async function foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isAsyncFunction(object: unknown): boolean; + /** + * Returns `true` if the value is a `BigInt64Array` instance. + * + * ```js + * util.types.isBigInt64Array(new BigInt64Array()); // Returns true + * util.types.isBigInt64Array(new BigUint64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isBigInt64Array(value: unknown): value is BigInt64Array; + /** + * Returns `true` if the value is a BigInt object, e.g. created + * by `Object(BigInt(123))`. + * + * ```js + * util.types.isBigIntObject(Object(BigInt(123))); // Returns true + * util.types.isBigIntObject(BigInt(123)); // Returns false + * util.types.isBigIntObject(123); // Returns false + * ``` + * @since v10.4.0 + */ + function isBigIntObject(object: unknown): object is BigInt; + /** + * Returns `true` if the value is a `BigUint64Array` instance. + * + * ```js + * util.types.isBigUint64Array(new BigInt64Array()); // Returns false + * util.types.isBigUint64Array(new BigUint64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isBigUint64Array(value: unknown): value is BigUint64Array; + /** + * Returns `true` if the value is a boolean object, e.g. created + * by `new Boolean()`. + * + * ```js + * util.types.isBooleanObject(false); // Returns false + * util.types.isBooleanObject(true); // Returns false + * util.types.isBooleanObject(new Boolean(false)); // Returns true + * util.types.isBooleanObject(new Boolean(true)); // Returns true + * util.types.isBooleanObject(Boolean(false)); // Returns false + * util.types.isBooleanObject(Boolean(true)); // Returns false + * ``` + * @since v10.0.0 + */ + function isBooleanObject(object: unknown): object is Boolean; + /** + * Returns `true` if the value is any boxed primitive object, e.g. created + * by `new Boolean()`, `new String()` or `Object(Symbol())`. + * + * For example: + * + * ```js + * util.types.isBoxedPrimitive(false); // Returns false + * util.types.isBoxedPrimitive(new Boolean(false)); // Returns true + * util.types.isBoxedPrimitive(Symbol('foo')); // Returns false + * util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true + * util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true + * ``` + * @since v10.11.0 + */ + function isBoxedPrimitive(object: unknown): object is String | Number | BigInt | Boolean | Symbol; + /** + * Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance. + * + * ```js + * const ab = new ArrayBuffer(20); + * util.types.isDataView(new DataView(ab)); // Returns true + * util.types.isDataView(new Float64Array()); // Returns false + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isDataView(object: unknown): object is DataView; + /** + * Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance. + * + * ```js + * util.types.isDate(new Date()); // Returns true + * ``` + * @since v10.0.0 + */ + function isDate(object: unknown): object is Date; + /** + * Returns `true` if the value is a native `External` value. + * + * A native `External` value is a special type of object that contains a + * raw C++ pointer (`void*`) for access from native code, and has no other + * properties. Such objects are created either by Node.js internals or native + * addons. In JavaScript, they are + * [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a + * `null` prototype. + * + * ```c + * #include + * #include + * napi_value result; + * static napi_value MyNapi(napi_env env, napi_callback_info info) { + * int* raw = (int*) malloc(1024); + * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); + * if (status != napi_ok) { + * napi_throw_error(env, NULL, "napi_create_external failed"); + * return NULL; + * } + * return result; + * } + * ... + * DECLARE_NAPI_PROPERTY("myNapi", MyNapi) + * ... + * ``` + * + * ```js + * import native from 'napi_addon.node'; + * import { types } from 'node:util'; + * + * const data = native.myNapi(); + * types.isExternal(data); // returns true + * types.isExternal(0); // returns false + * types.isExternal(new String('foo')); // returns false + * ``` + * + * For further information on `napi_create_external`, refer to + * [`napi_create_external()`](https://nodejs.org/docs/latest-v22.x/api/n-api.html#napi_create_external). + * @since v10.0.0 + */ + function isExternal(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in `Float16Array` instance. + * + * ```js + * util.types.isFloat16Array(new ArrayBuffer()); // Returns false + * util.types.isFloat16Array(new Float16Array()); // Returns true + * util.types.isFloat16Array(new Float32Array()); // Returns false + * ``` + * @since v22.16.0 + */ + // This does NOT return a type predicate in v22.x. + // The Float16Array feature does not yet exist in this version of Node.js. + function isFloat16Array(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance. + * + * ```js + * util.types.isFloat32Array(new ArrayBuffer()); // Returns false + * util.types.isFloat32Array(new Float32Array()); // Returns true + * util.types.isFloat32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isFloat32Array(object: unknown): object is Float32Array; + /** + * Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance. + * + * ```js + * util.types.isFloat64Array(new ArrayBuffer()); // Returns false + * util.types.isFloat64Array(new Uint8Array()); // Returns false + * util.types.isFloat64Array(new Float64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isFloat64Array(object: unknown): object is Float64Array; + /** + * Returns `true` if the value is a generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isGeneratorFunction(function foo() {}); // Returns false + * util.types.isGeneratorFunction(function* foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorFunction(object: unknown): object is GeneratorFunction; + /** + * Returns `true` if the value is a generator object as returned from a + * built-in generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * function* foo() {} + * const generator = foo(); + * util.types.isGeneratorObject(generator); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorObject(object: unknown): object is Generator; + /** + * Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance. + * + * ```js + * util.types.isInt8Array(new ArrayBuffer()); // Returns false + * util.types.isInt8Array(new Int8Array()); // Returns true + * util.types.isInt8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt8Array(object: unknown): object is Int8Array; + /** + * Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance. + * + * ```js + * util.types.isInt16Array(new ArrayBuffer()); // Returns false + * util.types.isInt16Array(new Int16Array()); // Returns true + * util.types.isInt16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt16Array(object: unknown): object is Int16Array; + /** + * Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance. + * + * ```js + * util.types.isInt32Array(new ArrayBuffer()); // Returns false + * util.types.isInt32Array(new Int32Array()); // Returns true + * util.types.isInt32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt32Array(object: unknown): object is Int32Array; + /** + * Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * util.types.isMap(new Map()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMap( + object: T | {}, + ): object is T extends ReadonlyMap ? (unknown extends T ? never : ReadonlyMap) + : Map; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * const map = new Map(); + * util.types.isMapIterator(map.keys()); // Returns true + * util.types.isMapIterator(map.values()); // Returns true + * util.types.isMapIterator(map.entries()); // Returns true + * util.types.isMapIterator(map[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMapIterator(object: unknown): boolean; + /** + * Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects). + * + * ```js + * import * as ns from './a.js'; + * + * util.types.isModuleNamespaceObject(ns); // Returns true + * ``` + * @since v10.0.0 + */ + function isModuleNamespaceObject(value: unknown): boolean; + /** + * Returns `true` if the value was returned by the constructor of a + * [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects). + * + * ```js + * console.log(util.types.isNativeError(new Error())); // true + * console.log(util.types.isNativeError(new TypeError())); // true + * console.log(util.types.isNativeError(new RangeError())); // true + * ``` + * + * Subclasses of the native error types are also native errors: + * + * ```js + * class MyError extends Error {} + * console.log(util.types.isNativeError(new MyError())); // true + * ``` + * + * A value being `instanceof` a native error class is not equivalent to `isNativeError()` + * returning `true` for that value. `isNativeError()` returns `true` for errors + * which come from a different [realm](https://tc39.es/ecma262/#realm) while `instanceof Error` returns `false` + * for these errors: + * + * ```js + * import { createContext, runInContext } from 'node:vm'; + * import { types } from 'node:util'; + * + * const context = createContext({}); + * const myError = runInContext('new Error()', context); + * console.log(types.isNativeError(myError)); // true + * console.log(myError instanceof Error); // false + * ``` + * + * Conversely, `isNativeError()` returns `false` for all objects which were not + * returned by the constructor of a native error. That includes values + * which are `instanceof` native errors: + * + * ```js + * const myError = { __proto__: Error.prototype }; + * console.log(util.types.isNativeError(myError)); // false + * console.log(myError instanceof Error); // true + * ``` + * @since v10.0.0 + */ + function isNativeError(object: unknown): object is Error; + /** + * Returns `true` if the value is a number object, e.g. created + * by `new Number()`. + * + * ```js + * util.types.isNumberObject(0); // Returns false + * util.types.isNumberObject(new Number(0)); // Returns true + * ``` + * @since v10.0.0 + */ + function isNumberObject(object: unknown): object is Number; + /** + * Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * + * ```js + * util.types.isPromise(Promise.resolve(42)); // Returns true + * ``` + * @since v10.0.0 + */ + function isPromise(object: unknown): object is Promise; + /** + * Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance. + * + * ```js + * const target = {}; + * const proxy = new Proxy(target, {}); + * util.types.isProxy(target); // Returns false + * util.types.isProxy(proxy); // Returns true + * ``` + * @since v10.0.0 + */ + function isProxy(object: unknown): boolean; + /** + * Returns `true` if the value is a regular expression object. + * + * ```js + * util.types.isRegExp(/abc/); // Returns true + * util.types.isRegExp(new RegExp('abc')); // Returns true + * ``` + * @since v10.0.0 + */ + function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * util.types.isSet(new Set()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSet( + object: T | {}, + ): object is T extends ReadonlySet ? (unknown extends T ? never : ReadonlySet) : Set; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * const set = new Set(); + * util.types.isSetIterator(set.keys()); // Returns true + * util.types.isSetIterator(set.values()); // Returns true + * util.types.isSetIterator(set.entries()); // Returns true + * util.types.isSetIterator(set[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSetIterator(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * This does _not_ include [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false + * util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSharedArrayBuffer(object: unknown): object is SharedArrayBuffer; + /** + * Returns `true` if the value is a string object, e.g. created + * by `new String()`. + * + * ```js + * util.types.isStringObject('foo'); // Returns false + * util.types.isStringObject(new String('foo')); // Returns true + * ``` + * @since v10.0.0 + */ + function isStringObject(object: unknown): object is String; + /** + * Returns `true` if the value is a symbol object, created + * by calling `Object()` on a `Symbol` primitive. + * + * ```js + * const symbol = Symbol('foo'); + * util.types.isSymbolObject(symbol); // Returns false + * util.types.isSymbolObject(Object(symbol)); // Returns true + * ``` + * @since v10.0.0 + */ + function isSymbolObject(object: unknown): object is Symbol; + /** + * Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance. + * + * ```js + * util.types.isTypedArray(new ArrayBuffer()); // Returns false + * util.types.isTypedArray(new Uint8Array()); // Returns true + * util.types.isTypedArray(new Float64Array()); // Returns true + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isTypedArray(object: unknown): object is NodeJS.TypedArray; + /** + * Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance. + * + * ```js + * util.types.isUint8Array(new ArrayBuffer()); // Returns false + * util.types.isUint8Array(new Uint8Array()); // Returns true + * util.types.isUint8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8Array(object: unknown): object is Uint8Array; + /** + * Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance. + * + * ```js + * util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false + * util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true + * util.types.isUint8ClampedArray(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8ClampedArray(object: unknown): object is Uint8ClampedArray; + /** + * Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance. + * + * ```js + * util.types.isUint16Array(new ArrayBuffer()); // Returns false + * util.types.isUint16Array(new Uint16Array()); // Returns true + * util.types.isUint16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint16Array(object: unknown): object is Uint16Array; + /** + * Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance. + * + * ```js + * util.types.isUint32Array(new ArrayBuffer()); // Returns false + * util.types.isUint32Array(new Uint32Array()); // Returns true + * util.types.isUint32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint32Array(object: unknown): object is Uint32Array; + /** + * Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance. + * + * ```js + * util.types.isWeakMap(new WeakMap()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakMap(object: unknown): object is WeakMap; + /** + * Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance. + * + * ```js + * util.types.isWeakSet(new WeakSet()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakSet(object: unknown): object is WeakSet; + /** + * Returns `true` if `value` is a `KeyObject`, `false` otherwise. + * @since v16.2.0 + */ + function isKeyObject(object: unknown): object is KeyObject; + /** + * Returns `true` if `value` is a `CryptoKey`, `false` otherwise. + * @since v16.2.0 + */ + function isCryptoKey(object: unknown): object is webcrypto.CryptoKey; +} +declare module "node:util" { + export * from "util"; +} +declare module "node:util/types" { + export * from "util/types"; +} diff --git a/node_modules/@types/node/v8.d.ts b/node_modules/@types/node/v8.d.ts new file mode 100644 index 0000000..34006cd --- /dev/null +++ b/node_modules/@types/node/v8.d.ts @@ -0,0 +1,920 @@ +/** + * The `node:v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: + * + * ```js + * import v8 from 'node:v8'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/v8.js) + */ +declare module "v8" { + import { NonSharedBuffer } from "node:buffer"; + import { Readable } from "node:stream"; + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + number_of_native_contexts: number; + number_of_detached_contexts: number; + total_global_handles_size: number; + used_global_handles_size: number; + external_memory: number; + } + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + interface HeapSnapshotOptions { + /** + * If true, expose internals in the heap snapshot. + * @default false + */ + exposeInternals?: boolean | undefined; + /** + * If true, expose numeric values in artificial fields. + * @default false + */ + exposeNumericValues?: boolean | undefined; + } + /** + * Returns an integer representing a version tag derived from the V8 version, + * command-line flags, and detected CPU features. This is useful for determining + * whether a `vm.Script` `cachedData` buffer is compatible with this instance + * of V8. + * + * ```js + * console.log(v8.cachedDataVersionTag()); // 3947234607 + * // The value returned by v8.cachedDataVersionTag() is derived from the V8 + * // version, command-line flags, and detected CPU features. Test that the value + * // does indeed update when flags are toggled. + * v8.setFlagsFromString('--allow_natives_syntax'); + * console.log(v8.cachedDataVersionTag()); // 183726201 + * ``` + * @since v8.0.0 + */ + function cachedDataVersionTag(): number; + /** + * Returns an object with the following properties: + * + * `does_zap_garbage` is a 0/1 boolean, which signifies whether the `--zap_code_space` option is enabled or not. This makes V8 overwrite heap + * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger + * because it continuously touches all heap pages and that makes them less likely + * to get swapped out by the operating system. + * + * `number_of_native_contexts` The value of native\_context is the number of the + * top-level contexts currently active. Increase of this number over time indicates + * a memory leak. + * + * `number_of_detached_contexts` The value of detached\_context is the number + * of contexts that were detached and not yet garbage collected. This number + * being non-zero indicates a potential memory leak. + * + * `total_global_handles_size` The value of total\_global\_handles\_size is the + * total memory size of V8 global handles. + * + * `used_global_handles_size` The value of used\_global\_handles\_size is the + * used memory size of V8 global handles. + * + * `external_memory` The value of external\_memory is the memory size of array + * buffers and external strings. + * + * ```js + * { + * total_heap_size: 7326976, + * total_heap_size_executable: 4194304, + * total_physical_size: 7326976, + * total_available_size: 1152656, + * used_heap_size: 3476208, + * heap_size_limit: 1535115264, + * malloced_memory: 16384, + * peak_malloced_memory: 1127496, + * does_zap_garbage: 0, + * number_of_native_contexts: 1, + * number_of_detached_contexts: 0, + * total_global_handles_size: 8192, + * used_global_handles_size: 3296, + * external_memory: 318824 + * } + * ``` + * @since v1.0.0 + */ + function getHeapStatistics(): HeapInfo; + /** + * It returns an object with a structure similar to the + * [`cppgc::HeapStatistics`](https://v8docs.nodesource.com/node-22.4/d7/d51/heap-statistics_8h_source.html) + * object. See the [V8 documentation](https://v8docs.nodesource.com/node-22.4/df/d2f/structcppgc_1_1_heap_statistics.html) + * for more information about the properties of the object. + * + * ```js + * // Detailed + * ({ + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 152, + * space_statistics: [ + * { + * name: 'NormalPageSpace0', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace1', + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 152, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace2', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace3', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'LargePageSpace', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * ], + * type_names: [], + * detail_level: 'detailed', + * }); + * ``` + * + * ```js + * // Brief + * ({ + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 128864, + * space_statistics: [], + * type_names: [], + * detail_level: 'brief', + * }); + * ``` + * @since v22.15.0 + * @param detailLevel **Default:** `'detailed'`. Specifies the level of detail in the returned statistics. + * Accepted values are: + * * `'brief'`: Brief statistics contain only the top-level + * allocated and used + * memory statistics for the entire heap. + * * `'detailed'`: Detailed statistics also contain a break + * down per space and page, as well as freelist statistics + * and object type histograms. + */ + function getCppHeapStatistics(detailLevel?: "brief" | "detailed"): object; + /** + * Returns statistics about the V8 heap spaces, i.e. the segments which make up + * the V8 heap. Neither the ordering of heap spaces, nor the availability of a + * heap space can be guaranteed as the statistics are provided via the + * V8 [`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the + * next. + * + * The value returned is an array of objects containing the following properties: + * + * ```json + * [ + * { + * "space_name": "new_space", + * "space_size": 2063872, + * "space_used_size": 951112, + * "space_available_size": 80824, + * "physical_space_size": 2063872 + * }, + * { + * "space_name": "old_space", + * "space_size": 3090560, + * "space_used_size": 2493792, + * "space_available_size": 0, + * "physical_space_size": 3090560 + * }, + * { + * "space_name": "code_space", + * "space_size": 1260160, + * "space_used_size": 644256, + * "space_available_size": 960, + * "physical_space_size": 1260160 + * }, + * { + * "space_name": "map_space", + * "space_size": 1094160, + * "space_used_size": 201608, + * "space_available_size": 0, + * "physical_space_size": 1094160 + * }, + * { + * "space_name": "large_object_space", + * "space_size": 0, + * "space_used_size": 0, + * "space_available_size": 1490980608, + * "physical_space_size": 0 + * } + * ] + * ``` + * @since v6.0.0 + */ + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + /** + * The `v8.setFlagsFromString()` method can be used to programmatically set + * V8 command-line flags. This method should be used with care. Changing settings + * after the VM has started may result in unpredictable behavior, including + * crashes and data loss; or it may simply do nothing. + * + * The V8 options available for a version of Node.js may be determined by running `node --v8-options`. + * + * Usage: + * + * ```js + * // Print GC events to stdout for one minute. + * import v8 from 'node:v8'; + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ + function setFlagsFromString(flags: string): void; + /** + * This is similar to the [`queryObjects()` console API](https://developer.chrome.com/docs/devtools/console/utilities#queryObjects-function) + * provided by the Chromium DevTools console. It can be used to search for objects that have the matching constructor on its prototype chain + * in the heap after a full garbage collection, which can be useful for memory leak regression tests. To avoid surprising results, users should + * avoid using this API on constructors whose implementation they don't control, or on constructors that can be invoked by other parties in the + * application. + * + * To avoid accidental leaks, this API does not return raw references to the objects found. By default, it returns the count of the objects + * found. If `options.format` is `'summary'`, it returns an array containing brief string representations for each object. The visibility provided + * in this API is similar to what the heap snapshot provides, while users can save the cost of serialization and parsing and directly filter the + * target objects during the search. + * + * Only objects created in the current execution context are included in the results. + * + * ```js + * import { queryObjects } from 'node:v8'; + * class A { foo = 'bar'; } + * console.log(queryObjects(A)); // 0 + * const a = new A(); + * console.log(queryObjects(A)); // 1 + * // [ "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * + * class B extends A { bar = 'qux'; } + * const b = new B(); + * console.log(queryObjects(B)); // 1 + * // [ "B { foo: 'bar', bar: 'qux' }" ] + * console.log(queryObjects(B, { format: 'summary' })); + * + * // Note that, when there are child classes inheriting from a constructor, + * // the constructor also shows up in the prototype chain of the child + * // classes's prototoype, so the child classes's prototoype would also be + * // included in the result. + * console.log(queryObjects(A)); // 3 + * // [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * ``` + * @param ctor The constructor that can be used to search on the prototype chain in order to filter target objects in the heap. + * @since v20.13.0 + * @experimental + */ + function queryObjects(ctor: Function): number | string[]; + function queryObjects(ctor: Function, options: { format: "count" }): number; + function queryObjects(ctor: Function, options: { format: "summary" }): string[]; + /** + * Generates a snapshot of the current V8 heap and returns a Readable + * Stream that may be used to read the JSON serialized representation. + * This JSON stream format is intended to be used with tools such as + * Chrome DevTools. The JSON schema is undocumented and specific to the + * V8 engine. Therefore, the schema may change from one version of V8 to the next. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * // Print heap snapshot to the console + * import v8 from 'node:v8'; + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable containing the V8 heap snapshot. + */ + function getHeapSnapshot(options?: HeapSnapshotOptions): Readable; + /** + * Generates a snapshot of the current V8 heap and writes it to a JSON + * file. This file is intended to be used with tools such as Chrome + * DevTools. The JSON schema is undocumented and specific to the V8 + * engine, and may change from one version of V8 to the next. + * + * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will + * not contain any information about the workers, and vice versa. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * import { writeHeapSnapshot } from 'node:v8'; + * import { + * Worker, + * isMainThread, + * parentPort, + * } from 'node:worker_threads'; + * + * if (isMainThread) { + * const worker = new Worker(__filename); + * + * worker.once('message', (filename) => { + * console.log(`worker heapdump: ${filename}`); + * // Now get a heapdump for the main thread. + * console.log(`main thread heapdump: ${writeHeapSnapshot()}`); + * }); + * + * // Tell the worker to create a heapdump. + * worker.postMessage('heapdump'); + * } else { + * parentPort.once('message', (message) => { + * if (message === 'heapdump') { + * // Generate a heapdump for the worker + * // and return the filename to the parent. + * parentPort.postMessage(writeHeapSnapshot()); + * } + * }); + * } + * ``` + * @since v11.13.0 + * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be + * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a + * worker thread. + * @return The filename where the snapshot was saved. + */ + function writeHeapSnapshot(filename?: string, options?: HeapSnapshotOptions): string; + /** + * Get statistics about code and its metadata in the heap, see + * V8 [`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the + * following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794, + * cpu_profiler_metadata_size: 0, + * } + * ``` + * @since v12.8.0 + */ + function getHeapCodeStatistics(): HeapCodeStatistics; + /** + * V8 only supports `Latin-1/ISO-8859-1` and `UTF16` as the underlying representation of a string. + * If the `content` uses `Latin-1/ISO-8859-1` as the underlying representation, this function will return true; + * otherwise, it returns false. + * + * If this method returns false, that does not mean that the string contains some characters not in `Latin-1/ISO-8859-1`. + * Sometimes a `Latin-1` string may also be represented as `UTF16`. + * + * ```js + * const { isStringOneByteRepresentation } = require('node:v8'); + * + * const Encoding = { + * latin1: 1, + * utf16le: 2, + * }; + * const buffer = Buffer.alloc(100); + * function writeString(input) { + * if (isStringOneByteRepresentation(input)) { + * buffer.writeUint8(Encoding.latin1); + * buffer.writeUint32LE(input.length, 1); + * buffer.write(input, 5, 'latin1'); + * } else { + * buffer.writeUint8(Encoding.utf16le); + * buffer.writeUint32LE(input.length * 2, 1); + * buffer.write(input, 5, 'utf16le'); + * } + * } + * writeString('hello'); + * writeString('你好'); + * ``` + * @since v22.15.0 + */ + function isStringOneByteRepresentation(content: string): boolean; + /** + * @since v8.0.0 + */ + class Serializer { + /** + * Writes out a header, which includes the serialization format version. + */ + writeHeader(): void; + /** + * Serializes a JavaScript value and adds the serialized representation to the + * internal buffer. + * + * This throws an error if `value` cannot be serialized. + */ + writeValue(val: any): boolean; + /** + * Returns the stored internal buffer. This serializer should not be used once + * the buffer is released. Calling this method results in undefined behavior + * if a previous write has failed. + */ + releaseBuffer(): NonSharedBuffer; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Write a raw 32-bit unsigned integer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint32(value: number): void; + /** + * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint64(hi: number, lo: number): void; + /** + * Write a JS `number` value. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeDouble(value: number): void; + /** + * Write raw bytes into the serializer's internal buffer. The deserializer + * will require a way to compute the length of the buffer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeRawBytes(buffer: NodeJS.ArrayBufferView): void; + } + /** + * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only + * stores the part of their underlying `ArrayBuffer`s that they are referring to. + * @since v8.0.0 + */ + class DefaultSerializer extends Serializer {} + /** + * @since v8.0.0 + */ + class Deserializer { + constructor(data: NodeJS.TypedArray); + /** + * Reads and validates a header (including the format version). + * May, for example, reject an invalid or unsupported wire format. In that case, + * an `Error` is thrown. + */ + readHeader(): boolean; + /** + * Deserializes a JavaScript value from the buffer and returns it. + */ + readValue(): any; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of + * `SharedArrayBuffer`s). + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Reads the underlying wire format version. Likely mostly to be useful to + * legacy code reading old wire format versions. May not be called before `.readHeader()`. + */ + getWireFormatVersion(): number; + /** + * Read a raw 32-bit unsigned integer and return it. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint32(): number; + /** + * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]` with two 32-bit unsigned integer entries. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint64(): [number, number]; + /** + * Read a JS `number` value. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readDouble(): number; + /** + * Read raw bytes from the deserializer's internal buffer. The `length` parameter + * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readRawBytes(length: number): Buffer; + } + /** + * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`. + * @since v8.0.0 + */ + class DefaultDeserializer extends Deserializer {} + /** + * Uses a `DefaultSerializer` to serialize `value` into a buffer. + * + * `ERR_BUFFER_TOO_LARGE` will be thrown when trying to + * serialize a huge object which requires buffer + * larger than `buffer.constants.MAX_LENGTH`. + * @since v8.0.0 + */ + function serialize(value: any): NonSharedBuffer; + /** + * Uses a `DefaultDeserializer` with default options to read a JS value + * from a buffer. + * @since v8.0.0 + * @param buffer A buffer returned by {@link serialize}. + */ + function deserialize(buffer: NodeJS.ArrayBufferView): any; + /** + * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple + * times during the lifetime of the process. Each time the execution counter will + * be reset and a new coverage report will be written to the directory specified + * by `NODE_V8_COVERAGE`. + * + * When the process is about to exit, one last coverage will still be written to + * disk unless {@link stopCoverage} is invoked before the process exits. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function takeCoverage(): void; + /** + * The `v8.stopCoverage()` method allows the user to stop the coverage collection + * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count + * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function stopCoverage(): void; + /** + * The API is a no-op if `--heapsnapshot-near-heap-limit` is already set from the command line or the API is called more than once. + * `limit` must be a positive integer. See [`--heapsnapshot-near-heap-limit`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--heapsnapshot-near-heap-limitmax_count) for more information. + * @since v18.10.0, v16.18.0 + */ + function setHeapSnapshotNearHeapLimit(limit: number): void; + /** + * This API collects GC data in current thread. + * @since v19.6.0, v18.15.0 + */ + class GCProfiler { + /** + * Start collecting GC data. + * @since v19.6.0, v18.15.0 + */ + start(): void; + /** + * Stop collecting GC data and return an object. The content of object + * is as follows. + * + * ```json + * { + * "version": 1, + * "startTime": 1674059033862, + * "statistics": [ + * { + * "gcType": "Scavenge", + * "beforeGC": { + * "heapStatistics": { + * "totalHeapSize": 5005312, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5226496, + * "totalAvailableSize": 4341325216, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4883840, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * }, + * "cost": 1574.14, + * "afterGC": { + * "heapStatistics": { + * "totalHeapSize": 6053888, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5500928, + * "totalAvailableSize": 4341101384, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4059096, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * } + * } + * ], + * "endTime": 1674059036865 + * } + * ``` + * + * Here's an example. + * + * ```js + * import { GCProfiler } from 'node:v8'; + * const profiler = new GCProfiler(); + * profiler.start(); + * setTimeout(() => { + * console.log(profiler.stop()); + * }, 1000); + * ``` + * @since v19.6.0, v18.15.0 + */ + stop(): GCProfilerResult; + } + interface GCProfilerResult { + version: number; + startTime: number; + endTime: number; + statistics: Array<{ + gcType: string; + cost: number; + beforeGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + afterGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + }>; + } + interface HeapStatistics { + totalHeapSize: number; + totalHeapSizeExecutable: number; + totalPhysicalSize: number; + totalAvailableSize: number; + totalGlobalHandlesSize: number; + usedGlobalHandlesSize: number; + usedHeapSize: number; + heapSizeLimit: number; + mallocedMemory: number; + externalMemory: number; + peakMallocedMemory: number; + } + interface HeapSpaceStatistics { + spaceName: string; + spaceSize: number; + spaceUsedSize: number; + spaceAvailableSize: number; + physicalSpaceSize: number; + } + /** + * Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will + * happen if a promise is created without ever getting a continuation. + * @since v17.1.0, v16.14.0 + * @param promise The promise being created. + * @param parent The promise continued from, if applicable. + */ + interface Init { + (promise: Promise, parent: Promise): void; + } + /** + * Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming. + * + * The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise. + * The before callback may be called many times in the case where many continuations have been made from the same promise. + * @since v17.1.0, v16.14.0 + */ + interface Before { + (promise: Promise): void; + } + /** + * Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await. + * @since v17.1.0, v16.14.0 + */ + interface After { + (promise: Promise): void; + } + /** + * Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or + * {@link Promise.reject()}. + * @since v17.1.0, v16.14.0 + */ + interface Settled { + (promise: Promise): void; + } + /** + * Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or + * around an await, and when the promise resolves or rejects. + * + * Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and + * `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop. + * @since v17.1.0, v16.14.0 + */ + interface HookCallbacks { + init?: Init; + before?: Before; + after?: After; + settled?: Settled; + } + interface PromiseHooks { + /** + * The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param init The {@link Init | `init` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onInit: (init: Init) => Function; + /** + * The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param settled The {@link Settled | `settled` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onSettled: (settled: Settled) => Function; + /** + * The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param before The {@link Before | `before` callback} to call before a promise continuation executes. + * @return Call to stop the hook. + */ + onBefore: (before: Before) => Function; + /** + * The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param after The {@link After | `after` callback} to call after a promise continuation executes. + * @return Call to stop the hook. + */ + onAfter: (after: After) => Function; + /** + * Registers functions to be called for different lifetime events of each promise. + * The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime. + * All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed. + * The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param callbacks The {@link HookCallbacks | Hook Callbacks} to register + * @return Used for disabling hooks + */ + createHook: (callbacks: HookCallbacks) => Function; + } + /** + * The `promiseHooks` interface can be used to track promise lifecycle events. + * @since v17.1.0, v16.14.0 + */ + const promiseHooks: PromiseHooks; + type StartupSnapshotCallbackFn = (args: any) => any; + /** + * The `v8.startupSnapshot` interface can be used to add serialization and deserialization hooks for custom startup snapshots. + * + * ```bash + * $ node --snapshot-blob snapshot.blob --build-snapshot entry.js + * # This launches a process with the snapshot + * $ node --snapshot-blob snapshot.blob + * ``` + * + * In the example above, `entry.js` can use methods from the `v8.startupSnapshot` interface to specify how to save information for custom objects + * in the snapshot during serialization and how the information can be used to synchronize these objects during deserialization of the snapshot. + * For example, if the `entry.js` contains the following script: + * + * ```js + * 'use strict'; + * + * import fs from 'node:fs'; + * import zlib from 'node:zlib'; + * import path from 'node:path'; + * import assert from 'node:assert'; + * + * import v8 from 'node:v8'; + * + * class BookShelf { + * storage = new Map(); + * + * // Reading a series of files from directory and store them into storage. + * constructor(directory, books) { + * for (const book of books) { + * this.storage.set(book, fs.readFileSync(path.join(directory, book))); + * } + * } + * + * static compressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gzipSync(content)); + * } + * } + * + * static decompressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gunzipSync(content)); + * } + * } + * } + * + * // __dirname here is where the snapshot script is placed + * // during snapshot building time. + * const shelf = new BookShelf(__dirname, [ + * 'book1.en_US.txt', + * 'book1.es_ES.txt', + * 'book2.zh_CN.txt', + * ]); + * + * assert(v8.startupSnapshot.isBuildingSnapshot()); + * // On snapshot serialization, compress the books to reduce size. + * v8.startupSnapshot.addSerializeCallback(BookShelf.compressAll, shelf); + * // On snapshot deserialization, decompress the books. + * v8.startupSnapshot.addDeserializeCallback(BookShelf.decompressAll, shelf); + * v8.startupSnapshot.setDeserializeMainFunction((shelf) => { + * // process.env and process.argv are refreshed during snapshot + * // deserialization. + * const lang = process.env.BOOK_LANG || 'en_US'; + * const book = process.argv[1]; + * const name = `${book}.${lang}.txt`; + * console.log(shelf.storage.get(name)); + * }, shelf); + * ``` + * + * The resulted binary will get print the data deserialized from the snapshot during start up, using the refreshed `process.env` and `process.argv` of the launched process: + * + * ```bash + * $ BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1 + * # Prints content of book1.es_ES.txt deserialized from the snapshot. + * ``` + * + * Currently the application deserialized from a user-land snapshot cannot be snapshotted again, so these APIs are only available to applications that are not deserialized from a user-land snapshot. + * + * @since v18.6.0, v16.17.0 + */ + namespace startupSnapshot { + /** + * Add a callback that will be called when the Node.js instance is about to get serialized into a snapshot and exit. + * This can be used to release resources that should not or cannot be serialized or to convert user data into a form more suitable for serialization. + * @since v18.6.0, v16.17.0 + */ + function addSerializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Add a callback that will be called when the Node.js instance is deserialized from a snapshot. + * The `callback` and the `data` (if provided) will be serialized into the snapshot, they can be used to re-initialize the state of the application or + * to re-acquire resources that the application needs when the application is restarted from the snapshot. + * @since v18.6.0, v16.17.0 + */ + function addDeserializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * This sets the entry point of the Node.js application when it is deserialized from a snapshot. This can be called only once in the snapshot building script. + * If called, the deserialized application no longer needs an additional entry point script to start up and will simply invoke the callback along with the deserialized + * data (if provided), otherwise an entry point script still needs to be provided to the deserialized application. + * @since v18.6.0, v16.17.0 + */ + function setDeserializeMainFunction(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Returns true if the Node.js instance is run to build a snapshot. + * @since v18.6.0, v16.17.0 + */ + function isBuildingSnapshot(): boolean; + } +} +declare module "node:v8" { + export * from "v8"; +} diff --git a/node_modules/@types/node/vm.d.ts b/node_modules/@types/node/vm.d.ts new file mode 100644 index 0000000..a2609bf --- /dev/null +++ b/node_modules/@types/node/vm.d.ts @@ -0,0 +1,1000 @@ +/** + * The `node:vm` module enables compiling and running code within V8 Virtual + * Machine contexts. + * + * **The `node:vm` module is not a security** + * **mechanism. Do not use it to run untrusted code.** + * + * JavaScript code can be compiled and run immediately or + * compiled, saved, and run later. + * + * A common use case is to run the code in a different V8 Context. This means + * invoked code has a different global object than the invoking code. + * + * One can provide the context by `contextifying` an + * object. The invoked code treats any property in the context like a + * global variable. Any changes to global variables caused by the invoked + * code are reflected in the context object. + * + * ```js + * import vm from 'node:vm'; + * + * const x = 1; + * + * const context = { x: 2 }; + * vm.createContext(context); // Contextify the object. + * + * const code = 'x += 40; var y = 17;'; + * // `x` and `y` are global variables in the context. + * // Initially, x has the value 2 because that is the value of context.x. + * vm.runInContext(code, context); + * + * console.log(context.x); // 42 + * console.log(context.y); // 17 + * + * console.log(x); // 1; y is not defined. + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/vm.js) + */ +declare module "vm" { + import { NonSharedBuffer } from "node:buffer"; + import { ImportAttributes } from "node:module"; + interface Context extends NodeJS.Dict {} + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * @default '' + */ + filename?: string | undefined; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + lineOffset?: number | undefined; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + columnOffset?: number | undefined; + } + type DynamicModuleLoader = ( + specifier: string, + referrer: T, + importAttributes: ImportAttributes, + ) => Module | Promise; + interface ScriptOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: NodeJS.ArrayBufferView | undefined; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean | undefined; + /** + * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is + * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see + * [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v22.x/api/vm.html#support-of-dynamic-import-in-compilation-apis). + */ + importModuleDynamically?: + | DynamicModuleLoader` + +[Get supported base64-js with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-base64-js?utm_source=npm-base64-js&utm_medium=referral&utm_campaign=readme) + +## methods + +`base64js` has three exposed functions, `byteLength`, `toByteArray` and `fromByteArray`, which both take a single argument. + +* `byteLength` - Takes a base64 string and returns length of byte array +* `toByteArray` - Takes a base64 string and returns a byte array +* `fromByteArray` - Takes a byte array and returns a base64 string + +## license + +MIT diff --git a/node_modules/base64-js/base64js.min.js b/node_modules/base64-js/base64js.min.js new file mode 100644 index 0000000..908ac83 --- /dev/null +++ b/node_modules/base64-js/base64js.min.js @@ -0,0 +1 @@ +(function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window,b.base64js=a()}})(function(){return function(){function b(d,e,g){function a(j,i){if(!e[j]){if(!d[j]){var f="function"==typeof require&&require;if(!i&&f)return f(j,!0);if(h)return h(j,!0);var c=new Error("Cannot find module '"+j+"'");throw c.code="MODULE_NOT_FOUND",c}var k=e[j]={exports:{}};d[j][0].call(k.exports,function(b){var c=d[j][1][b];return a(c||b)},k,k.exports,b,d,e,g)}return e[j].exports}for(var h="function"==typeof require&&require,c=0;c>16,j[k++]=255&b>>8,j[k++]=255&b;return 2===h&&(b=l[a.charCodeAt(c)]<<2|l[a.charCodeAt(c+1)]>>4,j[k++]=255&b),1===h&&(b=l[a.charCodeAt(c)]<<10|l[a.charCodeAt(c+1)]<<4|l[a.charCodeAt(c+2)]>>2,j[k++]=255&b>>8,j[k++]=255&b),j}function g(a){return k[63&a>>18]+k[63&a>>12]+k[63&a>>6]+k[63&a]}function h(a,b,c){for(var d,e=[],f=b;fj?j:g+f));return 1===d?(b=a[c-1],e.push(k[b>>2]+k[63&b<<4]+"==")):2===d&&(b=(a[c-2]<<8)+a[c-1],e.push(k[b>>10]+k[63&b>>4]+k[63&b<<2]+"=")),e.join("")}c.byteLength=function(a){var b=d(a),c=b[0],e=b[1];return 3*(c+e)/4-e},c.toByteArray=f,c.fromByteArray=j;for(var k=[],l=[],m="undefined"==typeof Uint8Array?Array:Uint8Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,p=n.length;o 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} diff --git a/node_modules/base64-js/package.json b/node_modules/base64-js/package.json new file mode 100644 index 0000000..c3972e3 --- /dev/null +++ b/node_modules/base64-js/package.json @@ -0,0 +1,47 @@ +{ + "name": "base64-js", + "description": "Base64 encoding/decoding in pure JS", + "version": "1.5.1", + "author": "T. Jameson Little ", + "typings": "index.d.ts", + "bugs": { + "url": "https://github.com/beatgammit/base64-js/issues" + }, + "devDependencies": { + "babel-minify": "^0.5.1", + "benchmark": "^2.1.4", + "browserify": "^16.3.0", + "standard": "*", + "tape": "4.x" + }, + "homepage": "https://github.com/beatgammit/base64-js", + "keywords": [ + "base64" + ], + "license": "MIT", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/beatgammit/base64-js.git" + }, + "scripts": { + "build": "browserify -s base64js -r ./ | minify > base64js.min.js", + "lint": "standard", + "test": "npm run lint && npm run unit", + "unit": "tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/bignumber.js/CHANGELOG.md b/node_modules/bignumber.js/CHANGELOG.md new file mode 100644 index 0000000..d7af1b8 --- /dev/null +++ b/node_modules/bignumber.js/CHANGELOG.md @@ -0,0 +1,381 @@ +#### 9.3.1 + +* 11/07/25 +* [BUGFIX] #388 `toPrecision` fix. + +#### 9.3.0 + +* 19/04/25 +* Refactor type declarations: +* Rename *bignumber.d.ts* to *types.d.ts*. +* Rename *bignumber.d.cts* to *bignumber.d.ts*. +* Add `export as namespace` to *bignumber.d.ts*. +* Remove subpath exports from *package.json*. +* Refactor named export from *bignumber.d.mts*. +* #383 Remove `?` from static `BigNumber` and `default` properties. +* Add blank lines after titles in *CHANGELOG.md*. + +#### 9.2.1 + +* 08/04/25 +* #371 #382 Add `BigNumber` as named export. + +#### 9.2.0 + +* 03/04/25 +* #355 Support `BigInt` argument. +* #371 Provide separate type definitions for CommonJS and ES modules. +* #374 Correct `comparedTo` return type. + +#### 9.1.2 + +* 28/08/23 +* #354 Amend `round` to avoid bug in v8 Maglev compiler. +* [BUGFIX] #344 `minimum(0, -0)` should be `-0`. + +#### 9.1.1 + +* 04/12/22 +* #338 [BUGFIX] `exponentiatedBy`: ensure `0**-n === Infinity` for very large `n`. + +#### 9.1.0 + +* 08/08/22 +* #329 Remove `import` example. +* #277 Resolve lint warnings and add number `toString` note. +* Correct `decimalPlaces()` return type in *bignumber.d.ts*. +* Add ES module global `crypto` example. +* #322 Add `exports` field to *package.json*. +* #251 (#308) Amend *bignumber.d.ts* to allow instantiating a BigNumber without `new`. + +#### 9.0.2 + +* 12/12/21 +* #250 [BUGFIX] Allow use of user-defined alphabet for base 10. +* #295 Remove *bignumber.min.js* and amend *README.md*. +* Update *.travis.yml* and *LICENCE.md*. + +#### 9.0.1 + +* 28/09/20 +* [BUGFIX] #276 Correct `sqrt` initial estimate. +* Update *.travis.yml*, *LICENCE.md* and *README.md*. + +#### 9.0.0 + +* 27/05/2019 +* For compatibility with legacy browsers, remove `Symbol` references. + +#### 8.1.1 + +* 24/02/2019 +* [BUGFIX] #222 Restore missing `var` to `export BigNumber`. +* Allow any key in BigNumber.Instance in *bignumber.d.ts*. + +#### 8.1.0 + +* 23/02/2019 +* [NEW FEATURE] #220 Create a BigNumber using `{s, e, c}`. +* [NEW FEATURE] `isBigNumber`: if `BigNumber.DEBUG` is `true`, also check that the BigNumber instance is well-formed. +* Remove `instanceof` checks; just use `_isBigNumber` to identify a BigNumber instance. +* Add `_isBigNumber` to prototype in *bignumber.mjs*. +* Add tests for BigNumber creation from object. +* Update *API.html*. + +#### 8.0.2 + +* 13/01/2019 +* #209 `toPrecision` without argument should follow `toString`. +* Improve *Use* section of *README*. +* Optimise `toString(10)`. +* Add verson number to API doc. + +#### 8.0.1 + +* 01/11/2018 +* Rest parameter must be array type in *bignumber.d.ts*. + +#### 8.0.0 + +* 01/11/2018 +* [NEW FEATURE] Add `BigNumber.sum` method. +* [NEW FEATURE]`toFormat`: add `prefix` and `suffix` options. +* [NEW FEATURE] #178 Pass custom formatting to `toFormat`. +* [BREAKING CHANGE] #184 `toFraction`: return array of BigNumbers not strings. +* [NEW FEATURE] #185 Enable overwrite of `valueOf` to prevent accidental addition to string. +* #183 Add Node.js `crypto` requirement to documentation. +* [BREAKING CHANGE] #198 Disallow signs and whitespace in custom alphabet. +* [NEW FEATURE] #188 Implement `util.inspect.custom` for Node.js REPL. +* #170 Make `isBigNumber` a type guard in *bignumber.d.ts*. +* [BREAKING CHANGE] `BigNumber.min` and `BigNumber.max`: don't accept an array. +* Update *.travis.yml*. +* Remove *bower.json*. + +#### 7.2.1 + +* 24/05/2018 +* Add `browser` field to *package.json*. + +#### 7.2.0 + +* 22/05/2018 +* #166 Correct *.mjs* file. Remove extension from `main` field in *package.json*. + +#### 7.1.0 + +* 18/05/2018 +* Add `module` field to *package.json* for *bignumber.mjs*. + +#### 7.0.2 + +* 17/05/2018 +* #165 Bugfix: upper-case letters for bases 11-36 in a custom alphabet. +* Add note to *README* regarding creating BigNumbers from Number values. + +#### 7.0.1 + +* 26/04/2018 +* #158 Fix global object variable name typo. + +#### 7.0.0 + +* 26/04/2018 +* #143 Remove global BigNumber from typings. +* #144 Enable compatibility with `Object.freeze(Object.prototype)`. +* #148 #123 #11 Only throw on a number primitive with more than 15 significant digits if `BigNumber.DEBUG` is `true`. +* Only throw on an invalid BigNumber value if `BigNumber.DEBUG` is `true`. Return BigNumber `NaN` instead. +* #154 `exponentiatedBy`: allow BigNumber exponent. +* #156 Prevent Content Security Policy *unsafe-eval* issue. +* `toFraction`: allow `Infinity` maximum denominator. +* Comment-out some excess tests to reduce test time. +* Amend indentation and other spacing. + +#### 6.0.0 + +* 26/01/2018 +* #137 Implement `APLHABET` configuration option. +* Remove `ERRORS` configuration option. +* Remove `toDigits` method; extend `precision` method accordingly. +* Remove s`round` method; extend `decimalPlaces` method accordingly. +* Remove methods: `ceil`, `floor`, and `truncated`. +* Remove method aliases: `add`, `cmp`, `isInt`, `isNeg`, `trunc`, `mul`, `neg` and `sub`. +* Rename methods: `shift` to `shiftedBy`, `another` to `clone`, `toPower` to `exponentiatedBy`, and `equals` to `isEqualTo`. +* Rename methods: add `is` prefix to `greaterThan`, `greaterThanOrEqualTo`, `lessThan` and `lessThanOrEqualTo`. +* Add methods: `multipliedBy`, `isBigNumber`, `isPositive`, `integerValue`, `maximum` and `minimum`. +* Refactor test suite. +* Add *CHANGELOG.md*. +* Rewrite *bignumber.d.ts*. +* Redo API image. + +#### 5.0.0 + +* 27/11/2017 +* #81 Don't throw on constructor call without `new`. + +#### 4.1.0 + +* 26/09/2017 +* Remove node 0.6 from *.travis.yml*. +* Add *bignumber.mjs*. + +#### 4.0.4 + +* 03/09/2017 +* Add missing aliases to *bignumber.d.ts*. + +#### 4.0.3 + +* 30/08/2017 +* Add types: *bignumber.d.ts*. + +#### 4.0.2 + +* 03/05/2017 +* #120 Workaround Safari/Webkit bug. + +#### 4.0.1 + +* 05/04/2017 +* #121 BigNumber.default to BigNumber['default']. + +#### 4.0.0 + +* 09/01/2017 +* Replace BigNumber.isBigNumber method with isBigNumber prototype property. + +#### 3.1.2 + +* 08/01/2017 +* Minor documentation edit. + +#### 3.1.1 + +* 08/01/2017 +* Uncomment `isBigNumber` tests. +* Ignore dot files. + +#### 3.1.0 + +* 08/01/2017 +* Add `isBigNumber` method. + +#### 3.0.2 + +* 08/01/2017 +* Bugfix: Possible incorrect value of `ERRORS` after a `BigNumber.another` call (due to `parseNumeric` declaration in outer scope). + +#### 3.0.1 + +* 23/11/2016 +* Apply fix for old ipads with `%` issue, see #57 and #102. +* Correct error message. + +#### 3.0.0 + +* 09/11/2016 +* Remove `require('crypto')` - leave it to the user. +* Add `BigNumber.set` as `BigNumber.config` alias. +* Default `POW_PRECISION` to `0`. + +#### 2.4.0 + +* 14/07/2016 +* #97 Add exports to support ES6 imports. + +#### 2.3.0 + +* 07/03/2016 +* #86 Add modulus parameter to `toPower`. + +#### 2.2.0 + +* 03/03/2016 +* #91 Permit larger JS integers. + +#### 2.1.4 + +* 15/12/2015 +* Correct UMD. + +#### 2.1.3 + +* 13/12/2015 +* Refactor re global object and crypto availability when bundling. + +#### 2.1.2 + +* 10/12/2015 +* Bugfix: `window.crypto` not assigned to `crypto`. + +#### 2.1.1 + +* 09/12/2015 +* Prevent code bundler from adding `crypto` shim. + +#### 2.1.0 + +* 26/10/2015 +* For `valueOf` and `toJSON`, include the minus sign with negative zero. + +#### 2.0.8 + +* 2/10/2015 +* Internal round function bugfix. + +#### 2.0.6 + +* 31/03/2015 +* Add bower.json. Tweak division after in-depth review. + +#### 2.0.5 + +* 25/03/2015 +* Amend README. Remove bitcoin address. + +#### 2.0.4 + +* 25/03/2015 +* Critical bugfix #58: division. + +#### 2.0.3 + +* 18/02/2015 +* Amend README. Add source map. + +#### 2.0.2 + +* 18/02/2015 +* Correct links. + +#### 2.0.1 + +* 18/02/2015 +* Add `max`, `min`, `precision`, `random`, `shiftedBy`, `toDigits` and `truncated` methods. +* Add the short-forms: `add`, `mul`, `sd`, `sub` and `trunc`. +* Add an `another` method to enable multiple independent constructors to be created. +* Add support for the base 2, 8 and 16 prefixes `0b`, `0o` and `0x`. +* Enable a rounding mode to be specified as a second parameter to `toExponential`, `toFixed`, `toFormat` and `toPrecision`. +* Add a `CRYPTO` configuration property so cryptographically-secure pseudo-random number generation can be specified. +* Add a `MODULO_MODE` configuration property to enable the rounding mode used by the `modulo` operation to be specified. +* Add a `POW_PRECISION` configuration property to enable the number of significant digits calculated by the power operation to be limited. +* Improve code quality. +* Improve documentation. + +#### 2.0.0 + +* 29/12/2014 +* Add `dividedToIntegerBy`, `isInteger` and `toFormat` methods. +* Remove the following short-forms: `isF`, `isZ`, `toE`, `toF`, `toFr`, `toN`, `toP`, `toS`. +* Store a BigNumber's coefficient in base 1e14, rather than base 10. +* Add fast path for integers to BigNumber constructor. +* Incorporate the library into the online documentation. + +#### 1.5.0 + +* 13/11/2014 +* Add `toJSON` and `decimalPlaces` methods. + +#### 1.4.1 + +* 08/06/2014 +* Amend README. + +#### 1.4.0 + +* 08/05/2014 +* Add `toNumber`. + +#### 1.3.0 + +* 08/11/2013 +* Ensure correct rounding of `sqrt` in all, rather than almost all, cases. +* Maximum radix to 64. + +#### 1.2.1 + +* 17/10/2013 +* Sign of zero when x < 0 and x + (-x) = 0. + +#### 1.2.0 + +* 19/9/2013 +* Throw Error objects for stack. + +#### 1.1.1 + +* 22/8/2013 +* Show original value in constructor error message. + +#### 1.1.0 + +* 1/8/2013 +* Allow numbers with trailing radix point. + +#### 1.0.1 + +* Bugfix: error messages with incorrect method name + +#### 1.0.0 + +* 8/11/2012 +* Initial release diff --git a/node_modules/bignumber.js/LICENCE.md b/node_modules/bignumber.js/LICENCE.md new file mode 100644 index 0000000..2800f9e --- /dev/null +++ b/node_modules/bignumber.js/LICENCE.md @@ -0,0 +1,26 @@ +The MIT License (MIT) +===================== + +Copyright © `<2025>` `Michael Mclaughlin` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/bignumber.js/README.md b/node_modules/bignumber.js/README.md new file mode 100644 index 0000000..5a40d09 --- /dev/null +++ b/node_modules/bignumber.js/README.md @@ -0,0 +1,289 @@ +![bignumber.js](https://raw.githubusercontent.com/MikeMcl/bignumber.js/gh-pages/bignumberjs.png) + +A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic. + +[![npm version](https://img.shields.io/npm/v/bignumber.js.svg)](https://www.npmjs.com/package/bignumber.js) +[![npm downloads](https://img.shields.io/npm/dw/bignumber.js)](https://www.npmjs.com/package/bignumber.js) +[![CI](https://github.com/MikeMcl/bignumber.js/actions/workflows/ci.yml/badge.svg)](https://github.com/MikeMcl/bignumber.js/actions/workflows/ci.yml) + +
                          + +## Features + +- Integers and decimals +- Simple API but full-featured +- Faster, smaller, and perhaps easier to use than JavaScript versions of Java's BigDecimal +- 8 KB minified and gzipped +- Replicates the `toExponential`, `toFixed`, `toPrecision` and `toString` methods of JavaScript's Number type +- Includes a `toFraction` and a correctly-rounded `squareRoot` method +- Supports cryptographically-secure pseudo-random number generation +- No dependencies +- Wide platform compatibility: uses JavaScript 1.5 (ECMAScript 3) features only +- Comprehensive [documentation](http://mikemcl.github.io/bignumber.js/) and test set + +![API](https://raw.githubusercontent.com/MikeMcl/bignumber.js/gh-pages/API.png) + +If a smaller and simpler library is required see [big.js](https://github.com/MikeMcl/big.js/). +It's less than half the size but only works with decimal numbers and only has half the methods. +It also has fewer configuration options than this library, and does not allow `NaN` or `Infinity`. + +See also [decimal.js](https://github.com/MikeMcl/decimal.js/), which among other things adds support for non-integer powers, and performs all operations to a specified number of significant digits. + +## Load + +The library is the single JavaScript file *bignumber.js* or ES module *bignumber.mjs*. + +### Browser + +```html + +``` + +> ES module + +```html + +``` + +### [Node.js](http://nodejs.org) + +```bash +npm install bignumber.js +``` + +```javascript +const BigNumber = require('bignumber.js'); +``` + +> ES module + +```javascript +import BigNumber from "bignumber.js"; +``` + +### [Deno](https://deno.land/) + +```javascript +// @deno-types="https://raw.githubusercontent.com/mikemcl/bignumber.js/v9.3.1/bignumber.d.mts" +import BigNumber from 'https://raw.githubusercontent.com/mikemcl/bignumber.js/v9.3.1/bignumber.mjs'; + +// @deno-types="https://unpkg.com/bignumber.js@latest/bignumber.d.mts" +import { BigNumber } from 'https://unpkg.com/bignumber.js@latest/bignumber.mjs'; +``` + +## Use + +The library exports a single constructor function, [`BigNumber`](http://mikemcl.github.io/bignumber.js/#bignumber), which accepts a value of type Number, String or BigNumber, + +```javascript +let x = new BigNumber(123.4567); +let y = BigNumber('123456.7e-3'); +let z = new BigNumber(x); +x.isEqualTo(y) && y.isEqualTo(z) && x.isEqualTo(z); // true +``` + +To get the string value of a BigNumber use [`toString()`](http://mikemcl.github.io/bignumber.js/#toS) or [`toFixed()`](http://mikemcl.github.io/bignumber.js/#toFix). Using `toFixed()` prevents exponential notation being returned, no matter how large or small the value. + +```javascript +let x = new BigNumber('1111222233334444555566'); +x.toString(); // "1.111222233334444555566e+21" +x.toFixed(); // "1111222233334444555566" +``` + +If the limited precision of Number values is not well understood, it is recommended to create BigNumbers from String values rather than Number values to avoid a potential loss of precision. + +*In all further examples below, `let`, semicolons and `toString` calls are not shown. If a commented-out value is in quotes it means `toString` has been called on the preceding expression.* + +```javascript +// Precision loss from using numeric literals with more than 15 significant digits. +new BigNumber(1.0000000000000001) // '1' +new BigNumber(88259496234518.57) // '88259496234518.56' +new BigNumber(99999999999999999999) // '100000000000000000000' + +// Precision loss from using numeric literals outside the range of Number values. +new BigNumber(2e+308) // 'Infinity' +new BigNumber(1e-324) // '0' + +// Precision loss from the unexpected result of arithmetic with Number values. +new BigNumber(0.7 + 0.1) // '0.7999999999999999' +``` + +When creating a BigNumber from a Number, note that a BigNumber is created from a Number's decimal `toString()` value not from its underlying binary value. If the latter is required, then pass the Number's `toString(2)` value and specify base 2. + +```javascript +new BigNumber(Number.MAX_VALUE.toString(2), 2) +``` + +BigNumbers can be created from values in bases from 2 to 36. See [`ALPHABET`](http://mikemcl.github.io/bignumber.js/#alphabet) to extend this range. + +```javascript +a = new BigNumber(1011, 2) // "11" +b = new BigNumber('zz.9', 36) // "1295.25" +c = a.plus(b) // "1306.25" +``` + +*Performance is better if base 10 is NOT specified for decimal values. Only specify base 10 when you want to limit the number of decimal places of the input value to the current [`DECIMAL_PLACES`](http://mikemcl.github.io/bignumber.js/#decimal-places) setting.* + +A BigNumber is immutable in the sense that it is not changed by its methods. + +```javascript +0.3 - 0.1 // 0.19999999999999998 +x = new BigNumber(0.3) +x.minus(0.1) // "0.2" +x // "0.3" +``` + +The methods that return a BigNumber can be chained. + +```javascript +x.dividedBy(y).plus(z).times(9) +x.times('1.23456780123456789e+9').plus(9876.5432321).dividedBy('4444562598.111772').integerValue() +``` + +Some of the longer method names have a shorter alias. + +```javascript +x.squareRoot().dividedBy(y).exponentiatedBy(3).isEqualTo(x.sqrt().div(y).pow(3)) // true +x.modulo(y).multipliedBy(z).eq(x.mod(y).times(z)) // true +``` + +As with JavaScript's Number type, there are [`toExponential`](http://mikemcl.github.io/bignumber.js/#toE), [`toFixed`](http://mikemcl.github.io/bignumber.js/#toFix) and [`toPrecision`](http://mikemcl.github.io/bignumber.js/#toP) methods. + +```javascript +x = new BigNumber(255.5) +x.toExponential(5) // "2.55500e+2" +x.toFixed(5) // "255.50000" +x.toPrecision(5) // "255.50" +x.toNumber() // 255.5 +``` + + A base can be specified for [`toString`](http://mikemcl.github.io/bignumber.js/#toS). + +*Performance is better if base 10 is NOT specified, i.e. use `toString()` not `toString(10)`. Only specify base 10 when you want to limit the number of decimal places of the string to the current [`DECIMAL_PLACES`](http://mikemcl.github.io/bignumber.js/#decimal-places) setting.* + + ```javascript + x.toString(16) // "ff.8" + ``` + +There is a [`toFormat`](http://mikemcl.github.io/bignumber.js/#toFor) method which may be useful for internationalisation. + +```javascript +y = new BigNumber('1234567.898765') +y.toFormat(2) // "1,234,567.90" +``` + +The maximum number of decimal places of the result of an operation involving division (i.e. a division, square root, base conversion or negative power operation) is set using the `set` or `config` method of the `BigNumber` constructor. + +The other arithmetic operations always give the exact result. + +```javascript +BigNumber.set({ DECIMAL_PLACES: 10, ROUNDING_MODE: 4 }) + +x = new BigNumber(2) +y = new BigNumber(3) +z = x.dividedBy(y) // "0.6666666667" +z.squareRoot() // "0.8164965809" +z.exponentiatedBy(-3) // "3.3749999995" +z.toString(2) // "0.1010101011" +z.multipliedBy(z) // "0.44444444448888888889" +z.multipliedBy(z).decimalPlaces(10) // "0.4444444445" +``` + +There is a [`toFraction`](http://mikemcl.github.io/bignumber.js/#toFr) method with an optional *maximum denominator* argument + +```javascript +y = new BigNumber(355) +pi = y.dividedBy(113) // "3.1415929204" +pi.toFraction() // [ "7853982301", "2500000000" ] +pi.toFraction(1000) // [ "355", "113" ] +``` + +and [`isNaN`](http://mikemcl.github.io/bignumber.js/#isNaN) and [`isFinite`](http://mikemcl.github.io/bignumber.js/#isF) methods, as `NaN` and `Infinity` are valid `BigNumber` values. + +```javascript +x = new BigNumber(NaN) // "NaN" +y = new BigNumber(Infinity) // "Infinity" +x.isNaN() && !y.isNaN() && !x.isFinite() && !y.isFinite() // true +``` + +The value of a BigNumber is stored in a decimal floating point format in terms of a coefficient, exponent and sign. + +```javascript +x = new BigNumber(-123.456); +x.c // [ 123, 45600000000000 ] coefficient (i.e. significand) +x.e // 2 exponent +x.s // -1 sign +``` + +For advanced usage, multiple BigNumber constructors can be created, each with its own independent configuration. + +```javascript +// Set DECIMAL_PLACES for the original BigNumber constructor +BigNumber.set({ DECIMAL_PLACES: 10 }) + +// Create another BigNumber constructor, optionally passing in a configuration object +BN = BigNumber.clone({ DECIMAL_PLACES: 5 }) + +x = new BigNumber(1) +y = new BN(1) + +x.div(3) // '0.3333333333' +y.div(3) // '0.33333' +``` + +To avoid having to call `toString` or `valueOf` on a BigNumber to get its value in the Node.js REPL or when using `console.log` use + +```javascript +BigNumber.prototype[require('util').inspect.custom] = BigNumber.prototype.valueOf; +``` + +For further information see the [API](http://mikemcl.github.io/bignumber.js/) reference in the *doc* directory. + +## Test + +The *test/modules* directory contains the test scripts for each method. + +The tests can be run with Node.js or a browser. For Node.js use + +```bash +npm test +``` + +or + +```bash +node test/test +``` + +To test a single method, use, for example + +```bash +node test/methods/toFraction +``` + +For the browser, open *test/test.html*. + +## Minify + +To minify using, for example, [terser](https://github.com/terser/terser) + +```bash +npm install -g terser +``` + +```bash +terser big.js -c -m -o big.min.js +``` + +## Licence + +The MIT Licence. + +See [LICENCE](https://github.com/MikeMcl/bignumber.js/blob/main/LICENCE.md). diff --git a/node_modules/bignumber.js/bignumber.d.mts b/node_modules/bignumber.js/bignumber.d.mts new file mode 100644 index 0000000..a58ca36 --- /dev/null +++ b/node_modules/bignumber.js/bignumber.d.mts @@ -0,0 +1,6 @@ +/// + +export default BigNumber; + +declare const BigNumberType: typeof BigNumber; +export { BigNumberType as BigNumber }; diff --git a/node_modules/bignumber.js/bignumber.d.ts b/node_modules/bignumber.js/bignumber.d.ts new file mode 100644 index 0000000..6fde7b0 --- /dev/null +++ b/node_modules/bignumber.js/bignumber.d.ts @@ -0,0 +1,5 @@ +/// + +export = BigNumber; + +export as namespace BigNumber; diff --git a/node_modules/bignumber.js/bignumber.js b/node_modules/bignumber.js/bignumber.js new file mode 100644 index 0000000..663c2ae --- /dev/null +++ b/node_modules/bignumber.js/bignumber.js @@ -0,0 +1,2922 @@ +;(function (globalObject) { + 'use strict'; + +/* + * bignumber.js v9.3.1 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2025 Michael Mclaughlin + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | sum + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ + + + var BigNumber, + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, + + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 + + + /* + * Create and return a BigNumber constructor. + */ + function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), + + + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + + + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + suffix: '' + }, + + // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', + // '-', '.', whitespace, or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz', + alphabetHasNormalDecimalDigits = true; + + + //------------------------------------------------------------------------------------------ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * v {number|string|BigNumber} A numeric value. + * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(v, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; + + // Enable constructor call without `new`. + if (!(x instanceof BigNumber)) return new BigNumber(v, b); + + if (b == null) { + + if (v && v._isBigNumber === true) { + x.s = v.s; + + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } + + return; + } + + if ((isNum = typeof v == 'number') && v * 0 == 0) { + + // Use `1 / n` to handle minus zero also. + x.s = 1 / v < 0 ? (v = -v, -1) : 1; + + // Fast path for integers, where n < 2147483648 (2**31). + if (v === ~~v) { + for (e = 0, i = v; i >= 10; i /= 10, e++); + + if (e > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e; + x.c = [v]; + } + + return; + } + + str = String(v); + } else { + + if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); + + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + } else { + + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); + + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10 && alphabetHasNormalDecimalDigits) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + + str = String(v); + + if (isNum = typeof v == 'number') { + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); + + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + v); + } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + + alphabet = ALPHABET.slice(0, b); + e = i = 0; + + // Check that str is a valid base b number. + // Don't use RegExp, so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + + return parseNumeric(x, String(v), isNum, b); + } + } + + // Prevent later check for length on converted number. + isNum = false; + str = convertBase(str, b, 10, x.s); + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); + + if (str = str.slice(i, ++len)) { + len -= i; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error + (tooManyDigits + (x.s * v)); + } + + // Overflow? + if ((e = e - i - 1) > MAX_EXP) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; // i < 1 + + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); + + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } + + for (; i--; str += '0'); + x.c.push(+str); + } + } else { + + // Zero. + x.c = [x.e = 0]; + } + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * prefix {string} + * groupSize {number} + * secondaryGroupSize {number} + * groupSeparator {string} + * decimalSeparator {string} + * fractionGroupSize {number} + * fractionGroupSeparator {string} + * suffix {string} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + + if (typeof obj == 'object') { + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } + + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if less than two characters, + // or if it contains '+', '-', '.', whitespace, or a repeated character. + if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { + alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789'; + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); + } + } + + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + + + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. + * + * v {any} + * + * '[BigNumber Error] Invalid BigNumber: {v}' + */ + BigNumber.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber.DEBUG) return true; + + var i, n, + c = v.c, + e = v.e, + s = v.s; + + out: if ({}.toString.call(c) == '[object Array]') { + + if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { + + // If the first element is zero, the BigNumber value must be zero. + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } + + // Calculate number of digits that c[0] should have, based on the exponent. + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; + + // Calculate number of digits of c[0]. + //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { + if (String(c[0]).length == i) { + + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; + } + + // Last element cannot be zero, unless it is the only element. + if (n !== 0) return true; + } + } + + // Infinity/NaN + } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { + return true; + } + + throw Error + (bignumberError + 'Invalid BigNumber: ' + v); + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, -1); + }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, 1); + }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); + + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes(k *= 7); + + for (; i < k;) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } + + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); + + // Zero? + if (i < 0) { + c = [e = 0]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + /* + * Return a BigNumber whose value is the sum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber(args[0]); + for (; i < args.length;) sum = sum.plus(args[i++]); + return sum; + }; + + + // PRIVATE FUNCTIONS + + + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + + arr[0] += alphabet.indexOf(str.charAt(i++)); + + for (j = 0; j < arr.length; j++) { + + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; + } + + // Convert the number as integer. + + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); + + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; + + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); + + // Zero? + if (!xc[0]) return alphabet.charAt(0); + + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; + + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } + + // xc now represents str converted to baseOut. + + // The index of the rounding digit. + d = e + dp + 1; + + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; + + // Look at the rounding digits and mode to determine whether to round up. + + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); + + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { + + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + + // Truncate xc to the required number of decimal places. + xc.length = d; + + // Round up? + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; + + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); + + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); + } + + // The caller will add the sign. + return str; + }; + })(); + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare(a, b, aL, bL) { + var i, cmp; + + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + + for (i = cmp = 0; i < aL; i++) { + + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return cmp; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } + + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); + + if (yc[i] > (xc[i] || 0)) e--; + + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); + + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); + + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if (prodL < remL) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + + // If product was < remainder. + if (cmp == -1) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + + more = rem[0] != null; + + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } + + if (base == BASE) { + + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; + + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + if (!n.c) return n.toString(); + + c0 = n.c[0]; + ne = n.e; + + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString(n.c); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); + + // Fixed-point notation. + } else { + i -= ne + (id === 2 && e > ne); + str = toFixedPoint(str, e, '0'); + + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + // If any number is NaN, return NaN. + function maxOrMin(args, n) { + var k, y, + i = 1, + x = new BigNumber(args[0]); + + for (; i < args.length; i++) { + y = new BigNumber(args[i]); + if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) { + x = y; + } + } + + return x; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for (; !c[--j]; c.pop()); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); + + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); + + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } + + if (str != s) return new BigNumber(s, base); + } + + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } + + // NaN + x.s = null; + } + + x.c = x.e = null; + } + })(); + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + + // Get the rounding digit at index j of n. + rd = mathfloor(n / pows10[d - j - 1] % 10); + } else { + ni = mathceil((i + 1) / LOG_BASE); + + if (ni >= xc.length) { + + if (r) { + + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10); + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xc[0]) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + + // Round up? + if (r) { + + for (; ;) { + + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } + + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; + + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } + + return x; + } + + + function valueOf(n) { + var str, + e = n.e; + + if (e === null) return n.toString(); + + str = coeffToString(n.c); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + + + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; + + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), dp + x.e + 1, rm); + } + + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; + + n = new BigNumber(n); + + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + valueOf(n)); + } + + if (m != null) m = new BigNumber(m); + + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; + + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n))); + return m ? y.mod(m) : y; + } + + nIsNeg = n.s < 0; + + if (m) { + + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + + if (isModExp) x = x.mod(m); + + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; + + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; + + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); + + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } + + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; + } + + y = new BigNumber(ONE); + + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { + + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; + + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + + if (i) { + i = mathfloor(i / 2); + if (i === 0) break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); + + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) break; + nIsOdd = i % 2; + } + } + + x = x.times(x); + + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } + + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + + // Either zero? + if (!xc[0] || !yc[0]) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if (a = xe - ye) { + + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) { + t = xc; + xc = yc; + yc = t; + y.s = -y.s; + } + + b = (j = yc.length) - (i = xc.length); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; + + // Subtract yc from xc. + for (; j > a;) { + + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); + + // Zero? + if (!xc[0]) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; + + y = new BigNumber(y, b); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } + + if (MODULO_MODE == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } + + y = x.minus(q.times(y)); + + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + + return y; + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; + + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i = xcL; + xcL = ycL; + ycL = i; + } + + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); + + base = BASE; + sqrtBase = SQRT_BASE; + + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise(y, zc, e); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) { + t = yc; + yc = xc; + xc = t; + b = a; + } + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; + + + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; + + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), sd, rm); + } + + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if (v = c[v]) { + + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); + + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + + if (sd && x.e + 1 > n) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + + + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + + // Initial estimate. + s = Math.sqrt(+valueOf(x)); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(+n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; + + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the format or FORMAT object (see BigNumber.set). + * + * The formatting object may contain some or all of the properties shown below. + * + * FORMAT = { + * prefix: '', + * groupSize: 3, + * secondaryGroupSize: 0, + * groupSeparator: ',', + * decimalSeparator: '.', + * fractionGroupSize: 0, + * fractionGroupSeparator: '\xA0', // non-breaking space + * suffix: '' + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * [format] {object} Formatting options. See FORMAT pbject above. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + * '[BigNumber Error] Argument not an object: {format}' + */ + P.toFormat = function (dp, rm, format) { + var str, + x = this; + + if (format == null) { + if (dp != null && rm && typeof rm == 'object') { + format = rm; + rm = null; + } else if (dp && typeof dp == 'object') { + format = dp; + dp = rm = null; + } else { + format = FORMAT; + } + } else if (typeof format != 'object') { + throw Error + (bignumberError + 'Argument not an object: ' + format); + } + + str = x.toFixed(dp, rm); + + if (x.c) { + var i, + arr = str.split('.'), + g1 = +format.groupSize, + g2 = +format.secondaryGroupSize, + groupSeparator = format.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) { + i = g1; + g1 = g2; + g2 = i; + len -= i; + } + + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + (format.fractionGroupSeparator || '')) + : fractionPart) + : intPart; + } + + return (format.prefix || '') + str + (format.suffix || ''); + }; + + + /* + * Return an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to the specified + * maximum denominator. If a maximum denominator is not specified, the denominator will be + * the lowest value necessary to represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); + + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); + } + } + + if (!xc) return new BigNumber(x); + + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e = e * 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + + MAX_EXP = exp; + + return r; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +valueOf(this); + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if (e === null) { + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(coeffToString(n.c), e) + : toFixedPoint(coeffToString(n.c), e, '0'); + } else if (b === 10 && alphabetHasNormalDecimalDigits) { + n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); + } + + if (s < 0 && n.c[0]) str = '-' + str; + } + + return str; + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + return valueOf(this); + }; + + + P._isBigNumber = true; + + if (configObject != null) BigNumber.set(configObject); + + return BigNumber; + } + + + // PRIVATE HELPER FUNCTIONS + + // These functions don't need access to variables, + // e.g. DECIMAL_PLACES, in the scope of the `clone` function above. + + + function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; + } + + + // Return a coefficient array as a string of base 10 digits. + function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; + } + + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); + + return r.slice(0, j + 1 || 1); + } + + + // Compare the value of BigNumbers x and y. + function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if (!i || !j) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; + + // Signs differ? + if (i != j) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; + + j = (k = xc.length) < (l = yc.length) ? k : l; + + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; + } + + + /* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ + function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + String(n)); + } + } + + + // Assumes finite n. + function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; + } + + + function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; + } + + + function toFixedPoint(str, e, z) { + var len, zs; + + // Negative exponent? + if (e < 0) { + + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } + + return str; + } + + + // EXPORT + + + BigNumber = clone(); + BigNumber['default'] = BigNumber.BigNumber = BigNumber; + + // AMD. + if (typeof define == 'function' && define.amd) { + define(function () { return BigNumber; }); + + // Node.js and other environments that support module.exports. + } else if (typeof module != 'undefined' && module.exports) { + module.exports = BigNumber; + + // Browser. + } else { + if (!globalObject) { + globalObject = typeof self != 'undefined' && self ? self : window; + } + + globalObject.BigNumber = BigNumber; + } +})(this); diff --git a/node_modules/bignumber.js/bignumber.mjs b/node_modules/bignumber.js/bignumber.mjs new file mode 100644 index 0000000..31d910b --- /dev/null +++ b/node_modules/bignumber.js/bignumber.mjs @@ -0,0 +1,2907 @@ +/* + * bignumber.js v9.3.1 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2025 Michael Mclaughlin + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | sum + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ + + +var + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, + + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 + + +/* + * Create and return a BigNumber constructor. + */ +function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), + + + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + + + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + suffix: '' + }, + + // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', + // '-', '.', whitespace, or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz', + alphabetHasNormalDecimalDigits = true; + + + //------------------------------------------------------------------------------------------ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * v {number|string|BigNumber} A numeric value. + * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(v, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; + + // Enable constructor call without `new`. + if (!(x instanceof BigNumber)) return new BigNumber(v, b); + + if (b == null) { + + if (v && v._isBigNumber === true) { + x.s = v.s; + + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } + + return; + } + + if ((isNum = typeof v == 'number') && v * 0 == 0) { + + // Use `1 / n` to handle minus zero also. + x.s = 1 / v < 0 ? (v = -v, -1) : 1; + + // Fast path for integers, where n < 2147483648 (2**31). + if (v === ~~v) { + for (e = 0, i = v; i >= 10; i /= 10, e++); + + if (e > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e; + x.c = [v]; + } + + return; + } + + str = String(v); + } else { + + if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); + + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + } else { + + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); + + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10 && alphabetHasNormalDecimalDigits) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + + str = String(v); + + if (isNum = typeof v == 'number') { + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); + + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + v); + } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + + alphabet = ALPHABET.slice(0, b); + e = i = 0; + + // Check that str is a valid base b number. + // Don't use RegExp, so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + + return parseNumeric(x, String(v), isNum, b); + } + } + + // Prevent later check for length on converted number. + isNum = false; + str = convertBase(str, b, 10, x.s); + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); + + if (str = str.slice(i, ++len)) { + len -= i; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error + (tooManyDigits + (x.s * v)); + } + + // Overflow? + if ((e = e - i - 1) > MAX_EXP) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; // i < 1 + + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); + + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } + + for (; i--; str += '0'); + x.c.push(+str); + } + } else { + + // Zero. + x.c = [x.e = 0]; + } + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * prefix {string} + * groupSize {number} + * secondaryGroupSize {number} + * groupSeparator {string} + * decimalSeparator {string} + * fractionGroupSize {number} + * fractionGroupSeparator {string} + * suffix {string} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + + if (typeof obj == 'object') { + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } + + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if less than two characters, + // or if it contains '+', '-', '.', whitespace, or a repeated character. + if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { + alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789'; + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); + } + } + + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + + + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. + * + * v {any} + * + * '[BigNumber Error] Invalid BigNumber: {v}' + */ + BigNumber.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber.DEBUG) return true; + + var i, n, + c = v.c, + e = v.e, + s = v.s; + + out: if ({}.toString.call(c) == '[object Array]') { + + if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { + + // If the first element is zero, the BigNumber value must be zero. + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } + + // Calculate number of digits that c[0] should have, based on the exponent. + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; + + // Calculate number of digits of c[0]. + //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { + if (String(c[0]).length == i) { + + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; + } + + // Last element cannot be zero, unless it is the only element. + if (n !== 0) return true; + } + } + + // Infinity/NaN + } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { + return true; + } + + throw Error + (bignumberError + 'Invalid BigNumber: ' + v); + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, -1); + }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, 1); + }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); + + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes(k *= 7); + + for (; i < k;) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } + + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); + + // Zero? + if (i < 0) { + c = [e = 0]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + /* + * Return a BigNumber whose value is the sum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber(args[0]); + for (; i < args.length;) sum = sum.plus(args[i++]); + return sum; + }; + + + // PRIVATE FUNCTIONS + + + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + + arr[0] += alphabet.indexOf(str.charAt(i++)); + + for (j = 0; j < arr.length; j++) { + + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; + } + + // Convert the number as integer. + + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); + + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; + + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); + + // Zero? + if (!xc[0]) return alphabet.charAt(0); + + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; + + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } + + // xc now represents str converted to baseOut. + + // The index of the rounding digit. + d = e + dp + 1; + + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; + + // Look at the rounding digits and mode to determine whether to round up. + + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); + + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { + + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + + // Truncate xc to the required number of decimal places. + xc.length = d; + + // Round up? + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; + + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); + + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); + } + + // The caller will add the sign. + return str; + }; + })(); + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare(a, b, aL, bL) { + var i, cmp; + + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + + for (i = cmp = 0; i < aL; i++) { + + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return cmp; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } + + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); + + if (yc[i] > (xc[i] || 0)) e--; + + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); + + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); + + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if (prodL < remL) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + + // If product was < remainder. + if (cmp == -1) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + + more = rem[0] != null; + + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } + + if (base == BASE) { + + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; + + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + if (!n.c) return n.toString(); + + c0 = n.c[0]; + ne = n.e; + + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString(n.c); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); + + // Fixed-point notation. + } else { + i -= ne + (id === 2 && e > ne); + str = toFixedPoint(str, e, '0'); + + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + // If any number is NaN, return NaN. + function maxOrMin(args, n) { + var k, y, + i = 1, + x = new BigNumber(args[0]); + + for (; i < args.length; i++) { + y = new BigNumber(args[i]); + if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) { + x = y; + } + } + + return x; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for (; !c[--j]; c.pop()); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); + + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); + + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } + + if (str != s) return new BigNumber(s, base); + } + + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } + + // NaN + x.s = null; + } + + x.c = x.e = null; + } + })(); + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + + // Get the rounding digit at index j of n. + rd = mathfloor(n / pows10[d - j - 1] % 10); + } else { + ni = mathceil((i + 1) / LOG_BASE); + + if (ni >= xc.length) { + + if (r) { + + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10); + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xc[0]) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + + // Round up? + if (r) { + + for (; ;) { + + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } + + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; + + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } + + return x; + } + + + function valueOf(n) { + var str, + e = n.e; + + if (e === null) return n.toString(); + + str = coeffToString(n.c); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + + + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; + + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), dp + x.e + 1, rm); + } + + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; + + n = new BigNumber(n); + + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + valueOf(n)); + } + + if (m != null) m = new BigNumber(m); + + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; + + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n))); + return m ? y.mod(m) : y; + } + + nIsNeg = n.s < 0; + + if (m) { + + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + + if (isModExp) x = x.mod(m); + + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; + + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; + + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); + + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } + + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; + } + + y = new BigNumber(ONE); + + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { + + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; + + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + + if (i) { + i = mathfloor(i / 2); + if (i === 0) break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); + + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) break; + nIsOdd = i % 2; + } + } + + x = x.times(x); + + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } + + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + + // Either zero? + if (!xc[0] || !yc[0]) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if (a = xe - ye) { + + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) { + t = xc; + xc = yc; + yc = t; + y.s = -y.s; + } + + b = (j = yc.length) - (i = xc.length); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; + + // Subtract yc from xc. + for (; j > a;) { + + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); + + // Zero? + if (!xc[0]) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; + + y = new BigNumber(y, b); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } + + if (MODULO_MODE == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } + + y = x.minus(q.times(y)); + + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + + return y; + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; + + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i = xcL; + xcL = ycL; + ycL = i; + } + + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); + + base = BASE; + sqrtBase = SQRT_BASE; + + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise(y, zc, e); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) { + t = yc; + yc = xc; + xc = t; + b = a; + } + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; + + + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; + + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), sd, rm); + } + + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if (v = c[v]) { + + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); + + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + + if (sd && x.e + 1 > n) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + + + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + + // Initial estimate. + s = Math.sqrt(+valueOf(x)); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(+n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; + + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the format or FORMAT object (see BigNumber.set). + * + * The formatting object may contain some or all of the properties shown below. + * + * FORMAT = { + * prefix: '', + * groupSize: 3, + * secondaryGroupSize: 0, + * groupSeparator: ',', + * decimalSeparator: '.', + * fractionGroupSize: 0, + * fractionGroupSeparator: '\xA0', // non-breaking space + * suffix: '' + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * [format] {object} Formatting options. See FORMAT pbject above. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + * '[BigNumber Error] Argument not an object: {format}' + */ + P.toFormat = function (dp, rm, format) { + var str, + x = this; + + if (format == null) { + if (dp != null && rm && typeof rm == 'object') { + format = rm; + rm = null; + } else if (dp && typeof dp == 'object') { + format = dp; + dp = rm = null; + } else { + format = FORMAT; + } + } else if (typeof format != 'object') { + throw Error + (bignumberError + 'Argument not an object: ' + format); + } + + str = x.toFixed(dp, rm); + + if (x.c) { + var i, + arr = str.split('.'), + g1 = +format.groupSize, + g2 = +format.secondaryGroupSize, + groupSeparator = format.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) { + i = g1; + g1 = g2; + g2 = i; + len -= i; + } + + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + (format.fractionGroupSeparator || '')) + : fractionPart) + : intPart; + } + + return (format.prefix || '') + str + (format.suffix || ''); + }; + + + /* + * Return an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to the specified + * maximum denominator. If a maximum denominator is not specified, the denominator will be + * the lowest value necessary to represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); + + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); + } + } + + if (!xc) return new BigNumber(x); + + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e = e * 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + + MAX_EXP = exp; + + return r; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +valueOf(this); + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if (e === null) { + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(coeffToString(n.c), e) + : toFixedPoint(coeffToString(n.c), e, '0'); + } else if (b === 10 && alphabetHasNormalDecimalDigits) { + n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); + } + + if (s < 0 && n.c[0]) str = '-' + str; + } + + return str; + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + return valueOf(this); + }; + + + P._isBigNumber = true; + + P[Symbol.toStringTag] = 'BigNumber'; + + // Node.js v10.12.0+ + P[Symbol.for('nodejs.util.inspect.custom')] = P.valueOf; + + if (configObject != null) BigNumber.set(configObject); + + return BigNumber; +} + + +// PRIVATE HELPER FUNCTIONS + +// These functions don't need access to variables, +// e.g. DECIMAL_PLACES, in the scope of the `clone` function above. + + +function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; +} + + +// Return a coefficient array as a string of base 10 digits. +function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; + } + + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); + + return r.slice(0, j + 1 || 1); +} + + +// Compare the value of BigNumbers x and y. +function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if (!i || !j) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; + + // Signs differ? + if (i != j) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; + + j = (k = xc.length) < (l = yc.length) ? k : l; + + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; +} + + +/* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ +function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + String(n)); + } +} + + +// Assumes finite n. +function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; +} + + +function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; +} + + +function toFixedPoint(str, e, z) { + var len, zs; + + // Negative exponent? + if (e < 0) { + + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } + + return str; +} + + +// EXPORT + + +export var BigNumber = clone(); + +export default BigNumber; diff --git a/node_modules/bignumber.js/doc/API.html b/node_modules/bignumber.js/doc/API.html new file mode 100644 index 0000000..bb2b7dd --- /dev/null +++ b/node_modules/bignumber.js/doc/API.html @@ -0,0 +1,2249 @@ + + + + + + +bignumber.js API + + + + + + +
                          + +

                          bignumber.js

                          + +

                          A JavaScript library for arbitrary-precision arithmetic.

                          +

                          Hosted on GitHub.

                          + +

                          API

                          + +

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

                          +

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

                          + + +

                          CONSTRUCTOR

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

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

                          +

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

                          +

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

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

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

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

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

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

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

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

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

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

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

                          +

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

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

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

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

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

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

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

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

                          Methods

                          +

                          The static methods of a BigNumber constructor.

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

                          object: object

                          +

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

                          +

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

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

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

                          +

                          Configures the settings for this particular BigNumber constructor.

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

                          +

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

                          +

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

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

                          value: any

                          +

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

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

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

                          +

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

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

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

                          +

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

                          +

                          The return value is always exact and unrounded.

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

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

                          +

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

                          +

                          The return value is always exact and unrounded.

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

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

                          +

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

                          +

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

                          +

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

                          +

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

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

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

                          +

                          + Throws if dp is invalid. See Errors. +

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

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

                          +

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

                          +

                          The return value is always exact and unrounded.

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

                          Properties

                          +

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

                          +

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

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

                          undefined|false|true

                          +

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

                          +

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

                          +
                          BigNumber.DEBUG = true
                          + + +

                          INSTANCE

                          + + +

                          Methods

                          +

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

                          +

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

                          +

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

                          +

                          Many method names have a shorter alias.

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

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

                          +

                          The return value is always exact and unrounded.

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

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

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

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

                          +

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

                          +

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

                          +

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

                          +

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

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

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

                          +

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

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

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

                          +

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

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

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

                          +

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

                          +

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

                          +

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

                          +

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

                          +

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

                          +

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

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

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

                          +

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

                          +

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

                          +

                          + Throws if rm is invalid. See Errors. +

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

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

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

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

                          +

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

                          +

                          Note: This method uses the comparedTo method internally.

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

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

                          +

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

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

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

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

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

                          +

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

                          +

                          Note: This method uses the comparedTo method internally.

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

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

                          +

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

                          +

                          Note: This method uses the comparedTo method internally.

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

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

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

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

                          +

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

                          +

                          Note: This method uses the comparedTo method internally.

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

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

                          +

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

                          +

                          Note: This method uses the comparedTo method internally.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                          +

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

                          +

                          The return value is always exact and unrounded.

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

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

                          +

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

                          +

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

                          +

                          The return value is always exact and unrounded.

                          +

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

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

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

                          +

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

                          +

                          The return value is always exact and unrounded.

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

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

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

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

                          +

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

                          +

                          The return value is always exact and unrounded.

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

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

                          +

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

                          +

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

                          +

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

                          +

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

                          +

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

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

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

                          +

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

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

                          +

                          The return value is always exact and unrounded.

                          +

                          + Throws if n is invalid. See Errors. +

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

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

                          +

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

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

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

                          +

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

                          +

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

                          +

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

                          +

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

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

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

                          +

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

                          +

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

                          +

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

                          +

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

                          +

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

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

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

                          +

                          +

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

                          +

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

                          +

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

                          +

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

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

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

                          +

                          + Returns an array of two BigNumbers representing the value of this BigNumber as a simple + fraction with an integer numerator and an integer denominator. The denominator will be a + positive non-zero value less than or equal to maximum_denominator. +

                          +

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

                          +

                          + Throws if maximum_denominator is invalid. See Errors. +

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

                          As valueOf.

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

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

                          +

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

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

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

                          +

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

                          +

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

                          +

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

                          +

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

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

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

                          +

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

                          +

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

                          +

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

                          +

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

                          +

                          If base is null or undefined it is ignored.

                          +

                          + Throws if base is invalid. See Errors. +

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

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

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

                          Properties

                          +

                          The properties of a BigNumber instance:

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

                          *significand

                          +

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

                          +

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

                          +

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

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

                          Zero, NaN and Infinity

                          +

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

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

                          Errors

                          +

                          The table below shows the errors that are thrown.

                          +

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

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

                          *Only thrown if BigNumber.DEBUG is true.

                          +

                          To determine if an exception is a BigNumber Error:

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

                          Type coercion

                          +

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

                          +

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

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

                          FAQ

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

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

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

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

                          +

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

                          +

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

                          +

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

                          +

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

                          +

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

                          +
                          + + + diff --git a/node_modules/bignumber.js/package.json b/node_modules/bignumber.js/package.json new file mode 100644 index 0000000..6b1d95b --- /dev/null +++ b/node_modules/bignumber.js/package.json @@ -0,0 +1,60 @@ +{ + "name": "bignumber.js", + "description": "A library for arbitrary-precision decimal and non-decimal arithmetic", + "version": "9.3.1", + "keywords": [ + "arbitrary", + "precision", + "arithmetic", + "big", + "number", + "decimal", + "float", + "biginteger", + "bigdecimal", + "bignumber", + "bigint", + "bignum" + ], + "repository": { + "type": "git", + "url": "https://github.com/MikeMcl/bignumber.js.git" + }, + "main": "bignumber", + "module": "bignumber.mjs", + "browser": "bignumber.js", + "types": "bignumber.d.ts", + "exports": { + ".": { + "import": { + "types": "./bignumber.d.mts", + "default": "./bignumber.mjs" + }, + "require": { + "types": "./bignumber.d.ts", + "default": "./bignumber.js" + }, + "browser": { + "types": "./bignumber.d.ts", + "default": "./bignumber.js" + }, + "default": { + "types": "./bignumber.d.ts", + "default": "./bignumber.js" + } + }, + "./package.json": "./package.json" + }, + "author": { + "name": "Michael Mclaughlin", + "email": "M8ch88l@gmail.com" + }, + "engines": { + "node": "*" + }, + "license": "MIT", + "scripts": { + "test": "node test/test" + }, + "dependencies": {} +} diff --git a/node_modules/bignumber.js/types.d.ts b/node_modules/bignumber.js/types.d.ts new file mode 100644 index 0000000..8145edd --- /dev/null +++ b/node_modules/bignumber.js/types.d.ts @@ -0,0 +1,1821 @@ +// Type definitions for bignumber.js >=8.1.0 +// Project: https://github.com/MikeMcl/bignumber.js +// Definitions by: Michael Mclaughlin +// Definitions: https://github.com/MikeMcl/bignumber.js + +// Documentation: http://mikemcl.github.io/bignumber.js/ +// +// class BigNumber +// type BigNumber.Constructor +// type BigNumber.ModuloMode +// type BigNumber.RoundingMode +// type BigNumber.Value +// interface BigNumber.Config +// interface BigNumber.Format +// interface BigNumber.Instance +// +// Example: +// +// import {BigNumber} from "bignumber.js" +// //import BigNumber from "bignumber.js" +// +// let rm: BigNumber.RoundingMode = BigNumber.ROUND_UP; +// let f: BigNumber.Format = { decimalSeparator: ',' }; +// let c: BigNumber.Config = { DECIMAL_PLACES: 4, ROUNDING_MODE: rm, FORMAT: f }; +// BigNumber.config(c); +// +// let v: BigNumber.Value = '12345.6789'; +// let b: BigNumber = new BigNumber(v); +// +// The use of compiler option `--strictNullChecks` is recommended. + +declare namespace BigNumber { + + /** See `BigNumber.config` (alias `BigNumber.set`) and `BigNumber.clone`. */ + interface Config { + + /** + * An integer, 0 to 1e+9. Default value: 20. + * + * The maximum number of decimal places of the result of operations involving division, i.e. + * division, square root and base conversion operations, and exponentiation when the exponent is + * negative. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * BigNumber.set({ DECIMAL_PLACES: 5 }) + * ``` + */ + DECIMAL_PLACES?: number; + + /** + * An integer, 0 to 8. Default value: `BigNumber.ROUND_HALF_UP` (4). + * + * The rounding mode used in operations that involve division (see `DECIMAL_PLACES`) and the + * default rounding mode of the `decimalPlaces`, `precision`, `toExponential`, `toFixed`, + * `toFormat` and `toPrecision` methods. + * + * The modes are available as enumerated properties of the BigNumber constructor. + * + * ```ts + * BigNumber.config({ ROUNDING_MODE: 0 }) + * BigNumber.set({ ROUNDING_MODE: BigNumber.ROUND_UP }) + * ``` + */ + ROUNDING_MODE?: BigNumber.RoundingMode; + + /** + * An integer, 0 to 1e+9, or an array, [-1e+9 to 0, 0 to 1e+9]. + * Default value: `[-7, 20]`. + * + * The exponent value(s) at which `toString` returns exponential notation. + * + * If a single number is assigned, the value is the exponent magnitude. + * + * If an array of two numbers is assigned then the first number is the negative exponent value at + * and beneath which exponential notation is used, and the second number is the positive exponent + * value at and above which exponential notation is used. + * + * For example, to emulate JavaScript numbers in terms of the exponent values at which they begin + * to use exponential notation, use `[-7, 20]`. + * + * ```ts + * BigNumber.config({ EXPONENTIAL_AT: 2 }) + * new BigNumber(12.3) // '12.3' e is only 1 + * new BigNumber(123) // '1.23e+2' + * new BigNumber(0.123) // '0.123' e is only -1 + * new BigNumber(0.0123) // '1.23e-2' + * + * BigNumber.config({ EXPONENTIAL_AT: [-7, 20] }) + * new BigNumber(123456789) // '123456789' e is only 8 + * new BigNumber(0.000000123) // '1.23e-7' + * + * // Almost never return exponential notation: + * BigNumber.config({ EXPONENTIAL_AT: 1e+9 }) + * + * // Always return exponential notation: + * BigNumber.config({ EXPONENTIAL_AT: 0 }) + * ``` + * + * Regardless of the value of `EXPONENTIAL_AT`, the `toFixed` method will always return a value in + * normal notation and the `toExponential` method will always return a value in exponential form. + * Calling `toString` with a base argument, e.g. `toString(10)`, will also always return normal + * notation. + */ + EXPONENTIAL_AT?: number | [number, number]; + + /** + * An integer, magnitude 1 to 1e+9, or an array, [-1e+9 to -1, 1 to 1e+9]. + * Default value: `[-1e+9, 1e+9]`. + * + * The exponent value(s) beyond which overflow to Infinity and underflow to zero occurs. + * + * If a single number is assigned, it is the maximum exponent magnitude: values wth a positive + * exponent of greater magnitude become Infinity and those with a negative exponent of greater + * magnitude become zero. + * + * If an array of two numbers is assigned then the first number is the negative exponent limit and + * the second number is the positive exponent limit. + * + * For example, to emulate JavaScript numbers in terms of the exponent values at which they + * become zero and Infinity, use [-324, 308]. + * + * ```ts + * BigNumber.config({ RANGE: 500 }) + * BigNumber.config().RANGE // [ -500, 500 ] + * new BigNumber('9.999e499') // '9.999e+499' + * new BigNumber('1e500') // 'Infinity' + * new BigNumber('1e-499') // '1e-499' + * new BigNumber('1e-500') // '0' + * + * BigNumber.config({ RANGE: [-3, 4] }) + * new BigNumber(99999) // '99999' e is only 4 + * new BigNumber(100000) // 'Infinity' e is 5 + * new BigNumber(0.001) // '0.01' e is only -3 + * new BigNumber(0.0001) // '0' e is -4 + * ``` + * The largest possible magnitude of a finite BigNumber is 9.999...e+1000000000. + * The smallest possible magnitude of a non-zero BigNumber is 1e-1000000000. + */ + RANGE?: number | [number, number]; + + /** + * A boolean: `true` or `false`. Default value: `false`. + * + * The value that determines whether cryptographically-secure pseudo-random number generation is + * used. If `CRYPTO` is set to true then the random method will generate random digits using + * `crypto.getRandomValues` in browsers that support it, or `crypto.randomBytes` if using a + * version of Node.js that supports it. + * + * If neither function is supported by the host environment then attempting to set `CRYPTO` to + * `true` will fail and an exception will be thrown. + * + * If `CRYPTO` is `false` then the source of randomness used will be `Math.random` (which is + * assumed to generate at least 30 bits of randomness). + * + * See `BigNumber.random`. + * + * ```ts + * // Node.js + * global.crypto = require('crypto') + * + * BigNumber.config({ CRYPTO: true }) + * BigNumber.config().CRYPTO // true + * BigNumber.random() // 0.54340758610486147524 + * ``` + */ + CRYPTO?: boolean; + + /** + * An integer, 0, 1, 3, 6 or 9. Default value: `BigNumber.ROUND_DOWN` (1). + * + * The modulo mode used when calculating the modulus: `a mod n`. + * The quotient, `q = a / n`, is calculated according to the `ROUNDING_MODE` that corresponds to + * the chosen `MODULO_MODE`. + * The remainder, `r`, is calculated as: `r = a - n * q`. + * + * The modes that are most commonly used for the modulus/remainder operation are shown in the + * following table. Although the other rounding modes can be used, they may not give useful + * results. + * + * Property | Value | Description + * :------------------|:------|:------------------------------------------------------------------ + * `ROUND_UP` | 0 | The remainder is positive if the dividend is negative. + * `ROUND_DOWN` | 1 | The remainder has the same sign as the dividend. + * | | Uses 'truncating division' and matches JavaScript's `%` operator . + * `ROUND_FLOOR` | 3 | The remainder has the same sign as the divisor. + * | | This matches Python's `%` operator. + * `ROUND_HALF_EVEN` | 6 | The IEEE 754 remainder function. + * `EUCLID` | 9 | The remainder is always positive. + * | | Euclidian division: `q = sign(n) * floor(a / abs(n))` + * + * The rounding/modulo modes are available as enumerated properties of the BigNumber constructor. + * + * See `modulo`. + * + * ```ts + * BigNumber.config({ MODULO_MODE: BigNumber.EUCLID }) + * BigNumber.set({ MODULO_MODE: 9 }) // equivalent + * ``` + */ + MODULO_MODE?: BigNumber.ModuloMode; + + /** + * An integer, 0 to 1e+9. Default value: 0. + * + * The maximum precision, i.e. number of significant digits, of the result of the power operation + * - unless a modulus is specified. + * + * If set to 0, the number of significant digits will not be limited. + * + * See `exponentiatedBy`. + * + * ```ts + * BigNumber.config({ POW_PRECISION: 100 }) + * ``` + */ + POW_PRECISION?: number; + + /** + * An object including any number of the properties shown below. + * + * The object configures the format of the string returned by the `toFormat` method. + * The example below shows the properties of the object that are recognised, and + * their default values. + * + * Unlike the other configuration properties, the values of the properties of the `FORMAT` object + * will not be checked for validity - the existing object will simply be replaced by the object + * that is passed in. + * + * See `toFormat`. + * + * ```ts + * BigNumber.config({ + * FORMAT: { + * // string to prepend + * prefix: '', + * // the decimal separator + * decimalSeparator: '.', + * // the grouping separator of the integer part + * groupSeparator: ',', + * // the primary grouping size of the integer part + * groupSize: 3, + * // the secondary grouping size of the integer part + * secondaryGroupSize: 0, + * // the grouping separator of the fraction part + * fractionGroupSeparator: ' ', + * // the grouping size of the fraction part + * fractionGroupSize: 0, + * // string to append + * suffix: '' + * } + * }) + * ``` + */ + FORMAT?: BigNumber.Format; + + /** + * The alphabet used for base conversion. The length of the alphabet corresponds to the maximum + * value of the base argument that can be passed to the BigNumber constructor or `toString`. + * + * Default value: `'0123456789abcdefghijklmnopqrstuvwxyz'`. + * + * There is no maximum length for the alphabet, but it must be at least 2 characters long, + * and it must not contain whitespace or a repeated character, or the sign indicators '+' and + * '-', or the decimal separator '.'. + * + * ```ts + * // duodecimal (base 12) + * BigNumber.config({ ALPHABET: '0123456789TE' }) + * x = new BigNumber('T', 12) + * x.toString() // '10' + * x.toString(12) // 'T' + * ``` + */ + ALPHABET?: string; + } + + /** See `FORMAT` and `toFormat`. */ + interface Format { + + /** The string to prepend. */ + prefix?: string; + + /** The decimal separator. */ + decimalSeparator?: string; + + /** The grouping separator of the integer part. */ + groupSeparator?: string; + + /** The primary grouping size of the integer part. */ + groupSize?: number; + + /** The secondary grouping size of the integer part. */ + secondaryGroupSize?: number; + + /** The grouping separator of the fraction part. */ + fractionGroupSeparator?: string; + + /** The grouping size of the fraction part. */ + fractionGroupSize?: number; + + /** The string to append. */ + suffix?: string; + } + + interface Instance { + + /** The coefficient of the value of this BigNumber, an array of base 1e14 integer numbers, or null. */ + readonly c: number[] | null; + + /** The exponent of the value of this BigNumber, an integer number, -1000000000 to 1000000000, or null. */ + readonly e: number | null; + + /** The sign of the value of this BigNumber, -1, 1, or null. */ + readonly s: number | null; + + [key: string]: any; + } + + type Constructor = typeof BigNumber; + type ModuloMode = 0 | 1 | 3 | 6 | 9; + type RoundingMode = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; + type Value = string | number | bigint | Instance; +} + +declare class BigNumber implements BigNumber.Instance { + + /** Used internally to identify a BigNumber instance. */ + private readonly _isBigNumber: true; + + /** The coefficient of the value of this BigNumber, an array of base 1e14 integer numbers, or null. */ + readonly c: number[] | null; + + /** The exponent of the value of this BigNumber, an integer number, -1000000000 to 1000000000, or null. */ + readonly e: number | null; + + /** The sign of the value of this BigNumber, -1, 1, or null. */ + readonly s: number | null; + + /** + * Returns a new instance of a BigNumber object with value `n`, where `n` is a numeric value in + * the specified `base`, or base 10 if `base` is omitted. + * + * ```ts + * x = new BigNumber(123.4567) // '123.4567' + * // 'new' is optional + * y = BigNumber(x) // '123.4567' + * ``` + * + * If `n` is a base 10 value it can be in normal (fixed-point) or exponential notation. + * Values in other bases must be in normal notation. Values in any base can have fraction digits, + * i.e. digits after the decimal point. + * + * ```ts + * new BigNumber(43210) // '43210' + * new BigNumber('4.321e+4') // '43210' + * new BigNumber('-735.0918e-430') // '-7.350918e-428' + * new BigNumber('123412421.234324', 5) // '607236.557696' + * ``` + * + * Signed `0`, signed `Infinity` and `NaN` are supported. + * + * ```ts + * new BigNumber('-Infinity') // '-Infinity' + * new BigNumber(NaN) // 'NaN' + * new BigNumber(-0) // '0' + * new BigNumber('.5') // '0.5' + * new BigNumber('+2') // '2' + * ``` + * + * String values in hexadecimal literal form, e.g. `'0xff'`, are valid, as are string values with + * the octal and binary prefixs `'0o'` and `'0b'`. String values in octal literal form without the + * prefix will be interpreted as decimals, e.g. `'011'` is interpreted as 11, not 9. + * + * ```ts + * new BigNumber(-10110100.1, 2) // '-180.5' + * new BigNumber('-0b10110100.1') // '-180.5' + * new BigNumber('ff.8', 16) // '255.5' + * new BigNumber('0xff.8') // '255.5' + * ``` + * + * If a base is specified, `n` is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings. This includes base 10, so don't include a `base` parameter for decimal + * values unless this behaviour is desired. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * new BigNumber(1.23456789) // '1.23456789' + * new BigNumber(1.23456789, 10) // '1.23457' + * ``` + * + * An error is thrown if `base` is invalid. + * + * There is no limit to the number of digits of a value of type string (other than that of + * JavaScript's maximum array size). See `RANGE` to set the maximum and minimum possible exponent + * value of a BigNumber. + * + * ```ts + * new BigNumber('5032485723458348569331745.33434346346912144534543') + * new BigNumber('4.321e10000000') + * ``` + * + * BigNumber `NaN` is returned if `n` is invalid (unless `BigNumber.DEBUG` is `true`, see below). + * + * ```ts + * new BigNumber('.1*') // 'NaN' + * new BigNumber('blurgh') // 'NaN' + * new BigNumber(9, 2) // 'NaN' + * ``` + * + * To aid in debugging, if `BigNumber.DEBUG` is `true` then an error will be thrown on an + * invalid `n`. An error will also be thrown if `n` is of type number with more than 15 + * significant digits, as calling `toString` or `valueOf` on these numbers may not result in the + * intended value. + * + * ```ts + * console.log(823456789123456.3) // 823456789123456.2 + * new BigNumber(823456789123456.3) // '823456789123456.2' + * BigNumber.DEBUG = true + * // 'Error: Number has more than 15 significant digits' + * new BigNumber(823456789123456.3) + * // 'Error: Not a base 2 number' + * new BigNumber(9, 2) + * ``` + * + * A BigNumber can also be created from an object literal. + * Use `isBigNumber` to check that it is well-formed. + * + * ```ts + * new BigNumber({ s: 1, e: 2, c: [ 777, 12300000000000 ], _isBigNumber: true }) // '777.123' + * ``` + * + * @param n A numeric value. + * @param base The base of `n`, integer, 2 to 36 (or `ALPHABET.length`, see `ALPHABET`). + */ + constructor(n: BigNumber.Value, base?: number); + + /** + * Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of this + * BigNumber. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber(-0.8) + * x.absoluteValue() // '0.8' + * ``` + */ + absoluteValue(): BigNumber; + + /** + * Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of this + * BigNumber. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber(-0.8) + * x.abs() // '0.8' + * ``` + */ + abs(): BigNumber; + + /** + * Returns | | + * :-------:|:--------------------------------------------------------------| + * 1 | If the value of this BigNumber is greater than the value of `n` + * -1 | If the value of this BigNumber is less than the value of `n` + * 0 | If this BigNumber and `n` have the same value + * `null` | If the value of either this BigNumber or `n` is `NaN` + * + * ```ts + * + * x = new BigNumber(Infinity) + * y = new BigNumber(5) + * x.comparedTo(y) // 1 + * x.comparedTo(x.minus(1)) // 0 + * y.comparedTo(NaN) // null + * y.comparedTo('110', 2) // -1 + * ``` + * @param n A numeric value. + * @param [base] The base of n. + */ + comparedTo(n: BigNumber.Value, base?: number): 1 | -1 | 0 | null; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded by rounding mode + * `roundingMode` to a maximum of `decimalPlaces` decimal places. + * + * If `decimalPlaces` is omitted, the return value is the number of decimal places of the value of + * this BigNumber, or `null` if the value of this BigNumber is ±`Infinity` or `NaN`. + * + * If `roundingMode` is omitted, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(1234.56) + * x.decimalPlaces() // 2 + * x.decimalPlaces(1) // '1234.6' + * x.decimalPlaces(2) // '1234.56' + * x.decimalPlaces(10) // '1234.56' + * x.decimalPlaces(0, 1) // '1234' + * x.decimalPlaces(0, 6) // '1235' + * x.decimalPlaces(1, 1) // '1234.5' + * x.decimalPlaces(1, BigNumber.ROUND_HALF_EVEN) // '1234.6' + * x // '1234.56' + * y = new BigNumber('9.9e-101') + * y.decimalPlaces() // 102 + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + decimalPlaces(): number | null; + decimalPlaces(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded by rounding mode + * `roundingMode` to a maximum of `decimalPlaces` decimal places. + * + * If `decimalPlaces` is omitted, the return value is the number of decimal places of the value of + * this BigNumber, or `null` if the value of this BigNumber is ±`Infinity` or `NaN`. + * + * If `roundingMode` is omitted, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(1234.56) + * x.dp() // 2 + * x.dp(1) // '1234.6' + * x.dp(2) // '1234.56' + * x.dp(10) // '1234.56' + * x.dp(0, 1) // '1234' + * x.dp(0, 6) // '1235' + * x.dp(1, 1) // '1234.5' + * x.dp(1, BigNumber.ROUND_HALF_EVEN) // '1234.6' + * x // '1234.56' + * y = new BigNumber('9.9e-101') + * y.dp() // 102 + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + dp(): number | null; + dp(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber divided by `n`, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * ```ts + * x = new BigNumber(355) + * y = new BigNumber(113) + * x.dividedBy(y) // '3.14159292035398230088' + * x.dividedBy(5) // '71' + * x.dividedBy(47, 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + dividedBy(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber divided by `n`, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * ```ts + * x = new BigNumber(355) + * y = new BigNumber(113) + * x.div(y) // '3.14159292035398230088' + * x.div(5) // '71' + * x.div(47, 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + div(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the integer part of dividing the value of this BigNumber by + * `n`. + * + * ```ts + * x = new BigNumber(5) + * y = new BigNumber(3) + * x.dividedToIntegerBy(y) // '1' + * x.dividedToIntegerBy(0.7) // '7' + * x.dividedToIntegerBy('0.f', 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + dividedToIntegerBy(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the integer part of dividing the value of this BigNumber by + * `n`. + * + * ```ts + * x = new BigNumber(5) + * y = new BigNumber(3) + * x.idiv(y) // '1' + * x.idiv(0.7) // '7' + * x.idiv('0.f', 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + idiv(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber exponentiated by `n`, i.e. + * raised to the power `n`, and optionally modulo a modulus `m`. + * + * If `n` is negative the result is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings. + * + * As the number of digits of the result of the power operation can grow so large so quickly, + * e.g. 123.456**10000 has over 50000 digits, the number of significant digits calculated is + * limited to the value of the `POW_PRECISION` setting (unless a modulus `m` is specified). + * + * By default `POW_PRECISION` is set to 0. This means that an unlimited number of significant + * digits will be calculated, and that the method's performance will decrease dramatically for + * larger exponents. + * + * If `m` is specified and the value of `m`, `n` and this BigNumber are integers and `n` is + * positive, then a fast modular exponentiation algorithm is used, otherwise the operation will + * be performed as `x.exponentiatedBy(n).modulo(m)` with a `POW_PRECISION` of 0. + * + * Throws if `n` is not an integer. + * + * ```ts + * Math.pow(0.7, 2) // 0.48999999999999994 + * x = new BigNumber(0.7) + * x.exponentiatedBy(2) // '0.49' + * BigNumber(3).exponentiatedBy(-2) // '0.11111111111111111111' + * ``` + * + * @param n The exponent, an integer. + * @param [m] The modulus. + */ + exponentiatedBy(n: BigNumber.Value, m?: BigNumber.Value): BigNumber; + exponentiatedBy(n: number, m?: BigNumber.Value): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber exponentiated by `n`, i.e. + * raised to the power `n`, and optionally modulo a modulus `m`. + * + * If `n` is negative the result is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings. + * + * As the number of digits of the result of the power operation can grow so large so quickly, + * e.g. 123.456**10000 has over 50000 digits, the number of significant digits calculated is + * limited to the value of the `POW_PRECISION` setting (unless a modulus `m` is specified). + * + * By default `POW_PRECISION` is set to 0. This means that an unlimited number of significant + * digits will be calculated, and that the method's performance will decrease dramatically for + * larger exponents. + * + * If `m` is specified and the value of `m`, `n` and this BigNumber are integers and `n` is + * positive, then a fast modular exponentiation algorithm is used, otherwise the operation will + * be performed as `x.pow(n).modulo(m)` with a `POW_PRECISION` of 0. + * + * Throws if `n` is not an integer. + * + * ```ts + * Math.pow(0.7, 2) // 0.48999999999999994 + * x = new BigNumber(0.7) + * x.pow(2) // '0.49' + * BigNumber(3).pow(-2) // '0.11111111111111111111' + * ``` + * + * @param n The exponent, an integer. + * @param [m] The modulus. + */ + pow(n: BigNumber.Value, m?: BigNumber.Value): BigNumber; + pow(n: number, m?: BigNumber.Value): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to an integer using + * rounding mode `rm`. + * + * If `rm` is omitted, `ROUNDING_MODE` is used. + * + * Throws if `rm` is invalid. + * + * ```ts + * x = new BigNumber(123.456) + * x.integerValue() // '123' + * x.integerValue(BigNumber.ROUND_CEIL) // '124' + * y = new BigNumber(-12.7) + * y.integerValue() // '-13' + * x.integerValue(BigNumber.ROUND_DOWN) // '-12' + * ``` + * + * @param {BigNumber.RoundingMode} [rm] The roundng mode, an integer, 0 to 8. + */ + integerValue(rm?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns `true` if the value of this BigNumber is equal to the value of `n`, otherwise returns + * `false`. + * + * As with JavaScript, `NaN` does not equal `NaN`. + * + * ```ts + * 0 === 1e-324 // true + * x = new BigNumber(0) + * x.isEqualTo('1e-324') // false + * BigNumber(-0).isEqualTo(x) // true ( -0 === 0 ) + * BigNumber(255).isEqualTo('ff', 16) // true + * + * y = new BigNumber(NaN) + * y.isEqualTo(NaN) // false + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isEqualTo(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is equal to the value of `n`, otherwise returns + * `false`. + * + * As with JavaScript, `NaN` does not equal `NaN`. + * + * ```ts + * 0 === 1e-324 // true + * x = new BigNumber(0) + * x.eq('1e-324') // false + * BigNumber(-0).eq(x) // true ( -0 === 0 ) + * BigNumber(255).eq('ff', 16) // true + * + * y = new BigNumber(NaN) + * y.eq(NaN) // false + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + eq(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is a finite number, otherwise returns `false`. + * + * The only possible non-finite values of a BigNumber are `NaN`, `Infinity` and `-Infinity`. + * + * ```ts + * x = new BigNumber(1) + * x.isFinite() // true + * y = new BigNumber(Infinity) + * y.isFinite() // false + * ``` + */ + isFinite(): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than the value of `n`, otherwise + * returns `false`. + * + * ```ts + * 0.1 > (0.3 - 0.2) // true + * x = new BigNumber(0.1) + * x.isGreaterThan(BigNumber(0.3).minus(0.2)) // false + * BigNumber(0).isGreaterThan(x) // false + * BigNumber(11, 3).isGreaterThan(11.1, 2) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isGreaterThan(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than the value of `n`, otherwise + * returns `false`. + * + * ```ts + * 0.1 > (0.3 - 0.2) // true + * x = new BigNumber(0.1) + * x.gt(BigNumber(0.3).minus(0.2)) // false + * BigNumber(0).gt(x) // false + * BigNumber(11, 3).gt(11.1, 2) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + gt(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * (0.3 - 0.2) >= 0.1 // false + * x = new BigNumber(0.3).minus(0.2) + * x.isGreaterThanOrEqualTo(0.1) // true + * BigNumber(1).isGreaterThanOrEqualTo(x) // true + * BigNumber(10, 18).isGreaterThanOrEqualTo('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isGreaterThanOrEqualTo(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * (0.3 - 0.2) >= 0.1 // false + * x = new BigNumber(0.3).minus(0.2) + * x.gte(0.1) // true + * BigNumber(1).gte(x) // true + * BigNumber(10, 18).gte('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + gte(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is an integer, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(1) + * x.isInteger() // true + * y = new BigNumber(123.456) + * y.isInteger() // false + * ``` + */ + isInteger(): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than the value of `n`, otherwise returns + * `false`. + * + * ```ts + * (0.3 - 0.2) < 0.1 // true + * x = new BigNumber(0.3).minus(0.2) + * x.isLessThan(0.1) // false + * BigNumber(0).isLessThan(x) // true + * BigNumber(11.1, 2).isLessThan(11, 3) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isLessThan(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than the value of `n`, otherwise returns + * `false`. + * + * ```ts + * (0.3 - 0.2) < 0.1 // true + * x = new BigNumber(0.3).minus(0.2) + * x.lt(0.1) // false + * BigNumber(0).lt(x) // true + * BigNumber(11.1, 2).lt(11, 3) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + lt(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * 0.1 <= (0.3 - 0.2) // false + * x = new BigNumber(0.1) + * x.isLessThanOrEqualTo(BigNumber(0.3).minus(0.2)) // true + * BigNumber(-1).isLessThanOrEqualTo(x) // true + * BigNumber(10, 18).isLessThanOrEqualTo('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isLessThanOrEqualTo(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * 0.1 <= (0.3 - 0.2) // false + * x = new BigNumber(0.1) + * x.lte(BigNumber(0.3).minus(0.2)) // true + * BigNumber(-1).lte(x) // true + * BigNumber(10, 18).lte('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + lte(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is `NaN`, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(NaN) + * x.isNaN() // true + * y = new BigNumber('Infinity') + * y.isNaN() // false + * ``` + */ + isNaN(): boolean; + + /** + * Returns `true` if the value of this BigNumber is negative, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(-0) + * x.isNegative() // true + * y = new BigNumber(2) + * y.isNegative() // false + * ``` + */ + isNegative(): boolean; + + /** + * Returns `true` if the value of this BigNumber is positive, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(-0) + * x.isPositive() // false + * y = new BigNumber(2) + * y.isPositive() // true + * ``` + */ + isPositive(): boolean; + + /** + * Returns `true` if the value of this BigNumber is zero or minus zero, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(-0) + * x.isZero() // true + * ``` + */ + isZero(): boolean; + + /** + * Returns a BigNumber whose value is the value of this BigNumber minus `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.3 - 0.1 // 0.19999999999999998 + * x = new BigNumber(0.3) + * x.minus(0.1) // '0.2' + * x.minus(0.6, 20) // '0' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + minus(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber modulo `n`, i.e. the integer + * remainder of dividing this BigNumber by `n`. + * + * The value returned, and in particular its sign, is dependent on the value of the `MODULO_MODE` + * setting of this BigNumber constructor. If it is 1 (default value), the result will have the + * same sign as this BigNumber, and it will match that of Javascript's `%` operator (within the + * limits of double precision) and BigDecimal's `remainder` method. + * + * The return value is always exact and unrounded. + * + * See `MODULO_MODE` for a description of the other modulo modes. + * + * ```ts + * 1 % 0.9 // 0.09999999999999998 + * x = new BigNumber(1) + * x.modulo(0.9) // '0.1' + * y = new BigNumber(33) + * y.modulo('a', 33) // '3' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + modulo(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber modulo `n`, i.e. the integer + * remainder of dividing this BigNumber by `n`. + * + * The value returned, and in particular its sign, is dependent on the value of the `MODULO_MODE` + * setting of this BigNumber constructor. If it is 1 (default value), the result will have the + * same sign as this BigNumber, and it will match that of Javascript's `%` operator (within the + * limits of double precision) and BigDecimal's `remainder` method. + * + * The return value is always exact and unrounded. + * + * See `MODULO_MODE` for a description of the other modulo modes. + * + * ```ts + * 1 % 0.9 // 0.09999999999999998 + * x = new BigNumber(1) + * x.mod(0.9) // '0.1' + * y = new BigNumber(33) + * y.mod('a', 33) // '3' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + mod(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber multiplied by `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.6 * 3 // 1.7999999999999998 + * x = new BigNumber(0.6) + * y = x.multipliedBy(3) // '1.8' + * BigNumber('7e+500').multipliedBy(y) // '1.26e+501' + * x.multipliedBy('-a', 16) // '-6' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + multipliedBy(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber multiplied by `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.6 * 3 // 1.7999999999999998 + * x = new BigNumber(0.6) + * y = x.times(3) // '1.8' + * BigNumber('7e+500').times(y) // '1.26e+501' + * x.times('-a', 16) // '-6' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + times(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by -1. + * + * ```ts + * x = new BigNumber(1.8) + * x.negated() // '-1.8' + * y = new BigNumber(-1.3) + * y.negated() // '1.3' + * ``` + */ + negated(): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber plus `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.1 + 0.2 // 0.30000000000000004 + * x = new BigNumber(0.1) + * y = x.plus(0.2) // '0.3' + * BigNumber(0.7).plus(x).plus(y) // '1.1' + * x.plus('0.1', 8) // '0.225' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + plus(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns the number of significant digits of the value of this BigNumber, or `null` if the value + * of this BigNumber is ±`Infinity` or `NaN`. + * + * If `includeZeros` is true then any trailing zeros of the integer part of the value of this + * BigNumber are counted as significant digits, otherwise they are not. + * + * Throws if `includeZeros` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.precision() // 9 + * y = new BigNumber(987000) + * y.precision(false) // 3 + * y.precision(true) // 6 + * ``` + * + * @param [includeZeros] Whether to include integer trailing zeros in the significant digit count. + */ + precision(includeZeros?: boolean): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to a precision of + * `significantDigits` significant digits using rounding mode `roundingMode`. + * + * If `roundingMode` is omitted, `ROUNDING_MODE` will be used. + * + * Throws if `significantDigits` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.precision(6) // '9876.54' + * x.precision(6, BigNumber.ROUND_UP) // '9876.55' + * x.precision(2) // '9900' + * x.precision(2, 1) // '9800' + * x // '9876.54321' + * ``` + * + * @param significantDigits Significant digits, integer, 1 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + precision(significantDigits: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns the number of significant digits of the value of this BigNumber, + * or `null` if the value of this BigNumber is ±`Infinity` or `NaN`. + * + * If `includeZeros` is true then any trailing zeros of the integer part of + * the value of this BigNumber are counted as significant digits, otherwise + * they are not. + * + * Throws if `includeZeros` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.sd() // 9 + * y = new BigNumber(987000) + * y.sd(false) // 3 + * y.sd(true) // 6 + * ``` + * + * @param [includeZeros] Whether to include integer trailing zeros in the significant digit count. + */ + sd(includeZeros?: boolean): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to a precision of + * `significantDigits` significant digits using rounding mode `roundingMode`. + * + * If `roundingMode` is omitted, `ROUNDING_MODE` will be used. + * + * Throws if `significantDigits` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.sd(6) // '9876.54' + * x.sd(6, BigNumber.ROUND_UP) // '9876.55' + * x.sd(2) // '9900' + * x.sd(2, 1) // '9800' + * x // '9876.54321' + * ``` + * + * @param significantDigits Significant digits, integer, 1 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + sd(significantDigits: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber shifted by `n` places. + * + * The shift is of the decimal point, i.e. of powers of ten, and is to the left if `n` is negative + * or to the right if `n` is positive. + * + * The return value is always exact and unrounded. + * + * Throws if `n` is invalid. + * + * ```ts + * x = new BigNumber(1.23) + * x.shiftedBy(3) // '1230' + * x.shiftedBy(-3) // '0.00123' + * ``` + * + * @param n The shift value, integer, -9007199254740991 to 9007199254740991. + */ + shiftedBy(n: number): BigNumber; + + /** + * Returns a BigNumber whose value is the square root of the value of this BigNumber, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * The return value will be correctly rounded, i.e. rounded as if the result was first calculated + * to an infinite number of correct digits before rounding. + * + * ```ts + * x = new BigNumber(16) + * x.squareRoot() // '4' + * y = new BigNumber(3) + * y.squareRoot() // '1.73205080756887729353' + * ``` + */ + squareRoot(): BigNumber; + + /** + * Returns a BigNumber whose value is the square root of the value of this BigNumber, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * The return value will be correctly rounded, i.e. rounded as if the result was first calculated + * to an infinite number of correct digits before rounding. + * + * ```ts + * x = new BigNumber(16) + * x.sqrt() // '4' + * y = new BigNumber(3) + * y.sqrt() // '1.73205080756887729353' + * ``` + */ + sqrt(): BigNumber; + + /** + * Returns a string representing the value of this BigNumber in exponential notation rounded using + * rounding mode `roundingMode` to `decimalPlaces` decimal places, i.e with one digit before the + * decimal point and `decimalPlaces` digits after it. + * + * If the value of this BigNumber in exponential notation has fewer than `decimalPlaces` fraction + * digits, the return value will be appended with zeros accordingly. + * + * If `decimalPlaces` is omitted, the number of digits after the decimal point defaults to the + * minimum number of digits necessary to represent the value exactly. + * + * If `roundingMode` is omitted, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = 45.6 + * y = new BigNumber(x) + * x.toExponential() // '4.56e+1' + * y.toExponential() // '4.56e+1' + * x.toExponential(0) // '5e+1' + * y.toExponential(0) // '5e+1' + * x.toExponential(1) // '4.6e+1' + * y.toExponential(1) // '4.6e+1' + * y.toExponential(1, 1) // '4.5e+1' (ROUND_DOWN) + * x.toExponential(3) // '4.560e+1' + * y.toExponential(3) // '4.560e+1' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + toExponential(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): string; + toExponential(): string; + + /** + * Returns a string representing the value of this BigNumber in normal (fixed-point) notation + * rounded to `decimalPlaces` decimal places using rounding mode `roundingMode`. + * + * If the value of this BigNumber in normal notation has fewer than `decimalPlaces` fraction + * digits, the return value will be appended with zeros accordingly. + * + * Unlike `Number.prototype.toFixed`, which returns exponential notation if a number is greater or + * equal to 10**21, this method will always return normal notation. + * + * If `decimalPlaces` is omitted, the return value will be unrounded and in normal notation. + * This is also unlike `Number.prototype.toFixed`, which returns the value to zero decimal places. + * It is useful when normal notation is required and the current `EXPONENTIAL_AT` setting causes + * `toString` to return exponential notation. + * + * If `roundingMode` is omitted, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = 3.456 + * y = new BigNumber(x) + * x.toFixed() // '3' + * y.toFixed() // '3.456' + * y.toFixed(0) // '3' + * x.toFixed(2) // '3.46' + * y.toFixed(2) // '3.46' + * y.toFixed(2, 1) // '3.45' (ROUND_DOWN) + * x.toFixed(5) // '3.45600' + * y.toFixed(5) // '3.45600' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + toFixed(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): string; + toFixed(): string; + + /** + * Returns a string representing the value of this BigNumber in normal (fixed-point) notation + * rounded to `decimalPlaces` decimal places using rounding mode `roundingMode`, and formatted + * according to the properties of the `format` or `FORMAT` object. + * + * The formatting object may contain some or all of the properties shown in the examples below. + * + * If `decimalPlaces` is omitted, then the return value is not rounded to a fixed number of + * decimal places. + * + * If `roundingMode` is omitted, `ROUNDING_MODE` is used. + * + * If `format` is omitted, `FORMAT` is used. + * + * Throws if `decimalPlaces`, `roundingMode`, or `format` is invalid. + * + * ```ts + * fmt = { + * decimalSeparator: '.', + * groupSeparator: ',', + * groupSize: 3, + * secondaryGroupSize: 0, + * fractionGroupSeparator: ' ', + * fractionGroupSize: 0 + * } + * + * x = new BigNumber('123456789.123456789') + * + * // Set the global formatting options + * BigNumber.config({ FORMAT: fmt }) + * + * x.toFormat() // '123,456,789.123456789' + * x.toFormat(3) // '123,456,789.123' + * + * // If a reference to the object assigned to FORMAT has been retained, + * // the format properties can be changed directly + * fmt.groupSeparator = ' ' + * fmt.fractionGroupSize = 5 + * x.toFormat() // '123 456 789.12345 6789' + * + * // Alternatively, pass the formatting options as an argument + * fmt = { + * decimalSeparator: ',', + * groupSeparator: '.', + * groupSize: 3, + * secondaryGroupSize: 2 + * } + * + * x.toFormat() // '123 456 789.12345 6789' + * x.toFormat(fmt) // '12.34.56.789,123456789' + * x.toFormat(2, fmt) // '12.34.56.789,12' + * x.toFormat(3, BigNumber.ROUND_UP, fmt) // '12.34.56.789,124' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + * @param [format] Formatting options object. See `BigNumber.Format`. + */ + toFormat(decimalPlaces: number, roundingMode: BigNumber.RoundingMode, format?: BigNumber.Format): string; + toFormat(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): string; + toFormat(decimalPlaces?: number): string; + toFormat(decimalPlaces: number, format: BigNumber.Format): string; + toFormat(format: BigNumber.Format): string; + + /** + * Returns an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to `max_denominator`. + * If a maximum denominator, `max_denominator`, is not specified, the denominator will be the + * lowest value necessary to represent the number exactly. + * + * Throws if `max_denominator` is invalid. + * + * ```ts + * x = new BigNumber(1.75) + * x.toFraction() // '7, 4' + * + * pi = new BigNumber('3.14159265358') + * pi.toFraction() // '157079632679,50000000000' + * pi.toFraction(100000) // '312689, 99532' + * pi.toFraction(10000) // '355, 113' + * pi.toFraction(100) // '311, 99' + * pi.toFraction(10) // '22, 7' + * pi.toFraction(1) // '3, 1' + * ``` + * + * @param [max_denominator] The maximum denominator, integer > 0, or Infinity. + */ + toFraction(max_denominator?: BigNumber.Value): [BigNumber, BigNumber]; + + /** As `valueOf`. */ + toJSON(): string; + + /** + * Returns the value of this BigNumber as a JavaScript primitive number. + * + * Using the unary plus operator gives the same result. + * + * ```ts + * x = new BigNumber(456.789) + * x.toNumber() // 456.789 + * +x // 456.789 + * + * y = new BigNumber('45987349857634085409857349856430985') + * y.toNumber() // 4.598734985763409e+34 + * + * z = new BigNumber(-0) + * 1 / z.toNumber() // -Infinity + * 1 / +z // -Infinity + * ``` + */ + toNumber(): number; + + /** + * Returns a string representing the value of this BigNumber rounded to `significantDigits` + * significant digits using rounding mode `roundingMode`. + * + * If `significantDigits` is less than the number of digits necessary to represent the integer + * part of the value in normal (fixed-point) notation, then exponential notation is used. + * + * If `significantDigits` is omitted, then the return value is the same as `n.toString()`. + * + * If `roundingMode` is omitted, `ROUNDING_MODE` is used. + * + * Throws if `significantDigits` or `roundingMode` is invalid. + * + * ```ts + * x = 45.6 + * y = new BigNumber(x) + * x.toPrecision() // '45.6' + * y.toPrecision() // '45.6' + * x.toPrecision(1) // '5e+1' + * y.toPrecision(1) // '5e+1' + * y.toPrecision(2, 0) // '4.6e+1' (ROUND_UP) + * y.toPrecision(2, 1) // '4.5e+1' (ROUND_DOWN) + * x.toPrecision(5) // '45.600' + * y.toPrecision(5) // '45.600' + * ``` + * + * @param [significantDigits] Significant digits, integer, 1 to 1e+9. + * @param [roundingMode] Rounding mode, integer 0 to 8. + */ + toPrecision(significantDigits: number, roundingMode?: BigNumber.RoundingMode): string; + toPrecision(): string; + + /** + * Returns a string representing the value of this BigNumber in base `base`, or base 10 if `base` + * is omitted. + * + * For bases above 10, and using the default base conversion alphabet (see `ALPHABET`), values + * from 10 to 35 are represented by a-z (the same as `Number.prototype.toString`). + * + * If a base is specified the value is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings, otherwise it is not. + * + * If a base is not specified, and this BigNumber has a positive exponent that is equal to or + * greater than the positive component of the current `EXPONENTIAL_AT` setting, or a negative + * exponent equal to or less than the negative component of the setting, then exponential notation + * is returned. + * + * Throws if `base` is invalid. + * + * ```ts + * x = new BigNumber(750000) + * x.toString() // '750000' + * BigNumber.config({ EXPONENTIAL_AT: 5 }) + * x.toString() // '7.5e+5' + * + * y = new BigNumber(362.875) + * y.toString(2) // '101101010.111' + * y.toString(9) // '442.77777777777777777778' + * y.toString(32) // 'ba.s' + * + * BigNumber.config({ DECIMAL_PLACES: 4 }); + * z = new BigNumber('1.23456789') + * z.toString() // '1.23456789' + * z.toString(10) // '1.2346' + * ``` + * + * @param [base] The base, integer, 2 to 36 (or `ALPHABET.length`, see `ALPHABET`). + */ + toString(base?: number): string; + + /** + * As `toString`, but does not accept a base argument and includes the minus sign for negative + * zero. + * + * ``ts + * x = new BigNumber('-0') + * x.toString() // '0' + * x.valueOf() // '-0' + * y = new BigNumber('1.777e+457') + * y.valueOf() // '1.777e+457' + * ``` + */ + valueOf(): string; + + /** Helps ES6 import. */ + private static readonly default: BigNumber.Constructor; + + /** Helps ES6 import. */ + private static readonly BigNumber: BigNumber.Constructor; + + /** Rounds away from zero. */ + static readonly ROUND_UP: 0; + + /** Rounds towards zero. */ + static readonly ROUND_DOWN: 1; + + /** Rounds towards Infinity. */ + static readonly ROUND_CEIL: 2; + + /** Rounds towards -Infinity. */ + static readonly ROUND_FLOOR: 3; + + /** Rounds towards nearest neighbour. If equidistant, rounds away from zero . */ + static readonly ROUND_HALF_UP: 4; + + /** Rounds towards nearest neighbour. If equidistant, rounds towards zero. */ + static readonly ROUND_HALF_DOWN: 5; + + /** Rounds towards nearest neighbour. If equidistant, rounds towards even neighbour. */ + static readonly ROUND_HALF_EVEN: 6; + + /** Rounds towards nearest neighbour. If equidistant, rounds towards Infinity. */ + static readonly ROUND_HALF_CEIL: 7; + + /** Rounds towards nearest neighbour. If equidistant, rounds towards -Infinity. */ + static readonly ROUND_HALF_FLOOR: 8; + + /** See `MODULO_MODE`. */ + static readonly EUCLID: 9; + + /** + * To aid in debugging, if a `BigNumber.DEBUG` property is `true` then an error will be thrown + * if the BigNumber constructor receives an invalid `BigNumber.Value`, or if `BigNumber.isBigNumber` + * receives a BigNumber instance that is malformed. + * + * ```ts + * // No error, and BigNumber NaN is returned. + * new BigNumber('blurgh') // 'NaN' + * new BigNumber(9, 2) // 'NaN' + * BigNumber.DEBUG = true + * new BigNumber('blurgh') // '[BigNumber Error] Not a number' + * new BigNumber(9, 2) // '[BigNumber Error] Not a base 2 number' + * ``` + * + * An error will also be thrown if a `BigNumber.Value` is of type number with more than 15 + * significant digits, as calling `toString` or `valueOf` on such numbers may not result + * in the intended value. + * + * ```ts + * console.log(823456789123456.3) // 823456789123456.2 + * // No error, and the returned BigNumber does not have the same value as the number literal. + * new BigNumber(823456789123456.3) // '823456789123456.2' + * BigNumber.DEBUG = true + * new BigNumber(823456789123456.3) + * // '[BigNumber Error] Number primitive has more than 15 significant digits' + * ``` + * + * Check that a BigNumber instance is well-formed: + * + * ```ts + * x = new BigNumber(10) + * + * BigNumber.DEBUG = false + * // Change x.c to an illegitimate value. + * x.c = NaN + * // No error, as BigNumber.DEBUG is false. + * BigNumber.isBigNumber(x) // true + * + * BigNumber.DEBUG = true + * BigNumber.isBigNumber(x) // '[BigNumber Error] Invalid BigNumber' + * ``` + */ + static DEBUG?: boolean; + + /** + * Returns a new independent BigNumber constructor with configuration as described by `object`, or + * with the default configuration if object is omitted. + * + * Throws if `object` is not an object. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) + * + * x = new BigNumber(1) + * y = new BN(1) + * + * x.div(3) // 0.33333 + * y.div(3) // 0.333333333 + * + * // BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) is equivalent to: + * BN = BigNumber.clone() + * BN.config({ DECIMAL_PLACES: 9 }) + * ``` + * + * @param [object] The configuration object. + */ + static clone(object?: BigNumber.Config): BigNumber.Constructor; + + /** + * Configures the settings that apply to this BigNumber constructor. + * + * The configuration object, `object`, contains any number of the properties shown in the example + * below. + * + * Returns an object with the above properties and their current values. + * + * Throws if `object` is not an object, or if an invalid value is assigned to one or more of the + * properties. + * + * ```ts + * BigNumber.config({ + * DECIMAL_PLACES: 40, + * ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL, + * EXPONENTIAL_AT: [-10, 20], + * RANGE: [-500, 500], + * CRYPTO: true, + * MODULO_MODE: BigNumber.ROUND_FLOOR, + * POW_PRECISION: 80, + * FORMAT: { + * groupSize: 3, + * groupSeparator: ' ', + * decimalSeparator: ',' + * }, + * ALPHABET: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + * }); + * + * BigNumber.config().DECIMAL_PLACES // 40 + * ``` + * + * @param object The configuration object. + */ + static config(object?: BigNumber.Config): BigNumber.Config; + + /** + * Returns `true` if `value` is a BigNumber instance, otherwise returns `false`. + * + * If `BigNumber.DEBUG` is `true`, throws if a BigNumber instance is not well-formed. + * + * ```ts + * x = 42 + * y = new BigNumber(x) + * + * BigNumber.isBigNumber(x) // false + * y instanceof BigNumber // true + * BigNumber.isBigNumber(y) // true + * + * BN = BigNumber.clone(); + * z = new BN(x) + * z instanceof BigNumber // false + * BigNumber.isBigNumber(z) // true + * ``` + * + * @param value The value to test. + */ + static isBigNumber(value: any): value is BigNumber; + + /** + * Returns a BigNumber whose value is the maximum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.maximum(4e9, x, '123456789.9') // '4000000000' + * + * arr = [12, '13', new BigNumber(14)] + * BigNumber.maximum.apply(null, arr) // '14' + * ``` + * + * @param n A numeric value. + */ + static maximum(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a BigNumber whose value is the maximum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.max(4e9, x, '123456789.9') // '4000000000' + * + * arr = [12, '13', new BigNumber(14)] + * BigNumber.max.apply(null, arr) // '14' + * ``` + * + * @param n A numeric value. + */ + static max(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a BigNumber whose value is the minimum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.minimum(4e9, x, '123456789.9') // '123456789.9' + * + * arr = [2, new BigNumber(-14), '-15.9999', -12] + * BigNumber.minimum.apply(null, arr) // '-15.9999' + * ``` + * + * @param n A numeric value. + */ + static minimum(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a BigNumber whose value is the minimum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.min(4e9, x, '123456789.9') // '123456789.9' + * + * arr = [2, new BigNumber(-14), '-15.9999', -12] + * BigNumber.min.apply(null, arr) // '-15.9999' + * ``` + * + * @param n A numeric value. + */ + static min(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a new BigNumber with a pseudo-random value equal to or greater than 0 and less than 1. + * + * The return value will have `decimalPlaces` decimal places, or less if trailing zeros are + * produced. If `decimalPlaces` is omitted, the current `DECIMAL_PLACES` setting will be used. + * + * Depending on the value of this BigNumber constructor's `CRYPTO` setting and the support for the + * `crypto` object in the host environment, the random digits of the return value are generated by + * either `Math.random` (fastest), `crypto.getRandomValues` (Web Cryptography API in recent + * browsers) or `crypto.randomBytes` (Node.js). + * + * To be able to set `CRYPTO` to true when using Node.js, the `crypto` object must be available + * globally: + * + * ```ts + * global.crypto = require('crypto') + * ``` + * + * If `CRYPTO` is true, i.e. one of the `crypto` methods is to be used, the value of a returned + * BigNumber should be cryptographically secure and statistically indistinguishable from a random + * value. + * + * Throws if `decimalPlaces` is invalid. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 10 }) + * BigNumber.random() // '0.4117936847' + * BigNumber.random(20) // '0.78193327636914089009' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + */ + static random(decimalPlaces?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the sum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.sum(4e9, x, '123456789.9') // '7381326134.9378653' + * + * arr = [2, new BigNumber(14), '15.9999', 12] + * BigNumber.sum.apply(null, arr) // '43.9999' + * ``` + * + * @param n A numeric value. + */ + static sum(...n: BigNumber.Value[]): BigNumber; + + /** + * Configures the settings that apply to this BigNumber constructor. + * + * The configuration object, `object`, contains any number of the properties shown in the example + * below. + * + * Returns an object with the above properties and their current values. + * + * Throws if `object` is not an object, or if an invalid value is assigned to one or more of the + * properties. + * + * ```ts + * BigNumber.set({ + * DECIMAL_PLACES: 40, + * ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL, + * EXPONENTIAL_AT: [-10, 20], + * RANGE: [-500, 500], + * CRYPTO: true, + * MODULO_MODE: BigNumber.ROUND_FLOOR, + * POW_PRECISION: 80, + * FORMAT: { + * groupSize: 3, + * groupSeparator: ' ', + * decimalSeparator: ',' + * }, + * ALPHABET: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + * }); + * + * BigNumber.set().DECIMAL_PLACES // 40 + * ``` + * + * @param object The configuration object. + */ + static set(object?: BigNumber.Config): BigNumber.Config; +} + +declare function BigNumber(n: BigNumber.Value, base?: number): BigNumber; diff --git a/node_modules/buffer-equal-constant-time/.npmignore b/node_modules/buffer-equal-constant-time/.npmignore new file mode 100644 index 0000000..34e4f5c --- /dev/null +++ b/node_modules/buffer-equal-constant-time/.npmignore @@ -0,0 +1,2 @@ +.*.sw[mnop] +node_modules/ diff --git a/node_modules/buffer-equal-constant-time/.travis.yml b/node_modules/buffer-equal-constant-time/.travis.yml new file mode 100644 index 0000000..78e1c01 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: +- "0.11" +- "0.10" diff --git a/node_modules/buffer-equal-constant-time/LICENSE.txt b/node_modules/buffer-equal-constant-time/LICENSE.txt new file mode 100644 index 0000000..9a064f3 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/LICENSE.txt @@ -0,0 +1,12 @@ +Copyright (c) 2013, GoInstant Inc., a salesforce.com company +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +* Neither the name of salesforce.com, nor GoInstant, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/buffer-equal-constant-time/README.md b/node_modules/buffer-equal-constant-time/README.md new file mode 100644 index 0000000..4f227f5 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/README.md @@ -0,0 +1,50 @@ +# buffer-equal-constant-time + +Constant-time `Buffer` comparison for node.js. Should work with browserify too. + +[![Build Status](https://travis-ci.org/goinstant/buffer-equal-constant-time.png?branch=master)](https://travis-ci.org/goinstant/buffer-equal-constant-time) + +```sh + npm install buffer-equal-constant-time +``` + +# Usage + +```js + var bufferEq = require('buffer-equal-constant-time'); + + var a = new Buffer('asdf'); + var b = new Buffer('asdf'); + if (bufferEq(a,b)) { + // the same! + } else { + // different in at least one byte! + } +``` + +If you'd like to install an `.equal()` method onto the node.js `Buffer` and +`SlowBuffer` prototypes: + +```js + require('buffer-equal-constant-time').install(); + + var a = new Buffer('asdf'); + var b = new Buffer('asdf'); + if (a.equal(b)) { + // the same! + } else { + // different in at least one byte! + } +``` + +To get rid of the installed `.equal()` method, call `.restore()`: + +```js + require('buffer-equal-constant-time').restore(); +``` + +# Legal + +© 2013 GoInstant Inc., a salesforce.com company + +Licensed under the BSD 3-clause license. diff --git a/node_modules/buffer-equal-constant-time/index.js b/node_modules/buffer-equal-constant-time/index.js new file mode 100644 index 0000000..5462c1f --- /dev/null +++ b/node_modules/buffer-equal-constant-time/index.js @@ -0,0 +1,41 @@ +/*jshint node:true */ +'use strict'; +var Buffer = require('buffer').Buffer; // browserify +var SlowBuffer = require('buffer').SlowBuffer; + +module.exports = bufferEq; + +function bufferEq(a, b) { + + // shortcutting on type is necessary for correctness + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + return false; + } + + // buffer sizes should be well-known information, so despite this + // shortcutting, it doesn't leak any information about the *contents* of the + // buffers. + if (a.length !== b.length) { + return false; + } + + var c = 0; + for (var i = 0; i < a.length; i++) { + /*jshint bitwise:false */ + c |= a[i] ^ b[i]; // XOR + } + return c === 0; +} + +bufferEq.install = function() { + Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { + return bufferEq(this, that); + }; +}; + +var origBufEqual = Buffer.prototype.equal; +var origSlowBufEqual = SlowBuffer.prototype.equal; +bufferEq.restore = function() { + Buffer.prototype.equal = origBufEqual; + SlowBuffer.prototype.equal = origSlowBufEqual; +}; diff --git a/node_modules/buffer-equal-constant-time/package.json b/node_modules/buffer-equal-constant-time/package.json new file mode 100644 index 0000000..17c7de2 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/package.json @@ -0,0 +1,21 @@ +{ + "name": "buffer-equal-constant-time", + "version": "1.0.1", + "description": "Constant-time comparison of Buffers", + "main": "index.js", + "scripts": { + "test": "mocha test.js" + }, + "repository": "git@github.com:goinstant/buffer-equal-constant-time.git", + "keywords": [ + "buffer", + "equal", + "constant-time", + "crypto" + ], + "author": "GoInstant Inc., a salesforce.com company", + "license": "BSD-3-Clause", + "devDependencies": { + "mocha": "~1.15.1" + } +} diff --git a/node_modules/buffer-equal-constant-time/test.js b/node_modules/buffer-equal-constant-time/test.js new file mode 100644 index 0000000..0bc972d --- /dev/null +++ b/node_modules/buffer-equal-constant-time/test.js @@ -0,0 +1,42 @@ +/*jshint node:true */ +'use strict'; + +var bufferEq = require('./index'); +var assert = require('assert'); + +describe('buffer-equal-constant-time', function() { + var a = new Buffer('asdfasdf123456'); + var b = new Buffer('asdfasdf123456'); + var c = new Buffer('asdfasdf'); + + describe('bufferEq', function() { + it('says a == b', function() { + assert.strictEqual(bufferEq(a, b), true); + }); + + it('says a != c', function() { + assert.strictEqual(bufferEq(a, c), false); + }); + }); + + describe('install/restore', function() { + before(function() { + bufferEq.install(); + }); + after(function() { + bufferEq.restore(); + }); + + it('installed an .equal method', function() { + var SlowBuffer = require('buffer').SlowBuffer; + assert.ok(Buffer.prototype.equal); + assert.ok(SlowBuffer.prototype.equal); + }); + + it('infected existing Buffers', function() { + assert.strictEqual(a.equal(b), true); + assert.strictEqual(a.equal(c), false); + }); + }); + +}); diff --git a/node_modules/call-bind-apply-helpers/.eslintrc b/node_modules/call-bind-apply-helpers/.eslintrc new file mode 100644 index 0000000..201e859 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/.eslintrc @@ -0,0 +1,17 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "id-length": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + "no-extra-parens": 0, + "no-magic-numbers": 0, + }, +} diff --git a/node_modules/call-bind-apply-helpers/.github/FUNDING.yml b/node_modules/call-bind-apply-helpers/.github/FUNDING.yml new file mode 100644 index 0000000..0011e9d --- /dev/null +++ b/node_modules/call-bind-apply-helpers/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/call-bind-apply-helpers +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/call-bind-apply-helpers/.nycrc b/node_modules/call-bind-apply-helpers/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/call-bind-apply-helpers/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/call-bind-apply-helpers/CHANGELOG.md b/node_modules/call-bind-apply-helpers/CHANGELOG.md new file mode 100644 index 0000000..2484942 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/CHANGELOG.md @@ -0,0 +1,30 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.2](https://github.com/ljharb/call-bind-apply-helpers/compare/v1.0.1...v1.0.2) - 2025-02-12 + +### Commits + +- [types] improve inferred types [`e6f9586`](https://github.com/ljharb/call-bind-apply-helpers/commit/e6f95860a3c72879cb861a858cdfb8138fbedec1) +- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/tsconfig`, `@types/tape`, `es-value-fixtures`, `for-each`, `has-strict-mode`, `object-inspect` [`e43d540`](https://github.com/ljharb/call-bind-apply-helpers/commit/e43d5409f97543bfbb11f345d47d8ce4e066d8c1) + +## [v1.0.1](https://github.com/ljharb/call-bind-apply-helpers/compare/v1.0.0...v1.0.1) - 2024-12-08 + +### Commits + +- [types] `reflectApply`: fix types [`4efc396`](https://github.com/ljharb/call-bind-apply-helpers/commit/4efc3965351a4f02cc55e836fa391d3d11ef2ef8) +- [Fix] `reflectApply`: oops, Reflect is not a function [`83cc739`](https://github.com/ljharb/call-bind-apply-helpers/commit/83cc7395de6b79b7730bdf092f1436f0b1263c75) +- [Dev Deps] update `@arethetypeswrong/cli` [`80bd5d3`](https://github.com/ljharb/call-bind-apply-helpers/commit/80bd5d3ae58b4f6b6995ce439dd5a1bcb178a940) + +## v1.0.0 - 2024-12-05 + +### Commits + +- Initial implementation, tests, readme [`7879629`](https://github.com/ljharb/call-bind-apply-helpers/commit/78796290f9b7430c9934d6f33d94ae9bc89fce04) +- Initial commit [`3f1dc16`](https://github.com/ljharb/call-bind-apply-helpers/commit/3f1dc164afc43285631b114a5f9dd9137b2b952f) +- npm init [`081df04`](https://github.com/ljharb/call-bind-apply-helpers/commit/081df048c312fcee400922026f6e97281200a603) +- Only apps should have lockfiles [`5b9ca0f`](https://github.com/ljharb/call-bind-apply-helpers/commit/5b9ca0fe8101ebfaf309c549caac4e0a017ed930) diff --git a/node_modules/call-bind-apply-helpers/LICENSE b/node_modules/call-bind-apply-helpers/LICENSE new file mode 100644 index 0000000..f82f389 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/call-bind-apply-helpers/README.md b/node_modules/call-bind-apply-helpers/README.md new file mode 100644 index 0000000..8fc0dae --- /dev/null +++ b/node_modules/call-bind-apply-helpers/README.md @@ -0,0 +1,62 @@ +# call-bind-apply-helpers [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Helper functions around Function call/apply/bind, for use in `call-bind`. + +The only packages that should likely ever use this package directly are `call-bind` and `get-intrinsic`. +Please use `call-bind` unless you have a very good reason not to. + +## Getting started + +```sh +npm install --save call-bind-apply-helpers +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const callBindBasic = require('call-bind-apply-helpers'); + +function f(a, b) { + assert.equal(this, 1); + assert.equal(a, 2); + assert.equal(b, 3); + assert.equal(arguments.length, 2); +} + +const fBound = callBindBasic([f, 1]); + +delete Function.prototype.call; +delete Function.prototype.bind; + +fBound(2, 3); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/call-bind-apply-helpers +[npm-version-svg]: https://versionbadg.es/ljharb/call-bind-apply-helpers.svg +[deps-svg]: https://david-dm.org/ljharb/call-bind-apply-helpers.svg +[deps-url]: https://david-dm.org/ljharb/call-bind-apply-helpers +[dev-deps-svg]: https://david-dm.org/ljharb/call-bind-apply-helpers/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/call-bind-apply-helpers#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/call-bind-apply-helpers.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/call-bind-apply-helpers.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/call-bind-apply-helpers.svg +[downloads-url]: https://npm-stat.com/charts.html?package=call-bind-apply-helpers +[codecov-image]: https://codecov.io/gh/ljharb/call-bind-apply-helpers/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/call-bind-apply-helpers/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/call-bind-apply-helpers +[actions-url]: https://github.com/ljharb/call-bind-apply-helpers/actions diff --git a/node_modules/call-bind-apply-helpers/actualApply.d.ts b/node_modules/call-bind-apply-helpers/actualApply.d.ts new file mode 100644 index 0000000..b87286a --- /dev/null +++ b/node_modules/call-bind-apply-helpers/actualApply.d.ts @@ -0,0 +1 @@ +export = Reflect.apply; \ No newline at end of file diff --git a/node_modules/call-bind-apply-helpers/actualApply.js b/node_modules/call-bind-apply-helpers/actualApply.js new file mode 100644 index 0000000..ffa5135 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/actualApply.js @@ -0,0 +1,10 @@ +'use strict'; + +var bind = require('function-bind'); + +var $apply = require('./functionApply'); +var $call = require('./functionCall'); +var $reflectApply = require('./reflectApply'); + +/** @type {import('./actualApply')} */ +module.exports = $reflectApply || bind.call($call, $apply); diff --git a/node_modules/call-bind-apply-helpers/applyBind.d.ts b/node_modules/call-bind-apply-helpers/applyBind.d.ts new file mode 100644 index 0000000..d176c1a --- /dev/null +++ b/node_modules/call-bind-apply-helpers/applyBind.d.ts @@ -0,0 +1,19 @@ +import actualApply from './actualApply'; + +type TupleSplitHead = T['length'] extends N + ? T + : T extends [...infer R, any] + ? TupleSplitHead + : never + +type TupleSplitTail = O['length'] extends N + ? T + : T extends [infer F, ...infer R] + ? TupleSplitTail<[...R], N, [...O, F]> + : never + +type TupleSplit = [TupleSplitHead, TupleSplitTail] + +declare function applyBind(...args: TupleSplit, 2>[1]): ReturnType; + +export = applyBind; \ No newline at end of file diff --git a/node_modules/call-bind-apply-helpers/applyBind.js b/node_modules/call-bind-apply-helpers/applyBind.js new file mode 100644 index 0000000..d2b7723 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/applyBind.js @@ -0,0 +1,10 @@ +'use strict'; + +var bind = require('function-bind'); +var $apply = require('./functionApply'); +var actualApply = require('./actualApply'); + +/** @type {import('./applyBind')} */ +module.exports = function applyBind() { + return actualApply(bind, $apply, arguments); +}; diff --git a/node_modules/call-bind-apply-helpers/functionApply.d.ts b/node_modules/call-bind-apply-helpers/functionApply.d.ts new file mode 100644 index 0000000..1f6e11b --- /dev/null +++ b/node_modules/call-bind-apply-helpers/functionApply.d.ts @@ -0,0 +1 @@ +export = Function.prototype.apply; \ No newline at end of file diff --git a/node_modules/call-bind-apply-helpers/functionApply.js b/node_modules/call-bind-apply-helpers/functionApply.js new file mode 100644 index 0000000..c71df9c --- /dev/null +++ b/node_modules/call-bind-apply-helpers/functionApply.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./functionApply')} */ +module.exports = Function.prototype.apply; diff --git a/node_modules/call-bind-apply-helpers/functionCall.d.ts b/node_modules/call-bind-apply-helpers/functionCall.d.ts new file mode 100644 index 0000000..15e93df --- /dev/null +++ b/node_modules/call-bind-apply-helpers/functionCall.d.ts @@ -0,0 +1 @@ +export = Function.prototype.call; \ No newline at end of file diff --git a/node_modules/call-bind-apply-helpers/functionCall.js b/node_modules/call-bind-apply-helpers/functionCall.js new file mode 100644 index 0000000..7a8d873 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/functionCall.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./functionCall')} */ +module.exports = Function.prototype.call; diff --git a/node_modules/call-bind-apply-helpers/index.d.ts b/node_modules/call-bind-apply-helpers/index.d.ts new file mode 100644 index 0000000..541516b --- /dev/null +++ b/node_modules/call-bind-apply-helpers/index.d.ts @@ -0,0 +1,64 @@ +type RemoveFromTuple< + Tuple extends readonly unknown[], + RemoveCount extends number, + Index extends 1[] = [] +> = Index["length"] extends RemoveCount + ? Tuple + : Tuple extends [infer First, ...infer Rest] + ? RemoveFromTuple + : Tuple; + +type ConcatTuples< + Prefix extends readonly unknown[], + Suffix extends readonly unknown[] +> = [...Prefix, ...Suffix]; + +type ExtractFunctionParams = T extends (this: infer TThis, ...args: infer P extends readonly unknown[]) => infer R + ? { thisArg: TThis; params: P; returnType: R } + : never; + +type BindFunction< + T extends (this: any, ...args: any[]) => any, + TThis, + TBoundArgs extends readonly unknown[], + ReceiverBound extends boolean +> = ExtractFunctionParams extends { + thisArg: infer OrigThis; + params: infer P extends readonly unknown[]; + returnType: infer R; +} + ? ReceiverBound extends true + ? (...args: RemoveFromTuple>) => R extends [OrigThis, ...infer Rest] + ? [TThis, ...Rest] // Replace `this` with `thisArg` + : R + : >>( + thisArg: U, + ...args: RemainingArgs + ) => R extends [OrigThis, ...infer Rest] + ? [U, ...ConcatTuples] // Preserve bound args in return type + : R + : never; + +declare function callBind< + const T extends (this: any, ...args: any[]) => any, + Extracted extends ExtractFunctionParams, + const TBoundArgs extends Partial & readonly unknown[], + const TThis extends Extracted["thisArg"] +>( + args: [fn: T, thisArg: TThis, ...boundArgs: TBoundArgs] +): BindFunction; + +declare function callBind< + const T extends (this: any, ...args: any[]) => any, + Extracted extends ExtractFunctionParams, + const TBoundArgs extends Partial & readonly unknown[] +>( + args: [fn: T, ...boundArgs: TBoundArgs] +): BindFunction; + +declare function callBind( + args: [fn: Exclude, ...rest: TArgs] +): never; + +// export as namespace callBind; +export = callBind; diff --git a/node_modules/call-bind-apply-helpers/index.js b/node_modules/call-bind-apply-helpers/index.js new file mode 100644 index 0000000..2f6dab4 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/index.js @@ -0,0 +1,15 @@ +'use strict'; + +var bind = require('function-bind'); +var $TypeError = require('es-errors/type'); + +var $call = require('./functionCall'); +var $actualApply = require('./actualApply'); + +/** @type {(args: [Function, thisArg?: unknown, ...args: unknown[]]) => Function} TODO FIXME, find a way to use import('.') */ +module.exports = function callBindBasic(args) { + if (args.length < 1 || typeof args[0] !== 'function') { + throw new $TypeError('a function is required'); + } + return $actualApply(bind, $call, args); +}; diff --git a/node_modules/call-bind-apply-helpers/package.json b/node_modules/call-bind-apply-helpers/package.json new file mode 100644 index 0000000..923b8be --- /dev/null +++ b/node_modules/call-bind-apply-helpers/package.json @@ -0,0 +1,85 @@ +{ + "name": "call-bind-apply-helpers", + "version": "1.0.2", + "description": "Helper functions around Function call/apply/bind, for use in `call-bind`", + "main": "index.js", + "exports": { + ".": "./index.js", + "./actualApply": "./actualApply.js", + "./applyBind": "./applyBind.js", + "./functionApply": "./functionApply.js", + "./functionCall": "./functionCall.js", + "./reflectApply": "./reflectApply.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=auto", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=.js,.mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/call-bind-apply-helpers.git" + }, + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/call-bind-apply-helpers/issues" + }, + "homepage": "https://github.com/ljharb/call-bind-apply-helpers#readme", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.3", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.3", + "@types/for-each": "^0.3.3", + "@types/function-bind": "^1.1.10", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.8.1", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "es-value-fixtures": "^1.7.1", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.5", + "has-strict-mode": "^1.1.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.4", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/call-bind-apply-helpers/reflectApply.d.ts b/node_modules/call-bind-apply-helpers/reflectApply.d.ts new file mode 100644 index 0000000..6b2ae76 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/reflectApply.d.ts @@ -0,0 +1,3 @@ +declare const reflectApply: false | typeof Reflect.apply; + +export = reflectApply; diff --git a/node_modules/call-bind-apply-helpers/reflectApply.js b/node_modules/call-bind-apply-helpers/reflectApply.js new file mode 100644 index 0000000..3d03caa --- /dev/null +++ b/node_modules/call-bind-apply-helpers/reflectApply.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./reflectApply')} */ +module.exports = typeof Reflect !== 'undefined' && Reflect && Reflect.apply; diff --git a/node_modules/call-bind-apply-helpers/test/index.js b/node_modules/call-bind-apply-helpers/test/index.js new file mode 100644 index 0000000..1cdc89e --- /dev/null +++ b/node_modules/call-bind-apply-helpers/test/index.js @@ -0,0 +1,63 @@ +'use strict'; + +var callBind = require('../'); +var hasStrictMode = require('has-strict-mode')(); +var forEach = require('for-each'); +var inspect = require('object-inspect'); +var v = require('es-value-fixtures'); + +var test = require('tape'); + +test('callBindBasic', function (t) { + forEach(v.nonFunctions, function (nonFunction) { + t['throws']( + // @ts-expect-error + function () { callBind([nonFunction]); }, + TypeError, + inspect(nonFunction) + ' is not a function' + ); + }); + + var sentinel = { sentinel: true }; + /** @type {(this: T, a: A, b: B) => [T | undefined, A, B]} */ + var func = function (a, b) { + // eslint-disable-next-line no-invalid-this + return [!hasStrictMode && this === global ? undefined : this, a, b]; + }; + t.equal(func.length, 2, 'original function length is 2'); + + /** type {(thisArg: unknown, a: number, b: number) => [unknown, number, number]} */ + var bound = callBind([func]); + /** type {((a: number, b: number) => [typeof sentinel, typeof a, typeof b])} */ + var boundR = callBind([func, sentinel]); + /** type {((b: number) => [typeof sentinel, number, typeof b])} */ + var boundArg = callBind([func, sentinel, /** @type {const} */ (1)]); + + // @ts-expect-error + t.deepEqual(bound(), [undefined, undefined, undefined], 'bound func with no args'); + + // @ts-expect-error + t.deepEqual(func(), [undefined, undefined, undefined], 'unbound func with too few args'); + // @ts-expect-error + t.deepEqual(bound(1, 2), [hasStrictMode ? 1 : Object(1), 2, undefined], 'bound func too few args'); + // @ts-expect-error + t.deepEqual(boundR(), [sentinel, undefined, undefined], 'bound func with receiver, with too few args'); + // @ts-expect-error + t.deepEqual(boundArg(), [sentinel, 1, undefined], 'bound func with receiver and arg, with too few args'); + + t.deepEqual(func(1, 2), [undefined, 1, 2], 'unbound func with right args'); + t.deepEqual(bound(1, 2, 3), [hasStrictMode ? 1 : Object(1), 2, 3], 'bound func with right args'); + t.deepEqual(boundR(1, 2), [sentinel, 1, 2], 'bound func with receiver, with right args'); + t.deepEqual(boundArg(2), [sentinel, 1, 2], 'bound func with receiver and arg, with right arg'); + + // @ts-expect-error + t.deepEqual(func(1, 2, 3), [undefined, 1, 2], 'unbound func with too many args'); + // @ts-expect-error + t.deepEqual(bound(1, 2, 3, 4), [hasStrictMode ? 1 : Object(1), 2, 3], 'bound func with too many args'); + // @ts-expect-error + t.deepEqual(boundR(1, 2, 3), [sentinel, 1, 2], 'bound func with receiver, with too many args'); + // @ts-expect-error + t.deepEqual(boundArg(2, 3), [sentinel, 1, 2], 'bound func with receiver and arg, with too many args'); + + t.end(); +}); diff --git a/node_modules/call-bind-apply-helpers/tsconfig.json b/node_modules/call-bind-apply-helpers/tsconfig.json new file mode 100644 index 0000000..aef9993 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} \ No newline at end of file diff --git a/node_modules/cliui/CHANGELOG.md b/node_modules/cliui/CHANGELOG.md new file mode 100644 index 0000000..61f06c3 --- /dev/null +++ b/node_modules/cliui/CHANGELOG.md @@ -0,0 +1,139 @@ +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## [8.0.1](https://github.com/yargs/cliui/compare/v8.0.0...v8.0.1) (2022-10-01) + + +### Bug Fixes + +* **deps:** move rollup-plugin-ts to dev deps ([#124](https://github.com/yargs/cliui/issues/124)) ([7c8bd6b](https://github.com/yargs/cliui/commit/7c8bd6ba024d61e4eeae310c7959ab8ab6829081)) + +## [8.0.0](https://github.com/yargs/cliui/compare/v7.0.4...v8.0.0) (2022-09-30) + + +### ⚠ BREAKING CHANGES + +* **deps:** drop Node 10 to release CVE-2021-3807 patch (#122) + +### Bug Fixes + +* **deps:** drop Node 10 to release CVE-2021-3807 patch ([#122](https://github.com/yargs/cliui/issues/122)) ([f156571](https://github.com/yargs/cliui/commit/f156571ce4f2ebf313335e3a53ad905589da5a30)) + +### [7.0.4](https://www.github.com/yargs/cliui/compare/v7.0.3...v7.0.4) (2020-11-08) + + +### Bug Fixes + +* **deno:** import UIOptions from definitions ([#97](https://www.github.com/yargs/cliui/issues/97)) ([f04f343](https://www.github.com/yargs/cliui/commit/f04f3439bc78114c7e90f82ff56f5acf16268ea8)) + +### [7.0.3](https://www.github.com/yargs/cliui/compare/v7.0.2...v7.0.3) (2020-10-16) + + +### Bug Fixes + +* **exports:** node 13.0 and 13.1 require the dotted object form _with_ a string fallback ([#93](https://www.github.com/yargs/cliui/issues/93)) ([eca16fc](https://www.github.com/yargs/cliui/commit/eca16fc05d26255df3280906c36d7f0e5b05c6e9)) + +### [7.0.2](https://www.github.com/yargs/cliui/compare/v7.0.1...v7.0.2) (2020-10-14) + + +### Bug Fixes + +* **exports:** node 13.0-13.6 require a string fallback ([#91](https://www.github.com/yargs/cliui/issues/91)) ([b529d7e](https://www.github.com/yargs/cliui/commit/b529d7e432901af1af7848b23ed6cf634497d961)) + +### [7.0.1](https://www.github.com/yargs/cliui/compare/v7.0.0...v7.0.1) (2020-08-16) + + +### Bug Fixes + +* **build:** main should be build/index.cjs ([dc29a3c](https://www.github.com/yargs/cliui/commit/dc29a3cc617a410aa850e06337b5954b04f2cb4d)) + +## [7.0.0](https://www.github.com/yargs/cliui/compare/v6.0.0...v7.0.0) (2020-08-16) + + +### ⚠ BREAKING CHANGES + +* tsc/ESM/Deno support (#82) +* modernize deps and build (#80) + +### Build System + +* modernize deps and build ([#80](https://www.github.com/yargs/cliui/issues/80)) ([339d08d](https://www.github.com/yargs/cliui/commit/339d08dc71b15a3928aeab09042af94db2f43743)) + + +### Code Refactoring + +* tsc/ESM/Deno support ([#82](https://www.github.com/yargs/cliui/issues/82)) ([4b777a5](https://www.github.com/yargs/cliui/commit/4b777a5fe01c5d8958c6708695d6aab7dbe5706c)) + +## [6.0.0](https://www.github.com/yargs/cliui/compare/v5.0.0...v6.0.0) (2019-11-10) + + +### ⚠ BREAKING CHANGES + +* update deps, drop Node 6 + +### Code Refactoring + +* update deps, drop Node 6 ([62056df](https://www.github.com/yargs/cliui/commit/62056df)) + +## [5.0.0](https://github.com/yargs/cliui/compare/v4.1.0...v5.0.0) (2019-04-10) + + +### Bug Fixes + +* Update wrap-ansi to fix compatibility with latest versions of chalk. ([#60](https://github.com/yargs/cliui/issues/60)) ([7bf79ae](https://github.com/yargs/cliui/commit/7bf79ae)) + + +### BREAKING CHANGES + +* Drop support for node < 6. + + + + +## [4.1.0](https://github.com/yargs/cliui/compare/v4.0.0...v4.1.0) (2018-04-23) + + +### Features + +* add resetOutput method ([#57](https://github.com/yargs/cliui/issues/57)) ([7246902](https://github.com/yargs/cliui/commit/7246902)) + + + + +## [4.0.0](https://github.com/yargs/cliui/compare/v3.2.0...v4.0.0) (2017-12-18) + + +### Bug Fixes + +* downgrades strip-ansi to version 3.0.1 ([#54](https://github.com/yargs/cliui/issues/54)) ([5764c46](https://github.com/yargs/cliui/commit/5764c46)) +* set env variable FORCE_COLOR. ([#56](https://github.com/yargs/cliui/issues/56)) ([7350e36](https://github.com/yargs/cliui/commit/7350e36)) + + +### Chores + +* drop support for node < 4 ([#53](https://github.com/yargs/cliui/issues/53)) ([b105376](https://github.com/yargs/cliui/commit/b105376)) + + +### Features + +* add fallback for window width ([#45](https://github.com/yargs/cliui/issues/45)) ([d064922](https://github.com/yargs/cliui/commit/d064922)) + + +### BREAKING CHANGES + +* officially drop support for Node < 4 + + + + +## [3.2.0](https://github.com/yargs/cliui/compare/v3.1.2...v3.2.0) (2016-04-11) + + +### Bug Fixes + +* reduces tarball size ([acc6c33](https://github.com/yargs/cliui/commit/acc6c33)) + +### Features + +* adds standard-version for release management ([ff84e32](https://github.com/yargs/cliui/commit/ff84e32)) diff --git a/node_modules/cliui/LICENSE.txt b/node_modules/cliui/LICENSE.txt new file mode 100644 index 0000000..c7e2747 --- /dev/null +++ b/node_modules/cliui/LICENSE.txt @@ -0,0 +1,14 @@ +Copyright (c) 2015, Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/cliui/README.md b/node_modules/cliui/README.md new file mode 100644 index 0000000..65b5672 --- /dev/null +++ b/node_modules/cliui/README.md @@ -0,0 +1,141 @@ +# cliui + +![ci](https://github.com/yargs/cliui/workflows/ci/badge.svg) +[![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) +[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) +![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/cliui) + +easily create complex multi-column command-line-interfaces. + +## Example + +```js +const ui = require('cliui')() + +ui.div('Usage: $0 [command] [options]') + +ui.div({ + text: 'Options:', + padding: [2, 0, 1, 0] +}) + +ui.div( + { + text: "-f, --file", + width: 20, + padding: [0, 4, 0, 4] + }, + { + text: "the file to load." + + chalk.green("(if this description is long it wraps).") + , + width: 20 + }, + { + text: chalk.red("[required]"), + align: 'right' + } +) + +console.log(ui.toString()) +``` + +## Deno/ESM Support + +As of `v7` `cliui` supports [Deno](https://github.com/denoland/deno) and +[ESM](https://nodejs.org/api/esm.html#esm_ecmascript_modules): + +```typescript +import cliui from "https://deno.land/x/cliui/deno.ts"; + +const ui = cliui({}) + +ui.div('Usage: $0 [command] [options]') + +ui.div({ + text: 'Options:', + padding: [2, 0, 1, 0] +}) + +ui.div({ + text: "-f, --file", + width: 20, + padding: [0, 4, 0, 4] +}) + +console.log(ui.toString()) +``` + + + +## Layout DSL + +cliui exposes a simple layout DSL: + +If you create a single `ui.div`, passing a string rather than an +object: + +* `\n`: characters will be interpreted as new rows. +* `\t`: characters will be interpreted as new columns. +* `\s`: characters will be interpreted as padding. + +**as an example...** + +```js +var ui = require('./')({ + width: 60 +}) + +ui.div( + 'Usage: node ./bin/foo.js\n' + + ' \t provide a regex\n' + + ' \t provide a glob\t [required]' +) + +console.log(ui.toString()) +``` + +**will output:** + +```shell +Usage: node ./bin/foo.js + provide a regex + provide a glob [required] +``` + +## Methods + +```js +cliui = require('cliui') +``` + +### cliui({width: integer}) + +Specify the maximum width of the UI being generated. +If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. + +### cliui({wrap: boolean}) + +Enable or disable the wrapping of text in a column. + +### cliui.div(column, column, column) + +Create a row with any number of columns, a column +can either be a string, or an object with the following +options: + +* **text:** some text to place in the column. +* **width:** the width of a column. +* **align:** alignment, `right` or `center`. +* **padding:** `[top, right, bottom, left]`. +* **border:** should a border be placed around the div? + +### cliui.span(column, column, column) + +Similar to `div`, except the next row will be appended without +a new line being created. + +### cliui.resetOutput() + +Resets the UI elements of the current cliui instance, maintaining the values +set for `width` and `wrap`. diff --git a/node_modules/cliui/build/index.cjs b/node_modules/cliui/build/index.cjs new file mode 100644 index 0000000..82126b6 --- /dev/null +++ b/node_modules/cliui/build/index.cjs @@ -0,0 +1,302 @@ +'use strict'; + +const align = { + right: alignRight, + center: alignCenter +}; +const top = 0; +const right = 1; +const bottom = 2; +const left = 3; +class UI { + constructor(opts) { + var _a; + this.width = opts.width; + this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true; + this.rows = []; + } + span(...args) { + const cols = this.div(...args); + cols.span = true; + } + resetOutput() { + this.rows = []; + } + div(...args) { + if (args.length === 0) { + this.div(''); + } + if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') { + return this.applyLayoutDSL(args[0]); + } + const cols = args.map(arg => { + if (typeof arg === 'string') { + return this.colFromString(arg); + } + return arg; + }); + this.rows.push(cols); + return cols; + } + shouldApplyLayoutDSL(...args) { + return args.length === 1 && typeof args[0] === 'string' && + /[\t\n]/.test(args[0]); + } + applyLayoutDSL(str) { + const rows = str.split('\n').map(row => row.split('\t')); + let leftColumnWidth = 0; + // simple heuristic for layout, make sure the + // second column lines up along the left-hand. + // don't allow the first column to take up more + // than 50% of the screen. + rows.forEach(columns => { + if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) { + leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0])); + } + }); + // generate a table: + // replacing ' ' with padding calculations. + // using the algorithmically generated width. + rows.forEach(columns => { + this.div(...columns.map((r, i) => { + return { + text: r.trim(), + padding: this.measurePadding(r), + width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined + }; + })); + }); + return this.rows[this.rows.length - 1]; + } + colFromString(text) { + return { + text, + padding: this.measurePadding(text) + }; + } + measurePadding(str) { + // measure padding without ansi escape codes + const noAnsi = mixin.stripAnsi(str); + return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length]; + } + toString() { + const lines = []; + this.rows.forEach(row => { + this.rowToString(row, lines); + }); + // don't display any lines with the + // hidden flag set. + return lines + .filter(line => !line.hidden) + .map(line => line.text) + .join('\n'); + } + rowToString(row, lines) { + this.rasterize(row).forEach((rrow, r) => { + let str = ''; + rrow.forEach((col, c) => { + const { width } = row[c]; // the width with padding. + const wrapWidth = this.negatePadding(row[c]); // the width without padding. + let ts = col; // temporary string used during alignment/padding. + if (wrapWidth > mixin.stringWidth(col)) { + ts += ' '.repeat(wrapWidth - mixin.stringWidth(col)); + } + // align the string within its column. + if (row[c].align && row[c].align !== 'left' && this.wrap) { + const fn = align[row[c].align]; + ts = fn(ts, wrapWidth); + if (mixin.stringWidth(ts) < wrapWidth) { + ts += ' '.repeat((width || 0) - mixin.stringWidth(ts) - 1); + } + } + // apply border and padding to string. + const padding = row[c].padding || [0, 0, 0, 0]; + if (padding[left]) { + str += ' '.repeat(padding[left]); + } + str += addBorder(row[c], ts, '| '); + str += ts; + str += addBorder(row[c], ts, ' |'); + if (padding[right]) { + str += ' '.repeat(padding[right]); + } + // if prior row is span, try to render the + // current row on the prior line. + if (r === 0 && lines.length > 0) { + str = this.renderInline(str, lines[lines.length - 1]); + } + }); + // remove trailing whitespace. + lines.push({ + text: str.replace(/ +$/, ''), + span: row.span + }); + }); + return lines; + } + // if the full 'source' can render in + // the target line, do so. + renderInline(source, previousLine) { + const match = source.match(/^ */); + const leadingWhitespace = match ? match[0].length : 0; + const target = previousLine.text; + const targetTextWidth = mixin.stringWidth(target.trimRight()); + if (!previousLine.span) { + return source; + } + // if we're not applying wrapping logic, + // just always append to the span. + if (!this.wrap) { + previousLine.hidden = true; + return target + source; + } + if (leadingWhitespace < targetTextWidth) { + return source; + } + previousLine.hidden = true; + return target.trimRight() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimLeft(); + } + rasterize(row) { + const rrows = []; + const widths = this.columnWidths(row); + let wrapped; + // word wrap all columns, and create + // a data-structure that is easy to rasterize. + row.forEach((col, c) => { + // leave room for left and right padding. + col.width = widths[c]; + if (this.wrap) { + wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n'); + } + else { + wrapped = col.text.split('\n'); + } + if (col.border) { + wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.'); + wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'"); + } + // add top and bottom padding. + if (col.padding) { + wrapped.unshift(...new Array(col.padding[top] || 0).fill('')); + wrapped.push(...new Array(col.padding[bottom] || 0).fill('')); + } + wrapped.forEach((str, r) => { + if (!rrows[r]) { + rrows.push([]); + } + const rrow = rrows[r]; + for (let i = 0; i < c; i++) { + if (rrow[i] === undefined) { + rrow.push(''); + } + } + rrow.push(str); + }); + }); + return rrows; + } + negatePadding(col) { + let wrapWidth = col.width || 0; + if (col.padding) { + wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0); + } + if (col.border) { + wrapWidth -= 4; + } + return wrapWidth; + } + columnWidths(row) { + if (!this.wrap) { + return row.map(col => { + return col.width || mixin.stringWidth(col.text); + }); + } + let unset = row.length; + let remainingWidth = this.width; + // column widths can be set in config. + const widths = row.map(col => { + if (col.width) { + unset--; + remainingWidth -= col.width; + return col.width; + } + return undefined; + }); + // any unset widths should be calculated. + const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0; + return widths.map((w, i) => { + if (w === undefined) { + return Math.max(unsetWidth, _minWidth(row[i])); + } + return w; + }); + } +} +function addBorder(col, ts, style) { + if (col.border) { + if (/[.']-+[.']/.test(ts)) { + return ''; + } + if (ts.trim().length !== 0) { + return style; + } + return ' '; + } + return ''; +} +// calculates the minimum width of +// a column, based on padding preferences. +function _minWidth(col) { + const padding = col.padding || []; + const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0); + if (col.border) { + return minWidth + 4; + } + return minWidth; +} +function getWindowWidth() { + /* istanbul ignore next: depends on terminal */ + if (typeof process === 'object' && process.stdout && process.stdout.columns) { + return process.stdout.columns; + } + return 80; +} +function alignRight(str, width) { + str = str.trim(); + const strWidth = mixin.stringWidth(str); + if (strWidth < width) { + return ' '.repeat(width - strWidth) + str; + } + return str; +} +function alignCenter(str, width) { + str = str.trim(); + const strWidth = mixin.stringWidth(str); + /* istanbul ignore next */ + if (strWidth >= width) { + return str; + } + return ' '.repeat((width - strWidth) >> 1) + str; +} +let mixin; +function cliui(opts, _mixin) { + mixin = _mixin; + return new UI({ + width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(), + wrap: opts === null || opts === void 0 ? void 0 : opts.wrap + }); +} + +// Bootstrap cliui with CommonJS dependencies: +const stringWidth = require('string-width'); +const stripAnsi = require('strip-ansi'); +const wrap = require('wrap-ansi'); +function ui(opts) { + return cliui(opts, { + stringWidth, + stripAnsi, + wrap + }); +} + +module.exports = ui; diff --git a/node_modules/cliui/build/index.d.cts b/node_modules/cliui/build/index.d.cts new file mode 100644 index 0000000..4567f94 --- /dev/null +++ b/node_modules/cliui/build/index.d.cts @@ -0,0 +1,43 @@ +interface UIOptions { + width: number; + wrap?: boolean; + rows?: string[]; +} +interface Column { + text: string; + width?: number; + align?: "right" | "left" | "center"; + padding: number[]; + border?: boolean; +} +interface ColumnArray extends Array { + span: boolean; +} +interface Line { + hidden?: boolean; + text: string; + span?: boolean; +} +declare class UI { + width: number; + wrap: boolean; + rows: ColumnArray[]; + constructor(opts: UIOptions); + span(...args: ColumnArray): void; + resetOutput(): void; + div(...args: (Column | string)[]): ColumnArray; + private shouldApplyLayoutDSL; + private applyLayoutDSL; + private colFromString; + private measurePadding; + toString(): string; + rowToString(row: ColumnArray, lines: Line[]): Line[]; + // if the full 'source' can render in + // the target line, do so. + private renderInline; + private rasterize; + private negatePadding; + private columnWidths; +} +declare function ui(opts: UIOptions): UI; +export { ui as default }; diff --git a/node_modules/cliui/build/lib/index.js b/node_modules/cliui/build/lib/index.js new file mode 100644 index 0000000..b6eb054 --- /dev/null +++ b/node_modules/cliui/build/lib/index.js @@ -0,0 +1,287 @@ +'use strict'; +const align = { + right: alignRight, + center: alignCenter +}; +const top = 0; +const right = 1; +const bottom = 2; +const left = 3; +export class UI { + constructor(opts) { + var _a; + this.width = opts.width; + this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true; + this.rows = []; + } + span(...args) { + const cols = this.div(...args); + cols.span = true; + } + resetOutput() { + this.rows = []; + } + div(...args) { + if (args.length === 0) { + this.div(''); + } + if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') { + return this.applyLayoutDSL(args[0]); + } + const cols = args.map(arg => { + if (typeof arg === 'string') { + return this.colFromString(arg); + } + return arg; + }); + this.rows.push(cols); + return cols; + } + shouldApplyLayoutDSL(...args) { + return args.length === 1 && typeof args[0] === 'string' && + /[\t\n]/.test(args[0]); + } + applyLayoutDSL(str) { + const rows = str.split('\n').map(row => row.split('\t')); + let leftColumnWidth = 0; + // simple heuristic for layout, make sure the + // second column lines up along the left-hand. + // don't allow the first column to take up more + // than 50% of the screen. + rows.forEach(columns => { + if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) { + leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0])); + } + }); + // generate a table: + // replacing ' ' with padding calculations. + // using the algorithmically generated width. + rows.forEach(columns => { + this.div(...columns.map((r, i) => { + return { + text: r.trim(), + padding: this.measurePadding(r), + width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined + }; + })); + }); + return this.rows[this.rows.length - 1]; + } + colFromString(text) { + return { + text, + padding: this.measurePadding(text) + }; + } + measurePadding(str) { + // measure padding without ansi escape codes + const noAnsi = mixin.stripAnsi(str); + return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length]; + } + toString() { + const lines = []; + this.rows.forEach(row => { + this.rowToString(row, lines); + }); + // don't display any lines with the + // hidden flag set. + return lines + .filter(line => !line.hidden) + .map(line => line.text) + .join('\n'); + } + rowToString(row, lines) { + this.rasterize(row).forEach((rrow, r) => { + let str = ''; + rrow.forEach((col, c) => { + const { width } = row[c]; // the width with padding. + const wrapWidth = this.negatePadding(row[c]); // the width without padding. + let ts = col; // temporary string used during alignment/padding. + if (wrapWidth > mixin.stringWidth(col)) { + ts += ' '.repeat(wrapWidth - mixin.stringWidth(col)); + } + // align the string within its column. + if (row[c].align && row[c].align !== 'left' && this.wrap) { + const fn = align[row[c].align]; + ts = fn(ts, wrapWidth); + if (mixin.stringWidth(ts) < wrapWidth) { + ts += ' '.repeat((width || 0) - mixin.stringWidth(ts) - 1); + } + } + // apply border and padding to string. + const padding = row[c].padding || [0, 0, 0, 0]; + if (padding[left]) { + str += ' '.repeat(padding[left]); + } + str += addBorder(row[c], ts, '| '); + str += ts; + str += addBorder(row[c], ts, ' |'); + if (padding[right]) { + str += ' '.repeat(padding[right]); + } + // if prior row is span, try to render the + // current row on the prior line. + if (r === 0 && lines.length > 0) { + str = this.renderInline(str, lines[lines.length - 1]); + } + }); + // remove trailing whitespace. + lines.push({ + text: str.replace(/ +$/, ''), + span: row.span + }); + }); + return lines; + } + // if the full 'source' can render in + // the target line, do so. + renderInline(source, previousLine) { + const match = source.match(/^ */); + const leadingWhitespace = match ? match[0].length : 0; + const target = previousLine.text; + const targetTextWidth = mixin.stringWidth(target.trimRight()); + if (!previousLine.span) { + return source; + } + // if we're not applying wrapping logic, + // just always append to the span. + if (!this.wrap) { + previousLine.hidden = true; + return target + source; + } + if (leadingWhitespace < targetTextWidth) { + return source; + } + previousLine.hidden = true; + return target.trimRight() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimLeft(); + } + rasterize(row) { + const rrows = []; + const widths = this.columnWidths(row); + let wrapped; + // word wrap all columns, and create + // a data-structure that is easy to rasterize. + row.forEach((col, c) => { + // leave room for left and right padding. + col.width = widths[c]; + if (this.wrap) { + wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n'); + } + else { + wrapped = col.text.split('\n'); + } + if (col.border) { + wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.'); + wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'"); + } + // add top and bottom padding. + if (col.padding) { + wrapped.unshift(...new Array(col.padding[top] || 0).fill('')); + wrapped.push(...new Array(col.padding[bottom] || 0).fill('')); + } + wrapped.forEach((str, r) => { + if (!rrows[r]) { + rrows.push([]); + } + const rrow = rrows[r]; + for (let i = 0; i < c; i++) { + if (rrow[i] === undefined) { + rrow.push(''); + } + } + rrow.push(str); + }); + }); + return rrows; + } + negatePadding(col) { + let wrapWidth = col.width || 0; + if (col.padding) { + wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0); + } + if (col.border) { + wrapWidth -= 4; + } + return wrapWidth; + } + columnWidths(row) { + if (!this.wrap) { + return row.map(col => { + return col.width || mixin.stringWidth(col.text); + }); + } + let unset = row.length; + let remainingWidth = this.width; + // column widths can be set in config. + const widths = row.map(col => { + if (col.width) { + unset--; + remainingWidth -= col.width; + return col.width; + } + return undefined; + }); + // any unset widths should be calculated. + const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0; + return widths.map((w, i) => { + if (w === undefined) { + return Math.max(unsetWidth, _minWidth(row[i])); + } + return w; + }); + } +} +function addBorder(col, ts, style) { + if (col.border) { + if (/[.']-+[.']/.test(ts)) { + return ''; + } + if (ts.trim().length !== 0) { + return style; + } + return ' '; + } + return ''; +} +// calculates the minimum width of +// a column, based on padding preferences. +function _minWidth(col) { + const padding = col.padding || []; + const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0); + if (col.border) { + return minWidth + 4; + } + return minWidth; +} +function getWindowWidth() { + /* istanbul ignore next: depends on terminal */ + if (typeof process === 'object' && process.stdout && process.stdout.columns) { + return process.stdout.columns; + } + return 80; +} +function alignRight(str, width) { + str = str.trim(); + const strWidth = mixin.stringWidth(str); + if (strWidth < width) { + return ' '.repeat(width - strWidth) + str; + } + return str; +} +function alignCenter(str, width) { + str = str.trim(); + const strWidth = mixin.stringWidth(str); + /* istanbul ignore next */ + if (strWidth >= width) { + return str; + } + return ' '.repeat((width - strWidth) >> 1) + str; +} +let mixin; +export function cliui(opts, _mixin) { + mixin = _mixin; + return new UI({ + width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(), + wrap: opts === null || opts === void 0 ? void 0 : opts.wrap + }); +} diff --git a/node_modules/cliui/build/lib/string-utils.js b/node_modules/cliui/build/lib/string-utils.js new file mode 100644 index 0000000..4b87453 --- /dev/null +++ b/node_modules/cliui/build/lib/string-utils.js @@ -0,0 +1,27 @@ +// Minimal replacement for ansi string helpers "wrap-ansi" and "strip-ansi". +// to facilitate ESM and Deno modules. +// TODO: look at porting https://www.npmjs.com/package/wrap-ansi to ESM. +// The npm application +// Copyright (c) npm, Inc. and Contributors +// Licensed on the terms of The Artistic License 2.0 +// See: https://github.com/npm/cli/blob/4c65cd952bc8627811735bea76b9b110cc4fc80e/lib/utils/ansi-trim.js +const ansi = new RegExp('\x1b(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|' + + '\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)', 'g'); +export function stripAnsi(str) { + return str.replace(ansi, ''); +} +export function wrap(str, width) { + const [start, end] = str.match(ansi) || ['', '']; + str = stripAnsi(str); + let wrapped = ''; + for (let i = 0; i < str.length; i++) { + if (i !== 0 && (i % width) === 0) { + wrapped += '\n'; + } + wrapped += str.charAt(i); + } + if (start && end) { + wrapped = `${start}${wrapped}${end}`; + } + return wrapped; +} diff --git a/node_modules/cliui/index.mjs b/node_modules/cliui/index.mjs new file mode 100644 index 0000000..bc7a022 --- /dev/null +++ b/node_modules/cliui/index.mjs @@ -0,0 +1,13 @@ +// Bootstrap cliui with CommonJS dependencies: +import { cliui } from './build/lib/index.js' +import { wrap, stripAnsi } from './build/lib/string-utils.js' + +export default function ui (opts) { + return cliui(opts, { + stringWidth: (str) => { + return [...str].length + }, + stripAnsi, + wrap + }) +} diff --git a/node_modules/cliui/package.json b/node_modules/cliui/package.json new file mode 100644 index 0000000..eab6bf4 --- /dev/null +++ b/node_modules/cliui/package.json @@ -0,0 +1,83 @@ +{ + "name": "cliui", + "version": "8.0.1", + "description": "easily create complex multi-column command-line-interfaces", + "main": "build/index.cjs", + "exports": { + ".": [ + { + "import": "./index.mjs", + "require": "./build/index.cjs" + }, + "./build/index.cjs" + ] + }, + "type": "module", + "module": "./index.mjs", + "scripts": { + "check": "standardx '**/*.ts' && standardx '**/*.js' && standardx '**/*.cjs'", + "fix": "standardx --fix '**/*.ts' && standardx --fix '**/*.js' && standardx --fix '**/*.cjs'", + "pretest": "rimraf build && tsc -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs", + "test": "c8 mocha ./test/*.cjs", + "test:esm": "c8 mocha ./test/esm/cliui-test.mjs", + "postest": "check", + "coverage": "c8 report --check-coverage", + "precompile": "rimraf build", + "compile": "tsc", + "postcompile": "npm run build:cjs", + "build:cjs": "rollup -c", + "prepare": "npm run compile" + }, + "repository": "yargs/cliui", + "standard": { + "ignore": [ + "**/example/**" + ], + "globals": [ + "it" + ] + }, + "keywords": [ + "cli", + "command-line", + "layout", + "design", + "console", + "wrap", + "table" + ], + "author": "Ben Coe ", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "devDependencies": { + "@types/node": "^14.0.27", + "@typescript-eslint/eslint-plugin": "^4.0.0", + "@typescript-eslint/parser": "^4.0.0", + "c8": "^7.3.0", + "chai": "^4.2.0", + "chalk": "^4.1.0", + "cross-env": "^7.0.2", + "eslint": "^7.6.0", + "eslint-plugin-import": "^2.22.0", + "eslint-plugin-node": "^11.1.0", + "gts": "^3.0.0", + "mocha": "^10.0.0", + "rimraf": "^3.0.2", + "rollup": "^2.23.1", + "rollup-plugin-ts": "^3.0.2", + "standardx": "^7.0.0", + "typescript": "^4.0.0" + }, + "files": [ + "build", + "index.mjs", + "!*.d.ts" + ], + "engines": { + "node": ">=12" + } +} diff --git a/node_modules/color-convert/CHANGELOG.md b/node_modules/color-convert/CHANGELOG.md new file mode 100644 index 0000000..0a7bce4 --- /dev/null +++ b/node_modules/color-convert/CHANGELOG.md @@ -0,0 +1,54 @@ +# 1.0.0 - 2016-01-07 + +- Removed: unused speed test +- Added: Automatic routing between previously unsupported conversions +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Removed: `xxx2xxx()` and `xxx2xxxRaw()` functions +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Removed: `convert()` class +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Changed: all functions to lookup dictionary +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Changed: `ansi` to `ansi256` +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Fixed: argument grouping for functions requiring only one argument +([#27](https://github.com/Qix-/color-convert/pull/27)) + +# 0.6.0 - 2015-07-23 + +- Added: methods to handle +[ANSI](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) 16/256 colors: + - rgb2ansi16 + - rgb2ansi + - hsl2ansi16 + - hsl2ansi + - hsv2ansi16 + - hsv2ansi + - hwb2ansi16 + - hwb2ansi + - cmyk2ansi16 + - cmyk2ansi + - keyword2ansi16 + - keyword2ansi + - ansi162rgb + - ansi162hsl + - ansi162hsv + - ansi162hwb + - ansi162cmyk + - ansi162keyword + - ansi2rgb + - ansi2hsl + - ansi2hsv + - ansi2hwb + - ansi2cmyk + - ansi2keyword +([#18](https://github.com/harthur/color-convert/pull/18)) + +# 0.5.3 - 2015-06-02 + +- Fixed: hsl2hsv does not return `NaN` anymore when using `[0,0,0]` +([#15](https://github.com/harthur/color-convert/issues/15)) + +--- + +Check out commit logs for older releases diff --git a/node_modules/color-convert/LICENSE b/node_modules/color-convert/LICENSE new file mode 100644 index 0000000..5b4c386 --- /dev/null +++ b/node_modules/color-convert/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2011-2016 Heather Arthur + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/color-convert/README.md b/node_modules/color-convert/README.md new file mode 100644 index 0000000..d4b08fc --- /dev/null +++ b/node_modules/color-convert/README.md @@ -0,0 +1,68 @@ +# color-convert + +[![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert) + +Color-convert is a color conversion library for JavaScript and node. +It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest): + +```js +var convert = require('color-convert'); + +convert.rgb.hsl(140, 200, 100); // [96, 48, 59] +convert.keyword.rgb('blue'); // [0, 0, 255] + +var rgbChannels = convert.rgb.channels; // 3 +var cmykChannels = convert.cmyk.channels; // 4 +var ansiChannels = convert.ansi16.channels; // 1 +``` + +# Install + +```console +$ npm install color-convert +``` + +# API + +Simply get the property of the _from_ and _to_ conversion that you're looking for. + +All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function. + +All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha). + +```js +var convert = require('color-convert'); + +// Hex to LAB +convert.hex.lab('DEADBF'); // [ 76, 21, -2 ] +convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ] + +// RGB to CMYK +convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ] +convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ] +``` + +### Arrays +All functions that accept multiple arguments also support passing an array. + +Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.) + +```js +var convert = require('color-convert'); + +convert.rgb.hex(123, 45, 67); // '7B2D43' +convert.rgb.hex([123, 45, 67]); // '7B2D43' +``` + +## Routing + +Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex). + +Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js). + +# Contribute + +If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request. + +# License +Copyright © 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE). diff --git a/node_modules/color-convert/conversions.js b/node_modules/color-convert/conversions.js new file mode 100644 index 0000000..2657f26 --- /dev/null +++ b/node_modules/color-convert/conversions.js @@ -0,0 +1,839 @@ +/* MIT license */ +/* eslint-disable no-mixed-operators */ +const cssKeywords = require('color-name'); + +// NOTE: conversions should only return primitive values (i.e. arrays, or +// values that give correct `typeof` results). +// do not use box values types (i.e. Number(), String(), etc.) + +const reverseKeywords = {}; +for (const key of Object.keys(cssKeywords)) { + reverseKeywords[cssKeywords[key]] = key; +} + +const convert = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} +}; + +module.exports = convert; + +// Hide .channels and .labels properties +for (const model of Object.keys(convert)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + const {channels, labels} = convert[model]; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', {value: channels}); + Object.defineProperty(convert[model], 'labels', {value: labels}); +} + +convert.rgb.hsl = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const min = Math.min(r, g, b); + const max = Math.max(r, g, b); + const delta = max - min; + let h; + let s; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + const l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; +}; + +convert.rgb.hsv = function (rgb) { + let rdif; + let gdif; + let bdif; + let h; + let s; + + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const v = Math.max(r, g, b); + const diff = v - Math.min(r, g, b); + const diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = 0; + s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = (1 / 3) + rdif - bdif; + } else if (b === v) { + h = (2 / 3) + gdif - rdif; + } + + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [ + h * 360, + s * 100, + v * 100 + ]; +}; + +convert.rgb.hwb = function (rgb) { + const r = rgb[0]; + const g = rgb[1]; + let b = rgb[2]; + const h = convert.rgb.hsl(rgb)[0]; + const w = 1 / 255 * Math.min(r, Math.min(g, b)); + + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; +}; + +convert.rgb.cmyk = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + + const k = Math.min(1 - r, 1 - g, 1 - b); + const c = (1 - r - k) / (1 - k) || 0; + const m = (1 - g - k) / (1 - k) || 0; + const y = (1 - b - k) / (1 - k) || 0; + + return [c * 100, m * 100, y * 100, k * 100]; +}; + +function comparativeDistance(x, y) { + /* + See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + */ + return ( + ((x[0] - y[0]) ** 2) + + ((x[1] - y[1]) ** 2) + + ((x[2] - y[2]) ** 2) + ); +} + +convert.rgb.keyword = function (rgb) { + const reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + + let currentClosestDistance = Infinity; + let currentClosestKeyword; + + for (const keyword of Object.keys(cssKeywords)) { + const value = cssKeywords[keyword]; + + // Compute comparative distance + const distance = comparativeDistance(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + + return currentClosestKeyword; +}; + +convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; +}; + +convert.rgb.xyz = function (rgb) { + let r = rgb[0] / 255; + let g = rgb[1] / 255; + let b = rgb[2] / 255; + + // Assume sRGB + r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); + g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); + b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); + + const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y * 100, z * 100]; +}; + +convert.rgb.lab = function (rgb) { + const xyz = convert.rgb.xyz(rgb); + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); + + const l = (116 * y) - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.hsl.rgb = function (hsl) { + const h = hsl[0] / 360; + const s = hsl[1] / 100; + const l = hsl[2] / 100; + let t2; + let t3; + let val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + const t1 = 2 * l - t2; + + const rgb = [0, 0, 0]; + for (let i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; +}; + +convert.hsl.hsv = function (hsl) { + const h = hsl[0]; + let s = hsl[1] / 100; + let l = hsl[2] / 100; + let smin = s; + const lmin = Math.max(l, 0.01); + + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + const v = (l + s) / 2; + const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); + + return [h, sv * 100, v * 100]; +}; + +convert.hsv.rgb = function (hsv) { + const h = hsv[0] / 60; + const s = hsv[1] / 100; + let v = hsv[2] / 100; + const hi = Math.floor(h) % 6; + + const f = h - Math.floor(h); + const p = 255 * v * (1 - s); + const q = 255 * v * (1 - (s * f)); + const t = 255 * v * (1 - (s * (1 - f))); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } +}; + +convert.hsv.hsl = function (hsv) { + const h = hsv[0]; + const s = hsv[1] / 100; + const v = hsv[2] / 100; + const vmin = Math.max(v, 0.01); + let sl; + let l; + + l = (2 - s) * v; + const lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + + return [h, sl * 100, l * 100]; +}; + +// http://dev.w3.org/csswg/css-color/#hwb-to-rgb +convert.hwb.rgb = function (hwb) { + const h = hwb[0] / 360; + let wh = hwb[1] / 100; + let bl = hwb[2] / 100; + const ratio = wh + bl; + let f; + + // Wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + const i = Math.floor(6 * h); + const v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + const n = wh + f * (v - wh); // Linear interpolation + + let r; + let g; + let b; + /* eslint-disable max-statements-per-line,no-multi-spaces */ + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + /* eslint-enable max-statements-per-line,no-multi-spaces */ + + return [r * 255, g * 255, b * 255]; +}; + +convert.cmyk.rgb = function (cmyk) { + const c = cmyk[0] / 100; + const m = cmyk[1] / 100; + const y = cmyk[2] / 100; + const k = cmyk[3] / 100; + + const r = 1 - Math.min(1, c * (1 - k) + k); + const g = 1 - Math.min(1, m * (1 - k) + k); + const b = 1 - Math.min(1, y * (1 - k) + k); + + return [r * 255, g * 255, b * 255]; +}; + +convert.xyz.rgb = function (xyz) { + const x = xyz[0] / 100; + const y = xyz[1] / 100; + const z = xyz[2] / 100; + let r; + let g; + let b; + + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + + // Assume sRGB + r = r > 0.0031308 + ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) + : r * 12.92; + + g = g > 0.0031308 + ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) + : g * 12.92; + + b = b > 0.0031308 + ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) + : b * 12.92; + + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; +}; + +convert.xyz.lab = function (xyz) { + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); + + const l = (116 * y) - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.lab.xyz = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let x; + let y; + let z; + + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + + const y2 = y ** 3; + const x2 = x ** 3; + const z2 = z ** 3; + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + + x *= 95.047; + y *= 100; + z *= 108.883; + + return [x, y, z]; +}; + +convert.lab.lch = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let h; + + const hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + const c = Math.sqrt(a * a + b * b); + + return [l, c, h]; +}; + +convert.lch.lab = function (lch) { + const l = lch[0]; + const c = lch[1]; + const h = lch[2]; + + const hr = h / 360 * 2 * Math.PI; + const a = c * Math.cos(hr); + const b = c * Math.sin(hr); + + return [l, a, b]; +}; + +convert.rgb.ansi16 = function (args, saturation = null) { + const [r, g, b] = args; + let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + let ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; +}; + +convert.hsv.ansi16 = function (args) { + // Optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); +}; + +convert.rgb.ansi256 = function (args) { + const r = args[0]; + const g = args[1]; + const b = args[2]; + + // We use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round(((r - 8) / 247) * 24) + 232; + } + + const ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); + + return ansi; +}; + +convert.ansi16.rgb = function (args) { + let color = args % 10; + + // Handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + + return [color, color, color]; + } + + const mult = (~~(args > 50) + 1) * 0.5; + const r = ((color & 1) * mult) * 255; + const g = (((color >> 1) & 1) * mult) * 255; + const b = (((color >> 2) & 1) * mult) * 255; + + return [r, g, b]; +}; + +convert.ansi256.rgb = function (args) { + // Handle greyscale + if (args >= 232) { + const c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + + let rem; + const r = Math.floor(args / 36) / 5 * 255; + const g = Math.floor((rem = args % 36) / 6) / 5 * 255; + const b = (rem % 6) / 5 * 255; + + return [r, g, b]; +}; + +convert.rgb.hex = function (args) { + const integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); + + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert.hex.rgb = function (args) { + const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + + let colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(char => { + return char + char; + }).join(''); + } + + const integer = parseInt(colorString, 16); + const r = (integer >> 16) & 0xFF; + const g = (integer >> 8) & 0xFF; + const b = integer & 0xFF; + + return [r, g, b]; +}; + +convert.rgb.hcg = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const max = Math.max(Math.max(r, g), b); + const min = Math.min(Math.min(r, g), b); + const chroma = (max - min); + let grayscale; + let hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma; + } + + hue /= 6; + hue %= 1; + + return [hue * 360, chroma * 100, grayscale * 100]; +}; + +convert.hsl.hcg = function (hsl) { + const s = hsl[1] / 100; + const l = hsl[2] / 100; + + const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); + + let f = 0; + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; +}; + +convert.hsv.hcg = function (hsv) { + const s = hsv[1] / 100; + const v = hsv[2] / 100; + + const c = s * v; + let f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; +}; + +convert.hcg.rgb = function (hcg) { + const h = hcg[0] / 360; + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + const pure = [0, 0, 0]; + const hi = (h % 1) * 6; + const v = hi % 1; + const w = 1 - v; + let mg = 0; + + /* eslint-disable max-statements-per-line */ + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } + /* eslint-enable max-statements-per-line */ + + mg = (1.0 - c) * g; + + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; +}; + +convert.hcg.hsv = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + const v = c + g * (1.0 - c); + let f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; +}; + +convert.hcg.hsl = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + const l = g * (1.0 - c) + 0.5 * c; + let s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; +}; + +convert.hcg.hwb = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; +}; + +convert.hwb.hcg = function (hwb) { + const w = hwb[1] / 100; + const b = hwb[2] / 100; + const v = 1 - b; + const c = v - w; + let g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; +}; + +convert.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; +}; + +convert.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; +}; + +convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; +}; + +convert.gray.hsl = function (args) { + return [0, 0, args[0]]; +}; + +convert.gray.hsv = convert.gray.hsl; + +convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; +}; + +convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; +}; + +convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; +}; + +convert.gray.hex = function (gray) { + const val = Math.round(gray[0] / 100 * 255) & 0xFF; + const integer = (val << 16) + (val << 8) + val; + + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert.rgb.gray = function (rgb) { + const val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; +}; diff --git a/node_modules/color-convert/index.js b/node_modules/color-convert/index.js new file mode 100644 index 0000000..b648e57 --- /dev/null +++ b/node_modules/color-convert/index.js @@ -0,0 +1,81 @@ +const conversions = require('./conversions'); +const route = require('./route'); + +const convert = {}; + +const models = Object.keys(conversions); + +function wrapRaw(fn) { + const wrappedFn = function (...args) { + const arg0 = args[0]; + if (arg0 === undefined || arg0 === null) { + return arg0; + } + + if (arg0.length > 1) { + args = arg0; + } + + return fn(args); + }; + + // Preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +function wrapRounded(fn) { + const wrappedFn = function (...args) { + const arg0 = args[0]; + + if (arg0 === undefined || arg0 === null) { + return arg0; + } + + if (arg0.length > 1) { + args = arg0; + } + + const result = fn(args); + + // We're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (let len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; + + // Preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +models.forEach(fromModel => { + convert[fromModel] = {}; + + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); + + const routes = route(fromModel); + const routeModels = Object.keys(routes); + + routeModels.forEach(toModel => { + const fn = routes[toModel]; + + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); +}); + +module.exports = convert; diff --git a/node_modules/color-convert/package.json b/node_modules/color-convert/package.json new file mode 100644 index 0000000..6e48000 --- /dev/null +++ b/node_modules/color-convert/package.json @@ -0,0 +1,48 @@ +{ + "name": "color-convert", + "description": "Plain color conversion functions", + "version": "2.0.1", + "author": "Heather Arthur ", + "license": "MIT", + "repository": "Qix-/color-convert", + "scripts": { + "pretest": "xo", + "test": "node test/basic.js" + }, + "engines": { + "node": ">=7.0.0" + }, + "keywords": [ + "color", + "colour", + "convert", + "converter", + "conversion", + "rgb", + "hsl", + "hsv", + "hwb", + "cmyk", + "ansi", + "ansi16" + ], + "files": [ + "index.js", + "conversions.js", + "route.js" + ], + "xo": { + "rules": { + "default-case": 0, + "no-inline-comments": 0, + "operator-linebreak": 0 + } + }, + "devDependencies": { + "chalk": "^2.4.2", + "xo": "^0.24.0" + }, + "dependencies": { + "color-name": "~1.1.4" + } +} diff --git a/node_modules/color-convert/route.js b/node_modules/color-convert/route.js new file mode 100644 index 0000000..1a08521 --- /dev/null +++ b/node_modules/color-convert/route.js @@ -0,0 +1,97 @@ +const conversions = require('./conversions'); + +/* + This function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. +*/ + +function buildGraph() { + const graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + const models = Object.keys(conversions); + + for (let len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; +} + +// https://en.wikipedia.org/wiki/Breadth-first_search +function deriveBFS(fromModel) { + const graph = buildGraph(); + const queue = [fromModel]; // Unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + const current = queue.pop(); + const adjacents = Object.keys(conversions[current]); + + for (let len = adjacents.length, i = 0; i < len; i++) { + const adjacent = adjacents[i]; + const node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; +} + +function link(from, to) { + return function (args) { + return to(from(args)); + }; +} + +function wrapConversion(toModel, graph) { + const path = [graph[toModel].parent, toModel]; + let fn = conversions[graph[toModel].parent][toModel]; + + let cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; +} + +module.exports = function (fromModel) { + const graph = deriveBFS(fromModel); + const conversion = {}; + + const models = Object.keys(graph); + for (let len = models.length, i = 0; i < len; i++) { + const toModel = models[i]; + const node = graph[toModel]; + + if (node.parent === null) { + // No possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; +}; + diff --git a/node_modules/color-name/LICENSE b/node_modules/color-name/LICENSE new file mode 100644 index 0000000..4d9802a --- /dev/null +++ b/node_modules/color-name/LICENSE @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright (c) 2015 Dmitry Ivanov + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/color-name/README.md b/node_modules/color-name/README.md new file mode 100644 index 0000000..3611a6b --- /dev/null +++ b/node_modules/color-name/README.md @@ -0,0 +1,11 @@ +A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors. + +[![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/) + + +```js +var colors = require('color-name'); +colors.red //[255,0,0] +``` + + diff --git a/node_modules/color-name/index.js b/node_modules/color-name/index.js new file mode 100644 index 0000000..e42aa68 --- /dev/null +++ b/node_modules/color-name/index.js @@ -0,0 +1,152 @@ +'use strict' + +module.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; diff --git a/node_modules/color-name/package.json b/node_modules/color-name/package.json new file mode 100644 index 0000000..7acc902 --- /dev/null +++ b/node_modules/color-name/package.json @@ -0,0 +1,28 @@ +{ + "name": "color-name", + "version": "1.1.4", + "description": "A list of color names and its values", + "main": "index.js", + "files": [ + "index.js" + ], + "scripts": { + "test": "node test.js" + }, + "repository": { + "type": "git", + "url": "git@github.com:colorjs/color-name.git" + }, + "keywords": [ + "color-name", + "color", + "color-keyword", + "keyword" + ], + "author": "DY ", + "license": "MIT", + "bugs": { + "url": "https://github.com/colorjs/color-name/issues" + }, + "homepage": "https://github.com/colorjs/color-name" +} diff --git a/node_modules/combined-stream/License b/node_modules/combined-stream/License new file mode 100644 index 0000000..4804b7a --- /dev/null +++ b/node_modules/combined-stream/License @@ -0,0 +1,19 @@ +Copyright (c) 2011 Debuggable Limited + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/combined-stream/Readme.md b/node_modules/combined-stream/Readme.md new file mode 100644 index 0000000..9e367b5 --- /dev/null +++ b/node_modules/combined-stream/Readme.md @@ -0,0 +1,138 @@ +# combined-stream + +A stream that emits multiple other streams one after another. + +**NB** Currently `combined-stream` works with streams version 1 only. There is ongoing effort to switch this library to streams version 2. Any help is welcome. :) Meanwhile you can explore other libraries that provide streams2 support with more or less compatibility with `combined-stream`. + +- [combined-stream2](https://www.npmjs.com/package/combined-stream2): A drop-in streams2-compatible replacement for the combined-stream module. + +- [multistream](https://www.npmjs.com/package/multistream): A stream that emits multiple other streams one after another. + +## Installation + +``` bash +npm install combined-stream +``` + +## Usage + +Here is a simple example that shows how you can use combined-stream to combine +two files into one: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create(); +combinedStream.append(fs.createReadStream('file1.txt')); +combinedStream.append(fs.createReadStream('file2.txt')); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +While the example above works great, it will pause all source streams until +they are needed. If you don't want that to happen, you can set `pauseStreams` +to `false`: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create({pauseStreams: false}); +combinedStream.append(fs.createReadStream('file1.txt')); +combinedStream.append(fs.createReadStream('file2.txt')); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +However, what if you don't have all the source streams yet, or you don't want +to allocate the resources (file descriptors, memory, etc.) for them right away? +Well, in that case you can simply provide a callback that supplies the stream +by calling a `next()` function: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create(); +combinedStream.append(function(next) { + next(fs.createReadStream('file1.txt')); +}); +combinedStream.append(function(next) { + next(fs.createReadStream('file2.txt')); +}); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +## API + +### CombinedStream.create([options]) + +Returns a new combined stream object. Available options are: + +* `maxDataSize` +* `pauseStreams` + +The effect of those options is described below. + +### combinedStream.pauseStreams = `true` + +Whether to apply back pressure to the underlaying streams. If set to `false`, +the underlaying streams will never be paused. If set to `true`, the +underlaying streams will be paused right after being appended, as well as when +`delayedStream.pipe()` wants to throttle. + +### combinedStream.maxDataSize = `2 * 1024 * 1024` + +The maximum amount of bytes (or characters) to buffer for all source streams. +If this value is exceeded, `combinedStream` emits an `'error'` event. + +### combinedStream.dataSize = `0` + +The amount of bytes (or characters) currently buffered by `combinedStream`. + +### combinedStream.append(stream) + +Appends the given `stream` to the combinedStream object. If `pauseStreams` is +set to `true, this stream will also be paused right away. + +`streams` can also be a function that takes one parameter called `next`. `next` +is a function that must be invoked in order to provide the `next` stream, see +example above. + +Regardless of how the `stream` is appended, combined-stream always attaches an +`'error'` listener to it, so you don't have to do that manually. + +Special case: `stream` can also be a String or Buffer. + +### combinedStream.write(data) + +You should not call this, `combinedStream` takes care of piping the appended +streams into itself for you. + +### combinedStream.resume() + +Causes `combinedStream` to start drain the streams it manages. The function is +idempotent, and also emits a `'resume'` event each time which usually goes to +the stream that is currently being drained. + +### combinedStream.pause(); + +If `combinedStream.pauseStreams` is set to `false`, this does nothing. +Otherwise a `'pause'` event is emitted, this goes to the stream that is +currently being drained, so you can use it to apply back pressure. + +### combinedStream.end(); + +Sets `combinedStream.writable` to false, emits an `'end'` event, and removes +all streams from the queue. + +### combinedStream.destroy(); + +Same as `combinedStream.end()`, except it emits a `'close'` event instead of +`'end'`. + +## License + +combined-stream is licensed under the MIT license. diff --git a/node_modules/combined-stream/lib/combined_stream.js b/node_modules/combined-stream/lib/combined_stream.js new file mode 100644 index 0000000..125f097 --- /dev/null +++ b/node_modules/combined-stream/lib/combined_stream.js @@ -0,0 +1,208 @@ +var util = require('util'); +var Stream = require('stream').Stream; +var DelayedStream = require('delayed-stream'); + +module.exports = CombinedStream; +function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; + + this._released = false; + this._streams = []; + this._currentStream = null; + this._insideLoop = false; + this._pendingNext = false; +} +util.inherits(CombinedStream, Stream); + +CombinedStream.create = function(options) { + var combinedStream = new this(); + + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; + } + + return combinedStream; +}; + +CombinedStream.isStreamLike = function(stream) { + return (typeof stream !== 'function') + && (typeof stream !== 'string') + && (typeof stream !== 'boolean') + && (typeof stream !== 'number') + && (!Buffer.isBuffer(stream)); +}; + +CombinedStream.prototype.append = function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + + if (isStreamLike) { + if (!(stream instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams, + }); + stream.on('data', this._checkDataSize.bind(this)); + stream = newStream; + } + + this._handleErrors(stream); + + if (this.pauseStreams) { + stream.pause(); + } + } + + this._streams.push(stream); + return this; +}; + +CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; +}; + +CombinedStream.prototype._getNext = function() { + this._currentStream = null; + + if (this._insideLoop) { + this._pendingNext = true; + return; // defer call + } + + this._insideLoop = true; + try { + do { + this._pendingNext = false; + this._realGetNext(); + } while (this._pendingNext); + } finally { + this._insideLoop = false; + } +}; + +CombinedStream.prototype._realGetNext = function() { + var stream = this._streams.shift(); + + + if (typeof stream == 'undefined') { + this.end(); + return; + } + + if (typeof stream !== 'function') { + this._pipeNext(stream); + return; + } + + var getStream = stream; + getStream(function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('data', this._checkDataSize.bind(this)); + this._handleErrors(stream); + } + + this._pipeNext(stream); + }.bind(this)); +}; + +CombinedStream.prototype._pipeNext = function(stream) { + this._currentStream = stream; + + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('end', this._getNext.bind(this)); + stream.pipe(this, {end: false}); + return; + } + + var value = stream; + this.write(value); + this._getNext(); +}; + +CombinedStream.prototype._handleErrors = function(stream) { + var self = this; + stream.on('error', function(err) { + self._emitError(err); + }); +}; + +CombinedStream.prototype.write = function(data) { + this.emit('data', data); +}; + +CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; + } + + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); + this.emit('pause'); +}; + +CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); + } + + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); + this.emit('resume'); +}; + +CombinedStream.prototype.end = function() { + this._reset(); + this.emit('end'); +}; + +CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit('close'); +}; + +CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; +}; + +CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; + } + + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; + this._emitError(new Error(message)); +}; + +CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; + + var self = this; + this._streams.forEach(function(stream) { + if (!stream.dataSize) { + return; + } + + self.dataSize += stream.dataSize; + }); + + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; + } +}; + +CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit('error', err); +}; diff --git a/node_modules/combined-stream/package.json b/node_modules/combined-stream/package.json new file mode 100644 index 0000000..6982b6d --- /dev/null +++ b/node_modules/combined-stream/package.json @@ -0,0 +1,25 @@ +{ + "author": "Felix Geisendörfer (http://debuggable.com/)", + "name": "combined-stream", + "description": "A stream that emits multiple other streams one after another.", + "version": "1.0.8", + "homepage": "https://github.com/felixge/node-combined-stream", + "repository": { + "type": "git", + "url": "git://github.com/felixge/node-combined-stream.git" + }, + "main": "./lib/combined_stream", + "scripts": { + "test": "node test/run.js" + }, + "engines": { + "node": ">= 0.8" + }, + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "devDependencies": { + "far": "~0.0.7" + }, + "license": "MIT" +} diff --git a/node_modules/combined-stream/yarn.lock b/node_modules/combined-stream/yarn.lock new file mode 100644 index 0000000..7edf418 --- /dev/null +++ b/node_modules/combined-stream/yarn.lock @@ -0,0 +1,17 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +delayed-stream@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" + +far@~0.0.7: + version "0.0.7" + resolved "https://registry.yarnpkg.com/far/-/far-0.0.7.tgz#01c1fd362bcd26ce9cf161af3938aa34619f79a7" + dependencies: + oop "0.0.3" + +oop@0.0.3: + version "0.0.3" + resolved "https://registry.yarnpkg.com/oop/-/oop-0.0.3.tgz#70fa405a5650891a194fdc82ca68dad6dabf4401" diff --git a/node_modules/debug/LICENSE b/node_modules/debug/LICENSE new file mode 100644 index 0000000..1a9820e --- /dev/null +++ b/node_modules/debug/LICENSE @@ -0,0 +1,20 @@ +(The MIT License) + +Copyright (c) 2014-2017 TJ Holowaychuk +Copyright (c) 2018-2021 Josh Junon + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software +and associated documentation files (the 'Software'), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/debug/README.md b/node_modules/debug/README.md new file mode 100644 index 0000000..9ebdfbf --- /dev/null +++ b/node_modules/debug/README.md @@ -0,0 +1,481 @@ +# debug +[![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) +[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) + + + +A tiny JavaScript debugging utility modelled after Node.js core's debugging +technique. Works in Node.js and web browsers. + +## Installation + +```bash +$ npm install debug +``` + +## Usage + +`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. + +Example [_app.js_](./examples/node/app.js): + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %o', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example [_worker.js_](./examples/node/worker.js): + +```js +var a = require('debug')('worker:a') + , b = require('debug')('worker:b'); + +function work() { + a('doing lots of uninteresting work'); + setTimeout(work, Math.random() * 1000); +} + +work(); + +function workb() { + b('doing some work'); + setTimeout(workb, Math.random() * 2000); +} + +workb(); +``` + +The `DEBUG` environment variable is then used to enable these based on space or +comma-delimited names. + +Here are some examples: + +screen shot 2017-08-08 at 12 53 04 pm +screen shot 2017-08-08 at 12 53 38 pm +screen shot 2017-08-08 at 12 53 25 pm + +#### Windows command prompt notes + +##### CMD + +On Windows the environment variable is set using the `set` command. + +```cmd +set DEBUG=*,-not_this +``` + +Example: + +```cmd +set DEBUG=* & node app.js +``` + +##### PowerShell (VS Code default) + +PowerShell uses different syntax to set environment variables. + +```cmd +$env:DEBUG = "*,-not_this" +``` + +Example: + +```cmd +$env:DEBUG='app';node app.js +``` + +Then, run the program to be debugged as usual. + +npm script example: +```js + "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", +``` + +## Namespace Colors + +Every debug instance has a color generated for it based on its namespace name. +This helps when visually parsing the debug output to identify which debug instance +a debug line belongs to. + +#### Node.js + +In Node.js, colors are enabled when stderr is a TTY. You also _should_ install +the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, +otherwise debug will only use a small handful of basic colors. + + + +#### Web Browser + +Colors are also enabled on "Web Inspectors" that understand the `%c` formatting +option. These are WebKit web inspectors, Firefox ([since version +31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) +and the Firebug plugin for Firefox (any version). + + + + +## Millisecond diff + +When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + + +When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: + + + + +## Conventions + +If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. + +## Wildcards + +The `*` character may be used as a wildcard. Suppose for example your library has +debuggers named "connect:bodyParser", "connect:compress", "connect:session", +instead of listing all three with +`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do +`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + +You can also exclude specific debuggers by prefixing them with a "-" character. +For example, `DEBUG=*,-connect:*` would include all debuggers except those +starting with "connect:". + +## Environment Variables + +When running through Node.js, you can set a few environment variables that will +change the behavior of the debug logging: + +| Name | Purpose | +|-----------|-------------------------------------------------| +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | +| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + + +__Note:__ The environment variables beginning with `DEBUG_` end up being +converted into an Options object that gets used with `%o`/`%O` formatters. +See the Node.js documentation for +[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) +for the complete list. + +## Formatters + +Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. +Below are the officially supported formatters: + +| Formatter | Representation | +|-----------|----------------| +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%s` | String. | +| `%d` | Number (both integer and float). | +| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| `%%` | Single percent sign ('%'). This does not consume an argument. | + + +### Custom formatters + +You can add custom formatters by extending the `debug.formatters` object. +For example, if you wanted to add support for rendering a Buffer as hex with +`%h`, you could do something like: + +```js +const createDebug = require('debug') +createDebug.formatters.h = (v) => { + return v.toString('hex') +} + +// …elsewhere +const debug = createDebug('foo') +debug('this is hex: %h', new Buffer('hello world')) +// foo this is hex: 68656c6c6f20776f726c6421 +0ms +``` + + +## Browser Support + +You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), +or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), +if you don't want to build it yourself. + +Debug's enable state is currently persisted by `localStorage`. +Consider the situation shown below where you have `worker:a` and `worker:b`, +and wish to debug both. You can enable this using `localStorage.debug`: + +```js +localStorage.debug = 'worker:*' +``` + +And then refresh the page. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + b('doing some work'); +}, 1200); +``` + +In Chromium-based web browsers (e.g. Brave, Chrome, and Electron), the JavaScript console will—by default—only show messages logged by `debug` if the "Verbose" log level is _enabled_. + + + +## Output streams + + By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: + +Example [_stdout.js_](./examples/node/stdout.js): + +```js +var debug = require('debug'); +var error = debug('app:error'); + +// by default stderr is used +error('goes to stderr!'); + +var log = debug('app:log'); +// set this namespace to log via console.log +log.log = console.log.bind(console); // don't forget to bind to console! +log('goes to stdout'); +error('still goes to stderr!'); + +// set all output to go via console.info +// overrides all per-namespace log settings +debug.log = console.info.bind(console); +error('now goes to stdout via console.info'); +log('still goes to stdout, but via console.info now'); +``` + +## Extend +You can simply extend debugger +```js +const log = require('debug')('auth'); + +//creates new debug instance with extended namespace +const logSign = log.extend('sign'); +const logLogin = log.extend('login'); + +log('hello'); // auth hello +logSign('hello'); //auth:sign hello +logLogin('hello'); //auth:login hello +``` + +## Set dynamically + +You can also enable debug dynamically by calling the `enable()` method : + +```js +let debug = require('debug'); + +console.log(1, debug.enabled('test')); + +debug.enable('test'); +console.log(2, debug.enabled('test')); + +debug.disable(); +console.log(3, debug.enabled('test')); + +``` + +print : +``` +1 false +2 true +3 false +``` + +Usage : +`enable(namespaces)` +`namespaces` can include modes separated by a colon and wildcards. + +Note that calling `enable()` completely overrides previously set DEBUG variable : + +``` +$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' +=> false +``` + +`disable()` + +Will disable all namespaces. The functions returns the namespaces currently +enabled (and skipped). This can be useful if you want to disable debugging +temporarily without knowing what was enabled to begin with. + +For example: + +```js +let debug = require('debug'); +debug.enable('foo:*,-foo:bar'); +let namespaces = debug.disable(); +debug.enable(namespaces); +``` + +Note: There is no guarantee that the string will be identical to the initial +enable string, but semantically they will be identical. + +## Checking whether a debug target is enabled + +After you've created a debug instance, you can determine whether or not it is +enabled by checking the `enabled` property: + +```javascript +const debug = require('debug')('http'); + +if (debug.enabled) { + // do stuff... +} +``` + +You can also manually toggle this property to force the debug instance to be +enabled or disabled. + +## Usage in child processes + +Due to the way `debug` detects if the output is a TTY or not, colors are not shown in child processes when `stderr` is piped. A solution is to pass the `DEBUG_COLORS=1` environment variable to the child process. +For example: + +```javascript +worker = fork(WORKER_WRAP_PATH, [workerPath], { + stdio: [ + /* stdin: */ 0, + /* stdout: */ 'pipe', + /* stderr: */ 'pipe', + 'ipc', + ], + env: Object.assign({}, process.env, { + DEBUG_COLORS: 1 // without this settings, colors won't be shown + }), +}); + +worker.stderr.pipe(process.stderr, { end: false }); +``` + + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + - Andrew Rhyne + - Josh Junon + +## Backers + +Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Sponsors + +Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## License + +(The MIT License) + +Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca> +Copyright (c) 2018-2021 Josh Junon + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/debug/package.json b/node_modules/debug/package.json new file mode 100644 index 0000000..ee8abb5 --- /dev/null +++ b/node_modules/debug/package.json @@ -0,0 +1,64 @@ +{ + "name": "debug", + "version": "4.4.3", + "repository": { + "type": "git", + "url": "git://github.com/debug-js/debug.git" + }, + "description": "Lightweight debugging utility for Node.js and the browser", + "keywords": [ + "debug", + "log", + "debugger" + ], + "files": [ + "src", + "LICENSE", + "README.md" + ], + "author": "Josh Junon (https://github.com/qix-)", + "contributors": [ + "TJ Holowaychuk ", + "Nathan Rajlich (http://n8.io)", + "Andrew Rhyne " + ], + "license": "MIT", + "scripts": { + "lint": "xo", + "test": "npm run test:node && npm run test:browser && npm run lint", + "test:node": "mocha test.js test.node.js", + "test:browser": "karma start --single-run", + "test:coverage": "cat ./coverage/lcov.info | coveralls" + }, + "dependencies": { + "ms": "^2.1.3" + }, + "devDependencies": { + "brfs": "^2.0.1", + "browserify": "^16.2.3", + "coveralls": "^3.0.2", + "karma": "^3.1.4", + "karma-browserify": "^6.0.0", + "karma-chrome-launcher": "^2.2.0", + "karma-mocha": "^1.3.0", + "mocha": "^5.2.0", + "mocha-lcov-reporter": "^1.2.0", + "sinon": "^14.0.0", + "xo": "^0.23.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + }, + "main": "./src/index.js", + "browser": "./src/browser.js", + "engines": { + "node": ">=6.0" + }, + "xo": { + "rules": { + "import/extensions": "off" + } + } +} diff --git a/node_modules/debug/src/browser.js b/node_modules/debug/src/browser.js new file mode 100644 index 0000000..5993451 --- /dev/null +++ b/node_modules/debug/src/browser.js @@ -0,0 +1,272 @@ +/* eslint-env browser */ + +/** + * This is the web browser implementation of `debug()`. + */ + +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); + +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + let m; + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + // eslint-disable-next-line no-return-assign + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +module.exports = require('./common')(exports); + +const {formatters} = module.exports; + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; diff --git a/node_modules/debug/src/common.js b/node_modules/debug/src/common.js new file mode 100644 index 0000000..141cb57 --- /dev/null +++ b/node_modules/debug/src/common.js @@ -0,0 +1,292 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require('ms'); + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + + createDebug.names = []; + createDebug.skips = []; + + const split = (typeof namespaces === 'string' ? namespaces : '') + .trim() + .replace(/\s+/g, ',') + .split(',') + .filter(Boolean); + + for (const ns of split) { + if (ns[0] === '-') { + createDebug.skips.push(ns.slice(1)); + } else { + createDebug.names.push(ns); + } + } + } + + /** + * Checks if the given string matches a namespace template, honoring + * asterisks as wildcards. + * + * @param {String} search + * @param {String} template + * @return {Boolean} + */ + function matchesTemplate(search, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; + + while (searchIndex < search.length) { + if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) { + // Match character or proceed with wildcard + if (template[templateIndex] === '*') { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; // Skip the '*' + } else { + searchIndex++; + templateIndex++; + } + } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition + // Backtrack to the last '*' and try to match more characters + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; + } else { + return false; // No match + } + } + + // Handle trailing '*' in template + while (templateIndex < template.length && template[templateIndex] === '*') { + templateIndex++; + } + + return templateIndex === template.length; + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names, + ...createDebug.skips.map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + for (const skip of createDebug.skips) { + if (matchesTemplate(name, skip)) { + return false; + } + } + + for (const ns of createDebug.names) { + if (matchesTemplate(name, ns)) { + return true; + } + } + + return false; + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; +} + +module.exports = setup; diff --git a/node_modules/debug/src/index.js b/node_modules/debug/src/index.js new file mode 100644 index 0000000..bf4c57f --- /dev/null +++ b/node_modules/debug/src/index.js @@ -0,0 +1,10 @@ +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +} diff --git a/node_modules/debug/src/node.js b/node_modules/debug/src/node.js new file mode 100644 index 0000000..715560a --- /dev/null +++ b/node_modules/debug/src/node.js @@ -0,0 +1,263 @@ +/** + * Module dependencies. + */ + +const tty = require('tty'); +const util = require('util'); + +/** + * This is the Node.js implementation of `debug()`. + */ + +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = require('supports-color'); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; +}, {}); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} + +/** + * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr. + */ + +function log(...args) { + return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +module.exports = require('./common')(exports); + +const {formatters} = module.exports; + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; + +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; diff --git a/node_modules/delayed-stream/.npmignore b/node_modules/delayed-stream/.npmignore new file mode 100644 index 0000000..9daeafb --- /dev/null +++ b/node_modules/delayed-stream/.npmignore @@ -0,0 +1 @@ +test diff --git a/node_modules/delayed-stream/License b/node_modules/delayed-stream/License new file mode 100644 index 0000000..4804b7a --- /dev/null +++ b/node_modules/delayed-stream/License @@ -0,0 +1,19 @@ +Copyright (c) 2011 Debuggable Limited + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/delayed-stream/Makefile b/node_modules/delayed-stream/Makefile new file mode 100644 index 0000000..b4ff85a --- /dev/null +++ b/node_modules/delayed-stream/Makefile @@ -0,0 +1,7 @@ +SHELL := /bin/bash + +test: + @./test/run.js + +.PHONY: test + diff --git a/node_modules/delayed-stream/Readme.md b/node_modules/delayed-stream/Readme.md new file mode 100644 index 0000000..aca36f9 --- /dev/null +++ b/node_modules/delayed-stream/Readme.md @@ -0,0 +1,141 @@ +# delayed-stream + +Buffers events from a stream until you are ready to handle them. + +## Installation + +``` bash +npm install delayed-stream +``` + +## Usage + +The following example shows how to write a http echo server that delays its +response by 1000 ms. + +``` javascript +var DelayedStream = require('delayed-stream'); +var http = require('http'); + +http.createServer(function(req, res) { + var delayed = DelayedStream.create(req); + + setTimeout(function() { + res.writeHead(200); + delayed.pipe(res); + }, 1000); +}); +``` + +If you are not using `Stream#pipe`, you can also manually release the buffered +events by calling `delayedStream.resume()`: + +``` javascript +var delayed = DelayedStream.create(req); + +setTimeout(function() { + // Emit all buffered events and resume underlaying source + delayed.resume(); +}, 1000); +``` + +## Implementation + +In order to use this meta stream properly, here are a few things you should +know about the implementation. + +### Event Buffering / Proxying + +All events of the `source` stream are hijacked by overwriting the `source.emit` +method. Until node implements a catch-all event listener, this is the only way. + +However, delayed-stream still continues to emit all events it captures on the +`source`, regardless of whether you have released the delayed stream yet or +not. + +Upon creation, delayed-stream captures all `source` events and stores them in +an internal event buffer. Once `delayedStream.release()` is called, all +buffered events are emitted on the `delayedStream`, and the event buffer is +cleared. After that, delayed-stream merely acts as a proxy for the underlaying +source. + +### Error handling + +Error events on `source` are buffered / proxied just like any other events. +However, `delayedStream.create` attaches a no-op `'error'` listener to the +`source`. This way you only have to handle errors on the `delayedStream` +object, rather than in two places. + +### Buffer limits + +delayed-stream provides a `maxDataSize` property that can be used to limit +the amount of data being buffered. In order to protect you from bad `source` +streams that don't react to `source.pause()`, this feature is enabled by +default. + +## API + +### DelayedStream.create(source, [options]) + +Returns a new `delayedStream`. Available options are: + +* `pauseStream` +* `maxDataSize` + +The description for those properties can be found below. + +### delayedStream.source + +The `source` stream managed by this object. This is useful if you are +passing your `delayedStream` around, and you still want to access properties +on the `source` object. + +### delayedStream.pauseStream = true + +Whether to pause the underlaying `source` when calling +`DelayedStream.create()`. Modifying this property afterwards has no effect. + +### delayedStream.maxDataSize = 1024 * 1024 + +The amount of data to buffer before emitting an `error`. + +If the underlaying source is emitting `Buffer` objects, the `maxDataSize` +refers to bytes. + +If the underlaying source is emitting JavaScript strings, the size refers to +characters. + +If you know what you are doing, you can set this property to `Infinity` to +disable this feature. You can also modify this property during runtime. + +### delayedStream.dataSize = 0 + +The amount of data buffered so far. + +### delayedStream.readable + +An ECMA5 getter that returns the value of `source.readable`. + +### delayedStream.resume() + +If the `delayedStream` has not been released so far, `delayedStream.release()` +is called. + +In either case, `source.resume()` is called. + +### delayedStream.pause() + +Calls `source.pause()`. + +### delayedStream.pipe(dest) + +Calls `delayedStream.resume()` and then proxies the arguments to `source.pipe`. + +### delayedStream.release() + +Emits and clears all events that have been buffered up so far. This does not +resume the underlaying source, use `delayedStream.resume()` instead. + +## License + +delayed-stream is licensed under the MIT license. diff --git a/node_modules/delayed-stream/lib/delayed_stream.js b/node_modules/delayed-stream/lib/delayed_stream.js new file mode 100644 index 0000000..b38fc85 --- /dev/null +++ b/node_modules/delayed-stream/lib/delayed_stream.js @@ -0,0 +1,107 @@ +var Stream = require('stream').Stream; +var util = require('util'); + +module.exports = DelayedStream; +function DelayedStream() { + this.source = null; + this.dataSize = 0; + this.maxDataSize = 1024 * 1024; + this.pauseStream = true; + + this._maxDataSizeExceeded = false; + this._released = false; + this._bufferedEvents = []; +} +util.inherits(DelayedStream, Stream); + +DelayedStream.create = function(source, options) { + var delayedStream = new this(); + + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; + } + + delayedStream.source = source; + + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); + }; + + source.on('error', function() {}); + if (delayedStream.pauseStream) { + source.pause(); + } + + return delayedStream; +}; + +Object.defineProperty(DelayedStream.prototype, 'readable', { + configurable: true, + enumerable: true, + get: function() { + return this.source.readable; + } +}); + +DelayedStream.prototype.setEncoding = function() { + return this.source.setEncoding.apply(this.source, arguments); +}; + +DelayedStream.prototype.resume = function() { + if (!this._released) { + this.release(); + } + + this.source.resume(); +}; + +DelayedStream.prototype.pause = function() { + this.source.pause(); +}; + +DelayedStream.prototype.release = function() { + this._released = true; + + this._bufferedEvents.forEach(function(args) { + this.emit.apply(this, args); + }.bind(this)); + this._bufferedEvents = []; +}; + +DelayedStream.prototype.pipe = function() { + var r = Stream.prototype.pipe.apply(this, arguments); + this.resume(); + return r; +}; + +DelayedStream.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); + return; + } + + if (args[0] === 'data') { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); + } + + this._bufferedEvents.push(args); +}; + +DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { + return; + } + + if (this.dataSize <= this.maxDataSize) { + return; + } + + this._maxDataSizeExceeded = true; + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' + this.emit('error', new Error(message)); +}; diff --git a/node_modules/delayed-stream/package.json b/node_modules/delayed-stream/package.json new file mode 100644 index 0000000..eea3291 --- /dev/null +++ b/node_modules/delayed-stream/package.json @@ -0,0 +1,27 @@ +{ + "author": "Felix Geisendörfer (http://debuggable.com/)", + "contributors": [ + "Mike Atkins " + ], + "name": "delayed-stream", + "description": "Buffers events from a stream until you are ready to handle them.", + "license": "MIT", + "version": "1.0.0", + "homepage": "https://github.com/felixge/node-delayed-stream", + "repository": { + "type": "git", + "url": "git://github.com/felixge/node-delayed-stream.git" + }, + "main": "./lib/delayed_stream", + "engines": { + "node": ">=0.4.0" + }, + "scripts": { + "test": "make test" + }, + "dependencies": {}, + "devDependencies": { + "fake": "0.2.0", + "far": "0.0.1" + } +} diff --git a/node_modules/dunder-proto/.eslintrc b/node_modules/dunder-proto/.eslintrc new file mode 100644 index 0000000..3b5d9e9 --- /dev/null +++ b/node_modules/dunder-proto/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/node_modules/dunder-proto/.github/FUNDING.yml b/node_modules/dunder-proto/.github/FUNDING.yml new file mode 100644 index 0000000..8a1d7b0 --- /dev/null +++ b/node_modules/dunder-proto/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/dunder-proto +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/dunder-proto/.nycrc b/node_modules/dunder-proto/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/dunder-proto/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/dunder-proto/CHANGELOG.md b/node_modules/dunder-proto/CHANGELOG.md new file mode 100644 index 0000000..9b8b2f8 --- /dev/null +++ b/node_modules/dunder-proto/CHANGELOG.md @@ -0,0 +1,24 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.1](https://github.com/es-shims/dunder-proto/compare/v1.0.0...v1.0.1) - 2024-12-16 + +### Commits + +- [Fix] do not crash when `--disable-proto=throw` [`6c367d9`](https://github.com/es-shims/dunder-proto/commit/6c367d919bc1604778689a297bbdbfea65752847) +- [Tests] ensure noproto tests only use the current version of dunder-proto [`b02365b`](https://github.com/es-shims/dunder-proto/commit/b02365b9cf889c4a2cac7be0c3cfc90a789af36c) +- [Dev Deps] update `@arethetypeswrong/cli`, `@types/tape` [`e3c5c3b`](https://github.com/es-shims/dunder-proto/commit/e3c5c3bd81cf8cef7dff2eca19e558f0e307f666) +- [Deps] update `call-bind-apply-helpers` [`19f1da0`](https://github.com/es-shims/dunder-proto/commit/19f1da028b8dd0d05c85bfd8f7eed2819b686450) + +## v1.0.0 - 2024-12-06 + +### Commits + +- Initial implementation, tests, readme, types [`a5b74b0`](https://github.com/es-shims/dunder-proto/commit/a5b74b0082f5270cb0905cd9a2e533cee7498373) +- Initial commit [`73fb5a3`](https://github.com/es-shims/dunder-proto/commit/73fb5a353b51ac2ab00c9fdeb0114daffd4c07a8) +- npm init [`80152dc`](https://github.com/es-shims/dunder-proto/commit/80152dc98155da4eb046d9f67a87ed96e8280a1d) +- Only apps should have lockfiles [`03e6660`](https://github.com/es-shims/dunder-proto/commit/03e6660a1d70dc401f3e217a031475ec537243dd) diff --git a/node_modules/dunder-proto/LICENSE b/node_modules/dunder-proto/LICENSE new file mode 100644 index 0000000..34995e7 --- /dev/null +++ b/node_modules/dunder-proto/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 ECMAScript Shims + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/dunder-proto/README.md b/node_modules/dunder-proto/README.md new file mode 100644 index 0000000..44b80a2 --- /dev/null +++ b/node_modules/dunder-proto/README.md @@ -0,0 +1,54 @@ +# dunder-proto [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +If available, the `Object.prototype.__proto__` accessor and mutator, call-bound. + +## Getting started + +```sh +npm install --save dunder-proto +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const getDunder = require('dunder-proto/get'); +const setDunder = require('dunder-proto/set'); + +const obj = {}; + +assert.equal('toString' in obj, true); +assert.equal(getDunder(obj), Object.prototype); + +setDunder(obj, null); + +assert.equal('toString' in obj, false); +assert.equal(getDunder(obj), null); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/dunder-proto +[npm-version-svg]: https://versionbadg.es/es-shims/dunder-proto.svg +[deps-svg]: https://david-dm.org/es-shims/dunder-proto.svg +[deps-url]: https://david-dm.org/es-shims/dunder-proto +[dev-deps-svg]: https://david-dm.org/es-shims/dunder-proto/dev-status.svg +[dev-deps-url]: https://david-dm.org/es-shims/dunder-proto#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/dunder-proto.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/dunder-proto.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/dunder-proto.svg +[downloads-url]: https://npm-stat.com/charts.html?package=dunder-proto +[codecov-image]: https://codecov.io/gh/es-shims/dunder-proto/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/es-shims/dunder-proto/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/es-shims/dunder-proto +[actions-url]: https://github.com/es-shims/dunder-proto/actions diff --git a/node_modules/dunder-proto/get.d.ts b/node_modules/dunder-proto/get.d.ts new file mode 100644 index 0000000..c7e14d2 --- /dev/null +++ b/node_modules/dunder-proto/get.d.ts @@ -0,0 +1,5 @@ +declare function getDunderProto(target: {}): object | null; + +declare const x: false | typeof getDunderProto; + +export = x; \ No newline at end of file diff --git a/node_modules/dunder-proto/get.js b/node_modules/dunder-proto/get.js new file mode 100644 index 0000000..45093df --- /dev/null +++ b/node_modules/dunder-proto/get.js @@ -0,0 +1,30 @@ +'use strict'; + +var callBind = require('call-bind-apply-helpers'); +var gOPD = require('gopd'); + +var hasProtoAccessor; +try { + // eslint-disable-next-line no-extra-parens, no-proto + hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ ([]).__proto__ === Array.prototype; +} catch (e) { + if (!e || typeof e !== 'object' || !('code' in e) || e.code !== 'ERR_PROTO_ACCESS') { + throw e; + } +} + +// eslint-disable-next-line no-extra-parens +var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, /** @type {keyof typeof Object.prototype} */ ('__proto__')); + +var $Object = Object; +var $getPrototypeOf = $Object.getPrototypeOf; + +/** @type {import('./get')} */ +module.exports = desc && typeof desc.get === 'function' + ? callBind([desc.get]) + : typeof $getPrototypeOf === 'function' + ? /** @type {import('./get')} */ function getDunder(value) { + // eslint-disable-next-line eqeqeq + return $getPrototypeOf(value == null ? value : $Object(value)); + } + : false; diff --git a/node_modules/dunder-proto/package.json b/node_modules/dunder-proto/package.json new file mode 100644 index 0000000..04a4036 --- /dev/null +++ b/node_modules/dunder-proto/package.json @@ -0,0 +1,76 @@ +{ + "name": "dunder-proto", + "version": "1.0.1", + "description": "If available, the `Object.prototype.__proto__` accessor and mutator, call-bound", + "main": false, + "exports": { + "./get": "./get.js", + "./set": "./set.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=.js,.mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>= 10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/es-shims/dunder-proto.git" + }, + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/es-shims/dunder-proto/issues" + }, + "homepage": "https://github.com/es-shims/dunder-proto#readme", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.1", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/tape": "^5.7.0", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "testling": { + "files": "test/index.js" + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/dunder-proto/set.d.ts b/node_modules/dunder-proto/set.d.ts new file mode 100644 index 0000000..16bfdfe --- /dev/null +++ b/node_modules/dunder-proto/set.d.ts @@ -0,0 +1,5 @@ +declare function setDunderProto

                          (target: {}, proto: P): P; + +declare const x: false | typeof setDunderProto; + +export = x; \ No newline at end of file diff --git a/node_modules/dunder-proto/set.js b/node_modules/dunder-proto/set.js new file mode 100644 index 0000000..6085b6e --- /dev/null +++ b/node_modules/dunder-proto/set.js @@ -0,0 +1,35 @@ +'use strict'; + +var callBind = require('call-bind-apply-helpers'); +var gOPD = require('gopd'); +var $TypeError = require('es-errors/type'); + +/** @type {{ __proto__?: object | null }} */ +var obj = {}; +try { + obj.__proto__ = null; // eslint-disable-line no-proto +} catch (e) { + if (!e || typeof e !== 'object' || !('code' in e) || e.code !== 'ERR_PROTO_ACCESS') { + throw e; + } +} + +var hasProtoMutator = !('toString' in obj); + +// eslint-disable-next-line no-extra-parens +var desc = gOPD && gOPD(Object.prototype, /** @type {keyof typeof Object.prototype} */ ('__proto__')); + +/** @type {import('./set')} */ +module.exports = hasProtoMutator && ( +// eslint-disable-next-line no-extra-parens + (!!desc && typeof desc.set === 'function' && /** @type {import('./set')} */ (callBind([desc.set]))) + || /** @type {import('./set')} */ function setDunder(object, proto) { + // this is node v0.10 or older, which doesn't have Object.setPrototypeOf and has undeniable __proto__ + if (object == null) { // eslint-disable-line eqeqeq + throw new $TypeError('set Object.prototype.__proto__ called on null or undefined'); + } + // eslint-disable-next-line no-proto, no-param-reassign, no-extra-parens + /** @type {{ __proto__?: object | null }} */ (object).__proto__ = proto; + return proto; + } +); diff --git a/node_modules/dunder-proto/test/get.js b/node_modules/dunder-proto/test/get.js new file mode 100644 index 0000000..253f183 --- /dev/null +++ b/node_modules/dunder-proto/test/get.js @@ -0,0 +1,34 @@ +'use strict'; + +var test = require('tape'); + +var getDunderProto = require('../get'); + +test('getDunderProto', { skip: !getDunderProto }, function (t) { + if (!getDunderProto) { + throw 'should never happen; this is just for type narrowing'; // eslint-disable-line no-throw-literal + } + + // @ts-expect-error + t['throws'](function () { getDunderProto(); }, TypeError, 'throws if no argument'); + // @ts-expect-error + t['throws'](function () { getDunderProto(undefined); }, TypeError, 'throws with undefined'); + // @ts-expect-error + t['throws'](function () { getDunderProto(null); }, TypeError, 'throws with null'); + + t.equal(getDunderProto({}), Object.prototype); + t.equal(getDunderProto([]), Array.prototype); + t.equal(getDunderProto(function () {}), Function.prototype); + t.equal(getDunderProto(/./g), RegExp.prototype); + t.equal(getDunderProto(42), Number.prototype); + t.equal(getDunderProto(true), Boolean.prototype); + t.equal(getDunderProto('foo'), String.prototype); + + t.end(); +}); + +test('no dunder proto', { skip: !!getDunderProto }, function (t) { + t.notOk('__proto__' in Object.prototype, 'no __proto__ in Object.prototype'); + + t.end(); +}); diff --git a/node_modules/dunder-proto/test/index.js b/node_modules/dunder-proto/test/index.js new file mode 100644 index 0000000..08ff36f --- /dev/null +++ b/node_modules/dunder-proto/test/index.js @@ -0,0 +1,4 @@ +'use strict'; + +require('./get'); +require('./set'); diff --git a/node_modules/dunder-proto/test/set.js b/node_modules/dunder-proto/test/set.js new file mode 100644 index 0000000..c3bfe4d --- /dev/null +++ b/node_modules/dunder-proto/test/set.js @@ -0,0 +1,50 @@ +'use strict'; + +var test = require('tape'); + +var setDunderProto = require('../set'); + +test('setDunderProto', { skip: !setDunderProto }, function (t) { + if (!setDunderProto) { + throw 'should never happen; this is just for type narrowing'; // eslint-disable-line no-throw-literal + } + + // @ts-expect-error + t['throws'](function () { setDunderProto(); }, TypeError, 'throws if no arguments'); + // @ts-expect-error + t['throws'](function () { setDunderProto(undefined); }, TypeError, 'throws with undefined and nothing'); + // @ts-expect-error + t['throws'](function () { setDunderProto(undefined, undefined); }, TypeError, 'throws with undefined and undefined'); + // @ts-expect-error + t['throws'](function () { setDunderProto(null); }, TypeError, 'throws with null and undefined'); + // @ts-expect-error + t['throws'](function () { setDunderProto(null, undefined); }, TypeError, 'throws with null and undefined'); + + /** @type {{ inherited?: boolean }} */ + var obj = {}; + t.ok('toString' in obj, 'object initially has toString'); + + setDunderProto(obj, null); + t.notOk('toString' in obj, 'object no longer has toString'); + + t.notOk('inherited' in obj, 'object lacks inherited property'); + setDunderProto(obj, { inherited: true }); + t.equal(obj.inherited, true, 'object has inherited property'); + + t.end(); +}); + +test('no dunder proto', { skip: !!setDunderProto }, function (t) { + if ('__proto__' in Object.prototype) { + t['throws']( + // @ts-expect-error + function () { ({}).__proto__ = null; }, // eslint-disable-line no-proto + Error, + 'throws when setting Object.prototype.__proto__' + ); + } else { + t.notOk('__proto__' in Object.prototype, 'no __proto__ in Object.prototype'); + } + + t.end(); +}); diff --git a/node_modules/dunder-proto/tsconfig.json b/node_modules/dunder-proto/tsconfig.json new file mode 100644 index 0000000..dabbe23 --- /dev/null +++ b/node_modules/dunder-proto/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "ES2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/duplexify/.travis.yml b/node_modules/duplexify/.travis.yml new file mode 100644 index 0000000..37494af --- /dev/null +++ b/node_modules/duplexify/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +arch: + - amd64 + - ppc64le +node_js: + - "4" + - "6" + - "8" + - "10" diff --git a/node_modules/duplexify/LICENSE b/node_modules/duplexify/LICENSE new file mode 100644 index 0000000..757562e --- /dev/null +++ b/node_modules/duplexify/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Mathias Buus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/duplexify/README.md b/node_modules/duplexify/README.md new file mode 100644 index 0000000..8352900 --- /dev/null +++ b/node_modules/duplexify/README.md @@ -0,0 +1,97 @@ +# duplexify + +Turn a writeable and readable stream into a single streams2 duplex stream. + +Similar to [duplexer2](https://github.com/deoxxa/duplexer2) except it supports both streams2 and streams1 as input +and it allows you to set the readable and writable part asynchronously using `setReadable(stream)` and `setWritable(stream)` + +``` +npm install duplexify +``` + +[![build status](http://img.shields.io/travis/mafintosh/duplexify.svg?style=flat)](http://travis-ci.org/mafintosh/duplexify) + +## Usage + +Use `duplexify(writable, readable, streamOptions)` (or `duplexify.obj(writable, readable)` to create an object stream) + +``` js +var duplexify = require('duplexify') + +// turn writableStream and readableStream into a single duplex stream +var dup = duplexify(writableStream, readableStream) + +dup.write('hello world') // will write to writableStream +dup.on('data', function(data) { + // will read from readableStream +}) +``` + +You can also set the readable and writable parts asynchronously + +``` js +var dup = duplexify() + +dup.write('hello world') // write will buffer until the writable + // part has been set + +// wait a bit ... +dup.setReadable(readableStream) + +// maybe wait some more? +dup.setWritable(writableStream) +``` + +If you call `setReadable` or `setWritable` multiple times it will unregister the previous readable/writable stream. +To disable the readable or writable part call `setReadable` or `setWritable` with `null`. + +If the readable or writable streams emits an error or close it will destroy both streams and bubble up the event. +You can also explicitly destroy the streams by calling `dup.destroy()`. The `destroy` method optionally takes an +error object as argument, in which case the error is emitted as part of the `error` event. + +``` js +dup.on('error', function(err) { + console.log('readable or writable emitted an error - close will follow') +}) + +dup.on('close', function() { + console.log('the duplex stream is destroyed') +}) + +dup.destroy() // calls destroy on the readable and writable part (if present) +``` + +## HTTP request example + +Turn a node core http request into a duplex stream is as easy as + +``` js +var duplexify = require('duplexify') +var http = require('http') + +var request = function(opts) { + var req = http.request(opts) + var dup = duplexify(req) + req.on('response', function(res) { + dup.setReadable(res) + }) + return dup +} + +var req = request({ + method: 'GET', + host: 'www.google.com', + port: 80 +}) + +req.end() +req.pipe(process.stdout) +``` + +## License + +MIT + +## Related + +`duplexify` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one. diff --git a/node_modules/duplexify/example.js b/node_modules/duplexify/example.js new file mode 100644 index 0000000..5585c19 --- /dev/null +++ b/node_modules/duplexify/example.js @@ -0,0 +1,21 @@ +var duplexify = require('duplexify') +var http = require('http') + +var request = function(opts) { + var req = http.request(opts) + var dup = duplexify() + dup.setWritable(req) + req.on('response', function(res) { + dup.setReadable(res) + }) + return dup +} + +var req = request({ + method: 'GET', + host: 'www.google.com', + port: 80 +}) + +req.end() +req.pipe(process.stdout) diff --git a/node_modules/duplexify/index.js b/node_modules/duplexify/index.js new file mode 100644 index 0000000..3430fe4 --- /dev/null +++ b/node_modules/duplexify/index.js @@ -0,0 +1,238 @@ +var stream = require('readable-stream') +var eos = require('end-of-stream') +var inherits = require('inherits') +var shift = require('stream-shift') + +var SIGNAL_FLUSH = (Buffer.from && Buffer.from !== Uint8Array.from) + ? Buffer.from([0]) + : new Buffer([0]) + +var onuncork = function(self, fn) { + if (self._corked) self.once('uncork', fn) + else fn() +} + +var autoDestroy = function (self, err) { + if (self._autoDestroy) self.destroy(err) +} + +var destroyer = function(self, end) { + return function(err) { + if (err) autoDestroy(self, err.message === 'premature close' ? null : err) + else if (end && !self._ended) self.end() + } +} + +var end = function(ws, fn) { + if (!ws) return fn() + if (ws._writableState && ws._writableState.finished) return fn() + if (ws._writableState) return ws.end(fn) + ws.end() + fn() +} + +var noop = function() {} + +var toStreams2 = function(rs) { + return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs) +} + +var Duplexify = function(writable, readable, opts) { + if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts) + stream.Duplex.call(this, opts) + + this._writable = null + this._readable = null + this._readable2 = null + + this._autoDestroy = !opts || opts.autoDestroy !== false + this._forwardDestroy = !opts || opts.destroy !== false + this._forwardEnd = !opts || opts.end !== false + this._corked = 1 // start corked + this._ondrain = null + this._drained = false + this._forwarding = false + this._unwrite = null + this._unread = null + this._ended = false + + this.destroyed = false + + if (writable) this.setWritable(writable) + if (readable) this.setReadable(readable) +} + +inherits(Duplexify, stream.Duplex) + +Duplexify.obj = function(writable, readable, opts) { + if (!opts) opts = {} + opts.objectMode = true + opts.highWaterMark = 16 + return new Duplexify(writable, readable, opts) +} + +Duplexify.prototype.cork = function() { + if (++this._corked === 1) this.emit('cork') +} + +Duplexify.prototype.uncork = function() { + if (this._corked && --this._corked === 0) this.emit('uncork') +} + +Duplexify.prototype.setWritable = function(writable) { + if (this._unwrite) this._unwrite() + + if (this.destroyed) { + if (writable && writable.destroy) writable.destroy() + return + } + + if (writable === null || writable === false) { + this.end() + return + } + + var self = this + var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd)) + + var ondrain = function() { + var ondrain = self._ondrain + self._ondrain = null + if (ondrain) ondrain() + } + + var clear = function() { + self._writable.removeListener('drain', ondrain) + unend() + } + + if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks + + this._writable = writable + this._writable.on('drain', ondrain) + this._unwrite = clear + + this.uncork() // always uncork setWritable +} + +Duplexify.prototype.setReadable = function(readable) { + if (this._unread) this._unread() + + if (this.destroyed) { + if (readable && readable.destroy) readable.destroy() + return + } + + if (readable === null || readable === false) { + this.push(null) + this.resume() + return + } + + var self = this + var unend = eos(readable, {writable:false, readable:true}, destroyer(this)) + + var onreadable = function() { + self._forward() + } + + var onend = function() { + self.push(null) + } + + var clear = function() { + self._readable2.removeListener('readable', onreadable) + self._readable2.removeListener('end', onend) + unend() + } + + this._drained = true + this._readable = readable + this._readable2 = readable._readableState ? readable : toStreams2(readable) + this._readable2.on('readable', onreadable) + this._readable2.on('end', onend) + this._unread = clear + + this._forward() +} + +Duplexify.prototype._read = function() { + this._drained = true + this._forward() +} + +Duplexify.prototype._forward = function() { + if (this._forwarding || !this._readable2 || !this._drained) return + this._forwarding = true + + var data + + while (this._drained && (data = shift(this._readable2)) !== null) { + if (this.destroyed) continue + this._drained = this.push(data) + } + + this._forwarding = false +} + +Duplexify.prototype.destroy = function(err, cb) { + if (!cb) cb = noop + if (this.destroyed) return cb(null) + this.destroyed = true + + var self = this + process.nextTick(function() { + self._destroy(err) + cb(null) + }) +} + +Duplexify.prototype._destroy = function(err) { + if (err) { + var ondrain = this._ondrain + this._ondrain = null + if (ondrain) ondrain(err) + else this.emit('error', err) + } + + if (this._forwardDestroy) { + if (this._readable && this._readable.destroy) this._readable.destroy() + if (this._writable && this._writable.destroy) this._writable.destroy() + } + + this.emit('close') +} + +Duplexify.prototype._write = function(data, enc, cb) { + if (this.destroyed) return + if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb)) + if (data === SIGNAL_FLUSH) return this._finish(cb) + if (!this._writable) return cb() + + if (this._writable.write(data) === false) this._ondrain = cb + else if (!this.destroyed) cb() +} + +Duplexify.prototype._finish = function(cb) { + var self = this + this.emit('preend') + onuncork(this, function() { + end(self._forwardEnd && self._writable, function() { + // haxx to not emit prefinish twice + if (self._writableState.prefinished === false) self._writableState.prefinished = true + self.emit('prefinish') + onuncork(self, cb) + }) + }) +} + +Duplexify.prototype.end = function(data, enc, cb) { + if (typeof data === 'function') return this.end(null, null, data) + if (typeof enc === 'function') return this.end(data, null, enc) + this._ended = true + if (data) this.write(data) + if (!this._writableState.ending && !this._writableState.destroyed) this.write(SIGNAL_FLUSH) + return stream.Writable.prototype.end.call(this, cb) +} + +module.exports = Duplexify diff --git a/node_modules/duplexify/package.json b/node_modules/duplexify/package.json new file mode 100644 index 0000000..dd28048 --- /dev/null +++ b/node_modules/duplexify/package.json @@ -0,0 +1,39 @@ +{ + "name": "duplexify", + "version": "4.1.3", + "description": "Turn a writable and readable stream into a streams2 duplex stream with support for async initialization and streams1/streams2 input", + "main": "index.js", + "dependencies": { + "end-of-stream": "^1.4.1", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1", + "stream-shift": "^1.0.2" + }, + "devDependencies": { + "concat-stream": "^1.5.2", + "tape": "^4.0.0", + "through2": "^2.0.0" + }, + "scripts": { + "test": "tape test.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/mafintosh/duplexify" + }, + "keywords": [ + "duplex", + "streams2", + "streams", + "stream", + "writable", + "readable", + "async" + ], + "author": "Mathias Buus", + "license": "MIT", + "bugs": { + "url": "https://github.com/mafintosh/duplexify/issues" + }, + "homepage": "https://github.com/mafintosh/duplexify" +} diff --git a/node_modules/duplexify/test.js b/node_modules/duplexify/test.js new file mode 100644 index 0000000..9341105 --- /dev/null +++ b/node_modules/duplexify/test.js @@ -0,0 +1,339 @@ +var tape = require('tape') +var through = require('through2') +var concat = require('concat-stream') +var stream = require('readable-stream') +var net = require('net') +var duplexify = require('./') + +var HELLO_WORLD = (Buffer.from && Buffer.from !== Uint8Array.from) + ? Buffer.from('hello world') + : new Buffer('hello world') + +tape('passthrough', function(t) { + t.plan(2) + + var pt = through() + var dup = duplexify(pt, pt) + + dup.end('hello world') + dup.on('finish', function() { + t.ok(true, 'should finish') + }) + dup.pipe(concat(function(data) { + t.same(data.toString(), 'hello world', 'same in as out') + })) +}) + +tape('passthrough + double end', function(t) { + t.plan(2) + + var pt = through() + var dup = duplexify(pt, pt) + + dup.end('hello world') + dup.end() + + dup.on('finish', function() { + t.ok(true, 'should finish') + }) + dup.pipe(concat(function(data) { + t.same(data.toString(), 'hello world', 'same in as out') + })) +}) + +tape('async passthrough + end', function(t) { + t.plan(2) + + var pt = through.obj({highWaterMark:1}, function(data, enc, cb) { + setTimeout(function() { + cb(null, data) + }, 100) + }) + + var dup = duplexify(pt, pt) + + dup.write('hello ') + dup.write('world') + dup.end() + + dup.on('finish', function() { + t.ok(true, 'should finish') + }) + dup.pipe(concat(function(data) { + t.same(data.toString(), 'hello world', 'same in as out') + })) +}) + +tape('duplex', function(t) { + var readExpected = ['read-a', 'read-b', 'read-c'] + var writeExpected = ['write-a', 'write-b', 'write-c'] + + t.plan(readExpected.length+writeExpected.length+2) + + var readable = through.obj() + var writable = through.obj(function(data, enc, cb) { + t.same(data, writeExpected.shift(), 'onwrite should match') + cb() + }) + + var dup = duplexify.obj(writable, readable) + + readExpected.slice().forEach(function(data) { + readable.write(data) + }) + readable.end() + + writeExpected.slice().forEach(function(data) { + dup.write(data) + }) + dup.end() + + dup.on('data', function(data) { + t.same(data, readExpected.shift(), 'ondata should match') + }) + dup.on('end', function() { + t.ok(true, 'should end') + }) + dup.on('finish', function() { + t.ok(true, 'should finish') + }) +}) + +tape('async', function(t) { + var dup = duplexify() + var pt = through() + + dup.pipe(concat(function(data) { + t.same(data.toString(), 'i was async', 'same in as out') + t.end() + })) + + dup.write('i') + dup.write(' was ') + dup.end('async') + + setTimeout(function() { + dup.setWritable(pt) + setTimeout(function() { + dup.setReadable(pt) + }, 50) + }, 50) +}) + +tape('destroy', function(t) { + t.plan(2) + + var write = through() + var read = through() + var dup = duplexify(write, read) + + write.destroy = function() { + t.ok(true, 'write destroyed') + } + + dup.on('close', function() { + t.ok(true, 'close emitted') + }) + + dup.destroy() + dup.destroy() // should only work once + dup.end() +}) + +tape('destroy both', function(t) { + t.plan(3) + + var write = through() + var read = through() + var dup = duplexify(write, read) + + write.destroy = function() { + t.ok(true, 'write destroyed') + } + + read.destroy = function() { + t.ok(true, 'read destroyed') + } + + dup.on('close', function() { + t.ok(true, 'close emitted') + }) + + dup.destroy() + dup.destroy() // should only work once +}) + +tape('bubble read errors', function(t) { + t.plan(2) + + var write = through() + var read = through() + var dup = duplexify(write, read) + + dup.on('error', function(err) { + t.same(err.message, 'read-error', 'received read error') + }) + dup.on('close', function() { + t.ok(true, 'close emitted') + }) + + read.emit('error', new Error('read-error')) + write.emit('error', new Error('write-error')) // only emit first error +}) + +tape('bubble write errors', function(t) { + t.plan(2) + + var write = through() + var read = through() + var dup = duplexify(write, read) + + dup.on('error', function(err) { + t.same(err.message, 'write-error', 'received write error') + }) + dup.on('close', function() { + t.ok(true, 'close emitted') + }) + + write.emit('error', new Error('write-error')) + read.emit('error', new Error('read-error')) // only emit first error +}) + +tape('bubble errors from write()', function(t) { + t.plan(3) + + var errored = false + var dup = duplexify(new stream.Writable({ + write: function(chunk, enc, next) { + next(new Error('write-error')) + } + })) + + dup.on('error', function(err) { + errored = true + t.same(err.message, 'write-error', 'received write error') + }) + dup.on('close', function() { + t.pass('close emitted') + t.ok(errored, 'error was emitted before close') + }) + dup.end('123') +}) + +tape('destroy while waiting for drain', function(t) { + t.plan(3) + + var errored = false + var dup = duplexify(new stream.Writable({ + highWaterMark: 0, + write: function() {} + })) + + dup.on('error', function(err) { + errored = true + t.same(err.message, 'destroy-error', 'received destroy error') + }) + dup.on('close', function() { + t.pass('close emitted') + t.ok(errored, 'error was emitted before close') + }) + dup.write('123') + dup.destroy(new Error('destroy-error')) +}) + +tape('reset writable / readable', function(t) { + t.plan(3) + + var toUpperCase = function(data, enc, cb) { + cb(null, data.toString().toUpperCase()) + } + + var passthrough = through() + var upper = through(toUpperCase) + var dup = duplexify(passthrough, passthrough) + + dup.once('data', function(data) { + t.same(data.toString(), 'hello') + dup.setWritable(upper) + dup.setReadable(upper) + dup.once('data', function(data) { + t.same(data.toString(), 'HELLO') + dup.once('data', function(data) { + t.same(data.toString(), 'HI') + t.end() + }) + }) + dup.write('hello') + dup.write('hi') + }) + dup.write('hello') +}) + +tape('cork', function(t) { + var passthrough = through() + var dup = duplexify(passthrough, passthrough) + var ok = false + + dup.on('prefinish', function() { + dup.cork() + setTimeout(function() { + ok = true + dup.uncork() + }, 100) + }) + dup.on('finish', function() { + t.ok(ok) + t.end() + }) + dup.end() +}) + +tape('prefinish not twice', function(t) { + var passthrough = through() + var dup = duplexify(passthrough, passthrough) + var prefinished = false + + dup.on('prefinish', function() { + t.ok(!prefinished, 'only prefinish once') + prefinished = true + }) + + dup.on('finish', function() { + t.end() + }) + + dup.end() +}) + +tape('close', function(t) { + var passthrough = through() + var dup = duplexify(passthrough, passthrough) + + passthrough.emit('close') + dup.on('close', function() { + t.ok(true, 'should forward close') + t.end() + }) +}) + +tape('works with node native streams (net)', function(t) { + t.plan(1) + + var server = net.createServer(function(socket) { + var dup = duplexify(socket, socket) + + dup.once('data', function(chunk) { + t.same(chunk, HELLO_WORLD) + server.close() + socket.end() + t.end() + }) + }) + + server.listen(0, function () { + var socket = net.connect(server.address().port) + var dup = duplexify(socket, socket) + + dup.write(HELLO_WORLD) + }) +}) diff --git a/node_modules/ecdsa-sig-formatter/CODEOWNERS b/node_modules/ecdsa-sig-formatter/CODEOWNERS new file mode 100644 index 0000000..4451d3d --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/CODEOWNERS @@ -0,0 +1 @@ +* @omsmith diff --git a/node_modules/ecdsa-sig-formatter/LICENSE b/node_modules/ecdsa-sig-formatter/LICENSE new file mode 100644 index 0000000..8754ed6 --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2015 D2L Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/ecdsa-sig-formatter/README.md b/node_modules/ecdsa-sig-formatter/README.md new file mode 100644 index 0000000..daa95d6 --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/README.md @@ -0,0 +1,65 @@ +# ecdsa-sig-formatter + +[![Build Status](https://travis-ci.org/Brightspace/node-ecdsa-sig-formatter.svg?branch=master)](https://travis-ci.org/Brightspace/node-ecdsa-sig-formatter) [![Coverage Status](https://coveralls.io/repos/Brightspace/node-ecdsa-sig-formatter/badge.svg)](https://coveralls.io/r/Brightspace/node-ecdsa-sig-formatter) + +Translate between JOSE and ASN.1/DER encodings for ECDSA signatures + +## Install +```sh +npm install ecdsa-sig-formatter --save +``` + +## Usage +```js +var format = require('ecdsa-sig-formatter'); + +var derSignature = '..'; // asn.1/DER encoded ecdsa signature + +var joseSignature = format.derToJose(derSignature); + +``` + +### API + +--- + +#### `.derToJose(Buffer|String signature, String alg)` -> `String` + +Convert the ASN.1/DER encoded signature to a JOSE-style concatenated signature. +Returns a _base64 url_ encoded `String`. + +* If _signature_ is a `String`, it should be _base64_ encoded +* _alg_ must be one of _ES256_, _ES384_ or _ES512_ + +--- + +#### `.joseToDer(Buffer|String signature, String alg)` -> `Buffer` + +Convert the JOSE-style concatenated signature to an ASN.1/DER encoded +signature. Returns a `Buffer` + +* If _signature_ is a `String`, it should be _base64 url_ encoded +* _alg_ must be one of _ES256_, _ES384_ or _ES512_ + +## Contributing + +1. **Fork** the repository. Committing directly against this repository is + highly discouraged. + +2. Make your modifications in a branch, updating and writing new unit tests + as necessary in the `spec` directory. + +3. Ensure that all tests pass with `npm test` + +4. `rebase` your changes against master. *Do not merge*. + +5. Submit a pull request to this repository. Wait for tests to run and someone + to chime in. + +### Code Style + +This repository is configured with [EditorConfig][EditorConfig] and +[ESLint][ESLint] rules. + +[EditorConfig]: http://editorconfig.org/ +[ESLint]: http://eslint.org diff --git a/node_modules/ecdsa-sig-formatter/package.json b/node_modules/ecdsa-sig-formatter/package.json new file mode 100644 index 0000000..6fb5ebf --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/package.json @@ -0,0 +1,46 @@ +{ + "name": "ecdsa-sig-formatter", + "version": "1.0.11", + "description": "Translate ECDSA signatures between ASN.1/DER and JOSE-style concatenation", + "main": "src/ecdsa-sig-formatter.js", + "scripts": { + "check-style": "eslint .", + "pretest": "npm run check-style", + "test": "istanbul cover --root src _mocha -- spec", + "report-cov": "cat ./coverage/lcov.info | coveralls" + }, + "typings": "./src/ecdsa-sig-formatter.d.ts", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/Brightspace/node-ecdsa-sig-formatter.git" + }, + "keywords": [ + "ecdsa", + "der", + "asn.1", + "jwt", + "jwa", + "jsonwebtoken", + "jose" + ], + "author": "D2L Corporation", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/Brightspace/node-ecdsa-sig-formatter/issues" + }, + "homepage": "https://github.com/Brightspace/node-ecdsa-sig-formatter#readme", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "devDependencies": { + "bench": "^0.3.6", + "chai": "^3.5.0", + "coveralls": "^2.11.9", + "eslint": "^2.12.0", + "eslint-config-brightspace": "^0.2.1", + "istanbul": "^0.4.3", + "jwk-to-pem": "^1.2.5", + "mocha": "^2.5.3", + "native-crypto": "^1.7.0" + } +} diff --git a/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.d.ts b/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.d.ts new file mode 100644 index 0000000..9693aa0 --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.d.ts @@ -0,0 +1,17 @@ +/// + +declare module "ecdsa-sig-formatter" { + /** + * Convert the ASN.1/DER encoded signature to a JOSE-style concatenated signature. Returns a base64 url encoded String. + * If signature is a String, it should be base64 encoded + * alg must be one of ES256, ES384 or ES512 + */ + export function derToJose(signature: Buffer | string, alg: string): string; + + /** + * Convert the JOSE-style concatenated signature to an ASN.1/DER encoded signature. Returns a Buffer + * If signature is a String, it should be base64 url encoded + * alg must be one of ES256, ES384 or ES512 + */ + export function joseToDer(signature: Buffer | string, alg: string): Buffer +} diff --git a/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js b/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js new file mode 100644 index 0000000..38eeb9b --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js @@ -0,0 +1,187 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer; + +var getParamBytesForAlg = require('./param-bytes-for-alg'); + +var MAX_OCTET = 0x80, + CLASS_UNIVERSAL = 0, + PRIMITIVE_BIT = 0x20, + TAG_SEQ = 0x10, + TAG_INT = 0x02, + ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), + ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); + +function base64Url(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} + +function signatureAsBuffer(signature) { + if (Buffer.isBuffer(signature)) { + return signature; + } else if ('string' === typeof signature) { + return Buffer.from(signature, 'base64'); + } + + throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); +} + +function derToJose(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); + + // the DER encoded param should at most be the param size, plus a padding + // zero, since due to being a signed integer + var maxEncodedParamLength = paramBytes + 1; + + var inputLength = signature.length; + + var offset = 0; + if (signature[offset++] !== ENCODED_TAG_SEQ) { + throw new Error('Could not find expected "seq"'); + } + + var seqLength = signature[offset++]; + if (seqLength === (MAX_OCTET | 1)) { + seqLength = signature[offset++]; + } + + if (inputLength - offset < seqLength) { + throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); + } + + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "r"'); + } + + var rLength = signature[offset++]; + + if (inputLength - offset - 2 < rLength) { + throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); + } + + if (maxEncodedParamLength < rLength) { + throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } + + var rOffset = offset; + offset += rLength; + + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "s"'); + } + + var sLength = signature[offset++]; + + if (inputLength - offset !== sLength) { + throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); + } + + if (maxEncodedParamLength < sLength) { + throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } + + var sOffset = offset; + offset += sLength; + + if (offset !== inputLength) { + throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); + } + + var rPadding = paramBytes - rLength, + sPadding = paramBytes - sLength; + + var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); + + for (offset = 0; offset < rPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); + + offset = paramBytes; + + for (var o = offset; offset < o + sPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); + + dst = dst.toString('base64'); + dst = base64Url(dst); + + return dst; +} + +function countPadding(buf, start, stop) { + var padding = 0; + while (start + padding < stop && buf[start + padding] === 0) { + ++padding; + } + + var needsSign = buf[start + padding] >= MAX_OCTET; + if (needsSign) { + --padding; + } + + return padding; +} + +function joseToDer(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); + + var signatureBytes = signature.length; + if (signatureBytes !== paramBytes * 2) { + throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); + } + + var rPadding = countPadding(signature, 0, paramBytes); + var sPadding = countPadding(signature, paramBytes, signature.length); + var rLength = paramBytes - rPadding; + var sLength = paramBytes - sPadding; + + var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; + + var shortLength = rsBytes < MAX_OCTET; + + var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); + + var offset = 0; + dst[offset++] = ENCODED_TAG_SEQ; + if (shortLength) { + // Bit 8 has value "0" + // bits 7-1 give the length. + dst[offset++] = rsBytes; + } else { + // Bit 8 of first octet has value "1" + // bits 7-1 give the number of additional length octets. + dst[offset++] = MAX_OCTET | 1; + // length, base 256 + dst[offset++] = rsBytes & 0xff; + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = rLength; + if (rPadding < 0) { + dst[offset++] = 0; + offset += signature.copy(dst, offset, 0, paramBytes); + } else { + offset += signature.copy(dst, offset, rPadding, paramBytes); + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = sLength; + if (sPadding < 0) { + dst[offset++] = 0; + signature.copy(dst, offset, paramBytes); + } else { + signature.copy(dst, offset, paramBytes + sPadding); + } + + return dst; +} + +module.exports = { + derToJose: derToJose, + joseToDer: joseToDer +}; diff --git a/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js b/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js new file mode 100644 index 0000000..9fe67ac --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js @@ -0,0 +1,23 @@ +'use strict'; + +function getParamSize(keySize) { + var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); + return result; +} + +var paramBytesForAlg = { + ES256: getParamSize(256), + ES384: getParamSize(384), + ES512: getParamSize(521) +}; + +function getParamBytesForAlg(alg) { + var paramBytes = paramBytesForAlg[alg]; + if (paramBytes) { + return paramBytes; + } + + throw new Error('Unknown algorithm "' + alg + '"'); +} + +module.exports = getParamBytesForAlg; diff --git a/node_modules/emoji-regex/LICENSE-MIT.txt b/node_modules/emoji-regex/LICENSE-MIT.txt new file mode 100644 index 0000000..a41e0a7 --- /dev/null +++ b/node_modules/emoji-regex/LICENSE-MIT.txt @@ -0,0 +1,20 @@ +Copyright Mathias Bynens + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/emoji-regex/README.md b/node_modules/emoji-regex/README.md new file mode 100644 index 0000000..f10e173 --- /dev/null +++ b/node_modules/emoji-regex/README.md @@ -0,0 +1,73 @@ +# emoji-regex [![Build status](https://travis-ci.org/mathiasbynens/emoji-regex.svg?branch=master)](https://travis-ci.org/mathiasbynens/emoji-regex) + +_emoji-regex_ offers a regular expression to match all emoji symbols (including textual representations of emoji) as per the Unicode Standard. + +This repository contains a script that generates this regular expression based on [the data from Unicode v12](https://github.com/mathiasbynens/unicode-12.0.0). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard. + +## Installation + +Via [npm](https://www.npmjs.com/): + +```bash +npm install emoji-regex +``` + +In [Node.js](https://nodejs.org/): + +```js +const emojiRegex = require('emoji-regex'); +// Note: because the regular expression has the global flag set, this module +// exports a function that returns the regex rather than exporting the regular +// expression itself, to make it impossible to (accidentally) mutate the +// original regular expression. + +const text = ` +\u{231A}: ⌚ default emoji presentation character (Emoji_Presentation) +\u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji +\u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base) +\u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier +`; + +const regex = emojiRegex(); +let match; +while (match = regex.exec(text)) { + const emoji = match[0]; + console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`); +} +``` + +Console output: + +``` +Matched sequence ⌚ — code points: 1 +Matched sequence ⌚ — code points: 1 +Matched sequence ↔️ — code points: 2 +Matched sequence ↔️ — code points: 2 +Matched sequence 👩 — code points: 1 +Matched sequence 👩 — code points: 1 +Matched sequence 👩🏿 — code points: 2 +Matched sequence 👩🏿 — code points: 2 +``` + +To match emoji in their textual representation as well (i.e. emoji that are not `Emoji_Presentation` symbols and that aren’t forced to render as emoji by a variation selector), `require` the other regex: + +```js +const emojiRegex = require('emoji-regex/text.js'); +``` + +Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes: + +```js +const emojiRegex = require('emoji-regex/es2015/index.js'); +const emojiRegexText = require('emoji-regex/es2015/text.js'); +``` + +## Author + +| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | +|---| +| [Mathias Bynens](https://mathiasbynens.be/) | + +## License + +_emoji-regex_ is available under the [MIT](https://mths.be/mit) license. diff --git a/node_modules/emoji-regex/es2015/index.js b/node_modules/emoji-regex/es2015/index.js new file mode 100644 index 0000000..b4cf3dc --- /dev/null +++ b/node_modules/emoji-regex/es2015/index.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = () => { + // https://mths.be/emoji + return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}|\u{1F468}(?:\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}\u{1F3FB}|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|[\u{1F3FB}-\u{1F3FF}])|(?:\u{1F9D1}\u{1F3FB}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F469})\u{1F3FB}|\u{1F9D1}(?:\u{1F3FF}\u200D\u{1F91D}\u200D\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u200D\u{1F91D}\u200D\u{1F9D1})|(?:\u{1F9D1}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}\u{1F3FC}]|\u{1F469}(?:\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FB}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|(?:\u{1F9D1}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}-\u{1F3FD}]|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}](?:[\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\u{1F3F4}\u200D\u2620)\uFE0F|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F415}\u200D\u{1F9BA}|\u{1F469}\u200D\u{1F466}|\u{1F469}\u200D\u{1F467}|\u{1F1FD}\u{1F1F0}|\u{1F1F4}\u{1F1F2}|\u{1F1F6}\u{1F1E6}|[#\*0-9]\uFE0F\u20E3|\u{1F1E7}[\u{1F1E6}\u{1F1E7}\u{1F1E9}-\u{1F1EF}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FE}\u{1F1FF}]|\u{1F1F9}[\u{1F1E6}\u{1F1E8}\u{1F1E9}\u{1F1EB}-\u{1F1ED}\u{1F1EF}-\u{1F1F4}\u{1F1F7}\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FF}]|\u{1F1EA}[\u{1F1E6}\u{1F1E8}\u{1F1EA}\u{1F1EC}\u{1F1ED}\u{1F1F7}-\u{1F1FA}]|\u{1F9D1}[\u{1F3FB}-\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F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F936}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]\uFE0F|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu; +}; diff --git a/node_modules/emoji-regex/es2015/text.js b/node_modules/emoji-regex/es2015/text.js new file mode 100644 index 0000000..780309d --- /dev/null +++ b/node_modules/emoji-regex/es2015/text.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = () => { + // https://mths.be/emoji + return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}|\u{1F468}(?:\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}\u{1F3FB}|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|[\u{1F3FB}-\u{1F3FF}])|(?:\u{1F9D1}\u{1F3FB}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F469})\u{1F3FB}|\u{1F9D1}(?:\u{1F3FF}\u200D\u{1F91D}\u200D\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u200D\u{1F91D}\u200D\u{1F9D1})|(?:\u{1F9D1}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}\u{1F3FC}]|\u{1F469}(?:\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FB}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|(?:\u{1F9D1}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}-\u{1F3FD}]|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B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1F1EB}\u{1F1F8}]|\u{1F1FA}[\u{1F1E6}\u{1F1EC}\u{1F1F2}\u{1F1F3}\u{1F1F8}\u{1F1FE}\u{1F1FF}]|\u{1F1EE}[\u{1F1E8}-\u{1F1EA}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}]|\u{1F1EF}[\u{1F1EA}\u{1F1F2}\u{1F1F4}\u{1F1F5}]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270A-\u270D\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F470}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F4AA}\u{1F574}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F936}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]\uFE0F?|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu; +}; diff --git a/node_modules/emoji-regex/index.d.ts b/node_modules/emoji-regex/index.d.ts new file mode 100644 index 0000000..1955b47 --- /dev/null +++ b/node_modules/emoji-regex/index.d.ts @@ -0,0 +1,23 @@ +declare module 'emoji-regex' { + function emojiRegex(): RegExp; + + export default emojiRegex; +} + +declare module 'emoji-regex/text' { + function emojiRegex(): RegExp; + + export default emojiRegex; +} + +declare module 'emoji-regex/es2015' { + function emojiRegex(): RegExp; + + export default emojiRegex; +} + +declare module 'emoji-regex/es2015/text' { + function emojiRegex(): RegExp; + + export default emojiRegex; +} diff --git a/node_modules/emoji-regex/index.js b/node_modules/emoji-regex/index.js new file mode 100644 index 0000000..d993a3a --- /dev/null +++ b/node_modules/emoji-regex/index.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\u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\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; +}; diff --git a/node_modules/emoji-regex/package.json b/node_modules/emoji-regex/package.json new file mode 100644 index 0000000..6d32352 --- /dev/null +++ b/node_modules/emoji-regex/package.json @@ -0,0 +1,50 @@ +{ + "name": "emoji-regex", + "version": "8.0.0", + "description": "A regular expression to match all Emoji-only symbols as per the Unicode Standard.", + "homepage": "https://mths.be/emoji-regex", + "main": "index.js", + "types": "index.d.ts", + "keywords": [ + "unicode", + "regex", + "regexp", + "regular expressions", + "code points", + "symbols", + "characters", + "emoji" + ], + "license": "MIT", + "author": { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + }, + "repository": { + "type": "git", + "url": "https://github.com/mathiasbynens/emoji-regex.git" + }, + "bugs": "https://github.com/mathiasbynens/emoji-regex/issues", + "files": [ + "LICENSE-MIT.txt", + "index.js", + "index.d.ts", + "text.js", + "es2015/index.js", + "es2015/text.js" + ], + "scripts": { + "build": "rm -rf -- es2015; babel src -d .; NODE_ENV=es2015 babel src -d ./es2015; node script/inject-sequences.js", + "test": "mocha", + "test:watch": "npm run test -- --watch" + }, + "devDependencies": { + "@babel/cli": "^7.2.3", + "@babel/core": "^7.3.4", + "@babel/plugin-proposal-unicode-property-regex": "^7.2.0", + "@babel/preset-env": "^7.3.4", + "mocha": "^6.0.2", + "regexgen": "^1.3.0", + "unicode-12.0.0": "^0.7.9" + } +} diff --git a/node_modules/emoji-regex/text.js b/node_modules/emoji-regex/text.js new file mode 100644 index 0000000..0a55ce2 --- /dev/null +++ b/node_modules/emoji-regex/text.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uD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\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F?|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; +}; diff --git a/node_modules/end-of-stream/LICENSE b/node_modules/end-of-stream/LICENSE new file mode 100644 index 0000000..757562e --- /dev/null +++ b/node_modules/end-of-stream/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Mathias Buus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/end-of-stream/README.md b/node_modules/end-of-stream/README.md new file mode 100644 index 0000000..857b14b --- /dev/null +++ b/node_modules/end-of-stream/README.md @@ -0,0 +1,54 @@ +# end-of-stream + +A node module that calls a callback when a readable/writable/duplex stream has completed or failed. + + npm install end-of-stream + +[![Build status](https://travis-ci.org/mafintosh/end-of-stream.svg?branch=master)](https://travis-ci.org/mafintosh/end-of-stream) + +## Usage + +Simply pass a stream and a callback to the `eos`. +Both legacy streams, streams2 and stream3 are supported. + +``` js +var eos = require('end-of-stream'); + +eos(readableStream, function(err) { + // this will be set to the stream instance + if (err) return console.log('stream had an error or closed early'); + console.log('stream has ended', this === readableStream); +}); + +eos(writableStream, function(err) { + if (err) return console.log('stream had an error or closed early'); + console.log('stream has finished', this === writableStream); +}); + +eos(duplexStream, function(err) { + if (err) return console.log('stream had an error or closed early'); + console.log('stream has ended and finished', this === duplexStream); +}); + +eos(duplexStream, {readable:false}, function(err) { + if (err) return console.log('stream had an error or closed early'); + console.log('stream has finished but might still be readable'); +}); + +eos(duplexStream, {writable:false}, function(err) { + if (err) return console.log('stream had an error or closed early'); + console.log('stream has ended but might still be writable'); +}); + +eos(readableStream, {error:false}, function(err) { + // do not treat emit('error', err) as a end-of-stream +}); +``` + +## License + +MIT + +## Related + +`end-of-stream` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one. diff --git a/node_modules/end-of-stream/index.js b/node_modules/end-of-stream/index.js new file mode 100644 index 0000000..7ce47e9 --- /dev/null +++ b/node_modules/end-of-stream/index.js @@ -0,0 +1,96 @@ +var once = require('once'); + +var noop = function() {}; + +var qnt = global.Bare ? queueMicrotask : process.nextTick.bind(process); + +var isRequest = function(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +}; + +var isChildProcess = function(stream) { + return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 +}; + +var eos = function(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + + callback = once(callback || noop); + + var ws = stream._writableState; + var rs = stream._readableState; + var readable = opts.readable || (opts.readable !== false && stream.readable); + var writable = opts.writable || (opts.writable !== false && stream.writable); + var cancelled = false; + + var onlegacyfinish = function() { + if (!stream.writable) onfinish(); + }; + + var onfinish = function() { + writable = false; + if (!readable) callback.call(stream); + }; + + var onend = function() { + readable = false; + if (!writable) callback.call(stream); + }; + + var onexit = function(exitCode) { + callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); + }; + + var onerror = function(err) { + callback.call(stream, err); + }; + + var onclose = function() { + qnt(onclosenexttick); + }; + + var onclosenexttick = function() { + if (cancelled) return; + if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); + if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); + }; + + var onrequest = function() { + stream.req.on('finish', onfinish); + }; + + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest(); + else stream.on('request', onrequest); + } else if (writable && !ws) { // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + if (isChildProcess(stream)) stream.on('exit', onexit); + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + + return function() { + cancelled = true; + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('exit', onexit); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +}; + +module.exports = eos; diff --git a/node_modules/end-of-stream/package.json b/node_modules/end-of-stream/package.json new file mode 100644 index 0000000..0b530cd --- /dev/null +++ b/node_modules/end-of-stream/package.json @@ -0,0 +1,37 @@ +{ + "name": "end-of-stream", + "version": "1.4.5", + "description": "Call a callback when a readable/writable/duplex stream has completed or failed.", + "repository": { + "type": "git", + "url": "git://github.com/mafintosh/end-of-stream.git" + }, + "dependencies": { + "once": "^1.4.0" + }, + "scripts": { + "test": "node test.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "stream", + "streams", + "callback", + "finish", + "close", + "end", + "wait" + ], + "bugs": { + "url": "https://github.com/mafintosh/end-of-stream/issues" + }, + "homepage": "https://github.com/mafintosh/end-of-stream", + "main": "index.js", + "author": "Mathias Buus ", + "license": "MIT", + "devDependencies": { + "tape": "^4.11.0" + } +} diff --git a/node_modules/es-define-property/.eslintrc b/node_modules/es-define-property/.eslintrc new file mode 100644 index 0000000..46f3b12 --- /dev/null +++ b/node_modules/es-define-property/.eslintrc @@ -0,0 +1,13 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "new-cap": ["error", { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/node_modules/es-define-property/.github/FUNDING.yml b/node_modules/es-define-property/.github/FUNDING.yml new file mode 100644 index 0000000..4445451 --- /dev/null +++ b/node_modules/es-define-property/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/es-define-property +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/es-define-property/.nycrc b/node_modules/es-define-property/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/es-define-property/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/es-define-property/CHANGELOG.md b/node_modules/es-define-property/CHANGELOG.md new file mode 100644 index 0000000..5f60cc0 --- /dev/null +++ b/node_modules/es-define-property/CHANGELOG.md @@ -0,0 +1,29 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.1](https://github.com/ljharb/es-define-property/compare/v1.0.0...v1.0.1) - 2024-12-06 + +### Commits + +- [types] use shared tsconfig [`954a663`](https://github.com/ljharb/es-define-property/commit/954a66360326e508a0e5daa4b07493d58f5e110e) +- [actions] split out node 10-20, and 20+ [`3a8e84b`](https://github.com/ljharb/es-define-property/commit/3a8e84b23883f26ff37b3e82ff283834228e18c6) +- [Dev Deps] update `@ljharb/eslint-config`, `@ljharb/tsconfig`, `@types/get-intrinsic`, `@types/tape`, `auto-changelog`, `gopd`, `tape` [`86ae27b`](https://github.com/ljharb/es-define-property/commit/86ae27bb8cc857b23885136fad9cbe965ae36612) +- [Refactor] avoid using `get-intrinsic` [`02480c0`](https://github.com/ljharb/es-define-property/commit/02480c0353ef6118965282977c3864aff53d98b1) +- [Tests] replace `aud` with `npm audit` [`f6093ff`](https://github.com/ljharb/es-define-property/commit/f6093ff74ab51c98015c2592cd393bd42478e773) +- [Tests] configure testling [`7139e66`](https://github.com/ljharb/es-define-property/commit/7139e66959247a56086d9977359caef27c6849e7) +- [Dev Deps] update `tape` [`b901b51`](https://github.com/ljharb/es-define-property/commit/b901b511a75e001a40ce1a59fef7d9ffcfc87482) +- [Tests] fix types in tests [`469d269`](https://github.com/ljharb/es-define-property/commit/469d269fd141b1e773ec053a9fa35843493583e0) +- [Dev Deps] add missing peer dep [`733acfb`](https://github.com/ljharb/es-define-property/commit/733acfb0c4c96edf337e470b89a25a5b3724c352) + +## v1.0.0 - 2024-02-12 + +### Commits + +- Initial implementation, tests, readme, types [`3e154e1`](https://github.com/ljharb/es-define-property/commit/3e154e11a2fee09127220f5e503bf2c0a31dd480) +- Initial commit [`07d98de`](https://github.com/ljharb/es-define-property/commit/07d98de34a4dc31ff5e83a37c0c3f49e0d85cd50) +- npm init [`c4eb634`](https://github.com/ljharb/es-define-property/commit/c4eb6348b0d3886aac36cef34ad2ee0665ea6f3e) +- Only apps should have lockfiles [`7af86ec`](https://github.com/ljharb/es-define-property/commit/7af86ec1d311ec0b17fdfe616a25f64276903856) diff --git a/node_modules/es-define-property/LICENSE b/node_modules/es-define-property/LICENSE new file mode 100644 index 0000000..f82f389 --- /dev/null +++ b/node_modules/es-define-property/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/es-define-property/README.md b/node_modules/es-define-property/README.md new file mode 100644 index 0000000..9b291bd --- /dev/null +++ b/node_modules/es-define-property/README.md @@ -0,0 +1,49 @@ +# es-define-property [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +`Object.defineProperty`, but not IE 8's broken one. + +## Example + +```js +const assert = require('assert'); + +const $defineProperty = require('es-define-property'); + +if ($defineProperty) { + assert.equal($defineProperty, Object.defineProperty); +} else if (Object.defineProperty) { + assert.equal($defineProperty, false, 'this is IE 8'); +} else { + assert.equal($defineProperty, false, 'this is an ES3 engine'); +} +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/es-define-property +[npm-version-svg]: https://versionbadg.es/ljharb/es-define-property.svg +[deps-svg]: https://david-dm.org/ljharb/es-define-property.svg +[deps-url]: https://david-dm.org/ljharb/es-define-property +[dev-deps-svg]: https://david-dm.org/ljharb/es-define-property/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/es-define-property#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/es-define-property.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/es-define-property.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/es-define-property.svg +[downloads-url]: https://npm-stat.com/charts.html?package=es-define-property +[codecov-image]: https://codecov.io/gh/ljharb/es-define-property/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/es-define-property/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/es-define-property +[actions-url]: https://github.com/ljharb/es-define-property/actions diff --git a/node_modules/es-define-property/index.d.ts b/node_modules/es-define-property/index.d.ts new file mode 100644 index 0000000..6012247 --- /dev/null +++ b/node_modules/es-define-property/index.d.ts @@ -0,0 +1,3 @@ +declare const defineProperty: false | typeof Object.defineProperty; + +export = defineProperty; \ No newline at end of file diff --git a/node_modules/es-define-property/index.js b/node_modules/es-define-property/index.js new file mode 100644 index 0000000..e0a2925 --- /dev/null +++ b/node_modules/es-define-property/index.js @@ -0,0 +1,14 @@ +'use strict'; + +/** @type {import('.')} */ +var $defineProperty = Object.defineProperty || false; +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = false; + } +} + +module.exports = $defineProperty; diff --git a/node_modules/es-define-property/package.json b/node_modules/es-define-property/package.json new file mode 100644 index 0000000..fbed187 --- /dev/null +++ b/node_modules/es-define-property/package.json @@ -0,0 +1,81 @@ +{ + "name": "es-define-property", + "version": "1.0.1", + "description": "`Object.defineProperty`, but not IE 8's broken one.", + "main": "index.js", + "types": "./index.d.ts", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>= 10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/es-define-property.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "object", + "define", + "property", + "defineProperty", + "Object.defineProperty" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/es-define-property/issues" + }, + "homepage": "https://github.com/ljharb/es-define-property#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/gopd": "^1.0.3", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "eslint": "^8.8.0", + "evalmd": "^0.0.19", + "gopd": "^1.2.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/es-define-property/test/index.js b/node_modules/es-define-property/test/index.js new file mode 100644 index 0000000..b4b4688 --- /dev/null +++ b/node_modules/es-define-property/test/index.js @@ -0,0 +1,56 @@ +'use strict'; + +var $defineProperty = require('../'); + +var test = require('tape'); +var gOPD = require('gopd'); + +test('defineProperty: supported', { skip: !$defineProperty }, function (t) { + t.plan(4); + + t.equal(typeof $defineProperty, 'function', 'defineProperty is supported'); + if ($defineProperty && gOPD) { // this `if` check is just to shut TS up + /** @type {{ a: number, b?: number, c?: number }} */ + var o = { a: 1 }; + + $defineProperty(o, 'b', { enumerable: true, value: 2 }); + t.deepEqual( + gOPD(o, 'b'), + { + configurable: false, + enumerable: true, + value: 2, + writable: false + }, + 'property descriptor is as expected' + ); + + $defineProperty(o, 'c', { enumerable: false, value: 3, writable: true }); + t.deepEqual( + gOPD(o, 'c'), + { + configurable: false, + enumerable: false, + value: 3, + writable: true + }, + 'property descriptor is as expected' + ); + } + + t.equal($defineProperty, Object.defineProperty, 'defineProperty is Object.defineProperty'); + + t.end(); +}); + +test('defineProperty: not supported', { skip: !!$defineProperty }, function (t) { + t.notOk($defineProperty, 'defineProperty is not supported'); + + t.match( + typeof $defineProperty, + /^(?:undefined|boolean)$/, + '`typeof defineProperty` is `undefined` or `boolean`' + ); + + t.end(); +}); diff --git a/node_modules/es-define-property/tsconfig.json b/node_modules/es-define-property/tsconfig.json new file mode 100644 index 0000000..5a49992 --- /dev/null +++ b/node_modules/es-define-property/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2022", + }, + "exclude": [ + "coverage", + "test/list-exports" + ], +} diff --git a/node_modules/es-errors/.eslintrc b/node_modules/es-errors/.eslintrc new file mode 100644 index 0000000..3b5d9e9 --- /dev/null +++ b/node_modules/es-errors/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/node_modules/es-errors/.github/FUNDING.yml b/node_modules/es-errors/.github/FUNDING.yml new file mode 100644 index 0000000..f1b8805 --- /dev/null +++ b/node_modules/es-errors/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/es-errors +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/es-errors/CHANGELOG.md b/node_modules/es-errors/CHANGELOG.md new file mode 100644 index 0000000..204a9e9 --- /dev/null +++ b/node_modules/es-errors/CHANGELOG.md @@ -0,0 +1,40 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.3.0](https://github.com/ljharb/es-errors/compare/v1.2.1...v1.3.0) - 2024-02-05 + +### Commits + +- [New] add `EvalError` and `URIError` [`1927627`](https://github.com/ljharb/es-errors/commit/1927627ba68cb6c829d307231376c967db53acdf) + +## [v1.2.1](https://github.com/ljharb/es-errors/compare/v1.2.0...v1.2.1) - 2024-02-04 + +### Commits + +- [Fix] add missing `exports` entry [`5bb5f28`](https://github.com/ljharb/es-errors/commit/5bb5f280f98922701109d6ebb82eea2257cecc7e) + +## [v1.2.0](https://github.com/ljharb/es-errors/compare/v1.1.0...v1.2.0) - 2024-02-04 + +### Commits + +- [New] add `ReferenceError` [`6d8cf5b`](https://github.com/ljharb/es-errors/commit/6d8cf5bbb6f3f598d02cf6f30e468ba2caa8e143) + +## [v1.1.0](https://github.com/ljharb/es-errors/compare/v1.0.0...v1.1.0) - 2024-02-04 + +### Commits + +- [New] add base Error [`2983ab6`](https://github.com/ljharb/es-errors/commit/2983ab65f7bc5441276cb021dc3aa03c78881698) + +## v1.0.0 - 2024-02-03 + +### Commits + +- Initial implementation, tests, readme, type [`8f47631`](https://github.com/ljharb/es-errors/commit/8f476317e9ad76f40ad648081829b1a1a3a1288b) +- Initial commit [`ea5d099`](https://github.com/ljharb/es-errors/commit/ea5d099ef18e550509ab9e2be000526afd81c385) +- npm init [`6f5ebf9`](https://github.com/ljharb/es-errors/commit/6f5ebf9cead474dadd72b9e63dad315820a089ae) +- Only apps should have lockfiles [`e1a0aeb`](https://github.com/ljharb/es-errors/commit/e1a0aeb7b80f5cfc56be54d6b2100e915d47def8) +- [meta] add `sideEffects` flag [`a9c7d46`](https://github.com/ljharb/es-errors/commit/a9c7d460a492f1d8a241c836bc25a322a19cc043) diff --git a/node_modules/es-errors/LICENSE b/node_modules/es-errors/LICENSE new file mode 100644 index 0000000..f82f389 --- /dev/null +++ b/node_modules/es-errors/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/es-errors/README.md b/node_modules/es-errors/README.md new file mode 100644 index 0000000..8dbfacf --- /dev/null +++ b/node_modules/es-errors/README.md @@ -0,0 +1,55 @@ +# es-errors [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +A simple cache for a few of the JS Error constructors. + +## Example + +```js +const assert = require('assert'); + +const Base = require('es-errors'); +const Eval = require('es-errors/eval'); +const Range = require('es-errors/range'); +const Ref = require('es-errors/ref'); +const Syntax = require('es-errors/syntax'); +const Type = require('es-errors/type'); +const URI = require('es-errors/uri'); + +assert.equal(Base, Error); +assert.equal(Eval, EvalError); +assert.equal(Range, RangeError); +assert.equal(Ref, ReferenceError); +assert.equal(Syntax, SyntaxError); +assert.equal(Type, TypeError); +assert.equal(URI, URIError); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/es-errors +[npm-version-svg]: https://versionbadg.es/ljharb/es-errors.svg +[deps-svg]: https://david-dm.org/ljharb/es-errors.svg +[deps-url]: https://david-dm.org/ljharb/es-errors +[dev-deps-svg]: https://david-dm.org/ljharb/es-errors/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/es-errors#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/es-errors.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/es-errors.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/es-errors.svg +[downloads-url]: https://npm-stat.com/charts.html?package=es-errors +[codecov-image]: https://codecov.io/gh/ljharb/es-errors/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/es-errors/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/es-errors +[actions-url]: https://github.com/ljharb/es-errors/actions diff --git a/node_modules/es-errors/eval.d.ts b/node_modules/es-errors/eval.d.ts new file mode 100644 index 0000000..e4210e0 --- /dev/null +++ b/node_modules/es-errors/eval.d.ts @@ -0,0 +1,3 @@ +declare const EvalError: EvalErrorConstructor; + +export = EvalError; diff --git a/node_modules/es-errors/eval.js b/node_modules/es-errors/eval.js new file mode 100644 index 0000000..725ccb6 --- /dev/null +++ b/node_modules/es-errors/eval.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./eval')} */ +module.exports = EvalError; diff --git a/node_modules/es-errors/index.d.ts b/node_modules/es-errors/index.d.ts new file mode 100644 index 0000000..69bdbc9 --- /dev/null +++ b/node_modules/es-errors/index.d.ts @@ -0,0 +1,3 @@ +declare const Error: ErrorConstructor; + +export = Error; diff --git a/node_modules/es-errors/index.js b/node_modules/es-errors/index.js new file mode 100644 index 0000000..cc0c521 --- /dev/null +++ b/node_modules/es-errors/index.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('.')} */ +module.exports = Error; diff --git a/node_modules/es-errors/package.json b/node_modules/es-errors/package.json new file mode 100644 index 0000000..ff8c2a5 --- /dev/null +++ b/node_modules/es-errors/package.json @@ -0,0 +1,80 @@ +{ + "name": "es-errors", + "version": "1.3.0", + "description": "A simple cache for a few of the JS Error constructors.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./eval": "./eval.js", + "./range": "./range.js", + "./ref": "./ref.js", + "./syntax": "./syntax.js", + "./type": "./type.js", + "./uri": "./uri.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'", + "posttest": "aud --production", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git' | grep -v dist/)", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/es-errors.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "error", + "typeerror", + "syntaxerror", + "rangeerror" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/es-errors/issues" + }, + "homepage": "https://github.com/ljharb/es-errors#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eclint": "^2.8.1", + "eslint": "^8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.4", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/es-errors/range.d.ts b/node_modules/es-errors/range.d.ts new file mode 100644 index 0000000..3a12e86 --- /dev/null +++ b/node_modules/es-errors/range.d.ts @@ -0,0 +1,3 @@ +declare const RangeError: RangeErrorConstructor; + +export = RangeError; diff --git a/node_modules/es-errors/range.js b/node_modules/es-errors/range.js new file mode 100644 index 0000000..2044fe0 --- /dev/null +++ b/node_modules/es-errors/range.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./range')} */ +module.exports = RangeError; diff --git a/node_modules/es-errors/ref.d.ts b/node_modules/es-errors/ref.d.ts new file mode 100644 index 0000000..a13107e --- /dev/null +++ b/node_modules/es-errors/ref.d.ts @@ -0,0 +1,3 @@ +declare const ReferenceError: ReferenceErrorConstructor; + +export = ReferenceError; diff --git a/node_modules/es-errors/ref.js b/node_modules/es-errors/ref.js new file mode 100644 index 0000000..d7c430f --- /dev/null +++ b/node_modules/es-errors/ref.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./ref')} */ +module.exports = ReferenceError; diff --git a/node_modules/es-errors/syntax.d.ts b/node_modules/es-errors/syntax.d.ts new file mode 100644 index 0000000..6a0c53c --- /dev/null +++ b/node_modules/es-errors/syntax.d.ts @@ -0,0 +1,3 @@ +declare const SyntaxError: SyntaxErrorConstructor; + +export = SyntaxError; diff --git a/node_modules/es-errors/syntax.js b/node_modules/es-errors/syntax.js new file mode 100644 index 0000000..5f5fdde --- /dev/null +++ b/node_modules/es-errors/syntax.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./syntax')} */ +module.exports = SyntaxError; diff --git a/node_modules/es-errors/test/index.js b/node_modules/es-errors/test/index.js new file mode 100644 index 0000000..1ff0277 --- /dev/null +++ b/node_modules/es-errors/test/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var test = require('tape'); + +var E = require('../'); +var R = require('../range'); +var Ref = require('../ref'); +var S = require('../syntax'); +var T = require('../type'); + +test('errors', function (t) { + t.equal(E, Error); + t.equal(R, RangeError); + t.equal(Ref, ReferenceError); + t.equal(S, SyntaxError); + t.equal(T, TypeError); + + t.end(); +}); diff --git a/node_modules/es-errors/tsconfig.json b/node_modules/es-errors/tsconfig.json new file mode 100644 index 0000000..99dfeb6 --- /dev/null +++ b/node_modules/es-errors/tsconfig.json @@ -0,0 +1,49 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Projects */ + + /* Language and Environment */ + "target": "es5", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": ["types"], /* Specify multiple folders that act like `./node_modules/@types`. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, /* Allow `import x from y` when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + + /* Completeness */ + // "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/es-errors/type.d.ts b/node_modules/es-errors/type.d.ts new file mode 100644 index 0000000..576fb51 --- /dev/null +++ b/node_modules/es-errors/type.d.ts @@ -0,0 +1,3 @@ +declare const TypeError: TypeErrorConstructor + +export = TypeError; diff --git a/node_modules/es-errors/type.js b/node_modules/es-errors/type.js new file mode 100644 index 0000000..9769e44 --- /dev/null +++ b/node_modules/es-errors/type.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./type')} */ +module.exports = TypeError; diff --git a/node_modules/es-errors/uri.d.ts b/node_modules/es-errors/uri.d.ts new file mode 100644 index 0000000..c3261c9 --- /dev/null +++ b/node_modules/es-errors/uri.d.ts @@ -0,0 +1,3 @@ +declare const URIError: URIErrorConstructor; + +export = URIError; diff --git a/node_modules/es-errors/uri.js b/node_modules/es-errors/uri.js new file mode 100644 index 0000000..e9cd1c7 --- /dev/null +++ b/node_modules/es-errors/uri.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./uri')} */ +module.exports = URIError; diff --git a/node_modules/es-object-atoms/.eslintrc b/node_modules/es-object-atoms/.eslintrc new file mode 100644 index 0000000..d90a1bc --- /dev/null +++ b/node_modules/es-object-atoms/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "eqeqeq": ["error", "allow-null"], + "id-length": "off", + "new-cap": ["error", { + "capIsNewExceptions": [ + "RequireObjectCoercible", + "ToObject", + ], + }], + }, +} diff --git a/node_modules/es-object-atoms/.github/FUNDING.yml b/node_modules/es-object-atoms/.github/FUNDING.yml new file mode 100644 index 0000000..352bfda --- /dev/null +++ b/node_modules/es-object-atoms/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/es-object +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/es-object-atoms/CHANGELOG.md b/node_modules/es-object-atoms/CHANGELOG.md new file mode 100644 index 0000000..fdd2abe --- /dev/null +++ b/node_modules/es-object-atoms/CHANGELOG.md @@ -0,0 +1,37 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.1](https://github.com/ljharb/es-object-atoms/compare/v1.1.0...v1.1.1) - 2025-01-14 + +### Commits + +- [types] `ToObject`: improve types [`cfe8c8a`](https://github.com/ljharb/es-object-atoms/commit/cfe8c8a105c44820cb22e26f62d12ef0ad9715c8) + +## [v1.1.0](https://github.com/ljharb/es-object-atoms/compare/v1.0.1...v1.1.0) - 2025-01-14 + +### Commits + +- [New] add `isObject` [`51e4042`](https://github.com/ljharb/es-object-atoms/commit/51e4042df722eb3165f40dc5f4bf33d0197ecb07) + +## [v1.0.1](https://github.com/ljharb/es-object-atoms/compare/v1.0.0...v1.0.1) - 2025-01-13 + +### Commits + +- [Dev Deps] update `@ljharb/eslint-config`, `@ljharb/tsconfig`, `@types/tape`, `auto-changelog`, `tape` [`38ab9eb`](https://github.com/ljharb/es-object-atoms/commit/38ab9eb00b62c2f4668644f5e513d9b414ebd595) +- [types] improve types [`7d1beb8`](https://github.com/ljharb/es-object-atoms/commit/7d1beb887958b78b6a728a210a1c8370ab7e2aa1) +- [Tests] replace `aud` with `npm audit` [`25863ba`](https://github.com/ljharb/es-object-atoms/commit/25863baf99178f1d1ad33d1120498db28631907e) +- [Dev Deps] add missing peer dep [`c012309`](https://github.com/ljharb/es-object-atoms/commit/c0123091287e6132d6f4240496340c427433df28) + +## v1.0.0 - 2024-03-16 + +### Commits + +- Initial implementation, tests, readme, types [`f1499db`](https://github.com/ljharb/es-object-atoms/commit/f1499db7d3e1741e64979c61d645ab3137705e82) +- Initial commit [`99eedc7`](https://github.com/ljharb/es-object-atoms/commit/99eedc7b5fde38a50a28d3c8b724706e3e4c5f6a) +- [meta] rename repo [`fc851fa`](https://github.com/ljharb/es-object-atoms/commit/fc851fa70616d2d182aaf0bd02c2ed7084dea8fa) +- npm init [`b909377`](https://github.com/ljharb/es-object-atoms/commit/b909377c50049bd0ec575562d20b0f9ebae8947f) +- Only apps should have lockfiles [`7249edd`](https://github.com/ljharb/es-object-atoms/commit/7249edd2178c1b9ddfc66ffcc6d07fdf0d28efc1) diff --git a/node_modules/es-object-atoms/LICENSE b/node_modules/es-object-atoms/LICENSE new file mode 100644 index 0000000..f82f389 --- /dev/null +++ b/node_modules/es-object-atoms/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/es-object-atoms/README.md b/node_modules/es-object-atoms/README.md new file mode 100644 index 0000000..447695b --- /dev/null +++ b/node_modules/es-object-atoms/README.md @@ -0,0 +1,63 @@ +# es-object-atoms [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +ES Object-related atoms: Object, ToObject, RequireObjectCoercible. + +## Example + +```js +const assert = require('assert'); + +const $Object = require('es-object-atoms'); +const isObject = require('es-object-atoms/isObject'); +const ToObject = require('es-object-atoms/ToObject'); +const RequireObjectCoercible = require('es-object-atoms/RequireObjectCoercible'); + +assert.equal($Object, Object); +assert.throws(() => ToObject(null), TypeError); +assert.throws(() => ToObject(undefined), TypeError); +assert.throws(() => RequireObjectCoercible(null), TypeError); +assert.throws(() => RequireObjectCoercible(undefined), TypeError); + +assert.equal(isObject(undefined), false); +assert.equal(isObject(null), false); +assert.equal(isObject({}), true); +assert.equal(isObject([]), true); +assert.equal(isObject(function () {}), true); + +assert.deepEqual(RequireObjectCoercible(true), true); +assert.deepEqual(ToObject(true), Object(true)); + +const obj = {}; +assert.equal(RequireObjectCoercible(obj), obj); +assert.equal(ToObject(obj), obj); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/es-object-atoms +[npm-version-svg]: https://versionbadg.es/ljharb/es-object-atoms.svg +[deps-svg]: https://david-dm.org/ljharb/es-object-atoms.svg +[deps-url]: https://david-dm.org/ljharb/es-object-atoms +[dev-deps-svg]: https://david-dm.org/ljharb/es-object-atoms/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/es-object-atoms#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/es-object-atoms.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/es-object-atoms.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/es-object.svg +[downloads-url]: https://npm-stat.com/charts.html?package=es-object-atoms +[codecov-image]: https://codecov.io/gh/ljharb/es-object-atoms/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/es-object-atoms/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/es-object-atoms +[actions-url]: https://github.com/ljharb/es-object-atoms/actions diff --git a/node_modules/es-object-atoms/RequireObjectCoercible.d.ts b/node_modules/es-object-atoms/RequireObjectCoercible.d.ts new file mode 100644 index 0000000..7e26c45 --- /dev/null +++ b/node_modules/es-object-atoms/RequireObjectCoercible.d.ts @@ -0,0 +1,3 @@ +declare function RequireObjectCoercible(value: T, optMessage?: string): T; + +export = RequireObjectCoercible; diff --git a/node_modules/es-object-atoms/RequireObjectCoercible.js b/node_modules/es-object-atoms/RequireObjectCoercible.js new file mode 100644 index 0000000..8e191c6 --- /dev/null +++ b/node_modules/es-object-atoms/RequireObjectCoercible.js @@ -0,0 +1,11 @@ +'use strict'; + +var $TypeError = require('es-errors/type'); + +/** @type {import('./RequireObjectCoercible')} */ +module.exports = function RequireObjectCoercible(value) { + if (value == null) { + throw new $TypeError((arguments.length > 0 && arguments[1]) || ('Cannot call method on ' + value)); + } + return value; +}; diff --git a/node_modules/es-object-atoms/ToObject.d.ts b/node_modules/es-object-atoms/ToObject.d.ts new file mode 100644 index 0000000..d6dd302 --- /dev/null +++ b/node_modules/es-object-atoms/ToObject.d.ts @@ -0,0 +1,7 @@ +declare function ToObject(value: number): Number; +declare function ToObject(value: boolean): Boolean; +declare function ToObject(value: string): String; +declare function ToObject(value: bigint): BigInt; +declare function ToObject(value: T): T; + +export = ToObject; diff --git a/node_modules/es-object-atoms/ToObject.js b/node_modules/es-object-atoms/ToObject.js new file mode 100644 index 0000000..2b99a7d --- /dev/null +++ b/node_modules/es-object-atoms/ToObject.js @@ -0,0 +1,10 @@ +'use strict'; + +var $Object = require('./'); +var RequireObjectCoercible = require('./RequireObjectCoercible'); + +/** @type {import('./ToObject')} */ +module.exports = function ToObject(value) { + RequireObjectCoercible(value); + return $Object(value); +}; diff --git a/node_modules/es-object-atoms/index.d.ts b/node_modules/es-object-atoms/index.d.ts new file mode 100644 index 0000000..8bdbfc8 --- /dev/null +++ b/node_modules/es-object-atoms/index.d.ts @@ -0,0 +1,3 @@ +declare const Object: ObjectConstructor; + +export = Object; diff --git a/node_modules/es-object-atoms/index.js b/node_modules/es-object-atoms/index.js new file mode 100644 index 0000000..1d33cef --- /dev/null +++ b/node_modules/es-object-atoms/index.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('.')} */ +module.exports = Object; diff --git a/node_modules/es-object-atoms/isObject.d.ts b/node_modules/es-object-atoms/isObject.d.ts new file mode 100644 index 0000000..43bee3b --- /dev/null +++ b/node_modules/es-object-atoms/isObject.d.ts @@ -0,0 +1,3 @@ +declare function isObject(x: unknown): x is object; + +export = isObject; diff --git a/node_modules/es-object-atoms/isObject.js b/node_modules/es-object-atoms/isObject.js new file mode 100644 index 0000000..ec49bf1 --- /dev/null +++ b/node_modules/es-object-atoms/isObject.js @@ -0,0 +1,6 @@ +'use strict'; + +/** @type {import('./isObject')} */ +module.exports = function isObject(x) { + return !!x && (typeof x === 'function' || typeof x === 'object'); +}; diff --git a/node_modules/es-object-atoms/package.json b/node_modules/es-object-atoms/package.json new file mode 100644 index 0000000..f4cec71 --- /dev/null +++ b/node_modules/es-object-atoms/package.json @@ -0,0 +1,80 @@ +{ + "name": "es-object-atoms", + "version": "1.1.1", + "description": "ES Object-related atoms: Object, ToObject, RequireObjectCoercible", + "main": "index.js", + "exports": { + ".": "./index.js", + "./RequireObjectCoercible": "./RequireObjectCoercible.js", + "./isObject": "./isObject.js", + "./ToObject": "./ToObject.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'", + "posttest": "npx npm@\">= 10.2\" audit --production", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git' | grep -v dist/)", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/es-object-atoms.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "object", + "toobject", + "coercible" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/es-object-atoms/issues" + }, + "homepage": "https://github.com/ljharb/es-object-atoms#readme", + "dependencies": { + "es-errors": "^1.3.0" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.3", + "@types/tape": "^5.8.1", + "auto-changelog": "^2.5.0", + "eclint": "^2.8.1", + "encoding": "^0.1.13", + "eslint": "^8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/es-object-atoms/test/index.js b/node_modules/es-object-atoms/test/index.js new file mode 100644 index 0000000..430b705 --- /dev/null +++ b/node_modules/es-object-atoms/test/index.js @@ -0,0 +1,38 @@ +'use strict'; + +var test = require('tape'); + +var $Object = require('../'); +var isObject = require('../isObject'); +var ToObject = require('../ToObject'); +var RequireObjectCoercible = require('..//RequireObjectCoercible'); + +test('errors', function (t) { + t.equal($Object, Object); + // @ts-expect-error + t['throws'](function () { ToObject(null); }, TypeError); + // @ts-expect-error + t['throws'](function () { ToObject(undefined); }, TypeError); + // @ts-expect-error + t['throws'](function () { RequireObjectCoercible(null); }, TypeError); + // @ts-expect-error + t['throws'](function () { RequireObjectCoercible(undefined); }, TypeError); + + t.deepEqual(RequireObjectCoercible(true), true); + t.deepEqual(ToObject(true), Object(true)); + t.deepEqual(ToObject(42), Object(42)); + var f = function () {}; + t.equal(ToObject(f), f); + + t.equal(isObject(undefined), false); + t.equal(isObject(null), false); + t.equal(isObject({}), true); + t.equal(isObject([]), true); + t.equal(isObject(function () {}), true); + + var obj = {}; + t.equal(RequireObjectCoercible(obj), obj); + t.equal(ToObject(obj), obj); + + t.end(); +}); diff --git a/node_modules/es-object-atoms/tsconfig.json b/node_modules/es-object-atoms/tsconfig.json new file mode 100644 index 0000000..1f73cb7 --- /dev/null +++ b/node_modules/es-object-atoms/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es5", + }, +} diff --git a/node_modules/es-set-tostringtag/.eslintrc b/node_modules/es-set-tostringtag/.eslintrc new file mode 100644 index 0000000..2612ed8 --- /dev/null +++ b/node_modules/es-set-tostringtag/.eslintrc @@ -0,0 +1,13 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/node_modules/es-set-tostringtag/.nycrc b/node_modules/es-set-tostringtag/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/es-set-tostringtag/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/es-set-tostringtag/CHANGELOG.md b/node_modules/es-set-tostringtag/CHANGELOG.md new file mode 100644 index 0000000..00bdc03 --- /dev/null +++ b/node_modules/es-set-tostringtag/CHANGELOG.md @@ -0,0 +1,67 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v2.1.0](https://github.com/es-shims/es-set-tostringtag/compare/v2.0.3...v2.1.0) - 2025-01-01 + +### Commits + +- [actions] split out node 10-20, and 20+ [`ede033c`](https://github.com/es-shims/es-set-tostringtag/commit/ede033cc4e506c3966d2d482d4ac5987e329162a) +- [types] use shared config [`28ef164`](https://github.com/es-shims/es-set-tostringtag/commit/28ef164ad7c5bc21837c79f7ef25542a1f258ade) +- [New] add `nonConfigurable` option [`3bee3f0`](https://github.com/es-shims/es-set-tostringtag/commit/3bee3f04caddd318f3932912212ed20b2d62aad7) +- [Fix] validate boolean option argument [`3c8a609`](https://github.com/es-shims/es-set-tostringtag/commit/3c8a609c795a305ccca163f0ff6956caa88cdc0e) +- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/eslint-config`, `@ljharb/tsconfig`, `@types/get-intrinsic`, `@types/tape`, `auto-changelog`, `tape` [`501a969`](https://github.com/es-shims/es-set-tostringtag/commit/501a96998484226e07f5ffd447e8f305a998f1d8) +- [Tests] add coverage [`18af289`](https://github.com/es-shims/es-set-tostringtag/commit/18af2897b4e937373c9b8c8831bc338932246470) +- [readme] document `force` option [`bd446a1`](https://github.com/es-shims/es-set-tostringtag/commit/bd446a107b71a2270278442e5124f45590d3ee64) +- [Tests] use `@arethetypeswrong/cli` [`7c2c2fa`](https://github.com/es-shims/es-set-tostringtag/commit/7c2c2fa3cca0f4d263603adb75426b239514598f) +- [Tests] replace `aud` with `npm audit` [`9e372d7`](https://github.com/es-shims/es-set-tostringtag/commit/9e372d7e6db3dab405599a14d9074a99a03b8242) +- [Deps] update `get-intrinsic` [`7df1216`](https://github.com/es-shims/es-set-tostringtag/commit/7df12167295385c2a547410e687cb0c04f3a34b9) +- [Deps] update `hasown` [`993a7d2`](https://github.com/es-shims/es-set-tostringtag/commit/993a7d200e2059fd857ec1a25d0a49c2c34ae6e2) +- [Dev Deps] add missing peer dep [`148ed8d`](https://github.com/es-shims/es-set-tostringtag/commit/148ed8db99a7a94f9af3823fd083e6e437fa1587) + +## [v2.0.3](https://github.com/es-shims/es-set-tostringtag/compare/v2.0.2...v2.0.3) - 2024-02-20 + +### Commits + +- add types [`d538513`](https://github.com/es-shims/es-set-tostringtag/commit/d5385133592a32a0a416cb535327918af7fbc4ad) +- [Deps] update `get-intrinsic`, `has-tostringtag`, `hasown` [`d129b29`](https://github.com/es-shims/es-set-tostringtag/commit/d129b29536bccc8a9d03a47887ca4d1f7ad0c5b9) +- [Dev Deps] update `aud`, `npmignore`, `tape` [`132ed23`](https://github.com/es-shims/es-set-tostringtag/commit/132ed23c964a41ed55e4ab4a5a2c3fe185e821c1) +- [Tests] fix hasOwn require [`f89c831`](https://github.com/es-shims/es-set-tostringtag/commit/f89c831fe5f3edf1f979c597b56fee1be6111f56) + +## [v2.0.2](https://github.com/es-shims/es-set-tostringtag/compare/v2.0.1...v2.0.2) - 2023-10-20 + +### Commits + +- [Refactor] use `hasown` instead of `has` [`0cc6c4e`](https://github.com/es-shims/es-set-tostringtag/commit/0cc6c4e61fd13e8f00b85424ae6e541ebf289e74) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`70e447c`](https://github.com/es-shims/es-set-tostringtag/commit/70e447cf9f82b896ddf359fda0a0498c16cf3ed2) +- [Deps] update `get-intrinsic` [`826aab7`](https://github.com/es-shims/es-set-tostringtag/commit/826aab76180392871c8efa99acc0f0bbf775c64e) + +## [v2.0.1](https://github.com/es-shims/es-set-tostringtag/compare/v2.0.0...v2.0.1) - 2023-01-05 + +### Fixed + +- [Fix] move `has` to prod deps [`#2`](https://github.com/es-shims/es-set-tostringtag/issues/2) + +### Commits + +- [Dev Deps] update `@ljharb/eslint-config` [`b9eecd2`](https://github.com/es-shims/es-set-tostringtag/commit/b9eecd23c10b7b43ba75089ac8ff8cc6b295798b) + +## [v2.0.0](https://github.com/es-shims/es-set-tostringtag/compare/v1.0.0...v2.0.0) - 2022-12-21 + +### Commits + +- [Tests] refactor tests [`168dcfb`](https://github.com/es-shims/es-set-tostringtag/commit/168dcfbb535c279dc48ccdc89419155125aaec18) +- [Breaking] do not set toStringTag if it is already set [`226ab87`](https://github.com/es-shims/es-set-tostringtag/commit/226ab874192c625d9e5f0e599d3f60d2b2aa83b5) +- [New] add `force` option to set even if already set [`1abd4ec`](https://github.com/es-shims/es-set-tostringtag/commit/1abd4ecb282f19718c4518284b0293a343564505) + +## v1.0.0 - 2022-12-21 + +### Commits + +- Initial implementation, tests, readme [`a0e1147`](https://github.com/es-shims/es-set-tostringtag/commit/a0e11473f79a233b46374525c962ea1b4d42418a) +- Initial commit [`ffd4aff`](https://github.com/es-shims/es-set-tostringtag/commit/ffd4afffbeebf29aff0d87a7cfc3f7844e09fe68) +- npm init [`fffe5bd`](https://github.com/es-shims/es-set-tostringtag/commit/fffe5bd1d1146d084730a387a9c672371f4a8fff) +- Only apps should have lockfiles [`d363871`](https://github.com/es-shims/es-set-tostringtag/commit/d36387139465623e161a15dbd39120537f150c62) diff --git a/node_modules/es-set-tostringtag/LICENSE b/node_modules/es-set-tostringtag/LICENSE new file mode 100644 index 0000000..c2a8460 --- /dev/null +++ b/node_modules/es-set-tostringtag/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 ECMAScript Shims + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/es-set-tostringtag/README.md b/node_modules/es-set-tostringtag/README.md new file mode 100644 index 0000000..c27bc9f --- /dev/null +++ b/node_modules/es-set-tostringtag/README.md @@ -0,0 +1,53 @@ +# es-set-tostringtag [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +A helper to optimistically set Symbol.toStringTag, when possible. + +## Example +Most common usage: +```js +var assert = require('assert'); +var setToStringTag = require('es-set-tostringtag'); + +var obj = {}; + +assert.equal(Object.prototype.toString.call(obj), '[object Object]'); + +setToStringTag(obj, 'tagged!'); + +assert.equal(Object.prototype.toString.call(obj), '[object tagged!]'); +``` + +## Options +An optional options argument can be provided as the third argument. The available options are: + +### `force` +If the `force` option is set to `true`, the toStringTag will be set even if it is already set. + +### `nonConfigurable` +If the `nonConfigurable` option is set to `true`, the toStringTag will be defined as non-configurable when possible. + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.com/package/es-set-tostringtag +[npm-version-svg]: https://versionbadg.es/es-shims/es-set-tostringtag.svg +[deps-svg]: https://david-dm.org/es-shims/es-set-tostringtag.svg +[deps-url]: https://david-dm.org/es-shims/es-set-tostringtag +[dev-deps-svg]: https://david-dm.org/es-shims/es-set-tostringtag/dev-status.svg +[dev-deps-url]: https://david-dm.org/es-shims/es-set-tostringtag#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/es-set-tostringtag.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/es-set-tostringtag.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/es-set-tostringtag.svg +[downloads-url]: https://npm-stat.com/charts.html?package=es-set-tostringtag +[codecov-image]: https://codecov.io/gh/es-shims/es-set-tostringtag/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/es-shims/es-set-tostringtag/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/es-shims/es-set-tostringtag +[actions-url]: https://github.com/es-shims/es-set-tostringtag/actions diff --git a/node_modules/es-set-tostringtag/index.d.ts b/node_modules/es-set-tostringtag/index.d.ts new file mode 100644 index 0000000..c9a8fc4 --- /dev/null +++ b/node_modules/es-set-tostringtag/index.d.ts @@ -0,0 +1,10 @@ +declare function setToStringTag( + object: object & { [Symbol.toStringTag]?: unknown }, + value: string | unknown, + options?: { + force?: boolean; + nonConfigurable?: boolean; + }, +): void; + +export = setToStringTag; \ No newline at end of file diff --git a/node_modules/es-set-tostringtag/index.js b/node_modules/es-set-tostringtag/index.js new file mode 100644 index 0000000..6b6b49c --- /dev/null +++ b/node_modules/es-set-tostringtag/index.js @@ -0,0 +1,35 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); + +var hasToStringTag = require('has-tostringtag/shams')(); +var hasOwn = require('hasown'); +var $TypeError = require('es-errors/type'); + +var toStringTag = hasToStringTag ? Symbol.toStringTag : null; + +/** @type {import('.')} */ +module.exports = function setToStringTag(object, value) { + var overrideIfSet = arguments.length > 2 && !!arguments[2] && arguments[2].force; + var nonConfigurable = arguments.length > 2 && !!arguments[2] && arguments[2].nonConfigurable; + if ( + (typeof overrideIfSet !== 'undefined' && typeof overrideIfSet !== 'boolean') + || (typeof nonConfigurable !== 'undefined' && typeof nonConfigurable !== 'boolean') + ) { + throw new $TypeError('if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans'); + } + if (toStringTag && (overrideIfSet || !hasOwn(object, toStringTag))) { + if ($defineProperty) { + $defineProperty(object, toStringTag, { + configurable: !nonConfigurable, + enumerable: false, + value: value, + writable: false + }); + } else { + object[toStringTag] = value; // eslint-disable-line no-param-reassign + } + } +}; diff --git a/node_modules/es-set-tostringtag/package.json b/node_modules/es-set-tostringtag/package.json new file mode 100644 index 0000000..277c3e5 --- /dev/null +++ b/node_modules/es-set-tostringtag/package.json @@ -0,0 +1,78 @@ +{ + "name": "es-set-tostringtag", + "version": "2.1.0", + "description": "A helper to optimistically set Symbol.toStringTag, when possible.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@\">= 10.2\" audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/es-shims/es-set-tostringtag.git" + }, + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/es-shims/es-set-tostringtag/issues" + }, + "homepage": "https://github.com/es-shims/es-set-tostringtag#readme", + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.2", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.3", + "@types/get-intrinsic": "^1.2.3", + "@types/has-symbols": "^1.0.2", + "@types/tape": "^5.8.0", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "testling": { + "files": "./test/index.js" + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/es-set-tostringtag/test/index.js b/node_modules/es-set-tostringtag/test/index.js new file mode 100644 index 0000000..f1757b3 --- /dev/null +++ b/node_modules/es-set-tostringtag/test/index.js @@ -0,0 +1,85 @@ +'use strict'; + +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); +var hasOwn = require('hasown'); + +var setToStringTag = require('../'); + +test('setToStringTag', function (t) { + t.equal(typeof setToStringTag, 'function', 'is a function'); + + /** @type {{ [Symbol.toStringTag]?: typeof sentinel }} */ + var obj = {}; + var sentinel = {}; + + setToStringTag(obj, sentinel); + + t['throws']( + // @ts-expect-error + function () { setToStringTag(obj, sentinel, { force: 'yes' }); }, + TypeError, + 'throws if options is not an object' + ); + + t.test('has Symbol.toStringTag', { skip: !hasToStringTag }, function (st) { + st.ok(hasOwn(obj, Symbol.toStringTag), 'has toStringTag property'); + + st.equal(obj[Symbol.toStringTag], sentinel, 'toStringTag property is as expected'); + + st.equal(String(obj), '[object Object]', 'toStringTag works'); + + /** @type {{ [Symbol.toStringTag]?: string }} */ + var tagged = {}; + tagged[Symbol.toStringTag] = 'already tagged'; + st.equal(String(tagged), '[object already tagged]', 'toStringTag works'); + + setToStringTag(tagged, 'new tag'); + st.equal(String(tagged), '[object already tagged]', 'toStringTag is unchanged'); + + setToStringTag(tagged, 'new tag', { force: true }); + st.equal(String(tagged), '[object new tag]', 'toStringTag is changed with force: true'); + + st.deepEqual( + Object.getOwnPropertyDescriptor(tagged, Symbol.toStringTag), + { + configurable: true, + enumerable: false, + value: 'new tag', + writable: false + }, + 'has expected property descriptor' + ); + + setToStringTag(tagged, 'new tag', { force: true, nonConfigurable: true }); + st.deepEqual( + Object.getOwnPropertyDescriptor(tagged, Symbol.toStringTag), + { + configurable: false, + enumerable: false, + value: 'new tag', + writable: false + }, + 'is nonconfigurable' + ); + + st.end(); + }); + + t.test('does not have Symbol.toStringTag', { skip: hasToStringTag }, function (st) { + var passed = true; + for (var key in obj) { // eslint-disable-line no-restricted-syntax + if (hasOwn(obj, key)) { + st.fail('object has own key ' + key); + passed = false; + } + } + if (passed) { + st.ok(true, 'object has no enumerable own keys'); + } + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/es-set-tostringtag/tsconfig.json b/node_modules/es-set-tostringtag/tsconfig.json new file mode 100644 index 0000000..d9a6668 --- /dev/null +++ b/node_modules/es-set-tostringtag/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/escalade/dist/index.js b/node_modules/escalade/dist/index.js new file mode 100644 index 0000000..ad236c4 --- /dev/null +++ b/node_modules/escalade/dist/index.js @@ -0,0 +1,22 @@ +const { dirname, resolve } = require('path'); +const { readdir, stat } = require('fs'); +const { promisify } = require('util'); + +const toStats = promisify(stat); +const toRead = promisify(readdir); + +module.exports = async function (start, callback) { + let dir = resolve('.', start); + let tmp, stats = await toStats(dir); + + if (!stats.isDirectory()) { + dir = dirname(dir); + } + + while (true) { + tmp = await callback(dir, await toRead(dir)); + if (tmp) return resolve(dir, tmp); + dir = dirname(tmp = dir); + if (tmp === dir) break; + } +} diff --git a/node_modules/escalade/dist/index.mjs b/node_modules/escalade/dist/index.mjs new file mode 100644 index 0000000..bf95be0 --- /dev/null +++ b/node_modules/escalade/dist/index.mjs @@ -0,0 +1,22 @@ +import { dirname, resolve } from 'path'; +import { readdir, stat } from 'fs'; +import { promisify } from 'util'; + +const toStats = promisify(stat); +const toRead = promisify(readdir); + +export default async function (start, callback) { + let dir = resolve('.', start); + let tmp, stats = await toStats(dir); + + if (!stats.isDirectory()) { + dir = dirname(dir); + } + + while (true) { + tmp = await callback(dir, await toRead(dir)); + if (tmp) return resolve(dir, tmp); + dir = dirname(tmp = dir); + if (tmp === dir) break; + } +} diff --git a/node_modules/escalade/index.d.mts b/node_modules/escalade/index.d.mts new file mode 100644 index 0000000..550699c --- /dev/null +++ b/node_modules/escalade/index.d.mts @@ -0,0 +1,11 @@ +type Promisable = T | Promise; + +export type Callback = ( + directory: string, + files: string[], +) => Promisable; + +export default function ( + directory: string, + callback: Callback, +): Promise; diff --git a/node_modules/escalade/index.d.ts b/node_modules/escalade/index.d.ts new file mode 100644 index 0000000..26c58f2 --- /dev/null +++ b/node_modules/escalade/index.d.ts @@ -0,0 +1,15 @@ +type Promisable = T | Promise; + +declare namespace escalade { + export type Callback = ( + directory: string, + files: string[], + ) => Promisable; +} + +declare function escalade( + directory: string, + callback: escalade.Callback, +): Promise; + +export = escalade; diff --git a/node_modules/escalade/license b/node_modules/escalade/license new file mode 100644 index 0000000..fa6089f --- /dev/null +++ b/node_modules/escalade/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Luke Edwards (lukeed.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/escalade/package.json b/node_modules/escalade/package.json new file mode 100644 index 0000000..1eed4f9 --- /dev/null +++ b/node_modules/escalade/package.json @@ -0,0 +1,74 @@ +{ + "name": "escalade", + "version": "3.2.0", + "repository": "lukeed/escalade", + "description": "A tiny (183B to 210B) and fast utility to ascend parent directories", + "module": "dist/index.mjs", + "main": "dist/index.js", + "types": "index.d.ts", + "license": "MIT", + "author": { + "name": "Luke Edwards", + "email": "luke.edwards05@gmail.com", + "url": "https://lukeed.com" + }, + "exports": { + ".": [ + { + "import": { + "types": "./index.d.mts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./index.d.ts", + "default": "./dist/index.js" + } + }, + "./dist/index.js" + ], + "./sync": [ + { + "import": { + "types": "./sync/index.d.mts", + "default": "./sync/index.mjs" + }, + "require": { + "types": "./sync/index.d.ts", + "default": "./sync/index.js" + } + }, + "./sync/index.js" + ] + }, + "files": [ + "*.d.mts", + "*.d.ts", + "dist", + "sync" + ], + "modes": { + "sync": "src/sync.js", + "default": "src/async.js" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "build": "bundt", + "pretest": "npm run build", + "test": "uvu -r esm test -i fixtures" + }, + "keywords": [ + "find", + "parent", + "parents", + "directory", + "search", + "walk" + ], + "devDependencies": { + "bundt": "1.1.1", + "esm": "3.2.25", + "uvu": "0.3.3" + } +} diff --git a/node_modules/escalade/readme.md b/node_modules/escalade/readme.md new file mode 100644 index 0000000..e07ee0d --- /dev/null +++ b/node_modules/escalade/readme.md @@ -0,0 +1,211 @@ +# escalade [![CI](https://github.com/lukeed/escalade/workflows/CI/badge.svg)](https://github.com/lukeed/escalade/actions) [![licenses](https://licenses.dev/b/npm/escalade)](https://licenses.dev/npm/escalade) [![codecov](https://badgen.now.sh/codecov/c/github/lukeed/escalade)](https://codecov.io/gh/lukeed/escalade) + +> A tiny (183B to 210B) and [fast](#benchmarks) utility to ascend parent directories + +With [escalade](https://en.wikipedia.org/wiki/Escalade), you can scale parent directories until you've found what you're looking for.
                          Given an input file or directory, `escalade` will continue executing your callback function until either: + +1) the callback returns a truthy value +2) `escalade` has reached the system root directory (eg, `/`) + +> **Important:**
                          Please note that `escalade` only deals with direct ancestry – it will not dive into parents' sibling directories. + +--- + +**Notice:** As of v3.1.0, `escalade` now includes [Deno support](http://deno.land/x/escalade)! Please see [Deno Usage](#deno) below. + +--- + +## Install + +``` +$ npm install --save escalade +``` + + +## Modes + +There are two "versions" of `escalade` available: + +#### "async" +> **Node.js:** >= 8.x
                          +> **Size (gzip):** 210 bytes
                          +> **Availability:** [CommonJS](https://unpkg.com/escalade/dist/index.js), [ES Module](https://unpkg.com/escalade/dist/index.mjs) + +This is the primary/default mode. It makes use of `async`/`await` and [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original). + +#### "sync" +> **Node.js:** >= 6.x
                          +> **Size (gzip):** 183 bytes
                          +> **Availability:** [CommonJS](https://unpkg.com/escalade/sync/index.js), [ES Module](https://unpkg.com/escalade/sync/index.mjs) + +This is the opt-in mode, ideal for scenarios where `async` usage cannot be supported. + + +## Usage + +***Example Structure*** + +``` +/Users/lukeed + └── oss + ├── license + └── escalade + ├── package.json + └── test + └── fixtures + ├── index.js + └── foobar + └── demo.js +``` + +***Example Usage*** + +```js +//~> demo.js +import { join } from 'path'; +import escalade from 'escalade'; + +const input = join(__dirname, 'demo.js'); +// or: const input = __dirname; + +const pkg = await escalade(input, (dir, names) => { + console.log('~> dir:', dir); + console.log('~> names:', names); + console.log('---'); + + if (names.includes('package.json')) { + // will be resolved into absolute + return 'package.json'; + } +}); + +//~> dir: /Users/lukeed/oss/escalade/test/fixtures/foobar +//~> names: ['demo.js'] +//--- +//~> dir: /Users/lukeed/oss/escalade/test/fixtures +//~> names: ['index.js', 'foobar'] +//--- +//~> dir: /Users/lukeed/oss/escalade/test +//~> names: ['fixtures'] +//--- +//~> dir: /Users/lukeed/oss/escalade +//~> names: ['package.json', 'test'] +//--- + +console.log(pkg); +//=> /Users/lukeed/oss/escalade/package.json + +// Now search for "missing123.txt" +// (Assume it doesn't exist anywhere!) +const missing = await escalade(input, (dir, names) => { + console.log('~> dir:', dir); + return names.includes('missing123.txt') && 'missing123.txt'; +}); + +//~> dir: /Users/lukeed/oss/escalade/test/fixtures/foobar +//~> dir: /Users/lukeed/oss/escalade/test/fixtures +//~> dir: /Users/lukeed/oss/escalade/test +//~> dir: /Users/lukeed/oss/escalade +//~> dir: /Users/lukeed/oss +//~> dir: /Users/lukeed +//~> dir: /Users +//~> dir: / + +console.log(missing); +//=> undefined +``` + +> **Note:** To run the above example with "sync" mode, import from `escalade/sync` and remove the `await` keyword. + + +## API + +### escalade(input, callback) +Returns: `string|void` or `Promise` + +When your `callback` locates a file, `escalade` will resolve/return with an absolute path.
                          +If your `callback` was never satisfied, then `escalade` will resolve/return with nothing (undefined). + +> **Important:**
                          The `sync` and `async` versions share the same API.
                          The **only** difference is that `sync` is not Promise-based. + +#### input +Type: `string` + +The path from which to start ascending. + +This may be a file or a directory path.
                          However, when `input` is a file, `escalade` will begin with its parent directory. + +> **Important:** Unless given an absolute path, `input` will be resolved from `process.cwd()` location. + +#### callback +Type: `Function` + +The callback to execute for each ancestry level. It always is given two arguments: + +1) `dir` - an absolute path of the current parent directory +2) `names` - a list (`string[]`) of contents _relative to_ the `dir` parent + +> **Note:** The `names` list can contain names of files _and_ directories. + +When your callback returns a _falsey_ value, then `escalade` will continue with `dir`'s parent directory, re-invoking your callback with new argument values. + +When your callback returns a string, then `escalade` stops iteration immediately.
                          +If the string is an absolute path, then it's left as is. Otherwise, the string is resolved into an absolute path _from_ the `dir` that housed the satisfying condition. + +> **Important:** Your `callback` can be a `Promise/AsyncFunction` when using the "async" version of `escalade`. + +## Benchmarks + +> Running on Node.js v10.13.0 + +``` +# Load Time + find-up 3.891ms + escalade 0.485ms + escalade/sync 0.309ms + +# Levels: 6 (target = "foo.txt"): + find-up x 24,856 ops/sec ±6.46% (55 runs sampled) + escalade x 73,084 ops/sec ±4.23% (73 runs sampled) + find-up.sync x 3,663 ops/sec ±1.12% (83 runs sampled) + escalade/sync x 9,360 ops/sec ±0.62% (88 runs sampled) + +# Levels: 12 (target = "package.json"): + find-up x 29,300 ops/sec ±10.68% (70 runs sampled) + escalade x 73,685 ops/sec ± 5.66% (66 runs sampled) + find-up.sync x 1,707 ops/sec ± 0.58% (91 runs sampled) + escalade/sync x 4,667 ops/sec ± 0.68% (94 runs sampled) + +# Levels: 18 (target = "missing123.txt"): + find-up x 21,818 ops/sec ±17.37% (14 runs sampled) + escalade x 67,101 ops/sec ±21.60% (20 runs sampled) + find-up.sync x 1,037 ops/sec ± 2.86% (88 runs sampled) + escalade/sync x 1,248 ops/sec ± 0.50% (93 runs sampled) +``` + +## Deno + +As of v3.1.0, `escalade` is available on the Deno registry. + +Please note that the [API](#api) is identical and that there are still [two modes](#modes) from which to choose: + +```ts +// Choose "async" mode +import escalade from 'https://deno.land/escalade/async.ts'; + +// Choose "sync" mode +import escalade from 'https://deno.land/escalade/sync.ts'; +``` + +> **Important:** The `allow-read` permission is required! + + +## Related + +- [premove](https://github.com/lukeed/premove) - A tiny (247B) utility to remove items recursively +- [totalist](https://github.com/lukeed/totalist) - A tiny (195B to 224B) utility to recursively list all (total) files in a directory +- [mk-dirs](https://github.com/lukeed/mk-dirs) - A tiny (420B) utility to make a directory and its parents, recursively + +## License + +MIT © [Luke Edwards](https://lukeed.com) diff --git a/node_modules/escalade/sync/index.d.mts b/node_modules/escalade/sync/index.d.mts new file mode 100644 index 0000000..c023d37 --- /dev/null +++ b/node_modules/escalade/sync/index.d.mts @@ -0,0 +1,9 @@ +export type Callback = ( + directory: string, + files: string[], +) => string | false | void; + +export default function ( + directory: string, + callback: Callback, +): string | void; diff --git a/node_modules/escalade/sync/index.d.ts b/node_modules/escalade/sync/index.d.ts new file mode 100644 index 0000000..9d5b589 --- /dev/null +++ b/node_modules/escalade/sync/index.d.ts @@ -0,0 +1,13 @@ +declare namespace escalade { + export type Callback = ( + directory: string, + files: string[], + ) => string | false | void; +} + +declare function escalade( + directory: string, + callback: escalade.Callback, +): string | void; + +export = escalade; diff --git a/node_modules/escalade/sync/index.js b/node_modules/escalade/sync/index.js new file mode 100644 index 0000000..902cc46 --- /dev/null +++ b/node_modules/escalade/sync/index.js @@ -0,0 +1,18 @@ +const { dirname, resolve } = require('path'); +const { readdirSync, statSync } = require('fs'); + +module.exports = function (start, callback) { + let dir = resolve('.', start); + let tmp, stats = statSync(dir); + + if (!stats.isDirectory()) { + dir = dirname(dir); + } + + while (true) { + tmp = callback(dir, readdirSync(dir)); + if (tmp) return resolve(dir, tmp); + dir = dirname(tmp = dir); + if (tmp === dir) break; + } +} diff --git a/node_modules/escalade/sync/index.mjs b/node_modules/escalade/sync/index.mjs new file mode 100644 index 0000000..3cdc5bd --- /dev/null +++ b/node_modules/escalade/sync/index.mjs @@ -0,0 +1,18 @@ +import { dirname, resolve } from 'path'; +import { readdirSync, statSync } from 'fs'; + +export default function (start, callback) { + let dir = resolve('.', start); + let tmp, stats = statSync(dir); + + if (!stats.isDirectory()) { + dir = dirname(dir); + } + + while (true) { + tmp = callback(dir, readdirSync(dir)); + if (tmp) return resolve(dir, tmp); + dir = dirname(tmp = dir); + if (tmp === dir) break; + } +} diff --git a/node_modules/event-target-shim/LICENSE b/node_modules/event-target-shim/LICENSE new file mode 100644 index 0000000..c39e694 --- /dev/null +++ b/node_modules/event-target-shim/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Toru Nagashima + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/event-target-shim/README.md b/node_modules/event-target-shim/README.md new file mode 100644 index 0000000..a4f9c1b --- /dev/null +++ b/node_modules/event-target-shim/README.md @@ -0,0 +1,293 @@ +# event-target-shim + +[![npm version](https://img.shields.io/npm/v/event-target-shim.svg)](https://www.npmjs.com/package/event-target-shim) +[![Downloads/month](https://img.shields.io/npm/dm/event-target-shim.svg)](http://www.npmtrends.com/event-target-shim) +[![Build Status](https://travis-ci.org/mysticatea/event-target-shim.svg?branch=master)](https://travis-ci.org/mysticatea/event-target-shim) +[![Coverage Status](https://codecov.io/gh/mysticatea/event-target-shim/branch/master/graph/badge.svg)](https://codecov.io/gh/mysticatea/event-target-shim) +[![Dependency Status](https://david-dm.org/mysticatea/event-target-shim.svg)](https://david-dm.org/mysticatea/event-target-shim) + +An implementation of [WHATWG EventTarget interface](https://dom.spec.whatwg.org/#interface-eventtarget), plus few extensions. + +- This provides `EventTarget` constructor that can inherit for your custom object. +- This provides an utility that defines properties of attribute listeners (e.g. `obj.onclick`). + +```js +import {EventTarget, defineEventAttribute} from "event-target-shim" + +class Foo extends EventTarget { + // ... +} + +// Define `foo.onhello` property. +defineEventAttribute(Foo.prototype, "hello") + +// Use +const foo = new Foo() +foo.addEventListener("hello", e => console.log("hello", e)) +foo.onhello = e => console.log("onhello:", e) +foo.dispatchEvent(new CustomEvent("hello")) +``` + +## 💿 Installation + +Use [npm](https://www.npmjs.com/) to install then use a bundler. + +``` +npm install event-target-shim +``` + +Or download from [`dist` directory](./dist). + +- [dist/event-target-shim.mjs](dist/event-target-shim.mjs) ... ES modules version. +- [dist/event-target-shim.js](dist/event-target-shim.js) ... Common JS version. +- [dist/event-target-shim.umd.js](dist/event-target-shim.umd.js) ... UMD (Universal Module Definition) version. This is transpiled by [Babel](https://babeljs.io/) for IE 11. + +## 📖 Usage + +```js +import {EventTarget, defineEventAttribute} from "event-target-shim" +// or +const {EventTarget, defineEventAttribute} = require("event-target-shim") + +// or UMD version defines a global variable: +const {EventTarget, defineEventAttribute} = window.EventTargetShim +``` + +### EventTarget + +> https://dom.spec.whatwg.org/#interface-eventtarget + +#### eventTarget.addEventListener(type, callback, options) + +Register an event listener. + +- `type` is a string. This is the event name to register. +- `callback` is a function. This is the event listener to register. +- `options` is a boolean or an object `{ capture?: boolean, passive?: boolean, once?: boolean }`. If this is a boolean, it's same meaning as `{ capture: options }`. + - `capture` is the flag to register the event listener for capture phase. + - `passive` is the flag to ignore `event.preventDefault()` method in the event listener. + - `once` is the flag to remove the event listener automatically after the first call. + +#### eventTarget.removeEventListener(type, callback, options) + +Unregister an event listener. + +- `type` is a string. This is the event name to unregister. +- `callback` is a function. This is the event listener to unregister. +- `options` is a boolean or an object `{ capture?: boolean }`. If this is a boolean, it's same meaning as `{ capture: options }`. + - `capture` is the flag to register the event listener for capture phase. + +#### eventTarget.dispatchEvent(event) + +Dispatch an event. + +- `event` is a [Event](https://dom.spec.whatwg.org/#event) object or an object `{ type: string, [key: string]: any }`. The latter is non-standard but useful. In both cases, listeners receive the event as implementing [Event](https://dom.spec.whatwg.org/#event) interface. + +### defineEventAttribute(proto, type) + +Define an event attribute (e.g. `onclick`) to `proto`. This is non-standard. + +- `proto` is an object (assuming it's a prototype object). This function defines a getter/setter pair for the event attribute. +- `type` is a string. This is the event name to define. + +For example: + +```js +class AbortSignal extends EventTarget { + constructor() { + this.aborted = false + } +} +// Define `onabort` property. +defineEventAttribute(AbortSignal.prototype, "abort") +``` + +### EventTarget(types) + +Define a custom `EventTarget` class with event attributes. This is non-standard. + +- `types` is a string or an array of strings. This is the event name to define. + +For example: + +```js +// This has `onabort` property. +class AbortSignal extends EventTarget("abort") { + constructor() { + this.aborted = false + } +} +``` + +## 📚 Examples + +### ES2015 and later + +> https://jsfiddle.net/636vea92/ + +```js +const {EventTarget, defineEventAttribute} = EventTargetShim + +// Define a derived class. +class Foo extends EventTarget { + // ... +} + +// Define `foo.onhello` property. +defineEventAttribute(Foo.prototype, "hello") + +// Register event listeners. +const foo = new Foo() +foo.addEventListener("hello", (e) => { + console.log("hello", e) +}) +foo.onhello = (e) => { + console.log("onhello", e) +} + +// Dispatching events +foo.dispatchEvent(new CustomEvent("hello", { detail: "detail" })) +``` + +### Typescript + +```ts +import { EventTarget, defineEventAttribute } from "event-target-shim"; + +// Define events +type FooEvents = { + hello: CustomEvent +} +type FooEventAttributes = { + onhello: CustomEvent +} + +// Define a derived class. +class Foo extends EventTarget { + // ... +} +// Define `foo.onhello` property's implementation. +defineEventAttribute(Foo.prototype, "hello") + +// Register event listeners. +const foo = new Foo() +foo.addEventListener("hello", (e) => { + console.log("hello", e.detail) +}) +foo.onhello = (e) => { + console.log("onhello", e.detail) +} + +// Dispatching events +foo.dispatchEvent(new CustomEvent("hello", { detail: "detail" })) +``` + +Unfortunately, both `FooEvents` and `FooEventAttributes` are needed because TypeScript doesn't allow the mutation of string literal types. If TypeScript allowed us to compute `"onhello"` from `"hello"` in types, `FooEventAttributes` will be optional. + +This `EventTarget` type is compatible with `EventTarget` interface of `lib.dom.d.ts`. + +#### To disallow unknown events + +By default, methods such as `addEventListener` accept unknown events. You can disallow unknown events by the third type parameter `"strict"`. + +```ts +type FooEvents = { + hello: CustomEvent +} +class Foo extends EventTarget { + // ... +} + +// OK because `hello` is defined in FooEvents. +foo.addEventListener("hello", (e) => { +}) +// Error because `unknown` is not defined in FooEvents. +foo.addEventListener("unknown", (e) => { +}) +``` + +However, if you use `"strict"` parameter, it loses compatibility with `EventTarget` interface of `lib.dom.d.ts`. + +#### To infer the type of `dispatchEvent()` method + +TypeScript cannot infer the event type of `dispatchEvent()` method properly from the argument in most cases. You can improve this behavior with the following steps: + +1. Use the third type parameter `"strict"`. This prevents inferring to `dispatchEvent()`. +2. Make the `type` property of event definitions stricter. + +```ts +type FooEvents = { + hello: CustomEvent & { type: "hello" } + hey: Event & { type: "hey" } +} +class Foo extends EventTarget { + // ... +} + +// Error because `detail` property is lacking. +foo.dispatchEvent({ type: "hello" }) +``` + +### ES5 + +> https://jsfiddle.net/522zc9de/ + +```js +// Define a derived class. +function Foo() { + EventTarget.call(this) +} +Foo.prototype = Object.create(EventTarget.prototype, { + constructor: { value: Foo, configurable: true, writable: true } + // ... +}) + +// Define `foo.onhello` property. +defineEventAttribute(Foo.prototype, "hello") + +// Register event listeners. +var foo = new Foo() +foo.addEventListener("hello", function(e) { + console.log("hello", e) +}) +foo.onhello = function(e) { + console.log("onhello", e) +} + +// Dispatching events +function isSupportEventConstrucor() { // IE does not support. + try { + new CusomEvent("hello") + return true + } catch (_err) { + return false + } +} +if (isSupportEventConstrucor()) { + foo.dispatchEvent(new CustomEvent("hello", { detail: "detail" })) +} else { + var e = document.createEvent("CustomEvent") + e.initCustomEvent("hello", false, false, "detail") + foo.dispatchEvent(e) +} +``` + +## 📰 Changelog + +- See [GitHub releases](https://github.com/mysticatea/event-target-shim/releases). + +## 🍻 Contributing + +Contributing is welcome ❤️ + +Please use GitHub issues/PRs. + +### Development tools + +- `npm install` installs dependencies for development. +- `npm test` runs tests and measures code coverage. +- `npm run clean` removes temporary files of tests. +- `npm run coverage` opens code coverage of the previous test with your default browser. +- `npm run lint` runs ESLint. +- `npm run build` generates `dist` codes. +- `npm run watch` runs tests on each file change. diff --git a/node_modules/event-target-shim/dist/event-target-shim.js b/node_modules/event-target-shim/dist/event-target-shim.js new file mode 100644 index 0000000..53ce220 --- /dev/null +++ b/node_modules/event-target-shim/dist/event-target-shim.js @@ -0,0 +1,871 @@ +/** + * @author Toru Nagashima + * @copyright 2015 Toru Nagashima. All rights reserved. + * See LICENSE file in root directory for full license. + */ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +/** + * @typedef {object} PrivateData + * @property {EventTarget} eventTarget The event target. + * @property {{type:string}} event The original event object. + * @property {number} eventPhase The current event phase. + * @property {EventTarget|null} currentTarget The current event target. + * @property {boolean} canceled The flag to prevent default. + * @property {boolean} stopped The flag to stop propagation. + * @property {boolean} immediateStopped The flag to stop propagation immediately. + * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null. + * @property {number} timeStamp The unix time. + * @private + */ + +/** + * Private data for event wrappers. + * @type {WeakMap} + * @private + */ +const privateData = new WeakMap(); + +/** + * Cache for wrapper classes. + * @type {WeakMap} + * @private + */ +const wrappers = new WeakMap(); + +/** + * Get private data. + * @param {Event} event The event object to get private data. + * @returns {PrivateData} The private data of the event. + * @private + */ +function pd(event) { + const retv = privateData.get(event); + console.assert( + retv != null, + "'this' is expected an Event object, but got", + event + ); + return retv +} + +/** + * https://dom.spec.whatwg.org/#set-the-canceled-flag + * @param data {PrivateData} private data. + */ +function setCancelFlag(data) { + if (data.passiveListener != null) { + if ( + typeof console !== "undefined" && + typeof console.error === "function" + ) { + console.error( + "Unable to preventDefault inside passive event listener invocation.", + data.passiveListener + ); + } + return + } + if (!data.event.cancelable) { + return + } + + data.canceled = true; + if (typeof data.event.preventDefault === "function") { + data.event.preventDefault(); + } +} + +/** + * @see https://dom.spec.whatwg.org/#interface-event + * @private + */ +/** + * The event wrapper. + * @constructor + * @param {EventTarget} eventTarget The event target of this dispatching. + * @param {Event|{type:string}} event The original event to wrap. + */ +function Event(eventTarget, event) { + privateData.set(this, { + eventTarget, + event, + eventPhase: 2, + currentTarget: eventTarget, + canceled: false, + stopped: false, + immediateStopped: false, + passiveListener: null, + timeStamp: event.timeStamp || Date.now(), + }); + + // https://heycam.github.io/webidl/#Unforgeable + Object.defineProperty(this, "isTrusted", { value: false, enumerable: true }); + + // Define accessors + const keys = Object.keys(event); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (!(key in this)) { + Object.defineProperty(this, key, defineRedirectDescriptor(key)); + } + } +} + +// Should be enumerable, but class methods are not enumerable. +Event.prototype = { + /** + * The type of this event. + * @type {string} + */ + get type() { + return pd(this).event.type + }, + + /** + * The target of this event. + * @type {EventTarget} + */ + get target() { + return pd(this).eventTarget + }, + + /** + * The target of this event. + * @type {EventTarget} + */ + get currentTarget() { + return pd(this).currentTarget + }, + + /** + * @returns {EventTarget[]} The composed path of this event. + */ + composedPath() { + const currentTarget = pd(this).currentTarget; + if (currentTarget == null) { + return [] + } + return [currentTarget] + }, + + /** + * Constant of NONE. + * @type {number} + */ + get NONE() { + return 0 + }, + + /** + * Constant of CAPTURING_PHASE. + * @type {number} + */ + get CAPTURING_PHASE() { + return 1 + }, + + /** + * Constant of AT_TARGET. + * @type {number} + */ + get AT_TARGET() { + return 2 + }, + + /** + * Constant of BUBBLING_PHASE. + * @type {number} + */ + get BUBBLING_PHASE() { + return 3 + }, + + /** + * The target of this event. + * @type {number} + */ + get eventPhase() { + return pd(this).eventPhase + }, + + /** + * Stop event bubbling. + * @returns {void} + */ + stopPropagation() { + const data = pd(this); + + data.stopped = true; + if (typeof data.event.stopPropagation === "function") { + data.event.stopPropagation(); + } + }, + + /** + * Stop event bubbling. + * @returns {void} + */ + stopImmediatePropagation() { + const data = pd(this); + + data.stopped = true; + data.immediateStopped = true; + if (typeof data.event.stopImmediatePropagation === "function") { + data.event.stopImmediatePropagation(); + } + }, + + /** + * The flag to be bubbling. + * @type {boolean} + */ + get bubbles() { + return Boolean(pd(this).event.bubbles) + }, + + /** + * The flag to be cancelable. + * @type {boolean} + */ + get cancelable() { + return Boolean(pd(this).event.cancelable) + }, + + /** + * Cancel this event. + * @returns {void} + */ + preventDefault() { + setCancelFlag(pd(this)); + }, + + /** + * The flag to indicate cancellation state. + * @type {boolean} + */ + get defaultPrevented() { + return pd(this).canceled + }, + + /** + * The flag to be composed. + * @type {boolean} + */ + get composed() { + return Boolean(pd(this).event.composed) + }, + + /** + * The unix time of this event. + * @type {number} + */ + get timeStamp() { + return pd(this).timeStamp + }, + + /** + * The target of this event. + * @type {EventTarget} + * @deprecated + */ + get srcElement() { + return pd(this).eventTarget + }, + + /** + * The flag to stop event bubbling. + * @type {boolean} + * @deprecated + */ + get cancelBubble() { + return pd(this).stopped + }, + set cancelBubble(value) { + if (!value) { + return + } + const data = pd(this); + + data.stopped = true; + if (typeof data.event.cancelBubble === "boolean") { + data.event.cancelBubble = true; + } + }, + + /** + * The flag to indicate cancellation state. + * @type {boolean} + * @deprecated + */ + get returnValue() { + return !pd(this).canceled + }, + set returnValue(value) { + if (!value) { + setCancelFlag(pd(this)); + } + }, + + /** + * Initialize this event object. But do nothing under event dispatching. + * @param {string} type The event type. + * @param {boolean} [bubbles=false] The flag to be possible to bubble up. + * @param {boolean} [cancelable=false] The flag to be possible to cancel. + * @deprecated + */ + initEvent() { + // Do nothing. + }, +}; + +// `constructor` is not enumerable. +Object.defineProperty(Event.prototype, "constructor", { + value: Event, + configurable: true, + writable: true, +}); + +// Ensure `event instanceof window.Event` is `true`. +if (typeof window !== "undefined" && typeof window.Event !== "undefined") { + Object.setPrototypeOf(Event.prototype, window.Event.prototype); + + // Make association for wrappers. + wrappers.set(window.Event.prototype, Event); +} + +/** + * Get the property descriptor to redirect a given property. + * @param {string} key Property name to define property descriptor. + * @returns {PropertyDescriptor} The property descriptor to redirect the property. + * @private + */ +function defineRedirectDescriptor(key) { + return { + get() { + return pd(this).event[key] + }, + set(value) { + pd(this).event[key] = value; + }, + configurable: true, + enumerable: true, + } +} + +/** + * Get the property descriptor to call a given method property. + * @param {string} key Property name to define property descriptor. + * @returns {PropertyDescriptor} The property descriptor to call the method property. + * @private + */ +function defineCallDescriptor(key) { + return { + value() { + const event = pd(this).event; + return event[key].apply(event, arguments) + }, + configurable: true, + enumerable: true, + } +} + +/** + * Define new wrapper class. + * @param {Function} BaseEvent The base wrapper class. + * @param {Object} proto The prototype of the original event. + * @returns {Function} The defined wrapper class. + * @private + */ +function defineWrapper(BaseEvent, proto) { + const keys = Object.keys(proto); + if (keys.length === 0) { + return BaseEvent + } + + /** CustomEvent */ + function CustomEvent(eventTarget, event) { + BaseEvent.call(this, eventTarget, event); + } + + CustomEvent.prototype = Object.create(BaseEvent.prototype, { + constructor: { value: CustomEvent, configurable: true, writable: true }, + }); + + // Define accessors. + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (!(key in BaseEvent.prototype)) { + const descriptor = Object.getOwnPropertyDescriptor(proto, key); + const isFunc = typeof descriptor.value === "function"; + Object.defineProperty( + CustomEvent.prototype, + key, + isFunc + ? defineCallDescriptor(key) + : defineRedirectDescriptor(key) + ); + } + } + + return CustomEvent +} + +/** + * Get the wrapper class of a given prototype. + * @param {Object} proto The prototype of the original event to get its wrapper. + * @returns {Function} The wrapper class. + * @private + */ +function getWrapper(proto) { + if (proto == null || proto === Object.prototype) { + return Event + } + + let wrapper = wrappers.get(proto); + if (wrapper == null) { + wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto); + wrappers.set(proto, wrapper); + } + return wrapper +} + +/** + * Wrap a given event to management a dispatching. + * @param {EventTarget} eventTarget The event target of this dispatching. + * @param {Object} event The event to wrap. + * @returns {Event} The wrapper instance. + * @private + */ +function wrapEvent(eventTarget, event) { + const Wrapper = getWrapper(Object.getPrototypeOf(event)); + return new Wrapper(eventTarget, event) +} + +/** + * Get the immediateStopped flag of a given event. + * @param {Event} event The event to get. + * @returns {boolean} The flag to stop propagation immediately. + * @private + */ +function isStopped(event) { + return pd(event).immediateStopped +} + +/** + * Set the current event phase of a given event. + * @param {Event} event The event to set current target. + * @param {number} eventPhase New event phase. + * @returns {void} + * @private + */ +function setEventPhase(event, eventPhase) { + pd(event).eventPhase = eventPhase; +} + +/** + * Set the current target of a given event. + * @param {Event} event The event to set current target. + * @param {EventTarget|null} currentTarget New current target. + * @returns {void} + * @private + */ +function setCurrentTarget(event, currentTarget) { + pd(event).currentTarget = currentTarget; +} + +/** + * Set a passive listener of a given event. + * @param {Event} event The event to set current target. + * @param {Function|null} passiveListener New passive listener. + * @returns {void} + * @private + */ +function setPassiveListener(event, passiveListener) { + pd(event).passiveListener = passiveListener; +} + +/** + * @typedef {object} ListenerNode + * @property {Function} listener + * @property {1|2|3} listenerType + * @property {boolean} passive + * @property {boolean} once + * @property {ListenerNode|null} next + * @private + */ + +/** + * @type {WeakMap>} + * @private + */ +const listenersMap = new WeakMap(); + +// Listener types +const CAPTURE = 1; +const BUBBLE = 2; +const ATTRIBUTE = 3; + +/** + * Check whether a given value is an object or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if the value is an object. + */ +function isObject(x) { + return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax +} + +/** + * Get listeners. + * @param {EventTarget} eventTarget The event target to get. + * @returns {Map} The listeners. + * @private + */ +function getListeners(eventTarget) { + const listeners = listenersMap.get(eventTarget); + if (listeners == null) { + throw new TypeError( + "'this' is expected an EventTarget object, but got another value." + ) + } + return listeners +} + +/** + * Get the property descriptor for the event attribute of a given event. + * @param {string} eventName The event name to get property descriptor. + * @returns {PropertyDescriptor} The property descriptor. + * @private + */ +function defineEventAttributeDescriptor(eventName) { + return { + get() { + const listeners = getListeners(this); + let node = listeners.get(eventName); + while (node != null) { + if (node.listenerType === ATTRIBUTE) { + return node.listener + } + node = node.next; + } + return null + }, + + set(listener) { + if (typeof listener !== "function" && !isObject(listener)) { + listener = null; // eslint-disable-line no-param-reassign + } + const listeners = getListeners(this); + + // Traverse to the tail while removing old value. + let prev = null; + let node = listeners.get(eventName); + while (node != null) { + if (node.listenerType === ATTRIBUTE) { + // Remove old value. + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + } else { + prev = node; + } + + node = node.next; + } + + // Add new value. + if (listener !== null) { + const newNode = { + listener, + listenerType: ATTRIBUTE, + passive: false, + once: false, + next: null, + }; + if (prev === null) { + listeners.set(eventName, newNode); + } else { + prev.next = newNode; + } + } + }, + configurable: true, + enumerable: true, + } +} + +/** + * Define an event attribute (e.g. `eventTarget.onclick`). + * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite. + * @param {string} eventName The event name to define. + * @returns {void} + */ +function defineEventAttribute(eventTargetPrototype, eventName) { + Object.defineProperty( + eventTargetPrototype, + `on${eventName}`, + defineEventAttributeDescriptor(eventName) + ); +} + +/** + * Define a custom EventTarget with event attributes. + * @param {string[]} eventNames Event names for event attributes. + * @returns {EventTarget} The custom EventTarget. + * @private + */ +function defineCustomEventTarget(eventNames) { + /** CustomEventTarget */ + function CustomEventTarget() { + EventTarget.call(this); + } + + CustomEventTarget.prototype = Object.create(EventTarget.prototype, { + constructor: { + value: CustomEventTarget, + configurable: true, + writable: true, + }, + }); + + for (let i = 0; i < eventNames.length; ++i) { + defineEventAttribute(CustomEventTarget.prototype, eventNames[i]); + } + + return CustomEventTarget +} + +/** + * EventTarget. + * + * - This is constructor if no arguments. + * - This is a function which returns a CustomEventTarget constructor if there are arguments. + * + * For example: + * + * class A extends EventTarget {} + * class B extends EventTarget("message") {} + * class C extends EventTarget("message", "error") {} + * class D extends EventTarget(["message", "error"]) {} + */ +function EventTarget() { + /*eslint-disable consistent-return */ + if (this instanceof EventTarget) { + listenersMap.set(this, new Map()); + return + } + if (arguments.length === 1 && Array.isArray(arguments[0])) { + return defineCustomEventTarget(arguments[0]) + } + if (arguments.length > 0) { + const types = new Array(arguments.length); + for (let i = 0; i < arguments.length; ++i) { + types[i] = arguments[i]; + } + return defineCustomEventTarget(types) + } + throw new TypeError("Cannot call a class as a function") + /*eslint-enable consistent-return */ +} + +// Should be enumerable, but class methods are not enumerable. +EventTarget.prototype = { + /** + * Add a given listener to this event target. + * @param {string} eventName The event name to add. + * @param {Function} listener The listener to add. + * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. + * @returns {void} + */ + addEventListener(eventName, listener, options) { + if (listener == null) { + return + } + if (typeof listener !== "function" && !isObject(listener)) { + throw new TypeError("'listener' should be a function or an object.") + } + + const listeners = getListeners(this); + const optionsIsObj = isObject(options); + const capture = optionsIsObj + ? Boolean(options.capture) + : Boolean(options); + const listenerType = capture ? CAPTURE : BUBBLE; + const newNode = { + listener, + listenerType, + passive: optionsIsObj && Boolean(options.passive), + once: optionsIsObj && Boolean(options.once), + next: null, + }; + + // Set it as the first node if the first node is null. + let node = listeners.get(eventName); + if (node === undefined) { + listeners.set(eventName, newNode); + return + } + + // Traverse to the tail while checking duplication.. + let prev = null; + while (node != null) { + if ( + node.listener === listener && + node.listenerType === listenerType + ) { + // Should ignore duplication. + return + } + prev = node; + node = node.next; + } + + // Add it. + prev.next = newNode; + }, + + /** + * Remove a given listener from this event target. + * @param {string} eventName The event name to remove. + * @param {Function} listener The listener to remove. + * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. + * @returns {void} + */ + removeEventListener(eventName, listener, options) { + if (listener == null) { + return + } + + const listeners = getListeners(this); + const capture = isObject(options) + ? Boolean(options.capture) + : Boolean(options); + const listenerType = capture ? CAPTURE : BUBBLE; + + let prev = null; + let node = listeners.get(eventName); + while (node != null) { + if ( + node.listener === listener && + node.listenerType === listenerType + ) { + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + return + } + + prev = node; + node = node.next; + } + }, + + /** + * Dispatch a given event. + * @param {Event|{type:string}} event The event to dispatch. + * @returns {boolean} `false` if canceled. + */ + dispatchEvent(event) { + if (event == null || typeof event.type !== "string") { + throw new TypeError('"event.type" should be a string.') + } + + // If listeners aren't registered, terminate. + const listeners = getListeners(this); + const eventName = event.type; + let node = listeners.get(eventName); + if (node == null) { + return true + } + + // Since we cannot rewrite several properties, so wrap object. + const wrappedEvent = wrapEvent(this, event); + + // This doesn't process capturing phase and bubbling phase. + // This isn't participating in a tree. + let prev = null; + while (node != null) { + // Remove this listener if it's once + if (node.once) { + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + } else { + prev = node; + } + + // Call this listener + setPassiveListener( + wrappedEvent, + node.passive ? node.listener : null + ); + if (typeof node.listener === "function") { + try { + node.listener.call(this, wrappedEvent); + } catch (err) { + if ( + typeof console !== "undefined" && + typeof console.error === "function" + ) { + console.error(err); + } + } + } else if ( + node.listenerType !== ATTRIBUTE && + typeof node.listener.handleEvent === "function" + ) { + node.listener.handleEvent(wrappedEvent); + } + + // Break if `event.stopImmediatePropagation` was called. + if (isStopped(wrappedEvent)) { + break + } + + node = node.next; + } + setPassiveListener(wrappedEvent, null); + setEventPhase(wrappedEvent, 0); + setCurrentTarget(wrappedEvent, null); + + return !wrappedEvent.defaultPrevented + }, +}; + +// `constructor` is not enumerable. +Object.defineProperty(EventTarget.prototype, "constructor", { + value: EventTarget, + configurable: true, + writable: true, +}); + +// Ensure `eventTarget instanceof window.EventTarget` is `true`. +if ( + typeof window !== "undefined" && + typeof window.EventTarget !== "undefined" +) { + Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype); +} + +exports.defineEventAttribute = defineEventAttribute; +exports.EventTarget = EventTarget; +exports.default = EventTarget; + +module.exports = EventTarget +module.exports.EventTarget = module.exports["default"] = EventTarget +module.exports.defineEventAttribute = defineEventAttribute +//# sourceMappingURL=event-target-shim.js.map diff --git a/node_modules/event-target-shim/dist/event-target-shim.js.map b/node_modules/event-target-shim/dist/event-target-shim.js.map new file mode 100644 index 0000000..83c5f62 --- /dev/null +++ b/node_modules/event-target-shim/dist/event-target-shim.js.map @@ -0,0 +1 @@ +{"version":3,"file":"event-target-shim.js","sources":["../src/event.mjs","../src/event-target.mjs"],"sourcesContent":["/**\n * @typedef {object} PrivateData\n * @property {EventTarget} eventTarget The event target.\n * @property {{type:string}} event The original event object.\n * @property {number} eventPhase The current event phase.\n * @property {EventTarget|null} currentTarget The current event target.\n * @property {boolean} canceled The flag to prevent default.\n * @property {boolean} stopped The flag to stop propagation.\n * @property {boolean} immediateStopped The flag to stop propagation immediately.\n * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null.\n * @property {number} timeStamp The unix time.\n * @private\n */\n\n/**\n * Private data for event wrappers.\n * @type {WeakMap}\n * @private\n */\nconst privateData = new WeakMap()\n\n/**\n * Cache for wrapper classes.\n * @type {WeakMap}\n * @private\n */\nconst wrappers = new WeakMap()\n\n/**\n * Get private data.\n * @param {Event} event The event object to get private data.\n * @returns {PrivateData} The private data of the event.\n * @private\n */\nfunction pd(event) {\n const retv = privateData.get(event)\n console.assert(\n retv != null,\n \"'this' is expected an Event object, but got\",\n event\n )\n return retv\n}\n\n/**\n * https://dom.spec.whatwg.org/#set-the-canceled-flag\n * @param data {PrivateData} private data.\n */\nfunction setCancelFlag(data) {\n if (data.passiveListener != null) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(\n \"Unable to preventDefault inside passive event listener invocation.\",\n data.passiveListener\n )\n }\n return\n }\n if (!data.event.cancelable) {\n return\n }\n\n data.canceled = true\n if (typeof data.event.preventDefault === \"function\") {\n data.event.preventDefault()\n }\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#interface-event\n * @private\n */\n/**\n * The event wrapper.\n * @constructor\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Event|{type:string}} event The original event to wrap.\n */\nfunction Event(eventTarget, event) {\n privateData.set(this, {\n eventTarget,\n event,\n eventPhase: 2,\n currentTarget: eventTarget,\n canceled: false,\n stopped: false,\n immediateStopped: false,\n passiveListener: null,\n timeStamp: event.timeStamp || Date.now(),\n })\n\n // https://heycam.github.io/webidl/#Unforgeable\n Object.defineProperty(this, \"isTrusted\", { value: false, enumerable: true })\n\n // Define accessors\n const keys = Object.keys(event)\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in this)) {\n Object.defineProperty(this, key, defineRedirectDescriptor(key))\n }\n }\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEvent.prototype = {\n /**\n * The type of this event.\n * @type {string}\n */\n get type() {\n return pd(this).event.type\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get target() {\n return pd(this).eventTarget\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get currentTarget() {\n return pd(this).currentTarget\n },\n\n /**\n * @returns {EventTarget[]} The composed path of this event.\n */\n composedPath() {\n const currentTarget = pd(this).currentTarget\n if (currentTarget == null) {\n return []\n }\n return [currentTarget]\n },\n\n /**\n * Constant of NONE.\n * @type {number}\n */\n get NONE() {\n return 0\n },\n\n /**\n * Constant of CAPTURING_PHASE.\n * @type {number}\n */\n get CAPTURING_PHASE() {\n return 1\n },\n\n /**\n * Constant of AT_TARGET.\n * @type {number}\n */\n get AT_TARGET() {\n return 2\n },\n\n /**\n * Constant of BUBBLING_PHASE.\n * @type {number}\n */\n get BUBBLING_PHASE() {\n return 3\n },\n\n /**\n * The target of this event.\n * @type {number}\n */\n get eventPhase() {\n return pd(this).eventPhase\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopPropagation() {\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.stopPropagation === \"function\") {\n data.event.stopPropagation()\n }\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopImmediatePropagation() {\n const data = pd(this)\n\n data.stopped = true\n data.immediateStopped = true\n if (typeof data.event.stopImmediatePropagation === \"function\") {\n data.event.stopImmediatePropagation()\n }\n },\n\n /**\n * The flag to be bubbling.\n * @type {boolean}\n */\n get bubbles() {\n return Boolean(pd(this).event.bubbles)\n },\n\n /**\n * The flag to be cancelable.\n * @type {boolean}\n */\n get cancelable() {\n return Boolean(pd(this).event.cancelable)\n },\n\n /**\n * Cancel this event.\n * @returns {void}\n */\n preventDefault() {\n setCancelFlag(pd(this))\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n */\n get defaultPrevented() {\n return pd(this).canceled\n },\n\n /**\n * The flag to be composed.\n * @type {boolean}\n */\n get composed() {\n return Boolean(pd(this).event.composed)\n },\n\n /**\n * The unix time of this event.\n * @type {number}\n */\n get timeStamp() {\n return pd(this).timeStamp\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n * @deprecated\n */\n get srcElement() {\n return pd(this).eventTarget\n },\n\n /**\n * The flag to stop event bubbling.\n * @type {boolean}\n * @deprecated\n */\n get cancelBubble() {\n return pd(this).stopped\n },\n set cancelBubble(value) {\n if (!value) {\n return\n }\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.cancelBubble === \"boolean\") {\n data.event.cancelBubble = true\n }\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n * @deprecated\n */\n get returnValue() {\n return !pd(this).canceled\n },\n set returnValue(value) {\n if (!value) {\n setCancelFlag(pd(this))\n }\n },\n\n /**\n * Initialize this event object. But do nothing under event dispatching.\n * @param {string} type The event type.\n * @param {boolean} [bubbles=false] The flag to be possible to bubble up.\n * @param {boolean} [cancelable=false] The flag to be possible to cancel.\n * @deprecated\n */\n initEvent() {\n // Do nothing.\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(Event.prototype, \"constructor\", {\n value: Event,\n configurable: true,\n writable: true,\n})\n\n// Ensure `event instanceof window.Event` is `true`.\nif (typeof window !== \"undefined\" && typeof window.Event !== \"undefined\") {\n Object.setPrototypeOf(Event.prototype, window.Event.prototype)\n\n // Make association for wrappers.\n wrappers.set(window.Event.prototype, Event)\n}\n\n/**\n * Get the property descriptor to redirect a given property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to redirect the property.\n * @private\n */\nfunction defineRedirectDescriptor(key) {\n return {\n get() {\n return pd(this).event[key]\n },\n set(value) {\n pd(this).event[key] = value\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Get the property descriptor to call a given method property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to call the method property.\n * @private\n */\nfunction defineCallDescriptor(key) {\n return {\n value() {\n const event = pd(this).event\n return event[key].apply(event, arguments)\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define new wrapper class.\n * @param {Function} BaseEvent The base wrapper class.\n * @param {Object} proto The prototype of the original event.\n * @returns {Function} The defined wrapper class.\n * @private\n */\nfunction defineWrapper(BaseEvent, proto) {\n const keys = Object.keys(proto)\n if (keys.length === 0) {\n return BaseEvent\n }\n\n /** CustomEvent */\n function CustomEvent(eventTarget, event) {\n BaseEvent.call(this, eventTarget, event)\n }\n\n CustomEvent.prototype = Object.create(BaseEvent.prototype, {\n constructor: { value: CustomEvent, configurable: true, writable: true },\n })\n\n // Define accessors.\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in BaseEvent.prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, key)\n const isFunc = typeof descriptor.value === \"function\"\n Object.defineProperty(\n CustomEvent.prototype,\n key,\n isFunc\n ? defineCallDescriptor(key)\n : defineRedirectDescriptor(key)\n )\n }\n }\n\n return CustomEvent\n}\n\n/**\n * Get the wrapper class of a given prototype.\n * @param {Object} proto The prototype of the original event to get its wrapper.\n * @returns {Function} The wrapper class.\n * @private\n */\nfunction getWrapper(proto) {\n if (proto == null || proto === Object.prototype) {\n return Event\n }\n\n let wrapper = wrappers.get(proto)\n if (wrapper == null) {\n wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto)\n wrappers.set(proto, wrapper)\n }\n return wrapper\n}\n\n/**\n * Wrap a given event to management a dispatching.\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Object} event The event to wrap.\n * @returns {Event} The wrapper instance.\n * @private\n */\nexport function wrapEvent(eventTarget, event) {\n const Wrapper = getWrapper(Object.getPrototypeOf(event))\n return new Wrapper(eventTarget, event)\n}\n\n/**\n * Get the immediateStopped flag of a given event.\n * @param {Event} event The event to get.\n * @returns {boolean} The flag to stop propagation immediately.\n * @private\n */\nexport function isStopped(event) {\n return pd(event).immediateStopped\n}\n\n/**\n * Set the current event phase of a given event.\n * @param {Event} event The event to set current target.\n * @param {number} eventPhase New event phase.\n * @returns {void}\n * @private\n */\nexport function setEventPhase(event, eventPhase) {\n pd(event).eventPhase = eventPhase\n}\n\n/**\n * Set the current target of a given event.\n * @param {Event} event The event to set current target.\n * @param {EventTarget|null} currentTarget New current target.\n * @returns {void}\n * @private\n */\nexport function setCurrentTarget(event, currentTarget) {\n pd(event).currentTarget = currentTarget\n}\n\n/**\n * Set a passive listener of a given event.\n * @param {Event} event The event to set current target.\n * @param {Function|null} passiveListener New passive listener.\n * @returns {void}\n * @private\n */\nexport function setPassiveListener(event, passiveListener) {\n pd(event).passiveListener = passiveListener\n}\n","import {\n isStopped,\n setCurrentTarget,\n setEventPhase,\n setPassiveListener,\n wrapEvent,\n} from \"./event.mjs\"\n\n/**\n * @typedef {object} ListenerNode\n * @property {Function} listener\n * @property {1|2|3} listenerType\n * @property {boolean} passive\n * @property {boolean} once\n * @property {ListenerNode|null} next\n * @private\n */\n\n/**\n * @type {WeakMap>}\n * @private\n */\nconst listenersMap = new WeakMap()\n\n// Listener types\nconst CAPTURE = 1\nconst BUBBLE = 2\nconst ATTRIBUTE = 3\n\n/**\n * Check whether a given value is an object or not.\n * @param {any} x The value to check.\n * @returns {boolean} `true` if the value is an object.\n */\nfunction isObject(x) {\n return x !== null && typeof x === \"object\" //eslint-disable-line no-restricted-syntax\n}\n\n/**\n * Get listeners.\n * @param {EventTarget} eventTarget The event target to get.\n * @returns {Map} The listeners.\n * @private\n */\nfunction getListeners(eventTarget) {\n const listeners = listenersMap.get(eventTarget)\n if (listeners == null) {\n throw new TypeError(\n \"'this' is expected an EventTarget object, but got another value.\"\n )\n }\n return listeners\n}\n\n/**\n * Get the property descriptor for the event attribute of a given event.\n * @param {string} eventName The event name to get property descriptor.\n * @returns {PropertyDescriptor} The property descriptor.\n * @private\n */\nfunction defineEventAttributeDescriptor(eventName) {\n return {\n get() {\n const listeners = getListeners(this)\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n return node.listener\n }\n node = node.next\n }\n return null\n },\n\n set(listener) {\n if (typeof listener !== \"function\" && !isObject(listener)) {\n listener = null // eslint-disable-line no-param-reassign\n }\n const listeners = getListeners(this)\n\n // Traverse to the tail while removing old value.\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n // Remove old value.\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n node = node.next\n }\n\n // Add new value.\n if (listener !== null) {\n const newNode = {\n listener,\n listenerType: ATTRIBUTE,\n passive: false,\n once: false,\n next: null,\n }\n if (prev === null) {\n listeners.set(eventName, newNode)\n } else {\n prev.next = newNode\n }\n }\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define an event attribute (e.g. `eventTarget.onclick`).\n * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.\n * @param {string} eventName The event name to define.\n * @returns {void}\n */\nfunction defineEventAttribute(eventTargetPrototype, eventName) {\n Object.defineProperty(\n eventTargetPrototype,\n `on${eventName}`,\n defineEventAttributeDescriptor(eventName)\n )\n}\n\n/**\n * Define a custom EventTarget with event attributes.\n * @param {string[]} eventNames Event names for event attributes.\n * @returns {EventTarget} The custom EventTarget.\n * @private\n */\nfunction defineCustomEventTarget(eventNames) {\n /** CustomEventTarget */\n function CustomEventTarget() {\n EventTarget.call(this)\n }\n\n CustomEventTarget.prototype = Object.create(EventTarget.prototype, {\n constructor: {\n value: CustomEventTarget,\n configurable: true,\n writable: true,\n },\n })\n\n for (let i = 0; i < eventNames.length; ++i) {\n defineEventAttribute(CustomEventTarget.prototype, eventNames[i])\n }\n\n return CustomEventTarget\n}\n\n/**\n * EventTarget.\n *\n * - This is constructor if no arguments.\n * - This is a function which returns a CustomEventTarget constructor if there are arguments.\n *\n * For example:\n *\n * class A extends EventTarget {}\n * class B extends EventTarget(\"message\") {}\n * class C extends EventTarget(\"message\", \"error\") {}\n * class D extends EventTarget([\"message\", \"error\"]) {}\n */\nfunction EventTarget() {\n /*eslint-disable consistent-return */\n if (this instanceof EventTarget) {\n listenersMap.set(this, new Map())\n return\n }\n if (arguments.length === 1 && Array.isArray(arguments[0])) {\n return defineCustomEventTarget(arguments[0])\n }\n if (arguments.length > 0) {\n const types = new Array(arguments.length)\n for (let i = 0; i < arguments.length; ++i) {\n types[i] = arguments[i]\n }\n return defineCustomEventTarget(types)\n }\n throw new TypeError(\"Cannot call a class as a function\")\n /*eslint-enable consistent-return */\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEventTarget.prototype = {\n /**\n * Add a given listener to this event target.\n * @param {string} eventName The event name to add.\n * @param {Function} listener The listener to add.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n addEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n if (typeof listener !== \"function\" && !isObject(listener)) {\n throw new TypeError(\"'listener' should be a function or an object.\")\n }\n\n const listeners = getListeners(this)\n const optionsIsObj = isObject(options)\n const capture = optionsIsObj\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n const newNode = {\n listener,\n listenerType,\n passive: optionsIsObj && Boolean(options.passive),\n once: optionsIsObj && Boolean(options.once),\n next: null,\n }\n\n // Set it as the first node if the first node is null.\n let node = listeners.get(eventName)\n if (node === undefined) {\n listeners.set(eventName, newNode)\n return\n }\n\n // Traverse to the tail while checking duplication..\n let prev = null\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n // Should ignore duplication.\n return\n }\n prev = node\n node = node.next\n }\n\n // Add it.\n prev.next = newNode\n },\n\n /**\n * Remove a given listener from this event target.\n * @param {string} eventName The event name to remove.\n * @param {Function} listener The listener to remove.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n removeEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n\n const listeners = getListeners(this)\n const capture = isObject(options)\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n return\n }\n\n prev = node\n node = node.next\n }\n },\n\n /**\n * Dispatch a given event.\n * @param {Event|{type:string}} event The event to dispatch.\n * @returns {boolean} `false` if canceled.\n */\n dispatchEvent(event) {\n if (event == null || typeof event.type !== \"string\") {\n throw new TypeError('\"event.type\" should be a string.')\n }\n\n // If listeners aren't registered, terminate.\n const listeners = getListeners(this)\n const eventName = event.type\n let node = listeners.get(eventName)\n if (node == null) {\n return true\n }\n\n // Since we cannot rewrite several properties, so wrap object.\n const wrappedEvent = wrapEvent(this, event)\n\n // This doesn't process capturing phase and bubbling phase.\n // This isn't participating in a tree.\n let prev = null\n while (node != null) {\n // Remove this listener if it's once\n if (node.once) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n // Call this listener\n setPassiveListener(\n wrappedEvent,\n node.passive ? node.listener : null\n )\n if (typeof node.listener === \"function\") {\n try {\n node.listener.call(this, wrappedEvent)\n } catch (err) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(err)\n }\n }\n } else if (\n node.listenerType !== ATTRIBUTE &&\n typeof node.listener.handleEvent === \"function\"\n ) {\n node.listener.handleEvent(wrappedEvent)\n }\n\n // Break if `event.stopImmediatePropagation` was called.\n if (isStopped(wrappedEvent)) {\n break\n }\n\n node = node.next\n }\n setPassiveListener(wrappedEvent, null)\n setEventPhase(wrappedEvent, 0)\n setCurrentTarget(wrappedEvent, null)\n\n return !wrappedEvent.defaultPrevented\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(EventTarget.prototype, \"constructor\", {\n value: EventTarget,\n configurable: true,\n writable: true,\n})\n\n// Ensure `eventTarget instanceof window.EventTarget` is `true`.\nif (\n typeof window !== \"undefined\" &&\n typeof window.EventTarget !== \"undefined\"\n) {\n Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype)\n}\n\nexport { defineEventAttribute, EventTarget }\nexport default EventTarget\n"],"names":[],"mappings":";;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;AAmBA,MAAM,WAAW,GAAG,IAAI,OAAO,GAAE;;;;;;;AAOjC,MAAM,QAAQ,GAAG,IAAI,OAAO,GAAE;;;;;;;;AAQ9B,SAAS,EAAE,CAAC,KAAK,EAAE;IACf,MAAM,IAAI,GAAG,WAAW,CAAC,GAAG,CAAC,KAAK,EAAC;IACnC,OAAO,CAAC,MAAM;QACV,IAAI,IAAI,IAAI;QACZ,6CAA6C;QAC7C,KAAK;MACR;IACD,OAAO,IAAI;CACd;;;;;;AAMD,SAAS,aAAa,CAAC,IAAI,EAAE;IACzB,IAAI,IAAI,CAAC,eAAe,IAAI,IAAI,EAAE;QAC9B;YACI,OAAO,OAAO,KAAK,WAAW;YAC9B,OAAO,OAAO,CAAC,KAAK,KAAK,UAAU;UACrC;YACE,OAAO,CAAC,KAAK;gBACT,oEAAoE;gBACpE,IAAI,CAAC,eAAe;cACvB;SACJ;QACD,MAAM;KACT;IACD,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,UAA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CAAC,GAAG,EAAC;qBACrB;iBACJ;aACJ,MAAM;gBACH,IAAI,CAAC,YAAY,KAAK,SAAS;gBAC/B,OAAO,IAAI,CAAC,QAAQ,CAAC,WAAW,KAAK,UAAU;cACjD;gBACE,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC,YAAY,EAAC;aAC1C;;;YAGD,IAAI,SAAS,CAAC,YAAY,CAAC,EAAE;gBACzB,KAAK;aACR;;YAED,IAAI,GAAG,IAAI,CAAC,KAAI;SACnB;QACD,kBAAkB,CAAC,YAAY,EAAE,IAAI,EAAC;QACtC,aAAa,CAAC,YAAY,EAAE,CAAC,EAAC;QAC9B,gBAAgB,CAAC,YAAY,EAAE,IAAI,EAAC;;QAEpC,OAAO,CAAC,YAAY,CAAC,gBAAgB;KACxC;EACJ;;;AAGD,MAAM,CAAC,cAAc,CAAC,WAAW,CAAC,SAAS,EAAE,aAAa,EAAE;IACxD,KAAK,EAAE,WAAW;IAClB,YAAY,EAAE,IAAI;IAClB,QAAQ,EAAE,IAAI;CACjB,EAAC;;;AAGF;IACI,OAAO,MAAM,KAAK,WAAW;IAC7B,OAAO,MAAM,CAAC,WAAW,KAAK,WAAW;EAC3C;IACE,MAAM,CAAC,cAAc,CAAC,WAAW,CAAC,SAAS,EAAE,MAAM,CAAC,WAAW,CAAC,SAAS,EAAC;CAC7E;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/event-target-shim/dist/event-target-shim.mjs b/node_modules/event-target-shim/dist/event-target-shim.mjs new file mode 100644 index 0000000..114f3a1 --- /dev/null +++ b/node_modules/event-target-shim/dist/event-target-shim.mjs @@ -0,0 +1,862 @@ +/** + * @author Toru Nagashima + * @copyright 2015 Toru Nagashima. All rights reserved. + * See LICENSE file in root directory for full license. + */ +/** + * @typedef {object} PrivateData + * @property {EventTarget} eventTarget The event target. + * @property {{type:string}} event The original event object. + * @property {number} eventPhase The current event phase. + * @property {EventTarget|null} currentTarget The current event target. + * @property {boolean} canceled The flag to prevent default. + * @property {boolean} stopped The flag to stop propagation. + * @property {boolean} immediateStopped The flag to stop propagation immediately. + * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null. + * @property {number} timeStamp The unix time. + * @private + */ + +/** + * Private data for event wrappers. + * @type {WeakMap} + * @private + */ +const privateData = new WeakMap(); + +/** + * Cache for wrapper classes. + * @type {WeakMap} + * @private + */ +const wrappers = new WeakMap(); + +/** + * Get private data. + * @param {Event} event The event object to get private data. + * @returns {PrivateData} The private data of the event. + * @private + */ +function pd(event) { + const retv = privateData.get(event); + console.assert( + retv != null, + "'this' is expected an Event object, but got", + event + ); + return retv +} + +/** + * https://dom.spec.whatwg.org/#set-the-canceled-flag + * @param data {PrivateData} private data. + */ +function setCancelFlag(data) { + if (data.passiveListener != null) { + if ( + typeof console !== "undefined" && + typeof console.error === "function" + ) { + console.error( + "Unable to preventDefault inside passive event listener invocation.", + data.passiveListener + ); + } + return + } + if (!data.event.cancelable) { + return + } + + data.canceled = true; + if (typeof data.event.preventDefault === "function") { + data.event.preventDefault(); + } +} + +/** + * @see https://dom.spec.whatwg.org/#interface-event + * @private + */ +/** + * The event wrapper. + * @constructor + * @param {EventTarget} eventTarget The event target of this dispatching. + * @param {Event|{type:string}} event The original event to wrap. + */ +function Event(eventTarget, event) { + privateData.set(this, { + eventTarget, + event, + eventPhase: 2, + currentTarget: eventTarget, + canceled: false, + stopped: false, + immediateStopped: false, + passiveListener: null, + timeStamp: event.timeStamp || Date.now(), + }); + + // https://heycam.github.io/webidl/#Unforgeable + Object.defineProperty(this, "isTrusted", { value: false, enumerable: true }); + + // Define accessors + const keys = Object.keys(event); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (!(key in this)) { + Object.defineProperty(this, key, defineRedirectDescriptor(key)); + } + } +} + +// Should be enumerable, but class methods are not enumerable. +Event.prototype = { + /** + * The type of this event. + * @type {string} + */ + get type() { + return pd(this).event.type + }, + + /** + * The target of this event. + * @type {EventTarget} + */ + get target() { + return pd(this).eventTarget + }, + + /** + * The target of this event. + * @type {EventTarget} + */ + get currentTarget() { + return pd(this).currentTarget + }, + + /** + * @returns {EventTarget[]} The composed path of this event. + */ + composedPath() { + const currentTarget = pd(this).currentTarget; + if (currentTarget == null) { + return [] + } + return [currentTarget] + }, + + /** + * Constant of NONE. + * @type {number} + */ + get NONE() { + return 0 + }, + + /** + * Constant of CAPTURING_PHASE. + * @type {number} + */ + get CAPTURING_PHASE() { + return 1 + }, + + /** + * Constant of AT_TARGET. + * @type {number} + */ + get AT_TARGET() { + return 2 + }, + + /** + * Constant of BUBBLING_PHASE. + * @type {number} + */ + get BUBBLING_PHASE() { + return 3 + }, + + /** + * The target of this event. + * @type {number} + */ + get eventPhase() { + return pd(this).eventPhase + }, + + /** + * Stop event bubbling. + * @returns {void} + */ + stopPropagation() { + const data = pd(this); + + data.stopped = true; + if (typeof data.event.stopPropagation === "function") { + data.event.stopPropagation(); + } + }, + + /** + * Stop event bubbling. + * @returns {void} + */ + stopImmediatePropagation() { + const data = pd(this); + + data.stopped = true; + data.immediateStopped = true; + if (typeof data.event.stopImmediatePropagation === "function") { + data.event.stopImmediatePropagation(); + } + }, + + /** + * The flag to be bubbling. + * @type {boolean} + */ + get bubbles() { + return Boolean(pd(this).event.bubbles) + }, + + /** + * The flag to be cancelable. + * @type {boolean} + */ + get cancelable() { + return Boolean(pd(this).event.cancelable) + }, + + /** + * Cancel this event. + * @returns {void} + */ + preventDefault() { + setCancelFlag(pd(this)); + }, + + /** + * The flag to indicate cancellation state. + * @type {boolean} + */ + get defaultPrevented() { + return pd(this).canceled + }, + + /** + * The flag to be composed. + * @type {boolean} + */ + get composed() { + return Boolean(pd(this).event.composed) + }, + + /** + * The unix time of this event. + * @type {number} + */ + get timeStamp() { + return pd(this).timeStamp + }, + + /** + * The target of this event. + * @type {EventTarget} + * @deprecated + */ + get srcElement() { + return pd(this).eventTarget + }, + + /** + * The flag to stop event bubbling. + * @type {boolean} + * @deprecated + */ + get cancelBubble() { + return pd(this).stopped + }, + set cancelBubble(value) { + if (!value) { + return + } + const data = pd(this); + + data.stopped = true; + if (typeof data.event.cancelBubble === "boolean") { + data.event.cancelBubble = true; + } + }, + + /** + * The flag to indicate cancellation state. + * @type {boolean} + * @deprecated + */ + get returnValue() { + return !pd(this).canceled + }, + set returnValue(value) { + if (!value) { + setCancelFlag(pd(this)); + } + }, + + /** + * Initialize this event object. But do nothing under event dispatching. + * @param {string} type The event type. + * @param {boolean} [bubbles=false] The flag to be possible to bubble up. + * @param {boolean} [cancelable=false] The flag to be possible to cancel. + * @deprecated + */ + initEvent() { + // Do nothing. + }, +}; + +// `constructor` is not enumerable. +Object.defineProperty(Event.prototype, "constructor", { + value: Event, + configurable: true, + writable: true, +}); + +// Ensure `event instanceof window.Event` is `true`. +if (typeof window !== "undefined" && typeof window.Event !== "undefined") { + Object.setPrototypeOf(Event.prototype, window.Event.prototype); + + // Make association for wrappers. + wrappers.set(window.Event.prototype, Event); +} + +/** + * Get the property descriptor to redirect a given property. + * @param {string} key Property name to define property descriptor. + * @returns {PropertyDescriptor} The property descriptor to redirect the property. + * @private + */ +function defineRedirectDescriptor(key) { + return { + get() { + return pd(this).event[key] + }, + set(value) { + pd(this).event[key] = value; + }, + configurable: true, + enumerable: true, + } +} + +/** + * Get the property descriptor to call a given method property. + * @param {string} key Property name to define property descriptor. + * @returns {PropertyDescriptor} The property descriptor to call the method property. + * @private + */ +function defineCallDescriptor(key) { + return { + value() { + const event = pd(this).event; + return event[key].apply(event, arguments) + }, + configurable: true, + enumerable: true, + } +} + +/** + * Define new wrapper class. + * @param {Function} BaseEvent The base wrapper class. + * @param {Object} proto The prototype of the original event. + * @returns {Function} The defined wrapper class. + * @private + */ +function defineWrapper(BaseEvent, proto) { + const keys = Object.keys(proto); + if (keys.length === 0) { + return BaseEvent + } + + /** CustomEvent */ + function CustomEvent(eventTarget, event) { + BaseEvent.call(this, eventTarget, event); + } + + CustomEvent.prototype = Object.create(BaseEvent.prototype, { + constructor: { value: CustomEvent, configurable: true, writable: true }, + }); + + // Define accessors. + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (!(key in BaseEvent.prototype)) { + const descriptor = Object.getOwnPropertyDescriptor(proto, key); + const isFunc = typeof descriptor.value === "function"; + Object.defineProperty( + CustomEvent.prototype, + key, + isFunc + ? defineCallDescriptor(key) + : defineRedirectDescriptor(key) + ); + } + } + + return CustomEvent +} + +/** + * Get the wrapper class of a given prototype. + * @param {Object} proto The prototype of the original event to get its wrapper. + * @returns {Function} The wrapper class. + * @private + */ +function getWrapper(proto) { + if (proto == null || proto === Object.prototype) { + return Event + } + + let wrapper = wrappers.get(proto); + if (wrapper == null) { + wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto); + wrappers.set(proto, wrapper); + } + return wrapper +} + +/** + * Wrap a given event to management a dispatching. + * @param {EventTarget} eventTarget The event target of this dispatching. + * @param {Object} event The event to wrap. + * @returns {Event} The wrapper instance. + * @private + */ +function wrapEvent(eventTarget, event) { + const Wrapper = getWrapper(Object.getPrototypeOf(event)); + return new Wrapper(eventTarget, event) +} + +/** + * Get the immediateStopped flag of a given event. + * @param {Event} event The event to get. + * @returns {boolean} The flag to stop propagation immediately. + * @private + */ +function isStopped(event) { + return pd(event).immediateStopped +} + +/** + * Set the current event phase of a given event. + * @param {Event} event The event to set current target. + * @param {number} eventPhase New event phase. + * @returns {void} + * @private + */ +function setEventPhase(event, eventPhase) { + pd(event).eventPhase = eventPhase; +} + +/** + * Set the current target of a given event. + * @param {Event} event The event to set current target. + * @param {EventTarget|null} currentTarget New current target. + * @returns {void} + * @private + */ +function setCurrentTarget(event, currentTarget) { + pd(event).currentTarget = currentTarget; +} + +/** + * Set a passive listener of a given event. + * @param {Event} event The event to set current target. + * @param {Function|null} passiveListener New passive listener. + * @returns {void} + * @private + */ +function setPassiveListener(event, passiveListener) { + pd(event).passiveListener = passiveListener; +} + +/** + * @typedef {object} ListenerNode + * @property {Function} listener + * @property {1|2|3} listenerType + * @property {boolean} passive + * @property {boolean} once + * @property {ListenerNode|null} next + * @private + */ + +/** + * @type {WeakMap>} + * @private + */ +const listenersMap = new WeakMap(); + +// Listener types +const CAPTURE = 1; +const BUBBLE = 2; +const ATTRIBUTE = 3; + +/** + * Check whether a given value is an object or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if the value is an object. + */ +function isObject(x) { + return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax +} + +/** + * Get listeners. + * @param {EventTarget} eventTarget The event target to get. + * @returns {Map} The listeners. + * @private + */ +function getListeners(eventTarget) { + const listeners = listenersMap.get(eventTarget); + if (listeners == null) { + throw new TypeError( + "'this' is expected an EventTarget object, but got another value." + ) + } + return listeners +} + +/** + * Get the property descriptor for the event attribute of a given event. + * @param {string} eventName The event name to get property descriptor. + * @returns {PropertyDescriptor} The property descriptor. + * @private + */ +function defineEventAttributeDescriptor(eventName) { + return { + get() { + const listeners = getListeners(this); + let node = listeners.get(eventName); + while (node != null) { + if (node.listenerType === ATTRIBUTE) { + return node.listener + } + node = node.next; + } + return null + }, + + set(listener) { + if (typeof listener !== "function" && !isObject(listener)) { + listener = null; // eslint-disable-line no-param-reassign + } + const listeners = getListeners(this); + + // Traverse to the tail while removing old value. + let prev = null; + let node = listeners.get(eventName); + while (node != null) { + if (node.listenerType === ATTRIBUTE) { + // Remove old value. + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + } else { + prev = node; + } + + node = node.next; + } + + // Add new value. + if (listener !== null) { + const newNode = { + listener, + listenerType: ATTRIBUTE, + passive: false, + once: false, + next: null, + }; + if (prev === null) { + listeners.set(eventName, newNode); + } else { + prev.next = newNode; + } + } + }, + configurable: true, + enumerable: true, + } +} + +/** + * Define an event attribute (e.g. `eventTarget.onclick`). + * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite. + * @param {string} eventName The event name to define. + * @returns {void} + */ +function defineEventAttribute(eventTargetPrototype, eventName) { + Object.defineProperty( + eventTargetPrototype, + `on${eventName}`, + defineEventAttributeDescriptor(eventName) + ); +} + +/** + * Define a custom EventTarget with event attributes. + * @param {string[]} eventNames Event names for event attributes. + * @returns {EventTarget} The custom EventTarget. + * @private + */ +function defineCustomEventTarget(eventNames) { + /** CustomEventTarget */ + function CustomEventTarget() { + EventTarget.call(this); + } + + CustomEventTarget.prototype = Object.create(EventTarget.prototype, { + constructor: { + value: CustomEventTarget, + configurable: true, + writable: true, + }, + }); + + for (let i = 0; i < eventNames.length; ++i) { + defineEventAttribute(CustomEventTarget.prototype, eventNames[i]); + } + + return CustomEventTarget +} + +/** + * EventTarget. + * + * - This is constructor if no arguments. + * - This is a function which returns a CustomEventTarget constructor if there are arguments. + * + * For example: + * + * class A extends EventTarget {} + * class B extends EventTarget("message") {} + * class C extends EventTarget("message", "error") {} + * class D extends EventTarget(["message", "error"]) {} + */ +function EventTarget() { + /*eslint-disable consistent-return */ + if (this instanceof EventTarget) { + listenersMap.set(this, new Map()); + return + } + if (arguments.length === 1 && Array.isArray(arguments[0])) { + return defineCustomEventTarget(arguments[0]) + } + if (arguments.length > 0) { + const types = new Array(arguments.length); + for (let i = 0; i < arguments.length; ++i) { + types[i] = arguments[i]; + } + return defineCustomEventTarget(types) + } + throw new TypeError("Cannot call a class as a function") + /*eslint-enable consistent-return */ +} + +// Should be enumerable, but class methods are not enumerable. +EventTarget.prototype = { + /** + * Add a given listener to this event target. + * @param {string} eventName The event name to add. + * @param {Function} listener The listener to add. + * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. + * @returns {void} + */ + addEventListener(eventName, listener, options) { + if (listener == null) { + return + } + if (typeof listener !== "function" && !isObject(listener)) { + throw new TypeError("'listener' should be a function or an object.") + } + + const listeners = getListeners(this); + const optionsIsObj = isObject(options); + const capture = optionsIsObj + ? Boolean(options.capture) + : Boolean(options); + const listenerType = capture ? CAPTURE : BUBBLE; + const newNode = { + listener, + listenerType, + passive: optionsIsObj && Boolean(options.passive), + once: optionsIsObj && Boolean(options.once), + next: null, + }; + + // Set it as the first node if the first node is null. + let node = listeners.get(eventName); + if (node === undefined) { + listeners.set(eventName, newNode); + return + } + + // Traverse to the tail while checking duplication.. + let prev = null; + while (node != null) { + if ( + node.listener === listener && + node.listenerType === listenerType + ) { + // Should ignore duplication. + return + } + prev = node; + node = node.next; + } + + // Add it. + prev.next = newNode; + }, + + /** + * Remove a given listener from this event target. + * @param {string} eventName The event name to remove. + * @param {Function} listener The listener to remove. + * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. + * @returns {void} + */ + removeEventListener(eventName, listener, options) { + if (listener == null) { + return + } + + const listeners = getListeners(this); + const capture = isObject(options) + ? Boolean(options.capture) + : Boolean(options); + const listenerType = capture ? CAPTURE : BUBBLE; + + let prev = null; + let node = listeners.get(eventName); + while (node != null) { + if ( + node.listener === listener && + node.listenerType === listenerType + ) { + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + return + } + + prev = node; + node = node.next; + } + }, + + /** + * Dispatch a given event. + * @param {Event|{type:string}} event The event to dispatch. + * @returns {boolean} `false` if canceled. + */ + dispatchEvent(event) { + if (event == null || typeof event.type !== "string") { + throw new TypeError('"event.type" should be a string.') + } + + // If listeners aren't registered, terminate. + const listeners = getListeners(this); + const eventName = event.type; + let node = listeners.get(eventName); + if (node == null) { + return true + } + + // Since we cannot rewrite several properties, so wrap object. + const wrappedEvent = wrapEvent(this, event); + + // This doesn't process capturing phase and bubbling phase. + // This isn't participating in a tree. + let prev = null; + while (node != null) { + // Remove this listener if it's once + if (node.once) { + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + } else { + prev = node; + } + + // Call this listener + setPassiveListener( + wrappedEvent, + node.passive ? node.listener : null + ); + if (typeof node.listener === "function") { + try { + node.listener.call(this, wrappedEvent); + } catch (err) { + if ( + typeof console !== "undefined" && + typeof console.error === "function" + ) { + console.error(err); + } + } + } else if ( + node.listenerType !== ATTRIBUTE && + typeof node.listener.handleEvent === "function" + ) { + node.listener.handleEvent(wrappedEvent); + } + + // Break if `event.stopImmediatePropagation` was called. + if (isStopped(wrappedEvent)) { + break + } + + node = node.next; + } + setPassiveListener(wrappedEvent, null); + setEventPhase(wrappedEvent, 0); + setCurrentTarget(wrappedEvent, null); + + return !wrappedEvent.defaultPrevented + }, +}; + +// `constructor` is not enumerable. +Object.defineProperty(EventTarget.prototype, "constructor", { + value: EventTarget, + configurable: true, + writable: true, +}); + +// Ensure `eventTarget instanceof window.EventTarget` is `true`. +if ( + typeof window !== "undefined" && + typeof window.EventTarget !== "undefined" +) { + Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype); +} + +export default EventTarget; +export { defineEventAttribute, EventTarget }; +//# sourceMappingURL=event-target-shim.mjs.map diff --git a/node_modules/event-target-shim/dist/event-target-shim.mjs.map b/node_modules/event-target-shim/dist/event-target-shim.mjs.map new file mode 100644 index 0000000..57b3e8f --- /dev/null +++ b/node_modules/event-target-shim/dist/event-target-shim.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"event-target-shim.mjs","sources":["../src/event.mjs","../src/event-target.mjs"],"sourcesContent":["/**\n * @typedef {object} PrivateData\n * @property {EventTarget} eventTarget The event target.\n * @property {{type:string}} event The original event object.\n * @property {number} eventPhase The current event phase.\n * @property {EventTarget|null} currentTarget The current event target.\n * @property {boolean} canceled The flag to prevent default.\n * @property {boolean} stopped The flag to stop propagation.\n * @property {boolean} immediateStopped The flag to stop propagation immediately.\n * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null.\n * @property {number} timeStamp The unix time.\n * @private\n */\n\n/**\n * Private data for event wrappers.\n * @type {WeakMap}\n * @private\n */\nconst privateData = new WeakMap()\n\n/**\n * Cache for wrapper classes.\n * @type {WeakMap}\n * @private\n */\nconst wrappers = new WeakMap()\n\n/**\n * Get private data.\n * @param {Event} event The event object to get private data.\n * @returns {PrivateData} The private data of the event.\n * @private\n */\nfunction pd(event) {\n const retv = privateData.get(event)\n console.assert(\n retv != null,\n \"'this' is expected an Event object, but got\",\n event\n )\n return retv\n}\n\n/**\n * https://dom.spec.whatwg.org/#set-the-canceled-flag\n * @param data {PrivateData} private data.\n */\nfunction setCancelFlag(data) {\n if (data.passiveListener != null) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(\n \"Unable to preventDefault inside passive event listener invocation.\",\n data.passiveListener\n )\n }\n return\n }\n if (!data.event.cancelable) {\n return\n }\n\n data.canceled = true\n if (typeof data.event.preventDefault === \"function\") {\n data.event.preventDefault()\n }\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#interface-event\n * @private\n */\n/**\n * The event wrapper.\n * @constructor\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Event|{type:string}} event The original event to wrap.\n */\nfunction Event(eventTarget, event) {\n privateData.set(this, {\n eventTarget,\n event,\n eventPhase: 2,\n currentTarget: eventTarget,\n canceled: false,\n stopped: false,\n immediateStopped: false,\n passiveListener: null,\n timeStamp: event.timeStamp || Date.now(),\n })\n\n // https://heycam.github.io/webidl/#Unforgeable\n Object.defineProperty(this, \"isTrusted\", { value: false, enumerable: true })\n\n // Define accessors\n const keys = Object.keys(event)\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in this)) {\n Object.defineProperty(this, key, defineRedirectDescriptor(key))\n }\n }\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEvent.prototype = {\n /**\n * The type of this event.\n * @type {string}\n */\n get type() {\n return pd(this).event.type\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get target() {\n return pd(this).eventTarget\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get currentTarget() {\n return pd(this).currentTarget\n },\n\n /**\n * @returns {EventTarget[]} The composed path of this event.\n */\n composedPath() {\n const currentTarget = pd(this).currentTarget\n if (currentTarget == null) {\n return []\n }\n return [currentTarget]\n },\n\n /**\n * Constant of NONE.\n * @type {number}\n */\n get NONE() {\n return 0\n },\n\n /**\n * Constant of CAPTURING_PHASE.\n * @type {number}\n */\n get CAPTURING_PHASE() {\n return 1\n },\n\n /**\n * Constant of AT_TARGET.\n * @type {number}\n */\n get AT_TARGET() {\n return 2\n },\n\n /**\n * Constant of BUBBLING_PHASE.\n * @type {number}\n */\n get BUBBLING_PHASE() {\n return 3\n },\n\n /**\n * The target of this event.\n * @type {number}\n */\n get eventPhase() {\n return pd(this).eventPhase\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopPropagation() {\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.stopPropagation === \"function\") {\n data.event.stopPropagation()\n }\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopImmediatePropagation() {\n const data = pd(this)\n\n data.stopped = true\n data.immediateStopped = true\n if (typeof data.event.stopImmediatePropagation === \"function\") {\n data.event.stopImmediatePropagation()\n }\n },\n\n /**\n * The flag to be bubbling.\n * @type {boolean}\n */\n get bubbles() {\n return Boolean(pd(this).event.bubbles)\n },\n\n /**\n * The flag to be cancelable.\n * @type {boolean}\n */\n get cancelable() {\n return Boolean(pd(this).event.cancelable)\n },\n\n /**\n * Cancel this event.\n * @returns {void}\n */\n preventDefault() {\n setCancelFlag(pd(this))\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n */\n get defaultPrevented() {\n return pd(this).canceled\n },\n\n /**\n * The flag to be composed.\n * @type {boolean}\n */\n get composed() {\n return Boolean(pd(this).event.composed)\n },\n\n /**\n * The unix time of this event.\n * @type {number}\n */\n get timeStamp() {\n return pd(this).timeStamp\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n * @deprecated\n */\n get srcElement() {\n return pd(this).eventTarget\n },\n\n /**\n * The flag to stop event bubbling.\n * @type {boolean}\n * @deprecated\n */\n get cancelBubble() {\n return pd(this).stopped\n },\n set cancelBubble(value) {\n if (!value) {\n return\n }\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.cancelBubble === \"boolean\") {\n data.event.cancelBubble = true\n }\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n * @deprecated\n */\n get returnValue() {\n return !pd(this).canceled\n },\n set returnValue(value) {\n if (!value) {\n setCancelFlag(pd(this))\n }\n },\n\n /**\n * Initialize this event object. But do nothing under event dispatching.\n * @param {string} type The event type.\n * @param {boolean} [bubbles=false] The flag to be possible to bubble up.\n * @param {boolean} [cancelable=false] The flag to be possible to cancel.\n * @deprecated\n */\n initEvent() {\n // Do nothing.\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(Event.prototype, \"constructor\", {\n value: Event,\n configurable: true,\n writable: true,\n})\n\n// Ensure `event instanceof window.Event` is `true`.\nif (typeof window !== \"undefined\" && typeof window.Event !== \"undefined\") {\n Object.setPrototypeOf(Event.prototype, window.Event.prototype)\n\n // Make association for wrappers.\n wrappers.set(window.Event.prototype, Event)\n}\n\n/**\n * Get the property descriptor to redirect a given property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to redirect the property.\n * @private\n */\nfunction defineRedirectDescriptor(key) {\n return {\n get() {\n return pd(this).event[key]\n },\n set(value) {\n pd(this).event[key] = value\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Get the property descriptor to call a given method property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to call the method property.\n * @private\n */\nfunction defineCallDescriptor(key) {\n return {\n value() {\n const event = pd(this).event\n return event[key].apply(event, arguments)\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define new wrapper class.\n * @param {Function} BaseEvent The base wrapper class.\n * @param {Object} proto The prototype of the original event.\n * @returns {Function} The defined wrapper class.\n * @private\n */\nfunction defineWrapper(BaseEvent, proto) {\n const keys = Object.keys(proto)\n if (keys.length === 0) {\n return BaseEvent\n }\n\n /** CustomEvent */\n function CustomEvent(eventTarget, event) {\n BaseEvent.call(this, eventTarget, event)\n }\n\n CustomEvent.prototype = Object.create(BaseEvent.prototype, {\n constructor: { value: CustomEvent, configurable: true, writable: true },\n })\n\n // Define accessors.\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in BaseEvent.prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, key)\n const isFunc = typeof descriptor.value === \"function\"\n Object.defineProperty(\n CustomEvent.prototype,\n key,\n isFunc\n ? defineCallDescriptor(key)\n : defineRedirectDescriptor(key)\n )\n }\n }\n\n return CustomEvent\n}\n\n/**\n * Get the wrapper class of a given prototype.\n * @param {Object} proto The prototype of the original event to get its wrapper.\n * @returns {Function} The wrapper class.\n * @private\n */\nfunction getWrapper(proto) {\n if (proto == null || proto === Object.prototype) {\n return Event\n }\n\n let wrapper = wrappers.get(proto)\n if (wrapper == null) {\n wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto)\n wrappers.set(proto, wrapper)\n }\n return wrapper\n}\n\n/**\n * Wrap a given event to management a dispatching.\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Object} event The event to wrap.\n * @returns {Event} The wrapper instance.\n * @private\n */\nexport function wrapEvent(eventTarget, event) {\n const Wrapper = getWrapper(Object.getPrototypeOf(event))\n return new Wrapper(eventTarget, event)\n}\n\n/**\n * Get the immediateStopped flag of a given event.\n * @param {Event} event The event to get.\n * @returns {boolean} The flag to stop propagation immediately.\n * @private\n */\nexport function isStopped(event) {\n return pd(event).immediateStopped\n}\n\n/**\n * Set the current event phase of a given event.\n * @param {Event} event The event to set current target.\n * @param {number} eventPhase New event phase.\n * @returns {void}\n * @private\n */\nexport function setEventPhase(event, eventPhase) {\n pd(event).eventPhase = eventPhase\n}\n\n/**\n * Set the current target of a given event.\n * @param {Event} event The event to set current target.\n * @param {EventTarget|null} currentTarget New current target.\n * @returns {void}\n * @private\n */\nexport function setCurrentTarget(event, currentTarget) {\n pd(event).currentTarget = currentTarget\n}\n\n/**\n * Set a passive listener of a given event.\n * @param {Event} event The event to set current target.\n * @param {Function|null} passiveListener New passive listener.\n * @returns {void}\n * @private\n */\nexport function setPassiveListener(event, passiveListener) {\n pd(event).passiveListener = passiveListener\n}\n","import {\n isStopped,\n setCurrentTarget,\n setEventPhase,\n setPassiveListener,\n wrapEvent,\n} from \"./event.mjs\"\n\n/**\n * @typedef {object} ListenerNode\n * @property {Function} listener\n * @property {1|2|3} listenerType\n * @property {boolean} passive\n * @property {boolean} once\n * @property {ListenerNode|null} next\n * @private\n */\n\n/**\n * @type {WeakMap>}\n * @private\n */\nconst listenersMap = new WeakMap()\n\n// Listener types\nconst CAPTURE = 1\nconst BUBBLE = 2\nconst ATTRIBUTE = 3\n\n/**\n * Check whether a given value is an object or not.\n * @param {any} x The value to check.\n * @returns {boolean} `true` if the value is an object.\n */\nfunction isObject(x) {\n return x !== null && typeof x === \"object\" //eslint-disable-line no-restricted-syntax\n}\n\n/**\n * Get listeners.\n * @param {EventTarget} eventTarget The event target to get.\n * @returns {Map} The listeners.\n * @private\n */\nfunction getListeners(eventTarget) {\n const listeners = listenersMap.get(eventTarget)\n if (listeners == null) {\n throw new TypeError(\n \"'this' is expected an EventTarget object, but got another value.\"\n )\n }\n return listeners\n}\n\n/**\n * Get the property descriptor for the event attribute of a given event.\n * @param {string} eventName The event name to get property descriptor.\n * @returns {PropertyDescriptor} The property descriptor.\n * @private\n */\nfunction defineEventAttributeDescriptor(eventName) {\n return {\n get() {\n const listeners = getListeners(this)\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n return node.listener\n }\n node = node.next\n }\n return null\n },\n\n set(listener) {\n if (typeof listener !== \"function\" && !isObject(listener)) {\n listener = null // eslint-disable-line no-param-reassign\n }\n const listeners = getListeners(this)\n\n // Traverse to the tail while removing old value.\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n // Remove old value.\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n node = node.next\n }\n\n // Add new value.\n if (listener !== null) {\n const newNode = {\n listener,\n listenerType: ATTRIBUTE,\n passive: false,\n once: false,\n next: null,\n }\n if (prev === null) {\n listeners.set(eventName, newNode)\n } else {\n prev.next = newNode\n }\n }\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define an event attribute (e.g. `eventTarget.onclick`).\n * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.\n * @param {string} eventName The event name to define.\n * @returns {void}\n */\nfunction defineEventAttribute(eventTargetPrototype, eventName) {\n Object.defineProperty(\n eventTargetPrototype,\n `on${eventName}`,\n defineEventAttributeDescriptor(eventName)\n )\n}\n\n/**\n * Define a custom EventTarget with event attributes.\n * @param {string[]} eventNames Event names for event attributes.\n * @returns {EventTarget} The custom EventTarget.\n * @private\n */\nfunction defineCustomEventTarget(eventNames) {\n /** CustomEventTarget */\n function CustomEventTarget() {\n EventTarget.call(this)\n }\n\n CustomEventTarget.prototype = Object.create(EventTarget.prototype, {\n constructor: {\n value: CustomEventTarget,\n configurable: true,\n writable: true,\n },\n })\n\n for (let i = 0; i < eventNames.length; ++i) {\n defineEventAttribute(CustomEventTarget.prototype, eventNames[i])\n }\n\n return CustomEventTarget\n}\n\n/**\n * EventTarget.\n *\n * - This is constructor if no arguments.\n * - This is a function which returns a CustomEventTarget constructor if there are arguments.\n *\n * For example:\n *\n * class A extends EventTarget {}\n * class B extends EventTarget(\"message\") {}\n * class C extends EventTarget(\"message\", \"error\") {}\n * class D extends EventTarget([\"message\", \"error\"]) {}\n */\nfunction EventTarget() {\n /*eslint-disable consistent-return */\n if (this instanceof EventTarget) {\n listenersMap.set(this, new Map())\n return\n }\n if (arguments.length === 1 && Array.isArray(arguments[0])) {\n return defineCustomEventTarget(arguments[0])\n }\n if (arguments.length > 0) {\n const types = new Array(arguments.length)\n for (let i = 0; i < arguments.length; ++i) {\n types[i] = arguments[i]\n }\n return defineCustomEventTarget(types)\n }\n throw new TypeError(\"Cannot call a class as a function\")\n /*eslint-enable consistent-return */\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEventTarget.prototype = {\n /**\n * Add a given listener to this event target.\n * @param {string} eventName The event name to add.\n * @param {Function} listener The listener to add.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n addEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n if (typeof listener !== \"function\" && !isObject(listener)) {\n throw new TypeError(\"'listener' should be a function or an object.\")\n }\n\n const listeners = getListeners(this)\n const optionsIsObj = isObject(options)\n const capture = optionsIsObj\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n const newNode = {\n listener,\n listenerType,\n passive: optionsIsObj && Boolean(options.passive),\n once: optionsIsObj && Boolean(options.once),\n next: null,\n }\n\n // Set it as the first node if the first node is null.\n let node = listeners.get(eventName)\n if (node === undefined) {\n listeners.set(eventName, newNode)\n return\n }\n\n // Traverse to the tail while checking duplication..\n let prev = null\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n // Should ignore duplication.\n return\n }\n prev = node\n node = node.next\n }\n\n // Add it.\n prev.next = newNode\n },\n\n /**\n * Remove a given listener from this event target.\n * @param {string} eventName The event name to remove.\n * @param {Function} listener The listener to remove.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n removeEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n\n const listeners = getListeners(this)\n const capture = isObject(options)\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n return\n }\n\n prev = node\n node = node.next\n }\n },\n\n /**\n * Dispatch a given event.\n * @param {Event|{type:string}} event The event to dispatch.\n * @returns {boolean} `false` if canceled.\n */\n dispatchEvent(event) {\n if (event == null || typeof event.type !== \"string\") {\n throw new TypeError('\"event.type\" should be a string.')\n }\n\n // If listeners aren't registered, terminate.\n const listeners = getListeners(this)\n const eventName = event.type\n let node = listeners.get(eventName)\n if (node == null) {\n return true\n }\n\n // Since we cannot rewrite several properties, so wrap object.\n const wrappedEvent = wrapEvent(this, event)\n\n // This doesn't process capturing phase and bubbling phase.\n // This isn't participating in a tree.\n let prev = null\n while (node != null) {\n // Remove this listener if it's once\n if (node.once) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n // Call this listener\n setPassiveListener(\n wrappedEvent,\n node.passive ? node.listener : null\n )\n if (typeof node.listener === \"function\") {\n try {\n node.listener.call(this, wrappedEvent)\n } catch (err) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(err)\n }\n }\n } else if (\n node.listenerType !== ATTRIBUTE &&\n typeof node.listener.handleEvent === \"function\"\n ) {\n node.listener.handleEvent(wrappedEvent)\n }\n\n // Break if `event.stopImmediatePropagation` was called.\n if (isStopped(wrappedEvent)) {\n break\n }\n\n node = node.next\n }\n setPassiveListener(wrappedEvent, null)\n setEventPhase(wrappedEvent, 0)\n setCurrentTarget(wrappedEvent, null)\n\n return !wrappedEvent.defaultPrevented\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(EventTarget.prototype, \"constructor\", {\n value: EventTarget,\n configurable: true,\n writable: true,\n})\n\n// Ensure `eventTarget instanceof window.EventTarget` is `true`.\nif (\n typeof window !== \"undefined\" &&\n typeof window.EventTarget !== \"undefined\"\n) {\n Object.setPrototypeOf(EventTarget.prototype, window.Event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AAc,CAAC,WAAW,CAAC,SAAS,EAAE,aAAa,EAAE;IACxD,KAAK,EAAE,WAAW;IAClB,YAAY,EAAE,IAAI;IAClB,QAAQ,EAAE,IAAI;CACjB,EAAC;;;AAGF;IACI,OAAO,MAAM,KAAK,WAAW;IAC7B,OAAO,MAAM,CAAC,WAAW,KAAK,WAAW;EAC3C;IACE,MAAM,CAAC,cAAc,CAAC,WAAW,CAAC,SAAS,EAAE,MAAM,CAAC,WAAW,CAAC,SAAS,EAAC;CAC7E;;;;;"} \ No newline at end of file diff --git a/node_modules/event-target-shim/dist/event-target-shim.umd.js b/node_modules/event-target-shim/dist/event-target-shim.umd.js new file mode 100644 index 0000000..e7cf5d4 --- /dev/null +++ b/node_modules/event-target-shim/dist/event-target-shim.umd.js @@ -0,0 +1,6 @@ +/** + * @author Toru Nagashima + * @copyright 2015 Toru Nagashima. All rights reserved. + * See LICENSE file in root directory for full license. + */(function(a,b){"object"==typeof exports&&"undefined"!=typeof module?b(exports):"function"==typeof define&&define.amd?define(["exports"],b):(a=a||self,b(a.EventTargetShim={}))})(this,function(a){"use strict";function b(a){return b="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},b(a)}function c(a){var b=u.get(a);return console.assert(null!=b,"'this' is expected an Event object, but got",a),b}function d(a){return null==a.passiveListener?void(!a.event.cancelable||(a.canceled=!0,"function"==typeof a.event.preventDefault&&a.event.preventDefault())):void("undefined"!=typeof console&&"function"==typeof console.error&&console.error("Unable to preventDefault inside passive event listener invocation.",a.passiveListener))}function e(a,b){u.set(this,{eventTarget:a,event:b,eventPhase:2,currentTarget:a,canceled:!1,stopped:!1,immediateStopped:!1,passiveListener:null,timeStamp:b.timeStamp||Date.now()}),Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});for(var c,d=Object.keys(b),e=0;e}\n * @private\n */\nconst privateData = new WeakMap()\n\n/**\n * Cache for wrapper classes.\n * @type {WeakMap}\n * @private\n */\nconst wrappers = new WeakMap()\n\n/**\n * Get private data.\n * @param {Event} event The event object to get private data.\n * @returns {PrivateData} The private data of the event.\n * @private\n */\nfunction pd(event) {\n const retv = privateData.get(event)\n console.assert(\n retv != null,\n \"'this' is expected an Event object, but got\",\n event\n )\n return retv\n}\n\n/**\n * https://dom.spec.whatwg.org/#set-the-canceled-flag\n * @param data {PrivateData} private data.\n */\nfunction setCancelFlag(data) {\n if (data.passiveListener != null) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(\n \"Unable to preventDefault inside passive event listener invocation.\",\n data.passiveListener\n )\n }\n return\n }\n if (!data.event.cancelable) {\n return\n }\n\n data.canceled = true\n if (typeof data.event.preventDefault === \"function\") {\n data.event.preventDefault()\n }\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#interface-event\n * @private\n */\n/**\n * The event wrapper.\n * @constructor\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Event|{type:string}} event The original event to wrap.\n */\nfunction Event(eventTarget, event) {\n privateData.set(this, {\n eventTarget,\n event,\n eventPhase: 2,\n currentTarget: eventTarget,\n canceled: false,\n stopped: false,\n immediateStopped: false,\n passiveListener: null,\n timeStamp: event.timeStamp || Date.now(),\n })\n\n // https://heycam.github.io/webidl/#Unforgeable\n Object.defineProperty(this, \"isTrusted\", { value: false, enumerable: true })\n\n // Define accessors\n const keys = Object.keys(event)\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in this)) {\n Object.defineProperty(this, key, defineRedirectDescriptor(key))\n }\n }\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEvent.prototype = {\n /**\n * The type of this event.\n * @type {string}\n */\n get type() {\n return pd(this).event.type\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get target() {\n return pd(this).eventTarget\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get currentTarget() {\n return pd(this).currentTarget\n },\n\n /**\n * @returns {EventTarget[]} The composed path of this event.\n */\n composedPath() {\n const currentTarget = pd(this).currentTarget\n if (currentTarget == null) {\n return []\n }\n return [currentTarget]\n },\n\n /**\n * Constant of NONE.\n * @type {number}\n */\n get NONE() {\n return 0\n },\n\n /**\n * Constant of CAPTURING_PHASE.\n * @type {number}\n */\n get CAPTURING_PHASE() {\n return 1\n },\n\n /**\n * Constant of AT_TARGET.\n * @type {number}\n */\n get AT_TARGET() {\n return 2\n },\n\n /**\n * Constant of BUBBLING_PHASE.\n * @type {number}\n */\n get BUBBLING_PHASE() {\n return 3\n },\n\n /**\n * The target of this event.\n * @type {number}\n */\n get eventPhase() {\n return pd(this).eventPhase\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopPropagation() {\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.stopPropagation === \"function\") {\n data.event.stopPropagation()\n }\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopImmediatePropagation() {\n const data = pd(this)\n\n data.stopped = true\n data.immediateStopped = true\n if (typeof data.event.stopImmediatePropagation === \"function\") {\n data.event.stopImmediatePropagation()\n }\n },\n\n /**\n * The flag to be bubbling.\n * @type {boolean}\n */\n get bubbles() {\n return Boolean(pd(this).event.bubbles)\n },\n\n /**\n * The flag to be cancelable.\n * @type {boolean}\n */\n get cancelable() {\n return Boolean(pd(this).event.cancelable)\n },\n\n /**\n * Cancel this event.\n * @returns {void}\n */\n preventDefault() {\n setCancelFlag(pd(this))\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n */\n get defaultPrevented() {\n return pd(this).canceled\n },\n\n /**\n * The flag to be composed.\n * @type {boolean}\n */\n get composed() {\n return Boolean(pd(this).event.composed)\n },\n\n /**\n * The unix time of this event.\n * @type {number}\n */\n get timeStamp() {\n return pd(this).timeStamp\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n * @deprecated\n */\n get srcElement() {\n return pd(this).eventTarget\n },\n\n /**\n * The flag to stop event bubbling.\n * @type {boolean}\n * @deprecated\n */\n get cancelBubble() {\n return pd(this).stopped\n },\n set cancelBubble(value) {\n if (!value) {\n return\n }\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.cancelBubble === \"boolean\") {\n data.event.cancelBubble = true\n }\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n * @deprecated\n */\n get returnValue() {\n return !pd(this).canceled\n },\n set returnValue(value) {\n if (!value) {\n setCancelFlag(pd(this))\n }\n },\n\n /**\n * Initialize this event object. But do nothing under event dispatching.\n * @param {string} type The event type.\n * @param {boolean} [bubbles=false] The flag to be possible to bubble up.\n * @param {boolean} [cancelable=false] The flag to be possible to cancel.\n * @deprecated\n */\n initEvent() {\n // Do nothing.\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(Event.prototype, \"constructor\", {\n value: Event,\n configurable: true,\n writable: true,\n})\n\n// Ensure `event instanceof window.Event` is `true`.\nif (typeof window !== \"undefined\" && typeof window.Event !== \"undefined\") {\n Object.setPrototypeOf(Event.prototype, window.Event.prototype)\n\n // Make association for wrappers.\n wrappers.set(window.Event.prototype, Event)\n}\n\n/**\n * Get the property descriptor to redirect a given property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to redirect the property.\n * @private\n */\nfunction defineRedirectDescriptor(key) {\n return {\n get() {\n return pd(this).event[key]\n },\n set(value) {\n pd(this).event[key] = value\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Get the property descriptor to call a given method property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to call the method property.\n * @private\n */\nfunction defineCallDescriptor(key) {\n return {\n value() {\n const event = pd(this).event\n return event[key].apply(event, arguments)\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define new wrapper class.\n * @param {Function} BaseEvent The base wrapper class.\n * @param {Object} proto The prototype of the original event.\n * @returns {Function} The defined wrapper class.\n * @private\n */\nfunction defineWrapper(BaseEvent, proto) {\n const keys = Object.keys(proto)\n if (keys.length === 0) {\n return BaseEvent\n }\n\n /** CustomEvent */\n function CustomEvent(eventTarget, event) {\n BaseEvent.call(this, eventTarget, event)\n }\n\n CustomEvent.prototype = Object.create(BaseEvent.prototype, {\n constructor: { value: CustomEvent, configurable: true, writable: true },\n })\n\n // Define accessors.\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in BaseEvent.prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, key)\n const isFunc = typeof descriptor.value === \"function\"\n Object.defineProperty(\n CustomEvent.prototype,\n key,\n isFunc\n ? defineCallDescriptor(key)\n : defineRedirectDescriptor(key)\n )\n }\n }\n\n return CustomEvent\n}\n\n/**\n * Get the wrapper class of a given prototype.\n * @param {Object} proto The prototype of the original event to get its wrapper.\n * @returns {Function} The wrapper class.\n * @private\n */\nfunction getWrapper(proto) {\n if (proto == null || proto === Object.prototype) {\n return Event\n }\n\n let wrapper = wrappers.get(proto)\n if (wrapper == null) {\n wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto)\n wrappers.set(proto, wrapper)\n }\n return wrapper\n}\n\n/**\n * Wrap a given event to management a dispatching.\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Object} event The event to wrap.\n * @returns {Event} The wrapper instance.\n * @private\n */\nexport function wrapEvent(eventTarget, event) {\n const Wrapper = getWrapper(Object.getPrototypeOf(event))\n return new Wrapper(eventTarget, event)\n}\n\n/**\n * Get the immediateStopped flag of a given event.\n * @param {Event} event The event to get.\n * @returns {boolean} The flag to stop propagation immediately.\n * @private\n */\nexport function isStopped(event) {\n return pd(event).immediateStopped\n}\n\n/**\n * Set the current event phase of a given event.\n * @param {Event} event The event to set current target.\n * @param {number} eventPhase New event phase.\n * @returns {void}\n * @private\n */\nexport function setEventPhase(event, eventPhase) {\n pd(event).eventPhase = eventPhase\n}\n\n/**\n * Set the current target of a given event.\n * @param {Event} event The event to set current target.\n * @param {EventTarget|null} currentTarget New current target.\n * @returns {void}\n * @private\n */\nexport function setCurrentTarget(event, currentTarget) {\n pd(event).currentTarget = currentTarget\n}\n\n/**\n * Set a passive listener of a given event.\n * @param {Event} event The event to set current target.\n * @param {Function|null} passiveListener New passive listener.\n * @returns {void}\n * @private\n */\nexport function setPassiveListener(event, passiveListener) {\n pd(event).passiveListener = passiveListener\n}\n","import {\n isStopped,\n setCurrentTarget,\n setEventPhase,\n setPassiveListener,\n wrapEvent,\n} from \"./event.mjs\"\n\n/**\n * @typedef {object} ListenerNode\n * @property {Function} listener\n * @property {1|2|3} listenerType\n * @property {boolean} passive\n * @property {boolean} once\n * @property {ListenerNode|null} next\n * @private\n */\n\n/**\n * @type {WeakMap>}\n * @private\n */\nconst listenersMap = new WeakMap()\n\n// Listener types\nconst CAPTURE = 1\nconst BUBBLE = 2\nconst ATTRIBUTE = 3\n\n/**\n * Check whether a given value is an object or not.\n * @param {any} x The value to check.\n * @returns {boolean} `true` if the value is an object.\n */\nfunction isObject(x) {\n return x !== null && typeof x === \"object\" //eslint-disable-line no-restricted-syntax\n}\n\n/**\n * Get listeners.\n * @param {EventTarget} eventTarget The event target to get.\n * @returns {Map} The listeners.\n * @private\n */\nfunction getListeners(eventTarget) {\n const listeners = listenersMap.get(eventTarget)\n if (listeners == null) {\n throw new TypeError(\n \"'this' is expected an EventTarget object, but got another value.\"\n )\n }\n return listeners\n}\n\n/**\n * Get the property descriptor for the event attribute of a given event.\n * @param {string} eventName The event name to get property descriptor.\n * @returns {PropertyDescriptor} The property descriptor.\n * @private\n */\nfunction defineEventAttributeDescriptor(eventName) {\n return {\n get() {\n const listeners = getListeners(this)\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n return node.listener\n }\n node = node.next\n }\n return null\n },\n\n set(listener) {\n if (typeof listener !== \"function\" && !isObject(listener)) {\n listener = null // eslint-disable-line no-param-reassign\n }\n const listeners = getListeners(this)\n\n // Traverse to the tail while removing old value.\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n // Remove old value.\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n node = node.next\n }\n\n // Add new value.\n if (listener !== null) {\n const newNode = {\n listener,\n listenerType: ATTRIBUTE,\n passive: false,\n once: false,\n next: null,\n }\n if (prev === null) {\n listeners.set(eventName, newNode)\n } else {\n prev.next = newNode\n }\n }\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define an event attribute (e.g. `eventTarget.onclick`).\n * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.\n * @param {string} eventName The event name to define.\n * @returns {void}\n */\nfunction defineEventAttribute(eventTargetPrototype, eventName) {\n Object.defineProperty(\n eventTargetPrototype,\n `on${eventName}`,\n defineEventAttributeDescriptor(eventName)\n )\n}\n\n/**\n * Define a custom EventTarget with event attributes.\n * @param {string[]} eventNames Event names for event attributes.\n * @returns {EventTarget} The custom EventTarget.\n * @private\n */\nfunction defineCustomEventTarget(eventNames) {\n /** CustomEventTarget */\n function CustomEventTarget() {\n EventTarget.call(this)\n }\n\n CustomEventTarget.prototype = Object.create(EventTarget.prototype, {\n constructor: {\n value: CustomEventTarget,\n configurable: true,\n writable: true,\n },\n })\n\n for (let i = 0; i < eventNames.length; ++i) {\n defineEventAttribute(CustomEventTarget.prototype, eventNames[i])\n }\n\n return CustomEventTarget\n}\n\n/**\n * EventTarget.\n *\n * - This is constructor if no arguments.\n * - This is a function which returns a CustomEventTarget constructor if there are arguments.\n *\n * For example:\n *\n * class A extends EventTarget {}\n * class B extends EventTarget(\"message\") {}\n * class C extends EventTarget(\"message\", \"error\") {}\n * class D extends EventTarget([\"message\", \"error\"]) {}\n */\nfunction EventTarget() {\n /*eslint-disable consistent-return */\n if (this instanceof EventTarget) {\n listenersMap.set(this, new Map())\n return\n }\n if (arguments.length === 1 && Array.isArray(arguments[0])) {\n return defineCustomEventTarget(arguments[0])\n }\n if (arguments.length > 0) {\n const types = new Array(arguments.length)\n for (let i = 0; i < arguments.length; ++i) {\n types[i] = arguments[i]\n }\n return defineCustomEventTarget(types)\n }\n throw new TypeError(\"Cannot call a class as a function\")\n /*eslint-enable consistent-return */\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEventTarget.prototype = {\n /**\n * Add a given listener to this event target.\n * @param {string} eventName The event name to add.\n * @param {Function} listener The listener to add.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n addEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n if (typeof listener !== \"function\" && !isObject(listener)) {\n throw new TypeError(\"'listener' should be a function or an object.\")\n }\n\n const listeners = getListeners(this)\n const optionsIsObj = isObject(options)\n const capture = optionsIsObj\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n const newNode = {\n listener,\n listenerType,\n passive: optionsIsObj && Boolean(options.passive),\n once: optionsIsObj && Boolean(options.once),\n next: null,\n }\n\n // Set it as the first node if the first node is null.\n let node = listeners.get(eventName)\n if (node === undefined) {\n listeners.set(eventName, newNode)\n return\n }\n\n // Traverse to the tail while checking duplication..\n let prev = null\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n // Should ignore duplication.\n return\n }\n prev = node\n node = node.next\n }\n\n // Add it.\n prev.next = newNode\n },\n\n /**\n * Remove a given listener from this event target.\n * @param {string} eventName The event name to remove.\n * @param {Function} listener The listener to remove.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n removeEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n\n const listeners = getListeners(this)\n const capture = isObject(options)\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n return\n }\n\n prev = node\n node = node.next\n }\n },\n\n /**\n * Dispatch a given event.\n * @param {Event|{type:string}} event The event to dispatch.\n * @returns {boolean} `false` if canceled.\n */\n dispatchEvent(event) {\n if (event == null || typeof event.type !== \"string\") {\n throw new TypeError('\"event.type\" should be a string.')\n }\n\n // If listeners aren't registered, terminate.\n const listeners = getListeners(this)\n const eventName = event.type\n let node = listeners.get(eventName)\n if (node == null) {\n return true\n }\n\n // Since we cannot rewrite several properties, so wrap object.\n const wrappedEvent = wrapEvent(this, event)\n\n // This doesn't process capturing phase and bubbling phase.\n // This isn't participating in a tree.\n let prev = null\n while (node != null) {\n // Remove this listener if it's once\n if (node.once) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n // Call this listener\n setPassiveListener(\n wrappedEvent,\n node.passive ? node.listener : null\n )\n if (typeof node.listener === \"function\") {\n try {\n node.listener.call(this, wrappedEvent)\n } catch (err) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(err)\n }\n }\n } else if (\n node.listenerType !== ATTRIBUTE &&\n typeof node.listener.handleEvent === \"function\"\n ) {\n node.listener.handleEvent(wrappedEvent)\n }\n\n // Break if `event.stopImmediatePropagation` was called.\n if (isStopped(wrappedEvent)) {\n break\n }\n\n node = node.next\n }\n setPassiveListener(wrappedEvent, null)\n setEventPhase(wrappedEvent, 0)\n setCurrentTarget(wrappedEvent, null)\n\n return !wrappedEvent.defaultPrevented\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(EventTarget.prototype, \"constructor\", {\n value: EventTarget,\n configurable: true,\n writable: true,\n})\n\n// Ensure `eventTarget instanceof window.EventTarget` is `true`.\nif (\n typeof window !== \"undefined\" &&\n typeof window.EventTarget !== \"undefined\"\n) {\n Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype)\n}\n\nexport { defineEventAttribute, EventTarget }\nexport default EventTarget\n"],"names":["pd","event","retv","privateData","get","console","assert","setCancelFlag","data","passiveListener","cancelable","canceled","preventDefault","error","Event","eventTarget","set","eventPhase","currentTarget","stopped","immediateStopped","timeStamp","Date","now","Object","defineProperty","value","enumerable","key","keys","i","length","defineRedirectDescriptor","configurable","defineCallDescriptor","apply","arguments","defineWrapper","BaseEvent","proto","CustomEvent","call","prototype","create","constructor","writable","descriptor","getOwnPropertyDescriptor","isFunc","getWrapper","wrapper","wrappers","getPrototypeOf","wrapEvent","Wrapper","isStopped","setEventPhase","setCurrentTarget","setPassiveListener","isObject","x","_typeof","getListeners","listeners","listenersMap","TypeError","defineEventAttributeDescriptor","eventName","node","listenerType","listener","next","prev","delete","newNode","passive","once","defineEventAttribute","eventTargetPrototype","defineCustomEventTarget","eventNames","CustomEventTarget","EventTarget","Map","Array","isArray","types","WeakMap","type","target","composedPath","NONE","CAPTURING_PHASE","AT_TARGET","BUBBLING_PHASE","stopPropagation","stopImmediatePropagation","bubbles","defaultPrevented","composed","srcElement","cancelBubble","returnValue","initEvent","window","setPrototypeOf","CAPTURE","BUBBLE","addEventListener","options","optionsIsObj","capture","removeEventListener","dispatchEvent","wrappedEvent","err","handleEvent"],"mappings":";;;;wbAkCA,QAASA,CAAAA,CAAT,CAAYC,CAAZ,CAAmB,IACTC,CAAAA,CAAI,CAAGC,CAAW,CAACC,GAAZD,CAAgBF,CAAhBE,QACbE,CAAAA,OAAO,CAACC,MAARD,CACY,IAARH,EAAAA,CADJG,CAEI,6CAFJA,CAGIJ,CAHJI,EAKOH,EAOX,QAASK,CAAAA,CAAT,CAAuBC,CAAvB,CAA6B,OACG,KAAxBA,EAAAA,CAAI,CAACC,eADgB,MAarB,CAACD,CAAI,CAACP,KAALO,CAAWE,UAbS,GAiBzBF,CAA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,CAAAA,OAAO,CAACQ,KAHT,EAKNR,OAAO,CAACQ,KAARR,CAAc8G,CAAd9G,MAIR+D,CAAAA,CAAI,CAACC,YAALD,GA/TE,CA+TFA,EACqC,UAArC,QAAOA,CAAAA,CAAI,CAACE,QAALF,CAAcgD,aAErBhD,CAAI,CAACE,QAALF,CAAcgD,WAAdhD,CAA0B8C,CAA1B9C,KAIAb,CAAS,CAAC2D,CAAD,QAIb9C,CAAI,CAAGA,CAAI,CAACG,WAEhBb,CAAAA,CAAkB,CAACwD,CAAD,CAAe,IAAf,EAClB1D,CAAa,CAAC0D,CAAD,CAAe,CAAf,EACbzD,CAAgB,CAACyD,CAAD,CAAe,IAAf,EAET,CAACA,CAAY,CAAChB,iBAvKL,EA4KxB1E,MAAM,CAACC,cAAPD,CAAsB0D,CAAW,CAACxC,SAAlClB,CAA6C,aAA7CA,CAA4D,CACxDE,KAAK,CAAEwD,CADiD,CAExDjD,YAAY,GAF4C,CAGxDY,QAAQ,GAHgD,CAA5DrB,EAQsB,WAAlB,QAAOgF,CAAAA,MAAP,EAC8B,WAA9B,QAAOA,CAAAA,MAAM,CAACtB,aAEd1D,MAAM,CAACiF,cAAPjF,CAAsB0D,CAAW,CAACxC,SAAlClB,CAA6CgF,MAAM,CAACtB,WAAPsB,CAAmB9D,SAAhElB"} \ No newline at end of file diff --git a/node_modules/event-target-shim/index.d.ts b/node_modules/event-target-shim/index.d.ts new file mode 100644 index 0000000..a303097 --- /dev/null +++ b/node_modules/event-target-shim/index.d.ts @@ -0,0 +1,399 @@ +export as namespace EventTargetShim + +/** + * `Event` interface. + * @see https://dom.spec.whatwg.org/#event + */ +export interface Event { + /** + * The type of this event. + */ + readonly type: string + + /** + * The target of this event. + */ + readonly target: EventTarget<{}, {}, "standard"> | null + + /** + * The current target of this event. + */ + readonly currentTarget: EventTarget<{}, {}, "standard"> | null + + /** + * The target of this event. + * @deprecated + */ + readonly srcElement: any | null + + /** + * The composed path of this event. + */ + composedPath(): EventTarget<{}, {}, "standard">[] + + /** + * Constant of NONE. + */ + readonly NONE: number + + /** + * Constant of CAPTURING_PHASE. + */ + readonly CAPTURING_PHASE: number + + /** + * Constant of BUBBLING_PHASE. + */ + readonly BUBBLING_PHASE: number + + /** + * Constant of AT_TARGET. + */ + readonly AT_TARGET: number + + /** + * Indicates which phase of the event flow is currently being evaluated. + */ + readonly eventPhase: number + + /** + * Stop event bubbling. + */ + stopPropagation(): void + + /** + * Stop event bubbling. + */ + stopImmediatePropagation(): void + + /** + * Initialize event. + * @deprecated + */ + initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void + + /** + * The flag indicating bubbling. + */ + readonly bubbles: boolean + + /** + * Stop event bubbling. + * @deprecated + */ + cancelBubble: boolean + + /** + * Set or get cancellation flag. + * @deprecated + */ + returnValue: boolean + + /** + * The flag indicating whether the event can be canceled. + */ + readonly cancelable: boolean + + /** + * Cancel this event. + */ + preventDefault(): void + + /** + * The flag to indicating whether the event was canceled. + */ + readonly defaultPrevented: boolean + + /** + * The flag to indicating if event is composed. + */ + readonly composed: boolean + + /** + * Indicates whether the event was dispatched by the user agent. + */ + readonly isTrusted: boolean + + /** + * The unix time of this event. + */ + readonly timeStamp: number +} + +/** + * The constructor of `EventTarget` interface. + */ +export type EventTargetConstructor< + TEvents extends EventTarget.EventDefinition = {}, + TEventAttributes extends EventTarget.EventDefinition = {}, + TMode extends EventTarget.Mode = "loose" +> = { + prototype: EventTarget + new(): EventTarget +} + +/** + * `EventTarget` interface. + * @see https://dom.spec.whatwg.org/#interface-eventtarget + */ +export type EventTarget< + TEvents extends EventTarget.EventDefinition = {}, + TEventAttributes extends EventTarget.EventDefinition = {}, + TMode extends EventTarget.Mode = "loose" +> = EventTarget.EventAttributes & { + /** + * Add a given listener to this event target. + * @param eventName The event name to add. + * @param listener The listener to add. + * @param options The options for this listener. + */ + addEventListener>( + type: TEventType, + listener: + | EventTarget.Listener> + | null, + options?: boolean | EventTarget.AddOptions + ): void + + /** + * Remove a given listener from this event target. + * @param eventName The event name to remove. + * @param listener The listener to remove. + * @param options The options for this listener. + */ + removeEventListener>( + type: TEventType, + listener: + | EventTarget.Listener> + | null, + options?: boolean | EventTarget.RemoveOptions + ): void + + /** + * Dispatch a given event. + * @param event The event to dispatch. + * @returns `false` if canceled. + */ + dispatchEvent>( + event: EventTarget.EventData + ): boolean +} + +export const EventTarget: EventTargetConstructor & { + /** + * Create an `EventTarget` instance with detailed event definition. + * + * The detailed event definition requires to use `defineEventAttribute()` + * function later. + * + * Unfortunately, the second type parameter `TEventAttributes` was needed + * because we cannot compute string literal types. + * + * @example + * const signal = new EventTarget<{ abort: Event }, { onabort: Event }>() + * defineEventAttribute(signal, "abort") + */ + new < + TEvents extends EventTarget.EventDefinition, + TEventAttributes extends EventTarget.EventDefinition, + TMode extends EventTarget.Mode = "loose" + >(): EventTarget + + /** + * Define an `EventTarget` constructor with attribute events and detailed event definition. + * + * Unfortunately, the second type parameter `TEventAttributes` was needed + * because we cannot compute string literal types. + * + * @example + * class AbortSignal extends EventTarget<{ abort: Event }, { onabort: Event }>("abort") { + * abort(): void {} + * } + * + * @param events Optional event attributes (e.g. passing in `"click"` adds `onclick` to prototype). + */ + < + TEvents extends EventTarget.EventDefinition = {}, + TEventAttributes extends EventTarget.EventDefinition = {}, + TMode extends EventTarget.Mode = "loose" + >(events: string[]): EventTargetConstructor< + TEvents, + TEventAttributes, + TMode + > + + /** + * Define an `EventTarget` constructor with attribute events and detailed event definition. + * + * Unfortunately, the second type parameter `TEventAttributes` was needed + * because we cannot compute string literal types. + * + * @example + * class AbortSignal extends EventTarget<{ abort: Event }, { onabort: Event }>("abort") { + * abort(): void {} + * } + * + * @param events Optional event attributes (e.g. passing in `"click"` adds `onclick` to prototype). + */ + < + TEvents extends EventTarget.EventDefinition = {}, + TEventAttributes extends EventTarget.EventDefinition = {}, + TMode extends EventTarget.Mode = "loose" + >(event0: string, ...events: string[]): EventTargetConstructor< + TEvents, + TEventAttributes, + TMode + > +} + +export namespace EventTarget { + /** + * Options of `removeEventListener()` method. + */ + export interface RemoveOptions { + /** + * The flag to indicate that the listener is for the capturing phase. + */ + capture?: boolean + } + + /** + * Options of `addEventListener()` method. + */ + export interface AddOptions extends RemoveOptions { + /** + * The flag to indicate that the listener doesn't support + * `event.preventDefault()` operation. + */ + passive?: boolean + /** + * The flag to indicate that the listener will be removed on the first + * event. + */ + once?: boolean + } + + /** + * The type of regular listeners. + */ + export interface FunctionListener { + (event: TEvent): void + } + + /** + * The type of object listeners. + */ + export interface ObjectListener { + handleEvent(event: TEvent): void + } + + /** + * The type of listeners. + */ + export type Listener = + | FunctionListener + | ObjectListener + + /** + * Event definition. + */ + export type EventDefinition = { + readonly [key: string]: Event + } + + /** + * Mapped type for event attributes. + */ + export type EventAttributes = { + [P in keyof TEventAttributes]: + | FunctionListener + | null + } + + /** + * The type of event data for `dispatchEvent()` method. + */ + export type EventData< + TEvents extends EventDefinition, + TEventType extends keyof TEvents | string, + TMode extends Mode + > = + TEventType extends keyof TEvents + ? ( + // Require properties which are not generated automatically. + & Pick< + TEvents[TEventType], + Exclude + > + // Properties which are generated automatically are optional. + & Partial> + ) + : ( + TMode extends "standard" + ? Event + : Event | NonStandardEvent + ) + + /** + * The string literal types of the properties which are generated + * automatically in `dispatchEvent()` method. + */ + export type OmittableEventKeys = Exclude + + /** + * The type of event data. + */ + export type NonStandardEvent = { + [key: string]: any + type: string + } + + /** + * The type of listeners. + */ + export type PickEvent< + TEvents extends EventDefinition, + TEventType extends keyof TEvents | string, + > = + TEventType extends keyof TEvents + ? TEvents[TEventType] + : Event + + /** + * Event type candidates. + */ + export type EventType< + TEvents extends EventDefinition, + TMode extends Mode + > = + TMode extends "strict" + ? keyof TEvents + : keyof TEvents | string + + /** + * - `"strict"` ..... Methods don't accept unknown events. + * `dispatchEvent()` accepts partial objects. + * - `"loose"` ...... Methods accept unknown events. + * `dispatchEvent()` accepts partial objects. + * - `"standard"` ... Methods accept unknown events. + * `dispatchEvent()` doesn't accept partial objects. + */ + export type Mode = "strict" | "standard" | "loose" +} + +/** + * Specialized `type` property. + */ +export type Type = { type: T } + +/** + * Define an event attribute (e.g. `eventTarget.onclick`). + * @param prototype The event target prototype to define an event attribute. + * @param eventName The event name to define. + */ +export function defineEventAttribute( + prototype: EventTarget, + eventName: string +): void + +export default EventTarget diff --git a/node_modules/event-target-shim/package.json b/node_modules/event-target-shim/package.json new file mode 100644 index 0000000..40326f3 --- /dev/null +++ b/node_modules/event-target-shim/package.json @@ -0,0 +1,82 @@ +{ + "name": "event-target-shim", + "version": "5.0.1", + "description": "An implementation of WHATWG EventTarget interface.", + "main": "dist/event-target-shim", + "types": "index.d.ts", + "files": [ + "dist", + "index.d.ts" + ], + "engines": { + "node": ">=6" + }, + "scripts": { + "preversion": "npm test", + "version": "npm run build && git add dist/*", + "postversion": "git push && git push --tags", + "clean": "rimraf .nyc_output coverage", + "coverage": "nyc report --reporter lcov && opener coverage/lcov-report/index.html", + "lint": "eslint src test scripts --ext .js,.mjs", + "build": "rollup -c scripts/rollup.config.js", + "pretest": "npm run lint", + "test": "run-s test:*", + "test:mocha": "nyc --require ./scripts/babel-register mocha test/*.mjs", + "test:karma": "karma start scripts/karma.conf.js --single-run", + "watch": "run-p watch:*", + "watch:mocha": "mocha test/*.mjs --require ./scripts/babel-register --watch --watch-extensions js,mjs --growl", + "watch:karma": "karma start scripts/karma.conf.js --watch", + "codecov": "codecov" + }, + "devDependencies": { + "@babel/core": "^7.2.2", + "@babel/plugin-transform-modules-commonjs": "^7.2.0", + "@babel/preset-env": "^7.2.3", + "@babel/register": "^7.0.0", + "@mysticatea/eslint-plugin": "^8.0.1", + "@mysticatea/spy": "^0.1.2", + "assert": "^1.4.1", + "codecov": "^3.1.0", + "eslint": "^5.12.1", + "karma": "^3.1.4", + "karma-chrome-launcher": "^2.2.0", + "karma-coverage": "^1.1.2", + "karma-firefox-launcher": "^1.0.0", + "karma-growl-reporter": "^1.0.0", + "karma-ie-launcher": "^1.0.0", + "karma-mocha": "^1.3.0", + "karma-rollup-preprocessor": "^7.0.0-rc.2", + "mocha": "^5.2.0", + "npm-run-all": "^4.1.5", + "nyc": "^13.1.0", + "opener": "^1.5.1", + "rimraf": "^2.6.3", + "rollup": "^1.1.1", + "rollup-plugin-babel": "^4.3.2", + "rollup-plugin-babel-minify": "^7.0.0", + "rollup-plugin-commonjs": "^9.2.0", + "rollup-plugin-json": "^3.1.0", + "rollup-plugin-node-resolve": "^4.0.0", + "rollup-watch": "^4.3.1", + "type-tester": "^1.0.0", + "typescript": "^3.2.4" + }, + "repository": { + "type": "git", + "url": "https://github.com/mysticatea/event-target-shim.git" + }, + "keywords": [ + "w3c", + "whatwg", + "eventtarget", + "event", + "events", + "shim" + ], + "author": "Toru Nagashima", + "license": "MIT", + "bugs": { + "url": "https://github.com/mysticatea/event-target-shim/issues" + }, + "homepage": "https://github.com/mysticatea/event-target-shim" +} diff --git a/node_modules/extend/.editorconfig b/node_modules/extend/.editorconfig new file mode 100644 index 0000000..bc228f8 --- /dev/null +++ b/node_modules/extend/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/node_modules/extend/.eslintrc b/node_modules/extend/.eslintrc new file mode 100644 index 0000000..a34cf28 --- /dev/null +++ b/node_modules/extend/.eslintrc @@ -0,0 +1,17 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "complexity": [2, 20], + "eqeqeq": [2, "allow-null"], + "func-name-matching": [1], + "max-depth": [1, 4], + "max-statements": [2, 26], + "no-extra-parens": [1], + "no-magic-numbers": [0], + "no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "DebuggerStatement", "LabeledStatement", "WithStatement"], + "sort-keys": [0], + } +} diff --git a/node_modules/extend/.jscs.json b/node_modules/extend/.jscs.json new file mode 100644 index 0000000..3cce01d --- /dev/null +++ b/node_modules/extend/.jscs.json @@ -0,0 +1,175 @@ +{ + "es3": true, + + "additionalRules": [], + + "requireSemicolons": true, + + "disallowMultipleSpaces": true, + + "disallowIdentifierNames": [], + + "requireCurlyBraces": { + "allExcept": [], + "keywords": ["if", "else", "for", "while", "do", "try", "catch"] + }, + + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], + + "disallowSpaceAfterKeywords": [], + + "disallowSpaceBeforeComma": true, + "disallowSpaceAfterComma": false, + "disallowSpaceBeforeSemicolon": true, + + "disallowNodeTypes": [ + "DebuggerStatement", + "LabeledStatement", + "SwitchCase", + "SwitchStatement", + "WithStatement" + ], + + "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, + + "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, + "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, + "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, + + "requireSpaceBetweenArguments": true, + + "disallowSpacesInsideParentheses": true, + + "disallowSpacesInsideArrayBrackets": true, + + "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, + + "disallowSpaceAfterObjectKeys": true, + + "requireCommaBeforeLineBreak": true, + + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "requireSpaceAfterPrefixUnaryOperators": [], + + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "requireSpaceBeforePostfixUnaryOperators": [], + + "disallowSpaceBeforeBinaryOperators": [], + "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + + "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + "disallowSpaceAfterBinaryOperators": [], + + "disallowImplicitTypeConversion": ["binary", "string"], + + "disallowKeywords": ["with", "eval"], + + "requireKeywordsOnNewLine": [], + "disallowKeywordsOnNewLine": ["else"], + + "requireLineFeedAtFileEnd": true, + + "disallowTrailingWhitespace": true, + + "disallowTrailingComma": true, + + "excludeFiles": ["node_modules/**", "vendor/**"], + + "disallowMultipleLineStrings": true, + + "requireDotNotation": { "allExcept": ["keywords"] }, + + "requireParenthesesAroundIIFE": true, + + "validateLineBreaks": "LF", + + "validateQuoteMarks": { + "escape": true, + "mark": "'" + }, + + "disallowOperatorBeforeLineBreak": [], + + "requireSpaceBeforeKeywords": [ + "do", + "for", + "if", + "else", + "switch", + "case", + "try", + "catch", + "finally", + "while", + "with", + "return" + ], + + "validateAlignedFunctionParameters": { + "lineBreakAfterOpeningBraces": true, + "lineBreakBeforeClosingBraces": true + }, + + "requirePaddingNewLinesBeforeExport": true, + + "validateNewlineAfterArrayElements": { + "maximum": 6 + }, + + "requirePaddingNewLinesAfterUseStrict": true, + + "disallowArrowFunctions": true, + + "disallowMultiLineTernary": true, + + "validateOrderInObjectKeys": false, + + "disallowIdenticalDestructuringNames": true, + + "disallowNestedTernaries": { "maxLevel": 1 }, + + "requireSpaceAfterComma": { "allExcept": ["trailing"] }, + "requireAlignedMultilineParams": false, + + "requireSpacesInGenerator": { + "afterStar": true + }, + + "disallowSpacesInGenerator": { + "beforeStar": true + }, + + "disallowVar": false, + + "requireArrayDestructuring": false, + + "requireEnhancedObjectLiterals": false, + + "requireObjectDestructuring": false, + + "requireEarlyReturn": false, + + "requireCapitalizedConstructorsNew": { + "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] + }, + + "requireImportAlphabetized": false, + + "requireSpaceBeforeObjectValues": true, + "requireSpaceBeforeDestructuredValues": true, + + "disallowSpacesInsideTemplateStringPlaceholders": true, + + "disallowArrayDestructuringReturn": false, + + "requireNewlineBeforeSingleStatementsInIf": false, + + "disallowUnusedVariables": true, + + "requireSpacesInsideImportedObjectBraces": true, + + "requireUseStrict": true +} + diff --git a/node_modules/extend/.travis.yml b/node_modules/extend/.travis.yml new file mode 100644 index 0000000..5ccdfc4 --- /dev/null +++ b/node_modules/extend/.travis.yml @@ -0,0 +1,230 @@ +language: node_js +os: + - linux +node_js: + - "10.7" + - "9.11" + - "8.11" + - "7.10" + - "6.14" + - "5.12" + - "4.9" + - "iojs-v3.3" + - "iojs-v2.5" + - "iojs-v1.8" + - "0.12" + - "0.10" + - "0.8" +before_install: + - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' + - 'nvm install-latest-npm' +install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "lts/*" + env: PRETEST=true + - node_js: "lts/*" + env: POSTTEST=true + - node_js: "4" + env: COVERAGE=true + - node_js: "10.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true diff --git a/node_modules/extend/CHANGELOG.md b/node_modules/extend/CHANGELOG.md new file mode 100644 index 0000000..2cf7de6 --- /dev/null +++ b/node_modules/extend/CHANGELOG.md @@ -0,0 +1,83 @@ +3.0.2 / 2018-07-19 +================== + * [Fix] Prevent merging `__proto__` property (#48) + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` + * [Tests] up to `node` `v10.7`, `v9.11`, `v8.11`, `v7.10`, `v6.14`, `v4.9`; use `nvm install-latest-npm` + +3.0.1 / 2017-04-27 +================== + * [Fix] deep extending should work with a non-object (#46) + * [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config` + * [Tests] up to `node` `v7.9`, `v6.10`, `v4.8`; improve matrix + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. + * [Docs] Add example to readme (#34) + +3.0.0 / 2015-07-01 +================== + * [Possible breaking change] Use global "strict" directive (#32) + * [Tests] `int` is an ES3 reserved word + * [Tests] Test up to `io.js` `v2.3` + * [Tests] Add `npm run eslint` + * [Dev Deps] Update `covert`, `jscs` + +2.0.1 / 2015-04-25 +================== + * Use an inline `isArray` check, for ES3 browsers. (#27) + * Some old browsers fail when an identifier is `toString` + * Test latest `node` and `io.js` versions on `travis-ci`; speed up builds + * Add license info to package.json (#25) + * Update `tape`, `jscs` + * Adding a CHANGELOG + +2.0.0 / 2014-10-01 +================== + * Increase code coverage to 100%; run code coverage as part of tests + * Add `npm run lint`; Run linter as part of tests + * Remove nodeType and setInterval checks in isPlainObject + * Updating `tape`, `jscs`, `covert` + * General style and README cleanup + +1.3.0 / 2014-06-20 +================== + * Add component.json for browser support (#18) + * Use SVG for badges in README (#16) + * Updating `tape`, `covert` + * Updating travis-ci to work with multiple node versions + * Fix `deep === false` bug (returning target as {}) (#14) + * Fixing constructor checks in isPlainObject + * Adding additional test coverage + * Adding `npm run coverage` + * Add LICENSE (#13) + * Adding a warning about `false`, per #11 + * General style and whitespace cleanup + +1.2.1 / 2013-09-14 +================== + * Fixing hasOwnProperty bugs that would only have shown up in specific browsers. Fixes #8 + * Updating `tape` + +1.2.0 / 2013-09-02 +================== + * Updating the README: add badges + * Adding a missing variable reference. + * Using `tape` instead of `buster` for tests; add more tests (#7) + * Adding node 0.10 to Travis CI (#6) + * Enabling "npm test" and cleaning up package.json (#5) + * Add Travis CI. + +1.1.3 / 2012-12-06 +================== + * Added unit tests. + * Ensure extend function is named. (Looks nicer in a stack trace.) + * README cleanup. + +1.1.1 / 2012-11-07 +================== + * README cleanup. + * Added installation instructions. + * Added a missing semicolon + +1.0.0 / 2012-04-08 +================== + * Initial commit + diff --git a/node_modules/extend/LICENSE b/node_modules/extend/LICENSE new file mode 100644 index 0000000..e16d6a5 --- /dev/null +++ b/node_modules/extend/LICENSE @@ -0,0 +1,23 @@ +The MIT License (MIT) + +Copyright (c) 2014 Stefan Thomas + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/extend/README.md b/node_modules/extend/README.md new file mode 100644 index 0000000..5b8249a --- /dev/null +++ b/node_modules/extend/README.md @@ -0,0 +1,81 @@ +[![Build Status][travis-svg]][travis-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] + +# extend() for Node.js [![Version Badge][npm-version-png]][npm-url] + +`node-extend` is a port of the classic extend() method from jQuery. It behaves as you expect. It is simple, tried and true. + +Notes: + +* Since Node.js >= 4, + [`Object.assign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) + now offers the same functionality natively (but without the "deep copy" option). + See [ECMAScript 2015 (ES6) in Node.js](https://nodejs.org/en/docs/es6). +* Some native implementations of `Object.assign` in both Node.js and many + browsers (since NPM modules are for the browser too) may not be fully + spec-compliant. + Check [`object.assign`](https://www.npmjs.com/package/object.assign) module for + a compliant candidate. + +## Installation + +This package is available on [npm][npm-url] as: `extend` + +``` sh +npm install extend +``` + +## Usage + +**Syntax:** extend **(** [`deep`], `target`, `object1`, [`objectN`] **)** + +*Extend one object with one or more others, returning the modified object.* + +**Example:** + +``` js +var extend = require('extend'); +extend(targetObject, object1, object2); +``` + +Keep in mind that the target object will be modified, and will be returned from extend(). + +If a boolean true is specified as the first argument, extend performs a deep copy, recursively copying any objects it finds. Otherwise, the copy will share structure with the original object(s). +Undefined properties are not copied. However, properties inherited from the object's prototype will be copied over. +Warning: passing `false` as the first argument is not supported. + +### Arguments + +* `deep` *Boolean* (optional) +If set, the merge becomes recursive (i.e. deep copy). +* `target` *Object* +The object to extend. +* `object1` *Object* +The object that will be merged into the first. +* `objectN` *Object* (Optional) +More objects to merge into the first. + +## License + +`node-extend` is licensed under the [MIT License][mit-license-url]. + +## Acknowledgements + +All credit to the jQuery authors for perfecting this amazing utility. + +Ported to Node.js by [Stefan Thomas][github-justmoon] with contributions by [Jonathan Buchanan][github-insin] and [Jordan Harband][github-ljharb]. + +[travis-svg]: https://travis-ci.org/justmoon/node-extend.svg +[travis-url]: https://travis-ci.org/justmoon/node-extend +[npm-url]: https://npmjs.org/package/extend +[mit-license-url]: http://opensource.org/licenses/MIT +[github-justmoon]: https://github.com/justmoon +[github-insin]: https://github.com/insin +[github-ljharb]: https://github.com/ljharb +[npm-version-png]: http://versionbadg.es/justmoon/node-extend.svg +[deps-svg]: https://david-dm.org/justmoon/node-extend.svg +[deps-url]: https://david-dm.org/justmoon/node-extend +[dev-deps-svg]: https://david-dm.org/justmoon/node-extend/dev-status.svg +[dev-deps-url]: https://david-dm.org/justmoon/node-extend#info=devDependencies + diff --git a/node_modules/extend/component.json b/node_modules/extend/component.json new file mode 100644 index 0000000..1500a2f --- /dev/null +++ b/node_modules/extend/component.json @@ -0,0 +1,32 @@ +{ + "name": "extend", + "author": "Stefan Thomas (http://www.justmoon.net)", + "version": "3.0.0", + "description": "Port of jQuery.extend for node.js and the browser.", + "scripts": [ + "index.js" + ], + "contributors": [ + { + "name": "Jordan Harband", + "url": "https://github.com/ljharb" + } + ], + "keywords": [ + "extend", + "clone", + "merge" + ], + "repository" : { + "type": "git", + "url": "https://github.com/justmoon/node-extend.git" + }, + "dependencies": { + }, + "devDependencies": { + "tape" : "~3.0.0", + "covert": "~0.4.0", + "jscs": "~1.6.2" + } +} + diff --git a/node_modules/extend/index.js b/node_modules/extend/index.js new file mode 100644 index 0000000..2aa3faa --- /dev/null +++ b/node_modules/extend/index.js @@ -0,0 +1,117 @@ +'use strict'; + +var hasOwn = Object.prototype.hasOwnProperty; +var toStr = Object.prototype.toString; +var defineProperty = Object.defineProperty; +var gOPD = Object.getOwnPropertyDescriptor; + +var isArray = function isArray(arr) { + if (typeof Array.isArray === 'function') { + return Array.isArray(arr); + } + + return toStr.call(arr) === '[object Array]'; +}; + +var isPlainObject = function isPlainObject(obj) { + if (!obj || toStr.call(obj) !== '[object Object]') { + return false; + } + + var hasOwnConstructor = hasOwn.call(obj, 'constructor'); + var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); + // Not own constructor property must be Object + if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + var key; + for (key in obj) { /**/ } + + return typeof key === 'undefined' || hasOwn.call(obj, key); +}; + +// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target +var setProperty = function setProperty(target, options) { + if (defineProperty && options.name === '__proto__') { + defineProperty(target, options.name, { + enumerable: true, + configurable: true, + value: options.newValue, + writable: true + }); + } else { + target[options.name] = options.newValue; + } +}; + +// Return undefined instead of __proto__ if '__proto__' is not an own property +var getProperty = function getProperty(obj, name) { + if (name === '__proto__') { + if (!hasOwn.call(obj, name)) { + return void 0; + } else if (gOPD) { + // In early versions of node, obj['__proto__'] is buggy when obj has + // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. + return gOPD(obj, name).value; + } + } + + return obj[name]; +}; + +module.exports = function extend() { + var options, name, src, copy, copyIsArray, clone; + var target = arguments[0]; + var i = 1; + var length = arguments.length; + var deep = false; + + // Handle a deep copy situation + if (typeof target === 'boolean') { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { + target = {}; + } + + for (; i < length; ++i) { + options = arguments[i]; + // Only deal with non-null/undefined values + if (options != null) { + // Extend the base object + for (name in options) { + src = getProperty(target, name); + copy = getProperty(options, name); + + // Prevent never-ending loop + if (target !== copy) { + // Recurse if we're merging plain objects or arrays + if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { + if (copyIsArray) { + copyIsArray = false; + clone = src && isArray(src) ? src : []; + } else { + clone = src && isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); + + // Don't bring in undefined values + } else if (typeof copy !== 'undefined') { + setProperty(target, { name: name, newValue: copy }); + } + } + } + } + } + + // Return the modified object + return target; +}; diff --git a/node_modules/extend/package.json b/node_modules/extend/package.json new file mode 100644 index 0000000..85279f7 --- /dev/null +++ b/node_modules/extend/package.json @@ -0,0 +1,42 @@ +{ + "name": "extend", + "author": "Stefan Thomas (http://www.justmoon.net)", + "version": "3.0.2", + "description": "Port of jQuery.extend for node.js and the browser", + "main": "index", + "scripts": { + "pretest": "npm run lint", + "test": "npm run tests-only", + "posttest": "npm run coverage-quiet", + "tests-only": "node test", + "coverage": "covert test/index.js", + "coverage-quiet": "covert test/index.js --quiet", + "lint": "npm run jscs && npm run eslint", + "jscs": "jscs *.js */*.js", + "eslint": "eslint *.js */*.js" + }, + "contributors": [ + { + "name": "Jordan Harband", + "url": "https://github.com/ljharb" + } + ], + "keywords": [ + "extend", + "clone", + "merge" + ], + "repository": { + "type": "git", + "url": "https://github.com/justmoon/node-extend.git" + }, + "dependencies": {}, + "devDependencies": { + "@ljharb/eslint-config": "^12.2.1", + "covert": "^1.1.0", + "eslint": "^4.19.1", + "jscs": "^3.0.7", + "tape": "^4.9.1" + }, + "license": "MIT" +} diff --git a/node_modules/farmhash-modern/LICENSE b/node_modules/farmhash-modern/LICENSE new file mode 100644 index 0000000..9007003 --- /dev/null +++ b/node_modules/farmhash-modern/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Forbes Lindesay + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/farmhash-modern/README.md b/node_modules/farmhash-modern/README.md new file mode 100644 index 0000000..a2ee1f8 --- /dev/null +++ b/node_modules/farmhash-modern/README.md @@ -0,0 +1,118 @@ +# farmhash-modern + +WASM/Web-Assembly implementation of Google's FarmHash family of very fast hash functions for use in node.js and the browser. FarmHash is the successor to CityHash. Functions in the FarmHash family are not suitable for cryptography. + +The [existing farmhash npm packge](https://github.com/lovell/farmhash) works great if you can get it to build, but this can create a lot of pain. This WASM build should work on any operating system that uses node.js with zero extra configuration. It should be 100% consistent across different platforms. You can even use it in the browser. This package also includes TypeScript types, and a handy `bigqueryFingerprint` that matches BigQuery's `FARM_FINGERPRINT` function. + +This WASM implementation is built using the [farmhash Rust Crate](https://crates.io/crates/farmhash). The 64-bit APIs use JavaScript's BigInt type to represent results. If you need a base-10 string, you can simply call `.toString()` on the result. + +[![Build Status](https://img.shields.io/github/actions/workflow/status/ForbesLindesay/farmhash-modern/test.yml?event=push&style=for-the-badge)](https://github.com/ForbesLindesay/farmhash-modern/actions?query=workflow%3ATest+branch%3Amain) +[![Rolling Versions](https://img.shields.io/badge/Rolling%20Versions-Enabled-brightgreen?style=for-the-badge)](https://rollingversions.com/ForbesLindesay/farmhash-modern) +[![NPM version](https://img.shields.io/npm/v/farmhash-modern?style=for-the-badge)](https://www.npmjs.com/package/farmhash-modern) + +[Click here for a live demo](https://farmhash.forbeslindesay.co.uk) + +## Node.js + +### Installation + +Install using npm or yarn. + +```sh +npm install farmhash-modern +# or +yarn install farmhash-modern +``` + +### Usage + +Import using ES Module syntax or CommonJS syntax. + +```typescript +import * as farmhash from 'farmhash-modern'; + +console.log(farmhash.fingerprint32('hello world')); +``` + +or + +```javascript +const farmhash = require('farmhash-modern'); + +console.log(farmhash.fingerprint32('hello world')); +``` + +## Webpack + +### Installation + +```sh +npm install farmhash-modern +# or +yarn install farmhash-modern +``` + +In your `webpack.config.js` file, make sure you have set: + +```js +module.exports = { + // ... + experiments: {asyncWebAssembly: true}, + // ... +}; +``` + +Also, make sure you do not have any rules that will capture `.wasm` files and turn them into URLs or some other format. + +### Usage + +Import using ES Module syntax syntax. + +```typescript +import * as farmhash from 'farmhash-modern'; + +console.log(farmhash.fingerprint32('hello world')); +``` + +## API + +### `fingerprint32(input: string | Uint8Array): number` + +Create a new farmhash based u32 for a string or an array of bytes. Fingerprint value should be portable and stable across library versions and platforms. + +### `fingerprint64(input: string | Uint8Array): bigint` + +Create a new farmhash based u64 for a string or an array of bytes. Fingerprint value should be portable and stable across library versions and platforms. + +### `bigqueryFingerprint(input: string | Uint8Array): bigint` + +Create a new farmhash based i64 for a string or an array of bytes. Fingerprint value should be portable and stable across library versions and platforms. + +This matches the format used by BigQuery's FARM_FINGERPRINT function. + +### `hash32(input: string | Uint8Array): number` + +Create a new farmhash based u32 for an array of bytes. Hash value may vary with library version. + +### `hash32WithSeed(input: string | Uint8Array, seed: number): number + +Create a new farmhash based u32 for an array of bytes with a given seed. Hash value may vary with library version. + +### `hash64(input: string | Uint8Array): bigint` + +Create a new farmhash based u64 for an array of bytes. Hash value may vary with library version. + +### `hash64WithSeed(input: string | Uint8Array, seed: bigint): bigint + +Create a new farmhash based u64 for an array of bytes with a given seed. Hash value may vary with library version. + +## Building the web-app example + +1. Install dependencies for farmhash-modern: `yarn install` +2. Build farmhash-modern: `yarn build` +3. Install dependencies for web-app: `cd web-app && npm install` +4. Build the web-app: `cd web-app && npm build` + +## License + +MIT diff --git a/node_modules/farmhash-modern/bin/bundler/farmhash_modern.js b/node_modules/farmhash-modern/bin/bundler/farmhash_modern.js new file mode 100644 index 0000000..2bff5f4 --- /dev/null +++ b/node_modules/farmhash-modern/bin/bundler/farmhash_modern.js @@ -0,0 +1,4 @@ +import * as wasm from "./farmhash_modern_bg.wasm"; +import { __wbg_set_wasm } from "./farmhash_modern_bg.js"; +__wbg_set_wasm(wasm); +export * from "./farmhash_modern_bg.js"; diff --git a/node_modules/farmhash-modern/bin/bundler/farmhash_modern_bg.js b/node_modules/farmhash-modern/bin/bundler/farmhash_modern_bg.js new file mode 100644 index 0000000..d634884 --- /dev/null +++ b/node_modules/farmhash-modern/bin/bundler/farmhash_modern_bg.js @@ -0,0 +1,235 @@ +let wasm; +export function __wbg_set_wasm(val) { + wasm = val; +} + + +const heap = new Array(128).fill(undefined); + +heap.push(undefined, null, true, false); + +function getObject(idx) { return heap[idx]; } + +let heap_next = heap.length; + +function dropObject(idx) { + if (idx < 132) return; + heap[idx] = heap_next; + heap_next = idx; +} + +function takeObject(idx) { + const ret = getObject(idx); + dropObject(idx); + return ret; +} + +let cachedUint8Memory0 = null; + +function getUint8Memory0() { + if (cachedUint8Memory0 === null || cachedUint8Memory0.byteLength === 0) { + cachedUint8Memory0 = new Uint8Array(wasm.memory.buffer); + } + return cachedUint8Memory0; +} + +let WASM_VECTOR_LEN = 0; + +function passArray8ToWasm0(arg, malloc) { + const ptr = malloc(arg.length * 1, 1) >>> 0; + getUint8Memory0().set(arg, ptr / 1); + WASM_VECTOR_LEN = arg.length; + return ptr; +} +/** +* @param {Uint8Array} input +* @returns {number} +*/ +export function fingerprint32(input) { + const ptr0 = passArray8ToWasm0(input, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.fingerprint32(ptr0, len0); + return ret >>> 0; +} + +/** +* @param {Uint8Array} input +* @returns {bigint} +*/ +export function fingerprint64(input) { + const ptr0 = passArray8ToWasm0(input, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.bigquery_fingerprint(ptr0, len0); + return BigInt.asUintN(64, ret); +} + +/** +* @param {Uint8Array} input +* @returns {bigint} +*/ +export function bigquery_fingerprint(input) { + const ptr0 = passArray8ToWasm0(input, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.bigquery_fingerprint(ptr0, len0); + return ret; +} + +/** +* @param {Uint8Array} input +* @returns {number} +*/ +export function hash32(input) { + const ptr0 = passArray8ToWasm0(input, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.hash32(ptr0, len0); + return ret >>> 0; +} + +/** +* @param {Uint8Array} input +* @param {number} seed +* @returns {number} +*/ +export function hash32_with_seed(input, seed) { + const ptr0 = passArray8ToWasm0(input, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.hash32_with_seed(ptr0, len0, seed); + return ret >>> 0; +} + +/** +* @param {Uint8Array} input +* @returns {bigint} +*/ +export function hash64(input) { + const ptr0 = passArray8ToWasm0(input, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.hash64(ptr0, len0); + return BigInt.asUintN(64, ret); +} + +/** +* @param {Uint8Array} input +* @param {bigint} seed +* @returns {bigint} +*/ +export function hash64_with_seed(input, seed) { + const ptr0 = passArray8ToWasm0(input, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.hash64_with_seed(ptr0, len0, seed); + return BigInt.asUintN(64, ret); +} + +const lTextDecoder = typeof TextDecoder === 'undefined' ? (0, module.require)('util').TextDecoder : TextDecoder; + +let cachedTextDecoder = new lTextDecoder('utf-8', { ignoreBOM: true, fatal: true }); + +cachedTextDecoder.decode(); + +function getStringFromWasm0(ptr, len) { + ptr = ptr >>> 0; + return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len)); +} + +function addHeapObject(obj) { + if (heap_next === heap.length) heap.push(heap.length + 1); + const idx = heap_next; + heap_next = heap[idx]; + + heap[idx] = obj; + return idx; +} + +const lTextEncoder = typeof TextEncoder === 'undefined' ? (0, module.require)('util').TextEncoder : TextEncoder; + +let cachedTextEncoder = new lTextEncoder('utf-8'); + +const encodeString = (typeof cachedTextEncoder.encodeInto === 'function' + ? function (arg, view) { + return cachedTextEncoder.encodeInto(arg, view); +} + : function (arg, view) { + const buf = cachedTextEncoder.encode(arg); + view.set(buf); + return { + read: arg.length, + written: buf.length + }; +}); + +function passStringToWasm0(arg, malloc, realloc) { + + if (realloc === undefined) { + const buf = cachedTextEncoder.encode(arg); + const ptr = malloc(buf.length, 1) >>> 0; + getUint8Memory0().subarray(ptr, ptr + buf.length).set(buf); + WASM_VECTOR_LEN = buf.length; + return ptr; + } + + let len = arg.length; + let ptr = malloc(len, 1) >>> 0; + + const mem = getUint8Memory0(); + + let offset = 0; + + for (; offset < len; offset++) { + const code = arg.charCodeAt(offset); + if (code > 0x7F) break; + mem[ptr + offset] = code; + } + + if (offset !== len) { + if (offset !== 0) { + arg = arg.slice(offset); + } + ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0; + const view = getUint8Memory0().subarray(ptr + offset, ptr + len); + const ret = encodeString(arg, view); + + offset += ret.written; + } + + WASM_VECTOR_LEN = offset; + return ptr; +} + +let cachedInt32Memory0 = null; + +function getInt32Memory0() { + if (cachedInt32Memory0 === null || cachedInt32Memory0.byteLength === 0) { + cachedInt32Memory0 = new Int32Array(wasm.memory.buffer); + } + return cachedInt32Memory0; +} + +export function __wbg_new_abda76e883ba8a5f() { + const ret = new Error(); + return addHeapObject(ret); +}; + +export function __wbg_stack_658279fe44541cf6(arg0, arg1) { + const ret = getObject(arg1).stack; + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len1; + getInt32Memory0()[arg0 / 4 + 0] = ptr1; +}; + +export function __wbg_error_f851667af71bcfc6(arg0, arg1) { + let deferred0_0; + let deferred0_1; + try { + deferred0_0 = arg0; + deferred0_1 = arg1; + console.error(getStringFromWasm0(arg0, arg1)); + } finally { + wasm.__wbindgen_free(deferred0_0, deferred0_1, 1); + } +}; + +export function __wbindgen_object_drop_ref(arg0) { + takeObject(arg0); +}; + diff --git a/node_modules/farmhash-modern/bin/bundler/farmhash_modern_bg.wasm b/node_modules/farmhash-modern/bin/bundler/farmhash_modern_bg.wasm new file mode 100644 index 0000000000000000000000000000000000000000..f1844cae6b42164bdb38a8610eb81231f6b7b440 GIT binary patch literal 28329 zcmd^|3vgW5dEf7A7YpoyxTGi>7HRA5HDghcNa77pNo-uilFZ1o@^qSqN`l~$!Y&99 z3y2h3h@@lDmJ&IBDXkJKGoGnaI}<6fU8SSxC<#6Fq;{h;PR28JJj#rlD2c>E?bw-4$pOwiukU>4JKyk+Xru;~dWStvPiN0kTT+@o(8f~%B?gz`;1B)iwR`s+n{A)C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27cNrxAF5FW%{R7 z@Qc*VTU%f?x#^}`lZc?D>Pw^{=^OdcKb48!ZcEl-?WPSwcthB~LnA|@Lt{hZLlZ-j zLsLWhhlhrThew7-hsTD;hbM+7ho^@3j|`0rkBp3rj*N|rk4%hAj!cd09~~MU9vvAS z9UU7TADtMT9Gx27KQ=TrJT@{mI;KA*HZe9iHZ`_?d}w@ld}Mrdd~AGtd}4fZd}@6E z#L&d>#K^?x#Ms361b;(pVrpXl``$2I(!|w<5e!A_as6ESH?n*G1+pCz(nEOexbl++M$GRGf!(?S)ey*V+ zjM3w(_j1A-o1O3)(iB>_mW{=uIfS=SF3K16x9g9ddH=lkWP9o8eRGZWN>Eu~*!yOW zH~i=aF{r&7RdWr@-=lkuoC!-Nb6$@JF|>Cm+1)X=6NovwXJ~xS=1!pbd`mHFd~dm8tz{$G{~*b@K% literal 0 HcmV?d00001 diff --git a/node_modules/farmhash-modern/bin/nodejs/farmhash_modern.js b/node_modules/farmhash-modern/bin/nodejs/farmhash_modern.js new file mode 100644 index 0000000..406d744 --- /dev/null +++ b/node_modules/farmhash-modern/bin/nodejs/farmhash_modern.js @@ -0,0 +1,238 @@ +let imports = {}; +imports['__wbindgen_placeholder__'] = module.exports; +let wasm; +const { TextDecoder, TextEncoder } = require(`util`); + +const heap = new Array(128).fill(undefined); + +heap.push(undefined, null, true, false); + +function getObject(idx) { return heap[idx]; } + +let heap_next = heap.length; + +function dropObject(idx) { + if (idx < 132) return; + heap[idx] = heap_next; + heap_next = idx; +} + +function takeObject(idx) { + const ret = getObject(idx); + dropObject(idx); + return ret; +} + +let cachedUint8Memory0 = null; + +function getUint8Memory0() { + if (cachedUint8Memory0 === null || cachedUint8Memory0.byteLength === 0) { + cachedUint8Memory0 = new Uint8Array(wasm.memory.buffer); + } + return cachedUint8Memory0; +} + +let WASM_VECTOR_LEN = 0; + +function passArray8ToWasm0(arg, malloc) { + const ptr = malloc(arg.length * 1, 1) >>> 0; + getUint8Memory0().set(arg, ptr / 1); + WASM_VECTOR_LEN = arg.length; + return ptr; +} +/** +* @param {Uint8Array} input +* @returns {number} +*/ +module.exports.fingerprint32 = function(input) { + const ptr0 = passArray8ToWasm0(input, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.fingerprint32(ptr0, len0); + return ret >>> 0; +}; + +/** +* @param {Uint8Array} input +* @returns {bigint} +*/ +module.exports.fingerprint64 = function(input) { + const ptr0 = passArray8ToWasm0(input, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.bigquery_fingerprint(ptr0, len0); + return BigInt.asUintN(64, ret); +}; + +/** +* @param {Uint8Array} input +* @returns {bigint} +*/ +module.exports.bigquery_fingerprint = function(input) { + const ptr0 = passArray8ToWasm0(input, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.bigquery_fingerprint(ptr0, len0); + return ret; +}; + +/** +* @param {Uint8Array} input +* @returns {number} +*/ +module.exports.hash32 = function(input) { + const ptr0 = passArray8ToWasm0(input, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.hash32(ptr0, len0); + return ret >>> 0; +}; + +/** +* @param {Uint8Array} input +* @param {number} seed +* @returns {number} +*/ +module.exports.hash32_with_seed = function(input, seed) { + const ptr0 = passArray8ToWasm0(input, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.hash32_with_seed(ptr0, len0, seed); + return ret >>> 0; +}; + +/** +* @param {Uint8Array} input +* @returns {bigint} +*/ +module.exports.hash64 = function(input) { + const ptr0 = passArray8ToWasm0(input, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.hash64(ptr0, len0); + return BigInt.asUintN(64, ret); +}; + +/** +* @param {Uint8Array} input +* @param {bigint} seed +* @returns {bigint} +*/ +module.exports.hash64_with_seed = function(input, seed) { + const ptr0 = passArray8ToWasm0(input, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.hash64_with_seed(ptr0, len0, seed); + return BigInt.asUintN(64, ret); +}; + +let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); + +cachedTextDecoder.decode(); + +function getStringFromWasm0(ptr, len) { + ptr = ptr >>> 0; + return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len)); +} + +function addHeapObject(obj) { + if (heap_next === heap.length) heap.push(heap.length + 1); + const idx = heap_next; + heap_next = heap[idx]; + + heap[idx] = obj; + return idx; +} + +let cachedTextEncoder = new TextEncoder('utf-8'); + +const encodeString = (typeof cachedTextEncoder.encodeInto === 'function' + ? function (arg, view) { + return cachedTextEncoder.encodeInto(arg, view); +} + : function (arg, view) { + const buf = cachedTextEncoder.encode(arg); + view.set(buf); + return { + read: arg.length, + written: buf.length + }; +}); + +function passStringToWasm0(arg, malloc, realloc) { + + if (realloc === undefined) { + const buf = cachedTextEncoder.encode(arg); + const ptr = malloc(buf.length, 1) >>> 0; + getUint8Memory0().subarray(ptr, ptr + buf.length).set(buf); + WASM_VECTOR_LEN = buf.length; + return ptr; + } + + let len = arg.length; + let ptr = malloc(len, 1) >>> 0; + + const mem = getUint8Memory0(); + + let offset = 0; + + for (; offset < len; offset++) { + const code = arg.charCodeAt(offset); + if (code > 0x7F) break; + mem[ptr + offset] = code; + } + + if (offset !== len) { + if (offset !== 0) { + arg = arg.slice(offset); + } + ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0; + const view = getUint8Memory0().subarray(ptr + offset, ptr + len); + const ret = encodeString(arg, view); + + offset += ret.written; + } + + WASM_VECTOR_LEN = offset; + return ptr; +} + +let cachedInt32Memory0 = null; + +function getInt32Memory0() { + if (cachedInt32Memory0 === null || cachedInt32Memory0.byteLength === 0) { + cachedInt32Memory0 = new Int32Array(wasm.memory.buffer); + } + return cachedInt32Memory0; +} + +module.exports.__wbg_new_abda76e883ba8a5f = function() { + const ret = new Error(); + return addHeapObject(ret); +}; + +module.exports.__wbg_stack_658279fe44541cf6 = function(arg0, arg1) { + const ret = getObject(arg1).stack; + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len1; + getInt32Memory0()[arg0 / 4 + 0] = ptr1; +}; + +module.exports.__wbg_error_f851667af71bcfc6 = function(arg0, arg1) { + let deferred0_0; + let deferred0_1; + try { + deferred0_0 = arg0; + deferred0_1 = arg1; + console.error(getStringFromWasm0(arg0, arg1)); + } finally { + wasm.__wbindgen_free(deferred0_0, deferred0_1, 1); + } +}; + +module.exports.__wbindgen_object_drop_ref = function(arg0) { + takeObject(arg0); +}; + +const path = require('path').join(__dirname, 'farmhash_modern_bg.wasm'); +const bytes = require('fs').readFileSync(path); + +const wasmModule = new WebAssembly.Module(bytes); +const wasmInstance = new WebAssembly.Instance(wasmModule, imports); +wasm = wasmInstance.exports; +module.exports.__wasm = wasm; + diff --git a/node_modules/farmhash-modern/bin/nodejs/farmhash_modern_bg.wasm b/node_modules/farmhash-modern/bin/nodejs/farmhash_modern_bg.wasm new file mode 100644 index 0000000000000000000000000000000000000000..92de9b5911bd07f06e3390a9711883210723db58 GIT binary patch literal 28333 zcmd^|3vgW5dEf7A7YpoyxTGi>7G>-1HDghcNa77pNo-uilFZ1o@^qSqN`l~$!Y&99 z3kVcjh@@lDmSQ=!W2IGMWyUjgYG)!PwyShB9VMZsp44uX#>sf5jz^wx6QxlTr%{@u zR$EQf-~T)JE*9WJiXA)CDLKHo=k=ZMeCIpg>zsSx&90pEJFMlQYD-G<2ikZlpv2%(9DK!(1`i)TeRO{D z*onsC;ZqBbJ?9z8ZYInkJ!8a+BYH9LOXt6Z_y^{&^- z>g-(W@WlAk$mD_Jjj^%uvEjMn6Q2J{{Tl7|Qv2}nsqx{7iOJdHlfy^nj?Z1KpJAD! zzjU)-$ z)vE9JdVa6(`%%e{qA>Km-crbl(8>?JfP&B~l>o{=Kd5*fNl#BtM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unn^$Er_4_e zKNWsdFBz%wK7J%Wm7h)CI==#coJr-4=kH-7xW9^&*l3RCOUIMs=oyTt#3^>*{b+COT}!$^Dw=OK z6s$M+Jxu)|^*@s1H#fT|Gw9^fvH9a?lGS@Khh%jnvbvJv?WL2D%}QDjoqGQA(Xl6i zF?N|TI_((e1=?IsoA>e~Iu!W~#;mP5t;R7Q>Bf}#jBcmf@BjY0zBapB$eWKQJ*g zF+4FcF*-3eF+RZ`5u2ErI50UhIXpQsIXXEuIX*ctIXO8sd0=X2YItg7YIJIBYJ6&9 zYI167>c9a|Jizb=0DXXN2PkUK@|U|3%;okfW;5n~k}Tc3n!vHH2IDYUS(u+|s0d^9 z#Oghqu*PO5yoNM|7OrJu@mLPwZIp}hMg491t7qOn?>*ICI(F||qrDPT78v&4*%J*v z`auk8uSV5e1M~OT-lJ#2lF6Lc<3SAV8%p+cjO_$sj_w^A-#a>dQ~C7l0?o=e8VB|b z)lT#G<@V-(=WWN(zL9-XlgXarL;N|n#^})lH+i=VFvAm#)x*adv&g^3N^tYQ$$M94 bk1jO!o>*8qI=irPb7f`z#Nyt@eXIW$s>> 0) { + return input; + } + throw new Error(`Expected input to be a 32-bit unsigned integer, got ${input}`); +} +function asUnsigned64BitNumber(input) { + if (typeof input === 'bigint' && + input >= 0 && + input <= 18446744073709551615n) { + return input; + } + throw new Error(`Expected input to be a 64-bit unsigned integer, got ${input}`); +} +/** + * Create a new farmhash based u32 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + */ +export function fingerprint32(input) { + return farmhash.fingerprint32(asBuffer(input)); +} +/** + * Create a new farmhash based u64 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + */ +export function fingerprint64(input) { + return farmhash.fingerprint64(asBuffer(input)); +} +/** + * Create a new farmhash based i64 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + * + * This matches the format used by BigQuery's FARM_FINGERPRINT function. + */ +export function bigqueryFingerprint(input) { + return farmhash.bigquery_fingerprint(asBuffer(input)); +} +/** + * Create a new farmhash based u32 for an array of bytes. Hash value may + * vary with library version. + */ +export function hash32(input) { + return farmhash.hash32(asBuffer(input)); +} +/** + * Create a new farmhash based u32 for an array of bytes with a given seed. + * Hash value may vary with library version. + */ +export function hash32WithSeed(input, seed) { + return farmhash.hash32_with_seed(asBuffer(input), asUnsigned32BitNumber(seed)); +} +/** + * Create a new farmhash based u64 for an array of bytes. Hash value may + * vary with library version. + */ +export function hash64(input) { + return farmhash.hash64(asBuffer(input)); +} +/** + * Create a new farmhash based u64 for an array of bytes with a given seed. + * Hash value may vary with library version. + */ +export function hash64WithSeed(input, seed) { + return farmhash.hash64_with_seed(asBuffer(input), asUnsigned64BitNumber(seed)); +} diff --git a/node_modules/farmhash-modern/lib/index.cjs b/node_modules/farmhash-modern/lib/index.cjs new file mode 100644 index 0000000..476280f --- /dev/null +++ b/node_modules/farmhash-modern/lib/index.cjs @@ -0,0 +1,78 @@ +const farmhash = require('../bin/nodejs/farmhash_modern.js') +function asBuffer(input) { + if (typeof input === 'string') { + return new TextEncoder().encode(input); + } + if (input instanceof Uint8Array) { + return input; + } + throw new Error('Expected input to be a string or Uint8Array'); +} +function asUnsigned32BitNumber(input) { + if (input === input >>> 0) { + return input; + } + throw new Error(`Expected input to be a 32-bit unsigned integer, got ${input}`); +} +function asUnsigned64BitNumber(input) { + if (typeof input === 'bigint' && + input >= 0 && + input <= 18446744073709551615n) { + return input; + } + throw new Error(`Expected input to be a 64-bit unsigned integer, got ${input}`); +} +/** + * Create a new farmhash based u32 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + */ +exports.fingerprint32 = function fingerprint32(input) { + return farmhash.fingerprint32(asBuffer(input)); +} +/** + * Create a new farmhash based u64 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + */ +exports.fingerprint64 = function fingerprint64(input) { + return farmhash.fingerprint64(asBuffer(input)); +} +/** + * Create a new farmhash based i64 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + * + * This matches the format used by BigQuery's FARM_FINGERPRINT function. + */ +exports.bigqueryFingerprint = function bigqueryFingerprint(input) { + return farmhash.bigquery_fingerprint(asBuffer(input)); +} +/** + * Create a new farmhash based u32 for an array of bytes. Hash value may + * vary with library version. + */ +exports.hash32 = function hash32(input) { + return farmhash.hash32(asBuffer(input)); +} +/** + * Create a new farmhash based u32 for an array of bytes with a given seed. + * Hash value may vary with library version. + */ +exports.hash32WithSeed = function hash32WithSeed(input, seed) { + return farmhash.hash32_with_seed(asBuffer(input), asUnsigned32BitNumber(seed)); +} +/** + * Create a new farmhash based u64 for an array of bytes. Hash value may + * vary with library version. + */ +exports.hash64 = function hash64(input) { + return farmhash.hash64(asBuffer(input)); +} +/** + * Create a new farmhash based u64 for an array of bytes with a given seed. + * Hash value may vary with library version. + */ +exports.hash64WithSeed = function hash64WithSeed(input, seed) { + return farmhash.hash64_with_seed(asBuffer(input), asUnsigned64BitNumber(seed)); +} diff --git a/node_modules/farmhash-modern/lib/index.d.cts b/node_modules/farmhash-modern/lib/index.d.cts new file mode 100644 index 0000000..9b36b88 --- /dev/null +++ b/node_modules/farmhash-modern/lib/index.d.cts @@ -0,0 +1,40 @@ +/** + * Create a new farmhash based u32 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + */ +export declare function fingerprint32(input: string | Uint8Array): number; +/** + * Create a new farmhash based u64 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + */ +export declare function fingerprint64(input: string | Uint8Array): bigint; +/** + * Create a new farmhash based i64 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + * + * This matches the format used by BigQuery's FARM_FINGERPRINT function. + */ +export declare function bigqueryFingerprint(input: string | Uint8Array): bigint; +/** + * Create a new farmhash based u32 for an array of bytes. Hash value may + * vary with library version. + */ +export declare function hash32(input: string | Uint8Array): number; +/** + * Create a new farmhash based u32 for an array of bytes with a given seed. + * Hash value may vary with library version. + */ +export declare function hash32WithSeed(input: string | Uint8Array, seed: number): number; +/** + * Create a new farmhash based u64 for an array of bytes. Hash value may + * vary with library version. + */ +export declare function hash64(input: string | Uint8Array): bigint; +/** + * Create a new farmhash based u64 for an array of bytes with a given seed. + * Hash value may vary with library version. + */ +export declare function hash64WithSeed(input: string | Uint8Array, seed: bigint): bigint; diff --git a/node_modules/farmhash-modern/lib/index.d.mts b/node_modules/farmhash-modern/lib/index.d.mts new file mode 100644 index 0000000..9b36b88 --- /dev/null +++ b/node_modules/farmhash-modern/lib/index.d.mts @@ -0,0 +1,40 @@ +/** + * Create a new farmhash based u32 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + */ +export declare function fingerprint32(input: string | Uint8Array): number; +/** + * Create a new farmhash based u64 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + */ +export declare function fingerprint64(input: string | Uint8Array): bigint; +/** + * Create a new farmhash based i64 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + * + * This matches the format used by BigQuery's FARM_FINGERPRINT function. + */ +export declare function bigqueryFingerprint(input: string | Uint8Array): bigint; +/** + * Create a new farmhash based u32 for an array of bytes. Hash value may + * vary with library version. + */ +export declare function hash32(input: string | Uint8Array): number; +/** + * Create a new farmhash based u32 for an array of bytes with a given seed. + * Hash value may vary with library version. + */ +export declare function hash32WithSeed(input: string | Uint8Array, seed: number): number; +/** + * Create a new farmhash based u64 for an array of bytes. Hash value may + * vary with library version. + */ +export declare function hash64(input: string | Uint8Array): bigint; +/** + * Create a new farmhash based u64 for an array of bytes with a given seed. + * Hash value may vary with library version. + */ +export declare function hash64WithSeed(input: string | Uint8Array, seed: bigint): bigint; diff --git a/node_modules/farmhash-modern/lib/index.d.ts b/node_modules/farmhash-modern/lib/index.d.ts new file mode 100644 index 0000000..9b36b88 --- /dev/null +++ b/node_modules/farmhash-modern/lib/index.d.ts @@ -0,0 +1,40 @@ +/** + * Create a new farmhash based u32 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + */ +export declare function fingerprint32(input: string | Uint8Array): number; +/** + * Create a new farmhash based u64 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + */ +export declare function fingerprint64(input: string | Uint8Array): bigint; +/** + * Create a new farmhash based i64 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + * + * This matches the format used by BigQuery's FARM_FINGERPRINT function. + */ +export declare function bigqueryFingerprint(input: string | Uint8Array): bigint; +/** + * Create a new farmhash based u32 for an array of bytes. Hash value may + * vary with library version. + */ +export declare function hash32(input: string | Uint8Array): number; +/** + * Create a new farmhash based u32 for an array of bytes with a given seed. + * Hash value may vary with library version. + */ +export declare function hash32WithSeed(input: string | Uint8Array, seed: number): number; +/** + * Create a new farmhash based u64 for an array of bytes. Hash value may + * vary with library version. + */ +export declare function hash64(input: string | Uint8Array): bigint; +/** + * Create a new farmhash based u64 for an array of bytes with a given seed. + * Hash value may vary with library version. + */ +export declare function hash64WithSeed(input: string | Uint8Array, seed: bigint): bigint; diff --git a/node_modules/farmhash-modern/lib/index.js b/node_modules/farmhash-modern/lib/index.js new file mode 100644 index 0000000..0720434 --- /dev/null +++ b/node_modules/farmhash-modern/lib/index.js @@ -0,0 +1,78 @@ +import * as farmhash from '../bin/nodejs/farmhash_modern.js'; +function asBuffer(input) { + if (typeof input === 'string') { + return new TextEncoder().encode(input); + } + if (input instanceof Uint8Array) { + return input; + } + throw new Error('Expected input to be a string or Uint8Array'); +} +function asUnsigned32BitNumber(input) { + if (input === input >>> 0) { + return input; + } + throw new Error(`Expected input to be a 32-bit unsigned integer, got ${input}`); +} +function asUnsigned64BitNumber(input) { + if (typeof input === 'bigint' && + input >= 0 && + input <= 18446744073709551615n) { + return input; + } + throw new Error(`Expected input to be a 64-bit unsigned integer, got ${input}`); +} +/** + * Create a new farmhash based u32 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + */ +export function fingerprint32(input) { + return farmhash.fingerprint32(asBuffer(input)); +} +/** + * Create a new farmhash based u64 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + */ +export function fingerprint64(input) { + return farmhash.fingerprint64(asBuffer(input)); +} +/** + * Create a new farmhash based i64 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + * + * This matches the format used by BigQuery's FARM_FINGERPRINT function. + */ +export function bigqueryFingerprint(input) { + return farmhash.bigquery_fingerprint(asBuffer(input)); +} +/** + * Create a new farmhash based u32 for an array of bytes. Hash value may + * vary with library version. + */ +export function hash32(input) { + return farmhash.hash32(asBuffer(input)); +} +/** + * Create a new farmhash based u32 for an array of bytes with a given seed. + * Hash value may vary with library version. + */ +export function hash32WithSeed(input, seed) { + return farmhash.hash32_with_seed(asBuffer(input), asUnsigned32BitNumber(seed)); +} +/** + * Create a new farmhash based u64 for an array of bytes. Hash value may + * vary with library version. + */ +export function hash64(input) { + return farmhash.hash64(asBuffer(input)); +} +/** + * Create a new farmhash based u64 for an array of bytes with a given seed. + * Hash value may vary with library version. + */ +export function hash64WithSeed(input, seed) { + return farmhash.hash64_with_seed(asBuffer(input), asUnsigned64BitNumber(seed)); +} diff --git a/node_modules/farmhash-modern/lib/index.mjs b/node_modules/farmhash-modern/lib/index.mjs new file mode 100644 index 0000000..0720434 --- /dev/null +++ b/node_modules/farmhash-modern/lib/index.mjs @@ -0,0 +1,78 @@ +import * as farmhash from '../bin/nodejs/farmhash_modern.js'; +function asBuffer(input) { + if (typeof input === 'string') { + return new TextEncoder().encode(input); + } + if (input instanceof Uint8Array) { + return input; + } + throw new Error('Expected input to be a string or Uint8Array'); +} +function asUnsigned32BitNumber(input) { + if (input === input >>> 0) { + return input; + } + throw new Error(`Expected input to be a 32-bit unsigned integer, got ${input}`); +} +function asUnsigned64BitNumber(input) { + if (typeof input === 'bigint' && + input >= 0 && + input <= 18446744073709551615n) { + return input; + } + throw new Error(`Expected input to be a 64-bit unsigned integer, got ${input}`); +} +/** + * Create a new farmhash based u32 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + */ +export function fingerprint32(input) { + return farmhash.fingerprint32(asBuffer(input)); +} +/** + * Create a new farmhash based u64 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + */ +export function fingerprint64(input) { + return farmhash.fingerprint64(asBuffer(input)); +} +/** + * Create a new farmhash based i64 for a string or an array of bytes. + * Fingerprint value should be portable and stable across library versions + * and platforms. + * + * This matches the format used by BigQuery's FARM_FINGERPRINT function. + */ +export function bigqueryFingerprint(input) { + return farmhash.bigquery_fingerprint(asBuffer(input)); +} +/** + * Create a new farmhash based u32 for an array of bytes. Hash value may + * vary with library version. + */ +export function hash32(input) { + return farmhash.hash32(asBuffer(input)); +} +/** + * Create a new farmhash based u32 for an array of bytes with a given seed. + * Hash value may vary with library version. + */ +export function hash32WithSeed(input, seed) { + return farmhash.hash32_with_seed(asBuffer(input), asUnsigned32BitNumber(seed)); +} +/** + * Create a new farmhash based u64 for an array of bytes. Hash value may + * vary with library version. + */ +export function hash64(input) { + return farmhash.hash64(asBuffer(input)); +} +/** + * Create a new farmhash based u64 for an array of bytes with a given seed. + * Hash value may vary with library version. + */ +export function hash64WithSeed(input, seed) { + return farmhash.hash64_with_seed(asBuffer(input), asUnsigned64BitNumber(seed)); +} diff --git a/node_modules/farmhash-modern/package.json b/node_modules/farmhash-modern/package.json new file mode 100644 index 0000000..48b4a15 --- /dev/null +++ b/node_modules/farmhash-modern/package.json @@ -0,0 +1,78 @@ +{ + "name": "farmhash-modern", + "version": "1.1.0", + "description": "FarmHash functions compiled using Rust and WebAssembly to make them easy to use in node.js and the browser", + "keywords": [ + "bigquery", + "farm_fingerprint", + "farmhash", + "fingerprint", + "hash", + "rust", + "wasm", + "webassembly" + ], + "main": "lib/index.cjs", + "module": "lib/index.mjs", + "types": "lib/index.d.ts", + "exports": { + "browser": "./lib/browser.js", + "import": "./lib/index.mjs", + "default": "./lib/index.cjs" + }, + "files": [ + "lib", + "bin" + ], + "repository": "git@github.com:ForbesLindesay/npm-package-template.git", + "author": "Forbes Lindesay ", + "license": "MIT", + "scripts": { + "build": "yarn build:rust && yarn build:tsc", + "build:rust": "yarn build:rust:bundler && yarn build:rust:nodejs", + "build:rust:web": "wasm-pack build rust-src --target web --out-dir ../bin/web", + "build:rust:bundler": "wasm-pack build rust-src --target bundler --out-dir ../bin/bundler", + "build:rust:nodejs": "wasm-pack build rust-src --target nodejs --out-dir ../bin/nodejs", + "build:tsc": "tsc", + "postbuild": "rimraf lib/**/__tests__ && node post-build-script && rimraf web-app/node_modules/farmhash-modern && rimraf tests/node_modules/farmhash-modern && npm pack", + "lint": "eslint --config .eslintrc-ts.js --no-eslintrc --ext .ts,.tsx src", + "lint:fix": "eslint --fix --config .eslintrc-ts.js --no-eslintrc --ext .ts,.tsx src", + "prettier:write": "prettier --ignore-path .gitignore --write './**/*.{md,json,yaml,js,jsx,ts,tsx}'", + "prettier:check": "prettier --ignore-path .gitignore --list-different './**/*.{md,json,yaml,js,jsx,ts,tsx}'", + "pretest": "rimraf tests/package-lock.json && cd tests && npm install", + "test": "yarn test:cjs && yarn test:mjs && yarn test:typescript && yarn test:attw", + "test:cjs": "node tests/src/test.cjs", + "test:mjs": "node tests/src/test.mjs", + "test:typescript": "cd tests && tsc", + "test:attw": "yarn attw farmhash-modern-0.0.0.tgz" + }, + "dependencies": {}, + "devDependencies": { + "@arethetypeswrong/cli": "^0.4.2", + "@forbeslindesay/tsconfig": "^2.1.0", + "@types/node": "^20.3.2", + "@typescript-eslint/eslint-plugin": "^5.60.1", + "@typescript-eslint/parser": "^5.60.1", + "eslint-plugin-import": "^2.27.5", + "eslint": "^8.43.0", + "husky": "^4.2.5", + "lint-staged": "^10.1.3", + "prettier": "^2.8.8", + "rimraf": "^3.0.2", + "typescript": "^5.1.6" + }, + "husky": { + "hooks": { + "pre-commit": "lint-staged" + } + }, + "lint-staged": { + "*.{md,json,yaml,js,jsx,ts,tsx}": [ + "prettier --write", + "git add" + ] + }, + "engines": { + "node": ">=18.0.0" + } +} diff --git a/node_modules/fast-deep-equal/LICENSE b/node_modules/fast-deep-equal/LICENSE new file mode 100644 index 0000000..7f15435 --- /dev/null +++ b/node_modules/fast-deep-equal/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Evgeny Poberezkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/fast-deep-equal/README.md b/node_modules/fast-deep-equal/README.md new file mode 100644 index 0000000..d3f4ffc --- /dev/null +++ b/node_modules/fast-deep-equal/README.md @@ -0,0 +1,96 @@ +# fast-deep-equal +The fastest deep equal with ES6 Map, Set and Typed arrays support. + +[![Build Status](https://travis-ci.org/epoberezkin/fast-deep-equal.svg?branch=master)](https://travis-ci.org/epoberezkin/fast-deep-equal) +[![npm](https://img.shields.io/npm/v/fast-deep-equal.svg)](https://www.npmjs.com/package/fast-deep-equal) +[![Coverage Status](https://coveralls.io/repos/github/epoberezkin/fast-deep-equal/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/fast-deep-equal?branch=master) + + +## Install + +```bash +npm install fast-deep-equal +``` + + +## Features + +- ES5 compatible +- works in node.js (8+) and browsers (IE9+) +- checks equality of Date and RegExp objects by value. + +ES6 equal (`require('fast-deep-equal/es6')`) also supports: +- Maps +- Sets +- Typed arrays + + +## Usage + +```javascript +var equal = require('fast-deep-equal'); +console.log(equal({foo: 'bar'}, {foo: 'bar'})); // true +``` + +To support ES6 Maps, Sets and Typed arrays equality use: + +```javascript +var equal = require('fast-deep-equal/es6'); +console.log(equal(Int16Array([1, 2]), Int16Array([1, 2]))); // true +``` + +To use with React (avoiding the traversal of React elements' _owner +property that contains circular references and is not needed when +comparing the elements - borrowed from [react-fast-compare](https://github.com/FormidableLabs/react-fast-compare)): + +```javascript +var equal = require('fast-deep-equal/react'); +var equal = require('fast-deep-equal/es6/react'); +``` + + +## Performance benchmark + +Node.js v12.6.0: + +``` +fast-deep-equal x 261,950 ops/sec ±0.52% (89 runs sampled) +fast-deep-equal/es6 x 212,991 ops/sec ±0.34% (92 runs sampled) +fast-equals x 230,957 ops/sec ±0.83% (85 runs sampled) +nano-equal x 187,995 ops/sec ±0.53% (88 runs sampled) +shallow-equal-fuzzy x 138,302 ops/sec ±0.49% (90 runs sampled) +underscore.isEqual x 74,423 ops/sec ±0.38% (89 runs sampled) +lodash.isEqual x 36,637 ops/sec ±0.72% (90 runs sampled) +deep-equal x 2,310 ops/sec ±0.37% (90 runs sampled) +deep-eql x 35,312 ops/sec ±0.67% (91 runs sampled) +ramda.equals x 12,054 ops/sec ±0.40% (91 runs sampled) +util.isDeepStrictEqual x 46,440 ops/sec ±0.43% (90 runs sampled) +assert.deepStrictEqual x 456 ops/sec ±0.71% (88 runs sampled) + +The fastest is fast-deep-equal +``` + +To run benchmark (requires node.js 6+): + +```bash +npm run benchmark +``` + +__Please note__: this benchmark runs against the available test cases. To choose the most performant library for your application, it is recommended to benchmark against your data and to NOT expect this benchmark to reflect the performance difference in your application. + + +## Enterprise support + +fast-deep-equal package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-fast-deep-equal?utm_source=npm-fast-deep-equal&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers. + + +## Security contact + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues. + + +## License + +[MIT](https://github.com/epoberezkin/fast-deep-equal/blob/master/LICENSE) diff --git a/node_modules/fast-deep-equal/es6/index.d.ts b/node_modules/fast-deep-equal/es6/index.d.ts new file mode 100644 index 0000000..c7eb9c7 --- /dev/null +++ b/node_modules/fast-deep-equal/es6/index.d.ts @@ -0,0 +1,2 @@ +declare const equal: (a: any, b: any) => boolean; +export = equal; diff --git a/node_modules/fast-deep-equal/es6/index.js b/node_modules/fast-deep-equal/es6/index.js new file mode 100644 index 0000000..d980be2 --- /dev/null +++ b/node_modules/fast-deep-equal/es6/index.js @@ -0,0 +1,72 @@ +'use strict'; + +// do not edit .js files directly - edit src/index.jst + + + var envHasBigInt64Array = typeof BigInt64Array !== 'undefined'; + + +module.exports = function equal(a, b) { + if (a === b) return true; + + if (a && b && typeof a == 'object' && typeof b == 'object') { + if (a.constructor !== b.constructor) return false; + + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (!equal(a[i], b[i])) return false; + return true; + } + + + if ((a instanceof Map) && (b instanceof Map)) { + if (a.size !== b.size) return false; + for (i of a.entries()) + if (!b.has(i[0])) return false; + for (i of a.entries()) + if (!equal(i[1], b.get(i[0]))) return false; + return true; + } + + if ((a instanceof Set) && (b instanceof Set)) { + if (a.size !== b.size) return false; + for (i of a.entries()) + if (!b.has(i[0])) return false; + return true; + } + + if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (a[i] !== b[i]) return false; + return true; + } + + + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + + for (i = length; i-- !== 0;) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + + for (i = length; i-- !== 0;) { + var key = keys[i]; + + if (!equal(a[key], b[key])) return false; + } + + return true; + } + + // true if both NaN, false otherwise + return a!==a && b!==b; +}; diff --git a/node_modules/fast-deep-equal/es6/react.d.ts b/node_modules/fast-deep-equal/es6/react.d.ts new file mode 100644 index 0000000..c7eb9c7 --- /dev/null +++ b/node_modules/fast-deep-equal/es6/react.d.ts @@ -0,0 +1,2 @@ +declare const equal: (a: any, b: any) => boolean; +export = equal; diff --git a/node_modules/fast-deep-equal/es6/react.js b/node_modules/fast-deep-equal/es6/react.js new file mode 100644 index 0000000..98e2f9b --- /dev/null +++ b/node_modules/fast-deep-equal/es6/react.js @@ -0,0 +1,79 @@ +'use strict'; + +// do not edit .js files directly - edit src/index.jst + + + var envHasBigInt64Array = typeof BigInt64Array !== 'undefined'; + + +module.exports = function equal(a, b) { + if (a === b) return true; + + if (a && b && typeof a == 'object' && typeof b == 'object') { + if (a.constructor !== b.constructor) return false; + + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (!equal(a[i], b[i])) return false; + return true; + } + + + if ((a instanceof Map) && (b instanceof Map)) { + if (a.size !== b.size) return false; + for (i of a.entries()) + if (!b.has(i[0])) return false; + for (i of a.entries()) + if (!equal(i[1], b.get(i[0]))) return false; + return true; + } + + if ((a instanceof Set) && (b instanceof Set)) { + if (a.size !== b.size) return false; + for (i of a.entries()) + if (!b.has(i[0])) return false; + return true; + } + + if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (a[i] !== b[i]) return false; + return true; + } + + + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + + for (i = length; i-- !== 0;) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + + for (i = length; i-- !== 0;) { + var key = keys[i]; + + if (key === '_owner' && a.$$typeof) { + // React-specific: avoid traversing React elements' _owner. + // _owner contains circular references + // and is not needed when comparing the actual elements (and not their owners) + continue; + } + + if (!equal(a[key], b[key])) return false; + } + + return true; + } + + // true if both NaN, false otherwise + return a!==a && b!==b; +}; diff --git a/node_modules/fast-deep-equal/index.d.ts b/node_modules/fast-deep-equal/index.d.ts new file mode 100644 index 0000000..3c042ca --- /dev/null +++ b/node_modules/fast-deep-equal/index.d.ts @@ -0,0 +1,4 @@ +declare module 'fast-deep-equal' { + const equal: (a: any, b: any) => boolean; + export = equal; +} diff --git a/node_modules/fast-deep-equal/index.js b/node_modules/fast-deep-equal/index.js new file mode 100644 index 0000000..30dd1ba --- /dev/null +++ b/node_modules/fast-deep-equal/index.js @@ -0,0 +1,46 @@ +'use strict'; + +// do not edit .js files directly - edit src/index.jst + + + +module.exports = function equal(a, b) { + if (a === b) return true; + + if (a && b && typeof a == 'object' && typeof b == 'object') { + if (a.constructor !== b.constructor) return false; + + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (!equal(a[i], b[i])) return false; + return true; + } + + + + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + + for (i = length; i-- !== 0;) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + + for (i = length; i-- !== 0;) { + var key = keys[i]; + + if (!equal(a[key], b[key])) return false; + } + + return true; + } + + // true if both NaN, false otherwise + return a!==a && b!==b; +}; diff --git a/node_modules/fast-deep-equal/package.json b/node_modules/fast-deep-equal/package.json new file mode 100644 index 0000000..3cfe66c --- /dev/null +++ b/node_modules/fast-deep-equal/package.json @@ -0,0 +1,61 @@ +{ + "name": "fast-deep-equal", + "version": "3.1.3", + "description": "Fast deep equal", + "main": "index.js", + "scripts": { + "eslint": "eslint *.js benchmark/*.js spec/*.js", + "build": "node build", + "benchmark": "npm i && npm run build && cd ./benchmark && npm i && node ./", + "test-spec": "mocha spec/*.spec.js -R spec", + "test-cov": "nyc npm run test-spec", + "test-ts": "tsc --target ES5 --noImplicitAny index.d.ts", + "test": "npm run build && npm run eslint && npm run test-ts && npm run test-cov", + "prepublish": "npm run build" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/epoberezkin/fast-deep-equal.git" + }, + "keywords": [ + "fast", + "equal", + "deep-equal" + ], + "author": "Evgeny Poberezkin", + "license": "MIT", + "bugs": { + "url": "https://github.com/epoberezkin/fast-deep-equal/issues" + }, + "homepage": "https://github.com/epoberezkin/fast-deep-equal#readme", + "devDependencies": { + "coveralls": "^3.1.0", + "dot": "^1.1.2", + "eslint": "^7.2.0", + "mocha": "^7.2.0", + "nyc": "^15.1.0", + "pre-commit": "^1.2.2", + "react": "^16.12.0", + "react-test-renderer": "^16.12.0", + "sinon": "^9.0.2", + "typescript": "^3.9.5" + }, + "nyc": { + "exclude": [ + "**/spec/**", + "node_modules" + ], + "reporter": [ + "lcov", + "text-summary" + ] + }, + "files": [ + "index.js", + "index.d.ts", + "react.js", + "react.d.ts", + "es6/" + ], + "types": "index.d.ts" +} diff --git a/node_modules/fast-deep-equal/react.d.ts b/node_modules/fast-deep-equal/react.d.ts new file mode 100644 index 0000000..c7eb9c7 --- /dev/null +++ b/node_modules/fast-deep-equal/react.d.ts @@ -0,0 +1,2 @@ +declare const equal: (a: any, b: any) => boolean; +export = equal; diff --git a/node_modules/fast-deep-equal/react.js b/node_modules/fast-deep-equal/react.js new file mode 100644 index 0000000..3489b98 --- /dev/null +++ b/node_modules/fast-deep-equal/react.js @@ -0,0 +1,53 @@ +'use strict'; + +// do not edit .js files directly - edit src/index.jst + + + +module.exports = function equal(a, b) { + if (a === b) return true; + + if (a && b && typeof a == 'object' && typeof b == 'object') { + if (a.constructor !== b.constructor) return false; + + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (!equal(a[i], b[i])) return false; + return true; + } + + + + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + + for (i = length; i-- !== 0;) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + + for (i = length; i-- !== 0;) { + var key = keys[i]; + + if (key === '_owner' && a.$$typeof) { + // React-specific: avoid traversing React elements' _owner. + // _owner contains circular references + // and is not needed when comparing the actual elements (and not their owners) + continue; + } + + if (!equal(a[key], b[key])) return false; + } + + return true; + } + + // true if both NaN, false otherwise + return a!==a && b!==b; +}; diff --git a/node_modules/fast-xml-parser/CHANGELOG.md b/node_modules/fast-xml-parser/CHANGELOG.md new file mode 100644 index 0000000..017e5d9 --- /dev/null +++ b/node_modules/fast-xml-parser/CHANGELOG.md @@ -0,0 +1,606 @@ +Note: If you find missing information about particular minor version, that version must have been changed without any functional change in this library. + +**4.5.2 / 2025-02-18** +- Fix null CDATA to comply with undefined behavior (#701) (By [Matthieu BOHEAS](https://github.com/Kelgors)) +- Fix(performance): Update check for leaf node in saveTextToParentTag function in OrderedObjParser.js (#707) (By [...](https://github.com/tomingtoming)) +- Fix: emit full JSON string from CLI when no output filename specified (#710) (By [Matt Benson](https://github.com/mbenson)) + +**4.5.1 / 2024-12-15** +- Fix empty tag key name for v5 (#697). no impact on v4 +- Fixes entity parsing when used in strict mode (#699) + +**4.5.0 / 2024-09-03** +- feat #666: ignoreAttributes support function, and array of string or regex (By [ArtemM](https://github.com/mav-rik)) + +**4.4.1 / 2024-07-28** +- v5 fix: maximum length limit to currency value +- fix #634: build attributes with oneListGroup and attributesGroupName (#653)(By [Andreas Naziris](https://github.com/a-rasin)) +- fix: get oneListGroup to work as expected for array of strings (#662)(By [Andreas Naziris](https://github.com/a-rasin)) + +**4.4.0 / 2024-05-18** +- fix #654: parse attribute list correctly for self closing stop node. +- fix: validator bug when closing tag is not opened. (#647) (By [Ryosuke Fukatani](https://github.com/RyosukeFukatani)) +- fix #581: typings; return type of `tagValueProcessor` & `attributeValueProcessor` (#582) (By [monholm]()) + +**4.3.6 / 2024-03-16** +- Add support for parsing HTML numeric entities (#645) (By [Jonas Schade ](https://github.com/DerZade)) + +**4.3.5 / 2024-02-24** +- code for v5 is added for experimental use + +**4.3.4 / 2024-01-10** +- fix: Don't escape entities in CDATA sections (#633) (By [wackbyte](https://github.com/wackbyte)) + +**4.3.3 / 2024-01-10** +- Remove unnecessary regex + +**4.3.2 / 2023-10-02** +- fix `jObj.hasOwnProperty` when give input is null (By [Arda TANRIKULU](https://github.com/ardatan)) + +**4.3.1 / 2023-09-24** +- revert back "Fix typings for builder and parser to make return type generic" to avoid failure of existing projects. Need to decide a common approach. + +**4.3.0 / 2023-09-20** +- Fix stopNodes to work with removeNSPrefix (#607) (#608) (By [Craig Andrews]https://github.com/candrews)) +- Fix #610 ignore properties set to Object.prototype +- Fix typings for builder and parser to make return type generic (By [Sarah Dayan](https://github.com/sarahdayan)) + +**4.2.7 / 2023-07-30** +- Fix: builder should set text node correctly when only textnode is present (#589) (By [qianqing](https://github.com/joneqian)) +- Fix: Fix for null and undefined attributes when building xml (#585) (#598). A null or undefined value should be ignored. (By [Eugenio Ceschia](https://github.com/cecia234)) + +**4.2.6 / 2023-07-17** +- Fix: Remove trailing slash from jPath for self-closing tags (#595) (By [Maciej Radzikowski](https://github.com/m-radzikowski)) + +**4.2.5 / 2023-06-22** +- change code implementation + +**4.2.4 / 2023-06-06** +- fix security bug + +**4.2.3 / 2023-06-05** +- fix security bug + +**4.2.2 / 2023-04-18** +- fix #562: fix unpaired tag when it comes in last of a nested tag. Also throw error when unpaired tag is used as closing tag + +**4.2.1 / 2023-04-18** +- fix: jpath after unpaired tags + +**4.2.0 / 2023-04-09** +- support `updateTag` parser property + +**4.1.4 / 2023-04-08** +- update typings to let user create XMLBuilder instance without options (#556) (By [Patrick](https://github.com/omggga)) +- fix: IsArray option isn't parsing tags with 0 as value correctly #490 (#557) (By [Aleksandr Murashkin](https://github.com/p-kuen)) +- feature: support `oneListGroup` to group repeated children tags udder single group + +**4.1.3 / 2023-02-26** +- fix #546: Support complex entity value + +**4.1.2 / 2023-02-12** +- Security Fix + +**4.1.1 / 2023-02-03** +- Fix #540: ignoreAttributes breaks unpairedTags +- Refactor XML builder code + +**4.1.0 / 2023-02-02** +- Fix '<' or '>' in DTD comment throwing an error. (#533) (By [Adam Baker](https://github.com/Cwazywierdo)) +- Set "eNotation" to 'true' as default + +**4.0.15 / 2023-01-25** +- make "eNotation" optional + +**4.0.14 / 2023-01-22** +- fixed: add missed typing "eNotation" to parse values + +**4.0.13 / 2023-01-07** +- preserveorder formatting (By [mdeknowis](https://github.com/mdeknowis)) +- support `transformAttributeName` (By [Erik Rothoff Andersson](https://github.com/erkie)) + +**4.0.12 / 2022-11-19** +- fix typescript + +**4.0.11 / 2022-10-05** +- fix #501: parse for entities only once + +**4.0.10 / 2022-09-14** +- fix broken links in demo site (By [Yannick Lang](https://github.com/layaxx)) +- fix #491: tagValueProcessor type definition (By [Andrea Francesco Speziale](https://github.com/andreafspeziale)) +- Add jsdocs for tagValueProcessor + + +**4.0.9 / 2022-07-10** +- fix #470: stop-tag can have self-closing tag with same name +- fix #472: stopNode can have any special tag inside +- Allow !ATTLIST and !NOTATION with DOCTYPE +- Add transformTagName option to transform tag names when parsing (#469) (By [Erik Rothoff Andersson](https://github.com/erkie)) + +**4.0.8 / 2022-05-28** +- Fix CDATA parsing returning empty string when value = 0 (#451) (By [ndelanou](https://github.com/ndelanou)) +- Fix stopNodes when same tag appears inside node (#456) (By [patrickshipe](https://github.com/patrickshipe)) +- fix #468: prettify own properties only + +**4.0.7 / 2022-03-18** +- support CDATA even if tag order is not preserved +- support Comments even if tag order is not preserved +- fix #446: XMLbuilder should not indent XML declaration + +**4.0.6 / 2022-03-08** +- fix: call tagValueProcessor only once for array items +- fix: missing changed for #437 + +**4.0.5 / 2022-03-06** +- fix #437: call tagValueProcessor from XML builder + +**4.0.4 / 2022-03-03** +- fix #435: should skip unpaired and self-closing nodes when set as stopnodes + +**4.0.3 / 2022-02-15** +- fix: ReferenceError when Bundled with Strict (#431) (By [Andreas Heissenberger](https://github.com/aheissenberger)) + + +**4.0.2 / 2022-02-04** +- builder supports `suppressUnpairedNode` +- parser supports `ignoreDeclaration` and `ignorePiTags` +- fix: when comment is parsed as text value if given as ` ...` #423 +- builder supports decoding `&` + +**4.0.1 / 2022-01-08** +- fix builder for pi tag +- fix: support suppressBooleanAttrs by builder + +**4.0.0 / 2022-01-06** +- Generating different combined, parser only, builder only, validator only browser bundles +- Keeping cjs modules as they can be imported in cjs and esm modules both. Otherwise refer `esm` branch. + +**4.0.0-beta.8 / 2021-12-13** +- call tagValueProcessor for stop nodes + +**4.0.0-beta.7 / 2021-12-09** +- fix Validator bug when an attribute has no value but '=' only +- XML Builder should suppress unpaired tags by default. +- documents update for missing features +- refactoring to use Object.assign +- refactoring to remove repeated code + +**4.0.0-beta.6 / 2021-12-05** +- Support PI Tags processing +- Support `suppressBooleanAttributes` by XML Builder for attributes with value `true`. + +**4.0.0-beta.5 / 2021-12-04** +- fix: when a tag with name "attributes" + +**4.0.0-beta.4 / 2021-12-02** +- Support HTML document parsing +- skip stop nodes parsing when building the XML from JS object +- Support external entites without DOCTYPE +- update dev dependency: strnum v1.0.5 to fix long number issue + +**4.0.0-beta.3 / 2021-11-30** +- support global stopNodes expression like "*.stop" +- support self-closing and paired unpaired tags +- fix: CDATA should not be parsed. +- Fix typings for XMLBuilder (#396)(By [Anders Emil Salvesen](https://github.com/andersem)) +- supports XML entities, HTML entities, DOCTYPE entities + +**⚠️ 4.0.0-beta.2 / 2021-11-19** +- rename `attrMap` to `attibutes` in parser output when `preserveOrder:true` +- supports unpairedTags + +**⚠️ 4.0.0-beta.1 / 2021-11-18** +- Parser returns an array now + - to make the structure common + - and to return root level detail +- renamed `cdataTagName` to `cdataPropName` +- Added `commentPropName` +- fix typings + +**⚠️ 4.0.0-beta.0 / 2021-11-16** +- Name change of many configuration properties. + - `attrNodeName` to `attributesGroupName` + - `attrValueProcessor` to `attributeValueProcessor` + - `parseNodeValue` to `parseTagValue` + - `ignoreNameSpace` to `removeNSPrefix` + - `numParseOptions` to `numberParseOptions` + - spelling correction for `suppressEmptyNode` +- Name change of cli and browser bundle to **fxparser** +- `isArray` option is added to parse a tag into array +- `preserveOrder` option is added to render XML in such a way that the result js Object maintains the order of properties same as in XML. +- Processing behaviour of `tagValueProcessor` and `attributeValueProcessor` are changes with extra input parameters +- j2xparser is renamed to XMLBuilder. +- You need to build XML parser instance for given options first before parsing XML. +- fix #327, #336: throw error when extra text after XML content +- fix #330: attribute value can have '\n', +- fix #350: attrbiutes can be separated by '\n' from tagname + +3.21.1 / 2021-10-31 +- Correctly format JSON elements with a text prop but no attribute props ( By [haddadnj](https://github.com/haddadnj) ) + +3.21.0 / 2021-10-25 + - feat: added option `rootNodeName` to set tag name for array input when converting js object to XML. + - feat: added option `alwaysCreateTextNode` to force text node creation (by: *@massimo-ua*) + - ⚠️ feat: Better error location for unclosed tags. (by *@Gei0r*) + - Some error messages would be changed when validating XML. Eg + - `{ InvalidXml: "Invalid '[ \"rootNode\"]' found." }` → `{InvalidTag: "Unclosed tag 'rootNode'."}` + - `{ InvalidTag: "Closing tag 'rootNode' is expected inplace of 'rootnode'." }` → `{ InvalidTag: "Expected closing tag 'rootNode' (opened in line 1) instead of closing tag 'rootnode'."}` + - ⚠️ feat: Column in error response when validating XML +```js +{ + "code": "InvalidAttr", + "msg": "Attribute 'abc' is repeated.", + "line": 1, + "col": 22 +} +``` + +3.20.1 / 2021-09-25 + - update strnum package + +3.20.0 / 2021-09-10 + - Use strnum npm package to parse string to number + - breaking change: long number will be parsed to scientific notation. + +3.19.0 / 2021-03-14 + - License changed to MIT original + - Fix #321 : namespace tag parsing + +3.18.0 / 2021-02-05 + - Support RegEx and function in arrayMode option + - Fix #317 : validate nested PI tags + +3.17.4 / 2020-06-07 + - Refactor some code to support IE11 + - Fix: `` space as attribute string + +3.17.3 / 2020-05-23 + - Fix: tag name separated by \n \t + - Fix: throw error for unclosed tags + +3.17.2 / 2020-05-23 + - Fixed an issue in processing doctype tag + - Fixed tagName where it should not have whitespace chars + +3.17.1 / 2020-05-19 + - Fixed an issue in checking opening tag + +3.17.0 / 2020-05-18 + - parser: fix '<' issue when it comes in aatr value + - parser: refactoring to remove dependency from regex + - validator: fix IE 11 issue for error messages + - updated dev dependencies + - separated benchmark module to sub-module + - breaking change: comments will not be removed from CDATA data + +3.16.0 / 2020-01-12 + - validaor: fix for ampersand characters (#215) + - refactoring to support unicode chars in tag name + - update typing for validator error + +3.15.1 / 2019-12-09 + - validaor: fix multiple roots are not allowed + +3.15.0 / 2019-11-23 + - validaor: improve error messaging + - validator: add line number in case of error + - validator: add more error scenarios to make it more descriptive + +3.14.0 / 2019-10-25 + - arrayMode for XML to JS obj parsing + +3.13.0 / 2019-10-02 + - pass tag/attr name to tag/attr value processor + - inbuilt optional validation with XML parser + +3.12.21 / 2019-10-02 + - Fix validator for unclosed XMLs + - move nimnjs dependency to dev dependency + - update dependencies + +3.12.20 / 2019-08-16 + - Revert: Fix #167: '>' in attribute value as it is causing high performance degrade. + +3.12.19 / 2019-07-28 + - Fix js to xml parser should work for date values. (broken: `tagValueProcessor` will receive the original value instead of string always) (breaking change) + +3.12.18 / 2019-07-27 + - remove configstore dependency + +3.12.17 / 2019-07-14 + - Fix #167: '>' in attribute value + +3.12.16 / 2019-03-23 + - Support a new option "stopNodes". (#150) +Accept the list of tags which are not required to be parsed. Instead, all the nested tag and data will be assigned as string. + - Don't show post-install message + +3.12.12 / 2019-01-11 + - fix : IE parseInt, parseFloat error + +3.12.11 / 2018-12-24 + - fix #132: "/" should not be parsed as boolean attr in case of self closing tags + +3.12.9 / 2018-11-23 + - fix #129 : validator should not fail when an atrribute name is 'length' + +3.12.8 / 2018-11-22 + - fix #128 : use 'attrValueProcessor' to process attribute value in json2xml parser + +3.12.6 / 2018-11-10 + - Fix #126: check for type + +3.12.4 / 2018-09-12 + - Fix: include tasks in npm package + +3.12.3 / 2018-09-12 + - Fix CLI issue raised in last PR + +3.12.2 / 2018-09-11 + - Fix formatting for JSON to XML output + - Migrate to webpack (PR merged) + - fix cli (PR merged) + +3.12.0 / 2018-08-06 + - Support hexadecimal values + - Support true number parsing + +3.11.2 / 2018-07-23 + - Update Demo for more options + - Update license information + - Update readme for formatting, users, and spelling mistakes + - Add missing typescript definition for j2xParser + - refactoring: change filenames + +3.11.1 / 2018-06-05 + - fix #93: read the text after self closing tag + +3.11.0 / 2018-05-20 + - return defaultOptions if there are not options in buildOptions function + - added localeRange declaration in parser.d.ts + - Added support of cyrillic characters in validator XML + - fixed bug in validator work when XML data with byte order marker + +3.10.0 / 2018-05-13 + - Added support of cyrillic characters in parsing XML to JSON + +3.9.11 / 2018-05-09 + - fix https://github.com/NaturalIntelligence/fast-xml-parser/issues/80 fix nimn chars + - update package information + - fix https://github.com/NaturalIntelligence/fast-xml-parser/issues/86: json 2 xml parser : property with null value should be parsed to self closing tag. + - update online demo + - revert zombiejs to old version to support old version of node + - update dependencies + +3.3.10 / 2018-04-23 + - fix #77 : parse even if closing tag has space before '>' + - include all css & js lib in demo app + - remove babel dependencies until needed + +3.3.9 / 2018-04-18 + - fix #74 : TS2314 TypeScript compiler error + +3.3.8 / 2018-04-17 + - fix #73 : IE doesn't support Object.assign + +3.3.7 / 2018-04-14 + - fix: use let insted of const in for loop of validator + - Merge pull request + https://github.com/NaturalIntelligence/fast-xml-parser/issues/71 from bb/master + first draft of typings for typescript + https://github.com/NaturalIntelligence/fast-xml-parser/issues/69 + - Merge pull request + https://github.com/NaturalIntelligence/fast-xml-parser/issues/70 from bb/patch-1 + fix some typos in readme + +3.3.6 / 2018-03-21 + - change arrow functions to full notation for IE compatibility + +3.3.5 / 2018-03-15 + - fix https://github.com/NaturalIntelligence/fast-xml-parser/issues/67 : attrNodeName invalid behavior + - fix: remove decodeHTML char condition + +3.3.4 / 2018-03-14 + - remove dependency on "he" package + - refactor code to separate methods in separate files. + - draft code for transforming XML to json string. It is not officially documented due to performance issue. + +3.3.0 / 2018-03-05 + - use common default options for XML parsing for consistency. And add `parseToNimn` method. + - update nexttodo + - update README about XML to Nimn transformation and remove special notes about 3.x release + - update CONTRIBUTING.ms mentioning nexttodo + - add negative case for XML PIs + - validate xml processing instruction tags https://github.com/NaturalIntelligence/fast-xml-parser/issues/62 + - nimndata: handle array with object + - nimndata: node with nested node and text node + - nimndata: handle attributes and text node + - nimndata: add options, handle array + - add xml to nimn data converter + - x2j: direct access property with tagname + - update changelog + - fix validator when single quote presents in value enclosed with double quotes or vice versa + - Revert "remove unneded nimnjs dependency, move opencollective to devDependencies and replace it + with more light opencollective-postinstall" + This reverts commit d47aa7181075d82db4fee97fd8ea32b056fe3f46. + - Merge pull request: https://github.com/NaturalIntelligence/fast-xml-parser/issues/63 from HaroldPutman/suppress-undefined + Keep undefined nodes out of the XML output : This is useful when you are deleting nodes from the JSON and rewriting XML. + +3.2.4 / 2018-03-01 + - fix #59 fix in validator when open quote presents in attribute value + - Create nexttodo.md + - exclude static from bitHound tests + - add package lock + +3.2.3 / 2018-02-28 + - Merge pull request from Delagen/master: fix namespaces can contain the same characters as xml names + +3.2.2 / 2018-02-22 + - fix: attribute xmlns should not be removed if ignoreNameSpace is false + - create CONTRIBUTING.md + +3.2.1 / 2018-02-17 + - fix: empty attribute should be parsed + +3.2.0 / 2018-02-16 + - Merge pull request : Dev to Master + - Update README and version + - j2x:add performance test + - j2x: Remove extra empty line before closing tag + - j2x: suppress empty nodes to self closing node if configured + - j2x: provide option to give indentation depth + - j2x: make optional formatting + - j2x: encodeHTMLchat + - j2x: handle cdata tag + - j2x: handle grouped attributes + - convert json to xml + - nested object + - array + - attributes + - text value + - small refactoring + - Merge pull request: Update cli.js to let user validate XML file or data + - Add option for rendering CDATA as separate property + +3.0.1 / 2018-02-09 + - fix CRLF: replace it with single space in attributes value only. + +3.0.0 / 2018-02-08 + - change online tool with new changes + - update info about new options + - separate tag value processing to separate function + - make HTML decoding optional + - give an option to allow boolean attributes + - change cli options as per v3 + - Correct comparison table format on README + - update v3 information + - some performance improvement changes + - Make regex object local to the method and move some common methods to util + - Change parser to + - handle multiple instances of CDATA + - make triming of value optionals + - HTML decode attribute and text value + - refactor code to separate files + - Ignore newline chars without RE (in validator) + - validate for XML prolog + - Validate DOCTYPE without RE + - Update validator to return error response + - Update README to add detail about V3 + - Separate xmlNode model class + - include vscode debug config + - fix for repeated object + - fix attribute regex for boolean attributes + - Fix validator for invalid attributes +2.9.4 / 2018-02-02 + - Merge pull request: Decode HTML characters + - refactor source folder name + - ignore bundle / browser js to be published to npm +2.9.3 / 2018-01-26 + - Merge pull request: Correctly remove CRLF line breaks + - Enable to parse attribute in online editor + - Fix testing demo app test + - Describe parsing options + - Add options for online demo +2.9.2 / 2018-01-18 + - Remove check if tag starting with "XML" + - Fix: when there are spaces before / after CDATA + +2.9.1 / 2018-01-16 + - Fix: newline should be replaced with single space + - Fix: for single and multiline comments + - validate xml with CDATA + - Fix: the issue when there is no space between 2 attributes + - Fix: https://github.com/NaturalIntelligence/fast-xml-parser/issues/33: when there is newline char in attr val, it doesn't parse + - Merge pull request: fix ignoreNamespace + - fix: don't wrap attributes if only namespace attrs + - fix: use portfinder for run tests, update deps + - fix: don't treat namespaces as attributes when ignoreNamespace enabled + +2.9.0 / 2018-01-10 + - Rewrite the validator to handle large files. + Ignore DOCTYPE validation. + - Fix: When attribute value has equal sign + +2.8.3 / 2017-12-15 + - Fix: when a tag has value along with subtags + +2.8.2 / 2017-12-04 + - Fix value parsing for IE + +2.8.1 / 2017-12-01 + - fix: validator should return false instead of err when invalid XML + +2.8.0 / 2017-11-29 + - Add CLI option to ignore value conversion + - Fix variable name when filename is given on CLI + - Update CLI help text + - Merge pull request: xml2js: Accept standard input + - Test Node 8 + - Update dependencies + - Bundle readToEnd + - Add ability to read from standard input + +2.7.4 / 2017-09-22 + - Merge pull request: Allow wrap attributes with subobject to compatible with other parsers output + +2.7.3 / 2017-08-02 + - fix: handle CDATA with regx + +2.7.2 / 2017-07-30 + - Change travis config for yarn caching + - fix validator: when tag property is same as array property + - Merge pull request: Failing test case in validator for valid SVG + +2.7.1 / 2017-07-26 + - Fix: Handle val 0 + +2.7.0 / 2017-07-25 + - Fix test for arrayMode + - Merge pull request: Add arrayMode option to parse any nodes as arrays + +2.6.0 / 2017-07-14 + - code improvement + - Add unit tests for value conversion for attr + - Merge pull request: option of an attribute value conversion to a number (textAttrConversion) the same way as the textNodeConversion option does. Default value is false. + +2.5.1 / 2017-07-01 + - Fix XML element name pattern + - Fix XML element name pattern while parsing + - Fix validation for xml tag element + +2.5.0 / 2017-06-25 + - Improve Validator performance + - update attr matching regex + - Add perf tests + - Improve atrr regex to handle all cases + +2.4.4 / 2017-06-08 + - Bug fix: when an attribute has single or double quote in value + +2.4.3 / 2017-06-05 + - Bug fix: when multiple CDATA tags are given + - Merge pull request: add option "textNodeConversion" + - add option "textNodeConversion" + +2.4.1 / 2017-04-14 + - fix tests + - Bug fix: preserve initial space of node value + - Handle CDATA + +2.3.1 / 2017-03-15 + - Bug fix: when single self closing tag + - Merge pull request: fix .codeclimate.yml + - Update .codeclimate.yml - Fixed config so it does not error anymore. + - Update .codeclimate.yml + +2.3.0 / 2017-02-26 + - Code improvement + - add bithound config + - Update usage + - Update travis to generate bundle js before running tests + - 1.Browserify, 2. add more tests for validator + - Add validator + - Fix CLI default parameter bug + +2.2.1 / 2017-02-05 + - Bug fix: CLI default option diff --git a/node_modules/fast-xml-parser/LICENSE b/node_modules/fast-xml-parser/LICENSE new file mode 100644 index 0000000..d7da622 --- /dev/null +++ b/node_modules/fast-xml-parser/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Amit Kumar Gupta + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/fast-xml-parser/README.md b/node_modules/fast-xml-parser/README.md new file mode 100644 index 0000000..22f2ddf --- /dev/null +++ b/node_modules/fast-xml-parser/README.md @@ -0,0 +1,237 @@ +# [fast-xml-parser](https://www.npmjs.com/package/fast-xml-parser) +[![NPM quality][quality-image]][quality-url] +[![Coverage Status](https://coveralls.io/repos/github/NaturalIntelligence/fast-xml-parser/badge.svg?branch=master)](https://coveralls.io/github/NaturalIntelligence/fast-xml-parser?branch=master) +[Try me](https://naturalintelligence.github.io/fast-xml-parser/) +[![NPM total downloads](https://img.shields.io/npm/dt/fast-xml-parser.svg)](https://npm.im/fast-xml-parser) + + +Validate XML, Parse XML to JS Object, or Build XML from JS Object without C/C++ based libraries and no callback. + +--- + +Checkout our new library [Text2Chart](https://solothought.com/text2chart/flow) that constructs flow chart out of simple text. Very helpful in creating or alayzing an algorithm, and documentation purpose +
                          + +Sponsor this project + + + + + + + + donate button +
                          +
                          +
                          + + + +![fxp_sponsors](https://raw.githubusercontent.com/NaturalIntelligence/ThankYouBackers/main/assets/NI_sponsors.jpg) +- Hiroki Kokubun + +> This is a donation. No goods or services are expected in return. Any requests for refunds for those purposes will be rejected. +## Users + + + + + + + + + + + + + + + + + + + +[more](./USERs.md) + +The list of users are mostly published by Github or communicated directly. Feel free to contact if you find any information wrong. + +--- + +## Main Features + +FXP logo + +* Validate XML data syntactically +* Parse XML to JS Object +* Build XML from JS Object +* Compatible to node js packages, in browser, and in CLI (click try me button above for demo) +* Faster than any other pure JS implementation. +* It can handle big files (tested up to 100mb). +* Controlled parsing using various options +* XML Entities, HTML entities, and DOCTYPE entites are supported. +* unpaired tags (Eg `
                          ` in HTML), stop nodes (Eg ` +: + +``` + +Bundle size + +| Bundle Name | Size | +| ------------------ | ---- | +| fxbuilder.min.js | 6.5K | +| fxparser.min.js | 20K | +| fxp.min.js | 26K | +| fxvalidator.min.js | 5.7K | + +### Documents + + + + + + + +
                          v3v4v5
                          + documents +
                            +
                          1. Getting Started
                          2. +
                          3. XML Parser
                          4. +
                          5. XML Builder
                          6. +
                          7. XML Validator
                          8. +
                          9. Entities
                          10. +
                          11. HTML Document Parsing
                          12. +
                          13. PI Tag processing
                          14. +
                            +
                          1. Getting Started +
                          2. Features
                          3. +
                          4. Options
                          5. +
                          6. Output Builders
                          7. +
                          8. Value Parsers
                          9. +
                          + +**note**: version 5 is released with version 4 tfor experimental use. Based on it's demand, it'll be developed and the features can be different in final release. + +## Performance +negative means error + +### XML Parser + + + + +* Y-axis: requests per second +* X-axis: File size + +### XML Builder + + +* Y-axis: requests per second + + + + + + +## Usage Trend + +[Usage Trend of fast-xml-parser](https://npm-compare.com/fast-xml-parser#timeRange=THREE_YEARS) + + + NPM Usage Trend of fast-xml-parser + + +## Supporters +### Contributors + +This project exists thanks to [all](graphs/contributors) the people who contribute. [[Contribute](docs/CONTRIBUTING.md)]. + + + + +### Backers + +Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/fast-xml-parser#backer)] + + + + + +# License +* MIT License + +![Donate $5](static/img/donation_quote.png) diff --git a/node_modules/fast-xml-parser/package.json b/node_modules/fast-xml-parser/package.json new file mode 100644 index 0000000..285ff12 --- /dev/null +++ b/node_modules/fast-xml-parser/package.json @@ -0,0 +1,72 @@ +{ + "name": "fast-xml-parser", + "version": "4.5.3", + "description": "Validate XML, Parse XML, Build XML without C/C++ based libraries", + "main": "./src/fxp.js", + "scripts": { + "test": "nyc --reporter=lcov --reporter=text jasmine spec/*spec.js", + "test-types": "tsc --noEmit spec/typings/typings-test.ts", + "unit": "jasmine", + "coverage": "nyc report --reporter html --reporter text -t .nyc_output --report-dir .nyc_output/summary", + "perf": "node ./benchmark/perfTest3.js", + "lint": "eslint src/*.js spec/*.js", + "bundle": "webpack --config webpack-prod.config.js", + "prettier": "prettier --write src/**/*.js", + "publish-please": "publish-please", + "checkReadiness": "publish-please --dry-run" + }, + "bin": { + "fxparser": "./src/cli/cli.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/NaturalIntelligence/fast-xml-parser" + }, + "keywords": [ + "fast", + "xml", + "json", + "parser", + "xml2js", + "x2js", + "xml2json", + "js", + "cli", + "validator", + "validate", + "transformer", + "assert", + "js2xml", + "json2xml", + "html" + ], + "author": "Amit Gupta (https://solothought.com)", + "license": "MIT", + "devDependencies": { + "@babel/core": "^7.13.10", + "@babel/plugin-transform-runtime": "^7.13.10", + "@babel/preset-env": "^7.13.10", + "@babel/register": "^7.13.8", + "@types/node": "20", + "babel-loader": "^8.2.2", + "eslint": "^8.3.0", + "he": "^1.2.0", + "jasmine": "^3.6.4", + "nyc": "^15.1.0", + "prettier": "^1.19.1", + "publish-please": "^5.5.2", + "typescript": "5", + "webpack": "^5.64.4", + "webpack-cli": "^4.9.1" + }, + "typings": "src/fxp.d.ts", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "dependencies": { + "strnum": "^1.1.1" + } +} diff --git a/node_modules/fast-xml-parser/src/cli/cli.js b/node_modules/fast-xml-parser/src/cli/cli.js new file mode 100644 index 0000000..2bc0cd6 --- /dev/null +++ b/node_modules/fast-xml-parser/src/cli/cli.js @@ -0,0 +1,93 @@ +#!/usr/bin/env node +'use strict'; +/*eslint-disable no-console*/ +const fs = require('fs'); +const path = require('path'); +const {XMLParser, XMLValidator} = require("../fxp"); +const readToEnd = require('./read').readToEnd; + +const version = require('./../../package.json').version; +if (process.argv[2] === '--help' || process.argv[2] === '-h') { + console.log(require("./man")); +} else if (process.argv[2] === '--version') { + console.log(version); +} else { + const options = { + removeNSPrefix: true, + ignoreAttributes: false, + parseTagValue: true, + parseAttributeValue: true, + }; + let fileName = ''; + let outputFileName; + let validate = false; + let validateOnly = false; + for (let i = 2; i < process.argv.length; i++) { + if (process.argv[i] === '-ns') { + options.removeNSPrefix = false; + } else if (process.argv[i] === '-a') { + options.ignoreAttributes = true; + } else if (process.argv[i] === '-c') { + options.parseTagValue = false; + options.parseAttributeValue = false; + } else if (process.argv[i] === '-o') { + outputFileName = process.argv[++i]; + } else if (process.argv[i] === '-v') { + validate = true; + } else if (process.argv[i] === '-V') { + validateOnly = true; + } else { + //filename + fileName = process.argv[i]; + } + } + + const callback = function(xmlData) { + let output = ''; + if (validate) { + const parser = new XMLParser(options); + output = parser.parse(xmlData,validate); + } else if (validateOnly) { + output = XMLValidator.validate(xmlData); + process.exitCode = output === true ? 0 : 1; + } else { + const parser = new XMLParser(options); + output = JSON.stringify(parser.parse(xmlData,validate), null, 4); + } + if (outputFileName) { + writeToFile(outputFileName, output); + } else { + console.log(JSON.stringify(output, null, 2)); + } + }; + + try { + + if (!fileName) { + readToEnd(process.stdin, function(err, data) { + if (err) { + throw err; + } + callback(data.toString()); + }); + } else { + fs.readFile(fileName, function(err, data) { + if (err) { + throw err; + } + callback(data.toString()); + }); + } + } catch (e) { + console.log('Seems an invalid file or stream.' + e); + } +} + +function writeToFile(fileName, data) { + fs.writeFile(fileName, data, function(err) { + if (err) { + throw err; + } + console.log('JSON output has been written to ' + fileName); + }); +} diff --git a/node_modules/fast-xml-parser/src/cli/man.js b/node_modules/fast-xml-parser/src/cli/man.js new file mode 100644 index 0000000..89947cc --- /dev/null +++ b/node_modules/fast-xml-parser/src/cli/man.js @@ -0,0 +1,12 @@ +module.exports = `Fast XML Parser 4.0.0 +---------------- +$ fxparser [-ns|-a|-c|-v|-V] [-o outputfile.json] +$ cat xmlfile.xml | fxparser [-ns|-a|-c|-v|-V] [-o outputfile.json] + +Options +---------------- +-ns: remove namespace from tag and atrribute name. +-a: don't parse attributes. +-c: parse values to premitive type. +-v: validate before parsing. +-V: validate only.` \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/cli/read.js b/node_modules/fast-xml-parser/src/cli/read.js new file mode 100644 index 0000000..642da52 --- /dev/null +++ b/node_modules/fast-xml-parser/src/cli/read.js @@ -0,0 +1,92 @@ +'use strict'; + +// Copyright 2013 Timothy J Fontaine +// +// 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 + +/* + +Read any stream all the way to the end and trigger a single cb + +const http = require('http'); + +const rte = require('readtoend'); + +http.get('http://nodejs.org', function(response) { + rte.readToEnd(response, function(err, body) { + console.log(body); + }); +}); + +*/ + +let stream = require('stream'); +const util = require('util'); + +if (!stream.Transform) { + stream = require('readable-stream'); +} + +function ReadToEnd(opts) { + if (!(this instanceof ReadToEnd)) { + return new ReadToEnd(opts); + } + + stream.Transform.call(this, opts); + + this._rte_encoding = opts.encoding || 'utf8'; + + this._buff = ''; +} + +module.exports = ReadToEnd; +util.inherits(ReadToEnd, stream.Transform); + +ReadToEnd.prototype._transform = function(chunk, encoding, done) { + this._buff += chunk.toString(this._rte_encoding); + this.push(chunk); + done(); +}; + +ReadToEnd.prototype._flush = function(done) { + this.emit('complete', undefined, this._buff); + done(); +}; + +ReadToEnd.readToEnd = function(stream, options, cb) { + if (!cb) { + cb = options; + options = {}; + } + + const dest = new ReadToEnd(options); + + stream.pipe(dest); + + stream.on('error', function(err) { + stream.unpipe(dest); + cb(err); + }); + + dest.on('complete', cb); + + dest.resume(); + + return dest; +}; diff --git a/node_modules/fast-xml-parser/src/fxp.d.ts b/node_modules/fast-xml-parser/src/fxp.d.ts new file mode 100644 index 0000000..7a48b9d --- /dev/null +++ b/node_modules/fast-xml-parser/src/fxp.d.ts @@ -0,0 +1,418 @@ +type X2jOptions = { + /** + * Preserve the order of tags in resulting JS object + * + * Defaults to `false` + */ + preserveOrder?: boolean; + + /** + * Give a prefix to the attribute name in the resulting JS object + * + * Defaults to '@_' + */ + attributeNamePrefix?: string; + + /** + * A name to group all attributes of a tag under, or `false` to disable + * + * Defaults to `false` + */ + attributesGroupName?: false | string; + + /** + * The name of the next node in the resulting JS + * + * Defaults to `#text` + */ + textNodeName?: string; + + /** + * Whether to ignore attributes when parsing + * + * When `true` - ignores all the attributes + * + * When `false` - parses all the attributes + * + * When `Array` - filters out attributes that match provided patterns + * + * When `Function` - calls the function for each attribute and filters out those for which the function returned `true` + * + * Defaults to `true` + */ + ignoreAttributes?: boolean | (string | RegExp)[] | ((attrName: string, jPath: string) => boolean); + + /** + * Whether to remove namespace string from tag and attribute names + * + * Defaults to `false` + */ + removeNSPrefix?: boolean; + + /** + * Whether to allow attributes without value + * + * Defaults to `false` + */ + allowBooleanAttributes?: boolean; + + /** + * Whether to parse tag value with `strnum` package + * + * Defaults to `true` + */ + parseTagValue?: boolean; + + /** + * Whether to parse tag value with `strnum` package + * + * Defaults to `false` + */ + parseAttributeValue?: boolean; + + /** + * Whether to remove surrounding whitespace from tag or attribute value + * + * Defaults to `true` + */ + trimValues?: boolean; + + /** + * Give a property name to set CDATA values to instead of merging to tag's text value + * + * Defaults to `false` + */ + cdataPropName?: false | string; + + /** + * If set, parse comments and set as this property + * + * Defaults to `false` + */ + commentPropName?: false | string; + + /** + * Control how tag value should be parsed. Called only if tag value is not empty + * + * @returns {undefined|null} `undefined` or `null` to set original value. + * @returns {unknown} + * + * 1. Different value or value with different data type to set new value. + * 2. Same value to set parsed value if `parseTagValue: true`. + * + * Defaults to `(tagName, val, jPath, hasAttributes, isLeafNode) => val` + */ + tagValueProcessor?: (tagName: string, tagValue: string, jPath: string, hasAttributes: boolean, isLeafNode: boolean) => unknown; + + /** + * Control how attribute value should be parsed + * + * @param attrName + * @param attrValue + * @param jPath + * @returns {undefined|null} `undefined` or `null` to set original value + * @returns {unknown} + * + * Defaults to `(attrName, val, jPath) => val` + */ + attributeValueProcessor?: (attrName: string, attrValue: string, jPath: string) => unknown; + + /** + * Options to pass to `strnum` for parsing numbers + * + * Defaults to `{ hex: true, leadingZeros: true, eNotation: true }` + */ + numberParseOptions?: strnumOptions; + + /** + * Nodes to stop parsing at + * + * Defaults to `[]` + */ + stopNodes?: string[]; + + /** + * List of tags without closing tags + * + * Defaults to `[]` + */ + unpairedTags?: string[]; + + /** + * Whether to always create a text node + * + * Defaults to `false` + */ + alwaysCreateTextNode?: boolean; + + /** + * Determine whether a tag should be parsed as an array + * + * @param tagName + * @param jPath + * @param isLeafNode + * @param isAttribute + * @returns {boolean} + * + * Defaults to `() => false` + */ + isArray?: (tagName: string, jPath: string, isLeafNode: boolean, isAttribute: boolean) => boolean; + + /** + * Whether to process default and DOCTYPE entities + * + * Defaults to `true` + */ + processEntities?: boolean; + + /** + * Whether to process HTML entities + * + * Defaults to `false` + */ + htmlEntities?: boolean; + + /** + * Whether to ignore the declaration tag from output + * + * Defaults to `false` + */ + ignoreDeclaration?: boolean; + + /** + * Whether to ignore Pi tags + * + * Defaults to `false` + */ + ignorePiTags?: boolean; + + /** + * Transform tag names + * + * Defaults to `false` + */ + transformTagName?: ((tagName: string) => string) | false; + + /** + * Transform attribute names + * + * Defaults to `false` + */ + transformAttributeName?: ((attributeName: string) => string) | false; + + /** + * Change the tag name when a different name is returned. Skip the tag from parsed result when false is returned. + * Modify `attrs` object to control attributes for the given tag. + * + * @returns {string} new tag name. + * @returns false to skip the tag + * + * Defaults to `(tagName, jPath, attrs) => tagName` + */ + updateTag?: (tagName: string, jPath: string, attrs: {[k: string]: string}) => string | boolean; +}; + +type strnumOptions = { + hex: boolean; + leadingZeros: boolean, + skipLike?: RegExp, + eNotation?: boolean +} + +type validationOptions = { + /** + * Whether to allow attributes without value + * + * Defaults to `false` + */ + allowBooleanAttributes?: boolean; + + /** + * List of tags without closing tags + * + * Defaults to `[]` + */ + unpairedTags?: string[]; +}; + +type XmlBuilderOptions = { + /** + * Give a prefix to the attribute name in the resulting JS object + * + * Defaults to '@_' + */ + attributeNamePrefix?: string; + + /** + * A name to group all attributes of a tag under, or `false` to disable + * + * Defaults to `false` + */ + attributesGroupName?: false | string; + + /** + * The name of the next node in the resulting JS + * + * Defaults to `#text` + */ + textNodeName?: string; + + /** + * Whether to ignore attributes when building + * + * When `true` - ignores all the attributes + * + * When `false` - builds all the attributes + * + * When `Array` - filters out attributes that match provided patterns + * + * When `Function` - calls the function for each attribute and filters out those for which the function returned `true` + * + * Defaults to `true` + */ + ignoreAttributes?: boolean | (string | RegExp)[] | ((attrName: string, jPath: string) => boolean); + + /** + * Give a property name to set CDATA values to instead of merging to tag's text value + * + * Defaults to `false` + */ + cdataPropName?: false | string; + + /** + * If set, parse comments and set as this property + * + * Defaults to `false` + */ + commentPropName?: false | string; + + /** + * Whether to make output pretty instead of single line + * + * Defaults to `false` + */ + format?: boolean; + + + /** + * If `format` is set to `true`, sets the indent string + * + * Defaults to ` ` + */ + indentBy?: string; + + /** + * Give a name to a top-level array + * + * Defaults to `undefined` + */ + arrayNodeName?: string; + + /** + * Create empty tags for tags with no text value + * + * Defaults to `false` + */ + suppressEmptyNode?: boolean; + + /** + * Suppress an unpaired tag + * + * Defaults to `true` + */ + suppressUnpairedNode?: boolean; + + /** + * Don't put a value for boolean attributes + * + * Defaults to `true` + */ + suppressBooleanAttributes?: boolean; + + /** + * Preserve the order of tags in resulting JS object + * + * Defaults to `false` + */ + preserveOrder?: boolean; + + /** + * List of tags without closing tags + * + * Defaults to `[]` + */ + unpairedTags?: string[]; + + /** + * Nodes to stop parsing at + * + * Defaults to `[]` + */ + stopNodes?: string[]; + + /** + * Control how tag value should be parsed. Called only if tag value is not empty + * + * @returns {undefined|null} `undefined` or `null` to set original value. + * @returns {unknown} + * + * 1. Different value or value with different data type to set new value. + * 2. Same value to set parsed value if `parseTagValue: true`. + * + * Defaults to `(tagName, val, jPath, hasAttributes, isLeafNode) => val` + */ + tagValueProcessor?: (name: string, value: unknown) => unknown; + + /** + * Control how attribute value should be parsed + * + * @param attrName + * @param attrValue + * @param jPath + * @returns {undefined|null} `undefined` or `null` to set original value + * @returns {unknown} + * + * Defaults to `(attrName, val, jPath) => val` + */ + attributeValueProcessor?: (name: string, value: unknown) => unknown; + + /** + * Whether to process default and DOCTYPE entities + * + * Defaults to `true` + */ + processEntities?: boolean; + + + oneListGroup?: boolean; +}; + +type ESchema = string | object | Array; + +type ValidationError = { + err: { + code: string; + msg: string, + line: number, + col: number + }; +}; + +export class XMLParser { + constructor(options?: X2jOptions); + parse(xmlData: string | Buffer ,validationOptions?: validationOptions | boolean): any; + /** + * Add Entity which is not by default supported by this library + * @param entityIdentifier {string} Eg: 'ent' for &ent; + * @param entityValue {string} Eg: '\r' + */ + addEntity(entityIdentifier: string, entityValue: string): void; +} + +export class XMLValidator{ + static validate( xmlData: string, options?: validationOptions): true | ValidationError; +} +export class XMLBuilder { + constructor(options?: XmlBuilderOptions); + build(jObj: any): any; +} diff --git a/node_modules/fast-xml-parser/src/fxp.js b/node_modules/fast-xml-parser/src/fxp.js new file mode 100644 index 0000000..9cfa0ac --- /dev/null +++ b/node_modules/fast-xml-parser/src/fxp.js @@ -0,0 +1,11 @@ +'use strict'; + +const validator = require('./validator'); +const XMLParser = require('./xmlparser/XMLParser'); +const XMLBuilder = require('./xmlbuilder/json2xml'); + +module.exports = { + XMLParser: XMLParser, + XMLValidator: validator, + XMLBuilder: XMLBuilder +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/ignoreAttributes.js b/node_modules/fast-xml-parser/src/ignoreAttributes.js new file mode 100644 index 0000000..9fb346b --- /dev/null +++ b/node_modules/fast-xml-parser/src/ignoreAttributes.js @@ -0,0 +1,20 @@ +function getIgnoreAttributesFn(ignoreAttributes) { + if (typeof ignoreAttributes === 'function') { + return ignoreAttributes + } + if (Array.isArray(ignoreAttributes)) { + return (attrName) => { + for (const pattern of ignoreAttributes) { + if (typeof pattern === 'string' && attrName === pattern) { + return true + } + if (pattern instanceof RegExp && pattern.test(attrName)) { + return true + } + } + } + } + return () => false +} + +module.exports = getIgnoreAttributesFn \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/util.js b/node_modules/fast-xml-parser/src/util.js new file mode 100644 index 0000000..df0a60d --- /dev/null +++ b/node_modules/fast-xml-parser/src/util.js @@ -0,0 +1,72 @@ +'use strict'; + +const nameStartChar = ':A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; +const nameChar = nameStartChar + '\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040'; +const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*' +const regexName = new RegExp('^' + nameRegexp + '$'); + +const getAllMatches = function(string, regex) { + const matches = []; + let match = regex.exec(string); + while (match) { + const allmatches = []; + allmatches.startIndex = regex.lastIndex - match[0].length; + const len = match.length; + for (let index = 0; index < len; index++) { + allmatches.push(match[index]); + } + matches.push(allmatches); + match = regex.exec(string); + } + return matches; +}; + +const isName = function(string) { + const match = regexName.exec(string); + return !(match === null || typeof match === 'undefined'); +}; + +exports.isExist = function(v) { + return typeof v !== 'undefined'; +}; + +exports.isEmptyObject = function(obj) { + return Object.keys(obj).length === 0; +}; + +/** + * Copy all the properties of a into b. + * @param {*} target + * @param {*} a + */ +exports.merge = function(target, a, arrayMode) { + if (a) { + const keys = Object.keys(a); // will return an array of own properties + const len = keys.length; //don't make it inline + for (let i = 0; i < len; i++) { + if (arrayMode === 'strict') { + target[keys[i]] = [ a[keys[i]] ]; + } else { + target[keys[i]] = a[keys[i]]; + } + } + } +}; +/* exports.merge =function (b,a){ + return Object.assign(b,a); +} */ + +exports.getValue = function(v) { + if (exports.isExist(v)) { + return v; + } else { + return ''; + } +}; + +// const fakeCall = function(a) {return a;}; +// const fakeCallNoReturn = function() {}; + +exports.isName = isName; +exports.getAllMatches = getAllMatches; +exports.nameRegexp = nameRegexp; diff --git a/node_modules/fast-xml-parser/src/v5/CharsSymbol.js b/node_modules/fast-xml-parser/src/v5/CharsSymbol.js new file mode 100644 index 0000000..fa5ce9e --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/CharsSymbol.js @@ -0,0 +1,16 @@ +modules.export = { + "<" : "<", //tag start + ">" : ">", //tag end + "/" : "/", //close tag + "!" : "!", //comment or docttype + "!--" : "!--", //comment + "-->" : "-->", //comment end + "?" : "?", //pi + "?>" : "?>", //pi end + "?xml" : "?xml", //pi end + "![" : "![", //cdata + "]]>" : "]]>", //cdata end + "[" : "[", + "-" : "-", + "D" : "D", +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/EntitiesParser.js b/node_modules/fast-xml-parser/src/v5/EntitiesParser.js new file mode 100644 index 0000000..62cc02f --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/EntitiesParser.js @@ -0,0 +1,107 @@ +const ampEntity = { regex: /&(amp|#38|#x26);/g, val : "&"}; +const htmlEntities = { + "space": { regex: /&(nbsp|#160);/g, val: " " }, + // "lt" : { regex: /&(lt|#60);/g, val: "<" }, + // "gt" : { regex: /&(gt|#62);/g, val: ">" }, + // "amp" : { regex: /&(amp|#38);/g, val: "&" }, + // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, + // "apos" : { regex: /&(apos|#39);/g, val: "'" }, + "cent" : { regex: /&(cent|#162);/g, val: "¢" }, + "pound" : { regex: /&(pound|#163);/g, val: "£" }, + "yen" : { regex: /&(yen|#165);/g, val: "¥" }, + "euro" : { regex: /&(euro|#8364);/g, val: "€" }, + "copyright" : { regex: /&(copy|#169);/g, val: "©" }, + "reg" : { regex: /&(reg|#174);/g, val: "®" }, + "inr" : { regex: /&(inr|#8377);/g, val: "₹" }, + "num_dec": { regex: /&#([0-9]{1,7});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 10)) }, + "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 16)) }, +}; + +class EntitiesParser{ + constructor(replaceHtmlEntities) { + this.replaceHtmlEntities = replaceHtmlEntities; + this.docTypeEntities = {}; + this.lastEntities = { + "apos" : { regex: /&(apos|#39|#x27);/g, val : "'"}, + "gt" : { regex: /&(gt|#62|#x3E);/g, val : ">"}, + "lt" : { regex: /&(lt|#60|#x3C);/g, val : "<"}, + "quot" : { regex: /&(quot|#34|#x22);/g, val : "\""}, + }; + } + + addExternalEntities(externalEntities){ + const entKeys = Object.keys(externalEntities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + this.addExternalEntity(ent,externalEntities[ent]) + } + } + addExternalEntity(key,val){ + validateEntityName(key); + if(val.indexOf("&") !== -1) { + reportWarning(`Entity ${key} is not added as '&' is found in value;`) + return; + }else{ + this.lastEntities[ent] = { + regex: new RegExp("&"+key+";","g"), + val : val + } + } + } + + addDocTypeEntities(entities){ + const entKeys = Object.keys(entities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + this.docTypeEntities[ent] = { + regex: new RegExp("&"+ent+";","g"), + val : entities[ent] + } + } + } + + parse(val){ + return this.replaceEntitiesValue(val) + } + + /** + * 1. Replace DOCTYPE entities + * 2. Replace external entities + * 3. Replace HTML entities if asked + * @param {string} val + */ + replaceEntitiesValue(val){ + if(typeof val === "string" && val.length > 0){ + for(let entityName in this.docTypeEntities){ + const entity = this.docTypeEntities[entityName]; + val = val.replace( entity.regx, entity.val); + } + for(let entityName in this.lastEntities){ + const entity = this.lastEntities[entityName]; + val = val.replace( entity.regex, entity.val); + } + if(this.replaceHtmlEntities){ + for(let entityName in htmlEntities){ + const entity = htmlEntities[entityName]; + val = val.replace( entity.regex, entity.val); + } + } + val = val.replace( ampEntity.regex, ampEntity.val); + } + return val; + } +}; + +//an entity name should not contains special characters that may be used in regex +//Eg !?\\\/[]$%{}^&*()<> +const specialChar = "!?\\\/[]$%{}^&*()<>|+"; + +function validateEntityName(name){ + for (let i = 0; i < specialChar.length; i++) { + const ch = specialChar[i]; + if(name.indexOf(ch) !== -1) throw new Error(`Invalid character ${ch} in entity name`); + } + return name; +} + +module.exports = EntitiesParser; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/OptionsBuilder.js b/node_modules/fast-xml-parser/src/v5/OptionsBuilder.js new file mode 100644 index 0000000..be1f1d4 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/OptionsBuilder.js @@ -0,0 +1,64 @@ + +const JsObjOutputBuilder = require("./OutputBuilders/JsObjBuilder"); + +const defaultOptions = { + preserveOrder: false, + removeNSPrefix: false, // remove NS from tag name or attribute name if true + //ignoreRootElement : false, + stopNodes: [], //nested tags will not be parsed even for errors + // isArray: () => false, //User will set it + htmlEntities: false, + // skipEmptyListItem: false + tags:{ + unpaired: [], + nameFor:{ + cdata: false, + comment: false, + text: '#text' + }, + separateTextProperty: false, + }, + attributes:{ + ignore: false, + booleanType: true, + entities: true, + }, + + // select: ["img[src]"], + // stop: ["anim", "[ads]"] + only: [], // rest tags will be skipped. It will result in flat array + hierarchy: false, //will be used when a particular tag is set to be parsed. + skip: [], // will be skipped from parse result. on('skip') will be triggered + + select: [], // on('select', tag => tag ) will be called if match + stop: [], //given tagPath will not be parsed. innerXML will be set as string value + OutputBuilder: new JsObjOutputBuilder(), +}; + +const buildOptions = function(options) { + const finalOptions = { ... defaultOptions}; + copyProperties(finalOptions,options) + return finalOptions; +}; + +function copyProperties(target, source) { + for (let key in source) { + if (source.hasOwnProperty(key)) { + if (key === 'OutputBuilder') { + target[key] = source[key]; + }else if (typeof source[key] === 'object' && !Array.isArray(source[key])) { + // Recursively copy nested properties + if (typeof target[key] === 'undefined') { + target[key] = {}; + } + copyProperties(target[key], source[key]); + } else { + // Copy non-nested properties + target[key] = source[key]; + } + } + } +} + +exports.buildOptions = buildOptions; +exports.defaultOptions = defaultOptions; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/OutputBuilders/BaseOutputBuilder.js b/node_modules/fast-xml-parser/src/v5/OutputBuilders/BaseOutputBuilder.js new file mode 100644 index 0000000..be2d478 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/OutputBuilders/BaseOutputBuilder.js @@ -0,0 +1,71 @@ +class BaseOutputBuilder{ + constructor(){ + // this.attributes = {}; + } + + addAttribute(name, value){ + if(this.options.onAttribute){ + //TODO: better to pass tag path + const v = this.options.onAttribute(name, value, this.tagName); + if(v) this.attributes[v.name] = v.value; + }else{ + name = this.options.attributes.prefix + name + this.options.attributes.suffix; + this.attributes[name] = this.parseValue(value, this.options.attributes.valueParsers); + } + } + + /** + * parse value by chain of parsers + * @param {string} val + * @returns {any} parsed value if matching parser found + */ + parseValue = function(val, valParsers){ + for (let i = 0; i < valParsers.length; i++) { + let valParser = valParsers[i]; + if(typeof valParser === "string"){ + valParser = this.registeredParsers[valParser]; + } + if(valParser){ + val = valParser.parse(val); + } + } + return val; + } + + /** + * To add a nested empty tag. + * @param {string} key + * @param {any} val + */ + _addChild(key, val){} + + /** + * skip the comment if property is not set + */ + addComment(text){ + if(this.options.nameFor.comment) + this._addChild(this.options.nameFor.comment, text); + } + + //store CDATA separately if property is set + //otherwise add to tag's value + addCdata(text){ + if (this.options.nameFor.cdata) { + this._addChild(this.options.nameFor.cdata, text); + } else { + this.addRawValue(text || ""); + } + } + + addRawValue = text => this.addValue(text); + + addDeclaration(){ + if(!this.options.declaration){ + }else{ + this.addPi("?xml"); + } + this.attributes = {} + } +} + +module.exports = BaseOutputBuilder; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/OutputBuilders/JsArrBuilder.js b/node_modules/fast-xml-parser/src/v5/OutputBuilders/JsArrBuilder.js new file mode 100644 index 0000000..c63f627 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/OutputBuilders/JsArrBuilder.js @@ -0,0 +1,103 @@ +const {buildOptions,registerCommonValueParsers} = require("./ParserOptionsBuilder"); + +class OutputBuilder{ + constructor(options){ + this.options = buildOptions(options); + this.registeredParsers = registerCommonValueParsers(this.options); + } + + registerValueParser(name,parserInstance){//existing name will override the parser without warning + this.registeredParsers[name] = parserInstance; + } + + getInstance(parserOptions){ + return new JsArrBuilder(parserOptions, this.options, this.registeredParsers); + } +} + +const rootName = '!js_arr'; +const BaseOutputBuilder = require("./BaseOutputBuilder"); + +class JsArrBuilder extends BaseOutputBuilder{ + + constructor(parserOptions, options,registeredParsers) { + super(); + this.tagsStack = []; + this.parserOptions = parserOptions; + this.options = options; + this.registeredParsers = registeredParsers; + + this.root = new Node(rootName); + this.currentNode = this.root; + this.attributes = {}; + } + + addTag(tag){ + //when a new tag is added, it should be added as child of current node + //TODO: shift this check to the parser + if(tag.name === "__proto__") tag.name = "#__proto__"; + + this.tagsStack.push(this.currentNode); + this.currentNode = new Node(tag.name, this.attributes); + this.attributes = {}; + } + + /** + * Check if the node should be added by checking user's preference + * @param {Node} node + * @returns boolean: true if the node should not be added + */ + closeTag(){ + const node = this.currentNode; + this.currentNode = this.tagsStack.pop(); //set parent node in scope + if(this.options.onClose !== undefined){ + //TODO TagPathMatcher + const resultTag = this.options.onClose(node, + new TagPathMatcher(this.tagsStack,node)); + + if(resultTag) return; + } + this.currentNode.child.push(node); //to parent node + } + + //Called by parent class methods + _addChild(key, val){ + // if(key === "__proto__") tagName = "#__proto__"; + this.currentNode.child.push( {[key]: val }); + // this.currentNode.leafType = false; + } + + /** + * Add text value child node + * @param {string} text + */ + addValue(text){ + this.currentNode.child.push( {[this.options.nameFor.text]: this.parseValue(text, this.options.tags.valueParsers) }); + } + + addPi(name){ + //TODO: set pi flag + if(!this.options.ignorePiTags){ + const node = new Node(name, this.attributes); + this.currentNode[":@"] = this.attributes; + this.currentNode.child.push(node); + } + this.attributes = {}; + } + getOutput(){ + return this.root.child[0]; + } +} + + + +class Node{ + constructor(tagname, attributes){ + this.tagname = tagname; + this.child = []; //nested tags, text, cdata, comments + if(attributes && Object.keys(attributes).length > 0) + this[":@"] = attributes; + } +} + +module.exports = OutputBuilder; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/OutputBuilders/JsMinArrBuilder.js b/node_modules/fast-xml-parser/src/v5/OutputBuilders/JsMinArrBuilder.js new file mode 100644 index 0000000..e0dc1e9 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/OutputBuilders/JsMinArrBuilder.js @@ -0,0 +1,102 @@ +const {buildOptions,registerCommonValueParsers} = require("./ParserOptionsBuilder"); + +class OutputBuilder{ + constructor(options){ + this.options = buildOptions(options); + this.registeredParsers = registerCommonValueParsers(this.options); + } + + registerValueParser(name,parserInstance){//existing name will override the parser without warning + this.registeredParsers[name] = parserInstance; + } + + getInstance(parserOptions){ + return new JsMinArrBuilder(parserOptions, this.options, this.registeredParsers); + } +} + +const BaseOutputBuilder = require("./BaseOutputBuilder"); +const rootName = '^'; + +class JsMinArrBuilder extends BaseOutputBuilder{ + + constructor(parserOptions, options,registeredParsers) { + super(); + this.tagsStack = []; + this.parserOptions = parserOptions; + this.options = options; + this.registeredParsers = registeredParsers; + + this.root = {[rootName]: []}; + this.currentNode = this.root; + this.currentNodeTagName = rootName; + this.attributes = {}; + } + + addTag(tag){ + //when a new tag is added, it should be added as child of current node + //TODO: shift this check to the parser + if(tag.name === "__proto__") tag.name = "#__proto__"; + + this.tagsStack.push([this.currentNodeTagName,this.currentNode]); //this.currentNode is parent node here + this.currentNodeTagName = tag.name; + this.currentNode = { [tag.name]:[]} + if(Object.keys(this.attributes).length > 0){ + this.currentNode[":@"] = this.attributes; + this.attributes = {}; + } + } + + /** + * Check if the node should be added by checking user's preference + * @param {Node} node + * @returns boolean: true if the node should not be added + */ + closeTag(){ + const node = this.currentNode; + const nodeName = this.currentNodeTagName; + const arr = this.tagsStack.pop(); //set parent node in scope + this.currentNodeTagName = arr[0]; + this.currentNode = arr[1]; + + if(this.options.onClose !== undefined){ + //TODO TagPathMatcher + const resultTag = this.options.onClose(node, + new TagPathMatcher(this.tagsStack,node)); + + if(resultTag) return; + } + this.currentNode[this.currentNodeTagName].push(node); //to parent node + } + + //Called by parent class methods + _addChild(key, val){ + // if(key === "__proto__") tagName = "#__proto__"; + this.currentNode.push( {[key]: val }); + // this.currentNode.leafType = false; + } + + /** + * Add text value child node + * @param {string} text + */ + addValue(text){ + this.currentNode[this.currentNodeTagName].push( {[this.options.nameFor.text]: this.parseValue(text, this.options.tags.valueParsers) }); + } + + addPi(name){ + if(!this.options.ignorePiTags){ + const node = { [name]:[]} + if(this.attributes){ + node[":@"] = this.attributes; + } + this.currentNode.push(node); + } + this.attributes = {}; + } + getOutput(){ + return this.root[rootName]; + } +} + +module.exports = OutputBuilder; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/OutputBuilders/JsObjBuilder.js b/node_modules/fast-xml-parser/src/v5/OutputBuilders/JsObjBuilder.js new file mode 100644 index 0000000..37036c5 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/OutputBuilders/JsObjBuilder.js @@ -0,0 +1,156 @@ + + +const {buildOptions,registerCommonValueParsers} = require("./ParserOptionsBuilder"); + +class OutputBuilder{ + constructor(builderOptions){ + this.options = buildOptions(builderOptions); + this.registeredParsers = registerCommonValueParsers(this.options); + } + + registerValueParser(name,parserInstance){//existing name will override the parser without warning + this.registeredParsers[name] = parserInstance; + } + + getInstance(parserOptions){ + return new JsObjBuilder(parserOptions, this.options, this.registeredParsers); + } +} + +const BaseOutputBuilder = require("./BaseOutputBuilder"); +const rootName = '^'; + +class JsObjBuilder extends BaseOutputBuilder{ + + constructor(parserOptions, builderOptions,registeredParsers) { + super(); + //hold the raw detail of a tag and sequence with reference to the output + this.tagsStack = []; + this.parserOptions = parserOptions; + this.options = builderOptions; + this.registeredParsers = registeredParsers; + + this.root = {}; + this.parent = this.root; + this.tagName = rootName; + this.value = {}; + this.textValue = ""; + this.attributes = {}; + } + + addTag(tag){ + + let value = ""; + if( !isEmpty(this.attributes)){ + value = {}; + if(this.options.attributes.groupBy){ + value[this.options.attributes.groupBy] = this.attributes; + }else{ + value = this.attributes; + } + } + + this.tagsStack.push([this.tagName, this.textValue, this.value]); //parent tag, parent text value, parent tag value (jsobj) + this.tagName = tag.name; + this.value = value; + this.textValue = ""; + this.attributes = {}; + } + + /** + * Check if the node should be added by checking user's preference + * @param {Node} node + * @returns boolean: true if the node should not be added + */ + closeTag(){ + const tagName = this.tagName; + let value = this.value; + let textValue = this.textValue; + + //update tag text value + if(typeof value !== "object" && !Array.isArray(value)){ + value = this.parseValue(textValue.trim(), this.options.tags.valueParsers); + }else if(textValue.length > 0){ + value[this.options.nameFor.text] = this.parseValue(textValue.trim(), this.options.tags.valueParsers); + } + + + let resultTag= { + tagName: tagName, + value: value + }; + + if(this.options.onTagClose !== undefined){ + //TODO TagPathMatcher + resultTag = this.options.onClose(tagName, value, this.textValue, new TagPathMatcher(this.tagsStack,node)); + + if(!resultTag) return; + } + + //set parent node in scope + let arr = this.tagsStack.pop(); + let parentTag = arr[2]; + parentTag=this._addChildTo(resultTag.tagName, resultTag.value, parentTag); + + this.tagName = arr[0]; + this.textValue = arr[1]; + this.value = parentTag; + } + + _addChild(key, val){ + if(typeof this.value === "string"){ + this.value = { [this.options.nameFor.text] : this.value }; + } + + this._addChildTo(key, val, this.value); + // this.currentNode.leafType = false; + this.attributes = {}; + } + + _addChildTo(key, val, node){ + if(typeof node === 'string') node = {}; + if(!node[key]){ + node[key] = val; + }else{ //Repeated + if(!Array.isArray(node[key])){ //but not stored as array + node[key] = [node[key]]; + } + node[key].push(val); + } + return node; + } + + + /** + * Add text value child node + * @param {string} text + */ + addValue(text){ + //TODO: use bytes join + if(this.textValue.length > 0) this.textValue += " " + text; + else this.textValue = text; + } + + addPi(name){ + let value = ""; + if( !isEmpty(this.attributes)){ + value = {}; + if(this.options.attributes.groupBy){ + value[this.options.attributes.groupBy] = this.attributes; + }else{ + value = this.attributes; + } + } + this._addChild(name, value); + + } + getOutput(){ + return this.value; + } +} + +function isEmpty(obj) { + return Object.keys(obj).length === 0; +} + +module.exports = OutputBuilder; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/OutputBuilders/ParserOptionsBuilder.js b/node_modules/fast-xml-parser/src/v5/OutputBuilders/ParserOptionsBuilder.js new file mode 100644 index 0000000..c71ea94 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/OutputBuilders/ParserOptionsBuilder.js @@ -0,0 +1,99 @@ +const trimParser = require("../valueParsers/trim") +const booleanParser = require("../valueParsers/booleanParser") +const currencyParser = require("../valueParsers/currency") +const numberParser = require("../valueParsers/number") + +const defaultOptions={ + nameFor:{ + text: "#text", + comment: "", + cdata: "", + }, + // onTagClose: () => {}, + // onAttribute: () => {}, + piTag: false, + declaration: false, //"?xml" + tags: { + valueParsers: [ + // "trim", + // "boolean", + // "number", + // "currency", + // "date", + ] + }, + attributes:{ + prefix: "@_", + suffix: "", + groupBy: "", + + valueParsers: [ + // "trim", + // "boolean", + // "number", + // "currency", + // "date", + ] + }, + dataType:{ + + } +} + +//TODO +const withJoin = ["trim","join", /*"entities",*/"number","boolean","currency"/*, "date"*/] +const withoutJoin = ["trim", /*"entities",*/"number","boolean","currency"/*, "date"*/] + +function buildOptions(options){ + //clone + const finalOptions = { ... defaultOptions}; + + //add config missed in cloning + finalOptions.tags.valueParsers.push(...withJoin) + if(!this.preserveOrder) + finalOptions.tags.valueParsers.push(...withoutJoin); + + //add config missed in cloning + finalOptions.attributes.valueParsers.push(...withJoin) + + //override configuration + copyProperties(finalOptions,options); + return finalOptions; +} + +function copyProperties(target, source) { + for (let key in source) { + if (source.hasOwnProperty(key)) { + if (typeof source[key] === 'object' && !Array.isArray(source[key])) { + // Recursively copy nested properties + if (typeof target[key] === 'undefined') { + target[key] = {}; + } + copyProperties(target[key], source[key]); + } else { + // Copy non-nested properties + target[key] = source[key]; + } + } + } +} + +function registerCommonValueParsers(options){ + return { + "trim": new trimParser(), + // "join": this.entityParser.parse, + "boolean": new booleanParser(), + "number": new numberParser({ + hex: true, + leadingZeros: true, + eNotation: true + }), + "currency": new currencyParser(), + // "date": this.entityParser.parse, + } +} + +module.exports = { + buildOptions : buildOptions, + registerCommonValueParsers: registerCommonValueParsers +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/Report.js b/node_modules/fast-xml-parser/src/v5/Report.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/fast-xml-parser/src/v5/TagPath.js b/node_modules/fast-xml-parser/src/v5/TagPath.js new file mode 100644 index 0000000..d901cc3 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/TagPath.js @@ -0,0 +1,81 @@ +class TagPath{ + constructor(pathStr){ + let text = ""; + let tName = ""; + let pos; + let aName = ""; + let aVal = ""; + this.stack = [] + + for (let i = 0; i < pathStr.length; i++) { + let ch = pathStr[i]; + if(ch === " ") { + if(text.length === 0) continue; + tName = text; text = ""; + }else if(ch === "["){ + if(tName.length === 0){ + tName = text; text = ""; + } + i++; + for (; i < pathStr.length; i++) { + ch = pathStr[i]; + if(ch=== "=") continue; + else if(ch=== "]") {aName = text.trim(); text=""; break; i--;} + else if(ch === "'" || ch === '"'){ + let attrEnd = pathStr.indexOf(ch,i+1); + aVal = pathStr.substring(i+1, attrEnd); + i = attrEnd; + }else{ + text +=ch; + } + } + }else if(ch !== " " && text.length === 0 && tName.length > 0){//reading tagName + //save previous tag + this.stack.push(new TagPathNode(tName,pos,aName,aVal)); + text = ch; tName = ""; aName = ""; aVal = ""; + }else{ + text+=ch; + } + } + + //last tag in the path + if(tName.length >0 || text.length>0){ + this.stack.push(new TagPathNode(text||tName,pos,aName,aVal)); + } + } + + match(tagStack,node){ + if(this.stack[0].name !== "*"){ + if(this.stack.length !== tagStack.length +1) return false; + + //loop through tagPath and tagStack and match + for (let i = 0; i < this.tagStack.length; i++) { + if(!this.stack[i].match(tagStack[i])) return false; + } + } + if(!this.stack[this.stack.length - 1].match(node)) return false; + return true; + } +} + +class TagPathNode{ + constructor(name,position,attrName,attrVal){ + this.name = name; + this.position = position; + this.attrName = attrName, + this.attrVal = attrVal; + } + + match(node){ + let matching = true; + matching = node.name === this.name; + if(this.position) matching = node.position === this.position; + if(this.attrName) matching = node.attrs[this.attrName !== undefined]; + if(this.attrVal) matching = node.attrs[this.attrName !== this.attrVal]; + return matching; + } +} + +// console.log((new TagPath("* b[b]")).stack); +// console.log((new TagPath("a[a] b[b] c")).stack); +// console.log((new TagPath(" b [ b= 'cf sdadwa' ] a ")).stack); \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/TagPathMatcher.js b/node_modules/fast-xml-parser/src/v5/TagPathMatcher.js new file mode 100644 index 0000000..af23607 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/TagPathMatcher.js @@ -0,0 +1,15 @@ +const TagPath = require("./TagPath"); + +class TagPathMatcher{ + constructor(stack,node){ + this.stack = stack; + this.node= node; + } + + match(path){ + const tagPath = new TagPath(path); + return tagPath.match(this.stack, this.node); + } +} + +module.exports = TagPathMatcher; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/XMLParser.js b/node_modules/fast-xml-parser/src/v5/XMLParser.js new file mode 100644 index 0000000..6de58ed --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/XMLParser.js @@ -0,0 +1,85 @@ +const { buildOptions} = require("./OptionsBuilder"); +const Xml2JsParser = require("./Xml2JsParser"); + +class XMLParser{ + + constructor(options){ + this.externalEntities = {}; + this.options = buildOptions(options); + // console.log(this.options) + } + /** + * Parse XML data string to JS object + * @param {string|Buffer} xmlData + * @param {boolean|Object} validationOption + */ + parse(xmlData){ + if(Array.isArray(xmlData) && xmlData.byteLength !== undefined){ + return this.parse(xmlData); + }else if( xmlData.toString){ + xmlData = xmlData.toString(); + }else{ + throw new Error("XML data is accepted in String or Bytes[] form.") + } + // if( validationOption){ + // if(validationOption === true) validationOption = {}; //validate with default options + + // const result = validator.validate(xmlData, validationOption); + // if (result !== true) { + // throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` ) + // } + // } + const parser = new Xml2JsParser(this.options); + parser.entityParser.addExternalEntities(this.externalEntities); + return parser.parse(xmlData); + } + /** + * Parse XML data buffer to JS object + * @param {string|Buffer} xmlData + * @param {boolean|Object} validationOption + */ + parseBytesArr(xmlData){ + if(Array.isArray(xmlData) && xmlData.byteLength !== undefined){ + }else{ + throw new Error("XML data is accepted in Bytes[] form.") + } + const parser = new Xml2JsParser(this.options); + parser.entityParser.addExternalEntities(this.externalEntities); + return parser.parseBytesArr(xmlData); + } + /** + * Parse XML data stream to JS object + * @param {fs.ReadableStream} xmlDataStream + */ + parseStream(xmlDataStream){ + if(!isStream(xmlDataStream)) throw new Error("FXP: Invalid stream input"); + + const orderedObjParser = new Xml2JsParser(this.options); + orderedObjParser.entityParser.addExternalEntities(this.externalEntities); + return orderedObjParser.parseStream(xmlDataStream); + } + + /** + * Add Entity which is not by default supported by this library + * @param {string} key + * @param {string} value + */ + addEntity(key, value){ + if(value.indexOf("&") !== -1){ + throw new Error("Entity value can't have '&'") + }else if(key.indexOf("&") !== -1 || key.indexOf(";") !== -1){ + throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '") + }else if(value === "&"){ + throw new Error("An entity with value '&' is not permitted"); + }else{ + this.externalEntities[key] = value; + } + } +} + +function isStream(stream){ + if(stream && typeof stream.read === "function" && typeof stream.on === "function" && typeof stream.readableEnded === "boolean") return true; + return false; +} + +module.exports = XMLParser; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/Xml2JsParser.js b/node_modules/fast-xml-parser/src/v5/Xml2JsParser.js new file mode 100644 index 0000000..c4baab4 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/Xml2JsParser.js @@ -0,0 +1,237 @@ +const StringSource = require("./inputSource/StringSource"); +const BufferSource = require("./inputSource/BufferSource"); +const {readTagExp,readClosingTagName} = require("./XmlPartReader"); +const {readComment, readCdata,readDocType,readPiTag} = require("./XmlSpecialTagsReader"); +const TagPath = require("./TagPath"); +const TagPathMatcher = require("./TagPathMatcher"); +const EntitiesParser = require('./EntitiesParser'); + +//To hold the data of current tag +//This is usually used to compare jpath expression against current tag +class TagDetail{ + constructor(name){ + this.name = name; + this.position = 0; + // this.attributes = {}; + } +} + +class Xml2JsParser { + constructor(options) { + this.options = options; + + this.currentTagDetail = null; + this.tagTextData = ""; + this.tagsStack = []; + this.entityParser = new EntitiesParser(options.htmlEntities); + this.stopNodes = []; + for (let i = 0; i < this.options.stopNodes.length; i++) { + this.stopNodes.push(new TagPath(this.options.stopNodes[i])); + } + } + + parse(strData) { + this.source = new StringSource(strData); + this.parseXml(); + return this.outputBuilder.getOutput(); + } + parseBytesArr(data) { + this.source = new BufferSource(data ); + this.parseXml(); + return this.outputBuilder.getOutput(); + } + + parseXml() { + //TODO: Separate TagValueParser as separate class. So no scope issue in node builder class + + //OutputBuilder should be set in XML Parser + this.outputBuilder = this.options.OutputBuilder.getInstance(this.options); + this.root = { root: true}; + this.currentTagDetail = this.root; + + while(this.source.canRead()){ + let ch = this.source.readCh(); + if (ch === "") break; + + if(ch === "<"){//tagStart + let nextChar = this.source.readChAt(0); + if (nextChar === "" ) throw new Error("Unexpected end of source"); + + + if(nextChar === "!" || nextChar === "?"){ + this.source.updateBufferBoundary(); + //previously collected text should be added to current node + this.addTextNode(); + + this.readSpecialTag(nextChar);// Read DOCTYPE, comment, CDATA, PI tag + }else if(nextChar === "/"){ + this.source.updateBufferBoundary(); + this.readClosingTag(); + // console.log(this.source.buffer.length, this.source.readable); + // console.log(this.tagsStack.length); + }else{//opening tag + this.readOpeningTag(); + } + }else{ + this.tagTextData += ch; + } + }//End While loop + if(this.tagsStack.length > 0 || ( this.tagTextData !== "undefined" && this.tagTextData.trimEnd().length > 0) ) throw new Error("Unexpected data in the end of document"); + } + + /** + * read closing paired tag. Set parent tag in scope. + * skip a node on user's choice + */ + readClosingTag(){ + const tagName = this.processTagName(readClosingTagName(this.source)); + // console.log(tagName, this.tagsStack.length); + this.validateClosingTag(tagName); + // All the text data collected, belongs to current tag. + if(!this.currentTagDetail.root) this.addTextNode(); + this.outputBuilder.closeTag(); + // Since the tag is closed now, parent tag comes in scope + this.currentTagDetail = this.tagsStack.pop(); + } + + validateClosingTag(tagName){ + // This can't be unpaired tag, or a stop tag. + if(this.isUnpaired(tagName) || this.isStopNode(tagName)) throw new Error(`Unexpected closing tag '${tagName}'`); + // This must match with last opening tag + else if(tagName !== this.currentTagDetail.name) + throw new Error(`Unexpected closing tag '${tagName}' expecting '${this.currentTagDetail.name}'`) + } + + /** + * Read paired, unpaired, self-closing, stop and special tags. + * Create a new node + * Push paired tag in stack. + */ + readOpeningTag(){ + //save previously collected text data to current node + this.addTextNode(); + + //create new tag + let tagExp = readTagExp(this, ">" ); + + // process and skip from tagsStack For unpaired tag, self closing tag, and stop node + const tagDetail = new TagDetail(tagExp.tagName); + if(this.isUnpaired(tagExp.tagName)) { + //TODO: this will lead 2 extra stack operation + this.outputBuilder.addTag(tagDetail); + this.outputBuilder.closeTag(); + } else if(tagExp.selfClosing){ + this.outputBuilder.addTag(tagDetail); + this.outputBuilder.closeTag(); + } else if(this.isStopNode(this.currentTagDetail)){ + // TODO: let's user set a stop node boundary detector for complex contents like script tag + //TODO: pass tag name only to avoid string operations + const content = source.readUptoCloseTag(` 0){ + //TODO: shift parsing to output builder + + this.outputBuilder.addValue(this.replaceEntities(this.tagTextData)); + } + this.tagTextData = ""; + } + // } + } + + processAttrName(name){ + if(name === "__proto__") name = "#__proto__"; + name = resolveNameSpace(name, this.removeNSPrefix); + return name; + } + + processTagName(name){ + if(name === "__proto__") name = "#__proto__"; + name = resolveNameSpace(name, this.removeNSPrefix); + return name; + } + + /** + * Generate tags path from tagsStack + */ + tagsPath(tagName){ + //TODO: return TagPath Object. User can call match method with path + return ""; + } + + isUnpaired(tagName){ + return this.options.tags.unpaired.indexOf(tagName) !== -1; + } + + /** + * valid expressions are + * tag nested + * * nested + * tag nested[attribute] + * tag nested[attribute=""] + * tag nested[attribute!=""] + * tag nested:0 //for future + * @param {string} tagName + * @returns + */ + isStopNode(node){ + for (let i = 0; i < this.stopNodes.length; i++) { + const givenPath = this.stopNodes[i]; + if(givenPath.match(this.tagsStack, node)) return true; + } + return false + } + + replaceEntities(text){ + //TODO: if option is set then replace entities + return this.entityParser.parse(text) + } +} + +function resolveNameSpace(name, removeNSPrefix) { + if (removeNSPrefix) { + const parts = name.split(':'); + if(parts.length === 2){ + if (parts[0] === 'xmlns') return ''; + else return parts[1]; + }else reportError(`Multiple namespaces ${name}`) + } + return name; +} + +module.exports = Xml2JsParser; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/XmlPartReader.js b/node_modules/fast-xml-parser/src/v5/XmlPartReader.js new file mode 100644 index 0000000..b77fb68 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/XmlPartReader.js @@ -0,0 +1,216 @@ +'use strict'; + +/** + * find paired tag for a stop node + * @param {string} xmlDoc + * @param {string} tagName + * @param {number} i : start index + */ +function readStopNode(xmlDoc, tagName, i){ + const startIndex = i; + // Starting at 1 since we already have an open tag + let openTagCount = 1; + + for (; i < xmlDoc.length; i++) { + if( xmlDoc[i] === "<"){ + if (xmlDoc[i+1] === "/") {//close tag + const closeIndex = findSubStrIndex(xmlDoc, ">", i, `${tagName} is not closed`); + let closeTagName = xmlDoc.substring(i+2,closeIndex).trim(); + if(closeTagName === tagName){ + openTagCount--; + if (openTagCount === 0) { + return { + tagContent: xmlDoc.substring(startIndex, i), + i : closeIndex + } + } + } + i=closeIndex; + } else if(xmlDoc[i+1] === '?') { + const closeIndex = findSubStrIndex(xmlDoc, "?>", i+1, "StopNode is not closed.") + i=closeIndex; + } else if(xmlDoc.substr(i + 1, 3) === '!--') { + const closeIndex = findSubStrIndex(xmlDoc, "-->", i+3, "StopNode is not closed.") + i=closeIndex; + } else if(xmlDoc.substr(i + 1, 2) === '![') { + const closeIndex = findSubStrIndex(xmlDoc, "]]>", i, "StopNode is not closed.") - 2; + i=closeIndex; + } else { + const tagData = readTagExp(xmlDoc, i, '>') + + if (tagData) { + const openTagName = tagData && tagData.tagName; + if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== "/") { + openTagCount++; + } + i=tagData.closeIndex; + } + } + } + }//end for loop +} + +/** + * Read closing tag name + * @param {Source} source + * @returns tag name + */ +function readClosingTagName(source){ + let text = ""; //temporary data + while(source.canRead()){ + let ch = source.readCh(); + // if (ch === null || ch === undefined) break; + // source.updateBuffer(); + + if (ch === ">") return text.trimEnd(); + else text += ch; + } + throw new Error(`Unexpected end of source. Reading '${substr}'`); +} + +/** + * Read XML tag and build attributes map + * This function can be used to read normal tag, pi tag. + * This function can't be used to read comment, CDATA, DOCTYPE. + * Eg + * @param {string} xmlDoc + * @param {number} startIndex starting index + * @returns tag expression includes tag name & attribute string + */ +function readTagExp(parser) { + let inSingleQuotes = false; + let inDoubleQuotes = false; + let i; + let EOE = false; + + for (i = 0; parser.source.canRead(i); i++) { + const char = parser.source.readChAt(i); + + if (char === "'" && !inDoubleQuotes) { + inSingleQuotes = !inSingleQuotes; + } else if (char === '"' && !inSingleQuotes) { + inDoubleQuotes = !inDoubleQuotes; + } else if (char === '>' && !inSingleQuotes && !inDoubleQuotes) { + // If not inside quotes, stop reading at '>' + EOE = true; + break; + } + + } + if(inSingleQuotes || inDoubleQuotes){ + throw new Error("Invalid attribute expression. Quote is not properly closed"); + }else if(!EOE) throw new Error("Unexpected closing of source. Waiting for '>'"); + + + const exp = parser.source.readStr(i); + parser.source.updateBufferBoundary(i + 1); + return buildTagExpObj(exp, parser) +} + +function readPiExp(parser) { + let inSingleQuotes = false; + let inDoubleQuotes = false; + let i; + let EOE = false; + + for (i = 0; parser.source.canRead(i) ; i++) { + const currentChar = parser.source.readChAt(i); + const nextChar = parser.source.readChAt(i+1); + + if (currentChar === "'" && !inDoubleQuotes) { + inSingleQuotes = !inSingleQuotes; + } else if (currentChar === '"' && !inSingleQuotes) { + inDoubleQuotes = !inDoubleQuotes; + } + + if (!inSingleQuotes && !inDoubleQuotes) { + if (currentChar === '?' && nextChar === '>') { + EOE = true; + break; // Exit the loop when '?>' is found + } + } + } + if(inSingleQuotes || inDoubleQuotes){ + throw new Error("Invalid attribute expression. Quote is not properly closed in PI tag expression"); + }else if(!EOE) throw new Error("Unexpected closing of source. Waiting for '?>'"); + + if(!parser.options.attributes.ignore){ + //TODO: use regex to verify attributes if not set to ignore + } + + const exp = parser.source.readStr(i); + parser.source.updateBufferBoundary(i + 1); + return buildTagExpObj(exp, parser) +} + +function buildTagExpObj(exp, parser){ + const tagExp = { + tagName: "", + selfClosing: false + }; + let attrsExp = ""; + + // Check for self-closing tag before setting the name + if(exp[exp.length -1] === "/") { + tagExp.selfClosing = true; + exp = exp.slice(0, -1); // Remove the trailing slash + } + + //separate tag name + let i = 0; + for (; i < exp.length; i++) { + const char = exp[i]; + if(char === " "){ + tagExp.tagName = exp.substring(0, i); + attrsExp = exp.substring(i + 1); + break; + } + } + //only tag + if(tagExp.tagName.length === 0 && i === exp.length)tagExp.tagName = exp; + + tagExp.tagName = tagExp.tagName.trimEnd(); + + if(!parser.options.attributes.ignore && attrsExp.length > 0){ + parseAttributesExp(attrsExp,parser) + } + + return tagExp; +} + +const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm'); + +function parseAttributesExp(attrStr, parser) { + const matches = getAllMatches(attrStr, attrsRegx); + const len = matches.length; //don't make it inline + for (let i = 0; i < len; i++) { + let attrName = parser.processAttrName(matches[i][1]); + let attrVal = parser.replaceEntities(matches[i][4] || true); + + parser.outputBuilder.addAttribute(attrName, attrVal); + } +} + + +const getAllMatches = function(string, regex) { + const matches = []; + let match = regex.exec(string); + while (match) { + const allmatches = []; + allmatches.startIndex = regex.lastIndex - match[0].length; + const len = match.length; + for (let index = 0; index < len; index++) { + allmatches.push(match[index]); + } + matches.push(allmatches); + match = regex.exec(string); + } + return matches; +}; + +module.exports = { + readStopNode: readStopNode, + readClosingTagName: readClosingTagName, + readTagExp: readTagExp, + readPiExp: readPiExp, +} diff --git a/node_modules/fast-xml-parser/src/v5/XmlSpecialTagsReader.js b/node_modules/fast-xml-parser/src/v5/XmlSpecialTagsReader.js new file mode 100644 index 0000000..0fba196 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/XmlSpecialTagsReader.js @@ -0,0 +1,118 @@ +const {readPiExp} = require("./XmlPartReader"); + +function readCdata(parser){ + //"); + parser.outputBuilder.addCdata(text); +} +function readPiTag(parser){ + //"); + if(!tagExp) throw new Error("Invalid Pi Tag expression."); + + if (tagExp.tagName === "?xml") {//TODO: test if tagName is just xml + parser.outputBuilder.addDeclaration(); + } else { + parser.outputBuilder.addPi("?"+tagExp.tagName); + } +} + +function readComment(parser){ + //"); + parser.outputBuilder.addComment(text); +} + +const DOCTYPE_tags = { + "EL":/^EMENT\s+([^\s>]+)\s+(ANY|EMPTY|\(.+\)\s*$)/m, + "AT":/^TLIST\s+[^\s]+\s+[^\s]+\s+[^\s]+\s+[^\s]+\s+$/m, + "NO":/^TATION.+$/m +} +function readDocType(parser){ + //"); + const regx = DOCTYPE_tags[str]; + if(regx){ + const match = dTagExp.match(regx); + if(!match) throw new Error("Invalid DOCTYPE"); + }else throw new Error("Invalid DOCTYPE"); + } + }else if( ch === '>' && lastch === "]"){//end of doctype + return; + } + }else if( ch === '>'){//end of doctype + return; + }else if( ch === '['){ + hasBody = true; + }else{ + lastch = ch; + } + }//End While loop + +} + +function registerEntity(parser){ + //read Entity + let attrBoundary=""; + let name ="", val =""; + while(source.canRead()){ + let ch = source.readCh(); + + if(attrBoundary){ + if (ch === attrBoundary){ + val = text; + text = "" + } + }else if(ch === " " || ch === "\t"){ + if(!name){ + name = text.trimStart(); + text = ""; + } + }else if (ch === '"' || ch === "'") {//start of attrBoundary + attrBoundary = ch; + }else if(ch === ">"){ + parser.entityParser.addExternalEntity(name,val); + return; + }else{ + text+=ch; + } + } +} + +module.exports = { + readCdata: readCdata, + readComment:readComment, + readDocType:readDocType, + readPiTag:readPiTag +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/inputSource/BufferSource.js b/node_modules/fast-xml-parser/src/v5/inputSource/BufferSource.js new file mode 100644 index 0000000..b83ce46 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/inputSource/BufferSource.js @@ -0,0 +1,118 @@ +const Constants = { + space: 32, + tab: 9 +} +class BufferSource{ + constructor(bytesArr){ + this.line = 1; + this.cols = 0; + this.buffer = bytesArr; + this.startIndex = 0; + } + + + + readCh() { + return String.fromCharCode(this.buffer[this.startIndex++]); + } + + readChAt(index) { + return String.fromCharCode(this.buffer[this.startIndex+index]); + } + + readStr(n,from){ + if(typeof from === "undefined") from = this.startIndex; + return this.buffer.slice(from, from + n).toString(); + } + + readUpto(stopStr) { + const inputLength = this.buffer.length; + const stopLength = stopStr.length; + const stopBuffer = Buffer.from(stopStr); + + for (let i = this.startIndex; i < inputLength; i++) { + let match = true; + for (let j = 0; j < stopLength; j++) { + if (this.buffer[i + j] !== stopBuffer[j]) { + match = false; + break; + } + } + + if (match) { + const result = this.buffer.slice(this.startIndex, i).toString(); + this.startIndex = i + stopLength; + return result; + } + } + + throw new Error(`Unexpected end of source. Reading '${stopStr}'`); +} + +readUptoCloseTag(stopStr) { //stopStr: "'){ //TODO: if it should be equivalent ASCII + match = 2; + //tag boundary found + // this.startIndex + } + }else{ + match = 1; + for (let j = 0; j < stopLength; j++) { + if (this.buffer[i + j] !== stopBuffer[j]) { + match = 0; + break; + } + } + } + if (match === 2) {//matched closing part + const result = this.buffer.slice(this.startIndex, stopIndex - 1 ).toString(); + this.startIndex = i + 1; + return result; + } + } + + throw new Error(`Unexpected end of source. Reading '${stopStr}'`); +} + + readFromBuffer(n, shouldUpdate) { + let ch; + if (n === 1) { + ch = this.buffer[this.startIndex]; + if (ch === 10) { + this.line++; + this.cols = 1; + } else { + this.cols++; + } + ch = String.fromCharCode(ch); + } else { + this.cols += n; + ch = this.buffer.slice(this.startIndex, this.startIndex + n).toString(); + } + if (shouldUpdate) this.updateBuffer(n); + return ch; + } + + updateBufferBoundary(n = 1) { //n: number of characters read + this.startIndex += n; + } + + canRead(n){ + n = n || this.startIndex; + return this.buffer.length - n + 1 > 0; + } + +} + +module.exports = BufferSource; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/inputSource/StringSource.js b/node_modules/fast-xml-parser/src/v5/inputSource/StringSource.js new file mode 100644 index 0000000..a996528 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/inputSource/StringSource.js @@ -0,0 +1,123 @@ +const whiteSpaces = [" ", "\n", "\t"]; + + +class StringSource{ + constructor(str){ + this.line = 1; + this.cols = 0; + this.buffer = str; + //a boundary pointer to indicate where from the buffer dat should be read + // data before this pointer can be deleted to free the memory + this.startIndex = 0; + } + + readCh() { + return this.buffer[this.startIndex++]; + } + + readChAt(index) { + return this.buffer[this.startIndex+index]; + } + + readStr(n,from){ + if(typeof from === "undefined") from = this.startIndex; + return this.buffer.substring(from, from + n); + } + + readUpto(stopStr) { + const inputLength = this.buffer.length; + const stopLength = stopStr.length; + + for (let i = this.startIndex; i < inputLength; i++) { + let match = true; + for (let j = 0; j < stopLength; j++) { + if (this.buffer[i + j] !== stopStr[j]) { + match = false; + break; + } + } + + if (match) { + const result = this.buffer.substring(this.startIndex, i); + this.startIndex = i + stopLength; + return result; + } + } + + throw new Error(`Unexpected end of source. Reading '${stopStr}'`); + } + + readUptoCloseTag(stopStr) { //stopStr: "'){ + match = 2; + //tag boundary found + // this.startIndex + } + }else{ + match = 1; + for (let j = 0; j < stopLength; j++) { + if (this.buffer[i + j] !== stopStr[j]) { + match = 0; + break; + } + } + } + if (match === 2) {//matched closing part + const result = this.buffer.substring(this.startIndex, stopIndex - 1 ); + this.startIndex = i + 1; + return result; + } + } + + throw new Error(`Unexpected end of source. Reading '${stopStr}'`); + } + + readFromBuffer(n, updateIndex){ + let ch; + if(n===1){ + ch = this.buffer[this.startIndex]; + // if(ch === "\n") { + // this.line++; + // this.cols = 1; + // }else{ + // this.cols++; + // } + }else{ + ch = this.buffer.substring(this.startIndex, this.startIndex + n); + // if("".indexOf("\n") !== -1){ + // //TODO: handle the scenario when there are multiple lines + // //TODO: col should be set to number of chars after last '\n' + // // this.cols = 1; + // }else{ + // this.cols += n; + + // } + } + if(updateIndex) this.updateBufferBoundary(n); + return ch; + } + + //TODO: rename to updateBufferReadIndex + + updateBufferBoundary(n = 1) { //n: number of characters read + this.startIndex += n; + } + + canRead(n){ + n = n || this.startIndex; + return this.buffer.length - n + 1 > 0; + } + +} + +module.exports = StringSource; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/valueParsers/EntitiesParser.js b/node_modules/fast-xml-parser/src/v5/valueParsers/EntitiesParser.js new file mode 100644 index 0000000..62cc02f --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/valueParsers/EntitiesParser.js @@ -0,0 +1,107 @@ +const ampEntity = { regex: /&(amp|#38|#x26);/g, val : "&"}; +const htmlEntities = { + "space": { regex: /&(nbsp|#160);/g, val: " " }, + // "lt" : { regex: /&(lt|#60);/g, val: "<" }, + // "gt" : { regex: /&(gt|#62);/g, val: ">" }, + // "amp" : { regex: /&(amp|#38);/g, val: "&" }, + // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, + // "apos" : { regex: /&(apos|#39);/g, val: "'" }, + "cent" : { regex: /&(cent|#162);/g, val: "¢" }, + "pound" : { regex: /&(pound|#163);/g, val: "£" }, + "yen" : { regex: /&(yen|#165);/g, val: "¥" }, + "euro" : { regex: /&(euro|#8364);/g, val: "€" }, + "copyright" : { regex: /&(copy|#169);/g, val: "©" }, + "reg" : { regex: /&(reg|#174);/g, val: "®" }, + "inr" : { regex: /&(inr|#8377);/g, val: "₹" }, + "num_dec": { regex: /&#([0-9]{1,7});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 10)) }, + "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 16)) }, +}; + +class EntitiesParser{ + constructor(replaceHtmlEntities) { + this.replaceHtmlEntities = replaceHtmlEntities; + this.docTypeEntities = {}; + this.lastEntities = { + "apos" : { regex: /&(apos|#39|#x27);/g, val : "'"}, + "gt" : { regex: /&(gt|#62|#x3E);/g, val : ">"}, + "lt" : { regex: /&(lt|#60|#x3C);/g, val : "<"}, + "quot" : { regex: /&(quot|#34|#x22);/g, val : "\""}, + }; + } + + addExternalEntities(externalEntities){ + const entKeys = Object.keys(externalEntities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + this.addExternalEntity(ent,externalEntities[ent]) + } + } + addExternalEntity(key,val){ + validateEntityName(key); + if(val.indexOf("&") !== -1) { + reportWarning(`Entity ${key} is not added as '&' is found in value;`) + return; + }else{ + this.lastEntities[ent] = { + regex: new RegExp("&"+key+";","g"), + val : val + } + } + } + + addDocTypeEntities(entities){ + const entKeys = Object.keys(entities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + this.docTypeEntities[ent] = { + regex: new RegExp("&"+ent+";","g"), + val : entities[ent] + } + } + } + + parse(val){ + return this.replaceEntitiesValue(val) + } + + /** + * 1. Replace DOCTYPE entities + * 2. Replace external entities + * 3. Replace HTML entities if asked + * @param {string} val + */ + replaceEntitiesValue(val){ + if(typeof val === "string" && val.length > 0){ + for(let entityName in this.docTypeEntities){ + const entity = this.docTypeEntities[entityName]; + val = val.replace( entity.regx, entity.val); + } + for(let entityName in this.lastEntities){ + const entity = this.lastEntities[entityName]; + val = val.replace( entity.regex, entity.val); + } + if(this.replaceHtmlEntities){ + for(let entityName in htmlEntities){ + const entity = htmlEntities[entityName]; + val = val.replace( entity.regex, entity.val); + } + } + val = val.replace( ampEntity.regex, ampEntity.val); + } + return val; + } +}; + +//an entity name should not contains special characters that may be used in regex +//Eg !?\\\/[]$%{}^&*()<> +const specialChar = "!?\\\/[]$%{}^&*()<>|+"; + +function validateEntityName(name){ + for (let i = 0; i < specialChar.length; i++) { + const ch = specialChar[i]; + if(name.indexOf(ch) !== -1) throw new Error(`Invalid character ${ch} in entity name`); + } + return name; +} + +module.exports = EntitiesParser; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/valueParsers/booleanParser.js b/node_modules/fast-xml-parser/src/v5/valueParsers/booleanParser.js new file mode 100644 index 0000000..f8f5d12 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/valueParsers/booleanParser.js @@ -0,0 +1,23 @@ +class boolParser{ + constructor(trueList, falseList){ + if(trueList) + this.trueList = trueList; + else + this.trueList = ["true"]; + + if(falseList) + this.falseList = falseList; + else + this.falseList = ["false"]; + } + parse(val){ + if (typeof val === 'string') { + //TODO: performance: don't convert + const temp = val.toLowerCase(); + if(this.trueList.indexOf(temp) !== -1) return true; + else if(this.falseList.indexOf(temp) !== -1 ) return false; + } + return val; + } +} +module.exports = boolParser; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/valueParsers/booleanParserExt.js b/node_modules/fast-xml-parser/src/v5/valueParsers/booleanParserExt.js new file mode 100644 index 0000000..21b8050 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/valueParsers/booleanParserExt.js @@ -0,0 +1,20 @@ +function boolParserExt(val){ + if(isArray(val)){ + for (let i = 0; i < val.length; i++) { + val[i] = parse(val[i]) + } + }else{ + val = parse(val) + } + return val; +} + +function parse(val){ + if (typeof val === 'string') { + const temp = val.toLowerCase(); + if(temp === 'true' || temp ==="yes" || temp==="1") return true; + else if(temp === 'false' || temp ==="no" || temp==="0") return false; + } + return val; +} +module.exports = boolParserExt; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/valueParsers/currency.js b/node_modules/fast-xml-parser/src/v5/valueParsers/currency.js new file mode 100644 index 0000000..82e21e7 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/valueParsers/currency.js @@ -0,0 +1,40 @@ +const defaultOptions = { + maxLength: 200, + // locale: "en-IN" +} +const localeMap = { + "$":"en-US", + "€":"de-DE", + "£":"en-GB", + "¥":"ja-JP", + "₹":"en-IN", +} +const sign = "(?:-|\+)?"; +const digitsAndSeparator = "(?:\d+|\d{1,3}(?:,\d{3})+)"; +const decimalPart = "(?:\.\d{1,2})?"; +const symbol = "(?:\$|€|¥|₹)?"; + +const currencyCheckRegex = /^\s*(?:-|\+)?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d{1,2})?\s*(?:\$|€|¥|₹)?\s*$/u; + +class CurrencyParser{ + constructor(options){ + this.options = options || defaultOptions; + } + parse(val){ + if (typeof val === 'string' && val.length <= this.options.maxLength) { + if(val.indexOf(",,") !== -1 && val.indexOf(".." !== -1)){ + const match = val.match(currencyCheckRegex); + if(match){ + const locale = this.options.locale || localeMap[match[2]||match[5]||"₹"]; + const formatter = new Intl.NumberFormat(locale) + val = val.replace(/[^0-9,.]/g, '').trim(); + val = Number(val.replace(formatter.format(1000)[1], '')); + } + } + } + return val; + } +} +CurrencyParser.defaultOptions = defaultOptions; + +module.exports = CurrencyParser; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/valueParsers/join.js b/node_modules/fast-xml-parser/src/v5/valueParsers/join.js new file mode 100644 index 0000000..d7f2027 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/valueParsers/join.js @@ -0,0 +1,14 @@ +/** + * + * @param {array} val + * @param {string} by + * @returns + */ +function join(val, by=" "){ + if(isArray(val)){ + val.join(by) + } + return val; +} + +module.exports = join; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/valueParsers/number.js b/node_modules/fast-xml-parser/src/v5/valueParsers/number.js new file mode 100644 index 0000000..bef3803 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/valueParsers/number.js @@ -0,0 +1,16 @@ +const toNumber = require("strnum"); + + +class numParser{ + constructor(options){ + this.options = options; + } + parse(val){ + if (typeof val === 'string') { + val = toNumber(val,this.options); + } + return val; + } +} + +module.exports = numParser; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v5/valueParsers/trim.js b/node_modules/fast-xml-parser/src/v5/valueParsers/trim.js new file mode 100644 index 0000000..ecce49a --- /dev/null +++ b/node_modules/fast-xml-parser/src/v5/valueParsers/trim.js @@ -0,0 +1,8 @@ +class trimmer{ + parse(val){ + if(typeof val === "string") return val.trim(); + else return val; + } +} + +module.exports = trimmer; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v6/CharsSymbol.js b/node_modules/fast-xml-parser/src/v6/CharsSymbol.js new file mode 100644 index 0000000..6ac2de4 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/CharsSymbol.js @@ -0,0 +1,16 @@ +export default { + "<" : "<", //tag start + ">" : ">", //tag end + "/" : "/", //close tag + "!" : "!", //comment or docttype + "!--" : "!--", //comment + "-->" : "-->", //comment end + "?" : "?", //pi + "?>" : "?>", //pi end + "?xml" : "?xml", //pi end + "![" : "![", //cdata + "]]>" : "]]>", //cdata end + "[" : "[", + "-" : "-", + "D" : "D", +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v6/EntitiesParser.js b/node_modules/fast-xml-parser/src/v6/EntitiesParser.js new file mode 100644 index 0000000..0639dd1 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/EntitiesParser.js @@ -0,0 +1,104 @@ +const ampEntity = { regex: /&(amp|#38|#x26);/g, val : "&"}; +const htmlEntities = { + "space": { regex: /&(nbsp|#160);/g, val: " " }, + // "lt" : { regex: /&(lt|#60);/g, val: "<" }, + // "gt" : { regex: /&(gt|#62);/g, val: ">" }, + // "amp" : { regex: /&(amp|#38);/g, val: "&" }, + // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, + // "apos" : { regex: /&(apos|#39);/g, val: "'" }, + "cent" : { regex: /&(cent|#162);/g, val: "¢" }, + "pound" : { regex: /&(pound|#163);/g, val: "£" }, + "yen" : { regex: /&(yen|#165);/g, val: "¥" }, + "euro" : { regex: /&(euro|#8364);/g, val: "€" }, + "copyright" : { regex: /&(copy|#169);/g, val: "©" }, + "reg" : { regex: /&(reg|#174);/g, val: "®" }, + "inr" : { regex: /&(inr|#8377);/g, val: "₹" }, + "num_dec": { regex: /&#([0-9]{1,7});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 10)) }, + "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 16)) }, +}; +export default class EntitiesParser{ + constructor(replaceHtmlEntities) { + this.replaceHtmlEntities = replaceHtmlEntities; + this.docTypeEntities = {}; + this.lastEntities = { + "apos" : { regex: /&(apos|#39|#x27);/g, val : "'"}, + "gt" : { regex: /&(gt|#62|#x3E);/g, val : ">"}, + "lt" : { regex: /&(lt|#60|#x3C);/g, val : "<"}, + "quot" : { regex: /&(quot|#34|#x22);/g, val : "\""}, + }; + } + + addExternalEntities(externalEntities){ + const entKeys = Object.keys(externalEntities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + this.addExternalEntity(ent,externalEntities[ent]) + } + } + addExternalEntity(key,val){ + validateEntityName(key); + if(val.indexOf("&") !== -1) { + reportWarning(`Entity ${key} is not added as '&' is found in value;`) + return; + }else{ + this.lastEntities[ent] = { + regex: new RegExp("&"+key+";","g"), + val : val + } + } + } + + addDocTypeEntities(entities){ + const entKeys = Object.keys(entities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + this.docTypeEntities[ent] = { + regex: new RegExp("&"+ent+";","g"), + val : entities[ent] + } + } + } + + parse(val){ + return this.replaceEntitiesValue(val) + } + + /** + * 1. Replace DOCTYPE entities + * 2. Replace external entities + * 3. Replace HTML entities if asked + * @param {string} val + */ + replaceEntitiesValue(val){ + if(typeof val === "string" && val.length > 0){ + for(let entityName in this.docTypeEntities){ + const entity = this.docTypeEntities[entityName]; + val = val.replace( entity.regx, entity.val); + } + for(let entityName in this.lastEntities){ + const entity = this.lastEntities[entityName]; + val = val.replace( entity.regex, entity.val); + } + if(this.replaceHtmlEntities){ + for(let entityName in htmlEntities){ + const entity = htmlEntities[entityName]; + val = val.replace( entity.regex, entity.val); + } + } + val = val.replace( ampEntity.regex, ampEntity.val); + } + return val; + } +}; + +//an entity name should not contains special characters that may be used in regex +//Eg !?\\\/[]$%{}^&*()<> +const specialChar = "!?\\\/[]$%{}^&*()<>|+"; + +function validateEntityName(name){ + for (let i = 0; i < specialChar.length; i++) { + const ch = specialChar[i]; + if(name.indexOf(ch) !== -1) throw new Error(`Invalid character ${ch} in entity name`); + } + return name; +} diff --git a/node_modules/fast-xml-parser/src/v6/OptionsBuilder.js b/node_modules/fast-xml-parser/src/v6/OptionsBuilder.js new file mode 100644 index 0000000..b245166 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/OptionsBuilder.js @@ -0,0 +1,61 @@ + +import {JsObjOutputBuilder} from './OutputBuilders/JsObjBuilder.js'; + +export const defaultOptions = { + preserveOrder: false, + removeNSPrefix: false, // remove NS from tag name or attribute name if true + //ignoreRootElement : false, + stopNodes: [], //nested tags will not be parsed even for errors + // isArray: () => false, //User will set it + htmlEntities: false, + // skipEmptyListItem: false + tags:{ + unpaired: [], + nameFor:{ + cdata: false, + comment: false, + text: '#text' + }, + separateTextProperty: false, + }, + attributes:{ + ignore: false, + booleanType: true, + entities: true, + }, + + // select: ["img[src]"], + // stop: ["anim", "[ads]"] + only: [], // rest tags will be skipped. It will result in flat array + hierarchy: false, //will be used when a particular tag is set to be parsed. + skip: [], // will be skipped from parse result. on('skip') will be triggered + + select: [], // on('select', tag => tag ) will be called if match + stop: [], //given tagPath will not be parsed. innerXML will be set as string value + OutputBuilder: new JsObjOutputBuilder(), +}; + +export const buildOptions = function(options) { + const finalOptions = { ... defaultOptions}; + copyProperties(finalOptions,options) + return finalOptions; +}; + +function copyProperties(target, source) { + for (let key in source) { + if (source.hasOwnProperty(key)) { + if (key === 'OutputBuilder') { + target[key] = source[key]; + }else if (typeof source[key] === 'object' && !Array.isArray(source[key])) { + // Recursively copy nested properties + if (typeof target[key] === 'undefined') { + target[key] = {}; + } + copyProperties(target[key], source[key]); + } else { + // Copy non-nested properties + target[key] = source[key]; + } + } + } +} diff --git a/node_modules/fast-xml-parser/src/v6/OutputBuilders/BaseOutputBuilder.js b/node_modules/fast-xml-parser/src/v6/OutputBuilders/BaseOutputBuilder.js new file mode 100644 index 0000000..8f9ce8d --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/OutputBuilders/BaseOutputBuilder.js @@ -0,0 +1,69 @@ +export default class BaseOutputBuilder{ + constructor(){ + // this.attributes = {}; + } + + addAttribute(name, value){ + if(this.options.onAttribute){ + //TODO: better to pass tag path + const v = this.options.onAttribute(name, value, this.tagName); + if(v) this.attributes[v.name] = v.value; + }else{ + name = this.options.attributes.prefix + name + this.options.attributes.suffix; + this.attributes[name] = this.parseValue(value, this.options.attributes.valueParsers); + } + } + + /** + * parse value by chain of parsers + * @param {string} val + * @returns {any} parsed value if matching parser found + */ + parseValue = function(val, valParsers){ + for (let i = 0; i < valParsers.length; i++) { + let valParser = valParsers[i]; + if(typeof valParser === "string"){ + valParser = this.registeredParsers[valParser]; + } + if(valParser){ + val = valParser.parse(val); + } + } + return val; + } + + /** + * To add a nested empty tag. + * @param {string} key + * @param {any} val + */ + _addChild(key, val){} + + /** + * skip the comment if property is not set + */ + addComment(text){ + if(this.options.nameFor.comment) + this._addChild(this.options.nameFor.comment, text); + } + + //store CDATA separately if property is set + //otherwise add to tag's value + addCdata(text){ + if (this.options.nameFor.cdata) { + this._addChild(this.options.nameFor.cdata, text); + } else { + this.addRawValue(text || ""); + } + } + + addRawValue = text => this.addValue(text); + + addDeclaration(){ + if(!this.options.declaration){ + }else{ + this.addPi("?xml"); + } + this.attributes = {} + } +} diff --git a/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsArrBuilder.js b/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsArrBuilder.js new file mode 100644 index 0000000..b9c6e65 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsArrBuilder.js @@ -0,0 +1,103 @@ +import {buildOptions,registerCommonValueParsers} from './ParserOptionsBuilder.js'; + +export default class OutputBuilder{ + constructor(options){ + this.options = buildOptions(options); + this.registeredParsers = registerCommonValueParsers(this.options); + } + + registerValueParser(name,parserInstance){//existing name will override the parser without warning + this.registeredParsers[name] = parserInstance; + } + + getInstance(parserOptions){ + return new JsArrBuilder(parserOptions, this.options, this.registeredParsers); + } +} + +const rootName = '!js_arr'; +import BaseOutputBuilder from './BaseOutputBuilder.js'; + +class JsArrBuilder extends BaseOutputBuilder{ + + constructor(parserOptions, options,registeredParsers) { + super(); + this.tagsStack = []; + this.parserOptions = parserOptions; + this.options = options; + this.registeredParsers = registeredParsers; + + this.root = new Node(rootName); + this.currentNode = this.root; + this.attributes = {}; + } + + addTag(tag){ + //when a new tag is added, it should be added as child of current node + //TODO: shift this check to the parser + if(tag.name === "__proto__") tag.name = "#__proto__"; + + this.tagsStack.push(this.currentNode); + this.currentNode = new Node(tag.name, this.attributes); + this.attributes = {}; + } + + /** + * Check if the node should be added by checking user's preference + * @param {Node} node + * @returns boolean: true if the node should not be added + */ + closeTag(){ + const node = this.currentNode; + this.currentNode = this.tagsStack.pop(); //set parent node in scope + if(this.options.onClose !== undefined){ + //TODO TagPathMatcher + const resultTag = this.options.onClose(node, + new TagPathMatcher(this.tagsStack,node)); + + if(resultTag) return; + } + this.currentNode.child.push(node); //to parent node + } + + //Called by parent class methods + _addChild(key, val){ + // if(key === "__proto__") tagName = "#__proto__"; + this.currentNode.child.push( {[key]: val }); + // this.currentNode.leafType = false; + } + + /** + * Add text value child node + * @param {string} text + */ + addValue(text){ + this.currentNode.child.push( {[this.options.nameFor.text]: this.parseValue(text, this.options.tags.valueParsers) }); + } + + addPi(name){ + //TODO: set pi flag + if(!this.options.ignorePiTags){ + const node = new Node(name, this.attributes); + this.currentNode[":@"] = this.attributes; + this.currentNode.child.push(node); + } + this.attributes = {}; + } + getOutput(){ + return this.root.child[0]; + } +} + + + +class Node{ + constructor(tagname, attributes){ + this.tagname = tagname; + this.child = []; //nested tags, text, cdata, comments + if(attributes && Object.keys(attributes).length > 0) + this[":@"] = attributes; + } +} + +module.exports = OutputBuilder; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsMinArrBuilder.js b/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsMinArrBuilder.js new file mode 100644 index 0000000..be96ebf --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsMinArrBuilder.js @@ -0,0 +1,100 @@ +import {buildOptions,registerCommonValueParsers} from"./ParserOptionsBuilder"; + +export default class OutputBuilder{ + constructor(options){ + this.options = buildOptions(options); + this.registeredParsers = registerCommonValueParsers(this.options); + } + + registerValueParser(name,parserInstance){//existing name will override the parser without warning + this.registeredParsers[name] = parserInstance; + } + + getInstance(parserOptions){ + return new JsMinArrBuilder(parserOptions, this.options, this.registeredParsers); + } +} + +import BaseOutputBuilder from "./BaseOutputBuilder.js"; +const rootName = '^'; + +class JsMinArrBuilder extends BaseOutputBuilder{ + + constructor(parserOptions, options,registeredParsers) { + super(); + this.tagsStack = []; + this.parserOptions = parserOptions; + this.options = options; + this.registeredParsers = registeredParsers; + + this.root = {[rootName]: []}; + this.currentNode = this.root; + this.currentNodeTagName = rootName; + this.attributes = {}; + } + + addTag(tag){ + //when a new tag is added, it should be added as child of current node + //TODO: shift this check to the parser + if(tag.name === "__proto__") tag.name = "#__proto__"; + + this.tagsStack.push([this.currentNodeTagName,this.currentNode]); //this.currentNode is parent node here + this.currentNodeTagName = tag.name; + this.currentNode = { [tag.name]:[]} + if(Object.keys(this.attributes).length > 0){ + this.currentNode[":@"] = this.attributes; + this.attributes = {}; + } + } + + /** + * Check if the node should be added by checking user's preference + * @param {Node} node + * @returns boolean: true if the node should not be added + */ + closeTag(){ + const node = this.currentNode; + const nodeName = this.currentNodeTagName; + const arr = this.tagsStack.pop(); //set parent node in scope + this.currentNodeTagName = arr[0]; + this.currentNode = arr[1]; + + if(this.options.onClose !== undefined){ + //TODO TagPathMatcher + const resultTag = this.options.onClose(node, + new TagPathMatcher(this.tagsStack,node)); + + if(resultTag) return; + } + this.currentNode[this.currentNodeTagName].push(node); //to parent node + } + + //Called by parent class methods + _addChild(key, val){ + // if(key === "__proto__") tagName = "#__proto__"; + this.currentNode.push( {[key]: val }); + // this.currentNode.leafType = false; + } + + /** + * Add text value child node + * @param {string} text + */ + addValue(text){ + this.currentNode[this.currentNodeTagName].push( {[this.options.nameFor.text]: this.parseValue(text, this.options.tags.valueParsers) }); + } + + addPi(name){ + if(!this.options.ignorePiTags){ + const node = { [name]:[]} + if(this.attributes){ + node[":@"] = this.attributes; + } + this.currentNode.push(node); + } + this.attributes = {}; + } + getOutput(){ + return this.root[rootName]; + } +} diff --git a/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsObjBuilder.js b/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsObjBuilder.js new file mode 100644 index 0000000..789a42b --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsObjBuilder.js @@ -0,0 +1,154 @@ + + +import {buildOptions,registerCommonValueParsers} from './ParserOptionsBuilder.js'; + +export default class OutputBuilder{ + constructor(builderOptions){ + this.options = buildOptions(builderOptions); + this.registeredParsers = registerCommonValueParsers(this.options); + } + + registerValueParser(name,parserInstance){//existing name will override the parser without warning + this.registeredParsers[name] = parserInstance; + } + + getInstance(parserOptions){ + return new JsObjBuilder(parserOptions, this.options, this.registeredParsers); + } +} + +import BaseOutputBuilder from './BaseOutputBuilder.js'; +const rootName = '^'; + +class JsObjBuilder extends BaseOutputBuilder{ + + constructor(parserOptions, builderOptions,registeredParsers) { + super(); + //hold the raw detail of a tag and sequence with reference to the output + this.tagsStack = []; + this.parserOptions = parserOptions; + this.options = builderOptions; + this.registeredParsers = registeredParsers; + + this.root = {}; + this.parent = this.root; + this.tagName = rootName; + this.value = {}; + this.textValue = ""; + this.attributes = {}; + } + + addTag(tag){ + + let value = ""; + if( !isEmpty(this.attributes)){ + value = {}; + if(this.options.attributes.groupBy){ + value[this.options.attributes.groupBy] = this.attributes; + }else{ + value = this.attributes; + } + } + + this.tagsStack.push([this.tagName, this.textValue, this.value]); //parent tag, parent text value, parent tag value (jsobj) + this.tagName = tag.name; + this.value = value; + this.textValue = ""; + this.attributes = {}; + } + + /** + * Check if the node should be added by checking user's preference + * @param {Node} node + * @returns boolean: true if the node should not be added + */ + closeTag(){ + const tagName = this.tagName; + let value = this.value; + let textValue = this.textValue; + + //update tag text value + if(typeof value !== "object" && !Array.isArray(value)){ + value = this.parseValue(textValue.trim(), this.options.tags.valueParsers); + }else if(textValue.length > 0){ + value[this.options.nameFor.text] = this.parseValue(textValue.trim(), this.options.tags.valueParsers); + } + + + let resultTag= { + tagName: tagName, + value: value + }; + + if(this.options.onTagClose !== undefined){ + //TODO TagPathMatcher + resultTag = this.options.onClose(tagName, value, this.textValue, new TagPathMatcher(this.tagsStack,node)); + + if(!resultTag) return; + } + + //set parent node in scope + let arr = this.tagsStack.pop(); + let parentTag = arr[2]; + parentTag=this._addChildTo(resultTag.tagName, resultTag.value, parentTag); + + this.tagName = arr[0]; + this.textValue = arr[1]; + this.value = parentTag; + } + + _addChild(key, val){ + if(typeof this.value === "string"){ + this.value = { [this.options.nameFor.text] : this.value }; + } + + this._addChildTo(key, val, this.value); + // this.currentNode.leafType = false; + this.attributes = {}; + } + + _addChildTo(key, val, node){ + if(typeof node === 'string') node = {}; + if(!node[key]){ + node[key] = val; + }else{ //Repeated + if(!Array.isArray(node[key])){ //but not stored as array + node[key] = [node[key]]; + } + node[key].push(val); + } + return node; + } + + + /** + * Add text value child node + * @param {string} text + */ + addValue(text){ + //TODO: use bytes join + if(this.textValue.length > 0) this.textValue += " " + text; + else this.textValue = text; + } + + addPi(name){ + let value = ""; + if( !isEmpty(this.attributes)){ + value = {}; + if(this.options.attributes.groupBy){ + value[this.options.attributes.groupBy] = this.attributes; + }else{ + value = this.attributes; + } + } + this._addChild(name, value); + + } + getOutput(){ + return this.value; + } +} + +function isEmpty(obj) { + return Object.keys(obj).length === 0; +} diff --git a/node_modules/fast-xml-parser/src/v6/OutputBuilders/ParserOptionsBuilder.js b/node_modules/fast-xml-parser/src/v6/OutputBuilders/ParserOptionsBuilder.js new file mode 100644 index 0000000..fa0e84e --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/OutputBuilders/ParserOptionsBuilder.js @@ -0,0 +1,94 @@ +import trimParser from "../valueParsers/trim"; +import booleanParser from "../valueParsers/booleanParser"; +import currencyParser from "../valueParsers/currency"; +import numberParser from "../valueParsers/number"; + +const defaultOptions={ + nameFor:{ + text: "#text", + comment: "", + cdata: "", + }, + // onTagClose: () => {}, + // onAttribute: () => {}, + piTag: false, + declaration: false, //"?xml" + tags: { + valueParsers: [ + // "trim", + // "boolean", + // "number", + // "currency", + // "date", + ] + }, + attributes:{ + prefix: "@_", + suffix: "", + groupBy: "", + + valueParsers: [ + // "trim", + // "boolean", + // "number", + // "currency", + // "date", + ] + }, + dataType:{ + + } +} + +//TODO +const withJoin = ["trim","join", /*"entities",*/"number","boolean","currency"/*, "date"*/] +const withoutJoin = ["trim", /*"entities",*/"number","boolean","currency"/*, "date"*/] + +export function buildOptions(options){ + //clone + const finalOptions = { ... defaultOptions}; + + //add config missed in cloning + finalOptions.tags.valueParsers.push(...withJoin) + if(!this.preserveOrder) + finalOptions.tags.valueParsers.push(...withoutJoin); + + //add config missed in cloning + finalOptions.attributes.valueParsers.push(...withJoin) + + //override configuration + copyProperties(finalOptions,options); + return finalOptions; +} + +function copyProperties(target, source) { + for (let key in source) { + if (source.hasOwnProperty(key)) { + if (typeof source[key] === 'object' && !Array.isArray(source[key])) { + // Recursively copy nested properties + if (typeof target[key] === 'undefined') { + target[key] = {}; + } + copyProperties(target[key], source[key]); + } else { + // Copy non-nested properties + target[key] = source[key]; + } + } + } +} + +export function registerCommonValueParsers(options){ + return { + "trim": new trimParser(), + // "join": this.entityParser.parse, + "boolean": new booleanParser(), + "number": new numberParser({ + hex: true, + leadingZeros: true, + eNotation: true + }), + "currency": new currencyParser(), + // "date": this.entityParser.parse, + } +} diff --git a/node_modules/fast-xml-parser/src/v6/Report.js b/node_modules/fast-xml-parser/src/v6/Report.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/fast-xml-parser/src/v6/TagPath.js b/node_modules/fast-xml-parser/src/v6/TagPath.js new file mode 100644 index 0000000..98148c7 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/TagPath.js @@ -0,0 +1,81 @@ +export default class TagPath{ + constructor(pathStr){ + let text = ""; + let tName = ""; + let pos; + let aName = ""; + let aVal = ""; + this.stack = [] + + for (let i = 0; i < pathStr.length; i++) { + let ch = pathStr[i]; + if(ch === " ") { + if(text.length === 0) continue; + tName = text; text = ""; + }else if(ch === "["){ + if(tName.length === 0){ + tName = text; text = ""; + } + i++; + for (; i < pathStr.length; i++) { + ch = pathStr[i]; + if(ch=== "=") continue; + else if(ch=== "]") {aName = text.trim(); text=""; break; i--;} + else if(ch === "'" || ch === '"'){ + let attrEnd = pathStr.indexOf(ch,i+1); + aVal = pathStr.substring(i+1, attrEnd); + i = attrEnd; + }else{ + text +=ch; + } + } + }else if(ch !== " " && text.length === 0 && tName.length > 0){//reading tagName + //save previous tag + this.stack.push(new TagPathNode(tName,pos,aName,aVal)); + text = ch; tName = ""; aName = ""; aVal = ""; + }else{ + text+=ch; + } + } + + //last tag in the path + if(tName.length >0 || text.length>0){ + this.stack.push(new TagPathNode(text||tName,pos,aName,aVal)); + } + } + + match(tagStack,node){ + if(this.stack[0].name !== "*"){ + if(this.stack.length !== tagStack.length +1) return false; + + //loop through tagPath and tagStack and match + for (let i = 0; i < this.tagStack.length; i++) { + if(!this.stack[i].match(tagStack[i])) return false; + } + } + if(!this.stack[this.stack.length - 1].match(node)) return false; + return true; + } +} + +class TagPathNode{ + constructor(name,position,attrName,attrVal){ + this.name = name; + this.position = position; + this.attrName = attrName, + this.attrVal = attrVal; + } + + match(node){ + let matching = true; + matching = node.name === this.name; + if(this.position) matching = node.position === this.position; + if(this.attrName) matching = node.attrs[this.attrName !== undefined]; + if(this.attrVal) matching = node.attrs[this.attrName !== this.attrVal]; + return matching; + } +} + +// console.log((new TagPath("* b[b]")).stack); +// console.log((new TagPath("a[a] b[b] c")).stack); +// console.log((new TagPath(" b [ b= 'cf sdadwa' ] a ")).stack); \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v6/TagPathMatcher.js b/node_modules/fast-xml-parser/src/v6/TagPathMatcher.js new file mode 100644 index 0000000..8110447 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/TagPathMatcher.js @@ -0,0 +1,13 @@ +import {TagPath} from './TagPath.js'; + +export default class TagPathMatcher{ + constructor(stack,node){ + this.stack = stack; + this.node= node; + } + + match(path){ + const tagPath = new TagPath(path); + return tagPath.match(this.stack, this.node); + } +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v6/XMLParser.js b/node_modules/fast-xml-parser/src/v6/XMLParser.js new file mode 100644 index 0000000..0da7059 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/XMLParser.js @@ -0,0 +1,83 @@ +import { buildOptions} from './OptionsBuilder.js'; +import Xml2JsParser from './Xml2JsParser.js'; + +export default class XMLParser{ + + constructor(options){ + this.externalEntities = {}; + this.options = buildOptions(options); + // console.log(this.options) + } + /** + * Parse XML data string to JS object + * @param {string|Buffer} xmlData + * @param {boolean|Object} validationOption + */ + parse(xmlData){ + if(Array.isArray(xmlData) && xmlData.byteLength !== undefined){ + return this.parse(xmlData); + }else if( xmlData.toString){ + xmlData = xmlData.toString(); + }else{ + throw new Error("XML data is accepted in String or Bytes[] form.") + } + // if( validationOption){ + // if(validationOption === true) validationOption = {}; //validate with default options + + // const result = validator.validate(xmlData, validationOption); + // if (result !== true) { + // throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` ) + // } + // } + const parser = new Xml2JsParser(this.options); + parser.entityParser.addExternalEntities(this.externalEntities); + return parser.parse(xmlData); + } + /** + * Parse XML data buffer to JS object + * @param {string|Buffer} xmlData + * @param {boolean|Object} validationOption + */ + parseBytesArr(xmlData){ + if(Array.isArray(xmlData) && xmlData.byteLength !== undefined){ + }else{ + throw new Error("XML data is accepted in Bytes[] form.") + } + const parser = new Xml2JsParser(this.options); + parser.entityParser.addExternalEntities(this.externalEntities); + return parser.parseBytesArr(xmlData); + } + /** + * Parse XML data stream to JS object + * @param {fs.ReadableStream} xmlDataStream + */ + parseStream(xmlDataStream){ + if(!isStream(xmlDataStream)) throw new Error("FXP: Invalid stream input"); + + const orderedObjParser = new Xml2JsParser(this.options); + orderedObjParser.entityParser.addExternalEntities(this.externalEntities); + return orderedObjParser.parseStream(xmlDataStream); + } + + /** + * Add Entity which is not by default supported by this library + * @param {string} key + * @param {string} value + */ + addEntity(key, value){ + if(value.indexOf("&") !== -1){ + throw new Error("Entity value can't have '&'") + }else if(key.indexOf("&") !== -1 || key.indexOf(";") !== -1){ + throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '") + }else if(value === "&"){ + throw new Error("An entity with value '&' is not permitted"); + }else{ + this.externalEntities[key] = value; + } + } +} + +function isStream(stream){ + if(stream && typeof stream.read === "function" && typeof stream.on === "function" && typeof stream.readableEnded === "boolean") return true; + return false; +} diff --git a/node_modules/fast-xml-parser/src/v6/Xml2JsParser.js b/node_modules/fast-xml-parser/src/v6/Xml2JsParser.js new file mode 100644 index 0000000..bd62265 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/Xml2JsParser.js @@ -0,0 +1,235 @@ +import StringSource from './inputSource/StringSource.js'; +import BufferSource from './inputSource/BufferSource.js'; +import {readTagExp,readClosingTagName} from './XmlPartReader.js'; +import {readComment, readCdata,readDocType,readPiTag} from './XmlSpecialTagsReader.js'; +import TagPath from './TagPath.js'; +import TagPathMatcher from './TagPathMatcher.js'; +import EntitiesParser from './EntitiesParser.js'; + +//To hold the data of current tag +//This is usually used to compare jpath expression against current tag +class TagDetail{ + constructor(name){ + this.name = name; + this.position = 0; + // this.attributes = {}; + } +} + +export default class Xml2JsParser { + constructor(options) { + this.options = options; + + this.currentTagDetail = null; + this.tagTextData = ""; + this.tagsStack = []; + this.entityParser = new EntitiesParser(options.htmlEntities); + this.stopNodes = []; + for (let i = 0; i < this.options.stopNodes.length; i++) { + this.stopNodes.push(new TagPath(this.options.stopNodes[i])); + } + } + + parse(strData) { + this.source = new StringSource(strData); + this.parseXml(); + return this.outputBuilder.getOutput(); + } + parseBytesArr(data) { + this.source = new BufferSource(data ); + this.parseXml(); + return this.outputBuilder.getOutput(); + } + + parseXml() { + //TODO: Separate TagValueParser as separate class. So no scope issue in node builder class + + //OutputBuilder should be set in XML Parser + this.outputBuilder = this.options.OutputBuilder.getInstance(this.options); + this.root = { root: true}; + this.currentTagDetail = this.root; + + while(this.source.canRead()){ + let ch = this.source.readCh(); + if (ch === "") break; + + if(ch === "<"){//tagStart + let nextChar = this.source.readChAt(0); + if (nextChar === "" ) throw new Error("Unexpected end of source"); + + + if(nextChar === "!" || nextChar === "?"){ + this.source.updateBufferBoundary(); + //previously collected text should be added to current node + this.addTextNode(); + + this.readSpecialTag(nextChar);// Read DOCTYPE, comment, CDATA, PI tag + }else if(nextChar === "/"){ + this.source.updateBufferBoundary(); + this.readClosingTag(); + // console.log(this.source.buffer.length, this.source.readable); + // console.log(this.tagsStack.length); + }else{//opening tag + this.readOpeningTag(); + } + }else{ + this.tagTextData += ch; + } + }//End While loop + if(this.tagsStack.length > 0 || ( this.tagTextData !== "undefined" && this.tagTextData.trimEnd().length > 0) ) throw new Error("Unexpected data in the end of document"); + } + + /** + * read closing paired tag. Set parent tag in scope. + * skip a node on user's choice + */ + readClosingTag(){ + const tagName = this.processTagName(readClosingTagName(this.source)); + // console.log(tagName, this.tagsStack.length); + this.validateClosingTag(tagName); + // All the text data collected, belongs to current tag. + if(!this.currentTagDetail.root) this.addTextNode(); + this.outputBuilder.closeTag(); + // Since the tag is closed now, parent tag comes in scope + this.currentTagDetail = this.tagsStack.pop(); + } + + validateClosingTag(tagName){ + // This can't be unpaired tag, or a stop tag. + if(this.isUnpaired(tagName) || this.isStopNode(tagName)) throw new Error(`Unexpected closing tag '${tagName}'`); + // This must match with last opening tag + else if(tagName !== this.currentTagDetail.name) + throw new Error(`Unexpected closing tag '${tagName}' expecting '${this.currentTagDetail.name}'`) + } + + /** + * Read paired, unpaired, self-closing, stop and special tags. + * Create a new node + * Push paired tag in stack. + */ + readOpeningTag(){ + //save previously collected text data to current node + this.addTextNode(); + + //create new tag + let tagExp = readTagExp(this, ">" ); + + // process and skip from tagsStack For unpaired tag, self closing tag, and stop node + const tagDetail = new TagDetail(tagExp.tagName); + if(this.isUnpaired(tagExp.tagName)) { + //TODO: this will lead 2 extra stack operation + this.outputBuilder.addTag(tagDetail); + this.outputBuilder.closeTag(); + } else if(tagExp.selfClosing){ + this.outputBuilder.addTag(tagDetail); + this.outputBuilder.closeTag(); + } else if(this.isStopNode(this.currentTagDetail)){ + // TODO: let's user set a stop node boundary detector for complex contents like script tag + //TODO: pass tag name only to avoid string operations + const content = source.readUptoCloseTag(` 0){ + //TODO: shift parsing to output builder + + this.outputBuilder.addValue(this.replaceEntities(this.tagTextData)); + } + this.tagTextData = ""; + } + // } + } + + processAttrName(name){ + if(name === "__proto__") name = "#__proto__"; + name = resolveNameSpace(name, this.removeNSPrefix); + return name; + } + + processTagName(name){ + if(name === "__proto__") name = "#__proto__"; + name = resolveNameSpace(name, this.removeNSPrefix); + return name; + } + + /** + * Generate tags path from tagsStack + */ + tagsPath(tagName){ + //TODO: return TagPath Object. User can call match method with path + return ""; + } + + isUnpaired(tagName){ + return this.options.tags.unpaired.indexOf(tagName) !== -1; + } + + /** + * valid expressions are + * tag nested + * * nested + * tag nested[attribute] + * tag nested[attribute=""] + * tag nested[attribute!=""] + * tag nested:0 //for future + * @param {string} tagName + * @returns + */ + isStopNode(node){ + for (let i = 0; i < this.stopNodes.length; i++) { + const givenPath = this.stopNodes[i]; + if(givenPath.match(this.tagsStack, node)) return true; + } + return false + } + + replaceEntities(text){ + //TODO: if option is set then replace entities + return this.entityParser.parse(text) + } +} + +function resolveNameSpace(name, removeNSPrefix) { + if (removeNSPrefix) { + const parts = name.split(':'); + if(parts.length === 2){ + if (parts[0] === 'xmlns') return ''; + else return parts[1]; + }else reportError(`Multiple namespaces ${name}`) + } + return name; +} diff --git a/node_modules/fast-xml-parser/src/v6/XmlPartReader.js b/node_modules/fast-xml-parser/src/v6/XmlPartReader.js new file mode 100644 index 0000000..61c57ec --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/XmlPartReader.js @@ -0,0 +1,210 @@ +'use strict'; + +/** + * find paired tag for a stop node + * @param {string} xmlDoc + * @param {string} tagName + * @param {number} i : start index + */ +export function readStopNode(xmlDoc, tagName, i){ + const startIndex = i; + // Starting at 1 since we already have an open tag + let openTagCount = 1; + + for (; i < xmlDoc.length; i++) { + if( xmlDoc[i] === "<"){ + if (xmlDoc[i+1] === "/") {//close tag + const closeIndex = findSubStrIndex(xmlDoc, ">", i, `${tagName} is not closed`); + let closeTagName = xmlDoc.substring(i+2,closeIndex).trim(); + if(closeTagName === tagName){ + openTagCount--; + if (openTagCount === 0) { + return { + tagContent: xmlDoc.substring(startIndex, i), + i : closeIndex + } + } + } + i=closeIndex; + } else if(xmlDoc[i+1] === '?') { + const closeIndex = findSubStrIndex(xmlDoc, "?>", i+1, "StopNode is not closed.") + i=closeIndex; + } else if(xmlDoc.substr(i + 1, 3) === '!--') { + const closeIndex = findSubStrIndex(xmlDoc, "-->", i+3, "StopNode is not closed.") + i=closeIndex; + } else if(xmlDoc.substr(i + 1, 2) === '![') { + const closeIndex = findSubStrIndex(xmlDoc, "]]>", i, "StopNode is not closed.") - 2; + i=closeIndex; + } else { + const tagData = readTagExp(xmlDoc, i, '>') + + if (tagData) { + const openTagName = tagData && tagData.tagName; + if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== "/") { + openTagCount++; + } + i=tagData.closeIndex; + } + } + } + }//end for loop +} + +/** + * Read closing tag name + * @param {Source} source + * @returns tag name + */ +export function readClosingTagName(source){ + let text = ""; //temporary data + while(source.canRead()){ + let ch = source.readCh(); + // if (ch === null || ch === undefined) break; + // source.updateBuffer(); + + if (ch === ">") return text.trimEnd(); + else text += ch; + } + throw new Error(`Unexpected end of source. Reading '${substr}'`); +} + +/** + * Read XML tag and build attributes map + * This function can be used to read normal tag, pi tag. + * This function can't be used to read comment, CDATA, DOCTYPE. + * Eg + * @param {string} xmlDoc + * @param {number} startIndex starting index + * @returns tag expression includes tag name & attribute string + */ +export function readTagExp(parser) { + let inSingleQuotes = false; + let inDoubleQuotes = false; + let i; + let EOE = false; + + for (i = 0; parser.source.canRead(i); i++) { + const char = parser.source.readChAt(i); + + if (char === "'" && !inDoubleQuotes) { + inSingleQuotes = !inSingleQuotes; + } else if (char === '"' && !inSingleQuotes) { + inDoubleQuotes = !inDoubleQuotes; + } else if (char === '>' && !inSingleQuotes && !inDoubleQuotes) { + // If not inside quotes, stop reading at '>' + EOE = true; + break; + } + + } + if(inSingleQuotes || inDoubleQuotes){ + throw new Error("Invalid attribute expression. Quote is not properly closed"); + }else if(!EOE) throw new Error("Unexpected closing of source. Waiting for '>'"); + + + const exp = parser.source.readStr(i); + parser.source.updateBufferBoundary(i + 1); + return buildTagExpObj(exp, parser) +} + +export function readPiExp(parser) { + let inSingleQuotes = false; + let inDoubleQuotes = false; + let i; + let EOE = false; + + for (i = 0; parser.source.canRead(i) ; i++) { + const currentChar = parser.source.readChAt(i); + const nextChar = parser.source.readChAt(i+1); + + if (currentChar === "'" && !inDoubleQuotes) { + inSingleQuotes = !inSingleQuotes; + } else if (currentChar === '"' && !inSingleQuotes) { + inDoubleQuotes = !inDoubleQuotes; + } + + if (!inSingleQuotes && !inDoubleQuotes) { + if (currentChar === '?' && nextChar === '>') { + EOE = true; + break; // Exit the loop when '?>' is found + } + } + } + if(inSingleQuotes || inDoubleQuotes){ + throw new Error("Invalid attribute expression. Quote is not properly closed in PI tag expression"); + }else if(!EOE) throw new Error("Unexpected closing of source. Waiting for '?>'"); + + if(!parser.options.attributes.ignore){ + //TODO: use regex to verify attributes if not set to ignore + } + + const exp = parser.source.readStr(i); + parser.source.updateBufferBoundary(i + 1); + return buildTagExpObj(exp, parser) +} + +function buildTagExpObj(exp, parser){ + const tagExp = { + tagName: "", + selfClosing: false + }; + let attrsExp = ""; + + // Check for self-closing tag before setting the name + if(exp[exp.length -1] === "/") { + tagExp.selfClosing = true; + exp = exp.slice(0, -1); // Remove the trailing slash + } + + //separate tag name + let i = 0; + for (; i < exp.length; i++) { + const char = exp[i]; + if(char === " "){ + tagExp.tagName = exp.substring(0, i); + attrsExp = exp.substring(i + 1); + break; + } + } + //only tag + if(tagExp.tagName.length === 0 && i === exp.length)tagExp.tagName = exp; + + tagExp.tagName = tagExp.tagName.trimEnd(); + + if(!parser.options.attributes.ignore && attrsExp.length > 0){ + parseAttributesExp(attrsExp,parser) + } + + return tagExp; +} + +const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm'); + +function parseAttributesExp(attrStr, parser) { + const matches = getAllMatches(attrStr, attrsRegx); + const len = matches.length; //don't make it inline + for (let i = 0; i < len; i++) { + let attrName = parser.processAttrName(matches[i][1]); + let attrVal = parser.replaceEntities(matches[i][4] || true); + + parser.outputBuilder.addAttribute(attrName, attrVal); + } +} + + +const getAllMatches = function(string, regex) { + const matches = []; + let match = regex.exec(string); + while (match) { + const allmatches = []; + allmatches.startIndex = regex.lastIndex - match[0].length; + const len = match.length; + for (let index = 0; index < len; index++) { + allmatches.push(match[index]); + } + matches.push(allmatches); + match = regex.exec(string); + } + return matches; +}; + diff --git a/node_modules/fast-xml-parser/src/v6/XmlSpecialTagsReader.js b/node_modules/fast-xml-parser/src/v6/XmlSpecialTagsReader.js new file mode 100644 index 0000000..330e0a4 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/XmlSpecialTagsReader.js @@ -0,0 +1,111 @@ +import {readPiExp} from './XmlPartReader.js'; + +export function readCdata(parser){ + //"); + parser.outputBuilder.addCdata(text); +} +export function readPiTag(parser){ + //"); + if(!tagExp) throw new Error("Invalid Pi Tag expression."); + + if (tagExp.tagName === "?xml") {//TODO: test if tagName is just xml + parser.outputBuilder.addDeclaration(); + } else { + parser.outputBuilder.addPi("?"+tagExp.tagName); + } +} + +export function readComment(parser){ + //"); + parser.outputBuilder.addComment(text); +} + +const DOCTYPE_tags = { + "EL":/^EMENT\s+([^\s>]+)\s+(ANY|EMPTY|\(.+\)\s*$)/m, + "AT":/^TLIST\s+[^\s]+\s+[^\s]+\s+[^\s]+\s+[^\s]+\s+$/m, + "NO":/^TATION.+$/m +} +export function readDocType(parser){ + //"); + const regx = DOCTYPE_tags[str]; + if(regx){ + const match = dTagExp.match(regx); + if(!match) throw new Error("Invalid DOCTYPE"); + }else throw new Error("Invalid DOCTYPE"); + } + }else if( ch === '>' && lastch === "]"){//end of doctype + return; + } + }else if( ch === '>'){//end of doctype + return; + }else if( ch === '['){ + hasBody = true; + }else{ + lastch = ch; + } + }//End While loop + +} + +function registerEntity(parser){ + //read Entity + let attrBoundary=""; + let name ="", val =""; + while(source.canRead()){ + let ch = source.readCh(); + + if(attrBoundary){ + if (ch === attrBoundary){ + val = text; + text = "" + } + }else if(ch === " " || ch === "\t"){ + if(!name){ + name = text.trimStart(); + text = ""; + } + }else if (ch === '"' || ch === "'") {//start of attrBoundary + attrBoundary = ch; + }else if(ch === ">"){ + parser.entityParser.addExternalEntity(name,val); + return; + }else{ + text+=ch; + } + } +} diff --git a/node_modules/fast-xml-parser/src/v6/inputSource/BufferSource.js b/node_modules/fast-xml-parser/src/v6/inputSource/BufferSource.js new file mode 100644 index 0000000..2c5d8b5 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/inputSource/BufferSource.js @@ -0,0 +1,116 @@ +const Constants = { + space: 32, + tab: 9 +} +export default class BufferSource{ + constructor(bytesArr){ + this.line = 1; + this.cols = 0; + this.buffer = bytesArr; + this.startIndex = 0; + } + + + + readCh() { + return String.fromCharCode(this.buffer[this.startIndex++]); + } + + readChAt(index) { + return String.fromCharCode(this.buffer[this.startIndex+index]); + } + + readStr(n,from){ + if(typeof from === "undefined") from = this.startIndex; + return this.buffer.slice(from, from + n).toString(); + } + + readUpto(stopStr) { + const inputLength = this.buffer.length; + const stopLength = stopStr.length; + const stopBuffer = Buffer.from(stopStr); + + for (let i = this.startIndex; i < inputLength; i++) { + let match = true; + for (let j = 0; j < stopLength; j++) { + if (this.buffer[i + j] !== stopBuffer[j]) { + match = false; + break; + } + } + + if (match) { + const result = this.buffer.slice(this.startIndex, i).toString(); + this.startIndex = i + stopLength; + return result; + } + } + + throw new Error(`Unexpected end of source. Reading '${stopStr}'`); +} + +readUptoCloseTag(stopStr) { //stopStr: "'){ //TODO: if it should be equivalent ASCII + match = 2; + //tag boundary found + // this.startIndex + } + }else{ + match = 1; + for (let j = 0; j < stopLength; j++) { + if (this.buffer[i + j] !== stopBuffer[j]) { + match = 0; + break; + } + } + } + if (match === 2) {//matched closing part + const result = this.buffer.slice(this.startIndex, stopIndex - 1 ).toString(); + this.startIndex = i + 1; + return result; + } + } + + throw new Error(`Unexpected end of source. Reading '${stopStr}'`); +} + + readFromBuffer(n, shouldUpdate) { + let ch; + if (n === 1) { + ch = this.buffer[this.startIndex]; + if (ch === 10) { + this.line++; + this.cols = 1; + } else { + this.cols++; + } + ch = String.fromCharCode(ch); + } else { + this.cols += n; + ch = this.buffer.slice(this.startIndex, this.startIndex + n).toString(); + } + if (shouldUpdate) this.updateBuffer(n); + return ch; + } + + updateBufferBoundary(n = 1) { //n: number of characters read + this.startIndex += n; + } + + canRead(n){ + n = n || this.startIndex; + return this.buffer.length - n + 1 > 0; + } + +} diff --git a/node_modules/fast-xml-parser/src/v6/inputSource/StringSource.js b/node_modules/fast-xml-parser/src/v6/inputSource/StringSource.js new file mode 100644 index 0000000..275889a --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/inputSource/StringSource.js @@ -0,0 +1,121 @@ +const whiteSpaces = [" ", "\n", "\t"]; + + +export default class StringSource{ + constructor(str){ + this.line = 1; + this.cols = 0; + this.buffer = str; + //a boundary pointer to indicate where from the buffer dat should be read + // data before this pointer can be deleted to free the memory + this.startIndex = 0; + } + + readCh() { + return this.buffer[this.startIndex++]; + } + + readChAt(index) { + return this.buffer[this.startIndex+index]; + } + + readStr(n,from){ + if(typeof from === "undefined") from = this.startIndex; + return this.buffer.substring(from, from + n); + } + + readUpto(stopStr) { + const inputLength = this.buffer.length; + const stopLength = stopStr.length; + + for (let i = this.startIndex; i < inputLength; i++) { + let match = true; + for (let j = 0; j < stopLength; j++) { + if (this.buffer[i + j] !== stopStr[j]) { + match = false; + break; + } + } + + if (match) { + const result = this.buffer.substring(this.startIndex, i); + this.startIndex = i + stopLength; + return result; + } + } + + throw new Error(`Unexpected end of source. Reading '${stopStr}'`); + } + + readUptoCloseTag(stopStr) { //stopStr: "'){ + match = 2; + //tag boundary found + // this.startIndex + } + }else{ + match = 1; + for (let j = 0; j < stopLength; j++) { + if (this.buffer[i + j] !== stopStr[j]) { + match = 0; + break; + } + } + } + if (match === 2) {//matched closing part + const result = this.buffer.substring(this.startIndex, stopIndex - 1 ); + this.startIndex = i + 1; + return result; + } + } + + throw new Error(`Unexpected end of source. Reading '${stopStr}'`); + } + + readFromBuffer(n, updateIndex){ + let ch; + if(n===1){ + ch = this.buffer[this.startIndex]; + // if(ch === "\n") { + // this.line++; + // this.cols = 1; + // }else{ + // this.cols++; + // } + }else{ + ch = this.buffer.substring(this.startIndex, this.startIndex + n); + // if("".indexOf("\n") !== -1){ + // //TODO: handle the scenario when there are multiple lines + // //TODO: col should be set to number of chars after last '\n' + // // this.cols = 1; + // }else{ + // this.cols += n; + + // } + } + if(updateIndex) this.updateBufferBoundary(n); + return ch; + } + + //TODO: rename to updateBufferReadIndex + + updateBufferBoundary(n = 1) { //n: number of characters read + this.startIndex += n; + } + + canRead(n){ + n = n || this.startIndex; + return this.buffer.length - n + 1 > 0; + } + +} diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/EntitiesParser.js b/node_modules/fast-xml-parser/src/v6/valueParsers/EntitiesParser.js new file mode 100644 index 0000000..52b4203 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/EntitiesParser.js @@ -0,0 +1,105 @@ +const ampEntity = { regex: /&(amp|#38|#x26);/g, val : "&"}; +const htmlEntities = { + "space": { regex: /&(nbsp|#160);/g, val: " " }, + // "lt" : { regex: /&(lt|#60);/g, val: "<" }, + // "gt" : { regex: /&(gt|#62);/g, val: ">" }, + // "amp" : { regex: /&(amp|#38);/g, val: "&" }, + // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, + // "apos" : { regex: /&(apos|#39);/g, val: "'" }, + "cent" : { regex: /&(cent|#162);/g, val: "¢" }, + "pound" : { regex: /&(pound|#163);/g, val: "£" }, + "yen" : { regex: /&(yen|#165);/g, val: "¥" }, + "euro" : { regex: /&(euro|#8364);/g, val: "€" }, + "copyright" : { regex: /&(copy|#169);/g, val: "©" }, + "reg" : { regex: /&(reg|#174);/g, val: "®" }, + "inr" : { regex: /&(inr|#8377);/g, val: "₹" }, + "num_dec": { regex: /&#([0-9]{1,7});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 10)) }, + "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 16)) }, +}; + +export default class EntitiesParser{ + constructor(replaceHtmlEntities) { + this.replaceHtmlEntities = replaceHtmlEntities; + this.docTypeEntities = {}; + this.lastEntities = { + "apos" : { regex: /&(apos|#39|#x27);/g, val : "'"}, + "gt" : { regex: /&(gt|#62|#x3E);/g, val : ">"}, + "lt" : { regex: /&(lt|#60|#x3C);/g, val : "<"}, + "quot" : { regex: /&(quot|#34|#x22);/g, val : "\""}, + }; + } + + addExternalEntities(externalEntities){ + const entKeys = Object.keys(externalEntities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + this.addExternalEntity(ent,externalEntities[ent]) + } + } + addExternalEntity(key,val){ + validateEntityName(key); + if(val.indexOf("&") !== -1) { + reportWarning(`Entity ${key} is not added as '&' is found in value;`) + return; + }else{ + this.lastEntities[ent] = { + regex: new RegExp("&"+key+";","g"), + val : val + } + } + } + + addDocTypeEntities(entities){ + const entKeys = Object.keys(entities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + this.docTypeEntities[ent] = { + regex: new RegExp("&"+ent+";","g"), + val : entities[ent] + } + } + } + + parse(val){ + return this.replaceEntitiesValue(val) + } + + /** + * 1. Replace DOCTYPE entities + * 2. Replace external entities + * 3. Replace HTML entities if asked + * @param {string} val + */ + replaceEntitiesValue(val){ + if(typeof val === "string" && val.length > 0){ + for(let entityName in this.docTypeEntities){ + const entity = this.docTypeEntities[entityName]; + val = val.replace( entity.regx, entity.val); + } + for(let entityName in this.lastEntities){ + const entity = this.lastEntities[entityName]; + val = val.replace( entity.regex, entity.val); + } + if(this.replaceHtmlEntities){ + for(let entityName in htmlEntities){ + const entity = htmlEntities[entityName]; + val = val.replace( entity.regex, entity.val); + } + } + val = val.replace( ampEntity.regex, ampEntity.val); + } + return val; + } +}; + +//an entity name should not contains special characters that may be used in regex +//Eg !?\\\/[]$%{}^&*()<> +const specialChar = "!?\\\/[]$%{}^&*()<>|+"; + +function validateEntityName(name){ + for (let i = 0; i < specialChar.length; i++) { + const ch = specialChar[i]; + if(name.indexOf(ch) !== -1) throw new Error(`Invalid character ${ch} in entity name`); + } + return name; +} diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/booleanParser.js b/node_modules/fast-xml-parser/src/v6/valueParsers/booleanParser.js new file mode 100644 index 0000000..bc8f806 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/booleanParser.js @@ -0,0 +1,22 @@ +export default class boolParser{ + constructor(trueList, falseList){ + if(trueList) + this.trueList = trueList; + else + this.trueList = ["true"]; + + if(falseList) + this.falseList = falseList; + else + this.falseList = ["false"]; + } + parse(val){ + if (typeof val === 'string') { + //TODO: performance: don't convert + const temp = val.toLowerCase(); + if(this.trueList.indexOf(temp) !== -1) return true; + else if(this.falseList.indexOf(temp) !== -1 ) return false; + } + return val; + } +} diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/booleanParserExt.js b/node_modules/fast-xml-parser/src/v6/valueParsers/booleanParserExt.js new file mode 100644 index 0000000..ec3ba42 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/booleanParserExt.js @@ -0,0 +1,19 @@ +export default function boolParserExt(val){ + if(isArray(val)){ + for (let i = 0; i < val.length; i++) { + val[i] = parse(val[i]) + } + }else{ + val = parse(val) + } + return val; +} + +function parse(val){ + if (typeof val === 'string') { + const temp = val.toLowerCase(); + if(temp === 'true' || temp ==="yes" || temp==="1") return true; + else if(temp === 'false' || temp ==="no" || temp==="0") return false; + } + return val; +} diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/currency.js b/node_modules/fast-xml-parser/src/v6/valueParsers/currency.js new file mode 100644 index 0000000..3772817 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/currency.js @@ -0,0 +1,38 @@ +const defaultOptions = { + maxLength: 200, + // locale: "en-IN" +} +const localeMap = { + "$":"en-US", + "€":"de-DE", + "£":"en-GB", + "¥":"ja-JP", + "₹":"en-IN", +} +const sign = "(?:-|\+)?"; +const digitsAndSeparator = "(?:\d+|\d{1,3}(?:,\d{3})+)"; +const decimalPart = "(?:\.\d{1,2})?"; +const symbol = "(?:\$|€|¥|₹)?"; + +const currencyCheckRegex = /^\s*(?:-|\+)?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d{1,2})?\s*(?:\$|€|¥|₹)?\s*$/u; + +export default class CurrencyParser{ + constructor(options){ + this.options = options || defaultOptions; + } + parse(val){ + if (typeof val === 'string' && val.length <= this.options.maxLength) { + if(val.indexOf(",,") !== -1 && val.indexOf(".." !== -1)){ + const match = val.match(currencyCheckRegex); + if(match){ + const locale = this.options.locale || localeMap[match[2]||match[5]||"₹"]; + const formatter = new Intl.NumberFormat(locale) + val = val.replace(/[^0-9,.]/g, '').trim(); + val = Number(val.replace(formatter.format(1000)[1], '')); + } + } + } + return val; + } +} +CurrencyParser.defaultOptions = defaultOptions; diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/join.js b/node_modules/fast-xml-parser/src/v6/valueParsers/join.js new file mode 100644 index 0000000..f597d99 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/join.js @@ -0,0 +1,13 @@ +/** + * + * @param {array} val + * @param {string} by + * @returns + */ +export default function join(val, by=" "){ + if(isArray(val)){ + val.join(by) + } + return val; +} + diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/number.js b/node_modules/fast-xml-parser/src/v6/valueParsers/number.js new file mode 100644 index 0000000..8397fb6 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/number.js @@ -0,0 +1,14 @@ +import toNumber from "strnum"; + + +export default class numParser{ + constructor(options){ + this.options = options; + } + parse(val){ + if (typeof val === 'string') { + val = toNumber(val,this.options); + } + return val; + } +} diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/trim.js b/node_modules/fast-xml-parser/src/v6/valueParsers/trim.js new file mode 100644 index 0000000..50eed7f --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/trim.js @@ -0,0 +1,6 @@ +export default class trimmer{ + parse(val){ + if(typeof val === "string") return val.trim(); + else return val; + } +} diff --git a/node_modules/fast-xml-parser/src/validator.js b/node_modules/fast-xml-parser/src/validator.js new file mode 100644 index 0000000..3b1b2ef --- /dev/null +++ b/node_modules/fast-xml-parser/src/validator.js @@ -0,0 +1,425 @@ +'use strict'; + +const util = require('./util'); + +const defaultOptions = { + allowBooleanAttributes: false, //A tag can have attributes without any value + unpairedTags: [] +}; + +//const tagsPattern = new RegExp("<\\/?([\\w:\\-_\.]+)\\s*\/?>","g"); +exports.validate = function (xmlData, options) { + options = Object.assign({}, defaultOptions, options); + + //xmlData = xmlData.replace(/(\r\n|\n|\r)/gm,"");//make it single line + //xmlData = xmlData.replace(/(^\s*<\?xml.*?\?>)/g,"");//Remove XML starting tag + //xmlData = xmlData.replace(/()/g,"");//Remove DOCTYPE + const tags = []; + let tagFound = false; + + //indicates that the root tag has been closed (aka. depth 0 has been reached) + let reachedRoot = false; + + if (xmlData[0] === '\ufeff') { + // check for byte order mark (BOM) + xmlData = xmlData.substr(1); + } + + for (let i = 0; i < xmlData.length; i++) { + + if (xmlData[i] === '<' && xmlData[i+1] === '?') { + i+=2; + i = readPI(xmlData,i); + if (i.err) return i; + }else if (xmlData[i] === '<') { + //starting of tag + //read until you reach to '>' avoiding any '>' in attribute value + let tagStartPos = i; + i++; + + if (xmlData[i] === '!') { + i = readCommentAndCDATA(xmlData, i); + continue; + } else { + let closingTag = false; + if (xmlData[i] === '/') { + //closing tag + closingTag = true; + i++; + } + //read tagname + let tagName = ''; + for (; i < xmlData.length && + xmlData[i] !== '>' && + xmlData[i] !== ' ' && + xmlData[i] !== '\t' && + xmlData[i] !== '\n' && + xmlData[i] !== '\r'; i++ + ) { + tagName += xmlData[i]; + } + tagName = tagName.trim(); + //console.log(tagName); + + if (tagName[tagName.length - 1] === '/') { + //self closing tag without attributes + tagName = tagName.substring(0, tagName.length - 1); + //continue; + i--; + } + if (!validateTagName(tagName)) { + let msg; + if (tagName.trim().length === 0) { + msg = "Invalid space after '<'."; + } else { + msg = "Tag '"+tagName+"' is an invalid name."; + } + return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i)); + } + + const result = readAttributeStr(xmlData, i); + if (result === false) { + return getErrorObject('InvalidAttr', "Attributes for '"+tagName+"' have open quote.", getLineNumberForPosition(xmlData, i)); + } + let attrStr = result.value; + i = result.index; + + if (attrStr[attrStr.length - 1] === '/') { + //self closing tag + const attrStrStart = i - attrStr.length; + attrStr = attrStr.substring(0, attrStr.length - 1); + const isValid = validateAttributeString(attrStr, options); + if (isValid === true) { + tagFound = true; + //continue; //text may presents after self closing tag + } else { + //the result from the nested function returns the position of the error within the attribute + //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute + //this gives us the absolute index in the entire xml, which we can use to find the line at last + return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line)); + } + } else if (closingTag) { + if (!result.tagClosed) { + return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' doesn't have proper closing.", getLineNumberForPosition(xmlData, i)); + } else if (attrStr.trim().length > 0) { + return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos)); + } else if (tags.length === 0) { + return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos)); + } else { + const otg = tags.pop(); + if (tagName !== otg.tagName) { + let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos); + return getErrorObject('InvalidTag', + "Expected closing tag '"+otg.tagName+"' (opened in line "+openPos.line+", col "+openPos.col+") instead of closing tag '"+tagName+"'.", + getLineNumberForPosition(xmlData, tagStartPos)); + } + + //when there are no more tags, we reached the root level. + if (tags.length == 0) { + reachedRoot = true; + } + } + } else { + const isValid = validateAttributeString(attrStr, options); + if (isValid !== true) { + //the result from the nested function returns the position of the error within the attribute + //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute + //this gives us the absolute index in the entire xml, which we can use to find the line at last + return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line)); + } + + //if the root level has been reached before ... + if (reachedRoot === true) { + return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i)); + } else if(options.unpairedTags.indexOf(tagName) !== -1){ + //don't push into stack + } else { + tags.push({tagName, tagStartPos}); + } + tagFound = true; + } + + //skip tag text value + //It may include comments and CDATA value + for (i++; i < xmlData.length; i++) { + if (xmlData[i] === '<') { + if (xmlData[i + 1] === '!') { + //comment or CADATA + i++; + i = readCommentAndCDATA(xmlData, i); + continue; + } else if (xmlData[i+1] === '?') { + i = readPI(xmlData, ++i); + if (i.err) return i; + } else{ + break; + } + } else if (xmlData[i] === '&') { + const afterAmp = validateAmpersand(xmlData, i); + if (afterAmp == -1) + return getErrorObject('InvalidChar', "char '&' is not expected.", getLineNumberForPosition(xmlData, i)); + i = afterAmp; + }else{ + if (reachedRoot === true && !isWhiteSpace(xmlData[i])) { + return getErrorObject('InvalidXml', "Extra text at the end", getLineNumberForPosition(xmlData, i)); + } + } + } //end of reading tag text value + if (xmlData[i] === '<') { + i--; + } + } + } else { + if ( isWhiteSpace(xmlData[i])) { + continue; + } + return getErrorObject('InvalidChar', "char '"+xmlData[i]+"' is not expected.", getLineNumberForPosition(xmlData, i)); + } + } + + if (!tagFound) { + return getErrorObject('InvalidXml', 'Start tag expected.', 1); + }else if (tags.length == 1) { + return getErrorObject('InvalidTag', "Unclosed tag '"+tags[0].tagName+"'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos)); + }else if (tags.length > 0) { + return getErrorObject('InvalidXml', "Invalid '"+ + JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\r?\n/g, '')+ + "' found.", {line: 1, col: 1}); + } + + return true; +}; + +function isWhiteSpace(char){ + return char === ' ' || char === '\t' || char === '\n' || char === '\r'; +} +/** + * Read Processing insstructions and skip + * @param {*} xmlData + * @param {*} i + */ +function readPI(xmlData, i) { + const start = i; + for (; i < xmlData.length; i++) { + if (xmlData[i] == '?' || xmlData[i] == ' ') { + //tagname + const tagname = xmlData.substr(start, i - start); + if (i > 5 && tagname === 'xml') { + return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i)); + } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') { + //check if valid attribut string + i++; + break; + } else { + continue; + } + } + } + return i; +} + +function readCommentAndCDATA(xmlData, i) { + if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') { + //comment + for (i += 3; i < xmlData.length; i++) { + if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') { + i += 2; + break; + } + } + } else if ( + xmlData.length > i + 8 && + xmlData[i + 1] === 'D' && + xmlData[i + 2] === 'O' && + xmlData[i + 3] === 'C' && + xmlData[i + 4] === 'T' && + xmlData[i + 5] === 'Y' && + xmlData[i + 6] === 'P' && + xmlData[i + 7] === 'E' + ) { + let angleBracketsCount = 1; + for (i += 8; i < xmlData.length; i++) { + if (xmlData[i] === '<') { + angleBracketsCount++; + } else if (xmlData[i] === '>') { + angleBracketsCount--; + if (angleBracketsCount === 0) { + break; + } + } + } + } else if ( + xmlData.length > i + 9 && + xmlData[i + 1] === '[' && + xmlData[i + 2] === 'C' && + xmlData[i + 3] === 'D' && + xmlData[i + 4] === 'A' && + xmlData[i + 5] === 'T' && + xmlData[i + 6] === 'A' && + xmlData[i + 7] === '[' + ) { + for (i += 8; i < xmlData.length; i++) { + if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') { + i += 2; + break; + } + } + } + + return i; +} + +const doubleQuote = '"'; +const singleQuote = "'"; + +/** + * Keep reading xmlData until '<' is found outside the attribute value. + * @param {string} xmlData + * @param {number} i + */ +function readAttributeStr(xmlData, i) { + let attrStr = ''; + let startChar = ''; + let tagClosed = false; + for (; i < xmlData.length; i++) { + if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) { + if (startChar === '') { + startChar = xmlData[i]; + } else if (startChar !== xmlData[i]) { + //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa + } else { + startChar = ''; + } + } else if (xmlData[i] === '>') { + if (startChar === '') { + tagClosed = true; + break; + } + } + attrStr += xmlData[i]; + } + if (startChar !== '') { + return false; + } + + return { + value: attrStr, + index: i, + tagClosed: tagClosed + }; +} + +/** + * Select all the attributes whether valid or invalid. + */ +const validAttrStrRegxp = new RegExp('(\\s*)([^\\s=]+)(\\s*=)?(\\s*([\'"])(([\\s\\S])*?)\\5)?', 'g'); + +//attr, ="sd", a="amit's", a="sd"b="saf", ab cd="" + +function validateAttributeString(attrStr, options) { + //console.log("start:"+attrStr+":end"); + + //if(attrStr.trim().length === 0) return true; //empty string + + const matches = util.getAllMatches(attrStr, validAttrStrRegxp); + const attrNames = {}; + + for (let i = 0; i < matches.length; i++) { + if (matches[i][1].length === 0) { + //nospace before attribute name: a="sd"b="saf" + return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' has no space in starting.", getPositionFromMatch(matches[i])) + } else if (matches[i][3] !== undefined && matches[i][4] === undefined) { + return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' is without value.", getPositionFromMatch(matches[i])); + } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) { + //independent attribute: ab + return getErrorObject('InvalidAttr', "boolean attribute '"+matches[i][2]+"' is not allowed.", getPositionFromMatch(matches[i])); + } + /* else if(matches[i][6] === undefined){//attribute without value: ab= + return { err: { code:"InvalidAttr",msg:"attribute " + matches[i][2] + " has no value assigned."}}; + } */ + const attrName = matches[i][2]; + if (!validateAttrName(attrName)) { + return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is an invalid name.", getPositionFromMatch(matches[i])); + } + if (!attrNames.hasOwnProperty(attrName)) { + //check for duplicate attribute. + attrNames[attrName] = 1; + } else { + return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is repeated.", getPositionFromMatch(matches[i])); + } + } + + return true; +} + +function validateNumberAmpersand(xmlData, i) { + let re = /\d/; + if (xmlData[i] === 'x') { + i++; + re = /[\da-fA-F]/; + } + for (; i < xmlData.length; i++) { + if (xmlData[i] === ';') + return i; + if (!xmlData[i].match(re)) + break; + } + return -1; +} + +function validateAmpersand(xmlData, i) { + // https://www.w3.org/TR/xml/#dt-charref + i++; + if (xmlData[i] === ';') + return -1; + if (xmlData[i] === '#') { + i++; + return validateNumberAmpersand(xmlData, i); + } + let count = 0; + for (; i < xmlData.length; i++, count++) { + if (xmlData[i].match(/\w/) && count < 20) + continue; + if (xmlData[i] === ';') + break; + return -1; + } + return i; +} + +function getErrorObject(code, message, lineNumber) { + return { + err: { + code: code, + msg: message, + line: lineNumber.line || lineNumber, + col: lineNumber.col, + }, + }; +} + +function validateAttrName(attrName) { + return util.isName(attrName); +} + +// const startsWithXML = /^xml/i; + +function validateTagName(tagname) { + return util.isName(tagname) /* && !tagname.match(startsWithXML) */; +} + +//this function returns the line number for the character at the given index +function getLineNumberForPosition(xmlData, index) { + const lines = xmlData.substring(0, index).split(/\r?\n/); + return { + line: lines.length, + + // column number is last line's length + 1, because column numbering starts at 1: + col: lines[lines.length - 1].length + 1 + }; +} + +//this function returns the position of the first character of match within attrStr +function getPositionFromMatch(match) { + return match.startIndex + match[1].length; +} diff --git a/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js b/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js new file mode 100644 index 0000000..2274dfa --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js @@ -0,0 +1,286 @@ +'use strict'; +//parse Empty Node as self closing node +const buildFromOrderedJs = require('./orderedJs2Xml'); +const getIgnoreAttributesFn = require('../ignoreAttributes') + +const defaultOptions = { + attributeNamePrefix: '@_', + attributesGroupName: false, + textNodeName: '#text', + ignoreAttributes: true, + cdataPropName: false, + format: false, + indentBy: ' ', + suppressEmptyNode: false, + suppressUnpairedNode: true, + suppressBooleanAttributes: true, + tagValueProcessor: function(key, a) { + return a; + }, + attributeValueProcessor: function(attrName, a) { + return a; + }, + preserveOrder: false, + commentPropName: false, + unpairedTags: [], + entities: [ + { regex: new RegExp("&", "g"), val: "&" },//it must be on top + { regex: new RegExp(">", "g"), val: ">" }, + { regex: new RegExp("<", "g"), val: "<" }, + { regex: new RegExp("\'", "g"), val: "'" }, + { regex: new RegExp("\"", "g"), val: """ } + ], + processEntities: true, + stopNodes: [], + // transformTagName: false, + // transformAttributeName: false, + oneListGroup: false +}; + +function Builder(options) { + this.options = Object.assign({}, defaultOptions, options); + if (this.options.ignoreAttributes === true || this.options.attributesGroupName) { + this.isAttribute = function(/*a*/) { + return false; + }; + } else { + this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes) + this.attrPrefixLen = this.options.attributeNamePrefix.length; + this.isAttribute = isAttribute; + } + + this.processTextOrObjNode = processTextOrObjNode + + if (this.options.format) { + this.indentate = indentate; + this.tagEndChar = '>\n'; + this.newLine = '\n'; + } else { + this.indentate = function() { + return ''; + }; + this.tagEndChar = '>'; + this.newLine = ''; + } +} + +Builder.prototype.build = function(jObj) { + if(this.options.preserveOrder){ + return buildFromOrderedJs(jObj, this.options); + }else { + if(Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1){ + jObj = { + [this.options.arrayNodeName] : jObj + } + } + return this.j2x(jObj, 0, []).val; + } +}; + +Builder.prototype.j2x = function(jObj, level, ajPath) { + let attrStr = ''; + let val = ''; + const jPath = ajPath.join('.') + for (let key in jObj) { + if(!Object.prototype.hasOwnProperty.call(jObj, key)) continue; + if (typeof jObj[key] === 'undefined') { + // supress undefined node only if it is not an attribute + if (this.isAttribute(key)) { + val += ''; + } + } else if (jObj[key] === null) { + // null attribute should be ignored by the attribute list, but should not cause the tag closing + if (this.isAttribute(key)) { + val += ''; + } else if (key === this.options.cdataPropName) { + val += ''; + } else if (key[0] === '?') { + val += this.indentate(level) + '<' + key + '?' + this.tagEndChar; + } else { + val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; + } + // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; + } else if (jObj[key] instanceof Date) { + val += this.buildTextValNode(jObj[key], key, '', level); + } else if (typeof jObj[key] !== 'object') { + //premitive type + const attr = this.isAttribute(key); + if (attr && !this.ignoreAttributesFn(attr, jPath)) { + attrStr += this.buildAttrPairStr(attr, '' + jObj[key]); + } else if (!attr) { + //tag value + if (key === this.options.textNodeName) { + let newval = this.options.tagValueProcessor(key, '' + jObj[key]); + val += this.replaceEntitiesValue(newval); + } else { + val += this.buildTextValNode(jObj[key], key, '', level); + } + } + } else if (Array.isArray(jObj[key])) { + //repeated nodes + const arrLen = jObj[key].length; + let listTagVal = ""; + let listTagAttr = ""; + for (let j = 0; j < arrLen; j++) { + const item = jObj[key][j]; + if (typeof item === 'undefined') { + // supress undefined node + } else if (item === null) { + if(key[0] === "?") val += this.indentate(level) + '<' + key + '?' + this.tagEndChar; + else val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; + // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; + } else if (typeof item === 'object') { + if(this.options.oneListGroup){ + const result = this.j2x(item, level + 1, ajPath.concat(key)); + listTagVal += result.val; + if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) { + listTagAttr += result.attrStr + } + }else{ + listTagVal += this.processTextOrObjNode(item, key, level, ajPath) + } + } else { + if (this.options.oneListGroup) { + let textValue = this.options.tagValueProcessor(key, item); + textValue = this.replaceEntitiesValue(textValue); + listTagVal += textValue; + } else { + listTagVal += this.buildTextValNode(item, key, '', level); + } + } + } + if(this.options.oneListGroup){ + listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level); + } + val += listTagVal; + } else { + //nested node + if (this.options.attributesGroupName && key === this.options.attributesGroupName) { + const Ks = Object.keys(jObj[key]); + const L = Ks.length; + for (let j = 0; j < L; j++) { + attrStr += this.buildAttrPairStr(Ks[j], '' + jObj[key][Ks[j]]); + } + } else { + val += this.processTextOrObjNode(jObj[key], key, level, ajPath) + } + } + } + return {attrStr: attrStr, val: val}; +}; + +Builder.prototype.buildAttrPairStr = function(attrName, val){ + val = this.options.attributeValueProcessor(attrName, '' + val); + val = this.replaceEntitiesValue(val); + if (this.options.suppressBooleanAttributes && val === "true") { + return ' ' + attrName; + } else return ' ' + attrName + '="' + val + '"'; +} + +function processTextOrObjNode (object, key, level, ajPath) { + const result = this.j2x(object, level + 1, ajPath.concat(key)); + if (object[this.options.textNodeName] !== undefined && Object.keys(object).length === 1) { + return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level); + } else { + return this.buildObjectNode(result.val, key, result.attrStr, level); + } +} + +Builder.prototype.buildObjectNode = function(val, key, attrStr, level) { + if(val === ""){ + if(key[0] === "?") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; + else { + return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar; + } + }else{ + + let tagEndExp = '' + val + tagEndExp ); + } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) { + return this.indentate(level) + `` + this.newLine; + }else { + return ( + this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar + + val + + this.indentate(level) + tagEndExp ); + } + } +} + +Builder.prototype.closeTag = function(key){ + let closeTag = ""; + if(this.options.unpairedTags.indexOf(key) !== -1){ //unpaired + if(!this.options.suppressUnpairedNode) closeTag = "/" + }else if(this.options.suppressEmptyNode){ //empty + closeTag = "/"; + }else{ + closeTag = `>` + this.newLine; + }else if (this.options.commentPropName !== false && key === this.options.commentPropName) { + return this.indentate(level) + `` + this.newLine; + }else if(key[0] === "?") {//PI tag + return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; + }else{ + let textValue = this.options.tagValueProcessor(key, val); + textValue = this.replaceEntitiesValue(textValue); + + if( textValue === ''){ + return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar; + }else{ + return this.indentate(level) + '<' + key + attrStr + '>' + + textValue + + ' 0 && this.options.processEntities){ + for (let i=0; i 0) { + indentation = EOL; + } + return arrToStr(jArray, options, "", indentation); +} + +function arrToStr(arr, options, jPath, indentation) { + let xmlStr = ""; + let isPreviousElementTag = false; + + for (let i = 0; i < arr.length; i++) { + const tagObj = arr[i]; + const tagName = propName(tagObj); + if(tagName === undefined) continue; + + let newJPath = ""; + if (jPath.length === 0) newJPath = tagName + else newJPath = `${jPath}.${tagName}`; + + if (tagName === options.textNodeName) { + let tagText = tagObj[tagName]; + if (!isStopNode(newJPath, options)) { + tagText = options.tagValueProcessor(tagName, tagText); + tagText = replaceEntitiesValue(tagText, options); + } + if (isPreviousElementTag) { + xmlStr += indentation; + } + xmlStr += tagText; + isPreviousElementTag = false; + continue; + } else if (tagName === options.cdataPropName) { + if (isPreviousElementTag) { + xmlStr += indentation; + } + xmlStr += ``; + isPreviousElementTag = false; + continue; + } else if (tagName === options.commentPropName) { + xmlStr += indentation + ``; + isPreviousElementTag = true; + continue; + } else if (tagName[0] === "?") { + const attStr = attr_to_str(tagObj[":@"], options); + const tempInd = tagName === "?xml" ? "" : indentation; + let piTextNodeName = tagObj[tagName][0][options.textNodeName]; + piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; //remove extra spacing + xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`; + isPreviousElementTag = true; + continue; + } + let newIdentation = indentation; + if (newIdentation !== "") { + newIdentation += options.indentBy; + } + const attStr = attr_to_str(tagObj[":@"], options); + const tagStart = indentation + `<${tagName}${attStr}`; + const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation); + if (options.unpairedTags.indexOf(tagName) !== -1) { + if (options.suppressUnpairedNode) xmlStr += tagStart + ">"; + else xmlStr += tagStart + "/>"; + } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) { + xmlStr += tagStart + "/>"; + } else if (tagValue && tagValue.endsWith(">")) { + xmlStr += tagStart + `>${tagValue}${indentation}`; + } else { + xmlStr += tagStart + ">"; + if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("`; + } + isPreviousElementTag = true; + } + + return xmlStr; +} + +function propName(obj) { + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if(!obj.hasOwnProperty(key)) continue; + if (key !== ":@") return key; + } +} + +function attr_to_str(attrMap, options) { + let attrStr = ""; + if (attrMap && !options.ignoreAttributes) { + for (let attr in attrMap) { + if(!attrMap.hasOwnProperty(attr)) continue; + let attrVal = options.attributeValueProcessor(attr, attrMap[attr]); + attrVal = replaceEntitiesValue(attrVal, options); + if (attrVal === true && options.suppressBooleanAttributes) { + attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`; + } else { + attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`; + } + } + } + return attrStr; +} + +function isStopNode(jPath, options) { + jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1); + let tagName = jPath.substr(jPath.lastIndexOf(".") + 1); + for (let index in options.stopNodes) { + if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true; + } + return false; +} + +function replaceEntitiesValue(textValue, options) { + if (textValue && textValue.length > 0 && options.processEntities) { + for (let i = 0; i < options.entities.length; i++) { + const entity = options.entities[i]; + textValue = textValue.replace(entity.regex, entity.val); + } + } + return textValue; +} +module.exports = toXml; diff --git a/node_modules/fast-xml-parser/src/xmlbuilder/prettifyJs2Xml.js b/node_modules/fast-xml-parser/src/xmlbuilder/prettifyJs2Xml.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js b/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js new file mode 100644 index 0000000..bfde18e --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js @@ -0,0 +1,153 @@ +const util = require('../util'); + +//TODO: handle comments +function readDocType(xmlData, i){ + + const entities = {}; + if( xmlData[i + 3] === 'O' && + xmlData[i + 4] === 'C' && + xmlData[i + 5] === 'T' && + xmlData[i + 6] === 'Y' && + xmlData[i + 7] === 'P' && + xmlData[i + 8] === 'E') + { + i = i+9; + let angleBracketsCount = 1; + let hasBody = false, comment = false; + let exp = ""; + for(;i') { //Read tag content + if(comment){ + if( xmlData[i - 1] === "-" && xmlData[i - 2] === "-"){ + comment = false; + angleBracketsCount--; + } + }else{ + angleBracketsCount--; + } + if (angleBracketsCount === 0) { + break; + } + }else if( xmlData[i] === '['){ + hasBody = true; + }else{ + exp += xmlData[i]; + } + } + if(angleBracketsCount !== 0){ + throw new Error(`Unclosed DOCTYPE`); + } + }else{ + throw new Error(`Invalid Tag instead of DOCTYPE`); + } + return {entities, i}; +} + +function readEntityExp(xmlData,i){ + //External entities are not supported + // + + //Parameter entities are not supported + // + + //Internal entities are supported + // + + //read EntityName + let entityName = ""; + for (; i < xmlData.length && (xmlData[i] !== "'" && xmlData[i] !== '"' ); i++) { + // if(xmlData[i] === " ") continue; + // else + entityName += xmlData[i]; + } + entityName = entityName.trim(); + if(entityName.indexOf(" ") !== -1) throw new Error("External entites are not supported"); + + //read Entity Value + const startChar = xmlData[i++]; + let val = "" + for (; i < xmlData.length && xmlData[i] !== startChar ; i++) { + val += xmlData[i]; + } + return [entityName, val, i]; +} + +function isComment(xmlData, i){ + if(xmlData[i+1] === '!' && + xmlData[i+2] === '-' && + xmlData[i+3] === '-') return true + return false +} +function isEntity(xmlData, i){ + if(xmlData[i+1] === '!' && + xmlData[i+2] === 'E' && + xmlData[i+3] === 'N' && + xmlData[i+4] === 'T' && + xmlData[i+5] === 'I' && + xmlData[i+6] === 'T' && + xmlData[i+7] === 'Y') return true + return false +} +function isElement(xmlData, i){ + if(xmlData[i+1] === '!' && + xmlData[i+2] === 'E' && + xmlData[i+3] === 'L' && + xmlData[i+4] === 'E' && + xmlData[i+5] === 'M' && + xmlData[i+6] === 'E' && + xmlData[i+7] === 'N' && + xmlData[i+8] === 'T') return true + return false +} + +function isAttlist(xmlData, i){ + if(xmlData[i+1] === '!' && + xmlData[i+2] === 'A' && + xmlData[i+3] === 'T' && + xmlData[i+4] === 'T' && + xmlData[i+5] === 'L' && + xmlData[i+6] === 'I' && + xmlData[i+7] === 'S' && + xmlData[i+8] === 'T') return true + return false +} +function isNotation(xmlData, i){ + if(xmlData[i+1] === '!' && + xmlData[i+2] === 'N' && + xmlData[i+3] === 'O' && + xmlData[i+4] === 'T' && + xmlData[i+5] === 'A' && + xmlData[i+6] === 'T' && + xmlData[i+7] === 'I' && + xmlData[i+8] === 'O' && + xmlData[i+9] === 'N') return true + return false +} + +function validateEntityName(name){ + if (util.isName(name)) + return name; + else + throw new Error(`Invalid entity name ${name}`); +} + +module.exports = readDocType; diff --git a/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js b/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js new file mode 100644 index 0000000..bca3776 --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js @@ -0,0 +1,48 @@ + +const defaultOptions = { + preserveOrder: false, + attributeNamePrefix: '@_', + attributesGroupName: false, + textNodeName: '#text', + ignoreAttributes: true, + removeNSPrefix: false, // remove NS from tag name or attribute name if true + allowBooleanAttributes: false, //a tag can have attributes without any value + //ignoreRootElement : false, + parseTagValue: true, + parseAttributeValue: false, + trimValues: true, //Trim string values of tag and attributes + cdataPropName: false, + numberParseOptions: { + hex: true, + leadingZeros: true, + eNotation: true + }, + tagValueProcessor: function(tagName, val) { + return val; + }, + attributeValueProcessor: function(attrName, val) { + return val; + }, + stopNodes: [], //nested tags will not be parsed even for errors + alwaysCreateTextNode: false, + isArray: () => false, + commentPropName: false, + unpairedTags: [], + processEntities: true, + htmlEntities: false, + ignoreDeclaration: false, + ignorePiTags: false, + transformTagName: false, + transformAttributeName: false, + updateTag: function(tagName, jPath, attrs){ + return tagName + }, + // skipEmptyListItem: false +}; + +const buildOptions = function(options) { + return Object.assign({}, defaultOptions, options); +}; + +exports.buildOptions = buildOptions; +exports.defaultOptions = defaultOptions; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js b/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js new file mode 100644 index 0000000..4f89003 --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js @@ -0,0 +1,606 @@ +'use strict'; +///@ts-check + +const util = require('../util'); +const xmlNode = require('./xmlNode'); +const readDocType = require("./DocTypeReader"); +const toNumber = require("strnum"); +const getIgnoreAttributesFn = require('../ignoreAttributes') + +// const regx = +// '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)' +// .replace(/NAME/g, util.nameRegexp); + +//const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g"); +//const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g"); + +class OrderedObjParser{ + constructor(options){ + this.options = options; + this.currentNode = null; + this.tagsNodeStack = []; + this.docTypeEntities = {}; + this.lastEntities = { + "apos" : { regex: /&(apos|#39|#x27);/g, val : "'"}, + "gt" : { regex: /&(gt|#62|#x3E);/g, val : ">"}, + "lt" : { regex: /&(lt|#60|#x3C);/g, val : "<"}, + "quot" : { regex: /&(quot|#34|#x22);/g, val : "\""}, + }; + this.ampEntity = { regex: /&(amp|#38|#x26);/g, val : "&"}; + this.htmlEntities = { + "space": { regex: /&(nbsp|#160);/g, val: " " }, + // "lt" : { regex: /&(lt|#60);/g, val: "<" }, + // "gt" : { regex: /&(gt|#62);/g, val: ">" }, + // "amp" : { regex: /&(amp|#38);/g, val: "&" }, + // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, + // "apos" : { regex: /&(apos|#39);/g, val: "'" }, + "cent" : { regex: /&(cent|#162);/g, val: "¢" }, + "pound" : { regex: /&(pound|#163);/g, val: "£" }, + "yen" : { regex: /&(yen|#165);/g, val: "¥" }, + "euro" : { regex: /&(euro|#8364);/g, val: "€" }, + "copyright" : { regex: /&(copy|#169);/g, val: "©" }, + "reg" : { regex: /&(reg|#174);/g, val: "®" }, + "inr" : { regex: /&(inr|#8377);/g, val: "₹" }, + "num_dec": { regex: /&#([0-9]{1,7});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 10)) }, + "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 16)) }, + }; + this.addExternalEntities = addExternalEntities; + this.parseXml = parseXml; + this.parseTextData = parseTextData; + this.resolveNameSpace = resolveNameSpace; + this.buildAttributesMap = buildAttributesMap; + this.isItStopNode = isItStopNode; + this.replaceEntitiesValue = replaceEntitiesValue; + this.readStopNodeData = readStopNodeData; + this.saveTextToParentTag = saveTextToParentTag; + this.addChild = addChild; + this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes) + } + +} + +function addExternalEntities(externalEntities){ + const entKeys = Object.keys(externalEntities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + this.lastEntities[ent] = { + regex: new RegExp("&"+ent+";","g"), + val : externalEntities[ent] + } + } +} + +/** + * @param {string} val + * @param {string} tagName + * @param {string} jPath + * @param {boolean} dontTrim + * @param {boolean} hasAttributes + * @param {boolean} isLeafNode + * @param {boolean} escapeEntities + */ +function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) { + if (val !== undefined) { + if (this.options.trimValues && !dontTrim) { + val = val.trim(); + } + if(val.length > 0){ + if(!escapeEntities) val = this.replaceEntitiesValue(val); + + const newval = this.options.tagValueProcessor(tagName, val, jPath, hasAttributes, isLeafNode); + if(newval === null || newval === undefined){ + //don't parse + return val; + }else if(typeof newval !== typeof val || newval !== val){ + //overwrite + return newval; + }else if(this.options.trimValues){ + return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions); + }else{ + const trimmedVal = val.trim(); + if(trimmedVal === val){ + return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions); + }else{ + return val; + } + } + } + } +} + +function resolveNameSpace(tagname) { + if (this.options.removeNSPrefix) { + const tags = tagname.split(':'); + const prefix = tagname.charAt(0) === '/' ? '/' : ''; + if (tags[0] === 'xmlns') { + return ''; + } + if (tags.length === 2) { + tagname = prefix + tags[1]; + } + } + return tagname; +} + +//TODO: change regex to capture NS +//const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm"); +const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm'); + +function buildAttributesMap(attrStr, jPath, tagName) { + if (this.options.ignoreAttributes !== true && typeof attrStr === 'string') { + // attrStr = attrStr.replace(/\r?\n/g, ' '); + //attrStr = attrStr || attrStr.trim(); + + const matches = util.getAllMatches(attrStr, attrsRegx); + const len = matches.length; //don't make it inline + const attrs = {}; + for (let i = 0; i < len; i++) { + const attrName = this.resolveNameSpace(matches[i][1]); + if (this.ignoreAttributesFn(attrName, jPath)) { + continue + } + let oldVal = matches[i][4]; + let aName = this.options.attributeNamePrefix + attrName; + if (attrName.length) { + if (this.options.transformAttributeName) { + aName = this.options.transformAttributeName(aName); + } + if(aName === "__proto__") aName = "#__proto__"; + if (oldVal !== undefined) { + if (this.options.trimValues) { + oldVal = oldVal.trim(); + } + oldVal = this.replaceEntitiesValue(oldVal); + const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath); + if(newVal === null || newVal === undefined){ + //don't parse + attrs[aName] = oldVal; + }else if(typeof newVal !== typeof oldVal || newVal !== oldVal){ + //overwrite + attrs[aName] = newVal; + }else{ + //parse + attrs[aName] = parseValue( + oldVal, + this.options.parseAttributeValue, + this.options.numberParseOptions + ); + } + } else if (this.options.allowBooleanAttributes) { + attrs[aName] = true; + } + } + } + if (!Object.keys(attrs).length) { + return; + } + if (this.options.attributesGroupName) { + const attrCollection = {}; + attrCollection[this.options.attributesGroupName] = attrs; + return attrCollection; + } + return attrs + } +} + +const parseXml = function(xmlData) { + xmlData = xmlData.replace(/\r\n?/g, "\n"); //TODO: remove this line + const xmlObj = new xmlNode('!xml'); + let currentNode = xmlObj; + let textData = ""; + let jPath = ""; + for(let i=0; i< xmlData.length; i++){//for each char in XML data + const ch = xmlData[i]; + if(ch === '<'){ + // const nextIndex = i+1; + // const _2ndChar = xmlData[nextIndex]; + if( xmlData[i+1] === '/') {//Closing Tag + const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.") + let tagName = xmlData.substring(i+2,closeIndex).trim(); + + if(this.options.removeNSPrefix){ + const colonIndex = tagName.indexOf(":"); + if(colonIndex !== -1){ + tagName = tagName.substr(colonIndex+1); + } + } + + if(this.options.transformTagName) { + tagName = this.options.transformTagName(tagName); + } + + if(currentNode){ + textData = this.saveTextToParentTag(textData, currentNode, jPath); + } + + //check if last tag of nested tag was unpaired tag + const lastTagName = jPath.substring(jPath.lastIndexOf(".")+1); + if(tagName && this.options.unpairedTags.indexOf(tagName) !== -1 ){ + throw new Error(`Unpaired tag can not be used as closing tag: `); + } + let propIndex = 0 + if(lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1 ){ + propIndex = jPath.lastIndexOf('.', jPath.lastIndexOf('.')-1) + this.tagsNodeStack.pop(); + }else{ + propIndex = jPath.lastIndexOf("."); + } + jPath = jPath.substring(0, propIndex); + + currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope + textData = ""; + i = closeIndex; + } else if( xmlData[i+1] === '?') { + + let tagData = readTagExp(xmlData,i, false, "?>"); + if(!tagData) throw new Error("Pi Tag is not closed."); + + textData = this.saveTextToParentTag(textData, currentNode, jPath); + if( (this.options.ignoreDeclaration && tagData.tagName === "?xml") || this.options.ignorePiTags){ + + }else{ + + const childNode = new xmlNode(tagData.tagName); + childNode.add(this.options.textNodeName, ""); + + if(tagData.tagName !== tagData.tagExp && tagData.attrExpPresent){ + childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName); + } + this.addChild(currentNode, childNode, jPath) + + } + + + i = tagData.closeIndex + 1; + } else if(xmlData.substr(i + 1, 3) === '!--') { + const endIndex = findClosingIndex(xmlData, "-->", i+4, "Comment is not closed.") + if(this.options.commentPropName){ + const comment = xmlData.substring(i + 4, endIndex - 2); + + textData = this.saveTextToParentTag(textData, currentNode, jPath); + + currentNode.add(this.options.commentPropName, [ { [this.options.textNodeName] : comment } ]); + } + i = endIndex; + } else if( xmlData.substr(i + 1, 2) === '!D') { + const result = readDocType(xmlData, i); + this.docTypeEntities = result.entities; + i = result.i; + }else if(xmlData.substr(i + 1, 2) === '![') { + const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2; + const tagExp = xmlData.substring(i + 9,closeIndex); + + textData = this.saveTextToParentTag(textData, currentNode, jPath); + + let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true); + if(val == undefined) val = ""; + + //cdata should be set even if it is 0 length string + if(this.options.cdataPropName){ + currentNode.add(this.options.cdataPropName, [ { [this.options.textNodeName] : tagExp } ]); + }else{ + currentNode.add(this.options.textNodeName, val); + } + + i = closeIndex + 2; + }else {//Opening tag + let result = readTagExp(xmlData,i, this.options.removeNSPrefix); + let tagName= result.tagName; + const rawTagName = result.rawTagName; + let tagExp = result.tagExp; + let attrExpPresent = result.attrExpPresent; + let closeIndex = result.closeIndex; + + if (this.options.transformTagName) { + tagName = this.options.transformTagName(tagName); + } + + //save text as child node + if (currentNode && textData) { + if(currentNode.tagname !== '!xml'){ + //when nested tag is found + textData = this.saveTextToParentTag(textData, currentNode, jPath, false); + } + } + + //check if last tag was unpaired tag + const lastTag = currentNode; + if(lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1 ){ + currentNode = this.tagsNodeStack.pop(); + jPath = jPath.substring(0, jPath.lastIndexOf(".")); + } + if(tagName !== xmlObj.tagname){ + jPath += jPath ? "." + tagName : tagName; + } + if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) { + let tagContent = ""; + //self-closing tag + if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){ + if(tagName[tagName.length - 1] === "/"){ //remove trailing '/' + tagName = tagName.substr(0, tagName.length - 1); + jPath = jPath.substr(0, jPath.length - 1); + tagExp = tagName; + }else{ + tagExp = tagExp.substr(0, tagExp.length - 1); + } + i = result.closeIndex; + } + //unpaired tag + else if(this.options.unpairedTags.indexOf(tagName) !== -1){ + + i = result.closeIndex; + } + //normal tag + else{ + //read until closing tag is found + const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1); + if(!result) throw new Error(`Unexpected end of ${rawTagName}`); + i = result.i; + tagContent = result.tagContent; + } + + const childNode = new xmlNode(tagName); + if(tagName !== tagExp && attrExpPresent){ + childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + } + if(tagContent) { + tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true); + } + + jPath = jPath.substr(0, jPath.lastIndexOf(".")); + childNode.add(this.options.textNodeName, tagContent); + + this.addChild(currentNode, childNode, jPath) + }else{ + //selfClosing tag + if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){ + if(tagName[tagName.length - 1] === "/"){ //remove trailing '/' + tagName = tagName.substr(0, tagName.length - 1); + jPath = jPath.substr(0, jPath.length - 1); + tagExp = tagName; + }else{ + tagExp = tagExp.substr(0, tagExp.length - 1); + } + + if(this.options.transformTagName) { + tagName = this.options.transformTagName(tagName); + } + + const childNode = new xmlNode(tagName); + if(tagName !== tagExp && attrExpPresent){ + childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + } + this.addChild(currentNode, childNode, jPath) + jPath = jPath.substr(0, jPath.lastIndexOf(".")); + } + //opening tag + else{ + const childNode = new xmlNode( tagName); + this.tagsNodeStack.push(currentNode); + + if(tagName !== tagExp && attrExpPresent){ + childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + } + this.addChild(currentNode, childNode, jPath) + currentNode = childNode; + } + textData = ""; + i = closeIndex; + } + } + }else{ + textData += xmlData[i]; + } + } + return xmlObj.child; +} + +function addChild(currentNode, childNode, jPath){ + const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]) + if(result === false){ + }else if(typeof result === "string"){ + childNode.tagname = result + currentNode.addChild(childNode); + }else{ + currentNode.addChild(childNode); + } +} + +const replaceEntitiesValue = function(val){ + + if(this.options.processEntities){ + for(let entityName in this.docTypeEntities){ + const entity = this.docTypeEntities[entityName]; + val = val.replace( entity.regx, entity.val); + } + for(let entityName in this.lastEntities){ + const entity = this.lastEntities[entityName]; + val = val.replace( entity.regex, entity.val); + } + if(this.options.htmlEntities){ + for(let entityName in this.htmlEntities){ + const entity = this.htmlEntities[entityName]; + val = val.replace( entity.regex, entity.val); + } + } + val = val.replace( this.ampEntity.regex, this.ampEntity.val); + } + return val; +} +function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) { + if (textData) { //store previously collected data as textNode + if(isLeafNode === undefined) isLeafNode = currentNode.child.length === 0 + + textData = this.parseTextData(textData, + currentNode.tagname, + jPath, + false, + currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false, + isLeafNode); + + if (textData !== undefined && textData !== "") + currentNode.add(this.options.textNodeName, textData); + textData = ""; + } + return textData; +} + +//TODO: use jPath to simplify the logic +/** + * + * @param {string[]} stopNodes + * @param {string} jPath + * @param {string} currentTagName + */ +function isItStopNode(stopNodes, jPath, currentTagName){ + const allNodesExp = "*." + currentTagName; + for (const stopNodePath in stopNodes) { + const stopNodeExp = stopNodes[stopNodePath]; + if( allNodesExp === stopNodeExp || jPath === stopNodeExp ) return true; + } + return false; +} + +/** + * Returns the tag Expression and where it is ending handling single-double quotes situation + * @param {string} xmlData + * @param {number} i starting index + * @returns + */ +function tagExpWithClosingIndex(xmlData, i, closingChar = ">"){ + let attrBoundary; + let tagExp = ""; + for (let index = i; index < xmlData.length; index++) { + let ch = xmlData[index]; + if (attrBoundary) { + if (ch === attrBoundary) attrBoundary = "";//reset + } else if (ch === '"' || ch === "'") { + attrBoundary = ch; + } else if (ch === closingChar[0]) { + if(closingChar[1]){ + if(xmlData[index + 1] === closingChar[1]){ + return { + data: tagExp, + index: index + } + } + }else{ + return { + data: tagExp, + index: index + } + } + } else if (ch === '\t') { + ch = " " + } + tagExp += ch; + } +} + +function findClosingIndex(xmlData, str, i, errMsg){ + const closingIndex = xmlData.indexOf(str, i); + if(closingIndex === -1){ + throw new Error(errMsg) + }else{ + return closingIndex + str.length - 1; + } +} + +function readTagExp(xmlData,i, removeNSPrefix, closingChar = ">"){ + const result = tagExpWithClosingIndex(xmlData, i+1, closingChar); + if(!result) return; + let tagExp = result.data; + const closeIndex = result.index; + const separatorIndex = tagExp.search(/\s/); + let tagName = tagExp; + let attrExpPresent = true; + if(separatorIndex !== -1){//separate tag name and attributes expression + tagName = tagExp.substring(0, separatorIndex); + tagExp = tagExp.substring(separatorIndex + 1).trimStart(); + } + + const rawTagName = tagName; + if(removeNSPrefix){ + const colonIndex = tagName.indexOf(":"); + if(colonIndex !== -1){ + tagName = tagName.substr(colonIndex+1); + attrExpPresent = tagName !== result.data.substr(colonIndex + 1); + } + } + + return { + tagName: tagName, + tagExp: tagExp, + closeIndex: closeIndex, + attrExpPresent: attrExpPresent, + rawTagName: rawTagName, + } +} +/** + * find paired tag for a stop node + * @param {string} xmlData + * @param {string} tagName + * @param {number} i + */ +function readStopNodeData(xmlData, tagName, i){ + const startIndex = i; + // Starting at 1 since we already have an open tag + let openTagCount = 1; + + for (; i < xmlData.length; i++) { + if( xmlData[i] === "<"){ + if (xmlData[i+1] === "/") {//close tag + const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`); + let closeTagName = xmlData.substring(i+2,closeIndex).trim(); + if(closeTagName === tagName){ + openTagCount--; + if (openTagCount === 0) { + return { + tagContent: xmlData.substring(startIndex, i), + i : closeIndex + } + } + } + i=closeIndex; + } else if(xmlData[i+1] === '?') { + const closeIndex = findClosingIndex(xmlData, "?>", i+1, "StopNode is not closed.") + i=closeIndex; + } else if(xmlData.substr(i + 1, 3) === '!--') { + const closeIndex = findClosingIndex(xmlData, "-->", i+3, "StopNode is not closed.") + i=closeIndex; + } else if(xmlData.substr(i + 1, 2) === '![') { + const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2; + i=closeIndex; + } else { + const tagData = readTagExp(xmlData, i, '>') + + if (tagData) { + const openTagName = tagData && tagData.tagName; + if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== "/") { + openTagCount++; + } + i=tagData.closeIndex; + } + } + } + }//end for loop +} + +function parseValue(val, shouldParse, options) { + if (shouldParse && typeof val === 'string') { + //console.log(options) + const newval = val.trim(); + if(newval === 'true' ) return true; + else if(newval === 'false' ) return false; + else return toNumber(val, options); + } else { + if (util.isExist(val)) { + return val; + } else { + return ''; + } + } +} + + +module.exports = OrderedObjParser; diff --git a/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js b/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js new file mode 100644 index 0000000..ffaf59b --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js @@ -0,0 +1,58 @@ +const { buildOptions} = require("./OptionsBuilder"); +const OrderedObjParser = require("./OrderedObjParser"); +const { prettify} = require("./node2json"); +const validator = require('../validator'); + +class XMLParser{ + + constructor(options){ + this.externalEntities = {}; + this.options = buildOptions(options); + + } + /** + * Parse XML dats to JS object + * @param {string|Buffer} xmlData + * @param {boolean|Object} validationOption + */ + parse(xmlData,validationOption){ + if(typeof xmlData === "string"){ + }else if( xmlData.toString){ + xmlData = xmlData.toString(); + }else{ + throw new Error("XML data is accepted in String or Bytes[] form.") + } + if( validationOption){ + if(validationOption === true) validationOption = {}; //validate with default options + + const result = validator.validate(xmlData, validationOption); + if (result !== true) { + throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` ) + } + } + const orderedObjParser = new OrderedObjParser(this.options); + orderedObjParser.addExternalEntities(this.externalEntities); + const orderedResult = orderedObjParser.parseXml(xmlData); + if(this.options.preserveOrder || orderedResult === undefined) return orderedResult; + else return prettify(orderedResult, this.options); + } + + /** + * Add Entity which is not by default supported by this library + * @param {string} key + * @param {string} value + */ + addEntity(key, value){ + if(value.indexOf("&") !== -1){ + throw new Error("Entity value can't have '&'") + }else if(key.indexOf("&") !== -1 || key.indexOf(";") !== -1){ + throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '") + }else if(value === "&"){ + throw new Error("An entity with value '&' is not permitted"); + }else{ + this.externalEntities[key] = value; + } + } +} + +module.exports = XMLParser; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/xmlparser/node2json.js b/node_modules/fast-xml-parser/src/xmlparser/node2json.js new file mode 100644 index 0000000..3045573 --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlparser/node2json.js @@ -0,0 +1,113 @@ +'use strict'; + +/** + * + * @param {array} node + * @param {any} options + * @returns + */ +function prettify(node, options){ + return compress( node, options); +} + +/** + * + * @param {array} arr + * @param {object} options + * @param {string} jPath + * @returns object + */ +function compress(arr, options, jPath){ + let text; + const compressedObj = {}; + for (let i = 0; i < arr.length; i++) { + const tagObj = arr[i]; + const property = propName(tagObj); + let newJpath = ""; + if(jPath === undefined) newJpath = property; + else newJpath = jPath + "." + property; + + if(property === options.textNodeName){ + if(text === undefined) text = tagObj[property]; + else text += "" + tagObj[property]; + }else if(property === undefined){ + continue; + }else if(tagObj[property]){ + + let val = compress(tagObj[property], options, newJpath); + const isLeaf = isLeafTag(val, options); + + if(tagObj[":@"]){ + assignAttributes( val, tagObj[":@"], newJpath, options); + }else if(Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode){ + val = val[options.textNodeName]; + }else if(Object.keys(val).length === 0){ + if(options.alwaysCreateTextNode) val[options.textNodeName] = ""; + else val = ""; + } + + if(compressedObj[property] !== undefined && compressedObj.hasOwnProperty(property)) { + if(!Array.isArray(compressedObj[property])) { + compressedObj[property] = [ compressedObj[property] ]; + } + compressedObj[property].push(val); + }else{ + //TODO: if a node is not an array, then check if it should be an array + //also determine if it is a leaf node + if (options.isArray(property, newJpath, isLeaf )) { + compressedObj[property] = [val]; + }else{ + compressedObj[property] = val; + } + } + } + + } + // if(text && text.length > 0) compressedObj[options.textNodeName] = text; + if(typeof text === "string"){ + if(text.length > 0) compressedObj[options.textNodeName] = text; + }else if(text !== undefined) compressedObj[options.textNodeName] = text; + return compressedObj; +} + +function propName(obj){ + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if(key !== ":@") return key; + } +} + +function assignAttributes(obj, attrMap, jpath, options){ + if (attrMap) { + const keys = Object.keys(attrMap); + const len = keys.length; //don't make it inline + for (let i = 0; i < len; i++) { + const atrrName = keys[i]; + if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) { + obj[atrrName] = [ attrMap[atrrName] ]; + } else { + obj[atrrName] = attrMap[atrrName]; + } + } + } +} + +function isLeafTag(obj, options){ + const { textNodeName } = options; + const propCount = Object.keys(obj).length; + + if (propCount === 0) { + return true; + } + + if ( + propCount === 1 && + (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0) + ) { + return true; + } + + return false; +} +exports.prettify = prettify; diff --git a/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js b/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js new file mode 100644 index 0000000..9319524 --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js @@ -0,0 +1,25 @@ +'use strict'; + +class XmlNode{ + constructor(tagname) { + this.tagname = tagname; + this.child = []; //nested tags, text, cdata, comments in order + this[":@"] = {}; //attributes map + } + add(key,val){ + // this.child.push( {name : key, val: val, isCdata: isCdata }); + if(key === "__proto__") key = "#__proto__"; + this.child.push( {[key]: val }); + } + addChild(node) { + if(node.tagname === "__proto__") node.tagname = "#__proto__"; + if(node[":@"] && Object.keys(node[":@"]).length > 0){ + this.child.push( { [node.tagname]: node.child, [":@"]: node[":@"] }); + }else{ + this.child.push( { [node.tagname]: node.child }); + } + }; +}; + + +module.exports = XmlNode; \ No newline at end of file diff --git a/node_modules/faye-websocket/CHANGELOG.md b/node_modules/faye-websocket/CHANGELOG.md new file mode 100644 index 0000000..b152afe --- /dev/null +++ b/node_modules/faye-websocket/CHANGELOG.md @@ -0,0 +1,139 @@ +### 0.11.4 / 2021-05-24 + +- Prevent the client hanging if `close()` is called when already closing + +### 0.11.3 / 2019-06-10 + +- Fix a race condition that caused a timeout not to be cancelled immediately + when the WebSocket is closed +- Change license from MIT to Apache 2.0 + +### 0.11.2 / 2019-06-10 + +(This version was pulled due to an error when publishing) + +### 0.11.1 / 2017-01-22 + +- Forcibly close the I/O stream after a timeout if the peer does not respond + after calling `close()` + +### 0.11.0 / 2016-02-24 + +- Introduce a `net` option to the `Client` class for setting things like, say, + `servername` + +### 0.10.0 / 2015-07-08 + +- Add the standard `code` and `reason` parameters to the `close` method + +### 0.9.4 / 2015-03-08 + +- Don't send input to the driver before `start()` is called + +### 0.9.3 / 2015-02-19 + +- Make sure the TCP socket is not left open when closing the connection + +### 0.9.2 / 2014-12-21 + +- Only emit `error` once, and don't emit it after `close` + +### 0.9.1 / 2014-12-18 + +- Check that all options to the WebSocket constructor are recognized + +### 0.9.0 / 2014-12-13 + +- Allow protocol extensions to be passed into websocket-extensions + +### 0.8.1 / 2014-11-12 + +- Send the correct hostname when upgrading a connection to TLS + +### 0.8.0 / 2014-11-08 + +- Support connections via HTTP proxies +- Close the connection cleanly if we're still waiting for a handshake response + +### 0.7.3 / 2014-10-04 + +- Allow sockets to be closed when they are in any state other than `CLOSED` + +### 0.7.2 / 2013-12-29 + +- Make sure the `close` event is emitted by clients on Node v0.10 + +### 0.7.1 / 2013-12-03 + +- Support the `maxLength` websocket-driver option +- Make the client emit `error` events on network errors + +### 0.7.0 / 2013-09-09 + +- Allow the server to send custom headers with EventSource responses + +### 0.6.1 / 2013-07-05 + +- Add `ca` option to the client for specifying certificate authorities +- Start the server driver asynchronously so that `onopen` handlers can be added + +### 0.6.0 / 2013-05-12 + +- Add support for custom headers + +### 0.5.0 / 2013-05-05 + +- Extract the protocol handlers into the `websocket-driver` library +- Support the Node streaming API + +### 0.4.4 / 2013-02-14 + +- Emit the `close` event if TCP is closed before CLOSE frame is acked + +### 0.4.3 / 2012-07-09 + +- Add `Connection: close` to EventSource response +- Handle situations where `request.socket` is undefined + +### 0.4.2 / 2012-04-06 + +- Add WebSocket error code `1011`. +- Handle URLs with no path correctly by sending `GET /` + +### 0.4.1 / 2012-02-26 + +- Treat anything other than a `Buffer` as a string when calling `send()` + +### 0.4.0 / 2012-02-13 + +- Add `ping()` method to server-side `WebSocket` and `EventSource` +- Buffer `send()` calls until the draft-76 handshake is complete +- Fix HTTPS problems on Node 0.7 + +### 0.3.1 / 2012-01-16 + +- Call `setNoDelay(true)` on `net.Socket` objects to reduce latency + +### 0.3.0 / 2012-01-13 + +- Add support for `EventSource` connections + +### 0.2.0 / 2011-12-21 + +- Add support for `Sec-WebSocket-Protocol` negotiation +- Support `hixie-76` close frames and 75/76 ignored segments +- Improve performance of HyBi parsing/framing functions +- Decouple parsers from TCP and reduce write volume + +### 0.1.2 / 2011-12-05 + +- Detect closed sockets on the server side when TCP connection breaks +- Make `hixie-76` sockets work through HAProxy + +### 0.1.1 / 2011-11-30 + +- Fix `addEventListener()` interface methods + +### 0.1.0 / 2011-11-27 + +- Initial release, based on WebSocket components from Faye diff --git a/node_modules/faye-websocket/LICENSE.md b/node_modules/faye-websocket/LICENSE.md new file mode 100644 index 0000000..1b47ee5 --- /dev/null +++ b/node_modules/faye-websocket/LICENSE.md @@ -0,0 +1,12 @@ +Copyright 2010-2021 James Coglan + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. diff --git a/node_modules/faye-websocket/README.md b/node_modules/faye-websocket/README.md new file mode 100644 index 0000000..f62e1b5 --- /dev/null +++ b/node_modules/faye-websocket/README.md @@ -0,0 +1,311 @@ +# faye-websocket + +This is a general-purpose WebSocket implementation extracted from the +[Faye](http://faye.jcoglan.com) project. It provides classes for easily building +WebSocket servers and clients in Node. It does not provide a server itself, but +rather makes it easy to handle WebSocket connections within an existing +[Node](https://nodejs.org/) application. It does not provide any abstraction +other than the standard [WebSocket +API](https://html.spec.whatwg.org/multipage/comms.html#network). + +It also provides an abstraction for handling +[EventSource](https://html.spec.whatwg.org/multipage/comms.html#server-sent-events) +connections, which are one-way connections that allow the server to push data to +the client. They are based on streaming HTTP responses and can be easier to access +via proxies than WebSockets. + + +## Installation + +``` +$ npm install faye-websocket +``` + + +## Handling WebSocket connections in Node + +You can handle WebSockets on the server side by listening for HTTP Upgrade +requests, and creating a new socket for the request. This socket object exposes +the usual WebSocket methods for receiving and sending messages. For example this +is how you'd implement an echo server: + +```js +var WebSocket = require('faye-websocket'), + http = require('http'); + +var server = http.createServer(); + +server.on('upgrade', function(request, socket, body) { + if (WebSocket.isWebSocket(request)) { + var ws = new WebSocket(request, socket, body); + + ws.on('message', function(event) { + ws.send(event.data); + }); + + ws.on('close', function(event) { + console.log('close', event.code, event.reason); + ws = null; + }); + } +}); + +server.listen(8000); +``` + +`WebSocket` objects are also duplex streams, so you could replace the +`ws.on('message', ...)` line with: + +```js + ws.pipe(ws); +``` + +Note that under certain circumstances (notably a draft-76 client connecting +through an HTTP proxy), the WebSocket handshake will not be complete after you +call `new WebSocket()` because the server will not have received the entire +handshake from the client yet. In this case, calls to `ws.send()` will buffer +the message in memory until the handshake is complete, at which point any +buffered messages will be sent to the client. + +If you need to detect when the WebSocket handshake is complete, you can use the +`onopen` event. + +If the connection's protocol version supports it, you can call `ws.ping()` to +send a ping message and wait for the client's response. This method takes a +message string, and an optional callback that fires when a matching pong message +is received. It returns `true` if and only if a ping message was sent. If the +client does not support ping/pong, this method sends no data and returns +`false`. + +```js +ws.ping('Mic check, one, two', function() { + // fires when pong is received +}); +``` + + +## Using the WebSocket client + +The client supports both the plain-text `ws` protocol and the encrypted `wss` +protocol, and has exactly the same interface as a socket you would use in a web +browser. On the wire it identifies itself as `hybi-13`. + +```js +var WebSocket = require('faye-websocket'), + ws = new WebSocket.Client('ws://www.example.com/'); + +ws.on('open', function(event) { + console.log('open'); + ws.send('Hello, world!'); +}); + +ws.on('message', function(event) { + console.log('message', event.data); +}); + +ws.on('close', function(event) { + console.log('close', event.code, event.reason); + ws = null; +}); +``` + +The WebSocket client also lets you inspect the status and headers of the +handshake response via its `statusCode` and `headers` properties. + +To connect via a proxy, set the `proxy` option to the HTTP origin of the proxy, +including any authorization information, custom headers and TLS config you +require. Only the `origin` setting is required. + +```js +var ws = new WebSocket.Client('ws://www.example.com/', [], { + proxy: { + origin: 'http://username:password@proxy.example.com', + headers: { 'User-Agent': 'node' }, + tls: { cert: fs.readFileSync('client.crt') } + } +}); +``` + +The `tls` value is an object that will be passed to +[`tls.connect()`](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback). + + +## Subprotocol negotiation + +The WebSocket protocol allows peers to select and identify the application +protocol to use over the connection. On the client side, you can set which +protocols the client accepts by passing a list of protocol names when you +construct the socket: + +```js +var ws = new WebSocket.Client('ws://www.example.com/', ['irc', 'amqp']); +``` + +On the server side, you can likewise pass in the list of protocols the server +supports after the other constructor arguments: + +```js +var ws = new WebSocket(request, socket, body, ['irc', 'amqp']); +``` + +If the client and server agree on a protocol, both the client- and server-side +socket objects expose the selected protocol through the `ws.protocol` property. + + +## Protocol extensions + +faye-websocket is based on the +[websocket-extensions](https://github.com/faye/websocket-extensions-node) +framework that allows extensions to be negotiated via the +`Sec-WebSocket-Extensions` header. To add extensions to a connection, pass an +array of extensions to the `:extensions` option. For example, to add +[permessage-deflate](https://github.com/faye/permessage-deflate-node): + +```js +var deflate = require('permessage-deflate'); + +var ws = new WebSocket(request, socket, body, [], { extensions: [deflate] }); +``` + + +## Initialization options + +Both the server- and client-side classes allow an options object to be passed in +at initialization time, for example: + +```js +var ws = new WebSocket(request, socket, body, protocols, options); +var ws = new WebSocket.Client(url, protocols, options); +``` + +`protocols` is an array of subprotocols as described above, or `null`. +`options` is an optional object containing any of these fields: + +- `extensions` - an array of + [websocket-extensions](https://github.com/faye/websocket-extensions-node) + compatible extensions, as described above +- `headers` - an object containing key-value pairs representing HTTP headers to + be sent during the handshake process +- `maxLength` - the maximum allowed size of incoming message frames, in bytes. + The default value is `2^26 - 1`, or 1 byte short of 64 MiB. +- `ping` - an integer that sets how often the WebSocket should send ping frames, + measured in seconds + +The client accepts some additional options: + +- `proxy` - settings for a proxy as described above +- `net` - an object containing settings for the origin server that will be + passed to + [`net.connect()`](https://nodejs.org/api/net.html#net_socket_connect_options_connectlistener) +- `tls` - an object containing TLS settings for the origin server, this will be + passed to + [`tls.connect()`](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback) +- `ca` - (legacy) a shorthand for passing `{ tls: { ca: value } }` + + +## WebSocket API + +Both server- and client-side `WebSocket` objects support the following API. + +- **`on('open', function(event) {})`** fires when the socket connection is + established. Event has no attributes. +- **`on('message', function(event) {})`** fires when the socket receives a + message. Event has one attribute, **`data`**, which is either a `String` (for + text frames) or a `Buffer` (for binary frames). +- **`on('error', function(event) {})`** fires when there is a protocol error due + to bad data sent by the other peer. This event is purely informational, you do + not need to implement error recover. +- **`on('close', function(event) {})`** fires when either the client or the + server closes the connection. Event has two optional attributes, **`code`** + and **`reason`**, that expose the status code and message sent by the peer + that closed the connection. +- **`send(message)`** accepts either a `String` or a `Buffer` and sends a text + or binary message over the connection to the other peer. +- **`ping(message, function() {})`** sends a ping frame with an optional message + and fires the callback when a matching pong is received. +- **`close(code, reason)`** closes the connection, sending the given status code + and reason text, both of which are optional. +- **`version`** is a string containing the version of the `WebSocket` protocol + the connection is using. +- **`protocol`** is a string (which may be empty) identifying the subprotocol + the socket is using. + + +## Handling EventSource connections in Node + +EventSource connections provide a very similar interface, although because they +only allow the server to send data to the client, there is no `onmessage` API. +EventSource allows the server to push text messages to the client, where each +message has an optional event-type and ID. + +```js +var WebSocket = require('faye-websocket'), + EventSource = WebSocket.EventSource, + http = require('http'); + +var server = http.createServer(); + +server.on('request', function(request, response) { + if (EventSource.isEventSource(request)) { + var es = new EventSource(request, response); + console.log('open', es.url, es.lastEventId); + + // Periodically send messages + var loop = setInterval(function() { es.send('Hello') }, 1000); + + es.on('close', function() { + clearInterval(loop); + es = null; + }); + + } else { + // Normal HTTP request + response.writeHead(200, { 'Content-Type': 'text/plain' }); + response.end('Hello'); + } +}); + +server.listen(8000); +``` + +The `send` method takes two optional parameters, `event` and `id`. The default +event-type is `'message'` with no ID. For example, to send a `notification` +event with ID `99`: + +```js +es.send('Breaking News!', { event: 'notification', id: '99' }); +``` + +The `EventSource` object exposes the following properties: + +- **`url`** is a string containing the URL the client used to create the + EventSource. +- **`lastEventId`** is a string containing the last event ID received by the + client. You can use this when the client reconnects after a dropped connection + to determine which messages need resending. + +When you initialize an EventSource with ` new EventSource()`, you can pass +configuration options after the `response` parameter. Available options are: + +- **`headers`** is an object containing custom headers to be set on the + EventSource response. +- **`retry`** is a number that tells the client how long (in seconds) it should + wait after a dropped connection before attempting to reconnect. +- **`ping`** is a number that tells the server how often (in seconds) to send + 'ping' packets to the client to keep the connection open, to defeat timeouts + set by proxies. The client will ignore these messages. + +For example, this creates a connection that allows access from any origin, pings +every 15 seconds and is retryable every 10 seconds if the connection is broken: + +```js +var es = new EventSource(request, response, { + headers: { 'Access-Control-Allow-Origin': '*' }, + ping: 15, + retry: 10 +}); +``` + +You can send a ping message at any time by calling `es.ping()`. Unlike +WebSocket, the client does not send a response to this; it is merely to send +some data over the wire to keep the connection alive. diff --git a/node_modules/faye-websocket/lib/faye/eventsource.js b/node_modules/faye-websocket/lib/faye/eventsource.js new file mode 100644 index 0000000..4af9d9d --- /dev/null +++ b/node_modules/faye-websocket/lib/faye/eventsource.js @@ -0,0 +1,133 @@ +'use strict'; + +var Stream = require('stream').Stream, + util = require('util'), + driver = require('websocket-driver'), + Headers = require('websocket-driver/lib/websocket/driver/headers'), + API = require('./websocket/api'), + EventTarget = require('./websocket/api/event_target'), + Event = require('./websocket/api/event'); + +var EventSource = function(request, response, options) { + this.writable = true; + options = options || {}; + + this._stream = response.socket; + this._ping = options.ping || this.DEFAULT_PING; + this._retry = options.retry || this.DEFAULT_RETRY; + + var scheme = driver.isSecureRequest(request) ? 'https:' : 'http:'; + this.url = scheme + '//' + request.headers.host + request.url; + this.lastEventId = request.headers['last-event-id'] || ''; + this.readyState = API.CONNECTING; + + var headers = new Headers(), + self = this; + + if (options.headers) { + for (var key in options.headers) headers.set(key, options.headers[key]); + } + + if (!this._stream || !this._stream.writable) return; + process.nextTick(function() { self._open() }); + + this._stream.setTimeout(0); + this._stream.setNoDelay(true); + + var handshake = 'HTTP/1.1 200 OK\r\n' + + 'Content-Type: text/event-stream\r\n' + + 'Cache-Control: no-cache, no-store\r\n' + + 'Connection: close\r\n' + + headers.toString() + + '\r\n' + + 'retry: ' + Math.floor(this._retry * 1000) + '\r\n\r\n'; + + this._write(handshake); + + this._stream.on('drain', function() { self.emit('drain') }); + + if (this._ping) + this._pingTimer = setInterval(function() { self.ping() }, this._ping * 1000); + + ['error', 'end'].forEach(function(event) { + self._stream.on(event, function() { self.close() }); + }); +}; +util.inherits(EventSource, Stream); + +EventSource.isEventSource = function(request) { + if (request.method !== 'GET') return false; + var accept = (request.headers.accept || '').split(/\s*,\s*/); + return accept.indexOf('text/event-stream') >= 0; +}; + +var instance = { + DEFAULT_PING: 10, + DEFAULT_RETRY: 5, + + _write: function(chunk) { + if (!this.writable) return false; + try { + return this._stream.write(chunk, 'utf8'); + } catch (e) { + return false; + } + }, + + _open: function() { + if (this.readyState !== API.CONNECTING) return; + + this.readyState = API.OPEN; + + var event = new Event('open'); + event.initEvent('open', false, false); + this.dispatchEvent(event); + }, + + write: function(message) { + return this.send(message); + }, + + end: function(message) { + if (message !== undefined) this.write(message); + this.close(); + }, + + send: function(message, options) { + if (this.readyState > API.OPEN) return false; + + message = String(message).replace(/(\r\n|\r|\n)/g, '$1data: '); + options = options || {}; + + var frame = ''; + if (options.event) frame += 'event: ' + options.event + '\r\n'; + if (options.id) frame += 'id: ' + options.id + '\r\n'; + frame += 'data: ' + message + '\r\n\r\n'; + + return this._write(frame); + }, + + ping: function() { + return this._write(':\r\n\r\n'); + }, + + close: function() { + if (this.readyState > API.OPEN) return false; + + this.readyState = API.CLOSED; + this.writable = false; + if (this._pingTimer) clearInterval(this._pingTimer); + if (this._stream) this._stream.end(); + + var event = new Event('close'); + event.initEvent('close', false, false); + this.dispatchEvent(event); + + return true; + } +}; + +for (var method in instance) EventSource.prototype[method] = instance[method]; +for (var key in EventTarget) EventSource.prototype[key] = EventTarget[key]; + +module.exports = EventSource; diff --git a/node_modules/faye-websocket/lib/faye/websocket.js b/node_modules/faye-websocket/lib/faye/websocket.js new file mode 100644 index 0000000..13255eb --- /dev/null +++ b/node_modules/faye-websocket/lib/faye/websocket.js @@ -0,0 +1,47 @@ +// API references: +// +// * https://html.spec.whatwg.org/multipage/comms.html#network +// * https://dom.spec.whatwg.org/#interface-eventtarget +// * https://dom.spec.whatwg.org/#interface-event + +'use strict'; + +var util = require('util'), + driver = require('websocket-driver'), + API = require('./websocket/api'); + +var WebSocket = function(request, socket, body, protocols, options) { + options = options || {}; + + this._stream = socket; + this._driver = driver.http(request, { maxLength: options.maxLength, protocols: protocols }); + + var self = this; + if (!this._stream || !this._stream.writable) return; + if (!this._stream.readable) return this._stream.end(); + + var catchup = function() { self._stream.removeListener('data', catchup) }; + this._stream.on('data', catchup); + + API.call(this, options); + + process.nextTick(function() { + self._driver.start(); + self._driver.io.write(body); + }); +}; +util.inherits(WebSocket, API); + +WebSocket.isWebSocket = function(request) { + return driver.isWebSocket(request); +}; + +WebSocket.validateOptions = function(options, validKeys) { + driver.validateOptions(options, validKeys); +}; + +WebSocket.WebSocket = WebSocket; +WebSocket.Client = require('./websocket/client'); +WebSocket.EventSource = require('./eventsource'); + +module.exports = WebSocket; diff --git a/node_modules/faye-websocket/lib/faye/websocket/api.js b/node_modules/faye-websocket/lib/faye/websocket/api.js new file mode 100644 index 0000000..d64cb03 --- /dev/null +++ b/node_modules/faye-websocket/lib/faye/websocket/api.js @@ -0,0 +1,199 @@ +'use strict'; + +var Stream = require('stream').Stream, + util = require('util'), + driver = require('websocket-driver'), + EventTarget = require('./api/event_target'), + Event = require('./api/event'); + +var API = function(options) { + options = options || {}; + driver.validateOptions(options, ['headers', 'extensions', 'maxLength', 'ping', 'proxy', 'tls', 'ca']); + + this.readable = this.writable = true; + + var headers = options.headers; + if (headers) { + for (var name in headers) this._driver.setHeader(name, headers[name]); + } + + var extensions = options.extensions; + if (extensions) { + [].concat(extensions).forEach(this._driver.addExtension, this._driver); + } + + this._ping = options.ping; + this._pingId = 0; + this.readyState = API.CONNECTING; + this.bufferedAmount = 0; + this.protocol = ''; + this.url = this._driver.url; + this.version = this._driver.version; + + var self = this; + + this._driver.on('open', function(e) { self._open() }); + this._driver.on('message', function(e) { self._receiveMessage(e.data) }); + this._driver.on('close', function(e) { self._beginClose(e.reason, e.code) }); + + this._driver.on('error', function(error) { + self._emitError(error.message); + }); + this.on('error', function() {}); + + this._driver.messages.on('drain', function() { + self.emit('drain'); + }); + + if (this._ping) + this._pingTimer = setInterval(function() { + self._pingId += 1; + self.ping(self._pingId.toString()); + }, this._ping * 1000); + + this._configureStream(); + + if (!this._proxy) { + this._stream.pipe(this._driver.io); + this._driver.io.pipe(this._stream); + } +}; +util.inherits(API, Stream); + +API.CONNECTING = 0; +API.OPEN = 1; +API.CLOSING = 2; +API.CLOSED = 3; + +API.CLOSE_TIMEOUT = 30000; + +var instance = { + write: function(data) { + return this.send(data); + }, + + end: function(data) { + if (data !== undefined) this.send(data); + this.close(); + }, + + pause: function() { + return this._driver.messages.pause(); + }, + + resume: function() { + return this._driver.messages.resume(); + }, + + send: function(data) { + if (this.readyState > API.OPEN) return false; + if (!(data instanceof Buffer)) data = String(data); + return this._driver.messages.write(data); + }, + + ping: function(message, callback) { + if (this.readyState > API.OPEN) return false; + return this._driver.ping(message, callback); + }, + + close: function(code, reason) { + if (code === undefined) code = 1000; + if (reason === undefined) reason = ''; + + if (code !== 1000 && (code < 3000 || code > 4999)) + throw new Error("Failed to execute 'close' on WebSocket: " + + "The code must be either 1000, or between 3000 and 4999. " + + code + " is neither."); + + if (this.readyState < API.CLOSING) { + var self = this; + this._closeTimer = setTimeout(function() { + self._beginClose('', 1006); + }, API.CLOSE_TIMEOUT); + } + + if (this.readyState !== API.CLOSED) this.readyState = API.CLOSING; + + this._driver.close(reason, code); + }, + + _configureStream: function() { + var self = this; + + this._stream.setTimeout(0); + this._stream.setNoDelay(true); + + ['close', 'end'].forEach(function(event) { + this._stream.on(event, function() { self._finalizeClose() }); + }, this); + + this._stream.on('error', function(error) { + self._emitError('Network error: ' + self.url + ': ' + error.message); + self._finalizeClose(); + }); + }, + + _open: function() { + if (this.readyState !== API.CONNECTING) return; + + this.readyState = API.OPEN; + this.protocol = this._driver.protocol || ''; + + var event = new Event('open'); + event.initEvent('open', false, false); + this.dispatchEvent(event); + }, + + _receiveMessage: function(data) { + if (this.readyState > API.OPEN) return false; + + if (this.readable) this.emit('data', data); + + var event = new Event('message', { data: data }); + event.initEvent('message', false, false); + this.dispatchEvent(event); + }, + + _emitError: function(message) { + if (this.readyState >= API.CLOSING) return; + + var event = new Event('error', { message: message }); + event.initEvent('error', false, false); + this.dispatchEvent(event); + }, + + _beginClose: function(reason, code) { + if (this.readyState === API.CLOSED) return; + this.readyState = API.CLOSING; + this._closeParams = [reason, code]; + + if (this._stream) { + this._stream.destroy(); + if (!this._stream.readable) this._finalizeClose(); + } + }, + + _finalizeClose: function() { + if (this.readyState === API.CLOSED) return; + this.readyState = API.CLOSED; + + if (this._closeTimer) clearTimeout(this._closeTimer); + if (this._pingTimer) clearInterval(this._pingTimer); + if (this._stream) this._stream.end(); + + if (this.readable) this.emit('end'); + this.readable = this.writable = false; + + var reason = this._closeParams ? this._closeParams[0] : '', + code = this._closeParams ? this._closeParams[1] : 1006; + + var event = new Event('close', { code: code, reason: reason }); + event.initEvent('close', false, false); + this.dispatchEvent(event); + } +}; + +for (var method in instance) API.prototype[method] = instance[method]; +for (var key in EventTarget) API.prototype[key] = EventTarget[key]; + +module.exports = API; diff --git a/node_modules/faye-websocket/lib/faye/websocket/api/event.js b/node_modules/faye-websocket/lib/faye/websocket/api/event.js new file mode 100644 index 0000000..00d82c5 --- /dev/null +++ b/node_modules/faye-websocket/lib/faye/websocket/api/event.js @@ -0,0 +1,22 @@ +'use strict'; + +var Event = function(eventType, options) { + this.type = eventType; + for (var key in options) + this[key] = options[key]; +}; + +Event.prototype.initEvent = function(eventType, canBubble, cancelable) { + this.type = eventType; + this.bubbles = canBubble; + this.cancelable = cancelable; +}; + +Event.prototype.stopPropagation = function() {}; +Event.prototype.preventDefault = function() {}; + +Event.CAPTURING_PHASE = 1; +Event.AT_TARGET = 2; +Event.BUBBLING_PHASE = 3; + +module.exports = Event; diff --git a/node_modules/faye-websocket/lib/faye/websocket/api/event_target.js b/node_modules/faye-websocket/lib/faye/websocket/api/event_target.js new file mode 100644 index 0000000..51a4ad9 --- /dev/null +++ b/node_modules/faye-websocket/lib/faye/websocket/api/event_target.js @@ -0,0 +1,30 @@ +'use strict'; + +var Event = require('./event'); + +var EventTarget = { + onopen: null, + onmessage: null, + onerror: null, + onclose: null, + + addEventListener: function(eventType, listener, useCapture) { + this.on(eventType, listener); + }, + + removeEventListener: function(eventType, listener, useCapture) { + this.removeListener(eventType, listener); + }, + + dispatchEvent: function(event) { + event.target = event.currentTarget = this; + event.eventPhase = Event.AT_TARGET; + + if (this['on' + event.type]) + this['on' + event.type](event); + + this.emit(event.type, event); + } +}; + +module.exports = EventTarget; diff --git a/node_modules/faye-websocket/lib/faye/websocket/client.js b/node_modules/faye-websocket/lib/faye/websocket/client.js new file mode 100644 index 0000000..c3f886d --- /dev/null +++ b/node_modules/faye-websocket/lib/faye/websocket/client.js @@ -0,0 +1,90 @@ +'use strict'; + +var util = require('util'), + net = require('net'), + tls = require('tls'), + url = require('url'), + driver = require('websocket-driver'), + API = require('./api'), + Event = require('./api/event'); + +var DEFAULT_PORTS = { 'http:': 80, 'https:': 443, 'ws:':80, 'wss:': 443 }, + SECURE_PROTOCOLS = ['https:', 'wss:']; + +var Client = function(_url, protocols, options) { + options = options || {}; + + this.url = _url; + this._driver = driver.client(this.url, { maxLength: options.maxLength, protocols: protocols }); + + ['open', 'error'].forEach(function(event) { + this._driver.on(event, function() { + self.headers = self._driver.headers; + self.statusCode = self._driver.statusCode; + }); + }, this); + + var proxy = options.proxy || {}, + endpoint = url.parse(proxy.origin || this.url), + port = endpoint.port || DEFAULT_PORTS[endpoint.protocol], + secure = SECURE_PROTOCOLS.indexOf(endpoint.protocol) >= 0, + onConnect = function() { self._onConnect() }, + netOptions = options.net || {}, + originTLS = options.tls || {}, + socketTLS = proxy.origin ? (proxy.tls || {}) : originTLS, + self = this; + + netOptions.host = socketTLS.host = endpoint.hostname; + netOptions.port = socketTLS.port = port; + + originTLS.ca = originTLS.ca || options.ca; + socketTLS.servername = socketTLS.servername || endpoint.hostname; + + this._stream = secure + ? tls.connect(socketTLS, onConnect) + : net.connect(netOptions, onConnect); + + if (proxy.origin) this._configureProxy(proxy, originTLS); + + API.call(this, options); +}; +util.inherits(Client, API); + +Client.prototype._onConnect = function() { + var worker = this._proxy || this._driver; + worker.start(); +}; + +Client.prototype._configureProxy = function(proxy, originTLS) { + var uri = url.parse(this.url), + secure = SECURE_PROTOCOLS.indexOf(uri.protocol) >= 0, + self = this, + name; + + this._proxy = this._driver.proxy(proxy.origin); + + if (proxy.headers) { + for (name in proxy.headers) this._proxy.setHeader(name, proxy.headers[name]); + } + + this._proxy.pipe(this._stream, { end: false }); + this._stream.pipe(this._proxy); + + this._proxy.on('connect', function() { + if (secure) { + var options = { socket: self._stream, servername: uri.hostname }; + for (name in originTLS) options[name] = originTLS[name]; + self._stream = tls.connect(options); + self._configureStream(); + } + self._driver.io.pipe(self._stream); + self._stream.pipe(self._driver.io); + self._driver.start(); + }); + + this._proxy.on('error', function(error) { + self._driver.emit('error', error); + }); +}; + +module.exports = Client; diff --git a/node_modules/faye-websocket/package.json b/node_modules/faye-websocket/package.json new file mode 100644 index 0000000..26acc2a --- /dev/null +++ b/node_modules/faye-websocket/package.json @@ -0,0 +1,35 @@ +{ + "name": "faye-websocket", + "description": "Standards-compliant WebSocket server and client", + "homepage": "https://github.com/faye/faye-websocket-node", + "author": "James Coglan (http://jcoglan.com/)", + "keywords": [ + "websocket", + "eventsource" + ], + "license": "Apache-2.0", + "version": "0.11.4", + "engines": { + "node": ">=0.8.0" + }, + "files": [ + "lib" + ], + "main": "./lib/faye/websocket", + "dependencies": { + "websocket-driver": ">=0.5.1" + }, + "devDependencies": { + "jstest": "*", + "pace": "*", + "permessage-deflate": "*" + }, + "scripts": { + "test": "jstest spec/runner.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/faye/faye-websocket-node.git" + }, + "bugs": "https://github.com/faye/faye-websocket-node/issues" +} diff --git a/node_modules/firebase-admin/LICENSE b/node_modules/firebase-admin/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/node_modules/firebase-admin/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/firebase-admin/README.md b/node_modules/firebase-admin/README.md new file mode 100644 index 0000000..8ebe57e --- /dev/null +++ b/node_modules/firebase-admin/README.md @@ -0,0 +1,94 @@ +[![Build Status](https://github.com/firebase/firebase-admin-node/workflows/Continuous%20Integration/badge.svg)](https://github.com/firebase/firebase-admin-node/actions) + +# Firebase Admin Node.js SDK + + +## Table of Contents + + * [Overview](#overview) + * [Installation](#installation) + * [Contributing](#contributing) + * [Documentation](#documentation) + * [Supported Environments](#supported-environments) + * [Acknowledgments](#acknowledgments) + * [License](#license) + + +## Overview + +[Firebase](https://firebase.google.com) provides the tools and infrastructure +you need to develop your app, grow your user base, and earn money. The Firebase +Admin Node.js SDK enables access to Firebase services from privileged environments +(such as servers or cloud) in Node.js. + +For more information, visit the +[Firebase Admin SDK setup guide](https://firebase.google.com/docs/admin/setup/). + + +## Installation + +The Firebase Admin Node.js SDK is available on npm as `firebase-admin`: + +```bash +$ npm install --save firebase-admin +``` + +To use the module in your application, `require` it from any JavaScript file: + +```js +const { initializeApp } = require("firebase-admin/app"); + +initializeApp(); +``` + +If you are using ES2015, you can `import` the module instead: + +```js +import { initializeApp } from "firebase-admin/app"; + +initializeApp(); +``` + + +## Contributing + +Please refer to the [CONTRIBUTING page](./CONTRIBUTING.md) for more information +about how you can contribute to this project. We welcome bug reports, feature +requests, code review feedback, and also pull requests. + + +## Supported Environments + +We support Node.js 18 and higher. + +Please also note that the Admin SDK should only +be used in server-side/back-end environments controlled by the app developer. +This includes most server and serverless platforms (both on-premise and in +the cloud). It is not recommended to use the Admin SDK in client-side +environments. + + +## Documentation + +* [Setup Guide](https://firebase.google.com/docs/admin/setup/) +* [Database Guide](https://firebase.google.com/docs/database/admin/start/) +* [Authentication Guide](https://firebase.google.com/docs/auth/admin/) +* [Cloud Messaging Guide](https://firebase.google.com/docs/cloud-messaging/admin/) +* [API Reference](https://firebase.google.com/docs/reference/admin/node/) +* [Release Notes](https://firebase.google.com/support/release-notes/admin/node/) + + +## Acknowledgments + +Thanks to the team at [Casetext](https://casetext.com/) for transferring +ownership of the `firebase-admin` npm module over to the Firebase team +and for their longtime use and support of the Firebase platform. + + +## License + +Firebase Admin Node.js SDK is licensed under the +[Apache License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0). + +Your use of Firebase is governed by the +[Terms of Service for Firebase Services](https://firebase.google.com/terms/). diff --git a/node_modules/firebase-admin/lib/app-check/app-check-api-client-internal.d.ts b/node_modules/firebase-admin/lib/app-check/app-check-api-client-internal.d.ts new file mode 100644 index 0000000..1316908 --- /dev/null +++ b/node_modules/firebase-admin/lib/app-check/app-check-api-client-internal.d.ts @@ -0,0 +1,32 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { PrefixedFirebaseError } from '../utils/error'; +export declare const APP_CHECK_ERROR_CODE_MAPPING: { + [key: string]: AppCheckErrorCode; +}; +export type AppCheckErrorCode = 'aborted' | 'invalid-argument' | 'invalid-credential' | 'internal-error' | 'permission-denied' | 'unauthenticated' | 'not-found' | 'app-check-token-expired' | 'unknown-error'; +/** + * Firebase App Check error code structure. This extends PrefixedFirebaseError. + * + * @param code - The error code. + * @param message - The error message. + * @constructor + */ +export declare class FirebaseAppCheckError extends PrefixedFirebaseError { + constructor(code: AppCheckErrorCode, message: string); +} diff --git a/node_modules/firebase-admin/lib/app-check/app-check-api-client-internal.js b/node_modules/firebase-admin/lib/app-check/app-check-api-client-internal.js new file mode 100644 index 0000000..f0811e7 --- /dev/null +++ b/node_modules/firebase-admin/lib/app-check/app-check-api-client-internal.js @@ -0,0 +1,214 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirebaseAppCheckError = exports.APP_CHECK_ERROR_CODE_MAPPING = exports.AppCheckApiClient = void 0; +const api_request_1 = require("../utils/api-request"); +const error_1 = require("../utils/error"); +const utils = require("../utils/index"); +const validator = require("../utils/validator"); +// App Check backend constants +const FIREBASE_APP_CHECK_V1_API_URL_FORMAT = 'https://firebaseappcheck.googleapis.com/v1/projects/{projectId}/apps/{appId}:exchangeCustomToken'; +const ONE_TIME_USE_TOKEN_VERIFICATION_URL_FORMAT = 'https://firebaseappcheck.googleapis.com/v1beta/projects/{projectId}:verifyAppCheckToken'; +const FIREBASE_APP_CHECK_CONFIG_HEADERS = { + 'X-Firebase-Client': `fire-admin-node/${utils.getSdkVersion()}` +}; +/** + * Class that facilitates sending requests to the Firebase App Check backend API. + * + * @internal + */ +class AppCheckApiClient { + constructor(app) { + this.app = app; + if (!validator.isNonNullObject(app) || !('options' in app)) { + throw new FirebaseAppCheckError('invalid-argument', 'First argument passed to admin.appCheck() must be a valid Firebase app instance.'); + } + this.httpClient = new api_request_1.AuthorizedHttpClient(app); + } + /** + * Exchange a signed custom token to App Check token + * + * @param customToken - The custom token to be exchanged. + * @param appId - The mobile App ID. + * @returns A promise that fulfills with a `AppCheckToken`. + */ + exchangeToken(customToken, appId) { + if (!validator.isNonEmptyString(appId)) { + throw new FirebaseAppCheckError('invalid-argument', '`appId` must be a non-empty string.'); + } + if (!validator.isNonEmptyString(customToken)) { + throw new FirebaseAppCheckError('invalid-argument', '`customToken` must be a non-empty string.'); + } + return this.getUrl(appId) + .then((url) => { + const request = { + method: 'POST', + url, + headers: FIREBASE_APP_CHECK_CONFIG_HEADERS, + data: { customToken } + }; + return this.httpClient.send(request); + }) + .then((resp) => { + return this.toAppCheckToken(resp); + }) + .catch((err) => { + throw this.toFirebaseError(err); + }); + } + verifyReplayProtection(token) { + if (!validator.isNonEmptyString(token)) { + throw new FirebaseAppCheckError('invalid-argument', '`token` must be a non-empty string.'); + } + return this.getVerifyTokenUrl() + .then((url) => { + const request = { + method: 'POST', + url, + headers: FIREBASE_APP_CHECK_CONFIG_HEADERS, + data: { app_check_token: token } + }; + return this.httpClient.send(request); + }) + .then((resp) => { + if (typeof resp.data.alreadyConsumed !== 'undefined' + && !validator.isBoolean(resp.data?.alreadyConsumed)) { + throw new FirebaseAppCheckError('invalid-argument', '`alreadyConsumed` must be a boolean value.'); + } + return resp.data.alreadyConsumed || false; + }) + .catch((err) => { + throw this.toFirebaseError(err); + }); + } + getUrl(appId) { + return this.getProjectId() + .then((projectId) => { + const urlParams = { + projectId, + appId, + }; + const baseUrl = utils.formatString(FIREBASE_APP_CHECK_V1_API_URL_FORMAT, urlParams); + return utils.formatString(baseUrl); + }); + } + getVerifyTokenUrl() { + return this.getProjectId() + .then((projectId) => { + const urlParams = { + projectId + }; + const baseUrl = utils.formatString(ONE_TIME_USE_TOKEN_VERIFICATION_URL_FORMAT, urlParams); + return utils.formatString(baseUrl); + }); + } + getProjectId() { + if (this.projectId) { + return Promise.resolve(this.projectId); + } + return utils.findProjectId(this.app) + .then((projectId) => { + if (!validator.isNonEmptyString(projectId)) { + throw new FirebaseAppCheckError('unknown-error', 'Failed to determine project ID. Initialize the ' + + 'SDK with service account credentials or set project ID as an app option. ' + + 'Alternatively, set the GOOGLE_CLOUD_PROJECT environment variable.'); + } + this.projectId = projectId; + return projectId; + }); + } + toFirebaseError(err) { + if (err instanceof error_1.PrefixedFirebaseError) { + return err; + } + const response = err.response; + if (!response.isJson()) { + return new FirebaseAppCheckError('unknown-error', `Unexpected response with status: ${response.status} and body: ${response.text}`); + } + const error = response.data.error || {}; + let code = 'unknown-error'; + if (error.status && error.status in exports.APP_CHECK_ERROR_CODE_MAPPING) { + code = exports.APP_CHECK_ERROR_CODE_MAPPING[error.status]; + } + const message = error.message || `Unknown server error: ${response.text}`; + return new FirebaseAppCheckError(code, message); + } + /** + * Creates an AppCheckToken from the API response. + * + * @param resp - API response object. + * @returns An AppCheckToken instance. + */ + toAppCheckToken(resp) { + const token = resp.data.token; + // `ttl` is a string with the suffix "s" preceded by the number of seconds, + // with nanoseconds expressed as fractional seconds. + const ttlMillis = this.stringToMilliseconds(resp.data.ttl); + return { + token, + ttlMillis + }; + } + /** + * Converts a duration string with the suffix `s` to milliseconds. + * + * @param duration - The duration as a string with the suffix "s" preceded by the + * number of seconds, with fractional seconds. For example, 3 seconds with 0 nanoseconds + * is expressed as "3s", while 3 seconds and 1 nanosecond is expressed as "3.000000001s", + * and 3 seconds and 1 microsecond is expressed as "3.000001s". + * + * @returns The duration in milliseconds. + */ + stringToMilliseconds(duration) { + if (!validator.isNonEmptyString(duration) || !duration.endsWith('s')) { + throw new FirebaseAppCheckError('invalid-argument', '`ttl` must be a valid duration string with the suffix `s`.'); + } + const seconds = duration.slice(0, -1); + return Math.floor(Number(seconds) * 1000); + } +} +exports.AppCheckApiClient = AppCheckApiClient; +exports.APP_CHECK_ERROR_CODE_MAPPING = { + ABORTED: 'aborted', + INVALID_ARGUMENT: 'invalid-argument', + INVALID_CREDENTIAL: 'invalid-credential', + INTERNAL: 'internal-error', + PERMISSION_DENIED: 'permission-denied', + UNAUTHENTICATED: 'unauthenticated', + NOT_FOUND: 'not-found', + UNKNOWN: 'unknown-error', +}; +/** + * Firebase App Check error code structure. This extends PrefixedFirebaseError. + * + * @param code - The error code. + * @param message - The error message. + * @constructor + */ +class FirebaseAppCheckError extends error_1.PrefixedFirebaseError { + constructor(code, message) { + super('app-check', code, message); + /* tslint:disable:max-line-length */ + // Set the prototype explicitly. See the following link for more details: + // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work + /* tslint:enable:max-line-length */ + this.__proto__ = FirebaseAppCheckError.prototype; + } +} +exports.FirebaseAppCheckError = FirebaseAppCheckError; diff --git a/node_modules/firebase-admin/lib/app-check/app-check-api.d.ts b/node_modules/firebase-admin/lib/app-check/app-check-api.d.ts new file mode 100644 index 0000000..05e8f8a --- /dev/null +++ b/node_modules/firebase-admin/lib/app-check/app-check-api.d.ts @@ -0,0 +1,129 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Interface representing an App Check token. + */ +export interface AppCheckToken { + /** + * The Firebase App Check token. + */ + token: string; + /** + * The time-to-live duration of the token in milliseconds. + */ + ttlMillis: number; +} +/** + * Interface representing App Check token options. + */ +export interface AppCheckTokenOptions { + /** + * The length of time, in milliseconds, for which the App Check token will + * be valid. This value must be between 30 minutes and 7 days, inclusive. + */ + ttlMillis?: number; +} +/** + * Interface representing options for the {@link AppCheck.verifyToken} method. + */ +export interface VerifyAppCheckTokenOptions { + /** + * To use the replay protection feature, set this to `true`. The {@link AppCheck.verifyToken} + * method will mark the token as consumed after verifying it. + * + * Tokens that are found to be already consumed will be marked as such in the response. + * + * Tokens are only considered to be consumed if it is sent to App Check backend by calling the + * {@link AppCheck.verifyToken} method with this field set to `true`; other uses of the token + * do not consume it. + * + * This replay protection feature requires an additional network call to the App Check backend + * and forces your clients to obtain a fresh attestation from your chosen attestation providers. + * This can therefore negatively impact performance and can potentially deplete your attestation + * providers' quotas faster. We recommend that you use this feature only for protecting + * low volume, security critical, or expensive operations. + */ + consume?: boolean; +} +/** + * Interface representing a decoded Firebase App Check token, returned from the + * {@link AppCheck.verifyToken} method. + */ +export interface DecodedAppCheckToken { + /** + * The issuer identifier for the issuer of the response. + * This value is a URL with the format + * `https://firebaseappcheck.googleapis.com/`, where `` is the + * same project number specified in the {@link DecodedAppCheckToken.aud | aud} property. + */ + iss: string; + /** + * The Firebase App ID corresponding to the app the token belonged to. + * As a convenience, this value is copied over to the {@link DecodedAppCheckToken.app_id | app_id} property. + */ + sub: string; + /** + * The audience for which this token is intended. + * This value is a JSON array of two strings, the first is the project number of your + * Firebase project, and the second is the project ID of the same project. + */ + aud: string[]; + /** + * The App Check token's expiration time, in seconds since the Unix epoch. That is, the + * time at which this App Check token expires and should no longer be considered valid. + */ + exp: number; + /** + * The App Check token's issued-at time, in seconds since the Unix epoch. That is, the + * time at which this App Check token was issued and should start to be considered + * valid. + */ + iat: number; + /** + * The App ID corresponding to the App the App Check token belonged to. + * This value is not actually one of the JWT token claims. It is added as a + * convenience, and is set as the value of the {@link DecodedAppCheckToken.sub | sub} property. + */ + app_id: string; + [key: string]: any; +} +/** + * Interface representing a verified App Check token response. + */ +export interface VerifyAppCheckTokenResponse { + /** + * The App ID corresponding to the App the App Check token belonged to. + */ + appId: string; + /** + * The decoded Firebase App Check token. + */ + token: DecodedAppCheckToken; + /** + * Indicates weather this token was already consumed. + * If this is the first time {@link AppCheck.verifyToken} method has seen this token, + * this field will contain the value `false`. The given token will then be + * marked as `already_consumed` for all future invocations of this {@link AppCheck.verifyToken} + * method for this token. + * + * When this field is `true`, the caller is attempting to reuse a previously consumed token. + * You should take precautions against such a caller; for example, you can take actions such as + * rejecting the request or ask the caller to pass additional layers of security checks. + */ + alreadyConsumed?: boolean; +} diff --git a/node_modules/firebase-admin/lib/app-check/app-check-api.js b/node_modules/firebase-admin/lib/app-check/app-check-api.js new file mode 100644 index 0000000..0457090 --- /dev/null +++ b/node_modules/firebase-admin/lib/app-check/app-check-api.js @@ -0,0 +1,19 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/firebase-admin/lib/app-check/app-check-namespace.d.ts b/node_modules/firebase-admin/lib/app-check/app-check-namespace.d.ts new file mode 100644 index 0000000..3154d1c --- /dev/null +++ b/node_modules/firebase-admin/lib/app-check/app-check-namespace.d.ts @@ -0,0 +1,72 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +import { AppCheckToken as TAppCheckToken, AppCheckTokenOptions as TAppCheckTokenOptions, DecodedAppCheckToken as TDecodedAppCheckToken, VerifyAppCheckTokenOptions as TVerifyAppCheckTokenOptions, VerifyAppCheckTokenResponse as TVerifyAppCheckTokenResponse } from './app-check-api'; +import { AppCheck as TAppCheck } from './app-check'; +/** + * Gets the {@link firebase-admin.app-check#AppCheck} service for the default app or a given app. + * + * `admin.appCheck()` can be called with no arguments to access the default + * app's `AppCheck` service or as `admin.appCheck(app)` to access the + * `AppCheck` service associated with a specific app. + * + * @example + * ```javascript + * // Get the `AppCheck` service for the default app + * var defaultAppCheck = admin.appCheck(); + * ``` + * + * @example + * ```javascript + * // Get the `AppCheck` service for a given app + * var otherAppCheck = admin.appCheck(otherApp); + * ``` + * + * @param app - Optional app for which to return the `AppCheck` service. + * If not provided, the default `AppCheck` service is returned. + * + * @returns The default `AppCheck` service if no + * app is provided, or the `AppCheck` service associated with the provided + * app. + */ +export declare function appCheck(app?: App): appCheck.AppCheck; +export declare namespace appCheck { + /** + * Type alias to {@link firebase-admin.app-check#AppCheck}. + */ + type AppCheck = TAppCheck; + /** + * Type alias to {@link firebase-admin.app-check#AppCheckToken}. + */ + type AppCheckToken = TAppCheckToken; + /** + * Type alias to {@link firebase-admin.app-check#DecodedAppCheckToken}. + */ + type DecodedAppCheckToken = TDecodedAppCheckToken; + /** + * Type alias to {@link firebase-admin.app-check#VerifyAppCheckTokenResponse}. + */ + type VerifyAppCheckTokenResponse = TVerifyAppCheckTokenResponse; + /** + * Type alias to {@link firebase-admin.app-check#AppCheckTokenOptions}. + */ + type AppCheckTokenOptions = TAppCheckTokenOptions; + /** + * Type alias to {@link firebase-admin.app-check#VerifyAppCheckTokenOptions}. + */ + type VerifyAppCheckTokenOptions = TVerifyAppCheckTokenOptions; +} diff --git a/node_modules/firebase-admin/lib/app-check/app-check-namespace.js b/node_modules/firebase-admin/lib/app-check/app-check-namespace.js new file mode 100644 index 0000000..a91b066 --- /dev/null +++ b/node_modules/firebase-admin/lib/app-check/app-check-namespace.js @@ -0,0 +1,18 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/firebase-admin/lib/app-check/app-check.d.ts b/node_modules/firebase-admin/lib/app-check/app-check.d.ts new file mode 100644 index 0000000..d289764 --- /dev/null +++ b/node_modules/firebase-admin/lib/app-check/app-check.d.ts @@ -0,0 +1,51 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +import { AppCheckToken, AppCheckTokenOptions, VerifyAppCheckTokenOptions, VerifyAppCheckTokenResponse } from './app-check-api'; +/** + * The Firebase `AppCheck` service interface. + */ +export declare class AppCheck { + readonly app: App; + private readonly client; + private readonly tokenGenerator; + private readonly appCheckTokenVerifier; + /** + * Creates a new {@link AppCheckToken} that can be sent + * back to a client. + * + * @param appId - The app ID to use as the JWT app_id. + * @param options - Optional options object when creating a new App Check Token. + * + * @returns A promise that fulfills with a `AppCheckToken`. + */ + createToken(appId: string, options?: AppCheckTokenOptions): Promise; + /** + * Verifies a Firebase App Check token (JWT). If the token is valid, the promise is + * fulfilled with the token's decoded claims; otherwise, the promise is + * rejected. + * + * @param appCheckToken - The App Check token to verify. + * @param options - Optional {@link VerifyAppCheckTokenOptions} object when verifying an App Check Token. + * + * @returns A promise fulfilled with the token's decoded claims + * if the App Check token is valid; otherwise, a rejected promise. + */ + verifyToken(appCheckToken: string, options?: VerifyAppCheckTokenOptions): Promise; + private validateVerifyAppCheckTokenOptions; +} diff --git a/node_modules/firebase-admin/lib/app-check/app-check.js b/node_modules/firebase-admin/lib/app-check/app-check.js new file mode 100644 index 0000000..5da6d87 --- /dev/null +++ b/node_modules/firebase-admin/lib/app-check/app-check.js @@ -0,0 +1,101 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AppCheck = void 0; +const validator = require("../utils/validator"); +const app_check_api_client_internal_1 = require("./app-check-api-client-internal"); +const token_generator_1 = require("./token-generator"); +const token_verifier_1 = require("./token-verifier"); +const crypto_signer_1 = require("../utils/crypto-signer"); +/** + * The Firebase `AppCheck` service interface. + */ +class AppCheck { + /** + * @param app - The app for this AppCheck service. + * @constructor + * @internal + */ + constructor(app) { + this.app = app; + this.client = new app_check_api_client_internal_1.AppCheckApiClient(app); + try { + this.tokenGenerator = new token_generator_1.AppCheckTokenGenerator((0, crypto_signer_1.cryptoSignerFromApp)(app)); + } + catch (err) { + throw (0, token_generator_1.appCheckErrorFromCryptoSignerError)(err); + } + this.appCheckTokenVerifier = new token_verifier_1.AppCheckTokenVerifier(app); + } + /** + * Creates a new {@link AppCheckToken} that can be sent + * back to a client. + * + * @param appId - The app ID to use as the JWT app_id. + * @param options - Optional options object when creating a new App Check Token. + * + * @returns A promise that fulfills with a `AppCheckToken`. + */ + createToken(appId, options) { + return this.tokenGenerator.createCustomToken(appId, options) + .then((customToken) => { + return this.client.exchangeToken(customToken, appId); + }); + } + /** + * Verifies a Firebase App Check token (JWT). If the token is valid, the promise is + * fulfilled with the token's decoded claims; otherwise, the promise is + * rejected. + * + * @param appCheckToken - The App Check token to verify. + * @param options - Optional {@link VerifyAppCheckTokenOptions} object when verifying an App Check Token. + * + * @returns A promise fulfilled with the token's decoded claims + * if the App Check token is valid; otherwise, a rejected promise. + */ + verifyToken(appCheckToken, options) { + this.validateVerifyAppCheckTokenOptions(options); + return this.appCheckTokenVerifier.verifyToken(appCheckToken) + .then((decodedToken) => { + if (options?.consume) { + return this.client.verifyReplayProtection(appCheckToken) + .then((alreadyConsumed) => { + return { + alreadyConsumed, + appId: decodedToken.app_id, + token: decodedToken, + }; + }); + } + return { + appId: decodedToken.app_id, + token: decodedToken, + }; + }); + } + validateVerifyAppCheckTokenOptions(options) { + if (typeof options === 'undefined') { + return; + } + if (!validator.isNonNullObject(options)) { + throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', 'VerifyAppCheckTokenOptions must be a non-null object.'); + } + } +} +exports.AppCheck = AppCheck; diff --git a/node_modules/firebase-admin/lib/app-check/index.d.ts b/node_modules/firebase-admin/lib/app-check/index.d.ts new file mode 100644 index 0000000..ec9c0e5 --- /dev/null +++ b/node_modules/firebase-admin/lib/app-check/index.d.ts @@ -0,0 +1,53 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Firebase App Check. + * + * @packageDocumentation + */ +import { App } from '../app'; +import { AppCheck } from './app-check'; +export { AppCheckToken, AppCheckTokenOptions, DecodedAppCheckToken, VerifyAppCheckTokenOptions, VerifyAppCheckTokenResponse, } from './app-check-api'; +export { AppCheck } from './app-check'; +/** + * Gets the {@link AppCheck} service for the default app or a given app. + * + * `getAppCheck()` can be called with no arguments to access the default + * app's `AppCheck` service or as `getAppCheck(app)` to access the + * `AppCheck` service associated with a specific app. + * + * @example + * ```javascript + * // Get the `AppCheck` service for the default app + * const defaultAppCheck = getAppCheck(); + * ``` + * + * @example + * ```javascript + * // Get the `AppCheck` service for a given app + * const otherAppCheck = getAppCheck(otherApp); + * ``` + * + * @param app - Optional app for which to return the `AppCheck` service. + * If not provided, the default `AppCheck` service is returned. + * + * @returns The default `AppCheck` service if no + * app is provided, or the `AppCheck` service associated with the provided + * app. + */ +export declare function getAppCheck(app?: App): AppCheck; diff --git a/node_modules/firebase-admin/lib/app-check/index.js b/node_modules/firebase-admin/lib/app-check/index.js new file mode 100644 index 0000000..889ba1d --- /dev/null +++ b/node_modules/firebase-admin/lib/app-check/index.js @@ -0,0 +1,63 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AppCheck = void 0; +exports.getAppCheck = getAppCheck; +/** + * Firebase App Check. + * + * @packageDocumentation + */ +const app_1 = require("../app"); +const app_check_1 = require("./app-check"); +var app_check_2 = require("./app-check"); +Object.defineProperty(exports, "AppCheck", { enumerable: true, get: function () { return app_check_2.AppCheck; } }); +/** + * Gets the {@link AppCheck} service for the default app or a given app. + * + * `getAppCheck()` can be called with no arguments to access the default + * app's `AppCheck` service or as `getAppCheck(app)` to access the + * `AppCheck` service associated with a specific app. + * + * @example + * ```javascript + * // Get the `AppCheck` service for the default app + * const defaultAppCheck = getAppCheck(); + * ``` + * + * @example + * ```javascript + * // Get the `AppCheck` service for a given app + * const otherAppCheck = getAppCheck(otherApp); + * ``` + * + * @param app - Optional app for which to return the `AppCheck` service. + * If not provided, the default `AppCheck` service is returned. + * + * @returns The default `AppCheck` service if no + * app is provided, or the `AppCheck` service associated with the provided + * app. + */ +function getAppCheck(app) { + if (typeof app === 'undefined') { + app = (0, app_1.getApp)(); + } + const firebaseApp = app; + return firebaseApp.getOrInitService('appCheck', (app) => new app_check_1.AppCheck(app)); +} diff --git a/node_modules/firebase-admin/lib/app-check/token-generator.d.ts b/node_modules/firebase-admin/lib/app-check/token-generator.d.ts new file mode 100644 index 0000000..9588459 --- /dev/null +++ b/node_modules/firebase-admin/lib/app-check/token-generator.d.ts @@ -0,0 +1,25 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Creates a new `FirebaseAppCheckError` by extracting the error code, message and other relevant + * details from a `CryptoSignerError`. + * + * @param err - The Error to convert into a `FirebaseAppCheckError` error + * @returns A Firebase App Check error that can be returned to the user. + */ +export declare function appCheckErrorFromCryptoSignerError(err: Error): Error; diff --git a/node_modules/firebase-admin/lib/app-check/token-generator.js b/node_modules/firebase-admin/lib/app-check/token-generator.js new file mode 100644 index 0000000..93730ca --- /dev/null +++ b/node_modules/firebase-admin/lib/app-check/token-generator.js @@ -0,0 +1,154 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AppCheckTokenGenerator = void 0; +exports.appCheckErrorFromCryptoSignerError = appCheckErrorFromCryptoSignerError; +const validator = require("../utils/validator"); +const utils_1 = require("../utils"); +const crypto_signer_1 = require("../utils/crypto-signer"); +const app_check_api_client_internal_1 = require("./app-check-api-client-internal"); +const ONE_MINUTE_IN_SECONDS = 60; +const ONE_MINUTE_IN_MILLIS = ONE_MINUTE_IN_SECONDS * 1000; +const ONE_DAY_IN_MILLIS = 24 * 60 * 60 * 1000; +// Audience to use for Firebase App Check Custom tokens +const FIREBASE_APP_CHECK_AUDIENCE = 'https://firebaseappcheck.googleapis.com/google.firebase.appcheck.v1.TokenExchangeService'; +/** + * Class for generating Firebase App Check tokens. + * + * @internal + */ +class AppCheckTokenGenerator { + /** + * The AppCheckTokenGenerator class constructor. + * + * @param signer - The CryptoSigner instance for this token generator. + * @constructor + */ + constructor(signer) { + if (!validator.isNonNullObject(signer)) { + throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', 'INTERNAL ASSERT: Must provide a CryptoSigner to use AppCheckTokenGenerator.'); + } + this.signer = signer; + } + /** + * Creates a new custom token that can be exchanged to an App Check token. + * + * @param appId - The Application ID to use for the generated token. + * + * @returns A Promise fulfilled with a custom token signed with a service account key + * that can be exchanged to an App Check token. + */ + createCustomToken(appId, options) { + if (!validator.isNonEmptyString(appId)) { + throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', '`appId` must be a non-empty string.'); + } + let customOptions = {}; + if (typeof options !== 'undefined') { + customOptions = this.validateTokenOptions(options); + } + return this.signer.getAccountId().then((account) => { + const header = { + alg: this.signer.algorithm, + typ: 'JWT', + }; + const iat = Math.floor(Date.now() / 1000); + const body = { + iss: account, + sub: account, + app_id: appId, + aud: FIREBASE_APP_CHECK_AUDIENCE, + exp: iat + (ONE_MINUTE_IN_SECONDS * 5), + iat, + ...customOptions, + }; + const token = `${this.encodeSegment(header)}.${this.encodeSegment(body)}`; + return this.signer.sign(Buffer.from(token)) + .then((signature) => { + return `${token}.${this.encodeSegment(signature)}`; + }); + }).catch((err) => { + throw appCheckErrorFromCryptoSignerError(err); + }); + } + encodeSegment(segment) { + const buffer = (segment instanceof Buffer) ? segment : Buffer.from(JSON.stringify(segment)); + return (0, utils_1.toWebSafeBase64)(buffer).replace(/=+$/, ''); + } + /** + * Checks if a given `AppCheckTokenOptions` object is valid. If successful, returns an object with + * custom properties. + * + * @param options - An options object to be validated. + * @returns A custom object with ttl converted to protobuf Duration string format. + */ + validateTokenOptions(options) { + if (!validator.isNonNullObject(options)) { + throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', 'AppCheckTokenOptions must be a non-null object.'); + } + if (typeof options.ttlMillis !== 'undefined') { + if (!validator.isNumber(options.ttlMillis)) { + throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', 'ttlMillis must be a duration in milliseconds.'); + } + // ttlMillis must be between 30 minutes and 7 days (inclusive) + if (options.ttlMillis < (ONE_MINUTE_IN_MILLIS * 30) || options.ttlMillis > (ONE_DAY_IN_MILLIS * 7)) { + throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', 'ttlMillis must be a duration in milliseconds between 30 minutes and 7 days (inclusive).'); + } + return { ttl: (0, utils_1.transformMillisecondsToSecondsString)(options.ttlMillis) }; + } + return {}; + } +} +exports.AppCheckTokenGenerator = AppCheckTokenGenerator; +/** + * Creates a new `FirebaseAppCheckError` by extracting the error code, message and other relevant + * details from a `CryptoSignerError`. + * + * @param err - The Error to convert into a `FirebaseAppCheckError` error + * @returns A Firebase App Check error that can be returned to the user. + */ +function appCheckErrorFromCryptoSignerError(err) { + if (!(err instanceof crypto_signer_1.CryptoSignerError)) { + return err; + } + if (err.code === crypto_signer_1.CryptoSignerErrorCode.SERVER_ERROR && validator.isNonNullObject(err.cause)) { + const httpError = err.cause; + const errorResponse = httpError.response.data; + if (errorResponse?.error) { + const status = errorResponse.error.status; + const description = errorResponse.error.message || JSON.stringify(httpError.response); + let code = 'unknown-error'; + if (status && status in app_check_api_client_internal_1.APP_CHECK_ERROR_CODE_MAPPING) { + code = app_check_api_client_internal_1.APP_CHECK_ERROR_CODE_MAPPING[status]; + } + return new app_check_api_client_internal_1.FirebaseAppCheckError(code, `Error returned from server while signing a custom token: ${description}`); + } + return new app_check_api_client_internal_1.FirebaseAppCheckError('internal-error', 'Error returned from server: ' + JSON.stringify(errorResponse) + '.'); + } + return new app_check_api_client_internal_1.FirebaseAppCheckError(mapToAppCheckErrorCode(err.code), err.message); +} +function mapToAppCheckErrorCode(code) { + switch (code) { + case crypto_signer_1.CryptoSignerErrorCode.INVALID_CREDENTIAL: + return 'invalid-credential'; + case crypto_signer_1.CryptoSignerErrorCode.INVALID_ARGUMENT: + return 'invalid-argument'; + default: + return 'internal-error'; + } +} diff --git a/node_modules/firebase-admin/lib/app-check/token-verifier.d.ts b/node_modules/firebase-admin/lib/app-check/token-verifier.d.ts new file mode 100644 index 0000000..3c0441a --- /dev/null +++ b/node_modules/firebase-admin/lib/app-check/token-verifier.d.ts @@ -0,0 +1,17 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/firebase-admin/lib/app-check/token-verifier.js b/node_modules/firebase-admin/lib/app-check/token-verifier.js new file mode 100644 index 0000000..a7296a9 --- /dev/null +++ b/node_modules/firebase-admin/lib/app-check/token-verifier.js @@ -0,0 +1,147 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AppCheckTokenVerifier = void 0; +const validator = require("../utils/validator"); +const util = require("../utils/index"); +const app_check_api_client_internal_1 = require("./app-check-api-client-internal"); +const jwt_1 = require("../utils/jwt"); +const APP_CHECK_ISSUER = 'https://firebaseappcheck.googleapis.com/'; +const JWKS_URL = 'https://firebaseappcheck.googleapis.com/v1/jwks'; +/** + * Class for verifying Firebase App Check tokens. + * + * @internal + */ +class AppCheckTokenVerifier { + constructor(app) { + this.app = app; + this.signatureVerifier = jwt_1.PublicKeySignatureVerifier.withJwksUrl(JWKS_URL, app.options.httpAgent); + } + /** + * Verifies the format and signature of a Firebase App Check token. + * + * @param token - The Firebase Auth JWT token to verify. + * @returns A promise fulfilled with the decoded claims of the Firebase App Check token. + */ + verifyToken(token) { + if (!validator.isString(token)) { + throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', 'App check token must be a non-null string.'); + } + return this.ensureProjectId() + .then((projectId) => { + return this.decodeAndVerify(token, projectId); + }) + .then((decoded) => { + const decodedAppCheckToken = decoded.payload; + decodedAppCheckToken.app_id = decodedAppCheckToken.sub; + return decodedAppCheckToken; + }); + } + ensureProjectId() { + return util.findProjectId(this.app) + .then((projectId) => { + if (!validator.isNonEmptyString(projectId)) { + throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-credential', 'Must initialize app with a cert credential or set your Firebase project ID as the ' + + 'GOOGLE_CLOUD_PROJECT environment variable to verify an App Check token.'); + } + return projectId; + }); + } + decodeAndVerify(token, projectId) { + return this.safeDecode(token) + .then((decodedToken) => { + this.verifyContent(decodedToken, projectId); + return this.verifySignature(token) + .then(() => decodedToken); + }); + } + safeDecode(jwtToken) { + return (0, jwt_1.decodeJwt)(jwtToken) + .catch(() => { + const errorMessage = 'Decoding App Check token failed. Make sure you passed ' + + 'the entire string JWT which represents the Firebase App Check token.'; + throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', errorMessage); + }); + } + /** + * Verifies the content of a Firebase App Check JWT. + * + * @param fullDecodedToken - The decoded JWT. + * @param projectId - The Firebase Project Id. + */ + verifyContent(fullDecodedToken, projectId) { + const header = fullDecodedToken.header; + const payload = fullDecodedToken.payload; + const projectIdMatchMessage = ' Make sure the App Check token comes from the same ' + + 'Firebase project as the service account used to authenticate this SDK.'; + const scopedProjectId = `projects/${projectId}`; + let errorMessage; + if (header.alg !== jwt_1.ALGORITHM_RS256) { + errorMessage = 'The provided App Check token has incorrect algorithm. Expected "' + + jwt_1.ALGORITHM_RS256 + '" but got ' + '"' + header.alg + '".'; + } + else if (!validator.isNonEmptyArray(payload.aud) || !payload.aud.includes(scopedProjectId)) { + errorMessage = 'The provided App Check token has incorrect "aud" (audience) claim. Expected "' + + scopedProjectId + '" but got "' + payload.aud + '".' + projectIdMatchMessage; + } + else if (typeof payload.iss !== 'string' || !payload.iss.startsWith(APP_CHECK_ISSUER)) { + errorMessage = 'The provided App Check token has incorrect "iss" (issuer) claim.'; + } + else if (typeof payload.sub !== 'string') { + errorMessage = 'The provided App Check token has no "sub" (subject) claim.'; + } + else if (payload.sub === '') { + errorMessage = 'The provided App Check token has an empty string "sub" (subject) claim.'; + } + if (errorMessage) { + throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', errorMessage); + } + } + verifySignature(jwtToken) { + return this.signatureVerifier.verify(jwtToken) + .catch((error) => { + throw this.mapJwtErrorToAppCheckError(error); + }); + } + /** + * Maps JwtError to FirebaseAppCheckError + * + * @param error - JwtError to be mapped. + * @returns FirebaseAppCheckError instance. + */ + mapJwtErrorToAppCheckError(error) { + if (error.code === jwt_1.JwtErrorCode.TOKEN_EXPIRED) { + const errorMessage = 'The provided App Check token has expired. Get a fresh App Check token' + + ' from your client app and try again.'; + return new app_check_api_client_internal_1.FirebaseAppCheckError('app-check-token-expired', errorMessage); + } + else if (error.code === jwt_1.JwtErrorCode.INVALID_SIGNATURE) { + const errorMessage = 'The provided App Check token has invalid signature.'; + return new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', errorMessage); + } + else if (error.code === jwt_1.JwtErrorCode.NO_MATCHING_KID) { + const errorMessage = 'The provided App Check token has "kid" claim which does not ' + + 'correspond to a known public key. Most likely the provided App Check token ' + + 'is expired, so get a fresh token from your client app and try again.'; + return new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', errorMessage); + } + return new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', error.message); + } +} +exports.AppCheckTokenVerifier = AppCheckTokenVerifier; diff --git a/node_modules/firebase-admin/lib/app/core.d.ts b/node_modules/firebase-admin/lib/app/core.d.ts new file mode 100644 index 0000000..e3246d1 --- /dev/null +++ b/node_modules/firebase-admin/lib/app/core.d.ts @@ -0,0 +1,187 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Agent } from 'http'; +import { Credential } from './credential'; +/** + * Available options to pass to {@link firebase-admin.app#initializeApp}. + */ +export interface AppOptions { + /** + * A {@link firebase-admin.app#Credential} object used to + * authenticate the Admin SDK. + * + * See {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK} + * for detailed documentation and code samples. + */ + credential?: Credential; + /** + * The object to use as the {@link https://firebase.google.com/docs/reference/security/database/#auth | auth} + * variable in your Realtime Database Rules when the Admin SDK reads from or + * writes to the Realtime Database. This allows you to downscope the Admin SDK + * from its default full read and write privileges. + * + * You can pass `null` to act as an unauthenticated client. + * + * See + * {@link https://firebase.google.com/docs/database/admin/start#authenticate-with-limited-privileges | + * Authenticate with limited privileges} + * for detailed documentation and code samples. + */ + databaseAuthVariableOverride?: object | null; + /** + * The URL of the Realtime Database from which to read and write data. + */ + databaseURL?: string; + /** + * The ID of the service account to be used for signing custom tokens. This + * can be found in the `client_email` field of a service account JSON file. + */ + serviceAccountId?: string; + /** + * The name of the Google Cloud Storage bucket used for storing application data. + * Use only the bucket name without any prefixes or additions (do *not* prefix + * the name with "gs://"). + */ + storageBucket?: string; + /** + * The ID of the Google Cloud project associated with the App. + */ + projectId?: string; + /** + * An {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent} + * to be used when making outgoing HTTP calls. This Agent instance is used + * by all services that make REST calls (e.g. `auth`, `messaging`, + * `projectManagement`). + * + * Realtime Database and Firestore use other means of communicating with + * the backend servers, so they do not use this HTTP Agent. `Credential` + * instances also do not use this HTTP Agent, but instead support + * specifying an HTTP Agent in the corresponding factory methods. + */ + httpAgent?: Agent; +} +/** + * A Firebase app holds the initialization information for a collection of + * services. + */ +export interface App { + /** + * The (read-only) name for this app. + * + * The default app's name is `"[DEFAULT]"`. + * + * @example + * ```javascript + * // The default app's name is "[DEFAULT]" + * initializeApp(defaultAppConfig); + * console.log(admin.app().name); // "[DEFAULT]" + * ``` + * + * @example + * ```javascript + * // A named app's name is what you provide to initializeApp() + * const otherApp = initializeApp(otherAppConfig, "other"); + * console.log(otherApp.name); // "other" + * ``` + */ + name: string; + /** + * The (read-only) configuration options for this app. These are the original + * parameters given in {@link firebase-admin.app#initializeApp}. + * + * @example + * ```javascript + * const app = initializeApp(config); + * console.log(app.options.credential === config.credential); // true + * console.log(app.options.databaseURL === config.databaseURL); // true + * ``` + */ + options: AppOptions; +} +/** + * `FirebaseError` is a subclass of the standard JavaScript `Error` object. In + * addition to a message string and stack trace, it contains a string code. + */ +export interface FirebaseError { + /** + * Error codes are strings using the following format: `"service/string-code"`. + * Some examples include `"auth/invalid-uid"` and + * `"messaging/invalid-recipient"`. + * + * While the message for a given error can change, the code will remain the same + * between backward-compatible versions of the Firebase SDK. + */ + code: string; + /** + * An explanatory message for the error that just occurred. + * + * This message is designed to be helpful to you, the developer. Because + * it generally does not convey meaningful information to end users, + * this message should not be displayed in your application. + */ + message: string; + /** + * A string value containing the execution backtrace when the error originally + * occurred. + * + * This information can be useful for troubleshooting the cause of the error with + * {@link https://firebase.google.com/support | Firebase Support}. + */ + stack?: string; + /** + * Returns a JSON-serializable object representation of this error. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON(): object; +} +/** + * Composite type which includes both a `FirebaseError` object and an index + * which can be used to get the errored item. + * + * @example + * ```javascript + * var registrationTokens = [token1, token2, token3]; + * admin.messaging().subscribeToTopic(registrationTokens, 'topic-name') + * .then(function(response) { + * if (response.failureCount > 0) { + * console.log("Following devices unsucessfully subscribed to topic:"); + * response.errors.forEach(function(error) { + * var invalidToken = registrationTokens[error.index]; + * console.log(invalidToken, error.error); + * }); + * } else { + * console.log("All devices successfully subscribed to topic:", response); + * } + * }) + * .catch(function(error) { + * console.log("Error subscribing to topic:", error); + * }); + *``` + */ +export interface FirebaseArrayIndexError { + /** + * The index of the errored item within the original array passed as part of the + * called API method. + */ + index: number; + /** + * The error object. + */ + error: FirebaseError; +} diff --git a/node_modules/firebase-admin/lib/app/core.js b/node_modules/firebase-admin/lib/app/core.js new file mode 100644 index 0000000..0457090 --- /dev/null +++ b/node_modules/firebase-admin/lib/app/core.js @@ -0,0 +1,19 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/firebase-admin/lib/app/credential-factory.d.ts b/node_modules/firebase-admin/lib/app/credential-factory.d.ts new file mode 100644 index 0000000..577aab3 --- /dev/null +++ b/node_modules/firebase-admin/lib/app/credential-factory.d.ts @@ -0,0 +1,122 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Agent } from 'http'; +import { Credential, ServiceAccount } from './credential'; +/** + * Returns a credential created from the + * {@link https://developers.google.com/identity/protocols/application-default-credentials | + * Google Application Default Credentials} + * that grants admin access to Firebase services. This credential can be used + * in the call to {@link firebase-admin.app#initializeApp}. + * + * Google Application Default Credentials are available on any Google + * infrastructure, such as Google App Engine and Google Compute Engine. + * + * See + * {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK} + * for more details. + * + * @example + * ```javascript + * initializeApp({ + * credential: applicationDefault(), + * databaseURL: "https://.firebaseio.com" + * }); + * ``` + * + * @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent} + * to be used when retrieving access tokens from Google token servers. + * + * @returns A credential authenticated via Google + * Application Default Credentials that can be used to initialize an app. + */ +export declare function applicationDefault(httpAgent?: Agent): Credential; +/** + * Returns a credential created from the provided service account that grants + * admin access to Firebase services. This credential can be used in the call + * to {@link firebase-admin.app#initializeApp}. + * + * See + * {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK} + * for more details. + * + * @example + * ```javascript + * // Providing a path to a service account key JSON file + * const serviceAccount = require("path/to/serviceAccountKey.json"); + * initializeApp({ + * credential: cert(serviceAccount), + * databaseURL: "https://.firebaseio.com" + * }); + * ``` + * + * @example + * ```javascript + * // Providing a service account object inline + * initializeApp({ + * credential: cert({ + * projectId: "", + * clientEmail: "foo@.iam.gserviceaccount.com", + * privateKey: "-----BEGIN PRIVATE KEY----------END PRIVATE KEY-----\n" + * }), + * databaseURL: "https://.firebaseio.com" + * }); + * ``` + * + * @param serviceAccountPathOrObject - The path to a service + * account key JSON file or an object representing a service account key. + * @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent} + * to be used when retrieving access tokens from Google token servers. + * + * @returns A credential authenticated via the + * provided service account that can be used to initialize an app. + */ +export declare function cert(serviceAccountPathOrObject: string | ServiceAccount, httpAgent?: Agent): Credential; +/** + * Returns a credential created from the provided refresh token that grants + * admin access to Firebase services. This credential can be used in the call + * to {@link firebase-admin.app#initializeApp}. + * + * See + * {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK} + * for more details. + * + * @example + * ```javascript + * // Providing a path to a refresh token JSON file + * const refreshToken = require("path/to/refreshToken.json"); + * initializeApp({ + * credential: refreshToken(refreshToken), + * databaseURL: "https://.firebaseio.com" + * }); + * ``` + * + * @param refreshTokenPathOrObject - The path to a Google + * OAuth2 refresh token JSON file or an object representing a Google OAuth2 + * refresh token. + * @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent} + * to be used when retrieving access tokens from Google token servers. + * + * @returns A credential authenticated via the + * provided service account that can be used to initialize an app. + */ +export declare function refreshToken(refreshTokenPathOrObject: string | object, httpAgent?: Agent): Credential; +/** + * Clears the global ADC cache. Exported for testing. + */ +export declare function clearGlobalAppDefaultCred(): void; diff --git a/node_modules/firebase-admin/lib/app/credential-factory.js b/node_modules/firebase-admin/lib/app/credential-factory.js new file mode 100644 index 0000000..3932d2d --- /dev/null +++ b/node_modules/firebase-admin/lib/app/credential-factory.js @@ -0,0 +1,149 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.applicationDefault = applicationDefault; +exports.cert = cert; +exports.refreshToken = refreshToken; +exports.clearGlobalAppDefaultCred = clearGlobalAppDefaultCred; +const credential_internal_1 = require("./credential-internal"); +let globalAppDefaultCred; +const globalCertCreds = {}; +const globalRefreshTokenCreds = {}; +/** + * Returns a credential created from the + * {@link https://developers.google.com/identity/protocols/application-default-credentials | + * Google Application Default Credentials} + * that grants admin access to Firebase services. This credential can be used + * in the call to {@link firebase-admin.app#initializeApp}. + * + * Google Application Default Credentials are available on any Google + * infrastructure, such as Google App Engine and Google Compute Engine. + * + * See + * {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK} + * for more details. + * + * @example + * ```javascript + * initializeApp({ + * credential: applicationDefault(), + * databaseURL: "https://.firebaseio.com" + * }); + * ``` + * + * @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent} + * to be used when retrieving access tokens from Google token servers. + * + * @returns A credential authenticated via Google + * Application Default Credentials that can be used to initialize an app. + */ +function applicationDefault(httpAgent) { + if (typeof globalAppDefaultCred === 'undefined') { + globalAppDefaultCred = (0, credential_internal_1.getApplicationDefault)(httpAgent); + } + return globalAppDefaultCred; +} +/** + * Returns a credential created from the provided service account that grants + * admin access to Firebase services. This credential can be used in the call + * to {@link firebase-admin.app#initializeApp}. + * + * See + * {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK} + * for more details. + * + * @example + * ```javascript + * // Providing a path to a service account key JSON file + * const serviceAccount = require("path/to/serviceAccountKey.json"); + * initializeApp({ + * credential: cert(serviceAccount), + * databaseURL: "https://.firebaseio.com" + * }); + * ``` + * + * @example + * ```javascript + * // Providing a service account object inline + * initializeApp({ + * credential: cert({ + * projectId: "", + * clientEmail: "foo@.iam.gserviceaccount.com", + * privateKey: "-----BEGIN PRIVATE KEY----------END PRIVATE KEY-----\n" + * }), + * databaseURL: "https://.firebaseio.com" + * }); + * ``` + * + * @param serviceAccountPathOrObject - The path to a service + * account key JSON file or an object representing a service account key. + * @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent} + * to be used when retrieving access tokens from Google token servers. + * + * @returns A credential authenticated via the + * provided service account that can be used to initialize an app. + */ +function cert(serviceAccountPathOrObject, httpAgent) { + const stringifiedServiceAccount = JSON.stringify(serviceAccountPathOrObject); + if (!(stringifiedServiceAccount in globalCertCreds)) { + globalCertCreds[stringifiedServiceAccount] = new credential_internal_1.ServiceAccountCredential(serviceAccountPathOrObject, httpAgent); + } + return globalCertCreds[stringifiedServiceAccount]; +} +/** + * Returns a credential created from the provided refresh token that grants + * admin access to Firebase services. This credential can be used in the call + * to {@link firebase-admin.app#initializeApp}. + * + * See + * {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK} + * for more details. + * + * @example + * ```javascript + * // Providing a path to a refresh token JSON file + * const refreshToken = require("path/to/refreshToken.json"); + * initializeApp({ + * credential: refreshToken(refreshToken), + * databaseURL: "https://.firebaseio.com" + * }); + * ``` + * + * @param refreshTokenPathOrObject - The path to a Google + * OAuth2 refresh token JSON file or an object representing a Google OAuth2 + * refresh token. + * @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent} + * to be used when retrieving access tokens from Google token servers. + * + * @returns A credential authenticated via the + * provided service account that can be used to initialize an app. + */ +function refreshToken(refreshTokenPathOrObject, httpAgent) { + const stringifiedRefreshToken = JSON.stringify(refreshTokenPathOrObject); + if (!(stringifiedRefreshToken in globalRefreshTokenCreds)) { + globalRefreshTokenCreds[stringifiedRefreshToken] = new credential_internal_1.RefreshTokenCredential(refreshTokenPathOrObject, httpAgent); + } + return globalRefreshTokenCreds[stringifiedRefreshToken]; +} +/** + * Clears the global ADC cache. Exported for testing. + */ +function clearGlobalAppDefaultCred() { + globalAppDefaultCred = undefined; +} diff --git a/node_modules/firebase-admin/lib/app/credential-internal.d.ts b/node_modules/firebase-admin/lib/app/credential-internal.d.ts new file mode 100644 index 0000000..5426e80 --- /dev/null +++ b/node_modules/firebase-admin/lib/app/credential-internal.d.ts @@ -0,0 +1,122 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Agent } from 'http'; +import { Credential, GoogleOAuthAccessToken } from './credential'; +/** + * Implementation of ADC that uses google-auth-library-nodejs. + */ +export declare class ApplicationDefaultCredential implements Credential { + private readonly googleAuth; + private authClient; + private projectId?; + private quotaProjectId?; + private accountId?; + constructor(httpAgent?: Agent); + getAccessToken(): Promise; + getProjectId(): Promise; + getQuotaProjectId(): string | undefined; + isComputeEngineCredential(): Promise; + /** + * getIDToken returns a OIDC token from the compute metadata service + * that can be used to make authenticated calls to audience + * @param audience the URL the returned ID token will be used to call. + */ + getIDToken(audience: string): Promise; + getServiceAccountEmail(): Promise; +} +/** + * Implementation of Credential that uses a service account. + */ +export declare class ServiceAccountCredential implements Credential { + private readonly serviceAccountPathOrObject; + private readonly httpAgent?; + readonly implicit: boolean; + readonly projectId: string; + readonly privateKey: string; + readonly clientEmail: string; + private googleAuth; + private authClient; + /** + * Creates a new ServiceAccountCredential from the given parameters. + * + * @param serviceAccountPathOrObject - Service account json object or path to a service account json file. + * @param httpAgent - Optional http.Agent to use when calling the remote token server. + * @param implicit - An optional boolean indicating whether this credential was implicitly discovered from the + * environment, as opposed to being explicitly specified by the developer. + * + * @constructor + */ + constructor(serviceAccountPathOrObject: string | object, httpAgent?: Agent | undefined, implicit?: boolean); + private getGoogleAuth; + getAccessToken(): Promise; +} +/** + * Implementation of Credential that gets access tokens from refresh tokens. + */ +export declare class RefreshTokenCredential implements Credential { + private readonly refreshTokenPathOrObject; + private readonly httpAgent?; + readonly implicit: boolean; + private googleAuth; + private authClient; + /** + * Creates a new RefreshTokenCredential from the given parameters. + * + * @param refreshTokenPathOrObject - Refresh token json object or path to a refresh token + * (user credentials) json file. + * @param httpAgent - Optional http.Agent to use when calling the remote token server. + * @param implicit - An optinal boolean indicating whether this credential was implicitly + * discovered from the environment, as opposed to being explicitly specified by the developer. + * + * @constructor + */ + constructor(refreshTokenPathOrObject: string | object, httpAgent?: Agent | undefined, implicit?: boolean); + private getGoogleAuth; + getAccessToken(): Promise; +} +/** + * Implementation of Credential that uses impersonated service account. + */ +export declare class ImpersonatedServiceAccountCredential implements Credential { + private readonly impersonatedServiceAccountPathOrObject; + private readonly httpAgent?; + readonly implicit: boolean; + private googleAuth; + private authClient; + /** + * Creates a new ImpersonatedServiceAccountCredential from the given parameters. + * + * @param impersonatedServiceAccountPathOrObject - Impersonated Service account json object or + * path to a service account json file. + * @param httpAgent - Optional http.Agent to use when calling the remote token server. + * @param implicit - An optional boolean indicating whether this credential was implicitly + * discovered from the environment, as opposed to being explicitly specified by the developer. + * + * @constructor + */ + constructor(impersonatedServiceAccountPathOrObject: string | object, httpAgent?: Agent | undefined, implicit?: boolean); + private getGoogleAuth; + getAccessToken(): Promise; +} +/** + * Checks if the given credential was loaded via the application default credentials mechanism. + * + * @param credential - The credential instance to check. + */ +export declare function isApplicationDefault(credential?: Credential): boolean; +export declare function getApplicationDefault(httpAgent?: Agent): Credential; diff --git a/node_modules/firebase-admin/lib/app/credential-internal.js b/node_modules/firebase-admin/lib/app/credential-internal.js new file mode 100644 index 0000000..4dd898c --- /dev/null +++ b/node_modules/firebase-admin/lib/app/credential-internal.js @@ -0,0 +1,418 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ImpersonatedServiceAccountCredential = exports.RefreshTokenCredential = exports.ServiceAccountCredential = exports.ApplicationDefaultCredential = void 0; +exports.isApplicationDefault = isApplicationDefault; +exports.getApplicationDefault = getApplicationDefault; +const fs = require("fs"); +const google_auth_library_1 = require("google-auth-library"); +const error_1 = require("../utils/error"); +const util = require("../utils/validator"); +const SCOPES = [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/firebase.database', + 'https://www.googleapis.com/auth/firebase.messaging', + 'https://www.googleapis.com/auth/identitytoolkit', + 'https://www.googleapis.com/auth/userinfo.email', +]; +/** + * Implementation of ADC that uses google-auth-library-nodejs. + */ +class ApplicationDefaultCredential { + constructor(httpAgent) { + this.googleAuth = new google_auth_library_1.GoogleAuth({ + scopes: SCOPES, + clientOptions: { + transporterOptions: { + agent: httpAgent, + }, + }, + }); + } + async getAccessToken() { + if (!this.authClient) { + this.authClient = await this.googleAuth.getClient(); + } + await this.authClient.getAccessToken(); + const credentials = this.authClient.credentials; + this.quotaProjectId = this.authClient.quotaProjectId; + return populateCredential(credentials); + } + async getProjectId() { + if (!this.projectId) { + this.projectId = await this.googleAuth.getProjectId(); + } + return Promise.resolve(this.projectId); + } + getQuotaProjectId() { + if (!this.quotaProjectId) { + this.quotaProjectId = this.authClient?.quotaProjectId; + } + return this.quotaProjectId; + } + async isComputeEngineCredential() { + if (!this.authClient) { + this.authClient = await this.googleAuth.getClient(); + } + return Promise.resolve(this.authClient instanceof google_auth_library_1.Compute); + } + /** + * getIDToken returns a OIDC token from the compute metadata service + * that can be used to make authenticated calls to audience + * @param audience the URL the returned ID token will be used to call. + */ + async getIDToken(audience) { + if (await this.isComputeEngineCredential()) { + return this.authClient.fetchIdToken(audience); + } + else { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Credentials type should be Compute Engine Credentials.'); + } + } + async getServiceAccountEmail() { + if (this.accountId) { + return Promise.resolve(this.accountId); + } + const { client_email: clientEmail } = await this.googleAuth.getCredentials(); + this.accountId = clientEmail ?? ''; + return Promise.resolve(this.accountId); + } +} +exports.ApplicationDefaultCredential = ApplicationDefaultCredential; +/** + * Implementation of Credential that uses a service account. + */ +class ServiceAccountCredential { + /** + * Creates a new ServiceAccountCredential from the given parameters. + * + * @param serviceAccountPathOrObject - Service account json object or path to a service account json file. + * @param httpAgent - Optional http.Agent to use when calling the remote token server. + * @param implicit - An optional boolean indicating whether this credential was implicitly discovered from the + * environment, as opposed to being explicitly specified by the developer. + * + * @constructor + */ + constructor(serviceAccountPathOrObject, httpAgent, implicit = false) { + this.serviceAccountPathOrObject = serviceAccountPathOrObject; + this.httpAgent = httpAgent; + this.implicit = implicit; + const serviceAccount = (typeof serviceAccountPathOrObject === 'string') ? + ServiceAccount.fromPath(serviceAccountPathOrObject) + : new ServiceAccount(serviceAccountPathOrObject); + this.projectId = serviceAccount.projectId; + this.privateKey = serviceAccount.privateKey; + this.clientEmail = serviceAccount.clientEmail; + } + getGoogleAuth() { + if (this.googleAuth) { + return this.googleAuth; + } + const { auth, client } = populateGoogleAuth(this.serviceAccountPathOrObject, this.httpAgent); + this.googleAuth = auth; + this.authClient = client; + return this.googleAuth; + } + async getAccessToken() { + const googleAuth = this.getGoogleAuth(); + if (this.authClient === undefined) { + this.authClient = await googleAuth.getClient(); + } + await this.authClient.getAccessToken(); + const credentials = this.authClient.credentials; + return populateCredential(credentials); + } +} +exports.ServiceAccountCredential = ServiceAccountCredential; +/** + * A struct containing the properties necessary to use service account JSON credentials. + */ +class ServiceAccount { + static fromPath(filePath) { + try { + return new ServiceAccount(JSON.parse(fs.readFileSync(filePath, 'utf8'))); + } + catch (error) { + // Throw a nicely formed error message if the file contents cannot be parsed + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse service account json file: ' + error); + } + } + constructor(json) { + if (!util.isNonNullObject(json)) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Service account must be an object.'); + } + copyAttr(this, json, 'projectId', 'project_id'); + copyAttr(this, json, 'privateKey', 'private_key'); + copyAttr(this, json, 'clientEmail', 'client_email'); + let errorMessage; + if (!util.isNonEmptyString(this.projectId)) { + errorMessage = 'Service account object must contain a string "project_id" property.'; + } + else if (!util.isNonEmptyString(this.privateKey)) { + errorMessage = 'Service account object must contain a string "private_key" property.'; + } + else if (!util.isNonEmptyString(this.clientEmail)) { + errorMessage = 'Service account object must contain a string "client_email" property.'; + } + if (typeof errorMessage !== 'undefined') { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, errorMessage); + } + // eslint-disable-next-line @typescript-eslint/no-var-requires + const forge = require('node-forge'); + try { + forge.pki.privateKeyFromPem(this.privateKey); + } + catch (error) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse private key: ' + error); + } + } +} +/** + * Implementation of Credential that gets access tokens from refresh tokens. + */ +class RefreshTokenCredential { + /** + * Creates a new RefreshTokenCredential from the given parameters. + * + * @param refreshTokenPathOrObject - Refresh token json object or path to a refresh token + * (user credentials) json file. + * @param httpAgent - Optional http.Agent to use when calling the remote token server. + * @param implicit - An optinal boolean indicating whether this credential was implicitly + * discovered from the environment, as opposed to being explicitly specified by the developer. + * + * @constructor + */ + constructor(refreshTokenPathOrObject, httpAgent, implicit = false) { + this.refreshTokenPathOrObject = refreshTokenPathOrObject; + this.httpAgent = httpAgent; + this.implicit = implicit; + (typeof refreshTokenPathOrObject === 'string') ? + RefreshToken.validateFromPath(refreshTokenPathOrObject) + : RefreshToken.validateFromJSON(refreshTokenPathOrObject); + } + getGoogleAuth() { + if (this.googleAuth) { + return this.googleAuth; + } + const { auth, client } = populateGoogleAuth(this.refreshTokenPathOrObject, this.httpAgent); + this.googleAuth = auth; + this.authClient = client; + return this.googleAuth; + } + async getAccessToken() { + const googleAuth = this.getGoogleAuth(); + if (this.authClient === undefined) { + this.authClient = await googleAuth.getClient(); + } + await this.authClient.getAccessToken(); + const credentials = this.authClient.credentials; + return populateCredential(credentials); + } +} +exports.RefreshTokenCredential = RefreshTokenCredential; +class RefreshToken { + /* + * Tries to load a RefreshToken from a path. Throws if the path doesn't exist or the + * data at the path is invalid. + */ + static validateFromPath(filePath) { + try { + RefreshToken.validateFromJSON(JSON.parse(fs.readFileSync(filePath, 'utf8'))); + } + catch (error) { + // Throw a nicely formed error message if the file contents cannot be parsed + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse refresh token file: ' + error); + } + } + static validateFromJSON(json) { + const creds = { clientId: '', clientSecret: '', refreshToken: '', type: '' }; + copyAttr(creds, json, 'clientId', 'client_id'); + copyAttr(creds, json, 'clientSecret', 'client_secret'); + copyAttr(creds, json, 'refreshToken', 'refresh_token'); + copyAttr(creds, json, 'type', 'type'); + let errorMessage; + if (!util.isNonEmptyString(creds.clientId)) { + errorMessage = 'Refresh token must contain a "client_id" property.'; + } + else if (!util.isNonEmptyString(creds.clientSecret)) { + errorMessage = 'Refresh token must contain a "client_secret" property.'; + } + else if (!util.isNonEmptyString(creds.refreshToken)) { + errorMessage = 'Refresh token must contain a "refresh_token" property.'; + } + else if (!util.isNonEmptyString(creds.type)) { + errorMessage = 'Refresh token must contain a "type" property.'; + } + if (typeof errorMessage !== 'undefined') { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, errorMessage); + } + } +} +/** + * Implementation of Credential that uses impersonated service account. + */ +class ImpersonatedServiceAccountCredential { + /** + * Creates a new ImpersonatedServiceAccountCredential from the given parameters. + * + * @param impersonatedServiceAccountPathOrObject - Impersonated Service account json object or + * path to a service account json file. + * @param httpAgent - Optional http.Agent to use when calling the remote token server. + * @param implicit - An optional boolean indicating whether this credential was implicitly + * discovered from the environment, as opposed to being explicitly specified by the developer. + * + * @constructor + */ + constructor(impersonatedServiceAccountPathOrObject, httpAgent, implicit = false) { + this.impersonatedServiceAccountPathOrObject = impersonatedServiceAccountPathOrObject; + this.httpAgent = httpAgent; + this.implicit = implicit; + (typeof impersonatedServiceAccountPathOrObject === 'string') ? + ImpersonatedServiceAccount.validateFromPath(impersonatedServiceAccountPathOrObject) + : ImpersonatedServiceAccount.validateFromJSON(impersonatedServiceAccountPathOrObject); + } + getGoogleAuth() { + if (this.googleAuth) { + return this.googleAuth; + } + const { auth, client } = populateGoogleAuth(this.impersonatedServiceAccountPathOrObject, this.httpAgent); + this.googleAuth = auth; + this.authClient = client; + return this.googleAuth; + } + async getAccessToken() { + const googleAuth = this.getGoogleAuth(); + if (this.authClient === undefined) { + this.authClient = await googleAuth.getClient(); + } + await this.authClient.getAccessToken(); + const credentials = this.authClient.credentials; + return populateCredential(credentials); + } +} +exports.ImpersonatedServiceAccountCredential = ImpersonatedServiceAccountCredential; +/** + * A helper class to validate the properties necessary to use impersonated service account credentials. + */ +class ImpersonatedServiceAccount { + /* + * Tries to load a ImpersonatedServiceAccount from a path. Throws if the path doesn't exist or the + * data at the path is invalid. + */ + static validateFromPath(filePath) { + try { + ImpersonatedServiceAccount.validateFromJSON(JSON.parse(fs.readFileSync(filePath, 'utf8'))); + } + catch (error) { + // Throw a nicely formed error message if the file contents cannot be parsed + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse impersonated service account file: ' + error); + } + } + static validateFromJSON(json) { + const { client_id: clientId, client_secret: clientSecret, refresh_token: refreshToken, type } = json['source_credentials']; + let errorMessage; + if (!util.isNonEmptyString(clientId)) { + errorMessage = 'Impersonated Service Account must contain a "source_credentials.client_id" property.'; + } + else if (!util.isNonEmptyString(clientSecret)) { + errorMessage = 'Impersonated Service Account must contain a "source_credentials.client_secret" property.'; + } + else if (!util.isNonEmptyString(refreshToken)) { + errorMessage = 'Impersonated Service Account must contain a "source_credentials.refresh_token" property.'; + } + else if (!util.isNonEmptyString(type)) { + errorMessage = 'Impersonated Service Account must contain a "source_credentials.type" property.'; + } + if (typeof errorMessage !== 'undefined') { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, errorMessage); + } + } +} +/** + * Checks if the given credential was loaded via the application default credentials mechanism. + * + * @param credential - The credential instance to check. + */ +function isApplicationDefault(credential) { + return credential instanceof ApplicationDefaultCredential || + (credential instanceof RefreshTokenCredential && credential.implicit); +} +function getApplicationDefault(httpAgent) { + return new ApplicationDefaultCredential(httpAgent); +} +/** + * Copies the specified property from one object to another. + * + * If no property exists by the given "key", looks for a property identified by "alt", and copies it instead. + * This can be used to implement behaviors such as "copy property myKey or my_key". + * + * @param to - Target object to copy the property into. + * @param from - Source object to copy the property from. + * @param key - Name of the property to copy. + * @param alt - Alternative name of the property to copy. + */ +function copyAttr(to, from, key, alt) { + const tmp = from[key] || from[alt]; + if (typeof tmp !== 'undefined') { + to[key] = tmp; + } +} +/** + * Populate google-auth-library GoogleAuth credentials type. + */ +function populateGoogleAuth(keyFile, httpAgent) { + let client; + const auth = new google_auth_library_1.GoogleAuth({ + scopes: SCOPES, + clientOptions: { + transporterOptions: { + agent: httpAgent, + }, + }, + keyFile: (typeof keyFile === 'string') ? keyFile : undefined, + }); + if (typeof keyFile === 'object') { + if (!util.isNonNullObject(keyFile)) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Service account must be an object.'); + } + copyAttr(keyFile, keyFile, 'project_id', 'projectId'); + copyAttr(keyFile, keyFile, 'private_key', 'privateKey'); + copyAttr(keyFile, keyFile, 'client_email', 'clientEmail'); + client = auth.fromJSON(keyFile); + } + return { auth, client }; +} +/** + * Populate GoogleOAuthAccessToken credentials from google-auth-library Credentials type. + */ +function populateCredential(credentials) { + const accessToken = credentials?.access_token; + const expiryDate = credentials?.expiry_date; + if (typeof accessToken !== 'string') + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse Google auth credential: access_token must be a non empty string.'); + if (typeof expiryDate !== 'number') + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse Google auth credential: Invalid expiry_date.'); + return { + ...credentials, + access_token: accessToken, + // inverse operation of following + // https://github.com/googleapis/google-auth-library-nodejs/blob/5ed910513451c82e2551777a3e2212964799ef8e/src/auth/baseexternalclient.ts#L446-L446 + expires_in: Math.floor((expiryDate - new Date().getTime()) / 1000), + }; +} diff --git a/node_modules/firebase-admin/lib/app/credential.d.ts b/node_modules/firebase-admin/lib/app/credential.d.ts new file mode 100644 index 0000000..c72b708 --- /dev/null +++ b/node_modules/firebase-admin/lib/app/credential.d.ts @@ -0,0 +1,45 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface ServiceAccount { + projectId?: string; + clientEmail?: string; + privateKey?: string; +} +/** + * Interface for Google OAuth 2.0 access tokens. + */ +export interface GoogleOAuthAccessToken { + access_token: string; + expires_in: number; +} +/** + * Interface that provides Google OAuth2 access tokens used to authenticate + * with Firebase services. + * + * In most cases, you will not need to implement this yourself and can instead + * use the default implementations provided by the `firebase-admin/app` module. + */ +export interface Credential { + /** + * Returns a Google OAuth2 access token object used to authenticate with + * Firebase services. + * + * @returns A Google OAuth2 access token object. + */ + getAccessToken(): Promise; +} diff --git a/node_modules/firebase-admin/lib/app/credential.js b/node_modules/firebase-admin/lib/app/credential.js new file mode 100644 index 0000000..0457090 --- /dev/null +++ b/node_modules/firebase-admin/lib/app/credential.js @@ -0,0 +1,19 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/firebase-admin/lib/app/firebase-app.d.ts b/node_modules/firebase-admin/lib/app/firebase-app.d.ts new file mode 100644 index 0000000..b0d57cc --- /dev/null +++ b/node_modules/firebase-admin/lib/app/firebase-app.d.ts @@ -0,0 +1,53 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Credential } from './credential'; +/** + * Type representing a Firebase OAuth access token (derived from a Google OAuth2 access token) which + * can be used to authenticate to Firebase services such as the Realtime Database and Auth. + */ +export interface FirebaseAccessToken { + accessToken: string; + expirationTime: number; +} +/** + * Internals of a FirebaseApp instance. + */ +export declare class FirebaseAppInternals { + private credential_; + private cachedToken_; + private promiseToCachedToken_; + private tokenListeners_; + private isRefreshing; + constructor(credential_: Credential); + getToken(forceRefresh?: boolean): Promise; + getCachedToken(): FirebaseAccessToken | null; + private refreshToken; + private shouldRefresh; + /** + * Adds a listener that is called each time a token changes. + * + * @param listener - The listener that will be called with each new token. + */ + addAuthTokenListener(listener: (token: string) => void): void; + /** + * Removes a token listener. + * + * @param listener - The listener to remove. + */ + removeAuthTokenListener(listener: (token: string) => void): void; +} diff --git a/node_modules/firebase-admin/lib/app/firebase-app.js b/node_modules/firebase-admin/lib/app/firebase-app.js new file mode 100644 index 0000000..1911d83 --- /dev/null +++ b/node_modules/firebase-admin/lib/app/firebase-app.js @@ -0,0 +1,234 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirebaseApp = exports.FirebaseAppInternals = void 0; +const credential_internal_1 = require("./credential-internal"); +const validator = require("../utils/validator"); +const deep_copy_1 = require("../utils/deep-copy"); +const error_1 = require("../utils/error"); +const TOKEN_EXPIRY_THRESHOLD_MILLIS = 5 * 60 * 1000; +/** + * Internals of a FirebaseApp instance. + */ +class FirebaseAppInternals { + // eslint-disable-next-line @typescript-eslint/naming-convention + constructor(credential_) { + this.credential_ = credential_; + this.tokenListeners_ = []; + this.isRefreshing = false; + } + getToken(forceRefresh = false) { + if (forceRefresh || this.shouldRefresh()) { + this.promiseToCachedToken_ = this.refreshToken(); + } + return this.promiseToCachedToken_; + } + getCachedToken() { + return this.cachedToken_ || null; + } + refreshToken() { + this.isRefreshing = true; + return Promise.resolve(this.credential_.getAccessToken()) + .then((result) => { + // Since the developer can provide the credential implementation, we want to weakly verify + // the return type until the type is properly exported. + if (!validator.isNonNullObject(result) || + typeof result.expires_in !== 'number' || + typeof result.access_token !== 'string') { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, `Invalid access token generated: "${JSON.stringify(result)}". Valid access ` + + 'tokens must be an object with the "expires_in" (number) and "access_token" ' + + '(string) properties.'); + } + const token = { + accessToken: result.access_token, + expirationTime: Date.now() + (result.expires_in * 1000), + }; + if (!this.cachedToken_ + || this.cachedToken_.accessToken !== token.accessToken + || this.cachedToken_.expirationTime !== token.expirationTime) { + // Update the cache before firing listeners. Listeners may directly query the + // cached token state. + this.cachedToken_ = token; + this.tokenListeners_.forEach((listener) => { + listener(token.accessToken); + }); + } + return token; + }) + .catch((error) => { + let errorMessage = (typeof error === 'string') ? error : error.message; + errorMessage = 'Credential implementation provided to initializeApp() via the ' + + '"credential" property failed to fetch a valid Google OAuth2 access token with the ' + + `following error: "${errorMessage}".`; + if (errorMessage.indexOf('invalid_grant') !== -1) { + errorMessage += ' There are two likely causes: (1) your server time is not properly ' + + 'synced or (2) your certificate key file has been revoked. To solve (1), re-sync the ' + + 'time on your server. To solve (2), make sure the key ID for your key file is still ' + + 'present at https://console.firebase.google.com/iam-admin/serviceaccounts/project. If ' + + 'not, generate a new key file at ' + + 'https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk.'; + } + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, errorMessage); + }) + .finally(() => { + this.isRefreshing = false; + }); + } + shouldRefresh() { + return (!this.cachedToken_ || (this.cachedToken_.expirationTime - Date.now()) <= TOKEN_EXPIRY_THRESHOLD_MILLIS) + && !this.isRefreshing; + } + /** + * Adds a listener that is called each time a token changes. + * + * @param listener - The listener that will be called with each new token. + */ + addAuthTokenListener(listener) { + this.tokenListeners_.push(listener); + if (this.cachedToken_) { + listener(this.cachedToken_.accessToken); + } + } + /** + * Removes a token listener. + * + * @param listener - The listener to remove. + */ + removeAuthTokenListener(listener) { + this.tokenListeners_ = this.tokenListeners_.filter((other) => other !== listener); + } +} +exports.FirebaseAppInternals = FirebaseAppInternals; +/** + * Global context object for a collection of services using a shared authentication state. + * + * @internal + */ +class FirebaseApp { + constructor(options, name, autoInit = false, appStore) { + this.appStore = appStore; + this.services_ = {}; + this.isDeleted_ = false; + this.autoInit_ = false; + this.customCredential_ = true; + this.name_ = name; + this.options_ = (0, deep_copy_1.deepCopy)(options); + this.autoInit_ = autoInit; + if (!validator.isNonNullObject(this.options_)) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_OPTIONS, 'Invalid Firebase app options passed as the first argument to initializeApp() for the ' + + `app named "${this.name_}". Options must be a non-null object.`); + } + const hasCredential = ('credential' in this.options_); + if (!hasCredential) { + this.customCredential_ = false; + this.options_.credential = (0, credential_internal_1.getApplicationDefault)(this.options_.httpAgent); + } + const credential = this.options_.credential; + if (typeof credential !== 'object' || credential === null || typeof credential.getAccessToken !== 'function') { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_OPTIONS, 'Invalid Firebase app options passed as the first argument to initializeApp() for the ' + + `app named "${this.name_}". The "credential" property must be an object which implements ` + + 'the Credential interface.'); + } + this.INTERNAL = new FirebaseAppInternals(credential); + } + /** + * Returns the name of the FirebaseApp instance. + * + * @returns The name of the FirebaseApp instance. + */ + get name() { + this.checkDestroyed_(); + return this.name_; + } + /** + * Returns the options for the FirebaseApp instance. + * + * @returns The options for the FirebaseApp instance. + */ + get options() { + this.checkDestroyed_(); + return (0, deep_copy_1.deepCopy)(this.options_); + } + /** + * @internal + */ + getOrInitService(name, init) { + return this.ensureService_(name, () => init(this)); + } + /** + * Returns `true` if this app was initialized with auto-initialization. + * + * @internal + */ + autoInit() { + return this.autoInit_; + } + /** + * Returns `true` if the `FirebaseApp` instance was initialized with a custom + * `Credential`. + * + * @internal + */ + customCredential() { + return this.customCredential_; + } + /** + * Deletes the FirebaseApp instance. + * + * @returns An empty Promise fulfilled once the FirebaseApp instance is deleted. + */ + delete() { + this.checkDestroyed_(); + // Also remove the instance from the AppStore. This is needed to support the existing + // app.delete() use case. In the future we can remove this API, and deleteApp() will + // become the only way to tear down an App. + this.appStore?.removeApp(this.name); + return Promise.all(Object.keys(this.services_).map((serviceName) => { + const service = this.services_[serviceName]; + if (isStateful(service)) { + return service.delete(); + } + return Promise.resolve(); + })).then(() => { + this.services_ = {}; + this.isDeleted_ = true; + }); + } + // eslint-disable-next-line @typescript-eslint/naming-convention + ensureService_(serviceName, initializer) { + this.checkDestroyed_(); + if (!(serviceName in this.services_)) { + this.services_[serviceName] = initializer(); + } + return this.services_[serviceName]; + } + /** + * Throws an Error if the FirebaseApp instance has already been deleted. + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + checkDestroyed_() { + if (this.isDeleted_) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.APP_DELETED, `Firebase app named "${this.name_}" has already been deleted.`); + } + } +} +exports.FirebaseApp = FirebaseApp; +function isStateful(service) { + return typeof service.delete === 'function'; +} diff --git a/node_modules/firebase-admin/lib/app/firebase-namespace.d.ts b/node_modules/firebase-admin/lib/app/firebase-namespace.d.ts new file mode 100644 index 0000000..83e405e --- /dev/null +++ b/node_modules/firebase-admin/lib/app/firebase-namespace.d.ts @@ -0,0 +1,163 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AppStore } from './lifecycle'; +import { app, appCheck, auth, messaging, machineLearning, storage, firestore, database, instanceId, installations, projectManagement, securityRules, remoteConfig, AppOptions } from '../firebase-namespace-api'; +import { cert, refreshToken, applicationDefault } from './credential-factory'; +import App = app.App; +import AppCheck = appCheck.AppCheck; +import Auth = auth.Auth; +import Database = database.Database; +import Firestore = firestore.Firestore; +import Installations = installations.Installations; +import InstanceId = instanceId.InstanceId; +import MachineLearning = machineLearning.MachineLearning; +import Messaging = messaging.Messaging; +import ProjectManagement = projectManagement.ProjectManagement; +import RemoteConfig = remoteConfig.RemoteConfig; +import SecurityRules = securityRules.SecurityRules; +import Storage = storage.Storage; +export interface FirebaseServiceNamespace { + (app?: App): T; + [key: string]: any; +} +/** + * Internals of a FirebaseNamespace instance. + */ +export declare class FirebaseNamespaceInternals { + private readonly appStore; + constructor(appStore: AppStore); + /** + * Initializes the App instance. + * + * @param options - Optional options for the App instance. If none present will try to initialize + * from the FIREBASE_CONFIG environment variable. If the environment variable contains a string + * that starts with '{' it will be parsed as JSON, otherwise it will be assumed to be pointing + * to a file. + * @param appName - Optional name of the FirebaseApp instance. + * + * @returns A new App instance. + */ + initializeApp(options?: AppOptions, appName?: string): App; + /** + * Returns the App instance with the provided name (or the default App instance + * if no name is provided). + * + * @param appName - Optional name of the FirebaseApp instance to return. + * @returns The App instance which has the provided name. + */ + app(appName?: string): App; + get apps(): App[]; +} +/** + * Global Firebase context object. + */ +export declare class FirebaseNamespace { + __esModule: boolean; + credential: { + cert: typeof cert; + refreshToken: typeof refreshToken; + applicationDefault: typeof applicationDefault; + }; + SDK_VERSION: string; + INTERNAL: FirebaseNamespaceInternals; + Promise: any; + constructor(appStore?: AppStore); + /** + * Gets the `Auth` service namespace. The returned namespace can be used to get the + * `Auth` service for the default app or an explicitly specified app. + */ + get auth(): FirebaseServiceNamespace; + /** + * Gets the `Database` service namespace. The returned namespace can be used to get the + * `Database` service for the default app or an explicitly specified app. + */ + get database(): FirebaseServiceNamespace; + /** + * Gets the `Messaging` service namespace. The returned namespace can be used to get the + * `Messaging` service for the default app or an explicitly specified app. + */ + get messaging(): FirebaseServiceNamespace; + /** + * Gets the `Storage` service namespace. The returned namespace can be used to get the + * `Storage` service for the default app or an explicitly specified app. + */ + get storage(): FirebaseServiceNamespace; + /** + * Gets the `Firestore` service namespace. The returned namespace can be used to get the + * `Firestore` service for the default app or an explicitly specified app. + */ + get firestore(): FirebaseServiceNamespace; + /** + * Gets the `MachineLearning` service namespace. The returned namespace can be + * used to get the `MachineLearning` service for the default app or an + * explicityly specified app. + */ + get machineLearning(): FirebaseServiceNamespace; + /** + * Gets the `Installations` service namespace. The returned namespace can be used to get the + * `Installations` service for the default app or an explicitly specified app. + */ + get installations(): FirebaseServiceNamespace; + /** + * Gets the `InstanceId` service namespace. The returned namespace can be used to get the + * `Instance` service for the default app or an explicitly specified app. + */ + get instanceId(): FirebaseServiceNamespace; + /** + * Gets the `ProjectManagement` service namespace. The returned namespace can be used to get the + * `ProjectManagement` service for the default app or an explicitly specified app. + */ + get projectManagement(): FirebaseServiceNamespace; + /** + * Gets the `SecurityRules` service namespace. The returned namespace can be used to get the + * `SecurityRules` service for the default app or an explicitly specified app. + */ + get securityRules(): FirebaseServiceNamespace; + /** + * Gets the `RemoteConfig` service namespace. The returned namespace can be used to get the + * `RemoteConfig` service for the default app or an explicitly specified app. + */ + get remoteConfig(): FirebaseServiceNamespace; + /** + * Gets the `AppCheck` service namespace. The returned namespace can be used to get the + * `AppCheck` service for the default app or an explicitly specified app. + */ + get appCheck(): FirebaseServiceNamespace; + /** + * Initializes the FirebaseApp instance. + * + * @param options - Optional options for the FirebaseApp instance. + * If none present will try to initialize from the FIREBASE_CONFIG environment variable. + * If the environment variable contains a string that starts with '{' it will be parsed as JSON, + * otherwise it will be assumed to be pointing to a file. + * @param appName - Optional name of the FirebaseApp instance. + * + * @returns A new FirebaseApp instance. + */ + initializeApp(options?: AppOptions, appName?: string): App; + /** + * Returns the FirebaseApp instance with the provided name (or the default FirebaseApp instance + * if no name is provided). + * + * @param appName - Optional name of the FirebaseApp instance to return. + * @returns The FirebaseApp instance which has the provided name. + */ + app(appName?: string): App; + get apps(): App[]; + private ensureApp; +} diff --git a/node_modules/firebase-admin/lib/app/firebase-namespace.js b/node_modules/firebase-admin/lib/app/firebase-namespace.js new file mode 100644 index 0000000..cc0a1b8 --- /dev/null +++ b/node_modules/firebase-admin/lib/app/firebase-namespace.js @@ -0,0 +1,335 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultNamespace = exports.FirebaseNamespace = exports.FirebaseNamespaceInternals = void 0; +const lifecycle_1 = require("./lifecycle"); +const credential_factory_1 = require("./credential-factory"); +const index_1 = require("../utils/index"); +/** + * Internals of a FirebaseNamespace instance. + */ +class FirebaseNamespaceInternals { + constructor(appStore) { + this.appStore = appStore; + } + /** + * Initializes the App instance. + * + * @param options - Optional options for the App instance. If none present will try to initialize + * from the FIREBASE_CONFIG environment variable. If the environment variable contains a string + * that starts with '{' it will be parsed as JSON, otherwise it will be assumed to be pointing + * to a file. + * @param appName - Optional name of the FirebaseApp instance. + * + * @returns A new App instance. + */ + initializeApp(options, appName) { + const app = this.appStore.initializeApp(options, appName); + return extendApp(app); + } + /** + * Returns the App instance with the provided name (or the default App instance + * if no name is provided). + * + * @param appName - Optional name of the FirebaseApp instance to return. + * @returns The App instance which has the provided name. + */ + app(appName) { + const app = this.appStore.getApp(appName); + return extendApp(app); + } + /* + * Returns an array of all the non-deleted App instances. + */ + get apps() { + return this.appStore.getApps().map((app) => extendApp(app)); + } +} +exports.FirebaseNamespaceInternals = FirebaseNamespaceInternals; +const firebaseCredential = { + cert: credential_factory_1.cert, refreshToken: credential_factory_1.refreshToken, applicationDefault: credential_factory_1.applicationDefault +}; +/** + * Global Firebase context object. + */ +class FirebaseNamespace { + /* tslint:enable */ + constructor(appStore) { + // Hack to prevent Babel from modifying the object returned as the default admin namespace. + /* tslint:disable:variable-name */ + this.__esModule = true; + /* tslint:enable:variable-name */ + this.credential = firebaseCredential; + this.SDK_VERSION = (0, index_1.getSdkVersion)(); + /* tslint:disable */ + // TODO(jwenger): Database is the only consumer of firebase.Promise. We should update it to use + // use the native Promise and then remove this. + this.Promise = Promise; + this.INTERNAL = new FirebaseNamespaceInternals(appStore ?? new lifecycle_1.AppStore()); + } + /** + * Gets the `Auth` service namespace. The returned namespace can be used to get the + * `Auth` service for the default app or an explicitly specified app. + */ + get auth() { + const fn = (app) => { + return this.ensureApp(app).auth(); + }; + const auth = require('../auth/auth').Auth; + return Object.assign(fn, { Auth: auth }); + } + /** + * Gets the `Database` service namespace. The returned namespace can be used to get the + * `Database` service for the default app or an explicitly specified app. + */ + get database() { + const fn = (app) => { + return this.ensureApp(app).database(); + }; + // eslint-disable-next-line @typescript-eslint/no-var-requires + return Object.assign(fn, require('@firebase/database-compat/standalone')); + } + /** + * Gets the `Messaging` service namespace. The returned namespace can be used to get the + * `Messaging` service for the default app or an explicitly specified app. + */ + get messaging() { + const fn = (app) => { + return this.ensureApp(app).messaging(); + }; + const messaging = require('../messaging/messaging').Messaging; + return Object.assign(fn, { Messaging: messaging }); + } + /** + * Gets the `Storage` service namespace. The returned namespace can be used to get the + * `Storage` service for the default app or an explicitly specified app. + */ + get storage() { + const fn = (app) => { + return this.ensureApp(app).storage(); + }; + const storage = require('../storage/storage').Storage; + return Object.assign(fn, { Storage: storage }); + } + /** + * Gets the `Firestore` service namespace. The returned namespace can be used to get the + * `Firestore` service for the default app or an explicitly specified app. + */ + get firestore() { + let fn = (app) => { + return this.ensureApp(app).firestore(); + }; + // eslint-disable-next-line @typescript-eslint/no-var-requires + const firestore = require('@google-cloud/firestore'); + fn = Object.assign(fn, firestore.Firestore); + // `v1beta1` and `v1` are lazy-loaded in the Firestore SDK. We use the same trick here + // to avoid triggering this lazy-loading upon initialization. + Object.defineProperty(fn, 'v1beta1', { + get: () => { + return firestore.v1beta1; + }, + }); + Object.defineProperty(fn, 'v1', { + get: () => { + return firestore.v1; + }, + }); + return fn; + } + /** + * Gets the `MachineLearning` service namespace. The returned namespace can be + * used to get the `MachineLearning` service for the default app or an + * explicityly specified app. + */ + get machineLearning() { + const fn = (app) => { + return this.ensureApp(app).machineLearning(); + }; + const machineLearning = require('../machine-learning/machine-learning').MachineLearning; + return Object.assign(fn, { MachineLearning: machineLearning }); + } + /** + * Gets the `Installations` service namespace. The returned namespace can be used to get the + * `Installations` service for the default app or an explicitly specified app. + */ + get installations() { + const fn = (app) => { + return this.ensureApp(app).installations(); + }; + const installations = require('../installations/installations').Installations; + return Object.assign(fn, { Installations: installations }); + } + /** + * Gets the `InstanceId` service namespace. The returned namespace can be used to get the + * `Instance` service for the default app or an explicitly specified app. + */ + get instanceId() { + const fn = (app) => { + return this.ensureApp(app).instanceId(); + }; + const instanceId = require('../instance-id/instance-id').InstanceId; + return Object.assign(fn, { InstanceId: instanceId }); + } + /** + * Gets the `ProjectManagement` service namespace. The returned namespace can be used to get the + * `ProjectManagement` service for the default app or an explicitly specified app. + */ + get projectManagement() { + const fn = (app) => { + return this.ensureApp(app).projectManagement(); + }; + const projectManagement = require('../project-management/project-management').ProjectManagement; + return Object.assign(fn, { ProjectManagement: projectManagement }); + } + /** + * Gets the `SecurityRules` service namespace. The returned namespace can be used to get the + * `SecurityRules` service for the default app or an explicitly specified app. + */ + get securityRules() { + const fn = (app) => { + return this.ensureApp(app).securityRules(); + }; + const securityRules = require('../security-rules/security-rules').SecurityRules; + return Object.assign(fn, { SecurityRules: securityRules }); + } + /** + * Gets the `RemoteConfig` service namespace. The returned namespace can be used to get the + * `RemoteConfig` service for the default app or an explicitly specified app. + */ + get remoteConfig() { + const fn = (app) => { + return this.ensureApp(app).remoteConfig(); + }; + const remoteConfig = require('../remote-config/remote-config').RemoteConfig; + return Object.assign(fn, { RemoteConfig: remoteConfig }); + } + /** + * Gets the `AppCheck` service namespace. The returned namespace can be used to get the + * `AppCheck` service for the default app or an explicitly specified app. + */ + get appCheck() { + const fn = (app) => { + return this.ensureApp(app).appCheck(); + }; + const appCheck = require('../app-check/app-check').AppCheck; + return Object.assign(fn, { AppCheck: appCheck }); + } + // TODO: Change the return types to app.App in the following methods. + /** + * Initializes the FirebaseApp instance. + * + * @param options - Optional options for the FirebaseApp instance. + * If none present will try to initialize from the FIREBASE_CONFIG environment variable. + * If the environment variable contains a string that starts with '{' it will be parsed as JSON, + * otherwise it will be assumed to be pointing to a file. + * @param appName - Optional name of the FirebaseApp instance. + * + * @returns A new FirebaseApp instance. + */ + initializeApp(options, appName) { + return this.INTERNAL.initializeApp(options, appName); + } + /** + * Returns the FirebaseApp instance with the provided name (or the default FirebaseApp instance + * if no name is provided). + * + * @param appName - Optional name of the FirebaseApp instance to return. + * @returns The FirebaseApp instance which has the provided name. + */ + app(appName) { + return this.INTERNAL.app(appName); + } + /* + * Returns an array of all the non-deleted FirebaseApp instances. + */ + get apps() { + return this.INTERNAL.apps; + } + ensureApp(app) { + if (typeof app === 'undefined') { + app = this.app(); + } + return app; + } +} +exports.FirebaseNamespace = FirebaseNamespace; +/** + * In order to maintain backward compatibility, we instantiate a default namespace instance in + * this module, and delegate all app lifecycle operations to it. In a future implementation where + * the old admin namespace is no longer supported, we should remove this. + * + * @internal + */ +exports.defaultNamespace = new FirebaseNamespace(lifecycle_1.defaultAppStore); +function extendApp(app) { + const result = app; + if (result.__extended) { + return result; + } + result.auth = () => { + const fn = require('../auth/index').getAuth; + return fn(app); + }; + result.appCheck = () => { + const fn = require('../app-check/index').getAppCheck; + return fn(app); + }; + result.database = (url) => { + const fn = require('../database/index').getDatabaseWithUrl; + return fn(url, app); + }; + result.messaging = () => { + const fn = require('../messaging/index').getMessaging; + return fn(app); + }; + result.storage = () => { + const fn = require('../storage/index').getStorage; + return fn(app); + }; + result.firestore = () => { + const fn = require('../firestore/index').getFirestore; + return fn(app); + }; + result.instanceId = () => { + const fn = require('../instance-id/index').getInstanceId; + return fn(app); + }; + result.installations = () => { + const fn = require('../installations/index').getInstallations; + return fn(app); + }; + result.machineLearning = () => { + const fn = require('../machine-learning/index').getMachineLearning; + return fn(app); + }; + result.projectManagement = () => { + const fn = require('../project-management/index').getProjectManagement; + return fn(app); + }; + result.securityRules = () => { + const fn = require('../security-rules/index').getSecurityRules; + return fn(app); + }; + result.remoteConfig = () => { + const fn = require('../remote-config/index').getRemoteConfig; + return fn(app); + }; + result.__extended = true; + return result; +} diff --git a/node_modules/firebase-admin/lib/app/index.d.ts b/node_modules/firebase-admin/lib/app/index.d.ts new file mode 100644 index 0000000..534c620 --- /dev/null +++ b/node_modules/firebase-admin/lib/app/index.d.ts @@ -0,0 +1,28 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Firebase App and SDK initialization. + * + * @packageDocumentation + */ +export { App, AppOptions, FirebaseArrayIndexError, FirebaseError } from './core'; +export { initializeApp, getApp, getApps, deleteApp } from './lifecycle'; +export { Credential, ServiceAccount, GoogleOAuthAccessToken } from './credential'; +export { applicationDefault, cert, refreshToken } from './credential-factory'; +export { FirebaseAppError, AppErrorCodes } from '../utils/error'; +export declare const SDK_VERSION: string; diff --git a/node_modules/firebase-admin/lib/app/index.js b/node_modules/firebase-admin/lib/app/index.js new file mode 100644 index 0000000..f7f9395 --- /dev/null +++ b/node_modules/firebase-admin/lib/app/index.js @@ -0,0 +1,34 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SDK_VERSION = exports.AppErrorCodes = exports.FirebaseAppError = exports.refreshToken = exports.cert = exports.applicationDefault = exports.deleteApp = exports.getApps = exports.getApp = exports.initializeApp = void 0; +const utils_1 = require("../utils"); +var lifecycle_1 = require("./lifecycle"); +Object.defineProperty(exports, "initializeApp", { enumerable: true, get: function () { return lifecycle_1.initializeApp; } }); +Object.defineProperty(exports, "getApp", { enumerable: true, get: function () { return lifecycle_1.getApp; } }); +Object.defineProperty(exports, "getApps", { enumerable: true, get: function () { return lifecycle_1.getApps; } }); +Object.defineProperty(exports, "deleteApp", { enumerable: true, get: function () { return lifecycle_1.deleteApp; } }); +var credential_factory_1 = require("./credential-factory"); +Object.defineProperty(exports, "applicationDefault", { enumerable: true, get: function () { return credential_factory_1.applicationDefault; } }); +Object.defineProperty(exports, "cert", { enumerable: true, get: function () { return credential_factory_1.cert; } }); +Object.defineProperty(exports, "refreshToken", { enumerable: true, get: function () { return credential_factory_1.refreshToken; } }); +var error_1 = require("../utils/error"); +Object.defineProperty(exports, "FirebaseAppError", { enumerable: true, get: function () { return error_1.FirebaseAppError; } }); +Object.defineProperty(exports, "AppErrorCodes", { enumerable: true, get: function () { return error_1.AppErrorCodes; } }); +exports.SDK_VERSION = (0, utils_1.getSdkVersion)(); diff --git a/node_modules/firebase-admin/lib/app/lifecycle.d.ts b/node_modules/firebase-admin/lib/app/lifecycle.d.ts new file mode 100644 index 0000000..3a5ecda --- /dev/null +++ b/node_modules/firebase-admin/lib/app/lifecycle.d.ts @@ -0,0 +1,116 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App, AppOptions } from './core'; +export declare class AppStore { + private readonly appStore; + initializeApp(options?: AppOptions, appName?: string): App; + getApp(appName?: string): App; + getApps(): App[]; + deleteApp(app: App): Promise; + clearAllApps(): Promise; + /** + * Removes the specified App instance from the store. This is currently called by the + * {@link FirebaseApp.delete} method. Can be removed once the app deletion is handled + * entirely by the {@link deleteApp} top-level function. + */ + removeApp(appName: string): void; +} +export declare const defaultAppStore: AppStore; +/** + * Initializes the `App` instance. + * + * Creates a new instance of {@link App} if one doesn't exist, or returns an existing + * `App` instance if one exists with the same `appName` and `options`. + * + * Note, due to the inablity to compare `http.Agent` objects and `Credential` objects, + * this function cannot support idempotency if either of `options.httpAgent` or + * `options.credential` are defined. When either is defined, subsequent invocations will + * throw a `FirebaseAppError` instead of returning an `App` object. + * + * For example, to safely initialize an app that may already exist: + * + * ```javascript + * let app; + * try { + * app = getApp("myApp"); + * } catch (error) { + * app = initializeApp({ credential: myCredential }, "myApp"); + * } + * ``` + * + * @param options - Optional A set of {@link AppOptions} for the `App` instance. + * If not present, `initializeApp` will try to initialize with the options from the + * `FIREBASE_CONFIG` environment variable. If the environment variable contains a + * string that starts with `{` it will be parsed as JSON, otherwise it will be + * assumed to be pointing to a file. + * @param appName - Optional name of the `App` instance. + * + * @returns A new App instance, or the existing App if the instance already exists with + * the provided configuration. + * + * @throws FirebaseAppError if an `App` with the same name has already been + * initialized with a different set of `AppOptions`. + * @throws FirebaseAppError if an existing `App` exists and `options.httpAgent` + * or `options.credential` are defined. This is due to the function's inability to + * determine if the existing `App`'s `options` equate to the `options` parameter + * of this function. It's recommended to use {@link getApp} or {@link getApps} if your + * implementation uses either of these two fields in `AppOptions`. + */ +export declare function initializeApp(options?: AppOptions, appName?: string): App; +/** + * Returns an existing {@link App} instance for the provided name. If no name + * is provided the the default app name is used. + * + * @param appName - Optional name of the `App` instance. + * + * @returns An existing `App` instance that matches the name provided. + * + * @throws FirebaseAppError if no `App` exists for the given name. + * @throws FirebaseAppError if the `appName` is malformed. + */ +export declare function getApp(appName?: string): App; +/** + * A (read-only) array of all initialized apps. + * + * @returns An array containing all initialized apps. + */ +export declare function getApps(): App[]; +/** + * Renders this given `App` unusable and frees the resources of + * all associated services (though it does *not* clean up any backend + * resources). When running the SDK locally, this method + * must be called to ensure graceful termination of the process. + * + * @example + * ```javascript + * deleteApp(app) + * .then(function() { + * console.log("App deleted successfully"); + * }) + * .catch(function(error) { + * console.log("Error deleting app:", error); + * }); + * ``` + */ +export declare function deleteApp(app: App): Promise; +/** + * Constant holding the environment variable name with the default config. + * If the environment variable contains a string that starts with '{' it will be parsed as JSON, + * otherwise it will be assumed to be pointing to a file. + */ +export declare const FIREBASE_CONFIG_VAR = "FIREBASE_CONFIG"; diff --git a/node_modules/firebase-admin/lib/app/lifecycle.js b/node_modules/firebase-admin/lib/app/lifecycle.js new file mode 100644 index 0000000..afb9599 --- /dev/null +++ b/node_modules/firebase-admin/lib/app/lifecycle.js @@ -0,0 +1,277 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FIREBASE_CONFIG_VAR = exports.defaultAppStore = exports.AppStore = void 0; +exports.initializeApp = initializeApp; +exports.getApp = getApp; +exports.getApps = getApps; +exports.deleteApp = deleteApp; +const fs = require("fs"); +const validator = require("../utils/validator"); +const error_1 = require("../utils/error"); +const credential_internal_1 = require("./credential-internal"); +const firebase_app_1 = require("./firebase-app"); +const fastDeepEqual = require('fast-deep-equal'); +const DEFAULT_APP_NAME = '[DEFAULT]'; +class AppStore { + constructor() { + this.appStore = new Map(); + } + initializeApp(options, appName = DEFAULT_APP_NAME) { + validateAppNameFormat(appName); + let autoInit = false; + if (typeof options === 'undefined') { + autoInit = true; + options = loadOptionsFromEnvVar(); + options.credential = (0, credential_internal_1.getApplicationDefault)(); + } + // Check if an app already exists and, if so, ensure its `AppOptions` match + // those of this `initializeApp` request. + if (!this.appStore.has(appName)) { + const app = new firebase_app_1.FirebaseApp(options, appName, autoInit, this); + this.appStore.set(app.name, app); + return app; + } + const currentApp = this.appStore.get(appName); + // Ensure the `autoInit` state matches the existing app's. If not, throw. + if (currentApp.autoInit() !== autoInit) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_OPTIONS, `A Firebase app named "${appName}" already exists with a different configuration.`); + } + if (autoInit) { + // Auto-initialization is triggered when no options were passed to + // `initializeApp`. With no options to compare, simply return the App. + return currentApp; + } + // Ensure the options objects don't break deep equal comparisons. + validateAppOptionsSupportDeepEquals(options, currentApp); + // `FirebaseApp()` adds a synthesized `Credential` to `app.options` upon + // app construction. Run a comparison w/o `Credential` to see if the base + // configurations match. Return the existing app if so. + const currentAppOptions = { ...currentApp.options }; + delete currentAppOptions.credential; + if (!fastDeepEqual(options, currentAppOptions)) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.DUPLICATE_APP, `A Firebase app named "${appName}" already exists with a different configuration.`); + } + return currentApp; + } + getApp(appName = DEFAULT_APP_NAME) { + validateAppNameFormat(appName); + if (!this.appStore.has(appName)) { + let errorMessage = (appName === DEFAULT_APP_NAME) + ? 'The default Firebase app does not exist. ' : `Firebase app named "${appName}" does not exist. `; + errorMessage += 'Make sure you call initializeApp() before using any of the Firebase services.'; + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.NO_APP, errorMessage); + } + return this.appStore.get(appName); + } + getApps() { + // Return a copy so the caller cannot mutate the array + return Array.from(this.appStore.values()); + } + deleteApp(app) { + if (typeof app !== 'object' || app === null || !('options' in app)) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_ARGUMENT, 'Invalid app argument.'); + } + // Make sure the given app already exists. + const existingApp = getApp(app.name); + // Delegate delete operation to the App instance itself. That will also remove the App + // instance from the AppStore. + return existingApp.delete(); + } + clearAllApps() { + const promises = []; + this.getApps().forEach((app) => { + promises.push(this.deleteApp(app)); + }); + return Promise.all(promises).then(); + } + /** + * Removes the specified App instance from the store. This is currently called by the + * {@link FirebaseApp.delete} method. Can be removed once the app deletion is handled + * entirely by the {@link deleteApp} top-level function. + */ + removeApp(appName) { + this.appStore.delete(appName); + } +} +exports.AppStore = AppStore; +/** + * Validates that the `requestedOptions` and the `existingApp` options objects + * do not have fields that would break deep equals comparisons. + * + * @param requestedOptions The incoming `AppOptions` of a new `initailizeApp` + * request. + * @param existingApp An existing `FirebaseApp` with internal `options` to + * compare against. + * + * @throws FirebaseAppError if the objects cannot be deeply compared. + * + * @internal + */ +function validateAppOptionsSupportDeepEquals(requestedOptions, existingApp) { + // http.Agent checks. + if (typeof requestedOptions.httpAgent !== 'undefined') { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_OPTIONS, `Firebase app named "${existingApp.name}" already exists and initializeApp was` + + ' invoked with an optional http.Agent. The SDK cannot confirm the equality' + + ' of http.Agent objects with the existing app. Please use getApp or getApps to reuse' + + ' the existing app instead.'); + } + else if (typeof existingApp.options.httpAgent !== 'undefined') { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_OPTIONS, `An existing app named "${existingApp.name}" already exists with a different` + + ' options configuration: httpAgent.'); + } + // Credential checks. + if (typeof requestedOptions.credential !== 'undefined') { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_OPTIONS, `Firebase app named "${existingApp.name}" already exists and initializeApp was` + + ' invoked with an optional Credential. The SDK cannot confirm the equality' + + ' of Credential objects with the existing app. Please use getApp or getApps' + + ' to reuse the existing app instead.'); + } + if (existingApp.customCredential()) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_OPTIONS, `An existing app named "${existingApp.name}" already exists with a different` + + ' options configuration: Credential.'); + } +} +/** + * Checks to see if the provided appName is a non-empty string and throws if it + * is not. + * + * @param appName A string representation of an App name. + * + * @throws FirebaseAppError if appName is not of type string or is empty. + * + * @internal + */ +function validateAppNameFormat(appName) { + if (!validator.isNonEmptyString(appName)) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_NAME, `Invalid Firebase app name "${appName}" provided. App name must be a non-empty string.`); + } +} +exports.defaultAppStore = new AppStore(); +/** + * Initializes the `App` instance. + * + * Creates a new instance of {@link App} if one doesn't exist, or returns an existing + * `App` instance if one exists with the same `appName` and `options`. + * + * Note, due to the inablity to compare `http.Agent` objects and `Credential` objects, + * this function cannot support idempotency if either of `options.httpAgent` or + * `options.credential` are defined. When either is defined, subsequent invocations will + * throw a `FirebaseAppError` instead of returning an `App` object. + * + * For example, to safely initialize an app that may already exist: + * + * ```javascript + * let app; + * try { + * app = getApp("myApp"); + * } catch (error) { + * app = initializeApp({ credential: myCredential }, "myApp"); + * } + * ``` + * + * @param options - Optional A set of {@link AppOptions} for the `App` instance. + * If not present, `initializeApp` will try to initialize with the options from the + * `FIREBASE_CONFIG` environment variable. If the environment variable contains a + * string that starts with `{` it will be parsed as JSON, otherwise it will be + * assumed to be pointing to a file. + * @param appName - Optional name of the `App` instance. + * + * @returns A new App instance, or the existing App if the instance already exists with + * the provided configuration. + * + * @throws FirebaseAppError if an `App` with the same name has already been + * initialized with a different set of `AppOptions`. + * @throws FirebaseAppError if an existing `App` exists and `options.httpAgent` + * or `options.credential` are defined. This is due to the function's inability to + * determine if the existing `App`'s `options` equate to the `options` parameter + * of this function. It's recommended to use {@link getApp} or {@link getApps} if your + * implementation uses either of these two fields in `AppOptions`. + */ +function initializeApp(options, appName = DEFAULT_APP_NAME) { + return exports.defaultAppStore.initializeApp(options, appName); +} +/** + * Returns an existing {@link App} instance for the provided name. If no name + * is provided the the default app name is used. + * + * @param appName - Optional name of the `App` instance. + * + * @returns An existing `App` instance that matches the name provided. + * + * @throws FirebaseAppError if no `App` exists for the given name. + * @throws FirebaseAppError if the `appName` is malformed. + */ +function getApp(appName = DEFAULT_APP_NAME) { + return exports.defaultAppStore.getApp(appName); +} +/** + * A (read-only) array of all initialized apps. + * + * @returns An array containing all initialized apps. + */ +function getApps() { + return exports.defaultAppStore.getApps(); +} +/** + * Renders this given `App` unusable and frees the resources of + * all associated services (though it does *not* clean up any backend + * resources). When running the SDK locally, this method + * must be called to ensure graceful termination of the process. + * + * @example + * ```javascript + * deleteApp(app) + * .then(function() { + * console.log("App deleted successfully"); + * }) + * .catch(function(error) { + * console.log("Error deleting app:", error); + * }); + * ``` + */ +function deleteApp(app) { + return exports.defaultAppStore.deleteApp(app); +} +/** + * Constant holding the environment variable name with the default config. + * If the environment variable contains a string that starts with '{' it will be parsed as JSON, + * otherwise it will be assumed to be pointing to a file. + */ +exports.FIREBASE_CONFIG_VAR = 'FIREBASE_CONFIG'; +/** + * Parse the file pointed to by the FIREBASE_CONFIG_VAR, if it exists. + * Or if the FIREBASE_CONFIG_ENV contains a valid JSON object, parse it directly. + * If the environment variable contains a string that starts with '{' it will be parsed as JSON, + * otherwise it will be assumed to be pointing to a file. + */ +function loadOptionsFromEnvVar() { + const config = process.env[exports.FIREBASE_CONFIG_VAR]; + if (!validator.isNonEmptyString(config)) { + return {}; + } + try { + const contents = config.startsWith('{') ? config : fs.readFileSync(config, 'utf8'); + return JSON.parse(contents); + } + catch (error) { + // Throw a nicely formed error message if the file contents cannot be parsed + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_OPTIONS, 'Failed to parse app options file: ' + error); + } +} diff --git a/node_modules/firebase-admin/lib/auth/action-code-settings-builder.d.ts b/node_modules/firebase-admin/lib/auth/action-code-settings-builder.d.ts new file mode 100644 index 0000000..02e2aef --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/action-code-settings-builder.d.ts @@ -0,0 +1,96 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This is the interface that defines the required continue/state URL with + * optional Android and iOS bundle identifiers. + */ +export interface ActionCodeSettings { + /** + * Defines the link continue/state URL, which has different meanings in + * different contexts: + *

                            + *
                          • When the link is handled in the web action widgets, this is the deep + * link in the `continueUrl` query parameter.
                          • + *
                          • When the link is handled in the app directly, this is the `continueUrl` + * query parameter in the deep link of the Dynamic Link.
                          • + *
                          + */ + url: string; + /** + * Whether to open the link via a mobile app or a browser. + * The default is false. When set to true, the action code link is sent + * as a Universal Link or Android App Link and is opened by the app if + * installed. In the false case, the code is sent to the web widget first + * and then redirects to the app if installed. + */ + handleCodeInApp?: boolean; + /** + * Defines the iOS bundle ID. This will try to open the link in an iOS app if it + * is installed. + */ + iOS?: { + /** + * Defines the required iOS bundle ID of the app where the link should be + * handled if the application is already installed on the device. + */ + bundleId: string; + }; + /** + * Defines the Android package name. This will try to open the link in an + * android app if it is installed. If `installApp` is passed, it specifies + * whether to install the Android app if the device supports it and the app is + * not already installed. If this field is provided without a `packageName`, an + * error is thrown explaining that the `packageName` must be provided in + * conjunction with this field. If `minimumVersion` is specified, and an older + * version of the app is installed, the user is taken to the Play Store to + * upgrade the app. + */ + android?: { + /** + * Defines the required Android package name of the app where the link should be + * handled if the Android app is installed. + */ + packageName: string; + /** + * Whether to install the Android app if the device supports it and the app is + * not already installed. + */ + installApp?: boolean; + /** + * The Android minimum version if available. If the installed app is an older + * version, the user is taken to the GOogle Play Store to upgrade the app. + */ + minimumVersion?: string; + }; + /** + * Defines the dynamic link domain to use for the current link if it is to be + * opened using Firebase Dynamic Links, as multiple dynamic link domains can be + * configured per project. This field provides the ability to explicitly choose + * configured per project. This fields provides the ability explicitly choose + * one. If none is provided, the oldest domain is used by default. + * @deprecated use `linkDomain` instead + */ + dynamicLinkDomain?: string; + /** + * Defines the custom Firebase Hosting domain to use when the link is to be opened + * via a specified mobile app, + * This is a replacement of Firebase Dynamic Link. + * If none is provided, + * a default hosting domain will be used (for example, `example.firebaseapp.com`) + */ + linkDomain?: string; +} diff --git a/node_modules/firebase-admin/lib/auth/action-code-settings-builder.js b/node_modules/firebase-admin/lib/auth/action-code-settings-builder.js new file mode 100644 index 0000000..bc1ed29 --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/action-code-settings-builder.js @@ -0,0 +1,125 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ActionCodeSettingsBuilder = void 0; +const validator = require("../utils/validator"); +const error_1 = require("../utils/error"); +/** + * Defines the ActionCodeSettings builder class used to convert the + * ActionCodeSettings object to its corresponding server request. + * + * @internal + */ +class ActionCodeSettingsBuilder { + /** + * ActionCodeSettingsBuilder constructor. + * + * @param {ActionCodeSettings} actionCodeSettings The ActionCodeSettings + * object used to initiliaze this server request builder. + * @constructor + */ + constructor(actionCodeSettings) { + if (!validator.isNonNullObject(actionCodeSettings)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings" must be a non-null object.'); + } + if (typeof actionCodeSettings.url === 'undefined') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISSING_CONTINUE_URI); + } + else if (!validator.isURL(actionCodeSettings.url)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONTINUE_URI); + } + this.continueUrl = actionCodeSettings.url; + if (typeof actionCodeSettings.handleCodeInApp !== 'undefined' && + !validator.isBoolean(actionCodeSettings.handleCodeInApp)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.handleCodeInApp" must be a boolean.'); + } + this.canHandleCodeInApp = actionCodeSettings.handleCodeInApp || false; + if (typeof actionCodeSettings.dynamicLinkDomain !== 'undefined' && + !validator.isNonEmptyString(actionCodeSettings.dynamicLinkDomain)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_DYNAMIC_LINK_DOMAIN); + } + this.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain; + if (typeof actionCodeSettings.linkDomain !== 'undefined' && + !validator.isNonEmptyString(actionCodeSettings.linkDomain)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HOSTING_LINK_DOMAIN); + } + this.linkDomain = actionCodeSettings.linkDomain; + if (typeof actionCodeSettings.iOS !== 'undefined') { + if (!validator.isNonNullObject(actionCodeSettings.iOS)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.iOS" must be a valid non-null object.'); + } + else if (typeof actionCodeSettings.iOS.bundleId === 'undefined') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISSING_IOS_BUNDLE_ID); + } + else if (!validator.isNonEmptyString(actionCodeSettings.iOS.bundleId)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.iOS.bundleId" must be a valid non-empty string.'); + } + this.ibi = actionCodeSettings.iOS.bundleId; + } + if (typeof actionCodeSettings.android !== 'undefined') { + if (!validator.isNonNullObject(actionCodeSettings.android)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.android" must be a valid non-null object.'); + } + else if (typeof actionCodeSettings.android.packageName === 'undefined') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISSING_ANDROID_PACKAGE_NAME); + } + else if (!validator.isNonEmptyString(actionCodeSettings.android.packageName)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.android.packageName" must be a valid non-empty string.'); + } + else if (typeof actionCodeSettings.android.minimumVersion !== 'undefined' && + !validator.isNonEmptyString(actionCodeSettings.android.minimumVersion)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.android.minimumVersion" must be a valid non-empty string.'); + } + else if (typeof actionCodeSettings.android.installApp !== 'undefined' && + !validator.isBoolean(actionCodeSettings.android.installApp)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.android.installApp" must be a valid boolean.'); + } + this.apn = actionCodeSettings.android.packageName; + this.amv = actionCodeSettings.android.minimumVersion; + this.installApp = actionCodeSettings.android.installApp || false; + } + } + /** + * Returns the corresponding constructed server request corresponding to the + * current ActionCodeSettings. + * + * @returns The constructed EmailActionCodeRequest request. + */ + buildRequest() { + const request = { + continueUrl: this.continueUrl, + canHandleCodeInApp: this.canHandleCodeInApp, + dynamicLinkDomain: this.dynamicLinkDomain, + linkDomain: this.linkDomain, + androidPackageName: this.apn, + androidMinimumVersion: this.amv, + androidInstallApp: this.installApp, + iOSBundleId: this.ibi, + }; + // Remove all null and undefined fields from request. + for (const key in request) { + if (Object.prototype.hasOwnProperty.call(request, key)) { + if (typeof request[key] === 'undefined' || request[key] === null) { + delete request[key]; + } + } + } + return request; + } +} +exports.ActionCodeSettingsBuilder = ActionCodeSettingsBuilder; diff --git a/node_modules/firebase-admin/lib/auth/auth-api-request.d.ts b/node_modules/firebase-admin/lib/auth/auth-api-request.d.ts new file mode 100644 index 0000000..0c7d90a --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/auth-api-request.d.ts @@ -0,0 +1,185 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app/index'; +import { UserImportOptions, UserImportRecord, UserImportResult } from './user-import-builder'; +import { TenantServerResponse, CreateTenantRequest, UpdateTenantRequest } from './tenant'; +import { ProjectConfigServerResponse, UpdateProjectConfigRequest } from './project-config'; +/** List of reserved claims which cannot be provided when creating a custom token. */ +export declare const RESERVED_CLAIMS: string[]; +/** List of supported email action request types. */ +export declare const EMAIL_ACTION_REQUEST_TYPES: string[]; +/** Defines a base utility to help with resource URL construction. */ +declare class AuthResourceUrlBuilder { + protected app: App; + protected version: string; + protected urlFormat: string; + private projectId; + /** + * The resource URL builder constructor. + * + * @param projectId - The resource project ID. + * @param version - The endpoint API version. + * @constructor + */ + constructor(app: App, version?: string); + /** + * Returns the resource URL corresponding to the provided parameters. + * + * @param api - The backend API name. + * @param params - The optional additional parameters to substitute in the + * URL path. + * @returns The corresponding resource URL. + */ + getUrl(api?: string, params?: object): Promise; + private getProjectId; +} +interface BatchDeleteErrorInfo { + index?: number; + localId?: string; + message?: string; +} +export interface BatchDeleteAccountsResponse { + errors?: BatchDeleteErrorInfo[]; +} +/** + * Utility for sending requests to Auth server that are Auth instance related. This includes user, tenant, + * and project config management related APIs. This extends the BaseFirebaseAuthRequestHandler class and defines + * additional tenant management related APIs. + */ +export declare class AuthRequestHandler extends AbstractAuthRequestHandler { + protected readonly authResourceUrlBuilder: AuthResourceUrlBuilder; + /** + * The FirebaseAuthRequestHandler constructor used to initialize an instance using a FirebaseApp. + * + * @param app - The app used to fetch access tokens to sign API requests. + * @constructor + */ + constructor(app: App); + /** + * @returns A new Auth user management resource URL builder instance. + */ + protected newAuthUrlBuilder(): AuthResourceUrlBuilder; + /** + * @returns A new project config resource URL builder instance. + */ + protected newProjectConfigUrlBuilder(): AuthResourceUrlBuilder; + /** + * Get the current project's config + * @returns A promise that resolves with the project config information. + */ + getProjectConfig(): Promise; + /** + * Update the current project's config. + * @returns A promise that resolves with the project config information. + */ + updateProjectConfig(options: UpdateProjectConfigRequest): Promise; + /** + * Looks up a tenant by tenant ID. + * + * @param tenantId - The tenant identifier of the tenant to lookup. + * @returns A promise that resolves with the tenant information. + */ + getTenant(tenantId: string): Promise; + /** + * Exports the tenants (single batch only) with a size of maxResults and starting from + * the offset as specified by pageToken. + * + * @param maxResults - The page size, 1000 if undefined. This is also the maximum + * allowed limit. + * @param pageToken - The next page token. If not specified, returns tenants starting + * without any offset. Tenants are returned in the order they were created from oldest to + * newest, relative to the page token offset. + * @returns A promise that resolves with the current batch of downloaded + * tenants and the next page token if available. For the last page, an empty list of tenants + * and no page token are returned. + */ + listTenants(maxResults?: number, pageToken?: string): Promise<{ + tenants: TenantServerResponse[]; + nextPageToken?: string; + }>; + /** + * Deletes a tenant identified by a tenantId. + * + * @param tenantId - The identifier of the tenant to delete. + * @returns A promise that resolves when the tenant is deleted. + */ + deleteTenant(tenantId: string): Promise; + /** + * Creates a new tenant with the properties provided. + * + * @param tenantOptions - The properties to set on the new tenant to be created. + * @returns A promise that resolves with the newly created tenant object. + */ + createTenant(tenantOptions: CreateTenantRequest): Promise; + /** + * Updates an existing tenant with the properties provided. + * + * @param tenantId - The tenant identifier of the tenant to update. + * @param tenantOptions - The properties to update on the existing tenant. + * @returns A promise that resolves with the modified tenant object. + */ + updateTenant(tenantId: string, tenantOptions: UpdateTenantRequest): Promise; +} +/** + * Utility for sending requests to Auth server that are tenant Auth instance related. This includes user + * management related APIs for specified tenants. + * This extends the BaseFirebaseAuthRequestHandler class. + */ +export declare class TenantAwareAuthRequestHandler extends AbstractAuthRequestHandler { + private readonly tenantId; + /** + * The FirebaseTenantRequestHandler constructor used to initialize an instance using a + * FirebaseApp and a tenant ID. + * + * @param app - The app used to fetch access tokens to sign API requests. + * @param tenantId - The request handler's tenant ID. + * @constructor + */ + constructor(app: App, tenantId: string); + /** + * @returns A new Auth user management resource URL builder instance. + */ + protected newAuthUrlBuilder(): AuthResourceUrlBuilder; + /** + * @returns A new project config resource URL builder instance. + */ + protected newProjectConfigUrlBuilder(): AuthResourceUrlBuilder; + /** + * Imports the list of users provided to Firebase Auth. This is useful when + * migrating from an external authentication system without having to use the Firebase CLI SDK. + * At most, 1000 users are allowed to be imported one at a time. + * When importing a list of password users, UserImportOptions are required to be specified. + * + * Overrides the superclass methods by adding an additional check to match tenant IDs of + * imported user records if present. + * + * @param users - The list of user records to import to Firebase Auth. + * @param options - The user import options, required when the users provided + * include password credentials. + * @returns A promise that resolves when the operation completes + * with the result of the import. This includes the number of successful imports, the number + * of failed uploads and their corresponding errors. + */ + uploadAccount(users: UserImportRecord[], options?: UserImportOptions): Promise; +} +/** + * When true the SDK should communicate with the Auth Emulator for all API + * calls and also produce unsigned tokens. + */ +export declare function useEmulator(): boolean; +export {}; diff --git a/node_modules/firebase-admin/lib/auth/auth-api-request.js b/node_modules/firebase-admin/lib/auth/auth-api-request.js new file mode 100644 index 0000000..15c01b1 --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/auth-api-request.js @@ -0,0 +1,1948 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TenantAwareAuthRequestHandler = exports.AuthRequestHandler = exports.AbstractAuthRequestHandler = exports.FIREBASE_AUTH_SIGN_UP_NEW_USER = exports.FIREBASE_AUTH_SET_ACCOUNT_INFO = exports.FIREBASE_AUTH_BATCH_DELETE_ACCOUNTS = exports.FIREBASE_AUTH_DELETE_ACCOUNT = exports.FIREBASE_AUTH_GET_ACCOUNTS_INFO = exports.FIREBASE_AUTH_GET_ACCOUNT_INFO = exports.FIREBASE_AUTH_DOWNLOAD_ACCOUNT = exports.FIREBASE_AUTH_UPLOAD_ACCOUNT = exports.FIREBASE_AUTH_CREATE_SESSION_COOKIE = exports.EMAIL_ACTION_REQUEST_TYPES = exports.RESERVED_CLAIMS = void 0; +exports.useEmulator = useEmulator; +const validator = require("../utils/validator"); +const deep_copy_1 = require("../utils/deep-copy"); +const error_1 = require("../utils/error"); +const api_request_1 = require("../utils/api-request"); +const utils = require("../utils/index"); +const user_import_builder_1 = require("./user-import-builder"); +const action_code_settings_builder_1 = require("./action-code-settings-builder"); +const tenant_1 = require("./tenant"); +const identifier_1 = require("./identifier"); +const auth_config_1 = require("./auth-config"); +const project_config_1 = require("./project-config"); +/** Firebase Auth request header. */ +const FIREBASE_AUTH_HEADERS = { + 'X-Client-Version': `Node/Admin/${utils.getSdkVersion()}`, +}; +/** Firebase Auth request timeout duration in milliseconds. */ +const FIREBASE_AUTH_TIMEOUT = 25000; +/** List of reserved claims which cannot be provided when creating a custom token. */ +exports.RESERVED_CLAIMS = [ + 'acr', 'amr', 'at_hash', 'aud', 'auth_time', 'azp', 'cnf', 'c_hash', 'exp', 'iat', + 'iss', 'jti', 'nbf', 'nonce', 'sub', 'firebase', +]; +/** List of supported email action request types. */ +exports.EMAIL_ACTION_REQUEST_TYPES = [ + 'PASSWORD_RESET', 'VERIFY_EMAIL', 'EMAIL_SIGNIN', 'VERIFY_AND_CHANGE_EMAIL', +]; +/** Maximum allowed number of characters in the custom claims payload. */ +const MAX_CLAIMS_PAYLOAD_SIZE = 1000; +/** Maximum allowed number of users to batch download at one time. */ +const MAX_DOWNLOAD_ACCOUNT_PAGE_SIZE = 1000; +/** Maximum allowed number of users to batch upload at one time. */ +const MAX_UPLOAD_ACCOUNT_BATCH_SIZE = 1000; +/** Maximum allowed number of users to batch get at one time. */ +const MAX_GET_ACCOUNTS_BATCH_SIZE = 100; +/** Maximum allowed number of users to batch delete at one time. */ +const MAX_DELETE_ACCOUNTS_BATCH_SIZE = 1000; +/** Minimum allowed session cookie duration in seconds (5 minutes). */ +const MIN_SESSION_COOKIE_DURATION_SECS = 5 * 60; +/** Maximum allowed session cookie duration in seconds (2 weeks). */ +const MAX_SESSION_COOKIE_DURATION_SECS = 14 * 24 * 60 * 60; +/** Maximum allowed number of provider configurations to batch download at one time. */ +const MAX_LIST_PROVIDER_CONFIGURATION_PAGE_SIZE = 100; +/** The Firebase Auth backend base URL format. */ +const FIREBASE_AUTH_BASE_URL_FORMAT = 'https://identitytoolkit.googleapis.com/{version}/projects/{projectId}{api}'; +/** Firebase Auth base URlLformat when using the auth emultor. */ +const FIREBASE_AUTH_EMULATOR_BASE_URL_FORMAT = 'http://{host}/identitytoolkit.googleapis.com/{version}/projects/{projectId}{api}'; +/** The Firebase Auth backend multi-tenancy base URL format. */ +const FIREBASE_AUTH_TENANT_URL_FORMAT = FIREBASE_AUTH_BASE_URL_FORMAT.replace('projects/{projectId}', 'projects/{projectId}/tenants/{tenantId}'); +/** Firebase Auth base URL format when using the auth emultor with multi-tenancy. */ +const FIREBASE_AUTH_EMULATOR_TENANT_URL_FORMAT = FIREBASE_AUTH_EMULATOR_BASE_URL_FORMAT.replace('projects/{projectId}', 'projects/{projectId}/tenants/{tenantId}'); +/** Maximum allowed number of tenants to download at one time. */ +const MAX_LIST_TENANT_PAGE_SIZE = 1000; +/** + * Enum for the user write operation type. + */ +var WriteOperationType; +(function (WriteOperationType) { + WriteOperationType["Create"] = "create"; + WriteOperationType["Update"] = "update"; + WriteOperationType["Upload"] = "upload"; +})(WriteOperationType || (WriteOperationType = {})); +/** Defines a base utility to help with resource URL construction. */ +class AuthResourceUrlBuilder { + /** + * The resource URL builder constructor. + * + * @param projectId - The resource project ID. + * @param version - The endpoint API version. + * @constructor + */ + constructor(app, version = 'v1') { + this.app = app; + this.version = version; + if (useEmulator()) { + this.urlFormat = utils.formatString(FIREBASE_AUTH_EMULATOR_BASE_URL_FORMAT, { + host: emulatorHost() + }); + } + else { + this.urlFormat = FIREBASE_AUTH_BASE_URL_FORMAT; + } + } + /** + * Returns the resource URL corresponding to the provided parameters. + * + * @param api - The backend API name. + * @param params - The optional additional parameters to substitute in the + * URL path. + * @returns The corresponding resource URL. + */ + getUrl(api, params) { + return this.getProjectId() + .then((projectId) => { + const baseParams = { + version: this.version, + projectId, + api: api || '', + }; + const baseUrl = utils.formatString(this.urlFormat, baseParams); + // Substitute additional api related parameters. + return utils.formatString(baseUrl, params || {}); + }); + } + getProjectId() { + if (this.projectId) { + return Promise.resolve(this.projectId); + } + return utils.findProjectId(this.app) + .then((projectId) => { + if (!validator.isNonEmptyString(projectId)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CREDENTIAL, 'Failed to determine project ID for Auth. Initialize the ' + + 'SDK with service account credentials or set project ID as an app option. ' + + 'Alternatively set the GOOGLE_CLOUD_PROJECT environment variable.'); + } + this.projectId = projectId; + return projectId; + }); + } +} +/** Tenant aware resource builder utility. */ +class TenantAwareAuthResourceUrlBuilder extends AuthResourceUrlBuilder { + /** + * The tenant aware resource URL builder constructor. + * + * @param projectId - The resource project ID. + * @param version - The endpoint API version. + * @param tenantId - The tenant ID. + * @constructor + */ + constructor(app, version, tenantId) { + super(app, version); + this.app = app; + this.version = version; + this.tenantId = tenantId; + if (useEmulator()) { + this.urlFormat = utils.formatString(FIREBASE_AUTH_EMULATOR_TENANT_URL_FORMAT, { + host: emulatorHost() + }); + } + else { + this.urlFormat = FIREBASE_AUTH_TENANT_URL_FORMAT; + } + } + /** + * Returns the resource URL corresponding to the provided parameters. + * + * @param api - The backend API name. + * @param params - The optional additional parameters to substitute in the + * URL path. + * @returns The corresponding resource URL. + */ + getUrl(api, params) { + return super.getUrl(api, params) + .then((url) => { + return utils.formatString(url, { tenantId: this.tenantId }); + }); + } +} +/** + * Auth-specific HTTP client which uses the special "owner" token + * when communicating with the Auth Emulator. + */ +class AuthHttpClient extends api_request_1.AuthorizedHttpClient { + getToken() { + if (useEmulator()) { + return Promise.resolve('owner'); + } + return super.getToken(); + } +} +/** + * Validates an AuthFactorInfo object. All unsupported parameters + * are removed from the original request. If an invalid field is passed + * an error is thrown. + * + * @param request - The AuthFactorInfo request object. + */ +function validateAuthFactorInfo(request) { + const validKeys = { + mfaEnrollmentId: true, + displayName: true, + phoneInfo: true, + enrolledAt: true, + }; + // Remove unsupported keys from the original request. + for (const key in request) { + if (!(key in validKeys)) { + delete request[key]; + } + } + // No enrollment ID is available for signupNewUser. Use another identifier. + const authFactorInfoIdentifier = request.mfaEnrollmentId || request.phoneInfo || JSON.stringify(request); + // Enrollment uid may or may not be specified for update operations. + if (typeof request.mfaEnrollmentId !== 'undefined' && + !validator.isNonEmptyString(request.mfaEnrollmentId)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_UID, 'The second factor "uid" must be a valid non-empty string.'); + } + if (typeof request.displayName !== 'undefined' && + !validator.isString(request.displayName)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_DISPLAY_NAME, `The second factor "displayName" for "${authFactorInfoIdentifier}" must be a valid string.`); + } + // enrolledAt must be a valid UTC date string. + if (typeof request.enrolledAt !== 'undefined' && + !validator.isISODateString(request.enrolledAt)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ENROLLMENT_TIME, `The second factor "enrollmentTime" for "${authFactorInfoIdentifier}" must be a valid ` + + 'UTC date string.'); + } + // Validate required fields depending on second factor type. + if (typeof request.phoneInfo !== 'undefined') { + // phoneNumber should be a string and a valid phone number. + if (!validator.isPhoneNumber(request.phoneInfo)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PHONE_NUMBER, `The second factor "phoneNumber" for "${authFactorInfoIdentifier}" must be a non-empty ` + + 'E.164 standard compliant identifier string.'); + } + } + else { + // Invalid second factor. For example, a phone second factor may have been provided without + // a phone number. A TOTP based second factor may require a secret key, etc. + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ENROLLED_FACTORS, 'MFAInfo object provided is invalid.'); + } +} +/** + * Validates a providerUserInfo object. All unsupported parameters + * are removed from the original request. If an invalid field is passed + * an error is thrown. + * + * @param request - The providerUserInfo request object. + */ +function validateProviderUserInfo(request) { + const validKeys = { + rawId: true, + providerId: true, + email: true, + displayName: true, + photoUrl: true, + }; + // Remove invalid keys from original request. + for (const key in request) { + if (!(key in validKeys)) { + delete request[key]; + } + } + if (!validator.isNonEmptyString(request.providerId)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID); + } + if (typeof request.displayName !== 'undefined' && + typeof request.displayName !== 'string') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_DISPLAY_NAME, `The provider "displayName" for "${request.providerId}" must be a valid string.`); + } + if (!validator.isNonEmptyString(request.rawId)) { + // This is called localId on the backend but the developer specifies this as + // uid externally. So the error message should use the client facing name. + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_UID, `The provider "uid" for "${request.providerId}" must be a valid non-empty string.`); + } + // email should be a string and a valid email. + if (typeof request.email !== 'undefined' && !validator.isEmail(request.email)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_EMAIL, `The provider "email" for "${request.providerId}" must be a valid email string.`); + } + // photoUrl should be a URL. + if (typeof request.photoUrl !== 'undefined' && + !validator.isURL(request.photoUrl)) { + // This is called photoUrl on the backend but the developer specifies this as + // photoURL externally. So the error message should use the client facing name. + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PHOTO_URL, `The provider "photoURL" for "${request.providerId}" must be a valid URL string.`); + } +} +/** + * Validates a create/edit request object. All unsupported parameters + * are removed from the original request. If an invalid field is passed + * an error is thrown. + * + * @param request - The create/edit request object. + * @param writeOperationType - The write operation type. + */ +function validateCreateEditRequest(request, writeOperationType) { + const uploadAccountRequest = writeOperationType === WriteOperationType.Upload; + // Hash set of whitelisted parameters. + const validKeys = { + displayName: true, + localId: true, + email: true, + password: true, + rawPassword: true, + emailVerified: true, + photoUrl: true, + disabled: true, + disableUser: true, + deleteAttribute: true, + deleteProvider: true, + sanityCheck: true, + phoneNumber: true, + customAttributes: true, + validSince: true, + // Pass linkProviderUserInfo only for updates (i.e. not for uploads.) + linkProviderUserInfo: !uploadAccountRequest, + // Pass tenantId only for uploadAccount requests. + tenantId: uploadAccountRequest, + passwordHash: uploadAccountRequest, + salt: uploadAccountRequest, + createdAt: uploadAccountRequest, + lastLoginAt: uploadAccountRequest, + providerUserInfo: uploadAccountRequest, + mfaInfo: uploadAccountRequest, + // Only for non-uploadAccount requests. + mfa: !uploadAccountRequest, + }; + // Remove invalid keys from original request. + for (const key in request) { + if (!(key in validKeys)) { + delete request[key]; + } + } + if (typeof request.tenantId !== 'undefined' && + !validator.isNonEmptyString(request.tenantId)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_TENANT_ID); + } + // For any invalid parameter, use the external key name in the error description. + // displayName should be a string. + if (typeof request.displayName !== 'undefined' && + !validator.isString(request.displayName)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_DISPLAY_NAME); + } + if ((typeof request.localId !== 'undefined' || uploadAccountRequest) && + !validator.isUid(request.localId)) { + // This is called localId on the backend but the developer specifies this as + // uid externally. So the error message should use the client facing name. + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_UID); + } + // email should be a string and a valid email. + if (typeof request.email !== 'undefined' && !validator.isEmail(request.email)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_EMAIL); + } + // phoneNumber should be a string and a valid phone number. + if (typeof request.phoneNumber !== 'undefined' && + !validator.isPhoneNumber(request.phoneNumber)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PHONE_NUMBER); + } + // password should be a string and a minimum of 6 chars. + if (typeof request.password !== 'undefined' && + !validator.isPassword(request.password)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PASSWORD); + } + // rawPassword should be a string and a minimum of 6 chars. + if (typeof request.rawPassword !== 'undefined' && + !validator.isPassword(request.rawPassword)) { + // This is called rawPassword on the backend but the developer specifies this as + // password externally. So the error message should use the client facing name. + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PASSWORD); + } + // emailVerified should be a boolean. + if (typeof request.emailVerified !== 'undefined' && + typeof request.emailVerified !== 'boolean') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_EMAIL_VERIFIED); + } + // photoUrl should be a URL. + if (typeof request.photoUrl !== 'undefined' && + !validator.isURL(request.photoUrl)) { + // This is called photoUrl on the backend but the developer specifies this as + // photoURL externally. So the error message should use the client facing name. + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PHOTO_URL); + } + // disabled should be a boolean. + if (typeof request.disabled !== 'undefined' && + typeof request.disabled !== 'boolean') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_DISABLED_FIELD); + } + // validSince should be a number. + if (typeof request.validSince !== 'undefined' && + !validator.isNumber(request.validSince)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_TOKENS_VALID_AFTER_TIME); + } + // createdAt should be a number. + if (typeof request.createdAt !== 'undefined' && + !validator.isNumber(request.createdAt)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CREATION_TIME); + } + // lastSignInAt should be a number. + if (typeof request.lastLoginAt !== 'undefined' && + !validator.isNumber(request.lastLoginAt)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_LAST_SIGN_IN_TIME); + } + // disableUser should be a boolean. + if (typeof request.disableUser !== 'undefined' && + typeof request.disableUser !== 'boolean') { + // This is called disableUser on the backend but the developer specifies this as + // disabled externally. So the error message should use the client facing name. + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_DISABLED_FIELD); + } + // customAttributes should be stringified JSON with no blacklisted claims. + // The payload should not exceed 1KB. + if (typeof request.customAttributes !== 'undefined') { + let developerClaims; + try { + developerClaims = JSON.parse(request.customAttributes); + } + catch (error) { + // JSON parsing error. This should never happen as we stringify the claims internally. + // However, we still need to check since setAccountInfo via edit requests could pass + // this field. + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CLAIMS, error.message); + } + const invalidClaims = []; + // Check for any invalid claims. + exports.RESERVED_CLAIMS.forEach((blacklistedClaim) => { + if (Object.prototype.hasOwnProperty.call(developerClaims, blacklistedClaim)) { + invalidClaims.push(blacklistedClaim); + } + }); + // Throw an error if an invalid claim is detected. + if (invalidClaims.length > 0) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.FORBIDDEN_CLAIM, invalidClaims.length > 1 ? + `Developer claims "${invalidClaims.join('", "')}" are reserved and cannot be specified.` : + `Developer claim "${invalidClaims[0]}" is reserved and cannot be specified.`); + } + // Check claims payload does not exceed maxmimum size. + if (request.customAttributes.length > MAX_CLAIMS_PAYLOAD_SIZE) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.CLAIMS_TOO_LARGE, `Developer claims payload should not exceed ${MAX_CLAIMS_PAYLOAD_SIZE} characters.`); + } + } + // passwordHash has to be a base64 encoded string. + if (typeof request.passwordHash !== 'undefined' && + !validator.isString(request.passwordHash)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PASSWORD_HASH); + } + // salt has to be a base64 encoded string. + if (typeof request.salt !== 'undefined' && + !validator.isString(request.salt)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PASSWORD_SALT); + } + // providerUserInfo has to be an array of valid UserInfo requests. + if (typeof request.providerUserInfo !== 'undefined' && + !validator.isArray(request.providerUserInfo)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_DATA); + } + else if (validator.isArray(request.providerUserInfo)) { + request.providerUserInfo.forEach((providerUserInfoEntry) => { + validateProviderUserInfo(providerUserInfoEntry); + }); + } + // linkProviderUserInfo must be a (single) UserProvider value. + if (typeof request.linkProviderUserInfo !== 'undefined') { + validateProviderUserInfo(request.linkProviderUserInfo); + } + // mfaInfo is used for importUsers. + // mfa.enrollments is used for setAccountInfo. + // enrollments has to be an array of valid AuthFactorInfo requests. + let enrollments = null; + if (request.mfaInfo) { + enrollments = request.mfaInfo; + } + else if (request.mfa && request.mfa.enrollments) { + enrollments = request.mfa.enrollments; + } + if (enrollments) { + if (!validator.isArray(enrollments)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ENROLLED_FACTORS); + } + enrollments.forEach((authFactorInfoEntry) => { + validateAuthFactorInfo(authFactorInfoEntry); + }); + } +} +/** + * Instantiates the createSessionCookie endpoint settings. + * + * @internal + */ +exports.FIREBASE_AUTH_CREATE_SESSION_COOKIE = new api_request_1.ApiSettings(':createSessionCookie', 'POST') + // Set request validator. + .setRequestValidator((request) => { + // Validate the ID token is a non-empty string. + if (!validator.isNonEmptyString(request.idToken)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ID_TOKEN); + } + // Validate the custom session cookie duration. + if (!validator.isNumber(request.validDuration) || + request.validDuration < MIN_SESSION_COOKIE_DURATION_SECS || + request.validDuration > MAX_SESSION_COOKIE_DURATION_SECS) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_SESSION_COOKIE_DURATION); + } +}) + // Set response validator. + .setResponseValidator((response) => { + // Response should always contain the session cookie. + if (!validator.isNonEmptyString(response.sessionCookie)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR); + } +}); +/** + * Instantiates the uploadAccount endpoint settings. + * + * @internal + */ +exports.FIREBASE_AUTH_UPLOAD_ACCOUNT = new api_request_1.ApiSettings('/accounts:batchCreate', 'POST'); +/** + * Instantiates the downloadAccount endpoint settings. + * + * @internal + */ +exports.FIREBASE_AUTH_DOWNLOAD_ACCOUNT = new api_request_1.ApiSettings('/accounts:batchGet', 'GET') + // Set request validator. + .setRequestValidator((request) => { + // Validate next page token. + if (typeof request.nextPageToken !== 'undefined' && + !validator.isNonEmptyString(request.nextPageToken)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PAGE_TOKEN); + } + // Validate max results. + if (!validator.isNumber(request.maxResults) || + request.maxResults <= 0 || + request.maxResults > MAX_DOWNLOAD_ACCOUNT_PAGE_SIZE) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'Required "maxResults" must be a positive integer that does not exceed ' + + `${MAX_DOWNLOAD_ACCOUNT_PAGE_SIZE}.`); + } +}); +/** + * Instantiates the getAccountInfo endpoint settings. + * + * @internal + */ +exports.FIREBASE_AUTH_GET_ACCOUNT_INFO = new api_request_1.ApiSettings('/accounts:lookup', 'POST') + // Set request validator. + .setRequestValidator((request) => { + if (!request.localId && !request.email && !request.phoneNumber && !request.federatedUserId) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Server request is missing user identifier'); + } +}) + // Set response validator. + .setResponseValidator((response) => { + if (!response.users || !response.users.length) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.USER_NOT_FOUND); + } +}); +/** + * Instantiates the getAccountInfo endpoint settings for use when fetching info + * for multiple accounts. + * + * @internal + */ +exports.FIREBASE_AUTH_GET_ACCOUNTS_INFO = new api_request_1.ApiSettings('/accounts:lookup', 'POST') + // Set request validator. + .setRequestValidator((request) => { + if (!request.localId && !request.email && !request.phoneNumber && !request.federatedUserId) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Server request is missing user identifier'); + } +}); +/** + * Instantiates the deleteAccount endpoint settings. + * + * @internal + */ +exports.FIREBASE_AUTH_DELETE_ACCOUNT = new api_request_1.ApiSettings('/accounts:delete', 'POST') + // Set request validator. + .setRequestValidator((request) => { + if (!request.localId) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Server request is missing user identifier'); + } +}); +/** + * @internal + */ +exports.FIREBASE_AUTH_BATCH_DELETE_ACCOUNTS = new api_request_1.ApiSettings('/accounts:batchDelete', 'POST') + .setRequestValidator((request) => { + if (!request.localIds) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Server request is missing user identifiers'); + } + if (typeof request.force === 'undefined' || request.force !== true) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Server request is missing force=true field'); + } +}) + .setResponseValidator((response) => { + const errors = response.errors || []; + errors.forEach((batchDeleteErrorInfo) => { + if (typeof batchDeleteErrorInfo.index === 'undefined') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Server BatchDeleteAccountResponse is missing an errors.index field'); + } + if (!batchDeleteErrorInfo.localId) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Server BatchDeleteAccountResponse is missing an errors.localId field'); + } + // Allow the (error) message to be missing/undef. + }); +}); +/** + * Instantiates the setAccountInfo endpoint settings for updating existing accounts. + * + * @internal + */ +exports.FIREBASE_AUTH_SET_ACCOUNT_INFO = new api_request_1.ApiSettings('/accounts:update', 'POST') + // Set request validator. + .setRequestValidator((request) => { + // localId is a required parameter. + if (typeof request.localId === 'undefined') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Server request is missing user identifier'); + } + // Throw error when tenantId is passed in POST body. + if (typeof request.tenantId !== 'undefined') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"tenantId" is an invalid "UpdateRequest" property.'); + } + validateCreateEditRequest(request, WriteOperationType.Update); +}) + // Set response validator. + .setResponseValidator((response) => { + // If the localId is not returned, then the request failed. + if (!response.localId) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.USER_NOT_FOUND); + } +}); +/** + * Instantiates the signupNewUser endpoint settings for creating a new user with or without + * uid being specified. The backend will create a new one if not provided and return it. + * + * @internal + */ +exports.FIREBASE_AUTH_SIGN_UP_NEW_USER = new api_request_1.ApiSettings('/accounts', 'POST') + // Set request validator. + .setRequestValidator((request) => { + // signupNewUser does not support customAttributes. + if (typeof request.customAttributes !== 'undefined') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"customAttributes" cannot be set when creating a new user.'); + } + // signupNewUser does not support validSince. + if (typeof request.validSince !== 'undefined') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"validSince" cannot be set when creating a new user.'); + } + // Throw error when tenantId is passed in POST body. + if (typeof request.tenantId !== 'undefined') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"tenantId" is an invalid "CreateRequest" property.'); + } + validateCreateEditRequest(request, WriteOperationType.Create); +}) + // Set response validator. + .setResponseValidator((response) => { + // If the localId is not returned, then the request failed. + if (!response.localId) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Unable to create new user'); + } +}); +const FIREBASE_AUTH_GET_OOB_CODE = new api_request_1.ApiSettings('/accounts:sendOobCode', 'POST') + // Set request validator. + .setRequestValidator((request) => { + if (!validator.isEmail(request.email)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_EMAIL); + } + if (typeof request.newEmail !== 'undefined' && !validator.isEmail(request.newEmail)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_NEW_EMAIL); + } + if (exports.EMAIL_ACTION_REQUEST_TYPES.indexOf(request.requestType) === -1) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, `"${request.requestType}" is not a supported email action request type.`); + } +}) + // Set response validator. + .setResponseValidator((response) => { + // If the oobLink is not returned, then the request failed. + if (!response.oobLink) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Unable to create the email action link'); + } +}); +/** + * Instantiates the retrieve OIDC configuration endpoint settings. + * + * @internal + */ +const GET_OAUTH_IDP_CONFIG = new api_request_1.ApiSettings('/oauthIdpConfigs/{providerId}', 'GET') + // Set response validator. + .setResponseValidator((response) => { + // Response should always contain the OIDC provider resource name. + if (!validator.isNonEmptyString(response.name)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Unable to get OIDC configuration'); + } +}); +/** + * Instantiates the delete OIDC configuration endpoint settings. + * + * @internal + */ +const DELETE_OAUTH_IDP_CONFIG = new api_request_1.ApiSettings('/oauthIdpConfigs/{providerId}', 'DELETE'); +/** + * Instantiates the create OIDC configuration endpoint settings. + * + * @internal + */ +const CREATE_OAUTH_IDP_CONFIG = new api_request_1.ApiSettings('/oauthIdpConfigs?oauthIdpConfigId={providerId}', 'POST') + // Set response validator. + .setResponseValidator((response) => { + // Response should always contain the OIDC provider resource name. + if (!validator.isNonEmptyString(response.name)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Unable to create new OIDC configuration'); + } +}); +/** + * Instantiates the update OIDC configuration endpoint settings. + * + * @internal + */ +const UPDATE_OAUTH_IDP_CONFIG = new api_request_1.ApiSettings('/oauthIdpConfigs/{providerId}?updateMask={updateMask}', 'PATCH') + // Set response validator. + .setResponseValidator((response) => { + // Response should always contain the configuration resource name. + if (!validator.isNonEmptyString(response.name)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Unable to update OIDC configuration'); + } +}); +/** + * Instantiates the list OIDC configuration endpoint settings. + * + * @internal + */ +const LIST_OAUTH_IDP_CONFIGS = new api_request_1.ApiSettings('/oauthIdpConfigs', 'GET') + // Set request validator. + .setRequestValidator((request) => { + // Validate next page token. + if (typeof request.pageToken !== 'undefined' && + !validator.isNonEmptyString(request.pageToken)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PAGE_TOKEN); + } + // Validate max results. + if (!validator.isNumber(request.pageSize) || + request.pageSize <= 0 || + request.pageSize > MAX_LIST_PROVIDER_CONFIGURATION_PAGE_SIZE) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'Required "maxResults" must be a positive integer that does not exceed ' + + `${MAX_LIST_PROVIDER_CONFIGURATION_PAGE_SIZE}.`); + } +}); +/** + * Instantiates the retrieve SAML configuration endpoint settings. + * + * @internal + */ +const GET_INBOUND_SAML_CONFIG = new api_request_1.ApiSettings('/inboundSamlConfigs/{providerId}', 'GET') + // Set response validator. + .setResponseValidator((response) => { + // Response should always contain the SAML provider resource name. + if (!validator.isNonEmptyString(response.name)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Unable to get SAML configuration'); + } +}); +/** + * Instantiates the delete SAML configuration endpoint settings. + * + * @internal + */ +const DELETE_INBOUND_SAML_CONFIG = new api_request_1.ApiSettings('/inboundSamlConfigs/{providerId}', 'DELETE'); +/** + * Instantiates the create SAML configuration endpoint settings. + * + * @internal + */ +const CREATE_INBOUND_SAML_CONFIG = new api_request_1.ApiSettings('/inboundSamlConfigs?inboundSamlConfigId={providerId}', 'POST') + // Set response validator. + .setResponseValidator((response) => { + // Response should always contain the SAML provider resource name. + if (!validator.isNonEmptyString(response.name)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Unable to create new SAML configuration'); + } +}); +/** + * Instantiates the update SAML configuration endpoint settings. + * + * @internal + */ +const UPDATE_INBOUND_SAML_CONFIG = new api_request_1.ApiSettings('/inboundSamlConfigs/{providerId}?updateMask={updateMask}', 'PATCH') + // Set response validator. + .setResponseValidator((response) => { + // Response should always contain the configuration resource name. + if (!validator.isNonEmptyString(response.name)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Unable to update SAML configuration'); + } +}); +/** + * Instantiates the list SAML configuration endpoint settings. + * + * @internal + */ +const LIST_INBOUND_SAML_CONFIGS = new api_request_1.ApiSettings('/inboundSamlConfigs', 'GET') + // Set request validator. + .setRequestValidator((request) => { + // Validate next page token. + if (typeof request.pageToken !== 'undefined' && + !validator.isNonEmptyString(request.pageToken)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PAGE_TOKEN); + } + // Validate max results. + if (!validator.isNumber(request.pageSize) || + request.pageSize <= 0 || + request.pageSize > MAX_LIST_PROVIDER_CONFIGURATION_PAGE_SIZE) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'Required "maxResults" must be a positive integer that does not exceed ' + + `${MAX_LIST_PROVIDER_CONFIGURATION_PAGE_SIZE}.`); + } +}); +/** + * Class that provides the mechanism to send requests to the Firebase Auth backend endpoints. + * + * @internal + */ +class AbstractAuthRequestHandler { + /** + * @param response - The response to check for errors. + * @returns The error code if present; null otherwise. + */ + static getErrorCode(response) { + return (validator.isNonNullObject(response) && response.error && response.error.message) || null; + } + static addUidToRequest(id, request) { + if (!validator.isUid(id.uid)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_UID); + } + request.localId ? request.localId.push(id.uid) : request.localId = [id.uid]; + return request; + } + static addEmailToRequest(id, request) { + if (!validator.isEmail(id.email)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_EMAIL); + } + request.email ? request.email.push(id.email) : request.email = [id.email]; + return request; + } + static addPhoneToRequest(id, request) { + if (!validator.isPhoneNumber(id.phoneNumber)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PHONE_NUMBER); + } + request.phoneNumber ? request.phoneNumber.push(id.phoneNumber) : request.phoneNumber = [id.phoneNumber]; + return request; + } + static addProviderToRequest(id, request) { + if (!validator.isNonEmptyString(id.providerId)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID); + } + if (!validator.isNonEmptyString(id.providerUid)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_UID); + } + const federatedUserId = { + providerId: id.providerId, + rawId: id.providerUid, + }; + request.federatedUserId + ? request.federatedUserId.push(federatedUserId) + : request.federatedUserId = [federatedUserId]; + return request; + } + /** + * @param app - The app used to fetch access tokens to sign API requests. + * @constructor + */ + constructor(app) { + this.app = app; + if (typeof app !== 'object' || app === null || !('options' in app)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'First argument passed to admin.auth() must be a valid Firebase app instance.'); + } + this.httpClient = new AuthHttpClient(app); + } + /** + * Creates a new Firebase session cookie with the specified duration that can be used for + * session management (set as a server side session cookie with custom cookie policy). + * The session cookie JWT will have the same payload claims as the provided ID token. + * + * @param idToken - The Firebase ID token to exchange for a session cookie. + * @param expiresIn - The session cookie duration in milliseconds. + * + * @returns A promise that resolves on success with the created session cookie. + */ + createSessionCookie(idToken, expiresIn) { + const request = { + idToken, + // Convert to seconds. + validDuration: Math.floor(expiresIn / 1000), + }; + return this.invokeRequestHandler(this.getAuthUrlBuilder(), exports.FIREBASE_AUTH_CREATE_SESSION_COOKIE, request) + .then((response) => response.sessionCookie); + } + /** + * Looks up a user by uid. + * + * @param uid - The uid of the user to lookup. + * @returns A promise that resolves with the user information. + */ + getAccountInfoByUid(uid) { + if (!validator.isUid(uid)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_UID)); + } + const request = { + localId: [uid], + }; + return this.invokeRequestHandler(this.getAuthUrlBuilder(), exports.FIREBASE_AUTH_GET_ACCOUNT_INFO, request); + } + /** + * Looks up a user by email. + * + * @param email - The email of the user to lookup. + * @returns A promise that resolves with the user information. + */ + getAccountInfoByEmail(email) { + if (!validator.isEmail(email)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_EMAIL)); + } + const request = { + email: [email], + }; + return this.invokeRequestHandler(this.getAuthUrlBuilder(), exports.FIREBASE_AUTH_GET_ACCOUNT_INFO, request); + } + /** + * Looks up a user by phone number. + * + * @param phoneNumber - The phone number of the user to lookup. + * @returns A promise that resolves with the user information. + */ + getAccountInfoByPhoneNumber(phoneNumber) { + if (!validator.isPhoneNumber(phoneNumber)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PHONE_NUMBER)); + } + const request = { + phoneNumber: [phoneNumber], + }; + return this.invokeRequestHandler(this.getAuthUrlBuilder(), exports.FIREBASE_AUTH_GET_ACCOUNT_INFO, request); + } + getAccountInfoByFederatedUid(providerId, rawId) { + if (!validator.isNonEmptyString(providerId) || !validator.isNonEmptyString(rawId)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID); + } + const request = { + federatedUserId: [{ + providerId, + rawId, + }], + }; + return this.invokeRequestHandler(this.getAuthUrlBuilder(), exports.FIREBASE_AUTH_GET_ACCOUNT_INFO, request); + } + /** + * Looks up multiple users by their identifiers (uid, email, etc). + * + * @param identifiers - The identifiers indicating the users + * to be looked up. Must have <= 100 entries. + * @param A - promise that resolves with the set of successfully + * looked up users. Possibly empty if no users were looked up. + */ + getAccountInfoByIdentifiers(identifiers) { + if (identifiers.length === 0) { + return Promise.resolve({ users: [] }); + } + else if (identifiers.length > MAX_GET_ACCOUNTS_BATCH_SIZE) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MAXIMUM_USER_COUNT_EXCEEDED, '`identifiers` parameter must have <= ' + MAX_GET_ACCOUNTS_BATCH_SIZE + ' entries.'); + } + let request = {}; + for (const id of identifiers) { + if ((0, identifier_1.isUidIdentifier)(id)) { + request = AbstractAuthRequestHandler.addUidToRequest(id, request); + } + else if ((0, identifier_1.isEmailIdentifier)(id)) { + request = AbstractAuthRequestHandler.addEmailToRequest(id, request); + } + else if ((0, identifier_1.isPhoneIdentifier)(id)) { + request = AbstractAuthRequestHandler.addPhoneToRequest(id, request); + } + else if ((0, identifier_1.isProviderIdentifier)(id)) { + request = AbstractAuthRequestHandler.addProviderToRequest(id, request); + } + else { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'Unrecognized identifier: ' + id); + } + } + return this.invokeRequestHandler(this.getAuthUrlBuilder(), exports.FIREBASE_AUTH_GET_ACCOUNTS_INFO, request); + } + /** + * Exports the users (single batch only) with a size of maxResults and starting from + * the offset as specified by pageToken. + * + * @param maxResults - The page size, 1000 if undefined. This is also the maximum + * allowed limit. + * @param pageToken - The next page token. If not specified, returns users starting + * without any offset. Users are returned in the order they were created from oldest to + * newest, relative to the page token offset. + * @returns A promise that resolves with the current batch of downloaded + * users and the next page token if available. For the last page, an empty list of users + * and no page token are returned. + */ + downloadAccount(maxResults = MAX_DOWNLOAD_ACCOUNT_PAGE_SIZE, pageToken) { + // Construct request. + const request = { + maxResults, + nextPageToken: pageToken, + }; + // Remove next page token if not provided. + if (typeof request.nextPageToken === 'undefined') { + delete request.nextPageToken; + } + return this.invokeRequestHandler(this.getAuthUrlBuilder(), exports.FIREBASE_AUTH_DOWNLOAD_ACCOUNT, request) + .then((response) => { + // No more users available. + if (!response.users) { + response.users = []; + } + return response; + }); + } + /** + * Imports the list of users provided to Firebase Auth. This is useful when + * migrating from an external authentication system without having to use the Firebase CLI SDK. + * At most, 1000 users are allowed to be imported one at a time. + * When importing a list of password users, UserImportOptions are required to be specified. + * + * @param users - The list of user records to import to Firebase Auth. + * @param options - The user import options, required when the users provided + * include password credentials. + * @returns A promise that resolves when the operation completes + * with the result of the import. This includes the number of successful imports, the number + * of failed uploads and their corresponding errors. + */ + uploadAccount(users, options) { + // This will throw if any error is detected in the hash options. + // For errors in the list of users, this will not throw and will report the errors and the + // corresponding user index in the user import generated response below. + // No need to validate raw request or raw response as this is done in UserImportBuilder. + const userImportBuilder = new user_import_builder_1.UserImportBuilder(users, options, (userRequest) => { + // Pass true to validate the uploadAccount specific fields. + validateCreateEditRequest(userRequest, WriteOperationType.Upload); + }); + const request = userImportBuilder.buildRequest(); + // Fail quickly if more users than allowed are to be imported. + if (validator.isArray(users) && users.length > MAX_UPLOAD_ACCOUNT_BATCH_SIZE) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MAXIMUM_USER_COUNT_EXCEEDED, `A maximum of ${MAX_UPLOAD_ACCOUNT_BATCH_SIZE} users can be imported at once.`); + } + // If no remaining user in request after client side processing, there is no need + // to send the request to the server. + if (!request.users || request.users.length === 0) { + return Promise.resolve(userImportBuilder.buildResponse([])); + } + return this.invokeRequestHandler(this.getAuthUrlBuilder(), exports.FIREBASE_AUTH_UPLOAD_ACCOUNT, request) + .then((response) => { + // No error object is returned if no error encountered. + const failedUploads = (response.error || []); + // Rewrite response as UserImportResult and re-insert client previously detected errors. + return userImportBuilder.buildResponse(failedUploads); + }); + } + /** + * Deletes an account identified by a uid. + * + * @param uid - The uid of the user to delete. + * @returns A promise that resolves when the user is deleted. + */ + deleteAccount(uid) { + if (!validator.isUid(uid)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_UID)); + } + const request = { + localId: uid, + }; + return this.invokeRequestHandler(this.getAuthUrlBuilder(), exports.FIREBASE_AUTH_DELETE_ACCOUNT, request); + } + deleteAccounts(uids, force) { + if (uids.length === 0) { + return Promise.resolve({}); + } + else if (uids.length > MAX_DELETE_ACCOUNTS_BATCH_SIZE) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MAXIMUM_USER_COUNT_EXCEEDED, '`uids` parameter must have <= ' + MAX_DELETE_ACCOUNTS_BATCH_SIZE + ' entries.'); + } + const request = { + localIds: [], + force, + }; + uids.forEach((uid) => { + if (!validator.isUid(uid)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_UID); + } + request.localIds.push(uid); + }); + return this.invokeRequestHandler(this.getAuthUrlBuilder(), exports.FIREBASE_AUTH_BATCH_DELETE_ACCOUNTS, request); + } + /** + * Sets additional developer claims on an existing user identified by provided UID. + * + * @param uid - The user to edit. + * @param customUserClaims - The developer claims to set. + * @returns A promise that resolves when the operation completes + * with the user id that was edited. + */ + setCustomUserClaims(uid, customUserClaims) { + // Validate user UID. + if (!validator.isUid(uid)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_UID)); + } + else if (!validator.isObject(customUserClaims)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'CustomUserClaims argument must be an object or null.')); + } + // Delete operation. Replace null with an empty object. + if (customUserClaims === null) { + customUserClaims = {}; + } + // Construct custom user attribute editting request. + const request = { + localId: uid, + customAttributes: JSON.stringify(customUserClaims), + }; + return this.invokeRequestHandler(this.getAuthUrlBuilder(), exports.FIREBASE_AUTH_SET_ACCOUNT_INFO, request) + .then((response) => { + return response.localId; + }); + } + /** + * Edits an existing user. + * + * @param uid - The user to edit. + * @param properties - The properties to set on the user. + * @returns A promise that resolves when the operation completes + * with the user id that was edited. + */ + updateExistingAccount(uid, properties) { + if (!validator.isUid(uid)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_UID)); + } + else if (!validator.isNonNullObject(properties)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'Properties argument must be a non-null object.')); + } + else if (validator.isNonNullObject(properties.providerToLink)) { + // TODO(rsgowman): These checks overlap somewhat with + // validateProviderUserInfo. It may be possible to refactor a bit. + if (!validator.isNonEmptyString(properties.providerToLink.providerId)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'providerToLink.providerId of properties argument must be a non-empty string.'); + } + if (!validator.isNonEmptyString(properties.providerToLink.uid)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'providerToLink.uid of properties argument must be a non-empty string.'); + } + } + else if (typeof properties.providersToUnlink !== 'undefined') { + if (!validator.isArray(properties.providersToUnlink)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'providersToUnlink of properties argument must be an array of strings.'); + } + properties.providersToUnlink.forEach((providerId) => { + if (!validator.isNonEmptyString(providerId)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'providersToUnlink of properties argument must be an array of strings.'); + } + }); + } + // Build the setAccountInfo request. + const request = (0, deep_copy_1.deepCopy)(properties); + request.localId = uid; + // For deleting displayName or photoURL, these values must be passed as null. + // They will be removed from the backend request and an additional parameter + // deleteAttribute: ['PHOTO_URL', 'DISPLAY_NAME'] + // with an array of the parameter names to delete will be passed. + // Parameters that are deletable and their deleteAttribute names. + // Use client facing names, photoURL instead of photoUrl. + const deletableParams = { + displayName: 'DISPLAY_NAME', + photoURL: 'PHOTO_URL', + }; + // Properties to delete if available. + request.deleteAttribute = []; + for (const key in deletableParams) { + if (request[key] === null) { + // Add property identifier to list of attributes to delete. + request.deleteAttribute.push(deletableParams[key]); + // Remove property from request. + delete request[key]; + } + } + if (request.deleteAttribute.length === 0) { + delete request.deleteAttribute; + } + // For deleting phoneNumber, this value must be passed as null. + // It will be removed from the backend request and an additional parameter + // deleteProvider: ['phone'] with an array of providerIds (phone in this case), + // will be passed. + if (request.phoneNumber === null) { + request.deleteProvider ? request.deleteProvider.push('phone') : request.deleteProvider = ['phone']; + delete request.phoneNumber; + } + if (typeof (request.providerToLink) !== 'undefined') { + request.linkProviderUserInfo = (0, deep_copy_1.deepCopy)(request.providerToLink); + delete request.providerToLink; + request.linkProviderUserInfo.rawId = request.linkProviderUserInfo.uid; + delete request.linkProviderUserInfo.uid; + } + if (typeof (request.providersToUnlink) !== 'undefined') { + if (!validator.isArray(request.deleteProvider)) { + request.deleteProvider = []; + } + request.deleteProvider = request.deleteProvider.concat(request.providersToUnlink); + delete request.providersToUnlink; + } + // Rewrite photoURL to photoUrl. + if (typeof request.photoURL !== 'undefined') { + request.photoUrl = request.photoURL; + delete request.photoURL; + } + // Rewrite disabled to disableUser. + if (typeof request.disabled !== 'undefined') { + request.disableUser = request.disabled; + delete request.disabled; + } + // Construct mfa related user data. + if (validator.isNonNullObject(request.multiFactor)) { + if (request.multiFactor.enrolledFactors === null) { + // Remove all second factors. + request.mfa = {}; + } + else if (validator.isArray(request.multiFactor.enrolledFactors)) { + request.mfa = { + enrollments: [], + }; + try { + request.multiFactor.enrolledFactors.forEach((multiFactorInfo) => { + request.mfa.enrollments.push((0, user_import_builder_1.convertMultiFactorInfoToServerFormat)(multiFactorInfo)); + }); + } + catch (e) { + return Promise.reject(e); + } + if (request.mfa.enrollments.length === 0) { + delete request.mfa.enrollments; + } + } + delete request.multiFactor; + } + return this.invokeRequestHandler(this.getAuthUrlBuilder(), exports.FIREBASE_AUTH_SET_ACCOUNT_INFO, request) + .then((response) => { + return response.localId; + }); + } + /** + * Revokes all refresh tokens for the specified user identified by the uid provided. + * In addition to revoking all refresh tokens for a user, all ID tokens issued + * before revocation will also be revoked on the Auth backend. Any request with an + * ID token generated before revocation will be rejected with a token expired error. + * Note that due to the fact that the timestamp is stored in seconds, any tokens minted in + * the same second as the revocation will still be valid. If there is a chance that a token + * was minted in the last second, delay for 1 second before revoking. + * + * @param uid - The user whose tokens are to be revoked. + * @returns A promise that resolves when the operation completes + * successfully with the user id of the corresponding user. + */ + revokeRefreshTokens(uid) { + // Validate user UID. + if (!validator.isUid(uid)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_UID)); + } + const request = { + localId: uid, + // validSince is in UTC seconds. + validSince: Math.floor(new Date().getTime() / 1000), + }; + return this.invokeRequestHandler(this.getAuthUrlBuilder(), exports.FIREBASE_AUTH_SET_ACCOUNT_INFO, request) + .then((response) => { + return response.localId; + }); + } + /** + * Create a new user with the properties supplied. + * + * @param properties - The properties to set on the user. + * @returns A promise that resolves when the operation completes + * with the user id that was created. + */ + createNewAccount(properties) { + if (!validator.isNonNullObject(properties)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'Properties argument must be a non-null object.')); + } + const request = (0, deep_copy_1.deepCopy)(properties); + // Rewrite photoURL to photoUrl. + if (typeof request.photoURL !== 'undefined') { + request.photoUrl = request.photoURL; + delete request.photoURL; + } + // Rewrite uid to localId if it exists. + if (typeof request.uid !== 'undefined') { + request.localId = request.uid; + delete request.uid; + } + // Construct mfa related user data. + if (validator.isNonNullObject(request.multiFactor)) { + if (validator.isNonEmptyArray(request.multiFactor.enrolledFactors)) { + const mfaInfo = []; + try { + request.multiFactor.enrolledFactors.forEach((multiFactorInfo) => { + // Enrollment time and uid are not allowed for signupNewUser endpoint. + // They will automatically be provisioned server side. + if ('enrollmentTime' in multiFactorInfo) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"enrollmentTime" is not supported when adding second factors via "createUser()"'); + } + else if ('uid' in multiFactorInfo) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"uid" is not supported when adding second factors via "createUser()"'); + } + mfaInfo.push((0, user_import_builder_1.convertMultiFactorInfoToServerFormat)(multiFactorInfo)); + }); + } + catch (e) { + return Promise.reject(e); + } + request.mfaInfo = mfaInfo; + } + delete request.multiFactor; + } + return this.invokeRequestHandler(this.getAuthUrlBuilder(), exports.FIREBASE_AUTH_SIGN_UP_NEW_USER, request) + .then((response) => { + // Return the user id. + return response.localId; + }); + } + /** + * Generates the out of band email action link for the email specified using the action code settings provided. + * Returns a promise that resolves with the generated link. + * + * @param requestType - The request type. This could be either used for password reset, + * email verification, email link sign-in. + * @param email - The email of the user the link is being sent to. + * @param actionCodeSettings - The optional action code setings which defines whether + * the link is to be handled by a mobile app and the additional state information to be passed in the + * deep link, etc. Required when requestType === 'EMAIL_SIGNIN' + * @param newEmail - The email address the account is being updated to. + * Required only for VERIFY_AND_CHANGE_EMAIL requests. + * @returns A promise that resolves with the email action link. + */ + getEmailActionLink(requestType, email, actionCodeSettings, newEmail) { + let request = { + requestType, + email, + returnOobLink: true, + ...(typeof newEmail !== 'undefined') && { newEmail }, + }; + // ActionCodeSettings required for email link sign-in to determine the url where the sign-in will + // be completed. + if (typeof actionCodeSettings === 'undefined' && requestType === 'EMAIL_SIGNIN') { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "`actionCodeSettings` is required when `requestType` === 'EMAIL_SIGNIN'")); + } + if (typeof actionCodeSettings !== 'undefined' || requestType === 'EMAIL_SIGNIN') { + try { + const builder = new action_code_settings_builder_1.ActionCodeSettingsBuilder(actionCodeSettings); + request = (0, deep_copy_1.deepExtend)(request, builder.buildRequest()); + } + catch (e) { + return Promise.reject(e); + } + } + if (requestType === 'VERIFY_AND_CHANGE_EMAIL' && typeof newEmail === 'undefined') { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "`newEmail` is required when `requestType` === 'VERIFY_AND_CHANGE_EMAIL'")); + } + return this.invokeRequestHandler(this.getAuthUrlBuilder(), FIREBASE_AUTH_GET_OOB_CODE, request) + .then((response) => { + // Return the link. + return response.oobLink; + }); + } + /** + * Looks up an OIDC provider configuration by provider ID. + * + * @param providerId - The provider identifier of the configuration to lookup. + * @returns A promise that resolves with the provider configuration information. + */ + getOAuthIdpConfig(providerId) { + if (!auth_config_1.OIDCConfig.isProviderId(providerId)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID)); + } + return this.invokeRequestHandler(this.getProjectConfigUrlBuilder(), GET_OAUTH_IDP_CONFIG, {}, { providerId }); + } + /** + * Lists the OIDC configurations (single batch only) with a size of maxResults and starting from + * the offset as specified by pageToken. + * + * @param maxResults - The page size, 100 if undefined. This is also the maximum + * allowed limit. + * @param pageToken - The next page token. If not specified, returns OIDC configurations + * without any offset. Configurations are returned in the order they were created from oldest to + * newest, relative to the page token offset. + * @returns A promise that resolves with the current batch of downloaded + * OIDC configurations and the next page token if available. For the last page, an empty list of provider + * configuration and no page token are returned. + */ + listOAuthIdpConfigs(maxResults = MAX_LIST_PROVIDER_CONFIGURATION_PAGE_SIZE, pageToken) { + const request = { + pageSize: maxResults, + }; + // Add next page token if provided. + if (typeof pageToken !== 'undefined') { + request.pageToken = pageToken; + } + return this.invokeRequestHandler(this.getProjectConfigUrlBuilder(), LIST_OAUTH_IDP_CONFIGS, request) + .then((response) => { + if (!response.oauthIdpConfigs) { + response.oauthIdpConfigs = []; + delete response.nextPageToken; + } + return response; + }); + } + /** + * Deletes an OIDC configuration identified by a providerId. + * + * @param providerId - The identifier of the OIDC configuration to delete. + * @returns A promise that resolves when the OIDC provider is deleted. + */ + deleteOAuthIdpConfig(providerId) { + if (!auth_config_1.OIDCConfig.isProviderId(providerId)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID)); + } + return this.invokeRequestHandler(this.getProjectConfigUrlBuilder(), DELETE_OAUTH_IDP_CONFIG, {}, { providerId }) + .then(() => { + // Return nothing. + }); + } + /** + * Creates a new OIDC provider configuration with the properties provided. + * + * @param options - The properties to set on the new OIDC provider configuration to be created. + * @returns A promise that resolves with the newly created OIDC + * configuration. + */ + createOAuthIdpConfig(options) { + // Construct backend request. + let request; + try { + request = auth_config_1.OIDCConfig.buildServerRequest(options) || {}; + } + catch (e) { + return Promise.reject(e); + } + const providerId = options.providerId; + return this.invokeRequestHandler(this.getProjectConfigUrlBuilder(), CREATE_OAUTH_IDP_CONFIG, request, { providerId }) + .then((response) => { + if (!auth_config_1.OIDCConfig.getProviderIdFromResourceName(response.name)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Unable to create new OIDC provider configuration'); + } + return response; + }); + } + /** + * Updates an existing OIDC provider configuration with the properties provided. + * + * @param providerId - The provider identifier of the OIDC configuration to update. + * @param options - The properties to update on the existing configuration. + * @returns A promise that resolves with the modified provider + * configuration. + */ + updateOAuthIdpConfig(providerId, options) { + if (!auth_config_1.OIDCConfig.isProviderId(providerId)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID)); + } + // Construct backend request. + let request; + try { + request = auth_config_1.OIDCConfig.buildServerRequest(options, true) || {}; + } + catch (e) { + return Promise.reject(e); + } + const updateMask = utils.generateUpdateMask(request); + return this.invokeRequestHandler(this.getProjectConfigUrlBuilder(), UPDATE_OAUTH_IDP_CONFIG, request, { providerId, updateMask: updateMask.join(',') }) + .then((response) => { + if (!auth_config_1.OIDCConfig.getProviderIdFromResourceName(response.name)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Unable to update OIDC provider configuration'); + } + return response; + }); + } + /** + * Looks up an SAML provider configuration by provider ID. + * + * @param providerId - The provider identifier of the configuration to lookup. + * @returns A promise that resolves with the provider configuration information. + */ + getInboundSamlConfig(providerId) { + if (!auth_config_1.SAMLConfig.isProviderId(providerId)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID)); + } + return this.invokeRequestHandler(this.getProjectConfigUrlBuilder(), GET_INBOUND_SAML_CONFIG, {}, { providerId }); + } + /** + * Lists the SAML configurations (single batch only) with a size of maxResults and starting from + * the offset as specified by pageToken. + * + * @param maxResults - The page size, 100 if undefined. This is also the maximum + * allowed limit. + * @param pageToken - The next page token. If not specified, returns SAML configurations starting + * without any offset. Configurations are returned in the order they were created from oldest to + * newest, relative to the page token offset. + * @returns A promise that resolves with the current batch of downloaded + * SAML configurations and the next page token if available. For the last page, an empty list of provider + * configuration and no page token are returned. + */ + listInboundSamlConfigs(maxResults = MAX_LIST_PROVIDER_CONFIGURATION_PAGE_SIZE, pageToken) { + const request = { + pageSize: maxResults, + }; + // Add next page token if provided. + if (typeof pageToken !== 'undefined') { + request.pageToken = pageToken; + } + return this.invokeRequestHandler(this.getProjectConfigUrlBuilder(), LIST_INBOUND_SAML_CONFIGS, request) + .then((response) => { + if (!response.inboundSamlConfigs) { + response.inboundSamlConfigs = []; + delete response.nextPageToken; + } + return response; + }); + } + /** + * Deletes a SAML configuration identified by a providerId. + * + * @param providerId - The identifier of the SAML configuration to delete. + * @returns A promise that resolves when the SAML provider is deleted. + */ + deleteInboundSamlConfig(providerId) { + if (!auth_config_1.SAMLConfig.isProviderId(providerId)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID)); + } + return this.invokeRequestHandler(this.getProjectConfigUrlBuilder(), DELETE_INBOUND_SAML_CONFIG, {}, { providerId }) + .then(() => { + // Return nothing. + }); + } + /** + * Creates a new SAML provider configuration with the properties provided. + * + * @param options - The properties to set on the new SAML provider configuration to be created. + * @returns A promise that resolves with the newly created SAML + * configuration. + */ + createInboundSamlConfig(options) { + // Construct backend request. + let request; + try { + request = auth_config_1.SAMLConfig.buildServerRequest(options) || {}; + } + catch (e) { + return Promise.reject(e); + } + const providerId = options.providerId; + return this.invokeRequestHandler(this.getProjectConfigUrlBuilder(), CREATE_INBOUND_SAML_CONFIG, request, { providerId }) + .then((response) => { + if (!auth_config_1.SAMLConfig.getProviderIdFromResourceName(response.name)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Unable to create new SAML provider configuration'); + } + return response; + }); + } + /** + * Updates an existing SAML provider configuration with the properties provided. + * + * @param providerId - The provider identifier of the SAML configuration to update. + * @param options - The properties to update on the existing configuration. + * @returns A promise that resolves with the modified provider + * configuration. + */ + updateInboundSamlConfig(providerId, options) { + if (!auth_config_1.SAMLConfig.isProviderId(providerId)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID)); + } + // Construct backend request. + let request; + try { + request = auth_config_1.SAMLConfig.buildServerRequest(options, true) || {}; + } + catch (e) { + return Promise.reject(e); + } + const updateMask = utils.generateUpdateMask(request); + return this.invokeRequestHandler(this.getProjectConfigUrlBuilder(), UPDATE_INBOUND_SAML_CONFIG, request, { providerId, updateMask: updateMask.join(',') }) + .then((response) => { + if (!auth_config_1.SAMLConfig.getProviderIdFromResourceName(response.name)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Unable to update SAML provider configuration'); + } + return response; + }); + } + /** + * Invokes the request handler based on the API settings object passed. + * + * @param urlBuilder - The URL builder for Auth endpoints. + * @param apiSettings - The API endpoint settings to apply to request and response. + * @param requestData - The request data. + * @param additionalResourceParams - Additional resource related params if needed. + * @returns A promise that resolves with the response. + */ + invokeRequestHandler(urlBuilder, apiSettings, requestData, additionalResourceParams) { + return urlBuilder.getUrl(apiSettings.getEndpoint(), additionalResourceParams) + .then((url) => { + // Validate request. + if (requestData) { + const requestValidator = apiSettings.getRequestValidator(); + requestValidator(requestData); + } + // Process request. + const req = { + method: apiSettings.getHttpMethod(), + url, + headers: FIREBASE_AUTH_HEADERS, + data: requestData, + timeout: FIREBASE_AUTH_TIMEOUT, + }; + return this.httpClient.send(req); + }) + .then((response) => { + // Validate response. + const responseValidator = apiSettings.getResponseValidator(); + responseValidator(response.data); + // Return entire response. + return response.data; + }) + .catch((err) => { + if (err instanceof api_request_1.RequestResponseError) { + const error = err.response.data; + const errorCode = AbstractAuthRequestHandler.getErrorCode(error); + if (!errorCode) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'Error returned from server: ' + error + '. Additionally, an ' + + 'internal error occurred while attempting to extract the ' + + 'errorcode from the error.'); + } + throw error_1.FirebaseAuthError.fromServerError(errorCode, /* message */ undefined, error); + } + throw err; + }); + } + /** + * @returns The current Auth user management resource URL builder. + */ + getAuthUrlBuilder() { + if (!this.authUrlBuilder) { + this.authUrlBuilder = this.newAuthUrlBuilder(); + } + return this.authUrlBuilder; + } + /** + * @returns The current project config resource URL builder. + */ + getProjectConfigUrlBuilder() { + if (!this.projectConfigUrlBuilder) { + this.projectConfigUrlBuilder = this.newProjectConfigUrlBuilder(); + } + return this.projectConfigUrlBuilder; + } +} +exports.AbstractAuthRequestHandler = AbstractAuthRequestHandler; +/** Instantiates the getConfig endpoint settings. */ +const GET_PROJECT_CONFIG = new api_request_1.ApiSettings('/config', 'GET') + .setResponseValidator((response) => { + // Response should always contain at least the config name. + if (!validator.isNonEmptyString(response.name)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Unable to get project config'); + } +}); +/** Instantiates the updateConfig endpoint settings. */ +const UPDATE_PROJECT_CONFIG = new api_request_1.ApiSettings('/config?updateMask={updateMask}', 'PATCH') + .setResponseValidator((response) => { + // Response should always contain at least the config name. + if (!validator.isNonEmptyString(response.name)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Unable to update project config'); + } +}); +/** Instantiates the getTenant endpoint settings. */ +const GET_TENANT = new api_request_1.ApiSettings('/tenants/{tenantId}', 'GET') + // Set response validator. + .setResponseValidator((response) => { + // Response should always contain at least the tenant name. + if (!validator.isNonEmptyString(response.name)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Unable to get tenant'); + } +}); +/** Instantiates the deleteTenant endpoint settings. */ +const DELETE_TENANT = new api_request_1.ApiSettings('/tenants/{tenantId}', 'DELETE'); +/** Instantiates the updateTenant endpoint settings. */ +const UPDATE_TENANT = new api_request_1.ApiSettings('/tenants/{tenantId}?updateMask={updateMask}', 'PATCH') + // Set response validator. + .setResponseValidator((response) => { + // Response should always contain at least the tenant name. + if (!validator.isNonEmptyString(response.name) || + !tenant_1.Tenant.getTenantIdFromResourceName(response.name)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Unable to update tenant'); + } +}); +/** Instantiates the listTenants endpoint settings. */ +const LIST_TENANTS = new api_request_1.ApiSettings('/tenants', 'GET') + // Set request validator. + .setRequestValidator((request) => { + // Validate next page token. + if (typeof request.pageToken !== 'undefined' && + !validator.isNonEmptyString(request.pageToken)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PAGE_TOKEN); + } + // Validate max results. + if (!validator.isNumber(request.pageSize) || + request.pageSize <= 0 || + request.pageSize > MAX_LIST_TENANT_PAGE_SIZE) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'Required "maxResults" must be a positive non-zero number that does not exceed ' + + `the allowed ${MAX_LIST_TENANT_PAGE_SIZE}.`); + } +}); +/** Instantiates the createTenant endpoint settings. */ +const CREATE_TENANT = new api_request_1.ApiSettings('/tenants', 'POST') + // Set response validator. + .setResponseValidator((response) => { + // Response should always contain at least the tenant name. + if (!validator.isNonEmptyString(response.name) || + !tenant_1.Tenant.getTenantIdFromResourceName(response.name)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Unable to create new tenant'); + } +}); +/** + * Utility for sending requests to Auth server that are Auth instance related. This includes user, tenant, + * and project config management related APIs. This extends the BaseFirebaseAuthRequestHandler class and defines + * additional tenant management related APIs. + */ +class AuthRequestHandler extends AbstractAuthRequestHandler { + /** + * The FirebaseAuthRequestHandler constructor used to initialize an instance using a FirebaseApp. + * + * @param app - The app used to fetch access tokens to sign API requests. + * @constructor + */ + constructor(app) { + super(app); + this.authResourceUrlBuilder = new AuthResourceUrlBuilder(app, 'v2'); + } + /** + * @returns A new Auth user management resource URL builder instance. + */ + newAuthUrlBuilder() { + return new AuthResourceUrlBuilder(this.app, 'v1'); + } + /** + * @returns A new project config resource URL builder instance. + */ + newProjectConfigUrlBuilder() { + return new AuthResourceUrlBuilder(this.app, 'v2'); + } + /** + * Get the current project's config + * @returns A promise that resolves with the project config information. + */ + getProjectConfig() { + return this.invokeRequestHandler(this.authResourceUrlBuilder, GET_PROJECT_CONFIG, {}, {}) + .then((response) => { + return response; + }); + } + /** + * Update the current project's config. + * @returns A promise that resolves with the project config information. + */ + updateProjectConfig(options) { + try { + const request = project_config_1.ProjectConfig.buildServerRequest(options); + const updateMask = utils.generateUpdateMask(request); + return this.invokeRequestHandler(this.authResourceUrlBuilder, UPDATE_PROJECT_CONFIG, request, { updateMask: updateMask.join(',') }) + .then((response) => { + return response; + }); + } + catch (e) { + return Promise.reject(e); + } + } + /** + * Looks up a tenant by tenant ID. + * + * @param tenantId - The tenant identifier of the tenant to lookup. + * @returns A promise that resolves with the tenant information. + */ + getTenant(tenantId) { + if (!validator.isNonEmptyString(tenantId)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_TENANT_ID)); + } + return this.invokeRequestHandler(this.authResourceUrlBuilder, GET_TENANT, {}, { tenantId }) + .then((response) => { + return response; + }); + } + /** + * Exports the tenants (single batch only) with a size of maxResults and starting from + * the offset as specified by pageToken. + * + * @param maxResults - The page size, 1000 if undefined. This is also the maximum + * allowed limit. + * @param pageToken - The next page token. If not specified, returns tenants starting + * without any offset. Tenants are returned in the order they were created from oldest to + * newest, relative to the page token offset. + * @returns A promise that resolves with the current batch of downloaded + * tenants and the next page token if available. For the last page, an empty list of tenants + * and no page token are returned. + */ + listTenants(maxResults = MAX_LIST_TENANT_PAGE_SIZE, pageToken) { + const request = { + pageSize: maxResults, + pageToken, + }; + // Remove next page token if not provided. + if (typeof request.pageToken === 'undefined') { + delete request.pageToken; + } + return this.invokeRequestHandler(this.authResourceUrlBuilder, LIST_TENANTS, request) + .then((response) => { + if (!response.tenants) { + response.tenants = []; + delete response.nextPageToken; + } + return response; + }); + } + /** + * Deletes a tenant identified by a tenantId. + * + * @param tenantId - The identifier of the tenant to delete. + * @returns A promise that resolves when the tenant is deleted. + */ + deleteTenant(tenantId) { + if (!validator.isNonEmptyString(tenantId)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_TENANT_ID)); + } + return this.invokeRequestHandler(this.authResourceUrlBuilder, DELETE_TENANT, undefined, { tenantId }) + .then(() => { + // Return nothing. + }); + } + /** + * Creates a new tenant with the properties provided. + * + * @param tenantOptions - The properties to set on the new tenant to be created. + * @returns A promise that resolves with the newly created tenant object. + */ + createTenant(tenantOptions) { + try { + // Construct backend request. + const request = tenant_1.Tenant.buildServerRequest(tenantOptions, true); + return this.invokeRequestHandler(this.authResourceUrlBuilder, CREATE_TENANT, request) + .then((response) => { + return response; + }); + } + catch (e) { + return Promise.reject(e); + } + } + /** + * Updates an existing tenant with the properties provided. + * + * @param tenantId - The tenant identifier of the tenant to update. + * @param tenantOptions - The properties to update on the existing tenant. + * @returns A promise that resolves with the modified tenant object. + */ + updateTenant(tenantId, tenantOptions) { + if (!validator.isNonEmptyString(tenantId)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_TENANT_ID)); + } + try { + // Construct backend request. + const request = tenant_1.Tenant.buildServerRequest(tenantOptions, false); + // Do not traverse deep into testPhoneNumbers. The entire content should be replaced + // and not just specific phone numbers. + const updateMask = utils.generateUpdateMask(request, ['testPhoneNumbers']); + return this.invokeRequestHandler(this.authResourceUrlBuilder, UPDATE_TENANT, request, { tenantId, updateMask: updateMask.join(',') }) + .then((response) => { + return response; + }); + } + catch (e) { + return Promise.reject(e); + } + } +} +exports.AuthRequestHandler = AuthRequestHandler; +/** + * Utility for sending requests to Auth server that are tenant Auth instance related. This includes user + * management related APIs for specified tenants. + * This extends the BaseFirebaseAuthRequestHandler class. + */ +class TenantAwareAuthRequestHandler extends AbstractAuthRequestHandler { + /** + * The FirebaseTenantRequestHandler constructor used to initialize an instance using a + * FirebaseApp and a tenant ID. + * + * @param app - The app used to fetch access tokens to sign API requests. + * @param tenantId - The request handler's tenant ID. + * @constructor + */ + constructor(app, tenantId) { + super(app); + this.tenantId = tenantId; + } + /** + * @returns A new Auth user management resource URL builder instance. + */ + newAuthUrlBuilder() { + return new TenantAwareAuthResourceUrlBuilder(this.app, 'v1', this.tenantId); + } + /** + * @returns A new project config resource URL builder instance. + */ + newProjectConfigUrlBuilder() { + return new TenantAwareAuthResourceUrlBuilder(this.app, 'v2', this.tenantId); + } + /** + * Imports the list of users provided to Firebase Auth. This is useful when + * migrating from an external authentication system without having to use the Firebase CLI SDK. + * At most, 1000 users are allowed to be imported one at a time. + * When importing a list of password users, UserImportOptions are required to be specified. + * + * Overrides the superclass methods by adding an additional check to match tenant IDs of + * imported user records if present. + * + * @param users - The list of user records to import to Firebase Auth. + * @param options - The user import options, required when the users provided + * include password credentials. + * @returns A promise that resolves when the operation completes + * with the result of the import. This includes the number of successful imports, the number + * of failed uploads and their corresponding errors. + */ + uploadAccount(users, options) { + // Add additional check to match tenant ID of imported user records. + users.forEach((user, index) => { + if (validator.isNonEmptyString(user.tenantId) && + user.tenantId !== this.tenantId) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISMATCHING_TENANT_ID, `UserRecord of index "${index}" has mismatching tenant ID "${user.tenantId}"`); + } + }); + return super.uploadAccount(users, options); + } +} +exports.TenantAwareAuthRequestHandler = TenantAwareAuthRequestHandler; +function emulatorHost() { + return process.env.FIREBASE_AUTH_EMULATOR_HOST; +} +/** + * When true the SDK should communicate with the Auth Emulator for all API + * calls and also produce unsigned tokens. + */ +function useEmulator() { + return !!emulatorHost(); +} diff --git a/node_modules/firebase-admin/lib/auth/auth-config.d.ts b/node_modules/firebase-admin/lib/auth/auth-config.d.ts new file mode 100644 index 0000000..bfb7ce0 --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/auth-config.d.ts @@ -0,0 +1,851 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Interface representing base properties of a user-enrolled second factor for a + * `CreateRequest`. + */ +export interface BaseCreateMultiFactorInfoRequest { + /** + * The optional display name for an enrolled second factor. + */ + displayName?: string; + /** + * The type identifier of the second factor. For SMS second factors, this is `phone`. + */ + factorId: string; +} +/** + * Interface representing a phone specific user-enrolled second factor for a + * `CreateRequest`. + */ +export interface CreatePhoneMultiFactorInfoRequest extends BaseCreateMultiFactorInfoRequest { + /** + * The phone number associated with a phone second factor. + */ + phoneNumber: string; +} +/** + * Type representing the properties of a user-enrolled second factor + * for a `CreateRequest`. + */ +export type CreateMultiFactorInfoRequest = CreatePhoneMultiFactorInfoRequest; +/** + * Interface representing common properties of a user-enrolled second factor + * for an `UpdateRequest`. + */ +export interface BaseUpdateMultiFactorInfoRequest { + /** + * The ID of the enrolled second factor. This ID is unique to the user. When not provided, + * a new one is provisioned by the Auth server. + */ + uid?: string; + /** + * The optional display name for an enrolled second factor. + */ + displayName?: string; + /** + * The optional date the second factor was enrolled, formatted as a UTC string. + */ + enrollmentTime?: string; + /** + * The type identifier of the second factor. For SMS second factors, this is `phone`. + */ + factorId: string; +} +/** + * Interface representing a phone specific user-enrolled second factor + * for an `UpdateRequest`. + */ +export interface UpdatePhoneMultiFactorInfoRequest extends BaseUpdateMultiFactorInfoRequest { + /** + * The phone number associated with a phone second factor. + */ + phoneNumber: string; +} +/** + * Type representing the properties of a user-enrolled second factor + * for an `UpdateRequest`. + */ +export type UpdateMultiFactorInfoRequest = UpdatePhoneMultiFactorInfoRequest; +/** + * The multi-factor related user settings for create operations. + */ +export interface MultiFactorCreateSettings { + /** + * The created user's list of enrolled second factors. + */ + enrolledFactors: CreateMultiFactorInfoRequest[]; +} +/** + * The multi-factor related user settings for update operations. + */ +export interface MultiFactorUpdateSettings { + /** + * The updated list of enrolled second factors. The provided list overwrites the user's + * existing list of second factors. + * When null is passed, all of the user's existing second factors are removed. + */ + enrolledFactors: UpdateMultiFactorInfoRequest[] | null; +} +/** + * Interface representing the properties to update on the provided user. + */ +export interface UpdateRequest { + /** + * Whether or not the user is disabled: `true` for disabled; + * `false` for enabled. + */ + disabled?: boolean; + /** + * The user's display name. + */ + displayName?: string | null; + /** + * The user's primary email. + */ + email?: string; + /** + * Whether or not the user's primary email is verified. + */ + emailVerified?: boolean; + /** + * The user's unhashed password. + */ + password?: string; + /** + * The user's primary phone number. + */ + phoneNumber?: string | null; + /** + * The user's photo URL. + */ + photoURL?: string | null; + /** + * The user's updated multi-factor related properties. + */ + multiFactor?: MultiFactorUpdateSettings; + /** + * Links this user to the specified provider. + * + * Linking a provider to an existing user account does not invalidate the + * refresh token of that account. In other words, the existing account + * would continue to be able to access resources, despite not having used + * the newly linked provider to log in. If you wish to force the user to + * authenticate with this new provider, you need to (a) revoke their + * refresh token (see + * https://firebase.google.com/docs/auth/admin/manage-sessions#revoke_refresh_tokens), + * and (b) ensure no other authentication methods are present on this + * account. + */ + providerToLink?: UserProvider; + /** + * Unlinks this user from the specified providers. + */ + providersToUnlink?: string[]; +} +/** + * Represents a user identity provider that can be associated with a Firebase user. + */ +export interface UserProvider { + /** + * The user identifier for the linked provider. + */ + uid?: string; + /** + * The display name for the linked provider. + */ + displayName?: string; + /** + * The email for the linked provider. + */ + email?: string; + /** + * The phone number for the linked provider. + */ + phoneNumber?: string; + /** + * The photo URL for the linked provider. + */ + photoURL?: string; + /** + * The linked provider ID (for example, "google.com" for the Google provider). + */ + providerId?: string; +} +/** + * Interface representing the properties to set on a new user record to be + * created. + */ +export interface CreateRequest extends UpdateRequest { + /** + * The user's `uid`. + */ + uid?: string; + /** + * The user's multi-factor related properties. + */ + multiFactor?: MultiFactorCreateSettings; +} +/** + * The response interface for listing provider configs. This is only available + * when listing all identity providers' configurations via + * {@link BaseAuth.listProviderConfigs}. + */ +export interface ListProviderConfigResults { + /** + * The list of providers for the specified type in the current page. + */ + providerConfigs: AuthProviderConfig[]; + /** + * The next page token, if available. + */ + pageToken?: string; +} +/** + * The filter interface used for listing provider configurations. This is used + * when specifying how to list configured identity providers via + * {@link BaseAuth.listProviderConfigs}. + */ +export interface AuthProviderConfigFilter { + /** + * The Auth provider configuration filter. This can be either `saml` or `oidc`. + * The former is used to look up SAML providers only, while the latter is used + * for OIDC providers. + */ + type: 'saml' | 'oidc'; + /** + * The maximum number of results to return per page. The default and maximum is + * 100. + */ + maxResults?: number; + /** + * The next page token. When not specified, the lookup starts from the beginning + * of the list. + */ + pageToken?: string; +} +/** + * The request interface for updating a SAML Auth provider. This is used + * when updating a SAML provider's configuration via + * {@link BaseAuth.updateProviderConfig}. + */ +export interface SAMLUpdateAuthProviderRequest { + /** + * The SAML provider's updated display name. If not provided, the existing + * configuration's value is not modified. + */ + displayName?: string; + /** + * Whether the SAML provider is enabled or not. If not provided, the existing + * configuration's setting is not modified. + */ + enabled?: boolean; + /** + * The SAML provider's updated IdP entity ID. If not provided, the existing + * configuration's value is not modified. + */ + idpEntityId?: string; + /** + * The SAML provider's updated SSO URL. If not provided, the existing + * configuration's value is not modified. + */ + ssoURL?: string; + /** + * The SAML provider's updated list of X.509 certificated. If not provided, the + * existing configuration list is not modified. + */ + x509Certificates?: string[]; + /** + * The SAML provider's updated RP entity ID. If not provided, the existing + * configuration's value is not modified. + */ + rpEntityId?: string; + /** + * The SAML provider's callback URL. If not provided, the existing + * configuration's value is not modified. + */ + callbackURL?: string; +} +/** + * The request interface for updating an OIDC Auth provider. This is used + * when updating an OIDC provider's configuration via + * {@link BaseAuth.updateProviderConfig}. + */ +export interface OIDCUpdateAuthProviderRequest { + /** + * The OIDC provider's updated display name. If not provided, the existing + * configuration's value is not modified. + */ + displayName?: string; + /** + * Whether the OIDC provider is enabled or not. If not provided, the existing + * configuration's setting is not modified. + */ + enabled?: boolean; + /** + * The OIDC provider's updated client ID. If not provided, the existing + * configuration's value is not modified. + */ + clientId?: string; + /** + * The OIDC provider's updated issuer. If not provided, the existing + * configuration's value is not modified. + */ + issuer?: string; + /** + * The OIDC provider's client secret to enable OIDC code flow. + * If not provided, the existing configuration's value is not modified. + */ + clientSecret?: string; + /** + * The OIDC provider's response object for OAuth authorization flow. + */ + responseType?: OAuthResponseType; +} +export type UpdateAuthProviderRequest = SAMLUpdateAuthProviderRequest | OIDCUpdateAuthProviderRequest; +/** A maximum of 10 test phone number / code pairs can be configured. */ +export declare const MAXIMUM_TEST_PHONE_NUMBERS = 10; +/** The server side SAML configuration request interface. */ +export interface SAMLConfigServerRequest { + idpConfig?: { + idpEntityId?: string; + ssoUrl?: string; + idpCertificates?: Array<{ + x509Certificate: string; + }>; + signRequest?: boolean; + }; + spConfig?: { + spEntityId?: string; + callbackUri?: string; + }; + displayName?: string; + enabled?: boolean; + [key: string]: any; +} +/** The server side SAML configuration response interface. */ +export interface SAMLConfigServerResponse { + name?: string; + idpConfig?: { + idpEntityId?: string; + ssoUrl?: string; + idpCertificates?: Array<{ + x509Certificate: string; + }>; + signRequest?: boolean; + }; + spConfig?: { + spEntityId?: string; + callbackUri?: string; + }; + displayName?: string; + enabled?: boolean; +} +/** The server side OIDC configuration request interface. */ +export interface OIDCConfigServerRequest { + clientId?: string; + issuer?: string; + displayName?: string; + enabled?: boolean; + clientSecret?: string; + responseType?: OAuthResponseType; + [key: string]: any; +} +/** The server side OIDC configuration response interface. */ +export interface OIDCConfigServerResponse { + name?: string; + clientId?: string; + issuer?: string; + displayName?: string; + enabled?: boolean; + clientSecret?: string; + responseType?: OAuthResponseType; +} +/** The server side email configuration request interface. */ +export interface EmailSignInConfigServerRequest { + allowPasswordSignup?: boolean; + enableEmailLinkSignin?: boolean; +} +/** Identifies the server side second factor type. */ +type AuthFactorServerType = 'PHONE_SMS'; +/** Server side multi-factor configuration. */ +export interface MultiFactorAuthServerConfig { + state?: MultiFactorConfigState; + enabledProviders?: AuthFactorServerType[]; + providerConfigs?: MultiFactorProviderConfig[]; +} +/** + * Identifies a second factor type. + */ +export type AuthFactorType = 'phone'; +/** + * Identifies a multi-factor configuration state. + */ +export type MultiFactorConfigState = 'ENABLED' | 'DISABLED'; +/** + * Interface representing a multi-factor configuration. + * This can be used to define whether multi-factor authentication is enabled + * or disabled and the list of second factor challenges that are supported. + */ +export interface MultiFactorConfig { + /** + * The multi-factor config state. + */ + state: MultiFactorConfigState; + /** + * The list of identifiers for enabled second factors. + * Currently only ‘phone’ is supported. + */ + factorIds?: AuthFactorType[]; + /** + * A list of multi-factor provider configurations. + * MFA providers (except phone) indicate whether they're enabled through this field. */ + providerConfigs?: MultiFactorProviderConfig[]; +} +/** + * Interface representing a multi-factor auth provider configuration. + * This interface is used for second factor auth providers other than SMS. + * Currently, only TOTP is supported. + */ export interface MultiFactorProviderConfig { + /** + * Indicates whether this multi-factor provider is enabled or disabled. */ + state: MultiFactorConfigState; + /** + * TOTP multi-factor provider config. */ + totpProviderConfig?: TotpMultiFactorProviderConfig; +} +/** + * Interface representing configuration settings for TOTP second factor auth. + */ +export interface TotpMultiFactorProviderConfig { + /** + * The allowed number of adjacent intervals that will be used for verification + * to compensate for clock skew. */ + adjacentIntervals?: number; +} +/** + * Validates the provided map of test phone number / code pairs. + * @param testPhoneNumbers - The phone number / code pairs to validate. + */ +export declare function validateTestPhoneNumbers(testPhoneNumbers: { + [phoneNumber: string]: string; +}): void; +/** + * The email sign in provider configuration. + */ +export interface EmailSignInProviderConfig { + /** + * Whether email provider is enabled. + */ + enabled: boolean; + /** + * Whether password is required for email sign-in. When not required, + * email sign-in can be performed with password or via email link sign-in. + */ + passwordRequired?: boolean; +} +/** + * The base Auth provider configuration interface. + */ +export interface BaseAuthProviderConfig { + /** + * The provider ID defined by the developer. + * For a SAML provider, this is always prefixed by `saml.`. + * For an OIDC provider, this is always prefixed by `oidc.`. + */ + providerId: string; + /** + * The user-friendly display name to the current configuration. This name is + * also used as the provider label in the Cloud Console. + */ + displayName?: string; + /** + * Whether the provider configuration is enabled or disabled. A user + * cannot sign in using a disabled provider. + */ + enabled: boolean; +} +/** + * The + * [SAML](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html) + * Auth provider configuration interface. A SAML provider can be created via + * {@link BaseAuth.createProviderConfig}. + */ +export interface SAMLAuthProviderConfig extends BaseAuthProviderConfig { + /** + * The SAML IdP entity identifier. + */ + idpEntityId: string; + /** + * The SAML IdP SSO URL. This must be a valid URL. + */ + ssoURL: string; + /** + * The list of SAML IdP X.509 certificates issued by CA for this provider. + * Multiple certificates are accepted to prevent outages during + * IdP key rotation (for example ADFS rotates every 10 days). When the Auth + * server receives a SAML response, it will match the SAML response with the + * certificate on record. Otherwise the response is rejected. + * Developers are expected to manage the certificate updates as keys are + * rotated. + */ + x509Certificates: string[]; + /** + * The SAML relying party (service provider) entity ID. + * This is defined by the developer but needs to be provided to the SAML IdP. + */ + rpEntityId: string; + /** + * This is fixed and must always be the same as the OAuth redirect URL + * provisioned by Firebase Auth, + * `https://project-id.firebaseapp.com/__/auth/handler` unless a custom + * `authDomain` is used. + * The callback URL should also be provided to the SAML IdP during + * configuration. + */ + callbackURL?: string; +} +/** + * The interface representing OIDC provider's response object for OAuth + * authorization flow. + * One of the following settings is required: + *
                            + *
                          • Set code to true for the code flow.
                          • + *
                          • Set idToken to true for the ID token flow.
                          • + *
                          + */ +export interface OAuthResponseType { + /** + * Whether ID token is returned from IdP's authorization endpoint. + */ + idToken?: boolean; + /** + * Whether authorization code is returned from IdP's authorization endpoint. + */ + code?: boolean; +} +/** + * The [OIDC](https://openid.net/specs/openid-connect-core-1_0-final.html) Auth + * provider configuration interface. An OIDC provider can be created via + * {@link BaseAuth.createProviderConfig}. + */ +export interface OIDCAuthProviderConfig extends BaseAuthProviderConfig { + /** + * This is the required client ID used to confirm the audience of an OIDC + * provider's + * [ID token](https://openid.net/specs/openid-connect-core-1_0-final.html#IDToken). + */ + clientId: string; + /** + * This is the required provider issuer used to match the provider issuer of + * the ID token and to determine the corresponding OIDC discovery document, eg. + * [`/.well-known/openid-configuration`](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig). + * This is needed for the following: + *
                            + *
                          • To verify the provided issuer.
                          • + *
                          • Determine the authentication/authorization endpoint during the OAuth + * `id_token` authentication flow.
                          • + *
                          • To retrieve the public signing keys via `jwks_uri` to verify the OIDC + * provider's ID token's signature.
                          • + *
                          • To determine the claims_supported to construct the user attributes to be + * returned in the additional user info response.
                          • + *
                          + * ID token validation will be performed as defined in the + * [spec](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). + */ + issuer: string; + /** + * The OIDC provider's client secret to enable OIDC code flow. + */ + clientSecret?: string; + /** + * The OIDC provider's response object for OAuth authorization flow. + */ + responseType?: OAuthResponseType; +} +/** + * The Auth provider configuration type. + * {@link BaseAuth.createProviderConfig}. + */ +export type AuthProviderConfig = SAMLAuthProviderConfig | OIDCAuthProviderConfig; +/** + * The request interface for updating a SMS Region Config. + * Configures the regions where users are allowed to send verification SMS. + * This is based on the calling code of the destination phone number. + */ +export type SmsRegionConfig = AllowByDefaultWrap | AllowlistOnlyWrap; +/** + * Mutual exclusive SMS Region Config of AllowByDefault interface + */ +export interface AllowByDefaultWrap { + /** + * Allow every region by default. + */ + allowByDefault: AllowByDefault; + /** @alpha */ + allowlistOnly?: never; +} +/** + * Mutually exclusive SMS Region Config of AllowlistOnly interface + */ +export interface AllowlistOnlyWrap { + /** + * Only allowing regions by explicitly adding them to an + * allowlist. + */ + allowlistOnly: AllowlistOnly; + /** @alpha */ + allowByDefault?: never; +} +/** + * Defines a policy of allowing every region by default and adding disallowed + * regions to a disallow list. + */ +export interface AllowByDefault { + /** + * Two letter unicode region codes to disallow as defined by + * https://cldr.unicode.org/ + * The full list of these region codes is here: + * https://github.com/unicode-cldr/cldr-localenames-full/blob/master/main/en/territories.json + */ + disallowedRegions: string[]; +} +/** + * Defines a policy of only allowing regions by explicitly adding them to an + * allowlist. + */ +export interface AllowlistOnly { + /** + * Two letter unicode region codes to allow as defined by + * https://cldr.unicode.org/ + * The full list of these region codes is here: + * https://github.com/unicode-cldr/cldr-localenames-full/blob/master/main/en/territories.json + */ + allowedRegions: string[]; +} +/** +* Enforcement state of reCAPTCHA protection. +* - 'OFF': Unenforced. +* - 'AUDIT': Create assessment but don't enforce the result. +* - 'ENFORCE': Create assessment and enforce the result. +*/ +export type RecaptchaProviderEnforcementState = 'OFF' | 'AUDIT' | 'ENFORCE'; +/** +* The actions to take for reCAPTCHA-protected requests. +* - 'BLOCK': The reCAPTCHA-protected request will be blocked. +*/ +export type RecaptchaAction = 'BLOCK'; +/** + * The config for a reCAPTCHA action rule. + */ +export interface RecaptchaManagedRule { + /** + * The action will be enforced if the reCAPTCHA score of a request is larger than endScore. + */ + endScore: number; + /** + * The action for reCAPTCHA-protected requests. + */ + action?: RecaptchaAction; +} +/** + * The managed rules for toll fraud provider, containing the enforcement status. + * The toll fraud provider contains all SMS related user flows. + */ +export interface RecaptchaTollFraudManagedRule { + /** + * The action will be enforced if the reCAPTCHA score of a request is larger than startScore. + */ + startScore: number; + /** + * The action for reCAPTCHA-protected requests. + */ + action?: RecaptchaAction; +} +/** + * The key's platform type. + */ +export type RecaptchaKeyClientType = 'WEB' | 'IOS' | 'ANDROID'; +/** + * The reCAPTCHA key config. + */ +export interface RecaptchaKey { + /** + * The key's client platform type. + */ + type?: RecaptchaKeyClientType; + /** + * The reCAPTCHA site key. + */ + key: string; +} +/** + * The request interface for updating a reCAPTCHA Config. + * By enabling reCAPTCHA Enterprise Integration you are + * agreeing to reCAPTCHA Enterprise + * {@link https://cloud.google.com/terms/service-terms | Term of Service}. + */ +export interface RecaptchaConfig { + /** + * The enforcement state of the email password provider. + */ + emailPasswordEnforcementState?: RecaptchaProviderEnforcementState; + /** + * The enforcement state of the phone provider. + */ + phoneEnforcementState?: RecaptchaProviderEnforcementState; + /** + * The reCAPTCHA managed rules. + */ + managedRules?: RecaptchaManagedRule[]; + /** + * The reCAPTCHA keys. + */ + recaptchaKeys?: RecaptchaKey[]; + /** + * Whether to use account defender for reCAPTCHA assessment. + * The default value is false. + */ + useAccountDefender?: boolean; + /** + * Whether to use the rCE bot score for reCAPTCHA phone provider. + * Can only be true when the phone_enforcement_state is AUDIT or ENFORCE. + */ + useSmsBotScore?: boolean; + /** + * Whether to use the rCE SMS toll fraud protection risk score for reCAPTCHA phone provider. + * Can only be true when the phone_enforcement_state is AUDIT or ENFORCE. + */ + useSmsTollFraudProtection?: boolean; + /** + * The managed rules for toll fraud provider, containing the enforcement status. + * The toll fraud provider contains all SMS related user flows. + */ + smsTollFraudManagedRules?: RecaptchaTollFraudManagedRule[]; +} +/** + * Server side recaptcha configuration. + */ +export interface RecaptchaAuthServerConfig { + emailPasswordEnforcementState?: RecaptchaProviderEnforcementState; + phoneEnforcementState?: RecaptchaProviderEnforcementState; + managedRules?: RecaptchaManagedRule[]; + recaptchaKeys?: RecaptchaKey[]; + useAccountDefender?: boolean; + useSmsBotScore?: boolean; + useSmsTollFraudProtection?: boolean; + tollFraudManagedRules?: RecaptchaTollFraudManagedRule[]; +} +/** + * A password policy configuration for a project or tenant +*/ +export interface PasswordPolicyConfig { + /** + * Enforcement state of the password policy + */ + enforcementState?: PasswordPolicyEnforcementState; + /** + * Require users to have a policy-compliant password to sign in + */ + forceUpgradeOnSignin?: boolean; + /** + * The constraints that make up the password strength policy + */ + constraints?: CustomStrengthOptionsConfig; +} +/** + * Configuration for settings related to univeral links (iOS) + * and app links (Android). + */ +export interface MobileLinksConfig { + /** + * Use Firebase Hosting or dynamic link domain as the out-of-band code domain. + */ + domain?: MobileLinksDomain; +} +/** + * Open code in app domain to use for app links and universal links. + */ +export type MobileLinksDomain = 'HOSTING_DOMAIN' | 'FIREBASE_DYNAMIC_LINK_DOMAIN'; +/** + * A password policy's enforcement state. + */ +export type PasswordPolicyEnforcementState = 'ENFORCE' | 'OFF'; +/** + * Constraints to be enforced on the password policy + */ +export interface CustomStrengthOptionsConfig { + /** + * The password must contain an upper case character + */ + requireUppercase?: boolean; + /** + * The password must contain a lower case character + */ + requireLowercase?: boolean; + /** + * The password must contain a non-alphanumeric character + */ + requireNonAlphanumeric?: boolean; + /** + * The password must contain a number + */ + requireNumeric?: boolean; + /** + * Minimum password length. Valid values are from 6 to 30 + */ + minLength?: number; + /** + * Maximum password length. No default max length + */ + maxLength?: number; +} +/** + * Server side password policy configuration. + */ +export interface PasswordPolicyAuthServerConfig { + passwordPolicyEnforcementState?: PasswordPolicyEnforcementState; + passwordPolicyVersions?: PasswordPolicyVersionsAuthServerConfig[]; + forceUpgradeOnSignin?: boolean; +} +/** + * Server side password policy versions configuration. + */ +export interface PasswordPolicyVersionsAuthServerConfig { + customStrengthOptions?: CustomStrengthOptionsAuthServerConfig; +} +/** + * Server side password policy constraints configuration. + */ +export interface CustomStrengthOptionsAuthServerConfig { + containsLowercaseCharacter?: boolean; + containsUppercaseCharacter?: boolean; + containsNumericCharacter?: boolean; + containsNonAlphanumericCharacter?: boolean; + minPasswordLength?: number; + maxPasswordLength?: number; +} +/** + * The email privacy configuration of a project or tenant. + */ +export interface EmailPrivacyConfig { + /** + * Whether enhanced email privacy is enabled. + */ + enableImprovedEmailPrivacy?: boolean; +} +export {}; diff --git a/node_modules/firebase-admin/lib/auth/auth-config.js b/node_modules/firebase-admin/lib/auth/auth-config.js new file mode 100644 index 0000000..964b3be --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/auth-config.js @@ -0,0 +1,1186 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EmailPrivacyAuthConfig = exports.PasswordPolicyAuthConfig = exports.MobileLinksAuthConfig = exports.RecaptchaAuthConfig = exports.SmsRegionsAuthConfig = exports.OIDCConfig = exports.SAMLConfig = exports.EmailSignInConfig = exports.MultiFactorAuthConfig = exports.MAXIMUM_TEST_PHONE_NUMBERS = void 0; +exports.validateTestPhoneNumbers = validateTestPhoneNumbers; +const validator = require("../utils/validator"); +const deep_copy_1 = require("../utils/deep-copy"); +const error_1 = require("../utils/error"); +/** A maximum of 10 test phone number / code pairs can be configured. */ +exports.MAXIMUM_TEST_PHONE_NUMBERS = 10; +/** Client Auth factor type to server auth factor type mapping. */ +const AUTH_FACTOR_CLIENT_TO_SERVER_TYPE = { + phone: 'PHONE_SMS', +}; +/** Server Auth factor type to client auth factor type mapping. */ +const AUTH_FACTOR_SERVER_TO_CLIENT_TYPE = Object.keys(AUTH_FACTOR_CLIENT_TO_SERVER_TYPE) + .reduce((res, key) => { + res[AUTH_FACTOR_CLIENT_TO_SERVER_TYPE[key]] = key; + return res; +}, {}); +/** + * Defines the multi-factor config class used to convert client side MultiFactorConfig + * to a format that is understood by the Auth server. + * + * @internal + */ +class MultiFactorAuthConfig { + /** + * Static method to convert a client side request to a MultiFactorAuthServerConfig. + * Throws an error if validation fails. + * + * @param options - The options object to convert to a server request. + * @returns The resulting server request. + * @internal + */ + static buildServerRequest(options) { + const request = {}; + MultiFactorAuthConfig.validate(options); + if (Object.prototype.hasOwnProperty.call(options, 'state')) { + request.state = options.state; + } + if (Object.prototype.hasOwnProperty.call(options, 'factorIds')) { + (options.factorIds || []).forEach((factorId) => { + if (typeof request.enabledProviders === 'undefined') { + request.enabledProviders = []; + } + request.enabledProviders.push(AUTH_FACTOR_CLIENT_TO_SERVER_TYPE[factorId]); + }); + // In case an empty array is passed. Ensure it gets populated so the array is cleared. + if (options.factorIds && options.factorIds.length === 0) { + request.enabledProviders = []; + } + } + if (Object.prototype.hasOwnProperty.call(options, 'providerConfigs')) { + request.providerConfigs = options.providerConfigs; + } + return request; + } + /** + * Validates the MultiFactorConfig options object. Throws an error on failure. + * + * @param options - The options object to validate. + */ + static validate(options) { + const validKeys = { + state: true, + factorIds: true, + providerConfigs: true, + }; + if (!validator.isNonNullObject(options)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"MultiFactorConfig" must be a non-null object.'); + } + // Check for unsupported top level attributes. + for (const key in options) { + if (!(key in validKeys)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid MultiFactorConfig parameter.`); + } + } + // Validate content. + if (typeof options.state !== 'undefined' && + options.state !== 'ENABLED' && + options.state !== 'DISABLED') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"MultiFactorConfig.state" must be either "ENABLED" or "DISABLED".'); + } + if (typeof options.factorIds !== 'undefined') { + if (!validator.isArray(options.factorIds)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"MultiFactorConfig.factorIds" must be an array of valid "AuthFactorTypes".'); + } + // Validate content of array. + options.factorIds.forEach((factorId) => { + if (typeof AUTH_FACTOR_CLIENT_TO_SERVER_TYPE[factorId] === 'undefined') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${factorId}" is not a valid "AuthFactorType".`); + } + }); + } + if (typeof options.providerConfigs !== 'undefined') { + if (!validator.isArray(options.providerConfigs)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"MultiFactorConfig.providerConfigs" must be an array of valid "MultiFactorProviderConfig."'); + } + //Validate content of array. + options.providerConfigs.forEach((multiFactorProviderConfig) => { + if (typeof multiFactorProviderConfig === 'undefined' || !validator.isObject(multiFactorProviderConfig)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${multiFactorProviderConfig}" is not a valid "MultiFactorProviderConfig" type.`); + } + const validProviderConfigKeys = { + state: true, + totpProviderConfig: true, + }; + for (const key in multiFactorProviderConfig) { + if (!(key in validProviderConfigKeys)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid ProviderConfig parameter.`); + } + } + if (typeof multiFactorProviderConfig.state === 'undefined' || + (multiFactorProviderConfig.state !== 'ENABLED' && + multiFactorProviderConfig.state !== 'DISABLED')) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"MultiFactorConfig.providerConfigs.state" must be either "ENABLED" or "DISABLED".'); + } + // Since TOTP is the only provider config available right now, not defining it will lead into an error + if (typeof multiFactorProviderConfig.totpProviderConfig === 'undefined') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"MultiFactorConfig.providerConfigs.totpProviderConfig" must be defined.'); + } + const validTotpProviderConfigKeys = { + adjacentIntervals: true, + }; + for (const key in multiFactorProviderConfig.totpProviderConfig) { + if (!(key in validTotpProviderConfigKeys)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid TotpProviderConfig parameter.`); + } + } + const adjIntervals = multiFactorProviderConfig.totpProviderConfig.adjacentIntervals; + if (typeof adjIntervals !== 'undefined' && + (!Number.isInteger(adjIntervals) || adjIntervals < 0 || adjIntervals > 10)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"MultiFactorConfig.providerConfigs.totpProviderConfig.adjacentIntervals" must' + + ' be a valid number between 0 and 10 (both inclusive).'); + } + }); + } + } + /** + * The MultiFactorAuthConfig constructor. + * + * @param response - The server side response used to initialize the + * MultiFactorAuthConfig object. + * @constructor + * @internal + */ + constructor(response) { + if (typeof response.state === 'undefined') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid multi-factor configuration response'); + } + this.state = response.state; + this.factorIds = []; + (response.enabledProviders || []).forEach((enabledProvider) => { + // Ignore unsupported types. It is possible the current admin SDK version is + // not up to date and newer backend types are supported. + if (typeof AUTH_FACTOR_SERVER_TO_CLIENT_TYPE[enabledProvider] !== 'undefined') { + this.factorIds.push(AUTH_FACTOR_SERVER_TO_CLIENT_TYPE[enabledProvider]); + } + }); + this.providerConfigs = []; + (response.providerConfigs || []).forEach((providerConfig) => { + if (typeof providerConfig !== 'undefined') { + if (typeof providerConfig.state === 'undefined' || + typeof providerConfig.totpProviderConfig === 'undefined' || + (typeof providerConfig.totpProviderConfig.adjacentIntervals !== 'undefined' && + typeof providerConfig.totpProviderConfig.adjacentIntervals !== 'number')) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid multi-factor configuration response'); + } + this.providerConfigs.push(providerConfig); + } + }); + } + /** Converts MultiFactorConfig to JSON object + * @returns The plain object representation of the multi-factor config instance. */ + toJSON() { + return { + state: this.state, + factorIds: this.factorIds, + providerConfigs: this.providerConfigs, + }; + } +} +exports.MultiFactorAuthConfig = MultiFactorAuthConfig; +/** + * Validates the provided map of test phone number / code pairs. + * @param testPhoneNumbers - The phone number / code pairs to validate. + */ +function validateTestPhoneNumbers(testPhoneNumbers) { + if (!validator.isObject(testPhoneNumbers)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"testPhoneNumbers" must be a map of phone number / code pairs.'); + } + if (Object.keys(testPhoneNumbers).length > exports.MAXIMUM_TEST_PHONE_NUMBERS) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MAXIMUM_TEST_PHONE_NUMBER_EXCEEDED); + } + for (const phoneNumber in testPhoneNumbers) { + // Validate phone number. + if (!validator.isPhoneNumber(phoneNumber)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_TESTING_PHONE_NUMBER, `"${phoneNumber}" is not a valid E.164 standard compliant phone number.`); + } + // Validate code. + if (!validator.isString(testPhoneNumbers[phoneNumber]) || + !/^[\d]{6}$/.test(testPhoneNumbers[phoneNumber])) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_TESTING_PHONE_NUMBER, `"${testPhoneNumbers[phoneNumber]}" is not a valid 6 digit code string.`); + } + } +} +/** + * Defines the email sign-in config class used to convert client side EmailSignInConfig + * to a format that is understood by the Auth server. + * + * @internal + */ +class EmailSignInConfig { + /** + * Static method to convert a client side request to a EmailSignInConfigServerRequest. + * Throws an error if validation fails. + * + * @param options - The options object to convert to a server request. + * @returns The resulting server request. + * @internal + */ + static buildServerRequest(options) { + const request = {}; + EmailSignInConfig.validate(options); + if (Object.prototype.hasOwnProperty.call(options, 'enabled')) { + request.allowPasswordSignup = options.enabled; + } + if (Object.prototype.hasOwnProperty.call(options, 'passwordRequired')) { + request.enableEmailLinkSignin = !options.passwordRequired; + } + return request; + } + /** + * Validates the EmailSignInConfig options object. Throws an error on failure. + * + * @param options - The options object to validate. + */ + static validate(options) { + // TODO: Validate the request. + const validKeys = { + enabled: true, + passwordRequired: true, + }; + if (!validator.isNonNullObject(options)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"EmailSignInConfig" must be a non-null object.'); + } + // Check for unsupported top level attributes. + for (const key in options) { + if (!(key in validKeys)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, `"${key}" is not a valid EmailSignInConfig parameter.`); + } + } + // Validate content. + if (typeof options.enabled !== 'undefined' && + !validator.isBoolean(options.enabled)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"EmailSignInConfig.enabled" must be a boolean.'); + } + if (typeof options.passwordRequired !== 'undefined' && + !validator.isBoolean(options.passwordRequired)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"EmailSignInConfig.passwordRequired" must be a boolean.'); + } + } + /** + * The EmailSignInConfig constructor. + * + * @param response - The server side response used to initialize the + * EmailSignInConfig object. + * @constructor + */ + constructor(response) { + if (typeof response.allowPasswordSignup === 'undefined') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid email sign-in configuration response'); + } + this.enabled = response.allowPasswordSignup; + this.passwordRequired = !response.enableEmailLinkSignin; + } + /** @returns The plain object representation of the email sign-in config. */ + toJSON() { + return { + enabled: this.enabled, + passwordRequired: this.passwordRequired, + }; + } +} +exports.EmailSignInConfig = EmailSignInConfig; +/** + * Defines the SAMLConfig class used to convert a client side configuration to its + * server side representation. + * + * @internal + */ +class SAMLConfig { + /** + * Converts a client side request to a SAMLConfigServerRequest which is the format + * accepted by the backend server. + * Throws an error if validation fails. If the request is not a SAMLConfig request, + * returns null. + * + * @param options - The options object to convert to a server request. + * @param ignoreMissingFields - Whether to ignore missing fields. + * @returns The resulting server request or null if not valid. + */ + static buildServerRequest(options, ignoreMissingFields = false) { + const makeRequest = validator.isNonNullObject(options) && + (options.providerId || ignoreMissingFields); + if (!makeRequest) { + return null; + } + const request = {}; + // Validate options. + SAMLConfig.validate(options, ignoreMissingFields); + request.enabled = options.enabled; + request.displayName = options.displayName; + // IdP config. + if (options.idpEntityId || options.ssoURL || options.x509Certificates) { + request.idpConfig = { + idpEntityId: options.idpEntityId, + ssoUrl: options.ssoURL, + signRequest: options.enableRequestSigning, + idpCertificates: typeof options.x509Certificates === 'undefined' ? undefined : [], + }; + if (options.x509Certificates) { + for (const cert of (options.x509Certificates || [])) { + request.idpConfig.idpCertificates.push({ x509Certificate: cert }); + } + } + } + // RP config. + if (options.callbackURL || options.rpEntityId) { + request.spConfig = { + spEntityId: options.rpEntityId, + callbackUri: options.callbackURL, + }; + } + return request; + } + /** + * Returns the provider ID corresponding to the resource name if available. + * + * @param resourceName - The server side resource name. + * @returns The provider ID corresponding to the resource, null otherwise. + */ + static getProviderIdFromResourceName(resourceName) { + // name is of form projects/project1/inboundSamlConfigs/providerId1 + const matchProviderRes = resourceName.match(/\/inboundSamlConfigs\/(saml\..*)$/); + if (!matchProviderRes || matchProviderRes.length < 2) { + return null; + } + return matchProviderRes[1]; + } + /** + * @param providerId - The provider ID to check. + * @returns Whether the provider ID corresponds to a SAML provider. + */ + static isProviderId(providerId) { + return validator.isNonEmptyString(providerId) && providerId.indexOf('saml.') === 0; + } + /** + * Validates the SAMLConfig options object. Throws an error on failure. + * + * @param options - The options object to validate. + * @param ignoreMissingFields - Whether to ignore missing fields. + */ + static validate(options, ignoreMissingFields = false) { + const validKeys = { + enabled: true, + displayName: true, + providerId: true, + idpEntityId: true, + ssoURL: true, + x509Certificates: true, + rpEntityId: true, + callbackURL: true, + enableRequestSigning: true, + }; + if (!validator.isNonNullObject(options)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig" must be a valid non-null object.'); + } + // Check for unsupported top level attributes. + for (const key in options) { + if (!(key in validKeys)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid SAML config parameter.`); + } + } + // Required fields. + if (validator.isNonEmptyString(options.providerId)) { + if (options.providerId.indexOf('saml.') !== 0) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID, '"SAMLAuthProviderConfig.providerId" must be a valid non-empty string prefixed with "saml.".'); + } + } + else if (!ignoreMissingFields) { + // providerId is required and not provided correctly. + throw new error_1.FirebaseAuthError(!options.providerId ? error_1.AuthClientErrorCode.MISSING_PROVIDER_ID : error_1.AuthClientErrorCode.INVALID_PROVIDER_ID, '"SAMLAuthProviderConfig.providerId" must be a valid non-empty string prefixed with "saml.".'); + } + if (!(ignoreMissingFields && typeof options.idpEntityId === 'undefined') && + !validator.isNonEmptyString(options.idpEntityId)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.idpEntityId" must be a valid non-empty string.'); + } + if (!(ignoreMissingFields && typeof options.ssoURL === 'undefined') && + !validator.isURL(options.ssoURL)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.ssoURL" must be a valid URL string.'); + } + if (!(ignoreMissingFields && typeof options.rpEntityId === 'undefined') && + !validator.isNonEmptyString(options.rpEntityId)) { + throw new error_1.FirebaseAuthError(!options.rpEntityId ? error_1.AuthClientErrorCode.MISSING_SAML_RELYING_PARTY_CONFIG : + error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.rpEntityId" must be a valid non-empty string.'); + } + if (!(ignoreMissingFields && typeof options.callbackURL === 'undefined') && + !validator.isURL(options.callbackURL)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.callbackURL" must be a valid URL string.'); + } + if (!(ignoreMissingFields && typeof options.x509Certificates === 'undefined') && + !validator.isArray(options.x509Certificates)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.x509Certificates" must be a valid array of X509 certificate strings.'); + } + (options.x509Certificates || []).forEach((cert) => { + if (!validator.isNonEmptyString(cert)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.x509Certificates" must be a valid array of X509 certificate strings.'); + } + }); + if (typeof options.enableRequestSigning !== 'undefined' && + !validator.isBoolean(options.enableRequestSigning)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.enableRequestSigning" must be a boolean.'); + } + if (typeof options.enabled !== 'undefined' && + !validator.isBoolean(options.enabled)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.enabled" must be a boolean.'); + } + if (typeof options.displayName !== 'undefined' && + !validator.isString(options.displayName)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.displayName" must be a valid string.'); + } + } + /** + * The SAMLConfig constructor. + * + * @param response - The server side response used to initialize the SAMLConfig object. + * @constructor + */ + constructor(response) { + if (!response || + !response.idpConfig || + !response.idpConfig.idpEntityId || + !response.idpConfig.ssoUrl || + !response.spConfig || + !response.spConfig.spEntityId || + !response.name || + !(validator.isString(response.name) && + SAMLConfig.getProviderIdFromResourceName(response.name))) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid SAML configuration response'); + } + const providerId = SAMLConfig.getProviderIdFromResourceName(response.name); + if (!providerId) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid SAML configuration response'); + } + this.providerId = providerId; + // RP config. + this.rpEntityId = response.spConfig.spEntityId; + this.callbackURL = response.spConfig.callbackUri; + // IdP config. + this.idpEntityId = response.idpConfig.idpEntityId; + this.ssoURL = response.idpConfig.ssoUrl; + this.enableRequestSigning = !!response.idpConfig.signRequest; + const x509Certificates = []; + for (const cert of (response.idpConfig.idpCertificates || [])) { + if (cert.x509Certificate) { + x509Certificates.push(cert.x509Certificate); + } + } + this.x509Certificates = x509Certificates; + // When enabled is undefined, it takes its default value of false. + this.enabled = !!response.enabled; + this.displayName = response.displayName; + } + /** @returns The plain object representation of the SAMLConfig. */ + toJSON() { + return { + enabled: this.enabled, + displayName: this.displayName, + providerId: this.providerId, + idpEntityId: this.idpEntityId, + ssoURL: this.ssoURL, + x509Certificates: (0, deep_copy_1.deepCopy)(this.x509Certificates), + rpEntityId: this.rpEntityId, + callbackURL: this.callbackURL, + enableRequestSigning: this.enableRequestSigning, + }; + } +} +exports.SAMLConfig = SAMLConfig; +/** + * Defines the OIDCConfig class used to convert a client side configuration to its + * server side representation. + * + * @internal + */ +class OIDCConfig { + /** + * Converts a client side request to a OIDCConfigServerRequest which is the format + * accepted by the backend server. + * Throws an error if validation fails. If the request is not a OIDCConfig request, + * returns null. + * + * @param options - The options object to convert to a server request. + * @param ignoreMissingFields - Whether to ignore missing fields. + * @returns The resulting server request or null if not valid. + */ + static buildServerRequest(options, ignoreMissingFields = false) { + const makeRequest = validator.isNonNullObject(options) && + (options.providerId || ignoreMissingFields); + if (!makeRequest) { + return null; + } + const request = {}; + // Validate options. + OIDCConfig.validate(options, ignoreMissingFields); + request.enabled = options.enabled; + request.displayName = options.displayName; + request.issuer = options.issuer; + request.clientId = options.clientId; + if (typeof options.clientSecret !== 'undefined') { + request.clientSecret = options.clientSecret; + } + if (typeof options.responseType !== 'undefined') { + request.responseType = options.responseType; + } + return request; + } + /** + * Returns the provider ID corresponding to the resource name if available. + * + * @param resourceName - The server side resource name + * @returns The provider ID corresponding to the resource, null otherwise. + */ + static getProviderIdFromResourceName(resourceName) { + // name is of form projects/project1/oauthIdpConfigs/providerId1 + const matchProviderRes = resourceName.match(/\/oauthIdpConfigs\/(oidc\..*)$/); + if (!matchProviderRes || matchProviderRes.length < 2) { + return null; + } + return matchProviderRes[1]; + } + /** + * @param providerId - The provider ID to check. + * @returns Whether the provider ID corresponds to an OIDC provider. + */ + static isProviderId(providerId) { + return validator.isNonEmptyString(providerId) && providerId.indexOf('oidc.') === 0; + } + /** + * Validates the OIDCConfig options object. Throws an error on failure. + * + * @param options - The options object to validate. + * @param ignoreMissingFields - Whether to ignore missing fields. + */ + static validate(options, ignoreMissingFields = false) { + const validKeys = { + enabled: true, + displayName: true, + providerId: true, + clientId: true, + issuer: true, + clientSecret: true, + responseType: true, + }; + const validResponseTypes = { + idToken: true, + code: true, + }; + if (!validator.isNonNullObject(options)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"OIDCAuthProviderConfig" must be a valid non-null object.'); + } + // Check for unsupported top level attributes. + for (const key in options) { + if (!(key in validKeys)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid OIDC config parameter.`); + } + } + // Required fields. + if (validator.isNonEmptyString(options.providerId)) { + if (options.providerId.indexOf('oidc.') !== 0) { + throw new error_1.FirebaseAuthError(!options.providerId ? error_1.AuthClientErrorCode.MISSING_PROVIDER_ID : error_1.AuthClientErrorCode.INVALID_PROVIDER_ID, '"OIDCAuthProviderConfig.providerId" must be a valid non-empty string prefixed with "oidc.".'); + } + } + else if (!ignoreMissingFields) { + throw new error_1.FirebaseAuthError(!options.providerId ? error_1.AuthClientErrorCode.MISSING_PROVIDER_ID : error_1.AuthClientErrorCode.INVALID_PROVIDER_ID, '"OIDCAuthProviderConfig.providerId" must be a valid non-empty string prefixed with "oidc.".'); + } + if (!(ignoreMissingFields && typeof options.clientId === 'undefined') && + !validator.isNonEmptyString(options.clientId)) { + throw new error_1.FirebaseAuthError(!options.clientId ? error_1.AuthClientErrorCode.MISSING_OAUTH_CLIENT_ID : error_1.AuthClientErrorCode.INVALID_OAUTH_CLIENT_ID, '"OIDCAuthProviderConfig.clientId" must be a valid non-empty string.'); + } + if (!(ignoreMissingFields && typeof options.issuer === 'undefined') && + !validator.isURL(options.issuer)) { + throw new error_1.FirebaseAuthError(!options.issuer ? error_1.AuthClientErrorCode.MISSING_ISSUER : error_1.AuthClientErrorCode.INVALID_CONFIG, '"OIDCAuthProviderConfig.issuer" must be a valid URL string.'); + } + if (typeof options.enabled !== 'undefined' && + !validator.isBoolean(options.enabled)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"OIDCAuthProviderConfig.enabled" must be a boolean.'); + } + if (typeof options.displayName !== 'undefined' && + !validator.isString(options.displayName)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"OIDCAuthProviderConfig.displayName" must be a valid string.'); + } + if (typeof options.clientSecret !== 'undefined' && + !validator.isNonEmptyString(options.clientSecret)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"OIDCAuthProviderConfig.clientSecret" must be a valid string.'); + } + if (validator.isNonNullObject(options.responseType) && typeof options.responseType !== 'undefined') { + Object.keys(options.responseType).forEach((key) => { + if (!(key in validResponseTypes)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid OAuthResponseType parameter.`); + } + }); + const idToken = options.responseType.idToken; + if (typeof idToken !== 'undefined' && !validator.isBoolean(idToken)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"OIDCAuthProviderConfig.responseType.idToken" must be a boolean.'); + } + const code = options.responseType.code; + if (typeof code !== 'undefined') { + if (!validator.isBoolean(code)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"OIDCAuthProviderConfig.responseType.code" must be a boolean.'); + } + // If code flow is enabled, client secret must be provided. + if (code && typeof options.clientSecret === 'undefined') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISSING_OAUTH_CLIENT_SECRET, 'The OAuth configuration client secret is required to enable OIDC code flow.'); + } + } + const allKeys = Object.keys(options.responseType).length; + const enabledCount = Object.values(options.responseType).filter(Boolean).length; + // Only one of OAuth response types can be set to true. + if (allKeys > 1 && enabledCount !== 1) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_OAUTH_RESPONSETYPE, 'Only exactly one OAuth responseType should be set to true.'); + } + } + } + /** + * The OIDCConfig constructor. + * + * @param response - The server side response used to initialize the OIDCConfig object. + * @constructor + */ + constructor(response) { + if (!response || + !response.issuer || + !response.clientId || + !response.name || + !(validator.isString(response.name) && + OIDCConfig.getProviderIdFromResourceName(response.name))) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid OIDC configuration response'); + } + const providerId = OIDCConfig.getProviderIdFromResourceName(response.name); + if (!providerId) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid SAML configuration response'); + } + this.providerId = providerId; + this.clientId = response.clientId; + this.issuer = response.issuer; + // When enabled is undefined, it takes its default value of false. + this.enabled = !!response.enabled; + this.displayName = response.displayName; + if (typeof response.clientSecret !== 'undefined') { + this.clientSecret = response.clientSecret; + } + if (typeof response.responseType !== 'undefined') { + this.responseType = response.responseType; + } + } + /** @returns The plain object representation of the OIDCConfig. */ + toJSON() { + return { + enabled: this.enabled, + displayName: this.displayName, + providerId: this.providerId, + issuer: this.issuer, + clientId: this.clientId, + clientSecret: (0, deep_copy_1.deepCopy)(this.clientSecret), + responseType: (0, deep_copy_1.deepCopy)(this.responseType), + }; + } +} +exports.OIDCConfig = OIDCConfig; +/** + * Defines the SMSRegionConfig class used for validation. + * + * @internal + */ +class SmsRegionsAuthConfig { + static validate(options) { + if (!validator.isNonNullObject(options)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SmsRegionConfig" must be a non-null object.'); + } + const validKeys = { + allowlistOnly: true, + allowByDefault: true, + }; + for (const key in options) { + if (!(key in validKeys)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid SmsRegionConfig parameter.`); + } + } + // validate mutual exclusiveness of allowByDefault and allowlistOnly + if (typeof options.allowByDefault !== 'undefined' && typeof options.allowlistOnly !== 'undefined') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, 'SmsRegionConfig cannot have both "allowByDefault" and "allowlistOnly" parameters.'); + } + // validation for allowByDefault type + if (typeof options.allowByDefault !== 'undefined') { + const allowByDefaultValidKeys = { + disallowedRegions: true, + }; + for (const key in options.allowByDefault) { + if (!(key in allowByDefaultValidKeys)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid SmsRegionConfig.allowByDefault parameter.`); + } + } + // disallowedRegion can be empty. + if (typeof options.allowByDefault.disallowedRegions !== 'undefined' + && !validator.isArray(options.allowByDefault.disallowedRegions)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SmsRegionConfig.allowByDefault.disallowedRegions" must be a valid string array.'); + } + } + if (typeof options.allowlistOnly !== 'undefined') { + const allowListOnlyValidKeys = { + allowedRegions: true, + }; + for (const key in options.allowlistOnly) { + if (!(key in allowListOnlyValidKeys)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid SmsRegionConfig.allowlistOnly parameter.`); + } + } + // allowedRegions can be empty + if (typeof options.allowlistOnly.allowedRegions !== 'undefined' + && !validator.isArray(options.allowlistOnly.allowedRegions)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SmsRegionConfig.allowlistOnly.allowedRegions" must be a valid string array.'); + } + } + } +} +exports.SmsRegionsAuthConfig = SmsRegionsAuthConfig; +/** + * Defines the recaptcha config class used to convert client side RecaptchaConfig + * to a format that is understood by the Auth server. + * + * @internal + */ +class RecaptchaAuthConfig { + /** + * The RecaptchaAuthConfig constructor. + * + * @param response - The server side response used to initialize the + * RecaptchaAuthConfig object. + * @constructor + * @internal + */ + constructor(response) { + const filteredResponse = Object.fromEntries(Object.entries(response).filter(([, value]) => value !== undefined)); + // Explicitly map the 'tollFraudManagedRules' to 'smsTollFraudManagedRules' + if (filteredResponse.tollFraudManagedRules !== undefined) { + this.smsTollFraudManagedRules = filteredResponse.tollFraudManagedRules; + delete filteredResponse.tollFraudManagedRules; // Remove it if necessary + } + // Assign the remaining properties directly + Object.assign(this, filteredResponse); + } + /** + * Builds a server request object from the client-side RecaptchaConfig. + * Converts client-side fields to their server-side equivalents. + * + * @param options - The client-side RecaptchaConfig object. + * @returns The server-side RecaptchaAuthServerConfig object. + */ + static buildServerRequest(options) { + RecaptchaAuthConfig.validate(options); // Validate options before building request + const request = {}; + if (typeof options.emailPasswordEnforcementState !== 'undefined') { + request.emailPasswordEnforcementState = options.emailPasswordEnforcementState; + } + if (typeof options.phoneEnforcementState !== 'undefined') { + request.phoneEnforcementState = options.phoneEnforcementState; + } + if (typeof options.managedRules !== 'undefined') { + request.managedRules = options.managedRules; + } + if (typeof options.recaptchaKeys !== 'undefined') { + request.recaptchaKeys = options.recaptchaKeys; + } + if (typeof options.useAccountDefender !== 'undefined') { + request.useAccountDefender = options.useAccountDefender; + } + if (typeof options.useSmsBotScore !== 'undefined') { + request.useSmsBotScore = options.useSmsBotScore; + } + if (typeof options.useSmsTollFraudProtection !== 'undefined') { + request.useSmsTollFraudProtection = options.useSmsTollFraudProtection; + } + if (typeof options.smsTollFraudManagedRules !== 'undefined') { + request.tollFraudManagedRules = options.smsTollFraudManagedRules; // Map client-side field to server-side + } + return request; + } + /** + * Validates the RecaptchaConfig options object. Throws an error on failure. + * @param options - The options object to validate. + */ + static validate(options) { + const validKeys = { + emailPasswordEnforcementState: true, + phoneEnforcementState: true, + managedRules: true, + recaptchaKeys: true, + useAccountDefender: true, + useSmsBotScore: true, + useSmsTollFraudProtection: true, + smsTollFraudManagedRules: true, + }; + if (!validator.isNonNullObject(options)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"RecaptchaConfig" must be a non-null object.'); + } + for (const key in options) { + if (!(key in validKeys)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid RecaptchaConfig parameter.`); + } + } + // Validation + if (typeof options.emailPasswordEnforcementState !== 'undefined') { + if (!validator.isNonEmptyString(options.emailPasswordEnforcementState)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"RecaptchaConfig.emailPasswordEnforcementState" must be a valid non-empty string.'); + } + if (options.emailPasswordEnforcementState !== 'OFF' && + options.emailPasswordEnforcementState !== 'AUDIT' && + options.emailPasswordEnforcementState !== 'ENFORCE') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"RecaptchaConfig.emailPasswordEnforcementState" must be either "OFF", "AUDIT" or "ENFORCE".'); + } + } + if (typeof options.phoneEnforcementState !== 'undefined') { + if (!validator.isNonEmptyString(options.phoneEnforcementState)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"RecaptchaConfig.phoneEnforcementState" must be a valid non-empty string.'); + } + if (options.phoneEnforcementState !== 'OFF' && + options.phoneEnforcementState !== 'AUDIT' && + options.phoneEnforcementState !== 'ENFORCE') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"RecaptchaConfig.phoneEnforcementState" must be either "OFF", "AUDIT" or "ENFORCE".'); + } + } + if (typeof options.managedRules !== 'undefined') { + // Validate array + if (!validator.isArray(options.managedRules)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"RecaptchaConfig.managedRules" must be an array of valid "RecaptchaManagedRule".'); + } + // Validate each rule of the array + options.managedRules.forEach((managedRule) => { + RecaptchaAuthConfig.validateManagedRule(managedRule); + }); + } + if (typeof options.useAccountDefender !== 'undefined') { + if (!validator.isBoolean(options.useAccountDefender)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"RecaptchaConfig.useAccountDefender" must be a boolean value".'); + } + } + if (typeof options.useSmsBotScore !== 'undefined') { + if (!validator.isBoolean(options.useSmsBotScore)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"RecaptchaConfig.useSmsBotScore" must be a boolean value".'); + } + } + if (typeof options.useSmsTollFraudProtection !== 'undefined') { + if (!validator.isBoolean(options.useSmsTollFraudProtection)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"RecaptchaConfig.useSmsTollFraudProtection" must be a boolean value".'); + } + } + if (typeof options.smsTollFraudManagedRules !== 'undefined') { + // Validate array + if (!validator.isArray(options.smsTollFraudManagedRules)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"RecaptchaConfig.smsTollFraudManagedRules" must be an array of valid "RecaptchaTollFraudManagedRule".'); + } + // Validate each rule of the array + options.smsTollFraudManagedRules.forEach((tollFraudManagedRule) => { + RecaptchaAuthConfig.validateTollFraudManagedRule(tollFraudManagedRule); + }); + } + } + /** + * Validate each element in ManagedRule array + * @param options - The options object to validate. + */ + static validateManagedRule(options) { + const validKeys = { + endScore: true, + action: true, + }; + if (!validator.isNonNullObject(options)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"RecaptchaManagedRule" must be a non-null object.'); + } + // Check for unsupported top level attributes. + for (const key in options) { + if (!(key in validKeys)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid RecaptchaManagedRule parameter.`); + } + } + // Validate content. + if (typeof options.action !== 'undefined' && + options.action !== 'BLOCK') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"RecaptchaManagedRule.action" must be "BLOCK".'); + } + } + /** + * Validate each element in TollFraudManagedRule array + * @param options - The options object to validate. + */ + static validateTollFraudManagedRule(options) { + const validKeys = { + startScore: true, + action: true, + }; + if (!validator.isNonNullObject(options)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"RecaptchaTollFraudManagedRule" must be a non-null object.'); + } + // Check for unsupported top level attributes. + for (const key in options) { + if (!(key in validKeys)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid RecaptchaTollFraudManagedRule parameter.`); + } + } + // Validate content. + if (typeof options.action !== 'undefined' && + options.action !== 'BLOCK') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"RecaptchaTollFraudManagedRule.action" must be "BLOCK".'); + } + } +} +exports.RecaptchaAuthConfig = RecaptchaAuthConfig; +/** + * Defines the MobileLinksAuthConfig class used for validation. + * + * @internal + */ +class MobileLinksAuthConfig { + static validate(options) { + if (!validator.isNonNullObject(options)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"MobileLinksConfig" must be a non-null object.'); + } + const validKeys = { + domain: true, + }; + for (const key in options) { + if (!(key in validKeys)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid "MobileLinksConfig" parameter.`); + } + } + if (typeof options.domain !== 'undefined' + && options.domain !== 'HOSTING_DOMAIN' + && options.domain !== 'FIREBASE_DYNAMIC_LINK_DOMAIN') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"MobileLinksConfig.domain" must be either "HOSTING_DOMAIN" or "FIREBASE_DYNAMIC_LINK_DOMAIN".'); + } + } +} +exports.MobileLinksAuthConfig = MobileLinksAuthConfig; +/** + * Defines the password policy config class used to convert client side PasswordPolicyConfig + * to a format that is understood by the Auth server. + * + * @internal + */ +class PasswordPolicyAuthConfig { + /** + * Static method to convert a client side request to a PasswordPolicyAuthServerConfig. + * Throws an error if validation fails. + * + * @param options - The options object to convert to a server request. + * @returns The resulting server request. + * @internal + */ + static buildServerRequest(options) { + const request = {}; + PasswordPolicyAuthConfig.validate(options); + if (Object.prototype.hasOwnProperty.call(options, 'enforcementState')) { + request.passwordPolicyEnforcementState = options.enforcementState; + } + request.forceUpgradeOnSignin = false; + if (Object.prototype.hasOwnProperty.call(options, 'forceUpgradeOnSignin')) { + request.forceUpgradeOnSignin = options.forceUpgradeOnSignin; + } + const constraintsRequest = { + containsUppercaseCharacter: false, + containsLowercaseCharacter: false, + containsNonAlphanumericCharacter: false, + containsNumericCharacter: false, + minPasswordLength: 6, + maxPasswordLength: 4096, + }; + request.passwordPolicyVersions = []; + if (Object.prototype.hasOwnProperty.call(options, 'constraints')) { + if (options) { + if (options.constraints?.requireUppercase !== undefined) { + constraintsRequest.containsUppercaseCharacter = options.constraints.requireUppercase; + } + if (options.constraints?.requireLowercase !== undefined) { + constraintsRequest.containsLowercaseCharacter = options.constraints.requireLowercase; + } + if (options.constraints?.requireNonAlphanumeric !== undefined) { + constraintsRequest.containsNonAlphanumericCharacter = options.constraints.requireNonAlphanumeric; + } + if (options.constraints?.requireNumeric !== undefined) { + constraintsRequest.containsNumericCharacter = options.constraints.requireNumeric; + } + if (options.constraints?.minLength !== undefined) { + constraintsRequest.minPasswordLength = options.constraints.minLength; + } + if (options.constraints?.maxLength !== undefined) { + constraintsRequest.maxPasswordLength = options.constraints.maxLength; + } + } + } + request.passwordPolicyVersions.push({ customStrengthOptions: constraintsRequest }); + return request; + } + /** + * Validates the PasswordPolicyConfig options object. Throws an error on failure. + * + * @param options - The options object to validate. + * @internal + */ + static validate(options) { + const validKeys = { + enforcementState: true, + forceUpgradeOnSignin: true, + constraints: true, + }; + if (!validator.isNonNullObject(options)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig" must be a non-null object.'); + } + // Check for unsupported top level attributes. + for (const key in options) { + if (!(key in validKeys)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid PasswordPolicyConfig parameter.`); + } + } + // Validate content. + if (typeof options.enforcementState === 'undefined' || + !(options.enforcementState === 'ENFORCE' || + options.enforcementState === 'OFF')) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.enforcementState" must be either "ENFORCE" or "OFF".'); + } + if (typeof options.forceUpgradeOnSignin !== 'undefined') { + if (!validator.isBoolean(options.forceUpgradeOnSignin)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.forceUpgradeOnSignin" must be a boolean.'); + } + } + if (typeof options.constraints !== 'undefined') { + if (options.enforcementState === 'ENFORCE' && !validator.isNonNullObject(options.constraints)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.constraints" must be a non-empty object.'); + } + const validCharKeys = { + requireUppercase: true, + requireLowercase: true, + requireNumeric: true, + requireNonAlphanumeric: true, + minLength: true, + maxLength: true, + }; + // Check for unsupported attributes. + for (const key in options.constraints) { + if (!(key in validCharKeys)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid PasswordPolicyConfig.constraints parameter.`); + } + } + if (typeof options.constraints.requireUppercase !== 'undefined' && + !validator.isBoolean(options.constraints.requireUppercase)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.constraints.requireUppercase" must be a boolean.'); + } + if (typeof options.constraints.requireLowercase !== 'undefined' && + !validator.isBoolean(options.constraints.requireLowercase)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.constraints.requireLowercase" must be a boolean.'); + } + if (typeof options.constraints.requireNonAlphanumeric !== 'undefined' && + !validator.isBoolean(options.constraints.requireNonAlphanumeric)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.constraints.requireNonAlphanumeric"' + + ' must be a boolean.'); + } + if (typeof options.constraints.requireNumeric !== 'undefined' && + !validator.isBoolean(options.constraints.requireNumeric)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.constraints.requireNumeric" must be a boolean.'); + } + if (typeof options.constraints.minLength === 'undefined') { + options.constraints.minLength = 6; + } + else if (!validator.isNumber(options.constraints.minLength)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.constraints.minLength" must be a number.'); + } + else { + if (!(options.constraints.minLength >= 6 + && options.constraints.minLength <= 30)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.constraints.minLength"' + + ' must be an integer between 6 and 30, inclusive.'); + } + } + if (typeof options.constraints.maxLength === 'undefined') { + options.constraints.maxLength = 4096; + } + else if (!validator.isNumber(options.constraints.maxLength)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.constraints.maxLength" must be a number.'); + } + else { + if (!(options.constraints.maxLength >= options.constraints.minLength && + options.constraints.maxLength <= 4096)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.constraints.maxLength"' + + ' must be greater than or equal to minLength and at max 4096.'); + } + } + } + else { + if (options.enforcementState === 'ENFORCE') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"PasswordPolicyConfig.constraints" must be defined.'); + } + } + } + /** + * The PasswordPolicyAuthConfig constructor. + * + * @param response - The server side response used to initialize the + * PasswordPolicyAuthConfig object. + * @constructor + * @internal + */ + constructor(response) { + if (typeof response.passwordPolicyEnforcementState === 'undefined') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid password policy configuration response'); + } + this.enforcementState = response.passwordPolicyEnforcementState; + let constraintsResponse = {}; + if (typeof response.passwordPolicyVersions !== 'undefined') { + (response.passwordPolicyVersions || []).forEach((policyVersion) => { + constraintsResponse = { + requireLowercase: policyVersion.customStrengthOptions?.containsLowercaseCharacter, + requireUppercase: policyVersion.customStrengthOptions?.containsUppercaseCharacter, + requireNonAlphanumeric: policyVersion.customStrengthOptions?.containsNonAlphanumericCharacter, + requireNumeric: policyVersion.customStrengthOptions?.containsNumericCharacter, + minLength: policyVersion.customStrengthOptions?.minPasswordLength, + maxLength: policyVersion.customStrengthOptions?.maxPasswordLength, + }; + }); + } + this.constraints = constraintsResponse; + this.forceUpgradeOnSignin = response.forceUpgradeOnSignin ? true : false; + } +} +exports.PasswordPolicyAuthConfig = PasswordPolicyAuthConfig; +/** + * Defines the EmailPrivacyAuthConfig class used for validation. + * + * @internal + */ +class EmailPrivacyAuthConfig { + static validate(options) { + if (!validator.isNonNullObject(options)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"EmailPrivacyConfig" must be a non-null object.'); + } + const validKeys = { + enableImprovedEmailPrivacy: true, + }; + for (const key in options) { + if (!(key in validKeys)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid "EmailPrivacyConfig" parameter.`); + } + } + if (typeof options.enableImprovedEmailPrivacy !== 'undefined' + && !validator.isBoolean(options.enableImprovedEmailPrivacy)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"EmailPrivacyConfig.enableImprovedEmailPrivacy" must be a valid boolean value.'); + } + } +} +exports.EmailPrivacyAuthConfig = EmailPrivacyAuthConfig; diff --git a/node_modules/firebase-admin/lib/auth/auth-namespace.d.ts b/node_modules/firebase-admin/lib/auth/auth-namespace.d.ts new file mode 100644 index 0000000..af0bdeb --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/auth-namespace.d.ts @@ -0,0 +1,257 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app/index'; +import { ActionCodeSettings as TActionCodeSettings } from './action-code-settings-builder'; +import { Auth as TAuth } from './auth'; +import { AuthFactorType as TAuthFactorType, AuthProviderConfig as TAuthProviderConfig, AuthProviderConfigFilter as TAuthProviderConfigFilter, CreateRequest as TCreateRequest, CreateMultiFactorInfoRequest as TCreateMultiFactorInfoRequest, CreatePhoneMultiFactorInfoRequest as TCreatePhoneMultiFactorInfoRequest, EmailSignInProviderConfig as TEmailSignInProviderConfig, ListProviderConfigResults as TListProviderConfigResults, MultiFactorCreateSettings as TMultiFactorCreateSettings, MultiFactorConfig as TMultiFactorConfig, MultiFactorConfigState as TMultiFactorConfigState, MultiFactorUpdateSettings as TMultiFactorUpdateSettings, OIDCAuthProviderConfig as TOIDCAuthProviderConfig, OIDCUpdateAuthProviderRequest as TOIDCUpdateAuthProviderRequest, SAMLAuthProviderConfig as TSAMLAuthProviderConfig, SAMLUpdateAuthProviderRequest as TSAMLUpdateAuthProviderRequest, UpdateAuthProviderRequest as TUpdateAuthProviderRequest, UpdateMultiFactorInfoRequest as TUpdateMultiFactorInfoRequest, UpdatePhoneMultiFactorInfoRequest as TUpdatePhoneMultiFactorInfoRequest, UpdateRequest as TUpdateRequest } from './auth-config'; +import { BaseAuth as TBaseAuth, DeleteUsersResult as TDeleteUsersResult, GetUsersResult as TGetUsersResult, ListUsersResult as TListUsersResult, SessionCookieOptions as TSessionCookieOptions } from './base-auth'; +import { EmailIdentifier as TEmailIdentifier, PhoneIdentifier as TPhoneIdentifier, ProviderIdentifier as TProviderIdentifier, UserIdentifier as TUserIdentifier, UidIdentifier as TUidIdentifier } from './identifier'; +import { CreateTenantRequest as TCreateTenantRequest, Tenant as TTenant, UpdateTenantRequest as TUpdateTenantRequest } from './tenant'; +import { ListTenantsResult as TListTenantsResult, TenantAwareAuth as TTenantAwareAuth, TenantManager as TTenantManager } from './tenant-manager'; +import { DecodedIdToken as TDecodedIdToken, DecodedAuthBlockingToken as TDecodedAuthBlockingToken } from './token-verifier'; +import { HashAlgorithmType as THashAlgorithmType, UserImportOptions as TUserImportOptions, UserImportRecord as TUserImportRecord, UserImportResult as TUserImportResult, UserMetadataRequest as TUserMetadataRequest, UserProviderRequest as TUserProviderRequest } from './user-import-builder'; +import { MultiFactorInfo as TMultiFactorInfo, MultiFactorSettings as TMultiFactorSettings, PhoneMultiFactorInfo as TPhoneMultiFactorInfo, UserInfo as TUserInfo, UserMetadata as TUserMetadata, UserRecord as TUserRecord } from './user-record'; +/** + * Gets the {@link firebase-admin.auth#Auth} service for the default app or a + * given app. + * + * `admin.auth()` can be called with no arguments to access the default app's + * {@link firebase-admin.auth#Auth} service or as `admin.auth(app)` to access the + * {@link firebase-admin.auth#Auth} service associated with a specific app. + * + * @example + * ```javascript + * // Get the Auth service for the default app + * var defaultAuth = admin.auth(); + * ``` + * + * @example + * ```javascript + * // Get the Auth service for a given app + * var otherAuth = admin.auth(otherApp); + * ``` + * + */ +export declare function auth(app?: App): auth.Auth; +export declare namespace auth { + /** + * Type alias to {@link firebase-admin.auth#ActionCodeSettings}. + */ + type ActionCodeSettings = TActionCodeSettings; + /** + * Type alias to {@link firebase-admin.auth#Auth}. + */ + type Auth = TAuth; + /** + * Type alias to {@link firebase-admin.auth#AuthFactorType}. + */ + type AuthFactorType = TAuthFactorType; + /** + * Type alias to {@link firebase-admin.auth#AuthProviderConfig}. + */ + type AuthProviderConfig = TAuthProviderConfig; + /** + * Type alias to {@link firebase-admin.auth#AuthProviderConfigFilter}. + */ + type AuthProviderConfigFilter = TAuthProviderConfigFilter; + /** + * Type alias to {@link firebase-admin.auth#BaseAuth}. + */ + type BaseAuth = TBaseAuth; + /** + * Type alias to {@link firebase-admin.auth#CreateMultiFactorInfoRequest}. + */ + type CreateMultiFactorInfoRequest = TCreateMultiFactorInfoRequest; + /** + * Type alias to {@link firebase-admin.auth#CreatePhoneMultiFactorInfoRequest}. + */ + type CreatePhoneMultiFactorInfoRequest = TCreatePhoneMultiFactorInfoRequest; + /** + * Type alias to {@link firebase-admin.auth#CreateRequest}. + */ + type CreateRequest = TCreateRequest; + /** + * Type alias to {@link firebase-admin.auth#CreateTenantRequest}. + */ + type CreateTenantRequest = TCreateTenantRequest; + /** + * Type alias to {@link firebase-admin.auth#DecodedIdToken}. + */ + type DecodedIdToken = TDecodedIdToken; + /** @alpha */ + type DecodedAuthBlockingToken = TDecodedAuthBlockingToken; + /** + * Type alias to {@link firebase-admin.auth#DeleteUsersResult}. + */ + type DeleteUsersResult = TDeleteUsersResult; + /** + * Type alias to {@link firebase-admin.auth#EmailIdentifier}. + */ + type EmailIdentifier = TEmailIdentifier; + /** + * Type alias to {@link firebase-admin.auth#EmailSignInProviderConfig}. + */ + type EmailSignInProviderConfig = TEmailSignInProviderConfig; + /** + * Type alias to {@link firebase-admin.auth#GetUsersResult}. + */ + type GetUsersResult = TGetUsersResult; + /** + * Type alias to {@link firebase-admin.auth#HashAlgorithmType}. + */ + type HashAlgorithmType = THashAlgorithmType; + /** + * Type alias to {@link firebase-admin.auth#ListProviderConfigResults}. + */ + type ListProviderConfigResults = TListProviderConfigResults; + /** + * Type alias to {@link firebase-admin.auth#ListTenantsResult}. + */ + type ListTenantsResult = TListTenantsResult; + /** + * Type alias to {@link firebase-admin.auth#ListUsersResult}. + */ + type ListUsersResult = TListUsersResult; + /** + * Type alias to {@link firebase-admin.auth#MultiFactorCreateSettings}. + */ + type MultiFactorCreateSettings = TMultiFactorCreateSettings; + /** + * Type alias to {@link firebase-admin.auth#MultiFactorConfig}. + */ + type MultiFactorConfig = TMultiFactorConfig; + /** + * Type alias to {@link firebase-admin.auth#MultiFactorConfigState}. + */ + type MultiFactorConfigState = TMultiFactorConfigState; + /** + * Type alias to {@link firebase-admin.auth#MultiFactorInfo}. + */ + type MultiFactorInfo = TMultiFactorInfo; + /** + * Type alias to {@link firebase-admin.auth#MultiFactorUpdateSettings}. + */ + type MultiFactorUpdateSettings = TMultiFactorUpdateSettings; + /** + * Type alias to {@link firebase-admin.auth#MultiFactorSettings}. + */ + type MultiFactorSettings = TMultiFactorSettings; + /** + * Type alias to {@link firebase-admin.auth#OIDCAuthProviderConfig}. + */ + type OIDCAuthProviderConfig = TOIDCAuthProviderConfig; + /** + * Type alias to {@link firebase-admin.auth#OIDCUpdateAuthProviderRequest}. + */ + type OIDCUpdateAuthProviderRequest = TOIDCUpdateAuthProviderRequest; + /** + * Type alias to {@link firebase-admin.auth#PhoneIdentifier}. + */ + type PhoneIdentifier = TPhoneIdentifier; + /** + * Type alias to {@link firebase-admin.auth#PhoneMultiFactorInfo}. + */ + type PhoneMultiFactorInfo = TPhoneMultiFactorInfo; + /** + * Type alias to {@link firebase-admin.auth#ProviderIdentifier}. + */ + type ProviderIdentifier = TProviderIdentifier; + /** + * Type alias to {@link firebase-admin.auth#SAMLAuthProviderConfig}. + */ + type SAMLAuthProviderConfig = TSAMLAuthProviderConfig; + /** + * Type alias to {@link firebase-admin.auth#SAMLUpdateAuthProviderRequest}. + */ + type SAMLUpdateAuthProviderRequest = TSAMLUpdateAuthProviderRequest; + /** + * Type alias to {@link firebase-admin.auth#SessionCookieOptions}. + */ + type SessionCookieOptions = TSessionCookieOptions; + /** + * Type alias to {@link firebase-admin.auth#Tenant}. + */ + type Tenant = TTenant; + /** + * Type alias to {@link firebase-admin.auth#TenantAwareAuth}. + */ + type TenantAwareAuth = TTenantAwareAuth; + /** + * Type alias to {@link firebase-admin.auth#TenantManager}. + */ + type TenantManager = TTenantManager; + /** + * Type alias to {@link firebase-admin.auth#UidIdentifier}. + */ + type UidIdentifier = TUidIdentifier; + /** + * Type alias to {@link firebase-admin.auth#UpdateAuthProviderRequest}. + */ + type UpdateAuthProviderRequest = TUpdateAuthProviderRequest; + /** + * Type alias to {@link firebase-admin.auth#UpdateMultiFactorInfoRequest}. + */ + type UpdateMultiFactorInfoRequest = TUpdateMultiFactorInfoRequest; + /** + * Type alias to {@link firebase-admin.auth#UpdatePhoneMultiFactorInfoRequest}. + */ + type UpdatePhoneMultiFactorInfoRequest = TUpdatePhoneMultiFactorInfoRequest; + /** + * Type alias to {@link firebase-admin.auth#UpdateRequest}. + */ + type UpdateRequest = TUpdateRequest; + /** + * Type alias to {@link firebase-admin.auth#UpdateTenantRequest}. + */ + type UpdateTenantRequest = TUpdateTenantRequest; + /** + * Type alias to {@link firebase-admin.auth#UserIdentifier}. + */ + type UserIdentifier = TUserIdentifier; + /** + * Type alias to {@link firebase-admin.auth#UserImportOptions}. + */ + type UserImportOptions = TUserImportOptions; + /** + * Type alias to {@link firebase-admin.auth#UserImportRecord}. + */ + type UserImportRecord = TUserImportRecord; + /** + * Type alias to {@link firebase-admin.auth#UserImportResult}. + */ + type UserImportResult = TUserImportResult; + /** + * Type alias to {@link firebase-admin.auth#UserInfo}. + */ + type UserInfo = TUserInfo; + /** + * Type alias to {@link firebase-admin.auth#UserMetadata}. + */ + type UserMetadata = TUserMetadata; + /** + * Type alias to {@link firebase-admin.auth#UserMetadataRequest}. + */ + type UserMetadataRequest = TUserMetadataRequest; + /** + * Type alias to {@link firebase-admin.auth#UserProviderRequest}. + */ + type UserProviderRequest = TUserProviderRequest; + /** + * Type alias to {@link firebase-admin.auth#UserRecord}. + */ + type UserRecord = TUserRecord; +} diff --git a/node_modules/firebase-admin/lib/auth/auth-namespace.js b/node_modules/firebase-admin/lib/auth/auth-namespace.js new file mode 100644 index 0000000..a91b066 --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/auth-namespace.js @@ -0,0 +1,18 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/firebase-admin/lib/auth/auth.d.ts b/node_modules/firebase-admin/lib/auth/auth.d.ts new file mode 100644 index 0000000..d9b6fe7 --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/auth.d.ts @@ -0,0 +1,48 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app/index'; +import { TenantManager } from './tenant-manager'; +import { BaseAuth } from './base-auth'; +import { ProjectConfigManager } from './project-config-manager'; +/** + * Auth service bound to the provided app. + * An Auth instance can have multiple tenants. + */ +export declare class Auth extends BaseAuth { + private readonly tenantManager_; + private readonly projectConfigManager_; + private readonly app_; + /** + * Returns the app associated with this Auth instance. + * + * @returns The app associated with this Auth instance. + */ + get app(): App; + /** + * Returns the tenant manager instance associated with the current project. + * + * @returns The tenant manager instance associated with the current project. + */ + tenantManager(): TenantManager; + /** + * Returns the project config manager instance associated with the current project. + * + * @returns The project config manager instance associated with the current project. + */ + projectConfigManager(): ProjectConfigManager; +} diff --git a/node_modules/firebase-admin/lib/auth/auth.js b/node_modules/firebase-admin/lib/auth/auth.js new file mode 100644 index 0000000..44b2fd7 --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/auth.js @@ -0,0 +1,66 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Auth = void 0; +const auth_api_request_1 = require("./auth-api-request"); +const tenant_manager_1 = require("./tenant-manager"); +const base_auth_1 = require("./base-auth"); +const project_config_manager_1 = require("./project-config-manager"); +/** + * Auth service bound to the provided app. + * An Auth instance can have multiple tenants. + */ +class Auth extends base_auth_1.BaseAuth { + /** + * @param app - The app for this Auth service. + * @constructor + * @internal + */ + constructor(app) { + super(app, new auth_api_request_1.AuthRequestHandler(app)); + this.app_ = app; + this.tenantManager_ = new tenant_manager_1.TenantManager(app); + this.projectConfigManager_ = new project_config_manager_1.ProjectConfigManager(app); + } + /** + * Returns the app associated with this Auth instance. + * + * @returns The app associated with this Auth instance. + */ + get app() { + return this.app_; + } + /** + * Returns the tenant manager instance associated with the current project. + * + * @returns The tenant manager instance associated with the current project. + */ + tenantManager() { + return this.tenantManager_; + } + /** + * Returns the project config manager instance associated with the current project. + * + * @returns The project config manager instance associated with the current project. + */ + projectConfigManager() { + return this.projectConfigManager_; + } +} +exports.Auth = Auth; diff --git a/node_modules/firebase-admin/lib/auth/base-auth.d.ts b/node_modules/firebase-admin/lib/auth/base-auth.d.ts new file mode 100644 index 0000000..e86dd7a --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/base-auth.d.ts @@ -0,0 +1,640 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseArrayIndexError } from '../app'; +import { DecodedIdToken, DecodedAuthBlockingToken } from './token-verifier'; +import { AuthProviderConfig, AuthProviderConfigFilter, ListProviderConfigResults, UpdateAuthProviderRequest, CreateRequest, UpdateRequest } from './auth-config'; +import { UserRecord } from './user-record'; +import { UserIdentifier } from './identifier'; +import { UserImportOptions, UserImportRecord, UserImportResult } from './user-import-builder'; +import { ActionCodeSettings } from './action-code-settings-builder'; +/** Represents the result of the {@link BaseAuth.getUsers} API. */ +export interface GetUsersResult { + /** + * Set of user records, corresponding to the set of users that were + * requested. Only users that were found are listed here. The result set is + * unordered. + */ + users: UserRecord[]; + /** Set of identifiers that were requested, but not found. */ + notFound: UserIdentifier[]; +} +/** + * Interface representing the object returned from a + * {@link BaseAuth.listUsers} operation. Contains the list + * of users for the current batch and the next page token if available. + */ +export interface ListUsersResult { + /** + * The list of {@link UserRecord} objects for the + * current downloaded batch. + */ + users: UserRecord[]; + /** + * The next page token if available. This is needed for the next batch download. + */ + pageToken?: string; +} +/** + * Represents the result of the {@link BaseAuth.deleteUsers}. + * API. + */ +export interface DeleteUsersResult { + /** + * The number of user records that failed to be deleted (possibly zero). + */ + failureCount: number; + /** + * The number of users that were deleted successfully (possibly zero). + * Users that did not exist prior to calling `deleteUsers()` are + * considered to be successfully deleted. + */ + successCount: number; + /** + * A list of `FirebaseArrayIndexError` instances describing the errors that + * were encountered during the deletion. Length of this list is equal to + * the return value of {@link DeleteUsersResult.failureCount}. + */ + errors: FirebaseArrayIndexError[]; +} +/** + * Interface representing the session cookie options needed for the + * {@link BaseAuth.createSessionCookie} method. + */ +export interface SessionCookieOptions { + /** + * The session cookie custom expiration in milliseconds. The minimum allowed is + * 5 minutes and the maxium allowed is 2 weeks. + */ + expiresIn: number; +} +/** + * Common parent interface for both `Auth` and `TenantAwareAuth` APIs. + */ +export declare abstract class BaseAuth { + /** + * Creates a new Firebase custom token (JWT) that can be sent back to a client + * device to use to sign in with the client SDKs' `signInWithCustomToken()` + * methods. (Tenant-aware instances will also embed the tenant ID in the + * token.) + * + * See {@link https://firebase.google.com/docs/auth/admin/create-custom-tokens | Create Custom Tokens} + * for code samples and detailed documentation. + * + * @param uid - The `uid` to use as the custom token's subject. + * @param developerClaims - Optional additional claims to include + * in the custom token's payload. + * + * @returns A promise fulfilled with a custom token for the + * provided `uid` and payload. + */ + createCustomToken(uid: string, developerClaims?: object): Promise; + /** + * Verifies a Firebase ID token (JWT). If the token is valid, the promise is + * fulfilled with the token's decoded claims; otherwise, the promise is + * rejected. + * + * If `checkRevoked` is set to true, first verifies whether the corresponding + * user is disabled. If yes, an `auth/user-disabled` error is thrown. If no, + * verifies if the session corresponding to the ID token was revoked. If the + * corresponding user's session was invalidated, an `auth/id-token-revoked` + * error is thrown. If not specified the check is not applied. + * + * See {@link https://firebase.google.com/docs/auth/admin/verify-id-tokens | Verify ID Tokens} + * for code samples and detailed documentation. + * + * @param idToken - The ID token to verify. + * @param checkRevoked - Whether to check if the ID token was revoked. + * This requires an extra request to the Firebase Auth backend to check + * the `tokensValidAfterTime` time for the corresponding user. + * When not specified, this additional check is not applied. + * + * @returns A promise fulfilled with the + * token's decoded claims if the ID token is valid; otherwise, a rejected + * promise. + */ + verifyIdToken(idToken: string, checkRevoked?: boolean): Promise; + /** + * Gets the user data for the user corresponding to a given `uid`. + * + * See {@link https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data | Retrieve user data} + * for code samples and detailed documentation. + * + * @param uid - The `uid` corresponding to the user whose data to fetch. + * + * @returns A promise fulfilled with the user + * data corresponding to the provided `uid`. + */ + getUser(uid: string): Promise; + /** + * Gets the user data for the user corresponding to a given email. + * + * See {@link https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data | Retrieve user data} + * for code samples and detailed documentation. + * + * @param email - The email corresponding to the user whose data to + * fetch. + * + * @returns A promise fulfilled with the user + * data corresponding to the provided email. + */ + getUserByEmail(email: string): Promise; + /** + * Gets the user data for the user corresponding to a given phone number. The + * phone number has to conform to the E.164 specification. + * + * See {@link https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data | Retrieve user data} + * for code samples and detailed documentation. + * + * @param phoneNumber - The phone number corresponding to the user whose + * data to fetch. + * + * @returns A promise fulfilled with the user + * data corresponding to the provided phone number. + */ + getUserByPhoneNumber(phoneNumber: string): Promise; + /** + * Gets the user data for the user corresponding to a given provider id. + * + * See {@link https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data | Retrieve user data} + * for code samples and detailed documentation. + * + * @param providerId - The provider ID, for example, "google.com" for the + * Google provider. + * @param uid - The user identifier for the given provider. + * + * @returns A promise fulfilled with the user data corresponding to the + * given provider id. + */ + getUserByProviderUid(providerId: string, uid: string): Promise; + /** + * Gets the user data corresponding to the specified identifiers. + * + * There are no ordering guarantees; in particular, the nth entry in the result list is not + * guaranteed to correspond to the nth entry in the input parameters list. + * + * Only a maximum of 100 identifiers may be supplied. If more than 100 identifiers are supplied, + * this method throws a FirebaseAuthError. + * + * @param identifiers - The identifiers used to indicate which user records should be returned. + * Must not have more than 100 entries. + * @returns A promise that resolves to the corresponding user records. + * @throws FirebaseAuthError If any of the identifiers are invalid or if more than 100 + * identifiers are specified. + */ + getUsers(identifiers: UserIdentifier[]): Promise; + /** + * Retrieves a list of users (single batch only) with a size of `maxResults` + * starting from the offset as specified by `pageToken`. This is used to + * retrieve all the users of a specified project in batches. + * + * See {@link https://firebase.google.com/docs/auth/admin/manage-users#list_all_users | List all users} + * for code samples and detailed documentation. + * + * @param maxResults - The page size, 1000 if undefined. This is also + * the maximum allowed limit. + * @param pageToken - The next page token. If not specified, returns + * users starting without any offset. + * @returns A promise that resolves with + * the current batch of downloaded users and the next page token. + */ + listUsers(maxResults?: number, pageToken?: string): Promise; + /** + * Creates a new user. + * + * See {@link https://firebase.google.com/docs/auth/admin/manage-users#create_a_user | Create a user} + * for code samples and detailed documentation. + * + * @param properties - The properties to set on the + * new user record to be created. + * + * @returns A promise fulfilled with the user + * data corresponding to the newly created user. + */ + createUser(properties: CreateRequest): Promise; + /** + * Deletes an existing user. + * + * See {@link https://firebase.google.com/docs/auth/admin/manage-users#delete_a_user | Delete a user} + * for code samples and detailed documentation. + * + * @param uid - The `uid` corresponding to the user to delete. + * + * @returns An empty promise fulfilled once the user has been + * deleted. + */ + deleteUser(uid: string): Promise; + /** + * Deletes the users specified by the given uids. + * + * Deleting a non-existing user won't generate an error (i.e. this method + * is idempotent.) Non-existing users are considered to be successfully + * deleted, and are therefore counted in the + * `DeleteUsersResult.successCount` value. + * + * Only a maximum of 1000 identifiers may be supplied. If more than 1000 + * identifiers are supplied, this method throws a FirebaseAuthError. + * + * This API is currently rate limited at the server to 1 QPS. If you exceed + * this, you may get a quota exceeded error. Therefore, if you want to + * delete more than 1000 users, you may need to add a delay to ensure you + * don't go over this limit. + * + * @param uids - The `uids` corresponding to the users to delete. + * + * @returns A Promise that resolves to the total number of successful/failed + * deletions, as well as the array of errors that corresponds to the + * failed deletions. + */ + deleteUsers(uids: string[]): Promise; + /** + * Updates an existing user. + * + * See {@link https://firebase.google.com/docs/auth/admin/manage-users#update_a_user | Update a user} + * for code samples and detailed documentation. + * + * @param uid - The `uid` corresponding to the user to update. + * @param properties - The properties to update on + * the provided user. + * + * @returns A promise fulfilled with the + * updated user data. + */ + updateUser(uid: string, properties: UpdateRequest): Promise; + /** + * Sets additional developer claims on an existing user identified by the + * provided `uid`, typically used to define user roles and levels of + * access. These claims should propagate to all devices where the user is + * already signed in (after token expiration or when token refresh is forced) + * and the next time the user signs in. If a reserved OIDC claim name + * is used (sub, iat, iss, etc), an error is thrown. They are set on the + * authenticated user's ID token JWT. + * + * See {@link https://firebase.google.com/docs/auth/admin/custom-claims | + * Defining user roles and access levels} + * for code samples and detailed documentation. + * + * @param uid - The `uid` of the user to edit. + * @param customUserClaims - The developer claims to set. If null is + * passed, existing custom claims are deleted. Passing a custom claims payload + * larger than 1000 bytes will throw an error. Custom claims are added to the + * user's ID token which is transmitted on every authenticated request. + * For profile non-access related user attributes, use database or other + * separate storage systems. + * @returns A promise that resolves when the operation completes + * successfully. + */ + setCustomUserClaims(uid: string, customUserClaims: object | null): Promise; + /** + * Revokes all refresh tokens for an existing user. + * + * This API will update the user's {@link UserRecord.tokensValidAfterTime} to + * the current UTC. It is important that the server on which this is called has + * its clock set correctly and synchronized. + * + * While this will revoke all sessions for a specified user and disable any + * new ID tokens for existing sessions from getting minted, existing ID tokens + * may remain active until their natural expiration (one hour). To verify that + * ID tokens are revoked, use {@link BaseAuth.verifyIdToken} + * where `checkRevoked` is set to true. + * + * @param uid - The `uid` corresponding to the user whose refresh tokens + * are to be revoked. + * + * @returns An empty promise fulfilled once the user's refresh + * tokens have been revoked. + */ + revokeRefreshTokens(uid: string): Promise; + /** + * Imports the provided list of users into Firebase Auth. + * A maximum of 1000 users are allowed to be imported one at a time. + * When importing users with passwords, + * {@link UserImportOptions} are required to be + * specified. + * This operation is optimized for bulk imports and will ignore checks on `uid`, + * `email` and other identifier uniqueness which could result in duplications. + * + * @param users - The list of user records to import to Firebase Auth. + * @param options - The user import options, required when the users provided include + * password credentials. + * @returns A promise that resolves when + * the operation completes with the result of the import. This includes the + * number of successful imports, the number of failed imports and their + * corresponding errors. + */ + importUsers(users: UserImportRecord[], options?: UserImportOptions): Promise; + /** + * Creates a new Firebase session cookie with the specified options. The created + * JWT string can be set as a server-side session cookie with a custom cookie + * policy, and be used for session management. The session cookie JWT will have + * the same payload claims as the provided ID token. + * + * See {@link https://firebase.google.com/docs/auth/admin/manage-cookies | Manage Session Cookies} + * for code samples and detailed documentation. + * + * @param idToken - The Firebase ID token to exchange for a session + * cookie. + * @param sessionCookieOptions - The session + * cookie options which includes custom session duration. + * + * @returns A promise that resolves on success with the + * created session cookie. + */ + createSessionCookie(idToken: string, sessionCookieOptions: SessionCookieOptions): Promise; + /** + * Verifies a Firebase session cookie. Returns a Promise with the cookie claims. + * Rejects the promise if the cookie could not be verified. + * + * If `checkRevoked` is set to true, first verifies whether the corresponding + * user is disabled: If yes, an `auth/user-disabled` error is thrown. If no, + * verifies if the session corresponding to the session cookie was revoked. + * If the corresponding user's session was invalidated, an + * `auth/session-cookie-revoked` error is thrown. If not specified the check + * is not performed. + * + * See {@link https://firebase.google.com/docs/auth/admin/manage-cookies#verify_session_cookie_and_check_permissions | + * Verify Session Cookies} + * for code samples and detailed documentation + * + * @param sessionCookie - The session cookie to verify. + * @param checkForRevocation - Whether to check if the session cookie was + * revoked. This requires an extra request to the Firebase Auth backend to + * check the `tokensValidAfterTime` time for the corresponding user. + * When not specified, this additional check is not performed. + * + * @returns A promise fulfilled with the + * session cookie's decoded claims if the session cookie is valid; otherwise, + * a rejected promise. + */ + verifySessionCookie(sessionCookie: string, checkRevoked?: boolean): Promise; + /** + * Generates the out of band email action link to reset a user's password. + * The link is generated for the user with the specified email address. The + * optional {@link ActionCodeSettings} object + * defines whether the link is to be handled by a mobile app or browser and the + * additional state information to be passed in the deep link, etc. + * + * @example + * ```javascript + * var actionCodeSettings = { + * url: 'https://www.example.com/?email=user@example.com', + * iOS: { + * bundleId: 'com.example.ios' + * }, + * android: { + * packageName: 'com.example.android', + * installApp: true, + * minimumVersion: '12' + * }, + * handleCodeInApp: true, + * linkDomain: 'project-id.firebaseapp.com' + * }; + * admin.auth() + * .generatePasswordResetLink('user@example.com', actionCodeSettings) + * .then(function(link) { + * // The link was successfully generated. + * }) + * .catch(function(error) { + * // Some error occurred, you can inspect the code: error.code + * }); + * ``` + * + * @param email - The email address of the user whose password is to be + * reset. + * @param actionCodeSettings - The action + * code settings. If specified, the state/continue URL is set as the + * "continueUrl" parameter in the password reset link. The default password + * reset landing page will use this to display a link to go back to the app + * if it is installed. + * If the actionCodeSettings is not specified, no URL is appended to the + * action URL. + * The state URL provided must belong to a domain that is whitelisted by the + * developer in the console. Otherwise an error is thrown. + * Mobile app redirects are only applicable if the developer configures + * and accepts the Firebase Dynamic Links terms of service. + * The Android package name and iOS bundle ID are respected only if they + * are configured in the same Firebase Auth project. + * @returns A promise that resolves with the generated link. + */ + generatePasswordResetLink(email: string, actionCodeSettings?: ActionCodeSettings): Promise; + /** + * Generates the out of band email action link to verify the user's ownership + * of the specified email. The {@link ActionCodeSettings} object provided + * as an argument to this method defines whether the link is to be handled by a + * mobile app or browser along with additional state information to be passed in + * the deep link, etc. + * + * @example + * ```javascript + * var actionCodeSettings = { + * url: 'https://www.example.com/cart?email=user@example.com&cartId=123', + * iOS: { + * bundleId: 'com.example.ios' + * }, + * android: { + * packageName: 'com.example.android', + * installApp: true, + * minimumVersion: '12' + * }, + * handleCodeInApp: true, + * linkDomain: 'project-id.firebaseapp.com' + * }; + * admin.auth() + * .generateEmailVerificationLink('user@example.com', actionCodeSettings) + * .then(function(link) { + * // The link was successfully generated. + * }) + * .catch(function(error) { + * // Some error occurred, you can inspect the code: error.code + * }); + * ``` + * + * @param email - The email account to verify. + * @param actionCodeSettings - The action + * code settings. If specified, the state/continue URL is set as the + * "continueUrl" parameter in the email verification link. The default email + * verification landing page will use this to display a link to go back to + * the app if it is installed. + * If the actionCodeSettings is not specified, no URL is appended to the + * action URL. + * The state URL provided must belong to a domain that is whitelisted by the + * developer in the console. Otherwise an error is thrown. + * Mobile app redirects are only applicable if the developer configures + * and accepts the Firebase Dynamic Links terms of service. + * The Android package name and iOS bundle ID are respected only if they + * are configured in the same Firebase Auth project. + * @returns A promise that resolves with the generated link. + */ + generateEmailVerificationLink(email: string, actionCodeSettings?: ActionCodeSettings): Promise; + /** + * Generates an out-of-band email action link to verify the user's ownership + * of the specified email. The {@link ActionCodeSettings} object provided + * as an argument to this method defines whether the link is to be handled by a + * mobile app or browser along with additional state information to be passed in + * the deep link, etc. + * + * @param email - The current email account. + * @param newEmail - The email address the account is being updated to. + * @param actionCodeSettings - The action + * code settings. If specified, the state/continue URL is set as the + * "continueUrl" parameter in the email verification link. The default email + * verification landing page will use this to display a link to go back to + * the app if it is installed. + * If the actionCodeSettings is not specified, no URL is appended to the + * action URL. + * The state URL provided must belong to a domain that is authorized + * in the console, or an error will be thrown. + * Mobile app redirects are only applicable if the developer configures + * and accepts the Firebase Dynamic Links terms of service. + * The Android package name and iOS bundle ID are respected only if they + * are configured in the same Firebase Auth project. + * @returns A promise that resolves with the generated link. + */ + generateVerifyAndChangeEmailLink(email: string, newEmail: string, actionCodeSettings?: ActionCodeSettings): Promise; + /** + * Generates the out of band email action link to verify the user's ownership + * of the specified email. The {@link ActionCodeSettings} object provided + * as an argument to this method defines whether the link is to be handled by a + * mobile app or browser along with additional state information to be passed in + * the deep link, etc. + * + * @example + * ```javascript + * var actionCodeSettings = { + * url: 'https://www.example.com/cart?email=user@example.com&cartId=123', + * iOS: { + * bundleId: 'com.example.ios' + * }, + * android: { + * packageName: 'com.example.android', + * installApp: true, + * minimumVersion: '12' + * }, + * handleCodeInApp: true, + * linkDomain: 'project-id.firebaseapp.com' + * }; + * admin.auth() + * .generateEmailVerificationLink('user@example.com', actionCodeSettings) + * .then(function(link) { + * // The link was successfully generated. + * }) + * .catch(function(error) { + * // Some error occurred, you can inspect the code: error.code + * }); + * ``` + * + * @param email - The email account to verify. + * @param actionCodeSettings - The action + * code settings. If specified, the state/continue URL is set as the + * "continueUrl" parameter in the email verification link. The default email + * verification landing page will use this to display a link to go back to + * the app if it is installed. + * If the actionCodeSettings is not specified, no URL is appended to the + * action URL. + * The state URL provided must belong to a domain that is whitelisted by the + * developer in the console. Otherwise an error is thrown. + * Mobile app redirects are only applicable if the developer configures + * and accepts the Firebase Dynamic Links terms of service. + * The Android package name and iOS bundle ID are respected only if they + * are configured in the same Firebase Auth project. + * @returns A promise that resolves with the generated link. + */ + generateSignInWithEmailLink(email: string, actionCodeSettings: ActionCodeSettings): Promise; + /** + * Returns the list of existing provider configurations matching the filter + * provided. At most, 100 provider configs can be listed at a time. + * + * SAML and OIDC provider support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. + * + * @param options - The provider config filter to apply. + * @returns A promise that resolves with the list of provider configs meeting the + * filter requirements. + */ + listProviderConfigs(options: AuthProviderConfigFilter): Promise; + /** + * Looks up an Auth provider configuration by the provided ID. + * Returns a promise that resolves with the provider configuration + * corresponding to the provider ID specified. If the specified ID does not + * exist, an `auth/configuration-not-found` error is thrown. + * + * SAML and OIDC provider support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. + * + * @param providerId - The provider ID corresponding to the provider + * config to return. + * @returns A promise that resolves + * with the configuration corresponding to the provided ID. + */ + getProviderConfig(providerId: string): Promise; + /** + * Deletes the provider configuration corresponding to the provider ID passed. + * If the specified ID does not exist, an `auth/configuration-not-found` error + * is thrown. + * + * SAML and OIDC provider support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. + * + * @param providerId - The provider ID corresponding to the provider + * config to delete. + * @returns A promise that resolves on completion. + */ + deleteProviderConfig(providerId: string): Promise; + /** + * Returns a promise that resolves with the updated `AuthProviderConfig` + * corresponding to the provider ID specified. + * If the specified ID does not exist, an `auth/configuration-not-found` error + * is thrown. + * + * SAML and OIDC provider support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. + * + * @param providerId - The provider ID corresponding to the provider + * config to update. + * @param updatedConfig - The updated configuration. + * @returns A promise that resolves with the updated provider configuration. + */ + updateProviderConfig(providerId: string, updatedConfig: UpdateAuthProviderRequest): Promise; + /** + * Returns a promise that resolves with the newly created `AuthProviderConfig` + * when the new provider configuration is created. + * + * SAML and OIDC provider support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. + * + * @param config - The provider configuration to create. + * @returns A promise that resolves with the created provider configuration. + */ + createProviderConfig(config: AuthProviderConfig): Promise; + /** @alpha */ + _verifyAuthBlockingToken(token: string, audience?: string): Promise; + /** + * Verifies the decoded Firebase issued JWT is not revoked or disabled. Returns a promise that + * resolves with the decoded claims on success. Rejects the promise with revocation error if revoked + * or user disabled. + * + * @param decodedIdToken - The JWT's decoded claims. + * @param revocationErrorInfo - The revocation error info to throw on revocation + * detection. + * @returns A promise that will be fulfilled after a successful verification. + */ + private verifyDecodedJWTNotRevokedOrDisabled; +} diff --git a/node_modules/firebase-admin/lib/auth/base-auth.js b/node_modules/firebase-admin/lib/auth/base-auth.js new file mode 100644 index 0000000..9626c41 --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/base-auth.js @@ -0,0 +1,981 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BaseAuth = void 0; +exports.createFirebaseTokenGenerator = createFirebaseTokenGenerator; +const error_1 = require("../utils/error"); +const deep_copy_1 = require("../utils/deep-copy"); +const validator = require("../utils/validator"); +const auth_api_request_1 = require("./auth-api-request"); +const token_generator_1 = require("./token-generator"); +const token_verifier_1 = require("./token-verifier"); +const auth_config_1 = require("./auth-config"); +const user_record_1 = require("./user-record"); +const identifier_1 = require("./identifier"); +const crypto_signer_1 = require("../utils/crypto-signer"); +/** + * @internal + */ +function createFirebaseTokenGenerator(app, tenantId) { + try { + const signer = (0, auth_api_request_1.useEmulator)() ? new token_generator_1.EmulatedSigner() : (0, crypto_signer_1.cryptoSignerFromApp)(app); + return new token_generator_1.FirebaseTokenGenerator(signer, tenantId); + } + catch (err) { + throw (0, token_generator_1.handleCryptoSignerError)(err); + } +} +/** + * Common parent interface for both `Auth` and `TenantAwareAuth` APIs. + */ +class BaseAuth { + /** + * The BaseAuth class constructor. + * + * @param app - The FirebaseApp to associate with this Auth instance. + * @param authRequestHandler - The RPC request handler for this instance. + * @param tokenGenerator - Optional token generator. If not specified, a + * (non-tenant-aware) instance will be created. Use this paramter to + * specify a tenant-aware tokenGenerator. + * @constructor + * @internal + */ + constructor(app, + /** @internal */ authRequestHandler, tokenGenerator) { + this.authRequestHandler = authRequestHandler; + if (tokenGenerator) { + this.tokenGenerator = tokenGenerator; + } + else { + this.tokenGenerator = createFirebaseTokenGenerator(app); + } + this.sessionCookieVerifier = (0, token_verifier_1.createSessionCookieVerifier)(app); + this.idTokenVerifier = (0, token_verifier_1.createIdTokenVerifier)(app); + this.authBlockingTokenVerifier = (0, token_verifier_1.createAuthBlockingTokenVerifier)(app); + } + /** + * Creates a new Firebase custom token (JWT) that can be sent back to a client + * device to use to sign in with the client SDKs' `signInWithCustomToken()` + * methods. (Tenant-aware instances will also embed the tenant ID in the + * token.) + * + * See {@link https://firebase.google.com/docs/auth/admin/create-custom-tokens | Create Custom Tokens} + * for code samples and detailed documentation. + * + * @param uid - The `uid` to use as the custom token's subject. + * @param developerClaims - Optional additional claims to include + * in the custom token's payload. + * + * @returns A promise fulfilled with a custom token for the + * provided `uid` and payload. + */ + createCustomToken(uid, developerClaims) { + return this.tokenGenerator.createCustomToken(uid, developerClaims); + } + /** + * Verifies a Firebase ID token (JWT). If the token is valid, the promise is + * fulfilled with the token's decoded claims; otherwise, the promise is + * rejected. + * + * If `checkRevoked` is set to true, first verifies whether the corresponding + * user is disabled. If yes, an `auth/user-disabled` error is thrown. If no, + * verifies if the session corresponding to the ID token was revoked. If the + * corresponding user's session was invalidated, an `auth/id-token-revoked` + * error is thrown. If not specified the check is not applied. + * + * See {@link https://firebase.google.com/docs/auth/admin/verify-id-tokens | Verify ID Tokens} + * for code samples and detailed documentation. + * + * @param idToken - The ID token to verify. + * @param checkRevoked - Whether to check if the ID token was revoked. + * This requires an extra request to the Firebase Auth backend to check + * the `tokensValidAfterTime` time for the corresponding user. + * When not specified, this additional check is not applied. + * + * @returns A promise fulfilled with the + * token's decoded claims if the ID token is valid; otherwise, a rejected + * promise. + */ + verifyIdToken(idToken, checkRevoked = false) { + const isEmulator = (0, auth_api_request_1.useEmulator)(); + return this.idTokenVerifier.verifyJWT(idToken, isEmulator) + .then((decodedIdToken) => { + // Whether to check if the token was revoked. + if (checkRevoked || isEmulator) { + return this.verifyDecodedJWTNotRevokedOrDisabled(decodedIdToken, error_1.AuthClientErrorCode.ID_TOKEN_REVOKED); + } + return decodedIdToken; + }); + } + /** + * Gets the user data for the user corresponding to a given `uid`. + * + * See {@link https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data | Retrieve user data} + * for code samples and detailed documentation. + * + * @param uid - The `uid` corresponding to the user whose data to fetch. + * + * @returns A promise fulfilled with the user + * data corresponding to the provided `uid`. + */ + getUser(uid) { + return this.authRequestHandler.getAccountInfoByUid(uid) + .then((response) => { + // Returns the user record populated with server response. + return new user_record_1.UserRecord(response.users[0]); + }); + } + /** + * Gets the user data for the user corresponding to a given email. + * + * See {@link https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data | Retrieve user data} + * for code samples and detailed documentation. + * + * @param email - The email corresponding to the user whose data to + * fetch. + * + * @returns A promise fulfilled with the user + * data corresponding to the provided email. + */ + getUserByEmail(email) { + return this.authRequestHandler.getAccountInfoByEmail(email) + .then((response) => { + // Returns the user record populated with server response. + return new user_record_1.UserRecord(response.users[0]); + }); + } + /** + * Gets the user data for the user corresponding to a given phone number. The + * phone number has to conform to the E.164 specification. + * + * See {@link https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data | Retrieve user data} + * for code samples and detailed documentation. + * + * @param phoneNumber - The phone number corresponding to the user whose + * data to fetch. + * + * @returns A promise fulfilled with the user + * data corresponding to the provided phone number. + */ + getUserByPhoneNumber(phoneNumber) { + return this.authRequestHandler.getAccountInfoByPhoneNumber(phoneNumber) + .then((response) => { + // Returns the user record populated with server response. + return new user_record_1.UserRecord(response.users[0]); + }); + } + /** + * Gets the user data for the user corresponding to a given provider id. + * + * See {@link https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data | Retrieve user data} + * for code samples and detailed documentation. + * + * @param providerId - The provider ID, for example, "google.com" for the + * Google provider. + * @param uid - The user identifier for the given provider. + * + * @returns A promise fulfilled with the user data corresponding to the + * given provider id. + */ + getUserByProviderUid(providerId, uid) { + // Although we don't really advertise it, we want to also handle + // non-federated idps with this call. So if we detect one of them, we'll + // reroute this request appropriately. + if (providerId === 'phone') { + return this.getUserByPhoneNumber(uid); + } + else if (providerId === 'email') { + return this.getUserByEmail(uid); + } + return this.authRequestHandler.getAccountInfoByFederatedUid(providerId, uid) + .then((response) => { + // Returns the user record populated with server response. + return new user_record_1.UserRecord(response.users[0]); + }); + } + /** + * Gets the user data corresponding to the specified identifiers. + * + * There are no ordering guarantees; in particular, the nth entry in the result list is not + * guaranteed to correspond to the nth entry in the input parameters list. + * + * Only a maximum of 100 identifiers may be supplied. If more than 100 identifiers are supplied, + * this method throws a FirebaseAuthError. + * + * @param identifiers - The identifiers used to indicate which user records should be returned. + * Must not have more than 100 entries. + * @returns A promise that resolves to the corresponding user records. + * @throws FirebaseAuthError If any of the identifiers are invalid or if more than 100 + * identifiers are specified. + */ + getUsers(identifiers) { + if (!validator.isArray(identifiers)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '`identifiers` parameter must be an array'); + } + return this.authRequestHandler + .getAccountInfoByIdentifiers(identifiers) + .then((response) => { + /** + * Checks if the specified identifier is within the list of + * UserRecords. + */ + const isUserFound = ((id, userRecords) => { + return !!userRecords.find((userRecord) => { + if ((0, identifier_1.isUidIdentifier)(id)) { + return id.uid === userRecord.uid; + } + else if ((0, identifier_1.isEmailIdentifier)(id)) { + return id.email === userRecord.email; + } + else if ((0, identifier_1.isPhoneIdentifier)(id)) { + return id.phoneNumber === userRecord.phoneNumber; + } + else if ((0, identifier_1.isProviderIdentifier)(id)) { + const matchingUserInfo = userRecord.providerData.find((userInfo) => { + return id.providerId === userInfo.providerId; + }); + return !!matchingUserInfo && id.providerUid === matchingUserInfo.uid; + } + else { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'Unhandled identifier type'); + } + }); + }); + const users = response.users ? response.users.map((user) => new user_record_1.UserRecord(user)) : []; + const notFound = identifiers.filter((id) => !isUserFound(id, users)); + return { users, notFound }; + }); + } + /** + * Retrieves a list of users (single batch only) with a size of `maxResults` + * starting from the offset as specified by `pageToken`. This is used to + * retrieve all the users of a specified project in batches. + * + * See {@link https://firebase.google.com/docs/auth/admin/manage-users#list_all_users | List all users} + * for code samples and detailed documentation. + * + * @param maxResults - The page size, 1000 if undefined. This is also + * the maximum allowed limit. + * @param pageToken - The next page token. If not specified, returns + * users starting without any offset. + * @returns A promise that resolves with + * the current batch of downloaded users and the next page token. + */ + listUsers(maxResults, pageToken) { + return this.authRequestHandler.downloadAccount(maxResults, pageToken) + .then((response) => { + // List of users to return. + const users = []; + // Convert each user response to a UserRecord. + response.users.forEach((userResponse) => { + users.push(new user_record_1.UserRecord(userResponse)); + }); + // Return list of user records and the next page token if available. + const result = { + users, + pageToken: response.nextPageToken, + }; + // Delete result.pageToken if undefined. + if (typeof result.pageToken === 'undefined') { + delete result.pageToken; + } + return result; + }); + } + /** + * Creates a new user. + * + * See {@link https://firebase.google.com/docs/auth/admin/manage-users#create_a_user | Create a user} + * for code samples and detailed documentation. + * + * @param properties - The properties to set on the + * new user record to be created. + * + * @returns A promise fulfilled with the user + * data corresponding to the newly created user. + */ + createUser(properties) { + return this.authRequestHandler.createNewAccount(properties) + .then((uid) => { + // Return the corresponding user record. + return this.getUser(uid); + }) + .catch((error) => { + if (error.code === 'auth/user-not-found') { + // Something must have happened after creating the user and then retrieving it. + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'Unable to create the user record provided.'); + } + throw error; + }); + } + /** + * Deletes an existing user. + * + * See {@link https://firebase.google.com/docs/auth/admin/manage-users#delete_a_user | Delete a user} + * for code samples and detailed documentation. + * + * @param uid - The `uid` corresponding to the user to delete. + * + * @returns An empty promise fulfilled once the user has been + * deleted. + */ + deleteUser(uid) { + return this.authRequestHandler.deleteAccount(uid) + .then(() => { + // Return nothing on success. + }); + } + /** + * Deletes the users specified by the given uids. + * + * Deleting a non-existing user won't generate an error (i.e. this method + * is idempotent.) Non-existing users are considered to be successfully + * deleted, and are therefore counted in the + * `DeleteUsersResult.successCount` value. + * + * Only a maximum of 1000 identifiers may be supplied. If more than 1000 + * identifiers are supplied, this method throws a FirebaseAuthError. + * + * This API is currently rate limited at the server to 1 QPS. If you exceed + * this, you may get a quota exceeded error. Therefore, if you want to + * delete more than 1000 users, you may need to add a delay to ensure you + * don't go over this limit. + * + * @param uids - The `uids` corresponding to the users to delete. + * + * @returns A Promise that resolves to the total number of successful/failed + * deletions, as well as the array of errors that corresponds to the + * failed deletions. + */ + deleteUsers(uids) { + if (!validator.isArray(uids)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '`uids` parameter must be an array'); + } + return this.authRequestHandler.deleteAccounts(uids, /*force=*/ true) + .then((batchDeleteAccountsResponse) => { + const result = { + failureCount: 0, + successCount: uids.length, + errors: [], + }; + if (!validator.isNonEmptyArray(batchDeleteAccountsResponse.errors)) { + return result; + } + result.failureCount = batchDeleteAccountsResponse.errors.length; + result.successCount = uids.length - batchDeleteAccountsResponse.errors.length; + result.errors = batchDeleteAccountsResponse.errors.map((batchDeleteErrorInfo) => { + if (batchDeleteErrorInfo.index === undefined) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'Corrupt BatchDeleteAccountsResponse detected'); + } + const errMsgToError = (msg) => { + // We unconditionally set force=true, so the 'NOT_DISABLED' error + // should not be possible. + const code = msg && msg.startsWith('NOT_DISABLED') ? + error_1.AuthClientErrorCode.USER_NOT_DISABLED : error_1.AuthClientErrorCode.INTERNAL_ERROR; + return new error_1.FirebaseAuthError(code, batchDeleteErrorInfo.message); + }; + return { + index: batchDeleteErrorInfo.index, + error: errMsgToError(batchDeleteErrorInfo.message), + }; + }); + return result; + }); + } + /** + * Updates an existing user. + * + * See {@link https://firebase.google.com/docs/auth/admin/manage-users#update_a_user | Update a user} + * for code samples and detailed documentation. + * + * @param uid - The `uid` corresponding to the user to update. + * @param properties - The properties to update on + * the provided user. + * + * @returns A promise fulfilled with the + * updated user data. + */ + updateUser(uid, properties) { + // Although we don't really advertise it, we want to also handle linking of + // non-federated idps with this call. So if we detect one of them, we'll + // adjust the properties parameter appropriately. This *does* imply that a + // conflict could arise, e.g. if the user provides a phoneNumber property, + // but also provides a providerToLink with a 'phone' provider id. In that + // case, we'll throw an error. + properties = (0, deep_copy_1.deepCopy)(properties); + if (properties?.providerToLink) { + if (properties.providerToLink.providerId === 'email') { + if (typeof properties.email !== 'undefined') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "Both UpdateRequest.email and UpdateRequest.providerToLink.providerId='email' were set. To " + + 'link to the email/password provider, only specify the UpdateRequest.email field.'); + } + properties.email = properties.providerToLink.uid; + delete properties.providerToLink; + } + else if (properties.providerToLink.providerId === 'phone') { + if (typeof properties.phoneNumber !== 'undefined') { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "Both UpdateRequest.phoneNumber and UpdateRequest.providerToLink.providerId='phone' were set. To " + + 'link to a phone provider, only specify the UpdateRequest.phoneNumber field.'); + } + properties.phoneNumber = properties.providerToLink.uid; + delete properties.providerToLink; + } + } + if (properties?.providersToUnlink) { + if (properties.providersToUnlink.indexOf('phone') !== -1) { + // If we've been told to unlink the phone provider both via setting + // phoneNumber to null *and* by setting providersToUnlink to include + // 'phone', then we'll reject that. Though it might also be reasonable + // to relax this restriction and just unlink it. + if (properties.phoneNumber === null) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "Both UpdateRequest.phoneNumber=null and UpdateRequest.providersToUnlink=['phone'] were set. To " + + 'unlink from a phone provider, only specify the UpdateRequest.phoneNumber=null field.'); + } + } + } + return this.authRequestHandler.updateExistingAccount(uid, properties) + .then((existingUid) => { + // Return the corresponding user record. + return this.getUser(existingUid); + }); + } + /** + * Sets additional developer claims on an existing user identified by the + * provided `uid`, typically used to define user roles and levels of + * access. These claims should propagate to all devices where the user is + * already signed in (after token expiration or when token refresh is forced) + * and the next time the user signs in. If a reserved OIDC claim name + * is used (sub, iat, iss, etc), an error is thrown. They are set on the + * authenticated user's ID token JWT. + * + * See {@link https://firebase.google.com/docs/auth/admin/custom-claims | + * Defining user roles and access levels} + * for code samples and detailed documentation. + * + * @param uid - The `uid` of the user to edit. + * @param customUserClaims - The developer claims to set. If null is + * passed, existing custom claims are deleted. Passing a custom claims payload + * larger than 1000 bytes will throw an error. Custom claims are added to the + * user's ID token which is transmitted on every authenticated request. + * For profile non-access related user attributes, use database or other + * separate storage systems. + * @returns A promise that resolves when the operation completes + * successfully. + */ + setCustomUserClaims(uid, customUserClaims) { + return this.authRequestHandler.setCustomUserClaims(uid, customUserClaims) + .then(() => { + // Return nothing on success. + }); + } + /** + * Revokes all refresh tokens for an existing user. + * + * This API will update the user's {@link UserRecord.tokensValidAfterTime} to + * the current UTC. It is important that the server on which this is called has + * its clock set correctly and synchronized. + * + * While this will revoke all sessions for a specified user and disable any + * new ID tokens for existing sessions from getting minted, existing ID tokens + * may remain active until their natural expiration (one hour). To verify that + * ID tokens are revoked, use {@link BaseAuth.verifyIdToken} + * where `checkRevoked` is set to true. + * + * @param uid - The `uid` corresponding to the user whose refresh tokens + * are to be revoked. + * + * @returns An empty promise fulfilled once the user's refresh + * tokens have been revoked. + */ + revokeRefreshTokens(uid) { + return this.authRequestHandler.revokeRefreshTokens(uid) + .then(() => { + // Return nothing on success. + }); + } + /** + * Imports the provided list of users into Firebase Auth. + * A maximum of 1000 users are allowed to be imported one at a time. + * When importing users with passwords, + * {@link UserImportOptions} are required to be + * specified. + * This operation is optimized for bulk imports and will ignore checks on `uid`, + * `email` and other identifier uniqueness which could result in duplications. + * + * @param users - The list of user records to import to Firebase Auth. + * @param options - The user import options, required when the users provided include + * password credentials. + * @returns A promise that resolves when + * the operation completes with the result of the import. This includes the + * number of successful imports, the number of failed imports and their + * corresponding errors. + */ + importUsers(users, options) { + return this.authRequestHandler.uploadAccount(users, options); + } + /** + * Creates a new Firebase session cookie with the specified options. The created + * JWT string can be set as a server-side session cookie with a custom cookie + * policy, and be used for session management. The session cookie JWT will have + * the same payload claims as the provided ID token. + * + * See {@link https://firebase.google.com/docs/auth/admin/manage-cookies | Manage Session Cookies} + * for code samples and detailed documentation. + * + * @param idToken - The Firebase ID token to exchange for a session + * cookie. + * @param sessionCookieOptions - The session + * cookie options which includes custom session duration. + * + * @returns A promise that resolves on success with the + * created session cookie. + */ + createSessionCookie(idToken, sessionCookieOptions) { + // Return rejected promise if expiresIn is not available. + if (!validator.isNonNullObject(sessionCookieOptions) || + !validator.isNumber(sessionCookieOptions.expiresIn)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_SESSION_COOKIE_DURATION)); + } + return this.authRequestHandler.createSessionCookie(idToken, sessionCookieOptions.expiresIn); + } + /** + * Verifies a Firebase session cookie. Returns a Promise with the cookie claims. + * Rejects the promise if the cookie could not be verified. + * + * If `checkRevoked` is set to true, first verifies whether the corresponding + * user is disabled: If yes, an `auth/user-disabled` error is thrown. If no, + * verifies if the session corresponding to the session cookie was revoked. + * If the corresponding user's session was invalidated, an + * `auth/session-cookie-revoked` error is thrown. If not specified the check + * is not performed. + * + * See {@link https://firebase.google.com/docs/auth/admin/manage-cookies#verify_session_cookie_and_check_permissions | + * Verify Session Cookies} + * for code samples and detailed documentation + * + * @param sessionCookie - The session cookie to verify. + * @param checkForRevocation - Whether to check if the session cookie was + * revoked. This requires an extra request to the Firebase Auth backend to + * check the `tokensValidAfterTime` time for the corresponding user. + * When not specified, this additional check is not performed. + * + * @returns A promise fulfilled with the + * session cookie's decoded claims if the session cookie is valid; otherwise, + * a rejected promise. + */ + verifySessionCookie(sessionCookie, checkRevoked = false) { + const isEmulator = (0, auth_api_request_1.useEmulator)(); + return this.sessionCookieVerifier.verifyJWT(sessionCookie, isEmulator) + .then((decodedIdToken) => { + // Whether to check if the token was revoked. + if (checkRevoked || isEmulator) { + return this.verifyDecodedJWTNotRevokedOrDisabled(decodedIdToken, error_1.AuthClientErrorCode.SESSION_COOKIE_REVOKED); + } + return decodedIdToken; + }); + } + /** + * Generates the out of band email action link to reset a user's password. + * The link is generated for the user with the specified email address. The + * optional {@link ActionCodeSettings} object + * defines whether the link is to be handled by a mobile app or browser and the + * additional state information to be passed in the deep link, etc. + * + * @example + * ```javascript + * var actionCodeSettings = { + * url: 'https://www.example.com/?email=user@example.com', + * iOS: { + * bundleId: 'com.example.ios' + * }, + * android: { + * packageName: 'com.example.android', + * installApp: true, + * minimumVersion: '12' + * }, + * handleCodeInApp: true, + * linkDomain: 'project-id.firebaseapp.com' + * }; + * admin.auth() + * .generatePasswordResetLink('user@example.com', actionCodeSettings) + * .then(function(link) { + * // The link was successfully generated. + * }) + * .catch(function(error) { + * // Some error occurred, you can inspect the code: error.code + * }); + * ``` + * + * @param email - The email address of the user whose password is to be + * reset. + * @param actionCodeSettings - The action + * code settings. If specified, the state/continue URL is set as the + * "continueUrl" parameter in the password reset link. The default password + * reset landing page will use this to display a link to go back to the app + * if it is installed. + * If the actionCodeSettings is not specified, no URL is appended to the + * action URL. + * The state URL provided must belong to a domain that is whitelisted by the + * developer in the console. Otherwise an error is thrown. + * Mobile app redirects are only applicable if the developer configures + * and accepts the Firebase Dynamic Links terms of service. + * The Android package name and iOS bundle ID are respected only if they + * are configured in the same Firebase Auth project. + * @returns A promise that resolves with the generated link. + */ + generatePasswordResetLink(email, actionCodeSettings) { + return this.authRequestHandler.getEmailActionLink('PASSWORD_RESET', email, actionCodeSettings); + } + /** + * Generates the out of band email action link to verify the user's ownership + * of the specified email. The {@link ActionCodeSettings} object provided + * as an argument to this method defines whether the link is to be handled by a + * mobile app or browser along with additional state information to be passed in + * the deep link, etc. + * + * @example + * ```javascript + * var actionCodeSettings = { + * url: 'https://www.example.com/cart?email=user@example.com&cartId=123', + * iOS: { + * bundleId: 'com.example.ios' + * }, + * android: { + * packageName: 'com.example.android', + * installApp: true, + * minimumVersion: '12' + * }, + * handleCodeInApp: true, + * linkDomain: 'project-id.firebaseapp.com' + * }; + * admin.auth() + * .generateEmailVerificationLink('user@example.com', actionCodeSettings) + * .then(function(link) { + * // The link was successfully generated. + * }) + * .catch(function(error) { + * // Some error occurred, you can inspect the code: error.code + * }); + * ``` + * + * @param email - The email account to verify. + * @param actionCodeSettings - The action + * code settings. If specified, the state/continue URL is set as the + * "continueUrl" parameter in the email verification link. The default email + * verification landing page will use this to display a link to go back to + * the app if it is installed. + * If the actionCodeSettings is not specified, no URL is appended to the + * action URL. + * The state URL provided must belong to a domain that is whitelisted by the + * developer in the console. Otherwise an error is thrown. + * Mobile app redirects are only applicable if the developer configures + * and accepts the Firebase Dynamic Links terms of service. + * The Android package name and iOS bundle ID are respected only if they + * are configured in the same Firebase Auth project. + * @returns A promise that resolves with the generated link. + */ + generateEmailVerificationLink(email, actionCodeSettings) { + return this.authRequestHandler.getEmailActionLink('VERIFY_EMAIL', email, actionCodeSettings); + } + /** + * Generates an out-of-band email action link to verify the user's ownership + * of the specified email. The {@link ActionCodeSettings} object provided + * as an argument to this method defines whether the link is to be handled by a + * mobile app or browser along with additional state information to be passed in + * the deep link, etc. + * + * @param email - The current email account. + * @param newEmail - The email address the account is being updated to. + * @param actionCodeSettings - The action + * code settings. If specified, the state/continue URL is set as the + * "continueUrl" parameter in the email verification link. The default email + * verification landing page will use this to display a link to go back to + * the app if it is installed. + * If the actionCodeSettings is not specified, no URL is appended to the + * action URL. + * The state URL provided must belong to a domain that is authorized + * in the console, or an error will be thrown. + * Mobile app redirects are only applicable if the developer configures + * and accepts the Firebase Dynamic Links terms of service. + * The Android package name and iOS bundle ID are respected only if they + * are configured in the same Firebase Auth project. + * @returns A promise that resolves with the generated link. + */ + generateVerifyAndChangeEmailLink(email, newEmail, actionCodeSettings) { + return this.authRequestHandler.getEmailActionLink('VERIFY_AND_CHANGE_EMAIL', email, actionCodeSettings, newEmail); + } + /** + * Generates the out of band email action link to verify the user's ownership + * of the specified email. The {@link ActionCodeSettings} object provided + * as an argument to this method defines whether the link is to be handled by a + * mobile app or browser along with additional state information to be passed in + * the deep link, etc. + * + * @example + * ```javascript + * var actionCodeSettings = { + * url: 'https://www.example.com/cart?email=user@example.com&cartId=123', + * iOS: { + * bundleId: 'com.example.ios' + * }, + * android: { + * packageName: 'com.example.android', + * installApp: true, + * minimumVersion: '12' + * }, + * handleCodeInApp: true, + * linkDomain: 'project-id.firebaseapp.com' + * }; + * admin.auth() + * .generateEmailVerificationLink('user@example.com', actionCodeSettings) + * .then(function(link) { + * // The link was successfully generated. + * }) + * .catch(function(error) { + * // Some error occurred, you can inspect the code: error.code + * }); + * ``` + * + * @param email - The email account to verify. + * @param actionCodeSettings - The action + * code settings. If specified, the state/continue URL is set as the + * "continueUrl" parameter in the email verification link. The default email + * verification landing page will use this to display a link to go back to + * the app if it is installed. + * If the actionCodeSettings is not specified, no URL is appended to the + * action URL. + * The state URL provided must belong to a domain that is whitelisted by the + * developer in the console. Otherwise an error is thrown. + * Mobile app redirects are only applicable if the developer configures + * and accepts the Firebase Dynamic Links terms of service. + * The Android package name and iOS bundle ID are respected only if they + * are configured in the same Firebase Auth project. + * @returns A promise that resolves with the generated link. + */ + generateSignInWithEmailLink(email, actionCodeSettings) { + return this.authRequestHandler.getEmailActionLink('EMAIL_SIGNIN', email, actionCodeSettings); + } + /** + * Returns the list of existing provider configurations matching the filter + * provided. At most, 100 provider configs can be listed at a time. + * + * SAML and OIDC provider support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. + * + * @param options - The provider config filter to apply. + * @returns A promise that resolves with the list of provider configs meeting the + * filter requirements. + */ + listProviderConfigs(options) { + const processResponse = (response, providerConfigs) => { + // Return list of provider configuration and the next page token if available. + const result = { + providerConfigs, + }; + // Delete result.pageToken if undefined. + if (Object.prototype.hasOwnProperty.call(response, 'nextPageToken')) { + result.pageToken = response.nextPageToken; + } + return result; + }; + if (options && options.type === 'oidc') { + return this.authRequestHandler.listOAuthIdpConfigs(options.maxResults, options.pageToken) + .then((response) => { + // List of provider configurations to return. + const providerConfigs = []; + // Convert each provider config response to a OIDCConfig. + response.oauthIdpConfigs.forEach((configResponse) => { + providerConfigs.push(new auth_config_1.OIDCConfig(configResponse)); + }); + // Return list of provider configuration and the next page token if available. + return processResponse(response, providerConfigs); + }); + } + else if (options && options.type === 'saml') { + return this.authRequestHandler.listInboundSamlConfigs(options.maxResults, options.pageToken) + .then((response) => { + // List of provider configurations to return. + const providerConfigs = []; + // Convert each provider config response to a SAMLConfig. + response.inboundSamlConfigs.forEach((configResponse) => { + providerConfigs.push(new auth_config_1.SAMLConfig(configResponse)); + }); + // Return list of provider configuration and the next page token if available. + return processResponse(response, providerConfigs); + }); + } + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"AuthProviderConfigFilter.type" must be either "saml" or "oidc"')); + } + /** + * Looks up an Auth provider configuration by the provided ID. + * Returns a promise that resolves with the provider configuration + * corresponding to the provider ID specified. If the specified ID does not + * exist, an `auth/configuration-not-found` error is thrown. + * + * SAML and OIDC provider support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. + * + * @param providerId - The provider ID corresponding to the provider + * config to return. + * @returns A promise that resolves + * with the configuration corresponding to the provided ID. + */ + getProviderConfig(providerId) { + if (auth_config_1.OIDCConfig.isProviderId(providerId)) { + return this.authRequestHandler.getOAuthIdpConfig(providerId) + .then((response) => { + return new auth_config_1.OIDCConfig(response); + }); + } + else if (auth_config_1.SAMLConfig.isProviderId(providerId)) { + return this.authRequestHandler.getInboundSamlConfig(providerId) + .then((response) => { + return new auth_config_1.SAMLConfig(response); + }); + } + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID)); + } + /** + * Deletes the provider configuration corresponding to the provider ID passed. + * If the specified ID does not exist, an `auth/configuration-not-found` error + * is thrown. + * + * SAML and OIDC provider support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. + * + * @param providerId - The provider ID corresponding to the provider + * config to delete. + * @returns A promise that resolves on completion. + */ + deleteProviderConfig(providerId) { + if (auth_config_1.OIDCConfig.isProviderId(providerId)) { + return this.authRequestHandler.deleteOAuthIdpConfig(providerId); + } + else if (auth_config_1.SAMLConfig.isProviderId(providerId)) { + return this.authRequestHandler.deleteInboundSamlConfig(providerId); + } + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID)); + } + /** + * Returns a promise that resolves with the updated `AuthProviderConfig` + * corresponding to the provider ID specified. + * If the specified ID does not exist, an `auth/configuration-not-found` error + * is thrown. + * + * SAML and OIDC provider support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. + * + * @param providerId - The provider ID corresponding to the provider + * config to update. + * @param updatedConfig - The updated configuration. + * @returns A promise that resolves with the updated provider configuration. + */ + updateProviderConfig(providerId, updatedConfig) { + if (!validator.isNonNullObject(updatedConfig)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, 'Request is missing "UpdateAuthProviderRequest" configuration.')); + } + if (auth_config_1.OIDCConfig.isProviderId(providerId)) { + return this.authRequestHandler.updateOAuthIdpConfig(providerId, updatedConfig) + .then((response) => { + return new auth_config_1.OIDCConfig(response); + }); + } + else if (auth_config_1.SAMLConfig.isProviderId(providerId)) { + return this.authRequestHandler.updateInboundSamlConfig(providerId, updatedConfig) + .then((response) => { + return new auth_config_1.SAMLConfig(response); + }); + } + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID)); + } + /** + * Returns a promise that resolves with the newly created `AuthProviderConfig` + * when the new provider configuration is created. + * + * SAML and OIDC provider support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. + * + * @param config - The provider configuration to create. + * @returns A promise that resolves with the created provider configuration. + */ + createProviderConfig(config) { + if (!validator.isNonNullObject(config)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, 'Request is missing "AuthProviderConfig" configuration.')); + } + if (auth_config_1.OIDCConfig.isProviderId(config.providerId)) { + return this.authRequestHandler.createOAuthIdpConfig(config) + .then((response) => { + return new auth_config_1.OIDCConfig(response); + }); + } + else if (auth_config_1.SAMLConfig.isProviderId(config.providerId)) { + return this.authRequestHandler.createInboundSamlConfig(config) + .then((response) => { + return new auth_config_1.SAMLConfig(response); + }); + } + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID)); + } + /** @alpha */ + // eslint-disable-next-line @typescript-eslint/naming-convention + _verifyAuthBlockingToken(token, audience) { + const isEmulator = (0, auth_api_request_1.useEmulator)(); + return this.authBlockingTokenVerifier._verifyAuthBlockingToken(token, isEmulator, audience) + .then((decodedAuthBlockingToken) => { + return decodedAuthBlockingToken; + }); + } + /** + * Verifies the decoded Firebase issued JWT is not revoked or disabled. Returns a promise that + * resolves with the decoded claims on success. Rejects the promise with revocation error if revoked + * or user disabled. + * + * @param decodedIdToken - The JWT's decoded claims. + * @param revocationErrorInfo - The revocation error info to throw on revocation + * detection. + * @returns A promise that will be fulfilled after a successful verification. + */ + verifyDecodedJWTNotRevokedOrDisabled(decodedIdToken, revocationErrorInfo) { + // Get tokens valid after time for the corresponding user. + return this.getUser(decodedIdToken.sub) + .then((user) => { + if (user.disabled) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.USER_DISABLED, 'The user record is disabled.'); + } + // If no tokens valid after time available, token is not revoked. + if (user.tokensValidAfterTime) { + // Get the ID token authentication time and convert to milliseconds UTC. + const authTimeUtc = decodedIdToken.auth_time * 1000; + // Get user tokens valid after time in milliseconds UTC. + const validSinceUtc = new Date(user.tokensValidAfterTime).getTime(); + // Check if authentication time is older than valid since time. + if (authTimeUtc < validSinceUtc) { + throw new error_1.FirebaseAuthError(revocationErrorInfo); + } + } + // All checks above passed. Return the decoded token. + return decodedIdToken; + }); + } +} +exports.BaseAuth = BaseAuth; diff --git a/node_modules/firebase-admin/lib/auth/identifier.d.ts b/node_modules/firebase-admin/lib/auth/identifier.d.ts new file mode 100644 index 0000000..59ee114 --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/identifier.d.ts @@ -0,0 +1,57 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Used for looking up an account by uid. + * + * See {@link BaseAuth.getUsers}. + */ +export interface UidIdentifier { + uid: string; +} +/** + * Used for looking up an account by email. + * + * See {@link BaseAuth.getUsers}. + */ +export interface EmailIdentifier { + email: string; +} +/** + * Used for looking up an account by phone number. + * + * See {@link BaseAuth.getUsers}. + */ +export interface PhoneIdentifier { + phoneNumber: string; +} +/** + * Used for looking up an account by federated provider. + * + * See {@link BaseAuth.getUsers}. + */ +export interface ProviderIdentifier { + providerId: string; + providerUid: string; +} +/** + * Identifies a user to be looked up. + */ +export type UserIdentifier = UidIdentifier | EmailIdentifier | PhoneIdentifier | ProviderIdentifier; +export declare function isUidIdentifier(id: UserIdentifier): id is UidIdentifier; +export declare function isEmailIdentifier(id: UserIdentifier): id is EmailIdentifier; +export declare function isPhoneIdentifier(id: UserIdentifier): id is PhoneIdentifier; +export declare function isProviderIdentifier(id: ProviderIdentifier): id is ProviderIdentifier; diff --git a/node_modules/firebase-admin/lib/auth/identifier.js b/node_modules/firebase-admin/lib/auth/identifier.js new file mode 100644 index 0000000..c27c417 --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/identifier.js @@ -0,0 +1,39 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isUidIdentifier = isUidIdentifier; +exports.isEmailIdentifier = isEmailIdentifier; +exports.isPhoneIdentifier = isPhoneIdentifier; +exports.isProviderIdentifier = isProviderIdentifier; +/* + * User defined type guards. See + * https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards + */ +function isUidIdentifier(id) { + return id.uid !== undefined; +} +function isEmailIdentifier(id) { + return id.email !== undefined; +} +function isPhoneIdentifier(id) { + return id.phoneNumber !== undefined; +} +function isProviderIdentifier(id) { + const pid = id; + return pid.providerId !== undefined && pid.providerUid !== undefined; +} diff --git a/node_modules/firebase-admin/lib/auth/index.d.ts b/node_modules/firebase-admin/lib/auth/index.d.ts new file mode 100644 index 0000000..2007437 --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/index.d.ts @@ -0,0 +1,58 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Firebase Authentication. + * + * @packageDocumentation + */ +import { App } from '../app/index'; +import { Auth } from './auth'; +/** + * Gets the {@link Auth} service for the default app or a + * given app. + * + * `getAuth()` can be called with no arguments to access the default app's + * {@link Auth} service or as `getAuth(app)` to access the + * {@link Auth} service associated with a specific app. + * + * @example + * ```javascript + * // Get the Auth service for the default app + * const defaultAuth = getAuth(); + * ``` + * + * @example + * ```javascript + * // Get the Auth service for a given app + * const otherAuth = getAuth(otherApp); + * ``` + * + */ +export declare function getAuth(app?: App): Auth; +export { ActionCodeSettings } from './action-code-settings-builder'; +export { Auth, } from './auth'; +export { AllowByDefault, AllowByDefaultWrap, AllowlistOnly, AllowlistOnlyWrap, AuthFactorType, AuthProviderConfig, AuthProviderConfigFilter, BaseAuthProviderConfig, BaseCreateMultiFactorInfoRequest, BaseUpdateMultiFactorInfoRequest, CreateMultiFactorInfoRequest, CreatePhoneMultiFactorInfoRequest, CreateRequest, EmailSignInProviderConfig, ListProviderConfigResults, MultiFactorConfig, MultiFactorConfigState, MultiFactorCreateSettings, MultiFactorUpdateSettings, MultiFactorProviderConfig, OAuthResponseType, OIDCAuthProviderConfig, OIDCUpdateAuthProviderRequest, RecaptchaAction, RecaptchaConfig, RecaptchaKey, RecaptchaKeyClientType, RecaptchaManagedRule, RecaptchaTollFraudManagedRule, RecaptchaProviderEnforcementState, SAMLAuthProviderConfig, SAMLUpdateAuthProviderRequest, SmsRegionConfig, UserProvider, UpdateAuthProviderRequest, UpdateMultiFactorInfoRequest, UpdatePhoneMultiFactorInfoRequest, UpdateRequest, TotpMultiFactorProviderConfig, PasswordPolicyConfig, PasswordPolicyEnforcementState, CustomStrengthOptionsConfig, EmailPrivacyConfig, MobileLinksConfig, MobileLinksDomain, } from './auth-config'; +export { BaseAuth, DeleteUsersResult, GetUsersResult, ListUsersResult, SessionCookieOptions, } from './base-auth'; +export { EmailIdentifier, PhoneIdentifier, ProviderIdentifier, UidIdentifier, UserIdentifier, } from './identifier'; +export { CreateTenantRequest, Tenant, UpdateTenantRequest, } from './tenant'; +export { ListTenantsResult, TenantAwareAuth, TenantManager, } from './tenant-manager'; +export { UpdateProjectConfigRequest, ProjectConfig, } from './project-config'; +export { ProjectConfigManager, } from './project-config-manager'; +export { DecodedIdToken, DecodedAuthBlockingToken } from './token-verifier'; +export { HashAlgorithmType, UserImportOptions, UserImportRecord, UserImportResult, UserMetadataRequest, UserProviderRequest, } from './user-import-builder'; +export { MultiFactorInfo, MultiFactorSettings, PhoneMultiFactorInfo, UserInfo, UserMetadata, UserRecord, } from './user-record'; +export { FirebaseAuthError, AuthClientErrorCode, } from '../utils/error'; diff --git a/node_modules/firebase-admin/lib/auth/index.js b/node_modules/firebase-admin/lib/auth/index.js new file mode 100644 index 0000000..d353643 --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/index.js @@ -0,0 +1,78 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AuthClientErrorCode = exports.FirebaseAuthError = exports.UserRecord = exports.UserMetadata = exports.UserInfo = exports.PhoneMultiFactorInfo = exports.MultiFactorSettings = exports.MultiFactorInfo = exports.ProjectConfigManager = exports.ProjectConfig = exports.TenantManager = exports.TenantAwareAuth = exports.Tenant = exports.BaseAuth = exports.Auth = void 0; +exports.getAuth = getAuth; +/** + * Firebase Authentication. + * + * @packageDocumentation + */ +const index_1 = require("../app/index"); +const auth_1 = require("./auth"); +/** + * Gets the {@link Auth} service for the default app or a + * given app. + * + * `getAuth()` can be called with no arguments to access the default app's + * {@link Auth} service or as `getAuth(app)` to access the + * {@link Auth} service associated with a specific app. + * + * @example + * ```javascript + * // Get the Auth service for the default app + * const defaultAuth = getAuth(); + * ``` + * + * @example + * ```javascript + * // Get the Auth service for a given app + * const otherAuth = getAuth(otherApp); + * ``` + * + */ +function getAuth(app) { + if (typeof app === 'undefined') { + app = (0, index_1.getApp)(); + } + const firebaseApp = app; + return firebaseApp.getOrInitService('auth', (app) => new auth_1.Auth(app)); +} +var auth_2 = require("./auth"); +Object.defineProperty(exports, "Auth", { enumerable: true, get: function () { return auth_2.Auth; } }); +var base_auth_1 = require("./base-auth"); +Object.defineProperty(exports, "BaseAuth", { enumerable: true, get: function () { return base_auth_1.BaseAuth; } }); +var tenant_1 = require("./tenant"); +Object.defineProperty(exports, "Tenant", { enumerable: true, get: function () { return tenant_1.Tenant; } }); +var tenant_manager_1 = require("./tenant-manager"); +Object.defineProperty(exports, "TenantAwareAuth", { enumerable: true, get: function () { return tenant_manager_1.TenantAwareAuth; } }); +Object.defineProperty(exports, "TenantManager", { enumerable: true, get: function () { return tenant_manager_1.TenantManager; } }); +var project_config_1 = require("./project-config"); +Object.defineProperty(exports, "ProjectConfig", { enumerable: true, get: function () { return project_config_1.ProjectConfig; } }); +var project_config_manager_1 = require("./project-config-manager"); +Object.defineProperty(exports, "ProjectConfigManager", { enumerable: true, get: function () { return project_config_manager_1.ProjectConfigManager; } }); +var user_record_1 = require("./user-record"); +Object.defineProperty(exports, "MultiFactorInfo", { enumerable: true, get: function () { return user_record_1.MultiFactorInfo; } }); +Object.defineProperty(exports, "MultiFactorSettings", { enumerable: true, get: function () { return user_record_1.MultiFactorSettings; } }); +Object.defineProperty(exports, "PhoneMultiFactorInfo", { enumerable: true, get: function () { return user_record_1.PhoneMultiFactorInfo; } }); +Object.defineProperty(exports, "UserInfo", { enumerable: true, get: function () { return user_record_1.UserInfo; } }); +Object.defineProperty(exports, "UserMetadata", { enumerable: true, get: function () { return user_record_1.UserMetadata; } }); +Object.defineProperty(exports, "UserRecord", { enumerable: true, get: function () { return user_record_1.UserRecord; } }); +var error_1 = require("../utils/error"); +Object.defineProperty(exports, "FirebaseAuthError", { enumerable: true, get: function () { return error_1.FirebaseAuthError; } }); +Object.defineProperty(exports, "AuthClientErrorCode", { enumerable: true, get: function () { return error_1.AuthClientErrorCode; } }); diff --git a/node_modules/firebase-admin/lib/auth/project-config-manager.d.ts b/node_modules/firebase-admin/lib/auth/project-config-manager.d.ts new file mode 100644 index 0000000..923b3eb --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/project-config-manager.d.ts @@ -0,0 +1,22 @@ +/*! firebase-admin v13.6.0 */ +import { ProjectConfig, UpdateProjectConfigRequest } from './project-config'; +/** + * Manages (gets and updates) the current project config. + */ +export declare class ProjectConfigManager { + private readonly authRequestHandler; + /** + * Get the project configuration. + * + * @returns A promise fulfilled with the project configuration. + */ + getProjectConfig(): Promise; + /** + * Updates an existing project configuration. + * + * @param projectConfigOptions - The properties to update on the project. + * + * @returns A promise fulfilled with the updated project config. + */ + updateProjectConfig(projectConfigOptions: UpdateProjectConfigRequest): Promise; +} diff --git a/node_modules/firebase-admin/lib/auth/project-config-manager.js b/node_modules/firebase-admin/lib/auth/project-config-manager.js new file mode 100644 index 0000000..2d6cf0d --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/project-config-manager.js @@ -0,0 +1,47 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProjectConfigManager = void 0; +const project_config_1 = require("./project-config"); +const auth_api_request_1 = require("./auth-api-request"); +/** + * Manages (gets and updates) the current project config. + */ +class ProjectConfigManager { + /** + * Initializes a ProjectConfigManager instance for a specified FirebaseApp. + * + * @param app - The app for this ProjectConfigManager instance. + * + * @constructor + * @internal + */ + constructor(app) { + this.authRequestHandler = new auth_api_request_1.AuthRequestHandler(app); + } + /** + * Get the project configuration. + * + * @returns A promise fulfilled with the project configuration. + */ + getProjectConfig() { + return this.authRequestHandler.getProjectConfig() + .then((response) => { + return new project_config_1.ProjectConfig(response); + }); + } + /** + * Updates an existing project configuration. + * + * @param projectConfigOptions - The properties to update on the project. + * + * @returns A promise fulfilled with the updated project config. + */ + updateProjectConfig(projectConfigOptions) { + return this.authRequestHandler.updateProjectConfig(projectConfigOptions) + .then((response) => { + return new project_config_1.ProjectConfig(response); + }); + } +} +exports.ProjectConfigManager = ProjectConfigManager; diff --git a/node_modules/firebase-admin/lib/auth/project-config.d.ts b/node_modules/firebase-admin/lib/auth/project-config.d.ts new file mode 100644 index 0000000..89716e0 --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/project-config.d.ts @@ -0,0 +1,111 @@ +/*! firebase-admin v13.6.0 */ +import { SmsRegionConfig, MultiFactorConfig, MultiFactorAuthServerConfig, RecaptchaConfig, RecaptchaAuthServerConfig, PasswordPolicyAuthServerConfig, PasswordPolicyConfig, EmailPrivacyConfig, MobileLinksConfig } from './auth-config'; +/** + * Interface representing the properties to update on the provided project config. + */ +export interface UpdateProjectConfigRequest { + /** + * The SMS configuration to update on the project. + */ + smsRegionConfig?: SmsRegionConfig; + /** + * The multi-factor auth configuration to update on the project. + */ + multiFactorConfig?: MultiFactorConfig; + /** + * The reCAPTCHA configuration to update on the project. + * By enabling reCAPTCHA Enterprise integration, you are + * agreeing to the reCAPTCHA Enterprise + * {@link https://cloud.google.com/terms/service-terms | Term of Service}. + */ + recaptchaConfig?: RecaptchaConfig; + /** + * The password policy configuration to update on the project + */ + passwordPolicyConfig?: PasswordPolicyConfig; + /** + * The email privacy configuration to update on the project + */ + emailPrivacyConfig?: EmailPrivacyConfig; + /** + * The mobile links configuration for the project + */ + mobileLinksConfig?: MobileLinksConfig; +} +/** + * Response received when getting or updating the project config. + */ +export interface ProjectConfigServerResponse { + smsRegionConfig?: SmsRegionConfig; + mfa?: MultiFactorAuthServerConfig; + recaptchaConfig?: RecaptchaAuthServerConfig; + passwordPolicyConfig?: PasswordPolicyAuthServerConfig; + emailPrivacyConfig?: EmailPrivacyConfig; + mobileLinksConfig?: MobileLinksConfig; +} +/** + * Request to update the project config. + */ +export interface ProjectConfigClientRequest { + smsRegionConfig?: SmsRegionConfig; + mfa?: MultiFactorAuthServerConfig; + recaptchaConfig?: RecaptchaAuthServerConfig; + passwordPolicyConfig?: PasswordPolicyAuthServerConfig; + emailPrivacyConfig?: EmailPrivacyConfig; + mobileLinksConfig?: MobileLinksConfig; +} +/** +* Represents a project configuration. +*/ +export declare class ProjectConfig { + /** + * The SMS Regions Config for the project. + * Configures the regions where users are allowed to send verification SMS. + * This is based on the calling code of the destination phone number. + */ + readonly smsRegionConfig?: SmsRegionConfig; + /** + * The project's multi-factor auth configuration. + * Supports only phone and TOTP. + */ + private readonly multiFactorConfig_?; + /** + * The multi-factor auth configuration. + */ + get multiFactorConfig(): MultiFactorConfig | undefined; + /** + * The reCAPTCHA configuration to update on the project. + * By enabling reCAPTCHA Enterprise integration, you are + * agreeing to the reCAPTCHA Enterprise + * {@link https://cloud.google.com/terms/service-terms | Term of Service}. + */ + private readonly recaptchaConfig_?; + /** + * The reCAPTCHA configuration. + */ + get recaptchaConfig(): RecaptchaConfig | undefined; + /** + * The password policy configuration for the project + */ + readonly passwordPolicyConfig?: PasswordPolicyConfig; + /** + * The email privacy configuration for the project + */ + readonly emailPrivacyConfig?: EmailPrivacyConfig; + /** + * The mobile links configuration for the project + */ + readonly mobileLinksConfig?: MobileLinksConfig; + /** + * Validates a project config options object. Throws an error on failure. + * + * @param request - The project config options object to validate. + */ + private static validate; + /** + * Returns a JSON-serializable representation of this object. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON(): object; +} diff --git a/node_modules/firebase-admin/lib/auth/project-config.js b/node_modules/firebase-admin/lib/auth/project-config.js new file mode 100644 index 0000000..2c8507a --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/project-config.js @@ -0,0 +1,183 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProjectConfig = void 0; +/*! + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const validator = require("../utils/validator"); +const error_1 = require("../utils/error"); +const auth_config_1 = require("./auth-config"); +const deep_copy_1 = require("../utils/deep-copy"); +/** +* Represents a project configuration. +*/ +class ProjectConfig { + /** + * The multi-factor auth configuration. + */ + get multiFactorConfig() { + return this.multiFactorConfig_; + } + /** + * The reCAPTCHA configuration. + */ + get recaptchaConfig() { + return this.recaptchaConfig_; + } + /** + * Validates a project config options object. Throws an error on failure. + * + * @param request - The project config options object to validate. + */ + static validate(request) { + if (!validator.isNonNullObject(request)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"UpdateProjectConfigRequest" must be a valid non-null object.'); + } + const validKeys = { + smsRegionConfig: true, + multiFactorConfig: true, + recaptchaConfig: true, + passwordPolicyConfig: true, + emailPrivacyConfig: true, + mobileLinksConfig: true, + }; + // Check for unsupported top level attributes. + for (const key in request) { + if (!(key in validKeys)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, `"${key}" is not a valid UpdateProjectConfigRequest parameter.`); + } + } + // Validate SMS Regions Config if provided. + if (typeof request.smsRegionConfig !== 'undefined') { + auth_config_1.SmsRegionsAuthConfig.validate(request.smsRegionConfig); + } + // Validate Multi Factor Config if provided + if (typeof request.multiFactorConfig !== 'undefined') { + auth_config_1.MultiFactorAuthConfig.validate(request.multiFactorConfig); + } + // Validate reCAPTCHA config attribute. + if (typeof request.recaptchaConfig !== 'undefined') { + auth_config_1.RecaptchaAuthConfig.validate(request.recaptchaConfig); + } + // Validate Password policy Config if provided + if (typeof request.passwordPolicyConfig !== 'undefined') { + auth_config_1.PasswordPolicyAuthConfig.validate(request.passwordPolicyConfig); + } + // Validate Email Privacy Config if provided. + if (typeof request.emailPrivacyConfig !== 'undefined') { + auth_config_1.EmailPrivacyAuthConfig.validate(request.emailPrivacyConfig); + } + // Validate Mobile Links Config if provided. + if (typeof request.mobileLinksConfig !== 'undefined') { + auth_config_1.MobileLinksAuthConfig.validate(request.mobileLinksConfig); + } + } + /** + * Build the corresponding server request for a UpdateProjectConfigRequest object. + * @param configOptions - The properties to convert to a server request. + * @returns The equivalent server request. + * + * @internal + */ + static buildServerRequest(configOptions) { + ProjectConfig.validate(configOptions); + const request = {}; + if (typeof configOptions.smsRegionConfig !== 'undefined') { + request.smsRegionConfig = configOptions.smsRegionConfig; + } + if (typeof configOptions.multiFactorConfig !== 'undefined') { + request.mfa = auth_config_1.MultiFactorAuthConfig.buildServerRequest(configOptions.multiFactorConfig); + } + if (typeof configOptions.recaptchaConfig !== 'undefined') { + request.recaptchaConfig = auth_config_1.RecaptchaAuthConfig.buildServerRequest(configOptions.recaptchaConfig); + } + if (typeof configOptions.passwordPolicyConfig !== 'undefined') { + request.passwordPolicyConfig = auth_config_1.PasswordPolicyAuthConfig.buildServerRequest(configOptions.passwordPolicyConfig); + } + if (typeof configOptions.emailPrivacyConfig !== 'undefined') { + request.emailPrivacyConfig = configOptions.emailPrivacyConfig; + } + if (typeof configOptions.mobileLinksConfig !== 'undefined') { + request.mobileLinksConfig = configOptions.mobileLinksConfig; + } + return request; + } + /** + * The Project Config object constructor. + * + * @param response - The server side response used to initialize the Project Config object. + * @constructor + * @internal + */ + constructor(response) { + if (typeof response.smsRegionConfig !== 'undefined') { + this.smsRegionConfig = response.smsRegionConfig; + } + //Backend API returns "mfa" in case of project config and "mfaConfig" in case of tenant config. + //The SDK exposes it as multiFactorConfig always. + if (typeof response.mfa !== 'undefined') { + this.multiFactorConfig_ = new auth_config_1.MultiFactorAuthConfig(response.mfa); + } + if (typeof response.recaptchaConfig !== 'undefined') { + this.recaptchaConfig_ = new auth_config_1.RecaptchaAuthConfig(response.recaptchaConfig); + } + if (typeof response.passwordPolicyConfig !== 'undefined') { + this.passwordPolicyConfig = new auth_config_1.PasswordPolicyAuthConfig(response.passwordPolicyConfig); + } + if (typeof response.emailPrivacyConfig !== 'undefined') { + this.emailPrivacyConfig = response.emailPrivacyConfig; + } + if (typeof response.mobileLinksConfig !== 'undefined') { + this.mobileLinksConfig = response.mobileLinksConfig; + } + } + /** + * Returns a JSON-serializable representation of this object. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON() { + // JSON serialization + const json = { + smsRegionConfig: (0, deep_copy_1.deepCopy)(this.smsRegionConfig), + multiFactorConfig: (0, deep_copy_1.deepCopy)(this.multiFactorConfig), + recaptchaConfig: (0, deep_copy_1.deepCopy)(this.recaptchaConfig), + passwordPolicyConfig: (0, deep_copy_1.deepCopy)(this.passwordPolicyConfig), + emailPrivacyConfig: (0, deep_copy_1.deepCopy)(this.emailPrivacyConfig), + mobileLinksConfig: (0, deep_copy_1.deepCopy)(this.mobileLinksConfig), + }; + if (typeof json.smsRegionConfig === 'undefined') { + delete json.smsRegionConfig; + } + if (typeof json.multiFactorConfig === 'undefined') { + delete json.multiFactorConfig; + } + if (typeof json.recaptchaConfig === 'undefined') { + delete json.recaptchaConfig; + } + if (typeof json.passwordPolicyConfig === 'undefined') { + delete json.passwordPolicyConfig; + } + if (typeof json.emailPrivacyConfig === 'undefined') { + delete json.emailPrivacyConfig; + } + if (typeof json.mobileLinksConfig === 'undefined') { + delete json.mobileLinksConfig; + } + return json; + } +} +exports.ProjectConfig = ProjectConfig; diff --git a/node_modules/firebase-admin/lib/auth/tenant-manager.d.ts b/node_modules/firebase-admin/lib/auth/tenant-manager.d.ts new file mode 100644 index 0000000..1579bf7 --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/tenant-manager.d.ts @@ -0,0 +1,146 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BaseAuth, SessionCookieOptions } from './base-auth'; +import { Tenant, CreateTenantRequest, UpdateTenantRequest } from './tenant'; +import { DecodedIdToken } from './token-verifier'; +/** + * Interface representing the object returned from a + * {@link TenantManager.listTenants} + * operation. + * Contains the list of tenants for the current batch and the next page token if available. + */ +export interface ListTenantsResult { + /** + * The list of {@link Tenant} objects for the downloaded batch. + */ + tenants: Tenant[]; + /** + * The next page token if available. This is needed for the next batch download. + */ + pageToken?: string; +} +/** + * Tenant-aware `Auth` interface used for managing users, configuring SAML/OIDC providers, + * generating email links for password reset, email verification, etc for specific tenants. + * + * Multi-tenancy support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. + * + * Each tenant contains its own identity providers, settings and sets of users. + * Using `TenantAwareAuth`, users for a specific tenant and corresponding OIDC/SAML + * configurations can also be managed, ID tokens for users signed in to a specific tenant + * can be verified, and email action links can also be generated for users belonging to the + * tenant. + * + * `TenantAwareAuth` instances for a specific `tenantId` can be instantiated by calling + * {@link TenantManager.authForTenant}. + */ +export declare class TenantAwareAuth extends BaseAuth { + /** + * The tenant identifier corresponding to this `TenantAwareAuth` instance. + * All calls to the user management APIs, OIDC/SAML provider management APIs, email link + * generation APIs, etc will only be applied within the scope of this tenant. + */ + readonly tenantId: string; + /** + * {@inheritdoc BaseAuth.verifyIdToken} + */ + verifyIdToken(idToken: string, checkRevoked?: boolean): Promise; + /** + * {@inheritdoc BaseAuth.createSessionCookie} + */ + createSessionCookie(idToken: string, sessionCookieOptions: SessionCookieOptions): Promise; + /** + * {@inheritdoc BaseAuth.verifySessionCookie} + */ + verifySessionCookie(sessionCookie: string, checkRevoked?: boolean): Promise; +} +/** + * Defines the tenant manager used to help manage tenant related operations. + * This includes: + *
                            + *
                          • The ability to create, update, list, get and delete tenants for the underlying + * project.
                          • + *
                          • Getting a `TenantAwareAuth` instance for running Auth related operations + * (user management, provider configuration management, token verification, + * email link generation, etc) in the context of a specified tenant.
                          • + *
                          + */ +export declare class TenantManager { + private readonly app; + private readonly authRequestHandler; + private readonly tenantsMap; + /** + * Returns a `TenantAwareAuth` instance bound to the given tenant ID. + * + * @param tenantId - The tenant ID whose `TenantAwareAuth` instance is to be returned. + * + * @returns The `TenantAwareAuth` instance corresponding to this tenant identifier. + */ + authForTenant(tenantId: string): TenantAwareAuth; + /** + * Gets the tenant configuration for the tenant corresponding to a given `tenantId`. + * + * @param tenantId - The tenant identifier corresponding to the tenant whose data to fetch. + * + * @returns A promise fulfilled with the tenant configuration to the provided `tenantId`. + */ + getTenant(tenantId: string): Promise; + /** + * Retrieves a list of tenants (single batch only) with a size of `maxResults` + * starting from the offset as specified by `pageToken`. This is used to + * retrieve all the tenants of a specified project in batches. + * + * @param maxResults - The page size, 1000 if undefined. This is also + * the maximum allowed limit. + * @param pageToken - The next page token. If not specified, returns + * tenants starting without any offset. + * + * @returns A promise that resolves with + * a batch of downloaded tenants and the next page token. + */ + listTenants(maxResults?: number, pageToken?: string): Promise; + /** + * Deletes an existing tenant. + * + * @param tenantId - The `tenantId` corresponding to the tenant to delete. + * + * @returns An empty promise fulfilled once the tenant has been deleted. + */ + deleteTenant(tenantId: string): Promise; + /** + * Creates a new tenant. + * When creating new tenants, tenants that use separate billing and quota will require their + * own project and must be defined as `full_service`. + * + * @param tenantOptions - The properties to set on the new tenant configuration to be created. + * + * @returns A promise fulfilled with the tenant configuration corresponding to the newly + * created tenant. + */ + createTenant(tenantOptions: CreateTenantRequest): Promise; + /** + * Updates an existing tenant configuration. + * + * @param tenantId - The `tenantId` corresponding to the tenant to delete. + * @param tenantOptions - The properties to update on the provided tenant. + * + * @returns A promise fulfilled with the update tenant data. + */ + updateTenant(tenantId: string, tenantOptions: UpdateTenantRequest): Promise; +} diff --git a/node_modules/firebase-admin/lib/auth/tenant-manager.js b/node_modules/firebase-admin/lib/auth/tenant-manager.js new file mode 100644 index 0000000..973307b --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/tenant-manager.js @@ -0,0 +1,230 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TenantManager = exports.TenantAwareAuth = void 0; +const validator = require("../utils/validator"); +const utils = require("../utils/index"); +const error_1 = require("../utils/error"); +const base_auth_1 = require("./base-auth"); +const tenant_1 = require("./tenant"); +const auth_api_request_1 = require("./auth-api-request"); +/** + * Tenant-aware `Auth` interface used for managing users, configuring SAML/OIDC providers, + * generating email links for password reset, email verification, etc for specific tenants. + * + * Multi-tenancy support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. + * + * Each tenant contains its own identity providers, settings and sets of users. + * Using `TenantAwareAuth`, users for a specific tenant and corresponding OIDC/SAML + * configurations can also be managed, ID tokens for users signed in to a specific tenant + * can be verified, and email action links can also be generated for users belonging to the + * tenant. + * + * `TenantAwareAuth` instances for a specific `tenantId` can be instantiated by calling + * {@link TenantManager.authForTenant}. + */ +class TenantAwareAuth extends base_auth_1.BaseAuth { + /** + * The TenantAwareAuth class constructor. + * + * @param app - The app that created this tenant. + * @param tenantId - The corresponding tenant ID. + * @constructor + * @internal + */ + constructor(app, tenantId) { + super(app, new auth_api_request_1.TenantAwareAuthRequestHandler(app, tenantId), (0, base_auth_1.createFirebaseTokenGenerator)(app, tenantId)); + utils.addReadonlyGetter(this, 'tenantId', tenantId); + } + /** + * {@inheritdoc BaseAuth.verifyIdToken} + */ + verifyIdToken(idToken, checkRevoked = false) { + return super.verifyIdToken(idToken, checkRevoked) + .then((decodedClaims) => { + // Validate tenant ID. + if (decodedClaims.firebase.tenant !== this.tenantId) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISMATCHING_TENANT_ID); + } + return decodedClaims; + }); + } + /** + * {@inheritdoc BaseAuth.createSessionCookie} + */ + createSessionCookie(idToken, sessionCookieOptions) { + // Validate arguments before processing. + if (!validator.isNonEmptyString(idToken)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ID_TOKEN)); + } + if (!validator.isNonNullObject(sessionCookieOptions) || + !validator.isNumber(sessionCookieOptions.expiresIn)) { + return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_SESSION_COOKIE_DURATION)); + } + // This will verify the ID token and then match the tenant ID before creating the session cookie. + return this.verifyIdToken(idToken) + .then(() => { + return super.createSessionCookie(idToken, sessionCookieOptions); + }); + } + /** + * {@inheritdoc BaseAuth.verifySessionCookie} + */ + verifySessionCookie(sessionCookie, checkRevoked = false) { + return super.verifySessionCookie(sessionCookie, checkRevoked) + .then((decodedClaims) => { + if (decodedClaims.firebase.tenant !== this.tenantId) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISMATCHING_TENANT_ID); + } + return decodedClaims; + }); + } +} +exports.TenantAwareAuth = TenantAwareAuth; +/** + * Defines the tenant manager used to help manage tenant related operations. + * This includes: + *
                            + *
                          • The ability to create, update, list, get and delete tenants for the underlying + * project.
                          • + *
                          • Getting a `TenantAwareAuth` instance for running Auth related operations + * (user management, provider configuration management, token verification, + * email link generation, etc) in the context of a specified tenant.
                          • + *
                          + */ +class TenantManager { + /** + * Initializes a TenantManager instance for a specified FirebaseApp. + * + * @param app - The app for this TenantManager instance. + * + * @constructor + * @internal + */ + constructor(app) { + this.app = app; + this.authRequestHandler = new auth_api_request_1.AuthRequestHandler(app); + this.tenantsMap = {}; + } + /** + * Returns a `TenantAwareAuth` instance bound to the given tenant ID. + * + * @param tenantId - The tenant ID whose `TenantAwareAuth` instance is to be returned. + * + * @returns The `TenantAwareAuth` instance corresponding to this tenant identifier. + */ + authForTenant(tenantId) { + if (!validator.isNonEmptyString(tenantId)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_TENANT_ID); + } + if (typeof this.tenantsMap[tenantId] === 'undefined') { + this.tenantsMap[tenantId] = new TenantAwareAuth(this.app, tenantId); + } + return this.tenantsMap[tenantId]; + } + /** + * Gets the tenant configuration for the tenant corresponding to a given `tenantId`. + * + * @param tenantId - The tenant identifier corresponding to the tenant whose data to fetch. + * + * @returns A promise fulfilled with the tenant configuration to the provided `tenantId`. + */ + getTenant(tenantId) { + return this.authRequestHandler.getTenant(tenantId) + .then((response) => { + return new tenant_1.Tenant(response); + }); + } + /** + * Retrieves a list of tenants (single batch only) with a size of `maxResults` + * starting from the offset as specified by `pageToken`. This is used to + * retrieve all the tenants of a specified project in batches. + * + * @param maxResults - The page size, 1000 if undefined. This is also + * the maximum allowed limit. + * @param pageToken - The next page token. If not specified, returns + * tenants starting without any offset. + * + * @returns A promise that resolves with + * a batch of downloaded tenants and the next page token. + */ + listTenants(maxResults, pageToken) { + return this.authRequestHandler.listTenants(maxResults, pageToken) + .then((response) => { + // List of tenants to return. + const tenants = []; + // Convert each user response to a Tenant. + response.tenants.forEach((tenantResponse) => { + tenants.push(new tenant_1.Tenant(tenantResponse)); + }); + // Return list of tenants and the next page token if available. + const result = { + tenants, + pageToken: response.nextPageToken, + }; + // Delete result.pageToken if undefined. + if (typeof result.pageToken === 'undefined') { + delete result.pageToken; + } + return result; + }); + } + /** + * Deletes an existing tenant. + * + * @param tenantId - The `tenantId` corresponding to the tenant to delete. + * + * @returns An empty promise fulfilled once the tenant has been deleted. + */ + deleteTenant(tenantId) { + return this.authRequestHandler.deleteTenant(tenantId); + } + /** + * Creates a new tenant. + * When creating new tenants, tenants that use separate billing and quota will require their + * own project and must be defined as `full_service`. + * + * @param tenantOptions - The properties to set on the new tenant configuration to be created. + * + * @returns A promise fulfilled with the tenant configuration corresponding to the newly + * created tenant. + */ + createTenant(tenantOptions) { + return this.authRequestHandler.createTenant(tenantOptions) + .then((response) => { + return new tenant_1.Tenant(response); + }); + } + /** + * Updates an existing tenant configuration. + * + * @param tenantId - The `tenantId` corresponding to the tenant to delete. + * @param tenantOptions - The properties to update on the provided tenant. + * + * @returns A promise fulfilled with the update tenant data. + */ + updateTenant(tenantId, tenantOptions) { + return this.authRequestHandler.updateTenant(tenantId, tenantOptions) + .then((response) => { + return new tenant_1.Tenant(response); + }); + } +} +exports.TenantManager = TenantManager; diff --git a/node_modules/firebase-admin/lib/auth/tenant.d.ts b/node_modules/firebase-admin/lib/auth/tenant.d.ts new file mode 100644 index 0000000..dcc86c2 --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/tenant.d.ts @@ -0,0 +1,182 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { EmailSignInConfigServerRequest, MultiFactorAuthServerConfig, MultiFactorConfig, EmailSignInProviderConfig, SmsRegionConfig, RecaptchaConfig, RecaptchaAuthServerConfig, PasswordPolicyConfig, PasswordPolicyAuthServerConfig, EmailPrivacyConfig } from './auth-config'; +/** + * Interface representing the properties to update on the provided tenant. + */ +export interface UpdateTenantRequest { + /** + * The tenant display name. + */ + displayName?: string; + /** + * The email sign in configuration. + */ + emailSignInConfig?: EmailSignInProviderConfig; + /** + * Whether the anonymous provider is enabled. + */ + anonymousSignInEnabled?: boolean; + /** + * The multi-factor auth configuration to update on the tenant. + */ + multiFactorConfig?: MultiFactorConfig; + /** + * The updated map containing the test phone number / code pairs for the tenant. + * Passing null clears the previously save phone number / code pairs. + */ + testPhoneNumbers?: { + [phoneNumber: string]: string; + } | null; + /** + * The SMS configuration to update on the project. + */ + smsRegionConfig?: SmsRegionConfig; + /** + * The reCAPTCHA configuration to update on the tenant. + * By enabling reCAPTCHA Enterprise integration, you are + * agreeing to the reCAPTCHA Enterprise + * {@link https://cloud.google.com/terms/service-terms | Term of Service}. + */ + recaptchaConfig?: RecaptchaConfig; + /** + * The password policy configuration for the tenant + */ + passwordPolicyConfig?: PasswordPolicyConfig; + /** + * The email privacy configuration for the tenant + */ + emailPrivacyConfig?: EmailPrivacyConfig; +} +/** + * Interface representing the properties to set on a new tenant. + */ +export type CreateTenantRequest = UpdateTenantRequest; +/** The corresponding server side representation of a TenantOptions object. */ +export interface TenantOptionsServerRequest extends EmailSignInConfigServerRequest { + displayName?: string; + enableAnonymousUser?: boolean; + mfaConfig?: MultiFactorAuthServerConfig; + testPhoneNumbers?: { + [key: string]: string; + }; + smsRegionConfig?: SmsRegionConfig; + recaptchaConfig?: RecaptchaAuthServerConfig; + passwordPolicyConfig?: PasswordPolicyAuthServerConfig; + emailPrivacyConfig?: EmailPrivacyConfig; +} +/** The tenant server response interface. */ +export interface TenantServerResponse { + name: string; + displayName?: string; + allowPasswordSignup?: boolean; + enableEmailLinkSignin?: boolean; + enableAnonymousUser?: boolean; + mfaConfig?: MultiFactorAuthServerConfig; + testPhoneNumbers?: { + [key: string]: string; + }; + smsRegionConfig?: SmsRegionConfig; + recaptchaConfig?: RecaptchaAuthServerConfig; + passwordPolicyConfig?: PasswordPolicyAuthServerConfig; + emailPrivacyConfig?: EmailPrivacyConfig; +} +/** + * Represents a tenant configuration. + * + * Multi-tenancy support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. + * + * Before multi-tenancy can be used on a Google Cloud Identity Platform project, + * tenants must be allowed on that project via the Cloud Console UI. + * + * A tenant configuration provides information such as the display name, tenant + * identifier and email authentication configuration. + * For OIDC/SAML provider configuration management, `TenantAwareAuth` instances should + * be used instead of a `Tenant` to retrieve the list of configured IdPs on a tenant. + * When configuring these providers, note that tenants will inherit + * whitelisted domains and authenticated redirect URIs of their parent project. + * + * All other settings of a tenant will also be inherited. These will need to be managed + * from the Cloud Console UI. + */ +export declare class Tenant { + /** + * The tenant identifier. + */ + readonly tenantId: string; + /** + * The tenant display name. + */ + readonly displayName?: string; + readonly anonymousSignInEnabled: boolean; + /** + * The map containing the test phone number / code pairs for the tenant. + */ + readonly testPhoneNumbers?: { + [phoneNumber: string]: string; + }; + private readonly emailSignInConfig_?; + private readonly multiFactorConfig_?; + /** + * The map conatining the reCAPTCHA config. + * By enabling reCAPTCHA Enterprise Integration you are + * agreeing to reCAPTCHA Enterprise + * {@link https://cloud.google.com/terms/service-terms | Term of Service}. + */ + private readonly recaptchaConfig_?; + /** + * The SMS Regions Config to update a tenant. + * Configures the regions where users are allowed to send verification SMS. + * This is based on the calling code of the destination phone number. + */ + readonly smsRegionConfig?: SmsRegionConfig; + /** + * The password policy configuration for the tenant + */ + readonly passwordPolicyConfig?: PasswordPolicyConfig; + /** + * The email privacy configuration for the tenant + */ + readonly emailPrivacyConfig?: EmailPrivacyConfig; + /** + * Validates a tenant options object. Throws an error on failure. + * + * @param request - The tenant options object to validate. + * @param createRequest - Whether this is a create request. + */ + private static validate; + /** + * The email sign in provider configuration. + */ + get emailSignInConfig(): EmailSignInProviderConfig | undefined; + /** + * The multi-factor auth configuration on the current tenant. + */ + get multiFactorConfig(): MultiFactorConfig | undefined; + /** + * The recaptcha config auth configuration of the current tenant. + */ + get recaptchaConfig(): RecaptchaConfig | undefined; + /** + * Returns a JSON-serializable representation of this object. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON(): object; +} diff --git a/node_modules/firebase-admin/lib/auth/tenant.js b/node_modules/firebase-admin/lib/auth/tenant.js new file mode 100644 index 0000000..eeff78b --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/tenant.js @@ -0,0 +1,273 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Tenant = void 0; +const validator = require("../utils/validator"); +const deep_copy_1 = require("../utils/deep-copy"); +const error_1 = require("../utils/error"); +const auth_config_1 = require("./auth-config"); +/** + * Represents a tenant configuration. + * + * Multi-tenancy support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. + * + * Before multi-tenancy can be used on a Google Cloud Identity Platform project, + * tenants must be allowed on that project via the Cloud Console UI. + * + * A tenant configuration provides information such as the display name, tenant + * identifier and email authentication configuration. + * For OIDC/SAML provider configuration management, `TenantAwareAuth` instances should + * be used instead of a `Tenant` to retrieve the list of configured IdPs on a tenant. + * When configuring these providers, note that tenants will inherit + * whitelisted domains and authenticated redirect URIs of their parent project. + * + * All other settings of a tenant will also be inherited. These will need to be managed + * from the Cloud Console UI. + */ +class Tenant { + /** + * Builds the corresponding server request for a TenantOptions object. + * + * @param tenantOptions - The properties to convert to a server request. + * @param createRequest - Whether this is a create request. + * @returns The equivalent server request. + * + * @internal + */ + static buildServerRequest(tenantOptions, createRequest) { + Tenant.validate(tenantOptions, createRequest); + let request = {}; + if (typeof tenantOptions.emailSignInConfig !== 'undefined') { + request = auth_config_1.EmailSignInConfig.buildServerRequest(tenantOptions.emailSignInConfig); + } + if (typeof tenantOptions.displayName !== 'undefined') { + request.displayName = tenantOptions.displayName; + } + if (typeof tenantOptions.anonymousSignInEnabled !== 'undefined') { + request.enableAnonymousUser = tenantOptions.anonymousSignInEnabled; + } + if (typeof tenantOptions.multiFactorConfig !== 'undefined') { + request.mfaConfig = auth_config_1.MultiFactorAuthConfig.buildServerRequest(tenantOptions.multiFactorConfig); + } + if (typeof tenantOptions.testPhoneNumbers !== 'undefined') { + // null will clear existing test phone numbers. Translate to empty object. + request.testPhoneNumbers = tenantOptions.testPhoneNumbers ?? {}; + } + if (typeof tenantOptions.smsRegionConfig !== 'undefined') { + request.smsRegionConfig = tenantOptions.smsRegionConfig; + } + if (typeof tenantOptions.recaptchaConfig !== 'undefined') { + request.recaptchaConfig = auth_config_1.RecaptchaAuthConfig.buildServerRequest(tenantOptions.recaptchaConfig); + } + if (typeof tenantOptions.passwordPolicyConfig !== 'undefined') { + request.passwordPolicyConfig = auth_config_1.PasswordPolicyAuthConfig.buildServerRequest(tenantOptions.passwordPolicyConfig); + } + if (typeof tenantOptions.emailPrivacyConfig !== 'undefined') { + request.emailPrivacyConfig = tenantOptions.emailPrivacyConfig; + } + return request; + } + /** + * Returns the tenant ID corresponding to the resource name if available. + * + * @param resourceName - The server side resource name + * @returns The tenant ID corresponding to the resource, null otherwise. + * + * @internal + */ + static getTenantIdFromResourceName(resourceName) { + // name is of form projects/project1/tenants/tenant1 + const matchTenantRes = resourceName.match(/\/tenants\/(.*)$/); + if (!matchTenantRes || matchTenantRes.length < 2) { + return null; + } + return matchTenantRes[1]; + } + /** + * Validates a tenant options object. Throws an error on failure. + * + * @param request - The tenant options object to validate. + * @param createRequest - Whether this is a create request. + */ + static validate(request, createRequest) { + const validKeys = { + displayName: true, + emailSignInConfig: true, + anonymousSignInEnabled: true, + multiFactorConfig: true, + testPhoneNumbers: true, + smsRegionConfig: true, + recaptchaConfig: true, + passwordPolicyConfig: true, + emailPrivacyConfig: true, + }; + const label = createRequest ? 'CreateTenantRequest' : 'UpdateTenantRequest'; + if (!validator.isNonNullObject(request)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, `"${label}" must be a valid non-null object.`); + } + // Check for unsupported top level attributes. + for (const key in request) { + if (!(key in validKeys)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, `"${key}" is not a valid ${label} parameter.`); + } + } + // Validate displayName type if provided. + if (typeof request.displayName !== 'undefined' && + !validator.isNonEmptyString(request.displayName)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, `"${label}.displayName" must be a valid non-empty string.`); + } + // Validate emailSignInConfig type if provided. + if (typeof request.emailSignInConfig !== 'undefined') { + // This will throw an error if invalid. + auth_config_1.EmailSignInConfig.buildServerRequest(request.emailSignInConfig); + } + // Validate test phone numbers if provided. + if (typeof request.testPhoneNumbers !== 'undefined' && + request.testPhoneNumbers !== null) { + (0, auth_config_1.validateTestPhoneNumbers)(request.testPhoneNumbers); + } + else if (request.testPhoneNumbers === null && createRequest) { + // null allowed only for update operations. + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, `"${label}.testPhoneNumbers" must be a non-null object.`); + } + // Validate multiFactorConfig type if provided. + if (typeof request.multiFactorConfig !== 'undefined') { + // This will throw an error if invalid. + auth_config_1.MultiFactorAuthConfig.buildServerRequest(request.multiFactorConfig); + } + // Validate SMS Regions Config if provided. + if (typeof request.smsRegionConfig !== 'undefined') { + auth_config_1.SmsRegionsAuthConfig.validate(request.smsRegionConfig); + } + // Validate reCAPTCHAConfig type if provided. + if (typeof request.recaptchaConfig !== 'undefined') { + auth_config_1.RecaptchaAuthConfig.buildServerRequest(request.recaptchaConfig); + } + // Validate passwordPolicyConfig type if provided. + if (typeof request.passwordPolicyConfig !== 'undefined') { + // This will throw an error if invalid. + auth_config_1.PasswordPolicyAuthConfig.buildServerRequest(request.passwordPolicyConfig); + } + // Validate Email Privacy Config if provided. + if (typeof request.emailPrivacyConfig !== 'undefined') { + auth_config_1.EmailPrivacyAuthConfig.validate(request.emailPrivacyConfig); + } + } + /** + * The Tenant object constructor. + * + * @param response - The server side response used to initialize the Tenant object. + * @constructor + * @internal + */ + constructor(response) { + const tenantId = Tenant.getTenantIdFromResourceName(response.name); + if (!tenantId) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid tenant response'); + } + this.tenantId = tenantId; + this.displayName = response.displayName; + try { + this.emailSignInConfig_ = new auth_config_1.EmailSignInConfig(response); + } + catch (e) { + // If allowPasswordSignup is undefined, it is disabled by default. + this.emailSignInConfig_ = new auth_config_1.EmailSignInConfig({ + allowPasswordSignup: false, + }); + } + this.anonymousSignInEnabled = !!response.enableAnonymousUser; + if (typeof response.mfaConfig !== 'undefined') { + this.multiFactorConfig_ = new auth_config_1.MultiFactorAuthConfig(response.mfaConfig); + } + if (typeof response.testPhoneNumbers !== 'undefined') { + this.testPhoneNumbers = (0, deep_copy_1.deepCopy)(response.testPhoneNumbers || {}); + } + if (typeof response.smsRegionConfig !== 'undefined') { + this.smsRegionConfig = (0, deep_copy_1.deepCopy)(response.smsRegionConfig); + } + if (typeof response.recaptchaConfig !== 'undefined') { + this.recaptchaConfig_ = new auth_config_1.RecaptchaAuthConfig(response.recaptchaConfig); + } + if (typeof response.passwordPolicyConfig !== 'undefined') { + this.passwordPolicyConfig = new auth_config_1.PasswordPolicyAuthConfig(response.passwordPolicyConfig); + } + if (typeof response.emailPrivacyConfig !== 'undefined') { + this.emailPrivacyConfig = (0, deep_copy_1.deepCopy)(response.emailPrivacyConfig); + } + } + /** + * The email sign in provider configuration. + */ + get emailSignInConfig() { + return this.emailSignInConfig_; + } + /** + * The multi-factor auth configuration on the current tenant. + */ + get multiFactorConfig() { + return this.multiFactorConfig_; + } + /** + * The recaptcha config auth configuration of the current tenant. + */ + get recaptchaConfig() { + return this.recaptchaConfig_; + } + /** + * Returns a JSON-serializable representation of this object. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON() { + const json = { + tenantId: this.tenantId, + displayName: this.displayName, + emailSignInConfig: this.emailSignInConfig_?.toJSON(), + multiFactorConfig: this.multiFactorConfig_?.toJSON(), + anonymousSignInEnabled: this.anonymousSignInEnabled, + testPhoneNumbers: this.testPhoneNumbers, + smsRegionConfig: (0, deep_copy_1.deepCopy)(this.smsRegionConfig), + recaptchaConfig: (0, deep_copy_1.deepCopy)(this.recaptchaConfig), + passwordPolicyConfig: (0, deep_copy_1.deepCopy)(this.passwordPolicyConfig), + emailPrivacyConfig: (0, deep_copy_1.deepCopy)(this.emailPrivacyConfig), + }; + if (typeof json.multiFactorConfig === 'undefined') { + delete json.multiFactorConfig; + } + if (typeof json.testPhoneNumbers === 'undefined') { + delete json.testPhoneNumbers; + } + if (typeof json.smsRegionConfig === 'undefined') { + delete json.smsRegionConfig; + } + if (typeof json.recaptchaConfig === 'undefined') { + delete json.recaptchaConfig; + } + if (typeof json.passwordPolicyConfig === 'undefined') { + delete json.passwordPolicyConfig; + } + if (typeof json.emailPrivacyConfig === 'undefined') { + delete json.emailPrivacyConfig; + } + return json; + } +} +exports.Tenant = Tenant; diff --git a/node_modules/firebase-admin/lib/auth/token-generator.d.ts b/node_modules/firebase-admin/lib/auth/token-generator.d.ts new file mode 100644 index 0000000..33ecc46 --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/token-generator.d.ts @@ -0,0 +1,43 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CryptoSigner } from '../utils/crypto-signer'; +import { Algorithm } from 'jsonwebtoken'; +export declare const BLACKLISTED_CLAIMS: string[]; +/** + * A CryptoSigner implementation that is used when communicating with the Auth emulator. + * It produces unsigned tokens. + */ +export declare class EmulatedSigner implements CryptoSigner { + algorithm: Algorithm; + /** + * @inheritDoc + */ + sign(buffer: Buffer): Promise; + /** + * @inheritDoc + */ + getAccountId(): Promise; +} +/** + * Creates a new FirebaseAuthError by extracting the error code, message and other relevant + * details from a CryptoSignerError. + * + * @param err - The Error to convert into a FirebaseAuthError error + * @returns A Firebase Auth error that can be returned to the user. + */ +export declare function handleCryptoSignerError(err: Error): Error; diff --git a/node_modules/firebase-admin/lib/auth/token-generator.js b/node_modules/firebase-admin/lib/auth/token-generator.js new file mode 100644 index 0000000..63847e5 --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/token-generator.js @@ -0,0 +1,198 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirebaseTokenGenerator = exports.EmulatedSigner = exports.BLACKLISTED_CLAIMS = void 0; +exports.handleCryptoSignerError = handleCryptoSignerError; +const error_1 = require("../utils/error"); +const crypto_signer_1 = require("../utils/crypto-signer"); +const validator = require("../utils/validator"); +const utils_1 = require("../utils"); +const ALGORITHM_NONE = 'none'; +const ONE_HOUR_IN_SECONDS = 60 * 60; +// List of blacklisted claims which cannot be provided when creating a custom token +exports.BLACKLISTED_CLAIMS = [ + 'acr', 'amr', 'at_hash', 'aud', 'auth_time', 'azp', 'cnf', 'c_hash', 'exp', 'iat', 'iss', 'jti', + 'nbf', 'nonce', +]; +// Audience to use for Firebase Auth Custom tokens +const FIREBASE_AUDIENCE = 'https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit'; +/** + * A CryptoSigner implementation that is used when communicating with the Auth emulator. + * It produces unsigned tokens. + */ +class EmulatedSigner { + constructor() { + this.algorithm = ALGORITHM_NONE; + } + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + sign(buffer) { + return Promise.resolve(Buffer.from('')); + } + /** + * @inheritDoc + */ + getAccountId() { + return Promise.resolve('firebase-auth-emulator@example.com'); + } +} +exports.EmulatedSigner = EmulatedSigner; +/** + * Class for generating different types of Firebase Auth tokens (JWTs). + * + * @internal + */ +class FirebaseTokenGenerator { + /** + * @param tenantId - The tenant ID to use for the generated Firebase Auth + * Custom token. If absent, then no tenant ID claim will be set in the + * resulting JWT. + */ + constructor(signer, tenantId) { + this.tenantId = tenantId; + if (!validator.isNonNullObject(signer)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CREDENTIAL, 'INTERNAL ASSERT: Must provide a CryptoSigner to use FirebaseTokenGenerator.'); + } + if (typeof this.tenantId !== 'undefined' && !validator.isNonEmptyString(this.tenantId)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '`tenantId` argument must be a non-empty string.'); + } + this.signer = signer; + } + /** + * Creates a new Firebase Auth Custom token. + * + * @param uid - The user ID to use for the generated Firebase Auth Custom token. + * @param developerClaims - Optional developer claims to include in the generated Firebase + * Auth Custom token. + * @returns A Promise fulfilled with a Firebase Auth Custom token signed with a + * service account key and containing the provided payload. + */ + createCustomToken(uid, developerClaims) { + let errorMessage; + if (!validator.isNonEmptyString(uid)) { + errorMessage = '`uid` argument must be a non-empty string uid.'; + } + else if (uid.length > 128) { + errorMessage = '`uid` argument must a uid with less than or equal to 128 characters.'; + } + else if (!this.isDeveloperClaimsValid_(developerClaims)) { + errorMessage = '`developerClaims` argument must be a valid, non-null object containing the developer claims.'; + } + if (errorMessage) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, errorMessage); + } + const claims = {}; + if (typeof developerClaims !== 'undefined') { + for (const key in developerClaims) { + /* istanbul ignore else */ + if (Object.prototype.hasOwnProperty.call(developerClaims, key)) { + if (exports.BLACKLISTED_CLAIMS.indexOf(key) !== -1) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, `Developer claim "${key}" is reserved and cannot be specified.`); + } + claims[key] = developerClaims[key]; + } + } + } + return this.signer.getAccountId().then((account) => { + const header = { + alg: this.signer.algorithm, + typ: 'JWT', + }; + const iat = Math.floor(Date.now() / 1000); + const body = { + aud: FIREBASE_AUDIENCE, + iat, + exp: iat + ONE_HOUR_IN_SECONDS, + iss: account, + sub: account, + uid, + }; + if (this.tenantId) { + body.tenant_id = this.tenantId; + } + if (Object.keys(claims).length > 0) { + body.claims = claims; + } + const token = `${this.encodeSegment(header)}.${this.encodeSegment(body)}`; + const signPromise = this.signer.sign(Buffer.from(token)); + return Promise.all([token, signPromise]); + }).then(([token, signature]) => { + return `${token}.${this.encodeSegment(signature)}`; + }).catch((err) => { + throw handleCryptoSignerError(err); + }); + } + encodeSegment(segment) { + const buffer = (segment instanceof Buffer) ? segment : Buffer.from(JSON.stringify(segment)); + return (0, utils_1.toWebSafeBase64)(buffer).replace(/=+$/, ''); + } + /** + * Returns whether or not the provided developer claims are valid. + * + * @param developerClaims - Optional developer claims to validate. + * @returns True if the provided claims are valid; otherwise, false. + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + isDeveloperClaimsValid_(developerClaims) { + if (typeof developerClaims === 'undefined') { + return true; + } + return validator.isNonNullObject(developerClaims); + } +} +exports.FirebaseTokenGenerator = FirebaseTokenGenerator; +/** + * Creates a new FirebaseAuthError by extracting the error code, message and other relevant + * details from a CryptoSignerError. + * + * @param err - The Error to convert into a FirebaseAuthError error + * @returns A Firebase Auth error that can be returned to the user. + */ +function handleCryptoSignerError(err) { + if (!(err instanceof crypto_signer_1.CryptoSignerError)) { + return err; + } + if (err.code === crypto_signer_1.CryptoSignerErrorCode.SERVER_ERROR && validator.isNonNullObject(err.cause)) { + const httpError = err.cause; + const errorResponse = httpError.response.data; + if (validator.isNonNullObject(errorResponse) && errorResponse.error) { + const errorCode = errorResponse.error.status; + const description = 'Please refer to https://firebase.google.com/docs/auth/admin/create-custom-tokens ' + + 'for more details on how to use and troubleshoot this feature.'; + const errorMsg = `${errorResponse.error.message}; ${description}`; + return error_1.FirebaseAuthError.fromServerError(errorCode, errorMsg, errorResponse); + } + return new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'Error returned from server: ' + errorResponse + '. Additionally, an ' + + 'internal error occurred while attempting to extract the ' + + 'errorcode from the error.'); + } + return new error_1.FirebaseAuthError(mapToAuthClientErrorCode(err.code), err.message); +} +function mapToAuthClientErrorCode(code) { + switch (code) { + case crypto_signer_1.CryptoSignerErrorCode.INVALID_CREDENTIAL: + return error_1.AuthClientErrorCode.INVALID_CREDENTIAL; + case crypto_signer_1.CryptoSignerErrorCode.INVALID_ARGUMENT: + return error_1.AuthClientErrorCode.INVALID_ARGUMENT; + default: + return error_1.AuthClientErrorCode.INTERNAL_ERROR; + } +} diff --git a/node_modules/firebase-admin/lib/auth/token-verifier.d.ts b/node_modules/firebase-admin/lib/auth/token-verifier.d.ts new file mode 100644 index 0000000..e7e3720 --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/token-verifier.d.ts @@ -0,0 +1,219 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Interface representing a decoded Firebase ID token, returned from the + * {@link BaseAuth.verifyIdToken} method. + * + * Firebase ID tokens are OpenID Connect spec-compliant JSON Web Tokens (JWTs). + * See the + * [ID Token section of the OpenID Connect spec](http://openid.net/specs/openid-connect-core-1_0.html#IDToken) + * for more information about the specific properties below. + */ +export interface DecodedIdToken { + /** + * The audience for which this token is intended. + * + * This value is a string equal to your Firebase project ID, the unique + * identifier for your Firebase project, which can be found in [your project's + * settings](https://console.firebase.google.com/project/_/settings/general/android:com.random.android). + */ + aud: string; + /** + * Time, in seconds since the Unix epoch, when the end-user authentication + * occurred. + * + * This value is not set when this particular ID token was created, but when the + * user initially logged in to this session. In a single session, the Firebase + * SDKs will refresh a user's ID tokens every hour. Each ID token will have a + * different [`iat`](#iat) value, but the same `auth_time` value. + */ + auth_time: number; + /** + * The email of the user to whom the ID token belongs, if available. + */ + email?: string; + /** + * Whether or not the email of the user to whom the ID token belongs is + * verified, provided the user has an email. + */ + email_verified?: boolean; + /** + * The ID token's expiration time, in seconds since the Unix epoch. That is, the + * time at which this ID token expires and should no longer be considered valid. + * + * The Firebase SDKs transparently refresh ID tokens every hour, issuing a new + * ID token with up to a one hour expiration. + */ + exp: number; + /** + * Information about the sign in event, including which sign in provider was + * used and provider-specific identity details. + * + * This data is provided by the Firebase Authentication service and is a + * reserved claim in the ID token. + */ + firebase: { + /** + * Provider-specific identity details corresponding + * to the provider used to sign in the user. + */ + identities: { + [key: string]: any; + }; + /** + * The ID of the provider used to sign in the user. + * One of `"anonymous"`, `"password"`, `"facebook.com"`, `"github.com"`, + * `"google.com"`, `"twitter.com"`, `"apple.com"`, `"microsoft.com"`, + * `"yahoo.com"`, `"phone"`, `"playgames.google.com"`, `"gc.apple.com"`, + * or `"custom"`. + * + * Additional Identity Platform provider IDs include `"linkedin.com"`, + * OIDC and SAML identity providers prefixed with `"saml."` and `"oidc."` + * respectively. + */ + sign_in_provider: string; + /** + * The type identifier or `factorId` of the second factor, provided the + * ID token was obtained from a multi-factor authenticated user. + * For phone, this is `"phone"`. + */ + sign_in_second_factor?: string; + /** + * The `uid` of the second factor used to sign in, provided the + * ID token was obtained from a multi-factor authenticated user. + */ + second_factor_identifier?: string; + /** + * The ID of the tenant the user belongs to, if available. + */ + tenant?: string; + [key: string]: any; + }; + /** + * The ID token's issued-at time, in seconds since the Unix epoch. That is, the + * time at which this ID token was issued and should start to be considered + * valid. + * + * The Firebase SDKs transparently refresh ID tokens every hour, issuing a new + * ID token with a new issued-at time. If you want to get the time at which the + * user session corresponding to the ID token initially occurred, see the + * [`auth_time`](#auth_time) property. + */ + iat: number; + /** + * The issuer identifier for the issuer of the response. + * + * This value is a URL with the format + * `https://securetoken.google.com/`, where `` is the + * same project ID specified in the [`aud`](#aud) property. + */ + iss: string; + /** + * The phone number of the user to whom the ID token belongs, if available. + */ + phone_number?: string; + /** + * The photo URL for the user to whom the ID token belongs, if available. + */ + picture?: string; + /** + * The `uid` corresponding to the user who the ID token belonged to. + * + * As a convenience, this value is copied over to the [`uid`](#uid) property. + */ + sub: string; + /** + * The `uid` corresponding to the user who the ID token belonged to. + * + * This value is not actually in the JWT token claims itself. It is added as a + * convenience, and is set as the value of the [`sub`](#sub) property. + */ + uid: string; + /** + * Other arbitrary claims included in the ID token. + */ + [key: string]: any; +} +/** @alpha */ +export interface DecodedAuthBlockingSharedUserInfo { + uid: string; + display_name?: string; + email?: string; + photo_url?: string; + phone_number?: string; +} +/** @alpha */ +export interface DecodedAuthBlockingMetadata { + creation_time?: number; + last_sign_in_time?: number; +} +/** @alpha */ +export interface DecodedAuthBlockingUserInfo extends DecodedAuthBlockingSharedUserInfo { + provider_id: string; +} +/** @alpha */ +export interface DecodedAuthBlockingMfaInfo { + uid: string; + display_name?: string; + phone_number?: string; + enrollment_time?: string; + factor_id?: string; +} +/** @alpha */ +export interface DecodedAuthBlockingEnrolledFactors { + enrolled_factors?: DecodedAuthBlockingMfaInfo[]; +} +/** @alpha */ +export interface DecodedAuthBlockingUserRecord extends DecodedAuthBlockingSharedUserInfo { + email_verified?: boolean; + disabled?: boolean; + metadata?: DecodedAuthBlockingMetadata; + password_hash?: string; + password_salt?: string; + provider_data?: DecodedAuthBlockingUserInfo[]; + multi_factor?: DecodedAuthBlockingEnrolledFactors; + custom_claims?: any; + tokens_valid_after_time?: number; + tenant_id?: string; + [key: string]: any; +} +/** @alpha */ +export interface DecodedAuthBlockingToken { + aud: string; + exp: number; + iat: number; + iss: string; + sub: string; + event_id: string; + event_type: string; + ip_address: string; + user_agent?: string; + locale?: string; + sign_in_method?: string; + user_record?: DecodedAuthBlockingUserRecord; + tenant_id?: string; + raw_user_info?: string; + sign_in_attributes?: { + [key: string]: any; + }; + oauth_id_token?: string; + oauth_access_token?: string; + oauth_refresh_token?: string; + oauth_token_secret?: string; + oauth_expires_in?: number; + [key: string]: any; +} diff --git a/node_modules/firebase-admin/lib/auth/token-verifier.js b/node_modules/firebase-admin/lib/auth/token-verifier.js new file mode 100644 index 0000000..1716fd6 --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/token-verifier.js @@ -0,0 +1,316 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirebaseTokenVerifier = exports.SESSION_COOKIE_INFO = exports.AUTH_BLOCKING_TOKEN_INFO = exports.ID_TOKEN_INFO = void 0; +exports.createIdTokenVerifier = createIdTokenVerifier; +exports.createAuthBlockingTokenVerifier = createAuthBlockingTokenVerifier; +exports.createSessionCookieVerifier = createSessionCookieVerifier; +const error_1 = require("../utils/error"); +const util = require("../utils/index"); +const validator = require("../utils/validator"); +const jwt_1 = require("../utils/jwt"); +// Audience to use for Firebase Auth Custom tokens +const FIREBASE_AUDIENCE = 'https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit'; +// URL containing the public keys for the Google certs (whose private keys are used to sign Firebase +// Auth ID tokens) +const CLIENT_CERT_URL = 'https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com'; +// URL containing the public keys for Firebase session cookies. This will be updated to a different URL soon. +const SESSION_COOKIE_CERT_URL = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/publicKeys'; +const EMULATOR_VERIFIER = new jwt_1.EmulatorSignatureVerifier(); +/** + * User facing token information related to the Firebase ID token. + * + * @internal + */ +exports.ID_TOKEN_INFO = { + url: 'https://firebase.google.com/docs/auth/admin/verify-id-tokens', + verifyApiName: 'verifyIdToken()', + jwtName: 'Firebase ID token', + shortName: 'ID token', + expiredErrorCode: error_1.AuthClientErrorCode.ID_TOKEN_EXPIRED, +}; +/** + * User facing token information related to the Firebase Auth Blocking token. + * + * @internal + */ +exports.AUTH_BLOCKING_TOKEN_INFO = { + url: 'https://cloud.google.com/identity-platform/docs/blocking-functions', + verifyApiName: '_verifyAuthBlockingToken()', + jwtName: 'Firebase Auth Blocking token', + shortName: 'Auth Blocking token', + expiredErrorCode: error_1.AuthClientErrorCode.AUTH_BLOCKING_TOKEN_EXPIRED, +}; +/** + * User facing token information related to the Firebase session cookie. + * + * @internal + */ +exports.SESSION_COOKIE_INFO = { + url: 'https://firebase.google.com/docs/auth/admin/manage-cookies', + verifyApiName: 'verifySessionCookie()', + jwtName: 'Firebase session cookie', + shortName: 'session cookie', + expiredErrorCode: error_1.AuthClientErrorCode.SESSION_COOKIE_EXPIRED, +}; +/** + * Class for verifying general purpose Firebase JWTs. This verifies ID tokens and session cookies. + * + * @internal + */ +class FirebaseTokenVerifier { + constructor(clientCertUrl, issuer, tokenInfo, app) { + this.issuer = issuer; + this.tokenInfo = tokenInfo; + this.app = app; + if (!validator.isURL(clientCertUrl)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'The provided public client certificate URL is an invalid URL.'); + } + else if (!validator.isURL(issuer)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'The provided JWT issuer is an invalid URL.'); + } + else if (!validator.isNonNullObject(tokenInfo)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'The provided JWT information is not an object or null.'); + } + else if (!validator.isURL(tokenInfo.url)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'The provided JWT verification documentation URL is invalid.'); + } + else if (!validator.isNonEmptyString(tokenInfo.verifyApiName)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'The JWT verify API name must be a non-empty string.'); + } + else if (!validator.isNonEmptyString(tokenInfo.jwtName)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'The JWT public full name must be a non-empty string.'); + } + else if (!validator.isNonEmptyString(tokenInfo.shortName)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'The JWT public short name must be a non-empty string.'); + } + else if (!validator.isNonNullObject(tokenInfo.expiredErrorCode) || !('code' in tokenInfo.expiredErrorCode)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'The JWT expiration error code must be a non-null ErrorInfo object.'); + } + this.shortNameArticle = tokenInfo.shortName.charAt(0).match(/[aeiou]/i) ? 'an' : 'a'; + this.signatureVerifier = + jwt_1.PublicKeySignatureVerifier.withCertificateUrl(clientCertUrl, app.options.httpAgent); + // For backward compatibility, the project ID is validated in the verification call. + } + /** + * Verifies the format and signature of a Firebase Auth JWT token. + * + * @param jwtToken - The Firebase Auth JWT token to verify. + * @param isEmulator - Whether to accept Auth Emulator tokens. + * @returns A promise fulfilled with the decoded claims of the Firebase Auth ID token. + */ + verifyJWT(jwtToken, isEmulator = false) { + if (!validator.isString(jwtToken)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, `First argument to ${this.tokenInfo.verifyApiName} must be a ${this.tokenInfo.jwtName} string.`); + } + return this.ensureProjectId() + .then((projectId) => { + return this.decodeAndVerify(jwtToken, projectId, isEmulator); + }) + .then((decoded) => { + const decodedIdToken = decoded.payload; + decodedIdToken.uid = decodedIdToken.sub; + return decodedIdToken; + }); + } + /** @alpha */ + // eslint-disable-next-line @typescript-eslint/naming-convention + _verifyAuthBlockingToken(jwtToken, isEmulator, audience) { + if (!validator.isString(jwtToken)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, `First argument to ${this.tokenInfo.verifyApiName} must be a ${this.tokenInfo.jwtName} string.`); + } + return this.ensureProjectId() + .then((projectId) => { + if (typeof audience === 'undefined') { + audience = `${projectId}.cloudfunctions.net/`; + } + return this.decodeAndVerify(jwtToken, projectId, isEmulator, audience); + }) + .then((decoded) => { + const decodedAuthBlockingToken = decoded.payload; + decodedAuthBlockingToken.uid = decodedAuthBlockingToken.sub; + return decodedAuthBlockingToken; + }); + } + ensureProjectId() { + return util.findProjectId(this.app) + .then((projectId) => { + if (!validator.isNonEmptyString(projectId)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CREDENTIAL, 'Must initialize app with a cert credential or set your Firebase project ID as the ' + + `GOOGLE_CLOUD_PROJECT environment variable to call ${this.tokenInfo.verifyApiName}.`); + } + return Promise.resolve(projectId); + }); + } + decodeAndVerify(token, projectId, isEmulator, audience) { + return this.safeDecode(token) + .then((decodedToken) => { + this.verifyContent(decodedToken, projectId, isEmulator, audience); + return this.verifySignature(token, isEmulator) + .then(() => decodedToken); + }); + } + safeDecode(jwtToken) { + return (0, jwt_1.decodeJwt)(jwtToken) + .catch((err) => { + if (err.code === jwt_1.JwtErrorCode.INVALID_ARGUMENT) { + const verifyJwtTokenDocsMessage = ` See ${this.tokenInfo.url} ` + + `for details on how to retrieve ${this.shortNameArticle} ${this.tokenInfo.shortName}.`; + const errorMessage = `Decoding ${this.tokenInfo.jwtName} failed. Make sure you passed ` + + `the entire string JWT which represents ${this.shortNameArticle} ` + + `${this.tokenInfo.shortName}.` + verifyJwtTokenDocsMessage; + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, errorMessage); + } + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, err.message); + }); + } + /** + * Verifies the content of a Firebase Auth JWT. + * + * @param fullDecodedToken - The decoded JWT. + * @param projectId - The Firebase Project Id. + * @param isEmulator - Whether the token is an Emulator token. + */ + verifyContent(fullDecodedToken, projectId, isEmulator, audience) { + const header = fullDecodedToken && fullDecodedToken.header; + const payload = fullDecodedToken && fullDecodedToken.payload; + const projectIdMatchMessage = ` Make sure the ${this.tokenInfo.shortName} comes from the same ` + + 'Firebase project as the service account used to authenticate this SDK.'; + const verifyJwtTokenDocsMessage = ` See ${this.tokenInfo.url} ` + + `for details on how to retrieve ${this.shortNameArticle} ${this.tokenInfo.shortName}.`; + let errorMessage; + if (!isEmulator && typeof header.kid === 'undefined') { + const isCustomToken = (payload.aud === FIREBASE_AUDIENCE); + const isLegacyCustomToken = (header.alg === 'HS256' && payload.v === 0 && 'd' in payload && 'uid' in payload.d); + if (isCustomToken) { + errorMessage = `${this.tokenInfo.verifyApiName} expects ${this.shortNameArticle} ` + + `${this.tokenInfo.shortName}, but was given a custom token.`; + } + else if (isLegacyCustomToken) { + errorMessage = `${this.tokenInfo.verifyApiName} expects ${this.shortNameArticle} ` + + `${this.tokenInfo.shortName}, but was given a legacy custom token.`; + } + else { + errorMessage = `${this.tokenInfo.jwtName} has no "kid" claim.`; + } + errorMessage += verifyJwtTokenDocsMessage; + } + else if (!isEmulator && header.alg !== jwt_1.ALGORITHM_RS256) { + errorMessage = `${this.tokenInfo.jwtName} has incorrect algorithm. Expected "` + jwt_1.ALGORITHM_RS256 + '" but got ' + + '"' + header.alg + '".' + verifyJwtTokenDocsMessage; + } + else if (typeof audience !== 'undefined' && !payload.aud.includes(audience)) { + errorMessage = `${this.tokenInfo.jwtName} has incorrect "aud" (audience) claim. Expected "` + + audience + '" but got "' + payload.aud + '".' + verifyJwtTokenDocsMessage; + } + else if (typeof audience === 'undefined' && payload.aud !== projectId) { + errorMessage = `${this.tokenInfo.jwtName} has incorrect "aud" (audience) claim. Expected "` + + projectId + '" but got "' + payload.aud + '".' + projectIdMatchMessage + + verifyJwtTokenDocsMessage; + } + else if (payload.iss !== this.issuer + projectId) { + errorMessage = `${this.tokenInfo.jwtName} has incorrect "iss" (issuer) claim. Expected ` + + `"${this.issuer}` + projectId + '" but got "' + + payload.iss + '".' + projectIdMatchMessage + verifyJwtTokenDocsMessage; + } + else if (!(payload.event_type !== undefined && + (payload.event_type === 'beforeSendSms' || payload.event_type === 'beforeSendEmail'))) { + // excluding `beforeSendSms` and `beforeSendEmail` from processing `sub` as there is no user record available. + // `sub` is the same as `uid` which is part of the user record. + if (typeof payload.sub !== 'string') { + errorMessage = `${this.tokenInfo.jwtName} has no "sub" (subject) claim.` + verifyJwtTokenDocsMessage; + } + else if (payload.sub === '') { + errorMessage = `${this.tokenInfo.jwtName} has an empty "sub" (subject) claim.` + + verifyJwtTokenDocsMessage; + } + else if (payload.sub.length > 128) { + errorMessage = `${this.tokenInfo.jwtName} has a "sub" (subject) claim longer than 128 characters.` + + verifyJwtTokenDocsMessage; + } + } + if (errorMessage) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, errorMessage); + } + } + verifySignature(jwtToken, isEmulator) { + const verifier = isEmulator ? EMULATOR_VERIFIER : this.signatureVerifier; + return verifier.verify(jwtToken) + .catch((error) => { + throw this.mapJwtErrorToAuthError(error); + }); + } + /** + * Maps JwtError to FirebaseAuthError + * + * @param error - JwtError to be mapped. + * @returns FirebaseAuthError or Error instance. + */ + mapJwtErrorToAuthError(error) { + const verifyJwtTokenDocsMessage = ` See ${this.tokenInfo.url} ` + + `for details on how to retrieve ${this.shortNameArticle} ${this.tokenInfo.shortName}.`; + if (error.code === jwt_1.JwtErrorCode.TOKEN_EXPIRED) { + const errorMessage = `${this.tokenInfo.jwtName} has expired. Get a fresh ${this.tokenInfo.shortName}` + + ` from your client app and try again (auth/${this.tokenInfo.expiredErrorCode.code}).` + + verifyJwtTokenDocsMessage; + return new error_1.FirebaseAuthError(this.tokenInfo.expiredErrorCode, errorMessage); + } + else if (error.code === jwt_1.JwtErrorCode.INVALID_SIGNATURE) { + const errorMessage = `${this.tokenInfo.jwtName} has invalid signature.` + verifyJwtTokenDocsMessage; + return new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, errorMessage); + } + else if (error.code === jwt_1.JwtErrorCode.NO_MATCHING_KID) { + const errorMessage = `${this.tokenInfo.jwtName} has "kid" claim which does not ` + + `correspond to a known public key. Most likely the ${this.tokenInfo.shortName} ` + + 'is expired, so get a fresh token from your client app and try again.'; + return new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, errorMessage); + } + return new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, error.message); + } +} +exports.FirebaseTokenVerifier = FirebaseTokenVerifier; +/** + * Creates a new FirebaseTokenVerifier to verify Firebase ID tokens. + * + * @internal + * @param app - Firebase app instance. + * @returns FirebaseTokenVerifier + */ +function createIdTokenVerifier(app) { + return new FirebaseTokenVerifier(CLIENT_CERT_URL, 'https://securetoken.google.com/', exports.ID_TOKEN_INFO, app); +} +/** + * Creates a new FirebaseTokenVerifier to verify Firebase Auth Blocking tokens. + * + * @internal + * @param app - Firebase app instance. + * @returns FirebaseTokenVerifier + */ +function createAuthBlockingTokenVerifier(app) { + return new FirebaseTokenVerifier(CLIENT_CERT_URL, 'https://securetoken.google.com/', exports.AUTH_BLOCKING_TOKEN_INFO, app); +} +/** + * Creates a new FirebaseTokenVerifier to verify Firebase session cookies. + * + * @internal + * @param app - Firebase app instance. + * @returns FirebaseTokenVerifier + */ +function createSessionCookieVerifier(app) { + return new FirebaseTokenVerifier(SESSION_COOKIE_CERT_URL, 'https://session.firebase.google.com/', exports.SESSION_COOKIE_INFO, app); +} diff --git a/node_modules/firebase-admin/lib/auth/user-import-builder.d.ts b/node_modules/firebase-admin/lib/auth/user-import-builder.d.ts new file mode 100644 index 0000000..0f3af2f --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/user-import-builder.d.ts @@ -0,0 +1,321 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseArrayIndexError } from '../app/index'; +import { UpdateMultiFactorInfoRequest, MultiFactorUpdateSettings } from './auth-config'; +export type HashAlgorithmType = 'SCRYPT' | 'STANDARD_SCRYPT' | 'HMAC_SHA512' | 'HMAC_SHA256' | 'HMAC_SHA1' | 'HMAC_MD5' | 'MD5' | 'PBKDF_SHA1' | 'BCRYPT' | 'PBKDF2_SHA256' | 'SHA512' | 'SHA256' | 'SHA1'; +/** + * Interface representing the user import options needed for + * {@link BaseAuth.importUsers} method. This is used to + * provide the password hashing algorithm information. + */ +export interface UserImportOptions { + /** + * The password hashing information. + */ + hash: { + /** + * The password hashing algorithm identifier. The following algorithm + * identifiers are supported: + * `SCRYPT`, `STANDARD_SCRYPT`, `HMAC_SHA512`, `HMAC_SHA256`, `HMAC_SHA1`, + * `HMAC_MD5`, `MD5`, `PBKDF_SHA1`, `BCRYPT`, `PBKDF2_SHA256`, `SHA512`, + * `SHA256` and `SHA1`. + */ + algorithm: HashAlgorithmType; + /** + * The signing key used in the hash algorithm in buffer bytes. + * Required by hashing algorithms `SCRYPT`, `HMAC_SHA512`, `HMAC_SHA256`, + * `HAMC_SHA1` and `HMAC_MD5`. + */ + key?: Buffer; + /** + * The salt separator in buffer bytes which is appended to salt when + * verifying a password. This is only used by the `SCRYPT` algorithm. + */ + saltSeparator?: Buffer; + /** + * The number of rounds for hashing calculation. + * Required for `SCRYPT`, `MD5`, `SHA512`, `SHA256`, `SHA1`, `PBKDF_SHA1` and + * `PBKDF2_SHA256`. + */ + rounds?: number; + /** + * The memory cost required for `SCRYPT` algorithm, or the CPU/memory cost. + * Required for `STANDARD_SCRYPT` algorithm. + */ + memoryCost?: number; + /** + * The parallelization of the hashing algorithm. Required for the + * `STANDARD_SCRYPT` algorithm. + */ + parallelization?: number; + /** + * The block size (normally 8) of the hashing algorithm. Required for the + * `STANDARD_SCRYPT` algorithm. + */ + blockSize?: number; + /** + * The derived key length of the hashing algorithm. Required for the + * `STANDARD_SCRYPT` algorithm. + */ + derivedKeyLength?: number; + }; +} +/** + * Interface representing a user to import to Firebase Auth via the + * {@link BaseAuth.importUsers} method. + */ +export interface UserImportRecord { + /** + * The user's `uid`. + */ + uid: string; + /** + * The user's primary email, if set. + */ + email?: string; + /** + * Whether or not the user's primary email is verified. + */ + emailVerified?: boolean; + /** + * The user's display name. + */ + displayName?: string; + /** + * The user's primary phone number, if set. + */ + phoneNumber?: string; + /** + * The user's photo URL. + */ + photoURL?: string; + /** + * Whether or not the user is disabled: `true` for disabled; `false` for + * enabled. + */ + disabled?: boolean; + /** + * Additional metadata about the user. + */ + metadata?: UserMetadataRequest; + /** + * An array of providers (for example, Google, Facebook) linked to the user. + */ + providerData?: UserProviderRequest[]; + /** + * The user's custom claims object if available, typically used to define + * user roles and propagated to an authenticated user's ID token. + */ + customClaims?: { + [key: string]: any; + }; + /** + * The buffer of bytes representing the user's hashed password. + * When a user is to be imported with a password hash, + * {@link UserImportOptions} are required to be + * specified to identify the hashing algorithm used to generate this hash. + */ + passwordHash?: Buffer; + /** + * The buffer of bytes representing the user's password salt. + */ + passwordSalt?: Buffer; + /** + * The identifier of the tenant where user is to be imported to. + * When not provided in an `admin.auth.Auth` context, the user is uploaded to + * the default parent project. + * When not provided in an `admin.auth.TenantAwareAuth` context, the user is uploaded + * to the tenant corresponding to that `TenantAwareAuth` instance's tenant ID. + */ + tenantId?: string; + /** + * The user's multi-factor related properties. + */ + multiFactor?: MultiFactorUpdateSettings; +} +/** + * User metadata to include when importing a user. + */ +export interface UserMetadataRequest { + /** + * The date the user last signed in, formatted as a UTC string. + */ + lastSignInTime?: string; + /** + * The date the user was created, formatted as a UTC string. + */ + creationTime?: string; +} +/** + * User provider data to include when importing a user. + */ +export interface UserProviderRequest { + /** + * The user identifier for the linked provider. + */ + uid: string; + /** + * The display name for the linked provider. + */ + displayName?: string; + /** + * The email for the linked provider. + */ + email?: string; + /** + * The phone number for the linked provider. + */ + phoneNumber?: string; + /** + * The photo URL for the linked provider. + */ + photoURL?: string; + /** + * The linked provider ID (for example, "google.com" for the Google provider). + */ + providerId: string; +} +/** + * Interface representing the response from the + * {@link BaseAuth.importUsers} method for batch + * importing users to Firebase Auth. + */ +export interface UserImportResult { + /** + * The number of user records that failed to import to Firebase Auth. + */ + failureCount: number; + /** + * The number of user records that successfully imported to Firebase Auth. + */ + successCount: number; + /** + * An array of errors corresponding to the provided users to import. The + * length of this array is equal to [`failureCount`](#failureCount). + */ + errors: FirebaseArrayIndexError[]; +} +/** Interface representing an Auth second factor in Auth server format. */ +export interface AuthFactorInfo { + mfaEnrollmentId?: string; + displayName?: string; + phoneInfo?: string; + enrolledAt?: string; + [key: string]: any; +} +/** UploadAccount endpoint request user interface. */ +interface UploadAccountUser { + localId: string; + email?: string; + emailVerified?: boolean; + displayName?: string; + disabled?: boolean; + photoUrl?: string; + phoneNumber?: string; + providerUserInfo?: Array<{ + rawId: string; + providerId: string; + email?: string; + displayName?: string; + photoUrl?: string; + }>; + mfaInfo?: AuthFactorInfo[]; + passwordHash?: string; + salt?: string; + lastLoginAt?: number; + createdAt?: number; + customAttributes?: string; + tenantId?: string; +} +/** UploadAccount endpoint request hash options. */ +export interface UploadAccountOptions { + hashAlgorithm?: string; + signerKey?: string; + rounds?: number; + memoryCost?: number; + saltSeparator?: string; + cpuMemCost?: number; + parallelization?: number; + blockSize?: number; + dkLen?: number; +} +/** UploadAccount endpoint complete request interface. */ +export interface UploadAccountRequest extends UploadAccountOptions { + users?: UploadAccountUser[]; +} +/** Callback function to validate an UploadAccountUser object. */ +export type ValidatorFunction = (data: UploadAccountUser) => void; +/** + * Converts a client format second factor object to server format. + * @param multiFactorInfo - The client format second factor. + * @returns The corresponding AuthFactorInfo server request format. + */ +export declare function convertMultiFactorInfoToServerFormat(multiFactorInfo: UpdateMultiFactorInfoRequest): AuthFactorInfo; +/** + * Class that provides a helper for building/validating uploadAccount requests and + * UserImportResult responses. + */ +export declare class UserImportBuilder { + private requiresHashOptions; + private validatedUsers; + private validatedOptions; + private indexMap; + private userImportResultErrors; + /** + * @param {UserImportRecord[]} users The list of user records to import. + * @param {UserImportOptions=} options The import options which includes hashing + * algorithm details. + * @param {ValidatorFunction=} userRequestValidator The user request validator function. + * @constructor + */ + constructor(users: UserImportRecord[], options?: UserImportOptions, userRequestValidator?: ValidatorFunction); + /** + * Returns the corresponding constructed uploadAccount request. + * @returns {UploadAccountRequest} The constructed uploadAccount request. + */ + buildRequest(): UploadAccountRequest; + /** + * Populates the UserImportResult using the client side detected errors and the server + * side returned errors. + * @returns {UserImportResult} The user import result based on the returned failed + * uploadAccount response. + */ + buildResponse(failedUploads: Array<{ + index: number; + message: string; + }>): UserImportResult; + /** + * Validates and returns the hashing options of the uploadAccount request. + * Throws an error whenever an invalid or missing options is detected. + * @param {UserImportOptions} options The UserImportOptions. + * @param {boolean} requiresHashOptions Whether to require hash options. + * @returns {UploadAccountOptions} The populated UploadAccount options. + */ + private populateOptions; + /** + * Validates and returns the users list of the uploadAccount request. + * Whenever a user with an error is detected, the error is cached and will later be + * merged into the user import result. This allows the processing of valid users without + * failing early on the first error detected. + * @param {UserImportRecord[]} users The UserImportRecords to convert to UnploadAccountUser + * objects. + * @param {ValidatorFunction=} userValidator The user validator function. + * @returns {UploadAccountUser[]} The populated uploadAccount users. + */ + private populateUsers; +} +export {}; diff --git a/node_modules/firebase-admin/lib/auth/user-import-builder.js b/node_modules/firebase-admin/lib/auth/user-import-builder.js new file mode 100644 index 0000000..ed1ed2e --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/user-import-builder.js @@ -0,0 +1,384 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UserImportBuilder = void 0; +exports.convertMultiFactorInfoToServerFormat = convertMultiFactorInfoToServerFormat; +const deep_copy_1 = require("../utils/deep-copy"); +const utils = require("../utils"); +const validator = require("../utils/validator"); +const error_1 = require("../utils/error"); +/** + * Converts a client format second factor object to server format. + * @param multiFactorInfo - The client format second factor. + * @returns The corresponding AuthFactorInfo server request format. + */ +function convertMultiFactorInfoToServerFormat(multiFactorInfo) { + let enrolledAt; + if (typeof multiFactorInfo.enrollmentTime !== 'undefined') { + if (validator.isUTCDateString(multiFactorInfo.enrollmentTime)) { + // Convert from UTC date string (client side format) to ISO date string (server side format). + enrolledAt = new Date(multiFactorInfo.enrollmentTime).toISOString(); + } + else { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ENROLLMENT_TIME, `The second factor "enrollmentTime" for "${multiFactorInfo.uid}" must be a valid ` + + 'UTC date string.'); + } + } + // Currently only phone second factors are supported. + if (isPhoneFactor(multiFactorInfo)) { + // If any required field is missing or invalid, validation will still fail later. + const authFactorInfo = { + mfaEnrollmentId: multiFactorInfo.uid, + displayName: multiFactorInfo.displayName, + // Required for all phone second factors. + phoneInfo: multiFactorInfo.phoneNumber, + enrolledAt, + }; + for (const objKey in authFactorInfo) { + if (typeof authFactorInfo[objKey] === 'undefined') { + delete authFactorInfo[objKey]; + } + } + return authFactorInfo; + } + else { + // Unsupported second factor. + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.UNSUPPORTED_SECOND_FACTOR, `Unsupported second factor "${JSON.stringify(multiFactorInfo)}" provided.`); + } +} +function isPhoneFactor(multiFactorInfo) { + return multiFactorInfo.factorId === 'phone'; +} +/** + * @param {any} obj The object to check for number field within. + * @param {string} key The entry key. + * @returns {number} The corresponding number if available. Otherwise, NaN. + */ +function getNumberField(obj, key) { + if (typeof obj[key] !== 'undefined' && obj[key] !== null) { + return parseInt(obj[key].toString(), 10); + } + return NaN; +} +/** + * Converts a UserImportRecord to a UploadAccountUser object. Throws an error when invalid + * fields are provided. + * @param {UserImportRecord} user The UserImportRecord to conver to UploadAccountUser. + * @param {ValidatorFunction=} userValidator The user validator function. + * @returns {UploadAccountUser} The corresponding UploadAccountUser to return. + */ +function populateUploadAccountUser(user, userValidator) { + const result = { + localId: user.uid, + email: user.email, + emailVerified: user.emailVerified, + displayName: user.displayName, + disabled: user.disabled, + photoUrl: user.photoURL, + phoneNumber: user.phoneNumber, + providerUserInfo: [], + mfaInfo: [], + tenantId: user.tenantId, + customAttributes: user.customClaims && JSON.stringify(user.customClaims), + }; + if (typeof user.passwordHash !== 'undefined') { + if (!validator.isBuffer(user.passwordHash)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PASSWORD_HASH); + } + result.passwordHash = utils.toWebSafeBase64(user.passwordHash); + } + if (typeof user.passwordSalt !== 'undefined') { + if (!validator.isBuffer(user.passwordSalt)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PASSWORD_SALT); + } + result.salt = utils.toWebSafeBase64(user.passwordSalt); + } + if (validator.isNonNullObject(user.metadata)) { + if (validator.isNonEmptyString(user.metadata.creationTime)) { + result.createdAt = new Date(user.metadata.creationTime).getTime(); + } + if (validator.isNonEmptyString(user.metadata.lastSignInTime)) { + result.lastLoginAt = new Date(user.metadata.lastSignInTime).getTime(); + } + } + if (validator.isArray(user.providerData)) { + user.providerData.forEach((providerData) => { + result.providerUserInfo.push({ + providerId: providerData.providerId, + rawId: providerData.uid, + email: providerData.email, + displayName: providerData.displayName, + photoUrl: providerData.photoURL, + }); + }); + } + // Convert user.multiFactor.enrolledFactors to server format. + if (validator.isNonNullObject(user.multiFactor) && + validator.isNonEmptyArray(user.multiFactor.enrolledFactors)) { + user.multiFactor.enrolledFactors.forEach((multiFactorInfo) => { + result.mfaInfo.push(convertMultiFactorInfoToServerFormat(multiFactorInfo)); + }); + } + // Remove blank fields. + let key; + for (key in result) { + if (typeof result[key] === 'undefined') { + delete result[key]; + } + } + if (result.providerUserInfo.length === 0) { + delete result.providerUserInfo; + } + if (result.mfaInfo.length === 0) { + delete result.mfaInfo; + } + // Validate the constructured user individual request. This will throw if an error + // is detected. + if (typeof userValidator === 'function') { + userValidator(result); + } + return result; +} +/** + * Class that provides a helper for building/validating uploadAccount requests and + * UserImportResult responses. + */ +class UserImportBuilder { + /** + * @param {UserImportRecord[]} users The list of user records to import. + * @param {UserImportOptions=} options The import options which includes hashing + * algorithm details. + * @param {ValidatorFunction=} userRequestValidator The user request validator function. + * @constructor + */ + constructor(users, options, userRequestValidator) { + this.requiresHashOptions = false; + this.validatedUsers = []; + this.userImportResultErrors = []; + this.indexMap = {}; + this.validatedUsers = this.populateUsers(users, userRequestValidator); + this.validatedOptions = this.populateOptions(options, this.requiresHashOptions); + } + /** + * Returns the corresponding constructed uploadAccount request. + * @returns {UploadAccountRequest} The constructed uploadAccount request. + */ + buildRequest() { + const users = this.validatedUsers.map((user) => { + return (0, deep_copy_1.deepCopy)(user); + }); + return (0, deep_copy_1.deepExtend)({ users }, (0, deep_copy_1.deepCopy)(this.validatedOptions)); + } + /** + * Populates the UserImportResult using the client side detected errors and the server + * side returned errors. + * @returns {UserImportResult} The user import result based on the returned failed + * uploadAccount response. + */ + buildResponse(failedUploads) { + // Initialize user import result. + const importResult = { + successCount: this.validatedUsers.length, + failureCount: this.userImportResultErrors.length, + errors: (0, deep_copy_1.deepCopy)(this.userImportResultErrors), + }; + importResult.failureCount += failedUploads.length; + importResult.successCount -= failedUploads.length; + failedUploads.forEach((failedUpload) => { + importResult.errors.push({ + // Map backend request index to original developer provided array index. + index: this.indexMap[failedUpload.index], + error: new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_USER_IMPORT, failedUpload.message), + }); + }); + // Sort errors by index. + importResult.errors.sort((a, b) => { + return a.index - b.index; + }); + // Return sorted result. + return importResult; + } + /** + * Validates and returns the hashing options of the uploadAccount request. + * Throws an error whenever an invalid or missing options is detected. + * @param {UserImportOptions} options The UserImportOptions. + * @param {boolean} requiresHashOptions Whether to require hash options. + * @returns {UploadAccountOptions} The populated UploadAccount options. + */ + populateOptions(options, requiresHashOptions) { + let populatedOptions; + if (!requiresHashOptions) { + return {}; + } + if (!validator.isNonNullObject(options)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"UserImportOptions" are required when importing users with passwords.'); + } + if (!validator.isNonNullObject(options.hash)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISSING_HASH_ALGORITHM, '"hash.algorithm" is missing from the provided "UserImportOptions".'); + } + if (typeof options.hash.algorithm === 'undefined' || + !validator.isNonEmptyString(options.hash.algorithm)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_ALGORITHM, '"hash.algorithm" must be a string matching the list of supported algorithms.'); + } + let rounds; + switch (options.hash.algorithm) { + case 'HMAC_SHA512': + case 'HMAC_SHA256': + case 'HMAC_SHA1': + case 'HMAC_MD5': + if (!validator.isBuffer(options.hash.key)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_KEY, 'A non-empty "hash.key" byte buffer must be provided for ' + + `hash algorithm ${options.hash.algorithm}.`); + } + populatedOptions = { + hashAlgorithm: options.hash.algorithm, + signerKey: utils.toWebSafeBase64(options.hash.key), + }; + break; + case 'MD5': + case 'SHA1': + case 'SHA256': + case 'SHA512': { + // MD5 is [0,8192] but SHA1, SHA256, and SHA512 are [1,8192] + rounds = getNumberField(options.hash, 'rounds'); + const minRounds = options.hash.algorithm === 'MD5' ? 0 : 1; + if (isNaN(rounds) || rounds < minRounds || rounds > 8192) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_ROUNDS, `A valid "hash.rounds" number between ${minRounds} and 8192 must be provided for ` + + `hash algorithm ${options.hash.algorithm}.`); + } + populatedOptions = { + hashAlgorithm: options.hash.algorithm, + rounds, + }; + break; + } + case 'PBKDF_SHA1': + case 'PBKDF2_SHA256': + rounds = getNumberField(options.hash, 'rounds'); + if (isNaN(rounds) || rounds < 0 || rounds > 120000) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_ROUNDS, 'A valid "hash.rounds" number between 0 and 120000 must be provided for ' + + `hash algorithm ${options.hash.algorithm}.`); + } + populatedOptions = { + hashAlgorithm: options.hash.algorithm, + rounds, + }; + break; + case 'SCRYPT': { + if (!validator.isBuffer(options.hash.key)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_KEY, 'A "hash.key" byte buffer must be provided for ' + + `hash algorithm ${options.hash.algorithm}.`); + } + rounds = getNumberField(options.hash, 'rounds'); + if (isNaN(rounds) || rounds <= 0 || rounds > 8) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_ROUNDS, 'A valid "hash.rounds" number between 1 and 8 must be provided for ' + + `hash algorithm ${options.hash.algorithm}.`); + } + const memoryCost = getNumberField(options.hash, 'memoryCost'); + if (isNaN(memoryCost) || memoryCost <= 0 || memoryCost > 14) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_MEMORY_COST, 'A valid "hash.memoryCost" number between 1 and 14 must be provided for ' + + `hash algorithm ${options.hash.algorithm}.`); + } + if (typeof options.hash.saltSeparator !== 'undefined' && + !validator.isBuffer(options.hash.saltSeparator)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_SALT_SEPARATOR, '"hash.saltSeparator" must be a byte buffer.'); + } + populatedOptions = { + hashAlgorithm: options.hash.algorithm, + signerKey: utils.toWebSafeBase64(options.hash.key), + rounds, + memoryCost, + saltSeparator: utils.toWebSafeBase64(options.hash.saltSeparator || Buffer.from('')), + }; + break; + } + case 'BCRYPT': + populatedOptions = { + hashAlgorithm: options.hash.algorithm, + }; + break; + case 'STANDARD_SCRYPT': { + const cpuMemCost = getNumberField(options.hash, 'memoryCost'); + if (isNaN(cpuMemCost)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_MEMORY_COST, 'A valid "hash.memoryCost" number must be provided for ' + + `hash algorithm ${options.hash.algorithm}.`); + } + const parallelization = getNumberField(options.hash, 'parallelization'); + if (isNaN(parallelization)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_PARALLELIZATION, 'A valid "hash.parallelization" number must be provided for ' + + `hash algorithm ${options.hash.algorithm}.`); + } + const blockSize = getNumberField(options.hash, 'blockSize'); + if (isNaN(blockSize)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_BLOCK_SIZE, 'A valid "hash.blockSize" number must be provided for ' + + `hash algorithm ${options.hash.algorithm}.`); + } + const dkLen = getNumberField(options.hash, 'derivedKeyLength'); + if (isNaN(dkLen)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_DERIVED_KEY_LENGTH, 'A valid "hash.derivedKeyLength" number must be provided for ' + + `hash algorithm ${options.hash.algorithm}.`); + } + populatedOptions = { + hashAlgorithm: options.hash.algorithm, + cpuMemCost, + parallelization, + blockSize, + dkLen, + }; + break; + } + default: + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_ALGORITHM, `Unsupported hash algorithm provider "${options.hash.algorithm}".`); + } + return populatedOptions; + } + /** + * Validates and returns the users list of the uploadAccount request. + * Whenever a user with an error is detected, the error is cached and will later be + * merged into the user import result. This allows the processing of valid users without + * failing early on the first error detected. + * @param {UserImportRecord[]} users The UserImportRecords to convert to UnploadAccountUser + * objects. + * @param {ValidatorFunction=} userValidator The user validator function. + * @returns {UploadAccountUser[]} The populated uploadAccount users. + */ + populateUsers(users, userValidator) { + const populatedUsers = []; + users.forEach((user, index) => { + try { + const result = populateUploadAccountUser(user, userValidator); + if (typeof result.passwordHash !== 'undefined') { + this.requiresHashOptions = true; + } + // Only users that pass client screening will be passed to backend for processing. + populatedUsers.push(result); + // Map user's index (the one to be sent to backend) to original developer provided array. + this.indexMap[populatedUsers.length - 1] = index; + } + catch (error) { + // Save the client side error with respect to the developer provided array. + this.userImportResultErrors.push({ + index, + error, + }); + } + }); + return populatedUsers; + } +} +exports.UserImportBuilder = UserImportBuilder; diff --git a/node_modules/firebase-admin/lib/auth/user-record.d.ts b/node_modules/firebase-admin/lib/auth/user-record.d.ts new file mode 100644 index 0000000..c82c1bf --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/user-record.d.ts @@ -0,0 +1,289 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface MultiFactorInfoResponse { + mfaEnrollmentId: string; + displayName?: string; + phoneInfo?: string; + totpInfo?: TotpInfoResponse; + enrolledAt?: string; + [key: string]: unknown; +} +export interface TotpInfoResponse { + [key: string]: unknown; +} +export interface ProviderUserInfoResponse { + rawId: string; + displayName?: string; + email?: string; + photoUrl?: string; + phoneNumber?: string; + providerId: string; + federatedId?: string; +} +export interface GetAccountInfoUserResponse { + localId: string; + email?: string; + emailVerified?: boolean; + phoneNumber?: string; + displayName?: string; + photoUrl?: string; + disabled?: boolean; + passwordHash?: string; + salt?: string; + customAttributes?: string; + validSince?: string; + tenantId?: string; + providerUserInfo?: ProviderUserInfoResponse[]; + mfaInfo?: MultiFactorInfoResponse[]; + createdAt?: string; + lastLoginAt?: string; + lastRefreshAt?: string; + [key: string]: any; +} +/** + * Interface representing the common properties of a user-enrolled second factor. + */ +export declare abstract class MultiFactorInfo { + /** + * The ID of the enrolled second factor. This ID is unique to the user. + */ + readonly uid: string; + /** + * The optional display name of the enrolled second factor. + */ + readonly displayName?: string; + /** + * The type identifier of the second factor. + * For SMS second factors, this is `phone`. + * For TOTP second factors, this is `totp`. + */ + readonly factorId: string; + /** + * The optional date the second factor was enrolled, formatted as a UTC string. + */ + readonly enrollmentTime?: string; + /** + * Returns a JSON-serializable representation of this object. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON(): object; + /** + * Initializes the MultiFactorInfo object using the provided server response. + * + * @param response - The server side response. + */ + private initFromServerResponse; +} +/** + * Interface representing a phone specific user-enrolled second factor. + */ +export declare class PhoneMultiFactorInfo extends MultiFactorInfo { + /** + * The phone number associated with a phone second factor. + */ + readonly phoneNumber: string; + /** + * {@inheritdoc MultiFactorInfo.toJSON} + */ + toJSON(): object; +} +/** + * `TotpInfo` struct associated with a second factor + */ +export declare class TotpInfo { +} +/** + * Interface representing a TOTP specific user-enrolled second factor. + */ +export declare class TotpMultiFactorInfo extends MultiFactorInfo { + /** + * `TotpInfo` struct associated with a second factor + */ + readonly totpInfo: TotpInfo; + /** + * {@inheritdoc MultiFactorInfo.toJSON} + */ + toJSON(): object; +} +/** + * The multi-factor related user settings. + */ +export declare class MultiFactorSettings { + /** + * List of second factors enrolled with the current user. + * Currently only phone and TOTP second factors are supported. + */ + enrolledFactors: MultiFactorInfo[]; + /** + * Returns a JSON-serializable representation of this multi-factor object. + * + * @returns A JSON-serializable representation of this multi-factor object. + */ + toJSON(): object; +} +/** + * Represents a user's metadata. + */ +export declare class UserMetadata { + /** + * The date the user was created, formatted as a UTC string. + */ + readonly creationTime: string; + /** + * The date the user last signed in, formatted as a UTC string. + */ + readonly lastSignInTime: string; + /** + * The time at which the user was last active (ID token refreshed), + * formatted as a UTC Date string (eg 'Sat, 03 Feb 2001 04:05:06 GMT'). + * Returns null if the user was never active. + */ + readonly lastRefreshTime?: string | null; + /** + * Returns a JSON-serializable representation of this object. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON(): object; +} +/** + * Represents a user's info from a third-party identity provider + * such as Google or Facebook. + */ +export declare class UserInfo { + /** + * The user identifier for the linked provider. + */ + readonly uid: string; + /** + * The display name for the linked provider. + */ + readonly displayName: string; + /** + * The email for the linked provider. + */ + readonly email: string; + /** + * The photo URL for the linked provider. + */ + readonly photoURL: string; + /** + * The linked provider ID (for example, "google.com" for the Google provider). + */ + readonly providerId: string; + /** + * The phone number for the linked provider. + */ + readonly phoneNumber: string; + /** + * Returns a JSON-serializable representation of this object. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON(): object; +} +/** + * Represents a user. + */ +export declare class UserRecord { + /** + * The user's `uid`. + */ + readonly uid: string; + /** + * The user's primary email, if set. + */ + readonly email?: string; + /** + * Whether or not the user's primary email is verified. + */ + readonly emailVerified: boolean; + /** + * The user's display name. + */ + readonly displayName?: string; + /** + * The user's photo URL. + */ + readonly photoURL?: string; + /** + * The user's primary phone number, if set. + */ + readonly phoneNumber?: string; + /** + * Whether or not the user is disabled: `true` for disabled; `false` for + * enabled. + */ + readonly disabled: boolean; + /** + * Additional metadata about the user. + */ + readonly metadata: UserMetadata; + /** + * An array of providers (for example, Google, Facebook) linked to the user. + */ + readonly providerData: UserInfo[]; + /** + * The user's hashed password (base64-encoded), only if Firebase Auth hashing + * algorithm (SCRYPT) is used. If a different hashing algorithm had been used + * when uploading this user, as is typical when migrating from another Auth + * system, this will be an empty string. If no password is set, this is + * null. This is only available when the user is obtained from + * {@link BaseAuth.listUsers}. + */ + readonly passwordHash?: string; + /** + * The user's password salt (base64-encoded), only if Firebase Auth hashing + * algorithm (SCRYPT) is used. If a different hashing algorithm had been used to + * upload this user, typical when migrating from another Auth system, this will + * be an empty string. If no password is set, this is null. This is only + * available when the user is obtained from {@link BaseAuth.listUsers}. + */ + readonly passwordSalt?: string; + /** + * The user's custom claims object if available, typically used to define + * user roles and propagated to an authenticated user's ID token. + * This is set via {@link BaseAuth.setCustomUserClaims} + */ + readonly customClaims?: { + [key: string]: any; + }; + /** + * The ID of the tenant the user belongs to, if available. + */ + readonly tenantId?: string | null; + /** + * The date the user's tokens are valid after, formatted as a UTC string. + * This is updated every time the user's refresh token are revoked either + * from the {@link BaseAuth.revokeRefreshTokens} + * API or from the Firebase Auth backend on big account changes (password + * resets, password or email updates, etc). + */ + readonly tokensValidAfterTime?: string; + /** + * The multi-factor related properties for the current user, if available. + */ + readonly multiFactor?: MultiFactorSettings; + /** + * Returns a JSON-serializable representation of this object. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON(): object; +} diff --git a/node_modules/firebase-admin/lib/auth/user-record.js b/node_modules/firebase-admin/lib/auth/user-record.js new file mode 100644 index 0000000..485de2c --- /dev/null +++ b/node_modules/firebase-admin/lib/auth/user-record.js @@ -0,0 +1,411 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UserRecord = exports.UserInfo = exports.UserMetadata = exports.MultiFactorSettings = exports.TotpMultiFactorInfo = exports.TotpInfo = exports.PhoneMultiFactorInfo = exports.MultiFactorInfo = void 0; +const deep_copy_1 = require("../utils/deep-copy"); +const validator_1 = require("../utils/validator"); +const utils = require("../utils"); +const error_1 = require("../utils/error"); +/** + * 'REDACTED', encoded as a base64 string. + */ +const B64_REDACTED = Buffer.from('REDACTED').toString('base64'); +/** + * Parses a time stamp string or number and returns the corresponding date if valid. + * + * @param time - The unix timestamp string or number in milliseconds. + * @returns The corresponding date as a UTC string, if valid. Otherwise, null. + */ +function parseDate(time) { + try { + const date = new Date(parseInt(time, 10)); + if (!isNaN(date.getTime())) { + return date.toUTCString(); + } + } + catch (e) { + // Do nothing. null will be returned. + } + return null; +} +var MultiFactorId; +(function (MultiFactorId) { + MultiFactorId["Phone"] = "phone"; + MultiFactorId["Totp"] = "totp"; +})(MultiFactorId || (MultiFactorId = {})); +/** + * Interface representing the common properties of a user-enrolled second factor. + */ +class MultiFactorInfo { + /** + * Initializes the MultiFactorInfo associated subclass using the server side. + * If no MultiFactorInfo is associated with the response, null is returned. + * + * @param response - The server side response. + * @internal + */ + static initMultiFactorInfo(response) { + let multiFactorInfo = null; + // PhoneMultiFactorInfo, TotpMultiFactorInfo currently available. + try { + if (response.phoneInfo !== undefined) { + multiFactorInfo = new PhoneMultiFactorInfo(response); + } + else if (response.totpInfo !== undefined) { + multiFactorInfo = new TotpMultiFactorInfo(response); + } + else { + // Ignore the other SDK unsupported MFA factors to prevent blocking developers using the current SDK. + } + } + catch (e) { + // Ignore error. + } + return multiFactorInfo; + } + /** + * Initializes the MultiFactorInfo object using the server side response. + * + * @param response - The server side response. + * @constructor + * @internal + */ + constructor(response) { + this.initFromServerResponse(response); + } + /** + * Returns a JSON-serializable representation of this object. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON() { + return { + uid: this.uid, + displayName: this.displayName, + factorId: this.factorId, + enrollmentTime: this.enrollmentTime, + }; + } + /** + * Initializes the MultiFactorInfo object using the provided server response. + * + * @param response - The server side response. + */ + initFromServerResponse(response) { + const factorId = response && this.getFactorId(response); + if (!factorId || !response || !response.mfaEnrollmentId) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid multi-factor info response'); + } + utils.addReadonlyGetter(this, 'uid', response.mfaEnrollmentId); + utils.addReadonlyGetter(this, 'factorId', factorId); + utils.addReadonlyGetter(this, 'displayName', response.displayName); + // Encoded using [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. + // For example, "2017-01-15T01:30:15.01Z". + // This can be parsed directly via Date constructor. + // This can be computed using Data.prototype.toISOString. + if (response.enrolledAt) { + utils.addReadonlyGetter(this, 'enrollmentTime', new Date(response.enrolledAt).toUTCString()); + } + else { + utils.addReadonlyGetter(this, 'enrollmentTime', null); + } + } +} +exports.MultiFactorInfo = MultiFactorInfo; +/** + * Interface representing a phone specific user-enrolled second factor. + */ +class PhoneMultiFactorInfo extends MultiFactorInfo { + /** + * Initializes the PhoneMultiFactorInfo object using the server side response. + * + * @param response - The server side response. + * @constructor + * @internal + */ + constructor(response) { + super(response); + utils.addReadonlyGetter(this, 'phoneNumber', response.phoneInfo); + } + /** + * {@inheritdoc MultiFactorInfo.toJSON} + */ + toJSON() { + return Object.assign(super.toJSON(), { + phoneNumber: this.phoneNumber, + }); + } + /** + * Returns the factor ID based on the response provided. + * + * @param response - The server side response. + * @returns The multi-factor ID associated with the provided response. If the response is + * not associated with any known multi-factor ID, null is returned. + * + * @internal + */ + getFactorId(response) { + return (response && response.phoneInfo) ? MultiFactorId.Phone : null; + } +} +exports.PhoneMultiFactorInfo = PhoneMultiFactorInfo; +/** + * `TotpInfo` struct associated with a second factor + */ +class TotpInfo { +} +exports.TotpInfo = TotpInfo; +/** + * Interface representing a TOTP specific user-enrolled second factor. + */ +class TotpMultiFactorInfo extends MultiFactorInfo { + /** + * Initializes the `TotpMultiFactorInfo` object using the server side response. + * + * @param response - The server side response. + * @constructor + * @internal + */ + constructor(response) { + super(response); + utils.addReadonlyGetter(this, 'totpInfo', response.totpInfo); + } + /** + * {@inheritdoc MultiFactorInfo.toJSON} + */ + toJSON() { + return Object.assign(super.toJSON(), { + totpInfo: this.totpInfo, + }); + } + /** + * Returns the factor ID based on the response provided. + * + * @param response - The server side response. + * @returns The multi-factor ID associated with the provided response. If the response is + * not associated with any known multi-factor ID, `null` is returned. + * + * @internal + */ + getFactorId(response) { + return (response && response.totpInfo) ? MultiFactorId.Totp : null; + } +} +exports.TotpMultiFactorInfo = TotpMultiFactorInfo; +/** + * The multi-factor related user settings. + */ +class MultiFactorSettings { + /** + * Initializes the `MultiFactor` object using the server side or JWT format response. + * + * @param response - The server side response. + * @constructor + * @internal + */ + constructor(response) { + const parsedEnrolledFactors = []; + if (!(0, validator_1.isNonNullObject)(response)) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid multi-factor response'); + } + else if (response.mfaInfo) { + response.mfaInfo.forEach((factorResponse) => { + const multiFactorInfo = MultiFactorInfo.initMultiFactorInfo(factorResponse); + if (multiFactorInfo) { + parsedEnrolledFactors.push(multiFactorInfo); + } + }); + } + // Make enrolled factors immutable. + utils.addReadonlyGetter(this, 'enrolledFactors', Object.freeze(parsedEnrolledFactors)); + } + /** + * Returns a JSON-serializable representation of this multi-factor object. + * + * @returns A JSON-serializable representation of this multi-factor object. + */ + toJSON() { + return { + enrolledFactors: this.enrolledFactors.map((info) => info.toJSON()), + }; + } +} +exports.MultiFactorSettings = MultiFactorSettings; +/** + * Represents a user's metadata. + */ +class UserMetadata { + /** + * @param response - The server side response returned from the `getAccountInfo` + * endpoint. + * @constructor + * @internal + */ + constructor(response) { + // Creation date should always be available but due to some backend bugs there + // were cases in the past where users did not have creation date properly set. + // This included legacy Firebase migrating project users and some anonymous users. + // These bugs have already been addressed since then. + utils.addReadonlyGetter(this, 'creationTime', parseDate(response.createdAt)); + utils.addReadonlyGetter(this, 'lastSignInTime', parseDate(response.lastLoginAt)); + const lastRefreshAt = response.lastRefreshAt ? new Date(response.lastRefreshAt).toUTCString() : null; + utils.addReadonlyGetter(this, 'lastRefreshTime', lastRefreshAt); + } + /** + * Returns a JSON-serializable representation of this object. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON() { + return { + lastSignInTime: this.lastSignInTime, + creationTime: this.creationTime, + lastRefreshTime: this.lastRefreshTime, + }; + } +} +exports.UserMetadata = UserMetadata; +/** + * Represents a user's info from a third-party identity provider + * such as Google or Facebook. + */ +class UserInfo { + /** + * @param response - The server side response returned from the `getAccountInfo` + * endpoint. + * @constructor + * @internal + */ + constructor(response) { + // Provider user id and provider id are required. + if (!response.rawId || !response.providerId) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid user info response'); + } + utils.addReadonlyGetter(this, 'uid', response.rawId); + utils.addReadonlyGetter(this, 'displayName', response.displayName); + utils.addReadonlyGetter(this, 'email', response.email); + utils.addReadonlyGetter(this, 'photoURL', response.photoUrl); + utils.addReadonlyGetter(this, 'providerId', response.providerId); + utils.addReadonlyGetter(this, 'phoneNumber', response.phoneNumber); + } + /** + * Returns a JSON-serializable representation of this object. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON() { + return { + uid: this.uid, + displayName: this.displayName, + email: this.email, + photoURL: this.photoURL, + providerId: this.providerId, + phoneNumber: this.phoneNumber, + }; + } +} +exports.UserInfo = UserInfo; +/** + * Represents a user. + */ +class UserRecord { + /** + * @param response - The server side response returned from the getAccountInfo + * endpoint. + * @constructor + * @internal + */ + constructor(response) { + // The Firebase user id is required. + if (!response.localId) { + throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid user response'); + } + utils.addReadonlyGetter(this, 'uid', response.localId); + utils.addReadonlyGetter(this, 'email', response.email); + utils.addReadonlyGetter(this, 'emailVerified', !!response.emailVerified); + utils.addReadonlyGetter(this, 'displayName', response.displayName); + utils.addReadonlyGetter(this, 'photoURL', response.photoUrl); + utils.addReadonlyGetter(this, 'phoneNumber', response.phoneNumber); + // If disabled is not provided, the account is enabled by default. + utils.addReadonlyGetter(this, 'disabled', response.disabled || false); + utils.addReadonlyGetter(this, 'metadata', new UserMetadata(response)); + const providerData = []; + for (const entry of (response.providerUserInfo || [])) { + providerData.push(new UserInfo(entry)); + } + utils.addReadonlyGetter(this, 'providerData', providerData); + // If the password hash is redacted (probably due to missing permissions) + // then clear it out, similar to how the salt is returned. (Otherwise, it + // *looks* like a b64-encoded hash is present, which is confusing.) + if (response.passwordHash === B64_REDACTED) { + utils.addReadonlyGetter(this, 'passwordHash', undefined); + } + else { + utils.addReadonlyGetter(this, 'passwordHash', response.passwordHash); + } + utils.addReadonlyGetter(this, 'passwordSalt', response.salt); + if (response.customAttributes) { + utils.addReadonlyGetter(this, 'customClaims', JSON.parse(response.customAttributes)); + } + let validAfterTime = null; + // Convert validSince first to UTC milliseconds and then to UTC date string. + if (typeof response.validSince !== 'undefined') { + validAfterTime = parseDate(parseInt(response.validSince, 10) * 1000); + } + utils.addReadonlyGetter(this, 'tokensValidAfterTime', validAfterTime || undefined); + utils.addReadonlyGetter(this, 'tenantId', response.tenantId); + const multiFactor = new MultiFactorSettings(response); + if (multiFactor.enrolledFactors.length > 0) { + utils.addReadonlyGetter(this, 'multiFactor', multiFactor); + } + } + /** + * Returns a JSON-serializable representation of this object. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON() { + const json = { + uid: this.uid, + email: this.email, + emailVerified: this.emailVerified, + displayName: this.displayName, + photoURL: this.photoURL, + phoneNumber: this.phoneNumber, + disabled: this.disabled, + // Convert metadata to json. + metadata: this.metadata.toJSON(), + passwordHash: this.passwordHash, + passwordSalt: this.passwordSalt, + customClaims: (0, deep_copy_1.deepCopy)(this.customClaims), + tokensValidAfterTime: this.tokensValidAfterTime, + tenantId: this.tenantId, + }; + if (this.multiFactor) { + json.multiFactor = this.multiFactor.toJSON(); + } + json.providerData = []; + for (const entry of this.providerData) { + // Convert each provider data to json. + json.providerData.push(entry.toJSON()); + } + return json; + } +} +exports.UserRecord = UserRecord; diff --git a/node_modules/firebase-admin/lib/credential/index.d.ts b/node_modules/firebase-admin/lib/credential/index.d.ts new file mode 100644 index 0000000..b4697fe --- /dev/null +++ b/node_modules/firebase-admin/lib/credential/index.d.ts @@ -0,0 +1,127 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Credential as TCredential, applicationDefault as applicationDefaultFn, cert as certFn, refreshToken as refreshTokenFn } from '../app/index'; +export { ServiceAccount, GoogleOAuthAccessToken } from '../app/index'; +export declare namespace credential { + /** + * Interface that provides Google OAuth2 access tokens used to authenticate + * with Firebase services. + * + * In most cases, you will not need to implement this yourself and can instead + * use the default implementations provided by the `admin.credential` namespace. + */ + type Credential = TCredential; + /** + * Returns a credential created from the + * {@link https://developers.google.com/identity/protocols/application-default-credentials | + * Google Application Default Credentials} + * that grants admin access to Firebase services. This credential can be used + * in the call to {@link firebase-admin.app#initializeApp}. + * + * Google Application Default Credentials are available on any Google + * infrastructure, such as Google App Engine and Google Compute Engine. + * + * See + * {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK} + * for more details. + * + * @example + * ```javascript + * admin.initializeApp({ + * credential: admin.credential.applicationDefault(), + * databaseURL: "https://.firebaseio.com" + * }); + * ``` + * + * @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent} + * to be used when retrieving access tokens from Google token servers. + * + * @returns A credential authenticated via Google + * Application Default Credentials that can be used to initialize an app. + */ + const applicationDefault: typeof applicationDefaultFn; + /** + * Returns a credential created from the provided service account that grants + * admin access to Firebase services. This credential can be used in the call + * to {@link firebase-admin.app#initializeApp}. + * + * See + * {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK} + * for more details. + * + * @example + * ```javascript + * // Providing a path to a service account key JSON file + * var serviceAccount = require("path/to/serviceAccountKey.json"); + * admin.initializeApp({ + * credential: admin.credential.cert(serviceAccount), + * databaseURL: "https://.firebaseio.com" + * }); + * ``` + * + * @example + * ```javascript + * // Providing a service account object inline + * admin.initializeApp({ + * credential: admin.credential.cert({ + * projectId: "", + * clientEmail: "foo@.iam.gserviceaccount.com", + * privateKey: "-----BEGIN PRIVATE KEY----------END PRIVATE KEY-----\n" + * }), + * databaseURL: "https://.firebaseio.com" + * }); + * ``` + * + * @param serviceAccountPathOrObject - The path to a service + * account key JSON file or an object representing a service account key. + * @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent} + * to be used when retrieving access tokens from Google token servers. + * + * @returns A credential authenticated via the + * provided service account that can be used to initialize an app. + */ + const cert: typeof certFn; + /** + * Returns a credential created from the provided refresh token that grants + * admin access to Firebase services. This credential can be used in the call + * to {@link firebase-admin.app#initializeApp}. + * + * See + * {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK} + * for more details. + * + * @example + * ```javascript + * // Providing a path to a refresh token JSON file + * var refreshToken = require("path/to/refreshToken.json"); + * admin.initializeApp({ + * credential: admin.credential.refreshToken(refreshToken), + * databaseURL: "https://.firebaseio.com" + * }); + * ``` + * + * @param refreshTokenPathOrObject - The path to a Google + * OAuth2 refresh token JSON file or an object representing a Google OAuth2 + * refresh token. + * @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent} + * to be used when retrieving access tokens from Google token servers. + * + * @returns A credential authenticated via the + * provided service account that can be used to initialize an app. + */ + const refreshToken: typeof refreshTokenFn; +} diff --git a/node_modules/firebase-admin/lib/credential/index.js b/node_modules/firebase-admin/lib/credential/index.js new file mode 100644 index 0000000..9d7c4d9 --- /dev/null +++ b/node_modules/firebase-admin/lib/credential/index.js @@ -0,0 +1,123 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.credential = void 0; +const index_1 = require("../app/index"); +/* eslint-disable @typescript-eslint/no-namespace */ +var credential; +(function (credential) { + /** + * Returns a credential created from the + * {@link https://developers.google.com/identity/protocols/application-default-credentials | + * Google Application Default Credentials} + * that grants admin access to Firebase services. This credential can be used + * in the call to {@link firebase-admin.app#initializeApp}. + * + * Google Application Default Credentials are available on any Google + * infrastructure, such as Google App Engine and Google Compute Engine. + * + * See + * {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK} + * for more details. + * + * @example + * ```javascript + * admin.initializeApp({ + * credential: admin.credential.applicationDefault(), + * databaseURL: "https://.firebaseio.com" + * }); + * ``` + * + * @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent} + * to be used when retrieving access tokens from Google token servers. + * + * @returns A credential authenticated via Google + * Application Default Credentials that can be used to initialize an app. + */ + credential.applicationDefault = index_1.applicationDefault; + /** + * Returns a credential created from the provided service account that grants + * admin access to Firebase services. This credential can be used in the call + * to {@link firebase-admin.app#initializeApp}. + * + * See + * {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK} + * for more details. + * + * @example + * ```javascript + * // Providing a path to a service account key JSON file + * var serviceAccount = require("path/to/serviceAccountKey.json"); + * admin.initializeApp({ + * credential: admin.credential.cert(serviceAccount), + * databaseURL: "https://.firebaseio.com" + * }); + * ``` + * + * @example + * ```javascript + * // Providing a service account object inline + * admin.initializeApp({ + * credential: admin.credential.cert({ + * projectId: "", + * clientEmail: "foo@.iam.gserviceaccount.com", + * privateKey: "-----BEGIN PRIVATE KEY----------END PRIVATE KEY-----\n" + * }), + * databaseURL: "https://.firebaseio.com" + * }); + * ``` + * + * @param serviceAccountPathOrObject - The path to a service + * account key JSON file or an object representing a service account key. + * @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent} + * to be used when retrieving access tokens from Google token servers. + * + * @returns A credential authenticated via the + * provided service account that can be used to initialize an app. + */ + credential.cert = index_1.cert; + /** + * Returns a credential created from the provided refresh token that grants + * admin access to Firebase services. This credential can be used in the call + * to {@link firebase-admin.app#initializeApp}. + * + * See + * {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK} + * for more details. + * + * @example + * ```javascript + * // Providing a path to a refresh token JSON file + * var refreshToken = require("path/to/refreshToken.json"); + * admin.initializeApp({ + * credential: admin.credential.refreshToken(refreshToken), + * databaseURL: "https://.firebaseio.com" + * }); + * ``` + * + * @param refreshTokenPathOrObject - The path to a Google + * OAuth2 refresh token JSON file or an object representing a Google OAuth2 + * refresh token. + * @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent} + * to be used when retrieving access tokens from Google token servers. + * + * @returns A credential authenticated via the + * provided service account that can be used to initialize an app. + */ + credential.refreshToken = index_1.refreshToken; +})(credential || (exports.credential = credential = {})); diff --git a/node_modules/firebase-admin/lib/data-connect/data-connect-api-client-internal.d.ts b/node_modules/firebase-admin/lib/data-connect/data-connect-api-client-internal.d.ts new file mode 100644 index 0000000..0b0047f --- /dev/null +++ b/node_modules/firebase-admin/lib/data-connect/data-connect-api-client-internal.d.ts @@ -0,0 +1,37 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { PrefixedFirebaseError } from '../utils/error'; +/** + * When true the SDK should communicate with the Data Connect Emulator for all API + * calls and also produce unsigned tokens. + */ +export declare function useEmulator(): boolean; +export declare const DATA_CONNECT_ERROR_CODE_MAPPING: { + [key: string]: DataConnectErrorCode; +}; +export type DataConnectErrorCode = 'aborted' | 'invalid-argument' | 'invalid-credential' | 'internal-error' | 'permission-denied' | 'unauthenticated' | 'not-found' | 'unknown-error' | 'query-error'; +/** + * Firebase Data Connect error code structure. This extends PrefixedFirebaseError. + * + * @param code - The error code. + * @param message - The error message. + * @constructor + */ +export declare class FirebaseDataConnectError extends PrefixedFirebaseError { + constructor(code: DataConnectErrorCode, message: string); +} diff --git a/node_modules/firebase-admin/lib/data-connect/data-connect-api-client-internal.js b/node_modules/firebase-admin/lib/data-connect/data-connect-api-client-internal.js new file mode 100644 index 0000000..b9967a6 --- /dev/null +++ b/node_modules/firebase-admin/lib/data-connect/data-connect-api-client-internal.js @@ -0,0 +1,490 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirebaseDataConnectError = exports.DATA_CONNECT_ERROR_CODE_MAPPING = exports.DataConnectApiClient = void 0; +exports.useEmulator = useEmulator; +const api_request_1 = require("../utils/api-request"); +const error_1 = require("../utils/error"); +const utils = require("../utils/index"); +const validator = require("../utils/validator"); +const API_VERSION = 'v1'; +const FIREBASE_DATA_CONNECT_PROD_URL = 'https://firebasedataconnect.googleapis.com'; +/** The Firebase Data Connect backend service URL format. */ +const FIREBASE_DATA_CONNECT_SERVICES_URL_FORMAT = FIREBASE_DATA_CONNECT_PROD_URL + + '/{version}' + + '/projects/{projectId}' + + '/locations/{locationId}' + + '/services/{serviceId}' + + ':{endpointId}'; +/** The Firebase Data Connect backend connector URL format. */ +const FIREBASE_DATA_CONNECT_CONNECTORS_URL_FORMAT = FIREBASE_DATA_CONNECT_PROD_URL + + '/{version}' + + '/projects/{projectId}' + + '/locations/{locationId}' + + '/services/{serviceId}' + + '/connectors/{connectorId}' + + ':{endpointId}'; +/** Firebase Data Connect service URL format when using the Data Connect emulator. */ +const FIREBASE_DATA_CONNECT_EMULATOR_SERVICES_URL_FORMAT = 'http://{host}/{version}/projects/{projectId}/locations/{locationId}/services/{serviceId}:{endpointId}'; +/** Firebase Data Connect connector URL format when using the Data Connect emulator. */ +const FIREBASE_DATA_CONNECT_EMULATOR_CONNECTORS_URL_FORMAT = 'http://{host}/{version}/projects/{projectId}/locations/{locationId}/services/{serviceId}/connectors/{connectorId}:{endpointId}'; +const EXECUTE_GRAPH_QL_ENDPOINT = 'executeGraphql'; +const EXECUTE_GRAPH_QL_READ_ENDPOINT = 'executeGraphqlRead'; +const IMPERSONATE_QUERY_ENDPOINT = 'impersonateQuery'; +const IMPERSONATE_MUTATION_ENDPOINT = 'impersonateMutation'; +function getHeaders(isUsingGen) { + const headerValue = { + 'X-Firebase-Client': `fire-admin-node/${utils.getSdkVersion()}`, + 'X-Goog-Api-Client': utils.getMetricsHeader(), + }; + if (isUsingGen) { + headerValue['X-Goog-Api-Client'] += ' admin-js/gen'; + } + return headerValue; +} +/** + * Class that facilitates sending requests to the Firebase Data Connect backend API. + * + * @internal + */ +class DataConnectApiClient { + constructor(connectorConfig, app) { + this.connectorConfig = connectorConfig; + this.app = app; + this.isUsingGen = false; + if (!validator.isNonNullObject(app) || !('options' in app)) { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT, 'First argument passed to getDataConnect() must be a valid Firebase app instance.'); + } + this.httpClient = new DataConnectHttpClient(app); + } + /** + * Update whether the SDK is using a generated one or not. + * @param isUsingGen + */ + setIsUsingGen(isUsingGen) { + this.isUsingGen = isUsingGen; + } + /** + * Execute arbitrary GraphQL, including both read and write queries + * + * @param query - The GraphQL string to be executed. + * @param options - GraphQL Options + * @returns A promise that fulfills with a `ExecuteGraphqlResponse`. + */ + async executeGraphql(query, options) { + return this.executeGraphqlHelper(query, EXECUTE_GRAPH_QL_ENDPOINT, options); + } + /** + * Execute arbitrary read-only GraphQL queries + * + * @param query - The GraphQL (read-only) string to be executed. + * @param options - GraphQL Options + * @returns A promise that fulfills with a `ExecuteGraphqlResponse`. + * @throws FirebaseDataConnectError + */ + async executeGraphqlRead(query, options) { + return this.executeGraphqlHelper(query, EXECUTE_GRAPH_QL_READ_ENDPOINT, options); + } + /** + * A helper function to execute GraphQL queries. + * + * @param query - The arbitrary GraphQL query to execute. + * @param endpoint - The endpoint to call. + * @param options - The GraphQL options. + * @returns A promise that fulfills with the GraphQL response, or throws an error. + */ + async executeGraphqlHelper(query, endpoint, options) { + if (!validator.isNonEmptyString(query)) { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT, '`query` must be a non-empty string.'); + } + if (typeof options !== 'undefined') { + if (!validator.isNonNullObject(options)) { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT, 'GraphqlOptions must be a non-null object'); + } + } + const data = { + query, + ...(options?.variables && { variables: options?.variables }), + ...(options?.operationName && { operationName: options?.operationName }), + ...(options?.impersonate && { extensions: { impersonate: options?.impersonate } }), + }; + const url = await this.getServicesUrl(API_VERSION, this.connectorConfig.location, this.connectorConfig.serviceId, endpoint); + try { + const resp = await this.makeGqlRequest(url, data); + return resp; + } + catch (err) { + throw this.toFirebaseError(err); + } + } + /** + * Executes a GraphQL query with impersonation. + * + * @param options - The GraphQL options. Must include impersonation details. + * @returns A promise that fulfills with the GraphQL response. + */ + async executeQuery(name, variables, options) { + return this.executeOperationHelper(IMPERSONATE_QUERY_ENDPOINT, name, variables, options); + } + /** + * Executes a GraphQL mutation with impersonation. + * + * @param options - The GraphQL options. Must include impersonation details. + * @returns A promise that fulfills with the GraphQL response. + */ + async executeMutation(name, variables, options) { + return this.executeOperationHelper(IMPERSONATE_MUTATION_ENDPOINT, name, variables, options); + } + /** + * A helper function to execute operations by making requests to FDC's impersonate + * operations endpoints. + * + * @param endpoint - The endpoint to call. + * @param options - The GraphQL options, including impersonation details. + * @returns A promise that fulfills with the GraphQL response. + */ + async executeOperationHelper(endpoint, name, variables, options) { + if (typeof name === 'undefined' || + !validator.isNonEmptyString(name)) { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT, '`name` must be a non-empty string.'); + } + if (this.connectorConfig.connector === undefined || this.connectorConfig.connector === '') { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT, `The 'connectorConfig.connector' field used to instantiate your Data Connect + instance must be a non-empty string (the connectorId) when calling executeQuery or executeMutation.`); + } + const data = { + ...(variables && { variables: variables }), + operationName: name, + extensions: { impersonate: options?.impersonate }, + }; + const url = await this.getConnectorsUrl(API_VERSION, this.connectorConfig.location, this.connectorConfig.serviceId, this.connectorConfig.connector, endpoint); + try { + const resp = await this.makeGqlRequest(url, data); + return resp; + } + catch (err) { + throw this.toFirebaseError(err); + } + } + /** + * Constructs the URL for a Data Connect request to a service endpoint. + * + * @param version - The API version. + * @param locationId - The location of the Data Connect service. + * @param serviceId - The ID of the Data Connect service. + * @param endpointId - The endpoint to call. + * @returns A promise which resolves to the formatted URL string. + */ + async getServicesUrl(version, locationId, serviceId, endpointId) { + const projectId = await this.getProjectId(); + const params = { + version, + projectId, + locationId, + serviceId, + endpointId, + }; + let urlFormat = FIREBASE_DATA_CONNECT_SERVICES_URL_FORMAT; + if (useEmulator()) { + urlFormat = FIREBASE_DATA_CONNECT_EMULATOR_SERVICES_URL_FORMAT; + params.host = emulatorHost(); + } + return utils.formatString(urlFormat, params); + } + /** + * Constructs the URL for a Data Connect request to a connector endpoint. + * + * @param version - The API version. + * @param locationId - The location of the Data Connect service. + * @param serviceId - The ID of the Data Connect service. + * @param connectorId - The ID of the Connector. + * @param endpointId - The endpoint to call. + * @returns A promise which resolves to the formatted URL string. + + */ + async getConnectorsUrl(version, locationId, serviceId, connectorId, endpointId) { + const projectId = await this.getProjectId(); + const params = { + version, + projectId, + locationId, + serviceId, + connectorId, + endpointId, + }; + let urlFormat = FIREBASE_DATA_CONNECT_CONNECTORS_URL_FORMAT; + if (useEmulator()) { + urlFormat = FIREBASE_DATA_CONNECT_EMULATOR_CONNECTORS_URL_FORMAT; + params.host = emulatorHost(); + } + return utils.formatString(urlFormat, params); + } + getProjectId() { + if (this.projectId) { + return Promise.resolve(this.projectId); + } + return utils.findProjectId(this.app) + .then((projectId) => { + if (!validator.isNonEmptyString(projectId)) { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.UNKNOWN, 'Failed to determine project ID. Initialize the ' + + 'SDK with service account credentials or set project ID as an app option. ' + + 'Alternatively, set the GOOGLE_CLOUD_PROJECT environment variable.'); + } + this.projectId = projectId; + return projectId; + }); + } + /** + * Makes a GraphQL request to the specified url. + * + * @param url - The URL to send the request to. + * @param data - The GraphQL request payload. + * @returns A promise that fulfills with the GraphQL response, or throws an error. + */ + async makeGqlRequest(url, data) { + const request = { + method: 'POST', + url, + headers: getHeaders(this.isUsingGen), + data, + }; + const resp = await this.httpClient.send(request); + if (resp.data.errors && validator.isNonEmptyArray(resp.data.errors)) { + const allMessages = resp.data.errors.map((error) => error.message).join(' '); + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.QUERY_ERROR, allMessages); + } + return Promise.resolve({ + data: resp.data.data, + }); + } + toFirebaseError(err) { + if (err instanceof error_1.PrefixedFirebaseError) { + return err; + } + const response = err.response; + if (!response.isJson()) { + return new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.UNKNOWN, `Unexpected response with status: ${response.status} and body: ${response.text}`); + } + const error = response.data.error || {}; + let code = exports.DATA_CONNECT_ERROR_CODE_MAPPING.UNKNOWN; + if (error.status && error.status in exports.DATA_CONNECT_ERROR_CODE_MAPPING) { + code = exports.DATA_CONNECT_ERROR_CODE_MAPPING[error.status]; + } + const message = error.message || `Unknown server error: ${response.text}`; + return new FirebaseDataConnectError(code, message); + } + /** + * Converts JSON data into a GraphQL literal string. + * Handles nested objects, arrays, strings, numbers, and booleans. + * Ensures strings are properly escaped. + */ + objectToString(data) { + if (typeof data === 'string') { + const escapedString = data + .replace(/\\/g, '\\\\') // Replace \ with \\ + .replace(/"/g, '\\"'); // Replace " with \" + return `"${escapedString}"`; + } + if (typeof data === 'number' || typeof data === 'boolean' || data === null) { + return String(data); + } + if (validator.isArray(data)) { + const elements = data.map(item => this.objectToString(item)).join(', '); + return `[${elements}]`; + } + if (typeof data === 'object' && data !== null) { + // Filter out properties where the value is undefined BEFORE mapping + const kvPairs = Object.entries(data) + .filter(([, val]) => val !== undefined) + .map(([key, val]) => { + // GraphQL object keys are typically unquoted. + return `${key}: ${this.objectToString(val)}`; + }); + if (kvPairs.length === 0) { + return '{}'; // Represent an object with no defined properties as {} + } + return `{ ${kvPairs.join(', ')} }`; + } + // If value is undefined (and not an object property, which is handled above, + // e.g., if objectToString(undefined) is called directly or for an array element) + // it should be represented as 'null'. + if (typeof data === 'undefined') { + return 'null'; + } + // Fallback for any other types (e.g., Symbol, BigInt - though less common in GQL contexts) + // Consider how these should be handled or if an error should be thrown. + // For now, simple string conversion. + return String(data); + } + formatTableName(tableName) { + // Format tableName: first character to lowercase + if (tableName && tableName.length > 0) { + return tableName.charAt(0).toLowerCase() + tableName.slice(1); + } + return tableName; + } + handleBulkImportErrors(err) { + if (err.code === `data-connect/${exports.DATA_CONNECT_ERROR_CODE_MAPPING.QUERY_ERROR}`) { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.QUERY_ERROR, `${err.message}. Make sure that your table name passed in matches the type name in your GraphQL schema file.`); + } + throw err; + } + /** + * Insert a single row into the specified table. + */ + async insert(tableName, data) { + if (!validator.isNonEmptyString(tableName)) { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT, '`tableName` must be a non-empty string.'); + } + if (validator.isArray(data)) { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT, '`data` must be an object, not an array, for single insert. For arrays, please use `insertMany` function.'); + } + if (!validator.isNonNullObject(data)) { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT, '`data` must be a non-null object.'); + } + try { + tableName = this.formatTableName(tableName); + const gqlDataString = this.objectToString(data); + const mutation = `mutation { ${tableName}_insert(data: ${gqlDataString}) }`; + // Use internal executeGraphql + return this.executeGraphql(mutation).catch(this.handleBulkImportErrors); + } + catch (e) { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.INTERNAL, `Failed to construct insert mutation: ${e.message}`); + } + } + /** + * Insert multiple rows into the specified table. + */ + async insertMany(tableName, data) { + if (!validator.isNonEmptyString(tableName)) { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT, '`tableName` must be a non-empty string.'); + } + if (!validator.isNonEmptyArray(data)) { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT, '`data` must be a non-empty array for insertMany.'); + } + try { + tableName = this.formatTableName(tableName); + const gqlDataString = this.objectToString(data); + const mutation = `mutation { ${tableName}_insertMany(data: ${gqlDataString}) }`; + // Use internal executeGraphql + return this.executeGraphql(mutation).catch(this.handleBulkImportErrors); + } + catch (e) { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.INTERNAL, `Failed to construct insertMany mutation: ${e.message}`); + } + } + /** + * Insert a single row into the specified table, or update it if it already exists. + */ + async upsert(tableName, data) { + if (!validator.isNonEmptyString(tableName)) { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT, '`tableName` must be a non-empty string.'); + } + if (validator.isArray(data)) { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT, '`data` must be an object, not an array, for single upsert. For arrays, please use `upsertMany` function.'); + } + if (!validator.isNonNullObject(data)) { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT, '`data` must be a non-null object.'); + } + try { + tableName = this.formatTableName(tableName); + const gqlDataString = this.objectToString(data); + const mutation = `mutation { ${tableName}_upsert(data: ${gqlDataString}) }`; + // Use internal executeGraphql + return this.executeGraphql(mutation).catch(this.handleBulkImportErrors); + } + catch (e) { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.INTERNAL, `Failed to construct upsert mutation: ${e.message}`); + } + } + /** + * Insert multiple rows into the specified table, or update them if they already exist. + */ + async upsertMany(tableName, data) { + if (!validator.isNonEmptyString(tableName)) { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT, '`tableName` must be a non-empty string.'); + } + if (!validator.isNonEmptyArray(data)) { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT, '`data` must be a non-empty array for upsertMany.'); + } + try { + tableName = this.formatTableName(tableName); + const gqlDataString = this.objectToString(data); + const mutation = `mutation { ${tableName}_upsertMany(data: ${gqlDataString}) }`; + // Use internal executeGraphql + return this.executeGraphql(mutation).catch(this.handleBulkImportErrors); + } + catch (e) { + throw new FirebaseDataConnectError(exports.DATA_CONNECT_ERROR_CODE_MAPPING.INTERNAL, `Failed to construct upsertMany mutation: ${e.message}`); + } + } +} +exports.DataConnectApiClient = DataConnectApiClient; +/** + * Data Connect-specific HTTP client which uses the special "owner" token + * when communicating with the Data Connect Emulator. + */ +class DataConnectHttpClient extends api_request_1.AuthorizedHttpClient { + getToken() { + if (useEmulator()) { + return Promise.resolve('owner'); + } + return super.getToken(); + } +} +function emulatorHost() { + return process.env.DATA_CONNECT_EMULATOR_HOST; +} +/** + * When true the SDK should communicate with the Data Connect Emulator for all API + * calls and also produce unsigned tokens. + */ +function useEmulator() { + return !!emulatorHost(); +} +exports.DATA_CONNECT_ERROR_CODE_MAPPING = { + ABORTED: 'aborted', + INVALID_ARGUMENT: 'invalid-argument', + INVALID_CREDENTIAL: 'invalid-credential', + INTERNAL: 'internal-error', + PERMISSION_DENIED: 'permission-denied', + UNAUTHENTICATED: 'unauthenticated', + NOT_FOUND: 'not-found', + UNKNOWN: 'unknown-error', + QUERY_ERROR: 'query-error', +}; +/** + * Firebase Data Connect error code structure. This extends PrefixedFirebaseError. + * + * @param code - The error code. + * @param message - The error message. + * @constructor + */ +class FirebaseDataConnectError extends error_1.PrefixedFirebaseError { + constructor(code, message) { + super('data-connect', code, message); + /* tslint:disable:max-line-length */ + // Set the prototype explicitly. See the following link for more details: + // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work + /* tslint:enable:max-line-length */ + this.__proto__ = FirebaseDataConnectError.prototype; + } +} +exports.FirebaseDataConnectError = FirebaseDataConnectError; diff --git a/node_modules/firebase-admin/lib/data-connect/data-connect-api.d.ts b/node_modules/firebase-admin/lib/data-connect/data-connect-api.d.ts new file mode 100644 index 0000000..2345e15 --- /dev/null +++ b/node_modules/firebase-admin/lib/data-connect/data-connect-api.d.ts @@ -0,0 +1,120 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DecodedIdToken } from '../auth/token-verifier'; +/** + * Interface representing a Data Connect connector configuration. + */ +export interface ConnectorConfig { + /** + * Location ID of the Data Connect service. + */ + location: string; + /** + * Service ID of the Data Connect service. + */ + serviceId: string; + /** + * Name of the Data Connect connector. + */ + connector?: string; +} +/** + * Interface representing ExecuteGraphQL response. + */ +export interface ExecuteGraphqlResponse { + /** + * Data payload of the GraphQL response. + */ + data: GraphqlResponse; +} +/** + * Interface representing ExecuteOperation response. + */ +export interface ExecuteOperationResponse { + /** + * Data payload of the GraphQL response. + */ + data: GraphqlResponse; +} +/** + * Interface representing GraphQL options for executing arbitrary GraphQL operations. + */ +export interface GraphqlOptions { + /** + * Values for GraphQL variables provided in this query or mutation. + */ + variables?: Variables; + /** + * The name of the GraphQL operation. + * Required for operations that interact with services, such as executeGraphql, if + * `query` contains multiple operations. + */ + operationName?: string; + /** + * If set, impersonate a request with given Firebase Auth context and evaluate the auth + * policies on the operation. If omitted, bypass any defined auth policies. + */ + impersonate?: ImpersonateAuthenticated | ImpersonateUnauthenticated; +} +/** + * Interface representing options for executing defined operations. + */ +export interface OperationOptions { + /** + * If set, impersonate a request with given Firebase Auth context and evaluate the auth + * policies on the operation. If omitted, bypass any defined auth policies. + */ + impersonate?: ImpersonateAuthenticated | ImpersonateUnauthenticated; +} +/** + * Type representing the partial claims of a Firebase Auth token used to evaluate the + * Data Connect auth policy. + */ +export type AuthClaims = Partial; +/** + * Interface representing the impersonation of an authenticated user. + */ +export interface ImpersonateAuthenticated { + /** + * Evaluate the auth policy with a customized JWT auth token. Should follow the Firebase Auth token format. + * https://firebase.google.com/docs/data-connect/cel-reference#auth-token-contents + * + * @example A verified user may have the following `authClaims`: + * ```json + * { "sub": "uid", "email_verified": true } + * ``` + */ + authClaims: AuthClaims; + /** + * Both `authClaims` and `unauthenticated` are mutually exclusive fields and should not be both set. + */ + unauthenticated?: never; +} +/** + * Interface representing the impersonation of an unauthenticated user. + */ +export interface ImpersonateUnauthenticated { + /** + * Both `authClaims` and `unauthenticated` are mutually exclusive fields and should not be both set. + */ + authClaims?: never; + /** + * Evaluates the auth policy as an unauthenticated request. Can only be set to true. + */ + unauthenticated: true; +} diff --git a/node_modules/firebase-admin/lib/data-connect/data-connect-api.js b/node_modules/firebase-admin/lib/data-connect/data-connect-api.js new file mode 100644 index 0000000..f0957c1 --- /dev/null +++ b/node_modules/firebase-admin/lib/data-connect/data-connect-api.js @@ -0,0 +1,19 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/firebase-admin/lib/data-connect/data-connect.d.ts b/node_modules/firebase-admin/lib/data-connect/data-connect.d.ts new file mode 100644 index 0000000..d029074 --- /dev/null +++ b/node_modules/firebase-admin/lib/data-connect/data-connect.d.ts @@ -0,0 +1,135 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +import { ConnectorConfig, ExecuteGraphqlResponse, ExecuteOperationResponse, GraphqlOptions, OperationOptions } from './data-connect-api'; +export declare class DataConnectService { + private readonly appInternal; + private dataConnectInstances; + constructor(app: App); + getDataConnect(connectorConfig: ConnectorConfig): DataConnect; + /** + * Returns the app associated with this `DataConnectService` instance. + * + * @returns The app associated with this `DataConnectService` instance. + */ + get app(): App; +} +/** + * The Firebase `DataConnect` service interface. + */ +export declare class DataConnect { + readonly connectorConfig: ConnectorConfig; + readonly app: App; + private readonly client; + /** + * Execute an arbitrary GraphQL query or mutation + * + * @param query - The GraphQL query or mutation. + * @param options - Optional {@link GraphqlOptions} when executing a GraphQL query or mutation. + * + * @returns A promise that fulfills with a `ExecuteGraphqlResponse`. + */ + executeGraphql(query: string, options?: GraphqlOptions): Promise>; + /** + * Execute an arbitrary read-only GraphQL query + * + * @param query - The GraphQL read-only query. + * @param options - Optional {@link GraphqlOptions} when executing a read-only GraphQL query. + * + * @returns A promise that fulfills with a `ExecuteGraphqlResponse`. + */ + executeGraphqlRead(query: string, options?: GraphqlOptions): Promise>; + /** + * Insert a single row into the specified table. + * + * @param tableName - The name of the table to insert data into. + * @param variables - The data object to insert. The keys should correspond to the column names. + * @returns A promise that fulfills with a `ExecuteGraphqlResponse`. + */ + insert(tableName: string, variables: Variables): Promise>; + /** + * Insert multiple rows into the specified table. + * + * @param tableName - The name of the table to insert data into. + * @param variables - An array of data objects to insert. Each object's keys should correspond to the column names. + * @returns A promise that fulfills with a `ExecuteGraphqlResponse`. + */ + insertMany>(tableName: string, variables: Variables): Promise>; + /** + * Insert a single row into the specified table, or update it if it already exists. + * + * @param tableName - The name of the table to upsert data into. + * @param variables - The data object to upsert. The keys should correspond to the column names. + * @returns A promise that fulfills with a `ExecuteGraphqlResponse`. + */ + upsert(tableName: string, variables: Variables): Promise>; + /** + * Insert multiple rows into the specified table, or update them if they already exist. + * + * @param tableName - The name of the table to upsert data into. + * @param variables - An array of data objects to upsert. Each object's keys should correspond to the column names. + * @returns A promise that fulfills with a `ExecuteGraphqlResponse`. + */ + upsertMany>(tableName: string, variables: Variables): Promise>; + /** + * Executes a GraphQL query. The query must be defined in your Data Connect GraphQL files. + * Optionally, you can provide auth impersonation details. If you don't + * specify a value for this option, the query will run with admin privileges + * and will ignore all auth directives. + * + * @param name - The name of the defined query to execute. + * @param options - The GraphQL options, must include operationName and impersonation details. + * @returns A promise that fulfills with the GraphQL response. + */ + executeQuery(name: string, options?: OperationOptions): Promise>; + /** + * Executes a GraphQL query. The query must be defined in your Data Connect GraphQL files. + * Optionally, you can provide auth impersonation details. If you don't + * specify a value for this option, the query will run with admin privileges + * and will ignore all auth directives. + * + * @param name - The name of the defined query to execute. + * @param variables - The variables for the query. May be optional if the query's variables are optional. + * @param options - The GraphQL options, must include operationName and impersonation details. + * @returns A promise that fulfills with the GraphQL response. + */ + executeQuery(name: string, variables: Variables, options?: OperationOptions): Promise>; + /** + * Executes a GraphQL mutation. The mutation must be defined in your Data Connect GraphQL files. + * Optionally, you can provide auth impersonation details. If you don't + * specify a value for this option, the query will run with admin privileges + * and will ignore all auth directives. + * + * @param name - The name of the defined mutation to execute. + * @param options - The GraphQL options, must include operationName and impersonation details. + * @returns A promise that fulfills with the GraphQL response. + */ + executeMutation(name: string, options?: OperationOptions): Promise>; + /** + * Executes a GraphQL mutation. The mutation must be defined in your Data Connect GraphQL files. + * Optionally, you can provide auth impersonation details. If you don't + * specify a value for this option, the query will run with admin privileges + * and will ignore all auth directives. + * + * @param name - The name of the defined mutation to execute. + * @param variables - The variables for the mutation. May be optional if the mutation's variables are optional. + * @param options - The GraphQL options, must include operationName and impersonation details. + * @returns A promise that fulfills with the GraphQL response. + */ + executeMutation(name: string, variables: Variables, options?: OperationOptions): Promise>; +} diff --git a/node_modules/firebase-admin/lib/data-connect/data-connect.js b/node_modules/firebase-admin/lib/data-connect/data-connect.js new file mode 100644 index 0000000..ec393e8 --- /dev/null +++ b/node_modules/firebase-admin/lib/data-connect/data-connect.js @@ -0,0 +1,138 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DataConnect = exports.DataConnectService = void 0; +const data_connect_api_client_internal_1 = require("./data-connect-api-client-internal"); +class DataConnectService { + constructor(app) { + this.dataConnectInstances = new Map(); + this.appInternal = app; + } + getDataConnect(connectorConfig) { + const id = `${connectorConfig.location}-${connectorConfig.serviceId}`; + const dc = this.dataConnectInstances.get(id); + if (typeof dc !== 'undefined') { + return dc; + } + const newInstance = new DataConnect(connectorConfig, this.appInternal); + this.dataConnectInstances.set(id, newInstance); + return newInstance; + } + /** + * Returns the app associated with this `DataConnectService` instance. + * + * @returns The app associated with this `DataConnectService` instance. + */ + get app() { + return this.appInternal; + } +} +exports.DataConnectService = DataConnectService; +/** + * The Firebase `DataConnect` service interface. + */ +class DataConnect { + /** + * @param connectorConfig - The connector configuration. + * @param app - The app for this `DataConnect` service. + * @constructor + * @internal + */ + constructor(connectorConfig, app) { + this.connectorConfig = connectorConfig; + this.app = app; + this.client = new data_connect_api_client_internal_1.DataConnectApiClient(connectorConfig, app); + } + /** + * @param isUsingGen + * @internal + */ + useGen(isUsingGen) { + this.client.setIsUsingGen(isUsingGen); + } + /** + * Execute an arbitrary GraphQL query or mutation + * + * @param query - The GraphQL query or mutation. + * @param options - Optional {@link GraphqlOptions} when executing a GraphQL query or mutation. + * + * @returns A promise that fulfills with a `ExecuteGraphqlResponse`. + */ + executeGraphql(query, options) { + return this.client.executeGraphql(query, options); + } + /** + * Execute an arbitrary read-only GraphQL query + * + * @param query - The GraphQL read-only query. + * @param options - Optional {@link GraphqlOptions} when executing a read-only GraphQL query. + * + * @returns A promise that fulfills with a `ExecuteGraphqlResponse`. + */ + executeGraphqlRead(query, options) { + return this.client.executeGraphqlRead(query, options); + } + /** + * Insert a single row into the specified table. + * + * @param tableName - The name of the table to insert data into. + * @param variables - The data object to insert. The keys should correspond to the column names. + * @returns A promise that fulfills with a `ExecuteGraphqlResponse`. + */ + insert(tableName, variables) { + return this.client.insert(tableName, variables); + } + /** + * Insert multiple rows into the specified table. + * + * @param tableName - The name of the table to insert data into. + * @param variables - An array of data objects to insert. Each object's keys should correspond to the column names. + * @returns A promise that fulfills with a `ExecuteGraphqlResponse`. + */ + insertMany(tableName, variables) { + return this.client.insertMany(tableName, variables); + } + /** + * Insert a single row into the specified table, or update it if it already exists. + * + * @param tableName - The name of the table to upsert data into. + * @param variables - The data object to upsert. The keys should correspond to the column names. + * @returns A promise that fulfills with a `ExecuteGraphqlResponse`. + */ + upsert(tableName, variables) { + return this.client.upsert(tableName, variables); + } + /** + * Insert multiple rows into the specified table, or update them if they already exist. + * + * @param tableName - The name of the table to upsert data into. + * @param variables - An array of data objects to upsert. Each object's keys should correspond to the column names. + * @returns A promise that fulfills with a `ExecuteGraphqlResponse`. + */ + upsertMany(tableName, variables) { + return this.client.upsertMany(tableName, variables); + } + executeQuery(name, variables, options) { + return this.client.executeQuery(name, variables, options); + } + executeMutation(name, variables, options) { + return this.client.executeMutation(name, variables, options); + } +} +exports.DataConnect = DataConnect; diff --git a/node_modules/firebase-admin/lib/data-connect/index.d.ts b/node_modules/firebase-admin/lib/data-connect/index.d.ts new file mode 100644 index 0000000..6d21b4e --- /dev/null +++ b/node_modules/firebase-admin/lib/data-connect/index.d.ts @@ -0,0 +1,46 @@ +/*! firebase-admin v13.6.0 */ +/** + * Firebase Data Connect service. + * + * @packageDocumentation + */ +import { App } from '../app'; +import { DataConnect } from './data-connect'; +import { ConnectorConfig } from './data-connect-api'; +export { GraphqlOptions, ExecuteGraphqlResponse, ExecuteOperationResponse, ConnectorConfig, ImpersonateAuthenticated, ImpersonateUnauthenticated, AuthClaims, OperationOptions, } from './data-connect-api'; +export { DataConnect, } from './data-connect'; +/** + * Gets the {@link DataConnect} service with the provided connector configuration + * for the default app or a given app. + * + * `getDataConnect(connectorConfig)` can be called with no app argument to access the default + * app's `DataConnect` service or as `getDataConnect(connectorConfig, app)` to access the + * `DataConnect` service associated with a specific app. + * + * @example + * ```javascript + * const connectorConfig: ConnectorConfig = { + * location: 'us-west2', + * serviceId: 'my-service', + * connectorName: 'my-connector', + * }; + * + * // Get the `DataConnect` service for the default app + * const defaultDataConnect = getDataConnect(connectorConfig); + * ``` + * + * @example + * ```javascript + * // Get the `DataConnect` service for a given app + * const otherDataConnect = getDataConnect(connectorConfig, otherApp); + * ``` + * + * @param connectorConfig - Connector configuration for the `DataConnect` service. + * + * @param app - Optional app for which to return the `DataConnect` service. + * If not provided, the default `DataConnect` service is returned. + * + * @returns The default `DataConnect` service with the provided connector configuration + * if no app is provided, or the `DataConnect` service associated with the provided app. + */ +export declare function getDataConnect(connectorConfig: ConnectorConfig, app?: App): DataConnect; diff --git a/node_modules/firebase-admin/lib/data-connect/index.js b/node_modules/firebase-admin/lib/data-connect/index.js new file mode 100644 index 0000000..7c540ae --- /dev/null +++ b/node_modules/firebase-admin/lib/data-connect/index.js @@ -0,0 +1,77 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/** + * Firebase Data Connect service. + * + * @packageDocumentation + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateAdminArgs = exports.DataConnect = void 0; +exports.getDataConnect = getDataConnect; +/*! + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const validate_admin_args_1 = require("./validate-admin-args"); +const app_1 = require("../app"); +const data_connect_1 = require("./data-connect"); +var data_connect_2 = require("./data-connect"); +Object.defineProperty(exports, "DataConnect", { enumerable: true, get: function () { return data_connect_2.DataConnect; } }); +/** + * Gets the {@link DataConnect} service with the provided connector configuration + * for the default app or a given app. + * + * `getDataConnect(connectorConfig)` can be called with no app argument to access the default + * app's `DataConnect` service or as `getDataConnect(connectorConfig, app)` to access the + * `DataConnect` service associated with a specific app. + * + * @example + * ```javascript + * const connectorConfig: ConnectorConfig = { + * location: 'us-west2', + * serviceId: 'my-service', + * connectorName: 'my-connector', + * }; + * + * // Get the `DataConnect` service for the default app + * const defaultDataConnect = getDataConnect(connectorConfig); + * ``` + * + * @example + * ```javascript + * // Get the `DataConnect` service for a given app + * const otherDataConnect = getDataConnect(connectorConfig, otherApp); + * ``` + * + * @param connectorConfig - Connector configuration for the `DataConnect` service. + * + * @param app - Optional app for which to return the `DataConnect` service. + * If not provided, the default `DataConnect` service is returned. + * + * @returns The default `DataConnect` service with the provided connector configuration + * if no app is provided, or the `DataConnect` service associated with the provided app. + */ +function getDataConnect(connectorConfig, app) { + if (typeof app === 'undefined') { + app = (0, app_1.getApp)(); + } + const firebaseApp = app; + const dataConnectService = firebaseApp.getOrInitService('dataConnect', (app) => new data_connect_1.DataConnectService(app)); + return dataConnectService.getDataConnect(connectorConfig); +} +/** + * @internal + */ +exports.validateAdminArgs = validate_admin_args_1._validateAdminArgs; diff --git a/node_modules/firebase-admin/lib/data-connect/validate-admin-args.d.ts b/node_modules/firebase-admin/lib/data-connect/validate-admin-args.d.ts new file mode 100644 index 0000000..e43394f --- /dev/null +++ b/node_modules/firebase-admin/lib/data-connect/validate-admin-args.d.ts @@ -0,0 +1,18 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/firebase-admin/lib/data-connect/validate-admin-args.js b/node_modules/firebase-admin/lib/data-connect/validate-admin-args.js new file mode 100644 index 0000000..f953d4e --- /dev/null +++ b/node_modules/firebase-admin/lib/data-connect/validate-admin-args.js @@ -0,0 +1,79 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports._validateAdminArgs = _validateAdminArgs; +const index_1 = require("./index"); +const data_connect_api_client_internal_1 = require("./data-connect-api-client-internal"); +/** + * @internal + * + * The generated Admin SDK will allow the user to pass in variables, a Data Connect + * instance, or operation options. The only required argument is the variables, + * which are only required when the operation has at least one required variable. + * Otherwise, all arguments are optional. + * + * This function validates the variables and returns back the DataConnect instance, + * variables, and options based on the arguments passed in. It always returns a + * DataConnect instance, using the connectorConfig to grab one if not provided. + * + * For this function to work properly, if the operation has variables (optional + * are required), you must pass hasVars: true (if there are no variables, it is + * not required, since undefined is false-y). + * + * Usage examples can be found in test files. + * + * @param connectorConfig - DataConnect connector config + * @param dcOrVarsOrOptions - the first argument provided to a generated admin function + * @param varsOrOptions - the second argument provided to a generated admin function + * @param options - the third argument provided to a generated admin function + * @param hasVars - boolean parameter indicating whether the operation has variables + * @param validateVars - boolean parameter indicating whether we should expect to find a value for realVars + * @returns parsed DataConnect, Variables, and Options for the operation + */ +function _validateAdminArgs(connectorConfig, dcOrVarsOrOptions, varsOrOptions, options, hasVars, validateVars) { + let dcInstance; + let realVars; + let realOptions; + if (dcOrVarsOrOptions && 'connectorConfig' in dcOrVarsOrOptions) { + dcInstance = dcOrVarsOrOptions; + if (hasVars) { + realVars = varsOrOptions; + realOptions = options; + } + else { + realVars = undefined; + realOptions = varsOrOptions; + } + } + else { + dcInstance = (0, index_1.getDataConnect)(connectorConfig); + if (hasVars) { + realVars = dcOrVarsOrOptions; + realOptions = varsOrOptions; + } + else { + realVars = undefined; + realOptions = dcOrVarsOrOptions; + } + } + if (!dcInstance || (!realVars && validateVars)) { + throw new data_connect_api_client_internal_1.FirebaseDataConnectError(data_connect_api_client_internal_1.DATA_CONNECT_ERROR_CODE_MAPPING.INVALID_ARGUMENT, 'Variables required.'); + } + return { dc: dcInstance, vars: realVars, options: realOptions }; +} diff --git a/node_modules/firebase-admin/lib/database/database-namespace.d.ts b/node_modules/firebase-admin/lib/database/database-namespace.d.ts new file mode 100644 index 0000000..4233efa --- /dev/null +++ b/node_modules/firebase-admin/lib/database/database-namespace.d.ts @@ -0,0 +1,95 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as rtdb from '@firebase/database-types'; +import { App } from '../app'; +import { Database as TDatabase } from './database'; +/** + * Gets the {@link firebase-admin.database#Database} service for the default + * app or a given app. + * + * `admin.database()` can be called with no arguments to access the default + * app's `Database` service or as `admin.database(app)` to access the + * `Database` service associated with a specific app. + * + * `admin.database` is also a namespace that can be used to access global + * constants and methods associated with the `Database` service. + * + * @example + * ```javascript + * // Get the Database service for the default app + * var defaultDatabase = admin.database(); + * ``` + * + * @example + * ```javascript + * // Get the Database service for a specific app + * var otherDatabase = admin.database(app); + * ``` + * + * @param App - whose `Database` service to + * return. If not provided, the default `Database` service will be returned. + * + * @returns The default `Database` service if no app + * is provided or the `Database` service associated with the provided app. + */ +export declare function database(app?: App): database.Database; +export declare namespace database { + /** + * Type alias to {@link firebase-admin.database#Database}. + */ + type Database = TDatabase; + /** + * Type alias to {@link https://firebase.google.com/docs/reference/js/v8/firebase.database.DataSnapshot | DataSnapshot} + * type from the `@firebase/database-compat` package. + */ + type DataSnapshot = rtdb.DataSnapshot; + /** + * Type alias to the {@link https://firebase.google.com/docs/reference/js/v8/firebase.database#eventtype | EventType} + * type from the `@firebase/database-compat` package. + */ + type EventType = rtdb.EventType; + /** + * Type alias to {@link https://firebase.google.com/docs/reference/js/v8/firebase.database.OnDisconnect | OnDisconnect} + * type from the `@firebase/database-compat` package. + */ + type OnDisconnect = rtdb.OnDisconnect; + /** + * Type alias to {@link https://firebase.google.com/docs/reference/js/v8/firebase.database.Query | Query} + * type from the `@firebase/database-compat` package. + */ + type Query = rtdb.Query; + /** + * Type alias to {@link https://firebase.google.com/docs/reference/js/v8/firebase.database.Reference | Reference} + * type from the `@firebase/database-compat` package. + */ + type Reference = rtdb.Reference; + /** + * Type alias to {@link https://firebase.google.com/docs/reference/js/v8/firebase.database.ThenableReference | + * ThenableReference} type from the `@firebase/database-compat` package. + */ + type ThenableReference = rtdb.ThenableReference; + /** + * {@link https://firebase.google.com/docs/reference/js/v8/firebase.database#enablelogging | enableLogging} + * function from the `@firebase/database-compat` package. + */ + const enableLogging: typeof rtdb.enableLogging; + /** + * {@link https://firebase.google.com/docs/reference/js/v8/firebase.database.ServerValue | ServerValue} + * constant from the `@firebase/database-compat` package. + */ + const ServerValue: rtdb.ServerValue; +} diff --git a/node_modules/firebase-admin/lib/database/database-namespace.js b/node_modules/firebase-admin/lib/database/database-namespace.js new file mode 100644 index 0000000..f3e9e1e --- /dev/null +++ b/node_modules/firebase-admin/lib/database/database-namespace.js @@ -0,0 +1,23 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.database = void 0; +/* eslint-disable @typescript-eslint/no-namespace */ +var database; +(function (database) { +})(database || (exports.database = database = {})); diff --git a/node_modules/firebase-admin/lib/database/database.d.ts b/node_modules/firebase-admin/lib/database/database.d.ts new file mode 100644 index 0000000..92e361e --- /dev/null +++ b/node_modules/firebase-admin/lib/database/database.d.ts @@ -0,0 +1,65 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseDatabase } from '@firebase/database-types'; +import { App } from '../app'; +/** + * The Firebase Database service interface. Extends the + * {@link https://firebase.google.com/docs/reference/js/v8/firebase.database.Database | Database} + * interface provided by the `@firebase/database-compat` package. + */ +export interface Database extends FirebaseDatabase { + /** + * Gets the currently applied security rules as a string. The return value consists of + * the rules source including comments. + * + * @returns A promise fulfilled with the rules as a raw string. + */ + getRules(): Promise; + /** + * Gets the currently applied security rules as a parsed JSON object. Any comments in + * the original source are stripped away. + * + * @returns A promise fulfilled with the parsed rules object. + */ + getRulesJSON(): Promise; + /** + * Sets the specified rules on the Firebase Realtime Database instance. If the rules source is + * specified as a string or a Buffer, it may include comments. + * + * @param source - Source of the rules to apply. Must not be `null` or empty. + * @returns Resolves when the rules are set on the Realtime Database. + */ + setRules(source: string | Buffer | object): Promise; +} +export declare class DatabaseService { + private readonly appInternal; + private tokenListener; + private tokenRefreshTimeout; + private databases; + constructor(app: App); + private get firebaseApp(); + /** + * Returns the app associated with this DatabaseService instance. + * + * @returns The app associated with this DatabaseService instance. + */ + get app(): App; + getDatabase(url?: string): Database; + private onTokenChange; + private scheduleTokenRefresh; + private ensureUrl; +} diff --git a/node_modules/firebase-admin/lib/database/database.js b/node_modules/firebase-admin/lib/database/database.js new file mode 100644 index 0000000..132cc1d --- /dev/null +++ b/node_modules/firebase-admin/lib/database/database.js @@ -0,0 +1,257 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DatabaseService = void 0; +const url_1 = require("url"); +const path = require("path"); +const error_1 = require("../utils/error"); +const validator = require("../utils/validator"); +const api_request_1 = require("../utils/api-request"); +const index_1 = require("../utils/index"); +const TOKEN_REFRESH_THRESHOLD_MILLIS = 5 * 60 * 1000; +class DatabaseService { + constructor(app) { + this.databases = {}; + if (!validator.isNonNullObject(app) || !('options' in app)) { + throw new error_1.FirebaseDatabaseError({ + code: 'invalid-argument', + message: 'First argument passed to admin.database() must be a valid Firebase app instance.', + }); + } + this.appInternal = app; + } + get firebaseApp() { + return this.app; + } + /** + * @internal + */ + delete() { + if (this.tokenListener) { + this.firebaseApp.INTERNAL.removeAuthTokenListener(this.tokenListener); + clearTimeout(this.tokenRefreshTimeout); + } + const promises = []; + for (const dbUrl of Object.keys(this.databases)) { + const db = this.databases[dbUrl]; + promises.push(db.INTERNAL.delete()); + } + return Promise.all(promises).then(() => { + this.databases = {}; + }); + } + /** + * Returns the app associated with this DatabaseService instance. + * + * @returns The app associated with this DatabaseService instance. + */ + get app() { + return this.appInternal; + } + getDatabase(url) { + const dbUrl = this.ensureUrl(url); + if (!validator.isNonEmptyString(dbUrl)) { + throw new error_1.FirebaseDatabaseError({ + code: 'invalid-argument', + message: 'Database URL must be a valid, non-empty URL string.', + }); + } + let db = this.databases[dbUrl]; + if (typeof db === 'undefined') { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const rtdb = require('@firebase/database-compat/standalone'); + db = rtdb.initStandalone(this.appInternal, dbUrl, (0, index_1.getSdkVersion)()).instance; + const rulesClient = new DatabaseRulesClient(this.app, dbUrl); + db.getRules = () => { + return rulesClient.getRules(); + }; + db.getRulesJSON = () => { + return rulesClient.getRulesJSON(); + }; + db.setRules = (source) => { + return rulesClient.setRules(source); + }; + this.databases[dbUrl] = db; + } + if (!this.tokenListener) { + this.tokenListener = this.onTokenChange.bind(this); + this.firebaseApp.INTERNAL.addAuthTokenListener(this.tokenListener); + } + return db; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onTokenChange(_) { + const token = this.firebaseApp.INTERNAL.getCachedToken(); + if (token) { + const delayMillis = token.expirationTime - TOKEN_REFRESH_THRESHOLD_MILLIS - Date.now(); + // If the new token is set to expire soon (unlikely), do nothing. Somebody will eventually + // notice and refresh the token, at which point this callback will fire again. + if (delayMillis > 0) { + this.scheduleTokenRefresh(delayMillis); + } + } + } + scheduleTokenRefresh(delayMillis) { + clearTimeout(this.tokenRefreshTimeout); + this.tokenRefreshTimeout = setTimeout(() => { + this.firebaseApp.INTERNAL.getToken(/*forceRefresh=*/ true) + .catch(() => { + // Ignore the error since this might just be an intermittent failure. If we really cannot + // refresh the token, an error will be logged once the existing token expires and we try + // to fetch a fresh one. + }); + }, delayMillis); + } + ensureUrl(url) { + if (typeof url !== 'undefined') { + return url; + } + else if (typeof this.appInternal.options.databaseURL !== 'undefined') { + return this.appInternal.options.databaseURL; + } + throw new error_1.FirebaseDatabaseError({ + code: 'invalid-argument', + message: 'Can\'t determine Firebase Database URL.', + }); + } +} +exports.DatabaseService = DatabaseService; +const RULES_URL_PATH = '.settings/rules.json'; +/** + * A helper client for managing RTDB security rules. + */ +class DatabaseRulesClient { + constructor(app, dbUrl) { + let parsedUrl = new url_1.URL(dbUrl); + const emulatorHost = process.env.FIREBASE_DATABASE_EMULATOR_HOST; + if (emulatorHost) { + const namespace = extractNamespace(parsedUrl); + parsedUrl = new url_1.URL(`http://${emulatorHost}?ns=${namespace}`); + } + parsedUrl.pathname = path.join(parsedUrl.pathname, RULES_URL_PATH); + this.dbUrl = parsedUrl.toString(); + this.httpClient = new api_request_1.AuthorizedHttpClient(app); + } + /** + * Gets the currently applied security rules as a string. The return value consists of + * the rules source including comments. + * + * @returns A promise fulfilled with the rules as a raw string. + */ + getRules() { + const req = { + method: 'GET', + url: this.dbUrl, + }; + return this.httpClient.send(req) + .then((resp) => { + if (!resp.text) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INTERNAL_ERROR, 'HTTP response missing data.'); + } + return resp.text; + }) + .catch((err) => { + throw this.handleError(err); + }); + } + /** + * Gets the currently applied security rules as a parsed JSON object. Any comments in + * the original source are stripped away. + * + * @returns {Promise} A promise fulfilled with the parsed rules source. + */ + getRulesJSON() { + const req = { + method: 'GET', + url: this.dbUrl, + data: { format: 'strict' }, + }; + return this.httpClient.send(req) + .then((resp) => { + return resp.data; + }) + .catch((err) => { + throw this.handleError(err); + }); + } + /** + * Sets the specified rules on the Firebase Database instance. If the rules source is + * specified as a string or a Buffer, it may include comments. + * + * @param {string|Buffer|object} source Source of the rules to apply. Must not be `null` + * or empty. + * @returns {Promise} Resolves when the rules are set on the Database. + */ + setRules(source) { + if (!validator.isNonEmptyString(source) && + !validator.isBuffer(source) && + !validator.isNonNullObject(source)) { + const error = new error_1.FirebaseDatabaseError({ + code: 'invalid-argument', + message: 'Source must be a non-empty string, Buffer or an object.', + }); + return Promise.reject(error); + } + const req = { + method: 'PUT', + url: this.dbUrl, + data: source, + headers: { + 'content-type': 'application/json; charset=utf-8', + }, + }; + return this.httpClient.send(req) + .then(() => { + return; + }) + .catch((err) => { + throw this.handleError(err); + }); + } + handleError(err) { + if (err instanceof api_request_1.RequestResponseError) { + return new error_1.FirebaseDatabaseError({ + code: error_1.AppErrorCodes.INTERNAL_ERROR, + message: this.getErrorMessage(err), + }); + } + return err; + } + getErrorMessage(err) { + const intro = 'Error while accessing security rules'; + try { + const body = err.response.data; + if (body && body.error) { + return `${intro}: ${body.error.trim()}`; + } + } + catch { + // Ignore parsing errors + } + return `${intro}: ${err.response.text}`; + } +} +function extractNamespace(parsedUrl) { + const ns = parsedUrl.searchParams.get('ns'); + if (ns) { + return ns; + } + const hostname = parsedUrl.hostname; + const dotIndex = hostname.indexOf('.'); + return hostname.substring(0, dotIndex).toLowerCase(); +} diff --git a/node_modules/firebase-admin/lib/database/index.d.ts b/node_modules/firebase-admin/lib/database/index.d.ts new file mode 100644 index 0000000..beee6cf --- /dev/null +++ b/node_modules/firebase-admin/lib/database/index.d.ts @@ -0,0 +1,91 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Firebase Realtime Database. + * + * @packageDocumentation + */ +import * as rtdb from '@firebase/database-types'; +import { App } from '../app'; +import { Database } from './database'; +export { Database }; +export { DataSnapshot, EventType, OnDisconnect, Query, Reference, ThenableReference, } from '@firebase/database-types'; +/** + * {@link https://firebase.google.com/docs/reference/js/v8/firebase.database#enablelogging | enableLogging} + * function from the `@firebase/database-compat` package. + */ +export declare const enableLogging: typeof rtdb.enableLogging; +/** + * {@link https://firebase.google.com/docs/reference/js/v8/firebase.database.ServerValue | ServerValue} + * constant from the `@firebase/database-compat` package. + */ +export declare const ServerValue: rtdb.ServerValue; +/** + * Gets the {@link Database} service for the default + * app or a given app. + * + * `getDatabase()` can be called with no arguments to access the default + * app's `Database` service or as `getDatabase(app)` to access the + * `Database` service associated with a specific app. + * + * @example + * ```javascript + * // Get the Database service for the default app + * const defaultDatabase = getDatabase(); + * ``` + * + * @example + * ```javascript + * // Get the Database service for a specific app + * const otherDatabase = getDatabase(app); + * ``` + * + * @param App - whose `Database` service to + * return. If not provided, the default `Database` service will be returned. + * + * @returns The default `Database` service if no app + * is provided or the `Database` service associated with the provided app. + */ +export declare function getDatabase(app?: App): Database; +/** + * Gets the {@link Database} service for the default + * app or a given app. + * + * `getDatabaseWithUrl()` can be called with no arguments to access the default + * app's {@link Database} service or as `getDatabaseWithUrl(app)` to access the + * {@link Database} service associated with a specific app. + * + * @example + * ```javascript + * // Get the Database service for the default app + * const defaultDatabase = getDatabaseWithUrl('https://example.firebaseio.com'); + * ``` + * + * @example + * ```javascript + * // Get the Database service for a specific app + * const otherDatabase = getDatabaseWithUrl('https://example.firebaseio.com', app); + * ``` + * + * @param App - whose `Database` service to + * return. If not provided, the default `Database` service will be returned. + * + * @returns The default `Database` service if no app + * is provided or the `Database` service associated with the provided app. + */ +export declare function getDatabaseWithUrl(url: string, app?: App): Database; +export { FirebaseDatabaseError } from '../utils/error'; diff --git a/node_modules/firebase-admin/lib/database/index.js b/node_modules/firebase-admin/lib/database/index.js new file mode 100644 index 0000000..d7ffabc --- /dev/null +++ b/node_modules/firebase-admin/lib/database/index.js @@ -0,0 +1,105 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirebaseDatabaseError = exports.ServerValue = exports.enableLogging = void 0; +exports.getDatabase = getDatabase; +exports.getDatabaseWithUrl = getDatabaseWithUrl; +const standalone_1 = require("@firebase/database-compat/standalone"); +const app_1 = require("../app"); +const database_1 = require("./database"); +// TODO: Remove the following any-cast once the typins in @firebase/database-types are fixed. +/** + * {@link https://firebase.google.com/docs/reference/js/v8/firebase.database#enablelogging | enableLogging} + * function from the `@firebase/database-compat` package. + */ +exports.enableLogging = standalone_1.enableLogging; +/** + * {@link https://firebase.google.com/docs/reference/js/v8/firebase.database.ServerValue | ServerValue} + * constant from the `@firebase/database-compat` package. + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +exports.ServerValue = standalone_1.ServerValue; +/** + * Gets the {@link Database} service for the default + * app or a given app. + * + * `getDatabase()` can be called with no arguments to access the default + * app's `Database` service or as `getDatabase(app)` to access the + * `Database` service associated with a specific app. + * + * @example + * ```javascript + * // Get the Database service for the default app + * const defaultDatabase = getDatabase(); + * ``` + * + * @example + * ```javascript + * // Get the Database service for a specific app + * const otherDatabase = getDatabase(app); + * ``` + * + * @param App - whose `Database` service to + * return. If not provided, the default `Database` service will be returned. + * + * @returns The default `Database` service if no app + * is provided or the `Database` service associated with the provided app. + */ +function getDatabase(app) { + return getDatabaseInstance({ app }); +} +/** + * Gets the {@link Database} service for the default + * app or a given app. + * + * `getDatabaseWithUrl()` can be called with no arguments to access the default + * app's {@link Database} service or as `getDatabaseWithUrl(app)` to access the + * {@link Database} service associated with a specific app. + * + * @example + * ```javascript + * // Get the Database service for the default app + * const defaultDatabase = getDatabaseWithUrl('https://example.firebaseio.com'); + * ``` + * + * @example + * ```javascript + * // Get the Database service for a specific app + * const otherDatabase = getDatabaseWithUrl('https://example.firebaseio.com', app); + * ``` + * + * @param App - whose `Database` service to + * return. If not provided, the default `Database` service will be returned. + * + * @returns The default `Database` service if no app + * is provided or the `Database` service associated with the provided app. + */ +function getDatabaseWithUrl(url, app) { + return getDatabaseInstance({ url, app }); +} +function getDatabaseInstance(options) { + let { app } = options; + if (typeof app === 'undefined') { + app = (0, app_1.getApp)(); + } + const firebaseApp = app; + const dbService = firebaseApp.getOrInitService('database', (app) => new database_1.DatabaseService(app)); + return dbService.getDatabase(options.url); +} +var error_1 = require("../utils/error"); +Object.defineProperty(exports, "FirebaseDatabaseError", { enumerable: true, get: function () { return error_1.FirebaseDatabaseError; } }); diff --git a/node_modules/firebase-admin/lib/default-namespace.d.ts b/node_modules/firebase-admin/lib/default-namespace.d.ts new file mode 100644 index 0000000..576ba79 --- /dev/null +++ b/node_modules/firebase-admin/lib/default-namespace.d.ts @@ -0,0 +1,24 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Firebase namespaced API (legacy). + * + * @packageDocumentation + */ + +export * from './firebase-namespace-api'; diff --git a/node_modules/firebase-admin/lib/default-namespace.js b/node_modules/firebase-admin/lib/default-namespace.js new file mode 100644 index 0000000..19cd276 --- /dev/null +++ b/node_modules/firebase-admin/lib/default-namespace.js @@ -0,0 +1,30 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const firebase_namespace_1 = require("./app/firebase-namespace"); +// Inject a circular default export to allow users to use both: +// +// import firebaseAdmin from 'firebase-admin'; +// which becomes: var firebaseAdmin = require('firebase-admin').default; +// +// as well as the more correct: +// +// import * as firebaseAdmin from 'firebase-admin'; +// which becomes: var firebaseAdmin = require('firebase-admin'); +firebase_namespace_1.defaultNamespace.default = firebase_namespace_1.defaultNamespace; +module.exports = firebase_namespace_1.defaultNamespace; diff --git a/node_modules/firebase-admin/lib/esm/app-check/index.js b/node_modules/firebase-admin/lib/esm/app-check/index.js new file mode 100644 index 0000000..ced85dd --- /dev/null +++ b/node_modules/firebase-admin/lib/esm/app-check/index.js @@ -0,0 +1,4 @@ +import mod from "../../app-check/index.js"; + +export const AppCheck = mod.AppCheck; +export const getAppCheck = mod.getAppCheck; diff --git a/node_modules/firebase-admin/lib/esm/app/index.js b/node_modules/firebase-admin/lib/esm/app/index.js new file mode 100644 index 0000000..1f5f1a7 --- /dev/null +++ b/node_modules/firebase-admin/lib/esm/app/index.js @@ -0,0 +1,12 @@ +import mod from "../../app/index.js"; + +export const AppErrorCodes = mod.AppErrorCodes; +export const FirebaseAppError = mod.FirebaseAppError; +export const SDK_VERSION = mod.SDK_VERSION; +export const applicationDefault = mod.applicationDefault; +export const cert = mod.cert; +export const deleteApp = mod.deleteApp; +export const getApp = mod.getApp; +export const getApps = mod.getApps; +export const initializeApp = mod.initializeApp; +export const refreshToken = mod.refreshToken; diff --git a/node_modules/firebase-admin/lib/esm/auth/index.js b/node_modules/firebase-admin/lib/esm/auth/index.js new file mode 100644 index 0000000..399f9ea --- /dev/null +++ b/node_modules/firebase-admin/lib/esm/auth/index.js @@ -0,0 +1,18 @@ +import mod from "../../auth/index.js"; + +export const Auth = mod.Auth; +export const AuthClientErrorCode = mod.AuthClientErrorCode; +export const BaseAuth = mod.BaseAuth; +export const FirebaseAuthError = mod.FirebaseAuthError; +export const MultiFactorInfo = mod.MultiFactorInfo; +export const MultiFactorSettings = mod.MultiFactorSettings; +export const PhoneMultiFactorInfo = mod.PhoneMultiFactorInfo; +export const ProjectConfig = mod.ProjectConfig; +export const ProjectConfigManager = mod.ProjectConfigManager; +export const Tenant = mod.Tenant; +export const TenantAwareAuth = mod.TenantAwareAuth; +export const TenantManager = mod.TenantManager; +export const UserInfo = mod.UserInfo; +export const UserMetadata = mod.UserMetadata; +export const UserRecord = mod.UserRecord; +export const getAuth = mod.getAuth; diff --git a/node_modules/firebase-admin/lib/esm/data-connect/index.js b/node_modules/firebase-admin/lib/esm/data-connect/index.js new file mode 100644 index 0000000..2a01632 --- /dev/null +++ b/node_modules/firebase-admin/lib/esm/data-connect/index.js @@ -0,0 +1,5 @@ +import mod from "../../data-connect/index.js"; + +export const DataConnect = mod.DataConnect; +export const getDataConnect = mod.getDataConnect; +export const validateAdminArgs = mod.validateAdminArgs; diff --git a/node_modules/firebase-admin/lib/esm/database/index.js b/node_modules/firebase-admin/lib/esm/database/index.js new file mode 100644 index 0000000..a9a7f04 --- /dev/null +++ b/node_modules/firebase-admin/lib/esm/database/index.js @@ -0,0 +1,7 @@ +import mod from "../../database/index.js"; + +export const FirebaseDatabaseError = mod.FirebaseDatabaseError; +export const ServerValue = mod.ServerValue; +export const enableLogging = mod.enableLogging; +export const getDatabase = mod.getDatabase; +export const getDatabaseWithUrl = mod.getDatabaseWithUrl; diff --git a/node_modules/firebase-admin/lib/esm/eventarc/index.js b/node_modules/firebase-admin/lib/esm/eventarc/index.js new file mode 100644 index 0000000..36920da --- /dev/null +++ b/node_modules/firebase-admin/lib/esm/eventarc/index.js @@ -0,0 +1,5 @@ +import mod from "../../eventarc/index.js"; + +export const Channel = mod.Channel; +export const Eventarc = mod.Eventarc; +export const getEventarc = mod.getEventarc; diff --git a/node_modules/firebase-admin/lib/esm/extensions/index.js b/node_modules/firebase-admin/lib/esm/extensions/index.js new file mode 100644 index 0000000..3f03f68 --- /dev/null +++ b/node_modules/firebase-admin/lib/esm/extensions/index.js @@ -0,0 +1,5 @@ +import mod from "../../extensions/index.js"; + +export const Extensions = mod.Extensions; +export const Runtime = mod.Runtime; +export const getExtensions = mod.getExtensions; diff --git a/node_modules/firebase-admin/lib/esm/firestore/index.js b/node_modules/firebase-admin/lib/esm/firestore/index.js new file mode 100644 index 0000000..a0f1efb --- /dev/null +++ b/node_modules/firebase-admin/lib/esm/firestore/index.js @@ -0,0 +1,30 @@ +import mod from "../../firestore/index.js"; + +export const AggregateField = mod.AggregateField; +export const AggregateQuery = mod.AggregateQuery; +export const AggregateQuerySnapshot = mod.AggregateQuerySnapshot; +export const BulkWriter = mod.BulkWriter; +export const BundleBuilder = mod.BundleBuilder; +export const CollectionGroup = mod.CollectionGroup; +export const CollectionReference = mod.CollectionReference; +export const DocumentReference = mod.DocumentReference; +export const DocumentSnapshot = mod.DocumentSnapshot; +export const FieldPath = mod.FieldPath; +export const FieldValue = mod.FieldValue; +export const Filter = mod.Filter; +export const FirebaseFirestoreError = mod.FirebaseFirestoreError; +export const Firestore = mod.Firestore; +export const GeoPoint = mod.GeoPoint; +export const GrpcStatus = mod.GrpcStatus; +export const Query = mod.Query; +export const QueryDocumentSnapshot = mod.QueryDocumentSnapshot; +export const QueryPartition = mod.QueryPartition; +export const QuerySnapshot = mod.QuerySnapshot; +export const Timestamp = mod.Timestamp; +export const Transaction = mod.Transaction; +export const WriteBatch = mod.WriteBatch; +export const WriteResult = mod.WriteResult; +export const getFirestore = mod.getFirestore; +export const initializeFirestore = mod.initializeFirestore; +export const setLogFunction = mod.setLogFunction; +export const v1 = mod.v1; diff --git a/node_modules/firebase-admin/lib/esm/functions/index.js b/node_modules/firebase-admin/lib/esm/functions/index.js new file mode 100644 index 0000000..bc29847 --- /dev/null +++ b/node_modules/firebase-admin/lib/esm/functions/index.js @@ -0,0 +1,5 @@ +import mod from "../../functions/index.js"; + +export const Functions = mod.Functions; +export const TaskQueue = mod.TaskQueue; +export const getFunctions = mod.getFunctions; diff --git a/node_modules/firebase-admin/lib/esm/installations/index.js b/node_modules/firebase-admin/lib/esm/installations/index.js new file mode 100644 index 0000000..3eab368 --- /dev/null +++ b/node_modules/firebase-admin/lib/esm/installations/index.js @@ -0,0 +1,6 @@ +import mod from "../../installations/index.js"; + +export const FirebaseInstallationsError = mod.FirebaseInstallationsError; +export const Installations = mod.Installations; +export const InstallationsClientErrorCode = mod.InstallationsClientErrorCode; +export const getInstallations = mod.getInstallations; diff --git a/node_modules/firebase-admin/lib/esm/instance-id/index.js b/node_modules/firebase-admin/lib/esm/instance-id/index.js new file mode 100644 index 0000000..8024cf5 --- /dev/null +++ b/node_modules/firebase-admin/lib/esm/instance-id/index.js @@ -0,0 +1,6 @@ +import mod from "../../instance-id/index.js"; + +export const FirebaseInstanceIdError = mod.FirebaseInstanceIdError; +export const InstanceId = mod.InstanceId; +export const InstanceIdClientErrorCode = mod.InstanceIdClientErrorCode; +export const getInstanceId = mod.getInstanceId; diff --git a/node_modules/firebase-admin/lib/esm/machine-learning/index.js b/node_modules/firebase-admin/lib/esm/machine-learning/index.js new file mode 100644 index 0000000..da7f62c --- /dev/null +++ b/node_modules/firebase-admin/lib/esm/machine-learning/index.js @@ -0,0 +1,5 @@ +import mod from "../../machine-learning/index.js"; + +export const MachineLearning = mod.MachineLearning; +export const Model = mod.Model; +export const getMachineLearning = mod.getMachineLearning; diff --git a/node_modules/firebase-admin/lib/esm/messaging/index.js b/node_modules/firebase-admin/lib/esm/messaging/index.js new file mode 100644 index 0000000..9aa93ac --- /dev/null +++ b/node_modules/firebase-admin/lib/esm/messaging/index.js @@ -0,0 +1,6 @@ +import mod from "../../messaging/index.js"; + +export const FirebaseMessagingError = mod.FirebaseMessagingError; +export const Messaging = mod.Messaging; +export const MessagingClientErrorCode = mod.MessagingClientErrorCode; +export const getMessaging = mod.getMessaging; diff --git a/node_modules/firebase-admin/lib/esm/package.json b/node_modules/firebase-admin/lib/esm/package.json new file mode 100644 index 0000000..7c34deb --- /dev/null +++ b/node_modules/firebase-admin/lib/esm/package.json @@ -0,0 +1 @@ +{"type":"module"} \ No newline at end of file diff --git a/node_modules/firebase-admin/lib/esm/project-management/index.js b/node_modules/firebase-admin/lib/esm/project-management/index.js new file mode 100644 index 0000000..ae1a7d5 --- /dev/null +++ b/node_modules/firebase-admin/lib/esm/project-management/index.js @@ -0,0 +1,9 @@ +import mod from "../../project-management/index.js"; + +export const AndroidApp = mod.AndroidApp; +export const AppPlatform = mod.AppPlatform; +export const FirebaseProjectManagementError = mod.FirebaseProjectManagementError; +export const IosApp = mod.IosApp; +export const ProjectManagement = mod.ProjectManagement; +export const ShaCertificate = mod.ShaCertificate; +export const getProjectManagement = mod.getProjectManagement; diff --git a/node_modules/firebase-admin/lib/esm/remote-config/index.js b/node_modules/firebase-admin/lib/esm/remote-config/index.js new file mode 100644 index 0000000..3b3a7ea --- /dev/null +++ b/node_modules/firebase-admin/lib/esm/remote-config/index.js @@ -0,0 +1,7 @@ +import mod from "../../remote-config/index.js"; + +export const CustomSignalOperator = mod.CustomSignalOperator; +export const PercentConditionOperator = mod.PercentConditionOperator; +export const RemoteConfig = mod.RemoteConfig; +export const RemoteConfigFetchResponse = mod.RemoteConfigFetchResponse; +export const getRemoteConfig = mod.getRemoteConfig; diff --git a/node_modules/firebase-admin/lib/esm/security-rules/index.js b/node_modules/firebase-admin/lib/esm/security-rules/index.js new file mode 100644 index 0000000..5540a47 --- /dev/null +++ b/node_modules/firebase-admin/lib/esm/security-rules/index.js @@ -0,0 +1,6 @@ +import mod from "../../security-rules/index.js"; + +export const Ruleset = mod.Ruleset; +export const RulesetMetadataList = mod.RulesetMetadataList; +export const SecurityRules = mod.SecurityRules; +export const getSecurityRules = mod.getSecurityRules; diff --git a/node_modules/firebase-admin/lib/esm/storage/index.js b/node_modules/firebase-admin/lib/esm/storage/index.js new file mode 100644 index 0000000..dbed1f6 --- /dev/null +++ b/node_modules/firebase-admin/lib/esm/storage/index.js @@ -0,0 +1,5 @@ +import mod from "../../storage/index.js"; + +export const Storage = mod.Storage; +export const getDownloadURL = mod.getDownloadURL; +export const getStorage = mod.getStorage; diff --git a/node_modules/firebase-admin/lib/eventarc/cloudevent.d.ts b/node_modules/firebase-admin/lib/eventarc/cloudevent.d.ts new file mode 100644 index 0000000..08a4469 --- /dev/null +++ b/node_modules/firebase-admin/lib/eventarc/cloudevent.d.ts @@ -0,0 +1,84 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A CloudEvent version. + */ +export type CloudEventVersion = '1.0'; +/** + * A CloudEvent describes event data. + * + * @see https://github.com/cloudevents/spec/blob/v1.0/spec.md + */ +export interface CloudEvent { + /** + * Identifier for the event. If not provided, it is auto-populated with a UUID. + * + * @see https://github.com/cloudevents/spec/blob/v1.0/spec.md#id + */ + id?: string; + /** + * Identifies the context in which an event happened. If not provided, the value of `EVENTARC_CLOUD_EVENT_SOURCE` + * environment variable is used and if that is not set, a validation error is thrown. + * + * @see https://github.com/cloudevents/spec/blob/v1.0/spec.md#source-1 + */ + source?: string; + /** + * The version of the CloudEvents specification which the event uses. If not provided, is set to `1.0` -- + * the only supported value. + * + * @see https://github.com/cloudevents/spec/blob/v1.0/spec.md#specversion + */ + specversion?: CloudEventVersion; + /** + * Type of the event. Should be prefixed with a reverse-DNS name (`com.my-org.v1.something.happended`). + * + * @see https://github.com/cloudevents/spec/blob/v1.0/spec.md#type + */ + type: string; + /** + * Subject (context) of the event in the context of the event producer. + * + * @see https://github.com/cloudevents/spec/blob/v1.0/spec.md#subject + */ + subject?: string; + /** + * MIME type of the data being sent with the event in the `data` field. Only `application/json` and `text/plain` + * are currently supported. If not specified, it is automatically inferred from the type of provided data. + * + * @see https://github.com/cloudevents/spec/blob/v1.0/spec.md#datacontenttype + */ + datacontenttype?: string; + /** + * Timestamp of the event. Must be in ISO time format. If not specified, current time (at the moment of publishing) + * is used. + * + * @see https://github.com/cloudevents/spec/blob/v1.0/spec.md#time + */ + time?: string; + /** + * Data payload of the event. Objects are stringified with JSON and strings are be passed along as-is. + */ + data?: object | string; + /** + * Custom attributes/extensions. Must be strings. Added to the event as is. + * + * @see https://github.com/cloudevents/spec/blob/v1.0/spec.md#extension-context-attributes + */ + [key: string]: any; +} diff --git a/node_modules/firebase-admin/lib/eventarc/cloudevent.js b/node_modules/firebase-admin/lib/eventarc/cloudevent.js new file mode 100644 index 0000000..ab5ec4a --- /dev/null +++ b/node_modules/firebase-admin/lib/eventarc/cloudevent.js @@ -0,0 +1,19 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/firebase-admin/lib/eventarc/eventarc-client-internal.d.ts b/node_modules/firebase-admin/lib/eventarc/eventarc-client-internal.d.ts new file mode 100644 index 0000000..fa1d824 --- /dev/null +++ b/node_modules/firebase-admin/lib/eventarc/eventarc-client-internal.d.ts @@ -0,0 +1,18 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/firebase-admin/lib/eventarc/eventarc-client-internal.js b/node_modules/firebase-admin/lib/eventarc/eventarc-client-internal.js new file mode 100644 index 0000000..2db1399 --- /dev/null +++ b/node_modules/firebase-admin/lib/eventarc/eventarc-client-internal.js @@ -0,0 +1,139 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EventarcApiClient = void 0; +const validator = require("../utils/validator"); +const eventarc_utils_1 = require("./eventarc-utils"); +const api_request_1 = require("../utils/api-request"); +const utils = require("../utils"); +const error_1 = require("../utils/error"); +const EVENTARC_API = 'https://eventarcpublishing.googleapis.com/v1'; +const FIREBASE_VERSION_HEADER = { + 'X-Firebase-Client': `fire-admin-node/${utils.getSdkVersion()}`, +}; +const CHANNEL_NAME_REGEX = /^(projects\/([^/]+)\/)?locations\/([^/]+)\/channels\/([^/]+)$/; +const DEFAULT_CHANNEL_REGION = 'us-central1'; +/** + * Class that facilitates sending requests to the Eventarc backend API. + * + * @internal + */ +class EventarcApiClient { + constructor(app, channel) { + this.app = app; + this.channel = channel; + if (!validator.isNonNullObject(app) || !('options' in app)) { + throw new eventarc_utils_1.FirebaseEventarcError('invalid-argument', 'First argument passed to Channel() must be a valid Eventarc service instance.'); + } + this.httpClient = new api_request_1.AuthorizedHttpClient(app); + this.resolvedChannelName = this.resolveChannelName(channel.name); + } + getProjectId() { + if (this.projectId) { + return Promise.resolve(this.projectId); + } + return utils.findProjectId(this.app) + .then((projectId) => { + if (!validator.isNonEmptyString(projectId)) { + throw new eventarc_utils_1.FirebaseEventarcError('unknown-error', 'Failed to determine project ID. Initialize the ' + + 'SDK with service account credentials or set project ID as an app option. ' + + 'Alternatively, set the GOOGLE_CLOUD_PROJECT environment variable.'); + } + this.projectId = projectId; + return projectId; + }); + } + /** + * Publishes provided events to this channel. If channel was created with `allowedEventsTypes` and event type + * is not on that list, the event is ignored. + * + * The following CloudEvent fields are auto-populated if not set: + * * specversion - `1.0` + * * id - uuidv4() + * * source - populated with `process.env.EVENTARC_CLOUD_EVENT_SOURCE` and + * if not set an error is thrown. + * + * @param events - CloudEvent to publish to the channel. + */ + async publish(events) { + if (!Array.isArray(events)) { + events = [events]; + } + return this.publishToEventarcApi(await this.resolvedChannelName, events + .filter(e => typeof this.channel.allowedEventTypes === 'undefined' || + this.channel.allowedEventTypes.includes(e.type)) + .map(eventarc_utils_1.toCloudEventProtoFormat)); + } + async publishToEventarcApi(channel, events) { + if (events.length === 0) { + return; + } + const request = { + method: 'POST', + url: `${this.getEventarcHost()}/${channel}:publishEvents`, + data: JSON.stringify({ events }), + }; + return this.sendRequest(request); + } + sendRequest(request) { + request.headers = FIREBASE_VERSION_HEADER; + return this.httpClient.send(request) + .then(() => undefined) + .catch((err) => { + throw this.toFirebaseError(err); + }); + } + toFirebaseError(err) { + if (err instanceof error_1.PrefixedFirebaseError) { + return err; + } + const response = err.response; + return new eventarc_utils_1.FirebaseEventarcError('unknown-error', `Unexpected response with status: ${response.status} and body: ${response.text}`); + } + resolveChannelName(name) { + if (!name.includes('/')) { + const location = DEFAULT_CHANNEL_REGION; + const channelId = name; + return this.resolveChannelNameProjectId(location, channelId); + } + else { + const match = CHANNEL_NAME_REGEX.exec(name); + if (match === null || match.length < 4) { + throw new eventarc_utils_1.FirebaseEventarcError('invalid-argument', 'Invalid channel name format.'); + } + const projectId = match[2]; + const location = match[3]; + const channelId = match[4]; + if (validator.isNonEmptyString(projectId)) { + return Promise.resolve(`projects/${projectId}/locations/${location}/channels/${channelId}`); + } + else { + return this.resolveChannelNameProjectId(location, channelId); + } + } + } + async resolveChannelNameProjectId(location, channelId) { + const projectId = await this.getProjectId(); + return `projects/${projectId}/locations/${location}/channels/${channelId}`; + } + getEventarcHost() { + return process.env.CLOUD_EVENTARC_EMULATOR_HOST ?? EVENTARC_API; + } +} +exports.EventarcApiClient = EventarcApiClient; diff --git a/node_modules/firebase-admin/lib/eventarc/eventarc-utils.d.ts b/node_modules/firebase-admin/lib/eventarc/eventarc-utils.d.ts new file mode 100644 index 0000000..b835cc3 --- /dev/null +++ b/node_modules/firebase-admin/lib/eventarc/eventarc-utils.d.ts @@ -0,0 +1,31 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { PrefixedFirebaseError } from '../utils/error'; +import { CloudEvent } from './cloudevent'; +export type EventarcErrorCode = 'unknown-error' | 'invalid-argument'; +/** + * Firebase Eventarc error code structure. This extends PrefixedFirebaseError. + * + * @param code - The error code. + * @param message - The error message. + * @constructor + */ +export declare class FirebaseEventarcError extends PrefixedFirebaseError { + constructor(code: EventarcErrorCode, message: string); +} +export declare function toCloudEventProtoFormat(ce: CloudEvent): any; diff --git a/node_modules/firebase-admin/lib/eventarc/eventarc-utils.js b/node_modules/firebase-admin/lib/eventarc/eventarc-utils.js new file mode 100644 index 0000000..608ccde --- /dev/null +++ b/node_modules/firebase-admin/lib/eventarc/eventarc-utils.js @@ -0,0 +1,125 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirebaseEventarcError = void 0; +exports.toCloudEventProtoFormat = toCloudEventProtoFormat; +const error_1 = require("../utils/error"); +const uuid_1 = require("uuid"); +const validator = require("../utils/validator"); +// List of CloudEvent properties that are handled "by hand" and should be skipped by +// automatic attribute copy. +const TOP_LEVEL_CE_ATTRS = ['id', 'type', 'specversion', 'source', 'data', 'time', 'datacontenttype', 'subject']; +/** + * Firebase Eventarc error code structure. This extends PrefixedFirebaseError. + * + * @param code - The error code. + * @param message - The error message. + * @constructor + */ +class FirebaseEventarcError extends error_1.PrefixedFirebaseError { + constructor(code, message) { + super('eventarc', code, message); + } +} +exports.FirebaseEventarcError = FirebaseEventarcError; +function toCloudEventProtoFormat(ce) { + const source = ce.source ?? process.env.EVENTARC_CLOUD_EVENT_SOURCE; + if (typeof source === 'undefined' || !validator.isNonEmptyString(source)) { + throw new FirebaseEventarcError('invalid-argument', "CloudEvent 'source' is required."); + } + if (!validator.isNonEmptyString(ce.type)) { + throw new FirebaseEventarcError('invalid-argument', "CloudEvent 'type' is required."); + } + const out = { + '@type': 'type.googleapis.com/io.cloudevents.v1.CloudEvent', + 'id': ce.id ?? (0, uuid_1.v4)(), + 'type': ce.type, + 'specVersion': ce.specversion ?? '1.0', + 'source': source + }; + if (typeof ce.time !== 'undefined') { + if (!validator.isISODateString(ce.time)) { + throw new FirebaseEventarcError('invalid-argument', "CloudEvent 'tyme' must be in ISO date format."); + } + setAttribute(out, 'time', { + 'ceTimestamp': ce.time + }); + } + else { + setAttribute(out, 'time', { + 'ceTimestamp': new Date().toISOString() + }); + } + if (typeof ce.datacontenttype !== 'undefined') { + if (!validator.isNonEmptyString(ce.datacontenttype)) { + throw new FirebaseEventarcError('invalid-argument', "CloudEvent 'datacontenttype' if specified must be non-empty string."); + } + setAttribute(out, 'datacontenttype', { + 'ceString': ce.datacontenttype + }); + } + if (ce.subject) { + if (!validator.isNonEmptyString(ce.subject)) { + throw new FirebaseEventarcError('invalid-argument', "CloudEvent 'subject' if specified must be non-empty string."); + } + setAttribute(out, 'subject', { + 'ceString': ce.subject + }); + } + if (typeof ce.data === 'undefined') { + throw new FirebaseEventarcError('invalid-argument', "CloudEvent 'data' is required."); + } + if (validator.isObject(ce.data)) { + out['textData'] = JSON.stringify(ce.data); + if (!ce.datacontenttype) { + setAttribute(out, 'datacontenttype', { + 'ceString': 'application/json' + }); + } + } + else if (validator.isNonEmptyString(ce.data)) { + out['textData'] = ce.data; + if (!ce.datacontenttype) { + setAttribute(out, 'datacontenttype', { + 'ceString': 'text/plain' + }); + } + } + else { + throw new FirebaseEventarcError('invalid-argument', `CloudEvent 'data' must be string or an object (which are converted to JSON), got '${typeof ce.data}'.`); + } + for (const attr in ce) { + if (TOP_LEVEL_CE_ATTRS.includes(attr)) { + continue; + } + if (!validator.isNonEmptyString(ce[attr])) { + throw new FirebaseEventarcError('invalid-argument', `CloudEvent extension attributes ('${attr}') must be string.`); + } + setAttribute(out, attr, { + 'ceString': ce[attr] + }); + } + return out; +} +function setAttribute(event, attr, value) { + if (!Object.prototype.hasOwnProperty.call(event, 'attributes')) { + event.attributes = {}; + } + event['attributes'][attr] = value; +} diff --git a/node_modules/firebase-admin/lib/eventarc/eventarc.d.ts b/node_modules/firebase-admin/lib/eventarc/eventarc.d.ts new file mode 100644 index 0000000..76a7d79 --- /dev/null +++ b/node_modules/firebase-admin/lib/eventarc/eventarc.d.ts @@ -0,0 +1,107 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +import { CloudEvent } from './cloudevent'; +/** + * Channel options interface. + */ +export interface ChannelOptions { + /** + * An array of allowed event types. If specified, publishing events of + * unknown types is a no op. When not provided, no event filtering is + * performed. + */ + allowedEventTypes?: string[] | string | undefined; +} +/** + * Eventarc service bound to the provided app. + */ +export declare class Eventarc { + private readonly appInternal; + /** + * The {@link firebase-admin.app#App} associated with the current Eventarc service + * instance. + * + * @example + * ```javascript + * var app = eventarc.app; + * ``` + */ + get app(): App; + /** + * Creates a reference to the Eventarc channel using the provided channel resource name. + * The channel resource name can be either: + * + * - A fully qualified channel resource name: + * `projects/{project}/locations/{location}/channels/{channel-id}` + * + * - A partial resource name with location and channel ID, in which case + * the runtime project ID of the function is used: + * `locations/{location}/channels/{channel-id}` + * + * - A partial channel ID, in which case the runtime project ID of the + * function and `us-central1` as location is used: + * `{channel-id}` + * + * @param name - Channel resource name. + * @param options - (optional) additional channel options + * @returns An Eventarc channel reference for publishing events. + */ + channel(name: string, options?: ChannelOptions): Channel; + /** + * Create a reference to the default Firebase channel: + * `locations/us-central1/channels/firebase` + * + * @param options - (optional) additional channel options + * @returns Eventarc channel reference for publishing events. + */ + channel(options?: ChannelOptions): Channel; +} +/** + * Eventarc Channel. + */ +export declare class Channel { + private readonly eventarcInternal; + private nameInternal; + /** + * List of event types allowed by this channel for publishing. Other event types are ignored. + */ + readonly allowedEventTypes?: string[]; + private readonly client; + /** + * The {@link firebase-admin.eventarc#Eventarc} service instance associated with the current `Channel`. + * + * @example + * ```javascript + * var app = channel.eventarc; + * ``` + */ + get eventarc(): Eventarc; + /** + * The channel name as provided during channel creation. If it was not specifed, the default channel name is returned + * ('locations/us-central1/channels/firebase'). + */ + get name(): string; + /** + * Publishes provided events to this channel. If channel was created with `allowedEventTypes` and event type is not + * on that list, the event is ignored. + * + * @param events - CloudEvent to publish to the channel. + */ + publish(events: CloudEvent | CloudEvent[]): Promise; +} diff --git a/node_modules/firebase-admin/lib/eventarc/eventarc.js b/node_modules/firebase-admin/lib/eventarc/eventarc.js new file mode 100644 index 0000000..91d952d --- /dev/null +++ b/node_modules/firebase-admin/lib/eventarc/eventarc.js @@ -0,0 +1,125 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Channel = exports.Eventarc = void 0; +const validator = require("../utils/validator"); +const eventarc_utils_1 = require("./eventarc-utils"); +const eventarc_client_internal_1 = require("./eventarc-client-internal"); +/** + * Eventarc service bound to the provided app. + */ +class Eventarc { + /** + * @internal + */ + constructor(app) { + if (!validator.isNonNullObject(app) || !('options' in app)) { + throw new eventarc_utils_1.FirebaseEventarcError('invalid-argument', 'First argument passed to Eventarc() must be a valid Firebase app instance.'); + } + this.appInternal = app; + } + /** + * The {@link firebase-admin.app#App} associated with the current Eventarc service + * instance. + * + * @example + * ```javascript + * var app = eventarc.app; + * ``` + */ + get app() { + return this.appInternal; + } + channel(nameOrOptions, options) { + let channel; + let opts; + if (validator.isNonEmptyString(nameOrOptions)) { + channel = nameOrOptions; + } + else { + channel = 'locations/us-central1/channels/firebase'; + } + if (validator.isNonNullObject(nameOrOptions)) { + opts = nameOrOptions; + } + else { + opts = options; + } + let allowedEventTypes = undefined; + if (typeof opts?.allowedEventTypes === 'string') { + allowedEventTypes = opts.allowedEventTypes.split(','); + } + else if (validator.isArray(opts?.allowedEventTypes)) { + allowedEventTypes = opts?.allowedEventTypes; + } + else if (typeof opts?.allowedEventTypes !== 'undefined') { + throw new eventarc_utils_1.FirebaseEventarcError('invalid-argument', 'AllowedEventTypes must be either an array of strings or a comma separated string.'); + } + return new Channel(this, channel, allowedEventTypes); + } +} +exports.Eventarc = Eventarc; +/** + * Eventarc Channel. + */ +class Channel { + /** + * @internal + */ + constructor(eventarc, name, allowedEventTypes) { + if (!validator.isNonNullObject(eventarc)) { + throw new eventarc_utils_1.FirebaseEventarcError('invalid-argument', 'First argument passed to Channel() must be a valid Eventarc service instance.'); + } + if (!validator.isNonEmptyString(name)) { + throw new eventarc_utils_1.FirebaseEventarcError('invalid-argument', 'name is required.'); + } + this.nameInternal = name; + this.eventarcInternal = eventarc; + this.allowedEventTypes = allowedEventTypes; + this.client = new eventarc_client_internal_1.EventarcApiClient(eventarc.app, this); + } + /** + * The {@link firebase-admin.eventarc#Eventarc} service instance associated with the current `Channel`. + * + * @example + * ```javascript + * var app = channel.eventarc; + * ``` + */ + get eventarc() { + return this.eventarcInternal; + } + /** + * The channel name as provided during channel creation. If it was not specifed, the default channel name is returned + * ('locations/us-central1/channels/firebase'). + */ + get name() { + return this.nameInternal; + } + /** + * Publishes provided events to this channel. If channel was created with `allowedEventTypes` and event type is not + * on that list, the event is ignored. + * + * @param events - CloudEvent to publish to the channel. + */ + publish(events) { + return this.client.publish(events); + } +} +exports.Channel = Channel; diff --git a/node_modules/firebase-admin/lib/eventarc/index.d.ts b/node_modules/firebase-admin/lib/eventarc/index.d.ts new file mode 100644 index 0000000..7227344 --- /dev/null +++ b/node_modules/firebase-admin/lib/eventarc/index.d.ts @@ -0,0 +1,53 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Firebase Eventarc. + * + * @packageDocumentation + */ +import { App } from '../app'; +import { Eventarc } from './eventarc'; +export { CloudEvent, CloudEventVersion } from './cloudevent'; +export { Eventarc, Channel, ChannelOptions } from './eventarc'; +/** + * Gets the {@link Eventarc} service for the default app or a given app. + * + * `getEventarc()` can be called with no arguments to access the default + * app's `Eventarc` service or as `getEventarc(app)` to access the + * `Eventarc` service associated with specific app. + * + * @example + * ```javascript + * // Get the Eventarc service for the default app + * const defaultEventarc = getEventarc(); + * ``` + * + * @example + * ```javascript + * // Get the Eventarc service for a given app + * const otherEventarc = getEventarc(otherApp); + * ``` + * + * @param app - Optional app whose `Eventarc` service will be returned. + * If not provided, the default `Eventarc` service will be returned. + * + * @returns The default `Eventarc` service if no + * app is provided or the `Eventarc` service associated with the provided + * app. + */ +export declare function getEventarc(app?: App): Eventarc; diff --git a/node_modules/firebase-admin/lib/eventarc/index.js b/node_modules/firebase-admin/lib/eventarc/index.js new file mode 100644 index 0000000..5cf4c8c --- /dev/null +++ b/node_modules/firebase-admin/lib/eventarc/index.js @@ -0,0 +1,64 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Channel = exports.Eventarc = void 0; +exports.getEventarc = getEventarc; +/** + * Firebase Eventarc. + * + * @packageDocumentation + */ +const app_1 = require("../app"); +const eventarc_1 = require("./eventarc"); +var eventarc_2 = require("./eventarc"); +Object.defineProperty(exports, "Eventarc", { enumerable: true, get: function () { return eventarc_2.Eventarc; } }); +Object.defineProperty(exports, "Channel", { enumerable: true, get: function () { return eventarc_2.Channel; } }); +/** + * Gets the {@link Eventarc} service for the default app or a given app. + * + * `getEventarc()` can be called with no arguments to access the default + * app's `Eventarc` service or as `getEventarc(app)` to access the + * `Eventarc` service associated with specific app. + * + * @example + * ```javascript + * // Get the Eventarc service for the default app + * const defaultEventarc = getEventarc(); + * ``` + * + * @example + * ```javascript + * // Get the Eventarc service for a given app + * const otherEventarc = getEventarc(otherApp); + * ``` + * + * @param app - Optional app whose `Eventarc` service will be returned. + * If not provided, the default `Eventarc` service will be returned. + * + * @returns The default `Eventarc` service if no + * app is provided or the `Eventarc` service associated with the provided + * app. + */ +function getEventarc(app) { + if (typeof app === 'undefined') { + app = (0, app_1.getApp)(); + } + const firebaseApp = app; + return firebaseApp.getOrInitService('eventarc', (app) => new eventarc_1.Eventarc(app)); +} diff --git a/node_modules/firebase-admin/lib/extensions/extensions-api-client-internal.d.ts b/node_modules/firebase-admin/lib/extensions/extensions-api-client-internal.d.ts new file mode 100644 index 0000000..c706bb9 --- /dev/null +++ b/node_modules/firebase-admin/lib/extensions/extensions-api-client-internal.d.ts @@ -0,0 +1,30 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { PrefixedFirebaseError } from '../utils/error'; +type ExtensionsErrorCode = 'invalid-argument' | 'not-found' | 'forbidden' | 'internal-error' | 'unknown-error'; +/** + * Firebase Extensions error code structure. This extends PrefixedFirebaseError. + * + * @param code - The error code. + * @param message - The error message. + * @constructor + */ +export declare class FirebaseExtensionsError extends PrefixedFirebaseError { + constructor(code: ExtensionsErrorCode, message: string); +} +export {}; diff --git a/node_modules/firebase-admin/lib/extensions/extensions-api-client-internal.js b/node_modules/firebase-admin/lib/extensions/extensions-api-client-internal.js new file mode 100644 index 0000000..e53573f --- /dev/null +++ b/node_modules/firebase-admin/lib/extensions/extensions-api-client-internal.js @@ -0,0 +1,105 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirebaseExtensionsError = exports.ExtensionsApiClient = void 0; +const api_request_1 = require("../utils/api-request"); +const error_1 = require("../utils/error"); +const validator = require("../utils/validator"); +const utils = require("../utils"); +const FIREBASE_FUNCTIONS_CONFIG_HEADERS = { + 'X-Firebase-Client': `fire-admin-node/${utils.getSdkVersion()}` +}; +const EXTENSIONS_API_VERSION = 'v1beta'; +// Note - use getExtensionsApiUri() instead so that changing environments is consistent. +const EXTENSIONS_URL = 'https://firebaseextensions.googleapis.com'; +/** + * Class that facilitates sending requests to the Firebase Extensions backend API. + * + * @internal + */ +class ExtensionsApiClient { + constructor(app) { + this.app = app; + if (!validator.isNonNullObject(app) || !('options' in app)) { + throw new error_1.FirebaseAppError('invalid-argument', 'First argument passed to getExtensions() must be a valid Firebase app instance.'); + } + this.httpClient = new api_request_1.AuthorizedHttpClient(this.app); + } + async updateRuntimeData(projectId, instanceId, runtimeData) { + const url = this.getRuntimeDataUri(projectId, instanceId); + const request = { + method: 'PATCH', + url, + headers: FIREBASE_FUNCTIONS_CONFIG_HEADERS, + data: runtimeData, + }; + try { + const res = await this.httpClient.send(request); + return res.data; + } + catch (err) { + throw this.toFirebaseError(err); + } + } + getExtensionsApiUri() { + return process.env['FIREBASE_EXT_URL'] ?? EXTENSIONS_URL; + } + getRuntimeDataUri(projectId, instanceId) { + return `${this.getExtensionsApiUri()}/${EXTENSIONS_API_VERSION}/projects/${projectId}/instances/${instanceId}/runtimeData`; + } + toFirebaseError(err) { + if (err instanceof error_1.PrefixedFirebaseError) { + return err; + } + const response = err.response; + if (!response?.isJson()) { + return new FirebaseExtensionsError('unknown-error', `Unexpected response with status: ${response.status} and body: ${response.text}`); + } + const error = response.data?.error; + const message = error?.message || `Unknown server error: ${response.text}`; + switch (error.code) { + case 403: + return new FirebaseExtensionsError('forbidden', message); + case 404: + return new FirebaseExtensionsError('not-found', message); + case 500: + return new FirebaseExtensionsError('internal-error', message); + } + return new FirebaseExtensionsError('unknown-error', message); + } +} +exports.ExtensionsApiClient = ExtensionsApiClient; +/** + * Firebase Extensions error code structure. This extends PrefixedFirebaseError. + * + * @param code - The error code. + * @param message - The error message. + * @constructor + */ +class FirebaseExtensionsError extends error_1.PrefixedFirebaseError { + constructor(code, message) { + super('Extensions', code, message); + /* tslint:disable:max-line-length */ + // Set the prototype explicitly. See the following link for more details: + // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work + /* tslint:enable:max-line-length */ + this.__proto__ = FirebaseExtensionsError.prototype; + } +} +exports.FirebaseExtensionsError = FirebaseExtensionsError; diff --git a/node_modules/firebase-admin/lib/extensions/extensions-api.d.ts b/node_modules/firebase-admin/lib/extensions/extensions-api.d.ts new file mode 100644 index 0000000..9b139e5 --- /dev/null +++ b/node_modules/firebase-admin/lib/extensions/extensions-api.d.ts @@ -0,0 +1,44 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * `SettableProcessingState` represents all the processing states that can be set + * on an Extension instance's runtime data. + * + * @remarks + * You can set the following states: + * + * - `NONE`: No relevant lifecycle event work has been done. + * Set this to clear out old statuses. + * + * - `PROCESSING_COMPLETE`: Lifecycle event work completed with no errors. + * + * - `PROCESSING_WARNING`: Lifecycle event work succeeded partially, or + * something happened that the user should be warned about. + * + * - `PROCESSING_FAILED`: Lifecycle event work failed completely, but the + * instance will still work correctly going forward. + * + * If the extension instance is in a broken state due to errors, instead call + * {@link Runtime.setFatalError}. + * + * The "processing" state gets set automatically when a lifecycle event handler + * starts; you can't set it explicitly. + * To report the ongoing status of an extension's function, use `console.log` + * or the Cloud Functions logger SDK. + */ +export type SettableProcessingState = 'NONE' | 'PROCESSING_COMPLETE' | 'PROCESSING_WARNING' | 'PROCESSING_FAILED'; diff --git a/node_modules/firebase-admin/lib/extensions/extensions-api.js b/node_modules/firebase-admin/lib/extensions/extensions-api.js new file mode 100644 index 0000000..ab5ec4a --- /dev/null +++ b/node_modules/firebase-admin/lib/extensions/extensions-api.js @@ -0,0 +1,19 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/firebase-admin/lib/extensions/extensions.d.ts b/node_modules/firebase-admin/lib/extensions/extensions.d.ts new file mode 100644 index 0000000..eb37d55 --- /dev/null +++ b/node_modules/firebase-admin/lib/extensions/extensions.d.ts @@ -0,0 +1,73 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +import { SettableProcessingState } from './extensions-api'; +/** + * The Firebase `Extensions` service interface. + */ +export declare class Extensions { + readonly app: App; + private readonly client; + /** + * The runtime() method returns a new Runtime, which provides methods to modify an extension instance's runtime data. + * + * @remarks + * This method will throw an error if called outside an Extensions environment. + * + * @returns A new {@link Runtime} object. + */ + runtime(): Runtime; +} +/** + * Runtime provides methods to modify an extension instance's runtime data. + */ +export declare class Runtime { + private projectId; + private extensionInstanceId; + private readonly client; + /** + * Sets the processing state of an extension instance. + * + * @remarks + * Use this method to report the results of a lifecycle event handler. + * + * If the lifecycle event failed & the extension instance will no longer work + * correctly, use {@link Runtime.setFatalError} instead. + * + * To report the status of function calls other than lifecycle event handlers, + * use `console.log` or the Cloud Functions logger SDK. + * + * @param state - The state to set the instance to. + * @param detailMessage - A message explaining the results of the lifecycle function. + */ + setProcessingState(state: SettableProcessingState, detailMessage: string): Promise; + /** + * Reports a fatal error while running a lifecycle event handler. + * + * @remarks + * Call this method when a lifecycle event handler fails in a way that makes + * the Instance inoperable. + * If the lifecycle event failed but the instance will still work as expected, + * call `setProcessingState` with the "PROCESSING_WARNING" or + * "PROCESSING_FAILED" state instead. + * + * @param errorMessage - A message explaining what went wrong and how to fix it. + */ + setFatalError(errorMessage: string): Promise; + private getProjectId; +} diff --git a/node_modules/firebase-admin/lib/extensions/extensions.js b/node_modules/firebase-admin/lib/extensions/extensions.js new file mode 100644 index 0000000..6332731 --- /dev/null +++ b/node_modules/firebase-admin/lib/extensions/extensions.js @@ -0,0 +1,122 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Runtime = exports.Extensions = void 0; +const extensions_api_client_internal_1 = require("./extensions-api-client-internal"); +const validator = require("../utils/validator"); +/** + * The Firebase `Extensions` service interface. + */ +class Extensions { + /** + * @param app - The app for this `Extensions` service. + * @constructor + * @internal + */ + constructor(app) { + this.app = app; + this.client = new extensions_api_client_internal_1.ExtensionsApiClient(app); + } + /** + * The runtime() method returns a new Runtime, which provides methods to modify an extension instance's runtime data. + * + * @remarks + * This method will throw an error if called outside an Extensions environment. + * + * @returns A new {@link Runtime} object. + */ + runtime() { + return new Runtime(this.client); + } +} +exports.Extensions = Extensions; +/** + * Runtime provides methods to modify an extension instance's runtime data. + */ +class Runtime { + /** + * @param client - The API client for this `Runtime` service. + * @constructor + * @internal + */ + constructor(client) { + this.projectId = this.getProjectId(); + if (!validator.isNonEmptyString(process.env['EXT_INSTANCE_ID'])) { + throw new extensions_api_client_internal_1.FirebaseExtensionsError('invalid-argument', 'Runtime is only available from within a running Extension instance.'); + } + this.extensionInstanceId = process.env['EXT_INSTANCE_ID']; + if (!validator.isNonNullObject(client) || !('updateRuntimeData' in client)) { + throw new extensions_api_client_internal_1.FirebaseExtensionsError('invalid-argument', 'Must provide a valid ExtensionsApiClient instance to create a new Runtime.'); + } + this.client = client; + } + /** + * Sets the processing state of an extension instance. + * + * @remarks + * Use this method to report the results of a lifecycle event handler. + * + * If the lifecycle event failed & the extension instance will no longer work + * correctly, use {@link Runtime.setFatalError} instead. + * + * To report the status of function calls other than lifecycle event handlers, + * use `console.log` or the Cloud Functions logger SDK. + * + * @param state - The state to set the instance to. + * @param detailMessage - A message explaining the results of the lifecycle function. + */ + async setProcessingState(state, detailMessage) { + await this.client.updateRuntimeData(this.projectId, this.extensionInstanceId, { + processingState: { + state, + detailMessage, + }, + }); + } + /** + * Reports a fatal error while running a lifecycle event handler. + * + * @remarks + * Call this method when a lifecycle event handler fails in a way that makes + * the Instance inoperable. + * If the lifecycle event failed but the instance will still work as expected, + * call `setProcessingState` with the "PROCESSING_WARNING" or + * "PROCESSING_FAILED" state instead. + * + * @param errorMessage - A message explaining what went wrong and how to fix it. + */ + async setFatalError(errorMessage) { + if (!validator.isNonEmptyString(errorMessage)) { + throw new extensions_api_client_internal_1.FirebaseExtensionsError('invalid-argument', 'errorMessage must not be empty'); + } + await this.client.updateRuntimeData(this.projectId, this.extensionInstanceId, { + fatalError: { + errorMessage, + }, + }); + } + getProjectId() { + const projectId = process.env['PROJECT_ID']; + if (!validator.isNonEmptyString(projectId)) { + throw new extensions_api_client_internal_1.FirebaseExtensionsError('invalid-argument', 'PROJECT_ID must not be undefined in Extensions runtime environment'); + } + return projectId; + } +} +exports.Runtime = Runtime; diff --git a/node_modules/firebase-admin/lib/extensions/index.d.ts b/node_modules/firebase-admin/lib/extensions/index.d.ts new file mode 100644 index 0000000..855b7c8 --- /dev/null +++ b/node_modules/firebase-admin/lib/extensions/index.d.ts @@ -0,0 +1,53 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Firebase Extensions service. + * + * @packageDocumentation + */ +import { App } from '../app'; +import { Extensions } from './extensions'; +export { Extensions, Runtime } from './extensions'; +export { SettableProcessingState } from './extensions-api'; +/** + * Gets the {@link Extensions} service for the default app + * or a given app. + * + * `getExtensions()` can be called with no arguments to access the default + * app's `Extensions` service or as `getExtensions(app)` to access the + * `Extensions` service associated with a specific app. + * + * @example + * ```javascript + * // Get the `Extensions` service for the default app + * const defaultExtensions = getExtensions(); + * ``` + * + * @example + * ```javascript + * // Get the `Extensions` service for a given app + * const otherExtensions = getExtensions(otherApp); + * ``` + * + * @param app - Optional app for which to return the `Extensions` service. + * If not provided, the default `Extensions` service is returned. + * + * @returns The default `Extensions` service if no app is provided, or the `Extensions` + * service associated with the provided app. + */ +export declare function getExtensions(app?: App): Extensions; diff --git a/node_modules/firebase-admin/lib/extensions/index.js b/node_modules/firebase-admin/lib/extensions/index.js new file mode 100644 index 0000000..fc0c1c9 --- /dev/null +++ b/node_modules/firebase-admin/lib/extensions/index.js @@ -0,0 +1,64 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Runtime = exports.Extensions = void 0; +exports.getExtensions = getExtensions; +/** + * Firebase Extensions service. + * + * @packageDocumentation + */ +const app_1 = require("../app"); +const extensions_1 = require("./extensions"); +var extensions_2 = require("./extensions"); +Object.defineProperty(exports, "Extensions", { enumerable: true, get: function () { return extensions_2.Extensions; } }); +Object.defineProperty(exports, "Runtime", { enumerable: true, get: function () { return extensions_2.Runtime; } }); +/** + * Gets the {@link Extensions} service for the default app + * or a given app. + * + * `getExtensions()` can be called with no arguments to access the default + * app's `Extensions` service or as `getExtensions(app)` to access the + * `Extensions` service associated with a specific app. + * + * @example + * ```javascript + * // Get the `Extensions` service for the default app + * const defaultExtensions = getExtensions(); + * ``` + * + * @example + * ```javascript + * // Get the `Extensions` service for a given app + * const otherExtensions = getExtensions(otherApp); + * ``` + * + * @param app - Optional app for which to return the `Extensions` service. + * If not provided, the default `Extensions` service is returned. + * + * @returns The default `Extensions` service if no app is provided, or the `Extensions` + * service associated with the provided app. + */ +function getExtensions(app) { + if (typeof app === 'undefined') { + app = (0, app_1.getApp)(); + } + const firebaseApp = app; + return firebaseApp.getOrInitService('extensions', (app) => new extensions_1.Extensions(app)); +} diff --git a/node_modules/firebase-admin/lib/firebase-namespace-api.d.ts b/node_modules/firebase-admin/lib/firebase-namespace-api.d.ts new file mode 100644 index 0000000..370c639 --- /dev/null +++ b/node_modules/firebase-admin/lib/firebase-namespace-api.d.ts @@ -0,0 +1,91 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { appCheck } from './app-check/app-check-namespace'; +import { auth } from './auth/auth-namespace'; +import { database } from './database/database-namespace'; +import { firestore } from './firestore/firestore-namespace'; +import { instanceId } from './instance-id/instance-id-namespace'; +import { installations } from './installations/installations-namespace'; +import { machineLearning } from './machine-learning/machine-learning-namespace'; +import { messaging } from './messaging/messaging-namespace'; +import { projectManagement } from './project-management/project-management-namespace'; +import { remoteConfig } from './remote-config/remote-config-namespace'; +import { securityRules } from './security-rules/security-rules-namespace'; +import { storage } from './storage/storage-namespace'; +import { App as AppCore, AppOptions } from './app/index'; +export { AppOptions, FirebaseError, FirebaseArrayIndexError } from './app/index'; +export declare namespace app { + /** + * A Firebase app holds the initialization information for a collection of + * services. + * + * Do not call this constructor directly. Instead, use + * {@link firebase-admin.app#initializeApp} to create an app. + */ + interface App extends AppCore { + appCheck(): appCheck.AppCheck; + auth(): auth.Auth; + database(url?: string): database.Database; + firestore(): firestore.Firestore; + installations(): installations.Installations; + /** + * @deprecated Use {@link firebase-admin.installations#Installations} instead. + */ + instanceId(): instanceId.InstanceId; + machineLearning(): machineLearning.MachineLearning; + messaging(): messaging.Messaging; + projectManagement(): projectManagement.ProjectManagement; + remoteConfig(): remoteConfig.RemoteConfig; + securityRules(): securityRules.SecurityRules; + storage(): storage.Storage; + /** + * Renders this local `FirebaseApp` unusable and frees the resources of + * all associated services (though it does *not* clean up any backend + * resources). When running the SDK locally, this method + * must be called to ensure graceful termination of the process. + * + * @example + * ```javascript + * app.delete() + * .then(function() { + * console.log("App deleted successfully"); + * }) + * .catch(function(error) { + * console.log("Error deleting app:", error); + * }); + * ``` + */ + delete(): Promise; + } +} +export * from './credential/index'; +export { appCheck } from './app-check/app-check-namespace'; +export { auth } from './auth/auth-namespace'; +export { database } from './database/database-namespace'; +export { firestore } from './firestore/firestore-namespace'; +export { instanceId } from './instance-id/instance-id-namespace'; +export { installations } from './installations/installations-namespace'; +export { machineLearning } from './machine-learning/machine-learning-namespace'; +export { messaging } from './messaging/messaging-namespace'; +export { projectManagement } from './project-management/project-management-namespace'; +export { remoteConfig } from './remote-config/remote-config-namespace'; +export { securityRules } from './security-rules/security-rules-namespace'; +export { storage } from './storage/storage-namespace'; +export declare const SDK_VERSION: string; +export declare const apps: (app.App | null)[]; +export declare function app(name?: string): app.App; +export declare function initializeApp(options?: AppOptions, name?: string): app.App; diff --git a/node_modules/firebase-admin/lib/firebase-namespace-api.js b/node_modules/firebase-admin/lib/firebase-namespace-api.js new file mode 100644 index 0000000..74c5c49 --- /dev/null +++ b/node_modules/firebase-admin/lib/firebase-namespace-api.js @@ -0,0 +1,58 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.storage = exports.securityRules = exports.remoteConfig = exports.projectManagement = exports.messaging = exports.machineLearning = exports.installations = exports.instanceId = exports.firestore = exports.database = exports.auth = exports.appCheck = void 0; +__exportStar(require("./credential/index"), exports); +var app_check_namespace_1 = require("./app-check/app-check-namespace"); +Object.defineProperty(exports, "appCheck", { enumerable: true, get: function () { return app_check_namespace_1.appCheck; } }); +var auth_namespace_1 = require("./auth/auth-namespace"); +Object.defineProperty(exports, "auth", { enumerable: true, get: function () { return auth_namespace_1.auth; } }); +var database_namespace_1 = require("./database/database-namespace"); +Object.defineProperty(exports, "database", { enumerable: true, get: function () { return database_namespace_1.database; } }); +var firestore_namespace_1 = require("./firestore/firestore-namespace"); +Object.defineProperty(exports, "firestore", { enumerable: true, get: function () { return firestore_namespace_1.firestore; } }); +var instance_id_namespace_1 = require("./instance-id/instance-id-namespace"); +Object.defineProperty(exports, "instanceId", { enumerable: true, get: function () { return instance_id_namespace_1.instanceId; } }); +var installations_namespace_1 = require("./installations/installations-namespace"); +Object.defineProperty(exports, "installations", { enumerable: true, get: function () { return installations_namespace_1.installations; } }); +var machine_learning_namespace_1 = require("./machine-learning/machine-learning-namespace"); +Object.defineProperty(exports, "machineLearning", { enumerable: true, get: function () { return machine_learning_namespace_1.machineLearning; } }); +var messaging_namespace_1 = require("./messaging/messaging-namespace"); +Object.defineProperty(exports, "messaging", { enumerable: true, get: function () { return messaging_namespace_1.messaging; } }); +var project_management_namespace_1 = require("./project-management/project-management-namespace"); +Object.defineProperty(exports, "projectManagement", { enumerable: true, get: function () { return project_management_namespace_1.projectManagement; } }); +var remote_config_namespace_1 = require("./remote-config/remote-config-namespace"); +Object.defineProperty(exports, "remoteConfig", { enumerable: true, get: function () { return remote_config_namespace_1.remoteConfig; } }); +var security_rules_namespace_1 = require("./security-rules/security-rules-namespace"); +Object.defineProperty(exports, "securityRules", { enumerable: true, get: function () { return security_rules_namespace_1.securityRules; } }); +var storage_namespace_1 = require("./storage/storage-namespace"); +Object.defineProperty(exports, "storage", { enumerable: true, get: function () { return storage_namespace_1.storage; } }); diff --git a/node_modules/firebase-admin/lib/firestore/firestore-internal.d.ts b/node_modules/firebase-admin/lib/firestore/firestore-internal.d.ts new file mode 100644 index 0000000..cf4c77d --- /dev/null +++ b/node_modules/firebase-admin/lib/firestore/firestore-internal.d.ts @@ -0,0 +1,54 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Firestore, Settings } from '@google-cloud/firestore'; +import { App } from '../app'; +/** + * Settings to pass to the Firestore constructor. + * + * @public + */ +export interface FirestoreSettings { + /** + * Use HTTP/1.1 REST transport where possible. + * + * `preferRest` will force the use of HTTP/1.1 REST transport until a method + * that requires gRPC is called. When a method requires gRPC, this Firestore + * client will load dependent gRPC libraries and then use gRPC transport for + * all communication from that point forward. Currently the only operation + * that requires gRPC is creating a snapshot listener using `onSnapshot()`. + * + * @defaultValue `undefined` + */ + preferRest?: boolean; +} +export declare class FirestoreService { + private readonly appInternal; + private readonly databases; + private readonly firestoreSettings; + constructor(app: App); + initializeDatabase(databaseId: string, settings: FirestoreSettings): Firestore; + getDatabase(databaseId: string): Firestore; + private checkIfSameSettings; + /** + * Returns the app associated with this Storage instance. + * + * @returns The app associated with this Storage instance. + */ + get app(): App; +} +export declare function getFirestoreOptions(app: App, firestoreSettings?: FirestoreSettings): Settings; diff --git a/node_modules/firebase-admin/lib/firestore/firestore-internal.js b/node_modules/firebase-admin/lib/firestore/firestore-internal.js new file mode 100644 index 0000000..87a4a33 --- /dev/null +++ b/node_modules/firebase-admin/lib/firestore/firestore-internal.js @@ -0,0 +1,145 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirestoreService = void 0; +exports.getFirestoreOptions = getFirestoreOptions; +const error_1 = require("../utils/error"); +const credential_internal_1 = require("../app/credential-internal"); +const validator = require("../utils/validator"); +const utils = require("../utils/index"); +class FirestoreService { + constructor(app) { + this.databases = new Map(); + this.firestoreSettings = new Map(); + this.appInternal = app; + } + initializeDatabase(databaseId, settings) { + const existingInstance = this.databases.get(databaseId); + if (existingInstance) { + const initialSettings = this.firestoreSettings.get(databaseId) ?? {}; + if (this.checkIfSameSettings(settings, initialSettings)) { + return existingInstance; + } + throw new error_1.FirebaseFirestoreError({ + code: 'failed-precondition', + message: 'initializeFirestore() has already been called with ' + + 'different options. To avoid this error, call initializeFirestore() with the ' + + 'same options as when it was originally called, or call getFirestore() to return the' + + ' already initialized instance.' + }); + } + const newInstance = initFirestore(this.app, databaseId, settings); + this.databases.set(databaseId, newInstance); + this.firestoreSettings.set(databaseId, settings); + return newInstance; + } + getDatabase(databaseId) { + let database = this.databases.get(databaseId); + if (database === undefined) { + database = initFirestore(this.app, databaseId, {}); + this.databases.set(databaseId, database); + this.firestoreSettings.set(databaseId, {}); + } + return database; + } + checkIfSameSettings(settingsA, settingsB) { + const a = settingsA ?? {}; + const b = settingsB ?? {}; + // If we start passing more settings to Firestore constructor, + // replace this with deep equality check. + return (a.preferRest === b.preferRest); + } + /** + * Returns the app associated with this Storage instance. + * + * @returns The app associated with this Storage instance. + */ + get app() { + return this.appInternal; + } +} +exports.FirestoreService = FirestoreService; +function getFirestoreOptions(app, firestoreSettings) { + if (!validator.isNonNullObject(app) || !('options' in app)) { + throw new error_1.FirebaseFirestoreError({ + code: 'invalid-argument', + message: 'First argument passed to admin.firestore() must be a valid Firebase app instance.', + }); + } + const projectId = utils.getExplicitProjectId(app); + const credential = app.options.credential; + // eslint-disable-next-line @typescript-eslint/no-var-requires + const sdkVersion = utils.getSdkVersion(); + const preferRest = firestoreSettings?.preferRest; + if (credential instanceof credential_internal_1.ServiceAccountCredential) { + return { + credentials: { + private_key: credential.privateKey, + client_email: credential.clientEmail, + }, + // When the SDK is initialized with ServiceAccountCredentials an explicit projectId is + // guaranteed to be available. + projectId: projectId, + firebaseVersion: sdkVersion, + firebaseAdminVersion: sdkVersion, + preferRest, + }; + } + else if ((0, credential_internal_1.isApplicationDefault)(app.options.credential)) { + // Try to use the Google application default credentials. + // If an explicit project ID is not available, let Firestore client discover one from the + // environment. This prevents the users from having to set GOOGLE_CLOUD_PROJECT in GCP runtimes. + return validator.isNonEmptyString(projectId) + ? { + projectId, + firebaseVersion: sdkVersion, + firebaseAdminVersion: sdkVersion, + preferRest + } + : { + firebaseVersion: sdkVersion, + firebaseAdminVersion: sdkVersion, + preferRest + }; + } + throw new error_1.FirebaseFirestoreError({ + code: 'invalid-credential', + message: 'Failed to initialize Google Cloud Firestore client with the available credentials. ' + + 'Must initialize the SDK with a certificate credential or application default credentials ' + + 'to use Cloud Firestore API.', + }); +} +function initFirestore(app, databaseId, firestoreSettings) { + const options = getFirestoreOptions(app, firestoreSettings); + options.databaseId = databaseId; + let firestoreDatabase; + try { + // Lazy-load the Firestore implementation here, which in turns loads gRPC. + firestoreDatabase = require('@google-cloud/firestore').Firestore; + } + catch (err) { + throw new error_1.FirebaseFirestoreError({ + code: 'missing-dependencies', + message: 'Failed to import the Cloud Firestore client library for Node.js. ' + + 'Make sure to install the "@google-cloud/firestore" npm package. ' + + `Original error: ${err}`, + }); + } + return new firestoreDatabase(options); +} diff --git a/node_modules/firebase-admin/lib/firestore/firestore-namespace.d.ts b/node_modules/firebase-admin/lib/firestore/firestore-namespace.d.ts new file mode 100644 index 0000000..67c8888 --- /dev/null +++ b/node_modules/firebase-admin/lib/firestore/firestore-namespace.d.ts @@ -0,0 +1,71 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as _firestore from '@google-cloud/firestore'; +import { App } from '../app'; +export declare function firestore(app?: App): _firestore.Firestore; +export declare namespace firestore { + export import v1beta1 = _firestore.v1beta1; + export import v1 = _firestore.v1; + export import AggregateField = _firestore.AggregateField; + export import AggregateFieldType = _firestore.AggregateFieldType; + export import AggregateQuery = _firestore.AggregateQuery; + export import AggregateQuerySnapshot = _firestore.AggregateQuerySnapshot; + export import AggregateSpecData = _firestore.AggregateSpecData; + export import AggregateSpec = _firestore.AggregateSpec; + export import AggregateType = _firestore.AggregateType; + export import BulkWriter = _firestore.BulkWriter; + export import BulkWriterOptions = _firestore.BulkWriterOptions; + export import BundleBuilder = _firestore.BundleBuilder; + export import CollectionGroup = _firestore.CollectionGroup; + export import CollectionReference = _firestore.CollectionReference; + export import DocumentChange = _firestore.DocumentChange; + export import DocumentChangeType = _firestore.DocumentChangeType; + export import DocumentData = _firestore.DocumentData; + export import DocumentReference = _firestore.DocumentReference; + export import DocumentSnapshot = _firestore.DocumentSnapshot; + export import FieldPath = _firestore.FieldPath; + export import FieldValue = _firestore.FieldValue; + export import Filter = _firestore.Filter; + export import Firestore = _firestore.Firestore; + export import FirestoreDataConverter = _firestore.FirestoreDataConverter; + export import GeoPoint = _firestore.GeoPoint; + export import GrpcStatus = _firestore.GrpcStatus; + export import OrderByDirection = _firestore.OrderByDirection; + export import Precondition = _firestore.Precondition; + export import Query = _firestore.Query; + export import QueryDocumentSnapshot = _firestore.QueryDocumentSnapshot; + export import QueryPartition = _firestore.QueryPartition; + export import QuerySnapshot = _firestore.QuerySnapshot; + export import ReadOptions = _firestore.ReadOptions; + export import Settings = _firestore.Settings; + export import SetOptions = _firestore.SetOptions; + export import Timestamp = _firestore.Timestamp; + export import Transaction = _firestore.Transaction; + export import UpdateData = _firestore.UpdateData; + export import WhereFilterOp = _firestore.WhereFilterOp; + export import WriteBatch = _firestore.WriteBatch; + export import WriteResult = _firestore.WriteResult; + export import PartialWithFieldValue = _firestore.PartialWithFieldValue; + export import WithFieldValue = _firestore.WithFieldValue; + export import Primitive = _firestore.Primitive; + export import NestedUpdateFields = _firestore.NestedUpdateFields; + export import ChildUpdateFields = _firestore.ChildUpdateFields; + export import AddPrefixToKeys = _firestore.AddPrefixToKeys; + export import UnionToIntersection = _firestore.UnionToIntersection; + export import ReadOnlyTransactionOptions = _firestore.ReadOnlyTransactionOptions; + export import setLogFunction = _firestore.setLogFunction; +} diff --git a/node_modules/firebase-admin/lib/firestore/firestore-namespace.js b/node_modules/firebase-admin/lib/firestore/firestore-namespace.js new file mode 100644 index 0000000..3bb9a6f --- /dev/null +++ b/node_modules/firebase-admin/lib/firestore/firestore-namespace.js @@ -0,0 +1,52 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.firestore = void 0; +const _firestore = require("@google-cloud/firestore"); +/* eslint-disable @typescript-eslint/no-namespace */ +var firestore; +(function (firestore) { + /* eslint-disable @typescript-eslint/no-unused-vars */ + // See https://github.com/typescript-eslint/typescript-eslint/issues/363 + firestore.v1beta1 = _firestore.v1beta1; + firestore.v1 = _firestore.v1; + firestore.AggregateField = _firestore.AggregateField; + firestore.AggregateQuery = _firestore.AggregateQuery; + firestore.AggregateQuerySnapshot = _firestore.AggregateQuerySnapshot; + firestore.BulkWriter = _firestore.BulkWriter; + firestore.BundleBuilder = _firestore.BundleBuilder; + firestore.CollectionGroup = _firestore.CollectionGroup; + firestore.CollectionReference = _firestore.CollectionReference; + firestore.DocumentReference = _firestore.DocumentReference; + firestore.DocumentSnapshot = _firestore.DocumentSnapshot; + firestore.FieldPath = _firestore.FieldPath; + firestore.FieldValue = _firestore.FieldValue; + firestore.Filter = _firestore.Filter; + firestore.Firestore = _firestore.Firestore; + firestore.GeoPoint = _firestore.GeoPoint; + firestore.GrpcStatus = _firestore.GrpcStatus; + firestore.Query = _firestore.Query; + firestore.QueryDocumentSnapshot = _firestore.QueryDocumentSnapshot; + firestore.QueryPartition = _firestore.QueryPartition; + firestore.QuerySnapshot = _firestore.QuerySnapshot; + firestore.Timestamp = _firestore.Timestamp; + firestore.Transaction = _firestore.Transaction; + firestore.WriteBatch = _firestore.WriteBatch; + firestore.WriteResult = _firestore.WriteResult; + firestore.setLogFunction = _firestore.setLogFunction; +})(firestore || (exports.firestore = firestore = {})); diff --git a/node_modules/firebase-admin/lib/firestore/index.d.ts b/node_modules/firebase-admin/lib/firestore/index.d.ts new file mode 100644 index 0000000..846c253 --- /dev/null +++ b/node_modules/firebase-admin/lib/firestore/index.d.ts @@ -0,0 +1,130 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Cloud Firestore. + * + * @packageDocumentation + */ +import { Firestore } from '@google-cloud/firestore'; +import { App } from '../app'; +import { FirestoreSettings } from './firestore-internal'; +export { AddPrefixToKeys, AggregateField, AggregateFieldType, AggregateQuery, AggregateQuerySnapshot, AggregateSpecData, AggregateSpec, AggregateType, BulkWriter, BulkWriterOptions, BundleBuilder, ChildUpdateFields, CollectionGroup, CollectionReference, DocumentChange, DocumentChangeType, DocumentData, DocumentReference, DocumentSnapshot, FieldPath, FieldValue, Filter, Firestore, FirestoreDataConverter, GeoPoint, GrpcStatus, NestedUpdateFields, OrderByDirection, PartialWithFieldValue, Precondition, Primitive, Query, QueryDocumentSnapshot, QueryPartition, QuerySnapshot, ReadOptions, ReadOnlyTransactionOptions, ReadWriteTransactionOptions, Settings, SetOptions, Timestamp, Transaction, UpdateData, UnionToIntersection, WhereFilterOp, WithFieldValue, WriteBatch, WriteResult, v1, setLogFunction, } from '@google-cloud/firestore'; +export { FirestoreSettings }; +/** + * Gets the default {@link https://googleapis.dev/nodejs/firestore/latest/Firestore.html | Firestore} + * service for the default app. + * + * @example + * ```javascript + * // Get the default Firestore service for the default app + * const defaultFirestore = getFirestore(); + * ``` + + * @returns The default {@link https://googleapis.dev/nodejs/firestore/latest/Firestore.html | Firestore} + * service for the default app. + */ +export declare function getFirestore(): Firestore; +/** + * Gets the default {@link https://googleapis.dev/nodejs/firestore/latest/Firestore.html | Firestore} + * service for the given app. + * + * @example + * ```javascript + * // Get the default Firestore service for a specific app + * const otherFirestore = getFirestore(app); + * ``` + * + * @param app - which `Firestore` service to return. + * + * @returns The default {@link https://googleapis.dev/nodejs/firestore/latest/Firestore.html | Firestore} + * service associated with the provided app. + */ +export declare function getFirestore(app: App): Firestore; +/** + * Gets the named {@link https://googleapis.dev/nodejs/firestore/latest/Firestore.html | Firestore} + * service for the default app. + * + * @example + * ```javascript + * // Get the Firestore service for a named database and default app + * const otherFirestore = getFirestore('otherDb'); + * ``` + * + * @param databaseId - name of database to return. + * + * @returns The named {@link https://googleapis.dev/nodejs/firestore/latest/Firestore.html | Firestore} + * service for the default app. + * @beta + */ +export declare function getFirestore(databaseId: string): Firestore; +/** + * Gets the named {@link https://googleapis.dev/nodejs/firestore/latest/Firestore.html | Firestore} + * service for the given app. + * + * @example + * ```javascript + * // Get the Firestore service for a named database and specific app. + * const otherFirestore = getFirestore('otherDb'); + * ``` + * + * @param app - which `Firestore` service to return. + * + * @param databaseId - name of database to return. + * + * @returns The named {@link https://googleapis.dev/nodejs/firestore/latest/Firestore.html | Firestore} + * service associated with the provided app. + * @beta + */ +export declare function getFirestore(app: App, databaseId: string): Firestore; +/** + * Gets the default {@link https://googleapis.dev/nodejs/firestore/latest/Firestore.html | Firestore} + * service for the given app, passing extra parameters to its constructor. + * + * @example + * ```javascript + * // Get the Firestore service for a specific app, require HTTP/1.1 REST transport + * const otherFirestore = initializeFirestore(app, {preferRest: true}); + * ``` + * + * @param app - which `Firestore` service to return. + * + * @param settings - Settings object to be passed to the constructor. + * + * @returns The default `Firestore` service associated with the provided app and settings. + */ +export declare function initializeFirestore(app: App, settings?: FirestoreSettings): Firestore; +/** + * Gets the named {@link https://googleapis.dev/nodejs/firestore/latest/Firestore.html | Firestore} + * service for the given app, passing extra parameters to its constructor. + * + * @example + * ```javascript + * // Get the Firestore service for a specific app, require HTTP/1.1 REST transport + * const otherFirestore = initializeFirestore(app, {preferRest: true}, 'otherDb'); + * ``` + * + * @param app - which `Firestore` service to return. + * + * @param settings - Settings object to be passed to the constructor. + * + * @param databaseId - name of database to return. + * + * @returns The named `Firestore` service associated with the provided app and settings. + * @beta + */ +export declare function initializeFirestore(app: App, settings: FirestoreSettings, databaseId: string): Firestore; +export { FirebaseFirestoreError } from '../utils/error'; diff --git a/node_modules/firebase-admin/lib/firestore/index.js b/node_modules/firebase-admin/lib/firestore/index.js new file mode 100644 index 0000000..deff46b --- /dev/null +++ b/node_modules/firebase-admin/lib/firestore/index.js @@ -0,0 +1,66 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirebaseFirestoreError = exports.setLogFunction = exports.v1 = exports.WriteResult = exports.WriteBatch = exports.Transaction = exports.Timestamp = exports.QuerySnapshot = exports.QueryPartition = exports.QueryDocumentSnapshot = exports.Query = exports.GrpcStatus = exports.GeoPoint = exports.Firestore = exports.Filter = exports.FieldValue = exports.FieldPath = exports.DocumentSnapshot = exports.DocumentReference = exports.CollectionReference = exports.CollectionGroup = exports.BundleBuilder = exports.BulkWriter = exports.AggregateQuerySnapshot = exports.AggregateQuery = exports.AggregateField = void 0; +exports.getFirestore = getFirestore; +exports.initializeFirestore = initializeFirestore; +const app_1 = require("../app"); +const firestore_internal_1 = require("./firestore-internal"); +const path_1 = require("@google-cloud/firestore/build/src/path"); +var firestore_1 = require("@google-cloud/firestore"); +Object.defineProperty(exports, "AggregateField", { enumerable: true, get: function () { return firestore_1.AggregateField; } }); +Object.defineProperty(exports, "AggregateQuery", { enumerable: true, get: function () { return firestore_1.AggregateQuery; } }); +Object.defineProperty(exports, "AggregateQuerySnapshot", { enumerable: true, get: function () { return firestore_1.AggregateQuerySnapshot; } }); +Object.defineProperty(exports, "BulkWriter", { enumerable: true, get: function () { return firestore_1.BulkWriter; } }); +Object.defineProperty(exports, "BundleBuilder", { enumerable: true, get: function () { return firestore_1.BundleBuilder; } }); +Object.defineProperty(exports, "CollectionGroup", { enumerable: true, get: function () { return firestore_1.CollectionGroup; } }); +Object.defineProperty(exports, "CollectionReference", { enumerable: true, get: function () { return firestore_1.CollectionReference; } }); +Object.defineProperty(exports, "DocumentReference", { enumerable: true, get: function () { return firestore_1.DocumentReference; } }); +Object.defineProperty(exports, "DocumentSnapshot", { enumerable: true, get: function () { return firestore_1.DocumentSnapshot; } }); +Object.defineProperty(exports, "FieldPath", { enumerable: true, get: function () { return firestore_1.FieldPath; } }); +Object.defineProperty(exports, "FieldValue", { enumerable: true, get: function () { return firestore_1.FieldValue; } }); +Object.defineProperty(exports, "Filter", { enumerable: true, get: function () { return firestore_1.Filter; } }); +Object.defineProperty(exports, "Firestore", { enumerable: true, get: function () { return firestore_1.Firestore; } }); +Object.defineProperty(exports, "GeoPoint", { enumerable: true, get: function () { return firestore_1.GeoPoint; } }); +Object.defineProperty(exports, "GrpcStatus", { enumerable: true, get: function () { return firestore_1.GrpcStatus; } }); +Object.defineProperty(exports, "Query", { enumerable: true, get: function () { return firestore_1.Query; } }); +Object.defineProperty(exports, "QueryDocumentSnapshot", { enumerable: true, get: function () { return firestore_1.QueryDocumentSnapshot; } }); +Object.defineProperty(exports, "QueryPartition", { enumerable: true, get: function () { return firestore_1.QueryPartition; } }); +Object.defineProperty(exports, "QuerySnapshot", { enumerable: true, get: function () { return firestore_1.QuerySnapshot; } }); +Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function () { return firestore_1.Timestamp; } }); +Object.defineProperty(exports, "Transaction", { enumerable: true, get: function () { return firestore_1.Transaction; } }); +Object.defineProperty(exports, "WriteBatch", { enumerable: true, get: function () { return firestore_1.WriteBatch; } }); +Object.defineProperty(exports, "WriteResult", { enumerable: true, get: function () { return firestore_1.WriteResult; } }); +Object.defineProperty(exports, "v1", { enumerable: true, get: function () { return firestore_1.v1; } }); +Object.defineProperty(exports, "setLogFunction", { enumerable: true, get: function () { return firestore_1.setLogFunction; } }); +function getFirestore(appOrDatabaseId, optionalDatabaseId) { + const app = typeof appOrDatabaseId === 'object' ? appOrDatabaseId : (0, app_1.getApp)(); + const databaseId = (typeof appOrDatabaseId === 'string' ? appOrDatabaseId : optionalDatabaseId) || path_1.DEFAULT_DATABASE_ID; + const firebaseApp = app; + const firestoreService = firebaseApp.getOrInitService('firestore', (app) => new firestore_internal_1.FirestoreService(app)); + return firestoreService.getDatabase(databaseId); +} +function initializeFirestore(app, settings, databaseId) { + settings ?? (settings = {}); + databaseId ?? (databaseId = path_1.DEFAULT_DATABASE_ID); + const firebaseApp = app; + const firestoreService = firebaseApp.getOrInitService('firestore', (app) => new firestore_internal_1.FirestoreService(app)); + return firestoreService.initializeDatabase(databaseId, settings); +} +var error_1 = require("../utils/error"); +Object.defineProperty(exports, "FirebaseFirestoreError", { enumerable: true, get: function () { return error_1.FirebaseFirestoreError; } }); diff --git a/node_modules/firebase-admin/lib/functions/functions-api-client-internal.d.ts b/node_modules/firebase-admin/lib/functions/functions-api-client-internal.d.ts new file mode 100644 index 0000000..f777315 --- /dev/null +++ b/node_modules/firebase-admin/lib/functions/functions-api-client-internal.d.ts @@ -0,0 +1,52 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { PrefixedFirebaseError } from '../utils/error'; +export declare const EMULATED_SERVICE_ACCOUNT_DEFAULT = "emulated-service-acct@email.com"; +/** + * Task is a limited subset of https://cloud.google.com/tasks/docs/reference/rest/v2/projects.locations.queues.tasks#resource:-task + * containing the relevant fields for enqueueing tasks that tirgger Cloud Functions. + */ +export interface Task { + name?: string; + scheduleTime?: string; + dispatchDeadline?: string; + httpRequest: { + url: string; + oidcToken?: { + serviceAccountEmail: string; + }; + body: string; + headers: { + [key: string]: string; + }; + }; +} +export declare const FUNCTIONS_ERROR_CODE_MAPPING: { + [key: string]: FunctionsErrorCode; +}; +export type FunctionsErrorCode = 'aborted' | 'invalid-argument' | 'invalid-credential' | 'internal-error' | 'failed-precondition' | 'permission-denied' | 'unauthenticated' | 'not-found' | 'unknown-error' | 'task-already-exists'; +/** + * Firebase Functions error code structure. This extends PrefixedFirebaseError. + * + * @param code - The error code. + * @param message - The error message. + * @constructor + */ +export declare class FirebaseFunctionsError extends PrefixedFirebaseError { + constructor(code: FunctionsErrorCode, message: string); +} diff --git a/node_modules/firebase-admin/lib/functions/functions-api-client-internal.js b/node_modules/firebase-admin/lib/functions/functions-api-client-internal.js new file mode 100644 index 0000000..6fc8342 --- /dev/null +++ b/node_modules/firebase-admin/lib/functions/functions-api-client-internal.js @@ -0,0 +1,372 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirebaseFunctionsError = exports.FUNCTIONS_ERROR_CODE_MAPPING = exports.FunctionsApiClient = exports.EMULATED_SERVICE_ACCOUNT_DEFAULT = void 0; +const api_request_1 = require("../utils/api-request"); +const error_1 = require("../utils/error"); +const utils = require("../utils/index"); +const validator = require("../utils/validator"); +const credential_internal_1 = require("../app/credential-internal"); +const CLOUD_TASKS_API_RESOURCE_PATH = 'projects/{projectId}/locations/{locationId}/queues/{resourceId}/tasks'; +const CLOUD_TASKS_API_URL_FORMAT = 'https://cloudtasks.googleapis.com/v2/' + CLOUD_TASKS_API_RESOURCE_PATH; +const FIREBASE_FUNCTION_URL_FORMAT = 'https://{locationId}-{projectId}.cloudfunctions.net/{resourceId}'; +exports.EMULATED_SERVICE_ACCOUNT_DEFAULT = 'emulated-service-acct@email.com'; +const FIREBASE_FUNCTIONS_CONFIG_HEADERS = { + 'X-Firebase-Client': `fire-admin-node/${utils.getSdkVersion()}` +}; +// Default canonical location ID of the task queue. +const DEFAULT_LOCATION = 'us-central1'; +/** + * Class that facilitates sending requests to the Firebase Functions backend API. + * + * @internal + */ +class FunctionsApiClient { + constructor(app) { + this.app = app; + if (!validator.isNonNullObject(app) || !('options' in app)) { + throw new FirebaseFunctionsError('invalid-argument', 'First argument passed to getFunctions() must be a valid Firebase app instance.'); + } + this.httpClient = new FunctionsHttpClient(app); + } + /** + * Deletes a task from a queue. + * + * @param id - The ID of the task to delete. + * @param functionName - The function name of the queue. + * @param extensionId - Optional canonical ID of the extension. + */ + async delete(id, functionName, extensionId) { + if (!validator.isNonEmptyString(functionName)) { + throw new FirebaseFunctionsError('invalid-argument', 'Function name must be a non empty string'); + } + if (!validator.isTaskId(id)) { + throw new FirebaseFunctionsError('invalid-argument', 'id can contain only letters ([A-Za-z]), numbers ([0-9]), ' + + 'hyphens (-), or underscores (_). The maximum length is 500 characters.'); + } + let resources; + try { + resources = utils.parseResourceName(functionName, 'functions'); + } + catch (err) { + throw new FirebaseFunctionsError('invalid-argument', 'Function name must be a single string or a qualified resource name'); + } + resources.projectId = resources.projectId || await this.getProjectId(); + resources.locationId = resources.locationId || DEFAULT_LOCATION; + if (!validator.isNonEmptyString(resources.resourceId)) { + throw new FirebaseFunctionsError('invalid-argument', 'No valid function name specified to enqueue tasks for.'); + } + if (typeof extensionId !== 'undefined' && validator.isNonEmptyString(extensionId)) { + resources.resourceId = `ext-${extensionId}-${resources.resourceId}`; + } + try { + const serviceUrl = tasksEmulatorUrl(resources)?.concat('/', id) + ?? await this.getUrl(resources, CLOUD_TASKS_API_URL_FORMAT.concat('/', id)); + const request = { + method: 'DELETE', + url: serviceUrl, + headers: FIREBASE_FUNCTIONS_CONFIG_HEADERS, + }; + await this.httpClient.send(request); + } + catch (err) { + if (err instanceof api_request_1.RequestResponseError) { + if (err.response.status === 404) { + // if no task with the provided ID exists, then ignore the delete. + return; + } + throw this.toFirebaseError(err); + } + else { + throw err; + } + } + } + /** + * Creates a task and adds it to a queue. + * + * @param data - The data payload of the task. + * @param functionName - The functionName of the queue. + * @param extensionId - Optional canonical ID of the extension. + * @param opts - Optional options when enqueuing a new task. + */ + async enqueue(data, functionName, extensionId, opts) { + if (!validator.isNonEmptyString(functionName)) { + throw new FirebaseFunctionsError('invalid-argument', 'Function name must be a non empty string'); + } + let resources; + try { + resources = utils.parseResourceName(functionName, 'functions'); + } + catch (err) { + throw new FirebaseFunctionsError('invalid-argument', 'Function name must be a single string or a qualified resource name'); + } + resources.projectId = resources.projectId || await this.getProjectId(); + resources.locationId = resources.locationId || DEFAULT_LOCATION; + if (!validator.isNonEmptyString(resources.resourceId)) { + throw new FirebaseFunctionsError('invalid-argument', 'No valid function name specified to enqueue tasks for.'); + } + if (typeof extensionId !== 'undefined' && validator.isNonEmptyString(extensionId)) { + resources.resourceId = `ext-${extensionId}-${resources.resourceId}`; + } + const task = this.validateTaskOptions(data, resources, opts); + try { + const serviceUrl = tasksEmulatorUrl(resources) ?? + await this.getUrl(resources, CLOUD_TASKS_API_URL_FORMAT); + const taskPayload = await this.updateTaskPayload(task, resources, extensionId); + const request = { + method: 'POST', + url: serviceUrl, + headers: FIREBASE_FUNCTIONS_CONFIG_HEADERS, + data: { + task: taskPayload, + } + }; + await this.httpClient.send(request); + } + catch (err) { + if (err instanceof api_request_1.RequestResponseError) { + if (err.response.status === 409) { + throw new FirebaseFunctionsError('task-already-exists', `A task with ID ${opts?.id} already exists`); + } + else { + throw this.toFirebaseError(err); + } + } + else { + throw err; + } + } + } + getUrl(resourceName, urlFormat) { + let { locationId } = resourceName; + const { projectId, resourceId } = resourceName; + if (typeof locationId === 'undefined' || !validator.isNonEmptyString(locationId)) { + locationId = DEFAULT_LOCATION; + } + return Promise.resolve() + .then(() => { + if (typeof projectId !== 'undefined' && validator.isNonEmptyString(projectId)) { + return projectId; + } + return this.getProjectId(); + }) + .then((projectId) => { + const urlParams = { + projectId, + locationId, + resourceId, + }; + // Formats a string of form 'project/{projectId}/{api}' and replaces + // with corresponding arguments {projectId: '1234', api: 'resource'} + // and returns output: 'project/1234/resource'. + return utils.formatString(urlFormat, urlParams); + }); + } + getProjectId() { + if (this.projectId) { + return Promise.resolve(this.projectId); + } + return utils.findProjectId(this.app) + .then((projectId) => { + if (!validator.isNonEmptyString(projectId)) { + throw new FirebaseFunctionsError('unknown-error', 'Failed to determine project ID. Initialize the ' + + 'SDK with service account credentials or set project ID as an app option. ' + + 'Alternatively, set the GOOGLE_CLOUD_PROJECT environment variable.'); + } + this.projectId = projectId; + return projectId; + }); + } + getServiceAccount() { + if (this.accountId) { + return Promise.resolve(this.accountId); + } + return utils.findServiceAccountEmail(this.app) + .then((accountId) => { + if (!validator.isNonEmptyString(accountId)) { + throw new FirebaseFunctionsError('unknown-error', 'Failed to determine service account. Initialize the ' + + 'SDK with service account credentials or set service account ID as an app option.'); + } + this.accountId = accountId; + return accountId; + }); + } + validateTaskOptions(data, resources, opts) { + const task = { + httpRequest: { + url: '', + oidcToken: { + serviceAccountEmail: '', + }, + body: Buffer.from(JSON.stringify({ data })).toString('base64'), + headers: { + 'Content-Type': 'application/json', + ...opts?.headers, + } + } + }; + if (typeof opts !== 'undefined') { + if (!validator.isNonNullObject(opts)) { + throw new FirebaseFunctionsError('invalid-argument', 'TaskOptions must be a non-null object'); + } + if ('scheduleTime' in opts && 'scheduleDelaySeconds' in opts) { + throw new FirebaseFunctionsError('invalid-argument', 'Both scheduleTime and scheduleDelaySeconds are provided. ' + + 'Only one value should be set.'); + } + if ('scheduleTime' in opts && typeof opts.scheduleTime !== 'undefined') { + if (!(opts.scheduleTime instanceof Date)) { + throw new FirebaseFunctionsError('invalid-argument', 'scheduleTime must be a valid Date object.'); + } + task.scheduleTime = opts.scheduleTime.toISOString(); + } + if ('scheduleDelaySeconds' in opts && typeof opts.scheduleDelaySeconds !== 'undefined') { + if (!validator.isNumber(opts.scheduleDelaySeconds) || opts.scheduleDelaySeconds < 0) { + throw new FirebaseFunctionsError('invalid-argument', 'scheduleDelaySeconds must be a non-negative duration in seconds.'); + } + const date = new Date(); + date.setSeconds(date.getSeconds() + opts.scheduleDelaySeconds); + task.scheduleTime = date.toISOString(); + } + if (typeof opts.dispatchDeadlineSeconds !== 'undefined') { + if (!validator.isNumber(opts.dispatchDeadlineSeconds) || opts.dispatchDeadlineSeconds < 15 + || opts.dispatchDeadlineSeconds > 1800) { + throw new FirebaseFunctionsError('invalid-argument', 'dispatchDeadlineSeconds must be a non-negative duration in seconds ' + + 'and must be in the range of 15s to 30 mins.'); + } + task.dispatchDeadline = `${opts.dispatchDeadlineSeconds}s`; + } + if ('id' in opts && typeof opts.id !== 'undefined') { + if (!validator.isTaskId(opts.id)) { + throw new FirebaseFunctionsError('invalid-argument', 'id can contain only letters ([A-Za-z]), numbers ([0-9]), ' + + 'hyphens (-), or underscores (_). The maximum length is 500 characters.'); + } + const resourcePath = utils.formatString(CLOUD_TASKS_API_RESOURCE_PATH, { + projectId: resources.projectId, + locationId: resources.locationId, + resourceId: resources.resourceId, + }); + task.name = resourcePath.concat('/', opts.id); + } + if (typeof opts.uri !== 'undefined') { + if (!validator.isURL(opts.uri)) { + throw new FirebaseFunctionsError('invalid-argument', 'uri must be a valid URL string.'); + } + task.httpRequest.url = opts.uri; + } + } + return task; + } + async updateTaskPayload(task, resources, extensionId) { + const defaultUrl = process.env.CLOUD_TASKS_EMULATOR_HOST ? + '' + : await this.getUrl(resources, FIREBASE_FUNCTION_URL_FORMAT); + const functionUrl = validator.isNonEmptyString(task.httpRequest.url) + ? task.httpRequest.url + : defaultUrl; + task.httpRequest.url = functionUrl; + // When run from a deployed extension, we should be using ComputeEngineCredentials + if (validator.isNonEmptyString(extensionId) && this.app.options.credential + instanceof credential_internal_1.ApplicationDefaultCredential && await this.app.options.credential.isComputeEngineCredential()) { + const idToken = await this.app.options.credential.getIDToken(functionUrl); + task.httpRequest.headers = { ...task.httpRequest.headers, 'Authorization': `Bearer ${idToken}` }; + // Don't send httpRequest.oidcToken if we set Authorization header, or Cloud Tasks will overwrite it. + delete task.httpRequest.oidcToken; + } + else { + try { + const account = await this.getServiceAccount(); + task.httpRequest.oidcToken = { serviceAccountEmail: account }; + } + catch (e) { + if (process.env.CLOUD_TASKS_EMULATOR_HOST) { + task.httpRequest.oidcToken = { serviceAccountEmail: exports.EMULATED_SERVICE_ACCOUNT_DEFAULT }; + } + else { + throw e; + } + } + } + return task; + } + toFirebaseError(err) { + if (err instanceof error_1.PrefixedFirebaseError) { + return err; + } + const response = err.response; + if (!response.isJson()) { + return new FirebaseFunctionsError('unknown-error', `Unexpected response with status: ${response.status} and body: ${response.text}`); + } + const error = response.data.error || {}; + let code = 'unknown-error'; + if (error.status && error.status in exports.FUNCTIONS_ERROR_CODE_MAPPING) { + code = exports.FUNCTIONS_ERROR_CODE_MAPPING[error.status]; + } + const message = error.message || `Unknown server error: ${response.text}`; + return new FirebaseFunctionsError(code, message); + } +} +exports.FunctionsApiClient = FunctionsApiClient; +/** + * Functions-specific HTTP client which uses the special "owner" token + * when communicating with the Emulator. + */ +class FunctionsHttpClient extends api_request_1.AuthorizedHttpClient { + getToken() { + if (process.env.CLOUD_TASKS_EMULATOR_HOST) { + return Promise.resolve('owner'); + } + return super.getToken(); + } +} +exports.FUNCTIONS_ERROR_CODE_MAPPING = { + ABORTED: 'aborted', + INVALID_ARGUMENT: 'invalid-argument', + INVALID_CREDENTIAL: 'invalid-credential', + INTERNAL: 'internal-error', + FAILED_PRECONDITION: 'failed-precondition', + PERMISSION_DENIED: 'permission-denied', + UNAUTHENTICATED: 'unauthenticated', + NOT_FOUND: 'not-found', + UNKNOWN: 'unknown-error', +}; +/** + * Firebase Functions error code structure. This extends PrefixedFirebaseError. + * + * @param code - The error code. + * @param message - The error message. + * @constructor + */ +class FirebaseFunctionsError extends error_1.PrefixedFirebaseError { + constructor(code, message) { + super('functions', code, message); + /* tslint:disable:max-line-length */ + // Set the prototype explicitly. See the following link for more details: + // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work + /* tslint:enable:max-line-length */ + this.__proto__ = FirebaseFunctionsError.prototype; + } +} +exports.FirebaseFunctionsError = FirebaseFunctionsError; +function tasksEmulatorUrl(resources) { + if (process.env.CLOUD_TASKS_EMULATOR_HOST) { + return `http://${process.env.CLOUD_TASKS_EMULATOR_HOST}/projects/${resources.projectId}/locations/${resources.locationId}/queues/${resources.resourceId}/tasks`; + } + return undefined; +} diff --git a/node_modules/firebase-admin/lib/functions/functions-api.d.ts b/node_modules/firebase-admin/lib/functions/functions-api.d.ts new file mode 100644 index 0000000..851c150 --- /dev/null +++ b/node_modules/firebase-admin/lib/functions/functions-api.d.ts @@ -0,0 +1,99 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Interface representing task options with delayed delivery. + */ +export interface DelayDelivery { + /** + * The duration of delay of the time when the task is scheduled to be attempted or retried. + * This delay is added to the current time. + */ + scheduleDelaySeconds?: number; + /** @alpha */ + scheduleTime?: never; +} +/** + * Interface representing task options with absolute delivery. + */ +export interface AbsoluteDelivery { + /** + * The time when the task is scheduled to be attempted or retried. + */ + scheduleTime?: Date; + /** @alpha */ + scheduleDelaySeconds?: never; +} +/** + * Type representing delivery schedule options. + * `DeliverySchedule` is a union type of {@link DelayDelivery} and {@link AbsoluteDelivery} types. + */ +export type DeliverySchedule = DelayDelivery | AbsoluteDelivery; +/** + * Type representing task options. + */ +export type TaskOptions = DeliverySchedule & TaskOptionsExperimental & { + /** + * The deadline for requests sent to the worker. If the worker does not respond by this deadline + * then the request is cancelled and the attempt is marked as a DEADLINE_EXCEEDED failure. + * Cloud Tasks will retry the task according to the `RetryConfig`. + * The default is 10 minutes. The deadline must be in the range of 15 seconds and 30 minutes. + */ + dispatchDeadlineSeconds?: number; + /** + * The ID to use for the enqueued event. + * If not provided, one will be automatically generated. + * If provided, an explicitly specified task ID enables task de-duplication. If a task's ID is + * identical to that of an existing task or a task that was deleted or executed recently then + * the call will throw an error with code "functions/task-already-exists". Another task with + * the same ID can't be created for ~1hour after the original task was deleted or executed. + * + * Because there is an extra lookup cost to identify duplicate task IDs, setting ID + * significantly increases latency. Using hashed strings for the task ID or for the prefix of + * the task ID is recommended. Choosing task IDs that are sequential or have sequential + * prefixes, for example using a timestamp, causes an increase in latency and error rates in + * all task commands. The infrastructure relies on an approximately uniform distribution of + * task IDs to store and serve tasks efficiently. + * + * "Push IDs" from the Firebase Realtime Database make poor IDs because they are based on + * timestamps and will cause contention (slowdowns) in your task queue. Reversed push IDs + * however form a perfect distribution and are an ideal key. To reverse a string in + * javascript use `someString.split("").reverse().join("")` + */ + id?: string; + /** + * HTTP request headers to include in the request to the task queue function. + * These headers represent a subset of the headers that will accompany the task's HTTP + * request. Some HTTP request headers will be ignored or replaced, e.g. Authorization, Host, Content-Length, + * User-Agent etc. cannot be overridden. + * + * By default, Content-Type is set to 'application/json'. + * + * The size of the headers must be less than 80KB. + */ + headers?: Record; +}; +/** + * Type representing experimental (beta) task options. + */ +export interface TaskOptionsExperimental { + /** + * The full URL path that the request will be sent to. Must be a valid URL. + * @beta + */ + uri?: string; +} diff --git a/node_modules/firebase-admin/lib/functions/functions-api.js b/node_modules/firebase-admin/lib/functions/functions-api.js new file mode 100644 index 0000000..0457090 --- /dev/null +++ b/node_modules/firebase-admin/lib/functions/functions-api.js @@ -0,0 +1,19 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/firebase-admin/lib/functions/functions.d.ts b/node_modules/firebase-admin/lib/functions/functions.d.ts new file mode 100644 index 0000000..c5d6c1e --- /dev/null +++ b/node_modules/firebase-admin/lib/functions/functions.d.ts @@ -0,0 +1,69 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +import { TaskOptions } from './functions-api'; +/** + * The Firebase `Functions` service interface. + */ +export declare class Functions { + readonly app: App; + private readonly client; + /** + * Creates a reference to a {@link TaskQueue} for a given function name. + * The function name can be either: + * + * 1) A fully qualified function resource name: + * `projects/{project}/locations/{location}/functions/{functionName}` + * + * 2) A partial resource name with location and function name, in which case + * the runtime project ID is used: + * `locations/{location}/functions/{functionName}` + * + * 3) A partial function name, in which case the runtime project ID and the default location, + * `us-central1`, is used: + * `{functionName}` + * + * @param functionName - The name of the function. + * @param extensionId - Optional Firebase extension ID. + * @returns A promise that fulfills with a `TaskQueue`. + */ + taskQueue>(functionName: string, extensionId?: string): TaskQueue; +} +/** + * The `TaskQueue` interface. + */ +export declare class TaskQueue> { + private readonly functionName; + private readonly client; + private readonly extensionId?; + /** + * Creates a task and adds it to the queue. Tasks cannot be updated after creation. + * This action requires `cloudtasks.tasks.create` IAM permission on the service account. + * + * @param data - The data payload of the task. + * @param opts - Optional options when enqueuing a new task. + * @returns A promise that resolves when the task has successfully been added to the queue. + */ + enqueue(data: Args, opts?: TaskOptions): Promise; + /** + * Deletes an enqueued task if it has not yet completed. + * @param id - the ID of the task, relative to this queue. + * @returns A promise that resolves when the task has been deleted. + */ + delete(id: string): Promise; +} diff --git a/node_modules/firebase-admin/lib/functions/functions.js b/node_modules/firebase-admin/lib/functions/functions.js new file mode 100644 index 0000000..44db287 --- /dev/null +++ b/node_modules/firebase-admin/lib/functions/functions.js @@ -0,0 +1,105 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TaskQueue = exports.Functions = void 0; +const functions_api_client_internal_1 = require("./functions-api-client-internal"); +const validator = require("../utils/validator"); +/** + * The Firebase `Functions` service interface. + */ +class Functions { + /** + * @param app - The app for this `Functions` service. + * @constructor + * @internal + */ + constructor(app) { + this.app = app; + this.client = new functions_api_client_internal_1.FunctionsApiClient(app); + } + /** + * Creates a reference to a {@link TaskQueue} for a given function name. + * The function name can be either: + * + * 1) A fully qualified function resource name: + * `projects/{project}/locations/{location}/functions/{functionName}` + * + * 2) A partial resource name with location and function name, in which case + * the runtime project ID is used: + * `locations/{location}/functions/{functionName}` + * + * 3) A partial function name, in which case the runtime project ID and the default location, + * `us-central1`, is used: + * `{functionName}` + * + * @param functionName - The name of the function. + * @param extensionId - Optional Firebase extension ID. + * @returns A promise that fulfills with a `TaskQueue`. + */ + taskQueue(functionName, extensionId) { + return new TaskQueue(functionName, this.client, extensionId); + } +} +exports.Functions = Functions; +/** + * The `TaskQueue` interface. + */ +class TaskQueue { + /** + * @param functionName - The name of the function. + * @param client - The `FunctionsApiClient` instance. + * @param extensionId - Optional canonical ID of the extension. + * @constructor + * @internal + */ + constructor(functionName, client, extensionId) { + this.functionName = functionName; + this.client = client; + this.extensionId = extensionId; + if (!validator.isNonEmptyString(functionName)) { + throw new functions_api_client_internal_1.FirebaseFunctionsError('invalid-argument', '`functionName` must be a non-empty string.'); + } + if (!validator.isNonNullObject(client) || !('enqueue' in client)) { + throw new functions_api_client_internal_1.FirebaseFunctionsError('invalid-argument', 'Must provide a valid FunctionsApiClient instance to create a new TaskQueue.'); + } + if (typeof extensionId !== 'undefined' && !validator.isString(extensionId)) { + throw new functions_api_client_internal_1.FirebaseFunctionsError('invalid-argument', '`extensionId` must be a string.'); + } + } + /** + * Creates a task and adds it to the queue. Tasks cannot be updated after creation. + * This action requires `cloudtasks.tasks.create` IAM permission on the service account. + * + * @param data - The data payload of the task. + * @param opts - Optional options when enqueuing a new task. + * @returns A promise that resolves when the task has successfully been added to the queue. + */ + enqueue(data, opts) { + return this.client.enqueue(data, this.functionName, this.extensionId, opts); + } + /** + * Deletes an enqueued task if it has not yet completed. + * @param id - the ID of the task, relative to this queue. + * @returns A promise that resolves when the task has been deleted. + */ + delete(id) { + return this.client.delete(id, this.functionName, this.extensionId); + } +} +exports.TaskQueue = TaskQueue; diff --git a/node_modules/firebase-admin/lib/functions/index.d.ts b/node_modules/firebase-admin/lib/functions/index.d.ts new file mode 100644 index 0000000..16e1199 --- /dev/null +++ b/node_modules/firebase-admin/lib/functions/index.d.ts @@ -0,0 +1,53 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Firebase Functions service. + * + * @packageDocumentation + */ +import { App } from '../app'; +import { Functions } from './functions'; +export { DelayDelivery, AbsoluteDelivery, DeliverySchedule, TaskOptions, TaskOptionsExperimental, } from './functions-api'; +export { Functions, TaskQueue } from './functions'; +/** + * Gets the {@link Functions} service for the default app + * or a given app. + * + * `getFunctions()` can be called with no arguments to access the default + * app's `Functions` service or as `getFunctions(app)` to access the + * `Functions` service associated with a specific app. + * + * @example + * ```javascript + * // Get the `Functions` service for the default app + * const defaultFunctions = getFunctions(); + * ``` + * + * @example + * ```javascript + * // Get the `Functions` service for a given app + * const otherFunctions = getFunctions(otherApp); + * ``` + * + * @param app - Optional app for which to return the `Functions` service. + * If not provided, the default `Functions` service is returned. + * + * @returns The default `Functions` service if no app is provided, or the `Functions` + * service associated with the provided app. + */ +export declare function getFunctions(app?: App): Functions; diff --git a/node_modules/firebase-admin/lib/functions/index.js b/node_modules/firebase-admin/lib/functions/index.js new file mode 100644 index 0000000..dacd094 --- /dev/null +++ b/node_modules/firebase-admin/lib/functions/index.js @@ -0,0 +1,64 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TaskQueue = exports.Functions = void 0; +exports.getFunctions = getFunctions; +/** + * Firebase Functions service. + * + * @packageDocumentation + */ +const app_1 = require("../app"); +const functions_1 = require("./functions"); +var functions_2 = require("./functions"); +Object.defineProperty(exports, "Functions", { enumerable: true, get: function () { return functions_2.Functions; } }); +Object.defineProperty(exports, "TaskQueue", { enumerable: true, get: function () { return functions_2.TaskQueue; } }); +/** + * Gets the {@link Functions} service for the default app + * or a given app. + * + * `getFunctions()` can be called with no arguments to access the default + * app's `Functions` service or as `getFunctions(app)` to access the + * `Functions` service associated with a specific app. + * + * @example + * ```javascript + * // Get the `Functions` service for the default app + * const defaultFunctions = getFunctions(); + * ``` + * + * @example + * ```javascript + * // Get the `Functions` service for a given app + * const otherFunctions = getFunctions(otherApp); + * ``` + * + * @param app - Optional app for which to return the `Functions` service. + * If not provided, the default `Functions` service is returned. + * + * @returns The default `Functions` service if no app is provided, or the `Functions` + * service associated with the provided app. + */ +function getFunctions(app) { + if (typeof app === 'undefined') { + app = (0, app_1.getApp)(); + } + const firebaseApp = app; + return firebaseApp.getOrInitService('functions', (app) => new functions_1.Functions(app)); +} diff --git a/node_modules/firebase-admin/lib/index.d.ts b/node_modules/firebase-admin/lib/index.d.ts new file mode 100644 index 0000000..b031e3e --- /dev/null +++ b/node_modules/firebase-admin/lib/index.d.ts @@ -0,0 +1,24 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as admin from './default-namespace'; + +declare module 'firebase-admin' { +} + +export = admin; diff --git a/node_modules/firebase-admin/lib/index.js b/node_modules/firebase-admin/lib/index.js new file mode 100644 index 0000000..f99186f --- /dev/null +++ b/node_modules/firebase-admin/lib/index.js @@ -0,0 +1,37 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const firebase = require("./default-namespace"); +// Only Node.js has a process variable that is of [[Class]] process +const processGlobal = typeof process !== 'undefined' ? process : 0; +if (Object.prototype.toString.call(processGlobal) !== '[object process]') { + const message = ` +======== WARNING! ======== + +firebase-admin appears to have been installed in an unsupported environment. +This package should only be used in server-side or backend Node.js environments, +and should not be used in web browsers or other client-side environments. + +Use the Firebase JS SDK for client-side Firebase integrations: + +https://firebase.google.com/docs/web/setup +`; + // tslint:disable-next-line:no-console + console.error(message); +} +module.exports = firebase; diff --git a/node_modules/firebase-admin/lib/installations/index.d.ts b/node_modules/firebase-admin/lib/installations/index.d.ts new file mode 100644 index 0000000..9421348 --- /dev/null +++ b/node_modules/firebase-admin/lib/installations/index.d.ts @@ -0,0 +1,53 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Firebase Instance ID service. + * + * @packageDocumentation + */ +import { App } from '../app/index'; +import { Installations } from './installations'; +export { Installations }; +/** + * Gets the {@link Installations} service for the default app or a given app. + * + * `getInstallations()` can be called with no arguments to access the default + * app's `Installations` service or as `getInstallations(app)` to access the + * `Installations` service associated with a specific app. + * + * @example + * ```javascript + * // Get the Installations service for the default app + * const defaultInstallations = getInstallations(); + * ``` + * + * @example + * ```javascript + * // Get the Installations service for a given app + * const otherInstallations = getInstallations(otherApp); + *``` + * + * @param app - Optional app whose `Installations` service to + * return. If not provided, the default `Installations` service will be + * returned. + * + * @returns The default `Installations` service if + * no app is provided or the `Installations` service associated with the + * provided app. + */ +export declare function getInstallations(app?: App): Installations; +export { FirebaseInstallationsError, InstallationsClientErrorCode } from '../utils/error'; diff --git a/node_modules/firebase-admin/lib/installations/index.js b/node_modules/firebase-admin/lib/installations/index.js new file mode 100644 index 0000000..9fec5f0 --- /dev/null +++ b/node_modules/firebase-admin/lib/installations/index.js @@ -0,0 +1,65 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InstallationsClientErrorCode = exports.FirebaseInstallationsError = exports.Installations = void 0; +exports.getInstallations = getInstallations; +/** + * Firebase Instance ID service. + * + * @packageDocumentation + */ +const index_1 = require("../app/index"); +const installations_1 = require("./installations"); +Object.defineProperty(exports, "Installations", { enumerable: true, get: function () { return installations_1.Installations; } }); +/** + * Gets the {@link Installations} service for the default app or a given app. + * + * `getInstallations()` can be called with no arguments to access the default + * app's `Installations` service or as `getInstallations(app)` to access the + * `Installations` service associated with a specific app. + * + * @example + * ```javascript + * // Get the Installations service for the default app + * const defaultInstallations = getInstallations(); + * ``` + * + * @example + * ```javascript + * // Get the Installations service for a given app + * const otherInstallations = getInstallations(otherApp); + *``` + * + * @param app - Optional app whose `Installations` service to + * return. If not provided, the default `Installations` service will be + * returned. + * + * @returns The default `Installations` service if + * no app is provided or the `Installations` service associated with the + * provided app. + */ +function getInstallations(app) { + if (typeof app === 'undefined') { + app = (0, index_1.getApp)(); + } + const firebaseApp = app; + return firebaseApp.getOrInitService('installations', (app) => new installations_1.Installations(app)); +} +var error_1 = require("../utils/error"); +Object.defineProperty(exports, "FirebaseInstallationsError", { enumerable: true, get: function () { return error_1.FirebaseInstallationsError; } }); +Object.defineProperty(exports, "InstallationsClientErrorCode", { enumerable: true, get: function () { return error_1.InstallationsClientErrorCode; } }); diff --git a/node_modules/firebase-admin/lib/installations/installations-namespace.d.ts b/node_modules/firebase-admin/lib/installations/installations-namespace.d.ts new file mode 100644 index 0000000..b163f95 --- /dev/null +++ b/node_modules/firebase-admin/lib/installations/installations-namespace.d.ts @@ -0,0 +1,55 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app/index'; +import { Installations as TInstallations } from './installations'; +/** + * Gets the {@link firebase-admin.installations#Installations} service for the + * default app or a given app. + * + * `admin.installations()` can be called with no arguments to access the default + * app's {@link firebase-admin.installations#Installations} service or as + * `admin.installations(app)` to access the + * {@link firebase-admin.installations#Installations} service associated with a + * specific app. + * + * @example + * ```javascript + * // Get the Installations service for the default app + * var defaultInstallations = admin.installations(); + * ``` + * + * @example + * ```javascript + * // Get the Installations service for a given app + * var otherInstallations = admin.installations(otherApp); + *``` + * + * @param app - Optional app whose `Installations` service to + * return. If not provided, the default `Installations` service is + * returned. + * + * @returns The default `Installations` service if + * no app is provided or the `Installations` service associated with the + * provided app. + */ +export declare function installations(app?: App): installations.Installations; +export declare namespace installations { + /** + * Type alias to {@link firebase-admin.installations#Installations}. + */ + type Installations = TInstallations; +} diff --git a/node_modules/firebase-admin/lib/installations/installations-namespace.js b/node_modules/firebase-admin/lib/installations/installations-namespace.js new file mode 100644 index 0000000..a91b066 --- /dev/null +++ b/node_modules/firebase-admin/lib/installations/installations-namespace.js @@ -0,0 +1,18 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/firebase-admin/lib/installations/installations-request-handler.d.ts b/node_modules/firebase-admin/lib/installations/installations-request-handler.d.ts new file mode 100644 index 0000000..d92f016 --- /dev/null +++ b/node_modules/firebase-admin/lib/installations/installations-request-handler.d.ts @@ -0,0 +1,43 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app/index'; +/** + * Class that provides mechanism to send requests to the FIS backend endpoints. + */ +export declare class FirebaseInstallationsRequestHandler { + private readonly app; + private readonly host; + private readonly timeout; + private readonly httpClient; + private path; + /** + * @param app - The app used to fetch access tokens to sign API requests. + * + * @constructor + */ + constructor(app: App); + deleteInstallation(fid: string): Promise; + /** + * Invokes the request handler based on the API settings object passed. + * + * @param apiSettings - The API endpoint settings to apply to request and response. + * @returns A promise that resolves when the request is complete. + */ + private invokeRequestHandler; + private getPathPrefix; +} diff --git a/node_modules/firebase-admin/lib/installations/installations-request-handler.js b/node_modules/firebase-admin/lib/installations/installations-request-handler.js new file mode 100644 index 0000000..f4ca96f --- /dev/null +++ b/node_modules/firebase-admin/lib/installations/installations-request-handler.js @@ -0,0 +1,114 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirebaseInstallationsRequestHandler = void 0; +const error_1 = require("../utils/error"); +const api_request_1 = require("../utils/api-request"); +const utils = require("../utils/index"); +const validator = require("../utils/validator"); +/** Firebase IID backend host. */ +const FIREBASE_IID_HOST = 'console.firebase.google.com'; +/** Firebase IID backend path. */ +const FIREBASE_IID_PATH = '/v1/'; +/** Firebase IID request timeout duration in milliseconds. */ +const FIREBASE_IID_TIMEOUT = 10000; +/** HTTP error codes raised by the backend server. */ +const ERROR_CODES = { + 400: 'Malformed installation ID argument.', + 401: 'Request not authorized.', + 403: 'Project does not match installation ID or the client does not have sufficient privileges.', + 404: 'Failed to find the installation ID.', + 409: 'Already deleted.', + 429: 'Request throttled out by the backend server.', + 500: 'Internal server error.', + 503: 'Backend servers are over capacity. Try again later.', +}; +/** + * Class that provides mechanism to send requests to the FIS backend endpoints. + */ +class FirebaseInstallationsRequestHandler { + /** + * @param app - The app used to fetch access tokens to sign API requests. + * + * @constructor + */ + constructor(app) { + this.app = app; + this.host = FIREBASE_IID_HOST; + this.timeout = FIREBASE_IID_TIMEOUT; + this.httpClient = new api_request_1.AuthorizedHttpClient(app); + } + deleteInstallation(fid) { + if (!validator.isNonEmptyString(fid)) { + return Promise.reject(new error_1.FirebaseInstallationsError(error_1.InstallationsClientErrorCode.INVALID_INSTALLATION_ID, 'Installation ID must be a non-empty string.')); + } + return this.invokeRequestHandler(new api_request_1.ApiSettings(fid, 'DELETE')); + } + /** + * Invokes the request handler based on the API settings object passed. + * + * @param apiSettings - The API endpoint settings to apply to request and response. + * @returns A promise that resolves when the request is complete. + */ + invokeRequestHandler(apiSettings) { + return this.getPathPrefix() + .then((path) => { + const req = { + url: `https://${this.host}${path}${apiSettings.getEndpoint()}`, + method: apiSettings.getHttpMethod(), + timeout: this.timeout, + }; + return this.httpClient.send(req); + }) + .then(() => { + // return nothing on success + }) + .catch((err) => { + if (err instanceof api_request_1.RequestResponseError) { + const response = err.response; + const errorMessage = (response.isJson() && 'error' in response.data) ? + response.data.error : response.text; + const template = ERROR_CODES[response.status]; + const message = template ? + `Installation ID "${apiSettings.getEndpoint()}": ${template}` : errorMessage; + throw new error_1.FirebaseInstallationsError(error_1.InstallationsClientErrorCode.API_ERROR, message); + } + // In case of timeouts and other network errors, the HttpClient returns a + // FirebaseError wrapped in the response. Simply throw it here. + throw err; + }); + } + getPathPrefix() { + if (this.path) { + return Promise.resolve(this.path); + } + return utils.findProjectId(this.app) + .then((projectId) => { + if (!validator.isNonEmptyString(projectId)) { + // Assert for an explicit projct ID (either via AppOptions or the cert itself). + throw new error_1.FirebaseInstallationsError(error_1.InstallationsClientErrorCode.INVALID_PROJECT_ID, 'Failed to determine project ID for Installations. Initialize the ' + + 'SDK with service account credentials or set project ID as an app option. ' + + 'Alternatively set the GOOGLE_CLOUD_PROJECT environment variable.'); + } + this.path = FIREBASE_IID_PATH + `project/${projectId}/instanceId/`; + return this.path; + }); + } +} +exports.FirebaseInstallationsRequestHandler = FirebaseInstallationsRequestHandler; diff --git a/node_modules/firebase-admin/lib/installations/installations.d.ts b/node_modules/firebase-admin/lib/installations/installations.d.ts new file mode 100644 index 0000000..0b659b3 --- /dev/null +++ b/node_modules/firebase-admin/lib/installations/installations.d.ts @@ -0,0 +1,38 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app/index'; +/** + * The `Installations` service for the current app. + */ +export declare class Installations { + private app_; + private requestHandler; + /** + * Deletes the specified installation ID and the associated data from Firebase. + * + * @param fid - The Firebase installation ID to be deleted. + * + * @returns A promise fulfilled when the installation ID is deleted. + */ + deleteInstallation(fid: string): Promise; + /** + * Returns the app associated with this Installations instance. + * + * @returns The app associated with this Installations instance. + */ + get app(): App; +} diff --git a/node_modules/firebase-admin/lib/installations/installations.js b/node_modules/firebase-admin/lib/installations/installations.js new file mode 100644 index 0000000..c786d58 --- /dev/null +++ b/node_modules/firebase-admin/lib/installations/installations.js @@ -0,0 +1,58 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Installations = void 0; +const error_1 = require("../utils/error"); +const installations_request_handler_1 = require("./installations-request-handler"); +const validator = require("../utils/validator"); +/** + * The `Installations` service for the current app. + */ +class Installations { + /** + * @param app - The app for this Installations service. + * @constructor + * @internal + */ + constructor(app) { + if (!validator.isNonNullObject(app) || !('options' in app)) { + throw new error_1.FirebaseInstallationsError(error_1.InstallationsClientErrorCode.INVALID_ARGUMENT, 'First argument passed to admin.installations() must be a valid Firebase app instance.'); + } + this.app_ = app; + this.requestHandler = new installations_request_handler_1.FirebaseInstallationsRequestHandler(app); + } + /** + * Deletes the specified installation ID and the associated data from Firebase. + * + * @param fid - The Firebase installation ID to be deleted. + * + * @returns A promise fulfilled when the installation ID is deleted. + */ + deleteInstallation(fid) { + return this.requestHandler.deleteInstallation(fid); + } + /** + * Returns the app associated with this Installations instance. + * + * @returns The app associated with this Installations instance. + */ + get app() { + return this.app_; + } +} +exports.Installations = Installations; diff --git a/node_modules/firebase-admin/lib/instance-id/index.d.ts b/node_modules/firebase-admin/lib/instance-id/index.d.ts new file mode 100644 index 0000000..5d97ffe --- /dev/null +++ b/node_modules/firebase-admin/lib/instance-id/index.d.ts @@ -0,0 +1,62 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Firebase Instance ID service. + * + * @packageDocumentation + */ +import { App } from '../app/index'; +import { InstanceId } from './instance-id'; +export { InstanceId }; +/** + * Gets the {@link InstanceId} service for the default app or a given app. + * + * This API is deprecated. Developers are advised to use the + * {@link firebase-admin.installations#getInstallations} + * API to delete their instance IDs and Firebase installation IDs. + * + * `getInstanceId()` can be called with no arguments to access the default + * app's `InstanceId` service or as `getInstanceId(app)` to access the + * `InstanceId` service associated with a specific app. + * + * @example + * ```javascript + * // Get the Instance ID service for the default app + * const defaultInstanceId = getInstanceId(); + * ``` + * + * @example + * ```javascript + * // Get the Instance ID service for a given app + * const otherInstanceId = getInstanceId(otherApp); + *``` + * + * This API is deprecated. Developers are advised to use the `admin.installations()` + * API to delete their instance IDs and Firebase installation IDs. + * + * @param app - Optional app whose `InstanceId` service to + * return. If not provided, the default `InstanceId` service will be + * returned. + * + * @returns The default `InstanceId` service if + * no app is provided or the `InstanceId` service associated with the + * provided app. + * + * @deprecated Use {@link firebase-admin.installations#getInstallations} instead. + */ +export declare function getInstanceId(app?: App): InstanceId; +export { FirebaseInstanceIdError, InstanceIdClientErrorCode } from '../utils/error'; diff --git a/node_modules/firebase-admin/lib/instance-id/index.js b/node_modules/firebase-admin/lib/instance-id/index.js new file mode 100644 index 0000000..bb6e660 --- /dev/null +++ b/node_modules/firebase-admin/lib/instance-id/index.js @@ -0,0 +1,74 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InstanceIdClientErrorCode = exports.FirebaseInstanceIdError = exports.InstanceId = void 0; +exports.getInstanceId = getInstanceId; +/** + * Firebase Instance ID service. + * + * @packageDocumentation + */ +const index_1 = require("../app/index"); +const instance_id_1 = require("./instance-id"); +Object.defineProperty(exports, "InstanceId", { enumerable: true, get: function () { return instance_id_1.InstanceId; } }); +/** + * Gets the {@link InstanceId} service for the default app or a given app. + * + * This API is deprecated. Developers are advised to use the + * {@link firebase-admin.installations#getInstallations} + * API to delete their instance IDs and Firebase installation IDs. + * + * `getInstanceId()` can be called with no arguments to access the default + * app's `InstanceId` service or as `getInstanceId(app)` to access the + * `InstanceId` service associated with a specific app. + * + * @example + * ```javascript + * // Get the Instance ID service for the default app + * const defaultInstanceId = getInstanceId(); + * ``` + * + * @example + * ```javascript + * // Get the Instance ID service for a given app + * const otherInstanceId = getInstanceId(otherApp); + *``` + * + * This API is deprecated. Developers are advised to use the `admin.installations()` + * API to delete their instance IDs and Firebase installation IDs. + * + * @param app - Optional app whose `InstanceId` service to + * return. If not provided, the default `InstanceId` service will be + * returned. + * + * @returns The default `InstanceId` service if + * no app is provided or the `InstanceId` service associated with the + * provided app. + * + * @deprecated Use {@link firebase-admin.installations#getInstallations} instead. + */ +function getInstanceId(app) { + if (typeof app === 'undefined') { + app = (0, index_1.getApp)(); + } + const firebaseApp = app; + return firebaseApp.getOrInitService('instanceId', (app) => new instance_id_1.InstanceId(app)); +} +var error_1 = require("../utils/error"); +Object.defineProperty(exports, "FirebaseInstanceIdError", { enumerable: true, get: function () { return error_1.FirebaseInstanceIdError; } }); +Object.defineProperty(exports, "InstanceIdClientErrorCode", { enumerable: true, get: function () { return error_1.InstanceIdClientErrorCode; } }); diff --git a/node_modules/firebase-admin/lib/instance-id/instance-id-namespace.d.ts b/node_modules/firebase-admin/lib/instance-id/instance-id-namespace.d.ts new file mode 100644 index 0000000..df56c82 --- /dev/null +++ b/node_modules/firebase-admin/lib/instance-id/instance-id-namespace.d.ts @@ -0,0 +1,38 @@ +/*! firebase-admin v13.6.0 */ +import { App } from '../app/index'; +import { InstanceId as TInstanceId } from './instance-id'; +/** + * Gets the {@link firebase-admin.instance-id#InstanceId} service for the + * default app or a given app. + * + * `admin.instanceId()` can be called with no arguments to access the default + * app's `InstanceId` service or as `admin.instanceId(app)` to access the + * `InstanceId` service associated with a specific app. + * + * @example + * ```javascript + * // Get the Instance ID service for the default app + * var defaultInstanceId = admin.instanceId(); + * ``` + * + * @example + * ```javascript + * // Get the Instance ID service for a given app + * var otherInstanceId = admin.instanceId(otherApp); + *``` + * + * @param app - Optional app whose `InstanceId` service to + * return. If not provided, the default `InstanceId` service will be + * returned. + * + * @returns The default `InstanceId` service if + * no app is provided or the `InstanceId` service associated with the + * provided app. + */ +export declare function instanceId(app?: App): instanceId.InstanceId; +export declare namespace instanceId { + /** + * Type alias to {@link firebase-admin.instance-id#InstanceId}. + */ + type InstanceId = TInstanceId; +} diff --git a/node_modules/firebase-admin/lib/instance-id/instance-id-namespace.js b/node_modules/firebase-admin/lib/instance-id/instance-id-namespace.js new file mode 100644 index 0000000..5572977 --- /dev/null +++ b/node_modules/firebase-admin/lib/instance-id/instance-id-namespace.js @@ -0,0 +1,3 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/firebase-admin/lib/instance-id/instance-id.d.ts b/node_modules/firebase-admin/lib/instance-id/instance-id.d.ts new file mode 100644 index 0000000..62b300c --- /dev/null +++ b/node_modules/firebase-admin/lib/instance-id/instance-id.d.ts @@ -0,0 +1,47 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app/index'; +/** + * The `InstanceId` service enables deleting the Firebase instance IDs + * associated with Firebase client app instances. + * + * @deprecated Use {@link firebase-admin.installations#Installations} instead. + */ +export declare class InstanceId { + private app_; + /** + * Deletes the specified instance ID and the associated data from Firebase. + * + * Note that Google Analytics for Firebase uses its own form of Instance ID to + * keep track of analytics data. Therefore deleting a Firebase Instance ID does + * not delete Analytics data. See + * {@link https://firebase.google.com/support/privacy/manage-iids#delete_an_instance_id | + * Delete an Instance ID} + * for more information. + * + * @param instanceId - The instance ID to be deleted. + * + * @returns A promise fulfilled when the instance ID is deleted. + */ + deleteInstanceId(instanceId: string): Promise; + /** + * Returns the app associated with this InstanceId instance. + * + * @returns The app associated with this InstanceId instance. + */ + get app(): App; +} diff --git a/node_modules/firebase-admin/lib/instance-id/instance-id.js b/node_modules/firebase-admin/lib/instance-id/instance-id.js new file mode 100644 index 0000000..f2feb10 --- /dev/null +++ b/node_modules/firebase-admin/lib/instance-id/instance-id.js @@ -0,0 +1,77 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InstanceId = void 0; +const installations_1 = require("../installations"); +const error_1 = require("../utils/error"); +const validator = require("../utils/validator"); +/** + * The `InstanceId` service enables deleting the Firebase instance IDs + * associated with Firebase client app instances. + * + * @deprecated Use {@link firebase-admin.installations#Installations} instead. + */ +class InstanceId { + /** + * @param app - The app for this InstanceId service. + * @constructor + * @internal + */ + constructor(app) { + if (!validator.isNonNullObject(app) || !('options' in app)) { + throw new error_1.FirebaseInstanceIdError(error_1.InstanceIdClientErrorCode.INVALID_ARGUMENT, 'First argument passed to instanceId() must be a valid Firebase app instance.'); + } + this.app_ = app; + } + /** + * Deletes the specified instance ID and the associated data from Firebase. + * + * Note that Google Analytics for Firebase uses its own form of Instance ID to + * keep track of analytics data. Therefore deleting a Firebase Instance ID does + * not delete Analytics data. See + * {@link https://firebase.google.com/support/privacy/manage-iids#delete_an_instance_id | + * Delete an Instance ID} + * for more information. + * + * @param instanceId - The instance ID to be deleted. + * + * @returns A promise fulfilled when the instance ID is deleted. + */ + deleteInstanceId(instanceId) { + return (0, installations_1.getInstallations)(this.app).deleteInstallation(instanceId) + .catch((err) => { + if (err instanceof error_1.FirebaseInstallationsError) { + let code = err.code.replace('installations/', ''); + if (code === error_1.InstallationsClientErrorCode.INVALID_INSTALLATION_ID.code) { + code = error_1.InstanceIdClientErrorCode.INVALID_INSTANCE_ID.code; + } + throw new error_1.FirebaseInstanceIdError({ code, message: err.message }); + } + throw err; + }); + } + /** + * Returns the app associated with this InstanceId instance. + * + * @returns The app associated with this InstanceId instance. + */ + get app() { + return this.app_; + } +} +exports.InstanceId = InstanceId; diff --git a/node_modules/firebase-admin/lib/machine-learning/index.d.ts b/node_modules/firebase-admin/lib/machine-learning/index.d.ts new file mode 100644 index 0000000..ff1d727 --- /dev/null +++ b/node_modules/firebase-admin/lib/machine-learning/index.d.ts @@ -0,0 +1,52 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Firebase Machine Learning. + * + * @packageDocumentation + */ +import { App } from '../app'; +import { MachineLearning } from './machine-learning'; +export { MachineLearning, ListModelsResult, Model, TFLiteModel, } from './machine-learning'; +export { GcsTfliteModelOptions, ListModelsOptions, ModelOptions, ModelOptionsBase, } from './machine-learning-api-client'; +/** + * Gets the {@link MachineLearning} service for the default app or a given app. + * + * `getMachineLearning()` can be called with no arguments to access the + * default app's `MachineLearning` service or as `getMachineLearning(app)` to access + * the `MachineLearning` service associated with a specific app. + * + * @example + * ```javascript + * // Get the MachineLearning service for the default app + * const defaultMachineLearning = getMachineLearning(); + * ``` + * + * @example + * ```javascript + * // Get the MachineLearning service for a given app + * const otherMachineLearning = getMachineLearning(otherApp); + * ``` + * + * @param app - Optional app whose `MachineLearning` service to + * return. If not provided, the default `MachineLearning` service + * will be returned. + * + * @returns The default `MachineLearning` service if no app is provided or the + * `MachineLearning` service associated with the provided app. + */ +export declare function getMachineLearning(app?: App): MachineLearning; diff --git a/node_modules/firebase-admin/lib/machine-learning/index.js b/node_modules/firebase-admin/lib/machine-learning/index.js new file mode 100644 index 0000000..6cbc7f8 --- /dev/null +++ b/node_modules/firebase-admin/lib/machine-learning/index.js @@ -0,0 +1,63 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Model = exports.MachineLearning = void 0; +exports.getMachineLearning = getMachineLearning; +/** + * Firebase Machine Learning. + * + * @packageDocumentation + */ +const app_1 = require("../app"); +const machine_learning_1 = require("./machine-learning"); +var machine_learning_2 = require("./machine-learning"); +Object.defineProperty(exports, "MachineLearning", { enumerable: true, get: function () { return machine_learning_2.MachineLearning; } }); +Object.defineProperty(exports, "Model", { enumerable: true, get: function () { return machine_learning_2.Model; } }); +/** + * Gets the {@link MachineLearning} service for the default app or a given app. + * + * `getMachineLearning()` can be called with no arguments to access the + * default app's `MachineLearning` service or as `getMachineLearning(app)` to access + * the `MachineLearning` service associated with a specific app. + * + * @example + * ```javascript + * // Get the MachineLearning service for the default app + * const defaultMachineLearning = getMachineLearning(); + * ``` + * + * @example + * ```javascript + * // Get the MachineLearning service for a given app + * const otherMachineLearning = getMachineLearning(otherApp); + * ``` + * + * @param app - Optional app whose `MachineLearning` service to + * return. If not provided, the default `MachineLearning` service + * will be returned. + * + * @returns The default `MachineLearning` service if no app is provided or the + * `MachineLearning` service associated with the provided app. + */ +function getMachineLearning(app) { + if (typeof app === 'undefined') { + app = (0, app_1.getApp)(); + } + const firebaseApp = app; + return firebaseApp.getOrInitService('machineLearning', (app) => new machine_learning_1.MachineLearning(app)); +} diff --git a/node_modules/firebase-admin/lib/machine-learning/machine-learning-api-client.d.ts b/node_modules/firebase-admin/lib/machine-learning/machine-learning-api-client.d.ts new file mode 100644 index 0000000..b02bf62 --- /dev/null +++ b/node_modules/firebase-admin/lib/machine-learning/machine-learning-api-client.d.ts @@ -0,0 +1,96 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Firebase ML Model input objects + */ +export interface ModelOptionsBase { + displayName?: string; + tags?: string[]; +} +export interface GcsTfliteModelOptions extends ModelOptionsBase { + tfliteModel: { + gcsTfliteUri: string; + }; +} +export type ModelOptions = ModelOptionsBase | GcsTfliteModelOptions; +/** + * Interface representing options for listing Models. + */ +export interface ListModelsOptions { + /** + * An expression that specifies how to filter the results. + * + * Examples: + * + * ``` + * display_name = your_model + * display_name : experimental_* + * tags: face_detector AND tags: experimental + * state.published = true + * ``` + * + * See https://firebase.google.com/docs/ml/manage-hosted-models#list_your_projects_models + */ + filter?: string; + /** The number of results to return in each page. */ + pageSize?: number; + /** A token that specifies the result page to return. */ + pageToken?: string; +} +export interface StatusErrorResponse { + readonly code: number; + readonly message: string; +} +export type ModelUpdateOptions = ModelOptions & { + state?: { + published?: boolean; + }; +}; +export declare function isGcsTfliteModelOptions(options: ModelOptions): options is GcsTfliteModelOptions; +export interface ModelContent { + readonly displayName?: string; + readonly tags?: string[]; + readonly state?: { + readonly validationError?: StatusErrorResponse; + readonly published?: boolean; + }; + readonly tfliteModel?: { + readonly gcsTfliteUri?: string; + readonly sizeBytes: number; + }; +} +export interface ModelResponse extends ModelContent { + readonly name: string; + readonly createTime: string; + readonly updateTime: string; + readonly etag: string; + readonly modelHash?: string; + readonly activeOperations?: OperationResponse[]; +} +export interface ListModelsResponse { + readonly models?: ModelResponse[]; + readonly nextPageToken?: string; +} +export interface OperationResponse { + readonly name?: string; + readonly metadata?: { + [key: string]: any; + }; + readonly done: boolean; + readonly error?: StatusErrorResponse; + readonly response?: ModelResponse; +} diff --git a/node_modules/firebase-admin/lib/machine-learning/machine-learning-api-client.js b/node_modules/firebase-admin/lib/machine-learning/machine-learning-api-client.js new file mode 100644 index 0000000..bff8098 --- /dev/null +++ b/node_modules/firebase-admin/lib/machine-learning/machine-learning-api-client.js @@ -0,0 +1,290 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MachineLearningApiClient = void 0; +exports.isGcsTfliteModelOptions = isGcsTfliteModelOptions; +const api_request_1 = require("../utils/api-request"); +const error_1 = require("../utils/error"); +const utils = require("../utils/index"); +const validator = require("../utils/validator"); +const machine_learning_utils_1 = require("./machine-learning-utils"); +const ML_V1BETA2_API = 'https://firebaseml.googleapis.com/v1beta2'; +const FIREBASE_VERSION_HEADER = { + 'X-Firebase-Client': `fire-admin-node/${utils.getSdkVersion()}`, +}; +// Operation polling defaults +const POLL_DEFAULT_MAX_TIME_MILLISECONDS = 120000; // Maximum overall 2 minutes +const POLL_BASE_WAIT_TIME_MILLISECONDS = 3000; // Start with 3 second delay +const POLL_MAX_WAIT_TIME_MILLISECONDS = 30000; // Maximum 30 second delay +function isGcsTfliteModelOptions(options) { + const gcsUri = options?.tfliteModel?.gcsTfliteUri; + return typeof gcsUri !== 'undefined'; +} +/** + * Class that facilitates sending requests to the Firebase ML backend API. + * + * @internal + */ +class MachineLearningApiClient { + constructor(app) { + this.app = app; + if (!validator.isNonNullObject(app) || !('options' in app)) { + throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'First argument passed to admin.machineLearning() must be a valid ' + + 'Firebase app instance.'); + } + this.httpClient = new api_request_1.AuthorizedHttpClient(app); + } + createModel(model) { + if (!validator.isNonNullObject(model) || + !validator.isNonEmptyString(model.displayName)) { + const err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Invalid model content.'); + return Promise.reject(err); + } + return this.getProjectUrl() + .then((url) => { + const request = { + method: 'POST', + url: `${url}/models`, + data: model, + }; + return this.sendRequest(request); + }); + } + updateModel(modelId, model, updateMask) { + if (!validator.isNonEmptyString(modelId) || + !validator.isNonNullObject(model) || + !validator.isNonEmptyArray(updateMask)) { + const err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Invalid model or mask content.'); + return Promise.reject(err); + } + return this.getProjectUrl() + .then((url) => { + const request = { + method: 'PATCH', + url: `${url}/models/${modelId}?updateMask=${updateMask.join()}`, + data: model, + }; + return this.sendRequest(request); + }); + } + getModel(modelId) { + return Promise.resolve() + .then(() => { + return this.getModelName(modelId); + }) + .then((modelName) => { + return this.getResourceWithShortName(modelName); + }); + } + getOperation(operationName) { + return Promise.resolve() + .then(() => { + return this.getResourceWithFullName(operationName); + }); + } + listModels(options = {}) { + if (!validator.isNonNullObject(options)) { + const err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Invalid ListModelsOptions'); + return Promise.reject(err); + } + if (typeof options.filter !== 'undefined' && !validator.isNonEmptyString(options.filter)) { + const err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Invalid list filter.'); + return Promise.reject(err); + } + if (typeof options.pageSize !== 'undefined') { + if (!validator.isNumber(options.pageSize)) { + const err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Invalid page size.'); + return Promise.reject(err); + } + if (options.pageSize < 1 || options.pageSize > 100) { + const err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Page size must be between 1 and 100.'); + return Promise.reject(err); + } + } + if (typeof options.pageToken !== 'undefined' && !validator.isNonEmptyString(options.pageToken)) { + const err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Next page token must be a non-empty string.'); + return Promise.reject(err); + } + return this.getProjectUrl() + .then((url) => { + const request = { + method: 'GET', + url: `${url}/models`, + data: options, + }; + return this.sendRequest(request); + }); + } + deleteModel(modelId) { + return this.getProjectUrl() + .then((url) => { + const modelName = this.getModelName(modelId); + const request = { + method: 'DELETE', + url: `${url}/${modelName}`, + }; + return this.sendRequest(request); + }); + } + /** + * Handles a Long Running Operation coming back from the server. + * + * @param op - The operation to handle + * @param options - The options for polling + */ + handleOperation(op, options) { + if (op.done) { + if (op.response) { + return Promise.resolve(op.response); + } + else if (op.error) { + const err = machine_learning_utils_1.FirebaseMachineLearningError.fromOperationError(op.error.code, op.error.message); + return Promise.reject(err); + } + // Done operations must have either a response or an error. + throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-server-response', 'Invalid operation response.'); + } + // Operation is not done + if (options?.wait) { + return this.pollOperationWithExponentialBackoff(op.name, options); + } + const metadata = op.metadata || {}; + const metadataType = metadata['@type'] || ''; + if (!metadataType.includes('ModelOperationMetadata')) { + throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-server-response', `Unknown Metadata type: ${JSON.stringify(metadata)}`); + } + return this.getModel(extractModelId(metadata.name)); + } + // baseWaitMillis and maxWaitMillis should only ever be modified by unit tests to run faster. + pollOperationWithExponentialBackoff(opName, options) { + const maxTimeMilliseconds = options?.maxTimeMillis ?? POLL_DEFAULT_MAX_TIME_MILLISECONDS; + const baseWaitMillis = options?.baseWaitMillis ?? POLL_BASE_WAIT_TIME_MILLISECONDS; + const maxWaitMillis = options?.maxWaitMillis ?? POLL_MAX_WAIT_TIME_MILLISECONDS; + const poller = new api_request_1.ExponentialBackoffPoller(baseWaitMillis, maxWaitMillis, maxTimeMilliseconds); + return poller.poll(() => { + return this.getOperation(opName) + .then((responseData) => { + if (!responseData.done) { + return null; + } + if (responseData.error) { + const err = machine_learning_utils_1.FirebaseMachineLearningError.fromOperationError(responseData.error.code, responseData.error.message); + throw err; + } + return responseData.response; + }); + }); + } + /** + * Gets the specified resource from the ML API. Resource names must be the short names without project + * ID prefix (e.g. `models/123456789`). + * + * @param {string} name Short name of the resource to get. e.g. 'models/12345' + * @returns {Promise} A promise that fulfills with the resource. + */ + getResourceWithShortName(name) { + return this.getProjectUrl() + .then((url) => { + const request = { + method: 'GET', + url: `${url}/${name}`, + }; + return this.sendRequest(request); + }); + } + /** + * Gets the specified resource from the ML API. Resource names must be the full names including project + * number prefix. + * @param fullName - Full resource name of the resource to get. e.g. projects/123465/operations/987654 + * @returns {Promise} A promise that fulfulls with the resource. + */ + getResourceWithFullName(fullName) { + const request = { + method: 'GET', + url: `${ML_V1BETA2_API}/${fullName}` + }; + return this.sendRequest(request); + } + sendRequest(request) { + request.headers = FIREBASE_VERSION_HEADER; + return this.httpClient.send(request) + .then((resp) => { + return resp.data; + }) + .catch((err) => { + throw this.toFirebaseError(err); + }); + } + toFirebaseError(err) { + if (err instanceof error_1.PrefixedFirebaseError) { + return err; + } + const response = err.response; + if (!response.isJson()) { + return new machine_learning_utils_1.FirebaseMachineLearningError('unknown-error', `Unexpected response with status: ${response.status} and body: ${response.text}`); + } + const error = response.data.error || {}; + let code = 'unknown-error'; + if (error.status && error.status in ERROR_CODE_MAPPING) { + code = ERROR_CODE_MAPPING[error.status]; + } + const message = error.message || `Unknown server error: ${response.text}`; + return new machine_learning_utils_1.FirebaseMachineLearningError(code, message); + } + getProjectUrl() { + return this.getProjectIdPrefix() + .then((projectIdPrefix) => { + return `${ML_V1BETA2_API}/${projectIdPrefix}`; + }); + } + getProjectIdPrefix() { + if (this.projectIdPrefix) { + return Promise.resolve(this.projectIdPrefix); + } + return utils.findProjectId(this.app) + .then((projectId) => { + if (!validator.isNonEmptyString(projectId)) { + throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Failed to determine project ID. Initialize the SDK with service account credentials, or ' + + 'set project ID as an app option. Alternatively, set the GOOGLE_CLOUD_PROJECT ' + + 'environment variable.'); + } + this.projectIdPrefix = `projects/${projectId}`; + return this.projectIdPrefix; + }); + } + getModelName(modelId) { + if (!validator.isNonEmptyString(modelId)) { + throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Model ID must be a non-empty string.'); + } + if (modelId.indexOf('/') !== -1) { + throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Model ID must not contain any "/" characters.'); + } + return `models/${modelId}`; + } +} +exports.MachineLearningApiClient = MachineLearningApiClient; +const ERROR_CODE_MAPPING = { + INVALID_ARGUMENT: 'invalid-argument', + NOT_FOUND: 'not-found', + RESOURCE_EXHAUSTED: 'resource-exhausted', + UNAUTHENTICATED: 'authentication-error', + UNKNOWN: 'unknown-error', +}; +function extractModelId(resourceName) { + return resourceName.split('/').pop(); +} diff --git a/node_modules/firebase-admin/lib/machine-learning/machine-learning-namespace.d.ts b/node_modules/firebase-admin/lib/machine-learning/machine-learning-namespace.d.ts new file mode 100644 index 0000000..f19bfad --- /dev/null +++ b/node_modules/firebase-admin/lib/machine-learning/machine-learning-namespace.d.ts @@ -0,0 +1,81 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +import { ListModelsResult as TListModelsResult, MachineLearning as TMachineLearning, Model as TModel, TFLiteModel as TTFLiteModel } from './machine-learning'; +import { GcsTfliteModelOptions as TGcsTfliteModelOptions, ListModelsOptions as TListModelsOptions, ModelOptions as TModelOptions, ModelOptionsBase as TModelOptionsBase } from './machine-learning-api-client'; +/** + * Gets the {@link firebase-admin.machine-learning#MachineLearning} service for the + * default app or a given app. + * + * `admin.machineLearning()` can be called with no arguments to access the + * default app's `MachineLearning` service or as `admin.machineLearning(app)` to access + * the `MachineLearning` service associated with a specific app. + * + * @example + * ```javascript + * // Get the MachineLearning service for the default app + * var defaultMachineLearning = admin.machineLearning(); + * ``` + * + * @example + * ```javascript + * // Get the MachineLearning service for a given app + * var otherMachineLearning = admin.machineLearning(otherApp); + * ``` + * + * @param app - Optional app whose `MachineLearning` service to + * return. If not provided, the default `MachineLearning` service + * will be returned. + * + * @returns The default `MachineLearning` service if no app is provided or the + * `MachineLearning` service associated with the provided app. + */ +export declare function machineLearning(app?: App): machineLearning.MachineLearning; +export declare namespace machineLearning { + /** + * Type alias to {@link firebase-admin.machine-learning#ListModelsResult}. + */ + type ListModelsResult = TListModelsResult; + /** + * Type alias to {@link firebase-admin.machine-learning#MachineLearning}. + */ + type MachineLearning = TMachineLearning; + /** + * Type alias to {@link firebase-admin.machine-learning#Model}. + */ + type Model = TModel; + /** + * Type alias to {@link firebase-admin.machine-learning#TFLiteModel}. + */ + type TFLiteModel = TTFLiteModel; + /** + * Type alias to {@link firebase-admin.machine-learning#GcsTfliteModelOptions}. + */ + type GcsTfliteModelOptions = TGcsTfliteModelOptions; + /** + * Type alias to {@link firebase-admin.machine-learning#ListModelsOptions}. + */ + type ListModelsOptions = TListModelsOptions; + /** + * Type alias to {@link firebase-admin.machine-learning#ModelOptions}. + */ + type ModelOptions = TModelOptions; + /** + * Type alias to {@link firebase-admin.machine-learning#ModelOptionsBase}. + */ + type ModelOptionsBase = TModelOptionsBase; +} diff --git a/node_modules/firebase-admin/lib/machine-learning/machine-learning-namespace.js b/node_modules/firebase-admin/lib/machine-learning/machine-learning-namespace.js new file mode 100644 index 0000000..a91b066 --- /dev/null +++ b/node_modules/firebase-admin/lib/machine-learning/machine-learning-namespace.js @@ -0,0 +1,18 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/firebase-admin/lib/machine-learning/machine-learning-utils.d.ts b/node_modules/firebase-admin/lib/machine-learning/machine-learning-utils.d.ts new file mode 100644 index 0000000..7db5c38 --- /dev/null +++ b/node_modules/firebase-admin/lib/machine-learning/machine-learning-utils.d.ts @@ -0,0 +1,22 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { PrefixedFirebaseError } from '../utils/error'; +export type MachineLearningErrorCode = 'already-exists' | 'authentication-error' | 'internal-error' | 'invalid-argument' | 'invalid-server-response' | 'not-found' | 'resource-exhausted' | 'service-unavailable' | 'unknown-error' | 'cancelled' | 'deadline-exceeded' | 'permission-denied' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'data-loss' | 'unauthenticated'; +export declare class FirebaseMachineLearningError extends PrefixedFirebaseError { + static fromOperationError(code: number, message: string): FirebaseMachineLearningError; + constructor(code: MachineLearningErrorCode, message: string); +} diff --git a/node_modules/firebase-admin/lib/machine-learning/machine-learning-utils.js b/node_modules/firebase-admin/lib/machine-learning/machine-learning-utils.js new file mode 100644 index 0000000..bbba702 --- /dev/null +++ b/node_modules/firebase-admin/lib/machine-learning/machine-learning-utils.js @@ -0,0 +1,47 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirebaseMachineLearningError = void 0; +const error_1 = require("../utils/error"); +class FirebaseMachineLearningError extends error_1.PrefixedFirebaseError { + static fromOperationError(code, message) { + switch (code) { + case 1: return new FirebaseMachineLearningError('cancelled', message); + case 2: return new FirebaseMachineLearningError('unknown-error', message); + case 3: return new FirebaseMachineLearningError('invalid-argument', message); + case 4: return new FirebaseMachineLearningError('deadline-exceeded', message); + case 5: return new FirebaseMachineLearningError('not-found', message); + case 6: return new FirebaseMachineLearningError('already-exists', message); + case 7: return new FirebaseMachineLearningError('permission-denied', message); + case 8: return new FirebaseMachineLearningError('resource-exhausted', message); + case 9: return new FirebaseMachineLearningError('failed-precondition', message); + case 10: return new FirebaseMachineLearningError('aborted', message); + case 11: return new FirebaseMachineLearningError('out-of-range', message); + case 13: return new FirebaseMachineLearningError('internal-error', message); + case 14: return new FirebaseMachineLearningError('service-unavailable', message); + case 15: return new FirebaseMachineLearningError('data-loss', message); + case 16: return new FirebaseMachineLearningError('unauthenticated', message); + default: + return new FirebaseMachineLearningError('unknown-error', message); + } + } + constructor(code, message) { + super('machine-learning', code, message); + } +} +exports.FirebaseMachineLearningError = FirebaseMachineLearningError; diff --git a/node_modules/firebase-admin/lib/machine-learning/machine-learning.d.ts b/node_modules/firebase-admin/lib/machine-learning/machine-learning.d.ts new file mode 100644 index 0000000..680b4e1 --- /dev/null +++ b/node_modules/firebase-admin/lib/machine-learning/machine-learning.d.ts @@ -0,0 +1,173 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +import { ListModelsOptions, ModelOptions } from './machine-learning-api-client'; +/** Response object for a listModels operation. */ +export interface ListModelsResult { + /** A list of models in your project. */ + readonly models: Model[]; + /** + * A token you can use to retrieve the next page of results. If null, the + * current page is the final page. + */ + readonly pageToken?: string; +} +/** + * A TensorFlow Lite Model output object + */ +export interface TFLiteModel { + /** The size of the model. */ + readonly sizeBytes: number; + /** The URI from which the model was originally provided to Firebase. */ + readonly gcsTfliteUri?: string; +} +/** + * The Firebase `MachineLearning` service interface. + */ +export declare class MachineLearning { + private readonly client; + private readonly appInternal; + /** + * The {@link firebase-admin.app#App} associated with the current `MachineLearning` + * service instance. + */ + get app(): App; + /** + * Creates a model in the current Firebase project. + * + * @param model - The model to create. + * + * @returns A Promise fulfilled with the created model. + */ + createModel(model: ModelOptions): Promise; + /** + * Updates a model's metadata or model file. + * + * @param modelId - The ID of the model to update. + * @param model - The model fields to update. + * + * @returns A Promise fulfilled with the updated model. + */ + updateModel(modelId: string, model: ModelOptions): Promise; + /** + * Publishes a Firebase ML model. + * + * A published model can be downloaded to client apps. + * + * @param modelId - The ID of the model to publish. + * + * @returns A Promise fulfilled with the published model. + */ + publishModel(modelId: string): Promise; + /** + * Unpublishes a Firebase ML model. + * + * @param modelId - The ID of the model to unpublish. + * + * @returns A Promise fulfilled with the unpublished model. + */ + unpublishModel(modelId: string): Promise; + /** + * Gets the model specified by the given ID. + * + * @param modelId - The ID of the model to get. + * + * @returns A Promise fulfilled with the model object. + */ + getModel(modelId: string): Promise; + /** + * Lists the current project's models. + * + * @param options - The listing options. + * + * @returns A promise that + * resolves with the current (filtered) list of models and the next page + * token. For the last page, an empty list of models and no page token + * are returned. + */ + listModels(options?: ListModelsOptions): Promise; + /** + * Deletes a model from the current project. + * + * @param modelId - The ID of the model to delete. + */ + deleteModel(modelId: string): Promise; + private setPublishStatus; + private signUrlIfPresent; + private signUrl; +} +/** + * A Firebase ML Model output object. + */ +export declare class Model { + private model; + private readonly client?; + /** The ID of the model. */ + get modelId(): string; + /** + * The model's name. This is the name you use from your app to load the + * model. + */ + get displayName(): string; + /** + * The model's tags, which can be used to group or filter models in list + * operations. + */ + get tags(): string[]; + /** The timestamp of the model's creation. */ + get createTime(): string; + /** The timestamp of the model's most recent update. */ + get updateTime(): string; + /** Error message when model validation fails. */ + get validationError(): string | undefined; + /** True if the model is published. */ + get published(): boolean; + /** + * The ETag identifier of the current version of the model. This value + * changes whenever you update any of the model's properties. + */ + get etag(): string; + /** + * The hash of the model's `tflite` file. This value changes only when + * you upload a new TensorFlow Lite model. + */ + get modelHash(): string | undefined; + /** Metadata about the model's TensorFlow Lite model file. */ + get tfliteModel(): TFLiteModel | undefined; + /** + * True if the model is locked by a server-side operation. You can't make + * changes to a locked model. See {@link Model.waitForUnlocked}. + */ + get locked(): boolean; + /** + * Return the model as a JSON object. + */ + toJSON(): { + [key: string]: any; + }; + /** + * Wait for the model to be unlocked. + * + * @param maxTimeMillis - The maximum time in milliseconds to wait. + * If not specified, a default maximum of 2 minutes is used. + * + * @returns A promise that resolves when the model is unlocked + * or the maximum wait time has passed. + */ + waitForUnlocked(maxTimeMillis?: number): Promise; + private static validateAndClone; +} diff --git a/node_modules/firebase-admin/lib/machine-learning/machine-learning.js b/node_modules/firebase-admin/lib/machine-learning/machine-learning.js new file mode 100644 index 0000000..539faa7 --- /dev/null +++ b/node_modules/firebase-admin/lib/machine-learning/machine-learning.js @@ -0,0 +1,336 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Model = exports.MachineLearning = void 0; +const index_1 = require("../storage/index"); +const error_1 = require("../utils/error"); +const validator = require("../utils/validator"); +const deep_copy_1 = require("../utils/deep-copy"); +const utils = require("../utils"); +const machine_learning_api_client_1 = require("./machine-learning-api-client"); +const machine_learning_utils_1 = require("./machine-learning-utils"); +/** + * The Firebase `MachineLearning` service interface. + */ +class MachineLearning { + /** + * @param app - The app for this ML service. + * @constructor + * @internal + */ + constructor(app) { + if (!validator.isNonNullObject(app) || !('options' in app)) { + throw new error_1.FirebaseError({ + code: 'machine-learning/invalid-argument', + message: 'First argument passed to admin.machineLearning() must be a ' + + 'valid Firebase app instance.', + }); + } + this.appInternal = app; + this.client = new machine_learning_api_client_1.MachineLearningApiClient(app); + } + /** + * The {@link firebase-admin.app#App} associated with the current `MachineLearning` + * service instance. + */ + get app() { + return this.appInternal; + } + /** + * Creates a model in the current Firebase project. + * + * @param model - The model to create. + * + * @returns A Promise fulfilled with the created model. + */ + createModel(model) { + return this.signUrlIfPresent(model) + .then((modelContent) => this.client.createModel(modelContent)) + .then((operation) => this.client.handleOperation(operation)) + .then((modelResponse) => new Model(modelResponse, this.client)); + } + /** + * Updates a model's metadata or model file. + * + * @param modelId - The ID of the model to update. + * @param model - The model fields to update. + * + * @returns A Promise fulfilled with the updated model. + */ + updateModel(modelId, model) { + const updateMask = utils.generateUpdateMask(model); + return this.signUrlIfPresent(model) + .then((modelContent) => this.client.updateModel(modelId, modelContent, updateMask)) + .then((operation) => this.client.handleOperation(operation)) + .then((modelResponse) => new Model(modelResponse, this.client)); + } + /** + * Publishes a Firebase ML model. + * + * A published model can be downloaded to client apps. + * + * @param modelId - The ID of the model to publish. + * + * @returns A Promise fulfilled with the published model. + */ + publishModel(modelId) { + return this.setPublishStatus(modelId, true); + } + /** + * Unpublishes a Firebase ML model. + * + * @param modelId - The ID of the model to unpublish. + * + * @returns A Promise fulfilled with the unpublished model. + */ + unpublishModel(modelId) { + return this.setPublishStatus(modelId, false); + } + /** + * Gets the model specified by the given ID. + * + * @param modelId - The ID of the model to get. + * + * @returns A Promise fulfilled with the model object. + */ + getModel(modelId) { + return this.client.getModel(modelId) + .then((modelResponse) => new Model(modelResponse, this.client)); + } + /** + * Lists the current project's models. + * + * @param options - The listing options. + * + * @returns A promise that + * resolves with the current (filtered) list of models and the next page + * token. For the last page, an empty list of models and no page token + * are returned. + */ + listModels(options = {}) { + return this.client.listModels(options) + .then((resp) => { + if (!validator.isNonNullObject(resp)) { + throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', `Invalid ListModels response: ${JSON.stringify(resp)}`); + } + let models = []; + if (resp.models) { + models = resp.models.map((rs) => new Model(rs, this.client)); + } + const result = { models }; + if (resp.nextPageToken) { + result.pageToken = resp.nextPageToken; + } + return result; + }); + } + /** + * Deletes a model from the current project. + * + * @param modelId - The ID of the model to delete. + */ + deleteModel(modelId) { + return this.client.deleteModel(modelId); + } + setPublishStatus(modelId, publish) { + const updateMask = ['state.published']; + const options = { state: { published: publish } }; + return this.client.updateModel(modelId, options, updateMask) + .then((operation) => this.client.handleOperation(operation)) + .then((modelResponse) => new Model(modelResponse, this.client)); + } + signUrlIfPresent(options) { + const modelOptions = (0, deep_copy_1.deepCopy)(options); + if ((0, machine_learning_api_client_1.isGcsTfliteModelOptions)(modelOptions)) { + return this.signUrl(modelOptions.tfliteModel.gcsTfliteUri) + .then((uri) => { + modelOptions.tfliteModel.gcsTfliteUri = uri; + return modelOptions; + }) + .catch((err) => { + throw new machine_learning_utils_1.FirebaseMachineLearningError('internal-error', `Error during signing upload url: ${err.message}`); + }); + } + return Promise.resolve(modelOptions); + } + signUrl(unsignedUrl) { + const MINUTES_IN_MILLIS = 60 * 1000; + const URL_VALID_DURATION = 10 * MINUTES_IN_MILLIS; + const gcsRegex = /^gs:\/\/([a-z0-9_.-]{3,63})\/(.+)$/; + const matches = gcsRegex.exec(unsignedUrl); + if (!matches) { + throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', `Invalid unsigned url: ${unsignedUrl}`); + } + const bucketName = matches[1]; + const blobName = matches[2]; + const bucket = (0, index_1.getStorage)(this.app).bucket(bucketName); + const blob = bucket.file(blobName); + return blob.getSignedUrl({ + action: 'read', + expires: Date.now() + URL_VALID_DURATION, + }).then((signUrl) => signUrl[0]); + } +} +exports.MachineLearning = MachineLearning; +/** + * A Firebase ML Model output object. + */ +class Model { + /** + * @internal + */ + constructor(model, client) { + this.model = Model.validateAndClone(model); + this.client = client; + } + /** The ID of the model. */ + get modelId() { + return extractModelId(this.model.name); + } + /** + * The model's name. This is the name you use from your app to load the + * model. + */ + get displayName() { + return this.model.displayName; + } + /** + * The model's tags, which can be used to group or filter models in list + * operations. + */ + get tags() { + return this.model.tags || []; + } + /** The timestamp of the model's creation. */ + get createTime() { + return new Date(this.model.createTime).toUTCString(); + } + /** The timestamp of the model's most recent update. */ + get updateTime() { + return new Date(this.model.updateTime).toUTCString(); + } + /** Error message when model validation fails. */ + get validationError() { + return this.model.state?.validationError?.message; + } + /** True if the model is published. */ + get published() { + return this.model.state?.published || false; + } + /** + * The ETag identifier of the current version of the model. This value + * changes whenever you update any of the model's properties. + */ + get etag() { + return this.model.etag; + } + /** + * The hash of the model's `tflite` file. This value changes only when + * you upload a new TensorFlow Lite model. + */ + get modelHash() { + return this.model.modelHash; + } + /** Metadata about the model's TensorFlow Lite model file. */ + get tfliteModel() { + // Make a copy so people can't directly modify the private this.model object. + return (0, deep_copy_1.deepCopy)(this.model.tfliteModel); + } + /** + * True if the model is locked by a server-side operation. You can't make + * changes to a locked model. See {@link Model.waitForUnlocked}. + */ + get locked() { + return (this.model.activeOperations?.length ?? 0) > 0; + } + /** + * Return the model as a JSON object. + */ + toJSON() { + // We can't just return this.model because it has extra fields and + // different formats etc. So we build the expected model object. + const jsonModel = { + modelId: this.modelId, + displayName: this.displayName, + tags: this.tags, + createTime: this.createTime, + updateTime: this.updateTime, + published: this.published, + etag: this.etag, + locked: this.locked, + }; + // Also add possibly undefined fields if they exist. + if (this.validationError) { + jsonModel['validationError'] = this.validationError; + } + if (this.modelHash) { + jsonModel['modelHash'] = this.modelHash; + } + if (this.tfliteModel) { + jsonModel['tfliteModel'] = this.tfliteModel; + } + return jsonModel; + } + /** + * Wait for the model to be unlocked. + * + * @param maxTimeMillis - The maximum time in milliseconds to wait. + * If not specified, a default maximum of 2 minutes is used. + * + * @returns A promise that resolves when the model is unlocked + * or the maximum wait time has passed. + */ + waitForUnlocked(maxTimeMillis) { + if ((this.model.activeOperations?.length ?? 0) > 0) { + // The client will always be defined on Models that have activeOperations + // because models with active operations came back from the server and + // were constructed with a non-empty client. + return this.client.handleOperation(this.model.activeOperations[0], { wait: true, maxTimeMillis }) + .then((modelResponse) => { + this.model = Model.validateAndClone(modelResponse); + }); + } + return Promise.resolve(); + } + static validateAndClone(model) { + if (!validator.isNonNullObject(model) || + !validator.isNonEmptyString(model.name) || + !validator.isNonEmptyString(model.createTime) || + !validator.isNonEmptyString(model.updateTime) || + !validator.isNonEmptyString(model.displayName) || + !validator.isNonEmptyString(model.etag)) { + throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-server-response', `Invalid Model response: ${JSON.stringify(model)}`); + } + const tmpModel = (0, deep_copy_1.deepCopy)(model); + // If tflite Model is specified, it must have a source of {gcsTfliteUri} + if (model.tfliteModel && + !validator.isNonEmptyString(model.tfliteModel.gcsTfliteUri)) { + // If we have some other source, ignore the whole tfliteModel. + delete tmpModel.tfliteModel; + } + // Remove '@type' field. We don't need it. + if (tmpModel['@type']) { + delete tmpModel['@type']; + } + return tmpModel; + } +} +exports.Model = Model; +function extractModelId(resourceName) { + return resourceName.split('/').pop(); +} diff --git a/node_modules/firebase-admin/lib/messaging/index.d.ts b/node_modules/firebase-admin/lib/messaging/index.d.ts new file mode 100644 index 0000000..8154bc2 --- /dev/null +++ b/node_modules/firebase-admin/lib/messaging/index.d.ts @@ -0,0 +1,53 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Firebase Cloud Messaging (FCM). + * + * @packageDocumentation + */ +import { App } from '../app'; +import { Messaging } from './messaging'; +export { Messaging, } from './messaging'; +export { AndroidConfig, AndroidFcmOptions, AndroidNotification, ApnsConfig, ApnsFcmOptions, ApnsPayload, Aps, ApsAlert, BaseMessage, BatchResponse, CriticalSound, ConditionMessage, FcmOptions, LightSettings, Message, MessagingTopicManagementResponse, MulticastMessage, Notification, SendResponse, TokenMessage, TopicMessage, WebpushConfig, WebpushFcmOptions, WebpushNotification, DataMessagePayload, MessagingOptions, MessagingPayload, NotificationMessagePayload, } from './messaging-api'; +/** + * Gets the {@link Messaging} service for the default app or a given app. + * + * `admin.messaging()` can be called with no arguments to access the default + * app's `Messaging` service or as `admin.messaging(app)` to access the + * `Messaging` service associated with aspecific app. + * + * @example + * ```javascript + * // Get the Messaging service for the default app + * const defaultMessaging = getMessaging(); + * ``` + * + * @example + * ```javascript + * // Get the Messaging service for a given app + * const otherMessaging = getMessaging(otherApp); + * ``` + * + * @param app - Optional app whose `Messaging` service to + * return. If not provided, the default `Messaging` service will be returned. + * + * @returns The default `Messaging` service if no + * app is provided or the `Messaging` service associated with the provided + * app. + */ +export declare function getMessaging(app?: App): Messaging; +export { FirebaseMessagingError, MessagingClientErrorCode } from '../utils/error'; diff --git a/node_modules/firebase-admin/lib/messaging/index.js b/node_modules/firebase-admin/lib/messaging/index.js new file mode 100644 index 0000000..9ce74bd --- /dev/null +++ b/node_modules/firebase-admin/lib/messaging/index.js @@ -0,0 +1,65 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MessagingClientErrorCode = exports.FirebaseMessagingError = exports.Messaging = void 0; +exports.getMessaging = getMessaging; +/** + * Firebase Cloud Messaging (FCM). + * + * @packageDocumentation + */ +const app_1 = require("../app"); +const messaging_1 = require("./messaging"); +var messaging_2 = require("./messaging"); +Object.defineProperty(exports, "Messaging", { enumerable: true, get: function () { return messaging_2.Messaging; } }); +/** + * Gets the {@link Messaging} service for the default app or a given app. + * + * `admin.messaging()` can be called with no arguments to access the default + * app's `Messaging` service or as `admin.messaging(app)` to access the + * `Messaging` service associated with aspecific app. + * + * @example + * ```javascript + * // Get the Messaging service for the default app + * const defaultMessaging = getMessaging(); + * ``` + * + * @example + * ```javascript + * // Get the Messaging service for a given app + * const otherMessaging = getMessaging(otherApp); + * ``` + * + * @param app - Optional app whose `Messaging` service to + * return. If not provided, the default `Messaging` service will be returned. + * + * @returns The default `Messaging` service if no + * app is provided or the `Messaging` service associated with the provided + * app. + */ +function getMessaging(app) { + if (typeof app === 'undefined') { + app = (0, app_1.getApp)(); + } + const firebaseApp = app; + return firebaseApp.getOrInitService('messaging', (app) => new messaging_1.Messaging(app)); +} +var error_1 = require("../utils/error"); +Object.defineProperty(exports, "FirebaseMessagingError", { enumerable: true, get: function () { return error_1.FirebaseMessagingError; } }); +Object.defineProperty(exports, "MessagingClientErrorCode", { enumerable: true, get: function () { return error_1.MessagingClientErrorCode; } }); diff --git a/node_modules/firebase-admin/lib/messaging/messaging-api-request-internal.d.ts b/node_modules/firebase-admin/lib/messaging/messaging-api-request-internal.d.ts new file mode 100644 index 0000000..447c21e --- /dev/null +++ b/node_modules/firebase-admin/lib/messaging/messaging-api-request-internal.d.ts @@ -0,0 +1,61 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +import { Http2SessionHandler } from '../utils/api-request'; +import { SendResponse } from './messaging-api'; +/** + * Class that provides a mechanism to send requests to the Firebase Cloud Messaging backend. + */ +export declare class FirebaseMessagingRequestHandler { + private readonly httpClient; + private readonly http2Client; + /** + * @param app - The app used to fetch access tokens to sign API requests. + * @constructor + */ + constructor(app: App); + /** + * Invokes the request handler with the provided request data. + * + * @param host - The host to which to send the request. + * @param path - The path to which to send the request. + * @param requestData - The request data. + * @returns A promise that resolves with the response. + */ + invokeRequestHandler(host: string, path: string, requestData: object): Promise; + /** + * Invokes the HTTP/1.1 request handler with the provided request data. + * + * @param host - The host to which to send the request. + * @param path - The path to which to send the request. + * @param requestData - The request data. + * @returns A promise that resolves with the {@link SendResponse}. + */ + invokeHttpRequestHandlerForSendResponse(host: string, path: string, requestData: object): Promise; + /** + * Invokes the HTTP/2 request handler with the provided request data. + * + * @param host - The host to which to send the request. + * @param path - The path to which to send the request. + * @param requestData - The request data. + * @returns A promise that resolves with the {@link SendResponse}. + */ + invokeHttp2RequestHandlerForSendResponse(host: string, path: string, requestData: object, http2SessionHandler: Http2SessionHandler): Promise; + private buildSendResponse; + private buildSendResponseFromError; +} diff --git a/node_modules/firebase-admin/lib/messaging/messaging-api-request-internal.js b/node_modules/firebase-admin/lib/messaging/messaging-api-request-internal.js new file mode 100644 index 0000000..c9b5928 --- /dev/null +++ b/node_modules/firebase-admin/lib/messaging/messaging-api-request-internal.js @@ -0,0 +1,154 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirebaseMessagingRequestHandler = void 0; +const api_request_1 = require("../utils/api-request"); +const messaging_errors_internal_1 = require("./messaging-errors-internal"); +const index_1 = require("../utils/index"); +// FCM backend constants +const FIREBASE_MESSAGING_TIMEOUT = 15000; +const FIREBASE_MESSAGING_HTTP_METHOD = 'POST'; +const FIREBASE_MESSAGING_HEADERS = { + 'X-Firebase-Client': `fire-admin-node/${(0, index_1.getSdkVersion)()}`, + 'access_token_auth': 'true', +}; +/** + * Class that provides a mechanism to send requests to the Firebase Cloud Messaging backend. + */ +class FirebaseMessagingRequestHandler { + /** + * @param app - The app used to fetch access tokens to sign API requests. + * @constructor + */ + constructor(app) { + this.httpClient = new api_request_1.AuthorizedHttpClient(app); + this.http2Client = new api_request_1.AuthorizedHttp2Client(app); + } + /** + * Invokes the request handler with the provided request data. + * + * @param host - The host to which to send the request. + * @param path - The path to which to send the request. + * @param requestData - The request data. + * @returns A promise that resolves with the response. + */ + invokeRequestHandler(host, path, requestData) { + const request = { + method: FIREBASE_MESSAGING_HTTP_METHOD, + url: `https://${host}${path}`, + data: requestData, + headers: FIREBASE_MESSAGING_HEADERS, + timeout: FIREBASE_MESSAGING_TIMEOUT, + }; + return this.httpClient.send(request).then((response) => { + // Send non-JSON responses to the catch() below where they will be treated as errors. + if (!response.isJson()) { + throw new api_request_1.RequestResponseError(response); + } + // Check for backend errors in the response. + const errorCode = (0, messaging_errors_internal_1.getErrorCode)(response.data); + if (errorCode) { + throw new api_request_1.RequestResponseError(response); + } + // Return entire response. + return response.data; + }) + .catch((err) => { + if (err instanceof api_request_1.RequestResponseError) { + throw (0, messaging_errors_internal_1.createFirebaseError)(err); + } + // Re-throw the error if it already has the proper format. + throw err; + }); + } + /** + * Invokes the HTTP/1.1 request handler with the provided request data. + * + * @param host - The host to which to send the request. + * @param path - The path to which to send the request. + * @param requestData - The request data. + * @returns A promise that resolves with the {@link SendResponse}. + */ + invokeHttpRequestHandlerForSendResponse(host, path, requestData) { + const request = { + method: FIREBASE_MESSAGING_HTTP_METHOD, + url: `https://${host}${path}`, + data: requestData, + headers: FIREBASE_MESSAGING_HEADERS, + timeout: FIREBASE_MESSAGING_TIMEOUT, + }; + return this.httpClient.send(request).then((response) => { + return this.buildSendResponse(response); + }) + .catch((err) => { + if (err instanceof api_request_1.RequestResponseError) { + return this.buildSendResponseFromError(err); + } + // Re-throw the error if it already has the proper format. + throw err; + }); + } + /** + * Invokes the HTTP/2 request handler with the provided request data. + * + * @param host - The host to which to send the request. + * @param path - The path to which to send the request. + * @param requestData - The request data. + * @returns A promise that resolves with the {@link SendResponse}. + */ + invokeHttp2RequestHandlerForSendResponse(host, path, requestData, http2SessionHandler) { + const request = { + method: FIREBASE_MESSAGING_HTTP_METHOD, + url: `https://${host}${path}`, + data: requestData, + headers: FIREBASE_MESSAGING_HEADERS, + timeout: FIREBASE_MESSAGING_TIMEOUT, + http2SessionHandler: http2SessionHandler + }; + return this.http2Client.send(request).then((response) => { + return this.buildSendResponse(response); + }) + .catch((err) => { + if (err instanceof api_request_1.RequestResponseError) { + return this.buildSendResponseFromError(err); + } + // Re-throw the error if it already has the proper format. + throw err; + }); + } + buildSendResponse(response) { + const result = { + success: response.status === 200, + }; + if (result.success) { + result.messageId = response.data.name; + } + else { + result.error = (0, messaging_errors_internal_1.createFirebaseError)(new api_request_1.RequestResponseError(response)); + } + return result; + } + buildSendResponseFromError(err) { + return { + success: false, + error: (0, messaging_errors_internal_1.createFirebaseError)(err) + }; + } +} +exports.FirebaseMessagingRequestHandler = FirebaseMessagingRequestHandler; diff --git a/node_modules/firebase-admin/lib/messaging/messaging-api.d.ts b/node_modules/firebase-admin/lib/messaging/messaging-api.d.ts new file mode 100644 index 0000000..e9c70ad --- /dev/null +++ b/node_modules/firebase-admin/lib/messaging/messaging-api.d.ts @@ -0,0 +1,914 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseArrayIndexError, FirebaseError } from '../app/index'; +export interface BaseMessage { + data?: { + [key: string]: string; + }; + notification?: Notification; + android?: AndroidConfig; + webpush?: WebpushConfig; + apns?: ApnsConfig; + fcmOptions?: FcmOptions; +} +export interface TokenMessage extends BaseMessage { + token: string; +} +export interface TopicMessage extends BaseMessage { + topic: string; +} +export interface ConditionMessage extends BaseMessage { + condition: string; +} +/** + * Payload for the {@link Messaging.send} operation. The payload contains all the fields + * in the BaseMessage type, and exactly one of token, topic or condition. + */ +export type Message = TokenMessage | TopicMessage | ConditionMessage; +/** + * Payload for the {@link Messaging.sendEachForMulticast} method. The payload contains all the fields + * in the BaseMessage type, and a list of tokens. + */ +export interface MulticastMessage extends BaseMessage { + tokens: string[]; +} +/** + * A notification that can be included in {@link Message}. + */ +export interface Notification { + /** + * The title of the notification. + */ + title?: string; + /** + * The notification body + */ + body?: string; + /** + * URL of an image to be displayed in the notification. + */ + imageUrl?: string; +} +/** + * Represents platform-independent options for features provided by the FCM SDKs. + */ +export interface FcmOptions { + /** + * The label associated with the message's analytics data. + */ + analyticsLabel?: string; +} +/** + * Represents the WebPush protocol options that can be included in an + * {@link Message}. + */ +export interface WebpushConfig { + /** + * A collection of WebPush headers. Header values must be strings. + * + * See {@link https://tools.ietf.org/html/rfc8030#section-5 | WebPush specification} + * for supported headers. + */ + headers?: { + [key: string]: string; + }; + /** + * A collection of data fields. + */ + data?: { + [key: string]: string; + }; + /** + * A WebPush notification payload to be included in the message. + */ + notification?: WebpushNotification; + /** + * Options for features provided by the FCM SDK for Web. + */ + fcmOptions?: WebpushFcmOptions; +} +/** Represents options for features provided by the FCM SDK for Web + * (which are not part of the Webpush standard). + */ +export interface WebpushFcmOptions { + /** + * The link to open when the user clicks on the notification. + * For all URL values, HTTPS is required. + */ + link?: string; +} +/** + * Represents the WebPush-specific notification options that can be included in + * {@link WebpushConfig}. This supports most of the standard + * options as defined in the Web Notification + * {@link https://developer.mozilla.org/en-US/docs/Web/API/notification/Notification | specification}. + */ +export interface WebpushNotification { + /** + * Title text of the notification. + */ + title?: string; + /** + * An array of notification actions representing the actions + * available to the user when the notification is presented. + */ + actions?: Array<{ + /** + * An action available to the user when the notification is presented + */ + action: string; + /** + * Optional icon for a notification action. + */ + icon?: string; + /** + * Title of the notification action. + */ + title: string; + }>; + /** + * URL of the image used to represent the notification when there is + * not enough space to display the notification itself. + */ + badge?: string; + /** + * Body text of the notification. + */ + body?: string; + /** + * Arbitrary data that you want associated with the notification. + * This can be of any data type. + */ + data?: any; + /** + * The direction in which to display the notification. Must be one + * of `auto`, `ltr` or `rtl`. + */ + dir?: 'auto' | 'ltr' | 'rtl'; + /** + * URL to the notification icon. + */ + icon?: string; + /** + * URL of an image to be displayed in the notification. + */ + image?: string; + /** + * The notification's language as a BCP 47 language tag. + */ + lang?: string; + /** + * A boolean specifying whether the user should be notified after a + * new notification replaces an old one. Defaults to false. + */ + renotify?: boolean; + /** + * Indicates that a notification should remain active until the user + * clicks or dismisses it, rather than closing automatically. + * Defaults to false. + */ + requireInteraction?: boolean; + /** + * A boolean specifying whether the notification should be silent. + * Defaults to false. + */ + silent?: boolean; + /** + * An identifying tag for the notification. + */ + tag?: string; + /** + * Timestamp of the notification. Refer to + * https://developer.mozilla.org/en-US/docs/Web/API/notification/timestamp + * for details. + */ + timestamp?: number; + /** + * A vibration pattern for the device's vibration hardware to emit + * when the notification fires. + */ + vibrate?: number | number[]; + [key: string]: any; +} +/** + * Represents the APNs-specific options that can be included in an + * {@link Message}. Refer to + * {@link https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html | + * Apple documentation} for various headers and payload fields supported by APNs. + */ +export interface ApnsConfig { + /** + * APN `pushToStartToken` or `pushToken` to start or update live activities. + */ + liveActivityToken?: string; + /** + * A collection of APNs headers. Header values must be strings. + */ + headers?: { + [key: string]: string; + }; + /** + * An APNs payload to be included in the message. + */ + payload?: ApnsPayload; + /** + * Options for features provided by the FCM SDK for iOS. + */ + fcmOptions?: ApnsFcmOptions; +} +/** + * Represents the payload of an APNs message. Mainly consists of the `aps` + * dictionary. But may also contain other arbitrary custom keys. + */ +export interface ApnsPayload { + /** + * The `aps` dictionary to be included in the message. + */ + aps: Aps; + [customData: string]: any; +} +/** + * Represents the {@link https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html | + * aps dictionary} that is part of APNs messages. + */ +export interface Aps { + /** + * Alert to be included in the message. This may be a string or an object of + * type `admin.messaging.ApsAlert`. + */ + alert?: string | ApsAlert; + /** + * Badge to be displayed with the message. Set to 0 to remove the badge. When + * not specified, the badge will remain unchanged. + */ + badge?: number; + /** + * Sound to be played with the message. + */ + sound?: string | CriticalSound; + /** + * Specifies whether to configure a background update notification. + */ + contentAvailable?: boolean; + /** + * Specifies whether to set the `mutable-content` property on the message + * so the clients can modify the notification via app extensions. + */ + mutableContent?: boolean; + /** + * Type of the notification. + */ + category?: string; + /** + * An app-specific identifier for grouping notifications. + */ + threadId?: string; + [customData: string]: any; +} +export interface ApsAlert { + title?: string; + subtitle?: string; + body?: string; + locKey?: string; + locArgs?: string[]; + titleLocKey?: string; + titleLocArgs?: string[]; + subtitleLocKey?: string; + subtitleLocArgs?: string[]; + actionLocKey?: string; + launchImage?: string; +} +/** + * Represents a critical sound configuration that can be included in the + * `aps` dictionary of an APNs payload. + */ +export interface CriticalSound { + /** + * The critical alert flag. Set to `true` to enable the critical alert. + */ + critical?: boolean; + /** + * The name of a sound file in the app's main bundle or in the `Library/Sounds` + * folder of the app's container directory. Specify the string "default" to play + * the system sound. + */ + name: string; + /** + * The volume for the critical alert's sound. Must be a value between 0.0 + * (silent) and 1.0 (full volume). + */ + volume?: number; +} +/** + * Represents options for features provided by the FCM SDK for iOS. + */ +export interface ApnsFcmOptions { + /** + * The label associated with the message's analytics data. + */ + analyticsLabel?: string; + /** + * URL of an image to be displayed in the notification. + */ + imageUrl?: string; +} +/** + * Represents the Android-specific options that can be included in an + * {@link Message}. + */ +export interface AndroidConfig { + /** + * Collapse key for the message. Collapse key serves as an identifier for a + * group of messages that can be collapsed, so that only the last message gets + * sent when delivery can be resumed. A maximum of four different collapse keys + * may be active at any given time. + */ + collapseKey?: string; + /** + * Priority of the message. Must be either `normal` or `high`. + */ + priority?: ('high' | 'normal'); + /** + * Time-to-live duration of the message in milliseconds. + */ + ttl?: number; + /** + * Package name of the application where the registration tokens must match + * in order to receive the message. + */ + restrictedPackageName?: string; + /** + * A collection of data fields to be included in the message. All values must + * be strings. When provided, overrides any data fields set on the top-level + * {@link Message}. + */ + data?: { + [key: string]: string; + }; + /** + * Android notification to be included in the message. + */ + notification?: AndroidNotification; + /** + * Options for features provided by the FCM SDK for Android. + */ + fcmOptions?: AndroidFcmOptions; + /** + * A boolean indicating whether messages will be allowed to be delivered to + * the app while the device is in direct boot mode. + */ + directBootOk?: boolean; +} +/** + * Represents the Android-specific notification options that can be included in + * {@link AndroidConfig}. + */ +export interface AndroidNotification { + /** + * Title of the Android notification. When provided, overrides the title set via + * `admin.messaging.Notification`. + */ + title?: string; + /** + * Body of the Android notification. When provided, overrides the body set via + * `admin.messaging.Notification`. + */ + body?: string; + /** + * Icon resource for the Android notification. + */ + icon?: string; + /** + * Notification icon color in `#rrggbb` format. + */ + color?: string; + /** + * File name of the sound to be played when the device receives the + * notification. + */ + sound?: string; + /** + * Notification tag. This is an identifier used to replace existing + * notifications in the notification drawer. If not specified, each request + * creates a new notification. + */ + tag?: string; + /** + * URL of an image to be displayed in the notification. + */ + imageUrl?: string; + /** + * Action associated with a user click on the notification. If specified, an + * activity with a matching Intent Filter is launched when a user clicks on the + * notification. + */ + clickAction?: string; + /** + * Key of the body string in the app's string resource to use to localize the + * body text. + * + */ + bodyLocKey?: string; + /** + * An array of resource keys that will be used in place of the format + * specifiers in `bodyLocKey`. + */ + bodyLocArgs?: string[]; + /** + * Key of the title string in the app's string resource to use to localize the + * title text. + */ + titleLocKey?: string; + /** + * An array of resource keys that will be used in place of the format + * specifiers in `titleLocKey`. + */ + titleLocArgs?: string[]; + /** + * The Android notification channel ID (new in Android O). The app must create + * a channel with this channel ID before any notification with this channel ID + * can be received. If you don't send this channel ID in the request, or if the + * channel ID provided has not yet been created by the app, FCM uses the channel + * ID specified in the app manifest. + */ + channelId?: string; + /** + * Sets the "ticker" text, which is sent to accessibility services. Prior to + * API level 21 (Lollipop), sets the text that is displayed in the status bar + * when the notification first arrives. + */ + ticker?: string; + /** + * When set to `false` or unset, the notification is automatically dismissed when + * the user clicks it in the panel. When set to `true`, the notification persists + * even when the user clicks it. + */ + sticky?: boolean; + /** + * For notifications that inform users about events with an absolute time reference, sets + * the time that the event in the notification occurred. Notifications + * in the panel are sorted by this time. + */ + eventTimestamp?: Date; + /** + * Sets whether or not this notification is relevant only to the current device. + * Some notifications can be bridged to other devices for remote display, such as + * a Wear OS watch. This hint can be set to recommend this notification not be bridged. + * See {@link https://developer.android.com/training/wearables/notifications/bridger#existing-method-of-preventing-bridging | + * Wear OS guides}. + */ + localOnly?: boolean; + /** + * Sets the relative priority for this notification. Low-priority notifications + * may be hidden from the user in certain situations. Note this priority differs + * from `AndroidMessagePriority`. This priority is processed by the client after + * the message has been delivered. Whereas `AndroidMessagePriority` is an FCM concept + * that controls when the message is delivered. + */ + priority?: ('min' | 'low' | 'default' | 'high' | 'max'); + /** + * Sets the vibration pattern to use. Pass in an array of milliseconds to + * turn the vibrator on or off. The first value indicates the duration to wait before + * turning the vibrator on. The next value indicates the duration to keep the + * vibrator on. Subsequent values alternate between duration to turn the vibrator + * off and to turn the vibrator on. If `vibrateTimingsMillis` is set and `defaultVibrateTimings` + * is set to `true`, the default value is used instead of the user-specified `vibrateTimingsMillis`. + */ + vibrateTimingsMillis?: number[]; + /** + * If set to `true`, use the Android framework's default vibrate pattern for the + * notification. Default values are specified in {@link https://android.googlesource.com/platform/frameworks/base/+/master/core/res/res/values/config.xml | + * config.xml}. If `defaultVibrateTimings` is set to `true` and `vibrateTimingsMillis` is also set, + * the default value is used instead of the user-specified `vibrateTimingsMillis`. + */ + defaultVibrateTimings?: boolean; + /** + * If set to `true`, use the Android framework's default sound for the notification. + * Default values are specified in {@link https://android.googlesource.com/platform/frameworks/base/+/master/core/res/res/values/config.xml | + * config.xml}. + */ + defaultSound?: boolean; + /** + * Settings to control the notification's LED blinking rate and color if LED is + * available on the device. The total blinking time is controlled by the OS. + */ + lightSettings?: LightSettings; + /** + * If set to `true`, use the Android framework's default LED light settings + * for the notification. Default values are specified in {@link https://android.googlesource.com/platform/frameworks/base/+/master/core/res/res/values/config.xml | + * config.xml}. + * If `default_light_settings` is set to `true` and `light_settings` is also set, + * the user-specified `light_settings` is used instead of the default value. + */ + defaultLightSettings?: boolean; + /** + * Sets the visibility of the notification. Must be either `private`, `public`, + * or `secret`. If unspecified, it remains undefined in the Admin SDK, and + * defers to the FCM backend's default mapping. + */ + visibility?: ('private' | 'public' | 'secret'); + /** + * Sets the number of items this notification represents. May be displayed as a + * badge count for Launchers that support badging. See {@link https://developer.android.com/training/notify-user/badges | + * NotificationBadge}. + * For example, this might be useful if you're using just one notification to + * represent multiple new messages but you want the count here to represent + * the number of total new messages. If zero or unspecified, systems + * that support badging use the default, which is to increment a number + * displayed on the long-press menu each time a new notification arrives. + */ + notificationCount?: number; + /** + * Sets if this notification should attempt to be proxied. Must be either + * `allow`, `deny` or `if_priority_lowered`. If unspecified, it remains + * undefined in the Admin SDK, and defers to the FCM backend's default mapping. + */ + proxy?: ('allow' | 'deny' | 'if_priority_lowered'); +} +/** + * Represents settings to control notification LED that can be included in + * {@link AndroidNotification}. + */ +export interface LightSettings { + /** + * Required. Sets color of the LED in `#rrggbb` or `#rrggbbaa` format. + */ + color: string; + /** + * Required. Along with `light_off_duration`, defines the blink rate of LED flashes. + */ + lightOnDurationMillis: number; + /** + * Required. Along with `light_on_duration`, defines the blink rate of LED flashes. + */ + lightOffDurationMillis: number; +} +/** + * Represents options for features provided by the FCM SDK for Android. + */ +export interface AndroidFcmOptions { + /** + * The label associated with the message's analytics data. + */ + analyticsLabel?: string; +} +/** + * Interface representing an FCM legacy API data message payload. Data + * messages let developers send up to 4KB of custom key-value pairs. The + * keys and values must both be strings. Keys can be any custom string, + * except for the following reserved strings: + * + *
                            + *
                          • from
                          • + *
                          • Anything starting with google.
                          • + *
                          + * + * See {@link https://firebase.google.com/docs/cloud-messaging/send-message | Build send requests} + * for code samples and detailed documentation. + */ +export interface DataMessagePayload { + [key: string]: string; +} +/** + * Interface representing an FCM legacy API notification message payload. + * Notification messages let developers send up to 4KB of predefined + * key-value pairs. Accepted keys are outlined below. + * + * See {@link https://firebase.google.com/docs/cloud-messaging/send-message | Build send requests} + * for code samples and detailed documentation. + */ +export interface NotificationMessagePayload { + /** + * Identifier used to replace existing notifications in the notification drawer. + * + * If not specified, each request creates a new notification. + * + * If specified and a notification with the same tag is already being shown, + * the new notification replaces the existing one in the notification drawer. + * + * **Platforms:** Android + */ + tag?: string; + /** + * The notification's body text. + * + * **Platforms:** iOS, Android, Web + */ + body?: string; + /** + * The notification's icon. + * + * **Android:** Sets the notification icon to `myicon` for drawable resource + * `myicon`. If you don't send this key in the request, FCM displays the + * launcher icon specified in your app manifest. + * + * **Web:** The URL to use for the notification's icon. + * + * **Platforms:** Android, Web + */ + icon?: string; + /** + * The value of the badge on the home screen app icon. + * + * If not specified, the badge is not changed. + * + * If set to `0`, the badge is removed. + * + * **Platforms:** iOS + */ + badge?: string; + /** + * The notification icon's color, expressed in `#rrggbb` format. + * + * **Platforms:** Android + */ + color?: string; + /** + * The sound to be played when the device receives a notification. Supports + * "default" for the default notification sound of the device or the filename of a + * sound resource bundled in the app. + * Sound files must reside in `/res/raw/`. + * + * **Platforms:** Android + */ + sound?: string; + /** + * The notification's title. + * + * **Platforms:** iOS, Android, Web + */ + title?: string; + /** + * The key to the body string in the app's string resources to use to localize + * the body text to the user's current localization. + * + * **iOS:** Corresponds to `loc-key` in the APNs payload. See + * {@link https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html | + * Payload Key Reference} and + * {@link https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH10-SW9 | + * Localizing the Content of Your Remote Notifications} for more information. + * + * **Android:** See + * {@link http://developer.android.com/guide/topics/resources/string-resource.html | String Resources} + * for more information. + * + * **Platforms:** iOS, Android + */ + bodyLocKey?: string; + /** + * Variable string values to be used in place of the format specifiers in + * `body_loc_key` to use to localize the body text to the user's current + * localization. + * + * The value should be a stringified JSON array. + * + * **iOS:** Corresponds to `loc-args` in the APNs payload. See + * {@link https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html | + * Payload Key Reference} and + * {@link https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH10-SW9 | + * Localizing the Content of Your Remote Notifications} for more information. + * + * **Android:** See + * {@link http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling | + * Formatting and Styling} for more information. + * + * **Platforms:** iOS, Android + */ + bodyLocArgs?: string; + /** + * Action associated with a user click on the notification. If specified, an + * activity with a matching Intent Filter is launched when a user clicks on the + * notification. + * + * * **Platforms:** Android + */ + clickAction?: string; + /** + * The key to the title string in the app's string resources to use to localize + * the title text to the user's current localization. + * + * **iOS:** Corresponds to `title-loc-key` in the APNs payload. See + * {@link https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html | + * Payload Key Reference} and + * {@link https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH10-SW9 | + * Localizing the Content of Your Remote Notifications} for more information. + * + * **Android:** See + * {@link http://developer.android.com/guide/topics/resources/string-resource.html | String Resources} + * for more information. + * + * **Platforms:** iOS, Android + */ + titleLocKey?: string; + /** + * Variable string values to be used in place of the format specifiers in + * `title_loc_key` to use to localize the title text to the user's current + * localization. + * + * The value should be a stringified JSON array. + * + * **iOS:** Corresponds to `title-loc-args` in the APNs payload. See + * {@link https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html | + * Payload Key Reference} and + * {@link https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH10-SW9 | + * Localizing the Content of Your Remote Notifications} for more information. + * + * **Android:** See + * {@link http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling | + * Formatting and Styling} for more information. + * + * **Platforms:** iOS, Android + */ + titleLocArgs?: string; + [key: string]: string | undefined; +} +/** + * Interface representing a Firebase Cloud Messaging message payload. One or + * both of the `data` and `notification` keys are required. + * + * See {@link https://firebase.google.com/docs/cloud-messaging/send-message | Build send requests} + * for code samples and detailed documentation. + */ +export interface MessagingPayload { + /** + * The data message payload. + */ + data?: DataMessagePayload; + /** + * The notification message payload. + */ + notification?: NotificationMessagePayload; +} +/** + * Interface representing the options that can be provided when sending a + * message via the FCM legacy APIs. + * + * See {@link https://firebase.google.com/docs/cloud-messaging/send-message | Build send requests} + * for code samples and detailed documentation. + */ +export interface MessagingOptions { + /** + * Whether or not the message should actually be sent. When set to `true`, + * allows developers to test a request without actually sending a message. When + * set to `false`, the message will be sent. + * + * **Default value:** `false` + */ + dryRun?: boolean; + /** + * The priority of the message. Valid values are `"normal"` and `"high".` On + * iOS, these correspond to APNs priorities `5` and `10`. + * + * By default, notification messages are sent with high priority, and data + * messages are sent with normal priority. Normal priority optimizes the client + * app's battery consumption and should be used unless immediate delivery is + * required. For messages with normal priority, the app may receive the message + * with unspecified delay. + * + * When a message is sent with high priority, it is sent immediately, and the + * app can wake a sleeping device and open a network connection to your server. + * + * For more information, see + * {@link https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message | + * Setting the priority of a message}. + * + * **Default value:** `"high"` for notification messages, `"normal"` for data + * messages + */ + priority?: string; + /** + * How long (in seconds) the message should be kept in FCM storage if the device + * is offline. The maximum time to live supported is four weeks, and the default + * value is also four weeks. For more information, see + * {@link https://firebase.google.com/docs/cloud-messaging/concept-options#ttl | Setting the lifespan of a message}. + * + * **Default value:** `2419200` (representing four weeks, in seconds) + */ + timeToLive?: number; + /** + * String identifying a group of messages (for example, "Updates Available") + * that can be collapsed, so that only the last message gets sent when delivery + * can be resumed. This is used to avoid sending too many of the same messages + * when the device comes back online or becomes active. + * + * There is no guarantee of the order in which messages get sent. + * + * A maximum of four different collapse keys is allowed at any given time. This + * means FCM server can simultaneously store four different + * send-to-sync messages per client app. If you exceed this number, there is no + * guarantee which four collapse keys the FCM server will keep. + * + * **Default value:** None + */ + collapseKey?: string; + /** + * On iOS, use this field to represent `mutable-content` in the APNs payload. + * When a notification is sent and this is set to `true`, the content of the + * notification can be modified before it is displayed, using a + * {@link https://developer.apple.com/reference/usernotifications/unnotificationserviceextension | + * Notification Service app extension}. + * + * On Android and Web, this parameter will be ignored. + * + * **Default value:** `false` + */ + mutableContent?: boolean; + /** + * On iOS, use this field to represent `content-available` in the APNs payload. + * When a notification or data message is sent and this is set to `true`, an + * inactive client app is awoken. On Android, data messages wake the app by + * default. On Chrome, this flag is currently not supported. + * + * **Default value:** `false` + */ + contentAvailable?: boolean; + /** + * The package name of the application which the registration tokens must match + * in order to receive the message. + * + * **Default value:** None + */ + restrictedPackageName?: string; + [key: string]: any | undefined; +} +/** + * Interface representing the server response from the + * {@link Messaging.subscribeToTopic} and {@link Messaging.unsubscribeFromTopic} + * methods. + * + * See + * {@link https://firebase.google.com/docs/cloud-messaging/manage-topics | + * Manage topics from the server} for code samples and detailed documentation. + */ +export interface MessagingTopicManagementResponse { + /** + * The number of registration tokens that could not be subscribed to the topic + * and resulted in an error. + */ + failureCount: number; + /** + * The number of registration tokens that were successfully subscribed to the + * topic. + */ + successCount: number; + /** + * An array of errors corresponding to the provided registration token(s). The + * length of this array will be equal to {@link MessagingTopicManagementResponse.failureCount}. + */ + errors: FirebaseArrayIndexError[]; +} +/** + * Interface representing the server response from the + * {@link Messaging.sendEach} and {@link Messaging.sendEachForMulticast} methods. + */ +export interface BatchResponse { + /** + * An array of responses, each corresponding to a message. + */ + responses: SendResponse[]; + /** + * The number of messages that were successfully handed off for sending. + */ + successCount: number; + /** + * The number of messages that resulted in errors when sending. + */ + failureCount: number; +} +/** + * Interface representing the status of an individual message that was sent as + * part of a batch request. + */ +export interface SendResponse { + /** + * A boolean indicating if the message was successfully handed off to FCM or + * not. When true, the `messageId` attribute is guaranteed to be set. When + * false, the `error` attribute is guaranteed to be set. + */ + success: boolean; + /** + * A unique message ID string, if the message was handed off to FCM for + * delivery. + * + */ + messageId?: string; + /** + * An error, if the message was not handed off to FCM successfully. + */ + error?: FirebaseError; +} diff --git a/node_modules/firebase-admin/lib/messaging/messaging-api.js b/node_modules/firebase-admin/lib/messaging/messaging-api.js new file mode 100644 index 0000000..0457090 --- /dev/null +++ b/node_modules/firebase-admin/lib/messaging/messaging-api.js @@ -0,0 +1,19 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/firebase-admin/lib/messaging/messaging-errors-internal.d.ts b/node_modules/firebase-admin/lib/messaging/messaging-errors-internal.d.ts new file mode 100644 index 0000000..a7c9e58 --- /dev/null +++ b/node_modules/firebase-admin/lib/messaging/messaging-errors-internal.d.ts @@ -0,0 +1,31 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { RequestResponseError } from '../utils/api-request'; +import { FirebaseMessagingError } from '../utils/error'; +/** + * Creates a new `FirebaseMessagingError` by extracting the error code, message and other relevant + * details from a `RequestResponseError` response. + * + * @param err - The `RequestResponseError` to convert into a Firebase error + * @returns A Firebase error that can be returned to the user. + */ +export declare function createFirebaseError(err: RequestResponseError): FirebaseMessagingError; +/** + * @param response - The response to check for errors. + * @returns The error code if present; null otherwise. + */ +export declare function getErrorCode(response: any): string | null; diff --git a/node_modules/firebase-admin/lib/messaging/messaging-errors-internal.js b/node_modules/firebase-admin/lib/messaging/messaging-errors-internal.js new file mode 100644 index 0000000..8de8490 --- /dev/null +++ b/node_modules/firebase-admin/lib/messaging/messaging-errors-internal.js @@ -0,0 +1,104 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createFirebaseError = createFirebaseError; +exports.getErrorCode = getErrorCode; +const error_1 = require("../utils/error"); +const validator = require("../utils/validator"); +/** + * Creates a new `FirebaseMessagingError` by extracting the error code, message and other relevant + * details from a `RequestResponseError` response. + * + * @param err - The `RequestResponseError` to convert into a Firebase error + * @returns A Firebase error that can be returned to the user. + */ +function createFirebaseError(err) { + if (err.response.isJson()) { + // For JSON responses, map the server response to a client-side error. + const json = err.response.data; + const errorCode = getErrorCode(json); + const errorMessage = getErrorMessage(json); + return error_1.FirebaseMessagingError.fromServerError(errorCode, errorMessage, json); + } + // Non-JSON response + let error; + switch (err.response.status) { + case 400: + error = error_1.MessagingClientErrorCode.INVALID_ARGUMENT; + break; + case 401: + case 403: + error = error_1.MessagingClientErrorCode.AUTHENTICATION_ERROR; + break; + case 500: + error = error_1.MessagingClientErrorCode.INTERNAL_ERROR; + break; + case 503: + error = error_1.MessagingClientErrorCode.SERVER_UNAVAILABLE; + break; + default: + // Treat non-JSON responses with unexpected status codes as unknown errors. + error = error_1.MessagingClientErrorCode.UNKNOWN_ERROR; + } + return new error_1.FirebaseMessagingError({ + code: error.code, + message: `${error.message} Raw server response: "${err.response.text}". Status code: ` + + `${err.response.status}.`, + }); +} +/** + * @param response - The response to check for errors. + * @returns The error code if present; null otherwise. + */ +function getErrorCode(response) { + if (validator.isNonNullObject(response) && 'error' in response) { + const error = response.error; + if (validator.isString(error)) { + return error; + } + if (validator.isArray(error.details)) { + const fcmErrorType = 'type.googleapis.com/google.firebase.fcm.v1.FcmError'; + for (const element of error.details) { + if (element['@type'] === fcmErrorType) { + return element.errorCode; + } + } + } + if ('status' in error) { + return error.status; + } + else { + return error.message; + } + } + return null; +} +/** + * Extracts error message from the given response object. + * + * @param response - The response to check for errors. + * @returns The error message if present; null otherwise. + */ +function getErrorMessage(response) { + if (validator.isNonNullObject(response) && + 'error' in response && + validator.isNonEmptyString(response.error.message)) { + return response.error.message; + } + return null; +} diff --git a/node_modules/firebase-admin/lib/messaging/messaging-internal.d.ts b/node_modules/firebase-admin/lib/messaging/messaging-internal.d.ts new file mode 100644 index 0000000..88d2e9d --- /dev/null +++ b/node_modules/firebase-admin/lib/messaging/messaging-internal.d.ts @@ -0,0 +1,27 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Message } from './messaging-api'; +export declare const BLACKLISTED_DATA_PAYLOAD_KEYS: string[]; +export declare const BLACKLISTED_OPTIONS_KEYS: string[]; +/** + * Checks if the given Message object is valid. Recursively validates all the child objects + * included in the message (android, apns, data etc.). If successful, transforms the message + * in place by renaming the keys to what's expected by the remote FCM service. + * + * @param {Message} Message An object to be validated. + */ +export declare function validateMessage(message: Message): void; diff --git a/node_modules/firebase-admin/lib/messaging/messaging-internal.js b/node_modules/firebase-admin/lib/messaging/messaging-internal.js new file mode 100644 index 0000000..c8fa09b --- /dev/null +++ b/node_modules/firebase-admin/lib/messaging/messaging-internal.js @@ -0,0 +1,505 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BLACKLISTED_OPTIONS_KEYS = exports.BLACKLISTED_DATA_PAYLOAD_KEYS = void 0; +exports.validateMessage = validateMessage; +const index_1 = require("../utils/index"); +const error_1 = require("../utils/error"); +const validator = require("../utils/validator"); +// Keys which are not allowed in the messaging data payload object. +exports.BLACKLISTED_DATA_PAYLOAD_KEYS = ['from']; +// Keys which are not allowed in the messaging options object. +exports.BLACKLISTED_OPTIONS_KEYS = [ + 'condition', 'data', 'notification', 'registrationIds', 'registration_ids', 'to', +]; +/** + * Checks if the given Message object is valid. Recursively validates all the child objects + * included in the message (android, apns, data etc.). If successful, transforms the message + * in place by renaming the keys to what's expected by the remote FCM service. + * + * @param {Message} Message An object to be validated. + */ +function validateMessage(message) { + if (!validator.isNonNullObject(message)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'Message must be a non-null object'); + } + const anyMessage = message; + if (anyMessage.topic) { + // If the topic name is prefixed, remove it. + if (anyMessage.topic.startsWith('/topics/')) { + anyMessage.topic = anyMessage.topic.replace(/^\/topics\//, ''); + } + // Checks for illegal characters and empty string. + if (!/^[a-zA-Z0-9-_.~%]+$/.test(anyMessage.topic)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'Malformed topic name'); + } + } + const targets = [anyMessage.token, anyMessage.topic, anyMessage.condition]; + if (targets.filter((v) => validator.isNonEmptyString(v)).length !== 1) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'Exactly one of topic, token or condition is required'); + } + validateStringMap(message.data, 'data'); + validateAndroidConfig(message.android); + validateWebpushConfig(message.webpush); + validateApnsConfig(message.apns); + validateFcmOptions(message.fcmOptions); + validateNotification(message.notification); +} +/** + * Checks if the given object only contains strings as child values. + * + * @param {object} map An object to be validated. + * @param {string} label A label to be included in the errors thrown. + */ +function validateStringMap(map, label) { + if (typeof map === 'undefined') { + return; + } + else if (!validator.isNonNullObject(map)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, `${label} must be a non-null object`); + } + Object.keys(map).forEach((key) => { + if (!validator.isString(map[key])) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, `${label} must only contain string values`); + } + }); +} +/** + * Checks if the given WebpushConfig object is valid. The object must have valid headers and data. + * + * @param {WebpushConfig} config An object to be validated. + */ +function validateWebpushConfig(config) { + if (typeof config === 'undefined') { + return; + } + else if (!validator.isNonNullObject(config)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'webpush must be a non-null object'); + } + validateStringMap(config.headers, 'webpush.headers'); + validateStringMap(config.data, 'webpush.data'); +} +/** + * Checks if the given ApnsConfig object is valid. The object must have valid headers and a + * payload. + * + * @param {ApnsConfig} config An object to be validated. + */ +function validateApnsConfig(config) { + if (typeof config === 'undefined') { + return; + } + else if (!validator.isNonNullObject(config)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns must be a non-null object'); + } + validateApnsLiveActivityToken(config.liveActivityToken); + validateStringMap(config.headers, 'apns.headers'); + validateApnsPayload(config.payload); + validateApnsFcmOptions(config.fcmOptions); + const propertyMappings = { + liveActivityToken: 'live_activity_token' + }; + (0, index_1.renameProperties)(config, propertyMappings); +} +function validateApnsLiveActivityToken(liveActivityToken) { + if (typeof liveActivityToken === 'undefined') { + return; + } + else if (!validator.isString(liveActivityToken)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.liveActivityToken must be a string value'); + } + else if (!validator.isNonEmptyString(liveActivityToken)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.liveActivityToken must be a non-empty string'); + } +} +/** + * Checks if the given ApnsFcmOptions object is valid. + * + * @param {ApnsFcmOptions} fcmOptions An object to be validated. + */ +function validateApnsFcmOptions(fcmOptions) { + if (typeof fcmOptions === 'undefined') { + return; + } + else if (!validator.isNonNullObject(fcmOptions)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'fcmOptions must be a non-null object'); + } + if (typeof fcmOptions.imageUrl !== 'undefined' && + !validator.isURL(fcmOptions.imageUrl)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'imageUrl must be a valid URL string'); + } + if (typeof fcmOptions.analyticsLabel !== 'undefined' && !validator.isString(fcmOptions.analyticsLabel)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'analyticsLabel must be a string value'); + } + const propertyMappings = { + imageUrl: 'image', + }; + Object.keys(propertyMappings).forEach((key) => { + if (key in fcmOptions && propertyMappings[key] in fcmOptions) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, `Multiple specifications for ${key} in ApnsFcmOptions`); + } + }); + (0, index_1.renameProperties)(fcmOptions, propertyMappings); +} +/** + * Checks if the given FcmOptions object is valid. + * + * @param {FcmOptions} fcmOptions An object to be validated. + */ +function validateFcmOptions(fcmOptions) { + if (typeof fcmOptions === 'undefined') { + return; + } + else if (!validator.isNonNullObject(fcmOptions)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'fcmOptions must be a non-null object'); + } + if (typeof fcmOptions.analyticsLabel !== 'undefined' && !validator.isString(fcmOptions.analyticsLabel)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'analyticsLabel must be a string value'); + } +} +/** + * Checks if the given Notification object is valid. + * + * @param {Notification} notification An object to be validated. + */ +function validateNotification(notification) { + if (typeof notification === 'undefined') { + return; + } + else if (!validator.isNonNullObject(notification)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'notification must be a non-null object'); + } + if (typeof notification.imageUrl !== 'undefined' && !validator.isURL(notification.imageUrl)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'notification.imageUrl must be a valid URL string'); + } + const propertyMappings = { + imageUrl: 'image', + }; + Object.keys(propertyMappings).forEach((key) => { + if (key in notification && propertyMappings[key] in notification) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, `Multiple specifications for ${key} in Notification`); + } + }); + (0, index_1.renameProperties)(notification, propertyMappings); +} +/** + * Checks if the given ApnsPayload object is valid. The object must have a valid aps value. + * + * @param {ApnsPayload} payload An object to be validated. + */ +function validateApnsPayload(payload) { + if (typeof payload === 'undefined') { + return; + } + else if (!validator.isNonNullObject(payload)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.payload must be a non-null object'); + } + validateAps(payload.aps); +} +/** + * Checks if the given Aps object is valid. The object must have a valid alert. If the validation + * is successful, transforms the input object by renaming the keys to valid APNS payload keys. + * + * @param {Aps} aps An object to be validated. + */ +function validateAps(aps) { + if (typeof aps === 'undefined') { + return; + } + else if (!validator.isNonNullObject(aps)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.payload.aps must be a non-null object'); + } + validateApsAlert(aps.alert); + validateApsSound(aps.sound); + const propertyMappings = { + contentAvailable: 'content-available', + mutableContent: 'mutable-content', + threadId: 'thread-id', + }; + Object.keys(propertyMappings).forEach((key) => { + if (key in aps && propertyMappings[key] in aps) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, `Multiple specifications for ${key} in Aps`); + } + }); + (0, index_1.renameProperties)(aps, propertyMappings); + const contentAvailable = aps['content-available']; + if (typeof contentAvailable !== 'undefined' && contentAvailable !== 1) { + if (contentAvailable === true) { + aps['content-available'] = 1; + } + else { + delete aps['content-available']; + } + } + const mutableContent = aps['mutable-content']; + if (typeof mutableContent !== 'undefined' && mutableContent !== 1) { + if (mutableContent === true) { + aps['mutable-content'] = 1; + } + else { + delete aps['mutable-content']; + } + } +} +function validateApsSound(sound) { + if (typeof sound === 'undefined' || validator.isNonEmptyString(sound)) { + return; + } + else if (!validator.isNonNullObject(sound)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.payload.aps.sound must be a non-empty string or a non-null object'); + } + if (!validator.isNonEmptyString(sound.name)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.payload.aps.sound.name must be a non-empty string'); + } + const volume = sound.volume; + if (typeof volume !== 'undefined') { + if (!validator.isNumber(volume)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.payload.aps.sound.volume must be a number'); + } + if (volume < 0 || volume > 1) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.payload.aps.sound.volume must be in the interval [0, 1]'); + } + } + const soundObject = sound; + const key = 'critical'; + const critical = soundObject[key]; + if (typeof critical !== 'undefined' && critical !== 1) { + if (critical === true) { + soundObject[key] = 1; + } + else { + delete soundObject[key]; + } + } +} +/** + * Checks if the given alert object is valid. Alert could be a string or a complex object. + * If specified as an object, it must have valid localization parameters. If successful, transforms + * the input object by renaming the keys to valid APNS payload keys. + * + * @param {string | ApsAlert} alert An alert string or an object to be validated. + */ +function validateApsAlert(alert) { + if (typeof alert === 'undefined' || validator.isString(alert)) { + return; + } + else if (!validator.isNonNullObject(alert)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.payload.aps.alert must be a string or a non-null object'); + } + const apsAlert = alert; + if (validator.isNonEmptyArray(apsAlert.locArgs) && + !validator.isNonEmptyString(apsAlert.locKey)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.payload.aps.alert.locKey is required when specifying locArgs'); + } + if (validator.isNonEmptyArray(apsAlert.titleLocArgs) && + !validator.isNonEmptyString(apsAlert.titleLocKey)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.payload.aps.alert.titleLocKey is required when specifying titleLocArgs'); + } + if (validator.isNonEmptyArray(apsAlert.subtitleLocArgs) && + !validator.isNonEmptyString(apsAlert.subtitleLocKey)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.payload.aps.alert.subtitleLocKey is required when specifying subtitleLocArgs'); + } + const propertyMappings = { + locKey: 'loc-key', + locArgs: 'loc-args', + titleLocKey: 'title-loc-key', + titleLocArgs: 'title-loc-args', + subtitleLocKey: 'subtitle-loc-key', + subtitleLocArgs: 'subtitle-loc-args', + actionLocKey: 'action-loc-key', + launchImage: 'launch-image', + }; + (0, index_1.renameProperties)(apsAlert, propertyMappings); +} +/** + * Checks if the given AndroidConfig object is valid. The object must have valid ttl, data, + * and notification fields. If successful, transforms the input object by renaming keys to valid + * Android keys. Also transforms the ttl value to the format expected by FCM service. + * + * @param config - An object to be validated. + */ +function validateAndroidConfig(config) { + if (typeof config === 'undefined') { + return; + } + else if (!validator.isNonNullObject(config)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android must be a non-null object'); + } + if (typeof config.ttl !== 'undefined') { + if (!validator.isNumber(config.ttl) || config.ttl < 0) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'TTL must be a non-negative duration in milliseconds'); + } + const duration = (0, index_1.transformMillisecondsToSecondsString)(config.ttl); + config.ttl = duration; + } + validateStringMap(config.data, 'android.data'); + validateAndroidNotification(config.notification); + validateAndroidFcmOptions(config.fcmOptions); + const propertyMappings = { + collapseKey: 'collapse_key', + restrictedPackageName: 'restricted_package_name', + directBootOk: 'direct_boot_ok', + }; + (0, index_1.renameProperties)(config, propertyMappings); +} +/** + * Checks if the given AndroidNotification object is valid. The object must have valid color and + * localization parameters. If successful, transforms the input object by renaming keys to valid + * Android keys. + * + * @param {AndroidNotification} notification An object to be validated. + */ +function validateAndroidNotification(notification) { + if (typeof notification === 'undefined') { + return; + } + else if (!validator.isNonNullObject(notification)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification must be a non-null object'); + } + if (typeof notification.color !== 'undefined' && !/^#[0-9a-fA-F]{6}$/.test(notification.color)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.color must be in the form #RRGGBB'); + } + if (validator.isNonEmptyArray(notification.bodyLocArgs) && + !validator.isNonEmptyString(notification.bodyLocKey)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.bodyLocKey is required when specifying bodyLocArgs'); + } + if (validator.isNonEmptyArray(notification.titleLocArgs) && + !validator.isNonEmptyString(notification.titleLocKey)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.titleLocKey is required when specifying titleLocArgs'); + } + if (typeof notification.imageUrl !== 'undefined' && + !validator.isURL(notification.imageUrl)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.imageUrl must be a valid URL string'); + } + if (typeof notification.eventTimestamp !== 'undefined') { + if (!(notification.eventTimestamp instanceof Date)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.eventTimestamp must be a valid `Date` object'); + } + // Convert timestamp to RFC3339 UTC "Zulu" format, example "2014-10-02T15:01:23.045123456Z" + const zuluTimestamp = notification.eventTimestamp.toISOString(); + notification.eventTimestamp = zuluTimestamp; + } + if (typeof notification.vibrateTimingsMillis !== 'undefined') { + if (!validator.isNonEmptyArray(notification.vibrateTimingsMillis)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.vibrateTimingsMillis must be a non-empty array of numbers'); + } + const vibrateTimings = []; + notification.vibrateTimingsMillis.forEach((value) => { + if (!validator.isNumber(value) || value < 0) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.vibrateTimingsMillis must be non-negative durations in milliseconds'); + } + const duration = (0, index_1.transformMillisecondsToSecondsString)(value); + vibrateTimings.push(duration); + }); + notification.vibrateTimingsMillis = vibrateTimings; + } + if (typeof notification.priority !== 'undefined') { + const priority = 'PRIORITY_' + notification.priority.toUpperCase(); + notification.priority = priority; + } + if (typeof notification.proxy !== 'undefined') { + const proxy = notification.proxy.toUpperCase(); + notification.proxy = proxy; + } + if (typeof notification.visibility !== 'undefined') { + const visibility = notification.visibility.toUpperCase(); + notification.visibility = visibility; + } + validateLightSettings(notification.lightSettings); + const propertyMappings = { + clickAction: 'click_action', + bodyLocKey: 'body_loc_key', + bodyLocArgs: 'body_loc_args', + titleLocKey: 'title_loc_key', + titleLocArgs: 'title_loc_args', + channelId: 'channel_id', + imageUrl: 'image', + eventTimestamp: 'event_time', + localOnly: 'local_only', + priority: 'notification_priority', + vibrateTimingsMillis: 'vibrate_timings', + defaultVibrateTimings: 'default_vibrate_timings', + defaultSound: 'default_sound', + lightSettings: 'light_settings', + defaultLightSettings: 'default_light_settings', + notificationCount: 'notification_count', + }; + (0, index_1.renameProperties)(notification, propertyMappings); +} +/** + * Checks if the given LightSettings object is valid. The object must have valid color and + * light on/off duration parameters. If successful, transforms the input object by renaming + * keys to valid Android keys. + * + * @param {LightSettings} lightSettings An object to be validated. + */ +function validateLightSettings(lightSettings) { + if (typeof lightSettings === 'undefined') { + return; + } + else if (!validator.isNonNullObject(lightSettings)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.lightSettings must be a non-null object'); + } + if (!validator.isNumber(lightSettings.lightOnDurationMillis) || lightSettings.lightOnDurationMillis < 0) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.lightSettings.lightOnDurationMillis must be a non-negative duration in milliseconds'); + } + const durationOn = (0, index_1.transformMillisecondsToSecondsString)(lightSettings.lightOnDurationMillis); + lightSettings.lightOnDurationMillis = durationOn; + if (!validator.isNumber(lightSettings.lightOffDurationMillis) || lightSettings.lightOffDurationMillis < 0) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.lightSettings.lightOffDurationMillis must be a non-negative duration in milliseconds'); + } + const durationOff = (0, index_1.transformMillisecondsToSecondsString)(lightSettings.lightOffDurationMillis); + lightSettings.lightOffDurationMillis = durationOff; + if (!validator.isString(lightSettings.color) || + (!/^#[0-9a-fA-F]{6}$/.test(lightSettings.color) && !/^#[0-9a-fA-F]{8}$/.test(lightSettings.color))) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.lightSettings.color must be in the form #RRGGBB or #RRGGBBAA format'); + } + const colorString = lightSettings.color.length === 7 ? lightSettings.color + 'FF' : lightSettings.color; + const rgb = /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/i.exec(colorString); + if (!rgb || rgb.length < 4) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INTERNAL_ERROR, 'regex to extract rgba values from ' + colorString + ' failed.'); + } + const color = { + red: parseInt(rgb[1], 16) / 255.0, + green: parseInt(rgb[2], 16) / 255.0, + blue: parseInt(rgb[3], 16) / 255.0, + alpha: parseInt(rgb[4], 16) / 255.0, + }; + lightSettings.color = color; + const propertyMappings = { + lightOnDurationMillis: 'light_on_duration', + lightOffDurationMillis: 'light_off_duration', + }; + (0, index_1.renameProperties)(lightSettings, propertyMappings); +} +/** + * Checks if the given AndroidFcmOptions object is valid. + * + * @param {AndroidFcmOptions} fcmOptions An object to be validated. + */ +function validateAndroidFcmOptions(fcmOptions) { + if (typeof fcmOptions === 'undefined') { + return; + } + else if (!validator.isNonNullObject(fcmOptions)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'fcmOptions must be a non-null object'); + } + if (typeof fcmOptions.analyticsLabel !== 'undefined' && !validator.isString(fcmOptions.analyticsLabel)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'analyticsLabel must be a string value'); + } +} diff --git a/node_modules/firebase-admin/lib/messaging/messaging-namespace.d.ts b/node_modules/firebase-admin/lib/messaging/messaging-namespace.d.ts new file mode 100644 index 0000000..a87b157 --- /dev/null +++ b/node_modules/firebase-admin/lib/messaging/messaging-namespace.d.ts @@ -0,0 +1,161 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +import { Messaging as TMessaging } from './messaging'; +import { AndroidConfig as TAndroidConfig, AndroidFcmOptions as TAndroidFcmOptions, AndroidNotification as TAndroidNotification, ApnsConfig as TApnsConfig, ApnsFcmOptions as TApnsFcmOptions, ApnsPayload as TApnsPayload, Aps as TAps, ApsAlert as TApsAlert, BatchResponse as TBatchResponse, CriticalSound as TCriticalSound, ConditionMessage as TConditionMessage, FcmOptions as TFcmOptions, LightSettings as TLightSettings, Message as TMessage, MessagingTopicManagementResponse as TMessagingTopicManagementResponse, MulticastMessage as TMulticastMessage, Notification as TNotification, SendResponse as TSendResponse, TokenMessage as TTokenMessage, TopicMessage as TTopicMessage, WebpushConfig as TWebpushConfig, WebpushFcmOptions as TWebpushFcmOptions, WebpushNotification as TWebpushNotification, DataMessagePayload as TDataMessagePayload, MessagingOptions as TMessagingOptions, MessagingPayload as TMessagingPayload, NotificationMessagePayload as TNotificationMessagePayload } from './messaging-api'; +/** + * Gets the {@link firebase-admin.messaging#Messaging} service for the + * default app or a given app. + * + * `admin.messaging()` can be called with no arguments to access the default + * app's `Messaging` service or as `admin.messaging(app)` to access the + * `Messaging` service associated with a specific app. + * + * @example + * ```javascript + * // Get the Messaging service for the default app + * var defaultMessaging = admin.messaging(); + * ``` + * + * @example + * ```javascript + * // Get the Messaging service for a given app + * var otherMessaging = admin.messaging(otherApp); + * ``` + * + * @param app - Optional app whose `Messaging` service to + * return. If not provided, the default `Messaging` service will be returned. + * + * @returns The default `Messaging` service if no + * app is provided or the `Messaging` service associated with the provided + * app. + */ +export declare function messaging(app?: App): messaging.Messaging; +export declare namespace messaging { + /** + * Type alias to {@link firebase-admin.messaging#Messaging}. + */ + type Messaging = TMessaging; + /** + * Type alias to {@link firebase-admin.messaging#AndroidConfig}. + */ + type AndroidConfig = TAndroidConfig; + /** + * Type alias to {@link firebase-admin.messaging#AndroidFcmOptions}. + */ + type AndroidFcmOptions = TAndroidFcmOptions; + /** + * Type alias to {@link firebase-admin.messaging#AndroidNotification}. + */ + type AndroidNotification = TAndroidNotification; + /** + * Type alias to {@link firebase-admin.messaging#ApnsConfig}. + */ + type ApnsConfig = TApnsConfig; + /** + * Type alias to {@link firebase-admin.messaging#ApnsFcmOptions}. + */ + type ApnsFcmOptions = TApnsFcmOptions; + /** + * Type alias to {@link firebase-admin.messaging#ApnsPayload}. + */ + type ApnsPayload = TApnsPayload; + /** + * Type alias to {@link firebase-admin.messaging#Aps}. + */ + type Aps = TAps; + /** + * Type alias to {@link firebase-admin.messaging#ApsAlert}. + */ + type ApsAlert = TApsAlert; + /** + * Type alias to {@link firebase-admin.messaging#BatchResponse}. + */ + type BatchResponse = TBatchResponse; + /** + * Type alias to {@link firebase-admin.messaging#CriticalSound}. + */ + type CriticalSound = TCriticalSound; + /** + * Type alias to {@link firebase-admin.messaging#ConditionMessage}. + */ + type ConditionMessage = TConditionMessage; + /** + * Type alias to {@link firebase-admin.messaging#FcmOptions}. + */ + type FcmOptions = TFcmOptions; + /** + * Type alias to {@link firebase-admin.messaging#LightSettings}. + */ + type LightSettings = TLightSettings; + /** + * Type alias to {@link firebase-admin.messaging#Message}. + */ + type Message = TMessage; + /** + * Type alias to {@link firebase-admin.messaging#MessagingTopicManagementResponse}. + */ + type MessagingTopicManagementResponse = TMessagingTopicManagementResponse; + /** + * Type alias to {@link firebase-admin.messaging#MulticastMessage}. + */ + type MulticastMessage = TMulticastMessage; + /** + * Type alias to {@link firebase-admin.messaging#Notification}. + */ + type Notification = TNotification; + /** + * Type alias to {@link firebase-admin.messaging#SendResponse}. + */ + type SendResponse = TSendResponse; + /** + * Type alias to {@link firebase-admin.messaging#TokenMessage}. + */ + type TokenMessage = TTokenMessage; + /** + * Type alias to {@link firebase-admin.messaging#TopicMessage}. + */ + type TopicMessage = TTopicMessage; + /** + * Type alias to {@link firebase-admin.messaging#WebpushConfig}. + */ + type WebpushConfig = TWebpushConfig; + /** + * Type alias to {@link firebase-admin.messaging#WebpushFcmOptions}. + */ + type WebpushFcmOptions = TWebpushFcmOptions; + /** + * Type alias to {@link firebase-admin.messaging#WebpushNotification}. + */ + type WebpushNotification = TWebpushNotification; + /** + * Type alias to {@link firebase-admin.messaging#DataMessagePayload}. + */ + type DataMessagePayload = TDataMessagePayload; + /** + * Type alias to {@link firebase-admin.messaging#MessagingOptions}. + */ + type MessagingOptions = TMessagingOptions; + /** + * Type alias to {@link firebase-admin.messaging#MessagingPayload}. + */ + type MessagingPayload = TMessagingPayload; + /** + * Type alias to {@link firebase-admin.messaging#NotificationMessagePayload}. + */ + type NotificationMessagePayload = TNotificationMessagePayload; +} diff --git a/node_modules/firebase-admin/lib/messaging/messaging-namespace.js b/node_modules/firebase-admin/lib/messaging/messaging-namespace.js new file mode 100644 index 0000000..a91b066 --- /dev/null +++ b/node_modules/firebase-admin/lib/messaging/messaging-namespace.js @@ -0,0 +1,18 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/firebase-admin/lib/messaging/messaging.d.ts b/node_modules/firebase-admin/lib/messaging/messaging.d.ts new file mode 100644 index 0000000..d8ab1c0 --- /dev/null +++ b/node_modules/firebase-admin/lib/messaging/messaging.d.ts @@ -0,0 +1,189 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +import { BatchResponse, Message, MessagingTopicManagementResponse, MulticastMessage } from './messaging-api'; +/** + * Messaging service bound to the provided app. + */ +export declare class Messaging { + private urlPath; + private readonly appInternal; + private readonly messagingRequestHandler; + private useLegacyTransport; + /** + * The {@link firebase-admin.app#App} associated with the current `Messaging` service + * instance. + * + * @example + * ```javascript + * var app = messaging.app; + * ``` + */ + get app(): App; + /** + * Enables the use of legacy HTTP/1.1 transport for `sendEach()` and `sendEachForMulticast()`. + * + * @example + * ```javascript + * const messaging = getMessaging(app); + * messaging.enableLegacyTransport(); + * messaging.sendEach(messages); + * ``` + * + * @deprecated This will be removed when the HTTP/2 transport implementation reaches the same + * stability as the legacy HTTP/1.1 implementation. + */ + enableLegacyHttpTransport(): void; + /** + * Sends the given message via FCM. + * + * @param message - The message payload. + * @param dryRun - Whether to send the message in the dry-run + * (validation only) mode. + * @returns A promise fulfilled with a unique message ID + * string after the message has been successfully handed off to the FCM + * service for delivery. + */ + send(message: Message, dryRun?: boolean): Promise; + /** + * Sends each message in the given array via Firebase Cloud Messaging. + * + * This method makes a single RPC call for each message + * in the given array. + * + * The responses list obtained from the return value corresponds to the order of `messages`. + * An error from this method or a `BatchResponse` with all failures indicates a total failure, + * meaning that none of the messages in the list could be sent. Partial failures or no + * failures are only indicated by a `BatchResponse` return value. + * + * @param messages - A non-empty array + * containing up to 500 messages. + * @param dryRun - Whether to send the messages in the dry-run + * (validation only) mode. + * @returns A Promise fulfilled with an object representing the result of the + * send operation. + */ + sendEach(messages: Message[], dryRun?: boolean): Promise; + private parseSendResponses; + /** + * Sends the given multicast message to all the FCM registration tokens + * specified in it. + * + * This method uses the {@link Messaging.sendEach} API under the hood to send the given + * message to all the target recipients. The responses list obtained from the + * return value corresponds to the order of tokens in the `MulticastMessage`. + * An error from this method or a `BatchResponse` with all failures indicates a total + * failure, meaning that the messages in the list could be sent. Partial failures or + * failures are only indicated by a `BatchResponse` return value. + * + * @param message - A multicast message + * containing up to 500 tokens. + * @param dryRun - Whether to send the message in the dry-run + * (validation only) mode. + * @returns A Promise fulfilled with an object representing the result of the + * send operation. + */ + sendEachForMulticast(message: MulticastMessage, dryRun?: boolean): Promise; + /** + * Subscribes a device to an FCM topic. + * + * See {@link https://firebase.google.com/docs/cloud-messaging/manage-topics#suscribe_and_unsubscribe_using_the | + * Subscribe to a topic} + * for code samples and detailed documentation. Optionally, you can provide an + * array of tokens to subscribe multiple devices. + * + * @param registrationTokens - A token or array of registration tokens + * for the devices to subscribe to the topic. + * @param topic - The topic to which to subscribe. + * + * @returns A promise fulfilled with the server's response after the device has been + * subscribed to the topic. + */ + subscribeToTopic(registrationTokenOrTokens: string | string[], topic: string): Promise; + /** + * Unsubscribes a device from an FCM topic. + * + * See {@link https://firebase.google.com/docs/cloud-messaging/admin/manage-topic-subscriptions#unsubscribe_from_a_topic | + * Unsubscribe from a topic} + * for code samples and detailed documentation. Optionally, you can provide an + * array of tokens to unsubscribe multiple devices. + * + * @param registrationTokens - A device registration token or an array of + * device registration tokens to unsubscribe from the topic. + * @param topic - The topic from which to unsubscribe. + * + * @returns A promise fulfilled with the server's response after the device has been + * unsubscribed from the topic. + */ + unsubscribeFromTopic(registrationTokenOrTokens: string | string[], topic: string): Promise; + private getUrlPath; + /** + * Helper method which sends and handles topic subscription management requests. + * + * @param registrationTokenOrTokens - The registration token or an array of + * registration tokens to unsubscribe from the topic. + * @param topic - The topic to which to subscribe. + * @param methodName - The name of the original method called. + * @param path - The endpoint path to use for the request. + * + * @returns A Promise fulfilled with the parsed server + * response. + */ + private sendTopicManagementRequest; + /** + * Validates the type of the provided registration token(s). If invalid, an error will be thrown. + * + * @param registrationTokenOrTokens - The registration token(s) to validate. + * @param method - The method name to use in error messages. + * @param errorInfo - The error info to use if the registration tokens are invalid. + */ + private validateRegistrationTokensType; + /** + * Validates the provided registration tokens. If invalid, an error will be thrown. + * + * @param registrationTokenOrTokens - The registration token or an array of + * registration tokens to validate. + * @param method - The method name to use in error messages. + * @param errorInfo - The error info to use if the registration tokens are invalid. + */ + private validateRegistrationTokens; + /** + * Validates the type of the provided topic. If invalid, an error will be thrown. + * + * @param topic - The topic to validate. + * @param method - The method name to use in error messages. + * @param errorInfo - The error info to use if the topic is invalid. + */ + private validateTopicType; + /** + * Validates the provided topic. If invalid, an error will be thrown. + * + * @param topic - The topic to validate. + * @param method - The method name to use in error messages. + * @param errorInfo - The error info to use if the topic is invalid. + */ + private validateTopic; + /** + * Normalizes the provided topic name by prepending it with '/topics/', if necessary. + * + * @param topic - The topic name to normalize. + * + * @returns The normalized topic name. + */ + private normalizeTopic; +} diff --git a/node_modules/firebase-admin/lib/messaging/messaging.js b/node_modules/firebase-admin/lib/messaging/messaging.js new file mode 100644 index 0000000..b0bc1fd --- /dev/null +++ b/node_modules/firebase-admin/lib/messaging/messaging.js @@ -0,0 +1,442 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Messaging = void 0; +const deep_copy_1 = require("../utils/deep-copy"); +const error_1 = require("../utils/error"); +const utils = require("../utils"); +const validator = require("../utils/validator"); +const messaging_internal_1 = require("./messaging-internal"); +const messaging_api_request_internal_1 = require("./messaging-api-request-internal"); +const api_request_1 = require("../utils/api-request"); +// FCM endpoints +const FCM_SEND_HOST = 'fcm.googleapis.com'; +const FCM_TOPIC_MANAGEMENT_HOST = 'iid.googleapis.com'; +const FCM_TOPIC_MANAGEMENT_ADD_PATH = '/iid/v1:batchAdd'; +const FCM_TOPIC_MANAGEMENT_REMOVE_PATH = '/iid/v1:batchRemove'; +// Maximum messages that can be included in a batch request. +const FCM_MAX_BATCH_SIZE = 500; +/** + * Maps a raw FCM server response to a `MessagingTopicManagementResponse` object. + * + * @param {object} response The raw FCM server response to map. + * + * @returns {MessagingTopicManagementResponse} The mapped `MessagingTopicManagementResponse` object. + */ +function mapRawResponseToTopicManagementResponse(response) { + // Add the success and failure counts. + const result = { + successCount: 0, + failureCount: 0, + errors: [], + }; + if ('results' in response) { + response.results.forEach((tokenManagementResult, index) => { + // Map the FCM server's error strings to actual error objects. + if ('error' in tokenManagementResult) { + result.failureCount += 1; + const newError = error_1.FirebaseMessagingError.fromTopicManagementServerError(tokenManagementResult.error, /* message */ undefined, tokenManagementResult.error); + result.errors.push({ + index, + error: newError, + }); + } + else { + result.successCount += 1; + } + }); + } + return result; +} +/** + * Messaging service bound to the provided app. + */ +class Messaging { + /** + * @internal + */ + constructor(app) { + this.useLegacyTransport = false; + if (!validator.isNonNullObject(app) || !('options' in app)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_ARGUMENT, 'First argument passed to admin.messaging() must be a valid Firebase app instance.'); + } + this.appInternal = app; + this.messagingRequestHandler = new messaging_api_request_internal_1.FirebaseMessagingRequestHandler(app); + } + /** + * The {@link firebase-admin.app#App} associated with the current `Messaging` service + * instance. + * + * @example + * ```javascript + * var app = messaging.app; + * ``` + */ + get app() { + return this.appInternal; + } + /** + * Enables the use of legacy HTTP/1.1 transport for `sendEach()` and `sendEachForMulticast()`. + * + * @example + * ```javascript + * const messaging = getMessaging(app); + * messaging.enableLegacyTransport(); + * messaging.sendEach(messages); + * ``` + * + * @deprecated This will be removed when the HTTP/2 transport implementation reaches the same + * stability as the legacy HTTP/1.1 implementation. + */ + enableLegacyHttpTransport() { + this.useLegacyTransport = true; + } + /** + * Sends the given message via FCM. + * + * @param message - The message payload. + * @param dryRun - Whether to send the message in the dry-run + * (validation only) mode. + * @returns A promise fulfilled with a unique message ID + * string after the message has been successfully handed off to the FCM + * service for delivery. + */ + send(message, dryRun) { + const copy = (0, deep_copy_1.deepCopy)(message); + (0, messaging_internal_1.validateMessage)(copy); + if (typeof dryRun !== 'undefined' && !validator.isBoolean(dryRun)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_ARGUMENT, 'dryRun must be a boolean'); + } + return this.getUrlPath() + .then((urlPath) => { + const request = { message: copy }; + if (dryRun) { + request.validate_only = true; + } + return this.messagingRequestHandler.invokeRequestHandler(FCM_SEND_HOST, urlPath, request); + }) + .then((response) => { + return response.name; + }); + } + /** + * Sends each message in the given array via Firebase Cloud Messaging. + * + * This method makes a single RPC call for each message + * in the given array. + * + * The responses list obtained from the return value corresponds to the order of `messages`. + * An error from this method or a `BatchResponse` with all failures indicates a total failure, + * meaning that none of the messages in the list could be sent. Partial failures or no + * failures are only indicated by a `BatchResponse` return value. + * + * @param messages - A non-empty array + * containing up to 500 messages. + * @param dryRun - Whether to send the messages in the dry-run + * (validation only) mode. + * @returns A Promise fulfilled with an object representing the result of the + * send operation. + */ + sendEach(messages, dryRun) { + if (validator.isArray(messages) && messages.constructor !== Array) { + // In more recent JS specs, an array-like object might have a constructor that is not of + // Array type. Our deepCopy() method doesn't handle them properly. Convert such objects to + // a regular array here before calling deepCopy(). See issue #566 for details. + messages = Array.from(messages); + } + const copy = (0, deep_copy_1.deepCopy)(messages); + if (!validator.isNonEmptyArray(copy)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_ARGUMENT, 'messages must be a non-empty array'); + } + if (copy.length > FCM_MAX_BATCH_SIZE) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_ARGUMENT, `messages list must not contain more than ${FCM_MAX_BATCH_SIZE} items`); + } + if (typeof dryRun !== 'undefined' && !validator.isBoolean(dryRun)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_ARGUMENT, 'dryRun must be a boolean'); + } + const http2SessionHandler = this.useLegacyTransport ? undefined : new api_request_1.Http2SessionHandler(`https://${FCM_SEND_HOST}`); + return this.getUrlPath() + .then((urlPath) => { + if (http2SessionHandler) { + let sendResponsePromise; + return new Promise((resolve, reject) => { + // Start session listeners + http2SessionHandler.invoke().catch((error) => { + const pendingBatchResponse = sendResponsePromise ? sendResponsePromise.then(this.parseSendResponses) : undefined; + reject(new error_1.FirebaseMessagingSessionError(error, undefined, pendingBatchResponse)); + }); + // Start making requests + const requests = copy.map(async (message) => { + (0, messaging_internal_1.validateMessage)(message); + const request = { message }; + if (dryRun) { + request.validate_only = true; + } + return this.messagingRequestHandler.invokeHttp2RequestHandlerForSendResponse(FCM_SEND_HOST, urlPath, request, http2SessionHandler); + }); + // Resolve once all requests have completed + sendResponsePromise = Promise.allSettled(requests); + sendResponsePromise.then(resolve); + }); + } + else { + const requests = copy.map(async (message) => { + (0, messaging_internal_1.validateMessage)(message); + const request = { message }; + if (dryRun) { + request.validate_only = true; + } + return this.messagingRequestHandler.invokeHttpRequestHandlerForSendResponse(FCM_SEND_HOST, urlPath, request); + }); + return Promise.allSettled(requests); + } + }) + .then(this.parseSendResponses) + .finally(() => { + http2SessionHandler?.close(); + }); + } + parseSendResponses(results) { + const responses = []; + results.forEach(result => { + if (result.status === 'fulfilled') { + responses.push(result.value); + } + else { // rejected + responses.push({ success: false, error: result.reason }); + } + }); + const successCount = responses.filter((resp) => resp.success).length; + return { + responses, + successCount, + failureCount: responses.length - successCount, + }; + } + /** + * Sends the given multicast message to all the FCM registration tokens + * specified in it. + * + * This method uses the {@link Messaging.sendEach} API under the hood to send the given + * message to all the target recipients. The responses list obtained from the + * return value corresponds to the order of tokens in the `MulticastMessage`. + * An error from this method or a `BatchResponse` with all failures indicates a total + * failure, meaning that the messages in the list could be sent. Partial failures or + * failures are only indicated by a `BatchResponse` return value. + * + * @param message - A multicast message + * containing up to 500 tokens. + * @param dryRun - Whether to send the message in the dry-run + * (validation only) mode. + * @returns A Promise fulfilled with an object representing the result of the + * send operation. + */ + sendEachForMulticast(message, dryRun) { + const copy = (0, deep_copy_1.deepCopy)(message); + if (!validator.isNonNullObject(copy)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_ARGUMENT, 'MulticastMessage must be a non-null object'); + } + if (!validator.isNonEmptyArray(copy.tokens)) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_ARGUMENT, 'tokens must be a non-empty array'); + } + if (copy.tokens.length > FCM_MAX_BATCH_SIZE) { + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_ARGUMENT, `tokens list must not contain more than ${FCM_MAX_BATCH_SIZE} items`); + } + const messages = copy.tokens.map((token) => { + return { + token, + android: copy.android, + apns: copy.apns, + data: copy.data, + notification: copy.notification, + webpush: copy.webpush, + fcmOptions: copy.fcmOptions, + }; + }); + return this.sendEach(messages, dryRun); + } + /** + * Subscribes a device to an FCM topic. + * + * See {@link https://firebase.google.com/docs/cloud-messaging/manage-topics#suscribe_and_unsubscribe_using_the | + * Subscribe to a topic} + * for code samples and detailed documentation. Optionally, you can provide an + * array of tokens to subscribe multiple devices. + * + * @param registrationTokens - A token or array of registration tokens + * for the devices to subscribe to the topic. + * @param topic - The topic to which to subscribe. + * + * @returns A promise fulfilled with the server's response after the device has been + * subscribed to the topic. + */ + subscribeToTopic(registrationTokenOrTokens, topic) { + return this.sendTopicManagementRequest(registrationTokenOrTokens, topic, 'subscribeToTopic', FCM_TOPIC_MANAGEMENT_ADD_PATH); + } + /** + * Unsubscribes a device from an FCM topic. + * + * See {@link https://firebase.google.com/docs/cloud-messaging/admin/manage-topic-subscriptions#unsubscribe_from_a_topic | + * Unsubscribe from a topic} + * for code samples and detailed documentation. Optionally, you can provide an + * array of tokens to unsubscribe multiple devices. + * + * @param registrationTokens - A device registration token or an array of + * device registration tokens to unsubscribe from the topic. + * @param topic - The topic from which to unsubscribe. + * + * @returns A promise fulfilled with the server's response after the device has been + * unsubscribed from the topic. + */ + unsubscribeFromTopic(registrationTokenOrTokens, topic) { + return this.sendTopicManagementRequest(registrationTokenOrTokens, topic, 'unsubscribeFromTopic', FCM_TOPIC_MANAGEMENT_REMOVE_PATH); + } + getUrlPath() { + if (this.urlPath) { + return Promise.resolve(this.urlPath); + } + return utils.findProjectId(this.app) + .then((projectId) => { + if (!validator.isNonEmptyString(projectId)) { + // Assert for an explicit project ID (either via AppOptions or the cert itself). + throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_ARGUMENT, 'Failed to determine project ID for Messaging. Initialize the ' + + 'SDK with service account credentials or set project ID as an app option. ' + + 'Alternatively set the GOOGLE_CLOUD_PROJECT environment variable.'); + } + this.urlPath = `/v1/projects/${projectId}/messages:send`; + return this.urlPath; + }); + } + /** + * Helper method which sends and handles topic subscription management requests. + * + * @param registrationTokenOrTokens - The registration token or an array of + * registration tokens to unsubscribe from the topic. + * @param topic - The topic to which to subscribe. + * @param methodName - The name of the original method called. + * @param path - The endpoint path to use for the request. + * + * @returns A Promise fulfilled with the parsed server + * response. + */ + sendTopicManagementRequest(registrationTokenOrTokens, topic, methodName, path) { + this.validateRegistrationTokensType(registrationTokenOrTokens, methodName); + this.validateTopicType(topic, methodName); + // Prepend the topic with /topics/ if necessary. + topic = this.normalizeTopic(topic); + return Promise.resolve() + .then(() => { + // Validate the contents of the input arguments. Because we are now in a promise, any thrown + // error will cause this method to return a rejected promise. + this.validateRegistrationTokens(registrationTokenOrTokens, methodName); + this.validateTopic(topic, methodName); + // Ensure the registration token(s) input argument is an array. + let registrationTokensArray = registrationTokenOrTokens; + if (validator.isString(registrationTokenOrTokens)) { + registrationTokensArray = [registrationTokenOrTokens]; + } + const request = { + to: topic, + registration_tokens: registrationTokensArray, + }; + return this.messagingRequestHandler.invokeRequestHandler(FCM_TOPIC_MANAGEMENT_HOST, path, request); + }) + .then((response) => { + return mapRawResponseToTopicManagementResponse(response); + }); + } + /** + * Validates the type of the provided registration token(s). If invalid, an error will be thrown. + * + * @param registrationTokenOrTokens - The registration token(s) to validate. + * @param method - The method name to use in error messages. + * @param errorInfo - The error info to use if the registration tokens are invalid. + */ + validateRegistrationTokensType(registrationTokenOrTokens, methodName, errorInfo = error_1.MessagingClientErrorCode.INVALID_ARGUMENT) { + if (!validator.isNonEmptyArray(registrationTokenOrTokens) && + !validator.isNonEmptyString(registrationTokenOrTokens)) { + throw new error_1.FirebaseMessagingError(errorInfo, `Registration token(s) provided to ${methodName}() must be a non-empty string or a ` + + 'non-empty array.'); + } + } + /** + * Validates the provided registration tokens. If invalid, an error will be thrown. + * + * @param registrationTokenOrTokens - The registration token or an array of + * registration tokens to validate. + * @param method - The method name to use in error messages. + * @param errorInfo - The error info to use if the registration tokens are invalid. + */ + validateRegistrationTokens(registrationTokenOrTokens, methodName, errorInfo = error_1.MessagingClientErrorCode.INVALID_ARGUMENT) { + if (validator.isArray(registrationTokenOrTokens)) { + // Validate the array contains no more than 1,000 registration tokens. + if (registrationTokenOrTokens.length > 1000) { + throw new error_1.FirebaseMessagingError(errorInfo, `Too many registration tokens provided in a single request to ${methodName}(). Batch ` + + 'your requests to contain no more than 1,000 registration tokens per request.'); + } + // Validate the array contains registration tokens which are non-empty strings. + registrationTokenOrTokens.forEach((registrationToken, index) => { + if (!validator.isNonEmptyString(registrationToken)) { + throw new error_1.FirebaseMessagingError(errorInfo, `Registration token provided to ${methodName}() at index ${index} must be a ` + + 'non-empty string.'); + } + }); + } + } + /** + * Validates the type of the provided topic. If invalid, an error will be thrown. + * + * @param topic - The topic to validate. + * @param method - The method name to use in error messages. + * @param errorInfo - The error info to use if the topic is invalid. + */ + validateTopicType(topic, methodName, errorInfo = error_1.MessagingClientErrorCode.INVALID_ARGUMENT) { + if (!validator.isNonEmptyString(topic)) { + throw new error_1.FirebaseMessagingError(errorInfo, `Topic provided to ${methodName}() must be a string which matches the format ` + + '"/topics/[a-zA-Z0-9-_.~%]+".'); + } + } + /** + * Validates the provided topic. If invalid, an error will be thrown. + * + * @param topic - The topic to validate. + * @param method - The method name to use in error messages. + * @param errorInfo - The error info to use if the topic is invalid. + */ + validateTopic(topic, methodName, errorInfo = error_1.MessagingClientErrorCode.INVALID_ARGUMENT) { + if (!validator.isTopic(topic)) { + throw new error_1.FirebaseMessagingError(errorInfo, `Topic provided to ${methodName}() must be a string which matches the format ` + + '"/topics/[a-zA-Z0-9-_.~%]+".'); + } + } + /** + * Normalizes the provided topic name by prepending it with '/topics/', if necessary. + * + * @param topic - The topic name to normalize. + * + * @returns The normalized topic name. + */ + normalizeTopic(topic) { + if (!/^\/topics\//.test(topic)) { + topic = `/topics/${topic}`; + } + return topic; + } +} +exports.Messaging = Messaging; diff --git a/node_modules/firebase-admin/lib/project-management/android-app.d.ts b/node_modules/firebase-admin/lib/project-management/android-app.d.ts new file mode 100644 index 0000000..3b2ba68 --- /dev/null +++ b/node_modules/firebase-admin/lib/project-management/android-app.d.ts @@ -0,0 +1,110 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AppMetadata, AppPlatform } from './app-metadata'; +/** + * Metadata about a Firebase Android App. + */ +export interface AndroidAppMetadata extends AppMetadata { + platform: AppPlatform.ANDROID; + /** + * The canonical package name of the Android App, as would appear in the Google Play Developer + * Console. + * + * @example + * ```javascript + * var packageName = androidAppMetadata.packageName; + * ``` + */ + packageName: string; +} +/** + * A reference to a Firebase Android app. + * + * Do not call this constructor directly. Instead, use {@link ProjectManagement.androidApp}. + */ +export declare class AndroidApp { + readonly appId: string; + private readonly requestHandler; + private readonly resourceName; + /** + * Retrieves metadata about this Android app. + * + * @returns A promise that resolves to the retrieved metadata about this Android app. + */ + getMetadata(): Promise; + /** + * Sets the optional user-assigned display name of the app. + * + * @param newDisplayName - The new display name to set. + * + * @returns A promise that resolves when the display name has been set. + */ + setDisplayName(newDisplayName: string): Promise; + /** + * Gets the list of SHA certificates associated with this Android app in Firebase. + * + * @returns The list of SHA-1 and SHA-256 certificates associated with this Android app in + * Firebase. + */ + getShaCertificates(): Promise; + /** + * Adds the given SHA certificate to this Android app. + * + * @param certificateToAdd - The SHA certificate to add. + * + * @returns A promise that resolves when the given certificate + * has been added to the Android app. + */ + addShaCertificate(certificateToAdd: ShaCertificate): Promise; + /** + * Deletes the specified SHA certificate from this Android app. + * + * @param certificateToDelete - The SHA certificate to delete. + * + * @returns A promise that resolves when the specified + * certificate has been removed from the Android app. + */ + deleteShaCertificate(certificateToDelete: ShaCertificate): Promise; + /** + * Gets the configuration artifact associated with this app. + * + * @returns A promise that resolves to the Android app's + * Firebase config file, in UTF-8 string format. This string is typically + * intended to be written to a JSON file that gets shipped with your Android + * app. + */ + getConfig(): Promise; +} +/** + * A SHA-1 or SHA-256 certificate. + * + * Do not call this constructor directly. Instead, use + * [`projectManagement.shaCertificate()`](projectManagement.ProjectManagement#shaCertificate). + */ +export declare class ShaCertificate { + readonly shaHash: string; + readonly resourceName?: string | undefined; + /** + * The SHA certificate type. + * + * @example + * ```javascript + * var certType = shaCertificate.certType; + * ``` + */ + readonly certType: ('sha1' | 'sha256'); +} diff --git a/node_modules/firebase-admin/lib/project-management/android-app.js b/node_modules/firebase-admin/lib/project-management/android-app.js new file mode 100644 index 0000000..5c7ca31 --- /dev/null +++ b/node_modules/firebase-admin/lib/project-management/android-app.js @@ -0,0 +1,183 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ShaCertificate = exports.AndroidApp = void 0; +const error_1 = require("../utils/error"); +const validator = require("../utils/validator"); +const project_management_api_request_internal_1 = require("./project-management-api-request-internal"); +const app_metadata_1 = require("./app-metadata"); +/** + * A reference to a Firebase Android app. + * + * Do not call this constructor directly. Instead, use {@link ProjectManagement.androidApp}. + */ +class AndroidApp { + /** + * @internal + */ + constructor(appId, requestHandler) { + this.appId = appId; + this.requestHandler = requestHandler; + if (!validator.isNonEmptyString(appId)) { + throw new error_1.FirebaseProjectManagementError('invalid-argument', 'appId must be a non-empty string.'); + } + this.resourceName = `projects/-/androidApps/${appId}`; + } + /** + * Retrieves metadata about this Android app. + * + * @returns A promise that resolves to the retrieved metadata about this Android app. + */ + getMetadata() { + return this.requestHandler.getResource(this.resourceName) + .then((responseData) => { + (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonNullObject(responseData), responseData, 'getMetadata()\'s responseData must be a non-null object.'); + const requiredFieldsList = ['name', 'appId', 'projectId', 'packageName']; + requiredFieldsList.forEach((requiredField) => { + (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonEmptyString(responseData[requiredField]), responseData, `getMetadata()'s responseData.${requiredField} must be a non-empty string.`); + }); + const metadata = { + platform: app_metadata_1.AppPlatform.ANDROID, + resourceName: responseData.name, + appId: responseData.appId, + displayName: responseData.displayName || null, + projectId: responseData.projectId, + packageName: responseData.packageName, + }; + return metadata; + }); + } + /** + * Sets the optional user-assigned display name of the app. + * + * @param newDisplayName - The new display name to set. + * + * @returns A promise that resolves when the display name has been set. + */ + setDisplayName(newDisplayName) { + return this.requestHandler.setDisplayName(this.resourceName, newDisplayName); + } + /** + * Gets the list of SHA certificates associated with this Android app in Firebase. + * + * @returns The list of SHA-1 and SHA-256 certificates associated with this Android app in + * Firebase. + */ + getShaCertificates() { + return this.requestHandler.getAndroidShaCertificates(this.resourceName) + .then((responseData) => { + (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonNullObject(responseData), responseData, 'getShaCertificates()\'s responseData must be a non-null object.'); + if (!responseData.certificates) { + return []; + } + (0, project_management_api_request_internal_1.assertServerResponse)(validator.isArray(responseData.certificates), responseData, '"certificates" field must be present in the getShaCertificates() response data.'); + const requiredFieldsList = ['name', 'shaHash']; + return responseData.certificates.map((certificateJson) => { + requiredFieldsList.forEach((requiredField) => { + (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonEmptyString(certificateJson[requiredField]), responseData, `getShaCertificates()'s responseData.certificates[].${requiredField} must be a ` + + 'non-empty string.'); + }); + return new ShaCertificate(certificateJson.shaHash, certificateJson.name); + }); + }); + } + /** + * Adds the given SHA certificate to this Android app. + * + * @param certificateToAdd - The SHA certificate to add. + * + * @returns A promise that resolves when the given certificate + * has been added to the Android app. + */ + addShaCertificate(certificateToAdd) { + return this.requestHandler.addAndroidShaCertificate(this.resourceName, certificateToAdd); + } + /** + * Deletes the specified SHA certificate from this Android app. + * + * @param certificateToDelete - The SHA certificate to delete. + * + * @returns A promise that resolves when the specified + * certificate has been removed from the Android app. + */ + deleteShaCertificate(certificateToDelete) { + if (!certificateToDelete.resourceName) { + throw new error_1.FirebaseProjectManagementError('invalid-argument', 'Specified certificate does not include a resourceName. (Use AndroidApp.getShaCertificates() to retrieve ' + + 'certificates with a resourceName.'); + } + return this.requestHandler.deleteResource(certificateToDelete.resourceName); + } + /** + * Gets the configuration artifact associated with this app. + * + * @returns A promise that resolves to the Android app's + * Firebase config file, in UTF-8 string format. This string is typically + * intended to be written to a JSON file that gets shipped with your Android + * app. + */ + getConfig() { + return this.requestHandler.getConfig(this.resourceName) + .then((responseData) => { + (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonNullObject(responseData), responseData, 'getConfig()\'s responseData must be a non-null object.'); + const base64ConfigFileContents = responseData.configFileContents; + (0, project_management_api_request_internal_1.assertServerResponse)(validator.isBase64String(base64ConfigFileContents), responseData, 'getConfig()\'s responseData.configFileContents must be a base64 string.'); + return Buffer.from(base64ConfigFileContents, 'base64').toString('utf8'); + }); + } +} +exports.AndroidApp = AndroidApp; +/** + * A SHA-1 or SHA-256 certificate. + * + * Do not call this constructor directly. Instead, use + * [`projectManagement.shaCertificate()`](projectManagement.ProjectManagement#shaCertificate). + */ +class ShaCertificate { + /** + * Creates a ShaCertificate using the given hash. The ShaCertificate's type (eg. 'sha256') is + * automatically determined from the hash itself. + * + * @param shaHash - The sha256 or sha1 hash for this certificate. + * @example + * ```javascript + * var shaHash = shaCertificate.shaHash; + * ``` + * @param resourceName - The Firebase resource name for this certificate. This does not need to be + * set when creating a new certificate. + * @example + * ```javascript + * var resourceName = shaCertificate.resourceName; + * ``` + * + * @internal + */ + constructor(shaHash, resourceName) { + this.shaHash = shaHash; + this.resourceName = resourceName; + if (/^[a-fA-F0-9]{40}$/.test(shaHash)) { + this.certType = 'sha1'; + } + else if (/^[a-fA-F0-9]{64}$/.test(shaHash)) { + this.certType = 'sha256'; + } + else { + throw new error_1.FirebaseProjectManagementError('invalid-argument', 'shaHash must be either a sha256 hash or a sha1 hash.'); + } + } +} +exports.ShaCertificate = ShaCertificate; diff --git a/node_modules/firebase-admin/lib/project-management/app-metadata.d.ts b/node_modules/firebase-admin/lib/project-management/app-metadata.d.ts new file mode 100644 index 0000000..9bd2706 --- /dev/null +++ b/node_modules/firebase-admin/lib/project-management/app-metadata.d.ts @@ -0,0 +1,85 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Platforms with which a Firebase App can be associated. + */ +export declare enum AppPlatform { + /** + * Unknown state. This is only used for distinguishing unset values. + */ + PLATFORM_UNKNOWN = "PLATFORM_UNKNOWN", + /** + * The Firebase App is associated with iOS. + */ + IOS = "IOS", + /** + * The Firebase App is associated with Android. + */ + ANDROID = "ANDROID" +} +/** + * Metadata about a Firebase app. + */ +export interface AppMetadata { + /** + * The globally unique, Firebase-assigned identifier of the app. + * + * @example + * ```javascript + * var appId = appMetadata.appId; + * ``` + */ + appId: string; + /** + * The optional user-assigned display name of the app. + * + * @example + * ```javascript + * var displayName = appMetadata.displayName; + * ``` + */ + displayName?: string; + /** + * The development platform of the app. Supporting Android and iOS app platforms. + * + * @example + * ```javascript + * var platform = AppPlatform.ANDROID; + * ``` + */ + platform: AppPlatform; + /** + * The globally unique, user-assigned ID of the parent project for the app. + * + * @example + * ```javascript + * var projectId = appMetadata.projectId; + * ``` + */ + projectId: string; + /** + * The fully-qualified resource name that identifies this app. + * + * This is useful when manually constructing requests for Firebase's public API. + * + * @example + * ```javascript + * var resourceName = androidAppMetadata.resourceName; + * ``` + */ + resourceName: string; +} diff --git a/node_modules/firebase-admin/lib/project-management/app-metadata.js b/node_modules/firebase-admin/lib/project-management/app-metadata.js new file mode 100644 index 0000000..e224a36 --- /dev/null +++ b/node_modules/firebase-admin/lib/project-management/app-metadata.js @@ -0,0 +1,37 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AppPlatform = void 0; +/** + * Platforms with which a Firebase App can be associated. + */ +var AppPlatform; +(function (AppPlatform) { + /** + * Unknown state. This is only used for distinguishing unset values. + */ + AppPlatform["PLATFORM_UNKNOWN"] = "PLATFORM_UNKNOWN"; + /** + * The Firebase App is associated with iOS. + */ + AppPlatform["IOS"] = "IOS"; + /** + * The Firebase App is associated with Android. + */ + AppPlatform["ANDROID"] = "ANDROID"; +})(AppPlatform || (exports.AppPlatform = AppPlatform = {})); diff --git a/node_modules/firebase-admin/lib/project-management/index.d.ts b/node_modules/firebase-admin/lib/project-management/index.d.ts new file mode 100644 index 0000000..d27e226 --- /dev/null +++ b/node_modules/firebase-admin/lib/project-management/index.d.ts @@ -0,0 +1,54 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Firebase project management. + * + * @packageDocumentation + */ +import { App } from '../app'; +import { ProjectManagement } from './project-management'; +export { AppMetadata, AppPlatform } from './app-metadata'; +export { ProjectManagement } from './project-management'; +export { AndroidApp, AndroidAppMetadata, ShaCertificate } from './android-app'; +export { IosApp, IosAppMetadata } from './ios-app'; +/** + * Gets the {@link ProjectManagement} service for the default app or a given app. + * + * `getProjectManagement()` can be called with no arguments to access the + * default app's `ProjectManagement` service, or as `getProjectManagement(app)` to access + * the `ProjectManagement` service associated with a specific app. + * + * @example + * ```javascript + * // Get the ProjectManagement service for the default app + * const defaultProjectManagement = getProjectManagement(); + * ``` + * + * @example + * ```javascript + * // Get the ProjectManagement service for a given app + * const otherProjectManagement = getProjectManagement(otherApp); + * ``` + * + * @param app - Optional app whose `ProjectManagement` service + * to return. If not provided, the default `ProjectManagement` service will + * be returned. * + * @returns The default `ProjectManagement` service if no app is provided or the + * `ProjectManagement` service associated with the provided app. + */ +export declare function getProjectManagement(app?: App): ProjectManagement; +export { FirebaseProjectManagementError, ProjectManagementErrorCode } from '../utils/error'; diff --git a/node_modules/firebase-admin/lib/project-management/index.js b/node_modules/firebase-admin/lib/project-management/index.js new file mode 100644 index 0000000..32ab60f --- /dev/null +++ b/node_modules/firebase-admin/lib/project-management/index.js @@ -0,0 +1,70 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirebaseProjectManagementError = exports.IosApp = exports.ShaCertificate = exports.AndroidApp = exports.ProjectManagement = exports.AppPlatform = void 0; +exports.getProjectManagement = getProjectManagement; +/** + * Firebase project management. + * + * @packageDocumentation + */ +const app_1 = require("../app"); +const project_management_1 = require("./project-management"); +var app_metadata_1 = require("./app-metadata"); +Object.defineProperty(exports, "AppPlatform", { enumerable: true, get: function () { return app_metadata_1.AppPlatform; } }); +var project_management_2 = require("./project-management"); +Object.defineProperty(exports, "ProjectManagement", { enumerable: true, get: function () { return project_management_2.ProjectManagement; } }); +var android_app_1 = require("./android-app"); +Object.defineProperty(exports, "AndroidApp", { enumerable: true, get: function () { return android_app_1.AndroidApp; } }); +Object.defineProperty(exports, "ShaCertificate", { enumerable: true, get: function () { return android_app_1.ShaCertificate; } }); +var ios_app_1 = require("./ios-app"); +Object.defineProperty(exports, "IosApp", { enumerable: true, get: function () { return ios_app_1.IosApp; } }); +/** + * Gets the {@link ProjectManagement} service for the default app or a given app. + * + * `getProjectManagement()` can be called with no arguments to access the + * default app's `ProjectManagement` service, or as `getProjectManagement(app)` to access + * the `ProjectManagement` service associated with a specific app. + * + * @example + * ```javascript + * // Get the ProjectManagement service for the default app + * const defaultProjectManagement = getProjectManagement(); + * ``` + * + * @example + * ```javascript + * // Get the ProjectManagement service for a given app + * const otherProjectManagement = getProjectManagement(otherApp); + * ``` + * + * @param app - Optional app whose `ProjectManagement` service + * to return. If not provided, the default `ProjectManagement` service will + * be returned. * + * @returns The default `ProjectManagement` service if no app is provided or the + * `ProjectManagement` service associated with the provided app. + */ +function getProjectManagement(app) { + if (typeof app === 'undefined') { + app = (0, app_1.getApp)(); + } + const firebaseApp = app; + return firebaseApp.getOrInitService('projectManagement', (app) => new project_management_1.ProjectManagement(app)); +} +var error_1 = require("../utils/error"); +Object.defineProperty(exports, "FirebaseProjectManagementError", { enumerable: true, get: function () { return error_1.FirebaseProjectManagementError; } }); diff --git a/node_modules/firebase-admin/lib/project-management/ios-app.d.ts b/node_modules/firebase-admin/lib/project-management/ios-app.d.ts new file mode 100644 index 0000000..4a1622e --- /dev/null +++ b/node_modules/firebase-admin/lib/project-management/ios-app.d.ts @@ -0,0 +1,66 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AppMetadata, AppPlatform } from './app-metadata'; +/** + * Metadata about a Firebase iOS App. + */ +export interface IosAppMetadata extends AppMetadata { + platform: AppPlatform.IOS; + /** + * The canonical bundle ID of the iOS App as it would appear in the iOS App Store. + * + * @example + * ```javascript + * var bundleId = iosAppMetadata.bundleId; + *``` + */ + bundleId: string; +} +/** + * A reference to a Firebase iOS app. + * + * Do not call this constructor directly. Instead, use {@link ProjectManagement.iosApp}. + */ +export declare class IosApp { + readonly appId: string; + private readonly requestHandler; + private readonly resourceName; + /** + * Retrieves metadata about this iOS app. + * + * @returns A promise that + * resolves to the retrieved metadata about this iOS app. + */ + getMetadata(): Promise; + /** + * Sets the optional user-assigned display name of the app. + * + * @param newDisplayName - The new display name to set. + * + * @returns A promise that resolves when the display name has + * been set. + */ + setDisplayName(newDisplayName: string): Promise; + /** + * Gets the configuration artifact associated with this app. + * + * @returns A promise that resolves to the iOS app's Firebase + * config file, in UTF-8 string format. This string is typically intended to + * be written to a plist file that gets shipped with your iOS app. + */ + getConfig(): Promise; +} diff --git a/node_modules/firebase-admin/lib/project-management/ios-app.js b/node_modules/firebase-admin/lib/project-management/ios-app.js new file mode 100644 index 0000000..2205fea --- /dev/null +++ b/node_modules/firebase-admin/lib/project-management/ios-app.js @@ -0,0 +1,94 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IosApp = void 0; +const error_1 = require("../utils/error"); +const validator = require("../utils/validator"); +const project_management_api_request_internal_1 = require("./project-management-api-request-internal"); +const app_metadata_1 = require("./app-metadata"); +/** + * A reference to a Firebase iOS app. + * + * Do not call this constructor directly. Instead, use {@link ProjectManagement.iosApp}. + */ +class IosApp { + /** + * @internal + */ + constructor(appId, requestHandler) { + this.appId = appId; + this.requestHandler = requestHandler; + if (!validator.isNonEmptyString(appId)) { + throw new error_1.FirebaseProjectManagementError('invalid-argument', 'appId must be a non-empty string.'); + } + this.resourceName = `projects/-/iosApps/${appId}`; + } + /** + * Retrieves metadata about this iOS app. + * + * @returns A promise that + * resolves to the retrieved metadata about this iOS app. + */ + getMetadata() { + return this.requestHandler.getResource(this.resourceName) + .then((responseData) => { + (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonNullObject(responseData), responseData, 'getMetadata()\'s responseData must be a non-null object.'); + const requiredFieldsList = ['name', 'appId', 'projectId', 'bundleId']; + requiredFieldsList.forEach((requiredField) => { + (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonEmptyString(responseData[requiredField]), responseData, `getMetadata()'s responseData.${requiredField} must be a non-empty string.`); + }); + const metadata = { + platform: app_metadata_1.AppPlatform.IOS, + resourceName: responseData.name, + appId: responseData.appId, + displayName: responseData.displayName || null, + projectId: responseData.projectId, + bundleId: responseData.bundleId, + }; + return metadata; + }); + } + /** + * Sets the optional user-assigned display name of the app. + * + * @param newDisplayName - The new display name to set. + * + * @returns A promise that resolves when the display name has + * been set. + */ + setDisplayName(newDisplayName) { + return this.requestHandler.setDisplayName(this.resourceName, newDisplayName); + } + /** + * Gets the configuration artifact associated with this app. + * + * @returns A promise that resolves to the iOS app's Firebase + * config file, in UTF-8 string format. This string is typically intended to + * be written to a plist file that gets shipped with your iOS app. + */ + getConfig() { + return this.requestHandler.getConfig(this.resourceName) + .then((responseData) => { + (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonNullObject(responseData), responseData, 'getConfig()\'s responseData must be a non-null object.'); + const base64ConfigFileContents = responseData.configFileContents; + (0, project_management_api_request_internal_1.assertServerResponse)(validator.isBase64String(base64ConfigFileContents), responseData, 'getConfig()\'s responseData.configFileContents must be a base64 string.'); + return Buffer.from(base64ConfigFileContents, 'base64').toString('utf8'); + }); + } +} +exports.IosApp = IosApp; diff --git a/node_modules/firebase-admin/lib/project-management/project-management-api-request-internal.d.ts b/node_modules/firebase-admin/lib/project-management/project-management-api-request-internal.d.ts new file mode 100644 index 0000000..26a8086 --- /dev/null +++ b/node_modules/firebase-admin/lib/project-management/project-management-api-request-internal.d.ts @@ -0,0 +1,17 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare function assertServerResponse(condition: boolean, responseData: object, message: string): void; diff --git a/node_modules/firebase-admin/lib/project-management/project-management-api-request-internal.js b/node_modules/firebase-admin/lib/project-management/project-management-api-request-internal.js new file mode 100644 index 0000000..74eb26d --- /dev/null +++ b/node_modules/firebase-admin/lib/project-management/project-management-api-request-internal.js @@ -0,0 +1,268 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProjectManagementRequestHandler = void 0; +exports.assertServerResponse = assertServerResponse; +const api_request_1 = require("../utils/api-request"); +const error_1 = require("../utils/error"); +const index_1 = require("../utils/index"); +const validator = require("../utils/validator"); +/** Project management backend host and port. */ +const PROJECT_MANAGEMENT_HOST_AND_PORT = 'firebase.googleapis.com:443'; +/** Project management backend path. */ +const PROJECT_MANAGEMENT_PATH = '/v1/'; +/** Project management beta backend path. */ +const PROJECT_MANAGEMENT_BETA_PATH = '/v1beta1/'; +/** Project management request header. */ +const PROJECT_MANAGEMENT_HEADERS = { + 'X-Client-Version': `Node/Admin/${(0, index_1.getSdkVersion)()}`, +}; +/** Project management request timeout duration in milliseconds. */ +const PROJECT_MANAGEMENT_TIMEOUT_MILLIS = 10000; +const LIST_APPS_MAX_PAGE_SIZE = 100; +const CERT_TYPE_API_MAP = { + sha1: 'SHA_1', + sha256: 'SHA_256', +}; +function assertServerResponse(condition, responseData, message) { + if (!condition) { + throw new error_1.FirebaseProjectManagementError('invalid-server-response', `${message} Response data: ${JSON.stringify(responseData, null, 2)}`); + } +} +/** + * Class that provides mechanism to send requests to the Firebase project management backend + * endpoints. + * + * @internal + */ +class ProjectManagementRequestHandler { + static wrapAndRethrowHttpError(errStatusCode, errText) { + let errorCode; + let errorMessage; + switch (errStatusCode) { + case 400: + errorCode = 'invalid-argument'; + errorMessage = 'Invalid argument provided.'; + break; + case 401: + case 403: + errorCode = 'authentication-error'; + errorMessage = 'An error occurred when trying to authenticate. Make sure the credential ' + + 'used to authenticate this SDK has the proper permissions. See ' + + 'https://firebase.google.com/docs/admin/setup for setup instructions.'; + break; + case 404: + errorCode = 'not-found'; + errorMessage = 'The specified entity could not be found.'; + break; + case 409: + errorCode = 'already-exists'; + errorMessage = 'The specified entity already exists.'; + break; + case 500: + errorCode = 'internal-error'; + errorMessage = 'An internal error has occurred. Please retry the request.'; + break; + case 503: + errorCode = 'service-unavailable'; + errorMessage = 'The server could not process the request in time. See the error ' + + 'documentation for more details.'; + break; + default: + errorCode = 'unknown-error'; + errorMessage = 'An unknown server error was returned.'; + } + if (!errText) { + errText = ''; + } + throw new error_1.FirebaseProjectManagementError(errorCode, `${errorMessage} Status code: ${errStatusCode}. Raw server response: "${errText}".`); + } + /** + * @param app - The app used to fetch access tokens to sign API requests. + * @constructor + */ + constructor(app) { + this.baseUrl = `https://${PROJECT_MANAGEMENT_HOST_AND_PORT}${PROJECT_MANAGEMENT_PATH}`; + this.baseBetaUrl = `https://${PROJECT_MANAGEMENT_HOST_AND_PORT}${PROJECT_MANAGEMENT_BETA_PATH}`; + this.httpClient = new api_request_1.AuthorizedHttpClient(app); + } + /** + * @param parentResourceName - Fully-qualified resource name of the project whose Android + * apps you want to list. + */ + listAndroidApps(parentResourceName) { + return this.invokeRequestHandler('GET', `${parentResourceName}/androidApps?page_size=${LIST_APPS_MAX_PAGE_SIZE}`, + /* requestData */ null, 'v1beta1'); + } + /** + * @param parentResourceName - Fully-qualified resource name of the project whose iOS apps + * you want to list. + */ + listIosApps(parentResourceName) { + return this.invokeRequestHandler('GET', `${parentResourceName}/iosApps?page_size=${LIST_APPS_MAX_PAGE_SIZE}`, + /* requestData */ null, 'v1beta1'); + } + /** + * @param parentResourceName - Fully-qualified resource name of the project whose iOS apps + * you want to list. + */ + listAppMetadata(parentResourceName) { + return this.invokeRequestHandler('GET', `${parentResourceName}:searchApps?page_size=${LIST_APPS_MAX_PAGE_SIZE}`, + /* requestData */ null, 'v1beta1'); + } + /** + * @param parentResourceName - Fully-qualified resource name of the project that you want + * to create the Android app within. + */ + createAndroidApp(parentResourceName, packageName, displayName) { + const requestData = { + packageName, + }; + if (validator.isNonEmptyString(displayName)) { + requestData.displayName = displayName; + } + return this + .invokeRequestHandler('POST', `${parentResourceName}/androidApps`, requestData, 'v1beta1') + .then((responseData) => { + assertServerResponse(validator.isNonNullObject(responseData), responseData, 'createAndroidApp\'s responseData must be a non-null object.'); + assertServerResponse(validator.isNonEmptyString(responseData.name), responseData, 'createAndroidApp\'s responseData.name must be a non-empty string.'); + return this.pollRemoteOperationWithExponentialBackoff(responseData.name); + }); + } + /** + * @param parentResourceName - Fully-qualified resource name of the project that you want + * to create the iOS app within. + */ + createIosApp(parentResourceName, bundleId, displayName) { + const requestData = { + bundleId, + }; + if (validator.isNonEmptyString(displayName)) { + requestData.displayName = displayName; + } + return this + .invokeRequestHandler('POST', `${parentResourceName}/iosApps`, requestData, 'v1beta1') + .then((responseData) => { + assertServerResponse(validator.isNonNullObject(responseData), responseData, 'createIosApp\'s responseData must be a non-null object.'); + assertServerResponse(validator.isNonEmptyString(responseData.name), responseData, 'createIosApp\'s responseData.name must be a non-empty string.'); + return this.pollRemoteOperationWithExponentialBackoff(responseData.name); + }); + } + /** + * @param resourceName - Fully-qualified resource name of the entity whose display name you + * want to set. + */ + setDisplayName(resourceName, newDisplayName) { + const requestData = { + displayName: newDisplayName, + }; + return this + .invokeRequestHandler('PATCH', `${resourceName}?update_mask=display_name`, requestData, 'v1beta1') + .then(() => undefined); + } + /** + * @param parentResourceName - Fully-qualified resource name of the Android app whose SHA + * certificates you want to get. + */ + getAndroidShaCertificates(parentResourceName) { + return this.invokeRequestHandler('GET', `${parentResourceName}/sha`, /* requestData */ null, 'v1beta1'); + } + /** + * @param parentResourceName - Fully-qualified resource name of the Android app that you + * want to add the given SHA certificate to. + */ + addAndroidShaCertificate(parentResourceName, certificate) { + const requestData = { + shaHash: certificate.shaHash, + certType: CERT_TYPE_API_MAP[certificate.certType], + }; + return this + .invokeRequestHandler('POST', `${parentResourceName}/sha`, requestData, 'v1beta1') + .then(() => undefined); + } + /** + * @param parentResourceName - Fully-qualified resource name of the app whose config you + * want to get. + */ + getConfig(parentResourceName) { + return this.invokeRequestHandler('GET', `${parentResourceName}/config`, /* requestData */ null, 'v1beta1'); + } + /** + * @param parentResourceName - Fully-qualified resource name of the entity that you want to + * get. + */ + getResource(parentResourceName) { + return this.invokeRequestHandler('GET', parentResourceName, /* requestData */ null, 'v1beta1'); + } + /** + * @param resourceName - Fully-qualified resource name of the entity that you want to + * delete. + */ + deleteResource(resourceName) { + return this + .invokeRequestHandler('DELETE', resourceName, /* requestData */ null, 'v1beta1') + .then(() => undefined); + } + pollRemoteOperationWithExponentialBackoff(operationResourceName) { + const poller = new api_request_1.ExponentialBackoffPoller(); + return poller.poll(() => { + return this.invokeRequestHandler('GET', operationResourceName, /* requestData */ null) + .then((responseData) => { + if (responseData.error) { + const errStatusCode = responseData.error.code || 500; + const errText = responseData.error.message || JSON.stringify(responseData.error); + ProjectManagementRequestHandler.wrapAndRethrowHttpError(errStatusCode, errText); + } + if (!responseData.done) { + // Continue polling. + return null; + } + // Polling complete. Resolve with operation response JSON. + return responseData.response; + }); + }); + } + /** + * Invokes the request handler with the provided request data. + */ + invokeRequestHandler(method, path, requestData, apiVersion = 'v1') { + const baseUrlToUse = (apiVersion === 'v1') ? this.baseUrl : this.baseBetaUrl; + const request = { + method, + url: `${baseUrlToUse}${path}`, + headers: PROJECT_MANAGEMENT_HEADERS, + data: requestData, + timeout: PROJECT_MANAGEMENT_TIMEOUT_MILLIS, + }; + return this.httpClient.send(request) + .then((response) => { + // Send non-JSON responses to the catch() below, where they will be treated as errors. + if (!response.isJson()) { + throw new api_request_1.RequestResponseError(response); + } + return response.data; + }) + .catch((err) => { + if (err instanceof api_request_1.RequestResponseError) { + ProjectManagementRequestHandler.wrapAndRethrowHttpError(err.response.status, err.response.text); + } + throw err; + }); + } +} +exports.ProjectManagementRequestHandler = ProjectManagementRequestHandler; diff --git a/node_modules/firebase-admin/lib/project-management/project-management-namespace.d.ts b/node_modules/firebase-admin/lib/project-management/project-management-namespace.d.ts new file mode 100644 index 0000000..1b455ce --- /dev/null +++ b/node_modules/firebase-admin/lib/project-management/project-management-namespace.d.ts @@ -0,0 +1,82 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +import { AppMetadata as TAppMetadata, AppPlatform as TAppPlatform } from './app-metadata'; +import { ProjectManagement as TProjectManagement } from './project-management'; +import { AndroidApp as TAndroidApp, AndroidAppMetadata as TAndroidAppMetadata, ShaCertificate as TShaCertificate } from './android-app'; +import { IosApp as TIosApp, IosAppMetadata as TIosAppMetadata } from './ios-app'; +/** + * Gets the {@link firebase-admin.project-management#ProjectManagement} service for the + * default app or a given app. + * + * `admin.projectManagement()` can be called with no arguments to access the + * default app's `ProjectManagement` service, or as `admin.projectManagement(app)` to access + * the `ProjectManagement` service associated with a specific app. + * + * @example + * ```javascript + * // Get the ProjectManagement service for the default app + * var defaultProjectManagement = admin.projectManagement(); + * ``` + * + * @example + * ```javascript + * // Get the ProjectManagement service for a given app + * var otherProjectManagement = admin.projectManagement(otherApp); + * ``` + * + * @param app - Optional app whose `ProjectManagement` service + * to return. If not provided, the default `ProjectManagement` service will + * be returned. * + * @returns The default `ProjectManagement` service if no app is provided or the + * `ProjectManagement` service associated with the provided app. + */ +export declare function projectManagement(app?: App): projectManagement.ProjectManagement; +export declare namespace projectManagement { + /** + * Type alias to {@link firebase-admin.project-management#AppMetadata}. + */ + type AppMetadata = TAppMetadata; + /** + * Type alias to {@link firebase-admin.project-management#AppPlatform}. + */ + type AppPlatform = TAppPlatform; + /** + * Type alias to {@link firebase-admin.project-management#ProjectManagement}. + */ + type ProjectManagement = TProjectManagement; + /** + * Type alias to {@link firebase-admin.project-management#IosApp}. + */ + type IosApp = TIosApp; + /** + * Type alias to {@link firebase-admin.project-management#IosAppMetadata}. + */ + type IosAppMetadata = TIosAppMetadata; + /** + * Type alias to {@link firebase-admin.project-management#AndroidApp}. + */ + type AndroidApp = TAndroidApp; + /** + * Type alias to {@link firebase-admin.project-management#AndroidAppMetadata}. + */ + type AndroidAppMetadata = TAndroidAppMetadata; + /** + * Type alias to {@link firebase-admin.project-management#ShaCertificate}. + */ + type ShaCertificate = TShaCertificate; +} diff --git a/node_modules/firebase-admin/lib/project-management/project-management-namespace.js b/node_modules/firebase-admin/lib/project-management/project-management-namespace.js new file mode 100644 index 0000000..a91b066 --- /dev/null +++ b/node_modules/firebase-admin/lib/project-management/project-management-namespace.js @@ -0,0 +1,18 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/firebase-admin/lib/project-management/project-management.d.ts b/node_modules/firebase-admin/lib/project-management/project-management.d.ts new file mode 100644 index 0000000..a2451c2 --- /dev/null +++ b/node_modules/firebase-admin/lib/project-management/project-management.d.ts @@ -0,0 +1,115 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +import { AndroidApp, ShaCertificate } from './android-app'; +import { IosApp } from './ios-app'; +import { AppMetadata } from './app-metadata'; +/** + * The Firebase ProjectManagement service interface. + */ +export declare class ProjectManagement { + readonly app: App; + private readonly requestHandler; + private projectId; + /** + * Lists up to 100 Firebase Android apps associated with this Firebase project. + * + * @returns The list of Android apps. + */ + listAndroidApps(): Promise; + /** + * Lists up to 100 Firebase iOS apps associated with this Firebase project. + * + * @returns The list of iOS apps. + */ + listIosApps(): Promise; + /** + * Creates an `AndroidApp` object, referencing the specified Android app within + * this Firebase project. + * + * This method does not perform an RPC. + * + * @param appId - The `appId` of the Android app to reference. + * + * @returns An `AndroidApp` object that references the specified Firebase Android app. + */ + androidApp(appId: string): AndroidApp; + /** + * Creates an `iOSApp` object, referencing the specified iOS app within + * this Firebase project. + * + * This method does not perform an RPC. + * + * @param appId - The `appId` of the iOS app to reference. + * + * @returns An `iOSApp` object that references the specified Firebase iOS app. + */ + iosApp(appId: string): IosApp; + /** + * Creates a `ShaCertificate` object. + * + * This method does not perform an RPC. + * + * @param shaHash - The SHA-1 or SHA-256 hash for this certificate. + * + * @returns A `ShaCertificate` object contains the specified SHA hash. + */ + shaCertificate(shaHash: string): ShaCertificate; + /** + * Creates a new Firebase Android app associated with this Firebase project. + * + * @param packageName - The canonical package name of the Android App, + * as would appear in the Google Play Developer Console. + * @param displayName - An optional user-assigned display name for this + * new app. + * + * @returns A promise that resolves to the newly created Android app. + */ + createAndroidApp(packageName: string, displayName?: string): Promise; + /** + * Creates a new Firebase iOS app associated with this Firebase project. + * + * @param bundleId - The iOS app bundle ID to use for this new app. + * @param displayName - An optional user-assigned display name for this + * new app. + * + * @returns A promise that resolves to the newly created iOS app. + */ + createIosApp(bundleId: string, displayName?: string): Promise; + /** + * Lists up to 100 Firebase apps associated with this Firebase project. + * + * @returns A promise that resolves to the metadata list of the apps. + */ + listAppMetadata(): Promise; + /** + * Update the display name of this Firebase project. + * + * @param newDisplayName - The new display name to be updated. + * + * @returns A promise that resolves when the project display name has been updated. + */ + setDisplayName(newDisplayName: string): Promise; + private transformResponseToAppMetadata; + private getResourceName; + private getProjectId; + /** + * Lists up to 100 Firebase apps for a specified platform, associated with this Firebase project. + */ + private listPlatformApps; + private assertListAppsResponseData; +} diff --git a/node_modules/firebase-admin/lib/project-management/project-management.js b/node_modules/firebase-admin/lib/project-management/project-management.js new file mode 100644 index 0000000..6d4cedb --- /dev/null +++ b/node_modules/firebase-admin/lib/project-management/project-management.js @@ -0,0 +1,244 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProjectManagement = void 0; +const error_1 = require("../utils/error"); +const utils = require("../utils/index"); +const validator = require("../utils/validator"); +const android_app_1 = require("./android-app"); +const ios_app_1 = require("./ios-app"); +const project_management_api_request_internal_1 = require("./project-management-api-request-internal"); +const app_metadata_1 = require("./app-metadata"); +/** + * The Firebase ProjectManagement service interface. + */ +class ProjectManagement { + /** + * @param app - The app for this ProjectManagement service. + * @constructor + * @internal + */ + constructor(app) { + this.app = app; + if (!validator.isNonNullObject(app) || !('options' in app)) { + throw new error_1.FirebaseProjectManagementError('invalid-argument', 'First argument passed to admin.projectManagement() must be a valid Firebase app ' + + 'instance.'); + } + this.requestHandler = new project_management_api_request_internal_1.ProjectManagementRequestHandler(app); + } + /** + * Lists up to 100 Firebase Android apps associated with this Firebase project. + * + * @returns The list of Android apps. + */ + listAndroidApps() { + return this.listPlatformApps('android', 'listAndroidApps()'); + } + /** + * Lists up to 100 Firebase iOS apps associated with this Firebase project. + * + * @returns The list of iOS apps. + */ + listIosApps() { + return this.listPlatformApps('ios', 'listIosApps()'); + } + /** + * Creates an `AndroidApp` object, referencing the specified Android app within + * this Firebase project. + * + * This method does not perform an RPC. + * + * @param appId - The `appId` of the Android app to reference. + * + * @returns An `AndroidApp` object that references the specified Firebase Android app. + */ + androidApp(appId) { + return new android_app_1.AndroidApp(appId, this.requestHandler); + } + /** + * Creates an `iOSApp` object, referencing the specified iOS app within + * this Firebase project. + * + * This method does not perform an RPC. + * + * @param appId - The `appId` of the iOS app to reference. + * + * @returns An `iOSApp` object that references the specified Firebase iOS app. + */ + iosApp(appId) { + return new ios_app_1.IosApp(appId, this.requestHandler); + } + /** + * Creates a `ShaCertificate` object. + * + * This method does not perform an RPC. + * + * @param shaHash - The SHA-1 or SHA-256 hash for this certificate. + * + * @returns A `ShaCertificate` object contains the specified SHA hash. + */ + shaCertificate(shaHash) { + return new android_app_1.ShaCertificate(shaHash); + } + /** + * Creates a new Firebase Android app associated with this Firebase project. + * + * @param packageName - The canonical package name of the Android App, + * as would appear in the Google Play Developer Console. + * @param displayName - An optional user-assigned display name for this + * new app. + * + * @returns A promise that resolves to the newly created Android app. + */ + createAndroidApp(packageName, displayName) { + return this.getResourceName() + .then((resourceName) => { + return this.requestHandler.createAndroidApp(resourceName, packageName, displayName); + }) + .then((responseData) => { + (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonNullObject(responseData), responseData, 'createAndroidApp()\'s responseData must be a non-null object.'); + (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonEmptyString(responseData.appId), responseData, '"responseData.appId" field must be present in createAndroidApp()\'s response data.'); + return new android_app_1.AndroidApp(responseData.appId, this.requestHandler); + }); + } + /** + * Creates a new Firebase iOS app associated with this Firebase project. + * + * @param bundleId - The iOS app bundle ID to use for this new app. + * @param displayName - An optional user-assigned display name for this + * new app. + * + * @returns A promise that resolves to the newly created iOS app. + */ + createIosApp(bundleId, displayName) { + return this.getResourceName() + .then((resourceName) => { + return this.requestHandler.createIosApp(resourceName, bundleId, displayName); + }) + .then((responseData) => { + (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonNullObject(responseData), responseData, 'createIosApp()\'s responseData must be a non-null object.'); + (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonEmptyString(responseData.appId), responseData, '"responseData.appId" field must be present in createIosApp()\'s response data.'); + return new ios_app_1.IosApp(responseData.appId, this.requestHandler); + }); + } + /** + * Lists up to 100 Firebase apps associated with this Firebase project. + * + * @returns A promise that resolves to the metadata list of the apps. + */ + listAppMetadata() { + return this.getResourceName() + .then((resourceName) => { + return this.requestHandler.listAppMetadata(resourceName); + }) + .then((responseData) => { + return this.getProjectId() + .then((projectId) => { + return this.transformResponseToAppMetadata(responseData, projectId); + }); + }); + } + /** + * Update the display name of this Firebase project. + * + * @param newDisplayName - The new display name to be updated. + * + * @returns A promise that resolves when the project display name has been updated. + */ + setDisplayName(newDisplayName) { + return this.getResourceName() + .then((resourceName) => { + return this.requestHandler.setDisplayName(resourceName, newDisplayName); + }); + } + transformResponseToAppMetadata(responseData, projectId) { + this.assertListAppsResponseData(responseData, 'listAppMetadata()'); + if (!responseData.apps) { + return []; + } + return responseData.apps.map((appJson) => { + (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonEmptyString(appJson.appId), responseData, '"apps[].appId" field must be present in the listAppMetadata() response data.'); + (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonEmptyString(appJson.platform), responseData, '"apps[].platform" field must be present in the listAppMetadata() response data.'); + const metadata = { + appId: appJson.appId, + platform: app_metadata_1.AppPlatform[appJson.platform] || app_metadata_1.AppPlatform.PLATFORM_UNKNOWN, + projectId, + resourceName: appJson.name, + }; + if (appJson.displayName) { + metadata.displayName = appJson.displayName; + } + return metadata; + }); + } + getResourceName() { + return this.getProjectId() + .then((projectId) => { + return `projects/${projectId}`; + }); + } + getProjectId() { + if (this.projectId) { + return Promise.resolve(this.projectId); + } + return utils.findProjectId(this.app) + .then((projectId) => { + // Assert that a specific project ID was provided within the app. + if (!validator.isNonEmptyString(projectId)) { + throw new error_1.FirebaseProjectManagementError('invalid-project-id', 'Failed to determine project ID. Initialize the SDK with service account credentials, or ' + + 'set project ID as an app option. Alternatively, set the GOOGLE_CLOUD_PROJECT ' + + 'environment variable.'); + } + this.projectId = projectId; + return this.projectId; + }); + } + /** + * Lists up to 100 Firebase apps for a specified platform, associated with this Firebase project. + */ + listPlatformApps(platform, callerName) { + return this.getResourceName() + .then((resourceName) => { + return (platform === 'android') ? + this.requestHandler.listAndroidApps(resourceName) + : this.requestHandler.listIosApps(resourceName); + }) + .then((responseData) => { + this.assertListAppsResponseData(responseData, callerName); + if (!responseData.apps) { + return []; + } + return responseData.apps.map((appJson) => { + (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonEmptyString(appJson.appId), responseData, `"apps[].appId" field must be present in the ${callerName} response data.`); + if (platform === 'android') { + return new android_app_1.AndroidApp(appJson.appId, this.requestHandler); + } + else { + return new ios_app_1.IosApp(appJson.appId, this.requestHandler); + } + }); + }); + } + assertListAppsResponseData(responseData, callerName) { + (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonNullObject(responseData), responseData, `${callerName}'s responseData must be a non-null object.`); + if (responseData.apps) { + (0, project_management_api_request_internal_1.assertServerResponse)(validator.isArray(responseData.apps), responseData, `"apps" field must be present in the ${callerName} response data.`); + } + } +} +exports.ProjectManagement = ProjectManagement; diff --git a/node_modules/firebase-admin/lib/remote-config/condition-evaluator-internal.d.ts b/node_modules/firebase-admin/lib/remote-config/condition-evaluator-internal.d.ts new file mode 100644 index 0000000..ca73f76 --- /dev/null +++ b/node_modules/firebase-admin/lib/remote-config/condition-evaluator-internal.d.ts @@ -0,0 +1,17 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/firebase-admin/lib/remote-config/condition-evaluator-internal.js b/node_modules/firebase-admin/lib/remote-config/condition-evaluator-internal.js new file mode 100644 index 0000000..081d002 --- /dev/null +++ b/node_modules/firebase-admin/lib/remote-config/condition-evaluator-internal.js @@ -0,0 +1,230 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use strict'; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConditionEvaluator = void 0; +const remote_config_api_1 = require("./remote-config-api"); +const crypto_1 = require("crypto"); +/** + * Encapsulates condition evaluation logic to simplify organization and + * facilitate testing. + * + * @internal + */ +class ConditionEvaluator { + evaluateConditions(namedConditions, context) { + // The order of the conditions is significant. + // A JS Map preserves the order of insertion ("Iteration happens in insertion order" + // - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#description). + const evaluatedConditions = new Map(); + for (const namedCondition of namedConditions) { + evaluatedConditions.set(namedCondition.name, this.evaluateCondition(namedCondition.condition, context)); + } + return evaluatedConditions; + } + evaluateCondition(condition, context, nestingLevel = 0) { + if (nestingLevel >= ConditionEvaluator.MAX_CONDITION_RECURSION_DEPTH) { + // TODO: add logging once we have a wrapped logger. + return false; + } + if (condition.orCondition) { + return this.evaluateOrCondition(condition.orCondition, context, nestingLevel + 1); + } + if (condition.andCondition) { + return this.evaluateAndCondition(condition.andCondition, context, nestingLevel + 1); + } + if (condition.true) { + return true; + } + if (condition.false) { + return false; + } + if (condition.percent) { + return this.evaluatePercentCondition(condition.percent, context); + } + if (condition.customSignal) { + return this.evaluateCustomSignalCondition(condition.customSignal, context); + } + // TODO: add logging once we have a wrapped logger. + return false; + } + evaluateOrCondition(orCondition, context, nestingLevel) { + const subConditions = orCondition.conditions || []; + for (const subCondition of subConditions) { + // Recursive call. + const result = this.evaluateCondition(subCondition, context, nestingLevel + 1); + // Short-circuit the evaluation result for true. + if (result) { + return result; + } + } + return false; + } + evaluateAndCondition(andCondition, context, nestingLevel) { + const subConditions = andCondition.conditions || []; + for (const subCondition of subConditions) { + // Recursive call. + const result = this.evaluateCondition(subCondition, context, nestingLevel + 1); + // Short-circuit the evaluation result for false. + if (!result) { + return result; + } + } + return true; + } + evaluatePercentCondition(percentCondition, context) { + if (!context.randomizationId) { + // TODO: add logging once we have a wrapped logger. + return false; + } + // This is the entry point for processing percent condition data from the response. + // We're not using a proto library, so we can't assume undefined fields have + // default values. + const { seed, percentOperator, microPercent, microPercentRange } = percentCondition; + if (!percentOperator) { + // TODO: add logging once we have a wrapped logger. + return false; + } + const normalizedMicroPercent = microPercent || 0; + const normalizedMicroPercentUpperBound = microPercentRange?.microPercentUpperBound || 0; + const normalizedMicroPercentLowerBound = microPercentRange?.microPercentLowerBound || 0; + const seedPrefix = seed && seed.length > 0 ? `${seed}.` : ''; + const stringToHash = `${seedPrefix}${context.randomizationId}`; + const hash = ConditionEvaluator.hashSeededRandomizationId(stringToHash); + const instanceMicroPercentile = hash % BigInt(100 * 1000000); + switch (percentOperator) { + case remote_config_api_1.PercentConditionOperator.LESS_OR_EQUAL: + return instanceMicroPercentile <= normalizedMicroPercent; + case remote_config_api_1.PercentConditionOperator.GREATER_THAN: + return instanceMicroPercentile > normalizedMicroPercent; + case remote_config_api_1.PercentConditionOperator.BETWEEN: + return instanceMicroPercentile > normalizedMicroPercentLowerBound + && instanceMicroPercentile <= normalizedMicroPercentUpperBound; + case remote_config_api_1.PercentConditionOperator.UNKNOWN: + default: + break; + } + // TODO: add logging once we have a wrapped logger. + return false; + } + static hashSeededRandomizationId(seededRandomizationId) { + const hex = (0, crypto_1.createHash)('sha256').update(seededRandomizationId).digest('hex'); + return BigInt(`0x${hex}`); + } + evaluateCustomSignalCondition(customSignalCondition, context) { + const { customSignalOperator, customSignalKey, targetCustomSignalValues, } = customSignalCondition; + if (!customSignalOperator || !customSignalKey || !targetCustomSignalValues) { + // TODO: add logging once we have a wrapped logger. + return false; + } + if (!targetCustomSignalValues.length) { + return false; + } + // Extract the value of the signal from the evaluation context. + const actualCustomSignalValue = context[customSignalKey]; + if (actualCustomSignalValue == undefined) { + return false; + } + switch (customSignalOperator) { + case remote_config_api_1.CustomSignalOperator.STRING_CONTAINS: + return compareStrings(targetCustomSignalValues, actualCustomSignalValue, (target, actual) => actual.includes(target)); + case remote_config_api_1.CustomSignalOperator.STRING_DOES_NOT_CONTAIN: + return !compareStrings(targetCustomSignalValues, actualCustomSignalValue, (target, actual) => actual.includes(target)); + case remote_config_api_1.CustomSignalOperator.STRING_EXACTLY_MATCHES: + return compareStrings(targetCustomSignalValues, actualCustomSignalValue, (target, actual) => actual.trim() === target.trim()); + case remote_config_api_1.CustomSignalOperator.STRING_CONTAINS_REGEX: + return compareStrings(targetCustomSignalValues, actualCustomSignalValue, (target, actual) => new RegExp(target).test(actual)); + // For numeric operators only one target value is allowed. + case remote_config_api_1.CustomSignalOperator.NUMERIC_LESS_THAN: + return compareNumbers(actualCustomSignalValue, targetCustomSignalValues[0], (r) => r < 0); + case remote_config_api_1.CustomSignalOperator.NUMERIC_LESS_EQUAL: + return compareNumbers(actualCustomSignalValue, targetCustomSignalValues[0], (r) => r <= 0); + case remote_config_api_1.CustomSignalOperator.NUMERIC_EQUAL: + return compareNumbers(actualCustomSignalValue, targetCustomSignalValues[0], (r) => r === 0); + case remote_config_api_1.CustomSignalOperator.NUMERIC_NOT_EQUAL: + return compareNumbers(actualCustomSignalValue, targetCustomSignalValues[0], (r) => r !== 0); + case remote_config_api_1.CustomSignalOperator.NUMERIC_GREATER_THAN: + return compareNumbers(actualCustomSignalValue, targetCustomSignalValues[0], (r) => r > 0); + case remote_config_api_1.CustomSignalOperator.NUMERIC_GREATER_EQUAL: + return compareNumbers(actualCustomSignalValue, targetCustomSignalValues[0], (r) => r >= 0); + // For semantic operators only one target value is allowed. + case remote_config_api_1.CustomSignalOperator.SEMANTIC_VERSION_LESS_THAN: + return compareSemanticVersions(actualCustomSignalValue, targetCustomSignalValues[0], (r) => r < 0); + case remote_config_api_1.CustomSignalOperator.SEMANTIC_VERSION_LESS_EQUAL: + return compareSemanticVersions(actualCustomSignalValue, targetCustomSignalValues[0], (r) => r <= 0); + case remote_config_api_1.CustomSignalOperator.SEMANTIC_VERSION_EQUAL: + return compareSemanticVersions(actualCustomSignalValue, targetCustomSignalValues[0], (r) => r === 0); + case remote_config_api_1.CustomSignalOperator.SEMANTIC_VERSION_NOT_EQUAL: + return compareSemanticVersions(actualCustomSignalValue, targetCustomSignalValues[0], (r) => r !== 0); + case remote_config_api_1.CustomSignalOperator.SEMANTIC_VERSION_GREATER_THAN: + return compareSemanticVersions(actualCustomSignalValue, targetCustomSignalValues[0], (r) => r > 0); + case remote_config_api_1.CustomSignalOperator.SEMANTIC_VERSION_GREATER_EQUAL: + return compareSemanticVersions(actualCustomSignalValue, targetCustomSignalValues[0], (r) => r >= 0); + } + // TODO: add logging once we have a wrapped logger. + return false; + } +} +exports.ConditionEvaluator = ConditionEvaluator; +ConditionEvaluator.MAX_CONDITION_RECURSION_DEPTH = 10; +// Compares the actual string value of a signal against a list of target +// values. If any of the target values are a match, returns true. +function compareStrings(targetValues, actualValue, predicateFn) { + const actual = String(actualValue); + return targetValues.some((target) => predicateFn(target, actual)); +} +// Compares two numbers against each other. +// Calls the predicate function with -1, 0, 1 if actual is less than, equal to, or greater than target. +function compareNumbers(actualValue, targetValue, predicateFn) { + const target = Number(targetValue); + const actual = Number(actualValue); + if (isNaN(target) || isNaN(actual)) { + return false; + } + return predicateFn(actual < target ? -1 : actual > target ? 1 : 0); +} +// Max number of segments a numeric version can have. This is enforced by the server as well. +const MAX_LENGTH = 5; +// Compares semantic version strings against each other. +// Calls the predicate function with -1, 0, 1 if actual is less than, equal to, or greater than target. +function compareSemanticVersions(actualValue, targetValue, predicateFn) { + const version1 = String(actualValue).split('.').map(Number); + const version2 = targetValue.split('.').map(Number); + if (version1.length > MAX_LENGTH || version2.length > MAX_LENGTH) { + return false; + } + for (let i = 0; i < MAX_LENGTH; i++) { + // Check to see if segments are present. Note that these may be present and be NaN. + const version1HasSegment = version1[i] !== undefined; + const version2HasSegment = version2[i] !== undefined; + // Insert zeros if undefined for easier comparison. + if (!version1HasSegment) + version1[i] = 0; + if (!version2HasSegment) + version2[i] = 0; + // At this point, if either segment is NaN, we return false directly. + if (isNaN(version1[i]) || isNaN(version2[i])) + return false; + // Check if we have a difference in segments. Otherwise continue to next segment. + if (version1[i] < version2[i]) + return predicateFn(-1); + if (version1[i] > version2[i]) + return predicateFn(1); + } + // If this point is reached, the semantic versions are equal. + return predicateFn(0); +} diff --git a/node_modules/firebase-admin/lib/remote-config/index.d.ts b/node_modules/firebase-admin/lib/remote-config/index.d.ts new file mode 100644 index 0000000..c34ac52 --- /dev/null +++ b/node_modules/firebase-admin/lib/remote-config/index.d.ts @@ -0,0 +1,52 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Firebase Remote Config. + * + * @packageDocumentation + */ +import { App } from '../app'; +import { RemoteConfig } from './remote-config'; +export { AndCondition, CustomSignalCondition, CustomSignalOperator, DefaultConfig, EvaluationContext, ExplicitParameterValue, FetchResponseData, GetServerTemplateOptions, InAppDefaultValue, InitServerTemplateOptions, ListVersionsOptions, ListVersionsResult, MicroPercentRange, NamedCondition, OneOfCondition, OrCondition, ParameterValueType, PercentConditionOperator, PercentCondition, PredefinedSignals, RemoteConfigCondition, RemoteConfigParameter, RemoteConfigParameterGroup, RemoteConfigParameterValue, RemoteConfigTemplate, RemoteConfigUser, ServerConfig, ServerTemplate, ServerTemplateData, ServerTemplateDataType, TagColor, UserProvidedSignals, Value, ValueSource, Version, } from './remote-config-api'; +export { RemoteConfig, RemoteConfigFetchResponse } from './remote-config'; +/** + * Gets the {@link RemoteConfig} service for the default app or a given app. + * + * `getRemoteConfig()` can be called with no arguments to access the default + * app's `RemoteConfig` service or as `getRemoteConfig(app)` to access the + * `RemoteConfig` service associated with a specific app. + * + * @example + * ```javascript + * // Get the `RemoteConfig` service for the default app + * const defaultRemoteConfig = getRemoteConfig(); + * ``` + * + * @example + * ```javascript + * // Get the `RemoteConfig` service for a given app + * const otherRemoteConfig = getRemoteConfig(otherApp); + * ``` + * + * @param app - Optional app for which to return the `RemoteConfig` service. + * If not provided, the default `RemoteConfig` service is returned. + * + * @returns The default `RemoteConfig` service if no + * app is provided, or the `RemoteConfig` service associated with the provided + * app. + */ +export declare function getRemoteConfig(app?: App): RemoteConfig; diff --git a/node_modules/firebase-admin/lib/remote-config/index.js b/node_modules/firebase-admin/lib/remote-config/index.js new file mode 100644 index 0000000..316b9b9 --- /dev/null +++ b/node_modules/firebase-admin/lib/remote-config/index.js @@ -0,0 +1,66 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RemoteConfigFetchResponse = exports.RemoteConfig = exports.PercentConditionOperator = exports.CustomSignalOperator = void 0; +exports.getRemoteConfig = getRemoteConfig; +/** + * Firebase Remote Config. + * + * @packageDocumentation + */ +const app_1 = require("../app"); +const remote_config_1 = require("./remote-config"); +var remote_config_api_1 = require("./remote-config-api"); +Object.defineProperty(exports, "CustomSignalOperator", { enumerable: true, get: function () { return remote_config_api_1.CustomSignalOperator; } }); +Object.defineProperty(exports, "PercentConditionOperator", { enumerable: true, get: function () { return remote_config_api_1.PercentConditionOperator; } }); +var remote_config_2 = require("./remote-config"); +Object.defineProperty(exports, "RemoteConfig", { enumerable: true, get: function () { return remote_config_2.RemoteConfig; } }); +Object.defineProperty(exports, "RemoteConfigFetchResponse", { enumerable: true, get: function () { return remote_config_2.RemoteConfigFetchResponse; } }); +/** + * Gets the {@link RemoteConfig} service for the default app or a given app. + * + * `getRemoteConfig()` can be called with no arguments to access the default + * app's `RemoteConfig` service or as `getRemoteConfig(app)` to access the + * `RemoteConfig` service associated with a specific app. + * + * @example + * ```javascript + * // Get the `RemoteConfig` service for the default app + * const defaultRemoteConfig = getRemoteConfig(); + * ``` + * + * @example + * ```javascript + * // Get the `RemoteConfig` service for a given app + * const otherRemoteConfig = getRemoteConfig(otherApp); + * ``` + * + * @param app - Optional app for which to return the `RemoteConfig` service. + * If not provided, the default `RemoteConfig` service is returned. + * + * @returns The default `RemoteConfig` service if no + * app is provided, or the `RemoteConfig` service associated with the provided + * app. + */ +function getRemoteConfig(app) { + if (typeof app === 'undefined') { + app = (0, app_1.getApp)(); + } + const firebaseApp = app; + return firebaseApp.getOrInitService('remoteConfig', (app) => new remote_config_1.RemoteConfig(app)); +} diff --git a/node_modules/firebase-admin/lib/remote-config/internal/value-impl.d.ts b/node_modules/firebase-admin/lib/remote-config/internal/value-impl.d.ts new file mode 100644 index 0000000..ca73f76 --- /dev/null +++ b/node_modules/firebase-admin/lib/remote-config/internal/value-impl.d.ts @@ -0,0 +1,17 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/node_modules/firebase-admin/lib/remote-config/internal/value-impl.js b/node_modules/firebase-admin/lib/remote-config/internal/value-impl.js new file mode 100644 index 0000000..a8c6ba4 --- /dev/null +++ b/node_modules/firebase-admin/lib/remote-config/internal/value-impl.js @@ -0,0 +1,59 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +'use strict'; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValueImpl = void 0; +/** + * Implements type-safe getters for parameter values. + * + * Visible for testing. + * + * @internal + */ +class ValueImpl { + constructor(source, value = ValueImpl.DEFAULT_VALUE_FOR_STRING) { + this.source = source; + this.value = value; + } + asString() { + return this.value; + } + asBoolean() { + if (this.source === 'static') { + return ValueImpl.DEFAULT_VALUE_FOR_BOOLEAN; + } + return ValueImpl.BOOLEAN_TRUTHY_VALUES.indexOf(this.value.toLowerCase()) >= 0; + } + asNumber() { + if (this.source === 'static') { + return ValueImpl.DEFAULT_VALUE_FOR_NUMBER; + } + const num = Number(this.value); + if (isNaN(num)) { + return ValueImpl.DEFAULT_VALUE_FOR_NUMBER; + } + return num; + } + getSource() { + return this.source; + } +} +exports.ValueImpl = ValueImpl; +ValueImpl.DEFAULT_VALUE_FOR_BOOLEAN = false; +ValueImpl.DEFAULT_VALUE_FOR_STRING = ''; +ValueImpl.DEFAULT_VALUE_FOR_NUMBER = 0; +ValueImpl.BOOLEAN_TRUTHY_VALUES = ['1', 'true', 't', 'yes', 'y', 'on']; diff --git a/node_modules/firebase-admin/lib/remote-config/remote-config-api-client-internal.d.ts b/node_modules/firebase-admin/lib/remote-config/remote-config-api-client-internal.d.ts new file mode 100644 index 0000000..59460af --- /dev/null +++ b/node_modules/firebase-admin/lib/remote-config/remote-config-api-client-internal.d.ts @@ -0,0 +1,28 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { PrefixedFirebaseError } from '../utils/error'; +export type RemoteConfigErrorCode = 'aborted' | 'already-exists' | 'failed-precondition' | 'internal-error' | 'invalid-argument' | 'not-found' | 'out-of-range' | 'permission-denied' | 'resource-exhausted' | 'unauthenticated' | 'unknown-error'; +/** + * Firebase Remote Config error code structure. This extends PrefixedFirebaseError. + * + * @param {RemoteConfigErrorCode} code The error code. + * @param {string} message The error message. + * @constructor + */ +export declare class FirebaseRemoteConfigError extends PrefixedFirebaseError { + constructor(code: RemoteConfigErrorCode, message: string); +} diff --git a/node_modules/firebase-admin/lib/remote-config/remote-config-api-client-internal.js b/node_modules/firebase-admin/lib/remote-config/remote-config-api-client-internal.js new file mode 100644 index 0000000..05517ac --- /dev/null +++ b/node_modules/firebase-admin/lib/remote-config/remote-config-api-client-internal.js @@ -0,0 +1,407 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirebaseRemoteConfigError = exports.RemoteConfigApiClient = void 0; +const api_request_1 = require("../utils/api-request"); +const error_1 = require("../utils/error"); +const utils = require("../utils/index"); +const validator = require("../utils/validator"); +const deep_copy_1 = require("../utils/deep-copy"); +// Remote Config backend constants +/** + * Allows the `FIREBASE_REMOTE_CONFIG_URL_BASE` environment + * variable to override the default API endpoint URL. + */ +const FIREBASE_REMOTE_CONFIG_URL_BASE = process.env.FIREBASE_REMOTE_CONFIG_URL_BASE || 'https://firebaseremoteconfig.googleapis.com'; +const FIREBASE_REMOTE_CONFIG_HEADERS = { + 'X-Firebase-Client': `fire-admin-node/${utils.getSdkVersion()}`, + // There is a known issue in which the ETag is not properly returned in cases where the request + // does not specify a compression type. Currently, it is required to include the header + // `Accept-Encoding: gzip` or equivalent in all requests. + // https://firebase.google.com/docs/remote-config/use-config-rest#etag_usage_and_forced_updates + 'Accept-Encoding': 'gzip', +}; +/** + * Class that facilitates sending requests to the Firebase Remote Config backend API. + * + * @internal + */ +class RemoteConfigApiClient { + constructor(app) { + this.app = app; + if (!validator.isNonNullObject(app) || !('options' in app)) { + throw new FirebaseRemoteConfigError('invalid-argument', 'First argument passed to admin.remoteConfig() must be a valid Firebase app instance.'); + } + this.httpClient = new api_request_1.AuthorizedHttpClient(app); + } + getTemplate() { + return this.getUrl() + .then((url) => { + const request = { + method: 'GET', + url: `${url}/remoteConfig`, + headers: FIREBASE_REMOTE_CONFIG_HEADERS + }; + return this.httpClient.send(request); + }) + .then((resp) => { + return this.toRemoteConfigTemplate(resp); + }) + .catch((err) => { + throw this.toFirebaseError(err); + }); + } + getTemplateAtVersion(versionNumber) { + const data = { versionNumber: this.validateVersionNumber(versionNumber) }; + return this.getUrl() + .then((url) => { + const request = { + method: 'GET', + url: `${url}/remoteConfig`, + headers: FIREBASE_REMOTE_CONFIG_HEADERS, + data + }; + return this.httpClient.send(request); + }) + .then((resp) => { + return this.toRemoteConfigTemplate(resp); + }) + .catch((err) => { + throw this.toFirebaseError(err); + }); + } + validateTemplate(template) { + template = this.validateInputRemoteConfigTemplate(template); + return this.sendPutRequest(template, template.etag, true) + .then((resp) => { + // validating a template returns an etag with the suffix -0 means that your update + // was successfully validated. We set the etag back to the original etag of the template + // to allow future operations. + this.validateEtag(resp.headers['etag']); + return this.toRemoteConfigTemplate(resp, template.etag); + }) + .catch((err) => { + throw this.toFirebaseError(err); + }); + } + publishTemplate(template, options) { + template = this.validateInputRemoteConfigTemplate(template); + let ifMatch = template.etag; + if (options && options.force === true) { + // setting `If-Match: *` forces the Remote Config template to be updated + // and circumvent the ETag, and the protection from that it provides. + ifMatch = '*'; + } + return this.sendPutRequest(template, ifMatch) + .then((resp) => { + return this.toRemoteConfigTemplate(resp); + }) + .catch((err) => { + throw this.toFirebaseError(err); + }); + } + rollback(versionNumber) { + const data = { versionNumber: this.validateVersionNumber(versionNumber) }; + return this.getUrl() + .then((url) => { + const request = { + method: 'POST', + url: `${url}/remoteConfig:rollback`, + headers: FIREBASE_REMOTE_CONFIG_HEADERS, + data + }; + return this.httpClient.send(request); + }) + .then((resp) => { + return this.toRemoteConfigTemplate(resp); + }) + .catch((err) => { + throw this.toFirebaseError(err); + }); + } + listVersions(options) { + if (typeof options !== 'undefined') { + options = this.validateListVersionsOptions(options); + } + return this.getUrl() + .then((url) => { + const request = { + method: 'GET', + url: `${url}/remoteConfig:listVersions`, + headers: FIREBASE_REMOTE_CONFIG_HEADERS, + data: options + }; + return this.httpClient.send(request); + }) + .then((resp) => { + return resp.data; + }) + .catch((err) => { + throw this.toFirebaseError(err); + }); + } + getServerTemplate() { + return this.getUrl() + .then((url) => { + const request = { + method: 'GET', + url: `${url}/namespaces/firebase-server/serverRemoteConfig`, + headers: FIREBASE_REMOTE_CONFIG_HEADERS + }; + return this.httpClient.send(request); + }) + .then((resp) => { + return this.toRemoteConfigServerTemplate(resp); + }) + .catch((err) => { + throw this.toFirebaseError(err); + }); + } + sendPutRequest(template, etag, validateOnly) { + let path = 'remoteConfig'; + if (validateOnly) { + path += '?validate_only=true'; + } + return this.getUrl() + .then((url) => { + const request = { + method: 'PUT', + url: `${url}/${path}`, + headers: { ...FIREBASE_REMOTE_CONFIG_HEADERS, 'If-Match': etag }, + data: { + conditions: template.conditions, + parameters: template.parameters, + parameterGroups: template.parameterGroups, + version: template.version, + } + }; + return this.httpClient.send(request); + }); + } + getUrl() { + return this.getProjectIdPrefix() + .then((projectIdPrefix) => { + return `${FIREBASE_REMOTE_CONFIG_URL_BASE}/v1/${projectIdPrefix}`; + }); + } + getProjectIdPrefix() { + if (this.projectIdPrefix) { + return Promise.resolve(this.projectIdPrefix); + } + return utils.findProjectId(this.app) + .then((projectId) => { + if (!validator.isNonEmptyString(projectId)) { + throw new FirebaseRemoteConfigError('unknown-error', 'Failed to determine project ID. Initialize the SDK with service account credentials, or ' + + 'set project ID as an app option. Alternatively, set the GOOGLE_CLOUD_PROJECT ' + + 'environment variable.'); + } + this.projectIdPrefix = `projects/${projectId}`; + return this.projectIdPrefix; + }); + } + toFirebaseError(err) { + if (err instanceof error_1.PrefixedFirebaseError) { + return err; + } + const response = err.response; + if (!response.isJson()) { + return new FirebaseRemoteConfigError('unknown-error', `Unexpected response with status: ${response.status} and body: ${response.text}`); + } + const error = response.data.error || {}; + let code = 'unknown-error'; + if (error.status && error.status in ERROR_CODE_MAPPING) { + code = ERROR_CODE_MAPPING[error.status]; + } + const message = error.message || `Unknown server error: ${response.text}`; + return new FirebaseRemoteConfigError(code, message); + } + /** + * Creates a RemoteConfigTemplate from the API response. + * If provided, customEtag is used instead of the etag returned in the API response. + * + * @param {HttpResponse} resp API response object. + * @param {string} customEtag A custom etag to replace the etag fom the API response (Optional). + */ + toRemoteConfigTemplate(resp, customEtag) { + const etag = (typeof customEtag === 'undefined') ? resp.headers['etag'] : customEtag; + this.validateEtag(etag); + return { + conditions: resp.data.conditions, + parameters: resp.data.parameters, + parameterGroups: resp.data.parameterGroups, + etag, + version: resp.data.version, + }; + } + /** + * Creates a RemoteConfigServerTemplate from the API response. + * If provided, customEtag is used instead of the etag returned in the API response. + * + * @param {HttpResponse} resp API response object. + * @param {string} customEtag A custom etag to replace the etag fom the API response (Optional). + */ + toRemoteConfigServerTemplate(resp, customEtag) { + const etag = (typeof customEtag === 'undefined') ? resp.headers['etag'] : customEtag; + this.validateEtag(etag); + return { + conditions: resp.data.conditions, + parameters: resp.data.parameters, + etag, + version: resp.data.version, + }; + } + /** + * Checks if the given RemoteConfigTemplate object is valid. + * The object must have valid parameters, parameter groups, conditions, and an etag. + * Removes output only properties from version metadata. + * + * @param {RemoteConfigTemplate} template A RemoteConfigTemplate object to be validated. + * + * @returns {RemoteConfigTemplate} The validated RemoteConfigTemplate object. + */ + validateInputRemoteConfigTemplate(template) { + const templateCopy = (0, deep_copy_1.deepCopy)(template); + if (!validator.isNonNullObject(templateCopy)) { + throw new FirebaseRemoteConfigError('invalid-argument', `Invalid Remote Config template: ${JSON.stringify(templateCopy)}`); + } + if (!validator.isNonEmptyString(templateCopy.etag)) { + throw new FirebaseRemoteConfigError('invalid-argument', 'ETag must be a non-empty string.'); + } + if (!validator.isNonNullObject(templateCopy.parameters)) { + throw new FirebaseRemoteConfigError('invalid-argument', 'Remote Config parameters must be a non-null object'); + } + if (!validator.isNonNullObject(templateCopy.parameterGroups)) { + throw new FirebaseRemoteConfigError('invalid-argument', 'Remote Config parameter groups must be a non-null object'); + } + if (!validator.isArray(templateCopy.conditions)) { + throw new FirebaseRemoteConfigError('invalid-argument', 'Remote Config conditions must be an array'); + } + if (typeof templateCopy.version !== 'undefined') { + // exclude output only properties and keep the only input property: description + templateCopy.version = { description: templateCopy.version.description }; + } + return templateCopy; + } + /** + * Checks if a given version number is valid. + * A version number must be an integer or a string in int64 format. + * If valid, returns the string representation of the provided version number. + * + * @param {string|number} versionNumber A version number to be validated. + * + * @returns {string} The validated version number as a string. + */ + validateVersionNumber(versionNumber, propertyName = 'versionNumber') { + if (!validator.isNonEmptyString(versionNumber) && + !validator.isNumber(versionNumber)) { + throw new FirebaseRemoteConfigError('invalid-argument', `${propertyName} must be a non-empty string in int64 format or a number`); + } + if (!Number.isInteger(Number(versionNumber))) { + throw new FirebaseRemoteConfigError('invalid-argument', `${propertyName} must be an integer or a string in int64 format`); + } + return versionNumber.toString(); + } + validateEtag(etag) { + if (!validator.isNonEmptyString(etag)) { + throw new FirebaseRemoteConfigError('invalid-argument', 'ETag header is not present in the server response.'); + } + } + /** + * Checks if a given `ListVersionsOptions` object is valid. If successful, creates a copy of the + * options object and convert `startTime` and `endTime` to RFC3339 UTC "Zulu" format, if present. + * + * @param {ListVersionsOptions} options An options object to be validated. + * + * @returns {ListVersionsOptions} A copy of the provided options object with timestamps converted + * to UTC Zulu format. + */ + validateListVersionsOptions(options) { + const optionsCopy = (0, deep_copy_1.deepCopy)(options); + if (!validator.isNonNullObject(optionsCopy)) { + throw new FirebaseRemoteConfigError('invalid-argument', 'ListVersionsOptions must be a non-null object.'); + } + if (typeof optionsCopy.pageSize !== 'undefined') { + if (!validator.isNumber(optionsCopy.pageSize)) { + throw new FirebaseRemoteConfigError('invalid-argument', 'pageSize must be a number.'); + } + if (optionsCopy.pageSize < 1 || optionsCopy.pageSize > 300) { + throw new FirebaseRemoteConfigError('invalid-argument', 'pageSize must be a number between 1 and 300 (inclusive).'); + } + } + if (typeof optionsCopy.pageToken !== 'undefined' && !validator.isNonEmptyString(optionsCopy.pageToken)) { + throw new FirebaseRemoteConfigError('invalid-argument', 'pageToken must be a string value.'); + } + if (typeof optionsCopy.endVersionNumber !== 'undefined') { + optionsCopy.endVersionNumber = this.validateVersionNumber(optionsCopy.endVersionNumber, 'endVersionNumber'); + } + if (typeof optionsCopy.startTime !== 'undefined') { + if (!(optionsCopy.startTime instanceof Date) && !validator.isUTCDateString(optionsCopy.startTime)) { + throw new FirebaseRemoteConfigError('invalid-argument', 'startTime must be a valid Date object or a UTC date string.'); + } + // Convert startTime to RFC3339 UTC "Zulu" format. + if (optionsCopy.startTime instanceof Date) { + optionsCopy.startTime = optionsCopy.startTime.toISOString(); + } + else { + optionsCopy.startTime = new Date(optionsCopy.startTime).toISOString(); + } + } + if (typeof optionsCopy.endTime !== 'undefined') { + if (!(optionsCopy.endTime instanceof Date) && !validator.isUTCDateString(optionsCopy.endTime)) { + throw new FirebaseRemoteConfigError('invalid-argument', 'endTime must be a valid Date object or a UTC date string.'); + } + // Convert endTime to RFC3339 UTC "Zulu" format. + if (optionsCopy.endTime instanceof Date) { + optionsCopy.endTime = optionsCopy.endTime.toISOString(); + } + else { + optionsCopy.endTime = new Date(optionsCopy.endTime).toISOString(); + } + } + // Remove undefined fields from optionsCopy + Object.keys(optionsCopy).forEach(key => (typeof optionsCopy[key] === 'undefined') && delete optionsCopy[key]); + return optionsCopy; + } +} +exports.RemoteConfigApiClient = RemoteConfigApiClient; +const ERROR_CODE_MAPPING = { + ABORTED: 'aborted', + ALREADY_EXISTS: 'already-exists', + INVALID_ARGUMENT: 'invalid-argument', + INTERNAL: 'internal-error', + FAILED_PRECONDITION: 'failed-precondition', + NOT_FOUND: 'not-found', + OUT_OF_RANGE: 'out-of-range', + PERMISSION_DENIED: 'permission-denied', + RESOURCE_EXHAUSTED: 'resource-exhausted', + UNAUTHENTICATED: 'unauthenticated', + UNKNOWN: 'unknown-error', +}; +/** + * Firebase Remote Config error code structure. This extends PrefixedFirebaseError. + * + * @param {RemoteConfigErrorCode} code The error code. + * @param {string} message The error message. + * @constructor + */ +class FirebaseRemoteConfigError extends error_1.PrefixedFirebaseError { + constructor(code, message) { + super('remote-config', code, message); + } +} +exports.FirebaseRemoteConfigError = FirebaseRemoteConfigError; diff --git a/node_modules/firebase-admin/lib/remote-config/remote-config-api.d.ts b/node_modules/firebase-admin/lib/remote-config/remote-config-api.d.ts new file mode 100644 index 0000000..8f021b1 --- /dev/null +++ b/node_modules/firebase-admin/lib/remote-config/remote-config-api.d.ts @@ -0,0 +1,708 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Colors that are associated with conditions for display purposes. + */ +export type TagColor = 'BLUE' | 'BROWN' | 'CYAN' | 'DEEP_ORANGE' | 'GREEN' | 'INDIGO' | 'LIME' | 'ORANGE' | 'PINK' | 'PURPLE' | 'TEAL'; +/** + * Type representing a Remote Config parameter value data type. + * Defaults to `STRING` if unspecified. + */ +export type ParameterValueType = 'STRING' | 'BOOLEAN' | 'NUMBER' | 'JSON'; +/** + * Interface representing a Remote Config condition. + * A condition targets a specific group of users. A list of these conditions make up + * part of a Remote Config template. + */ +export interface RemoteConfigCondition { + /** + * A non-empty and unique name of this condition. + */ + name: string; + /** + * The logic of this condition. + * See the documentation on + * {@link https://firebase.google.com/docs/remote-config/condition-reference | condition expressions} + * for the expected syntax of this field. + */ + expression: string; + /** + * The color associated with this condition for display purposes in the Firebase Console. + * Not specifying this value results in the console picking an arbitrary color to associate + * with the condition. + */ + tagColor?: TagColor; +} +/** + * Represents a Remote Config condition in the dataplane. + * A condition targets a specific group of users. A list of these conditions + * comprise part of a Remote Config template. + */ +export interface NamedCondition { + /** + * A non-empty and unique name of this condition. + */ + name: string; + /** + * The logic of this condition. + * See the documentation on + * {@link https://firebase.google.com/docs/remote-config/condition-reference | condition expressions} + * for the expected syntax of this field. + */ + condition: OneOfCondition; +} +/** + * Represents a condition that may be one of several types. + * Only the first defined field will be processed. + */ +export interface OneOfCondition { + /** + * Makes this condition an OR condition. + */ + orCondition?: OrCondition; + /** + * Makes this condition an AND condition. + */ + andCondition?: AndCondition; + /** + * Makes this condition a constant true. + */ + true?: Record; + /** + * Makes this condition a constant false. + */ + false?: Record; + /** + * Makes this condition a percent condition. + */ + percent?: PercentCondition; + /** + * Makes this condition a custom signal condition. + */ + customSignal?: CustomSignalCondition; +} +/** + * Represents a collection of conditions that evaluate to true if all are true. + */ +export interface AndCondition { + /** + * The collection of conditions. + */ + conditions?: Array; +} +/** + * Represents a collection of conditions that evaluate to true if any are true. + */ +export interface OrCondition { + /** + * The collection of conditions. + */ + conditions?: Array; +} +/** + * Defines supported operators for percent conditions. + */ +export declare enum PercentConditionOperator { + /** + * A catchall error case. + */ + UNKNOWN = "UNKNOWN", + /** + * Target percentiles less than or equal to the target percent. + * A condition using this operator must specify microPercent. + */ + LESS_OR_EQUAL = "LESS_OR_EQUAL", + /** + * Target percentiles greater than the target percent. + * A condition using this operator must specify microPercent. + */ + GREATER_THAN = "GREATER_THAN", + /** + * Target percentiles within an interval defined by a lower bound and an + * upper bound. The lower bound is an exclusive (open) bound and the + * micro_percent_range_upper_bound is an inclusive (closed) bound. + * A condition using this operator must specify microPercentRange. + */ + BETWEEN = "BETWEEN" +} +/** + * Represents the limit of percentiles to target in micro-percents. + * The value must be in the range [0 and 100000000] + */ +export interface MicroPercentRange { + /** + * The lower limit of percentiles to target in micro-percents. + * The value must be in the range [0 and 100000000]. + */ + microPercentLowerBound?: number; + /** + * The upper limit of percentiles to target in micro-percents. + * The value must be in the range [0 and 100000000]. + */ + microPercentUpperBound?: number; +} +/** + * Represents a condition that compares the instance pseudo-random + * percentile to a given limit. + */ +export interface PercentCondition { + /** + * The choice of percent operator to determine how to compare targets + * to percent(s). + */ + percentOperator?: PercentConditionOperator; + /** + * The limit of percentiles to target in micro-percents when + * using the LESS_OR_EQUAL and GREATER_THAN operators. The value must + * be in the range [0 and 100000000]. + */ + microPercent?: number; + /** + * The seed used when evaluating the hash function to map an instance to + * a value in the hash space. This is a string which can have 0 - 32 + * characters and can contain ASCII characters [-_.0-9a-zA-Z].The string + * is case-sensitive. + */ + seed?: string; + /** + * The micro-percent interval to be used with the + * BETWEEN operator. + */ + microPercentRange?: MicroPercentRange; +} +/** + * Defines supported operators for custom signal conditions. + */ +export declare enum CustomSignalOperator { + /** + * A catchall error case. + */ + UNKNOWN = "UNKNOWN", + /** + * Matches a numeric value less than the target value. + */ + NUMERIC_LESS_THAN = "NUMERIC_LESS_THAN", + /** + * Matches a numeric value less than or equal to the target value. + */ + NUMERIC_LESS_EQUAL = "NUMERIC_LESS_EQUAL", + /** + * Matches a numeric value equal to the target value. + */ + NUMERIC_EQUAL = "NUMERIC_EQUAL", + /** + * Matches a numeric value not equal to the target value. + */ + NUMERIC_NOT_EQUAL = "NUMERIC_NOT_EQUAL", + /** + * Matches a numeric value greater than the target value. + */ + NUMERIC_GREATER_THAN = "NUMERIC_GREATER_THAN", + /** + * Matches a numeric value greater than or equal to the target value. + */ + NUMERIC_GREATER_EQUAL = "NUMERIC_GREATER_EQUAL", + /** + * Matches if at least one of the target values is a substring of the actual custom + * signal value (e.g. "abc" contains the string "a", "bc"). + */ + STRING_CONTAINS = "STRING_CONTAINS", + /** + * Matches if none of the target values is a substring of the actual custom signal value. + */ + STRING_DOES_NOT_CONTAIN = "STRING_DOES_NOT_CONTAIN", + /** + * Matches if the actual value exactly matches at least one of the target values. + */ + STRING_EXACTLY_MATCHES = "STRING_EXACTLY_MATCHES", + /** + * The target regular expression matches at least one of the actual values. + * The regex conforms to RE2 format. See https://github.com/google/re2/wiki/Syntax + */ + STRING_CONTAINS_REGEX = "STRING_CONTAINS_REGEX", + /** + * Matches if the actual version value is less than the target value. + */ + SEMANTIC_VERSION_LESS_THAN = "SEMANTIC_VERSION_LESS_THAN", + /** + * Matches if the actual version value is less than or equal to the target value. + */ + SEMANTIC_VERSION_LESS_EQUAL = "SEMANTIC_VERSION_LESS_EQUAL", + /** + * Matches if the actual version value is equal to the target value. + */ + SEMANTIC_VERSION_EQUAL = "SEMANTIC_VERSION_EQUAL", + /** + * Matches if the actual version value is not equal to the target value. + */ + SEMANTIC_VERSION_NOT_EQUAL = "SEMANTIC_VERSION_NOT_EQUAL", + /** + * Matches if the actual version value is greater than the target value. + */ + SEMANTIC_VERSION_GREATER_THAN = "SEMANTIC_VERSION_GREATER_THAN", + /** + * Matches if the actual version value is greater than or equal to the target value. + */ + SEMANTIC_VERSION_GREATER_EQUAL = "SEMANTIC_VERSION_GREATER_EQUAL" +} +/** + * Represents a condition that compares provided signals against a target value. + */ +export interface CustomSignalCondition { + /** + * The choice of custom signal operator to determine how to compare targets + * to value(s). + */ + customSignalOperator?: CustomSignalOperator; + /** + * The key of the signal set in the EvaluationContext + */ + customSignalKey?: string; + /** + * A list of at most 100 target custom signal values. For numeric operators, + * this will have exactly ONE target value. + */ + targetCustomSignalValues?: string[]; +} +/** + * Interface representing an explicit parameter value. + */ +export interface ExplicitParameterValue { + /** + * The `string` value that the parameter is set to. + */ + value: string; +} +/** + * Interface representing an in-app-default value. + */ +export interface InAppDefaultValue { + /** + * If `true`, the parameter is omitted from the parameter values returned to a client. + */ + useInAppDefault: boolean; +} +/** + * Type representing a Remote Config parameter value. + * A `RemoteConfigParameterValue` could be either an `ExplicitParameterValue` or + * an `InAppDefaultValue`. + */ +export type RemoteConfigParameterValue = ExplicitParameterValue | InAppDefaultValue; +/** + * Interface representing a Remote Config parameter. + * At minimum, a `defaultValue` or a `conditionalValues` entry must be present for the + * parameter to have any effect. + */ +export interface RemoteConfigParameter { + /** + * The value to set the parameter to, when none of the named conditions evaluate to `true`. + */ + defaultValue?: RemoteConfigParameterValue; + /** + * A `(condition name, value)` map. The condition name of the highest priority + * (the one listed first in the Remote Config template's conditions list) determines the value of + * this parameter. + */ + conditionalValues?: { + [key: string]: RemoteConfigParameterValue; + }; + /** + * A description for this parameter. Should not be over 100 characters and may contain any + * Unicode characters. + */ + description?: string; + /** + * The data type for all values of this parameter in the current version of the template. + * Defaults to `ParameterValueType.STRING` if unspecified. + */ + valueType?: ParameterValueType; +} +/** + * Interface representing a Remote Config parameter group. + * Grouping parameters is only for management purposes and does not affect client-side + * fetching of parameter values. + */ +export interface RemoteConfigParameterGroup { + /** + * A description for the group. Its length must be less than or equal to 256 characters. + * A description may contain any Unicode characters. + */ + description?: string; + /** + * Map of parameter keys to their optional default values and optional conditional values for + * parameters that belong to this group. A parameter only appears once per + * Remote Config template. An ungrouped parameter appears at the top level, whereas a + * parameter organized within a group appears within its group's map of parameters. + */ + parameters: { + [key: string]: RemoteConfigParameter; + }; +} +/** + * Represents a Remote Config client template. + */ +export interface RemoteConfigTemplate { + /** + * A list of conditions in descending order by priority. + */ + conditions: RemoteConfigCondition[]; + /** + * Map of parameter keys to their optional default values and optional conditional values. + */ + parameters: { + [key: string]: RemoteConfigParameter; + }; + /** + * Map of parameter group names to their parameter group objects. + * A group's name is mutable but must be unique among groups in the Remote Config template. + * The name is limited to 256 characters and intended to be human-readable. Any Unicode + * characters are allowed. + */ + parameterGroups: { + [key: string]: RemoteConfigParameterGroup; + }; + /** + * ETag of the current Remote Config template (readonly). + */ + readonly etag: string; + /** + * Version information for the current Remote Config template. + */ + version?: Version; +} +/** + * Represents the data in a Remote Config server template. + */ +export interface ServerTemplateData { + /** + * A list of conditions in descending order by priority. + */ + conditions: NamedCondition[]; + /** + * Map of parameter keys to their optional default values and optional conditional values. + */ + parameters: { + [key: string]: RemoteConfigParameter; + }; + /** + * Current Remote Config template ETag (read-only). + */ + readonly etag: string; + /** + * Version information for the current Remote Config template. + */ + version?: Version; +} +/** + * Represents optional arguments that can be used when instantiating {@link ServerTemplate}. + */ +export interface GetServerTemplateOptions { + /** + * Defines in-app default parameter values, so that your app behaves as + * intended before it connects to the Remote Config backend, and so that + * default values are available if none are set on the backend. + */ + defaultConfig?: DefaultConfig; +} +/** + * Represents the type of a Remote Config server template that can be set on + * {@link ServerTemplate}. This can either be a {@link ServerTemplateData} object + * or a template JSON string. + */ +export type ServerTemplateDataType = ServerTemplateData | string; +/** + * Represents optional arguments that can be used when instantiating + * {@link ServerTemplate} synchronously. + */ +export interface InitServerTemplateOptions extends GetServerTemplateOptions { + /** + * Enables integrations to use template data loaded independently. For + * example, customers can reduce initialization latency by pre-fetching and + * caching template data and then using this option to initialize the SDK with + * that data. + */ + template?: ServerTemplateDataType; +} +/** + * Represents a stateful abstraction for a Remote Config server template. + */ +export interface ServerTemplate { + /** + * Evaluates the current template to produce a {@link ServerConfig}. + */ + evaluate(context?: EvaluationContext): ServerConfig; + /** + * Fetches and caches the current active version of the + * project's {@link ServerTemplate}. + */ + load(): Promise; + /** + * Sets and caches a {@link ServerTemplateData} or a JSON string representing + * the server template + */ + set(template: ServerTemplateDataType): void; + /** + * Returns a JSON representation of {@link ServerTemplateData} + */ + toJSON(): ServerTemplateData; +} +/** + * Generic map of developer-defined signals used as evaluation input signals. + */ +export type UserProvidedSignals = { + [key: string]: string | number; +}; +/** + * Predefined template evaluation input signals. + */ +export type PredefinedSignals = { + /** + * Defines the identifier to use when splitting a group. For example, + * this is used by the percent condition. + */ + randomizationId?: string; +}; +/** + * Represents template evaluation input signals. + */ +export type EvaluationContext = UserProvidedSignals & PredefinedSignals; +/** + * Interface representing a Remote Config user. + */ +export interface RemoteConfigUser { + /** + * Email address. Output only. + */ + email: string; + /** + * Display name. Output only. + */ + name?: string; + /** + * Image URL. Output only. + */ + imageUrl?: string; +} +/** + * Interface representing a Remote Config template version. + * Output only, except for the version description. Contains metadata about a particular + * version of the Remote Config template. All fields are set at the time the specified Remote + * Config template is published. A version's description field may be specified in + * `publishTemplate` calls. + */ +export interface Version { + /** + * The version number of a Remote Config template. + */ + versionNumber?: string; + /** + * The timestamp of when this version of the Remote Config template was written to the + * Remote Config backend. + */ + updateTime?: string; + /** + * The origin of the template update action. + */ + updateOrigin?: ('REMOTE_CONFIG_UPDATE_ORIGIN_UNSPECIFIED' | 'CONSOLE' | 'REST_API' | 'ADMIN_SDK_NODE'); + /** + * The type of the template update action. + */ + updateType?: ('REMOTE_CONFIG_UPDATE_TYPE_UNSPECIFIED' | 'INCREMENTAL_UPDATE' | 'FORCED_UPDATE' | 'ROLLBACK'); + /** + * Aggregation of all metadata fields about the account that performed the update. + */ + updateUser?: RemoteConfigUser; + /** + * The user-provided description of the corresponding Remote Config template. + */ + description?: string; + /** + * The version number of the Remote Config template that has become the current version + * due to a rollback. Only present if this version is the result of a rollback. + */ + rollbackSource?: string; + /** + * Indicates whether this Remote Config template was published before version history was + * supported. + */ + isLegacy?: boolean; +} +/** + * Interface representing a list of Remote Config template versions. + */ +export interface ListVersionsResult { + /** + * A list of version metadata objects, sorted in reverse chronological order. + */ + versions: Version[]; + /** + * Token to retrieve the next page of results, or empty if there are no more results + * in the list. + */ + nextPageToken?: string; +} +/** + * Interface representing options for Remote Config list versions operation. + */ +export interface ListVersionsOptions { + /** + * The maximum number of items to return per page. + */ + pageSize?: number; + /** + * The `nextPageToken` value returned from a previous list versions request, if any. + */ + pageToken?: string; + /** + * Specifies the newest version number to include in the results. + * If specified, must be greater than zero. Defaults to the newest version. + */ + endVersionNumber?: string | number; + /** + * Specifies the earliest update time to include in the results. Any entries updated before this + * time are omitted. + */ + startTime?: Date | string; + /** + * Specifies the latest update time to include in the results. Any entries updated on or after + * this time are omitted. + */ + endTime?: Date | string; +} +/** + * Represents the configuration produced by evaluating a server template. + */ +export interface ServerConfig { + /** + * Gets the value for the given key as a boolean. + * + * Convenience method for calling serverConfig.getValue(key).asBoolean(). + * + * @param key - The name of the parameter. + * + * @returns The value for the given key as a boolean. + */ + getBoolean(key: string): boolean; + /** + * Gets the value for the given key as a number. + * + * Convenience method for calling serverConfig.getValue(key).asNumber(). + * + * @param key - The name of the parameter. + * + * @returns The value for the given key as a number. + */ + getNumber(key: string): number; + /** + * Gets the value for the given key as a string. + * Convenience method for calling serverConfig.getValue(key).asString(). + * + * @param key - The name of the parameter. + * + * @returns The value for the given key as a string. + */ + getString(key: string): string; + /** + * Gets the {@link Value} for the given key. + * + * Ensures application logic will always have a type-safe reference, + * even if the parameter is removed remotely. + * + * @param key - The name of the parameter. + * + * @returns The value for the given key. + */ + getValue(key: string): Value; + /** + * Returns all config values. + * + * @returns A map of all config keys to their values. + */ + getAll(): { + [key: string]: Value; + }; +} +/** + * JSON-serializable representation of evaluated config values. This can be consumed by + * Remote Config web client SDKs. + */ +export interface FetchResponseData { + /** + * The HTTP status, which is useful for differentiating success responses with data from + * those without. + * + * This use of 200 and 304 response codes is consistent with Remote Config's server + * implementation. + */ + status: number; + /** + * Defines the ETag response header value. Only defined for 200 and 304 responses. + * + * This is consistent with Remote Config's server eTag implementation. + */ + eTag?: string; + /** + * Defines the map of parameters returned as "entries" in the fetch response body. + */ + config?: { + [key: string]: string; + }; +} +/** + * Wraps a parameter value with metadata and type-safe getters. + * + * Type-safe getters insulate application logic from remote + * changes to parameter names and types. + */ +export interface Value { + /** + * Gets the value as a boolean. + * + * The following values (case insensitive) are interpreted as true: + * "1", "true", "t", "yes", "y", "on". Other values are interpreted as false. + */ + asBoolean(): boolean; + /** + * Gets the value as a number. Comparable to calling Number(value) || 0. + */ + asNumber(): number; + /** + * Gets the value as a string. + */ + asString(): string; + /** + * Gets the {@link ValueSource} for the given key. + */ + getSource(): ValueSource; +} +/** + * Indicates the source of a value. + * + *
                            + *
                          • "static" indicates the value was defined by a static constant.
                          • + *
                          • "default" indicates the value was defined by default config.
                          • + *
                          • "remote" indicates the value was defined by config produced by + * evaluating a template.
                          • + *
                          + */ +export type ValueSource = 'static' | 'default' | 'remote'; +/** + * Defines the format for in-app default parameter values. + */ +export type DefaultConfig = { + [key: string]: string | number | boolean; +}; diff --git a/node_modules/firebase-admin/lib/remote-config/remote-config-api.js b/node_modules/firebase-admin/lib/remote-config/remote-config-api.js new file mode 100644 index 0000000..39c29b3 --- /dev/null +++ b/node_modules/firebase-admin/lib/remote-config/remote-config-api.js @@ -0,0 +1,122 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CustomSignalOperator = exports.PercentConditionOperator = void 0; +/** + * Defines supported operators for percent conditions. + */ +var PercentConditionOperator; +(function (PercentConditionOperator) { + /** + * A catchall error case. + */ + PercentConditionOperator["UNKNOWN"] = "UNKNOWN"; + /** + * Target percentiles less than or equal to the target percent. + * A condition using this operator must specify microPercent. + */ + PercentConditionOperator["LESS_OR_EQUAL"] = "LESS_OR_EQUAL"; + /** + * Target percentiles greater than the target percent. + * A condition using this operator must specify microPercent. + */ + PercentConditionOperator["GREATER_THAN"] = "GREATER_THAN"; + /** + * Target percentiles within an interval defined by a lower bound and an + * upper bound. The lower bound is an exclusive (open) bound and the + * micro_percent_range_upper_bound is an inclusive (closed) bound. + * A condition using this operator must specify microPercentRange. + */ + PercentConditionOperator["BETWEEN"] = "BETWEEN"; +})(PercentConditionOperator || (exports.PercentConditionOperator = PercentConditionOperator = {})); +/** + * Defines supported operators for custom signal conditions. + */ +var CustomSignalOperator; +(function (CustomSignalOperator) { + /** + * A catchall error case. + */ + CustomSignalOperator["UNKNOWN"] = "UNKNOWN"; + /** + * Matches a numeric value less than the target value. + */ + CustomSignalOperator["NUMERIC_LESS_THAN"] = "NUMERIC_LESS_THAN"; + /** + * Matches a numeric value less than or equal to the target value. + */ + CustomSignalOperator["NUMERIC_LESS_EQUAL"] = "NUMERIC_LESS_EQUAL"; + /** + * Matches a numeric value equal to the target value. + */ + CustomSignalOperator["NUMERIC_EQUAL"] = "NUMERIC_EQUAL"; + /** + * Matches a numeric value not equal to the target value. + */ + CustomSignalOperator["NUMERIC_NOT_EQUAL"] = "NUMERIC_NOT_EQUAL"; + /** + * Matches a numeric value greater than the target value. + */ + CustomSignalOperator["NUMERIC_GREATER_THAN"] = "NUMERIC_GREATER_THAN"; + /** + * Matches a numeric value greater than or equal to the target value. + */ + CustomSignalOperator["NUMERIC_GREATER_EQUAL"] = "NUMERIC_GREATER_EQUAL"; + /** + * Matches if at least one of the target values is a substring of the actual custom + * signal value (e.g. "abc" contains the string "a", "bc"). + */ + CustomSignalOperator["STRING_CONTAINS"] = "STRING_CONTAINS"; + /** + * Matches if none of the target values is a substring of the actual custom signal value. + */ + CustomSignalOperator["STRING_DOES_NOT_CONTAIN"] = "STRING_DOES_NOT_CONTAIN"; + /** + * Matches if the actual value exactly matches at least one of the target values. + */ + CustomSignalOperator["STRING_EXACTLY_MATCHES"] = "STRING_EXACTLY_MATCHES"; + /** + * The target regular expression matches at least one of the actual values. + * The regex conforms to RE2 format. See https://github.com/google/re2/wiki/Syntax + */ + CustomSignalOperator["STRING_CONTAINS_REGEX"] = "STRING_CONTAINS_REGEX"; + /** + * Matches if the actual version value is less than the target value. + */ + CustomSignalOperator["SEMANTIC_VERSION_LESS_THAN"] = "SEMANTIC_VERSION_LESS_THAN"; + /** + * Matches if the actual version value is less than or equal to the target value. + */ + CustomSignalOperator["SEMANTIC_VERSION_LESS_EQUAL"] = "SEMANTIC_VERSION_LESS_EQUAL"; + /** + * Matches if the actual version value is equal to the target value. + */ + CustomSignalOperator["SEMANTIC_VERSION_EQUAL"] = "SEMANTIC_VERSION_EQUAL"; + /** + * Matches if the actual version value is not equal to the target value. + */ + CustomSignalOperator["SEMANTIC_VERSION_NOT_EQUAL"] = "SEMANTIC_VERSION_NOT_EQUAL"; + /** + * Matches if the actual version value is greater than the target value. + */ + CustomSignalOperator["SEMANTIC_VERSION_GREATER_THAN"] = "SEMANTIC_VERSION_GREATER_THAN"; + /** + * Matches if the actual version value is greater than or equal to the target value. + */ + CustomSignalOperator["SEMANTIC_VERSION_GREATER_EQUAL"] = "SEMANTIC_VERSION_GREATER_EQUAL"; +})(CustomSignalOperator || (exports.CustomSignalOperator = CustomSignalOperator = {})); diff --git a/node_modules/firebase-admin/lib/remote-config/remote-config-namespace.d.ts b/node_modules/firebase-admin/lib/remote-config/remote-config-namespace.d.ts new file mode 100644 index 0000000..4642749 --- /dev/null +++ b/node_modules/firebase-admin/lib/remote-config/remote-config-namespace.d.ts @@ -0,0 +1,105 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +import { ExplicitParameterValue as TExplicitParameterValue, InAppDefaultValue as TInAppDefaultValue, ListVersionsOptions as TListVersionsOptions, ListVersionsResult as TListVersionsResult, ParameterValueType as TParameterValueType, RemoteConfigCondition as TRemoteConfigCondition, RemoteConfigParameter as TRemoteConfigParameter, RemoteConfigParameterGroup as TRemoteConfigParameterGroup, RemoteConfigParameterValue as TRemoteConfigParameterValue, RemoteConfigTemplate as TRemoteConfigTemplate, RemoteConfigUser as TRemoteConfigUser, TagColor as TTagColor, Version as TVersion } from './remote-config-api'; +import { RemoteConfig as TRemoteConfig } from './remote-config'; +/** + * Gets the {@link firebase-admin.remote-config#RemoteConfig} service for the + * default app or a given app. + * + * `admin.remoteConfig()` can be called with no arguments to access the default + * app's `RemoteConfig` service or as `admin.remoteConfig(app)` to access the + * `RemoteConfig` service associated with a specific app. + * + * @example + * ```javascript + * // Get the `RemoteConfig` service for the default app + * var defaultRemoteConfig = admin.remoteConfig(); + * ``` + * + * @example + * ```javascript + * // Get the `RemoteConfig` service for a given app + * var otherRemoteConfig = admin.remoteConfig(otherApp); + * ``` + * + * @param app - Optional app for which to return the `RemoteConfig` service. + * If not provided, the default `RemoteConfig` service is returned. + * + * @returns The default `RemoteConfig` service if no + * app is provided, or the `RemoteConfig` service associated with the provided + * app. + */ +export declare function remoteConfig(app?: App): remoteConfig.RemoteConfig; +export declare namespace remoteConfig { + /** + * Type alias to {@link firebase-admin.remote-config#ExplicitParameterValue}. + */ + type ExplicitParameterValue = TExplicitParameterValue; + /** + * Type alias to {@link firebase-admin.remote-config#InAppDefaultValue}. + */ + type InAppDefaultValue = TInAppDefaultValue; + /** + * Type alias to {@link firebase-admin.remote-config#ListVersionsOptions}. + */ + type ListVersionsOptions = TListVersionsOptions; + /** + * Type alias to {@link firebase-admin.remote-config#ListVersionsResult}. + */ + type ListVersionsResult = TListVersionsResult; + /** + * Type alias to {@link firebase-admin.remote-config#ParameterValueType}. + */ + type ParameterValueType = TParameterValueType; + /** + * Type alias to {@link firebase-admin.remote-config#RemoteConfig}. + */ + type RemoteConfig = TRemoteConfig; + /** + * Type alias to {@link firebase-admin.remote-config#RemoteConfigCondition}. + */ + type RemoteConfigCondition = TRemoteConfigCondition; + /** + * Type alias to {@link firebase-admin.remote-config#RemoteConfigParameter}. + */ + type RemoteConfigParameter = TRemoteConfigParameter; + /** + * Type alias to {@link firebase-admin.remote-config#RemoteConfigParameterGroup}. + */ + type RemoteConfigParameterGroup = TRemoteConfigParameterGroup; + /** + * Type alias to {@link firebase-admin.remote-config#RemoteConfigParameterValue}. + */ + type RemoteConfigParameterValue = TRemoteConfigParameterValue; + /** + * Type alias to {@link firebase-admin.remote-config#RemoteConfigTemplate}. + */ + type RemoteConfigTemplate = TRemoteConfigTemplate; + /** + * Type alias to {@link firebase-admin.remote-config#RemoteConfigUser}. + */ + type RemoteConfigUser = TRemoteConfigUser; + /** + * Type alias to {@link firebase-admin.remote-config#TagColor}. + */ + type TagColor = TTagColor; + /** + * Type alias to {@link firebase-admin.remote-config#Version}. + */ + type Version = TVersion; +} diff --git a/node_modules/firebase-admin/lib/remote-config/remote-config-namespace.js b/node_modules/firebase-admin/lib/remote-config/remote-config-namespace.js new file mode 100644 index 0000000..a91b066 --- /dev/null +++ b/node_modules/firebase-admin/lib/remote-config/remote-config-namespace.js @@ -0,0 +1,18 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/firebase-admin/lib/remote-config/remote-config.d.ts b/node_modules/firebase-admin/lib/remote-config/remote-config.d.ts new file mode 100644 index 0000000..5a5ddd8 --- /dev/null +++ b/node_modules/firebase-admin/lib/remote-config/remote-config.d.ts @@ -0,0 +1,121 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +import { ListVersionsOptions, ListVersionsResult, ServerTemplate, RemoteConfigTemplate, ServerConfig, GetServerTemplateOptions, InitServerTemplateOptions, FetchResponseData } from './remote-config-api'; +/** + * The Firebase `RemoteConfig` service interface. + */ +export declare class RemoteConfig { + readonly app: App; + private readonly client; + /** + * Gets the current active version of the {@link RemoteConfigTemplate} of the project. + * + * @returns A promise that fulfills with a `RemoteConfigTemplate`. + */ + getTemplate(): Promise; + /** + * Gets the requested version of the {@link RemoteConfigTemplate} of the project. + * + * @param versionNumber - Version number of the Remote Config template to look up. + * + * @returns A promise that fulfills with a `RemoteConfigTemplate`. + */ + getTemplateAtVersion(versionNumber: number | string): Promise; + /** + * Validates a {@link RemoteConfigTemplate}. + * + * @param template - The Remote Config template to be validated. + * @returns A promise that fulfills with the validated `RemoteConfigTemplate`. + */ + validateTemplate(template: RemoteConfigTemplate): Promise; + /** + * Publishes a Remote Config template. + * + * @param template - The Remote Config template to be published. + * @param options - Optional options object when publishing a Remote Config template: + * - `force`: Setting this to `true` forces the Remote Config template to + * be updated and circumvent the ETag. This approach is not recommended + * because it risks causing the loss of updates to your Remote Config + * template if multiple clients are updating the Remote Config template. + * See {@link https://firebase.google.com/docs/remote-config/use-config-rest#etag_usage_and_forced_updates | + * ETag usage and forced updates}. + * + * @returns A Promise that fulfills with the published `RemoteConfigTemplate`. + */ + publishTemplate(template: RemoteConfigTemplate, options?: { + force: boolean; + }): Promise; + /** + * Rolls back a project's published Remote Config template to the specified version. + * A rollback is equivalent to getting a previously published Remote Config + * template and re-publishing it using a force update. + * + * @param versionNumber - The version number of the Remote Config template to roll back to. + * The specified version number must be lower than the current version number, and not have + * been deleted due to staleness. Only the last 300 versions are stored. + * All versions that correspond to non-active Remote Config templates (that is, all except the + * template that is being fetched by clients) are also deleted if they are more than 90 days old. + * @returns A promise that fulfills with the published `RemoteConfigTemplate`. + */ + rollback(versionNumber: number | string): Promise; + /** + * Gets a list of Remote Config template versions that have been published, sorted in reverse + * chronological order. Only the last 300 versions are stored. + * All versions that correspond to non-active Remote Config templates (i.e., all except the + * template that is being fetched by clients) are also deleted if they are older than 90 days. + * + * @param options - Optional options object for getting a list of versions. + * @returns A promise that fulfills with a `ListVersionsResult`. + */ + listVersions(options?: ListVersionsOptions): Promise; + /** + * Creates and returns a new Remote Config template from a JSON string. + * + * @param json - The JSON string to populate a Remote Config template. + * + * @returns A new template instance. + */ + createTemplateFromJSON(json: string): RemoteConfigTemplate; + /** + * Instantiates {@link ServerTemplate} and then fetches and caches the latest + * template version of the project. + */ + getServerTemplate(options?: GetServerTemplateOptions): Promise; + /** + * Synchronously instantiates {@link ServerTemplate}. + */ + initServerTemplate(options?: InitServerTemplateOptions): ServerTemplate; +} +/** + * Represents a fetch response that can be used to interact with RC's client SDK. + */ +export declare class RemoteConfigFetchResponse { + private response; + /** + * @param app - The app for this RemoteConfig service. + * @param serverConfig - The server config for which to generate a fetch response. + * @param requestEtag - A request eTag with which to compare the current response. + */ + constructor(app: App, serverConfig: ServerConfig, requestEtag?: string); + /** + * @returns JSON representation of the fetch response that can be consumed + * by the RC client SDK. + */ + toJSON(): FetchResponseData; + private processEtag; +} diff --git a/node_modules/firebase-admin/lib/remote-config/remote-config.js b/node_modules/firebase-admin/lib/remote-config/remote-config.js new file mode 100644 index 0000000..ec1e78b --- /dev/null +++ b/node_modules/firebase-admin/lib/remote-config/remote-config.js @@ -0,0 +1,529 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RemoteConfigFetchResponse = exports.RemoteConfig = void 0; +const utils = require("../utils/index"); +const validator = require("../utils/validator"); +const remote_config_api_client_internal_1 = require("./remote-config-api-client-internal"); +const condition_evaluator_internal_1 = require("./condition-evaluator-internal"); +const value_impl_1 = require("./internal/value-impl"); +/** + * The Firebase `RemoteConfig` service interface. + */ +class RemoteConfig { + /** + * @param app - The app for this RemoteConfig service. + * @constructor + * @internal + */ + constructor(app) { + this.app = app; + this.client = new remote_config_api_client_internal_1.RemoteConfigApiClient(app); + } + /** + * Gets the current active version of the {@link RemoteConfigTemplate} of the project. + * + * @returns A promise that fulfills with a `RemoteConfigTemplate`. + */ + getTemplate() { + return this.client.getTemplate() + .then((templateResponse) => { + return new RemoteConfigTemplateImpl(templateResponse); + }); + } + /** + * Gets the requested version of the {@link RemoteConfigTemplate} of the project. + * + * @param versionNumber - Version number of the Remote Config template to look up. + * + * @returns A promise that fulfills with a `RemoteConfigTemplate`. + */ + getTemplateAtVersion(versionNumber) { + return this.client.getTemplateAtVersion(versionNumber) + .then((templateResponse) => { + return new RemoteConfigTemplateImpl(templateResponse); + }); + } + /** + * Validates a {@link RemoteConfigTemplate}. + * + * @param template - The Remote Config template to be validated. + * @returns A promise that fulfills with the validated `RemoteConfigTemplate`. + */ + validateTemplate(template) { + return this.client.validateTemplate(template) + .then((templateResponse) => { + return new RemoteConfigTemplateImpl(templateResponse); + }); + } + /** + * Publishes a Remote Config template. + * + * @param template - The Remote Config template to be published. + * @param options - Optional options object when publishing a Remote Config template: + * - `force`: Setting this to `true` forces the Remote Config template to + * be updated and circumvent the ETag. This approach is not recommended + * because it risks causing the loss of updates to your Remote Config + * template if multiple clients are updating the Remote Config template. + * See {@link https://firebase.google.com/docs/remote-config/use-config-rest#etag_usage_and_forced_updates | + * ETag usage and forced updates}. + * + * @returns A Promise that fulfills with the published `RemoteConfigTemplate`. + */ + publishTemplate(template, options) { + return this.client.publishTemplate(template, options) + .then((templateResponse) => { + return new RemoteConfigTemplateImpl(templateResponse); + }); + } + /** + * Rolls back a project's published Remote Config template to the specified version. + * A rollback is equivalent to getting a previously published Remote Config + * template and re-publishing it using a force update. + * + * @param versionNumber - The version number of the Remote Config template to roll back to. + * The specified version number must be lower than the current version number, and not have + * been deleted due to staleness. Only the last 300 versions are stored. + * All versions that correspond to non-active Remote Config templates (that is, all except the + * template that is being fetched by clients) are also deleted if they are more than 90 days old. + * @returns A promise that fulfills with the published `RemoteConfigTemplate`. + */ + rollback(versionNumber) { + return this.client.rollback(versionNumber) + .then((templateResponse) => { + return new RemoteConfigTemplateImpl(templateResponse); + }); + } + /** + * Gets a list of Remote Config template versions that have been published, sorted in reverse + * chronological order. Only the last 300 versions are stored. + * All versions that correspond to non-active Remote Config templates (i.e., all except the + * template that is being fetched by clients) are also deleted if they are older than 90 days. + * + * @param options - Optional options object for getting a list of versions. + * @returns A promise that fulfills with a `ListVersionsResult`. + */ + listVersions(options) { + return this.client.listVersions(options) + .then((listVersionsResponse) => { + return { + versions: listVersionsResponse.versions?.map(version => new VersionImpl(version)) ?? [], + nextPageToken: listVersionsResponse.nextPageToken, + }; + }); + } + /** + * Creates and returns a new Remote Config template from a JSON string. + * + * @param json - The JSON string to populate a Remote Config template. + * + * @returns A new template instance. + */ + createTemplateFromJSON(json) { + if (!validator.isNonEmptyString(json)) { + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'JSON string must be a valid non-empty string'); + } + let template; + try { + template = JSON.parse(json); + } + catch (e) { + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', `Failed to parse the JSON string: ${json}. ` + e); + } + return new RemoteConfigTemplateImpl(template); + } + /** + * Instantiates {@link ServerTemplate} and then fetches and caches the latest + * template version of the project. + */ + async getServerTemplate(options) { + const template = this.initServerTemplate(options); + await template.load(); + return template; + } + /** + * Synchronously instantiates {@link ServerTemplate}. + */ + initServerTemplate(options) { + const template = new ServerTemplateImpl(this.client, new condition_evaluator_internal_1.ConditionEvaluator(), options?.defaultConfig); + if (options?.template) { + template.set(options?.template); + } + return template; + } +} +exports.RemoteConfig = RemoteConfig; +/** + * Remote Config template internal implementation. + */ +class RemoteConfigTemplateImpl { + constructor(config) { + if (!validator.isNonNullObject(config) || + !validator.isNonEmptyString(config.etag)) { + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', `Invalid Remote Config template: ${JSON.stringify(config)}`); + } + this.etagInternal = config.etag; + if (typeof config.parameters !== 'undefined') { + if (!validator.isNonNullObject(config.parameters)) { + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Remote Config parameters must be a non-null object'); + } + this.parameters = config.parameters; + } + else { + this.parameters = {}; + } + if (typeof config.parameterGroups !== 'undefined') { + if (!validator.isNonNullObject(config.parameterGroups)) { + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Remote Config parameter groups must be a non-null object'); + } + this.parameterGroups = config.parameterGroups; + } + else { + this.parameterGroups = {}; + } + if (typeof config.conditions !== 'undefined') { + if (!validator.isArray(config.conditions)) { + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Remote Config conditions must be an array'); + } + this.conditions = config.conditions; + } + else { + this.conditions = []; + } + if (typeof config.version !== 'undefined') { + this.version = new VersionImpl(config.version); + } + } + /** + * Gets the ETag of the template. + * + * @returns The ETag of the Remote Config template. + */ + get etag() { + return this.etagInternal; + } + /** + * Returns a JSON-serializable representation of this object. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON() { + return { + conditions: this.conditions, + parameters: this.parameters, + parameterGroups: this.parameterGroups, + etag: this.etag, + version: this.version, + }; + } +} +/** + * Remote Config dataplane template data implementation. + */ +class ServerTemplateImpl { + constructor(apiClient, conditionEvaluator, defaultConfig = {}) { + this.apiClient = apiClient; + this.conditionEvaluator = conditionEvaluator; + this.defaultConfig = defaultConfig; + this.stringifiedDefaultConfig = {}; + // RC stores all remote values as string, but it's more intuitive + // to declare default values with specific types, so this converts + // the external declaration to an internal string representation. + for (const key in defaultConfig) { + this.stringifiedDefaultConfig[key] = String(defaultConfig[key]); + } + } + /** + * Fetches and caches the current active version of the project's {@link ServerTemplate}. + */ + load() { + return this.apiClient.getServerTemplate() + .then((template) => { + this.cache = new ServerTemplateDataImpl(template); + }); + } + /** + * Parses a {@link ServerTemplateDataType} and caches it. + */ + set(template) { + let parsed; + if (validator.isString(template)) { + try { + parsed = JSON.parse(template); + } + catch (e) { + // Transforms JSON parse errors to Firebase error. + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', `Failed to parse the JSON string: ${template}. ` + e); + } + } + else { + parsed = template; + } + // Throws template parse errors. + this.cache = new ServerTemplateDataImpl(parsed); + } + /** + * Evaluates the current template in cache to produce a {@link ServerConfig}. + */ + evaluate(context = {}) { + if (!this.cache) { + // This is the only place we should throw during evaluation, since it's under the + // control of application logic. To preserve forward-compatibility, we should only + // return false in cases where the SDK is unsure how to evaluate the fetched template. + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('failed-precondition', 'No Remote Config Server template in cache. Call load() before calling evaluate().'); + } + const evaluatedConditions = this.conditionEvaluator.evaluateConditions(this.cache.conditions, context); + const configValues = {}; + // Initializes config Value objects with default values. + for (const key in this.stringifiedDefaultConfig) { + configValues[key] = new value_impl_1.ValueImpl('default', this.stringifiedDefaultConfig[key]); + } + // Overlays config Value objects derived by evaluating the template. + for (const [key, parameter] of Object.entries(this.cache.parameters)) { + const { conditionalValues, defaultValue } = parameter; + // Supports parameters with no conditional values. + const normalizedConditionalValues = conditionalValues || {}; + let parameterValueWrapper = undefined; + // Iterates in order over condition list. If there is a value associated + // with a condition, this checks if the condition is true. + for (const [conditionName, conditionEvaluation] of evaluatedConditions) { + if (normalizedConditionalValues[conditionName] && conditionEvaluation) { + parameterValueWrapper = normalizedConditionalValues[conditionName]; + break; + } + } + if (parameterValueWrapper && parameterValueWrapper.useInAppDefault) { + // TODO: add logging once we have a wrapped logger. + continue; + } + if (parameterValueWrapper) { + const parameterValue = parameterValueWrapper.value; + configValues[key] = new value_impl_1.ValueImpl('remote', parameterValue); + continue; + } + if (!defaultValue) { + // TODO: add logging once we have a wrapped logger. + continue; + } + if (defaultValue.useInAppDefault) { + // TODO: add logging once we have a wrapped logger. + continue; + } + const parameterDefaultValue = defaultValue.value; + configValues[key] = new value_impl_1.ValueImpl('remote', parameterDefaultValue); + } + return new ServerConfigImpl(configValues); + } + /** + * @returns JSON representation of the server template + */ + toJSON() { + return this.cache; + } +} +class ServerConfigImpl { + constructor(configValues) { + this.configValues = configValues; + } + getBoolean(key) { + return this.getValue(key).asBoolean(); + } + getNumber(key) { + return this.getValue(key).asNumber(); + } + getString(key) { + return this.getValue(key).asString(); + } + getValue(key) { + return this.configValues[key] || new value_impl_1.ValueImpl('static'); + } + getAll() { + return { ...this.configValues }; + } +} +/** + * Remote Config dataplane template data implementation. + */ +class ServerTemplateDataImpl { + constructor(template) { + if (!validator.isNonNullObject(template) || + !validator.isNonEmptyString(template.etag)) { + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', `Invalid Remote Config template: ${JSON.stringify(template)}`); + } + this.etag = template.etag; + if (typeof template.parameters !== 'undefined') { + if (!validator.isNonNullObject(template.parameters)) { + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Remote Config parameters must be a non-null object'); + } + this.parameters = template.parameters; + } + else { + this.parameters = {}; + } + if (typeof template.conditions !== 'undefined') { + if (!validator.isArray(template.conditions)) { + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Remote Config conditions must be an array'); + } + this.conditions = template.conditions; + } + else { + this.conditions = []; + } + if (typeof template.version !== 'undefined') { + this.version = new VersionImpl(template.version); + } + } +} +/** +* Remote Config Version internal implementation. +*/ +class VersionImpl { + constructor(version) { + if (!validator.isNonNullObject(version)) { + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', `Invalid Remote Config version instance: ${JSON.stringify(version)}`); + } + if (typeof version.versionNumber !== 'undefined') { + if (!validator.isNonEmptyString(version.versionNumber) && + !validator.isNumber(version.versionNumber)) { + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Version number must be a non-empty string in int64 format or a number'); + } + if (!Number.isInteger(Number(version.versionNumber))) { + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Version number must be an integer or a string in int64 format'); + } + this.versionNumber = version.versionNumber; + } + if (typeof version.updateOrigin !== 'undefined') { + if (!validator.isNonEmptyString(version.updateOrigin)) { + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Version update origin must be a non-empty string'); + } + this.updateOrigin = version.updateOrigin; + } + if (typeof version.updateType !== 'undefined') { + if (!validator.isNonEmptyString(version.updateType)) { + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Version update type must be a non-empty string'); + } + this.updateType = version.updateType; + } + if (typeof version.updateUser !== 'undefined') { + if (!validator.isNonNullObject(version.updateUser)) { + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Version update user must be a non-null object'); + } + this.updateUser = version.updateUser; + } + if (typeof version.description !== 'undefined') { + if (!validator.isNonEmptyString(version.description)) { + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Version description must be a non-empty string'); + } + this.description = version.description; + } + if (typeof version.rollbackSource !== 'undefined') { + if (!validator.isNonEmptyString(version.rollbackSource)) { + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Version rollback source must be a non-empty string'); + } + this.rollbackSource = version.rollbackSource; + } + if (typeof version.isLegacy !== 'undefined') { + if (!validator.isBoolean(version.isLegacy)) { + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Version.isLegacy must be a boolean'); + } + this.isLegacy = version.isLegacy; + } + // The backend API provides timestamps in ISO date strings. The Admin SDK exposes timestamps + // in UTC date strings. If a developer uses a previously obtained template with UTC timestamps + // we could still validate it below. + if (typeof version.updateTime !== 'undefined') { + if (!this.isValidTimestamp(version.updateTime)) { + throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Version update time must be a valid date string'); + } + this.updateTime = new Date(version.updateTime).toUTCString(); + } + } + /** + * @returns A JSON-serializable representation of this object. + */ + toJSON() { + return { + versionNumber: this.versionNumber, + updateOrigin: this.updateOrigin, + updateType: this.updateType, + updateUser: this.updateUser, + description: this.description, + rollbackSource: this.rollbackSource, + isLegacy: this.isLegacy, + updateTime: this.updateTime, + }; + } + isValidTimestamp(timestamp) { + // This validation fails for timestamps earlier than January 1, 1970 and considers strings + // such as "1.2" as valid timestamps. + return validator.isNonEmptyString(timestamp) && (new Date(timestamp)).getTime() > 0; + } +} +const HTTP_NOT_MODIFIED = 304; +const HTTP_OK = 200; +/** + * Represents a fetch response that can be used to interact with RC's client SDK. + */ +class RemoteConfigFetchResponse { + /** + * @param app - The app for this RemoteConfig service. + * @param serverConfig - The server config for which to generate a fetch response. + * @param requestEtag - A request eTag with which to compare the current response. + */ + constructor(app, serverConfig, requestEtag) { + const config = {}; + for (const [param, value] of Object.entries(serverConfig.getAll())) { + config[param] = value.asString(); + } + const currentEtag = this.processEtag(config, app); + if (currentEtag === requestEtag) { + this.response = { + status: HTTP_NOT_MODIFIED, + eTag: currentEtag, + }; + } + else { + this.response = { + status: HTTP_OK, + eTag: currentEtag, + config, + }; + } + } + /** + * @returns JSON representation of the fetch response that can be consumed + * by the RC client SDK. + */ + toJSON() { + return this.response; + } + processEtag(config, app) { + const configJson = JSON.stringify(config); + let hash = 0; + // Mimics Java's `String.hashCode()` which is used in RC's servers. + for (let i = 0; i < configJson.length; i++) { + const char = configJson.charCodeAt(i); + hash = (hash << 5) - hash + char; + hash |= 0; + } + const projectId = utils.getExplicitProjectId(app); + const parts = ['etag', projectId, 'firebase-server', 'fetch', hash]; + return parts.filter(a => !!a).join('-'); + } +} +exports.RemoteConfigFetchResponse = RemoteConfigFetchResponse; diff --git a/node_modules/firebase-admin/lib/security-rules/index.d.ts b/node_modules/firebase-admin/lib/security-rules/index.d.ts new file mode 100644 index 0000000..c1db832 --- /dev/null +++ b/node_modules/firebase-admin/lib/security-rules/index.d.ts @@ -0,0 +1,50 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Security Rules for Cloud Firestore and Cloud Storage. + * + * @packageDocumentation + */ +import { App } from '../app'; +import { SecurityRules } from './security-rules'; +export { RulesFile, Ruleset, RulesetMetadata, RulesetMetadataList, SecurityRules, } from './security-rules'; +/** + * Gets the {@link SecurityRules} service for the default app or a given app. + * + * `admin.securityRules()` can be called with no arguments to access the + * default app's `SecurityRules` service, or as `admin.securityRules(app)` to access + * the `SecurityRules` service associated with a specific app. + * + * @example + * ```javascript + * // Get the SecurityRules service for the default app + * const defaultSecurityRules = getSecurityRules(); + * ``` + * + * @example + * ```javascript + * // Get the SecurityRules service for a given app + * const otherSecurityRules = getSecurityRules(otherApp); + * ``` + * + * @param app - Optional app to return the `SecurityRules` service + * for. If not provided, the default `SecurityRules` service + * is returned. + * @returns The default `SecurityRules` service if no app is provided, or the + * `SecurityRules` service associated with the provided app. + */ +export declare function getSecurityRules(app?: App): SecurityRules; diff --git a/node_modules/firebase-admin/lib/security-rules/index.js b/node_modules/firebase-admin/lib/security-rules/index.js new file mode 100644 index 0000000..b4cfa5c --- /dev/null +++ b/node_modules/firebase-admin/lib/security-rules/index.js @@ -0,0 +1,63 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SecurityRules = exports.RulesetMetadataList = exports.Ruleset = void 0; +exports.getSecurityRules = getSecurityRules; +/** + * Security Rules for Cloud Firestore and Cloud Storage. + * + * @packageDocumentation + */ +const app_1 = require("../app"); +const security_rules_1 = require("./security-rules"); +var security_rules_2 = require("./security-rules"); +Object.defineProperty(exports, "Ruleset", { enumerable: true, get: function () { return security_rules_2.Ruleset; } }); +Object.defineProperty(exports, "RulesetMetadataList", { enumerable: true, get: function () { return security_rules_2.RulesetMetadataList; } }); +Object.defineProperty(exports, "SecurityRules", { enumerable: true, get: function () { return security_rules_2.SecurityRules; } }); +/** + * Gets the {@link SecurityRules} service for the default app or a given app. + * + * `admin.securityRules()` can be called with no arguments to access the + * default app's `SecurityRules` service, or as `admin.securityRules(app)` to access + * the `SecurityRules` service associated with a specific app. + * + * @example + * ```javascript + * // Get the SecurityRules service for the default app + * const defaultSecurityRules = getSecurityRules(); + * ``` + * + * @example + * ```javascript + * // Get the SecurityRules service for a given app + * const otherSecurityRules = getSecurityRules(otherApp); + * ``` + * + * @param app - Optional app to return the `SecurityRules` service + * for. If not provided, the default `SecurityRules` service + * is returned. + * @returns The default `SecurityRules` service if no app is provided, or the + * `SecurityRules` service associated with the provided app. + */ +function getSecurityRules(app) { + if (typeof app === 'undefined') { + app = (0, app_1.getApp)(); + } + const firebaseApp = app; + return firebaseApp.getOrInitService('securityRules', (app) => new security_rules_1.SecurityRules(app)); +} diff --git a/node_modules/firebase-admin/lib/security-rules/security-rules-api-client-internal.d.ts b/node_modules/firebase-admin/lib/security-rules/security-rules-api-client-internal.d.ts new file mode 100644 index 0000000..a41e400 --- /dev/null +++ b/node_modules/firebase-admin/lib/security-rules/security-rules-api-client-internal.d.ts @@ -0,0 +1,75 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +export interface Release { + readonly name: string; + readonly rulesetName: string; + readonly createTime?: string; + readonly updateTime?: string; +} +export interface RulesetContent { + readonly source: { + readonly files: Array<{ + name: string; + content: string; + }>; + }; +} +export interface RulesetResponse extends RulesetContent { + readonly name: string; + readonly createTime: string; +} +export interface ListRulesetsResponse { + readonly rulesets: Array<{ + name: string; + createTime: string; + }>; + readonly nextPageToken?: string; +} +/** + * Class that facilitates sending requests to the Firebase security rules backend API. + * + * @private + */ +export declare class SecurityRulesApiClient { + private readonly app; + private readonly httpClient; + private projectIdPrefix?; + constructor(app: App); + getRuleset(name: string): Promise; + createRuleset(ruleset: RulesetContent): Promise; + deleteRuleset(name: string): Promise; + listRulesets(pageSize?: number, pageToken?: string): Promise; + getRelease(name: string): Promise; + updateOrCreateRelease(name: string, rulesetName: string): Promise; + updateRelease(name: string, rulesetName: string): Promise; + createRelease(name: string, rulesetName: string): Promise; + private getUrl; + private getProjectIdPrefix; + /** + * Gets the specified resource from the rules API. Resource names must be the short names without project + * ID prefix (e.g. `rulesets/ruleset-name`). + * + * @param {string} name Full qualified name of the resource to get. + * @returns {Promise} A promise that fulfills with the resource. + */ + private getResource; + private getReleaseDescription; + private getRulesetName; + private sendRequest; + private toFirebaseError; +} diff --git a/node_modules/firebase-admin/lib/security-rules/security-rules-api-client-internal.js b/node_modules/firebase-admin/lib/security-rules/security-rules-api-client-internal.js new file mode 100644 index 0000000..77101a5 --- /dev/null +++ b/node_modules/firebase-admin/lib/security-rules/security-rules-api-client-internal.js @@ -0,0 +1,248 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SecurityRulesApiClient = void 0; +const api_request_1 = require("../utils/api-request"); +const error_1 = require("../utils/error"); +const security_rules_internal_1 = require("./security-rules-internal"); +const utils = require("../utils/index"); +const validator = require("../utils/validator"); +const RULES_V1_API = 'https://firebaserules.googleapis.com/v1'; +const FIREBASE_VERSION_HEADER = { + 'X-Firebase-Client': `fire-admin-node/${utils.getSdkVersion()}`, +}; +/** + * Class that facilitates sending requests to the Firebase security rules backend API. + * + * @private + */ +class SecurityRulesApiClient { + constructor(app) { + this.app = app; + if (!validator.isNonNullObject(app) || !('options' in app)) { + throw new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'First argument passed to admin.securityRules() must be a valid Firebase app ' + + 'instance.'); + } + this.httpClient = new api_request_1.AuthorizedHttpClient(app); + } + getRuleset(name) { + return Promise.resolve() + .then(() => { + return this.getRulesetName(name); + }) + .then((rulesetName) => { + return this.getResource(rulesetName); + }); + } + createRuleset(ruleset) { + if (!validator.isNonNullObject(ruleset) || + !validator.isNonNullObject(ruleset.source) || + !validator.isNonEmptyArray(ruleset.source.files)) { + const err = new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'Invalid rules content.'); + return Promise.reject(err); + } + for (const rf of ruleset.source.files) { + if (!validator.isNonNullObject(rf) || + !validator.isNonEmptyString(rf.name) || + !validator.isNonEmptyString(rf.content)) { + const err = new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', `Invalid rules file argument: ${JSON.stringify(rf)}`); + return Promise.reject(err); + } + } + return this.getUrl() + .then((url) => { + const request = { + method: 'POST', + url: `${url}/rulesets`, + data: ruleset, + }; + return this.sendRequest(request); + }); + } + deleteRuleset(name) { + return this.getUrl() + .then((url) => { + const rulesetName = this.getRulesetName(name); + const request = { + method: 'DELETE', + url: `${url}/${rulesetName}`, + }; + return this.sendRequest(request); + }); + } + listRulesets(pageSize = 100, pageToken) { + if (!validator.isNumber(pageSize)) { + const err = new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'Invalid page size.'); + return Promise.reject(err); + } + if (pageSize < 1 || pageSize > 100) { + const err = new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'Page size must be between 1 and 100.'); + return Promise.reject(err); + } + if (typeof pageToken !== 'undefined' && !validator.isNonEmptyString(pageToken)) { + const err = new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'Next page token must be a non-empty string.'); + return Promise.reject(err); + } + const data = { + pageSize, + pageToken, + }; + if (!pageToken) { + delete data.pageToken; + } + return this.getUrl() + .then((url) => { + const request = { + method: 'GET', + url: `${url}/rulesets`, + data, + }; + return this.sendRequest(request); + }); + } + getRelease(name) { + return this.getResource(`releases/${name}`); + } + updateOrCreateRelease(name, rulesetName) { + return this.updateRelease(name, rulesetName).catch((error) => { + // if ruleset update failed with a NOT_FOUND error, attempt to create instead. + if (error.code === `security-rules/${ERROR_CODE_MAPPING.NOT_FOUND}`) { + return this.createRelease(name, rulesetName); + } + throw error; + }); + } + updateRelease(name, rulesetName) { + return this.getUrl() + .then((url) => { + return this.getReleaseDescription(name, rulesetName) + .then((release) => { + const request = { + method: 'PATCH', + url: `${url}/releases/${name}`, + data: { release }, + }; + return this.sendRequest(request); + }); + }); + } + createRelease(name, rulesetName) { + return this.getUrl() + .then((url) => { + return this.getReleaseDescription(name, rulesetName) + .then((release) => { + const request = { + method: 'POST', + url: `${url}/releases`, + data: release, + }; + return this.sendRequest(request); + }); + }); + } + getUrl() { + return this.getProjectIdPrefix() + .then((projectIdPrefix) => { + return `${RULES_V1_API}/${projectIdPrefix}`; + }); + } + getProjectIdPrefix() { + if (this.projectIdPrefix) { + return Promise.resolve(this.projectIdPrefix); + } + return utils.findProjectId(this.app) + .then((projectId) => { + if (!validator.isNonEmptyString(projectId)) { + throw new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'Failed to determine project ID. Initialize the SDK with service account credentials, or ' + + 'set project ID as an app option. Alternatively, set the GOOGLE_CLOUD_PROJECT ' + + 'environment variable.'); + } + this.projectIdPrefix = `projects/${projectId}`; + return this.projectIdPrefix; + }); + } + /** + * Gets the specified resource from the rules API. Resource names must be the short names without project + * ID prefix (e.g. `rulesets/ruleset-name`). + * + * @param {string} name Full qualified name of the resource to get. + * @returns {Promise} A promise that fulfills with the resource. + */ + getResource(name) { + return this.getUrl() + .then((url) => { + const request = { + method: 'GET', + url: `${url}/${name}`, + }; + return this.sendRequest(request); + }); + } + getReleaseDescription(name, rulesetName) { + return this.getProjectIdPrefix() + .then((projectIdPrefix) => { + return { + name: `${projectIdPrefix}/releases/${name}`, + rulesetName: `${projectIdPrefix}/${this.getRulesetName(rulesetName)}`, + }; + }); + } + getRulesetName(name) { + if (!validator.isNonEmptyString(name)) { + throw new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'Ruleset name must be a non-empty string.'); + } + if (name.indexOf('/') !== -1) { + throw new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'Ruleset name must not contain any "/" characters.'); + } + return `rulesets/${name}`; + } + sendRequest(request) { + request.headers = FIREBASE_VERSION_HEADER; + return this.httpClient.send(request) + .then((resp) => { + return resp.data; + }) + .catch((err) => { + throw this.toFirebaseError(err); + }); + } + toFirebaseError(err) { + if (err instanceof error_1.PrefixedFirebaseError) { + return err; + } + const response = err.response; + if (!response.isJson()) { + return new security_rules_internal_1.FirebaseSecurityRulesError('unknown-error', `Unexpected response with status: ${response.status} and body: ${response.text}`); + } + const error = response.data.error || {}; + let code = 'unknown-error'; + if (error.status && error.status in ERROR_CODE_MAPPING) { + code = ERROR_CODE_MAPPING[error.status]; + } + const message = error.message || `Unknown server error: ${response.text}`; + return new security_rules_internal_1.FirebaseSecurityRulesError(code, message); + } +} +exports.SecurityRulesApiClient = SecurityRulesApiClient; +const ERROR_CODE_MAPPING = { + INVALID_ARGUMENT: 'invalid-argument', + NOT_FOUND: 'not-found', + RESOURCE_EXHAUSTED: 'resource-exhausted', + UNAUTHENTICATED: 'authentication-error', + UNKNOWN: 'unknown-error', +}; diff --git a/node_modules/firebase-admin/lib/security-rules/security-rules-internal.d.ts b/node_modules/firebase-admin/lib/security-rules/security-rules-internal.d.ts new file mode 100644 index 0000000..5b8806b --- /dev/null +++ b/node_modules/firebase-admin/lib/security-rules/security-rules-internal.d.ts @@ -0,0 +1,21 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { PrefixedFirebaseError } from '../utils/error'; +export type SecurityRulesErrorCode = 'already-exists' | 'authentication-error' | 'internal-error' | 'invalid-argument' | 'invalid-server-response' | 'not-found' | 'resource-exhausted' | 'service-unavailable' | 'unknown-error'; +export declare class FirebaseSecurityRulesError extends PrefixedFirebaseError { + constructor(code: SecurityRulesErrorCode, message: string); +} diff --git a/node_modules/firebase-admin/lib/security-rules/security-rules-internal.js b/node_modules/firebase-admin/lib/security-rules/security-rules-internal.js new file mode 100644 index 0000000..e8a69c5 --- /dev/null +++ b/node_modules/firebase-admin/lib/security-rules/security-rules-internal.js @@ -0,0 +1,26 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FirebaseSecurityRulesError = void 0; +const error_1 = require("../utils/error"); +class FirebaseSecurityRulesError extends error_1.PrefixedFirebaseError { + constructor(code, message) { + super('security-rules', code, message); + } +} +exports.FirebaseSecurityRulesError = FirebaseSecurityRulesError; diff --git a/node_modules/firebase-admin/lib/security-rules/security-rules-namespace.d.ts b/node_modules/firebase-admin/lib/security-rules/security-rules-namespace.d.ts new file mode 100644 index 0000000..7d96dd9 --- /dev/null +++ b/node_modules/firebase-admin/lib/security-rules/security-rules-namespace.d.ts @@ -0,0 +1,69 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +import { RulesFile as TRulesFile, Ruleset as TRuleset, RulesetMetadata as TRulesetMetadata, RulesetMetadataList as TRulesetMetadataList, SecurityRules as TSecurityRules } from './security-rules'; +/** + * Gets the {@link firebase-admin.security-rules#SecurityRules} service for the default + * app or a given app. + * + * `admin.securityRules()` can be called with no arguments to access the + * default app's {@link firebase-admin.security-rules#SecurityRules} + * service, or as `admin.securityRules(app)` to access + * the {@link firebase-admin.security-rules#SecurityRules} + * service associated with a specific app. + * + * @example + * ```javascript + * // Get the SecurityRules service for the default app + * var defaultSecurityRules = admin.securityRules(); + * ``` + * + * @example + * ```javascript + * // Get the SecurityRules service for a given app + * var otherSecurityRules = admin.securityRules(otherApp); + * ``` + * + * @param app - Optional app to return the `SecurityRules` service + * for. If not provided, the default `SecurityRules` service + * is returned. + * @returns The default `SecurityRules` service if no app is provided, or the + * `SecurityRules` service associated with the provided app. + */ +export declare function securityRules(app?: App): securityRules.SecurityRules; +export declare namespace securityRules { + /** + * Type alias to {@link firebase-admin.security-rules#RulesFile}. + */ + type RulesFile = TRulesFile; + /** + * Type alias to {@link firebase-admin.security-rules#Ruleset}. + */ + type Ruleset = TRuleset; + /** + * Type alias to {@link firebase-admin.security-rules#RulesetMetadata}. + */ + type RulesetMetadata = TRulesetMetadata; + /** + * Type alias to {@link firebase-admin.security-rules#RulesetMetadataList}. + */ + type RulesetMetadataList = TRulesetMetadataList; + /** + * Type alias to {@link firebase-admin.security-rules#SecurityRules}. + */ + type SecurityRules = TSecurityRules; +} diff --git a/node_modules/firebase-admin/lib/security-rules/security-rules-namespace.js b/node_modules/firebase-admin/lib/security-rules/security-rules-namespace.js new file mode 100644 index 0000000..a91b066 --- /dev/null +++ b/node_modules/firebase-admin/lib/security-rules/security-rules-namespace.js @@ -0,0 +1,18 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/firebase-admin/lib/security-rules/security-rules.d.ts b/node_modules/firebase-admin/lib/security-rules/security-rules.d.ts new file mode 100644 index 0000000..a095247 --- /dev/null +++ b/node_modules/firebase-admin/lib/security-rules/security-rules.d.ts @@ -0,0 +1,195 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +/** + * A source file containing some Firebase security rules. The content includes raw + * source code including text formatting, indentation and comments. Use the + * {@link SecurityRules.createRulesFileFromSource} method to create new instances of this type. + */ +export interface RulesFile { + readonly name: string; + readonly content: string; +} +/** + * Required metadata associated with a ruleset. + */ +export interface RulesetMetadata { + /** + * Name of the `Ruleset` as a short string. This can be directly passed into APIs + * like {@link SecurityRules.getRuleset} and {@link SecurityRules.deleteRuleset}. + */ + readonly name: string; + /** + * Creation time of the `Ruleset` as a UTC timestamp string. + */ + readonly createTime: string; +} +/** + * A page of ruleset metadata. + */ +export declare class RulesetMetadataList { + /** + * A batch of ruleset metadata. + */ + readonly rulesets: RulesetMetadata[]; + /** + * The next page token if available. This is needed to retrieve the next batch. + */ + readonly nextPageToken?: string; +} +/** + * A set of Firebase security rules. + */ +export declare class Ruleset implements RulesetMetadata { + /** + * {@inheritdoc RulesetMetadata.name} + */ + readonly name: string; + /** + * {@inheritdoc RulesetMetadata.createTime} + */ + readonly createTime: string; + readonly source: RulesFile[]; +} +/** + * The Firebase `SecurityRules` service interface. + */ +export declare class SecurityRules { + readonly app: App; + private static readonly CLOUD_FIRESTORE; + private static readonly FIREBASE_STORAGE; + private readonly client; + /** + * Gets the {@link Ruleset} identified by the given + * name. The input name should be the short name string without the project ID + * prefix. For example, to retrieve the `projects/project-id/rulesets/my-ruleset`, + * pass the short name "my-ruleset". Rejects with a `not-found` error if the + * specified `Ruleset` cannot be found. + * + * @param name - Name of the `Ruleset` to retrieve. + * @returns A promise that fulfills with the specified `Ruleset`. + */ + getRuleset(name: string): Promise; + /** + * Gets the {@link Ruleset} currently applied to + * Cloud Firestore. Rejects with a `not-found` error if no ruleset is applied + * on Firestore. + * + * @returns A promise that fulfills with the Firestore ruleset. + */ + getFirestoreRuleset(): Promise; + /** + * Creates a new {@link Ruleset} from the given + * source, and applies it to Cloud Firestore. + * + * @param source - Rules source to apply. + * @returns A promise that fulfills when the ruleset is created and released. + */ + releaseFirestoreRulesetFromSource(source: string | Buffer): Promise; + /** + * Applies the specified {@link Ruleset} ruleset + * to Cloud Firestore. + * + * @param ruleset - Name of the ruleset to apply or a `RulesetMetadata` object + * containing the name. + * @returns A promise that fulfills when the ruleset is released. + */ + releaseFirestoreRuleset(ruleset: string | RulesetMetadata): Promise; + /** + * Gets the {@link Ruleset} currently applied to a + * Cloud Storage bucket. Rejects with a `not-found` error if no ruleset is applied + * on the bucket. + * + * @param bucket - Optional name of the Cloud Storage bucket to be retrieved. If not + * specified, retrieves the ruleset applied on the default bucket configured via + * `AppOptions`. + * @returns A promise that fulfills with the Cloud Storage ruleset. + */ + getStorageRuleset(bucket?: string): Promise; + /** + * Creates a new {@link Ruleset} from the given + * source, and applies it to a Cloud Storage bucket. + * + * @param source - Rules source to apply. + * @param bucket - Optional name of the Cloud Storage bucket to apply the rules on. If + * not specified, applies the ruleset on the default bucket configured via + * {@link firebase-admin.app#AppOptions}. + * @returns A promise that fulfills when the ruleset is created and released. + */ + releaseStorageRulesetFromSource(source: string | Buffer, bucket?: string): Promise; + /** + * Applies the specified {@link Ruleset} ruleset + * to a Cloud Storage bucket. + * + * @param ruleset - Name of the ruleset to apply or a `RulesetMetadata` object + * containing the name. + * @param bucket - Optional name of the Cloud Storage bucket to apply the rules on. If + * not specified, applies the ruleset on the default bucket configured via + * {@link firebase-admin.app#AppOptions}. + * @returns A promise that fulfills when the ruleset is released. + */ + releaseStorageRuleset(ruleset: string | RulesetMetadata, bucket?: string): Promise; + /** + * Creates a {@link RulesFile} with the given name + * and source. Throws an error if any of the arguments are invalid. This is a local + * operation, and does not involve any network API calls. + * + * @example + * ```javascript + * const source = '// Some rules source'; + * const rulesFile = admin.securityRules().createRulesFileFromSource( + * 'firestore.rules', source); + * ``` + * + * @param name - Name to assign to the rules file. This is usually a short file name that + * helps identify the file in a ruleset. + * @param source - Contents of the rules file. + * @returns A new rules file instance. + */ + createRulesFileFromSource(name: string, source: string | Buffer): RulesFile; + /** + * Creates a new {@link Ruleset} from the given {@link RulesFile}. + * + * @param file - Rules file to include in the new `Ruleset`. + * @returns A promise that fulfills with the newly created `Ruleset`. + */ + createRuleset(file: RulesFile): Promise; + /** + * Deletes the {@link Ruleset} identified by the given + * name. The input name should be the short name string without the project ID + * prefix. For example, to delete the `projects/project-id/rulesets/my-ruleset`, + * pass the short name "my-ruleset". Rejects with a `not-found` error if the + * specified `Ruleset` cannot be found. + * + * @param name - Name of the `Ruleset` to delete. + * @returns A promise that fulfills when the `Ruleset` is deleted. + */ + deleteRuleset(name: string): Promise; + /** + * Retrieves a page of ruleset metadata. + * + * @param pageSize - The page size, 100 if undefined. This is also the maximum allowed + * limit. + * @param nextPageToken - The next page token. If not specified, returns rulesets + * starting without any offset. + * @returns A promise that fulfills with a page of rulesets. + */ + listRulesetMetadata(pageSize?: number, nextPageToken?: string): Promise; + private getRulesetForRelease; + private releaseRuleset; + private getBucketName; +} diff --git a/node_modules/firebase-admin/lib/security-rules/security-rules.js b/node_modules/firebase-admin/lib/security-rules/security-rules.js new file mode 100644 index 0000000..ecd9552 --- /dev/null +++ b/node_modules/firebase-admin/lib/security-rules/security-rules.js @@ -0,0 +1,319 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SecurityRules = exports.Ruleset = exports.RulesetMetadataList = void 0; +const validator = require("../utils/validator"); +const security_rules_api_client_internal_1 = require("./security-rules-api-client-internal"); +const security_rules_internal_1 = require("./security-rules-internal"); +/** + * A page of ruleset metadata. + */ +class RulesetMetadataList { + /** + * @internal + */ + constructor(response) { + if (!validator.isNonNullObject(response) || !validator.isArray(response.rulesets)) { + throw new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', `Invalid ListRulesets response: ${JSON.stringify(response)}`); + } + this.rulesets = response.rulesets.map((rs) => { + return { + name: stripProjectIdPrefix(rs.name), + createTime: new Date(rs.createTime).toUTCString(), + }; + }); + if (response.nextPageToken) { + this.nextPageToken = response.nextPageToken; + } + } +} +exports.RulesetMetadataList = RulesetMetadataList; +/** + * A set of Firebase security rules. + */ +class Ruleset { + /** + * @internal + */ + constructor(ruleset) { + if (!validator.isNonNullObject(ruleset) || + !validator.isNonEmptyString(ruleset.name) || + !validator.isNonEmptyString(ruleset.createTime) || + !validator.isNonNullObject(ruleset.source)) { + throw new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', `Invalid Ruleset response: ${JSON.stringify(ruleset)}`); + } + this.name = stripProjectIdPrefix(ruleset.name); + this.createTime = new Date(ruleset.createTime).toUTCString(); + this.source = ruleset.source.files || []; + } +} +exports.Ruleset = Ruleset; +/** + * The Firebase `SecurityRules` service interface. + */ +class SecurityRules { + /** + * @param app - The app for this SecurityRules service. + * @constructor + * @internal + */ + constructor(app) { + this.app = app; + this.client = new security_rules_api_client_internal_1.SecurityRulesApiClient(app); + } + /** + * Gets the {@link Ruleset} identified by the given + * name. The input name should be the short name string without the project ID + * prefix. For example, to retrieve the `projects/project-id/rulesets/my-ruleset`, + * pass the short name "my-ruleset". Rejects with a `not-found` error if the + * specified `Ruleset` cannot be found. + * + * @param name - Name of the `Ruleset` to retrieve. + * @returns A promise that fulfills with the specified `Ruleset`. + */ + getRuleset(name) { + return this.client.getRuleset(name) + .then((rulesetResponse) => { + return new Ruleset(rulesetResponse); + }); + } + /** + * Gets the {@link Ruleset} currently applied to + * Cloud Firestore. Rejects with a `not-found` error if no ruleset is applied + * on Firestore. + * + * @returns A promise that fulfills with the Firestore ruleset. + */ + getFirestoreRuleset() { + return this.getRulesetForRelease(SecurityRules.CLOUD_FIRESTORE); + } + /** + * Creates a new {@link Ruleset} from the given + * source, and applies it to Cloud Firestore. + * + * @param source - Rules source to apply. + * @returns A promise that fulfills when the ruleset is created and released. + */ + releaseFirestoreRulesetFromSource(source) { + return Promise.resolve() + .then(() => { + const rulesFile = this.createRulesFileFromSource('firestore.rules', source); + return this.createRuleset(rulesFile); + }) + .then((ruleset) => { + return this.releaseFirestoreRuleset(ruleset) + .then(() => { + return ruleset; + }); + }); + } + /** + * Applies the specified {@link Ruleset} ruleset + * to Cloud Firestore. + * + * @param ruleset - Name of the ruleset to apply or a `RulesetMetadata` object + * containing the name. + * @returns A promise that fulfills when the ruleset is released. + */ + releaseFirestoreRuleset(ruleset) { + return this.releaseRuleset(ruleset, SecurityRules.CLOUD_FIRESTORE); + } + /** + * Gets the {@link Ruleset} currently applied to a + * Cloud Storage bucket. Rejects with a `not-found` error if no ruleset is applied + * on the bucket. + * + * @param bucket - Optional name of the Cloud Storage bucket to be retrieved. If not + * specified, retrieves the ruleset applied on the default bucket configured via + * `AppOptions`. + * @returns A promise that fulfills with the Cloud Storage ruleset. + */ + getStorageRuleset(bucket) { + return Promise.resolve() + .then(() => { + return this.getBucketName(bucket); + }) + .then((bucketName) => { + return this.getRulesetForRelease(`${SecurityRules.FIREBASE_STORAGE}/${bucketName}`); + }); + } + /** + * Creates a new {@link Ruleset} from the given + * source, and applies it to a Cloud Storage bucket. + * + * @param source - Rules source to apply. + * @param bucket - Optional name of the Cloud Storage bucket to apply the rules on. If + * not specified, applies the ruleset on the default bucket configured via + * {@link firebase-admin.app#AppOptions}. + * @returns A promise that fulfills when the ruleset is created and released. + */ + releaseStorageRulesetFromSource(source, bucket) { + return Promise.resolve() + .then(() => { + // Bucket name is not required until the last step. But since there's a createRuleset step + // before then, make sure to run this check and fail early if the bucket name is invalid. + this.getBucketName(bucket); + const rulesFile = this.createRulesFileFromSource('storage.rules', source); + return this.createRuleset(rulesFile); + }) + .then((ruleset) => { + return this.releaseStorageRuleset(ruleset, bucket) + .then(() => { + return ruleset; + }); + }); + } + /** + * Applies the specified {@link Ruleset} ruleset + * to a Cloud Storage bucket. + * + * @param ruleset - Name of the ruleset to apply or a `RulesetMetadata` object + * containing the name. + * @param bucket - Optional name of the Cloud Storage bucket to apply the rules on. If + * not specified, applies the ruleset on the default bucket configured via + * {@link firebase-admin.app#AppOptions}. + * @returns A promise that fulfills when the ruleset is released. + */ + releaseStorageRuleset(ruleset, bucket) { + return Promise.resolve() + .then(() => { + return this.getBucketName(bucket); + }) + .then((bucketName) => { + return this.releaseRuleset(ruleset, `${SecurityRules.FIREBASE_STORAGE}/${bucketName}`); + }); + } + /** + * Creates a {@link RulesFile} with the given name + * and source. Throws an error if any of the arguments are invalid. This is a local + * operation, and does not involve any network API calls. + * + * @example + * ```javascript + * const source = '// Some rules source'; + * const rulesFile = admin.securityRules().createRulesFileFromSource( + * 'firestore.rules', source); + * ``` + * + * @param name - Name to assign to the rules file. This is usually a short file name that + * helps identify the file in a ruleset. + * @param source - Contents of the rules file. + * @returns A new rules file instance. + */ + createRulesFileFromSource(name, source) { + if (!validator.isNonEmptyString(name)) { + throw new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'Name must be a non-empty string.'); + } + let content; + if (validator.isNonEmptyString(source)) { + content = source; + } + else if (validator.isBuffer(source)) { + content = source.toString('utf-8'); + } + else { + throw new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'Source must be a non-empty string or a Buffer.'); + } + return { + name, + content, + }; + } + /** + * Creates a new {@link Ruleset} from the given {@link RulesFile}. + * + * @param file - Rules file to include in the new `Ruleset`. + * @returns A promise that fulfills with the newly created `Ruleset`. + */ + createRuleset(file) { + const ruleset = { + source: { + files: [file], + }, + }; + return this.client.createRuleset(ruleset) + .then((rulesetResponse) => { + return new Ruleset(rulesetResponse); + }); + } + /** + * Deletes the {@link Ruleset} identified by the given + * name. The input name should be the short name string without the project ID + * prefix. For example, to delete the `projects/project-id/rulesets/my-ruleset`, + * pass the short name "my-ruleset". Rejects with a `not-found` error if the + * specified `Ruleset` cannot be found. + * + * @param name - Name of the `Ruleset` to delete. + * @returns A promise that fulfills when the `Ruleset` is deleted. + */ + deleteRuleset(name) { + return this.client.deleteRuleset(name); + } + /** + * Retrieves a page of ruleset metadata. + * + * @param pageSize - The page size, 100 if undefined. This is also the maximum allowed + * limit. + * @param nextPageToken - The next page token. If not specified, returns rulesets + * starting without any offset. + * @returns A promise that fulfills with a page of rulesets. + */ + listRulesetMetadata(pageSize = 100, nextPageToken) { + return this.client.listRulesets(pageSize, nextPageToken) + .then((response) => { + return new RulesetMetadataList(response); + }); + } + getRulesetForRelease(releaseName) { + return this.client.getRelease(releaseName) + .then((release) => { + const rulesetName = release.rulesetName; + if (!validator.isNonEmptyString(rulesetName)) { + throw new security_rules_internal_1.FirebaseSecurityRulesError('not-found', `Ruleset name not found for ${releaseName}.`); + } + return this.getRuleset(stripProjectIdPrefix(rulesetName)); + }); + } + releaseRuleset(ruleset, releaseName) { + if (!validator.isNonEmptyString(ruleset) && + (!validator.isNonNullObject(ruleset) || !validator.isNonEmptyString(ruleset.name))) { + const err = new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'ruleset must be a non-empty name or a RulesetMetadata object.'); + return Promise.reject(err); + } + const rulesetName = validator.isString(ruleset) ? ruleset : ruleset.name; + return this.client.updateOrCreateRelease(releaseName, rulesetName) + .then(() => { + return; + }); + } + getBucketName(bucket) { + const bucketName = (typeof bucket !== 'undefined') ? bucket : this.app.options.storageBucket; + if (!validator.isNonEmptyString(bucketName)) { + throw new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'Bucket name not specified or invalid. Specify a default bucket name via the ' + + 'storageBucket option when initializing the app, or specify the bucket name ' + + 'explicitly when calling the rules API.'); + } + return bucketName; + } +} +exports.SecurityRules = SecurityRules; +SecurityRules.CLOUD_FIRESTORE = 'cloud.firestore'; +SecurityRules.FIREBASE_STORAGE = 'firebase.storage'; +function stripProjectIdPrefix(name) { + return name.split('/').pop(); +} diff --git a/node_modules/firebase-admin/lib/storage/index.d.ts b/node_modules/firebase-admin/lib/storage/index.d.ts new file mode 100644 index 0000000..d14b344 --- /dev/null +++ b/node_modules/firebase-admin/lib/storage/index.d.ts @@ -0,0 +1,57 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Cloud Storage for Firebase. + * + * @packageDocumentation + */ +import { File } from '@google-cloud/storage'; +import { App } from '../app'; +import { Storage } from './storage'; +export { Storage } from './storage'; +/** + * Gets the {@link Storage} service for the default app or a given app. + * + * `getStorage()` can be called with no arguments to access the default + * app's `Storage` service or as `getStorage(app)` to access the + * `Storage` service associated with a specific app. + * + * @example + * ```javascript + * // Get the Storage service for the default app + * const defaultStorage = getStorage(); + * ``` + * + * @example + * ```javascript + * // Get the Storage service for a given app + * const otherStorage = getStorage(otherApp); + * ``` + */ +export declare function getStorage(app?: App): Storage; +/** + * Gets the download URL for the given {@link https://cloud.google.com/nodejs/docs/reference/storage/latest/storage/file | File}. + * + * @example + * ```javascript + * // Get the downloadUrl for a given file ref + * const storage = getStorage(); + * const myRef = ref(storage, 'images/mountains.jpg'); + * const downloadUrl = await getDownloadURL(myRef); + * ``` + */ +export declare function getDownloadURL(file: File): Promise; diff --git a/node_modules/firebase-admin/lib/storage/index.js b/node_modules/firebase-admin/lib/storage/index.js new file mode 100644 index 0000000..04e4949 --- /dev/null +++ b/node_modules/firebase-admin/lib/storage/index.js @@ -0,0 +1,77 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Storage = void 0; +exports.getStorage = getStorage; +exports.getDownloadURL = getDownloadURL; +const app_1 = require("../app"); +const storage_1 = require("./storage"); +const error_1 = require("../utils/error"); +const utils_1 = require("./utils"); +var storage_2 = require("./storage"); +Object.defineProperty(exports, "Storage", { enumerable: true, get: function () { return storage_2.Storage; } }); +/** + * Gets the {@link Storage} service for the default app or a given app. + * + * `getStorage()` can be called with no arguments to access the default + * app's `Storage` service or as `getStorage(app)` to access the + * `Storage` service associated with a specific app. + * + * @example + * ```javascript + * // Get the Storage service for the default app + * const defaultStorage = getStorage(); + * ``` + * + * @example + * ```javascript + * // Get the Storage service for a given app + * const otherStorage = getStorage(otherApp); + * ``` + */ +function getStorage(app) { + if (typeof app === 'undefined') { + app = (0, app_1.getApp)(); + } + const firebaseApp = app; + return firebaseApp.getOrInitService('storage', (app) => new storage_1.Storage(app)); +} +/** + * Gets the download URL for the given {@link https://cloud.google.com/nodejs/docs/reference/storage/latest/storage/file | File}. + * + * @example + * ```javascript + * // Get the downloadUrl for a given file ref + * const storage = getStorage(); + * const myRef = ref(storage, 'images/mountains.jpg'); + * const downloadUrl = await getDownloadURL(myRef); + * ``` + */ +async function getDownloadURL(file) { + const endpoint = (process.env.STORAGE_EMULATOR_HOST || + 'https://firebasestorage.googleapis.com') + '/v0'; + const { downloadTokens } = await (0, utils_1.getFirebaseMetadata)(endpoint, file); + if (!downloadTokens) { + throw new error_1.FirebaseError({ + code: 'storage/no-download-token', + message: 'No download token available. Please create one in the Firebase Console.', + }); + } + const [token] = downloadTokens.split(','); + return `${endpoint}/b/${file.bucket.name}/o/${encodeURIComponent(file.name)}?alt=media&token=${token}`; +} diff --git a/node_modules/firebase-admin/lib/storage/storage-namespace.d.ts b/node_modules/firebase-admin/lib/storage/storage-namespace.d.ts new file mode 100644 index 0000000..4b4f835 --- /dev/null +++ b/node_modules/firebase-admin/lib/storage/storage-namespace.d.ts @@ -0,0 +1,45 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +import { Storage as TStorage } from './storage'; +/** + * Gets the {@link firebase-admin.storage#Storage} service for the + * default app or a given app. + * + * `admin.storage()` can be called with no arguments to access the default + * app's `Storage` service or as `admin.storage(app)` to access the + * `Storage` service associated with a specific app. + * + * @example + * ```javascript + * // Get the Storage service for the default app + * var defaultStorage = admin.storage(); + * ``` + * + * @example + * ```javascript + * // Get the Storage service for a given app + * var otherStorage = admin.storage(otherApp); + * ``` + */ +export declare function storage(app?: App): storage.Storage; +export declare namespace storage { + /** + * Type alias to {@link firebase-admin.storage#Storage}. + */ + type Storage = TStorage; +} diff --git a/node_modules/firebase-admin/lib/storage/storage-namespace.js b/node_modules/firebase-admin/lib/storage/storage-namespace.js new file mode 100644 index 0000000..a91b066 --- /dev/null +++ b/node_modules/firebase-admin/lib/storage/storage-namespace.js @@ -0,0 +1,18 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/firebase-admin/lib/storage/storage.d.ts b/node_modules/firebase-admin/lib/storage/storage.d.ts new file mode 100644 index 0000000..073c2c4 --- /dev/null +++ b/node_modules/firebase-admin/lib/storage/storage.d.ts @@ -0,0 +1,42 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +import { Bucket } from '@google-cloud/storage'; +/** + * The default `Storage` service if no + * app is provided or the `Storage` service associated with the provided + * app. + */ +export declare class Storage { + private readonly appInternal; + private readonly storageClient; + /** + * Gets a reference to a Cloud Storage bucket. + * + * @param name - Optional name of the bucket to be retrieved. If name is not specified, + * retrieves a reference to the default bucket. + * @returns A {@link https://cloud.google.com/nodejs/docs/reference/storage/latest/Bucket | Bucket} + * instance as defined in the `@google-cloud/storage` package. + */ + bucket(name?: string): Bucket; + /** + * Optional app whose `Storage` service to + * return. If not provided, the default `Storage` service will be returned. + */ + get app(): App; +} diff --git a/node_modules/firebase-admin/lib/storage/storage.js b/node_modules/firebase-admin/lib/storage/storage.js new file mode 100644 index 0000000..783e9f7 --- /dev/null +++ b/node_modules/firebase-admin/lib/storage/storage.js @@ -0,0 +1,121 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Storage = void 0; +const error_1 = require("../utils/error"); +const credential_internal_1 = require("../app/credential-internal"); +const utils = require("../utils/index"); +const validator = require("../utils/validator"); +/** + * The default `Storage` service if no + * app is provided or the `Storage` service associated with the provided + * app. + */ +class Storage { + /** + * @param app - The app for this Storage service. + * @constructor + * @internal + */ + constructor(app) { + if (!validator.isNonNullObject(app) || !('options' in app)) { + throw new error_1.FirebaseError({ + code: 'storage/invalid-argument', + message: 'First argument passed to admin.storage() must be a valid Firebase app instance.', + }); + } + if (!process.env.STORAGE_EMULATOR_HOST && process.env.FIREBASE_STORAGE_EMULATOR_HOST) { + const firebaseStorageEmulatorHost = process.env.FIREBASE_STORAGE_EMULATOR_HOST; + if (firebaseStorageEmulatorHost.match(/https?:\/\//)) { + throw new error_1.FirebaseError({ + code: 'storage/invalid-emulator-host', + message: 'FIREBASE_STORAGE_EMULATOR_HOST should not contain a protocol (http or https).', + }); + } + process.env.STORAGE_EMULATOR_HOST = `http://${process.env.FIREBASE_STORAGE_EMULATOR_HOST}`; + } + let storage; + try { + storage = require('@google-cloud/storage').Storage; + } + catch (err) { + throw new error_1.FirebaseError({ + code: 'storage/missing-dependencies', + message: 'Failed to import the Cloud Storage client library for Node.js. ' + + 'Make sure to install the "@google-cloud/storage" npm package. ' + + `Original error: ${err}`, + }); + } + const projectId = utils.getExplicitProjectId(app); + const credential = app.options.credential; + if (credential instanceof credential_internal_1.ServiceAccountCredential) { + this.storageClient = new storage({ + // When the SDK is initialized with ServiceAccountCredentials an explicit projectId is + // guaranteed to be available. + projectId: projectId, + credentials: { + private_key: credential.privateKey, + client_email: credential.clientEmail, + }, + }); + } + else if ((0, credential_internal_1.isApplicationDefault)(app.options.credential)) { + // Try to use the Google application default credentials. + this.storageClient = new storage(); + } + else { + throw new error_1.FirebaseError({ + code: 'storage/invalid-credential', + message: 'Failed to initialize Google Cloud Storage client with the available credential. ' + + 'Must initialize the SDK with a certificate credential or application default credentials ' + + 'to use Cloud Storage API.', + }); + } + this.appInternal = app; + } + /** + * Gets a reference to a Cloud Storage bucket. + * + * @param name - Optional name of the bucket to be retrieved. If name is not specified, + * retrieves a reference to the default bucket. + * @returns A {@link https://cloud.google.com/nodejs/docs/reference/storage/latest/Bucket | Bucket} + * instance as defined in the `@google-cloud/storage` package. + */ + bucket(name) { + const bucketName = (typeof name !== 'undefined') + ? name : this.appInternal.options.storageBucket; + if (validator.isNonEmptyString(bucketName)) { + return this.storageClient.bucket(bucketName); + } + throw new error_1.FirebaseError({ + code: 'storage/invalid-argument', + message: 'Bucket name not specified or invalid. Specify a valid bucket name via the ' + + 'storageBucket option when initializing the app, or specify the bucket name ' + + 'explicitly when calling the getBucket() method.', + }); + } + /** + * Optional app whose `Storage` service to + * return. If not provided, the default `Storage` service will be returned. + */ + get app() { + return this.appInternal; + } +} +exports.Storage = Storage; diff --git a/node_modules/firebase-admin/lib/storage/utils.d.ts b/node_modules/firebase-admin/lib/storage/utils.d.ts new file mode 100644 index 0000000..74d8afc --- /dev/null +++ b/node_modules/firebase-admin/lib/storage/utils.d.ts @@ -0,0 +1,20 @@ +/*! firebase-admin v13.6.0 */ +import { File } from '@google-cloud/storage'; +export interface FirebaseMetadata { + name: string; + bucket: string; + generation: string; + metageneration: string; + contentType: string; + timeCreated: string; + updated: string; + storageClass: string; + size: string; + md5Hash: string; + contentEncoding: string; + contentDisposition: string; + crc32c: string; + etag: string; + downloadTokens?: string; +} +export declare function getFirebaseMetadata(endpoint: string, file: File): Promise; diff --git a/node_modules/firebase-admin/lib/storage/utils.js b/node_modules/firebase-admin/lib/storage/utils.js new file mode 100644 index 0000000..a310d2a --- /dev/null +++ b/node_modules/firebase-admin/lib/storage/utils.js @@ -0,0 +1,20 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getFirebaseMetadata = getFirebaseMetadata; +function getFirebaseMetadata(endpoint, file) { + const uri = `${endpoint}/b/${file.bucket.name}/o/${encodeURIComponent(file.name)}`; + return new Promise((resolve, reject) => { + file.storage.makeAuthenticatedRequest({ + method: 'GET', + uri, + }, (err, body) => { + if (err) { + reject(err); + } + else { + resolve(body); + } + }); + }); +} diff --git a/node_modules/firebase-admin/lib/utils/api-request.d.ts b/node_modules/firebase-admin/lib/utils/api-request.d.ts new file mode 100644 index 0000000..983f55b --- /dev/null +++ b/node_modules/firebase-admin/lib/utils/api-request.d.ts @@ -0,0 +1,324 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '../app/firebase-app'; +import http = require('http'); +import http2 = require('http2'); +import { EventEmitter } from 'events'; +/** Http method type definition. */ +export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD'; +/** API callback function type definition. */ +export type ApiCallbackFunction = (data: object) => void; +/** + * Base configuration for constructing a new request. + */ +export interface BaseRequestConfig { + method: HttpMethod; + /** Target URL of the request. Should be a well-formed URL including protocol, hostname, port and path. */ + url: string; + headers?: { + [key: string]: string; + }; + data?: string | object | Buffer | null; + /** Connect and read timeout (in milliseconds) for the outgoing request. */ + timeout?: number; +} +/** + * Configuration for constructing a new HTTP request. + */ +export interface HttpRequestConfig extends BaseRequestConfig { + httpAgent?: http.Agent; +} +/** + * Configuration for constructing a new HTTP/2 request. + */ +export interface Http2RequestConfig extends BaseRequestConfig { + http2SessionHandler: Http2SessionHandler; +} +type RequestConfig = HttpRequestConfig | Http2RequestConfig; +/** + * Represents an HTTP or HTTP/2 response received from a remote server. + */ +export interface RequestResponse { + readonly status: number; + readonly headers: any; + /** Response data as a raw string. */ + readonly text?: string; + /** Response data as a parsed JSON object. */ + readonly data?: any; + /** For multipart responses, the payloads of individual parts. */ + readonly multipart?: Buffer[]; + /** + * Indicates if the response content is JSON-formatted or not. If true, data field can be used + * to retrieve the content as a parsed JSON object. + */ + isJson(): boolean; +} +interface BaseLowLevelResponse { + status: number; + data?: string; + multipart?: Buffer[]; +} +interface LowLevelHttpResponse extends BaseLowLevelResponse { + headers: http.IncomingHttpHeaders; + request: http.ClientRequest | null; + config: HttpRequestConfig; +} +type IncomingHttp2Headers = http2.IncomingHttpHeaders & http2.IncomingHttpStatusHeader; +interface LowLevelHttp2Response extends BaseLowLevelResponse { + headers: IncomingHttp2Headers; + request: http2.ClientHttp2Stream | null; + config: Http2RequestConfig; +} +type LowLevelResponse = LowLevelHttpResponse | LowLevelHttp2Response; +interface BaseLowLevelError extends Error { + code?: string; +} +interface LowLevelHttpError extends BaseLowLevelError { + config: HttpRequestConfig; + request?: http.ClientRequest; + response?: LowLevelHttpResponse; +} +interface LowLevelHttp2Error extends BaseLowLevelError { + config: Http2RequestConfig; + request?: http2.ClientHttp2Stream; + response?: LowLevelHttp2Response; +} +type LowLevelError = LowLevelHttpError | LowLevelHttp2Error; +export declare class RequestResponseError extends Error { + readonly response: RequestResponse; + constructor(response: RequestResponse); +} +/** + * Specifies how failing HTTP and HTTP/2 requests should be retried. + */ +export interface RetryConfig { + /** Maximum number of times to retry a given request. */ + maxRetries: number; + /** Response status codes that should be retried. */ + statusCodes?: number[]; + /** Low-level I/O error codes that should be retried. */ + ioErrorCodes?: string[]; + /** + * The multiplier for exponential back off. The retry delay is calculated in seconds using the formula + * `(2^n) * backOffFactor`, where n is the number of retries performed so far. When the `backOffFactor` is set + * to 0, retries are not delayed. When the `backOffFactor` is 1, retry duration is doubled each iteration. + */ + backOffFactor?: number; + /** Maximum duration to wait before initiating a retry. */ + maxDelayInMillis: number; +} +/** + * Default retry configuration for HTTP and HTTP/2 requests. Retries up to 4 times on connection reset and timeout + * errors as well as 503 errors. Exposed as a function to ensure that every `RequestClient` gets its own `RetryConfig` + * instance. + */ +export declare function defaultRetryConfig(): RetryConfig; +export declare class RequestClient { + protected readonly retry: RetryConfig; + constructor(retry?: RetryConfig | null); + protected createRequestResponse(resp: LowLevelResponse): RequestResponse; + protected waitForRetry(delayMillis: number): Promise; + /** + * Checks if a failed request is eligible for a retry, and if so returns the duration to wait before initiating + * the retry. + * + * @param retryAttempts - Number of retries completed up to now. + * @param err - The last encountered error. + * @returns A 2-tuple where the 1st element is the duration to wait before another retry, and the + * 2nd element is a boolean indicating whether the request is eligible for a retry or not. + */ + protected getRetryDelayMillis(retryAttempts: number, err: LowLevelError): [number, boolean]; + protected isRetryEligible(retryAttempts: number, err: LowLevelError): boolean; + /**??? + * Parses the Retry-After header as a milliseconds value. Return value is negative if the Retry-After header + * contains an expired timestamp or otherwise malformed. + */ + protected parseRetryAfterIntoMillis(retryAfter: string): number; + protected backOffDelayMillis(retryAttempts: number): number; +} +export declare class HttpClient extends RequestClient { + constructor(retry?: RetryConfig | null); + /** + * Sends an HTTP request to a remote server. If the server responds with a successful response (2xx), the returned + * promise resolves with an `RequestResponse`. If the server responds with an error (3xx, 4xx, 5xx), the promise + * rejects with an `RequestResponseError`. In case of all other errors, the promise rejects with a `FirebaseAppError`. + * If a request fails due to a low-level network error, the client transparently retries the request once before + * rejecting the promise. + * + * If the request data is specified as an object, it will be serialized into a JSON string. The application/json + * content-type header will also be automatically set in this case. For all other payload types, the content-type + * header should be explicitly set by the caller. To send a JSON leaf value (e.g. "foo", 5), parse it into JSON, + * and pass as a string or a Buffer along with the appropriate content-type header. + * + * @param config - HTTP request to be sent. + * @returns A promise that resolves with the response details. + */ + send(config: HttpRequestConfig): Promise; + /** + * Sends an HTTP request. In the event of an error, retries the HTTP request according to the + * `RetryConfig` set on the `HttpClient`. + * + * @param config - HTTP request to be sent. + * @param retryAttempts - Number of retries performed up to now. + * @returns A promise that resolves with the response details. + */ + private sendWithRetry; +} +export declare class Http2Client extends RequestClient { + constructor(retry?: RetryConfig | null); + /** + * Sends an HTTP/2 request to a remote server. If the server responds with a successful response (2xx), the returned + * promise resolves with an `RequestResponse`. If the server responds with an error (3xx, 4xx, 5xx), the promise + * rejects with an `RequestResponseError`. In case of all other errors, the promise rejects with a `FirebaseAppError`. + * If a request fails due to a low-level network error, the client transparently retries the request once before + * rejecting the promise. + * + * If the request data is specified as an object, it will be serialized into a JSON string. The application/json + * content-type header will also be automatically set in this case. For all other payload types, the content-type + * header should be explicitly set by the caller. To send a JSON leaf value (e.g. "foo", 5), parse it into JSON, + * and pass as a string or a Buffer along with the appropriate content-type header. + * + * @param config - HTTP/2 request to be sent. + * @returns A promise that resolves with the response details. + */ + send(config: Http2RequestConfig): Promise; + /** + * Sends an HTTP/2 request. In the event of an error, retries the HTTP/2 request according to the + * `RetryConfig` set on the `Http2Client`. + * + * @param config - HTTP/2 request to be sent. + * @param retryAttempts - Number of retries performed up to now. + * @returns A promise that resolves with the response details. + */ + private sendWithRetry; +} +/** + * Parses a full HTTP or HTTP/2 response message containing both a header and a body. + * + * @param response - The HTTP or HTTP/2 response to be parsed. + * @param config - The request configuration that resulted in the HTTP or HTTP/2 response. + * @returns An object containing the response's parsed status, headers and the body. + */ +export declare function parseHttpResponse(response: string | Buffer, config: RequestConfig): RequestResponse; +export declare class AuthorizedHttpClient extends HttpClient { + private readonly app; + constructor(app: FirebaseApp); + send(request: HttpRequestConfig): Promise; + protected getToken(): Promise; +} +export declare class AuthorizedHttp2Client extends Http2Client { + private readonly app; + constructor(app: FirebaseApp); + send(request: Http2RequestConfig): Promise; + protected getToken(): Promise; +} +/** + * Class that defines all the settings for the backend API endpoint. + * + * @param endpoint - The Firebase Auth backend endpoint. + * @param httpMethod - The HTTP method for that endpoint. + * @constructor + */ +export declare class ApiSettings { + private endpoint; + private httpMethod; + private requestValidator; + private responseValidator; + constructor(endpoint: string, httpMethod?: HttpMethod); + /** @returns The backend API endpoint. */ + getEndpoint(): string; + /** @returns The request HTTP method. */ + getHttpMethod(): HttpMethod; + /** + * @param requestValidator - The request validator. + * @returns The current API settings instance. + */ + setRequestValidator(requestValidator: ApiCallbackFunction | null): ApiSettings; + /** @returns The request validator. */ + getRequestValidator(): ApiCallbackFunction; + /** + * @param responseValidator - The response validator. + * @returns The current API settings instance. + */ + setResponseValidator(responseValidator: ApiCallbackFunction | null): ApiSettings; + /** @returns The response validator. */ + getResponseValidator(): ApiCallbackFunction; +} +/** + * Class used for polling an endpoint with exponential backoff. + * + * Example usage: + * ``` + * const poller = new ExponentialBackoffPoller(); + * poller + * .poll(() => { + * return myRequestToPoll() + * .then((responseData: any) => { + * if (!isValid(responseData)) { + * // Continue polling. + * return null; + * } + * + * // Polling complete. Resolve promise with final response data. + * return responseData; + * }); + * }) + * .then((responseData: any) => { + * console.log(`Final response: ${responseData}`); + * }); + * ``` + */ +export declare class ExponentialBackoffPoller extends EventEmitter { + private readonly initialPollingDelayMillis; + private readonly maxPollingDelayMillis; + private readonly masterTimeoutMillis; + private numTries; + private completed; + private masterTimer; + private repollTimer; + private pollCallback?; + private resolve; + private reject; + constructor(initialPollingDelayMillis?: number, maxPollingDelayMillis?: number, masterTimeoutMillis?: number); + /** + * Poll the provided callback with exponential backoff. + * + * @param callback - The callback to be called for each poll. If the + * callback resolves to a falsey value, polling will continue. Otherwise, the truthy + * resolution will be used to resolve the promise returned by this method. + * @returns A Promise which resolves to the truthy value returned by the provided + * callback when polling is complete. + */ + poll(callback: () => Promise): Promise; + private repoll; + private getPollingDelayMillis; + private markCompleted; +} +export declare class Http2SessionHandler { + private http2Session; + protected promise: Promise; + protected resolve: () => void; + protected reject: (_: any) => void; + constructor(url: string); + createSession(url: string): http2.ClientHttp2Session; + invoke(): Promise; + get session(): http2.ClientHttp2Session; + get isClosed(): boolean; + close(): void; +} +export {}; diff --git a/node_modules/firebase-admin/lib/utils/api-request.js b/node_modules/firebase-admin/lib/utils/api-request.js new file mode 100644 index 0000000..8f03d27 --- /dev/null +++ b/node_modules/firebase-admin/lib/utils/api-request.js @@ -0,0 +1,1052 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Http2SessionHandler = exports.ExponentialBackoffPoller = exports.ApiSettings = exports.AuthorizedHttp2Client = exports.AuthorizedHttpClient = exports.Http2Client = exports.HttpClient = exports.RequestClient = exports.RequestResponseError = void 0; +exports.defaultRetryConfig = defaultRetryConfig; +exports.parseHttpResponse = parseHttpResponse; +const error_1 = require("./error"); +const validator = require("./validator"); +const http = require("http"); +const https = require("https"); +const http2 = require("http2"); +const url = require("url"); +const events_1 = require("events"); +const credential_internal_1 = require("../app/credential-internal"); +const index_1 = require("../utils/index"); +class DefaultRequestResponse { + /** + * Constructs a new `RequestResponse` from the given `LowLevelResponse`. + */ + constructor(resp) { + this.status = resp.status; + this.headers = resp.headers; + this.text = resp.data; + try { + if (!resp.data) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INTERNAL_ERROR, 'HTTP response missing data.'); + } + this.parsedData = JSON.parse(resp.data); + } + catch (err) { + this.parsedData = undefined; + this.parseError = err; + } + this.request = `${resp.config.method} ${resp.config.url}`; + } + get data() { + if (this.isJson()) { + return this.parsedData; + } + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.UNABLE_TO_PARSE_RESPONSE, `Error while parsing response data: "${this.parseError.toString()}". Raw server ` + + `response: "${this.text}". Status code: "${this.status}". Outgoing ` + + `request: "${this.request}."`); + } + isJson() { + return typeof this.parsedData !== 'undefined'; + } +} +/** + * Represents a multipart HTTP or HTTP/2 response. Parts that constitute the response body can be accessed + * via the multipart getter. Getters for text and data throw errors. + */ +class MultipartRequestResponse { + constructor(resp) { + this.status = resp.status; + this.headers = resp.headers; + this.multipart = resp.multipart; + } + get text() { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.UNABLE_TO_PARSE_RESPONSE, 'Unable to parse multipart payload as text'); + } + get data() { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.UNABLE_TO_PARSE_RESPONSE, 'Unable to parse multipart payload as JSON'); + } + isJson() { + return false; + } +} +class RequestResponseError extends Error { + constructor(response) { + super(`Server responded with status ${response.status}.`); + this.response = response; + // Set the prototype so that instanceof checks will work correctly. + // See: https://github.com/Microsoft/TypeScript/issues/13965 + Object.setPrototypeOf(this, RequestResponseError.prototype); + } +} +exports.RequestResponseError = RequestResponseError; +/** + * Default retry configuration for HTTP and HTTP/2 requests. Retries up to 4 times on connection reset and timeout + * errors as well as 503 errors. Exposed as a function to ensure that every `RequestClient` gets its own `RetryConfig` + * instance. + */ +function defaultRetryConfig() { + return { + maxRetries: 4, + statusCodes: [503], + ioErrorCodes: ['ECONNRESET', 'ETIMEDOUT'], + backOffFactor: 0.5, + maxDelayInMillis: 60 * 1000, + }; +} +/** + * Ensures that the given `RetryConfig` object is valid. + * + * @param retry - The configuration to be validated. + */ +function validateRetryConfig(retry) { + if (!validator.isNumber(retry.maxRetries) || retry.maxRetries < 0) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_ARGUMENT, 'maxRetries must be a non-negative integer'); + } + if (typeof retry.backOffFactor !== 'undefined') { + if (!validator.isNumber(retry.backOffFactor) || retry.backOffFactor < 0) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_ARGUMENT, 'backOffFactor must be a non-negative number'); + } + } + if (!validator.isNumber(retry.maxDelayInMillis) || retry.maxDelayInMillis < 0) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_ARGUMENT, 'maxDelayInMillis must be a non-negative integer'); + } + if (typeof retry.statusCodes !== 'undefined' && !validator.isArray(retry.statusCodes)) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_ARGUMENT, 'statusCodes must be an array'); + } + if (typeof retry.ioErrorCodes !== 'undefined' && !validator.isArray(retry.ioErrorCodes)) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_ARGUMENT, 'ioErrorCodes must be an array'); + } +} +class RequestClient { + constructor(retry = defaultRetryConfig()) { + if (retry) { + this.retry = retry; + validateRetryConfig(this.retry); + } + } + createRequestResponse(resp) { + if (resp.multipart) { + return new MultipartRequestResponse(resp); + } + return new DefaultRequestResponse(resp); + } + waitForRetry(delayMillis) { + if (delayMillis > 0) { + return new Promise((resolve) => { + setTimeout(resolve, delayMillis); + }); + } + return Promise.resolve(); + } + /** + * Checks if a failed request is eligible for a retry, and if so returns the duration to wait before initiating + * the retry. + * + * @param retryAttempts - Number of retries completed up to now. + * @param err - The last encountered error. + * @returns A 2-tuple where the 1st element is the duration to wait before another retry, and the + * 2nd element is a boolean indicating whether the request is eligible for a retry or not. + */ + getRetryDelayMillis(retryAttempts, err) { + if (!this.isRetryEligible(retryAttempts, err)) { + return [0, false]; + } + const response = err.response; + if (response && response.headers['retry-after']) { + const delayMillis = this.parseRetryAfterIntoMillis(response.headers['retry-after']); + if (delayMillis > 0) { + return [delayMillis, true]; + } + } + return [this.backOffDelayMillis(retryAttempts), true]; + } + isRetryEligible(retryAttempts, err) { + if (!this.retry) { + return false; + } + if (retryAttempts >= this.retry.maxRetries) { + return false; + } + if (err.response) { + const statusCodes = this.retry.statusCodes || []; + return statusCodes.indexOf(err.response.status) !== -1; + } + if (err.code) { + const retryCodes = this.retry.ioErrorCodes || []; + return retryCodes.indexOf(err.code) !== -1; + } + return false; + } + /**??? + * Parses the Retry-After header as a milliseconds value. Return value is negative if the Retry-After header + * contains an expired timestamp or otherwise malformed. + */ + parseRetryAfterIntoMillis(retryAfter) { + const delaySeconds = parseInt(retryAfter, 10); + if (!isNaN(delaySeconds)) { + return delaySeconds * 1000; + } + const date = new Date(retryAfter); + if (!isNaN(date.getTime())) { + return date.getTime() - Date.now(); + } + return -1; + } + backOffDelayMillis(retryAttempts) { + if (retryAttempts === 0) { + return 0; + } + if (!this.retry) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INTERNAL_ERROR, 'Expected this.retry to exist.'); + } + const backOffFactor = this.retry.backOffFactor || 0; + const delayInSeconds = (2 ** retryAttempts) * backOffFactor; + return Math.min(delayInSeconds * 1000, this.retry.maxDelayInMillis); + } +} +exports.RequestClient = RequestClient; +class HttpClient extends RequestClient { + constructor(retry) { + super(retry); + } + /** + * Sends an HTTP request to a remote server. If the server responds with a successful response (2xx), the returned + * promise resolves with an `RequestResponse`. If the server responds with an error (3xx, 4xx, 5xx), the promise + * rejects with an `RequestResponseError`. In case of all other errors, the promise rejects with a `FirebaseAppError`. + * If a request fails due to a low-level network error, the client transparently retries the request once before + * rejecting the promise. + * + * If the request data is specified as an object, it will be serialized into a JSON string. The application/json + * content-type header will also be automatically set in this case. For all other payload types, the content-type + * header should be explicitly set by the caller. To send a JSON leaf value (e.g. "foo", 5), parse it into JSON, + * and pass as a string or a Buffer along with the appropriate content-type header. + * + * @param config - HTTP request to be sent. + * @returns A promise that resolves with the response details. + */ + send(config) { + return this.sendWithRetry(config); + } + /** + * Sends an HTTP request. In the event of an error, retries the HTTP request according to the + * `RetryConfig` set on the `HttpClient`. + * + * @param config - HTTP request to be sent. + * @param retryAttempts - Number of retries performed up to now. + * @returns A promise that resolves with the response details. + */ + sendWithRetry(config, retryAttempts = 0) { + return AsyncHttpCall.invoke(config) + .then((resp) => { + return this.createRequestResponse(resp); + }) + .catch((err) => { + const [delayMillis, canRetry] = this.getRetryDelayMillis(retryAttempts, err); + if (canRetry && this.retry && delayMillis <= this.retry.maxDelayInMillis) { + return this.waitForRetry(delayMillis).then(() => { + return this.sendWithRetry(config, retryAttempts + 1); + }); + } + if (err.response) { + throw new RequestResponseError(this.createRequestResponse(err.response)); + } + if (err.code === 'ETIMEDOUT') { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.NETWORK_TIMEOUT, `Error while making request: ${err.message}.`); + } + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.NETWORK_ERROR, `Error while making request: ${err.message}. Error code: ${err.code}`); + }); + } +} +exports.HttpClient = HttpClient; +class Http2Client extends RequestClient { + constructor(retry = defaultRetryConfig()) { + super(retry); + } + /** + * Sends an HTTP/2 request to a remote server. If the server responds with a successful response (2xx), the returned + * promise resolves with an `RequestResponse`. If the server responds with an error (3xx, 4xx, 5xx), the promise + * rejects with an `RequestResponseError`. In case of all other errors, the promise rejects with a `FirebaseAppError`. + * If a request fails due to a low-level network error, the client transparently retries the request once before + * rejecting the promise. + * + * If the request data is specified as an object, it will be serialized into a JSON string. The application/json + * content-type header will also be automatically set in this case. For all other payload types, the content-type + * header should be explicitly set by the caller. To send a JSON leaf value (e.g. "foo", 5), parse it into JSON, + * and pass as a string or a Buffer along with the appropriate content-type header. + * + * @param config - HTTP/2 request to be sent. + * @returns A promise that resolves with the response details. + */ + send(config) { + return this.sendWithRetry(config); + } + /** + * Sends an HTTP/2 request. In the event of an error, retries the HTTP/2 request according to the + * `RetryConfig` set on the `Http2Client`. + * + * @param config - HTTP/2 request to be sent. + * @param retryAttempts - Number of retries performed up to now. + * @returns A promise that resolves with the response details. + */ + sendWithRetry(config, retryAttempts = 0) { + return AsyncHttp2Call.invoke(config) + .then((resp) => { + return this.createRequestResponse(resp); + }) + .catch((err) => { + const [delayMillis, canRetry] = this.getRetryDelayMillis(retryAttempts, err); + if (canRetry && this.retry && delayMillis <= this.retry.maxDelayInMillis) { + return this.waitForRetry(delayMillis).then(() => { + return this.sendWithRetry(config, retryAttempts + 1); + }); + } + if (err.response) { + throw new RequestResponseError(this.createRequestResponse(err.response)); + } + if (err.code === 'ETIMEDOUT') { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.NETWORK_TIMEOUT, `Error while making request: ${err.message}.`); + } + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.NETWORK_ERROR, `Error while making request: ${err.message}. Error code: ${err.code}`); + }); + } +} +exports.Http2Client = Http2Client; +/** + * Parses a full HTTP or HTTP/2 response message containing both a header and a body. + * + * @param response - The HTTP or HTTP/2 response to be parsed. + * @param config - The request configuration that resulted in the HTTP or HTTP/2 response. + * @returns An object containing the response's parsed status, headers and the body. + */ +function parseHttpResponse(response, config) { + const responseText = validator.isBuffer(response) ? + response.toString('utf-8') : response; + const endOfHeaderPos = responseText.indexOf('\r\n\r\n'); + const headerLines = responseText.substring(0, endOfHeaderPos).split('\r\n'); + const statusLine = headerLines[0]; + const status = statusLine.trim().split(/\s/)[1]; + const headers = {}; + headerLines.slice(1).forEach((line) => { + const colonPos = line.indexOf(':'); + const name = line.substring(0, colonPos).trim().toLowerCase(); + const value = line.substring(colonPos + 1).trim(); + headers[name] = value; + }); + let data = responseText.substring(endOfHeaderPos + 4); + if (data.endsWith('\n')) { + data = data.slice(0, -1); + } + if (data.endsWith('\r')) { + data = data.slice(0, -1); + } + const lowLevelResponse = { + status: parseInt(status, 10), + headers, + data, + config, + request: null, + }; + if (!validator.isNumber(lowLevelResponse.status)) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INTERNAL_ERROR, 'Malformed HTTP status line.'); + } + return new DefaultRequestResponse(lowLevelResponse); +} +/** + * A helper class for common functionality needed to send requests over the wire. + * It also wraps the callback API of the Node.js standard library in a more flexible Promise API. + */ +class AsyncRequestCall { + constructor(configImpl) { + this.configImpl = configImpl; + } + /** + * Extracts multipart boundary from the HTTP header. The content-type header of a multipart + * response has the form 'multipart/subtype; boundary=string'. + * + * If the content-type header does not exist, or does not start with + * 'multipart/', then null will be returned. + */ + getMultipartBoundary(headers) { + const contentType = headers['content-type']; + if (!contentType || !contentType.startsWith('multipart/')) { + return null; + } + const segments = contentType.split(';'); + const emptyObject = {}; + const headerParams = segments.slice(1) + .map((segment) => segment.trim().split('=')) + .reduce((curr, params) => { + // Parse key=value pairs in the content-type header into properties of an object. + if (params.length === 2) { + const keyValuePair = {}; + keyValuePair[params[0]] = params[1]; + return Object.assign(curr, keyValuePair); + } + return curr; + }, emptyObject); + return headerParams.boundary; + } + handleMultipartResponse(response, respStream, boundary) { + const busboy = require('@fastify/busboy'); // eslint-disable-line @typescript-eslint/no-var-requires + const multipartParser = new busboy.Dicer({ boundary }); + const responseBuffer = []; + multipartParser.on('part', (part) => { + const tempBuffers = []; + part.on('data', (partData) => { + tempBuffers.push(partData); + }); + part.on('end', () => { + responseBuffer.push(Buffer.concat(tempBuffers)); + }); + }); + multipartParser.on('finish', () => { + response.data = undefined; + response.multipart = responseBuffer; + this.finalizeResponse(response); + }); + respStream.pipe(multipartParser); + } + handleRegularResponse(response, respStream) { + const responseBuffer = []; + respStream.on('data', (chunk) => { + responseBuffer.push(chunk); + }); + respStream.on('error', (err) => { + const req = response.request; + if (req && req.destroyed) { + return; + } + this.enhanceAndReject(err, null, req); + }); + respStream.on('end', () => { + response.data = Buffer.concat(responseBuffer).toString(); + this.finalizeResponse(response); + }); + } + /** + * Finalizes the current request call in-flight by either resolving or rejecting the associated + * promise. In the event of an error, adds additional useful information to the returned error. + */ + finalizeResponse(response) { + if (response.status >= 200 && response.status < 300) { + this.resolve(response); + } + else { + this.rejectWithError('Request failed with status code ' + response.status, null, response.request, response); + } + } + /** + * Creates a new error from the given message, and enhances it with other information available. + * Then the promise associated with this request call is rejected with the resulting error. + */ + rejectWithError(message, code, request, response) { + const error = new Error(message); + this.enhanceAndReject(error, code, request, response); + } + enhanceAndReject(error, code, request, response) { + this.reject(this.enhanceError(error, code, request, response)); + } + /** + * Enhances the given error by adding more information to it. Specifically, the request config, + * the underlying request and response will be attached to the error. + */ + enhanceError(error, code, request, response) { + error.config = this.configImpl; + if (code) { + error.code = code; + } + error.request = request; + error.response = response; + return error; + } +} +/** + * A helper class for sending HTTP requests over the wire. This is a wrapper around the standard + * http and https packages of Node.js, providing content processing, timeouts and error handling. + * It also wraps the callback API of the Node.js standard library in a more flexible Promise API. + */ +class AsyncHttpCall extends AsyncRequestCall { + /** + * Sends an HTTP request based on the provided configuration. + */ + static invoke(config) { + return new AsyncHttpCall(config).promise; + } + constructor(config) { + const httpConfigImpl = new HttpRequestConfigImpl(config); + super(httpConfigImpl); + try { + this.httpConfigImpl = httpConfigImpl; + this.options = this.httpConfigImpl.buildRequestOptions(); + this.entity = this.httpConfigImpl.buildEntity(this.options.headers); + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + this.execute(); + }); + } + catch (err) { + this.promise = Promise.reject(this.enhanceError(err, null)); + } + } + execute() { + const transport = this.options.protocol === 'https:' ? https : http; + const req = transport.request(this.options, (res) => { + this.handleResponse(res, req); + }); + // Handle errors + req.on('error', (err) => { + if (req.aborted) { + return; + } + this.enhanceAndReject(err, null, req); + }); + const timeout = this.httpConfigImpl.timeout; + const timeoutCallback = () => { + req.destroy(); + this.rejectWithError(`timeout of ${timeout}ms exceeded`, 'ETIMEDOUT', req); + }; + if (timeout) { + // Listen to timeouts and throw an error. + req.setTimeout(timeout, timeoutCallback); + } + // Send the request + req.end(this.entity); + } + handleResponse(res, req) { + if (req.aborted) { + return; + } + if (!res.statusCode) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INTERNAL_ERROR, 'Expected a statusCode on the response from a ClientRequest'); + } + const response = { + status: res.statusCode, + headers: res.headers, + request: req, + data: undefined, + config: this.httpConfigImpl, + }; + const boundary = this.getMultipartBoundary(res.headers); + const respStream = this.uncompressResponse(res); + if (boundary) { + this.handleMultipartResponse(response, respStream, boundary); + } + else { + this.handleRegularResponse(response, respStream); + } + } + uncompressResponse(res) { + // Uncompress the response body transparently if required. + let respStream = res; + const encodings = ['gzip', 'compress', 'deflate']; + if (res.headers['content-encoding'] && encodings.indexOf(res.headers['content-encoding']) !== -1) { + // Add the unzipper to the body stream processing pipeline. + const zlib = require('zlib'); // eslint-disable-line @typescript-eslint/no-var-requires + respStream = respStream.pipe(zlib.createUnzip()); + // Remove the content-encoding in order to not confuse downstream operations. + delete res.headers['content-encoding']; + } + return respStream; + } +} +class AsyncHttp2Call extends AsyncRequestCall { + /** + * Sends an HTTP2 request based on the provided configuration. + */ + static invoke(config) { + return new AsyncHttp2Call(config).promise; + } + constructor(config) { + const http2ConfigImpl = new Http2RequestConfigImpl(config); + super(http2ConfigImpl); + try { + this.http2ConfigImpl = http2ConfigImpl; + this.options = this.http2ConfigImpl.buildRequestOptions(); + this.entity = this.http2ConfigImpl.buildEntity(this.options.headers); + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + this.execute(); + }); + } + catch (err) { + this.promise = Promise.reject(this.enhanceError(err, null)); + } + } + execute() { + const req = this.http2ConfigImpl.http2SessionHandler.session.request({ + ':method': this.options.method, + ':scheme': this.options.protocol, + ':path': this.options.path, + ...this.options.headers + }); + req.on('response', (headers) => { + this.handleHttp2Response(headers, req); + }); + // Handle errors + req.on('error', (err) => { + if (req.aborted) { + return; + } + this.enhanceAndReject(err, null, req); + }); + const timeout = this.http2ConfigImpl.timeout; + const timeoutCallback = () => { + req.destroy(); + this.rejectWithError(`timeout of ${timeout}ms exceeded`, 'ETIMEDOUT', req); + }; + if (timeout) { + // Listen to timeouts and throw an error. + req.setTimeout(timeout, timeoutCallback); + } + req.end(this.entity); + } + handleHttp2Response(headers, stream) { + if (stream.aborted) { + return; + } + if (!headers[':status']) { + throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INTERNAL_ERROR, 'Expected a statusCode on the response from a ClientRequest'); + } + const response = { + status: headers[':status'], + headers: headers, + request: stream, + data: undefined, + config: this.http2ConfigImpl, + }; + const boundary = this.getMultipartBoundary(headers); + const respStream = this.uncompressResponse(headers, stream); + if (boundary) { + this.handleMultipartResponse(response, respStream, boundary); + } + else { + this.handleRegularResponse(response, respStream); + } + } + uncompressResponse(headers, stream) { + // Uncompress the response body transparently if required. + let respStream = stream; + const encodings = ['gzip', 'compress', 'deflate']; + if (headers['content-encoding'] && encodings.indexOf(headers['content-encoding']) !== -1) { + // Add the unzipper to the body stream processing pipeline. + const zlib = require('zlib'); // eslint-disable-line @typescript-eslint/no-var-requires + respStream = respStream.pipe(zlib.createUnzip()); + // Remove the content-encoding in order to not confuse downstream operations. + delete headers['content-encoding']; + } + return respStream; + } +} +/** + * An adapter class with common functionality needed to extract options and entity data from a `RequestConfig`. + */ +class BaseRequestConfigImpl { + constructor(config) { + this.config = config; + this.config = config; + } + get method() { + return this.config.method; + } + get url() { + return this.config.url; + } + get headers() { + return this.config.headers; + } + get data() { + return this.config.data; + } + get timeout() { + return this.config.timeout; + } + buildEntity(headers) { + let data; + if (!this.hasEntity() || !this.isEntityEnclosingRequest()) { + return data; + } + if (validator.isBuffer(this.data)) { + data = this.data; + } + else if (validator.isObject(this.data)) { + data = Buffer.from(JSON.stringify(this.data), 'utf-8'); + if (typeof headers['content-type'] === 'undefined') { + headers['content-type'] = 'application/json;charset=utf-8'; + } + } + else if (validator.isString(this.data)) { + data = Buffer.from(this.data, 'utf-8'); + } + else { + throw new Error('Request data must be a string, a Buffer or a json serializable object'); + } + // Add Content-Length header if data exists. + headers['Content-Length'] = data.length.toString(); + return data; + } + buildUrl() { + const fullUrl = this.urlWithProtocol(); + if (!this.hasEntity() || this.isEntityEnclosingRequest()) { + return url.parse(fullUrl); + } + if (!validator.isObject(this.data)) { + throw new Error(`${this.method} requests cannot have a body`); + } + // Parse URL and append data to query string. + const parsedUrl = new url.URL(fullUrl); + const dataObj = this.data; + for (const key in dataObj) { + if (Object.prototype.hasOwnProperty.call(dataObj, key)) { + parsedUrl.searchParams.append(key, dataObj[key]); + } + } + return url.parse(parsedUrl.toString()); + } + urlWithProtocol() { + const fullUrl = this.url; + if (fullUrl.startsWith('http://') || fullUrl.startsWith('https://')) { + return fullUrl; + } + return `https://${fullUrl}`; + } + hasEntity() { + return !!this.data; + } + isEntityEnclosingRequest() { + // GET and HEAD requests do not support entity (body) in request. + return this.method !== 'GET' && this.method !== 'HEAD'; + } +} +/** + * An adapter class for extracting options and entity data from an `HttpRequestConfig`. + */ +class HttpRequestConfigImpl extends BaseRequestConfigImpl { + constructor(httpConfig) { + super(httpConfig); + this.httpConfig = httpConfig; + } + get httpAgent() { + return this.httpConfig.httpAgent; + } + buildRequestOptions() { + const parsed = this.buildUrl(); + const protocol = parsed.protocol; + let port = parsed.port; + if (!port) { + const isHttps = protocol === 'https:'; + port = isHttps ? '443' : '80'; + } + return { + protocol, + hostname: parsed.hostname, + port, + path: parsed.path, + method: this.method, + agent: this.httpAgent, + headers: Object.assign({}, this.headers), + }; + } +} +/** + * An adapter class for extracting options and entity data from an `Http2RequestConfig`. + */ +class Http2RequestConfigImpl extends BaseRequestConfigImpl { + constructor(http2Config) { + super(http2Config); + this.http2Config = http2Config; + } + get http2SessionHandler() { + return this.http2Config.http2SessionHandler; + } + buildRequestOptions() { + const parsed = this.buildUrl(); + // TODO(b/401051826) + const protocol = parsed.protocol; + return { + protocol, + path: parsed.path, + method: this.method, + headers: Object.assign({}, this.headers), + }; + } +} +class AuthorizedHttpClient extends HttpClient { + constructor(app) { + super(); + this.app = app; + } + send(request) { + return this.getToken().then((token) => { + const requestCopy = Object.assign({}, request); + requestCopy.headers = Object.assign({}, request.headers); + const authHeader = 'Authorization'; + requestCopy.headers[authHeader] = `Bearer ${token}`; + let quotaProjectId; + if (this.app.options.credential instanceof credential_internal_1.ApplicationDefaultCredential) { + quotaProjectId = this.app.options.credential.getQuotaProjectId(); + } + quotaProjectId = process.env.GOOGLE_CLOUD_QUOTA_PROJECT || quotaProjectId; + if (!requestCopy.headers['x-goog-user-project'] && validator.isNonEmptyString(quotaProjectId)) { + requestCopy.headers['x-goog-user-project'] = quotaProjectId; + } + if (!requestCopy.httpAgent && this.app.options.httpAgent) { + requestCopy.httpAgent = this.app.options.httpAgent; + } + if (!requestCopy.headers['X-Goog-Api-Client']) { + requestCopy.headers['X-Goog-Api-Client'] = (0, index_1.getMetricsHeader)(); + } + return super.send(requestCopy); + }); + } + getToken() { + return this.app.INTERNAL.getToken() + .then((accessTokenObj) => accessTokenObj.accessToken); + } +} +exports.AuthorizedHttpClient = AuthorizedHttpClient; +class AuthorizedHttp2Client extends Http2Client { + constructor(app) { + super(); + this.app = app; + } + send(request) { + return this.getToken().then((token) => { + const requestCopy = Object.assign({}, request); + requestCopy.headers = Object.assign({}, request.headers); + const authHeader = 'Authorization'; + requestCopy.headers[authHeader] = `Bearer ${token}`; + let quotaProjectId; + if (this.app.options.credential instanceof credential_internal_1.ApplicationDefaultCredential) { + quotaProjectId = this.app.options.credential.getQuotaProjectId(); + } + quotaProjectId = process.env.GOOGLE_CLOUD_QUOTA_PROJECT || quotaProjectId; + if (!requestCopy.headers['x-goog-user-project'] && validator.isNonEmptyString(quotaProjectId)) { + requestCopy.headers['x-goog-user-project'] = quotaProjectId; + } + if (!requestCopy.headers['X-Goog-Api-Client']) { + requestCopy.headers['X-Goog-Api-Client'] = (0, index_1.getMetricsHeader)(); + } + return super.send(requestCopy); + }); + } + getToken() { + return this.app.INTERNAL.getToken() + .then((accessTokenObj) => accessTokenObj.accessToken); + } +} +exports.AuthorizedHttp2Client = AuthorizedHttp2Client; +/** + * Class that defines all the settings for the backend API endpoint. + * + * @param endpoint - The Firebase Auth backend endpoint. + * @param httpMethod - The HTTP method for that endpoint. + * @constructor + */ +class ApiSettings { + constructor(endpoint, httpMethod = 'POST') { + this.endpoint = endpoint; + this.httpMethod = httpMethod; + this.setRequestValidator(null) + .setResponseValidator(null); + } + /** @returns The backend API endpoint. */ + getEndpoint() { + return this.endpoint; + } + /** @returns The request HTTP method. */ + getHttpMethod() { + return this.httpMethod; + } + /** + * @param requestValidator - The request validator. + * @returns The current API settings instance. + */ + setRequestValidator(requestValidator) { + const nullFunction = () => undefined; + this.requestValidator = requestValidator || nullFunction; + return this; + } + /** @returns The request validator. */ + getRequestValidator() { + return this.requestValidator; + } + /** + * @param responseValidator - The response validator. + * @returns The current API settings instance. + */ + setResponseValidator(responseValidator) { + const nullFunction = () => undefined; + this.responseValidator = responseValidator || nullFunction; + return this; + } + /** @returns The response validator. */ + getResponseValidator() { + return this.responseValidator; + } +} +exports.ApiSettings = ApiSettings; +/** + * Class used for polling an endpoint with exponential backoff. + * + * Example usage: + * ``` + * const poller = new ExponentialBackoffPoller(); + * poller + * .poll(() => { + * return myRequestToPoll() + * .then((responseData: any) => { + * if (!isValid(responseData)) { + * // Continue polling. + * return null; + * } + * + * // Polling complete. Resolve promise with final response data. + * return responseData; + * }); + * }) + * .then((responseData: any) => { + * console.log(`Final response: ${responseData}`); + * }); + * ``` + */ +class ExponentialBackoffPoller extends events_1.EventEmitter { + constructor(initialPollingDelayMillis = 1000, maxPollingDelayMillis = 10000, masterTimeoutMillis = 60000) { + super(); + this.initialPollingDelayMillis = initialPollingDelayMillis; + this.maxPollingDelayMillis = maxPollingDelayMillis; + this.masterTimeoutMillis = masterTimeoutMillis; + this.numTries = 0; + this.completed = false; + } + /** + * Poll the provided callback with exponential backoff. + * + * @param callback - The callback to be called for each poll. If the + * callback resolves to a falsey value, polling will continue. Otherwise, the truthy + * resolution will be used to resolve the promise returned by this method. + * @returns A Promise which resolves to the truthy value returned by the provided + * callback when polling is complete. + */ + poll(callback) { + if (this.pollCallback) { + throw new Error('poll() can only be called once per instance of ExponentialBackoffPoller'); + } + this.pollCallback = callback; + this.on('poll', this.repoll); + this.masterTimer = setTimeout(() => { + if (this.completed) { + return; + } + this.markCompleted(); + this.reject(new Error('ExponentialBackoffPoller deadline exceeded - Master timeout reached')); + }, this.masterTimeoutMillis); + return new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + this.repoll(); + }); + } + repoll() { + this.pollCallback() + .then((result) => { + if (this.completed) { + return; + } + if (!result) { + this.repollTimer = + setTimeout(() => this.emit('poll'), this.getPollingDelayMillis()); + this.numTries++; + return; + } + this.markCompleted(); + this.resolve(result); + }) + .catch((err) => { + if (this.completed) { + return; + } + this.markCompleted(); + this.reject(err); + }); + } + getPollingDelayMillis() { + const increasedPollingDelay = Math.pow(2, this.numTries) * this.initialPollingDelayMillis; + return Math.min(increasedPollingDelay, this.maxPollingDelayMillis); + } + markCompleted() { + this.completed = true; + if (this.masterTimer) { + clearTimeout(this.masterTimer); + } + if (this.repollTimer) { + clearTimeout(this.repollTimer); + } + } +} +exports.ExponentialBackoffPoller = ExponentialBackoffPoller; +class Http2SessionHandler { + constructor(url) { + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + this.http2Session = this.createSession(url); + }); + } + createSession(url) { + if (!this.http2Session || this.isClosed) { + const opts = { + // Set local max concurrent stream limit to respect backend limit + peerMaxConcurrentStreams: 100, + ALPNProtocols: ['h2'] + }; + const http2Session = http2.connect(url, opts); + http2Session.on('goaway', (errorCode, _, opaqueData) => { + this.reject(new error_1.FirebaseAppError(error_1.AppErrorCodes.NETWORK_ERROR, `Error while making requests: GOAWAY - ${opaqueData?.toString()}, Error code: ${errorCode}`)); + }); + http2Session.on('error', (error) => { + let errorMessage; + if (error.name == 'AggregateError' && error.errors) { + errorMessage = `Session error while making requests: ${error.code} - ${error.name}: ` + + `[${error.errors.map((error) => error.message).join(', ')}]`; + } + else { + errorMessage = `Session error while making requests: ${error.code} - ${error.message} `; + } + this.reject(new error_1.FirebaseAppError(error_1.AppErrorCodes.NETWORK_ERROR, errorMessage)); + }); + http2Session.on('close', () => { + // Resolve current promise + this.resolve(); + }); + return http2Session; + } + return this.http2Session; + } + invoke() { + return this.promise; + } + get session() { + return this.http2Session; + } + get isClosed() { + return this.http2Session.closed; + } + close() { + this.http2Session.close(); + } +} +exports.Http2SessionHandler = Http2SessionHandler; diff --git a/node_modules/firebase-admin/lib/utils/crypto-signer.d.ts b/node_modules/firebase-admin/lib/utils/crypto-signer.d.ts new file mode 100644 index 0000000..142e86f --- /dev/null +++ b/node_modules/firebase-admin/lib/utils/crypto-signer.d.ts @@ -0,0 +1,128 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app'; +import { ServiceAccountCredential } from '../app/credential-internal'; +import { AuthorizedHttpClient } from './api-request'; +import { Algorithm } from 'jsonwebtoken'; +import { ErrorInfo } from '../utils/error'; +/** + * CryptoSigner interface represents an object that can be used to sign JWTs. + */ +export interface CryptoSigner { + /** + * The name of the signing algorithm. + */ + readonly algorithm: Algorithm; + /** + * Cryptographically signs a buffer of data. + * + * @param buffer - The data to be signed. + * @returns A promise that resolves with the raw bytes of a signature. + */ + sign(buffer: Buffer): Promise; + /** + * Returns the ID of the service account used to sign tokens. + * + * @returns A promise that resolves with a service account ID. + */ + getAccountId(): Promise; +} +/** + * A CryptoSigner implementation that uses an explicitly specified service account private key to + * sign data. Performs all operations locally, and does not make any RPC calls. + */ +export declare class ServiceAccountSigner implements CryptoSigner { + private readonly credential; + algorithm: Algorithm; + /** + * Creates a new CryptoSigner instance from the given service account credential. + * + * @param credential - A service account credential. + */ + constructor(credential: ServiceAccountCredential); + /** + * @inheritDoc + */ + sign(buffer: Buffer): Promise; + /** + * @inheritDoc + */ + getAccountId(): Promise; +} +/** + * A CryptoSigner implementation that uses the remote IAM service to sign data. If initialized without + * a service account ID, attempts to discover a service account ID by consulting the local Metadata + * service. This will succeed in managed environments like Google Cloud Functions and App Engine. + * + * @see https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/signBlob + * @see https://cloud.google.com/compute/docs/storing-retrieving-metadata + */ +export declare class IAMSigner implements CryptoSigner { + algorithm: Algorithm; + private readonly httpClient; + private serviceAccountId?; + private app?; + constructor(httpClient: AuthorizedHttpClient, app?: App); + /** + * @inheritDoc + */ + sign(buffer: Buffer): Promise; + /** + * @inheritDoc + */ + getAccountId(): Promise; +} +/** + * Creates a new CryptoSigner instance for the given app. If the app has been initialized with a + * service account credential, creates a ServiceAccountSigner. + * + * @param app - A FirebaseApp instance. + * @returns A CryptoSigner instance. + */ +export declare function cryptoSignerFromApp(app: App): CryptoSigner; +/** + * Defines extended error info type. This includes a code, message string, and error data. + */ +export interface ExtendedErrorInfo extends ErrorInfo { + cause?: Error; +} +/** + * CryptoSigner error code structure. + * + * @param errorInfo - The error information (code and message). + * @constructor + */ +export declare class CryptoSignerError extends Error { + private errorInfo; + constructor(errorInfo: ExtendedErrorInfo); + /** @returns The error code. */ + get code(): string; + /** @returns The error message. */ + get message(): string; + /** @returns The error data. */ + get cause(): Error | undefined; +} +/** + * Crypto Signer error codes and their default messages. + */ +export declare class CryptoSignerErrorCode { + static INVALID_ARGUMENT: string; + static INTERNAL_ERROR: string; + static INVALID_CREDENTIAL: string; + static SERVER_ERROR: string; +} diff --git a/node_modules/firebase-admin/lib/utils/crypto-signer.js b/node_modules/firebase-admin/lib/utils/crypto-signer.js new file mode 100644 index 0000000..621e519 --- /dev/null +++ b/node_modules/firebase-admin/lib/utils/crypto-signer.js @@ -0,0 +1,210 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CryptoSignerErrorCode = exports.CryptoSignerError = exports.IAMSigner = exports.ServiceAccountSigner = void 0; +exports.cryptoSignerFromApp = cryptoSignerFromApp; +const credential_internal_1 = require("../app/credential-internal"); +const api_request_1 = require("./api-request"); +const utils = require("../utils/index"); +const validator = require("../utils/validator"); +const ALGORITHM_RS256 = 'RS256'; +/** + * A CryptoSigner implementation that uses an explicitly specified service account private key to + * sign data. Performs all operations locally, and does not make any RPC calls. + */ +class ServiceAccountSigner { + /** + * Creates a new CryptoSigner instance from the given service account credential. + * + * @param credential - A service account credential. + */ + constructor(credential) { + this.credential = credential; + this.algorithm = ALGORITHM_RS256; + if (!credential) { + throw new CryptoSignerError({ + code: CryptoSignerErrorCode.INVALID_CREDENTIAL, + message: 'INTERNAL ASSERT: Must provide a service account credential to initialize ServiceAccountSigner.', + }); + } + } + /** + * @inheritDoc + */ + sign(buffer) { + const crypto = require('crypto'); // eslint-disable-line @typescript-eslint/no-var-requires + const sign = crypto.createSign('RSA-SHA256'); + sign.update(buffer); + return Promise.resolve(sign.sign(this.credential.privateKey)); + } + /** + * @inheritDoc + */ + getAccountId() { + return Promise.resolve(this.credential.clientEmail); + } +} +exports.ServiceAccountSigner = ServiceAccountSigner; +/** + * A CryptoSigner implementation that uses the remote IAM service to sign data. If initialized without + * a service account ID, attempts to discover a service account ID by consulting the local Metadata + * service. This will succeed in managed environments like Google Cloud Functions and App Engine. + * + * @see https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/signBlob + * @see https://cloud.google.com/compute/docs/storing-retrieving-metadata + */ +class IAMSigner { + constructor(httpClient, app) { + this.algorithm = ALGORITHM_RS256; + if (!httpClient) { + throw new CryptoSignerError({ + code: CryptoSignerErrorCode.INVALID_ARGUMENT, + message: 'INTERNAL ASSERT: Must provide a HTTP client to initialize IAMSigner.', + }); + } + if (app && (typeof app !== 'object' || app === null || !('options' in app))) { + throw new CryptoSignerError({ + code: CryptoSignerErrorCode.INVALID_ARGUMENT, + message: 'INTERNAL ASSERT: Must provide a valid Firebase app instance.', + }); + } + this.httpClient = httpClient; + this.app = app; + } + /** + * @inheritDoc + */ + sign(buffer) { + return this.getAccountId().then((serviceAccount) => { + const request = { + method: 'POST', + url: `https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${serviceAccount}:signBlob`, + data: { payload: buffer.toString('base64') }, + }; + return this.httpClient.send(request); + }).then((response) => { + // Response from IAM is base64 encoded. Decode it into a buffer and return. + return Buffer.from(response.data.signedBlob, 'base64'); + }).catch((err) => { + if (err instanceof api_request_1.RequestResponseError) { + throw new CryptoSignerError({ + code: CryptoSignerErrorCode.SERVER_ERROR, + message: err.message, + cause: err + }); + } + throw err; + }); + } + /** + * @inheritDoc + */ + async getAccountId() { + if (validator.isNonEmptyString(this.serviceAccountId)) { + return this.serviceAccountId; + } + if (this.app) { + const accountId = await utils.findServiceAccountEmail(this.app); + if (accountId) { + this.serviceAccountId = accountId; + return accountId; + } + } + const request = { + method: 'GET', + url: 'http://metadata/computeMetadata/v1/instance/service-accounts/default/email', + headers: { + 'Metadata-Flavor': 'Google', + }, + }; + const client = new api_request_1.HttpClient(); + return client.send(request).then((response) => { + if (!response.text) { + throw new CryptoSignerError({ + code: CryptoSignerErrorCode.INTERNAL_ERROR, + message: 'HTTP Response missing payload', + }); + } + this.serviceAccountId = response.text; + return response.text; + }).catch((err) => { + throw new CryptoSignerError({ + code: CryptoSignerErrorCode.INVALID_CREDENTIAL, + message: 'Failed to determine service account. Make sure to initialize ' + + 'the SDK with a service account credential. Alternatively specify a service ' + + `account with iam.serviceAccounts.signBlob permission. Original error: ${err}`, + }); + }); + } +} +exports.IAMSigner = IAMSigner; +/** + * Creates a new CryptoSigner instance for the given app. If the app has been initialized with a + * service account credential, creates a ServiceAccountSigner. + * + * @param app - A FirebaseApp instance. + * @returns A CryptoSigner instance. + */ +function cryptoSignerFromApp(app) { + const credential = app.options.credential; + if (credential instanceof credential_internal_1.ServiceAccountCredential) { + return new ServiceAccountSigner(credential); + } + return new IAMSigner(new api_request_1.AuthorizedHttpClient(app), app); +} +/** + * CryptoSigner error code structure. + * + * @param errorInfo - The error information (code and message). + * @constructor + */ +class CryptoSignerError extends Error { + constructor(errorInfo) { + super(errorInfo.message); + this.errorInfo = errorInfo; + /* tslint:disable:max-line-length */ + // Set the prototype explicitly. See the following link for more details: + // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work + /* tslint:enable:max-line-length */ + this.__proto__ = CryptoSignerError.prototype; + } + /** @returns The error code. */ + get code() { + return this.errorInfo.code; + } + /** @returns The error message. */ + get message() { + return this.errorInfo.message; + } + /** @returns The error data. */ + get cause() { + return this.errorInfo.cause; + } +} +exports.CryptoSignerError = CryptoSignerError; +/** + * Crypto Signer error codes and their default messages. + */ +class CryptoSignerErrorCode { +} +exports.CryptoSignerErrorCode = CryptoSignerErrorCode; +CryptoSignerErrorCode.INVALID_ARGUMENT = 'invalid-argument'; +CryptoSignerErrorCode.INTERNAL_ERROR = 'internal-error'; +CryptoSignerErrorCode.INVALID_CREDENTIAL = 'invalid-credential'; +CryptoSignerErrorCode.SERVER_ERROR = 'server-error'; diff --git a/node_modules/firebase-admin/lib/utils/deep-copy.d.ts b/node_modules/firebase-admin/lib/utils/deep-copy.d.ts new file mode 100644 index 0000000..2ca611b --- /dev/null +++ b/node_modules/firebase-admin/lib/utils/deep-copy.d.ts @@ -0,0 +1,40 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a deep copy of an object or array. + * + * @param value - The object or array to deep copy. + * @returns A deep copy of the provided object or array. + */ +export declare function deepCopy(value: T): T; +/** + * Copies properties from source to target (recursively allows extension of objects and arrays). + * Scalar values in the target are over-written. If target is undefined, an object of the + * appropriate type will be created (and returned). + * + * We recursively copy all child properties of plain objects in the source - so that namespace-like + * objects are merged. + * + * Note that the target can be a function, in which case the properties in the source object are + * copied onto it as static properties of the function. + * + * @param target - The value which is being extended. + * @param source - The value whose properties are extending the target. + * @returns The target value. + */ +export declare function deepExtend(target: any, source: any): any; diff --git a/node_modules/firebase-admin/lib/utils/deep-copy.js b/node_modules/firebase-admin/lib/utils/deep-copy.js new file mode 100644 index 0000000..4dd9997 --- /dev/null +++ b/node_modules/firebase-admin/lib/utils/deep-copy.js @@ -0,0 +1,77 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.deepCopy = deepCopy; +exports.deepExtend = deepExtend; +/** + * Returns a deep copy of an object or array. + * + * @param value - The object or array to deep copy. + * @returns A deep copy of the provided object or array. + */ +function deepCopy(value) { + return deepExtend(undefined, value); +} +/** + * Copies properties from source to target (recursively allows extension of objects and arrays). + * Scalar values in the target are over-written. If target is undefined, an object of the + * appropriate type will be created (and returned). + * + * We recursively copy all child properties of plain objects in the source - so that namespace-like + * objects are merged. + * + * Note that the target can be a function, in which case the properties in the source object are + * copied onto it as static properties of the function. + * + * @param target - The value which is being extended. + * @param source - The value whose properties are extending the target. + * @returns The target value. + */ +function deepExtend(target, source) { + if (!(source instanceof Object)) { + return source; + } + switch (source.constructor) { + case Date: { + // Treat Dates like scalars; if the target date object had any child + // properties - they will be lost! + const dateValue = source; + return new Date(dateValue.getTime()); + } + case Object: + if (target === undefined) { + target = {}; + } + break; + case Array: + // Always copy the array source and overwrite the target. + target = []; + break; + default: + // Not a plain Object - treat it as a scalar. + return source; + } + for (const prop in source) { + if (!Object.prototype.hasOwnProperty.call(source, prop)) { + continue; + } + target[prop] = deepExtend(target[prop], source[prop]); + } + return target; +} diff --git a/node_modules/firebase-admin/lib/utils/error.d.ts b/node_modules/firebase-admin/lib/utils/error.d.ts new file mode 100644 index 0000000..2b272f5 --- /dev/null +++ b/node_modules/firebase-admin/lib/utils/error.d.ts @@ -0,0 +1,604 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseError as FirebaseErrorInterface } from '../app'; +import { BatchResponse } from '../messaging/messaging-api'; +/** + * Defines error info type. This includes a code and message string. + */ +export interface ErrorInfo { + code: string; + message: string; +} +/** + * Firebase error code structure. This extends Error. + */ +export declare class FirebaseError extends Error implements FirebaseErrorInterface { + private errorInfo; + /** @returns The error code. */ + get code(): string; + /** @returns The error message. */ + get message(): string; + /** @returns The object representation of the error. */ + toJSON(): object; +} +/** + * A FirebaseError with a prefix in front of the error code. + */ +export declare class PrefixedFirebaseError extends FirebaseError { + private codePrefix; + /** + * Allows the error type to be checked without needing to know implementation details + * of the code prefixing. + * + * @param code - The non-prefixed error code to test against. + * @returns True if the code matches, false otherwise. + */ + hasCode(code: string): boolean; +} +/** + * Firebase App error code structure. This extends PrefixedFirebaseError. + */ +export declare class FirebaseAppError extends PrefixedFirebaseError { +} +/** + * Firebase Auth error code structure. This extends PrefixedFirebaseError. + */ +export declare class FirebaseAuthError extends PrefixedFirebaseError { +} +/** + * Firebase Database error code structure. This extends FirebaseError. + */ +export declare class FirebaseDatabaseError extends FirebaseError { +} +/** + * Firebase Firestore error code structure. This extends FirebaseError. + */ +export declare class FirebaseFirestoreError extends FirebaseError { +} +/** + * Firebase instance ID error code structure. This extends FirebaseError. + */ +export declare class FirebaseInstanceIdError extends FirebaseError { +} +/** + * Firebase Installations service error code structure. This extends `FirebaseError`. + */ +export declare class FirebaseInstallationsError extends FirebaseError { +} +/** + * Firebase Messaging error code structure. This extends PrefixedFirebaseError. + */ +export declare class FirebaseMessagingError extends PrefixedFirebaseError { +} +export declare class FirebaseMessagingSessionError extends FirebaseMessagingError { + pendingBatchResponse?: Promise; + /** @returns The object representation of the error. */ + toJSON(): object; +} +/** + * Firebase project management error code structure. This extends PrefixedFirebaseError. + */ +export declare class FirebaseProjectManagementError extends PrefixedFirebaseError { +} +/** + * App client error codes and their default messages. + */ +export declare class AppErrorCodes { + static APP_DELETED: string; + static DUPLICATE_APP: string; + static INVALID_ARGUMENT: string; + static INTERNAL_ERROR: string; + static INVALID_APP_NAME: string; + static INVALID_APP_OPTIONS: string; + static INVALID_CREDENTIAL: string; + static NETWORK_ERROR: string; + static NETWORK_TIMEOUT: string; + static NO_APP: string; + static UNABLE_TO_PARSE_RESPONSE: string; +} +/** + * Auth client error codes and their default messages. + */ +export declare class AuthClientErrorCode { + static AUTH_BLOCKING_TOKEN_EXPIRED: { + code: string; + message: string; + }; + static BILLING_NOT_ENABLED: { + code: string; + message: string; + }; + static CLAIMS_TOO_LARGE: { + code: string; + message: string; + }; + static CONFIGURATION_EXISTS: { + code: string; + message: string; + }; + static CONFIGURATION_NOT_FOUND: { + code: string; + message: string; + }; + static ID_TOKEN_EXPIRED: { + code: string; + message: string; + }; + static INVALID_ARGUMENT: { + code: string; + message: string; + }; + static INVALID_CONFIG: { + code: string; + message: string; + }; + static EMAIL_ALREADY_EXISTS: { + code: string; + message: string; + }; + static EMAIL_NOT_FOUND: { + code: string; + message: string; + }; + static FORBIDDEN_CLAIM: { + code: string; + message: string; + }; + static INVALID_ID_TOKEN: { + code: string; + message: string; + }; + static ID_TOKEN_REVOKED: { + code: string; + message: string; + }; + static INTERNAL_ERROR: { + code: string; + message: string; + }; + static INVALID_CLAIMS: { + code: string; + message: string; + }; + static INVALID_CONTINUE_URI: { + code: string; + message: string; + }; + static INVALID_CREATION_TIME: { + code: string; + message: string; + }; + static INVALID_CREDENTIAL: { + code: string; + message: string; + }; + static INVALID_DISABLED_FIELD: { + code: string; + message: string; + }; + static INVALID_DISPLAY_NAME: { + code: string; + message: string; + }; + static INVALID_DYNAMIC_LINK_DOMAIN: { + code: string; + message: string; + }; + static INVALID_HOSTING_LINK_DOMAIN: { + code: string; + message: string; + }; + static INVALID_EMAIL_VERIFIED: { + code: string; + message: string; + }; + static INVALID_EMAIL: { + code: string; + message: string; + }; + static INVALID_NEW_EMAIL: { + code: string; + message: string; + }; + static INVALID_ENROLLED_FACTORS: { + code: string; + message: string; + }; + static INVALID_ENROLLMENT_TIME: { + code: string; + message: string; + }; + static INVALID_HASH_ALGORITHM: { + code: string; + message: string; + }; + static INVALID_HASH_BLOCK_SIZE: { + code: string; + message: string; + }; + static INVALID_HASH_DERIVED_KEY_LENGTH: { + code: string; + message: string; + }; + static INVALID_HASH_KEY: { + code: string; + message: string; + }; + static INVALID_HASH_MEMORY_COST: { + code: string; + message: string; + }; + static INVALID_HASH_PARALLELIZATION: { + code: string; + message: string; + }; + static INVALID_HASH_ROUNDS: { + code: string; + message: string; + }; + static INVALID_HASH_SALT_SEPARATOR: { + code: string; + message: string; + }; + static INVALID_LAST_SIGN_IN_TIME: { + code: string; + message: string; + }; + static INVALID_NAME: { + code: string; + message: string; + }; + static INVALID_OAUTH_CLIENT_ID: { + code: string; + message: string; + }; + static INVALID_PAGE_TOKEN: { + code: string; + message: string; + }; + static INVALID_PASSWORD: { + code: string; + message: string; + }; + static INVALID_PASSWORD_HASH: { + code: string; + message: string; + }; + static INVALID_PASSWORD_SALT: { + code: string; + message: string; + }; + static INVALID_PHONE_NUMBER: { + code: string; + message: string; + }; + static INVALID_PHOTO_URL: { + code: string; + message: string; + }; + static INVALID_PROJECT_ID: { + code: string; + message: string; + }; + static INVALID_PROVIDER_DATA: { + code: string; + message: string; + }; + static INVALID_PROVIDER_ID: { + code: string; + message: string; + }; + static INVALID_PROVIDER_UID: { + code: string; + message: string; + }; + static INVALID_OAUTH_RESPONSETYPE: { + code: string; + message: string; + }; + static INVALID_SESSION_COOKIE_DURATION: { + code: string; + message: string; + }; + static INVALID_TENANT_ID: { + code: string; + message: string; + }; + static INVALID_TENANT_TYPE: { + code: string; + message: string; + }; + static INVALID_TESTING_PHONE_NUMBER: { + code: string; + message: string; + }; + static INVALID_UID: { + code: string; + message: string; + }; + static INVALID_USER_IMPORT: { + code: string; + message: string; + }; + static INVALID_TOKENS_VALID_AFTER_TIME: { + code: string; + message: string; + }; + static MISMATCHING_TENANT_ID: { + code: string; + message: string; + }; + static MISSING_ANDROID_PACKAGE_NAME: { + code: string; + message: string; + }; + static MISSING_CONFIG: { + code: string; + message: string; + }; + static MISSING_CONTINUE_URI: { + code: string; + message: string; + }; + static MISSING_DISPLAY_NAME: { + code: string; + message: string; + }; + static MISSING_EMAIL: { + code: string; + message: string; + }; + static MISSING_IOS_BUNDLE_ID: { + code: string; + message: string; + }; + static MISSING_ISSUER: { + code: string; + message: string; + }; + static MISSING_HASH_ALGORITHM: { + code: string; + message: string; + }; + static MISSING_OAUTH_CLIENT_ID: { + code: string; + message: string; + }; + static MISSING_OAUTH_CLIENT_SECRET: { + code: string; + message: string; + }; + static MISSING_PROVIDER_ID: { + code: string; + message: string; + }; + static MISSING_SAML_RELYING_PARTY_CONFIG: { + code: string; + message: string; + }; + static MAXIMUM_TEST_PHONE_NUMBER_EXCEEDED: { + code: string; + message: string; + }; + static MAXIMUM_USER_COUNT_EXCEEDED: { + code: string; + message: string; + }; + static MISSING_UID: { + code: string; + message: string; + }; + static OPERATION_NOT_ALLOWED: { + code: string; + message: string; + }; + static PHONE_NUMBER_ALREADY_EXISTS: { + code: string; + message: string; + }; + static PROJECT_NOT_FOUND: { + code: string; + message: string; + }; + static INSUFFICIENT_PERMISSION: { + code: string; + message: string; + }; + static QUOTA_EXCEEDED: { + code: string; + message: string; + }; + static SECOND_FACTOR_LIMIT_EXCEEDED: { + code: string; + message: string; + }; + static SECOND_FACTOR_UID_ALREADY_EXISTS: { + code: string; + message: string; + }; + static SESSION_COOKIE_EXPIRED: { + code: string; + message: string; + }; + static SESSION_COOKIE_REVOKED: { + code: string; + message: string; + }; + static TENANT_NOT_FOUND: { + code: string; + message: string; + }; + static UID_ALREADY_EXISTS: { + code: string; + message: string; + }; + static UNAUTHORIZED_DOMAIN: { + code: string; + message: string; + }; + static UNSUPPORTED_FIRST_FACTOR: { + code: string; + message: string; + }; + static UNSUPPORTED_SECOND_FACTOR: { + code: string; + message: string; + }; + static UNSUPPORTED_TENANT_OPERATION: { + code: string; + message: string; + }; + static UNVERIFIED_EMAIL: { + code: string; + message: string; + }; + static USER_NOT_FOUND: { + code: string; + message: string; + }; + static NOT_FOUND: { + code: string; + message: string; + }; + static USER_DISABLED: { + code: string; + message: string; + }; + static USER_NOT_DISABLED: { + code: string; + message: string; + }; + static INVALID_RECAPTCHA_ACTION: { + code: string; + message: string; + }; + static INVALID_RECAPTCHA_ENFORCEMENT_STATE: { + code: string; + message: string; + }; + static RECAPTCHA_NOT_ENABLED: { + code: string; + message: string; + }; +} +/** + * Messaging client error codes and their default messages. + */ +export declare class MessagingClientErrorCode { + static INVALID_ARGUMENT: { + code: string; + message: string; + }; + static INVALID_RECIPIENT: { + code: string; + message: string; + }; + static INVALID_PAYLOAD: { + code: string; + message: string; + }; + static INVALID_DATA_PAYLOAD_KEY: { + code: string; + message: string; + }; + static PAYLOAD_SIZE_LIMIT_EXCEEDED: { + code: string; + message: string; + }; + static INVALID_OPTIONS: { + code: string; + message: string; + }; + static INVALID_REGISTRATION_TOKEN: { + code: string; + message: string; + }; + static REGISTRATION_TOKEN_NOT_REGISTERED: { + code: string; + message: string; + }; + static MISMATCHED_CREDENTIAL: { + code: string; + message: string; + }; + static INVALID_PACKAGE_NAME: { + code: string; + message: string; + }; + static DEVICE_MESSAGE_RATE_EXCEEDED: { + code: string; + message: string; + }; + static TOPICS_MESSAGE_RATE_EXCEEDED: { + code: string; + message: string; + }; + static MESSAGE_RATE_EXCEEDED: { + code: string; + message: string; + }; + static THIRD_PARTY_AUTH_ERROR: { + code: string; + message: string; + }; + static TOO_MANY_TOPICS: { + code: string; + message: string; + }; + static AUTHENTICATION_ERROR: { + code: string; + message: string; + }; + static SERVER_UNAVAILABLE: { + code: string; + message: string; + }; + static INTERNAL_ERROR: { + code: string; + message: string; + }; + static UNKNOWN_ERROR: { + code: string; + message: string; + }; +} +export declare class InstallationsClientErrorCode { + static INVALID_ARGUMENT: { + code: string; + message: string; + }; + static INVALID_PROJECT_ID: { + code: string; + message: string; + }; + static INVALID_INSTALLATION_ID: { + code: string; + message: string; + }; + static API_ERROR: { + code: string; + message: string; + }; +} +export declare class InstanceIdClientErrorCode extends InstallationsClientErrorCode { + static INVALID_INSTANCE_ID: { + code: string; + message: string; + }; +} +export type ProjectManagementErrorCode = 'already-exists' | 'authentication-error' | 'internal-error' | 'invalid-argument' | 'invalid-project-id' | 'invalid-server-response' | 'not-found' | 'service-unavailable' | 'unknown-error'; diff --git a/node_modules/firebase-admin/lib/utils/error.js b/node_modules/firebase-admin/lib/utils/error.js new file mode 100644 index 0000000..8c7c8e7 --- /dev/null +++ b/node_modules/firebase-admin/lib/utils/error.js @@ -0,0 +1,1086 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InstanceIdClientErrorCode = exports.InstallationsClientErrorCode = exports.MessagingClientErrorCode = exports.AuthClientErrorCode = exports.AppErrorCodes = exports.FirebaseProjectManagementError = exports.FirebaseMessagingSessionError = exports.FirebaseMessagingError = exports.FirebaseInstallationsError = exports.FirebaseInstanceIdError = exports.FirebaseFirestoreError = exports.FirebaseDatabaseError = exports.FirebaseAuthError = exports.FirebaseAppError = exports.PrefixedFirebaseError = exports.FirebaseError = void 0; +const deep_copy_1 = require("../utils/deep-copy"); +/** + * Firebase error code structure. This extends Error. + */ +class FirebaseError extends Error { + /** + * @param errorInfo - The error information (code and message). + * @constructor + * @internal + */ + constructor(errorInfo) { + super(errorInfo.message); + this.errorInfo = errorInfo; + /* tslint:disable:max-line-length */ + // Set the prototype explicitly. See the following link for more details: + // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work + /* tslint:enable:max-line-length */ + this.__proto__ = FirebaseError.prototype; + } + /** @returns The error code. */ + get code() { + return this.errorInfo?.code; + } + /** @returns The error message. */ + get message() { + return this.errorInfo?.message; + } + /** @returns The object representation of the error. */ + toJSON() { + return { + code: this.code, + message: this.message, + }; + } +} +exports.FirebaseError = FirebaseError; +/** + * A FirebaseError with a prefix in front of the error code. + */ +class PrefixedFirebaseError extends FirebaseError { + /** + * @param codePrefix - The prefix to apply to the error code. + * @param code - The error code. + * @param message - The error message. + * @constructor + * @internal + */ + constructor(codePrefix, code, message) { + super({ + code: `${codePrefix}/${code}`, + message, + }); + this.codePrefix = codePrefix; + /* tslint:disable:max-line-length */ + // Set the prototype explicitly. See the following link for more details: + // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work + /* tslint:enable:max-line-length */ + this.__proto__ = PrefixedFirebaseError.prototype; + } + /** + * Allows the error type to be checked without needing to know implementation details + * of the code prefixing. + * + * @param code - The non-prefixed error code to test against. + * @returns True if the code matches, false otherwise. + */ + hasCode(code) { + return `${this.codePrefix}/${code}` === this.code; + } +} +exports.PrefixedFirebaseError = PrefixedFirebaseError; +/** + * Firebase App error code structure. This extends PrefixedFirebaseError. + */ +class FirebaseAppError extends PrefixedFirebaseError { + /** + * @param code - The error code. + * @param message - The error message. + * @constructor + * @internal + */ + constructor(code, message) { + super('app', code, message); + /* tslint:disable:max-line-length */ + // Set the prototype explicitly. See the following link for more details: + // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work + /* tslint:enable:max-line-length */ + this.__proto__ = FirebaseAppError.prototype; + } +} +exports.FirebaseAppError = FirebaseAppError; +/** + * Firebase Auth error code structure. This extends PrefixedFirebaseError. + */ +class FirebaseAuthError extends PrefixedFirebaseError { + /** + * Creates the developer-facing error corresponding to the backend error code. + * + * @param serverErrorCode - The server error code. + * @param [message] The error message. The default message is used + * if not provided. + * @param [rawServerResponse] The error's raw server response. + * @returns The corresponding developer-facing error. + * @internal + */ + static fromServerError(serverErrorCode, message, rawServerResponse) { + // serverErrorCode could contain additional details: + // ERROR_CODE : Detailed message which can also contain colons + const colonSeparator = (serverErrorCode || '').indexOf(':'); + let customMessage = null; + if (colonSeparator !== -1) { + customMessage = serverErrorCode.substring(colonSeparator + 1).trim(); + serverErrorCode = serverErrorCode.substring(0, colonSeparator).trim(); + } + // If not found, default to internal error. + const clientCodeKey = AUTH_SERVER_TO_CLIENT_CODE[serverErrorCode] || 'INTERNAL_ERROR'; + const error = (0, deep_copy_1.deepCopy)(AuthClientErrorCode[clientCodeKey]); + // Server detailed message should have highest priority. + error.message = customMessage || message || error.message; + if (clientCodeKey === 'INTERNAL_ERROR' && typeof rawServerResponse !== 'undefined') { + try { + error.message += ` Raw server response: "${JSON.stringify(rawServerResponse)}"`; + } + catch (e) { + // Ignore JSON parsing error. + } + } + return new FirebaseAuthError(error); + } + /** + * @param info - The error code info. + * @param message - The error message. This will override the default message if provided. + * @constructor + * @internal + */ + constructor(info, message) { + // Override default message if custom message provided. + super('auth', info.code, message || info.message); + /* tslint:disable:max-line-length */ + // Set the prototype explicitly. See the following link for more details: + // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work + /* tslint:enable:max-line-length */ + this.__proto__ = FirebaseAuthError.prototype; + } +} +exports.FirebaseAuthError = FirebaseAuthError; +/** + * Firebase Database error code structure. This extends FirebaseError. + */ +class FirebaseDatabaseError extends FirebaseError { + /** + * @param info - The error code info. + * @param message - The error message. This will override the default + * message if provided. + * @constructor + * @internal + */ + constructor(info, message) { + // Override default message if custom message provided. + super({ code: 'database/' + info.code, message: message || info.message }); + } +} +exports.FirebaseDatabaseError = FirebaseDatabaseError; +/** + * Firebase Firestore error code structure. This extends FirebaseError. + */ +class FirebaseFirestoreError extends FirebaseError { + /** + * @param info - The error code info. + * @param message - The error message. This will override the default + * message if provided. + * @constructor + * @internal + */ + constructor(info, message) { + // Override default message if custom message provided. + super({ code: 'firestore/' + info.code, message: message || info.message }); + } +} +exports.FirebaseFirestoreError = FirebaseFirestoreError; +/** + * Firebase instance ID error code structure. This extends FirebaseError. + */ +class FirebaseInstanceIdError extends FirebaseError { + /** + * + * @param info - The error code info. + * @param message - The error message. This will override the default + * message if provided. + * @constructor + * @internal + */ + constructor(info, message) { + // Override default message if custom message provided. + super({ code: 'instance-id/' + info.code, message: message || info.message }); + this.__proto__ = FirebaseInstanceIdError.prototype; + } +} +exports.FirebaseInstanceIdError = FirebaseInstanceIdError; +/** + * Firebase Installations service error code structure. This extends `FirebaseError`. + */ +class FirebaseInstallationsError extends FirebaseError { + /** + * + * @param info - The error code info. + * @param message - The error message. This will override the default + * message if provided. + * @constructor + * @internal + */ + constructor(info, message) { + // Override default message if custom message provided. + super({ code: 'installations/' + info.code, message: message || info.message }); + this.__proto__ = FirebaseInstallationsError.prototype; + } +} +exports.FirebaseInstallationsError = FirebaseInstallationsError; +/** + * Firebase Messaging error code structure. This extends PrefixedFirebaseError. + */ +class FirebaseMessagingError extends PrefixedFirebaseError { + /** + * Creates the developer-facing error corresponding to the backend error code. + * + * @param serverErrorCode - The server error code. + * @param [message] The error message. The default message is used + * if not provided. + * @param [rawServerResponse] The error's raw server response. + * @returns The corresponding developer-facing error. + * @internal + */ + static fromServerError(serverErrorCode, message, rawServerResponse) { + // If not found, default to unknown error. + let clientCodeKey = 'UNKNOWN_ERROR'; + if (serverErrorCode && serverErrorCode in MESSAGING_SERVER_TO_CLIENT_CODE) { + clientCodeKey = MESSAGING_SERVER_TO_CLIENT_CODE[serverErrorCode]; + } + const error = (0, deep_copy_1.deepCopy)(MessagingClientErrorCode[clientCodeKey]); + error.message = message || error.message; + if (clientCodeKey === 'UNKNOWN_ERROR' && typeof rawServerResponse !== 'undefined') { + try { + error.message += ` Raw server response: "${JSON.stringify(rawServerResponse)}"`; + } + catch (e) { + // Ignore JSON parsing error. + } + } + return new FirebaseMessagingError(error); + } + /** + * @internal + */ + static fromTopicManagementServerError(serverErrorCode, message, rawServerResponse) { + // If not found, default to unknown error. + const clientCodeKey = TOPIC_MGT_SERVER_TO_CLIENT_CODE[serverErrorCode] || 'UNKNOWN_ERROR'; + const error = (0, deep_copy_1.deepCopy)(MessagingClientErrorCode[clientCodeKey]); + error.message = message || error.message; + if (clientCodeKey === 'UNKNOWN_ERROR' && typeof rawServerResponse !== 'undefined') { + try { + error.message += ` Raw server response: "${JSON.stringify(rawServerResponse)}"`; + } + catch (e) { + // Ignore JSON parsing error. + } + } + return new FirebaseMessagingError(error); + } + /** + * + * @param info - The error code info. + * @param message - The error message. This will override the default message if provided. + * @constructor + * @internal + */ + constructor(info, message) { + // Override default message if custom message provided. + super('messaging', info.code, message || info.message); + /* tslint:disable:max-line-length */ + // Set the prototype explicitly. See the following link for more details: + // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work + /* tslint:enable:max-line-length */ + this.__proto__ = FirebaseMessagingError.prototype; + } +} +exports.FirebaseMessagingError = FirebaseMessagingError; +class FirebaseMessagingSessionError extends FirebaseMessagingError { + /** + * + * @param info - The error code info. + * @param message - The error message. This will override the default message if provided. + * @param pendingBatchResponse - BatchResponse for pending messages when session error occured. + * @constructor + * @internal + */ + constructor(info, message, pendingBatchResponse) { + // Override default message if custom message provided. + super(info, message || info.message); + this.pendingBatchResponse = pendingBatchResponse; + /* tslint:disable:max-line-length */ + // Set the prototype explicitly. See the following link for more details: + // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work + /* tslint:enable:max-line-length */ + this.__proto__ = FirebaseMessagingSessionError.prototype; + } + /** @returns The object representation of the error. */ + toJSON() { + return { + code: this.code, + message: this.message, + pendingBatchResponse: this.pendingBatchResponse, + }; + } +} +exports.FirebaseMessagingSessionError = FirebaseMessagingSessionError; +/** + * Firebase project management error code structure. This extends PrefixedFirebaseError. + */ +class FirebaseProjectManagementError extends PrefixedFirebaseError { + /** + * @param code - The error code. + * @param message - The error message. + * @constructor + * @internal + */ + constructor(code, message) { + super('project-management', code, message); + /* tslint:disable:max-line-length */ + // Set the prototype explicitly. See the following link for more details: + // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work + /* tslint:enable:max-line-length */ + this.__proto__ = FirebaseProjectManagementError.prototype; + } +} +exports.FirebaseProjectManagementError = FirebaseProjectManagementError; +/** + * App client error codes and their default messages. + */ +class AppErrorCodes { +} +exports.AppErrorCodes = AppErrorCodes; +AppErrorCodes.APP_DELETED = 'app-deleted'; +AppErrorCodes.DUPLICATE_APP = 'duplicate-app'; +AppErrorCodes.INVALID_ARGUMENT = 'invalid-argument'; +AppErrorCodes.INTERNAL_ERROR = 'internal-error'; +AppErrorCodes.INVALID_APP_NAME = 'invalid-app-name'; +AppErrorCodes.INVALID_APP_OPTIONS = 'invalid-app-options'; +AppErrorCodes.INVALID_CREDENTIAL = 'invalid-credential'; +AppErrorCodes.NETWORK_ERROR = 'network-error'; +AppErrorCodes.NETWORK_TIMEOUT = 'network-timeout'; +AppErrorCodes.NO_APP = 'no-app'; +AppErrorCodes.UNABLE_TO_PARSE_RESPONSE = 'unable-to-parse-response'; +/** + * Auth client error codes and their default messages. + */ +class AuthClientErrorCode { +} +exports.AuthClientErrorCode = AuthClientErrorCode; +AuthClientErrorCode.AUTH_BLOCKING_TOKEN_EXPIRED = { + code: 'auth-blocking-token-expired', + message: 'The provided Firebase Auth Blocking token is expired.', +}; +AuthClientErrorCode.BILLING_NOT_ENABLED = { + code: 'billing-not-enabled', + message: 'Feature requires billing to be enabled.', +}; +AuthClientErrorCode.CLAIMS_TOO_LARGE = { + code: 'claims-too-large', + message: 'Developer claims maximum payload size exceeded.', +}; +AuthClientErrorCode.CONFIGURATION_EXISTS = { + code: 'configuration-exists', + message: 'A configuration already exists with the provided identifier.', +}; +AuthClientErrorCode.CONFIGURATION_NOT_FOUND = { + code: 'configuration-not-found', + message: 'There is no configuration corresponding to the provided identifier.', +}; +AuthClientErrorCode.ID_TOKEN_EXPIRED = { + code: 'id-token-expired', + message: 'The provided Firebase ID token is expired.', +}; +AuthClientErrorCode.INVALID_ARGUMENT = { + code: 'argument-error', + message: 'Invalid argument provided.', +}; +AuthClientErrorCode.INVALID_CONFIG = { + code: 'invalid-config', + message: 'The provided configuration is invalid.', +}; +AuthClientErrorCode.EMAIL_ALREADY_EXISTS = { + code: 'email-already-exists', + message: 'The email address is already in use by another account.', +}; +AuthClientErrorCode.EMAIL_NOT_FOUND = { + code: 'email-not-found', + message: 'There is no user record corresponding to the provided email.', +}; +AuthClientErrorCode.FORBIDDEN_CLAIM = { + code: 'reserved-claim', + message: 'The specified developer claim is reserved and cannot be specified.', +}; +AuthClientErrorCode.INVALID_ID_TOKEN = { + code: 'invalid-id-token', + message: 'The provided ID token is not a valid Firebase ID token.', +}; +AuthClientErrorCode.ID_TOKEN_REVOKED = { + code: 'id-token-revoked', + message: 'The Firebase ID token has been revoked.', +}; +AuthClientErrorCode.INTERNAL_ERROR = { + code: 'internal-error', + message: 'An internal error has occurred.', +}; +AuthClientErrorCode.INVALID_CLAIMS = { + code: 'invalid-claims', + message: 'The provided custom claim attributes are invalid.', +}; +AuthClientErrorCode.INVALID_CONTINUE_URI = { + code: 'invalid-continue-uri', + message: 'The continue URL must be a valid URL string.', +}; +AuthClientErrorCode.INVALID_CREATION_TIME = { + code: 'invalid-creation-time', + message: 'The creation time must be a valid UTC date string.', +}; +AuthClientErrorCode.INVALID_CREDENTIAL = { + code: 'invalid-credential', + message: 'Invalid credential object provided.', +}; +AuthClientErrorCode.INVALID_DISABLED_FIELD = { + code: 'invalid-disabled-field', + message: 'The disabled field must be a boolean.', +}; +AuthClientErrorCode.INVALID_DISPLAY_NAME = { + code: 'invalid-display-name', + message: 'The displayName field must be a valid string.', +}; +AuthClientErrorCode.INVALID_DYNAMIC_LINK_DOMAIN = { + code: 'invalid-dynamic-link-domain', + message: 'The provided dynamic link domain is not configured or authorized ' + + 'for the current project.', +}; +AuthClientErrorCode.INVALID_HOSTING_LINK_DOMAIN = { + code: 'invalid-hosting-link-domain', + message: 'The provided hosting link domain is not configured in Firebase ' + + 'Hosting or is not owned by the current project.', +}; +AuthClientErrorCode.INVALID_EMAIL_VERIFIED = { + code: 'invalid-email-verified', + message: 'The emailVerified field must be a boolean.', +}; +AuthClientErrorCode.INVALID_EMAIL = { + code: 'invalid-email', + message: 'The email address is improperly formatted.', +}; +AuthClientErrorCode.INVALID_NEW_EMAIL = { + code: 'invalid-new-email', + message: 'The new email address is improperly formatted.', +}; +AuthClientErrorCode.INVALID_ENROLLED_FACTORS = { + code: 'invalid-enrolled-factors', + message: 'The enrolled factors must be a valid array of MultiFactorInfo objects.', +}; +AuthClientErrorCode.INVALID_ENROLLMENT_TIME = { + code: 'invalid-enrollment-time', + message: 'The second factor enrollment time must be a valid UTC date string.', +}; +AuthClientErrorCode.INVALID_HASH_ALGORITHM = { + code: 'invalid-hash-algorithm', + message: 'The hash algorithm must match one of the strings in the list of ' + + 'supported algorithms.', +}; +AuthClientErrorCode.INVALID_HASH_BLOCK_SIZE = { + code: 'invalid-hash-block-size', + message: 'The hash block size must be a valid number.', +}; +AuthClientErrorCode.INVALID_HASH_DERIVED_KEY_LENGTH = { + code: 'invalid-hash-derived-key-length', + message: 'The hash derived key length must be a valid number.', +}; +AuthClientErrorCode.INVALID_HASH_KEY = { + code: 'invalid-hash-key', + message: 'The hash key must a valid byte buffer.', +}; +AuthClientErrorCode.INVALID_HASH_MEMORY_COST = { + code: 'invalid-hash-memory-cost', + message: 'The hash memory cost must be a valid number.', +}; +AuthClientErrorCode.INVALID_HASH_PARALLELIZATION = { + code: 'invalid-hash-parallelization', + message: 'The hash parallelization must be a valid number.', +}; +AuthClientErrorCode.INVALID_HASH_ROUNDS = { + code: 'invalid-hash-rounds', + message: 'The hash rounds must be a valid number.', +}; +AuthClientErrorCode.INVALID_HASH_SALT_SEPARATOR = { + code: 'invalid-hash-salt-separator', + message: 'The hashing algorithm salt separator field must be a valid byte buffer.', +}; +AuthClientErrorCode.INVALID_LAST_SIGN_IN_TIME = { + code: 'invalid-last-sign-in-time', + message: 'The last sign-in time must be a valid UTC date string.', +}; +AuthClientErrorCode.INVALID_NAME = { + code: 'invalid-name', + message: 'The resource name provided is invalid.', +}; +AuthClientErrorCode.INVALID_OAUTH_CLIENT_ID = { + code: 'invalid-oauth-client-id', + message: 'The provided OAuth client ID is invalid.', +}; +AuthClientErrorCode.INVALID_PAGE_TOKEN = { + code: 'invalid-page-token', + message: 'The page token must be a valid non-empty string.', +}; +AuthClientErrorCode.INVALID_PASSWORD = { + code: 'invalid-password', + message: 'The password must be a string with at least 6 characters.', +}; +AuthClientErrorCode.INVALID_PASSWORD_HASH = { + code: 'invalid-password-hash', + message: 'The password hash must be a valid byte buffer.', +}; +AuthClientErrorCode.INVALID_PASSWORD_SALT = { + code: 'invalid-password-salt', + message: 'The password salt must be a valid byte buffer.', +}; +AuthClientErrorCode.INVALID_PHONE_NUMBER = { + code: 'invalid-phone-number', + message: 'The phone number must be a non-empty E.164 standard compliant identifier ' + + 'string.', +}; +AuthClientErrorCode.INVALID_PHOTO_URL = { + code: 'invalid-photo-url', + message: 'The photoURL field must be a valid URL.', +}; +AuthClientErrorCode.INVALID_PROJECT_ID = { + code: 'invalid-project-id', + message: 'Invalid parent project. Either parent project doesn\'t exist or didn\'t enable multi-tenancy.', +}; +AuthClientErrorCode.INVALID_PROVIDER_DATA = { + code: 'invalid-provider-data', + message: 'The providerData must be a valid array of UserInfo objects.', +}; +AuthClientErrorCode.INVALID_PROVIDER_ID = { + code: 'invalid-provider-id', + message: 'The providerId must be a valid supported provider identifier string.', +}; +AuthClientErrorCode.INVALID_PROVIDER_UID = { + code: 'invalid-provider-uid', + message: 'The providerUid must be a valid provider uid string.', +}; +AuthClientErrorCode.INVALID_OAUTH_RESPONSETYPE = { + code: 'invalid-oauth-responsetype', + message: 'Only exactly one OAuth responseType should be set to true.', +}; +AuthClientErrorCode.INVALID_SESSION_COOKIE_DURATION = { + code: 'invalid-session-cookie-duration', + message: 'The session cookie duration must be a valid number in milliseconds ' + + 'between 5 minutes and 2 weeks.', +}; +AuthClientErrorCode.INVALID_TENANT_ID = { + code: 'invalid-tenant-id', + message: 'The tenant ID must be a valid non-empty string.', +}; +AuthClientErrorCode.INVALID_TENANT_TYPE = { + code: 'invalid-tenant-type', + message: 'Tenant type must be either "full_service" or "lightweight".', +}; +AuthClientErrorCode.INVALID_TESTING_PHONE_NUMBER = { + code: 'invalid-testing-phone-number', + message: 'Invalid testing phone number or invalid test code provided.', +}; +AuthClientErrorCode.INVALID_UID = { + code: 'invalid-uid', + message: 'The uid must be a non-empty string with at most 128 characters.', +}; +AuthClientErrorCode.INVALID_USER_IMPORT = { + code: 'invalid-user-import', + message: 'The user record to import is invalid.', +}; +AuthClientErrorCode.INVALID_TOKENS_VALID_AFTER_TIME = { + code: 'invalid-tokens-valid-after-time', + message: 'The tokensValidAfterTime must be a valid UTC number in seconds.', +}; +AuthClientErrorCode.MISMATCHING_TENANT_ID = { + code: 'mismatching-tenant-id', + message: 'User tenant ID does not match with the current TenantAwareAuth tenant ID.', +}; +AuthClientErrorCode.MISSING_ANDROID_PACKAGE_NAME = { + code: 'missing-android-pkg-name', + message: 'An Android Package Name must be provided if the Android App is ' + + 'required to be installed.', +}; +AuthClientErrorCode.MISSING_CONFIG = { + code: 'missing-config', + message: 'The provided configuration is missing required attributes.', +}; +AuthClientErrorCode.MISSING_CONTINUE_URI = { + code: 'missing-continue-uri', + message: 'A valid continue URL must be provided in the request.', +}; +AuthClientErrorCode.MISSING_DISPLAY_NAME = { + code: 'missing-display-name', + message: 'The resource being created or edited is missing a valid display name.', +}; +AuthClientErrorCode.MISSING_EMAIL = { + code: 'missing-email', + message: 'The email is required for the specified action. For example, a multi-factor user ' + + 'requires a verified email.', +}; +AuthClientErrorCode.MISSING_IOS_BUNDLE_ID = { + code: 'missing-ios-bundle-id', + message: 'The request is missing an iOS Bundle ID.', +}; +AuthClientErrorCode.MISSING_ISSUER = { + code: 'missing-issuer', + message: 'The OAuth/OIDC configuration issuer must not be empty.', +}; +AuthClientErrorCode.MISSING_HASH_ALGORITHM = { + code: 'missing-hash-algorithm', + message: 'Importing users with password hashes requires that the hashing ' + + 'algorithm and its parameters be provided.', +}; +AuthClientErrorCode.MISSING_OAUTH_CLIENT_ID = { + code: 'missing-oauth-client-id', + message: 'The OAuth/OIDC configuration client ID must not be empty.', +}; +AuthClientErrorCode.MISSING_OAUTH_CLIENT_SECRET = { + code: 'missing-oauth-client-secret', + message: 'The OAuth configuration client secret is required to enable OIDC code flow.', +}; +AuthClientErrorCode.MISSING_PROVIDER_ID = { + code: 'missing-provider-id', + message: 'A valid provider ID must be provided in the request.', +}; +AuthClientErrorCode.MISSING_SAML_RELYING_PARTY_CONFIG = { + code: 'missing-saml-relying-party-config', + message: 'The SAML configuration provided is missing a relying party configuration.', +}; +AuthClientErrorCode.MAXIMUM_TEST_PHONE_NUMBER_EXCEEDED = { + code: 'test-phone-number-limit-exceeded', + message: 'The maximum allowed number of test phone number / code pairs has been exceeded.', +}; +AuthClientErrorCode.MAXIMUM_USER_COUNT_EXCEEDED = { + code: 'maximum-user-count-exceeded', + message: 'The maximum allowed number of users to import has been exceeded.', +}; +AuthClientErrorCode.MISSING_UID = { + code: 'missing-uid', + message: 'A uid identifier is required for the current operation.', +}; +AuthClientErrorCode.OPERATION_NOT_ALLOWED = { + code: 'operation-not-allowed', + message: 'The given sign-in provider is disabled for this Firebase project. ' + + 'Enable it in the Firebase console, under the sign-in method tab of the ' + + 'Auth section.', +}; +AuthClientErrorCode.PHONE_NUMBER_ALREADY_EXISTS = { + code: 'phone-number-already-exists', + message: 'The user with the provided phone number already exists.', +}; +AuthClientErrorCode.PROJECT_NOT_FOUND = { + code: 'project-not-found', + message: 'No Firebase project was found for the provided credential.', +}; +AuthClientErrorCode.INSUFFICIENT_PERMISSION = { + code: 'insufficient-permission', + message: 'Credential implementation provided to initializeApp() via the "credential" property ' + + 'has insufficient permission to access the requested resource. See ' + + 'https://firebase.google.com/docs/admin/setup for details on how to authenticate this SDK ' + + 'with appropriate permissions.', +}; +AuthClientErrorCode.QUOTA_EXCEEDED = { + code: 'quota-exceeded', + message: 'The project quota for the specified operation has been exceeded.', +}; +AuthClientErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED = { + code: 'second-factor-limit-exceeded', + message: 'The maximum number of allowed second factors on a user has been exceeded.', +}; +AuthClientErrorCode.SECOND_FACTOR_UID_ALREADY_EXISTS = { + code: 'second-factor-uid-already-exists', + message: 'The specified second factor "uid" already exists.', +}; +AuthClientErrorCode.SESSION_COOKIE_EXPIRED = { + code: 'session-cookie-expired', + message: 'The Firebase session cookie is expired.', +}; +AuthClientErrorCode.SESSION_COOKIE_REVOKED = { + code: 'session-cookie-revoked', + message: 'The Firebase session cookie has been revoked.', +}; +AuthClientErrorCode.TENANT_NOT_FOUND = { + code: 'tenant-not-found', + message: 'There is no tenant corresponding to the provided identifier.', +}; +AuthClientErrorCode.UID_ALREADY_EXISTS = { + code: 'uid-already-exists', + message: 'The user with the provided uid already exists.', +}; +AuthClientErrorCode.UNAUTHORIZED_DOMAIN = { + code: 'unauthorized-continue-uri', + message: 'The domain of the continue URL is not whitelisted. Whitelist the domain in the ' + + 'Firebase console.', +}; +AuthClientErrorCode.UNSUPPORTED_FIRST_FACTOR = { + code: 'unsupported-first-factor', + message: 'A multi-factor user requires a supported first factor.', +}; +AuthClientErrorCode.UNSUPPORTED_SECOND_FACTOR = { + code: 'unsupported-second-factor', + message: 'The request specified an unsupported type of second factor.', +}; +AuthClientErrorCode.UNSUPPORTED_TENANT_OPERATION = { + code: 'unsupported-tenant-operation', + message: 'This operation is not supported in a multi-tenant context.', +}; +AuthClientErrorCode.UNVERIFIED_EMAIL = { + code: 'unverified-email', + message: 'A verified email is required for the specified action. For example, a multi-factor user ' + + 'requires a verified email.', +}; +AuthClientErrorCode.USER_NOT_FOUND = { + code: 'user-not-found', + message: 'There is no user record corresponding to the provided identifier.', +}; +AuthClientErrorCode.NOT_FOUND = { + code: 'not-found', + message: 'The requested resource was not found.', +}; +AuthClientErrorCode.USER_DISABLED = { + code: 'user-disabled', + message: 'The user record is disabled.', +}; +AuthClientErrorCode.USER_NOT_DISABLED = { + code: 'user-not-disabled', + message: 'The user must be disabled in order to bulk delete it (or you must pass force=true).', +}; +AuthClientErrorCode.INVALID_RECAPTCHA_ACTION = { + code: 'invalid-recaptcha-action', + message: 'reCAPTCHA action must be "BLOCK".' +}; +AuthClientErrorCode.INVALID_RECAPTCHA_ENFORCEMENT_STATE = { + code: 'invalid-recaptcha-enforcement-state', + message: 'reCAPTCHA enforcement state must be either "OFF", "AUDIT" or "ENFORCE".' +}; +AuthClientErrorCode.RECAPTCHA_NOT_ENABLED = { + code: 'racaptcha-not-enabled', + message: 'reCAPTCHA enterprise is not enabled.' +}; +/** + * Messaging client error codes and their default messages. + */ +class MessagingClientErrorCode { +} +exports.MessagingClientErrorCode = MessagingClientErrorCode; +MessagingClientErrorCode.INVALID_ARGUMENT = { + code: 'invalid-argument', + message: 'Invalid argument provided.', +}; +MessagingClientErrorCode.INVALID_RECIPIENT = { + code: 'invalid-recipient', + message: 'Invalid message recipient provided.', +}; +MessagingClientErrorCode.INVALID_PAYLOAD = { + code: 'invalid-payload', + message: 'Invalid message payload provided.', +}; +MessagingClientErrorCode.INVALID_DATA_PAYLOAD_KEY = { + code: 'invalid-data-payload-key', + message: 'The data message payload contains an invalid key. See the reference documentation ' + + 'for the DataMessagePayload type for restricted keys.', +}; +MessagingClientErrorCode.PAYLOAD_SIZE_LIMIT_EXCEEDED = { + code: 'payload-size-limit-exceeded', + message: 'The provided message payload exceeds the FCM size limits. See the error documentation ' + + 'for more details.', +}; +MessagingClientErrorCode.INVALID_OPTIONS = { + code: 'invalid-options', + message: 'Invalid message options provided.', +}; +MessagingClientErrorCode.INVALID_REGISTRATION_TOKEN = { + code: 'invalid-registration-token', + message: 'Invalid registration token provided. Make sure it matches the registration token ' + + 'the client app receives from registering with FCM.', +}; +MessagingClientErrorCode.REGISTRATION_TOKEN_NOT_REGISTERED = { + code: 'registration-token-not-registered', + message: 'The provided registration token is not registered. A previously valid registration ' + + 'token can be unregistered for a variety of reasons. See the error documentation for more ' + + 'details. Remove this registration token and stop using it to send messages.', +}; +MessagingClientErrorCode.MISMATCHED_CREDENTIAL = { + code: 'mismatched-credential', + message: 'The credential used to authenticate this SDK does not have permission to send ' + + 'messages to the device corresponding to the provided registration token. Make sure the ' + + 'credential and registration token both belong to the same Firebase project.', +}; +MessagingClientErrorCode.INVALID_PACKAGE_NAME = { + code: 'invalid-package-name', + message: 'The message was addressed to a registration token whose package name does not match ' + + 'the provided "restrictedPackageName" option.', +}; +MessagingClientErrorCode.DEVICE_MESSAGE_RATE_EXCEEDED = { + code: 'device-message-rate-exceeded', + message: 'The rate of messages to a particular device is too high. Reduce the number of ' + + 'messages sent to this device and do not immediately retry sending to this device.', +}; +MessagingClientErrorCode.TOPICS_MESSAGE_RATE_EXCEEDED = { + code: 'topics-message-rate-exceeded', + message: 'The rate of messages to subscribers to a particular topic is too high. Reduce the ' + + 'number of messages sent for this topic, and do not immediately retry sending to this topic.', +}; +MessagingClientErrorCode.MESSAGE_RATE_EXCEEDED = { + code: 'message-rate-exceeded', + message: 'Sending limit exceeded for the message target.', +}; +MessagingClientErrorCode.THIRD_PARTY_AUTH_ERROR = { + code: 'third-party-auth-error', + message: 'A message targeted to an iOS device could not be sent because the required APNs ' + + 'SSL certificate was not uploaded or has expired. Check the validity of your development ' + + 'and production certificates.', +}; +MessagingClientErrorCode.TOO_MANY_TOPICS = { + code: 'too-many-topics', + message: 'The maximum number of topics the provided registration token can be subscribed to ' + + 'has been exceeded.', +}; +MessagingClientErrorCode.AUTHENTICATION_ERROR = { + code: 'authentication-error', + message: 'An error occurred when trying to authenticate to the FCM servers. Make sure the ' + + 'credential used to authenticate this SDK has the proper permissions. See ' + + 'https://firebase.google.com/docs/admin/setup for setup instructions.', +}; +MessagingClientErrorCode.SERVER_UNAVAILABLE = { + code: 'server-unavailable', + message: 'The FCM server could not process the request in time. See the error documentation ' + + 'for more details.', +}; +MessagingClientErrorCode.INTERNAL_ERROR = { + code: 'internal-error', + message: 'An internal error has occurred. Please retry the request.', +}; +MessagingClientErrorCode.UNKNOWN_ERROR = { + code: 'unknown-error', + message: 'An unknown server error was returned.', +}; +class InstallationsClientErrorCode { +} +exports.InstallationsClientErrorCode = InstallationsClientErrorCode; +InstallationsClientErrorCode.INVALID_ARGUMENT = { + code: 'invalid-argument', + message: 'Invalid argument provided.', +}; +InstallationsClientErrorCode.INVALID_PROJECT_ID = { + code: 'invalid-project-id', + message: 'Invalid project ID provided.', +}; +InstallationsClientErrorCode.INVALID_INSTALLATION_ID = { + code: 'invalid-installation-id', + message: 'Invalid installation ID provided.', +}; +InstallationsClientErrorCode.API_ERROR = { + code: 'api-error', + message: 'Installation ID API call failed.', +}; +class InstanceIdClientErrorCode extends InstallationsClientErrorCode { +} +exports.InstanceIdClientErrorCode = InstanceIdClientErrorCode; +InstanceIdClientErrorCode.INVALID_INSTANCE_ID = { + code: 'invalid-instance-id', + message: 'Invalid instance ID provided.', +}; +/** @const {ServerToClientCode} Auth server to client enum error codes. */ +const AUTH_SERVER_TO_CLIENT_CODE = { + // Feature being configured or used requires a billing account. + BILLING_NOT_ENABLED: 'BILLING_NOT_ENABLED', + // Claims payload is too large. + CLAIMS_TOO_LARGE: 'CLAIMS_TOO_LARGE', + // Configuration being added already exists. + CONFIGURATION_EXISTS: 'CONFIGURATION_EXISTS', + // Configuration not found. + CONFIGURATION_NOT_FOUND: 'CONFIGURATION_NOT_FOUND', + // Provided credential has insufficient permissions. + INSUFFICIENT_PERMISSION: 'INSUFFICIENT_PERMISSION', + // Provided configuration has invalid fields. + INVALID_CONFIG: 'INVALID_CONFIG', + // Provided configuration identifier is invalid. + INVALID_CONFIG_ID: 'INVALID_PROVIDER_ID', + // ActionCodeSettings missing continue URL. + INVALID_CONTINUE_URI: 'INVALID_CONTINUE_URI', + // Dynamic link domain in provided ActionCodeSettings is not authorized. + INVALID_DYNAMIC_LINK_DOMAIN: 'INVALID_DYNAMIC_LINK_DOMAIN', + // Hosting link domain in provided ActionCodeSettings is not owned by the current project. + INVALID_HOSTING_LINK_DOMAIN: 'INVALID_HOSTING_LINK_DOMAIN', + // uploadAccount provides an email that already exists. + DUPLICATE_EMAIL: 'EMAIL_ALREADY_EXISTS', + // uploadAccount provides a localId that already exists. + DUPLICATE_LOCAL_ID: 'UID_ALREADY_EXISTS', + // Request specified a multi-factor enrollment ID that already exists. + DUPLICATE_MFA_ENROLLMENT_ID: 'SECOND_FACTOR_UID_ALREADY_EXISTS', + // setAccountInfo email already exists. + EMAIL_EXISTS: 'EMAIL_ALREADY_EXISTS', + // /accounts:sendOobCode for password reset when user is not found. + EMAIL_NOT_FOUND: 'EMAIL_NOT_FOUND', + // Reserved claim name. + FORBIDDEN_CLAIM: 'FORBIDDEN_CLAIM', + // Invalid claims provided. + INVALID_CLAIMS: 'INVALID_CLAIMS', + // Invalid session cookie duration. + INVALID_DURATION: 'INVALID_SESSION_COOKIE_DURATION', + // Invalid email provided. + INVALID_EMAIL: 'INVALID_EMAIL', + // Invalid new email provided. + INVALID_NEW_EMAIL: 'INVALID_NEW_EMAIL', + // Invalid tenant display name. This can be thrown on CreateTenant and UpdateTenant. + INVALID_DISPLAY_NAME: 'INVALID_DISPLAY_NAME', + // Invalid ID token provided. + INVALID_ID_TOKEN: 'INVALID_ID_TOKEN', + // Invalid tenant/parent resource name. + INVALID_NAME: 'INVALID_NAME', + // OIDC configuration has an invalid OAuth client ID. + INVALID_OAUTH_CLIENT_ID: 'INVALID_OAUTH_CLIENT_ID', + // Invalid page token. + INVALID_PAGE_SELECTION: 'INVALID_PAGE_TOKEN', + // Invalid phone number. + INVALID_PHONE_NUMBER: 'INVALID_PHONE_NUMBER', + // Invalid agent project. Either agent project doesn't exist or didn't enable multi-tenancy. + INVALID_PROJECT_ID: 'INVALID_PROJECT_ID', + // Invalid provider ID. + INVALID_PROVIDER_ID: 'INVALID_PROVIDER_ID', + // Invalid service account. + INVALID_SERVICE_ACCOUNT: 'INVALID_SERVICE_ACCOUNT', + // Invalid testing phone number. + INVALID_TESTING_PHONE_NUMBER: 'INVALID_TESTING_PHONE_NUMBER', + // Invalid tenant type. + INVALID_TENANT_TYPE: 'INVALID_TENANT_TYPE', + // Missing Android package name. + MISSING_ANDROID_PACKAGE_NAME: 'MISSING_ANDROID_PACKAGE_NAME', + // Missing configuration. + MISSING_CONFIG: 'MISSING_CONFIG', + // Missing configuration identifier. + MISSING_CONFIG_ID: 'MISSING_PROVIDER_ID', + // Missing tenant display name: This can be thrown on CreateTenant and UpdateTenant. + MISSING_DISPLAY_NAME: 'MISSING_DISPLAY_NAME', + // Email is required for the specified action. For example a multi-factor user requires + // a verified email. + MISSING_EMAIL: 'MISSING_EMAIL', + // Missing iOS bundle ID. + MISSING_IOS_BUNDLE_ID: 'MISSING_IOS_BUNDLE_ID', + // Missing OIDC issuer. + MISSING_ISSUER: 'MISSING_ISSUER', + // No localId provided (deleteAccount missing localId). + MISSING_LOCAL_ID: 'MISSING_UID', + // OIDC configuration is missing an OAuth client ID. + MISSING_OAUTH_CLIENT_ID: 'MISSING_OAUTH_CLIENT_ID', + // Missing provider ID. + MISSING_PROVIDER_ID: 'MISSING_PROVIDER_ID', + // Missing SAML RP config. + MISSING_SAML_RELYING_PARTY_CONFIG: 'MISSING_SAML_RELYING_PARTY_CONFIG', + // Empty user list in uploadAccount. + MISSING_USER_ACCOUNT: 'MISSING_UID', + // Password auth disabled in console. + OPERATION_NOT_ALLOWED: 'OPERATION_NOT_ALLOWED', + // Provided credential has insufficient permissions. + PERMISSION_DENIED: 'INSUFFICIENT_PERMISSION', + // Phone number already exists. + PHONE_NUMBER_EXISTS: 'PHONE_NUMBER_ALREADY_EXISTS', + // Project not found. + PROJECT_NOT_FOUND: 'PROJECT_NOT_FOUND', + // In multi-tenancy context: project creation quota exceeded. + QUOTA_EXCEEDED: 'QUOTA_EXCEEDED', + // Currently only 5 second factors can be set on the same user. + SECOND_FACTOR_LIMIT_EXCEEDED: 'SECOND_FACTOR_LIMIT_EXCEEDED', + // Tenant not found. + TENANT_NOT_FOUND: 'TENANT_NOT_FOUND', + // Tenant ID mismatch. + TENANT_ID_MISMATCH: 'MISMATCHING_TENANT_ID', + // Token expired error. + TOKEN_EXPIRED: 'ID_TOKEN_EXPIRED', + // Continue URL provided in ActionCodeSettings has a domain that is not whitelisted. + UNAUTHORIZED_DOMAIN: 'UNAUTHORIZED_DOMAIN', + // A multi-factor user requires a supported first factor. + UNSUPPORTED_FIRST_FACTOR: 'UNSUPPORTED_FIRST_FACTOR', + // The request specified an unsupported type of second factor. + UNSUPPORTED_SECOND_FACTOR: 'UNSUPPORTED_SECOND_FACTOR', + // Operation is not supported in a multi-tenant context. + UNSUPPORTED_TENANT_OPERATION: 'UNSUPPORTED_TENANT_OPERATION', + // A verified email is required for the specified action. For example a multi-factor user + // requires a verified email. + UNVERIFIED_EMAIL: 'UNVERIFIED_EMAIL', + // User on which action is to be performed is not found. + USER_NOT_FOUND: 'USER_NOT_FOUND', + // User record is disabled. + USER_DISABLED: 'USER_DISABLED', + // Password provided is too weak. + WEAK_PASSWORD: 'INVALID_PASSWORD', + // Unrecognized reCAPTCHA action. + INVALID_RECAPTCHA_ACTION: 'INVALID_RECAPTCHA_ACTION', + // Unrecognized reCAPTCHA enforcement state. + INVALID_RECAPTCHA_ENFORCEMENT_STATE: 'INVALID_RECAPTCHA_ENFORCEMENT_STATE', + // reCAPTCHA is not enabled for account defender. + RECAPTCHA_NOT_ENABLED: 'RECAPTCHA_NOT_ENABLED' +}; +/** @const {ServerToClientCode} Messaging server to client enum error codes. */ +const MESSAGING_SERVER_TO_CLIENT_CODE = { + /* GENERIC ERRORS */ + // Generic invalid message parameter provided. + InvalidParameters: 'INVALID_ARGUMENT', + // Mismatched sender ID. + MismatchSenderId: 'MISMATCHED_CREDENTIAL', + // FCM server unavailable. + Unavailable: 'SERVER_UNAVAILABLE', + // FCM server internal error. + InternalServerError: 'INTERNAL_ERROR', + /* SEND ERRORS */ + // Invalid registration token format. + InvalidRegistration: 'INVALID_REGISTRATION_TOKEN', + // Registration token is not registered. + NotRegistered: 'REGISTRATION_TOKEN_NOT_REGISTERED', + // Registration token does not match restricted package name. + InvalidPackageName: 'INVALID_PACKAGE_NAME', + // Message payload size limit exceeded. + MessageTooBig: 'PAYLOAD_SIZE_LIMIT_EXCEEDED', + // Invalid key in the data message payload. + InvalidDataKey: 'INVALID_DATA_PAYLOAD_KEY', + // Invalid time to live option. + InvalidTtl: 'INVALID_OPTIONS', + // Device message rate exceeded. + DeviceMessageRateExceeded: 'DEVICE_MESSAGE_RATE_EXCEEDED', + // Topics message rate exceeded. + TopicsMessageRateExceeded: 'TOPICS_MESSAGE_RATE_EXCEEDED', + // Invalid APNs credentials. + InvalidApnsCredential: 'THIRD_PARTY_AUTH_ERROR', + /* FCM v1 canonical error codes */ + NOT_FOUND: 'REGISTRATION_TOKEN_NOT_REGISTERED', + PERMISSION_DENIED: 'MISMATCHED_CREDENTIAL', + RESOURCE_EXHAUSTED: 'MESSAGE_RATE_EXCEEDED', + UNAUTHENTICATED: 'THIRD_PARTY_AUTH_ERROR', + /* FCM v1 new error codes */ + APNS_AUTH_ERROR: 'THIRD_PARTY_AUTH_ERROR', + INTERNAL: 'INTERNAL_ERROR', + INVALID_ARGUMENT: 'INVALID_ARGUMENT', + QUOTA_EXCEEDED: 'MESSAGE_RATE_EXCEEDED', + SENDER_ID_MISMATCH: 'MISMATCHED_CREDENTIAL', + THIRD_PARTY_AUTH_ERROR: 'THIRD_PARTY_AUTH_ERROR', + UNAVAILABLE: 'SERVER_UNAVAILABLE', + UNREGISTERED: 'REGISTRATION_TOKEN_NOT_REGISTERED', + UNSPECIFIED_ERROR: 'UNKNOWN_ERROR', +}; +/** @const {ServerToClientCode} Topic management (IID) server to client enum error codes. */ +const TOPIC_MGT_SERVER_TO_CLIENT_CODE = { + /* TOPIC SUBSCRIPTION MANAGEMENT ERRORS */ + NOT_FOUND: 'REGISTRATION_TOKEN_NOT_REGISTERED', + INVALID_ARGUMENT: 'INVALID_REGISTRATION_TOKEN', + TOO_MANY_TOPICS: 'TOO_MANY_TOPICS', + RESOURCE_EXHAUSTED: 'TOO_MANY_TOPICS', + PERMISSION_DENIED: 'AUTHENTICATION_ERROR', + DEADLINE_EXCEEDED: 'SERVER_UNAVAILABLE', + INTERNAL: 'INTERNAL_ERROR', + UNKNOWN: 'UNKNOWN_ERROR', +}; diff --git a/node_modules/firebase-admin/lib/utils/index.d.ts b/node_modules/firebase-admin/lib/utils/index.d.ts new file mode 100644 index 0000000..2351969 --- /dev/null +++ b/node_modules/firebase-admin/lib/utils/index.d.ts @@ -0,0 +1,147 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { App } from '../app/index'; +export declare function getSdkVersion(): string; +export declare function getMetricsHeader(): string; +/** + * Renames properties on an object given a mapping from old to new property names. + * + * For example, this can be used to map underscore_cased properties to camelCase. + * + * @param obj - The object whose properties to rename. + * @param keyMap - The mapping from old to new property names. + */ +export declare function renameProperties(obj: { + [key: string]: any; +}, keyMap: { + [key: string]: string; +}): void; +/** + * Defines a new read-only property directly on an object and returns the object. + * + * @param obj - The object on which to define the property. + * @param prop - The name of the property to be defined or modified. + * @param value - The value associated with the property. + */ +export declare function addReadonlyGetter(obj: object, prop: string, value: any): void; +/** + * Returns the Google Cloud project ID associated with a Firebase app, if it's explicitly + * specified in either the Firebase app options, credentials or the local environment. + * Otherwise returns null. + * + * @param app - A Firebase app to get the project ID from. + * + * @returns A project ID string or null. + */ +export declare function getExplicitProjectId(app: App): string | null; +/** + * Determines the Google Cloud project ID associated with a Firebase app. This method + * first checks if a project ID is explicitly specified in either the Firebase app options, + * credentials or the local environment in that order. If no explicit project ID is + * configured, but the SDK has been initialized with ComputeEngineCredentials, this + * method attempts to discover the project ID from the local metadata service. + * + * @param app - A Firebase app to get the project ID from. + * + * @returns A project ID string or null. + */ +export declare function findProjectId(app: App): Promise; +/** + * Returns the service account email associated with a Firebase app, if it's explicitly + * specified in either the Firebase app options, credentials or the local environment. + * Otherwise returns null. + * + * @param app - A Firebase app to get the service account email from. + * + * @returns A service account email string or null. + */ +export declare function getExplicitServiceAccountEmail(app: App): string | null; +/** + * Determines the service account email associated with a Firebase app. This method first + * checks if a service account email is explicitly specified in either the Firebase app options, + * credentials or the local environment in that order. If no explicit service account email is + * configured, but the SDK has been initialized with ComputeEngineCredentials, this + * method attempts to discover the service account email from the local metadata service. + * + * @param app - A Firebase app to get the service account email from. + * + * @returns A service account email ID string or null. + */ +export declare function findServiceAccountEmail(app: App): Promise; +/** + * Encodes data using web-safe-base64. + * + * @param data - The raw data byte input. + * @returns The base64-encoded result. + */ +export declare function toWebSafeBase64(data: Buffer): string; +/** + * Formats a string of form 'project/{projectId}/{api}' and replaces + * with corresponding arguments {projectId: '1234', api: 'resource'} + * and returns output: 'project/1234/resource'. + * + * @param str - The original string where the param need to be + * replaced. + * @param params - The optional parameters to replace in the + * string. + * @returns The resulting formatted string. + */ +export declare function formatString(str: string, params?: object): string; +/** + * Generates the update mask for the provided object. + * Note this will ignore the last key with value undefined. + * + * @param obj - The object to generate the update mask for. + * @param terminalPaths - The optional map of keys for maximum paths to traverse. + * Nested objects beyond that path will be ignored. This is useful for + * keys with variable object values. + * @param root - The path so far. + * @returns The computed update mask list. + */ +export declare function generateUpdateMask(obj: any, terminalPaths?: string[], root?: string): string[]; +/** + * Transforms milliseconds to a protobuf Duration type string. + * Returns the duration in seconds with up to nine fractional + * digits, terminated by 's'. Example: "3 seconds 0 nano seconds as 3s, + * 3 seconds 1 nano seconds as 3.000000001s". + * + * @param milliseconds - The duration in milliseconds. + * @returns The resulting formatted string in seconds with up to nine fractional + * digits, terminated by 's'. + */ +export declare function transformMillisecondsToSecondsString(milliseconds: number): string; +/** + * Internal type to represent a resource name + */ +export type ParsedResource = { + projectId?: string; + locationId?: string; + resourceId: string; +}; +/** + * Parses the top level resources of a given resource name. + * Supports both full and partial resources names, example: + * `locations/{location}/functions/{functionName}`, + * `projects/{project}/locations/{location}/functions/{functionName}`, or {functionName} + * Does not support deeply nested resource names. + * + * @param resourceName - The resource name string. + * @param resourceIdKey - The key of the resource name to be parsed. + * @returns A parsed resource name object. + */ +export declare function parseResourceName(resourceName: string, resourceIdKey: string): ParsedResource; diff --git a/node_modules/firebase-admin/lib/utils/index.js b/node_modules/firebase-admin/lib/utils/index.js new file mode 100644 index 0000000..eb9e48a --- /dev/null +++ b/node_modules/firebase-admin/lib/utils/index.js @@ -0,0 +1,286 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getSdkVersion = getSdkVersion; +exports.getMetricsHeader = getMetricsHeader; +exports.renameProperties = renameProperties; +exports.addReadonlyGetter = addReadonlyGetter; +exports.getExplicitProjectId = getExplicitProjectId; +exports.findProjectId = findProjectId; +exports.getExplicitServiceAccountEmail = getExplicitServiceAccountEmail; +exports.findServiceAccountEmail = findServiceAccountEmail; +exports.toWebSafeBase64 = toWebSafeBase64; +exports.formatString = formatString; +exports.generateUpdateMask = generateUpdateMask; +exports.transformMillisecondsToSecondsString = transformMillisecondsToSecondsString; +exports.parseResourceName = parseResourceName; +const credential_internal_1 = require("../app/credential-internal"); +const validator = require("./validator"); +let sdkVersion; +// TODO: Move to firebase-admin/app as an internal member. +function getSdkVersion() { + if (!sdkVersion) { + const { version } = require('../../package.json'); // eslint-disable-line @typescript-eslint/no-var-requires + sdkVersion = version; + } + return sdkVersion; +} +function getMetricsHeader() { + return `gl-node/${process.versions.node} fire-admin/${getSdkVersion()}`; +} +/** + * Renames properties on an object given a mapping from old to new property names. + * + * For example, this can be used to map underscore_cased properties to camelCase. + * + * @param obj - The object whose properties to rename. + * @param keyMap - The mapping from old to new property names. + */ +function renameProperties(obj, keyMap) { + Object.keys(keyMap).forEach((oldKey) => { + if (oldKey in obj) { + const newKey = keyMap[oldKey]; + // The old key's value takes precedence over the new key's value. + obj[newKey] = obj[oldKey]; + delete obj[oldKey]; + } + }); +} +/** + * Defines a new read-only property directly on an object and returns the object. + * + * @param obj - The object on which to define the property. + * @param prop - The name of the property to be defined or modified. + * @param value - The value associated with the property. + */ +function addReadonlyGetter(obj, prop, value) { + Object.defineProperty(obj, prop, { + value, + // Make this property read-only. + writable: false, + // Include this property during enumeration of obj's properties. + enumerable: true, + }); +} +/** + * Returns the Google Cloud project ID associated with a Firebase app, if it's explicitly + * specified in either the Firebase app options, credentials or the local environment. + * Otherwise returns null. + * + * @param app - A Firebase app to get the project ID from. + * + * @returns A project ID string or null. + */ +function getExplicitProjectId(app) { + const options = app.options; + if (validator.isNonEmptyString(options.projectId)) { + return options.projectId; + } + const credential = app.options.credential; + if (credential instanceof credential_internal_1.ServiceAccountCredential) { + return credential.projectId; + } + const projectId = process.env.GOOGLE_CLOUD_PROJECT || process.env.GCLOUD_PROJECT; + if (validator.isNonEmptyString(projectId)) { + return projectId; + } + return null; +} +/** + * Determines the Google Cloud project ID associated with a Firebase app. This method + * first checks if a project ID is explicitly specified in either the Firebase app options, + * credentials or the local environment in that order. If no explicit project ID is + * configured, but the SDK has been initialized with ComputeEngineCredentials, this + * method attempts to discover the project ID from the local metadata service. + * + * @param app - A Firebase app to get the project ID from. + * + * @returns A project ID string or null. + */ +function findProjectId(app) { + const projectId = getExplicitProjectId(app); + if (projectId) { + return Promise.resolve(projectId); + } + const credential = app.options.credential; + if (credential instanceof credential_internal_1.ApplicationDefaultCredential) { + return credential.getProjectId(); + } + return Promise.resolve(null); +} +/** + * Returns the service account email associated with a Firebase app, if it's explicitly + * specified in either the Firebase app options, credentials or the local environment. + * Otherwise returns null. + * + * @param app - A Firebase app to get the service account email from. + * + * @returns A service account email string or null. + */ +function getExplicitServiceAccountEmail(app) { + const options = app.options; + if (validator.isNonEmptyString(options.serviceAccountId)) { + return options.serviceAccountId; + } + const credential = app.options.credential; + if (credential instanceof credential_internal_1.ServiceAccountCredential) { + return credential.clientEmail; + } + return null; +} +/** + * Determines the service account email associated with a Firebase app. This method first + * checks if a service account email is explicitly specified in either the Firebase app options, + * credentials or the local environment in that order. If no explicit service account email is + * configured, but the SDK has been initialized with ComputeEngineCredentials, this + * method attempts to discover the service account email from the local metadata service. + * + * @param app - A Firebase app to get the service account email from. + * + * @returns A service account email ID string or null. + */ +function findServiceAccountEmail(app) { + const accountId = getExplicitServiceAccountEmail(app); + if (accountId) { + return Promise.resolve(accountId); + } + const credential = app.options.credential; + if (credential instanceof credential_internal_1.ApplicationDefaultCredential) { + return credential.getServiceAccountEmail(); + } + return Promise.resolve(null); +} +/** + * Encodes data using web-safe-base64. + * + * @param data - The raw data byte input. + * @returns The base64-encoded result. + */ +function toWebSafeBase64(data) { + return data.toString('base64').replace(/\//g, '_').replace(/\+/g, '-'); +} +/** + * Formats a string of form 'project/{projectId}/{api}' and replaces + * with corresponding arguments {projectId: '1234', api: 'resource'} + * and returns output: 'project/1234/resource'. + * + * @param str - The original string where the param need to be + * replaced. + * @param params - The optional parameters to replace in the + * string. + * @returns The resulting formatted string. + */ +function formatString(str, params) { + let formatted = str; + Object.keys(params || {}).forEach((key) => { + formatted = formatted.replace(new RegExp('{' + key + '}', 'g'), params[key]); + }); + return formatted; +} +/** + * Generates the update mask for the provided object. + * Note this will ignore the last key with value undefined. + * + * @param obj - The object to generate the update mask for. + * @param terminalPaths - The optional map of keys for maximum paths to traverse. + * Nested objects beyond that path will be ignored. This is useful for + * keys with variable object values. + * @param root - The path so far. + * @returns The computed update mask list. + */ +function generateUpdateMask(obj, terminalPaths = [], root = '') { + const updateMask = []; + if (!validator.isNonNullObject(obj)) { + return updateMask; + } + for (const key in obj) { + if (typeof obj[key] !== 'undefined') { + const nextPath = root ? `${root}.${key}` : key; + // We hit maximum path. + // Consider switching to Set if the list grows too large. + if (terminalPaths.indexOf(nextPath) !== -1) { + // Add key and stop traversing this branch. + updateMask.push(key); + } + else { + const maskList = generateUpdateMask(obj[key], terminalPaths, nextPath); + if (maskList.length > 0) { + maskList.forEach((mask) => { + updateMask.push(`${key}.${mask}`); + }); + } + else { + updateMask.push(key); + } + } + } + } + return updateMask; +} +/** + * Transforms milliseconds to a protobuf Duration type string. + * Returns the duration in seconds with up to nine fractional + * digits, terminated by 's'. Example: "3 seconds 0 nano seconds as 3s, + * 3 seconds 1 nano seconds as 3.000000001s". + * + * @param milliseconds - The duration in milliseconds. + * @returns The resulting formatted string in seconds with up to nine fractional + * digits, terminated by 's'. + */ +function transformMillisecondsToSecondsString(milliseconds) { + let duration; + const seconds = Math.floor(milliseconds / 1000); + const nanos = Math.floor((milliseconds - seconds * 1000) * 1000000); + if (nanos > 0) { + let nanoString = nanos.toString(); + while (nanoString.length < 9) { + nanoString = '0' + nanoString; + } + duration = `${seconds}.${nanoString}s`; + } + else { + duration = `${seconds}s`; + } + return duration; +} +/** + * Parses the top level resources of a given resource name. + * Supports both full and partial resources names, example: + * `locations/{location}/functions/{functionName}`, + * `projects/{project}/locations/{location}/functions/{functionName}`, or {functionName} + * Does not support deeply nested resource names. + * + * @param resourceName - The resource name string. + * @param resourceIdKey - The key of the resource name to be parsed. + * @returns A parsed resource name object. + */ +function parseResourceName(resourceName, resourceIdKey) { + if (!resourceName.includes('/')) { + return { resourceId: resourceName }; + } + const CHANNEL_NAME_REGEX = new RegExp(`^(projects/([^/]+)/)?locations/([^/]+)/${resourceIdKey}/([^/]+)$`); + const match = CHANNEL_NAME_REGEX.exec(resourceName); + if (match === null) { + throw new Error('Invalid resource name format.'); + } + const projectId = match[2]; + const locationId = match[3]; + const resourceId = match[4]; + return { projectId, locationId, resourceId }; +} diff --git a/node_modules/firebase-admin/lib/utils/jwt.d.ts b/node_modules/firebase-admin/lib/utils/jwt.d.ts new file mode 100644 index 0000000..bfc92b1 --- /dev/null +++ b/node_modules/firebase-admin/lib/utils/jwt.d.ts @@ -0,0 +1,130 @@ +/*! firebase-admin v13.6.0 */ +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as jwt from 'jsonwebtoken'; +import { Agent } from 'http'; +export declare const ALGORITHM_RS256: jwt.Algorithm; +export type Dictionary = { + [key: string]: any; +}; +export type DecodedToken = { + header: Dictionary; + payload: Dictionary; +}; +export interface SignatureVerifier { + verify(token: string): Promise; +} +interface KeyFetcher { + fetchPublicKeys(): Promise<{ + [key: string]: string; + }>; +} +export declare class JwksFetcher implements KeyFetcher { + private publicKeys; + private publicKeysExpireAt; + private client; + constructor(jwksUrl: string, httpAgent?: Agent); + fetchPublicKeys(): Promise<{ + [key: string]: string; + }>; + private shouldRefresh; + private refresh; +} +/** + * Class to fetch public keys from a client certificates URL. + */ +export declare class UrlKeyFetcher implements KeyFetcher { + private clientCertUrl; + private readonly httpAgent?; + private publicKeys; + private publicKeysExpireAt; + constructor(clientCertUrl: string, httpAgent?: Agent | undefined); + /** + * Fetches the public keys for the Google certs. + * + * @returns A promise fulfilled with public keys for the Google certs. + */ + fetchPublicKeys(): Promise<{ + [key: string]: string; + }>; + /** + * Checks if the cached public keys need to be refreshed. + * + * @returns Whether the keys should be fetched from the client certs url or not. + */ + private shouldRefresh; + private refresh; +} +/** + * Class for verifying JWT signature with a public key. + */ +export declare class PublicKeySignatureVerifier implements SignatureVerifier { + private keyFetcher; + constructor(keyFetcher: KeyFetcher); + static withCertificateUrl(clientCertUrl: string, httpAgent?: Agent): PublicKeySignatureVerifier; + static withJwksUrl(jwksUrl: string, httpAgent?: Agent): PublicKeySignatureVerifier; + verify(token: string): Promise; + private verifyWithoutKid; + private verifyWithAllKeys; +} +/** + * Class for verifying unsigned (emulator) JWTs. + */ +export declare class EmulatorSignatureVerifier implements SignatureVerifier { + verify(token: string): Promise; +} +/** + * Verifies the signature of a JWT using the provided secret or a function to fetch + * the secret or public key. + * + * @param token - The JWT to be verified. + * @param secretOrPublicKey - The secret or a function to fetch the secret or public key. + * @param options - JWT verification options. + * @returns A Promise resolving for a token with a valid signature. + */ +export declare function verifyJwtSignature(token: string, secretOrPublicKey: jwt.Secret | jwt.GetPublicKeyOrSecret, options?: jwt.VerifyOptions): Promise; +/** + * Decodes general purpose Firebase JWTs. + * + * @param jwtToken - JWT token to be decoded. + * @returns Decoded token containing the header and payload. + */ +export declare function decodeJwt(jwtToken: string): Promise; +/** + * Jwt error code structure. + * + * @param code - The error code. + * @param message - The error message. + * @constructor + */ +export declare class JwtError extends Error { + readonly code: JwtErrorCode; + readonly message: string; + constructor(code: JwtErrorCode, message: string); +} +/** + * JWT error codes. + */ +export declare enum JwtErrorCode { + INVALID_ARGUMENT = "invalid-argument", + INVALID_CREDENTIAL = "invalid-credential", + TOKEN_EXPIRED = "token-expired", + INVALID_SIGNATURE = "invalid-token", + NO_MATCHING_KID = "no-matching-kid-error", + NO_KID_IN_HEADER = "no-kid-error", + KEY_FETCH_ERROR = "key-fetch-error" +} +export {}; diff --git a/node_modules/firebase-admin/lib/utils/jwt.js b/node_modules/firebase-admin/lib/utils/jwt.js new file mode 100644 index 0000000..af52fa5 --- /dev/null +++ b/node_modules/firebase-admin/lib/utils/jwt.js @@ -0,0 +1,330 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.JwtErrorCode = exports.JwtError = exports.EmulatorSignatureVerifier = exports.PublicKeySignatureVerifier = exports.UrlKeyFetcher = exports.JwksFetcher = exports.ALGORITHM_RS256 = void 0; +exports.verifyJwtSignature = verifyJwtSignature; +exports.decodeJwt = decodeJwt; +const validator = require("./validator"); +const jwt = require("jsonwebtoken"); +const jwks = require("jwks-rsa"); +const api_request_1 = require("../utils/api-request"); +exports.ALGORITHM_RS256 = 'RS256'; +// `jsonwebtoken` converts errors from the `getKey` callback to its own `JsonWebTokenError` type +// and prefixes the error message with the following. Use the prefix to identify errors thrown +// from the key provider callback. +// https://github.com/auth0/node-jsonwebtoken/blob/d71e383862fc735991fd2e759181480f066bf138/verify.js#L96 +const JWT_CALLBACK_ERROR_PREFIX = 'error in secret or public key callback: '; +const NO_MATCHING_KID_ERROR_MESSAGE = 'no-matching-kid-error'; +const NO_KID_IN_HEADER_ERROR_MESSAGE = 'no-kid-in-header-error'; +const HOUR_IN_SECONDS = 3600; +class JwksFetcher { + constructor(jwksUrl, httpAgent) { + this.publicKeysExpireAt = 0; + if (!validator.isURL(jwksUrl)) { + throw new Error('The provided JWKS URL is not a valid URL.'); + } + this.client = jwks({ + jwksUri: jwksUrl, + cache: false, // disable jwks-rsa LRU cache as the keys are always cached for 6 hours. + requestAgent: httpAgent, + }); + } + fetchPublicKeys() { + if (this.shouldRefresh()) { + return this.refresh(); + } + return Promise.resolve(this.publicKeys); + } + shouldRefresh() { + return !this.publicKeys || this.publicKeysExpireAt <= Date.now(); + } + refresh() { + return this.client.getSigningKeys() + .then((signingKeys) => { + // reset expire at from previous set of keys. + this.publicKeysExpireAt = 0; + const newKeys = signingKeys.reduce((map, signingKey) => { + map[signingKey.kid] = signingKey.getPublicKey(); + return map; + }, {}); + this.publicKeysExpireAt = Date.now() + (HOUR_IN_SECONDS * 6 * 1000); + this.publicKeys = newKeys; + return newKeys; + }).catch((err) => { + throw new Error(`Error fetching Json Web Keys: ${err.message}`); + }); + } +} +exports.JwksFetcher = JwksFetcher; +/** + * Class to fetch public keys from a client certificates URL. + */ +class UrlKeyFetcher { + constructor(clientCertUrl, httpAgent) { + this.clientCertUrl = clientCertUrl; + this.httpAgent = httpAgent; + this.publicKeysExpireAt = 0; + if (!validator.isURL(clientCertUrl)) { + throw new Error('The provided public client certificate URL is not a valid URL.'); + } + } + /** + * Fetches the public keys for the Google certs. + * + * @returns A promise fulfilled with public keys for the Google certs. + */ + fetchPublicKeys() { + if (this.shouldRefresh()) { + return this.refresh(); + } + return Promise.resolve(this.publicKeys); + } + /** + * Checks if the cached public keys need to be refreshed. + * + * @returns Whether the keys should be fetched from the client certs url or not. + */ + shouldRefresh() { + return !this.publicKeys || this.publicKeysExpireAt <= Date.now(); + } + refresh() { + const client = new api_request_1.HttpClient(); + const request = { + method: 'GET', + url: this.clientCertUrl, + httpAgent: this.httpAgent, + }; + return client.send(request).then((resp) => { + if (!resp.isJson() || resp.data.error) { + // Treat all non-json messages and messages with an 'error' field as + // error responses. + throw new api_request_1.RequestResponseError(resp); + } + // reset expire at from previous set of keys. + this.publicKeysExpireAt = 0; + if (Object.prototype.hasOwnProperty.call(resp.headers, 'cache-control')) { + const cacheControlHeader = resp.headers['cache-control']; + const parts = cacheControlHeader.split(','); + parts.forEach((part) => { + const subParts = part.trim().split('='); + if (subParts[0] === 'max-age') { + const maxAge = +subParts[1]; + this.publicKeysExpireAt = Date.now() + (maxAge * 1000); + } + }); + } + this.publicKeys = resp.data; + return resp.data; + }).catch((err) => { + if (err instanceof api_request_1.RequestResponseError) { + let errorMessage = 'Error fetching public keys for Google certs: '; + const resp = err.response; + if (resp.isJson() && resp.data.error) { + errorMessage += `${resp.data.error}`; + if (resp.data.error_description) { + errorMessage += ' (' + resp.data.error_description + ')'; + } + } + else { + errorMessage += `${resp.text}`; + } + throw new Error(errorMessage); + } + throw err; + }); + } +} +exports.UrlKeyFetcher = UrlKeyFetcher; +/** + * Class for verifying JWT signature with a public key. + */ +class PublicKeySignatureVerifier { + constructor(keyFetcher) { + this.keyFetcher = keyFetcher; + if (!validator.isNonNullObject(keyFetcher)) { + throw new Error('The provided key fetcher is not an object or null.'); + } + } + static withCertificateUrl(clientCertUrl, httpAgent) { + return new PublicKeySignatureVerifier(new UrlKeyFetcher(clientCertUrl, httpAgent)); + } + static withJwksUrl(jwksUrl, httpAgent) { + return new PublicKeySignatureVerifier(new JwksFetcher(jwksUrl, httpAgent)); + } + verify(token) { + if (!validator.isString(token)) { + return Promise.reject(new JwtError(JwtErrorCode.INVALID_ARGUMENT, 'The provided token must be a string.')); + } + return verifyJwtSignature(token, getKeyCallback(this.keyFetcher), { algorithms: [exports.ALGORITHM_RS256] }) + .catch((error) => { + if (error.code === JwtErrorCode.NO_KID_IN_HEADER) { + // No kid in JWT header. Try with all the public keys. + return this.verifyWithoutKid(token); + } + throw error; + }); + } + verifyWithoutKid(token) { + return this.keyFetcher.fetchPublicKeys() + .then(publicKeys => this.verifyWithAllKeys(token, publicKeys)); + } + verifyWithAllKeys(token, keys) { + const promises = []; + Object.values(keys).forEach((key) => { + const result = verifyJwtSignature(token, key) + .then(() => true) + .catch((error) => { + if (error.code === JwtErrorCode.TOKEN_EXPIRED) { + throw error; + } + return false; + }); + promises.push(result); + }); + return Promise.all(promises) + .then((result) => { + if (result.every((r) => r === false)) { + throw new JwtError(JwtErrorCode.INVALID_SIGNATURE, 'Invalid token signature.'); + } + }); + } +} +exports.PublicKeySignatureVerifier = PublicKeySignatureVerifier; +/** + * Class for verifying unsigned (emulator) JWTs. + */ +class EmulatorSignatureVerifier { + verify(token) { + // Signature checks skipped for emulator; no need to fetch public keys. + return verifyJwtSignature(token, undefined, { algorithms: ['none'] }); + } +} +exports.EmulatorSignatureVerifier = EmulatorSignatureVerifier; +/** + * Provides a callback to fetch public keys. + * + * @param fetcher - KeyFetcher to fetch the keys from. + * @returns A callback function that can be used to get keys in `jsonwebtoken`. + */ +function getKeyCallback(fetcher) { + return (header, callback) => { + if (!header.kid) { + callback(new Error(NO_KID_IN_HEADER_ERROR_MESSAGE)); + } + const kid = header.kid || ''; + fetcher.fetchPublicKeys().then((publicKeys) => { + if (!Object.prototype.hasOwnProperty.call(publicKeys, kid)) { + callback(new Error(NO_MATCHING_KID_ERROR_MESSAGE)); + } + else { + callback(null, publicKeys[kid]); + } + }) + .catch(error => { + callback(error); + }); + }; +} +/** + * Verifies the signature of a JWT using the provided secret or a function to fetch + * the secret or public key. + * + * @param token - The JWT to be verified. + * @param secretOrPublicKey - The secret or a function to fetch the secret or public key. + * @param options - JWT verification options. + * @returns A Promise resolving for a token with a valid signature. + */ +function verifyJwtSignature(token, secretOrPublicKey, options) { + if (!validator.isString(token)) { + return Promise.reject(new JwtError(JwtErrorCode.INVALID_ARGUMENT, 'The provided token must be a string.')); + } + return new Promise((resolve, reject) => { + jwt.verify(token, secretOrPublicKey, options, (error) => { + if (!error) { + return resolve(); + } + if (error.name === 'TokenExpiredError') { + return reject(new JwtError(JwtErrorCode.TOKEN_EXPIRED, 'The provided token has expired. Get a fresh token from your ' + + 'client app and try again.')); + } + else if (error.name === 'JsonWebTokenError') { + if (error.message && error.message.includes(JWT_CALLBACK_ERROR_PREFIX)) { + const message = error.message.split(JWT_CALLBACK_ERROR_PREFIX).pop() || 'Error fetching public keys.'; + let code = JwtErrorCode.KEY_FETCH_ERROR; + if (message === NO_MATCHING_KID_ERROR_MESSAGE) { + code = JwtErrorCode.NO_MATCHING_KID; + } + else if (message === NO_KID_IN_HEADER_ERROR_MESSAGE) { + code = JwtErrorCode.NO_KID_IN_HEADER; + } + return reject(new JwtError(code, message)); + } + } + return reject(new JwtError(JwtErrorCode.INVALID_SIGNATURE, error.message)); + }); + }); +} +/** + * Decodes general purpose Firebase JWTs. + * + * @param jwtToken - JWT token to be decoded. + * @returns Decoded token containing the header and payload. + */ +function decodeJwt(jwtToken) { + if (!validator.isString(jwtToken)) { + return Promise.reject(new JwtError(JwtErrorCode.INVALID_ARGUMENT, 'The provided token must be a string.')); + } + const fullDecodedToken = jwt.decode(jwtToken, { + complete: true, + }); + if (!fullDecodedToken) { + return Promise.reject(new JwtError(JwtErrorCode.INVALID_ARGUMENT, 'Decoding token failed.')); + } + const header = fullDecodedToken?.header; + const payload = fullDecodedToken?.payload; + return Promise.resolve({ header, payload }); +} +/** + * Jwt error code structure. + * + * @param code - The error code. + * @param message - The error message. + * @constructor + */ +class JwtError extends Error { + constructor(code, message) { + super(message); + this.code = code; + this.message = message; + this.__proto__ = JwtError.prototype; + } +} +exports.JwtError = JwtError; +/** + * JWT error codes. + */ +var JwtErrorCode; +(function (JwtErrorCode) { + JwtErrorCode["INVALID_ARGUMENT"] = "invalid-argument"; + JwtErrorCode["INVALID_CREDENTIAL"] = "invalid-credential"; + JwtErrorCode["TOKEN_EXPIRED"] = "token-expired"; + JwtErrorCode["INVALID_SIGNATURE"] = "invalid-token"; + JwtErrorCode["NO_MATCHING_KID"] = "no-matching-kid-error"; + JwtErrorCode["NO_KID_IN_HEADER"] = "no-kid-error"; + JwtErrorCode["KEY_FETCH_ERROR"] = "key-fetch-error"; +})(JwtErrorCode || (exports.JwtErrorCode = JwtErrorCode = {})); diff --git a/node_modules/firebase-admin/lib/utils/validator.d.ts b/node_modules/firebase-admin/lib/utils/validator.d.ts new file mode 100644 index 0000000..7773596 --- /dev/null +++ b/node_modules/firebase-admin/lib/utils/validator.d.ts @@ -0,0 +1,151 @@ +/*! firebase-admin v13.6.0 */ +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Validates that a value is a byte buffer. + * + * @param value - The value to validate. + * @returns Whether the value is byte buffer or not. + */ +export declare function isBuffer(value: any): value is Buffer; +/** + * Validates that a value is an array. + * + * @param value - The value to validate. + * @returns Whether the value is an array or not. + */ +export declare function isArray(value: any): value is T[]; +/** + * Validates that a value is a non-empty array. + * + * @param value - The value to validate. + * @returns Whether the value is a non-empty array or not. + */ +export declare function isNonEmptyArray(value: any): value is T[]; +/** + * Validates that a value is a boolean. + * + * @param value - The value to validate. + * @returns Whether the value is a boolean or not. + */ +export declare function isBoolean(value: any): boolean; +/** + * Validates that a value is a number. + * + * @param value - The value to validate. + * @returns Whether the value is a number or not. + */ +export declare function isNumber(value: any): boolean; +/** + * Validates that a value is a string. + * + * @param value - The value to validate. + * @returns Whether the value is a string or not. + */ +export declare function isString(value: any): value is string; +/** + * Validates that a value is a base64 string. + * + * @param value - The value to validate. + * @returns Whether the value is a base64 string or not. + */ +export declare function isBase64String(value: any): boolean; +/** + * Validates that a value is a non-empty string. + * + * @param value - The value to validate. + * @returns Whether the value is a non-empty string or not. + */ +export declare function isNonEmptyString(value: any): value is string; +/** + * Validates that a value is a nullable object. + * + * @param value - The value to validate. + * @returns Whether the value is an object or not. + */ +export declare function isObject(value: any): boolean; +/** + * Validates that a value is a non-null object. + * + * @param value - The value to validate. + * @returns Whether the value is a non-null object or not. + */ +export declare function isNonNullObject(value: T | null | undefined): value is T; +/** + * Validates that a string is a valid Firebase Auth uid. + * + * @param uid - The string to validate. + * @returns Whether the string is a valid Firebase Auth uid. + */ +export declare function isUid(uid: any): boolean; +/** + * Validates that a string is a valid Firebase Auth password. + * + * @param password - The password string to validate. + * @returns Whether the string is a valid Firebase Auth password. + */ +export declare function isPassword(password: any): boolean; +/** + * Validates that a string is a valid email. + * + * @param email - The string to validate. + * @returns Whether the string is valid email or not. + */ +export declare function isEmail(email: any): boolean; +/** + * Validates that a string is a valid phone number. + * + * @param phoneNumber - The string to validate. + * @returns Whether the string is a valid phone number or not. + */ +export declare function isPhoneNumber(phoneNumber: any): boolean; +/** + * Validates that a string is a valid ISO date string. + * + * @param dateString - The string to validate. + * @returns Whether the string is a valid ISO date string. + */ +export declare function isISODateString(dateString: any): boolean; +/** + * Validates that a string is a valid UTC date string. + * + * @param dateString - The string to validate. + * @returns Whether the string is a valid UTC date string. + */ +export declare function isUTCDateString(dateString: any): boolean; +/** + * Validates that a string is a valid web URL. + * + * @param urlStr - The string to validate. + * @returns Whether the string is valid web URL or not. + */ +export declare function isURL(urlStr: any): boolean; +/** + * Validates that the provided topic is a valid FCM topic name. + * + * @param topic - The topic to validate. + * @returns Whether the provided topic is a valid FCM topic name. + */ +export declare function isTopic(topic: any): boolean; +/** + * Validates that the provided string can be used as a task ID + * for Cloud Tasks. + * + * @param taskId - the task ID to validate. + * @returns Whether the provided task ID is valid. + */ +export declare function isTaskId(taskId: any): boolean; diff --git a/node_modules/firebase-admin/lib/utils/validator.js b/node_modules/firebase-admin/lib/utils/validator.js new file mode 100644 index 0000000..d43cc6a --- /dev/null +++ b/node_modules/firebase-admin/lib/utils/validator.js @@ -0,0 +1,285 @@ +/*! firebase-admin v13.6.0 */ +"use strict"; +/*! + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isBuffer = isBuffer; +exports.isArray = isArray; +exports.isNonEmptyArray = isNonEmptyArray; +exports.isBoolean = isBoolean; +exports.isNumber = isNumber; +exports.isString = isString; +exports.isBase64String = isBase64String; +exports.isNonEmptyString = isNonEmptyString; +exports.isObject = isObject; +exports.isNonNullObject = isNonNullObject; +exports.isUid = isUid; +exports.isPassword = isPassword; +exports.isEmail = isEmail; +exports.isPhoneNumber = isPhoneNumber; +exports.isISODateString = isISODateString; +exports.isUTCDateString = isUTCDateString; +exports.isURL = isURL; +exports.isTopic = isTopic; +exports.isTaskId = isTaskId; +const url = require("url"); +/** + * Validates that a value is a byte buffer. + * + * @param value - The value to validate. + * @returns Whether the value is byte buffer or not. + */ +function isBuffer(value) { + return value instanceof Buffer; +} +/** + * Validates that a value is an array. + * + * @param value - The value to validate. + * @returns Whether the value is an array or not. + */ +function isArray(value) { + return Array.isArray(value); +} +/** + * Validates that a value is a non-empty array. + * + * @param value - The value to validate. + * @returns Whether the value is a non-empty array or not. + */ +function isNonEmptyArray(value) { + return isArray(value) && value.length !== 0; +} +/** + * Validates that a value is a boolean. + * + * @param value - The value to validate. + * @returns Whether the value is a boolean or not. + */ +function isBoolean(value) { + return typeof value === 'boolean'; +} +/** + * Validates that a value is a number. + * + * @param value - The value to validate. + * @returns Whether the value is a number or not. + */ +function isNumber(value) { + return typeof value === 'number' && !isNaN(value); +} +/** + * Validates that a value is a string. + * + * @param value - The value to validate. + * @returns Whether the value is a string or not. + */ +function isString(value) { + return typeof value === 'string'; +} +/** + * Validates that a value is a base64 string. + * + * @param value - The value to validate. + * @returns Whether the value is a base64 string or not. + */ +function isBase64String(value) { + if (!isString(value)) { + return false; + } + return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value); +} +/** + * Validates that a value is a non-empty string. + * + * @param value - The value to validate. + * @returns Whether the value is a non-empty string or not. + */ +function isNonEmptyString(value) { + return isString(value) && value !== ''; +} +/** + * Validates that a value is a nullable object. + * + * @param value - The value to validate. + * @returns Whether the value is an object or not. + */ +function isObject(value) { + return typeof value === 'object' && !isArray(value); +} +/** + * Validates that a value is a non-null object. + * + * @param value - The value to validate. + * @returns Whether the value is a non-null object or not. + */ +function isNonNullObject(value) { + return isObject(value) && value !== null; +} +/** + * Validates that a string is a valid Firebase Auth uid. + * + * @param uid - The string to validate. + * @returns Whether the string is a valid Firebase Auth uid. + */ +function isUid(uid) { + return typeof uid === 'string' && uid.length > 0 && uid.length <= 128; +} +/** + * Validates that a string is a valid Firebase Auth password. + * + * @param password - The password string to validate. + * @returns Whether the string is a valid Firebase Auth password. + */ +function isPassword(password) { + // A password must be a string of at least 6 characters. + return typeof password === 'string' && password.length >= 6; +} +/** + * Validates that a string is a valid email. + * + * @param email - The string to validate. + * @returns Whether the string is valid email or not. + */ +function isEmail(email) { + if (typeof email !== 'string') { + return false; + } + // There must at least one character before the @ symbol and another after. + const re = /^[^@]+@[^@]+$/; + return re.test(email); +} +/** + * Validates that a string is a valid phone number. + * + * @param phoneNumber - The string to validate. + * @returns Whether the string is a valid phone number or not. + */ +function isPhoneNumber(phoneNumber) { + if (typeof phoneNumber !== 'string') { + return false; + } + // Phone number validation is very lax here. Backend will enforce E.164 + // spec compliance and will normalize accordingly. + // The phone number string must be non-empty and starts with a plus sign. + const re1 = /^\+/; + // The phone number string must contain at least one alphanumeric character. + const re2 = /[\da-zA-Z]+/; + return re1.test(phoneNumber) && re2.test(phoneNumber); +} +/** + * Validates that a string is a valid ISO date string. + * + * @param dateString - The string to validate. + * @returns Whether the string is a valid ISO date string. + */ +function isISODateString(dateString) { + try { + return isNonEmptyString(dateString) && + (new Date(dateString).toISOString() === dateString); + } + catch (e) { + return false; + } +} +/** + * Validates that a string is a valid UTC date string. + * + * @param dateString - The string to validate. + * @returns Whether the string is a valid UTC date string. + */ +function isUTCDateString(dateString) { + try { + return isNonEmptyString(dateString) && + (new Date(dateString).toUTCString() === dateString); + } + catch (e) { + return false; + } +} +/** + * Validates that a string is a valid web URL. + * + * @param urlStr - The string to validate. + * @returns Whether the string is valid web URL or not. + */ +function isURL(urlStr) { + if (typeof urlStr !== 'string') { + return false; + } + // Lookup illegal characters. + const re = /[^a-z0-9:/?#[\]@!$&'()*+,;=.\-_~%]/i; + if (re.test(urlStr)) { + return false; + } + try { + const uri = url.parse(urlStr); + const scheme = uri.protocol; + const slashes = uri.slashes; + const hostname = uri.hostname; + const pathname = uri.pathname; + if ((scheme !== 'http:' && scheme !== 'https:') || !slashes) { + return false; + } + // Validate hostname: Can contain letters, numbers, underscore and dashes separated by a dot. + // Each zone must not start with a hyphen or underscore. + if (!hostname || !/^[a-zA-Z0-9]+[\w-]*([.]?[a-zA-Z0-9]+[\w-]*)*$/.test(hostname)) { + return false; + } + // Allow for pathnames: (/chars+)*/? + // Where chars can be a combination of: a-z A-Z 0-9 - _ . ~ ! $ & ' ( ) * + , ; = : @ % + const pathnameRe = /^(\/[\w\-.~!$'()*+,;=:@%]+)*\/?$/; + // Validate pathname. + if (pathname && + pathname !== '/' && + !pathnameRe.test(pathname)) { + return false; + } + // Allow any query string and hash as long as no invalid character is used. + } + catch (e) { + return false; + } + return true; +} +/** + * Validates that the provided topic is a valid FCM topic name. + * + * @param topic - The topic to validate. + * @returns Whether the provided topic is a valid FCM topic name. + */ +function isTopic(topic) { + if (typeof topic !== 'string') { + return false; + } + const VALID_TOPIC_REGEX = /^(\/topics\/)?(private\/)?[a-zA-Z0-9-_.~%]+$/; + return VALID_TOPIC_REGEX.test(topic); +} +/** + * Validates that the provided string can be used as a task ID + * for Cloud Tasks. + * + * @param taskId - the task ID to validate. + * @returns Whether the provided task ID is valid. + */ +function isTaskId(taskId) { + if (typeof taskId !== 'string') { + return false; + } + const VALID_TASK_ID_REGEX = /^[A-Za-z0-9_-]+$/; + return VALID_TASK_ID_REGEX.test(taskId); +} diff --git a/node_modules/firebase-admin/package.json b/node_modules/firebase-admin/package.json new file mode 100644 index 0000000..721ff00 --- /dev/null +++ b/node_modules/firebase-admin/package.json @@ -0,0 +1,277 @@ +{ + "name": "firebase-admin", + "version": "13.6.0", + "description": "Firebase admin SDK for Node.js", + "author": "Firebase (https://firebase.google.com/)", + "license": "Apache-2.0", + "homepage": "https://firebase.google.com/", + "engines": { + "node": ">=18" + }, + "scripts": { + "build": "gulp build", + "build:tests": "gulp compile_test", + "prepare": "npm run build && npm run esm-wrap", + "lint": "run-p lint:src lint:test", + "test": "run-s lint test:unit", + "integration": "run-s build test:integration", + "test:unit": "mocha test/unit/*.spec.ts --require ts-node/register", + "test:integration": "mocha test/integration/*.ts --slow 5000 --timeout 20000 --require ts-node/register", + "test:coverage": "nyc npm run test:unit", + "lint:src": "eslint src/ --ext .ts", + "lint:src:fix": "eslint src/ --ext .ts --fix", + "lint:test": "eslint test/ --ext .ts", + "lint:test:fix": "eslint test/ --ext .ts --fix", + "apidocs": "run-s api-extractor:local api-documenter", + "api-extractor": "node generate-reports.js", + "api-extractor:local": "npm run build && node generate-reports.js --local", + "esm-wrap": "node generate-esm-wrapper.js", + "api-documenter": "run-s api-documenter:markdown api-documenter:toc api-documenter:post", + "api-documenter:markdown": "api-documenter-fire markdown --input temp --output docgen/markdown -s --project admin", + "api-documenter:toc": "api-documenter-fire toc --input temp --output docgen/markdown -p /docs/reference/admin/node -s", + "api-documenter:post": "node docgen/post-process.js" + }, + "nyc": { + "extension": [ + ".ts" + ], + "include": [ + "src" + ], + "exclude": [ + "**/*.d.ts" + ], + "all": true + }, + "keywords": [ + "admin", + "database", + "Firebase", + "realtime", + "authentication" + ], + "repository": { + "type": "git", + "url": "https://github.com/firebase/firebase-admin-node" + }, + "main": "lib/index.js", + "files": [ + "lib/", + "LICENSE", + "README.md", + "package.json" + ], + "types": "./lib/index.d.ts", + "typesVersions": { + "*": { + "app": [ + "lib/app" + ], + "app-check": [ + "lib/app-check" + ], + "auth": [ + "lib/auth" + ], + "eventarc": [ + "lib/eventarc" + ], + "extensions": [ + "lib/extensions" + ], + "database": [ + "lib/database" + ], + "data-connect": [ + "lib/data-connect" + ], + "firestore": [ + "lib/firestore" + ], + "functions": [ + "lib/functions" + ], + "installations": [ + "lib/installations" + ], + "instance-id": [ + "lib/instance-id" + ], + "machine-learning": [ + "lib/machine-learning" + ], + "messaging": [ + "lib/messaging" + ], + "project-management": [ + "lib/project-management" + ], + "remote-config": [ + "lib/remote-config" + ], + "security-rules": [ + "lib/security-rules" + ], + "storage": [ + "lib/storage" + ] + } + }, + "exports": { + ".": "./lib/index.js", + "./app": { + "types": "./lib/app/index.d.ts", + "require": "./lib/app/index.js", + "import": "./lib/esm/app/index.js" + }, + "./app-check": { + "types": "./lib/app-check/index.d.ts", + "require": "./lib/app-check/index.js", + "import": "./lib/esm/app-check/index.js" + }, + "./auth": { + "types": "./lib/auth/index.d.ts", + "require": "./lib/auth/index.js", + "import": "./lib/esm/auth/index.js" + }, + "./database": { + "types": "./lib/database/index.d.ts", + "require": "./lib/database/index.js", + "import": "./lib/esm/database/index.js" + }, + "./data-connect": { + "types": "./lib/data-connect/index.d.ts", + "require": "./lib/data-connect/index.js", + "import": "./lib/esm/data-connect/index.js" + }, + "./eventarc": { + "types": "./lib/eventarc/index.d.ts", + "require": "./lib/eventarc/index.js", + "import": "./lib/esm/eventarc/index.js" + }, + "./extensions": { + "types": "./lib/extensions/index.d.ts", + "require": "./lib/extensions/index.js", + "import": "./lib/esm/extensions/index.js" + }, + "./firestore": { + "types": "./lib/firestore/index.d.ts", + "require": "./lib/firestore/index.js", + "import": "./lib/esm/firestore/index.js" + }, + "./functions": { + "types": "./lib/functions/index.d.ts", + "require": "./lib/functions/index.js", + "import": "./lib/esm/functions/index.js" + }, + "./installations": { + "types": "./lib/installations/index.d.ts", + "require": "./lib/installations/index.js", + "import": "./lib/esm/installations/index.js" + }, + "./instance-id": { + "types": "./lib/instance-id/index.d.ts", + "require": "./lib/instance-id/index.js", + "import": "./lib/esm/instance-id/index.js" + }, + "./machine-learning": { + "types": "./lib/machine-learning/index.d.ts", + "require": "./lib/machine-learning/index.js", + "import": "./lib/esm/machine-learning/index.js" + }, + "./messaging": { + "types": "./lib/messaging/index.d.ts", + "require": "./lib/messaging/index.js", + "import": "./lib/esm/messaging/index.js" + }, + "./project-management": { + "types": "./lib/project-management/index.d.ts", + "require": "./lib/project-management/index.js", + "import": "./lib/esm/project-management/index.js" + }, + "./remote-config": { + "types": "./lib/remote-config/index.d.ts", + "require": "./lib/remote-config/index.js", + "import": "./lib/esm/remote-config/index.js" + }, + "./security-rules": { + "types": "./lib/security-rules/index.d.ts", + "require": "./lib/security-rules/index.js", + "import": "./lib/esm/security-rules/index.js" + }, + "./storage": { + "types": "./lib/storage/index.d.ts", + "require": "./lib/storage/index.js", + "import": "./lib/esm/storage/index.js" + } + }, + "dependencies": { + "@fastify/busboy": "^3.0.0", + "@firebase/database-compat": "^2.0.0", + "@firebase/database-types": "^1.0.6", + "@types/node": "^22.8.7", + "farmhash-modern": "^1.1.0", + "fast-deep-equal": "^3.1.1", + "google-auth-library": "^9.14.2", + "jsonwebtoken": "^9.0.0", + "jwks-rsa": "^3.1.0", + "node-forge": "^1.3.1", + "uuid": "^11.0.2" + }, + "optionalDependencies": { + "@google-cloud/firestore": "^7.11.0", + "@google-cloud/storage": "^7.14.0" + }, + "devDependencies": { + "@firebase/api-documenter": "^0.5.0", + "@firebase/app-compat": "^0.2.1", + "@firebase/auth-compat": "^0.6.0", + "@firebase/auth-types": "^0.13.0", + "@microsoft/api-extractor": "^7.11.2", + "@types/bcrypt": "^5.0.0", + "@types/chai": "^4.0.0", + "@types/chai-as-promised": "^7.1.0", + "@types/firebase-token-generator": "^2.0.28", + "@types/jsonwebtoken": "8.5.1", + "@types/lodash": "^4.14.104", + "@types/minimist": "^1.2.2", + "@types/mocha": "^10.0.0", + "@types/nock": "^11.1.0", + "@types/request": "^2.47.0", + "@types/request-promise": "^4.1.41", + "@types/sinon": "^17.0.2", + "@types/sinon-chai": "^3.0.0", + "@types/uuid": "^10.0.0", + "@typescript-eslint/eslint-plugin": "^7.16.1", + "@typescript-eslint/parser": "^7.16.1", + "bcrypt": "^5.0.0", + "chai": "^4.2.0", + "chai-as-promised": "^7.0.0", + "chai-exclude": "^2.1.0", + "chalk": "^4.1.1", + "child-process-promise": "^2.2.1", + "del": "^6.0.0", + "eslint": "^8.56.0", + "firebase-token-generator": "^2.0.0", + "gulp": "^5.0.0", + "gulp-filter": "^7.0.0", + "gulp-header": "^2.0.9", + "gulp-typescript": "^5.0.1", + "http-message-parser": "^0.0.34", + "lodash": "^4.17.15", + "minimist": "^1.2.6", + "mocha": "^11.0.0", + "mz": "^2.7.0", + "nock": "^13.0.0", + "npm-run-all": "^4.1.5", + "nyc": "^17.0.0", + "request": "^2.75.0", + "request-promise": "^4.1.1", + "run-sequence": "^2.2.1", + "sinon": "^18.0.0", + "sinon-chai": "^3.0.0", + "ts-node": "^10.2.0", + "typescript": "5.5.4", + "yargs": "^17.0.1" + } +} diff --git a/node_modules/form-data/CHANGELOG.md b/node_modules/form-data/CHANGELOG.md new file mode 100644 index 0000000..43a714e --- /dev/null +++ b/node_modules/form-data/CHANGELOG.md @@ -0,0 +1,651 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v4.0.4](https://github.com/form-data/form-data/compare/v4.0.3...v4.0.4) - 2025-07-16 + +### Commits + +- [meta] add `auto-changelog` [`811f682`](https://github.com/form-data/form-data/commit/811f68282fab0315209d0e2d1c44b6c32ea0d479) +- [Tests] handle predict-v8-randomness failures in node < 17 and node > 23 [`1d11a76`](https://github.com/form-data/form-data/commit/1d11a76434d101f22fdb26b8aef8615f28b98402) +- [Fix] Switch to using `crypto` random for boundary values [`3d17230`](https://github.com/form-data/form-data/commit/3d1723080e6577a66f17f163ecd345a21d8d0fd0) +- [Tests] fix linting errors [`5e34080`](https://github.com/form-data/form-data/commit/5e340800b5f8914213e4e0378c084aae71cfd73a) +- [meta] actually ensure the readme backup isn’t published [`316c82b`](https://github.com/form-data/form-data/commit/316c82ba93fd4985af757b771b9a1f26d3b709ef) +- [Dev Deps] update `@ljharb/eslint-config` [`58c25d7`](https://github.com/form-data/form-data/commit/58c25d76406a5b0dfdf54045cf252563f2bbda8d) +- [meta] fix readme capitalization [`2300ca1`](https://github.com/form-data/form-data/commit/2300ca19595b0ee96431e868fe2a40db79e41c61) + +## [v4.0.3](https://github.com/form-data/form-data/compare/v4.0.2...v4.0.3) - 2025-06-05 + +### Fixed + +- [Fix] `append`: avoid a crash on nullish values [`#577`](https://github.com/form-data/form-data/issues/577) + +### Commits + +- [eslint] use a shared config [`426ba9a`](https://github.com/form-data/form-data/commit/426ba9ac440f95d1998dac9a5cd8d738043b048f) +- [eslint] fix some spacing issues [`2094191`](https://github.com/form-data/form-data/commit/20941917f0e9487e68c564ebc3157e23609e2939) +- [Refactor] use `hasown` [`81ab41b`](https://github.com/form-data/form-data/commit/81ab41b46fdf34f5d89d7ff30b513b0925febfaa) +- [Fix] validate boundary type in `setBoundary()` method [`8d8e469`](https://github.com/form-data/form-data/commit/8d8e4693093519f7f18e3c597d1e8df8c493de9e) +- [Tests] add tests to check the behavior of `getBoundary` with non-strings [`837b8a1`](https://github.com/form-data/form-data/commit/837b8a1f7562bfb8bda74f3fc538adb7a5858995) +- [Dev Deps] remove unused deps [`870e4e6`](https://github.com/form-data/form-data/commit/870e4e665935e701bf983a051244ab928e62d58e) +- [meta] remove local commit hooks [`e6e83cc`](https://github.com/form-data/form-data/commit/e6e83ccb545a5619ed6cd04f31d5c2f655eb633e) +- [Dev Deps] update `eslint` [`4066fd6`](https://github.com/form-data/form-data/commit/4066fd6f65992b62fa324a6474a9292a4f88c916) +- [meta] fix scripts to use prepublishOnly [`c4bbb13`](https://github.com/form-data/form-data/commit/c4bbb13c0ef669916657bc129341301b1d331d75) + +## [v4.0.2](https://github.com/form-data/form-data/compare/v4.0.1...v4.0.2) - 2025-02-14 + +### Merged + +- [Fix] set `Symbol.toStringTag` when available [`#573`](https://github.com/form-data/form-data/pull/573) +- [Fix] set `Symbol.toStringTag` when available [`#573`](https://github.com/form-data/form-data/pull/573) +- fix (npmignore): ignore temporary build files [`#532`](https://github.com/form-data/form-data/pull/532) +- fix (npmignore): ignore temporary build files [`#532`](https://github.com/form-data/form-data/pull/532) + +### Fixed + +- [Fix] set `Symbol.toStringTag` when available (#573) [`#396`](https://github.com/form-data/form-data/issues/396) +- [Fix] set `Symbol.toStringTag` when available (#573) [`#396`](https://github.com/form-data/form-data/issues/396) +- [Fix] set `Symbol.toStringTag` when available [`#396`](https://github.com/form-data/form-data/issues/396) + +### Commits + +- Merge tags v2.5.3 and v3.0.3 [`92613b9`](https://github.com/form-data/form-data/commit/92613b9208556eb4ebc482fdf599fae111626fb6) +- [Tests] migrate from travis to GHA [`806eda7`](https://github.com/form-data/form-data/commit/806eda77740e6e3c67c7815afb216f2e1f187ba5) +- [Tests] migrate from travis to GHA [`8fdb3bc`](https://github.com/form-data/form-data/commit/8fdb3bc6b5d001f8909a9fca391d1d1d97ef1d79) +- [Refactor] use `Object.prototype.hasOwnProperty.call` [`7fecefe`](https://github.com/form-data/form-data/commit/7fecefe4ba8f775634aff86a698776ad95ecffb5) +- [Refactor] use `Object.prototype.hasOwnProperty.call` [`6e682d4`](https://github.com/form-data/form-data/commit/6e682d4bd41de7e80de41e3c4ee10f23fcc3dd00) +- [Refactor] use `Object.prototype.hasOwnProperty.call` [`df3c1e6`](https://github.com/form-data/form-data/commit/df3c1e6f0937f47a782dc4573756a54987f31dde) +- [Dev Deps] update `@types/node`, `browserify`, `coveralls`, `cross-spawn`, `eslint`, `formidable`, `in-publish`, `pkgfiles`, `pre-commit`, `puppeteer`, `request`, `tape`, `typescript` [`8261fcb`](https://github.com/form-data/form-data/commit/8261fcb8bf5944d30ae3bd04b91b71d6a9932ef4) +- [Dev Deps] update `@types/node`, `browserify`, `coveralls`, `cross-spawn`, `eslint`, `formidable`, `in-publish`, `pkgfiles`, `pre-commit`, `puppeteer`, `request`, `tape`, `typescript` [`fb66cb7`](https://github.com/form-data/form-data/commit/fb66cb740e29fb170eee947d4be6fdf82d6659af) +- [Dev Deps] update `@types/node`, `browserify`, `coveralls`, `eslint`, `formidable`, `in-publish`, `phantomjs-prebuilt`, `pkgfiles`, `pre-commit`, `request`, `tape`, `typescript` [`819f6b7`](https://github.com/form-data/form-data/commit/819f6b7a543306a891fca37c3a06d0ff4a734422) +- [eslint] clean up ignores [`3217b3d`](https://github.com/form-data/form-data/commit/3217b3ded8e382e51171d5c74c6038a21cc54440) +- [eslint] clean up ignores [`3a9d480`](https://github.com/form-data/form-data/commit/3a9d480232dbcbc07260ad84c3da4975d9a3ae9e) +- [Fix] `Buffer.from` and `Buffer.alloc` require node 4+ [`c499f76`](https://github.com/form-data/form-data/commit/c499f76f1faac1ddbf210c45217038e4c1e02337) +- Only apps should have lockfiles [`b82f590`](https://github.com/form-data/form-data/commit/b82f59093cdbadb4b7ec0922d33ae7ab048b82ff) +- Only apps should have lockfiles [`b170ee2`](https://github.com/form-data/form-data/commit/b170ee2b22b4c695c363b811c0c553d2fb1bbd79) +- [Deps] update `combined-stream`, `mime-types` [`6b1ca1d`](https://github.com/form-data/form-data/commit/6b1ca1dc7362a1b1c3a99a885516cca4b7eb817f) +- [Dev Deps] pin `request` which via `tough-cookie` ^2.4 depends on `psl` [`e5df7f2`](https://github.com/form-data/form-data/commit/e5df7f24383342264bd73dee3274818a40d04065) +- [Deps] update `mime-types` [`5a5bafe`](https://github.com/form-data/form-data/commit/5a5bafee894fead10da49e1fa2b084e17f2e1034) +- Bumped version 2.5.3 [`9457283`](https://github.com/form-data/form-data/commit/9457283e1dce6122adc908fdd7442cfc54cabe7a) +- [Dev Deps] pin `request` which via `tough-cookie` ^2.4 depends on `psl` [`9dbe192`](https://github.com/form-data/form-data/commit/9dbe192be3db215eac4d9c0b980470a5c2c030c6) +- Merge tags v2.5.2 and v3.0.2 [`d53265d`](https://github.com/form-data/form-data/commit/d53265d86c5153f535ec68eb107548b1b2883576) +- Bumped version 2.5.2 [`7020dd4`](https://github.com/form-data/form-data/commit/7020dd4c1260370abc40e86e3dfe49c5d576fbda) +- [Dev Deps] downgrade `cross-spawn` [`3fc1a9b`](https://github.com/form-data/form-data/commit/3fc1a9b62ddf1fe77a2bd6bd3476e4c0a9e01a88) +- fix: move util.isArray to Array.isArray (#564) [`edb555a`](https://github.com/form-data/form-data/commit/edb555a811f6f7e4668db4831551cf41c1de1cac) +- fix: move util.isArray to Array.isArray (#564) [`10418d1`](https://github.com/form-data/form-data/commit/10418d1fe4b0d65fe020eafe3911feb5ad5e2bd6) + +## [v4.0.1](https://github.com/form-data/form-data/compare/v4.0.0...v4.0.1) - 2024-10-10 + +### Commits + +- [Tests] migrate from travis to GHA [`757b4e3`](https://github.com/form-data/form-data/commit/757b4e32e95726aec9bdcc771fb5a3b564d88034) +- [eslint] clean up ignores [`e8f0d80`](https://github.com/form-data/form-data/commit/e8f0d80cd7cd424d1488532621ec40a33218b30b) +- fix (npmignore): ignore temporary build files [`335ad19`](https://github.com/form-data/form-data/commit/335ad19c6e17dc2d7298ffe0e9b37ba63600e94b) +- fix: move util.isArray to Array.isArray [`440d3be`](https://github.com/form-data/form-data/commit/440d3bed752ac2f9213b4c2229dbccefe140e5fa) + +## [v4.0.0](https://github.com/form-data/form-data/compare/v3.0.4...v4.0.0) - 2021-02-15 + +### Merged + +- Handle custom stream [`#382`](https://github.com/form-data/form-data/pull/382) + +### Commits + +- Fix typo [`e705c0a`](https://github.com/form-data/form-data/commit/e705c0a1fdaf90d21501f56460b93e43a18bd435) +- Update README for custom stream behavior [`6dd8624`](https://github.com/form-data/form-data/commit/6dd8624b2999e32768d62752c9aae5845a803b0d) + +## [v3.0.4](https://github.com/form-data/form-data/compare/v3.0.3...v3.0.4) - 2025-07-16 + +### Fixed + +- [Fix] `append`: avoid a crash on nullish values [`#577`](https://github.com/form-data/form-data/issues/577) + +### Commits + +- [eslint] update linting config [`f5e7eb0`](https://github.com/form-data/form-data/commit/f5e7eb024bc3fc7e2074ff80f143a4f4cbc1dbda) +- [meta] add `auto-changelog` [`d2eb290`](https://github.com/form-data/form-data/commit/d2eb290a3e47ed5bcad7020d027daa15b3cf5ef5) +- [Tests] handle predict-v8-randomness failures in node < 17 and node > 23 [`e8c574c`](https://github.com/form-data/form-data/commit/e8c574cb07ff3a0de2ecc0912d783ef22e190c1f) +- [Fix] Switch to using `crypto` random for boundary values [`c6ced61`](https://github.com/form-data/form-data/commit/c6ced61d4fae8f617ee2fd692133ed87baa5d0fd) +- [Refactor] use `hasown` [`1a78b5d`](https://github.com/form-data/form-data/commit/1a78b5dd05e508d67e97764d812ac7c6d92ea88d) +- [Fix] validate boundary type in `setBoundary()` method [`70bbaa0`](https://github.com/form-data/form-data/commit/70bbaa0b395ca0fb975c309de8d7286979254cc4) +- [Tests] add tests to check the behavior of `getBoundary` with non-strings [`b22a64e`](https://github.com/form-data/form-data/commit/b22a64ef94ba4f3f6ff7d1ac72a54cca128567df) +- [meta] actually ensure the readme backup isn’t published [`0150851`](https://github.com/form-data/form-data/commit/01508513ffb26fd662ae7027834b325af8efb9ea) +- [meta] remove local commit hooks [`fc42bb9`](https://github.com/form-data/form-data/commit/fc42bb9315b641bfa6dae51cb4e188a86bb04769) +- [Dev Deps] remove unused deps [`a14d09e`](https://github.com/form-data/form-data/commit/a14d09ea8ed7e0a2e1705269ce6fb54bb7ee6bdb) +- [meta] fix scripts to use prepublishOnly [`11d9f73`](https://github.com/form-data/form-data/commit/11d9f7338f18a59b431832a3562b49baece0a432) +- [meta] fix readme capitalization [`fc38b48`](https://github.com/form-data/form-data/commit/fc38b4834a117a1856f3d877eb2f5b7496a24932) + +## [v3.0.3](https://github.com/form-data/form-data/compare/v3.0.2...v3.0.3) - 2025-02-14 + +### Merged + +- [Fix] set `Symbol.toStringTag` when available [`#573`](https://github.com/form-data/form-data/pull/573) + +### Fixed + +- [Fix] set `Symbol.toStringTag` when available (#573) [`#396`](https://github.com/form-data/form-data/issues/396) + +### Commits + +- [Refactor] use `Object.prototype.hasOwnProperty.call` [`7fecefe`](https://github.com/form-data/form-data/commit/7fecefe4ba8f775634aff86a698776ad95ecffb5) +- [Dev Deps] update `@types/node`, `browserify`, `coveralls`, `cross-spawn`, `eslint`, `formidable`, `in-publish`, `pkgfiles`, `pre-commit`, `puppeteer`, `request`, `tape`, `typescript` [`8261fcb`](https://github.com/form-data/form-data/commit/8261fcb8bf5944d30ae3bd04b91b71d6a9932ef4) +- Only apps should have lockfiles [`b82f590`](https://github.com/form-data/form-data/commit/b82f59093cdbadb4b7ec0922d33ae7ab048b82ff) +- [Dev Deps] pin `request` which via `tough-cookie` ^2.4 depends on `psl` [`e5df7f2`](https://github.com/form-data/form-data/commit/e5df7f24383342264bd73dee3274818a40d04065) +- [Deps] update `mime-types` [`5a5bafe`](https://github.com/form-data/form-data/commit/5a5bafee894fead10da49e1fa2b084e17f2e1034) + +## [v3.0.2](https://github.com/form-data/form-data/compare/v3.0.1...v3.0.2) - 2024-10-10 + +### Merged + +- fix (npmignore): ignore temporary build files [`#532`](https://github.com/form-data/form-data/pull/532) + +### Commits + +- [Tests] migrate from travis to GHA [`8fdb3bc`](https://github.com/form-data/form-data/commit/8fdb3bc6b5d001f8909a9fca391d1d1d97ef1d79) +- [eslint] clean up ignores [`3217b3d`](https://github.com/form-data/form-data/commit/3217b3ded8e382e51171d5c74c6038a21cc54440) +- fix: move util.isArray to Array.isArray (#564) [`edb555a`](https://github.com/form-data/form-data/commit/edb555a811f6f7e4668db4831551cf41c1de1cac) + +## [v3.0.1](https://github.com/form-data/form-data/compare/v3.0.0...v3.0.1) - 2021-02-15 + +### Merged + +- Fix typo: ads -> adds [`#451`](https://github.com/form-data/form-data/pull/451) + +### Commits + +- feat: add setBoundary method [`55d90ce`](https://github.com/form-data/form-data/commit/55d90ce4a4c22b0ea0647991d85cb946dfb7395b) + +## [v3.0.0](https://github.com/form-data/form-data/compare/v2.5.5...v3.0.0) - 2019-11-05 + +### Merged + +- Update Readme.md [`#449`](https://github.com/form-data/form-data/pull/449) +- Update package.json [`#448`](https://github.com/form-data/form-data/pull/448) +- fix memory leak [`#447`](https://github.com/form-data/form-data/pull/447) +- form-data: Replaced PhantomJS Dependency [`#442`](https://github.com/form-data/form-data/pull/442) +- Fix constructor options in Typescript definitions [`#446`](https://github.com/form-data/form-data/pull/446) +- Fix the getHeaders method signatures [`#434`](https://github.com/form-data/form-data/pull/434) +- Update combined-stream (fixes #422) [`#424`](https://github.com/form-data/form-data/pull/424) + +### Fixed + +- Merge pull request #424 from botgram/update-combined-stream [`#422`](https://github.com/form-data/form-data/issues/422) +- Update combined-stream (fixes #422) [`#422`](https://github.com/form-data/form-data/issues/422) + +### Commits + +- Add readable stream options to constructor type [`80c8f74`](https://github.com/form-data/form-data/commit/80c8f746bcf4c0418ae35fbedde12fb8c01e2748) +- Fixed: getHeaders method signatures [`f4ca7f8`](https://github.com/form-data/form-data/commit/f4ca7f8e31f7e07df22c1aeb8e0a32a7055a64ca) +- Pass options to constructor if not used with new [`4bde68e`](https://github.com/form-data/form-data/commit/4bde68e12de1ba90fefad2e7e643f6375b902763) +- Make userHeaders optional [`2b4e478`](https://github.com/form-data/form-data/commit/2b4e4787031490942f2d1ee55c56b85a250875a7) + +## [v2.5.5](https://github.com/form-data/form-data/compare/v2.5.4...v2.5.5) - 2025-07-18 + +### Commits + +- [meta] actually ensure the readme backup isn’t published [`10626c0`](https://github.com/form-data/form-data/commit/10626c0a9b78c7d3fcaa51772265015ee0afc25c) +- [Fix] use proper dependency [`026abe5`](https://github.com/form-data/form-data/commit/026abe5c5c0489d8a2ccb59d5cfd14fb63078377) + +## [v2.5.4](https://github.com/form-data/form-data/compare/v2.5.3...v2.5.4) - 2025-07-17 + +### Fixed + +- [Fix] `append`: avoid a crash on nullish values [`#577`](https://github.com/form-data/form-data/issues/577) + +### Commits + +- [eslint] update linting config [`8bf2492`](https://github.com/form-data/form-data/commit/8bf2492e0555d41ff58fa04c91593af998f87a3c) +- [meta] add `auto-changelog` [`b5101ad`](https://github.com/form-data/form-data/commit/b5101ad3d5f73cfd0143aae3735b92826fd731ea) +- [Tests] handle predict-v8-randomness failures in node < 17 and node > 23 [`0e93122`](https://github.com/form-data/form-data/commit/0e93122358414942393d9c2dc434ae69e58be7c8) +- [Fix] Switch to using `crypto` random for boundary values [`b88316c`](https://github.com/form-data/form-data/commit/b88316c94bb004323669cd3639dc8bb8262539eb) +- [Fix] validate boundary type in `setBoundary()` method [`131ae5e`](https://github.com/form-data/form-data/commit/131ae5efa30b9c608add4faef3befb38aa2e1bf1) +- [Tests] Switch to newer v8 prediction library; enable node 24 testing [`c97cfbe`](https://github.com/form-data/form-data/commit/c97cfbed9eb6d2d4b5d53090f69ded4bf9fd8a21) +- [Refactor] use `hasown` [`97ac9c2`](https://github.com/form-data/form-data/commit/97ac9c208be0b83faeee04bb3faef1ed3474ee4c) +- [meta] remove local commit hooks [`be99d4e`](https://github.com/form-data/form-data/commit/be99d4eea5ce47139c23c1f0914596194019d7fb) +- [Dev Deps] remove unused deps [`ddbc89b`](https://github.com/form-data/form-data/commit/ddbc89b6d6d64f730bcb27cb33b7544068466a05) +- [meta] fix scripts to use prepublishOnly [`e351a97`](https://github.com/form-data/form-data/commit/e351a97e9f6c57c74ffd01625e83b09de805d08a) +- [Dev Deps] remove unused script [`8f23366`](https://github.com/form-data/form-data/commit/8f233664842da5bd605ce85541defc713d1d1e0a) +- [Dev Deps] add missing peer dep [`02ff026`](https://github.com/form-data/form-data/commit/02ff026fda71f9943cfdd5754727c628adb8d135) +- [meta] fix readme capitalization [`2fd5f61`](https://github.com/form-data/form-data/commit/2fd5f61ebfb526cd015fb8e7b8b8c1add4a38872) + +## [v2.5.3](https://github.com/form-data/form-data/compare/v2.5.2...v2.5.3) - 2025-02-14 + +### Merged + +- [Fix] set `Symbol.toStringTag` when available [`#573`](https://github.com/form-data/form-data/pull/573) + +### Fixed + +- [Fix] set `Symbol.toStringTag` when available (#573) [`#396`](https://github.com/form-data/form-data/issues/396) + +### Commits + +- [Refactor] use `Object.prototype.hasOwnProperty.call` [`6e682d4`](https://github.com/form-data/form-data/commit/6e682d4bd41de7e80de41e3c4ee10f23fcc3dd00) +- [Dev Deps] update `@types/node`, `browserify`, `coveralls`, `eslint`, `formidable`, `in-publish`, `phantomjs-prebuilt`, `pkgfiles`, `pre-commit`, `request`, `tape`, `typescript` [`819f6b7`](https://github.com/form-data/form-data/commit/819f6b7a543306a891fca37c3a06d0ff4a734422) +- Only apps should have lockfiles [`b170ee2`](https://github.com/form-data/form-data/commit/b170ee2b22b4c695c363b811c0c553d2fb1bbd79) +- [Deps] update `combined-stream`, `mime-types` [`6b1ca1d`](https://github.com/form-data/form-data/commit/6b1ca1dc7362a1b1c3a99a885516cca4b7eb817f) +- Bumped version 2.5.3 [`9457283`](https://github.com/form-data/form-data/commit/9457283e1dce6122adc908fdd7442cfc54cabe7a) +- [Dev Deps] pin `request` which via `tough-cookie` ^2.4 depends on `psl` [`9dbe192`](https://github.com/form-data/form-data/commit/9dbe192be3db215eac4d9c0b980470a5c2c030c6) + +## [v2.5.2](https://github.com/form-data/form-data/compare/v2.5.1...v2.5.2) - 2024-10-10 + +### Merged + +- fix (npmignore): ignore temporary build files [`#532`](https://github.com/form-data/form-data/pull/532) + +### Commits + +- [Tests] migrate from travis to GHA [`806eda7`](https://github.com/form-data/form-data/commit/806eda77740e6e3c67c7815afb216f2e1f187ba5) +- [eslint] clean up ignores [`3a9d480`](https://github.com/form-data/form-data/commit/3a9d480232dbcbc07260ad84c3da4975d9a3ae9e) +- [Fix] `Buffer.from` and `Buffer.alloc` require node 4+ [`c499f76`](https://github.com/form-data/form-data/commit/c499f76f1faac1ddbf210c45217038e4c1e02337) +- Bumped version 2.5.2 [`7020dd4`](https://github.com/form-data/form-data/commit/7020dd4c1260370abc40e86e3dfe49c5d576fbda) +- [Dev Deps] downgrade `cross-spawn` [`3fc1a9b`](https://github.com/form-data/form-data/commit/3fc1a9b62ddf1fe77a2bd6bd3476e4c0a9e01a88) +- fix: move util.isArray to Array.isArray (#564) [`10418d1`](https://github.com/form-data/form-data/commit/10418d1fe4b0d65fe020eafe3911feb5ad5e2bd6) + +## [v2.5.1](https://github.com/form-data/form-data/compare/v2.5.0...v2.5.1) - 2019-08-28 + +### Merged + +- Fix error in callback signatures [`#435`](https://github.com/form-data/form-data/pull/435) +- -Fixed: Eerror in the documentations as indicated in #439 [`#440`](https://github.com/form-data/form-data/pull/440) +- Add constructor options to TypeScript defs [`#437`](https://github.com/form-data/form-data/pull/437) + +### Commits + +- Add remaining combined-stream options to typedef [`4d41a32`](https://github.com/form-data/form-data/commit/4d41a32c0b3f85f8bbc9cf17df43befd2d5fc305) +- Bumped version 2.5.1 [`8ce81f5`](https://github.com/form-data/form-data/commit/8ce81f56cccf5466363a5eff135ad394a929f59b) +- Bump rimraf to 2.7.1 [`a6bc2d4`](https://github.com/form-data/form-data/commit/a6bc2d4296dbdee5d84cbab7c69bcd0eea7a12e2) + +## [v2.5.0](https://github.com/form-data/form-data/compare/v2.4.0...v2.5.0) - 2019-07-03 + +### Merged + +- - Added: public methods with information and examples to readme [`#429`](https://github.com/form-data/form-data/pull/429) +- chore: move @types/node to devDep [`#431`](https://github.com/form-data/form-data/pull/431) +- Switched windows tests from AppVeyor to Travis [`#430`](https://github.com/form-data/form-data/pull/430) +- feat(typings): migrate TS typings #427 [`#428`](https://github.com/form-data/form-data/pull/428) +- enhance the method of path.basename, handle undefined case [`#421`](https://github.com/form-data/form-data/pull/421) + +### Commits + +- - Added: public methods with information and examples to the readme file. [`21323f3`](https://github.com/form-data/form-data/commit/21323f3b4043a167046a4a2554c5f2825356c423) +- feat(typings): migrate TS typings [`a3c0142`](https://github.com/form-data/form-data/commit/a3c0142ed91b0c7dcaf89c4f618776708f1f70a9) +- - Fixed: Typos [`37350fa`](https://github.com/form-data/form-data/commit/37350fa250782f156a998ec1fa9671866d40ac49) +- Switched to Travis Windows from Appveyor [`fc61c73`](https://github.com/form-data/form-data/commit/fc61c7381fad12662df16dbc3e7621c91b886f03) +- - Fixed: rendering of subheaders [`e93ed8d`](https://github.com/form-data/form-data/commit/e93ed8df9d7f22078bc3a2c24889e9dfa11e192d) +- Updated deps and readme [`e3d8628`](https://github.com/form-data/form-data/commit/e3d8628728f6e4817ab97deeed92f0c822661b89) +- Updated dependencies [`19add50`](https://github.com/form-data/form-data/commit/19add50afb7de66c70d189f422d16f1b886616e2) +- Bumped version to 2.5.0 [`905f173`](https://github.com/form-data/form-data/commit/905f173a3f785e8d312998e765634ee451ca5f42) +- - Fixed: filesize is not a valid option? knownLength should be used for streams [`d88f912`](https://github.com/form-data/form-data/commit/d88f912b75b666b47f8674467516eade69d2d5be) +- Bump notion of modern node to node8 [`508b626`](https://github.com/form-data/form-data/commit/508b626bf1b460d3733d3420dc1cfd001617f6ac) +- enhance the method of path.basename [`faaa68a`](https://github.com/form-data/form-data/commit/faaa68a297be7d4fca0ac4709d5b93afc1f78b5c) + +## [v2.4.0](https://github.com/form-data/form-data/compare/v2.3.2...v2.4.0) - 2019-06-19 + +### Merged + +- Added "getBuffer" method and updated certificates [`#419`](https://github.com/form-data/form-data/pull/419) +- docs(readme): add axios integration document [`#425`](https://github.com/form-data/form-data/pull/425) +- Allow newer versions of combined-stream [`#402`](https://github.com/form-data/form-data/pull/402) + +### Commits + +- Updated: Certificate [`e90a76a`](https://github.com/form-data/form-data/commit/e90a76ab3dcaa63a6f3045f8255bfbb9c25a3e4e) +- Updated build/test/badges [`8512eef`](https://github.com/form-data/form-data/commit/8512eef436e28372f5bc88de3ca76a9cb46e6847) +- Bumped version 2.4.0 [`0f8da06`](https://github.com/form-data/form-data/commit/0f8da06c0b4c997bd2f6b09d78290d339616a950) +- docs(readme): remove unnecessary bracket [`4e3954d`](https://github.com/form-data/form-data/commit/4e3954dde304d27e3b95371d8c78002f3af5d5b2) +- Bumped version to 2.3.3 [`b16916a`](https://github.com/form-data/form-data/commit/b16916a568a0d06f3f8a16c31f9a8b89b7844094) + +## [v2.3.2](https://github.com/form-data/form-data/compare/v2.3.1...v2.3.2) - 2018-02-13 + +### Merged + +- Pulling in fixed combined-stream [`#379`](https://github.com/form-data/form-data/pull/379) + +### Commits + +- All the dev dependencies are breaking in old versions of node :'( [`c7dba6a`](https://github.com/form-data/form-data/commit/c7dba6a139d872d173454845e25e1850ed6b72b4) +- Updated badges [`19b6c7a`](https://github.com/form-data/form-data/commit/19b6c7a8a5c40f47f91c8a8da3e5e4dc3c449fa3) +- Try tests in node@4 [`872a326`](https://github.com/form-data/form-data/commit/872a326ab13e2740b660ff589b75232c3a85fcc9) +- Pull in final version [`9d44871`](https://github.com/form-data/form-data/commit/9d44871073d647995270b19dbc26f65671ce15c7) + +## [v2.3.1](https://github.com/form-data/form-data/compare/v2.3.0...v2.3.1) - 2017-08-24 + +### Commits + +- Updated readme with custom options example [`8e0a569`](https://github.com/form-data/form-data/commit/8e0a5697026016fe171e93bec43c2205279e23ca) +- Added support (tests) for node 8 [`d1d6f4a`](https://github.com/form-data/form-data/commit/d1d6f4ad4670d8ba84cc85b28e522ca0e93eb362) + +## [v2.3.0](https://github.com/form-data/form-data/compare/v2.2.0...v2.3.0) - 2017-08-24 + +### Merged + +- Added custom `options` support [`#368`](https://github.com/form-data/form-data/pull/368) +- Allow form.submit with url string param to use https [`#249`](https://github.com/form-data/form-data/pull/249) +- Proper header production [`#357`](https://github.com/form-data/form-data/pull/357) +- Fix wrong MIME type in example [`#285`](https://github.com/form-data/form-data/pull/285) + +### Commits + +- allow form.submit with url string param to use https [`c0390dc`](https://github.com/form-data/form-data/commit/c0390dcc623e15215308fa2bb0225aa431d9381e) +- update tests for url parsing [`eec0e80`](https://github.com/form-data/form-data/commit/eec0e807889d46697abd39a89ad9bf39996ba787) +- Uses for in to assign properties instead of Object.assign [`f6854ed`](https://github.com/form-data/form-data/commit/f6854edd85c708191bb9c89615a09fd0a9afe518) +- Adds test to check for option override [`61762f2`](https://github.com/form-data/form-data/commit/61762f2c5262e576d6a7f778b4ebab6546ef8582) +- Removes the 2mb maxDataSize limitation [`dc171c3`](https://github.com/form-data/form-data/commit/dc171c3ba49ac9b8813636fd4159d139b812315b) +- Ignore .DS_Store [`e8a05d3`](https://github.com/form-data/form-data/commit/e8a05d33361f7dca8927fe1d96433d049843de24) + +## [v2.2.0](https://github.com/form-data/form-data/compare/v2.1.4...v2.2.0) - 2017-06-11 + +### Merged + +- Filename can be a nested path [`#355`](https://github.com/form-data/form-data/pull/355) + +### Commits + +- Bumped version number. [`d7398c3`](https://github.com/form-data/form-data/commit/d7398c3e7cd81ed12ecc0b84363721bae467db02) + +## [v2.1.4](https://github.com/form-data/form-data/compare/2.1.3...v2.1.4) - 2017-04-08 + +## [2.1.3](https://github.com/form-data/form-data/compare/v2.1.3...2.1.3) - 2017-04-08 + +## [v2.1.3](https://github.com/form-data/form-data/compare/v2.1.2...v2.1.3) - 2017-04-08 + +### Merged + +- toString should output '[object FormData]' [`#346`](https://github.com/form-data/form-data/pull/346) + +## [v2.1.2](https://github.com/form-data/form-data/compare/v2.1.1...v2.1.2) - 2016-11-07 + +### Merged + +- #271 Added check for self and window objects + tests [`#282`](https://github.com/form-data/form-data/pull/282) + +### Commits + +- Added check for self and window objects + tests [`c99e4ec`](https://github.com/form-data/form-data/commit/c99e4ec32cd14d83776f2bdcc5a4e7384131c1b1) + +## [v2.1.1](https://github.com/form-data/form-data/compare/v2.1.0...v2.1.1) - 2016-10-03 + +### Merged + +- Bumped dependencies. [`#270`](https://github.com/form-data/form-data/pull/270) +- Update browser.js shim to use self instead of window [`#267`](https://github.com/form-data/form-data/pull/267) +- Boilerplate code rediction [`#265`](https://github.com/form-data/form-data/pull/265) +- eslint@3.7.0 [`#266`](https://github.com/form-data/form-data/pull/266) + +### Commits + +- code duplicates removed [`e9239fb`](https://github.com/form-data/form-data/commit/e9239fbe7d3c897b29fe3bde857d772469541c01) +- Changed according to requests [`aa99246`](https://github.com/form-data/form-data/commit/aa9924626bd9168334d73fea568c0ad9d8fbaa96) +- chore(package): update eslint to version 3.7.0 [`090a859`](https://github.com/form-data/form-data/commit/090a859835016cab0de49629140499e418db9c3a) + +## [v2.1.0](https://github.com/form-data/form-data/compare/v2.0.0...v2.1.0) - 2016-09-25 + +### Merged + +- Added `hasKnownLength` public method [`#263`](https://github.com/form-data/form-data/pull/263) + +### Commits + +- Added hasKnownLength public method [`655b959`](https://github.com/form-data/form-data/commit/655b95988ef2ed3399f8796b29b2a8673c1df11c) + +## [v2.0.0](https://github.com/form-data/form-data/compare/v1.0.0...v2.0.0) - 2016-09-16 + +### Merged + +- Replaced async with asynckit [`#258`](https://github.com/form-data/form-data/pull/258) +- Pre-release house cleaning [`#247`](https://github.com/form-data/form-data/pull/247) + +### Commits + +- Replaced async with asynckit. Modernized [`1749b78`](https://github.com/form-data/form-data/commit/1749b78d50580fbd080e65c1eb9702ad4f4fc0c0) +- Ignore .bak files [`c08190a`](https://github.com/form-data/form-data/commit/c08190a87d3e22a528b6e32b622193742a4c2672) +- Trying to be more chatty. :) [`c79eabb`](https://github.com/form-data/form-data/commit/c79eabb24eaf761069255a44abf4f540cfd47d40) + +## [v1.0.0](https://github.com/form-data/form-data/compare/v1.0.0-rc4...v1.0.0) - 2016-08-26 + +### Merged + +- Allow custom header fields to be set as an object. [`#190`](https://github.com/form-data/form-data/pull/190) +- v1.0.0-rc4 [`#182`](https://github.com/form-data/form-data/pull/182) +- Avoid undefined variable reference in older browsers [`#176`](https://github.com/form-data/form-data/pull/176) +- More housecleaning [`#164`](https://github.com/form-data/form-data/pull/164) +- More cleanup [`#159`](https://github.com/form-data/form-data/pull/159) +- Added windows testing. Some cleanup. [`#158`](https://github.com/form-data/form-data/pull/158) +- Housecleaning. Added test coverage. [`#156`](https://github.com/form-data/form-data/pull/156) +- Second iteration of cleanup. [`#145`](https://github.com/form-data/form-data/pull/145) + +### Commits + +- Pre-release house cleaning [`440d72b`](https://github.com/form-data/form-data/commit/440d72b5fd44dd132f42598c3183d46e5f35ce71) +- Updated deps, updated docs [`54b6114`](https://github.com/form-data/form-data/commit/54b61143e9ce66a656dd537a1e7b31319a4991be) +- make docs up-to-date [`5e383d7`](https://github.com/form-data/form-data/commit/5e383d7f1466713f7fcef58a6817e0cb466c8ba7) +- Added missing deps [`fe04862`](https://github.com/form-data/form-data/commit/fe04862000b2762245e2db69d5207696a08c1174) + +## [v1.0.0-rc4](https://github.com/form-data/form-data/compare/v1.0.0-rc3...v1.0.0-rc4) - 2016-03-15 + +### Merged + +- Housecleaning, preparing for the release [`#144`](https://github.com/form-data/form-data/pull/144) +- lib: emit error when failing to get length [`#127`](https://github.com/form-data/form-data/pull/127) +- Cleaning up for Codacity 2. [`#143`](https://github.com/form-data/form-data/pull/143) +- Cleaned up codacity concerns. [`#142`](https://github.com/form-data/form-data/pull/142) +- Should throw type error without new operator. [`#129`](https://github.com/form-data/form-data/pull/129) + +### Commits + +- More cleanup [`94b6565`](https://github.com/form-data/form-data/commit/94b6565bb98a387335c72feff5ed5c10da0a7f6f) +- Shuffling things around [`3c2f172`](https://github.com/form-data/form-data/commit/3c2f172eaddf0979b3eef5c73985d1a6fd3eee4a) +- Second iteration of cleanup. [`347c88e`](https://github.com/form-data/form-data/commit/347c88ef9a99a66b9bcf4278497425db2f0182b2) +- Housecleaning [`c335610`](https://github.com/form-data/form-data/commit/c3356100c054a4695e4dec8ed7072775cd745616) +- More housecleaning [`f573321`](https://github.com/form-data/form-data/commit/f573321824aae37ba2052a92cc889d533d9f8fb8) +- Trying to make far run on windows. + cleanup [`e426dfc`](https://github.com/form-data/form-data/commit/e426dfcefb07ee307d8a15dec04044cce62413e6) +- Playing with appveyor [`c9458a7`](https://github.com/form-data/form-data/commit/c9458a7c328782b19859bc1745e7d6b2005ede86) +- Updated dev dependencies. [`ceebe88`](https://github.com/form-data/form-data/commit/ceebe88872bb22da0a5a98daf384e3cc232928d3) +- Replaced win-spawn with cross-spawn [`405a69e`](https://github.com/form-data/form-data/commit/405a69ee34e235ee6561b5ff0140b561be40d1cc) +- Updated readme badges. [`12f282a`](https://github.com/form-data/form-data/commit/12f282a1310fcc2f70cc5669782283929c32a63d) +- Making paths windows friendly. [`f4bddc5`](https://github.com/form-data/form-data/commit/f4bddc5955e2472f8e23c892c9b4d7a08fcb85a3) +- [WIP] trying things for greater sanity [`8ad1f02`](https://github.com/form-data/form-data/commit/8ad1f02b0b3db4a0b00c5d6145ed69bcb7558213) +- Bending under Codacy [`bfff3bb`](https://github.com/form-data/form-data/commit/bfff3bb36052dc83f429949b4e6f9b146a49d996) +- Another attempt to make windows friendly [`f3eb628`](https://github.com/form-data/form-data/commit/f3eb628974ccb91ba0020f41df490207eeed77f6) +- Updated dependencies. [`f73996e`](https://github.com/form-data/form-data/commit/f73996e0508ee2d4b2b376276adfac1de4188ac2) +- Missed travis changes. [`67ee79f`](https://github.com/form-data/form-data/commit/67ee79f964fdabaf300bd41b0af0c1cfaca07687) +- Restructured badges. [`48444a1`](https://github.com/form-data/form-data/commit/48444a1ff156ba2c2c3cfd11047c2f2fd92d4474) +- Add similar type error as the browser for attempting to use form-data without new. [`5711320`](https://github.com/form-data/form-data/commit/5711320fb7c8cc620cfc79b24c7721526e23e539) +- Took out codeclimate-test-reporter [`a7e0c65`](https://github.com/form-data/form-data/commit/a7e0c6522afe85ca9974b0b4e1fca9c77c3e52b1) +- One more [`8e84cff`](https://github.com/form-data/form-data/commit/8e84cff3370526ecd3e175fd98e966242d81993c) + +## [v1.0.0-rc3](https://github.com/form-data/form-data/compare/v1.0.0-rc2...v1.0.0-rc3) - 2015-07-29 + +### Merged + +- House cleaning. Added `pre-commit`. [`#140`](https://github.com/form-data/form-data/pull/140) +- Allow custom content-type without setting a filename. [`#138`](https://github.com/form-data/form-data/pull/138) +- Add node-fetch to alternative submission methods. [`#132`](https://github.com/form-data/form-data/pull/132) +- Update dependencies [`#130`](https://github.com/form-data/form-data/pull/130) +- Switching to container based TravisCI [`#136`](https://github.com/form-data/form-data/pull/136) +- Default content-type to 'application/octect-stream' [`#128`](https://github.com/form-data/form-data/pull/128) +- Allow filename as third option of .append [`#125`](https://github.com/form-data/form-data/pull/125) + +### Commits + +- Allow custom content-type without setting a filename [`c8a77cc`](https://github.com/form-data/form-data/commit/c8a77cc0cf16d15f1ebf25272beaab639ce89f76) +- Fixed ranged test. [`a5ac58c`](https://github.com/form-data/form-data/commit/a5ac58cbafd0909f32fe8301998f689314fd4859) +- Allow filename as third option of #append [`d081005`](https://github.com/form-data/form-data/commit/d0810058c84764b3c463a18b15ebb37864de9260) +- Allow custom content-type without setting a filename [`8cb9709`](https://github.com/form-data/form-data/commit/8cb9709e5f1809cfde0cd707dbabf277138cd771) + +## [v1.0.0-rc2](https://github.com/form-data/form-data/compare/v1.0.0-rc1...v1.0.0-rc2) - 2015-07-21 + +### Merged + +- #109 Append proper line break [`#123`](https://github.com/form-data/form-data/pull/123) +- Add shim for browser (browserify/webpack). [`#122`](https://github.com/form-data/form-data/pull/122) +- Update license field [`#115`](https://github.com/form-data/form-data/pull/115) + +### Commits + +- Add shim for browser. [`87c33f4`](https://github.com/form-data/form-data/commit/87c33f4269a2211938f80ab3e53835362b1afee8) +- Bump version [`a3f5d88`](https://github.com/form-data/form-data/commit/a3f5d8872c810ce240c7d3838c69c3c9fcecc111) + +## [v1.0.0-rc1](https://github.com/form-data/form-data/compare/0.2...v1.0.0-rc1) - 2015-06-13 + +### Merged + +- v1.0.0-rc1 [`#114`](https://github.com/form-data/form-data/pull/114) +- Updated test targets [`#102`](https://github.com/form-data/form-data/pull/102) +- Remove duplicate plus sign [`#94`](https://github.com/form-data/form-data/pull/94) + +### Commits + +- Made https test local. Updated deps. [`afe1959`](https://github.com/form-data/form-data/commit/afe1959ec711f23e57038ab5cb20fedd86271f29) +- Proper self-signed ssl [`4d5ec50`](https://github.com/form-data/form-data/commit/4d5ec50e81109ad2addf3dbb56dc7c134df5ff87) +- Update HTTPS handling for modern days [`2c11b01`](https://github.com/form-data/form-data/commit/2c11b01ce2c06e205c84d7154fa2f27b66c94f3b) +- Made tests more local [`09633fa`](https://github.com/form-data/form-data/commit/09633fa249e7ce3ac581543aafe16ee9039a823b) +- Auto create tmp folder for Formidable [`28714b7`](https://github.com/form-data/form-data/commit/28714b7f71ad556064cdff88fabe6b92bd407ddd) +- remove duplicate plus sign [`36e09c6`](https://github.com/form-data/form-data/commit/36e09c695b0514d91a23f5cd64e6805404776fc7) + +## [0.2](https://github.com/form-data/form-data/compare/0.1.4...0.2) - 2014-12-06 + +### Merged + +- Bumped version [`#96`](https://github.com/form-data/form-data/pull/96) +- Replace mime library. [`#95`](https://github.com/form-data/form-data/pull/95) +- #71 Respect bytes range in a read stream. [`#73`](https://github.com/form-data/form-data/pull/73) + +## [0.1.4](https://github.com/form-data/form-data/compare/0.1.3...0.1.4) - 2014-06-23 + +### Merged + +- Updated version. [`#76`](https://github.com/form-data/form-data/pull/76) +- #71 Respect bytes range in a read stream. [`#75`](https://github.com/form-data/form-data/pull/75) + +## [0.1.3](https://github.com/form-data/form-data/compare/0.1.2...0.1.3) - 2014-06-17 + +### Merged + +- Updated versions. [`#69`](https://github.com/form-data/form-data/pull/69) +- Added custom headers support [`#60`](https://github.com/form-data/form-data/pull/60) +- Added test for Request. Small fixes. [`#56`](https://github.com/form-data/form-data/pull/56) + +### Commits + +- Added test for the custom header functionality [`bd50685`](https://github.com/form-data/form-data/commit/bd506855af62daf728ef1718cae88ed23bb732f3) +- Documented custom headers option [`77a024a`](https://github.com/form-data/form-data/commit/77a024a9375f93c246c35513d80f37d5e11d35ff) +- Removed 0.6 support. [`aee8dce`](https://github.com/form-data/form-data/commit/aee8dce604c595cfaacfc6efb12453d1691ac0d6) + +## [0.1.2](https://github.com/form-data/form-data/compare/0.1.1...0.1.2) - 2013-10-02 + +### Merged + +- Fixed default https port assignment, added tests. [`#52`](https://github.com/form-data/form-data/pull/52) +- #45 Added tests for multi-submit. Updated readme. [`#49`](https://github.com/form-data/form-data/pull/49) +- #47 return request from .submit() [`#48`](https://github.com/form-data/form-data/pull/48) + +### Commits + +- Bumped version. [`2b761b2`](https://github.com/form-data/form-data/commit/2b761b256ae607fc2121621f12c2e1042be26baf) + +## [0.1.1](https://github.com/form-data/form-data/compare/0.1.0...0.1.1) - 2013-08-21 + +### Merged + +- Added license type and reference to package.json [`#46`](https://github.com/form-data/form-data/pull/46) + +### Commits + +- #47 return request from .submit() [`1d61c2d`](https://github.com/form-data/form-data/commit/1d61c2da518bd5e136550faa3b5235bb540f1e06) +- #47 Updated readme. [`e3dae15`](https://github.com/form-data/form-data/commit/e3dae1526bd3c3b9d7aff6075abdaac12c3cc60f) + +## [0.1.0](https://github.com/form-data/form-data/compare/0.0.10...0.1.0) - 2013-07-08 + +### Merged + +- Update master to 0.1.0 [`#44`](https://github.com/form-data/form-data/pull/44) +- 0.1.0 - Added error handling. Streamlined edge cases behavior. [`#43`](https://github.com/form-data/form-data/pull/43) +- Pointed badges back to mothership. [`#39`](https://github.com/form-data/form-data/pull/39) +- Updated node-fake to support 0.11 tests. [`#37`](https://github.com/form-data/form-data/pull/37) +- Updated tests to play nice with 0.10 [`#36`](https://github.com/form-data/form-data/pull/36) +- #32 Added .npmignore [`#34`](https://github.com/form-data/form-data/pull/34) +- Spring cleaning [`#30`](https://github.com/form-data/form-data/pull/30) + +### Commits + +- Added error handling. Streamlined edge cases behavior. [`4da496e`](https://github.com/form-data/form-data/commit/4da496e577cb9bc0fd6c94cbf9333a0082ce353a) +- Made tests more deterministic. [`7fc009b`](https://github.com/form-data/form-data/commit/7fc009b8a2cc9232514a44b2808b9f89ce68f7d2) +- Fixed styling. [`d373b41`](https://github.com/form-data/form-data/commit/d373b417e779024bc3326073e176383cd08c0b18) +- #40 Updated Readme.md regarding getLengthSync() [`efb373f`](https://github.com/form-data/form-data/commit/efb373fd63814d977960e0299d23c92cd876cfef) +- Updated readme. [`527e3a6`](https://github.com/form-data/form-data/commit/527e3a63b032cb6f576f597ad7ff2ebcf8a0b9b4) + +## [0.0.10](https://github.com/form-data/form-data/compare/0.0.9...0.0.10) - 2013-05-08 + +### Commits + +- Updated tests to play nice with 0.10. [`932b39b`](https://github.com/form-data/form-data/commit/932b39b773e49edcb2c5d2e58fe389ab6c42f47c) +- Added dependency tracking. [`3131d7f`](https://github.com/form-data/form-data/commit/3131d7f6996cd519d50547e4de1587fd80d0fa07) + +## 0.0.9 - 2013-04-29 + +### Merged + +- Custom params for form.submit() should cover most edge cases. [`#22`](https://github.com/form-data/form-data/pull/22) +- Updated Readme and version number. [`#20`](https://github.com/form-data/form-data/pull/20) +- Allow custom headers and pre-known length in parts [`#17`](https://github.com/form-data/form-data/pull/17) +- Bumped version number. [`#12`](https://github.com/form-data/form-data/pull/12) +- Fix for #10 [`#11`](https://github.com/form-data/form-data/pull/11) +- Bumped version number. [`#8`](https://github.com/form-data/form-data/pull/8) +- Added support for https destination, http-response and mikeal's request streams. [`#7`](https://github.com/form-data/form-data/pull/7) +- Updated git url. [`#6`](https://github.com/form-data/form-data/pull/6) +- Version bump. [`#5`](https://github.com/form-data/form-data/pull/5) +- Changes to support custom content-type and getLengthSync. [`#4`](https://github.com/form-data/form-data/pull/4) +- make .submit(url) use host from url, not 'localhost' [`#2`](https://github.com/form-data/form-data/pull/2) +- Make package.json JSON [`#1`](https://github.com/form-data/form-data/pull/1) + +### Fixed + +- Add MIT license [`#14`](https://github.com/form-data/form-data/issues/14) + +### Commits + +- Spring cleaning. [`850ba1b`](https://github.com/form-data/form-data/commit/850ba1b649b6856b0fa87bbcb04bc70ece0137a6) +- Added custom request params to form.submit(). Made tests more stable. [`de3502f`](https://github.com/form-data/form-data/commit/de3502f6c4a509f6ed12a7dd9dc2ce9c2e0a8d23) +- Basic form (no files) working [`6ffdc34`](https://github.com/form-data/form-data/commit/6ffdc343e8594cfc2efe1e27653ea39d8980a14e) +- Got initial test to pass [`9a59d08`](https://github.com/form-data/form-data/commit/9a59d08c024479fd3c9d99ba2f0893a47b3980f0) +- Implement initial getLength [`9060c91`](https://github.com/form-data/form-data/commit/9060c91b861a6573b73beddd11e866db422b5830) +- Make getLength work with file streams [`6f6b1e9`](https://github.com/form-data/form-data/commit/6f6b1e9b65951e6314167db33b446351702f5558) +- Implemented a simplistic submit() function [`41e9cc1`](https://github.com/form-data/form-data/commit/41e9cc124124721e53bc1d1459d45db1410c44e6) +- added test for custom headers and content-length in parts (felixge/node-form-data/17) [`b16d14e`](https://github.com/form-data/form-data/commit/b16d14e693670f5d52babec32cdedd1aa07c1aa4) +- Fixed code styling. [`5847424`](https://github.com/form-data/form-data/commit/5847424c666970fc2060acd619e8a78678888a82) +- #29 Added custom filename and content-type options to support identity-less streams. [`adf8b4a`](https://github.com/form-data/form-data/commit/adf8b4a41530795682cd3e35ffaf26b30288ccda) +- Initial Readme and package.json [`8c744e5`](https://github.com/form-data/form-data/commit/8c744e58be4014bdf432e11b718ed87f03e217af) +- allow append() to completely override header and boundary [`3fb2ad4`](https://github.com/form-data/form-data/commit/3fb2ad491f66e4b4ff16130be25b462820b8c972) +- Syntax highlighting [`ab3a6a5`](https://github.com/form-data/form-data/commit/ab3a6a5ed1ab77a2943ce3befcb2bb3cd9ff0330) +- Updated Readme.md [`de8f441`](https://github.com/form-data/form-data/commit/de8f44122ca754cbfedc0d2748e84add5ff0b669) +- Added examples to Readme file. [`c406ac9`](https://github.com/form-data/form-data/commit/c406ac921d299cbc130464ed19338a9ef97cb650) +- pass options.knownLength to set length at beginning, w/o waiting for async size calculation [`e2ac039`](https://github.com/form-data/form-data/commit/e2ac0397ff7c37c3dca74fa9925b55f832e4fa0b) +- Updated dependencies and added test command. [`09bd7cd`](https://github.com/form-data/form-data/commit/09bd7cd86f1ad7a58df1b135eb6eef0d290894b4) +- Bumped version. Updated readme. [`4581140`](https://github.com/form-data/form-data/commit/4581140f322758c6fc92019d342c7d7d6c94af5c) +- Test runner [`1707ebb`](https://github.com/form-data/form-data/commit/1707ebbd180856e6ed44e80c46b02557e2425762) +- Added .npmignore, bumped version. [`2e033e0`](https://github.com/form-data/form-data/commit/2e033e0e4be7c1457be090cd9b2996f19d8fb665) +- FormData.prototype.append takes and passes along options (for header) [`b519203`](https://github.com/form-data/form-data/commit/b51920387ed4da7b4e106fc07b9459f26b5ae2f0) +- Make package.json JSON [`bf1b58d`](https://github.com/form-data/form-data/commit/bf1b58df794b10fda86ed013eb9237b1e5032085) +- Add dependencies to package.json [`7413d0b`](https://github.com/form-data/form-data/commit/7413d0b4cf5546312d47ea426db8180619083974) +- Add convenient submit() interface [`55855e4`](https://github.com/form-data/form-data/commit/55855e4bea14585d4a3faf9e7318a56696adbc7d) +- Fix content type [`08b6ae3`](https://github.com/form-data/form-data/commit/08b6ae337b23ef1ba457ead72c9b133047df213c) +- Combatting travis rvm calls. [`409adfd`](https://github.com/form-data/form-data/commit/409adfd100a3cf4968a632c05ba58d92d262d144) +- Fixed Issue #2 [`b3a5d66`](https://github.com/form-data/form-data/commit/b3a5d661739dcd6921b444b81d5cb3c32fab655d) +- Fix for #10. [`bab70b9`](https://github.com/form-data/form-data/commit/bab70b9e803e17287632762073d227d6c59989e0) +- Trying workarounds for formidable - 0.6 "love". [`25782a3`](https://github.com/form-data/form-data/commit/25782a3f183d9c30668ec2bca6247ed83f10611c) +- change whitespace to conform with felixge's style guide [`9fa34f4`](https://github.com/form-data/form-data/commit/9fa34f433bece85ef73086a874c6f0164ab7f1f6) +- Add async to deps [`b7d1a6b`](https://github.com/form-data/form-data/commit/b7d1a6b10ee74be831de24ed76843e5a6935f155) +- typo [`7860a9c`](https://github.com/form-data/form-data/commit/7860a9c8a582f0745ce0e4a0549f4bffc29c0b50) +- Bumped version. [`fa36c1b`](https://github.com/form-data/form-data/commit/fa36c1b4229c34b85d7efd41908429b6d1da3bfc) +- Updated .gitignore [`de567bd`](https://github.com/form-data/form-data/commit/de567bde620e53b8e9b0ed3506e79491525ec558) +- Don't rely on resume() being called by pipe [`1deae47`](https://github.com/form-data/form-data/commit/1deae47e042bcd170bd5dbe2b4a4fa5356bb8aa2) +- One more wrong content type [`28f166d`](https://github.com/form-data/form-data/commit/28f166d443e2eb77f2559324014670674b97e46e) +- Another typo [`b959b6a`](https://github.com/form-data/form-data/commit/b959b6a2be061cac17f8d329b89cea109f0f32be) +- Typo [`698fa0a`](https://github.com/form-data/form-data/commit/698fa0aa5dbf4eeb77377415acc202a6fbe3f4a2) +- Being simply dumb. [`b614db8`](https://github.com/form-data/form-data/commit/b614db85702061149fbd98418605106975e72ade) +- Fixed typo in the filename. [`30af6be`](https://github.com/form-data/form-data/commit/30af6be13fb0c9e92b32e935317680b9d7599928) diff --git a/node_modules/form-data/License b/node_modules/form-data/License new file mode 100644 index 0000000..c7ff12a --- /dev/null +++ b/node_modules/form-data/License @@ -0,0 +1,19 @@ +Copyright (c) 2012 Felix Geisendörfer (felix@debuggable.com) and contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. diff --git a/node_modules/form-data/README.md b/node_modules/form-data/README.md new file mode 100644 index 0000000..f9d540a --- /dev/null +++ b/node_modules/form-data/README.md @@ -0,0 +1,350 @@ +# Form-Data [![NPM Module](https://img.shields.io/npm/v/form-data.svg)](https://www.npmjs.com/package/form-data) [![Join the chat at https://gitter.im/form-data/form-data](http://form-data.github.io/images/gitterbadge.svg)](https://gitter.im/form-data/form-data) + +A library to create readable ```"multipart/form-data"``` streams. Can be used to submit forms and file uploads to other web applications. + +The API of this library is inspired by the [XMLHttpRequest-2 FormData Interface][xhr2-fd]. + +[xhr2-fd]: http://dev.w3.org/2006/webapi/XMLHttpRequest-2/Overview.html#the-formdata-interface + +[![Linux Build](https://img.shields.io/travis/form-data/form-data/v2.5.5.svg?label=linux:4.x-12.x)](https://travis-ci.org/form-data/form-data) +[![MacOS Build](https://img.shields.io/travis/form-data/form-data/v2.5.5.svg?label=macos:4.x-12.x)](https://travis-ci.org/form-data/form-data) +[![Windows Build](https://img.shields.io/travis/form-data/form-data/v2.5.5.svg?label=windows:4.x-12.x)](https://travis-ci.org/form-data/form-data) + +[![Coverage Status](https://img.shields.io/coveralls/form-data/form-data/v2.5.5.svg?label=code+coverage)](https://coveralls.io/github/form-data/form-data?branch=master) +[![Dependency Status](https://img.shields.io/david/form-data/form-data.svg)](https://david-dm.org/form-data/form-data) + +## Install + +``` +npm install --save form-data +``` + +## Usage + +In this example we are constructing a form with 3 fields that contain a string, +a buffer and a file stream. + +``` javascript +var FormData = require('form-data'); +var fs = require('fs'); + +var form = new FormData(); +form.append('my_field', 'my value'); +form.append('my_buffer', new Buffer(10)); +form.append('my_file', fs.createReadStream('/foo/bar.jpg')); +``` + +Also you can use http-response stream: + +``` javascript +var FormData = require('form-data'); +var http = require('http'); + +var form = new FormData(); + +http.request('http://nodejs.org/images/logo.png', function(response) { + form.append('my_field', 'my value'); + form.append('my_buffer', new Buffer(10)); + form.append('my_logo', response); +}); +``` + +Or @mikeal's [request](https://github.com/request/request) stream: + +``` javascript +var FormData = require('form-data'); +var request = require('request'); + +var form = new FormData(); + +form.append('my_field', 'my value'); +form.append('my_buffer', new Buffer(10)); +form.append('my_logo', request('http://nodejs.org/images/logo.png')); +``` + +In order to submit this form to a web application, call ```submit(url, [callback])``` method: + +``` javascript +form.submit('http://example.org/', function(err, res) { + // res – response object (http.IncomingMessage) // + res.resume(); +}); + +``` + +For more advanced request manipulations ```submit()``` method returns ```http.ClientRequest``` object, or you can choose from one of the alternative submission methods. + +### Custom options + +You can provide custom options, such as `maxDataSize`: + +``` javascript +var FormData = require('form-data'); + +var form = new FormData({ maxDataSize: 20971520 }); +form.append('my_field', 'my value'); +form.append('my_buffer', /* something big */); +``` + +List of available options could be found in [combined-stream](https://github.com/felixge/node-combined-stream/blob/master/lib/combined_stream.js#L7-L15) + +### Alternative submission methods + +You can use node's http client interface: + +``` javascript +var http = require('http'); + +var request = http.request({ + method: 'post', + host: 'example.org', + path: '/upload', + headers: form.getHeaders() +}); + +form.pipe(request); + +request.on('response', function(res) { + console.log(res.statusCode); +}); +``` + +Or if you would prefer the `'Content-Length'` header to be set for you: + +``` javascript +form.submit('example.org/upload', function(err, res) { + console.log(res.statusCode); +}); +``` + +To use custom headers and pre-known length in parts: + +``` javascript +var CRLF = '\r\n'; +var form = new FormData(); + +var options = { + header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF, + knownLength: 1 +}; + +form.append('my_buffer', buffer, options); + +form.submit('http://example.com/', function(err, res) { + if (err) throw err; + console.log('Done'); +}); +``` + +Form-Data can recognize and fetch all the required information from common types of streams (```fs.readStream```, ```http.response``` and ```mikeal's request```), for some other types of streams you'd need to provide "file"-related information manually: + +``` javascript +someModule.stream(function(err, stdout, stderr) { + if (err) throw err; + + var form = new FormData(); + + form.append('file', stdout, { + filename: 'unicycle.jpg', // ... or: + filepath: 'photos/toys/unicycle.jpg', + contentType: 'image/jpeg', + knownLength: 19806 + }); + + form.submit('http://example.com/', function(err, res) { + if (err) throw err; + console.log('Done'); + }); +}); +``` + +The `filepath` property overrides `filename` and may contain a relative path. This is typically used when uploading [multiple files from a directory](https://wicg.github.io/entries-api/#dom-htmlinputelement-webkitdirectory). + +For edge cases, like POST request to URL with query string or to pass HTTP auth credentials, object can be passed to `form.submit()` as first parameter: + +``` javascript +form.submit({ + host: 'example.com', + path: '/probably.php?extra=params', + auth: 'username:password' +}, function(err, res) { + console.log(res.statusCode); +}); +``` + +In case you need to also send custom HTTP headers with the POST request, you can use the `headers` key in first parameter of `form.submit()`: + +``` javascript +form.submit({ + host: 'example.com', + path: '/surelynot.php', + headers: {'x-test-header': 'test-header-value'} +}, function(err, res) { + console.log(res.statusCode); +}); +``` + +### Methods + +- [_Void_ append( **String** _field_, **Mixed** _value_ [, **Mixed** _options_] )](https://github.com/form-data/form-data#void-append-string-field-mixed-value--mixed-options-). +- [_Array_ getHeaders( [**Array** _userHeaders_] )](https://github.com/form-data/form-data#array-getheaders-array-userheaders-) +- [_String_ getBoundary()](https://github.com/form-data/form-data#string-getboundary) +- [_Buffer_ getBuffer()](https://github.com/form-data/form-data#buffer-getbuffer) +- [_Integer_ getLengthSync()](https://github.com/form-data/form-data#integer-getlengthsync) +- [_Integer_ getLength( **function** _callback_ )](https://github.com/form-data/form-data#integer-getlength-function-callback-) +- [_Boolean_ hasKnownLength()](https://github.com/form-data/form-data#boolean-hasknownlength) +- [_Request_ submit( _params_, **function** _callback_ )](https://github.com/form-data/form-data#request-submit-params-function-callback-) +- [_String_ toString()](https://github.com/form-data/form-data#string-tostring) + +#### _Void_ append( **String** _field_, **Mixed** _value_ [, **Mixed** _options_] ) +Append data to the form. You can submit about any format (string, integer, boolean, buffer, etc.). However, Arrays are not supported and need to be turned into strings by the user. +```javascript +var form = new FormData(); +form.append( 'my_string', 'my value' ); +form.append( 'my_integer', 1 ); +form.append( 'my_boolean', true ); +form.append( 'my_buffer', new Buffer(10) ); +form.append( 'my_array_as_json', JSON.stringify( ['bird','cute'] ) ) +``` + +You may provide a string for options, or an object. +```javascript +// Set filename by providing a string for options +form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), 'bar.jpg' ); + +// provide an object. +form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), {filename: 'bar.jpg', contentType: 'image/jpeg', knownLength: 19806} ); +``` + +#### _Array_ getHeaders( [**Array** _userHeaders_] ) +This method ads the correct `content-type` header to the provided array of `userHeaders`. + +#### _String_ getBoundary() +Return the boundary of the formData. A boundary consists of 26 `-` followed by 24 numbers +for example: +```javascript +--------------------------515890814546601021194782 +``` +_Note: The boundary must be unique and may not appear in the data._ + +#### _Buffer_ getBuffer() +Return the full formdata request package, as a Buffer. You can insert this Buffer in e.g. Axios to send multipart data. +```javascript +var form = new FormData(); +form.append( 'my_buffer', Buffer.from([0x4a,0x42,0x20,0x52,0x6f,0x63,0x6b,0x73]) ); +form.append( 'my_file', fs.readFileSync('/foo/bar.jpg') ); + +axios.post( 'https://example.com/path/to/api', + form.getBuffer(), + form.getHeaders() + ) +``` +**Note:** Because the output is of type Buffer, you can only append types that are accepted by Buffer: *string, Buffer, ArrayBuffer, Array, or Array-like Object*. A ReadStream for example will result in an error. + +#### _Integer_ getLengthSync() +Same as `getLength` but synchronous. + +_Note: getLengthSync __doesn't__ calculate streams length._ + +#### _Integer_ getLength( **function** _callback_ ) +Returns the `Content-Length` async. The callback is used to handle errors and continue once the length has been calculated +```javascript +this.getLength(function(err, length) { + if (err) { + this._error(err); + return; + } + + // add content length + request.setHeader('Content-Length', length); + + ... +}.bind(this)); +``` + +#### _Boolean_ hasKnownLength() +Checks if the length of added values is known. + +#### _Request_ submit( _params_, **function** _callback_ ) +Submit the form to a web application. +```javascript +var form = new FormData(); +form.append( 'my_string', 'Hello World' ); + +form.submit( 'http://example.com/', function(err, res) { + // res – response object (http.IncomingMessage) // + res.resume(); +} ); +``` + +#### _String_ toString() +Returns the form data as a string. Don't use this if you are sending files or buffers, use `getBuffer()` instead. + +### Integration with other libraries + +#### Request + +Form submission using [request](https://github.com/request/request): + +```javascript +var formData = { + my_field: 'my_value', + my_file: fs.createReadStream(__dirname + '/unicycle.jpg'), +}; + +request.post({url:'http://service.com/upload', formData: formData}, function(err, httpResponse, body) { + if (err) { + return console.error('upload failed:', err); + } + console.log('Upload successful! Server responded with:', body); +}); +``` + +For more details see [request readme](https://github.com/request/request#multipartform-data-multipart-form-uploads). + +#### node-fetch + +You can also submit a form using [node-fetch](https://github.com/bitinn/node-fetch): + +```javascript +var form = new FormData(); + +form.append('a', 1); + +fetch('http://example.com', { method: 'POST', body: form }) + .then(function(res) { + return res.json(); + }).then(function(json) { + console.log(json); + }); +``` + +#### axios + +In Node.js you can post a file using [axios](https://github.com/axios/axios): +```javascript +const form = new FormData(); +const stream = fs.createReadStream(PATH_TO_FILE); + +form.append('image', stream); + +// In Node.js environment you need to set boundary in the header field 'Content-Type' by calling method `getHeaders` +const formHeaders = form.getHeaders(); + +axios.post('http://example.com', form, { + headers: { + ...formHeaders, + }, +}) +.then(response => response) +.catch(error => error) +``` + +## Notes + +- ```getLengthSync()``` method DOESN'T calculate length for streams, use ```knownLength``` options as workaround. +- Starting version `2.x` FormData has dropped support for `node@0.10.x`. + +## License + +Form-Data is released under the [MIT](License) license. diff --git a/node_modules/form-data/index.d.ts b/node_modules/form-data/index.d.ts new file mode 100644 index 0000000..255292d --- /dev/null +++ b/node_modules/form-data/index.d.ts @@ -0,0 +1,51 @@ +// Definitions by: Carlos Ballesteros Velasco +// Leon Yu +// BendingBender +// Maple Miao + +/// +import * as stream from 'stream'; +import * as http from 'http'; + +export = FormData; + +interface Options { + writable?: boolean; + readable?: boolean; + dataSize?: number; + maxDataSize?: number; + pauseStreams?: boolean; +} + +declare class FormData extends stream.Readable { + constructor(options?: Options); + append(key: string, value: any, options?: FormData.AppendOptions | string): void; + getHeaders(): FormData.Headers; + submit( + params: string | FormData.SubmitOptions, + callback?: (error: Error | null, response: http.IncomingMessage) => void + ): http.ClientRequest; + getBuffer(): Buffer; + getBoundary(): string; + getLength(callback: (err: Error | null, length: number) => void): void; + getLengthSync(): number; + hasKnownLength(): boolean; +} + +declare namespace FormData { + interface Headers { + [key: string]: any; + } + + interface AppendOptions { + header?: string | Headers; + knownLength?: number; + filename?: string; + filepath?: string; + contentType?: string; + } + + interface SubmitOptions extends http.RequestOptions { + protocol?: 'https:' | 'http:'; + } +} diff --git a/node_modules/form-data/lib/browser.js b/node_modules/form-data/lib/browser.js new file mode 100644 index 0000000..8950a91 --- /dev/null +++ b/node_modules/form-data/lib/browser.js @@ -0,0 +1,4 @@ +'use strict'; + +/* eslint-env browser */ +module.exports = typeof self === 'object' ? self.FormData : window.FormData; diff --git a/node_modules/form-data/lib/form_data.js b/node_modules/form-data/lib/form_data.js new file mode 100644 index 0000000..58486d1 --- /dev/null +++ b/node_modules/form-data/lib/form_data.js @@ -0,0 +1,509 @@ +'use strict'; + +var CombinedStream = require('combined-stream'); +var util = require('util'); +var path = require('path'); +var http = require('http'); +var https = require('https'); +var parseUrl = require('url').parse; +var fs = require('fs'); +var crypto = require('crypto'); +var mime = require('mime-types'); +var asynckit = require('asynckit'); +var hasOwn = require('hasown'); +var setToStringTag = require('es-set-tostringtag'); +var populate = require('./populate.js'); +var Buffer = require('safe-buffer').Buffer; + +/** + * Create readable "multipart/form-data" streams. + * Can be used to submit forms + * and file uploads to other web applications. + * + * @constructor + * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream + */ +function FormData(options) { + if (!(this instanceof FormData)) { + return new FormData(); + } + + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; + + CombinedStream.call(this); + + options = options || {}; + for (var option in options) { // eslint-disable-line no-restricted-syntax + this[option] = options[option]; + } +} + +// make it a Stream +util.inherits(FormData, CombinedStream); + +FormData.LINE_BREAK = '\r\n'; +FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; + +FormData.prototype.append = function (field, value, options) { + + options = options || {}; + + // allow filename as single option + if (typeof options === 'string') { + options = { filename: options }; + } + + var append = CombinedStream.prototype.append.bind(this); + + // all that streamy business can't handle numbers + if (typeof value === 'number' || value == null) { + value = String(value); + } + + // https://github.com/felixge/node-form-data/issues/38 + if (Array.isArray(value)) { + /* + * Please convert your array into string + * the way web server expects it + */ + this._error(new Error('Arrays are not supported.')); + return; + } + + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(); + + append(header); + append(value); + append(footer); + + // pass along options.knownLength + this._trackLength(header, value, options); +}; + +FormData.prototype._trackLength = function (header, value, options) { + var valueLength = 0; + + /* + * used w/ getLengthSync(), when length is known. + * e.g. for streaming directly from a remote server, + * w/ a known file a size, and not wanting to wait for + * incoming file to finish to get its size. + */ + if (options.knownLength != null) { + valueLength += Number(options.knownLength); + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === 'string') { + valueLength = Buffer.byteLength(value); + } + + this._valueLength += valueLength; + + // @check why add CRLF? does this account for custom/multiple CRLFs? + this._overheadLength += Buffer.byteLength(header) + FormData.LINE_BREAK.length; + + // empty or either doesn't have path or not an http response + if (!value || (!value.path && !(value.readable && hasOwn(value, 'httpVersion')))) { + return; + } + + // no need to bother with the length + if (!options.knownLength) { + this._valuesToMeasure.push(value); + } +}; + +FormData.prototype._lengthRetriever = function (value, callback) { + if (hasOwn(value, 'fd')) { + + /* + * take read range into a account + * `end` = Infinity –> read file till the end + * + * TODO: Looks like there is bug in Node fs.createReadStream + * it doesn't respect `end` options without `start` options + * Fix it when node fixes it. + * https://github.com/joyent/node/issues/7819 + */ + if (value.end != null && value.end !== Infinity && value.start != null) { + + /* + * when end specified + * no need to calculate range + * inclusive, starts with 0 + */ + callback(null, value.end + 1 - (value.start ? value.start : 0)); + + // not that fast snoopy + } else { + // still need to fetch file size from fs + fs.stat(value.path, function (err, stat) { + + var fileSize; + + if (err) { + callback(err); + return; + } + + // update final size based on the range options + fileSize = stat.size - (value.start ? value.start : 0); + callback(null, fileSize); + }); + } + + // or http response + } else if (hasOwn(value, 'httpVersion')) { + callback(null, Number(value.headers['content-length'])); + + // or request stream http://github.com/mikeal/request + } else if (hasOwn(value, 'httpModule')) { + // wait till response come back + value.on('response', function (response) { + value.pause(); + callback(null, Number(response.headers['content-length'])); + }); + value.resume(); + + // something else + } else { + callback('Unknown stream'); + } +}; + +FormData.prototype._multiPartHeader = function (field, value, options) { + /* + * custom header specified (as string)? + * it becomes responsible for boundary + * (e.g. to handle extra CRLFs on .NET servers) + */ + if (typeof options.header === 'string') { + return options.header; + } + + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); + + var contents = ''; + var headers = { + // add custom disposition as third element or keep it two elements if not + 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), + // if no content type. allow it to be empty array + 'Content-Type': [].concat(contentType || []), + }; + + // allow custom headers. + if (typeof options.header === 'object') { + populate(headers, options.header); + } + + var header; + for (var prop in headers) { // eslint-disable-line no-restricted-syntax + if (hasOwn(headers, prop)) { + header = headers[prop]; + + // skip nullish headers. + if (header == null) { + continue; // eslint-disable-line no-continue, no-restricted-syntax + } + + // convert all headers to arrays. + if (!Array.isArray(header)) { + header = [header]; + } + + // add non-empty headers. + if (header.length) { + contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; + } + } + } + + return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; +}; + +FormData.prototype._getContentDisposition = function (value, options) { + + var filename, + contentDisposition; + if (typeof options.filepath === 'string') { + // custom filepath for relative paths + filename = path.normalize(options.filepath).replace(/\\/g, '/'); + } else if (options.filename || (value && (value.name || value.path))) { + /* + * custom filename take precedence + * formidable and the browser add a name property + * fs- and request- streams have path property + */ + filename = path.basename(options.filename || (value && (value.name || value.path))); + } else if (value && value.readable && hasOwn(value, 'httpVersion')) { + // or try http response + filename = path.basename(value.client._httpMessage.path || ''); + } + + if (filename) { + contentDisposition = 'filename="' + filename + '"'; + } + + return contentDisposition; +}; + +FormData.prototype._getContentType = function (value, options) { + + // use custom content-type above all + var contentType = options.contentType; + + // or try `name` from formidable, browser + if (!contentType && value && value.name) { + contentType = mime.lookup(value.name); + } + + // or try `path` from fs-, request- streams + if (!contentType && value && value.path) { + contentType = mime.lookup(value.path); + } + + // or if it's http-reponse + if (!contentType && value && value.readable && hasOwn(value, 'httpVersion')) { + contentType = value.headers['content-type']; + } + + // or guess it from the filepath or filename + if (!contentType && (options.filepath || options.filename)) { + contentType = mime.lookup(options.filepath || options.filename); + } + + // fallback to the default content type if `value` is not simple value + if (!contentType && value && typeof value === 'object') { + contentType = FormData.DEFAULT_CONTENT_TYPE; + } + + return contentType; +}; + +FormData.prototype._multiPartFooter = function () { + return function (next) { + var footer = FormData.LINE_BREAK; + + var lastPart = this._streams.length === 0; + if (lastPart) { + footer += this._lastBoundary(); + } + + next(footer); + }.bind(this); +}; + +FormData.prototype._lastBoundary = function () { + return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; +}; + +FormData.prototype.getHeaders = function (userHeaders) { + var header; + var formHeaders = { + 'content-type': 'multipart/form-data; boundary=' + this.getBoundary(), + }; + + for (header in userHeaders) { // eslint-disable-line no-restricted-syntax + if (hasOwn(userHeaders, header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; + } + } + + return formHeaders; +}; + +FormData.prototype.setBoundary = function (boundary) { + if (typeof boundary !== 'string') { + throw new TypeError('FormData boundary must be a string'); + } + this._boundary = boundary; +}; + +FormData.prototype.getBoundary = function () { + if (!this._boundary) { + this._generateBoundary(); + } + + return this._boundary; +}; + +FormData.prototype.getBuffer = function () { + var dataBuffer = Buffer.alloc(0); + var boundary = this.getBoundary(); + + // Create the form content. Add Line breaks to the end of data. + for (var i = 0, len = this._streams.length; i < len; i++) { + if (typeof this._streams[i] !== 'function') { + + // Add content to the buffer. + if (Buffer.isBuffer(this._streams[i])) { + dataBuffer = Buffer.concat([dataBuffer, this._streams[i]]); + } else { + dataBuffer = Buffer.concat([dataBuffer, Buffer.from(this._streams[i])]); + } + + // Add break after content. + if (typeof this._streams[i] !== 'string' || this._streams[i].substring(2, boundary.length + 2) !== boundary) { + dataBuffer = Buffer.concat([dataBuffer, Buffer.from(FormData.LINE_BREAK)]); + } + } + } + + // Add the footer and return the Buffer object. + return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]); +}; + +FormData.prototype._generateBoundary = function () { + // This generates a 50 character boundary similar to those used by Firefox. + + // They are optimized for boyer-moore parsing. + this._boundary = '--------------------------' + crypto.randomBytes(12).toString('hex'); +}; + +/* + * Note: getLengthSync DOESN'T calculate streams length + * As workaround one can calculate file size manually + * and add it as knownLength option + */ +FormData.prototype.getLengthSync = function () { + var knownLength = this._overheadLength + this._valueLength; + + /* + * Don't get confused, there are 3 "internal" streams for each keyval pair + * so it basically checks if there is any value added to the form + */ + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } + + // https://github.com/form-data/form-data/issues/40 + if (!this.hasKnownLength()) { + /* + * Some async length retrievers are present + * therefore synchronous length calculation is false. + * Please use getLength(callback) to get proper length + */ + this._error(new Error('Cannot calculate proper length in synchronous way.')); + } + + return knownLength; +}; + +/* + * Public API to check if length of added values is known + * https://github.com/form-data/form-data/issues/196 + * https://github.com/form-data/form-data/issues/262 + */ +FormData.prototype.hasKnownLength = function () { + var hasKnownLength = true; + + if (this._valuesToMeasure.length) { + hasKnownLength = false; + } + + return hasKnownLength; +}; + +FormData.prototype.getLength = function (cb) { + var knownLength = this._overheadLength + this._valueLength; + + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } + + if (!this._valuesToMeasure.length) { + process.nextTick(cb.bind(this, null, knownLength)); + return; + } + + asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function (err, values) { + if (err) { + cb(err); + return; + } + + values.forEach(function (length) { + knownLength += length; + }); + + cb(null, knownLength); + }); +}; + +FormData.prototype.submit = function (params, cb) { + var request; + var options; + var defaults = { method: 'post' }; + + /* + * parse provided url if it's string + * or treat it as options object + */ + if (typeof params === 'string') { + + params = parseUrl(params); + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname, + protocol: params.protocol, + }, defaults); + + // use custom params + } else { + + options = populate(params, defaults); + // if no port provided use default one + if (!options.port) { + options.port = options.protocol === 'https:' ? 443 : 80; + } + } + + // put that good code in getHeaders to some use + options.headers = this.getHeaders(params.headers); + + // https if specified, fallback to http in any other case + if (options.protocol === 'https:') { + request = https.request(options); + } else { + request = http.request(options); + } + + // get content length and fire away + this.getLength(function (err, length) { + if (err) { + this._error(err); + return; + } + + // add content length + request.setHeader('Content-Length', length); + + this.pipe(request); + if (cb) { + request.on('error', cb); + request.on('response', cb.bind(this, null)); + } + }.bind(this)); + + return request; +}; + +FormData.prototype._error = function (err) { + if (!this.error) { + this.error = err; + this.pause(); + this.emit('error', err); + } +}; + +FormData.prototype.toString = function () { + return '[object FormData]'; +}; +setToStringTag(FormData, 'FormData'); + +module.exports = FormData; diff --git a/node_modules/form-data/lib/populate.js b/node_modules/form-data/lib/populate.js new file mode 100644 index 0000000..4b8cc2f --- /dev/null +++ b/node_modules/form-data/lib/populate.js @@ -0,0 +1,10 @@ +'use strict'; + +// populates missing values +module.exports = function (dst, src) { + Object.keys(src).forEach(function (prop) { + dst[prop] = dst[prop] || src[prop]; + }); + + return dst; +}; diff --git a/node_modules/form-data/package.json b/node_modules/form-data/package.json new file mode 100644 index 0000000..c2a7fc1 --- /dev/null +++ b/node_modules/form-data/package.json @@ -0,0 +1,83 @@ +{ + "author": "Felix Geisendörfer (http://debuggable.com/)", + "name": "form-data", + "description": "A library to create readable \"multipart/form-data\" streams. Can be used to submit forms and file uploads to other web applications.", + "version": "2.5.5", + "repository": { + "type": "git", + "url": "git://github.com/form-data/form-data.git" + }, + "main": "./lib/form_data", + "browser": "./lib/browser", + "typings": "./index.d.ts", + "scripts": { + "pretest": "npm run lint", + "pretests-only": "rimraf coverage test/tmp", + "tests-only": "istanbul cover test/run.js", + "posttests-only": "istanbul report lcov text", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "lint": "eslint --ext=js,mjs .", + "report": "istanbul report lcov text", + "ci-test": "npm run tests-only && npm run browser && npm run report", + "predebug": "rimraf coverage test/tmp", + "debug": "verbose=1 ./test/run.js", + "browser": "browserify -t browserify-istanbul test/run-browser.js | obake --coverage", + "check": "istanbul check-coverage coverage/coverage*.json", + "files": "pkgfiles --sort=name", + "get-version": "node -e \"console.log(require('./package.json').version)\"", + "update-readme": "sed -i.bak 's/\\/master\\.svg/\\/v'$(npm --silent run get-version)'.svg/g' README.md", + "postupdate-readme": "mv README.md.bak READ.ME.md.bak", + "restore-readme": "mv READ.ME.md.bak README.md", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepack": "npm run update-readme", + "postpack": "npm run restore-readme", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "engines": { + "node": ">= 0.12" + }, + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", + "mime-types": "^2.1.35", + "safe-buffer": "^5.2.1" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.2.0", + "auto-changelog": "^2.5.0", + "browserify": "^13.3.0", + "browserify-istanbul": "^2.0.0", + "coveralls": "^3.1.1", + "cross-spawn": "^4.0.2", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "fake": "^0.2.2", + "far": "^0.0.7", + "formidable": "^1.2.6", + "in-publish": "^2.0.1", + "istanbul": "^0.4.5", + "js-randomness-predictor": "^1.5.5", + "obake": "^0.1.2", + "phantomjs-prebuilt": "^2.1.16", + "pkgfiles": "^2.3.2", + "pre-commit": "^1.2.2", + "puppeteer": "^1.20.0", + "request": "~2.87.0", + "rimraf": "^2.7.1", + "semver": "^6.3.1", + "tape": "^5.9.0" + }, + "license": "MIT", + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/node_modules/function-bind/.eslintrc b/node_modules/function-bind/.eslintrc new file mode 100644 index 0000000..71a054f --- /dev/null +++ b/node_modules/function-bind/.eslintrc @@ -0,0 +1,21 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "indent": [2, 4], + "no-new-func": [1], + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "max-lines-per-function": 0, + "strict": [0] + }, + }, + ], +} diff --git a/node_modules/function-bind/.github/FUNDING.yml b/node_modules/function-bind/.github/FUNDING.yml new file mode 100644 index 0000000..7448219 --- /dev/null +++ b/node_modules/function-bind/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/function-bind +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/function-bind/.github/SECURITY.md b/node_modules/function-bind/.github/SECURITY.md new file mode 100644 index 0000000..82e4285 --- /dev/null +++ b/node_modules/function-bind/.github/SECURITY.md @@ -0,0 +1,3 @@ +# Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. diff --git a/node_modules/function-bind/.nycrc b/node_modules/function-bind/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/function-bind/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/function-bind/CHANGELOG.md b/node_modules/function-bind/CHANGELOG.md new file mode 100644 index 0000000..f9e6cc0 --- /dev/null +++ b/node_modules/function-bind/CHANGELOG.md @@ -0,0 +1,136 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.2](https://github.com/ljharb/function-bind/compare/v1.1.1...v1.1.2) - 2023-10-12 + +### Merged + +- Point to the correct file [`#16`](https://github.com/ljharb/function-bind/pull/16) + +### Commits + +- [Tests] migrate tests to Github Actions [`4f8b57c`](https://github.com/ljharb/function-bind/commit/4f8b57c02f2011fe9ae353d5e74e8745f0988af8) +- [Tests] remove `jscs` [`90eb2ed`](https://github.com/ljharb/function-bind/commit/90eb2edbeefd5b76cd6c3a482ea3454db169b31f) +- [meta] update `.gitignore` [`53fcdc3`](https://github.com/ljharb/function-bind/commit/53fcdc371cd66634d6e9b71c836a50f437e89fed) +- [Tests] up to `node` `v11.10`, `v10.15`, `v9.11`, `v8.15`, `v6.16`, `v4.9`; use `nvm install-latest-npm`; run audit script in tests [`1fe8f6e`](https://github.com/ljharb/function-bind/commit/1fe8f6e9aed0dfa8d8b3cdbd00c7f5ea0cd2b36e) +- [meta] add `auto-changelog` [`1921fcb`](https://github.com/ljharb/function-bind/commit/1921fcb5b416b63ffc4acad051b6aad5722f777d) +- [Robustness] remove runtime dependency on all builtins except `.apply` [`f743e61`](https://github.com/ljharb/function-bind/commit/f743e61aa6bb2360358c04d4884c9db853d118b7) +- Docs: enable badges; update wording [`503cb12`](https://github.com/ljharb/function-bind/commit/503cb12d998b5f91822776c73332c7adcd6355dd) +- [readme] update badges [`290c5db`](https://github.com/ljharb/function-bind/commit/290c5dbbbda7264efaeb886552a374b869a4bb48) +- [Tests] switch to nyc for coverage [`ea360ba`](https://github.com/ljharb/function-bind/commit/ea360ba907fc2601ed18d01a3827fa2d3533cdf8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`cae5e9e`](https://github.com/ljharb/function-bind/commit/cae5e9e07a5578dc6df26c03ee22851ce05b943c) +- [meta] add `funding` field; create FUNDING.yml [`c9f4274`](https://github.com/ljharb/function-bind/commit/c9f4274aa80ea3aae9657a3938fdba41a3b04ca6) +- [Tests] fix eslint errors from #15 [`f69aaa2`](https://github.com/ljharb/function-bind/commit/f69aaa2beb2fdab4415bfb885760a699d0b9c964) +- [actions] fix permissions [`99a0cd9`](https://github.com/ljharb/function-bind/commit/99a0cd9f3b5bac223a0d572f081834cd73314be7) +- [meta] use `npmignore` to autogenerate an npmignore file [`f03b524`](https://github.com/ljharb/function-bind/commit/f03b524ca91f75a109a5d062f029122c86ecd1ae) +- [Dev Deps] update `@ljharb/eslint‑config`, `eslint`, `tape` [`7af9300`](https://github.com/ljharb/function-bind/commit/7af930023ae2ce7645489532821e4fbbcd7a2280) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape` [`64a9127`](https://github.com/ljharb/function-bind/commit/64a9127ab0bd331b93d6572eaf6e9971967fc08c) +- [Tests] use `aud` instead of `npm audit` [`e75069c`](https://github.com/ljharb/function-bind/commit/e75069c50010a8fcce2a9ce2324934c35fdb4386) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`d03555c`](https://github.com/ljharb/function-bind/commit/d03555ca59dea3b71ce710045e4303b9e2619e28) +- [meta] add `safe-publish-latest` [`9c8f809`](https://github.com/ljharb/function-bind/commit/9c8f8092aed027d7e80c94f517aa892385b64f09) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`baf6893`](https://github.com/ljharb/function-bind/commit/baf6893e27f5b59abe88bc1995e6f6ed1e527397) +- [meta] create SECURITY.md [`4db1779`](https://github.com/ljharb/function-bind/commit/4db17799f1f28ae294cb95e0081ca2b591c3911b) +- [Tests] add `npm run audit` [`c8b38ec`](https://github.com/ljharb/function-bind/commit/c8b38ec40ed3f85dabdee40ed4148f1748375bc2) +- Revert "Point to the correct file" [`05cdf0f`](https://github.com/ljharb/function-bind/commit/05cdf0fa205c6a3c5ba40bbedd1dfa9874f915c9) + +## [v1.1.1](https://github.com/ljharb/function-bind/compare/v1.1.0...v1.1.1) - 2017-08-28 + +### Commits + +- [Tests] up to `node` `v8`; newer npm breaks on older node; fix scripts [`817f7d2`](https://github.com/ljharb/function-bind/commit/817f7d28470fdbff8ef608d4d565dd4d1430bc5e) +- [Dev Deps] update `eslint`, `jscs`, `tape`, `@ljharb/eslint-config` [`854288b`](https://github.com/ljharb/function-bind/commit/854288b1b6f5c555f89aceb9eff1152510262084) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`83e639f`](https://github.com/ljharb/function-bind/commit/83e639ff74e6cd6921285bccec22c1bcf72311bd) +- Only apps should have lockfiles [`5ed97f5`](https://github.com/ljharb/function-bind/commit/5ed97f51235c17774e0832e122abda0f3229c908) +- Use a SPDX-compliant “license” field. [`5feefea`](https://github.com/ljharb/function-bind/commit/5feefea0dc0193993e83e5df01ded424403a5381) + +## [v1.1.0](https://github.com/ljharb/function-bind/compare/v1.0.2...v1.1.0) - 2016-02-14 + +### Commits + +- Update `eslint`, `tape`; use my personal shared `eslint` config [`9c9062a`](https://github.com/ljharb/function-bind/commit/9c9062abbe9dd70b59ea2c3a3c3a81f29b457097) +- Add `npm run eslint` [`dd96c56`](https://github.com/ljharb/function-bind/commit/dd96c56720034a3c1ffee10b8a59a6f7c53e24ad) +- [New] return the native `bind` when available. [`82186e0`](https://github.com/ljharb/function-bind/commit/82186e03d73e580f95ff167e03f3582bed90ed72) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`a3dd767`](https://github.com/ljharb/function-bind/commit/a3dd76720c795cb7f4586b0544efabf8aa107b8b) +- Update `eslint` [`3dae2f7`](https://github.com/ljharb/function-bind/commit/3dae2f7423de30a2d20313ddb1edc19660142fe9) +- Update `tape`, `covert`, `jscs` [`a181eee`](https://github.com/ljharb/function-bind/commit/a181eee0cfa24eb229c6e843a971f36e060a2f6a) +- [Tests] up to `node` `v5.6`, `v4.3` [`964929a`](https://github.com/ljharb/function-bind/commit/964929a6a4ddb36fb128de2bcc20af5e4f22e1ed) +- Test up to `io.js` `v2.1` [`2be7310`](https://github.com/ljharb/function-bind/commit/2be7310f2f74886a7124ca925be411117d41d5ea) +- Update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`45f3d68`](https://github.com/ljharb/function-bind/commit/45f3d6865c6ca93726abcef54febe009087af101) +- [Dev Deps] update `tape`, `jscs` [`6e1340d`](https://github.com/ljharb/function-bind/commit/6e1340d94642deaecad3e717825db641af4f8b1f) +- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`d9bad2b`](https://github.com/ljharb/function-bind/commit/d9bad2b778b1b3a6dd2876087b88b3acf319f8cc) +- Update `eslint` [`935590c`](https://github.com/ljharb/function-bind/commit/935590caa024ab356102e4858e8fc315b2ccc446) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` [`8c9a1ef`](https://github.com/ljharb/function-bind/commit/8c9a1efd848e5167887aa8501857a0940a480c57) +- Test on `io.js` `v2.2` [`9a3a38c`](https://github.com/ljharb/function-bind/commit/9a3a38c92013aed6e108666e7bd40969b84ac86e) +- Run `travis-ci` tests on `iojs` and `node` v0.12; speed up builds; allow 0.8 failures. [`69afc26`](https://github.com/ljharb/function-bind/commit/69afc2617405b147dd2a8d8ae73ca9e9283f18b4) +- [Dev Deps] Update `tape`, `eslint` [`36c1be0`](https://github.com/ljharb/function-bind/commit/36c1be0ab12b45fe5df6b0fdb01a5d5137fd0115) +- Update `tape`, `jscs` [`98d8303`](https://github.com/ljharb/function-bind/commit/98d8303cd5ca1c6b8f985469f86b0d44d7d45f6e) +- Update `jscs` [`9633a4e`](https://github.com/ljharb/function-bind/commit/9633a4e9fbf82051c240855166e468ba8ba0846f) +- Update `tape`, `jscs` [`c80ef0f`](https://github.com/ljharb/function-bind/commit/c80ef0f46efc9791e76fa50de4414092ac147831) +- Test up to `io.js` `v3.0` [`7e2c853`](https://github.com/ljharb/function-bind/commit/7e2c8537d52ab9cf5a655755561d8917684c0df4) +- Test on `io.js` `v2.4` [`5a199a2`](https://github.com/ljharb/function-bind/commit/5a199a27ba46795ba5eaf0845d07d4b8232895c9) +- Test on `io.js` `v2.3` [`a511b88`](https://github.com/ljharb/function-bind/commit/a511b8896de0bddf3b56862daa416c701f4d0453) +- Fixing a typo from 822b4e1938db02dc9584aa434fd3a45cb20caf43 [`732d6b6`](https://github.com/ljharb/function-bind/commit/732d6b63a9b33b45230e630dbcac7a10855d3266) +- Update `jscs` [`da52a48`](https://github.com/ljharb/function-bind/commit/da52a4886c06d6490f46ae30b15e4163ba08905d) +- Lock covert to v1.0.0. [`d6150fd`](https://github.com/ljharb/function-bind/commit/d6150fda1e6f486718ebdeff823333d9e48e7430) + +## [v1.0.2](https://github.com/ljharb/function-bind/compare/v1.0.1...v1.0.2) - 2014-10-04 + +## [v1.0.1](https://github.com/ljharb/function-bind/compare/v1.0.0...v1.0.1) - 2014-10-03 + +### Merged + +- make CI build faster [`#3`](https://github.com/ljharb/function-bind/pull/3) + +### Commits + +- Using my standard jscs.json [`d8ee94c`](https://github.com/ljharb/function-bind/commit/d8ee94c993eff0a84cf5744fe6a29627f5cffa1a) +- Adding `npm run lint` [`7571ab7`](https://github.com/ljharb/function-bind/commit/7571ab7dfdbd99b25a1dbb2d232622bd6f4f9c10) +- Using consistent indentation [`e91a1b1`](https://github.com/ljharb/function-bind/commit/e91a1b13a61e99ec1e530e299b55508f74218a95) +- Updating jscs [`7e17892`](https://github.com/ljharb/function-bind/commit/7e1789284bc629bc9c1547a61c9b227bbd8c7a65) +- Using consistent quotes [`c50b57f`](https://github.com/ljharb/function-bind/commit/c50b57fcd1c5ec38320979c837006069ebe02b77) +- Adding keywords [`cb94631`](https://github.com/ljharb/function-bind/commit/cb946314eed35f21186a25fb42fc118772f9ee00) +- Directly export a function expression instead of using a declaration, and relying on hoisting. [`5a33c5f`](https://github.com/ljharb/function-bind/commit/5a33c5f45642de180e0d207110bf7d1843ceb87c) +- Naming npm URL and badge in README; use SVG [`2aef8fc`](https://github.com/ljharb/function-bind/commit/2aef8fcb79d54e63a58ae557c4e60949e05d5e16) +- Naming deps URLs in README [`04228d7`](https://github.com/ljharb/function-bind/commit/04228d766670ee45ca24e98345c1f6a7621065b5) +- Naming travis-ci URLs in README; using SVG [`62c810c`](https://github.com/ljharb/function-bind/commit/62c810c2f54ced956cd4d4ab7b793055addfe36e) +- Make sure functions are invoked correctly (also passing coverage tests) [`2b289b4`](https://github.com/ljharb/function-bind/commit/2b289b4dfbf037ffcfa4dc95eb540f6165e9e43a) +- Removing the strict mode pragmas; they make tests fail. [`1aa701d`](https://github.com/ljharb/function-bind/commit/1aa701d199ddc3782476e8f7eef82679be97b845) +- Adding myself as a contributor [`85fd57b`](https://github.com/ljharb/function-bind/commit/85fd57b0860e5a7af42de9a287f3f265fc6d72fc) +- Adding strict mode pragmas [`915b08e`](https://github.com/ljharb/function-bind/commit/915b08e084c86a722eafe7245e21db74aa21ca4c) +- Adding devDeps URLs to README [`4ccc731`](https://github.com/ljharb/function-bind/commit/4ccc73112c1769859e4ca3076caf4086b3cba2cd) +- Fixing the description. [`a7a472c`](https://github.com/ljharb/function-bind/commit/a7a472cf649af515c635cf560fc478fbe48999c8) +- Using a function expression instead of a function declaration. [`b5d3e4e`](https://github.com/ljharb/function-bind/commit/b5d3e4ea6aaffc63888953eeb1fbc7ff45f1fa14) +- Updating tape [`f086be6`](https://github.com/ljharb/function-bind/commit/f086be6029fb56dde61a258c1340600fa174d1e0) +- Updating jscs [`5f9bdb3`](https://github.com/ljharb/function-bind/commit/5f9bdb375ab13ba48f30852aab94029520c54d71) +- Updating jscs [`9b409ba`](https://github.com/ljharb/function-bind/commit/9b409ba6118e23395a4e5d83ef39152aab9d3bfc) +- Run coverage as part of tests. [`8e1b6d4`](https://github.com/ljharb/function-bind/commit/8e1b6d459f047d1bd4fee814e01247c984c80bd0) +- Run linter as part of tests [`c1ca83f`](https://github.com/ljharb/function-bind/commit/c1ca83f832df94587d09e621beba682fabfaa987) +- Updating covert [`701e837`](https://github.com/ljharb/function-bind/commit/701e83774b57b4d3ef631e1948143f43a72f4bb9) + +## [v1.0.0](https://github.com/ljharb/function-bind/compare/v0.2.0...v1.0.0) - 2014-08-09 + +### Commits + +- Make sure old and unstable nodes don't fail Travis [`27adca3`](https://github.com/ljharb/function-bind/commit/27adca34a4ab6ad67b6dfde43942a1b103ce4d75) +- Fixing an issue when the bound function is called as a constructor in ES3. [`e20122d`](https://github.com/ljharb/function-bind/commit/e20122d267d92ce553859b280cbbea5d27c07731) +- Adding `npm run coverage` [`a2e29c4`](https://github.com/ljharb/function-bind/commit/a2e29c4ecaef9e2f6cd1603e868c139073375502) +- Updating tape [`b741168`](https://github.com/ljharb/function-bind/commit/b741168b12b235b1717ff696087645526b69213c) +- Upgrading tape [`63631a0`](https://github.com/ljharb/function-bind/commit/63631a04c7fbe97cc2fa61829cc27246d6986f74) +- Updating tape [`363cb46`](https://github.com/ljharb/function-bind/commit/363cb46dafb23cb3e347729a22f9448051d78464) + +## v0.2.0 - 2014-03-23 + +### Commits + +- Updating test coverage to match es5-shim. [`aa94d44`](https://github.com/ljharb/function-bind/commit/aa94d44b8f9d7f69f10e060db7709aa7a694e5d4) +- initial [`942ee07`](https://github.com/ljharb/function-bind/commit/942ee07e94e542d91798137bc4b80b926137e066) +- Setting the bound function's length properly. [`079f46a`](https://github.com/ljharb/function-bind/commit/079f46a2d3515b7c0b308c2c13fceb641f97ca25) +- Ensuring that some older browsers will throw when given a regex. [`36ac55b`](https://github.com/ljharb/function-bind/commit/36ac55b87f460d4330253c92870aa26fbfe8227f) +- Removing npm scripts that don't have dependencies [`9d2be60`](https://github.com/ljharb/function-bind/commit/9d2be600002cb8bc8606f8f3585ad3e05868c750) +- Updating tape [`297a4ac`](https://github.com/ljharb/function-bind/commit/297a4acc5464db381940aafb194d1c88f4e678f3) +- Skipping length tests for now. [`d9891ea`](https://github.com/ljharb/function-bind/commit/d9891ea4d2aaffa69f408339cdd61ff740f70565) +- don't take my tea [`dccd930`](https://github.com/ljharb/function-bind/commit/dccd930bfd60ea10cb178d28c97550c3bc8c1e07) diff --git a/node_modules/function-bind/LICENSE b/node_modules/function-bind/LICENSE new file mode 100644 index 0000000..62d6d23 --- /dev/null +++ b/node_modules/function-bind/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2013 Raynos. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/node_modules/function-bind/README.md b/node_modules/function-bind/README.md new file mode 100644 index 0000000..814c20b --- /dev/null +++ b/node_modules/function-bind/README.md @@ -0,0 +1,46 @@ +# function-bind [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] + +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Implementation of function.prototype.bind + +Old versions of phantomjs, Internet Explorer < 9, and node < 0.6 don't support `Function.prototype.bind`. + +## Example + +```js +Function.prototype.bind = require("function-bind") +``` + +## Installation + +`npm install function-bind` + +## Contributors + + - Raynos + +## MIT Licenced + +[package-url]: https://npmjs.org/package/function-bind +[npm-version-svg]: https://versionbadg.es/Raynos/function-bind.svg +[deps-svg]: https://david-dm.org/Raynos/function-bind.svg +[deps-url]: https://david-dm.org/Raynos/function-bind +[dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg +[dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/function-bind.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/function-bind.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/function-bind.svg +[downloads-url]: https://npm-stat.com/charts.html?package=function-bind +[codecov-image]: https://codecov.io/gh/Raynos/function-bind/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/Raynos/function-bind/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/Raynos/function-bind +[actions-url]: https://github.com/Raynos/function-bind/actions diff --git a/node_modules/function-bind/implementation.js b/node_modules/function-bind/implementation.js new file mode 100644 index 0000000..fd4384c --- /dev/null +++ b/node_modules/function-bind/implementation.js @@ -0,0 +1,84 @@ +'use strict'; + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var toStr = Object.prototype.toString; +var max = Math.max; +var funcType = '[object Function]'; + +var concatty = function concatty(a, b) { + var arr = []; + + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + + return arr; +}; + +var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; +}; + +var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; +}; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + + }; + + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = '$' + i; + } + + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; diff --git a/node_modules/function-bind/index.js b/node_modules/function-bind/index.js new file mode 100644 index 0000000..3bb6b96 --- /dev/null +++ b/node_modules/function-bind/index.js @@ -0,0 +1,5 @@ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = Function.prototype.bind || implementation; diff --git a/node_modules/function-bind/package.json b/node_modules/function-bind/package.json new file mode 100644 index 0000000..6185963 --- /dev/null +++ b/node_modules/function-bind/package.json @@ -0,0 +1,87 @@ +{ + "name": "function-bind", + "version": "1.1.2", + "description": "Implementation of Function.prototype.bind", + "keywords": [ + "function", + "bind", + "shim", + "es5" + ], + "author": "Raynos ", + "repository": { + "type": "git", + "url": "https://github.com/Raynos/function-bind.git" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "main": "index", + "homepage": "https://github.com/Raynos/function-bind", + "contributors": [ + { + "name": "Raynos" + }, + { + "name": "Jordan Harband", + "url": "https://github.com/ljharb" + } + ], + "bugs": { + "url": "https://github.com/Raynos/function-bind/issues", + "email": "raynos2@gmail.com" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.3", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.1" + }, + "license": "MIT", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepack": "npmignore --auto --commentLines=autogenerated", + "pretest": "npm run lint", + "test": "npm run tests-only", + "posttest": "aud --production", + "tests-only": "nyc tape 'test/**/*.js'", + "lint": "eslint --ext=js,mjs .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "ie/8..latest", + "firefox/16..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/function-bind/test/.eslintrc b/node_modules/function-bind/test/.eslintrc new file mode 100644 index 0000000..8a56d5b --- /dev/null +++ b/node_modules/function-bind/test/.eslintrc @@ -0,0 +1,9 @@ +{ + "rules": { + "array-bracket-newline": 0, + "array-element-newline": 0, + "max-statements-per-line": [2, { "max": 2 }], + "no-invalid-this": 0, + "no-magic-numbers": 0, + } +} diff --git a/node_modules/function-bind/test/index.js b/node_modules/function-bind/test/index.js new file mode 100644 index 0000000..2edecce --- /dev/null +++ b/node_modules/function-bind/test/index.js @@ -0,0 +1,252 @@ +// jscs:disable requireUseStrict + +var test = require('tape'); + +var functionBind = require('../implementation'); +var getCurrentContext = function () { return this; }; + +test('functionBind is a function', function (t) { + t.equal(typeof functionBind, 'function'); + t.end(); +}); + +test('non-functions', function (t) { + var nonFunctions = [true, false, [], {}, 42, 'foo', NaN, /a/g]; + t.plan(nonFunctions.length); + for (var i = 0; i < nonFunctions.length; ++i) { + try { functionBind.call(nonFunctions[i]); } catch (ex) { + t.ok(ex instanceof TypeError, 'throws when given ' + String(nonFunctions[i])); + } + } + t.end(); +}); + +test('without a context', function (t) { + t.test('binds properly', function (st) { + var args, context; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }) + }; + namespace.func(1, 2, 3); + st.deepEqual(args, [1, 2, 3]); + st.equal(context, getCurrentContext.call()); + st.end(); + }); + + t.test('binds properly, and still supplies bound arguments', function (st) { + var args, context; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, undefined, 1, 2, 3) + }; + namespace.func(4, 5, 6); + st.deepEqual(args, [1, 2, 3, 4, 5, 6]); + st.equal(context, getCurrentContext.call()); + st.end(); + }); + + t.test('returns properly', function (st) { + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, null) + }; + var context = namespace.func(1, 2, 3); + st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); + st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); + st.end(); + }); + + t.test('returns properly with bound arguments', function (st) { + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, null, 1, 2, 3) + }; + var context = namespace.func(4, 5, 6); + st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); + st.end(); + }); + + t.test('called as a constructor', function (st) { + var thunkify = function (value) { + return function () { return value; }; + }; + st.test('returns object value', function (sst) { + var expectedReturnValue = [1, 2, 3]; + var Constructor = functionBind.call(thunkify(expectedReturnValue), null); + var result = new Constructor(); + sst.equal(result, expectedReturnValue); + sst.end(); + }); + + st.test('does not return primitive value', function (sst) { + var Constructor = functionBind.call(thunkify(42), null); + var result = new Constructor(); + sst.notEqual(result, 42); + sst.end(); + }); + + st.test('object from bound constructor is instance of original and bound constructor', function (sst) { + var A = function (x) { + this.name = x || 'A'; + }; + var B = functionBind.call(A, null, 'B'); + + var result = new B(); + sst.ok(result instanceof B, 'result is instance of bound constructor'); + sst.ok(result instanceof A, 'result is instance of original constructor'); + sst.end(); + }); + + st.end(); + }); + + t.end(); +}); + +test('with a context', function (t) { + t.test('with no bound arguments', function (st) { + var args, context; + var boundContext = {}; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, boundContext) + }; + namespace.func(1, 2, 3); + st.equal(context, boundContext, 'binds a context properly'); + st.deepEqual(args, [1, 2, 3], 'supplies passed arguments'); + st.end(); + }); + + t.test('with bound arguments', function (st) { + var args, context; + var boundContext = {}; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, boundContext, 1, 2, 3) + }; + namespace.func(4, 5, 6); + st.equal(context, boundContext, 'binds a context properly'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'supplies bound and passed arguments'); + st.end(); + }); + + t.test('returns properly', function (st) { + var boundContext = {}; + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, boundContext) + }; + var context = namespace.func(1, 2, 3); + st.equal(context, boundContext, 'returned context is bound context'); + st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); + st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); + st.end(); + }); + + t.test('returns properly with bound arguments', function (st) { + var boundContext = {}; + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, boundContext, 1, 2, 3) + }; + var context = namespace.func(4, 5, 6); + st.equal(context, boundContext, 'returned context is bound context'); + st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); + st.end(); + }); + + t.test('passes the correct arguments when called as a constructor', function (st) { + var expected = { name: 'Correct' }; + var namespace = { + Func: functionBind.call(function (arg) { + return arg; + }, { name: 'Incorrect' }) + }; + var returned = new namespace.Func(expected); + st.equal(returned, expected, 'returns the right arg when called as a constructor'); + st.end(); + }); + + t.test('has the new instance\'s context when called as a constructor', function (st) { + var actualContext; + var expectedContext = { foo: 'bar' }; + var namespace = { + Func: functionBind.call(function () { + actualContext = this; + }, expectedContext) + }; + var result = new namespace.Func(); + st.equal(result instanceof namespace.Func, true); + st.notEqual(actualContext, expectedContext); + st.end(); + }); + + t.end(); +}); + +test('bound function length', function (t) { + t.test('sets a correct length without thisArg', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }); + st.equal(subject.length, 3); + st.equal(subject(1, 2, 3), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}); + st.equal(subject.length, 3); + st.equal(subject(1, 2, 3), 6); + st.end(); + }); + + t.test('sets a correct length without thisArg and first argument', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1); + st.equal(subject.length, 2); + st.equal(subject(2, 3), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg and first argument', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1); + st.equal(subject.length, 2); + st.equal(subject(2, 3), 6); + st.end(); + }); + + t.test('sets a correct length without thisArg and too many arguments', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1, 2, 3, 4); + st.equal(subject.length, 0); + st.equal(subject(), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg and too many arguments', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1, 2, 3, 4); + st.equal(subject.length, 0); + st.equal(subject(), 6); + st.end(); + }); +}); diff --git a/node_modules/functional-red-black-tree/.npmignore b/node_modules/functional-red-black-tree/.npmignore new file mode 100644 index 0000000..ddc9ab3 --- /dev/null +++ b/node_modules/functional-red-black-tree/.npmignore @@ -0,0 +1,16 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +npm-debug.log +node_modules/* +*.DS_Store \ No newline at end of file diff --git a/node_modules/functional-red-black-tree/LICENSE b/node_modules/functional-red-black-tree/LICENSE new file mode 100644 index 0000000..8ce206a --- /dev/null +++ b/node_modules/functional-red-black-tree/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2013 Mikola Lysenko + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/functional-red-black-tree/README.md b/node_modules/functional-red-black-tree/README.md new file mode 100644 index 0000000..edd19cb --- /dev/null +++ b/node_modules/functional-red-black-tree/README.md @@ -0,0 +1,237 @@ +functional-red-black-tree +========================= +A [fully persistent](http://en.wikipedia.org/wiki/Persistent_data_structure) [red-black tree](http://en.wikipedia.org/wiki/Red%E2%80%93black_tree) written 100% in JavaScript. Works both in node.js and in the browser via [browserify](http://browserify.org/). + +Functional (or fully presistent) data structures allow for non-destructive updates. So if you insert an element into the tree, it returns a new tree with the inserted element rather than destructively updating the existing tree in place. Doing this requires using extra memory, and if one were naive it could cost as much as reallocating the entire tree. Instead, this data structure saves some memory by recycling references to previously allocated subtrees. This requires using only O(log(n)) additional memory per update instead of a full O(n) copy. + +Some advantages of this is that it is possible to apply insertions and removals to the tree while still iterating over previous versions of the tree. Functional and persistent data structures can also be useful in many geometric algorithms like point location within triangulations or ray queries, and can be used to analyze the history of executing various algorithms. This added power though comes at a cost, since it is generally a bit slower to use a functional data structure than an imperative version. However, if your application needs this behavior then you may consider using this module. + +# Install + + npm install functional-red-black-tree + +# Example + +Here is an example of some basic usage: + +```javascript +//Load the library +var createTree = require("functional-red-black-tree") + +//Create a tree +var t1 = createTree() + +//Insert some items into the tree +var t2 = t1.insert(1, "foo") +var t3 = t2.insert(2, "bar") + +//Remove something +var t4 = t3.remove(1) +``` + + +# API + +```javascript +var createTree = require("functional-red-black-tree") +``` + +## Overview + +- [Tree methods](#tree-methods) + - [`var tree = createTree([compare])`](#var-tree-=-createtreecompare) + - [`tree.keys`](#treekeys) + - [`tree.values`](#treevalues) + - [`tree.length`](#treelength) + - [`tree.get(key)`](#treegetkey) + - [`tree.insert(key, value)`](#treeinsertkey-value) + - [`tree.remove(key)`](#treeremovekey) + - [`tree.find(key)`](#treefindkey) + - [`tree.ge(key)`](#treegekey) + - [`tree.gt(key)`](#treegtkey) + - [`tree.lt(key)`](#treeltkey) + - [`tree.le(key)`](#treelekey) + - [`tree.at(position)`](#treeatposition) + - [`tree.begin`](#treebegin) + - [`tree.end`](#treeend) + - [`tree.forEach(visitor(key,value)[, lo[, hi]])`](#treeforEachvisitorkeyvalue-lo-hi) + - [`tree.root`](#treeroot) +- [Node properties](#node-properties) + - [`node.key`](#nodekey) + - [`node.value`](#nodevalue) + - [`node.left`](#nodeleft) + - [`node.right`](#noderight) +- [Iterator methods](#iterator-methods) + - [`iter.key`](#iterkey) + - [`iter.value`](#itervalue) + - [`iter.node`](#iternode) + - [`iter.tree`](#itertree) + - [`iter.index`](#iterindex) + - [`iter.valid`](#itervalid) + - [`iter.clone()`](#iterclone) + - [`iter.remove()`](#iterremove) + - [`iter.update(value)`](#iterupdatevalue) + - [`iter.next()`](#iternext) + - [`iter.prev()`](#iterprev) + - [`iter.hasNext`](#iterhasnext) + - [`iter.hasPrev`](#iterhasprev) + +## Tree methods + +### `var tree = createTree([compare])` +Creates an empty functional tree + +* `compare` is an optional comparison function, same semantics as array.sort() + +**Returns** An empty tree ordered by `compare` + +### `tree.keys` +A sorted array of all the keys in the tree + +### `tree.values` +An array array of all the values in the tree + +### `tree.length` +The number of items in the tree + +### `tree.get(key)` +Retrieves the value associated to the given key + +* `key` is the key of the item to look up + +**Returns** The value of the first node associated to `key` + +### `tree.insert(key, value)` +Creates a new tree with the new pair inserted. + +* `key` is the key of the item to insert +* `value` is the value of the item to insert + +**Returns** A new tree with `key` and `value` inserted + +### `tree.remove(key)` +Removes the first item with `key` in the tree + +* `key` is the key of the item to remove + +**Returns** A new tree with the given item removed if it exists + +### `tree.find(key)` +Returns an iterator pointing to the first item in the tree with `key`, otherwise `null`. + +### `tree.ge(key)` +Find the first item in the tree whose key is `>= key` + +* `key` is the key to search for + +**Returns** An iterator at the given element. + +### `tree.gt(key)` +Finds the first item in the tree whose key is `> key` + +* `key` is the key to search for + +**Returns** An iterator at the given element + +### `tree.lt(key)` +Finds the last item in the tree whose key is `< key` + +* `key` is the key to search for + +**Returns** An iterator at the given element + +### `tree.le(key)` +Finds the last item in the tree whose key is `<= key` + +* `key` is the key to search for + +**Returns** An iterator at the given element + +### `tree.at(position)` +Finds an iterator starting at the given element + +* `position` is the index at which the iterator gets created + +**Returns** An iterator starting at position + +### `tree.begin` +An iterator pointing to the first element in the tree + +### `tree.end` +An iterator pointing to the last element in the tree + +### `tree.forEach(visitor(key,value)[, lo[, hi]])` +Walks a visitor function over the nodes of the tree in order. + +* `visitor(key,value)` is a callback that gets executed on each node. If a truthy value is returned from the visitor, then iteration is stopped. +* `lo` is an optional start of the range to visit (inclusive) +* `hi` is an optional end of the range to visit (non-inclusive) + +**Returns** The last value returned by the callback + +### `tree.root` +Returns the root node of the tree + + +## Node properties +Each node of the tree has the following properties: + +### `node.key` +The key associated to the node + +### `node.value` +The value associated to the node + +### `node.left` +The left subtree of the node + +### `node.right` +The right subtree of the node + +## Iterator methods + +### `iter.key` +The key of the item referenced by the iterator + +### `iter.value` +The value of the item referenced by the iterator + +### `iter.node` +The value of the node at the iterator's current position. `null` is iterator is node valid. + +### `iter.tree` +The tree associated to the iterator + +### `iter.index` +Returns the position of this iterator in the sequence. + +### `iter.valid` +Checks if the iterator is valid + +### `iter.clone()` +Makes a copy of the iterator + +### `iter.remove()` +Removes the item at the position of the iterator + +**Returns** A new binary search tree with `iter`'s item removed + +### `iter.update(value)` +Updates the value of the node in the tree at this iterator + +**Returns** A new binary search tree with the corresponding node updated + +### `iter.next()` +Advances the iterator to the next position + +### `iter.prev()` +Moves the iterator backward one element + +### `iter.hasNext` +If true, then the iterator is not at the end of the sequence + +### `iter.hasPrev` +If true, then the iterator is not at the beginning of the sequence + +# Credits +(c) 2013 Mikola Lysenko. MIT License \ No newline at end of file diff --git a/node_modules/functional-red-black-tree/bench/test.js b/node_modules/functional-red-black-tree/bench/test.js new file mode 100644 index 0000000..41c5a31 --- /dev/null +++ b/node_modules/functional-red-black-tree/bench/test.js @@ -0,0 +1,11 @@ +"use strict" + +var createTree = require("../rbtree.js") + +var t = createTree() + +var s = Date.now() +for(var i=0; i<100000; ++i) { + t = t.insert(Math.random(), Math.random()) +} +console.log(Date.now() - s) \ No newline at end of file diff --git a/node_modules/functional-red-black-tree/package.json b/node_modules/functional-red-black-tree/package.json new file mode 100644 index 0000000..13d6f27 --- /dev/null +++ b/node_modules/functional-red-black-tree/package.json @@ -0,0 +1,40 @@ +{ + "name": "functional-red-black-tree", + "version": "1.0.1", + "description": "A fully persistent balanced binary search tree", + "main": "rbtree.js", + "directories": { + "test": "test" + }, + "dependencies": {}, + "devDependencies": { + "iota-array": "^0.0.1", + "tape": "^2.12.0" + }, + "scripts": { + "test": "tape test/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/mikolalysenko/functional-red-black-tree.git" + }, + "keywords": [ + "functional", + "red", + "black", + "tree", + "binary", + "search", + "balance", + "persistent", + "fully", + "dynamic", + "data", + "structure" + ], + "author": "Mikola Lysenko", + "license": "MIT", + "bugs": { + "url": "https://github.com/mikolalysenko/functional-red-black-tree/issues" + } +} diff --git a/node_modules/functional-red-black-tree/rbtree.js b/node_modules/functional-red-black-tree/rbtree.js new file mode 100644 index 0000000..5a69a40 --- /dev/null +++ b/node_modules/functional-red-black-tree/rbtree.js @@ -0,0 +1,996 @@ +"use strict" + +module.exports = createRBTree + +var RED = 0 +var BLACK = 1 + +function RBNode(color, key, value, left, right, count) { + this._color = color + this.key = key + this.value = value + this.left = left + this.right = right + this._count = count +} + +function cloneNode(node) { + return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count) +} + +function repaint(color, node) { + return new RBNode(color, node.key, node.value, node.left, node.right, node._count) +} + +function recount(node) { + node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0) +} + +function RedBlackTree(compare, root) { + this._compare = compare + this.root = root +} + +var proto = RedBlackTree.prototype + +Object.defineProperty(proto, "keys", { + get: function() { + var result = [] + this.forEach(function(k,v) { + result.push(k) + }) + return result + } +}) + +Object.defineProperty(proto, "values", { + get: function() { + var result = [] + this.forEach(function(k,v) { + result.push(v) + }) + return result + } +}) + +//Returns the number of nodes in the tree +Object.defineProperty(proto, "length", { + get: function() { + if(this.root) { + return this.root._count + } + return 0 + } +}) + +//Insert a new item into the tree +proto.insert = function(key, value) { + var cmp = this._compare + //Find point to insert new node at + var n = this.root + var n_stack = [] + var d_stack = [] + while(n) { + var d = cmp(key, n.key) + n_stack.push(n) + d_stack.push(d) + if(d <= 0) { + n = n.left + } else { + n = n.right + } + } + //Rebuild path to leaf node + n_stack.push(new RBNode(RED, key, value, null, null, 1)) + for(var s=n_stack.length-2; s>=0; --s) { + var n = n_stack[s] + if(d_stack[s] <= 0) { + n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1) + } else { + n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1) + } + } + //Rebalance tree using rotations + //console.log("start insert", key, d_stack) + for(var s=n_stack.length-1; s>1; --s) { + var p = n_stack[s-1] + var n = n_stack[s] + if(p._color === BLACK || n._color === BLACK) { + break + } + var pp = n_stack[s-2] + if(pp.left === p) { + if(p.left === n) { + var y = pp.right + if(y && y._color === RED) { + //console.log("LLr") + p._color = BLACK + pp.right = repaint(BLACK, y) + pp._color = RED + s -= 1 + } else { + //console.log("LLb") + pp._color = RED + pp.left = p.right + p._color = BLACK + p.right = pp + n_stack[s-2] = p + n_stack[s-1] = n + recount(pp) + recount(p) + if(s >= 3) { + var ppp = n_stack[s-3] + if(ppp.left === pp) { + ppp.left = p + } else { + ppp.right = p + } + } + break + } + } else { + var y = pp.right + if(y && y._color === RED) { + //console.log("LRr") + p._color = BLACK + pp.right = repaint(BLACK, y) + pp._color = RED + s -= 1 + } else { + //console.log("LRb") + p.right = n.left + pp._color = RED + pp.left = n.right + n._color = BLACK + n.left = p + n.right = pp + n_stack[s-2] = n + n_stack[s-1] = p + recount(pp) + recount(p) + recount(n) + if(s >= 3) { + var ppp = n_stack[s-3] + if(ppp.left === pp) { + ppp.left = n + } else { + ppp.right = n + } + } + break + } + } + } else { + if(p.right === n) { + var y = pp.left + if(y && y._color === RED) { + //console.log("RRr", y.key) + p._color = BLACK + pp.left = repaint(BLACK, y) + pp._color = RED + s -= 1 + } else { + //console.log("RRb") + pp._color = RED + pp.right = p.left + p._color = BLACK + p.left = pp + n_stack[s-2] = p + n_stack[s-1] = n + recount(pp) + recount(p) + if(s >= 3) { + var ppp = n_stack[s-3] + if(ppp.right === pp) { + ppp.right = p + } else { + ppp.left = p + } + } + break + } + } else { + var y = pp.left + if(y && y._color === RED) { + //console.log("RLr") + p._color = BLACK + pp.left = repaint(BLACK, y) + pp._color = RED + s -= 1 + } else { + //console.log("RLb") + p.left = n.right + pp._color = RED + pp.right = n.left + n._color = BLACK + n.right = p + n.left = pp + n_stack[s-2] = n + n_stack[s-1] = p + recount(pp) + recount(p) + recount(n) + if(s >= 3) { + var ppp = n_stack[s-3] + if(ppp.right === pp) { + ppp.right = n + } else { + ppp.left = n + } + } + break + } + } + } + } + //Return new tree + n_stack[0]._color = BLACK + return new RedBlackTree(cmp, n_stack[0]) +} + + +//Visit all nodes inorder +function doVisitFull(visit, node) { + if(node.left) { + var v = doVisitFull(visit, node.left) + if(v) { return v } + } + var v = visit(node.key, node.value) + if(v) { return v } + if(node.right) { + return doVisitFull(visit, node.right) + } +} + +//Visit half nodes in order +function doVisitHalf(lo, compare, visit, node) { + var l = compare(lo, node.key) + if(l <= 0) { + if(node.left) { + var v = doVisitHalf(lo, compare, visit, node.left) + if(v) { return v } + } + var v = visit(node.key, node.value) + if(v) { return v } + } + if(node.right) { + return doVisitHalf(lo, compare, visit, node.right) + } +} + +//Visit all nodes within a range +function doVisit(lo, hi, compare, visit, node) { + var l = compare(lo, node.key) + var h = compare(hi, node.key) + var v + if(l <= 0) { + if(node.left) { + v = doVisit(lo, hi, compare, visit, node.left) + if(v) { return v } + } + if(h > 0) { + v = visit(node.key, node.value) + if(v) { return v } + } + } + if(h > 0 && node.right) { + return doVisit(lo, hi, compare, visit, node.right) + } +} + + +proto.forEach = function rbTreeForEach(visit, lo, hi) { + if(!this.root) { + return + } + switch(arguments.length) { + case 1: + return doVisitFull(visit, this.root) + break + + case 2: + return doVisitHalf(lo, this._compare, visit, this.root) + break + + case 3: + if(this._compare(lo, hi) >= 0) { + return + } + return doVisit(lo, hi, this._compare, visit, this.root) + break + } +} + +//First item in list +Object.defineProperty(proto, "begin", { + get: function() { + var stack = [] + var n = this.root + while(n) { + stack.push(n) + n = n.left + } + return new RedBlackTreeIterator(this, stack) + } +}) + +//Last item in list +Object.defineProperty(proto, "end", { + get: function() { + var stack = [] + var n = this.root + while(n) { + stack.push(n) + n = n.right + } + return new RedBlackTreeIterator(this, stack) + } +}) + +//Find the ith item in the tree +proto.at = function(idx) { + if(idx < 0) { + return new RedBlackTreeIterator(this, []) + } + var n = this.root + var stack = [] + while(true) { + stack.push(n) + if(n.left) { + if(idx < n.left._count) { + n = n.left + continue + } + idx -= n.left._count + } + if(!idx) { + return new RedBlackTreeIterator(this, stack) + } + idx -= 1 + if(n.right) { + if(idx >= n.right._count) { + break + } + n = n.right + } else { + break + } + } + return new RedBlackTreeIterator(this, []) +} + +proto.ge = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + var last_ptr = 0 + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d <= 0) { + last_ptr = stack.length + } + if(d <= 0) { + n = n.left + } else { + n = n.right + } + } + stack.length = last_ptr + return new RedBlackTreeIterator(this, stack) +} + +proto.gt = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + var last_ptr = 0 + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d < 0) { + last_ptr = stack.length + } + if(d < 0) { + n = n.left + } else { + n = n.right + } + } + stack.length = last_ptr + return new RedBlackTreeIterator(this, stack) +} + +proto.lt = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + var last_ptr = 0 + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d > 0) { + last_ptr = stack.length + } + if(d <= 0) { + n = n.left + } else { + n = n.right + } + } + stack.length = last_ptr + return new RedBlackTreeIterator(this, stack) +} + +proto.le = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + var last_ptr = 0 + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d >= 0) { + last_ptr = stack.length + } + if(d < 0) { + n = n.left + } else { + n = n.right + } + } + stack.length = last_ptr + return new RedBlackTreeIterator(this, stack) +} + +//Finds the item with key if it exists +proto.find = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d === 0) { + return new RedBlackTreeIterator(this, stack) + } + if(d <= 0) { + n = n.left + } else { + n = n.right + } + } + return new RedBlackTreeIterator(this, []) +} + +//Removes item with key from tree +proto.remove = function(key) { + var iter = this.find(key) + if(iter) { + return iter.remove() + } + return this +} + +//Returns the item at `key` +proto.get = function(key) { + var cmp = this._compare + var n = this.root + while(n) { + var d = cmp(key, n.key) + if(d === 0) { + return n.value + } + if(d <= 0) { + n = n.left + } else { + n = n.right + } + } + return +} + +//Iterator for red black tree +function RedBlackTreeIterator(tree, stack) { + this.tree = tree + this._stack = stack +} + +var iproto = RedBlackTreeIterator.prototype + +//Test if iterator is valid +Object.defineProperty(iproto, "valid", { + get: function() { + return this._stack.length > 0 + } +}) + +//Node of the iterator +Object.defineProperty(iproto, "node", { + get: function() { + if(this._stack.length > 0) { + return this._stack[this._stack.length-1] + } + return null + }, + enumerable: true +}) + +//Makes a copy of an iterator +iproto.clone = function() { + return new RedBlackTreeIterator(this.tree, this._stack.slice()) +} + +//Swaps two nodes +function swapNode(n, v) { + n.key = v.key + n.value = v.value + n.left = v.left + n.right = v.right + n._color = v._color + n._count = v._count +} + +//Fix up a double black node in a tree +function fixDoubleBlack(stack) { + var n, p, s, z + for(var i=stack.length-1; i>=0; --i) { + n = stack[i] + if(i === 0) { + n._color = BLACK + return + } + //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key) + p = stack[i-1] + if(p.left === n) { + //console.log("left child") + s = p.right + if(s.right && s.right._color === RED) { + //console.log("case 1: right sibling child red") + s = p.right = cloneNode(s) + z = s.right = cloneNode(s.right) + p.right = s.left + s.left = p + s.right = z + s._color = p._color + n._color = BLACK + p._color = BLACK + z._color = BLACK + recount(p) + recount(s) + if(i > 1) { + var pp = stack[i-2] + if(pp.left === p) { + pp.left = s + } else { + pp.right = s + } + } + stack[i-1] = s + return + } else if(s.left && s.left._color === RED) { + //console.log("case 1: left sibling child red") + s = p.right = cloneNode(s) + z = s.left = cloneNode(s.left) + p.right = z.left + s.left = z.right + z.left = p + z.right = s + z._color = p._color + p._color = BLACK + s._color = BLACK + n._color = BLACK + recount(p) + recount(s) + recount(z) + if(i > 1) { + var pp = stack[i-2] + if(pp.left === p) { + pp.left = z + } else { + pp.right = z + } + } + stack[i-1] = z + return + } + if(s._color === BLACK) { + if(p._color === RED) { + //console.log("case 2: black sibling, red parent", p.right.value) + p._color = BLACK + p.right = repaint(RED, s) + return + } else { + //console.log("case 2: black sibling, black parent", p.right.value) + p.right = repaint(RED, s) + continue + } + } else { + //console.log("case 3: red sibling") + s = cloneNode(s) + p.right = s.left + s.left = p + s._color = p._color + p._color = RED + recount(p) + recount(s) + if(i > 1) { + var pp = stack[i-2] + if(pp.left === p) { + pp.left = s + } else { + pp.right = s + } + } + stack[i-1] = s + stack[i] = p + if(i+1 < stack.length) { + stack[i+1] = n + } else { + stack.push(n) + } + i = i+2 + } + } else { + //console.log("right child") + s = p.left + if(s.left && s.left._color === RED) { + //console.log("case 1: left sibling child red", p.value, p._color) + s = p.left = cloneNode(s) + z = s.left = cloneNode(s.left) + p.left = s.right + s.right = p + s.left = z + s._color = p._color + n._color = BLACK + p._color = BLACK + z._color = BLACK + recount(p) + recount(s) + if(i > 1) { + var pp = stack[i-2] + if(pp.right === p) { + pp.right = s + } else { + pp.left = s + } + } + stack[i-1] = s + return + } else if(s.right && s.right._color === RED) { + //console.log("case 1: right sibling child red") + s = p.left = cloneNode(s) + z = s.right = cloneNode(s.right) + p.left = z.right + s.right = z.left + z.right = p + z.left = s + z._color = p._color + p._color = BLACK + s._color = BLACK + n._color = BLACK + recount(p) + recount(s) + recount(z) + if(i > 1) { + var pp = stack[i-2] + if(pp.right === p) { + pp.right = z + } else { + pp.left = z + } + } + stack[i-1] = z + return + } + if(s._color === BLACK) { + if(p._color === RED) { + //console.log("case 2: black sibling, red parent") + p._color = BLACK + p.left = repaint(RED, s) + return + } else { + //console.log("case 2: black sibling, black parent") + p.left = repaint(RED, s) + continue + } + } else { + //console.log("case 3: red sibling") + s = cloneNode(s) + p.left = s.right + s.right = p + s._color = p._color + p._color = RED + recount(p) + recount(s) + if(i > 1) { + var pp = stack[i-2] + if(pp.right === p) { + pp.right = s + } else { + pp.left = s + } + } + stack[i-1] = s + stack[i] = p + if(i+1 < stack.length) { + stack[i+1] = n + } else { + stack.push(n) + } + i = i+2 + } + } + } +} + +//Removes item at iterator from tree +iproto.remove = function() { + var stack = this._stack + if(stack.length === 0) { + return this.tree + } + //First copy path to node + var cstack = new Array(stack.length) + var n = stack[stack.length-1] + cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count) + for(var i=stack.length-2; i>=0; --i) { + var n = stack[i] + if(n.left === stack[i+1]) { + cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) + } else { + cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) + } + } + + //Get node + n = cstack[cstack.length-1] + //console.log("start remove: ", n.value) + + //If not leaf, then swap with previous node + if(n.left && n.right) { + //console.log("moving to leaf") + + //First walk to previous leaf + var split = cstack.length + n = n.left + while(n.right) { + cstack.push(n) + n = n.right + } + //Copy path to leaf + var v = cstack[split-1] + cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count)) + cstack[split-1].key = n.key + cstack[split-1].value = n.value + + //Fix up stack + for(var i=cstack.length-2; i>=split; --i) { + n = cstack[i] + cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) + } + cstack[split-1].left = cstack[split] + } + //console.log("stack=", cstack.map(function(v) { return v.value })) + + //Remove leaf node + n = cstack[cstack.length-1] + if(n._color === RED) { + //Easy case: removing red leaf + //console.log("RED leaf") + var p = cstack[cstack.length-2] + if(p.left === n) { + p.left = null + } else if(p.right === n) { + p.right = null + } + cstack.pop() + for(var i=0; i 0) { + return this._stack[this._stack.length-1].key + } + return + }, + enumerable: true +}) + +//Returns value +Object.defineProperty(iproto, "value", { + get: function() { + if(this._stack.length > 0) { + return this._stack[this._stack.length-1].value + } + return + }, + enumerable: true +}) + + +//Returns the position of this iterator in the sorted list +Object.defineProperty(iproto, "index", { + get: function() { + var idx = 0 + var stack = this._stack + if(stack.length === 0) { + var r = this.tree.root + if(r) { + return r._count + } + return 0 + } else if(stack[stack.length-1].left) { + idx = stack[stack.length-1].left._count + } + for(var s=stack.length-2; s>=0; --s) { + if(stack[s+1] === stack[s].right) { + ++idx + if(stack[s].left) { + idx += stack[s].left._count + } + } + } + return idx + }, + enumerable: true +}) + +//Advances iterator to next element in list +iproto.next = function() { + var stack = this._stack + if(stack.length === 0) { + return + } + var n = stack[stack.length-1] + if(n.right) { + n = n.right + while(n) { + stack.push(n) + n = n.left + } + } else { + stack.pop() + while(stack.length > 0 && stack[stack.length-1].right === n) { + n = stack[stack.length-1] + stack.pop() + } + } +} + +//Checks if iterator is at end of tree +Object.defineProperty(iproto, "hasNext", { + get: function() { + var stack = this._stack + if(stack.length === 0) { + return false + } + if(stack[stack.length-1].right) { + return true + } + for(var s=stack.length-1; s>0; --s) { + if(stack[s-1].left === stack[s]) { + return true + } + } + return false + } +}) + +//Update value +iproto.update = function(value) { + var stack = this._stack + if(stack.length === 0) { + throw new Error("Can't update empty node!") + } + var cstack = new Array(stack.length) + var n = stack[stack.length-1] + cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count) + for(var i=stack.length-2; i>=0; --i) { + n = stack[i] + if(n.left === stack[i+1]) { + cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) + } else { + cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) + } + } + return new RedBlackTree(this.tree._compare, cstack[0]) +} + +//Moves iterator backward one element +iproto.prev = function() { + var stack = this._stack + if(stack.length === 0) { + return + } + var n = stack[stack.length-1] + if(n.left) { + n = n.left + while(n) { + stack.push(n) + n = n.right + } + } else { + stack.pop() + while(stack.length > 0 && stack[stack.length-1].left === n) { + n = stack[stack.length-1] + stack.pop() + } + } +} + +//Checks if iterator is at start of tree +Object.defineProperty(iproto, "hasPrev", { + get: function() { + var stack = this._stack + if(stack.length === 0) { + return false + } + if(stack[stack.length-1].left) { + return true + } + for(var s=stack.length-1; s>0; --s) { + if(stack[s-1].right === stack[s]) { + return true + } + } + return false + } +}) + +//Default comparison function +function defaultCompare(a, b) { + if(a < b) { + return -1 + } + if(a > b) { + return 1 + } + return 0 +} + +//Build a tree +function createRBTree(compare) { + return new RedBlackTree(compare || defaultCompare, null) +} \ No newline at end of file diff --git a/node_modules/functional-red-black-tree/test/test.js b/node_modules/functional-red-black-tree/test/test.js new file mode 100644 index 0000000..fd945d0 --- /dev/null +++ b/node_modules/functional-red-black-tree/test/test.js @@ -0,0 +1,479 @@ +"use strict" + +var makeTree = require("../rbtree.js") +var tape = require("tape") +var util = require("util") +var iota = require("iota-array") + +var COLORS = [ "r", "b", "bb" ] + +function printTree(tree) { + if(!tree) { + return [] + } + return [ COLORS[tree._color], tree.key, printTree(tree.left), printTree(tree.right) ] +} + +function print(t) { + console.log(util.inspect(printTree(t.root), {depth:12})) +} + +//Ensures the red black axioms are satisfied by tree +function checkTree(tree, t) { + if(!tree.root) { + return + } + t.equals(tree.root._color, 1, "root is black") + function checkNode(node) { + if(!node) { + return [1, 0] + } + if(node._color === 0) { + t.assert(!node.left || node.left._color === 1, "children of red node must be black") + t.assert(!node.right || node.right._color === 1, "children of red node must be black") + } else { + t.equals(node._color, 1, "node color must be red or black") + } + if(node.left) { + t.assert(tree._compare(node.left.key, node.key) <= 0, "left tree order invariant") + } + if(node.right) { + t.assert(tree._compare(node.right.key, node.key) >= 0, "right tree order invariant") + } + var cl = checkNode(node.left) + var cr = checkNode(node.right) + t.equals(cl[0], cr[0], "number of black nodes along all paths to root must be constant") + t.equals(cl[1] + cr[1] + 1, node._count, "item count consistency") + return [cl[0] + node._color, cl[1] + cr[1] + 1] + } + var r = checkNode(tree.root) + t.equals(r[1], tree.length, "tree length") +} + +tape("insert()", function(t) { + var t1 = makeTree() + + var u = t1 + var arr = [] + for(var i=20; i>=0; --i) { + var x = i + var next = u.insert(x, true) + checkTree(u, t) + checkTree(next, t) + t.equals(u.length, arr.length) + arr.push(x) + u = next + } + for(var i=-20; i<0; ++i) { + var x = i + var next = u.insert(x, true) + checkTree(u, t) + checkTree(next, t) + arr.sort(function(a,b) { return a-b }) + var ptr = 0 + u.forEach(function(k,v) { + t.equals(k, arr[ptr++]) + }) + t.equals(ptr, arr.length) + arr.push(x) + u = next + } + + var start = u.begin + for(var i=-20, j=0; j<=40; ++i, ++j) { + t.equals(u.at(j).key, i, "checking at()") + t.equals(start.key, i, "checking iter") + t.equals(start.index, j, "checking index") + t.assert(start.valid, "checking valid") + if(j < 40) { + t.assert(start.hasNext, "hasNext()") + } else { + t.assert(!start.hasNext, "eof hasNext()") + } + start.next() + } + t.assert(!start.valid, "invalid eof iterator") + t.assert(!start.hasNext, "hasNext() at eof fail") + t.equals(start.index, 41, "eof index") + + t.end() +}) + +tape("foreach", function(t) { + var u = iota(31).reduce(function(u, k, v) { + return u.insert(k, v) + }, makeTree()) + + //Check basic foreach + var visit_keys = [] + var visit_vals = [] + u.forEach(function(k,v) { + visit_keys.push(k) + visit_vals.push(v) + }) + t.same(visit_keys, u.keys) + t.same(visit_vals, u.values) + + //Check foreach with termination + visit_keys = [] + visit_vals = [] + t.equals(u.forEach(function(k,v) { + if(k === 5) { + return 1000 + } + visit_keys.push(k) + visit_vals.push(v) + }), 1000) + t.same(visit_keys, u.keys.slice(0, 5)) + t.same(visit_vals, u.values.slice(0, 5)) + + //Check half interval foreach + visit_keys = [] + visit_vals = [] + u.forEach(function(k,v) { + visit_keys.push(k) + visit_vals.push(v) + }, 3) + t.same(visit_keys, u.keys.slice(3)) + t.same(visit_vals, u.values.slice(3)) + + //Check half interval foreach with termination + visit_keys = [] + visit_vals = [] + t.equals(u.forEach(function(k,v) { + if(k === 12) { + return 1000 + } + visit_keys.push(k) + visit_vals.push(v) + }, 3), 1000) + t.same(visit_keys, u.keys.slice(3, 12)) + t.same(visit_vals, u.values.slice(3, 12)) + + + //Check interval foreach + visit_keys = [] + visit_vals = [] + u.forEach(function(k,v) { + visit_keys.push(k) + visit_vals.push(v) + }, 3, 15) + t.same(visit_keys, u.keys.slice(3, 15)) + t.same(visit_vals, u.values.slice(3, 15)) + + //Check interval foreach with termination + visit_keys = [] + visit_vals = [] + t.equals(u.forEach(function(k,v) { + if(k === 12) { + return 1000 + } + visit_keys.push(k) + visit_vals.push(v) + }, 3, 15), 1000) + t.same(visit_keys, u.keys.slice(3, 12)) + t.same(visit_vals, u.values.slice(3, 12)) + + t.end() +}) + +function compareIterators(a, b, t) { + t.equals(a.tree, b.tree, "iter trees") + t.equals(a.valid, b.valid, "iter validity") + if(!b.valid) { + return + } + t.equals(a.node, b.node, "iter node") + t.equals(a.key, b.key, "iter key") + t.equals(a.value, b.value, "iter value") + t.equals(a.index, b.index, "iter index") +} + +tape("iterators", function(t) { + var u = iota(20).reduce(function(u, k, v) { + return u.insert(k, v) + }, makeTree()) + + //Try walking forward + var iter = u.begin + var c = iter.clone() + t.ok(iter.hasNext, "must have next at beginneing") + t.ok(!iter.hasPrev, "must not have predecessor") + for(var i=0; i<20; ++i) { + var v = u.at(i) + compareIterators(iter, v, t) + t.equals(iter.index, i) + iter.next() + } + t.ok(!iter.valid, "must be eof iterator") + + //Check if the clone worked + compareIterators(c, u.begin, t) + + //Try walking backward + var iter = u.end + t.ok(!iter.hasNext, "must not have next") + t.ok(iter.hasPrev, "must have predecessor") + for(var i=19; i>=0; --i) { + var v = u.at(i) + compareIterators(iter, v, t) + t.equals(iter.index, i) + iter.prev() + } + t.ok(!iter.valid, "must be eof iterator") + + t.end() +}) + + +tape("remove()", function(t) { + + var sz = [1, 2, 10, 20, 23, 31, 32, 33] + for(var n=0; n b[0]) { return 1 } + return 0 + }) + + var keys = zipped.map(function(v) { return v[0] }) + var values = zipped.map(function(v) { return v[1] }) + + t.same(u.keys, keys) + t.same(u.values, values) + + t.end() +}) + +tape("searching", function(t) { + + var arr = [0, 1, 1, 1, 1, 2, 3, 4, 5, 6, 6 ] + var u = arr.reduce(function(u, k, v) { + return u.insert(k, v) + }, makeTree()) + + + for(var i=0; i 0, "find repeat") + t.ok(u.find(1).index < 5, "find repeat") + + for(var i=0; i An HTTP request client that provides an `axios` like interface over top of `node-fetch`. + +## Install + +```sh +$ npm install gaxios +``` + +## Example + +```js +const {request} = require('gaxios'); +const res = await request({ + url: 'https://www.googleapis.com/discovery/v1/apis/', +}); +``` + +## Setting Defaults + +Gaxios supports setting default properties both on the default instance, and on additional instances. This is often useful when making many requests to the same domain with the same base settings. For example: + +```js +const gaxios = require('gaxios'); +gaxios.instance.defaults = { + baseURL: 'https://example.com' + headers: { + Authorization: 'SOME_TOKEN' + } +} +gaxios.request({url: '/data'}).then(...); +``` + +Note that setting default values will take precedence +over other authentication methods, i.e., application default credentials. + +## Request Options + +```ts +interface GaxiosOptions = { + // The url to which the request should be sent. Required. + url: string, + + // The HTTP method to use for the request. Defaults to `GET`. + method: 'GET', + + // The base Url to use for the request. Prepended to the `url` property above. + baseURL: 'https://example.com'; + + // The HTTP methods to be sent with the request. + headers: { 'some': 'header' }, + + // The data to send in the body of the request. Data objects will be + // serialized as JSON. + // + // Note: if you would like to provide a Content-Type header other than + // application/json you you must provide a string or readable stream, rather + // than an object: + // data: JSON.stringify({some: 'data'}) + // data: fs.readFile('./some-data.jpeg') + data: { + some: 'data' + }, + + // The max size of the http response content in bytes allowed. + // Defaults to `0`, which is the same as unset. + maxContentLength: 2000, + + // The max number of HTTP redirects to follow. + // Defaults to 100. + maxRedirects: 100, + + // The querystring parameters that will be encoded using `qs` and + // appended to the url + params: { + querystring: 'parameters' + }, + + // By default, we use the `querystring` package in node core to serialize + // querystring parameters. You can override that and provide your + // own implementation. + paramsSerializer: (params) => { + return qs.stringify(params); + }, + + // The timeout for the HTTP request in milliseconds. Defaults to 0. + timeout: 1000, + + // Optional method to override making the actual HTTP request. Useful + // for writing tests and instrumentation + adapter?: async (options, defaultAdapter) => { + const res = await defaultAdapter(options); + res.data = { + ...res.data, + extraProperty: 'your extra property', + }; + return res; + }; + + // The expected return type of the request. Options are: + // json | stream | blob | arraybuffer | text | unknown + // Defaults to `unknown`. + responseType: 'unknown', + + // The node.js http agent to use for the request. + agent: someHttpsAgent, + + // Custom function to determine if the response is valid based on the + // status code. Defaults to (>= 200 && < 300) + validateStatus: (status: number) => true, + + // Implementation of `fetch` to use when making the API call. By default, + // will use the browser context if available, and fall back to `node-fetch` + // in node.js otherwise. + fetchImplementation?: typeof fetch; + + // Configuration for retrying of requests. + retryConfig: { + // The number of times to retry the request. Defaults to 3. + retry?: number; + + // The number of retries already attempted. + currentRetryAttempt?: number; + + // The HTTP Methods that will be automatically retried. + // Defaults to ['GET','PUT','HEAD','OPTIONS','DELETE'] + httpMethodsToRetry?: string[]; + + // The HTTP response status codes that will automatically be retried. + // Defaults to: [[100, 199], [408, 408], [429, 429], [500, 599]] + statusCodesToRetry?: number[][]; + + // Function to invoke when a retry attempt is made. + onRetryAttempt?: (err: GaxiosError) => Promise | void; + + // Function to invoke which determines if you should retry + shouldRetry?: (err: GaxiosError) => Promise | boolean; + + // When there is no response, the number of retries to attempt. Defaults to 2. + noResponseRetries?: number; + + // The amount of time to initially delay the retry, in ms. Defaults to 100ms. + retryDelay?: number; + }, + + // Enables default configuration for retries. + retry: boolean, + + // Cancelling a request requires the `abort-controller` library. + // See https://github.com/bitinn/node-fetch#request-cancellation-with-abortsignal + signal?: AbortSignal + + /** + * A collection of parts to send as a `Content-Type: multipart/related` request. + */ + multipart?: GaxiosMultipartOptions; + + /** + * An optional proxy to use for requests. + * Available via `process.env.HTTP_PROXY` and `process.env.HTTPS_PROXY` as well - with a preference for the this config option when multiple are available. + * The `agent` option overrides this. + * + * @see {@link GaxiosOptions.noProxy} + * @see {@link GaxiosOptions.agent} + */ + proxy?: string | URL; + /** + * A list for excluding traffic for proxies. + * Available via `process.env.NO_PROXY` as well as a common-separated list of strings - merged with any local `noProxy` rules. + * + * - When provided a string, it is matched by + * - Wildcard `*.` and `.` matching are available. (e.g. `.example.com` or `*.example.com`) + * - When provided a URL, it is matched by the `.origin` property. + * - For example, requesting `https://example.com` with the following `noProxy`s would result in a no proxy use: + * - new URL('https://example.com') + * - new URL('https://example.com:443') + * - The following would be used with a proxy: + * - new URL('http://example.com:80') + * - new URL('https://example.com:8443') + * - When provided a regular expression it is used to match the stringified URL + * + * @see {@link GaxiosOptions.proxy} + */ + noProxy?: (string | URL | RegExp)[]; + + /** + * An experimental, customizable error redactor. + * + * Set `false` to disable. + * + * @remarks + * + * This does not replace the requirement for an active Data Loss Prevention (DLP) provider. For DLP suggestions, see: + * - https://cloud.google.com/sensitive-data-protection/docs/redacting-sensitive-data#dlp_deidentify_replace_infotype-nodejs + * - https://cloud.google.com/sensitive-data-protection/docs/infotypes-reference#credentials_and_secrets + * + * @experimental + */ + errorRedactor?: typeof defaultErrorRedactor | false; +} +``` + +## License + +[Apache-2.0](https://github.com/googleapis/gaxios/blob/master/LICENSE) diff --git a/node_modules/gaxios/build/src/common.d.ts b/node_modules/gaxios/build/src/common.d.ts new file mode 100644 index 0000000..93589ac --- /dev/null +++ b/node_modules/gaxios/build/src/common.d.ts @@ -0,0 +1,274 @@ +import { Agent } from 'http'; +import { URL } from 'url'; +import { Readable } from 'stream'; +/** + * Support `instanceof` operator for `GaxiosError`s in different versions of this library. + * + * @see {@link GaxiosError[Symbol.hasInstance]} + */ +export declare const GAXIOS_ERROR_SYMBOL: unique symbol; +export declare class GaxiosError extends Error { + config: GaxiosOptions; + response?: GaxiosResponse | undefined; + error?: (Error | NodeJS.ErrnoException) | undefined; + /** + * An Error code. + * See {@link https://nodejs.org/api/errors.html#errorcode error.code} + * + * @example + * 'ECONNRESET' + */ + code?: string; + /** + * An HTTP Status code. + * See {@link https://developer.mozilla.org/en-US/docs/Web/API/Response/status Response: status property} + * + * @example + * 500 + */ + status?: number; + /** + * Support `instanceof` operator for `GaxiosError` across builds/duplicated files. + * + * @see {@link GAXIOS_ERROR_SYMBOL} + * @see {@link GaxiosError[Symbol.hasInstance]} + * @see {@link https://github.com/microsoft/TypeScript/issues/13965#issuecomment-278570200} + * @see {@link https://stackoverflow.com/questions/46618852/require-and-instanceof} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance#reverting_to_default_instanceof_behavior} + */ + [GAXIOS_ERROR_SYMBOL]: string; + /** + * Support `instanceof` operator for `GaxiosError` across builds/duplicated files. + * + * @see {@link GAXIOS_ERROR_SYMBOL} + * @see {@link GaxiosError[GAXIOS_ERROR_SYMBOL]} + */ + static [Symbol.hasInstance](instance: unknown): boolean; + constructor(message: string, config: GaxiosOptions, response?: GaxiosResponse | undefined, error?: (Error | NodeJS.ErrnoException) | undefined); +} +export interface Headers { + [index: string]: any; +} +export type GaxiosPromise = Promise>; +export interface GaxiosXMLHttpRequest { + responseURL: string; +} +export interface GaxiosResponse { + config: GaxiosOptions; + data: T; + status: number; + statusText: string; + headers: Headers; + request: GaxiosXMLHttpRequest; +} +export interface GaxiosMultipartOptions { + headers: Headers; + content: string | Readable; +} +/** + * Request options that are used to form the request. + */ +export interface GaxiosOptions { + /** + * Optional method to override making the actual HTTP request. Useful + * for writing tests. + */ + adapter?: (options: GaxiosOptions, defaultAdapter: (options: GaxiosOptions) => GaxiosPromise) => GaxiosPromise; + url?: string | URL; + /** + * @deprecated + */ + baseUrl?: string; + baseURL?: string | URL; + method?: 'GET' | 'HEAD' | 'POST' | 'DELETE' | 'PUT' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'; + headers?: Headers; + data?: any; + body?: any; + /** + * The maximum size of the http response content in bytes allowed. + */ + maxContentLength?: number; + /** + * The maximum number of redirects to follow. Defaults to 20. + */ + maxRedirects?: number; + follow?: number; + /** + * A collection of parts to send as a `Content-Type: multipart/related` request. + */ + multipart?: GaxiosMultipartOptions[]; + params?: any; + paramsSerializer?: (params: { + [index: string]: string | number; + }) => string; + timeout?: number; + /** + * @deprecated ignored + */ + onUploadProgress?: (progressEvent: any) => void; + responseType?: 'arraybuffer' | 'blob' | 'json' | 'text' | 'stream' | 'unknown'; + agent?: Agent | ((parsedUrl: URL) => Agent); + validateStatus?: (status: number) => boolean; + retryConfig?: RetryConfig; + retry?: boolean; + signal?: any; + size?: number; + /** + * Implementation of `fetch` to use when making the API call. By default, + * will use the browser context if available, and fall back to `node-fetch` + * in node.js otherwise. + */ + fetchImplementation?: FetchImplementation; + cert?: string; + key?: string; + /** + * An optional proxy to use for requests. + * Available via `process.env.HTTP_PROXY` and `process.env.HTTPS_PROXY` as well - with a preference for the this config option when multiple are available. + * The {@link GaxiosOptions.agent `agent`} option overrides this. + * + * @see {@link GaxiosOptions.noProxy} + * @see {@link GaxiosOptions.agent} + */ + proxy?: string | URL; + /** + * A list for excluding traffic for proxies. + * Available via `process.env.NO_PROXY` as well as a common-separated list of strings - merged with any local `noProxy` rules. + * + * - When provided a string, it is matched by + * - Wildcard `*.` and `.` matching are available. (e.g. `.example.com` or `*.example.com`) + * - When provided a URL, it is matched by the `.origin` property. + * - For example, requesting `https://example.com` with the following `noProxy`s would result in a no proxy use: + * - new URL('https://example.com') + * - new URL('https://example.com:443') + * - The following would be used with a proxy: + * - new URL('http://example.com:80') + * - new URL('https://example.com:8443') + * - When provided a regular expression it is used to match the stringified URL + * + * @see {@link GaxiosOptions.proxy} + */ + noProxy?: (string | URL | RegExp)[]; + /** + * An experimental error redactor. + * + * @remarks + * + * This does not replace the requirement for an active Data Loss Prevention (DLP) provider. For DLP suggestions, see: + * - https://cloud.google.com/sensitive-data-protection/docs/redacting-sensitive-data#dlp_deidentify_replace_infotype-nodejs + * - https://cloud.google.com/sensitive-data-protection/docs/infotypes-reference#credentials_and_secrets + * + * @experimental + */ + errorRedactor?: typeof defaultErrorRedactor | false; +} +/** + * A partial object of `GaxiosResponse` with only redactable keys + * + * @experimental + */ +export type RedactableGaxiosOptions = Pick; +/** + * A partial object of `GaxiosResponse` with only redactable keys + * + * @experimental + */ +export type RedactableGaxiosResponse = Pick, 'config' | 'data' | 'headers'>; +/** + * Configuration for the Gaxios `request` method. + */ +export interface RetryConfig { + /** + * The number of times to retry the request. Defaults to 3. + */ + retry?: number; + /** + * The number of retries already attempted. + */ + currentRetryAttempt?: number; + /** + * The amount of time to initially delay the retry, in ms. Defaults to 100ms. + */ + retryDelay?: number; + /** + * The HTTP Methods that will be automatically retried. + * Defaults to ['GET','PUT','HEAD','OPTIONS','DELETE'] + */ + httpMethodsToRetry?: string[]; + /** + * The HTTP response status codes that will automatically be retried. + * Defaults to: [[100, 199], [408, 408], [429, 429], [500, 599]] + */ + statusCodesToRetry?: number[][]; + /** + * Function to invoke when a retry attempt is made. + */ + onRetryAttempt?: (err: GaxiosError) => Promise | void; + /** + * Function to invoke which determines if you should retry + */ + shouldRetry?: (err: GaxiosError) => Promise | boolean; + /** + * When there is no response, the number of retries to attempt. Defaults to 2. + */ + noResponseRetries?: number; + /** + * Function to invoke which returns a promise. After the promise resolves, + * the retry will be triggered. If provided, this will be used in-place of + * the `retryDelay` + */ + retryBackoff?: (err: GaxiosError, defaultBackoffMs: number) => Promise; + /** + * Time that the initial request was made. Users should not set this directly. + */ + timeOfFirstRequest?: number; + /** + * The length of time to keep retrying in ms. The last sleep period will + * be shortened as necessary, so that the last retry runs at deadline (and not + * considerably beyond it). The total time starting from when the initial + * request is sent, after which an error will be returned, regardless of the + * retrying attempts made meanwhile. Defaults to Number.MAX_SAFE_INTEGER indicating to effectively + * ignore totalTimeout. + */ + totalTimeout?: number; + maxRetryDelay?: number; + retryDelayMultiplier?: number; +} +export type FetchImplementation = (input: FetchRequestInfo, init?: FetchRequestInit) => Promise; +export type FetchRequestInfo = any; +export interface FetchResponse { + readonly status: number; + readonly statusText: string; + readonly url: string; + readonly body: unknown | null; + arrayBuffer(): Promise; + blob(): Promise; + readonly headers: FetchHeaders; + json(): Promise; + text(): Promise; +} +export interface FetchRequestInit { + method?: string; +} +export interface FetchHeaders { + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + has(name: string): boolean; + set(name: string, value: string): void; + forEach(callbackfn: (value: string, key: string) => void, thisArg?: any): void; +} +/** + * An experimental error redactor. + * + * @param config Config to potentially redact properties of + * @param response Config to potentially redact properties of + * + * @experimental + */ +export declare function defaultErrorRedactor(data: { + config?: RedactableGaxiosOptions; + response?: RedactableGaxiosResponse; +}): { + config?: RedactableGaxiosOptions; + response?: RedactableGaxiosResponse; +}; diff --git a/node_modules/gaxios/build/src/common.js b/node_modules/gaxios/build/src/common.js new file mode 100644 index 0000000..4e9dcea --- /dev/null +++ b/node_modules/gaxios/build/src/common.js @@ -0,0 +1,188 @@ +"use strict"; +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +var _a; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GaxiosError = exports.GAXIOS_ERROR_SYMBOL = void 0; +exports.defaultErrorRedactor = defaultErrorRedactor; +const url_1 = require("url"); +const util_1 = require("./util"); +const extend_1 = __importDefault(require("extend")); +/** + * Support `instanceof` operator for `GaxiosError`s in different versions of this library. + * + * @see {@link GaxiosError[Symbol.hasInstance]} + */ +exports.GAXIOS_ERROR_SYMBOL = Symbol.for(`${util_1.pkg.name}-gaxios-error`); +/* eslint-disable-next-line @typescript-eslint/no-explicit-any */ +class GaxiosError extends Error { + /** + * Support `instanceof` operator for `GaxiosError` across builds/duplicated files. + * + * @see {@link GAXIOS_ERROR_SYMBOL} + * @see {@link GaxiosError[GAXIOS_ERROR_SYMBOL]} + */ + static [(_a = exports.GAXIOS_ERROR_SYMBOL, Symbol.hasInstance)](instance) { + if (instance && + typeof instance === 'object' && + exports.GAXIOS_ERROR_SYMBOL in instance && + instance[exports.GAXIOS_ERROR_SYMBOL] === util_1.pkg.version) { + return true; + } + // fallback to native + return Function.prototype[Symbol.hasInstance].call(GaxiosError, instance); + } + constructor(message, config, response, error) { + var _b; + super(message); + this.config = config; + this.response = response; + this.error = error; + /** + * Support `instanceof` operator for `GaxiosError` across builds/duplicated files. + * + * @see {@link GAXIOS_ERROR_SYMBOL} + * @see {@link GaxiosError[Symbol.hasInstance]} + * @see {@link https://github.com/microsoft/TypeScript/issues/13965#issuecomment-278570200} + * @see {@link https://stackoverflow.com/questions/46618852/require-and-instanceof} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance#reverting_to_default_instanceof_behavior} + */ + this[_a] = util_1.pkg.version; + // deep-copy config as we do not want to mutate + // the existing config for future retries/use + this.config = (0, extend_1.default)(true, {}, config); + if (this.response) { + this.response.config = (0, extend_1.default)(true, {}, this.response.config); + } + if (this.response) { + try { + this.response.data = translateData(this.config.responseType, (_b = this.response) === null || _b === void 0 ? void 0 : _b.data); + } + catch (_c) { + // best effort - don't throw an error within an error + // we could set `this.response.config.responseType = 'unknown'`, but + // that would mutate future calls with this config object. + } + this.status = this.response.status; + } + if (error && 'code' in error && error.code) { + this.code = error.code; + } + if (config.errorRedactor) { + config.errorRedactor({ + config: this.config, + response: this.response, + }); + } + } +} +exports.GaxiosError = GaxiosError; +function translateData(responseType, data) { + switch (responseType) { + case 'stream': + return data; + case 'json': + return JSON.parse(JSON.stringify(data)); + case 'arraybuffer': + return JSON.parse(Buffer.from(data).toString('utf8')); + case 'blob': + return JSON.parse(data.text()); + default: + return data; + } +} +/** + * An experimental error redactor. + * + * @param config Config to potentially redact properties of + * @param response Config to potentially redact properties of + * + * @experimental + */ +function defaultErrorRedactor(data) { + const REDACT = '< - See `errorRedactor` option in `gaxios` for configuration>.'; + function redactHeaders(headers) { + if (!headers) + return; + for (const key of Object.keys(headers)) { + // any casing of `Authentication` + if (/^authentication$/i.test(key)) { + headers[key] = REDACT; + } + // any casing of `Authorization` + if (/^authorization$/i.test(key)) { + headers[key] = REDACT; + } + // anything containing secret, such as 'client secret' + if (/secret/i.test(key)) { + headers[key] = REDACT; + } + } + } + function redactString(obj, key) { + if (typeof obj === 'object' && + obj !== null && + typeof obj[key] === 'string') { + const text = obj[key]; + if (/grant_type=/i.test(text) || + /assertion=/i.test(text) || + /secret/i.test(text)) { + obj[key] = REDACT; + } + } + } + function redactObject(obj) { + if (typeof obj === 'object' && obj !== null) { + if ('grant_type' in obj) { + obj['grant_type'] = REDACT; + } + if ('assertion' in obj) { + obj['assertion'] = REDACT; + } + if ('client_secret' in obj) { + obj['client_secret'] = REDACT; + } + } + } + if (data.config) { + redactHeaders(data.config.headers); + redactString(data.config, 'data'); + redactObject(data.config.data); + redactString(data.config, 'body'); + redactObject(data.config.body); + try { + const url = new url_1.URL('', data.config.url); + if (url.searchParams.has('token')) { + url.searchParams.set('token', REDACT); + } + if (url.searchParams.has('client_secret')) { + url.searchParams.set('client_secret', REDACT); + } + data.config.url = url.toString(); + } + catch (_b) { + // ignore error - no need to parse an invalid URL + } + } + if (data.response) { + defaultErrorRedactor({ config: data.response.config }); + redactHeaders(data.response.headers); + redactString(data.response, 'data'); + redactObject(data.response.data); + } + return data; +} +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/node_modules/gaxios/build/src/common.js.map b/node_modules/gaxios/build/src/common.js.map new file mode 100644 index 0000000..4ee2d43 --- /dev/null +++ b/node_modules/gaxios/build/src/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","sourceRoot":"","sources":["../../src/common.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;A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QAAQ,EAAE,CAAC;QACnC,CAAC;QAAC,WAAM,CAAC;YACP,iDAAiD;QACnD,CAAC;IACH,CAAC;IAED,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;QAClB,oBAAoB,CAAC,EAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAC,CAAC,CAAC;QACrD,aAAa,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;QAErC,YAAY,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;QACpC,YAAY,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IACnC,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC"} \ No newline at end of file diff --git a/node_modules/gaxios/build/src/gaxios.d.ts b/node_modules/gaxios/build/src/gaxios.d.ts new file mode 100644 index 0000000..031d4b7 --- /dev/null +++ b/node_modules/gaxios/build/src/gaxios.d.ts @@ -0,0 +1,62 @@ +import { Agent } from 'http'; +import { URL } from 'url'; +import { GaxiosOptions, GaxiosPromise, GaxiosResponse } from './common'; +import { GaxiosInterceptorManager } from './interceptor'; +export declare class Gaxios { + #private; + protected agentCache: Map Agent)>; + /** + * Default HTTP options that will be used for every HTTP request. + */ + defaults: GaxiosOptions; + /** + * Interceptors + */ + interceptors: { + request: GaxiosInterceptorManager; + response: GaxiosInterceptorManager; + }; + /** + * The Gaxios class is responsible for making HTTP requests. + * @param defaults The default set of options to be used for this instance. + */ + constructor(defaults?: GaxiosOptions); + /** + * Perform an HTTP request with the given options. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + request(opts?: GaxiosOptions): GaxiosPromise; + private _defaultAdapter; + /** + * Internal, retryable version of the `request` method. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + protected _request(opts?: GaxiosOptions): GaxiosPromise; + private getResponseData; + /** + * By default, throw for any non-2xx status code + * @param status status code from the HTTP response + */ + private validateStatus; + /** + * Encode a set of key/value pars into a querystring format (?foo=bar&baz=boo) + * @param params key value pars to encode + */ + private paramsSerializer; + private translateResponse; + /** + * Attempts to parse a response by looking at the Content-Type header. + * @param {FetchResponse} response the HTTP response. + * @returns {Promise} a promise that resolves to the response data. + */ + private getResponseDataFromContentType; + /** + * Creates an async generator that yields the pieces of a multipart/related request body. + * This implementation follows the spec: https://www.ietf.org/rfc/rfc2387.txt. However, recursive + * multipart/related requests are not currently supported. + * + * @param {GaxioMultipartOptions[]} multipartOptions the pieces to turn into a multipart/related body. + * @param {string} boundary the boundary string to be placed between each part. + */ + private getMultipartRequest; +} diff --git a/node_modules/gaxios/build/src/gaxios.js b/node_modules/gaxios/build/src/gaxios.js new file mode 100644 index 0000000..b9fc1c0 --- /dev/null +++ b/node_modules/gaxios/build/src/gaxios.js @@ -0,0 +1,480 @@ +"use strict"; +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +var _Gaxios_instances, _a, _Gaxios_urlMayUseProxy, _Gaxios_applyRequestInterceptors, _Gaxios_applyResponseInterceptors, _Gaxios_prepareRequest, _Gaxios_proxyAgent, _Gaxios_getProxyAgent; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Gaxios = void 0; +const extend_1 = __importDefault(require("extend")); +const https_1 = require("https"); +const node_fetch_1 = __importDefault(require("node-fetch")); +const querystring_1 = __importDefault(require("querystring")); +const is_stream_1 = __importDefault(require("is-stream")); +const url_1 = require("url"); +const common_1 = require("./common"); +const retry_1 = require("./retry"); +const stream_1 = require("stream"); +const uuid_1 = require("uuid"); +const interceptor_1 = require("./interceptor"); +/* eslint-disable @typescript-eslint/no-explicit-any */ +const fetch = hasFetch() ? window.fetch : node_fetch_1.default; +function hasWindow() { + return typeof window !== 'undefined' && !!window; +} +function hasFetch() { + return hasWindow() && !!window.fetch; +} +function hasBuffer() { + return typeof Buffer !== 'undefined'; +} +function hasHeader(options, header) { + return !!getHeader(options, header); +} +function getHeader(options, header) { + header = header.toLowerCase(); + for (const key of Object.keys((options === null || options === void 0 ? void 0 : options.headers) || {})) { + if (header === key.toLowerCase()) { + return options.headers[key]; + } + } + return undefined; +} +class Gaxios { + /** + * The Gaxios class is responsible for making HTTP requests. + * @param defaults The default set of options to be used for this instance. + */ + constructor(defaults) { + _Gaxios_instances.add(this); + this.agentCache = new Map(); + this.defaults = defaults || {}; + this.interceptors = { + request: new interceptor_1.GaxiosInterceptorManager(), + response: new interceptor_1.GaxiosInterceptorManager(), + }; + } + /** + * Perform an HTTP request with the given options. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + async request(opts = {}) { + opts = await __classPrivateFieldGet(this, _Gaxios_instances, "m", _Gaxios_prepareRequest).call(this, opts); + opts = await __classPrivateFieldGet(this, _Gaxios_instances, "m", _Gaxios_applyRequestInterceptors).call(this, opts); + return __classPrivateFieldGet(this, _Gaxios_instances, "m", _Gaxios_applyResponseInterceptors).call(this, this._request(opts)); + } + async _defaultAdapter(opts) { + const fetchImpl = opts.fetchImplementation || fetch; + const res = (await fetchImpl(opts.url, opts)); + const data = await this.getResponseData(opts, res); + return this.translateResponse(opts, res, data); + } + /** + * Internal, retryable version of the `request` method. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + async _request(opts = {}) { + var _b; + try { + let translatedResponse; + if (opts.adapter) { + translatedResponse = await opts.adapter(opts, this._defaultAdapter.bind(this)); + } + else { + translatedResponse = await this._defaultAdapter(opts); + } + if (!opts.validateStatus(translatedResponse.status)) { + if (opts.responseType === 'stream') { + let response = ''; + await new Promise(resolve => { + (translatedResponse === null || translatedResponse === void 0 ? void 0 : translatedResponse.data).on('data', chunk => { + response += chunk; + }); + (translatedResponse === null || translatedResponse === void 0 ? void 0 : translatedResponse.data).on('end', resolve); + }); + translatedResponse.data = response; + } + throw new common_1.GaxiosError(`Request failed with status code ${translatedResponse.status}`, opts, translatedResponse); + } + return translatedResponse; + } + catch (e) { + const err = e instanceof common_1.GaxiosError + ? e + : new common_1.GaxiosError(e.message, opts, undefined, e); + const { shouldRetry, config } = await (0, retry_1.getRetryConfig)(err); + if (shouldRetry && config) { + err.config.retryConfig.currentRetryAttempt = + config.retryConfig.currentRetryAttempt; + // The error's config could be redacted - therefore we only want to + // copy the retry state over to the existing config + opts.retryConfig = (_b = err.config) === null || _b === void 0 ? void 0 : _b.retryConfig; + return this._request(opts); + } + throw err; + } + } + async getResponseData(opts, res) { + switch (opts.responseType) { + case 'stream': + return res.body; + case 'json': { + let data = await res.text(); + try { + data = JSON.parse(data); + } + catch (_b) { + // continue + } + return data; + } + case 'arraybuffer': + return res.arrayBuffer(); + case 'blob': + return res.blob(); + case 'text': + return res.text(); + default: + return this.getResponseDataFromContentType(res); + } + } + /** + * By default, throw for any non-2xx status code + * @param status status code from the HTTP response + */ + validateStatus(status) { + return status >= 200 && status < 300; + } + /** + * Encode a set of key/value pars into a querystring format (?foo=bar&baz=boo) + * @param params key value pars to encode + */ + paramsSerializer(params) { + return querystring_1.default.stringify(params); + } + translateResponse(opts, res, data) { + // headers need to be converted from a map to an obj + const headers = {}; + res.headers.forEach((value, key) => { + headers[key] = value; + }); + return { + config: opts, + data: data, + headers, + status: res.status, + statusText: res.statusText, + // XMLHttpRequestLike + request: { + responseURL: res.url, + }, + }; + } + /** + * Attempts to parse a response by looking at the Content-Type header. + * @param {FetchResponse} response the HTTP response. + * @returns {Promise} a promise that resolves to the response data. + */ + async getResponseDataFromContentType(response) { + let contentType = response.headers.get('Content-Type'); + if (contentType === null) { + // Maintain existing functionality by calling text() + return response.text(); + } + contentType = contentType.toLowerCase(); + if (contentType.includes('application/json')) { + let data = await response.text(); + try { + data = JSON.parse(data); + } + catch (_b) { + // continue + } + return data; + } + else if (contentType.match(/^text\//)) { + return response.text(); + } + else { + // If the content type is something not easily handled, just return the raw data (blob) + return response.blob(); + } + } + /** + * Creates an async generator that yields the pieces of a multipart/related request body. + * This implementation follows the spec: https://www.ietf.org/rfc/rfc2387.txt. However, recursive + * multipart/related requests are not currently supported. + * + * @param {GaxioMultipartOptions[]} multipartOptions the pieces to turn into a multipart/related body. + * @param {string} boundary the boundary string to be placed between each part. + */ + async *getMultipartRequest(multipartOptions, boundary) { + const finale = `--${boundary}--`; + for (const currentPart of multipartOptions) { + const partContentType = currentPart.headers['Content-Type'] || 'application/octet-stream'; + const preamble = `--${boundary}\r\nContent-Type: ${partContentType}\r\n\r\n`; + yield preamble; + if (typeof currentPart.content === 'string') { + yield currentPart.content; + } + else { + yield* currentPart.content; + } + yield '\r\n'; + } + yield finale; + } +} +exports.Gaxios = Gaxios; +_a = Gaxios, _Gaxios_instances = new WeakSet(), _Gaxios_urlMayUseProxy = function _Gaxios_urlMayUseProxy(url, noProxy = []) { + var _b, _c; + const candidate = new url_1.URL(url); + const noProxyList = [...noProxy]; + const noProxyEnvList = ((_c = ((_b = process.env.NO_PROXY) !== null && _b !== void 0 ? _b : process.env.no_proxy)) === null || _c === void 0 ? void 0 : _c.split(',')) || []; + for (const rule of noProxyEnvList) { + noProxyList.push(rule.trim()); + } + for (const rule of noProxyList) { + // Match regex + if (rule instanceof RegExp) { + if (rule.test(candidate.toString())) { + return false; + } + } + // Match URL + else if (rule instanceof url_1.URL) { + if (rule.origin === candidate.origin) { + return false; + } + } + // Match string regex + else if (rule.startsWith('*.') || rule.startsWith('.')) { + const cleanedRule = rule.replace(/^\*\./, '.'); + if (candidate.hostname.endsWith(cleanedRule)) { + return false; + } + } + // Basic string match + else if (rule === candidate.origin || + rule === candidate.hostname || + rule === candidate.href) { + return false; + } + } + return true; +}, _Gaxios_applyRequestInterceptors = +/** + * Applies the request interceptors. The request interceptors are applied after the + * call to prepareRequest is completed. + * + * @param {GaxiosOptions} options The current set of options. + * + * @returns {Promise} Promise that resolves to the set of options or response after interceptors are applied. + */ +async function _Gaxios_applyRequestInterceptors(options) { + let promiseChain = Promise.resolve(options); + for (const interceptor of this.interceptors.request.values()) { + if (interceptor) { + promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected); + } + } + return promiseChain; +}, _Gaxios_applyResponseInterceptors = +/** + * Applies the response interceptors. The response interceptors are applied after the + * call to request is made. + * + * @param {GaxiosOptions} options The current set of options. + * + * @returns {Promise} Promise that resolves to the set of options or response after interceptors are applied. + */ +async function _Gaxios_applyResponseInterceptors(response) { + let promiseChain = Promise.resolve(response); + for (const interceptor of this.interceptors.response.values()) { + if (interceptor) { + promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected); + } + } + return promiseChain; +}, _Gaxios_prepareRequest = +/** + * Validates the options, merges them with defaults, and prepare request. + * + * @param options The original options passed from the client. + * @returns Prepared options, ready to make a request + */ +async function _Gaxios_prepareRequest(options) { + var _b, _c, _d, _e; + const opts = (0, extend_1.default)(true, {}, this.defaults, options); + if (!opts.url) { + throw new Error('URL is required.'); + } + // baseUrl has been deprecated, remove in 2.0 + const baseUrl = opts.baseUrl || opts.baseURL; + if (baseUrl) { + opts.url = baseUrl.toString() + opts.url; + } + opts.paramsSerializer = opts.paramsSerializer || this.paramsSerializer; + if (opts.params && Object.keys(opts.params).length > 0) { + let additionalQueryParams = opts.paramsSerializer(opts.params); + if (additionalQueryParams.startsWith('?')) { + additionalQueryParams = additionalQueryParams.slice(1); + } + const prefix = opts.url.toString().includes('?') ? '&' : '?'; + opts.url = opts.url + prefix + additionalQueryParams; + } + if (typeof options.maxContentLength === 'number') { + opts.size = options.maxContentLength; + } + if (typeof options.maxRedirects === 'number') { + opts.follow = options.maxRedirects; + } + opts.headers = opts.headers || {}; + if (opts.multipart === undefined && opts.data) { + const isFormData = typeof FormData === 'undefined' + ? false + : (opts === null || opts === void 0 ? void 0 : opts.data) instanceof FormData; + if (is_stream_1.default.readable(opts.data)) { + opts.body = opts.data; + } + else if (hasBuffer() && Buffer.isBuffer(opts.data)) { + // Do not attempt to JSON.stringify() a Buffer: + opts.body = opts.data; + if (!hasHeader(opts, 'Content-Type')) { + opts.headers['Content-Type'] = 'application/json'; + } + } + else if (typeof opts.data === 'object') { + // If www-form-urlencoded content type has been set, but data is + // provided as an object, serialize the content using querystring: + if (!isFormData) { + if (getHeader(opts, 'content-type') === + 'application/x-www-form-urlencoded') { + opts.body = opts.paramsSerializer(opts.data); + } + else { + // } else if (!(opts.data instanceof FormData)) { + if (!hasHeader(opts, 'Content-Type')) { + opts.headers['Content-Type'] = 'application/json'; + } + opts.body = JSON.stringify(opts.data); + } + } + } + else { + opts.body = opts.data; + } + } + else if (opts.multipart && opts.multipart.length > 0) { + // note: once the minimum version reaches Node 16, + // this can be replaced with randomUUID() function from crypto + // and the dependency on UUID removed + const boundary = (0, uuid_1.v4)(); + opts.headers['Content-Type'] = `multipart/related; boundary=${boundary}`; + const bodyStream = new stream_1.PassThrough(); + opts.body = bodyStream; + (0, stream_1.pipeline)(this.getMultipartRequest(opts.multipart, boundary), bodyStream, () => { }); + } + opts.validateStatus = opts.validateStatus || this.validateStatus; + opts.responseType = opts.responseType || 'unknown'; + if (!opts.headers['Accept'] && opts.responseType === 'json') { + opts.headers['Accept'] = 'application/json'; + } + opts.method = opts.method || 'GET'; + const proxy = opts.proxy || + ((_b = process === null || process === void 0 ? void 0 : process.env) === null || _b === void 0 ? void 0 : _b.HTTPS_PROXY) || + ((_c = process === null || process === void 0 ? void 0 : process.env) === null || _c === void 0 ? void 0 : _c.https_proxy) || + ((_d = process === null || process === void 0 ? void 0 : process.env) === null || _d === void 0 ? void 0 : _d.HTTP_PROXY) || + ((_e = process === null || process === void 0 ? void 0 : process.env) === null || _e === void 0 ? void 0 : _e.http_proxy); + const urlMayUseProxy = __classPrivateFieldGet(this, _Gaxios_instances, "m", _Gaxios_urlMayUseProxy).call(this, opts.url, opts.noProxy); + if (opts.agent) { + // don't do any of the following options - use the user-provided agent. + } + else if (proxy && urlMayUseProxy) { + const HttpsProxyAgent = await __classPrivateFieldGet(_a, _a, "m", _Gaxios_getProxyAgent).call(_a); + if (this.agentCache.has(proxy)) { + opts.agent = this.agentCache.get(proxy); + } + else { + opts.agent = new HttpsProxyAgent(proxy, { + cert: opts.cert, + key: opts.key, + }); + this.agentCache.set(proxy, opts.agent); + } + } + else if (opts.cert && opts.key) { + // Configure client for mTLS + if (this.agentCache.has(opts.key)) { + opts.agent = this.agentCache.get(opts.key); + } + else { + opts.agent = new https_1.Agent({ + cert: opts.cert, + key: opts.key, + }); + this.agentCache.set(opts.key, opts.agent); + } + } + if (typeof opts.errorRedactor !== 'function' && + opts.errorRedactor !== false) { + opts.errorRedactor = common_1.defaultErrorRedactor; + } + return opts; +}, _Gaxios_getProxyAgent = async function _Gaxios_getProxyAgent() { + __classPrivateFieldSet(this, _a, __classPrivateFieldGet(this, _a, "f", _Gaxios_proxyAgent) || (await Promise.resolve().then(() => __importStar(require('https-proxy-agent')))).HttpsProxyAgent, "f", _Gaxios_proxyAgent); + return __classPrivateFieldGet(this, _a, "f", _Gaxios_proxyAgent); +}; +/** + * A cache for the lazily-loaded proxy agent. + * + * Should use {@link Gaxios[#getProxyAgent]} to retrieve. + */ +// using `import` to dynamically import the types here +_Gaxios_proxyAgent = { value: void 0 }; +//# sourceMappingURL=gaxios.js.map \ No newline at end of file diff --git a/node_modules/gaxios/build/src/gaxios.js.map b/node_modules/gaxios/build/src/gaxios.js.map new file mode 100644 index 0000000..ff6e97f --- /dev/null +++ b/node_modules/gaxios/build/src/gaxios.js.map @@ -0,0 +1 @@ +{"version":3,"file":"gaxios.js","sourceRoot":"","sources":["../../src/gaxios.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEjC,oDAA4B;AAE5B,iCAA0C;AAC1C,4DAAmC;AACnC,8DAA6B;AAC7B,0DAAiC;AACjC,6BAAwB;AAExB,qCASkB;AAClB,mCAAuC;AACv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AC;QACzC,CAAC;IACH,CAAC;SAAM,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;QACjC,4BAA4B;QAC5B,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YAClC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC7C,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,KAAK,GAAG,IAAI,aAAU,CAAC;gBAC1B,IAAI,EAAE,IAAI,CAAC,IAAI;gBACf,GAAG,EAAE,IAAI,CAAC,GAAG;aACd,CAAC,CAAC;YACH,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;QAC5C,CAAC;IACH,CAAC;IAED,IACE,OAAO,IAAI,CAAC,aAAa,KAAK,UAAU;QACxC,IAAI,CAAC,aAAa,KAAK,KAAK,EAC5B,CAAC;QACD,IAAI,CAAC,aAAa,GAAG,6BAAoB,CAAC;IAC5C,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC,0BAkHM,KAAK;IACV,8FAAqB,CAAC,wDAAa,mBAAmB,GAAC,CAAC,CAAC,eAAe,0BAAA,CAAC;IAEzE,OAAO,uBAAA,IAAI,8BAAY,CAAC;AAC1B,CAAC;AAjBD;;;;GAIG;AACH,sDAAsD;AAC/C,sCAAW,CAAsD"} \ No newline at end of file diff --git a/node_modules/gaxios/build/src/index.d.ts b/node_modules/gaxios/build/src/index.d.ts new file mode 100644 index 0000000..bcc7821 --- /dev/null +++ b/node_modules/gaxios/build/src/index.d.ts @@ -0,0 +1,15 @@ +import { GaxiosOptions } from './common'; +import { Gaxios } from './gaxios'; +export { GaxiosError, GaxiosPromise, GaxiosResponse, Headers, RetryConfig, } from './common'; +export { Gaxios, GaxiosOptions }; +export * from './interceptor'; +/** + * The default instance used when the `request` method is directly + * invoked. + */ +export declare const instance: Gaxios; +/** + * Make an HTTP request using the given options. + * @param opts Options for the request + */ +export declare function request(opts: GaxiosOptions): Promise>; diff --git a/node_modules/gaxios/build/src/index.js b/node_modules/gaxios/build/src/index.js new file mode 100644 index 0000000..cbda152 --- /dev/null +++ b/node_modules/gaxios/build/src/index.js @@ -0,0 +1,48 @@ +"use strict"; +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.instance = exports.Gaxios = exports.GaxiosError = void 0; +exports.request = request; +const gaxios_1 = require("./gaxios"); +Object.defineProperty(exports, "Gaxios", { enumerable: true, get: function () { return gaxios_1.Gaxios; } }); +var common_1 = require("./common"); +Object.defineProperty(exports, "GaxiosError", { enumerable: true, get: function () { return common_1.GaxiosError; } }); +__exportStar(require("./interceptor"), exports); +/** + * The default instance used when the `request` method is directly + * invoked. + */ +exports.instance = new gaxios_1.Gaxios(); +/** + * Make an HTTP request using the given options. + * @param opts Options for the request + */ +async function request(opts) { + return exports.instance.request(opts); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/gaxios/build/src/index.js.map b/node_modules/gaxios/build/src/index.js.map new file mode 100644 index 0000000..731822f --- /dev/null +++ b/node_modules/gaxios/build/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;;;;;;;;;;;;;;;AAyBjC,0BAEC;AAxBD,qCAAgC;AASxB,uFATA,eAAM,OASA;AAPd,mCAMkB;AALhB,qGAAA,WAAW,OAAA;AAOb,gDAA8B;AAE9B;;;GAGG;AACU,QAAA,QAAQ,GAAG,IAAI,eAAM,EAAE,CAAC;AAErC;;;GAGG;AACI,KAAK,UAAU,OAAO,CAAI,IAAmB;IAClD,OAAO,gBAAQ,CAAC,OAAO,CAAI,IAAI,CAAC,CAAC;AACnC,CAAC"} \ No newline at end of file diff --git a/node_modules/gaxios/build/src/interceptor.d.ts b/node_modules/gaxios/build/src/interceptor.d.ts new file mode 100644 index 0000000..62ab938 --- /dev/null +++ b/node_modules/gaxios/build/src/interceptor.d.ts @@ -0,0 +1,25 @@ +import { GaxiosError, GaxiosOptions, GaxiosResponse } from './common'; +/** + * Interceptors that can be run for requests or responses. These interceptors run asynchronously. + */ +export interface GaxiosInterceptor { + /** + * Function to be run when applying an interceptor. + * + * @param {T} configOrResponse The current configuration or response. + * @returns {Promise} Promise that resolves to the modified set of options or response. + */ + resolved?: (configOrResponse: T) => Promise; + /** + * Function to be run if the previous call to resolved throws / rejects or the request results in an invalid status + * as determined by the call to validateStatus. + * + * @param {GaxiosError} err The error thrown from the previously called resolved function. + */ + rejected?: (err: GaxiosError) => void; +} +/** + * Class to manage collections of GaxiosInterceptors for both requests and responses. + */ +export declare class GaxiosInterceptorManager extends Set | null> { +} diff --git a/node_modules/gaxios/build/src/interceptor.js b/node_modules/gaxios/build/src/interceptor.js new file mode 100644 index 0000000..c5e632e --- /dev/null +++ b/node_modules/gaxios/build/src/interceptor.js @@ -0,0 +1,22 @@ +"use strict"; +// Copyright 2024 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GaxiosInterceptorManager = void 0; +/** + * Class to manage collections of GaxiosInterceptors for both requests and responses. + */ +class GaxiosInterceptorManager extends Set { +} +exports.GaxiosInterceptorManager = GaxiosInterceptorManager; +//# sourceMappingURL=interceptor.js.map \ No newline at end of file diff --git a/node_modules/gaxios/build/src/interceptor.js.map b/node_modules/gaxios/build/src/interceptor.js.map new file mode 100644 index 0000000..cfd39c2 --- /dev/null +++ b/node_modules/gaxios/build/src/interceptor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"interceptor.js","sourceRoot":"","sources":["../../src/interceptor.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAwBjC;;GAEG;AACH,MAAa,wBAEX,SAAQ,GAAgC;CAAG;AAF7C,4DAE6C"} \ No newline at end of file diff --git a/node_modules/gaxios/build/src/retry.d.ts b/node_modules/gaxios/build/src/retry.d.ts new file mode 100644 index 0000000..cfc5ee2 --- /dev/null +++ b/node_modules/gaxios/build/src/retry.d.ts @@ -0,0 +1,8 @@ +import { GaxiosError } from './common'; +export declare function getRetryConfig(err: GaxiosError): Promise<{ + shouldRetry: boolean; + config?: undefined; +} | { + shouldRetry: boolean; + config: import("./common").GaxiosOptions; +}>; diff --git a/node_modules/gaxios/build/src/retry.js b/node_modules/gaxios/build/src/retry.js new file mode 100644 index 0000000..16074a4 --- /dev/null +++ b/node_modules/gaxios/build/src/retry.js @@ -0,0 +1,166 @@ +"use strict"; +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRetryConfig = getRetryConfig; +async function getRetryConfig(err) { + let config = getConfig(err); + if (!err || !err.config || (!config && !err.config.retry)) { + return { shouldRetry: false }; + } + config = config || {}; + config.currentRetryAttempt = config.currentRetryAttempt || 0; + config.retry = + config.retry === undefined || config.retry === null ? 3 : config.retry; + config.httpMethodsToRetry = config.httpMethodsToRetry || [ + 'GET', + 'HEAD', + 'PUT', + 'OPTIONS', + 'DELETE', + ]; + config.noResponseRetries = + config.noResponseRetries === undefined || config.noResponseRetries === null + ? 2 + : config.noResponseRetries; + config.retryDelayMultiplier = config.retryDelayMultiplier + ? config.retryDelayMultiplier + : 2; + config.timeOfFirstRequest = config.timeOfFirstRequest + ? config.timeOfFirstRequest + : Date.now(); + config.totalTimeout = config.totalTimeout + ? config.totalTimeout + : Number.MAX_SAFE_INTEGER; + config.maxRetryDelay = config.maxRetryDelay + ? config.maxRetryDelay + : Number.MAX_SAFE_INTEGER; + // If this wasn't in the list of status codes where we want + // to automatically retry, return. + const retryRanges = [ + // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes + // 1xx - Retry (Informational, request still processing) + // 2xx - Do not retry (Success) + // 3xx - Do not retry (Redirect) + // 4xx - Do not retry (Client errors) + // 408 - Retry ("Request Timeout") + // 429 - Retry ("Too Many Requests") + // 5xx - Retry (Server errors) + [100, 199], + [408, 408], + [429, 429], + [500, 599], + ]; + config.statusCodesToRetry = config.statusCodesToRetry || retryRanges; + // Put the config back into the err + err.config.retryConfig = config; + // Determine if we should retry the request + const shouldRetryFn = config.shouldRetry || shouldRetryRequest; + if (!(await shouldRetryFn(err))) { + return { shouldRetry: false, config: err.config }; + } + const delay = getNextRetryDelay(config); + // We're going to retry! Incremenent the counter. + err.config.retryConfig.currentRetryAttempt += 1; + // Create a promise that invokes the retry after the backOffDelay + const backoff = config.retryBackoff + ? config.retryBackoff(err, delay) + : new Promise(resolve => { + setTimeout(resolve, delay); + }); + // Notify the user if they added an `onRetryAttempt` handler + if (config.onRetryAttempt) { + config.onRetryAttempt(err); + } + // Return the promise in which recalls Gaxios to retry the request + await backoff; + return { shouldRetry: true, config: err.config }; +} +/** + * Determine based on config if we should retry the request. + * @param err The GaxiosError passed to the interceptor. + */ +function shouldRetryRequest(err) { + var _a; + const config = getConfig(err); + // node-fetch raises an AbortError if signaled: + // https://github.com/bitinn/node-fetch#request-cancellation-with-abortsignal + if (err.name === 'AbortError' || ((_a = err.error) === null || _a === void 0 ? void 0 : _a.name) === 'AbortError') { + return false; + } + // If there's no config, or retries are disabled, return. + if (!config || config.retry === 0) { + return false; + } + // Check if this error has no response (ETIMEDOUT, ENOTFOUND, etc) + if (!err.response && + (config.currentRetryAttempt || 0) >= config.noResponseRetries) { + return false; + } + // Only retry with configured HttpMethods. + if (!err.config.method || + config.httpMethodsToRetry.indexOf(err.config.method.toUpperCase()) < 0) { + return false; + } + // If this wasn't in the list of status codes where we want + // to automatically retry, return. + if (err.response && err.response.status) { + let isInRange = false; + for (const [min, max] of config.statusCodesToRetry) { + const status = err.response.status; + if (status >= min && status <= max) { + isInRange = true; + break; + } + } + if (!isInRange) { + return false; + } + } + // If we are out of retry attempts, return + config.currentRetryAttempt = config.currentRetryAttempt || 0; + if (config.currentRetryAttempt >= config.retry) { + return false; + } + return true; +} +/** + * Acquire the raxConfig object from an GaxiosError if available. + * @param err The Gaxios error with a config object. + */ +function getConfig(err) { + if (err && err.config && err.config.retryConfig) { + return err.config.retryConfig; + } + return; +} +/** + * Gets the delay to wait before the next retry. + * + * @param {RetryConfig} config The current set of retry options + * @returns {number} the amount of ms to wait before the next retry attempt. + */ +function getNextRetryDelay(config) { + var _a; + // Calculate time to wait with exponential backoff. + // If this is the first retry, look for a configured retryDelay. + const retryDelay = config.currentRetryAttempt ? 0 : (_a = config.retryDelay) !== null && _a !== void 0 ? _a : 100; + // Formula: retryDelay + ((retryDelayMultiplier^currentRetryAttempt - 1 / 2) * 1000) + const calculatedDelay = retryDelay + + ((Math.pow(config.retryDelayMultiplier, config.currentRetryAttempt) - 1) / + 2) * + 1000; + const maxAllowableDelay = config.totalTimeout - (Date.now() - config.timeOfFirstRequest); + return Math.min(calculatedDelay, maxAllowableDelay, config.maxRetryDelay); +} +//# sourceMappingURL=retry.js.map \ No newline at end of file diff --git a/node_modules/gaxios/build/src/retry.js.map b/node_modules/gaxios/build/src/retry.js.map new file mode 100644 index 0000000..b289e5d --- /dev/null +++ b/node_modules/gaxios/build/src/retry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/retry.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAIjC,wCAgFC;AAhFM,KAAK,UAAU,cAAc,CAAC,GAAgB;IACnD,IAAI,MAAM,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC;IAC5B,IAAI,CAAC,GAAG,IAAI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BAAiB,EAAE,MAAM,CAAC,aAAc,CAAC,CAAC;AAC7E,CAAC"} \ No newline at end of file diff --git a/node_modules/gaxios/build/src/util.d.ts b/node_modules/gaxios/build/src/util.d.ts new file mode 100644 index 0000000..53d5b74 --- /dev/null +++ b/node_modules/gaxios/build/src/util.d.ts @@ -0,0 +1,4 @@ +export declare const pkg: { + name: string; + version: string; +}; diff --git a/node_modules/gaxios/build/src/util.js b/node_modules/gaxios/build/src/util.js new file mode 100644 index 0000000..be41844 --- /dev/null +++ b/node_modules/gaxios/build/src/util.js @@ -0,0 +1,17 @@ +"use strict"; +// Copyright 2023 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.pkg = void 0; +exports.pkg = require('../../package.json'); +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/node_modules/gaxios/build/src/util.js.map b/node_modules/gaxios/build/src/util.js.map new file mode 100644 index 0000000..5750839 --- /dev/null +++ b/node_modules/gaxios/build/src/util.js.map @@ -0,0 +1 @@ +{"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/util.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAEpB,QAAA,GAAG,GAGZ,OAAO,CAAC,oBAAoB,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/.bin/uuid b/node_modules/gaxios/node_modules/.bin/uuid new file mode 100644 index 0000000..0c2d469 --- /dev/null +++ b/node_modules/gaxios/node_modules/.bin/uuid @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../uuid/dist/bin/uuid" "$@" +else + exec node "$basedir/../uuid/dist/bin/uuid" "$@" +fi diff --git a/node_modules/gaxios/node_modules/.bin/uuid.cmd b/node_modules/gaxios/node_modules/.bin/uuid.cmd new file mode 100644 index 0000000..0f2376e --- /dev/null +++ b/node_modules/gaxios/node_modules/.bin/uuid.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\uuid\dist\bin\uuid" %* diff --git a/node_modules/gaxios/node_modules/.bin/uuid.ps1 b/node_modules/gaxios/node_modules/.bin/uuid.ps1 new file mode 100644 index 0000000..7804628 --- /dev/null +++ b/node_modules/gaxios/node_modules/.bin/uuid.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } else { + & "$basedir/node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } else { + & "node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/gaxios/node_modules/uuid/CHANGELOG.md b/node_modules/gaxios/node_modules/uuid/CHANGELOG.md new file mode 100644 index 0000000..0412ad8 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/CHANGELOG.md @@ -0,0 +1,274 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## [9.0.1](https://github.com/uuidjs/uuid/compare/v9.0.0...v9.0.1) (2023-09-12) + +### build + +- Fix CI to work with Node.js 20.x + +## [9.0.0](https://github.com/uuidjs/uuid/compare/v8.3.2...v9.0.0) (2022-09-05) + +### ⚠ BREAKING CHANGES + +- Drop Node.js 10.x support. This library always aims at supporting one EOLed LTS release which by this time now is 12.x which has reached EOL 30 Apr 2022. + +- Remove the minified UMD build from the package. + + Minified code is hard to audit and since this is a widely used library it seems more appropriate nowadays to optimize for auditability than to ship a legacy module format that, at best, serves educational purposes nowadays. + + For production browser use cases, users should be using a bundler. For educational purposes, today's online sandboxes like replit.com offer convenient ways to load npm modules, so the use case for UMD through repos like UNPKG or jsDelivr has largely vanished. + +- Drop IE 11 and Safari 10 support. Drop support for browsers that don't correctly implement const/let and default arguments, and no longer transpile the browser build to ES2015. + + This also removes the fallback on msCrypto instead of the crypto API. + + Browser tests are run in the first supported version of each supported browser and in the latest (as of this commit) version available on Browserstack. + +### Features + +- optimize uuid.v1 by 1.3x uuid.v4 by 4.3x (430%) ([#597](https://github.com/uuidjs/uuid/issues/597)) ([3a033f6](https://github.com/uuidjs/uuid/commit/3a033f6bab6bb3780ece6d645b902548043280bc)) +- remove UMD build ([#645](https://github.com/uuidjs/uuid/issues/645)) ([e948a0f](https://github.com/uuidjs/uuid/commit/e948a0f22bf22f4619b27bd913885e478e20fe6f)), closes [#620](https://github.com/uuidjs/uuid/issues/620) +- use native crypto.randomUUID when available ([#600](https://github.com/uuidjs/uuid/issues/600)) ([c9e076c](https://github.com/uuidjs/uuid/commit/c9e076c852edad7e9a06baaa1d148cf4eda6c6c4)) + +### Bug Fixes + +- add Jest/jsdom compatibility ([#642](https://github.com/uuidjs/uuid/issues/642)) ([16f9c46](https://github.com/uuidjs/uuid/commit/16f9c469edf46f0786164cdf4dc980743984a6fd)) +- change default export to named function ([#545](https://github.com/uuidjs/uuid/issues/545)) ([c57bc5a](https://github.com/uuidjs/uuid/commit/c57bc5a9a0653273aa639cda9177ce52efabe42a)) +- handle error when parameter is not set in v3 and v5 ([#622](https://github.com/uuidjs/uuid/issues/622)) ([fcd7388](https://github.com/uuidjs/uuid/commit/fcd73881692d9fabb63872576ba28e30ff852091)) +- run npm audit fix ([#644](https://github.com/uuidjs/uuid/issues/644)) ([04686f5](https://github.com/uuidjs/uuid/commit/04686f54c5fed2cfffc1b619f4970c4bb8532353)) +- upgrading from uuid3 broken link ([#568](https://github.com/uuidjs/uuid/issues/568)) ([1c849da](https://github.com/uuidjs/uuid/commit/1c849da6e164259e72e18636726345b13a7eddd6)) + +### build + +- drop Node.js 8.x from babel transpile target ([#603](https://github.com/uuidjs/uuid/issues/603)) ([aa11485](https://github.com/uuidjs/uuid/commit/aa114858260402107ec8a1e1a825dea0a259bcb5)) +- drop support for legacy browsers (IE11, Safari 10) ([#604](https://github.com/uuidjs/uuid/issues/604)) ([0f433e5](https://github.com/uuidjs/uuid/commit/0f433e5ec444edacd53016de67db021102f36148)) + +- drop node 10.x to upgrade dev dependencies ([#653](https://github.com/uuidjs/uuid/issues/653)) ([28a5712](https://github.com/uuidjs/uuid/commit/28a571283f8abda6b9d85e689f95b7d3ee9e282e)), closes [#643](https://github.com/uuidjs/uuid/issues/643) + +### [8.3.2](https://github.com/uuidjs/uuid/compare/v8.3.1...v8.3.2) (2020-12-08) + +### Bug Fixes + +- lazy load getRandomValues ([#537](https://github.com/uuidjs/uuid/issues/537)) ([16c8f6d](https://github.com/uuidjs/uuid/commit/16c8f6df2f6b09b4d6235602d6a591188320a82e)), closes [#536](https://github.com/uuidjs/uuid/issues/536) + +### [8.3.1](https://github.com/uuidjs/uuid/compare/v8.3.0...v8.3.1) (2020-10-04) + +### Bug Fixes + +- support expo>=39.0.0 ([#515](https://github.com/uuidjs/uuid/issues/515)) ([c65a0f3](https://github.com/uuidjs/uuid/commit/c65a0f3fa73b901959d638d1e3591dfacdbed867)), closes [#375](https://github.com/uuidjs/uuid/issues/375) + +## [8.3.0](https://github.com/uuidjs/uuid/compare/v8.2.0...v8.3.0) (2020-07-27) + +### Features + +- add parse/stringify/validate/version/NIL APIs ([#479](https://github.com/uuidjs/uuid/issues/479)) ([0e6c10b](https://github.com/uuidjs/uuid/commit/0e6c10ba1bf9517796ff23c052fc0468eedfd5f4)), closes [#475](https://github.com/uuidjs/uuid/issues/475) [#478](https://github.com/uuidjs/uuid/issues/478) [#480](https://github.com/uuidjs/uuid/issues/480) [#481](https://github.com/uuidjs/uuid/issues/481) [#180](https://github.com/uuidjs/uuid/issues/180) + +## [8.2.0](https://github.com/uuidjs/uuid/compare/v8.1.0...v8.2.0) (2020-06-23) + +### Features + +- improve performance of v1 string representation ([#453](https://github.com/uuidjs/uuid/issues/453)) ([0ee0b67](https://github.com/uuidjs/uuid/commit/0ee0b67c37846529c66089880414d29f3ae132d5)) +- remove deprecated v4 string parameter ([#454](https://github.com/uuidjs/uuid/issues/454)) ([88ce3ca](https://github.com/uuidjs/uuid/commit/88ce3ca0ba046f60856de62c7ce03f7ba98ba46c)), closes [#437](https://github.com/uuidjs/uuid/issues/437) +- support jspm ([#473](https://github.com/uuidjs/uuid/issues/473)) ([e9f2587](https://github.com/uuidjs/uuid/commit/e9f2587a92575cac31bc1d4ae944e17c09756659)) + +### Bug Fixes + +- prepare package exports for webpack 5 ([#468](https://github.com/uuidjs/uuid/issues/468)) ([8d6e6a5](https://github.com/uuidjs/uuid/commit/8d6e6a5f8965ca9575eb4d92e99a43435f4a58a8)) + +## [8.1.0](https://github.com/uuidjs/uuid/compare/v8.0.0...v8.1.0) (2020-05-20) + +### Features + +- improve v4 performance by reusing random number array ([#435](https://github.com/uuidjs/uuid/issues/435)) ([bf4af0d](https://github.com/uuidjs/uuid/commit/bf4af0d711b4d2ed03d1f74fd12ad0baa87dc79d)) +- optimize V8 performance of bytesToUuid ([#434](https://github.com/uuidjs/uuid/issues/434)) ([e156415](https://github.com/uuidjs/uuid/commit/e156415448ec1af2351fa0b6660cfb22581971f2)) + +### Bug Fixes + +- export package.json required by react-native and bundlers ([#449](https://github.com/uuidjs/uuid/issues/449)) ([be1c8fe](https://github.com/uuidjs/uuid/commit/be1c8fe9a3206c358e0059b52fafd7213aa48a52)), closes [ai/nanoevents#44](https://github.com/ai/nanoevents/issues/44#issuecomment-602010343) [#444](https://github.com/uuidjs/uuid/issues/444) + +## [8.0.0](https://github.com/uuidjs/uuid/compare/v7.0.3...v8.0.0) (2020-04-29) + +### ⚠ BREAKING CHANGES + +- For native ECMAScript Module (ESM) usage in Node.js only named exports are exposed, there is no more default export. + + ```diff + -import uuid from 'uuid'; + -console.log(uuid.v4()); // -> 'cd6c3b08-0adc-4f4b-a6ef-36087a1c9869' + +import { v4 as uuidv4 } from 'uuid'; + +uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' + ``` + +- Deep requiring specific algorithms of this library like `require('uuid/v4')`, which has been deprecated in `uuid@7`, is no longer supported. + + Instead use the named exports that this module exports. + + For ECMAScript Modules (ESM): + + ```diff + -import uuidv4 from 'uuid/v4'; + +import { v4 as uuidv4 } from 'uuid'; + uuidv4(); + ``` + + For CommonJS: + + ```diff + -const uuidv4 = require('uuid/v4'); + +const { v4: uuidv4 } = require('uuid'); + uuidv4(); + ``` + +### Features + +- native Node.js ES Modules (wrapper approach) ([#423](https://github.com/uuidjs/uuid/issues/423)) ([2d9f590](https://github.com/uuidjs/uuid/commit/2d9f590ad9701d692625c07ed62f0a0f91227991)), closes [#245](https://github.com/uuidjs/uuid/issues/245) [#419](https://github.com/uuidjs/uuid/issues/419) [#342](https://github.com/uuidjs/uuid/issues/342) +- remove deep requires ([#426](https://github.com/uuidjs/uuid/issues/426)) ([daf72b8](https://github.com/uuidjs/uuid/commit/daf72b84ceb20272a81bb5fbddb05dd95922cbba)) + +### Bug Fixes + +- add CommonJS syntax example to README quickstart section ([#417](https://github.com/uuidjs/uuid/issues/417)) ([e0ec840](https://github.com/uuidjs/uuid/commit/e0ec8402c7ad44b7ef0453036c612f5db513fda0)) + +### [7.0.3](https://github.com/uuidjs/uuid/compare/v7.0.2...v7.0.3) (2020-03-31) + +### Bug Fixes + +- make deep require deprecation warning work in browsers ([#409](https://github.com/uuidjs/uuid/issues/409)) ([4b71107](https://github.com/uuidjs/uuid/commit/4b71107d8c0d2ef56861ede6403fc9dc35a1e6bf)), closes [#408](https://github.com/uuidjs/uuid/issues/408) + +### [7.0.2](https://github.com/uuidjs/uuid/compare/v7.0.1...v7.0.2) (2020-03-04) + +### Bug Fixes + +- make access to msCrypto consistent ([#393](https://github.com/uuidjs/uuid/issues/393)) ([8bf2a20](https://github.com/uuidjs/uuid/commit/8bf2a20f3565df743da7215eebdbada9d2df118c)) +- simplify link in deprecation warning ([#391](https://github.com/uuidjs/uuid/issues/391)) ([bb2c8e4](https://github.com/uuidjs/uuid/commit/bb2c8e4e9f4c5f9c1eaaf3ea59710c633cd90cb7)) +- update links to match content in readme ([#386](https://github.com/uuidjs/uuid/issues/386)) ([44f2f86](https://github.com/uuidjs/uuid/commit/44f2f86e9d2bbf14ee5f0f00f72a3db1292666d4)) + +### [7.0.1](https://github.com/uuidjs/uuid/compare/v7.0.0...v7.0.1) (2020-02-25) + +### Bug Fixes + +- clean up esm builds for node and browser ([#383](https://github.com/uuidjs/uuid/issues/383)) ([59e6a49](https://github.com/uuidjs/uuid/commit/59e6a49e7ce7b3e8fb0f3ee52b9daae72af467dc)) +- provide browser versions independent from module system ([#380](https://github.com/uuidjs/uuid/issues/380)) ([4344a22](https://github.com/uuidjs/uuid/commit/4344a22e7aed33be8627eeaaf05360f256a21753)), closes [#378](https://github.com/uuidjs/uuid/issues/378) + +## [7.0.0](https://github.com/uuidjs/uuid/compare/v3.4.0...v7.0.0) (2020-02-24) + +### ⚠ BREAKING CHANGES + +- The default export, which used to be the v4() method but which was already discouraged in v3.x of this library, has been removed. +- Explicitly note that deep imports of the different uuid version functions are deprecated and no longer encouraged and that ECMAScript module named imports should be used instead. Emit a deprecation warning for people who deep-require the different algorithm variants. +- Remove builtin support for insecure random number generators in the browser. Users who want that will have to supply their own random number generator function. +- Remove support for generating v3 and v5 UUIDs in Node.js<4.x +- Convert code base to ECMAScript Modules (ESM) and release CommonJS build for node and ESM build for browser bundlers. + +### Features + +- add UMD build to npm package ([#357](https://github.com/uuidjs/uuid/issues/357)) ([4e75adf](https://github.com/uuidjs/uuid/commit/4e75adf435196f28e3fbbe0185d654b5ded7ca2c)), closes [#345](https://github.com/uuidjs/uuid/issues/345) +- add various es module and CommonJS examples ([b238510](https://github.com/uuidjs/uuid/commit/b238510bf352463521f74bab175a3af9b7a42555)) +- ensure that docs are up-to-date in CI ([ee5e77d](https://github.com/uuidjs/uuid/commit/ee5e77db547474f5a8f23d6c857a6d399209986b)) +- hybrid CommonJS & ECMAScript modules build ([a3f078f](https://github.com/uuidjs/uuid/commit/a3f078faa0baff69ab41aed08e041f8f9c8993d0)) +- remove insecure fallback random number generator ([3a5842b](https://github.com/uuidjs/uuid/commit/3a5842b141a6e5de0ae338f391661e6b84b167c9)), closes [#173](https://github.com/uuidjs/uuid/issues/173) +- remove support for pre Node.js v4 Buffer API ([#356](https://github.com/uuidjs/uuid/issues/356)) ([b59b5c5](https://github.com/uuidjs/uuid/commit/b59b5c5ecad271c5453f1a156f011671f6d35627)) +- rename repository to github:uuidjs/uuid ([#351](https://github.com/uuidjs/uuid/issues/351)) ([c37a518](https://github.com/uuidjs/uuid/commit/c37a518e367ac4b6d0aa62dba1bc6ce9e85020f7)), closes [#338](https://github.com/uuidjs/uuid/issues/338) + +### Bug Fixes + +- add deep-require proxies for local testing and adjust tests ([#365](https://github.com/uuidjs/uuid/issues/365)) ([7fedc79](https://github.com/uuidjs/uuid/commit/7fedc79ac8fda4bfd1c566c7f05ef4ac13b2db48)) +- add note about removal of default export ([#372](https://github.com/uuidjs/uuid/issues/372)) ([12749b7](https://github.com/uuidjs/uuid/commit/12749b700eb49db8a9759fd306d8be05dbfbd58c)), closes [#370](https://github.com/uuidjs/uuid/issues/370) +- deprecated deep requiring of the different algorithm versions ([#361](https://github.com/uuidjs/uuid/issues/361)) ([c0bdf15](https://github.com/uuidjs/uuid/commit/c0bdf15e417639b1aeb0b247b2fb11f7a0a26b23)) + +## [3.4.0](https://github.com/uuidjs/uuid/compare/v3.3.3...v3.4.0) (2020-01-16) + +### Features + +- rename repository to github:uuidjs/uuid ([#351](https://github.com/uuidjs/uuid/issues/351)) ([e2d7314](https://github.com/uuidjs/uuid/commit/e2d7314)), closes [#338](https://github.com/uuidjs/uuid/issues/338) + +## [3.3.3](https://github.com/uuidjs/uuid/compare/v3.3.2...v3.3.3) (2019-08-19) + +### Bug Fixes + +- no longer run ci tests on node v4 +- upgrade dependencies + +## [3.3.2](https://github.com/uuidjs/uuid/compare/v3.3.1...v3.3.2) (2018-06-28) + +### Bug Fixes + +- typo ([305d877](https://github.com/uuidjs/uuid/commit/305d877)) + +## [3.3.1](https://github.com/uuidjs/uuid/compare/v3.3.0...v3.3.1) (2018-06-28) + +### Bug Fixes + +- fix [#284](https://github.com/uuidjs/uuid/issues/284) by setting function name in try-catch ([f2a60f2](https://github.com/uuidjs/uuid/commit/f2a60f2)) + +# [3.3.0](https://github.com/uuidjs/uuid/compare/v3.2.1...v3.3.0) (2018-06-22) + +### Bug Fixes + +- assignment to readonly property to allow running in strict mode ([#270](https://github.com/uuidjs/uuid/issues/270)) ([d062fdc](https://github.com/uuidjs/uuid/commit/d062fdc)) +- fix [#229](https://github.com/uuidjs/uuid/issues/229) ([c9684d4](https://github.com/uuidjs/uuid/commit/c9684d4)) +- Get correct version of IE11 crypto ([#274](https://github.com/uuidjs/uuid/issues/274)) ([153d331](https://github.com/uuidjs/uuid/commit/153d331)) +- mem issue when generating uuid ([#267](https://github.com/uuidjs/uuid/issues/267)) ([c47702c](https://github.com/uuidjs/uuid/commit/c47702c)) + +### Features + +- enforce Conventional Commit style commit messages ([#282](https://github.com/uuidjs/uuid/issues/282)) ([cc9a182](https://github.com/uuidjs/uuid/commit/cc9a182)) + +## [3.2.1](https://github.com/uuidjs/uuid/compare/v3.2.0...v3.2.1) (2018-01-16) + +### Bug Fixes + +- use msCrypto if available. Fixes [#241](https://github.com/uuidjs/uuid/issues/241) ([#247](https://github.com/uuidjs/uuid/issues/247)) ([1fef18b](https://github.com/uuidjs/uuid/commit/1fef18b)) + +# [3.2.0](https://github.com/uuidjs/uuid/compare/v3.1.0...v3.2.0) (2018-01-16) + +### Bug Fixes + +- remove mistakenly added typescript dependency, rollback version (standard-version will auto-increment) ([09fa824](https://github.com/uuidjs/uuid/commit/09fa824)) +- use msCrypto if available. Fixes [#241](https://github.com/uuidjs/uuid/issues/241) ([#247](https://github.com/uuidjs/uuid/issues/247)) ([1fef18b](https://github.com/uuidjs/uuid/commit/1fef18b)) + +### Features + +- Add v3 Support ([#217](https://github.com/uuidjs/uuid/issues/217)) ([d94f726](https://github.com/uuidjs/uuid/commit/d94f726)) + +# [3.1.0](https://github.com/uuidjs/uuid/compare/v3.1.0...v3.0.1) (2017-06-17) + +### Bug Fixes + +- (fix) Add .npmignore file to exclude test/ and other non-essential files from packing. (#183) +- Fix typo (#178) +- Simple typo fix (#165) + +### Features + +- v5 support in CLI (#197) +- V5 support (#188) + +# 3.0.1 (2016-11-28) + +- split uuid versions into separate files + +# 3.0.0 (2016-11-17) + +- remove .parse and .unparse + +# 2.0.0 + +- Removed uuid.BufferClass + +# 1.4.0 + +- Improved module context detection +- Removed public RNG functions + +# 1.3.2 + +- Improve tests and handling of v1() options (Issue #24) +- Expose RNG option to allow for perf testing with different generators + +# 1.3.0 + +- Support for version 1 ids, thanks to [@ctavan](https://github.com/ctavan)! +- Support for node.js crypto API +- De-emphasizing performance in favor of a) cryptographic quality PRNGs where available and b) more manageable code diff --git a/node_modules/gaxios/node_modules/uuid/CONTRIBUTING.md b/node_modules/gaxios/node_modules/uuid/CONTRIBUTING.md new file mode 100644 index 0000000..4a4503d --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/CONTRIBUTING.md @@ -0,0 +1,18 @@ +# Contributing + +Please feel free to file GitHub Issues or propose Pull Requests. We're always happy to discuss improvements to this library! + +## Testing + +```shell +npm test +``` + +## Releasing + +Releases are supposed to be done from master, version bumping is automated through [`standard-version`](https://github.com/conventional-changelog/standard-version): + +```shell +npm run release -- --dry-run # verify output manually +npm run release # follow the instructions from the output of this command +``` diff --git a/node_modules/gaxios/node_modules/uuid/LICENSE.md b/node_modules/gaxios/node_modules/uuid/LICENSE.md new file mode 100644 index 0000000..3934168 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/LICENSE.md @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2010-2020 Robert Kieffer and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/gaxios/node_modules/uuid/README.md b/node_modules/gaxios/node_modules/uuid/README.md new file mode 100644 index 0000000..4f51e09 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/README.md @@ -0,0 +1,466 @@ + + + +# uuid [![CI](https://github.com/uuidjs/uuid/workflows/CI/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ACI) [![Browser](https://github.com/uuidjs/uuid/workflows/Browser/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ABrowser) + +For the creation of [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) UUIDs + +- **Complete** - Support for RFC4122 version 1, 3, 4, and 5 UUIDs +- **Cross-platform** - Support for ... + - CommonJS, [ECMAScript Modules](#ecmascript-modules) and [CDN builds](#cdn-builds) + - NodeJS 12+ ([LTS releases](https://github.com/nodejs/Release)) + - Chrome, Safari, Firefox, Edge browsers + - Webpack and rollup.js module bundlers + - [React Native / Expo](#react-native--expo) +- **Secure** - Cryptographically-strong random values +- **Small** - Zero-dependency, small footprint, plays nice with "tree shaking" packagers +- **CLI** - Includes the [`uuid` command line](#command-line) utility + +> **Note** Upgrading from `uuid@3`? Your code is probably okay, but check out [Upgrading From `uuid@3`](#upgrading-from-uuid3) for details. + +> **Note** Only interested in creating a version 4 UUID? You might be able to use [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID), eliminating the need to install this library. + +## Quickstart + +To create a random UUID... + +**1. Install** + +```shell +npm install uuid +``` + +**2. Create a UUID** (ES6 module syntax) + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' +``` + +... or using CommonJS syntax: + +```javascript +const { v4: uuidv4 } = require('uuid'); +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +For timestamp UUIDs, namespace UUIDs, and other options read on ... + +## API Summary + +| | | | +| --- | --- | --- | +| [`uuid.NIL`](#uuidnil) | The nil UUID string (all zeros) | New in `uuid@8.3` | +| [`uuid.parse()`](#uuidparsestr) | Convert UUID string to array of bytes | New in `uuid@8.3` | +| [`uuid.stringify()`](#uuidstringifyarr-offset) | Convert array of bytes to UUID string | New in `uuid@8.3` | +| [`uuid.v1()`](#uuidv1options-buffer-offset) | Create a version 1 (timestamp) UUID | | +| [`uuid.v3()`](#uuidv3name-namespace-buffer-offset) | Create a version 3 (namespace w/ MD5) UUID | | +| [`uuid.v4()`](#uuidv4options-buffer-offset) | Create a version 4 (random) UUID | | +| [`uuid.v5()`](#uuidv5name-namespace-buffer-offset) | Create a version 5 (namespace w/ SHA-1) UUID | | +| [`uuid.validate()`](#uuidvalidatestr) | Test a string to see if it is a valid UUID | New in `uuid@8.3` | +| [`uuid.version()`](#uuidversionstr) | Detect RFC version of a UUID | New in `uuid@8.3` | + +## API + +### uuid.NIL + +The nil UUID string (all zeros). + +Example: + +```javascript +import { NIL as NIL_UUID } from 'uuid'; + +NIL_UUID; // ⇨ '00000000-0000-0000-0000-000000000000' +``` + +### uuid.parse(str) + +Convert UUID string to array of bytes + +| | | +| --------- | ---------------------------------------- | +| `str` | A valid UUID `String` | +| _returns_ | `Uint8Array[16]` | +| _throws_ | `TypeError` if `str` is not a valid UUID | + +Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left ↠ right order of hex-pairs in UUID strings. As shown in the example below. + +Example: + +```javascript +import { parse as uuidParse } from 'uuid'; + +// Parse a UUID +const bytes = uuidParse('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); + +// Convert to hex strings to show byte order (for documentation purposes) +[...bytes].map((v) => v.toString(16).padStart(2, '0')); // ⇨ + // [ + // '6e', 'c0', 'bd', '7f', + // '11', 'c0', '43', 'da', + // '97', '5e', '2a', '8a', + // 'd9', 'eb', 'ae', '0b' + // ] +``` + +### uuid.stringify(arr[, offset]) + +Convert array of bytes to UUID string + +| | | +| -------------- | ---------------------------------------------------------------------------- | +| `arr` | `Array`-like collection of 16 values (starting from `offset`) between 0-255. | +| [`offset` = 0] | `Number` Starting index in the Array | +| _returns_ | `String` | +| _throws_ | `TypeError` if a valid UUID string cannot be generated | + +Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left ↠ right order of hex-pairs in UUID strings. As shown in the example below. + +Example: + +```javascript +import { stringify as uuidStringify } from 'uuid'; + +const uuidBytes = [ + 0x6e, 0xc0, 0xbd, 0x7f, 0x11, 0xc0, 0x43, 0xda, 0x97, 0x5e, 0x2a, 0x8a, 0xd9, 0xeb, 0xae, 0x0b, +]; + +uuidStringify(uuidBytes); // ⇨ '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b' +``` + +### uuid.v1([options[, buffer[, offset]]]) + +Create an RFC version 1 (timestamp) UUID + +| | | +| --- | --- | +| [`options`] | `Object` with one or more of the following properties: | +| [`options.node` ] | RFC "node" field as an `Array[6]` of byte values (per 4.1.6) | +| [`options.clockseq`] | RFC "clock sequence" as a `Number` between 0 - 0x3fff | +| [`options.msecs`] | RFC "timestamp" field (`Number` of milliseconds, unix epoch) | +| [`options.nsecs`] | RFC "timestamp" field (`Number` of nanoseconds to add to `msecs`, should be 0-10,000) | +| [`options.random`] | `Array` of 16 random bytes (0-255) | +| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | +| _throws_ | `Error` if more than 10M UUIDs/sec are requested | + +Note: The default [node id](https://tools.ietf.org/html/rfc4122#section-4.1.6) (the last 12 digits in the UUID) is generated once, randomly, on process startup, and then remains unchanged for the duration of the process. + +Note: `options.random` and `options.rng` are only meaningful on the very first call to `v1()`, where they may be passed to initialize the internal `node` and `clockseq` fields. + +Example: + +```javascript +import { v1 as uuidv1 } from 'uuid'; + +uuidv1(); // ⇨ '2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d' +``` + +Example using `options`: + +```javascript +import { v1 as uuidv1 } from 'uuid'; + +const v1options = { + node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab], + clockseq: 0x1234, + msecs: new Date('2011-11-01').getTime(), + nsecs: 5678, +}; +uuidv1(v1options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab' +``` + +### uuid.v3(name, namespace[, buffer[, offset]]) + +Create an RFC version 3 (namespace w/ MD5) UUID + +API is identical to `v5()`, but uses "v3" instead. + +⚠️ Note: Per the RFC, "_If backward compatibility is not an issue, SHA-1 [Version 5] is preferred_." + +### uuid.v4([options[, buffer[, offset]]]) + +Create an RFC version 4 (random) UUID + +| | | +| --- | --- | +| [`options`] | `Object` with one or more of the following properties: | +| [`options.random`] | `Array` of 16 random bytes (0-255) | +| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | + +Example: + +```javascript +import { v4 as uuidv4 } from 'uuid'; + +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +Example using predefined `random` values: + +```javascript +import { v4 as uuidv4 } from 'uuid'; + +const v4options = { + random: [ + 0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea, 0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36, + ], +}; +uuidv4(v4options); // ⇨ '109156be-c4fb-41ea-b1b4-efe1671c5836' +``` + +### uuid.v5(name, namespace[, buffer[, offset]]) + +Create an RFC version 5 (namespace w/ SHA-1) UUID + +| | | +| --- | --- | +| `name` | `String \| Array` | +| `namespace` | `String \| Array[16]` Namespace UUID | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | + +Note: The RFC `DNS` and `URL` namespaces are available as `v5.DNS` and `v5.URL`. + +Example with custom namespace: + +```javascript +import { v5 as uuidv5 } from 'uuid'; + +// Define a custom namespace. Readers, create your own using something like +// https://www.uuidgenerator.net/ +const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; + +uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681' +``` + +Example with RFC `URL` namespace: + +```javascript +import { v5 as uuidv5 } from 'uuid'; + +uuidv5('https://www.w3.org/', uuidv5.URL); // ⇨ 'c106a26a-21bb-5538-8bf2-57095d1976c1' +``` + +### uuid.validate(str) + +Test a string to see if it is a valid UUID + +| | | +| --------- | --------------------------------------------------- | +| `str` | `String` to validate | +| _returns_ | `true` if string is a valid UUID, `false` otherwise | + +Example: + +```javascript +import { validate as uuidValidate } from 'uuid'; + +uuidValidate('not a UUID'); // ⇨ false +uuidValidate('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ true +``` + +Using `validate` and `version` together it is possible to do per-version validation, e.g. validate for only v4 UUIds. + +```javascript +import { version as uuidVersion } from 'uuid'; +import { validate as uuidValidate } from 'uuid'; + +function uuidValidateV4(uuid) { + return uuidValidate(uuid) && uuidVersion(uuid) === 4; +} + +const v1Uuid = 'd9428888-122b-11e1-b85c-61cd3cbb3210'; +const v4Uuid = '109156be-c4fb-41ea-b1b4-efe1671c5836'; + +uuidValidateV4(v4Uuid); // ⇨ true +uuidValidateV4(v1Uuid); // ⇨ false +``` + +### uuid.version(str) + +Detect RFC version of a UUID + +| | | +| --------- | ---------------------------------------- | +| `str` | A valid UUID `String` | +| _returns_ | `Number` The RFC version of the UUID | +| _throws_ | `TypeError` if `str` is not a valid UUID | + +Example: + +```javascript +import { version as uuidVersion } from 'uuid'; + +uuidVersion('45637ec4-c85f-11ea-87d0-0242ac130003'); // ⇨ 1 +uuidVersion('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ 4 +``` + +## Command Line + +UUIDs can be generated from the command line using `uuid`. + +```shell +$ npx uuid +ddeb27fb-d9a0-4624-be4d-4615062daed4 +``` + +The default is to generate version 4 UUIDS, however the other versions are supported. Type `uuid --help` for details: + +```shell +$ npx uuid --help + +Usage: + uuid + uuid v1 + uuid v3 + uuid v4 + uuid v5 + uuid --help + +Note: may be "URL" or "DNS" to use the corresponding UUIDs +defined by RFC4122 +``` + +## ECMAScript Modules + +This library comes with [ECMAScript Modules](https://www.ecma-international.org/ecma-262/6.0/#sec-modules) (ESM) support for Node.js versions that support it ([example](./examples/node-esmodules/)) as well as bundlers like [rollup.js](https://rollupjs.org/guide/en/#tree-shaking) ([example](./examples/browser-rollup/)) and [webpack](https://webpack.js.org/guides/tree-shaking/) ([example](./examples/browser-webpack/)) (targeting both, Node.js and browser environments). + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +To run the examples you must first create a dist build of this library in the module root: + +```shell +npm run build +``` + +## CDN Builds + +### ECMAScript Modules + +To load this module directly into modern browsers that [support loading ECMAScript Modules](https://caniuse.com/#feat=es6-module) you can make use of [jspm](https://jspm.org/): + +```html + +``` + +### UMD + +As of `uuid@9` [UMD (Universal Module Definition)](https://github.com/umdjs/umd) builds are no longer shipped with this library. + +If you need a UMD build of this library, use a bundler like Webpack or Rollup. Alternatively, refer to the documentation of [`uuid@8.3.2`](https://github.com/uuidjs/uuid/blob/v8.3.2/README.md#umd) which was the last version that shipped UMD builds. + +## Known issues + +### Duplicate UUIDs (Googlebot) + +This module may generate duplicate UUIDs when run in clients with _deterministic_ random number generators, such as [Googlebot crawlers](https://developers.google.com/search/docs/advanced/crawling/overview-google-crawlers). This can cause problems for apps that expect client-generated UUIDs to always be unique. Developers should be prepared for this and have a strategy for dealing with possible collisions, such as: + +- Check for duplicate UUIDs, fail gracefully +- Disable write operations for Googlebot clients + +### "getRandomValues() not supported" + +This error occurs in environments where the standard [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) API is not supported. This issue can be resolved by adding an appropriate polyfill: + +### React Native / Expo + +1. Install [`react-native-get-random-values`](https://github.com/LinusU/react-native-get-random-values#readme) +1. Import it _before_ `uuid`. Since `uuid` might also appear as a transitive dependency of some other imports it's safest to just import `react-native-get-random-values` as the very first thing in your entry point: + +```javascript +import 'react-native-get-random-values'; +import { v4 as uuidv4 } from 'uuid'; +``` + +Note: If you are using Expo, you must be using at least `react-native-get-random-values@1.5.0` and `expo@39.0.0`. + +### Web Workers / Service Workers (Edge <= 18) + +[In Edge <= 18, Web Crypto is not supported in Web Workers or Service Workers](https://caniuse.com/#feat=cryptography) and we are not aware of a polyfill (let us know if you find one, please). + +### IE 11 (Internet Explorer) + +Support for IE11 and other legacy browsers has been dropped as of `uuid@9`. If you need to support legacy browsers, you can always transpile the uuid module source yourself (e.g. using [Babel](https://babeljs.io/)). + +## Upgrading From `uuid@7` + +### Only Named Exports Supported When Using with Node.js ESM + +`uuid@7` did not come with native ECMAScript Module (ESM) support for Node.js. Importing it in Node.js ESM consequently imported the CommonJS source with a default export. This library now comes with true Node.js ESM support and only provides named exports. + +Instead of doing: + +```javascript +import uuid from 'uuid'; +uuid.v4(); +``` + +you will now have to use the named exports: + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); +``` + +### Deep Requires No Longer Supported + +Deep requires like `require('uuid/v4')` [which have been deprecated in `uuid@7`](#deep-requires-now-deprecated) are no longer supported. + +## Upgrading From `uuid@3` + +"_Wait... what happened to `uuid@4` thru `uuid@6`?!?_" + +In order to avoid confusion with RFC [version 4](#uuidv4options-buffer-offset) and [version 5](#uuidv5name-namespace-buffer-offset) UUIDs, and a possible [version 6](http://gh.peabody.io/uuidv6/), releases 4 thru 6 of this module have been skipped. + +### Deep Requires Now Deprecated + +`uuid@3` encouraged the use of deep requires to minimize the bundle size of browser builds: + +```javascript +const uuidv4 = require('uuid/v4'); // <== NOW DEPRECATED! +uuidv4(); +``` + +As of `uuid@7` this library now provides ECMAScript modules builds, which allow packagers like Webpack and Rollup to do "tree-shaking" to remove dead code. Instead, use the `import` syntax: + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); +``` + +... or for CommonJS: + +```javascript +const { v4: uuidv4 } = require('uuid'); +uuidv4(); +``` + +### Default Export Removed + +`uuid@3` was exporting the Version 4 UUID method as a default export: + +```javascript +const uuid = require('uuid'); // <== REMOVED! +``` + +This usage pattern was already discouraged in `uuid@3` and has been removed in `uuid@7`. + +--- + +Markdown generated from [README_js.md](README_js.md) by diff --git a/node_modules/gaxios/node_modules/uuid/dist/bin/uuid b/node_modules/gaxios/node_modules/uuid/dist/bin/uuid new file mode 100644 index 0000000..f38d2ee --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/bin/uuid @@ -0,0 +1,2 @@ +#!/usr/bin/env node +require('../uuid-bin'); diff --git a/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/index.js b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/index.js new file mode 100644 index 0000000..5586dd3 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/index.js @@ -0,0 +1,79 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "NIL", { + enumerable: true, + get: function get() { + return _nil.default; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function get() { + return _parse.default; + } +}); +Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function get() { + return _stringify.default; + } +}); +Object.defineProperty(exports, "v1", { + enumerable: true, + get: function get() { + return _v.default; + } +}); +Object.defineProperty(exports, "v3", { + enumerable: true, + get: function get() { + return _v2.default; + } +}); +Object.defineProperty(exports, "v4", { + enumerable: true, + get: function get() { + return _v3.default; + } +}); +Object.defineProperty(exports, "v5", { + enumerable: true, + get: function get() { + return _v4.default; + } +}); +Object.defineProperty(exports, "validate", { + enumerable: true, + get: function get() { + return _validate.default; + } +}); +Object.defineProperty(exports, "version", { + enumerable: true, + get: function get() { + return _version.default; + } +}); + +var _v = _interopRequireDefault(require("./v1.js")); + +var _v2 = _interopRequireDefault(require("./v3.js")); + +var _v3 = _interopRequireDefault(require("./v4.js")); + +var _v4 = _interopRequireDefault(require("./v5.js")); + +var _nil = _interopRequireDefault(require("./nil.js")); + +var _version = _interopRequireDefault(require("./version.js")); + +var _validate = _interopRequireDefault(require("./validate.js")); + +var _stringify = _interopRequireDefault(require("./stringify.js")); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/md5.js b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/md5.js new file mode 100644 index 0000000..7a4582a --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/md5.js @@ -0,0 +1,223 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Uint8Array(msg.length); + + for (let i = 0; i < msg.length; ++i) { + bytes[i] = msg.charCodeAt(i); + } + } + + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); +} +/* + * Convert an array of little-endian words to an array of bytes + */ + + +function md5ToHexEncodedArray(input) { + const output = []; + const length32 = input.length * 32; + const hexTab = '0123456789abcdef'; + + for (let i = 0; i < length32; i += 8) { + const x = input[i >> 5] >>> i % 32 & 0xff; + const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); + } + + return output; +} +/** + * Calculate output length with padding and bit length + */ + + +function getOutputLength(inputLength8) { + return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; +} +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + + +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[getOutputLength(len) - 1] = len; + let a = 1732584193; + let b = -271733879; + let c = -1732584194; + let d = 271733878; + + for (let i = 0; i < x.length; i += 16) { + const olda = a; + const oldb = b; + const oldc = c; + const oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; +} +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + + +function bytesToWords(input) { + if (input.length === 0) { + return []; + } + + const length8 = input.length * 8; + const output = new Uint32Array(getOutputLength(length8)); + + for (let i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } + + return output; +} +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + + +function safeAdd(x, y) { + const lsw = (x & 0xffff) + (y & 0xffff); + const msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; +} +/* + * Bitwise rotate a 32-bit number to the left. + */ + + +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; +} +/* + * These functions implement the four basic operations the algorithm uses. + */ + + +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} + +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); +} + +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); +} + +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} + +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} + +var _default = md5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/native.js b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/native.js new file mode 100644 index 0000000..c2eea59 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/native.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); +var _default = { + randomUUID +}; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/nil.js b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/nil.js new file mode 100644 index 0000000..7ade577 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/nil.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = '00000000-0000-0000-0000-000000000000'; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/parse.js b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/parse.js new file mode 100644 index 0000000..4c69fc3 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/parse.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +var _default = parse; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/regex.js b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/regex.js new file mode 100644 index 0000000..1ef91d6 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/regex.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/rng.js b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/rng.js new file mode 100644 index 0000000..d067cdb --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/rng.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rng; +// Unique ID creation requires a high quality random # generator. In the browser we therefore +// require the crypto API and do not support built-in fallback to lower quality random number +// generators (like Math.random()). +let getRandomValues; +const rnds8 = new Uint8Array(16); + +function rng() { + // lazy load so that environments that need to polyfill have a chance to do so + if (!getRandomValues) { + // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. + 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); +} \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/sha1.js b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/sha1.js new file mode 100644 index 0000000..24cbced --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/sha1.js @@ -0,0 +1,104 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + + case 1: + return x ^ y ^ z; + + case 2: + return x & y ^ x & z ^ y & z; + + case 3: + return x ^ y ^ z; + } +} + +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} + +function sha1(bytes) { + const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = []; + + for (let i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + // Convert Array-like to Array + bytes = Array.prototype.slice.call(bytes); + } + + bytes.push(0x80); + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + + for (let i = 0; i < N; ++i) { + const arr = new Uint32Array(16); + + for (let j = 0; j < 16; ++j) { + arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + } + + M[i] = arr; + } + + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; + + for (let i = 0; i < N; ++i) { + const W = new Uint32Array(80); + + for (let t = 0; t < 16; ++t) { + W[t] = M[i][t]; + } + + for (let t = 16; t < 80; ++t) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } + + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; +} + +var _default = sha1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/stringify.js b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/stringify.js new file mode 100644 index 0000000..390bf89 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/stringify.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +exports.unsafeStringify = unsafeStringify; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} + +function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; +} + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!(0, _validate.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +var _default = stringify; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/v1.js b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/v1.js new file mode 100644 index 0000000..125bc58 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/v1.js @@ -0,0 +1,107 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = require("./stringify.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || _rng.default)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || (0, _stringify.unsafeStringify)(b); +} + +var _default = v1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/v3.js b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/v3.js new file mode 100644 index 0000000..6b47ff5 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/v3.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _md = _interopRequireDefault(require("./md5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/v35.js b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/v35.js new file mode 100644 index 0000000..7c522d9 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/v35.js @@ -0,0 +1,80 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.URL = exports.DNS = void 0; +exports.default = v35; + +var _stringify = require("./stringify.js"); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.DNS = DNS; +const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = URL; + +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 = (0, _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)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return (0, _stringify.unsafeStringify)(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/v4.js b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/v4.js new file mode 100644 index 0000000..959d698 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/v4.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _native = _interopRequireDefault(require("./native.js")); + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = require("./stringify.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function v4(options, buf, offset) { + if (_native.default.randomUUID && !buf && !options) { + return _native.default.randomUUID(); + } + + options = options || {}; + + const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return (0, _stringify.unsafeStringify)(rnds); +} + +var _default = v4; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/v5.js b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/v5.js new file mode 100644 index 0000000..99d615e --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/v5.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _sha = _interopRequireDefault(require("./sha1.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/validate.js b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/validate.js new file mode 100644 index 0000000..fd05215 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/validate.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _regex = _interopRequireDefault(require("./regex.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function validate(uuid) { + return typeof uuid === 'string' && _regex.default.test(uuid); +} + +var _default = validate; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/version.js b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/version.js new file mode 100644 index 0000000..f63af01 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/commonjs-browser/version.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function version(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.slice(14, 15), 16); +} + +var _default = version; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-browser/index.js b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/index.js new file mode 100644 index 0000000..1db6f6d --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/index.js @@ -0,0 +1,9 @@ +export { default as v1 } from './v1.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as NIL } from './nil.js'; +export { default as version } from './version.js'; +export { default as validate } from './validate.js'; +export { default as stringify } from './stringify.js'; +export { default as parse } from './parse.js'; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-browser/md5.js b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/md5.js new file mode 100644 index 0000000..f12212e --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/md5.js @@ -0,0 +1,215 @@ +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Uint8Array(msg.length); + + for (let i = 0; i < msg.length; ++i) { + bytes[i] = msg.charCodeAt(i); + } + } + + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); +} +/* + * Convert an array of little-endian words to an array of bytes + */ + + +function md5ToHexEncodedArray(input) { + const output = []; + const length32 = input.length * 32; + const hexTab = '0123456789abcdef'; + + for (let i = 0; i < length32; i += 8) { + const x = input[i >> 5] >>> i % 32 & 0xff; + const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); + } + + return output; +} +/** + * Calculate output length with padding and bit length + */ + + +function getOutputLength(inputLength8) { + return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; +} +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + + +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[getOutputLength(len) - 1] = len; + let a = 1732584193; + let b = -271733879; + let c = -1732584194; + let d = 271733878; + + for (let i = 0; i < x.length; i += 16) { + const olda = a; + const oldb = b; + const oldc = c; + const oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; +} +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + + +function bytesToWords(input) { + if (input.length === 0) { + return []; + } + + const length8 = input.length * 8; + const output = new Uint32Array(getOutputLength(length8)); + + for (let i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } + + return output; +} +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + + +function safeAdd(x, y) { + const lsw = (x & 0xffff) + (y & 0xffff); + const msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; +} +/* + * Bitwise rotate a 32-bit number to the left. + */ + + +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; +} +/* + * These functions implement the four basic operations the algorithm uses. + */ + + +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} + +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); +} + +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); +} + +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} + +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} + +export default md5; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-browser/native.js b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/native.js new file mode 100644 index 0000000..b22292c --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/native.js @@ -0,0 +1,4 @@ +const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); +export default { + randomUUID +}; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-browser/nil.js b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/nil.js new file mode 100644 index 0000000..b36324c --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/nil.js @@ -0,0 +1 @@ +export default '00000000-0000-0000-0000-000000000000'; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-browser/parse.js b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/parse.js new file mode 100644 index 0000000..6421c5d --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/parse.js @@ -0,0 +1,35 @@ +import validate from './validate.js'; + +function parse(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +export default parse; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-browser/regex.js b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/regex.js new file mode 100644 index 0000000..3da8673 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/regex.js @@ -0,0 +1 @@ +export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-browser/rng.js b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/rng.js new file mode 100644 index 0000000..6e65234 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/rng.js @@ -0,0 +1,18 @@ +// Unique ID creation requires a high quality random # generator. In the browser we therefore +// require the crypto API and do not support built-in fallback to lower quality random number +// generators (like Math.random()). +let getRandomValues; +const rnds8 = new Uint8Array(16); +export default function rng() { + // lazy load so that environments that need to polyfill have a chance to do so + if (!getRandomValues) { + // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. + 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); +} \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-browser/sha1.js b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/sha1.js new file mode 100644 index 0000000..d3c2565 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/sha1.js @@ -0,0 +1,96 @@ +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + + case 1: + return x ^ y ^ z; + + case 2: + return x & y ^ x & z ^ y & z; + + case 3: + return x ^ y ^ z; + } +} + +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} + +function sha1(bytes) { + const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = []; + + for (let i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + // Convert Array-like to Array + bytes = Array.prototype.slice.call(bytes); + } + + bytes.push(0x80); + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + + for (let i = 0; i < N; ++i) { + const arr = new Uint32Array(16); + + for (let j = 0; j < 16; ++j) { + arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + } + + M[i] = arr; + } + + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; + + for (let i = 0; i < N; ++i) { + const W = new Uint32Array(80); + + for (let t = 0; t < 16; ++t) { + W[t] = M[i][t]; + } + + for (let t = 16; t < 80; ++t) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } + + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; +} + +export default sha1; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-browser/stringify.js b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/stringify.js new file mode 100644 index 0000000..a6e4c88 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/stringify.js @@ -0,0 +1,33 @@ +import validate from './validate.js'; +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ + +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} + +export function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; +} + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!validate(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +export default stringify; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-browser/v1.js b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/v1.js new file mode 100644 index 0000000..382e5d7 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/v1.js @@ -0,0 +1,95 @@ +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; // **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || rng)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || unsafeStringify(b); +} + +export default v1; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-browser/v3.js b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/v3.js new file mode 100644 index 0000000..09063b8 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/v3.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import md5 from './md5.js'; +const v3 = v35('v3', 0x30, md5); +export default v3; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-browser/v35.js b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/v35.js new file mode 100644 index 0000000..3355e1f --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/v35.js @@ -0,0 +1,66 @@ +import { unsafeStringify } from './stringify.js'; +import parse from './parse.js'; + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +export const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +export const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +export default 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(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)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return unsafeStringify(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-browser/v4.js b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/v4.js new file mode 100644 index 0000000..95ea879 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/v4.js @@ -0,0 +1,29 @@ +import native from './native.js'; +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; + +function v4(options, buf, offset) { + if (native.randomUUID && !buf && !options) { + return native.randomUUID(); + } + + options = options || {}; + const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return unsafeStringify(rnds); +} + +export default v4; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-browser/v5.js b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/v5.js new file mode 100644 index 0000000..e87fe31 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/v5.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import sha1 from './sha1.js'; +const v5 = v35('v5', 0x50, sha1); +export default v5; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-browser/validate.js b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/validate.js new file mode 100644 index 0000000..f1cdc7a --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/validate.js @@ -0,0 +1,7 @@ +import REGEX from './regex.js'; + +function validate(uuid) { + return typeof uuid === 'string' && REGEX.test(uuid); +} + +export default validate; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-browser/version.js b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/version.js new file mode 100644 index 0000000..9363076 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-browser/version.js @@ -0,0 +1,11 @@ +import validate from './validate.js'; + +function version(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.slice(14, 15), 16); +} + +export default version; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-node/index.js b/node_modules/gaxios/node_modules/uuid/dist/esm-node/index.js new file mode 100644 index 0000000..1db6f6d --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-node/index.js @@ -0,0 +1,9 @@ +export { default as v1 } from './v1.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as NIL } from './nil.js'; +export { default as version } from './version.js'; +export { default as validate } from './validate.js'; +export { default as stringify } from './stringify.js'; +export { default as parse } from './parse.js'; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-node/md5.js b/node_modules/gaxios/node_modules/uuid/dist/esm-node/md5.js new file mode 100644 index 0000000..4d68b04 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-node/md5.js @@ -0,0 +1,13 @@ +import crypto from 'crypto'; + +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return crypto.createHash('md5').update(bytes).digest(); +} + +export default md5; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-node/native.js b/node_modules/gaxios/node_modules/uuid/dist/esm-node/native.js new file mode 100644 index 0000000..f0d1992 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-node/native.js @@ -0,0 +1,4 @@ +import crypto from 'crypto'; +export default { + randomUUID: crypto.randomUUID +}; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-node/nil.js b/node_modules/gaxios/node_modules/uuid/dist/esm-node/nil.js new file mode 100644 index 0000000..b36324c --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-node/nil.js @@ -0,0 +1 @@ +export default '00000000-0000-0000-0000-000000000000'; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-node/parse.js b/node_modules/gaxios/node_modules/uuid/dist/esm-node/parse.js new file mode 100644 index 0000000..6421c5d --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-node/parse.js @@ -0,0 +1,35 @@ +import validate from './validate.js'; + +function parse(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +export default parse; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-node/regex.js b/node_modules/gaxios/node_modules/uuid/dist/esm-node/regex.js new file mode 100644 index 0000000..3da8673 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-node/regex.js @@ -0,0 +1 @@ +export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-node/rng.js b/node_modules/gaxios/node_modules/uuid/dist/esm-node/rng.js new file mode 100644 index 0000000..8006244 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-node/rng.js @@ -0,0 +1,12 @@ +import crypto from 'crypto'; +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate + +let poolPtr = rnds8Pool.length; +export default function rng() { + if (poolPtr > rnds8Pool.length - 16) { + crypto.randomFillSync(rnds8Pool); + poolPtr = 0; + } + + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-node/sha1.js b/node_modules/gaxios/node_modules/uuid/dist/esm-node/sha1.js new file mode 100644 index 0000000..e23850b --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-node/sha1.js @@ -0,0 +1,13 @@ +import crypto from 'crypto'; + +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return crypto.createHash('sha1').update(bytes).digest(); +} + +export default sha1; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-node/stringify.js b/node_modules/gaxios/node_modules/uuid/dist/esm-node/stringify.js new file mode 100644 index 0000000..a6e4c88 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-node/stringify.js @@ -0,0 +1,33 @@ +import validate from './validate.js'; +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ + +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} + +export function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; +} + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!validate(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +export default stringify; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-node/v1.js b/node_modules/gaxios/node_modules/uuid/dist/esm-node/v1.js new file mode 100644 index 0000000..382e5d7 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-node/v1.js @@ -0,0 +1,95 @@ +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; // **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || rng)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || unsafeStringify(b); +} + +export default v1; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-node/v3.js b/node_modules/gaxios/node_modules/uuid/dist/esm-node/v3.js new file mode 100644 index 0000000..09063b8 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-node/v3.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import md5 from './md5.js'; +const v3 = v35('v3', 0x30, md5); +export default v3; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-node/v35.js b/node_modules/gaxios/node_modules/uuid/dist/esm-node/v35.js new file mode 100644 index 0000000..3355e1f --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-node/v35.js @@ -0,0 +1,66 @@ +import { unsafeStringify } from './stringify.js'; +import parse from './parse.js'; + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +export const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +export const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +export default 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(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)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return unsafeStringify(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-node/v4.js b/node_modules/gaxios/node_modules/uuid/dist/esm-node/v4.js new file mode 100644 index 0000000..95ea879 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-node/v4.js @@ -0,0 +1,29 @@ +import native from './native.js'; +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; + +function v4(options, buf, offset) { + if (native.randomUUID && !buf && !options) { + return native.randomUUID(); + } + + options = options || {}; + const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return unsafeStringify(rnds); +} + +export default v4; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-node/v5.js b/node_modules/gaxios/node_modules/uuid/dist/esm-node/v5.js new file mode 100644 index 0000000..e87fe31 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-node/v5.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import sha1 from './sha1.js'; +const v5 = v35('v5', 0x50, sha1); +export default v5; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-node/validate.js b/node_modules/gaxios/node_modules/uuid/dist/esm-node/validate.js new file mode 100644 index 0000000..f1cdc7a --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-node/validate.js @@ -0,0 +1,7 @@ +import REGEX from './regex.js'; + +function validate(uuid) { + return typeof uuid === 'string' && REGEX.test(uuid); +} + +export default validate; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/esm-node/version.js b/node_modules/gaxios/node_modules/uuid/dist/esm-node/version.js new file mode 100644 index 0000000..9363076 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/esm-node/version.js @@ -0,0 +1,11 @@ +import validate from './validate.js'; + +function version(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.slice(14, 15), 16); +} + +export default version; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/index.js b/node_modules/gaxios/node_modules/uuid/dist/index.js new file mode 100644 index 0000000..88d676a --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/index.js @@ -0,0 +1,79 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "NIL", { + enumerable: true, + get: function () { + return _nil.default; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function () { + return _parse.default; + } +}); +Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function () { + return _stringify.default; + } +}); +Object.defineProperty(exports, "v1", { + enumerable: true, + get: function () { + return _v.default; + } +}); +Object.defineProperty(exports, "v3", { + enumerable: true, + get: function () { + return _v2.default; + } +}); +Object.defineProperty(exports, "v4", { + enumerable: true, + get: function () { + return _v3.default; + } +}); +Object.defineProperty(exports, "v5", { + enumerable: true, + get: function () { + return _v4.default; + } +}); +Object.defineProperty(exports, "validate", { + enumerable: true, + get: function () { + return _validate.default; + } +}); +Object.defineProperty(exports, "version", { + enumerable: true, + get: function () { + return _version.default; + } +}); + +var _v = _interopRequireDefault(require("./v1.js")); + +var _v2 = _interopRequireDefault(require("./v3.js")); + +var _v3 = _interopRequireDefault(require("./v4.js")); + +var _v4 = _interopRequireDefault(require("./v5.js")); + +var _nil = _interopRequireDefault(require("./nil.js")); + +var _version = _interopRequireDefault(require("./version.js")); + +var _validate = _interopRequireDefault(require("./validate.js")); + +var _stringify = _interopRequireDefault(require("./stringify.js")); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/md5-browser.js b/node_modules/gaxios/node_modules/uuid/dist/md5-browser.js new file mode 100644 index 0000000..7a4582a --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/md5-browser.js @@ -0,0 +1,223 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Uint8Array(msg.length); + + for (let i = 0; i < msg.length; ++i) { + bytes[i] = msg.charCodeAt(i); + } + } + + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); +} +/* + * Convert an array of little-endian words to an array of bytes + */ + + +function md5ToHexEncodedArray(input) { + const output = []; + const length32 = input.length * 32; + const hexTab = '0123456789abcdef'; + + for (let i = 0; i < length32; i += 8) { + const x = input[i >> 5] >>> i % 32 & 0xff; + const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); + } + + return output; +} +/** + * Calculate output length with padding and bit length + */ + + +function getOutputLength(inputLength8) { + return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; +} +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + + +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[getOutputLength(len) - 1] = len; + let a = 1732584193; + let b = -271733879; + let c = -1732584194; + let d = 271733878; + + for (let i = 0; i < x.length; i += 16) { + const olda = a; + const oldb = b; + const oldc = c; + const oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; +} +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + + +function bytesToWords(input) { + if (input.length === 0) { + return []; + } + + const length8 = input.length * 8; + const output = new Uint32Array(getOutputLength(length8)); + + for (let i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } + + return output; +} +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + + +function safeAdd(x, y) { + const lsw = (x & 0xffff) + (y & 0xffff); + const msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; +} +/* + * Bitwise rotate a 32-bit number to the left. + */ + + +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; +} +/* + * These functions implement the four basic operations the algorithm uses. + */ + + +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} + +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); +} + +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); +} + +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} + +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} + +var _default = md5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/md5.js b/node_modules/gaxios/node_modules/uuid/dist/md5.js new file mode 100644 index 0000000..824d481 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/md5.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return _crypto.default.createHash('md5').update(bytes).digest(); +} + +var _default = md5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/native-browser.js b/node_modules/gaxios/node_modules/uuid/dist/native-browser.js new file mode 100644 index 0000000..c2eea59 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/native-browser.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); +var _default = { + randomUUID +}; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/native.js b/node_modules/gaxios/node_modules/uuid/dist/native.js new file mode 100644 index 0000000..de80469 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/native.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var _default = { + randomUUID: _crypto.default.randomUUID +}; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/nil.js b/node_modules/gaxios/node_modules/uuid/dist/nil.js new file mode 100644 index 0000000..7ade577 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/nil.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = '00000000-0000-0000-0000-000000000000'; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/parse.js b/node_modules/gaxios/node_modules/uuid/dist/parse.js new file mode 100644 index 0000000..4c69fc3 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/parse.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +var _default = parse; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/regex.js b/node_modules/gaxios/node_modules/uuid/dist/regex.js new file mode 100644 index 0000000..1ef91d6 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/regex.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/rng-browser.js b/node_modules/gaxios/node_modules/uuid/dist/rng-browser.js new file mode 100644 index 0000000..d067cdb --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/rng-browser.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rng; +// Unique ID creation requires a high quality random # generator. In the browser we therefore +// require the crypto API and do not support built-in fallback to lower quality random number +// generators (like Math.random()). +let getRandomValues; +const rnds8 = new Uint8Array(16); + +function rng() { + // lazy load so that environments that need to polyfill have a chance to do so + if (!getRandomValues) { + // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. + 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); +} \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/rng.js b/node_modules/gaxios/node_modules/uuid/dist/rng.js new file mode 100644 index 0000000..3507f93 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/rng.js @@ -0,0 +1,24 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rng; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate + +let poolPtr = rnds8Pool.length; + +function rng() { + if (poolPtr > rnds8Pool.length - 16) { + _crypto.default.randomFillSync(rnds8Pool); + + poolPtr = 0; + } + + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/sha1-browser.js b/node_modules/gaxios/node_modules/uuid/dist/sha1-browser.js new file mode 100644 index 0000000..24cbced --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/sha1-browser.js @@ -0,0 +1,104 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + + case 1: + return x ^ y ^ z; + + case 2: + return x & y ^ x & z ^ y & z; + + case 3: + return x ^ y ^ z; + } +} + +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} + +function sha1(bytes) { + const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = []; + + for (let i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + // Convert Array-like to Array + bytes = Array.prototype.slice.call(bytes); + } + + bytes.push(0x80); + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + + for (let i = 0; i < N; ++i) { + const arr = new Uint32Array(16); + + for (let j = 0; j < 16; ++j) { + arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + } + + M[i] = arr; + } + + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; + + for (let i = 0; i < N; ++i) { + const W = new Uint32Array(80); + + for (let t = 0; t < 16; ++t) { + W[t] = M[i][t]; + } + + for (let t = 16; t < 80; ++t) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } + + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; +} + +var _default = sha1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/sha1.js b/node_modules/gaxios/node_modules/uuid/dist/sha1.js new file mode 100644 index 0000000..03bdd63 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/sha1.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return _crypto.default.createHash('sha1').update(bytes).digest(); +} + +var _default = sha1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/stringify.js b/node_modules/gaxios/node_modules/uuid/dist/stringify.js new file mode 100644 index 0000000..390bf89 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/stringify.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +exports.unsafeStringify = unsafeStringify; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} + +function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; +} + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!(0, _validate.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +var _default = stringify; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/uuid-bin.js b/node_modules/gaxios/node_modules/uuid/dist/uuid-bin.js new file mode 100644 index 0000000..50a7a9f --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/uuid-bin.js @@ -0,0 +1,85 @@ +"use strict"; + +var _assert = _interopRequireDefault(require("assert")); + +var _v = _interopRequireDefault(require("./v1.js")); + +var _v2 = _interopRequireDefault(require("./v3.js")); + +var _v3 = _interopRequireDefault(require("./v4.js")); + +var _v4 = _interopRequireDefault(require("./v5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function usage() { + console.log('Usage:'); + console.log(' uuid'); + console.log(' uuid v1'); + console.log(' uuid v3 '); + console.log(' uuid v4'); + console.log(' uuid v5 '); + console.log(' uuid --help'); + console.log('\nNote: may be "URL" or "DNS" to use the corresponding UUIDs defined by RFC4122'); +} + +const args = process.argv.slice(2); + +if (args.indexOf('--help') >= 0) { + usage(); + process.exit(0); +} + +const version = args.shift() || 'v4'; + +switch (version) { + case 'v1': + console.log((0, _v.default)()); + break; + + case 'v3': + { + const name = args.shift(); + let namespace = args.shift(); + (0, _assert.default)(name != null, 'v3 name not specified'); + (0, _assert.default)(namespace != null, 'v3 namespace not specified'); + + if (namespace === 'URL') { + namespace = _v2.default.URL; + } + + if (namespace === 'DNS') { + namespace = _v2.default.DNS; + } + + console.log((0, _v2.default)(name, namespace)); + break; + } + + case 'v4': + console.log((0, _v3.default)()); + break; + + case 'v5': + { + const name = args.shift(); + let namespace = args.shift(); + (0, _assert.default)(name != null, 'v5 name not specified'); + (0, _assert.default)(namespace != null, 'v5 namespace not specified'); + + if (namespace === 'URL') { + namespace = _v4.default.URL; + } + + if (namespace === 'DNS') { + namespace = _v4.default.DNS; + } + + console.log((0, _v4.default)(name, namespace)); + break; + } + + default: + usage(); + process.exit(1); +} \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/v1.js b/node_modules/gaxios/node_modules/uuid/dist/v1.js new file mode 100644 index 0000000..125bc58 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/v1.js @@ -0,0 +1,107 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = require("./stringify.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || _rng.default)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || (0, _stringify.unsafeStringify)(b); +} + +var _default = v1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/v3.js b/node_modules/gaxios/node_modules/uuid/dist/v3.js new file mode 100644 index 0000000..6b47ff5 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/v3.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _md = _interopRequireDefault(require("./md5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/v35.js b/node_modules/gaxios/node_modules/uuid/dist/v35.js new file mode 100644 index 0000000..7c522d9 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/v35.js @@ -0,0 +1,80 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.URL = exports.DNS = void 0; +exports.default = v35; + +var _stringify = require("./stringify.js"); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.DNS = DNS; +const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = URL; + +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 = (0, _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)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return (0, _stringify.unsafeStringify)(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/v4.js b/node_modules/gaxios/node_modules/uuid/dist/v4.js new file mode 100644 index 0000000..959d698 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/v4.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _native = _interopRequireDefault(require("./native.js")); + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = require("./stringify.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function v4(options, buf, offset) { + if (_native.default.randomUUID && !buf && !options) { + return _native.default.randomUUID(); + } + + options = options || {}; + + const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return (0, _stringify.unsafeStringify)(rnds); +} + +var _default = v4; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/v5.js b/node_modules/gaxios/node_modules/uuid/dist/v5.js new file mode 100644 index 0000000..99d615e --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/v5.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _sha = _interopRequireDefault(require("./sha1.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/validate.js b/node_modules/gaxios/node_modules/uuid/dist/validate.js new file mode 100644 index 0000000..fd05215 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/validate.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _regex = _interopRequireDefault(require("./regex.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function validate(uuid) { + return typeof uuid === 'string' && _regex.default.test(uuid); +} + +var _default = validate; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/dist/version.js b/node_modules/gaxios/node_modules/uuid/dist/version.js new file mode 100644 index 0000000..f63af01 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/dist/version.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function version(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.slice(14, 15), 16); +} + +var _default = version; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/gaxios/node_modules/uuid/package.json b/node_modules/gaxios/node_modules/uuid/package.json new file mode 100644 index 0000000..6cc3361 --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/package.json @@ -0,0 +1,135 @@ +{ + "name": "uuid", + "version": "9.0.1", + "description": "RFC4122 (v1, v4, and v5) UUIDs", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "commitlint": { + "extends": [ + "@commitlint/config-conventional" + ] + }, + "keywords": [ + "uuid", + "guid", + "rfc4122" + ], + "license": "MIT", + "bin": { + "uuid": "./dist/bin/uuid" + }, + "sideEffects": false, + "main": "./dist/index.js", + "exports": { + ".": { + "node": { + "module": "./dist/esm-node/index.js", + "require": "./dist/index.js", + "import": "./wrapper.mjs" + }, + "browser": { + "import": "./dist/esm-browser/index.js", + "require": "./dist/commonjs-browser/index.js" + }, + "default": "./dist/esm-browser/index.js" + }, + "./package.json": "./package.json" + }, + "module": "./dist/esm-node/index.js", + "browser": { + "./dist/md5.js": "./dist/md5-browser.js", + "./dist/native.js": "./dist/native-browser.js", + "./dist/rng.js": "./dist/rng-browser.js", + "./dist/sha1.js": "./dist/sha1-browser.js", + "./dist/esm-node/index.js": "./dist/esm-browser/index.js" + }, + "files": [ + "CHANGELOG.md", + "CONTRIBUTING.md", + "LICENSE.md", + "README.md", + "dist", + "wrapper.mjs" + ], + "devDependencies": { + "@babel/cli": "7.18.10", + "@babel/core": "7.18.10", + "@babel/eslint-parser": "7.18.9", + "@babel/preset-env": "7.18.10", + "@commitlint/cli": "17.0.3", + "@commitlint/config-conventional": "17.0.3", + "bundlewatch": "0.3.3", + "eslint": "8.21.0", + "eslint-config-prettier": "8.5.0", + "eslint-config-standard": "17.0.0", + "eslint-plugin-import": "2.26.0", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-prettier": "4.2.1", + "eslint-plugin-promise": "6.0.0", + "husky": "8.0.1", + "jest": "28.1.3", + "lint-staged": "13.0.3", + "npm-run-all": "4.1.5", + "optional-dev-dependency": "2.0.1", + "prettier": "2.7.1", + "random-seed": "0.3.0", + "runmd": "1.3.9", + "standard-version": "9.5.0" + }, + "optionalDevDependencies": { + "@wdio/browserstack-service": "7.16.10", + "@wdio/cli": "7.16.10", + "@wdio/jasmine-framework": "7.16.6", + "@wdio/local-runner": "7.16.10", + "@wdio/spec-reporter": "7.16.9", + "@wdio/static-server-service": "7.16.6" + }, + "scripts": { + "examples:browser:webpack:build": "cd examples/browser-webpack && npm install && npm run build", + "examples:browser:rollup:build": "cd examples/browser-rollup && npm install && npm run build", + "examples:node:commonjs:test": "cd examples/node-commonjs && npm install && npm test", + "examples:node:esmodules:test": "cd examples/node-esmodules && npm install && npm test", + "examples:node:jest:test": "cd examples/node-jest && npm install && npm test", + "prepare": "cd $( git rev-parse --show-toplevel ) && husky install", + "lint": "npm run eslint:check && npm run prettier:check", + "eslint:check": "eslint src/ test/ examples/ *.js", + "eslint:fix": "eslint --fix src/ test/ examples/ *.js", + "pretest": "[ -n $CI ] || npm run build", + "test": "BABEL_ENV=commonjsNode node --throw-deprecation node_modules/.bin/jest test/unit/", + "pretest:browser": "optional-dev-dependency && npm run build && npm-run-all --parallel examples:browser:**", + "test:browser": "wdio run ./wdio.conf.js", + "pretest:node": "npm run build", + "test:node": "npm-run-all --parallel examples:node:**", + "test:pack": "./scripts/testpack.sh", + "pretest:benchmark": "npm run build", + "test:benchmark": "cd examples/benchmark && npm install && npm test", + "prettier:check": "prettier --check '**/*.{js,jsx,json,md}'", + "prettier:fix": "prettier --write '**/*.{js,jsx,json,md}'", + "bundlewatch": "npm run pretest:browser && bundlewatch --config bundlewatch.config.json", + "md": "runmd --watch --output=README.md README_js.md", + "docs": "( node --version | grep -q 'v18' ) && ( npm run build && npx runmd --output=README.md README_js.md )", + "docs:diff": "npm run docs && git diff --quiet README.md", + "build": "./scripts/build.sh", + "prepack": "npm run build", + "release": "standard-version --no-verify" + }, + "repository": { + "type": "git", + "url": "https://github.com/uuidjs/uuid.git" + }, + "lint-staged": { + "*.{js,jsx,json,md}": [ + "prettier --write" + ], + "*.{js,jsx}": [ + "eslint --fix" + ] + }, + "standard-version": { + "scripts": { + "postchangelog": "prettier --write CHANGELOG.md" + } + } +} diff --git a/node_modules/gaxios/node_modules/uuid/wrapper.mjs b/node_modules/gaxios/node_modules/uuid/wrapper.mjs new file mode 100644 index 0000000..c31e9ce --- /dev/null +++ b/node_modules/gaxios/node_modules/uuid/wrapper.mjs @@ -0,0 +1,10 @@ +import uuid from './dist/index.js'; +export const v1 = uuid.v1; +export const v3 = uuid.v3; +export const v4 = uuid.v4; +export const v5 = uuid.v5; +export const NIL = uuid.NIL; +export const version = uuid.version; +export const validate = uuid.validate; +export const stringify = uuid.stringify; +export const parse = uuid.parse; diff --git a/node_modules/gaxios/package.json b/node_modules/gaxios/package.json new file mode 100644 index 0000000..f47ade9 --- /dev/null +++ b/node_modules/gaxios/package.json @@ -0,0 +1,96 @@ +{ + "name": "gaxios", + "version": "6.7.1", + "description": "A simple common HTTP client specifically for Google APIs and services.", + "main": "build/src/index.js", + "types": "build/src/index.d.ts", + "files": [ + "build/src" + ], + "scripts": { + "lint": "gts check", + "test": "c8 mocha build/test", + "presystem-test": "npm run compile", + "system-test": "mocha build/system-test --timeout 80000", + "compile": "tsc -p .", + "fix": "gts fix", + "prepare": "npm run compile", + "pretest": "npm run compile", + "webpack": "webpack", + "prebrowser-test": "npm run compile", + "browser-test": "node build/browser-test/browser-test-runner.js", + "docs": "compodoc src/", + "docs-test": "linkinator docs", + "predocs-test": "npm run docs", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "prelint": "cd samples; npm link ../; npm install", + "clean": "gts clean", + "precompile": "gts clean" + }, + "repository": "googleapis/gaxios", + "keywords": [ + "google" + ], + "engines": { + "node": ">=14" + }, + "author": "Google, LLC", + "license": "Apache-2.0", + "devDependencies": { + "@babel/plugin-proposal-private-methods": "^7.18.6", + "@compodoc/compodoc": "1.1.19", + "@types/cors": "^2.8.6", + "@types/express": "^4.16.1", + "@types/extend": "^3.0.1", + "@types/mocha": "^9.0.0", + "@types/multiparty": "0.0.36", + "@types/mv": "^2.1.0", + "@types/ncp": "^2.0.1", + "@types/node": "^20.0.0", + "@types/node-fetch": "^2.5.7", + "@types/sinon": "^17.0.0", + "@types/tmp": "0.2.6", + "@types/uuid": "^10.0.0", + "abort-controller": "^3.0.0", + "assert": "^2.0.0", + "browserify": "^17.0.0", + "c8": "^8.0.0", + "cheerio": "1.0.0-rc.10", + "cors": "^2.8.5", + "execa": "^5.0.0", + "express": "^4.16.4", + "form-data": "^4.0.0", + "gts": "^5.0.0", + "is-docker": "^2.0.0", + "karma": "^6.0.0", + "karma-chrome-launcher": "^3.0.0", + "karma-coverage": "^2.0.0", + "karma-firefox-launcher": "^2.0.0", + "karma-mocha": "^2.0.0", + "karma-remap-coverage": "^0.1.5", + "karma-sourcemap-loader": "^0.4.0", + "karma-webpack": "5.0.0", + "linkinator": "^3.0.0", + "mocha": "^8.0.0", + "multiparty": "^4.2.1", + "mv": "^2.1.1", + "ncp": "^2.0.0", + "nock": "^13.0.0", + "null-loader": "^4.0.0", + "puppeteer": "^19.0.0", + "sinon": "^18.0.0", + "stream-browserify": "^3.0.0", + "tmp": "0.2.3", + "ts-loader": "^8.0.0", + "typescript": "^5.1.6", + "webpack": "^5.35.0", + "webpack-cli": "^4.0.0" + }, + "dependencies": { + "extend": "^3.0.2", + "https-proxy-agent": "^7.0.1", + "is-stream": "^2.0.0", + "node-fetch": "^2.6.9", + "uuid": "^9.0.1" + } +} diff --git a/node_modules/gcp-metadata/CHANGELOG.md b/node_modules/gcp-metadata/CHANGELOG.md new file mode 100644 index 0000000..c82697f --- /dev/null +++ b/node_modules/gcp-metadata/CHANGELOG.md @@ -0,0 +1,463 @@ +# Changelog + +[npm history][1] + +[1]: https://www.npmjs.com/package/gcp-metadata?activeTab=versions + +## [6.1.1](https://github.com/googleapis/gcp-metadata/compare/v6.1.0...v6.1.1) (2025-01-30) + + +### Bug Fixes + +* Add extra logging for incorrect headers ([#637](https://github.com/googleapis/gcp-metadata/issues/637)) ([edafa87](https://github.com/googleapis/gcp-metadata/commit/edafa87e020ffe28983048de5da183ceb0483bfa)) +* Add extra logging for incorrect headers ([#637](https://github.com/googleapis/gcp-metadata/issues/637)) ([#647](https://github.com/googleapis/gcp-metadata/issues/647)) ([ccbb98e](https://github.com/googleapis/gcp-metadata/commit/ccbb98e3519496414ab654769072d3397153b4b2)) + +## [6.1.0](https://github.com/googleapis/gcp-metadata/compare/v6.0.0...v6.1.0) (2023-11-10) + + +### Features + +* Add `universe` metadata handler ([#596](https://github.com/googleapis/gcp-metadata/issues/596)) ([0c02016](https://github.com/googleapis/gcp-metadata/commit/0c02016756754cddde6c4402fac1ceb6a318e82d)) +* Bulk Metadata Requests ([#598](https://github.com/googleapis/gcp-metadata/issues/598)) ([0a51378](https://github.com/googleapis/gcp-metadata/commit/0a513788537173570f9910d368dd36717de7233b)) + + +### Bug Fixes + +* Repo Metadata ([#595](https://github.com/googleapis/gcp-metadata/issues/595)) ([470a872](https://github.com/googleapis/gcp-metadata/commit/470a8722df2b2fb2da1b076b73414d2e28a3ff4e)) + +## [6.0.0](https://github.com/googleapis/gcp-metadata/compare/v5.3.0...v6.0.0) (2023-07-17) + + +### ⚠ BREAKING CHANGES + +* upgrade to Node 14, and update gaxios, ts, and gts ([#571](https://github.com/googleapis/gcp-metadata/issues/571)) + +### Miscellaneous Chores + +* Upgrade to Node 14, and update gaxios, ts, and gts ([#571](https://github.com/googleapis/gcp-metadata/issues/571)) ([88ff3ff](https://github.com/googleapis/gcp-metadata/commit/88ff3ff3d9bd8be32126e7fe76cbf33e401f8db7)) + +## [5.3.0](https://github.com/googleapis/gcp-metadata/compare/v5.2.0...v5.3.0) (2023-06-28) + + +### Features + +* Metadata Server Detection Configuration ([#562](https://github.com/googleapis/gcp-metadata/issues/562)) ([8c7c715](https://github.com/googleapis/gcp-metadata/commit/8c7c715f1fc22ad65554a745a93915713ca6698f)) + +## [5.2.0](https://github.com/googleapis/gcp-metadata/compare/v5.1.0...v5.2.0) (2023-01-03) + + +### Features + +* Export `gcp-residency` tools ([#552](https://github.com/googleapis/gcp-metadata/issues/552)) ([ba9ae24](https://github.com/googleapis/gcp-metadata/commit/ba9ae24331b53199f81e97b6a88414050cfcf546)) + +## [5.1.0](https://github.com/googleapis/gcp-metadata/compare/v5.0.1...v5.1.0) (2022-12-07) + + +### Features + +* Extend GCP Residency Detection Support ([#528](https://github.com/googleapis/gcp-metadata/issues/528)) ([2b35bb0](https://github.com/googleapis/gcp-metadata/commit/2b35bb0e6fb1a18294aeeebba91a6bf7b400385a)) + +## [5.0.1](https://github.com/googleapis/gcp-metadata/compare/v5.0.0...v5.0.1) (2022-09-09) + + +### Bug Fixes + +* Remove pip install statements ([#1546](https://github.com/googleapis/gcp-metadata/issues/1546)) ([#529](https://github.com/googleapis/gcp-metadata/issues/529)) ([064c64c](https://github.com/googleapis/gcp-metadata/commit/064c64cec160ffe645e6946a5125960e3e269d7f)) + +## [5.0.0](https://github.com/googleapis/gcp-metadata/compare/v4.3.1...v5.0.0) (2022-04-22) + + +### ⚠ BREAKING CHANGES + +* drop node 10, update typescript to 4.6.3 (#519) + +### Build System + +* drop node 10, update typescript to 4.6.3 ([#519](https://github.com/googleapis/gcp-metadata/issues/519)) ([688749b](https://github.com/googleapis/gcp-metadata/commit/688749bc50407f3cd127a0b10ae09487d6fe5aea)) + +### [4.3.1](https://www.github.com/googleapis/gcp-metadata/compare/v4.3.0...v4.3.1) (2021-09-02) + + +### Bug Fixes + +* **build:** switch primary branch to main ([#481](https://www.github.com/googleapis/gcp-metadata/issues/481)) ([8a7965c](https://www.github.com/googleapis/gcp-metadata/commit/8a7965c47c077ef766e4b416358630c0b24b0af2)) + +## [4.3.0](https://www.github.com/googleapis/gcp-metadata/compare/v4.2.1...v4.3.0) (2021-06-10) + + +### Features + +* add `gcf-owl-bot[bot]` to `ignoreAuthors` ([#450](https://www.github.com/googleapis/gcp-metadata/issues/450)) ([6a0f9ad](https://www.github.com/googleapis/gcp-metadata/commit/6a0f9ad09b6d16370d08c5d60541ce3ef64a9f97)) + +### [4.2.1](https://www.github.com/googleapis/gcp-metadata/compare/v4.2.0...v4.2.1) (2020-10-29) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v4 ([#420](https://www.github.com/googleapis/gcp-metadata/issues/420)) ([b99fb07](https://www.github.com/googleapis/gcp-metadata/commit/b99fb0764b8dbb8b083f73b8007816914db4f09a)) + +## [4.2.0](https://www.github.com/googleapis/gcp-metadata/compare/v4.1.4...v4.2.0) (2020-09-15) + + +### Features + +* add support for GCE_METADATA_HOST environment variable ([#406](https://www.github.com/googleapis/gcp-metadata/issues/406)) ([eaf128a](https://www.github.com/googleapis/gcp-metadata/commit/eaf128ad5afc4357cde72d19b017b9474c070fea)) + +### [4.1.4](https://www.github.com/googleapis/gcp-metadata/compare/v4.1.3...v4.1.4) (2020-07-15) + + +### Bug Fixes + +* **deps:** update dependency json-bigint to v1 ([#382](https://www.github.com/googleapis/gcp-metadata/issues/382)) ([ab4d8c3](https://www.github.com/googleapis/gcp-metadata/commit/ab4d8c3022903206d433bafc47c27815c6f85e36)) + +### [4.1.3](https://www.github.com/googleapis/gcp-metadata/compare/v4.1.2...v4.1.3) (2020-07-13) + + +### Bug Fixes + +* **deps:** update dependency json-bigint to ^0.4.0 ([#378](https://www.github.com/googleapis/gcp-metadata/issues/378)) ([b214280](https://www.github.com/googleapis/gcp-metadata/commit/b2142807928c8c032509277900d35fccd1023f0f)) + +### [4.1.2](https://www.github.com/googleapis/gcp-metadata/compare/v4.1.1...v4.1.2) (2020-07-10) + + +### Bug Fixes + +* **deps:** roll back dependency gcp-metadata to ^4.1.0 ([#373](https://www.github.com/googleapis/gcp-metadata/issues/373)) ([a45adef](https://www.github.com/googleapis/gcp-metadata/commit/a45adefd92418faa08c8a5014cedb844d1eb3ae6)) + +### [4.1.1](https://www.github.com/googleapis/gcp-metadata/compare/v4.1.0...v4.1.1) (2020-07-09) + + +### Bug Fixes + +* typeo in nodejs .gitattribute ([#371](https://www.github.com/googleapis/gcp-metadata/issues/371)) ([5b4bb1c](https://www.github.com/googleapis/gcp-metadata/commit/5b4bb1c85e67e3ef0a6d1ec2ea316d560e03092f)) + +## [4.1.0](https://www.github.com/googleapis/gcp-metadata/compare/v4.0.1...v4.1.0) (2020-05-05) + + +### Features + +* Introduces the GCE_METADATA_IP to allow using a different IP address for the GCE metadata server. ([#346](https://www.github.com/googleapis/gcp-metadata/issues/346)) ([ec0f82d](https://www.github.com/googleapis/gcp-metadata/commit/ec0f82d022b4b3aac95e94ee1d8e53cfac3b14a4)) + + +### Bug Fixes + +* do not check secondary host if GCE_METADATA_IP set ([#352](https://www.github.com/googleapis/gcp-metadata/issues/352)) ([64fa7d6](https://www.github.com/googleapis/gcp-metadata/commit/64fa7d68cbb76f455a3bfdcb27d58e7775eb789a)) +* warn rather than throwing when we fail to connect to metadata server ([#351](https://www.github.com/googleapis/gcp-metadata/issues/351)) ([754a6c0](https://www.github.com/googleapis/gcp-metadata/commit/754a6c07d1a72615cbb5ebf9ee04475a9a12f1c0)) + +### [4.0.1](https://www.github.com/googleapis/gcp-metadata/compare/v4.0.0...v4.0.1) (2020-04-14) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v3 ([#326](https://www.github.com/googleapis/gcp-metadata/issues/326)) ([5667178](https://www.github.com/googleapis/gcp-metadata/commit/5667178429baff71ad5dab2a96f97f27b2106d57)) +* apache license URL ([#468](https://www.github.com/googleapis/gcp-metadata/issues/468)) ([#336](https://www.github.com/googleapis/gcp-metadata/issues/336)) ([195dcd2](https://www.github.com/googleapis/gcp-metadata/commit/195dcd2d227ba496949e7ec0dcd77e5b9269066c)) + +## [4.0.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.5.0...v4.0.0) (2020-03-19) + + +### ⚠ BREAKING CHANGES + +* typescript@3.7.x has breaking changes; compiler now targets es2015 +* drops Node 8 from engines field (#315) + +### Features + +* drops Node 8 from engines field ([#315](https://www.github.com/googleapis/gcp-metadata/issues/315)) ([acb6233](https://www.github.com/googleapis/gcp-metadata/commit/acb62337e8ba7f0b259ae4e553f19c5786207d84)) + + +### Build System + +* switch to latest typescirpt/gts ([#317](https://www.github.com/googleapis/gcp-metadata/issues/317)) ([fbb7158](https://www.github.com/googleapis/gcp-metadata/commit/fbb7158be62c9f1949b69079e35113be1e10495c)) + +## [3.5.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.4.0...v3.5.0) (2020-03-03) + + +### Features + +* add ECONNREFUSED to list of known errors for isAvailable() ([#309](https://www.github.com/googleapis/gcp-metadata/issues/309)) ([17ff6ea](https://www.github.com/googleapis/gcp-metadata/commit/17ff6ea361d02de31463532d4ab4040bf6276e0b)) + +## [3.4.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.3.1...v3.4.0) (2020-02-24) + + +### Features + +* significantly increase timeout if GCF environment detected ([#300](https://www.github.com/googleapis/gcp-metadata/issues/300)) ([8e507c6](https://www.github.com/googleapis/gcp-metadata/commit/8e507c645f69a11f508884b3181dc4414e579fcc)) + +### [3.3.1](https://www.github.com/googleapis/gcp-metadata/compare/v3.3.0...v3.3.1) (2020-01-30) + + +### Bug Fixes + +* **isAvailable:** handle EHOSTDOWN and EHOSTUNREACH error codes ([#291](https://www.github.com/googleapis/gcp-metadata/issues/291)) ([ba8d9f5](https://www.github.com/googleapis/gcp-metadata/commit/ba8d9f50eac6cf8b439c1b66c48ace146c75f6e2)) + +## [3.3.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.2.3...v3.3.0) (2019-12-16) + + +### Features + +* add environment variable for configuring environment detection ([#275](https://www.github.com/googleapis/gcp-metadata/issues/275)) ([580cfa4](https://www.github.com/googleapis/gcp-metadata/commit/580cfa4a5f5d0041aa09ae85cfc5a4575dd3957f)) +* cache response from isAvailable() method ([#274](https://www.github.com/googleapis/gcp-metadata/issues/274)) ([a05e13f](https://www.github.com/googleapis/gcp-metadata/commit/a05e13f1d1d61b1f9b9b1703bc37cdbdc022c93b)) + + +### Bug Fixes + +* fastFailMetadataRequest should not reject, if response already happened ([#273](https://www.github.com/googleapis/gcp-metadata/issues/273)) ([a6590c4](https://www.github.com/googleapis/gcp-metadata/commit/a6590c4fd8bc2dff3995c83d4c9175d5bd9f5e4a)) + +### [3.2.3](https://www.github.com/googleapis/gcp-metadata/compare/v3.2.2...v3.2.3) (2019-12-12) + + +### Bug Fixes + +* **deps:** pin TypeScript below 3.7.0 ([e4bf622](https://www.github.com/googleapis/gcp-metadata/commit/e4bf622e6654a51ddffc0921a15250130591db2f)) + +### [3.2.2](https://www.github.com/googleapis/gcp-metadata/compare/v3.2.1...v3.2.2) (2019-11-13) + + +### Bug Fixes + +* **docs:** add jsdoc-region-tag plugin ([#264](https://www.github.com/googleapis/gcp-metadata/issues/264)) ([af8362b](https://www.github.com/googleapis/gcp-metadata/commit/af8362b5a35d270af00cb3696bbf7344810e9b0c)) + +### [3.2.1](https://www.github.com/googleapis/gcp-metadata/compare/v3.2.0...v3.2.1) (2019-11-08) + + +### Bug Fixes + +* **deps:** update gaxios ([#257](https://www.github.com/googleapis/gcp-metadata/issues/257)) ([ba6e0b6](https://www.github.com/googleapis/gcp-metadata/commit/ba6e0b668635b4aa4ed10535ff021c02b2edf5ea)) + +## [3.2.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.1.0...v3.2.0) (2019-10-10) + + +### Features + +* add DEBUG_AUTH for digging into authentication issues ([#254](https://www.github.com/googleapis/gcp-metadata/issues/254)) ([804156d](https://www.github.com/googleapis/gcp-metadata/commit/804156d)) + +## [3.1.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.0.0...v3.1.0) (2019-10-07) + + +### Features + +* don't throw on ENETUNREACH ([#250](https://www.github.com/googleapis/gcp-metadata/issues/250)) ([88f2101](https://www.github.com/googleapis/gcp-metadata/commit/88f2101)) + +## [3.0.0](https://www.github.com/googleapis/gcp-metadata/compare/v2.0.4...v3.0.0) (2019-09-17) + + +### ⚠ BREAKING CHANGES + +* isAvailable now tries both DNS and IP, choosing whichever responds first (#239) + +### Features + +* isAvailable now tries both DNS and IP, choosing whichever responds first ([#239](https://www.github.com/googleapis/gcp-metadata/issues/239)) ([25bc116](https://www.github.com/googleapis/gcp-metadata/commit/25bc116)) + +### [2.0.4](https://www.github.com/googleapis/gcp-metadata/compare/v2.0.3...v2.0.4) (2019-09-13) + + +### Bug Fixes + +* IP address takes 15 seconds to timeout, vs., metadata returning immediately ([#235](https://www.github.com/googleapis/gcp-metadata/issues/235)) ([d04207b](https://www.github.com/googleapis/gcp-metadata/commit/d04207b)) +* use 3s timeout rather than 15 default ([#237](https://www.github.com/googleapis/gcp-metadata/issues/237)) ([231ca5c](https://www.github.com/googleapis/gcp-metadata/commit/231ca5c)) + +### [2.0.3](https://www.github.com/googleapis/gcp-metadata/compare/v2.0.2...v2.0.3) (2019-09-12) + + +### Bug Fixes + +* use IP for metadata server ([#233](https://www.github.com/googleapis/gcp-metadata/issues/233)) ([20a15cb](https://www.github.com/googleapis/gcp-metadata/commit/20a15cb)) + +### [2.0.2](https://www.github.com/googleapis/gcp-metadata/compare/v2.0.1...v2.0.2) (2019-08-26) + + +### Bug Fixes + +* allow calls with no request, add JSON proto ([#224](https://www.github.com/googleapis/gcp-metadata/issues/224)) ([dc758b1](https://www.github.com/googleapis/gcp-metadata/commit/dc758b1)) + +### [2.0.1](https://www.github.com/googleapis/gcp-metadata/compare/v2.0.0...v2.0.1) (2019-06-26) + + +### Bug Fixes + +* **docs:** make anchors work in jsdoc ([#212](https://www.github.com/googleapis/gcp-metadata/issues/212)) ([9174b43](https://www.github.com/googleapis/gcp-metadata/commit/9174b43)) + +## [2.0.0](https://www.github.com/googleapis/gcp-metadata/compare/v1.0.0...v2.0.0) (2019-05-07) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v2 ([#191](https://www.github.com/googleapis/gcp-metadata/issues/191)) ([ac8c1ef](https://www.github.com/googleapis/gcp-metadata/commit/ac8c1ef)) + + +### Build System + +* upgrade engines field to >=8.10.0 ([#194](https://www.github.com/googleapis/gcp-metadata/issues/194)) ([97c23c8](https://www.github.com/googleapis/gcp-metadata/commit/97c23c8)) + + +### BREAKING CHANGES + +* upgrade engines field to >=8.10.0 (#194) + +## v1.0.0 + +02-14-2019 16:00 PST + +### Bug Fixes +- fix: ask gaxios for text and not json ([#152](https://github.com/googleapis/gcp-metadata/pull/152)) + +### Documentation +- docs: update links in contrib guide ([#168](https://github.com/googleapis/gcp-metadata/pull/168)) +- docs: add lint/fix example to contributing guide ([#160](https://github.com/googleapis/gcp-metadata/pull/160)) + +### Internal / Testing Changes +- build: use linkinator for docs test ([#166](https://github.com/googleapis/gcp-metadata/pull/166)) +- chore(deps): update dependency @types/tmp to v0.0.34 ([#167](https://github.com/googleapis/gcp-metadata/pull/167)) +- build: create docs test npm scripts ([#165](https://github.com/googleapis/gcp-metadata/pull/165)) +- test: run system tests on GCB ([#157](https://github.com/googleapis/gcp-metadata/pull/157)) +- build: test using @grpc/grpc-js in CI ([#164](https://github.com/googleapis/gcp-metadata/pull/164)) +- chore: move CONTRIBUTING.md to root ([#162](https://github.com/googleapis/gcp-metadata/pull/162)) +- chore(deps): update dependency gcx to v0.1.1 ([#159](https://github.com/googleapis/gcp-metadata/pull/159)) +- chore(deps): update dependency gcx to v0.1.0 ([#158](https://github.com/googleapis/gcp-metadata/pull/158)) +- chore(deps): update dependency gcx to v0.0.4 ([#155](https://github.com/googleapis/gcp-metadata/pull/155)) +- chore(deps): update dependency googleapis to v37 ([#156](https://github.com/googleapis/gcp-metadata/pull/156)) +- build: ignore googleapis.com in doc link check ([#153](https://github.com/googleapis/gcp-metadata/pull/153)) +- build: check broken links in generated docs ([#149](https://github.com/googleapis/gcp-metadata/pull/149)) +- chore(build): inject yoshi automation key ([#148](https://github.com/googleapis/gcp-metadata/pull/148)) + +## v0.9.3 + +12-10-2018 16:16 PST + +### Dependencies +- chore(deps): update dependency googleapis to v36 ([#135](https://github.com/googleapis/gcp-metadata/pull/135)) +- chore(deps): use gaxios for http requests ([#121](https://github.com/googleapis/gcp-metadata/pull/121)) +- chore(deps): update dependency gts to ^0.9.0 ([#123](https://github.com/googleapis/gcp-metadata/pull/123)) + +### Internal / Testing Changes +- fix(build): fix Kokoro release script ([#141](https://github.com/googleapis/gcp-metadata/pull/141)) +- Release v0.9.2 ([#140](https://github.com/googleapis/gcp-metadata/pull/140)) +- build: add Kokoro configs for autorelease ([#138](https://github.com/googleapis/gcp-metadata/pull/138)) +- Release gcp-metadata v0.9.1 ([#139](https://github.com/googleapis/gcp-metadata/pull/139)) +- chore: always nyc report before calling codecov ([#134](https://github.com/googleapis/gcp-metadata/pull/134)) +- chore: nyc ignore build/test by default ([#133](https://github.com/googleapis/gcp-metadata/pull/133)) +- Sync repo build files ([#131](https://github.com/googleapis/gcp-metadata/pull/131)) +- fix(build): fix system key decryption ([#128](https://github.com/googleapis/gcp-metadata/pull/128)) +- refactor: use execa, move post install test to system ([#127](https://github.com/googleapis/gcp-metadata/pull/127)) +- chore: add a synth.metadata +- test: add a system test ([#126](https://github.com/googleapis/gcp-metadata/pull/126)) +- chore: update eslintignore config ([#122](https://github.com/googleapis/gcp-metadata/pull/122)) +- chore: use latest npm on Windows ([#120](https://github.com/googleapis/gcp-metadata/pull/120)) +- chore: update CircleCI config ([#119](https://github.com/googleapis/gcp-metadata/pull/119)) +- chore: include build in eslintignore ([#115](https://github.com/googleapis/gcp-metadata/pull/115)) + +## v0.9.2 + +12-10-2018 14:01 PST + +- chore(deps): update dependency googleapis to v36 ([#135](https://github.com/googleapis/gcp-metadata/pull/135)) +- chore: always nyc report before calling codecov ([#134](https://github.com/googleapis/gcp-metadata/pull/134)) +- chore: nyc ignore build/test by default ([#133](https://github.com/googleapis/gcp-metadata/pull/133)) +- chore: Re-generated to pick up changes in the API or client library generator. ([#131](https://github.com/googleapis/gcp-metadata/pull/131)) +- fix(build): fix system key decryption ([#128](https://github.com/googleapis/gcp-metadata/pull/128)) +- chore(deps): use gaxios for http requests ([#121](https://github.com/googleapis/gcp-metadata/pull/121)) +- refactor: use execa, move post install test to system ([#127](https://github.com/googleapis/gcp-metadata/pull/127)) +- chore: add a synth.metadata +- test: add a system test ([#126](https://github.com/googleapis/gcp-metadata/pull/126)) +- chore(deps): update dependency gts to ^0.9.0 ([#123](https://github.com/googleapis/gcp-metadata/pull/123)) +- chore: update eslintignore config ([#122](https://github.com/googleapis/gcp-metadata/pull/122)) +- chore: use latest npm on Windows ([#120](https://github.com/googleapis/gcp-metadata/pull/120)) +- chore: update CircleCI config ([#119](https://github.com/googleapis/gcp-metadata/pull/119)) +- chore: include build in eslintignore ([#115](https://github.com/googleapis/gcp-metadata/pull/115)) +- build: add Kokoro configs for autorelease ([#138](https://github.com/googleapis/gcp-metadata/pull/138)) + +## v0.9.1 + +12-10-2018 11:53 PST + +- chore(deps): update dependency googleapis to v36 ([#135](https://github.com/googleapis/gcp-metadata/pull/135)) +- chore: always nyc report before calling codecov ([#134](https://github.com/googleapis/gcp-metadata/pull/134)) +- chore: nyc ignore build/test by default ([#133](https://github.com/googleapis/gcp-metadata/pull/133)) +- chore: Re-generated to pick up changes in the API or client library generator. ([#131](https://github.com/googleapis/gcp-metadata/pull/131)) +- fix(build): fix system key decryption ([#128](https://github.com/googleapis/gcp-metadata/pull/128)) +- chore(deps): use gaxios for http requests ([#121](https://github.com/googleapis/gcp-metadata/pull/121)) +- refactor: use execa, move post install test to system ([#127](https://github.com/googleapis/gcp-metadata/pull/127)) +- chore: add a synth.metadata +- test: add a system test ([#126](https://github.com/googleapis/gcp-metadata/pull/126)) +- chore(deps): update dependency gts to ^0.9.0 ([#123](https://github.com/googleapis/gcp-metadata/pull/123)) +- chore: update eslintignore config ([#122](https://github.com/googleapis/gcp-metadata/pull/122)) +- chore: use latest npm on Windows ([#120](https://github.com/googleapis/gcp-metadata/pull/120)) +- chore: update CircleCI config ([#119](https://github.com/googleapis/gcp-metadata/pull/119)) +- chore: include build in eslintignore ([#115](https://github.com/googleapis/gcp-metadata/pull/115)) + +## v0.9.0 + +10-26-2018 13:10 PDT + +- feat: allow custom headers ([#109](https://github.com/googleapis/gcp-metadata/pull/109)) +- chore: update issue templates ([#108](https://github.com/googleapis/gcp-metadata/pull/108)) +- chore: remove old issue template ([#106](https://github.com/googleapis/gcp-metadata/pull/106)) +- build: run tests on node11 ([#105](https://github.com/googleapis/gcp-metadata/pull/105)) +- chores(build): do not collect sponge.xml from windows builds ([#104](https://github.com/googleapis/gcp-metadata/pull/104)) +- chores(build): run codecov on continuous builds ([#102](https://github.com/googleapis/gcp-metadata/pull/102)) +- chore(deps): update dependency nock to v10 ([#103](https://github.com/googleapis/gcp-metadata/pull/103)) +- chore: update new issue template ([#101](https://github.com/googleapis/gcp-metadata/pull/101)) +- build: fix codecov uploading on Kokoro ([#97](https://github.com/googleapis/gcp-metadata/pull/97)) +- Update kokoro config ([#95](https://github.com/googleapis/gcp-metadata/pull/95)) +- Update CI config ([#93](https://github.com/googleapis/gcp-metadata/pull/93)) +- Update kokoro config ([#91](https://github.com/googleapis/gcp-metadata/pull/91)) +- Re-generate library using /synth.py ([#90](https://github.com/googleapis/gcp-metadata/pull/90)) +- test: remove appveyor config ([#89](https://github.com/googleapis/gcp-metadata/pull/89)) +- Update kokoro config ([#88](https://github.com/googleapis/gcp-metadata/pull/88)) +- Enable prefer-const in the eslint config ([#87](https://github.com/googleapis/gcp-metadata/pull/87)) +- Enable no-var in eslint ([#86](https://github.com/googleapis/gcp-metadata/pull/86)) + +### New Features + +A new option, `headers`, has been added to allow metadata queries to be sent with custom headers. + +## v0.8.0 + +**This release has breaking changes**. Please take care when upgrading to the latest version. + +#### Dropped support for Node.js 4.x and 9.x +This library is no longer tested against versions 4.x and 9.x of Node.js. Please upgrade to the latest supported LTS version! + +#### Return type of `instance()` and `project()` has changed +The `instance()` and `project()` methods are much more selective about which properties they will accept. + +The only accepted properties are `params` and `properties`. The `instance()` and `project()` methods also now directly return the data instead of a response object. + +#### Changes in how large number valued properties are handled + +Previously large number-valued properties were being silently losing precision when +returned by this library (as a number). In the cases where a number valued property +returned by the metadata service is too large to represent as a JavaScript number, we +will now return the value as a BigNumber (from the bignumber.js) library. Numbers that +do fit into the JavaScript number range will continue to be returned as numbers. +For more details see [#74](https://github.com/googleapis/gcp-metadata/pull/74). + +### Breaking Changes +- chore: drop support for node.js 4 and 9 ([#68](https://github.com/googleapis/gcp-metadata/pull/68)) +- fix: quarantine axios config ([#62](https://github.com/googleapis/gcp-metadata/pull/62)) + +### Implementation Changes +- fix: properly handle large numbers in responses ([#74](https://github.com/googleapis/gcp-metadata/pull/74)) + +### Dependencies +- chore(deps): update dependency pify to v4 ([#73](https://github.com/googleapis/gcp-metadata/pull/73)) + +### Internal / Testing Changes +- Move to the new github org ([#84](https://github.com/googleapis/gcp-metadata/pull/84)) +- Update CI config ([#83](https://github.com/googleapis/gcp-metadata/pull/83)) +- Retry npm install in CI ([#81](https://github.com/googleapis/gcp-metadata/pull/81)) +- Update CI config ([#79](https://github.com/googleapis/gcp-metadata/pull/79)) +- chore(deps): update dependency nyc to v13 ([#77](https://github.com/googleapis/gcp-metadata/pull/77)) +- add key for system tests +- increase kitchen test timeout +- add a lint npm script +- update npm scripts +- add a synth file and run it ([#75](https://github.com/googleapis/gcp-metadata/pull/75)) +- chore(deps): update dependency assert-rejects to v1 ([#72](https://github.com/googleapis/gcp-metadata/pull/72)) +- chore: ignore package-log.json ([#71](https://github.com/googleapis/gcp-metadata/pull/71)) +- chore: update renovate config ([#70](https://github.com/googleapis/gcp-metadata/pull/70)) +- test: throw on deprecation +- chore(deps): update dependency typescript to v3 ([#67](https://github.com/googleapis/gcp-metadata/pull/67)) +- chore: make it OSPO compliant ([#66](https://github.com/googleapis/gcp-metadata/pull/66)) +- chore(deps): update dependency gts to ^0.8.0 ([#65](https://github.com/googleapis/gcp-metadata/pull/65)) diff --git a/node_modules/gcp-metadata/LICENSE b/node_modules/gcp-metadata/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/gcp-metadata/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/gcp-metadata/README.md b/node_modules/gcp-metadata/README.md new file mode 100644 index 0000000..d0c1b9d --- /dev/null +++ b/node_modules/gcp-metadata/README.md @@ -0,0 +1,235 @@ +[//]: # "This README.md file is auto-generated, all changes to this file will be lost." +[//]: # "To regenerate it, use `python -m synthtool`." +Google Cloud Platform logo + +# [GCP Metadata: Node.js Client](https://github.com/googleapis/gcp-metadata) + +[![release level](https://img.shields.io/badge/release%20level-stable-brightgreen.svg?style=flat)](https://cloud.google.com/terms/launch-stages) +[![npm version](https://img.shields.io/npm/v/gcp-metadata.svg)](https://www.npmjs.org/package/gcp-metadata) + + + + +Get the metadata from a Google Cloud Platform environment + + +A comprehensive list of changes in each version may be found in +[the CHANGELOG](https://github.com/googleapis/gcp-metadata/blob/main/CHANGELOG.md). + +* [GCP Metadata Node.js Client API Reference][client-docs] +* [GCP Metadata Documentation][product-docs] +* [github.com/googleapis/gcp-metadata](https://github.com/googleapis/gcp-metadata) + +Read more about the client libraries for Cloud APIs, including the older +Google APIs Client Libraries, in [Client Libraries Explained][explained]. + +[explained]: https://cloud.google.com/apis/docs/client-libraries-explained + +**Table of contents:** + + +* [Quickstart](#quickstart) + + * [Installing the client library](#installing-the-client-library) + * [Using the client library](#using-the-client-library) +* [Samples](#samples) +* [Versioning](#versioning) +* [Contributing](#contributing) +* [License](#license) + +## Quickstart + +### Installing the client library + +```bash +npm install gcp-metadata +``` + + +### Using the client library + +```javascript +const gcpMetadata = require('gcp-metadata'); + +async function quickstart() { + // check to see if this code can access a metadata server + const isAvailable = await gcpMetadata.isAvailable(); + console.log(`Is available: ${isAvailable}`); + + // Instance and Project level metadata will only be available if + // running inside of a Google Cloud compute environment such as + // Cloud Functions, App Engine, Kubernetes Engine, or Compute Engine. + // To learn more about the differences between instance and project + // level metadata, see: + // https://cloud.google.com/compute/docs/storing-retrieving-metadata#project-instance-metadata + if (isAvailable) { + // grab all top level metadata from the service + const instanceMetadata = await gcpMetadata.instance(); + console.log('Instance metadata:'); + console.log(instanceMetadata); + + // get all project level metadata + const projectMetadata = await gcpMetadata.project(); + console.log('Project metadata:'); + console.log(projectMetadata); + } +} + +quickstart(); + +``` + +#### Check to see if the metadata server is available +```js +const isAvailable = await gcpMetadata.isAvailable(); +``` + +#### Access all metadata + +```js +const data = await gcpMetadata.instance(); +console.log(data); // ... All metadata properties +``` + +#### Access specific properties +```js +const data = await gcpMetadata.instance('hostname'); +console.log(data); // ...Instance hostname +const projectId = await gcpMetadata.project('project-id'); +console.log(projectId); // ...Project ID of the running instance +``` + +#### Access nested properties with the relative path +```js +const data = await gcpMetadata.instance('service-accounts/default/email'); +console.log(data); // ...Email address of the Compute identity service account +``` + +#### Access specific properties with query parameters +```js +const data = await gcpMetadata.instance({ + property: 'tags', + params: { alt: 'text' } +}); +console.log(data) // ...Tags as newline-delimited list +``` + +#### Access with custom headers +```js +await gcpMetadata.instance({ + headers: { 'no-trace': '1' } +}); // ...Request is untraced +``` + +### Take care with large number valued properties + +In some cases number valued properties returned by the Metadata Service may be +too large to be representable as JavaScript numbers. In such cases we return +those values as `BigNumber` objects (from the [bignumber.js](https://github.com/MikeMcl/bignumber.js) library). Numbers +that fit within the JavaScript number range will be returned as normal number +values. + +```js +const id = await gcpMetadata.instance('id'); +console.log(id) // ... BigNumber { s: 1, e: 18, c: [ 45200, 31799277581759 ] } +console.log(id.toString()) // ... 4520031799277581759 +``` + +### Environment variables + +* `GCE_METADATA_HOST`: provide an alternate host or IP to perform lookup against (useful, for example, you're connecting through a custom proxy server). + + For example: + ``` + export GCE_METADATA_HOST='169.254.169.254' + ``` + +* `DETECT_GCP_RETRIES`: number representing number of retries that should be attempted on metadata lookup. + +* `DEBUG_AUTH`: emit debugging logs + +* `METADATA_SERVER_DETECTION`: configure desired metadata server availability check behavior. + + * `assume-present`: don't try to ping the metadata server, but assume it's present + * `none`: don't try to ping the metadata server, but don't try to use it either + * `bios-only`: treat the result of a BIOS probe as canonical (don't fall back to pinging) + * `ping-only`: skip the BIOS probe, and go straight to pinging + + +## Samples + +Samples are in the [`samples/`](https://github.com/googleapis/gcp-metadata/tree/main/samples) directory. Each sample's `README.md` has instructions for running its sample. + +| Sample | Source Code | Try it | +| --------------------------- | --------------------------------- | ------ | +| Quickstart | [source code](https://github.com/googleapis/gcp-metadata/blob/main/samples/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/gcp-metadata&page=editor&open_in_editor=samples/quickstart.js,samples/README.md) | + + + +The [GCP Metadata Node.js Client API Reference][client-docs] documentation +also contains samples. + +## Supported Node.js Versions + +Our client libraries follow the [Node.js release schedule](https://github.com/nodejs/release#release-schedule). +Libraries are compatible with all current _active_ and _maintenance_ versions of +Node.js. +If you are using an end-of-life version of Node.js, we recommend that you update +as soon as possible to an actively supported LTS version. + +Google's client libraries support legacy versions of Node.js runtimes on a +best-efforts basis with the following warnings: + +* Legacy versions are not tested in continuous integration. +* Some security patches and features cannot be backported. +* Dependencies cannot be kept up-to-date. + +Client libraries targeting some end-of-life versions of Node.js are available, and +can be installed through npm [dist-tags](https://docs.npmjs.com/cli/dist-tag). +The dist-tags follow the naming convention `legacy-(version)`. +For example, `npm install gcp-metadata@legacy-8` installs client libraries +for versions compatible with Node.js 8. + +## Versioning + +This library follows [Semantic Versioning](http://semver.org/). + + + +This library is considered to be **stable**. The code surface will not change in backwards-incompatible ways +unless absolutely necessary (e.g. because of critical security issues) or with +an extensive deprecation period. Issues and requests against **stable** libraries +are addressed with the highest priority. + + + + + + +More Information: [Google Cloud Platform Launch Stages][launch_stages] + +[launch_stages]: https://cloud.google.com/terms/launch-stages + +## Contributing + +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/gcp-metadata/blob/main/CONTRIBUTING.md). + +Please note that this `README.md`, the `samples/README.md`, +and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) +are generated from a central template. To edit one of these files, make an edit +to its templates in +[directory](https://github.com/googleapis/synthtool). + +## License + +Apache Version 2.0 + +See [LICENSE](https://github.com/googleapis/gcp-metadata/blob/main/LICENSE) + +[client-docs]: https://cloud.google.com/nodejs/docs/reference/gcp-metadata/latest +[product-docs]: https://cloud.google.com/compute/docs/storing-retrieving-metadata +[shell_img]: https://gstatic.com/cloudssh/images/open-btn.png +[projects]: https://console.cloud.google.com/project +[billing]: https://support.google.com/cloud/answer/6293499#enable-billing + +[auth]: https://cloud.google.com/docs/authentication/external/set-up-adc-local diff --git a/node_modules/gcp-metadata/build/src/gcp-residency.d.ts b/node_modules/gcp-metadata/build/src/gcp-residency.d.ts new file mode 100644 index 0000000..f39896f --- /dev/null +++ b/node_modules/gcp-metadata/build/src/gcp-residency.d.ts @@ -0,0 +1,57 @@ +/** + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Known paths unique to Google Compute Engine Linux instances + */ +export declare const GCE_LINUX_BIOS_PATHS: { + BIOS_DATE: string; + BIOS_VENDOR: string; +}; +/** + * Determines if the process is running on a Google Cloud Serverless environment (Cloud Run or Cloud Functions instance). + * + * Uses the: + * - {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}. + * - {@link https://cloud.google.com/functions/docs/env-var Cloud Functions environment variables}. + * + * @returns {boolean} `true` if the process is running on GCP serverless, `false` otherwise. + */ +export declare function isGoogleCloudServerless(): boolean; +/** + * Determines if the process is running on a Linux Google Compute Engine instance. + * + * @returns {boolean} `true` if the process is running on Linux GCE, `false` otherwise. + */ +export declare function isGoogleComputeEngineLinux(): boolean; +/** + * Determines if the process is running on a Google Compute Engine instance with a known + * MAC address. + * + * @returns {boolean} `true` if the process is running on GCE (as determined by MAC address), `false` otherwise. + */ +export declare function isGoogleComputeEngineMACAddress(): boolean; +/** + * Determines if the process is running on a Google Compute Engine instance. + * + * @returns {boolean} `true` if the process is running on GCE, `false` otherwise. + */ +export declare function isGoogleComputeEngine(): boolean; +/** + * Determines if the process is running on Google Cloud Platform. + * + * @returns {boolean} `true` if the process is running on GCP, `false` otherwise. + */ +export declare function detectGCPResidency(): boolean; diff --git a/node_modules/gcp-metadata/build/src/gcp-residency.js b/node_modules/gcp-metadata/build/src/gcp-residency.js new file mode 100644 index 0000000..83e7dbf --- /dev/null +++ b/node_modules/gcp-metadata/build/src/gcp-residency.js @@ -0,0 +1,114 @@ +"use strict"; +/** + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GCE_LINUX_BIOS_PATHS = void 0; +exports.isGoogleCloudServerless = isGoogleCloudServerless; +exports.isGoogleComputeEngineLinux = isGoogleComputeEngineLinux; +exports.isGoogleComputeEngineMACAddress = isGoogleComputeEngineMACAddress; +exports.isGoogleComputeEngine = isGoogleComputeEngine; +exports.detectGCPResidency = detectGCPResidency; +const fs_1 = require("fs"); +const os_1 = require("os"); +/** + * Known paths unique to Google Compute Engine Linux instances + */ +exports.GCE_LINUX_BIOS_PATHS = { + BIOS_DATE: '/sys/class/dmi/id/bios_date', + BIOS_VENDOR: '/sys/class/dmi/id/bios_vendor', +}; +const GCE_MAC_ADDRESS_REGEX = /^42:01/; +/** + * Determines if the process is running on a Google Cloud Serverless environment (Cloud Run or Cloud Functions instance). + * + * Uses the: + * - {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}. + * - {@link https://cloud.google.com/functions/docs/env-var Cloud Functions environment variables}. + * + * @returns {boolean} `true` if the process is running on GCP serverless, `false` otherwise. + */ +function isGoogleCloudServerless() { + /** + * `CLOUD_RUN_JOB` is used for Cloud Run Jobs + * - See {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}. + * + * `FUNCTION_NAME` is used in older Cloud Functions environments: + * - See {@link https://cloud.google.com/functions/docs/env-var Python 3.7 and Go 1.11}. + * + * `K_SERVICE` is used in Cloud Run and newer Cloud Functions environments: + * - See {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}. + * - See {@link https://cloud.google.com/functions/docs/env-var Cloud Functions newer runtimes}. + */ + const isGFEnvironment = process.env.CLOUD_RUN_JOB || + process.env.FUNCTION_NAME || + process.env.K_SERVICE; + return !!isGFEnvironment; +} +/** + * Determines if the process is running on a Linux Google Compute Engine instance. + * + * @returns {boolean} `true` if the process is running on Linux GCE, `false` otherwise. + */ +function isGoogleComputeEngineLinux() { + if ((0, os_1.platform)() !== 'linux') + return false; + try { + // ensure this file exist + (0, fs_1.statSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_DATE); + // ensure this file exist and matches + const biosVendor = (0, fs_1.readFileSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR, 'utf8'); + return /Google/.test(biosVendor); + } + catch (_a) { + return false; + } +} +/** + * Determines if the process is running on a Google Compute Engine instance with a known + * MAC address. + * + * @returns {boolean} `true` if the process is running on GCE (as determined by MAC address), `false` otherwise. + */ +function isGoogleComputeEngineMACAddress() { + const interfaces = (0, os_1.networkInterfaces)(); + for (const item of Object.values(interfaces)) { + if (!item) + continue; + for (const { mac } of item) { + if (GCE_MAC_ADDRESS_REGEX.test(mac)) { + return true; + } + } + } + return false; +} +/** + * Determines if the process is running on a Google Compute Engine instance. + * + * @returns {boolean} `true` if the process is running on GCE, `false` otherwise. + */ +function isGoogleComputeEngine() { + return isGoogleComputeEngineLinux() || isGoogleComputeEngineMACAddress(); +} +/** + * Determines if the process is running on Google Cloud Platform. + * + * @returns {boolean} `true` if the process is running on GCP, `false` otherwise. + */ +function detectGCPResidency() { + return isGoogleCloudServerless() || isGoogleComputeEngine(); +} +//# sourceMappingURL=gcp-residency.js.map \ No newline at end of file diff --git a/node_modules/gcp-metadata/build/src/gcp-residency.js.map b/node_modules/gcp-metadata/build/src/gcp-residency.js.map new file mode 100644 index 0000000..e32c69f --- /dev/null +++ b/node_modules/gcp-metadata/build/src/gcp-residency.js.map @@ -0,0 +1 @@ +{"version":3,"file":"gcp-residency.js","sourceRoot":"","sources":["../../src/gcp-residency.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAwBH,0DAkBC;AAOD,gEAcC;AAQD,0EAcC;AAOD,sDAEC;AAOD,gDAEC;AArGD,2BAA0C;AAC1C,2BAA+C;AAE/C;;GAEG;AACU,QAAA,oBAAoB,GAAG;IAClC,SAAS,EAAE,6BAA6B;IACxC,WAAW,EAAE,+BAA+B;CAC7C,CAAC;AAEF,MAAM,qBAAqB,GAAG,QAAQ,CAAC;AAEvC;;;;;;;;GAQG;AACH,SAAgB,uBAAuB;IACrC;;;;;;;;;;OAUG;IACH,MAAM,eAAe,GACnB,OAAO,CAAC,GAAG,CAAC,aAAa;QACzB,OAAO,CAAC,GAAG,CAAC,aAAa;QACzB,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC;IAExB,OAAO,CAAC,CAAC,eAAe,CAAC;AAC3B,CAAC;AAED;;;;GAIG;AACH,SAAgB,0BAA0B;IACxC,IAAI,IAAA,aAAQ,GAAE,KAAK,OAAO;QAAE,OAAO,KAAK,CAAC;IAEzC,IAAI,CAAC;QACH,yBAAyB;QACzB,IAAA,aAAQ,EAAC,4BAAoB,CAAC,SAAS,CAAC,CAAC;QAEzC,qCAAqC;QACrC,MAAM,UAAU,GAAG,IAAA,iBAAY,EAAC,4BAAoB,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;QAE1E,OAAO,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IACnC,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,SAAgB,+BAA+B;IAC7C,MAAM,UAAU,GAAG,IAAA,sBAAiB,GAAE,CAAC;IAEvC,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC;QAC7C,IAAI,CAAC,IAAI;YAAE,SAAS;QAEpB,KAAK,MAAM,EAAC,GAAG,EAAC,IAAI,IAAI,EAAE,CAAC;YACzB,IAAI,qBAAqB,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;gBACpC,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;GAIG;AACH,SAAgB,qBAAqB;IACnC,OAAO,0BAA0B,EAAE,IAAI,+BAA+B,EAAE,CAAC;AAC3E,CAAC;AAED;;;;GAIG;AACH,SAAgB,kBAAkB;IAChC,OAAO,uBAAuB,EAAE,IAAI,qBAAqB,EAAE,CAAC;AAC9D,CAAC"} \ No newline at end of file diff --git a/node_modules/gcp-metadata/build/src/index.d.ts b/node_modules/gcp-metadata/build/src/index.d.ts new file mode 100644 index 0000000..25705e7 --- /dev/null +++ b/node_modules/gcp-metadata/build/src/index.d.ts @@ -0,0 +1,156 @@ +/** + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { OutgoingHttpHeaders } from 'http'; +export declare const BASE_PATH = "/computeMetadata/v1"; +export declare const HOST_ADDRESS = "http://169.254.169.254"; +export declare const SECONDARY_HOST_ADDRESS = "http://metadata.google.internal."; +export declare const HEADER_NAME = "Metadata-Flavor"; +export declare const HEADER_VALUE = "Google"; +export declare const HEADERS: Readonly<{ + "Metadata-Flavor": "Google"; +}>; +/** + * Metadata server detection override options. + * + * Available via `process.env.METADATA_SERVER_DETECTION`. + */ +export declare const METADATA_SERVER_DETECTION: Readonly<{ + 'assume-present': "don't try to ping the metadata server, but assume it's present"; + none: "don't try to ping the metadata server, but don't try to use it either"; + 'bios-only': "treat the result of a BIOS probe as canonical (don't fall back to pinging)"; + 'ping-only': "skip the BIOS probe, and go straight to pinging"; +}>; +export interface Options { + params?: { + [index: string]: string; + }; + property?: string; + headers?: OutgoingHttpHeaders; +} +export interface MetadataAccessor { + /** + * + * @example + * + * // equivalent to `project('project-id')`; + * const metadataKey = 'project/project-id'; + */ + metadataKey: string; + params?: Options['params']; + headers?: Options['headers']; + noResponseRetries?: number; + fastFail?: boolean; +} +export type BulkResults = { + [key in T[number]['metadataKey']]: ReturnType; +}; +/** + * Obtain metadata for the current GCE instance. + * + * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} + * + * @example + * ``` + * const serviceAccount: {} = await instance('service-accounts/'); + * const serviceAccountEmail: string = await instance('service-accounts/default/email'); + * ``` + */ +export declare function instance(options?: string | Options): Promise; +/** + * Obtain metadata for the current GCP project. + * + * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} + * + * @example + * ``` + * const projectId: string = await project('project-id'); + * const numericProjectId: number = await project('numeric-project-id'); + * ``` + */ +export declare function project(options?: string | Options): Promise; +/** + * Obtain metadata for the current universe. + * + * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} + * + * @example + * ``` + * const universeDomain: string = await universe('universe-domain'); + * ``` + */ +export declare function universe(options?: string | Options): Promise; +/** + * Retrieve metadata items in parallel. + * + * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} + * + * @example + * ``` + * const data = await bulk([ + * { + * metadataKey: 'instance', + * }, + * { + * metadataKey: 'project/project-id', + * }, + * ] as const); + * + * // data.instance; + * // data['project/project-id']; + * ``` + * + * @param properties The metadata properties to retrieve + * @returns The metadata in `metadatakey:value` format + */ +export declare function bulk[], R extends BulkResults = BulkResults>(properties: T): Promise; +/** + * Determine if the metadata server is currently available. + */ +export declare function isAvailable(): Promise; +/** + * reset the memoized isAvailable() lookup. + */ +export declare function resetIsAvailableCache(): void; +/** + * A cache for the detected GCP Residency. + */ +export declare let gcpResidencyCache: boolean | null; +/** + * Detects GCP Residency. + * Caches results to reduce costs for subsequent calls. + * + * @see setGCPResidency for setting + */ +export declare function getGCPResidency(): boolean; +/** + * Sets the detected GCP Residency. + * Useful for forcing metadata server detection behavior. + * + * Set `null` to autodetect the environment (default behavior). + * @see getGCPResidency for getting + */ +export declare function setGCPResidency(value?: boolean | null): void; +/** + * Obtain the timeout for requests to the metadata server. + * + * In certain environments and conditions requests can take longer than + * the default timeout to complete. This function will determine the + * appropriate timeout based on the environment. + * + * @returns {number} a request timeout duration in milliseconds. + */ +export declare function requestTimeout(): number; +export * from './gcp-residency'; diff --git a/node_modules/gcp-metadata/build/src/index.js b/node_modules/gcp-metadata/build/src/index.js new file mode 100644 index 0000000..1345936 --- /dev/null +++ b/node_modules/gcp-metadata/build/src/index.js @@ -0,0 +1,408 @@ +"use strict"; +/** + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.gcpResidencyCache = exports.METADATA_SERVER_DETECTION = exports.HEADERS = exports.HEADER_VALUE = exports.HEADER_NAME = exports.SECONDARY_HOST_ADDRESS = exports.HOST_ADDRESS = exports.BASE_PATH = void 0; +exports.instance = instance; +exports.project = project; +exports.universe = universe; +exports.bulk = bulk; +exports.isAvailable = isAvailable; +exports.resetIsAvailableCache = resetIsAvailableCache; +exports.getGCPResidency = getGCPResidency; +exports.setGCPResidency = setGCPResidency; +exports.requestTimeout = requestTimeout; +const gaxios_1 = require("gaxios"); +const jsonBigint = require("json-bigint"); +const gcp_residency_1 = require("./gcp-residency"); +const logger = require("google-logging-utils"); +exports.BASE_PATH = '/computeMetadata/v1'; +exports.HOST_ADDRESS = 'http://169.254.169.254'; +exports.SECONDARY_HOST_ADDRESS = 'http://metadata.google.internal.'; +exports.HEADER_NAME = 'Metadata-Flavor'; +exports.HEADER_VALUE = 'Google'; +exports.HEADERS = Object.freeze({ [exports.HEADER_NAME]: exports.HEADER_VALUE }); +const log = logger.log('gcp metadata'); +/** + * Metadata server detection override options. + * + * Available via `process.env.METADATA_SERVER_DETECTION`. + */ +exports.METADATA_SERVER_DETECTION = Object.freeze({ + 'assume-present': "don't try to ping the metadata server, but assume it's present", + none: "don't try to ping the metadata server, but don't try to use it either", + 'bios-only': "treat the result of a BIOS probe as canonical (don't fall back to pinging)", + 'ping-only': 'skip the BIOS probe, and go straight to pinging', +}); +/** + * Returns the base URL while taking into account the GCE_METADATA_HOST + * environment variable if it exists. + * + * @returns The base URL, e.g., http://169.254.169.254/computeMetadata/v1. + */ +function getBaseUrl(baseUrl) { + if (!baseUrl) { + baseUrl = + process.env.GCE_METADATA_IP || + process.env.GCE_METADATA_HOST || + exports.HOST_ADDRESS; + } + // If no scheme is provided default to HTTP: + if (!/^https?:\/\//.test(baseUrl)) { + baseUrl = `http://${baseUrl}`; + } + return new URL(exports.BASE_PATH, baseUrl).href; +} +// Accepts an options object passed from the user to the API. In previous +// versions of the API, it referred to a `Request` or an `Axios` request +// options object. Now it refers to an object with very limited property +// names. This is here to help ensure users don't pass invalid options when +// they upgrade from 0.4 to 0.5 to 0.8. +function validate(options) { + Object.keys(options).forEach(key => { + switch (key) { + case 'params': + case 'property': + case 'headers': + break; + case 'qs': + throw new Error("'qs' is not a valid configuration option. Please use 'params' instead."); + default: + throw new Error(`'${key}' is not a valid configuration option.`); + } + }); +} +async function metadataAccessor(type, options = {}, noResponseRetries = 3, fastFail = false) { + let metadataKey = ''; + let params = {}; + let headers = {}; + if (typeof type === 'object') { + const metadataAccessor = type; + metadataKey = metadataAccessor.metadataKey; + params = metadataAccessor.params || params; + headers = metadataAccessor.headers || headers; + noResponseRetries = metadataAccessor.noResponseRetries || noResponseRetries; + fastFail = metadataAccessor.fastFail || fastFail; + } + else { + metadataKey = type; + } + if (typeof options === 'string') { + metadataKey += `/${options}`; + } + else { + validate(options); + if (options.property) { + metadataKey += `/${options.property}`; + } + headers = options.headers || headers; + params = options.params || params; + } + const requestMethod = fastFail ? fastFailMetadataRequest : gaxios_1.request; + const req = { + url: `${getBaseUrl()}/${metadataKey}`, + headers: { ...exports.HEADERS, ...headers }, + retryConfig: { noResponseRetries }, + params, + responseType: 'text', + timeout: requestTimeout(), + }; + log.info('instance request %j', req); + const res = await requestMethod(req); + log.info('instance metadata is %s', res.data); + // NOTE: node.js converts all incoming headers to lower case. + if (res.headers[exports.HEADER_NAME.toLowerCase()] !== exports.HEADER_VALUE) { + throw new Error(`Invalid response from metadata service: incorrect ${exports.HEADER_NAME} header. Expected '${exports.HEADER_VALUE}', got ${res.headers[exports.HEADER_NAME.toLowerCase()] ? `'${res.headers[exports.HEADER_NAME.toLowerCase()]}'` : 'no header'}`); + } + if (typeof res.data === 'string') { + try { + return jsonBigint.parse(res.data); + } + catch (_a) { + /* ignore */ + } + } + return res.data; +} +async function fastFailMetadataRequest(options) { + var _a; + const secondaryOptions = { + ...options, + url: (_a = options.url) === null || _a === void 0 ? void 0 : _a.toString().replace(getBaseUrl(), getBaseUrl(exports.SECONDARY_HOST_ADDRESS)), + }; + // We race a connection between DNS/IP to metadata server. There are a couple + // reasons for this: + // + // 1. the DNS is slow in some GCP environments; by checking both, we might + // detect the runtime environment signficantly faster. + // 2. we can't just check the IP, which is tarpitted and slow to respond + // on a user's local machine. + // + // Additional logic has been added to make sure that we don't create an + // unhandled rejection in scenarios where a failure happens sometime + // after a success. + // + // Note, however, if a failure happens prior to a success, a rejection should + // occur, this is for folks running locally. + // + let responded = false; + const r1 = (0, gaxios_1.request)(options) + .then(res => { + responded = true; + return res; + }) + .catch(err => { + if (responded) { + return r2; + } + else { + responded = true; + throw err; + } + }); + const r2 = (0, gaxios_1.request)(secondaryOptions) + .then(res => { + responded = true; + return res; + }) + .catch(err => { + if (responded) { + return r1; + } + else { + responded = true; + throw err; + } + }); + return Promise.race([r1, r2]); +} +/** + * Obtain metadata for the current GCE instance. + * + * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} + * + * @example + * ``` + * const serviceAccount: {} = await instance('service-accounts/'); + * const serviceAccountEmail: string = await instance('service-accounts/default/email'); + * ``` + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function instance(options) { + return metadataAccessor('instance', options); +} +/** + * Obtain metadata for the current GCP project. + * + * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} + * + * @example + * ``` + * const projectId: string = await project('project-id'); + * const numericProjectId: number = await project('numeric-project-id'); + * ``` + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function project(options) { + return metadataAccessor('project', options); +} +/** + * Obtain metadata for the current universe. + * + * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} + * + * @example + * ``` + * const universeDomain: string = await universe('universe-domain'); + * ``` + */ +function universe(options) { + return metadataAccessor('universe', options); +} +/** + * Retrieve metadata items in parallel. + * + * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} + * + * @example + * ``` + * const data = await bulk([ + * { + * metadataKey: 'instance', + * }, + * { + * metadataKey: 'project/project-id', + * }, + * ] as const); + * + * // data.instance; + * // data['project/project-id']; + * ``` + * + * @param properties The metadata properties to retrieve + * @returns The metadata in `metadatakey:value` format + */ +async function bulk(properties) { + const r = {}; + await Promise.all(properties.map(item => { + return (async () => { + const res = await metadataAccessor(item); + const key = item.metadataKey; + r[key] = res; + })(); + })); + return r; +} +/* + * How many times should we retry detecting GCP environment. + */ +function detectGCPAvailableRetries() { + return process.env.DETECT_GCP_RETRIES + ? Number(process.env.DETECT_GCP_RETRIES) + : 0; +} +let cachedIsAvailableResponse; +/** + * Determine if the metadata server is currently available. + */ +async function isAvailable() { + if (process.env.METADATA_SERVER_DETECTION) { + const value = process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase(); + if (!(value in exports.METADATA_SERVER_DETECTION)) { + throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${value}\`, but it should be \`${Object.keys(exports.METADATA_SERVER_DETECTION).join('`, `')}\`, or unset`); + } + switch (value) { + case 'assume-present': + return true; + case 'none': + return false; + case 'bios-only': + return getGCPResidency(); + case 'ping-only': + // continue, we want to ping the server + } + } + try { + // If a user is instantiating several GCP libraries at the same time, + // this may result in multiple calls to isAvailable(), to detect the + // runtime environment. We use the same promise for each of these calls + // to reduce the network load. + if (cachedIsAvailableResponse === undefined) { + cachedIsAvailableResponse = metadataAccessor('instance', undefined, detectGCPAvailableRetries(), + // If the default HOST_ADDRESS has been overridden, we should not + // make an effort to try SECONDARY_HOST_ADDRESS (as we are likely in + // a non-GCP environment): + !(process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST)); + } + await cachedIsAvailableResponse; + return true; + } + catch (e) { + const err = e; + if (process.env.DEBUG_AUTH) { + console.info(err); + } + if (err.type === 'request-timeout') { + // If running in a GCP environment, metadata endpoint should return + // within ms. + return false; + } + if (err.response && err.response.status === 404) { + return false; + } + else { + if (!(err.response && err.response.status === 404) && + // A warning is emitted if we see an unexpected err.code, or err.code + // is not populated: + (!err.code || + ![ + 'EHOSTDOWN', + 'EHOSTUNREACH', + 'ENETUNREACH', + 'ENOENT', + 'ENOTFOUND', + 'ECONNREFUSED', + ].includes(err.code))) { + let code = 'UNKNOWN'; + if (err.code) + code = err.code; + process.emitWarning(`received unexpected error = ${err.message} code = ${code}`, 'MetadataLookupWarning'); + } + // Failure to resolve the metadata service means that it is not available. + return false; + } + } +} +/** + * reset the memoized isAvailable() lookup. + */ +function resetIsAvailableCache() { + cachedIsAvailableResponse = undefined; +} +/** + * A cache for the detected GCP Residency. + */ +exports.gcpResidencyCache = null; +/** + * Detects GCP Residency. + * Caches results to reduce costs for subsequent calls. + * + * @see setGCPResidency for setting + */ +function getGCPResidency() { + if (exports.gcpResidencyCache === null) { + setGCPResidency(); + } + return exports.gcpResidencyCache; +} +/** + * Sets the detected GCP Residency. + * Useful for forcing metadata server detection behavior. + * + * Set `null` to autodetect the environment (default behavior). + * @see getGCPResidency for getting + */ +function setGCPResidency(value = null) { + exports.gcpResidencyCache = value !== null ? value : (0, gcp_residency_1.detectGCPResidency)(); +} +/** + * Obtain the timeout for requests to the metadata server. + * + * In certain environments and conditions requests can take longer than + * the default timeout to complete. This function will determine the + * appropriate timeout based on the environment. + * + * @returns {number} a request timeout duration in milliseconds. + */ +function requestTimeout() { + return getGCPResidency() ? 0 : 3000; +} +__exportStar(require("./gcp-residency"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/gcp-metadata/build/src/index.js.map b/node_modules/gcp-metadata/build/src/index.js.map new file mode 100644 index 0000000..eace797 --- /dev/null +++ b/node_modules/gcp-metadata/build/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;AA8OH,4BAEC;AAcD,0BAEC;AAYD,4BAEC;AAyBD,oBAkBC;AAgBD,kCAmFC;AAKD,sDAEC;AAaD,0CAMC;AASD,0CAEC;AAWD,wCAEC;AA5cD,mCAA2E;AAE3E,0CAA2C;AAC3C,mDAAmD;AACnD,+CAA+C;AAElC,QAAA,SAAS,GAAG,qBAAqB,CAAC;AAClC,QAAA,YAAY,GAAG,wBAAwB,CAAC;AACxC,QAAA,sBAAsB,GAAG,kCAAkC,CAAC;AAE5D,QAAA,WAAW,GAAG,iBAAiB,CAAC;AAChC,QAAA,YAAY,GAAG,QAAQ,CAAC;AACxB,QAAA,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,EAAC,CAAC,mBAAW,CAAC,EAAE,oBAAY,EAAC,CAAC,CAAC;AAEpE,MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;AAEvC;;;;GAIG;AACU,QAAA,yBAAyB,GAAG,MAAM,CAAC,MAAM,CAAC;IACrD,gBAAgB,EACd,gEAAgE;IAClE,IAAI,EAAE,uEAAuE;IAC7E,WAAW,EACT,4EAA4E;IAC9E,WAAW,EAAE,iDAAiD;CAC/D,CAAC,CAAC;AA2BH;;;;;GAKG;AACH,SAAS,UAAU,CAAC,OAAgB;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AG,CAAC,OAAO,WAAW,IAAI,EAAE,EAC3D,uBAAuB,CACxB,CAAC;YACJ,CAAC;YAED,0EAA0E;YAC1E,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;AACH,CAAC;AAED;;GAEG;AACH,SAAgB,qBAAqB;IACnC,yBAAyB,GAAG,SAAS,CAAC;AACxC,CAAC;AAED;;GAEG;AACQ,QAAA,iBAAiB,GAAmB,IAAI,CAAC;AAEpD;;;;;GAKG;AACH,SAAgB,eAAe;IAC7B,IAAI,yBAAiB,KAAK,IAAI,EAAE,CAAC;QAC/B,eAAe,EAAE,CAAC;IACpB,CAAC;IAED,OAAO,yBAAkB,CAAC;AAC5B,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,eAAe,CAAC,QAAwB,IAAI;IAC1D,yBAAiB,GAAG,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAA,kCAAkB,GAAE,CAAC;AACpE,CAAC;AAED;;;;;;;;GAQG;AACH,SAAgB,cAAc;IAC5B,OAAO,eAAe,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AACtC,CAAC;AAED,kDAAgC"} \ No newline at end of file diff --git a/node_modules/gcp-metadata/package.json b/node_modules/gcp-metadata/package.json new file mode 100644 index 0000000..d1df1b8 --- /dev/null +++ b/node_modules/gcp-metadata/package.json @@ -0,0 +1,73 @@ +{ + "name": "gcp-metadata", + "version": "6.1.1", + "description": "Get the metadata from a Google Cloud Platform environment", + "repository": "googleapis/gcp-metadata", + "main": "./build/src/index.js", + "types": "./build/src/index.d.ts", + "files": [ + "build/src" + ], + "scripts": { + "compile": "cross-env NODE_OPTIONS=--max-old-space-size=8192 tsc -p .", + "fix": "gts fix", + "pretest": "npm run compile", + "prepare": "npm run compile", + "samples-test": "npm link && cd samples/ && npm link ../ && npm test && cd ../", + "presystem-test": "npm run compile", + "system-test": "mocha build/system-test --timeout 600000", + "test": "c8 mocha --timeout=5000 build/test", + "docs": "jsdoc -c .jsdoc.js", + "lint": "gts check", + "docs-test": "linkinator docs", + "predocs-test": "npm run docs", + "prelint": "cd samples; npm link ../; npm install", + "clean": "gts clean", + "precompile": "gts clean" + }, + "keywords": [ + "google cloud platform", + "google cloud", + "google", + "app engine", + "compute engine", + "metadata server", + "metadata" + ], + "author": "Google LLC", + "license": "Apache-2.0", + "dependencies": { + "gaxios": "^6.1.1", + "google-logging-utils": "^0.0.2", + "json-bigint": "^1.0.0" + }, + "devDependencies": { + "@google-cloud/functions": "^3.0.0", + "@types/json-bigint": "^1.0.0", + "@types/mocha": "^9.0.0", + "@types/ncp": "^2.0.1", + "@types/node": "^20.0.0", + "@types/sinon": "^17.0.0", + "@types/tmp": "0.2.6", + "@types/uuid": "^9.0.0", + "c8": "^9.0.0", + "cross-env": "^7.0.3", + "gcbuild": "^1.3.4", + "gcx": "^1.0.0", + "gts": "^5.0.0", + "linkinator": "^3.0.0", + "jsdoc": "^4.0.0", + "jsdoc-fresh": "^3.0.0", + "jsdoc-region-tag": "^3.0.0", + "mocha": "^8.0.0", + "ncp": "^2.0.0", + "nock": "^13.0.0", + "sinon": "^17.0.0", + "tmp": "^0.2.0", + "typescript": "^5.1.6", + "uuid": "^9.0.0" + }, + "engines": { + "node": ">=14" + } +} diff --git a/node_modules/get-caller-file/LICENSE.md b/node_modules/get-caller-file/LICENSE.md new file mode 100644 index 0000000..bf3e1c0 --- /dev/null +++ b/node_modules/get-caller-file/LICENSE.md @@ -0,0 +1,6 @@ +ISC License (ISC) +Copyright 2018 Stefan Penner + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/get-caller-file/README.md b/node_modules/get-caller-file/README.md new file mode 100644 index 0000000..a7d8c07 --- /dev/null +++ b/node_modules/get-caller-file/README.md @@ -0,0 +1,41 @@ +# get-caller-file + +[![Build Status](https://travis-ci.org/stefanpenner/get-caller-file.svg?branch=master)](https://travis-ci.org/stefanpenner/get-caller-file) +[![Build status](https://ci.appveyor.com/api/projects/status/ol2q94g1932cy14a/branch/master?svg=true)](https://ci.appveyor.com/project/embercli/get-caller-file/branch/master) + +This is a utility, which allows a function to figure out from which file it was invoked. It does so by inspecting v8's stack trace at the time it is invoked. + +Inspired by http://stackoverflow.com/questions/13227489 + +*note: this relies on Node/V8 specific APIs, as such other runtimes may not work* + +## Installation + +```bash +yarn add get-caller-file +``` + +## Usage + +Given: + +```js +// ./foo.js +const getCallerFile = require('get-caller-file'); + +module.exports = function() { + return getCallerFile(); // figures out who called it +}; +``` + +```js +// index.js +const foo = require('./foo'); + +foo() // => /full/path/to/this/file/index.js +``` + + +## Options: + +* `getCallerFile(position = 2)`: where position is stack frame whos fileName we want. diff --git a/node_modules/get-caller-file/index.d.ts b/node_modules/get-caller-file/index.d.ts new file mode 100644 index 0000000..babed69 --- /dev/null +++ b/node_modules/get-caller-file/index.d.ts @@ -0,0 +1,2 @@ +declare const _default: (position?: number) => any; +export = _default; diff --git a/node_modules/get-caller-file/index.js b/node_modules/get-caller-file/index.js new file mode 100644 index 0000000..57304f8 --- /dev/null +++ b/node_modules/get-caller-file/index.js @@ -0,0 +1,22 @@ +"use strict"; +// Call this function in a another function to find out the file from +// which that function was called from. (Inspects the v8 stack trace) +// +// Inspired by http://stackoverflow.com/questions/13227489 +module.exports = function getCallerFile(position) { + if (position === void 0) { position = 2; } + if (position >= Error.stackTraceLimit) { + throw new TypeError('getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `' + position + '` and Error.stackTraceLimit was: `' + Error.stackTraceLimit + '`'); + } + var oldPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = function (_, stack) { return stack; }; + var stack = new Error().stack; + Error.prepareStackTrace = oldPrepareStackTrace; + if (stack !== null && typeof stack === 'object') { + // stack[0] holds this file + // stack[1] holds where this function was called + // stack[2] holds the file we're interested in + return stack[position] ? stack[position].getFileName() : undefined; + } +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/get-caller-file/index.js.map b/node_modules/get-caller-file/index.js.map new file mode 100644 index 0000000..89c655c --- /dev/null +++ b/node_modules/get-caller-file/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";AAAA,qEAAqE;AACrE,qEAAqE;AACrE,EAAE;AACF,0DAA0D;AAE1D,iBAAS,SAAS,aAAa,CAAC,QAAY;IAAZ,yBAAA,EAAA,YAAY;IAC1C,IAAI,QAAQ,IAAI,KAAK,CAAC,eAAe,EAAE;QACrC,MAAM,IAAI,SAAS,CAAC,kGAAkG,GAAG,QAAQ,GAAG,oCAAoC,GAAG,KAAK,CAAC,eAAe,GAAG,GAAG,CAAC,CAAC;KACzM;IAED,IAAM,oBAAoB,GAAG,KAAK,CAAC,iBAAiB,CAAC;IACrD,KAAK,CAAC,iBAAiB,GAAG,UAAC,CAAC,EAAE,KAAK,IAAM,OAAA,KAAK,EAAL,CAAK,CAAC;IAC/C,IAAM,KAAK,GAAG,IAAI,KAAK,EAAE,CAAC,KAAK,CAAC;IAChC,KAAK,CAAC,iBAAiB,GAAG,oBAAoB,CAAC;IAG/C,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC/C,2BAA2B;QAC3B,gDAAgD;QAChD,8CAA8C;QAC9C,OAAO,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAE,KAAK,CAAC,QAAQ,CAAS,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;KAC7E;AACH,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/get-caller-file/package.json b/node_modules/get-caller-file/package.json new file mode 100644 index 0000000..b0dd571 --- /dev/null +++ b/node_modules/get-caller-file/package.json @@ -0,0 +1,42 @@ +{ + "name": "get-caller-file", + "version": "2.0.5", + "description": "", + "main": "index.js", + "directories": { + "test": "tests" + }, + "files": [ + "index.js", + "index.js.map", + "index.d.ts" + ], + "scripts": { + "prepare": "tsc", + "test": "mocha test", + "test:debug": "mocha test" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/stefanpenner/get-caller-file.git" + }, + "author": "Stefan Penner", + "license": "ISC", + "bugs": { + "url": "https://github.com/stefanpenner/get-caller-file/issues" + }, + "homepage": "https://github.com/stefanpenner/get-caller-file#readme", + "devDependencies": { + "@types/chai": "^4.1.7", + "@types/ensure-posix-path": "^1.0.0", + "@types/mocha": "^5.2.6", + "@types/node": "^11.10.5", + "chai": "^4.1.2", + "ensure-posix-path": "^1.0.1", + "mocha": "^5.2.0", + "typescript": "^3.3.3333" + }, + "engines": { + "node": "6.* || 8.* || >= 10.*" + } +} diff --git a/node_modules/get-intrinsic/.eslintrc b/node_modules/get-intrinsic/.eslintrc new file mode 100644 index 0000000..235fb79 --- /dev/null +++ b/node_modules/get-intrinsic/.eslintrc @@ -0,0 +1,42 @@ +{ + "root": true, + + "extends": "@ljharb", + + "env": { + "es6": true, + "es2017": true, + "es2020": true, + "es2021": true, + "es2022": true, + }, + + "globals": { + "Float16Array": false, + }, + + "rules": { + "array-bracket-newline": 0, + "complexity": 0, + "eqeqeq": [2, "allow-null"], + "func-name-matching": 0, + "id-length": 0, + "max-lines": 0, + "max-lines-per-function": [2, 90], + "max-params": [2, 4], + "max-statements": 0, + "max-statements-per-line": [2, { "max": 2 }], + "multiline-comment-style": 0, + "no-magic-numbers": 0, + "sort-keys": 0, + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "new-cap": 0, + }, + }, + ], +} diff --git a/node_modules/get-intrinsic/.github/FUNDING.yml b/node_modules/get-intrinsic/.github/FUNDING.yml new file mode 100644 index 0000000..8e8da0d --- /dev/null +++ b/node_modules/get-intrinsic/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/get-intrinsic +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/get-intrinsic/.nycrc b/node_modules/get-intrinsic/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/get-intrinsic/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/get-intrinsic/CHANGELOG.md b/node_modules/get-intrinsic/CHANGELOG.md new file mode 100644 index 0000000..ce1dd98 --- /dev/null +++ b/node_modules/get-intrinsic/CHANGELOG.md @@ -0,0 +1,186 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.3.0](https://github.com/ljharb/get-intrinsic/compare/v1.2.7...v1.3.0) - 2025-02-22 + +### Commits + +- [Dev Deps] update `es-abstract`, `es-value-fixtures`, `for-each`, `object-inspect` [`9b61553`](https://github.com/ljharb/get-intrinsic/commit/9b61553c587f1c1edbd435597e88c7d387da97dd) +- [Deps] update `call-bind-apply-helpers`, `es-object-atoms`, `get-proto` [`a341fee`](https://github.com/ljharb/get-intrinsic/commit/a341fee0f39a403b0f0069e82c97642d5eb11043) +- [New] add `Float16Array` [`de22116`](https://github.com/ljharb/get-intrinsic/commit/de22116b492fb989a0341bceb6e573abfaed73dc) + +## [v1.2.7](https://github.com/ljharb/get-intrinsic/compare/v1.2.6...v1.2.7) - 2025-01-02 + +### Commits + +- [Refactor] use `get-proto` directly [`00ab955`](https://github.com/ljharb/get-intrinsic/commit/00ab95546a0980c8ad42a84253daaa8d2adcedf9) +- [Deps] update `math-intrinsics` [`c716cdd`](https://github.com/ljharb/get-intrinsic/commit/c716cdd6bbe36b438057025561b8bb5a879ac8a0) +- [Dev Deps] update `call-bound`, `es-abstract` [`dc648a6`](https://github.com/ljharb/get-intrinsic/commit/dc648a67eb359037dff8d8619bfa71d86debccb1) + +## [v1.2.6](https://github.com/ljharb/get-intrinsic/compare/v1.2.5...v1.2.6) - 2024-12-11 + +### Commits + +- [Refactor] use `math-intrinsics` [`841be86`](https://github.com/ljharb/get-intrinsic/commit/841be8641a9254c4c75483b30c8871b5d5065926) +- [Refactor] use `es-object-atoms` [`42057df`](https://github.com/ljharb/get-intrinsic/commit/42057dfa16f66f64787e66482af381cc6f31d2c1) +- [Deps] update `call-bind-apply-helpers` [`45afa24`](https://github.com/ljharb/get-intrinsic/commit/45afa24a9ee4d6d3c172db1f555b16cb27843ef4) +- [Dev Deps] update `call-bound` [`9cba9c6`](https://github.com/ljharb/get-intrinsic/commit/9cba9c6e70212bc163b7a5529cb25df46071646f) + +## [v1.2.5](https://github.com/ljharb/get-intrinsic/compare/v1.2.4...v1.2.5) - 2024-12-06 + +### Commits + +- [actions] split out node 10-20, and 20+ [`6e2b9dd`](https://github.com/ljharb/get-intrinsic/commit/6e2b9dd23902665681ebe453256ccfe21d7966f0) +- [Refactor] use `dunder-proto` and `call-bind-apply-helpers` instead of `has-proto` [`c095d17`](https://github.com/ljharb/get-intrinsic/commit/c095d179ad0f4fbfff20c8a3e0cb4fe668018998) +- [Refactor] use `gopd` [`9841d5b`](https://github.com/ljharb/get-intrinsic/commit/9841d5b35f7ab4fd2d193f0c741a50a077920e90) +- [Dev Deps] update `@ljharb/eslint-config`, `auto-changelog`, `es-abstract`, `es-value-fixtures`, `gopd`, `mock-property`, `object-inspect`, `tape` [`2d07e01`](https://github.com/ljharb/get-intrinsic/commit/2d07e01310cee2cbaedfead6903df128b1f5d425) +- [Deps] update `gopd`, `has-proto`, `has-symbols`, `hasown` [`974d8bf`](https://github.com/ljharb/get-intrinsic/commit/974d8bf5baad7939eef35c25cc1dd88c10a30fa6) +- [Dev Deps] update `call-bind`, `es-abstract`, `tape` [`df9dde1`](https://github.com/ljharb/get-intrinsic/commit/df9dde178186631ab8a3165ede056549918ce4bc) +- [Refactor] cache `es-define-property` as well [`43ef543`](https://github.com/ljharb/get-intrinsic/commit/43ef543cb02194401420e3a914a4ca9168691926) +- [Deps] update `has-proto`, `has-symbols`, `hasown` [`ad4949d`](https://github.com/ljharb/get-intrinsic/commit/ad4949d5467316505aad89bf75f9417ed782f7af) +- [Tests] use `call-bound` directly [`ad5c406`](https://github.com/ljharb/get-intrinsic/commit/ad5c4069774bfe90e520a35eead5fe5ca9d69e80) +- [Deps] update `has-proto`, `hasown` [`45414ca`](https://github.com/ljharb/get-intrinsic/commit/45414caa312333a2798953682c68f85c550627dd) +- [Tests] replace `aud` with `npm audit` [`18d3509`](https://github.com/ljharb/get-intrinsic/commit/18d3509f79460e7924da70409ee81e5053087523) +- [Deps] update `es-define-property` [`aadaa3b`](https://github.com/ljharb/get-intrinsic/commit/aadaa3b2188d77ad9bff394ce5d4249c49eb21f5) +- [Dev Deps] add missing peer dep [`c296a16`](https://github.com/ljharb/get-intrinsic/commit/c296a16246d0c9a5981944f4cc5cf61fbda0cf6a) + +## [v1.2.4](https://github.com/ljharb/get-intrinsic/compare/v1.2.3...v1.2.4) - 2024-02-05 + +### Commits + +- [Refactor] use all 7 <+ ES6 Errors from `es-errors` [`bcac811`](https://github.com/ljharb/get-intrinsic/commit/bcac811abdc1c982e12abf848a410d6aae148d14) + +## [v1.2.3](https://github.com/ljharb/get-intrinsic/compare/v1.2.2...v1.2.3) - 2024-02-03 + +### Commits + +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`f11db9c`](https://github.com/ljharb/get-intrinsic/commit/f11db9c4fb97d87bbd53d3c73ac6b3db3613ad3b) +- [Dev Deps] update `aud`, `es-abstract`, `mock-property`, `npmignore` [`b7ac7d1`](https://github.com/ljharb/get-intrinsic/commit/b7ac7d1616fefb03877b1aed0c8f8d61aad32b6c) +- [meta] simplify `exports` [`faa0cc6`](https://github.com/ljharb/get-intrinsic/commit/faa0cc618e2830ffb51a8202490b0c215d965cbc) +- [meta] add missing `engines.node` [`774dd0b`](https://github.com/ljharb/get-intrinsic/commit/774dd0b3e8f741c3f05a6322d124d6087f146af1) +- [Dev Deps] update `tape` [`5828e8e`](https://github.com/ljharb/get-intrinsic/commit/5828e8e4a04e69312e87a36c0ea39428a7a4c3d8) +- [Robustness] use null objects for lookups [`eb9a11f`](https://github.com/ljharb/get-intrinsic/commit/eb9a11fa9eb3e13b193fcc05a7fb814341b1a7b7) +- [meta] add `sideEffects` flag [`89bcc7a`](https://github.com/ljharb/get-intrinsic/commit/89bcc7a42e19bf07b7c21e3094d5ab177109e6d2) + +## [v1.2.2](https://github.com/ljharb/get-intrinsic/compare/v1.2.1...v1.2.2) - 2023-10-20 + +### Commits + +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `call-bind`, `es-abstract`, `mock-property`, `object-inspect`, `tape` [`f51bcf2`](https://github.com/ljharb/get-intrinsic/commit/f51bcf26412d58d17ce17c91c9afd0ad271f0762) +- [Refactor] use `hasown` instead of `has` [`18d14b7`](https://github.com/ljharb/get-intrinsic/commit/18d14b799bea6b5765e1cec91890830cbcdb0587) +- [Deps] update `function-bind` [`6e109c8`](https://github.com/ljharb/get-intrinsic/commit/6e109c81e03804cc5e7824fb64353cdc3d8ee2c7) + +## [v1.2.1](https://github.com/ljharb/get-intrinsic/compare/v1.2.0...v1.2.1) - 2023-05-13 + +### Commits + +- [Fix] avoid a crash in envs without `__proto__` [`7bad8d0`](https://github.com/ljharb/get-intrinsic/commit/7bad8d061bf8721733b58b73a2565af2b6756b64) +- [Dev Deps] update `es-abstract` [`c60e6b7`](https://github.com/ljharb/get-intrinsic/commit/c60e6b7b4cf9660c7f27ed970970fd55fac48dc5) + +## [v1.2.0](https://github.com/ljharb/get-intrinsic/compare/v1.1.3...v1.2.0) - 2023-01-19 + +### Commits + +- [actions] update checkout action [`ca6b12f`](https://github.com/ljharb/get-intrinsic/commit/ca6b12f31eaacea4ea3b055e744cd61623385ffb) +- [Dev Deps] update `@ljharb/eslint-config`, `es-abstract`, `object-inspect`, `tape` [`41a3727`](https://github.com/ljharb/get-intrinsic/commit/41a3727d0026fa04273ae216a5f8e12eefd72da8) +- [Fix] ensure `Error.prototype` is undeniable [`c511e97`](https://github.com/ljharb/get-intrinsic/commit/c511e97ae99c764c4524b540dee7a70757af8da3) +- [Dev Deps] update `aud`, `es-abstract`, `tape` [`1bef8a8`](https://github.com/ljharb/get-intrinsic/commit/1bef8a8fd439ebb80863199b6189199e0851ac67) +- [Dev Deps] update `aud`, `es-abstract` [`0d41f16`](https://github.com/ljharb/get-intrinsic/commit/0d41f16bcd500bc28b7bfc98043ebf61ea081c26) +- [New] add `BigInt64Array` and `BigUint64Array` [`a6cca25`](https://github.com/ljharb/get-intrinsic/commit/a6cca25f29635889b7e9bd669baf9e04be90e48c) +- [Tests] use `gopd` [`ecf7722`](https://github.com/ljharb/get-intrinsic/commit/ecf7722240d15cfd16edda06acf63359c10fb9bd) + +## [v1.1.3](https://github.com/ljharb/get-intrinsic/compare/v1.1.2...v1.1.3) - 2022-09-12 + +### Commits + +- [Dev Deps] update `es-abstract`, `es-value-fixtures`, `tape` [`07ff291`](https://github.com/ljharb/get-intrinsic/commit/07ff291816406ebe5a12d7f16965bde0942dd688) +- [Fix] properly check for % signs [`50ac176`](https://github.com/ljharb/get-intrinsic/commit/50ac1760fe99c227e64eabde76e9c0e44cd881b5) + +## [v1.1.2](https://github.com/ljharb/get-intrinsic/compare/v1.1.1...v1.1.2) - 2022-06-08 + +### Fixed + +- [Fix] properly validate against extra % signs [`#16`](https://github.com/ljharb/get-intrinsic/issues/16) + +### Commits + +- [actions] reuse common workflows [`0972547`](https://github.com/ljharb/get-intrinsic/commit/0972547efd0abc863fe4c445a6ca7eb4f8c6901d) +- [meta] use `npmignore` to autogenerate an npmignore file [`5ba0b51`](https://github.com/ljharb/get-intrinsic/commit/5ba0b51d8d8d4f1c31d426d74abc0770fd106bad) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`c364492`](https://github.com/ljharb/get-intrinsic/commit/c364492af4af51333e6f81c0bf21fd3d602c3661) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `es-abstract`, `object-inspect`, `tape` [`dc04dad`](https://github.com/ljharb/get-intrinsic/commit/dc04dad86f6e5608775a2640cb0db5927ae29ed9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `es-abstract`, `object-inspect`, `safe-publish-latest`, `tape` [`1c14059`](https://github.com/ljharb/get-intrinsic/commit/1c1405984e86dd2dc9366c15d8a0294a96a146a5) +- [Tests] use `mock-property` [`b396ef0`](https://github.com/ljharb/get-intrinsic/commit/b396ef05bb73b1d699811abd64b0d9b97997fdda) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `object-inspect`, `tape` [`c2c758d`](https://github.com/ljharb/get-intrinsic/commit/c2c758d3b90af4fef0a76910d8d3c292ec8d1d3e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `es-abstract`, `es-value-fixtures`, `object-inspect`, `tape` [`29e3c09`](https://github.com/ljharb/get-intrinsic/commit/29e3c091c2bf3e17099969847e8729d0e46896de) +- [actions] update codecov uploader [`8cbc141`](https://github.com/ljharb/get-intrinsic/commit/8cbc1418940d7a8941f3a7985cbc4ac095c5e13d) +- [Dev Deps] update `@ljharb/eslint-config`, `es-abstract`, `es-value-fixtures`, `object-inspect`, `tape` [`10b6f5c`](https://github.com/ljharb/get-intrinsic/commit/10b6f5c02593fb3680c581d696ac124e30652932) +- [readme] add github actions/codecov badges [`4e25400`](https://github.com/ljharb/get-intrinsic/commit/4e25400d9f51ae9eb059cbe22d9144e70ea214e8) +- [Tests] use `for-each` instead of `foreach` [`c05b957`](https://github.com/ljharb/get-intrinsic/commit/c05b957ad9a7bc7721af7cc9e9be1edbfe057496) +- [Dev Deps] update `es-abstract` [`29b05ae`](https://github.com/ljharb/get-intrinsic/commit/29b05aec3e7330e9ad0b8e0f685a9112c20cdd97) +- [meta] use `prepublishOnly` script for npm 7+ [`95c285d`](https://github.com/ljharb/get-intrinsic/commit/95c285da810516057d3bbfa871176031af38f05d) +- [Deps] update `has-symbols` [`593cb4f`](https://github.com/ljharb/get-intrinsic/commit/593cb4fb38e7922e40e42c183f45274b636424cd) +- [readme] fix repo URLs [`1c8305b`](https://github.com/ljharb/get-intrinsic/commit/1c8305b5365827c9b6fc785434aac0e1328ff2f5) +- [Deps] update `has-symbols` [`c7138b6`](https://github.com/ljharb/get-intrinsic/commit/c7138b6c6d73132d859471fb8c13304e1e7c8b20) +- [Dev Deps] remove unused `has-bigints` [`bd63aff`](https://github.com/ljharb/get-intrinsic/commit/bd63aff6ad8f3a986c557fcda2914187bdaab359) + +## [v1.1.1](https://github.com/ljharb/get-intrinsic/compare/v1.1.0...v1.1.1) - 2021-02-03 + +### Fixed + +- [meta] export `./package.json` [`#9`](https://github.com/ljharb/get-intrinsic/issues/9) + +### Commits + +- [readme] flesh out the readme; use `evalmd` [`d12f12c`](https://github.com/ljharb/get-intrinsic/commit/d12f12c15345a0a0772cc65a7c64369529abd614) +- [eslint] set up proper globals config [`5a8c098`](https://github.com/ljharb/get-intrinsic/commit/5a8c0984e3319d1ac0e64b102f8ec18b64e79f36) +- [Dev Deps] update `eslint` [`7b9a5c0`](https://github.com/ljharb/get-intrinsic/commit/7b9a5c0d31a90ca1a1234181c74988fb046701cd) + +## [v1.1.0](https://github.com/ljharb/get-intrinsic/compare/v1.0.2...v1.1.0) - 2021-01-25 + +### Fixed + +- [Refactor] delay `Function` eval until syntax-derived values are requested [`#3`](https://github.com/ljharb/get-intrinsic/issues/3) + +### Commits + +- [Tests] migrate tests to Github Actions [`2ab762b`](https://github.com/ljharb/get-intrinsic/commit/2ab762b48164aea8af37a40ba105bbc8246ab8c4) +- [meta] do not publish github action workflow files [`5e7108e`](https://github.com/ljharb/get-intrinsic/commit/5e7108e4768b244d48d9567ba4f8a6cab9c65b8e) +- [Tests] add some coverage [`01ac7a8`](https://github.com/ljharb/get-intrinsic/commit/01ac7a87ac29738567e8524cd8c9e026b1fa8cb3) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `call-bind`, `es-abstract`, `tape`; add `call-bind` [`911b672`](https://github.com/ljharb/get-intrinsic/commit/911b672fbffae433a96924c6ce013585e425f4b7) +- [Refactor] rearrange evalled constructors a bit [`7e7e4bf`](https://github.com/ljharb/get-intrinsic/commit/7e7e4bf583f3799c8ac1c6c5e10d2cb553957347) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`0199968`](https://github.com/ljharb/get-intrinsic/commit/01999687a263ffce0a3cb011dfbcb761754aedbc) + +## [v1.0.2](https://github.com/ljharb/get-intrinsic/compare/v1.0.1...v1.0.2) - 2020-12-17 + +### Commits + +- [Fix] Throw for non‑existent intrinsics [`68f873b`](https://github.com/ljharb/get-intrinsic/commit/68f873b013c732a05ad6f5fc54f697e55515461b) +- [Fix] Throw for non‑existent segments in the intrinsic path [`8325dee`](https://github.com/ljharb/get-intrinsic/commit/8325deee43128f3654d3399aa9591741ebe17b21) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-bigints`, `object-inspect` [`0c227a7`](https://github.com/ljharb/get-intrinsic/commit/0c227a7d8b629166f25715fd242553892e458525) +- [meta] do not lint coverage output [`70d2419`](https://github.com/ljharb/get-intrinsic/commit/70d24199b620043cd9110fc5f426d214ebe21dc9) + +## [v1.0.1](https://github.com/ljharb/get-intrinsic/compare/v1.0.0...v1.0.1) - 2020-10-30 + +### Commits + +- [Tests] gather coverage data on every job [`d1d280d`](https://github.com/ljharb/get-intrinsic/commit/d1d280dec714e3f0519cc877dbcb193057d9cac6) +- [Fix] add missing dependencies [`5031771`](https://github.com/ljharb/get-intrinsic/commit/5031771bb1095b38be88ce7c41d5de88718e432e) +- [Tests] use `es-value-fixtures` [`af48765`](https://github.com/ljharb/get-intrinsic/commit/af48765a23c5323fb0b6b38dbf00eb5099c7bebc) + +## v1.0.0 - 2020-10-29 + +### Commits + +- Implementation [`bbce57c`](https://github.com/ljharb/get-intrinsic/commit/bbce57c6f33d05b2d8d3efa273ceeb3ee01127bb) +- Tests [`17b4f0d`](https://github.com/ljharb/get-intrinsic/commit/17b4f0d56dea6b4059b56fc30ef3ee4d9500ebc2) +- Initial commit [`3153294`](https://github.com/ljharb/get-intrinsic/commit/31532948de363b0a27dd9fd4649e7b7028ec4b44) +- npm init [`fb326c4`](https://github.com/ljharb/get-intrinsic/commit/fb326c4d2817c8419ec31de1295f06bb268a7902) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`48862fb`](https://github.com/ljharb/get-intrinsic/commit/48862fb2508c8f6a57968e6d08b7c883afc9d550) +- [meta] add `auto-changelog` [`5f28ad0`](https://github.com/ljharb/get-intrinsic/commit/5f28ad019e060a353d8028f9f2591a9cc93074a1) +- [meta] add "funding"; create `FUNDING.yml` [`c2bbdde`](https://github.com/ljharb/get-intrinsic/commit/c2bbddeba73a875be61484ee4680b129a6d4e0a1) +- [Tests] add `npm run lint` [`0a84b98`](https://github.com/ljharb/get-intrinsic/commit/0a84b98b22b7cf7a748666f705b0003a493c35fd) +- Only apps should have lockfiles [`9586c75`](https://github.com/ljharb/get-intrinsic/commit/9586c75866c1ee678e4d5d4dbbdef6997e511b05) diff --git a/node_modules/get-intrinsic/LICENSE b/node_modules/get-intrinsic/LICENSE new file mode 100644 index 0000000..48f05d0 --- /dev/null +++ b/node_modules/get-intrinsic/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/get-intrinsic/README.md b/node_modules/get-intrinsic/README.md new file mode 100644 index 0000000..3aa0bba --- /dev/null +++ b/node_modules/get-intrinsic/README.md @@ -0,0 +1,71 @@ +# get-intrinsic [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Get and robustly cache all JS language-level intrinsics at first require time. + +See the syntax described [in the JS spec](https://tc39.es/ecma262/#sec-well-known-intrinsic-objects) for reference. + +## Example + +```js +var GetIntrinsic = require('get-intrinsic'); +var assert = require('assert'); + +// static methods +assert.equal(GetIntrinsic('%Math.pow%'), Math.pow); +assert.equal(Math.pow(2, 3), 8); +assert.equal(GetIntrinsic('%Math.pow%')(2, 3), 8); +delete Math.pow; +assert.equal(GetIntrinsic('%Math.pow%')(2, 3), 8); + +// instance methods +var arr = [1]; +assert.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push); +assert.deepEqual(arr, [1]); + +arr.push(2); +assert.deepEqual(arr, [1, 2]); + +GetIntrinsic('%Array.prototype.push%').call(arr, 3); +assert.deepEqual(arr, [1, 2, 3]); + +delete Array.prototype.push; +GetIntrinsic('%Array.prototype.push%').call(arr, 4); +assert.deepEqual(arr, [1, 2, 3, 4]); + +// missing features +delete JSON.parse; // to simulate a real intrinsic that is missing in the environment +assert.throws(() => GetIntrinsic('%JSON.parse%')); +assert.equal(undefined, GetIntrinsic('%JSON.parse%', true)); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/get-intrinsic +[npm-version-svg]: https://versionbadg.es/ljharb/get-intrinsic.svg +[deps-svg]: https://david-dm.org/ljharb/get-intrinsic.svg +[deps-url]: https://david-dm.org/ljharb/get-intrinsic +[dev-deps-svg]: https://david-dm.org/ljharb/get-intrinsic/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/get-intrinsic#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/get-intrinsic.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/get-intrinsic.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/get-intrinsic.svg +[downloads-url]: https://npm-stat.com/charts.html?package=get-intrinsic +[codecov-image]: https://codecov.io/gh/ljharb/get-intrinsic/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/get-intrinsic/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/get-intrinsic +[actions-url]: https://github.com/ljharb/get-intrinsic/actions diff --git a/node_modules/get-intrinsic/index.js b/node_modules/get-intrinsic/index.js new file mode 100644 index 0000000..bd1d94b --- /dev/null +++ b/node_modules/get-intrinsic/index.js @@ -0,0 +1,378 @@ +'use strict'; + +var undefined; + +var $Object = require('es-object-atoms'); + +var $Error = require('es-errors'); +var $EvalError = require('es-errors/eval'); +var $RangeError = require('es-errors/range'); +var $ReferenceError = require('es-errors/ref'); +var $SyntaxError = require('es-errors/syntax'); +var $TypeError = require('es-errors/type'); +var $URIError = require('es-errors/uri'); + +var abs = require('math-intrinsics/abs'); +var floor = require('math-intrinsics/floor'); +var max = require('math-intrinsics/max'); +var min = require('math-intrinsics/min'); +var pow = require('math-intrinsics/pow'); +var round = require('math-intrinsics/round'); +var sign = require('math-intrinsics/sign'); + +var $Function = Function; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; + +var $gOPD = require('gopd'); +var $defineProperty = require('es-define-property'); + +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = require('has-symbols')(); + +var getProto = require('get-proto'); +var $ObjectGPO = require('get-proto/Object.getPrototypeOf'); +var $ReflectGPO = require('get-proto/Reflect.getPrototypeOf'); + +var $apply = require('call-bind-apply-helpers/functionApply'); +var $call = require('call-bind-apply-helpers/functionCall'); + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + __proto__: null, + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': $Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': $EvalError, + '%Float16Array%': typeof Float16Array === 'undefined' ? undefined : Float16Array, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': $Object, + '%Object.getOwnPropertyDescriptor%': $gOPD, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': $RangeError, + '%ReferenceError%': $ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': $URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, + + '%Function.prototype.call%': $call, + '%Function.prototype.apply%': $apply, + '%Object.defineProperty%': $defineProperty, + '%Object.getPrototypeOf%': $ObjectGPO, + '%Math.abs%': abs, + '%Math.floor%': floor, + '%Math.max%': max, + '%Math.min%': min, + '%Math.pow%': pow, + '%Math.round%': round, + '%Math.sign%': sign, + '%Reflect.getPrototypeOf%': $ReflectGPO +}; + +if (getProto) { + try { + null.error; // eslint-disable-line no-unused-expressions + } catch (e) { + // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 + var errorProto = getProto(getProto(e)); + INTRINSICS['%Error.prototype%'] = errorProto; + } +} + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + __proto__: null, + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; + +var bind = require('function-bind'); +var hasOwn = require('hasown'); +var $concat = bind.call($call, Array.prototype.concat); +var $spliceApply = bind.call($apply, Array.prototype.splice); +var $replace = bind.call($call, String.prototype.replace); +var $strSlice = bind.call($call, String.prototype.slice); +var $exec = bind.call($call, RegExp.prototype.exec); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; diff --git a/node_modules/get-intrinsic/package.json b/node_modules/get-intrinsic/package.json new file mode 100644 index 0000000..2828e73 --- /dev/null +++ b/node_modules/get-intrinsic/package.json @@ -0,0 +1,97 @@ +{ + "name": "get-intrinsic", + "version": "1.3.0", + "description": "Get and robustly cache all JS language-level intrinsics at first require time", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=.js,.mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>= 10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/get-intrinsic.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "es", + "js", + "intrinsic", + "getintrinsic", + "es-abstract" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/get-intrinsic/issues" + }, + "homepage": "https://github.com/ljharb/get-intrinsic#readme", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.1", + "auto-changelog": "^2.5.0", + "call-bound": "^1.0.3", + "encoding": "^0.1.13", + "es-abstract": "^1.23.9", + "es-value-fixtures": "^1.7.1", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.5", + "make-async-function": "^1.0.0", + "make-async-generator-function": "^1.0.0", + "make-generator-function": "^2.0.0", + "mock-property": "^1.1.0", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.4", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "testling": { + "files": "test/GetIntrinsic.js" + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/get-intrinsic/test/GetIntrinsic.js b/node_modules/get-intrinsic/test/GetIntrinsic.js new file mode 100644 index 0000000..d9c0f30 --- /dev/null +++ b/node_modules/get-intrinsic/test/GetIntrinsic.js @@ -0,0 +1,274 @@ +'use strict'; + +var GetIntrinsic = require('../'); + +var test = require('tape'); +var forEach = require('for-each'); +var debug = require('object-inspect'); +var generatorFns = require('make-generator-function')(); +var asyncFns = require('make-async-function').list(); +var asyncGenFns = require('make-async-generator-function')(); +var mockProperty = require('mock-property'); + +var callBound = require('call-bound'); +var v = require('es-value-fixtures'); +var $gOPD = require('gopd'); +var DefinePropertyOrThrow = require('es-abstract/2023/DefinePropertyOrThrow'); + +var $isProto = callBound('%Object.prototype.isPrototypeOf%'); + +test('export', function (t) { + t.equal(typeof GetIntrinsic, 'function', 'it is a function'); + t.equal(GetIntrinsic.length, 2, 'function has length of 2'); + + t.end(); +}); + +test('throws', function (t) { + t['throws']( + function () { GetIntrinsic('not an intrinsic'); }, + SyntaxError, + 'nonexistent intrinsic throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic(''); }, + TypeError, + 'empty string intrinsic throws a type error' + ); + + t['throws']( + function () { GetIntrinsic('.'); }, + SyntaxError, + '"just a dot" intrinsic throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic('%String'); }, + SyntaxError, + 'Leading % without trailing % throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic('String%'); }, + SyntaxError, + 'Trailing % without leading % throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic("String['prototype]"); }, + SyntaxError, + 'Dynamic property access is disallowed for intrinsics (unterminated string)' + ); + + t['throws']( + function () { GetIntrinsic('%Proxy.prototype.undefined%'); }, + TypeError, + "Throws when middle part doesn't exist (%Proxy.prototype.undefined%)" + ); + + t['throws']( + function () { GetIntrinsic('%Array.prototype%garbage%'); }, + SyntaxError, + 'Throws with extra percent signs' + ); + + t['throws']( + function () { GetIntrinsic('%Array.prototype%push%'); }, + SyntaxError, + 'Throws with extra percent signs, even on an existing intrinsic' + ); + + forEach(v.nonStrings, function (nonString) { + t['throws']( + function () { GetIntrinsic(nonString); }, + TypeError, + debug(nonString) + ' is not a String' + ); + }); + + forEach(v.nonBooleans, function (nonBoolean) { + t['throws']( + function () { GetIntrinsic('%', nonBoolean); }, + TypeError, + debug(nonBoolean) + ' is not a Boolean' + ); + }); + + forEach([ + 'toString', + 'propertyIsEnumerable', + 'hasOwnProperty' + ], function (objectProtoMember) { + t['throws']( + function () { GetIntrinsic(objectProtoMember); }, + SyntaxError, + debug(objectProtoMember) + ' is not an intrinsic' + ); + }); + + t.end(); +}); + +test('base intrinsics', function (t) { + t.equal(GetIntrinsic('%Object%'), Object, '%Object% yields Object'); + t.equal(GetIntrinsic('Object'), Object, 'Object yields Object'); + t.equal(GetIntrinsic('%Array%'), Array, '%Array% yields Array'); + t.equal(GetIntrinsic('Array'), Array, 'Array yields Array'); + + t.end(); +}); + +test('dotted paths', function (t) { + t.equal(GetIntrinsic('%Object.prototype.toString%'), Object.prototype.toString, '%Object.prototype.toString% yields Object.prototype.toString'); + t.equal(GetIntrinsic('Object.prototype.toString'), Object.prototype.toString, 'Object.prototype.toString yields Object.prototype.toString'); + t.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push, '%Array.prototype.push% yields Array.prototype.push'); + t.equal(GetIntrinsic('Array.prototype.push'), Array.prototype.push, 'Array.prototype.push yields Array.prototype.push'); + + test('underscore paths are aliases for dotted paths', { skip: !Object.isFrozen || Object.isFrozen(Object.prototype) }, function (st) { + var original = GetIntrinsic('%ObjProto_toString%'); + + forEach([ + '%Object.prototype.toString%', + 'Object.prototype.toString', + '%ObjectPrototype.toString%', + 'ObjectPrototype.toString', + '%ObjProto_toString%', + 'ObjProto_toString' + ], function (name) { + DefinePropertyOrThrow(Object.prototype, 'toString', { + '[[Value]]': function toString() { + return original.apply(this, arguments); + } + }); + st.equal(GetIntrinsic(name), original, name + ' yields original Object.prototype.toString'); + }); + + DefinePropertyOrThrow(Object.prototype, 'toString', { '[[Value]]': original }); + st.end(); + }); + + test('dotted paths cache', { skip: !Object.isFrozen || Object.isFrozen(Object.prototype) }, function (st) { + var original = GetIntrinsic('%Object.prototype.propertyIsEnumerable%'); + + forEach([ + '%Object.prototype.propertyIsEnumerable%', + 'Object.prototype.propertyIsEnumerable', + '%ObjectPrototype.propertyIsEnumerable%', + 'ObjectPrototype.propertyIsEnumerable' + ], function (name) { + var restore = mockProperty(Object.prototype, 'propertyIsEnumerable', { + value: function propertyIsEnumerable() { + return original.apply(this, arguments); + } + }); + st.equal(GetIntrinsic(name), original, name + ' yields cached Object.prototype.propertyIsEnumerable'); + + restore(); + }); + + st.end(); + }); + + test('dotted path reports correct error', function (st) { + st['throws'](function () { + GetIntrinsic('%NonExistentIntrinsic.prototype.property%'); + }, /%NonExistentIntrinsic%/, 'The base intrinsic of %NonExistentIntrinsic.prototype.property% is %NonExistentIntrinsic%'); + + st['throws'](function () { + GetIntrinsic('%NonExistentIntrinsicPrototype.property%'); + }, /%NonExistentIntrinsicPrototype%/, 'The base intrinsic of %NonExistentIntrinsicPrototype.property% is %NonExistentIntrinsicPrototype%'); + + st.end(); + }); + + t.end(); +}); + +test('accessors', { skip: !$gOPD || typeof Map !== 'function' }, function (t) { + var actual = $gOPD(Map.prototype, 'size'); + t.ok(actual, 'Map.prototype.size has a descriptor'); + t.equal(typeof actual.get, 'function', 'Map.prototype.size has a getter function'); + t.equal(GetIntrinsic('%Map.prototype.size%'), actual.get, '%Map.prototype.size% yields the getter for it'); + t.equal(GetIntrinsic('Map.prototype.size'), actual.get, 'Map.prototype.size yields the getter for it'); + + t.end(); +}); + +test('generator functions', { skip: !generatorFns.length }, function (t) { + var $GeneratorFunction = GetIntrinsic('%GeneratorFunction%'); + var $GeneratorFunctionPrototype = GetIntrinsic('%Generator%'); + var $GeneratorPrototype = GetIntrinsic('%GeneratorPrototype%'); + + forEach(generatorFns, function (genFn) { + var fnName = genFn.name; + fnName = fnName ? "'" + fnName + "'" : 'genFn'; + + t.ok(genFn instanceof $GeneratorFunction, fnName + ' instanceof %GeneratorFunction%'); + t.ok($isProto($GeneratorFunctionPrototype, genFn), '%Generator% is prototype of ' + fnName); + t.ok($isProto($GeneratorPrototype, genFn.prototype), '%GeneratorPrototype% is prototype of ' + fnName + '.prototype'); + }); + + t.end(); +}); + +test('async functions', { skip: !asyncFns.length }, function (t) { + var $AsyncFunction = GetIntrinsic('%AsyncFunction%'); + var $AsyncFunctionPrototype = GetIntrinsic('%AsyncFunctionPrototype%'); + + forEach(asyncFns, function (asyncFn) { + var fnName = asyncFn.name; + fnName = fnName ? "'" + fnName + "'" : 'asyncFn'; + + t.ok(asyncFn instanceof $AsyncFunction, fnName + ' instanceof %AsyncFunction%'); + t.ok($isProto($AsyncFunctionPrototype, asyncFn), '%AsyncFunctionPrototype% is prototype of ' + fnName); + }); + + t.end(); +}); + +test('async generator functions', { skip: asyncGenFns.length === 0 }, function (t) { + var $AsyncGeneratorFunction = GetIntrinsic('%AsyncGeneratorFunction%'); + var $AsyncGeneratorFunctionPrototype = GetIntrinsic('%AsyncGenerator%'); + var $AsyncGeneratorPrototype = GetIntrinsic('%AsyncGeneratorPrototype%'); + + forEach(asyncGenFns, function (asyncGenFn) { + var fnName = asyncGenFn.name; + fnName = fnName ? "'" + fnName + "'" : 'asyncGenFn'; + + t.ok(asyncGenFn instanceof $AsyncGeneratorFunction, fnName + ' instanceof %AsyncGeneratorFunction%'); + t.ok($isProto($AsyncGeneratorFunctionPrototype, asyncGenFn), '%AsyncGenerator% is prototype of ' + fnName); + t.ok($isProto($AsyncGeneratorPrototype, asyncGenFn.prototype), '%AsyncGeneratorPrototype% is prototype of ' + fnName + '.prototype'); + }); + + t.end(); +}); + +test('%ThrowTypeError%', function (t) { + var $ThrowTypeError = GetIntrinsic('%ThrowTypeError%'); + + t.equal(typeof $ThrowTypeError, 'function', 'is a function'); + t['throws']( + $ThrowTypeError, + TypeError, + '%ThrowTypeError% throws a TypeError' + ); + + t.end(); +}); + +test('allowMissing', { skip: asyncGenFns.length > 0 }, function (t) { + t['throws']( + function () { GetIntrinsic('%AsyncGeneratorPrototype%'); }, + TypeError, + 'throws when missing' + ); + + t.equal( + GetIntrinsic('%AsyncGeneratorPrototype%', true), + undefined, + 'does not throw when allowMissing' + ); + + t.end(); +}); diff --git a/node_modules/get-proto/.eslintrc b/node_modules/get-proto/.eslintrc new file mode 100644 index 0000000..1d21a8a --- /dev/null +++ b/node_modules/get-proto/.eslintrc @@ -0,0 +1,10 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": "off", + "sort-keys": "off", + }, +} diff --git a/node_modules/get-proto/.github/FUNDING.yml b/node_modules/get-proto/.github/FUNDING.yml new file mode 100644 index 0000000..93183ef --- /dev/null +++ b/node_modules/get-proto/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/get-proto +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/get-proto/.nycrc b/node_modules/get-proto/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/get-proto/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/get-proto/CHANGELOG.md b/node_modules/get-proto/CHANGELOG.md new file mode 100644 index 0000000..5860229 --- /dev/null +++ b/node_modules/get-proto/CHANGELOG.md @@ -0,0 +1,21 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.1](https://github.com/ljharb/get-proto/compare/v1.0.0...v1.0.1) - 2025-01-02 + +### Commits + +- [Fix] for the `Object.getPrototypeOf` window, throw for non-objects [`7fe6508`](https://github.com/ljharb/get-proto/commit/7fe6508b71419ebe1976bedb86001d1feaeaa49a) + +## v1.0.0 - 2025-01-01 + +### Commits + +- Initial implementation, tests, readme, types [`5c70775`](https://github.com/ljharb/get-proto/commit/5c707751e81c3deeb2cf980d185fc7fd43611415) +- Initial commit [`7c65c2a`](https://github.com/ljharb/get-proto/commit/7c65c2ad4e33d5dae2f219ebe1a046ae2256972c) +- npm init [`0b8cf82`](https://github.com/ljharb/get-proto/commit/0b8cf824c9634e4a34ef7dd2a2cdc5be6ac79518) +- Only apps should have lockfiles [`a6d1bff`](https://github.com/ljharb/get-proto/commit/a6d1bffc364f5828377cea7194558b2dbef7aea2) diff --git a/node_modules/get-proto/LICENSE b/node_modules/get-proto/LICENSE new file mode 100644 index 0000000..eeabd1c --- /dev/null +++ b/node_modules/get-proto/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/get-proto/Object.getPrototypeOf.d.ts b/node_modules/get-proto/Object.getPrototypeOf.d.ts new file mode 100644 index 0000000..028b3ff --- /dev/null +++ b/node_modules/get-proto/Object.getPrototypeOf.d.ts @@ -0,0 +1,5 @@ +declare function getProto(object: O): object | null; + +declare const x: typeof getProto | null; + +export = x; \ No newline at end of file diff --git a/node_modules/get-proto/Object.getPrototypeOf.js b/node_modules/get-proto/Object.getPrototypeOf.js new file mode 100644 index 0000000..c2cbbdf --- /dev/null +++ b/node_modules/get-proto/Object.getPrototypeOf.js @@ -0,0 +1,6 @@ +'use strict'; + +var $Object = require('es-object-atoms'); + +/** @type {import('./Object.getPrototypeOf')} */ +module.exports = $Object.getPrototypeOf || null; diff --git a/node_modules/get-proto/README.md b/node_modules/get-proto/README.md new file mode 100644 index 0000000..f8b4cce --- /dev/null +++ b/node_modules/get-proto/README.md @@ -0,0 +1,50 @@ +# get-proto [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Robustly get the [[Prototype]] of an object. Uses the best available method. + +## Getting started + +```sh +npm install --save get-proto +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const getProto = require('get-proto'); + +const a = { a: 1, b: 2, [Symbol.toStringTag]: 'foo' }; +const b = { c: 3, __proto__: a }; + +assert.equal(getProto(b), a); +assert.equal(getProto(a), Object.prototype); +assert.equal(getProto({ __proto__: null }), null); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/get-proto +[npm-version-svg]: https://versionbadg.es/ljharb/get-proto.svg +[deps-svg]: https://david-dm.org/ljharb/get-proto.svg +[deps-url]: https://david-dm.org/ljharb/get-proto +[dev-deps-svg]: https://david-dm.org/ljharb/get-proto/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/get-proto#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/get-proto.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/get-proto.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/get-proto.svg +[downloads-url]: https://npm-stat.com/charts.html?package=get-proto +[codecov-image]: https://codecov.io/gh/ljharb/get-proto/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/get-proto/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/get-proto +[actions-url]: https://github.com/ljharb/get-proto/actions diff --git a/node_modules/get-proto/Reflect.getPrototypeOf.d.ts b/node_modules/get-proto/Reflect.getPrototypeOf.d.ts new file mode 100644 index 0000000..2388fe0 --- /dev/null +++ b/node_modules/get-proto/Reflect.getPrototypeOf.d.ts @@ -0,0 +1,3 @@ +declare const x: typeof Reflect.getPrototypeOf | null; + +export = x; \ No newline at end of file diff --git a/node_modules/get-proto/Reflect.getPrototypeOf.js b/node_modules/get-proto/Reflect.getPrototypeOf.js new file mode 100644 index 0000000..e6c51be --- /dev/null +++ b/node_modules/get-proto/Reflect.getPrototypeOf.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./Reflect.getPrototypeOf')} */ +module.exports = (typeof Reflect !== 'undefined' && Reflect.getPrototypeOf) || null; diff --git a/node_modules/get-proto/index.d.ts b/node_modules/get-proto/index.d.ts new file mode 100644 index 0000000..2c021f3 --- /dev/null +++ b/node_modules/get-proto/index.d.ts @@ -0,0 +1,5 @@ +declare function getProto(object: O): object | null; + +declare const x: typeof getProto | null; + +export = x; diff --git a/node_modules/get-proto/index.js b/node_modules/get-proto/index.js new file mode 100644 index 0000000..7e5747b --- /dev/null +++ b/node_modules/get-proto/index.js @@ -0,0 +1,27 @@ +'use strict'; + +var reflectGetProto = require('./Reflect.getPrototypeOf'); +var originalGetProto = require('./Object.getPrototypeOf'); + +var getDunderProto = require('dunder-proto/get'); + +/** @type {import('.')} */ +module.exports = reflectGetProto + ? function getProto(O) { + // @ts-expect-error TS can't narrow inside a closure, for some reason + return reflectGetProto(O); + } + : originalGetProto + ? function getProto(O) { + if (!O || (typeof O !== 'object' && typeof O !== 'function')) { + throw new TypeError('getProto: not an object'); + } + // @ts-expect-error TS can't narrow inside a closure, for some reason + return originalGetProto(O); + } + : getDunderProto + ? function getProto(O) { + // @ts-expect-error TS can't narrow inside a closure, for some reason + return getDunderProto(O); + } + : null; diff --git a/node_modules/get-proto/package.json b/node_modules/get-proto/package.json new file mode 100644 index 0000000..9c35cec --- /dev/null +++ b/node_modules/get-proto/package.json @@ -0,0 +1,81 @@ +{ + "name": "get-proto", + "version": "1.0.1", + "description": "Robustly get the [[Prototype]] of an object", + "main": "index.js", + "exports": { + ".": "./index.js", + "./Reflect.getPrototypeOf": "./Reflect.getPrototypeOf.js", + "./Object.getPrototypeOf": "./Object.getPrototypeOf.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "pretest": "npm run --silent lint", + "test": "npm run tests-only", + "posttest": "npx npm@\">=10.2\" audit --production", + "tests-only": "nyc tape 'test/**/*.js'", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc && attw -P", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/get-proto.git" + }, + "keywords": [ + "get", + "proto", + "prototype", + "getPrototypeOf", + "[[Prototype]]" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/get-proto/issues" + }, + "homepage": "https://github.com/ljharb/get-proto#readme", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.2", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.3", + "@types/tape": "^5.8.0", + "auto-changelog": "^2.5.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "testling": { + "files": "test/index.js" + } +} diff --git a/node_modules/get-proto/test/index.js b/node_modules/get-proto/test/index.js new file mode 100644 index 0000000..5a2ece2 --- /dev/null +++ b/node_modules/get-proto/test/index.js @@ -0,0 +1,68 @@ +'use strict'; + +var test = require('tape'); + +var getProto = require('../'); + +test('getProto', function (t) { + t.equal(typeof getProto, 'function', 'is a function'); + + t.test('can get', { skip: !getProto }, function (st) { + if (getProto) { // TS doesn't understand tape's skip + var proto = { b: 2 }; + st.equal(getProto(proto), Object.prototype, 'proto: returns the [[Prototype]]'); + + st.test('nullish value', function (s2t) { + // @ts-expect-error + s2t['throws'](function () { return getProto(undefined); }, TypeError, 'undefined is not an object'); + // @ts-expect-error + s2t['throws'](function () { return getProto(null); }, TypeError, 'null is not an object'); + s2t.end(); + }); + + // @ts-expect-error + st['throws'](function () { getProto(true); }, 'throws for true'); + // @ts-expect-error + st['throws'](function () { getProto(false); }, 'throws for false'); + // @ts-expect-error + st['throws'](function () { getProto(42); }, 'throws for 42'); + // @ts-expect-error + st['throws'](function () { getProto(NaN); }, 'throws for NaN'); + // @ts-expect-error + st['throws'](function () { getProto(0); }, 'throws for +0'); + // @ts-expect-error + st['throws'](function () { getProto(-0); }, 'throws for -0'); + // @ts-expect-error + st['throws'](function () { getProto(Infinity); }, 'throws for ∞'); + // @ts-expect-error + st['throws'](function () { getProto(-Infinity); }, 'throws for -∞'); + // @ts-expect-error + st['throws'](function () { getProto(''); }, 'throws for empty string'); + // @ts-expect-error + st['throws'](function () { getProto('foo'); }, 'throws for non-empty string'); + st.equal(getProto(/a/g), RegExp.prototype); + st.equal(getProto(new Date()), Date.prototype); + st.equal(getProto(function () {}), Function.prototype); + st.equal(getProto([]), Array.prototype); + st.equal(getProto({}), Object.prototype); + + var nullObject = { __proto__: null }; + if ('toString' in nullObject) { + st.comment('no null objects in this engine'); + st.equal(getProto(nullObject), Object.prototype, '"null" object has Object.prototype as [[Prototype]]'); + } else { + st.equal(getProto(nullObject), null, 'null object has null [[Prototype]]'); + } + } + + st.end(); + }); + + t.test('can not get', { skip: !!getProto }, function (st) { + st.equal(getProto, null); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/get-proto/tsconfig.json b/node_modules/get-proto/tsconfig.json new file mode 100644 index 0000000..60fb90e --- /dev/null +++ b/node_modules/get-proto/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + //"target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/google-auth-library/CHANGELOG.md b/node_modules/google-auth-library/CHANGELOG.md new file mode 100644 index 0000000..dc942a7 --- /dev/null +++ b/node_modules/google-auth-library/CHANGELOG.md @@ -0,0 +1,1394 @@ +# Changelog + +[npm history][1] + +[1]: https://www.npmjs.com/package/google-auth-library?activeTab=versions + +## [9.15.1](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.15.0...v9.15.1) (2025-01-24) + + +### Bug Fixes + +* Resolve typo in document ([#1901](https://github.com/googleapis/google-auth-library-nodejs/issues/1901)) ([12f2c87](https://github.com/googleapis/google-auth-library-nodejs/commit/12f2c87266de0a3ccd33e6b4993cab3537f9a242)) + +## [9.15.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.14.2...v9.15.0) (2024-11-01) + + +### Features + +* Impersonated Universe Domain Support ([#1875](https://github.com/googleapis/google-auth-library-nodejs/issues/1875)) ([902bf8b](https://github.com/googleapis/google-auth-library-nodejs/commit/902bf8b7faf8f7a0735011c252907282f550cd14)) + +## [9.14.2](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.14.1...v9.14.2) (2024-10-09) + + +### Bug Fixes + +* Disable Universe Domain Check ([#1878](https://github.com/googleapis/google-auth-library-nodejs/issues/1878)) ([8adb44c](https://github.com/googleapis/google-auth-library-nodejs/commit/8adb44c738b88bfc44e57b0694c3815d138a40e5)) + +## [9.14.1](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.14.0...v9.14.1) (2024-08-30) + + +### Performance Improvements + +* **GoogleAuth:** Improve Client Creation From Files/Streams Perf ([#1856](https://github.com/googleapis/google-auth-library-nodejs/issues/1856)) ([85d9d6f](https://github.com/googleapis/google-auth-library-nodejs/commit/85d9d6fe312f5ed68db22a28b84b6c8f257f9ec9)) + +## [9.14.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.13.0...v9.14.0) (2024-08-19) + + +### Features + +* Add `AnyAuthClient` type ([#1843](https://github.com/googleapis/google-auth-library-nodejs/issues/1843)) ([3ae120d](https://github.com/googleapis/google-auth-library-nodejs/commit/3ae120d0a45c95e36c59c9ac8286483938781f30)) +* Extend API Key Support ([#1835](https://github.com/googleapis/google-auth-library-nodejs/issues/1835)) ([5fc3bcc](https://github.com/googleapis/google-auth-library-nodejs/commit/5fc3bccacc74082f71983595dd7654b1b60be0f8)) +* Group Concurrent `getClient` Requests ([#1848](https://github.com/googleapis/google-auth-library-nodejs/issues/1848)) ([243ce28](https://github.com/googleapis/google-auth-library-nodejs/commit/243ce284bedd101a15a0e738a59a7db808c2ad3f)) + + +### Bug Fixes + +* **deps:** Update dependency @googleapis/iam to v21 ([#1847](https://github.com/googleapis/google-auth-library-nodejs/issues/1847)) ([e9459f3](https://github.com/googleapis/google-auth-library-nodejs/commit/e9459f3d11418ce8afd4fe87cd92d4b2d06457ba)) + +## [9.13.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.12.0...v9.13.0) (2024-07-29) + + +### Features + +* Group Concurrent Access Token Requests for Base External Clients ([#1840](https://github.com/googleapis/google-auth-library-nodejs/issues/1840)) ([0e08fc5](https://github.com/googleapis/google-auth-library-nodejs/commit/0e08fc58eb61bba431ab4f217f7f7ad3a7dce9df)) + +## [9.12.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.11.0...v9.12.0) (2024-07-26) + + +### Features + +* Expose More Public API Types ([#1838](https://github.com/googleapis/google-auth-library-nodejs/issues/1838)) ([5745a49](https://github.com/googleapis/google-auth-library-nodejs/commit/5745a49df31ff87c0e53edf44671f3a10c024d9f)) + + +### Bug Fixes + +* **deps:** Update dependency @googleapis/iam to v19 ([#1823](https://github.com/googleapis/google-auth-library-nodejs/issues/1823)) ([b070ffb](https://github.com/googleapis/google-auth-library-nodejs/commit/b070ffbfeb35a7f4552e86bf1840645096951b58)) +* **deps:** Update dependency @googleapis/iam to v20 ([#1832](https://github.com/googleapis/google-auth-library-nodejs/issues/1832)) ([e31a831](https://github.com/googleapis/google-auth-library-nodejs/commit/e31a831417692e730f79d42608bd543046070ae3)) + +## [9.11.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.10.0...v9.11.0) (2024-06-01) + + +### Features + +* Adding support of client authentication method. ([#1814](https://github.com/googleapis/google-auth-library-nodejs/issues/1814)) ([4a14e8c](https://github.com/googleapis/google-auth-library-nodejs/commit/4a14e8c3bdcfa9d8531a231b00b946728530ce12)) + +## [9.10.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.9.0...v9.10.0) (2024-05-10) + + +### Features + +* Implement `UserRefreshClient#fetchIdToken` ([#1811](https://github.com/googleapis/google-auth-library-nodejs/issues/1811)) ([ae8bc54](https://github.com/googleapis/google-auth-library-nodejs/commit/ae8bc5476f5d93c8516d9a9eb553e7ce7c00edd5)) + + +### Bug Fixes + +* **deps:** Update dependency @googleapis/iam to v16 ([#1803](https://github.com/googleapis/google-auth-library-nodejs/issues/1803)) ([40406a0](https://github.com/googleapis/google-auth-library-nodejs/commit/40406a0512cde1d75d2af7dd23aa7aa7de38d30b)) +* **deps:** Update dependency @googleapis/iam to v17 ([#1808](https://github.com/googleapis/google-auth-library-nodejs/issues/1808)) ([4d67f07](https://github.com/googleapis/google-auth-library-nodejs/commit/4d67f07380f690a99c8facf7266db7cb2d6c69b3)) +* **deps:** Update dependency @googleapis/iam to v18 ([#1809](https://github.com/googleapis/google-auth-library-nodejs/issues/1809)) ([b2b9676](https://github.com/googleapis/google-auth-library-nodejs/commit/b2b9676f933c012fb2cd1789ad80b927af0de07c)) + +## [9.9.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.8.0...v9.9.0) (2024-04-18) + + +### Features + +* Adds suppliers for custom subject token and AWS credentials ([#1795](https://github.com/googleapis/google-auth-library-nodejs/issues/1795)) ([c680b5d](https://github.com/googleapis/google-auth-library-nodejs/commit/c680b5ddfa526d414ad1250bb6f5af69c498b909)) + +## [9.8.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.7.0...v9.8.0) (2024-04-12) + + +### Features + +* Enable Retries For Auth Requests ([#1791](https://github.com/googleapis/google-auth-library-nodejs/issues/1791)) ([9b69a31](https://github.com/googleapis/google-auth-library-nodejs/commit/9b69a3119c2d0dfe12d41a5f77658d35a2c92d74)) +* Improve `gaxios` exposure ([#1794](https://github.com/googleapis/google-auth-library-nodejs/issues/1794)) ([5058726](https://github.com/googleapis/google-auth-library-nodejs/commit/5058726e2234a2da4edd31f0898465798943ebe6)) + + +### Bug Fixes + +* **deps:** Update dependency open to v10 ([#1782](https://github.com/googleapis/google-auth-library-nodejs/issues/1782)) ([16e5cae](https://github.com/googleapis/google-auth-library-nodejs/commit/16e5cae1d56d5c3dd6cc3bdca5ecdfb534eaf529)) +* **deps:** Update dependency opn to v6 ([#1775](https://github.com/googleapis/google-auth-library-nodejs/issues/1775)) ([fc8dfe9](https://github.com/googleapis/google-auth-library-nodejs/commit/fc8dfe9d373e30dd1bd06eb8cbb8b52e735b4d83)) + +## [9.7.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.6.3...v9.7.0) (2024-03-12) + + +### Features + +* `PassThrough` AuthClient ([#1771](https://github.com/googleapis/google-auth-library-nodejs/issues/1771)) ([0003bee](https://github.com/googleapis/google-auth-library-nodejs/commit/0003bee317dd8e99b553857edfffeb4a47a4af26)) + + +### Bug Fixes + +* **deps:** Update dependency @googleapis/iam to v15 ([#1772](https://github.com/googleapis/google-auth-library-nodejs/issues/1772)) ([f45f975](https://github.com/googleapis/google-auth-library-nodejs/commit/f45f9753a7c83bc04616a1bdbaf687b3f38a17d2)) +* Making aws request signer get a new session token each time security credentials are requested. ([#1765](https://github.com/googleapis/google-auth-library-nodejs/issues/1765)) ([6a6e496](https://github.com/googleapis/google-auth-library-nodejs/commit/6a6e49634863f61487688724d0d20632e03f0299)) + +## [9.6.3](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.6.2...v9.6.3) (2024-02-06) + + +### Bug Fixes + +* Always sign with `scopes` on Non-Default Universes ([#1752](https://github.com/googleapis/google-auth-library-nodejs/issues/1752)) ([f3d3a03](https://github.com/googleapis/google-auth-library-nodejs/commit/f3d3a03dbce42a400c11457131dd1fabc206826a)) + +## [9.6.2](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.6.1...v9.6.2) (2024-02-02) + + +### Bug Fixes + +* Allow Get Universe Without Credentials ([#1748](https://github.com/googleapis/google-auth-library-nodejs/issues/1748)) ([696db72](https://github.com/googleapis/google-auth-library-nodejs/commit/696db72bb8644739768d20375d670813d4490714)) + +## [9.6.1](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.6.0...v9.6.1) (2024-02-01) + + +### Bug Fixes + +* Universe Domain Resolution ([#1745](https://github.com/googleapis/google-auth-library-nodejs/issues/1745)) ([a4f9f9c](https://github.com/googleapis/google-auth-library-nodejs/commit/a4f9f9c65853a37e6e83861c5d22533dba774037)) + +## [9.6.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.5.0...v9.6.0) (2024-01-29) + + +### Features + +* Open More Endpoints for Customization ([#1721](https://github.com/googleapis/google-auth-library-nodejs/issues/1721)) ([effbf87](https://github.com/googleapis/google-auth-library-nodejs/commit/effbf87f6f0fd11a0cb1c749dad81737926dc436)) +* Use self-signed JWTs when non-default Universe Domains ([#1722](https://github.com/googleapis/google-auth-library-nodejs/issues/1722)) ([7e9876e](https://github.com/googleapis/google-auth-library-nodejs/commit/7e9876e2496b073220ca270368da7e9522da88f9)) + + +### Bug Fixes + +* Revert Missing `WORKFORCE_AUDIENCE_PATTERN` ([#1740](https://github.com/googleapis/google-auth-library-nodejs/issues/1740)) ([422de68](https://github.com/googleapis/google-auth-library-nodejs/commit/422de68d8d9ea66e6bf1fea923f61c8af0842420)) + +## [9.5.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.4.2...v9.5.0) (2024-01-25) + + +### Features + +* Improve Universe Domain Ergonomics ([#1732](https://github.com/googleapis/google-auth-library-nodejs/issues/1732)) ([eec82f5](https://github.com/googleapis/google-auth-library-nodejs/commit/eec82f5f48a250744b5c3200ef247c3eae184e2f)) + + +### Bug Fixes + +* **deps:** Update dependency @googleapis/iam to v14 ([#1725](https://github.com/googleapis/google-auth-library-nodejs/issues/1725)) ([594bf2c](https://github.com/googleapis/google-auth-library-nodejs/commit/594bf2cc808c03733274d6b08d92f1d4b12dd630)) +* Typos in samples ([#1728](https://github.com/googleapis/google-auth-library-nodejs/issues/1728)) ([058a503](https://github.com/googleapis/google-auth-library-nodejs/commit/058a5035e3e4df35663c6b3adef2dda617271849)) + +## [9.4.2](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.4.1...v9.4.2) (2024-01-04) + + +### Bug Fixes + +* **deps:** Update dependency @googleapis/iam to v13 ([#1710](https://github.com/googleapis/google-auth-library-nodejs/issues/1710)) ([7ae4aae](https://github.com/googleapis/google-auth-library-nodejs/commit/7ae4aaea0311de1a3e10f4e86a1ef93ff00656b5)) +* Expand credentials type ([#1719](https://github.com/googleapis/google-auth-library-nodejs/issues/1719)) ([846c8e9](https://github.com/googleapis/google-auth-library-nodejs/commit/846c8e96cc36feb05148c16e12127e805e388189)) + +## [9.4.1](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.4.0...v9.4.1) (2023-12-01) + + +### Bug Fixes + +* Support 404 When `GaxiosError` != `GaxiosError` ([#1707](https://github.com/googleapis/google-auth-library-nodejs/issues/1707)) ([704674f](https://github.com/googleapis/google-auth-library-nodejs/commit/704674fe14750d31e7d3a58d6f9b2387c89fb184)) + +## [9.4.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.3.0...v9.4.0) (2023-11-30) + + +### Features + +* Update gcp metadata dependency ([#1703](https://github.com/googleapis/google-auth-library-nodejs/issues/1703)) ([615bdd9](https://github.com/googleapis/google-auth-library-nodejs/commit/615bdd92d1eb1a2a5b8d8c2675fd53350d5fbc21)) + +## [9.3.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.2.0...v9.3.0) (2023-11-29) + + +### Features + +* Add impersonated signer ([#1694](https://github.com/googleapis/google-auth-library-nodejs/issues/1694)) ([cb78a1b](https://github.com/googleapis/google-auth-library-nodejs/commit/cb78a1bfb4104e05be85877fee56d703f749e525)) +* Retrieve `universe_domain` for Compute clients ([#1692](https://github.com/googleapis/google-auth-library-nodejs/issues/1692)) ([a735ec5](https://github.com/googleapis/google-auth-library-nodejs/commit/a735ec5f5e280a1c47f0f4d5e99acf228d5a320a)) + + +### Bug Fixes + +* Verifier algorithm ([#1696](https://github.com/googleapis/google-auth-library-nodejs/issues/1696)) ([c5080a0](https://github.com/googleapis/google-auth-library-nodejs/commit/c5080a0d56b52b90b5d26cfc5f7343afb58199a4)) + +## [9.2.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.1.0...v9.2.0) (2023-10-26) + + +### Features + +* Unify Base `AuthClient` Options ([#1663](https://github.com/googleapis/google-auth-library-nodejs/issues/1663)) ([5ac6705](https://github.com/googleapis/google-auth-library-nodejs/commit/5ac67052f6c19e93c3e8c4e1636fad4737fcee08)) + + +### Bug Fixes + +* **deps:** Update dependency @googleapis/iam to v12 ([#1671](https://github.com/googleapis/google-auth-library-nodejs/issues/1671)) ([4f94ffe](https://github.com/googleapis/google-auth-library-nodejs/commit/4f94ffe474ee41b560813b81e8d621be848d38d0)) +* DOS security risks ([#1668](https://github.com/googleapis/google-auth-library-nodejs/issues/1668)) ([b25d4f5](https://github.com/googleapis/google-auth-library-nodejs/commit/b25d4f54f88c52c8496ef65f5ab2a75122100f2c)) +* Increase max asset size ([#1682](https://github.com/googleapis/google-auth-library-nodejs/issues/1682)) ([edb9401](https://github.com/googleapis/google-auth-library-nodejs/commit/edb94018cadd2ad796ccec5496e3bfcbade39c7f)) +* Remove broken source maps ([#1669](https://github.com/googleapis/google-auth-library-nodejs/issues/1669)) ([56cb3ad](https://github.com/googleapis/google-auth-library-nodejs/commit/56cb3ad24c5e4b6952169b88d0a43e89cbf1252e)) + +## [9.1.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.0.0...v9.1.0) (2023-10-02) + + +### Features + +* Byoid metrics ([#1595](https://github.com/googleapis/google-auth-library-nodejs/issues/1595)) ([fe09d6b](https://github.com/googleapis/google-auth-library-nodejs/commit/fe09d6b4eb5a8215d21564a97bcc7ea5beb570bf)) +* Expose `gcp-metadata` ([#1655](https://github.com/googleapis/google-auth-library-nodejs/issues/1655)) ([d76140f](https://github.com/googleapis/google-auth-library-nodejs/commit/d76140f253c3903a22ed9087623be05e79a220f9)) +* Expose Compute's Service Account Email ([#1656](https://github.com/googleapis/google-auth-library-nodejs/issues/1656)) ([ef29297](https://github.com/googleapis/google-auth-library-nodejs/commit/ef29297215eb907c511627543391db9b43c1eac5)) +* Extend `universe_domain` support ([#1633](https://github.com/googleapis/google-auth-library-nodejs/issues/1633)) ([4ee02da](https://github.com/googleapis/google-auth-library-nodejs/commit/4ee02da4f6934eeb9550b8b659d1abda85194e6b)) +* Support Instantiating OAuth2Client with Credentials ([#1652](https://github.com/googleapis/google-auth-library-nodejs/issues/1652)) ([4339d64](https://github.com/googleapis/google-auth-library-nodejs/commit/4339d6410da7b792f96d31f62800507313c25430)) + + +### Bug Fixes + +* **deps:** Update dependency @google-cloud/storage to v7 ([#1629](https://github.com/googleapis/google-auth-library-nodejs/issues/1629)) ([8075b6f](https://github.com/googleapis/google-auth-library-nodejs/commit/8075b6fbb347067ec231134fb4388ab9bcd1bde0)) +* **deps:** Update dependency @googleapis/iam to v11 ([#1622](https://github.com/googleapis/google-auth-library-nodejs/issues/1622)) ([03c0ac9](https://github.com/googleapis/google-auth-library-nodejs/commit/03c0ac9950217ec08ac9ad66eaaa4e9a9e67d423)) +* **deps:** Update dependency google-auth-library to v9 ([#1618](https://github.com/googleapis/google-auth-library-nodejs/issues/1618)) ([1873fef](https://github.com/googleapis/google-auth-library-nodejs/commit/1873fefcdf4df00ff40b0f311e40dcdd402f799e)) +* **deps:** Update dependency puppeteer to v21 ([#1627](https://github.com/googleapis/google-auth-library-nodejs/issues/1627)) ([dd04fbd](https://github.com/googleapis/google-auth-library-nodejs/commit/dd04fbdeb17e457a09b06a4abc2aedf511f355ea)) +* Workforce Audience Pattern ([#1654](https://github.com/googleapis/google-auth-library-nodejs/issues/1654)) ([77eeaed](https://github.com/googleapis/google-auth-library-nodejs/commit/77eeaed1d66c89e855a15db0bb6b9dbd96179c8f)) + +## [9.0.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.9.0...v9.0.0) (2023-07-20) + + +### ⚠ BREAKING CHANGES + +* **deps:** upgrade node-gtoken to 7.0.0 ([#1590](https://github.com/googleapis/google-auth-library-nodejs/issues/1590)) +* make transporter attribute type more generic ([#1406](https://github.com/googleapis/google-auth-library-nodejs/issues/1406)) +* migrate to Node 14 ([#1582](https://github.com/googleapis/google-auth-library-nodejs/issues/1582)) +* remove arrify and fast-text-encoding ([#1583](https://github.com/googleapis/google-auth-library-nodejs/issues/1583)) + +### Features + +* Make transporter attribute type more generic ([#1406](https://github.com/googleapis/google-auth-library-nodejs/issues/1406)) ([dfac525](https://github.com/googleapis/google-auth-library-nodejs/commit/dfac5259fa573f25960949ae1c2f98bc78962717)) + + +### Bug Fixes + +* **deps:** Update dependency @googleapis/iam to v10 ([#1588](https://github.com/googleapis/google-auth-library-nodejs/issues/1588)) ([f95a153](https://github.com/googleapis/google-auth-library-nodejs/commit/f95a153409735a1f4c470fd7de18bf9ab5d5e771)) + + +### Build System + +* Remove arrify and fast-text-encoding ([#1583](https://github.com/googleapis/google-auth-library-nodejs/issues/1583)) ([d736da3](https://github.com/googleapis/google-auth-library-nodejs/commit/d736da3fa5536650ae6a3aebbcae408254ebd035)) + + +### Miscellaneous Chores + +* **deps:** Upgrade node-gtoken to 7.0.0 ([#1590](https://github.com/googleapis/google-auth-library-nodejs/issues/1590)) ([8738df9](https://github.com/googleapis/google-auth-library-nodejs/commit/8738df9e24c62213b5a78e34a70cdcf456a794fa)) +* Migrate to Node 14 ([#1582](https://github.com/googleapis/google-auth-library-nodejs/issues/1582)) ([6004dca](https://github.com/googleapis/google-auth-library-nodejs/commit/6004dca8d7e7aca7e570b56afd84d3c7f5d40242)) + +## [8.9.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.8.0...v8.9.0) (2023-06-29) + + +### Features + +* Adds universe_domain field to base external client ([#1548](https://github.com/googleapis/google-auth-library-nodejs/issues/1548)) ([7412d7c](https://github.com/googleapis/google-auth-library-nodejs/commit/7412d7c55c688601199b5201b29cfbe63c4c7a70)) +* Utilize `gcp-metadata`'s GCP Residency Check ([#1513](https://github.com/googleapis/google-auth-library-nodejs/issues/1513)) ([43377ac](https://github.com/googleapis/google-auth-library-nodejs/commit/43377ac7af1ece14b82b053b504449f257d11af6)) + + +### Bug Fixes + +* **deps:** Update dependency @googleapis/iam to v8 ([#1581](https://github.com/googleapis/google-auth-library-nodejs/issues/1581)) ([7373b75](https://github.com/googleapis/google-auth-library-nodejs/commit/7373b75c2205876f38ec2697f23758176a327fc7)) +* **deps:** Update dependency puppeteer to v20 ([#1550](https://github.com/googleapis/google-auth-library-nodejs/issues/1550)) ([3563c16](https://github.com/googleapis/google-auth-library-nodejs/commit/3563c16e2376729e399fefc0b1fad7bff78c296e)) +* IdTokenClient expiry_date check ([#1555](https://github.com/googleapis/google-auth-library-nodejs/issues/1555)) ([efcdef1](https://github.com/googleapis/google-auth-library-nodejs/commit/efcdef190fd94537d79087e7fcb26e5925a46173)) +* KeepAlive sample ([#1561](https://github.com/googleapis/google-auth-library-nodejs/issues/1561)) ([e3ab824](https://github.com/googleapis/google-auth-library-nodejs/commit/e3ab8247761b0a61f25e08a1b8fd6b200a4be200)) +* Make universeDomain private ([#1552](https://github.com/googleapis/google-auth-library-nodejs/issues/1552)) ([73b63d5](https://github.com/googleapis/google-auth-library-nodejs/commit/73b63d56fad8da033307e1be501a8846a5311211)) +* Remove auth lib version from x-goog-api-client header ([#1558](https://github.com/googleapis/google-auth-library-nodejs/issues/1558)) ([ce6013c](https://github.com/googleapis/google-auth-library-nodejs/commit/ce6013c6132ba2b82a1f8cba0a15c4710536204c)) + +## [8.8.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.7.0...v8.8.0) (2023-04-25) + + +### Features + +* Add External Account Authorized User client type ([#1530](https://github.com/googleapis/google-auth-library-nodejs/issues/1530)) ([06d4ef3](https://github.com/googleapis/google-auth-library-nodejs/commit/06d4ef3cc9ba1651af5b1f90c02b231862822ba2)) +* Document External Account Authorized User Credentials ([#1540](https://github.com/googleapis/google-auth-library-nodejs/issues/1540)) ([c6138be](https://github.com/googleapis/google-auth-library-nodejs/commit/c6138be12753c68d7645843451e1e3f9146e515a)) + + +### Bug Fixes + +* **deps:** Update `gcp-metadata` to v5.2.0 ([#1502](https://github.com/googleapis/google-auth-library-nodejs/issues/1502)) ([2562d11](https://github.com/googleapis/google-auth-library-nodejs/commit/2562d1192e0f89a3232897b8e27f24a14d5222f2)) +* **deps:** Update dependency @googleapis/iam to v4 ([#1482](https://github.com/googleapis/google-auth-library-nodejs/issues/1482)) ([00d6135](https://github.com/googleapis/google-auth-library-nodejs/commit/00d6135f35a1aa193d50fad6b3ec28a7fda9df66)) +* **deps:** Update dependency @googleapis/iam to v5 ([#1526](https://github.com/googleapis/google-auth-library-nodejs/issues/1526)) ([a1f9835](https://github.com/googleapis/google-auth-library-nodejs/commit/a1f9835fe155722206046d6bb5b56f9e53f2fe9a)) +* **deps:** Update dependency @googleapis/iam to v6 ([#1536](https://github.com/googleapis/google-auth-library-nodejs/issues/1536)) ([86a4de8](https://github.com/googleapis/google-auth-library-nodejs/commit/86a4de82c0de3efeb4b9b05a6ef34bd98cce398c)) +* **deps:** Update dependency @googleapis/iam to v7 ([#1538](https://github.com/googleapis/google-auth-library-nodejs/issues/1538)) ([fdb67dc](https://github.com/googleapis/google-auth-library-nodejs/commit/fdb67dc634f7fa2fcf8977d6d488cc91e9a7cccb)) +* Do not call metadata server if security creds and region are retrievable through environment vars ([#1493](https://github.com/googleapis/google-auth-library-nodejs/issues/1493)) ([d4de941](https://github.com/googleapis/google-auth-library-nodejs/commit/d4de9412e12f1f6f23f2a7c0d176dc5d2543e607)) +* Removing 3pi config URL validation ([#1517](https://github.com/googleapis/google-auth-library-nodejs/issues/1517)) ([a278d19](https://github.com/googleapis/google-auth-library-nodejs/commit/a278d19a0b211b13e5cf5176d40128e704b55780)) +* Removing aws url validation ([#1531](https://github.com/googleapis/google-auth-library-nodejs/issues/1531)) ([f4d9335](https://github.com/googleapis/google-auth-library-nodejs/commit/f4d933579cb5b9e50adf6e679a73cc78388ad8f8)) + +## [8.7.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.6.0...v8.7.0) (2022-11-08) + + +### Features + +* Introduce environment variable for quota project ([#1478](https://github.com/googleapis/google-auth-library-nodejs/issues/1478)) ([8706abc](https://github.com/googleapis/google-auth-library-nodejs/commit/8706abc64bb7d7b4336597589abb011150015a8c)) + + +### Bug Fixes + +* **deps:** Update dependency puppeteer to v19 ([#1476](https://github.com/googleapis/google-auth-library-nodejs/issues/1476)) ([86b258d](https://github.com/googleapis/google-auth-library-nodejs/commit/86b258da699810ead624419333a1a7f998f1b376)) +* Validate url domain for aws metadata urls ([#1484](https://github.com/googleapis/google-auth-library-nodejs/issues/1484)) ([6dc4e58](https://github.com/googleapis/google-auth-library-nodejs/commit/6dc4e583dfd3aa3030dfbf959ee1c68a259abe2f)) + +## [8.6.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.5.2...v8.6.0) (2022-10-06) + + +### Features + +* Adding validation for psc endpoints ([#1473](https://github.com/googleapis/google-auth-library-nodejs/issues/1473)) ([4bbd13f](https://github.com/googleapis/google-auth-library-nodejs/commit/4bbd13fbf9081e004209d0ffc336648cff0c529e)) +* **samples:** Auth samples ([#1444](https://github.com/googleapis/google-auth-library-nodejs/issues/1444)) ([137883a](https://github.com/googleapis/google-auth-library-nodejs/commit/137883aff56c9e847abb6445c89a76a27536fe26)) + +## [8.5.2](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.5.1...v8.5.2) (2022-09-22) + + +### Bug Fixes + +* **deps:** Update dependency puppeteer to v17 ([#1452](https://github.com/googleapis/google-auth-library-nodejs/issues/1452)) ([b317b59](https://github.com/googleapis/google-auth-library-nodejs/commit/b317b5963c18a598fceb85d4f32cc8cd64bb9b7b)) +* **deps:** Update dependency puppeteer to v18 ([#1471](https://github.com/googleapis/google-auth-library-nodejs/issues/1471)) ([9a2a918](https://github.com/googleapis/google-auth-library-nodejs/commit/9a2a9188c674c41a6a67095c3b102a7dc545fff5)) + +## [8.5.1](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.5.0...v8.5.1) (2022-08-31) + + +### Bug Fixes + +* do not use #private ([#1454](https://github.com/googleapis/google-auth-library-nodejs/issues/1454)) ([6c30274](https://github.com/googleapis/google-auth-library-nodejs/commit/6c302746c9eb4778619dec5f2f5f6e940af8086a)) + +## [8.5.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.4.0...v8.5.0) (2022-08-31) + + +### Features + +* Support Not Requiring `projectId` When Not Required ([#1448](https://github.com/googleapis/google-auth-library-nodejs/issues/1448)) ([b37489b](https://github.com/googleapis/google-auth-library-nodejs/commit/b37489b6bc17645d3ea23fbceb2326adb296240b)) + + +### Bug Fixes + +* add hashes to requirements.txt ([#1544](https://github.com/googleapis/google-auth-library-nodejs/issues/1544)) ([#1449](https://github.com/googleapis/google-auth-library-nodejs/issues/1449)) ([54afa8e](https://github.com/googleapis/google-auth-library-nodejs/commit/54afa8ef184c8a68c9930d67d850b7334c28ecaf)) +* remove `projectId` check for `signBlob` calls ([6c04661](https://github.com/googleapis/google-auth-library-nodejs/commit/6c04661c6950532a8239cb95f0509a9d5368ffcc)) + +## [8.4.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.3.0...v8.4.0) (2022-08-23) + + +### Features + +* adding configurable token lifespan support ([#1441](https://github.com/googleapis/google-auth-library-nodejs/issues/1441)) ([178e3b8](https://github.com/googleapis/google-auth-library-nodejs/commit/178e3b83104f5a050f09e17d522d36c8feca632c)) + + +### Bug Fixes + +* **functions:** clarify auth comments ([#1427](https://github.com/googleapis/google-auth-library-nodejs/issues/1427)) ([7e06732](https://github.com/googleapis/google-auth-library-nodejs/commit/7e067327634281bba948c9cc6bc99c7ab860f827)) + +## [8.3.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.2.0...v8.3.0) (2022-08-19) + + +### Features + +* Add `generateIdToken` support for `Impersonated` Clients ([#1439](https://github.com/googleapis/google-auth-library-nodejs/issues/1439)) ([4ace981](https://github.com/googleapis/google-auth-library-nodejs/commit/4ace981ba1d37a9a00201a1c91e1b79c8cdb5cec)) + +## [8.2.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.1.1...v8.2.0) (2022-08-11) + + +### Features + +* adds Pluggable Auth support ([#1437](https://github.com/googleapis/google-auth-library-nodejs/issues/1437)) ([ed7ef7a](https://github.com/googleapis/google-auth-library-nodejs/commit/ed7ef7a5d1fa6bf5d06bdaab278052fd3930fb7f)) + +## [8.1.1](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.1.0...v8.1.1) (2022-07-08) + + +### Bug Fixes + +* **deps:** update dependency puppeteer to v15 ([#1424](https://github.com/googleapis/google-auth-library-nodejs/issues/1424)) ([1462f2c](https://github.com/googleapis/google-auth-library-nodejs/commit/1462f2c533da22b0a07130b25c41df046d4d713d)) + +## [8.1.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.0.3...v8.1.0) (2022-06-30) + + +### Features + +* handle impersonated ADC ([#1425](https://github.com/googleapis/google-auth-library-nodejs/issues/1425)) ([835be89](https://github.com/googleapis/google-auth-library-nodejs/commit/835be89687c2dff19f34e8b55645d3d611339e14)) + +## [8.0.3](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.0.2...v8.0.3) (2022-06-17) + + +### Bug Fixes + +* **deps:** update dependency @googleapis/iam to v3 ([#1421](https://github.com/googleapis/google-auth-library-nodejs/issues/1421)) ([0dc8857](https://github.com/googleapis/google-auth-library-nodejs/commit/0dc88572958520ddd4834aa982d41b98851895d9)) + +### [8.0.2](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.0.1...v8.0.2) (2022-04-27) + + +### Bug Fixes + +* Fixing Implementation of GoogleAuth.sign() for external account credentials ([#1397](https://github.com/googleapis/google-auth-library-nodejs/issues/1397)) ([b0ddb75](https://github.com/googleapis/google-auth-library-nodejs/commit/b0ddb7512fb9ed1e51b6874b7376d7e1f26be644)) + +### [8.0.1](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.0.0...v8.0.1) (2022-04-22) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v5 ([#1398](https://github.com/googleapis/google-auth-library-nodejs/issues/1398)) ([cbd7d4f](https://github.com/googleapis/google-auth-library-nodejs/commit/cbd7d4f471046afa05ff4539c9a93bba998b318c)) +* **deps:** update dependency google-auth-library to v8 ([#1399](https://github.com/googleapis/google-auth-library-nodejs/issues/1399)) ([9a8be63](https://github.com/googleapis/google-auth-library-nodejs/commit/9a8be636eaea979979426558dca40def9c0e569e)) + +## [8.0.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v7.14.1...v8.0.0) (2022-04-20) + + +### ⚠ BREAKING CHANGES + +* Set Node v12 to minimum supported version & Upgrade TypeScript (#1392) +* remove deprecated DeprecatedGetClientOptions (#1393) + +### Code Refactoring + +* remove deprecated DeprecatedGetClientOptions ([#1393](https://github.com/googleapis/google-auth-library-nodejs/issues/1393)) ([9c02941](https://github.com/googleapis/google-auth-library-nodejs/commit/9c02941e52514f8e3b07fedb01439fc313046063)) + + +### Build System + +* Set Node v12 to minimum supported version & Upgrade TypeScript ([#1392](https://github.com/googleapis/google-auth-library-nodejs/issues/1392)) ([b7bcedb](https://github.com/googleapis/google-auth-library-nodejs/commit/b7bcedb9e4ec24217a861016f3378460af7598c7)) + +### [7.14.1](https://github.com/googleapis/google-auth-library-nodejs/compare/v7.14.0...v7.14.1) (2022-03-09) + + +### Bug Fixes + +* **serverless:** clean up ID token example ([#1380](https://github.com/googleapis/google-auth-library-nodejs/issues/1380)) ([db27f1b](https://github.com/googleapis/google-auth-library-nodejs/commit/db27f1bc31efaa9df28da2e0a1229ee3ebea0751)) + +## [7.14.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v7.13.0...v7.14.0) (2022-02-22) + + +### Features + +* Add AWS Session Token to Metadata Requests ([#1363](https://github.com/googleapis/google-auth-library-nodejs/issues/1363)) ([9ea3e98](https://github.com/googleapis/google-auth-library-nodejs/commit/9ea3e98582e8a69dedef89952ae08d64c49f48ef)) + + +### Bug Fixes + +* Rename `auth` to `authClient` & Use Generics for `AuthClient` ([#1371](https://github.com/googleapis/google-auth-library-nodejs/issues/1371)) ([8373000](https://github.com/googleapis/google-auth-library-nodejs/commit/8373000b2240cb694e9492f849e5cc7e13c89b1a)) + +## [7.13.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v7.12.0...v7.13.0) (2022-02-17) + + +### Features + +* Support instantiating `GoogleAuth` with an `AuthClient` ([#1364](https://github.com/googleapis/google-auth-library-nodejs/issues/1364)) ([8839b5b](https://github.com/googleapis/google-auth-library-nodejs/commit/8839b5b12531ae4966b38795ed818ad138eb326a)) + +## [7.12.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v7.11.0...v7.12.0) (2022-02-09) + + +### Features + +* Export `AuthClient` ([#1361](https://github.com/googleapis/google-auth-library-nodejs/issues/1361)) ([88f42ec](https://github.com/googleapis/google-auth-library-nodejs/commit/88f42eca1a02ab5768e02538f2dc639d196de9fb)) + +## [7.11.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.10.4...v7.11.0) (2021-12-15) + + +### Features + +* adds README, samples and integration tests for downscoping with CAB ([#1311](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1311)) ([4549116](https://www.github.com/googleapis/google-auth-library-nodejs/commit/454911637eca6a1272a729b2b2dfcf690c53fe29)) + +### [7.10.4](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.10.3...v7.10.4) (2021-12-13) + + +### Bug Fixes + +* **deps:** update dependency puppeteer to v13 ([#1334](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1334)) ([e05548d](https://www.github.com/googleapis/google-auth-library-nodejs/commit/e05548dfb431638d618aa8b846d0944541387033)) + +### [7.10.3](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.10.2...v7.10.3) (2021-11-29) + + +### Bug Fixes + +* **deps:** update dependency puppeteer to v12 ([#1325](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1325)) ([110ddc2](https://www.github.com/googleapis/google-auth-library-nodejs/commit/110ddc245b768888a88d8c7211f0b0391326cc10)) + +### [7.10.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.10.1...v7.10.2) (2021-11-03) + + +### Bug Fixes + +* **deps:** update dependency puppeteer to v11 ([#1312](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1312)) ([b3ba9ac](https://www.github.com/googleapis/google-auth-library-nodejs/commit/b3ba9ac834de86022a78ac540995fa35857d6670)) + +### [7.10.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.10.0...v7.10.1) (2021-10-14) + + +### Bug Fixes + +* **security:** explicitly update keypair dependency ([94401a6](https://www.github.com/googleapis/google-auth-library-nodejs/commit/94401a6b73eeaf370aeaf9cbf92f23f4fc7bde9b)) + +## [7.10.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.9.2...v7.10.0) (2021-09-28) + + +### Features + +* add workforce config support. ([#1251](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1251)) ([fe29e38](https://www.github.com/googleapis/google-auth-library-nodejs/commit/fe29e384820f1c97ca62478c55813aad3f8ecbea)) + +### [7.9.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.9.1...v7.9.2) (2021-09-16) + + +### Bug Fixes + +* **deps:** update dependency @googleapis/iam to v2 ([#1253](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1253)) ([59b8243](https://www.github.com/googleapis/google-auth-library-nodejs/commit/59b82436d6b9b68b6ae0e0e81d4b797d964acae2)) + +### [7.9.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.9.0...v7.9.1) (2021-09-02) + + +### Bug Fixes + +* **build:** switch to main branch ([#1249](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1249)) ([2c72de4](https://www.github.com/googleapis/google-auth-library-nodejs/commit/2c72de4ef7c07ddb4586094faf117715ab50143e)) + +## [7.9.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.8.0...v7.9.0) (2021-09-02) + + +### Features + +* wire up implementation of DownscopedClient. ([#1232](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1232)) ([baa1318](https://www.github.com/googleapis/google-auth-library-nodejs/commit/baa13185836bb299b769c034bfb7d37231eea8d1)) + +## [7.8.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.7.0...v7.8.0) (2021-08-30) + + +### Features + +* use self-signed JWTs if alwaysUseJWTAccessWithScope is true ([#1196](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1196)) ([ad3f652](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ad3f652e8e859d8d8a69dfe9df01d001862fe0ae)) + +## [7.7.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.6.2...v7.7.0) (2021-08-27) + + +### Features + +* add refreshHandler callback to OAuth 2.0 client to handle token refresh ([#1213](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1213)) ([2fcab77](https://www.github.com/googleapis/google-auth-library-nodejs/commit/2fcab77a1fae85489829f22ec95cc66b0b284342)) + +### [7.6.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.6.1...v7.6.2) (2021-08-17) + + +### Bug Fixes + +* validate token_url and service_account_impersonation_url ([#1229](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1229)) ([0360bb7](https://www.github.com/googleapis/google-auth-library-nodejs/commit/0360bb722aaa082c36c1e1919bf5df27efbe15b3)) + +### [7.6.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.6.0...v7.6.1) (2021-08-13) + + +### Bug Fixes + +* use updated variable name for self-signed JWTs ([#1233](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1233)) ([ef41fe5](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ef41fe59b423125c607e3ad20896a35f12f5365b)) + +## [7.6.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.5.0...v7.6.0) (2021-08-10) + + +### Features + +* add GoogleAuth.sign() support to external account client ([#1227](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1227)) ([1ca3b73](https://www.github.com/googleapis/google-auth-library-nodejs/commit/1ca3b733427d951ed624e1129fca510d84d5d0fe)) + +## [7.5.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.4.1...v7.5.0) (2021-08-04) + + +### Features + +* Adds support for STS response not returning expires_in field. ([#1216](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1216)) ([24bb456](https://www.github.com/googleapis/google-auth-library-nodejs/commit/24bb4568820c2692b1b3ff29835a38fdb3f28c9e)) + +### [7.4.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.4.0...v7.4.1) (2021-07-29) + + +### Bug Fixes + +* **downscoped-client:** bug fixes for downscoped client implementation. ([#1219](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1219)) ([4fbe67e](https://www.github.com/googleapis/google-auth-library-nodejs/commit/4fbe67e08bce3f31193d3bb7b93c4cc1251e66a2)) + +## [7.4.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.3.0...v7.4.0) (2021-07-29) + + +### Features + +* **impersonated:** add impersonated credentials auth ([#1207](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1207)) ([ab1cd31](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ab1cd31e07d45424f614e0401d1068df2fbd914c)) + +## [7.3.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.2.0...v7.3.0) (2021-07-02) + + +### Features + +* add useJWTAccessWithScope and defaultServicePath variable ([#1204](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1204)) ([79e100e](https://www.github.com/googleapis/google-auth-library-nodejs/commit/79e100e9ddc64f34e34d0e91c8188f1818e33a1c)) + +## [7.2.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.1.2...v7.2.0) (2021-06-30) + + +### Features + +* Implement DownscopedClient#getAccessToken() and unit test ([#1201](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1201)) ([faa6677](https://www.github.com/googleapis/google-auth-library-nodejs/commit/faa6677fe72c8fc671a2190abe45897ac58cc42e)) + +### [7.1.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.1.1...v7.1.2) (2021-06-10) + + +### Bug Fixes + +* use iam client library to setup test ([#1173](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1173)) ([74ac5db](https://www.github.com/googleapis/google-auth-library-nodejs/commit/74ac5db59f9eff8fa4f3bdb6acc0647a1a4f491f)) + +### [7.1.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.1.0...v7.1.1) (2021-06-02) + + +### Bug Fixes + +* **deps:** update dependency puppeteer to v10 ([#1182](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1182)) ([003e3ee](https://www.github.com/googleapis/google-auth-library-nodejs/commit/003e3ee5d8aeb749c07a4a4db2b75a5882988cc3)) + +## [7.1.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.0.4...v7.1.0) (2021-05-21) + + +### Features + +* add `gcf-owl-bot[bot]` to `ignoreAuthors` ([#1174](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1174)) ([f377adc](https://www.github.com/googleapis/google-auth-library-nodejs/commit/f377adc01ca16687bb905aa14f6c62a23e90aaa9)) +* add detection for Cloud Run ([#1177](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1177)) ([4512363](https://www.github.com/googleapis/google-auth-library-nodejs/commit/4512363cf712dff5f178af0e7022c258775dfec7)) + +### [7.0.4](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.0.3...v7.0.4) (2021-04-06) + + +### Bug Fixes + +* do not suppress external project ID determination errors ([#1153](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1153)) ([6c1c91d](https://www.github.com/googleapis/google-auth-library-nodejs/commit/6c1c91dac6c31d762b03774a385d780a824fce97)) + +### [7.0.3](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.0.2...v7.0.3) (2021-03-23) + + +### Bug Fixes + +* support AWS_DEFAULT_REGION for determining AWS region ([#1149](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1149)) ([9ae2d30](https://www.github.com/googleapis/google-auth-library-nodejs/commit/9ae2d30c15c9bce3cae70ccbe6e227c096005695)) + +### [7.0.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.0.1...v7.0.2) (2021-02-10) + + +### Bug Fixes + +* expose `BaseExternalAccountClient` and `BaseExternalAccountClientOptions` ([#1142](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1142)) ([1d62c04](https://www.github.com/googleapis/google-auth-library-nodejs/commit/1d62c04dfa117b6a81e8c78385dc72792369cf21)) + +### [7.0.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.0.0...v7.0.1) (2021-02-09) + + +### Bug Fixes + +* **deps:** update dependency google-auth-library to v7 ([#1140](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1140)) ([9c717f7](https://www.github.com/googleapis/google-auth-library-nodejs/commit/9c717f70ca155b24edd5511b6038679db25b85b7)) + +## [7.0.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.1.6...v7.0.0) (2021-02-08) + + +### ⚠ BREAKING CHANGES + +* integrates external_accounts with `GoogleAuth` and ADC (#1052) +* workload identity federation support (#1131) + +### Features + +* adds service account impersonation to `ExternalAccountClient` ([#1041](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1041)) ([997f124](https://www.github.com/googleapis/google-auth-library-nodejs/commit/997f124a5c02dfa44879a759bf701a9fa4c3ba90)) +* adds text/json credential_source support to IdentityPoolClients ([#1059](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1059)) ([997f124](https://www.github.com/googleapis/google-auth-library-nodejs/commit/997f124a5c02dfa44879a759bf701a9fa4c3ba90)) +* defines `ExternalAccountClient` used to instantiate external account clients ([#1050](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1050)) ([997f124](https://www.github.com/googleapis/google-auth-library-nodejs/commit/997f124a5c02dfa44879a759bf701a9fa4c3ba90)) +* defines `IdentityPoolClient` used for K8s and Azure workloads ([#1042](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1042)) ([997f124](https://www.github.com/googleapis/google-auth-library-nodejs/commit/997f124a5c02dfa44879a759bf701a9fa4c3ba90)) +* defines ExternalAccountClient abstract class for external_account credentials ([#1030](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1030)) ([997f124](https://www.github.com/googleapis/google-auth-library-nodejs/commit/997f124a5c02dfa44879a759bf701a9fa4c3ba90)) +* get AWS region from environment variable ([#1067](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1067)) ([997f124](https://www.github.com/googleapis/google-auth-library-nodejs/commit/997f124a5c02dfa44879a759bf701a9fa4c3ba90)) +* implements AWS signature version 4 for signing requests ([#1047](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1047)) ([997f124](https://www.github.com/googleapis/google-auth-library-nodejs/commit/997f124a5c02dfa44879a759bf701a9fa4c3ba90)) +* implements the OAuth token exchange spec based on rfc8693 ([#1026](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1026)) ([997f124](https://www.github.com/googleapis/google-auth-library-nodejs/commit/997f124a5c02dfa44879a759bf701a9fa4c3ba90)) +* integrates external_accounts with `GoogleAuth` and ADC ([#1052](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1052)) ([997f124](https://www.github.com/googleapis/google-auth-library-nodejs/commit/997f124a5c02dfa44879a759bf701a9fa4c3ba90)) +* workload identity federation support ([#1131](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1131)) ([997f124](https://www.github.com/googleapis/google-auth-library-nodejs/commit/997f124a5c02dfa44879a759bf701a9fa4c3ba90)) + + +### Bug Fixes + +* **deps:** update dependency puppeteer to v6 ([#1129](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1129)) ([5240fb0](https://www.github.com/googleapis/google-auth-library-nodejs/commit/5240fb0e7ba5503d562659a0d1d7c952bc44ce0e)) +* **deps:** update dependency puppeteer to v7 ([#1134](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1134)) ([02d0d73](https://www.github.com/googleapis/google-auth-library-nodejs/commit/02d0d73a5f0d2fc7de9b13b160e4e7074652f9d0)) + +### [6.1.6](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.1.5...v6.1.6) (2021-01-27) + + +### Bug Fixes + +* call addSharedMetadataHeaders even when token has not expired ([#1116](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1116)) ([aad043d](https://www.github.com/googleapis/google-auth-library-nodejs/commit/aad043d20df3f1e44f56c58a21f15000b6fe970d)) + +### [6.1.5](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.1.4...v6.1.5) (2021-01-22) + + +### Bug Fixes + +* support PEM and p12 when using factory ([#1120](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1120)) ([c2ead4c](https://www.github.com/googleapis/google-auth-library-nodejs/commit/c2ead4cc7650f100b883c9296fce628f17085992)) + +### [6.1.4](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.1.3...v6.1.4) (2020-12-22) + + +### Bug Fixes + +* move accessToken to headers instead of parameter ([#1108](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1108)) ([67b0cc3](https://www.github.com/googleapis/google-auth-library-nodejs/commit/67b0cc3077860a1583bcf18ce50aeff58bbb5496)) + +### [6.1.3](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.1.2...v6.1.3) (2020-10-22) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v4 ([#1086](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1086)) ([f2678ff](https://www.github.com/googleapis/google-auth-library-nodejs/commit/f2678ff5f8f5a0ee33924278b58e0a6e3122cb12)) + +### [6.1.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.1.1...v6.1.2) (2020-10-19) + + +### Bug Fixes + +* update gcp-metadata to catch a json-bigint security fix ([#1078](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1078)) ([125fe09](https://www.github.com/googleapis/google-auth-library-nodejs/commit/125fe0924a2206ebb0c83ece9947524e7b135803)) + +### [6.1.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.1.0...v6.1.1) (2020-10-06) + + +### Bug Fixes + +* **deps:** upgrade gtoken ([#1064](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1064)) ([9116f24](https://www.github.com/googleapis/google-auth-library-nodejs/commit/9116f247486d6376feca505bbfa42a91d5e579e2)) + +## [6.1.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.0.8...v6.1.0) (2020-09-22) + + +### Features + +* default self-signed JWTs ([#1054](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1054)) ([b4d139d](https://www.github.com/googleapis/google-auth-library-nodejs/commit/b4d139d9ee27f886ca8cc5478615c052700fff48)) + +### [6.0.8](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.0.7...v6.0.8) (2020-08-13) + + +### Bug Fixes + +* **deps:** roll back dependency google-auth-library to ^6.0.6 ([#1033](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1033)) ([eb54ee9](https://www.github.com/googleapis/google-auth-library-nodejs/commit/eb54ee9369d9e5a01d164ccf7f826858d44827fd)) + +### [6.0.7](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.0.6...v6.0.7) (2020-08-11) + + +### Bug Fixes + +* migrate token info API to not pass token in query string ([#991](https://www.github.com/googleapis/google-auth-library-nodejs/issues/991)) ([a7e5701](https://www.github.com/googleapis/google-auth-library-nodejs/commit/a7e5701a8394d79fe93d28794467747a23cf9ff4)) + +### [6.0.6](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.0.5...v6.0.6) (2020-07-30) + + +### Bug Fixes + +* **types:** include scope in credentials type ([#1007](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1007)) ([a2b7d23](https://www.github.com/googleapis/google-auth-library-nodejs/commit/a2b7d23caa5bf253c7c0756396f1b58216182089)) + +### [6.0.5](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.0.4...v6.0.5) (2020-07-13) + + +### Bug Fixes + +* **deps:** update dependency lru-cache to v6 ([#995](https://www.github.com/googleapis/google-auth-library-nodejs/issues/995)) ([3c07566](https://www.github.com/googleapis/google-auth-library-nodejs/commit/3c07566f0384611227030e9b381fc6e6707e526b)) + +### [6.0.4](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.0.3...v6.0.4) (2020-07-09) + + +### Bug Fixes + +* typeo in nodejs .gitattribute ([#993](https://www.github.com/googleapis/google-auth-library-nodejs/issues/993)) ([ad12ceb](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ad12ceb3309b7db7394fe1fe1d5e7b2e4901141d)) + +### [6.0.3](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.0.2...v6.0.3) (2020-07-06) + + +### Bug Fixes + +* **deps:** update dependency puppeteer to v5 ([#986](https://www.github.com/googleapis/google-auth-library-nodejs/issues/986)) ([7cfe6f2](https://www.github.com/googleapis/google-auth-library-nodejs/commit/7cfe6f200b9c04fe4805d1b1e3a2e03a9668e551)) + +### [6.0.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.0.1...v6.0.2) (2020-06-16) + + +### Bug Fixes + +* **deps:** update dependency puppeteer to v4 ([#976](https://www.github.com/googleapis/google-auth-library-nodejs/issues/976)) ([9ddfb9b](https://www.github.com/googleapis/google-auth-library-nodejs/commit/9ddfb9befedd10d6c82cbf799c1afea9ba10d444)) +* **tsc:** audience property is not mandatory on verifyIdToken ([#972](https://www.github.com/googleapis/google-auth-library-nodejs/issues/972)) ([17a7e24](https://www.github.com/googleapis/google-auth-library-nodejs/commit/17a7e247cdb798ddf3173cf44ab762665cbce0a1)) +* **types:** add locale property to idtoken ([#974](https://www.github.com/googleapis/google-auth-library-nodejs/issues/974)) ([ebf9bed](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ebf9beda30f251da6adb9ec0bf943019ea0171c5)), closes [#973](https://www.github.com/googleapis/google-auth-library-nodejs/issues/973) + +### [6.0.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.0.0...v6.0.1) (2020-05-21) + + +### Bug Fixes + +* **deps:** update dependency google-auth-library to v6 ([#930](https://www.github.com/googleapis/google-auth-library-nodejs/issues/930)) ([81fdabe](https://www.github.com/googleapis/google-auth-library-nodejs/commit/81fdabe6fb7f0b8c5114c0d835680a28def822e2)) +* apache license URL ([#468](https://www.github.com/googleapis/google-auth-library-nodejs/issues/468)) ([#936](https://www.github.com/googleapis/google-auth-library-nodejs/issues/936)) ([53831cf](https://www.github.com/googleapis/google-auth-library-nodejs/commit/53831cf72f6669d13692c5665fef5062dc8f6c1a)) +* **deps:** update dependency puppeteer to v3 ([#944](https://www.github.com/googleapis/google-auth-library-nodejs/issues/944)) ([4d6fba0](https://www.github.com/googleapis/google-auth-library-nodejs/commit/4d6fba034cb0e70092656e9aff1ba419fdfca880)) +* fixing tsc error caused by @types/node update ([#965](https://www.github.com/googleapis/google-auth-library-nodejs/issues/965)) ([b94edb0](https://www.github.com/googleapis/google-auth-library-nodejs/commit/b94edb0716572593e4e9cb8a9b9bbfa567f71625)) +* gcp-metadata now warns rather than throwing ([#956](https://www.github.com/googleapis/google-auth-library-nodejs/issues/956)) ([89e16c2](https://www.github.com/googleapis/google-auth-library-nodejs/commit/89e16c2401101d086a8f9d05b8f0771b5c74157c)) + +## [6.0.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.10.1...v6.0.0) (2020-03-26) + + +### ⚠ BREAKING CHANGES + +* typescript@3.7.x introduced some breaking changes in +generated code. +* require node 10 in engines field (#926) +* remove deprecated methods (#906) + +### Features + +* require node 10 in engines field ([#926](https://www.github.com/googleapis/google-auth-library-nodejs/issues/926)) ([d89c59a](https://www.github.com/googleapis/google-auth-library-nodejs/commit/d89c59a316e9ca5b8c351128ee3e2d91e9729d5c)) + + +### Bug Fixes + +* do not warn for SDK creds ([#905](https://www.github.com/googleapis/google-auth-library-nodejs/issues/905)) ([9536840](https://www.github.com/googleapis/google-auth-library-nodejs/commit/9536840f88e77f747bbbc2c1b5b4289018fc23c9)) +* use iamcredentials API to sign blobs ([#908](https://www.github.com/googleapis/google-auth-library-nodejs/issues/908)) ([7b8e4c5](https://www.github.com/googleapis/google-auth-library-nodejs/commit/7b8e4c52e31bb3d448c3ff8c05002188900eaa04)) +* **deps:** update dependency gaxios to v3 ([#917](https://www.github.com/googleapis/google-auth-library-nodejs/issues/917)) ([1f4bf61](https://www.github.com/googleapis/google-auth-library-nodejs/commit/1f4bf6128a0dcf22cfe1ec492b2192f513836cb2)) +* **deps:** update dependency gcp-metadata to v4 ([#918](https://www.github.com/googleapis/google-auth-library-nodejs/issues/918)) ([d337131](https://www.github.com/googleapis/google-auth-library-nodejs/commit/d337131d009cc1f8182f7a1f8a9034433ee3fbf7)) +* **types:** add additional fields to TokenInfo ([#907](https://www.github.com/googleapis/google-auth-library-nodejs/issues/907)) ([5b48eb8](https://www.github.com/googleapis/google-auth-library-nodejs/commit/5b48eb86c108c47d317a0eb96b47c0cae86f98cb)) + + +### Build System + +* update to latest gts and TypeScript ([#927](https://www.github.com/googleapis/google-auth-library-nodejs/issues/927)) ([e11e18c](https://www.github.com/googleapis/google-auth-library-nodejs/commit/e11e18cb33eb60a666980d061c54bb8891cdd242)) + + +### Miscellaneous Chores + +* remove deprecated methods ([#906](https://www.github.com/googleapis/google-auth-library-nodejs/issues/906)) ([f453fb7](https://www.github.com/googleapis/google-auth-library-nodejs/commit/f453fb7d8355e6dc74800b18d6f43c4e91d4acc9)) + +### [5.10.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.10.0...v5.10.1) (2020-02-25) + + +### Bug Fixes + +* if GCF environment detected, increase library timeout ([#899](https://www.github.com/googleapis/google-auth-library-nodejs/issues/899)) ([2577ff2](https://www.github.com/googleapis/google-auth-library-nodejs/commit/2577ff28bf22dfc58bd09e7365471c16f359f109)) + +## [5.10.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.9.2...v5.10.0) (2020-02-20) + + +### Features + +* support for verifying ES256 and retrieving IAP public keys ([#887](https://www.github.com/googleapis/google-auth-library-nodejs/issues/887)) ([a98e386](https://www.github.com/googleapis/google-auth-library-nodejs/commit/a98e38678dc4a5e963356378c75c658e36dccd01)) + + +### Bug Fixes + +* **docs:** correct links in README ([f6a3194](https://www.github.com/googleapis/google-auth-library-nodejs/commit/f6a3194ff6df97d4fd833ae69ec80c05eab46e7b)), closes [#891](https://www.github.com/googleapis/google-auth-library-nodejs/issues/891) + +### [5.9.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.9.1...v5.9.2) (2020-01-28) + + +### Bug Fixes + +* populate credentials.refresh_token if provided ([#881](https://www.github.com/googleapis/google-auth-library-nodejs/issues/881)) ([63c4637](https://www.github.com/googleapis/google-auth-library-nodejs/commit/63c4637c57e4113a7b01bf78933a8bff0356c104)) + +### [5.9.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.9.0...v5.9.1) (2020-01-16) + + +### Bug Fixes + +* ensures GCE metadata sets email field for ID tokens ([#874](https://www.github.com/googleapis/google-auth-library-nodejs/issues/874)) ([e45b73d](https://www.github.com/googleapis/google-auth-library-nodejs/commit/e45b73dbb22e1c2d8115882006a21337c7d9bd63)) + +## [5.9.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.8.0...v5.9.0) (2020-01-14) + + +### Features + +* add methods for fetching and using id tokens ([#867](https://www.github.com/googleapis/google-auth-library-nodejs/issues/867)) ([8036f1a](https://www.github.com/googleapis/google-auth-library-nodejs/commit/8036f1a51d1a103b08daf62c7ce372c9f68cd9d4)) +* export LoginTicket and TokenPayload ([#870](https://www.github.com/googleapis/google-auth-library-nodejs/issues/870)) ([539ea5e](https://www.github.com/googleapis/google-auth-library-nodejs/commit/539ea5e804386b79ecf469838fff19465aeb2ca6)) + +## [5.8.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.7.0...v5.8.0) (2020-01-06) + + +### Features + +* cache results of getEnv() ([#857](https://www.github.com/googleapis/google-auth-library-nodejs/issues/857)) ([d4545a9](https://www.github.com/googleapis/google-auth-library-nodejs/commit/d4545a9001184fac0b67e7073e463e3efd345037)) + + +### Bug Fixes + +* **deps:** update dependency jws to v4 ([#851](https://www.github.com/googleapis/google-auth-library-nodejs/issues/851)) ([71366d4](https://www.github.com/googleapis/google-auth-library-nodejs/commit/71366d43406047ce9e1d818d59a14191fb678e3a)) + +## [5.7.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.6.1...v5.7.0) (2019-12-10) + + +### Features + +* make x-goog-user-project work for additional auth clients ([#848](https://www.github.com/googleapis/google-auth-library-nodejs/issues/848)) ([46af865](https://www.github.com/googleapis/google-auth-library-nodejs/commit/46af865172103c6f28712d78b30c2291487cbe86)) + +### [5.6.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.6.0...v5.6.1) (2019-12-05) + + +### Bug Fixes + +* **deps:** pin TypeScript below 3.7.0 ([#845](https://www.github.com/googleapis/google-auth-library-nodejs/issues/845)) ([a9c6e92](https://www.github.com/googleapis/google-auth-library-nodejs/commit/a9c6e9284efe8102974c57c9824ed6275d743c7a)) +* **docs:** improve types and docs for generateCodeVerifierAsync ([#840](https://www.github.com/googleapis/google-auth-library-nodejs/issues/840)) ([04dae9c](https://www.github.com/googleapis/google-auth-library-nodejs/commit/04dae9c271f0099025188489c61fd245d482832b)) + +## [5.6.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.5.1...v5.6.0) (2019-12-02) + + +### Features + +* populate x-goog-user-project for requestAsync ([#837](https://www.github.com/googleapis/google-auth-library-nodejs/issues/837)) ([5a068fb](https://www.github.com/googleapis/google-auth-library-nodejs/commit/5a068fb8f5a3827ab70404f1d9699a97f962bdad)) +* set x-goog-user-project header, with quota_project from default credentials ([#829](https://www.github.com/googleapis/google-auth-library-nodejs/issues/829)) ([3240d16](https://www.github.com/googleapis/google-auth-library-nodejs/commit/3240d16f05171781fe6d70d64c476bceb25805a5)) + + +### Bug Fixes + +* **deps:** update dependency puppeteer to v2 ([#821](https://www.github.com/googleapis/google-auth-library-nodejs/issues/821)) ([2c04117](https://www.github.com/googleapis/google-auth-library-nodejs/commit/2c0411708761cc7debdda1af1e593d82cb4aed31)) +* **docs:** add jsdoc-region-tag plugin ([#826](https://www.github.com/googleapis/google-auth-library-nodejs/issues/826)) ([558677f](https://www.github.com/googleapis/google-auth-library-nodejs/commit/558677fd90d3451e9ac4bf6d0b98907e3313f287)) +* expand on x-goog-user-project to handle auth.getClient() ([#831](https://www.github.com/googleapis/google-auth-library-nodejs/issues/831)) ([3646b7f](https://www.github.com/googleapis/google-auth-library-nodejs/commit/3646b7f9deb296aaff602dd2168ce93f014ce840)) +* use quota_project_id field instead of quota_project ([#832](https://www.github.com/googleapis/google-auth-library-nodejs/issues/832)) ([8933966](https://www.github.com/googleapis/google-auth-library-nodejs/commit/8933966659f3b07f5454a2756fa52d92fea147d2)) + +### [5.5.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.5.0...v5.5.1) (2019-10-22) + + +### Bug Fixes + +* **deps:** update gaxios dependency ([#817](https://www.github.com/googleapis/google-auth-library-nodejs/issues/817)) ([6730698](https://www.github.com/googleapis/google-auth-library-nodejs/commit/6730698b876eb52889acfead33bc4af52a8a7ba5)) +* don't append x-goog-api-client multiple times ([#820](https://www.github.com/googleapis/google-auth-library-nodejs/issues/820)) ([a46b271](https://www.github.com/googleapis/google-auth-library-nodejs/commit/a46b271947b635377eacbdfcd22ae363ce9260a1)) + +## [5.5.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.4.1...v5.5.0) (2019-10-14) + + +### Features + +* **refresh:** add forceRefreshOnFailure flag for refreshing token on error ([#790](https://www.github.com/googleapis/google-auth-library-nodejs/issues/790)) ([54cf477](https://www.github.com/googleapis/google-auth-library-nodejs/commit/54cf4770f487fd1db48f2444c86109ca97608ed1)) + +### [5.4.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.4.0...v5.4.1) (2019-10-10) + + +### Bug Fixes + +* **deps:** updats to gcp-metadata with debug option ([#811](https://www.github.com/googleapis/google-auth-library-nodejs/issues/811)) ([744e3e8](https://www.github.com/googleapis/google-auth-library-nodejs/commit/744e3e8fea223eb4fb115ef0a4d36ad88fc6921a)) + +## [5.4.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.3.0...v5.4.0) (2019-10-08) + + +### Features + +* do not deprecate refreshAccessToken ([#804](https://www.github.com/googleapis/google-auth-library-nodejs/issues/804)) ([f05de11](https://www.github.com/googleapis/google-auth-library-nodejs/commit/f05de11)) + +## [5.3.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.2.2...v5.3.0) (2019-09-27) + + +### Features + +* if token expires soon, force refresh ([#794](https://www.github.com/googleapis/google-auth-library-nodejs/issues/794)) ([fecd4f4](https://www.github.com/googleapis/google-auth-library-nodejs/commit/fecd4f4)) + +### [5.2.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.2.1...v5.2.2) (2019-09-17) + + +### Bug Fixes + +* **deps:** update to gcp-metadata and address envDetect performance issues ([#787](https://www.github.com/googleapis/google-auth-library-nodejs/issues/787)) ([651b5d4](https://www.github.com/googleapis/google-auth-library-nodejs/commit/651b5d4)) + +### [5.2.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.2.0...v5.2.1) (2019-09-06) + + +### Bug Fixes + +* **deps:** nock@next has types that work with our libraries ([#783](https://www.github.com/googleapis/google-auth-library-nodejs/issues/783)) ([a253709](https://www.github.com/googleapis/google-auth-library-nodejs/commit/a253709)) +* **docs:** fix variable name in README.md ([#782](https://www.github.com/googleapis/google-auth-library-nodejs/issues/782)) ([d8c70b9](https://www.github.com/googleapis/google-auth-library-nodejs/commit/d8c70b9)) + +## [5.2.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.1.2...v5.2.0) (2019-08-09) + + +### Features + +* populate x-goog-api-client header for auth ([#772](https://www.github.com/googleapis/google-auth-library-nodejs/issues/772)) ([526dcf6](https://www.github.com/googleapis/google-auth-library-nodejs/commit/526dcf6)) + +### [5.1.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.1.1...v5.1.2) (2019-08-05) + + +### Bug Fixes + +* **deps:** upgrade to gtoken 4.x ([#763](https://www.github.com/googleapis/google-auth-library-nodejs/issues/763)) ([a1fcc25](https://www.github.com/googleapis/google-auth-library-nodejs/commit/a1fcc25)) + +### [5.1.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.1.0...v5.1.1) (2019-07-29) + + +### Bug Fixes + +* **deps:** update dependency google-auth-library to v5 ([#759](https://www.github.com/googleapis/google-auth-library-nodejs/issues/759)) ([e32a12b](https://www.github.com/googleapis/google-auth-library-nodejs/commit/e32a12b)) + +## [5.1.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.0.0...v5.1.0) (2019-07-24) + + +### Features + +* **types:** expose ProjectIdCallback interface ([#753](https://www.github.com/googleapis/google-auth-library-nodejs/issues/753)) ([5577f0d](https://www.github.com/googleapis/google-auth-library-nodejs/commit/5577f0d)) + +## [5.0.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.6...v5.0.0) (2019-07-23) + + +### ⚠ BREAKING CHANGES + +* getOptions() no longer accepts GoogleAuthOptions (#749) + +### Code Refactoring + +* getOptions() no longer accepts GoogleAuthOptions ([#749](https://www.github.com/googleapis/google-auth-library-nodejs/issues/749)) ([ba58e3b](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ba58e3b)) + +### [4.2.6](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.5...v4.2.6) (2019-07-23) + + +### Bug Fixes + +* use FUNCTION_TARGET to detect GCF 10 and above ([#748](https://www.github.com/googleapis/google-auth-library-nodejs/issues/748)) ([ca17685](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ca17685)) + +### [4.2.5](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.4...v4.2.5) (2019-06-26) + + +### Bug Fixes + +* **docs:** make anchors work in jsdoc ([#742](https://www.github.com/googleapis/google-auth-library-nodejs/issues/742)) ([7901456](https://www.github.com/googleapis/google-auth-library-nodejs/commit/7901456)) + +### [4.2.4](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.3...v4.2.4) (2019-06-25) + + +### Bug Fixes + +* only require fast-text-encoding when needed ([#740](https://www.github.com/googleapis/google-auth-library-nodejs/issues/740)) ([04fcd77](https://www.github.com/googleapis/google-auth-library-nodejs/commit/04fcd77)) + +### [4.2.3](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.2...v4.2.3) (2019-06-24) + + +### Bug Fixes + +* feature detection to check for browser ([#738](https://www.github.com/googleapis/google-auth-library-nodejs/issues/738)) ([83a5ba5](https://www.github.com/googleapis/google-auth-library-nodejs/commit/83a5ba5)) + +### [4.2.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.1...v4.2.2) (2019-06-18) + + +### Bug Fixes + +* **compute:** correctly specify scopes when fetching token ([#735](https://www.github.com/googleapis/google-auth-library-nodejs/issues/735)) ([4803e3c](https://www.github.com/googleapis/google-auth-library-nodejs/commit/4803e3c)) + +### [4.2.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.0...v4.2.1) (2019-06-14) + + +### Bug Fixes + +* **docs:** move to new client docs URL ([#733](https://www.github.com/googleapis/google-auth-library-nodejs/issues/733)) ([cfbbe2a](https://www.github.com/googleapis/google-auth-library-nodejs/commit/cfbbe2a)) + +## [4.2.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.1.0...v4.2.0) (2019-06-05) + + +### Bug Fixes + +* pad base64 strings for base64js ([#722](https://www.github.com/googleapis/google-auth-library-nodejs/issues/722)) ([81e0a23](https://www.github.com/googleapis/google-auth-library-nodejs/commit/81e0a23)) + + +### Features + +* make both crypto implementations support sign ([#727](https://www.github.com/googleapis/google-auth-library-nodejs/issues/727)) ([e445fb3](https://www.github.com/googleapis/google-auth-library-nodejs/commit/e445fb3)) + +## [4.1.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.0.0...v4.1.0) (2019-05-29) + + +### Bug Fixes + +* **deps:** update dependency google-auth-library to v4 ([#705](https://www.github.com/googleapis/google-auth-library-nodejs/issues/705)) ([2b13344](https://www.github.com/googleapis/google-auth-library-nodejs/commit/2b13344)) + + +### Features + +* use X-Goog-Api-Key header ([#719](https://www.github.com/googleapis/google-auth-library-nodejs/issues/719)) ([35471d0](https://www.github.com/googleapis/google-auth-library-nodejs/commit/35471d0)) + +## [4.0.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v3.1.2...v4.0.0) (2019-05-08) + + +### Bug Fixes + +* **deps:** update dependency arrify to v2 ([#684](https://www.github.com/googleapis/google-auth-library-nodejs/issues/684)) ([1757ee2](https://www.github.com/googleapis/google-auth-library-nodejs/commit/1757ee2)) +* **deps:** update dependency gaxios to v2 ([#681](https://www.github.com/googleapis/google-auth-library-nodejs/issues/681)) ([770ad2f](https://www.github.com/googleapis/google-auth-library-nodejs/commit/770ad2f)) +* **deps:** update dependency gcp-metadata to v2 ([#701](https://www.github.com/googleapis/google-auth-library-nodejs/issues/701)) ([be20528](https://www.github.com/googleapis/google-auth-library-nodejs/commit/be20528)) +* **deps:** update dependency gtoken to v3 ([#702](https://www.github.com/googleapis/google-auth-library-nodejs/issues/702)) ([2c538e5](https://www.github.com/googleapis/google-auth-library-nodejs/commit/2c538e5)) +* re-throw original exception and preserve message in compute client ([#668](https://www.github.com/googleapis/google-auth-library-nodejs/issues/668)) ([dffd1cc](https://www.github.com/googleapis/google-auth-library-nodejs/commit/dffd1cc)) +* surface original stack trace and message with errors ([#651](https://www.github.com/googleapis/google-auth-library-nodejs/issues/651)) ([8fb65eb](https://www.github.com/googleapis/google-auth-library-nodejs/commit/8fb65eb)) +* throw on missing refresh token in all cases ([#670](https://www.github.com/googleapis/google-auth-library-nodejs/issues/670)) ([0a02946](https://www.github.com/googleapis/google-auth-library-nodejs/commit/0a02946)) +* throw when adc cannot acquire a projectId ([#658](https://www.github.com/googleapis/google-auth-library-nodejs/issues/658)) ([ba48164](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ba48164)) +* **deps:** update dependency semver to v6 ([#655](https://www.github.com/googleapis/google-auth-library-nodejs/issues/655)) ([ec56c88](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ec56c88)) + + +### Build System + +* upgrade engines field to >=8.10.0 ([#686](https://www.github.com/googleapis/google-auth-library-nodejs/issues/686)) ([377d5c6](https://www.github.com/googleapis/google-auth-library-nodejs/commit/377d5c6)) + + +### Features + +* support scopes on compute credentials ([#642](https://www.github.com/googleapis/google-auth-library-nodejs/issues/642)) ([1811b7f](https://www.github.com/googleapis/google-auth-library-nodejs/commit/1811b7f)) + + +### BREAKING CHANGES + +* upgrade engines field to >=8.10.0 (#686) + +## v3.1.2 + +03-22-2019 15:38 PDT + +### Implementation Changes +- fix: getCredential(): load credentials with getClient() ([#648](https://github.com/google/google-auth-library-nodejs/pull/648)) + +### Internal / Testing Changes +- chore: publish to npm using wombat ([#645](https://github.com/google/google-auth-library-nodejs/pull/645)) + +## v3.1.1 + +03-18-2019 08:32 PDT + +### Bug Fixes +- fix: Avoid loading fast-text-encoding if not in browser environment ([#627](https://github.com/google/google-auth-library-nodejs/pull/627)) + +### Dependencies +- fix(deps): update dependency gcp-metadata to v1 ([#632](https://github.com/google/google-auth-library-nodejs/pull/632)) + +### Documentation +- docs: update links in contrib guide ([#630](https://github.com/google/google-auth-library-nodejs/pull/630)) + +### Internal / Testing Changes +- build: use per-repo publish token ([#641](https://github.com/google/google-auth-library-nodejs/pull/641)) +- build: Add docuploader credentials to node publish jobs ([#639](https://github.com/google/google-auth-library-nodejs/pull/639)) +- build: use node10 to run samples-test, system-test etc ([#638](https://github.com/google/google-auth-library-nodejs/pull/638)) +- build: update release configuration +- chore(deps): update dependency @types/lru-cache to v5 ([#635](https://github.com/google/google-auth-library-nodejs/pull/635)) +- chore(deps): update dependency mocha to v6 +- chore: fix lint ([#631](https://github.com/google/google-auth-library-nodejs/pull/631)) +- build: use linkinator for docs test ([#628](https://github.com/google/google-auth-library-nodejs/pull/628)) +- chore(deps): update dependency @types/tmp to ^0.0.34 ([#629](https://github.com/google/google-auth-library-nodejs/pull/629)) +- build: create docs test npm scripts ([#625](https://github.com/google/google-auth-library-nodejs/pull/625)) +- build: test using @grpc/grpc-js in CI ([#624](https://github.com/google/google-auth-library-nodejs/pull/624)) + +## v3.1.0 + +02-08-2019 08:29 PST + +### Bug fixes +- fix: use key file when fetching project id ([#618](https://github.com/googleapis/google-auth-library-nodejs/pull/618)) +- fix: Throw error if there is no refresh token despite the necessity of refreshing ([#605](https://github.com/googleapis/google-auth-library-nodejs/pull/605)) + +### New Features +- feat: allow passing constructor options to getClient ([#611](https://github.com/googleapis/google-auth-library-nodejs/pull/611)) + +### Documentation +- docs: update contributing path in README ([#621](https://github.com/googleapis/google-auth-library-nodejs/pull/621)) +- chore: move CONTRIBUTING.md to root ([#619](https://github.com/googleapis/google-auth-library-nodejs/pull/619)) +- docs: add lint/fix example to contributing guide ([#615](https://github.com/googleapis/google-auth-library-nodejs/pull/615)) +- docs: use the People API for samples ([#609](https://github.com/googleapis/google-auth-library-nodejs/pull/609)) + +### Internal / Testing Changes +- chore(deps): update dependency typescript to ~3.3.0 ([#612](https://github.com/googleapis/google-auth-library-nodejs/pull/612)) +- chore(deps): update dependency eslint-config-prettier to v4 ([#604](https://github.com/googleapis/google-auth-library-nodejs/pull/604)) +- build: ignore googleapis.com in doc link check ([#602](https://github.com/googleapis/google-auth-library-nodejs/pull/602)) +- chore(deps): update dependency karma to v4 ([#603](https://github.com/googleapis/google-auth-library-nodejs/pull/603)) + +## v3.0.1 + +01-16-2019 21:04 PST + +### Bug Fixes +- fix(deps): upgrade to the latest gaxios ([#596](https://github.com/googleapis/google-auth-library-nodejs/pull/596)) + +## v3.0.0 + +01-16-2019 10:00 PST + +Welcome to 3.0 🎉 This release has it all. New features, bug fixes, breaking changes, performance improvements - something for everyone! The biggest addition to this release is support for the browser via Webpack. + +**This release has breaking changes.** This release has a few breaking changes. These changes are unlikely to affect most clients. + +#### BREAKING: Migration from `axios` to `gaxios` +The 2.0 version of this library used the [axios](https://github.com/axios/axios) library for making HTTP requests. In the 3.0 release, this has been replaced by a *mostly* API compatible library [gaxios](https://github.com/JustinBeckwith/gaxios). The new request library natively supports proxies, and comes with a smaller dependency chain. While this is mostly an implementation detail, the `request` method was directly exposed via the `GoogleAuth.request` and `OAuth2Client.request` methods. The gaxios library aims to provide an API compatible implementation of axios, but that can never be 100% promised. If you run into bugs or differences that cause issues - please do let us know. + +#### BREAKING: `generateCodeVerifier` is now `generateCodeVerifierAsync` +The `OAuth2Client.generateCodeVerifier` method has been replaced by the `OAuth2Client.generateCodeVerifierAsync` method. It has changed from a synchronous method to an asynchronous method to support async browser crypto APIs required for Webpack support. + +#### BREAKING: `verifySignedJwtWithCerts` is now `verifySignedJwtWithCertsAsync` +The `OAuth2Client.verifySignedJwtWithCerts` method has been replaced by the `OAuth2Client.verifySignedJwtWithCertsAsync` method. It has changed from a synchronous method to an asynchronous method to support async browser crypto APIs required for Webpack support. + + +### New Features +- feat: make it webpackable ([#371](https://github.com/google/google-auth-library-nodejs/pull/371)) + +### Bug Fixes +- fix: accept lowercase env vars ([#578](https://github.com/google/google-auth-library-nodejs/pull/578)) + +### Dependencies +- chore(deps): update gtoken ([#592](https://github.com/google/google-auth-library-nodejs/pull/592)) +- fix(deps): upgrade to gcp-metadata v0.9.3 ([#586](https://github.com/google/google-auth-library-nodejs/pull/586)) + +### Documentation +- docs: update bug report link ([#585](https://github.com/google/google-auth-library-nodejs/pull/585)) +- docs: clarify access and refresh token docs ([#577](https://github.com/google/google-auth-library-nodejs/pull/577)) + +### Internal / Testing Changes +- refactor(deps): use `gaxios` for HTTP requests instead of `axios` ([#593](https://github.com/google/google-auth-library-nodejs/pull/593)) +- fix: some browser fixes ([#590](https://github.com/google/google-auth-library-nodejs/pull/590)) +- chore(deps): update dependency ts-loader to v5 ([#588](https://github.com/google/google-auth-library-nodejs/pull/588)) +- chore(deps): update dependency karma to v3 ([#587](https://github.com/google/google-auth-library-nodejs/pull/587)) +- build: check broken links in generated docs ([#579](https://github.com/google/google-auth-library-nodejs/pull/579)) +- chore(deps): drop unused dep on typedoc ([#583](https://github.com/google/google-auth-library-nodejs/pull/583)) +- build: add browser test running on Kokoro ([#584](https://github.com/google/google-auth-library-nodejs/pull/584)) +- test: improve samples and add tests ([#576](https://github.com/google/google-auth-library-nodejs/pull/576)) + +## v2.0.2 + +12-16-2018 10:48 PST + +### Fixes +- fix(types): export GCPEnv type ([#569](https://github.com/google/google-auth-library-nodejs/pull/569)) +- fix: use post for token revocation ([#524](https://github.com/google/google-auth-library-nodejs/pull/524)) + +### Dependencies +- fix(deps): update dependency lru-cache to v5 ([#541](https://github.com/google/google-auth-library-nodejs/pull/541)) + +### Documentation +- docs: add ref docs again ([#553](https://github.com/google/google-auth-library-nodejs/pull/553)) +- docs: clean up the readme ([#554](https://github.com/google/google-auth-library-nodejs/pull/554)) + +### Internal / Testing Changes +- chore(deps): update dependency @types/sinon to v7 ([#568](https://github.com/google/google-auth-library-nodejs/pull/568)) +- refactor: use execa for install tests, run eslint on samples ([#559](https://github.com/google/google-auth-library-nodejs/pull/559)) +- chore(build): inject yoshi automation key ([#566](https://github.com/google/google-auth-library-nodejs/pull/566)) +- chore: update nyc and eslint configs ([#565](https://github.com/google/google-auth-library-nodejs/pull/565)) +- chore: fix publish.sh permission +x ([#563](https://github.com/google/google-auth-library-nodejs/pull/563)) +- fix(build): fix Kokoro release script ([#562](https://github.com/google/google-auth-library-nodejs/pull/562)) +- build: add Kokoro configs for autorelease ([#561](https://github.com/google/google-auth-library-nodejs/pull/561)) +- chore: always nyc report before calling codecov ([#557](https://github.com/google/google-auth-library-nodejs/pull/557)) +- chore: nyc ignore build/test by default ([#556](https://github.com/google/google-auth-library-nodejs/pull/556)) +- chore(build): update the prettier and renovate config ([#552](https://github.com/google/google-auth-library-nodejs/pull/552)) +- chore: update license file ([#551](https://github.com/google/google-auth-library-nodejs/pull/551)) +- fix(build): fix system key decryption ([#547](https://github.com/google/google-auth-library-nodejs/pull/547)) +- chore(deps): update dependency typescript to ~3.2.0 ([#546](https://github.com/google/google-auth-library-nodejs/pull/546)) +- chore(deps): unpin sinon ([#544](https://github.com/google/google-auth-library-nodejs/pull/544)) +- refactor: drop non-required modules ([#542](https://github.com/google/google-auth-library-nodejs/pull/542)) +- chore: add synth.metadata ([#537](https://github.com/google/google-auth-library-nodejs/pull/537)) +- fix: Pin @types/sinon to last compatible version ([#538](https://github.com/google/google-auth-library-nodejs/pull/538)) +- chore(deps): update dependency gts to ^0.9.0 ([#531](https://github.com/google/google-auth-library-nodejs/pull/531)) +- chore: update eslintignore config ([#530](https://github.com/google/google-auth-library-nodejs/pull/530)) +- chore: drop contributors from multiple places ([#528](https://github.com/google/google-auth-library-nodejs/pull/528)) +- chore: use latest npm on Windows ([#527](https://github.com/google/google-auth-library-nodejs/pull/527)) +- chore: update CircleCI config ([#523](https://github.com/google/google-auth-library-nodejs/pull/523)) +- chore: include build in eslintignore ([#516](https://github.com/google/google-auth-library-nodejs/pull/516)) + +## v2.0.1 + +### Implementation Changes +- fix: verifyIdToken will never return null ([#488](https://github.com/google/google-auth-library-nodejs/pull/488)) +- Update the url to application default credentials ([#470](https://github.com/google/google-auth-library-nodejs/pull/470)) +- Update omitted parameter 'hd' ([#467](https://github.com/google/google-auth-library-nodejs/pull/467)) + +### Dependencies +- chore(deps): update dependency nock to v10 ([#501](https://github.com/google/google-auth-library-nodejs/pull/501)) +- chore(deps): update dependency sinon to v7 ([#502](https://github.com/google/google-auth-library-nodejs/pull/502)) +- chore(deps): update dependency typescript to v3.1.3 ([#503](https://github.com/google/google-auth-library-nodejs/pull/503)) +- chore(deps): update dependency gh-pages to v2 ([#499](https://github.com/google/google-auth-library-nodejs/pull/499)) +- chore(deps): update dependency typedoc to ^0.13.0 ([#497](https://github.com/google/google-auth-library-nodejs/pull/497)) + +### Documentation +- docs: Remove code format from Application Default Credentials ([#483](https://github.com/google/google-auth-library-nodejs/pull/483)) +- docs: replace google/ with googleapis/ in URIs ([#472](https://github.com/google/google-auth-library-nodejs/pull/472)) +- Fix typo in readme ([#469](https://github.com/google/google-auth-library-nodejs/pull/469)) +- Update samples and docs for 2.0 ([#459](https://github.com/google/google-auth-library-nodejs/pull/459)) + +### Internal / Testing Changes +- chore: update issue templates ([#509](https://github.com/google/google-auth-library-nodejs/pull/509)) +- chore: remove old issue template ([#507](https://github.com/google/google-auth-library-nodejs/pull/507)) +- build: run tests on node11 ([#506](https://github.com/google/google-auth-library-nodejs/pull/506)) +- chore(build): drop hard rejection and update gts in the kitchen test ([#504](https://github.com/google/google-auth-library-nodejs/pull/504)) +- chores(build): do not collect sponge.xml from windows builds ([#500](https://github.com/google/google-auth-library-nodejs/pull/500)) +- chores(build): run codecov on continuous builds ([#495](https://github.com/google/google-auth-library-nodejs/pull/495)) +- chore: update new issue template ([#494](https://github.com/google/google-auth-library-nodejs/pull/494)) +- build: fix codecov uploading on Kokoro ([#490](https://github.com/google/google-auth-library-nodejs/pull/490)) +- test: move kitchen sink tests to system-test ([#489](https://github.com/google/google-auth-library-nodejs/pull/489)) +- Update kokoro config ([#482](https://github.com/google/google-auth-library-nodejs/pull/482)) +- fix: export additional typescript types ([#479](https://github.com/google/google-auth-library-nodejs/pull/479)) +- Don't publish sourcemaps ([#478](https://github.com/google/google-auth-library-nodejs/pull/478)) +- test: remove appveyor config ([#477](https://github.com/google/google-auth-library-nodejs/pull/477)) +- Enable prefer-const in the eslint config ([#473](https://github.com/google/google-auth-library-nodejs/pull/473)) +- Enable no-var in eslint ([#471](https://github.com/google/google-auth-library-nodejs/pull/471)) +- Update CI config ([#468](https://github.com/google/google-auth-library-nodejs/pull/468)) +- Retry npm install in CI ([#465](https://github.com/google/google-auth-library-nodejs/pull/465)) +- Update Kokoro config ([#462](https://github.com/google/google-auth-library-nodejs/pull/462)) + +## v2.0.0 + +Well hello 2.0 🎉 **This release has multiple breaking changes**. It also has a lot of bug fixes. + +### Breaking Changes + +#### Support for node.js 4.x and 9.x has been dropped +These versions of node.js are no longer supported. + +#### The `getRequestMetadata` method has been deprecated +The `getRequestMetadata` method has been deprecated on the `IAM`, `OAuth2`, `JWT`, and `JWTAccess` classes. The `getRequestHeaders` method should be used instead. The methods have a subtle difference: the `getRequestMetadata` method returns an object with a headers property, which contains the authorization header. The `getRequestHeaders` method simply returns the headers. + +##### Old code +```js +const client = await auth.getClient(); +const res = await client.getRequestMetadata(); +const headers = res.headers; +``` + +##### New code +```js +const client = await auth.getClient(); +const headers = await client.getRequestHeaders(); +``` + +#### The `createScopedRequired` method has been deprecated +The `createScopedRequired` method has been deprecated on multiple classes. The `createScopedRequired` and `createScoped` methods on the `JWT` class were largely in place to help inform clients when scopes were required in an application default credential scenario. Instead of checking if scopes are required after creating the client, instead scopes should just be passed either into the `GoogleAuth.getClient` method, or directly into the `JWT` constructor. + +##### Old code +```js +auth.getApplicationDefault(function(err, authClient) { + if (err) { + return callback(err); + } + if (authClient.createScopedRequired && authClient.createScopedRequired()) { + authClient = authClient.createScoped([ + 'https://www.googleapis.com/auth/cloud-platform' + ]); + } + callback(null, authClient); +}); +``` + +##### New code +```js +const client = await auth.getClient({ + scopes: ['https://www.googleapis.com/auth/cloud-platform'] +}); +``` + +#### Deprecate `refreshAccessToken` + +_Note: `refreshAccessToken` is no longer deprecated._ + +`getAccessToken`, `getRequestMetadata`, and `request` methods will all refresh the token if needed automatically. + +You should not need to invoke `refreshAccessToken` directly except in [certain edge-cases](https://github.com/googleapis/google-auth-library-nodejs/issues/575). + +### Features +- Set private_key_id in JWT access token header like other google auth libraries. (#450) + +### Bug Fixes +- fix: support HTTPS proxies (#405) +- fix: export missing interfaces (#437) +- fix: Use new auth URIs (#434) +- docs: Fix broken link (#423) +- fix: surface file read streams (#413) +- fix: prevent unhandled rejections by avoid .catch (#404) +- fix: use gcp-metadata for compute credentials (#409) +- Add Code of Conduct +- fix: Warn when using user credentials from the Cloud SDK (#399) +- fix: use `Buffer.from` instead of `new Buffer` (#400) +- fix: Fix link format in README.md (#385) + +### Breaking changes +- chore: deprecate getRequestMetadata (#414) +- fix: deprecate the `createScopedRequired` methods (#410) +- fix: drop support for node.js 4.x and 9.x (#417) +- fix: deprecate the `refreshAccessToken` methods (#411) +- fix: deprecate the `getDefaultProjectId` method (#402) +- fix: drop support for node.js 4 (#401) + +### Build / Test changes +- Run synth to make build tools consistent (#455) +- Add a package.json for samples and cleanup README (#454) +- chore(deps): update dependency typedoc to ^0.12.0 (#453) +- chore: move examples => samples + synth (#448) +- chore(deps): update dependency nyc to v13 (#452) +- chore(deps): update dependency pify to v4 (#447) +- chore(deps): update dependency assert-rejects to v1 (#446) +- chore: ignore package-lock.json (#445) +- chore: update renovate config (#442) +- chore(deps): lock file maintenance (#443) +- chore: remove greenkeeper badge (#440) +- test: throw on deprecation +- chore: add intelli-espower-loader for running tests (#430) +- chore(deps): update dependency typescript to v3 (#432) +- chore(deps): lock file maintenance (#431) +- test: use strictEqual in tests (#425) +- chore(deps): lock file maintenance (#428) +- chore: Configure Renovate (#424) +- chore: Update gts to the latest version 🚀 (#422) +- chore: update gcp-metadata for isAvailable fix (#420) +- refactor: use assert.reject in the tests (#415) +- refactor: cleanup types for certificates (#412) +- test: run tests with hard-rejection (#397) +- cleanup: straighten nested try-catch (#394) +- test: getDefaultProjectId should prefer config (#388) +- chore(package): Update gts to the latest version 🚀 (#387) +- chore(package): update sinon to version 6.0.0 (#386) + +## Upgrading to 1.x +The `1.x` release includes a variety of bug fixes, new features, and breaking changes. Please take care, and see [the release notes](https://github.com/googleapis/google-auth-library-nodejs/releases/tag/v1.0.0) for a list of breaking changes, and the upgrade guide. diff --git a/node_modules/google-auth-library/LICENSE b/node_modules/google-auth-library/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/google-auth-library/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/google-auth-library/README.md b/node_modules/google-auth-library/README.md new file mode 100644 index 0000000..4e9255e --- /dev/null +++ b/node_modules/google-auth-library/README.md @@ -0,0 +1,1470 @@ +[//]: # "This README.md file is auto-generated, all changes to this file will be lost." +[//]: # "To regenerate it, use `python -m synthtool`." +Google Cloud Platform logo + +# [Google Auth Library: Node.js Client](https://github.com/googleapis/google-auth-library-nodejs) + +[![release level](https://img.shields.io/badge/release%20level-stable-brightgreen.svg?style=flat)](https://cloud.google.com/terms/launch-stages) +[![npm version](https://img.shields.io/npm/v/google-auth-library.svg)](https://www.npmjs.org/package/google-auth-library) + + + + +This is Google's officially supported [node.js](http://nodejs.org/) client library for using OAuth 2.0 authorization and authentication with Google APIs. + + +A comprehensive list of changes in each version may be found in +[the CHANGELOG](https://github.com/googleapis/google-auth-library-nodejs/blob/main/CHANGELOG.md). + +* [Google Auth Library Node.js Client API Reference][client-docs] +* [Google Auth Library Documentation][product-docs] +* [github.com/googleapis/google-auth-library-nodejs](https://github.com/googleapis/google-auth-library-nodejs) + +Read more about the client libraries for Cloud APIs, including the older +Google APIs Client Libraries, in [Client Libraries Explained][explained]. + +[explained]: https://cloud.google.com/apis/docs/client-libraries-explained + +**Table of contents:** + + +* [Quickstart](#quickstart) + + * [Installing the client library](#installing-the-client-library) + +* [Samples](#samples) +* [Versioning](#versioning) +* [Contributing](#contributing) +* [License](#license) + +## Quickstart + +### Installing the client library + +```bash +npm install google-auth-library +``` + +## Ways to authenticate +This library provides a variety of ways to authenticate to your Google services. +- [Application Default Credentials](#choosing-the-correct-credential-type-automatically) - Use Application Default Credentials when you use a single identity for all users in your application. Especially useful for applications running on Google Cloud. Application Default Credentials also support workload identity federation to access Google Cloud resources from non-Google Cloud platforms. +- [OAuth 2](#oauth2) - Use OAuth2 when you need to perform actions on behalf of the end user. +- [JSON Web Tokens](#json-web-tokens) - Use JWT when you are using a single identity for all users. Especially useful for server->server or server->API communication. +- [Google Compute](#compute) - Directly use a service account on Google Cloud Platform. Useful for server->server or server->API communication. +- [Workload Identity Federation](#workload-identity-federation) - Use workload identity federation to access Google Cloud resources from Amazon Web Services (AWS), Microsoft Azure or any identity provider that supports OpenID Connect (OIDC). +- [Workforce Identity Federation](#workforce-identity-federation) - Use workforce identity federation to access Google Cloud resources using an external identity provider (IdP) to authenticate and authorize a workforce—a group of users, such as employees, partners, and contractors—using IAM, so that the users can access Google Cloud services. +- [Impersonated Credentials Client](#impersonated-credentials-client) - access protected resources on behalf of another service account. +- [Downscoped Client](#downscoped-client) - Use Downscoped Client with Credential Access Boundary to generate a short-lived credential with downscoped, restricted IAM permissions that can use for Cloud Storage. + +## Application Default Credentials +This library provides an implementation of [Application Default Credentials](https://cloud.google.com/docs/authentication/getting-started) for Node.js. The [Application Default Credentials](https://cloud.google.com/docs/authentication/getting-started) provide a simple way to get authorization credentials for use in calling Google APIs. + +They are best suited for cases when the call needs to have the same identity and authorization level for the application independent of the user. This is the recommended approach to authorize calls to Cloud APIs, particularly when you're building an application that uses Google Cloud Platform. + +Application Default Credentials also support workload identity federation to access Google Cloud resources from non-Google Cloud platforms including Amazon Web Services (AWS), Microsoft Azure or any identity provider that supports OpenID Connect (OIDC). Workload identity federation is recommended for non-Google Cloud environments as it avoids the need to download, manage and store service account private keys locally, see: [Workload Identity Federation](#workload-identity-federation). + +#### Download your Service Account Credentials JSON file + +To use Application Default Credentials, You first need to download a set of JSON credentials for your project. Go to **APIs & Auth** > **Credentials** in the [Google Developers Console](https://console.cloud.google.com/) and select **Service account** from the **Add credentials** dropdown. + +> This file is your *only copy* of these credentials. It should never be +> committed with your source code, and should be stored securely. + +Once downloaded, store the path to this file in the `GOOGLE_APPLICATION_CREDENTIALS` environment variable. + +#### Enable the API you want to use + +Before making your API call, you must be sure the API you're calling has been enabled. Go to **APIs & Auth** > **APIs** in the [Google Developers Console](https://console.cloud.google.com/) and enable the APIs you'd like to call. For the example below, you must enable the `DNS API`. + + +#### Choosing the correct credential type automatically + +Rather than manually creating an OAuth2 client, JWT client, or Compute client, the auth library can create the correct credential type for you, depending upon the environment your code is running under. + +For example, a JWT auth client will be created when your code is running on your local developer machine, and a Compute client will be created when the same code is running on Google Cloud Platform. If you need a specific set of scopes, you can pass those in the form of a string or an array to the `GoogleAuth` constructor. + +The code below shows how to retrieve a default credential type, depending upon the runtime environment. + +```js +const {GoogleAuth} = require('google-auth-library'); + +/** +* Instead of specifying the type of client you'd like to use (JWT, OAuth2, etc) +* this library will automatically choose the right client based on the environment. +*/ +async function main() { + const auth = new GoogleAuth({ + scopes: 'https://www.googleapis.com/auth/cloud-platform' + }); + const client = await auth.getClient(); + const projectId = await auth.getProjectId(); + const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; + const res = await client.request({ url }); + console.log(res.data); +} + +main().catch(console.error); +``` + +## OAuth2 + +This library comes with an [OAuth2](https://developers.google.com/identity/protocols/OAuth2) client that allows you to retrieve an access token and refreshes the token and retry the request seamlessly if you also provide an `expiry_date` and the token is expired. The basics of Google's OAuth2 implementation is explained on [Google Authorization and Authentication documentation](https://developers.google.com/accounts/docs/OAuth2Login). + +In the following examples, you may need a `CLIENT_ID`, `CLIENT_SECRET` and `REDIRECT_URL`. You can find these pieces of information by going to the [Developer Console](https://console.cloud.google.com/), clicking your project > APIs & auth > credentials. + +For more information about OAuth2 and how it works, [see here](https://developers.google.com/identity/protocols/OAuth2). + +#### A complete OAuth2 example + +Let's take a look at a complete example. + +``` js +const {OAuth2Client} = require('google-auth-library'); +const http = require('http'); +const url = require('url'); +const open = require('open'); +const destroyer = require('server-destroy'); + +// Download your OAuth2 configuration from the Google +const keys = require('./oauth2.keys.json'); + +/** +* Start by acquiring a pre-authenticated oAuth2 client. +*/ +async function main() { + const oAuth2Client = await getAuthenticatedClient(); + // Make a simple request to the People API using our pre-authenticated client. The `request()` method + // takes an GaxiosOptions object. Visit https://github.com/JustinBeckwith/gaxios. + const url = 'https://people.googleapis.com/v1/people/me?personFields=names'; + const res = await oAuth2Client.request({url}); + console.log(res.data); + + // After acquiring an access_token, you may want to check on the audience, expiration, + // or original scopes requested. You can do that with the `getTokenInfo` method. + const tokenInfo = await oAuth2Client.getTokenInfo( + oAuth2Client.credentials.access_token + ); + console.log(tokenInfo); +} + +/** +* Create a new OAuth2Client, and go through the OAuth2 content +* workflow. Return the full client to the callback. +*/ +function getAuthenticatedClient() { + return new Promise((resolve, reject) => { + // create an oAuth client to authorize the API call. Secrets are kept in a `keys.json` file, + // which should be downloaded from the Google Developers Console. + const oAuth2Client = new OAuth2Client( + keys.web.client_id, + keys.web.client_secret, + keys.web.redirect_uris[0] + ); + + // Generate the url that will be used for the consent dialog. + const authorizeUrl = oAuth2Client.generateAuthUrl({ + access_type: 'offline', + scope: 'https://www.googleapis.com/auth/userinfo.profile', + }); + + // Open an http server to accept the oauth callback. In this simple example, the + // only request to our webserver is to /oauth2callback?code= + const server = http + .createServer(async (req, res) => { + try { + if (req.url.indexOf('/oauth2callback') > -1) { + // acquire the code from the querystring, and close the web server. + const qs = new url.URL(req.url, 'http://localhost:3000') + .searchParams; + const code = qs.get('code'); + console.log(`Code is ${code}`); + res.end('Authentication successful! Please return to the console.'); + server.destroy(); + + // Now that we have the code, use that to acquire tokens. + const r = await oAuth2Client.getToken(code); + // Make sure to set the credentials on the OAuth2 client. + oAuth2Client.setCredentials(r.tokens); + console.info('Tokens acquired.'); + resolve(oAuth2Client); + } + } catch (e) { + reject(e); + } + }) + .listen(3000, () => { + // open the browser to the authorize url to start the workflow + open(authorizeUrl, {wait: false}).then(cp => cp.unref()); + }); + destroyer(server); + }); +} + +main().catch(console.error); +``` + +#### Handling token events + +This library will automatically obtain an `access_token`, and automatically refresh the `access_token` if a `refresh_token` is present. The `refresh_token` is only returned on the [first authorization](https://github.com/googleapis/google-api-nodejs-client/issues/750#issuecomment-304521450), so if you want to make sure you store it safely. An easy way to make sure you always store the most recent tokens is to use the `tokens` event: + +```js +const client = await auth.getClient(); + +client.on('tokens', (tokens) => { + if (tokens.refresh_token) { + // store the refresh_token in my database! + console.log(tokens.refresh_token); + } + console.log(tokens.access_token); +}); + +const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; +const res = await client.request({ url }); +// The `tokens` event would now be raised if this was the first request +``` + +#### Retrieve access token +With the code returned, you can ask for an access token as shown below: + +``` js +const tokens = await oauth2Client.getToken(code); +// Now tokens contains an access_token and an optional refresh_token. Save them. +oauth2Client.setCredentials(tokens); +``` + +#### Obtaining a new Refresh Token +If you need to obtain a new `refresh_token`, ensure the call to `generateAuthUrl` sets the `access_type` to `offline`. The refresh token will only be returned for the first authorization by the user. To force consent, set the `prompt` property to `consent`: + +```js +// Generate the url that will be used for the consent dialog. +const authorizeUrl = oAuth2Client.generateAuthUrl({ + // To get a refresh token, you MUST set access_type to `offline`. + access_type: 'offline', + // set the appropriate scopes + scope: 'https://www.googleapis.com/auth/userinfo.profile', + // A refresh token is only returned the first time the user + // consents to providing access. For illustration purposes, + // setting the prompt to 'consent' will force this consent + // every time, forcing a refresh_token to be returned. + prompt: 'consent' +}); +``` + +#### Checking `access_token` information +After obtaining and storing an `access_token`, at a later time you may want to go check the expiration date, +original scopes, or audience for the token. To get the token info, you can use the `getTokenInfo` method: + +```js +// after acquiring an oAuth2Client... +const tokenInfo = await oAuth2Client.getTokenInfo('my-access-token'); + +// take a look at the scopes originally provisioned for the access token +console.log(tokenInfo.scopes); +``` + +This method will throw if the token is invalid. + +#### Using an API Key + +An API key can be provided to the constructor: +```js +const client = new OAuth2Client({ + apiKey: 'my-api-key' +}); +``` + +Note, classes that extend from this can utilize this parameter as well, such as `JWT` and `UserRefreshClient`. + +Additionally, an API key can be used in `GoogleAuth` via the `clientOptions` parameter and will be passed to any generated `OAuth2Client` instances: +```js +const auth = new GoogleAuth({ + clientOptions: { + apiKey: 'my-api-key' + } +}) +``` + +API Key support varies by API. + +## JSON Web Tokens +The Google Developers Console provides a `.json` file that you can use to configure a JWT auth client and authenticate your requests, for example when using a service account. + +``` js +const {JWT} = require('google-auth-library'); +const keys = require('./jwt.keys.json'); + +async function main() { + const client = new JWT({ + email: keys.client_email, + key: keys.private_key, + scopes: ['https://www.googleapis.com/auth/cloud-platform'], + }); + const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`; + const res = await client.request({url}); + console.log(res.data); +} + +main().catch(console.error); +``` + +The parameters for the JWT auth client including how to use it with a `.pem` file are explained in [samples/jwt.js](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/jwt.js). + +#### Loading credentials from environment variables +Instead of loading credentials from a key file, you can also provide them using an environment variable and the `GoogleAuth.fromJSON()` method. This is particularly convenient for systems that deploy directly from source control (Heroku, App Engine, etc). + +Start by exporting your credentials: + +``` +$ export CREDS='{ + "type": "service_account", + "project_id": "your-project-id", + "private_key_id": "your-private-key-id", + "private_key": "your-private-key", + "client_email": "your-client-email", + "client_id": "your-client-id", + "auth_uri": "https://accounts.google.com/o/oauth2/auth", + "token_uri": "https://accounts.google.com/o/oauth2/token", + "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", + "client_x509_cert_url": "your-cert-url" +}' +``` +Now you can create a new client from the credentials: + +```js +const {auth} = require('google-auth-library'); + +// load the environment variable with our keys +const keysEnvVar = process.env['CREDS']; +if (!keysEnvVar) { + throw new Error('The $CREDS environment variable was not found!'); +} +const keys = JSON.parse(keysEnvVar); + +async function main() { + // load the JWT or UserRefreshClient from the keys + const client = auth.fromJSON(keys); + client.scopes = ['https://www.googleapis.com/auth/cloud-platform']; + const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`; + const res = await client.request({url}); + console.log(res.data); +} + +main().catch(console.error); +``` + +**Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to [Validate credential configurations from external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials). + +#### Using a Proxy +You can set the `HTTPS_PROXY` or `https_proxy` environment variables to proxy HTTPS requests. When `HTTPS_PROXY` or `https_proxy` are set, they will be used to proxy SSL requests that do not have an explicit proxy configuration option present. + +## Compute +If your application is running on Google Cloud Platform, you can authenticate using the default service account or by specifying a specific service account. + +**Note**: In most cases, you will want to use [Application Default Credentials](#choosing-the-correct-credential-type-automatically). Direct use of the `Compute` class is for very specific scenarios. + +``` js +const {auth, Compute} = require('google-auth-library'); + +async function main() { + const client = new Compute({ + // Specifying the service account email is optional. + serviceAccountEmail: 'my-service-account@example.com' + }); + const projectId = await auth.getProjectId(); + const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; + const res = await client.request({url}); + console.log(res.data); +} + +main().catch(console.error); +``` + +## Workload Identity Federation + +Using workload identity federation, your application can access Google Cloud resources from Amazon Web Services (AWS), Microsoft Azure or any identity provider that supports OpenID Connect (OIDC). + +Traditionally, applications running outside Google Cloud have used service account keys to access Google Cloud resources. Using identity federation, you can allow your workload to impersonate a service account. +This lets you access Google Cloud resources directly, eliminating the maintenance and security burden associated with service account keys. + +### Accessing resources from AWS + +In order to access Google Cloud resources from Amazon Web Services (AWS), the following requirements are needed: +- A workload identity pool needs to be created. +- AWS needs to be added as an identity provider in the workload identity pool (The Google [organization policy](https://cloud.google.com/iam/docs/manage-workload-identity-pools-providers#restrict) needs to allow federation from AWS). +- Permission to impersonate a service account needs to be granted to the external identity. + +Follow the detailed [instructions](https://cloud.google.com/iam/docs/access-resources-aws) on how to configure workload identity federation from AWS. + +After configuring the AWS provider to impersonate a service account, a credential configuration file needs to be generated. +Unlike service account credential files, the generated credential configuration file will only contain non-sensitive metadata to instruct the library on how to retrieve external subject tokens and exchange them for service account access tokens. +The configuration file can be generated by using the [gcloud CLI](https://cloud.google.com/sdk/). + +To generate the AWS workload identity configuration, run the following command: + +```bash +# Generate an AWS configuration file. +gcloud iam workload-identity-pools create-cred-config \ + projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AWS_PROVIDER_ID \ + --service-account $SERVICE_ACCOUNT_EMAIL \ + --aws \ + --output-file /path/to/generated/config.json +``` + +Where the following variables need to be substituted: +- `$PROJECT_NUMBER`: The Google Cloud project number. +- `$POOL_ID`: The workload identity pool ID. +- `$AWS_PROVIDER_ID`: The AWS provider ID. +- `$SERVICE_ACCOUNT_EMAIL`: The email of the service account to impersonate. + +This will generate the configuration file in the specified output file. + +If you want to use the AWS IMDSv2 flow, you can add the field below to the credential_source in your AWS ADC configuration file: +"imdsv2_session_token_url": "http://169.254.169.254/latest/api/token" +The gcloud create-cred-config command will be updated to support this soon. + +You can now [start using the Auth library](#using-external-identities) to call Google Cloud resources from AWS. + +### Accessing resources from AWS using a custom AWS security credentials supplier. + +In order to access Google Cloud resources from Amazon Web Services (AWS), the following requirements are needed: +- A workload identity pool needs to be created. +- AWS needs to be added as an identity provider in the workload identity pool (The Google [organization policy](https://cloud.google.com/iam/docs/manage-workload-identity-pools-providers#restrict) needs to allow federation from AWS). +- Permission to impersonate a service account needs to be granted to the external identity. + +Follow the detailed [instructions](https://cloud.google.com/iam/docs/access-resources-aws) on how to configure workload identity federation from AWS. + +If you want to use AWS security credentials that cannot be retrieved using methods supported natively by this library, +a custom AwsSecurityCredentialsSupplier implementation may be specified when creating an AWS client. The supplier must +return valid, unexpired AWS security credentials when called by the GCP credential. Currently, using ADC with your AWS +workloads is only supported with EC2. An example of a good use case for using a custom credential suppliers is when +your workloads are running in other AWS environments, such as ECS, EKS, Fargate, etc. + +Note that the client does not cache the returned AWS security credentials, so caching logic should be implemented in the supplier to prevent multiple requests for the same resources. + +```ts +import { AwsClient, AwsSecurityCredentials, AwsSecurityCredentialsSupplier, ExternalAccountSupplierContext } from 'google-auth-library'; +import { fromNodeProviderChain } from '@aws-sdk/credential-providers'; +import { Storage } from '@google-cloud/storage'; + +class AwsSupplier implements AwsSecurityCredentialsSupplier { + private readonly region: string + + constructor(region: string) { + this.region = options.region; + } + + async getAwsRegion(context: ExternalAccountSupplierContext): Promise { + // Return the AWS region i.e. "us-east-2". + return this.region + } + + async getAwsSecurityCredentials( + context: ExternalAccountSupplierContext + ): Promise { + // Retrieve the AWS credentails. + const awsCredentialsProvider = fromNodeProviderChain(); + const awsCredentials = await awsCredentialsProvider(); + + // Parse the AWS credentials into a AWS security credentials instance and + // return them. + const awsSecurityCredentials = { + accessKeyId: awsCredentials.accessKeyId, + secretAccessKey: awsCredentials.secretAccessKey, + token: awsCredentials.sessionToken + } + return awsSecurityCredentials; + } +} + +const clientOptions = { + audience: '//iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$WORKLOAD_POOL_ID/providers/$PROVIDER_ID', // Set the GCP audience. + subject_token_type: 'urn:ietf:params:aws:token-type:aws4_request', // Set the subject token type. + aws_security_credentials_supplier: new AwsSupplier("AWS_REGION") // Set the custom supplier. + service_account_impersonation_url: 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/$EMAIL:generateAccessToken', // Set the service account impersonation url. +} + +// Create a new Auth client and use it to create service client, i.e. storage. +const authClient = new AwsClient(clientOptions); +const storage = new Storage({ authClient }); +``` + +Where the [audience](https://cloud.google.com/iam/docs/best-practices-for-using-workload-identity-federation#provider-audience) is: `//iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$WORKLOAD_POOL_ID/providers/$PROVIDER_ID` + +Where the following variables need to be substituted: + +* `$PROJECT_NUMBER`: The Google Cloud project number. +* `$WORKLOAD_POOL_ID`: The workload pool ID. +* `$PROVIDER_ID`: The provider ID. + + +The values for audience, service account impersonation URL, and any other builder field can also be found by generating a [credential configuration file with the gcloud CLI](https://cloud.google.com/sdk/gcloud/reference/iam/workload-identity-pools/create-cred-config). + +### Access resources from Microsoft Azure + +In order to access Google Cloud resources from Microsoft Azure, the following requirements are needed: +- A workload identity pool needs to be created. +- Azure needs to be added as an identity provider in the workload identity pool (The Google [organization policy](https://cloud.google.com/iam/docs/manage-workload-identity-pools-providers#restrict) needs to allow federation from Azure). +- The Azure tenant needs to be configured for identity federation. +- Permission to impersonate a service account needs to be granted to the external identity. + +Follow the detailed [instructions](https://cloud.google.com/iam/docs/access-resources-azure) on how to configure workload identity federation from Microsoft Azure. + +After configuring the Azure provider to impersonate a service account, a credential configuration file needs to be generated. +Unlike service account credential files, the generated credential configuration file will only contain non-sensitive metadata to instruct the library on how to retrieve external subject tokens and exchange them for service account access tokens. +The configuration file can be generated by using the [gcloud CLI](https://cloud.google.com/sdk/). + +To generate the Azure workload identity configuration, run the following command: + +```bash +# Generate an Azure configuration file. +gcloud iam workload-identity-pools create-cred-config \ + projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AZURE_PROVIDER_ID \ + --service-account $SERVICE_ACCOUNT_EMAIL \ + --azure \ + --output-file /path/to/generated/config.json +``` + +Where the following variables need to be substituted: +- `$PROJECT_NUMBER`: The Google Cloud project number. +- `$POOL_ID`: The workload identity pool ID. +- `$AZURE_PROVIDER_ID`: The Azure provider ID. +- `$SERVICE_ACCOUNT_EMAIL`: The email of the service account to impersonate. + +This will generate the configuration file in the specified output file. + +You can now [start using the Auth library](#using-external-identities) to call Google Cloud resources from Azure. + +### Accessing resources from an OIDC identity provider + +In order to access Google Cloud resources from an identity provider that supports [OpenID Connect (OIDC)](https://openid.net/connect/), the following requirements are needed: +- A workload identity pool needs to be created. +- An OIDC identity provider needs to be added in the workload identity pool (The Google [organization policy](https://cloud.google.com/iam/docs/manage-workload-identity-pools-providers#restrict) needs to allow federation from the identity provider). +- Permission to impersonate a service account needs to be granted to the external identity. + +Follow the detailed [instructions](https://cloud.google.com/iam/docs/access-resources-oidc) on how to configure workload identity federation from an OIDC identity provider. + +After configuring the OIDC provider to impersonate a service account, a credential configuration file needs to be generated. +Unlike service account credential files, the generated credential configuration file will only contain non-sensitive metadata to instruct the library on how to retrieve external subject tokens and exchange them for service account access tokens. +The configuration file can be generated by using the [gcloud CLI](https://cloud.google.com/sdk/). + +For OIDC providers, the Auth library can retrieve OIDC tokens either from a local file location (file-sourced credentials) or from a local server (URL-sourced credentials). + +**File-sourced credentials** +For file-sourced credentials, a background process needs to be continuously refreshing the file location with a new OIDC token prior to expiration. +For tokens with one hour lifetimes, the token needs to be updated in the file every hour. The token can be stored directly as plain text or in JSON format. + +To generate a file-sourced OIDC configuration, run the following command: + +```bash +# Generate an OIDC configuration file for file-sourced credentials. +gcloud iam workload-identity-pools create-cred-config \ + projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$OIDC_PROVIDER_ID \ + --service-account $SERVICE_ACCOUNT_EMAIL \ + --credential-source-file $PATH_TO_OIDC_ID_TOKEN \ + # Optional arguments for file types. Default is "text": + # --credential-source-type "json" \ + # Optional argument for the field that contains the OIDC credential. + # This is required for json. + # --credential-source-field-name "id_token" \ + --output-file /path/to/generated/config.json +``` + +Where the following variables need to be substituted: +- `$PROJECT_NUMBER`: The Google Cloud project number. +- `$POOL_ID`: The workload identity pool ID. +- `$OIDC_PROVIDER_ID`: The OIDC provider ID. +- `$SERVICE_ACCOUNT_EMAIL`: The email of the service account to impersonate. +- `$PATH_TO_OIDC_ID_TOKEN`: The file path where the OIDC token will be retrieved from. + +This will generate the configuration file in the specified output file. + +**URL-sourced credentials** +For URL-sourced credentials, a local server needs to host a GET endpoint to return the OIDC token. The response can be in plain text or JSON. +Additional required request headers can also be specified. + +To generate a URL-sourced OIDC workload identity configuration, run the following command: + +```bash +# Generate an OIDC configuration file for URL-sourced credentials. +gcloud iam workload-identity-pools create-cred-config \ + projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$OIDC_PROVIDER_ID \ + --service-account $SERVICE_ACCOUNT_EMAIL \ + --credential-source-url $URL_TO_GET_OIDC_TOKEN \ + --credential-source-headers $HEADER_KEY=$HEADER_VALUE \ + # Optional arguments for file types. Default is "text": + # --credential-source-type "json" \ + # Optional argument for the field that contains the OIDC credential. + # This is required for json. + # --credential-source-field-name "id_token" \ + --output-file /path/to/generated/config.json +``` + +Where the following variables need to be substituted: +- `$PROJECT_NUMBER`: The Google Cloud project number. +- `$POOL_ID`: The workload identity pool ID. +- `$OIDC_PROVIDER_ID`: The OIDC provider ID. +- `$SERVICE_ACCOUNT_EMAIL`: The email of the service account to impersonate. +- `$URL_TO_GET_OIDC_TOKEN`: The URL of the local server endpoint to call to retrieve the OIDC token. +- `$HEADER_KEY` and `$HEADER_VALUE`: The additional header key/value pairs to pass along the GET request to `$URL_TO_GET_OIDC_TOKEN`, e.g. `Metadata-Flavor=Google`. + +### Accessing resources from an OIDC or SAML2.0 identity provider using a custom supplier + +If you want to use OIDC or SAML2.0 that cannot be retrieved using methods supported natively by this library, +a custom SubjectTokenSupplier implementation may be specified when creating an identity pool client. The supplier must +return a valid, unexpired subject token when called by the GCP credential. + +Note that the client does not cache the returned subject token, so caching logic should be implemented in the supplier to prevent multiple requests for the same resources. + +```ts +class CustomSupplier implements SubjectTokenSupplier { + async getSubjectToken( + context: ExternalAccountSupplierContext + ): Promise { + const audience = context.audience; + const subjectTokenType = context.subjectTokenType; + // Return a valid subject token for the requested audience and subject token type. + } +} + +const clientOptions = { + audience: '//iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$WORKLOAD_POOL_ID/providers/$PROVIDER_ID', // Set the GCP audience. + subject_token_type: 'urn:ietf:params:oauth:token-type:id_token', // Set the subject token type. + subject_token_supplier: new CustomSupplier() // Set the custom supplier. +} + +const client = new CustomSupplier(clientOptions); +``` + +Where the [audience](https://cloud.google.com/iam/docs/best-practices-for-using-workload-identity-federation#provider-audience) is: `//iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$WORKLOAD_POOL_ID/providers/$PROVIDER_ID` + +Where the following variables need to be substituted: + +* `$PROJECT_NUMBER`: The Google Cloud project number. +* `$WORKLOAD_POOL_ID`: The workload pool ID. +* `$PROVIDER_ID`: The provider ID. + +The values for audience, service account impersonation URL, and any other builder field can also be found by generating a [credential configuration file with the gcloud CLI](https://cloud.google.com/sdk/gcloud/reference/iam/workload-identity-pools/create-cred-config). + +#### Using External Account Authorized User workforce credentials + +[External account authorized user credentials](https://cloud.google.com/iam/docs/workforce-obtaining-short-lived-credentials#browser-based-sign-in) allow you to sign in with a web browser to an external identity provider account via the +gcloud CLI and create a configuration for the auth library to use. + +To generate an external account authorized user workforce identity configuration, run the following command: + +```bash +gcloud auth application-default login --login-config=$LOGIN_CONFIG +``` + +Where the following variable needs to be substituted: +- `$LOGIN_CONFIG`: The login config file generated with the cloud console or + [gcloud iam workforce-pools create-login-config](https://cloud.google.com/sdk/gcloud/reference/iam/workforce-pools/create-login-config) + +This will open a browser flow for you to sign in via the configured third party identity provider +and then will store the external account authorized user configuration at the well known ADC location. +The auth library will then use the provided refresh token from the configuration to generate and refresh +an access token to call Google Cloud services. + +Note that the default lifetime of the refresh token is one hour, after which a new configuration will need to be generated from the gcloud CLI. +The lifetime can be modified by changing the [session duration of the workforce pool](https://cloud.google.com/iam/docs/reference/rest/v1/locations.workforcePools), and can be set as high as 12 hours. + +#### Using Executable-sourced credentials with OIDC and SAML + +**Executable-sourced credentials** +For executable-sourced credentials, a local executable is used to retrieve the 3rd party token. +The executable must handle providing a valid, unexpired OIDC ID token or SAML assertion in JSON format +to stdout. + +To use executable-sourced credentials, the `GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES` +environment variable must be set to `1`. + +To generate an executable-sourced workload identity configuration, run the following command: + +```bash +# Generate a configuration file for executable-sourced credentials. +gcloud iam workload-identity-pools create-cred-config \ + projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$PROVIDER_ID \ + --service-account=$SERVICE_ACCOUNT_EMAIL \ + --subject-token-type=$SUBJECT_TOKEN_TYPE \ + # The absolute path for the program, including arguments. + # e.g. --executable-command="/path/to/command --foo=bar" + --executable-command=$EXECUTABLE_COMMAND \ + # Optional argument for the executable timeout. Defaults to 30s. + # --executable-timeout-millis=$EXECUTABLE_TIMEOUT \ + # Optional argument for the absolute path to the executable output file. + # See below on how this argument impacts the library behaviour. + # --executable-output-file=$EXECUTABLE_OUTPUT_FILE \ + --output-file /path/to/generated/config.json +``` +Where the following variables need to be substituted: +- `$PROJECT_NUMBER`: The Google Cloud project number. +- `$POOL_ID`: The workload identity pool ID. +- `$PROVIDER_ID`: The OIDC or SAML provider ID. +- `$SERVICE_ACCOUNT_EMAIL`: The email of the service account to impersonate. +- `$SUBJECT_TOKEN_TYPE`: The subject token type. +- `$EXECUTABLE_COMMAND`: The full command to run, including arguments. Must be an absolute path to the program. + +The `--executable-timeout-millis` flag is optional. This is the duration for which +the auth library will wait for the executable to finish, in milliseconds. +Defaults to 30 seconds when not provided. The maximum allowed value is 2 minutes. +The minimum is 5 seconds. + +The `--executable-output-file` flag is optional. If provided, the file path must +point to the 3PI credential response generated by the executable. This is useful +for caching the credentials. By specifying this path, the Auth libraries will first +check for its existence before running the executable. By caching the executable JSON +response to this file, it improves performance as it avoids the need to run the executable +until the cached credentials in the output file are expired. The executable must +handle writing to this file - the auth libraries will only attempt to read from +this location. The format of contents in the file should match the JSON format +expected by the executable shown below. + +To retrieve the 3rd party token, the library will call the executable +using the command specified. The executable's output must adhere to the response format +specified below. It must output the response to stdout. + +A sample successful executable OIDC response: +```json +{ + "version": 1, + "success": true, + "token_type": "urn:ietf:params:oauth:token-type:id_token", + "id_token": "HEADER.PAYLOAD.SIGNATURE", + "expiration_time": 1620499962 +} +``` + +A sample successful executable SAML response: +```json +{ + "version": 1, + "success": true, + "token_type": "urn:ietf:params:oauth:token-type:saml2", + "saml_response": "...", + "expiration_time": 1620499962 +} +``` +For successful responses, the `expiration_time` field is only required +when an output file is specified in the credential configuration. + +A sample executable error response: +```json +{ + "version": 1, + "success": false, + "code": "401", + "message": "Caller not authorized." +} +``` +These are all required fields for an error response. The code and message +fields will be used by the library as part of the thrown exception. + +Response format fields summary: +* `version`: The version of the JSON output. Currently, only version 1 is supported. +* `success`: The status of the response. When true, the response must contain the 3rd party token + and token type. The response must also contain the expiration time if an output file was specified in the credential configuration. + The executable must also exit with exit code 0. + When false, the response must contain the error code and message fields and exit with a non-zero value. +* `token_type`: The 3rd party subject token type. Must be *urn:ietf:params:oauth:token-type:jwt*, +*urn:ietf:params:oauth:token-type:id_token*, or *urn:ietf:params:oauth:token-type:saml2*. +* `id_token`: The 3rd party OIDC token. +* `saml_response`: The 3rd party SAML response. +* `expiration_time`: The 3rd party subject token expiration time in seconds (unix epoch time). +* `code`: The error code string. +* `message`: The error message. + +All response types must include both the `version` and `success` fields. +* Successful responses must include the `token_type` and one of +`id_token` or `saml_response`. The `expiration_time` field must also be present if an output file was specified in +the credential configuration. +* Error responses must include both the `code` and `message` fields. + +The library will populate the following environment variables when the executable is run: +* `GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE`: The audience field from the credential configuration. Always present. +* `GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL`: The service account email. Only present when service account impersonation is used. +* `GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE`: The output file location from the credential configuration. Only present when specified in the credential configuration. +* `GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE`: This expected subject token type. Always present. + +These environment variables can be used by the executable to avoid hard-coding these values. + +##### Security considerations +The following security practices are highly recommended: +* Access to the script should be restricted as it will be displaying credentials to stdout. This ensures that rogue processes do not gain access to the script. +* The configuration file should not be modifiable. Write access should be restricted to avoid processes modifying the executable command portion. + +Given the complexity of using executable-sourced credentials, it is recommended to use +the existing supported mechanisms (file-sourced/URL-sourced) for providing 3rd party +credentials unless they do not meet your specific requirements. + +You can now [use the Auth library](#using-external-identities) to call Google Cloud +resources from an OIDC or SAML provider. + +#### Configurable Token Lifetime +When creating a credential configuration with workload identity federation using service account impersonation, you can provide an optional argument to configure the service account access token lifetime. + +To generate the configuration with configurable token lifetime, run the following command (this example uses an AWS configuration, but the token lifetime can be configured for all workload identity federation providers): + +```bash +# Generate an AWS configuration file with configurable token lifetime. +gcloud iam workload-identity-pools create-cred-config \ + projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AWS_PROVIDER_ID \ + --service-account $SERVICE_ACCOUNT_EMAIL \ + --aws \ + --output-file /path/to/generated/config.json \ + --service-account-token-lifetime-seconds $TOKEN_LIFETIME +``` + + Where the following variables need to be substituted: +- `$PROJECT_NUMBER`: The Google Cloud project number. +- `$POOL_ID`: The workload identity pool ID. +- `$AWS_PROVIDER_ID`: The AWS provider ID. +- `$SERVICE_ACCOUNT_EMAIL`: The email of the service account to impersonate. +- `$TOKEN_LIFETIME`: The desired lifetime duration of the service account access token in seconds. + +The `service-account-token-lifetime-seconds` flag is optional. If not provided, this defaults to one hour. +The minimum allowed value is 600 (10 minutes) and the maximum allowed value is 43200 (12 hours). +If a lifetime greater than one hour is required, the service account must be added as an allowed value in an Organization Policy that enforces the `constraints/iam.allowServiceAccountCredentialLifetimeExtension` constraint. + +Note that configuring a short lifetime (e.g. 10 minutes) will result in the library initiating the entire token exchange flow every 10 minutes, which will call the 3rd party token provider even if the 3rd party token is not expired. + +## Workforce Identity Federation + +[Workforce identity federation](https://cloud.google.com/iam/docs/workforce-identity-federation) lets you use an +external identity provider (IdP) to authenticate and authorize a workforce—a group of users, such as employees, +partners, and contractors—using IAM, so that the users can access Google Cloud services. Workforce identity federation +extends Google Cloud's identity capabilities to support syncless, attribute-based single sign on. + +With workforce identity federation, your workforce can access Google Cloud resources using an external +identity provider (IdP) that supports OpenID Connect (OIDC) or SAML 2.0 such as Azure Active Directory (Azure AD), +Active Directory Federation Services (AD FS), Okta, and others. + +### Accessing resources using an OIDC or SAML 2.0 identity provider + +In order to access Google Cloud resources from an identity provider that supports [OpenID Connect (OIDC)](https://openid.net/connect/), +the following requirements are needed: +- A workforce identity pool needs to be created. +- An OIDC or SAML 2.0 identity provider needs to be added in the workforce pool. + +Follow the detailed [instructions](https://cloud.google.com/iam/docs/configuring-workforce-identity-federation) on how +to configure workforce identity federation. + +After configuring an OIDC or SAML 2.0 provider, a credential configuration +file needs to be generated. The generated credential configuration file contains non-sensitive metadata to instruct the +library on how to retrieve external subject tokens and exchange them for GCP access tokens. +The configuration file can be generated by using the [gcloud CLI](https://cloud.google.com/sdk/). + +The Auth library can retrieve external subject tokens from a local file location +(file-sourced credentials), from a local server (URL-sourced credentials) or by calling an executable +(executable-sourced credentials). + +**File-sourced credentials** +For file-sourced credentials, a background process needs to be continuously refreshing the file +location with a new subject token prior to expiration. For tokens with one hour lifetimes, the token +needs to be updated in the file every hour. The token can be stored directly as plain text or in +JSON format. + +To generate a file-sourced OIDC configuration, run the following command: + +```bash +# Generate an OIDC configuration file for file-sourced credentials. +gcloud iam workforce-pools create-cred-config \ + locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ + --subject-token-type=urn:ietf:params:oauth:token-type:id_token \ + --credential-source-file=$PATH_TO_OIDC_ID_TOKEN \ + --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ + # Optional arguments for file types. Default is "text": + # --credential-source-type "json" \ + # Optional argument for the field that contains the OIDC credential. + # This is required for json. + # --credential-source-field-name "id_token" \ + --output-file=/path/to/generated/config.json +``` +Where the following variables need to be substituted: +- `$WORKFORCE_POOL_ID`: The workforce pool ID. +- `$PROVIDER_ID`: The provider ID. +- `$PATH_TO_OIDC_ID_TOKEN`: The file path used to retrieve the OIDC token. +- `$WORKFORCE_POOL_USER_PROJECT`: The project number associated with the [workforce pools user project](https://cloud.google.com/iam/docs/workforce-identity-federation#workforce-pools-user-project). + +To generate a file-sourced SAML configuration, run the following command: + +```bash +# Generate a SAML configuration file for file-sourced credentials. +gcloud iam workforce-pools create-cred-config \ + locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ + --credential-source-file=$PATH_TO_SAML_ASSERTION \ + --subject-token-type=urn:ietf:params:oauth:token-type:saml2 \ + --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ + --output-file=/path/to/generated/config.json +``` + +Where the following variables need to be substituted: +- `$WORKFORCE_POOL_ID`: The workforce pool ID. +- `$PROVIDER_ID`: The provider ID. +- `$PATH_TO_SAML_ASSERTION`: The file path used to retrieve the base64-encoded SAML assertion. +- `$WORKFORCE_POOL_USER_PROJECT`: The project number associated with the [workforce pools user project](https://cloud.google.com/iam/docs/workforce-identity-federation#workforce-pools-user-project). + +These commands generate the configuration file in the specified output file. + +**URL-sourced credentials** +For URL-sourced credentials, a local server needs to host a GET endpoint to return the OIDC token. +The response can be in plain text or JSON. Additional required request headers can also be +specified. + +To generate a URL-sourced OIDC workforce identity configuration, run the following command: + +```bash +# Generate an OIDC configuration file for URL-sourced credentials. +gcloud iam workforce-pools create-cred-config \ + locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ + --subject-token-type=urn:ietf:params:oauth:token-type:id_token \ + --credential-source-url=$URL_TO_RETURN_OIDC_ID_TOKEN \ + --credential-source-headers $HEADER_KEY=$HEADER_VALUE \ + --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ + --output-file=/path/to/generated/config.json +``` + +Where the following variables need to be substituted: +- `$WORKFORCE_POOL_ID`: The workforce pool ID. +- `$PROVIDER_ID`: The provider ID. +- `$URL_TO_RETURN_OIDC_ID_TOKEN`: The URL of the local server endpoint. +- `$HEADER_KEY` and `$HEADER_VALUE`: The additional header key/value pairs to pass along the GET request to + `$URL_TO_GET_OIDC_TOKEN`, e.g. `Metadata-Flavor=Google`. +- `$WORKFORCE_POOL_USER_PROJECT`: The project number associated with the [workforce pools user project](https://cloud.google.com/iam/docs/workforce-identity-federation#workforce-pools-user-project). + +To generate a URL-sourced SAML configuration, run the following command: + +```bash +# Generate a SAML configuration file for file-sourced credentials. +gcloud iam workforce-pools create-cred-config \ + locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ + --subject-token-type=urn:ietf:params:oauth:token-type:saml2 \ + --credential-source-url=$URL_TO_GET_SAML_ASSERTION \ + --credential-source-headers $HEADER_KEY=$HEADER_VALUE \ + --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ + --output-file=/path/to/generated/config.json +``` + +These commands generate the configuration file in the specified output file. + +Where the following variables need to be substituted: +- `$WORKFORCE_POOL_ID`: The workforce pool ID. +- `$PROVIDER_ID`: The provider ID. +- `$URL_TO_GET_SAML_ASSERTION`: The URL of the local server endpoint. +- `$HEADER_KEY` and `$HEADER_VALUE`: The additional header key/value pairs to pass along the GET request to + `$URL_TO_GET_SAML_ASSERTION`, e.g. `Metadata-Flavor=Google`. +- `$WORKFORCE_POOL_USER_PROJECT`: The project number associated with the [workforce pools user project](https://cloud.google.com/iam/docs/workforce-identity-federation#workforce-pools-user-project). + +### Using Executable-sourced workforce credentials with OIDC and SAML + +**Executable-sourced credentials** +For executable-sourced credentials, a local executable is used to retrieve the 3rd party token. +The executable must handle providing a valid, unexpired OIDC ID token or SAML assertion in JSON format +to stdout. + +To use executable-sourced credentials, the `GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES` +environment variable must be set to `1`. + +To generate an executable-sourced workforce identity configuration, run the following command: + +```bash +# Generate a configuration file for executable-sourced credentials. +gcloud iam workforce-pools create-cred-config \ + locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ + --subject-token-type=$SUBJECT_TOKEN_TYPE \ + # The absolute path for the program, including arguments. + # e.g. --executable-command="/path/to/command --foo=bar" + --executable-command=$EXECUTABLE_COMMAND \ + # Optional argument for the executable timeout. Defaults to 30s. + # --executable-timeout-millis=$EXECUTABLE_TIMEOUT \ + # Optional argument for the absolute path to the executable output file. + # See below on how this argument impacts the library behaviour. + # --executable-output-file=$EXECUTABLE_OUTPUT_FILE \ + --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ + --output-file /path/to/generated/config.json +``` +Where the following variables need to be substituted: +- `$WORKFORCE_POOL_ID`: The workforce pool ID. +- `$PROVIDER_ID`: The provider ID. +- `$SUBJECT_TOKEN_TYPE`: The subject token type. +- `$EXECUTABLE_COMMAND`: The full command to run, including arguments. Must be an absolute path to the program. +- `$WORKFORCE_POOL_USER_PROJECT`: The project number associated with the [workforce pools user project](https://cloud.google.com/iam/docs/workforce-identity-federation#workforce-pools-user-project). + +The `--executable-timeout-millis` flag is optional. This is the duration for which +the auth library will wait for the executable to finish, in milliseconds. +Defaults to 30 seconds when not provided. The maximum allowed value is 2 minutes. +The minimum is 5 seconds. + +The `--executable-output-file` flag is optional. If provided, the file path must +point to the 3rd party credential response generated by the executable. This is useful +for caching the credentials. By specifying this path, the Auth libraries will first +check for its existence before running the executable. By caching the executable JSON +response to this file, it improves performance as it avoids the need to run the executable +until the cached credentials in the output file are expired. The executable must +handle writing to this file - the auth libraries will only attempt to read from +this location. The format of contents in the file should match the JSON format +expected by the executable shown below. + +To retrieve the 3rd party token, the library will call the executable +using the command specified. The executable's output must adhere to the response format +specified below. It must output the response to stdout. + +Refer to the [using executable-sourced credentials with Workload Identity Federation](#using-executable-sourced-credentials-with-oidc-and-saml) +above for the executable response specification. + +##### Security considerations +The following security practices are highly recommended: +* Access to the script should be restricted as it will be displaying credentials to stdout. This ensures that rogue processes do not gain access to the script. +* The configuration file should not be modifiable. Write access should be restricted to avoid processes modifying the executable command portion. + +Given the complexity of using executable-sourced credentials, it is recommended to use +the existing supported mechanisms (file-sourced/URL-sourced) for providing 3rd party +credentials unless they do not meet your specific requirements. + +You can now [use the Auth library](#using-external-identities) to call Google Cloud +resources from an OIDC or SAML provider. + +### Accessing resources from an OIDC or SAML2.0 identity provider using a custom supplier + +If you want to use OIDC or SAML2.0 that cannot be retrieved using methods supported natively by this library, +a custom SubjectTokenSupplier implementation may be specified when creating an identity pool client. The supplier must +return a valid, unexpired subject token when called by the GCP credential. + +Note that the client does not cache the returned subject token, so caching logic should be implemented in the supplier to prevent multiple requests for the same resources. + +```ts +class CustomSupplier implements SubjectTokenSupplier { + async getSubjectToken( + context: ExternalAccountSupplierContext + ): Promise { + const audience = context.audience; + const subjectTokenType = context.subjectTokenType; + // Return a valid subject token for the requested audience and subject token type. + } +} + +const clientOptions = { + audience: '//iam.googleapis.com/locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID', // Set the GCP audience. + subject_token_type: 'urn:ietf:params:oauth:token-type:id_token', // Set the subject token type. + subject_token_supplier: new CustomSupplier() // Set the custom supplier. +} + +const client = new CustomSupplier(clientOptions); +``` + +Where the audience is: `//iam.googleapis.com/locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID` + +Where the following variables need to be substituted: + +* `$WORKFORCE_POOL_ID`: The worforce pool ID. +* `$PROVIDER_ID`: The provider ID. + +and the workforce pool user project is the project number associated with the [workforce pools user project](https://cloud.google.com/iam/docs/workforce-identity-federation#workforce-pools-user-project). + +The values for audience, service account impersonation URL, and any other builder field can also be found by generating a [credential configuration file with the gcloud CLI](https://cloud.google.com/iam/docs/workforce-obtaining-short-lived-credentials#use_configuration_files_for_sign-in). + +### Using External Identities + +External identities (AWS, Azure and OIDC-based providers) can be used with `Application Default Credentials`. +In order to use external identities with Application Default Credentials, you need to generate the JSON credentials configuration file for your external identity as described above. +Once generated, store the path to this file in the `GOOGLE_APPLICATION_CREDENTIALS` environment variable. + +```bash +export GOOGLE_APPLICATION_CREDENTIALS=/path/to/config.json +``` + +The library can now automatically choose the right type of client and initialize credentials from the context provided in the configuration file. + +```js +async function main() { + const auth = new GoogleAuth({ + scopes: 'https://www.googleapis.com/auth/cloud-platform' + }); + const client = await auth.getClient(); + const projectId = await auth.getProjectId(); + // List all buckets in a project. + const url = `https://storage.googleapis.com/storage/v1/b?project=${projectId}`; + const res = await client.request({ url }); + console.log(res.data); +} +``` + +When using external identities with Application Default Credentials in Node.js, the `roles/browser` role needs to be granted to the service account. +The `Cloud Resource Manager API` should also be enabled on the project. +This is needed since the library will try to auto-discover the project ID from the current environment using the impersonated credential. +To avoid this requirement, the project ID can be explicitly specified on initialization. + +```js +const auth = new GoogleAuth({ + scopes: 'https://www.googleapis.com/auth/cloud-platform', + // Pass the project ID explicitly to avoid the need to grant `roles/browser` to the service account + // or enable Cloud Resource Manager API on the project. + projectId: 'CLOUD_RESOURCE_PROJECT_ID', +}); +``` + +You can also explicitly initialize external account clients using the generated configuration file. + +```js +const {ExternalAccountClient} = require('google-auth-library'); +const jsonConfig = require('/path/to/config.json'); + +async function main() { + const client = ExternalAccountClient.fromJSON(jsonConfig); + client.scopes = ['https://www.googleapis.com/auth/cloud-platform']; + // List all buckets in a project. + const url = `https://storage.googleapis.com/storage/v1/b?project=${projectId}`; + const res = await client.request({url}); + console.log(res.data); +} +``` + +#### Security Considerations +Note that this library does not perform any validation on the token_url, token_info_url, or service_account_impersonation_url fields of the credential configuration. It is not recommended to use a credential configuration that you did not generate with the gcloud CLI unless you verify that the URL fields point to a googleapis.com domain. + +## Working with ID Tokens +### Fetching ID Tokens +If your application is running on Cloud Run or Cloud Functions, or using Cloud Identity-Aware +Proxy (IAP), you will need to fetch an ID token to access your application. For +this, use the method `getIdTokenClient` on the `GoogleAuth` client. + +For invoking Cloud Run services, your service account will need the +[`Cloud Run Invoker`](https://cloud.google.com/run/docs/authenticating/service-to-service) +IAM permission. + +For invoking Cloud Functions, your service account will need the +[`Function Invoker`](https://cloud.google.com/functions/docs/securing/authenticating#function-to-function) +IAM permission. + +``` js +// Make a request to a protected Cloud Run service. +const {GoogleAuth} = require('google-auth-library'); + +async function main() { + const url = 'https://cloud-run-1234-uc.a.run.app'; + const auth = new GoogleAuth(); + const client = await auth.getIdTokenClient(url); + const res = await client.request({url}); + console.log(res.data); +} + +main().catch(console.error); +``` + +A complete example can be found in [`samples/idtokens-serverless.js`](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idtokens-serverless.js). + +For invoking Cloud Identity-Aware Proxy, you will need to pass the Client ID +used when you set up your protected resource as the target audience. + +``` js +// Make a request to a protected Cloud Identity-Aware Proxy (IAP) resource +const {GoogleAuth} = require('google-auth-library'); + +async function main() + const targetAudience = 'iap-client-id'; + const url = 'https://iap-url.com'; + const auth = new GoogleAuth(); + const client = await auth.getIdTokenClient(targetAudience); + const res = await client.request({url}); + console.log(res.data); +} + +main().catch(console.error); +``` + +A complete example can be found in [`samples/idtokens-iap.js`](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idtokens-iap.js). + +### Verifying ID Tokens + +If you've [secured your IAP app with signed headers](https://cloud.google.com/iap/docs/signed-headers-howto), +you can use this library to verify the IAP header: + +```js +const {OAuth2Client} = require('google-auth-library'); +// Expected audience for App Engine. +const expectedAudience = `/projects/your-project-number/apps/your-project-id`; +// IAP issuer +const issuers = ['https://cloud.google.com/iap']; +// Verify the token. OAuth2Client throws an Error if verification fails +const oAuth2Client = new OAuth2Client(); +const response = await oAuth2Client.getIapCerts(); +const ticket = await oAuth2Client.verifySignedJwtWithCertsAsync( + idToken, + response.pubkeys, + expectedAudience, + issuers +); + +// Print out the info contained in the IAP ID token +console.log(ticket) +``` + +A complete example can be found in [`samples/verifyIdToken-iap.js`](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/verifyIdToken-iap.js). + +## Impersonated Credentials Client + +Google Cloud Impersonated credentials used for [Creating short-lived service account credentials](https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials). + +Provides authentication for applications where local credentials impersonates a remote service account using [IAM Credentials API](https://cloud.google.com/iam/docs/reference/credentials/rest). + +An Impersonated Credentials Client is instantiated with a `sourceClient`. This +client should use credentials that have the "Service Account Token Creator" role (`roles/iam.serviceAccountTokenCreator`), +and should authenticate with the `https://www.googleapis.com/auth/cloud-platform`, or `https://www.googleapis.com/auth/iam` scopes. + +`sourceClient` is used by the Impersonated +Credentials Client to impersonate a target service account with a specified +set of scopes. + +### Sample Usage + +```javascript +const { GoogleAuth, Impersonated } = require('google-auth-library'); +const { SecretManagerServiceClient } = require('@google-cloud/secret-manager'); + +async function main() { + + // Acquire source credentials: + const auth = new GoogleAuth(); + const client = await auth.getClient(); + + // Impersonate new credentials: + let targetClient = new Impersonated({ + sourceClient: client, + targetPrincipal: 'impersonated-account@projectID.iam.gserviceaccount.com', + lifetime: 30, + delegates: [], + targetScopes: ['https://www.googleapis.com/auth/cloud-platform'] + }); + + // Get impersonated credentials: + const authHeaders = await targetClient.getRequestHeaders(); + // Do something with `authHeaders.Authorization`. + + // Use impersonated credentials: + const url = 'https://www.googleapis.com/storage/v1/b?project=anotherProjectID' + const resp = await targetClient.request({ url }); + for (const bucket of resp.data.items) { + console.log(bucket.name); + } + + // Use impersonated credentials with google-cloud client library + // Note: this works only with certain cloud client libraries utilizing gRPC + // e.g., SecretManager, KMS, AIPlatform + // will not currently work with libraries using REST, e.g., Storage, Compute + const smClient = new SecretManagerServiceClient({ + projectId: anotherProjectID, + auth: { + getClient: () => targetClient, + }, + }); + const secretName = 'projects/anotherProjectNumber/secrets/someProjectName/versions/1'; + const [accessResponse] = await smClient.accessSecretVersion({ + name: secretName, + }); + + const responsePayload = accessResponse.payload.data.toString('utf8'); + // Do something with the secret contained in `responsePayload`. +}; + +main(); +``` + +## Downscoped Client + +[Downscoping with Credential Access Boundaries](https://cloud.google.com/iam/docs/downscoping-short-lived-credentials) is used to restrict the Identity and Access Management (IAM) permissions that a short-lived credential can use. + +The `DownscopedClient` class can be used to produce a downscoped access token from a +`CredentialAccessBoundary` and a source credential. The Credential Access Boundary specifies which resources the newly created credential can access, as well as an upper bound on the permissions that are available on each resource. Using downscoped credentials ensures tokens in flight always have the least privileges, e.g. Principle of Least Privilege. + +> Notice: Only Cloud Storage supports Credential Access Boundaries for now. + +### Sample Usage +There are two entities needed to generate and use credentials generated from +Downscoped Client with Credential Access Boundaries. + +- Token broker: This is the entity with elevated permissions. This entity has the permissions needed to generate downscoped tokens. The common pattern of usage is to have a token broker with elevated access generate these downscoped credentials from higher access source credentials and pass the downscoped short-lived access tokens to a token consumer via some secure authenticated channel for limited access to Google Cloud Storage resources. + +``` js +const {GoogleAuth, DownscopedClient} = require('google-auth-library'); +// Define CAB rules which will restrict the downscoped token to have readonly +// access to objects starting with "customer-a" in bucket "bucket_name". +const cabRules = { + accessBoundary: { + accessBoundaryRules: [ + { + availableResource: `//storage.googleapis.com/projects/_/buckets/bucket_name`, + availablePermissions: ['inRole:roles/storage.objectViewer'], + availabilityCondition: { + expression: + `resource.name.startsWith('projects/_/buckets/` + + `bucket_name/objects/customer-a)` + } + }, + ], + }, +}; + +// This will use ADC to get the credentials used for the downscoped client. +const googleAuth = new GoogleAuth({ + scopes: ['https://www.googleapis.com/auth/cloud-platform'] +}); + +// Obtain an authenticated client via ADC. +const client = await googleAuth.getClient(); + +// Use the client to create a DownscopedClient. +const cabClient = new DownscopedClient(client, cab); + +// Refresh the tokens. +const refreshedAccessToken = await cabClient.getAccessToken(); + +// This will need to be passed to the token consumer. +access_token = refreshedAccessToken.token; +expiry_date = refreshedAccessToken.expirationTime; +``` + +A token broker can be set up on a server in a private network. Various workloads +(token consumers) in the same network will send authenticated requests to that broker for downscoped tokens to access or modify specific google cloud storage buckets. + +The broker will instantiate downscoped credentials instances that can be used to generate short lived downscoped access tokens which will be passed to the token consumer. + +- Token consumer: This is the consumer of the downscoped tokens. This entity does not have the direct ability to generate access tokens and instead relies on the token broker to provide it with downscoped tokens to run operations on GCS buckets. It is assumed that the downscoped token consumer may have its own mechanism to authenticate itself with the token broker. + +``` js +const {OAuth2Client} = require('google-auth-library'); +const {Storage} = require('@google-cloud/storage'); + +// Create the OAuth credentials (the consumer). +const oauth2Client = new OAuth2Client(); +// We are defining a refresh handler instead of a one-time access +// token/expiry pair. +// This will allow the consumer to obtain new downscoped tokens on +// demand every time a token is expired, without any additional code +// changes. +oauth2Client.refreshHandler = async () => { + // The common pattern of usage is to have a token broker pass the + // downscoped short-lived access tokens to a token consumer via some + // secure authenticated channel. + const refreshedAccessToken = await cabClient.getAccessToken(); + return { + access_token: refreshedAccessToken.token, + expiry_date: refreshedAccessToken.expirationTime, + } +}; + +// Use the consumer client to define storageOptions and create a GCS object. +const storageOptions = { + projectId: 'my_project_id', + authClient: oauth2Client, +}; + +const storage = new Storage(storageOptions); + +const downloadFile = await storage + .bucket('bucket_name') + .file('customer-a-data.txt') + .download(); +console.log(downloadFile.toString('utf8')); + +main().catch(console.error); +``` + + +## Samples + +Samples are in the [`samples/`](https://github.com/googleapis/google-auth-library-nodejs/tree/main/samples) directory. Each sample's `README.md` has instructions for running its sample. + +| Sample | Source Code | Try it | +| --------------------------- | --------------------------------- | ------ | +| Adc | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/adc.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/adc.js,samples/README.md) | +| Authenticate API Key | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/authenticateAPIKey.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/authenticateAPIKey.js,samples/README.md) | +| Authenticate Explicit | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/authenticateExplicit.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/authenticateExplicit.js,samples/README.md) | +| Authenticate Implicit With Adc | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/authenticateImplicitWithAdc.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/authenticateImplicitWithAdc.js,samples/README.md) | +| Compute | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/compute.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/compute.js,samples/README.md) | +| Credentials | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/credentials.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/credentials.js,samples/README.md) | +| Downscopedclient | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/downscopedclient.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/downscopedclient.js,samples/README.md) | +| Headers | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/headers.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/headers.js,samples/README.md) | +| Id Token From Impersonated Credentials | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idTokenFromImpersonatedCredentials.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/idTokenFromImpersonatedCredentials.js,samples/README.md) | +| Id Token From Metadata Server | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idTokenFromMetadataServer.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/idTokenFromMetadataServer.js,samples/README.md) | +| Id Token From Service Account | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idTokenFromServiceAccount.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/idTokenFromServiceAccount.js,samples/README.md) | +| ID Tokens for Identity-Aware Proxy (IAP) | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idtokens-iap.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/idtokens-iap.js,samples/README.md) | +| ID Tokens for Serverless | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idtokens-serverless.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/idtokens-serverless.js,samples/README.md) | +| Jwt | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/jwt.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/jwt.js,samples/README.md) | +| Keepalive | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/keepalive.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/keepalive.js,samples/README.md) | +| Keyfile | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/keyfile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/keyfile.js,samples/README.md) | +| Oauth2-code Verifier | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/oauth2-codeVerifier.js,samples/README.md) | +| Oauth2 | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/oauth2.js,samples/README.md) | +| Sign Blob | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/signBlob.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/signBlob.js,samples/README.md) | +| Sign Blob Impersonated | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/signBlobImpersonated.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/signBlobImpersonated.js,samples/README.md) | +| Verify Google Id Token | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/verifyGoogleIdToken.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/verifyGoogleIdToken.js,samples/README.md) | +| Verifying ID Tokens from Identity-Aware Proxy (IAP) | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/verifyIdToken-iap.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/verifyIdToken-iap.js,samples/README.md) | +| Verify Id Token | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/verifyIdToken.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/verifyIdToken.js,samples/README.md) | + + + +The [Google Auth Library Node.js Client API Reference][client-docs] documentation +also contains samples. + +## Supported Node.js Versions + +Our client libraries follow the [Node.js release schedule](https://github.com/nodejs/release#release-schedule). +Libraries are compatible with all current _active_ and _maintenance_ versions of +Node.js. +If you are using an end-of-life version of Node.js, we recommend that you update +as soon as possible to an actively supported LTS version. + +Google's client libraries support legacy versions of Node.js runtimes on a +best-efforts basis with the following warnings: + +* Legacy versions are not tested in continuous integration. +* Some security patches and features cannot be backported. +* Dependencies cannot be kept up-to-date. + +Client libraries targeting some end-of-life versions of Node.js are available, and +can be installed through npm [dist-tags](https://docs.npmjs.com/cli/dist-tag). +The dist-tags follow the naming convention `legacy-(version)`. +For example, `npm install google-auth-library@legacy-8` installs client libraries +for versions compatible with Node.js 8. + +## Versioning + +This library follows [Semantic Versioning](http://semver.org/). + + + +This library is considered to be **stable**. The code surface will not change in backwards-incompatible ways +unless absolutely necessary (e.g. because of critical security issues) or with +an extensive deprecation period. Issues and requests against **stable** libraries +are addressed with the highest priority. + + + + + + +More Information: [Google Cloud Platform Launch Stages][launch_stages] + +[launch_stages]: https://cloud.google.com/terms/launch-stages + +## Contributing + +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-auth-library-nodejs/blob/main/CONTRIBUTING.md). + +Please note that this `README.md`, the `samples/README.md`, +and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) +are generated from a central template. To edit one of these files, make an edit +to its templates in +[directory](https://github.com/googleapis/synthtool). + +## License + +Apache Version 2.0 + +See [LICENSE](https://github.com/googleapis/google-auth-library-nodejs/blob/main/LICENSE) + +[client-docs]: https://cloud.google.com/nodejs/docs/reference/google-auth-library/latest +[product-docs]: https://cloud.google.com/docs/authentication/ +[shell_img]: https://gstatic.com/cloudssh/images/open-btn.png +[projects]: https://console.cloud.google.com/project +[billing]: https://support.google.com/cloud/answer/6293499#enable-billing + +[auth]: https://cloud.google.com/docs/authentication/external/set-up-adc-local diff --git a/node_modules/google-auth-library/build/src/auth/authclient.d.ts b/node_modules/google-auth-library/build/src/auth/authclient.d.ts new file mode 100644 index 0000000..22b020c --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/authclient.d.ts @@ -0,0 +1,202 @@ +import { EventEmitter } from 'events'; +import { Gaxios, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +import { Transporter } from '../transporters'; +import { Credentials } from './credentials'; +import { GetAccessTokenResponse, Headers } from './oauth2client'; +import { OriginalAndCamel } from '../util'; +/** + * Base auth configurations (e.g. from JWT or `.json` files) with conventional + * camelCased options. + * + * @privateRemarks + * + * This interface is purposely not exported so that it can be removed once + * {@link https://github.com/microsoft/TypeScript/issues/50715} has been + * resolved. Then, we can use {@link OriginalAndCamel} to shrink this interface. + * + * Tracking: {@link https://github.com/googleapis/google-auth-library-nodejs/issues/1686} + */ +interface AuthJSONOptions { + /** + * The project ID corresponding to the current credentials if available. + */ + project_id: string | null; + /** + * An alias for {@link AuthJSONOptions.project_id `project_id`}. + */ + projectId: AuthJSONOptions['project_id']; + /** + * The quota project ID. The quota project can be used by client libraries for the billing purpose. + * See {@link https://cloud.google.com/docs/quota Working with quotas} + */ + quota_project_id: string; + /** + * An alias for {@link AuthJSONOptions.quota_project_id `quota_project_id`}. + */ + quotaProjectId: AuthJSONOptions['quota_project_id']; + /** + * The default service domain for a given Cloud universe. + * + * @example + * 'googleapis.com' + */ + universe_domain: string; + /** + * An alias for {@link AuthJSONOptions.universe_domain `universe_domain`}. + */ + universeDomain: AuthJSONOptions['universe_domain']; +} +/** + * Base `AuthClient` configuration. + * + * The camelCased options are aliases of the snake_cased options, supporting both + * JSON API and JS conventions. + */ +export interface AuthClientOptions extends Partial> { + /** + * An API key to use, optional. + */ + apiKey?: string; + credentials?: Credentials; + /** + * A `Gaxios` or `Transporter` instance to use for `AuthClient` requests. + */ + transporter?: Gaxios | Transporter; + /** + * Provides default options to the transporter, such as {@link GaxiosOptions.agent `agent`} or + * {@link GaxiosOptions.retryConfig `retryConfig`}. + */ + transporterOptions?: GaxiosOptions; + /** + * The expiration threshold in milliseconds before forcing token refresh of + * unexpired tokens. + */ + eagerRefreshThresholdMillis?: number; + /** + * Whether to attempt to refresh tokens on status 401/403 responses + * even if an attempt is made to refresh the token preemptively based + * on the expiry_date. + */ + forceRefreshOnFailure?: boolean; +} +/** + * The default cloud universe + * + * @see {@link AuthJSONOptions.universe_domain} + */ +export declare const DEFAULT_UNIVERSE = "googleapis.com"; +/** + * The default {@link AuthClientOptions.eagerRefreshThresholdMillis} + */ +export declare const DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS: number; +/** + * Defines the root interface for all clients that generate credentials + * for calling Google APIs. All clients should implement this interface. + */ +export interface CredentialsClient { + projectId?: AuthClientOptions['projectId']; + eagerRefreshThresholdMillis: NonNullable; + forceRefreshOnFailure: NonNullable; + /** + * @return A promise that resolves with the current GCP access token + * response. If the current credential is expired, a new one is retrieved. + */ + getAccessToken(): Promise; + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * The result has the form: + * { Authorization: 'Bearer ' } + * @param url The URI being authorized. + */ + getRequestHeaders(url?: string): Promise; + /** + * Provides an alternative Gaxios request implementation with auth credentials + */ + request(opts: GaxiosOptions): GaxiosPromise; + /** + * Sets the auth credentials. + */ + setCredentials(credentials: Credentials): void; + /** + * Subscribes a listener to the tokens event triggered when a token is + * generated. + * + * @param event The tokens event to subscribe to. + * @param listener The listener that triggers on event trigger. + * @return The current client instance. + */ + on(event: 'tokens', listener: (tokens: Credentials) => void): this; +} +export declare interface AuthClient { + on(event: 'tokens', listener: (tokens: Credentials) => void): this; +} +export declare abstract class AuthClient extends EventEmitter implements CredentialsClient { + apiKey?: string; + projectId?: string | null; + /** + * The quota project ID. The quota project can be used by client libraries for the billing purpose. + * See {@link https://cloud.google.com/docs/quota Working with quotas} + */ + quotaProjectId?: string; + transporter: Transporter; + credentials: Credentials; + eagerRefreshThresholdMillis: number; + forceRefreshOnFailure: boolean; + universeDomain: string; + constructor(opts?: AuthClientOptions); + /** + * Return the {@link Gaxios `Gaxios`} instance from the {@link AuthClient.transporter}. + * + * @expiremental + */ + get gaxios(): Gaxios | null; + /** + * Provides an alternative Gaxios request implementation with auth credentials + */ + abstract request(opts: GaxiosOptions): GaxiosPromise; + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * The result has the form: + * { Authorization: 'Bearer ' } + * @param url The URI being authorized. + */ + abstract getRequestHeaders(url?: string): Promise; + /** + * @return A promise that resolves with the current GCP access token + * response. If the current credential is expired, a new one is retrieved. + */ + abstract getAccessToken(): Promise<{ + token?: string | null; + res?: GaxiosResponse | null; + }>; + /** + * Sets the auth credentials. + */ + setCredentials(credentials: Credentials): void; + /** + * Append additional headers, e.g., x-goog-user-project, shared across the + * classes inheriting AuthClient. This method should be used by any method + * that overrides getRequestMetadataAsync(), which is a shared helper for + * setting request information in both gRPC and HTTP API calls. + * + * @param headers object to append additional headers to. + */ + protected addSharedMetadataHeaders(headers: Headers): Headers; + /** + * Retry config for Auth-related requests. + * + * @remarks + * + * This is not a part of the default {@link AuthClient.transporter transporter/gaxios} + * config as some downstream APIs would prefer if customers explicitly enable retries, + * such as GCS. + */ + protected static get RETRY_CONFIG(): GaxiosOptions; +} +export {}; diff --git a/node_modules/google-auth-library/build/src/auth/authclient.js b/node_modules/google-auth-library/build/src/auth/authclient.js new file mode 100644 index 0000000..f80ca58 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/authclient.js @@ -0,0 +1,116 @@ +"use strict"; +// Copyright 2012 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AuthClient = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = exports.DEFAULT_UNIVERSE = void 0; +const events_1 = require("events"); +const gaxios_1 = require("gaxios"); +const transporters_1 = require("../transporters"); +const util_1 = require("../util"); +/** + * The default cloud universe + * + * @see {@link AuthJSONOptions.universe_domain} + */ +exports.DEFAULT_UNIVERSE = 'googleapis.com'; +/** + * The default {@link AuthClientOptions.eagerRefreshThresholdMillis} + */ +exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = 5 * 60 * 1000; +class AuthClient extends events_1.EventEmitter { + constructor(opts = {}) { + var _a, _b, _c, _d, _e; + super(); + this.credentials = {}; + this.eagerRefreshThresholdMillis = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS; + this.forceRefreshOnFailure = false; + this.universeDomain = exports.DEFAULT_UNIVERSE; + const options = (0, util_1.originalOrCamelOptions)(opts); + // Shared auth options + this.apiKey = opts.apiKey; + this.projectId = (_a = options.get('project_id')) !== null && _a !== void 0 ? _a : null; + this.quotaProjectId = options.get('quota_project_id'); + this.credentials = (_b = options.get('credentials')) !== null && _b !== void 0 ? _b : {}; + this.universeDomain = (_c = options.get('universe_domain')) !== null && _c !== void 0 ? _c : exports.DEFAULT_UNIVERSE; + // Shared client options + this.transporter = (_d = opts.transporter) !== null && _d !== void 0 ? _d : new transporters_1.DefaultTransporter(); + if (opts.transporterOptions) { + this.transporter.defaults = opts.transporterOptions; + } + if (opts.eagerRefreshThresholdMillis) { + this.eagerRefreshThresholdMillis = opts.eagerRefreshThresholdMillis; + } + this.forceRefreshOnFailure = (_e = opts.forceRefreshOnFailure) !== null && _e !== void 0 ? _e : false; + } + /** + * Return the {@link Gaxios `Gaxios`} instance from the {@link AuthClient.transporter}. + * + * @expiremental + */ + get gaxios() { + if (this.transporter instanceof gaxios_1.Gaxios) { + return this.transporter; + } + else if (this.transporter instanceof transporters_1.DefaultTransporter) { + return this.transporter.instance; + } + else if ('instance' in this.transporter && + this.transporter.instance instanceof gaxios_1.Gaxios) { + return this.transporter.instance; + } + return null; + } + /** + * Sets the auth credentials. + */ + setCredentials(credentials) { + this.credentials = credentials; + } + /** + * Append additional headers, e.g., x-goog-user-project, shared across the + * classes inheriting AuthClient. This method should be used by any method + * that overrides getRequestMetadataAsync(), which is a shared helper for + * setting request information in both gRPC and HTTP API calls. + * + * @param headers object to append additional headers to. + */ + addSharedMetadataHeaders(headers) { + // quota_project_id, stored in application_default_credentials.json, is set in + // the x-goog-user-project header, to indicate an alternate account for + // billing and quota: + if (!headers['x-goog-user-project'] && // don't override a value the user sets. + this.quotaProjectId) { + headers['x-goog-user-project'] = this.quotaProjectId; + } + return headers; + } + /** + * Retry config for Auth-related requests. + * + * @remarks + * + * This is not a part of the default {@link AuthClient.transporter transporter/gaxios} + * config as some downstream APIs would prefer if customers explicitly enable retries, + * such as GCS. + */ + static get RETRY_CONFIG() { + return { + retry: true, + retryConfig: { + httpMethodsToRetry: ['GET', 'PUT', 'POST', 'HEAD', 'OPTIONS', 'DELETE'], + }, + }; + } +} +exports.AuthClient = AuthClient; diff --git a/node_modules/google-auth-library/build/src/auth/awsclient.d.ts b/node_modules/google-auth-library/build/src/auth/awsclient.d.ts new file mode 100644 index 0000000..a3bc138 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/awsclient.d.ts @@ -0,0 +1,120 @@ +import { AwsSecurityCredentials } from './awsrequestsigner'; +import { BaseExternalAccountClient, BaseExternalAccountClientOptions, ExternalAccountSupplierContext } from './baseexternalclient'; +import { AuthClientOptions } from './authclient'; +import { SnakeToCamelObject } from '../util'; +/** + * AWS credentials JSON interface. This is used for AWS workloads. + */ +export interface AwsClientOptions extends BaseExternalAccountClientOptions { + /** + * Object containing options to retrieve AWS security credentials. A valid credential + * source or a aws security credentials supplier should be specified. + */ + credential_source?: { + /** + * AWS environment ID. Currently only 'AWS1' is supported. + */ + environment_id: string; + /** + * The EC2 metadata URL to retrieve the current AWS region from. If this is + * not provided, the region should be present in the AWS_REGION or AWS_DEFAULT_REGION + * environment variables. + */ + region_url?: string; + /** + * The EC2 metadata URL to retrieve AWS security credentials. If this is not provided, + * the credentials should be present in the AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, + * and AWS_SESSION_TOKEN environment variables. + */ + url?: string; + /** + * The regional GetCallerIdentity action URL, used to determine the account + * ID and its roles. + */ + regional_cred_verification_url: string; + /** + * The imdsv2 session token url is used to fetch session token from AWS + * which is later sent through headers for metadata requests. If the + * field is missing, then session token won't be fetched and sent with + * the metadata requests. + * The session token is required for IMDSv2 but optional for IMDSv1 + */ + imdsv2_session_token_url?: string; + }; + /** + * The AWS security credentials supplier to call to retrieve the AWS region + * and AWS security credentials. Either this or a valid credential source + * must be specified. + */ + aws_security_credentials_supplier?: AwsSecurityCredentialsSupplier; +} +/** + * Supplier interface for AWS security credentials. This can be implemented to + * return an AWS region and AWS security credentials. These credentials can + * then be exchanged for a GCP token by an {@link AwsClient}. + */ +export interface AwsSecurityCredentialsSupplier { + /** + * Gets the active AWS region. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link AwsClient}, contains the requested audience and subject token type + * for the external account identity as well as the transport from the + * calling client to use for requests. + * @return A promise that resolves with the AWS region string. + */ + getAwsRegion: (context: ExternalAccountSupplierContext) => Promise; + /** + * Gets valid AWS security credentials for the requested external account + * identity. Note that these are not cached by the calling {@link AwsClient}, + * so caching should be including in the implementation. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link AwsClient}, contains the requested audience and subject token type + * for the external account identity as well as the transport from the + * calling client to use for requests. + * @return A promise that resolves with the requested {@link AwsSecurityCredentials}. + */ + getAwsSecurityCredentials: (context: ExternalAccountSupplierContext) => Promise; +} +/** + * AWS external account client. This is used for AWS workloads, where + * AWS STS GetCallerIdentity serialized signed requests are exchanged for + * GCP access token. + */ +export declare class AwsClient extends BaseExternalAccountClient { + #private; + private readonly environmentId?; + private readonly awsSecurityCredentialsSupplier; + private readonly regionalCredVerificationUrl; + private awsRequestSigner; + private region; + /** + * @deprecated AWS client no validates the EC2 metadata address. + **/ + static AWS_EC2_METADATA_IPV4_ADDRESS: string; + /** + * @deprecated AWS client no validates the EC2 metadata address. + **/ + static AWS_EC2_METADATA_IPV6_ADDRESS: string; + /** + * Instantiates an AwsClient instance using the provided JSON + * object loaded from an external account credentials file. + * An error is thrown if the credential is not a valid AWS credential. + * @param options The external account options object typically loaded + * from the external account JSON credential file. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options: AwsClientOptions | SnakeToCamelObject, additionalOptions?: AuthClientOptions); + private validateEnvironmentId; + /** + * Triggered when an external subject token is needed to be exchanged for a + * GCP access token via GCP STS endpoint. This will call the + * {@link AwsSecurityCredentialsSupplier} to retrieve an AWS region and AWS + * Security Credentials, then use them to create a signed AWS STS request that + * can be exchanged for a GCP access token. + * @return A promise that resolves with the external subject token. + */ + retrieveSubjectToken(): Promise; +} diff --git a/node_modules/google-auth-library/build/src/auth/awsclient.js b/node_modules/google-auth-library/build/src/auth/awsclient.js new file mode 100644 index 0000000..c2bebd4 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/awsclient.js @@ -0,0 +1,164 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _a, _AwsClient_DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AwsClient = void 0; +const awsrequestsigner_1 = require("./awsrequestsigner"); +const baseexternalclient_1 = require("./baseexternalclient"); +const defaultawssecuritycredentialssupplier_1 = require("./defaultawssecuritycredentialssupplier"); +const util_1 = require("../util"); +/** + * AWS external account client. This is used for AWS workloads, where + * AWS STS GetCallerIdentity serialized signed requests are exchanged for + * GCP access token. + */ +class AwsClient extends baseexternalclient_1.BaseExternalAccountClient { + /** + * Instantiates an AwsClient instance using the provided JSON + * object loaded from an external account credentials file. + * An error is thrown if the credential is not a valid AWS credential. + * @param options The external account options object typically loaded + * from the external account JSON credential file. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options, additionalOptions) { + super(options, additionalOptions); + const opts = (0, util_1.originalOrCamelOptions)(options); + const credentialSource = opts.get('credential_source'); + const awsSecurityCredentialsSupplier = opts.get('aws_security_credentials_supplier'); + // Validate credential sourcing configuration. + if (!credentialSource && !awsSecurityCredentialsSupplier) { + throw new Error('A credential source or AWS security credentials supplier must be specified.'); + } + if (credentialSource && awsSecurityCredentialsSupplier) { + throw new Error('Only one of credential source or AWS security credentials supplier can be specified.'); + } + if (awsSecurityCredentialsSupplier) { + this.awsSecurityCredentialsSupplier = awsSecurityCredentialsSupplier; + this.regionalCredVerificationUrl = + __classPrivateFieldGet(_a, _a, "f", _AwsClient_DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL); + this.credentialSourceType = 'programmatic'; + } + else { + const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource); + this.environmentId = credentialSourceOpts.get('environment_id'); + // This is only required if the AWS region is not available in the + // AWS_REGION or AWS_DEFAULT_REGION environment variables. + const regionUrl = credentialSourceOpts.get('region_url'); + // This is only required if AWS security credentials are not available in + // environment variables. + const securityCredentialsUrl = credentialSourceOpts.get('url'); + const imdsV2SessionTokenUrl = credentialSourceOpts.get('imdsv2_session_token_url'); + this.awsSecurityCredentialsSupplier = + new defaultawssecuritycredentialssupplier_1.DefaultAwsSecurityCredentialsSupplier({ + regionUrl: regionUrl, + securityCredentialsUrl: securityCredentialsUrl, + imdsV2SessionTokenUrl: imdsV2SessionTokenUrl, + }); + this.regionalCredVerificationUrl = credentialSourceOpts.get('regional_cred_verification_url'); + this.credentialSourceType = 'aws'; + // Data validators. + this.validateEnvironmentId(); + } + this.awsRequestSigner = null; + this.region = ''; + } + validateEnvironmentId() { + var _b; + const match = (_b = this.environmentId) === null || _b === void 0 ? void 0 : _b.match(/^(aws)(\d+)$/); + if (!match || !this.regionalCredVerificationUrl) { + throw new Error('No valid AWS "credential_source" provided'); + } + else if (parseInt(match[2], 10) !== 1) { + throw new Error(`aws version "${match[2]}" is not supported in the current build.`); + } + } + /** + * Triggered when an external subject token is needed to be exchanged for a + * GCP access token via GCP STS endpoint. This will call the + * {@link AwsSecurityCredentialsSupplier} to retrieve an AWS region and AWS + * Security Credentials, then use them to create a signed AWS STS request that + * can be exchanged for a GCP access token. + * @return A promise that resolves with the external subject token. + */ + async retrieveSubjectToken() { + // Initialize AWS request signer if not already initialized. + if (!this.awsRequestSigner) { + this.region = await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext); + this.awsRequestSigner = new awsrequestsigner_1.AwsRequestSigner(async () => { + return this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext); + }, this.region); + } + // Generate signed request to AWS STS GetCallerIdentity API. + // Use the required regional endpoint. Otherwise, the request will fail. + const options = await this.awsRequestSigner.getRequestOptions({ + ..._a.RETRY_CONFIG, + url: this.regionalCredVerificationUrl.replace('{region}', this.region), + method: 'POST', + }); + // The GCP STS endpoint expects the headers to be formatted as: + // [ + // {key: 'x-amz-date', value: '...'}, + // {key: 'Authorization', value: '...'}, + // ... + // ] + // And then serialized as: + // encodeURIComponent(JSON.stringify({ + // url: '...', + // method: 'POST', + // headers: [{key: 'x-amz-date', value: '...'}, ...] + // })) + const reformattedHeader = []; + const extendedHeaders = Object.assign({ + // The full, canonical resource name of the workload identity pool + // provider, with or without the HTTPS prefix. + // Including this header as part of the signature is recommended to + // ensure data integrity. + 'x-goog-cloud-target-resource': this.audience, + }, options.headers); + // Reformat header to GCP STS expected format. + for (const key in extendedHeaders) { + reformattedHeader.push({ + key, + value: extendedHeaders[key], + }); + } + // Serialize the reformatted signed request. + return encodeURIComponent(JSON.stringify({ + url: options.url, + method: options.method, + headers: reformattedHeader, + })); + } +} +exports.AwsClient = AwsClient; +_a = AwsClient; +_AwsClient_DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL = { value: 'https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15' }; +/** + * @deprecated AWS client no validates the EC2 metadata address. + **/ +AwsClient.AWS_EC2_METADATA_IPV4_ADDRESS = '169.254.169.254'; +/** + * @deprecated AWS client no validates the EC2 metadata address. + **/ +AwsClient.AWS_EC2_METADATA_IPV6_ADDRESS = 'fd00:ec2::254'; diff --git a/node_modules/google-auth-library/build/src/auth/awsrequestsigner.d.ts b/node_modules/google-auth-library/build/src/auth/awsrequestsigner.d.ts new file mode 100644 index 0000000..3467e97 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/awsrequestsigner.d.ts @@ -0,0 +1,40 @@ +import { GaxiosOptions } from 'gaxios'; +/** + * Interface defining AWS security credentials. + * These are either determined from AWS security_credentials endpoint or + * AWS environment variables. + */ +export interface AwsSecurityCredentials { + accessKeyId: string; + secretAccessKey: string; + token?: string; +} +/** + * Implements an AWS API request signer based on the AWS Signature Version 4 + * signing process. + * https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html + */ +export declare class AwsRequestSigner { + private readonly getCredentials; + private readonly region; + private readonly crypto; + /** + * Instantiates an AWS API request signer used to send authenticated signed + * requests to AWS APIs based on the AWS Signature Version 4 signing process. + * This also provides a mechanism to generate the signed request without + * sending it. + * @param getCredentials A mechanism to retrieve AWS security credentials + * when needed. + * @param region The AWS region to use. + */ + constructor(getCredentials: () => Promise, region: string); + /** + * Generates the signed request for the provided HTTP request for calling + * an AWS API. This follows the steps described at: + * https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html + * @param amzOptions The AWS request options that need to be signed. + * @return A promise that resolves with the GaxiosOptions containing the + * signed HTTP request parameters. + */ + getRequestOptions(amzOptions: GaxiosOptions): Promise; +} diff --git a/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js b/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js new file mode 100644 index 0000000..882a9a9 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js @@ -0,0 +1,209 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AwsRequestSigner = void 0; +const crypto_1 = require("../crypto/crypto"); +/** AWS Signature Version 4 signing algorithm identifier. */ +const AWS_ALGORITHM = 'AWS4-HMAC-SHA256'; +/** + * The termination string for the AWS credential scope value as defined in + * https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html + */ +const AWS_REQUEST_TYPE = 'aws4_request'; +/** + * Implements an AWS API request signer based on the AWS Signature Version 4 + * signing process. + * https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html + */ +class AwsRequestSigner { + /** + * Instantiates an AWS API request signer used to send authenticated signed + * requests to AWS APIs based on the AWS Signature Version 4 signing process. + * This also provides a mechanism to generate the signed request without + * sending it. + * @param getCredentials A mechanism to retrieve AWS security credentials + * when needed. + * @param region The AWS region to use. + */ + constructor(getCredentials, region) { + this.getCredentials = getCredentials; + this.region = region; + this.crypto = (0, crypto_1.createCrypto)(); + } + /** + * Generates the signed request for the provided HTTP request for calling + * an AWS API. This follows the steps described at: + * https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html + * @param amzOptions The AWS request options that need to be signed. + * @return A promise that resolves with the GaxiosOptions containing the + * signed HTTP request parameters. + */ + async getRequestOptions(amzOptions) { + if (!amzOptions.url) { + throw new Error('"url" is required in "amzOptions"'); + } + // Stringify JSON requests. This will be set in the request body of the + // generated signed request. + const requestPayloadData = typeof amzOptions.data === 'object' + ? JSON.stringify(amzOptions.data) + : amzOptions.data; + const url = amzOptions.url; + const method = amzOptions.method || 'GET'; + const requestPayload = amzOptions.body || requestPayloadData; + const additionalAmzHeaders = amzOptions.headers; + const awsSecurityCredentials = await this.getCredentials(); + const uri = new URL(url); + const headerMap = await generateAuthenticationHeaderMap({ + crypto: this.crypto, + host: uri.host, + canonicalUri: uri.pathname, + canonicalQuerystring: uri.search.substr(1), + method, + region: this.region, + securityCredentials: awsSecurityCredentials, + requestPayload, + additionalAmzHeaders, + }); + // Append additional optional headers, eg. X-Amz-Target, Content-Type, etc. + const headers = Object.assign( + // Add x-amz-date if available. + headerMap.amzDate ? { 'x-amz-date': headerMap.amzDate } : {}, { + Authorization: headerMap.authorizationHeader, + host: uri.host, + }, additionalAmzHeaders || {}); + if (awsSecurityCredentials.token) { + Object.assign(headers, { + 'x-amz-security-token': awsSecurityCredentials.token, + }); + } + const awsSignedReq = { + url, + method: method, + headers, + }; + if (typeof requestPayload !== 'undefined') { + awsSignedReq.body = requestPayload; + } + return awsSignedReq; + } +} +exports.AwsRequestSigner = AwsRequestSigner; +/** + * Creates the HMAC-SHA256 hash of the provided message using the + * provided key. + * + * @param crypto The crypto instance used to facilitate cryptographic + * operations. + * @param key The HMAC-SHA256 key to use. + * @param msg The message to hash. + * @return The computed hash bytes. + */ +async function sign(crypto, key, msg) { + return await crypto.signWithHmacSha256(key, msg); +} +/** + * Calculates the signing key used to calculate the signature for + * AWS Signature Version 4 based on: + * https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html + * + * @param crypto The crypto instance used to facilitate cryptographic + * operations. + * @param key The AWS secret access key. + * @param dateStamp The '%Y%m%d' date format. + * @param region The AWS region. + * @param serviceName The AWS service name, eg. sts. + * @return The signing key bytes. + */ +async function getSigningKey(crypto, key, dateStamp, region, serviceName) { + const kDate = await sign(crypto, `AWS4${key}`, dateStamp); + const kRegion = await sign(crypto, kDate, region); + const kService = await sign(crypto, kRegion, serviceName); + const kSigning = await sign(crypto, kService, 'aws4_request'); + return kSigning; +} +/** + * Generates the authentication header map needed for generating the AWS + * Signature Version 4 signed request. + * + * @param option The options needed to compute the authentication header map. + * @return The AWS authentication header map which constitutes of the following + * components: amz-date, authorization header and canonical query string. + */ +async function generateAuthenticationHeaderMap(options) { + const additionalAmzHeaders = options.additionalAmzHeaders || {}; + const requestPayload = options.requestPayload || ''; + // iam.amazonaws.com host => iam service. + // sts.us-east-2.amazonaws.com => sts service. + const serviceName = options.host.split('.')[0]; + const now = new Date(); + // Format: '%Y%m%dT%H%M%SZ'. + const amzDate = now + .toISOString() + .replace(/[-:]/g, '') + .replace(/\.[0-9]+/, ''); + // Format: '%Y%m%d'. + const dateStamp = now.toISOString().replace(/[-]/g, '').replace(/T.*/, ''); + // Change all additional headers to be lower case. + const reformattedAdditionalAmzHeaders = {}; + Object.keys(additionalAmzHeaders).forEach(key => { + reformattedAdditionalAmzHeaders[key.toLowerCase()] = + additionalAmzHeaders[key]; + }); + // Add AWS token if available. + if (options.securityCredentials.token) { + reformattedAdditionalAmzHeaders['x-amz-security-token'] = + options.securityCredentials.token; + } + // Header keys need to be sorted alphabetically. + const amzHeaders = Object.assign({ + host: options.host, + }, + // Previously the date was not fixed with x-amz- and could be provided manually. + // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req + reformattedAdditionalAmzHeaders.date ? {} : { 'x-amz-date': amzDate }, reformattedAdditionalAmzHeaders); + let canonicalHeaders = ''; + const signedHeadersList = Object.keys(amzHeaders).sort(); + signedHeadersList.forEach(key => { + canonicalHeaders += `${key}:${amzHeaders[key]}\n`; + }); + const signedHeaders = signedHeadersList.join(';'); + const payloadHash = await options.crypto.sha256DigestHex(requestPayload); + // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html + const canonicalRequest = `${options.method}\n` + + `${options.canonicalUri}\n` + + `${options.canonicalQuerystring}\n` + + `${canonicalHeaders}\n` + + `${signedHeaders}\n` + + `${payloadHash}`; + const credentialScope = `${dateStamp}/${options.region}/${serviceName}/${AWS_REQUEST_TYPE}`; + // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html + const stringToSign = `${AWS_ALGORITHM}\n` + + `${amzDate}\n` + + `${credentialScope}\n` + + (await options.crypto.sha256DigestHex(canonicalRequest)); + // https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html + const signingKey = await getSigningKey(options.crypto, options.securityCredentials.secretAccessKey, dateStamp, options.region, serviceName); + const signature = await sign(options.crypto, signingKey, stringToSign); + // https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html + const authorizationHeader = `${AWS_ALGORITHM} Credential=${options.securityCredentials.accessKeyId}/` + + `${credentialScope}, SignedHeaders=${signedHeaders}, ` + + `Signature=${(0, crypto_1.fromArrayBufferToHex)(signature)}`; + return { + // Do not return x-amz-date if date is available. + amzDate: reformattedAdditionalAmzHeaders.date ? undefined : amzDate, + authorizationHeader, + canonicalQuerystring: options.canonicalQuerystring, + }; +} diff --git a/node_modules/google-auth-library/build/src/auth/baseexternalclient.d.ts b/node_modules/google-auth-library/build/src/auth/baseexternalclient.d.ts new file mode 100644 index 0000000..af14bee --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/baseexternalclient.d.ts @@ -0,0 +1,322 @@ +import { Gaxios, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +import { Credentials } from './credentials'; +import { AuthClient, AuthClientOptions } from './authclient'; +import { BodyResponseCallback, Transporter } from '../transporters'; +import { GetAccessTokenResponse, Headers } from './oauth2client'; +import { SnakeToCamelObject } from '../util'; +/** + * Offset to take into account network delays and server clock skews. + */ +export declare const EXPIRATION_TIME_OFFSET: number; +/** + * The credentials JSON file type for external account clients. + * There are 3 types of JSON configs: + * 1. authorized_user => Google end user credential + * 2. service_account => Google service account credential + * 3. external_Account => non-GCP service (eg. AWS, Azure, K8s) + */ +export declare const EXTERNAL_ACCOUNT_TYPE = "external_account"; +/** + * Cloud resource manager URL used to retrieve project information. + * + * @deprecated use {@link BaseExternalAccountClient.cloudResourceManagerURL} instead + **/ +export declare const CLOUD_RESOURCE_MANAGER = "https://cloudresourcemanager.googleapis.com/v1/projects/"; +/** + * For backwards compatibility. + */ +export { DEFAULT_UNIVERSE } from './authclient'; +/** + * Shared options used to build {@link ExternalAccountClient} and + * {@link ExternalAccountAuthorizedUserClient}. + */ +export interface SharedExternalAccountClientOptions extends AuthClientOptions { + /** + * The Security Token Service audience, which is usually the fully specified + * resource name of the workload or workforce pool provider. + */ + audience: string; + /** + * The Security Token Service token URL used to exchange the third party token + * for a GCP access token. If not provided, will default to + * 'https://sts.googleapis.com/v1/token' + */ + token_url?: string; +} +/** + * Interface containing context about the requested external identity. This is + * passed on all requests from external account clients to external identity suppliers. + */ +export interface ExternalAccountSupplierContext { + /** + * The requested external account audience. For example: + * * "//iam.googleapis.com/locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID" + * * "//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID" + */ + audience: string; + /** + * The requested subject token type. Expected values include: + * * "urn:ietf:params:oauth:token-type:jwt" + * * "urn:ietf:params:aws:token-type:aws4_request" + * * "urn:ietf:params:oauth:token-type:saml2" + * * "urn:ietf:params:oauth:token-type:id_token" + */ + subjectTokenType: string; + /** The {@link Gaxios} or {@link Transporter} instance from + * the calling external account to use for requests. + */ + transporter: Transporter | Gaxios; +} +/** + * Base external account credentials json interface. + */ +export interface BaseExternalAccountClientOptions extends SharedExternalAccountClientOptions { + /** + * Credential type, should always be 'external_account'. + */ + type?: string; + /** + * The Security Token Service subject token type based on the OAuth 2.0 + * token exchange spec. Expected values include: + * * 'urn:ietf:params:oauth:token-type:jwt' + * * 'urn:ietf:params:aws:token-type:aws4_request' + * * 'urn:ietf:params:oauth:token-type:saml2' + * * 'urn:ietf:params:oauth:token-type:id_token' + */ + subject_token_type: string; + /** + * The URL for the service account impersonation request. This URL is required + * for some APIs. If this URL is not available, the access token from the + * Security Token Service is used directly. + */ + service_account_impersonation_url?: string; + /** + * Object containing additional options for service account impersonation. + */ + service_account_impersonation?: { + /** + * The desired lifetime of the impersonated service account access token. + * If not provided, the default lifetime will be 3600 seconds. + */ + token_lifetime_seconds?: number; + }; + /** + * The endpoint used to retrieve account related information. + */ + token_info_url?: string; + /** + * Client ID of the service account from the console. + */ + client_id?: string; + /** + * Client secret of the service account from the console. + */ + client_secret?: string; + /** + * The workforce pool user project. Required when using a workforce identity + * pool. + */ + workforce_pool_user_project?: string; + /** + * The scopes to request during the authorization grant. + */ + scopes?: string[]; + /** + * @example + * https://cloudresourcemanager.googleapis.com/v1/projects/ + **/ + cloud_resource_manager_url?: string | URL; +} +/** + * Interface defining the successful response for iamcredentials + * generateAccessToken API. + * https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateAccessToken + */ +export interface IamGenerateAccessTokenResponse { + accessToken: string; + /** + * ISO format used for expiration time. + * + * @example + * '2014-10-02T15:01:23.045123456Z' + */ + expireTime: string; +} +/** + * Interface defining the project information response returned by the cloud + * resource manager. + * https://cloud.google.com/resource-manager/reference/rest/v1/projects#Project + */ +export interface ProjectInfo { + projectNumber: string; + projectId: string; + lifecycleState: string; + name: string; + createTime?: string; + parent: { + [key: string]: any; + }; +} +/** + * Internal interface for tracking the access token expiration time. + */ +interface CredentialsWithResponse extends Credentials { + res?: GaxiosResponse | null; +} +/** + * Base external account client. This is used to instantiate AuthClients for + * exchanging external account credentials for GCP access token and authorizing + * requests to GCP APIs. + * The base class implements common logic for exchanging various type of + * external credentials for GCP access token. The logic of determining and + * retrieving the external credential based on the environment and + * credential_source will be left for the subclasses. + */ +export declare abstract class BaseExternalAccountClient extends AuthClient { + #private; + /** + * OAuth scopes for the GCP access token to use. When not provided, + * the default https://www.googleapis.com/auth/cloud-platform is + * used. + */ + scopes?: string | string[]; + private cachedAccessToken; + protected readonly audience: string; + protected readonly subjectTokenType: string; + private readonly serviceAccountImpersonationUrl?; + private readonly serviceAccountImpersonationLifetime?; + private readonly stsCredential; + private readonly clientAuth?; + private readonly workforcePoolUserProject?; + projectNumber: string | null; + private readonly configLifetimeRequested; + protected credentialSourceType?: string; + /** + * @example + * ```ts + * new URL('https://cloudresourcemanager.googleapis.com/v1/projects/'); + * ``` + */ + protected cloudResourceManagerURL: URL | string; + protected supplierContext: ExternalAccountSupplierContext; + /** + * Instantiate a BaseExternalAccountClient instance using the provided JSON + * object loaded from an external account credentials file. + * @param options The external account options object typically loaded + * from the external account JSON credential file. The camelCased options + * are aliases for the snake_cased options. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options: BaseExternalAccountClientOptions | SnakeToCamelObject, additionalOptions?: AuthClientOptions); + /** The service account email to be impersonated, if available. */ + getServiceAccountEmail(): string | null; + /** + * Provides a mechanism to inject GCP access tokens directly. + * When the provided credential expires, a new credential, using the + * external account options, is retrieved. + * @param credentials The Credentials object to set on the current client. + */ + setCredentials(credentials: Credentials): void; + /** + * Triggered when a external subject token is needed to be exchanged for a GCP + * access token via GCP STS endpoint. + * This abstract method needs to be implemented by subclasses depending on + * the type of external credential used. + * @return A promise that resolves with the external subject token. + */ + abstract retrieveSubjectToken(): Promise; + /** + * @return A promise that resolves with the current GCP access token + * response. If the current credential is expired, a new one is retrieved. + */ + getAccessToken(): Promise; + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * The result has the form: + * { Authorization: 'Bearer ' } + */ + getRequestHeaders(): Promise; + /** + * Provides a request implementation with OAuth 2.0 flow. In cases of + * HTTP 401 and 403 responses, it automatically asks for a new access token + * and replays the unsuccessful request. + * @param opts Request options. + * @param callback callback. + * @return A promise that resolves with the HTTP response when no callback is + * provided. + */ + request(opts: GaxiosOptions): GaxiosPromise; + request(opts: GaxiosOptions, callback: BodyResponseCallback): void; + /** + * @return A promise that resolves with the project ID corresponding to the + * current workload identity pool or current workforce pool if + * determinable. For workforce pool credential, it returns the project ID + * corresponding to the workforcePoolUserProject. + * This is introduced to match the current pattern of using the Auth + * library: + * const projectId = await auth.getProjectId(); + * const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; + * const res = await client.request({ url }); + * The resource may not have permission + * (resourcemanager.projects.get) to call this API or the required + * scopes may not be selected: + * https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes + */ + getProjectId(): Promise; + /** + * Authenticates the provided HTTP request, processes it and resolves with the + * returned response. + * @param opts The HTTP request options. + * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure. + * @return A promise that resolves with the successful response. + */ + protected requestAsync(opts: GaxiosOptions, reAuthRetried?: boolean): Promise>; + /** + * Forces token refresh, even if unexpired tokens are currently cached. + * External credentials are exchanged for GCP access tokens via the token + * exchange endpoint and other settings provided in the client options + * object. + * If the service_account_impersonation_url is provided, an additional + * step to exchange the external account GCP access token for a service + * account impersonated token is performed. + * @return A promise that resolves with the fresh GCP access tokens. + */ + protected refreshAccessTokenAsync(): Promise; + /** + * Returns the workload identity pool project number if it is determinable + * from the audience resource name. + * @param audience The STS audience used to determine the project number. + * @return The project number associated with the workload identity pool, if + * this can be determined from the STS audience field. Otherwise, null is + * returned. + */ + private getProjectNumber; + /** + * Exchanges an external account GCP access token for a service + * account impersonated access token using iamcredentials + * GenerateAccessToken API. + * @param token The access token to exchange for a service account access + * token. + * @return A promise that resolves with the service account impersonated + * credentials response. + */ + private getImpersonatedAccessToken; + /** + * Returns whether the provided credentials are expired or not. + * If there is no expiry time, assumes the token is not expired or expiring. + * @param accessToken The credentials to check for expiration. + * @return Whether the credentials are expired or not. + */ + private isExpired; + /** + * @return The list of scopes for the requested GCP access token. + */ + private getScopesArray; + private getMetricsHeaderValue; +} diff --git a/node_modules/google-auth-library/build/src/auth/baseexternalclient.js b/node_modules/google-auth-library/build/src/auth/baseexternalclient.js new file mode 100644 index 0000000..c39861b --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/baseexternalclient.js @@ -0,0 +1,468 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var _BaseExternalAccountClient_instances, _BaseExternalAccountClient_pendingAccessToken, _BaseExternalAccountClient_internalRefreshAccessTokenAsync; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BaseExternalAccountClient = exports.DEFAULT_UNIVERSE = exports.CLOUD_RESOURCE_MANAGER = exports.EXTERNAL_ACCOUNT_TYPE = exports.EXPIRATION_TIME_OFFSET = void 0; +const stream = require("stream"); +const authclient_1 = require("./authclient"); +const sts = require("./stscredentials"); +const util_1 = require("../util"); +/** + * The required token exchange grant_type: rfc8693#section-2.1 + */ +const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange'; +/** + * The requested token exchange requested_token_type: rfc8693#section-2.1 + */ +const STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'; +/** The default OAuth scope to request when none is provided. */ +const DEFAULT_OAUTH_SCOPE = 'https://www.googleapis.com/auth/cloud-platform'; +/** Default impersonated token lifespan in seconds.*/ +const DEFAULT_TOKEN_LIFESPAN = 3600; +/** + * Offset to take into account network delays and server clock skews. + */ +exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000; +/** + * The credentials JSON file type for external account clients. + * There are 3 types of JSON configs: + * 1. authorized_user => Google end user credential + * 2. service_account => Google service account credential + * 3. external_Account => non-GCP service (eg. AWS, Azure, K8s) + */ +exports.EXTERNAL_ACCOUNT_TYPE = 'external_account'; +/** + * Cloud resource manager URL used to retrieve project information. + * + * @deprecated use {@link BaseExternalAccountClient.cloudResourceManagerURL} instead + **/ +exports.CLOUD_RESOURCE_MANAGER = 'https://cloudresourcemanager.googleapis.com/v1/projects/'; +/** The workforce audience pattern. */ +const WORKFORCE_AUDIENCE_PATTERN = '//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+'; +const DEFAULT_TOKEN_URL = 'https://sts.{universeDomain}/v1/token'; +// eslint-disable-next-line @typescript-eslint/no-var-requires +const pkg = require('../../../package.json'); +/** + * For backwards compatibility. + */ +var authclient_2 = require("./authclient"); +Object.defineProperty(exports, "DEFAULT_UNIVERSE", { enumerable: true, get: function () { return authclient_2.DEFAULT_UNIVERSE; } }); +/** + * Base external account client. This is used to instantiate AuthClients for + * exchanging external account credentials for GCP access token and authorizing + * requests to GCP APIs. + * The base class implements common logic for exchanging various type of + * external credentials for GCP access token. The logic of determining and + * retrieving the external credential based on the environment and + * credential_source will be left for the subclasses. + */ +class BaseExternalAccountClient extends authclient_1.AuthClient { + /** + * Instantiate a BaseExternalAccountClient instance using the provided JSON + * object loaded from an external account credentials file. + * @param options The external account options object typically loaded + * from the external account JSON credential file. The camelCased options + * are aliases for the snake_cased options. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options, additionalOptions) { + var _a; + super({ ...options, ...additionalOptions }); + _BaseExternalAccountClient_instances.add(this); + /** + * A pending access token request. Used for concurrent calls. + */ + _BaseExternalAccountClient_pendingAccessToken.set(this, null); + const opts = (0, util_1.originalOrCamelOptions)(options); + const type = opts.get('type'); + if (type && type !== exports.EXTERNAL_ACCOUNT_TYPE) { + throw new Error(`Expected "${exports.EXTERNAL_ACCOUNT_TYPE}" type but ` + + `received "${options.type}"`); + } + const clientId = opts.get('client_id'); + const clientSecret = opts.get('client_secret'); + const tokenUrl = (_a = opts.get('token_url')) !== null && _a !== void 0 ? _a : DEFAULT_TOKEN_URL.replace('{universeDomain}', this.universeDomain); + const subjectTokenType = opts.get('subject_token_type'); + const workforcePoolUserProject = opts.get('workforce_pool_user_project'); + const serviceAccountImpersonationUrl = opts.get('service_account_impersonation_url'); + const serviceAccountImpersonation = opts.get('service_account_impersonation'); + const serviceAccountImpersonationLifetime = (0, util_1.originalOrCamelOptions)(serviceAccountImpersonation).get('token_lifetime_seconds'); + this.cloudResourceManagerURL = new URL(opts.get('cloud_resource_manager_url') || + `https://cloudresourcemanager.${this.universeDomain}/v1/projects/`); + if (clientId) { + this.clientAuth = { + confidentialClientType: 'basic', + clientId, + clientSecret, + }; + } + this.stsCredential = new sts.StsCredentials(tokenUrl, this.clientAuth); + this.scopes = opts.get('scopes') || [DEFAULT_OAUTH_SCOPE]; + this.cachedAccessToken = null; + this.audience = opts.get('audience'); + this.subjectTokenType = subjectTokenType; + this.workforcePoolUserProject = workforcePoolUserProject; + const workforceAudiencePattern = new RegExp(WORKFORCE_AUDIENCE_PATTERN); + if (this.workforcePoolUserProject && + !this.audience.match(workforceAudiencePattern)) { + throw new Error('workforcePoolUserProject should not be set for non-workforce pool ' + + 'credentials.'); + } + this.serviceAccountImpersonationUrl = serviceAccountImpersonationUrl; + this.serviceAccountImpersonationLifetime = + serviceAccountImpersonationLifetime; + if (this.serviceAccountImpersonationLifetime) { + this.configLifetimeRequested = true; + } + else { + this.configLifetimeRequested = false; + this.serviceAccountImpersonationLifetime = DEFAULT_TOKEN_LIFESPAN; + } + this.projectNumber = this.getProjectNumber(this.audience); + this.supplierContext = { + audience: this.audience, + subjectTokenType: this.subjectTokenType, + transporter: this.transporter, + }; + } + /** The service account email to be impersonated, if available. */ + getServiceAccountEmail() { + var _a; + if (this.serviceAccountImpersonationUrl) { + if (this.serviceAccountImpersonationUrl.length > 256) { + /** + * Prevents DOS attacks. + * @see {@link https://github.com/googleapis/google-auth-library-nodejs/security/code-scanning/84} + **/ + throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`); + } + // Parse email from URL. The formal looks as follows: + // https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/name@project-id.iam.gserviceaccount.com:generateAccessToken + const re = /serviceAccounts\/(?[^:]+):generateAccessToken$/; + const result = re.exec(this.serviceAccountImpersonationUrl); + return ((_a = result === null || result === void 0 ? void 0 : result.groups) === null || _a === void 0 ? void 0 : _a.email) || null; + } + return null; + } + /** + * Provides a mechanism to inject GCP access tokens directly. + * When the provided credential expires, a new credential, using the + * external account options, is retrieved. + * @param credentials The Credentials object to set on the current client. + */ + setCredentials(credentials) { + super.setCredentials(credentials); + this.cachedAccessToken = credentials; + } + /** + * @return A promise that resolves with the current GCP access token + * response. If the current credential is expired, a new one is retrieved. + */ + async getAccessToken() { + // If cached access token is unavailable or expired, force refresh. + if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) { + await this.refreshAccessTokenAsync(); + } + // Return GCP access token in GetAccessTokenResponse format. + return { + token: this.cachedAccessToken.access_token, + res: this.cachedAccessToken.res, + }; + } + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * The result has the form: + * { Authorization: 'Bearer ' } + */ + async getRequestHeaders() { + const accessTokenResponse = await this.getAccessToken(); + const headers = { + Authorization: `Bearer ${accessTokenResponse.token}`, + }; + return this.addSharedMetadataHeaders(headers); + } + request(opts, callback) { + if (callback) { + this.requestAsync(opts).then(r => callback(null, r), e => { + return callback(e, e.response); + }); + } + else { + return this.requestAsync(opts); + } + } + /** + * @return A promise that resolves with the project ID corresponding to the + * current workload identity pool or current workforce pool if + * determinable. For workforce pool credential, it returns the project ID + * corresponding to the workforcePoolUserProject. + * This is introduced to match the current pattern of using the Auth + * library: + * const projectId = await auth.getProjectId(); + * const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; + * const res = await client.request({ url }); + * The resource may not have permission + * (resourcemanager.projects.get) to call this API or the required + * scopes may not be selected: + * https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes + */ + async getProjectId() { + const projectNumber = this.projectNumber || this.workforcePoolUserProject; + if (this.projectId) { + // Return previously determined project ID. + return this.projectId; + } + else if (projectNumber) { + // Preferable not to use request() to avoid retrial policies. + const headers = await this.getRequestHeaders(); + const response = await this.transporter.request({ + ...BaseExternalAccountClient.RETRY_CONFIG, + headers, + url: `${this.cloudResourceManagerURL.toString()}${projectNumber}`, + responseType: 'json', + }); + this.projectId = response.data.projectId; + return this.projectId; + } + return null; + } + /** + * Authenticates the provided HTTP request, processes it and resolves with the + * returned response. + * @param opts The HTTP request options. + * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure. + * @return A promise that resolves with the successful response. + */ + async requestAsync(opts, reAuthRetried = false) { + let response; + try { + const requestHeaders = await this.getRequestHeaders(); + opts.headers = opts.headers || {}; + if (requestHeaders && requestHeaders['x-goog-user-project']) { + opts.headers['x-goog-user-project'] = + requestHeaders['x-goog-user-project']; + } + if (requestHeaders && requestHeaders.Authorization) { + opts.headers.Authorization = requestHeaders.Authorization; + } + response = await this.transporter.request(opts); + } + catch (e) { + const res = e.response; + if (res) { + const statusCode = res.status; + // Retry the request for metadata if the following criteria are true: + // - We haven't already retried. It only makes sense to retry once. + // - The response was a 401 or a 403 + // - The request didn't send a readableStream + // - forceRefreshOnFailure is true + const isReadableStream = res.config.data instanceof stream.Readable; + const isAuthErr = statusCode === 401 || statusCode === 403; + if (!reAuthRetried && + isAuthErr && + !isReadableStream && + this.forceRefreshOnFailure) { + await this.refreshAccessTokenAsync(); + return await this.requestAsync(opts, true); + } + } + throw e; + } + return response; + } + /** + * Forces token refresh, even if unexpired tokens are currently cached. + * External credentials are exchanged for GCP access tokens via the token + * exchange endpoint and other settings provided in the client options + * object. + * If the service_account_impersonation_url is provided, an additional + * step to exchange the external account GCP access token for a service + * account impersonated token is performed. + * @return A promise that resolves with the fresh GCP access tokens. + */ + async refreshAccessTokenAsync() { + // Use an existing access token request, or cache a new one + __classPrivateFieldSet(this, _BaseExternalAccountClient_pendingAccessToken, __classPrivateFieldGet(this, _BaseExternalAccountClient_pendingAccessToken, "f") || __classPrivateFieldGet(this, _BaseExternalAccountClient_instances, "m", _BaseExternalAccountClient_internalRefreshAccessTokenAsync).call(this), "f"); + try { + return await __classPrivateFieldGet(this, _BaseExternalAccountClient_pendingAccessToken, "f"); + } + finally { + // clear pending access token for future requests + __classPrivateFieldSet(this, _BaseExternalAccountClient_pendingAccessToken, null, "f"); + } + } + /** + * Returns the workload identity pool project number if it is determinable + * from the audience resource name. + * @param audience The STS audience used to determine the project number. + * @return The project number associated with the workload identity pool, if + * this can be determined from the STS audience field. Otherwise, null is + * returned. + */ + getProjectNumber(audience) { + // STS audience pattern: + // //iam.googleapis.com/projects/$PROJECT_NUMBER/locations/... + const match = audience.match(/\/projects\/([^/]+)/); + if (!match) { + return null; + } + return match[1]; + } + /** + * Exchanges an external account GCP access token for a service + * account impersonated access token using iamcredentials + * GenerateAccessToken API. + * @param token The access token to exchange for a service account access + * token. + * @return A promise that resolves with the service account impersonated + * credentials response. + */ + async getImpersonatedAccessToken(token) { + const opts = { + ...BaseExternalAccountClient.RETRY_CONFIG, + url: this.serviceAccountImpersonationUrl, + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}`, + }, + data: { + scope: this.getScopesArray(), + lifetime: this.serviceAccountImpersonationLifetime + 's', + }, + responseType: 'json', + }; + const response = await this.transporter.request(opts); + const successResponse = response.data; + return { + access_token: successResponse.accessToken, + // Convert from ISO format to timestamp. + expiry_date: new Date(successResponse.expireTime).getTime(), + res: response, + }; + } + /** + * Returns whether the provided credentials are expired or not. + * If there is no expiry time, assumes the token is not expired or expiring. + * @param accessToken The credentials to check for expiration. + * @return Whether the credentials are expired or not. + */ + isExpired(accessToken) { + const now = new Date().getTime(); + return accessToken.expiry_date + ? now >= accessToken.expiry_date - this.eagerRefreshThresholdMillis + : false; + } + /** + * @return The list of scopes for the requested GCP access token. + */ + getScopesArray() { + // Since scopes can be provided as string or array, the type should + // be normalized. + if (typeof this.scopes === 'string') { + return [this.scopes]; + } + return this.scopes || [DEFAULT_OAUTH_SCOPE]; + } + getMetricsHeaderValue() { + const nodeVersion = process.version.replace(/^v/, ''); + const saImpersonation = this.serviceAccountImpersonationUrl !== undefined; + const credentialSourceType = this.credentialSourceType + ? this.credentialSourceType + : 'unknown'; + return `gl-node/${nodeVersion} auth/${pkg.version} google-byoid-sdk source/${credentialSourceType} sa-impersonation/${saImpersonation} config-lifetime/${this.configLifetimeRequested}`; + } +} +exports.BaseExternalAccountClient = BaseExternalAccountClient; +_BaseExternalAccountClient_pendingAccessToken = new WeakMap(), _BaseExternalAccountClient_instances = new WeakSet(), _BaseExternalAccountClient_internalRefreshAccessTokenAsync = async function _BaseExternalAccountClient_internalRefreshAccessTokenAsync() { + // Retrieve the external credential. + const subjectToken = await this.retrieveSubjectToken(); + // Construct the STS credentials options. + const stsCredentialsOptions = { + grantType: STS_GRANT_TYPE, + audience: this.audience, + requestedTokenType: STS_REQUEST_TOKEN_TYPE, + subjectToken, + subjectTokenType: this.subjectTokenType, + // generateAccessToken requires the provided access token to have + // scopes: + // https://www.googleapis.com/auth/iam or + // https://www.googleapis.com/auth/cloud-platform + // The new service account access token scopes will match the user + // provided ones. + scope: this.serviceAccountImpersonationUrl + ? [DEFAULT_OAUTH_SCOPE] + : this.getScopesArray(), + }; + // Exchange the external credentials for a GCP access token. + // Client auth is prioritized over passing the workforcePoolUserProject + // parameter for STS token exchange. + const additionalOptions = !this.clientAuth && this.workforcePoolUserProject + ? { userProject: this.workforcePoolUserProject } + : undefined; + const additionalHeaders = { + 'x-goog-api-client': this.getMetricsHeaderValue(), + }; + const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, additionalHeaders, additionalOptions); + if (this.serviceAccountImpersonationUrl) { + this.cachedAccessToken = await this.getImpersonatedAccessToken(stsResponse.access_token); + } + else if (stsResponse.expires_in) { + // Save response in cached access token. + this.cachedAccessToken = { + access_token: stsResponse.access_token, + expiry_date: new Date().getTime() + stsResponse.expires_in * 1000, + res: stsResponse.res, + }; + } + else { + // Save response in cached access token. + this.cachedAccessToken = { + access_token: stsResponse.access_token, + res: stsResponse.res, + }; + } + // Save credentials. + this.credentials = {}; + Object.assign(this.credentials, this.cachedAccessToken); + delete this.credentials.res; + // Trigger tokens event to notify external listeners. + this.emit('tokens', { + refresh_token: null, + expiry_date: this.cachedAccessToken.expiry_date, + access_token: this.cachedAccessToken.access_token, + token_type: 'Bearer', + id_token: null, + }); + // Return the cached access token. + return this.cachedAccessToken; +}; diff --git a/node_modules/google-auth-library/build/src/auth/computeclient.d.ts b/node_modules/google-auth-library/build/src/auth/computeclient.d.ts new file mode 100644 index 0000000..2d88366 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/computeclient.d.ts @@ -0,0 +1,37 @@ +import { GaxiosError } from 'gaxios'; +import { GetTokenResponse, OAuth2Client, OAuth2ClientOptions } from './oauth2client'; +export interface ComputeOptions extends OAuth2ClientOptions { + /** + * The service account email to use, or 'default'. A Compute Engine instance + * may have multiple service accounts. + */ + serviceAccountEmail?: string; + /** + * The scopes that will be requested when acquiring service account + * credentials. Only applicable to modern App Engine and Cloud Function + * runtimes as of March 2019. + */ + scopes?: string | string[]; +} +export declare class Compute extends OAuth2Client { + readonly serviceAccountEmail: string; + scopes: string[]; + /** + * Google Compute Engine service account credentials. + * + * Retrieve access token from the metadata server. + * See: https://cloud.google.com/compute/docs/access/authenticate-workloads#applications + */ + constructor(options?: ComputeOptions); + /** + * Refreshes the access token. + * @param refreshToken Unused parameter + */ + protected refreshTokenNoCache(refreshToken?: string | null): Promise; + /** + * Fetches an ID token. + * @param targetAudience the audience for the fetched ID token. + */ + fetchIdToken(targetAudience: string): Promise; + protected wrapError(e: GaxiosError): void; +} diff --git a/node_modules/google-auth-library/build/src/auth/computeclient.js b/node_modules/google-auth-library/build/src/auth/computeclient.js new file mode 100644 index 0000000..4554e03 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/computeclient.js @@ -0,0 +1,117 @@ +"use strict"; +// Copyright 2013 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Compute = void 0; +const gaxios_1 = require("gaxios"); +const gcpMetadata = require("gcp-metadata"); +const oauth2client_1 = require("./oauth2client"); +class Compute extends oauth2client_1.OAuth2Client { + /** + * Google Compute Engine service account credentials. + * + * Retrieve access token from the metadata server. + * See: https://cloud.google.com/compute/docs/access/authenticate-workloads#applications + */ + constructor(options = {}) { + super(options); + // Start with an expired refresh token, which will automatically be + // refreshed before the first API call is made. + this.credentials = { expiry_date: 1, refresh_token: 'compute-placeholder' }; + this.serviceAccountEmail = options.serviceAccountEmail || 'default'; + this.scopes = Array.isArray(options.scopes) + ? options.scopes + : options.scopes + ? [options.scopes] + : []; + } + /** + * Refreshes the access token. + * @param refreshToken Unused parameter + */ + async refreshTokenNoCache( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + refreshToken) { + const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`; + let data; + try { + const instanceOptions = { + property: tokenPath, + }; + if (this.scopes.length > 0) { + instanceOptions.params = { + scopes: this.scopes.join(','), + }; + } + data = await gcpMetadata.instance(instanceOptions); + } + catch (e) { + if (e instanceof gaxios_1.GaxiosError) { + e.message = `Could not refresh access token: ${e.message}`; + this.wrapError(e); + } + throw e; + } + const tokens = data; + if (data && data.expires_in) { + tokens.expiry_date = new Date().getTime() + data.expires_in * 1000; + delete tokens.expires_in; + } + this.emit('tokens', tokens); + return { tokens, res: null }; + } + /** + * Fetches an ID token. + * @param targetAudience the audience for the fetched ID token. + */ + async fetchIdToken(targetAudience) { + const idTokenPath = `service-accounts/${this.serviceAccountEmail}/identity` + + `?format=full&audience=${targetAudience}`; + let idToken; + try { + const instanceOptions = { + property: idTokenPath, + }; + idToken = await gcpMetadata.instance(instanceOptions); + } + catch (e) { + if (e instanceof Error) { + e.message = `Could not fetch ID token: ${e.message}`; + } + throw e; + } + return idToken; + } + wrapError(e) { + const res = e.response; + if (res && res.status) { + e.status = res.status; + if (res.status === 403) { + e.message = + 'A Forbidden error was returned while attempting to retrieve an access ' + + 'token for the Compute Engine built-in service account. This may be because the Compute ' + + 'Engine instance does not have the correct permission scopes specified: ' + + e.message; + } + else if (res.status === 404) { + e.message = + 'A Not Found error was returned while attempting to retrieve an access' + + 'token for the Compute Engine built-in service account. This may be because the Compute ' + + 'Engine instance does not have any permission scopes specified: ' + + e.message; + } + } + } +} +exports.Compute = Compute; diff --git a/node_modules/google-auth-library/build/src/auth/credentials.d.ts b/node_modules/google-auth-library/build/src/auth/credentials.d.ts new file mode 100644 index 0000000..896b014 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/credentials.d.ts @@ -0,0 +1,75 @@ +export interface Credentials { + /** + * This field is only present if the access_type parameter was set to offline in the authentication request. For details, see Refresh tokens. + */ + refresh_token?: string | null; + /** + * The time in ms at which this token is thought to expire. + */ + expiry_date?: number | null; + /** + * A token that can be sent to a Google API. + */ + access_token?: string | null; + /** + * Identifies the type of token returned. At this time, this field always has the value Bearer. + */ + token_type?: string | null; + /** + * A JWT that contains identity information about the user that is digitally signed by Google. + */ + id_token?: string | null; + /** + * The scopes of access granted by the access_token expressed as a list of space-delimited, case-sensitive strings. + */ + scope?: string; +} +export interface CredentialRequest { + /** + * This field is only present if the access_type parameter was set to offline in the authentication request. For details, see Refresh tokens. + */ + refresh_token?: string; + /** + * A token that can be sent to a Google API. + */ + access_token?: string; + /** + * Identifies the type of token returned. At this time, this field always has the value Bearer. + */ + token_type?: string; + /** + * The remaining lifetime of the access token in seconds. + */ + expires_in?: number; + /** + * A JWT that contains identity information about the user that is digitally signed by Google. + */ + id_token?: string; + /** + * The scopes of access granted by the access_token expressed as a list of space-delimited, case-sensitive strings. + */ + scope?: string; +} +export interface JWTInput { + type?: string; + client_email?: string; + private_key?: string; + private_key_id?: string; + project_id?: string; + client_id?: string; + client_secret?: string; + refresh_token?: string; + quota_project_id?: string; + universe_domain?: string; +} +export interface ImpersonatedJWTInput { + type?: string; + source_credentials?: JWTInput; + service_account_impersonation_url?: string; + delegates?: string[]; +} +export interface CredentialBody { + client_email?: string; + private_key?: string; + universe_domain?: string; +} diff --git a/node_modules/google-auth-library/build/src/auth/credentials.js b/node_modules/google-auth-library/build/src/auth/credentials.js new file mode 100644 index 0000000..8db999f --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/credentials.js @@ -0,0 +1,15 @@ +"use strict"; +// Copyright 2014 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.d.ts b/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.d.ts new file mode 100644 index 0000000..62a2fa4 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.d.ts @@ -0,0 +1,79 @@ +import { ExternalAccountSupplierContext } from './baseexternalclient'; +import { GaxiosOptions } from 'gaxios'; +import { AwsSecurityCredentialsSupplier } from './awsclient'; +import { AwsSecurityCredentials } from './awsrequestsigner'; +/** + * Interface defining the options used to build a {@link DefaultAwsSecurityCredentialsSupplier}. + */ +export interface DefaultAwsSecurityCredentialsSupplierOptions { + /** + * The URL to call to retrieve the active AWS region. + **/ + regionUrl?: string; + /** + * The URL to call to retrieve AWS security credentials. + **/ + securityCredentialsUrl?: string; + /** + ** The URL to call to retrieve the IMDSV2 session token. + **/ + imdsV2SessionTokenUrl?: string; + /** + * Additional Gaxios options to use when making requests to the AWS metadata + * endpoints. + */ + additionalGaxiosOptions?: GaxiosOptions; +} +/** + * Internal AWS security credentials supplier implementation used by {@link AwsClient} + * when a credential source is provided instead of a user defined supplier. + * The logic is summarized as: + * 1. If imdsv2_session_token_url is provided in the credential source, then + * fetch the aws session token and include it in the headers of the + * metadata requests. This is a requirement for IDMSv2 but optional + * for IDMSv1. + * 2. Retrieve AWS region from availability-zone. + * 3a. Check AWS credentials in environment variables. If not found, get + * from security-credentials endpoint. + * 3b. Get AWS credentials from security-credentials endpoint. In order + * to retrieve this, the AWS role needs to be determined by calling + * security-credentials endpoint without any argument. Then the + * credentials can be retrieved via: security-credentials/role_name + * 4. Generate the signed request to AWS STS GetCallerIdentity action. + * 5. Inject x-goog-cloud-target-resource into header and serialize the + * signed request. This will be the subject-token to pass to GCP STS. + */ +export declare class DefaultAwsSecurityCredentialsSupplier implements AwsSecurityCredentialsSupplier { + #private; + private readonly regionUrl?; + private readonly securityCredentialsUrl?; + private readonly imdsV2SessionTokenUrl?; + private readonly additionalGaxiosOptions?; + /** + * Instantiates a new DefaultAwsSecurityCredentialsSupplier using information + * from the credential_source stored in the ADC file. + * @param opts The default aws security credentials supplier options object to + * build the supplier with. + */ + constructor(opts: DefaultAwsSecurityCredentialsSupplierOptions); + /** + * Returns the active AWS region. This first checks to see if the region + * is available as an environment variable. If it is not, then the supplier + * will call the region URL. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link AwsClient}, contains the requested audience and subject token type + * for the external account identity. + * @return A promise that resolves with the AWS region string. + */ + getAwsRegion(context: ExternalAccountSupplierContext): Promise; + /** + * Returns AWS security credentials. This first checks to see if the credentials + * is available as environment variables. If it is not, then the supplier + * will call the security credentials URL. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link AwsClient}, contains the requested audience and subject token type + * for the external account identity. + * @return A promise that resolves with the AWS security credentials. + */ + getAwsSecurityCredentials(context: ExternalAccountSupplierContext): Promise; +} diff --git a/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js b/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js new file mode 100644 index 0000000..83d95bc --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js @@ -0,0 +1,196 @@ +"use strict"; +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _DefaultAwsSecurityCredentialsSupplier_instances, _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken, _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName, _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials, _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get, _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DefaultAwsSecurityCredentialsSupplier = void 0; +/** + * Internal AWS security credentials supplier implementation used by {@link AwsClient} + * when a credential source is provided instead of a user defined supplier. + * The logic is summarized as: + * 1. If imdsv2_session_token_url is provided in the credential source, then + * fetch the aws session token and include it in the headers of the + * metadata requests. This is a requirement for IDMSv2 but optional + * for IDMSv1. + * 2. Retrieve AWS region from availability-zone. + * 3a. Check AWS credentials in environment variables. If not found, get + * from security-credentials endpoint. + * 3b. Get AWS credentials from security-credentials endpoint. In order + * to retrieve this, the AWS role needs to be determined by calling + * security-credentials endpoint without any argument. Then the + * credentials can be retrieved via: security-credentials/role_name + * 4. Generate the signed request to AWS STS GetCallerIdentity action. + * 5. Inject x-goog-cloud-target-resource into header and serialize the + * signed request. This will be the subject-token to pass to GCP STS. + */ +class DefaultAwsSecurityCredentialsSupplier { + /** + * Instantiates a new DefaultAwsSecurityCredentialsSupplier using information + * from the credential_source stored in the ADC file. + * @param opts The default aws security credentials supplier options object to + * build the supplier with. + */ + constructor(opts) { + _DefaultAwsSecurityCredentialsSupplier_instances.add(this); + this.regionUrl = opts.regionUrl; + this.securityCredentialsUrl = opts.securityCredentialsUrl; + this.imdsV2SessionTokenUrl = opts.imdsV2SessionTokenUrl; + this.additionalGaxiosOptions = opts.additionalGaxiosOptions; + } + /** + * Returns the active AWS region. This first checks to see if the region + * is available as an environment variable. If it is not, then the supplier + * will call the region URL. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link AwsClient}, contains the requested audience and subject token type + * for the external account identity. + * @return A promise that resolves with the AWS region string. + */ + async getAwsRegion(context) { + // Priority order for region determination: + // AWS_REGION > AWS_DEFAULT_REGION > metadata server. + if (__classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get)) { + return __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get); + } + const metadataHeaders = {}; + if (!__classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get) && this.imdsV2SessionTokenUrl) { + metadataHeaders['x-aws-ec2-metadata-token'] = + await __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken).call(this, context.transporter); + } + if (!this.regionUrl) { + throw new Error('Unable to determine AWS region due to missing ' + + '"options.credential_source.region_url"'); + } + const opts = { + ...this.additionalGaxiosOptions, + url: this.regionUrl, + method: 'GET', + responseType: 'text', + headers: metadataHeaders, + }; + const response = await context.transporter.request(opts); + // Remove last character. For example, if us-east-2b is returned, + // the region would be us-east-2. + return response.data.substr(0, response.data.length - 1); + } + /** + * Returns AWS security credentials. This first checks to see if the credentials + * is available as environment variables. If it is not, then the supplier + * will call the security credentials URL. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link AwsClient}, contains the requested audience and subject token type + * for the external account identity. + * @return A promise that resolves with the AWS security credentials. + */ + async getAwsSecurityCredentials(context) { + // Check environment variables for permanent credentials first. + // https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html + if (__classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get)) { + return __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get); + } + const metadataHeaders = {}; + if (this.imdsV2SessionTokenUrl) { + metadataHeaders['x-aws-ec2-metadata-token'] = + await __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken).call(this, context.transporter); + } + // Since the role on a VM can change, we don't need to cache it. + const roleName = await __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName).call(this, metadataHeaders, context.transporter); + // Temporary credentials typically last for several hours. + // Expiration is returned in response. + // Consider future optimization of this logic to cache AWS tokens + // until their natural expiration. + const awsCreds = await __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials).call(this, roleName, metadataHeaders, context.transporter); + return { + accessKeyId: awsCreds.AccessKeyId, + secretAccessKey: awsCreds.SecretAccessKey, + token: awsCreds.Token, + }; + } +} +exports.DefaultAwsSecurityCredentialsSupplier = DefaultAwsSecurityCredentialsSupplier; +_DefaultAwsSecurityCredentialsSupplier_instances = new WeakSet(), _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken = +/** + * @param transporter The transporter to use for requests. + * @return A promise that resolves with the IMDSv2 Session Token. + */ +async function _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken(transporter) { + const opts = { + ...this.additionalGaxiosOptions, + url: this.imdsV2SessionTokenUrl, + method: 'PUT', + responseType: 'text', + headers: { 'x-aws-ec2-metadata-token-ttl-seconds': '300' }, + }; + const response = await transporter.request(opts); + return response.data; +}, _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName = +/** + * @param headers The headers to be used in the metadata request. + * @param transporter The transporter to use for requests. + * @return A promise that resolves with the assigned role to the current + * AWS VM. This is needed for calling the security-credentials endpoint. + */ +async function _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName(headers, transporter) { + if (!this.securityCredentialsUrl) { + throw new Error('Unable to determine AWS role name due to missing ' + + '"options.credential_source.url"'); + } + const opts = { + ...this.additionalGaxiosOptions, + url: this.securityCredentialsUrl, + method: 'GET', + responseType: 'text', + headers: headers, + }; + const response = await transporter.request(opts); + return response.data; +}, _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials = +/** + * Retrieves the temporary AWS credentials by calling the security-credentials + * endpoint as specified in the `credential_source` object. + * @param roleName The role attached to the current VM. + * @param headers The headers to be used in the metadata request. + * @param transporter The transporter to use for requests. + * @return A promise that resolves with the temporary AWS credentials + * needed for creating the GetCallerIdentity signed request. + */ +async function _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials(roleName, headers, transporter) { + const response = await transporter.request({ + ...this.additionalGaxiosOptions, + url: `${this.securityCredentialsUrl}/${roleName}`, + responseType: 'json', + headers: headers, + }); + return response.data; +}, _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get = function _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get() { + // The AWS region can be provided through AWS_REGION or AWS_DEFAULT_REGION. + // Only one is required. + return (process.env['AWS_REGION'] || process.env['AWS_DEFAULT_REGION'] || null); +}, _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get = function _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get() { + // Both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required. + if (process.env['AWS_ACCESS_KEY_ID'] && + process.env['AWS_SECRET_ACCESS_KEY']) { + return { + accessKeyId: process.env['AWS_ACCESS_KEY_ID'], + secretAccessKey: process.env['AWS_SECRET_ACCESS_KEY'], + token: process.env['AWS_SESSION_TOKEN'], + }; + } + return null; +}; diff --git a/node_modules/google-auth-library/build/src/auth/downscopedclient.d.ts b/node_modules/google-auth-library/build/src/auth/downscopedclient.d.ts new file mode 100644 index 0000000..028379b --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/downscopedclient.d.ts @@ -0,0 +1,139 @@ +import { GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +import { BodyResponseCallback } from '../transporters'; +import { Credentials } from './credentials'; +import { AuthClient, AuthClientOptions } from './authclient'; +import { GetAccessTokenResponse, Headers } from './oauth2client'; +/** + * The maximum number of access boundary rules a Credential Access Boundary + * can contain. + */ +export declare const MAX_ACCESS_BOUNDARY_RULES_COUNT = 10; +/** + * Offset to take into account network delays and server clock skews. + */ +export declare const EXPIRATION_TIME_OFFSET: number; +/** + * Internal interface for tracking the access token expiration time. + */ +interface CredentialsWithResponse extends Credentials { + res?: GaxiosResponse | null; +} +/** + * Internal interface for tracking and returning the Downscoped access token + * expiration time in epoch time (seconds). + */ +interface DownscopedAccessTokenResponse extends GetAccessTokenResponse { + expirationTime?: number | null; +} +/** + * Defines an upper bound of permissions available for a GCP credential. + */ +export interface CredentialAccessBoundary { + accessBoundary: { + accessBoundaryRules: AccessBoundaryRule[]; + }; +} +/** Defines an upper bound of permissions on a particular resource. */ +interface AccessBoundaryRule { + availablePermissions: string[]; + availableResource: string; + availabilityCondition?: AvailabilityCondition; +} +/** + * An optional condition that can be used as part of a + * CredentialAccessBoundary to further restrict permissions. + */ +interface AvailabilityCondition { + expression: string; + title?: string; + description?: string; +} +/** + * Defines a set of Google credentials that are downscoped from an existing set + * of Google OAuth2 credentials. This is useful to restrict the Identity and + * Access Management (IAM) permissions that a short-lived credential can use. + * The common pattern of usage is to have a token broker with elevated access + * generate these downscoped credentials from higher access source credentials + * and pass the downscoped short-lived access tokens to a token consumer via + * some secure authenticated channel for limited access to Google Cloud Storage + * resources. + */ +export declare class DownscopedClient extends AuthClient { + private readonly authClient; + private readonly credentialAccessBoundary; + private cachedDownscopedAccessToken; + private readonly stsCredential; + /** + * Instantiates a downscoped client object using the provided source + * AuthClient and credential access boundary rules. + * To downscope permissions of a source AuthClient, a Credential Access + * Boundary that specifies which resources the new credential can access, as + * well as an upper bound on the permissions that are available on each + * resource, has to be defined. A downscoped client can then be instantiated + * using the source AuthClient and the Credential Access Boundary. + * @param authClient The source AuthClient to be downscoped based on the + * provided Credential Access Boundary rules. + * @param credentialAccessBoundary The Credential Access Boundary which + * contains a list of access boundary rules. Each rule contains information + * on the resource that the rule applies to, the upper bound of the + * permissions that are available on that resource and an optional + * condition to further restrict permissions. + * @param additionalOptions **DEPRECATED, set this in the provided `authClient`.** + * Optional additional behavior customization options. + * @param quotaProjectId **DEPRECATED, set this in the provided `authClient`.** + * Optional quota project id for setting up in the x-goog-user-project header. + */ + constructor(authClient: AuthClient, credentialAccessBoundary: CredentialAccessBoundary, additionalOptions?: AuthClientOptions, quotaProjectId?: string); + /** + * Provides a mechanism to inject Downscoped access tokens directly. + * The expiry_date field is required to facilitate determination of the token + * expiration which would make it easier for the token consumer to handle. + * @param credentials The Credentials object to set on the current client. + */ + setCredentials(credentials: Credentials): void; + getAccessToken(): Promise; + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * The result has the form: + * { Authorization: 'Bearer ' } + */ + getRequestHeaders(): Promise; + /** + * Provides a request implementation with OAuth 2.0 flow. In cases of + * HTTP 401 and 403 responses, it automatically asks for a new access token + * and replays the unsuccessful request. + * @param opts Request options. + * @param callback callback. + * @return A promise that resolves with the HTTP response when no callback + * is provided. + */ + request(opts: GaxiosOptions): GaxiosPromise; + request(opts: GaxiosOptions, callback: BodyResponseCallback): void; + /** + * Authenticates the provided HTTP request, processes it and resolves with the + * returned response. + * @param opts The HTTP request options. + * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure + * @return A promise that resolves with the successful response. + */ + protected requestAsync(opts: GaxiosOptions, reAuthRetried?: boolean): Promise>; + /** + * Forces token refresh, even if unexpired tokens are currently cached. + * GCP access tokens are retrieved from authclient object/source credential. + * Then GCP access tokens are exchanged for downscoped access tokens via the + * token exchange endpoint. + * @return A promise that resolves with the fresh downscoped access token. + */ + protected refreshAccessTokenAsync(): Promise; + /** + * Returns whether the provided credentials are expired or not. + * If there is no expiry time, assumes the token is not expired or expiring. + * @param downscopedAccessToken The credentials to check for expiration. + * @return Whether the credentials are expired or not. + */ + private isExpired; +} +export {}; diff --git a/node_modules/google-auth-library/build/src/auth/downscopedclient.js b/node_modules/google-auth-library/build/src/auth/downscopedclient.js new file mode 100644 index 0000000..9252974 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/downscopedclient.js @@ -0,0 +1,262 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DownscopedClient = exports.EXPIRATION_TIME_OFFSET = exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = void 0; +const stream = require("stream"); +const authclient_1 = require("./authclient"); +const sts = require("./stscredentials"); +/** + * The required token exchange grant_type: rfc8693#section-2.1 + */ +const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange'; +/** + * The requested token exchange requested_token_type: rfc8693#section-2.1 + */ +const STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'; +/** + * The requested token exchange subject_token_type: rfc8693#section-2.1 + */ +const STS_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'; +/** + * The maximum number of access boundary rules a Credential Access Boundary + * can contain. + */ +exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = 10; +/** + * Offset to take into account network delays and server clock skews. + */ +exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000; +/** + * Defines a set of Google credentials that are downscoped from an existing set + * of Google OAuth2 credentials. This is useful to restrict the Identity and + * Access Management (IAM) permissions that a short-lived credential can use. + * The common pattern of usage is to have a token broker with elevated access + * generate these downscoped credentials from higher access source credentials + * and pass the downscoped short-lived access tokens to a token consumer via + * some secure authenticated channel for limited access to Google Cloud Storage + * resources. + */ +class DownscopedClient extends authclient_1.AuthClient { + /** + * Instantiates a downscoped client object using the provided source + * AuthClient and credential access boundary rules. + * To downscope permissions of a source AuthClient, a Credential Access + * Boundary that specifies which resources the new credential can access, as + * well as an upper bound on the permissions that are available on each + * resource, has to be defined. A downscoped client can then be instantiated + * using the source AuthClient and the Credential Access Boundary. + * @param authClient The source AuthClient to be downscoped based on the + * provided Credential Access Boundary rules. + * @param credentialAccessBoundary The Credential Access Boundary which + * contains a list of access boundary rules. Each rule contains information + * on the resource that the rule applies to, the upper bound of the + * permissions that are available on that resource and an optional + * condition to further restrict permissions. + * @param additionalOptions **DEPRECATED, set this in the provided `authClient`.** + * Optional additional behavior customization options. + * @param quotaProjectId **DEPRECATED, set this in the provided `authClient`.** + * Optional quota project id for setting up in the x-goog-user-project header. + */ + constructor(authClient, credentialAccessBoundary, additionalOptions, quotaProjectId) { + super({ ...additionalOptions, quotaProjectId }); + this.authClient = authClient; + this.credentialAccessBoundary = credentialAccessBoundary; + // Check 1-10 Access Boundary Rules are defined within Credential Access + // Boundary. + if (credentialAccessBoundary.accessBoundary.accessBoundaryRules.length === 0) { + throw new Error('At least one access boundary rule needs to be defined.'); + } + else if (credentialAccessBoundary.accessBoundary.accessBoundaryRules.length > + exports.MAX_ACCESS_BOUNDARY_RULES_COUNT) { + throw new Error('The provided access boundary has more than ' + + `${exports.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`); + } + // Check at least one permission should be defined in each Access Boundary + // Rule. + for (const rule of credentialAccessBoundary.accessBoundary + .accessBoundaryRules) { + if (rule.availablePermissions.length === 0) { + throw new Error('At least one permission should be defined in access boundary rules.'); + } + } + this.stsCredential = new sts.StsCredentials(`https://sts.${this.universeDomain}/v1/token`); + this.cachedDownscopedAccessToken = null; + } + /** + * Provides a mechanism to inject Downscoped access tokens directly. + * The expiry_date field is required to facilitate determination of the token + * expiration which would make it easier for the token consumer to handle. + * @param credentials The Credentials object to set on the current client. + */ + setCredentials(credentials) { + if (!credentials.expiry_date) { + throw new Error('The access token expiry_date field is missing in the provided ' + + 'credentials.'); + } + super.setCredentials(credentials); + this.cachedDownscopedAccessToken = credentials; + } + async getAccessToken() { + // If the cached access token is unavailable or expired, force refresh. + // The Downscoped access token will be returned in + // DownscopedAccessTokenResponse format. + if (!this.cachedDownscopedAccessToken || + this.isExpired(this.cachedDownscopedAccessToken)) { + await this.refreshAccessTokenAsync(); + } + // Return Downscoped access token in DownscopedAccessTokenResponse format. + return { + token: this.cachedDownscopedAccessToken.access_token, + expirationTime: this.cachedDownscopedAccessToken.expiry_date, + res: this.cachedDownscopedAccessToken.res, + }; + } + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * The result has the form: + * { Authorization: 'Bearer ' } + */ + async getRequestHeaders() { + const accessTokenResponse = await this.getAccessToken(); + const headers = { + Authorization: `Bearer ${accessTokenResponse.token}`, + }; + return this.addSharedMetadataHeaders(headers); + } + request(opts, callback) { + if (callback) { + this.requestAsync(opts).then(r => callback(null, r), e => { + return callback(e, e.response); + }); + } + else { + return this.requestAsync(opts); + } + } + /** + * Authenticates the provided HTTP request, processes it and resolves with the + * returned response. + * @param opts The HTTP request options. + * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure + * @return A promise that resolves with the successful response. + */ + async requestAsync(opts, reAuthRetried = false) { + let response; + try { + const requestHeaders = await this.getRequestHeaders(); + opts.headers = opts.headers || {}; + if (requestHeaders && requestHeaders['x-goog-user-project']) { + opts.headers['x-goog-user-project'] = + requestHeaders['x-goog-user-project']; + } + if (requestHeaders && requestHeaders.Authorization) { + opts.headers.Authorization = requestHeaders.Authorization; + } + response = await this.transporter.request(opts); + } + catch (e) { + const res = e.response; + if (res) { + const statusCode = res.status; + // Retry the request for metadata if the following criteria are true: + // - We haven't already retried. It only makes sense to retry once. + // - The response was a 401 or a 403 + // - The request didn't send a readableStream + // - forceRefreshOnFailure is true + const isReadableStream = res.config.data instanceof stream.Readable; + const isAuthErr = statusCode === 401 || statusCode === 403; + if (!reAuthRetried && + isAuthErr && + !isReadableStream && + this.forceRefreshOnFailure) { + await this.refreshAccessTokenAsync(); + return await this.requestAsync(opts, true); + } + } + throw e; + } + return response; + } + /** + * Forces token refresh, even if unexpired tokens are currently cached. + * GCP access tokens are retrieved from authclient object/source credential. + * Then GCP access tokens are exchanged for downscoped access tokens via the + * token exchange endpoint. + * @return A promise that resolves with the fresh downscoped access token. + */ + async refreshAccessTokenAsync() { + var _a; + // Retrieve GCP access token from source credential. + const subjectToken = (await this.authClient.getAccessToken()).token; + // Construct the STS credentials options. + const stsCredentialsOptions = { + grantType: STS_GRANT_TYPE, + requestedTokenType: STS_REQUEST_TOKEN_TYPE, + subjectToken: subjectToken, + subjectTokenType: STS_SUBJECT_TOKEN_TYPE, + }; + // Exchange the source AuthClient access token for a Downscoped access + // token. + const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, undefined, this.credentialAccessBoundary); + /** + * The STS endpoint will only return the expiration time for the downscoped + * access token if the original access token represents a service account. + * The downscoped token's expiration time will always match the source + * credential expiration. When no expires_in is returned, we can copy the + * source credential's expiration time. + */ + const sourceCredExpireDate = ((_a = this.authClient.credentials) === null || _a === void 0 ? void 0 : _a.expiry_date) || null; + const expiryDate = stsResponse.expires_in + ? new Date().getTime() + stsResponse.expires_in * 1000 + : sourceCredExpireDate; + // Save response in cached access token. + this.cachedDownscopedAccessToken = { + access_token: stsResponse.access_token, + expiry_date: expiryDate, + res: stsResponse.res, + }; + // Save credentials. + this.credentials = {}; + Object.assign(this.credentials, this.cachedDownscopedAccessToken); + delete this.credentials.res; + // Trigger tokens event to notify external listeners. + this.emit('tokens', { + refresh_token: null, + expiry_date: this.cachedDownscopedAccessToken.expiry_date, + access_token: this.cachedDownscopedAccessToken.access_token, + token_type: 'Bearer', + id_token: null, + }); + // Return the cached access token. + return this.cachedDownscopedAccessToken; + } + /** + * Returns whether the provided credentials are expired or not. + * If there is no expiry time, assumes the token is not expired or expiring. + * @param downscopedAccessToken The credentials to check for expiration. + * @return Whether the credentials are expired or not. + */ + isExpired(downscopedAccessToken) { + const now = new Date().getTime(); + return downscopedAccessToken.expiry_date + ? now >= + downscopedAccessToken.expiry_date - this.eagerRefreshThresholdMillis + : false; + } +} +exports.DownscopedClient = DownscopedClient; diff --git a/node_modules/google-auth-library/build/src/auth/envDetect.d.ts b/node_modules/google-auth-library/build/src/auth/envDetect.d.ts new file mode 100644 index 0000000..2fc01c6 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/envDetect.d.ts @@ -0,0 +1,10 @@ +export declare enum GCPEnv { + APP_ENGINE = "APP_ENGINE", + KUBERNETES_ENGINE = "KUBERNETES_ENGINE", + CLOUD_FUNCTIONS = "CLOUD_FUNCTIONS", + COMPUTE_ENGINE = "COMPUTE_ENGINE", + CLOUD_RUN = "CLOUD_RUN", + NONE = "NONE" +} +export declare function clear(): void; +export declare function getEnv(): Promise; diff --git a/node_modules/google-auth-library/build/src/auth/envDetect.js b/node_modules/google-auth-library/build/src/auth/envDetect.js new file mode 100644 index 0000000..73fb915 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/envDetect.js @@ -0,0 +1,89 @@ +"use strict"; +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GCPEnv = void 0; +exports.clear = clear; +exports.getEnv = getEnv; +const gcpMetadata = require("gcp-metadata"); +var GCPEnv; +(function (GCPEnv) { + GCPEnv["APP_ENGINE"] = "APP_ENGINE"; + GCPEnv["KUBERNETES_ENGINE"] = "KUBERNETES_ENGINE"; + GCPEnv["CLOUD_FUNCTIONS"] = "CLOUD_FUNCTIONS"; + GCPEnv["COMPUTE_ENGINE"] = "COMPUTE_ENGINE"; + GCPEnv["CLOUD_RUN"] = "CLOUD_RUN"; + GCPEnv["NONE"] = "NONE"; +})(GCPEnv || (exports.GCPEnv = GCPEnv = {})); +let envPromise; +function clear() { + envPromise = undefined; +} +async function getEnv() { + if (envPromise) { + return envPromise; + } + envPromise = getEnvMemoized(); + return envPromise; +} +async function getEnvMemoized() { + let env = GCPEnv.NONE; + if (isAppEngine()) { + env = GCPEnv.APP_ENGINE; + } + else if (isCloudFunction()) { + env = GCPEnv.CLOUD_FUNCTIONS; + } + else if (await isComputeEngine()) { + if (await isKubernetesEngine()) { + env = GCPEnv.KUBERNETES_ENGINE; + } + else if (isCloudRun()) { + env = GCPEnv.CLOUD_RUN; + } + else { + env = GCPEnv.COMPUTE_ENGINE; + } + } + else { + env = GCPEnv.NONE; + } + return env; +} +function isAppEngine() { + return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME); +} +function isCloudFunction() { + return !!(process.env.FUNCTION_NAME || process.env.FUNCTION_TARGET); +} +/** + * This check only verifies that the environment is running knative. + * This must be run *after* checking for Kubernetes, otherwise it will + * return a false positive. + */ +function isCloudRun() { + return !!process.env.K_CONFIGURATION; +} +async function isKubernetesEngine() { + try { + await gcpMetadata.instance('attributes/cluster-name'); + return true; + } + catch (e) { + return false; + } +} +async function isComputeEngine() { + return gcpMetadata.isAvailable(); +} diff --git a/node_modules/google-auth-library/build/src/auth/executable-response.d.ts b/node_modules/google-auth-library/build/src/auth/executable-response.d.ts new file mode 100644 index 0000000..259d276 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/executable-response.d.ts @@ -0,0 +1,137 @@ +/** + * Interface defining the JSON formatted response of a 3rd party executable + * used by the pluggable auth client. + */ +export interface ExecutableResponseJson { + /** + * The version of the JSON response. Only version 1 is currently supported. + * Always required. + */ + version: number; + /** + * Whether the executable ran successfully. Always required. + */ + success: boolean; + /** + * The epoch time for expiration of the token in seconds, required for + * successful responses. + */ + expiration_time?: number; + /** + * The type of subject token in the response, currently supported values are: + * urn:ietf:params:oauth:token-type:saml2 + * urn:ietf:params:oauth:token-type:id_token + * urn:ietf:params:oauth:token-type:jwt + */ + token_type?: string; + /** + * The error code from the executable, required when unsuccessful. + */ + code?: string; + /** + * The error message from the executable, required when unsuccessful. + */ + message?: string; + /** + * The ID token to be used as a subject token when token_type is id_token or jwt. + */ + id_token?: string; + /** + * The response to be used as a subject token when token_type is saml2. + */ + saml_response?: string; +} +/** + * Defines the response of a 3rd party executable run by the pluggable auth client. + */ +export declare class ExecutableResponse { + /** + * The version of the Executable response. Only version 1 is currently supported. + */ + readonly version: number; + /** + * Whether the executable ran successfully. + */ + readonly success: boolean; + /** + * The epoch time for expiration of the token in seconds. + */ + readonly expirationTime?: number; + /** + * The type of subject token in the response, currently supported values are: + * urn:ietf:params:oauth:token-type:saml2 + * urn:ietf:params:oauth:token-type:id_token + * urn:ietf:params:oauth:token-type:jwt + */ + readonly tokenType?: string; + /** + * The error code from the executable. + */ + readonly errorCode?: string; + /** + * The error message from the executable. + */ + readonly errorMessage?: string; + /** + * The subject token from the executable, format depends on tokenType. + */ + readonly subjectToken?: string; + /** + * Instantiates an ExecutableResponse instance using the provided JSON object + * from the output of the executable. + * @param responseJson Response from a 3rd party executable, loaded from a + * run of the executable or a cached output file. + */ + constructor(responseJson: ExecutableResponseJson); + /** + * @return A boolean representing if the response has a valid token. Returns + * true when the response was successful and the token is not expired. + */ + isValid(): boolean; + /** + * @return A boolean representing if the response is expired. Returns true if the + * provided timeout has passed. + */ + isExpired(): boolean; +} +/** + * An error thrown by the ExecutableResponse class. + */ +export declare class ExecutableResponseError extends Error { + constructor(message: string); +} +/** + * An error thrown when the 'version' field in an executable response is missing or invalid. + */ +export declare class InvalidVersionFieldError extends ExecutableResponseError { +} +/** + * An error thrown when the 'success' field in an executable response is missing or invalid. + */ +export declare class InvalidSuccessFieldError extends ExecutableResponseError { +} +/** + * An error thrown when the 'expiration_time' field in an executable response is missing or invalid. + */ +export declare class InvalidExpirationTimeFieldError extends ExecutableResponseError { +} +/** + * An error thrown when the 'token_type' field in an executable response is missing or invalid. + */ +export declare class InvalidTokenTypeFieldError extends ExecutableResponseError { +} +/** + * An error thrown when the 'code' field in an executable response is missing or invalid. + */ +export declare class InvalidCodeFieldError extends ExecutableResponseError { +} +/** + * An error thrown when the 'message' field in an executable response is missing or invalid. + */ +export declare class InvalidMessageFieldError extends ExecutableResponseError { +} +/** + * An error thrown when the subject token in an executable response is missing or invalid. + */ +export declare class InvalidSubjectTokenError extends ExecutableResponseError { +} diff --git a/node_modules/google-auth-library/build/src/auth/executable-response.js b/node_modules/google-auth-library/build/src/auth/executable-response.js new file mode 100644 index 0000000..be4e818 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/executable-response.js @@ -0,0 +1,146 @@ +"use strict"; +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InvalidSubjectTokenError = exports.InvalidMessageFieldError = exports.InvalidCodeFieldError = exports.InvalidTokenTypeFieldError = exports.InvalidExpirationTimeFieldError = exports.InvalidSuccessFieldError = exports.InvalidVersionFieldError = exports.ExecutableResponseError = exports.ExecutableResponse = void 0; +const SAML_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:saml2'; +const OIDC_SUBJECT_TOKEN_TYPE1 = 'urn:ietf:params:oauth:token-type:id_token'; +const OIDC_SUBJECT_TOKEN_TYPE2 = 'urn:ietf:params:oauth:token-type:jwt'; +/** + * Defines the response of a 3rd party executable run by the pluggable auth client. + */ +class ExecutableResponse { + /** + * Instantiates an ExecutableResponse instance using the provided JSON object + * from the output of the executable. + * @param responseJson Response from a 3rd party executable, loaded from a + * run of the executable or a cached output file. + */ + constructor(responseJson) { + // Check that the required fields exist in the json response. + if (!responseJson.version) { + throw new InvalidVersionFieldError("Executable response must contain a 'version' field."); + } + if (responseJson.success === undefined) { + throw new InvalidSuccessFieldError("Executable response must contain a 'success' field."); + } + this.version = responseJson.version; + this.success = responseJson.success; + // Validate required fields for a successful response. + if (this.success) { + this.expirationTime = responseJson.expiration_time; + this.tokenType = responseJson.token_type; + // Validate token type field. + if (this.tokenType !== SAML_SUBJECT_TOKEN_TYPE && + this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE1 && + this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE2) { + throw new InvalidTokenTypeFieldError("Executable response must contain a 'token_type' field when successful " + + `and it must be one of ${OIDC_SUBJECT_TOKEN_TYPE1}, ${OIDC_SUBJECT_TOKEN_TYPE2}, or ${SAML_SUBJECT_TOKEN_TYPE}.`); + } + // Validate subject token. + if (this.tokenType === SAML_SUBJECT_TOKEN_TYPE) { + if (!responseJson.saml_response) { + throw new InvalidSubjectTokenError(`Executable response must contain a 'saml_response' field when token_type=${SAML_SUBJECT_TOKEN_TYPE}.`); + } + this.subjectToken = responseJson.saml_response; + } + else { + if (!responseJson.id_token) { + throw new InvalidSubjectTokenError("Executable response must contain a 'id_token' field when " + + `token_type=${OIDC_SUBJECT_TOKEN_TYPE1} or ${OIDC_SUBJECT_TOKEN_TYPE2}.`); + } + this.subjectToken = responseJson.id_token; + } + } + else { + // Both code and message must be provided for unsuccessful responses. + if (!responseJson.code) { + throw new InvalidCodeFieldError("Executable response must contain a 'code' field when unsuccessful."); + } + if (!responseJson.message) { + throw new InvalidMessageFieldError("Executable response must contain a 'message' field when unsuccessful."); + } + this.errorCode = responseJson.code; + this.errorMessage = responseJson.message; + } + } + /** + * @return A boolean representing if the response has a valid token. Returns + * true when the response was successful and the token is not expired. + */ + isValid() { + return !this.isExpired() && this.success; + } + /** + * @return A boolean representing if the response is expired. Returns true if the + * provided timeout has passed. + */ + isExpired() { + return (this.expirationTime !== undefined && + this.expirationTime < Math.round(Date.now() / 1000)); + } +} +exports.ExecutableResponse = ExecutableResponse; +/** + * An error thrown by the ExecutableResponse class. + */ +class ExecutableResponseError extends Error { + constructor(message) { + super(message); + Object.setPrototypeOf(this, new.target.prototype); + } +} +exports.ExecutableResponseError = ExecutableResponseError; +/** + * An error thrown when the 'version' field in an executable response is missing or invalid. + */ +class InvalidVersionFieldError extends ExecutableResponseError { +} +exports.InvalidVersionFieldError = InvalidVersionFieldError; +/** + * An error thrown when the 'success' field in an executable response is missing or invalid. + */ +class InvalidSuccessFieldError extends ExecutableResponseError { +} +exports.InvalidSuccessFieldError = InvalidSuccessFieldError; +/** + * An error thrown when the 'expiration_time' field in an executable response is missing or invalid. + */ +class InvalidExpirationTimeFieldError extends ExecutableResponseError { +} +exports.InvalidExpirationTimeFieldError = InvalidExpirationTimeFieldError; +/** + * An error thrown when the 'token_type' field in an executable response is missing or invalid. + */ +class InvalidTokenTypeFieldError extends ExecutableResponseError { +} +exports.InvalidTokenTypeFieldError = InvalidTokenTypeFieldError; +/** + * An error thrown when the 'code' field in an executable response is missing or invalid. + */ +class InvalidCodeFieldError extends ExecutableResponseError { +} +exports.InvalidCodeFieldError = InvalidCodeFieldError; +/** + * An error thrown when the 'message' field in an executable response is missing or invalid. + */ +class InvalidMessageFieldError extends ExecutableResponseError { +} +exports.InvalidMessageFieldError = InvalidMessageFieldError; +/** + * An error thrown when the subject token in an executable response is missing or invalid. + */ +class InvalidSubjectTokenError extends ExecutableResponseError { +} +exports.InvalidSubjectTokenError = InvalidSubjectTokenError; diff --git a/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.d.ts b/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.d.ts new file mode 100644 index 0000000..1707deb --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.d.ts @@ -0,0 +1,78 @@ +import { AuthClient, AuthClientOptions } from './authclient'; +import { Headers } from './oauth2client'; +import { BodyResponseCallback } from '../transporters'; +import { GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +import { Credentials } from './credentials'; +import { SharedExternalAccountClientOptions } from './baseexternalclient'; +/** + * The credentials JSON file type for external account authorized user clients. + */ +export declare const EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = "external_account_authorized_user"; +/** + * External Account Authorized User Credentials JSON interface. + */ +export interface ExternalAccountAuthorizedUserClientOptions extends SharedExternalAccountClientOptions { + type: typeof EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE; + client_id: string; + client_secret: string; + refresh_token: string; + token_info_url: string; + revoke_url?: string; +} +/** + * Internal interface for tracking the access token expiration time. + */ +interface CredentialsWithResponse extends Credentials { + res?: GaxiosResponse | null; +} +/** + * External Account Authorized User Client. This is used for OAuth2 credentials + * sourced using external identities through Workforce Identity Federation. + * Obtaining the initial access and refresh token can be done through the + * Google Cloud CLI. + */ +export declare class ExternalAccountAuthorizedUserClient extends AuthClient { + private cachedAccessToken; + private readonly externalAccountAuthorizedUserHandler; + private refreshToken; + /** + * Instantiates an ExternalAccountAuthorizedUserClient instances using the + * provided JSON object loaded from a credentials files. + * An error is throws if the credential is not valid. + * @param options The external account authorized user option object typically + * from the external accoutn authorized user JSON credential file. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options: ExternalAccountAuthorizedUserClientOptions, additionalOptions?: AuthClientOptions); + getAccessToken(): Promise<{ + token?: string | null; + res?: GaxiosResponse | null; + }>; + getRequestHeaders(): Promise; + request(opts: GaxiosOptions): GaxiosPromise; + request(opts: GaxiosOptions, callback: BodyResponseCallback): void; + /** + * Authenticates the provided HTTP request, processes it and resolves with the + * returned response. + * @param opts The HTTP request options. + * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure. + * @return A promise that resolves with the successful response. + */ + protected requestAsync(opts: GaxiosOptions, reAuthRetried?: boolean): Promise>; + /** + * Forces token refresh, even if unexpired tokens are currently cached. + * @return A promise that resolves with the refreshed credential. + */ + protected refreshAccessTokenAsync(): Promise; + /** + * Returns whether the provided credentials are expired or not. + * If there is no expiry time, assumes the token is not expired or expiring. + * @param credentials The credentials to check for expiration. + * @return Whether the credentials are expired or not. + */ + private isExpired; +} +export {}; diff --git a/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js b/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js new file mode 100644 index 0000000..b7147a3 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js @@ -0,0 +1,239 @@ +"use strict"; +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ExternalAccountAuthorizedUserClient = exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = void 0; +const authclient_1 = require("./authclient"); +const oauth2common_1 = require("./oauth2common"); +const gaxios_1 = require("gaxios"); +const stream = require("stream"); +const baseexternalclient_1 = require("./baseexternalclient"); +/** + * The credentials JSON file type for external account authorized user clients. + */ +exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = 'external_account_authorized_user'; +const DEFAULT_TOKEN_URL = 'https://sts.{universeDomain}/v1/oauthtoken'; +/** + * Handler for token refresh requests sent to the token_url endpoint for external + * authorized user credentials. + */ +class ExternalAccountAuthorizedUserHandler extends oauth2common_1.OAuthClientAuthHandler { + /** + * Initializes an ExternalAccountAuthorizedUserHandler instance. + * @param url The URL of the token refresh endpoint. + * @param transporter The transporter to use for the refresh request. + * @param clientAuthentication The client authentication credentials to use + * for the refresh request. + */ + constructor(url, transporter, clientAuthentication) { + super(clientAuthentication); + this.url = url; + this.transporter = transporter; + } + /** + * Requests a new access token from the token_url endpoint using the provided + * refresh token. + * @param refreshToken The refresh token to use to generate a new access token. + * @param additionalHeaders Optional additional headers to pass along the + * request. + * @return A promise that resolves with the token refresh response containing + * the requested access token and its expiration time. + */ + async refreshToken(refreshToken, additionalHeaders) { + const values = new URLSearchParams({ + grant_type: 'refresh_token', + refresh_token: refreshToken, + }); + const headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + ...additionalHeaders, + }; + const opts = { + ...ExternalAccountAuthorizedUserHandler.RETRY_CONFIG, + url: this.url, + method: 'POST', + headers, + data: values.toString(), + responseType: 'json', + }; + // Apply OAuth client authentication. + this.applyClientAuthenticationOptions(opts); + try { + const response = await this.transporter.request(opts); + // Successful response. + const tokenRefreshResponse = response.data; + tokenRefreshResponse.res = response; + return tokenRefreshResponse; + } + catch (error) { + // Translate error to OAuthError. + if (error instanceof gaxios_1.GaxiosError && error.response) { + throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, + // Preserve other fields from the original error. + error); + } + // Request could fail before the server responds. + throw error; + } + } +} +/** + * External Account Authorized User Client. This is used for OAuth2 credentials + * sourced using external identities through Workforce Identity Federation. + * Obtaining the initial access and refresh token can be done through the + * Google Cloud CLI. + */ +class ExternalAccountAuthorizedUserClient extends authclient_1.AuthClient { + /** + * Instantiates an ExternalAccountAuthorizedUserClient instances using the + * provided JSON object loaded from a credentials files. + * An error is throws if the credential is not valid. + * @param options The external account authorized user option object typically + * from the external accoutn authorized user JSON credential file. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options, additionalOptions) { + var _a; + super({ ...options, ...additionalOptions }); + if (options.universe_domain) { + this.universeDomain = options.universe_domain; + } + this.refreshToken = options.refresh_token; + const clientAuth = { + confidentialClientType: 'basic', + clientId: options.client_id, + clientSecret: options.client_secret, + }; + this.externalAccountAuthorizedUserHandler = + new ExternalAccountAuthorizedUserHandler((_a = options.token_url) !== null && _a !== void 0 ? _a : DEFAULT_TOKEN_URL.replace('{universeDomain}', this.universeDomain), this.transporter, clientAuth); + this.cachedAccessToken = null; + this.quotaProjectId = options.quota_project_id; + // As threshold could be zero, + // eagerRefreshThresholdMillis || EXPIRATION_TIME_OFFSET will override the + // zero value. + if (typeof (additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.eagerRefreshThresholdMillis) !== 'number') { + this.eagerRefreshThresholdMillis = baseexternalclient_1.EXPIRATION_TIME_OFFSET; + } + else { + this.eagerRefreshThresholdMillis = additionalOptions + .eagerRefreshThresholdMillis; + } + this.forceRefreshOnFailure = !!(additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.forceRefreshOnFailure); + } + async getAccessToken() { + // If cached access token is unavailable or expired, force refresh. + if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) { + await this.refreshAccessTokenAsync(); + } + // Return GCP access token in GetAccessTokenResponse format. + return { + token: this.cachedAccessToken.access_token, + res: this.cachedAccessToken.res, + }; + } + async getRequestHeaders() { + const accessTokenResponse = await this.getAccessToken(); + const headers = { + Authorization: `Bearer ${accessTokenResponse.token}`, + }; + return this.addSharedMetadataHeaders(headers); + } + request(opts, callback) { + if (callback) { + this.requestAsync(opts).then(r => callback(null, r), e => { + return callback(e, e.response); + }); + } + else { + return this.requestAsync(opts); + } + } + /** + * Authenticates the provided HTTP request, processes it and resolves with the + * returned response. + * @param opts The HTTP request options. + * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure. + * @return A promise that resolves with the successful response. + */ + async requestAsync(opts, reAuthRetried = false) { + let response; + try { + const requestHeaders = await this.getRequestHeaders(); + opts.headers = opts.headers || {}; + if (requestHeaders && requestHeaders['x-goog-user-project']) { + opts.headers['x-goog-user-project'] = + requestHeaders['x-goog-user-project']; + } + if (requestHeaders && requestHeaders.Authorization) { + opts.headers.Authorization = requestHeaders.Authorization; + } + response = await this.transporter.request(opts); + } + catch (e) { + const res = e.response; + if (res) { + const statusCode = res.status; + // Retry the request for metadata if the following criteria are true: + // - We haven't already retried. It only makes sense to retry once. + // - The response was a 401 or a 403 + // - The request didn't send a readableStream + // - forceRefreshOnFailure is true + const isReadableStream = res.config.data instanceof stream.Readable; + const isAuthErr = statusCode === 401 || statusCode === 403; + if (!reAuthRetried && + isAuthErr && + !isReadableStream && + this.forceRefreshOnFailure) { + await this.refreshAccessTokenAsync(); + return await this.requestAsync(opts, true); + } + } + throw e; + } + return response; + } + /** + * Forces token refresh, even if unexpired tokens are currently cached. + * @return A promise that resolves with the refreshed credential. + */ + async refreshAccessTokenAsync() { + // Refresh the access token using the refresh token. + const refreshResponse = await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken); + this.cachedAccessToken = { + access_token: refreshResponse.access_token, + expiry_date: new Date().getTime() + refreshResponse.expires_in * 1000, + res: refreshResponse.res, + }; + if (refreshResponse.refresh_token !== undefined) { + this.refreshToken = refreshResponse.refresh_token; + } + return this.cachedAccessToken; + } + /** + * Returns whether the provided credentials are expired or not. + * If there is no expiry time, assumes the token is not expired or expiring. + * @param credentials The credentials to check for expiration. + * @return Whether the credentials are expired or not. + */ + isExpired(credentials) { + const now = new Date().getTime(); + return credentials.expiry_date + ? now >= credentials.expiry_date - this.eagerRefreshThresholdMillis + : false; + } +} +exports.ExternalAccountAuthorizedUserClient = ExternalAccountAuthorizedUserClient; diff --git a/node_modules/google-auth-library/build/src/auth/externalclient.d.ts b/node_modules/google-auth-library/build/src/auth/externalclient.d.ts new file mode 100644 index 0000000..90caac5 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/externalclient.d.ts @@ -0,0 +1,26 @@ +import { BaseExternalAccountClient } from './baseexternalclient'; +import { IdentityPoolClientOptions } from './identitypoolclient'; +import { AwsClientOptions } from './awsclient'; +import { PluggableAuthClientOptions } from './pluggable-auth-client'; +import { AuthClientOptions } from './authclient'; +export type ExternalAccountClientOptions = IdentityPoolClientOptions | AwsClientOptions | PluggableAuthClientOptions; +/** + * Dummy class with no constructor. Developers are expected to use fromJSON. + */ +export declare class ExternalAccountClient { + constructor(); + /** + * This static method will instantiate the + * corresponding type of external account credential depending on the + * underlying credential source. + * @param options The external account options object typically loaded + * from the external account JSON credential file. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + * @return A BaseExternalAccountClient instance or null if the options + * provided do not correspond to an external account credential. + */ + static fromJSON(options: ExternalAccountClientOptions, additionalOptions?: AuthClientOptions): BaseExternalAccountClient | null; +} diff --git a/node_modules/google-auth-library/build/src/auth/externalclient.js b/node_modules/google-auth-library/build/src/auth/externalclient.js new file mode 100644 index 0000000..54860ea --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/externalclient.js @@ -0,0 +1,64 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ExternalAccountClient = void 0; +const baseexternalclient_1 = require("./baseexternalclient"); +const identitypoolclient_1 = require("./identitypoolclient"); +const awsclient_1 = require("./awsclient"); +const pluggable_auth_client_1 = require("./pluggable-auth-client"); +/** + * Dummy class with no constructor. Developers are expected to use fromJSON. + */ +class ExternalAccountClient { + constructor() { + throw new Error('ExternalAccountClients should be initialized via: ' + + 'ExternalAccountClient.fromJSON(), ' + + 'directly via explicit constructors, eg. ' + + 'new AwsClient(options), new IdentityPoolClient(options), new' + + 'PluggableAuthClientOptions, or via ' + + 'new GoogleAuth(options).getClient()'); + } + /** + * This static method will instantiate the + * corresponding type of external account credential depending on the + * underlying credential source. + * @param options The external account options object typically loaded + * from the external account JSON credential file. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + * @return A BaseExternalAccountClient instance or null if the options + * provided do not correspond to an external account credential. + */ + static fromJSON(options, additionalOptions) { + var _a, _b; + if (options && options.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { + if ((_a = options.credential_source) === null || _a === void 0 ? void 0 : _a.environment_id) { + return new awsclient_1.AwsClient(options, additionalOptions); + } + else if ((_b = options.credential_source) === null || _b === void 0 ? void 0 : _b.executable) { + return new pluggable_auth_client_1.PluggableAuthClient(options, additionalOptions); + } + else { + return new identitypoolclient_1.IdentityPoolClient(options, additionalOptions); + } + } + else { + return null; + } + } +} +exports.ExternalAccountClient = ExternalAccountClient; diff --git a/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.d.ts b/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.d.ts new file mode 100644 index 0000000..7a67d40 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.d.ts @@ -0,0 +1,42 @@ +import { ExternalAccountSupplierContext } from './baseexternalclient'; +import { SubjectTokenFormatType, SubjectTokenSupplier } from './identitypoolclient'; +/** + * Interface that defines options used to build a {@link FileSubjectTokenSupplier} + */ +export interface FileSubjectTokenSupplierOptions { + /** + * The file path where the external credential is located. + */ + filePath: string; + /** + * The token file or URL response type (JSON or text). + */ + formatType: SubjectTokenFormatType; + /** + * For JSON response types, this is the subject_token field name. For Azure, + * this is access_token. For text response types, this is ignored. + */ + subjectTokenFieldName?: string; +} +/** + * Internal subject token supplier implementation used when a file location + * is configured in the credential configuration used to build an {@link IdentityPoolClient} + */ +export declare class FileSubjectTokenSupplier implements SubjectTokenSupplier { + private readonly filePath; + private readonly formatType; + private readonly subjectTokenFieldName?; + /** + * Instantiates a new file based subject token supplier. + * @param opts The file subject token supplier options to build the supplier + * with. + */ + constructor(opts: FileSubjectTokenSupplierOptions); + /** + * Returns the subject token stored at the file specified in the constructor. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link IdentityPoolClient}, contains the requested audience and subject + * token type for the external account identity. Not used. + */ + getSubjectToken(context: ExternalAccountSupplierContext): Promise; +} diff --git a/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js b/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js new file mode 100644 index 0000000..abf9bed --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js @@ -0,0 +1,81 @@ +"use strict"; +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var _a, _b, _c; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FileSubjectTokenSupplier = void 0; +const util_1 = require("util"); +const fs = require("fs"); +// fs.readfile is undefined in browser karma tests causing +// `npm run browser-test` to fail as test.oauth2.ts imports this file via +// src/index.ts. +// Fallback to void function to avoid promisify throwing a TypeError. +const readFile = (0, util_1.promisify)((_a = fs.readFile) !== null && _a !== void 0 ? _a : (() => { })); +const realpath = (0, util_1.promisify)((_b = fs.realpath) !== null && _b !== void 0 ? _b : (() => { })); +const lstat = (0, util_1.promisify)((_c = fs.lstat) !== null && _c !== void 0 ? _c : (() => { })); +/** + * Internal subject token supplier implementation used when a file location + * is configured in the credential configuration used to build an {@link IdentityPoolClient} + */ +class FileSubjectTokenSupplier { + /** + * Instantiates a new file based subject token supplier. + * @param opts The file subject token supplier options to build the supplier + * with. + */ + constructor(opts) { + this.filePath = opts.filePath; + this.formatType = opts.formatType; + this.subjectTokenFieldName = opts.subjectTokenFieldName; + } + /** + * Returns the subject token stored at the file specified in the constructor. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link IdentityPoolClient}, contains the requested audience and subject + * token type for the external account identity. Not used. + */ + async getSubjectToken(context) { + // Make sure there is a file at the path. lstatSync will throw if there is + // nothing there. + let parsedFilePath = this.filePath; + try { + // Resolve path to actual file in case of symlink. Expect a thrown error + // if not resolvable. + parsedFilePath = await realpath(parsedFilePath); + if (!(await lstat(parsedFilePath)).isFile()) { + throw new Error(); + } + } + catch (err) { + if (err instanceof Error) { + err.message = `The file at ${parsedFilePath} does not exist, or it is not a file. ${err.message}`; + } + throw err; + } + let subjectToken; + const rawText = await readFile(parsedFilePath, { encoding: 'utf8' }); + if (this.formatType === 'text') { + subjectToken = rawText; + } + else if (this.formatType === 'json' && this.subjectTokenFieldName) { + const json = JSON.parse(rawText); + subjectToken = json[this.subjectTokenFieldName]; + } + if (!subjectToken) { + throw new Error('Unable to parse the subject_token from the credential_source file'); + } + return subjectToken; + } +} +exports.FileSubjectTokenSupplier = FileSubjectTokenSupplier; diff --git a/node_modules/google-auth-library/build/src/auth/googleauth.d.ts b/node_modules/google-auth-library/build/src/auth/googleauth.d.ts new file mode 100644 index 0000000..099c280 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/googleauth.d.ts @@ -0,0 +1,375 @@ +import { GaxiosOptions, GaxiosResponse } from 'gaxios'; +import * as stream from 'stream'; +import { DefaultTransporter, Transporter } from '../transporters'; +import { CredentialBody, ImpersonatedJWTInput, JWTInput } from './credentials'; +import { IdTokenClient } from './idtokenclient'; +import { GCPEnv } from './envDetect'; +import { JWT, JWTOptions } from './jwtclient'; +import { Headers, OAuth2ClientOptions } from './oauth2client'; +import { UserRefreshClient, UserRefreshClientOptions } from './refreshclient'; +import { Impersonated, ImpersonatedOptions } from './impersonated'; +import { ExternalAccountClientOptions } from './externalclient'; +import { BaseExternalAccountClient } from './baseexternalclient'; +import { AuthClient, AuthClientOptions } from './authclient'; +import { ExternalAccountAuthorizedUserClient } from './externalAccountAuthorizedUserClient'; +import { AnyAuthClient } from '..'; +/** + * Defines all types of explicit clients that are determined via ADC JSON + * config file. + */ +export type JSONClient = JWT | UserRefreshClient | BaseExternalAccountClient | ExternalAccountAuthorizedUserClient | Impersonated; +export interface ProjectIdCallback { + (err?: Error | null, projectId?: string | null): void; +} +export interface CredentialCallback { + (err: Error | null, result?: JSONClient): void; +} +export interface ADCCallback { + (err: Error | null, credential?: AuthClient, projectId?: string | null): void; +} +export interface ADCResponse { + credential: AuthClient; + projectId: string | null; +} +export interface GoogleAuthOptions { + /** + * An API key to use, optional. Cannot be used with {@link GoogleAuthOptions.credentials `credentials`}. + */ + apiKey?: string; + /** + * An `AuthClient` to use + */ + authClient?: T; + /** + * Path to a .json, .pem, or .p12 key file + */ + keyFilename?: string; + /** + * Path to a .json, .pem, or .p12 key file + */ + keyFile?: string; + /** + * Object containing client_email and private_key properties, or the + * external account client options. + * Cannot be used with {@link GoogleAuthOptions.apiKey `apiKey`}. + * + * @remarks + * + * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}. + */ + credentials?: JWTInput | ExternalAccountClientOptions; + /** + * Options object passed to the constructor of the client + */ + clientOptions?: JWTOptions | OAuth2ClientOptions | UserRefreshClientOptions | ImpersonatedOptions; + /** + * Required scopes for the desired API request + */ + scopes?: string | string[]; + /** + * Your project ID. + */ + projectId?: string; + /** + * The default service domain for a given Cloud universe. + * + * This is an ergonomic equivalent to {@link clientOptions}'s `universeDomain` + * property and will be set for all generated {@link AuthClient}s. + */ + universeDomain?: string; +} +export declare const CLOUD_SDK_CLIENT_ID = "764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com"; +export declare const GoogleAuthExceptionMessages: { + readonly API_KEY_WITH_CREDENTIALS: "API Keys and Credentials are mutually exclusive authentication methods and cannot be used together."; + readonly NO_PROJECT_ID_FOUND: string; + readonly NO_CREDENTIALS_FOUND: string; + readonly NO_ADC_FOUND: "Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information."; + readonly NO_UNIVERSE_DOMAIN_FOUND: string; +}; +export declare class GoogleAuth { + #private; + transporter?: Transporter; + /** + * Caches a value indicating whether the auth layer is running on Google + * Compute Engine. + * @private + */ + private checkIsGCE?; + useJWTAccessWithScope?: boolean; + defaultServicePath?: string; + get isGCE(): boolean | undefined; + private _findProjectIdPromise?; + private _cachedProjectId?; + jsonContent: JWTInput | ExternalAccountClientOptions | null; + apiKey: string | null; + cachedCredential: AnyAuthClient | T | null; + /** + * Scopes populated by the client library by default. We differentiate between + * these and user defined scopes when deciding whether to use a self-signed JWT. + */ + defaultScopes?: string | string[]; + private keyFilename?; + private scopes?; + private clientOptions; + /** + * Export DefaultTransporter as a static property of the class. + */ + static DefaultTransporter: typeof DefaultTransporter; + /** + * Configuration is resolved in the following order of precedence: + * - {@link GoogleAuthOptions.credentials `credentials`} + * - {@link GoogleAuthOptions.keyFilename `keyFilename`} + * - {@link GoogleAuthOptions.keyFile `keyFile`} + * + * {@link GoogleAuthOptions.clientOptions `clientOptions`} are passed to the + * {@link AuthClient `AuthClient`s}. + * + * @param opts + */ + constructor(opts?: GoogleAuthOptions); + setGapicJWTValues(client: JWT): void; + /** + * Obtains the default project ID for the application. + * + * Retrieves in the following order of precedence: + * - The `projectId` provided in this object's construction + * - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable + * - GOOGLE_APPLICATION_CREDENTIALS JSON file + * - Cloud SDK: `gcloud config config-helper --format json` + * - GCE project ID from metadata server + */ + getProjectId(): Promise; + getProjectId(callback: ProjectIdCallback): void; + /** + * A temporary method for internal `getProjectId` usages where `null` is + * acceptable. In a future major release, `getProjectId` should return `null` + * (as the `Promise` base signature describes) and this private + * method should be removed. + * + * @returns Promise that resolves with project id (or `null`) + */ + private getProjectIdOptional; + /** + * A private method for finding and caching a projectId. + * + * Supports environments in order of precedence: + * - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable + * - GOOGLE_APPLICATION_CREDENTIALS JSON file + * - Cloud SDK: `gcloud config config-helper --format json` + * - GCE project ID from metadata server + * + * @returns projectId + */ + private findAndCacheProjectId; + private getProjectIdAsync; + /** + * Retrieves a universe domain from the metadata server via + * {@link gcpMetadata.universe}. + * + * @returns a universe domain + */ + getUniverseDomainFromMetadataServer(): Promise; + /** + * Retrieves, caches, and returns the universe domain in the following order + * of precedence: + * - The universe domain in {@link GoogleAuth.clientOptions} + * - An existing or ADC {@link AuthClient}'s universe domain + * - {@link gcpMetadata.universe}, if {@link Compute} client + * + * @returns The universe domain + */ + getUniverseDomain(): Promise; + /** + * @returns Any scopes (user-specified or default scopes specified by the + * client library) that need to be set on the current Auth client. + */ + private getAnyScopes; + /** + * Obtains the default service-level credentials for the application. + * @param callback Optional callback. + * @returns Promise that resolves with the ADCResponse (if no callback was + * passed). + */ + getApplicationDefault(): Promise; + getApplicationDefault(callback: ADCCallback): void; + getApplicationDefault(options: AuthClientOptions): Promise; + getApplicationDefault(options: AuthClientOptions, callback: ADCCallback): void; + private getApplicationDefaultAsync; + /** + * Determines whether the auth layer is running on Google Compute Engine. + * Checks for GCP Residency, then fallback to checking if metadata server + * is available. + * + * @returns A promise that resolves with the boolean. + * @api private + */ + _checkIsGCE(): Promise; + /** + * Attempts to load default credentials from the environment variable path.. + * @returns Promise that resolves with the OAuth2Client or null. + * @api private + */ + _tryGetApplicationCredentialsFromEnvironmentVariable(options?: AuthClientOptions): Promise; + /** + * Attempts to load default credentials from a well-known file location + * @return Promise that resolves with the OAuth2Client or null. + * @api private + */ + _tryGetApplicationCredentialsFromWellKnownFile(options?: AuthClientOptions): Promise; + /** + * Attempts to load default credentials from a file at the given path.. + * @param filePath The path to the file to read. + * @returns Promise that resolves with the OAuth2Client + * @api private + */ + _getApplicationCredentialsFromFilePath(filePath: string, options?: AuthClientOptions): Promise; + /** + * Create a credentials instance using a given impersonated input options. + * @param json The impersonated input object. + * @returns JWT or UserRefresh Client with data + */ + fromImpersonatedJSON(json: ImpersonatedJWTInput): Impersonated; + /** + * Create a credentials instance using the given input options. + * This client is not cached. + * + * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}. + * + * @param json The input object. + * @param options The JWT or UserRefresh options for the client + * @returns JWT or UserRefresh Client with data + */ + fromJSON(json: JWTInput | ImpersonatedJWTInput, options?: AuthClientOptions): JSONClient; + /** + * Return a JWT or UserRefreshClient from JavaScript object, caching both the + * object used to instantiate and the client. + * @param json The input object. + * @param options The JWT or UserRefresh options for the client + * @returns JWT or UserRefresh Client with data + */ + private _cacheClientFromJSON; + /** + * Create a credentials instance using the given input stream. + * @param inputStream The input stream. + * @param callback Optional callback. + */ + fromStream(inputStream: stream.Readable): Promise; + fromStream(inputStream: stream.Readable, callback: CredentialCallback): void; + fromStream(inputStream: stream.Readable, options: AuthClientOptions): Promise; + fromStream(inputStream: stream.Readable, options: AuthClientOptions, callback: CredentialCallback): void; + private fromStreamAsync; + /** + * Create a credentials instance using the given API key string. + * The created client is not cached. In order to create and cache it use the {@link GoogleAuth.getClient `getClient`} method after first providing an {@link GoogleAuth.apiKey `apiKey`}. + * + * @param apiKey The API key string + * @param options An optional options object. + * @returns A JWT loaded from the key + */ + fromAPIKey(apiKey: string, options?: AuthClientOptions): JWT; + /** + * Determines whether the current operating system is Windows. + * @api private + */ + private _isWindows; + /** + * Run the Google Cloud SDK command that prints the default project ID + */ + private getDefaultServiceProjectId; + /** + * Loads the project id from environment variables. + * @api private + */ + private getProductionProjectId; + /** + * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file. + * @api private + */ + private getFileProjectId; + /** + * Gets the project ID from external account client if available. + */ + private getExternalAccountClientProjectId; + /** + * Gets the Compute Engine project ID if it can be inferred. + */ + private getGCEProjectId; + /** + * The callback function handles a credential object that contains the + * client_email and private_key (if exists). + * getCredentials first checks if the client is using an external account and + * uses the service account email in place of client_email. + * If that doesn't exist, it checks for these values from the user JSON. + * If the user JSON doesn't exist, and the environment is on GCE, it gets the + * client_email from the cloud metadata server. + * @param callback Callback that handles the credential object that contains + * a client_email and optional private key, or the error. + * returned + */ + getCredentials(): Promise; + getCredentials(callback: (err: Error | null, credentials?: CredentialBody) => void): void; + private getCredentialsAsync; + /** + * Automatically obtain an {@link AuthClient `AuthClient`} based on the + * provided configuration. If no options were passed, use Application + * Default Credentials. + */ + getClient(): Promise; + /** + * Creates a client which will fetch an ID token for authorization. + * @param targetAudience the audience for the fetched ID token. + * @returns IdTokenClient for making HTTP calls authenticated with ID tokens. + */ + getIdTokenClient(targetAudience: string): Promise; + /** + * Automatically obtain application default credentials, and return + * an access token for making requests. + */ + getAccessToken(): Promise; + /** + * Obtain the HTTP headers that will provide authorization for a given + * request. + */ + getRequestHeaders(url?: string): Promise; + /** + * Obtain credentials for a request, then attach the appropriate headers to + * the request options. + * @param opts Axios or Request options on which to attach the headers + */ + authorizeRequest(opts: { + url?: string; + uri?: string; + headers?: Headers; + }): Promise<{ + url?: string; + uri?: string; + headers?: Headers; + }>; + /** + * Automatically obtain application default credentials, and make an + * HTTP request using the given options. + * @param opts Axios request options for the HTTP request. + */ + request(opts: GaxiosOptions): Promise>; + /** + * Determine the compute environment in which the code is running. + */ + getEnv(): Promise; + /** + * Sign the given data with the current private key, or go out + * to the IAM API to sign it. + * @param data The data to be signed. + * @param endpoint A custom endpoint to use. + * + * @example + * ``` + * sign('data', 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/'); + * ``` + */ + sign(data: string, endpoint?: string): Promise; + private signBlob; +} +export interface SignBlobResponse { + keyId: string; + signedBlob: string; +} diff --git a/node_modules/google-auth-library/build/src/auth/googleauth.js b/node_modules/google-auth-library/build/src/auth/googleauth.js new file mode 100644 index 0000000..1f68a8d --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/googleauth.js @@ -0,0 +1,841 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var _GoogleAuth_instances, _GoogleAuth_pendingAuthClient, _GoogleAuth_prepareAndCacheClient, _GoogleAuth_determineClient; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GoogleAuth = exports.GoogleAuthExceptionMessages = exports.CLOUD_SDK_CLIENT_ID = void 0; +const child_process_1 = require("child_process"); +const fs = require("fs"); +const gcpMetadata = require("gcp-metadata"); +const os = require("os"); +const path = require("path"); +const crypto_1 = require("../crypto/crypto"); +const transporters_1 = require("../transporters"); +const computeclient_1 = require("./computeclient"); +const idtokenclient_1 = require("./idtokenclient"); +const envDetect_1 = require("./envDetect"); +const jwtclient_1 = require("./jwtclient"); +const refreshclient_1 = require("./refreshclient"); +const impersonated_1 = require("./impersonated"); +const externalclient_1 = require("./externalclient"); +const baseexternalclient_1 = require("./baseexternalclient"); +const authclient_1 = require("./authclient"); +const externalAccountAuthorizedUserClient_1 = require("./externalAccountAuthorizedUserClient"); +const util_1 = require("../util"); +exports.CLOUD_SDK_CLIENT_ID = '764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com'; +exports.GoogleAuthExceptionMessages = { + API_KEY_WITH_CREDENTIALS: 'API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.', + NO_PROJECT_ID_FOUND: 'Unable to detect a Project Id in the current environment. \n' + + 'To learn more about authentication and Google APIs, visit: \n' + + 'https://cloud.google.com/docs/authentication/getting-started', + NO_CREDENTIALS_FOUND: 'Unable to find credentials in current environment. \n' + + 'To learn more about authentication and Google APIs, visit: \n' + + 'https://cloud.google.com/docs/authentication/getting-started', + NO_ADC_FOUND: 'Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.', + NO_UNIVERSE_DOMAIN_FOUND: 'Unable to detect a Universe Domain in the current environment.\n' + + 'To learn more about Universe Domain retrieval, visit: \n' + + 'https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys', +}; +class GoogleAuth { + // Note: this properly is only public to satisfy unit tests. + // https://github.com/Microsoft/TypeScript/issues/5228 + get isGCE() { + return this.checkIsGCE; + } + /** + * Configuration is resolved in the following order of precedence: + * - {@link GoogleAuthOptions.credentials `credentials`} + * - {@link GoogleAuthOptions.keyFilename `keyFilename`} + * - {@link GoogleAuthOptions.keyFile `keyFile`} + * + * {@link GoogleAuthOptions.clientOptions `clientOptions`} are passed to the + * {@link AuthClient `AuthClient`s}. + * + * @param opts + */ + constructor(opts = {}) { + _GoogleAuth_instances.add(this); + /** + * Caches a value indicating whether the auth layer is running on Google + * Compute Engine. + * @private + */ + this.checkIsGCE = undefined; + // To save the contents of the JSON credential file + this.jsonContent = null; + this.cachedCredential = null; + /** + * A pending {@link AuthClient}. Used for concurrent {@link GoogleAuth.getClient} calls. + */ + _GoogleAuth_pendingAuthClient.set(this, null); + this.clientOptions = {}; + this._cachedProjectId = opts.projectId || null; + this.cachedCredential = opts.authClient || null; + this.keyFilename = opts.keyFilename || opts.keyFile; + this.scopes = opts.scopes; + this.clientOptions = opts.clientOptions || {}; + this.jsonContent = opts.credentials || null; + this.apiKey = opts.apiKey || this.clientOptions.apiKey || null; + // Cannot use both API Key + Credentials + if (this.apiKey && (this.jsonContent || this.clientOptions.credentials)) { + throw new RangeError(exports.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS); + } + if (opts.universeDomain) { + this.clientOptions.universeDomain = opts.universeDomain; + } + } + // GAPIC client libraries should always use self-signed JWTs. The following + // variables are set on the JWT client in order to indicate the type of library, + // and sign the JWT with the correct audience and scopes (if not supplied). + setGapicJWTValues(client) { + client.defaultServicePath = this.defaultServicePath; + client.useJWTAccessWithScope = this.useJWTAccessWithScope; + client.defaultScopes = this.defaultScopes; + } + getProjectId(callback) { + if (callback) { + this.getProjectIdAsync().then(r => callback(null, r), callback); + } + else { + return this.getProjectIdAsync(); + } + } + /** + * A temporary method for internal `getProjectId` usages where `null` is + * acceptable. In a future major release, `getProjectId` should return `null` + * (as the `Promise` base signature describes) and this private + * method should be removed. + * + * @returns Promise that resolves with project id (or `null`) + */ + async getProjectIdOptional() { + try { + return await this.getProjectId(); + } + catch (e) { + if (e instanceof Error && + e.message === exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND) { + return null; + } + else { + throw e; + } + } + } + /** + * A private method for finding and caching a projectId. + * + * Supports environments in order of precedence: + * - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable + * - GOOGLE_APPLICATION_CREDENTIALS JSON file + * - Cloud SDK: `gcloud config config-helper --format json` + * - GCE project ID from metadata server + * + * @returns projectId + */ + async findAndCacheProjectId() { + let projectId = null; + projectId || (projectId = await this.getProductionProjectId()); + projectId || (projectId = await this.getFileProjectId()); + projectId || (projectId = await this.getDefaultServiceProjectId()); + projectId || (projectId = await this.getGCEProjectId()); + projectId || (projectId = await this.getExternalAccountClientProjectId()); + if (projectId) { + this._cachedProjectId = projectId; + return projectId; + } + else { + throw new Error(exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND); + } + } + async getProjectIdAsync() { + if (this._cachedProjectId) { + return this._cachedProjectId; + } + if (!this._findProjectIdPromise) { + this._findProjectIdPromise = this.findAndCacheProjectId(); + } + return this._findProjectIdPromise; + } + /** + * Retrieves a universe domain from the metadata server via + * {@link gcpMetadata.universe}. + * + * @returns a universe domain + */ + async getUniverseDomainFromMetadataServer() { + var _a; + let universeDomain; + try { + universeDomain = await gcpMetadata.universe('universe-domain'); + universeDomain || (universeDomain = authclient_1.DEFAULT_UNIVERSE); + } + catch (e) { + if (e && ((_a = e === null || e === void 0 ? void 0 : e.response) === null || _a === void 0 ? void 0 : _a.status) === 404) { + universeDomain = authclient_1.DEFAULT_UNIVERSE; + } + else { + throw e; + } + } + return universeDomain; + } + /** + * Retrieves, caches, and returns the universe domain in the following order + * of precedence: + * - The universe domain in {@link GoogleAuth.clientOptions} + * - An existing or ADC {@link AuthClient}'s universe domain + * - {@link gcpMetadata.universe}, if {@link Compute} client + * + * @returns The universe domain + */ + async getUniverseDomain() { + let universeDomain = (0, util_1.originalOrCamelOptions)(this.clientOptions).get('universe_domain'); + try { + universeDomain !== null && universeDomain !== void 0 ? universeDomain : (universeDomain = (await this.getClient()).universeDomain); + } + catch (_a) { + // client or ADC is not available + universeDomain !== null && universeDomain !== void 0 ? universeDomain : (universeDomain = authclient_1.DEFAULT_UNIVERSE); + } + return universeDomain; + } + /** + * @returns Any scopes (user-specified or default scopes specified by the + * client library) that need to be set on the current Auth client. + */ + getAnyScopes() { + return this.scopes || this.defaultScopes; + } + getApplicationDefault(optionsOrCallback = {}, callback) { + let options; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else { + options = optionsOrCallback; + } + if (callback) { + this.getApplicationDefaultAsync(options).then(r => callback(null, r.credential, r.projectId), callback); + } + else { + return this.getApplicationDefaultAsync(options); + } + } + async getApplicationDefaultAsync(options = {}) { + // If we've already got a cached credential, return it. + // This will also preserve one's configured quota project, in case they + // set one directly on the credential previously. + if (this.cachedCredential) { + // cache, while preserving existing quota project preferences + return await __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, this.cachedCredential, null); + } + let credential; + // Check for the existence of a local environment variable pointing to the + // location of the credential file. This is typically used in local + // developer scenarios. + credential = + await this._tryGetApplicationCredentialsFromEnvironmentVariable(options); + if (credential) { + if (credential instanceof jwtclient_1.JWT) { + credential.scopes = this.scopes; + } + else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) { + credential.scopes = this.getAnyScopes(); + } + return await __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, credential); + } + // Look in the well-known credential file location. + credential = + await this._tryGetApplicationCredentialsFromWellKnownFile(options); + if (credential) { + if (credential instanceof jwtclient_1.JWT) { + credential.scopes = this.scopes; + } + else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) { + credential.scopes = this.getAnyScopes(); + } + return await __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, credential); + } + // Determine if we're running on GCE. + if (await this._checkIsGCE()) { + options.scopes = this.getAnyScopes(); + return await __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, new computeclient_1.Compute(options)); + } + throw new Error(exports.GoogleAuthExceptionMessages.NO_ADC_FOUND); + } + /** + * Determines whether the auth layer is running on Google Compute Engine. + * Checks for GCP Residency, then fallback to checking if metadata server + * is available. + * + * @returns A promise that resolves with the boolean. + * @api private + */ + async _checkIsGCE() { + if (this.checkIsGCE === undefined) { + this.checkIsGCE = + gcpMetadata.getGCPResidency() || (await gcpMetadata.isAvailable()); + } + return this.checkIsGCE; + } + /** + * Attempts to load default credentials from the environment variable path.. + * @returns Promise that resolves with the OAuth2Client or null. + * @api private + */ + async _tryGetApplicationCredentialsFromEnvironmentVariable(options) { + const credentialsPath = process.env['GOOGLE_APPLICATION_CREDENTIALS'] || + process.env['google_application_credentials']; + if (!credentialsPath || credentialsPath.length === 0) { + return null; + } + try { + return this._getApplicationCredentialsFromFilePath(credentialsPath, options); + } + catch (e) { + if (e instanceof Error) { + e.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e.message}`; + } + throw e; + } + } + /** + * Attempts to load default credentials from a well-known file location + * @return Promise that resolves with the OAuth2Client or null. + * @api private + */ + async _tryGetApplicationCredentialsFromWellKnownFile(options) { + // First, figure out the location of the file, depending upon the OS type. + let location = null; + if (this._isWindows()) { + // Windows + location = process.env['APPDATA']; + } + else { + // Linux or Mac + const home = process.env['HOME']; + if (home) { + location = path.join(home, '.config'); + } + } + // If we found the root path, expand it. + if (location) { + location = path.join(location, 'gcloud', 'application_default_credentials.json'); + if (!fs.existsSync(location)) { + location = null; + } + } + // The file does not exist. + if (!location) { + return null; + } + // The file seems to exist. Try to use it. + const client = await this._getApplicationCredentialsFromFilePath(location, options); + return client; + } + /** + * Attempts to load default credentials from a file at the given path.. + * @param filePath The path to the file to read. + * @returns Promise that resolves with the OAuth2Client + * @api private + */ + async _getApplicationCredentialsFromFilePath(filePath, options = {}) { + // Make sure the path looks like a string. + if (!filePath || filePath.length === 0) { + throw new Error('The file path is invalid.'); + } + // Make sure there is a file at the path. lstatSync will throw if there is + // nothing there. + try { + // Resolve path to actual file in case of symlink. Expect a thrown error + // if not resolvable. + filePath = fs.realpathSync(filePath); + if (!fs.lstatSync(filePath).isFile()) { + throw new Error(); + } + } + catch (err) { + if (err instanceof Error) { + err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`; + } + throw err; + } + // Now open a read stream on the file, and parse it. + const readStream = fs.createReadStream(filePath); + return this.fromStream(readStream, options); + } + /** + * Create a credentials instance using a given impersonated input options. + * @param json The impersonated input object. + * @returns JWT or UserRefresh Client with data + */ + fromImpersonatedJSON(json) { + var _a, _b, _c, _d; + if (!json) { + throw new Error('Must pass in a JSON object containing an impersonated refresh token'); + } + if (json.type !== impersonated_1.IMPERSONATED_ACCOUNT_TYPE) { + throw new Error(`The incoming JSON object does not have the "${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}" type`); + } + if (!json.source_credentials) { + throw new Error('The incoming JSON object does not contain a source_credentials field'); + } + if (!json.service_account_impersonation_url) { + throw new Error('The incoming JSON object does not contain a service_account_impersonation_url field'); + } + const sourceClient = this.fromJSON(json.source_credentials); + if (((_a = json.service_account_impersonation_url) === null || _a === void 0 ? void 0 : _a.length) > 256) { + /** + * Prevents DOS attacks. + * @see {@link https://github.com/googleapis/google-auth-library-nodejs/security/code-scanning/85} + **/ + throw new RangeError(`Target principal is too long: ${json.service_account_impersonation_url}`); + } + // Extract service account from service_account_impersonation_url + const targetPrincipal = (_c = (_b = /(?[^/]+):(generateAccessToken|generateIdToken)$/.exec(json.service_account_impersonation_url)) === null || _b === void 0 ? void 0 : _b.groups) === null || _c === void 0 ? void 0 : _c.target; + if (!targetPrincipal) { + throw new RangeError(`Cannot extract target principal from ${json.service_account_impersonation_url}`); + } + const targetScopes = (_d = this.getAnyScopes()) !== null && _d !== void 0 ? _d : []; + return new impersonated_1.Impersonated({ + ...json, + sourceClient, + targetPrincipal, + targetScopes: Array.isArray(targetScopes) ? targetScopes : [targetScopes], + }); + } + /** + * Create a credentials instance using the given input options. + * This client is not cached. + * + * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}. + * + * @param json The input object. + * @param options The JWT or UserRefresh options for the client + * @returns JWT or UserRefresh Client with data + */ + fromJSON(json, options = {}) { + let client; + // user's preferred universe domain + const preferredUniverseDomain = (0, util_1.originalOrCamelOptions)(options).get('universe_domain'); + if (json.type === refreshclient_1.USER_REFRESH_ACCOUNT_TYPE) { + client = new refreshclient_1.UserRefreshClient(options); + client.fromJSON(json); + } + else if (json.type === impersonated_1.IMPERSONATED_ACCOUNT_TYPE) { + client = this.fromImpersonatedJSON(json); + } + else if (json.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { + client = externalclient_1.ExternalAccountClient.fromJSON(json, options); + client.scopes = this.getAnyScopes(); + } + else if (json.type === externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE) { + client = new externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient(json, options); + } + else { + options.scopes = this.scopes; + client = new jwtclient_1.JWT(options); + this.setGapicJWTValues(client); + client.fromJSON(json); + } + if (preferredUniverseDomain) { + client.universeDomain = preferredUniverseDomain; + } + return client; + } + /** + * Return a JWT or UserRefreshClient from JavaScript object, caching both the + * object used to instantiate and the client. + * @param json The input object. + * @param options The JWT or UserRefresh options for the client + * @returns JWT or UserRefresh Client with data + */ + _cacheClientFromJSON(json, options) { + const client = this.fromJSON(json, options); + // cache both raw data used to instantiate client and client itself. + this.jsonContent = json; + this.cachedCredential = client; + return client; + } + fromStream(inputStream, optionsOrCallback = {}, callback) { + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else { + options = optionsOrCallback; + } + if (callback) { + this.fromStreamAsync(inputStream, options).then(r => callback(null, r), callback); + } + else { + return this.fromStreamAsync(inputStream, options); + } + } + fromStreamAsync(inputStream, options) { + return new Promise((resolve, reject) => { + if (!inputStream) { + throw new Error('Must pass in a stream containing the Google auth settings.'); + } + const chunks = []; + inputStream + .setEncoding('utf8') + .on('error', reject) + .on('data', chunk => chunks.push(chunk)) + .on('end', () => { + try { + try { + const data = JSON.parse(chunks.join('')); + const r = this._cacheClientFromJSON(data, options); + return resolve(r); + } + catch (err) { + // If we failed parsing this.keyFileName, assume that it + // is a PEM or p12 certificate: + if (!this.keyFilename) + throw err; + const client = new jwtclient_1.JWT({ + ...this.clientOptions, + keyFile: this.keyFilename, + }); + this.cachedCredential = client; + this.setGapicJWTValues(client); + return resolve(client); + } + } + catch (err) { + return reject(err); + } + }); + }); + } + /** + * Create a credentials instance using the given API key string. + * The created client is not cached. In order to create and cache it use the {@link GoogleAuth.getClient `getClient`} method after first providing an {@link GoogleAuth.apiKey `apiKey`}. + * + * @param apiKey The API key string + * @param options An optional options object. + * @returns A JWT loaded from the key + */ + fromAPIKey(apiKey, options = {}) { + return new jwtclient_1.JWT({ ...options, apiKey }); + } + /** + * Determines whether the current operating system is Windows. + * @api private + */ + _isWindows() { + const sys = os.platform(); + if (sys && sys.length >= 3) { + if (sys.substring(0, 3).toLowerCase() === 'win') { + return true; + } + } + return false; + } + /** + * Run the Google Cloud SDK command that prints the default project ID + */ + async getDefaultServiceProjectId() { + return new Promise(resolve => { + (0, child_process_1.exec)('gcloud config config-helper --format json', (err, stdout) => { + if (!err && stdout) { + try { + const projectId = JSON.parse(stdout).configuration.properties.core.project; + resolve(projectId); + return; + } + catch (e) { + // ignore errors + } + } + resolve(null); + }); + }); + } + /** + * Loads the project id from environment variables. + * @api private + */ + getProductionProjectId() { + return (process.env['GCLOUD_PROJECT'] || + process.env['GOOGLE_CLOUD_PROJECT'] || + process.env['gcloud_project'] || + process.env['google_cloud_project']); + } + /** + * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file. + * @api private + */ + async getFileProjectId() { + if (this.cachedCredential) { + // Try to read the project ID from the cached credentials file + return this.cachedCredential.projectId; + } + // Ensure the projectId is loaded from the keyFile if available. + if (this.keyFilename) { + const creds = await this.getClient(); + if (creds && creds.projectId) { + return creds.projectId; + } + } + // Try to load a credentials file and read its project ID + const r = await this._tryGetApplicationCredentialsFromEnvironmentVariable(); + if (r) { + return r.projectId; + } + else { + return null; + } + } + /** + * Gets the project ID from external account client if available. + */ + async getExternalAccountClientProjectId() { + if (!this.jsonContent || this.jsonContent.type !== baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { + return null; + } + const creds = await this.getClient(); + // Do not suppress the underlying error, as the error could contain helpful + // information for debugging and fixing. This is especially true for + // external account creds as in order to get the project ID, the following + // operations have to succeed: + // 1. Valid credentials file should be supplied. + // 2. Ability to retrieve access tokens from STS token exchange API. + // 3. Ability to exchange for service account impersonated credentials (if + // enabled). + // 4. Ability to get project info using the access token from step 2 or 3. + // Without surfacing the error, it is harder for developers to determine + // which step went wrong. + return await creds.getProjectId(); + } + /** + * Gets the Compute Engine project ID if it can be inferred. + */ + async getGCEProjectId() { + try { + const r = await gcpMetadata.project('project-id'); + return r; + } + catch (e) { + // Ignore any errors + return null; + } + } + getCredentials(callback) { + if (callback) { + this.getCredentialsAsync().then(r => callback(null, r), callback); + } + else { + return this.getCredentialsAsync(); + } + } + async getCredentialsAsync() { + const client = await this.getClient(); + if (client instanceof impersonated_1.Impersonated) { + return { client_email: client.getTargetPrincipal() }; + } + if (client instanceof baseexternalclient_1.BaseExternalAccountClient) { + const serviceAccountEmail = client.getServiceAccountEmail(); + if (serviceAccountEmail) { + return { + client_email: serviceAccountEmail, + universe_domain: client.universeDomain, + }; + } + } + if (this.jsonContent) { + return { + client_email: this.jsonContent.client_email, + private_key: this.jsonContent.private_key, + universe_domain: this.jsonContent.universe_domain, + }; + } + if (await this._checkIsGCE()) { + const [client_email, universe_domain] = await Promise.all([ + gcpMetadata.instance('service-accounts/default/email'), + this.getUniverseDomain(), + ]); + return { client_email, universe_domain }; + } + throw new Error(exports.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND); + } + /** + * Automatically obtain an {@link AuthClient `AuthClient`} based on the + * provided configuration. If no options were passed, use Application + * Default Credentials. + */ + async getClient() { + if (this.cachedCredential) { + return this.cachedCredential; + } + // Use an existing auth client request, or cache a new one + __classPrivateFieldSet(this, _GoogleAuth_pendingAuthClient, __classPrivateFieldGet(this, _GoogleAuth_pendingAuthClient, "f") || __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_determineClient).call(this), "f"); + try { + return await __classPrivateFieldGet(this, _GoogleAuth_pendingAuthClient, "f"); + } + finally { + // reset the pending auth client in case it is changed later + __classPrivateFieldSet(this, _GoogleAuth_pendingAuthClient, null, "f"); + } + } + /** + * Creates a client which will fetch an ID token for authorization. + * @param targetAudience the audience for the fetched ID token. + * @returns IdTokenClient for making HTTP calls authenticated with ID tokens. + */ + async getIdTokenClient(targetAudience) { + const client = await this.getClient(); + if (!('fetchIdToken' in client)) { + throw new Error('Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.'); + } + return new idtokenclient_1.IdTokenClient({ targetAudience, idTokenProvider: client }); + } + /** + * Automatically obtain application default credentials, and return + * an access token for making requests. + */ + async getAccessToken() { + const client = await this.getClient(); + return (await client.getAccessToken()).token; + } + /** + * Obtain the HTTP headers that will provide authorization for a given + * request. + */ + async getRequestHeaders(url) { + const client = await this.getClient(); + return client.getRequestHeaders(url); + } + /** + * Obtain credentials for a request, then attach the appropriate headers to + * the request options. + * @param opts Axios or Request options on which to attach the headers + */ + async authorizeRequest(opts) { + opts = opts || {}; + const url = opts.url || opts.uri; + const client = await this.getClient(); + const headers = await client.getRequestHeaders(url); + opts.headers = Object.assign(opts.headers || {}, headers); + return opts; + } + /** + * Automatically obtain application default credentials, and make an + * HTTP request using the given options. + * @param opts Axios request options for the HTTP request. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async request(opts) { + const client = await this.getClient(); + return client.request(opts); + } + /** + * Determine the compute environment in which the code is running. + */ + getEnv() { + return (0, envDetect_1.getEnv)(); + } + /** + * Sign the given data with the current private key, or go out + * to the IAM API to sign it. + * @param data The data to be signed. + * @param endpoint A custom endpoint to use. + * + * @example + * ``` + * sign('data', 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/'); + * ``` + */ + async sign(data, endpoint) { + const client = await this.getClient(); + const universe = await this.getUniverseDomain(); + endpoint = + endpoint || + `https://iamcredentials.${universe}/v1/projects/-/serviceAccounts/`; + if (client instanceof impersonated_1.Impersonated) { + const signed = await client.sign(data); + return signed.signedBlob; + } + const crypto = (0, crypto_1.createCrypto)(); + if (client instanceof jwtclient_1.JWT && client.key) { + const sign = await crypto.sign(client.key, data); + return sign; + } + const creds = await this.getCredentials(); + if (!creds.client_email) { + throw new Error('Cannot sign data without `client_email`.'); + } + return this.signBlob(crypto, creds.client_email, data, endpoint); + } + async signBlob(crypto, emailOrUniqueId, data, endpoint) { + const url = new URL(endpoint + `${emailOrUniqueId}:signBlob`); + const res = await this.request({ + method: 'POST', + url: url.href, + data: { + payload: crypto.encodeBase64StringUtf8(data), + }, + retry: true, + retryConfig: { + httpMethodsToRetry: ['POST'], + }, + }); + return res.data.signedBlob; + } +} +exports.GoogleAuth = GoogleAuth; +_GoogleAuth_pendingAuthClient = new WeakMap(), _GoogleAuth_instances = new WeakSet(), _GoogleAuth_prepareAndCacheClient = async function _GoogleAuth_prepareAndCacheClient(credential, quotaProjectIdOverride = process.env['GOOGLE_CLOUD_QUOTA_PROJECT'] || null) { + const projectId = await this.getProjectIdOptional(); + if (quotaProjectIdOverride) { + credential.quotaProjectId = quotaProjectIdOverride; + } + this.cachedCredential = credential; + return { credential, projectId }; +}, _GoogleAuth_determineClient = async function _GoogleAuth_determineClient() { + if (this.jsonContent) { + return this._cacheClientFromJSON(this.jsonContent, this.clientOptions); + } + else if (this.keyFilename) { + const filePath = path.resolve(this.keyFilename); + const stream = fs.createReadStream(filePath); + return await this.fromStreamAsync(stream, this.clientOptions); + } + else if (this.apiKey) { + const client = await this.fromAPIKey(this.apiKey, this.clientOptions); + client.scopes = this.scopes; + const { credential } = await __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, client); + return credential; + } + else { + const { credential } = await this.getApplicationDefaultAsync(this.clientOptions); + return credential; + } +}; +/** + * Export DefaultTransporter as a static property of the class. + */ +GoogleAuth.DefaultTransporter = transporters_1.DefaultTransporter; diff --git a/node_modules/google-auth-library/build/src/auth/iam.d.ts b/node_modules/google-auth-library/build/src/auth/iam.d.ts new file mode 100644 index 0000000..93470a4 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/iam.d.ts @@ -0,0 +1,23 @@ +export interface RequestMetadata { + 'x-goog-iam-authority-selector': string; + 'x-goog-iam-authorization-token': string; +} +export declare class IAMAuth { + selector: string; + token: string; + /** + * IAM credentials. + * + * @param selector the iam authority selector + * @param token the token + * @constructor + */ + constructor(selector: string, token: string); + /** + * Acquire the HTTP headers required to make an authenticated request. + */ + getRequestHeaders(): { + 'x-goog-iam-authority-selector': string; + 'x-goog-iam-authorization-token': string; + }; +} diff --git a/node_modules/google-auth-library/build/src/auth/iam.js b/node_modules/google-auth-library/build/src/auth/iam.js new file mode 100644 index 0000000..e837114 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/iam.js @@ -0,0 +1,41 @@ +"use strict"; +// Copyright 2014 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IAMAuth = void 0; +class IAMAuth { + /** + * IAM credentials. + * + * @param selector the iam authority selector + * @param token the token + * @constructor + */ + constructor(selector, token) { + this.selector = selector; + this.token = token; + this.selector = selector; + this.token = token; + } + /** + * Acquire the HTTP headers required to make an authenticated request. + */ + getRequestHeaders() { + return { + 'x-goog-iam-authority-selector': this.selector, + 'x-goog-iam-authorization-token': this.token, + }; + } +} +exports.IAMAuth = IAMAuth; diff --git a/node_modules/google-auth-library/build/src/auth/identitypoolclient.d.ts b/node_modules/google-auth-library/build/src/auth/identitypoolclient.d.ts new file mode 100644 index 0000000..1b2e6c1 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/identitypoolclient.d.ts @@ -0,0 +1,102 @@ +import { BaseExternalAccountClient, BaseExternalAccountClientOptions, ExternalAccountSupplierContext } from './baseexternalclient'; +import { AuthClientOptions } from './authclient'; +import { SnakeToCamelObject } from '../util'; +export type SubjectTokenFormatType = 'json' | 'text'; +export interface SubjectTokenJsonResponse { + [key: string]: string; +} +/** + * Supplier interface for subject tokens. This can be implemented to + * return a subject token which can then be exchanged for a GCP token by an + * {@link IdentityPoolClient}. + */ +export interface SubjectTokenSupplier { + /** + * Gets a valid subject token for the requested external account identity. + * Note that these are not cached by the calling {@link IdentityPoolClient}, + * so caching should be including in the implementation. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link IdentityPoolClient}, contains the requested audience and subject token type + * for the external account identity as well as the transport from the + * calling client to use for requests. + * @return A promise that resolves with the requested subject token string. + */ + getSubjectToken: (context: ExternalAccountSupplierContext) => Promise; +} +/** + * Url-sourced/file-sourced credentials json interface. + * This is used for K8s and Azure workloads. + */ +export interface IdentityPoolClientOptions extends BaseExternalAccountClientOptions { + /** + * Object containing options to retrieve identity pool credentials. A valid credential + * source or a subject token supplier must be specified. + */ + credential_source?: { + /** + * The file location to read the subject token from. Either this or a URL + * should be specified. + */ + file?: string; + /** + * The URL to call to retrieve the subject token. Either this or a file + * location should be specified. + */ + url?: string; + /** + * Optional headers to send on the request to the specified URL. + */ + headers?: { + [key: string]: string; + }; + /** + * The format that the subject token is in the file or the URL response. + * If not provided, will default to reading the text string directly. + */ + format?: { + /** + * The format type. Can either be 'text' or 'json'. + */ + type: SubjectTokenFormatType; + /** + * The field name containing the subject token value if the type is 'json'. + */ + subject_token_field_name?: string; + }; + }; + /** + * The subject token supplier to call to retrieve the subject token to exchange + * for a GCP access token. Either this or a valid credential source should + * be specified. + */ + subject_token_supplier?: SubjectTokenSupplier; +} +/** + * Defines the Url-sourced and file-sourced external account clients mainly + * used for K8s and Azure workloads. + */ +export declare class IdentityPoolClient extends BaseExternalAccountClient { + private readonly subjectTokenSupplier; + /** + * Instantiate an IdentityPoolClient instance using the provided JSON + * object loaded from an external account credentials file. + * An error is thrown if the credential is not a valid file-sourced or + * url-sourced credential or a workforce pool user project is provided + * with a non workforce audience. + * @param options The external account options object typically loaded + * from the external account JSON credential file. The camelCased options + * are aliases for the snake_cased options. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options: IdentityPoolClientOptions | SnakeToCamelObject, additionalOptions?: AuthClientOptions); + /** + * Triggered when a external subject token is needed to be exchanged for a GCP + * access token via GCP STS endpoint. Gets a subject token by calling + * the configured {@link SubjectTokenSupplier} + * @return A promise that resolves with the external subject token. + */ + retrieveSubjectToken(): Promise; +} diff --git a/node_modules/google-auth-library/build/src/auth/identitypoolclient.js b/node_modules/google-auth-library/build/src/auth/identitypoolclient.js new file mode 100644 index 0000000..c2e2307 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/identitypoolclient.js @@ -0,0 +1,107 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IdentityPoolClient = void 0; +const baseexternalclient_1 = require("./baseexternalclient"); +const util_1 = require("../util"); +const filesubjecttokensupplier_1 = require("./filesubjecttokensupplier"); +const urlsubjecttokensupplier_1 = require("./urlsubjecttokensupplier"); +/** + * Defines the Url-sourced and file-sourced external account clients mainly + * used for K8s and Azure workloads. + */ +class IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient { + /** + * Instantiate an IdentityPoolClient instance using the provided JSON + * object loaded from an external account credentials file. + * An error is thrown if the credential is not a valid file-sourced or + * url-sourced credential or a workforce pool user project is provided + * with a non workforce audience. + * @param options The external account options object typically loaded + * from the external account JSON credential file. The camelCased options + * are aliases for the snake_cased options. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options, additionalOptions) { + super(options, additionalOptions); + const opts = (0, util_1.originalOrCamelOptions)(options); + const credentialSource = opts.get('credential_source'); + const subjectTokenSupplier = opts.get('subject_token_supplier'); + // Validate credential sourcing configuration. + if (!credentialSource && !subjectTokenSupplier) { + throw new Error('A credential source or subject token supplier must be specified.'); + } + if (credentialSource && subjectTokenSupplier) { + throw new Error('Only one of credential source or subject token supplier can be specified.'); + } + if (subjectTokenSupplier) { + this.subjectTokenSupplier = subjectTokenSupplier; + this.credentialSourceType = 'programmatic'; + } + else { + const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource); + const formatOpts = (0, util_1.originalOrCamelOptions)(credentialSourceOpts.get('format')); + // Text is the default format type. + const formatType = formatOpts.get('type') || 'text'; + const formatSubjectTokenFieldName = formatOpts.get('subject_token_field_name'); + if (formatType !== 'json' && formatType !== 'text') { + throw new Error(`Invalid credential_source format "${formatType}"`); + } + if (formatType === 'json' && !formatSubjectTokenFieldName) { + throw new Error('Missing subject_token_field_name for JSON credential_source format'); + } + const file = credentialSourceOpts.get('file'); + const url = credentialSourceOpts.get('url'); + const headers = credentialSourceOpts.get('headers'); + if (file && url) { + throw new Error('No valid Identity Pool "credential_source" provided, must be either file or url.'); + } + else if (file && !url) { + this.credentialSourceType = 'file'; + this.subjectTokenSupplier = new filesubjecttokensupplier_1.FileSubjectTokenSupplier({ + filePath: file, + formatType: formatType, + subjectTokenFieldName: formatSubjectTokenFieldName, + }); + } + else if (!file && url) { + this.credentialSourceType = 'url'; + this.subjectTokenSupplier = new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({ + url: url, + formatType: formatType, + subjectTokenFieldName: formatSubjectTokenFieldName, + headers: headers, + additionalGaxiosOptions: IdentityPoolClient.RETRY_CONFIG, + }); + } + else { + throw new Error('No valid Identity Pool "credential_source" provided, must be either file or url.'); + } + } + } + /** + * Triggered when a external subject token is needed to be exchanged for a GCP + * access token via GCP STS endpoint. Gets a subject token by calling + * the configured {@link SubjectTokenSupplier} + * @return A promise that resolves with the external subject token. + */ + async retrieveSubjectToken() { + return this.subjectTokenSupplier.getSubjectToken(this.supplierContext); + } +} +exports.IdentityPoolClient = IdentityPoolClient; diff --git a/node_modules/google-auth-library/build/src/auth/idtokenclient.d.ts b/node_modules/google-auth-library/build/src/auth/idtokenclient.d.ts new file mode 100644 index 0000000..311d29d --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/idtokenclient.d.ts @@ -0,0 +1,27 @@ +import { OAuth2Client, OAuth2ClientOptions, RequestMetadataResponse } from './oauth2client'; +export interface IdTokenOptions extends OAuth2ClientOptions { + /** + * The client to make the request to fetch an ID token. + */ + idTokenProvider: IdTokenProvider; + /** + * The audience to use when requesting an ID token. + */ + targetAudience: string; +} +export interface IdTokenProvider { + fetchIdToken: (targetAudience: string) => Promise; +} +export declare class IdTokenClient extends OAuth2Client { + targetAudience: string; + idTokenProvider: IdTokenProvider; + /** + * Google ID Token client + * + * Retrieve ID token from the metadata server. + * See: https://cloud.google.com/docs/authentication/get-id-token#metadata-server + */ + constructor(options: IdTokenOptions); + protected getRequestMetadataAsync(url?: string | null): Promise; + private getIdTokenExpiryDate; +} diff --git a/node_modules/google-auth-library/build/src/auth/idtokenclient.js b/node_modules/google-auth-library/build/src/auth/idtokenclient.js new file mode 100644 index 0000000..77e6fa3 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/idtokenclient.js @@ -0,0 +1,55 @@ +"use strict"; +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IdTokenClient = void 0; +const oauth2client_1 = require("./oauth2client"); +class IdTokenClient extends oauth2client_1.OAuth2Client { + /** + * Google ID Token client + * + * Retrieve ID token from the metadata server. + * See: https://cloud.google.com/docs/authentication/get-id-token#metadata-server + */ + constructor(options) { + super(options); + this.targetAudience = options.targetAudience; + this.idTokenProvider = options.idTokenProvider; + } + async getRequestMetadataAsync( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + url) { + if (!this.credentials.id_token || + !this.credentials.expiry_date || + this.isTokenExpiring()) { + const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience); + this.credentials = { + id_token: idToken, + expiry_date: this.getIdTokenExpiryDate(idToken), + }; + } + const headers = { + Authorization: 'Bearer ' + this.credentials.id_token, + }; + return { headers }; + } + getIdTokenExpiryDate(idToken) { + const payloadB64 = idToken.split('.')[1]; + if (payloadB64) { + const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('ascii')); + return payload.exp * 1000; + } + } +} +exports.IdTokenClient = IdTokenClient; diff --git a/node_modules/google-auth-library/build/src/auth/impersonated.d.ts b/node_modules/google-auth-library/build/src/auth/impersonated.d.ts new file mode 100644 index 0000000..fed007d --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/impersonated.d.ts @@ -0,0 +1,127 @@ +/** + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { GetTokenResponse, OAuth2Client, OAuth2ClientOptions } from './oauth2client'; +import { AuthClient } from './authclient'; +import { IdTokenProvider } from './idtokenclient'; +import { SignBlobResponse } from './googleauth'; +export interface ImpersonatedOptions extends OAuth2ClientOptions { + /** + * Client used to perform exchange for impersonated client. + */ + sourceClient?: AuthClient; + /** + * The service account to impersonate. + */ + targetPrincipal?: string; + /** + * Scopes to request during the authorization grant. + */ + targetScopes?: string[]; + /** + * The chained list of delegates required to grant the final access_token. + */ + delegates?: string[]; + /** + * Number of seconds the delegated credential should be valid. + */ + lifetime?: number | 3600; + /** + * API endpoint to fetch token from. + */ + endpoint?: string; +} +export declare const IMPERSONATED_ACCOUNT_TYPE = "impersonated_service_account"; +export interface TokenResponse { + accessToken: string; + expireTime: string; +} +export interface FetchIdTokenOptions { + /** + * Include the service account email in the token. + * If set to `true`, the token will contain `email` and `email_verified` claims. + */ + includeEmail: boolean; +} +export interface FetchIdTokenResponse { + /** The OpenId Connect ID token. */ + token: string; +} +export declare class Impersonated extends OAuth2Client implements IdTokenProvider { + private sourceClient; + private targetPrincipal; + private targetScopes; + private delegates; + private lifetime; + private endpoint; + /** + * Impersonated service account credentials. + * + * Create a new access token by impersonating another service account. + * + * Impersonated Credentials allowing credentials issued to a user or + * service account to impersonate another. The source project using + * Impersonated Credentials must enable the "IAMCredentials" API. + * Also, the target service account must grant the orginating principal + * the "Service Account Token Creator" IAM role. + * + * @param {object} options - The configuration object. + * @param {object} [options.sourceClient] the source credential used as to + * acquire the impersonated credentials. + * @param {string} [options.targetPrincipal] the service account to + * impersonate. + * @param {string[]} [options.delegates] the chained list of delegates + * required to grant the final access_token. If set, the sequence of + * identities must have "Service Account Token Creator" capability granted to + * the preceding identity. For example, if set to [serviceAccountB, + * serviceAccountC], the sourceCredential must have the Token Creator role on + * serviceAccountB. serviceAccountB must have the Token Creator on + * serviceAccountC. Finally, C must have Token Creator on target_principal. + * If left unset, sourceCredential must have that role on targetPrincipal. + * @param {string[]} [options.targetScopes] scopes to request during the + * authorization grant. + * @param {number} [options.lifetime] number of seconds the delegated + * credential should be valid for up to 3600 seconds by default, or 43,200 + * seconds by extending the token's lifetime, see: + * https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth + * @param {string} [options.endpoint] api endpoint override. + */ + constructor(options?: ImpersonatedOptions); + /** + * Signs some bytes. + * + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob Reference Documentation} + * @param blobToSign String to sign. + * + * @returns A {@link SignBlobResponse} denoting the keyID and signedBlob in base64 string + */ + sign(blobToSign: string): Promise; + /** The service account email to be impersonated. */ + getTargetPrincipal(): string; + /** + * Refreshes the access token. + */ + protected refreshToken(): Promise; + /** + * Generates an OpenID Connect ID token for a service account. + * + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateIdToken Reference Documentation} + * + * @param targetAudience the audience for the fetched ID token. + * @param options the for the request + * @return an OpenID Connect ID token + */ + fetchIdToken(targetAudience: string, options?: FetchIdTokenOptions): Promise; +} diff --git a/node_modules/google-auth-library/build/src/auth/impersonated.js b/node_modules/google-auth-library/build/src/auth/impersonated.js new file mode 100644 index 0000000..46c07c9 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/impersonated.js @@ -0,0 +1,186 @@ +"use strict"; +/** + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Impersonated = exports.IMPERSONATED_ACCOUNT_TYPE = void 0; +const oauth2client_1 = require("./oauth2client"); +const gaxios_1 = require("gaxios"); +const util_1 = require("../util"); +exports.IMPERSONATED_ACCOUNT_TYPE = 'impersonated_service_account'; +class Impersonated extends oauth2client_1.OAuth2Client { + /** + * Impersonated service account credentials. + * + * Create a new access token by impersonating another service account. + * + * Impersonated Credentials allowing credentials issued to a user or + * service account to impersonate another. The source project using + * Impersonated Credentials must enable the "IAMCredentials" API. + * Also, the target service account must grant the orginating principal + * the "Service Account Token Creator" IAM role. + * + * @param {object} options - The configuration object. + * @param {object} [options.sourceClient] the source credential used as to + * acquire the impersonated credentials. + * @param {string} [options.targetPrincipal] the service account to + * impersonate. + * @param {string[]} [options.delegates] the chained list of delegates + * required to grant the final access_token. If set, the sequence of + * identities must have "Service Account Token Creator" capability granted to + * the preceding identity. For example, if set to [serviceAccountB, + * serviceAccountC], the sourceCredential must have the Token Creator role on + * serviceAccountB. serviceAccountB must have the Token Creator on + * serviceAccountC. Finally, C must have Token Creator on target_principal. + * If left unset, sourceCredential must have that role on targetPrincipal. + * @param {string[]} [options.targetScopes] scopes to request during the + * authorization grant. + * @param {number} [options.lifetime] number of seconds the delegated + * credential should be valid for up to 3600 seconds by default, or 43,200 + * seconds by extending the token's lifetime, see: + * https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth + * @param {string} [options.endpoint] api endpoint override. + */ + constructor(options = {}) { + var _a, _b, _c, _d, _e, _f; + super(options); + // Start with an expired refresh token, which will automatically be + // refreshed before the first API call is made. + this.credentials = { + expiry_date: 1, + refresh_token: 'impersonated-placeholder', + }; + this.sourceClient = (_a = options.sourceClient) !== null && _a !== void 0 ? _a : new oauth2client_1.OAuth2Client(); + this.targetPrincipal = (_b = options.targetPrincipal) !== null && _b !== void 0 ? _b : ''; + this.delegates = (_c = options.delegates) !== null && _c !== void 0 ? _c : []; + this.targetScopes = (_d = options.targetScopes) !== null && _d !== void 0 ? _d : []; + this.lifetime = (_e = options.lifetime) !== null && _e !== void 0 ? _e : 3600; + const usingExplicitUniverseDomain = !!(0, util_1.originalOrCamelOptions)(options).get('universe_domain'); + if (!usingExplicitUniverseDomain) { + // override the default universe with the source's universe + this.universeDomain = this.sourceClient.universeDomain; + } + else if (this.sourceClient.universeDomain !== this.universeDomain) { + // non-default universe and is not matching the source - this could be a credential leak + throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`); + } + this.endpoint = + (_f = options.endpoint) !== null && _f !== void 0 ? _f : `https://iamcredentials.${this.universeDomain}`; + } + /** + * Signs some bytes. + * + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob Reference Documentation} + * @param blobToSign String to sign. + * + * @returns A {@link SignBlobResponse} denoting the keyID and signedBlob in base64 string + */ + async sign(blobToSign) { + await this.sourceClient.getAccessToken(); + const name = `projects/-/serviceAccounts/${this.targetPrincipal}`; + const u = `${this.endpoint}/v1/${name}:signBlob`; + const body = { + delegates: this.delegates, + payload: Buffer.from(blobToSign).toString('base64'), + }; + const res = await this.sourceClient.request({ + ...Impersonated.RETRY_CONFIG, + url: u, + data: body, + method: 'POST', + }); + return res.data; + } + /** The service account email to be impersonated. */ + getTargetPrincipal() { + return this.targetPrincipal; + } + /** + * Refreshes the access token. + */ + async refreshToken() { + var _a, _b, _c, _d, _e, _f; + try { + await this.sourceClient.getAccessToken(); + const name = 'projects/-/serviceAccounts/' + this.targetPrincipal; + const u = `${this.endpoint}/v1/${name}:generateAccessToken`; + const body = { + delegates: this.delegates, + scope: this.targetScopes, + lifetime: this.lifetime + 's', + }; + const res = await this.sourceClient.request({ + ...Impersonated.RETRY_CONFIG, + url: u, + data: body, + method: 'POST', + }); + const tokenResponse = res.data; + this.credentials.access_token = tokenResponse.accessToken; + this.credentials.expiry_date = Date.parse(tokenResponse.expireTime); + return { + tokens: this.credentials, + res, + }; + } + catch (error) { + if (!(error instanceof Error)) + throw error; + let status = 0; + let message = ''; + if (error instanceof gaxios_1.GaxiosError) { + status = (_c = (_b = (_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.error) === null || _c === void 0 ? void 0 : _c.status; + message = (_f = (_e = (_d = error === null || error === void 0 ? void 0 : error.response) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.error) === null || _f === void 0 ? void 0 : _f.message; + } + if (status && message) { + error.message = `${status}: unable to impersonate: ${message}`; + throw error; + } + else { + error.message = `unable to impersonate: ${error}`; + throw error; + } + } + } + /** + * Generates an OpenID Connect ID token for a service account. + * + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateIdToken Reference Documentation} + * + * @param targetAudience the audience for the fetched ID token. + * @param options the for the request + * @return an OpenID Connect ID token + */ + async fetchIdToken(targetAudience, options) { + var _a, _b; + await this.sourceClient.getAccessToken(); + const name = `projects/-/serviceAccounts/${this.targetPrincipal}`; + const u = `${this.endpoint}/v1/${name}:generateIdToken`; + const body = { + delegates: this.delegates, + audience: targetAudience, + includeEmail: (_a = options === null || options === void 0 ? void 0 : options.includeEmail) !== null && _a !== void 0 ? _a : true, + useEmailAzp: (_b = options === null || options === void 0 ? void 0 : options.includeEmail) !== null && _b !== void 0 ? _b : true, + }; + const res = await this.sourceClient.request({ + ...Impersonated.RETRY_CONFIG, + url: u, + data: body, + method: 'POST', + }); + return res.data.token; + } +} +exports.Impersonated = Impersonated; diff --git a/node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts b/node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts new file mode 100644 index 0000000..9244650 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts @@ -0,0 +1,62 @@ +import * as stream from 'stream'; +import { JWTInput } from './credentials'; +import { Headers } from './oauth2client'; +export interface Claims { + [index: string]: string; +} +export declare class JWTAccess { + email?: string | null; + key?: string | null; + keyId?: string | null; + projectId?: string; + eagerRefreshThresholdMillis: number; + private cache; + /** + * JWTAccess service account credentials. + * + * Create a new access token by using the credential to create a new JWT token + * that's recognized as the access token. + * + * @param email the service account email address. + * @param key the private key that will be used to sign the token. + * @param keyId the ID of the private key used to sign the token. + */ + constructor(email?: string | null, key?: string | null, keyId?: string | null, eagerRefreshThresholdMillis?: number); + /** + * Ensures that we're caching a key appropriately, giving precedence to scopes vs. url + * + * @param url The URI being authorized. + * @param scopes The scope or scopes being authorized + * @returns A string that returns the cached key. + */ + getCachedKey(url?: string, scopes?: string | string[]): string; + /** + * Get a non-expired access token, after refreshing if necessary. + * + * @param url The URI being authorized. + * @param additionalClaims An object with a set of additional claims to + * include in the payload. + * @returns An object that includes the authorization header. + */ + getRequestHeaders(url?: string, additionalClaims?: Claims, scopes?: string | string[]): Headers; + /** + * Returns an expiration time for the JWT token. + * + * @param iat The issued at time for the JWT. + * @returns An expiration time for the JWT. + */ + private static getExpirationTime; + /** + * Create a JWTAccess credentials instance using the given input options. + * @param json The input object. + */ + fromJSON(json: JWTInput): void; + /** + * Create a JWTAccess credentials instance using the given input stream. + * @param inputStream The input stream. + * @param callback Optional callback. + */ + fromStream(inputStream: stream.Readable): Promise; + fromStream(inputStream: stream.Readable, callback: (err?: Error) => void): void; + private fromStreamAsync; +} diff --git a/node_modules/google-auth-library/build/src/auth/jwtaccess.js b/node_modules/google-auth-library/build/src/auth/jwtaccess.js new file mode 100644 index 0000000..664387b --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/jwtaccess.js @@ -0,0 +1,192 @@ +"use strict"; +// Copyright 2015 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.JWTAccess = void 0; +const jws = require("jws"); +const util_1 = require("../util"); +const DEFAULT_HEADER = { + alg: 'RS256', + typ: 'JWT', +}; +class JWTAccess { + /** + * JWTAccess service account credentials. + * + * Create a new access token by using the credential to create a new JWT token + * that's recognized as the access token. + * + * @param email the service account email address. + * @param key the private key that will be used to sign the token. + * @param keyId the ID of the private key used to sign the token. + */ + constructor(email, key, keyId, eagerRefreshThresholdMillis) { + this.cache = new util_1.LRUCache({ + capacity: 500, + maxAge: 60 * 60 * 1000, + }); + this.email = email; + this.key = key; + this.keyId = keyId; + this.eagerRefreshThresholdMillis = + eagerRefreshThresholdMillis !== null && eagerRefreshThresholdMillis !== void 0 ? eagerRefreshThresholdMillis : 5 * 60 * 1000; + } + /** + * Ensures that we're caching a key appropriately, giving precedence to scopes vs. url + * + * @param url The URI being authorized. + * @param scopes The scope or scopes being authorized + * @returns A string that returns the cached key. + */ + getCachedKey(url, scopes) { + let cacheKey = url; + if (scopes && Array.isArray(scopes) && scopes.length) { + cacheKey = url ? `${url}_${scopes.join('_')}` : `${scopes.join('_')}`; + } + else if (typeof scopes === 'string') { + cacheKey = url ? `${url}_${scopes}` : scopes; + } + if (!cacheKey) { + throw Error('Scopes or url must be provided'); + } + return cacheKey; + } + /** + * Get a non-expired access token, after refreshing if necessary. + * + * @param url The URI being authorized. + * @param additionalClaims An object with a set of additional claims to + * include in the payload. + * @returns An object that includes the authorization header. + */ + getRequestHeaders(url, additionalClaims, scopes) { + // Return cached authorization headers, unless we are within + // eagerRefreshThresholdMillis ms of them expiring: + const key = this.getCachedKey(url, scopes); + const cachedToken = this.cache.get(key); + const now = Date.now(); + if (cachedToken && + cachedToken.expiration - now > this.eagerRefreshThresholdMillis) { + return cachedToken.headers; + } + const iat = Math.floor(Date.now() / 1000); + const exp = JWTAccess.getExpirationTime(iat); + let defaultClaims; + // Turn scopes into space-separated string + if (Array.isArray(scopes)) { + scopes = scopes.join(' '); + } + // If scopes are specified, sign with scopes + if (scopes) { + defaultClaims = { + iss: this.email, + sub: this.email, + scope: scopes, + exp, + iat, + }; + } + else { + defaultClaims = { + iss: this.email, + sub: this.email, + aud: url, + exp, + iat, + }; + } + // if additionalClaims are provided, ensure they do not collide with + // other required claims. + if (additionalClaims) { + for (const claim in defaultClaims) { + if (additionalClaims[claim]) { + throw new Error(`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`); + } + } + } + const header = this.keyId + ? { ...DEFAULT_HEADER, kid: this.keyId } + : DEFAULT_HEADER; + const payload = Object.assign(defaultClaims, additionalClaims); + // Sign the jwt and add it to the cache + const signedJWT = jws.sign({ header, payload, secret: this.key }); + const headers = { Authorization: `Bearer ${signedJWT}` }; + this.cache.set(key, { + expiration: exp * 1000, + headers, + }); + return headers; + } + /** + * Returns an expiration time for the JWT token. + * + * @param iat The issued at time for the JWT. + * @returns An expiration time for the JWT. + */ + static getExpirationTime(iat) { + const exp = iat + 3600; // 3600 seconds = 1 hour + return exp; + } + /** + * Create a JWTAccess credentials instance using the given input options. + * @param json The input object. + */ + fromJSON(json) { + if (!json) { + throw new Error('Must pass in a JSON object containing the service account auth settings.'); + } + if (!json.client_email) { + throw new Error('The incoming JSON object does not contain a client_email field'); + } + if (!json.private_key) { + throw new Error('The incoming JSON object does not contain a private_key field'); + } + // Extract the relevant information from the json key file. + this.email = json.client_email; + this.key = json.private_key; + this.keyId = json.private_key_id; + this.projectId = json.project_id; + } + fromStream(inputStream, callback) { + if (callback) { + this.fromStreamAsync(inputStream).then(() => callback(), callback); + } + else { + return this.fromStreamAsync(inputStream); + } + } + fromStreamAsync(inputStream) { + return new Promise((resolve, reject) => { + if (!inputStream) { + reject(new Error('Must pass in a stream containing the service account auth settings.')); + } + let s = ''; + inputStream + .setEncoding('utf8') + .on('data', chunk => (s += chunk)) + .on('error', reject) + .on('end', () => { + try { + const data = JSON.parse(s); + this.fromJSON(data); + resolve(); + } + catch (err) { + reject(err); + } + }); + }); + } +} +exports.JWTAccess = JWTAccess; diff --git a/node_modules/google-auth-library/build/src/auth/jwtclient.d.ts b/node_modules/google-auth-library/build/src/auth/jwtclient.d.ts new file mode 100644 index 0000000..1d8ab2a --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/jwtclient.d.ts @@ -0,0 +1,117 @@ +import { GoogleToken } from 'gtoken'; +import * as stream from 'stream'; +import { CredentialBody, Credentials, JWTInput } from './credentials'; +import { IdTokenProvider } from './idtokenclient'; +import { GetTokenResponse, OAuth2Client, OAuth2ClientOptions, RequestMetadataResponse } from './oauth2client'; +export interface JWTOptions extends OAuth2ClientOptions { + email?: string; + keyFile?: string; + key?: string; + keyId?: string; + scopes?: string | string[]; + subject?: string; + additionalClaims?: {}; +} +export declare class JWT extends OAuth2Client implements IdTokenProvider { + email?: string; + keyFile?: string; + key?: string; + keyId?: string; + defaultScopes?: string | string[]; + scopes?: string | string[]; + scope?: string; + subject?: string; + gtoken?: GoogleToken; + additionalClaims?: {}; + useJWTAccessWithScope?: boolean; + defaultServicePath?: string; + private access?; + /** + * JWT service account credentials. + * + * Retrieve access token using gtoken. + * + * @param email service account email address. + * @param keyFile path to private key file. + * @param key value of key + * @param scopes list of requested scopes or a single scope. + * @param subject impersonated account's email address. + * @param key_id the ID of the key + */ + constructor(options: JWTOptions); + constructor(email?: string, keyFile?: string, key?: string, scopes?: string | string[], subject?: string, keyId?: string); + /** + * Creates a copy of the credential with the specified scopes. + * @param scopes List of requested scopes or a single scope. + * @return The cloned instance. + */ + createScoped(scopes?: string | string[]): JWT; + /** + * Obtains the metadata to be sent with the request. + * + * @param url the URI being authorized. + */ + protected getRequestMetadataAsync(url?: string | null): Promise; + /** + * Fetches an ID token. + * @param targetAudience the audience for the fetched ID token. + */ + fetchIdToken(targetAudience: string): Promise; + /** + * Determine if there are currently scopes available. + */ + private hasUserScopes; + /** + * Are there any default or user scopes defined. + */ + private hasAnyScopes; + /** + * Get the initial access token using gToken. + * @param callback Optional callback. + * @returns Promise that resolves with credentials + */ + authorize(): Promise; + authorize(callback: (err: Error | null, result?: Credentials) => void): void; + private authorizeAsync; + /** + * Refreshes the access token. + * @param refreshToken ignored + * @private + */ + protected refreshTokenNoCache(refreshToken?: string | null): Promise; + /** + * Create a gToken if it doesn't already exist. + */ + private createGToken; + /** + * Create a JWT credentials instance using the given input options. + * @param json The input object. + * + * @remarks + * + * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}. + */ + fromJSON(json: JWTInput): void; + /** + * Create a JWT credentials instance using the given input stream. + * @param inputStream The input stream. + * @param callback Optional callback. + * + * @remarks + * + * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}. + */ + fromStream(inputStream: stream.Readable): Promise; + fromStream(inputStream: stream.Readable, callback: (err?: Error | null) => void): void; + private fromStreamAsync; + /** + * Creates a JWT credentials instance using an API Key for authentication. + * @param apiKey The API Key in string form. + */ + fromAPIKey(apiKey: string): void; + /** + * Using the key or keyFile on the JWT client, obtain an object that contains + * the key and the client email. + */ + getCredentials(): Promise; +} diff --git a/node_modules/google-auth-library/build/src/auth/jwtclient.js b/node_modules/google-auth-library/build/src/auth/jwtclient.js new file mode 100644 index 0000000..d068b7d --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/jwtclient.js @@ -0,0 +1,284 @@ +"use strict"; +// Copyright 2013 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.JWT = void 0; +const gtoken_1 = require("gtoken"); +const jwtaccess_1 = require("./jwtaccess"); +const oauth2client_1 = require("./oauth2client"); +const authclient_1 = require("./authclient"); +class JWT extends oauth2client_1.OAuth2Client { + constructor(optionsOrEmail, keyFile, key, scopes, subject, keyId) { + const opts = optionsOrEmail && typeof optionsOrEmail === 'object' + ? optionsOrEmail + : { email: optionsOrEmail, keyFile, key, keyId, scopes, subject }; + super(opts); + this.email = opts.email; + this.keyFile = opts.keyFile; + this.key = opts.key; + this.keyId = opts.keyId; + this.scopes = opts.scopes; + this.subject = opts.subject; + this.additionalClaims = opts.additionalClaims; + // Start with an expired refresh token, which will automatically be + // refreshed before the first API call is made. + this.credentials = { refresh_token: 'jwt-placeholder', expiry_date: 1 }; + } + /** + * Creates a copy of the credential with the specified scopes. + * @param scopes List of requested scopes or a single scope. + * @return The cloned instance. + */ + createScoped(scopes) { + const jwt = new JWT(this); + jwt.scopes = scopes; + return jwt; + } + /** + * Obtains the metadata to be sent with the request. + * + * @param url the URI being authorized. + */ + async getRequestMetadataAsync(url) { + url = this.defaultServicePath ? `https://${this.defaultServicePath}/` : url; + const useSelfSignedJWT = (!this.hasUserScopes() && url) || + (this.useJWTAccessWithScope && this.hasAnyScopes()) || + this.universeDomain !== authclient_1.DEFAULT_UNIVERSE; + if (this.subject && this.universeDomain !== authclient_1.DEFAULT_UNIVERSE) { + throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${authclient_1.DEFAULT_UNIVERSE}`); + } + if (!this.apiKey && useSelfSignedJWT) { + if (this.additionalClaims && + this.additionalClaims.target_audience) { + const { tokens } = await this.refreshToken(); + return { + headers: this.addSharedMetadataHeaders({ + Authorization: `Bearer ${tokens.id_token}`, + }), + }; + } + else { + // no scopes have been set, but a uri has been provided. Use JWTAccess + // credentials. + if (!this.access) { + this.access = new jwtaccess_1.JWTAccess(this.email, this.key, this.keyId, this.eagerRefreshThresholdMillis); + } + let scopes; + if (this.hasUserScopes()) { + scopes = this.scopes; + } + else if (!url) { + scopes = this.defaultScopes; + } + const useScopes = this.useJWTAccessWithScope || + this.universeDomain !== authclient_1.DEFAULT_UNIVERSE; + const headers = await this.access.getRequestHeaders(url !== null && url !== void 0 ? url : undefined, this.additionalClaims, + // Scopes take precedent over audience for signing, + // so we only provide them if `useJWTAccessWithScope` is on or + // if we are in a non-default universe + useScopes ? scopes : undefined); + return { headers: this.addSharedMetadataHeaders(headers) }; + } + } + else if (this.hasAnyScopes() || this.apiKey) { + return super.getRequestMetadataAsync(url); + } + else { + // If no audience, apiKey, or scopes are provided, we should not attempt + // to populate any headers: + return { headers: {} }; + } + } + /** + * Fetches an ID token. + * @param targetAudience the audience for the fetched ID token. + */ + async fetchIdToken(targetAudience) { + // Create a new gToken for fetching an ID token + const gtoken = new gtoken_1.GoogleToken({ + iss: this.email, + sub: this.subject, + scope: this.scopes || this.defaultScopes, + keyFile: this.keyFile, + key: this.key, + additionalClaims: { target_audience: targetAudience }, + transporter: this.transporter, + }); + await gtoken.getToken({ + forceRefresh: true, + }); + if (!gtoken.idToken) { + throw new Error('Unknown error: Failed to fetch ID token'); + } + return gtoken.idToken; + } + /** + * Determine if there are currently scopes available. + */ + hasUserScopes() { + if (!this.scopes) { + return false; + } + return this.scopes.length > 0; + } + /** + * Are there any default or user scopes defined. + */ + hasAnyScopes() { + if (this.scopes && this.scopes.length > 0) + return true; + if (this.defaultScopes && this.defaultScopes.length > 0) + return true; + return false; + } + authorize(callback) { + if (callback) { + this.authorizeAsync().then(r => callback(null, r), callback); + } + else { + return this.authorizeAsync(); + } + } + async authorizeAsync() { + const result = await this.refreshToken(); + if (!result) { + throw new Error('No result returned'); + } + this.credentials = result.tokens; + this.credentials.refresh_token = 'jwt-placeholder'; + this.key = this.gtoken.key; + this.email = this.gtoken.iss; + return result.tokens; + } + /** + * Refreshes the access token. + * @param refreshToken ignored + * @private + */ + async refreshTokenNoCache( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + refreshToken) { + const gtoken = this.createGToken(); + const token = await gtoken.getToken({ + forceRefresh: this.isTokenExpiring(), + }); + const tokens = { + access_token: token.access_token, + token_type: 'Bearer', + expiry_date: gtoken.expiresAt, + id_token: gtoken.idToken, + }; + this.emit('tokens', tokens); + return { res: null, tokens }; + } + /** + * Create a gToken if it doesn't already exist. + */ + createGToken() { + if (!this.gtoken) { + this.gtoken = new gtoken_1.GoogleToken({ + iss: this.email, + sub: this.subject, + scope: this.scopes || this.defaultScopes, + keyFile: this.keyFile, + key: this.key, + additionalClaims: this.additionalClaims, + transporter: this.transporter, + }); + } + return this.gtoken; + } + /** + * Create a JWT credentials instance using the given input options. + * @param json The input object. + * + * @remarks + * + * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}. + */ + fromJSON(json) { + if (!json) { + throw new Error('Must pass in a JSON object containing the service account auth settings.'); + } + if (!json.client_email) { + throw new Error('The incoming JSON object does not contain a client_email field'); + } + if (!json.private_key) { + throw new Error('The incoming JSON object does not contain a private_key field'); + } + // Extract the relevant information from the json key file. + this.email = json.client_email; + this.key = json.private_key; + this.keyId = json.private_key_id; + this.projectId = json.project_id; + this.quotaProjectId = json.quota_project_id; + this.universeDomain = json.universe_domain || this.universeDomain; + } + fromStream(inputStream, callback) { + if (callback) { + this.fromStreamAsync(inputStream).then(() => callback(), callback); + } + else { + return this.fromStreamAsync(inputStream); + } + } + fromStreamAsync(inputStream) { + return new Promise((resolve, reject) => { + if (!inputStream) { + throw new Error('Must pass in a stream containing the service account auth settings.'); + } + let s = ''; + inputStream + .setEncoding('utf8') + .on('error', reject) + .on('data', chunk => (s += chunk)) + .on('end', () => { + try { + const data = JSON.parse(s); + this.fromJSON(data); + resolve(); + } + catch (e) { + reject(e); + } + }); + }); + } + /** + * Creates a JWT credentials instance using an API Key for authentication. + * @param apiKey The API Key in string form. + */ + fromAPIKey(apiKey) { + if (typeof apiKey !== 'string') { + throw new Error('Must provide an API Key string.'); + } + this.apiKey = apiKey; + } + /** + * Using the key or keyFile on the JWT client, obtain an object that contains + * the key and the client email. + */ + async getCredentials() { + if (this.key) { + return { private_key: this.key, client_email: this.email }; + } + else if (this.keyFile) { + const gtoken = this.createGToken(); + const creds = await gtoken.getCredentials(this.keyFile); + return { private_key: creds.privateKey, client_email: creds.clientEmail }; + } + throw new Error('A key or a keyFile must be provided to getCredentials.'); + } +} +exports.JWT = JWT; diff --git a/node_modules/google-auth-library/build/src/auth/loginticket.d.ts b/node_modules/google-auth-library/build/src/auth/loginticket.d.ts new file mode 100644 index 0000000..33fd407 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/loginticket.d.ts @@ -0,0 +1,140 @@ +export declare class LoginTicket { + private envelope?; + private payload?; + /** + * Create a simple class to extract user ID from an ID Token + * + * @param {string} env Envelope of the jwt + * @param {TokenPayload} pay Payload of the jwt + * @constructor + */ + constructor(env?: string, pay?: TokenPayload); + getEnvelope(): string | undefined; + getPayload(): TokenPayload | undefined; + /** + * Create a simple class to extract user ID from an ID Token + * + * @return The user ID + */ + getUserId(): string | null; + /** + * Returns attributes from the login ticket. This can contain + * various information about the user session. + * + * @return The envelope and payload + */ + getAttributes(): { + envelope: string | undefined; + payload: TokenPayload | undefined; + }; +} +export interface TokenPayload { + /** + * The Issuer Identifier for the Issuer of the response. Always + * https://accounts.google.com or accounts.google.com for Google ID tokens. + */ + iss: string; + /** + * Access token hash. Provides validation that the access token is tied to the + * identity token. If the ID token is issued with an access token in the + * server flow, this is always included. This can be used as an alternate + * mechanism to protect against cross-site request forgery attacks, but if you + * follow Step 1 and Step 3 it is not necessary to verify the access token. + */ + at_hash?: string; + /** + * True if the user's e-mail address has been verified; otherwise false. + */ + email_verified?: boolean; + /** + * An identifier for the user, unique among all Google accounts and never + * reused. A Google account can have multiple emails at different points in + * time, but the sub value is never changed. Use sub within your application + * as the unique-identifier key for the user. + */ + sub: string; + /** + * The client_id of the authorized presenter. This claim is only needed when + * the party requesting the ID token is not the same as the audience of the ID + * token. This may be the case at Google for hybrid apps where a web + * application and Android app have a different client_id but share the same + * project. + */ + azp?: string; + /** + * The user's email address. This may not be unique and is not suitable for + * use as a primary key. Provided only if your scope included the string + * "email". + */ + email?: string; + /** + * The URL of the user's profile page. Might be provided when: + * - The request scope included the string "profile" + * - The ID token is returned from a token refresh + * - When profile claims are present, you can use them to update your app's + * user records. Note that this claim is never guaranteed to be present. + */ + profile?: string; + /** + * The URL of the user's profile picture. Might be provided when: + * - The request scope included the string "profile" + * - The ID token is returned from a token refresh + * - When picture claims are present, you can use them to update your app's + * user records. Note that this claim is never guaranteed to be present. + */ + picture?: string; + /** + * The user's full name, in a displayable form. Might be provided when: + * - The request scope included the string "profile" + * - The ID token is returned from a token refresh + * - When name claims are present, you can use them to update your app's user + * records. Note that this claim is never guaranteed to be present. + */ + name?: string; + /** + * The user's given name, in a displayable form. Might be provided when: + * - The request scope included the string "profile" + * - The ID token is returned from a token refresh + * - When name claims are present, you can use them to update your app's user + * records. Note that this claim is never guaranteed to be present. + */ + given_name?: string; + /** + * The user's family name, in a displayable form. Might be provided when: + * - The request scope included the string "profile" + * - The ID token is returned from a token refresh + * - When name claims are present, you can use them to update your app's user + * records. Note that this claim is never guaranteed to be present. + */ + family_name?: string; + /** + * Identifies the audience that this ID token is intended for. It must be one + * of the OAuth 2.0 client IDs of your application. + */ + aud: string; + /** + * The time the ID token was issued, represented in Unix time (integer + * seconds). + */ + iat: number; + /** + * The time the ID token expires, represented in Unix time (integer seconds). + */ + exp: number; + /** + * The value of the nonce supplied by your app in the authentication request. + * You should enforce protection against replay attacks by ensuring it is + * presented only once. + */ + nonce?: string; + /** + * The hosted G Suite domain of the user. Provided only if the user belongs to + * a hosted domain. + */ + hd?: string; + /** + * The user's locale, represented by a BCP 47 language tag. + * Might be provided when a name claim is present. + */ + locale?: string; +} diff --git a/node_modules/google-auth-library/build/src/auth/loginticket.js b/node_modules/google-auth-library/build/src/auth/loginticket.js new file mode 100644 index 0000000..9a1687b --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/loginticket.js @@ -0,0 +1,57 @@ +"use strict"; +// Copyright 2014 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LoginTicket = void 0; +class LoginTicket { + /** + * Create a simple class to extract user ID from an ID Token + * + * @param {string} env Envelope of the jwt + * @param {TokenPayload} pay Payload of the jwt + * @constructor + */ + constructor(env, pay) { + this.envelope = env; + this.payload = pay; + } + getEnvelope() { + return this.envelope; + } + getPayload() { + return this.payload; + } + /** + * Create a simple class to extract user ID from an ID Token + * + * @return The user ID + */ + getUserId() { + const payload = this.getPayload(); + if (payload && payload.sub) { + return payload.sub; + } + return null; + } + /** + * Returns attributes from the login ticket. This can contain + * various information about the user session. + * + * @return The envelope and payload + */ + getAttributes() { + return { envelope: this.getEnvelope(), payload: this.getPayload() }; + } +} +exports.LoginTicket = LoginTicket; diff --git a/node_modules/google-auth-library/build/src/auth/oauth2client.d.ts b/node_modules/google-auth-library/build/src/auth/oauth2client.d.ts new file mode 100644 index 0000000..7080d08 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/oauth2client.d.ts @@ -0,0 +1,575 @@ +import { GaxiosError, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +import * as querystring from 'querystring'; +import { JwkCertificate } from '../crypto/crypto'; +import { BodyResponseCallback } from '../transporters'; +import { AuthClient, AuthClientOptions } from './authclient'; +import { Credentials } from './credentials'; +import { LoginTicket } from './loginticket'; +/** + * The results from the `generateCodeVerifierAsync` method. To learn more, + * See the sample: + * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js + */ +export interface CodeVerifierResults { + /** + * The code verifier that will be used when calling `getToken` to obtain a new + * access token. + */ + codeVerifier: string; + /** + * The code_challenge that should be sent with the `generateAuthUrl` call + * to obtain a verifiable authentication url. + */ + codeChallenge?: string; +} +export interface Certificates { + [index: string]: string | JwkCertificate; +} +export interface PublicKeys { + [index: string]: string; +} +export interface Headers { + [index: string]: string; +} +export declare enum CodeChallengeMethod { + Plain = "plain", + S256 = "S256" +} +export declare enum CertificateFormat { + PEM = "PEM", + JWK = "JWK" +} +/** + * The client authentication type. Supported values are basic, post, and none. + * https://datatracker.ietf.org/doc/html/rfc7591#section-2 + */ +export declare enum ClientAuthentication { + ClientSecretPost = "ClientSecretPost", + ClientSecretBasic = "ClientSecretBasic", + None = "None" +} +export interface GetTokenOptions { + code: string; + codeVerifier?: string; + /** + * The client ID for your application. The value passed into the constructor + * will be used if not provided. Must match any client_id option passed to + * a corresponding call to generateAuthUrl. + */ + client_id?: string; + /** + * Determines where the API server redirects the user after the user + * completes the authorization flow. The value passed into the constructor + * will be used if not provided. Must match any redirect_uri option passed to + * a corresponding call to generateAuthUrl. + */ + redirect_uri?: string; +} +export interface TokenInfo { + /** + * The application that is the intended user of the access token. + */ + aud: string; + /** + * This value lets you correlate profile information from multiple Google + * APIs. It is only present in the response if you included the profile scope + * in your request in step 1. The field value is an immutable identifier for + * the logged-in user that can be used to create and manage user sessions in + * your application. The identifier is the same regardless of which client ID + * is used to retrieve it. This enables multiple applications in the same + * organization to correlate profile information. + */ + user_id?: string; + /** + * An array of scopes that the user granted access to. + */ + scopes: string[]; + /** + * The datetime when the token becomes invalid. + */ + expiry_date: number; + /** + * An identifier for the user, unique among all Google accounts and never + * reused. A Google account can have multiple emails at different points in + * time, but the sub value is never changed. Use sub within your application + * as the unique-identifier key for the user. + */ + sub?: string; + /** + * The client_id of the authorized presenter. This claim is only needed when + * the party requesting the ID token is not the same as the audience of the ID + * token. This may be the case at Google for hybrid apps where a web + * application and Android app have a different client_id but share the same + * project. + */ + azp?: string; + /** + * Indicates whether your application can refresh access tokens + * when the user is not present at the browser. Valid parameter values are + * 'online', which is the default value, and 'offline'. Set the value to + * 'offline' if your application needs to refresh access tokens when the user + * is not present at the browser. This value instructs the Google + * authorization server to return a refresh token and an access token the + * first time that your application exchanges an authorization code for + * tokens. + */ + access_type?: string; + /** + * The user's email address. This value may not be unique to this user and + * is not suitable for use as a primary key. Provided only if your scope + * included the email scope value. + */ + email?: string; + /** + * True if the user's e-mail address has been verified; otherwise false. + */ + email_verified?: boolean; +} +export interface GenerateAuthUrlOpts { + /** + * Recommended. Indicates whether your application can refresh access tokens + * when the user is not present at the browser. Valid parameter values are + * 'online', which is the default value, and 'offline'. Set the value to + * 'offline' if your application needs to refresh access tokens when the user + * is not present at the browser. This value instructs the Google + * authorization server to return a refresh token and an access token the + * first time that your application exchanges an authorization code for + * tokens. + */ + access_type?: string; + /** + * The hd (hosted domain) parameter streamlines the login process for G Suite + * hosted accounts. By including the domain of the G Suite user (for example, + * mycollege.edu), you can indicate that the account selection UI should be + * optimized for accounts at that domain. To optimize for G Suite accounts + * generally instead of just one domain, use an asterisk: hd=*. + * Don't rely on this UI optimization to control who can access your app, + * as client-side requests can be modified. Be sure to validate that the + * returned ID token has an hd claim value that matches what you expect + * (e.g. mycolledge.edu). Unlike the request parameter, the ID token claim is + * contained within a security token from Google, so the value can be trusted. + */ + hd?: string; + /** + * The 'response_type' will always be set to 'CODE'. + */ + response_type?: string; + /** + * The client ID for your application. The value passed into the constructor + * will be used if not provided. You can find this value in the API Console. + */ + client_id?: string; + /** + * Determines where the API server redirects the user after the user + * completes the authorization flow. The value must exactly match one of the + * 'redirect_uri' values listed for your project in the API Console. Note that + * the http or https scheme, case, and trailing slash ('/') must all match. + * The value passed into the constructor will be used if not provided. + */ + redirect_uri?: string; + /** + * Required. A space-delimited list of scopes that identify the resources that + * your application could access on the user's behalf. These values inform the + * consent screen that Google displays to the user. Scopes enable your + * application to only request access to the resources that it needs while + * also enabling users to control the amount of access that they grant to your + * application. Thus, there is an inverse relationship between the number of + * scopes requested and the likelihood of obtaining user consent. The + * OAuth 2.0 API Scopes document provides a full list of scopes that you might + * use to access Google APIs. We recommend that your application request + * access to authorization scopes in context whenever possible. By requesting + * access to user data in context, via incremental authorization, you help + * users to more easily understand why your application needs the access it is + * requesting. + */ + scope?: string[] | string; + /** + * Recommended. Specifies any string value that your application uses to + * maintain state between your authorization request and the authorization + * server's response. The server returns the exact value that you send as a + * name=value pair in the hash (#) fragment of the 'redirect_uri' after the + * user consents to or denies your application's access request. You can use + * this parameter for several purposes, such as directing the user to the + * correct resource in your application, sending nonces, and mitigating + * cross-site request forgery. Since your redirect_uri can be guessed, using a + * state value can increase your assurance that an incoming connection is the + * result of an authentication request. If you generate a random string or + * encode the hash of a cookie or another value that captures the client's + * state, you can validate the response to additionally ensure that the + * request and response originated in the same browser, providing protection + * against attacks such as cross-site request forgery. See the OpenID Connect + * documentation for an example of how to create and confirm a state token. + */ + state?: string; + /** + * Optional. Enables applications to use incremental authorization to request + * access to additional scopes in context. If you set this parameter's value + * to true and the authorization request is granted, then the new access token + * will also cover any scopes to which the user previously granted the + * application access. See the incremental authorization section for examples. + */ + include_granted_scopes?: boolean; + /** + * Optional. If your application knows which user is trying to authenticate, + * it can use this parameter to provide a hint to the Google Authentication + * Server. The server uses the hint to simplify the login flow either by + * prefilling the email field in the sign-in form or by selecting the + * appropriate multi-login session. Set the parameter value to an email + * address or sub identifier, which is equivalent to the user's Google ID. + */ + login_hint?: string; + /** + * Optional. A space-delimited, case-sensitive list of prompts to present the + * user. If you don't specify this parameter, the user will be prompted only + * the first time your app requests access. Possible values are: + * + * 'none' - Donot display any authentication or consent screens. Must not be + * specified with other values. + * 'consent' - Prompt the user for consent. + * 'select_account' - Prompt the user to select an account. + */ + prompt?: string; + /** + * Recommended. Specifies what method was used to encode a 'code_verifier' + * that will be used during authorization code exchange. This parameter must + * be used with the 'code_challenge' parameter. The value of the + * 'code_challenge_method' defaults to "plain" if not present in the request + * that includes a 'code_challenge'. The only supported values for this + * parameter are "S256" or "plain". + */ + code_challenge_method?: CodeChallengeMethod; + /** + * Recommended. Specifies an encoded 'code_verifier' that will be used as a + * server-side challenge during authorization code exchange. This parameter + * must be used with the 'code_challenge' parameter described above. + */ + code_challenge?: string; + /** + * A way for developers and/or the auth team to provide a set of key value + * pairs to be added as query parameters to the authorization url. + */ + [key: string]: querystring.ParsedUrlQueryInput[keyof querystring.ParsedUrlQueryInput]; +} +export interface AccessTokenResponse { + access_token: string; + expiry_date: number; +} +export interface GetRefreshHandlerCallback { + (): Promise; +} +export interface GetTokenCallback { + (err: GaxiosError | null, token?: Credentials | null, res?: GaxiosResponse | null): void; +} +export interface GetTokenResponse { + tokens: Credentials; + res: GaxiosResponse | null; +} +export interface GetAccessTokenCallback { + (err: GaxiosError | null, token?: string | null, res?: GaxiosResponse | null): void; +} +export interface GetAccessTokenResponse { + token?: string | null; + res?: GaxiosResponse | null; +} +export interface RefreshAccessTokenCallback { + (err: GaxiosError | null, credentials?: Credentials | null, res?: GaxiosResponse | null): void; +} +export interface RefreshAccessTokenResponse { + credentials: Credentials; + res: GaxiosResponse | null; +} +export interface RequestMetadataResponse { + headers: Headers; + res?: GaxiosResponse | null; +} +export interface RequestMetadataCallback { + (err: GaxiosError | null, headers?: Headers, res?: GaxiosResponse | null): void; +} +export interface GetFederatedSignonCertsCallback { + (err: GaxiosError | null, certs?: Certificates, response?: GaxiosResponse | null): void; +} +export interface FederatedSignonCertsResponse { + certs: Certificates; + format: CertificateFormat; + res?: GaxiosResponse | null; +} +export interface GetIapPublicKeysCallback { + (err: GaxiosError | null, pubkeys?: PublicKeys, response?: GaxiosResponse | null): void; +} +export interface IapPublicKeysResponse { + pubkeys: PublicKeys; + res?: GaxiosResponse | null; +} +export interface RevokeCredentialsResult { + success: boolean; +} +export interface VerifyIdTokenOptions { + idToken: string; + audience?: string | string[]; + maxExpiry?: number; +} +export interface OAuth2ClientEndpoints { + /** + * The endpoint for viewing access token information + * + * @example + * 'https://oauth2.googleapis.com/tokeninfo' + */ + tokenInfoUrl: string | URL; + /** + * The base URL for auth endpoints. + * + * @example + * 'https://accounts.google.com/o/oauth2/v2/auth' + */ + oauth2AuthBaseUrl: string | URL; + /** + * The base endpoint for token retrieval + * . + * @example + * 'https://oauth2.googleapis.com/token' + */ + oauth2TokenUrl: string | URL; + /** + * The base endpoint to revoke tokens. + * + * @example + * 'https://oauth2.googleapis.com/revoke' + */ + oauth2RevokeUrl: string | URL; + /** + * Sign on certificates in PEM format. + * + * @example + * 'https://www.googleapis.com/oauth2/v1/certs' + */ + oauth2FederatedSignonPemCertsUrl: string | URL; + /** + * Sign on certificates in JWK format. + * + * @example + * 'https://www.googleapis.com/oauth2/v3/certs' + */ + oauth2FederatedSignonJwkCertsUrl: string | URL; + /** + * IAP Public Key URL. + * This URL contains a JSON dictionary that maps the `kid` claims to the public key values. + * + * @example + * 'https://www.gstatic.com/iap/verify/public_key' + */ + oauth2IapPublicKeyUrl: string | URL; +} +export interface OAuth2ClientOptions extends AuthClientOptions { + clientId?: string; + clientSecret?: string; + redirectUri?: string; + /** + * Customizable endpoints. + */ + endpoints?: Partial; + /** + * The allowed OAuth2 token issuers. + */ + issuers?: string[]; + /** + * The client authentication type. Supported values are basic, post, and none. + * Defaults to post if not provided. + * https://datatracker.ietf.org/doc/html/rfc7591#section-2 + */ + clientAuthentication?: ClientAuthentication; +} +export type RefreshOptions = Pick; +export declare class OAuth2Client extends AuthClient { + private redirectUri?; + private certificateCache; + private certificateExpiry; + private certificateCacheFormat; + protected refreshTokenPromises: Map>; + readonly endpoints: Readonly; + readonly issuers: string[]; + readonly clientAuthentication: ClientAuthentication; + _clientId?: string; + _clientSecret?: string; + refreshHandler?: GetRefreshHandlerCallback; + /** + * Handles OAuth2 flow for Google APIs. + * + * @param clientId The authentication client ID. + * @param clientSecret The authentication client secret. + * @param redirectUri The URI to redirect to after completing the auth + * request. + * @param opts optional options for overriding the given parameters. + * @constructor + */ + constructor(options?: OAuth2ClientOptions); + constructor(clientId?: string, clientSecret?: string, redirectUri?: string); + /** + * @deprecated use instance's {@link OAuth2Client.endpoints} + */ + protected static readonly GOOGLE_TOKEN_INFO_URL = "https://oauth2.googleapis.com/tokeninfo"; + /** + * Clock skew - five minutes in seconds + */ + private static readonly CLOCK_SKEW_SECS_; + /** + * The default max Token Lifetime is one day in seconds + */ + private static readonly DEFAULT_MAX_TOKEN_LIFETIME_SECS_; + /** + * Generates URL for consent page landing. + * @param opts Options. + * @return URL to consent page. + */ + generateAuthUrl(opts?: GenerateAuthUrlOpts): string; + generateCodeVerifier(): void; + /** + * Convenience method to automatically generate a code_verifier, and its + * resulting SHA256. If used, this must be paired with a S256 + * code_challenge_method. + * + * For a full example see: + * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js + */ + generateCodeVerifierAsync(): Promise; + /** + * Gets the access token for the given code. + * @param code The authorization code. + * @param callback Optional callback fn. + */ + getToken(code: string): Promise; + getToken(options: GetTokenOptions): Promise; + getToken(code: string, callback: GetTokenCallback): void; + getToken(options: GetTokenOptions, callback: GetTokenCallback): void; + private getTokenAsync; + /** + * Refreshes the access token. + * @param refresh_token Existing refresh token. + * @private + */ + protected refreshToken(refreshToken?: string | null): Promise; + protected refreshTokenNoCache(refreshToken?: string | null): Promise; + /** + * Retrieves the access token using refresh token + * + * @param callback callback + */ + refreshAccessToken(): Promise; + refreshAccessToken(callback: RefreshAccessTokenCallback): void; + private refreshAccessTokenAsync; + /** + * Get a non-expired access token, after refreshing if necessary + * + * @param callback Callback to call with the access token + */ + getAccessToken(): Promise; + getAccessToken(callback: GetAccessTokenCallback): void; + private getAccessTokenAsync; + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * In OAuth2Client, the result has the form: + * { Authorization: 'Bearer ' } + * @param url The optional url being authorized + */ + getRequestHeaders(url?: string): Promise; + protected getRequestMetadataAsync(url?: string | URL | null): Promise; + /** + * Generates an URL to revoke the given token. + * @param token The existing token to be revoked. + * + * @deprecated use instance method {@link OAuth2Client.getRevokeTokenURL} + */ + static getRevokeTokenUrl(token: string): string; + /** + * Generates a URL to revoke the given token. + * + * @param token The existing token to be revoked. + */ + getRevokeTokenURL(token: string): URL; + /** + * Revokes the access given to token. + * @param token The existing token to be revoked. + * @param callback Optional callback fn. + */ + revokeToken(token: string): GaxiosPromise; + revokeToken(token: string, callback: BodyResponseCallback): void; + /** + * Revokes access token and clears the credentials object + * @param callback callback + */ + revokeCredentials(): GaxiosPromise; + revokeCredentials(callback: BodyResponseCallback): void; + private revokeCredentialsAsync; + /** + * Provides a request implementation with OAuth 2.0 flow. If credentials have + * a refresh_token, in cases of HTTP 401 and 403 responses, it automatically + * asks for a new access token and replays the unsuccessful request. + * @param opts Request options. + * @param callback callback. + * @return Request object + */ + request(opts: GaxiosOptions): GaxiosPromise; + request(opts: GaxiosOptions, callback: BodyResponseCallback): void; + protected requestAsync(opts: GaxiosOptions, reAuthRetried?: boolean): Promise>; + /** + * Verify id token is token by checking the certs and audience + * @param options that contains all options. + * @param callback Callback supplying GoogleLogin if successful + */ + verifyIdToken(options: VerifyIdTokenOptions): Promise; + verifyIdToken(options: VerifyIdTokenOptions, callback: (err: Error | null, login?: LoginTicket) => void): void; + private verifyIdTokenAsync; + /** + * Obtains information about the provisioned access token. Especially useful + * if you want to check the scopes that were provisioned to a given token. + * + * @param accessToken Required. The Access Token for which you want to get + * user info. + */ + getTokenInfo(accessToken: string): Promise; + /** + * Gets federated sign-on certificates to use for verifying identity tokens. + * Returns certs as array structure, where keys are key ids, and values + * are certificates in either PEM or JWK format. + * @param callback Callback supplying the certificates + */ + getFederatedSignonCerts(): Promise; + getFederatedSignonCerts(callback: GetFederatedSignonCertsCallback): void; + getFederatedSignonCertsAsync(): Promise; + /** + * Gets federated sign-on certificates to use for verifying identity tokens. + * Returns certs as array structure, where keys are key ids, and values + * are certificates in either PEM or JWK format. + * @param callback Callback supplying the certificates + */ + getIapPublicKeys(): Promise; + getIapPublicKeys(callback: GetIapPublicKeysCallback): void; + getIapPublicKeysAsync(): Promise; + verifySignedJwtWithCerts(): void; + /** + * Verify the id token is signed with the correct certificate + * and is from the correct audience. + * @param jwt The jwt to verify (The ID Token in this case). + * @param certs The array of certs to test the jwt against. + * @param requiredAudience The audience to test the jwt against. + * @param issuers The allowed issuers of the jwt (Optional). + * @param maxExpiry The max expiry the certificate can be (Optional). + * @return Returns a promise resolving to LoginTicket on verification. + */ + verifySignedJwtWithCertsAsync(jwt: string, certs: Certificates | PublicKeys, requiredAudience?: string | string[], issuers?: string[], maxExpiry?: number): Promise; + /** + * Returns a promise that resolves with AccessTokenResponse type if + * refreshHandler is defined. + * If not, nothing is returned. + */ + private processAndValidateRefreshHandler; + /** + * Returns true if a token is expired or will expire within + * eagerRefreshThresholdMillismilliseconds. + * If there is no expiry time, assumes the token is not expired or expiring. + */ + protected isTokenExpiring(): boolean; +} diff --git a/node_modules/google-auth-library/build/src/auth/oauth2client.js b/node_modules/google-auth-library/build/src/auth/oauth2client.js new file mode 100644 index 0000000..3764bda --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/oauth2client.js @@ -0,0 +1,794 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OAuth2Client = exports.ClientAuthentication = exports.CertificateFormat = exports.CodeChallengeMethod = void 0; +const gaxios_1 = require("gaxios"); +const querystring = require("querystring"); +const stream = require("stream"); +const formatEcdsa = require("ecdsa-sig-formatter"); +const crypto_1 = require("../crypto/crypto"); +const authclient_1 = require("./authclient"); +const loginticket_1 = require("./loginticket"); +var CodeChallengeMethod; +(function (CodeChallengeMethod) { + CodeChallengeMethod["Plain"] = "plain"; + CodeChallengeMethod["S256"] = "S256"; +})(CodeChallengeMethod || (exports.CodeChallengeMethod = CodeChallengeMethod = {})); +var CertificateFormat; +(function (CertificateFormat) { + CertificateFormat["PEM"] = "PEM"; + CertificateFormat["JWK"] = "JWK"; +})(CertificateFormat || (exports.CertificateFormat = CertificateFormat = {})); +/** + * The client authentication type. Supported values are basic, post, and none. + * https://datatracker.ietf.org/doc/html/rfc7591#section-2 + */ +var ClientAuthentication; +(function (ClientAuthentication) { + ClientAuthentication["ClientSecretPost"] = "ClientSecretPost"; + ClientAuthentication["ClientSecretBasic"] = "ClientSecretBasic"; + ClientAuthentication["None"] = "None"; +})(ClientAuthentication || (exports.ClientAuthentication = ClientAuthentication = {})); +class OAuth2Client extends authclient_1.AuthClient { + constructor(optionsOrClientId, clientSecret, redirectUri) { + const opts = optionsOrClientId && typeof optionsOrClientId === 'object' + ? optionsOrClientId + : { clientId: optionsOrClientId, clientSecret, redirectUri }; + super(opts); + this.certificateCache = {}; + this.certificateExpiry = null; + this.certificateCacheFormat = CertificateFormat.PEM; + this.refreshTokenPromises = new Map(); + this._clientId = opts.clientId; + this._clientSecret = opts.clientSecret; + this.redirectUri = opts.redirectUri; + this.endpoints = { + tokenInfoUrl: 'https://oauth2.googleapis.com/tokeninfo', + oauth2AuthBaseUrl: 'https://accounts.google.com/o/oauth2/v2/auth', + oauth2TokenUrl: 'https://oauth2.googleapis.com/token', + oauth2RevokeUrl: 'https://oauth2.googleapis.com/revoke', + oauth2FederatedSignonPemCertsUrl: 'https://www.googleapis.com/oauth2/v1/certs', + oauth2FederatedSignonJwkCertsUrl: 'https://www.googleapis.com/oauth2/v3/certs', + oauth2IapPublicKeyUrl: 'https://www.gstatic.com/iap/verify/public_key', + ...opts.endpoints, + }; + this.clientAuthentication = + opts.clientAuthentication || ClientAuthentication.ClientSecretPost; + this.issuers = opts.issuers || [ + 'accounts.google.com', + 'https://accounts.google.com', + this.universeDomain, + ]; + } + /** + * Generates URL for consent page landing. + * @param opts Options. + * @return URL to consent page. + */ + generateAuthUrl(opts = {}) { + if (opts.code_challenge_method && !opts.code_challenge) { + throw new Error('If a code_challenge_method is provided, code_challenge must be included.'); + } + opts.response_type = opts.response_type || 'code'; + opts.client_id = opts.client_id || this._clientId; + opts.redirect_uri = opts.redirect_uri || this.redirectUri; + // Allow scopes to be passed either as array or a string + if (Array.isArray(opts.scope)) { + opts.scope = opts.scope.join(' '); + } + const rootUrl = this.endpoints.oauth2AuthBaseUrl.toString(); + return (rootUrl + + '?' + + querystring.stringify(opts)); + } + generateCodeVerifier() { + // To make the code compatible with browser SubtleCrypto we need to make + // this method async. + throw new Error('generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.'); + } + /** + * Convenience method to automatically generate a code_verifier, and its + * resulting SHA256. If used, this must be paired with a S256 + * code_challenge_method. + * + * For a full example see: + * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js + */ + async generateCodeVerifierAsync() { + // base64 encoding uses 6 bits per character, and we want to generate128 + // characters. 6*128/8 = 96. + const crypto = (0, crypto_1.createCrypto)(); + const randomString = crypto.randomBytesBase64(96); + // The valid characters in the code_verifier are [A-Z]/[a-z]/[0-9]/ + // "-"/"."/"_"/"~". Base64 encoded strings are pretty close, so we're just + // swapping out a few chars. + const codeVerifier = randomString + .replace(/\+/g, '~') + .replace(/=/g, '_') + .replace(/\//g, '-'); + // Generate the base64 encoded SHA256 + const unencodedCodeChallenge = await crypto.sha256DigestBase64(codeVerifier); + // We need to use base64UrlEncoding instead of standard base64 + const codeChallenge = unencodedCodeChallenge + .split('=')[0] + .replace(/\+/g, '-') + .replace(/\//g, '_'); + return { codeVerifier, codeChallenge }; + } + getToken(codeOrOptions, callback) { + const options = typeof codeOrOptions === 'string' ? { code: codeOrOptions } : codeOrOptions; + if (callback) { + this.getTokenAsync(options).then(r => callback(null, r.tokens, r.res), e => callback(e, null, e.response)); + } + else { + return this.getTokenAsync(options); + } + } + async getTokenAsync(options) { + const url = this.endpoints.oauth2TokenUrl.toString(); + const headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + }; + const values = { + client_id: options.client_id || this._clientId, + code_verifier: options.codeVerifier, + code: options.code, + grant_type: 'authorization_code', + redirect_uri: options.redirect_uri || this.redirectUri, + }; + if (this.clientAuthentication === ClientAuthentication.ClientSecretBasic) { + const basic = Buffer.from(`${this._clientId}:${this._clientSecret}`); + headers['Authorization'] = `Basic ${basic.toString('base64')}`; + } + if (this.clientAuthentication === ClientAuthentication.ClientSecretPost) { + values.client_secret = this._clientSecret; + } + const res = await this.transporter.request({ + ...OAuth2Client.RETRY_CONFIG, + method: 'POST', + url, + data: querystring.stringify(values), + headers, + }); + const tokens = res.data; + if (res.data && res.data.expires_in) { + tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000; + delete tokens.expires_in; + } + this.emit('tokens', tokens); + return { tokens, res }; + } + /** + * Refreshes the access token. + * @param refresh_token Existing refresh token. + * @private + */ + async refreshToken(refreshToken) { + if (!refreshToken) { + return this.refreshTokenNoCache(refreshToken); + } + // If a request to refresh using the same token has started, + // return the same promise. + if (this.refreshTokenPromises.has(refreshToken)) { + return this.refreshTokenPromises.get(refreshToken); + } + const p = this.refreshTokenNoCache(refreshToken).then(r => { + this.refreshTokenPromises.delete(refreshToken); + return r; + }, e => { + this.refreshTokenPromises.delete(refreshToken); + throw e; + }); + this.refreshTokenPromises.set(refreshToken, p); + return p; + } + async refreshTokenNoCache(refreshToken) { + var _a; + if (!refreshToken) { + throw new Error('No refresh token is set.'); + } + const url = this.endpoints.oauth2TokenUrl.toString(); + const data = { + refresh_token: refreshToken, + client_id: this._clientId, + client_secret: this._clientSecret, + grant_type: 'refresh_token', + }; + let res; + try { + // request for new token + res = await this.transporter.request({ + ...OAuth2Client.RETRY_CONFIG, + method: 'POST', + url, + data: querystring.stringify(data), + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + }); + } + catch (e) { + if (e instanceof gaxios_1.GaxiosError && + e.message === 'invalid_grant' && + ((_a = e.response) === null || _a === void 0 ? void 0 : _a.data) && + /ReAuth/i.test(e.response.data.error_description)) { + e.message = JSON.stringify(e.response.data); + } + throw e; + } + const tokens = res.data; + // TODO: de-duplicate this code from a few spots + if (res.data && res.data.expires_in) { + tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000; + delete tokens.expires_in; + } + this.emit('tokens', tokens); + return { tokens, res }; + } + refreshAccessToken(callback) { + if (callback) { + this.refreshAccessTokenAsync().then(r => callback(null, r.credentials, r.res), callback); + } + else { + return this.refreshAccessTokenAsync(); + } + } + async refreshAccessTokenAsync() { + const r = await this.refreshToken(this.credentials.refresh_token); + const tokens = r.tokens; + tokens.refresh_token = this.credentials.refresh_token; + this.credentials = tokens; + return { credentials: this.credentials, res: r.res }; + } + getAccessToken(callback) { + if (callback) { + this.getAccessTokenAsync().then(r => callback(null, r.token, r.res), callback); + } + else { + return this.getAccessTokenAsync(); + } + } + async getAccessTokenAsync() { + const shouldRefresh = !this.credentials.access_token || this.isTokenExpiring(); + if (shouldRefresh) { + if (!this.credentials.refresh_token) { + if (this.refreshHandler) { + const refreshedAccessToken = await this.processAndValidateRefreshHandler(); + if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) { + this.setCredentials(refreshedAccessToken); + return { token: this.credentials.access_token }; + } + } + else { + throw new Error('No refresh token or refresh handler callback is set.'); + } + } + const r = await this.refreshAccessTokenAsync(); + if (!r.credentials || (r.credentials && !r.credentials.access_token)) { + throw new Error('Could not refresh access token.'); + } + return { token: r.credentials.access_token, res: r.res }; + } + else { + return { token: this.credentials.access_token }; + } + } + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * In OAuth2Client, the result has the form: + * { Authorization: 'Bearer ' } + * @param url The optional url being authorized + */ + async getRequestHeaders(url) { + const headers = (await this.getRequestMetadataAsync(url)).headers; + return headers; + } + async getRequestMetadataAsync( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + url) { + const thisCreds = this.credentials; + if (!thisCreds.access_token && + !thisCreds.refresh_token && + !this.apiKey && + !this.refreshHandler) { + throw new Error('No access, refresh token, API key or refresh handler callback is set.'); + } + if (thisCreds.access_token && !this.isTokenExpiring()) { + thisCreds.token_type = thisCreds.token_type || 'Bearer'; + const headers = { + Authorization: thisCreds.token_type + ' ' + thisCreds.access_token, + }; + return { headers: this.addSharedMetadataHeaders(headers) }; + } + // If refreshHandler exists, call processAndValidateRefreshHandler(). + if (this.refreshHandler) { + const refreshedAccessToken = await this.processAndValidateRefreshHandler(); + if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) { + this.setCredentials(refreshedAccessToken); + const headers = { + Authorization: 'Bearer ' + this.credentials.access_token, + }; + return { headers: this.addSharedMetadataHeaders(headers) }; + } + } + if (this.apiKey) { + return { headers: { 'X-Goog-Api-Key': this.apiKey } }; + } + let r = null; + let tokens = null; + try { + r = await this.refreshToken(thisCreds.refresh_token); + tokens = r.tokens; + } + catch (err) { + const e = err; + if (e.response && + (e.response.status === 403 || e.response.status === 404)) { + e.message = `Could not refresh access token: ${e.message}`; + } + throw e; + } + const credentials = this.credentials; + credentials.token_type = credentials.token_type || 'Bearer'; + tokens.refresh_token = credentials.refresh_token; + this.credentials = tokens; + const headers = { + Authorization: credentials.token_type + ' ' + tokens.access_token, + }; + return { headers: this.addSharedMetadataHeaders(headers), res: r.res }; + } + /** + * Generates an URL to revoke the given token. + * @param token The existing token to be revoked. + * + * @deprecated use instance method {@link OAuth2Client.getRevokeTokenURL} + */ + static getRevokeTokenUrl(token) { + return new OAuth2Client().getRevokeTokenURL(token).toString(); + } + /** + * Generates a URL to revoke the given token. + * + * @param token The existing token to be revoked. + */ + getRevokeTokenURL(token) { + const url = new URL(this.endpoints.oauth2RevokeUrl); + url.searchParams.append('token', token); + return url; + } + revokeToken(token, callback) { + const opts = { + ...OAuth2Client.RETRY_CONFIG, + url: this.getRevokeTokenURL(token).toString(), + method: 'POST', + }; + if (callback) { + this.transporter + .request(opts) + .then(r => callback(null, r), callback); + } + else { + return this.transporter.request(opts); + } + } + revokeCredentials(callback) { + if (callback) { + this.revokeCredentialsAsync().then(res => callback(null, res), callback); + } + else { + return this.revokeCredentialsAsync(); + } + } + async revokeCredentialsAsync() { + const token = this.credentials.access_token; + this.credentials = {}; + if (token) { + return this.revokeToken(token); + } + else { + throw new Error('No access token to revoke.'); + } + } + request(opts, callback) { + if (callback) { + this.requestAsync(opts).then(r => callback(null, r), e => { + return callback(e, e.response); + }); + } + else { + return this.requestAsync(opts); + } + } + async requestAsync(opts, reAuthRetried = false) { + let r2; + try { + const r = await this.getRequestMetadataAsync(opts.url); + opts.headers = opts.headers || {}; + if (r.headers && r.headers['x-goog-user-project']) { + opts.headers['x-goog-user-project'] = r.headers['x-goog-user-project']; + } + if (r.headers && r.headers.Authorization) { + opts.headers.Authorization = r.headers.Authorization; + } + if (this.apiKey) { + opts.headers['X-Goog-Api-Key'] = this.apiKey; + } + r2 = await this.transporter.request(opts); + } + catch (e) { + const res = e.response; + if (res) { + const statusCode = res.status; + // Retry the request for metadata if the following criteria are true: + // - We haven't already retried. It only makes sense to retry once. + // - The response was a 401 or a 403 + // - The request didn't send a readableStream + // - An access_token and refresh_token were available, but either no + // expiry_date was available or the forceRefreshOnFailure flag is set. + // The absent expiry_date case can happen when developers stash the + // access_token and refresh_token for later use, but the access_token + // fails on the first try because it's expired. Some developers may + // choose to enable forceRefreshOnFailure to mitigate time-related + // errors. + // Or the following criteria are true: + // - We haven't already retried. It only makes sense to retry once. + // - The response was a 401 or a 403 + // - The request didn't send a readableStream + // - No refresh_token was available + // - An access_token and a refreshHandler callback were available, but + // either no expiry_date was available or the forceRefreshOnFailure + // flag is set. The access_token fails on the first try because it's + // expired. Some developers may choose to enable forceRefreshOnFailure + // to mitigate time-related errors. + const mayRequireRefresh = this.credentials && + this.credentials.access_token && + this.credentials.refresh_token && + (!this.credentials.expiry_date || this.forceRefreshOnFailure); + const mayRequireRefreshWithNoRefreshToken = this.credentials && + this.credentials.access_token && + !this.credentials.refresh_token && + (!this.credentials.expiry_date || this.forceRefreshOnFailure) && + this.refreshHandler; + const isReadableStream = res.config.data instanceof stream.Readable; + const isAuthErr = statusCode === 401 || statusCode === 403; + if (!reAuthRetried && + isAuthErr && + !isReadableStream && + mayRequireRefresh) { + await this.refreshAccessTokenAsync(); + return this.requestAsync(opts, true); + } + else if (!reAuthRetried && + isAuthErr && + !isReadableStream && + mayRequireRefreshWithNoRefreshToken) { + const refreshedAccessToken = await this.processAndValidateRefreshHandler(); + if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) { + this.setCredentials(refreshedAccessToken); + } + return this.requestAsync(opts, true); + } + } + throw e; + } + return r2; + } + verifyIdToken(options, callback) { + // This function used to accept two arguments instead of an options object. + // Check the types to help users upgrade with less pain. + // This check can be removed after a 2.0 release. + if (callback && typeof callback !== 'function') { + throw new Error('This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.'); + } + if (callback) { + this.verifyIdTokenAsync(options).then(r => callback(null, r), callback); + } + else { + return this.verifyIdTokenAsync(options); + } + } + async verifyIdTokenAsync(options) { + if (!options.idToken) { + throw new Error('The verifyIdToken method requires an ID Token'); + } + const response = await this.getFederatedSignonCertsAsync(); + const login = await this.verifySignedJwtWithCertsAsync(options.idToken, response.certs, options.audience, this.issuers, options.maxExpiry); + return login; + } + /** + * Obtains information about the provisioned access token. Especially useful + * if you want to check the scopes that were provisioned to a given token. + * + * @param accessToken Required. The Access Token for which you want to get + * user info. + */ + async getTokenInfo(accessToken) { + const { data } = await this.transporter.request({ + ...OAuth2Client.RETRY_CONFIG, + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + Authorization: `Bearer ${accessToken}`, + }, + url: this.endpoints.tokenInfoUrl.toString(), + }); + const info = Object.assign({ + expiry_date: new Date().getTime() + data.expires_in * 1000, + scopes: data.scope.split(' '), + }, data); + delete info.expires_in; + delete info.scope; + return info; + } + getFederatedSignonCerts(callback) { + if (callback) { + this.getFederatedSignonCertsAsync().then(r => callback(null, r.certs, r.res), callback); + } + else { + return this.getFederatedSignonCertsAsync(); + } + } + async getFederatedSignonCertsAsync() { + const nowTime = new Date().getTime(); + const format = (0, crypto_1.hasBrowserCrypto)() + ? CertificateFormat.JWK + : CertificateFormat.PEM; + if (this.certificateExpiry && + nowTime < this.certificateExpiry.getTime() && + this.certificateCacheFormat === format) { + return { certs: this.certificateCache, format }; + } + let res; + let url; + switch (format) { + case CertificateFormat.PEM: + url = this.endpoints.oauth2FederatedSignonPemCertsUrl.toString(); + break; + case CertificateFormat.JWK: + url = this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString(); + break; + default: + throw new Error(`Unsupported certificate format ${format}`); + } + try { + res = await this.transporter.request({ + ...OAuth2Client.RETRY_CONFIG, + url, + }); + } + catch (e) { + if (e instanceof Error) { + e.message = `Failed to retrieve verification certificates: ${e.message}`; + } + throw e; + } + const cacheControl = res ? res.headers['cache-control'] : undefined; + let cacheAge = -1; + if (cacheControl) { + const pattern = new RegExp('max-age=([0-9]*)'); + const regexResult = pattern.exec(cacheControl); + if (regexResult && regexResult.length === 2) { + // Cache results with max-age (in seconds) + cacheAge = Number(regexResult[1]) * 1000; // milliseconds + } + } + let certificates = {}; + switch (format) { + case CertificateFormat.PEM: + certificates = res.data; + break; + case CertificateFormat.JWK: + for (const key of res.data.keys) { + certificates[key.kid] = key; + } + break; + default: + throw new Error(`Unsupported certificate format ${format}`); + } + const now = new Date(); + this.certificateExpiry = + cacheAge === -1 ? null : new Date(now.getTime() + cacheAge); + this.certificateCache = certificates; + this.certificateCacheFormat = format; + return { certs: certificates, format, res }; + } + getIapPublicKeys(callback) { + if (callback) { + this.getIapPublicKeysAsync().then(r => callback(null, r.pubkeys, r.res), callback); + } + else { + return this.getIapPublicKeysAsync(); + } + } + async getIapPublicKeysAsync() { + let res; + const url = this.endpoints.oauth2IapPublicKeyUrl.toString(); + try { + res = await this.transporter.request({ + ...OAuth2Client.RETRY_CONFIG, + url, + }); + } + catch (e) { + if (e instanceof Error) { + e.message = `Failed to retrieve verification certificates: ${e.message}`; + } + throw e; + } + return { pubkeys: res.data, res }; + } + verifySignedJwtWithCerts() { + // To make the code compatible with browser SubtleCrypto we need to make + // this method async. + throw new Error('verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.'); + } + /** + * Verify the id token is signed with the correct certificate + * and is from the correct audience. + * @param jwt The jwt to verify (The ID Token in this case). + * @param certs The array of certs to test the jwt against. + * @param requiredAudience The audience to test the jwt against. + * @param issuers The allowed issuers of the jwt (Optional). + * @param maxExpiry The max expiry the certificate can be (Optional). + * @return Returns a promise resolving to LoginTicket on verification. + */ + async verifySignedJwtWithCertsAsync(jwt, certs, requiredAudience, issuers, maxExpiry) { + const crypto = (0, crypto_1.createCrypto)(); + if (!maxExpiry) { + maxExpiry = OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_; + } + const segments = jwt.split('.'); + if (segments.length !== 3) { + throw new Error('Wrong number of segments in token: ' + jwt); + } + const signed = segments[0] + '.' + segments[1]; + let signature = segments[2]; + let envelope; + let payload; + try { + envelope = JSON.parse(crypto.decodeBase64StringUtf8(segments[0])); + } + catch (err) { + if (err instanceof Error) { + err.message = `Can't parse token envelope: ${segments[0]}': ${err.message}`; + } + throw err; + } + if (!envelope) { + throw new Error("Can't parse token envelope: " + segments[0]); + } + try { + payload = JSON.parse(crypto.decodeBase64StringUtf8(segments[1])); + } + catch (err) { + if (err instanceof Error) { + err.message = `Can't parse token payload '${segments[0]}`; + } + throw err; + } + if (!payload) { + throw new Error("Can't parse token payload: " + segments[1]); + } + if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) { + // If this is not present, then there's no reason to attempt verification + throw new Error('No pem found for envelope: ' + JSON.stringify(envelope)); + } + const cert = certs[envelope.kid]; + if (envelope.alg === 'ES256') { + signature = formatEcdsa.joseToDer(signature, 'ES256').toString('base64'); + } + const verified = await crypto.verify(cert, signed, signature); + if (!verified) { + throw new Error('Invalid token signature: ' + jwt); + } + if (!payload.iat) { + throw new Error('No issue time in token: ' + JSON.stringify(payload)); + } + if (!payload.exp) { + throw new Error('No expiration time in token: ' + JSON.stringify(payload)); + } + const iat = Number(payload.iat); + if (isNaN(iat)) + throw new Error('iat field using invalid format'); + const exp = Number(payload.exp); + if (isNaN(exp)) + throw new Error('exp field using invalid format'); + const now = new Date().getTime() / 1000; + if (exp >= now + maxExpiry) { + throw new Error('Expiration time too far in future: ' + JSON.stringify(payload)); + } + const earliest = iat - OAuth2Client.CLOCK_SKEW_SECS_; + const latest = exp + OAuth2Client.CLOCK_SKEW_SECS_; + if (now < earliest) { + throw new Error('Token used too early, ' + + now + + ' < ' + + earliest + + ': ' + + JSON.stringify(payload)); + } + if (now > latest) { + throw new Error('Token used too late, ' + + now + + ' > ' + + latest + + ': ' + + JSON.stringify(payload)); + } + if (issuers && issuers.indexOf(payload.iss) < 0) { + throw new Error('Invalid issuer, expected one of [' + + issuers + + '], but got ' + + payload.iss); + } + // Check the audience matches if we have one + if (typeof requiredAudience !== 'undefined' && requiredAudience !== null) { + const aud = payload.aud; + let audVerified = false; + // If the requiredAudience is an array, check if it contains token + // audience + if (requiredAudience.constructor === Array) { + audVerified = requiredAudience.indexOf(aud) > -1; + } + else { + audVerified = aud === requiredAudience; + } + if (!audVerified) { + throw new Error('Wrong recipient, payload audience != requiredAudience'); + } + } + return new loginticket_1.LoginTicket(envelope, payload); + } + /** + * Returns a promise that resolves with AccessTokenResponse type if + * refreshHandler is defined. + * If not, nothing is returned. + */ + async processAndValidateRefreshHandler() { + if (this.refreshHandler) { + const accessTokenResponse = await this.refreshHandler(); + if (!accessTokenResponse.access_token) { + throw new Error('No access token is returned by the refreshHandler callback.'); + } + return accessTokenResponse; + } + return; + } + /** + * Returns true if a token is expired or will expire within + * eagerRefreshThresholdMillismilliseconds. + * If there is no expiry time, assumes the token is not expired or expiring. + */ + isTokenExpiring() { + const expiryDate = this.credentials.expiry_date; + return expiryDate + ? expiryDate <= new Date().getTime() + this.eagerRefreshThresholdMillis + : false; + } +} +exports.OAuth2Client = OAuth2Client; +/** + * @deprecated use instance's {@link OAuth2Client.endpoints} + */ +OAuth2Client.GOOGLE_TOKEN_INFO_URL = 'https://oauth2.googleapis.com/tokeninfo'; +/** + * Clock skew - five minutes in seconds + */ +OAuth2Client.CLOCK_SKEW_SECS_ = 300; +/** + * The default max Token Lifetime is one day in seconds + */ +OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_ = 86400; diff --git a/node_modules/google-auth-library/build/src/auth/oauth2common.d.ts b/node_modules/google-auth-library/build/src/auth/oauth2common.d.ts new file mode 100644 index 0000000..84916be --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/oauth2common.d.ts @@ -0,0 +1,92 @@ +import { GaxiosOptions } from 'gaxios'; +/** + * OAuth error codes. + * https://tools.ietf.org/html/rfc6749#section-5.2 + */ +type OAuthErrorCode = 'invalid_request' | 'invalid_client' | 'invalid_grant' | 'unauthorized_client' | 'unsupported_grant_type' | 'invalid_scope' | string; +/** + * The standard OAuth error response. + * https://tools.ietf.org/html/rfc6749#section-5.2 + */ +export interface OAuthErrorResponse { + error: OAuthErrorCode; + error_description?: string; + error_uri?: string; +} +/** + * OAuth client authentication types. + * https://tools.ietf.org/html/rfc6749#section-2.3 + */ +export type ConfidentialClientType = 'basic' | 'request-body'; +/** + * Defines the client authentication credentials for basic and request-body + * credentials. + * https://tools.ietf.org/html/rfc6749#section-2.3.1 + */ +export interface ClientAuthentication { + confidentialClientType: ConfidentialClientType; + clientId: string; + clientSecret?: string; +} +/** + * Abstract class for handling client authentication in OAuth-based + * operations. + * When request-body client authentication is used, only application/json and + * application/x-www-form-urlencoded content types for HTTP methods that support + * request bodies are supported. + */ +export declare abstract class OAuthClientAuthHandler { + private readonly clientAuthentication?; + private crypto; + /** + * Instantiates an OAuth client authentication handler. + * @param clientAuthentication The client auth credentials. + */ + constructor(clientAuthentication?: ClientAuthentication | undefined); + /** + * Applies client authentication on the OAuth request's headers or POST + * body but does not process the request. + * @param opts The GaxiosOptions whose headers or data are to be modified + * depending on the client authentication mechanism to be used. + * @param bearerToken The optional bearer token to use for authentication. + * When this is used, no client authentication credentials are needed. + */ + protected applyClientAuthenticationOptions(opts: GaxiosOptions, bearerToken?: string): void; + /** + * Applies client authentication on the request's header if either + * basic authentication or bearer token authentication is selected. + * + * @param opts The GaxiosOptions whose headers or data are to be modified + * depending on the client authentication mechanism to be used. + * @param bearerToken The optional bearer token to use for authentication. + * When this is used, no client authentication credentials are needed. + */ + private injectAuthenticatedHeaders; + /** + * Applies client authentication on the request's body if request-body + * client authentication is selected. + * + * @param opts The GaxiosOptions whose headers or data are to be modified + * depending on the client authentication mechanism to be used. + */ + private injectAuthenticatedRequestBody; + /** + * Retry config for Auth-related requests. + * + * @remarks + * + * This is not a part of the default {@link AuthClient.transporter transporter/gaxios} + * config as some downstream APIs would prefer if customers explicitly enable retries, + * such as GCS. + */ + protected static get RETRY_CONFIG(): GaxiosOptions; +} +/** + * Converts an OAuth error response to a native JavaScript Error. + * @param resp The OAuth error response to convert to a native Error object. + * @param err The optional original error. If provided, the error properties + * will be copied to the new error. + * @return The converted native Error object. + */ +export declare function getErrorFromOAuthErrorResponse(resp: OAuthErrorResponse, err?: Error): Error; +export {}; diff --git a/node_modules/google-auth-library/build/src/auth/oauth2common.js b/node_modules/google-auth-library/build/src/auth/oauth2common.js new file mode 100644 index 0000000..f580c1e --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/oauth2common.js @@ -0,0 +1,192 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OAuthClientAuthHandler = void 0; +exports.getErrorFromOAuthErrorResponse = getErrorFromOAuthErrorResponse; +const querystring = require("querystring"); +const crypto_1 = require("../crypto/crypto"); +/** List of HTTP methods that accept request bodies. */ +const METHODS_SUPPORTING_REQUEST_BODY = ['PUT', 'POST', 'PATCH']; +/** + * Abstract class for handling client authentication in OAuth-based + * operations. + * When request-body client authentication is used, only application/json and + * application/x-www-form-urlencoded content types for HTTP methods that support + * request bodies are supported. + */ +class OAuthClientAuthHandler { + /** + * Instantiates an OAuth client authentication handler. + * @param clientAuthentication The client auth credentials. + */ + constructor(clientAuthentication) { + this.clientAuthentication = clientAuthentication; + this.crypto = (0, crypto_1.createCrypto)(); + } + /** + * Applies client authentication on the OAuth request's headers or POST + * body but does not process the request. + * @param opts The GaxiosOptions whose headers or data are to be modified + * depending on the client authentication mechanism to be used. + * @param bearerToken The optional bearer token to use for authentication. + * When this is used, no client authentication credentials are needed. + */ + applyClientAuthenticationOptions(opts, bearerToken) { + // Inject authenticated header. + this.injectAuthenticatedHeaders(opts, bearerToken); + // Inject authenticated request body. + if (!bearerToken) { + this.injectAuthenticatedRequestBody(opts); + } + } + /** + * Applies client authentication on the request's header if either + * basic authentication or bearer token authentication is selected. + * + * @param opts The GaxiosOptions whose headers or data are to be modified + * depending on the client authentication mechanism to be used. + * @param bearerToken The optional bearer token to use for authentication. + * When this is used, no client authentication credentials are needed. + */ + injectAuthenticatedHeaders(opts, bearerToken) { + var _a; + // Bearer token prioritized higher than basic Auth. + if (bearerToken) { + opts.headers = opts.headers || {}; + Object.assign(opts.headers, { + Authorization: `Bearer ${bearerToken}}`, + }); + } + else if (((_a = this.clientAuthentication) === null || _a === void 0 ? void 0 : _a.confidentialClientType) === 'basic') { + opts.headers = opts.headers || {}; + const clientId = this.clientAuthentication.clientId; + const clientSecret = this.clientAuthentication.clientSecret || ''; + const base64EncodedCreds = this.crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`); + Object.assign(opts.headers, { + Authorization: `Basic ${base64EncodedCreds}`, + }); + } + } + /** + * Applies client authentication on the request's body if request-body + * client authentication is selected. + * + * @param opts The GaxiosOptions whose headers or data are to be modified + * depending on the client authentication mechanism to be used. + */ + injectAuthenticatedRequestBody(opts) { + var _a; + if (((_a = this.clientAuthentication) === null || _a === void 0 ? void 0 : _a.confidentialClientType) === 'request-body') { + const method = (opts.method || 'GET').toUpperCase(); + // Inject authenticated request body. + if (METHODS_SUPPORTING_REQUEST_BODY.indexOf(method) !== -1) { + // Get content-type. + let contentType; + const headers = opts.headers || {}; + for (const key in headers) { + if (key.toLowerCase() === 'content-type' && headers[key]) { + contentType = headers[key].toLowerCase(); + break; + } + } + if (contentType === 'application/x-www-form-urlencoded') { + opts.data = opts.data || ''; + const data = querystring.parse(opts.data); + Object.assign(data, { + client_id: this.clientAuthentication.clientId, + client_secret: this.clientAuthentication.clientSecret || '', + }); + opts.data = querystring.stringify(data); + } + else if (contentType === 'application/json') { + opts.data = opts.data || {}; + Object.assign(opts.data, { + client_id: this.clientAuthentication.clientId, + client_secret: this.clientAuthentication.clientSecret || '', + }); + } + else { + throw new Error(`${contentType} content-types are not supported with ` + + `${this.clientAuthentication.confidentialClientType} ` + + 'client authentication'); + } + } + else { + throw new Error(`${method} HTTP method does not support ` + + `${this.clientAuthentication.confidentialClientType} ` + + 'client authentication'); + } + } + } + /** + * Retry config for Auth-related requests. + * + * @remarks + * + * This is not a part of the default {@link AuthClient.transporter transporter/gaxios} + * config as some downstream APIs would prefer if customers explicitly enable retries, + * such as GCS. + */ + static get RETRY_CONFIG() { + return { + retry: true, + retryConfig: { + httpMethodsToRetry: ['GET', 'PUT', 'POST', 'HEAD', 'OPTIONS', 'DELETE'], + }, + }; + } +} +exports.OAuthClientAuthHandler = OAuthClientAuthHandler; +/** + * Converts an OAuth error response to a native JavaScript Error. + * @param resp The OAuth error response to convert to a native Error object. + * @param err The optional original error. If provided, the error properties + * will be copied to the new error. + * @return The converted native Error object. + */ +function getErrorFromOAuthErrorResponse(resp, err) { + // Error response. + const errorCode = resp.error; + const errorDescription = resp.error_description; + const errorUri = resp.error_uri; + let message = `Error code ${errorCode}`; + if (typeof errorDescription !== 'undefined') { + message += `: ${errorDescription}`; + } + if (typeof errorUri !== 'undefined') { + message += ` - ${errorUri}`; + } + const newError = new Error(message); + // Copy properties from original error to newly generated error. + if (err) { + const keys = Object.keys(err); + if (err.stack) { + // Copy error.stack if available. + keys.push('stack'); + } + keys.forEach(key => { + // Do not overwrite the message field. + if (key !== 'message') { + Object.defineProperty(newError, key, { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + value: err[key], + writable: false, + enumerable: true, + }); + } + }); + } + return newError; +} diff --git a/node_modules/google-auth-library/build/src/auth/passthrough.d.ts b/node_modules/google-auth-library/build/src/auth/passthrough.d.ts new file mode 100644 index 0000000..6ec4617 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/passthrough.d.ts @@ -0,0 +1,38 @@ +import { GaxiosOptions } from 'gaxios'; +import { AuthClient } from './authclient'; +import { GetAccessTokenResponse, Headers } from './oauth2client'; +/** + * An AuthClient without any Authentication information. Useful for: + * - Anonymous access + * - Local Emulators + * - Testing Environments + * + */ +export declare class PassThroughClient extends AuthClient { + /** + * Creates a request without any authentication headers or checks. + * + * @remarks + * + * In testing environments it may be useful to change the provided + * {@link AuthClient.transporter} for any desired request overrides/handling. + * + * @param opts + * @returns The response of the request. + */ + request(opts: GaxiosOptions): Promise>; + /** + * A required method of the base class. + * Always will return an empty object. + * + * @returns {} + */ + getAccessToken(): Promise; + /** + * A required method of the base class. + * Always will return an empty object. + * + * @returns {} + */ + getRequestHeaders(): Promise; +} diff --git a/node_modules/google-auth-library/build/src/auth/passthrough.js b/node_modules/google-auth-library/build/src/auth/passthrough.js new file mode 100644 index 0000000..07e9812 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/passthrough.js @@ -0,0 +1,61 @@ +"use strict"; +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PassThroughClient = void 0; +const authclient_1 = require("./authclient"); +/** + * An AuthClient without any Authentication information. Useful for: + * - Anonymous access + * - Local Emulators + * - Testing Environments + * + */ +class PassThroughClient extends authclient_1.AuthClient { + /** + * Creates a request without any authentication headers or checks. + * + * @remarks + * + * In testing environments it may be useful to change the provided + * {@link AuthClient.transporter} for any desired request overrides/handling. + * + * @param opts + * @returns The response of the request. + */ + async request(opts) { + return this.transporter.request(opts); + } + /** + * A required method of the base class. + * Always will return an empty object. + * + * @returns {} + */ + async getAccessToken() { + return {}; + } + /** + * A required method of the base class. + * Always will return an empty object. + * + * @returns {} + */ + async getRequestHeaders() { + return {}; + } +} +exports.PassThroughClient = PassThroughClient; +const a = new PassThroughClient(); +a.getAccessToken(); diff --git a/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.d.ts b/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.d.ts new file mode 100644 index 0000000..6b4e62f --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.d.ts @@ -0,0 +1,155 @@ +import { BaseExternalAccountClient, BaseExternalAccountClientOptions } from './baseexternalclient'; +import { AuthClientOptions } from './authclient'; +/** + * Defines the credential source portion of the configuration for PluggableAuthClient. + * + *

                          Command is the only required field. If timeout_millis is not specified, the library will + * default to a 30-second timeout. + * + *

                          + * Sample credential source for Pluggable Auth Client:
                          + * {
                          + *   ...
                          + *   "credential_source": {
                          + *     "executable": {
                          + *       "command": "/path/to/get/credentials.sh --arg1=value1 --arg2=value2",
                          + *       "timeout_millis": 5000,
                          + *       "output_file": "/path/to/generated/cached/credentials"
                          + *     }
                          + *   }
                          + * }
                          + * 
                          + */ +export interface PluggableAuthClientOptions extends BaseExternalAccountClientOptions { + credential_source: { + executable: { + /** + * The command used to retrieve the 3rd party token. + */ + command: string; + /** + * The timeout for executable to run in milliseconds. If none is provided it + * will be set to the default timeout of 30 seconds. + */ + timeout_millis?: number; + /** + * An optional output file location that will be checked for a cached response + * from a previous run of the executable. + */ + output_file?: string; + }; + }; +} +/** + * Error thrown from the executable run by PluggableAuthClient. + */ +export declare class ExecutableError extends Error { + /** + * The exit code returned by the executable. + */ + readonly code: string; + constructor(message: string, code: string); +} +/** + * PluggableAuthClient enables the exchange of workload identity pool external credentials for + * Google access tokens by retrieving 3rd party tokens through a user supplied executable. These + * scripts/executables are completely independent of the Google Cloud Auth libraries. These + * credentials plug into ADC and will call the specified executable to retrieve the 3rd party token + * to be exchanged for a Google access token. + * + *

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

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

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

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

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

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

                          Please see this repositories README for a complete executable request/response specification. + */ +export declare class PluggableAuthClient extends BaseExternalAccountClient { + /** + * The command used to retrieve the third party token. + */ + private readonly command; + /** + * The timeout in milliseconds for running executable, + * set to default if none provided. + */ + private readonly timeoutMillis; + /** + * The path to file to check for cached executable response. + */ + private readonly outputFile?; + /** + * Executable and output file handler. + */ + private readonly handler; + /** + * Instantiates a PluggableAuthClient instance using the provided JSON + * object loaded from an external account credentials file. + * An error is thrown if the credential is not a valid pluggable auth credential. + * @param options The external account options object typically loaded from + * the external account JSON credential file. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options: PluggableAuthClientOptions, additionalOptions?: AuthClientOptions); + /** + * Triggered when an external subject token is needed to be exchanged for a + * GCP access token via GCP STS endpoint. + * This uses the `options.credential_source` object to figure out how + * to retrieve the token using the current environment. In this case, + * this calls a user provided executable which returns the subject token. + * The logic is summarized as: + * 1. Validated that the executable is allowed to run. The + * GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment must be set to + * 1 for security reasons. + * 2. If an output file is specified by the user, check the file location + * for a response. If the file exists and contains a valid response, + * return the subject token from the file. + * 3. Call the provided executable and return response. + * @return A promise that resolves with the external subject token. + */ + retrieveSubjectToken(): Promise; +} diff --git a/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js b/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js new file mode 100644 index 0000000..acb299d --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js @@ -0,0 +1,215 @@ +"use strict"; +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PluggableAuthClient = exports.ExecutableError = void 0; +const baseexternalclient_1 = require("./baseexternalclient"); +const executable_response_1 = require("./executable-response"); +const pluggable_auth_handler_1 = require("./pluggable-auth-handler"); +/** + * Error thrown from the executable run by PluggableAuthClient. + */ +class ExecutableError extends Error { + constructor(message, code) { + super(`The executable failed with exit code: ${code} and error message: ${message}.`); + this.code = code; + Object.setPrototypeOf(this, new.target.prototype); + } +} +exports.ExecutableError = ExecutableError; +/** + * The default executable timeout when none is provided, in milliseconds. + */ +const DEFAULT_EXECUTABLE_TIMEOUT_MILLIS = 30 * 1000; +/** + * The minimum allowed executable timeout in milliseconds. + */ +const MINIMUM_EXECUTABLE_TIMEOUT_MILLIS = 5 * 1000; +/** + * The maximum allowed executable timeout in milliseconds. + */ +const MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS = 120 * 1000; +/** + * The environment variable to check to see if executable can be run. + * Value must be set to '1' for the executable to run. + */ +const GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES = 'GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES'; +/** + * The maximum currently supported executable version. + */ +const MAXIMUM_EXECUTABLE_VERSION = 1; +/** + * PluggableAuthClient enables the exchange of workload identity pool external credentials for + * Google access tokens by retrieving 3rd party tokens through a user supplied executable. These + * scripts/executables are completely independent of the Google Cloud Auth libraries. These + * credentials plug into ADC and will call the specified executable to retrieve the 3rd party token + * to be exchanged for a Google access token. + * + *

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

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

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

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

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

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

                          Please see this repositories README for a complete executable request/response specification. + */ +class PluggableAuthClient extends baseexternalclient_1.BaseExternalAccountClient { + /** + * Instantiates a PluggableAuthClient instance using the provided JSON + * object loaded from an external account credentials file. + * An error is thrown if the credential is not a valid pluggable auth credential. + * @param options The external account options object typically loaded from + * the external account JSON credential file. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options, additionalOptions) { + super(options, additionalOptions); + if (!options.credential_source.executable) { + throw new Error('No valid Pluggable Auth "credential_source" provided.'); + } + this.command = options.credential_source.executable.command; + if (!this.command) { + throw new Error('No valid Pluggable Auth "credential_source" provided.'); + } + // Check if the provided timeout exists and if it is valid. + if (options.credential_source.executable.timeout_millis === undefined) { + this.timeoutMillis = DEFAULT_EXECUTABLE_TIMEOUT_MILLIS; + } + else { + this.timeoutMillis = options.credential_source.executable.timeout_millis; + if (this.timeoutMillis < MINIMUM_EXECUTABLE_TIMEOUT_MILLIS || + this.timeoutMillis > MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS) { + throw new Error(`Timeout must be between ${MINIMUM_EXECUTABLE_TIMEOUT_MILLIS} and ` + + `${MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS} milliseconds.`); + } + } + this.outputFile = options.credential_source.executable.output_file; + this.handler = new pluggable_auth_handler_1.PluggableAuthHandler({ + command: this.command, + timeoutMillis: this.timeoutMillis, + outputFile: this.outputFile, + }); + this.credentialSourceType = 'executable'; + } + /** + * Triggered when an external subject token is needed to be exchanged for a + * GCP access token via GCP STS endpoint. + * This uses the `options.credential_source` object to figure out how + * to retrieve the token using the current environment. In this case, + * this calls a user provided executable which returns the subject token. + * The logic is summarized as: + * 1. Validated that the executable is allowed to run. The + * GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment must be set to + * 1 for security reasons. + * 2. If an output file is specified by the user, check the file location + * for a response. If the file exists and contains a valid response, + * return the subject token from the file. + * 3. Call the provided executable and return response. + * @return A promise that resolves with the external subject token. + */ + async retrieveSubjectToken() { + // Check if the executable is allowed to run. + if (process.env[GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES] !== '1') { + throw new Error('Pluggable Auth executables need to be explicitly allowed to run by ' + + 'setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment ' + + 'Variable to 1.'); + } + let executableResponse = undefined; + // Try to get cached executable response from output file. + if (this.outputFile) { + executableResponse = await this.handler.retrieveCachedResponse(); + } + // If no response from output file, call the executable. + if (!executableResponse) { + // Set up environment map with required values for the executable. + const envMap = new Map(); + envMap.set('GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE', this.audience); + envMap.set('GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE', this.subjectTokenType); + // Always set to 0 because interactive mode is not supported. + envMap.set('GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE', '0'); + if (this.outputFile) { + envMap.set('GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE', this.outputFile); + } + const serviceAccountEmail = this.getServiceAccountEmail(); + if (serviceAccountEmail) { + envMap.set('GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL', serviceAccountEmail); + } + executableResponse = + await this.handler.retrieveResponseFromExecutable(envMap); + } + if (executableResponse.version > MAXIMUM_EXECUTABLE_VERSION) { + throw new Error(`Version of executable is not currently supported, maximum supported version is ${MAXIMUM_EXECUTABLE_VERSION}.`); + } + // Check that response was successful. + if (!executableResponse.success) { + throw new ExecutableError(executableResponse.errorMessage, executableResponse.errorCode); + } + // Check that response contains expiration time if output file was specified. + if (this.outputFile) { + if (!executableResponse.expirationTime) { + throw new executable_response_1.InvalidExpirationTimeFieldError('The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.'); + } + } + // Check that response is not expired. + if (executableResponse.isExpired()) { + throw new Error('Executable response is expired.'); + } + // Return subject token from response. + return executableResponse.subjectToken; + } +} +exports.PluggableAuthClient = PluggableAuthClient; diff --git a/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.d.ts b/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.d.ts new file mode 100644 index 0000000..e5ddd02 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.d.ts @@ -0,0 +1,51 @@ +import { ExecutableResponse } from './executable-response'; +/** + * Defines the options used for the PluggableAuthHandler class. + */ +export interface PluggableAuthHandlerOptions { + /** + * The command used to retrieve the third party token. + */ + command: string; + /** + * The timeout in milliseconds for running executable, + * set to default if none provided. + */ + timeoutMillis: number; + /** + * The path to file to check for cached executable response. + */ + outputFile?: string; +} +/** + * A handler used to retrieve 3rd party token responses from user defined + * executables and cached file output for the PluggableAuthClient class. + */ +export declare class PluggableAuthHandler { + private readonly commandComponents; + private readonly timeoutMillis; + private readonly outputFile?; + /** + * Instantiates a PluggableAuthHandler instance using the provided + * PluggableAuthHandlerOptions object. + */ + constructor(options: PluggableAuthHandlerOptions); + /** + * Calls user provided executable to get a 3rd party subject token and + * returns the response. + * @param envMap a Map of additional Environment Variables required for + * the executable. + * @return A promise that resolves with the executable response. + */ + retrieveResponseFromExecutable(envMap: Map): Promise; + /** + * Checks user provided output file for response from previous run of + * executable and return the response if it exists, is formatted correctly, and is not expired. + */ + retrieveCachedResponse(): Promise; + /** + * Parses given command string into component array, splitting on spaces unless + * spaces are between quotation marks. + */ + private static parseCommand; +} diff --git a/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js b/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js new file mode 100644 index 0000000..47fa276 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js @@ -0,0 +1,156 @@ +"use strict"; +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PluggableAuthHandler = void 0; +const pluggable_auth_client_1 = require("./pluggable-auth-client"); +const executable_response_1 = require("./executable-response"); +const childProcess = require("child_process"); +const fs = require("fs"); +/** + * A handler used to retrieve 3rd party token responses from user defined + * executables and cached file output for the PluggableAuthClient class. + */ +class PluggableAuthHandler { + /** + * Instantiates a PluggableAuthHandler instance using the provided + * PluggableAuthHandlerOptions object. + */ + constructor(options) { + if (!options.command) { + throw new Error('No command provided.'); + } + this.commandComponents = PluggableAuthHandler.parseCommand(options.command); + this.timeoutMillis = options.timeoutMillis; + if (!this.timeoutMillis) { + throw new Error('No timeoutMillis provided.'); + } + this.outputFile = options.outputFile; + } + /** + * Calls user provided executable to get a 3rd party subject token and + * returns the response. + * @param envMap a Map of additional Environment Variables required for + * the executable. + * @return A promise that resolves with the executable response. + */ + retrieveResponseFromExecutable(envMap) { + return new Promise((resolve, reject) => { + // Spawn process to run executable using added environment variables. + const child = childProcess.spawn(this.commandComponents[0], this.commandComponents.slice(1), { + env: { ...process.env, ...Object.fromEntries(envMap) }, + }); + let output = ''; + // Append stdout to output as executable runs. + child.stdout.on('data', (data) => { + output += data; + }); + // Append stderr as executable runs. + child.stderr.on('data', (err) => { + output += err; + }); + // Set up a timeout to end the child process and throw an error. + const timeout = setTimeout(() => { + // Kill child process and remove listeners so 'close' event doesn't get + // read after child process is killed. + child.removeAllListeners(); + child.kill(); + return reject(new Error('The executable failed to finish within the timeout specified.')); + }, this.timeoutMillis); + child.on('close', (code) => { + // Cancel timeout if executable closes before timeout is reached. + clearTimeout(timeout); + if (code === 0) { + // If the executable completed successfully, try to return the parsed response. + try { + const responseJson = JSON.parse(output); + const response = new executable_response_1.ExecutableResponse(responseJson); + return resolve(response); + } + catch (error) { + if (error instanceof executable_response_1.ExecutableResponseError) { + return reject(error); + } + return reject(new executable_response_1.ExecutableResponseError(`The executable returned an invalid response: ${output}`)); + } + } + else { + return reject(new pluggable_auth_client_1.ExecutableError(output, code.toString())); + } + }); + }); + } + /** + * Checks user provided output file for response from previous run of + * executable and return the response if it exists, is formatted correctly, and is not expired. + */ + async retrieveCachedResponse() { + if (!this.outputFile || this.outputFile.length === 0) { + return undefined; + } + let filePath; + try { + filePath = await fs.promises.realpath(this.outputFile); + } + catch (_a) { + // If file path cannot be resolved, return undefined. + return undefined; + } + if (!(await fs.promises.lstat(filePath)).isFile()) { + // If path does not lead to file, return undefined. + return undefined; + } + const responseString = await fs.promises.readFile(filePath, { + encoding: 'utf8', + }); + if (responseString === '') { + return undefined; + } + try { + const responseJson = JSON.parse(responseString); + const response = new executable_response_1.ExecutableResponse(responseJson); + // Check if response is successful and unexpired. + if (response.isValid()) { + return new executable_response_1.ExecutableResponse(responseJson); + } + return undefined; + } + catch (error) { + if (error instanceof executable_response_1.ExecutableResponseError) { + throw error; + } + throw new executable_response_1.ExecutableResponseError(`The output file contained an invalid response: ${responseString}`); + } + } + /** + * Parses given command string into component array, splitting on spaces unless + * spaces are between quotation marks. + */ + static parseCommand(command) { + // Split the command into components by splitting on spaces, + // unless spaces are contained in quotation marks. + const components = command.match(/(?:[^\s"]+|"[^"]*")+/g); + if (!components) { + throw new Error(`Provided command: "${command}" could not be parsed.`); + } + // Remove quotation marks from the beginning and end of each component if they are present. + for (let i = 0; i < components.length; i++) { + if (components[i][0] === '"' && components[i].slice(-1) === '"') { + components[i] = components[i].slice(1, -1); + } + } + return components; + } +} +exports.PluggableAuthHandler = PluggableAuthHandler; diff --git a/node_modules/google-auth-library/build/src/auth/refreshclient.d.ts b/node_modules/google-auth-library/build/src/auth/refreshclient.d.ts new file mode 100644 index 0000000..c84459a --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/refreshclient.d.ts @@ -0,0 +1,50 @@ +import * as stream from 'stream'; +import { JWTInput } from './credentials'; +import { GetTokenResponse, OAuth2Client, OAuth2ClientOptions } from './oauth2client'; +export declare const USER_REFRESH_ACCOUNT_TYPE = "authorized_user"; +export interface UserRefreshClientOptions extends OAuth2ClientOptions { + clientId?: string; + clientSecret?: string; + refreshToken?: string; +} +export declare class UserRefreshClient extends OAuth2Client { + _refreshToken?: string | null; + /** + * User Refresh Token credentials. + * + * @param clientId The authentication client ID. + * @param clientSecret The authentication client secret. + * @param refreshToken The authentication refresh token. + */ + constructor(clientId?: string, clientSecret?: string, refreshToken?: string); + constructor(options: UserRefreshClientOptions); + constructor(clientId?: string, clientSecret?: string, refreshToken?: string); + /** + * Refreshes the access token. + * @param refreshToken An ignored refreshToken.. + * @param callback Optional callback. + */ + protected refreshTokenNoCache(refreshToken?: string | null): Promise; + fetchIdToken(targetAudience: string): Promise; + /** + * Create a UserRefreshClient credentials instance using the given input + * options. + * @param json The input object. + */ + fromJSON(json: JWTInput): void; + /** + * Create a UserRefreshClient credentials instance using the given input + * stream. + * @param inputStream The input stream. + * @param callback Optional callback. + */ + fromStream(inputStream: stream.Readable): Promise; + fromStream(inputStream: stream.Readable, callback: (err?: Error) => void): void; + private fromStreamAsync; + /** + * Create a UserRefreshClient credentials instance using the given input + * options. + * @param json The input object. + */ + static fromJSON(json: JWTInput): UserRefreshClient; +} diff --git a/node_modules/google-auth-library/build/src/auth/refreshclient.js b/node_modules/google-auth-library/build/src/auth/refreshclient.js new file mode 100644 index 0000000..85a5f18 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/refreshclient.js @@ -0,0 +1,132 @@ +"use strict"; +// Copyright 2015 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UserRefreshClient = exports.USER_REFRESH_ACCOUNT_TYPE = void 0; +const oauth2client_1 = require("./oauth2client"); +const querystring_1 = require("querystring"); +exports.USER_REFRESH_ACCOUNT_TYPE = 'authorized_user'; +class UserRefreshClient extends oauth2client_1.OAuth2Client { + constructor(optionsOrClientId, clientSecret, refreshToken, eagerRefreshThresholdMillis, forceRefreshOnFailure) { + const opts = optionsOrClientId && typeof optionsOrClientId === 'object' + ? optionsOrClientId + : { + clientId: optionsOrClientId, + clientSecret, + refreshToken, + eagerRefreshThresholdMillis, + forceRefreshOnFailure, + }; + super(opts); + this._refreshToken = opts.refreshToken; + this.credentials.refresh_token = opts.refreshToken; + } + /** + * Refreshes the access token. + * @param refreshToken An ignored refreshToken.. + * @param callback Optional callback. + */ + async refreshTokenNoCache( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + refreshToken) { + return super.refreshTokenNoCache(this._refreshToken); + } + async fetchIdToken(targetAudience) { + const res = await this.transporter.request({ + ...UserRefreshClient.RETRY_CONFIG, + url: this.endpoints.oauth2TokenUrl, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + }, + method: 'POST', + data: (0, querystring_1.stringify)({ + client_id: this._clientId, + client_secret: this._clientSecret, + grant_type: 'refresh_token', + refresh_token: this._refreshToken, + target_audience: targetAudience, + }), + }); + return res.data.id_token; + } + /** + * Create a UserRefreshClient credentials instance using the given input + * options. + * @param json The input object. + */ + fromJSON(json) { + if (!json) { + throw new Error('Must pass in a JSON object containing the user refresh token'); + } + if (json.type !== 'authorized_user') { + throw new Error('The incoming JSON object does not have the "authorized_user" type'); + } + if (!json.client_id) { + throw new Error('The incoming JSON object does not contain a client_id field'); + } + if (!json.client_secret) { + throw new Error('The incoming JSON object does not contain a client_secret field'); + } + if (!json.refresh_token) { + throw new Error('The incoming JSON object does not contain a refresh_token field'); + } + this._clientId = json.client_id; + this._clientSecret = json.client_secret; + this._refreshToken = json.refresh_token; + this.credentials.refresh_token = json.refresh_token; + this.quotaProjectId = json.quota_project_id; + this.universeDomain = json.universe_domain || this.universeDomain; + } + fromStream(inputStream, callback) { + if (callback) { + this.fromStreamAsync(inputStream).then(() => callback(), callback); + } + else { + return this.fromStreamAsync(inputStream); + } + } + async fromStreamAsync(inputStream) { + return new Promise((resolve, reject) => { + if (!inputStream) { + return reject(new Error('Must pass in a stream containing the user refresh token.')); + } + let s = ''; + inputStream + .setEncoding('utf8') + .on('error', reject) + .on('data', chunk => (s += chunk)) + .on('end', () => { + try { + const data = JSON.parse(s); + this.fromJSON(data); + return resolve(); + } + catch (err) { + return reject(err); + } + }); + }); + } + /** + * Create a UserRefreshClient credentials instance using the given input + * options. + * @param json The input object. + */ + static fromJSON(json) { + const client = new UserRefreshClient(); + client.fromJSON(json); + return client; + } +} +exports.UserRefreshClient = UserRefreshClient; diff --git a/node_modules/google-auth-library/build/src/auth/stscredentials.d.ts b/node_modules/google-auth-library/build/src/auth/stscredentials.d.ts new file mode 100644 index 0000000..4c9adf5 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/stscredentials.d.ts @@ -0,0 +1,114 @@ +import { GaxiosResponse } from 'gaxios'; +import { Headers } from './oauth2client'; +import { ClientAuthentication, OAuthClientAuthHandler } from './oauth2common'; +/** + * Defines the interface needed to initialize an StsCredentials instance. + * The interface does not directly map to the spec and instead is converted + * to be compliant with the JavaScript style guide. This is because this is + * instantiated internally. + * StsCredentials implement the OAuth 2.0 token exchange based on + * https://tools.ietf.org/html/rfc8693. + * Request options are defined in + * https://tools.ietf.org/html/rfc8693#section-2.1 + */ +export interface StsCredentialsOptions { + /** + * REQUIRED. The value "urn:ietf:params:oauth:grant-type:token-exchange" + * indicates that a token exchange is being performed. + */ + grantType: string; + /** + * OPTIONAL. A URI that indicates the target service or resource where the + * client intends to use the requested security token. + */ + resource?: string; + /** + * OPTIONAL. The logical name of the target service where the client + * intends to use the requested security token. This serves a purpose + * similar to the "resource" parameter but with the client providing a + * logical name for the target service. + */ + audience?: string; + /** + * OPTIONAL. A list of space-delimited, case-sensitive strings, as defined + * in Section 3.3 of [RFC6749], that allow the client to specify the desired + * scope of the requested security token in the context of the service or + * resource where the token will be used. + */ + scope?: string[]; + /** + * OPTIONAL. An identifier, as described in Section 3 of [RFC8693], eg. + * "urn:ietf:params:oauth:token-type:access_token" for the type of the + * requested security token. + */ + requestedTokenType?: string; + /** + * REQUIRED. A security token that represents the identity of the party on + * behalf of whom the request is being made. + */ + subjectToken: string; + /** + * REQUIRED. An identifier, as described in Section 3 of [RFC8693], that + * indicates the type of the security token in the "subject_token" parameter. + */ + subjectTokenType: string; + actingParty?: { + /** + * OPTIONAL. A security token that represents the identity of the acting + * party. Typically, this will be the party that is authorized to use the + * requested security token and act on behalf of the subject. + */ + actorToken: string; + /** + * An identifier, as described in Section 3, that indicates the type of the + * security token in the "actor_token" parameter. This is REQUIRED when the + * "actor_token" parameter is present in the request but MUST NOT be + * included otherwise. + */ + actorTokenType: string; + }; +} +/** + * Defines the OAuth 2.0 token exchange successful response based on + * https://tools.ietf.org/html/rfc8693#section-2.2.1 + */ +export interface StsSuccessfulResponse { + access_token: string; + issued_token_type: string; + token_type: string; + expires_in?: number; + refresh_token?: string; + scope?: string; + res?: GaxiosResponse | null; +} +/** + * Implements the OAuth 2.0 token exchange based on + * https://tools.ietf.org/html/rfc8693 + */ +export declare class StsCredentials extends OAuthClientAuthHandler { + private readonly tokenExchangeEndpoint; + private transporter; + /** + * Initializes an STS credentials instance. + * @param tokenExchangeEndpoint The token exchange endpoint. + * @param clientAuthentication The client authentication credentials if + * available. + */ + constructor(tokenExchangeEndpoint: string | URL, clientAuthentication?: ClientAuthentication); + /** + * Exchanges the provided token for another type of token based on the + * rfc8693 spec. + * @param stsCredentialsOptions The token exchange options used to populate + * the token exchange request. + * @param additionalHeaders Optional additional headers to pass along the + * request. + * @param options Optional additional GCP-specific non-spec defined options + * to send with the request. + * Example: `&options=${encodeUriComponent(JSON.stringified(options))}` + * @return A promise that resolves with the token exchange response containing + * the requested token and its expiration time. + */ + exchangeToken(stsCredentialsOptions: StsCredentialsOptions, additionalHeaders?: Headers, options?: { + [key: string]: any; + }): Promise; +} diff --git a/node_modules/google-auth-library/build/src/auth/stscredentials.js b/node_modules/google-auth-library/build/src/auth/stscredentials.js new file mode 100644 index 0000000..46edef1 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/stscredentials.js @@ -0,0 +1,109 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StsCredentials = void 0; +const gaxios_1 = require("gaxios"); +const querystring = require("querystring"); +const transporters_1 = require("../transporters"); +const oauth2common_1 = require("./oauth2common"); +/** + * Implements the OAuth 2.0 token exchange based on + * https://tools.ietf.org/html/rfc8693 + */ +class StsCredentials extends oauth2common_1.OAuthClientAuthHandler { + /** + * Initializes an STS credentials instance. + * @param tokenExchangeEndpoint The token exchange endpoint. + * @param clientAuthentication The client authentication credentials if + * available. + */ + constructor(tokenExchangeEndpoint, clientAuthentication) { + super(clientAuthentication); + this.tokenExchangeEndpoint = tokenExchangeEndpoint; + this.transporter = new transporters_1.DefaultTransporter(); + } + /** + * Exchanges the provided token for another type of token based on the + * rfc8693 spec. + * @param stsCredentialsOptions The token exchange options used to populate + * the token exchange request. + * @param additionalHeaders Optional additional headers to pass along the + * request. + * @param options Optional additional GCP-specific non-spec defined options + * to send with the request. + * Example: `&options=${encodeUriComponent(JSON.stringified(options))}` + * @return A promise that resolves with the token exchange response containing + * the requested token and its expiration time. + */ + async exchangeToken(stsCredentialsOptions, additionalHeaders, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + options) { + var _a, _b, _c; + const values = { + grant_type: stsCredentialsOptions.grantType, + resource: stsCredentialsOptions.resource, + audience: stsCredentialsOptions.audience, + scope: (_a = stsCredentialsOptions.scope) === null || _a === void 0 ? void 0 : _a.join(' '), + requested_token_type: stsCredentialsOptions.requestedTokenType, + subject_token: stsCredentialsOptions.subjectToken, + subject_token_type: stsCredentialsOptions.subjectTokenType, + actor_token: (_b = stsCredentialsOptions.actingParty) === null || _b === void 0 ? void 0 : _b.actorToken, + actor_token_type: (_c = stsCredentialsOptions.actingParty) === null || _c === void 0 ? void 0 : _c.actorTokenType, + // Non-standard GCP-specific options. + options: options && JSON.stringify(options), + }; + // Remove undefined fields. + Object.keys(values).forEach(key => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (typeof values[key] === 'undefined') { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + delete values[key]; + } + }); + const headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + }; + // Inject additional STS headers if available. + Object.assign(headers, additionalHeaders || {}); + const opts = { + ...StsCredentials.RETRY_CONFIG, + url: this.tokenExchangeEndpoint.toString(), + method: 'POST', + headers, + data: querystring.stringify(values), + responseType: 'json', + }; + // Apply OAuth client authentication. + this.applyClientAuthenticationOptions(opts); + try { + const response = await this.transporter.request(opts); + // Successful response. + const stsSuccessfulResponse = response.data; + stsSuccessfulResponse.res = response; + return stsSuccessfulResponse; + } + catch (error) { + // Translate error to OAuthError. + if (error instanceof gaxios_1.GaxiosError && error.response) { + throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, + // Preserve other fields from the original error. + error); + } + // Request could fail before the server responds. + throw error; + } + } +} +exports.StsCredentials = StsCredentials; diff --git a/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.d.ts b/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.d.ts new file mode 100644 index 0000000..1c6d088 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.d.ts @@ -0,0 +1,57 @@ +import { ExternalAccountSupplierContext } from './baseexternalclient'; +import { GaxiosOptions } from 'gaxios'; +import { SubjectTokenFormatType, SubjectTokenSupplier } from './identitypoolclient'; +/** + * Interface that defines options used to build a {@link UrlSubjectTokenSupplier} + */ +export interface UrlSubjectTokenSupplierOptions { + /** + * The URL to call to retrieve the subject token. This is typically a local + * metadata server. + */ + url: string; + /** + * The token file or URL response type (JSON or text). + */ + formatType: SubjectTokenFormatType; + /** + * For JSON response types, this is the subject_token field name. For Azure, + * this is access_token. For text response types, this is ignored. + */ + subjectTokenFieldName?: string; + /** + * The optional additional headers to send with the request to the metadata + * server url. + */ + headers?: { + [key: string]: string; + }; + /** + * Additional gaxios options to use for the request to the specified URL. + */ + additionalGaxiosOptions?: GaxiosOptions; +} +/** + * Internal subject token supplier implementation used when a URL + * is configured in the credential configuration used to build an {@link IdentityPoolClient} + */ +export declare class UrlSubjectTokenSupplier implements SubjectTokenSupplier { + private readonly url; + private readonly headers?; + private readonly formatType; + private readonly subjectTokenFieldName?; + private readonly additionalGaxiosOptions?; + /** + * Instantiates a URL subject token supplier. + * @param opts The URL subject token supplier options to build the supplier with. + */ + constructor(opts: UrlSubjectTokenSupplierOptions); + /** + * Sends a GET request to the URL provided in the constructor and resolves + * with the returned external subject token. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link IdentityPoolClient}, contains the requested audience and subject + * token type for the external account identity. Not used. + */ + getSubjectToken(context: ExternalAccountSupplierContext): Promise; +} diff --git a/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js b/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js new file mode 100644 index 0000000..317736e --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js @@ -0,0 +1,63 @@ +"use strict"; +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UrlSubjectTokenSupplier = void 0; +/** + * Internal subject token supplier implementation used when a URL + * is configured in the credential configuration used to build an {@link IdentityPoolClient} + */ +class UrlSubjectTokenSupplier { + /** + * Instantiates a URL subject token supplier. + * @param opts The URL subject token supplier options to build the supplier with. + */ + constructor(opts) { + this.url = opts.url; + this.formatType = opts.formatType; + this.subjectTokenFieldName = opts.subjectTokenFieldName; + this.headers = opts.headers; + this.additionalGaxiosOptions = opts.additionalGaxiosOptions; + } + /** + * Sends a GET request to the URL provided in the constructor and resolves + * with the returned external subject token. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link IdentityPoolClient}, contains the requested audience and subject + * token type for the external account identity. Not used. + */ + async getSubjectToken(context) { + const opts = { + ...this.additionalGaxiosOptions, + url: this.url, + method: 'GET', + headers: this.headers, + responseType: this.formatType, + }; + let subjectToken; + if (this.formatType === 'text') { + const response = await context.transporter.request(opts); + subjectToken = response.data; + } + else if (this.formatType === 'json' && this.subjectTokenFieldName) { + const response = await context.transporter.request(opts); + subjectToken = response.data[this.subjectTokenFieldName]; + } + if (!subjectToken) { + throw new Error('Unable to parse the subject_token from the credential_source URL'); + } + return subjectToken; + } +} +exports.UrlSubjectTokenSupplier = UrlSubjectTokenSupplier; diff --git a/node_modules/google-auth-library/build/src/crypto/browser/crypto.d.ts b/node_modules/google-auth-library/build/src/crypto/browser/crypto.d.ts new file mode 100644 index 0000000..e0ed1ae --- /dev/null +++ b/node_modules/google-auth-library/build/src/crypto/browser/crypto.d.ts @@ -0,0 +1,27 @@ +import { Crypto, JwkCertificate } from '../crypto'; +export declare class BrowserCrypto implements Crypto { + constructor(); + sha256DigestBase64(str: string): Promise; + randomBytesBase64(count: number): string; + private static padBase64; + verify(pubkey: JwkCertificate, data: string, signature: string): Promise; + sign(privateKey: JwkCertificate, data: string): Promise; + decodeBase64StringUtf8(base64: string): string; + encodeBase64StringUtf8(text: string): string; + /** + * Computes the SHA-256 hash of the provided string. + * @param str The plain text string to hash. + * @return A promise that resolves with the SHA-256 hash of the provided + * string in hexadecimal encoding. + */ + sha256DigestHex(str: string): Promise; + /** + * Computes the HMAC hash of a message using the provided crypto key and the + * SHA-256 algorithm. + * @param key The secret crypto key in utf-8 or ArrayBuffer format. + * @param msg The plain text message. + * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer + * format. + */ + signWithHmacSha256(key: string | ArrayBuffer, msg: string): Promise; +} diff --git a/node_modules/google-auth-library/build/src/crypto/browser/crypto.js b/node_modules/google-auth-library/build/src/crypto/browser/crypto.js new file mode 100644 index 0000000..ccc6b57 --- /dev/null +++ b/node_modules/google-auth-library/build/src/crypto/browser/crypto.js @@ -0,0 +1,126 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +/* global window */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BrowserCrypto = void 0; +// This file implements crypto functions we need using in-browser +// SubtleCrypto interface `window.crypto.subtle`. +const base64js = require("base64-js"); +const crypto_1 = require("../crypto"); +class BrowserCrypto { + constructor() { + if (typeof window === 'undefined' || + window.crypto === undefined || + window.crypto.subtle === undefined) { + throw new Error("SubtleCrypto not found. Make sure it's an https:// website."); + } + } + async sha256DigestBase64(str) { + // SubtleCrypto digest() method is async, so we must make + // this method async as well. + // To calculate SHA256 digest using SubtleCrypto, we first + // need to convert an input string to an ArrayBuffer: + const inputBuffer = new TextEncoder().encode(str); + // Result is ArrayBuffer as well. + const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer); + return base64js.fromByteArray(new Uint8Array(outputBuffer)); + } + randomBytesBase64(count) { + const array = new Uint8Array(count); + window.crypto.getRandomValues(array); + return base64js.fromByteArray(array); + } + static padBase64(base64) { + // base64js requires padding, so let's add some '=' + while (base64.length % 4 !== 0) { + base64 += '='; + } + return base64; + } + async verify(pubkey, data, signature) { + const algo = { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: 'SHA-256' }, + }; + const dataArray = new TextEncoder().encode(data); + const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature)); + const cryptoKey = await window.crypto.subtle.importKey('jwk', pubkey, algo, true, ['verify']); + // SubtleCrypto's verify method is async so we must make + // this method async as well. + const result = await window.crypto.subtle.verify(algo, cryptoKey, signatureArray, dataArray); + return result; + } + async sign(privateKey, data) { + const algo = { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: 'SHA-256' }, + }; + const dataArray = new TextEncoder().encode(data); + const cryptoKey = await window.crypto.subtle.importKey('jwk', privateKey, algo, true, ['sign']); + // SubtleCrypto's sign method is async so we must make + // this method async as well. + const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray); + return base64js.fromByteArray(new Uint8Array(result)); + } + decodeBase64StringUtf8(base64) { + const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64)); + const result = new TextDecoder().decode(uint8array); + return result; + } + encodeBase64StringUtf8(text) { + const uint8array = new TextEncoder().encode(text); + const result = base64js.fromByteArray(uint8array); + return result; + } + /** + * Computes the SHA-256 hash of the provided string. + * @param str The plain text string to hash. + * @return A promise that resolves with the SHA-256 hash of the provided + * string in hexadecimal encoding. + */ + async sha256DigestHex(str) { + // SubtleCrypto digest() method is async, so we must make + // this method async as well. + // To calculate SHA256 digest using SubtleCrypto, we first + // need to convert an input string to an ArrayBuffer: + const inputBuffer = new TextEncoder().encode(str); + // Result is ArrayBuffer as well. + const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer); + return (0, crypto_1.fromArrayBufferToHex)(outputBuffer); + } + /** + * Computes the HMAC hash of a message using the provided crypto key and the + * SHA-256 algorithm. + * @param key The secret crypto key in utf-8 or ArrayBuffer format. + * @param msg The plain text message. + * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer + * format. + */ + async signWithHmacSha256(key, msg) { + // Convert key, if provided in ArrayBuffer format, to string. + const rawKey = typeof key === 'string' + ? key + : String.fromCharCode(...new Uint16Array(key)); + const enc = new TextEncoder(); + const cryptoKey = await window.crypto.subtle.importKey('raw', enc.encode(rawKey), { + name: 'HMAC', + hash: { + name: 'SHA-256', + }, + }, false, ['sign']); + return window.crypto.subtle.sign('HMAC', cryptoKey, enc.encode(msg)); + } +} +exports.BrowserCrypto = BrowserCrypto; diff --git a/node_modules/google-auth-library/build/src/crypto/crypto.d.ts b/node_modules/google-auth-library/build/src/crypto/crypto.d.ts new file mode 100644 index 0000000..7897f68 --- /dev/null +++ b/node_modules/google-auth-library/build/src/crypto/crypto.d.ts @@ -0,0 +1,44 @@ +export interface JwkCertificate { + kty: string; + alg: string; + use?: string; + kid: string; + n: string; + e: string; +} +export interface CryptoSigner { + update(data: string): void; + sign(key: string, outputFormat: string): string; +} +export interface Crypto { + sha256DigestBase64(str: string): Promise; + randomBytesBase64(n: number): string; + verify(pubkey: string | JwkCertificate, data: string | Buffer, signature: string): Promise; + sign(privateKey: string | JwkCertificate, data: string | Buffer): Promise; + decodeBase64StringUtf8(base64: string): string; + encodeBase64StringUtf8(text: string): string; + /** + * Computes the SHA-256 hash of the provided string. + * @param str The plain text string to hash. + * @return A promise that resolves with the SHA-256 hash of the provided + * string in hexadecimal encoding. + */ + sha256DigestHex(str: string): Promise; + /** + * Computes the HMAC hash of a message using the provided crypto key and the + * SHA-256 algorithm. + * @param key The secret crypto key in utf-8 or ArrayBuffer format. + * @param msg The plain text message. + * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer + * format. + */ + signWithHmacSha256(key: string | ArrayBuffer, msg: string): Promise; +} +export declare function createCrypto(): Crypto; +export declare function hasBrowserCrypto(): boolean; +/** + * Converts an ArrayBuffer to a hexadecimal string. + * @param arrayBuffer The ArrayBuffer to convert to hexadecimal string. + * @return The hexadecimal encoding of the ArrayBuffer. + */ +export declare function fromArrayBufferToHex(arrayBuffer: ArrayBuffer): string; diff --git a/node_modules/google-auth-library/build/src/crypto/crypto.js b/node_modules/google-auth-library/build/src/crypto/crypto.js new file mode 100644 index 0000000..b66fdda --- /dev/null +++ b/node_modules/google-auth-library/build/src/crypto/crypto.js @@ -0,0 +1,47 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +/* global window */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createCrypto = createCrypto; +exports.hasBrowserCrypto = hasBrowserCrypto; +exports.fromArrayBufferToHex = fromArrayBufferToHex; +const crypto_1 = require("./browser/crypto"); +const crypto_2 = require("./node/crypto"); +function createCrypto() { + if (hasBrowserCrypto()) { + return new crypto_1.BrowserCrypto(); + } + return new crypto_2.NodeCrypto(); +} +function hasBrowserCrypto() { + return (typeof window !== 'undefined' && + typeof window.crypto !== 'undefined' && + typeof window.crypto.subtle !== 'undefined'); +} +/** + * Converts an ArrayBuffer to a hexadecimal string. + * @param arrayBuffer The ArrayBuffer to convert to hexadecimal string. + * @return The hexadecimal encoding of the ArrayBuffer. + */ +function fromArrayBufferToHex(arrayBuffer) { + // Convert buffer to byte array. + const byteArray = Array.from(new Uint8Array(arrayBuffer)); + // Convert bytes to hex string. + return byteArray + .map(byte => { + return byte.toString(16).padStart(2, '0'); + }) + .join(''); +} diff --git a/node_modules/google-auth-library/build/src/crypto/node/crypto.d.ts b/node_modules/google-auth-library/build/src/crypto/node/crypto.d.ts new file mode 100644 index 0000000..8a56b11 --- /dev/null +++ b/node_modules/google-auth-library/build/src/crypto/node/crypto.d.ts @@ -0,0 +1,25 @@ +import { Crypto } from '../crypto'; +export declare class NodeCrypto implements Crypto { + sha256DigestBase64(str: string): Promise; + randomBytesBase64(count: number): string; + verify(pubkey: string, data: string | Buffer, signature: string): Promise; + sign(privateKey: string, data: string | Buffer): Promise; + decodeBase64StringUtf8(base64: string): string; + encodeBase64StringUtf8(text: string): string; + /** + * Computes the SHA-256 hash of the provided string. + * @param str The plain text string to hash. + * @return A promise that resolves with the SHA-256 hash of the provided + * string in hexadecimal encoding. + */ + sha256DigestHex(str: string): Promise; + /** + * Computes the HMAC hash of a message using the provided crypto key and the + * SHA-256 algorithm. + * @param key The secret crypto key in utf-8 or ArrayBuffer format. + * @param msg The plain text message. + * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer + * format. + */ + signWithHmacSha256(key: string | ArrayBuffer, msg: string): Promise; +} diff --git a/node_modules/google-auth-library/build/src/crypto/node/crypto.js b/node_modules/google-auth-library/build/src/crypto/node/crypto.js new file mode 100644 index 0000000..26ede46 --- /dev/null +++ b/node_modules/google-auth-library/build/src/crypto/node/crypto.js @@ -0,0 +1,82 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NodeCrypto = void 0; +const crypto = require("crypto"); +class NodeCrypto { + async sha256DigestBase64(str) { + return crypto.createHash('sha256').update(str).digest('base64'); + } + randomBytesBase64(count) { + return crypto.randomBytes(count).toString('base64'); + } + async verify(pubkey, data, signature) { + const verifier = crypto.createVerify('RSA-SHA256'); + verifier.update(data); + verifier.end(); + return verifier.verify(pubkey, signature, 'base64'); + } + async sign(privateKey, data) { + const signer = crypto.createSign('RSA-SHA256'); + signer.update(data); + signer.end(); + return signer.sign(privateKey, 'base64'); + } + decodeBase64StringUtf8(base64) { + return Buffer.from(base64, 'base64').toString('utf-8'); + } + encodeBase64StringUtf8(text) { + return Buffer.from(text, 'utf-8').toString('base64'); + } + /** + * Computes the SHA-256 hash of the provided string. + * @param str The plain text string to hash. + * @return A promise that resolves with the SHA-256 hash of the provided + * string in hexadecimal encoding. + */ + async sha256DigestHex(str) { + return crypto.createHash('sha256').update(str).digest('hex'); + } + /** + * Computes the HMAC hash of a message using the provided crypto key and the + * SHA-256 algorithm. + * @param key The secret crypto key in utf-8 or ArrayBuffer format. + * @param msg The plain text message. + * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer + * format. + */ + async signWithHmacSha256(key, msg) { + const cryptoKey = typeof key === 'string' ? key : toBuffer(key); + return toArrayBuffer(crypto.createHmac('sha256', cryptoKey).update(msg).digest()); + } +} +exports.NodeCrypto = NodeCrypto; +/** + * Converts a Node.js Buffer to an ArrayBuffer. + * https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer + * @param buffer The Buffer input to covert. + * @return The ArrayBuffer representation of the input. + */ +function toArrayBuffer(buffer) { + return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength); +} +/** + * Converts an ArrayBuffer to a Node.js Buffer. + * @param arrayBuffer The ArrayBuffer input to covert. + * @return The Buffer representation of the input. + */ +function toBuffer(arrayBuffer) { + return Buffer.from(arrayBuffer); +} diff --git a/node_modules/google-auth-library/build/src/index.d.ts b/node_modules/google-auth-library/build/src/index.d.ts new file mode 100644 index 0000000..dd44dc5 --- /dev/null +++ b/node_modules/google-auth-library/build/src/index.d.ts @@ -0,0 +1,33 @@ +import { GoogleAuth } from './auth/googleauth'; +export * as gcpMetadata from 'gcp-metadata'; +export * as gaxios from 'gaxios'; +import { AuthClient } from './auth/authclient'; +export { AuthClient, DEFAULT_UNIVERSE } from './auth/authclient'; +export { Compute, ComputeOptions } from './auth/computeclient'; +export { CredentialBody, CredentialRequest, Credentials, JWTInput, } from './auth/credentials'; +export { GCPEnv } from './auth/envDetect'; +export { GoogleAuthOptions, ProjectIdCallback } from './auth/googleauth'; +export { IAMAuth, RequestMetadata } from './auth/iam'; +export { IdTokenClient, IdTokenProvider } from './auth/idtokenclient'; +export { Claims, JWTAccess } from './auth/jwtaccess'; +export { JWT, JWTOptions } from './auth/jwtclient'; +export { Impersonated, ImpersonatedOptions } from './auth/impersonated'; +export { Certificates, CodeChallengeMethod, CodeVerifierResults, GenerateAuthUrlOpts, GetTokenOptions, OAuth2Client, OAuth2ClientOptions, RefreshOptions, TokenInfo, VerifyIdTokenOptions, ClientAuthentication, } from './auth/oauth2client'; +export { LoginTicket, TokenPayload } from './auth/loginticket'; +export { UserRefreshClient, UserRefreshClientOptions, } from './auth/refreshclient'; +export { AwsClient, AwsClientOptions, AwsSecurityCredentialsSupplier, } from './auth/awsclient'; +export { AwsSecurityCredentials, AwsRequestSigner, } from './auth/awsrequestsigner'; +export { IdentityPoolClient, IdentityPoolClientOptions, SubjectTokenSupplier, } from './auth/identitypoolclient'; +export { ExternalAccountClient, ExternalAccountClientOptions, } from './auth/externalclient'; +export { BaseExternalAccountClient, BaseExternalAccountClientOptions, SharedExternalAccountClientOptions, ExternalAccountSupplierContext, IamGenerateAccessTokenResponse, } from './auth/baseexternalclient'; +export { CredentialAccessBoundary, DownscopedClient, } from './auth/downscopedclient'; +export { PluggableAuthClient, PluggableAuthClientOptions, ExecutableError, } from './auth/pluggable-auth-client'; +export { PassThroughClient } from './auth/passthrough'; +export { DefaultTransporter } from './transporters'; +type ALL_EXPORTS = (typeof import('./'))[keyof typeof import('./')]; +/** + * A union type for all {@link AuthClient `AuthClient`}s. + */ +export type AnyAuthClient = InstanceType>; +declare const auth: GoogleAuth; +export { auth, GoogleAuth }; diff --git a/node_modules/google-auth-library/build/src/index.js b/node_modules/google-auth-library/build/src/index.js new file mode 100644 index 0000000..e0691c2 --- /dev/null +++ b/node_modules/google-auth-library/build/src/index.js @@ -0,0 +1,68 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GoogleAuth = exports.auth = exports.DefaultTransporter = exports.PassThroughClient = exports.ExecutableError = exports.PluggableAuthClient = exports.DownscopedClient = exports.BaseExternalAccountClient = exports.ExternalAccountClient = exports.IdentityPoolClient = exports.AwsRequestSigner = exports.AwsClient = exports.UserRefreshClient = exports.LoginTicket = exports.ClientAuthentication = exports.OAuth2Client = exports.CodeChallengeMethod = exports.Impersonated = exports.JWT = exports.JWTAccess = exports.IdTokenClient = exports.IAMAuth = exports.GCPEnv = exports.Compute = exports.DEFAULT_UNIVERSE = exports.AuthClient = exports.gaxios = exports.gcpMetadata = void 0; +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +const googleauth_1 = require("./auth/googleauth"); +Object.defineProperty(exports, "GoogleAuth", { enumerable: true, get: function () { return googleauth_1.GoogleAuth; } }); +// Export common deps to ensure types/instances are the exact match. Useful +// for consistently configuring the library across versions. +exports.gcpMetadata = require("gcp-metadata"); +exports.gaxios = require("gaxios"); +var authclient_1 = require("./auth/authclient"); +Object.defineProperty(exports, "AuthClient", { enumerable: true, get: function () { return authclient_1.AuthClient; } }); +Object.defineProperty(exports, "DEFAULT_UNIVERSE", { enumerable: true, get: function () { return authclient_1.DEFAULT_UNIVERSE; } }); +var computeclient_1 = require("./auth/computeclient"); +Object.defineProperty(exports, "Compute", { enumerable: true, get: function () { return computeclient_1.Compute; } }); +var envDetect_1 = require("./auth/envDetect"); +Object.defineProperty(exports, "GCPEnv", { enumerable: true, get: function () { return envDetect_1.GCPEnv; } }); +var iam_1 = require("./auth/iam"); +Object.defineProperty(exports, "IAMAuth", { enumerable: true, get: function () { return iam_1.IAMAuth; } }); +var idtokenclient_1 = require("./auth/idtokenclient"); +Object.defineProperty(exports, "IdTokenClient", { enumerable: true, get: function () { return idtokenclient_1.IdTokenClient; } }); +var jwtaccess_1 = require("./auth/jwtaccess"); +Object.defineProperty(exports, "JWTAccess", { enumerable: true, get: function () { return jwtaccess_1.JWTAccess; } }); +var jwtclient_1 = require("./auth/jwtclient"); +Object.defineProperty(exports, "JWT", { enumerable: true, get: function () { return jwtclient_1.JWT; } }); +var impersonated_1 = require("./auth/impersonated"); +Object.defineProperty(exports, "Impersonated", { enumerable: true, get: function () { return impersonated_1.Impersonated; } }); +var oauth2client_1 = require("./auth/oauth2client"); +Object.defineProperty(exports, "CodeChallengeMethod", { enumerable: true, get: function () { return oauth2client_1.CodeChallengeMethod; } }); +Object.defineProperty(exports, "OAuth2Client", { enumerable: true, get: function () { return oauth2client_1.OAuth2Client; } }); +Object.defineProperty(exports, "ClientAuthentication", { enumerable: true, get: function () { return oauth2client_1.ClientAuthentication; } }); +var loginticket_1 = require("./auth/loginticket"); +Object.defineProperty(exports, "LoginTicket", { enumerable: true, get: function () { return loginticket_1.LoginTicket; } }); +var refreshclient_1 = require("./auth/refreshclient"); +Object.defineProperty(exports, "UserRefreshClient", { enumerable: true, get: function () { return refreshclient_1.UserRefreshClient; } }); +var awsclient_1 = require("./auth/awsclient"); +Object.defineProperty(exports, "AwsClient", { enumerable: true, get: function () { return awsclient_1.AwsClient; } }); +var awsrequestsigner_1 = require("./auth/awsrequestsigner"); +Object.defineProperty(exports, "AwsRequestSigner", { enumerable: true, get: function () { return awsrequestsigner_1.AwsRequestSigner; } }); +var identitypoolclient_1 = require("./auth/identitypoolclient"); +Object.defineProperty(exports, "IdentityPoolClient", { enumerable: true, get: function () { return identitypoolclient_1.IdentityPoolClient; } }); +var externalclient_1 = require("./auth/externalclient"); +Object.defineProperty(exports, "ExternalAccountClient", { enumerable: true, get: function () { return externalclient_1.ExternalAccountClient; } }); +var baseexternalclient_1 = require("./auth/baseexternalclient"); +Object.defineProperty(exports, "BaseExternalAccountClient", { enumerable: true, get: function () { return baseexternalclient_1.BaseExternalAccountClient; } }); +var downscopedclient_1 = require("./auth/downscopedclient"); +Object.defineProperty(exports, "DownscopedClient", { enumerable: true, get: function () { return downscopedclient_1.DownscopedClient; } }); +var pluggable_auth_client_1 = require("./auth/pluggable-auth-client"); +Object.defineProperty(exports, "PluggableAuthClient", { enumerable: true, get: function () { return pluggable_auth_client_1.PluggableAuthClient; } }); +Object.defineProperty(exports, "ExecutableError", { enumerable: true, get: function () { return pluggable_auth_client_1.ExecutableError; } }); +var passthrough_1 = require("./auth/passthrough"); +Object.defineProperty(exports, "PassThroughClient", { enumerable: true, get: function () { return passthrough_1.PassThroughClient; } }); +var transporters_1 = require("./transporters"); +Object.defineProperty(exports, "DefaultTransporter", { enumerable: true, get: function () { return transporters_1.DefaultTransporter; } }); +const auth = new googleauth_1.GoogleAuth(); +exports.auth = auth; diff --git a/node_modules/google-auth-library/build/src/messages.d.ts b/node_modules/google-auth-library/build/src/messages.d.ts new file mode 100644 index 0000000..9de99bc --- /dev/null +++ b/node_modules/google-auth-library/build/src/messages.d.ts @@ -0,0 +1,11 @@ +export declare enum WarningTypes { + WARNING = "Warning", + DEPRECATION = "DeprecationWarning" +} +export declare function warn(warning: Warning): void; +export interface Warning { + code: string; + type: WarningTypes; + message: string; + warned?: boolean; +} diff --git a/node_modules/google-auth-library/build/src/messages.js b/node_modules/google-auth-library/build/src/messages.js new file mode 100644 index 0000000..9a45c3d --- /dev/null +++ b/node_modules/google-auth-library/build/src/messages.js @@ -0,0 +1,39 @@ +"use strict"; +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WarningTypes = void 0; +exports.warn = warn; +var WarningTypes; +(function (WarningTypes) { + WarningTypes["WARNING"] = "Warning"; + WarningTypes["DEPRECATION"] = "DeprecationWarning"; +})(WarningTypes || (exports.WarningTypes = WarningTypes = {})); +function warn(warning) { + // Only show a given warning once + if (warning.warned) { + return; + } + warning.warned = true; + if (typeof process !== 'undefined' && process.emitWarning) { + // @types/node doesn't recognize the emitWarning syntax which + // accepts a config object, so `as any` it is + // https://nodejs.org/docs/latest-v8.x/api/process.html#process_process_emitwarning_warning_options + // eslint-disable-next-line @typescript-eslint/no-explicit-any + process.emitWarning(warning.message, warning); + } + else { + console.warn(warning.message); + } +} diff --git a/node_modules/google-auth-library/build/src/options.d.ts b/node_modules/google-auth-library/build/src/options.d.ts new file mode 100644 index 0000000..ede9689 --- /dev/null +++ b/node_modules/google-auth-library/build/src/options.d.ts @@ -0,0 +1 @@ +export declare function validate(options: any): void; diff --git a/node_modules/google-auth-library/build/src/options.js b/node_modules/google-auth-library/build/src/options.js new file mode 100644 index 0000000..a6db1a6 --- /dev/null +++ b/node_modules/google-auth-library/build/src/options.js @@ -0,0 +1,34 @@ +"use strict"; +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validate = validate; +// Accepts an options object passed from the user to the API. In the +// previous version of the API, it referred to a `Request` options object. +// Now it refers to an Axiox Request Config object. This is here to help +// ensure users don't pass invalid options when they upgrade from 0.x to 1.x. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function validate(options) { + const vpairs = [ + { invalid: 'uri', expected: 'url' }, + { invalid: 'json', expected: 'data' }, + { invalid: 'qs', expected: 'params' }, + ]; + for (const pair of vpairs) { + if (options[pair.invalid]) { + const e = `'${pair.invalid}' is not a valid configuration option. Please use '${pair.expected}' instead. This library is using Axios for requests. Please see https://github.com/axios/axios to learn more about the valid request options.`; + throw new Error(e); + } + } +} diff --git a/node_modules/google-auth-library/build/src/transporters.d.ts b/node_modules/google-auth-library/build/src/transporters.d.ts new file mode 100644 index 0000000..b0ff7f2 --- /dev/null +++ b/node_modules/google-auth-library/build/src/transporters.d.ts @@ -0,0 +1,40 @@ +import { Gaxios, GaxiosError, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +export interface Transporter { + defaults?: GaxiosOptions; + request(opts: GaxiosOptions): GaxiosPromise; +} +export interface BodyResponseCallback { + (err: Error | null, res?: GaxiosResponse | null): void; +} +export interface RequestError extends GaxiosError { + errors: Error[]; +} +export declare class DefaultTransporter implements Transporter { + /** + * Default user agent. + */ + static readonly USER_AGENT: string; + /** + * A configurable, replacable `Gaxios` instance. + */ + instance: Gaxios; + /** + * Configures request options before making a request. + * @param opts GaxiosOptions options. + * @return Configured options. + */ + configure(opts?: GaxiosOptions): GaxiosOptions; + /** + * Makes a request using Gaxios with given options. + * @param opts GaxiosOptions options. + * @param callback optional callback that contains GaxiosResponse object. + * @return GaxiosPromise, assuming no callback is passed. + */ + request(opts: GaxiosOptions): GaxiosPromise; + get defaults(): GaxiosOptions; + set defaults(opts: GaxiosOptions); + /** + * Changes the error to include details from the body. + */ + private processError; +} diff --git a/node_modules/google-auth-library/build/src/transporters.js b/node_modules/google-auth-library/build/src/transporters.js new file mode 100644 index 0000000..7e9d072 --- /dev/null +++ b/node_modules/google-auth-library/build/src/transporters.js @@ -0,0 +1,110 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DefaultTransporter = void 0; +const gaxios_1 = require("gaxios"); +const options_1 = require("./options"); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const pkg = require('../../package.json'); +const PRODUCT_NAME = 'google-api-nodejs-client'; +class DefaultTransporter { + constructor() { + /** + * A configurable, replacable `Gaxios` instance. + */ + this.instance = new gaxios_1.Gaxios(); + } + /** + * Configures request options before making a request. + * @param opts GaxiosOptions options. + * @return Configured options. + */ + configure(opts = {}) { + opts.headers = opts.headers || {}; + if (typeof window === 'undefined') { + // set transporter user agent if not in browser + const uaValue = opts.headers['User-Agent']; + if (!uaValue) { + opts.headers['User-Agent'] = DefaultTransporter.USER_AGENT; + } + else if (!uaValue.includes(`${PRODUCT_NAME}/`)) { + opts.headers['User-Agent'] = + `${uaValue} ${DefaultTransporter.USER_AGENT}`; + } + // track google-auth-library-nodejs version: + if (!opts.headers['x-goog-api-client']) { + const nodeVersion = process.version.replace(/^v/, ''); + opts.headers['x-goog-api-client'] = `gl-node/${nodeVersion}`; + } + } + return opts; + } + /** + * Makes a request using Gaxios with given options. + * @param opts GaxiosOptions options. + * @param callback optional callback that contains GaxiosResponse object. + * @return GaxiosPromise, assuming no callback is passed. + */ + request(opts) { + // ensure the user isn't passing in request-style options + opts = this.configure(opts); + (0, options_1.validate)(opts); + return this.instance.request(opts).catch(e => { + throw this.processError(e); + }); + } + get defaults() { + return this.instance.defaults; + } + set defaults(opts) { + this.instance.defaults = opts; + } + /** + * Changes the error to include details from the body. + */ + processError(e) { + const res = e.response; + const err = e; + const body = res ? res.data : null; + if (res && body && body.error && res.status !== 200) { + if (typeof body.error === 'string') { + err.message = body.error; + err.status = res.status; + } + else if (Array.isArray(body.error.errors)) { + err.message = body.error.errors + .map((err2) => err2.message) + .join('\n'); + err.code = body.error.code; + err.errors = body.error.errors; + } + else { + err.message = body.error.message; + err.code = body.error.code; + } + } + else if (res && res.status >= 400) { + // Consider all 4xx and 5xx responses errors. + err.message = body; + err.status = res.status; + } + return err; + } +} +exports.DefaultTransporter = DefaultTransporter; +/** + * Default user agent. + */ +DefaultTransporter.USER_AGENT = `${PRODUCT_NAME}/${pkg.version}`; diff --git a/node_modules/google-auth-library/build/src/util.d.ts b/node_modules/google-auth-library/build/src/util.d.ts new file mode 100644 index 0000000..2c01475 --- /dev/null +++ b/node_modules/google-auth-library/build/src/util.d.ts @@ -0,0 +1,151 @@ +/** + * A utility for converting snake_case to camelCase. + * + * For, for example `my_snake_string` becomes `mySnakeString`. + * + * @internal + */ +export type SnakeToCamel = S extends `${infer FirstWord}_${infer Remainder}` ? `${FirstWord}${Capitalize>}` : S; +/** + * A utility for converting an type's keys from snake_case + * to camelCase, if the keys are strings. + * + * For example: + * + * ```ts + * { + * my_snake_string: boolean; + * myCamelString: string; + * my_snake_obj: { + * my_snake_obj_string: string; + * }; + * } + * ``` + * + * becomes: + * + * ```ts + * { + * mySnakeString: boolean; + * myCamelString: string; + * mySnakeObj: { + * mySnakeObjString: string; + * } + * } + * ``` + * + * @remarks + * + * The generated documentation for the camelCase'd properties won't be available + * until {@link https://github.com/microsoft/TypeScript/issues/50715} has been + * resolved. + * + * @internal + */ +export type SnakeToCamelObject = { + [K in keyof T as SnakeToCamel]: T[K] extends {} ? SnakeToCamelObject : T[K]; +}; +/** + * A utility for adding camelCase versions of a type's snake_case keys, if the + * keys are strings, preserving any existing keys. + * + * For example: + * + * ```ts + * { + * my_snake_boolean: boolean; + * myCamelString: string; + * my_snake_obj: { + * my_snake_obj_string: string; + * }; + * } + * ``` + * + * becomes: + * + * ```ts + * { + * my_snake_boolean: boolean; + * mySnakeBoolean: boolean; + * myCamelString: string; + * my_snake_obj: { + * my_snake_obj_string: string; + * }; + * mySnakeObj: { + * mySnakeObjString: string; + * } + * } + * ``` + * @remarks + * + * The generated documentation for the camelCase'd properties won't be available + * until {@link https://github.com/microsoft/TypeScript/issues/50715} has been + * resolved. + * + * Tracking: {@link https://github.com/googleapis/google-auth-library-nodejs/issues/1686} + * + * @internal + */ +export type OriginalAndCamel = { + [K in keyof T as K | SnakeToCamel]: T[K] extends {} ? OriginalAndCamel : T[K]; +}; +/** + * Returns the camel case of a provided string. + * + * @remarks + * + * Match any `_` and not `_` pair, then return the uppercase of the not `_` + * character. + * + * @internal + * + * @param str the string to convert + * @returns the camelCase'd string + */ +export declare function snakeToCamel(str: T): SnakeToCamel; +/** + * Get the value of `obj[key]` or `obj[camelCaseKey]`, with a preference + * for original, non-camelCase key. + * + * @param obj object to lookup a value in + * @returns a `get` function for getting `obj[key || snakeKey]`, if available + */ +export declare function originalOrCamelOptions(obj?: T): { + get: & string>(key: K) => OriginalAndCamel[K]; +}; +export interface LRUCacheOptions { + /** + * The maximum number of items to cache. + */ + capacity: number; + /** + * An optional max age for items in milliseconds. + */ + maxAge?: number; +} +/** + * A simple LRU cache utility. + * Not meant for external usage. + * + * @experimental + * @internal + */ +export declare class LRUCache { + #private; + readonly capacity: number; + maxAge?: number; + constructor(options: LRUCacheOptions); + /** + * Add an item to the cache. + * + * @param key the key to upsert + * @param value the value of the key + */ + set(key: string, value: T): void; + /** + * Get an item from the cache. + * + * @param key the key to retrieve + */ + get(key: string): T | undefined; +} diff --git a/node_modules/google-auth-library/build/src/util.js b/node_modules/google-auth-library/build/src/util.js new file mode 100644 index 0000000..856b705 --- /dev/null +++ b/node_modules/google-auth-library/build/src/util.js @@ -0,0 +1,125 @@ +"use strict"; +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _LRUCache_instances, _LRUCache_cache, _LRUCache_moveToEnd, _LRUCache_evict; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LRUCache = void 0; +exports.snakeToCamel = snakeToCamel; +exports.originalOrCamelOptions = originalOrCamelOptions; +/** + * Returns the camel case of a provided string. + * + * @remarks + * + * Match any `_` and not `_` pair, then return the uppercase of the not `_` + * character. + * + * @internal + * + * @param str the string to convert + * @returns the camelCase'd string + */ +function snakeToCamel(str) { + return str.replace(/([_][^_])/g, match => match.slice(1).toUpperCase()); +} +/** + * Get the value of `obj[key]` or `obj[camelCaseKey]`, with a preference + * for original, non-camelCase key. + * + * @param obj object to lookup a value in + * @returns a `get` function for getting `obj[key || snakeKey]`, if available + */ +function originalOrCamelOptions(obj) { + /** + * + * @param key an index of object, preferably snake_case + * @returns the value `obj[key || snakeKey]`, if available + */ + function get(key) { + var _a; + const o = (obj || {}); + return (_a = o[key]) !== null && _a !== void 0 ? _a : o[snakeToCamel(key)]; + } + return { get }; +} +/** + * A simple LRU cache utility. + * Not meant for external usage. + * + * @experimental + * @internal + */ +class LRUCache { + constructor(options) { + _LRUCache_instances.add(this); + /** + * Maps are in order. Thus, the older item is the first item. + * + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map} + */ + _LRUCache_cache.set(this, new Map()); + this.capacity = options.capacity; + this.maxAge = options.maxAge; + } + /** + * Add an item to the cache. + * + * @param key the key to upsert + * @param value the value of the key + */ + set(key, value) { + __classPrivateFieldGet(this, _LRUCache_instances, "m", _LRUCache_moveToEnd).call(this, key, value); + __classPrivateFieldGet(this, _LRUCache_instances, "m", _LRUCache_evict).call(this); + } + /** + * Get an item from the cache. + * + * @param key the key to retrieve + */ + get(key) { + const item = __classPrivateFieldGet(this, _LRUCache_cache, "f").get(key); + if (!item) + return; + __classPrivateFieldGet(this, _LRUCache_instances, "m", _LRUCache_moveToEnd).call(this, key, item.value); + __classPrivateFieldGet(this, _LRUCache_instances, "m", _LRUCache_evict).call(this); + return item.value; + } +} +exports.LRUCache = LRUCache; +_LRUCache_cache = new WeakMap(), _LRUCache_instances = new WeakSet(), _LRUCache_moveToEnd = function _LRUCache_moveToEnd(key, value) { + __classPrivateFieldGet(this, _LRUCache_cache, "f").delete(key); + __classPrivateFieldGet(this, _LRUCache_cache, "f").set(key, { + value, + lastAccessed: Date.now(), + }); +}, _LRUCache_evict = function _LRUCache_evict() { + const cutoffDate = this.maxAge ? Date.now() - this.maxAge : 0; + /** + * Because we know Maps are in order, this item is both the + * last item in the list (capacity) and oldest (maxAge). + */ + let oldestItem = __classPrivateFieldGet(this, _LRUCache_cache, "f").entries().next(); + while (!oldestItem.done && + (__classPrivateFieldGet(this, _LRUCache_cache, "f").size > this.capacity || // too many + oldestItem.value[1].lastAccessed < cutoffDate) // too old + ) { + __classPrivateFieldGet(this, _LRUCache_cache, "f").delete(oldestItem.value[0]); + oldestItem = __classPrivateFieldGet(this, _LRUCache_cache, "f").entries().next(); + } +}; diff --git a/node_modules/google-auth-library/package.json b/node_modules/google-auth-library/package.json new file mode 100644 index 0000000..a7e3231 --- /dev/null +++ b/node_modules/google-auth-library/package.json @@ -0,0 +1,94 @@ +{ + "name": "google-auth-library", + "version": "9.15.1", + "author": "Google Inc.", + "description": "Google APIs Authentication Client Library for Node.js", + "engines": { + "node": ">=14" + }, + "main": "./build/src/index.js", + "types": "./build/src/index.d.ts", + "repository": "googleapis/google-auth-library-nodejs.git", + "keywords": [ + "google", + "api", + "google apis", + "client", + "client library" + ], + "dependencies": { + "base64-js": "^1.3.0", + "ecdsa-sig-formatter": "^1.0.11", + "gaxios": "^6.1.1", + "gcp-metadata": "^6.1.0", + "gtoken": "^7.0.0", + "jws": "^4.0.0" + }, + "devDependencies": { + "@types/base64-js": "^1.2.5", + "@types/chai": "^4.1.7", + "@types/jws": "^3.1.0", + "@types/mocha": "^9.0.0", + "@types/mv": "^2.1.0", + "@types/ncp": "^2.0.1", + "@types/node": "^20.4.2", + "@types/sinon": "^17.0.0", + "assert-rejects": "^1.0.0", + "c8": "^8.0.0", + "chai": "^4.2.0", + "cheerio": "1.0.0-rc.12", + "codecov": "^3.0.2", + "engine.io": "6.6.2", + "gts": "^5.0.0", + "is-docker": "^2.0.0", + "jsdoc": "^4.0.0", + "jsdoc-fresh": "^3.0.0", + "jsdoc-region-tag": "^3.0.0", + "karma": "^6.0.0", + "karma-chrome-launcher": "^3.0.0", + "karma-coverage": "^2.0.0", + "karma-firefox-launcher": "^2.0.0", + "karma-mocha": "^2.0.0", + "karma-sourcemap-loader": "^0.4.0", + "karma-webpack": "5.0.0", + "keypair": "^1.0.4", + "linkinator": "^4.0.0", + "mocha": "^9.2.2", + "mv": "^2.1.1", + "ncp": "^2.0.0", + "nock": "^13.0.0", + "null-loader": "^4.0.0", + "pdfmake": "0.2.12", + "puppeteer": "^21.0.0", + "sinon": "^18.0.0", + "ts-loader": "^8.0.0", + "typescript": "^5.1.6", + "webpack": "^5.21.2", + "webpack-cli": "^4.0.0" + }, + "files": [ + "build/src", + "!build/src/**/*.map" + ], + "scripts": { + "test": "c8 mocha build/test", + "clean": "gts clean", + "prepare": "npm run compile", + "lint": "gts check", + "compile": "tsc -p .", + "fix": "gts fix", + "pretest": "npm run compile -- --sourceMap", + "docs": "jsdoc -c .jsdoc.json", + "samples-setup": "cd samples/ && npm link ../ && npm run setup && cd ../", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "system-test": "mocha build/system-test --timeout 60000", + "presystem-test": "npm run compile -- --sourceMap", + "webpack": "webpack", + "browser-test": "karma start", + "docs-test": "linkinator docs", + "predocs-test": "npm run docs", + "prelint": "cd samples; npm link ../; npm install", + "precompile": "gts clean" + }, + "license": "Apache-2.0" +} diff --git a/node_modules/google-gax/build/protos/compute_operations.d.ts b/node_modules/google-gax/build/protos/compute_operations.d.ts new file mode 100644 index 0000000..6551e1a --- /dev/null +++ b/node_modules/google-gax/build/protos/compute_operations.d.ts @@ -0,0 +1,7304 @@ +// Copyright 2021 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +import * as $protobuf from "protobufjs"; +import Long = require('long'); +/** Namespace google. */ +export namespace google { + + /** Namespace cloud. */ + namespace cloud { + + /** Namespace compute. */ + namespace compute { + + /** Namespace v1. */ + namespace v1 { + + /** Properties of an Operation. */ + interface IOperation { + + /** Operation clientOperationId */ + clientOperationId?: (string|null); + + /** Operation creationTimestamp */ + creationTimestamp?: (string|null); + + /** Operation description */ + description?: (string|null); + + /** Operation endTime */ + endTime?: (string|null); + + /** Operation error */ + error?: (google.cloud.compute.v1.IError|null); + + /** Operation httpErrorMessage */ + httpErrorMessage?: (string|null); + + /** Operation httpErrorStatusCode */ + httpErrorStatusCode?: (number|null); + + /** Operation id */ + id?: (string|null); + + /** Operation insertTime */ + insertTime?: (string|null); + + /** Operation kind */ + kind?: (string|null); + + /** Operation name */ + name?: (string|null); + + /** Operation operationType */ + operationType?: (string|null); + + /** Operation progress */ + progress?: (number|null); + + /** Operation region */ + region?: (string|null); + + /** Operation selfLink */ + selfLink?: (string|null); + + /** Operation startTime */ + startTime?: (string|null); + + /** Operation status */ + status?: (google.cloud.compute.v1.Operation.Status|null); + + /** Operation statusMessage */ + statusMessage?: (string|null); + + /** Operation targetId */ + targetId?: (string|null); + + /** Operation targetLink */ + targetLink?: (string|null); + + /** Operation user */ + user?: (string|null); + + /** Operation warnings */ + warnings?: (google.cloud.compute.v1.IWarnings[]|null); + + /** Operation zone */ + zone?: (string|null); + } + + /** Represents an Operation. */ + class Operation implements IOperation { + + /** + * Constructs a new Operation. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IOperation); + + /** Operation clientOperationId. */ + public clientOperationId?: (string|null); + + /** Operation creationTimestamp. */ + public creationTimestamp?: (string|null); + + /** Operation description. */ + public description?: (string|null); + + /** Operation endTime. */ + public endTime?: (string|null); + + /** Operation error. */ + public error?: (google.cloud.compute.v1.IError|null); + + /** Operation httpErrorMessage. */ + public httpErrorMessage?: (string|null); + + /** Operation httpErrorStatusCode. */ + public httpErrorStatusCode?: (number|null); + + /** Operation id. */ + public id?: (string|null); + + /** Operation insertTime. */ + public insertTime?: (string|null); + + /** Operation kind. */ + public kind?: (string|null); + + /** Operation name. */ + public name?: (string|null); + + /** Operation operationType. */ + public operationType?: (string|null); + + /** Operation progress. */ + public progress?: (number|null); + + /** Operation region. */ + public region?: (string|null); + + /** Operation selfLink. */ + public selfLink?: (string|null); + + /** Operation startTime. */ + public startTime?: (string|null); + + /** Operation status. */ + public status?: (google.cloud.compute.v1.Operation.Status|null); + + /** Operation statusMessage. */ + public statusMessage?: (string|null); + + /** Operation targetId. */ + public targetId?: (string|null); + + /** Operation targetLink. */ + public targetLink?: (string|null); + + /** Operation user. */ + public user?: (string|null); + + /** Operation warnings. */ + public warnings: google.cloud.compute.v1.IWarnings[]; + + /** Operation zone. */ + public zone?: (string|null); + + /** Operation _clientOperationId. */ + public _clientOperationId?: "clientOperationId"; + + /** Operation _creationTimestamp. */ + public _creationTimestamp?: "creationTimestamp"; + + /** Operation _description. */ + public _description?: "description"; + + /** Operation _endTime. */ + public _endTime?: "endTime"; + + /** Operation _error. */ + public _error?: "error"; + + /** Operation _httpErrorMessage. */ + public _httpErrorMessage?: "httpErrorMessage"; + + /** Operation _httpErrorStatusCode. */ + public _httpErrorStatusCode?: "httpErrorStatusCode"; + + /** Operation _id. */ + public _id?: "id"; + + /** Operation _insertTime. */ + public _insertTime?: "insertTime"; + + /** Operation _kind. */ + public _kind?: "kind"; + + /** Operation _name. */ + public _name?: "name"; + + /** Operation _operationType. */ + public _operationType?: "operationType"; + + /** Operation _progress. */ + public _progress?: "progress"; + + /** Operation _region. */ + public _region?: "region"; + + /** Operation _selfLink. */ + public _selfLink?: "selfLink"; + + /** Operation _startTime. */ + public _startTime?: "startTime"; + + /** Operation _status. */ + public _status?: "status"; + + /** Operation _statusMessage. */ + public _statusMessage?: "statusMessage"; + + /** Operation _targetId. */ + public _targetId?: "targetId"; + + /** Operation _targetLink. */ + public _targetLink?: "targetLink"; + + /** Operation _user. */ + public _user?: "user"; + + /** Operation _zone. */ + public _zone?: "zone"; + + /** + * Creates a new Operation instance using the specified properties. + * @param [properties] Properties to set + * @returns Operation instance + */ + public static create(properties?: google.cloud.compute.v1.IOperation): google.cloud.compute.v1.Operation; + + /** + * Encodes the specified Operation message. Does not implicitly {@link google.cloud.compute.v1.Operation.verify|verify} messages. + * @param message Operation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IOperation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Operation message, length delimited. Does not implicitly {@link google.cloud.compute.v1.Operation.verify|verify} messages. + * @param message Operation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IOperation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Operation message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Operation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.Operation; + + /** + * Decodes an Operation message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Operation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.Operation; + + /** + * Verifies an Operation message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an Operation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Operation + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.Operation; + + /** + * Creates a plain object from an Operation message. Also converts values to other types if specified. + * @param message Operation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.Operation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Operation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace Operation { + + /** Status enum. */ + enum Status { + UNDEFINED_STATUS = 0, + DONE = 2104194, + PENDING = 35394935, + RUNNING = 121282975 + } + } + + /** Properties of an Errors. */ + interface IErrors { + + /** Errors code */ + code?: (string|null); + + /** Errors location */ + location?: (string|null); + + /** Errors message */ + message?: (string|null); + } + + /** Represents an Errors. */ + class Errors implements IErrors { + + /** + * Constructs a new Errors. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IErrors); + + /** Errors code. */ + public code?: (string|null); + + /** Errors location. */ + public location?: (string|null); + + /** Errors message. */ + public message?: (string|null); + + /** Errors _code. */ + public _code?: "code"; + + /** Errors _location. */ + public _location?: "location"; + + /** Errors _message. */ + public _message?: "message"; + + /** + * Creates a new Errors instance using the specified properties. + * @param [properties] Properties to set + * @returns Errors instance + */ + public static create(properties?: google.cloud.compute.v1.IErrors): google.cloud.compute.v1.Errors; + + /** + * Encodes the specified Errors message. Does not implicitly {@link google.cloud.compute.v1.Errors.verify|verify} messages. + * @param message Errors message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IErrors, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Errors message, length delimited. Does not implicitly {@link google.cloud.compute.v1.Errors.verify|verify} messages. + * @param message Errors message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IErrors, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Errors message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Errors + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.Errors; + + /** + * Decodes an Errors message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Errors + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.Errors; + + /** + * Verifies an Errors message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an Errors message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Errors + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.Errors; + + /** + * Creates a plain object from an Errors message. Also converts values to other types if specified. + * @param message Errors + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.Errors, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Errors to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of an Error. */ + interface IError { + + /** Error errors */ + errors?: (google.cloud.compute.v1.IErrors[]|null); + } + + /** Represents an Error. */ + class Error implements IError { + + /** + * Constructs a new Error. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IError); + + /** Error errors. */ + public errors: google.cloud.compute.v1.IErrors[]; + + /** + * Creates a new Error instance using the specified properties. + * @param [properties] Properties to set + * @returns Error instance + */ + public static create(properties?: google.cloud.compute.v1.IError): google.cloud.compute.v1.Error; + + /** + * Encodes the specified Error message. Does not implicitly {@link google.cloud.compute.v1.Error.verify|verify} messages. + * @param message Error message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IError, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Error message, length delimited. Does not implicitly {@link google.cloud.compute.v1.Error.verify|verify} messages. + * @param message Error message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IError, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Error message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Error + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.Error; + + /** + * Decodes an Error message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Error + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.Error; + + /** + * Verifies an Error message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an Error message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Error + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.Error; + + /** + * Creates a plain object from an Error message. Also converts values to other types if specified. + * @param message Error + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.Error, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Error to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a Warnings. */ + interface IWarnings { + + /** Warnings code */ + code?: (google.cloud.compute.v1.Warnings.Code|null); + + /** Warnings data */ + data?: (google.cloud.compute.v1.IData[]|null); + + /** Warnings message */ + message?: (string|null); + } + + /** Represents a Warnings. */ + class Warnings implements IWarnings { + + /** + * Constructs a new Warnings. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IWarnings); + + /** Warnings code. */ + public code?: (google.cloud.compute.v1.Warnings.Code|null); + + /** Warnings data. */ + public data: google.cloud.compute.v1.IData[]; + + /** Warnings message. */ + public message?: (string|null); + + /** Warnings _code. */ + public _code?: "code"; + + /** Warnings _message. */ + public _message?: "message"; + + /** + * Creates a new Warnings instance using the specified properties. + * @param [properties] Properties to set + * @returns Warnings instance + */ + public static create(properties?: google.cloud.compute.v1.IWarnings): google.cloud.compute.v1.Warnings; + + /** + * Encodes the specified Warnings message. Does not implicitly {@link google.cloud.compute.v1.Warnings.verify|verify} messages. + * @param message Warnings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IWarnings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Warnings message, length delimited. Does not implicitly {@link google.cloud.compute.v1.Warnings.verify|verify} messages. + * @param message Warnings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IWarnings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Warnings message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Warnings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.Warnings; + + /** + * Decodes a Warnings message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Warnings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.Warnings; + + /** + * Verifies a Warnings message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Warnings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Warnings + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.Warnings; + + /** + * Creates a plain object from a Warnings message. Also converts values to other types if specified. + * @param message Warnings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.Warnings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Warnings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace Warnings { + + /** Code enum. */ + enum Code { + UNDEFINED_CODE = 0, + CLEANUP_FAILED = 150308440, + DEPRECATED_RESOURCE_USED = 391835586, + DEPRECATED_TYPE_USED = 346526230, + DISK_SIZE_LARGER_THAN_IMAGE_SIZE = 369442967, + EXPERIMENTAL_TYPE_USED = 451954443, + EXTERNAL_API_WARNING = 175546307, + FIELD_VALUE_OVERRIDEN = 329669423, + INJECTED_KERNELS_DEPRECATED = 417377419, + MISSING_TYPE_DEPENDENCY = 344505463, + NEXT_HOP_ADDRESS_NOT_ASSIGNED = 324964999, + NEXT_HOP_CANNOT_IP_FORWARD = 383382887, + NEXT_HOP_INSTANCE_NOT_FOUND = 464250446, + NEXT_HOP_INSTANCE_NOT_ON_NETWORK = 243758146, + NEXT_HOP_NOT_RUNNING = 417081265, + NOT_CRITICAL_ERROR = 105763924, + NO_RESULTS_ON_PAGE = 30036744, + REQUIRED_TOS_AGREEMENT = 3745539, + RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING = 496728641, + RESOURCE_NOT_DELETED = 168598460, + SCHEMA_VALIDATION_IGNORED = 275245642, + SINGLE_INSTANCE_PROPERTY_TEMPLATE = 268305617, + UNDECLARED_PROPERTIES = 390513439, + UNREACHABLE = 13328052 + } + } + + /** Properties of a Warning. */ + interface IWarning { + + /** Warning code */ + code?: (google.cloud.compute.v1.Warning.Code|null); + + /** Warning data */ + data?: (google.cloud.compute.v1.IData[]|null); + + /** Warning message */ + message?: (string|null); + } + + /** Represents a Warning. */ + class Warning implements IWarning { + + /** + * Constructs a new Warning. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IWarning); + + /** Warning code. */ + public code?: (google.cloud.compute.v1.Warning.Code|null); + + /** Warning data. */ + public data: google.cloud.compute.v1.IData[]; + + /** Warning message. */ + public message?: (string|null); + + /** Warning _code. */ + public _code?: "code"; + + /** Warning _message. */ + public _message?: "message"; + + /** + * Creates a new Warning instance using the specified properties. + * @param [properties] Properties to set + * @returns Warning instance + */ + public static create(properties?: google.cloud.compute.v1.IWarning): google.cloud.compute.v1.Warning; + + /** + * Encodes the specified Warning message. Does not implicitly {@link google.cloud.compute.v1.Warning.verify|verify} messages. + * @param message Warning message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IWarning, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Warning message, length delimited. Does not implicitly {@link google.cloud.compute.v1.Warning.verify|verify} messages. + * @param message Warning message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IWarning, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Warning message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Warning + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.Warning; + + /** + * Decodes a Warning message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Warning + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.Warning; + + /** + * Verifies a Warning message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Warning message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Warning + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.Warning; + + /** + * Creates a plain object from a Warning message. Also converts values to other types if specified. + * @param message Warning + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.Warning, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Warning to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace Warning { + + /** Code enum. */ + enum Code { + UNDEFINED_CODE = 0, + CLEANUP_FAILED = 150308440, + DEPRECATED_RESOURCE_USED = 391835586, + DEPRECATED_TYPE_USED = 346526230, + DISK_SIZE_LARGER_THAN_IMAGE_SIZE = 369442967, + EXPERIMENTAL_TYPE_USED = 451954443, + EXTERNAL_API_WARNING = 175546307, + FIELD_VALUE_OVERRIDEN = 329669423, + INJECTED_KERNELS_DEPRECATED = 417377419, + LARGE_DEPLOYMENT_WARNING = 481440678, + MISSING_TYPE_DEPENDENCY = 344505463, + NEXT_HOP_ADDRESS_NOT_ASSIGNED = 324964999, + NEXT_HOP_CANNOT_IP_FORWARD = 383382887, + NEXT_HOP_INSTANCE_NOT_FOUND = 464250446, + NEXT_HOP_INSTANCE_NOT_ON_NETWORK = 243758146, + NEXT_HOP_NOT_RUNNING = 417081265, + NOT_CRITICAL_ERROR = 105763924, + NO_RESULTS_ON_PAGE = 30036744, + PARTIAL_SUCCESS = 39966469, + REQUIRED_TOS_AGREEMENT = 3745539, + RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING = 496728641, + RESOURCE_NOT_DELETED = 168598460, + SCHEMA_VALIDATION_IGNORED = 275245642, + SINGLE_INSTANCE_PROPERTY_TEMPLATE = 268305617, + UNDECLARED_PROPERTIES = 390513439, + UNREACHABLE = 13328052 + } + } + + /** Properties of a Data. */ + interface IData { + + /** Data key */ + key?: (string|null); + + /** Data value */ + value?: (string|null); + } + + /** Represents a Data. */ + class Data implements IData { + + /** + * Constructs a new Data. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IData); + + /** Data key. */ + public key?: (string|null); + + /** Data value. */ + public value?: (string|null); + + /** Data _key. */ + public _key?: "key"; + + /** Data _value. */ + public _value?: "value"; + + /** + * Creates a new Data instance using the specified properties. + * @param [properties] Properties to set + * @returns Data instance + */ + public static create(properties?: google.cloud.compute.v1.IData): google.cloud.compute.v1.Data; + + /** + * Encodes the specified Data message. Does not implicitly {@link google.cloud.compute.v1.Data.verify|verify} messages. + * @param message Data message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IData, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Data message, length delimited. Does not implicitly {@link google.cloud.compute.v1.Data.verify|verify} messages. + * @param message Data message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IData, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Data message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Data + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.Data; + + /** + * Decodes a Data message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Data + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.Data; + + /** + * Verifies a Data message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Data message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Data + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.Data; + + /** + * Creates a plain object from a Data message. Also converts values to other types if specified. + * @param message Data + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.Data, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Data to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of an OperationsScopedList. */ + interface IOperationsScopedList { + + /** OperationsScopedList operations */ + operations?: (google.cloud.compute.v1.IOperation[]|null); + + /** OperationsScopedList warning */ + warning?: (google.cloud.compute.v1.IWarning|null); + } + + /** Represents an OperationsScopedList. */ + class OperationsScopedList implements IOperationsScopedList { + + /** + * Constructs a new OperationsScopedList. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IOperationsScopedList); + + /** OperationsScopedList operations. */ + public operations: google.cloud.compute.v1.IOperation[]; + + /** OperationsScopedList warning. */ + public warning?: (google.cloud.compute.v1.IWarning|null); + + /** OperationsScopedList _warning. */ + public _warning?: "warning"; + + /** + * Creates a new OperationsScopedList instance using the specified properties. + * @param [properties] Properties to set + * @returns OperationsScopedList instance + */ + public static create(properties?: google.cloud.compute.v1.IOperationsScopedList): google.cloud.compute.v1.OperationsScopedList; + + /** + * Encodes the specified OperationsScopedList message. Does not implicitly {@link google.cloud.compute.v1.OperationsScopedList.verify|verify} messages. + * @param message OperationsScopedList message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IOperationsScopedList, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified OperationsScopedList message, length delimited. Does not implicitly {@link google.cloud.compute.v1.OperationsScopedList.verify|verify} messages. + * @param message OperationsScopedList message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IOperationsScopedList, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an OperationsScopedList message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns OperationsScopedList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.OperationsScopedList; + + /** + * Decodes an OperationsScopedList message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns OperationsScopedList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.OperationsScopedList; + + /** + * Verifies an OperationsScopedList message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an OperationsScopedList message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OperationsScopedList + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.OperationsScopedList; + + /** + * Creates a plain object from an OperationsScopedList message. Also converts values to other types if specified. + * @param message OperationsScopedList + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.OperationsScopedList, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OperationsScopedList to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of an OperationAggregatedList. */ + interface IOperationAggregatedList { + + /** OperationAggregatedList id */ + id?: (string|null); + + /** OperationAggregatedList items */ + items?: ({ [k: string]: google.cloud.compute.v1.IOperationsScopedList }|null); + + /** OperationAggregatedList kind */ + kind?: (string|null); + + /** OperationAggregatedList nextPageToken */ + nextPageToken?: (string|null); + + /** OperationAggregatedList selfLink */ + selfLink?: (string|null); + + /** OperationAggregatedList unreachables */ + unreachables?: (string[]|null); + + /** OperationAggregatedList warning */ + warning?: (google.cloud.compute.v1.IWarning|null); + } + + /** Represents an OperationAggregatedList. */ + class OperationAggregatedList implements IOperationAggregatedList { + + /** + * Constructs a new OperationAggregatedList. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IOperationAggregatedList); + + /** OperationAggregatedList id. */ + public id?: (string|null); + + /** OperationAggregatedList items. */ + public items: { [k: string]: google.cloud.compute.v1.IOperationsScopedList }; + + /** OperationAggregatedList kind. */ + public kind?: (string|null); + + /** OperationAggregatedList nextPageToken. */ + public nextPageToken?: (string|null); + + /** OperationAggregatedList selfLink. */ + public selfLink?: (string|null); + + /** OperationAggregatedList unreachables. */ + public unreachables: string[]; + + /** OperationAggregatedList warning. */ + public warning?: (google.cloud.compute.v1.IWarning|null); + + /** OperationAggregatedList _id. */ + public _id?: "id"; + + /** OperationAggregatedList _kind. */ + public _kind?: "kind"; + + /** OperationAggregatedList _nextPageToken. */ + public _nextPageToken?: "nextPageToken"; + + /** OperationAggregatedList _selfLink. */ + public _selfLink?: "selfLink"; + + /** OperationAggregatedList _warning. */ + public _warning?: "warning"; + + /** + * Creates a new OperationAggregatedList instance using the specified properties. + * @param [properties] Properties to set + * @returns OperationAggregatedList instance + */ + public static create(properties?: google.cloud.compute.v1.IOperationAggregatedList): google.cloud.compute.v1.OperationAggregatedList; + + /** + * Encodes the specified OperationAggregatedList message. Does not implicitly {@link google.cloud.compute.v1.OperationAggregatedList.verify|verify} messages. + * @param message OperationAggregatedList message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IOperationAggregatedList, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified OperationAggregatedList message, length delimited. Does not implicitly {@link google.cloud.compute.v1.OperationAggregatedList.verify|verify} messages. + * @param message OperationAggregatedList message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IOperationAggregatedList, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an OperationAggregatedList message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns OperationAggregatedList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.OperationAggregatedList; + + /** + * Decodes an OperationAggregatedList message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns OperationAggregatedList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.OperationAggregatedList; + + /** + * Verifies an OperationAggregatedList message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an OperationAggregatedList message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OperationAggregatedList + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.OperationAggregatedList; + + /** + * Creates a plain object from an OperationAggregatedList message. Also converts values to other types if specified. + * @param message OperationAggregatedList + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.OperationAggregatedList, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OperationAggregatedList to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a GetRegionOperationRequest. */ + interface IGetRegionOperationRequest { + + /** GetRegionOperationRequest operation */ + operation?: (string|null); + + /** GetRegionOperationRequest project */ + project?: (string|null); + + /** GetRegionOperationRequest region */ + region?: (string|null); + } + + /** Represents a GetRegionOperationRequest. */ + class GetRegionOperationRequest implements IGetRegionOperationRequest { + + /** + * Constructs a new GetRegionOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IGetRegionOperationRequest); + + /** GetRegionOperationRequest operation. */ + public operation: string; + + /** GetRegionOperationRequest project. */ + public project: string; + + /** GetRegionOperationRequest region. */ + public region: string; + + /** + * Creates a new GetRegionOperationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetRegionOperationRequest instance + */ + public static create(properties?: google.cloud.compute.v1.IGetRegionOperationRequest): google.cloud.compute.v1.GetRegionOperationRequest; + + /** + * Encodes the specified GetRegionOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.GetRegionOperationRequest.verify|verify} messages. + * @param message GetRegionOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IGetRegionOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetRegionOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.GetRegionOperationRequest.verify|verify} messages. + * @param message GetRegionOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IGetRegionOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetRegionOperationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetRegionOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.GetRegionOperationRequest; + + /** + * Decodes a GetRegionOperationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetRegionOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.GetRegionOperationRequest; + + /** + * Verifies a GetRegionOperationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetRegionOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetRegionOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.GetRegionOperationRequest; + + /** + * Creates a plain object from a GetRegionOperationRequest message. Also converts values to other types if specified. + * @param message GetRegionOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.GetRegionOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetRegionOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a DeleteRegionOperationRequest. */ + interface IDeleteRegionOperationRequest { + + /** DeleteRegionOperationRequest operation */ + operation?: (string|null); + + /** DeleteRegionOperationRequest project */ + project?: (string|null); + + /** DeleteRegionOperationRequest region */ + region?: (string|null); + } + + /** Represents a DeleteRegionOperationRequest. */ + class DeleteRegionOperationRequest implements IDeleteRegionOperationRequest { + + /** + * Constructs a new DeleteRegionOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IDeleteRegionOperationRequest); + + /** DeleteRegionOperationRequest operation. */ + public operation: string; + + /** DeleteRegionOperationRequest project. */ + public project: string; + + /** DeleteRegionOperationRequest region. */ + public region: string; + + /** + * Creates a new DeleteRegionOperationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteRegionOperationRequest instance + */ + public static create(properties?: google.cloud.compute.v1.IDeleteRegionOperationRequest): google.cloud.compute.v1.DeleteRegionOperationRequest; + + /** + * Encodes the specified DeleteRegionOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.DeleteRegionOperationRequest.verify|verify} messages. + * @param message DeleteRegionOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IDeleteRegionOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteRegionOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.DeleteRegionOperationRequest.verify|verify} messages. + * @param message DeleteRegionOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IDeleteRegionOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteRegionOperationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteRegionOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.DeleteRegionOperationRequest; + + /** + * Decodes a DeleteRegionOperationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteRegionOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.DeleteRegionOperationRequest; + + /** + * Verifies a DeleteRegionOperationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteRegionOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteRegionOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.DeleteRegionOperationRequest; + + /** + * Creates a plain object from a DeleteRegionOperationRequest message. Also converts values to other types if specified. + * @param message DeleteRegionOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.DeleteRegionOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteRegionOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a DeleteRegionOperationResponse. */ + interface IDeleteRegionOperationResponse { + } + + /** Represents a DeleteRegionOperationResponse. */ + class DeleteRegionOperationResponse implements IDeleteRegionOperationResponse { + + /** + * Constructs a new DeleteRegionOperationResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IDeleteRegionOperationResponse); + + /** + * Creates a new DeleteRegionOperationResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteRegionOperationResponse instance + */ + public static create(properties?: google.cloud.compute.v1.IDeleteRegionOperationResponse): google.cloud.compute.v1.DeleteRegionOperationResponse; + + /** + * Encodes the specified DeleteRegionOperationResponse message. Does not implicitly {@link google.cloud.compute.v1.DeleteRegionOperationResponse.verify|verify} messages. + * @param message DeleteRegionOperationResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IDeleteRegionOperationResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteRegionOperationResponse message, length delimited. Does not implicitly {@link google.cloud.compute.v1.DeleteRegionOperationResponse.verify|verify} messages. + * @param message DeleteRegionOperationResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IDeleteRegionOperationResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteRegionOperationResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteRegionOperationResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.DeleteRegionOperationResponse; + + /** + * Decodes a DeleteRegionOperationResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteRegionOperationResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.DeleteRegionOperationResponse; + + /** + * Verifies a DeleteRegionOperationResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteRegionOperationResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteRegionOperationResponse + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.DeleteRegionOperationResponse; + + /** + * Creates a plain object from a DeleteRegionOperationResponse message. Also converts values to other types if specified. + * @param message DeleteRegionOperationResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.DeleteRegionOperationResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteRegionOperationResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a ListRegionOperationsRequest. */ + interface IListRegionOperationsRequest { + + /** ListRegionOperationsRequest filter */ + filter?: (string|null); + + /** ListRegionOperationsRequest maxResults */ + maxResults?: (number|null); + + /** ListRegionOperationsRequest orderBy */ + orderBy?: (string|null); + + /** ListRegionOperationsRequest pageToken */ + pageToken?: (string|null); + + /** ListRegionOperationsRequest project */ + project?: (string|null); + + /** ListRegionOperationsRequest region */ + region?: (string|null); + + /** ListRegionOperationsRequest returnPartialSuccess */ + returnPartialSuccess?: (boolean|null); + } + + /** Represents a ListRegionOperationsRequest. */ + class ListRegionOperationsRequest implements IListRegionOperationsRequest { + + /** + * Constructs a new ListRegionOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IListRegionOperationsRequest); + + /** ListRegionOperationsRequest filter. */ + public filter?: (string|null); + + /** ListRegionOperationsRequest maxResults. */ + public maxResults?: (number|null); + + /** ListRegionOperationsRequest orderBy. */ + public orderBy?: (string|null); + + /** ListRegionOperationsRequest pageToken. */ + public pageToken?: (string|null); + + /** ListRegionOperationsRequest project. */ + public project: string; + + /** ListRegionOperationsRequest region. */ + public region: string; + + /** ListRegionOperationsRequest returnPartialSuccess. */ + public returnPartialSuccess?: (boolean|null); + + /** ListRegionOperationsRequest _filter. */ + public _filter?: "filter"; + + /** ListRegionOperationsRequest _maxResults. */ + public _maxResults?: "maxResults"; + + /** ListRegionOperationsRequest _orderBy. */ + public _orderBy?: "orderBy"; + + /** ListRegionOperationsRequest _pageToken. */ + public _pageToken?: "pageToken"; + + /** ListRegionOperationsRequest _returnPartialSuccess. */ + public _returnPartialSuccess?: "returnPartialSuccess"; + + /** + * Creates a new ListRegionOperationsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListRegionOperationsRequest instance + */ + public static create(properties?: google.cloud.compute.v1.IListRegionOperationsRequest): google.cloud.compute.v1.ListRegionOperationsRequest; + + /** + * Encodes the specified ListRegionOperationsRequest message. Does not implicitly {@link google.cloud.compute.v1.ListRegionOperationsRequest.verify|verify} messages. + * @param message ListRegionOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IListRegionOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListRegionOperationsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.ListRegionOperationsRequest.verify|verify} messages. + * @param message ListRegionOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IListRegionOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListRegionOperationsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListRegionOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.ListRegionOperationsRequest; + + /** + * Decodes a ListRegionOperationsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListRegionOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.ListRegionOperationsRequest; + + /** + * Verifies a ListRegionOperationsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListRegionOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListRegionOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.ListRegionOperationsRequest; + + /** + * Creates a plain object from a ListRegionOperationsRequest message. Also converts values to other types if specified. + * @param message ListRegionOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.ListRegionOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListRegionOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of an OperationList. */ + interface IOperationList { + + /** OperationList id */ + id?: (string|null); + + /** OperationList items */ + items?: (google.cloud.compute.v1.IOperation[]|null); + + /** OperationList kind */ + kind?: (string|null); + + /** OperationList nextPageToken */ + nextPageToken?: (string|null); + + /** OperationList selfLink */ + selfLink?: (string|null); + + /** OperationList warning */ + warning?: (google.cloud.compute.v1.IWarning|null); + } + + /** Represents an OperationList. */ + class OperationList implements IOperationList { + + /** + * Constructs a new OperationList. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IOperationList); + + /** OperationList id. */ + public id?: (string|null); + + /** OperationList items. */ + public items: google.cloud.compute.v1.IOperation[]; + + /** OperationList kind. */ + public kind?: (string|null); + + /** OperationList nextPageToken. */ + public nextPageToken?: (string|null); + + /** OperationList selfLink. */ + public selfLink?: (string|null); + + /** OperationList warning. */ + public warning?: (google.cloud.compute.v1.IWarning|null); + + /** OperationList _id. */ + public _id?: "id"; + + /** OperationList _kind. */ + public _kind?: "kind"; + + /** OperationList _nextPageToken. */ + public _nextPageToken?: "nextPageToken"; + + /** OperationList _selfLink. */ + public _selfLink?: "selfLink"; + + /** OperationList _warning. */ + public _warning?: "warning"; + + /** + * Creates a new OperationList instance using the specified properties. + * @param [properties] Properties to set + * @returns OperationList instance + */ + public static create(properties?: google.cloud.compute.v1.IOperationList): google.cloud.compute.v1.OperationList; + + /** + * Encodes the specified OperationList message. Does not implicitly {@link google.cloud.compute.v1.OperationList.verify|verify} messages. + * @param message OperationList message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IOperationList, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified OperationList message, length delimited. Does not implicitly {@link google.cloud.compute.v1.OperationList.verify|verify} messages. + * @param message OperationList message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IOperationList, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an OperationList message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns OperationList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.OperationList; + + /** + * Decodes an OperationList message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns OperationList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.OperationList; + + /** + * Verifies an OperationList message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an OperationList message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OperationList + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.OperationList; + + /** + * Creates a plain object from an OperationList message. Also converts values to other types if specified. + * @param message OperationList + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.OperationList, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OperationList to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a WaitRegionOperationRequest. */ + interface IWaitRegionOperationRequest { + + /** WaitRegionOperationRequest operation */ + operation?: (string|null); + + /** WaitRegionOperationRequest project */ + project?: (string|null); + + /** WaitRegionOperationRequest region */ + region?: (string|null); + } + + /** Represents a WaitRegionOperationRequest. */ + class WaitRegionOperationRequest implements IWaitRegionOperationRequest { + + /** + * Constructs a new WaitRegionOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IWaitRegionOperationRequest); + + /** WaitRegionOperationRequest operation. */ + public operation: string; + + /** WaitRegionOperationRequest project. */ + public project: string; + + /** WaitRegionOperationRequest region. */ + public region: string; + + /** + * Creates a new WaitRegionOperationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns WaitRegionOperationRequest instance + */ + public static create(properties?: google.cloud.compute.v1.IWaitRegionOperationRequest): google.cloud.compute.v1.WaitRegionOperationRequest; + + /** + * Encodes the specified WaitRegionOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.WaitRegionOperationRequest.verify|verify} messages. + * @param message WaitRegionOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IWaitRegionOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified WaitRegionOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.WaitRegionOperationRequest.verify|verify} messages. + * @param message WaitRegionOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IWaitRegionOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a WaitRegionOperationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns WaitRegionOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.WaitRegionOperationRequest; + + /** + * Decodes a WaitRegionOperationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns WaitRegionOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.WaitRegionOperationRequest; + + /** + * Verifies a WaitRegionOperationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a WaitRegionOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WaitRegionOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.WaitRegionOperationRequest; + + /** + * Creates a plain object from a WaitRegionOperationRequest message. Also converts values to other types if specified. + * @param message WaitRegionOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.WaitRegionOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WaitRegionOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a DeleteZoneOperationRequest. */ + interface IDeleteZoneOperationRequest { + + /** DeleteZoneOperationRequest operation */ + operation?: (string|null); + + /** DeleteZoneOperationRequest project */ + project?: (string|null); + + /** DeleteZoneOperationRequest zone */ + zone?: (string|null); + } + + /** Represents a DeleteZoneOperationRequest. */ + class DeleteZoneOperationRequest implements IDeleteZoneOperationRequest { + + /** + * Constructs a new DeleteZoneOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IDeleteZoneOperationRequest); + + /** DeleteZoneOperationRequest operation. */ + public operation: string; + + /** DeleteZoneOperationRequest project. */ + public project: string; + + /** DeleteZoneOperationRequest zone. */ + public zone: string; + + /** + * Creates a new DeleteZoneOperationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteZoneOperationRequest instance + */ + public static create(properties?: google.cloud.compute.v1.IDeleteZoneOperationRequest): google.cloud.compute.v1.DeleteZoneOperationRequest; + + /** + * Encodes the specified DeleteZoneOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.DeleteZoneOperationRequest.verify|verify} messages. + * @param message DeleteZoneOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IDeleteZoneOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteZoneOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.DeleteZoneOperationRequest.verify|verify} messages. + * @param message DeleteZoneOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IDeleteZoneOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteZoneOperationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteZoneOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.DeleteZoneOperationRequest; + + /** + * Decodes a DeleteZoneOperationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteZoneOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.DeleteZoneOperationRequest; + + /** + * Verifies a DeleteZoneOperationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteZoneOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteZoneOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.DeleteZoneOperationRequest; + + /** + * Creates a plain object from a DeleteZoneOperationRequest message. Also converts values to other types if specified. + * @param message DeleteZoneOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.DeleteZoneOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteZoneOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a DeleteZoneOperationResponse. */ + interface IDeleteZoneOperationResponse { + } + + /** Represents a DeleteZoneOperationResponse. */ + class DeleteZoneOperationResponse implements IDeleteZoneOperationResponse { + + /** + * Constructs a new DeleteZoneOperationResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IDeleteZoneOperationResponse); + + /** + * Creates a new DeleteZoneOperationResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteZoneOperationResponse instance + */ + public static create(properties?: google.cloud.compute.v1.IDeleteZoneOperationResponse): google.cloud.compute.v1.DeleteZoneOperationResponse; + + /** + * Encodes the specified DeleteZoneOperationResponse message. Does not implicitly {@link google.cloud.compute.v1.DeleteZoneOperationResponse.verify|verify} messages. + * @param message DeleteZoneOperationResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IDeleteZoneOperationResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteZoneOperationResponse message, length delimited. Does not implicitly {@link google.cloud.compute.v1.DeleteZoneOperationResponse.verify|verify} messages. + * @param message DeleteZoneOperationResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IDeleteZoneOperationResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteZoneOperationResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteZoneOperationResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.DeleteZoneOperationResponse; + + /** + * Decodes a DeleteZoneOperationResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteZoneOperationResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.DeleteZoneOperationResponse; + + /** + * Verifies a DeleteZoneOperationResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteZoneOperationResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteZoneOperationResponse + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.DeleteZoneOperationResponse; + + /** + * Creates a plain object from a DeleteZoneOperationResponse message. Also converts values to other types if specified. + * @param message DeleteZoneOperationResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.DeleteZoneOperationResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteZoneOperationResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a GetZoneOperationRequest. */ + interface IGetZoneOperationRequest { + + /** GetZoneOperationRequest operation */ + operation?: (string|null); + + /** GetZoneOperationRequest project */ + project?: (string|null); + + /** GetZoneOperationRequest zone */ + zone?: (string|null); + } + + /** Represents a GetZoneOperationRequest. */ + class GetZoneOperationRequest implements IGetZoneOperationRequest { + + /** + * Constructs a new GetZoneOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IGetZoneOperationRequest); + + /** GetZoneOperationRequest operation. */ + public operation: string; + + /** GetZoneOperationRequest project. */ + public project: string; + + /** GetZoneOperationRequest zone. */ + public zone: string; + + /** + * Creates a new GetZoneOperationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetZoneOperationRequest instance + */ + public static create(properties?: google.cloud.compute.v1.IGetZoneOperationRequest): google.cloud.compute.v1.GetZoneOperationRequest; + + /** + * Encodes the specified GetZoneOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.GetZoneOperationRequest.verify|verify} messages. + * @param message GetZoneOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IGetZoneOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetZoneOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.GetZoneOperationRequest.verify|verify} messages. + * @param message GetZoneOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IGetZoneOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetZoneOperationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetZoneOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.GetZoneOperationRequest; + + /** + * Decodes a GetZoneOperationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetZoneOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.GetZoneOperationRequest; + + /** + * Verifies a GetZoneOperationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetZoneOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetZoneOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.GetZoneOperationRequest; + + /** + * Creates a plain object from a GetZoneOperationRequest message. Also converts values to other types if specified. + * @param message GetZoneOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.GetZoneOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetZoneOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a ListZoneOperationsRequest. */ + interface IListZoneOperationsRequest { + + /** ListZoneOperationsRequest filter */ + filter?: (string|null); + + /** ListZoneOperationsRequest maxResults */ + maxResults?: (number|null); + + /** ListZoneOperationsRequest orderBy */ + orderBy?: (string|null); + + /** ListZoneOperationsRequest pageToken */ + pageToken?: (string|null); + + /** ListZoneOperationsRequest project */ + project?: (string|null); + + /** ListZoneOperationsRequest returnPartialSuccess */ + returnPartialSuccess?: (boolean|null); + + /** ListZoneOperationsRequest zone */ + zone?: (string|null); + } + + /** Represents a ListZoneOperationsRequest. */ + class ListZoneOperationsRequest implements IListZoneOperationsRequest { + + /** + * Constructs a new ListZoneOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IListZoneOperationsRequest); + + /** ListZoneOperationsRequest filter. */ + public filter?: (string|null); + + /** ListZoneOperationsRequest maxResults. */ + public maxResults?: (number|null); + + /** ListZoneOperationsRequest orderBy. */ + public orderBy?: (string|null); + + /** ListZoneOperationsRequest pageToken. */ + public pageToken?: (string|null); + + /** ListZoneOperationsRequest project. */ + public project: string; + + /** ListZoneOperationsRequest returnPartialSuccess. */ + public returnPartialSuccess?: (boolean|null); + + /** ListZoneOperationsRequest zone. */ + public zone: string; + + /** ListZoneOperationsRequest _filter. */ + public _filter?: "filter"; + + /** ListZoneOperationsRequest _maxResults. */ + public _maxResults?: "maxResults"; + + /** ListZoneOperationsRequest _orderBy. */ + public _orderBy?: "orderBy"; + + /** ListZoneOperationsRequest _pageToken. */ + public _pageToken?: "pageToken"; + + /** ListZoneOperationsRequest _returnPartialSuccess. */ + public _returnPartialSuccess?: "returnPartialSuccess"; + + /** + * Creates a new ListZoneOperationsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListZoneOperationsRequest instance + */ + public static create(properties?: google.cloud.compute.v1.IListZoneOperationsRequest): google.cloud.compute.v1.ListZoneOperationsRequest; + + /** + * Encodes the specified ListZoneOperationsRequest message. Does not implicitly {@link google.cloud.compute.v1.ListZoneOperationsRequest.verify|verify} messages. + * @param message ListZoneOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IListZoneOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListZoneOperationsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.ListZoneOperationsRequest.verify|verify} messages. + * @param message ListZoneOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IListZoneOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListZoneOperationsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListZoneOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.ListZoneOperationsRequest; + + /** + * Decodes a ListZoneOperationsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListZoneOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.ListZoneOperationsRequest; + + /** + * Verifies a ListZoneOperationsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListZoneOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListZoneOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.ListZoneOperationsRequest; + + /** + * Creates a plain object from a ListZoneOperationsRequest message. Also converts values to other types if specified. + * @param message ListZoneOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.ListZoneOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListZoneOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a WaitZoneOperationRequest. */ + interface IWaitZoneOperationRequest { + + /** WaitZoneOperationRequest operation */ + operation?: (string|null); + + /** WaitZoneOperationRequest project */ + project?: (string|null); + + /** WaitZoneOperationRequest zone */ + zone?: (string|null); + } + + /** Represents a WaitZoneOperationRequest. */ + class WaitZoneOperationRequest implements IWaitZoneOperationRequest { + + /** + * Constructs a new WaitZoneOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IWaitZoneOperationRequest); + + /** WaitZoneOperationRequest operation. */ + public operation: string; + + /** WaitZoneOperationRequest project. */ + public project: string; + + /** WaitZoneOperationRequest zone. */ + public zone: string; + + /** + * Creates a new WaitZoneOperationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns WaitZoneOperationRequest instance + */ + public static create(properties?: google.cloud.compute.v1.IWaitZoneOperationRequest): google.cloud.compute.v1.WaitZoneOperationRequest; + + /** + * Encodes the specified WaitZoneOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.WaitZoneOperationRequest.verify|verify} messages. + * @param message WaitZoneOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IWaitZoneOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified WaitZoneOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.WaitZoneOperationRequest.verify|verify} messages. + * @param message WaitZoneOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IWaitZoneOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a WaitZoneOperationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns WaitZoneOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.WaitZoneOperationRequest; + + /** + * Decodes a WaitZoneOperationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns WaitZoneOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.WaitZoneOperationRequest; + + /** + * Verifies a WaitZoneOperationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a WaitZoneOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WaitZoneOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.WaitZoneOperationRequest; + + /** + * Creates a plain object from a WaitZoneOperationRequest message. Also converts values to other types if specified. + * @param message WaitZoneOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.WaitZoneOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WaitZoneOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of an AggregatedListGlobalOperationsRequest. */ + interface IAggregatedListGlobalOperationsRequest { + + /** AggregatedListGlobalOperationsRequest filter */ + filter?: (string|null); + + /** AggregatedListGlobalOperationsRequest includeAllScopes */ + includeAllScopes?: (boolean|null); + + /** AggregatedListGlobalOperationsRequest maxResults */ + maxResults?: (number|null); + + /** AggregatedListGlobalOperationsRequest orderBy */ + orderBy?: (string|null); + + /** AggregatedListGlobalOperationsRequest pageToken */ + pageToken?: (string|null); + + /** AggregatedListGlobalOperationsRequest project */ + project?: (string|null); + + /** AggregatedListGlobalOperationsRequest returnPartialSuccess */ + returnPartialSuccess?: (boolean|null); + } + + /** Represents an AggregatedListGlobalOperationsRequest. */ + class AggregatedListGlobalOperationsRequest implements IAggregatedListGlobalOperationsRequest { + + /** + * Constructs a new AggregatedListGlobalOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IAggregatedListGlobalOperationsRequest); + + /** AggregatedListGlobalOperationsRequest filter. */ + public filter?: (string|null); + + /** AggregatedListGlobalOperationsRequest includeAllScopes. */ + public includeAllScopes?: (boolean|null); + + /** AggregatedListGlobalOperationsRequest maxResults. */ + public maxResults?: (number|null); + + /** AggregatedListGlobalOperationsRequest orderBy. */ + public orderBy?: (string|null); + + /** AggregatedListGlobalOperationsRequest pageToken. */ + public pageToken?: (string|null); + + /** AggregatedListGlobalOperationsRequest project. */ + public project: string; + + /** AggregatedListGlobalOperationsRequest returnPartialSuccess. */ + public returnPartialSuccess?: (boolean|null); + + /** AggregatedListGlobalOperationsRequest _filter. */ + public _filter?: "filter"; + + /** AggregatedListGlobalOperationsRequest _includeAllScopes. */ + public _includeAllScopes?: "includeAllScopes"; + + /** AggregatedListGlobalOperationsRequest _maxResults. */ + public _maxResults?: "maxResults"; + + /** AggregatedListGlobalOperationsRequest _orderBy. */ + public _orderBy?: "orderBy"; + + /** AggregatedListGlobalOperationsRequest _pageToken. */ + public _pageToken?: "pageToken"; + + /** AggregatedListGlobalOperationsRequest _returnPartialSuccess. */ + public _returnPartialSuccess?: "returnPartialSuccess"; + + /** + * Creates a new AggregatedListGlobalOperationsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns AggregatedListGlobalOperationsRequest instance + */ + public static create(properties?: google.cloud.compute.v1.IAggregatedListGlobalOperationsRequest): google.cloud.compute.v1.AggregatedListGlobalOperationsRequest; + + /** + * Encodes the specified AggregatedListGlobalOperationsRequest message. Does not implicitly {@link google.cloud.compute.v1.AggregatedListGlobalOperationsRequest.verify|verify} messages. + * @param message AggregatedListGlobalOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IAggregatedListGlobalOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AggregatedListGlobalOperationsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.AggregatedListGlobalOperationsRequest.verify|verify} messages. + * @param message AggregatedListGlobalOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IAggregatedListGlobalOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AggregatedListGlobalOperationsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AggregatedListGlobalOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.AggregatedListGlobalOperationsRequest; + + /** + * Decodes an AggregatedListGlobalOperationsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AggregatedListGlobalOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.AggregatedListGlobalOperationsRequest; + + /** + * Verifies an AggregatedListGlobalOperationsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AggregatedListGlobalOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AggregatedListGlobalOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.AggregatedListGlobalOperationsRequest; + + /** + * Creates a plain object from an AggregatedListGlobalOperationsRequest message. Also converts values to other types if specified. + * @param message AggregatedListGlobalOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.AggregatedListGlobalOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AggregatedListGlobalOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a DeleteGlobalOperationRequest. */ + interface IDeleteGlobalOperationRequest { + + /** DeleteGlobalOperationRequest operation */ + operation?: (string|null); + + /** DeleteGlobalOperationRequest project */ + project?: (string|null); + } + + /** Represents a DeleteGlobalOperationRequest. */ + class DeleteGlobalOperationRequest implements IDeleteGlobalOperationRequest { + + /** + * Constructs a new DeleteGlobalOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IDeleteGlobalOperationRequest); + + /** DeleteGlobalOperationRequest operation. */ + public operation: string; + + /** DeleteGlobalOperationRequest project. */ + public project: string; + + /** + * Creates a new DeleteGlobalOperationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteGlobalOperationRequest instance + */ + public static create(properties?: google.cloud.compute.v1.IDeleteGlobalOperationRequest): google.cloud.compute.v1.DeleteGlobalOperationRequest; + + /** + * Encodes the specified DeleteGlobalOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.DeleteGlobalOperationRequest.verify|verify} messages. + * @param message DeleteGlobalOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IDeleteGlobalOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteGlobalOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.DeleteGlobalOperationRequest.verify|verify} messages. + * @param message DeleteGlobalOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IDeleteGlobalOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteGlobalOperationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteGlobalOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.DeleteGlobalOperationRequest; + + /** + * Decodes a DeleteGlobalOperationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteGlobalOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.DeleteGlobalOperationRequest; + + /** + * Verifies a DeleteGlobalOperationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteGlobalOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteGlobalOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.DeleteGlobalOperationRequest; + + /** + * Creates a plain object from a DeleteGlobalOperationRequest message. Also converts values to other types if specified. + * @param message DeleteGlobalOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.DeleteGlobalOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteGlobalOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a DeleteGlobalOperationResponse. */ + interface IDeleteGlobalOperationResponse { + } + + /** Represents a DeleteGlobalOperationResponse. */ + class DeleteGlobalOperationResponse implements IDeleteGlobalOperationResponse { + + /** + * Constructs a new DeleteGlobalOperationResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IDeleteGlobalOperationResponse); + + /** + * Creates a new DeleteGlobalOperationResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteGlobalOperationResponse instance + */ + public static create(properties?: google.cloud.compute.v1.IDeleteGlobalOperationResponse): google.cloud.compute.v1.DeleteGlobalOperationResponse; + + /** + * Encodes the specified DeleteGlobalOperationResponse message. Does not implicitly {@link google.cloud.compute.v1.DeleteGlobalOperationResponse.verify|verify} messages. + * @param message DeleteGlobalOperationResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IDeleteGlobalOperationResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteGlobalOperationResponse message, length delimited. Does not implicitly {@link google.cloud.compute.v1.DeleteGlobalOperationResponse.verify|verify} messages. + * @param message DeleteGlobalOperationResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IDeleteGlobalOperationResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteGlobalOperationResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteGlobalOperationResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.DeleteGlobalOperationResponse; + + /** + * Decodes a DeleteGlobalOperationResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteGlobalOperationResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.DeleteGlobalOperationResponse; + + /** + * Verifies a DeleteGlobalOperationResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteGlobalOperationResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteGlobalOperationResponse + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.DeleteGlobalOperationResponse; + + /** + * Creates a plain object from a DeleteGlobalOperationResponse message. Also converts values to other types if specified. + * @param message DeleteGlobalOperationResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.DeleteGlobalOperationResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteGlobalOperationResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a GetGlobalOperationRequest. */ + interface IGetGlobalOperationRequest { + + /** GetGlobalOperationRequest operation */ + operation?: (string|null); + + /** GetGlobalOperationRequest project */ + project?: (string|null); + } + + /** Represents a GetGlobalOperationRequest. */ + class GetGlobalOperationRequest implements IGetGlobalOperationRequest { + + /** + * Constructs a new GetGlobalOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IGetGlobalOperationRequest); + + /** GetGlobalOperationRequest operation. */ + public operation: string; + + /** GetGlobalOperationRequest project. */ + public project: string; + + /** + * Creates a new GetGlobalOperationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetGlobalOperationRequest instance + */ + public static create(properties?: google.cloud.compute.v1.IGetGlobalOperationRequest): google.cloud.compute.v1.GetGlobalOperationRequest; + + /** + * Encodes the specified GetGlobalOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.GetGlobalOperationRequest.verify|verify} messages. + * @param message GetGlobalOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IGetGlobalOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetGlobalOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.GetGlobalOperationRequest.verify|verify} messages. + * @param message GetGlobalOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IGetGlobalOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetGlobalOperationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetGlobalOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.GetGlobalOperationRequest; + + /** + * Decodes a GetGlobalOperationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetGlobalOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.GetGlobalOperationRequest; + + /** + * Verifies a GetGlobalOperationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetGlobalOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetGlobalOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.GetGlobalOperationRequest; + + /** + * Creates a plain object from a GetGlobalOperationRequest message. Also converts values to other types if specified. + * @param message GetGlobalOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.GetGlobalOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetGlobalOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a ListGlobalOperationsRequest. */ + interface IListGlobalOperationsRequest { + + /** ListGlobalOperationsRequest filter */ + filter?: (string|null); + + /** ListGlobalOperationsRequest maxResults */ + maxResults?: (number|null); + + /** ListGlobalOperationsRequest orderBy */ + orderBy?: (string|null); + + /** ListGlobalOperationsRequest pageToken */ + pageToken?: (string|null); + + /** ListGlobalOperationsRequest project */ + project?: (string|null); + + /** ListGlobalOperationsRequest returnPartialSuccess */ + returnPartialSuccess?: (boolean|null); + } + + /** Represents a ListGlobalOperationsRequest. */ + class ListGlobalOperationsRequest implements IListGlobalOperationsRequest { + + /** + * Constructs a new ListGlobalOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IListGlobalOperationsRequest); + + /** ListGlobalOperationsRequest filter. */ + public filter?: (string|null); + + /** ListGlobalOperationsRequest maxResults. */ + public maxResults?: (number|null); + + /** ListGlobalOperationsRequest orderBy. */ + public orderBy?: (string|null); + + /** ListGlobalOperationsRequest pageToken. */ + public pageToken?: (string|null); + + /** ListGlobalOperationsRequest project. */ + public project: string; + + /** ListGlobalOperationsRequest returnPartialSuccess. */ + public returnPartialSuccess?: (boolean|null); + + /** ListGlobalOperationsRequest _filter. */ + public _filter?: "filter"; + + /** ListGlobalOperationsRequest _maxResults. */ + public _maxResults?: "maxResults"; + + /** ListGlobalOperationsRequest _orderBy. */ + public _orderBy?: "orderBy"; + + /** ListGlobalOperationsRequest _pageToken. */ + public _pageToken?: "pageToken"; + + /** ListGlobalOperationsRequest _returnPartialSuccess. */ + public _returnPartialSuccess?: "returnPartialSuccess"; + + /** + * Creates a new ListGlobalOperationsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListGlobalOperationsRequest instance + */ + public static create(properties?: google.cloud.compute.v1.IListGlobalOperationsRequest): google.cloud.compute.v1.ListGlobalOperationsRequest; + + /** + * Encodes the specified ListGlobalOperationsRequest message. Does not implicitly {@link google.cloud.compute.v1.ListGlobalOperationsRequest.verify|verify} messages. + * @param message ListGlobalOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IListGlobalOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListGlobalOperationsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.ListGlobalOperationsRequest.verify|verify} messages. + * @param message ListGlobalOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IListGlobalOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListGlobalOperationsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListGlobalOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.ListGlobalOperationsRequest; + + /** + * Decodes a ListGlobalOperationsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListGlobalOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.ListGlobalOperationsRequest; + + /** + * Verifies a ListGlobalOperationsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListGlobalOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListGlobalOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.ListGlobalOperationsRequest; + + /** + * Creates a plain object from a ListGlobalOperationsRequest message. Also converts values to other types if specified. + * @param message ListGlobalOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.ListGlobalOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListGlobalOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a WaitGlobalOperationRequest. */ + interface IWaitGlobalOperationRequest { + + /** WaitGlobalOperationRequest operation */ + operation?: (string|null); + + /** WaitGlobalOperationRequest project */ + project?: (string|null); + } + + /** Represents a WaitGlobalOperationRequest. */ + class WaitGlobalOperationRequest implements IWaitGlobalOperationRequest { + + /** + * Constructs a new WaitGlobalOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IWaitGlobalOperationRequest); + + /** WaitGlobalOperationRequest operation. */ + public operation: string; + + /** WaitGlobalOperationRequest project. */ + public project: string; + + /** + * Creates a new WaitGlobalOperationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns WaitGlobalOperationRequest instance + */ + public static create(properties?: google.cloud.compute.v1.IWaitGlobalOperationRequest): google.cloud.compute.v1.WaitGlobalOperationRequest; + + /** + * Encodes the specified WaitGlobalOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.WaitGlobalOperationRequest.verify|verify} messages. + * @param message WaitGlobalOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IWaitGlobalOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified WaitGlobalOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.WaitGlobalOperationRequest.verify|verify} messages. + * @param message WaitGlobalOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IWaitGlobalOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a WaitGlobalOperationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns WaitGlobalOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.WaitGlobalOperationRequest; + + /** + * Decodes a WaitGlobalOperationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns WaitGlobalOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.WaitGlobalOperationRequest; + + /** + * Verifies a WaitGlobalOperationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a WaitGlobalOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WaitGlobalOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.WaitGlobalOperationRequest; + + /** + * Creates a plain object from a WaitGlobalOperationRequest message. Also converts values to other types if specified. + * @param message WaitGlobalOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.WaitGlobalOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WaitGlobalOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a DeleteGlobalOrganizationOperationRequest. */ + interface IDeleteGlobalOrganizationOperationRequest { + + /** DeleteGlobalOrganizationOperationRequest operation */ + operation?: (string|null); + + /** DeleteGlobalOrganizationOperationRequest parentId */ + parentId?: (string|null); + } + + /** Represents a DeleteGlobalOrganizationOperationRequest. */ + class DeleteGlobalOrganizationOperationRequest implements IDeleteGlobalOrganizationOperationRequest { + + /** + * Constructs a new DeleteGlobalOrganizationOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IDeleteGlobalOrganizationOperationRequest); + + /** DeleteGlobalOrganizationOperationRequest operation. */ + public operation: string; + + /** DeleteGlobalOrganizationOperationRequest parentId. */ + public parentId?: (string|null); + + /** DeleteGlobalOrganizationOperationRequest _parentId. */ + public _parentId?: "parentId"; + + /** + * Creates a new DeleteGlobalOrganizationOperationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteGlobalOrganizationOperationRequest instance + */ + public static create(properties?: google.cloud.compute.v1.IDeleteGlobalOrganizationOperationRequest): google.cloud.compute.v1.DeleteGlobalOrganizationOperationRequest; + + /** + * Encodes the specified DeleteGlobalOrganizationOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.DeleteGlobalOrganizationOperationRequest.verify|verify} messages. + * @param message DeleteGlobalOrganizationOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IDeleteGlobalOrganizationOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteGlobalOrganizationOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.DeleteGlobalOrganizationOperationRequest.verify|verify} messages. + * @param message DeleteGlobalOrganizationOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IDeleteGlobalOrganizationOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteGlobalOrganizationOperationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteGlobalOrganizationOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.DeleteGlobalOrganizationOperationRequest; + + /** + * Decodes a DeleteGlobalOrganizationOperationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteGlobalOrganizationOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.DeleteGlobalOrganizationOperationRequest; + + /** + * Verifies a DeleteGlobalOrganizationOperationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteGlobalOrganizationOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteGlobalOrganizationOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.DeleteGlobalOrganizationOperationRequest; + + /** + * Creates a plain object from a DeleteGlobalOrganizationOperationRequest message. Also converts values to other types if specified. + * @param message DeleteGlobalOrganizationOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.DeleteGlobalOrganizationOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteGlobalOrganizationOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a DeleteGlobalOrganizationOperationResponse. */ + interface IDeleteGlobalOrganizationOperationResponse { + } + + /** Represents a DeleteGlobalOrganizationOperationResponse. */ + class DeleteGlobalOrganizationOperationResponse implements IDeleteGlobalOrganizationOperationResponse { + + /** + * Constructs a new DeleteGlobalOrganizationOperationResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IDeleteGlobalOrganizationOperationResponse); + + /** + * Creates a new DeleteGlobalOrganizationOperationResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteGlobalOrganizationOperationResponse instance + */ + public static create(properties?: google.cloud.compute.v1.IDeleteGlobalOrganizationOperationResponse): google.cloud.compute.v1.DeleteGlobalOrganizationOperationResponse; + + /** + * Encodes the specified DeleteGlobalOrganizationOperationResponse message. Does not implicitly {@link google.cloud.compute.v1.DeleteGlobalOrganizationOperationResponse.verify|verify} messages. + * @param message DeleteGlobalOrganizationOperationResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IDeleteGlobalOrganizationOperationResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteGlobalOrganizationOperationResponse message, length delimited. Does not implicitly {@link google.cloud.compute.v1.DeleteGlobalOrganizationOperationResponse.verify|verify} messages. + * @param message DeleteGlobalOrganizationOperationResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IDeleteGlobalOrganizationOperationResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteGlobalOrganizationOperationResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteGlobalOrganizationOperationResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.DeleteGlobalOrganizationOperationResponse; + + /** + * Decodes a DeleteGlobalOrganizationOperationResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteGlobalOrganizationOperationResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.DeleteGlobalOrganizationOperationResponse; + + /** + * Verifies a DeleteGlobalOrganizationOperationResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteGlobalOrganizationOperationResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteGlobalOrganizationOperationResponse + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.DeleteGlobalOrganizationOperationResponse; + + /** + * Creates a plain object from a DeleteGlobalOrganizationOperationResponse message. Also converts values to other types if specified. + * @param message DeleteGlobalOrganizationOperationResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.DeleteGlobalOrganizationOperationResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteGlobalOrganizationOperationResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a GetGlobalOrganizationOperationRequest. */ + interface IGetGlobalOrganizationOperationRequest { + + /** GetGlobalOrganizationOperationRequest operation */ + operation?: (string|null); + + /** GetGlobalOrganizationOperationRequest parentId */ + parentId?: (string|null); + } + + /** Represents a GetGlobalOrganizationOperationRequest. */ + class GetGlobalOrganizationOperationRequest implements IGetGlobalOrganizationOperationRequest { + + /** + * Constructs a new GetGlobalOrganizationOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IGetGlobalOrganizationOperationRequest); + + /** GetGlobalOrganizationOperationRequest operation. */ + public operation: string; + + /** GetGlobalOrganizationOperationRequest parentId. */ + public parentId?: (string|null); + + /** GetGlobalOrganizationOperationRequest _parentId. */ + public _parentId?: "parentId"; + + /** + * Creates a new GetGlobalOrganizationOperationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetGlobalOrganizationOperationRequest instance + */ + public static create(properties?: google.cloud.compute.v1.IGetGlobalOrganizationOperationRequest): google.cloud.compute.v1.GetGlobalOrganizationOperationRequest; + + /** + * Encodes the specified GetGlobalOrganizationOperationRequest message. Does not implicitly {@link google.cloud.compute.v1.GetGlobalOrganizationOperationRequest.verify|verify} messages. + * @param message GetGlobalOrganizationOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IGetGlobalOrganizationOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetGlobalOrganizationOperationRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.GetGlobalOrganizationOperationRequest.verify|verify} messages. + * @param message GetGlobalOrganizationOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IGetGlobalOrganizationOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetGlobalOrganizationOperationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetGlobalOrganizationOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.GetGlobalOrganizationOperationRequest; + + /** + * Decodes a GetGlobalOrganizationOperationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetGlobalOrganizationOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.GetGlobalOrganizationOperationRequest; + + /** + * Verifies a GetGlobalOrganizationOperationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetGlobalOrganizationOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetGlobalOrganizationOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.GetGlobalOrganizationOperationRequest; + + /** + * Creates a plain object from a GetGlobalOrganizationOperationRequest message. Also converts values to other types if specified. + * @param message GetGlobalOrganizationOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.GetGlobalOrganizationOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetGlobalOrganizationOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a ListGlobalOrganizationOperationsRequest. */ + interface IListGlobalOrganizationOperationsRequest { + + /** ListGlobalOrganizationOperationsRequest filter */ + filter?: (string|null); + + /** ListGlobalOrganizationOperationsRequest maxResults */ + maxResults?: (number|null); + + /** ListGlobalOrganizationOperationsRequest orderBy */ + orderBy?: (string|null); + + /** ListGlobalOrganizationOperationsRequest pageToken */ + pageToken?: (string|null); + + /** ListGlobalOrganizationOperationsRequest parentId */ + parentId?: (string|null); + + /** ListGlobalOrganizationOperationsRequest returnPartialSuccess */ + returnPartialSuccess?: (boolean|null); + } + + /** Represents a ListGlobalOrganizationOperationsRequest. */ + class ListGlobalOrganizationOperationsRequest implements IListGlobalOrganizationOperationsRequest { + + /** + * Constructs a new ListGlobalOrganizationOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1.IListGlobalOrganizationOperationsRequest); + + /** ListGlobalOrganizationOperationsRequest filter. */ + public filter?: (string|null); + + /** ListGlobalOrganizationOperationsRequest maxResults. */ + public maxResults?: (number|null); + + /** ListGlobalOrganizationOperationsRequest orderBy. */ + public orderBy?: (string|null); + + /** ListGlobalOrganizationOperationsRequest pageToken. */ + public pageToken?: (string|null); + + /** ListGlobalOrganizationOperationsRequest parentId. */ + public parentId?: (string|null); + + /** ListGlobalOrganizationOperationsRequest returnPartialSuccess. */ + public returnPartialSuccess?: (boolean|null); + + /** ListGlobalOrganizationOperationsRequest _filter. */ + public _filter?: "filter"; + + /** ListGlobalOrganizationOperationsRequest _maxResults. */ + public _maxResults?: "maxResults"; + + /** ListGlobalOrganizationOperationsRequest _orderBy. */ + public _orderBy?: "orderBy"; + + /** ListGlobalOrganizationOperationsRequest _pageToken. */ + public _pageToken?: "pageToken"; + + /** ListGlobalOrganizationOperationsRequest _parentId. */ + public _parentId?: "parentId"; + + /** ListGlobalOrganizationOperationsRequest _returnPartialSuccess. */ + public _returnPartialSuccess?: "returnPartialSuccess"; + + /** + * Creates a new ListGlobalOrganizationOperationsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListGlobalOrganizationOperationsRequest instance + */ + public static create(properties?: google.cloud.compute.v1.IListGlobalOrganizationOperationsRequest): google.cloud.compute.v1.ListGlobalOrganizationOperationsRequest; + + /** + * Encodes the specified ListGlobalOrganizationOperationsRequest message. Does not implicitly {@link google.cloud.compute.v1.ListGlobalOrganizationOperationsRequest.verify|verify} messages. + * @param message ListGlobalOrganizationOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1.IListGlobalOrganizationOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListGlobalOrganizationOperationsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1.ListGlobalOrganizationOperationsRequest.verify|verify} messages. + * @param message ListGlobalOrganizationOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1.IListGlobalOrganizationOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListGlobalOrganizationOperationsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListGlobalOrganizationOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1.ListGlobalOrganizationOperationsRequest; + + /** + * Decodes a ListGlobalOrganizationOperationsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListGlobalOrganizationOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1.ListGlobalOrganizationOperationsRequest; + + /** + * Verifies a ListGlobalOrganizationOperationsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListGlobalOrganizationOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListGlobalOrganizationOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1.ListGlobalOrganizationOperationsRequest; + + /** + * Creates a plain object from a ListGlobalOrganizationOperationsRequest message. Also converts values to other types if specified. + * @param message ListGlobalOrganizationOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1.ListGlobalOrganizationOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListGlobalOrganizationOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Represents a RegionOperations */ + class RegionOperations extends $protobuf.rpc.Service { + + /** + * Constructs a new RegionOperations service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new RegionOperations service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): RegionOperations; + + /** + * Calls Delete. + * @param request DeleteRegionOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and DeleteRegionOperationResponse + */ + public delete(request: google.cloud.compute.v1.IDeleteRegionOperationRequest, callback: google.cloud.compute.v1.RegionOperations.DeleteCallback): void; + + /** + * Calls Delete. + * @param request DeleteRegionOperationRequest message or plain object + * @returns Promise + */ + public delete(request: google.cloud.compute.v1.IDeleteRegionOperationRequest): Promise; + + /** + * Calls Get. + * @param request GetRegionOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public get(request: google.cloud.compute.v1.IGetRegionOperationRequest, callback: google.cloud.compute.v1.RegionOperations.GetCallback): void; + + /** + * Calls Get. + * @param request GetRegionOperationRequest message or plain object + * @returns Promise + */ + public get(request: google.cloud.compute.v1.IGetRegionOperationRequest): Promise; + + /** + * Calls List. + * @param request ListRegionOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and OperationList + */ + public list(request: google.cloud.compute.v1.IListRegionOperationsRequest, callback: google.cloud.compute.v1.RegionOperations.ListCallback): void; + + /** + * Calls List. + * @param request ListRegionOperationsRequest message or plain object + * @returns Promise + */ + public list(request: google.cloud.compute.v1.IListRegionOperationsRequest): Promise; + + /** + * Calls Wait. + * @param request WaitRegionOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public wait(request: google.cloud.compute.v1.IWaitRegionOperationRequest, callback: google.cloud.compute.v1.RegionOperations.WaitCallback): void; + + /** + * Calls Wait. + * @param request WaitRegionOperationRequest message or plain object + * @returns Promise + */ + public wait(request: google.cloud.compute.v1.IWaitRegionOperationRequest): Promise; + } + + namespace RegionOperations { + + /** + * Callback as used by {@link google.cloud.compute.v1.RegionOperations#delete_}. + * @param error Error, if any + * @param [response] DeleteRegionOperationResponse + */ + type DeleteCallback = (error: (Error|null), response?: google.cloud.compute.v1.DeleteRegionOperationResponse) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1.RegionOperations#get}. + * @param error Error, if any + * @param [response] Operation + */ + type GetCallback = (error: (Error|null), response?: google.cloud.compute.v1.Operation) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1.RegionOperations#list}. + * @param error Error, if any + * @param [response] OperationList + */ + type ListCallback = (error: (Error|null), response?: google.cloud.compute.v1.OperationList) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1.RegionOperations#wait}. + * @param error Error, if any + * @param [response] Operation + */ + type WaitCallback = (error: (Error|null), response?: google.cloud.compute.v1.Operation) => void; + } + + /** Represents a ZoneOperations */ + class ZoneOperations extends $protobuf.rpc.Service { + + /** + * Constructs a new ZoneOperations service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new ZoneOperations service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): ZoneOperations; + + /** + * Calls Delete. + * @param request DeleteZoneOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and DeleteZoneOperationResponse + */ + public delete(request: google.cloud.compute.v1.IDeleteZoneOperationRequest, callback: google.cloud.compute.v1.ZoneOperations.DeleteCallback): void; + + /** + * Calls Delete. + * @param request DeleteZoneOperationRequest message or plain object + * @returns Promise + */ + public delete(request: google.cloud.compute.v1.IDeleteZoneOperationRequest): Promise; + + /** + * Calls Get. + * @param request GetZoneOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public get(request: google.cloud.compute.v1.IGetZoneOperationRequest, callback: google.cloud.compute.v1.ZoneOperations.GetCallback): void; + + /** + * Calls Get. + * @param request GetZoneOperationRequest message or plain object + * @returns Promise + */ + public get(request: google.cloud.compute.v1.IGetZoneOperationRequest): Promise; + + /** + * Calls List. + * @param request ListZoneOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and OperationList + */ + public list(request: google.cloud.compute.v1.IListZoneOperationsRequest, callback: google.cloud.compute.v1.ZoneOperations.ListCallback): void; + + /** + * Calls List. + * @param request ListZoneOperationsRequest message or plain object + * @returns Promise + */ + public list(request: google.cloud.compute.v1.IListZoneOperationsRequest): Promise; + + /** + * Calls Wait. + * @param request WaitZoneOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public wait(request: google.cloud.compute.v1.IWaitZoneOperationRequest, callback: google.cloud.compute.v1.ZoneOperations.WaitCallback): void; + + /** + * Calls Wait. + * @param request WaitZoneOperationRequest message or plain object + * @returns Promise + */ + public wait(request: google.cloud.compute.v1.IWaitZoneOperationRequest): Promise; + } + + namespace ZoneOperations { + + /** + * Callback as used by {@link google.cloud.compute.v1.ZoneOperations#delete_}. + * @param error Error, if any + * @param [response] DeleteZoneOperationResponse + */ + type DeleteCallback = (error: (Error|null), response?: google.cloud.compute.v1.DeleteZoneOperationResponse) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1.ZoneOperations#get}. + * @param error Error, if any + * @param [response] Operation + */ + type GetCallback = (error: (Error|null), response?: google.cloud.compute.v1.Operation) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1.ZoneOperations#list}. + * @param error Error, if any + * @param [response] OperationList + */ + type ListCallback = (error: (Error|null), response?: google.cloud.compute.v1.OperationList) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1.ZoneOperations#wait}. + * @param error Error, if any + * @param [response] Operation + */ + type WaitCallback = (error: (Error|null), response?: google.cloud.compute.v1.Operation) => void; + } + + /** Represents a GlobalOperations */ + class GlobalOperations extends $protobuf.rpc.Service { + + /** + * Constructs a new GlobalOperations service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new GlobalOperations service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): GlobalOperations; + + /** + * Calls AggregatedList. + * @param request AggregatedListGlobalOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and OperationAggregatedList + */ + public aggregatedList(request: google.cloud.compute.v1.IAggregatedListGlobalOperationsRequest, callback: google.cloud.compute.v1.GlobalOperations.AggregatedListCallback): void; + + /** + * Calls AggregatedList. + * @param request AggregatedListGlobalOperationsRequest message or plain object + * @returns Promise + */ + public aggregatedList(request: google.cloud.compute.v1.IAggregatedListGlobalOperationsRequest): Promise; + + /** + * Calls Delete. + * @param request DeleteGlobalOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and DeleteGlobalOperationResponse + */ + public delete(request: google.cloud.compute.v1.IDeleteGlobalOperationRequest, callback: google.cloud.compute.v1.GlobalOperations.DeleteCallback): void; + + /** + * Calls Delete. + * @param request DeleteGlobalOperationRequest message or plain object + * @returns Promise + */ + public delete(request: google.cloud.compute.v1.IDeleteGlobalOperationRequest): Promise; + + /** + * Calls Get. + * @param request GetGlobalOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public get(request: google.cloud.compute.v1.IGetGlobalOperationRequest, callback: google.cloud.compute.v1.GlobalOperations.GetCallback): void; + + /** + * Calls Get. + * @param request GetGlobalOperationRequest message or plain object + * @returns Promise + */ + public get(request: google.cloud.compute.v1.IGetGlobalOperationRequest): Promise; + + /** + * Calls List. + * @param request ListGlobalOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and OperationList + */ + public list(request: google.cloud.compute.v1.IListGlobalOperationsRequest, callback: google.cloud.compute.v1.GlobalOperations.ListCallback): void; + + /** + * Calls List. + * @param request ListGlobalOperationsRequest message or plain object + * @returns Promise + */ + public list(request: google.cloud.compute.v1.IListGlobalOperationsRequest): Promise; + + /** + * Calls Wait. + * @param request WaitGlobalOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public wait(request: google.cloud.compute.v1.IWaitGlobalOperationRequest, callback: google.cloud.compute.v1.GlobalOperations.WaitCallback): void; + + /** + * Calls Wait. + * @param request WaitGlobalOperationRequest message or plain object + * @returns Promise + */ + public wait(request: google.cloud.compute.v1.IWaitGlobalOperationRequest): Promise; + } + + namespace GlobalOperations { + + /** + * Callback as used by {@link google.cloud.compute.v1.GlobalOperations#aggregatedList}. + * @param error Error, if any + * @param [response] OperationAggregatedList + */ + type AggregatedListCallback = (error: (Error|null), response?: google.cloud.compute.v1.OperationAggregatedList) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1.GlobalOperations#delete_}. + * @param error Error, if any + * @param [response] DeleteGlobalOperationResponse + */ + type DeleteCallback = (error: (Error|null), response?: google.cloud.compute.v1.DeleteGlobalOperationResponse) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1.GlobalOperations#get}. + * @param error Error, if any + * @param [response] Operation + */ + type GetCallback = (error: (Error|null), response?: google.cloud.compute.v1.Operation) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1.GlobalOperations#list}. + * @param error Error, if any + * @param [response] OperationList + */ + type ListCallback = (error: (Error|null), response?: google.cloud.compute.v1.OperationList) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1.GlobalOperations#wait}. + * @param error Error, if any + * @param [response] Operation + */ + type WaitCallback = (error: (Error|null), response?: google.cloud.compute.v1.Operation) => void; + } + + /** Represents a GlobalOrganizationOperations */ + class GlobalOrganizationOperations extends $protobuf.rpc.Service { + + /** + * Constructs a new GlobalOrganizationOperations service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new GlobalOrganizationOperations service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): GlobalOrganizationOperations; + + /** + * Calls Delete. + * @param request DeleteGlobalOrganizationOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and DeleteGlobalOrganizationOperationResponse + */ + public delete(request: google.cloud.compute.v1.IDeleteGlobalOrganizationOperationRequest, callback: google.cloud.compute.v1.GlobalOrganizationOperations.DeleteCallback): void; + + /** + * Calls Delete. + * @param request DeleteGlobalOrganizationOperationRequest message or plain object + * @returns Promise + */ + public delete(request: google.cloud.compute.v1.IDeleteGlobalOrganizationOperationRequest): Promise; + + /** + * Calls Get. + * @param request GetGlobalOrganizationOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public get(request: google.cloud.compute.v1.IGetGlobalOrganizationOperationRequest, callback: google.cloud.compute.v1.GlobalOrganizationOperations.GetCallback): void; + + /** + * Calls Get. + * @param request GetGlobalOrganizationOperationRequest message or plain object + * @returns Promise + */ + public get(request: google.cloud.compute.v1.IGetGlobalOrganizationOperationRequest): Promise; + + /** + * Calls List. + * @param request ListGlobalOrganizationOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and OperationList + */ + public list(request: google.cloud.compute.v1.IListGlobalOrganizationOperationsRequest, callback: google.cloud.compute.v1.GlobalOrganizationOperations.ListCallback): void; + + /** + * Calls List. + * @param request ListGlobalOrganizationOperationsRequest message or plain object + * @returns Promise + */ + public list(request: google.cloud.compute.v1.IListGlobalOrganizationOperationsRequest): Promise; + } + + namespace GlobalOrganizationOperations { + + /** + * Callback as used by {@link google.cloud.compute.v1.GlobalOrganizationOperations#delete_}. + * @param error Error, if any + * @param [response] DeleteGlobalOrganizationOperationResponse + */ + type DeleteCallback = (error: (Error|null), response?: google.cloud.compute.v1.DeleteGlobalOrganizationOperationResponse) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1.GlobalOrganizationOperations#get}. + * @param error Error, if any + * @param [response] Operation + */ + type GetCallback = (error: (Error|null), response?: google.cloud.compute.v1.Operation) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1.GlobalOrganizationOperations#list}. + * @param error Error, if any + * @param [response] OperationList + */ + type ListCallback = (error: (Error|null), response?: google.cloud.compute.v1.OperationList) => void; + } + } + } + } + + /** Namespace api. */ + namespace api { + + /** Properties of a Http. */ + interface IHttp { + + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); + + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); + } + + /** Represents a Http. */ + class Http implements IHttp { + + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); + + /** Http rules. */ + public rules: google.api.IHttpRule[]; + + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; + + /** + * Creates a new Http instance using the specified properties. + * @param [properties] Properties to set + * @returns Http instance + */ + public static create(properties?: google.api.IHttp): google.api.Http; + + /** + * Encodes the specified Http message. Does not implicitly {@link google.api.Http.verify|verify} messages. + * @param message Http message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Http message, length delimited. Does not implicitly {@link google.api.Http.verify|verify} messages. + * @param message Http message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Http message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Http + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Http; + + /** + * Decodes a Http message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Http + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Http; + + /** + * Verifies a Http message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a HttpRule. */ + interface IHttpRule { + + /** HttpRule selector */ + selector?: (string|null); + + /** HttpRule get */ + get?: (string|null); + + /** HttpRule put */ + put?: (string|null); + + /** HttpRule post */ + post?: (string|null); + + /** HttpRule delete */ + "delete"?: (string|null); + + /** HttpRule patch */ + patch?: (string|null); + + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body */ + body?: (string|null); + + /** HttpRule responseBody */ + responseBody?: (string|null); + + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); + } + + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { + + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); + + /** HttpRule selector. */ + public selector: string; + + /** HttpRule get. */ + public get?: (string|null); + + /** HttpRule put. */ + public put?: (string|null); + + /** HttpRule post. */ + public post?: (string|null); + + /** HttpRule delete. */ + public delete?: (string|null); + + /** HttpRule patch. */ + public patch?: (string|null); + + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body. */ + public body: string; + + /** HttpRule responseBody. */ + public responseBody: string; + + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; + + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + + /** + * Creates a new HttpRule instance using the specified properties. + * @param [properties] Properties to set + * @returns HttpRule instance + */ + public static create(properties?: google.api.IHttpRule): google.api.HttpRule; + + /** + * Encodes the specified HttpRule message. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. + * @param message HttpRule message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified HttpRule message, length delimited. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. + * @param message HttpRule message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a HttpRule message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns HttpRule + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.HttpRule; + + /** + * Decodes a HttpRule message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns HttpRule + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.HttpRule; + + /** + * Verifies a HttpRule message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { + + /** CustomHttpPattern kind */ + kind?: (string|null); + + /** CustomHttpPattern path */ + path?: (string|null); + } + + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { + + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); + + /** CustomHttpPattern kind. */ + public kind: string; + + /** CustomHttpPattern path. */ + public path: string; + + /** + * Creates a new CustomHttpPattern instance using the specified properties. + * @param [properties] Properties to set + * @returns CustomHttpPattern instance + */ + public static create(properties?: google.api.ICustomHttpPattern): google.api.CustomHttpPattern; + + /** + * Encodes the specified CustomHttpPattern message. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. + * @param message CustomHttpPattern message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CustomHttpPattern message, length delimited. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. + * @param message CustomHttpPattern message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CustomHttpPattern message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CustomHttpPattern + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.CustomHttpPattern; + + /** + * Decodes a CustomHttpPattern message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CustomHttpPattern + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.CustomHttpPattern; + + /** + * Verifies a CustomHttpPattern message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Namespace protobuf. */ + namespace protobuf { + + /** Properties of a FileDescriptorSet. */ + interface IFileDescriptorSet { + + /** FileDescriptorSet file */ + file?: (google.protobuf.IFileDescriptorProto[]|null); + } + + /** Represents a FileDescriptorSet. */ + class FileDescriptorSet implements IFileDescriptorSet { + + /** + * Constructs a new FileDescriptorSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorSet); + + /** FileDescriptorSet file. */ + public file: google.protobuf.IFileDescriptorProto[]; + + /** + * Creates a new FileDescriptorSet instance using the specified properties. + * @param [properties] Properties to set + * @returns FileDescriptorSet instance + */ + public static create(properties?: google.protobuf.IFileDescriptorSet): google.protobuf.FileDescriptorSet; + + /** + * Encodes the specified FileDescriptorSet message. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. + * @param message FileDescriptorSet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FileDescriptorSet message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. + * @param message FileDescriptorSet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FileDescriptorSet message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FileDescriptorSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorSet; + + /** + * Decodes a FileDescriptorSet message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FileDescriptorSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorSet; + + /** + * Verifies a FileDescriptorSet message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; + + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @param message FileDescriptorSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a FileDescriptorProto. */ + interface IFileDescriptorProto { + + /** FileDescriptorProto name */ + name?: (string|null); + + /** FileDescriptorProto package */ + "package"?: (string|null); + + /** FileDescriptorProto dependency */ + dependency?: (string[]|null); + + /** FileDescriptorProto publicDependency */ + publicDependency?: (number[]|null); + + /** FileDescriptorProto weakDependency */ + weakDependency?: (number[]|null); + + /** FileDescriptorProto messageType */ + messageType?: (google.protobuf.IDescriptorProto[]|null); + + /** FileDescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** FileDescriptorProto service */ + service?: (google.protobuf.IServiceDescriptorProto[]|null); + + /** FileDescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** FileDescriptorProto options */ + options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo */ + sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax */ + syntax?: (string|null); + } + + /** Represents a FileDescriptorProto. */ + class FileDescriptorProto implements IFileDescriptorProto { + + /** + * Constructs a new FileDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorProto); + + /** FileDescriptorProto name. */ + public name: string; + + /** FileDescriptorProto package. */ + public package: string; + + /** FileDescriptorProto dependency. */ + public dependency: string[]; + + /** FileDescriptorProto publicDependency. */ + public publicDependency: number[]; + + /** FileDescriptorProto weakDependency. */ + public weakDependency: number[]; + + /** FileDescriptorProto messageType. */ + public messageType: google.protobuf.IDescriptorProto[]; + + /** FileDescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** FileDescriptorProto service. */ + public service: google.protobuf.IServiceDescriptorProto[]; + + /** FileDescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** FileDescriptorProto options. */ + public options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo. */ + public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax. */ + public syntax: string; + + /** + * Creates a new FileDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns FileDescriptorProto instance + */ + public static create(properties?: google.protobuf.IFileDescriptorProto): google.protobuf.FileDescriptorProto; + + /** + * Encodes the specified FileDescriptorProto message. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. + * @param message FileDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FileDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. + * @param message FileDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FileDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FileDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorProto; + + /** + * Decodes a FileDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FileDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorProto; + + /** + * Verifies a FileDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; + + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @param message FileDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a DescriptorProto. */ + interface IDescriptorProto { + + /** DescriptorProto name */ + name?: (string|null); + + /** DescriptorProto field */ + field?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto nestedType */ + nestedType?: (google.protobuf.IDescriptorProto[]|null); + + /** DescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** DescriptorProto extensionRange */ + extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); + + /** DescriptorProto oneofDecl */ + oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); + + /** DescriptorProto options */ + options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange */ + reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); + + /** DescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents a DescriptorProto. */ + class DescriptorProto implements IDescriptorProto { + + /** + * Constructs a new DescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDescriptorProto); + + /** DescriptorProto name. */ + public name: string; + + /** DescriptorProto field. */ + public field: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto nestedType. */ + public nestedType: google.protobuf.IDescriptorProto[]; + + /** DescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** DescriptorProto extensionRange. */ + public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; + + /** DescriptorProto oneofDecl. */ + public oneofDecl: google.protobuf.IOneofDescriptorProto[]; + + /** DescriptorProto options. */ + public options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange. */ + public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; + + /** DescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates a new DescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns DescriptorProto instance + */ + public static create(properties?: google.protobuf.IDescriptorProto): google.protobuf.DescriptorProto; + + /** + * Encodes the specified DescriptorProto message. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. + * @param message DescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. + * @param message DescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto; + + /** + * Decodes a DescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto; + + /** + * Verifies a DescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; + + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @param message DescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace DescriptorProto { + + /** Properties of an ExtensionRange. */ + interface IExtensionRange { + + /** ExtensionRange start */ + start?: (number|null); + + /** ExtensionRange end */ + end?: (number|null); + + /** ExtensionRange options */ + options?: (google.protobuf.IExtensionRangeOptions|null); + } + + /** Represents an ExtensionRange. */ + class ExtensionRange implements IExtensionRange { + + /** + * Constructs a new ExtensionRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); + + /** ExtensionRange start. */ + public start: number; + + /** ExtensionRange end. */ + public end: number; + + /** ExtensionRange options. */ + public options?: (google.protobuf.IExtensionRangeOptions|null); + + /** + * Creates a new ExtensionRange instance using the specified properties. + * @param [properties] Properties to set + * @returns ExtensionRange instance + */ + public static create(properties?: google.protobuf.DescriptorProto.IExtensionRange): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Encodes the specified ExtensionRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. + * @param message ExtensionRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExtensionRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. + * @param message ExtensionRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExtensionRange message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExtensionRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Decodes an ExtensionRange message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExtensionRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Verifies an ExtensionRange message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @param message ExtensionRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a ReservedRange. */ + interface IReservedRange { + + /** ReservedRange start */ + start?: (number|null); + + /** ReservedRange end */ + end?: (number|null); + } + + /** Represents a ReservedRange. */ + class ReservedRange implements IReservedRange { + + /** + * Constructs a new ReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); + + /** ReservedRange start. */ + public start: number; + + /** ReservedRange end. */ + public end: number; + + /** + * Creates a new ReservedRange instance using the specified properties. + * @param [properties] Properties to set + * @returns ReservedRange instance + */ + public static create(properties?: google.protobuf.DescriptorProto.IReservedRange): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Encodes the specified ReservedRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. + * @param message ReservedRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReservedRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. + * @param message ReservedRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReservedRange message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Decodes a ReservedRange message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Verifies a ReservedRange message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @param message ReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Properties of an ExtensionRangeOptions. */ + interface IExtensionRangeOptions { + + /** ExtensionRangeOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an ExtensionRangeOptions. */ + class ExtensionRangeOptions implements IExtensionRangeOptions { + + /** + * Constructs a new ExtensionRangeOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IExtensionRangeOptions); + + /** ExtensionRangeOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new ExtensionRangeOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns ExtensionRangeOptions instance + */ + public static create(properties?: google.protobuf.IExtensionRangeOptions): google.protobuf.ExtensionRangeOptions; + + /** + * Encodes the specified ExtensionRangeOptions message. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages. + * @param message ExtensionRangeOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IExtensionRangeOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExtensionRangeOptions message, length delimited. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages. + * @param message ExtensionRangeOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IExtensionRangeOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExtensionRangeOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExtensionRangeOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ExtensionRangeOptions; + + /** + * Decodes an ExtensionRangeOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExtensionRangeOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ExtensionRangeOptions; + + /** + * Verifies an ExtensionRangeOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRangeOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @param message ExtensionRangeOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a FieldDescriptorProto. */ + interface IFieldDescriptorProto { + + /** FieldDescriptorProto name */ + name?: (string|null); + + /** FieldDescriptorProto number */ + number?: (number|null); + + /** FieldDescriptorProto label */ + label?: (google.protobuf.FieldDescriptorProto.Label|null); + + /** FieldDescriptorProto type */ + type?: (google.protobuf.FieldDescriptorProto.Type|null); + + /** FieldDescriptorProto typeName */ + typeName?: (string|null); + + /** FieldDescriptorProto extendee */ + extendee?: (string|null); + + /** FieldDescriptorProto defaultValue */ + defaultValue?: (string|null); + + /** FieldDescriptorProto oneofIndex */ + oneofIndex?: (number|null); + + /** FieldDescriptorProto jsonName */ + jsonName?: (string|null); + + /** FieldDescriptorProto options */ + options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional */ + proto3Optional?: (boolean|null); + } + + /** Represents a FieldDescriptorProto. */ + class FieldDescriptorProto implements IFieldDescriptorProto { + + /** + * Constructs a new FieldDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldDescriptorProto); + + /** FieldDescriptorProto name. */ + public name: string; + + /** FieldDescriptorProto number. */ + public number: number; + + /** FieldDescriptorProto label. */ + public label: google.protobuf.FieldDescriptorProto.Label; + + /** FieldDescriptorProto type. */ + public type: google.protobuf.FieldDescriptorProto.Type; + + /** FieldDescriptorProto typeName. */ + public typeName: string; + + /** FieldDescriptorProto extendee. */ + public extendee: string; + + /** FieldDescriptorProto defaultValue. */ + public defaultValue: string; + + /** FieldDescriptorProto oneofIndex. */ + public oneofIndex: number; + + /** FieldDescriptorProto jsonName. */ + public jsonName: string; + + /** FieldDescriptorProto options. */ + public options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional. */ + public proto3Optional: boolean; + + /** + * Creates a new FieldDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns FieldDescriptorProto instance + */ + public static create(properties?: google.protobuf.IFieldDescriptorProto): google.protobuf.FieldDescriptorProto; + + /** + * Encodes the specified FieldDescriptorProto message. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. + * @param message FieldDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FieldDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. + * @param message FieldDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FieldDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FieldDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldDescriptorProto; + + /** + * Decodes a FieldDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FieldDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldDescriptorProto; + + /** + * Verifies a FieldDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @param message FieldDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace FieldDescriptorProto { + + /** Type enum. */ + enum Type { + TYPE_DOUBLE = 1, + TYPE_FLOAT = 2, + TYPE_INT64 = 3, + TYPE_UINT64 = 4, + TYPE_INT32 = 5, + TYPE_FIXED64 = 6, + TYPE_FIXED32 = 7, + TYPE_BOOL = 8, + TYPE_STRING = 9, + TYPE_GROUP = 10, + TYPE_MESSAGE = 11, + TYPE_BYTES = 12, + TYPE_UINT32 = 13, + TYPE_ENUM = 14, + TYPE_SFIXED32 = 15, + TYPE_SFIXED64 = 16, + TYPE_SINT32 = 17, + TYPE_SINT64 = 18 + } + + /** Label enum. */ + enum Label { + LABEL_OPTIONAL = 1, + LABEL_REQUIRED = 2, + LABEL_REPEATED = 3 + } + } + + /** Properties of an OneofDescriptorProto. */ + interface IOneofDescriptorProto { + + /** OneofDescriptorProto name */ + name?: (string|null); + + /** OneofDescriptorProto options */ + options?: (google.protobuf.IOneofOptions|null); + } + + /** Represents an OneofDescriptorProto. */ + class OneofDescriptorProto implements IOneofDescriptorProto { + + /** + * Constructs a new OneofDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofDescriptorProto); + + /** OneofDescriptorProto name. */ + public name: string; + + /** OneofDescriptorProto options. */ + public options?: (google.protobuf.IOneofOptions|null); + + /** + * Creates a new OneofDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns OneofDescriptorProto instance + */ + public static create(properties?: google.protobuf.IOneofDescriptorProto): google.protobuf.OneofDescriptorProto; + + /** + * Encodes the specified OneofDescriptorProto message. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. + * @param message OneofDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified OneofDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. + * @param message OneofDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an OneofDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns OneofDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofDescriptorProto; + + /** + * Decodes an OneofDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns OneofDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofDescriptorProto; + + /** + * Verifies an OneofDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; + + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @param message OneofDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of an EnumDescriptorProto. */ + interface IEnumDescriptorProto { + + /** EnumDescriptorProto name */ + name?: (string|null); + + /** EnumDescriptorProto value */ + value?: (google.protobuf.IEnumValueDescriptorProto[]|null); + + /** EnumDescriptorProto options */ + options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange */ + reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); + + /** EnumDescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents an EnumDescriptorProto. */ + class EnumDescriptorProto implements IEnumDescriptorProto { + + /** + * Constructs a new EnumDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumDescriptorProto); + + /** EnumDescriptorProto name. */ + public name: string; + + /** EnumDescriptorProto value. */ + public value: google.protobuf.IEnumValueDescriptorProto[]; + + /** EnumDescriptorProto options. */ + public options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange. */ + public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; + + /** EnumDescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates a new EnumDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumDescriptorProto instance + */ + public static create(properties?: google.protobuf.IEnumDescriptorProto): google.protobuf.EnumDescriptorProto; + + /** + * Encodes the specified EnumDescriptorProto message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. + * @param message EnumDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. + * @param message EnumDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto; + + /** + * Decodes an EnumDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto; + + /** + * Verifies an EnumDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; + + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @param message EnumDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace EnumDescriptorProto { + + /** Properties of an EnumReservedRange. */ + interface IEnumReservedRange { + + /** EnumReservedRange start */ + start?: (number|null); + + /** EnumReservedRange end */ + end?: (number|null); + } + + /** Represents an EnumReservedRange. */ + class EnumReservedRange implements IEnumReservedRange { + + /** + * Constructs a new EnumReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); + + /** EnumReservedRange start. */ + public start: number; + + /** EnumReservedRange end. */ + public end: number; + + /** + * Creates a new EnumReservedRange instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumReservedRange instance + */ + public static create(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Encodes the specified EnumReservedRange message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages. + * @param message EnumReservedRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.EnumDescriptorProto.IEnumReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumReservedRange message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages. + * @param message EnumReservedRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.EnumDescriptorProto.IEnumReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumReservedRange message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Decodes an EnumReservedRange message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Verifies an EnumReservedRange message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @param message EnumReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Properties of an EnumValueDescriptorProto. */ + interface IEnumValueDescriptorProto { + + /** EnumValueDescriptorProto name */ + name?: (string|null); + + /** EnumValueDescriptorProto number */ + number?: (number|null); + + /** EnumValueDescriptorProto options */ + options?: (google.protobuf.IEnumValueOptions|null); + } + + /** Represents an EnumValueDescriptorProto. */ + class EnumValueDescriptorProto implements IEnumValueDescriptorProto { + + /** + * Constructs a new EnumValueDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueDescriptorProto); + + /** EnumValueDescriptorProto name. */ + public name: string; + + /** EnumValueDescriptorProto number. */ + public number: number; + + /** EnumValueDescriptorProto options. */ + public options?: (google.protobuf.IEnumValueOptions|null); + + /** + * Creates a new EnumValueDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumValueDescriptorProto instance + */ + public static create(properties?: google.protobuf.IEnumValueDescriptorProto): google.protobuf.EnumValueDescriptorProto; + + /** + * Encodes the specified EnumValueDescriptorProto message. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. + * @param message EnumValueDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumValueDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. + * @param message EnumValueDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumValueDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumValueDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueDescriptorProto; + + /** + * Decodes an EnumValueDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumValueDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueDescriptorProto; + + /** + * Verifies an EnumValueDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; + + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @param message EnumValueDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a ServiceDescriptorProto. */ + interface IServiceDescriptorProto { + + /** ServiceDescriptorProto name */ + name?: (string|null); + + /** ServiceDescriptorProto method */ + method?: (google.protobuf.IMethodDescriptorProto[]|null); + + /** ServiceDescriptorProto options */ + options?: (google.protobuf.IServiceOptions|null); + } + + /** Represents a ServiceDescriptorProto. */ + class ServiceDescriptorProto implements IServiceDescriptorProto { + + /** + * Constructs a new ServiceDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceDescriptorProto); + + /** ServiceDescriptorProto name. */ + public name: string; + + /** ServiceDescriptorProto method. */ + public method: google.protobuf.IMethodDescriptorProto[]; + + /** ServiceDescriptorProto options. */ + public options?: (google.protobuf.IServiceOptions|null); + + /** + * Creates a new ServiceDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns ServiceDescriptorProto instance + */ + public static create(properties?: google.protobuf.IServiceDescriptorProto): google.protobuf.ServiceDescriptorProto; + + /** + * Encodes the specified ServiceDescriptorProto message. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. + * @param message ServiceDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ServiceDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. + * @param message ServiceDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ServiceDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ServiceDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceDescriptorProto; + + /** + * Decodes a ServiceDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ServiceDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceDescriptorProto; + + /** + * Verifies a ServiceDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @param message ServiceDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a MethodDescriptorProto. */ + interface IMethodDescriptorProto { + + /** MethodDescriptorProto name */ + name?: (string|null); + + /** MethodDescriptorProto inputType */ + inputType?: (string|null); + + /** MethodDescriptorProto outputType */ + outputType?: (string|null); + + /** MethodDescriptorProto options */ + options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming */ + clientStreaming?: (boolean|null); + + /** MethodDescriptorProto serverStreaming */ + serverStreaming?: (boolean|null); + } + + /** Represents a MethodDescriptorProto. */ + class MethodDescriptorProto implements IMethodDescriptorProto { + + /** + * Constructs a new MethodDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodDescriptorProto); + + /** MethodDescriptorProto name. */ + public name: string; + + /** MethodDescriptorProto inputType. */ + public inputType: string; + + /** MethodDescriptorProto outputType. */ + public outputType: string; + + /** MethodDescriptorProto options. */ + public options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming. */ + public clientStreaming: boolean; + + /** MethodDescriptorProto serverStreaming. */ + public serverStreaming: boolean; + + /** + * Creates a new MethodDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns MethodDescriptorProto instance + */ + public static create(properties?: google.protobuf.IMethodDescriptorProto): google.protobuf.MethodDescriptorProto; + + /** + * Encodes the specified MethodDescriptorProto message. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. + * @param message MethodDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MethodDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. + * @param message MethodDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MethodDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MethodDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodDescriptorProto; + + /** + * Decodes a MethodDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MethodDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodDescriptorProto; + + /** + * Verifies a MethodDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @param message MethodDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a FileOptions. */ + interface IFileOptions { + + /** FileOptions javaPackage */ + javaPackage?: (string|null); + + /** FileOptions javaOuterClassname */ + javaOuterClassname?: (string|null); + + /** FileOptions javaMultipleFiles */ + javaMultipleFiles?: (boolean|null); + + /** FileOptions javaGenerateEqualsAndHash */ + javaGenerateEqualsAndHash?: (boolean|null); + + /** FileOptions javaStringCheckUtf8 */ + javaStringCheckUtf8?: (boolean|null); + + /** FileOptions optimizeFor */ + optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); + + /** FileOptions goPackage */ + goPackage?: (string|null); + + /** FileOptions ccGenericServices */ + ccGenericServices?: (boolean|null); + + /** FileOptions javaGenericServices */ + javaGenericServices?: (boolean|null); + + /** FileOptions pyGenericServices */ + pyGenericServices?: (boolean|null); + + /** FileOptions phpGenericServices */ + phpGenericServices?: (boolean|null); + + /** FileOptions deprecated */ + deprecated?: (boolean|null); + + /** FileOptions ccEnableArenas */ + ccEnableArenas?: (boolean|null); + + /** FileOptions objcClassPrefix */ + objcClassPrefix?: (string|null); + + /** FileOptions csharpNamespace */ + csharpNamespace?: (string|null); + + /** FileOptions swiftPrefix */ + swiftPrefix?: (string|null); + + /** FileOptions phpClassPrefix */ + phpClassPrefix?: (string|null); + + /** FileOptions phpNamespace */ + phpNamespace?: (string|null); + + /** FileOptions phpMetadataNamespace */ + phpMetadataNamespace?: (string|null); + + /** FileOptions rubyPackage */ + rubyPackage?: (string|null); + + /** FileOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents a FileOptions. */ + class FileOptions implements IFileOptions { + + /** + * Constructs a new FileOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileOptions); + + /** FileOptions javaPackage. */ + public javaPackage: string; + + /** FileOptions javaOuterClassname. */ + public javaOuterClassname: string; + + /** FileOptions javaMultipleFiles. */ + public javaMultipleFiles: boolean; + + /** FileOptions javaGenerateEqualsAndHash. */ + public javaGenerateEqualsAndHash: boolean; + + /** FileOptions javaStringCheckUtf8. */ + public javaStringCheckUtf8: boolean; + + /** FileOptions optimizeFor. */ + public optimizeFor: google.protobuf.FileOptions.OptimizeMode; + + /** FileOptions goPackage. */ + public goPackage: string; + + /** FileOptions ccGenericServices. */ + public ccGenericServices: boolean; + + /** FileOptions javaGenericServices. */ + public javaGenericServices: boolean; + + /** FileOptions pyGenericServices. */ + public pyGenericServices: boolean; + + /** FileOptions phpGenericServices. */ + public phpGenericServices: boolean; + + /** FileOptions deprecated. */ + public deprecated: boolean; + + /** FileOptions ccEnableArenas. */ + public ccEnableArenas: boolean; + + /** FileOptions objcClassPrefix. */ + public objcClassPrefix: string; + + /** FileOptions csharpNamespace. */ + public csharpNamespace: string; + + /** FileOptions swiftPrefix. */ + public swiftPrefix: string; + + /** FileOptions phpClassPrefix. */ + public phpClassPrefix: string; + + /** FileOptions phpNamespace. */ + public phpNamespace: string; + + /** FileOptions phpMetadataNamespace. */ + public phpMetadataNamespace: string; + + /** FileOptions rubyPackage. */ + public rubyPackage: string; + + /** FileOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new FileOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns FileOptions instance + */ + public static create(properties?: google.protobuf.IFileOptions): google.protobuf.FileOptions; + + /** + * Encodes the specified FileOptions message. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. + * @param message FileOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FileOptions message, length delimited. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. + * @param message FileOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FileOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FileOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileOptions; + + /** + * Decodes a FileOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FileOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileOptions; + + /** + * Verifies a FileOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; + + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @param message FileOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace FileOptions { + + /** OptimizeMode enum. */ + enum OptimizeMode { + SPEED = 1, + CODE_SIZE = 2, + LITE_RUNTIME = 3 + } + } + + /** Properties of a MessageOptions. */ + interface IMessageOptions { + + /** MessageOptions messageSetWireFormat */ + messageSetWireFormat?: (boolean|null); + + /** MessageOptions noStandardDescriptorAccessor */ + noStandardDescriptorAccessor?: (boolean|null); + + /** MessageOptions deprecated */ + deprecated?: (boolean|null); + + /** MessageOptions mapEntry */ + mapEntry?: (boolean|null); + + /** MessageOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents a MessageOptions. */ + class MessageOptions implements IMessageOptions { + + /** + * Constructs a new MessageOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMessageOptions); + + /** MessageOptions messageSetWireFormat. */ + public messageSetWireFormat: boolean; + + /** MessageOptions noStandardDescriptorAccessor. */ + public noStandardDescriptorAccessor: boolean; + + /** MessageOptions deprecated. */ + public deprecated: boolean; + + /** MessageOptions mapEntry. */ + public mapEntry: boolean; + + /** MessageOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new MessageOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns MessageOptions instance + */ + public static create(properties?: google.protobuf.IMessageOptions): google.protobuf.MessageOptions; + + /** + * Encodes the specified MessageOptions message. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. + * @param message MessageOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MessageOptions message, length delimited. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. + * @param message MessageOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MessageOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MessageOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MessageOptions; + + /** + * Decodes a MessageOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MessageOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MessageOptions; + + /** + * Verifies a MessageOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MessageOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; + + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @param message MessageOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MessageOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a FieldOptions. */ + interface IFieldOptions { + + /** FieldOptions ctype */ + ctype?: (google.protobuf.FieldOptions.CType|null); + + /** FieldOptions packed */ + packed?: (boolean|null); + + /** FieldOptions jstype */ + jstype?: (google.protobuf.FieldOptions.JSType|null); + + /** FieldOptions lazy */ + lazy?: (boolean|null); + + /** FieldOptions deprecated */ + deprecated?: (boolean|null); + + /** FieldOptions weak */ + weak?: (boolean|null); + + /** FieldOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents a FieldOptions. */ + class FieldOptions implements IFieldOptions { + + /** + * Constructs a new FieldOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldOptions); + + /** FieldOptions ctype. */ + public ctype: google.protobuf.FieldOptions.CType; + + /** FieldOptions packed. */ + public packed: boolean; + + /** FieldOptions jstype. */ + public jstype: google.protobuf.FieldOptions.JSType; + + /** FieldOptions lazy. */ + public lazy: boolean; + + /** FieldOptions deprecated. */ + public deprecated: boolean; + + /** FieldOptions weak. */ + public weak: boolean; + + /** FieldOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new FieldOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns FieldOptions instance + */ + public static create(properties?: google.protobuf.IFieldOptions): google.protobuf.FieldOptions; + + /** + * Encodes the specified FieldOptions message. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. + * @param message FieldOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FieldOptions message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. + * @param message FieldOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FieldOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FieldOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions; + + /** + * Decodes a FieldOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FieldOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions; + + /** + * Verifies a FieldOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; + + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @param message FieldOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace FieldOptions { + + /** CType enum. */ + enum CType { + STRING = 0, + CORD = 1, + STRING_PIECE = 2 + } + + /** JSType enum. */ + enum JSType { + JS_NORMAL = 0, + JS_STRING = 1, + JS_NUMBER = 2 + } + } + + /** Properties of an OneofOptions. */ + interface IOneofOptions { + + /** OneofOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an OneofOptions. */ + class OneofOptions implements IOneofOptions { + + /** + * Constructs a new OneofOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofOptions); + + /** OneofOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new OneofOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns OneofOptions instance + */ + public static create(properties?: google.protobuf.IOneofOptions): google.protobuf.OneofOptions; + + /** + * Encodes the specified OneofOptions message. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. + * @param message OneofOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified OneofOptions message, length delimited. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. + * @param message OneofOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an OneofOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns OneofOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofOptions; + + /** + * Decodes an OneofOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns OneofOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofOptions; + + /** + * Verifies an OneofOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @param message OneofOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of an EnumOptions. */ + interface IEnumOptions { + + /** EnumOptions allowAlias */ + allowAlias?: (boolean|null); + + /** EnumOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumOptions. */ + class EnumOptions implements IEnumOptions { + + /** + * Constructs a new EnumOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumOptions); + + /** EnumOptions allowAlias. */ + public allowAlias: boolean; + + /** EnumOptions deprecated. */ + public deprecated: boolean; + + /** EnumOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new EnumOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumOptions instance + */ + public static create(properties?: google.protobuf.IEnumOptions): google.protobuf.EnumOptions; + + /** + * Encodes the specified EnumOptions message. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. + * @param message EnumOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. + * @param message EnumOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumOptions; + + /** + * Decodes an EnumOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumOptions; + + /** + * Verifies an EnumOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @param message EnumOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of an EnumValueOptions. */ + interface IEnumValueOptions { + + /** EnumValueOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumValueOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumValueOptions. */ + class EnumValueOptions implements IEnumValueOptions { + + /** + * Constructs a new EnumValueOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueOptions); + + /** EnumValueOptions deprecated. */ + public deprecated: boolean; + + /** EnumValueOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new EnumValueOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumValueOptions instance + */ + public static create(properties?: google.protobuf.IEnumValueOptions): google.protobuf.EnumValueOptions; + + /** + * Encodes the specified EnumValueOptions message. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. + * @param message EnumValueOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumValueOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. + * @param message EnumValueOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumValueOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumValueOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueOptions; + + /** + * Decodes an EnumValueOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumValueOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueOptions; + + /** + * Verifies an EnumValueOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; + + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @param message EnumValueOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a ServiceOptions. */ + interface IServiceOptions { + + /** ServiceOptions deprecated */ + deprecated?: (boolean|null); + + /** ServiceOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents a ServiceOptions. */ + class ServiceOptions implements IServiceOptions { + + /** + * Constructs a new ServiceOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceOptions); + + /** ServiceOptions deprecated. */ + public deprecated: boolean; + + /** ServiceOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new ServiceOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns ServiceOptions instance + */ + public static create(properties?: google.protobuf.IServiceOptions): google.protobuf.ServiceOptions; + + /** + * Encodes the specified ServiceOptions message. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. + * @param message ServiceOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ServiceOptions message, length delimited. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. + * @param message ServiceOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ServiceOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ServiceOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceOptions; + + /** + * Decodes a ServiceOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ServiceOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceOptions; + + /** + * Verifies a ServiceOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @param message ServiceOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a MethodOptions. */ + interface IMethodOptions { + + /** MethodOptions deprecated */ + deprecated?: (boolean|null); + + /** MethodOptions idempotencyLevel */ + idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); + + /** MethodOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MethodOptions .google.api.http */ + ".google.api.http"?: (google.api.IHttpRule|null); + } + + /** Represents a MethodOptions. */ + class MethodOptions implements IMethodOptions { + + /** + * Constructs a new MethodOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodOptions); + + /** MethodOptions deprecated. */ + public deprecated: boolean; + + /** MethodOptions idempotencyLevel. */ + public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; + + /** MethodOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new MethodOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns MethodOptions instance + */ + public static create(properties?: google.protobuf.IMethodOptions): google.protobuf.MethodOptions; + + /** + * Encodes the specified MethodOptions message. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. + * @param message MethodOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MethodOptions message, length delimited. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. + * @param message MethodOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MethodOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MethodOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodOptions; + + /** + * Decodes a MethodOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MethodOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodOptions; + + /** + * Verifies a MethodOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; + + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @param message MethodOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace MethodOptions { + + /** IdempotencyLevel enum. */ + enum IdempotencyLevel { + IDEMPOTENCY_UNKNOWN = 0, + NO_SIDE_EFFECTS = 1, + IDEMPOTENT = 2 + } + } + + /** Properties of an UninterpretedOption. */ + interface IUninterpretedOption { + + /** UninterpretedOption name */ + name?: (google.protobuf.UninterpretedOption.INamePart[]|null); + + /** UninterpretedOption identifierValue */ + identifierValue?: (string|null); + + /** UninterpretedOption positiveIntValue */ + positiveIntValue?: (number|Long|null); + + /** UninterpretedOption negativeIntValue */ + negativeIntValue?: (number|Long|null); + + /** UninterpretedOption doubleValue */ + doubleValue?: (number|null); + + /** UninterpretedOption stringValue */ + stringValue?: (Uint8Array|null); + + /** UninterpretedOption aggregateValue */ + aggregateValue?: (string|null); + } + + /** Represents an UninterpretedOption. */ + class UninterpretedOption implements IUninterpretedOption { + + /** + * Constructs a new UninterpretedOption. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUninterpretedOption); + + /** UninterpretedOption name. */ + public name: google.protobuf.UninterpretedOption.INamePart[]; + + /** UninterpretedOption identifierValue. */ + public identifierValue: string; + + /** UninterpretedOption positiveIntValue. */ + public positiveIntValue: (number|Long); + + /** UninterpretedOption negativeIntValue. */ + public negativeIntValue: (number|Long); + + /** UninterpretedOption doubleValue. */ + public doubleValue: number; + + /** UninterpretedOption stringValue. */ + public stringValue: Uint8Array; + + /** UninterpretedOption aggregateValue. */ + public aggregateValue: string; + + /** + * Creates a new UninterpretedOption instance using the specified properties. + * @param [properties] Properties to set + * @returns UninterpretedOption instance + */ + public static create(properties?: google.protobuf.IUninterpretedOption): google.protobuf.UninterpretedOption; + + /** + * Encodes the specified UninterpretedOption message. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. + * @param message UninterpretedOption message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UninterpretedOption message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. + * @param message UninterpretedOption message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UninterpretedOption message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UninterpretedOption + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption; + + /** + * Decodes an UninterpretedOption message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UninterpretedOption + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption; + + /** + * Verifies an UninterpretedOption message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UninterpretedOption + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @param message UninterpretedOption + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UninterpretedOption to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace UninterpretedOption { + + /** Properties of a NamePart. */ + interface INamePart { + + /** NamePart namePart */ + namePart: string; + + /** NamePart isExtension */ + isExtension: boolean; + } + + /** Represents a NamePart. */ + class NamePart implements INamePart { + + /** + * Constructs a new NamePart. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.UninterpretedOption.INamePart); + + /** NamePart namePart. */ + public namePart: string; + + /** NamePart isExtension. */ + public isExtension: boolean; + + /** + * Creates a new NamePart instance using the specified properties. + * @param [properties] Properties to set + * @returns NamePart instance + */ + public static create(properties?: google.protobuf.UninterpretedOption.INamePart): google.protobuf.UninterpretedOption.NamePart; + + /** + * Encodes the specified NamePart message. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. + * @param message NamePart message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified NamePart message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. + * @param message NamePart message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a NamePart message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns NamePart + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption.NamePart; + + /** + * Decodes a NamePart message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns NamePart + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption.NamePart; + + /** + * Verifies a NamePart message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamePart + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @param message NamePart + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamePart to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Properties of a SourceCodeInfo. */ + interface ISourceCodeInfo { + + /** SourceCodeInfo location */ + location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); + } + + /** Represents a SourceCodeInfo. */ + class SourceCodeInfo implements ISourceCodeInfo { + + /** + * Constructs a new SourceCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ISourceCodeInfo); + + /** SourceCodeInfo location. */ + public location: google.protobuf.SourceCodeInfo.ILocation[]; + + /** + * Creates a new SourceCodeInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns SourceCodeInfo instance + */ + public static create(properties?: google.protobuf.ISourceCodeInfo): google.protobuf.SourceCodeInfo; + + /** + * Encodes the specified SourceCodeInfo message. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. + * @param message SourceCodeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SourceCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. + * @param message SourceCodeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SourceCodeInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SourceCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo; + + /** + * Decodes a SourceCodeInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SourceCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo; + + /** + * Verifies a SourceCodeInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @param message SourceCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace SourceCodeInfo { + + /** Properties of a Location. */ + interface ILocation { + + /** Location path */ + path?: (number[]|null); + + /** Location span */ + span?: (number[]|null); + + /** Location leadingComments */ + leadingComments?: (string|null); + + /** Location trailingComments */ + trailingComments?: (string|null); + + /** Location leadingDetachedComments */ + leadingDetachedComments?: (string[]|null); + } + + /** Represents a Location. */ + class Location implements ILocation { + + /** + * Constructs a new Location. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); + + /** Location path. */ + public path: number[]; + + /** Location span. */ + public span: number[]; + + /** Location leadingComments. */ + public leadingComments: string; + + /** Location trailingComments. */ + public trailingComments: string; + + /** Location leadingDetachedComments. */ + public leadingDetachedComments: string[]; + + /** + * Creates a new Location instance using the specified properties. + * @param [properties] Properties to set + * @returns Location instance + */ + public static create(properties?: google.protobuf.SourceCodeInfo.ILocation): google.protobuf.SourceCodeInfo.Location; + + /** + * Encodes the specified Location message. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. + * @param message Location message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Location message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. + * @param message Location message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Location message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Location + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo.Location; + + /** + * Decodes a Location message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Location + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo.Location; + + /** + * Verifies a Location message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Location + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @param message Location + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Location to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Properties of a GeneratedCodeInfo. */ + interface IGeneratedCodeInfo { + + /** GeneratedCodeInfo annotation */ + annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); + } + + /** Represents a GeneratedCodeInfo. */ + class GeneratedCodeInfo implements IGeneratedCodeInfo { + + /** + * Constructs a new GeneratedCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IGeneratedCodeInfo); + + /** GeneratedCodeInfo annotation. */ + public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; + + /** + * Creates a new GeneratedCodeInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns GeneratedCodeInfo instance + */ + public static create(properties?: google.protobuf.IGeneratedCodeInfo): google.protobuf.GeneratedCodeInfo; + + /** + * Encodes the specified GeneratedCodeInfo message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. + * @param message GeneratedCodeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GeneratedCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. + * @param message GeneratedCodeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GeneratedCodeInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GeneratedCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo; + + /** + * Decodes a GeneratedCodeInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GeneratedCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo; + + /** + * Verifies a GeneratedCodeInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GeneratedCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; + + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @param message GeneratedCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace GeneratedCodeInfo { + + /** Properties of an Annotation. */ + interface IAnnotation { + + /** Annotation path */ + path?: (number[]|null); + + /** Annotation sourceFile */ + sourceFile?: (string|null); + + /** Annotation begin */ + begin?: (number|null); + + /** Annotation end */ + end?: (number|null); + } + + /** Represents an Annotation. */ + class Annotation implements IAnnotation { + + /** + * Constructs a new Annotation. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); + + /** Annotation path. */ + public path: number[]; + + /** Annotation sourceFile. */ + public sourceFile: string; + + /** Annotation begin. */ + public begin: number; + + /** Annotation end. */ + public end: number; + + /** + * Creates a new Annotation instance using the specified properties. + * @param [properties] Properties to set + * @returns Annotation instance + */ + public static create(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Encodes the specified Annotation message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. + * @param message Annotation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Annotation message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. + * @param message Annotation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Annotation message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Annotation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Decodes an Annotation message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Annotation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Verifies an Annotation message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Annotation + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @param message Annotation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Annotation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + } +} diff --git a/node_modules/google-gax/build/protos/compute_operations.js b/node_modules/google-gax/build/protos/compute_operations.js new file mode 100644 index 0000000..16083fb --- /dev/null +++ b/node_modules/google-gax/build/protos/compute_operations.js @@ -0,0 +1 @@ +(e=>{"function"==typeof define&&define.amd?define(["protobufjs/minimal"],e):"function"==typeof require&&"object"==typeof module&&module&&module.exports&&(module.exports=e(require("protobufjs/minimal")))})(function(r){var e,t,n,o,i,G,s=r.Reader,a=r.Writer,c=r.util,u=r.roots.compute_operations_protos||(r.roots.compute_operations_protos={});function p(e){if(this.warnings=[],e)for(var t=Object.keys(e),n=0;n>>3){case 297240295:r.clientOperationId=e.string();break;case 30525366:r.creationTimestamp=e.string();break;case 422937596:r.description=e.string();break;case 114938801:r.endTime=e.string();break;case 96784904:r.error=u.google.cloud.compute.v1.Error.decode(e,e.uint32());break;case 202521945:r.httpErrorMessage=e.string();break;case 312345196:r.httpErrorStatusCode=e.int32();break;case 3355:r.id=e.string();break;case 433722515:r.insertTime=e.string();break;case 3292052:r.kind=e.string();break;case 3373707:r.name=e.string();break;case 177650450:r.operationType=e.string();break;case 72663597:r.progress=e.int32();break;case 138946292:r.region=e.string();break;case 456214797:r.selfLink=e.string();break;case 37467274:r.startTime=e.string();break;case 181260274:r.status=e.int32();break;case 297428154:r.statusMessage=e.string();break;case 258165385:r.targetId=e.string();break;case 62671336:r.targetLink=e.string();break;case 3599307:r.user=e.string();break;case 498091095:r.warnings&&r.warnings.length||(r.warnings=[]),r.warnings.push(u.google.cloud.compute.v1.Warnings.decode(e,e.uint32()));break;case 3744684:r.zone=e.string();break;default:e.skipType(7&o)}}return r},p.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},p.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.clientOperationId&&e.hasOwnProperty("clientOperationId")&&!c.isString(e.clientOperationId))return"clientOperationId: string expected";if(null!=e.creationTimestamp&&e.hasOwnProperty("creationTimestamp")&&!c.isString(e.creationTimestamp))return"creationTimestamp: string expected";if(null!=e.description&&e.hasOwnProperty("description")&&!c.isString(e.description))return"description: string expected";if(null!=e.endTime&&e.hasOwnProperty("endTime")&&!c.isString(e.endTime))return"endTime: string expected";if(null!=e.error&&e.hasOwnProperty("error")&&(t=u.google.cloud.compute.v1.Error.verify(e.error)))return"error."+t;if(null!=e.httpErrorMessage&&e.hasOwnProperty("httpErrorMessage")&&!c.isString(e.httpErrorMessage))return"httpErrorMessage: string expected";if(null!=e.httpErrorStatusCode&&e.hasOwnProperty("httpErrorStatusCode")&&!c.isInteger(e.httpErrorStatusCode))return"httpErrorStatusCode: integer expected";if(null!=e.id&&e.hasOwnProperty("id")&&!c.isString(e.id))return"id: string expected";if(null!=e.insertTime&&e.hasOwnProperty("insertTime")&&!c.isString(e.insertTime))return"insertTime: string expected";if(null!=e.kind&&e.hasOwnProperty("kind")&&!c.isString(e.kind))return"kind: string expected";if(null!=e.name&&e.hasOwnProperty("name")&&!c.isString(e.name))return"name: string expected";if(null!=e.operationType&&e.hasOwnProperty("operationType")&&!c.isString(e.operationType))return"operationType: string expected";if(null!=e.progress&&e.hasOwnProperty("progress")&&!c.isInteger(e.progress))return"progress: integer expected";if(null!=e.region&&e.hasOwnProperty("region")&&!c.isString(e.region))return"region: string expected";if(null!=e.selfLink&&e.hasOwnProperty("selfLink")&&!c.isString(e.selfLink))return"selfLink: string expected";if(null!=e.startTime&&e.hasOwnProperty("startTime")&&!c.isString(e.startTime))return"startTime: string expected";if(null!=e.status&&e.hasOwnProperty("status"))switch(e.status){default:return"status: enum value expected";case 0:case 2104194:case 35394935:case 121282975:}if(null!=e.statusMessage&&e.hasOwnProperty("statusMessage")&&!c.isString(e.statusMessage))return"statusMessage: string expected";if(null!=e.targetId&&e.hasOwnProperty("targetId")&&!c.isString(e.targetId))return"targetId: string expected";if(null!=e.targetLink&&e.hasOwnProperty("targetLink")&&!c.isString(e.targetLink))return"targetLink: string expected";if(null!=e.user&&e.hasOwnProperty("user")&&!c.isString(e.user))return"user: string expected";if(null!=e.warnings&&e.hasOwnProperty("warnings")){if(!Array.isArray(e.warnings))return"warnings: array expected";for(var t,n=0;n>>3){case 3059181:r.code=e.string();break;case 290430901:r.location=e.string();break;case 418054151:r.message=e.string();break;default:e.skipType(7&o)}}return r},l.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},l.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.code&&e.hasOwnProperty("code")&&!c.isString(e.code)?"code: string expected":null!=e.location&&e.hasOwnProperty("location")&&!c.isString(e.location)?"location: string expected":null!=e.message&&e.hasOwnProperty("message")&&!c.isString(e.message)?"message: string expected":null},l.fromObject=function(e){var t;return e instanceof u.google.cloud.compute.v1.Errors?e:(t=new u.google.cloud.compute.v1.Errors,null!=e.code&&(t.code=String(e.code)),null!=e.location&&(t.location=String(e.location)),null!=e.message&&(t.message=String(e.message)),t)},l.toObject=function(e,t){t=t||{};var n={};return null!=e.code&&e.hasOwnProperty("code")&&(n.code=e.code,t.oneofs)&&(n._code="code"),null!=e.location&&e.hasOwnProperty("location")&&(n.location=e.location,t.oneofs)&&(n._location="location"),null!=e.message&&e.hasOwnProperty("message")&&(n.message=e.message,t.oneofs)&&(n._message="message"),n},l.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},l),i.Error=(L.prototype.errors=c.emptyArray,L.create=function(e){return new L(e)},L.encode=function(e,t){if(t=t||a.create(),null!=e.errors&&e.errors.length)for(var n=0;n>>3==315977579?(r.errors&&r.errors.length||(r.errors=[]),r.errors.push(u.google.cloud.compute.v1.Errors.decode(e,e.uint32()))):e.skipType(7&o)}return r},L.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},L.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.errors&&e.hasOwnProperty("errors")){if(!Array.isArray(e.errors))return"errors: array expected";for(var t=0;t>>3){case 3059181:r.code=e.int32();break;case 3076010:r.data&&r.data.length||(r.data=[]),r.data.push(u.google.cloud.compute.v1.Data.decode(e,e.uint32()));break;case 418054151:r.message=e.string();break;default:e.skipType(7&o)}}return r},d.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},d.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.code&&e.hasOwnProperty("code"))switch(e.code){default:return"code: enum value expected";case 0:case 150308440:case 391835586:case 346526230:case 369442967:case 451954443:case 175546307:case 329669423:case 417377419:case 344505463:case 324964999:case 383382887:case 464250446:case 243758146:case 417081265:case 105763924:case 30036744:case 3745539:case 496728641:case 168598460:case 275245642:case 268305617:case 390513439:case 13328052:}if(null!=e.data&&e.hasOwnProperty("data")){if(!Array.isArray(e.data))return"data: array expected";for(var t=0;t>>3){case 3059181:r.code=e.int32();break;case 3076010:r.data&&r.data.length||(r.data=[]),r.data.push(u.google.cloud.compute.v1.Data.decode(e,e.uint32()));break;case 418054151:r.message=e.string();break;default:e.skipType(7&o)}}return r},g.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},g.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.code&&e.hasOwnProperty("code"))switch(e.code){default:return"code: enum value expected";case 0:case 150308440:case 391835586:case 346526230:case 369442967:case 451954443:case 175546307:case 329669423:case 417377419:case 481440678:case 344505463:case 324964999:case 383382887:case 464250446:case 243758146:case 417081265:case 105763924:case 30036744:case 39966469:case 3745539:case 496728641:case 168598460:case 275245642:case 268305617:case 390513439:case 13328052:}if(null!=e.data&&e.hasOwnProperty("data")){if(!Array.isArray(e.data))return"data: array expected";for(var t=0;t>>3){case 106079:r.key=e.string();break;case 111972721:r.value=e.string();break;default:e.skipType(7&o)}}return r},f.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},f.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.key&&e.hasOwnProperty("key")&&!c.isString(e.key)?"key: string expected":null!=e.value&&e.hasOwnProperty("value")&&!c.isString(e.value)?"value: string expected":null},f.fromObject=function(e){var t;return e instanceof u.google.cloud.compute.v1.Data?e:(t=new u.google.cloud.compute.v1.Data,null!=e.key&&(t.key=String(e.key)),null!=e.value&&(t.value=String(e.value)),t)},f.toObject=function(e,t){t=t||{};var n={};return null!=e.key&&e.hasOwnProperty("key")&&(n.key=e.key,t.oneofs)&&(n._key="key"),null!=e.value&&e.hasOwnProperty("value")&&(n.value=e.value,t.oneofs)&&(n._value="value"),n},f.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},f),i.OperationsScopedList=(y.prototype.operations=c.emptyArray,y.prototype.warning=null,Object.defineProperty(y.prototype,"_warning",{get:c.oneOfGetter(t=["warning"]),set:c.oneOfSetter(t)}),y.create=function(e){return new y(e)},y.encode=function(e,t){if(t=t||a.create(),null!=e.operations&&e.operations.length)for(var n=0;n>>3){case 4184044:r.operations&&r.operations.length||(r.operations=[]),r.operations.push(u.google.cloud.compute.v1.Operation.decode(e,e.uint32()));break;case 50704284:r.warning=u.google.cloud.compute.v1.Warning.decode(e,e.uint32());break;default:e.skipType(7&o)}}return r},y.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},y.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.operations&&e.hasOwnProperty("operations")){if(!Array.isArray(e.operations))return"operations: array expected";for(var t,n=0;n>>3){case 3355:r.id=e.string();break;case 100526016:r.items===c.emptyObject&&(r.items={});for(var i=e.uint32()+e.pos,a="",p=null;e.pos>>3){case 1:a=e.string();break;case 2:p=u.google.cloud.compute.v1.OperationsScopedList.decode(e,e.uint32());break;default:e.skipType(7&l)}}r.items[a]=p;break;case 3292052:r.kind=e.string();break;case 79797525:r.nextPageToken=e.string();break;case 456214797:r.selfLink=e.string();break;case 243372063:r.unreachables&&r.unreachables.length||(r.unreachables=[]),r.unreachables.push(e.string());break;case 50704284:r.warning=u.google.cloud.compute.v1.Warning.decode(e,e.uint32());break;default:e.skipType(7&o)}}return r},O.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},O.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.id&&e.hasOwnProperty("id")&&!c.isString(e.id))return"id: string expected";if(null!=e.items&&e.hasOwnProperty("items")){if(!c.isObject(e.items))return"items: object expected";for(var t,n=Object.keys(e.items),r=0;r>>3){case 52090215:r.operation=e.string();break;case 227560217:r.project=e.string();break;case 138946292:r.region=e.string();break;default:e.skipType(7&o)}}return r},B.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},B.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.operation&&e.hasOwnProperty("operation")&&!c.isString(e.operation)?"operation: string expected":null!=e.project&&e.hasOwnProperty("project")&&!c.isString(e.project)?"project: string expected":null!=e.region&&e.hasOwnProperty("region")&&!c.isString(e.region)?"region: string expected":null},B.fromObject=function(e){var t;return e instanceof u.google.cloud.compute.v1.GetRegionOperationRequest?e:(t=new u.google.cloud.compute.v1.GetRegionOperationRequest,null!=e.operation&&(t.operation=String(e.operation)),null!=e.project&&(t.project=String(e.project)),null!=e.region&&(t.region=String(e.region)),t)},B.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.operation="",n.region="",n.project=""),null!=e.operation&&e.hasOwnProperty("operation")&&(n.operation=e.operation),null!=e.region&&e.hasOwnProperty("region")&&(n.region=e.region),null!=e.project&&e.hasOwnProperty("project")&&(n.project=e.project),n},B.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},B),i.DeleteRegionOperationRequest=(V.prototype.operation="",V.prototype.project="",V.prototype.region="",V.create=function(e){return new V(e)},V.encode=function(e,t){return t=t||a.create(),null!=e.operation&&Object.hasOwnProperty.call(e,"operation")&&t.uint32(416721722).string(e.operation),null!=e.region&&Object.hasOwnProperty.call(e,"region")&&t.uint32(1111570338).string(e.region),null!=e.project&&Object.hasOwnProperty.call(e,"project")&&t.uint32(1820481738).string(e.project),t},V.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},V.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new u.google.cloud.compute.v1.DeleteRegionOperationRequest;e.pos>>3){case 52090215:r.operation=e.string();break;case 227560217:r.project=e.string();break;case 138946292:r.region=e.string();break;default:e.skipType(7&o)}}return r},V.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},V.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.operation&&e.hasOwnProperty("operation")&&!c.isString(e.operation)?"operation: string expected":null!=e.project&&e.hasOwnProperty("project")&&!c.isString(e.project)?"project: string expected":null!=e.region&&e.hasOwnProperty("region")&&!c.isString(e.region)?"region: string expected":null},V.fromObject=function(e){var t;return e instanceof u.google.cloud.compute.v1.DeleteRegionOperationRequest?e:(t=new u.google.cloud.compute.v1.DeleteRegionOperationRequest,null!=e.operation&&(t.operation=String(e.operation)),null!=e.project&&(t.project=String(e.project)),null!=e.region&&(t.region=String(e.region)),t)},V.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.operation="",n.region="",n.project=""),null!=e.operation&&e.hasOwnProperty("operation")&&(n.operation=e.operation),null!=e.region&&e.hasOwnProperty("region")&&(n.region=e.region),null!=e.project&&e.hasOwnProperty("project")&&(n.project=e.project),n},V.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},V),i.DeleteRegionOperationResponse=(F.create=function(e){return new F(e)},F.encode=function(e,t){return t=t||a.create()},F.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},F.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,t=new u.google.cloud.compute.v1.DeleteRegionOperationResponse;e.pos>>3){case 336120696:r.filter=e.string();break;case 54715419:r.maxResults=e.uint32();break;case 160562920:r.orderBy=e.string();break;case 19994697:r.pageToken=e.string();break;case 227560217:r.project=e.string();break;case 138946292:r.region=e.string();break;case 517198390:r.returnPartialSuccess=e.bool();break;default:e.skipType(7&o)}}return r},h.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},h.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.filter&&e.hasOwnProperty("filter")&&!c.isString(e.filter)?"filter: string expected":null!=e.maxResults&&e.hasOwnProperty("maxResults")&&!c.isInteger(e.maxResults)?"maxResults: integer expected":null!=e.orderBy&&e.hasOwnProperty("orderBy")&&!c.isString(e.orderBy)?"orderBy: string expected":null!=e.pageToken&&e.hasOwnProperty("pageToken")&&!c.isString(e.pageToken)?"pageToken: string expected":null!=e.project&&e.hasOwnProperty("project")&&!c.isString(e.project)?"project: string expected":null!=e.region&&e.hasOwnProperty("region")&&!c.isString(e.region)?"region: string expected":null!=e.returnPartialSuccess&&e.hasOwnProperty("returnPartialSuccess")&&"boolean"!=typeof e.returnPartialSuccess?"returnPartialSuccess: boolean expected":null},h.fromObject=function(e){var t;return e instanceof u.google.cloud.compute.v1.ListRegionOperationsRequest?e:(t=new u.google.cloud.compute.v1.ListRegionOperationsRequest,null!=e.filter&&(t.filter=String(e.filter)),null!=e.maxResults&&(t.maxResults=e.maxResults>>>0),null!=e.orderBy&&(t.orderBy=String(e.orderBy)),null!=e.pageToken&&(t.pageToken=String(e.pageToken)),null!=e.project&&(t.project=String(e.project)),null!=e.region&&(t.region=String(e.region)),null!=e.returnPartialSuccess&&(t.returnPartialSuccess=Boolean(e.returnPartialSuccess)),t)},h.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.region="",n.project=""),null!=e.pageToken&&e.hasOwnProperty("pageToken")&&(n.pageToken=e.pageToken,t.oneofs)&&(n._pageToken="pageToken"),null!=e.maxResults&&e.hasOwnProperty("maxResults")&&(n.maxResults=e.maxResults,t.oneofs)&&(n._maxResults="maxResults"),null!=e.region&&e.hasOwnProperty("region")&&(n.region=e.region),null!=e.orderBy&&e.hasOwnProperty("orderBy")&&(n.orderBy=e.orderBy,t.oneofs)&&(n._orderBy="orderBy"),null!=e.project&&e.hasOwnProperty("project")&&(n.project=e.project),null!=e.filter&&e.hasOwnProperty("filter")&&(n.filter=e.filter,t.oneofs)&&(n._filter="filter"),null!=e.returnPartialSuccess&&e.hasOwnProperty("returnPartialSuccess")&&(n.returnPartialSuccess=e.returnPartialSuccess,t.oneofs)&&(n._returnPartialSuccess="returnPartialSuccess"),n},h.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},h),i.OperationList=(b.prototype.id=null,b.prototype.items=c.emptyArray,b.prototype.kind=null,b.prototype.nextPageToken=null,b.prototype.selfLink=null,b.prototype.warning=null,Object.defineProperty(b.prototype,"_id",{get:c.oneOfGetter(e=["id"]),set:c.oneOfSetter(e)}),Object.defineProperty(b.prototype,"_kind",{get:c.oneOfGetter(e=["kind"]),set:c.oneOfSetter(e)}),Object.defineProperty(b.prototype,"_nextPageToken",{get:c.oneOfGetter(e=["nextPageToken"]),set:c.oneOfSetter(e)}),Object.defineProperty(b.prototype,"_selfLink",{get:c.oneOfGetter(e=["selfLink"]),set:c.oneOfSetter(e)}),Object.defineProperty(b.prototype,"_warning",{get:c.oneOfGetter(e=["warning"]),set:c.oneOfSetter(e)}),b.create=function(e){return new b(e)},b.encode=function(e,t){if(t=t||a.create(),null!=e.id&&Object.hasOwnProperty.call(e,"id")&&t.uint32(26842).string(e.id),null!=e.kind&&Object.hasOwnProperty.call(e,"kind")&&t.uint32(26336418).string(e.kind),null!=e.warning&&Object.hasOwnProperty.call(e,"warning")&&u.google.cloud.compute.v1.Warning.encode(e.warning,t.uint32(405634274).fork()).ldelim(),null!=e.nextPageToken&&Object.hasOwnProperty.call(e,"nextPageToken")&&t.uint32(638380202).string(e.nextPageToken),null!=e.items&&e.items.length)for(var n=0;n>>3){case 3355:r.id=e.string();break;case 100526016:r.items&&r.items.length||(r.items=[]),r.items.push(u.google.cloud.compute.v1.Operation.decode(e,e.uint32()));break;case 3292052:r.kind=e.string();break;case 79797525:r.nextPageToken=e.string();break;case 456214797:r.selfLink=e.string();break;case 50704284:r.warning=u.google.cloud.compute.v1.Warning.decode(e,e.uint32());break;default:e.skipType(7&o)}}return r},b.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},b.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.id&&e.hasOwnProperty("id")&&!c.isString(e.id))return"id: string expected";if(null!=e.items&&e.hasOwnProperty("items")){if(!Array.isArray(e.items))return"items: array expected";for(var t,n=0;n>>3){case 52090215:r.operation=e.string();break;case 227560217:r.project=e.string();break;case 138946292:r.region=e.string();break;default:e.skipType(7&o)}}return r},U.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},U.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.operation&&e.hasOwnProperty("operation")&&!c.isString(e.operation)?"operation: string expected":null!=e.project&&e.hasOwnProperty("project")&&!c.isString(e.project)?"project: string expected":null!=e.region&&e.hasOwnProperty("region")&&!c.isString(e.region)?"region: string expected":null},U.fromObject=function(e){var t;return e instanceof u.google.cloud.compute.v1.WaitRegionOperationRequest?e:(t=new u.google.cloud.compute.v1.WaitRegionOperationRequest,null!=e.operation&&(t.operation=String(e.operation)),null!=e.project&&(t.project=String(e.project)),null!=e.region&&(t.region=String(e.region)),t)},U.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.operation="",n.region="",n.project=""),null!=e.operation&&e.hasOwnProperty("operation")&&(n.operation=e.operation),null!=e.region&&e.hasOwnProperty("region")&&(n.region=e.region),null!=e.project&&e.hasOwnProperty("project")&&(n.project=e.project),n},U.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},U),i.DeleteZoneOperationRequest=(M.prototype.operation="",M.prototype.project="",M.prototype.zone="",M.create=function(e){return new M(e)},M.encode=function(e,t){return t=t||a.create(),null!=e.zone&&Object.hasOwnProperty.call(e,"zone")&&t.uint32(29957474).string(e.zone),null!=e.operation&&Object.hasOwnProperty.call(e,"operation")&&t.uint32(416721722).string(e.operation),null!=e.project&&Object.hasOwnProperty.call(e,"project")&&t.uint32(1820481738).string(e.project),t},M.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},M.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new u.google.cloud.compute.v1.DeleteZoneOperationRequest;e.pos>>3){case 52090215:r.operation=e.string();break;case 227560217:r.project=e.string();break;case 3744684:r.zone=e.string();break;default:e.skipType(7&o)}}return r},M.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},M.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.operation&&e.hasOwnProperty("operation")&&!c.isString(e.operation)?"operation: string expected":null!=e.project&&e.hasOwnProperty("project")&&!c.isString(e.project)?"project: string expected":null!=e.zone&&e.hasOwnProperty("zone")&&!c.isString(e.zone)?"zone: string expected":null},M.fromObject=function(e){var t;return e instanceof u.google.cloud.compute.v1.DeleteZoneOperationRequest?e:(t=new u.google.cloud.compute.v1.DeleteZoneOperationRequest,null!=e.operation&&(t.operation=String(e.operation)),null!=e.project&&(t.project=String(e.project)),null!=e.zone&&(t.zone=String(e.zone)),t)},M.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.zone="",n.operation="",n.project=""),null!=e.zone&&e.hasOwnProperty("zone")&&(n.zone=e.zone),null!=e.operation&&e.hasOwnProperty("operation")&&(n.operation=e.operation),null!=e.project&&e.hasOwnProperty("project")&&(n.project=e.project),n},M.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},M),i.DeleteZoneOperationResponse=(z.create=function(e){return new z(e)},z.encode=function(e,t){return t=t||a.create()},z.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},z.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,t=new u.google.cloud.compute.v1.DeleteZoneOperationResponse;e.pos>>3){case 52090215:r.operation=e.string();break;case 227560217:r.project=e.string();break;case 3744684:r.zone=e.string();break;default:e.skipType(7&o)}}return r},J.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},J.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.operation&&e.hasOwnProperty("operation")&&!c.isString(e.operation)?"operation: string expected":null!=e.project&&e.hasOwnProperty("project")&&!c.isString(e.project)?"project: string expected":null!=e.zone&&e.hasOwnProperty("zone")&&!c.isString(e.zone)?"zone: string expected":null},J.fromObject=function(e){var t;return e instanceof u.google.cloud.compute.v1.GetZoneOperationRequest?e:(t=new u.google.cloud.compute.v1.GetZoneOperationRequest,null!=e.operation&&(t.operation=String(e.operation)),null!=e.project&&(t.project=String(e.project)),null!=e.zone&&(t.zone=String(e.zone)),t)},J.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.zone="",n.operation="",n.project=""),null!=e.zone&&e.hasOwnProperty("zone")&&(n.zone=e.zone),null!=e.operation&&e.hasOwnProperty("operation")&&(n.operation=e.operation),null!=e.project&&e.hasOwnProperty("project")&&(n.project=e.project),n},J.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},J),i.ListZoneOperationsRequest=(m.prototype.filter=null,m.prototype.maxResults=null,m.prototype.orderBy=null,m.prototype.pageToken=null,m.prototype.project="",m.prototype.returnPartialSuccess=null,m.prototype.zone="",Object.defineProperty(m.prototype,"_filter",{get:c.oneOfGetter(t=["filter"]),set:c.oneOfSetter(t)}),Object.defineProperty(m.prototype,"_maxResults",{get:c.oneOfGetter(t=["maxResults"]),set:c.oneOfSetter(t)}),Object.defineProperty(m.prototype,"_orderBy",{get:c.oneOfGetter(t=["orderBy"]),set:c.oneOfSetter(t)}),Object.defineProperty(m.prototype,"_pageToken",{get:c.oneOfGetter(t=["pageToken"]),set:c.oneOfSetter(t)}),Object.defineProperty(m.prototype,"_returnPartialSuccess",{get:c.oneOfGetter(t=["returnPartialSuccess"]),set:c.oneOfSetter(t)}),m.create=function(e){return new m(e)},m.encode=function(e,t){return t=t||a.create(),null!=e.zone&&Object.hasOwnProperty.call(e,"zone")&&t.uint32(29957474).string(e.zone),null!=e.pageToken&&Object.hasOwnProperty.call(e,"pageToken")&&t.uint32(159957578).string(e.pageToken),null!=e.maxResults&&Object.hasOwnProperty.call(e,"maxResults")&&t.uint32(437723352).uint32(e.maxResults),null!=e.orderBy&&Object.hasOwnProperty.call(e,"orderBy")&&t.uint32(1284503362).string(e.orderBy),null!=e.project&&Object.hasOwnProperty.call(e,"project")&&t.uint32(1820481738).string(e.project),null!=e.filter&&Object.hasOwnProperty.call(e,"filter")&&t.uint32(2688965570).string(e.filter),null!=e.returnPartialSuccess&&Object.hasOwnProperty.call(e,"returnPartialSuccess")&&t.uint32(4137587120).bool(e.returnPartialSuccess),t},m.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},m.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new u.google.cloud.compute.v1.ListZoneOperationsRequest;e.pos>>3){case 336120696:r.filter=e.string();break;case 54715419:r.maxResults=e.uint32();break;case 160562920:r.orderBy=e.string();break;case 19994697:r.pageToken=e.string();break;case 227560217:r.project=e.string();break;case 517198390:r.returnPartialSuccess=e.bool();break;case 3744684:r.zone=e.string();break;default:e.skipType(7&o)}}return r},m.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},m.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.filter&&e.hasOwnProperty("filter")&&!c.isString(e.filter)?"filter: string expected":null!=e.maxResults&&e.hasOwnProperty("maxResults")&&!c.isInteger(e.maxResults)?"maxResults: integer expected":null!=e.orderBy&&e.hasOwnProperty("orderBy")&&!c.isString(e.orderBy)?"orderBy: string expected":null!=e.pageToken&&e.hasOwnProperty("pageToken")&&!c.isString(e.pageToken)?"pageToken: string expected":null!=e.project&&e.hasOwnProperty("project")&&!c.isString(e.project)?"project: string expected":null!=e.returnPartialSuccess&&e.hasOwnProperty("returnPartialSuccess")&&"boolean"!=typeof e.returnPartialSuccess?"returnPartialSuccess: boolean expected":null!=e.zone&&e.hasOwnProperty("zone")&&!c.isString(e.zone)?"zone: string expected":null},m.fromObject=function(e){var t;return e instanceof u.google.cloud.compute.v1.ListZoneOperationsRequest?e:(t=new u.google.cloud.compute.v1.ListZoneOperationsRequest,null!=e.filter&&(t.filter=String(e.filter)),null!=e.maxResults&&(t.maxResults=e.maxResults>>>0),null!=e.orderBy&&(t.orderBy=String(e.orderBy)),null!=e.pageToken&&(t.pageToken=String(e.pageToken)),null!=e.project&&(t.project=String(e.project)),null!=e.returnPartialSuccess&&(t.returnPartialSuccess=Boolean(e.returnPartialSuccess)),null!=e.zone&&(t.zone=String(e.zone)),t)},m.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.zone="",n.project=""),null!=e.zone&&e.hasOwnProperty("zone")&&(n.zone=e.zone),null!=e.pageToken&&e.hasOwnProperty("pageToken")&&(n.pageToken=e.pageToken,t.oneofs)&&(n._pageToken="pageToken"),null!=e.maxResults&&e.hasOwnProperty("maxResults")&&(n.maxResults=e.maxResults,t.oneofs)&&(n._maxResults="maxResults"),null!=e.orderBy&&e.hasOwnProperty("orderBy")&&(n.orderBy=e.orderBy,t.oneofs)&&(n._orderBy="orderBy"),null!=e.project&&e.hasOwnProperty("project")&&(n.project=e.project),null!=e.filter&&e.hasOwnProperty("filter")&&(n.filter=e.filter,t.oneofs)&&(n._filter="filter"),null!=e.returnPartialSuccess&&e.hasOwnProperty("returnPartialSuccess")&&(n.returnPartialSuccess=e.returnPartialSuccess,t.oneofs)&&(n._returnPartialSuccess="returnPartialSuccess"),n},m.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},m),i.WaitZoneOperationRequest=(q.prototype.operation="",q.prototype.project="",q.prototype.zone="",q.create=function(e){return new q(e)},q.encode=function(e,t){return t=t||a.create(),null!=e.zone&&Object.hasOwnProperty.call(e,"zone")&&t.uint32(29957474).string(e.zone),null!=e.operation&&Object.hasOwnProperty.call(e,"operation")&&t.uint32(416721722).string(e.operation),null!=e.project&&Object.hasOwnProperty.call(e,"project")&&t.uint32(1820481738).string(e.project),t},q.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},q.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new u.google.cloud.compute.v1.WaitZoneOperationRequest;e.pos>>3){case 52090215:r.operation=e.string();break;case 227560217:r.project=e.string();break;case 3744684:r.zone=e.string();break;default:e.skipType(7&o)}}return r},q.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},q.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.operation&&e.hasOwnProperty("operation")&&!c.isString(e.operation)?"operation: string expected":null!=e.project&&e.hasOwnProperty("project")&&!c.isString(e.project)?"project: string expected":null!=e.zone&&e.hasOwnProperty("zone")&&!c.isString(e.zone)?"zone: string expected":null},q.fromObject=function(e){var t;return e instanceof u.google.cloud.compute.v1.WaitZoneOperationRequest?e:(t=new u.google.cloud.compute.v1.WaitZoneOperationRequest,null!=e.operation&&(t.operation=String(e.operation)),null!=e.project&&(t.project=String(e.project)),null!=e.zone&&(t.zone=String(e.zone)),t)},q.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.zone="",n.operation="",n.project=""),null!=e.zone&&e.hasOwnProperty("zone")&&(n.zone=e.zone),null!=e.operation&&e.hasOwnProperty("operation")&&(n.operation=e.operation),null!=e.project&&e.hasOwnProperty("project")&&(n.project=e.project),n},q.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},q),i.AggregatedListGlobalOperationsRequest=(v.prototype.filter=null,v.prototype.includeAllScopes=null,v.prototype.maxResults=null,v.prototype.orderBy=null,v.prototype.pageToken=null,v.prototype.project="",v.prototype.returnPartialSuccess=null,Object.defineProperty(v.prototype,"_filter",{get:c.oneOfGetter(e=["filter"]),set:c.oneOfSetter(e)}),Object.defineProperty(v.prototype,"_includeAllScopes",{get:c.oneOfGetter(e=["includeAllScopes"]),set:c.oneOfSetter(e)}),Object.defineProperty(v.prototype,"_maxResults",{get:c.oneOfGetter(e=["maxResults"]),set:c.oneOfSetter(e)}),Object.defineProperty(v.prototype,"_orderBy",{get:c.oneOfGetter(e=["orderBy"]),set:c.oneOfSetter(e)}),Object.defineProperty(v.prototype,"_pageToken",{get:c.oneOfGetter(e=["pageToken"]),set:c.oneOfSetter(e)}),Object.defineProperty(v.prototype,"_returnPartialSuccess",{get:c.oneOfGetter(e=["returnPartialSuccess"]),set:c.oneOfSetter(e)}),v.create=function(e){return new v(e)},v.encode=function(e,t){return t=t||a.create(),null!=e.pageToken&&Object.hasOwnProperty.call(e,"pageToken")&&t.uint32(159957578).string(e.pageToken),null!=e.maxResults&&Object.hasOwnProperty.call(e,"maxResults")&&t.uint32(437723352).uint32(e.maxResults),null!=e.orderBy&&Object.hasOwnProperty.call(e,"orderBy")&&t.uint32(1284503362).string(e.orderBy),null!=e.project&&Object.hasOwnProperty.call(e,"project")&&t.uint32(1820481738).string(e.project),null!=e.filter&&Object.hasOwnProperty.call(e,"filter")&&t.uint32(2688965570).string(e.filter),null!=e.includeAllScopes&&Object.hasOwnProperty.call(e,"includeAllScopes")&&t.uint32(3130623904).bool(e.includeAllScopes),null!=e.returnPartialSuccess&&Object.hasOwnProperty.call(e,"returnPartialSuccess")&&t.uint32(4137587120).bool(e.returnPartialSuccess),t},v.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},v.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new u.google.cloud.compute.v1.AggregatedListGlobalOperationsRequest;e.pos>>3){case 336120696:r.filter=e.string();break;case 391327988:r.includeAllScopes=e.bool();break;case 54715419:r.maxResults=e.uint32();break;case 160562920:r.orderBy=e.string();break;case 19994697:r.pageToken=e.string();break;case 227560217:r.project=e.string();break;case 517198390:r.returnPartialSuccess=e.bool();break;default:e.skipType(7&o)}}return r},v.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},v.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.filter&&e.hasOwnProperty("filter")&&!c.isString(e.filter)?"filter: string expected":null!=e.includeAllScopes&&e.hasOwnProperty("includeAllScopes")&&"boolean"!=typeof e.includeAllScopes?"includeAllScopes: boolean expected":null!=e.maxResults&&e.hasOwnProperty("maxResults")&&!c.isInteger(e.maxResults)?"maxResults: integer expected":null!=e.orderBy&&e.hasOwnProperty("orderBy")&&!c.isString(e.orderBy)?"orderBy: string expected":null!=e.pageToken&&e.hasOwnProperty("pageToken")&&!c.isString(e.pageToken)?"pageToken: string expected":null!=e.project&&e.hasOwnProperty("project")&&!c.isString(e.project)?"project: string expected":null!=e.returnPartialSuccess&&e.hasOwnProperty("returnPartialSuccess")&&"boolean"!=typeof e.returnPartialSuccess?"returnPartialSuccess: boolean expected":null},v.fromObject=function(e){var t;return e instanceof u.google.cloud.compute.v1.AggregatedListGlobalOperationsRequest?e:(t=new u.google.cloud.compute.v1.AggregatedListGlobalOperationsRequest,null!=e.filter&&(t.filter=String(e.filter)),null!=e.includeAllScopes&&(t.includeAllScopes=Boolean(e.includeAllScopes)),null!=e.maxResults&&(t.maxResults=e.maxResults>>>0),null!=e.orderBy&&(t.orderBy=String(e.orderBy)),null!=e.pageToken&&(t.pageToken=String(e.pageToken)),null!=e.project&&(t.project=String(e.project)),null!=e.returnPartialSuccess&&(t.returnPartialSuccess=Boolean(e.returnPartialSuccess)),t)},v.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.project=""),null!=e.pageToken&&e.hasOwnProperty("pageToken")&&(n.pageToken=e.pageToken,t.oneofs)&&(n._pageToken="pageToken"),null!=e.maxResults&&e.hasOwnProperty("maxResults")&&(n.maxResults=e.maxResults,t.oneofs)&&(n._maxResults="maxResults"),null!=e.orderBy&&e.hasOwnProperty("orderBy")&&(n.orderBy=e.orderBy,t.oneofs)&&(n._orderBy="orderBy"),null!=e.project&&e.hasOwnProperty("project")&&(n.project=e.project),null!=e.filter&&e.hasOwnProperty("filter")&&(n.filter=e.filter,t.oneofs)&&(n._filter="filter"),null!=e.includeAllScopes&&e.hasOwnProperty("includeAllScopes")&&(n.includeAllScopes=e.includeAllScopes,t.oneofs)&&(n._includeAllScopes="includeAllScopes"),null!=e.returnPartialSuccess&&e.hasOwnProperty("returnPartialSuccess")&&(n.returnPartialSuccess=e.returnPartialSuccess,t.oneofs)&&(n._returnPartialSuccess="returnPartialSuccess"),n},v.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},v),i.DeleteGlobalOperationRequest=(W.prototype.operation="",W.prototype.project="",W.create=function(e){return new W(e)},W.encode=function(e,t){return t=t||a.create(),null!=e.operation&&Object.hasOwnProperty.call(e,"operation")&&t.uint32(416721722).string(e.operation),null!=e.project&&Object.hasOwnProperty.call(e,"project")&&t.uint32(1820481738).string(e.project),t},W.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},W.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new u.google.cloud.compute.v1.DeleteGlobalOperationRequest;e.pos>>3){case 52090215:r.operation=e.string();break;case 227560217:r.project=e.string();break;default:e.skipType(7&o)}}return r},W.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},W.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.operation&&e.hasOwnProperty("operation")&&!c.isString(e.operation)?"operation: string expected":null!=e.project&&e.hasOwnProperty("project")&&!c.isString(e.project)?"project: string expected":null},W.fromObject=function(e){var t;return e instanceof u.google.cloud.compute.v1.DeleteGlobalOperationRequest?e:(t=new u.google.cloud.compute.v1.DeleteGlobalOperationRequest,null!=e.operation&&(t.operation=String(e.operation)),null!=e.project&&(t.project=String(e.project)),t)},W.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.operation="",n.project=""),null!=e.operation&&e.hasOwnProperty("operation")&&(n.operation=e.operation),null!=e.project&&e.hasOwnProperty("project")&&(n.project=e.project),n},W.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},W),i.DeleteGlobalOperationResponse=(H.create=function(e){return new H(e)},H.encode=function(e,t){return t=t||a.create()},H.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},H.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,t=new u.google.cloud.compute.v1.DeleteGlobalOperationResponse;e.pos>>3){case 52090215:r.operation=e.string();break;case 227560217:r.project=e.string();break;default:e.skipType(7&o)}}return r},Y.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},Y.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.operation&&e.hasOwnProperty("operation")&&!c.isString(e.operation)?"operation: string expected":null!=e.project&&e.hasOwnProperty("project")&&!c.isString(e.project)?"project: string expected":null},Y.fromObject=function(e){var t;return e instanceof u.google.cloud.compute.v1.GetGlobalOperationRequest?e:(t=new u.google.cloud.compute.v1.GetGlobalOperationRequest,null!=e.operation&&(t.operation=String(e.operation)),null!=e.project&&(t.project=String(e.project)),t)},Y.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.operation="",n.project=""),null!=e.operation&&e.hasOwnProperty("operation")&&(n.operation=e.operation),null!=e.project&&e.hasOwnProperty("project")&&(n.project=e.project),n},Y.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Y),i.ListGlobalOperationsRequest=(P.prototype.filter=null,P.prototype.maxResults=null,P.prototype.orderBy=null,P.prototype.pageToken=null,P.prototype.project="",P.prototype.returnPartialSuccess=null,Object.defineProperty(P.prototype,"_filter",{get:c.oneOfGetter(t=["filter"]),set:c.oneOfSetter(t)}),Object.defineProperty(P.prototype,"_maxResults",{get:c.oneOfGetter(t=["maxResults"]),set:c.oneOfSetter(t)}),Object.defineProperty(P.prototype,"_orderBy",{get:c.oneOfGetter(t=["orderBy"]),set:c.oneOfSetter(t)}),Object.defineProperty(P.prototype,"_pageToken",{get:c.oneOfGetter(t=["pageToken"]),set:c.oneOfSetter(t)}),Object.defineProperty(P.prototype,"_returnPartialSuccess",{get:c.oneOfGetter(t=["returnPartialSuccess"]),set:c.oneOfSetter(t)}),P.create=function(e){return new P(e)},P.encode=function(e,t){return t=t||a.create(),null!=e.pageToken&&Object.hasOwnProperty.call(e,"pageToken")&&t.uint32(159957578).string(e.pageToken),null!=e.maxResults&&Object.hasOwnProperty.call(e,"maxResults")&&t.uint32(437723352).uint32(e.maxResults),null!=e.orderBy&&Object.hasOwnProperty.call(e,"orderBy")&&t.uint32(1284503362).string(e.orderBy),null!=e.project&&Object.hasOwnProperty.call(e,"project")&&t.uint32(1820481738).string(e.project),null!=e.filter&&Object.hasOwnProperty.call(e,"filter")&&t.uint32(2688965570).string(e.filter),null!=e.returnPartialSuccess&&Object.hasOwnProperty.call(e,"returnPartialSuccess")&&t.uint32(4137587120).bool(e.returnPartialSuccess),t},P.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},P.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new u.google.cloud.compute.v1.ListGlobalOperationsRequest;e.pos>>3){case 336120696:r.filter=e.string();break;case 54715419:r.maxResults=e.uint32();break;case 160562920:r.orderBy=e.string();break;case 19994697:r.pageToken=e.string();break;case 227560217:r.project=e.string();break;case 517198390:r.returnPartialSuccess=e.bool();break;default:e.skipType(7&o)}}return r},P.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},P.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.filter&&e.hasOwnProperty("filter")&&!c.isString(e.filter)?"filter: string expected":null!=e.maxResults&&e.hasOwnProperty("maxResults")&&!c.isInteger(e.maxResults)?"maxResults: integer expected":null!=e.orderBy&&e.hasOwnProperty("orderBy")&&!c.isString(e.orderBy)?"orderBy: string expected":null!=e.pageToken&&e.hasOwnProperty("pageToken")&&!c.isString(e.pageToken)?"pageToken: string expected":null!=e.project&&e.hasOwnProperty("project")&&!c.isString(e.project)?"project: string expected":null!=e.returnPartialSuccess&&e.hasOwnProperty("returnPartialSuccess")&&"boolean"!=typeof e.returnPartialSuccess?"returnPartialSuccess: boolean expected":null},P.fromObject=function(e){var t;return e instanceof u.google.cloud.compute.v1.ListGlobalOperationsRequest?e:(t=new u.google.cloud.compute.v1.ListGlobalOperationsRequest,null!=e.filter&&(t.filter=String(e.filter)),null!=e.maxResults&&(t.maxResults=e.maxResults>>>0),null!=e.orderBy&&(t.orderBy=String(e.orderBy)),null!=e.pageToken&&(t.pageToken=String(e.pageToken)),null!=e.project&&(t.project=String(e.project)),null!=e.returnPartialSuccess&&(t.returnPartialSuccess=Boolean(e.returnPartialSuccess)),t)},P.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.project=""),null!=e.pageToken&&e.hasOwnProperty("pageToken")&&(n.pageToken=e.pageToken,t.oneofs)&&(n._pageToken="pageToken"),null!=e.maxResults&&e.hasOwnProperty("maxResults")&&(n.maxResults=e.maxResults,t.oneofs)&&(n._maxResults="maxResults"),null!=e.orderBy&&e.hasOwnProperty("orderBy")&&(n.orderBy=e.orderBy,t.oneofs)&&(n._orderBy="orderBy"),null!=e.project&&e.hasOwnProperty("project")&&(n.project=e.project),null!=e.filter&&e.hasOwnProperty("filter")&&(n.filter=e.filter,t.oneofs)&&(n._filter="filter"),null!=e.returnPartialSuccess&&e.hasOwnProperty("returnPartialSuccess")&&(n.returnPartialSuccess=e.returnPartialSuccess,t.oneofs)&&(n._returnPartialSuccess="returnPartialSuccess"),n},P.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},P),i.WaitGlobalOperationRequest=(X.prototype.operation="",X.prototype.project="",X.create=function(e){return new X(e)},X.encode=function(e,t){return t=t||a.create(),null!=e.operation&&Object.hasOwnProperty.call(e,"operation")&&t.uint32(416721722).string(e.operation),null!=e.project&&Object.hasOwnProperty.call(e,"project")&&t.uint32(1820481738).string(e.project),t},X.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},X.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new u.google.cloud.compute.v1.WaitGlobalOperationRequest;e.pos>>3){case 52090215:r.operation=e.string();break;case 227560217:r.project=e.string();break;default:e.skipType(7&o)}}return r},X.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},X.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.operation&&e.hasOwnProperty("operation")&&!c.isString(e.operation)?"operation: string expected":null!=e.project&&e.hasOwnProperty("project")&&!c.isString(e.project)?"project: string expected":null},X.fromObject=function(e){var t;return e instanceof u.google.cloud.compute.v1.WaitGlobalOperationRequest?e:(t=new u.google.cloud.compute.v1.WaitGlobalOperationRequest,null!=e.operation&&(t.operation=String(e.operation)),null!=e.project&&(t.project=String(e.project)),t)},X.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.operation="",n.project=""),null!=e.operation&&e.hasOwnProperty("operation")&&(n.operation=e.operation),null!=e.project&&e.hasOwnProperty("project")&&(n.project=e.project),n},X.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},X),i.DeleteGlobalOrganizationOperationRequest=(Z.prototype.operation="",Z.prototype.parentId=null,Object.defineProperty(Z.prototype,"_parentId",{get:c.oneOfGetter(e=["parentId"]),set:c.oneOfSetter(e)}),Z.create=function(e){return new Z(e)},Z.encode=function(e,t){return t=t||a.create(),null!=e.operation&&Object.hasOwnProperty.call(e,"operation")&&t.uint32(416721722).string(e.operation),null!=e.parentId&&Object.hasOwnProperty.call(e,"parentId")&&t.uint32(3677718146).string(e.parentId),t},Z.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},Z.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new u.google.cloud.compute.v1.DeleteGlobalOrganizationOperationRequest;e.pos>>3){case 52090215:r.operation=e.string();break;case 459714768:r.parentId=e.string();break;default:e.skipType(7&o)}}return r},Z.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},Z.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.operation&&e.hasOwnProperty("operation")&&!c.isString(e.operation)?"operation: string expected":null!=e.parentId&&e.hasOwnProperty("parentId")&&!c.isString(e.parentId)?"parentId: string expected":null},Z.fromObject=function(e){var t;return e instanceof u.google.cloud.compute.v1.DeleteGlobalOrganizationOperationRequest?e:(t=new u.google.cloud.compute.v1.DeleteGlobalOrganizationOperationRequest,null!=e.operation&&(t.operation=String(e.operation)),null!=e.parentId&&(t.parentId=String(e.parentId)),t)},Z.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.operation=""),null!=e.operation&&e.hasOwnProperty("operation")&&(n.operation=e.operation),null!=e.parentId&&e.hasOwnProperty("parentId")&&(n.parentId=e.parentId,t.oneofs)&&(n._parentId="parentId"),n},Z.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Z),i.DeleteGlobalOrganizationOperationResponse=(K.create=function(e){return new K(e)},K.encode=function(e,t){return t=t||a.create()},K.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},K.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,t=new u.google.cloud.compute.v1.DeleteGlobalOrganizationOperationResponse;e.pos>>3){case 52090215:r.operation=e.string();break;case 459714768:r.parentId=e.string();break;default:e.skipType(7&o)}}return r},Q.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},Q.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.operation&&e.hasOwnProperty("operation")&&!c.isString(e.operation)?"operation: string expected":null!=e.parentId&&e.hasOwnProperty("parentId")&&!c.isString(e.parentId)?"parentId: string expected":null},Q.fromObject=function(e){var t;return e instanceof u.google.cloud.compute.v1.GetGlobalOrganizationOperationRequest?e:(t=new u.google.cloud.compute.v1.GetGlobalOrganizationOperationRequest,null!=e.operation&&(t.operation=String(e.operation)),null!=e.parentId&&(t.parentId=String(e.parentId)),t)},Q.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.operation=""),null!=e.operation&&e.hasOwnProperty("operation")&&(n.operation=e.operation),null!=e.parentId&&e.hasOwnProperty("parentId")&&(n.parentId=e.parentId,t.oneofs)&&(n._parentId="parentId"),n},Q.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Q),i.ListGlobalOrganizationOperationsRequest=(w.prototype.filter=null,w.prototype.maxResults=null,w.prototype.orderBy=null,w.prototype.pageToken=null,w.prototype.parentId=null,w.prototype.returnPartialSuccess=null,Object.defineProperty(w.prototype,"_filter",{get:c.oneOfGetter(e=["filter"]),set:c.oneOfSetter(e)}),Object.defineProperty(w.prototype,"_maxResults",{get:c.oneOfGetter(e=["maxResults"]),set:c.oneOfSetter(e)}),Object.defineProperty(w.prototype,"_orderBy",{get:c.oneOfGetter(e=["orderBy"]),set:c.oneOfSetter(e)}),Object.defineProperty(w.prototype,"_pageToken",{get:c.oneOfGetter(e=["pageToken"]),set:c.oneOfSetter(e)}),Object.defineProperty(w.prototype,"_parentId",{get:c.oneOfGetter(e=["parentId"]),set:c.oneOfSetter(e)}),Object.defineProperty(w.prototype,"_returnPartialSuccess",{get:c.oneOfGetter(e=["returnPartialSuccess"]),set:c.oneOfSetter(e)}),w.create=function(e){return new w(e)},w.encode=function(e,t){return t=t||a.create(),null!=e.pageToken&&Object.hasOwnProperty.call(e,"pageToken")&&t.uint32(159957578).string(e.pageToken),null!=e.maxResults&&Object.hasOwnProperty.call(e,"maxResults")&&t.uint32(437723352).uint32(e.maxResults),null!=e.orderBy&&Object.hasOwnProperty.call(e,"orderBy")&&t.uint32(1284503362).string(e.orderBy),null!=e.filter&&Object.hasOwnProperty.call(e,"filter")&&t.uint32(2688965570).string(e.filter),null!=e.parentId&&Object.hasOwnProperty.call(e,"parentId")&&t.uint32(3677718146).string(e.parentId),null!=e.returnPartialSuccess&&Object.hasOwnProperty.call(e,"returnPartialSuccess")&&t.uint32(4137587120).bool(e.returnPartialSuccess),t},w.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},w.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new u.google.cloud.compute.v1.ListGlobalOrganizationOperationsRequest;e.pos>>3){case 336120696:r.filter=e.string();break;case 54715419:r.maxResults=e.uint32();break;case 160562920:r.orderBy=e.string();break;case 19994697:r.pageToken=e.string();break;case 459714768:r.parentId=e.string();break;case 517198390:r.returnPartialSuccess=e.bool();break;default:e.skipType(7&o)}}return r},w.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},w.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.filter&&e.hasOwnProperty("filter")&&!c.isString(e.filter)?"filter: string expected":null!=e.maxResults&&e.hasOwnProperty("maxResults")&&!c.isInteger(e.maxResults)?"maxResults: integer expected":null!=e.orderBy&&e.hasOwnProperty("orderBy")&&!c.isString(e.orderBy)?"orderBy: string expected":null!=e.pageToken&&e.hasOwnProperty("pageToken")&&!c.isString(e.pageToken)?"pageToken: string expected":null!=e.parentId&&e.hasOwnProperty("parentId")&&!c.isString(e.parentId)?"parentId: string expected":null!=e.returnPartialSuccess&&e.hasOwnProperty("returnPartialSuccess")&&"boolean"!=typeof e.returnPartialSuccess?"returnPartialSuccess: boolean expected":null},w.fromObject=function(e){var t;return e instanceof u.google.cloud.compute.v1.ListGlobalOrganizationOperationsRequest?e:(t=new u.google.cloud.compute.v1.ListGlobalOrganizationOperationsRequest,null!=e.filter&&(t.filter=String(e.filter)),null!=e.maxResults&&(t.maxResults=e.maxResults>>>0),null!=e.orderBy&&(t.orderBy=String(e.orderBy)),null!=e.pageToken&&(t.pageToken=String(e.pageToken)),null!=e.parentId&&(t.parentId=String(e.parentId)),null!=e.returnPartialSuccess&&(t.returnPartialSuccess=Boolean(e.returnPartialSuccess)),t)},w.toObject=function(e,t){t=t||{};var n={};return null!=e.pageToken&&e.hasOwnProperty("pageToken")&&(n.pageToken=e.pageToken,t.oneofs)&&(n._pageToken="pageToken"),null!=e.maxResults&&e.hasOwnProperty("maxResults")&&(n.maxResults=e.maxResults,t.oneofs)&&(n._maxResults="maxResults"),null!=e.orderBy&&e.hasOwnProperty("orderBy")&&(n.orderBy=e.orderBy,t.oneofs)&&(n._orderBy="orderBy"),null!=e.filter&&e.hasOwnProperty("filter")&&(n.filter=e.filter,t.oneofs)&&(n._filter="filter"),null!=e.parentId&&e.hasOwnProperty("parentId")&&(n.parentId=e.parentId,t.oneofs)&&(n._parentId="parentId"),null!=e.returnPartialSuccess&&e.hasOwnProperty("returnPartialSuccess")&&(n.returnPartialSuccess=e.returnPartialSuccess,t.oneofs)&&(n._returnPartialSuccess="returnPartialSuccess"),n},w.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},w),i.RegionOperations=((($.prototype=Object.create(r.rpc.Service.prototype)).constructor=$).create=function(e,t,n){return new this(e,t,n)},Object.defineProperty($.prototype.delete=function e(t,n){return this.rpcCall(e,u.google.cloud.compute.v1.DeleteRegionOperationRequest,u.google.cloud.compute.v1.DeleteRegionOperationResponse,t,n)},"name",{value:"Delete"}),Object.defineProperty($.prototype.get=function e(t,n){return this.rpcCall(e,u.google.cloud.compute.v1.GetRegionOperationRequest,u.google.cloud.compute.v1.Operation,t,n)},"name",{value:"Get"}),Object.defineProperty($.prototype.list=function e(t,n){return this.rpcCall(e,u.google.cloud.compute.v1.ListRegionOperationsRequest,u.google.cloud.compute.v1.OperationList,t,n)},"name",{value:"List"}),Object.defineProperty($.prototype.wait=function e(t,n){return this.rpcCall(e,u.google.cloud.compute.v1.WaitRegionOperationRequest,u.google.cloud.compute.v1.Operation,t,n)},"name",{value:"Wait"}),$),i.ZoneOperations=(((ee.prototype=Object.create(r.rpc.Service.prototype)).constructor=ee).create=function(e,t,n){return new this(e,t,n)},Object.defineProperty(ee.prototype.delete=function e(t,n){return this.rpcCall(e,u.google.cloud.compute.v1.DeleteZoneOperationRequest,u.google.cloud.compute.v1.DeleteZoneOperationResponse,t,n)},"name",{value:"Delete"}),Object.defineProperty(ee.prototype.get=function e(t,n){return this.rpcCall(e,u.google.cloud.compute.v1.GetZoneOperationRequest,u.google.cloud.compute.v1.Operation,t,n)},"name",{value:"Get"}),Object.defineProperty(ee.prototype.list=function e(t,n){return this.rpcCall(e,u.google.cloud.compute.v1.ListZoneOperationsRequest,u.google.cloud.compute.v1.OperationList,t,n)},"name",{value:"List"}),Object.defineProperty(ee.prototype.wait=function e(t,n){return this.rpcCall(e,u.google.cloud.compute.v1.WaitZoneOperationRequest,u.google.cloud.compute.v1.Operation,t,n)},"name",{value:"Wait"}),ee),i.GlobalOperations=(((te.prototype=Object.create(r.rpc.Service.prototype)).constructor=te).create=function(e,t,n){return new this(e,t,n)},Object.defineProperty(te.prototype.aggregatedList=function e(t,n){return this.rpcCall(e,u.google.cloud.compute.v1.AggregatedListGlobalOperationsRequest,u.google.cloud.compute.v1.OperationAggregatedList,t,n)},"name",{value:"AggregatedList"}),Object.defineProperty(te.prototype.delete=function e(t,n){return this.rpcCall(e,u.google.cloud.compute.v1.DeleteGlobalOperationRequest,u.google.cloud.compute.v1.DeleteGlobalOperationResponse,t,n)},"name",{value:"Delete"}),Object.defineProperty(te.prototype.get=function e(t,n){return this.rpcCall(e,u.google.cloud.compute.v1.GetGlobalOperationRequest,u.google.cloud.compute.v1.Operation,t,n)},"name",{value:"Get"}),Object.defineProperty(te.prototype.list=function e(t,n){return this.rpcCall(e,u.google.cloud.compute.v1.ListGlobalOperationsRequest,u.google.cloud.compute.v1.OperationList,t,n)},"name",{value:"List"}),Object.defineProperty(te.prototype.wait=function e(t,n){return this.rpcCall(e,u.google.cloud.compute.v1.WaitGlobalOperationRequest,u.google.cloud.compute.v1.Operation,t,n)},"name",{value:"Wait"}),te),i.GlobalOrganizationOperations=(((ne.prototype=Object.create(r.rpc.Service.prototype)).constructor=ne).create=function(e,t,n){return new this(e,t,n)},Object.defineProperty(ne.prototype.delete=function e(t,n){return this.rpcCall(e,u.google.cloud.compute.v1.DeleteGlobalOrganizationOperationRequest,u.google.cloud.compute.v1.DeleteGlobalOrganizationOperationResponse,t,n)},"name",{value:"Delete"}),Object.defineProperty(ne.prototype.get=function e(t,n){return this.rpcCall(e,u.google.cloud.compute.v1.GetGlobalOrganizationOperationRequest,u.google.cloud.compute.v1.Operation,t,n)},"name",{value:"Get"}),Object.defineProperty(ne.prototype.list=function e(t,n){return this.rpcCall(e,u.google.cloud.compute.v1.ListGlobalOrganizationOperationsRequest,u.google.cloud.compute.v1.OperationList,t,n)},"name",{value:"List"}),ne),i),n),o),G.api=((t={}).Http=(re.prototype.rules=c.emptyArray,re.prototype.fullyDecodeReservedExpansion=!1,re.create=function(e){return new re(e)},re.encode=function(e,t){if(t=t||a.create(),null!=e.rules&&e.rules.length)for(var n=0;n>>3){case 1:r.rules&&r.rules.length||(r.rules=[]),r.rules.push(u.google.api.HttpRule.decode(e,e.uint32()));break;case 2:r.fullyDecodeReservedExpansion=e.bool();break;default:e.skipType(7&o)}}return r},re.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},re.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.rules&&e.hasOwnProperty("rules")){if(!Array.isArray(e.rules))return"rules: array expected";for(var t=0;t>>3){case 1:r.selector=e.string();break;case 2:r.get=e.string();break;case 3:r.put=e.string();break;case 4:r.post=e.string();break;case 5:r.delete=e.string();break;case 6:r.patch=e.string();break;case 8:r.custom=u.google.api.CustomHttpPattern.decode(e,e.uint32());break;case 7:r.body=e.string();break;case 12:r.responseBody=e.string();break;case 11:r.additionalBindings&&r.additionalBindings.length||(r.additionalBindings=[]),r.additionalBindings.push(u.google.api.HttpRule.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return r},j.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},j.verify=function(e){if("object"!=typeof e||null===e)return"object expected";var t={};if(null!=e.selector&&e.hasOwnProperty("selector")&&!c.isString(e.selector))return"selector: string expected";if(null!=e.get&&e.hasOwnProperty("get")&&(t.pattern=1,!c.isString(e.get)))return"get: string expected";if(null!=e.put&&e.hasOwnProperty("put")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,!c.isString(e.put))return"put: string expected"}if(null!=e.post&&e.hasOwnProperty("post")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,!c.isString(e.post))return"post: string expected"}if(null!=e.delete&&e.hasOwnProperty("delete")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,!c.isString(e.delete))return"delete: string expected"}if(null!=e.patch&&e.hasOwnProperty("patch")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,!c.isString(e.patch))return"patch: string expected"}if(null!=e.custom&&e.hasOwnProperty("custom")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,n=u.google.api.CustomHttpPattern.verify(e.custom))return"custom."+n}if(null!=e.body&&e.hasOwnProperty("body")&&!c.isString(e.body))return"body: string expected";if(null!=e.responseBody&&e.hasOwnProperty("responseBody")&&!c.isString(e.responseBody))return"responseBody: string expected";if(null!=e.additionalBindings&&e.hasOwnProperty("additionalBindings")){if(!Array.isArray(e.additionalBindings))return"additionalBindings: array expected";for(var n,r=0;r>>3){case 1:r.kind=e.string();break;case 2:r.path=e.string();break;default:e.skipType(7&o)}}return r},oe.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},oe.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.kind&&e.hasOwnProperty("kind")&&!c.isString(e.kind)?"kind: string expected":null!=e.path&&e.hasOwnProperty("path")&&!c.isString(e.path)?"path: string expected":null},oe.fromObject=function(e){var t;return e instanceof u.google.api.CustomHttpPattern?e:(t=new u.google.api.CustomHttpPattern,null!=e.kind&&(t.kind=String(e.kind)),null!=e.path&&(t.path=String(e.path)),t)},oe.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.kind="",n.path=""),null!=e.kind&&e.hasOwnProperty("kind")&&(n.kind=e.kind),null!=e.path&&e.hasOwnProperty("path")&&(n.path=e.path),n},oe.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},oe),t),G.protobuf=((i={}).FileDescriptorSet=(ie.prototype.file=c.emptyArray,ie.create=function(e){return new ie(e)},ie.encode=function(e,t){if(t=t||a.create(),null!=e.file&&e.file.length)for(var n=0;n>>3==1?(r.file&&r.file.length||(r.file=[]),r.file.push(u.google.protobuf.FileDescriptorProto.decode(e,e.uint32()))):e.skipType(7&o)}return r},ie.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},ie.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.file&&e.hasOwnProperty("file")){if(!Array.isArray(e.file))return"file: array expected";for(var t=0;t>>3){case 1:r.name=e.string();break;case 2:r.package=e.string();break;case 3:r.dependency&&r.dependency.length||(r.dependency=[]),r.dependency.push(e.string());break;case 10:if(r.publicDependency&&r.publicDependency.length||(r.publicDependency=[]),2==(7&o))for(var i=e.uint32()+e.pos;e.pos>>3){case 1:r.name=e.string();break;case 2:r.field&&r.field.length||(r.field=[]),r.field.push(u.google.protobuf.FieldDescriptorProto.decode(e,e.uint32()));break;case 6:r.extension&&r.extension.length||(r.extension=[]),r.extension.push(u.google.protobuf.FieldDescriptorProto.decode(e,e.uint32()));break;case 3:r.nestedType&&r.nestedType.length||(r.nestedType=[]),r.nestedType.push(u.google.protobuf.DescriptorProto.decode(e,e.uint32()));break;case 4:r.enumType&&r.enumType.length||(r.enumType=[]),r.enumType.push(u.google.protobuf.EnumDescriptorProto.decode(e,e.uint32()));break;case 5:r.extensionRange&&r.extensionRange.length||(r.extensionRange=[]),r.extensionRange.push(u.google.protobuf.DescriptorProto.ExtensionRange.decode(e,e.uint32()));break;case 8:r.oneofDecl&&r.oneofDecl.length||(r.oneofDecl=[]),r.oneofDecl.push(u.google.protobuf.OneofDescriptorProto.decode(e,e.uint32()));break;case 7:r.options=u.google.protobuf.MessageOptions.decode(e,e.uint32());break;case 9:r.reservedRange&&r.reservedRange.length||(r.reservedRange=[]),r.reservedRange.push(u.google.protobuf.DescriptorProto.ReservedRange.decode(e,e.uint32()));break;case 10:r.reservedName&&r.reservedName.length||(r.reservedName=[]),r.reservedName.push(e.string());break;default:e.skipType(7&o)}}return r},k.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},k.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!c.isString(e.name))return"name: string expected";if(null!=e.field&&e.hasOwnProperty("field")){if(!Array.isArray(e.field))return"field: array expected";for(var t=0;t>>3){case 1:r.start=e.int32();break;case 2:r.end=e.int32();break;case 3:r.options=u.google.protobuf.ExtensionRangeOptions.decode(e,e.uint32());break;default:e.skipType(7&o)}}return r},ae.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},ae.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.start&&e.hasOwnProperty("start")&&!c.isInteger(e.start))return"start: integer expected";if(null!=e.end&&e.hasOwnProperty("end")&&!c.isInteger(e.end))return"end: integer expected";if(null!=e.options&&e.hasOwnProperty("options")){e=u.google.protobuf.ExtensionRangeOptions.verify(e.options);if(e)return"options."+e}return null},ae.fromObject=function(e){if(e instanceof u.google.protobuf.DescriptorProto.ExtensionRange)return e;var t=new u.google.protobuf.DescriptorProto.ExtensionRange;if(null!=e.start&&(t.start=0|e.start),null!=e.end&&(t.end=0|e.end),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.protobuf.DescriptorProto.ExtensionRange.options: object expected");t.options=u.google.protobuf.ExtensionRangeOptions.fromObject(e.options)}return t},ae.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.start=0,n.end=0,n.options=null),null!=e.start&&e.hasOwnProperty("start")&&(n.start=e.start),null!=e.end&&e.hasOwnProperty("end")&&(n.end=e.end),null!=e.options&&e.hasOwnProperty("options")&&(n.options=u.google.protobuf.ExtensionRangeOptions.toObject(e.options,t)),n},ae.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},ae),k.ReservedRange=(pe.prototype.start=0,pe.prototype.end=0,pe.create=function(e){return new pe(e)},pe.encode=function(e,t){return t=t||a.create(),null!=e.start&&Object.hasOwnProperty.call(e,"start")&&t.uint32(8).int32(e.start),null!=e.end&&Object.hasOwnProperty.call(e,"end")&&t.uint32(16).int32(e.end),t},pe.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},pe.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new u.google.protobuf.DescriptorProto.ReservedRange;e.pos>>3){case 1:r.start=e.int32();break;case 2:r.end=e.int32();break;default:e.skipType(7&o)}}return r},pe.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},pe.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.start&&e.hasOwnProperty("start")&&!c.isInteger(e.start)?"start: integer expected":null!=e.end&&e.hasOwnProperty("end")&&!c.isInteger(e.end)?"end: integer expected":null},pe.fromObject=function(e){var t;return e instanceof u.google.protobuf.DescriptorProto.ReservedRange?e:(t=new u.google.protobuf.DescriptorProto.ReservedRange,null!=e.start&&(t.start=0|e.start),null!=e.end&&(t.end=0|e.end),t)},pe.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.start=0,n.end=0),null!=e.start&&e.hasOwnProperty("start")&&(n.start=e.start),null!=e.end&&e.hasOwnProperty("end")&&(n.end=e.end),n},pe.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},pe),k),i.ExtensionRangeOptions=(le.prototype.uninterpretedOption=c.emptyArray,le.create=function(e){return new le(e)},le.encode=function(e,t){if(t=t||a.create(),null!=e.uninterpretedOption&&e.uninterpretedOption.length)for(var n=0;n>>3==999?(r.uninterpretedOption&&r.uninterpretedOption.length||(r.uninterpretedOption=[]),r.uninterpretedOption.push(u.google.protobuf.UninterpretedOption.decode(e,e.uint32()))):e.skipType(7&o)}return r},le.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},le.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 1:r.name=e.string();break;case 3:r.number=e.int32();break;case 4:r.label=e.int32();break;case 5:r.type=e.int32();break;case 6:r.typeName=e.string();break;case 2:r.extendee=e.string();break;case 7:r.defaultValue=e.string();break;case 9:r.oneofIndex=e.int32();break;case 10:r.jsonName=e.string();break;case 8:r.options=u.google.protobuf.FieldOptions.decode(e,e.uint32());break;case 17:r.proto3Optional=e.bool();break;default:e.skipType(7&o)}}return r},T.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},T.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!c.isString(e.name))return"name: string expected";if(null!=e.number&&e.hasOwnProperty("number")&&!c.isInteger(e.number))return"number: integer expected";if(null!=e.label&&e.hasOwnProperty("label"))switch(e.label){default:return"label: enum value expected";case 1:case 2:case 3:}if(null!=e.type&&e.hasOwnProperty("type"))switch(e.type){default:return"type: enum value expected";case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:case 11:case 12:case 13:case 14:case 15:case 16:case 17:case 18:}if(null!=e.typeName&&e.hasOwnProperty("typeName")&&!c.isString(e.typeName))return"typeName: string expected";if(null!=e.extendee&&e.hasOwnProperty("extendee")&&!c.isString(e.extendee))return"extendee: string expected";if(null!=e.defaultValue&&e.hasOwnProperty("defaultValue")&&!c.isString(e.defaultValue))return"defaultValue: string expected";if(null!=e.oneofIndex&&e.hasOwnProperty("oneofIndex")&&!c.isInteger(e.oneofIndex))return"oneofIndex: integer expected";if(null!=e.jsonName&&e.hasOwnProperty("jsonName")&&!c.isString(e.jsonName))return"jsonName: string expected";if(null!=e.options&&e.hasOwnProperty("options")){var t=u.google.protobuf.FieldOptions.verify(e.options);if(t)return"options."+t}return null!=e.proto3Optional&&e.hasOwnProperty("proto3Optional")&&"boolean"!=typeof e.proto3Optional?"proto3Optional: boolean expected":null},T.fromObject=function(e){if(e instanceof u.google.protobuf.FieldDescriptorProto)return e;var t=new u.google.protobuf.FieldDescriptorProto;switch(null!=e.name&&(t.name=String(e.name)),null!=e.number&&(t.number=0|e.number),e.label){case"LABEL_OPTIONAL":case 1:t.label=1;break;case"LABEL_REQUIRED":case 2:t.label=2;break;case"LABEL_REPEATED":case 3:t.label=3}switch(e.type){case"TYPE_DOUBLE":case 1:t.type=1;break;case"TYPE_FLOAT":case 2:t.type=2;break;case"TYPE_INT64":case 3:t.type=3;break;case"TYPE_UINT64":case 4:t.type=4;break;case"TYPE_INT32":case 5:t.type=5;break;case"TYPE_FIXED64":case 6:t.type=6;break;case"TYPE_FIXED32":case 7:t.type=7;break;case"TYPE_BOOL":case 8:t.type=8;break;case"TYPE_STRING":case 9:t.type=9;break;case"TYPE_GROUP":case 10:t.type=10;break;case"TYPE_MESSAGE":case 11:t.type=11;break;case"TYPE_BYTES":case 12:t.type=12;break;case"TYPE_UINT32":case 13:t.type=13;break;case"TYPE_ENUM":case 14:t.type=14;break;case"TYPE_SFIXED32":case 15:t.type=15;break;case"TYPE_SFIXED64":case 16:t.type=16;break;case"TYPE_SINT32":case 17:t.type=17;break;case"TYPE_SINT64":case 18:t.type=18}if(null!=e.typeName&&(t.typeName=String(e.typeName)),null!=e.extendee&&(t.extendee=String(e.extendee)),null!=e.defaultValue&&(t.defaultValue=String(e.defaultValue)),null!=e.oneofIndex&&(t.oneofIndex=0|e.oneofIndex),null!=e.jsonName&&(t.jsonName=String(e.jsonName)),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.protobuf.FieldDescriptorProto.options: object expected");t.options=u.google.protobuf.FieldOptions.fromObject(e.options)}return null!=e.proto3Optional&&(t.proto3Optional=Boolean(e.proto3Optional)),t},T.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name="",n.extendee="",n.number=0,n.label=t.enums===String?"LABEL_OPTIONAL":1,n.type=t.enums===String?"TYPE_DOUBLE":1,n.typeName="",n.defaultValue="",n.options=null,n.oneofIndex=0,n.jsonName="",n.proto3Optional=!1),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.extendee&&e.hasOwnProperty("extendee")&&(n.extendee=e.extendee),null!=e.number&&e.hasOwnProperty("number")&&(n.number=e.number),null!=e.label&&e.hasOwnProperty("label")&&(n.label=t.enums===String?u.google.protobuf.FieldDescriptorProto.Label[e.label]:e.label),null!=e.type&&e.hasOwnProperty("type")&&(n.type=t.enums===String?u.google.protobuf.FieldDescriptorProto.Type[e.type]:e.type),null!=e.typeName&&e.hasOwnProperty("typeName")&&(n.typeName=e.typeName),null!=e.defaultValue&&e.hasOwnProperty("defaultValue")&&(n.defaultValue=e.defaultValue),null!=e.options&&e.hasOwnProperty("options")&&(n.options=u.google.protobuf.FieldOptions.toObject(e.options,t)),null!=e.oneofIndex&&e.hasOwnProperty("oneofIndex")&&(n.oneofIndex=e.oneofIndex),null!=e.jsonName&&e.hasOwnProperty("jsonName")&&(n.jsonName=e.jsonName),null!=e.proto3Optional&&e.hasOwnProperty("proto3Optional")&&(n.proto3Optional=e.proto3Optional),n},T.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},T.Type=(n={},(o=Object.create(n))[n[1]="TYPE_DOUBLE"]=1,o[n[2]="TYPE_FLOAT"]=2,o[n[3]="TYPE_INT64"]=3,o[n[4]="TYPE_UINT64"]=4,o[n[5]="TYPE_INT32"]=5,o[n[6]="TYPE_FIXED64"]=6,o[n[7]="TYPE_FIXED32"]=7,o[n[8]="TYPE_BOOL"]=8,o[n[9]="TYPE_STRING"]=9,o[n[10]="TYPE_GROUP"]=10,o[n[11]="TYPE_MESSAGE"]=11,o[n[12]="TYPE_BYTES"]=12,o[n[13]="TYPE_UINT32"]=13,o[n[14]="TYPE_ENUM"]=14,o[n[15]="TYPE_SFIXED32"]=15,o[n[16]="TYPE_SFIXED64"]=16,o[n[17]="TYPE_SINT32"]=17,o[n[18]="TYPE_SINT64"]=18,o),T.Label=(n={},(o=Object.create(n))[n[1]="LABEL_OPTIONAL"]=1,o[n[2]="LABEL_REQUIRED"]=2,o[n[3]="LABEL_REPEATED"]=3,o),T),i.OneofDescriptorProto=(se.prototype.name="",se.prototype.options=null,se.create=function(e){return new se(e)},se.encode=function(e,t){return t=t||a.create(),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(10).string(e.name),null!=e.options&&Object.hasOwnProperty.call(e,"options")&&u.google.protobuf.OneofOptions.encode(e.options,t.uint32(18).fork()).ldelim(),t},se.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},se.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new u.google.protobuf.OneofDescriptorProto;e.pos>>3){case 1:r.name=e.string();break;case 2:r.options=u.google.protobuf.OneofOptions.decode(e,e.uint32());break;default:e.skipType(7&o)}}return r},se.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},se.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!c.isString(e.name))return"name: string expected";if(null!=e.options&&e.hasOwnProperty("options")){e=u.google.protobuf.OneofOptions.verify(e.options);if(e)return"options."+e}return null},se.fromObject=function(e){if(e instanceof u.google.protobuf.OneofDescriptorProto)return e;var t=new u.google.protobuf.OneofDescriptorProto;if(null!=e.name&&(t.name=String(e.name)),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.protobuf.OneofDescriptorProto.options: object expected");t.options=u.google.protobuf.OneofOptions.fromObject(e.options)}return t},se.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name="",n.options=null),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.options&&e.hasOwnProperty("options")&&(n.options=u.google.protobuf.OneofOptions.toObject(e.options,t)),n},se.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},se),i.EnumDescriptorProto=(x.prototype.name="",x.prototype.value=c.emptyArray,x.prototype.options=null,x.prototype.reservedRange=c.emptyArray,x.prototype.reservedName=c.emptyArray,x.create=function(e){return new x(e)},x.encode=function(e,t){if(t=t||a.create(),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(10).string(e.name),null!=e.value&&e.value.length)for(var n=0;n>>3){case 1:r.name=e.string();break;case 2:r.value&&r.value.length||(r.value=[]),r.value.push(u.google.protobuf.EnumValueDescriptorProto.decode(e,e.uint32()));break;case 3:r.options=u.google.protobuf.EnumOptions.decode(e,e.uint32());break;case 4:r.reservedRange&&r.reservedRange.length||(r.reservedRange=[]),r.reservedRange.push(u.google.protobuf.EnumDescriptorProto.EnumReservedRange.decode(e,e.uint32()));break;case 5:r.reservedName&&r.reservedName.length||(r.reservedName=[]),r.reservedName.push(e.string());break;default:e.skipType(7&o)}}return r},x.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},x.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!c.isString(e.name))return"name: string expected";if(null!=e.value&&e.hasOwnProperty("value")){if(!Array.isArray(e.value))return"value: array expected";for(var t=0;t>>3){case 1:r.start=e.int32();break;case 2:r.end=e.int32();break;default:e.skipType(7&o)}}return r},ce.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},ce.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.start&&e.hasOwnProperty("start")&&!c.isInteger(e.start)?"start: integer expected":null!=e.end&&e.hasOwnProperty("end")&&!c.isInteger(e.end)?"end: integer expected":null},ce.fromObject=function(e){var t;return e instanceof u.google.protobuf.EnumDescriptorProto.EnumReservedRange?e:(t=new u.google.protobuf.EnumDescriptorProto.EnumReservedRange,null!=e.start&&(t.start=0|e.start),null!=e.end&&(t.end=0|e.end),t)},ce.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.start=0,n.end=0),null!=e.start&&e.hasOwnProperty("start")&&(n.start=e.start),null!=e.end&&e.hasOwnProperty("end")&&(n.end=e.end),n},ce.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},ce),x),i.EnumValueDescriptorProto=(ue.prototype.name="",ue.prototype.number=0,ue.prototype.options=null,ue.create=function(e){return new ue(e)},ue.encode=function(e,t){return t=t||a.create(),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(10).string(e.name),null!=e.number&&Object.hasOwnProperty.call(e,"number")&&t.uint32(16).int32(e.number),null!=e.options&&Object.hasOwnProperty.call(e,"options")&&u.google.protobuf.EnumValueOptions.encode(e.options,t.uint32(26).fork()).ldelim(),t},ue.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},ue.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new u.google.protobuf.EnumValueDescriptorProto;e.pos>>3){case 1:r.name=e.string();break;case 2:r.number=e.int32();break;case 3:r.options=u.google.protobuf.EnumValueOptions.decode(e,e.uint32());break;default:e.skipType(7&o)}}return r},ue.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},ue.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!c.isString(e.name))return"name: string expected";if(null!=e.number&&e.hasOwnProperty("number")&&!c.isInteger(e.number))return"number: integer expected";if(null!=e.options&&e.hasOwnProperty("options")){e=u.google.protobuf.EnumValueOptions.verify(e.options);if(e)return"options."+e}return null},ue.fromObject=function(e){if(e instanceof u.google.protobuf.EnumValueDescriptorProto)return e;var t=new u.google.protobuf.EnumValueDescriptorProto;if(null!=e.name&&(t.name=String(e.name)),null!=e.number&&(t.number=0|e.number),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.protobuf.EnumValueDescriptorProto.options: object expected");t.options=u.google.protobuf.EnumValueOptions.fromObject(e.options)}return t},ue.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name="",n.number=0,n.options=null),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.number&&e.hasOwnProperty("number")&&(n.number=e.number),null!=e.options&&e.hasOwnProperty("options")&&(n.options=u.google.protobuf.EnumValueOptions.toObject(e.options,t)),n},ue.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},ue),i.ServiceDescriptorProto=(de.prototype.name="",de.prototype.method=c.emptyArray,de.prototype.options=null,de.create=function(e){return new de(e)},de.encode=function(e,t){if(t=t||a.create(),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(10).string(e.name),null!=e.method&&e.method.length)for(var n=0;n>>3){case 1:r.name=e.string();break;case 2:r.method&&r.method.length||(r.method=[]),r.method.push(u.google.protobuf.MethodDescriptorProto.decode(e,e.uint32()));break;case 3:r.options=u.google.protobuf.ServiceOptions.decode(e,e.uint32());break;default:e.skipType(7&o)}}return r},de.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},de.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!c.isString(e.name))return"name: string expected";if(null!=e.method&&e.hasOwnProperty("method")){if(!Array.isArray(e.method))return"method: array expected";for(var t=0;t>>3){case 1:r.name=e.string();break;case 2:r.inputType=e.string();break;case 3:r.outputType=e.string();break;case 4:r.options=u.google.protobuf.MethodOptions.decode(e,e.uint32());break;case 5:r.clientStreaming=e.bool();break;case 6:r.serverStreaming=e.bool();break;default:e.skipType(7&o)}}return r},E.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},E.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!c.isString(e.name))return"name: string expected";if(null!=e.inputType&&e.hasOwnProperty("inputType")&&!c.isString(e.inputType))return"inputType: string expected";if(null!=e.outputType&&e.hasOwnProperty("outputType")&&!c.isString(e.outputType))return"outputType: string expected";if(null!=e.options&&e.hasOwnProperty("options")){var t=u.google.protobuf.MethodOptions.verify(e.options);if(t)return"options."+t}return null!=e.clientStreaming&&e.hasOwnProperty("clientStreaming")&&"boolean"!=typeof e.clientStreaming?"clientStreaming: boolean expected":null!=e.serverStreaming&&e.hasOwnProperty("serverStreaming")&&"boolean"!=typeof e.serverStreaming?"serverStreaming: boolean expected":null},E.fromObject=function(e){if(e instanceof u.google.protobuf.MethodDescriptorProto)return e;var t=new u.google.protobuf.MethodDescriptorProto;if(null!=e.name&&(t.name=String(e.name)),null!=e.inputType&&(t.inputType=String(e.inputType)),null!=e.outputType&&(t.outputType=String(e.outputType)),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.protobuf.MethodDescriptorProto.options: object expected");t.options=u.google.protobuf.MethodOptions.fromObject(e.options)}return null!=e.clientStreaming&&(t.clientStreaming=Boolean(e.clientStreaming)),null!=e.serverStreaming&&(t.serverStreaming=Boolean(e.serverStreaming)),t},E.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name="",n.inputType="",n.outputType="",n.options=null,n.clientStreaming=!1,n.serverStreaming=!1),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.inputType&&e.hasOwnProperty("inputType")&&(n.inputType=e.inputType),null!=e.outputType&&e.hasOwnProperty("outputType")&&(n.outputType=e.outputType),null!=e.options&&e.hasOwnProperty("options")&&(n.options=u.google.protobuf.MethodOptions.toObject(e.options,t)),null!=e.clientStreaming&&e.hasOwnProperty("clientStreaming")&&(n.clientStreaming=e.clientStreaming),null!=e.serverStreaming&&e.hasOwnProperty("serverStreaming")&&(n.serverStreaming=e.serverStreaming),n},E.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},E),i.FileOptions=(D.prototype.javaPackage="",D.prototype.javaOuterClassname="",D.prototype.javaMultipleFiles=!1,D.prototype.javaGenerateEqualsAndHash=!1,D.prototype.javaStringCheckUtf8=!1,D.prototype.optimizeFor=1,D.prototype.goPackage="",D.prototype.ccGenericServices=!1,D.prototype.javaGenericServices=!1,D.prototype.pyGenericServices=!1,D.prototype.phpGenericServices=!1,D.prototype.deprecated=!1,D.prototype.ccEnableArenas=!0,D.prototype.objcClassPrefix="",D.prototype.csharpNamespace="",D.prototype.swiftPrefix="",D.prototype.phpClassPrefix="",D.prototype.phpNamespace="",D.prototype.phpMetadataNamespace="",D.prototype.rubyPackage="",D.prototype.uninterpretedOption=c.emptyArray,D.create=function(e){return new D(e)},D.encode=function(e,t){if(t=t||a.create(),null!=e.javaPackage&&Object.hasOwnProperty.call(e,"javaPackage")&&t.uint32(10).string(e.javaPackage),null!=e.javaOuterClassname&&Object.hasOwnProperty.call(e,"javaOuterClassname")&&t.uint32(66).string(e.javaOuterClassname),null!=e.optimizeFor&&Object.hasOwnProperty.call(e,"optimizeFor")&&t.uint32(72).int32(e.optimizeFor),null!=e.javaMultipleFiles&&Object.hasOwnProperty.call(e,"javaMultipleFiles")&&t.uint32(80).bool(e.javaMultipleFiles),null!=e.goPackage&&Object.hasOwnProperty.call(e,"goPackage")&&t.uint32(90).string(e.goPackage),null!=e.ccGenericServices&&Object.hasOwnProperty.call(e,"ccGenericServices")&&t.uint32(128).bool(e.ccGenericServices),null!=e.javaGenericServices&&Object.hasOwnProperty.call(e,"javaGenericServices")&&t.uint32(136).bool(e.javaGenericServices),null!=e.pyGenericServices&&Object.hasOwnProperty.call(e,"pyGenericServices")&&t.uint32(144).bool(e.pyGenericServices),null!=e.javaGenerateEqualsAndHash&&Object.hasOwnProperty.call(e,"javaGenerateEqualsAndHash")&&t.uint32(160).bool(e.javaGenerateEqualsAndHash),null!=e.deprecated&&Object.hasOwnProperty.call(e,"deprecated")&&t.uint32(184).bool(e.deprecated),null!=e.javaStringCheckUtf8&&Object.hasOwnProperty.call(e,"javaStringCheckUtf8")&&t.uint32(216).bool(e.javaStringCheckUtf8),null!=e.ccEnableArenas&&Object.hasOwnProperty.call(e,"ccEnableArenas")&&t.uint32(248).bool(e.ccEnableArenas),null!=e.objcClassPrefix&&Object.hasOwnProperty.call(e,"objcClassPrefix")&&t.uint32(290).string(e.objcClassPrefix),null!=e.csharpNamespace&&Object.hasOwnProperty.call(e,"csharpNamespace")&&t.uint32(298).string(e.csharpNamespace),null!=e.swiftPrefix&&Object.hasOwnProperty.call(e,"swiftPrefix")&&t.uint32(314).string(e.swiftPrefix),null!=e.phpClassPrefix&&Object.hasOwnProperty.call(e,"phpClassPrefix")&&t.uint32(322).string(e.phpClassPrefix),null!=e.phpNamespace&&Object.hasOwnProperty.call(e,"phpNamespace")&&t.uint32(330).string(e.phpNamespace),null!=e.phpGenericServices&&Object.hasOwnProperty.call(e,"phpGenericServices")&&t.uint32(336).bool(e.phpGenericServices),null!=e.phpMetadataNamespace&&Object.hasOwnProperty.call(e,"phpMetadataNamespace")&&t.uint32(354).string(e.phpMetadataNamespace),null!=e.rubyPackage&&Object.hasOwnProperty.call(e,"rubyPackage")&&t.uint32(362).string(e.rubyPackage),null!=e.uninterpretedOption&&e.uninterpretedOption.length)for(var n=0;n>>3){case 1:r.javaPackage=e.string();break;case 8:r.javaOuterClassname=e.string();break;case 10:r.javaMultipleFiles=e.bool();break;case 20:r.javaGenerateEqualsAndHash=e.bool();break;case 27:r.javaStringCheckUtf8=e.bool();break;case 9:r.optimizeFor=e.int32();break;case 11:r.goPackage=e.string();break;case 16:r.ccGenericServices=e.bool();break;case 17:r.javaGenericServices=e.bool();break;case 18:r.pyGenericServices=e.bool();break;case 42:r.phpGenericServices=e.bool();break;case 23:r.deprecated=e.bool();break;case 31:r.ccEnableArenas=e.bool();break;case 36:r.objcClassPrefix=e.string();break;case 37:r.csharpNamespace=e.string();break;case 39:r.swiftPrefix=e.string();break;case 40:r.phpClassPrefix=e.string();break;case 41:r.phpNamespace=e.string();break;case 44:r.phpMetadataNamespace=e.string();break;case 45:r.rubyPackage=e.string();break;case 999:r.uninterpretedOption&&r.uninterpretedOption.length||(r.uninterpretedOption=[]),r.uninterpretedOption.push(u.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return r},D.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},D.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.javaPackage&&e.hasOwnProperty("javaPackage")&&!c.isString(e.javaPackage))return"javaPackage: string expected";if(null!=e.javaOuterClassname&&e.hasOwnProperty("javaOuterClassname")&&!c.isString(e.javaOuterClassname))return"javaOuterClassname: string expected";if(null!=e.javaMultipleFiles&&e.hasOwnProperty("javaMultipleFiles")&&"boolean"!=typeof e.javaMultipleFiles)return"javaMultipleFiles: boolean expected";if(null!=e.javaGenerateEqualsAndHash&&e.hasOwnProperty("javaGenerateEqualsAndHash")&&"boolean"!=typeof e.javaGenerateEqualsAndHash)return"javaGenerateEqualsAndHash: boolean expected";if(null!=e.javaStringCheckUtf8&&e.hasOwnProperty("javaStringCheckUtf8")&&"boolean"!=typeof e.javaStringCheckUtf8)return"javaStringCheckUtf8: boolean expected";if(null!=e.optimizeFor&&e.hasOwnProperty("optimizeFor"))switch(e.optimizeFor){default:return"optimizeFor: enum value expected";case 1:case 2:case 3:}if(null!=e.goPackage&&e.hasOwnProperty("goPackage")&&!c.isString(e.goPackage))return"goPackage: string expected";if(null!=e.ccGenericServices&&e.hasOwnProperty("ccGenericServices")&&"boolean"!=typeof e.ccGenericServices)return"ccGenericServices: boolean expected";if(null!=e.javaGenericServices&&e.hasOwnProperty("javaGenericServices")&&"boolean"!=typeof e.javaGenericServices)return"javaGenericServices: boolean expected";if(null!=e.pyGenericServices&&e.hasOwnProperty("pyGenericServices")&&"boolean"!=typeof e.pyGenericServices)return"pyGenericServices: boolean expected";if(null!=e.phpGenericServices&&e.hasOwnProperty("phpGenericServices")&&"boolean"!=typeof e.phpGenericServices)return"phpGenericServices: boolean expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.ccEnableArenas&&e.hasOwnProperty("ccEnableArenas")&&"boolean"!=typeof e.ccEnableArenas)return"ccEnableArenas: boolean expected";if(null!=e.objcClassPrefix&&e.hasOwnProperty("objcClassPrefix")&&!c.isString(e.objcClassPrefix))return"objcClassPrefix: string expected";if(null!=e.csharpNamespace&&e.hasOwnProperty("csharpNamespace")&&!c.isString(e.csharpNamespace))return"csharpNamespace: string expected";if(null!=e.swiftPrefix&&e.hasOwnProperty("swiftPrefix")&&!c.isString(e.swiftPrefix))return"swiftPrefix: string expected";if(null!=e.phpClassPrefix&&e.hasOwnProperty("phpClassPrefix")&&!c.isString(e.phpClassPrefix))return"phpClassPrefix: string expected";if(null!=e.phpNamespace&&e.hasOwnProperty("phpNamespace")&&!c.isString(e.phpNamespace))return"phpNamespace: string expected";if(null!=e.phpMetadataNamespace&&e.hasOwnProperty("phpMetadataNamespace")&&!c.isString(e.phpMetadataNamespace))return"phpMetadataNamespace: string expected";if(null!=e.rubyPackage&&e.hasOwnProperty("rubyPackage")&&!c.isString(e.rubyPackage))return"rubyPackage: string expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 1:r.messageSetWireFormat=e.bool();break;case 2:r.noStandardDescriptorAccessor=e.bool();break;case 3:r.deprecated=e.bool();break;case 7:r.mapEntry=e.bool();break;case 999:r.uninterpretedOption&&r.uninterpretedOption.length||(r.uninterpretedOption=[]),r.uninterpretedOption.push(u.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return r},R.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},R.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.messageSetWireFormat&&e.hasOwnProperty("messageSetWireFormat")&&"boolean"!=typeof e.messageSetWireFormat)return"messageSetWireFormat: boolean expected";if(null!=e.noStandardDescriptorAccessor&&e.hasOwnProperty("noStandardDescriptorAccessor")&&"boolean"!=typeof e.noStandardDescriptorAccessor)return"noStandardDescriptorAccessor: boolean expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.mapEntry&&e.hasOwnProperty("mapEntry")&&"boolean"!=typeof e.mapEntry)return"mapEntry: boolean expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 1:r.ctype=e.int32();break;case 2:r.packed=e.bool();break;case 6:r.jstype=e.int32();break;case 5:r.lazy=e.bool();break;case 3:r.deprecated=e.bool();break;case 10:r.weak=e.bool();break;case 999:r.uninterpretedOption&&r.uninterpretedOption.length||(r.uninterpretedOption=[]),r.uninterpretedOption.push(u.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return r},N.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},N.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.ctype&&e.hasOwnProperty("ctype"))switch(e.ctype){default:return"ctype: enum value expected";case 0:case 1:case 2:}if(null!=e.packed&&e.hasOwnProperty("packed")&&"boolean"!=typeof e.packed)return"packed: boolean expected";if(null!=e.jstype&&e.hasOwnProperty("jstype"))switch(e.jstype){default:return"jstype: enum value expected";case 0:case 1:case 2:}if(null!=e.lazy&&e.hasOwnProperty("lazy")&&"boolean"!=typeof e.lazy)return"lazy: boolean expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.weak&&e.hasOwnProperty("weak")&&"boolean"!=typeof e.weak)return"weak: boolean expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3==999?(r.uninterpretedOption&&r.uninterpretedOption.length||(r.uninterpretedOption=[]),r.uninterpretedOption.push(u.google.protobuf.UninterpretedOption.decode(e,e.uint32()))):e.skipType(7&o)}return r},ge.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},ge.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 2:r.allowAlias=e.bool();break;case 3:r.deprecated=e.bool();break;case 999:r.uninterpretedOption&&r.uninterpretedOption.length||(r.uninterpretedOption=[]),r.uninterpretedOption.push(u.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return r},fe.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},fe.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.allowAlias&&e.hasOwnProperty("allowAlias")&&"boolean"!=typeof e.allowAlias)return"allowAlias: boolean expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 1:r.deprecated=e.bool();break;case 999:r.uninterpretedOption&&r.uninterpretedOption.length||(r.uninterpretedOption=[]),r.uninterpretedOption.push(u.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return r},ye.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},ye.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 33:r.deprecated=e.bool();break;case 999:r.uninterpretedOption&&r.uninterpretedOption.length||(r.uninterpretedOption=[]),r.uninterpretedOption.push(u.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return r},Oe.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},Oe.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 33:r.deprecated=e.bool();break;case 34:r.idempotencyLevel=e.int32();break;case 999:r.uninterpretedOption&&r.uninterpretedOption.length||(r.uninterpretedOption=[]),r.uninterpretedOption.push(u.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;case 72295728:r[".google.api.http"]=u.google.api.HttpRule.decode(e,e.uint32());break;default:e.skipType(7&o)}}return r},A.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},A.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.idempotencyLevel&&e.hasOwnProperty("idempotencyLevel"))switch(e.idempotencyLevel){default:return"idempotencyLevel: enum value expected";case 0:case 1:case 2:}if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 2:r.name&&r.name.length||(r.name=[]),r.name.push(u.google.protobuf.UninterpretedOption.NamePart.decode(e,e.uint32()));break;case 3:r.identifierValue=e.string();break;case 4:r.positiveIntValue=e.uint64();break;case 5:r.negativeIntValue=e.int64();break;case 6:r.doubleValue=e.double();break;case 7:r.stringValue=e.bytes();break;case 8:r.aggregateValue=e.string();break;default:e.skipType(7&o)}}return r},_.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},_.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")){if(!Array.isArray(e.name))return"name: array expected";for(var t=0;t>>0,e.positiveIntValue.high>>>0).toNumber(!0))),null!=e.negativeIntValue&&(c.Long?(t.negativeIntValue=c.Long.fromValue(e.negativeIntValue)).unsigned=!1:"string"==typeof e.negativeIntValue?t.negativeIntValue=parseInt(e.negativeIntValue,10):"number"==typeof e.negativeIntValue?t.negativeIntValue=e.negativeIntValue:"object"==typeof e.negativeIntValue&&(t.negativeIntValue=new c.LongBits(e.negativeIntValue.low>>>0,e.negativeIntValue.high>>>0).toNumber())),null!=e.doubleValue&&(t.doubleValue=Number(e.doubleValue)),null!=e.stringValue&&("string"==typeof e.stringValue?c.base64.decode(e.stringValue,t.stringValue=c.newBuffer(c.base64.length(e.stringValue)),0):e.stringValue.length&&(t.stringValue=e.stringValue)),null!=e.aggregateValue&&(t.aggregateValue=String(e.aggregateValue)),t},_.toObject=function(e,t){var n,r={};if(((t=t||{}).arrays||t.defaults)&&(r.name=[]),t.defaults&&(r.identifierValue="",c.Long?(n=new c.Long(0,0,!0),r.positiveIntValue=t.longs===String?n.toString():t.longs===Number?n.toNumber():n):r.positiveIntValue=t.longs===String?"0":0,c.Long?(n=new c.Long(0,0,!1),r.negativeIntValue=t.longs===String?n.toString():t.longs===Number?n.toNumber():n):r.negativeIntValue=t.longs===String?"0":0,r.doubleValue=0,t.bytes===String?r.stringValue="":(r.stringValue=[],t.bytes!==Array&&(r.stringValue=c.newBuffer(r.stringValue))),r.aggregateValue=""),e.name&&e.name.length){r.name=[];for(var o=0;o>>0,e.positiveIntValue.high>>>0).toNumber(!0):e.positiveIntValue),null!=e.negativeIntValue&&e.hasOwnProperty("negativeIntValue")&&("number"==typeof e.negativeIntValue?r.negativeIntValue=t.longs===String?String(e.negativeIntValue):e.negativeIntValue:r.negativeIntValue=t.longs===String?c.Long.prototype.toString.call(e.negativeIntValue):t.longs===Number?new c.LongBits(e.negativeIntValue.low>>>0,e.negativeIntValue.high>>>0).toNumber():e.negativeIntValue),null!=e.doubleValue&&e.hasOwnProperty("doubleValue")&&(r.doubleValue=t.json&&!isFinite(e.doubleValue)?String(e.doubleValue):e.doubleValue),null!=e.stringValue&&e.hasOwnProperty("stringValue")&&(r.stringValue=t.bytes===String?c.base64.encode(e.stringValue,0,e.stringValue.length):t.bytes===Array?Array.prototype.slice.call(e.stringValue):e.stringValue),null!=e.aggregateValue&&e.hasOwnProperty("aggregateValue")&&(r.aggregateValue=e.aggregateValue),r},_.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},_.NamePart=(he.prototype.namePart="",he.prototype.isExtension=!1,he.create=function(e){return new he(e)},he.encode=function(e,t){return(t=t||a.create()).uint32(10).string(e.namePart),t.uint32(16).bool(e.isExtension),t},he.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},he.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new u.google.protobuf.UninterpretedOption.NamePart;e.pos>>3){case 1:r.namePart=e.string();break;case 2:r.isExtension=e.bool();break;default:e.skipType(7&o)}}if(!r.hasOwnProperty("namePart"))throw c.ProtocolError("missing required 'namePart'",{instance:r});if(r.hasOwnProperty("isExtension"))return r;throw c.ProtocolError("missing required 'isExtension'",{instance:r})},he.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},he.verify=function(e){return"object"!=typeof e||null===e?"object expected":c.isString(e.namePart)?"boolean"!=typeof e.isExtension?"isExtension: boolean expected":null:"namePart: string expected"},he.fromObject=function(e){var t;return e instanceof u.google.protobuf.UninterpretedOption.NamePart?e:(t=new u.google.protobuf.UninterpretedOption.NamePart,null!=e.namePart&&(t.namePart=String(e.namePart)),null!=e.isExtension&&(t.isExtension=Boolean(e.isExtension)),t)},he.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.namePart="",n.isExtension=!1),null!=e.namePart&&e.hasOwnProperty("namePart")&&(n.namePart=e.namePart),null!=e.isExtension&&e.hasOwnProperty("isExtension")&&(n.isExtension=e.isExtension),n},he.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},he),_),i.SourceCodeInfo=(be.prototype.location=c.emptyArray,be.create=function(e){return new be(e)},be.encode=function(e,t){if(t=t||a.create(),null!=e.location&&e.location.length)for(var n=0;n>>3==1?(r.location&&r.location.length||(r.location=[]),r.location.push(u.google.protobuf.SourceCodeInfo.Location.decode(e,e.uint32()))):e.skipType(7&o)}return r},be.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},be.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.location&&e.hasOwnProperty("location")){if(!Array.isArray(e.location))return"location: array expected";for(var t=0;t>>3){case 1:if(r.path&&r.path.length||(r.path=[]),2==(7&o))for(var i=e.uint32()+e.pos;e.pos>>3==1?(r.annotation&&r.annotation.length||(r.annotation=[]),r.annotation.push(u.google.protobuf.GeneratedCodeInfo.Annotation.decode(e,e.uint32()))):e.skipType(7&o)}return r},me.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},me.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.annotation&&e.hasOwnProperty("annotation")){if(!Array.isArray(e.annotation))return"annotation: array expected";for(var t=0;t>>3){case 1:if(r.path&&r.path.length||(r.path=[]),2==(7&o))for(var i=e.uint32()+e.pos;e.pos/locations/global/keys/`. + // For example: + // `projects/123456867718/locations/global/keys/b7ff1f9f-8275-410a-94dd-3855ee9b5dd2` + // + // NOTE: Key is a global resource; hence the only supported value for + // location is `global`. + string name = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Unique id in UUID4 format. + string uid = 5 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Human-readable display name of this key that you can modify. + // The maximum length is 63 characters. + string display_name = 2; + + // Output only. An encrypted and signed value held by this key. + // This field can be accessed only through the `GetKeyString` method. + string key_string = 3 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. A timestamp identifying the time this key was originally + // created. + google.protobuf.Timestamp create_time = 4 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. A timestamp identifying the time this key was last + // updated. + google.protobuf.Timestamp update_time = 6 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. A timestamp when this key was deleted. If the resource is not + // deleted, this must be empty. + google.protobuf.Timestamp delete_time = 7 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Annotations is an unstructured key-value map stored with a policy that + // may be set by external tools to store and retrieve arbitrary metadata. + // They are not queryable and should be preserved when modifying objects. + map annotations = 8; + + // Key restrictions. + Restrictions restrictions = 9; + + // Output only. A checksum computed by the server based on the current value + // of the Key resource. This may be sent on update and delete requests to + // ensure the client has an up-to-date value before proceeding. See + // https://google.aip.dev/154. + string etag = 11 [(google.api.field_behavior) = OUTPUT_ONLY]; +} + +// Describes the restrictions on the key. +message Restrictions { + // The websites, IP addresses, Android apps, or iOS apps (the clients) that + // are allowed to use the key. You can specify only one type of client + // restrictions per key. + oneof client_restrictions { + // The HTTP referrers (websites) that are allowed to use the key. + BrowserKeyRestrictions browser_key_restrictions = 1; + + // The IP addresses of callers that are allowed to use the key. + ServerKeyRestrictions server_key_restrictions = 2; + + // The Android apps that are allowed to use the key. + AndroidKeyRestrictions android_key_restrictions = 3; + + // The iOS apps that are allowed to use the key. + IosKeyRestrictions ios_key_restrictions = 4; + } + + // A restriction for a specific service and optionally one or + // more specific methods. Requests are allowed if they + // match any of these restrictions. If no restrictions are + // specified, all targets are allowed. + repeated ApiTarget api_targets = 5; +} + +// The HTTP referrers (websites) that are allowed to use the key. +message BrowserKeyRestrictions { + // A list of regular expressions for the referrer URLs that are allowed + // to make API calls with this key. + repeated string allowed_referrers = 1; +} + +// The IP addresses of callers that are allowed to use the key. +message ServerKeyRestrictions { + // A list of the caller IP addresses that are allowed to make API calls + // with this key. + repeated string allowed_ips = 1; +} + +// The Android apps that are allowed to use the key. +message AndroidKeyRestrictions { + // A list of Android applications that are allowed to make API calls with + // this key. + repeated AndroidApplication allowed_applications = 1; +} + +// Identifier of an Android application for key use. +message AndroidApplication { + // The SHA1 fingerprint of the application. For example, both sha1 formats are + // acceptable : DA:39:A3:EE:5E:6B:4B:0D:32:55:BF:EF:95:60:18:90:AF:D8:07:09 or + // DA39A3EE5E6B4B0D3255BFEF95601890AFD80709. + // Output format is the latter. + string sha1_fingerprint = 1; + + // The package name of the application. + string package_name = 2; +} + +// The iOS apps that are allowed to use the key. +message IosKeyRestrictions { + // A list of bundle IDs that are allowed when making API calls with this key. + repeated string allowed_bundle_ids = 1; +} + +// A restriction for a specific service and optionally one or multiple +// specific methods. Both fields are case insensitive. +message ApiTarget { + // The service for this restriction. It should be the canonical + // service name, for example: `translate.googleapis.com`. + // You can use [`gcloud services list`](/sdk/gcloud/reference/services/list) + // to get a list of services that are enabled in the project. + string service = 1; + + // Optional. List of one or more methods that can be called. + // If empty, all methods for the service are allowed. A wildcard + // (*) can be used as the last symbol. + // Valid examples: + // `google.cloud.translate.v2.TranslateService.GetSupportedLanguage` + // `TranslateText` + // `Get*` + // `translate.googleapis.com.Get*` + repeated string methods = 2 [(google.api.field_behavior) = OPTIONAL]; +} diff --git a/node_modules/google-gax/build/protos/google/api/auth.proto b/node_modules/google-gax/build/protos/google/api/auth.proto new file mode 100644 index 0000000..ca91bb1 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/auth.proto @@ -0,0 +1,237 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option go_package = "google.golang.org/genproto/googleapis/api/serviceconfig;serviceconfig"; +option java_multiple_files = true; +option java_outer_classname = "AuthProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// `Authentication` defines the authentication configuration for API methods +// provided by an API service. +// +// Example: +// +// name: calendar.googleapis.com +// authentication: +// providers: +// - id: google_calendar_auth +// jwks_uri: https://www.googleapis.com/oauth2/v1/certs +// issuer: https://securetoken.google.com +// rules: +// - selector: "*" +// requirements: +// provider_id: google_calendar_auth +// - selector: google.calendar.Delegate +// oauth: +// canonical_scopes: https://www.googleapis.com/auth/calendar.read +message Authentication { + // A list of authentication rules that apply to individual API methods. + // + // **NOTE:** All service configuration rules follow "last one wins" order. + repeated AuthenticationRule rules = 3; + + // Defines a set of authentication providers that a service supports. + repeated AuthProvider providers = 4; +} + +// Authentication rules for the service. +// +// By default, if a method has any authentication requirements, every request +// must include a valid credential matching one of the requirements. +// It's an error to include more than one kind of credential in a single +// request. +// +// If a method doesn't have any auth requirements, request credentials will be +// ignored. +message AuthenticationRule { + // Selects the methods to which this rule applies. + // + // Refer to [selector][google.api.DocumentationRule.selector] for syntax + // details. + string selector = 1; + + // The requirements for OAuth credentials. + OAuthRequirements oauth = 2; + + // If true, the service accepts API keys without any other credential. + // This flag only applies to HTTP and gRPC requests. + bool allow_without_credential = 5; + + // Requirements for additional authentication providers. + repeated AuthRequirement requirements = 7; +} + +// Specifies a location to extract JWT from an API request. +message JwtLocation { + oneof in { + // Specifies HTTP header name to extract JWT token. + string header = 1; + + // Specifies URL query parameter name to extract JWT token. + string query = 2; + + // Specifies cookie name to extract JWT token. + string cookie = 4; + } + + // The value prefix. The value format is "value_prefix{token}" + // Only applies to "in" header type. Must be empty for "in" query type. + // If not empty, the header value has to match (case sensitive) this prefix. + // If not matched, JWT will not be extracted. If matched, JWT will be + // extracted after the prefix is removed. + // + // For example, for "Authorization: Bearer {JWT}", + // value_prefix="Bearer " with a space at the end. + string value_prefix = 3; +} + +// Configuration for an authentication provider, including support for +// [JSON Web Token +// (JWT)](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32). +message AuthProvider { + // The unique identifier of the auth provider. It will be referred to by + // `AuthRequirement.provider_id`. + // + // Example: "bookstore_auth". + string id = 1; + + // Identifies the principal that issued the JWT. See + // https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.1 + // Usually a URL or an email address. + // + // Example: https://securetoken.google.com + // Example: 1234567-compute@developer.gserviceaccount.com + string issuer = 2; + + // URL of the provider's public key set to validate signature of the JWT. See + // [OpenID + // Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata). + // Optional if the key set document: + // - can be retrieved from + // [OpenID + // Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) + // of the issuer. + // - can be inferred from the email domain of the issuer (e.g. a Google + // service account). + // + // Example: https://www.googleapis.com/oauth2/v1/certs + string jwks_uri = 3; + + // The list of JWT + // [audiences](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.3). + // that are allowed to access. A JWT containing any of these audiences will + // be accepted. When this setting is absent, JWTs with audiences: + // - "https://[service.name]/[google.protobuf.Api.name]" + // - "https://[service.name]/" + // will be accepted. + // For example, if no audiences are in the setting, LibraryService API will + // accept JWTs with the following audiences: + // - + // https://library-example.googleapis.com/google.example.library.v1.LibraryService + // - https://library-example.googleapis.com/ + // + // Example: + // + // audiences: bookstore_android.apps.googleusercontent.com, + // bookstore_web.apps.googleusercontent.com + string audiences = 4; + + // Redirect URL if JWT token is required but not present or is expired. + // Implement authorizationUrl of securityDefinitions in OpenAPI spec. + string authorization_url = 5; + + // Defines the locations to extract the JWT. For now it is only used by the + // Cloud Endpoints to store the OpenAPI extension [x-google-jwt-locations] + // (https://cloud.google.com/endpoints/docs/openapi/openapi-extensions#x-google-jwt-locations) + // + // JWT locations can be one of HTTP headers, URL query parameters or + // cookies. The rule is that the first match wins. + // + // If not specified, default to use following 3 locations: + // 1) Authorization: Bearer + // 2) x-goog-iap-jwt-assertion + // 3) access_token query parameter + // + // Default locations can be specified as followings: + // jwt_locations: + // - header: Authorization + // value_prefix: "Bearer " + // - header: x-goog-iap-jwt-assertion + // - query: access_token + repeated JwtLocation jwt_locations = 6; +} + +// OAuth scopes are a way to define data and permissions on data. For example, +// there are scopes defined for "Read-only access to Google Calendar" and +// "Access to Cloud Platform". Users can consent to a scope for an application, +// giving it permission to access that data on their behalf. +// +// OAuth scope specifications should be fairly coarse grained; a user will need +// to see and understand the text description of what your scope means. +// +// In most cases: use one or at most two OAuth scopes for an entire family of +// products. If your product has multiple APIs, you should probably be sharing +// the OAuth scope across all of those APIs. +// +// When you need finer grained OAuth consent screens: talk with your product +// management about how developers will use them in practice. +// +// Please note that even though each of the canonical scopes is enough for a +// request to be accepted and passed to the backend, a request can still fail +// due to the backend requiring additional scopes or permissions. +message OAuthRequirements { + // The list of publicly documented OAuth scopes that are allowed access. An + // OAuth token containing any of these scopes will be accepted. + // + // Example: + // + // canonical_scopes: https://www.googleapis.com/auth/calendar, + // https://www.googleapis.com/auth/calendar.read + string canonical_scopes = 1; +} + +// User-defined authentication requirements, including support for +// [JSON Web Token +// (JWT)](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32). +message AuthRequirement { + // [id][google.api.AuthProvider.id] from authentication provider. + // + // Example: + // + // provider_id: bookstore_auth + string provider_id = 1; + + // NOTE: This will be deprecated soon, once AuthProvider.audiences is + // implemented and accepted in all the runtime components. + // + // The list of JWT + // [audiences](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.3). + // that are allowed to access. A JWT containing any of these audiences will + // be accepted. When this setting is absent, only JWTs with audience + // "https://[Service_name][google.api.Service.name]/[API_name][google.protobuf.Api.name]" + // will be accepted. For example, if no audiences are in the setting, + // LibraryService API will only accept JWTs with the following audience + // "https://library-example.googleapis.com/google.example.library.v1.LibraryService". + // + // Example: + // + // audiences: bookstore_android.apps.googleusercontent.com, + // bookstore_web.apps.googleusercontent.com + string audiences = 2; +} diff --git a/node_modules/google-gax/build/protos/google/api/backend.proto b/node_modules/google-gax/build/protos/google/api/backend.proto new file mode 100644 index 0000000..6ff6887 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/backend.proto @@ -0,0 +1,185 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option go_package = "google.golang.org/genproto/googleapis/api/serviceconfig;serviceconfig"; +option java_multiple_files = true; +option java_outer_classname = "BackendProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// `Backend` defines the backend configuration for a service. +message Backend { + // A list of API backend rules that apply to individual API methods. + // + // **NOTE:** All service configuration rules follow "last one wins" order. + repeated BackendRule rules = 1; +} + +// A backend rule provides configuration for an individual API element. +message BackendRule { + // Path Translation specifies how to combine the backend address with the + // request path in order to produce the appropriate forwarding URL for the + // request. + // + // Path Translation is applicable only to HTTP-based backends. Backends which + // do not accept requests over HTTP/HTTPS should leave `path_translation` + // unspecified. + enum PathTranslation { + PATH_TRANSLATION_UNSPECIFIED = 0; + + // Use the backend address as-is, with no modification to the path. If the + // URL pattern contains variables, the variable names and values will be + // appended to the query string. If a query string parameter and a URL + // pattern variable have the same name, this may result in duplicate keys in + // the query string. + // + // # Examples + // + // Given the following operation config: + // + // Method path: /api/company/{cid}/user/{uid} + // Backend address: https://example.cloudfunctions.net/getUser + // + // Requests to the following request paths will call the backend at the + // translated path: + // + // Request path: /api/company/widgetworks/user/johndoe + // Translated: + // https://example.cloudfunctions.net/getUser?cid=widgetworks&uid=johndoe + // + // Request path: /api/company/widgetworks/user/johndoe?timezone=EST + // Translated: + // https://example.cloudfunctions.net/getUser?timezone=EST&cid=widgetworks&uid=johndoe + CONSTANT_ADDRESS = 1; + + // The request path will be appended to the backend address. + // + // # Examples + // + // Given the following operation config: + // + // Method path: /api/company/{cid}/user/{uid} + // Backend address: https://example.appspot.com + // + // Requests to the following request paths will call the backend at the + // translated path: + // + // Request path: /api/company/widgetworks/user/johndoe + // Translated: + // https://example.appspot.com/api/company/widgetworks/user/johndoe + // + // Request path: /api/company/widgetworks/user/johndoe?timezone=EST + // Translated: + // https://example.appspot.com/api/company/widgetworks/user/johndoe?timezone=EST + APPEND_PATH_TO_ADDRESS = 2; + } + + // Selects the methods to which this rule applies. + // + // Refer to [selector][google.api.DocumentationRule.selector] for syntax + // details. + string selector = 1; + + // The address of the API backend. + // + // The scheme is used to determine the backend protocol and security. + // The following schemes are accepted: + // + // SCHEME PROTOCOL SECURITY + // http:// HTTP None + // https:// HTTP TLS + // grpc:// gRPC None + // grpcs:// gRPC TLS + // + // It is recommended to explicitly include a scheme. Leaving out the scheme + // may cause constrasting behaviors across platforms. + // + // If the port is unspecified, the default is: + // - 80 for schemes without TLS + // - 443 for schemes with TLS + // + // For HTTP backends, use [protocol][google.api.BackendRule.protocol] + // to specify the protocol version. + string address = 2; + + // The number of seconds to wait for a response from a request. The default + // varies based on the request protocol and deployment environment. + double deadline = 3; + + // Deprecated, do not use. + double min_deadline = 4 [deprecated = true]; + + // The number of seconds to wait for the completion of a long running + // operation. The default is no deadline. + double operation_deadline = 5; + + PathTranslation path_translation = 6; + + // Authentication settings used by the backend. + // + // These are typically used to provide service management functionality to + // a backend served on a publicly-routable URL. The `authentication` + // details should match the authentication behavior used by the backend. + // + // For example, specifying `jwt_audience` implies that the backend expects + // authentication via a JWT. + // + // When authentication is unspecified, the resulting behavior is the same + // as `disable_auth` set to `true`. + // + // Refer to https://developers.google.com/identity/protocols/OpenIDConnect for + // JWT ID token. + oneof authentication { + // The JWT audience is used when generating a JWT ID token for the backend. + // This ID token will be added in the HTTP "authorization" header, and sent + // to the backend. + string jwt_audience = 7; + + // When disable_auth is true, a JWT ID token won't be generated and the + // original "Authorization" HTTP header will be preserved. If the header is + // used to carry the original token and is expected by the backend, this + // field must be set to true to preserve the header. + bool disable_auth = 8; + } + + // The protocol used for sending a request to the backend. + // The supported values are "http/1.1" and "h2". + // + // The default value is inferred from the scheme in the + // [address][google.api.BackendRule.address] field: + // + // SCHEME PROTOCOL + // http:// http/1.1 + // https:// http/1.1 + // grpc:// h2 + // grpcs:// h2 + // + // For secure HTTP backends (https://) that support HTTP/2, set this field + // to "h2" for improved performance. + // + // Configuring this field to non-default values is only supported for secure + // HTTP backends. This field will be ignored for all other backends. + // + // See + // https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids + // for more details on the supported values. + string protocol = 9; + + // The map between request protocol and the backend address. + map overrides_by_request_protocol = 10; +} diff --git a/node_modules/google-gax/build/protos/google/api/billing.proto b/node_modules/google-gax/build/protos/google/api/billing.proto new file mode 100644 index 0000000..8b75452 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/billing.proto @@ -0,0 +1,77 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option go_package = "google.golang.org/genproto/googleapis/api/serviceconfig;serviceconfig"; +option java_multiple_files = true; +option java_outer_classname = "BillingProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Billing related configuration of the service. +// +// The following example shows how to configure monitored resources and metrics +// for billing, `consumer_destinations` is the only supported destination and +// the monitored resources need at least one label key +// `cloud.googleapis.com/location` to indicate the location of the billing +// usage, using different monitored resources between monitoring and billing is +// recommended so they can be evolved independently: +// +// +// monitored_resources: +// - type: library.googleapis.com/billing_branch +// labels: +// - key: cloud.googleapis.com/location +// description: | +// Predefined label to support billing location restriction. +// - key: city +// description: | +// Custom label to define the city where the library branch is located +// in. +// - key: name +// description: Custom label to define the name of the library branch. +// metrics: +// - name: library.googleapis.com/book/borrowed_count +// metric_kind: DELTA +// value_type: INT64 +// unit: "1" +// billing: +// consumer_destinations: +// - monitored_resource: library.googleapis.com/billing_branch +// metrics: +// - library.googleapis.com/book/borrowed_count +message Billing { + // Configuration of a specific billing destination (Currently only support + // bill against consumer project). + message BillingDestination { + // The monitored resource type. The type must be defined in + // [Service.monitored_resources][google.api.Service.monitored_resources] + // section. + string monitored_resource = 1; + + // Names of the metrics to report to this billing destination. + // Each name must be defined in + // [Service.metrics][google.api.Service.metrics] section. + repeated string metrics = 2; + } + + // Billing configurations for sending metrics to the consumer project. + // There can be multiple consumer destinations per service, each one must have + // a different monitored resource type. A metric can be used in at most + // one consumer destination. + repeated BillingDestination consumer_destinations = 8; +} diff --git a/node_modules/google-gax/build/protos/google/api/client.proto b/node_modules/google-gax/build/protos/google/api/client.proto new file mode 100644 index 0000000..0952e83 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/client.proto @@ -0,0 +1,427 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/api/launch_stage.proto"; +import "google/protobuf/descriptor.proto"; +import "google/protobuf/duration.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "ClientProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +extend google.protobuf.MethodOptions { + // A definition of a client library method signature. + // + // In client libraries, each proto RPC corresponds to one or more methods + // which the end user is able to call, and calls the underlying RPC. + // Normally, this method receives a single argument (a struct or instance + // corresponding to the RPC request object). Defining this field will + // add one or more overloads providing flattened or simpler method signatures + // in some languages. + // + // The fields on the method signature are provided as a comma-separated + // string. + // + // For example, the proto RPC and annotation: + // + // rpc CreateSubscription(CreateSubscriptionRequest) + // returns (Subscription) { + // option (google.api.method_signature) = "name,topic"; + // } + // + // Would add the following Java overload (in addition to the method accepting + // the request object): + // + // public final Subscription createSubscription(String name, String topic) + // + // The following backwards-compatibility guidelines apply: + // + // * Adding this annotation to an unannotated method is backwards + // compatible. + // * Adding this annotation to a method which already has existing + // method signature annotations is backwards compatible if and only if + // the new method signature annotation is last in the sequence. + // * Modifying or removing an existing method signature annotation is + // a breaking change. + // * Re-ordering existing method signature annotations is a breaking + // change. + repeated string method_signature = 1051; +} + +extend google.protobuf.ServiceOptions { + // The hostname for this service. + // This should be specified with no prefix or protocol. + // + // Example: + // + // service Foo { + // option (google.api.default_host) = "foo.googleapi.com"; + // ... + // } + string default_host = 1049; + + // OAuth scopes needed for the client. + // + // Example: + // + // service Foo { + // option (google.api.oauth_scopes) = \ + // "https://www.googleapis.com/auth/cloud-platform"; + // ... + // } + // + // If there is more than one scope, use a comma-separated string: + // + // Example: + // + // service Foo { + // option (google.api.oauth_scopes) = \ + // "https://www.googleapis.com/auth/cloud-platform," + // "https://www.googleapis.com/auth/monitoring"; + // ... + // } + string oauth_scopes = 1050; + + // The API version of this service, which should be sent by version-aware + // clients to the service. This allows services to abide by the schema and + // behavior of the service at the time this API version was deployed. + // The format of the API version must be treated as opaque by clients. + // Services may use a format with an apparent structure, but clients must + // not rely on this to determine components within an API version, or attempt + // to construct other valid API versions. Note that this is for upcoming + // functionality and may not be implemented for all services. + // + // Example: + // + // service Foo { + // option (google.api.api_version) = "v1_20230821_preview"; + // } + string api_version = 525000001; +} + +// Required information for every language. +message CommonLanguageSettings { + // Link to automatically generated reference documentation. Example: + // https://cloud.google.com/nodejs/docs/reference/asset/latest + string reference_docs_uri = 1 [deprecated = true]; + + // The destination where API teams want this client library to be published. + repeated ClientLibraryDestination destinations = 2; +} + +// Details about how and where to publish client libraries. +message ClientLibrarySettings { + // Version of the API to apply these settings to. This is the full protobuf + // package for the API, ending in the version element. + // Examples: "google.cloud.speech.v1" and "google.spanner.admin.database.v1". + string version = 1; + + // Launch stage of this version of the API. + LaunchStage launch_stage = 2; + + // When using transport=rest, the client request will encode enums as + // numbers rather than strings. + bool rest_numeric_enums = 3; + + // Settings for legacy Java features, supported in the Service YAML. + JavaSettings java_settings = 21; + + // Settings for C++ client libraries. + CppSettings cpp_settings = 22; + + // Settings for PHP client libraries. + PhpSettings php_settings = 23; + + // Settings for Python client libraries. + PythonSettings python_settings = 24; + + // Settings for Node client libraries. + NodeSettings node_settings = 25; + + // Settings for .NET client libraries. + DotnetSettings dotnet_settings = 26; + + // Settings for Ruby client libraries. + RubySettings ruby_settings = 27; + + // Settings for Go client libraries. + GoSettings go_settings = 28; +} + +// This message configures the settings for publishing [Google Cloud Client +// libraries](https://cloud.google.com/apis/docs/cloud-client-libraries) +// generated from the service config. +message Publishing { + // A list of API method settings, e.g. the behavior for methods that use the + // long-running operation pattern. + repeated MethodSettings method_settings = 2; + + // Link to a *public* URI where users can report issues. Example: + // https://issuetracker.google.com/issues/new?component=190865&template=1161103 + string new_issue_uri = 101; + + // Link to product home page. Example: + // https://cloud.google.com/asset-inventory/docs/overview + string documentation_uri = 102; + + // Used as a tracking tag when collecting data about the APIs developer + // relations artifacts like docs, packages delivered to package managers, + // etc. Example: "speech". + string api_short_name = 103; + + // GitHub label to apply to issues and pull requests opened for this API. + string github_label = 104; + + // GitHub teams to be added to CODEOWNERS in the directory in GitHub + // containing source code for the client libraries for this API. + repeated string codeowner_github_teams = 105; + + // A prefix used in sample code when demarking regions to be included in + // documentation. + string doc_tag_prefix = 106; + + // For whom the client library is being published. + ClientLibraryOrganization organization = 107; + + // Client library settings. If the same version string appears multiple + // times in this list, then the last one wins. Settings from earlier + // settings with the same version string are discarded. + repeated ClientLibrarySettings library_settings = 109; + + // Optional link to proto reference documentation. Example: + // https://cloud.google.com/pubsub/lite/docs/reference/rpc + string proto_reference_documentation_uri = 110; + + // Optional link to REST reference documentation. Example: + // https://cloud.google.com/pubsub/lite/docs/reference/rest + string rest_reference_documentation_uri = 111; +} + +// Settings for Java client libraries. +message JavaSettings { + // The package name to use in Java. Clobbers the java_package option + // set in the protobuf. This should be used **only** by APIs + // who have already set the language_settings.java.package_name" field + // in gapic.yaml. API teams should use the protobuf java_package option + // where possible. + // + // Example of a YAML configuration:: + // + // publishing: + // java_settings: + // library_package: com.google.cloud.pubsub.v1 + string library_package = 1; + + // Configure the Java class name to use instead of the service's for its + // corresponding generated GAPIC client. Keys are fully-qualified + // service names as they appear in the protobuf (including the full + // the language_settings.java.interface_names" field in gapic.yaml. API + // teams should otherwise use the service name as it appears in the + // protobuf. + // + // Example of a YAML configuration:: + // + // publishing: + // java_settings: + // service_class_names: + // - google.pubsub.v1.Publisher: TopicAdmin + // - google.pubsub.v1.Subscriber: SubscriptionAdmin + map service_class_names = 2; + + // Some settings. + CommonLanguageSettings common = 3; +} + +// Settings for C++ client libraries. +message CppSettings { + // Some settings. + CommonLanguageSettings common = 1; +} + +// Settings for Php client libraries. +message PhpSettings { + // Some settings. + CommonLanguageSettings common = 1; +} + +// Settings for Python client libraries. +message PythonSettings { + // Some settings. + CommonLanguageSettings common = 1; +} + +// Settings for Node client libraries. +message NodeSettings { + // Some settings. + CommonLanguageSettings common = 1; +} + +// Settings for Dotnet client libraries. +message DotnetSettings { + // Some settings. + CommonLanguageSettings common = 1; + + // Map from original service names to renamed versions. + // This is used when the default generated types + // would cause a naming conflict. (Neither name is + // fully-qualified.) + // Example: Subscriber to SubscriberServiceApi. + map renamed_services = 2; + + // Map from full resource types to the effective short name + // for the resource. This is used when otherwise resource + // named from different services would cause naming collisions. + // Example entry: + // "datalabeling.googleapis.com/Dataset": "DataLabelingDataset" + map renamed_resources = 3; + + // List of full resource types to ignore during generation. + // This is typically used for API-specific Location resources, + // which should be handled by the generator as if they were actually + // the common Location resources. + // Example entry: "documentai.googleapis.com/Location" + repeated string ignored_resources = 4; + + // Namespaces which must be aliased in snippets due to + // a known (but non-generator-predictable) naming collision + repeated string forced_namespace_aliases = 5; + + // Method signatures (in the form "service.method(signature)") + // which are provided separately, so shouldn't be generated. + // Snippets *calling* these methods are still generated, however. + repeated string handwritten_signatures = 6; +} + +// Settings for Ruby client libraries. +message RubySettings { + // Some settings. + CommonLanguageSettings common = 1; +} + +// Settings for Go client libraries. +message GoSettings { + // Some settings. + CommonLanguageSettings common = 1; +} + +// Describes the generator configuration for a method. +message MethodSettings { + // Describes settings to use when generating API methods that use the + // long-running operation pattern. + // All default values below are from those used in the client library + // generators (e.g. + // [Java](https://github.com/googleapis/gapic-generator-java/blob/04c2faa191a9b5a10b92392fe8482279c4404803/src/main/java/com/google/api/generator/gapic/composer/common/RetrySettingsComposer.java)). + message LongRunning { + // Initial delay after which the first poll request will be made. + // Default value: 5 seconds. + google.protobuf.Duration initial_poll_delay = 1; + + // Multiplier to gradually increase delay between subsequent polls until it + // reaches max_poll_delay. + // Default value: 1.5. + float poll_delay_multiplier = 2; + + // Maximum time between two subsequent poll requests. + // Default value: 45 seconds. + google.protobuf.Duration max_poll_delay = 3; + + // Total polling timeout. + // Default value: 5 minutes. + google.protobuf.Duration total_poll_timeout = 4; + } + + // The fully qualified name of the method, for which the options below apply. + // This is used to find the method to apply the options. + string selector = 1; + + // Describes settings to use for long-running operations when generating + // API methods for RPCs. Complements RPCs that use the annotations in + // google/longrunning/operations.proto. + // + // Example of a YAML configuration:: + // + // publishing: + // method_settings: + // - selector: google.cloud.speech.v2.Speech.BatchRecognize + // long_running: + // initial_poll_delay: + // seconds: 60 # 1 minute + // poll_delay_multiplier: 1.5 + // max_poll_delay: + // seconds: 360 # 6 minutes + // total_poll_timeout: + // seconds: 54000 # 90 minutes + LongRunning long_running = 2; + + // List of top-level fields of the request message, that should be + // automatically populated by the client libraries based on their + // (google.api.field_info).format. Currently supported format: UUID4. + // + // Example of a YAML configuration: + // + // publishing: + // method_settings: + // - selector: google.example.v1.ExampleService.CreateExample + // auto_populated_fields: + // - request_id + repeated string auto_populated_fields = 3; +} + +// The organization for which the client libraries are being published. +// Affects the url where generated docs are published, etc. +enum ClientLibraryOrganization { + // Not useful. + CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED = 0; + + // Google Cloud Platform Org. + CLOUD = 1; + + // Ads (Advertising) Org. + ADS = 2; + + // Photos Org. + PHOTOS = 3; + + // Street View Org. + STREET_VIEW = 4; + + // Shopping Org. + SHOPPING = 5; + + // Geo Org. + GEO = 6; + + // Generative AI - https://developers.generativeai.google + GENERATIVE_AI = 7; +} + +// To where should client libraries be published? +enum ClientLibraryDestination { + // Client libraries will neither be generated nor published to package + // managers. + CLIENT_LIBRARY_DESTINATION_UNSPECIFIED = 0; + + // Generate the client library in a repo under github.com/googleapis, + // but don't publish it to package managers. + GITHUB = 10; + + // Publish the library to package managers like nuget.org and npmjs.com. + PACKAGE_MANAGER = 20; +} diff --git a/node_modules/google-gax/build/protos/google/api/cloudquotas/v1/cloudquotas.proto b/node_modules/google-gax/build/protos/google/api/cloudquotas/v1/cloudquotas.proto new file mode 100644 index 0000000..6727025 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/cloudquotas/v1/cloudquotas.proto @@ -0,0 +1,322 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.cloudquotas.v1; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/cloudquotas/v1/resources.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/protobuf/field_mask.proto"; + +option csharp_namespace = "Google.Cloud.CloudQuotas.V1"; +option go_package = "cloud.google.com/go/cloudquotas/apiv1/cloudquotaspb;cloudquotaspb"; +option java_multiple_files = true; +option java_outer_classname = "CloudquotasProto"; +option java_package = "com.google.api.cloudquotas.v1"; +option php_namespace = "Google\\Cloud\\CloudQuotas\\V1"; +option ruby_package = "Google::Cloud::CloudQuotas::V1"; +option (google.api.resource_definition) = { + type: "cloudquotas.googleapis.com/Service" + pattern: "projects/{project}/locations/{location}/services/{service}" + pattern: "folders/{folder}/locations/{location}/services/{service}" + pattern: "organizations/{organization}/locations/{location}/services/{service}" +}; +option (google.api.resource_definition) = { + type: "cloudquotas.googleapis.com/Location" + pattern: "projects/{project}/locations/{location}" + pattern: "folders/{folder}/locations/{location}" + pattern: "organizations/{organization}/locations/{location}" +}; + +// The Cloud Quotas API is an infrastructure service for Google Cloud that lets +// service consumers list and manage their resource usage limits. +// +// - List/Get the metadata and current status of the quotas for a service. +// - Create/Update quota preferencess that declare the preferred quota values. +// - Check the status of a quota preference request. +// - List/Get pending and historical quota preference. +service CloudQuotas { + option (google.api.default_host) = "cloudquotas.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform"; + + // Lists QuotaInfos of all quotas for a given project, folder or organization. + rpc ListQuotaInfos(ListQuotaInfosRequest) returns (ListQuotaInfosResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/locations/*/services/*}/quotaInfos" + additional_bindings { + get: "/v1/{parent=organizations/*/locations/*/services/*}/quotaInfos" + } + additional_bindings { + get: "/v1/{parent=folders/*/locations/*/services/*}/quotaInfos" + } + }; + option (google.api.method_signature) = "parent"; + } + + // Retrieve the QuotaInfo of a quota for a project, folder or organization. + rpc GetQuotaInfo(GetQuotaInfoRequest) returns (QuotaInfo) { + option (google.api.http) = { + get: "/v1/{name=projects/*/locations/*/services/*/quotaInfos/*}" + additional_bindings { + get: "/v1/{name=organizations/*/locations/*/services/*/quotaInfos/*}" + } + additional_bindings { + get: "/v1/{name=folders/*/locations/*/services/*/quotaInfos/*}" + } + }; + option (google.api.method_signature) = "name"; + } + + // Lists QuotaPreferences in a given project, folder or organization. + rpc ListQuotaPreferences(ListQuotaPreferencesRequest) + returns (ListQuotaPreferencesResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/locations/*}/quotaPreferences" + additional_bindings { + get: "/v1/{parent=folders/*/locations/*}/quotaPreferences" + } + additional_bindings { + get: "/v1/{parent=organizations/*/locations/*}/quotaPreferences" + } + }; + option (google.api.method_signature) = "parent"; + } + + // Gets details of a single QuotaPreference. + rpc GetQuotaPreference(GetQuotaPreferenceRequest) returns (QuotaPreference) { + option (google.api.http) = { + get: "/v1/{name=projects/*/locations/*/quotaPreferences/*}" + additional_bindings { + get: "/v1/{name=organizations/*/locations/*/quotaPreferences/*}" + } + additional_bindings { + get: "/v1/{name=folders/*/locations/*/quotaPreferences/*}" + } + }; + option (google.api.method_signature) = "name"; + } + + // Creates a new QuotaPreference that declares the desired value for a quota. + rpc CreateQuotaPreference(CreateQuotaPreferenceRequest) + returns (QuotaPreference) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/locations/*}/quotaPreferences" + body: "quota_preference" + additional_bindings { + post: "/v1/{parent=folders/*/locations/*}/quotaPreferences" + body: "quota_preference" + } + additional_bindings { + post: "/v1/{parent=organizations/*/locations/*}/quotaPreferences" + body: "quota_preference" + } + }; + option (google.api.method_signature) = + "parent,quota_preference,quota_preference_id"; + option (google.api.method_signature) = "parent,quota_preference"; + } + + // Updates the parameters of a single QuotaPreference. It can updates the + // config in any states, not just the ones pending approval. + rpc UpdateQuotaPreference(UpdateQuotaPreferenceRequest) + returns (QuotaPreference) { + option (google.api.http) = { + patch: "/v1/{quota_preference.name=projects/*/locations/*/quotaPreferences/*}" + body: "quota_preference" + additional_bindings { + patch: "/v1/{quota_preference.name=folders/*/locations/*/quotaPreferences/*}" + body: "quota_preference" + } + additional_bindings { + patch: "/v1/{quota_preference.name=organizations/*/locations/*/quotaPreferences/*}" + body: "quota_preference" + } + }; + option (google.api.method_signature) = "quota_preference,update_mask"; + } +} + +// Message for requesting list of QuotaInfos +message ListQuotaInfosRequest { + // Required. Parent value of QuotaInfo resources. + // Listing across different resource containers (such as 'projects/-') is not + // allowed. + // + // Example names: + // `projects/123/locations/global/services/compute.googleapis.com` + // `folders/234/locations/global/services/compute.googleapis.com` + // `organizations/345/locations/global/services/compute.googleapis.com` + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "cloudquotas.googleapis.com/QuotaInfo" + } + ]; + + // Optional. Requested page size. Server may return fewer items than + // requested. If unspecified, server will pick an appropriate default. + int32 page_size = 2 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. A token identifying a page of results the server should return. + string page_token = 3 [(google.api.field_behavior) = OPTIONAL]; +} + +// Message for response to listing QuotaInfos +message ListQuotaInfosResponse { + // The list of QuotaInfo + repeated QuotaInfo quota_infos = 1; + + // A token, which can be sent as `page_token` to retrieve the next page. + // If this field is omitted, there are no subsequent pages. + string next_page_token = 2; +} + +// Message for getting a QuotaInfo +message GetQuotaInfoRequest { + // Required. The resource name of the quota info. + // + // An example name: + // `projects/123/locations/global/services/compute.googleapis.com/quotaInfos/CpusPerProjectPerRegion` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "cloudquotas.googleapis.com/QuotaInfo" + } + ]; +} + +// Message for requesting list of QuotaPreferences +message ListQuotaPreferencesRequest { + // Required. Parent value of QuotaPreference resources. + // Listing across different resource containers (such as 'projects/-') is not + // allowed. + // + // When the value starts with 'folders' or 'organizations', it lists the + // QuotaPreferences for org quotas in the container. It does not list the + // QuotaPreferences in the descendant projects of the container. + // + // Example parents: + // `projects/123/locations/global` + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "cloudquotas.googleapis.com/QuotaPreference" + } + ]; + + // Optional. Requested page size. Server may return fewer items than + // requested. If unspecified, server will pick an appropriate default. + int32 page_size = 2 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. A token identifying a page of results the server should return. + string page_token = 3 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Filter result QuotaPreferences by their state, type, + // create/update time range. + // + // Example filters: + // `reconciling=true AND request_type=CLOUD_CONSOLE`, + // `reconciling=true OR creation_time>2022-12-03T10:30:00` + string filter = 4 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. How to order of the results. By default, the results are ordered + // by create time. + // + // Example orders: + // `quota_id`, + // `service, create_time` + string order_by = 5 [(google.api.field_behavior) = OPTIONAL]; +} + +// Message for response to listing QuotaPreferences +message ListQuotaPreferencesResponse { + // The list of QuotaPreference + repeated QuotaPreference quota_preferences = 1; + + // A token, which can be sent as `page_token` to retrieve the next page. + // If this field is omitted, there are no subsequent pages. + string next_page_token = 2; + + // Locations that could not be reached. + repeated string unreachable = 3; +} + +// Message for getting a QuotaPreference +message GetQuotaPreferenceRequest { + // Required. Name of the resource + // + // Example name: + // `projects/123/locations/global/quota_preferences/my-config-for-us-east1` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "cloudquotas.googleapis.com/QuotaPreference" + } + ]; +} + +// Message for creating a QuotaPreference +message CreateQuotaPreferenceRequest { + // Required. Value for parent. + // + // Example: + // `projects/123/locations/global` + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "cloudquotas.googleapis.com/QuotaPreference" + } + ]; + + // Optional. Id of the requesting object, must be unique under its parent. + // If client does not set this field, the service will generate one. + string quota_preference_id = 2 [(google.api.field_behavior) = OPTIONAL]; + + // Required. The resource being created + QuotaPreference quota_preference = 3 [(google.api.field_behavior) = REQUIRED]; + + // The list of quota safety checks to be ignored. + repeated QuotaSafetyCheck ignore_safety_checks = 4; +} + +// Message for updating a QuotaPreference +message UpdateQuotaPreferenceRequest { + // Optional. Field mask is used to specify the fields to be overwritten in the + // QuotaPreference resource by the update. + // The fields specified in the update_mask are relative to the resource, not + // the full request. A field will be overwritten if it is in the mask. If the + // user does not provide a mask then all fields will be overwritten. + google.protobuf.FieldMask update_mask = 1 + [(google.api.field_behavior) = OPTIONAL]; + + // Required. The resource being updated + QuotaPreference quota_preference = 2 [(google.api.field_behavior) = REQUIRED]; + + // Optional. If set to true, and the quota preference is not found, a new one + // will be created. In this situation, `update_mask` is ignored. + bool allow_missing = 3 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. If set to true, validate the request, but do not actually update. + // Note that a request being valid does not mean that the request is + // guaranteed to be fulfilled. + bool validate_only = 4 [(google.api.field_behavior) = OPTIONAL]; + + // The list of quota safety checks to be ignored. + repeated QuotaSafetyCheck ignore_safety_checks = 5; +} diff --git a/node_modules/google-gax/build/protos/google/api/cloudquotas/v1/resources.proto b/node_modules/google-gax/build/protos/google/api/cloudquotas/v1/resources.proto new file mode 100644 index 0000000..05de83f --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/cloudquotas/v1/resources.proto @@ -0,0 +1,311 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.cloudquotas.v1; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/protobuf/timestamp.proto"; +import "google/protobuf/wrappers.proto"; + +option csharp_namespace = "Google.Cloud.CloudQuotas.V1"; +option go_package = "cloud.google.com/go/cloudquotas/apiv1/cloudquotaspb;cloudquotaspb"; +option java_multiple_files = true; +option java_outer_classname = "ResourcesProto"; +option java_package = "com.google.api.cloudquotas.v1"; +option php_namespace = "Google\\Cloud\\CloudQuotas\\V1"; +option ruby_package = "Google::Cloud::CloudQuotas::V1"; + +// Enumerations of quota safety checks. +enum QuotaSafetyCheck { + // Unspecified quota safety check. + QUOTA_SAFETY_CHECK_UNSPECIFIED = 0; + + // Validates that a quota mutation would not cause the consumer's effective + // limit to be lower than the consumer's quota usage. + QUOTA_DECREASE_BELOW_USAGE = 1; + + // Validates that a quota mutation would not cause the consumer's effective + // limit to decrease by more than 10 percent. + QUOTA_DECREASE_PERCENTAGE_TOO_HIGH = 2; +} + +// QuotaInfo represents information about a particular quota for a given +// project, folder or organization. +message QuotaInfo { + option (google.api.resource) = { + type: "cloudquotas.googleapis.com/QuotaInfo" + pattern: "projects/{project}/locations/{location}/services/{service}/quotaInfos/{quota_info}" + pattern: "folders/{folder}/locations/{location}/services/{service}/quotaInfos/{quota_info}" + pattern: "organizations/{organization}/locations/{location}/services/{service}/quotaInfos/{quota_info}" + }; + + // The enumeration of the types of a cloud resource container. + enum ContainerType { + // Unspecified container type. + CONTAINER_TYPE_UNSPECIFIED = 0; + + // consumer project + PROJECT = 1; + + // folder + FOLDER = 2; + + // organization + ORGANIZATION = 3; + } + + // Resource name of this QuotaInfo. + // The ID component following "locations/" must be "global". + // Example: + // `projects/123/locations/global/services/compute.googleapis.com/quotaInfos/CpusPerProjectPerRegion` + string name = 1; + + // The id of the quota, which is unquie within the service. + // Example: `CpusPerProjectPerRegion` + string quota_id = 2; + + // The metric of the quota. It specifies the resources consumption the quota + // is defined for. + // Example: `compute.googleapis.com/cpus` + string metric = 3; + + // The name of the service in which the quota is defined. + // Example: `compute.googleapis.com` + string service = 4; + + // Whether this is a precise quota. A precise quota is tracked with absolute + // precision. In contrast, an imprecise quota is not tracked with precision. + bool is_precise = 5; + + // The reset time interval for the quota. Refresh interval applies to rate + // quota only. + // Example: "minute" for per minute, "day" for per day, or "10 seconds" for + // every 10 seconds. + string refresh_interval = 6; + + // The container type of the QuotaInfo. + ContainerType container_type = 7; + + // The dimensions the quota is defined on. + repeated string dimensions = 8; + + // The display name of the quota metric + string metric_display_name = 9; + + // The display name of the quota. + string quota_display_name = 10; + + // The unit in which the metric value is reported, e.g., "MByte". + string metric_unit = 11; + + // Whether it is eligible to request a higher quota value for this quota. + QuotaIncreaseEligibility quota_increase_eligibility = 12; + + // Whether the quota value is fixed or adjustable + bool is_fixed = 13; + + // The collection of dimensions info ordered by their dimensions from more + // specific ones to less specific ones. + repeated DimensionsInfo dimensions_infos = 14; + + // Whether the quota is a concurrent quota. Concurrent quotas are enforced + // on the total number of concurrent operations in flight at any given time. + bool is_concurrent = 15; + + // URI to the page where the user can request more quotas for the cloud + // service, such as + // https://docs.google.com/spreadsheet/viewform?formkey=abc123&entry_0={email}&entry_1={id}. + // Google Developers Console UI replace {email} with the current + // user's e-mail, {id} with the current project number, or organization ID + // with "organizations/" prefix. For example, + // https://docs.google.com/spreadsheet/viewform?formkey=abc123&entry_0=johndoe@gmail.com&entry_1=25463754, + // or + // https://docs.google.com/spreadsheet/viewform?formkey=abc123&entry_0=johndoe@gmail.com&entry_1=organizations/26474422. + string service_request_quota_uri = 17; +} + +// Eligibility information regarding requesting increase adjustment of a quota. +message QuotaIncreaseEligibility { + // The enumeration of reasons when it is ineligible to request increase + // adjustment. + enum IneligibilityReason { + // Default value when is_eligible is true. + INELIGIBILITY_REASON_UNSPECIFIED = 0; + + // The container is not linked with a valid billing account. + NO_VALID_BILLING_ACCOUNT = 1; + + // Other reasons. + OTHER = 2; + } + + // Whether a higher quota value can be requested for the quota. + bool is_eligible = 1; + + // The reason of why it is ineligible to request increased value of the quota. + // If the is_eligible field is true, it defaults to + // INELIGIBILITY_REASON_UNSPECIFIED. + IneligibilityReason ineligibility_reason = 2; +} + +// QuotaPreference represents the preferred quota configuration specified for +// a project, folder or organization. There is only one QuotaPreference +// resource for a quota value targeting a unique set of dimensions. +message QuotaPreference { + option (google.api.resource) = { + type: "cloudquotas.googleapis.com/QuotaPreference" + pattern: "projects/{project}/locations/{location}/quotaPreferences/{quota_preference}" + pattern: "folders/{folder}/locations/{location}/quotaPreferences/{quota_preference}" + pattern: "organizations/{organization}/locations/{location}/quotaPreferences/{quota_preference}" + }; + + // Required except in the CREATE requests. + // The resource name of the quota preference. + // The ID component following "locations/" must be "global". + // Example: + // `projects/123/locations/global/quotaPreferences/my-config-for-us-east1` + string name = 1; + + // Immutable. The dimensions that this quota preference applies to. The key of + // the map entry is the name of a dimension, such as "region", "zone", + // "network_id", and the value of the map entry is the dimension value. + // + // If a dimension is missing from the map of dimensions, the quota preference + // applies to all the dimension values except for those that have other quota + // preferences configured for the specific value. + // + // NOTE: QuotaPreferences can only be applied across all values of "user" and + // "resource" dimension. Do not set values for "user" or "resource" in the + // dimension map. + // + // Example: {"provider", "Foo Inc"} where "provider" is a service specific + // dimension. + map dimensions = 2 [(google.api.field_behavior) = IMMUTABLE]; + + // Required. Preferred quota configuration. + QuotaConfig quota_config = 3 [(google.api.field_behavior) = REQUIRED]; + + // Optional. The current etag of the quota preference. If an etag is provided + // on update and does not match the current server's etag of the quota + // preference, the request will be blocked and an ABORTED error will be + // returned. See https://google.aip.dev/134#etags for more details on etags. + string etag = 4 [(google.api.field_behavior) = OPTIONAL]; + + // Output only. Create time stamp + google.protobuf.Timestamp create_time = 5 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Update time stamp + google.protobuf.Timestamp update_time = 6 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Required. The name of the service to which the quota preference is applied. + string service = 7 [(google.api.field_behavior) = REQUIRED]; + + // Required. The id of the quota to which the quota preference is applied. A + // quota name is unique in the service. Example: `CpusPerProjectPerRegion` + string quota_id = 8 [(google.api.field_behavior) = REQUIRED]; + + // Output only. Is the quota preference pending Google Cloud approval and + // fulfillment. + bool reconciling = 10 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // The reason / justification for this quota preference. + string justification = 11; + + // Required. Input only. An email address that can be used for quota related + // communication between the Google Cloud and the user in case the Google + // Cloud needs further information to make a decision on whether the user + // preferred quota can be granted. + // + // The Google account for the email address must have quota update permission + // for the project, folder or organization this quota preference is for. + string contact_email = 12 [ + (google.api.field_behavior) = INPUT_ONLY, + (google.api.field_behavior) = REQUIRED + ]; +} + +// The preferred quota configuration. +message QuotaConfig { + // The enumeration of the origins of quota preference requests. + enum Origin { + // The unspecified value. + ORIGIN_UNSPECIFIED = 0; + + // Created through Cloud Console. + CLOUD_CONSOLE = 1; + + // Generated by automatic quota adjustment. + AUTO_ADJUSTER = 2; + } + + // Required. The preferred value. Must be greater than or equal to -1. If set + // to -1, it means the value is "unlimited". + int64 preferred_value = 1 [(google.api.field_behavior) = REQUIRED]; + + // Output only. Optional details about the state of this quota preference. + string state_detail = 2 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Granted quota value. + google.protobuf.Int64Value granted_value = 3 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The trace id that the Google Cloud uses to provision the + // requested quota. This trace id may be used by the client to contact Cloud + // support to track the state of a quota preference request. The trace id is + // only produced for increase requests and is unique for each request. The + // quota decrease requests do not have a trace id. + string trace_id = 4 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Optional. The annotations map for clients to store small amounts of + // arbitrary data. Do not put PII or other sensitive information here. See + // https://google.aip.dev/128#annotations + map annotations = 5 [(google.api.field_behavior) = OPTIONAL]; + + // Output only. The origin of the quota preference request. + Origin request_origin = 6 [(google.api.field_behavior) = OUTPUT_ONLY]; +} + +// The detailed quota information such as effective quota value for a +// combination of dimensions. +message DimensionsInfo { + // The map of dimensions for this dimensions info. The key of a map entry + // is "region", "zone" or the name of a service specific dimension, and the + // value of a map entry is the value of the dimension. If a dimension does + // not appear in the map of dimensions, the dimensions info applies to all + // the dimension values except for those that have another DimenisonInfo + // instance configured for the specific value. + // Example: {"provider" : "Foo Inc"} where "provider" is a service specific + // dimension of a quota. + map dimensions = 1; + + // Quota details for the specified dimensions. + QuotaDetails details = 2; + + // The applicable regions or zones of this dimensions info. The field will be + // set to ['global'] for quotas that are not per region or per zone. + // Otherwise, it will be set to the list of locations this dimension info is + // applicable to. + repeated string applicable_locations = 3; +} + +// The quota details for a map of dimensions. +message QuotaDetails { + // The value currently in effect and being enforced. + int64 value = 1; +} diff --git a/node_modules/google-gax/build/protos/google/api/config_change.proto b/node_modules/google-gax/build/protos/google/api/config_change.proto new file mode 100644 index 0000000..1dc8044 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/config_change.proto @@ -0,0 +1,84 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option go_package = "google.golang.org/genproto/googleapis/api/configchange;configchange"; +option java_multiple_files = true; +option java_outer_classname = "ConfigChangeProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Output generated from semantically comparing two versions of a service +// configuration. +// +// Includes detailed information about a field that have changed with +// applicable advice about potential consequences for the change, such as +// backwards-incompatibility. +message ConfigChange { + // Object hierarchy path to the change, with levels separated by a '.' + // character. For repeated fields, an applicable unique identifier field is + // used for the index (usually selector, name, or id). For maps, the term + // 'key' is used. If the field has no unique identifier, the numeric index + // is used. + // Examples: + // - visibility.rules[selector=="google.LibraryService.ListBooks"].restriction + // - quota.metric_rules[selector=="google"].metric_costs[key=="reads"].value + // - logging.producer_destinations[0] + string element = 1; + + // Value of the changed object in the old Service configuration, + // in JSON format. This field will not be populated if ChangeType == ADDED. + string old_value = 2; + + // Value of the changed object in the new Service configuration, + // in JSON format. This field will not be populated if ChangeType == REMOVED. + string new_value = 3; + + // The type for this change, either ADDED, REMOVED, or MODIFIED. + ChangeType change_type = 4; + + // Collection of advice provided for this change, useful for determining the + // possible impact of this change. + repeated Advice advices = 5; +} + +// Generated advice about this change, used for providing more +// information about how a change will affect the existing service. +message Advice { + // Useful description for why this advice was applied and what actions should + // be taken to mitigate any implied risks. + string description = 2; +} + +// Classifies set of possible modifications to an object in the service +// configuration. +enum ChangeType { + // No value was provided. + CHANGE_TYPE_UNSPECIFIED = 0; + + // The changed object exists in the 'new' service configuration, but not + // in the 'old' service configuration. + ADDED = 1; + + // The changed object exists in the 'old' service configuration, but not + // in the 'new' service configuration. + REMOVED = 2; + + // The changed object exists in both service configurations, but its value + // is different. + MODIFIED = 3; +} diff --git a/node_modules/google-gax/build/protos/google/api/consumer.proto b/node_modules/google-gax/build/protos/google/api/consumer.proto new file mode 100644 index 0000000..b7e5df1 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/consumer.proto @@ -0,0 +1,82 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option go_package = "google.golang.org/genproto/googleapis/api/serviceconfig;serviceconfig"; +option java_multiple_files = true; +option java_outer_classname = "ConsumerProto"; +option java_package = "com.google.api"; + +// A descriptor for defining project properties for a service. One service may +// have many consumer projects, and the service may want to behave differently +// depending on some properties on the project. For example, a project may be +// associated with a school, or a business, or a government agency, a business +// type property on the project may affect how a service responds to the client. +// This descriptor defines which properties are allowed to be set on a project. +// +// Example: +// +// project_properties: +// properties: +// - name: NO_WATERMARK +// type: BOOL +// description: Allows usage of the API without watermarks. +// - name: EXTENDED_TILE_CACHE_PERIOD +// type: INT64 +message ProjectProperties { + // List of per consumer project-specific properties. + repeated Property properties = 1; +} + +// Defines project properties. +// +// API services can define properties that can be assigned to consumer projects +// so that backends can perform response customization without having to make +// additional calls or maintain additional storage. For example, Maps API +// defines properties that controls map tile cache period, or whether to embed a +// watermark in a result. +// +// These values can be set via API producer console. Only API providers can +// define and set these properties. +message Property { + // Supported data type of the property values + enum PropertyType { + // The type is unspecified, and will result in an error. + UNSPECIFIED = 0; + + // The type is `int64`. + INT64 = 1; + + // The type is `bool`. + BOOL = 2; + + // The type is `string`. + STRING = 3; + + // The type is 'double'. + DOUBLE = 4; + } + + // The name of the property (a.k.a key). + string name = 1; + + // The type of this property. + PropertyType type = 2; + + // The description of the property + string description = 3; +} diff --git a/node_modules/google-gax/build/protos/google/api/context.proto b/node_modules/google-gax/build/protos/google/api/context.proto new file mode 100644 index 0000000..1b16517 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/context.proto @@ -0,0 +1,90 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option go_package = "google.golang.org/genproto/googleapis/api/serviceconfig;serviceconfig"; +option java_multiple_files = true; +option java_outer_classname = "ContextProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// `Context` defines which contexts an API requests. +// +// Example: +// +// context: +// rules: +// - selector: "*" +// requested: +// - google.rpc.context.ProjectContext +// - google.rpc.context.OriginContext +// +// The above specifies that all methods in the API request +// `google.rpc.context.ProjectContext` and +// `google.rpc.context.OriginContext`. +// +// Available context types are defined in package +// `google.rpc.context`. +// +// This also provides mechanism to allowlist any protobuf message extension that +// can be sent in grpc metadata using “x-goog-ext--bin” and +// “x-goog-ext--jspb” format. For example, list any service +// specific protobuf types that can appear in grpc metadata as follows in your +// yaml file: +// +// Example: +// +// context: +// rules: +// - selector: "google.example.library.v1.LibraryService.CreateBook" +// allowed_request_extensions: +// - google.foo.v1.NewExtension +// allowed_response_extensions: +// - google.foo.v1.NewExtension +// +// You can also specify extension ID instead of fully qualified extension name +// here. +message Context { + // A list of RPC context rules that apply to individual API methods. + // + // **NOTE:** All service configuration rules follow "last one wins" order. + repeated ContextRule rules = 1; +} + +// A context rule provides information about the context for an individual API +// element. +message ContextRule { + // Selects the methods to which this rule applies. + // + // Refer to [selector][google.api.DocumentationRule.selector] for syntax + // details. + string selector = 1; + + // A list of full type names of requested contexts. + repeated string requested = 2; + + // A list of full type names of provided contexts. + repeated string provided = 3; + + // A list of full type names or extension IDs of extensions allowed in grpc + // side channel from client to backend. + repeated string allowed_request_extensions = 4; + + // A list of full type names or extension IDs of extensions allowed in grpc + // side channel from backend to client. + repeated string allowed_response_extensions = 5; +} diff --git a/node_modules/google-gax/build/protos/google/api/control.proto b/node_modules/google-gax/build/protos/google/api/control.proto new file mode 100644 index 0000000..cbbce6f --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/control.proto @@ -0,0 +1,41 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/api/policy.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/serviceconfig;serviceconfig"; +option java_multiple_files = true; +option java_outer_classname = "ControlProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Selects and configures the service controller used by the service. +// +// Example: +// +// control: +// environment: servicecontrol.googleapis.com +message Control { + // The service controller environment to use. If empty, no control plane + // feature (like quota and billing) will be enabled. The recommended value for + // most services is servicecontrol.googleapis.com + string environment = 1; + + // Defines policies applying to the API methods of the service. + repeated MethodPolicy method_policies = 4; +} diff --git a/node_modules/google-gax/build/protos/google/api/distribution.proto b/node_modules/google-gax/build/protos/google/api/distribution.proto new file mode 100644 index 0000000..b0bc493 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/distribution.proto @@ -0,0 +1,213 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/protobuf/any.proto"; +import "google/protobuf/timestamp.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/distribution;distribution"; +option java_multiple_files = true; +option java_outer_classname = "DistributionProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// `Distribution` contains summary statistics for a population of values. It +// optionally contains a histogram representing the distribution of those values +// across a set of buckets. +// +// The summary statistics are the count, mean, sum of the squared deviation from +// the mean, the minimum, and the maximum of the set of population of values. +// The histogram is based on a sequence of buckets and gives a count of values +// that fall into each bucket. The boundaries of the buckets are given either +// explicitly or by formulas for buckets of fixed or exponentially increasing +// widths. +// +// Although it is not forbidden, it is generally a bad idea to include +// non-finite values (infinities or NaNs) in the population of values, as this +// will render the `mean` and `sum_of_squared_deviation` fields meaningless. +message Distribution { + // The range of the population values. + message Range { + // The minimum of the population values. + double min = 1; + + // The maximum of the population values. + double max = 2; + } + + // `BucketOptions` describes the bucket boundaries used to create a histogram + // for the distribution. The buckets can be in a linear sequence, an + // exponential sequence, or each bucket can be specified explicitly. + // `BucketOptions` does not include the number of values in each bucket. + // + // A bucket has an inclusive lower bound and exclusive upper bound for the + // values that are counted for that bucket. The upper bound of a bucket must + // be strictly greater than the lower bound. The sequence of N buckets for a + // distribution consists of an underflow bucket (number 0), zero or more + // finite buckets (number 1 through N - 2) and an overflow bucket (number N - + // 1). The buckets are contiguous: the lower bound of bucket i (i > 0) is the + // same as the upper bound of bucket i - 1. The buckets span the whole range + // of finite values: lower bound of the underflow bucket is -infinity and the + // upper bound of the overflow bucket is +infinity. The finite buckets are + // so-called because both bounds are finite. + message BucketOptions { + // Specifies a linear sequence of buckets that all have the same width + // (except overflow and underflow). Each bucket represents a constant + // absolute uncertainty on the specific value in the bucket. + // + // There are `num_finite_buckets + 2` (= N) buckets. Bucket `i` has the + // following boundaries: + // + // Upper bound (0 <= i < N-1): offset + (width * i). + // + // Lower bound (1 <= i < N): offset + (width * (i - 1)). + message Linear { + // Must be greater than 0. + int32 num_finite_buckets = 1; + + // Must be greater than 0. + double width = 2; + + // Lower bound of the first bucket. + double offset = 3; + } + + // Specifies an exponential sequence of buckets that have a width that is + // proportional to the value of the lower bound. Each bucket represents a + // constant relative uncertainty on a specific value in the bucket. + // + // There are `num_finite_buckets + 2` (= N) buckets. Bucket `i` has the + // following boundaries: + // + // Upper bound (0 <= i < N-1): scale * (growth_factor ^ i). + // + // Lower bound (1 <= i < N): scale * (growth_factor ^ (i - 1)). + message Exponential { + // Must be greater than 0. + int32 num_finite_buckets = 1; + + // Must be greater than 1. + double growth_factor = 2; + + // Must be greater than 0. + double scale = 3; + } + + // Specifies a set of buckets with arbitrary widths. + // + // There are `size(bounds) + 1` (= N) buckets. Bucket `i` has the following + // boundaries: + // + // Upper bound (0 <= i < N-1): bounds[i] + // Lower bound (1 <= i < N); bounds[i - 1] + // + // The `bounds` field must contain at least one element. If `bounds` has + // only one element, then there are no finite buckets, and that single + // element is the common boundary of the overflow and underflow buckets. + message Explicit { + // The values must be monotonically increasing. + repeated double bounds = 1; + } + + // Exactly one of these three fields must be set. + oneof options { + // The linear bucket. + Linear linear_buckets = 1; + + // The exponential buckets. + Exponential exponential_buckets = 2; + + // The explicit buckets. + Explicit explicit_buckets = 3; + } + } + + // Exemplars are example points that may be used to annotate aggregated + // distribution values. They are metadata that gives information about a + // particular value added to a Distribution bucket, such as a trace ID that + // was active when a value was added. They may contain further information, + // such as a example values and timestamps, origin, etc. + message Exemplar { + // Value of the exemplar point. This value determines to which bucket the + // exemplar belongs. + double value = 1; + + // The observation (sampling) time of the above value. + google.protobuf.Timestamp timestamp = 2; + + // Contextual information about the example value. Examples are: + // + // Trace: type.googleapis.com/google.monitoring.v3.SpanContext + // + // Literal string: type.googleapis.com/google.protobuf.StringValue + // + // Labels dropped during aggregation: + // type.googleapis.com/google.monitoring.v3.DroppedLabels + // + // There may be only a single attachment of any given message type in a + // single exemplar, and this is enforced by the system. + repeated google.protobuf.Any attachments = 3; + } + + // The number of values in the population. Must be non-negative. This value + // must equal the sum of the values in `bucket_counts` if a histogram is + // provided. + int64 count = 1; + + // The arithmetic mean of the values in the population. If `count` is zero + // then this field must be zero. + double mean = 2; + + // The sum of squared deviations from the mean of the values in the + // population. For values x_i this is: + // + // Sum[i=1..n]((x_i - mean)^2) + // + // Knuth, "The Art of Computer Programming", Vol. 2, page 232, 3rd edition + // describes Welford's method for accumulating this sum in one pass. + // + // If `count` is zero then this field must be zero. + double sum_of_squared_deviation = 3; + + // If specified, contains the range of the population values. The field + // must not be present if the `count` is zero. + Range range = 4; + + // Defines the histogram bucket boundaries. If the distribution does not + // contain a histogram, then omit this field. + BucketOptions bucket_options = 6; + + // The number of values in each bucket of the histogram, as described in + // `bucket_options`. If the distribution does not have a histogram, then omit + // this field. If there is a histogram, then the sum of the values in + // `bucket_counts` must equal the value in the `count` field of the + // distribution. + // + // If present, `bucket_counts` should contain N values, where N is the number + // of buckets specified in `bucket_options`. If you supply fewer than N + // values, the remaining values are assumed to be 0. + // + // The order of the values in `bucket_counts` follows the bucket numbering + // schemes described for the three bucket types. The first value must be the + // count for the underflow bucket (number 0). The next N-2 values are the + // counts for the finite buckets (number 1 through N-2). The N'th value in + // `bucket_counts` is the count for the overflow bucket (number N-1). + repeated int64 bucket_counts = 7; + + // Must be in increasing order of `value` field. + repeated Exemplar exemplars = 10; +} diff --git a/node_modules/google-gax/build/protos/google/api/documentation.proto b/node_modules/google-gax/build/protos/google/api/documentation.proto new file mode 100644 index 0000000..12936c7 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/documentation.proto @@ -0,0 +1,168 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option go_package = "google.golang.org/genproto/googleapis/api/serviceconfig;serviceconfig"; +option java_multiple_files = true; +option java_outer_classname = "DocumentationProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// `Documentation` provides the information for describing a service. +// +// Example: +//

                          documentation:
                          +//   summary: >
                          +//     The Google Calendar API gives access
                          +//     to most calendar features.
                          +//   pages:
                          +//   - name: Overview
                          +//     content: (== include google/foo/overview.md ==)
                          +//   - name: Tutorial
                          +//     content: (== include google/foo/tutorial.md ==)
                          +//     subpages:
                          +//     - name: Java
                          +//       content: (== include google/foo/tutorial_java.md ==)
                          +//   rules:
                          +//   - selector: google.calendar.Calendar.Get
                          +//     description: >
                          +//       ...
                          +//   - selector: google.calendar.Calendar.Put
                          +//     description: >
                          +//       ...
                          +// 
                          +// Documentation is provided in markdown syntax. In addition to +// standard markdown features, definition lists, tables and fenced +// code blocks are supported. Section headers can be provided and are +// interpreted relative to the section nesting of the context where +// a documentation fragment is embedded. +// +// Documentation from the IDL is merged with documentation defined +// via the config at normalization time, where documentation provided +// by config rules overrides IDL provided. +// +// A number of constructs specific to the API platform are supported +// in documentation text. +// +// In order to reference a proto element, the following +// notation can be used: +//
                          [fully.qualified.proto.name][]
                          +// To override the display text used for the link, this can be used: +//
                          [display text][fully.qualified.proto.name]
                          +// Text can be excluded from doc using the following notation: +//
                          (-- internal comment --)
                          +// +// A few directives are available in documentation. Note that +// directives must appear on a single line to be properly +// identified. The `include` directive includes a markdown file from +// an external source: +//
                          (== include path/to/file ==)
                          +// The `resource_for` directive marks a message to be the resource of +// a collection in REST view. If it is not specified, tools attempt +// to infer the resource from the operations in a collection: +//
                          (== resource_for v1.shelves.books ==)
                          +// The directive `suppress_warning` does not directly affect documentation +// and is documented together with service config validation. +message Documentation { + // A short description of what the service does. The summary must be plain + // text. It becomes the overview of the service displayed in Google Cloud + // Console. + // NOTE: This field is equivalent to the standard field `description`. + string summary = 1; + + // The top level pages for the documentation set. + repeated Page pages = 5; + + // A list of documentation rules that apply to individual API elements. + // + // **NOTE:** All service configuration rules follow "last one wins" order. + repeated DocumentationRule rules = 3; + + // The URL to the root of documentation. + string documentation_root_url = 4; + + // Specifies the service root url if the default one (the service name + // from the yaml file) is not suitable. This can be seen in any fully + // specified service urls as well as sections that show a base that other + // urls are relative to. + string service_root_url = 6; + + // Declares a single overview page. For example: + //
                          documentation:
                          +  //   summary: ...
                          +  //   overview: (== include overview.md ==)
                          +  // 
                          + // This is a shortcut for the following declaration (using pages style): + //
                          documentation:
                          +  //   summary: ...
                          +  //   pages:
                          +  //   - name: Overview
                          +  //     content: (== include overview.md ==)
                          +  // 
                          + // Note: you cannot specify both `overview` field and `pages` field. + string overview = 2; +} + +// A documentation rule provides information about individual API elements. +message DocumentationRule { + // The selector is a comma-separated list of patterns for any element such as + // a method, a field, an enum value. Each pattern is a qualified name of the + // element which may end in "*", indicating a wildcard. Wildcards are only + // allowed at the end and for a whole component of the qualified name, + // i.e. "foo.*" is ok, but not "foo.b*" or "foo.*.bar". A wildcard will match + // one or more components. To specify a default for all applicable elements, + // the whole pattern "*" is used. + string selector = 1; + + // Description of the selected proto element (e.g. a message, a method, a + // 'service' definition, or a field). Defaults to leading & trailing comments + // taken from the proto source definition of the proto element. + string description = 2; + + // Deprecation description of the selected element(s). It can be provided if + // an element is marked as `deprecated`. + string deprecation_description = 3; +} + +// Represents a documentation page. A page can contain subpages to represent +// nested documentation set structure. +message Page { + // The name of the page. It will be used as an identity of the page to + // generate URI of the page, text of the link to this page in navigation, + // etc. The full page name (start from the root page name to this page + // concatenated with `.`) can be used as reference to the page in your + // documentation. For example: + //
                          pages:
                          +  // - name: Tutorial
                          +  //   content: (== include tutorial.md ==)
                          +  //   subpages:
                          +  //   - name: Java
                          +  //     content: (== include tutorial_java.md ==)
                          +  // 
                          + // You can reference `Java` page using Markdown reference link syntax: + // `[Java][Tutorial.Java]`. + string name = 1; + + // The Markdown content of the page. You can use (== include {path} + // ==) to include content from a Markdown file. The content can be + // used to produce the documentation page such as HTML format page. + string content = 2; + + // Subpages of this page. The order of subpages specified here will be + // honored in the generated docset. + repeated Page subpages = 3; +} diff --git a/node_modules/google-gax/build/protos/google/api/endpoint.proto b/node_modules/google-gax/build/protos/google/api/endpoint.proto new file mode 100644 index 0000000..7f6dca7 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/endpoint.proto @@ -0,0 +1,73 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option go_package = "google.golang.org/genproto/googleapis/api/serviceconfig;serviceconfig"; +option java_multiple_files = true; +option java_outer_classname = "EndpointProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// `Endpoint` describes a network address of a service that serves a set of +// APIs. It is commonly known as a service endpoint. A service may expose +// any number of service endpoints, and all service endpoints share the same +// service definition, such as quota limits and monitoring metrics. +// +// Example: +// +// type: google.api.Service +// name: library-example.googleapis.com +// endpoints: +// # Declares network address `https://library-example.googleapis.com` +// # for service `library-example.googleapis.com`. The `https` scheme +// # is implicit for all service endpoints. Other schemes may be +// # supported in the future. +// - name: library-example.googleapis.com +// allow_cors: false +// - name: content-staging-library-example.googleapis.com +// # Allows HTTP OPTIONS calls to be passed to the API frontend, for it +// # to decide whether the subsequent cross-origin request is allowed +// # to proceed. +// allow_cors: true +message Endpoint { + // The canonical name of this endpoint. + string name = 1; + + // Unimplemented. Dot not use. + // + // DEPRECATED: This field is no longer supported. Instead of using aliases, + // please specify multiple [google.api.Endpoint][google.api.Endpoint] for each + // of the intended aliases. + // + // Additional names that this endpoint will be hosted on. + repeated string aliases = 2 [deprecated = true]; + + // The specification of an Internet routable address of API frontend that will + // handle requests to this [API + // Endpoint](https://cloud.google.com/apis/design/glossary). It should be + // either a valid IPv4 address or a fully-qualified domain name. For example, + // "8.8.8.8" or "myservice.appspot.com". + string target = 101; + + // Allowing + // [CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing), aka + // cross-domain traffic, would allow the backends served from this endpoint to + // receive and respond to HTTP OPTIONS requests. The response will be used by + // the browser to determine whether the subsequent cross-origin request is + // allowed to proceed. + bool allow_cors = 5; +} diff --git a/node_modules/google-gax/build/protos/google/api/error_reason.proto b/node_modules/google-gax/build/protos/google/api/error_reason.proto new file mode 100644 index 0000000..cf80669 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/error_reason.proto @@ -0,0 +1,589 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option go_package = "google.golang.org/genproto/googleapis/api/error_reason;error_reason"; +option java_multiple_files = true; +option java_outer_classname = "ErrorReasonProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Defines the supported values for `google.rpc.ErrorInfo.reason` for the +// `googleapis.com` error domain. This error domain is reserved for [Service +// Infrastructure](https://cloud.google.com/service-infrastructure/docs/overview). +// For each error info of this domain, the metadata key "service" refers to the +// logical identifier of an API service, such as "pubsub.googleapis.com". The +// "consumer" refers to the entity that consumes an API Service. It typically is +// a Google project that owns the client application or the server resource, +// such as "projects/123". Other metadata keys are specific to each error +// reason. For more information, see the definition of the specific error +// reason. +enum ErrorReason { + // Do not use this default value. + ERROR_REASON_UNSPECIFIED = 0; + + // The request is calling a disabled service for a consumer. + // + // Example of an ErrorInfo when the consumer "projects/123" contacting + // "pubsub.googleapis.com" service which is disabled: + // + // { "reason": "SERVICE_DISABLED", + // "domain": "googleapis.com", + // "metadata": { + // "consumer": "projects/123", + // "service": "pubsub.googleapis.com" + // } + // } + // + // This response indicates the "pubsub.googleapis.com" has been disabled in + // "projects/123". + SERVICE_DISABLED = 1; + + // The request whose associated billing account is disabled. + // + // Example of an ErrorInfo when the consumer "projects/123" fails to contact + // "pubsub.googleapis.com" service because the associated billing account is + // disabled: + // + // { "reason": "BILLING_DISABLED", + // "domain": "googleapis.com", + // "metadata": { + // "consumer": "projects/123", + // "service": "pubsub.googleapis.com" + // } + // } + // + // This response indicates the billing account associated has been disabled. + BILLING_DISABLED = 2; + + // The request is denied because the provided [API + // key](https://cloud.google.com/docs/authentication/api-keys) is invalid. It + // may be in a bad format, cannot be found, or has been expired). + // + // Example of an ErrorInfo when the request is contacting + // "storage.googleapis.com" service with an invalid API key: + // + // { "reason": "API_KEY_INVALID", + // "domain": "googleapis.com", + // "metadata": { + // "service": "storage.googleapis.com", + // } + // } + API_KEY_INVALID = 3; + + // The request is denied because it violates [API key API + // restrictions](https://cloud.google.com/docs/authentication/api-keys#adding_api_restrictions). + // + // Example of an ErrorInfo when the consumer "projects/123" fails to call the + // "storage.googleapis.com" service because this service is restricted in the + // API key: + // + // { "reason": "API_KEY_SERVICE_BLOCKED", + // "domain": "googleapis.com", + // "metadata": { + // "consumer": "projects/123", + // "service": "storage.googleapis.com" + // } + // } + API_KEY_SERVICE_BLOCKED = 4; + + // The request is denied because it violates [API key HTTP + // restrictions](https://cloud.google.com/docs/authentication/api-keys#adding_http_restrictions). + // + // Example of an ErrorInfo when the consumer "projects/123" fails to call + // "storage.googleapis.com" service because the http referrer of the request + // violates API key HTTP restrictions: + // + // { "reason": "API_KEY_HTTP_REFERRER_BLOCKED", + // "domain": "googleapis.com", + // "metadata": { + // "consumer": "projects/123", + // "service": "storage.googleapis.com", + // } + // } + API_KEY_HTTP_REFERRER_BLOCKED = 7; + + // The request is denied because it violates [API key IP address + // restrictions](https://cloud.google.com/docs/authentication/api-keys#adding_application_restrictions). + // + // Example of an ErrorInfo when the consumer "projects/123" fails to call + // "storage.googleapis.com" service because the caller IP of the request + // violates API key IP address restrictions: + // + // { "reason": "API_KEY_IP_ADDRESS_BLOCKED", + // "domain": "googleapis.com", + // "metadata": { + // "consumer": "projects/123", + // "service": "storage.googleapis.com", + // } + // } + API_KEY_IP_ADDRESS_BLOCKED = 8; + + // The request is denied because it violates [API key Android application + // restrictions](https://cloud.google.com/docs/authentication/api-keys#adding_application_restrictions). + // + // Example of an ErrorInfo when the consumer "projects/123" fails to call + // "storage.googleapis.com" service because the request from the Android apps + // violates the API key Android application restrictions: + // + // { "reason": "API_KEY_ANDROID_APP_BLOCKED", + // "domain": "googleapis.com", + // "metadata": { + // "consumer": "projects/123", + // "service": "storage.googleapis.com" + // } + // } + API_KEY_ANDROID_APP_BLOCKED = 9; + + // The request is denied because it violates [API key iOS application + // restrictions](https://cloud.google.com/docs/authentication/api-keys#adding_application_restrictions). + // + // Example of an ErrorInfo when the consumer "projects/123" fails to call + // "storage.googleapis.com" service because the request from the iOS apps + // violates the API key iOS application restrictions: + // + // { "reason": "API_KEY_IOS_APP_BLOCKED", + // "domain": "googleapis.com", + // "metadata": { + // "consumer": "projects/123", + // "service": "storage.googleapis.com" + // } + // } + API_KEY_IOS_APP_BLOCKED = 13; + + // The request is denied because there is not enough rate quota for the + // consumer. + // + // Example of an ErrorInfo when the consumer "projects/123" fails to contact + // "pubsub.googleapis.com" service because consumer's rate quota usage has + // reached the maximum value set for the quota limit + // "ReadsPerMinutePerProject" on the quota metric + // "pubsub.googleapis.com/read_requests": + // + // { "reason": "RATE_LIMIT_EXCEEDED", + // "domain": "googleapis.com", + // "metadata": { + // "consumer": "projects/123", + // "service": "pubsub.googleapis.com", + // "quota_metric": "pubsub.googleapis.com/read_requests", + // "quota_limit": "ReadsPerMinutePerProject" + // } + // } + // + // Example of an ErrorInfo when the consumer "projects/123" checks quota on + // the service "dataflow.googleapis.com" and hits the organization quota + // limit "DefaultRequestsPerMinutePerOrganization" on the metric + // "dataflow.googleapis.com/default_requests". + // + // { "reason": "RATE_LIMIT_EXCEEDED", + // "domain": "googleapis.com", + // "metadata": { + // "consumer": "projects/123", + // "service": "dataflow.googleapis.com", + // "quota_metric": "dataflow.googleapis.com/default_requests", + // "quota_limit": "DefaultRequestsPerMinutePerOrganization" + // } + // } + RATE_LIMIT_EXCEEDED = 5; + + // The request is denied because there is not enough resource quota for the + // consumer. + // + // Example of an ErrorInfo when the consumer "projects/123" fails to contact + // "compute.googleapis.com" service because consumer's resource quota usage + // has reached the maximum value set for the quota limit "VMsPerProject" + // on the quota metric "compute.googleapis.com/vms": + // + // { "reason": "RESOURCE_QUOTA_EXCEEDED", + // "domain": "googleapis.com", + // "metadata": { + // "consumer": "projects/123", + // "service": "compute.googleapis.com", + // "quota_metric": "compute.googleapis.com/vms", + // "quota_limit": "VMsPerProject" + // } + // } + // + // Example of an ErrorInfo when the consumer "projects/123" checks resource + // quota on the service "dataflow.googleapis.com" and hits the organization + // quota limit "jobs-per-organization" on the metric + // "dataflow.googleapis.com/job_count". + // + // { "reason": "RESOURCE_QUOTA_EXCEEDED", + // "domain": "googleapis.com", + // "metadata": { + // "consumer": "projects/123", + // "service": "dataflow.googleapis.com", + // "quota_metric": "dataflow.googleapis.com/job_count", + // "quota_limit": "jobs-per-organization" + // } + // } + RESOURCE_QUOTA_EXCEEDED = 6; + + // The request whose associated billing account address is in a tax restricted + // location, violates the local tax restrictions when creating resources in + // the restricted region. + // + // Example of an ErrorInfo when creating the Cloud Storage Bucket in the + // container "projects/123" under a tax restricted region + // "locations/asia-northeast3": + // + // { "reason": "LOCATION_TAX_POLICY_VIOLATED", + // "domain": "googleapis.com", + // "metadata": { + // "consumer": "projects/123", + // "service": "storage.googleapis.com", + // "location": "locations/asia-northeast3" + // } + // } + // + // This response indicates creating the Cloud Storage Bucket in + // "locations/asia-northeast3" violates the location tax restriction. + LOCATION_TAX_POLICY_VIOLATED = 10; + + // The request is denied because the caller does not have required permission + // on the user project "projects/123" or the user project is invalid. For more + // information, check the [userProject System + // Parameters](https://cloud.google.com/apis/docs/system-parameters). + // + // Example of an ErrorInfo when the caller is calling Cloud Storage service + // with insufficient permissions on the user project: + // + // { "reason": "USER_PROJECT_DENIED", + // "domain": "googleapis.com", + // "metadata": { + // "consumer": "projects/123", + // "service": "storage.googleapis.com" + // } + // } + USER_PROJECT_DENIED = 11; + + // The request is denied because the consumer "projects/123" is suspended due + // to Terms of Service(Tos) violations. Check [Project suspension + // guidelines](https://cloud.google.com/resource-manager/docs/project-suspension-guidelines) + // for more information. + // + // Example of an ErrorInfo when calling Cloud Storage service with the + // suspended consumer "projects/123": + // + // { "reason": "CONSUMER_SUSPENDED", + // "domain": "googleapis.com", + // "metadata": { + // "consumer": "projects/123", + // "service": "storage.googleapis.com" + // } + // } + CONSUMER_SUSPENDED = 12; + + // The request is denied because the associated consumer is invalid. It may be + // in a bad format, cannot be found, or have been deleted. + // + // Example of an ErrorInfo when calling Cloud Storage service with the + // invalid consumer "projects/123": + // + // { "reason": "CONSUMER_INVALID", + // "domain": "googleapis.com", + // "metadata": { + // "consumer": "projects/123", + // "service": "storage.googleapis.com" + // } + // } + CONSUMER_INVALID = 14; + + // The request is denied because it violates [VPC Service + // Controls](https://cloud.google.com/vpc-service-controls/docs/overview). + // The 'uid' field is a random generated identifier that customer can use it + // to search the audit log for a request rejected by VPC Service Controls. For + // more information, please refer [VPC Service Controls + // Troubleshooting](https://cloud.google.com/vpc-service-controls/docs/troubleshooting#unique-id) + // + // Example of an ErrorInfo when the consumer "projects/123" fails to call + // Cloud Storage service because the request is prohibited by the VPC Service + // Controls. + // + // { "reason": "SECURITY_POLICY_VIOLATED", + // "domain": "googleapis.com", + // "metadata": { + // "uid": "123456789abcde", + // "consumer": "projects/123", + // "service": "storage.googleapis.com" + // } + // } + SECURITY_POLICY_VIOLATED = 15; + + // The request is denied because the provided access token has expired. + // + // Example of an ErrorInfo when the request is calling Cloud Storage service + // with an expired access token: + // + // { "reason": "ACCESS_TOKEN_EXPIRED", + // "domain": "googleapis.com", + // "metadata": { + // "service": "storage.googleapis.com", + // "method": "google.storage.v1.Storage.GetObject" + // } + // } + ACCESS_TOKEN_EXPIRED = 16; + + // The request is denied because the provided access token doesn't have at + // least one of the acceptable scopes required for the API. Please check + // [OAuth 2.0 Scopes for Google + // APIs](https://developers.google.com/identity/protocols/oauth2/scopes) for + // the list of the OAuth 2.0 scopes that you might need to request to access + // the API. + // + // Example of an ErrorInfo when the request is calling Cloud Storage service + // with an access token that is missing required scopes: + // + // { "reason": "ACCESS_TOKEN_SCOPE_INSUFFICIENT", + // "domain": "googleapis.com", + // "metadata": { + // "service": "storage.googleapis.com", + // "method": "google.storage.v1.Storage.GetObject" + // } + // } + ACCESS_TOKEN_SCOPE_INSUFFICIENT = 17; + + // The request is denied because the account associated with the provided + // access token is in an invalid state, such as disabled or deleted. + // For more information, see https://cloud.google.com/docs/authentication. + // + // Warning: For privacy reasons, the server may not be able to disclose the + // email address for some accounts. The client MUST NOT depend on the + // availability of the `email` attribute. + // + // Example of an ErrorInfo when the request is to the Cloud Storage API with + // an access token that is associated with a disabled or deleted [service + // account](http://cloud/iam/docs/service-accounts): + // + // { "reason": "ACCOUNT_STATE_INVALID", + // "domain": "googleapis.com", + // "metadata": { + // "service": "storage.googleapis.com", + // "method": "google.storage.v1.Storage.GetObject", + // "email": "user@123.iam.gserviceaccount.com" + // } + // } + ACCOUNT_STATE_INVALID = 18; + + // The request is denied because the type of the provided access token is not + // supported by the API being called. + // + // Example of an ErrorInfo when the request is to the Cloud Storage API with + // an unsupported token type. + // + // { "reason": "ACCESS_TOKEN_TYPE_UNSUPPORTED", + // "domain": "googleapis.com", + // "metadata": { + // "service": "storage.googleapis.com", + // "method": "google.storage.v1.Storage.GetObject" + // } + // } + ACCESS_TOKEN_TYPE_UNSUPPORTED = 19; + + // The request is denied because the request doesn't have any authentication + // credentials. For more information regarding the supported authentication + // strategies for Google Cloud APIs, see + // https://cloud.google.com/docs/authentication. + // + // Example of an ErrorInfo when the request is to the Cloud Storage API + // without any authentication credentials. + // + // { "reason": "CREDENTIALS_MISSING", + // "domain": "googleapis.com", + // "metadata": { + // "service": "storage.googleapis.com", + // "method": "google.storage.v1.Storage.GetObject" + // } + // } + CREDENTIALS_MISSING = 20; + + // The request is denied because the provided project owning the resource + // which acts as the [API + // consumer](https://cloud.google.com/apis/design/glossary#api_consumer) is + // invalid. It may be in a bad format or empty. + // + // Example of an ErrorInfo when the request is to the Cloud Functions API, + // but the offered resource project in the request in a bad format which can't + // perform the ListFunctions method. + // + // { "reason": "RESOURCE_PROJECT_INVALID", + // "domain": "googleapis.com", + // "metadata": { + // "service": "cloudfunctions.googleapis.com", + // "method": + // "google.cloud.functions.v1.CloudFunctionsService.ListFunctions" + // } + // } + RESOURCE_PROJECT_INVALID = 21; + + // The request is denied because the provided session cookie is missing, + // invalid or failed to decode. + // + // Example of an ErrorInfo when the request is calling Cloud Storage service + // with a SID cookie which can't be decoded. + // + // { "reason": "SESSION_COOKIE_INVALID", + // "domain": "googleapis.com", + // "metadata": { + // "service": "storage.googleapis.com", + // "method": "google.storage.v1.Storage.GetObject", + // "cookie": "SID" + // } + // } + SESSION_COOKIE_INVALID = 23; + + // The request is denied because the user is from a Google Workspace customer + // that blocks their users from accessing a particular service. + // + // Example scenario: https://support.google.com/a/answer/9197205?hl=en + // + // Example of an ErrorInfo when access to Google Cloud Storage service is + // blocked by the Google Workspace administrator: + // + // { "reason": "USER_BLOCKED_BY_ADMIN", + // "domain": "googleapis.com", + // "metadata": { + // "service": "storage.googleapis.com", + // "method": "google.storage.v1.Storage.GetObject", + // } + // } + USER_BLOCKED_BY_ADMIN = 24; + + // The request is denied because the resource service usage is restricted + // by administrators according to the organization policy constraint. + // For more information see + // https://cloud.google.com/resource-manager/docs/organization-policy/restricting-services. + // + // Example of an ErrorInfo when access to Google Cloud Storage service is + // restricted by Resource Usage Restriction policy: + // + // { "reason": "RESOURCE_USAGE_RESTRICTION_VIOLATED", + // "domain": "googleapis.com", + // "metadata": { + // "consumer": "projects/project-123", + // "service": "storage.googleapis.com" + // } + // } + RESOURCE_USAGE_RESTRICTION_VIOLATED = 25; + + // Unimplemented. Do not use. + // + // The request is denied because it contains unsupported system parameters in + // URL query parameters or HTTP headers. For more information, + // see https://cloud.google.com/apis/docs/system-parameters + // + // Example of an ErrorInfo when access "pubsub.googleapis.com" service with + // a request header of "x-goog-user-ip": + // + // { "reason": "SYSTEM_PARAMETER_UNSUPPORTED", + // "domain": "googleapis.com", + // "metadata": { + // "service": "pubsub.googleapis.com" + // "parameter": "x-goog-user-ip" + // } + // } + SYSTEM_PARAMETER_UNSUPPORTED = 26; + + // The request is denied because it violates Org Restriction: the requested + // resource does not belong to allowed organizations specified in + // "X-Goog-Allowed-Resources" header. + // + // Example of an ErrorInfo when accessing a GCP resource that is restricted by + // Org Restriction for "pubsub.googleapis.com" service. + // + // { + // reason: "ORG_RESTRICTION_VIOLATION" + // domain: "googleapis.com" + // metadata { + // "consumer":"projects/123456" + // "service": "pubsub.googleapis.com" + // } + // } + ORG_RESTRICTION_VIOLATION = 27; + + // The request is denied because "X-Goog-Allowed-Resources" header is in a bad + // format. + // + // Example of an ErrorInfo when + // accessing "pubsub.googleapis.com" service with an invalid + // "X-Goog-Allowed-Resources" request header. + // + // { + // reason: "ORG_RESTRICTION_HEADER_INVALID" + // domain: "googleapis.com" + // metadata { + // "consumer":"projects/123456" + // "service": "pubsub.googleapis.com" + // } + // } + ORG_RESTRICTION_HEADER_INVALID = 28; + + // Unimplemented. Do not use. + // + // The request is calling a service that is not visible to the consumer. + // + // Example of an ErrorInfo when the consumer "projects/123" contacting + // "pubsub.googleapis.com" service which is not visible to the consumer. + // + // { "reason": "SERVICE_NOT_VISIBLE", + // "domain": "googleapis.com", + // "metadata": { + // "consumer": "projects/123", + // "service": "pubsub.googleapis.com" + // } + // } + // + // This response indicates the "pubsub.googleapis.com" is not visible to + // "projects/123" (or it may not exist). + SERVICE_NOT_VISIBLE = 29; + + // The request is related to a project for which GCP access is suspended. + // + // Example of an ErrorInfo when the consumer "projects/123" fails to contact + // "pubsub.googleapis.com" service because GCP access is suspended: + // + // { "reason": "GCP_SUSPENDED", + // "domain": "googleapis.com", + // "metadata": { + // "consumer": "projects/123", + // "service": "pubsub.googleapis.com" + // } + // } + // + // This response indicates the associated GCP account has been suspended. + GCP_SUSPENDED = 30; + + // The request violates the location policies when creating resources in + // the restricted region. + // + // Example of an ErrorInfo when creating the Cloud Storage Bucket by + // "projects/123" for service storage.googleapis.com: + // + // { "reason": "LOCATION_POLICY_VIOLATED", + // "domain": "googleapis.com", + // "metadata": { + // "consumer": "projects/123", + // "service": "storage.googleapis.com", + // } + // } + // + // This response indicates creating the Cloud Storage Bucket in + // "locations/asia-northeast3" violates at least one location policy. + // The troubleshooting guidance is provided in the Help links. + LOCATION_POLICY_VIOLATED = 31; +} diff --git a/node_modules/google-gax/build/protos/google/api/expr/conformance/v1alpha1/conformance_service.proto b/node_modules/google-gax/build/protos/google/api/expr/conformance/v1alpha1/conformance_service.proto new file mode 100644 index 0000000..c1ad7aa --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/expr/conformance/v1alpha1/conformance_service.proto @@ -0,0 +1,183 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.expr.conformance.v1alpha1; + +import "google/api/client.proto"; +import "google/api/expr/v1alpha1/checked.proto"; +import "google/api/expr/v1alpha1/eval.proto"; +import "google/api/expr/v1alpha1/syntax.proto"; +import "google/rpc/status.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/expr/conformance/v1alpha1;confpb"; +option java_multiple_files = true; +option java_outer_classname = "ConformanceServiceProto"; +option java_package = "com.google.api.expr.conformance.v1alpha1"; + +// Access a CEL implementation from another process or machine. +// A CEL implementation is decomposed as a parser, a static checker, +// and an evaluator. Every CEL implementation is expected to provide +// a server for this API. The API will be used for conformance testing +// and other utilities. +service ConformanceService { + option (google.api.default_host) = "cel.googleapis.com"; + + // Transforms CEL source text into a parsed representation. + rpc Parse(ParseRequest) returns (ParseResponse) { + } + + // Runs static checks on a parsed CEL representation and return + // an annotated representation, or a set of issues. + rpc Check(CheckRequest) returns (CheckResponse) { + } + + // Evaluates a parsed or annotation CEL representation given + // values of external bindings. + rpc Eval(EvalRequest) returns (EvalResponse) { + } +} + +// Request message for the Parse method. +message ParseRequest { + // Required. Source text in CEL syntax. + string cel_source = 1; + + // Tag for version of CEL syntax, for future use. + string syntax_version = 2; + + // File or resource for source text, used in [SourceInfo][google.api.SourceInfo]. + string source_location = 3; + + // Prevent macro expansion. See "Macros" in Language Defiinition. + bool disable_macros = 4; +} + +// Response message for the Parse method. +message ParseResponse { + // The parsed representation, or unset if parsing failed. + google.api.expr.v1alpha1.ParsedExpr parsed_expr = 1; + + // Any number of issues with [StatusDetails][] as the details. + repeated google.rpc.Status issues = 2; +} + +// Request message for the Check method. +message CheckRequest { + // Required. The parsed representation of the CEL program. + google.api.expr.v1alpha1.ParsedExpr parsed_expr = 1; + + // Declarations of types for external variables and functions. + // Required if program uses external variables or functions + // not in the default environment. + repeated google.api.expr.v1alpha1.Decl type_env = 2; + + // The protocol buffer context. See "Name Resolution" in the + // Language Definition. + string container = 3; + + // If true, use only the declarations in [type_env][google.api.expr.conformance.v1alpha1.CheckRequest.type_env]. If false (default), + // add declarations for the standard definitions to the type environment. See + // "Standard Definitions" in the Language Definition. + bool no_std_env = 4; +} + +// Response message for the Check method. +message CheckResponse { + // The annotated representation, or unset if checking failed. + google.api.expr.v1alpha1.CheckedExpr checked_expr = 1; + + // Any number of issues with [StatusDetails][] as the details. + repeated google.rpc.Status issues = 2; +} + +// Request message for the Eval method. +message EvalRequest { + // Required. Either the parsed or annotated representation of the CEL program. + oneof expr_kind { + // Evaluate based on the parsed representation. + google.api.expr.v1alpha1.ParsedExpr parsed_expr = 1; + + // Evaluate based on the checked representation. + google.api.expr.v1alpha1.CheckedExpr checked_expr = 2; + } + + // Bindings for the external variables. The types SHOULD be compatible + // with the type environment in [CheckRequest][google.api.expr.conformance.v1alpha1.CheckRequest], if checked. + map bindings = 3; + + // SHOULD be the same container as used in [CheckRequest][google.api.expr.conformance.v1alpha1.CheckRequest], if checked. + string container = 4; +} + +// Response message for the Eval method. +message EvalResponse { + // The execution result, or unset if execution couldn't start. + google.api.expr.v1alpha1.ExprValue result = 1; + + // Any number of issues with [StatusDetails][] as the details. + // Note that CEL execution errors are reified into [ExprValue][]. + // Nevertheless, we'll allow out-of-band issues to be raised, + // which also makes the replies more regular. + repeated google.rpc.Status issues = 2; +} + +// A specific position in source. +message SourcePosition { + // The source location name (e.g. file name). + string location = 1; + + // The UTF-8 code unit offset. + int32 offset = 2; + + // The 1-based index of the starting line in the source text + // where the issue occurs, or 0 if unknown. + int32 line = 3; + + // The 0-based index of the starting position within the line of source text + // where the issue occurs. Only meaningful if line is nonzero. + int32 column = 4; +} + +// Warnings or errors in service execution are represented by +// [google.rpc.Status][google.rpc.Status] messages, with the following message +// in the details field. +message IssueDetails { + // Severities of issues. + enum Severity { + // An unspecified severity. + SEVERITY_UNSPECIFIED = 0; + + // Deprecation issue for statements and method that may no longer be + // supported or maintained. + DEPRECATION = 1; + + // Warnings such as: unused variables. + WARNING = 2; + + // Errors such as: unmatched curly braces or variable redefinition. + ERROR = 3; + } + + // The severity of the issue. + Severity severity = 1; + + // Position in the source, if known. + SourcePosition position = 2; + + // Expression ID from [Expr][], 0 if unknown. + int64 id = 3; +} diff --git a/node_modules/google-gax/build/protos/google/api/expr/v1alpha1/checked.proto b/node_modules/google-gax/build/protos/google/api/expr/v1alpha1/checked.proto new file mode 100644 index 0000000..031a651 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/expr/v1alpha1/checked.proto @@ -0,0 +1,343 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.expr.v1alpha1; + +import "google/api/expr/v1alpha1/syntax.proto"; +import "google/protobuf/empty.proto"; +import "google/protobuf/struct.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/expr/v1alpha1;expr"; +option java_multiple_files = true; +option java_outer_classname = "DeclProto"; +option java_package = "com.google.api.expr.v1alpha1"; + +// Protos for representing CEL declarations and typed checked expressions. + +// A CEL expression which has been successfully type checked. +message CheckedExpr { + // A map from expression ids to resolved references. + // + // The following entries are in this table: + // + // - An Ident or Select expression is represented here if it resolves to a + // declaration. For instance, if `a.b.c` is represented by + // `select(select(id(a), b), c)`, and `a.b` resolves to a declaration, + // while `c` is a field selection, then the reference is attached to the + // nested select expression (but not to the id or or the outer select). + // In turn, if `a` resolves to a declaration and `b.c` are field selections, + // the reference is attached to the ident expression. + // - Every Call expression has an entry here, identifying the function being + // called. + // - Every CreateStruct expression for a message has an entry, identifying + // the message. + map reference_map = 2; + + // A map from expression ids to types. + // + // Every expression node which has a type different than DYN has a mapping + // here. If an expression has type DYN, it is omitted from this map to save + // space. + map type_map = 3; + + // The source info derived from input that generated the parsed `expr` and + // any optimizations made during the type-checking pass. + SourceInfo source_info = 5; + + // The expr version indicates the major / minor version number of the `expr` + // representation. + // + // The most common reason for a version change will be to indicate to the CEL + // runtimes that transformations have been performed on the expr during static + // analysis. In some cases, this will save the runtime the work of applying + // the same or similar transformations prior to evaluation. + string expr_version = 6; + + // The checked expression. Semantically equivalent to the parsed `expr`, but + // may have structural differences. + Expr expr = 4; +} + +// Represents a CEL type. +message Type { + // List type with typed elements, e.g. `list`. + message ListType { + // The element type. + Type elem_type = 1; + } + + // Map type with parameterized key and value types, e.g. `map`. + message MapType { + // The type of the key. + Type key_type = 1; + + // The type of the value. + Type value_type = 2; + } + + // Function type with result and arg types. + message FunctionType { + // Result type of the function. + Type result_type = 1; + + // Argument types of the function. + repeated Type arg_types = 2; + } + + // Application defined abstract type. + message AbstractType { + // The fully qualified name of this abstract type. + string name = 1; + + // Parameter types for this abstract type. + repeated Type parameter_types = 2; + } + + // CEL primitive types. + enum PrimitiveType { + // Unspecified type. + PRIMITIVE_TYPE_UNSPECIFIED = 0; + + // Boolean type. + BOOL = 1; + + // Int64 type. + // + // Proto-based integer values are widened to int64. + INT64 = 2; + + // Uint64 type. + // + // Proto-based unsigned integer values are widened to uint64. + UINT64 = 3; + + // Double type. + // + // Proto-based float values are widened to double values. + DOUBLE = 4; + + // String type. + STRING = 5; + + // Bytes type. + BYTES = 6; + } + + // Well-known protobuf types treated with first-class support in CEL. + enum WellKnownType { + // Unspecified type. + WELL_KNOWN_TYPE_UNSPECIFIED = 0; + + // Well-known protobuf.Any type. + // + // Any types are a polymorphic message type. During type-checking they are + // treated like `DYN` types, but at runtime they are resolved to a specific + // message type specified at evaluation time. + ANY = 1; + + // Well-known protobuf.Timestamp type, internally referenced as `timestamp`. + TIMESTAMP = 2; + + // Well-known protobuf.Duration type, internally referenced as `duration`. + DURATION = 3; + } + + // The kind of type. + oneof type_kind { + // Dynamic type. + google.protobuf.Empty dyn = 1; + + // Null value. + google.protobuf.NullValue null = 2; + + // Primitive types: `true`, `1u`, `-2.0`, `'string'`, `b'bytes'`. + PrimitiveType primitive = 3; + + // Wrapper of a primitive type, e.g. `google.protobuf.Int64Value`. + PrimitiveType wrapper = 4; + + // Well-known protobuf type such as `google.protobuf.Timestamp`. + WellKnownType well_known = 5; + + // Parameterized list with elements of `list_type`, e.g. `list`. + ListType list_type = 6; + + // Parameterized map with typed keys and values. + MapType map_type = 7; + + // Function type. + FunctionType function = 8; + + // Protocol buffer message type. + // + // The `message_type` string specifies the qualified message type name. For + // example, `google.plus.Profile`. + string message_type = 9; + + // Type param type. + // + // The `type_param` string specifies the type parameter name, e.g. `list` + // would be a `list_type` whose element type was a `type_param` type + // named `E`. + string type_param = 10; + + // Type type. + // + // The `type` value specifies the target type. e.g. int is type with a + // target type of `Primitive.INT`. + Type type = 11; + + // Error type. + // + // During type-checking if an expression is an error, its type is propagated + // as the `ERROR` type. This permits the type-checker to discover other + // errors present in the expression. + google.protobuf.Empty error = 12; + + // Abstract, application defined type. + AbstractType abstract_type = 14; + } +} + +// Represents a declaration of a named value or function. +// +// A declaration is part of the contract between the expression, the agent +// evaluating that expression, and the caller requesting evaluation. +message Decl { + // Identifier declaration which specifies its type and optional `Expr` value. + // + // An identifier without a value is a declaration that must be provided at + // evaluation time. An identifier with a value should resolve to a constant, + // but may be used in conjunction with other identifiers bound at evaluation + // time. + message IdentDecl { + // Required. The type of the identifier. + Type type = 1; + + // The constant value of the identifier. If not specified, the identifier + // must be supplied at evaluation time. + Constant value = 2; + + // Documentation string for the identifier. + string doc = 3; + } + + // Function declaration specifies one or more overloads which indicate the + // function's parameter types and return type. + // + // Functions have no observable side-effects (there may be side-effects like + // logging which are not observable from CEL). + message FunctionDecl { + // An overload indicates a function's parameter types and return type, and + // may optionally include a function body described in terms of + // [Expr][google.api.expr.v1alpha1.Expr] values. + // + // Functions overloads are declared in either a function or method + // call-style. For methods, the `params[0]` is the expected type of the + // target receiver. + // + // Overloads must have non-overlapping argument types after erasure of all + // parameterized type variables (similar as type erasure in Java). + message Overload { + // Required. Globally unique overload name of the function which reflects + // the function name and argument types. + // + // This will be used by a [Reference][google.api.expr.v1alpha1.Reference] + // to indicate the `overload_id` that was resolved for the function + // `name`. + string overload_id = 1; + + // List of function parameter [Type][google.api.expr.v1alpha1.Type] + // values. + // + // Param types are disjoint after generic type parameters have been + // replaced with the type `DYN`. Since the `DYN` type is compatible with + // any other type, this means that if `A` is a type parameter, the + // function types `int` and `int` are not disjoint. Likewise, + // `map` is not disjoint from `map`. + // + // When the `result_type` of a function is a generic type param, the + // type param name also appears as the `type` of on at least one params. + repeated Type params = 2; + + // The type param names associated with the function declaration. + // + // For example, `function ex(K key, map map) : V` would yield + // the type params of `K, V`. + repeated string type_params = 3; + + // Required. The result type of the function. For example, the operator + // `string.isEmpty()` would have `result_type` of `kind: BOOL`. + Type result_type = 4; + + // Whether the function is to be used in a method call-style `x.f(...)` + // or a function call-style `f(x, ...)`. + // + // For methods, the first parameter declaration, `params[0]` is the + // expected type of the target receiver. + bool is_instance_function = 5; + + // Documentation string for the overload. + string doc = 6; + } + + // Required. List of function overloads, must contain at least one overload. + repeated Overload overloads = 1; + } + + // The fully qualified name of the declaration. + // + // Declarations are organized in containers and this represents the full path + // to the declaration in its container, as in `google.api.expr.Decl`. + // + // Declarations used as + // [FunctionDecl.Overload][google.api.expr.v1alpha1.Decl.FunctionDecl.Overload] + // parameters may or may not have a name depending on whether the overload is + // function declaration or a function definition containing a result + // [Expr][google.api.expr.v1alpha1.Expr]. + string name = 1; + + // Required. The declaration kind. + oneof decl_kind { + // Identifier declaration. + IdentDecl ident = 2; + + // Function declaration. + FunctionDecl function = 3; + } +} + +// Describes a resolved reference to a declaration. +message Reference { + // The fully qualified name of the declaration. + string name = 1; + + // For references to functions, this is a list of `Overload.overload_id` + // values which match according to typing rules. + // + // If the list has more than one element, overload resolution among the + // presented candidates must happen at runtime because of dynamic types. The + // type checker attempts to narrow down this list as much as possible. + // + // Empty if this is not a reference to a + // [Decl.FunctionDecl][google.api.expr.v1alpha1.Decl.FunctionDecl]. + repeated string overload_id = 3; + + // For references to constants, this may contain the value of the + // constant if known at compile time. + Constant value = 4; +} diff --git a/node_modules/google-gax/build/protos/google/api/expr/v1alpha1/eval.proto b/node_modules/google-gax/build/protos/google/api/expr/v1alpha1/eval.proto new file mode 100644 index 0000000..8af43be --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/expr/v1alpha1/eval.proto @@ -0,0 +1,118 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.expr.v1alpha1; + +import "google/api/expr/v1alpha1/value.proto"; +import "google/rpc/status.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/expr/v1alpha1;expr"; +option java_multiple_files = true; +option java_outer_classname = "EvalProto"; +option java_package = "com.google.api.expr.v1alpha1"; + +// The state of an evaluation. +// +// Can represent an inital, partial, or completed state of evaluation. +message EvalState { + // A single evalution result. + message Result { + // The id of the expression this result if for. + int64 expr = 1; + + // The index in `values` of the resulting value. + int64 value = 2; + } + + // The unique values referenced in this message. + repeated ExprValue values = 1; + + // An ordered list of results. + // + // Tracks the flow of evaluation through the expression. + // May be sparse. + repeated Result results = 3; +} + +// The value of an evaluated expression. +message ExprValue { + // An expression can resolve to a value, error or unknown. + oneof kind { + // A concrete value. + Value value = 1; + + // The set of errors in the critical path of evalution. + // + // Only errors in the critical path are included. For example, + // `( || true) && ` will only result in ``, + // while ` || ` will result in both `` and + // ``. + // + // Errors cause by the presence of other errors are not included in the + // set. For example `.foo`, `foo()`, and ` + 1` will + // only result in ``. + // + // Multiple errors *might* be included when evaluation could result + // in different errors. For example ` + ` and + // `foo(, )` may result in ``, `` or both. + // The exact subset of errors included for this case is unspecified and + // depends on the implementation details of the evaluator. + ErrorSet error = 2; + + // The set of unknowns in the critical path of evaluation. + // + // Unknown behaves identically to Error with regards to propagation. + // Specifically, only unknowns in the critical path are included, unknowns + // caused by the presence of other unknowns are not included, and multiple + // unknowns *might* be included included when evaluation could result in + // different unknowns. For example: + // + // ( || true) && -> + // || -> + // .foo -> + // foo() -> + // + -> or + // + // Unknown takes precidence over Error in cases where a `Value` can short + // circuit the result: + // + // || -> + // && -> + // + // Errors take precidence in all other cases: + // + // + -> + // foo(, ) -> + UnknownSet unknown = 3; + } +} + +// A set of errors. +// +// The errors included depend on the context. See `ExprValue.error`. +message ErrorSet { + // The errors in the set. + repeated google.rpc.Status errors = 1; +} + +// A set of expressions for which the value is unknown. +// +// The unknowns included depend on the context. See `ExprValue.unknown`. +message UnknownSet { + // The ids of the expressions with unknown values. + repeated int64 exprs = 1; +} diff --git a/node_modules/google-gax/build/protos/google/api/expr/v1alpha1/explain.proto b/node_modules/google-gax/build/protos/google/api/expr/v1alpha1/explain.proto new file mode 100644 index 0000000..8b2cb7e --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/expr/v1alpha1/explain.proto @@ -0,0 +1,53 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.expr.v1alpha1; + +import "google/api/expr/v1alpha1/value.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/expr/v1alpha1;expr"; +option java_multiple_files = true; +option java_outer_classname = "ExplainProto"; +option java_package = "com.google.api.expr.v1alpha1"; + +// Values of intermediate expressions produced when evaluating expression. +// Deprecated, use `EvalState` instead. +message Explain { + option deprecated = true; + + // ID and value index of one step. + message ExprStep { + // ID of corresponding Expr node. + int64 id = 1; + + // Index of the value in the values list. + int32 value_index = 2; + } + + // All of the observed values. + // + // The field value_index is an index in the values list. + // Separating values from steps is needed to remove redundant values. + repeated Value values = 1; + + // List of steps. + // + // Repeated evaluations of the same expression generate new ExprStep + // instances. The order of such ExprStep instances matches the order of + // elements returned by Comprehension.iter_range. + repeated ExprStep expr_steps = 2; +} diff --git a/node_modules/google-gax/build/protos/google/api/expr/v1alpha1/syntax.proto b/node_modules/google-gax/build/protos/google/api/expr/v1alpha1/syntax.proto new file mode 100644 index 0000000..4920a13 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/expr/v1alpha1/syntax.proto @@ -0,0 +1,400 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.expr.v1alpha1; + +import "google/protobuf/duration.proto"; +import "google/protobuf/struct.proto"; +import "google/protobuf/timestamp.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/expr/v1alpha1;expr"; +option java_multiple_files = true; +option java_outer_classname = "SyntaxProto"; +option java_package = "com.google.api.expr.v1alpha1"; + +// A representation of the abstract syntax of the Common Expression Language. + +// An expression together with source information as returned by the parser. +message ParsedExpr { + // The parsed expression. + Expr expr = 2; + + // The source info derived from input that generated the parsed `expr`. + SourceInfo source_info = 3; +} + +// An abstract representation of a common expression. +// +// Expressions are abstractly represented as a collection of identifiers, +// select statements, function calls, literals, and comprehensions. All +// operators with the exception of the '.' operator are modelled as function +// calls. This makes it easy to represent new operators into the existing AST. +// +// All references within expressions must resolve to a +// [Decl][google.api.expr.v1alpha1.Decl] provided at type-check for an +// expression to be valid. A reference may either be a bare identifier `name` or +// a qualified identifier `google.api.name`. References may either refer to a +// value or a function declaration. +// +// For example, the expression `google.api.name.startsWith('expr')` references +// the declaration `google.api.name` within a +// [Expr.Select][google.api.expr.v1alpha1.Expr.Select] expression, and the +// function declaration `startsWith`. +message Expr { + // An identifier expression. e.g. `request`. + message Ident { + // Required. Holds a single, unqualified identifier, possibly preceded by a + // '.'. + // + // Qualified names are represented by the + // [Expr.Select][google.api.expr.v1alpha1.Expr.Select] expression. + string name = 1; + } + + // A field selection expression. e.g. `request.auth`. + message Select { + // Required. The target of the selection expression. + // + // For example, in the select expression `request.auth`, the `request` + // portion of the expression is the `operand`. + Expr operand = 1; + + // Required. The name of the field to select. + // + // For example, in the select expression `request.auth`, the `auth` portion + // of the expression would be the `field`. + string field = 2; + + // Whether the select is to be interpreted as a field presence test. + // + // This results from the macro `has(request.auth)`. + bool test_only = 3; + } + + // A call expression, including calls to predefined functions and operators. + // + // For example, `value == 10`, `size(map_value)`. + message Call { + // The target of an method call-style expression. For example, `x` in + // `x.f()`. + Expr target = 1; + + // Required. The name of the function or method being called. + string function = 2; + + // The arguments. + repeated Expr args = 3; + } + + // A list creation expression. + // + // Lists may either be homogenous, e.g. `[1, 2, 3]`, or heterogeneous, e.g. + // `dyn([1, 'hello', 2.0])` + message CreateList { + // The elements part of the list. + repeated Expr elements = 1; + + // The indices within the elements list which are marked as optional + // elements. + // + // When an optional-typed value is present, the value it contains + // is included in the list. If the optional-typed value is absent, the list + // element is omitted from the CreateList result. + repeated int32 optional_indices = 2; + } + + // A map or message creation expression. + // + // Maps are constructed as `{'key_name': 'value'}`. Message construction is + // similar, but prefixed with a type name and composed of field ids: + // `types.MyType{field_id: 'value'}`. + message CreateStruct { + // Represents an entry. + message Entry { + // Required. An id assigned to this node by the parser which is unique + // in a given expression tree. This is used to associate type + // information and other attributes to the node. + int64 id = 1; + + // The `Entry` key kinds. + oneof key_kind { + // The field key for a message creator statement. + string field_key = 2; + + // The key expression for a map creation statement. + Expr map_key = 3; + } + + // Required. The value assigned to the key. + // + // If the optional_entry field is true, the expression must resolve to an + // optional-typed value. If the optional value is present, the key will be + // set; however, if the optional value is absent, the key will be unset. + Expr value = 4; + + // Whether the key-value pair is optional. + bool optional_entry = 5; + } + + // The type name of the message to be created, empty when creating map + // literals. + string message_name = 1; + + // The entries in the creation expression. + repeated Entry entries = 2; + } + + // A comprehension expression applied to a list or map. + // + // Comprehensions are not part of the core syntax, but enabled with macros. + // A macro matches a specific call signature within a parsed AST and replaces + // the call with an alternate AST block. Macro expansion happens at parse + // time. + // + // The following macros are supported within CEL: + // + // Aggregate type macros may be applied to all elements in a list or all keys + // in a map: + // + // * `all`, `exists`, `exists_one` - test a predicate expression against + // the inputs and return `true` if the predicate is satisfied for all, + // any, or only one value `list.all(x, x < 10)`. + // * `filter` - test a predicate expression against the inputs and return + // the subset of elements which satisfy the predicate: + // `payments.filter(p, p > 1000)`. + // * `map` - apply an expression to all elements in the input and return the + // output aggregate type: `[1, 2, 3].map(i, i * i)`. + // + // The `has(m.x)` macro tests whether the property `x` is present in struct + // `m`. The semantics of this macro depend on the type of `m`. For proto2 + // messages `has(m.x)` is defined as 'defined, but not set`. For proto3, the + // macro tests whether the property is set to its default. For map and struct + // types, the macro tests whether the property `x` is defined on `m`. + message Comprehension { + // The name of the iteration variable. + string iter_var = 1; + + // The range over which var iterates. + Expr iter_range = 2; + + // The name of the variable used for accumulation of the result. + string accu_var = 3; + + // The initial value of the accumulator. + Expr accu_init = 4; + + // An expression which can contain iter_var and accu_var. + // + // Returns false when the result has been computed and may be used as + // a hint to short-circuit the remainder of the comprehension. + Expr loop_condition = 5; + + // An expression which can contain iter_var and accu_var. + // + // Computes the next value of accu_var. + Expr loop_step = 6; + + // An expression which can contain accu_var. + // + // Computes the result. + Expr result = 7; + } + + // Required. An id assigned to this node by the parser which is unique in a + // given expression tree. This is used to associate type information and other + // attributes to a node in the parse tree. + int64 id = 2; + + // Required. Variants of expressions. + oneof expr_kind { + // A literal expression. + Constant const_expr = 3; + + // An identifier expression. + Ident ident_expr = 4; + + // A field selection expression, e.g. `request.auth`. + Select select_expr = 5; + + // A call expression, including calls to predefined functions and operators. + Call call_expr = 6; + + // A list creation expression. + CreateList list_expr = 7; + + // A map or message creation expression. + CreateStruct struct_expr = 8; + + // A comprehension expression. + Comprehension comprehension_expr = 9; + } +} + +// Represents a primitive literal. +// +// Named 'Constant' here for backwards compatibility. +// +// This is similar as the primitives supported in the well-known type +// `google.protobuf.Value`, but richer so it can represent CEL's full range of +// primitives. +// +// Lists and structs are not included as constants as these aggregate types may +// contain [Expr][google.api.expr.v1alpha1.Expr] elements which require +// evaluation and are thus not constant. +// +// Examples of literals include: `"hello"`, `b'bytes'`, `1u`, `4.2`, `-2`, +// `true`, `null`. +message Constant { + // Required. The valid constant kinds. + oneof constant_kind { + // null value. + google.protobuf.NullValue null_value = 1; + + // boolean value. + bool bool_value = 2; + + // int64 value. + int64 int64_value = 3; + + // uint64 value. + uint64 uint64_value = 4; + + // double value. + double double_value = 5; + + // string value. + string string_value = 6; + + // bytes value. + bytes bytes_value = 7; + + // protobuf.Duration value. + // + // Deprecated: duration is no longer considered a builtin cel type. + google.protobuf.Duration duration_value = 8 [deprecated = true]; + + // protobuf.Timestamp value. + // + // Deprecated: timestamp is no longer considered a builtin cel type. + google.protobuf.Timestamp timestamp_value = 9 [deprecated = true]; + } +} + +// Source information collected at parse time. +message SourceInfo { + // An extension that was requested for the source expression. + message Extension { + // Version + message Version { + // Major version changes indicate different required support level from + // the required components. + int64 major = 1; + + // Minor version changes must not change the observed behavior from + // existing implementations, but may be provided informationally. + int64 minor = 2; + } + + // CEL component specifier. + enum Component { + // Unspecified, default. + COMPONENT_UNSPECIFIED = 0; + + // Parser. Converts a CEL string to an AST. + COMPONENT_PARSER = 1; + + // Type checker. Checks that references in an AST are defined and types + // agree. + COMPONENT_TYPE_CHECKER = 2; + + // Runtime. Evaluates a parsed and optionally checked CEL AST against a + // context. + COMPONENT_RUNTIME = 3; + } + + // Identifier for the extension. Example: constant_folding + string id = 1; + + // If set, the listed components must understand the extension for the + // expression to evaluate correctly. + // + // This field has set semantics, repeated values should be deduplicated. + repeated Component affected_components = 2; + + // Version info. May be skipped if it isn't meaningful for the extension. + // (for example constant_folding might always be v0.0). + Version version = 3; + } + + // The syntax version of the source, e.g. `cel1`. + string syntax_version = 1; + + // The location name. All position information attached to an expression is + // relative to this location. + // + // The location could be a file, UI element, or similar. For example, + // `acme/app/AnvilPolicy.cel`. + string location = 2; + + // Monotonically increasing list of code point offsets where newlines + // `\n` appear. + // + // The line number of a given position is the index `i` where for a given + // `id` the `line_offsets[i] < id_positions[id] < line_offsets[i+1]`. The + // column may be derivd from `id_positions[id] - line_offsets[i]`. + repeated int32 line_offsets = 3; + + // A map from the parse node id (e.g. `Expr.id`) to the code point offset + // within the source. + map positions = 4; + + // A map from the parse node id where a macro replacement was made to the + // call `Expr` that resulted in a macro expansion. + // + // For example, `has(value.field)` is a function call that is replaced by a + // `test_only` field selection in the AST. Likewise, the call + // `list.exists(e, e > 10)` translates to a comprehension expression. The key + // in the map corresponds to the expression id of the expanded macro, and the + // value is the call `Expr` that was replaced. + map macro_calls = 5; + + // A list of tags for extensions that were used while parsing or type checking + // the source expression. For example, optimizations that require special + // runtime support may be specified. + // + // These are used to check feature support between components in separate + // implementations. This can be used to either skip redundant work or + // report an error if the extension is unsupported. + repeated Extension extensions = 6; +} + +// A specific position in source. +message SourcePosition { + // The soucre location name (e.g. file name). + string location = 1; + + // The UTF-8 code unit offset. + int32 offset = 2; + + // The 1-based index of the starting line in the source text + // where the issue occurs, or 0 if unknown. + int32 line = 3; + + // The 0-based index of the starting position within the line of source text + // where the issue occurs. Only meaningful if line is nonzero. + int32 column = 4; +} diff --git a/node_modules/google-gax/build/protos/google/api/expr/v1alpha1/value.proto b/node_modules/google-gax/build/protos/google/api/expr/v1alpha1/value.proto new file mode 100644 index 0000000..9074fcc --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/expr/v1alpha1/value.proto @@ -0,0 +1,115 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.expr.v1alpha1; + +import "google/protobuf/any.proto"; +import "google/protobuf/struct.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/expr/v1alpha1;expr"; +option java_multiple_files = true; +option java_outer_classname = "ValueProto"; +option java_package = "com.google.api.expr.v1alpha1"; + +// Contains representations for CEL runtime values. + +// Represents a CEL value. +// +// This is similar to `google.protobuf.Value`, but can represent CEL's full +// range of values. +message Value { + // Required. The valid kinds of values. + oneof kind { + // Null value. + google.protobuf.NullValue null_value = 1; + + // Boolean value. + bool bool_value = 2; + + // Signed integer value. + int64 int64_value = 3; + + // Unsigned integer value. + uint64 uint64_value = 4; + + // Floating point value. + double double_value = 5; + + // UTF-8 string value. + string string_value = 6; + + // Byte string value. + bytes bytes_value = 7; + + // An enum value. + EnumValue enum_value = 9; + + // The proto message backing an object value. + google.protobuf.Any object_value = 10; + + // Map value. + MapValue map_value = 11; + + // List value. + ListValue list_value = 12; + + // Type value. + string type_value = 15; + } +} + +// An enum value. +message EnumValue { + // The fully qualified name of the enum type. + string type = 1; + + // The value of the enum. + int32 value = 2; +} + +// A list. +// +// Wrapped in a message so 'not set' and empty can be differentiated, which is +// required for use in a 'oneof'. +message ListValue { + // The ordered values in the list. + repeated Value values = 1; +} + +// A map. +// +// Wrapped in a message so 'not set' and empty can be differentiated, which is +// required for use in a 'oneof'. +message MapValue { + // An entry in the map. + message Entry { + // The key. + // + // Must be unique with in the map. + // Currently only boolean, int, uint, and string values can be keys. + Value key = 1; + + // The value. + Value value = 2; + } + + // The set of map entries. + // + // CEL has fewer restrictions on keys, so a protobuf map represenation + // cannot be used. + repeated Entry entries = 1; +} diff --git a/node_modules/google-gax/build/protos/google/api/expr/v1beta1/decl.proto b/node_modules/google-gax/build/protos/google/api/expr/v1beta1/decl.proto new file mode 100644 index 0000000..d3d748b --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/expr/v1beta1/decl.proto @@ -0,0 +1,84 @@ +// Copyright 2019 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +syntax = "proto3"; + +package google.api.expr.v1beta1; + +import "google/api/expr/v1beta1/expr.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/expr/v1beta1;expr"; +option java_multiple_files = true; +option java_outer_classname = "DeclProto"; +option java_package = "com.google.api.expr.v1beta1"; + +// A declaration. +message Decl { + // The id of the declaration. + int32 id = 1; + + // The name of the declaration. + string name = 2; + + // The documentation string for the declaration. + string doc = 3; + + // The kind of declaration. + oneof kind { + // An identifier declaration. + IdentDecl ident = 4; + + // A function declaration. + FunctionDecl function = 5; + } +} + +// The declared type of a variable. +// +// Extends runtime type values with extra information used for type checking +// and dispatching. +message DeclType { + // The expression id of the declared type, if applicable. + int32 id = 1; + + // The type name, e.g. 'int', 'my.type.Type' or 'T' + string type = 2; + + // An ordered list of type parameters, e.g. ``. + // Only applies to a subset of types, e.g. `map`, `list`. + repeated DeclType type_params = 4; +} + +// An identifier declaration. +message IdentDecl { + // Optional type of the identifier. + DeclType type = 3; + + // Optional value of the identifier. + Expr value = 4; +} + +// A function declaration. +message FunctionDecl { + // The function arguments. + repeated IdentDecl args = 1; + + // Optional declared return type. + DeclType return_type = 2; + + // If the first argument of the function is the receiver. + bool receiver_function = 3; +} diff --git a/node_modules/google-gax/build/protos/google/api/expr/v1beta1/eval.proto b/node_modules/google-gax/build/protos/google/api/expr/v1beta1/eval.proto new file mode 100644 index 0000000..0c6c4d9 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/expr/v1beta1/eval.proto @@ -0,0 +1,125 @@ +// Copyright 2019 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +syntax = "proto3"; + +package google.api.expr.v1beta1; + +import "google/api/expr/v1beta1/value.proto"; +import "google/rpc/status.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/expr/v1beta1;expr"; +option java_multiple_files = true; +option java_outer_classname = "EvalProto"; +option java_package = "com.google.api.expr.v1beta1"; + +// The state of an evaluation. +// +// Can represent an initial, partial, or completed state of evaluation. +message EvalState { + // A single evaluation result. + message Result { + // The expression this result is for. + IdRef expr = 1; + + // The index in `values` of the resulting value. + int32 value = 2; + } + + // The unique values referenced in this message. + repeated ExprValue values = 1; + + // An ordered list of results. + // + // Tracks the flow of evaluation through the expression. + // May be sparse. + repeated Result results = 3; +} + +// The value of an evaluated expression. +message ExprValue { + // An expression can resolve to a value, error or unknown. + oneof kind { + // A concrete value. + Value value = 1; + + // The set of errors in the critical path of evalution. + // + // Only errors in the critical path are included. For example, + // `( || true) && ` will only result in ``, + // while ` || ` will result in both `` and + // ``. + // + // Errors cause by the presence of other errors are not included in the + // set. For example `.foo`, `foo()`, and ` + 1` will + // only result in ``. + // + // Multiple errors *might* be included when evaluation could result + // in different errors. For example ` + ` and + // `foo(, )` may result in ``, `` or both. + // The exact subset of errors included for this case is unspecified and + // depends on the implementation details of the evaluator. + ErrorSet error = 2; + + // The set of unknowns in the critical path of evaluation. + // + // Unknown behaves identically to Error with regards to propagation. + // Specifically, only unknowns in the critical path are included, unknowns + // caused by the presence of other unknowns are not included, and multiple + // unknowns *might* be included included when evaluation could result in + // different unknowns. For example: + // + // ( || true) && -> + // || -> + // .foo -> + // foo() -> + // + -> or + // + // Unknown takes precidence over Error in cases where a `Value` can short + // circuit the result: + // + // || -> + // && -> + // + // Errors take precidence in all other cases: + // + // + -> + // foo(, ) -> + UnknownSet unknown = 3; + } +} + +// A set of errors. +// +// The errors included depend on the context. See `ExprValue.error`. +message ErrorSet { + // The errors in the set. + repeated google.rpc.Status errors = 1; +} + +// A set of expressions for which the value is unknown. +// +// The unknowns included depend on the context. See `ExprValue.unknown`. +message UnknownSet { + // The ids of the expressions with unknown values. + repeated IdRef exprs = 1; +} + +// A reference to an expression id. +message IdRef { + // The expression id. + int32 id = 1; +} diff --git a/node_modules/google-gax/build/protos/google/api/expr/v1beta1/expr.proto b/node_modules/google-gax/build/protos/google/api/expr/v1beta1/expr.proto new file mode 100644 index 0000000..77249ba --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/expr/v1beta1/expr.proto @@ -0,0 +1,265 @@ +// Copyright 2019 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +syntax = "proto3"; + +package google.api.expr.v1beta1; + +import "google/api/expr/v1beta1/source.proto"; +import "google/protobuf/struct.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/expr/v1beta1;expr"; +option java_multiple_files = true; +option java_outer_classname = "ExprProto"; +option java_package = "com.google.api.expr.v1beta1"; + +// An expression together with source information as returned by the parser. +message ParsedExpr { + // The parsed expression. + Expr expr = 2; + + // The source info derived from input that generated the parsed `expr`. + SourceInfo source_info = 3; + + // The syntax version of the source, e.g. `cel1`. + string syntax_version = 4; +} + +// An abstract representation of a common expression. +// +// Expressions are abstractly represented as a collection of identifiers, +// select statements, function calls, literals, and comprehensions. All +// operators with the exception of the '.' operator are modelled as function +// calls. This makes it easy to represent new operators into the existing AST. +// +// All references within expressions must resolve to a [Decl][google.api.expr.v1beta1.Decl] provided at +// type-check for an expression to be valid. A reference may either be a bare +// identifier `name` or a qualified identifier `google.api.name`. References +// may either refer to a value or a function declaration. +// +// For example, the expression `google.api.name.startsWith('expr')` references +// the declaration `google.api.name` within a [Expr.Select][google.api.expr.v1beta1.Expr.Select] expression, and +// the function declaration `startsWith`. +message Expr { + // An identifier expression. e.g. `request`. + message Ident { + // Required. Holds a single, unqualified identifier, possibly preceded by a + // '.'. + // + // Qualified names are represented by the [Expr.Select][google.api.expr.v1beta1.Expr.Select] expression. + string name = 1; + } + + // A field selection expression. e.g. `request.auth`. + message Select { + // Required. The target of the selection expression. + // + // For example, in the select expression `request.auth`, the `request` + // portion of the expression is the `operand`. + Expr operand = 1; + + // Required. The name of the field to select. + // + // For example, in the select expression `request.auth`, the `auth` portion + // of the expression would be the `field`. + string field = 2; + + // Whether the select is to be interpreted as a field presence test. + // + // This results from the macro `has(request.auth)`. + bool test_only = 3; + } + + // A call expression, including calls to predefined functions and operators. + // + // For example, `value == 10`, `size(map_value)`. + message Call { + // The target of an method call-style expression. For example, `x` in + // `x.f()`. + Expr target = 1; + + // Required. The name of the function or method being called. + string function = 2; + + // The arguments. + repeated Expr args = 3; + } + + // A list creation expression. + // + // Lists may either be homogenous, e.g. `[1, 2, 3]`, or heterogenous, e.g. + // `dyn([1, 'hello', 2.0])` + message CreateList { + // The elements part of the list. + repeated Expr elements = 1; + } + + // A map or message creation expression. + // + // Maps are constructed as `{'key_name': 'value'}`. Message construction is + // similar, but prefixed with a type name and composed of field ids: + // `types.MyType{field_id: 'value'}`. + message CreateStruct { + // Represents an entry. + message Entry { + // Required. An id assigned to this node by the parser which is unique + // in a given expression tree. This is used to associate type + // information and other attributes to the node. + int32 id = 1; + + // The `Entry` key kinds. + oneof key_kind { + // The field key for a message creator statement. + string field_key = 2; + + // The key expression for a map creation statement. + Expr map_key = 3; + } + + // Required. The value assigned to the key. + Expr value = 4; + } + + // The type name of the message to be created, empty when creating map + // literals. + string type = 1; + + // The entries in the creation expression. + repeated Entry entries = 2; + } + + // A comprehension expression applied to a list or map. + // + // Comprehensions are not part of the core syntax, but enabled with macros. + // A macro matches a specific call signature within a parsed AST and replaces + // the call with an alternate AST block. Macro expansion happens at parse + // time. + // + // The following macros are supported within CEL: + // + // Aggregate type macros may be applied to all elements in a list or all keys + // in a map: + // + // * `all`, `exists`, `exists_one` - test a predicate expression against + // the inputs and return `true` if the predicate is satisfied for all, + // any, or only one value `list.all(x, x < 10)`. + // * `filter` - test a predicate expression against the inputs and return + // the subset of elements which satisfy the predicate: + // `payments.filter(p, p > 1000)`. + // * `map` - apply an expression to all elements in the input and return the + // output aggregate type: `[1, 2, 3].map(i, i * i)`. + // + // The `has(m.x)` macro tests whether the property `x` is present in struct + // `m`. The semantics of this macro depend on the type of `m`. For proto2 + // messages `has(m.x)` is defined as 'defined, but not set`. For proto3, the + // macro tests whether the property is set to its default. For map and struct + // types, the macro tests whether the property `x` is defined on `m`. + message Comprehension { + // The name of the iteration variable. + string iter_var = 1; + + // The range over which var iterates. + Expr iter_range = 2; + + // The name of the variable used for accumulation of the result. + string accu_var = 3; + + // The initial value of the accumulator. + Expr accu_init = 4; + + // An expression which can contain iter_var and accu_var. + // + // Returns false when the result has been computed and may be used as + // a hint to short-circuit the remainder of the comprehension. + Expr loop_condition = 5; + + // An expression which can contain iter_var and accu_var. + // + // Computes the next value of accu_var. + Expr loop_step = 6; + + // An expression which can contain accu_var. + // + // Computes the result. + Expr result = 7; + } + + // Required. An id assigned to this node by the parser which is unique in a + // given expression tree. This is used to associate type information and other + // attributes to a node in the parse tree. + int32 id = 2; + + // Required. Variants of expressions. + oneof expr_kind { + // A literal expression. + Literal literal_expr = 3; + + // An identifier expression. + Ident ident_expr = 4; + + // A field selection expression, e.g. `request.auth`. + Select select_expr = 5; + + // A call expression, including calls to predefined functions and operators. + Call call_expr = 6; + + // A list creation expression. + CreateList list_expr = 7; + + // A map or object creation expression. + CreateStruct struct_expr = 8; + + // A comprehension expression. + Comprehension comprehension_expr = 9; + } +} + +// Represents a primitive literal. +// +// This is similar to the primitives supported in the well-known type +// `google.protobuf.Value`, but richer so it can represent CEL's full range of +// primitives. +// +// Lists and structs are not included as constants as these aggregate types may +// contain [Expr][google.api.expr.v1beta1.Expr] elements which require evaluation and are thus not constant. +// +// Examples of literals include: `"hello"`, `b'bytes'`, `1u`, `4.2`, `-2`, +// `true`, `null`. +message Literal { + // Required. The valid constant kinds. + oneof constant_kind { + // null value. + google.protobuf.NullValue null_value = 1; + + // boolean value. + bool bool_value = 2; + + // int64 value. + int64 int64_value = 3; + + // uint64 value. + uint64 uint64_value = 4; + + // double value. + double double_value = 5; + + // string value. + string string_value = 6; + + // bytes value. + bytes bytes_value = 7; + } +} diff --git a/node_modules/google-gax/build/protos/google/api/expr/v1beta1/source.proto b/node_modules/google-gax/build/protos/google/api/expr/v1beta1/source.proto new file mode 100644 index 0000000..78bb0a0 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/expr/v1beta1/source.proto @@ -0,0 +1,62 @@ +// Copyright 2019 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +syntax = "proto3"; + +package google.api.expr.v1beta1; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/expr/v1beta1;expr"; +option java_multiple_files = true; +option java_outer_classname = "SourceProto"; +option java_package = "com.google.api.expr.v1beta1"; + +// Source information collected at parse time. +message SourceInfo { + // The location name. All position information attached to an expression is + // relative to this location. + // + // The location could be a file, UI element, or similar. For example, + // `acme/app/AnvilPolicy.cel`. + string location = 2; + + // Monotonically increasing list of character offsets where newlines appear. + // + // The line number of a given position is the index `i` where for a given + // `id` the `line_offsets[i] < id_positions[id] < line_offsets[i+1]`. The + // column may be derivd from `id_positions[id] - line_offsets[i]`. + repeated int32 line_offsets = 3; + + // A map from the parse node id (e.g. `Expr.id`) to the character offset + // within source. + map positions = 4; +} + +// A specific position in source. +message SourcePosition { + // The soucre location name (e.g. file name). + string location = 1; + + // The character offset. + int32 offset = 2; + + // The 1-based index of the starting line in the source text + // where the issue occurs, or 0 if unknown. + int32 line = 3; + + // The 0-based index of the starting position within the line of source text + // where the issue occurs. Only meaningful if line is nonzer.. + int32 column = 4; +} diff --git a/node_modules/google-gax/build/protos/google/api/expr/v1beta1/value.proto b/node_modules/google-gax/build/protos/google/api/expr/v1beta1/value.proto new file mode 100644 index 0000000..0978228 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/expr/v1beta1/value.proto @@ -0,0 +1,114 @@ +// Copyright 2019 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +syntax = "proto3"; + +package google.api.expr.v1beta1; + +import "google/protobuf/any.proto"; +import "google/protobuf/struct.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/expr/v1beta1;expr"; +option java_multiple_files = true; +option java_outer_classname = "ValueProto"; +option java_package = "com.google.api.expr.v1beta1"; + +// Represents a CEL value. +// +// This is similar to `google.protobuf.Value`, but can represent CEL's full +// range of values. +message Value { + // Required. The valid kinds of values. + oneof kind { + // Null value. + google.protobuf.NullValue null_value = 1; + + // Boolean value. + bool bool_value = 2; + + // Signed integer value. + int64 int64_value = 3; + + // Unsigned integer value. + uint64 uint64_value = 4; + + // Floating point value. + double double_value = 5; + + // UTF-8 string value. + string string_value = 6; + + // Byte string value. + bytes bytes_value = 7; + + // An enum value. + EnumValue enum_value = 9; + + // The proto message backing an object value. + google.protobuf.Any object_value = 10; + + // Map value. + MapValue map_value = 11; + + // List value. + ListValue list_value = 12; + + // A Type value represented by the fully qualified name of the type. + string type_value = 15; + } +} + +// An enum value. +message EnumValue { + // The fully qualified name of the enum type. + string type = 1; + + // The value of the enum. + int32 value = 2; +} + +// A list. +// +// Wrapped in a message so 'not set' and empty can be differentiated, which is +// required for use in a 'oneof'. +message ListValue { + // The ordered values in the list. + repeated Value values = 1; +} + +// A map. +// +// Wrapped in a message so 'not set' and empty can be differentiated, which is +// required for use in a 'oneof'. +message MapValue { + // An entry in the map. + message Entry { + // The key. + // + // Must be unique with in the map. + // Currently only boolean, int, uint, and string values can be keys. + Value key = 1; + + // The value. + Value value = 2; + } + + // The set of map entries. + // + // CEL has fewer restrictions on keys, so a protobuf map represenation + // cannot be used. + repeated Entry entries = 1; +} diff --git a/node_modules/google-gax/build/protos/google/api/field_behavior.proto b/node_modules/google-gax/build/protos/google/api/field_behavior.proto new file mode 100644 index 0000000..21895bf --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/field_behavior.proto @@ -0,0 +1,104 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/protobuf/descriptor.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "FieldBehaviorProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +extend google.protobuf.FieldOptions { + // A designation of a specific field behavior (required, output only, etc.) + // in protobuf messages. + // + // Examples: + // + // string name = 1 [(google.api.field_behavior) = REQUIRED]; + // State state = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + // google.protobuf.Duration ttl = 1 + // [(google.api.field_behavior) = INPUT_ONLY]; + // google.protobuf.Timestamp expire_time = 1 + // [(google.api.field_behavior) = OUTPUT_ONLY, + // (google.api.field_behavior) = IMMUTABLE]; + repeated google.api.FieldBehavior field_behavior = 1052 [packed = false]; +} + +// An indicator of the behavior of a given field (for example, that a field +// is required in requests, or given as output but ignored as input). +// This **does not** change the behavior in protocol buffers itself; it only +// denotes the behavior and may affect how API tooling handles the field. +// +// Note: This enum **may** receive new values in the future. +enum FieldBehavior { + // Conventional default for enums. Do not use this. + FIELD_BEHAVIOR_UNSPECIFIED = 0; + + // Specifically denotes a field as optional. + // While all fields in protocol buffers are optional, this may be specified + // for emphasis if appropriate. + OPTIONAL = 1; + + // Denotes a field as required. + // This indicates that the field **must** be provided as part of the request, + // and failure to do so will cause an error (usually `INVALID_ARGUMENT`). + REQUIRED = 2; + + // Denotes a field as output only. + // This indicates that the field is provided in responses, but including the + // field in a request does nothing (the server *must* ignore it and + // *must not* throw an error as a result of the field's presence). + OUTPUT_ONLY = 3; + + // Denotes a field as input only. + // This indicates that the field is provided in requests, and the + // corresponding field is not included in output. + INPUT_ONLY = 4; + + // Denotes a field as immutable. + // This indicates that the field may be set once in a request to create a + // resource, but may not be changed thereafter. + IMMUTABLE = 5; + + // Denotes that a (repeated) field is an unordered list. + // This indicates that the service may provide the elements of the list + // in any arbitrary order, rather than the order the user originally + // provided. Additionally, the list's order may or may not be stable. + UNORDERED_LIST = 6; + + // Denotes that this field returns a non-empty default value if not set. + // This indicates that if the user provides the empty value in a request, + // a non-empty value will be returned. The user will not be aware of what + // non-empty value to expect. + NON_EMPTY_DEFAULT = 7; + + // Denotes that the field in a resource (a message annotated with + // google.api.resource) is used in the resource name to uniquely identify the + // resource. For AIP-compliant APIs, this should only be applied to the + // `name` field on the resource. + // + // This behavior should not be applied to references to other resources within + // the message. + // + // The identifier field of resources often have different field behavior + // depending on the request it is embedded in (e.g. for Create methods name + // is optional and unused, while for Update methods it is required). Instead + // of method-specific annotations, only `IDENTIFIER` is required. + IDENTIFIER = 8; +} diff --git a/node_modules/google-gax/build/protos/google/api/field_info.proto b/node_modules/google-gax/build/protos/google/api/field_info.proto new file mode 100644 index 0000000..e62d845 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/field_info.proto @@ -0,0 +1,79 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/protobuf/descriptor.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "FieldInfoProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +extend google.protobuf.FieldOptions { + // Rich semantic descriptor of an API field beyond the basic typing. + // + // Examples: + // + // string request_id = 1 [(google.api.field_info).format = UUID4]; + // string old_ip_address = 2 [(google.api.field_info).format = IPV4]; + // string new_ip_address = 3 [(google.api.field_info).format = IPV6]; + // string actual_ip_address = 4 [ + // (google.api.field_info).format = IPV4_OR_IPV6 + // ]; + google.api.FieldInfo field_info = 291403980; +} + +// Rich semantic information of an API field beyond basic typing. +message FieldInfo { + // The standard format of a field value. The supported formats are all backed + // by either an RFC defined by the IETF or a Google-defined AIP. + enum Format { + // Default, unspecified value. + FORMAT_UNSPECIFIED = 0; + + // Universally Unique Identifier, version 4, value as defined by + // https://datatracker.ietf.org/doc/html/rfc4122. The value may be + // normalized to entirely lowercase letters. For example, the value + // `F47AC10B-58CC-0372-8567-0E02B2C3D479` would be normalized to + // `f47ac10b-58cc-0372-8567-0e02b2c3d479`. + UUID4 = 1; + + // Internet Protocol v4 value as defined by [RFC + // 791](https://datatracker.ietf.org/doc/html/rfc791). The value may be + // condensed, with leading zeros in each octet stripped. For example, + // `001.022.233.040` would be condensed to `1.22.233.40`. + IPV4 = 2; + + // Internet Protocol v6 value as defined by [RFC + // 2460](https://datatracker.ietf.org/doc/html/rfc2460). The value may be + // normalized to entirely lowercase letters with zeros compressed, following + // [RFC 5952](https://datatracker.ietf.org/doc/html/rfc5952). For example, + // the value `2001:0DB8:0::0` would be normalized to `2001:db8::`. + IPV6 = 3; + + // An IP address in either v4 or v6 format as described by the individual + // values defined herein. See the comments on the IPV4 and IPV6 types for + // allowed normalizations of each. + IPV4_OR_IPV6 = 4; + } + + // The standard format of a field value. This does not explicitly configure + // any API consumer, just documents the API's format for the field it is + // applied to. + Format format = 1; +} diff --git a/node_modules/google-gax/build/protos/google/api/http.proto b/node_modules/google-gax/build/protos/google/api/http.proto new file mode 100644 index 0000000..31d867a --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/http.proto @@ -0,0 +1,379 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "HttpProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Defines the HTTP configuration for an API service. It contains a list of +// [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method +// to one or more HTTP REST API methods. +message Http { + // A list of HTTP configuration rules that apply to individual API methods. + // + // **NOTE:** All service configuration rules follow "last one wins" order. + repeated HttpRule rules = 1; + + // When set to true, URL path parameters will be fully URI-decoded except in + // cases of single segment matches in reserved expansion, where "%2F" will be + // left encoded. + // + // The default behavior is to not decode RFC 6570 reserved characters in multi + // segment matches. + bool fully_decode_reserved_expansion = 2; +} + +// # gRPC Transcoding +// +// gRPC Transcoding is a feature for mapping between a gRPC method and one or +// more HTTP REST endpoints. It allows developers to build a single API service +// that supports both gRPC APIs and REST APIs. Many systems, including [Google +// APIs](https://github.com/googleapis/googleapis), +// [Cloud Endpoints](https://cloud.google.com/endpoints), [gRPC +// Gateway](https://github.com/grpc-ecosystem/grpc-gateway), +// and [Envoy](https://github.com/envoyproxy/envoy) proxy support this feature +// and use it for large scale production services. +// +// `HttpRule` defines the schema of the gRPC/REST mapping. The mapping specifies +// how different portions of the gRPC request message are mapped to the URL +// path, URL query parameters, and HTTP request body. It also controls how the +// gRPC response message is mapped to the HTTP response body. `HttpRule` is +// typically specified as an `google.api.http` annotation on the gRPC method. +// +// Each mapping specifies a URL path template and an HTTP method. The path +// template may refer to one or more fields in the gRPC request message, as long +// as each field is a non-repeated field with a primitive (non-message) type. +// The path template controls how fields of the request message are mapped to +// the URL path. +// +// Example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get: "/v1/{name=messages/*}" +// }; +// } +// } +// message GetMessageRequest { +// string name = 1; // Mapped to URL path. +// } +// message Message { +// string text = 1; // The resource content. +// } +// +// This enables an HTTP REST to gRPC mapping as below: +// +// HTTP | gRPC +// -----|----- +// `GET /v1/messages/123456` | `GetMessage(name: "messages/123456")` +// +// Any fields in the request message which are not bound by the path template +// automatically become HTTP query parameters if there is no HTTP request body. +// For example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get:"/v1/messages/{message_id}" +// }; +// } +// } +// message GetMessageRequest { +// message SubMessage { +// string subfield = 1; +// } +// string message_id = 1; // Mapped to URL path. +// int64 revision = 2; // Mapped to URL query parameter `revision`. +// SubMessage sub = 3; // Mapped to URL query parameter `sub.subfield`. +// } +// +// This enables a HTTP JSON to RPC mapping as below: +// +// HTTP | gRPC +// -----|----- +// `GET /v1/messages/123456?revision=2&sub.subfield=foo` | +// `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield: +// "foo"))` +// +// Note that fields which are mapped to URL query parameters must have a +// primitive type or a repeated primitive type or a non-repeated message type. +// In the case of a repeated type, the parameter can be repeated in the URL +// as `...?param=A¶m=B`. In the case of a message type, each field of the +// message is mapped to a separate parameter, such as +// `...?foo.a=A&foo.b=B&foo.c=C`. +// +// For HTTP methods that allow a request body, the `body` field +// specifies the mapping. Consider a REST update method on the +// message resource collection: +// +// service Messaging { +// rpc UpdateMessage(UpdateMessageRequest) returns (Message) { +// option (google.api.http) = { +// patch: "/v1/messages/{message_id}" +// body: "message" +// }; +// } +// } +// message UpdateMessageRequest { +// string message_id = 1; // mapped to the URL +// Message message = 2; // mapped to the body +// } +// +// The following HTTP JSON to RPC mapping is enabled, where the +// representation of the JSON in the request body is determined by +// protos JSON encoding: +// +// HTTP | gRPC +// -----|----- +// `PATCH /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: +// "123456" message { text: "Hi!" })` +// +// The special name `*` can be used in the body mapping to define that +// every field not bound by the path template should be mapped to the +// request body. This enables the following alternative definition of +// the update method: +// +// service Messaging { +// rpc UpdateMessage(Message) returns (Message) { +// option (google.api.http) = { +// patch: "/v1/messages/{message_id}" +// body: "*" +// }; +// } +// } +// message Message { +// string message_id = 1; +// string text = 2; +// } +// +// +// The following HTTP JSON to RPC mapping is enabled: +// +// HTTP | gRPC +// -----|----- +// `PATCH /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: +// "123456" text: "Hi!")` +// +// Note that when using `*` in the body mapping, it is not possible to +// have HTTP parameters, as all fields not bound by the path end in +// the body. This makes this option more rarely used in practice when +// defining REST APIs. The common usage of `*` is in custom methods +// which don't use the URL at all for transferring data. +// +// It is possible to define multiple HTTP methods for one RPC by using +// the `additional_bindings` option. Example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get: "/v1/messages/{message_id}" +// additional_bindings { +// get: "/v1/users/{user_id}/messages/{message_id}" +// } +// }; +// } +// } +// message GetMessageRequest { +// string message_id = 1; +// string user_id = 2; +// } +// +// This enables the following two alternative HTTP JSON to RPC mappings: +// +// HTTP | gRPC +// -----|----- +// `GET /v1/messages/123456` | `GetMessage(message_id: "123456")` +// `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id: +// "123456")` +// +// ## Rules for HTTP mapping +// +// 1. Leaf request fields (recursive expansion nested messages in the request +// message) are classified into three categories: +// - Fields referred by the path template. They are passed via the URL path. +// - Fields referred by the [HttpRule.body][google.api.HttpRule.body]. They +// are passed via the HTTP +// request body. +// - All other fields are passed via the URL query parameters, and the +// parameter name is the field path in the request message. A repeated +// field can be represented as multiple query parameters under the same +// name. +// 2. If [HttpRule.body][google.api.HttpRule.body] is "*", there is no URL +// query parameter, all fields +// are passed via URL path and HTTP request body. +// 3. If [HttpRule.body][google.api.HttpRule.body] is omitted, there is no HTTP +// request body, all +// fields are passed via URL path and URL query parameters. +// +// ### Path template syntax +// +// Template = "/" Segments [ Verb ] ; +// Segments = Segment { "/" Segment } ; +// Segment = "*" | "**" | LITERAL | Variable ; +// Variable = "{" FieldPath [ "=" Segments ] "}" ; +// FieldPath = IDENT { "." IDENT } ; +// Verb = ":" LITERAL ; +// +// The syntax `*` matches a single URL path segment. The syntax `**` matches +// zero or more URL path segments, which must be the last part of the URL path +// except the `Verb`. +// +// The syntax `Variable` matches part of the URL path as specified by its +// template. A variable template must not contain other variables. If a variable +// matches a single path segment, its template may be omitted, e.g. `{var}` +// is equivalent to `{var=*}`. +// +// The syntax `LITERAL` matches literal text in the URL path. If the `LITERAL` +// contains any reserved character, such characters should be percent-encoded +// before the matching. +// +// If a variable contains exactly one path segment, such as `"{var}"` or +// `"{var=*}"`, when such a variable is expanded into a URL path on the client +// side, all characters except `[-_.~0-9a-zA-Z]` are percent-encoded. The +// server side does the reverse decoding. Such variables show up in the +// [Discovery +// Document](https://developers.google.com/discovery/v1/reference/apis) as +// `{var}`. +// +// If a variable contains multiple path segments, such as `"{var=foo/*}"` +// or `"{var=**}"`, when such a variable is expanded into a URL path on the +// client side, all characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. +// The server side does the reverse decoding, except "%2F" and "%2f" are left +// unchanged. Such variables show up in the +// [Discovery +// Document](https://developers.google.com/discovery/v1/reference/apis) as +// `{+var}`. +// +// ## Using gRPC API Service Configuration +// +// gRPC API Service Configuration (service config) is a configuration language +// for configuring a gRPC service to become a user-facing product. The +// service config is simply the YAML representation of the `google.api.Service` +// proto message. +// +// As an alternative to annotating your proto file, you can configure gRPC +// transcoding in your service config YAML files. You do this by specifying a +// `HttpRule` that maps the gRPC method to a REST endpoint, achieving the same +// effect as the proto annotation. This can be particularly useful if you +// have a proto that is reused in multiple services. Note that any transcoding +// specified in the service config will override any matching transcoding +// configuration in the proto. +// +// Example: +// +// http: +// rules: +// # Selects a gRPC method and applies HttpRule to it. +// - selector: example.v1.Messaging.GetMessage +// get: /v1/messages/{message_id}/{sub.subfield} +// +// ## Special notes +// +// When gRPC Transcoding is used to map a gRPC to JSON REST endpoints, the +// proto to JSON conversion must follow the [proto3 +// specification](https://developers.google.com/protocol-buffers/docs/proto3#json). +// +// While the single segment variable follows the semantics of +// [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 Simple String +// Expansion, the multi segment variable **does not** follow RFC 6570 Section +// 3.2.3 Reserved Expansion. The reason is that the Reserved Expansion +// does not expand special characters like `?` and `#`, which would lead +// to invalid URLs. As the result, gRPC Transcoding uses a custom encoding +// for multi segment variables. +// +// The path variables **must not** refer to any repeated or mapped field, +// because client libraries are not capable of handling such variable expansion. +// +// The path variables **must not** capture the leading "/" character. The reason +// is that the most common use case "{var}" does not capture the leading "/" +// character. For consistency, all path variables must share the same behavior. +// +// Repeated message fields must not be mapped to URL query parameters, because +// no client library can support such complicated mapping. +// +// If an API needs to use a JSON array for request or response body, it can map +// the request or response body to a repeated field. However, some gRPC +// Transcoding implementations may not support this feature. +message HttpRule { + // Selects a method to which this rule applies. + // + // Refer to [selector][google.api.DocumentationRule.selector] for syntax + // details. + string selector = 1; + + // Determines the URL pattern is matched by this rules. This pattern can be + // used with any of the {get|put|post|delete|patch} methods. A custom method + // can be defined using the 'custom' field. + oneof pattern { + // Maps to HTTP GET. Used for listing and getting information about + // resources. + string get = 2; + + // Maps to HTTP PUT. Used for replacing a resource. + string put = 3; + + // Maps to HTTP POST. Used for creating a resource or performing an action. + string post = 4; + + // Maps to HTTP DELETE. Used for deleting a resource. + string delete = 5; + + // Maps to HTTP PATCH. Used for updating a resource. + string patch = 6; + + // The custom pattern is used for specifying an HTTP method that is not + // included in the `pattern` field, such as HEAD, or "*" to leave the + // HTTP method unspecified for this rule. The wild-card rule is useful + // for services that provide content to Web (HTML) clients. + CustomHttpPattern custom = 8; + } + + // The name of the request field whose value is mapped to the HTTP request + // body, or `*` for mapping all request fields not captured by the path + // pattern to the HTTP body, or omitted for not having any HTTP request body. + // + // NOTE: the referred field must be present at the top-level of the request + // message type. + string body = 7; + + // Optional. The name of the response field whose value is mapped to the HTTP + // response body. When omitted, the entire response message will be used + // as the HTTP response body. + // + // NOTE: The referred field must be present at the top-level of the response + // message type. + string response_body = 12; + + // Additional HTTP bindings for the selector. Nested bindings must + // not contain an `additional_bindings` field themselves (that is, + // the nesting may only be one level deep). + repeated HttpRule additional_bindings = 11; +} + +// A custom pattern is used for defining custom HTTP verb. +message CustomHttpPattern { + // The name of this custom HTTP verb. + string kind = 1; + + // The path matched by this custom verb. + string path = 2; +} diff --git a/node_modules/google-gax/build/protos/google/api/httpbody.proto b/node_modules/google-gax/build/protos/google/api/httpbody.proto new file mode 100644 index 0000000..7f1685e --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/httpbody.proto @@ -0,0 +1,81 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/protobuf/any.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/httpbody;httpbody"; +option java_multiple_files = true; +option java_outer_classname = "HttpBodyProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Message that represents an arbitrary HTTP body. It should only be used for +// payload formats that can't be represented as JSON, such as raw binary or +// an HTML page. +// +// +// This message can be used both in streaming and non-streaming API methods in +// the request as well as the response. +// +// It can be used as a top-level request field, which is convenient if one +// wants to extract parameters from either the URL or HTTP template into the +// request fields and also want access to the raw HTTP body. +// +// Example: +// +// message GetResourceRequest { +// // A unique request id. +// string request_id = 1; +// +// // The raw HTTP body is bound to this field. +// google.api.HttpBody http_body = 2; +// +// } +// +// service ResourceService { +// rpc GetResource(GetResourceRequest) +// returns (google.api.HttpBody); +// rpc UpdateResource(google.api.HttpBody) +// returns (google.protobuf.Empty); +// +// } +// +// Example with streaming methods: +// +// service CaldavService { +// rpc GetCalendar(stream google.api.HttpBody) +// returns (stream google.api.HttpBody); +// rpc UpdateCalendar(stream google.api.HttpBody) +// returns (stream google.api.HttpBody); +// +// } +// +// Use of this type only changes how the request and response bodies are +// handled, all other features will continue to work unchanged. +message HttpBody { + // The HTTP Content-Type header value specifying the content type of the body. + string content_type = 1; + + // The HTTP request/response body as raw binary. + bytes data = 2; + + // Application specific response metadata. Must be set in the first response + // for streaming APIs. + repeated google.protobuf.Any extensions = 3; +} diff --git a/node_modules/google-gax/build/protos/google/api/label.proto b/node_modules/google-gax/build/protos/google/api/label.proto new file mode 100644 index 0000000..698f6bd --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/label.proto @@ -0,0 +1,48 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/label;label"; +option java_multiple_files = true; +option java_outer_classname = "LabelProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// A description of a label. +message LabelDescriptor { + // Value types that can be used as label values. + enum ValueType { + // A variable-length string. This is the default. + STRING = 0; + + // Boolean; true or false. + BOOL = 1; + + // A 64-bit signed integer. + INT64 = 2; + } + + // The label key. + string key = 1; + + // The type of data that can be assigned to the label. + ValueType value_type = 2; + + // A human-readable description for the label. + string description = 3; +} diff --git a/node_modules/google-gax/build/protos/google/api/launch_stage.proto b/node_modules/google-gax/build/protos/google/api/launch_stage.proto new file mode 100644 index 0000000..9802de7 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/launch_stage.proto @@ -0,0 +1,72 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option go_package = "google.golang.org/genproto/googleapis/api;api"; +option java_multiple_files = true; +option java_outer_classname = "LaunchStageProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// The launch stage as defined by [Google Cloud Platform +// Launch Stages](https://cloud.google.com/terms/launch-stages). +enum LaunchStage { + // Do not use this default value. + LAUNCH_STAGE_UNSPECIFIED = 0; + + // The feature is not yet implemented. Users can not use it. + UNIMPLEMENTED = 6; + + // Prelaunch features are hidden from users and are only visible internally. + PRELAUNCH = 7; + + // Early Access features are limited to a closed group of testers. To use + // these features, you must sign up in advance and sign a Trusted Tester + // agreement (which includes confidentiality provisions). These features may + // be unstable, changed in backward-incompatible ways, and are not + // guaranteed to be released. + EARLY_ACCESS = 1; + + // Alpha is a limited availability test for releases before they are cleared + // for widespread use. By Alpha, all significant design issues are resolved + // and we are in the process of verifying functionality. Alpha customers + // need to apply for access, agree to applicable terms, and have their + // projects allowlisted. Alpha releases don't have to be feature complete, + // no SLAs are provided, and there are no technical support obligations, but + // they will be far enough along that customers can actually use them in + // test environments or for limited-use tests -- just like they would in + // normal production cases. + ALPHA = 2; + + // Beta is the point at which we are ready to open a release for any + // customer to use. There are no SLA or technical support obligations in a + // Beta release. Products will be complete from a feature perspective, but + // may have some open outstanding issues. Beta releases are suitable for + // limited production use cases. + BETA = 3; + + // GA features are open to all developers and are considered stable and + // fully qualified for production use. + GA = 4; + + // Deprecated features are scheduled to be shut down and removed. For more + // information, see the "Deprecation Policy" section of our [Terms of + // Service](https://cloud.google.com/terms/) + // and the [Google Cloud Platform Subject to the Deprecation + // Policy](https://cloud.google.com/terms/deprecation) documentation. + DEPRECATED = 5; +} diff --git a/node_modules/google-gax/build/protos/google/api/log.proto b/node_modules/google-gax/build/protos/google/api/log.proto new file mode 100644 index 0000000..416c4f6 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/log.proto @@ -0,0 +1,54 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/api/label.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/serviceconfig;serviceconfig"; +option java_multiple_files = true; +option java_outer_classname = "LogProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// A description of a log type. Example in YAML format: +// +// - name: library.googleapis.com/activity_history +// description: The history of borrowing and returning library items. +// display_name: Activity +// labels: +// - key: /customer_id +// description: Identifier of a library customer +message LogDescriptor { + // The name of the log. It must be less than 512 characters long and can + // include the following characters: upper- and lower-case alphanumeric + // characters [A-Za-z0-9], and punctuation characters including + // slash, underscore, hyphen, period [/_-.]. + string name = 1; + + // The set of labels that are available to describe a specific log entry. + // Runtime requests that contain labels not specified here are + // considered invalid. + repeated LabelDescriptor labels = 2; + + // A human-readable description of this log. This information appears in + // the documentation and can contain details. + string description = 3; + + // The human-readable name for this log. This information appears on + // the user interface and should be concise. + string display_name = 4; +} diff --git a/node_modules/google-gax/build/protos/google/api/logging.proto b/node_modules/google-gax/build/protos/google/api/logging.proto new file mode 100644 index 0000000..650786f --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/logging.proto @@ -0,0 +1,81 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option go_package = "google.golang.org/genproto/googleapis/api/serviceconfig;serviceconfig"; +option java_multiple_files = true; +option java_outer_classname = "LoggingProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Logging configuration of the service. +// +// The following example shows how to configure logs to be sent to the +// producer and consumer projects. In the example, the `activity_history` +// log is sent to both the producer and consumer projects, whereas the +// `purchase_history` log is only sent to the producer project. +// +// monitored_resources: +// - type: library.googleapis.com/branch +// labels: +// - key: /city +// description: The city where the library branch is located in. +// - key: /name +// description: The name of the branch. +// logs: +// - name: activity_history +// labels: +// - key: /customer_id +// - name: purchase_history +// logging: +// producer_destinations: +// - monitored_resource: library.googleapis.com/branch +// logs: +// - activity_history +// - purchase_history +// consumer_destinations: +// - monitored_resource: library.googleapis.com/branch +// logs: +// - activity_history +message Logging { + // Configuration of a specific logging destination (the producer project + // or the consumer project). + message LoggingDestination { + // The monitored resource type. The type must be defined in the + // [Service.monitored_resources][google.api.Service.monitored_resources] + // section. + string monitored_resource = 3; + + // Names of the logs to be sent to this destination. Each name must + // be defined in the [Service.logs][google.api.Service.logs] section. If the + // log name is not a domain scoped name, it will be automatically prefixed + // with the service name followed by "/". + repeated string logs = 1; + } + + // Logging configurations for sending logs to the producer project. + // There can be multiple producer destinations, each one must have a + // different monitored resource type. A log can be used in at most + // one producer destination. + repeated LoggingDestination producer_destinations = 1; + + // Logging configurations for sending logs to the consumer project. + // There can be multiple consumer destinations, each one must have a + // different monitored resource type. A log can be used in at most + // one consumer destination. + repeated LoggingDestination consumer_destinations = 2; +} diff --git a/node_modules/google-gax/build/protos/google/api/metric.proto b/node_modules/google-gax/build/protos/google/api/metric.proto new file mode 100644 index 0000000..9bf043c --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/metric.proto @@ -0,0 +1,268 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/api/label.proto"; +import "google/api/launch_stage.proto"; +import "google/protobuf/duration.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/metric;metric"; +option java_multiple_files = true; +option java_outer_classname = "MetricProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Defines a metric type and its schema. Once a metric descriptor is created, +// deleting or altering it stops data collection and makes the metric type's +// existing data unusable. +// +message MetricDescriptor { + // The kind of measurement. It describes how the data is reported. + // For information on setting the start time and end time based on + // the MetricKind, see [TimeInterval][google.monitoring.v3.TimeInterval]. + enum MetricKind { + // Do not use this default value. + METRIC_KIND_UNSPECIFIED = 0; + + // An instantaneous measurement of a value. + GAUGE = 1; + + // The change in a value during a time interval. + DELTA = 2; + + // A value accumulated over a time interval. Cumulative + // measurements in a time series should have the same start time + // and increasing end times, until an event resets the cumulative + // value to zero and sets a new start time for the following + // points. + CUMULATIVE = 3; + } + + // The value type of a metric. + enum ValueType { + // Do not use this default value. + VALUE_TYPE_UNSPECIFIED = 0; + + // The value is a boolean. + // This value type can be used only if the metric kind is `GAUGE`. + BOOL = 1; + + // The value is a signed 64-bit integer. + INT64 = 2; + + // The value is a double precision floating point number. + DOUBLE = 3; + + // The value is a text string. + // This value type can be used only if the metric kind is `GAUGE`. + STRING = 4; + + // The value is a [`Distribution`][google.api.Distribution]. + DISTRIBUTION = 5; + + // The value is money. + MONEY = 6; + } + + // Additional annotations that can be used to guide the usage of a metric. + message MetricDescriptorMetadata { + // Deprecated. Must use the + // [MetricDescriptor.launch_stage][google.api.MetricDescriptor.launch_stage] + // instead. + LaunchStage launch_stage = 1 [deprecated = true]; + + // The sampling period of metric data points. For metrics which are written + // periodically, consecutive data points are stored at this time interval, + // excluding data loss due to errors. Metrics with a higher granularity have + // a smaller sampling period. + google.protobuf.Duration sample_period = 2; + + // The delay of data points caused by ingestion. Data points older than this + // age are guaranteed to be ingested and available to be read, excluding + // data loss due to errors. + google.protobuf.Duration ingest_delay = 3; + } + + // The resource name of the metric descriptor. + string name = 1; + + // The metric type, including its DNS name prefix. The type is not + // URL-encoded. All user-defined metric types have the DNS name + // `custom.googleapis.com` or `external.googleapis.com`. Metric types should + // use a natural hierarchical grouping. For example: + // + // "custom.googleapis.com/invoice/paid/amount" + // "external.googleapis.com/prometheus/up" + // "appengine.googleapis.com/http/server/response_latencies" + string type = 8; + + // The set of labels that can be used to describe a specific + // instance of this metric type. For example, the + // `appengine.googleapis.com/http/server/response_latencies` metric + // type has a label for the HTTP response code, `response_code`, so + // you can look at latencies for successful responses or just + // for responses that failed. + repeated LabelDescriptor labels = 2; + + // Whether the metric records instantaneous values, changes to a value, etc. + // Some combinations of `metric_kind` and `value_type` might not be supported. + MetricKind metric_kind = 3; + + // Whether the measurement is an integer, a floating-point number, etc. + // Some combinations of `metric_kind` and `value_type` might not be supported. + ValueType value_type = 4; + + // The units in which the metric value is reported. It is only applicable + // if the `value_type` is `INT64`, `DOUBLE`, or `DISTRIBUTION`. The `unit` + // defines the representation of the stored metric values. + // + // Different systems might scale the values to be more easily displayed (so a + // value of `0.02kBy` _might_ be displayed as `20By`, and a value of + // `3523kBy` _might_ be displayed as `3.5MBy`). However, if the `unit` is + // `kBy`, then the value of the metric is always in thousands of bytes, no + // matter how it might be displayed. + // + // If you want a custom metric to record the exact number of CPU-seconds used + // by a job, you can create an `INT64 CUMULATIVE` metric whose `unit` is + // `s{CPU}` (or equivalently `1s{CPU}` or just `s`). If the job uses 12,005 + // CPU-seconds, then the value is written as `12005`. + // + // Alternatively, if you want a custom metric to record data in a more + // granular way, you can create a `DOUBLE CUMULATIVE` metric whose `unit` is + // `ks{CPU}`, and then write the value `12.005` (which is `12005/1000`), + // or use `Kis{CPU}` and write `11.723` (which is `12005/1024`). + // + // The supported units are a subset of [The Unified Code for Units of + // Measure](https://unitsofmeasure.org/ucum.html) standard: + // + // **Basic units (UNIT)** + // + // * `bit` bit + // * `By` byte + // * `s` second + // * `min` minute + // * `h` hour + // * `d` day + // * `1` dimensionless + // + // **Prefixes (PREFIX)** + // + // * `k` kilo (10^3) + // * `M` mega (10^6) + // * `G` giga (10^9) + // * `T` tera (10^12) + // * `P` peta (10^15) + // * `E` exa (10^18) + // * `Z` zetta (10^21) + // * `Y` yotta (10^24) + // + // * `m` milli (10^-3) + // * `u` micro (10^-6) + // * `n` nano (10^-9) + // * `p` pico (10^-12) + // * `f` femto (10^-15) + // * `a` atto (10^-18) + // * `z` zepto (10^-21) + // * `y` yocto (10^-24) + // + // * `Ki` kibi (2^10) + // * `Mi` mebi (2^20) + // * `Gi` gibi (2^30) + // * `Ti` tebi (2^40) + // * `Pi` pebi (2^50) + // + // **Grammar** + // + // The grammar also includes these connectors: + // + // * `/` division or ratio (as an infix operator). For examples, + // `kBy/{email}` or `MiBy/10ms` (although you should almost never + // have `/s` in a metric `unit`; rates should always be computed at + // query time from the underlying cumulative or delta value). + // * `.` multiplication or composition (as an infix operator). For + // examples, `GBy.d` or `k{watt}.h`. + // + // The grammar for a unit is as follows: + // + // Expression = Component { "." Component } { "/" Component } ; + // + // Component = ( [ PREFIX ] UNIT | "%" ) [ Annotation ] + // | Annotation + // | "1" + // ; + // + // Annotation = "{" NAME "}" ; + // + // Notes: + // + // * `Annotation` is just a comment if it follows a `UNIT`. If the annotation + // is used alone, then the unit is equivalent to `1`. For examples, + // `{request}/s == 1/s`, `By{transmitted}/s == By/s`. + // * `NAME` is a sequence of non-blank printable ASCII characters not + // containing `{` or `}`. + // * `1` represents a unitary [dimensionless + // unit](https://en.wikipedia.org/wiki/Dimensionless_quantity) of 1, such + // as in `1/s`. It is typically used when none of the basic units are + // appropriate. For example, "new users per day" can be represented as + // `1/d` or `{new-users}/d` (and a metric value `5` would mean "5 new + // users). Alternatively, "thousands of page views per day" would be + // represented as `1000/d` or `k1/d` or `k{page_views}/d` (and a metric + // value of `5.3` would mean "5300 page views per day"). + // * `%` represents dimensionless value of 1/100, and annotates values giving + // a percentage (so the metric values are typically in the range of 0..100, + // and a metric value `3` means "3 percent"). + // * `10^2.%` indicates a metric contains a ratio, typically in the range + // 0..1, that will be multiplied by 100 and displayed as a percentage + // (so a metric value `0.03` means "3 percent"). + string unit = 5; + + // A detailed description of the metric, which can be used in documentation. + string description = 6; + + // A concise name for the metric, which can be displayed in user interfaces. + // Use sentence case without an ending period, for example "Request count". + // This field is optional but it is recommended to be set for any metrics + // associated with user-visible concepts, such as Quota. + string display_name = 7; + + // Optional. Metadata which can be used to guide usage of the metric. + MetricDescriptorMetadata metadata = 10; + + // Optional. The launch stage of the metric definition. + LaunchStage launch_stage = 12; + + // Read-only. If present, then a [time + // series][google.monitoring.v3.TimeSeries], which is identified partially by + // a metric type and a + // [MonitoredResourceDescriptor][google.api.MonitoredResourceDescriptor], that + // is associated with this metric type can only be associated with one of the + // monitored resource types listed here. + repeated string monitored_resource_types = 13; +} + +// A specific metric, identified by specifying values for all of the +// labels of a [`MetricDescriptor`][google.api.MetricDescriptor]. +message Metric { + // An existing metric type, see + // [google.api.MetricDescriptor][google.api.MetricDescriptor]. For example, + // `custom.googleapis.com/invoice/paid/amount`. + string type = 3; + + // The set of label values that uniquely identify this metric. All + // labels listed in the `MetricDescriptor` must be assigned values. + map labels = 2; +} diff --git a/node_modules/google-gax/build/protos/google/api/monitored_resource.proto b/node_modules/google-gax/build/protos/google/api/monitored_resource.proto new file mode 100644 index 0000000..08bc39b --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/monitored_resource.proto @@ -0,0 +1,130 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/api/label.proto"; +import "google/api/launch_stage.proto"; +import "google/protobuf/struct.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/monitoredres;monitoredres"; +option java_multiple_files = true; +option java_outer_classname = "MonitoredResourceProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// An object that describes the schema of a +// [MonitoredResource][google.api.MonitoredResource] object using a type name +// and a set of labels. For example, the monitored resource descriptor for +// Google Compute Engine VM instances has a type of +// `"gce_instance"` and specifies the use of the labels `"instance_id"` and +// `"zone"` to identify particular VM instances. +// +// Different APIs can support different monitored resource types. APIs generally +// provide a `list` method that returns the monitored resource descriptors used +// by the API. +// +message MonitoredResourceDescriptor { + // Optional. The resource name of the monitored resource descriptor: + // `"projects/{project_id}/monitoredResourceDescriptors/{type}"` where + // {type} is the value of the `type` field in this object and + // {project_id} is a project ID that provides API-specific context for + // accessing the type. APIs that do not use project information can use the + // resource name format `"monitoredResourceDescriptors/{type}"`. + string name = 5; + + // Required. The monitored resource type. For example, the type + // `"cloudsql_database"` represents databases in Google Cloud SQL. + // For a list of types, see [Monitored resource + // types](https://cloud.google.com/monitoring/api/resources) + // and [Logging resource + // types](https://cloud.google.com/logging/docs/api/v2/resource-list). + string type = 1; + + // Optional. A concise name for the monitored resource type that might be + // displayed in user interfaces. It should be a Title Cased Noun Phrase, + // without any article or other determiners. For example, + // `"Google Cloud SQL Database"`. + string display_name = 2; + + // Optional. A detailed description of the monitored resource type that might + // be used in documentation. + string description = 3; + + // Required. A set of labels used to describe instances of this monitored + // resource type. For example, an individual Google Cloud SQL database is + // identified by values for the labels `"database_id"` and `"zone"`. + repeated LabelDescriptor labels = 4; + + // Optional. The launch stage of the monitored resource definition. + LaunchStage launch_stage = 7; +} + +// An object representing a resource that can be used for monitoring, logging, +// billing, or other purposes. Examples include virtual machine instances, +// databases, and storage devices such as disks. The `type` field identifies a +// [MonitoredResourceDescriptor][google.api.MonitoredResourceDescriptor] object +// that describes the resource's schema. Information in the `labels` field +// identifies the actual resource and its attributes according to the schema. +// For example, a particular Compute Engine VM instance could be represented by +// the following object, because the +// [MonitoredResourceDescriptor][google.api.MonitoredResourceDescriptor] for +// `"gce_instance"` has labels +// `"project_id"`, `"instance_id"` and `"zone"`: +// +// { "type": "gce_instance", +// "labels": { "project_id": "my-project", +// "instance_id": "12345678901234", +// "zone": "us-central1-a" }} +message MonitoredResource { + // Required. The monitored resource type. This field must match + // the `type` field of a + // [MonitoredResourceDescriptor][google.api.MonitoredResourceDescriptor] + // object. For example, the type of a Compute Engine VM instance is + // `gce_instance`. Some descriptors include the service name in the type; for + // example, the type of a Datastream stream is + // `datastream.googleapis.com/Stream`. + string type = 1; + + // Required. Values for all of the labels listed in the associated monitored + // resource descriptor. For example, Compute Engine VM instances use the + // labels `"project_id"`, `"instance_id"`, and `"zone"`. + map labels = 2; +} + +// Auxiliary metadata for a [MonitoredResource][google.api.MonitoredResource] +// object. [MonitoredResource][google.api.MonitoredResource] objects contain the +// minimum set of information to uniquely identify a monitored resource +// instance. There is some other useful auxiliary metadata. Monitoring and +// Logging use an ingestion pipeline to extract metadata for cloud resources of +// all types, and store the metadata in this message. +message MonitoredResourceMetadata { + // Output only. Values for predefined system metadata labels. + // System labels are a kind of metadata extracted by Google, including + // "machine_image", "vpc", "subnet_id", + // "security_group", "name", etc. + // System label values can be only strings, Boolean values, or a list of + // strings. For example: + // + // { "name": "my-test-instance", + // "security_group": ["a", "b", "c"], + // "spot_instance": false } + google.protobuf.Struct system_labels = 1; + + // Output only. A map of user-defined metadata labels. + map user_labels = 2; +} diff --git a/node_modules/google-gax/build/protos/google/api/monitoring.proto b/node_modules/google-gax/build/protos/google/api/monitoring.proto new file mode 100644 index 0000000..753703e --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/monitoring.proto @@ -0,0 +1,107 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option go_package = "google.golang.org/genproto/googleapis/api/serviceconfig;serviceconfig"; +option java_multiple_files = true; +option java_outer_classname = "MonitoringProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Monitoring configuration of the service. +// +// The example below shows how to configure monitored resources and metrics +// for monitoring. In the example, a monitored resource and two metrics are +// defined. The `library.googleapis.com/book/returned_count` metric is sent +// to both producer and consumer projects, whereas the +// `library.googleapis.com/book/num_overdue` metric is only sent to the +// consumer project. +// +// monitored_resources: +// - type: library.googleapis.com/Branch +// display_name: "Library Branch" +// description: "A branch of a library." +// launch_stage: GA +// labels: +// - key: resource_container +// description: "The Cloud container (ie. project id) for the Branch." +// - key: location +// description: "The location of the library branch." +// - key: branch_id +// description: "The id of the branch." +// metrics: +// - name: library.googleapis.com/book/returned_count +// display_name: "Books Returned" +// description: "The count of books that have been returned." +// launch_stage: GA +// metric_kind: DELTA +// value_type: INT64 +// unit: "1" +// labels: +// - key: customer_id +// description: "The id of the customer." +// - name: library.googleapis.com/book/num_overdue +// display_name: "Books Overdue" +// description: "The current number of overdue books." +// launch_stage: GA +// metric_kind: GAUGE +// value_type: INT64 +// unit: "1" +// labels: +// - key: customer_id +// description: "The id of the customer." +// monitoring: +// producer_destinations: +// - monitored_resource: library.googleapis.com/Branch +// metrics: +// - library.googleapis.com/book/returned_count +// consumer_destinations: +// - monitored_resource: library.googleapis.com/Branch +// metrics: +// - library.googleapis.com/book/returned_count +// - library.googleapis.com/book/num_overdue +message Monitoring { + // Configuration of a specific monitoring destination (the producer project + // or the consumer project). + message MonitoringDestination { + // The monitored resource type. The type must be defined in + // [Service.monitored_resources][google.api.Service.monitored_resources] + // section. + string monitored_resource = 1; + + // Types of the metrics to report to this monitoring destination. + // Each type must be defined in + // [Service.metrics][google.api.Service.metrics] section. + repeated string metrics = 2; + } + + // Monitoring configurations for sending metrics to the producer project. + // There can be multiple producer destinations. A monitored resource type may + // appear in multiple monitoring destinations if different aggregations are + // needed for different sets of metrics associated with that monitored + // resource type. A monitored resource and metric pair may only be used once + // in the Monitoring configuration. + repeated MonitoringDestination producer_destinations = 1; + + // Monitoring configurations for sending metrics to the consumer project. + // There can be multiple consumer destinations. A monitored resource type may + // appear in multiple monitoring destinations if different aggregations are + // needed for different sets of metrics associated with that monitored + // resource type. A monitored resource and metric pair may only be used once + // in the Monitoring configuration. + repeated MonitoringDestination consumer_destinations = 2; +} diff --git a/node_modules/google-gax/build/protos/google/api/policy.proto b/node_modules/google-gax/build/protos/google/api/policy.proto new file mode 100644 index 0000000..dd202bc --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/policy.proto @@ -0,0 +1,85 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/protobuf/descriptor.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/serviceconfig;serviceconfig"; +option java_multiple_files = true; +option java_outer_classname = "PolicyProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Provides `google.api.field_policy` annotation at proto fields. +extend google.protobuf.FieldOptions { + // See [FieldPolicy][]. + FieldPolicy field_policy = 158361448; +} + +// Provides `google.api.method_policy` annotation at proto methods. +extend google.protobuf.MethodOptions { + // See [MethodPolicy][]. + MethodPolicy method_policy = 161893301; +} + +// Google API Policy Annotation +// +// This message defines a simple API policy annotation that can be used to +// annotate API request and response message fields with applicable policies. +// One field may have multiple applicable policies that must all be satisfied +// before a request can be processed. This policy annotation is used to +// generate the overall policy that will be used for automatic runtime +// policy enforcement and documentation generation. +message FieldPolicy { + // Selects one or more request or response message fields to apply this + // `FieldPolicy`. + // + // When a `FieldPolicy` is used in proto annotation, the selector must + // be left as empty. The service config generator will automatically fill + // the correct value. + // + // When a `FieldPolicy` is used in service config, the selector must be a + // comma-separated string with valid request or response field paths, + // such as "foo.bar" or "foo.bar,foo.baz". + string selector = 1; + + // Specifies the required permission(s) for the resource referred to by the + // field. It requires the field contains a valid resource reference, and + // the request must pass the permission checks to proceed. For example, + // "resourcemanager.projects.get". + string resource_permission = 2; + + // Specifies the resource type for the resource referred to by the field. + string resource_type = 3; +} + +// Defines policies applying to an RPC method. +message MethodPolicy { + // Selects a method to which these policies should be enforced, for example, + // "google.pubsub.v1.Subscriber.CreateSubscription". + // + // Refer to [selector][google.api.DocumentationRule.selector] for syntax + // details. + // + // NOTE: This field must not be set in the proto annotation. It will be + // automatically filled by the service config compiler . + string selector = 9; + + // Policies that are applicable to the request message. + repeated FieldPolicy request_policies = 2; +} diff --git a/node_modules/google-gax/build/protos/google/api/quota.proto b/node_modules/google-gax/build/protos/google/api/quota.proto new file mode 100644 index 0000000..7ccc102 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/quota.proto @@ -0,0 +1,184 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option go_package = "google.golang.org/genproto/googleapis/api/serviceconfig;serviceconfig"; +option java_multiple_files = true; +option java_outer_classname = "QuotaProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Quota configuration helps to achieve fairness and budgeting in service +// usage. +// +// The metric based quota configuration works this way: +// - The service configuration defines a set of metrics. +// - For API calls, the quota.metric_rules maps methods to metrics with +// corresponding costs. +// - The quota.limits defines limits on the metrics, which will be used for +// quota checks at runtime. +// +// An example quota configuration in yaml format: +// +// quota: +// limits: +// +// - name: apiWriteQpsPerProject +// metric: library.googleapis.com/write_calls +// unit: "1/min/{project}" # rate limit for consumer projects +// values: +// STANDARD: 10000 +// +// +// (The metric rules bind all methods to the read_calls metric, +// except for the UpdateBook and DeleteBook methods. These two methods +// are mapped to the write_calls metric, with the UpdateBook method +// consuming at twice rate as the DeleteBook method.) +// metric_rules: +// - selector: "*" +// metric_costs: +// library.googleapis.com/read_calls: 1 +// - selector: google.example.library.v1.LibraryService.UpdateBook +// metric_costs: +// library.googleapis.com/write_calls: 2 +// - selector: google.example.library.v1.LibraryService.DeleteBook +// metric_costs: +// library.googleapis.com/write_calls: 1 +// +// Corresponding Metric definition: +// +// metrics: +// - name: library.googleapis.com/read_calls +// display_name: Read requests +// metric_kind: DELTA +// value_type: INT64 +// +// - name: library.googleapis.com/write_calls +// display_name: Write requests +// metric_kind: DELTA +// value_type: INT64 +// +// +message Quota { + // List of QuotaLimit definitions for the service. + repeated QuotaLimit limits = 3; + + // List of MetricRule definitions, each one mapping a selected method to one + // or more metrics. + repeated MetricRule metric_rules = 4; +} + +// Bind API methods to metrics. Binding a method to a metric causes that +// metric's configured quota behaviors to apply to the method call. +message MetricRule { + // Selects the methods to which this rule applies. + // + // Refer to [selector][google.api.DocumentationRule.selector] for syntax + // details. + string selector = 1; + + // Metrics to update when the selected methods are called, and the associated + // cost applied to each metric. + // + // The key of the map is the metric name, and the values are the amount + // increased for the metric against which the quota limits are defined. + // The value must not be negative. + map metric_costs = 2; +} + +// `QuotaLimit` defines a specific limit that applies over a specified duration +// for a limit type. There can be at most one limit for a duration and limit +// type combination defined within a `QuotaGroup`. +message QuotaLimit { + // Name of the quota limit. + // + // The name must be provided, and it must be unique within the service. The + // name can only include alphanumeric characters as well as '-'. + // + // The maximum length of the limit name is 64 characters. + string name = 6; + + // Optional. User-visible, extended description for this quota limit. + // Should be used only when more context is needed to understand this limit + // than provided by the limit's display name (see: `display_name`). + string description = 2; + + // Default number of tokens that can be consumed during the specified + // duration. This is the number of tokens assigned when a client + // application developer activates the service for his/her project. + // + // Specifying a value of 0 will block all requests. This can be used if you + // are provisioning quota to selected consumers and blocking others. + // Similarly, a value of -1 will indicate an unlimited quota. No other + // negative values are allowed. + // + // Used by group-based quotas only. + int64 default_limit = 3; + + // Maximum number of tokens that can be consumed during the specified + // duration. Client application developers can override the default limit up + // to this maximum. If specified, this value cannot be set to a value less + // than the default limit. If not specified, it is set to the default limit. + // + // To allow clients to apply overrides with no upper bound, set this to -1, + // indicating unlimited maximum quota. + // + // Used by group-based quotas only. + int64 max_limit = 4; + + // Free tier value displayed in the Developers Console for this limit. + // The free tier is the number of tokens that will be subtracted from the + // billed amount when billing is enabled. + // This field can only be set on a limit with duration "1d", in a billable + // group; it is invalid on any other limit. If this field is not set, it + // defaults to 0, indicating that there is no free tier for this service. + // + // Used by group-based quotas only. + int64 free_tier = 7; + + // Duration of this limit in textual notation. Must be "100s" or "1d". + // + // Used by group-based quotas only. + string duration = 5; + + // The name of the metric this quota limit applies to. The quota limits with + // the same metric will be checked together during runtime. The metric must be + // defined within the service config. + string metric = 8; + + // Specify the unit of the quota limit. It uses the same syntax as + // [Metric.unit][]. The supported unit kinds are determined by the quota + // backend system. + // + // Here are some examples: + // * "1/min/{project}" for quota per minute per project. + // + // Note: the order of unit components is insignificant. + // The "1" at the beginning is required to follow the metric unit syntax. + string unit = 9; + + // Tiered limit values. You must specify this as a key:value pair, with an + // integer value that is the maximum number of requests allowed for the + // specified unit. Currently only STANDARD is supported. + map values = 10; + + // User-visible display name for this limit. + // Optional. If not set, the UI will provide a default display name based on + // the quota configuration. This field can be used to override the default + // display name generated from the configuration. + string display_name = 12; +} diff --git a/node_modules/google-gax/build/protos/google/api/resource.proto b/node_modules/google-gax/build/protos/google/api/resource.proto new file mode 100644 index 0000000..bf0cbec --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/resource.proto @@ -0,0 +1,238 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/protobuf/descriptor.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "ResourceProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +extend google.protobuf.FieldOptions { + // An annotation that describes a resource reference, see + // [ResourceReference][]. + google.api.ResourceReference resource_reference = 1055; +} + +extend google.protobuf.FileOptions { + // An annotation that describes a resource definition without a corresponding + // message; see [ResourceDescriptor][]. + repeated google.api.ResourceDescriptor resource_definition = 1053; +} + +extend google.protobuf.MessageOptions { + // An annotation that describes a resource definition, see + // [ResourceDescriptor][]. + google.api.ResourceDescriptor resource = 1053; +} + +// A simple descriptor of a resource type. +// +// ResourceDescriptor annotates a resource message (either by means of a +// protobuf annotation or use in the service config), and associates the +// resource's schema, the resource type, and the pattern of the resource name. +// +// Example: +// +// message Topic { +// // Indicates this message defines a resource schema. +// // Declares the resource type in the format of {service}/{kind}. +// // For Kubernetes resources, the format is {api group}/{kind}. +// option (google.api.resource) = { +// type: "pubsub.googleapis.com/Topic" +// pattern: "projects/{project}/topics/{topic}" +// }; +// } +// +// The ResourceDescriptor Yaml config will look like: +// +// resources: +// - type: "pubsub.googleapis.com/Topic" +// pattern: "projects/{project}/topics/{topic}" +// +// Sometimes, resources have multiple patterns, typically because they can +// live under multiple parents. +// +// Example: +// +// message LogEntry { +// option (google.api.resource) = { +// type: "logging.googleapis.com/LogEntry" +// pattern: "projects/{project}/logs/{log}" +// pattern: "folders/{folder}/logs/{log}" +// pattern: "organizations/{organization}/logs/{log}" +// pattern: "billingAccounts/{billing_account}/logs/{log}" +// }; +// } +// +// The ResourceDescriptor Yaml config will look like: +// +// resources: +// - type: 'logging.googleapis.com/LogEntry' +// pattern: "projects/{project}/logs/{log}" +// pattern: "folders/{folder}/logs/{log}" +// pattern: "organizations/{organization}/logs/{log}" +// pattern: "billingAccounts/{billing_account}/logs/{log}" +message ResourceDescriptor { + // A description of the historical or future-looking state of the + // resource pattern. + enum History { + // The "unset" value. + HISTORY_UNSPECIFIED = 0; + + // The resource originally had one pattern and launched as such, and + // additional patterns were added later. + ORIGINALLY_SINGLE_PATTERN = 1; + + // The resource has one pattern, but the API owner expects to add more + // later. (This is the inverse of ORIGINALLY_SINGLE_PATTERN, and prevents + // that from being necessary once there are multiple patterns.) + FUTURE_MULTI_PATTERN = 2; + } + + // A flag representing a specific style that a resource claims to conform to. + enum Style { + // The unspecified value. Do not use. + STYLE_UNSPECIFIED = 0; + + // This resource is intended to be "declarative-friendly". + // + // Declarative-friendly resources must be more strictly consistent, and + // setting this to true communicates to tools that this resource should + // adhere to declarative-friendly expectations. + // + // Note: This is used by the API linter (linter.aip.dev) to enable + // additional checks. + DECLARATIVE_FRIENDLY = 1; + } + + // The resource type. It must be in the format of + // {service_name}/{resource_type_kind}. The `resource_type_kind` must be + // singular and must not include version numbers. + // + // Example: `storage.googleapis.com/Bucket` + // + // The value of the resource_type_kind must follow the regular expression + // /[A-Za-z][a-zA-Z0-9]+/. It should start with an upper case character and + // should use PascalCase (UpperCamelCase). The maximum number of + // characters allowed for the `resource_type_kind` is 100. + string type = 1; + + // Optional. The relative resource name pattern associated with this resource + // type. The DNS prefix of the full resource name shouldn't be specified here. + // + // The path pattern must follow the syntax, which aligns with HTTP binding + // syntax: + // + // Template = Segment { "/" Segment } ; + // Segment = LITERAL | Variable ; + // Variable = "{" LITERAL "}" ; + // + // Examples: + // + // - "projects/{project}/topics/{topic}" + // - "projects/{project}/knowledgeBases/{knowledge_base}" + // + // The components in braces correspond to the IDs for each resource in the + // hierarchy. It is expected that, if multiple patterns are provided, + // the same component name (e.g. "project") refers to IDs of the same + // type of resource. + repeated string pattern = 2; + + // Optional. The field on the resource that designates the resource name + // field. If omitted, this is assumed to be "name". + string name_field = 3; + + // Optional. The historical or future-looking state of the resource pattern. + // + // Example: + // + // // The InspectTemplate message originally only supported resource + // // names with organization, and project was added later. + // message InspectTemplate { + // option (google.api.resource) = { + // type: "dlp.googleapis.com/InspectTemplate" + // pattern: + // "organizations/{organization}/inspectTemplates/{inspect_template}" + // pattern: "projects/{project}/inspectTemplates/{inspect_template}" + // history: ORIGINALLY_SINGLE_PATTERN + // }; + // } + History history = 4; + + // The plural name used in the resource name and permission names, such as + // 'projects' for the resource name of 'projects/{project}' and the permission + // name of 'cloudresourcemanager.googleapis.com/projects.get'. It is the same + // concept of the `plural` field in k8s CRD spec + // https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/ + // + // Note: The plural form is required even for singleton resources. See + // https://aip.dev/156 + string plural = 5; + + // The same concept of the `singular` field in k8s CRD spec + // https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/ + // Such as "project" for the `resourcemanager.googleapis.com/Project` type. + string singular = 6; + + // Style flag(s) for this resource. + // These indicate that a resource is expected to conform to a given + // style. See the specific style flags for additional information. + repeated Style style = 10; +} + +// Defines a proto annotation that describes a string field that refers to +// an API resource. +message ResourceReference { + // The resource type that the annotated field references. + // + // Example: + // + // message Subscription { + // string topic = 2 [(google.api.resource_reference) = { + // type: "pubsub.googleapis.com/Topic" + // }]; + // } + // + // Occasionally, a field may reference an arbitrary resource. In this case, + // APIs use the special value * in their resource reference. + // + // Example: + // + // message GetIamPolicyRequest { + // string resource = 2 [(google.api.resource_reference) = { + // type: "*" + // }]; + // } + string type = 1; + + // The resource type of a child collection that the annotated field + // references. This is useful for annotating the `parent` field that + // doesn't have a fixed resource type. + // + // Example: + // + // message ListLogEntriesRequest { + // string parent = 1 [(google.api.resource_reference) = { + // child_type: "logging.googleapis.com/LogEntry" + // }; + // } + string child_type = 2; +} diff --git a/node_modules/google-gax/build/protos/google/api/routing.proto b/node_modules/google-gax/build/protos/google/api/routing.proto new file mode 100644 index 0000000..b35289b --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/routing.proto @@ -0,0 +1,461 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/protobuf/descriptor.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "RoutingProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +extend google.protobuf.MethodOptions { + // See RoutingRule. + google.api.RoutingRule routing = 72295729; +} + +// Specifies the routing information that should be sent along with the request +// in the form of routing header. +// **NOTE:** All service configuration rules follow the "last one wins" order. +// +// The examples below will apply to an RPC which has the following request type: +// +// Message Definition: +// +// message Request { +// // The name of the Table +// // Values can be of the following formats: +// // - `projects//tables/` +// // - `projects//instances//tables/
                          ` +// // - `region//zones//tables/
                          ` +// string table_name = 1; +// +// // This value specifies routing for replication. +// // It can be in the following formats: +// // - `profiles/` +// // - a legacy `profile_id` that can be any string +// string app_profile_id = 2; +// } +// +// Example message: +// +// { +// table_name: projects/proj_foo/instances/instance_bar/table/table_baz, +// app_profile_id: profiles/prof_qux +// } +// +// The routing header consists of one or multiple key-value pairs. Every key +// and value must be percent-encoded, and joined together in the format of +// `key1=value1&key2=value2`. +// In the examples below I am skipping the percent-encoding for readablity. +// +// Example 1 +// +// Extracting a field from the request to put into the routing header +// unchanged, with the key equal to the field name. +// +// annotation: +// +// option (google.api.routing) = { +// // Take the `app_profile_id`. +// routing_parameters { +// field: "app_profile_id" +// } +// }; +// +// result: +// +// x-goog-request-params: app_profile_id=profiles/prof_qux +// +// Example 2 +// +// Extracting a field from the request to put into the routing header +// unchanged, with the key different from the field name. +// +// annotation: +// +// option (google.api.routing) = { +// // Take the `app_profile_id`, but name it `routing_id` in the header. +// routing_parameters { +// field: "app_profile_id" +// path_template: "{routing_id=**}" +// } +// }; +// +// result: +// +// x-goog-request-params: routing_id=profiles/prof_qux +// +// Example 3 +// +// Extracting a field from the request to put into the routing +// header, while matching a path template syntax on the field's value. +// +// NB: it is more useful to send nothing than to send garbage for the purpose +// of dynamic routing, since garbage pollutes cache. Thus the matching. +// +// Sub-example 3a +// +// The field matches the template. +// +// annotation: +// +// option (google.api.routing) = { +// // Take the `table_name`, if it's well-formed (with project-based +// // syntax). +// routing_parameters { +// field: "table_name" +// path_template: "{table_name=projects/*/instances/*/**}" +// } +// }; +// +// result: +// +// x-goog-request-params: +// table_name=projects/proj_foo/instances/instance_bar/table/table_baz +// +// Sub-example 3b +// +// The field does not match the template. +// +// annotation: +// +// option (google.api.routing) = { +// // Take the `table_name`, if it's well-formed (with region-based +// // syntax). +// routing_parameters { +// field: "table_name" +// path_template: "{table_name=regions/*/zones/*/**}" +// } +// }; +// +// result: +// +// +// +// Sub-example 3c +// +// Multiple alternative conflictingly named path templates are +// specified. The one that matches is used to construct the header. +// +// annotation: +// +// option (google.api.routing) = { +// // Take the `table_name`, if it's well-formed, whether +// // using the region- or projects-based syntax. +// +// routing_parameters { +// field: "table_name" +// path_template: "{table_name=regions/*/zones/*/**}" +// } +// routing_parameters { +// field: "table_name" +// path_template: "{table_name=projects/*/instances/*/**}" +// } +// }; +// +// result: +// +// x-goog-request-params: +// table_name=projects/proj_foo/instances/instance_bar/table/table_baz +// +// Example 4 +// +// Extracting a single routing header key-value pair by matching a +// template syntax on (a part of) a single request field. +// +// annotation: +// +// option (google.api.routing) = { +// // Take just the project id from the `table_name` field. +// routing_parameters { +// field: "table_name" +// path_template: "{routing_id=projects/*}/**" +// } +// }; +// +// result: +// +// x-goog-request-params: routing_id=projects/proj_foo +// +// Example 5 +// +// Extracting a single routing header key-value pair by matching +// several conflictingly named path templates on (parts of) a single request +// field. The last template to match "wins" the conflict. +// +// annotation: +// +// option (google.api.routing) = { +// // If the `table_name` does not have instances information, +// // take just the project id for routing. +// // Otherwise take project + instance. +// +// routing_parameters { +// field: "table_name" +// path_template: "{routing_id=projects/*}/**" +// } +// routing_parameters { +// field: "table_name" +// path_template: "{routing_id=projects/*/instances/*}/**" +// } +// }; +// +// result: +// +// x-goog-request-params: +// routing_id=projects/proj_foo/instances/instance_bar +// +// Example 6 +// +// Extracting multiple routing header key-value pairs by matching +// several non-conflicting path templates on (parts of) a single request field. +// +// Sub-example 6a +// +// Make the templates strict, so that if the `table_name` does not +// have an instance information, nothing is sent. +// +// annotation: +// +// option (google.api.routing) = { +// // The routing code needs two keys instead of one composite +// // but works only for the tables with the "project-instance" name +// // syntax. +// +// routing_parameters { +// field: "table_name" +// path_template: "{project_id=projects/*}/instances/*/**" +// } +// routing_parameters { +// field: "table_name" +// path_template: "projects/*/{instance_id=instances/*}/**" +// } +// }; +// +// result: +// +// x-goog-request-params: +// project_id=projects/proj_foo&instance_id=instances/instance_bar +// +// Sub-example 6b +// +// Make the templates loose, so that if the `table_name` does not +// have an instance information, just the project id part is sent. +// +// annotation: +// +// option (google.api.routing) = { +// // The routing code wants two keys instead of one composite +// // but will work with just the `project_id` for tables without +// // an instance in the `table_name`. +// +// routing_parameters { +// field: "table_name" +// path_template: "{project_id=projects/*}/**" +// } +// routing_parameters { +// field: "table_name" +// path_template: "projects/*/{instance_id=instances/*}/**" +// } +// }; +// +// result (is the same as 6a for our example message because it has the instance +// information): +// +// x-goog-request-params: +// project_id=projects/proj_foo&instance_id=instances/instance_bar +// +// Example 7 +// +// Extracting multiple routing header key-value pairs by matching +// several path templates on multiple request fields. +// +// NB: note that here there is no way to specify sending nothing if one of the +// fields does not match its template. E.g. if the `table_name` is in the wrong +// format, the `project_id` will not be sent, but the `routing_id` will be. +// The backend routing code has to be aware of that and be prepared to not +// receive a full complement of keys if it expects multiple. +// +// annotation: +// +// option (google.api.routing) = { +// // The routing needs both `project_id` and `routing_id` +// // (from the `app_profile_id` field) for routing. +// +// routing_parameters { +// field: "table_name" +// path_template: "{project_id=projects/*}/**" +// } +// routing_parameters { +// field: "app_profile_id" +// path_template: "{routing_id=**}" +// } +// }; +// +// result: +// +// x-goog-request-params: +// project_id=projects/proj_foo&routing_id=profiles/prof_qux +// +// Example 8 +// +// Extracting a single routing header key-value pair by matching +// several conflictingly named path templates on several request fields. The +// last template to match "wins" the conflict. +// +// annotation: +// +// option (google.api.routing) = { +// // The `routing_id` can be a project id or a region id depending on +// // the table name format, but only if the `app_profile_id` is not set. +// // If `app_profile_id` is set it should be used instead. +// +// routing_parameters { +// field: "table_name" +// path_template: "{routing_id=projects/*}/**" +// } +// routing_parameters { +// field: "table_name" +// path_template: "{routing_id=regions/*}/**" +// } +// routing_parameters { +// field: "app_profile_id" +// path_template: "{routing_id=**}" +// } +// }; +// +// result: +// +// x-goog-request-params: routing_id=profiles/prof_qux +// +// Example 9 +// +// Bringing it all together. +// +// annotation: +// +// option (google.api.routing) = { +// // For routing both `table_location` and a `routing_id` are needed. +// // +// // table_location can be either an instance id or a region+zone id. +// // +// // For `routing_id`, take the value of `app_profile_id` +// // - If it's in the format `profiles/`, send +// // just the `` part. +// // - If it's any other literal, send it as is. +// // If the `app_profile_id` is empty, and the `table_name` starts with +// // the project_id, send that instead. +// +// routing_parameters { +// field: "table_name" +// path_template: "projects/*/{table_location=instances/*}/tables/*" +// } +// routing_parameters { +// field: "table_name" +// path_template: "{table_location=regions/*/zones/*}/tables/*" +// } +// routing_parameters { +// field: "table_name" +// path_template: "{routing_id=projects/*}/**" +// } +// routing_parameters { +// field: "app_profile_id" +// path_template: "{routing_id=**}" +// } +// routing_parameters { +// field: "app_profile_id" +// path_template: "profiles/{routing_id=*}" +// } +// }; +// +// result: +// +// x-goog-request-params: +// table_location=instances/instance_bar&routing_id=prof_qux +message RoutingRule { + // A collection of Routing Parameter specifications. + // **NOTE:** If multiple Routing Parameters describe the same key + // (via the `path_template` field or via the `field` field when + // `path_template` is not provided), "last one wins" rule + // determines which Parameter gets used. + // See the examples for more details. + repeated RoutingParameter routing_parameters = 2; +} + +// A projection from an input message to the GRPC or REST header. +message RoutingParameter { + // A request field to extract the header key-value pair from. + string field = 1; + + // A pattern matching the key-value field. Optional. + // If not specified, the whole field specified in the `field` field will be + // taken as value, and its name used as key. If specified, it MUST contain + // exactly one named segment (along with any number of unnamed segments) The + // pattern will be matched over the field specified in the `field` field, then + // if the match is successful: + // - the name of the single named segment will be used as a header name, + // - the match value of the segment will be used as a header value; + // if the match is NOT successful, nothing will be sent. + // + // Example: + // + // -- This is a field in the request message + // | that the header value will be extracted from. + // | + // | -- This is the key name in the + // | | routing header. + // V | + // field: "table_name" v + // path_template: "projects/*/{table_location=instances/*}/tables/*" + // ^ ^ + // | | + // In the {} brackets is the pattern that -- | + // specifies what to extract from the | + // field as a value to be sent. | + // | + // The string in the field must match the whole pattern -- + // before brackets, inside brackets, after brackets. + // + // When looking at this specific example, we can see that: + // - A key-value pair with the key `table_location` + // and the value matching `instances/*` should be added + // to the x-goog-request-params routing header. + // - The value is extracted from the request message's `table_name` field + // if it matches the full pattern specified: + // `projects/*/instances/*/tables/*`. + // + // **NB:** If the `path_template` field is not provided, the key name is + // equal to the field name, and the whole field should be sent as a value. + // This makes the pattern for the field and the value functionally equivalent + // to `**`, and the configuration + // + // { + // field: "table_name" + // } + // + // is a functionally equivalent shorthand to: + // + // { + // field: "table_name" + // path_template: "{table_name=**}" + // } + // + // See Example 1 for more details. + string path_template = 2; +} diff --git a/node_modules/google-gax/build/protos/google/api/service.proto b/node_modules/google-gax/build/protos/google/api/service.proto new file mode 100644 index 0000000..3de5b66 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/service.proto @@ -0,0 +1,191 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/api/auth.proto"; +import "google/api/backend.proto"; +import "google/api/billing.proto"; +import "google/api/client.proto"; +import "google/api/context.proto"; +import "google/api/control.proto"; +import "google/api/documentation.proto"; +import "google/api/endpoint.proto"; +import "google/api/http.proto"; +import "google/api/log.proto"; +import "google/api/logging.proto"; +import "google/api/metric.proto"; +import "google/api/monitored_resource.proto"; +import "google/api/monitoring.proto"; +import "google/api/quota.proto"; +import "google/api/source_info.proto"; +import "google/api/system_parameter.proto"; +import "google/api/usage.proto"; +import "google/protobuf/api.proto"; +import "google/protobuf/type.proto"; +import "google/protobuf/wrappers.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/serviceconfig;serviceconfig"; +option java_multiple_files = true; +option java_outer_classname = "ServiceProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// `Service` is the root object of Google API service configuration (service +// config). It describes the basic information about a logical service, +// such as the service name and the user-facing title, and delegates other +// aspects to sub-sections. Each sub-section is either a proto message or a +// repeated proto message that configures a specific aspect, such as auth. +// For more information, see each proto message definition. +// +// Example: +// +// type: google.api.Service +// name: calendar.googleapis.com +// title: Google Calendar API +// apis: +// - name: google.calendar.v3.Calendar +// +// visibility: +// rules: +// - selector: "google.calendar.v3.*" +// restriction: PREVIEW +// backend: +// rules: +// - selector: "google.calendar.v3.*" +// address: calendar.example.com +// +// authentication: +// providers: +// - id: google_calendar_auth +// jwks_uri: https://www.googleapis.com/oauth2/v1/certs +// issuer: https://securetoken.google.com +// rules: +// - selector: "*" +// requirements: +// provider_id: google_calendar_auth +message Service { + // The service name, which is a DNS-like logical identifier for the + // service, such as `calendar.googleapis.com`. The service name + // typically goes through DNS verification to make sure the owner + // of the service also owns the DNS name. + string name = 1; + + // The product title for this service, it is the name displayed in Google + // Cloud Console. + string title = 2; + + // The Google project that owns this service. + string producer_project_id = 22; + + // A unique ID for a specific instance of this message, typically assigned + // by the client for tracking purpose. Must be no longer than 63 characters + // and only lower case letters, digits, '.', '_' and '-' are allowed. If + // empty, the server may choose to generate one instead. + string id = 33; + + // A list of API interfaces exported by this service. Only the `name` field + // of the [google.protobuf.Api][google.protobuf.Api] needs to be provided by + // the configuration author, as the remaining fields will be derived from the + // IDL during the normalization process. It is an error to specify an API + // interface here which cannot be resolved against the associated IDL files. + repeated google.protobuf.Api apis = 3; + + // A list of all proto message types included in this API service. + // Types referenced directly or indirectly by the `apis` are automatically + // included. Messages which are not referenced but shall be included, such as + // types used by the `google.protobuf.Any` type, should be listed here by + // name by the configuration author. Example: + // + // types: + // - name: google.protobuf.Int32 + repeated google.protobuf.Type types = 4; + + // A list of all enum types included in this API service. Enums referenced + // directly or indirectly by the `apis` are automatically included. Enums + // which are not referenced but shall be included should be listed here by + // name by the configuration author. Example: + // + // enums: + // - name: google.someapi.v1.SomeEnum + repeated google.protobuf.Enum enums = 5; + + // Additional API documentation. + Documentation documentation = 6; + + // API backend configuration. + Backend backend = 8; + + // HTTP configuration. + Http http = 9; + + // Quota configuration. + Quota quota = 10; + + // Auth configuration. + Authentication authentication = 11; + + // Context configuration. + Context context = 12; + + // Configuration controlling usage of this service. + Usage usage = 15; + + // Configuration for network endpoints. If this is empty, then an endpoint + // with the same name as the service is automatically generated to service all + // defined APIs. + repeated Endpoint endpoints = 18; + + // Configuration for the service control plane. + Control control = 21; + + // Defines the logs used by this service. + repeated LogDescriptor logs = 23; + + // Defines the metrics used by this service. + repeated MetricDescriptor metrics = 24; + + // Defines the monitored resources used by this service. This is required + // by the [Service.monitoring][google.api.Service.monitoring] and + // [Service.logging][google.api.Service.logging] configurations. + repeated MonitoredResourceDescriptor monitored_resources = 25; + + // Billing configuration. + Billing billing = 26; + + // Logging configuration. + Logging logging = 27; + + // Monitoring configuration. + Monitoring monitoring = 28; + + // System parameter configuration. + SystemParameters system_parameters = 29; + + // Output only. The source information for this configuration if available. + SourceInfo source_info = 37; + + // Settings for [Google Cloud Client + // libraries](https://cloud.google.com/apis/docs/cloud-client-libraries) + // generated from APIs defined as protocol buffers. + Publishing publishing = 45; + + // Obsolete. Do not use. + // + // This field has no semantic meaning. The service config compiler always + // sets this field to `3`. + google.protobuf.UInt32Value config_version = 20; +} diff --git a/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/check_error.proto b/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/check_error.proto new file mode 100644 index 0000000..5c97e91 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/check_error.proto @@ -0,0 +1,124 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.servicecontrol.v1; + +import "google/rpc/status.proto"; + +option cc_enable_arenas = true; +option csharp_namespace = "Google.Cloud.ServiceControl.V1"; +option go_package = "cloud.google.com/go/servicecontrol/apiv1/servicecontrolpb;servicecontrolpb"; +option java_multiple_files = true; +option java_outer_classname = "CheckErrorProto"; +option java_package = "com.google.api.servicecontrol.v1"; +option php_namespace = "Google\\Cloud\\ServiceControl\\V1"; +option ruby_package = "Google::Cloud::ServiceControl::V1"; + +// Defines the errors to be returned in +// [google.api.servicecontrol.v1.CheckResponse.check_errors][google.api.servicecontrol.v1.CheckResponse.check_errors]. +message CheckError { + // Error codes for Check responses. + enum Code { + // This is never used in `CheckResponse`. + ERROR_CODE_UNSPECIFIED = 0; + + // The consumer's project id, network container, or resource container was + // not found. Same as [google.rpc.Code.NOT_FOUND][google.rpc.Code.NOT_FOUND]. + NOT_FOUND = 5; + + // The consumer doesn't have access to the specified resource. + // Same as [google.rpc.Code.PERMISSION_DENIED][google.rpc.Code.PERMISSION_DENIED]. + PERMISSION_DENIED = 7; + + // Quota check failed. Same as [google.rpc.Code.RESOURCE_EXHAUSTED][google.rpc.Code.RESOURCE_EXHAUSTED]. + RESOURCE_EXHAUSTED = 8; + + // The consumer hasn't activated the service. + SERVICE_NOT_ACTIVATED = 104; + + // The consumer cannot access the service because billing is disabled. + BILLING_DISABLED = 107; + + // The consumer's project has been marked as deleted (soft deletion). + PROJECT_DELETED = 108; + + // The consumer's project number or id does not represent a valid project. + PROJECT_INVALID = 114; + + // The input consumer info does not represent a valid consumer folder or + // organization. + CONSUMER_INVALID = 125; + + // The IP address of the consumer is invalid for the specific consumer + // project. + IP_ADDRESS_BLOCKED = 109; + + // The referer address of the consumer request is invalid for the specific + // consumer project. + REFERER_BLOCKED = 110; + + // The client application of the consumer request is invalid for the + // specific consumer project. + CLIENT_APP_BLOCKED = 111; + + // The API targeted by this request is invalid for the specified consumer + // project. + API_TARGET_BLOCKED = 122; + + // The consumer's API key is invalid. + API_KEY_INVALID = 105; + + // The consumer's API Key has expired. + API_KEY_EXPIRED = 112; + + // The consumer's API Key was not found in config record. + API_KEY_NOT_FOUND = 113; + + // The credential in the request can not be verified. + INVALID_CREDENTIAL = 123; + + // The backend server for looking up project id/number is unavailable. + NAMESPACE_LOOKUP_UNAVAILABLE = 300; + + // The backend server for checking service status is unavailable. + SERVICE_STATUS_UNAVAILABLE = 301; + + // The backend server for checking billing status is unavailable. + BILLING_STATUS_UNAVAILABLE = 302; + + // Cloud Resource Manager backend server is unavailable. + CLOUD_RESOURCE_MANAGER_BACKEND_UNAVAILABLE = 305; + } + + // The error code. + Code code = 1; + + // Subject to whom this error applies. See the specific code enum for more + // details on this field. For example: + // + // - "project:" + // - "folder:" + // - "organization:" + string subject = 4; + + // Free-form text providing details on the error cause of the error. + string detail = 2; + + // Contains public information about the check error. If available, + // `status.code` will be non zero and client can propagate it out as public + // error. + google.rpc.Status status = 3; +} diff --git a/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/distribution.proto b/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/distribution.proto new file mode 100644 index 0000000..17c92e9 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/distribution.proto @@ -0,0 +1,166 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.servicecontrol.v1; + +import "google/api/distribution.proto"; + +option cc_enable_arenas = true; +option csharp_namespace = "Google.Cloud.ServiceControl.V1"; +option go_package = "cloud.google.com/go/servicecontrol/apiv1/servicecontrolpb;servicecontrolpb"; +option java_multiple_files = true; +option java_outer_classname = "DistributionProto"; +option java_package = "com.google.api.servicecontrol.v1"; +option php_namespace = "Google\\Cloud\\ServiceControl\\V1"; +option ruby_package = "Google::Cloud::ServiceControl::V1"; + +// Distribution represents a frequency distribution of double-valued sample +// points. It contains the size of the population of sample points plus +// additional optional information: +// +// * the arithmetic mean of the samples +// * the minimum and maximum of the samples +// * the sum-squared-deviation of the samples, used to compute variance +// * a histogram of the values of the sample points +message Distribution { + // Describing buckets with constant width. + message LinearBuckets { + // The number of finite buckets. With the underflow and overflow buckets, + // the total number of buckets is `num_finite_buckets` + 2. + // See comments on `bucket_options` for details. + int32 num_finite_buckets = 1; + + // The i'th linear bucket covers the interval + // [offset + (i-1) * width, offset + i * width) + // where i ranges from 1 to num_finite_buckets, inclusive. + // Must be strictly positive. + double width = 2; + + // The i'th linear bucket covers the interval + // [offset + (i-1) * width, offset + i * width) + // where i ranges from 1 to num_finite_buckets, inclusive. + double offset = 3; + } + + // Describing buckets with exponentially growing width. + message ExponentialBuckets { + // The number of finite buckets. With the underflow and overflow buckets, + // the total number of buckets is `num_finite_buckets` + 2. + // See comments on `bucket_options` for details. + int32 num_finite_buckets = 1; + + // The i'th exponential bucket covers the interval + // [scale * growth_factor^(i-1), scale * growth_factor^i) + // where i ranges from 1 to num_finite_buckets inclusive. + // Must be larger than 1.0. + double growth_factor = 2; + + // The i'th exponential bucket covers the interval + // [scale * growth_factor^(i-1), scale * growth_factor^i) + // where i ranges from 1 to num_finite_buckets inclusive. + // Must be > 0. + double scale = 3; + } + + // Describing buckets with arbitrary user-provided width. + message ExplicitBuckets { + // 'bound' is a list of strictly increasing boundaries between + // buckets. Note that a list of length N-1 defines N buckets because + // of fenceposting. See comments on `bucket_options` for details. + // + // The i'th finite bucket covers the interval + // [bound[i-1], bound[i]) + // where i ranges from 1 to bound_size() - 1. Note that there are no + // finite buckets at all if 'bound' only contains a single element; in + // that special case the single bound defines the boundary between the + // underflow and overflow buckets. + // + // bucket number lower bound upper bound + // i == 0 (underflow) -inf bound[i] + // 0 < i < bound_size() bound[i-1] bound[i] + // i == bound_size() (overflow) bound[i-1] +inf + repeated double bounds = 1; + } + + // The total number of samples in the distribution. Must be >= 0. + int64 count = 1; + + // The arithmetic mean of the samples in the distribution. If `count` is + // zero then this field must be zero. + double mean = 2; + + // The minimum of the population of values. Ignored if `count` is zero. + double minimum = 3; + + // The maximum of the population of values. Ignored if `count` is zero. + double maximum = 4; + + // The sum of squared deviations from the mean: + // Sum[i=1..count]((x_i - mean)^2) + // where each x_i is a sample values. If `count` is zero then this field + // must be zero, otherwise validation of the request fails. + double sum_of_squared_deviation = 5; + + // The number of samples in each histogram bucket. `bucket_counts` are + // optional. If present, they must sum to the `count` value. + // + // The buckets are defined below in `bucket_option`. There are N buckets. + // `bucket_counts[0]` is the number of samples in the underflow bucket. + // `bucket_counts[1]` to `bucket_counts[N-1]` are the numbers of samples + // in each of the finite buckets. And `bucket_counts[N] is the number + // of samples in the overflow bucket. See the comments of `bucket_option` + // below for more details. + // + // Any suffix of trailing zeros may be omitted. + repeated int64 bucket_counts = 6; + + // Defines the buckets in the histogram. `bucket_option` and `bucket_counts` + // must be both set, or both unset. + // + // Buckets are numbered in the range of [0, N], with a total of N+1 buckets. + // There must be at least two buckets (a single-bucket histogram gives + // no information that isn't already provided by `count`). + // + // The first bucket is the underflow bucket which has a lower bound + // of -inf. The last bucket is the overflow bucket which has an + // upper bound of +inf. All other buckets (if any) are called "finite" + // buckets because they have finite lower and upper bounds. As described + // below, there are three ways to define the finite buckets. + // + // (1) Buckets with constant width. + // (2) Buckets with exponentially growing widths. + // (3) Buckets with arbitrary user-provided widths. + // + // In all cases, the buckets cover the entire real number line (-inf, + // +inf). Bucket upper bounds are exclusive and lower bounds are + // inclusive. The upper bound of the underflow bucket is equal to the + // lower bound of the smallest finite bucket; the lower bound of the + // overflow bucket is equal to the upper bound of the largest finite + // bucket. + oneof bucket_option { + // Buckets with constant width. + LinearBuckets linear_buckets = 7; + + // Buckets with exponentially growing width. + ExponentialBuckets exponential_buckets = 8; + + // Buckets with arbitrary user-provided width. + ExplicitBuckets explicit_buckets = 9; + } + + // Example points. Must be in increasing order of `value` field. + repeated google.api.Distribution.Exemplar exemplars = 10; +} diff --git a/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/http_request.proto b/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/http_request.proto new file mode 100644 index 0000000..9d51a04 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/http_request.proto @@ -0,0 +1,93 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.servicecontrol.v1; + +import "google/protobuf/duration.proto"; + +option csharp_namespace = "Google.Cloud.ServiceControl.V1"; +option go_package = "cloud.google.com/go/servicecontrol/apiv1/servicecontrolpb;servicecontrolpb"; +option java_multiple_files = true; +option java_outer_classname = "HttpRequestProto"; +option java_package = "com.google.api.servicecontrol.v1"; +option php_namespace = "Google\\Cloud\\ServiceControl\\V1"; +option ruby_package = "Google::Cloud::ServiceControl::V1"; + +// A common proto for logging HTTP requests. Only contains semantics +// defined by the HTTP specification. Product-specific logging +// information MUST be defined in a separate message. +message HttpRequest { + // The request method. Examples: `"GET"`, `"HEAD"`, `"PUT"`, `"POST"`. + string request_method = 1; + + // The scheme (http, https), the host name, the path, and the query + // portion of the URL that was requested. + // Example: `"http://example.com/some/info?color=red"`. + string request_url = 2; + + // The size of the HTTP request message in bytes, including the request + // headers and the request body. + int64 request_size = 3; + + // The response code indicating the status of the response. + // Examples: 200, 404. + int32 status = 4; + + // The size of the HTTP response message sent back to the client, in bytes, + // including the response headers and the response body. + int64 response_size = 5; + + // The user agent sent by the client. Example: + // `"Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; Q312461; .NET + // CLR 1.0.3705)"`. + string user_agent = 6; + + // The IP address (IPv4 or IPv6) of the client that issued the HTTP + // request. Examples: `"192.168.1.1"`, `"FE80::0202:B3FF:FE1E:8329"`. + string remote_ip = 7; + + // The IP address (IPv4 or IPv6) of the origin server that the request was + // sent to. + string server_ip = 13; + + // The referer URL of the request, as defined in + // [HTTP/1.1 Header Field + // Definitions](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). + string referer = 8; + + // The request processing latency on the server, from the time the request was + // received until the response was sent. + google.protobuf.Duration latency = 14; + + // Whether or not a cache lookup was attempted. + bool cache_lookup = 11; + + // Whether or not an entity was served from cache + // (with or without validation). + bool cache_hit = 9; + + // Whether or not the response was validated with the origin server before + // being served from cache. This field is only meaningful if `cache_hit` is + // True. + bool cache_validated_with_origin_server = 10; + + // The number of HTTP response bytes inserted into cache. Set only when a + // cache fill was attempted. + int64 cache_fill_bytes = 12; + + // Protocol used for the request. Examples: "HTTP/1.1", "HTTP/2", "websocket" + string protocol = 15; +} diff --git a/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/log_entry.proto b/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/log_entry.proto new file mode 100644 index 0000000..410b2ae --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/log_entry.proto @@ -0,0 +1,126 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.servicecontrol.v1; + +import "google/api/servicecontrol/v1/http_request.proto"; +import "google/logging/type/log_severity.proto"; +import "google/protobuf/any.proto"; +import "google/protobuf/struct.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.ServiceControl.V1"; +option go_package = "cloud.google.com/go/servicecontrol/apiv1/servicecontrolpb;servicecontrolpb"; +option java_multiple_files = true; +option java_outer_classname = "LogEntryProto"; +option java_package = "com.google.api.servicecontrol.v1"; +option php_namespace = "Google\\Cloud\\ServiceControl\\V1"; +option ruby_package = "Google::Cloud::ServiceControl::V1"; + +// An individual log entry. +message LogEntry { + // Required. The log to which this log entry belongs. Examples: `"syslog"`, + // `"book_log"`. + string name = 10; + + // The time the event described by the log entry occurred. If + // omitted, defaults to operation start time. + google.protobuf.Timestamp timestamp = 11; + + // The severity of the log entry. The default value is + // `LogSeverity.DEFAULT`. + google.logging.type.LogSeverity severity = 12; + + // Optional. Information about the HTTP request associated with this + // log entry, if applicable. + HttpRequest http_request = 14; + + // Optional. Resource name of the trace associated with the log entry, if any. + // If this field contains a relative resource name, you can assume the name is + // relative to `//tracing.googleapis.com`. Example: + // `projects/my-projectid/traces/06796866738c859f2f19b7cfb3214824` + string trace = 15; + + // A unique ID for the log entry used for deduplication. If omitted, + // the implementation will generate one based on operation_id. + string insert_id = 4; + + // A set of user-defined (key, value) data that provides additional + // information about the log entry. + map labels = 13; + + // The log entry payload, which can be one of multiple types. + oneof payload { + // The log entry payload, represented as a protocol buffer that is + // expressed as a JSON object. The only accepted type currently is + // [AuditLog][google.cloud.audit.AuditLog]. + google.protobuf.Any proto_payload = 2; + + // The log entry payload, represented as a Unicode string (UTF-8). + string text_payload = 3; + + // The log entry payload, represented as a structure that + // is expressed as a JSON object. + google.protobuf.Struct struct_payload = 6; + } + + // Optional. Information about an operation associated with the log entry, if + // applicable. + LogEntryOperation operation = 16; + + // Optional. Source code location information associated with the log entry, + // if any. + LogEntrySourceLocation source_location = 17; +} + +// Additional information about a potentially long-running operation with which +// a log entry is associated. +message LogEntryOperation { + // Optional. An arbitrary operation identifier. Log entries with the + // same identifier are assumed to be part of the same operation. + string id = 1; + + // Optional. An arbitrary producer identifier. The combination of + // `id` and `producer` must be globally unique. Examples for `producer`: + // `"MyDivision.MyBigCompany.com"`, `"github.com/MyProject/MyApplication"`. + string producer = 2; + + // Optional. Set this to True if this is the first log entry in the operation. + bool first = 3; + + // Optional. Set this to True if this is the last log entry in the operation. + bool last = 4; +} + +// Additional information about the source code location that produced the log +// entry. +message LogEntrySourceLocation { + // Optional. Source file name. Depending on the runtime environment, this + // might be a simple name or a fully-qualified name. + string file = 1; + + // Optional. Line within the source file. 1-based; 0 indicates no line number + // available. + int64 line = 2; + + // Optional. Human-readable name of the function or method being invoked, with + // optional context such as the class or package name. This information may be + // used in contexts such as the logs viewer, where a file and line number are + // less meaningful. The format can vary by language. For example: + // `qual.if.ied.Class.method` (Java), `dir/package.func` (Go), `function` + // (Python). + string function = 3; +} diff --git a/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/metric_value.proto b/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/metric_value.proto new file mode 100644 index 0000000..c84f47c --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/metric_value.proto @@ -0,0 +1,81 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.servicecontrol.v1; + +import "google/api/servicecontrol/v1/distribution.proto"; +import "google/protobuf/timestamp.proto"; + +option cc_enable_arenas = true; +option csharp_namespace = "Google.Cloud.ServiceControl.V1"; +option go_package = "cloud.google.com/go/servicecontrol/apiv1/servicecontrolpb;servicecontrolpb"; +option java_multiple_files = true; +option java_outer_classname = "MetricValueSetProto"; +option java_package = "com.google.api.servicecontrol.v1"; +option php_namespace = "Google\\Cloud\\ServiceControl\\V1"; +option ruby_package = "Google::Cloud::ServiceControl::V1"; + +// Represents a single metric value. +message MetricValue { + // The labels describing the metric value. + // See comments on [google.api.servicecontrol.v1.Operation.labels][google.api.servicecontrol.v1.Operation.labels] for + // the overriding relationship. + // Note that this map must not contain monitored resource labels. + map labels = 1; + + // The start of the time period over which this metric value's measurement + // applies. The time period has different semantics for different metric + // types (cumulative, delta, and gauge). See the metric definition + // documentation in the service configuration for details. If not specified, + // [google.api.servicecontrol.v1.Operation.start_time][google.api.servicecontrol.v1.Operation.start_time] will be used. + google.protobuf.Timestamp start_time = 2; + + // The end of the time period over which this metric value's measurement + // applies. If not specified, + // [google.api.servicecontrol.v1.Operation.end_time][google.api.servicecontrol.v1.Operation.end_time] will be used. + google.protobuf.Timestamp end_time = 3; + + // The value. The type of value used in the request must + // agree with the metric definition in the service configuration, otherwise + // the MetricValue is rejected. + oneof value { + // A boolean value. + bool bool_value = 4; + + // A signed 64-bit integer value. + int64 int64_value = 5; + + // A double precision floating point value. + double double_value = 6; + + // A text string value. + string string_value = 7; + + // A distribution value. + Distribution distribution_value = 8; + } +} + +// Represents a set of metric values in the same metric. +// Each metric value in the set should have a unique combination of start time, +// end time, and label values. +message MetricValueSet { + // The metric name defined in the service configuration. + string metric_name = 1; + + // The values in this metric. + repeated MetricValue metric_values = 2; +} diff --git a/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/operation.proto b/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/operation.proto new file mode 100644 index 0000000..e477a48 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/operation.proto @@ -0,0 +1,123 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.servicecontrol.v1; + +import "google/api/servicecontrol/v1/log_entry.proto"; +import "google/api/servicecontrol/v1/metric_value.proto"; +import "google/protobuf/any.proto"; +import "google/protobuf/timestamp.proto"; + +option cc_enable_arenas = true; +option csharp_namespace = "Google.Cloud.ServiceControl.V1"; +option go_package = "cloud.google.com/go/servicecontrol/apiv1/servicecontrolpb;servicecontrolpb"; +option java_multiple_files = true; +option java_outer_classname = "OperationProto"; +option java_package = "com.google.api.servicecontrol.v1"; +option php_namespace = "Google\\Cloud\\ServiceControl\\V1"; +option ruby_package = "Google::Cloud::ServiceControl::V1"; + +// Represents information regarding an operation. +message Operation { + // Defines the importance of the data contained in the operation. + enum Importance { + // Allows data caching, batching, and aggregation. It provides + // higher performance with higher data loss risk. + LOW = 0; + + // Disables data aggregation to minimize data loss. It is for operations + // that contains significant monetary value or audit trail. This feature + // only applies to the client libraries. + HIGH = 1; + } + + // Identity of the operation. This must be unique within the scope of the + // service that generated the operation. If the service calls + // Check() and Report() on the same operation, the two calls should carry + // the same id. + // + // UUID version 4 is recommended, though not required. + // In scenarios where an operation is computed from existing information + // and an idempotent id is desirable for deduplication purpose, UUID version 5 + // is recommended. See RFC 4122 for details. + string operation_id = 1; + + // Fully qualified name of the operation. Reserved for future use. + string operation_name = 2; + + // Identity of the consumer who is using the service. + // This field should be filled in for the operations initiated by a + // consumer, but not for service-initiated operations that are + // not related to a specific consumer. + // + // - This can be in one of the following formats: + // - project:PROJECT_ID, + // - project`_`number:PROJECT_NUMBER, + // - projects/PROJECT_ID or PROJECT_NUMBER, + // - folders/FOLDER_NUMBER, + // - organizations/ORGANIZATION_NUMBER, + // - api`_`key:API_KEY. + string consumer_id = 3; + + // Required. Start time of the operation. + google.protobuf.Timestamp start_time = 4; + + // End time of the operation. + // Required when the operation is used in + // [ServiceController.Report][google.api.servicecontrol.v1.ServiceController.Report], + // but optional when the operation is used in + // [ServiceController.Check][google.api.servicecontrol.v1.ServiceController.Check]. + google.protobuf.Timestamp end_time = 5; + + // Labels describing the operation. Only the following labels are allowed: + // + // - Labels describing monitored resources as defined in + // the service configuration. + // - Default labels of metric values. When specified, labels defined in the + // metric value override these default. + // - The following labels defined by Google Cloud Platform: + // - `cloud.googleapis.com/location` describing the location where the + // operation happened, + // - `servicecontrol.googleapis.com/user_agent` describing the user agent + // of the API request, + // - `servicecontrol.googleapis.com/service_agent` describing the service + // used to handle the API request (e.g. ESP), + // - `servicecontrol.googleapis.com/platform` describing the platform + // where the API is served, such as App Engine, Compute Engine, or + // Kubernetes Engine. + map labels = 6; + + // Represents information about this operation. Each MetricValueSet + // corresponds to a metric defined in the service configuration. + // The data type used in the MetricValueSet must agree with + // the data type specified in the metric definition. + // + // Within a single operation, it is not allowed to have more than one + // MetricValue instances that have the same metric names and identical + // label value combinations. If a request has such duplicated MetricValue + // instances, the entire request is rejected with + // an invalid argument error. + repeated MetricValueSet metric_value_sets = 7; + + // Represents information to be logged. + repeated LogEntry log_entries = 8; + + // DO NOT USE. This is an experimental field. + Importance importance = 11; + + // Unimplemented. + repeated google.protobuf.Any extensions = 16; +} diff --git a/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/quota_controller.proto b/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/quota_controller.proto new file mode 100644 index 0000000..b4b1198 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/quota_controller.proto @@ -0,0 +1,245 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.servicecontrol.v1; + +import "google/api/annotations.proto"; +import "google/api/servicecontrol/v1/metric_value.proto"; +import "google/rpc/status.proto"; +import "google/api/client.proto"; + +option cc_enable_arenas = true; +option csharp_namespace = "Google.Cloud.ServiceControl.V1"; +option go_package = "cloud.google.com/go/servicecontrol/apiv1/servicecontrolpb;servicecontrolpb"; +option java_multiple_files = true; +option java_outer_classname = "QuotaControllerProto"; +option java_package = "com.google.api.servicecontrol.v1"; +option php_namespace = "Google\\Cloud\\ServiceControl\\V1"; +option ruby_package = "Google::Cloud::ServiceControl::V1"; + +// [Google Quota Control API](/service-control/overview) +// +// Allows clients to allocate and release quota against a [managed +// service](https://cloud.google.com/service-management/reference/rpc/google.api/servicemanagement.v1#google.api.servicemanagement.v1.ManagedService). +service QuotaController { + option (google.api.default_host) = "servicecontrol.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/servicecontrol"; + + // Attempts to allocate quota for the specified consumer. It should be called + // before the operation is executed. + // + // This method requires the `servicemanagement.services.quota` + // permission on the specified service. For more information, see + // [Cloud IAM](https://cloud.google.com/iam). + // + // **NOTE:** The client **must** fail-open on server errors `INTERNAL`, + // `UNKNOWN`, `DEADLINE_EXCEEDED`, and `UNAVAILABLE`. To ensure system + // reliability, the server may inject these errors to prohibit any hard + // dependency on the quota functionality. + rpc AllocateQuota(AllocateQuotaRequest) returns (AllocateQuotaResponse) { + option (google.api.http) = { + post: "/v1/services/{service_name}:allocateQuota" + body: "*" + }; + } +} + +// Request message for the AllocateQuota method. +message AllocateQuotaRequest { + // Name of the service as specified in the service configuration. For example, + // `"pubsub.googleapis.com"`. + // + // See [google.api.Service][google.api.Service] for the definition of a service name. + string service_name = 1; + + // Operation that describes the quota allocation. + QuotaOperation allocate_operation = 2; + + // Specifies which version of service configuration should be used to process + // the request. If unspecified or no matching version can be found, the latest + // one will be used. + string service_config_id = 4; +} + +// Represents information regarding a quota operation. +message QuotaOperation { + // Supported quota modes. + enum QuotaMode { + // Guard against implicit default. Must not be used. + UNSPECIFIED = 0; + + // For AllocateQuota request, allocates quota for the amount specified in + // the service configuration or specified using the quota metrics. If the + // amount is higher than the available quota, allocation error will be + // returned and no quota will be allocated. + // If multiple quotas are part of the request, and one fails, none of the + // quotas are allocated or released. + NORMAL = 1; + + // The operation allocates quota for the amount specified in the service + // configuration or specified using the quota metrics. If the amount is + // higher than the available quota, request does not fail but all available + // quota will be allocated. + // For rate quota, BEST_EFFORT will continue to deduct from other groups + // even if one does not have enough quota. For allocation, it will find the + // minimum available amount across all groups and deduct that amount from + // all the affected groups. + BEST_EFFORT = 2; + + // For AllocateQuota request, only checks if there is enough quota + // available and does not change the available quota. No lock is placed on + // the available quota either. + CHECK_ONLY = 3; + + // Unimplemented. When used in AllocateQuotaRequest, this returns the + // effective quota limit(s) in the response, and no quota check will be + // performed. Not supported for other requests, and even for + // AllocateQuotaRequest, this is currently supported only for allowlisted + // services. + QUERY_ONLY = 4; + + // The operation allocates quota for the amount specified in the service + // configuration or specified using the quota metrics. If the requested + // amount is higher than the available quota, request does not fail and + // remaining quota would become negative (going over the limit). + // Not supported for Rate Quota. + ADJUST_ONLY = 5; + } + + // Identity of the operation. This is expected to be unique within the scope + // of the service that generated the operation, and guarantees idempotency in + // case of retries. + // + // In order to ensure best performance and latency in the Quota backends, + // operation_ids are optimally associated with time, so that related + // operations can be accessed fast in storage. For this reason, the + // recommended token for services that intend to operate at a high QPS is + // Unix time in nanos + UUID + string operation_id = 1; + + // Fully qualified name of the API method for which this quota operation is + // requested. This name is used for matching quota rules or metric rules and + // billing status rules defined in service configuration. + // + // This field should not be set if any of the following is true: + // (1) the quota operation is performed on non-API resources. + // (2) quota_metrics is set because the caller is doing quota override. + // + // + // Example of an RPC method name: + // google.example.library.v1.LibraryService.CreateShelf + string method_name = 2; + + // Identity of the consumer for whom this quota operation is being performed. + // + // This can be in one of the following formats: + // project:, + // project_number:, + // api_key:. + string consumer_id = 3; + + // Labels describing the operation. + map labels = 4; + + // Represents information about this operation. Each MetricValueSet + // corresponds to a metric defined in the service configuration. + // The data type used in the MetricValueSet must agree with + // the data type specified in the metric definition. + // + // Within a single operation, it is not allowed to have more than one + // MetricValue instances that have the same metric names and identical + // label value combinations. If a request has such duplicated MetricValue + // instances, the entire request is rejected with + // an invalid argument error. + // + // This field is mutually exclusive with method_name. + repeated MetricValueSet quota_metrics = 5; + + // Quota mode for this operation. + QuotaMode quota_mode = 6; +} + +// Response message for the AllocateQuota method. +message AllocateQuotaResponse { + // The same operation_id value used in the AllocateQuotaRequest. Used for + // logging and diagnostics purposes. + string operation_id = 1; + + // Indicates the decision of the allocate. + repeated QuotaError allocate_errors = 2; + + // Quota metrics to indicate the result of allocation. Depending on the + // request, one or more of the following metrics will be included: + // + // 1. Per quota group or per quota metric incremental usage will be specified + // using the following delta metric : + // "serviceruntime.googleapis.com/api/consumer/quota_used_count" + // + // 2. The quota limit reached condition will be specified using the following + // boolean metric : + // "serviceruntime.googleapis.com/quota/exceeded" + repeated MetricValueSet quota_metrics = 3; + + // ID of the actual config used to process the request. + string service_config_id = 4; +} + +// Represents error information for [QuotaOperation][google.api.servicecontrol.v1.QuotaOperation]. +message QuotaError { + // Error codes related to project config validations are deprecated since the + // quota controller methods do not perform these validations. Instead services + // have to call the Check method, without quota_properties field, to perform + // these validations before calling the quota controller methods. These + // methods check only for project deletion to be wipe out compliant. + enum Code { + // This is never used. + UNSPECIFIED = 0; + + // Quota allocation failed. + // Same as [google.rpc.Code.RESOURCE_EXHAUSTED][google.rpc.Code.RESOURCE_EXHAUSTED]. + RESOURCE_EXHAUSTED = 8; + + // Consumer cannot access the service because the service requires active + // billing. + BILLING_NOT_ACTIVE = 107; + + // Consumer's project has been marked as deleted (soft deletion). + PROJECT_DELETED = 108; + + // Specified API key is invalid. + API_KEY_INVALID = 105; + + // Specified API Key has expired. + API_KEY_EXPIRED = 112; + } + + // Error code. + Code code = 1; + + // Subject to whom this error applies. See the specific enum for more details + // on this field. For example, "clientip:" or + // "project:". + string subject = 2; + + // Free-form text that provides details on the cause of the error. + string description = 3; + + // Contains additional information about the quota error. + // If available, `status.code` will be non zero. + google.rpc.Status status = 4; +} diff --git a/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/service_controller.proto b/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/service_controller.proto new file mode 100644 index 0000000..9429744 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/servicecontrol/v1/service_controller.proto @@ -0,0 +1,260 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.servicecontrol.v1; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/servicecontrol/v1/check_error.proto"; +import "google/api/servicecontrol/v1/operation.proto"; +import "google/rpc/status.proto"; + +option cc_enable_arenas = true; +option csharp_namespace = "Google.Cloud.ServiceControl.V1"; +option go_package = "cloud.google.com/go/servicecontrol/apiv1/servicecontrolpb;servicecontrolpb"; +option java_multiple_files = true; +option java_outer_classname = "ServiceControllerProto"; +option java_package = "com.google.api.servicecontrol.v1"; +option objc_class_prefix = "GASC"; +option php_namespace = "Google\\Cloud\\ServiceControl\\V1"; +option ruby_package = "Google::Cloud::ServiceControl::V1"; + +// [Google Service Control API](/service-control/overview) +// +// Lets clients check and report operations against a [managed +// service](https://cloud.google.com/service-management/reference/rpc/google.api/servicemanagement.v1#google.api.servicemanagement.v1.ManagedService). +service ServiceController { + option (google.api.default_host) = "servicecontrol.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/servicecontrol"; + + // Checks whether an operation on a service should be allowed to proceed + // based on the configuration of the service and related policies. It must be + // called before the operation is executed. + // + // If feasible, the client should cache the check results and reuse them for + // 60 seconds. In case of any server errors, the client should rely on the + // cached results for much longer time to avoid outage. + // WARNING: There is general 60s delay for the configuration and policy + // propagation, therefore callers MUST NOT depend on the `Check` method having + // the latest policy information. + // + // NOTE: the [CheckRequest][google.api.servicecontrol.v1.CheckRequest] has + // the size limit (wire-format byte size) of 1MB. + // + // This method requires the `servicemanagement.services.check` permission + // on the specified service. For more information, see + // [Cloud IAM](https://cloud.google.com/iam). + rpc Check(CheckRequest) returns (CheckResponse) { + option (google.api.http) = { + post: "/v1/services/{service_name}:check" + body: "*" + }; + } + + // Reports operation results to Google Service Control, such as logs and + // metrics. It should be called after an operation is completed. + // + // If feasible, the client should aggregate reporting data for up to 5 + // seconds to reduce API traffic. Limiting aggregation to 5 seconds is to + // reduce data loss during client crashes. Clients should carefully choose + // the aggregation time window to avoid data loss risk more than 0.01% + // for business and compliance reasons. + // + // NOTE: the [ReportRequest][google.api.servicecontrol.v1.ReportRequest] has + // the size limit (wire-format byte size) of 1MB. + // + // This method requires the `servicemanagement.services.report` permission + // on the specified service. For more information, see + // [Google Cloud IAM](https://cloud.google.com/iam). + rpc Report(ReportRequest) returns (ReportResponse) { + option (google.api.http) = { + post: "/v1/services/{service_name}:report" + body: "*" + }; + } +} + +// Request message for the Check method. +message CheckRequest { + // The service name as specified in its service configuration. For example, + // `"pubsub.googleapis.com"`. + // + // See + // [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service) + // for the definition of a service name. + string service_name = 1; + + // The operation to be checked. + Operation operation = 2; + + // Specifies which version of service configuration should be used to process + // the request. + // + // If unspecified or no matching version can be found, the + // latest one will be used. + string service_config_id = 4; +} + +// Response message for the Check method. +message CheckResponse { + // Contains additional information about the check operation. + message CheckInfo { + // A list of fields and label keys that are ignored by the server. + // The client doesn't need to send them for following requests to improve + // performance and allow better aggregation. + repeated string unused_arguments = 1; + + // Consumer info of this check. + ConsumerInfo consumer_info = 2; + + // The unique id of the api key in the format of "apikey:". + // This field will be populated when the consumer passed to Service Control + // is an API key and all the API key related validations are successful. + string api_key_uid = 5; + } + + // `ConsumerInfo` provides information about the consumer. + message ConsumerInfo { + // The type of the consumer as defined in + // [Google Resource Manager](https://cloud.google.com/resource-manager/). + enum ConsumerType { + // This is never used. + CONSUMER_TYPE_UNSPECIFIED = 0; + + // The consumer is a Google Cloud Project. + PROJECT = 1; + + // The consumer is a Google Cloud Folder. + FOLDER = 2; + + // The consumer is a Google Cloud Organization. + ORGANIZATION = 3; + + // Service-specific resource container which is defined by the service + // producer to offer their users the ability to manage service control + // functionalities at a finer level of granularity than the PROJECT. + SERVICE_SPECIFIC = 4; + } + + // The Google cloud project number, e.g. 1234567890. A value of 0 indicates + // no project number is found. + // + // NOTE: This field is deprecated after we support flexible consumer + // id. New code should not depend on this field anymore. + int64 project_number = 1; + + // The type of the consumer which should have been defined in + // [Google Resource Manager](https://cloud.google.com/resource-manager/). + ConsumerType type = 2; + + // The consumer identity number, can be Google cloud project number, folder + // number or organization number e.g. 1234567890. A value of 0 indicates no + // consumer number is found. + int64 consumer_number = 3; + } + + // The same operation_id value used in the + // [CheckRequest][google.api.servicecontrol.v1.CheckRequest]. Used for logging + // and diagnostics purposes. + string operation_id = 1; + + // Indicate the decision of the check. + // + // If no check errors are present, the service should process the operation. + // Otherwise the service should use the list of errors to determine the + // appropriate action. + repeated CheckError check_errors = 2; + + // The actual config id used to process the request. + string service_config_id = 5; + + // The current service rollout id used to process the request. + string service_rollout_id = 11; + + // Feedback data returned from the server during processing a Check request. + CheckInfo check_info = 6; +} + +// Request message for the Report method. +message ReportRequest { + // The service name as specified in its service configuration. For example, + // `"pubsub.googleapis.com"`. + // + // See + // [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service) + // for the definition of a service name. + string service_name = 1; + + // Operations to be reported. + // + // Typically the service should report one operation per request. + // Putting multiple operations into a single request is allowed, but should + // be used only when multiple operations are natually available at the time + // of the report. + // + // There is no limit on the number of operations in the same ReportRequest, + // however the ReportRequest size should be no larger than 1MB. See + // [ReportResponse.report_errors][google.api.servicecontrol.v1.ReportResponse.report_errors] + // for partial failure behavior. + repeated Operation operations = 2; + + // Specifies which version of service config should be used to process the + // request. + // + // If unspecified or no matching version can be found, the + // latest one will be used. + string service_config_id = 3; +} + +// Response message for the Report method. +message ReportResponse { + // Represents the processing error of one + // [Operation][google.api.servicecontrol.v1.Operation] in the request. + message ReportError { + // The + // [Operation.operation_id][google.api.servicecontrol.v1.Operation.operation_id] + // value from the request. + string operation_id = 1; + + // Details of the error when processing the + // [Operation][google.api.servicecontrol.v1.Operation]. + google.rpc.Status status = 2; + } + + // Partial failures, one for each `Operation` in the request that failed + // processing. There are three possible combinations of the RPC status: + // + // 1. The combination of a successful RPC status and an empty `report_errors` + // list indicates a complete success where all `Operations` in the + // request are processed successfully. + // 2. The combination of a successful RPC status and a non-empty + // `report_errors` list indicates a partial success where some + // `Operations` in the request succeeded. Each + // `Operation` that failed processing has a corresponding item + // in this list. + // 3. A failed RPC status indicates a general non-deterministic failure. + // When this happens, it's impossible to know which of the + // 'Operations' in the request succeeded or failed. + repeated ReportError report_errors = 1; + + // The actual config id used to process the request. + string service_config_id = 2; + + // The current service rollout id used to process the request. + string service_rollout_id = 4; +} diff --git a/node_modules/google-gax/build/protos/google/api/servicecontrol/v2/service_controller.proto b/node_modules/google-gax/build/protos/google/api/servicecontrol/v2/service_controller.proto new file mode 100644 index 0000000..ff226a0 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/servicecontrol/v2/service_controller.proto @@ -0,0 +1,196 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.servicecontrol.v2; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/rpc/context/attribute_context.proto"; +import "google/rpc/status.proto"; + +option cc_enable_arenas = true; +option csharp_namespace = "Google.Cloud.ServiceControl.V2"; +option go_package = "google.golang.org/genproto/googleapis/api/servicecontrol/v2;servicecontrol"; +option java_multiple_files = true; +option java_outer_classname = "ServiceControllerProto"; +option java_package = "com.google.api.servicecontrol.v2"; +option objc_class_prefix = "GASC"; +option php_namespace = "Google\\Cloud\\ServiceControl\\V2"; +option ruby_package = "Google::Cloud::ServiceControl::V2"; + +// [Service Control API +// v2](https://cloud.google.com/service-infrastructure/docs/service-control/access-control) +// +// Private Preview. This feature is only available for approved services. +// +// This API provides admission control and telemetry reporting for services +// that are integrated with [Service +// Infrastructure](https://cloud.google.com/service-infrastructure). +service ServiceController { + option (google.api.default_host) = "servicecontrol.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/servicecontrol"; + + // Private Preview. This feature is only available for approved services. + // + // This method provides admission control for services that are integrated + // with [Service + // Infrastructure](https://cloud.google.com/service-infrastructure). It checks + // whether an operation should be allowed based on the service configuration + // and relevant policies. It must be called before the operation is executed. + // For more information, see + // [Admission + // Control](https://cloud.google.com/service-infrastructure/docs/admission-control). + // + // NOTE: The admission control has an expected policy propagation delay of + // 60s. The caller **must** not depend on the most recent policy changes. + // + // NOTE: The admission control has a hard limit of 1 referenced resources + // per call. If an operation refers to more than 1 resources, the caller + // must call the Check method multiple times. + // + // This method requires the `servicemanagement.services.check` permission + // on the specified service. For more information, see + // [Service Control API Access + // Control](https://cloud.google.com/service-infrastructure/docs/service-control/access-control). + rpc Check(CheckRequest) returns (CheckResponse) { + option (google.api.http) = { + post: "/v2/services/{service_name}:check" + body: "*" + }; + } + + // Private Preview. This feature is only available for approved services. + // + // This method provides telemetry reporting for services that are integrated + // with [Service + // Infrastructure](https://cloud.google.com/service-infrastructure). It + // reports a list of operations that have occurred on a service. It must be + // called after the operations have been executed. For more information, see + // [Telemetry + // Reporting](https://cloud.google.com/service-infrastructure/docs/telemetry-reporting). + // + // NOTE: The telemetry reporting has a hard limit of 1000 operations and 1MB + // per Report call. It is recommended to have no more than 100 operations per + // call. + // + // This method requires the `servicemanagement.services.report` permission + // on the specified service. For more information, see + // [Service Control API Access + // Control](https://cloud.google.com/service-infrastructure/docs/service-control/access-control). + rpc Report(ReportRequest) returns (ReportResponse) { + option (google.api.http) = { + post: "/v2/services/{service_name}:report" + body: "*" + }; + } +} + +// Request message for the Check method. +message CheckRequest { + // The service name as specified in its service configuration. For example, + // `"pubsub.googleapis.com"`. + // + // See + // [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service) + // for the definition of a service name. + string service_name = 1; + + // Specifies the version of the service configuration that should be used to + // process the request. Must not be empty. Set this field to 'latest' to + // specify using the latest configuration. + string service_config_id = 2; + + // Describes attributes about the operation being executed by the service. + google.rpc.context.AttributeContext attributes = 3; + + // Describes the resources and the policies applied to each resource. + repeated ResourceInfo resources = 4; + + // Optional. Contains a comma-separated list of flags. + string flags = 5; +} + +// Describes a resource referenced in the request. +message ResourceInfo { + // The name of the resource referenced in the request. + string name = 1; + + // The resource type in the format of "{service}/{kind}". + string type = 2; + + // The resource permission needed for this request. + // The format must be "{service}/{plural}.{verb}". + string permission = 3; + + // Optional. The identifier of the container of this resource. For Google + // Cloud APIs, the resource container must be one of the following formats: + // - `projects/` + // - `folders/` + // - `organizations/` + // For the policy enforcement on the container level (VPCSC and Location + // Policy check), this field takes precedence on the container extracted from + // name when presents. + string container = 4; + + // Optional. The location of the resource. The value must be a valid zone, + // region or multiregion. For example: "europe-west4" or + // "northamerica-northeast1-a" + string location = 5; +} + +// Response message for the Check method. +message CheckResponse { + // Operation is allowed when this field is not set. Any non-'OK' status + // indicates a denial; [google.rpc.Status.details][google.rpc.Status.details] + // would contain additional details about the denial. + google.rpc.Status status = 1; + + // Returns a set of request contexts generated from the `CheckRequest`. + map headers = 2; +} + +// Request message for the Report method. +message ReportRequest { + // The service name as specified in its service configuration. For example, + // `"pubsub.googleapis.com"`. + // + // See + // [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service) + // for the definition of a service name. + string service_name = 1; + + // Specifies the version of the service configuration that should be used to + // process the request. Must not be empty. Set this field to 'latest' to + // specify using the latest configuration. + string service_config_id = 2; + + // Describes the list of operations to be reported. Each operation is + // represented as an AttributeContext, and contains all attributes around an + // API access. + repeated google.rpc.context.AttributeContext operations = 3; +} + +// Response message for the Report method. +// If the request contains any invalid data, the server returns an RPC error. +message ReportResponse {} + +// Message containing resource details in a batch mode. +message ResourceInfoList { + // The resource details. + repeated ResourceInfo resources = 1; +} diff --git a/node_modules/google-gax/build/protos/google/api/servicemanagement/v1/resources.proto b/node_modules/google-gax/build/protos/google/api/servicemanagement/v1/resources.proto new file mode 100644 index 0000000..fd984dd --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/servicemanagement/v1/resources.proto @@ -0,0 +1,295 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.servicemanagement.v1; + +import "google/api/config_change.proto"; +import "google/api/field_behavior.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.ServiceManagement.V1"; +option go_package = "cloud.google.com/go/servicemanagement/apiv1/servicemanagementpb;servicemanagementpb"; +option java_multiple_files = true; +option java_outer_classname = "ResourcesProto"; +option java_package = "com.google.api.servicemanagement.v1"; +option objc_class_prefix = "GASM"; +option php_namespace = "Google\\Cloud\\ServiceManagement\\V1"; +option ruby_package = "Google::Cloud::ServiceManagement::V1"; + +// The full representation of a Service that is managed by +// Google Service Management. +message ManagedService { + // The name of the service. See the + // [overview](https://cloud.google.com/service-infrastructure/docs/overview) + // for naming requirements. + string service_name = 2; + + // ID of the project that produces and owns this service. + string producer_project_id = 3; +} + +// The metadata associated with a long running operation resource. +message OperationMetadata { + // Represents the status of one operation step. + message Step { + // The short description of the step. + string description = 2; + + // The status code. + Status status = 4; + } + + // Code describes the status of the operation (or one of its steps). + enum Status { + // Unspecifed code. + STATUS_UNSPECIFIED = 0; + + // The operation or step has completed without errors. + DONE = 1; + + // The operation or step has not started yet. + NOT_STARTED = 2; + + // The operation or step is in progress. + IN_PROGRESS = 3; + + // The operation or step has completed with errors. If the operation is + // rollbackable, the rollback completed with errors too. + FAILED = 4; + + // The operation or step has completed with cancellation. + CANCELLED = 5; + } + + // The full name of the resources that this operation is directly + // associated with. + repeated string resource_names = 1; + + // Detailed status information for each step. The order is undetermined. + repeated Step steps = 2; + + // Percentage of completion of this operation, ranging from 0 to 100. + int32 progress_percentage = 3; + + // The start time of the operation. + google.protobuf.Timestamp start_time = 4; +} + +// Represents a diagnostic message (error or warning) +message Diagnostic { + // The kind of diagnostic information possible. + enum Kind { + // Warnings and errors + WARNING = 0; + + // Only errors + ERROR = 1; + } + + // File name and line number of the error or warning. + string location = 1; + + // The kind of diagnostic information provided. + Kind kind = 2; + + // Message describing the error or warning. + string message = 3; +} + +// Represents a source file which is used to generate the service configuration +// defined by `google.api.Service`. +message ConfigSource { + // A unique ID for a specific instance of this message, typically assigned + // by the client for tracking purpose. If empty, the server may choose to + // generate one instead. + string id = 5; + + // Set of source configuration files that are used to generate a service + // configuration (`google.api.Service`). + repeated ConfigFile files = 2; +} + +// Generic specification of a source configuration file +message ConfigFile { + enum FileType { + // Unknown file type. + FILE_TYPE_UNSPECIFIED = 0; + + // YAML-specification of service. + SERVICE_CONFIG_YAML = 1; + + // OpenAPI specification, serialized in JSON. + OPEN_API_JSON = 2; + + // OpenAPI specification, serialized in YAML. + OPEN_API_YAML = 3; + + // FileDescriptorSet, generated by protoc. + // + // To generate, use protoc with imports and source info included. + // For an example test.proto file, the following command would put the value + // in a new file named out.pb. + // + // $protoc --include_imports --include_source_info test.proto -o out.pb + FILE_DESCRIPTOR_SET_PROTO = 4; + + // Uncompiled Proto file. Used for storage and display purposes only, + // currently server-side compilation is not supported. Should match the + // inputs to 'protoc' command used to generated FILE_DESCRIPTOR_SET_PROTO. A + // file of this type can only be included if at least one file of type + // FILE_DESCRIPTOR_SET_PROTO is included. + PROTO_FILE = 6; + } + + // The file name of the configuration file (full or relative path). + string file_path = 1; + + // The bytes that constitute the file. + bytes file_contents = 3; + + // The type of configuration file this represents. + FileType file_type = 4; +} + +// Represents a service configuration with its name and id. +message ConfigRef { + // Resource name of a service config. It must have the following + // format: "services/{service name}/configs/{config id}". + string name = 1; +} + +// Change report associated with a particular service configuration. +// +// It contains a list of ConfigChanges based on the comparison between +// two service configurations. +message ChangeReport { + // List of changes between two service configurations. + // The changes will be alphabetically sorted based on the identifier + // of each change. + // A ConfigChange identifier is a dot separated path to the configuration. + // Example: visibility.rules[selector='LibraryService.CreateBook'].restriction + repeated google.api.ConfigChange config_changes = 1; +} + +// A rollout resource that defines how service configuration versions are pushed +// to control plane systems. Typically, you create a new version of the +// service config, and then create a Rollout to push the service config. +message Rollout { + // Strategy that specifies how clients of Google Service Controller want to + // send traffic to use different config versions. This is generally + // used by API proxy to split traffic based on your configured percentage for + // each config version. + // + // One example of how to gradually rollout a new service configuration using + // this + // strategy: + // Day 1 + // + // Rollout { + // id: "example.googleapis.com/rollout_20160206" + // traffic_percent_strategy { + // percentages: { + // "example.googleapis.com/20160201": 70.00 + // "example.googleapis.com/20160206": 30.00 + // } + // } + // } + // + // Day 2 + // + // Rollout { + // id: "example.googleapis.com/rollout_20160207" + // traffic_percent_strategy: { + // percentages: { + // "example.googleapis.com/20160206": 100.00 + // } + // } + // } + message TrafficPercentStrategy { + // Maps service configuration IDs to their corresponding traffic percentage. + // Key is the service configuration ID, Value is the traffic percentage + // which must be greater than 0.0 and the sum must equal to 100.0. + map percentages = 1; + } + + // Strategy used to delete a service. This strategy is a placeholder only + // used by the system generated rollout to delete a service. + message DeleteServiceStrategy {} + + // Status of a Rollout. + enum RolloutStatus { + // No status specified. + ROLLOUT_STATUS_UNSPECIFIED = 0; + + // The Rollout is in progress. + IN_PROGRESS = 1; + + // The Rollout has completed successfully. + SUCCESS = 2; + + // The Rollout has been cancelled. This can happen if you have overlapping + // Rollout pushes, and the previous ones will be cancelled. + CANCELLED = 3; + + // The Rollout has failed and the rollback attempt has failed too. + FAILED = 4; + + // The Rollout has not started yet and is pending for execution. + PENDING = 5; + + // The Rollout has failed and rolled back to the previous successful + // Rollout. + FAILED_ROLLED_BACK = 6; + } + + // Optional. Unique identifier of this Rollout. Must be no longer than 63 + // characters and only lower case letters, digits, '.', '_' and '-' are + // allowed. + // + // If not specified by client, the server will generate one. The generated id + // will have the form of , where "date" is the create + // date in ISO 8601 format. "revision number" is a monotonically increasing + // positive number that is reset every day for each service. + // An example of the generated rollout_id is '2016-02-16r1' + string rollout_id = 1 [(google.api.field_behavior) = OPTIONAL]; + + // Creation time of the rollout. Readonly. + google.protobuf.Timestamp create_time = 2; + + // The user who created the Rollout. Readonly. + string created_by = 3; + + // The status of this rollout. Readonly. In case of a failed rollout, + // the system will automatically rollback to the current Rollout + // version. Readonly. + RolloutStatus status = 4; + + // Strategy that defines which versions of service configurations should be + // pushed + // and how they should be used at runtime. + oneof strategy { + // Google Service Control selects service configurations based on + // traffic percentage. + TrafficPercentStrategy traffic_percent_strategy = 5; + + // The strategy associated with a rollout to delete a `ManagedService`. + // Readonly. + DeleteServiceStrategy delete_service_strategy = 200; + } + + // The name of the service associated with this Rollout. + string service_name = 8; +} diff --git a/node_modules/google-gax/build/protos/google/api/servicemanagement/v1/servicemanager.proto b/node_modules/google-gax/build/protos/google/api/servicemanagement/v1/servicemanager.proto new file mode 100644 index 0000000..0aa966c --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/servicemanagement/v1/servicemanager.proto @@ -0,0 +1,508 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.servicemanagement.v1; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/service.proto"; +import "google/api/servicemanagement/v1/resources.proto"; +import "google/longrunning/operations.proto"; +import "google/protobuf/any.proto"; +import "google/protobuf/empty.proto"; + +option csharp_namespace = "Google.Cloud.ServiceManagement.V1"; +option go_package = "cloud.google.com/go/servicemanagement/apiv1/servicemanagementpb;servicemanagementpb"; +option java_multiple_files = true; +option java_outer_classname = "ServiceManagerProto"; +option java_package = "com.google.api.servicemanagement.v1"; +option objc_class_prefix = "GASM"; +option php_namespace = "Google\\Cloud\\ServiceManagement\\V1"; +option ruby_package = "Google::Cloud::ServiceManagement::V1"; + +// [Google Service Management +// API](https://cloud.google.com/service-infrastructure/docs/overview) +service ServiceManager { + option (google.api.default_host) = "servicemanagement.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/cloud-platform.read-only," + "https://www.googleapis.com/auth/service.management," + "https://www.googleapis.com/auth/service.management.readonly"; + + // Lists managed services. + // + // Returns all public services. For authenticated users, also returns all + // services the calling user has "servicemanagement.services.get" permission + // for. + rpc ListServices(ListServicesRequest) returns (ListServicesResponse) { + option (google.api.http) = { + get: "/v1/services" + }; + option (google.api.method_signature) = "producer_project_id,consumer_id"; + } + + // Gets a managed service. Authentication is required unless the service is + // public. + rpc GetService(GetServiceRequest) returns (ManagedService) { + option (google.api.http) = { + get: "/v1/services/{service_name}" + }; + option (google.api.method_signature) = "service_name"; + } + + // Creates a new managed service. + // + // A managed service is immutable, and is subject to mandatory 30-day + // data retention. You cannot move a service or recreate it within 30 days + // after deletion. + // + // One producer project can own no more than 500 services. For security and + // reliability purposes, a production service should be hosted in a + // dedicated producer project. + // + // Operation + rpc CreateService(CreateServiceRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/services" + body: "service" + }; + option (google.api.method_signature) = "service"; + option (google.longrunning.operation_info) = { + response_type: "google.api.servicemanagement.v1.ManagedService" + metadata_type: "google.api.servicemanagement.v1.OperationMetadata" + }; + } + + // Deletes a managed service. This method will change the service to the + // `Soft-Delete` state for 30 days. Within this period, service producers may + // call + // [UndeleteService][google.api.servicemanagement.v1.ServiceManager.UndeleteService] + // to restore the service. After 30 days, the service will be permanently + // deleted. + // + // Operation + rpc DeleteService(DeleteServiceRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + delete: "/v1/services/{service_name}" + }; + option (google.api.method_signature) = "service_name"; + option (google.longrunning.operation_info) = { + response_type: "google.protobuf.Empty" + metadata_type: "google.api.servicemanagement.v1.OperationMetadata" + }; + } + + // Revives a previously deleted managed service. The method restores the + // service using the configuration at the time the service was deleted. + // The target service must exist and must have been deleted within the + // last 30 days. + // + // Operation + rpc UndeleteService(UndeleteServiceRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/services/{service_name}:undelete" + }; + option (google.api.method_signature) = "service_name"; + option (google.longrunning.operation_info) = { + response_type: "google.api.servicemanagement.v1.UndeleteServiceResponse" + metadata_type: "google.api.servicemanagement.v1.OperationMetadata" + }; + } + + // Lists the history of the service configuration for a managed service, + // from the newest to the oldest. + rpc ListServiceConfigs(ListServiceConfigsRequest) + returns (ListServiceConfigsResponse) { + option (google.api.http) = { + get: "/v1/services/{service_name}/configs" + }; + option (google.api.method_signature) = "service_name"; + } + + // Gets a service configuration (version) for a managed service. + rpc GetServiceConfig(GetServiceConfigRequest) returns (google.api.Service) { + option (google.api.http) = { + get: "/v1/services/{service_name}/configs/{config_id}" + additional_bindings { get: "/v1/services/{service_name}/config" } + }; + option (google.api.method_signature) = "service_name,config_id,view"; + } + + // Creates a new service configuration (version) for a managed service. + // This method only stores the service configuration. To roll out the service + // configuration to backend systems please call + // [CreateServiceRollout][google.api.servicemanagement.v1.ServiceManager.CreateServiceRollout]. + // + // Only the 100 most recent service configurations and ones referenced by + // existing rollouts are kept for each service. The rest will be deleted + // eventually. + rpc CreateServiceConfig(CreateServiceConfigRequest) + returns (google.api.Service) { + option (google.api.http) = { + post: "/v1/services/{service_name}/configs" + body: "service_config" + }; + option (google.api.method_signature) = "service_name,service_config"; + } + + // Creates a new service configuration (version) for a managed service based + // on + // user-supplied configuration source files (for example: OpenAPI + // Specification). This method stores the source configurations as well as the + // generated service configuration. To rollout the service configuration to + // other services, + // please call + // [CreateServiceRollout][google.api.servicemanagement.v1.ServiceManager.CreateServiceRollout]. + // + // Only the 100 most recent configuration sources and ones referenced by + // existing service configurtions are kept for each service. The rest will be + // deleted eventually. + // + // Operation + rpc SubmitConfigSource(SubmitConfigSourceRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/services/{service_name}/configs:submit" + body: "*" + }; + option (google.api.method_signature) = + "service_name,config_source,validate_only"; + option (google.longrunning.operation_info) = { + response_type: "google.api.servicemanagement.v1.SubmitConfigSourceResponse" + metadata_type: "google.api.servicemanagement.v1.OperationMetadata" + }; + } + + // Lists the history of the service configuration rollouts for a managed + // service, from the newest to the oldest. + rpc ListServiceRollouts(ListServiceRolloutsRequest) + returns (ListServiceRolloutsResponse) { + option (google.api.http) = { + get: "/v1/services/{service_name}/rollouts" + }; + option (google.api.method_signature) = "service_name,filter"; + } + + // Gets a service configuration + // [rollout][google.api.servicemanagement.v1.Rollout]. + rpc GetServiceRollout(GetServiceRolloutRequest) returns (Rollout) { + option (google.api.http) = { + get: "/v1/services/{service_name}/rollouts/{rollout_id}" + }; + option (google.api.method_signature) = "service_name,rollout_id"; + } + + // Creates a new service configuration rollout. Based on rollout, the + // Google Service Management will roll out the service configurations to + // different backend services. For example, the logging configuration will be + // pushed to Google Cloud Logging. + // + // Please note that any previous pending and running Rollouts and associated + // Operations will be automatically cancelled so that the latest Rollout will + // not be blocked by previous Rollouts. + // + // Only the 100 most recent (in any state) and the last 10 successful (if not + // already part of the set of 100 most recent) rollouts are kept for each + // service. The rest will be deleted eventually. + // + // Operation + rpc CreateServiceRollout(CreateServiceRolloutRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/services/{service_name}/rollouts" + body: "rollout" + }; + option (google.api.method_signature) = "service_name,rollout"; + option (google.longrunning.operation_info) = { + response_type: "google.api.servicemanagement.v1.Rollout" + metadata_type: "google.api.servicemanagement.v1.OperationMetadata" + }; + } + + // Generates and returns a report (errors, warnings and changes from + // existing configurations) associated with + // GenerateConfigReportRequest.new_value + // + // If GenerateConfigReportRequest.old_value is specified, + // GenerateConfigReportRequest will contain a single ChangeReport based on the + // comparison between GenerateConfigReportRequest.new_value and + // GenerateConfigReportRequest.old_value. + // If GenerateConfigReportRequest.old_value is not specified, this method + // will compare GenerateConfigReportRequest.new_value with the last pushed + // service configuration. + rpc GenerateConfigReport(GenerateConfigReportRequest) + returns (GenerateConfigReportResponse) { + option (google.api.http) = { + post: "/v1/services:generateConfigReport" + body: "*" + }; + option (google.api.method_signature) = "new_config,old_config"; + } +} + +// Request message for `ListServices` method. +message ListServicesRequest { + // Include services produced by the specified project. + string producer_project_id = 1; + + // The max number of items to include in the response list. Page size is 50 + // if not specified. Maximum value is 500. + int32 page_size = 5; + + // Token identifying which result to start with; returned by a previous list + // call. + string page_token = 6; + + // Include services consumed by the specified consumer. + // + // The Google Service Management implementation accepts the following + // forms: + // - project: + string consumer_id = 7 [deprecated = true]; +} + +// Response message for `ListServices` method. +message ListServicesResponse { + // The returned services will only have the name field set. + repeated ManagedService services = 1; + + // Token that can be passed to `ListServices` to resume a paginated query. + string next_page_token = 2; +} + +// Request message for `GetService` method. +message GetServiceRequest { + // Required. The name of the service. See the `ServiceManager` overview for + // naming requirements. For example: `example.googleapis.com`. + string service_name = 1 [(google.api.field_behavior) = REQUIRED]; +} + +// Request message for CreateService method. +message CreateServiceRequest { + // Required. Initial values for the service resource. + ManagedService service = 1 [(google.api.field_behavior) = REQUIRED]; +} + +// Request message for DeleteService method. +message DeleteServiceRequest { + // Required. The name of the service. See the + // [overview](https://cloud.google.com/service-management/overview) for naming + // requirements. For example: `example.googleapis.com`. + string service_name = 1 [(google.api.field_behavior) = REQUIRED]; +} + +// Request message for UndeleteService method. +message UndeleteServiceRequest { + // Required. The name of the service. See the + // [overview](https://cloud.google.com/service-management/overview) for naming + // requirements. For example: `example.googleapis.com`. + string service_name = 1 [(google.api.field_behavior) = REQUIRED]; +} + +// Response message for UndeleteService method. +message UndeleteServiceResponse { + // Revived service resource. + ManagedService service = 1; +} + +// Request message for GetServiceConfig method. +message GetServiceConfigRequest { + enum ConfigView { + // Server response includes all fields except SourceInfo. + BASIC = 0; + + // Server response includes all fields including SourceInfo. + // SourceFiles are of type 'google.api.servicemanagement.v1.ConfigFile' + // and are only available for configs created using the + // SubmitConfigSource method. + FULL = 1; + } + + // Required. The name of the service. See the + // [overview](https://cloud.google.com/service-management/overview) for naming + // requirements. For example: `example.googleapis.com`. + string service_name = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The id of the service configuration resource. + // + // This field must be specified for the server to return all fields, including + // `SourceInfo`. + string config_id = 2 [(google.api.field_behavior) = REQUIRED]; + + // Specifies which parts of the Service Config should be returned in the + // response. + ConfigView view = 3; +} + +// Request message for ListServiceConfigs method. +message ListServiceConfigsRequest { + // Required. The name of the service. See the + // [overview](https://cloud.google.com/service-management/overview) for naming + // requirements. For example: `example.googleapis.com`. + string service_name = 1 [(google.api.field_behavior) = REQUIRED]; + + // The token of the page to retrieve. + string page_token = 2; + + // The max number of items to include in the response list. Page size is 50 + // if not specified. Maximum value is 100. + int32 page_size = 3; +} + +// Response message for ListServiceConfigs method. +message ListServiceConfigsResponse { + // The list of service configuration resources. + repeated google.api.Service service_configs = 1; + + // The token of the next page of results. + string next_page_token = 2; +} + +// Request message for CreateServiceConfig method. +message CreateServiceConfigRequest { + // Required. The name of the service. See the + // [overview](https://cloud.google.com/service-management/overview) for naming + // requirements. For example: `example.googleapis.com`. + string service_name = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The service configuration resource. + google.api.Service service_config = 2 + [(google.api.field_behavior) = REQUIRED]; +} + +// Request message for SubmitConfigSource method. +message SubmitConfigSourceRequest { + // Required. The name of the service. See the + // [overview](https://cloud.google.com/service-management/overview) for naming + // requirements. For example: `example.googleapis.com`. + string service_name = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The source configuration for the service. + ConfigSource config_source = 2 [(google.api.field_behavior) = REQUIRED]; + + // Optional. If set, this will result in the generation of a + // `google.api.Service` configuration based on the `ConfigSource` provided, + // but the generated config and the sources will NOT be persisted. + bool validate_only = 3 [(google.api.field_behavior) = OPTIONAL]; +} + +// Response message for SubmitConfigSource method. +message SubmitConfigSourceResponse { + // The generated service configuration. + google.api.Service service_config = 1; +} + +// +// Request message for 'CreateServiceRollout' +message CreateServiceRolloutRequest { + // Required. The name of the service. See the + // [overview](https://cloud.google.com/service-management/overview) for naming + // requirements. For example: `example.googleapis.com`. + string service_name = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The rollout resource. The `service_name` field is output only. + Rollout rollout = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// Request message for 'ListServiceRollouts' +message ListServiceRolloutsRequest { + // Required. The name of the service. See the + // [overview](https://cloud.google.com/service-management/overview) for naming + // requirements. For example: `example.googleapis.com`. + string service_name = 1 [(google.api.field_behavior) = REQUIRED]; + + // The token of the page to retrieve. + string page_token = 2; + + // The max number of items to include in the response list. Page size is 50 + // if not specified. Maximum value is 100. + int32 page_size = 3; + + // Required. Use `filter` to return subset of rollouts. + // The following filters are supported: + // + // -- By [status] + // [google.api.servicemanagement.v1.Rollout.RolloutStatus]. For example, + // `filter='status=SUCCESS'` + // + // -- By [strategy] + // [google.api.servicemanagement.v1.Rollout.strategy]. For example, + // `filter='strategy=TrafficPercentStrategy'` + string filter = 4 [(google.api.field_behavior) = REQUIRED]; +} + +// Response message for ListServiceRollouts method. +message ListServiceRolloutsResponse { + // The list of rollout resources. + repeated Rollout rollouts = 1; + + // The token of the next page of results. + string next_page_token = 2; +} + +// Request message for GetServiceRollout method. +message GetServiceRolloutRequest { + // Required. The name of the service. See the + // [overview](https://cloud.google.com/service-management/overview) for naming + // requirements. For example: `example.googleapis.com`. + string service_name = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The id of the rollout resource. + string rollout_id = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// Operation payload for EnableService method. +message EnableServiceResponse {} + +// Request message for GenerateConfigReport method. +message GenerateConfigReportRequest { + // Required. Service configuration for which we want to generate the report. + // For this version of API, the supported types are + // [google.api.servicemanagement.v1.ConfigRef][google.api.servicemanagement.v1.ConfigRef], + // [google.api.servicemanagement.v1.ConfigSource][google.api.servicemanagement.v1.ConfigSource], + // and [google.api.Service][google.api.Service] + google.protobuf.Any new_config = 1 [(google.api.field_behavior) = REQUIRED]; + + // Optional. Service configuration against which the comparison will be done. + // For this version of API, the supported types are + // [google.api.servicemanagement.v1.ConfigRef][google.api.servicemanagement.v1.ConfigRef], + // [google.api.servicemanagement.v1.ConfigSource][google.api.servicemanagement.v1.ConfigSource], + // and [google.api.Service][google.api.Service] + google.protobuf.Any old_config = 2 [(google.api.field_behavior) = OPTIONAL]; +} + +// Response message for GenerateConfigReport method. +message GenerateConfigReportResponse { + // Name of the service this report belongs to. + string service_name = 1; + + // ID of the service configuration this report belongs to. + string id = 2; + + // list of ChangeReport, each corresponding to comparison between two + // service configurations. + repeated ChangeReport change_reports = 3; + + // Errors / Linter warnings associated with the service definition this + // report + // belongs to. + repeated Diagnostic diagnostics = 4; +} diff --git a/node_modules/google-gax/build/protos/google/api/serviceusage/v1/resources.proto b/node_modules/google-gax/build/protos/google/api/serviceusage/v1/resources.proto new file mode 100644 index 0000000..e7c5405 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/serviceusage/v1/resources.proto @@ -0,0 +1,130 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.serviceusage.v1; + +import "google/api/auth.proto"; +import "google/api/documentation.proto"; +import "google/api/endpoint.proto"; +import "google/api/monitored_resource.proto"; +import "google/api/monitoring.proto"; +import "google/api/quota.proto"; +import "google/api/resource.proto"; +import "google/api/usage.proto"; +import "google/protobuf/api.proto"; + +option csharp_namespace = "Google.Cloud.ServiceUsage.V1"; +option go_package = "cloud.google.com/go/serviceusage/apiv1/serviceusagepb;serviceusagepb"; +option java_multiple_files = true; +option java_outer_classname = "ResourcesProto"; +option java_package = "com.google.api.serviceusage.v1"; +option php_namespace = "Google\\Cloud\\ServiceUsage\\V1"; +option ruby_package = "Google::Cloud::ServiceUsage::V1"; + +// A service that is available for use by the consumer. +message Service { + option (google.api.resource) = { + type: "serviceusage.googleapis.com/Service" + pattern: "projects/{project}/services/{service}" + pattern: "folders/{folder}/services/{service}" + pattern: "organizations/{organization}/services/{service}" + }; + + // The resource name of the consumer and service. + // + // A valid name would be: + // - projects/123/services/serviceusage.googleapis.com + string name = 1; + + // The resource name of the consumer. + // + // A valid name would be: + // - projects/123 + string parent = 5; + + // The service configuration of the available service. + // Some fields may be filtered out of the configuration in responses to + // the `ListServices` method. These fields are present only in responses to + // the `GetService` method. + ServiceConfig config = 2; + + // Whether or not the service has been enabled for use by the consumer. + State state = 4; +} + +// Whether or not a service has been enabled for use by a consumer. +enum State { + // The default value, which indicates that the enabled state of the service + // is unspecified or not meaningful. Currently, all consumers other than + // projects (such as folders and organizations) are always in this state. + STATE_UNSPECIFIED = 0; + + // The service cannot be used by this consumer. It has either been explicitly + // disabled, or has never been enabled. + DISABLED = 1; + + // The service has been explicitly enabled for use by this consumer. + ENABLED = 2; +} + +// The configuration of the service. +message ServiceConfig { + // The DNS address at which this service is available. + // + // An example DNS address would be: + // `calendar.googleapis.com`. + string name = 1; + + // The product title for this service. + string title = 2; + + // A list of API interfaces exported by this service. Contains only the names, + // versions, and method names of the interfaces. + repeated google.protobuf.Api apis = 3; + + // Additional API documentation. Contains only the summary and the + // documentation URL. + google.api.Documentation documentation = 6; + + // Quota configuration. + google.api.Quota quota = 10; + + // Auth configuration. Contains only the OAuth rules. + google.api.Authentication authentication = 11; + + // Configuration controlling usage of this service. + google.api.Usage usage = 15; + + // Configuration for network endpoints. Contains only the names and aliases + // of the endpoints. + repeated google.api.Endpoint endpoints = 18; + + // Defines the monitored resources used by this service. This is required + // by the [Service.monitoring][google.api.Service.monitoring] and + // [Service.logging][google.api.Service.logging] configurations. + repeated google.api.MonitoredResourceDescriptor monitored_resources = 25; + + // Monitoring configuration. + // This should not include the 'producer_destinations' field. + google.api.Monitoring monitoring = 28; +} + +// The operation metadata returned for the batchend services operation. +message OperationMetadata { + // The full name of the resources that this operation is directly + // associated with. + repeated string resource_names = 2; +} diff --git a/node_modules/google-gax/build/protos/google/api/serviceusage/v1/serviceusage.proto b/node_modules/google-gax/build/protos/google/api/serviceusage/v1/serviceusage.proto new file mode 100644 index 0000000..d6a079e --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/serviceusage/v1/serviceusage.proto @@ -0,0 +1,305 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.serviceusage.v1; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/serviceusage/v1/resources.proto"; +import "google/longrunning/operations.proto"; + +option csharp_namespace = "Google.Cloud.ServiceUsage.V1"; +option go_package = "cloud.google.com/go/serviceusage/apiv1/serviceusagepb;serviceusagepb"; +option java_multiple_files = true; +option java_outer_classname = "ServiceUsageProto"; +option java_package = "com.google.api.serviceusage.v1"; +option php_namespace = "Google\\Cloud\\ServiceUsage\\V1"; +option ruby_package = "Google::Cloud::ServiceUsage::V1"; + +// Enables services that service consumers want to use on Google Cloud Platform, +// lists the available or enabled services, or disables services that service +// consumers no longer use. +// +// See [Service Usage API](https://cloud.google.com/service-usage/docs/overview) +service ServiceUsage { + option (google.api.default_host) = "serviceusage.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/cloud-platform.read-only," + "https://www.googleapis.com/auth/service.management"; + + // Enable a service so that it can be used with a project. + rpc EnableService(EnableServiceRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{name=*/*/services/*}:enable" + body: "*" + }; + option (google.longrunning.operation_info) = { + response_type: "EnableServiceResponse" + metadata_type: "OperationMetadata" + }; + } + + // Disable a service so that it can no longer be used with a project. + // This prevents unintended usage that may cause unexpected billing + // charges or security leaks. + // + // It is not valid to call the disable method on a service that is not + // currently enabled. Callers will receive a `FAILED_PRECONDITION` status if + // the target service is not currently enabled. + rpc DisableService(DisableServiceRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{name=*/*/services/*}:disable" + body: "*" + }; + option (google.longrunning.operation_info) = { + response_type: "DisableServiceResponse" + metadata_type: "OperationMetadata" + }; + } + + // Returns the service configuration and enabled state for a given service. + rpc GetService(GetServiceRequest) returns (Service) { + option (google.api.http) = { + get: "/v1/{name=*/*/services/*}" + }; + } + + // List all services available to the specified project, and the current + // state of those services with respect to the project. The list includes + // all public services, all services for which the calling user has the + // `servicemanagement.services.bind` permission, and all services that have + // already been enabled on the project. The list can be filtered to + // only include services in a specific state, for example to only include + // services enabled on the project. + // + // WARNING: If you need to query enabled services frequently or across + // an organization, you should use + // [Cloud Asset Inventory + // API](https://cloud.google.com/asset-inventory/docs/apis), which provides + // higher throughput and richer filtering capability. + rpc ListServices(ListServicesRequest) returns (ListServicesResponse) { + option (google.api.http) = { + get: "/v1/{parent=*/*}/services" + }; + } + + // Enable multiple services on a project. The operation is atomic: if enabling + // any service fails, then the entire batch fails, and no state changes occur. + // To enable a single service, use the `EnableService` method instead. + rpc BatchEnableServices(BatchEnableServicesRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{parent=*/*}/services:batchEnable" + body: "*" + }; + option (google.longrunning.operation_info) = { + response_type: "BatchEnableServicesResponse" + metadata_type: "OperationMetadata" + }; + } + + // Returns the service configurations and enabled states for a given list of + // services. + rpc BatchGetServices(BatchGetServicesRequest) + returns (BatchGetServicesResponse) { + option (google.api.http) = { + get: "/v1/{parent=*/*}/services:batchGet" + }; + } +} + +// Request message for the `EnableService` method. +message EnableServiceRequest { + // Name of the consumer and service to enable the service on. + // + // The `EnableService` and `DisableService` methods currently only support + // projects. + // + // Enabling a service requires that the service is public or is shared with + // the user enabling the service. + // + // An example name would be: + // `projects/123/services/serviceusage.googleapis.com` where `123` is the + // project number. + string name = 1; +} + +// Response message for the `EnableService` method. +// This response message is assigned to the `response` field of the returned +// Operation when that operation is done. +message EnableServiceResponse { + // The new state of the service after enabling. + Service service = 1; +} + +// Request message for the `DisableService` method. +message DisableServiceRequest { + // Enum to determine if service usage should be checked when disabling a + // service. + enum CheckIfServiceHasUsage { + // When unset, the default behavior is used, which is SKIP. + CHECK_IF_SERVICE_HAS_USAGE_UNSPECIFIED = 0; + + // If set, skip checking service usage when disabling a service. + SKIP = 1; + + // If set, service usage is checked when disabling the service. If a + // service, or its dependents, has usage in the last 30 days, the request + // returns a FAILED_PRECONDITION error. + CHECK = 2; + } + + // Name of the consumer and service to disable the service on. + // + // The enable and disable methods currently only support projects. + // + // An example name would be: + // `projects/123/services/serviceusage.googleapis.com` where `123` is the + // project number. + string name = 1; + + // Indicates if services that are enabled and which depend on this service + // should also be disabled. If not set, an error will be generated if any + // enabled services depend on the service to be disabled. When set, the + // service, and any enabled services that depend on it, will be disabled + // together. + bool disable_dependent_services = 2; + + // Defines the behavior for checking service usage when disabling a service. + CheckIfServiceHasUsage check_if_service_has_usage = 3; +} + +// Response message for the `DisableService` method. +// This response message is assigned to the `response` field of the returned +// Operation when that operation is done. +message DisableServiceResponse { + // The new state of the service after disabling. + Service service = 1; +} + +// Request message for the `GetService` method. +message GetServiceRequest { + // Name of the consumer and service to get the `ConsumerState` for. + // + // An example name would be: + // `projects/123/services/serviceusage.googleapis.com` where `123` is the + // project number. + string name = 1; +} + +// Request message for the `ListServices` method. +message ListServicesRequest { + // Parent to search for services on. + // + // An example name would be: + // `projects/123` where `123` is the project number. + string parent = 1; + + // Requested size of the next page of data. + // Requested page size cannot exceed 200. + // If not set, the default page size is 50. + int32 page_size = 2; + + // Token identifying which result to start with, which is returned by a + // previous list call. + string page_token = 3; + + // Only list services that conform to the given filter. + // The allowed filter strings are `state:ENABLED` and `state:DISABLED`. + string filter = 4; +} + +// Response message for the `ListServices` method. +message ListServicesResponse { + // The available services for the requested project. + repeated Service services = 1; + + // Token that can be passed to `ListServices` to resume a paginated + // query. + string next_page_token = 2; +} + +// Request message for the `BatchEnableServices` method. +message BatchEnableServicesRequest { + // Parent to enable services on. + // + // An example name would be: + // `projects/123` where `123` is the project number. + // + // The `BatchEnableServices` method currently only supports projects. + string parent = 1; + + // The identifiers of the services to enable on the project. + // + // A valid identifier would be: + // serviceusage.googleapis.com + // + // Enabling services requires that each service is public or is shared with + // the user enabling the service. + // + // A single request can enable a maximum of 20 services at a time. If more + // than 20 services are specified, the request will fail, and no state changes + // will occur. + repeated string service_ids = 2; +} + +// Response message for the `BatchEnableServices` method. +// This response message is assigned to the `response` field of the returned +// Operation when that operation is done. +message BatchEnableServicesResponse { + // Provides error messages for the failing services. + message EnableFailure { + // The service id of a service that could not be enabled. + string service_id = 1; + + // An error message describing why the service could not be enabled. + string error_message = 2; + } + + // The new state of the services after enabling. + repeated Service services = 1; + + // If allow_partial_success is true, and one or more services could not be + // enabled, this field contains the details about each failure. + repeated EnableFailure failures = 2; +} + +// Request message for the `BatchGetServices` method. +message BatchGetServicesRequest { + // Parent to retrieve services from. + // If this is set, the parent of all of the services specified in `names` must + // match this field. An example name would be: `projects/123` where `123` is + // the project number. The `BatchGetServices` method currently only supports + // projects. + string parent = 1; + + // Names of the services to retrieve. + // + // An example name would be: + // `projects/123/services/serviceusage.googleapis.com` where `123` is the + // project number. + // A single request can get a maximum of 30 services at a time. + repeated string names = 2; +} + +// Response message for the `BatchGetServices` method. +message BatchGetServicesResponse { + // The requested Service states. + repeated Service services = 1; +} diff --git a/node_modules/google-gax/build/protos/google/api/serviceusage/v1beta1/resources.proto b/node_modules/google-gax/build/protos/google/api/serviceusage/v1beta1/resources.proto new file mode 100644 index 0000000..7411658 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/serviceusage/v1beta1/resources.proto @@ -0,0 +1,458 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.serviceusage.v1beta1; + +import "google/api/auth.proto"; +import "google/api/documentation.proto"; +import "google/api/endpoint.proto"; +import "google/api/monitored_resource.proto"; +import "google/api/monitoring.proto"; +import "google/api/quota.proto"; +import "google/api/usage.proto"; +import "google/protobuf/api.proto"; + +option csharp_namespace = "Google.Api.ServiceUsage.V1Beta1"; +option go_package = "google.golang.org/genproto/googleapis/api/serviceusage/v1beta1;serviceusage"; +option java_multiple_files = true; +option java_outer_classname = "ResourcesProto"; +option java_package = "com.google.api.serviceusage.v1beta1"; +option php_namespace = "Google\\Api\\ServiceUsage\\V1beta1"; +option ruby_package = "Google::Api::ServiceUsage::V1beta1"; + +// A service that is available for use by the consumer. +message Service { + // The resource name of the consumer and service. + // + // A valid name would be: + // - `projects/123/services/serviceusage.googleapis.com` + string name = 1; + + // The resource name of the consumer. + // + // A valid name would be: + // - `projects/123` + string parent = 5; + + // The service configuration of the available service. + // Some fields may be filtered out of the configuration in responses to + // the `ListServices` method. These fields are present only in responses to + // the `GetService` method. + ServiceConfig config = 2; + + // Whether or not the service has been enabled for use by the consumer. + State state = 4; +} + +// Whether or not a service has been enabled for use by a consumer. +enum State { + // The default value, which indicates that the enabled state of the service + // is unspecified or not meaningful. Currently, all consumers other than + // projects (such as folders and organizations) are always in this state. + STATE_UNSPECIFIED = 0; + + // The service cannot be used by this consumer. It has either been explicitly + // disabled, or has never been enabled. + DISABLED = 1; + + // The service has been explicitly enabled for use by this consumer. + ENABLED = 2; +} + +// The configuration of the service. +message ServiceConfig { + // The DNS address at which this service is available. + // + // An example DNS address would be: + // `calendar.googleapis.com`. + string name = 1; + + // The product title for this service. + string title = 2; + + // A list of API interfaces exported by this service. Contains only the names, + // versions, and method names of the interfaces. + repeated google.protobuf.Api apis = 3; + + // Additional API documentation. Contains only the summary and the + // documentation URL. + google.api.Documentation documentation = 6; + + // Quota configuration. + google.api.Quota quota = 10; + + // Auth configuration. Contains only the OAuth rules. + google.api.Authentication authentication = 11; + + // Configuration controlling usage of this service. + google.api.Usage usage = 15; + + // Configuration for network endpoints. Contains only the names and aliases + // of the endpoints. + repeated google.api.Endpoint endpoints = 18; + + // Defines the monitored resources used by this service. This is required + // by the [Service.monitoring][google.api.Service.monitoring] and + // [Service.logging][google.api.Service.logging] configurations. + repeated google.api.MonitoredResourceDescriptor monitored_resources = 25; + + // Monitoring configuration. + // This should not include the 'producer_destinations' field. + google.api.Monitoring monitoring = 28; +} + +// The operation metadata returned for the batchend services operation. +message OperationMetadata { + // The full name of the resources that this operation is directly + // associated with. + repeated string resource_names = 2; +} + +// Consumer quota settings for a quota metric. +message ConsumerQuotaMetric { + // The resource name of the quota settings on this metric for this consumer. + // + // An example name would be: + // `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus` + // + // The resource name is intended to be opaque and should not be parsed for + // its component strings, since its representation could change in the future. + string name = 1; + + // The name of the metric. + // + // An example name would be: + // `compute.googleapis.com/cpus` + string metric = 4; + + // The display name of the metric. + // + // An example name would be: + // `CPUs` + string display_name = 2; + + // The consumer quota for each quota limit defined on the metric. + repeated ConsumerQuotaLimit consumer_quota_limits = 3; + + // The quota limits targeting the descendant containers of the + // consumer in request. + // + // If the consumer in request is of type `organizations` + // or `folders`, the field will list per-project limits in the metric; if the + // consumer in request is of type `project`, the field will be empty. + // + // The `quota_buckets` field of each descendant consumer quota limit will not + // be populated. + repeated ConsumerQuotaLimit descendant_consumer_quota_limits = 6; + + // The units in which the metric value is reported. + string unit = 5; +} + +// Consumer quota settings for a quota limit. +message ConsumerQuotaLimit { + // The resource name of the quota limit. + // + // An example name would be: + // `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion` + // + // The resource name is intended to be opaque and should not be parsed for + // its component strings, since its representation could change in the future. + string name = 1; + + // The name of the parent metric of this limit. + // + // An example name would be: + // `compute.googleapis.com/cpus` + string metric = 8; + + // The limit unit. + // + // An example unit would be + // `1/{project}/{region}` + // Note that `{project}` and `{region}` are not placeholders in this example; + // the literal characters `{` and `}` occur in the string. + string unit = 2; + + // Whether this limit is precise or imprecise. + bool is_precise = 3; + + // Whether admin overrides are allowed on this limit + bool allows_admin_overrides = 7; + + // Summary of the enforced quota buckets, organized by quota dimension, + // ordered from least specific to most specific (for example, the global + // default bucket, with no quota dimensions, will always appear first). + repeated QuotaBucket quota_buckets = 9; + + // List of all supported locations. + // This field is present only if the limit has a {region} or {zone} dimension. + repeated string supported_locations = 11; +} + +// Selected view of quota. Can be used to request more detailed quota +// information when retrieving quota metrics and limits. +enum QuotaView { + // No quota view specified. Requests that do not specify a quota view will + // typically default to the BASIC view. + QUOTA_VIEW_UNSPECIFIED = 0; + + // Only buckets with overrides are shown in the response. + BASIC = 1; + + // Include per-location buckets even if they do not have overrides. + // When the view is FULL, and a limit has regional or zonal quota, the limit + // will include buckets for all regions or zones that could support + // overrides, even if none are currently present. In some cases this will + // cause the response to become very large; callers that do not need this + // extra information should use the BASIC view instead. + FULL = 2; +} + +// A quota bucket is a quota provisioning unit for a specific set of dimensions. +message QuotaBucket { + // The effective limit of this quota bucket. Equal to default_limit if there + // are no overrides. + int64 effective_limit = 1; + + // The default limit of this quota bucket, as specified by the service + // configuration. + int64 default_limit = 2; + + // Producer override on this quota bucket. + QuotaOverride producer_override = 3; + + // Consumer override on this quota bucket. + QuotaOverride consumer_override = 4; + + // Admin override on this quota bucket. + QuotaOverride admin_override = 5; + + // Producer policy inherited from the closet ancestor of the current consumer. + ProducerQuotaPolicy producer_quota_policy = 7; + + // The dimensions of this quota bucket. + // + // If this map is empty, this is the global bucket, which is the default quota + // value applied to all requests that do not have a more specific override. + // + // If this map is nonempty, the default limit, effective limit, and quota + // overrides apply only to requests that have the dimensions given in the map. + // + // For example, if the map has key `region` and value `us-east-1`, then the + // specified effective limit is only effective in that region, and the + // specified overrides apply only in that region. + map dimensions = 6; +} + +// A quota override +message QuotaOverride { + // The resource name of the override. + // This name is generated by the server when the override is created. + // + // Example names would be: + // `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion/adminOverrides/4a3f2c1d` + // `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion/consumerOverrides/4a3f2c1d` + // + // The resource name is intended to be opaque and should not be parsed for + // its component strings, since its representation could change in the future. + string name = 1; + + // The overriding quota limit value. + // Can be any nonnegative integer, or -1 (unlimited quota). + int64 override_value = 2; + + // If this map is nonempty, then this override applies only to specific values + // for dimensions defined in the limit unit. + // + // For example, an override on a limit with the unit `1/{project}/{region}` + // could contain an entry with the key `region` and the value `us-east-1`; + // the override is only applied to quota consumed in that region. + // + // This map has the following restrictions: + // + // * Keys that are not defined in the limit's unit are not valid keys. + // Any string appearing in `{brackets}` in the unit (besides `{project}` + // or + // `{user}`) is a defined key. + // * `project` is not a valid key; the project is already specified in + // the parent resource name. + // * `user` is not a valid key; the API does not support quota overrides + // that apply only to a specific user. + // * If `region` appears as a key, its value must be a valid Cloud region. + // * If `zone` appears as a key, its value must be a valid Cloud zone. + // * If any valid key other than `region` or `zone` appears in the map, then + // all valid keys other than `region` or `zone` must also appear in the + // map. + map dimensions = 3; + + // The name of the metric to which this override applies. + // + // An example name would be: + // `compute.googleapis.com/cpus` + string metric = 4; + + // The limit unit of the limit to which this override applies. + // + // An example unit would be: + // `1/{project}/{region}` + // Note that `{project}` and `{region}` are not placeholders in this example; + // the literal characters `{` and `}` occur in the string. + string unit = 5; + + // The resource name of the ancestor that requested the override. For example: + // `organizations/12345` or `folders/67890`. + // Used by admin overrides only. + string admin_override_ancestor = 6; +} + +// Import data embedded in the request message +message OverrideInlineSource { + // The overrides to create. + // Each override must have a value for 'metric' and 'unit', to specify + // which metric and which limit the override should be applied to. + // The 'name' field of the override does not need to be set; it is ignored. + repeated QuotaOverride overrides = 1; +} + +// Enumerations of quota safety checks. +enum QuotaSafetyCheck { + // Unspecified quota safety check. + QUOTA_SAFETY_CHECK_UNSPECIFIED = 0; + + // Validates that a quota mutation would not cause the consumer's effective + // limit to be lower than the consumer's quota usage. + LIMIT_DECREASE_BELOW_USAGE = 1; + + // Validates that a quota mutation would not cause the consumer's effective + // limit to decrease by more than 10 percent. + LIMIT_DECREASE_PERCENTAGE_TOO_HIGH = 2; +} + +// Quota policy created by service producer. +message ProducerQuotaPolicy { + // The resource name of the policy. + // This name is generated by the server when the policy is created. + // + // Example names would be: + // `organizations/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion/producerQuotaPolicies/4a3f2c1d` + string name = 1; + + // The quota policy value. + // Can be any nonnegative integer, or -1 (unlimited quota). + int64 policy_value = 2; + + // + // If this map is nonempty, then this policy applies only to specific values + // for dimensions defined in the limit unit. + // + // For example, a policy on a limit with the unit `1/{project}/{region}` + // could contain an entry with the key `region` and the value `us-east-1`; + // the policy is only applied to quota consumed in that region. + // + // This map has the following restrictions: + // + // * Keys that are not defined in the limit's unit are not valid keys. + // Any string appearing in {brackets} in the unit (besides {project} or + // {user}) is a defined key. + // * `project` is not a valid key; the project is already specified in + // the parent resource name. + // * `user` is not a valid key; the API does not support quota policies + // that apply only to a specific user. + // * If `region` appears as a key, its value must be a valid Cloud region. + // * If `zone` appears as a key, its value must be a valid Cloud zone. + // * If any valid key other than `region` or `zone` appears in the map, then + // all valid keys other than `region` or `zone` must also appear in the + // map. + map dimensions = 3; + + // The name of the metric to which this policy applies. + // + // An example name would be: + // `compute.googleapis.com/cpus` + string metric = 4; + + // The limit unit of the limit to which this policy applies. + // + // An example unit would be: + // `1/{project}/{region}` + // Note that `{project}` and `{region}` are not placeholders in this example; + // the literal characters `{` and `}` occur in the string. + string unit = 5; + + // The cloud resource container at which the quota policy is created. The + // format is `{container_type}/{container_number}` + string container = 6; +} + +// Quota policy created by quota administrator. +message AdminQuotaPolicy { + // The resource name of the policy. + // This name is generated by the server when the policy is created. + // + // Example names would be: + // `organizations/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion/adminQuotaPolicies/4a3f2c1d` + string name = 1; + + // The quota policy value. + // Can be any nonnegative integer, or -1 (unlimited quota). + int64 policy_value = 2; + + // + // If this map is nonempty, then this policy applies only to specific values + // for dimensions defined in the limit unit. + // + // For example, a policy on a limit with the unit `1/{project}/{region}` + // could contain an entry with the key `region` and the value `us-east-1`; + // the policy is only applied to quota consumed in that region. + // + // This map has the following restrictions: + // + // * If `region` appears as a key, its value must be a valid Cloud region. + // * If `zone` appears as a key, its value must be a valid Cloud zone. + // * Keys other than `region` or `zone` are not valid. + map dimensions = 3; + + // The name of the metric to which this policy applies. + // + // An example name would be: + // `compute.googleapis.com/cpus` + string metric = 4; + + // The limit unit of the limit to which this policy applies. + // + // An example unit would be: + // `1/{project}/{region}` + // Note that `{project}` and `{region}` are not placeholders in this example; + // the literal characters `{` and `}` occur in the string. + string unit = 5; + + // The cloud resource container at which the quota policy is created. The + // format is `{container_type}/{container_number}` + string container = 6; +} + +// Service identity for a service. This is the identity that service producer +// should use to access consumer resources. +message ServiceIdentity { + // The email address of the service account that a service producer would use + // to access consumer resources. + string email = 1; + + // The unique and stable id of the service account. + // https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts#ServiceAccount + string unique_id = 2; +} diff --git a/node_modules/google-gax/build/protos/google/api/serviceusage/v1beta1/serviceusage.proto b/node_modules/google-gax/build/protos/google/api/serviceusage/v1beta1/serviceusage.proto new file mode 100644 index 0000000..5db5465 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/serviceusage/v1beta1/serviceusage.proto @@ -0,0 +1,793 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api.serviceusage.v1beta1; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/serviceusage/v1beta1/resources.proto"; +import "google/longrunning/operations.proto"; +import "google/protobuf/empty.proto"; +import "google/protobuf/field_mask.proto"; + +option csharp_namespace = "Google.Api.ServiceUsage.V1Beta1"; +option go_package = "google.golang.org/genproto/googleapis/api/serviceusage/v1beta1;serviceusage"; +option java_multiple_files = true; +option java_outer_classname = "ServiceUsageProto"; +option java_package = "com.google.api.serviceusage.v1beta1"; +option php_namespace = "Google\\Api\\ServiceUsage\\V1beta1"; +option ruby_package = "Google::Api::ServiceUsage::V1beta1"; + +// [Service Usage API](https://cloud.google.com/service-usage/docs/overview) +service ServiceUsage { + option (google.api.default_host) = "serviceusage.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/cloud-platform.read-only," + "https://www.googleapis.com/auth/service.management"; + + // Enables a service so that it can be used with a project. + // + // Operation response type: `google.protobuf.Empty` + rpc EnableService(EnableServiceRequest) + returns (google.longrunning.Operation) { + option deprecated = true; + option (google.api.http) = { + post: "/v1beta1/{name=*/*/services/*}:enable" + body: "*" + }; + option (google.longrunning.operation_info) = { + response_type: "google.protobuf.Empty" + metadata_type: "OperationMetadata" + }; + } + + // Disables a service so that it can no longer be used with a project. + // This prevents unintended usage that may cause unexpected billing + // charges or security leaks. + // + // It is not valid to call the disable method on a service that is not + // currently enabled. Callers will receive a `FAILED_PRECONDITION` status if + // the target service is not currently enabled. + // + // Operation response type: `google.protobuf.Empty` + rpc DisableService(DisableServiceRequest) + returns (google.longrunning.Operation) { + option deprecated = true; + option (google.api.http) = { + post: "/v1beta1/{name=*/*/services/*}:disable" + body: "*" + }; + option (google.longrunning.operation_info) = { + response_type: "google.protobuf.Empty" + metadata_type: "OperationMetadata" + }; + } + + // Returns the service configuration and enabled state for a given service. + rpc GetService(GetServiceRequest) returns (Service) { + option deprecated = true; + option (google.api.http) = { + get: "/v1beta1/{name=*/*/services/*}" + }; + } + + // Lists all services available to the specified project, and the current + // state of those services with respect to the project. The list includes + // all public services, all services for which the calling user has the + // `servicemanagement.services.bind` permission, and all services that have + // already been enabled on the project. The list can be filtered to + // only include services in a specific state, for example to only include + // services enabled on the project. + rpc ListServices(ListServicesRequest) returns (ListServicesResponse) { + option deprecated = true; + option (google.api.http) = { + get: "/v1beta1/{parent=*/*}/services" + }; + } + + // Enables multiple services on a project. The operation is atomic: if + // enabling any service fails, then the entire batch fails, and no state + // changes occur. + // + // Operation response type: `google.protobuf.Empty` + rpc BatchEnableServices(BatchEnableServicesRequest) + returns (google.longrunning.Operation) { + option deprecated = true; + option (google.api.http) = { + post: "/v1beta1/{parent=*/*}/services:batchEnable" + body: "*" + }; + option (google.longrunning.operation_info) = { + response_type: "google.protobuf.Empty" + metadata_type: "OperationMetadata" + }; + } + + // Retrieves a summary of all quota information visible to the service + // consumer, organized by service metric. Each metric includes information + // about all of its defined limits. Each limit includes the limit + // configuration (quota unit, preciseness, default value), the current + // effective limit value, and all of the overrides applied to the limit. + rpc ListConsumerQuotaMetrics(ListConsumerQuotaMetricsRequest) + returns (ListConsumerQuotaMetricsResponse) { + option (google.api.http) = { + get: "/v1beta1/{parent=*/*/services/*}/consumerQuotaMetrics" + }; + } + + // Retrieves a summary of quota information for a specific quota metric + rpc GetConsumerQuotaMetric(GetConsumerQuotaMetricRequest) + returns (ConsumerQuotaMetric) { + option (google.api.http) = { + get: "/v1beta1/{name=*/*/services/*/consumerQuotaMetrics/*}" + }; + } + + // Retrieves a summary of quota information for a specific quota limit. + rpc GetConsumerQuotaLimit(GetConsumerQuotaLimitRequest) + returns (ConsumerQuotaLimit) { + option (google.api.http) = { + get: "/v1beta1/{name=*/*/services/*/consumerQuotaMetrics/*/limits/*}" + }; + } + + // Creates an admin override. + // An admin override is applied by an administrator of a parent folder or + // parent organization of the consumer receiving the override. An admin + // override is intended to limit the amount of quota the consumer can use out + // of the total quota pool allocated to all children of the folder or + // organization. + rpc CreateAdminOverride(CreateAdminOverrideRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1beta1/{parent=*/*/services/*/consumerQuotaMetrics/*/limits/*}/adminOverrides" + body: "override" + }; + option (google.longrunning.operation_info) = { + response_type: "QuotaOverride" + metadata_type: "OperationMetadata" + }; + } + + // Updates an admin override. + rpc UpdateAdminOverride(UpdateAdminOverrideRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + patch: "/v1beta1/{name=*/*/services/*/consumerQuotaMetrics/*/limits/*/adminOverrides/*}" + body: "override" + }; + option (google.longrunning.operation_info) = { + response_type: "QuotaOverride" + metadata_type: "OperationMetadata" + }; + } + + // Deletes an admin override. + rpc DeleteAdminOverride(DeleteAdminOverrideRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + delete: "/v1beta1/{name=*/*/services/*/consumerQuotaMetrics/*/limits/*/adminOverrides/*}" + }; + option (google.longrunning.operation_info) = { + response_type: "google.protobuf.Empty" + metadata_type: "OperationMetadata" + }; + } + + // Lists all admin overrides on this limit. + rpc ListAdminOverrides(ListAdminOverridesRequest) + returns (ListAdminOverridesResponse) { + option (google.api.http) = { + get: "/v1beta1/{parent=*/*/services/*/consumerQuotaMetrics/*/limits/*}/adminOverrides" + }; + } + + // Creates or updates multiple admin overrides atomically, all on the + // same consumer, but on many different metrics or limits. + // The name field in the quota override message should not be set. + rpc ImportAdminOverrides(ImportAdminOverridesRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1beta1/{parent=*/*/services/*}/consumerQuotaMetrics:importAdminOverrides" + body: "*" + }; + option (google.longrunning.operation_info) = { + response_type: "ImportAdminOverridesResponse" + metadata_type: "ImportAdminOverridesMetadata" + }; + } + + // Creates a consumer override. + // A consumer override is applied to the consumer on its own authority to + // limit its own quota usage. Consumer overrides cannot be used to grant more + // quota than would be allowed by admin overrides, producer overrides, or the + // default limit of the service. + rpc CreateConsumerOverride(CreateConsumerOverrideRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1beta1/{parent=*/*/services/*/consumerQuotaMetrics/*/limits/*}/consumerOverrides" + body: "override" + }; + option (google.longrunning.operation_info) = { + response_type: "QuotaOverride" + metadata_type: "OperationMetadata" + }; + } + + // Updates a consumer override. + rpc UpdateConsumerOverride(UpdateConsumerOverrideRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + patch: "/v1beta1/{name=*/*/services/*/consumerQuotaMetrics/*/limits/*/consumerOverrides/*}" + body: "override" + }; + option (google.longrunning.operation_info) = { + response_type: "QuotaOverride" + metadata_type: "OperationMetadata" + }; + } + + // Deletes a consumer override. + rpc DeleteConsumerOverride(DeleteConsumerOverrideRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + delete: "/v1beta1/{name=*/*/services/*/consumerQuotaMetrics/*/limits/*/consumerOverrides/*}" + }; + option (google.longrunning.operation_info) = { + response_type: "google.protobuf.Empty" + metadata_type: "OperationMetadata" + }; + } + + // Lists all consumer overrides on this limit. + rpc ListConsumerOverrides(ListConsumerOverridesRequest) + returns (ListConsumerOverridesResponse) { + option (google.api.http) = { + get: "/v1beta1/{parent=*/*/services/*/consumerQuotaMetrics/*/limits/*}/consumerOverrides" + }; + } + + // Creates or updates multiple consumer overrides atomically, all on the + // same consumer, but on many different metrics or limits. + // The name field in the quota override message should not be set. + rpc ImportConsumerOverrides(ImportConsumerOverridesRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1beta1/{parent=*/*/services/*}/consumerQuotaMetrics:importConsumerOverrides" + body: "*" + }; + option (google.longrunning.operation_info) = { + response_type: "ImportConsumerOverridesResponse" + metadata_type: "ImportConsumerOverridesMetadata" + }; + } + + // Generates service identity for service. + rpc GenerateServiceIdentity(GenerateServiceIdentityRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1beta1/{parent=*/*/services/*}:generateServiceIdentity" + }; + option (google.longrunning.operation_info) = { + response_type: "ServiceIdentity" + metadata_type: "google.protobuf.Empty" + }; + } +} + +// Request message for the `EnableService` method. +message EnableServiceRequest { + // Name of the consumer and service to enable the service on. + // + // The `EnableService` and `DisableService` methods currently only support + // projects. + // + // Enabling a service requires that the service is public or is shared with + // the user enabling the service. + // + // An example name would be: + // `projects/123/services/serviceusage.googleapis.com` + // where `123` is the project number (not project ID). + string name = 1; +} + +// Request message for the `DisableService` method. +message DisableServiceRequest { + // Name of the consumer and service to disable the service on. + // + // The enable and disable methods currently only support projects. + // + // An example name would be: + // `projects/123/services/serviceusage.googleapis.com` + // where `123` is the project number (not project ID). + string name = 1; +} + +// Request message for the `GetService` method. +message GetServiceRequest { + // Name of the consumer and service to get the `ConsumerState` for. + // + // An example name would be: + // `projects/123/services/serviceusage.googleapis.com` + // where `123` is the project number (not project ID). + string name = 1; +} + +// Request message for the `ListServices` method. +message ListServicesRequest { + // Parent to search for services on. + // + // An example name would be: + // `projects/123` + // where `123` is the project number (not project ID). + string parent = 1; + + // Requested size of the next page of data. + // Requested page size cannot exceed 200. + // If not set, the default page size is 50. + int32 page_size = 2; + + // Token identifying which result to start with, which is returned by a + // previous list call. + string page_token = 3; + + // Only list services that conform to the given filter. + // The allowed filter strings are `state:ENABLED` and `state:DISABLED`. + string filter = 4; +} + +// Response message for the `ListServices` method. +message ListServicesResponse { + // The available services for the requested project. + repeated Service services = 1; + + // Token that can be passed to `ListServices` to resume a paginated + // query. + string next_page_token = 2; +} + +// Request message for the `BatchEnableServices` method. +message BatchEnableServicesRequest { + // Parent to enable services on. + // + // An example name would be: + // `projects/123` + // where `123` is the project number (not project ID). + // + // The `BatchEnableServices` method currently only supports projects. + string parent = 1; + + // The identifiers of the services to enable on the project. + // + // A valid identifier would be: + // serviceusage.googleapis.com + // + // Enabling services requires that each service is public or is shared with + // the user enabling the service. + // + // Two or more services must be specified. To enable a single service, + // use the `EnableService` method instead. + // + // A single request can enable a maximum of 20 services at a time. If more + // than 20 services are specified, the request will fail, and no state changes + // will occur. + repeated string service_ids = 2; +} + +// Request message for ListConsumerQuotaMetrics +message ListConsumerQuotaMetricsRequest { + // Parent of the quotas resource. + // + // Some example names would be: + // `projects/123/services/serviceconsumermanagement.googleapis.com` + // `folders/345/services/serviceconsumermanagement.googleapis.com` + // `organizations/456/services/serviceconsumermanagement.googleapis.com` + string parent = 1; + + // Requested size of the next page of data. + int32 page_size = 2; + + // Token identifying which result to start with; returned by a previous list + // call. + string page_token = 3; + + // Specifies the level of detail for quota information in the response. + QuotaView view = 4; +} + +// Response message for ListConsumerQuotaMetrics +message ListConsumerQuotaMetricsResponse { + // Quota settings for the consumer, organized by quota metric. + repeated ConsumerQuotaMetric metrics = 1; + + // Token identifying which result to start with; returned by a previous list + // call. + string next_page_token = 2; +} + +// Request message for GetConsumerQuotaMetric +message GetConsumerQuotaMetricRequest { + // The resource name of the quota limit. + // + // An example name would be: + // `projects/123/services/serviceusage.googleapis.com/quotas/metrics/serviceusage.googleapis.com%2Fmutate_requests` + string name = 1; + + // Specifies the level of detail for quota information in the response. + QuotaView view = 2; +} + +// Request message for GetConsumerQuotaLimit +message GetConsumerQuotaLimitRequest { + // The resource name of the quota limit. + // + // Use the quota limit resource name returned by previous + // ListConsumerQuotaMetrics and GetConsumerQuotaMetric API calls. + string name = 1; + + // Specifies the level of detail for quota information in the response. + QuotaView view = 2; +} + +// Request message for CreateAdminOverride. +message CreateAdminOverrideRequest { + // The resource name of the parent quota limit, returned by a + // ListConsumerQuotaMetrics or GetConsumerQuotaMetric call. + // + // An example name would be: + // `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion` + string parent = 1; + + // The admin override to create. + QuotaOverride override = 2; + + // Whether to force the creation of the quota override. + // Setting the force parameter to 'true' ignores all quota safety checks that + // would fail the request. QuotaSafetyCheck lists all such validations. + bool force = 3; + + // The list of quota safety checks to ignore before the override mutation. + // Unlike 'force' field that ignores all the quota safety checks, the + // 'force_only' field ignores only the specified checks; other checks are + // still enforced. The 'force' and 'force_only' fields cannot both be set. + repeated QuotaSafetyCheck force_only = 4; +} + +// Request message for UpdateAdminOverride. +message UpdateAdminOverrideRequest { + // The resource name of the override to update. + // + // An example name would be: + // `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion/adminOverrides/4a3f2c1d` + string name = 1; + + // The new override. + // Only the override_value is updated; all other fields are ignored. + QuotaOverride override = 2; + + // Whether to force the update of the quota override. + // Setting the force parameter to 'true' ignores all quota safety checks that + // would fail the request. QuotaSafetyCheck lists all such validations. + bool force = 3; + + // Update only the specified fields of the override. + // If unset, all fields will be updated. + google.protobuf.FieldMask update_mask = 4; + + // The list of quota safety checks to ignore before the override mutation. + // Unlike 'force' field that ignores all the quota safety checks, the + // 'force_only' field ignores only the specified checks; other checks are + // still enforced. The 'force' and 'force_only' fields cannot both be set. + repeated QuotaSafetyCheck force_only = 5; +} + +// Request message for DeleteAdminOverride. +message DeleteAdminOverrideRequest { + // The resource name of the override to delete. + // + // An example name would be: + // `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion/adminOverrides/4a3f2c1d` + string name = 1; + + // Whether to force the deletion of the quota override. + // Setting the force parameter to 'true' ignores all quota safety checks that + // would fail the request. QuotaSafetyCheck lists all such validations. + bool force = 2; + + // The list of quota safety checks to ignore before the override mutation. + // Unlike 'force' field that ignores all the quota safety checks, the + // 'force_only' field ignores only the specified checks; other checks are + // still enforced. The 'force' and 'force_only' fields cannot both be set. + repeated QuotaSafetyCheck force_only = 3; +} + +// Request message for ListAdminOverrides +message ListAdminOverridesRequest { + // The resource name of the parent quota limit, returned by a + // ListConsumerQuotaMetrics or GetConsumerQuotaMetric call. + // + // An example name would be: + // `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion` + string parent = 1; + + // Requested size of the next page of data. + int32 page_size = 2; + + // Token identifying which result to start with; returned by a previous list + // call. + string page_token = 3; +} + +// Response message for ListAdminOverrides. +message ListAdminOverridesResponse { + // Admin overrides on this limit. + repeated QuotaOverride overrides = 1; + + // Token identifying which result to start with; returned by a previous list + // call. + string next_page_token = 2; +} + +// Response message for BatchCreateAdminOverrides +message BatchCreateAdminOverridesResponse { + // The overrides that were created. + repeated QuotaOverride overrides = 1; +} + +// Request message for ImportAdminOverrides +message ImportAdminOverridesRequest { + // The resource name of the consumer. + // + // An example name would be: + // `projects/123/services/compute.googleapis.com` + string parent = 1; + + // Source of import data + oneof source { + // The import data is specified in the request message itself + OverrideInlineSource inline_source = 2; + } + + // Whether to force the creation of the quota overrides. + // Setting the force parameter to 'true' ignores all quota safety checks that + // would fail the request. QuotaSafetyCheck lists all such validations. + bool force = 3; + + // The list of quota safety checks to ignore before the override mutation. + // Unlike 'force' field that ignores all the quota safety checks, the + // 'force_only' field ignores only the specified checks; other checks are + // still enforced. The 'force' and 'force_only' fields cannot both be set. + repeated QuotaSafetyCheck force_only = 4; +} + +// Response message for ImportAdminOverrides +message ImportAdminOverridesResponse { + // The overrides that were created from the imported data. + repeated QuotaOverride overrides = 1; +} + +// Metadata message that provides information such as progress, +// partial failures, and similar information on each GetOperation call +// of LRO returned by ImportAdminOverrides. +message ImportAdminOverridesMetadata {} + +// Request message for CreateConsumerOverride. +message CreateConsumerOverrideRequest { + // The resource name of the parent quota limit, returned by a + // ListConsumerQuotaMetrics or GetConsumerQuotaMetric call. + // + // An example name would be: + // `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion` + string parent = 1; + + // The override to create. + QuotaOverride override = 2; + + // Whether to force the creation of the quota override. + // Setting the force parameter to 'true' ignores all quota safety checks that + // would fail the request. QuotaSafetyCheck lists all such validations. + bool force = 3; + + // The list of quota safety checks to ignore before the override mutation. + // Unlike 'force' field that ignores all the quota safety checks, the + // 'force_only' field ignores only the specified checks; other checks are + // still enforced. The 'force' and 'force_only' fields cannot both be set. + repeated QuotaSafetyCheck force_only = 4; +} + +// Request message for UpdateConsumerOverride. +message UpdateConsumerOverrideRequest { + // The resource name of the override to update. + // + // An example name would be: + // `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion/consumerOverrides/4a3f2c1d` + string name = 1; + + // The new override. + // Only the override_value is updated; all other fields are ignored. + QuotaOverride override = 2; + + // Whether to force the update of the quota override. + // Setting the force parameter to 'true' ignores all quota safety checks that + // would fail the request. QuotaSafetyCheck lists all such validations. + bool force = 3; + + // Update only the specified fields of the override. + // If unset, all fields will be updated. + google.protobuf.FieldMask update_mask = 4; + + // The list of quota safety checks to ignore before the override mutation. + // Unlike 'force' field that ignores all the quota safety checks, the + // 'force_only' field ignores only the specified checks; other checks are + // still enforced. The 'force' and 'force_only' fields cannot both be set. + repeated QuotaSafetyCheck force_only = 5; +} + +// Request message for DeleteConsumerOverride. +message DeleteConsumerOverrideRequest { + // The resource name of the override to delete. + // + // An example name would be: + // `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion/consumerOverrides/4a3f2c1d` + string name = 1; + + // Whether to force the deletion of the quota override. + // Setting the force parameter to 'true' ignores all quota safety checks that + // would fail the request. QuotaSafetyCheck lists all such validations. + bool force = 2; + + // The list of quota safety checks to ignore before the override mutation. + // Unlike 'force' field that ignores all the quota safety checks, the + // 'force_only' field ignores only the specified checks; other checks are + // still enforced. The 'force' and 'force_only' fields cannot both be set. + repeated QuotaSafetyCheck force_only = 3; +} + +// Request message for ListConsumerOverrides +message ListConsumerOverridesRequest { + // The resource name of the parent quota limit, returned by a + // ListConsumerQuotaMetrics or GetConsumerQuotaMetric call. + // + // An example name would be: + // `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion` + string parent = 1; + + // Requested size of the next page of data. + int32 page_size = 2; + + // Token identifying which result to start with; returned by a previous list + // call. + string page_token = 3; +} + +// Response message for ListConsumerOverrides. +message ListConsumerOverridesResponse { + // Consumer overrides on this limit. + repeated QuotaOverride overrides = 1; + + // Token identifying which result to start with; returned by a previous list + // call. + string next_page_token = 2; +} + +// Response message for BatchCreateConsumerOverrides +message BatchCreateConsumerOverridesResponse { + // The overrides that were created. + repeated QuotaOverride overrides = 1; +} + +// Request message for ImportConsumerOverrides +message ImportConsumerOverridesRequest { + // The resource name of the consumer. + // + // An example name would be: + // `projects/123/services/compute.googleapis.com` + string parent = 1; + + // Source of import data + oneof source { + // The import data is specified in the request message itself + OverrideInlineSource inline_source = 2; + } + + // Whether to force the creation of the quota overrides. + // Setting the force parameter to 'true' ignores all quota safety checks that + // would fail the request. QuotaSafetyCheck lists all such validations. + bool force = 3; + + // The list of quota safety checks to ignore before the override mutation. + // Unlike 'force' field that ignores all the quota safety checks, the + // 'force_only' field ignores only the specified checks; other checks are + // still enforced. The 'force' and 'force_only' fields cannot both be set. + repeated QuotaSafetyCheck force_only = 4; +} + +// Response message for ImportConsumerOverrides +message ImportConsumerOverridesResponse { + // The overrides that were created from the imported data. + repeated QuotaOverride overrides = 1; +} + +// Metadata message that provides information such as progress, +// partial failures, and similar information on each GetOperation call +// of LRO returned by ImportConsumerOverrides. +message ImportConsumerOverridesMetadata {} + +// Response message for ImportAdminQuotaPolicies +message ImportAdminQuotaPoliciesResponse { + // The policies that were created from the imported data. + repeated AdminQuotaPolicy policies = 1; +} + +// Metadata message that provides information such as progress, +// partial failures, and similar information on each GetOperation call +// of LRO returned by ImportAdminQuotaPolicies. +message ImportAdminQuotaPoliciesMetadata {} + +// Metadata message that provides information such as progress, +// partial failures, and similar information on each GetOperation call +// of LRO returned by CreateAdminQuotaPolicy. +message CreateAdminQuotaPolicyMetadata {} + +// Metadata message that provides information such as progress, +// partial failures, and similar information on each GetOperation call +// of LRO returned by UpdateAdminQuotaPolicy. +message UpdateAdminQuotaPolicyMetadata {} + +// Metadata message that provides information such as progress, +// partial failures, and similar information on each GetOperation call +// of LRO returned by DeleteAdminQuotaPolicy. +message DeleteAdminQuotaPolicyMetadata {} + +// Request message for generating service identity. +message GenerateServiceIdentityRequest { + // Name of the consumer and service to generate an identity for. + // + // The `GenerateServiceIdentity` methods currently support projects, folders, + // organizations. + // + // Example parents would be: + // `projects/123/services/example.googleapis.com` + // `folders/123/services/example.googleapis.com` + // `organizations/123/services/example.googleapis.com` + string parent = 1; +} + +// Response message for getting service identity. +message GetServiceIdentityResponse { + // Enum for service identity state. + enum IdentityState { + // Default service identity state. This value is used if the state is + // omitted. + IDENTITY_STATE_UNSPECIFIED = 0; + + // Service identity has been created and can be used. + ACTIVE = 1; + } + + // Service identity that service producer can use to access consumer + // resources. If exists is true, it contains email and unique_id. If exists is + // false, it contains pre-constructed email and empty unique_id. + ServiceIdentity identity = 1; + + // Service identity state. + IdentityState state = 2; +} + +// Metadata for the `GetServiceIdentity` method. +message GetServiceIdentityMetadata {} diff --git a/node_modules/google-gax/build/protos/google/api/source_info.proto b/node_modules/google-gax/build/protos/google/api/source_info.proto new file mode 100644 index 0000000..51fe279 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/source_info.proto @@ -0,0 +1,31 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/protobuf/any.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/serviceconfig;serviceconfig"; +option java_multiple_files = true; +option java_outer_classname = "SourceInfoProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Source information used to create a Service Config +message SourceInfo { + // All files used during config generation. + repeated google.protobuf.Any source_files = 1; +} diff --git a/node_modules/google-gax/build/protos/google/api/system_parameter.proto b/node_modules/google-gax/build/protos/google/api/system_parameter.proto new file mode 100644 index 0000000..8d29057 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/system_parameter.proto @@ -0,0 +1,96 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option go_package = "google.golang.org/genproto/googleapis/api/serviceconfig;serviceconfig"; +option java_multiple_files = true; +option java_outer_classname = "SystemParameterProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// ### System parameter configuration +// +// A system parameter is a special kind of parameter defined by the API +// system, not by an individual API. It is typically mapped to an HTTP header +// and/or a URL query parameter. This configuration specifies which methods +// change the names of the system parameters. +message SystemParameters { + // Define system parameters. + // + // The parameters defined here will override the default parameters + // implemented by the system. If this field is missing from the service + // config, default system parameters will be used. Default system parameters + // and names is implementation-dependent. + // + // Example: define api key for all methods + // + // system_parameters + // rules: + // - selector: "*" + // parameters: + // - name: api_key + // url_query_parameter: api_key + // + // + // Example: define 2 api key names for a specific method. + // + // system_parameters + // rules: + // - selector: "/ListShelves" + // parameters: + // - name: api_key + // http_header: Api-Key1 + // - name: api_key + // http_header: Api-Key2 + // + // **NOTE:** All service configuration rules follow "last one wins" order. + repeated SystemParameterRule rules = 1; +} + +// Define a system parameter rule mapping system parameter definitions to +// methods. +message SystemParameterRule { + // Selects the methods to which this rule applies. Use '*' to indicate all + // methods in all APIs. + // + // Refer to [selector][google.api.DocumentationRule.selector] for syntax + // details. + string selector = 1; + + // Define parameters. Multiple names may be defined for a parameter. + // For a given method call, only one of them should be used. If multiple + // names are used the behavior is implementation-dependent. + // If none of the specified names are present the behavior is + // parameter-dependent. + repeated SystemParameter parameters = 2; +} + +// Define a parameter's name and location. The parameter may be passed as either +// an HTTP header or a URL query parameter, and if both are passed the behavior +// is implementation-dependent. +message SystemParameter { + // Define the name of the parameter, such as "api_key" . It is case sensitive. + string name = 1; + + // Define the HTTP header name to use for the parameter. It is case + // insensitive. + string http_header = 2; + + // Define the URL query parameter name to use for the parameter. It is case + // sensitive. + string url_query_parameter = 3; +} diff --git a/node_modules/google-gax/build/protos/google/api/usage.proto b/node_modules/google-gax/build/protos/google/api/usage.proto new file mode 100644 index 0000000..b9384b4 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/usage.proto @@ -0,0 +1,96 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option go_package = "google.golang.org/genproto/googleapis/api/serviceconfig;serviceconfig"; +option java_multiple_files = true; +option java_outer_classname = "UsageProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Configuration controlling usage of a service. +message Usage { + // Requirements that must be satisfied before a consumer project can use the + // service. Each requirement is of the form /; + // for example 'serviceusage.googleapis.com/billing-enabled'. + // + // For Google APIs, a Terms of Service requirement must be included here. + // Google Cloud APIs must include "serviceusage.googleapis.com/tos/cloud". + // Other Google APIs should include + // "serviceusage.googleapis.com/tos/universal". Additional ToS can be + // included based on the business needs. + repeated string requirements = 1; + + // A list of usage rules that apply to individual API methods. + // + // **NOTE:** All service configuration rules follow "last one wins" order. + repeated UsageRule rules = 6; + + // The full resource name of a channel used for sending notifications to the + // service producer. + // + // Google Service Management currently only supports + // [Google Cloud Pub/Sub](https://cloud.google.com/pubsub) as a notification + // channel. To use Google Cloud Pub/Sub as the channel, this must be the name + // of a Cloud Pub/Sub topic that uses the Cloud Pub/Sub topic name format + // documented in https://cloud.google.com/pubsub/docs/overview. + string producer_notification_channel = 7; +} + +// Usage configuration rules for the service. +// +// NOTE: Under development. +// +// +// Use this rule to configure unregistered calls for the service. Unregistered +// calls are calls that do not contain consumer project identity. +// (Example: calls that do not contain an API key). +// By default, API methods do not allow unregistered calls, and each method call +// must be identified by a consumer project identity. Use this rule to +// allow/disallow unregistered calls. +// +// Example of an API that wants to allow unregistered calls for entire service. +// +// usage: +// rules: +// - selector: "*" +// allow_unregistered_calls: true +// +// Example of a method that wants to allow unregistered calls. +// +// usage: +// rules: +// - selector: "google.example.library.v1.LibraryService.CreateBook" +// allow_unregistered_calls: true +message UsageRule { + // Selects the methods to which this rule applies. Use '*' to indicate all + // methods in all APIs. + // + // Refer to [selector][google.api.DocumentationRule.selector] for syntax + // details. + string selector = 1; + + // If true, the selected method allows unregistered calls, e.g. calls + // that don't identify any user or application. + bool allow_unregistered_calls = 2; + + // If true, the selected method should skip service control and the control + // plane features, such as quota and billing, will not be available. + // This flag is used by Google Cloud Endpoints to bypass checks for internal + // methods, such as service health check methods. + bool skip_service_control = 3; +} diff --git a/node_modules/google-gax/build/protos/google/api/visibility.proto b/node_modules/google-gax/build/protos/google/api/visibility.proto new file mode 100644 index 0000000..8b1f946 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/api/visibility.proto @@ -0,0 +1,113 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/protobuf/descriptor.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/visibility;visibility"; +option java_multiple_files = true; +option java_outer_classname = "VisibilityProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +extend google.protobuf.EnumOptions { + // See `VisibilityRule`. + google.api.VisibilityRule enum_visibility = 72295727; +} + +extend google.protobuf.EnumValueOptions { + // See `VisibilityRule`. + google.api.VisibilityRule value_visibility = 72295727; +} + +extend google.protobuf.FieldOptions { + // See `VisibilityRule`. + google.api.VisibilityRule field_visibility = 72295727; +} + +extend google.protobuf.MessageOptions { + // See `VisibilityRule`. + google.api.VisibilityRule message_visibility = 72295727; +} + +extend google.protobuf.MethodOptions { + // See `VisibilityRule`. + google.api.VisibilityRule method_visibility = 72295727; +} + +extend google.protobuf.ServiceOptions { + // See `VisibilityRule`. + google.api.VisibilityRule api_visibility = 72295727; +} + +// `Visibility` restricts service consumer's access to service elements, +// such as whether an application can call a visibility-restricted method. +// The restriction is expressed by applying visibility labels on service +// elements. The visibility labels are elsewhere linked to service consumers. +// +// A service can define multiple visibility labels, but a service consumer +// should be granted at most one visibility label. Multiple visibility +// labels for a single service consumer are not supported. +// +// If an element and all its parents have no visibility label, its visibility +// is unconditionally granted. +// +// Example: +// +// visibility: +// rules: +// - selector: google.calendar.Calendar.EnhancedSearch +// restriction: PREVIEW +// - selector: google.calendar.Calendar.Delegate +// restriction: INTERNAL +// +// Here, all methods are publicly visible except for the restricted methods +// EnhancedSearch and Delegate. +message Visibility { + // A list of visibility rules that apply to individual API elements. + // + // **NOTE:** All service configuration rules follow "last one wins" order. + repeated VisibilityRule rules = 1; +} + +// A visibility rule provides visibility configuration for an individual API +// element. +message VisibilityRule { + // Selects methods, messages, fields, enums, etc. to which this rule applies. + // + // Refer to [selector][google.api.DocumentationRule.selector] for syntax + // details. + string selector = 1; + + // A comma-separated list of visibility labels that apply to the `selector`. + // Any of the listed labels can be used to grant the visibility. + // + // If a rule has multiple labels, removing one of the labels but not all of + // them can break clients. + // + // Example: + // + // visibility: + // rules: + // - selector: google.calendar.Calendar.EnhancedSearch + // restriction: INTERNAL, PREVIEW + // + // Removing INTERNAL from this restriction will break clients that rely on + // this method and only had access to it through INTERNAL. + string restriction = 2; +} diff --git a/node_modules/google-gax/build/protos/google/cloud/location/locations.proto b/node_modules/google-gax/build/protos/google/cloud/location/locations.proto new file mode 100644 index 0000000..a91766c --- /dev/null +++ b/node_modules/google-gax/build/protos/google/cloud/location/locations.proto @@ -0,0 +1,108 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.cloud.location; + +import "google/api/annotations.proto"; +import "google/protobuf/any.proto"; +import "google/api/client.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/cloud/location;location"; +option java_multiple_files = true; +option java_outer_classname = "LocationsProto"; +option java_package = "com.google.cloud.location"; + +// An abstract interface that provides location-related information for +// a service. Service-specific metadata is provided through the +// [Location.metadata][google.cloud.location.Location.metadata] field. +service Locations { + option (google.api.default_host) = "cloud.googleapis.com"; + option (google.api.oauth_scopes) = "https://www.googleapis.com/auth/cloud-platform"; + + // Lists information about the supported locations for this service. + rpc ListLocations(ListLocationsRequest) returns (ListLocationsResponse) { + option (google.api.http) = { + get: "/v1/{name=locations}" + additional_bindings { + get: "/v1/{name=projects/*}/locations" + } + }; + } + + // Gets information about a location. + rpc GetLocation(GetLocationRequest) returns (Location) { + option (google.api.http) = { + get: "/v1/{name=locations/*}" + additional_bindings { + get: "/v1/{name=projects/*/locations/*}" + } + }; + } +} + +// The request message for [Locations.ListLocations][google.cloud.location.Locations.ListLocations]. +message ListLocationsRequest { + // The resource that owns the locations collection, if applicable. + string name = 1; + + // The standard list filter. + string filter = 2; + + // The standard list page size. + int32 page_size = 3; + + // The standard list page token. + string page_token = 4; +} + +// The response message for [Locations.ListLocations][google.cloud.location.Locations.ListLocations]. +message ListLocationsResponse { + // A list of locations that matches the specified filter in the request. + repeated Location locations = 1; + + // The standard List next-page token. + string next_page_token = 2; +} + +// The request message for [Locations.GetLocation][google.cloud.location.Locations.GetLocation]. +message GetLocationRequest { + // Resource name for the location. + string name = 1; +} + +// A resource that represents Google Cloud Platform location. +message Location { + // Resource name for the location, which may vary between implementations. + // For example: `"projects/example-project/locations/us-east1"` + string name = 1; + + // The canonical id for this location. For example: `"us-east1"`. + string location_id = 4; + + // The friendly name for this location, typically a nearby city name. + // For example, "Tokyo". + string display_name = 5; + + // Cross-service attributes for the location. For example + // + // {"cloud.googleapis.com/region": "us-east1"} + map labels = 2; + + // Service-specific metadata. For example the available capacity at the given + // location. + google.protobuf.Any metadata = 3; +} diff --git a/node_modules/google-gax/build/protos/google/iam/v1/iam_policy.proto b/node_modules/google-gax/build/protos/google/iam/v1/iam_policy.proto new file mode 100644 index 0000000..10c65f9 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/iam/v1/iam_policy.proto @@ -0,0 +1,155 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.iam.v1; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/iam/v1/options.proto"; +import "google/iam/v1/policy.proto"; +import "google/protobuf/field_mask.proto"; + +option cc_enable_arenas = true; +option csharp_namespace = "Google.Cloud.Iam.V1"; +option go_package = "cloud.google.com/go/iam/apiv1/iampb;iampb"; +option java_multiple_files = true; +option java_outer_classname = "IamPolicyProto"; +option java_package = "com.google.iam.v1"; +option php_namespace = "Google\\Cloud\\Iam\\V1"; + +// API Overview +// +// +// Manages Identity and Access Management (IAM) policies. +// +// Any implementation of an API that offers access control features +// implements the google.iam.v1.IAMPolicy interface. +// +// ## Data model +// +// Access control is applied when a principal (user or service account), takes +// some action on a resource exposed by a service. Resources, identified by +// URI-like names, are the unit of access control specification. Service +// implementations can choose the granularity of access control and the +// supported permissions for their resources. +// For example one database service may allow access control to be +// specified only at the Table level, whereas another might allow access control +// to also be specified at the Column level. +// +// ## Policy Structure +// +// See google.iam.v1.Policy +// +// This is intentionally not a CRUD style API because access control policies +// are created and deleted implicitly with the resources to which they are +// attached. +service IAMPolicy { + option (google.api.default_host) = "iam-meta-api.googleapis.com"; + + // Sets the access control policy on the specified resource. Replaces any + // existing policy. + // + // Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors. + rpc SetIamPolicy(SetIamPolicyRequest) returns (Policy) { + option (google.api.http) = { + post: "/v1/{resource=**}:setIamPolicy" + body: "*" + }; + } + + // Gets the access control policy for a resource. + // Returns an empty policy if the resource exists and does not have a policy + // set. + rpc GetIamPolicy(GetIamPolicyRequest) returns (Policy) { + option (google.api.http) = { + post: "/v1/{resource=**}:getIamPolicy" + body: "*" + }; + } + + // Returns permissions that a caller has on the specified resource. + // If the resource does not exist, this will return an empty set of + // permissions, not a `NOT_FOUND` error. + // + // Note: This operation is designed to be used for building permission-aware + // UIs and command-line tools, not for authorization checking. This operation + // may "fail open" without warning. + rpc TestIamPermissions(TestIamPermissionsRequest) returns (TestIamPermissionsResponse) { + option (google.api.http) = { + post: "/v1/{resource=**}:testIamPermissions" + body: "*" + }; + } +} + +// Request message for `SetIamPolicy` method. +message SetIamPolicyRequest { + // REQUIRED: The resource for which the policy is being specified. + // See the operation documentation for the appropriate value for this field. + string resource = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference).type = "*"]; + + // REQUIRED: The complete policy to be applied to the `resource`. The size of + // the policy is limited to a few 10s of KB. An empty policy is a + // valid policy but certain Cloud Platform services (such as Projects) + // might reject them. + Policy policy = 2 [(google.api.field_behavior) = REQUIRED]; + + // OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only + // the fields in the mask will be modified. If no mask is provided, the + // following default mask is used: + // + // `paths: "bindings, etag"` + google.protobuf.FieldMask update_mask = 3; +} + +// Request message for `GetIamPolicy` method. +message GetIamPolicyRequest { + // REQUIRED: The resource for which the policy is being requested. + // See the operation documentation for the appropriate value for this field. + string resource = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference).type = "*"]; + + // OPTIONAL: A `GetPolicyOptions` object for specifying options to + // `GetIamPolicy`. + GetPolicyOptions options = 2; +} + +// Request message for `TestIamPermissions` method. +message TestIamPermissionsRequest { + // REQUIRED: The resource for which the policy detail is being requested. + // See the operation documentation for the appropriate value for this field. + string resource = 1[ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference).type = "*"]; + + // The set of permissions to check for the `resource`. Permissions with + // wildcards (such as '*' or 'storage.*') are not allowed. For more + // information see + // [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). + repeated string permissions = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// Response message for `TestIamPermissions` method. +message TestIamPermissionsResponse { + // A subset of `TestPermissionsRequest.permissions` that the caller is + // allowed. + repeated string permissions = 1; +} diff --git a/node_modules/google-gax/build/protos/google/iam/v1/logging/audit_data.proto b/node_modules/google-gax/build/protos/google/iam/v1/logging/audit_data.proto new file mode 100644 index 0000000..ee5550c --- /dev/null +++ b/node_modules/google-gax/build/protos/google/iam/v1/logging/audit_data.proto @@ -0,0 +1,33 @@ +// Copyright 2017 Google Inc. +// +// 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. + +syntax = "proto3"; + +package google.iam.v1.logging; + +import "google/iam/v1/policy.proto"; + +option csharp_namespace = "Google.Cloud.Iam.V1.Logging"; +option go_package = "cloud.google.com/go/iam/apiv1/logging/loggingpb;loggingpb"; +option java_multiple_files = true; +option java_outer_classname = "AuditDataProto"; +option java_package = "com.google.iam.v1.logging"; + +// Audit log information specific to Cloud IAM. This message is serialized +// as an `Any` type in the `ServiceData` message of an +// `AuditLog` message. +message AuditData { + // Policy delta between the original policy and the newly set policy. + google.iam.v1.PolicyDelta policy_delta = 2; +} diff --git a/node_modules/google-gax/build/protos/google/iam/v1/options.proto b/node_modules/google-gax/build/protos/google/iam/v1/options.proto new file mode 100644 index 0000000..84e9c47 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/iam/v1/options.proto @@ -0,0 +1,48 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.iam.v1; + +option cc_enable_arenas = true; +option csharp_namespace = "Google.Cloud.Iam.V1"; +option go_package = "cloud.google.com/go/iam/apiv1/iampb;iampb"; +option java_multiple_files = true; +option java_outer_classname = "OptionsProto"; +option java_package = "com.google.iam.v1"; +option php_namespace = "Google\\Cloud\\Iam\\V1"; + +// Encapsulates settings provided to GetIamPolicy. +message GetPolicyOptions { + // Optional. The maximum policy version that will be used to format the + // policy. + // + // Valid values are 0, 1, and 3. Requests specifying an invalid value will be + // rejected. + // + // Requests for policies with any conditional role bindings must specify + // version 3. Policies with no conditional role bindings may specify any valid + // value or leave the field unset. + // + // The policy in the response might use the policy version that you specified, + // or it might use a lower policy version. For example, if you specify version + // 3, but the policy has no conditional role bindings, the response uses + // version 1. + // + // To learn which resources support conditions in their IAM policies, see the + // [IAM + // documentation](https://cloud.google.com/iam/help/conditions/resource-policies). + int32 requested_policy_version = 1; +} diff --git a/node_modules/google-gax/build/protos/google/iam/v1/policy.proto b/node_modules/google-gax/build/protos/google/iam/v1/policy.proto new file mode 100644 index 0000000..2386563 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/iam/v1/policy.proto @@ -0,0 +1,410 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.iam.v1; + +import "google/type/expr.proto"; + +option cc_enable_arenas = true; +option csharp_namespace = "Google.Cloud.Iam.V1"; +option go_package = "cloud.google.com/go/iam/apiv1/iampb;iampb"; +option java_multiple_files = true; +option java_outer_classname = "PolicyProto"; +option java_package = "com.google.iam.v1"; +option php_namespace = "Google\\Cloud\\Iam\\V1"; + +// An Identity and Access Management (IAM) policy, which specifies access +// controls for Google Cloud resources. +// +// +// A `Policy` is a collection of `bindings`. A `binding` binds one or more +// `members`, or principals, to a single `role`. Principals can be user +// accounts, service accounts, Google groups, and domains (such as G Suite). A +// `role` is a named list of permissions; each `role` can be an IAM predefined +// role or a user-created custom role. +// +// For some types of Google Cloud resources, a `binding` can also specify a +// `condition`, which is a logical expression that allows access to a resource +// only if the expression evaluates to `true`. A condition can add constraints +// based on attributes of the request, the resource, or both. To learn which +// resources support conditions in their IAM policies, see the +// [IAM +// documentation](https://cloud.google.com/iam/help/conditions/resource-policies). +// +// **JSON example:** +// +// ``` +// { +// "bindings": [ +// { +// "role": "roles/resourcemanager.organizationAdmin", +// "members": [ +// "user:mike@example.com", +// "group:admins@example.com", +// "domain:google.com", +// "serviceAccount:my-project-id@appspot.gserviceaccount.com" +// ] +// }, +// { +// "role": "roles/resourcemanager.organizationViewer", +// "members": [ +// "user:eve@example.com" +// ], +// "condition": { +// "title": "expirable access", +// "description": "Does not grant access after Sep 2020", +// "expression": "request.time < +// timestamp('2020-10-01T00:00:00.000Z')", +// } +// } +// ], +// "etag": "BwWWja0YfJA=", +// "version": 3 +// } +// ``` +// +// **YAML example:** +// +// ``` +// bindings: +// - members: +// - user:mike@example.com +// - group:admins@example.com +// - domain:google.com +// - serviceAccount:my-project-id@appspot.gserviceaccount.com +// role: roles/resourcemanager.organizationAdmin +// - members: +// - user:eve@example.com +// role: roles/resourcemanager.organizationViewer +// condition: +// title: expirable access +// description: Does not grant access after Sep 2020 +// expression: request.time < timestamp('2020-10-01T00:00:00.000Z') +// etag: BwWWja0YfJA= +// version: 3 +// ``` +// +// For a description of IAM and its features, see the +// [IAM documentation](https://cloud.google.com/iam/docs/). +message Policy { + // Specifies the format of the policy. + // + // Valid values are `0`, `1`, and `3`. Requests that specify an invalid value + // are rejected. + // + // Any operation that affects conditional role bindings must specify version + // `3`. This requirement applies to the following operations: + // + // * Getting a policy that includes a conditional role binding + // * Adding a conditional role binding to a policy + // * Changing a conditional role binding in a policy + // * Removing any role binding, with or without a condition, from a policy + // that includes conditions + // + // **Important:** If you use IAM Conditions, you must include the `etag` field + // whenever you call `setIamPolicy`. If you omit this field, then IAM allows + // you to overwrite a version `3` policy with a version `1` policy, and all of + // the conditions in the version `3` policy are lost. + // + // If a policy does not include any conditions, operations on that policy may + // specify any valid version or leave the field unset. + // + // To learn which resources support conditions in their IAM policies, see the + // [IAM + // documentation](https://cloud.google.com/iam/help/conditions/resource-policies). + int32 version = 1; + + // Associates a list of `members`, or principals, with a `role`. Optionally, + // may specify a `condition` that determines how and when the `bindings` are + // applied. Each of the `bindings` must contain at least one principal. + // + // The `bindings` in a `Policy` can refer to up to 1,500 principals; up to 250 + // of these principals can be Google groups. Each occurrence of a principal + // counts towards these limits. For example, if the `bindings` grant 50 + // different roles to `user:alice@example.com`, and not to any other + // principal, then you can add another 1,450 principals to the `bindings` in + // the `Policy`. + repeated Binding bindings = 4; + + // Specifies cloud audit logging configuration for this policy. + repeated AuditConfig audit_configs = 6; + + // `etag` is used for optimistic concurrency control as a way to help + // prevent simultaneous updates of a policy from overwriting each other. + // It is strongly suggested that systems make use of the `etag` in the + // read-modify-write cycle to perform policy updates in order to avoid race + // conditions: An `etag` is returned in the response to `getIamPolicy`, and + // systems are expected to put that etag in the request to `setIamPolicy` to + // ensure that their change will be applied to the same version of the policy. + // + // **Important:** If you use IAM Conditions, you must include the `etag` field + // whenever you call `setIamPolicy`. If you omit this field, then IAM allows + // you to overwrite a version `3` policy with a version `1` policy, and all of + // the conditions in the version `3` policy are lost. + bytes etag = 3; +} + +// Associates `members`, or principals, with a `role`. +message Binding { + // Role that is assigned to the list of `members`, or principals. + // For example, `roles/viewer`, `roles/editor`, or `roles/owner`. + string role = 1; + + // Specifies the principals requesting access for a Google Cloud resource. + // `members` can have the following values: + // + // * `allUsers`: A special identifier that represents anyone who is + // on the internet; with or without a Google account. + // + // * `allAuthenticatedUsers`: A special identifier that represents anyone + // who is authenticated with a Google account or a service account. + // + // * `user:{emailid}`: An email address that represents a specific Google + // account. For example, `alice@example.com` . + // + // + // * `serviceAccount:{emailid}`: An email address that represents a service + // account. For example, `my-other-app@appspot.gserviceaccount.com`. + // + // * `group:{emailid}`: An email address that represents a Google group. + // For example, `admins@example.com`. + // + // * `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique + // identifier) representing a user that has been recently deleted. For + // example, `alice@example.com?uid=123456789012345678901`. If the user is + // recovered, this value reverts to `user:{emailid}` and the recovered user + // retains the role in the binding. + // + // * `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus + // unique identifier) representing a service account that has been recently + // deleted. For example, + // `my-other-app@appspot.gserviceaccount.com?uid=123456789012345678901`. + // If the service account is undeleted, this value reverts to + // `serviceAccount:{emailid}` and the undeleted service account retains the + // role in the binding. + // + // * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique + // identifier) representing a Google group that has been recently + // deleted. For example, `admins@example.com?uid=123456789012345678901`. If + // the group is recovered, this value reverts to `group:{emailid}` and the + // recovered group retains the role in the binding. + // + // + // * `domain:{domain}`: The G Suite domain (primary) that represents all the + // users of that domain. For example, `google.com` or `example.com`. + // + // + repeated string members = 2; + + // The condition that is associated with this binding. + // + // If the condition evaluates to `true`, then this binding applies to the + // current request. + // + // If the condition evaluates to `false`, then this binding does not apply to + // the current request. However, a different role binding might grant the same + // role to one or more of the principals in this binding. + // + // To learn which resources support conditions in their IAM policies, see the + // [IAM + // documentation](https://cloud.google.com/iam/help/conditions/resource-policies). + google.type.Expr condition = 3; +} + +// Specifies the audit configuration for a service. +// The configuration determines which permission types are logged, and what +// identities, if any, are exempted from logging. +// An AuditConfig must have one or more AuditLogConfigs. +// +// If there are AuditConfigs for both `allServices` and a specific service, +// the union of the two AuditConfigs is used for that service: the log_types +// specified in each AuditConfig are enabled, and the exempted_members in each +// AuditLogConfig are exempted. +// +// Example Policy with multiple AuditConfigs: +// +// { +// "audit_configs": [ +// { +// "service": "allServices", +// "audit_log_configs": [ +// { +// "log_type": "DATA_READ", +// "exempted_members": [ +// "user:jose@example.com" +// ] +// }, +// { +// "log_type": "DATA_WRITE" +// }, +// { +// "log_type": "ADMIN_READ" +// } +// ] +// }, +// { +// "service": "sampleservice.googleapis.com", +// "audit_log_configs": [ +// { +// "log_type": "DATA_READ" +// }, +// { +// "log_type": "DATA_WRITE", +// "exempted_members": [ +// "user:aliya@example.com" +// ] +// } +// ] +// } +// ] +// } +// +// For sampleservice, this policy enables DATA_READ, DATA_WRITE and ADMIN_READ +// logging. It also exempts `jose@example.com` from DATA_READ logging, and +// `aliya@example.com` from DATA_WRITE logging. +message AuditConfig { + // Specifies a service that will be enabled for audit logging. + // For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. + // `allServices` is a special value that covers all services. + string service = 1; + + // The configuration for logging of each type of permission. + repeated AuditLogConfig audit_log_configs = 3; +} + +// Provides the configuration for logging a type of permissions. +// Example: +// +// { +// "audit_log_configs": [ +// { +// "log_type": "DATA_READ", +// "exempted_members": [ +// "user:jose@example.com" +// ] +// }, +// { +// "log_type": "DATA_WRITE" +// } +// ] +// } +// +// This enables 'DATA_READ' and 'DATA_WRITE' logging, while exempting +// jose@example.com from DATA_READ logging. +message AuditLogConfig { + // The list of valid permission types for which logging can be configured. + // Admin writes are always logged, and are not configurable. + enum LogType { + // Default case. Should never be this. + LOG_TYPE_UNSPECIFIED = 0; + + // Admin reads. Example: CloudIAM getIamPolicy + ADMIN_READ = 1; + + // Data writes. Example: CloudSQL Users create + DATA_WRITE = 2; + + // Data reads. Example: CloudSQL Users list + DATA_READ = 3; + } + + // The log type that this config enables. + LogType log_type = 1; + + // Specifies the identities that do not cause logging for this type of + // permission. + // Follows the same format of + // [Binding.members][google.iam.v1.Binding.members]. + repeated string exempted_members = 2; +} + +// The difference delta between two policies. +message PolicyDelta { + // The delta for Bindings between two policies. + repeated BindingDelta binding_deltas = 1; + + // The delta for AuditConfigs between two policies. + repeated AuditConfigDelta audit_config_deltas = 2; +} + +// One delta entry for Binding. Each individual change (only one member in each +// entry) to a binding will be a separate entry. +message BindingDelta { + // The type of action performed on a Binding in a policy. + enum Action { + // Unspecified. + ACTION_UNSPECIFIED = 0; + + // Addition of a Binding. + ADD = 1; + + // Removal of a Binding. + REMOVE = 2; + } + + // The action that was performed on a Binding. + // Required + Action action = 1; + + // Role that is assigned to `members`. + // For example, `roles/viewer`, `roles/editor`, or `roles/owner`. + // Required + string role = 2; + + // A single identity requesting access for a Google Cloud resource. + // Follows the same format of Binding.members. + // Required + string member = 3; + + // The condition that is associated with this binding. + google.type.Expr condition = 4; +} + +// One delta entry for AuditConfig. Each individual change (only one +// exempted_member in each entry) to a AuditConfig will be a separate entry. +message AuditConfigDelta { + // The type of action performed on an audit configuration in a policy. + enum Action { + // Unspecified. + ACTION_UNSPECIFIED = 0; + + // Addition of an audit configuration. + ADD = 1; + + // Removal of an audit configuration. + REMOVE = 2; + } + + // The action that was performed on an audit configuration in a policy. + // Required + Action action = 1; + + // Specifies a service that was configured for Cloud Audit Logging. + // For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. + // `allServices` is a special value that covers all services. + // Required + string service = 2; + + // A single identity that is exempted from "data access" audit + // logging for the `service` specified above. + // Follows the same format of Binding.members. + string exempted_member = 3; + + // Specifies the log_type that was be enabled. ADMIN_ACTIVITY is always + // enabled, and cannot be configured. + // Required + string log_type = 4; +} diff --git a/node_modules/google-gax/build/protos/google/logging/type/http_request.proto b/node_modules/google-gax/build/protos/google/logging/type/http_request.proto new file mode 100644 index 0000000..425a09d --- /dev/null +++ b/node_modules/google-gax/build/protos/google/logging/type/http_request.proto @@ -0,0 +1,95 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.logging.type; + +import "google/protobuf/duration.proto"; + +option csharp_namespace = "Google.Cloud.Logging.Type"; +option go_package = "google.golang.org/genproto/googleapis/logging/type;ltype"; +option java_multiple_files = true; +option java_outer_classname = "HttpRequestProto"; +option java_package = "com.google.logging.type"; +option php_namespace = "Google\\Cloud\\Logging\\Type"; +option ruby_package = "Google::Cloud::Logging::Type"; + +// A common proto for logging HTTP requests. Only contains semantics +// defined by the HTTP specification. Product-specific logging +// information MUST be defined in a separate message. +message HttpRequest { + // The request method. Examples: `"GET"`, `"HEAD"`, `"PUT"`, `"POST"`. + string request_method = 1; + + // The scheme (http, https), the host name, the path and the query + // portion of the URL that was requested. + // Example: `"http://example.com/some/info?color=red"`. + string request_url = 2; + + // The size of the HTTP request message in bytes, including the request + // headers and the request body. + int64 request_size = 3; + + // The response code indicating the status of response. + // Examples: 200, 404. + int32 status = 4; + + // The size of the HTTP response message sent back to the client, in bytes, + // including the response headers and the response body. + int64 response_size = 5; + + // The user agent sent by the client. Example: + // `"Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; Q312461; .NET + // CLR 1.0.3705)"`. + string user_agent = 6; + + // The IP address (IPv4 or IPv6) of the client that issued the HTTP + // request. This field can include port information. Examples: + // `"192.168.1.1"`, `"10.0.0.1:80"`, `"FE80::0202:B3FF:FE1E:8329"`. + string remote_ip = 7; + + // The IP address (IPv4 or IPv6) of the origin server that the request was + // sent to. This field can include port information. Examples: + // `"192.168.1.1"`, `"10.0.0.1:80"`, `"FE80::0202:B3FF:FE1E:8329"`. + string server_ip = 13; + + // The referer URL of the request, as defined in + // [HTTP/1.1 Header Field + // Definitions](https://datatracker.ietf.org/doc/html/rfc2616#section-14.36). + string referer = 8; + + // The request processing latency on the server, from the time the request was + // received until the response was sent. + google.protobuf.Duration latency = 14; + + // Whether or not a cache lookup was attempted. + bool cache_lookup = 11; + + // Whether or not an entity was served from cache + // (with or without validation). + bool cache_hit = 9; + + // Whether or not the response was validated with the origin server before + // being served from cache. This field is only meaningful if `cache_hit` is + // True. + bool cache_validated_with_origin_server = 10; + + // The number of HTTP response bytes inserted into cache. Set only when a + // cache fill was attempted. + int64 cache_fill_bytes = 12; + + // Protocol used for the request. Examples: "HTTP/1.1", "HTTP/2", "websocket" + string protocol = 15; +} diff --git a/node_modules/google-gax/build/protos/google/logging/type/log_severity.proto b/node_modules/google-gax/build/protos/google/logging/type/log_severity.proto new file mode 100644 index 0000000..6740125 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/logging/type/log_severity.proto @@ -0,0 +1,71 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.logging.type; + +option csharp_namespace = "Google.Cloud.Logging.Type"; +option go_package = "google.golang.org/genproto/googleapis/logging/type;ltype"; +option java_multiple_files = true; +option java_outer_classname = "LogSeverityProto"; +option java_package = "com.google.logging.type"; +option objc_class_prefix = "GLOG"; +option php_namespace = "Google\\Cloud\\Logging\\Type"; +option ruby_package = "Google::Cloud::Logging::Type"; + +// The severity of the event described in a log entry, expressed as one of the +// standard severity levels listed below. For your reference, the levels are +// assigned the listed numeric values. The effect of using numeric values other +// than those listed is undefined. +// +// You can filter for log entries by severity. For example, the following +// filter expression will match log entries with severities `INFO`, `NOTICE`, +// and `WARNING`: +// +// severity > DEBUG AND severity <= WARNING +// +// If you are writing log entries, you should map other severity encodings to +// one of these standard levels. For example, you might map all of Java's FINE, +// FINER, and FINEST levels to `LogSeverity.DEBUG`. You can preserve the +// original severity level in the log entry payload if you wish. +enum LogSeverity { + // (0) The log entry has no assigned severity level. + DEFAULT = 0; + + // (100) Debug or trace information. + DEBUG = 100; + + // (200) Routine information, such as ongoing status or performance. + INFO = 200; + + // (300) Normal but significant events, such as start up, shut down, or + // a configuration change. + NOTICE = 300; + + // (400) Warning events might cause problems. + WARNING = 400; + + // (500) Error events are likely to cause problems. + ERROR = 500; + + // (600) Critical events cause more severe problems or outages. + CRITICAL = 600; + + // (700) A person must take an action immediately. + ALERT = 700; + + // (800) One or more systems are unusable. + EMERGENCY = 800; +} diff --git a/node_modules/google-gax/build/protos/google/longrunning/operations.proto b/node_modules/google-gax/build/protos/google/longrunning/operations.proto new file mode 100644 index 0000000..c8fda20 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/longrunning/operations.proto @@ -0,0 +1,247 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.longrunning; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/protobuf/any.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/empty.proto"; +import "google/rpc/status.proto"; +import "google/protobuf/descriptor.proto"; + +option cc_enable_arenas = true; +option csharp_namespace = "Google.LongRunning"; +option go_package = "cloud.google.com/go/longrunning/autogen/longrunningpb;longrunningpb"; +option java_multiple_files = true; +option java_outer_classname = "OperationsProto"; +option java_package = "com.google.longrunning"; +option php_namespace = "Google\\LongRunning"; + +extend google.protobuf.MethodOptions { + // Additional information regarding long-running operations. + // In particular, this specifies the types that are returned from + // long-running operations. + // + // Required for methods that return `google.longrunning.Operation`; invalid + // otherwise. + google.longrunning.OperationInfo operation_info = 1049; +} + +// Manages long-running operations with an API service. +// +// When an API method normally takes long time to complete, it can be designed +// to return [Operation][google.longrunning.Operation] to the client, and the client can use this +// interface to receive the real response asynchronously by polling the +// operation resource, or pass the operation resource to another API (such as +// Google Cloud Pub/Sub API) to receive the response. Any API service that +// returns long-running operations should implement the `Operations` interface +// so developers can have a consistent client experience. +service Operations { + option (google.api.default_host) = "longrunning.googleapis.com"; + + // Lists operations that match the specified filter in the request. If the + // server doesn't support this method, it returns `UNIMPLEMENTED`. + // + // NOTE: the `name` binding allows API services to override the binding + // to use different resource name schemes, such as `users/*/operations`. To + // override the binding, API services can add a binding such as + // `"/v1/{name=users/*}/operations"` to their service configuration. + // For backwards compatibility, the default name includes the operations + // collection id, however overriding users must ensure the name binding + // is the parent resource, without the operations collection id. + rpc ListOperations(ListOperationsRequest) returns (ListOperationsResponse) { + option (google.api.http) = { + get: "/v1/{name=operations}" + }; + option (google.api.method_signature) = "name,filter"; + } + + // Gets the latest state of a long-running operation. Clients can use this + // method to poll the operation result at intervals as recommended by the API + // service. + rpc GetOperation(GetOperationRequest) returns (Operation) { + option (google.api.http) = { + get: "/v1/{name=operations/**}" + }; + option (google.api.method_signature) = "name"; + } + + // Deletes a long-running operation. This method indicates that the client is + // no longer interested in the operation result. It does not cancel the + // operation. If the server doesn't support this method, it returns + // `google.rpc.Code.UNIMPLEMENTED`. + rpc DeleteOperation(DeleteOperationRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=operations/**}" + }; + option (google.api.method_signature) = "name"; + } + + // Starts asynchronous cancellation on a long-running operation. The server + // makes a best effort to cancel the operation, but success is not + // guaranteed. If the server doesn't support this method, it returns + // `google.rpc.Code.UNIMPLEMENTED`. Clients can use + // [Operations.GetOperation][google.longrunning.Operations.GetOperation] or + // other methods to check whether the cancellation succeeded or whether the + // operation completed despite cancellation. On successful cancellation, + // the operation is not deleted; instead, it becomes an operation with + // an [Operation.error][google.longrunning.Operation.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1, + // corresponding to `Code.CANCELLED`. + rpc CancelOperation(CancelOperationRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + post: "/v1/{name=operations/**}:cancel" + body: "*" + }; + option (google.api.method_signature) = "name"; + } + + // Waits until the specified long-running operation is done or reaches at most + // a specified timeout, returning the latest state. If the operation is + // already done, the latest state is immediately returned. If the timeout + // specified is greater than the default HTTP/RPC timeout, the HTTP/RPC + // timeout is used. If the server does not support this method, it returns + // `google.rpc.Code.UNIMPLEMENTED`. + // Note that this method is on a best-effort basis. It may return the latest + // state before the specified timeout (including immediately), meaning even an + // immediate response is no guarantee that the operation is done. + rpc WaitOperation(WaitOperationRequest) returns (Operation) { + } +} + +// This resource represents a long-running operation that is the result of a +// network API call. +message Operation { + // The server-assigned name, which is only unique within the same service that + // originally returns it. If you use the default HTTP mapping, the + // `name` should be a resource name ending with `operations/{unique_id}`. + string name = 1; + + // Service-specific metadata associated with the operation. It typically + // contains progress information and common metadata such as create time. + // Some services might not provide such metadata. Any method that returns a + // long-running operation should document the metadata type, if any. + google.protobuf.Any metadata = 2; + + // If the value is `false`, it means the operation is still in progress. + // If `true`, the operation is completed, and either `error` or `response` is + // available. + bool done = 3; + + // The operation result, which can be either an `error` or a valid `response`. + // If `done` == `false`, neither `error` nor `response` is set. + // If `done` == `true`, exactly one of `error` or `response` is set. + oneof result { + // The error result of the operation in case of failure or cancellation. + google.rpc.Status error = 4; + + // The normal response of the operation in case of success. If the original + // method returns no data on success, such as `Delete`, the response is + // `google.protobuf.Empty`. If the original method is standard + // `Get`/`Create`/`Update`, the response should be the resource. For other + // methods, the response should have the type `XxxResponse`, where `Xxx` + // is the original method name. For example, if the original method name + // is `TakeSnapshot()`, the inferred response type is + // `TakeSnapshotResponse`. + google.protobuf.Any response = 5; + } +} + +// The request message for [Operations.GetOperation][google.longrunning.Operations.GetOperation]. +message GetOperationRequest { + // The name of the operation resource. + string name = 1; +} + +// The request message for [Operations.ListOperations][google.longrunning.Operations.ListOperations]. +message ListOperationsRequest { + // The name of the operation's parent resource. + string name = 4; + + // The standard list filter. + string filter = 1; + + // The standard list page size. + int32 page_size = 2; + + // The standard list page token. + string page_token = 3; +} + +// The response message for [Operations.ListOperations][google.longrunning.Operations.ListOperations]. +message ListOperationsResponse { + // A list of operations that matches the specified filter in the request. + repeated Operation operations = 1; + + // The standard List next-page token. + string next_page_token = 2; +} + +// The request message for [Operations.CancelOperation][google.longrunning.Operations.CancelOperation]. +message CancelOperationRequest { + // The name of the operation resource to be cancelled. + string name = 1; +} + +// The request message for [Operations.DeleteOperation][google.longrunning.Operations.DeleteOperation]. +message DeleteOperationRequest { + // The name of the operation resource to be deleted. + string name = 1; +} + +// The request message for [Operations.WaitOperation][google.longrunning.Operations.WaitOperation]. +message WaitOperationRequest { + // The name of the operation resource to wait on. + string name = 1; + + // The maximum duration to wait before timing out. If left blank, the wait + // will be at most the time permitted by the underlying HTTP/RPC protocol. + // If RPC context deadline is also specified, the shorter one will be used. + google.protobuf.Duration timeout = 2; +} + +// A message representing the message types used by a long-running operation. +// +// Example: +// +// rpc LongRunningRecognize(LongRunningRecognizeRequest) +// returns (google.longrunning.Operation) { +// option (google.longrunning.operation_info) = { +// response_type: "LongRunningRecognizeResponse" +// metadata_type: "LongRunningRecognizeMetadata" +// }; +// } +message OperationInfo { + // Required. The message name of the primary return type for this + // long-running operation. + // This type will be used to deserialize the LRO's response. + // + // If the response is in a different package from the rpc, a fully-qualified + // message name must be used (e.g. `google.protobuf.Struct`). + // + // Note: Altering this value constitutes a breaking change. + string response_type = 1; + + // Required. The message name of the metadata type for this long-running + // operation. + // + // If the response is in a different package from the rpc, a fully-qualified + // message name must be used (e.g. `google.protobuf.Struct`). + // + // Note: Altering this value constitutes a breaking change. + string metadata_type = 2; +} diff --git a/node_modules/google-gax/build/protos/google/monitoring/v3/alert.proto b/node_modules/google-gax/build/protos/google/monitoring/v3/alert.proto new file mode 100644 index 0000000..8dafe88 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/monitoring/v3/alert.proto @@ -0,0 +1,669 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.monitoring.v3; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/monitoring/v3/common.proto"; +import "google/monitoring/v3/mutation_record.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/wrappers.proto"; +import "google/rpc/status.proto"; + +option csharp_namespace = "Google.Cloud.Monitoring.V3"; +option go_package = "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb;monitoringpb"; +option java_multiple_files = true; +option java_outer_classname = "AlertProto"; +option java_package = "com.google.monitoring.v3"; +option php_namespace = "Google\\Cloud\\Monitoring\\V3"; +option ruby_package = "Google::Cloud::Monitoring::V3"; + +// A description of the conditions under which some aspect of your system is +// considered to be "unhealthy" and the ways to notify people or services about +// this state. For an overview of alert policies, see +// [Introduction to Alerting](https://cloud.google.com/monitoring/alerts/). +// +message AlertPolicy { + option (google.api.resource) = { + type: "monitoring.googleapis.com/AlertPolicy" + pattern: "projects/{project}/alertPolicies/{alert_policy}" + pattern: "organizations/{organization}/alertPolicies/{alert_policy}" + pattern: "folders/{folder}/alertPolicies/{alert_policy}" + pattern: "*" + }; + + // A content string and a MIME type that describes the content string's + // format. + message Documentation { + // The body of the documentation, interpreted according to `mime_type`. + // The content may not exceed 8,192 Unicode characters and may not exceed + // more than 10,240 bytes when encoded in UTF-8 format, whichever is + // smaller. This text can be [templatized by using + // variables](https://cloud.google.com/monitoring/alerts/doc-variables). + string content = 1; + + // The format of the `content` field. Presently, only the value + // `"text/markdown"` is supported. See + // [Markdown](https://en.wikipedia.org/wiki/Markdown) for more information. + string mime_type = 2; + + // Optional. The subject line of the notification. The subject line may not + // exceed 10,240 bytes. In notifications generated by this policy, the + // contents of the subject line after variable expansion will be truncated + // to 255 bytes or shorter at the latest UTF-8 character boundary. The + // 255-byte limit is recommended by [this + // thread](https://stackoverflow.com/questions/1592291/what-is-the-email-subject-length-limit). + // It is both the limit imposed by some third-party ticketing products and + // it is common to define textual fields in databases as VARCHAR(255). + // + // The contents of the subject line can be [templatized by using + // variables](https://cloud.google.com/monitoring/alerts/doc-variables). + // If this field is missing or empty, a default subject line will be + // generated. + string subject = 3 [(google.api.field_behavior) = OPTIONAL]; + } + + // A condition is a true/false test that determines when an alerting policy + // should open an incident. If a condition evaluates to true, it signifies + // that something is wrong. + message Condition { + option (google.api.resource) = { + type: "monitoring.googleapis.com/AlertPolicyCondition" + pattern: "projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}" + pattern: "organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}" + pattern: "folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}" + pattern: "*" + }; + + // Specifies how many time series must fail a predicate to trigger a + // condition. If not specified, then a `{count: 1}` trigger is used. + message Trigger { + // A type of trigger. + oneof type { + // The absolute number of time series that must fail + // the predicate for the condition to be triggered. + int32 count = 1; + + // The percentage of time series that must fail the + // predicate for the condition to be triggered. + double percent = 2; + } + } + + // A condition control that determines how metric-threshold conditions + // are evaluated when data stops arriving. + // This control doesn't affect metric-absence policies. + enum EvaluationMissingData { + // An unspecified evaluation missing data option. Equivalent to + // EVALUATION_MISSING_DATA_NO_OP. + EVALUATION_MISSING_DATA_UNSPECIFIED = 0; + + // If there is no data to evaluate the condition, then evaluate the + // condition as false. + EVALUATION_MISSING_DATA_INACTIVE = 1; + + // If there is no data to evaluate the condition, then evaluate the + // condition as true. + EVALUATION_MISSING_DATA_ACTIVE = 2; + + // Do not evaluate the condition to any value if there is no data. + EVALUATION_MISSING_DATA_NO_OP = 3; + } + + // A condition type that compares a collection of time series + // against a threshold. + message MetricThreshold { + // Options used when forecasting the time series and testing + // the predicted value against the threshold. + message ForecastOptions { + // Required. The length of time into the future to forecast whether a + // time series will violate the threshold. If the predicted value is + // found to violate the threshold, and the violation is observed in all + // forecasts made for the configured `duration`, then the time series is + // considered to be failing. + // The forecast horizon can range from 1 hour to 60 hours. + google.protobuf.Duration forecast_horizon = 1 + [(google.api.field_behavior) = REQUIRED]; + } + + // Required. A + // [filter](https://cloud.google.com/monitoring/api/v3/filters) that + // identifies which time series should be compared with the threshold. + // + // The filter is similar to the one that is specified in the + // [`ListTimeSeries` + // request](https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list) + // (that call is useful to verify the time series that will be retrieved / + // processed). The filter must specify the metric type and the resource + // type. Optionally, it can specify resource labels and metric labels. + // This field must not exceed 2048 Unicode characters in length. + string filter = 2 [(google.api.field_behavior) = REQUIRED]; + + // Specifies the alignment of data points in individual time series as + // well as how to combine the retrieved time series together (such as + // when aggregating multiple streams on each resource to a single + // stream for each resource or when aggregating streams across all + // members of a group of resources). Multiple aggregations + // are applied in the order specified. + // + // This field is similar to the one in the [`ListTimeSeries` + // request](https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list). + // It is advisable to use the `ListTimeSeries` method when debugging this + // field. + repeated Aggregation aggregations = 8; + + // A [filter](https://cloud.google.com/monitoring/api/v3/filters) that + // identifies a time series that should be used as the denominator of a + // ratio that will be compared with the threshold. If a + // `denominator_filter` is specified, the time series specified by the + // `filter` field will be used as the numerator. + // + // The filter must specify the metric type and optionally may contain + // restrictions on resource type, resource labels, and metric labels. + // This field may not exceed 2048 Unicode characters in length. + string denominator_filter = 9; + + // Specifies the alignment of data points in individual time series + // selected by `denominatorFilter` as + // well as how to combine the retrieved time series together (such as + // when aggregating multiple streams on each resource to a single + // stream for each resource or when aggregating streams across all + // members of a group of resources). + // + // When computing ratios, the `aggregations` and + // `denominator_aggregations` fields must use the same alignment period + // and produce time series that have the same periodicity and labels. + repeated Aggregation denominator_aggregations = 10; + + // When this field is present, the `MetricThreshold` condition forecasts + // whether the time series is predicted to violate the threshold within + // the `forecast_horizon`. When this field is not set, the + // `MetricThreshold` tests the current value of the timeseries against the + // threshold. + ForecastOptions forecast_options = 12; + + // The comparison to apply between the time series (indicated by `filter` + // and `aggregation`) and the threshold (indicated by `threshold_value`). + // The comparison is applied on each time series, with the time series + // on the left-hand side and the threshold on the right-hand side. + // + // Only `COMPARISON_LT` and `COMPARISON_GT` are supported currently. + ComparisonType comparison = 4; + + // A value against which to compare the time series. + double threshold_value = 5; + + // The amount of time that a time series must violate the + // threshold to be considered failing. Currently, only values + // that are a multiple of a minute--e.g., 0, 60, 120, or 300 + // seconds--are supported. If an invalid value is given, an + // error will be returned. When choosing a duration, it is useful to + // keep in mind the frequency of the underlying time series data + // (which may also be affected by any alignments specified in the + // `aggregations` field); a good duration is long enough so that a single + // outlier does not generate spurious alerts, but short enough that + // unhealthy states are detected and alerted on quickly. + google.protobuf.Duration duration = 6; + + // The number/percent of time series for which the comparison must hold + // in order for the condition to trigger. If unspecified, then the + // condition will trigger if the comparison is true for any of the + // time series that have been identified by `filter` and `aggregations`, + // or by the ratio, if `denominator_filter` and `denominator_aggregations` + // are specified. + Trigger trigger = 7; + + // A condition control that determines how metric-threshold conditions + // are evaluated when data stops arriving. + EvaluationMissingData evaluation_missing_data = 11; + } + + // A condition type that checks that monitored resources + // are reporting data. The configuration defines a metric and + // a set of monitored resources. The predicate is considered in violation + // when a time series for the specified metric of a monitored + // resource does not include any data in the specified `duration`. + message MetricAbsence { + // Required. A + // [filter](https://cloud.google.com/monitoring/api/v3/filters) that + // identifies which time series should be compared with the threshold. + // + // The filter is similar to the one that is specified in the + // [`ListTimeSeries` + // request](https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list) + // (that call is useful to verify the time series that will be retrieved / + // processed). The filter must specify the metric type and the resource + // type. Optionally, it can specify resource labels and metric labels. + // This field must not exceed 2048 Unicode characters in length. + string filter = 1 [(google.api.field_behavior) = REQUIRED]; + + // Specifies the alignment of data points in individual time series as + // well as how to combine the retrieved time series together (such as + // when aggregating multiple streams on each resource to a single + // stream for each resource or when aggregating streams across all + // members of a group of resources). Multiple aggregations + // are applied in the order specified. + // + // This field is similar to the one in the [`ListTimeSeries` + // request](https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list). + // It is advisable to use the `ListTimeSeries` method when debugging this + // field. + repeated Aggregation aggregations = 5; + + // The amount of time that a time series must fail to report new + // data to be considered failing. The minimum value of this field + // is 120 seconds. Larger values that are a multiple of a + // minute--for example, 240 or 300 seconds--are supported. + // If an invalid value is given, an + // error will be returned. The `Duration.nanos` field is + // ignored. + google.protobuf.Duration duration = 2; + + // The number/percent of time series for which the comparison must hold + // in order for the condition to trigger. If unspecified, then the + // condition will trigger if the comparison is true for any of the + // time series that have been identified by `filter` and `aggregations`. + Trigger trigger = 3; + } + + // A condition type that checks whether a log message in the [scoping + // project](https://cloud.google.com/monitoring/api/v3#project_name) + // satisfies the given filter. Logs from other projects in the metrics + // scope are not evaluated. + message LogMatch { + // Required. A logs-based filter. See [Advanced Logs + // Queries](https://cloud.google.com/logging/docs/view/advanced-queries) + // for how this filter should be constructed. + string filter = 1 [(google.api.field_behavior) = REQUIRED]; + + // Optional. A map from a label key to an extractor expression, which is + // used to extract the value for this label key. Each entry in this map is + // a specification for how data should be extracted from log entries that + // match `filter`. Each combination of extracted values is treated as a + // separate rule for the purposes of triggering notifications. Label keys + // and corresponding values can be used in notifications generated by this + // condition. + // + // Please see [the documentation on logs-based metric + // `valueExtractor`s](https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics#LogMetric.FIELDS.value_extractor) + // for syntax and examples. + map label_extractors = 2; + } + + // A condition type that allows alert policies to be defined using + // [Monitoring Query Language](https://cloud.google.com/monitoring/mql). + message MonitoringQueryLanguageCondition { + // [Monitoring Query Language](https://cloud.google.com/monitoring/mql) + // query that outputs a boolean stream. + string query = 1; + + // The amount of time that a time series must violate the + // threshold to be considered failing. Currently, only values + // that are a multiple of a minute--e.g., 0, 60, 120, or 300 + // seconds--are supported. If an invalid value is given, an + // error will be returned. When choosing a duration, it is useful to + // keep in mind the frequency of the underlying time series data + // (which may also be affected by any alignments specified in the + // `aggregations` field); a good duration is long enough so that a single + // outlier does not generate spurious alerts, but short enough that + // unhealthy states are detected and alerted on quickly. + google.protobuf.Duration duration = 2; + + // The number/percent of time series for which the comparison must hold + // in order for the condition to trigger. If unspecified, then the + // condition will trigger if the comparison is true for any of the + // time series that have been identified by `filter` and `aggregations`, + // or by the ratio, if `denominator_filter` and `denominator_aggregations` + // are specified. + Trigger trigger = 3; + + // A condition control that determines how metric-threshold conditions + // are evaluated when data stops arriving. + EvaluationMissingData evaluation_missing_data = 4; + } + + // A condition type that allows alert policies to be defined using + // [Prometheus Query Language + // (PromQL)](https://prometheus.io/docs/prometheus/latest/querying/basics/). + // + // The PrometheusQueryLanguageCondition message contains information + // from a Prometheus alerting rule and its associated rule group. + // + // A Prometheus alerting rule is described + // [here](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/). + // The semantics of a Prometheus alerting rule is described + // [here](https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/#rule). + // + // A Prometheus rule group is described + // [here](https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/). + // The semantics of a Prometheus rule group is described + // [here](https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/#rule_group). + // + // Because Cloud Alerting has no representation of a Prometheus rule + // group resource, we must embed the information of the parent rule + // group inside each of the conditions that refer to it. We must also + // update the contents of all Prometheus alerts in case the information + // of their rule group changes. + // + // The PrometheusQueryLanguageCondition protocol buffer combines the + // information of the corresponding rule group and alerting rule. + // The structure of the PrometheusQueryLanguageCondition protocol buffer + // does NOT mimic the structure of the Prometheus rule group and alerting + // rule YAML declarations. The PrometheusQueryLanguageCondition protocol + // buffer may change in the future to support future rule group and/or + // alerting rule features. There are no new such features at the present + // time (2023-06-26). + message PrometheusQueryLanguageCondition { + // Required. The PromQL expression to evaluate. Every evaluation cycle + // this expression is evaluated at the current time, and all resultant + // time series become pending/firing alerts. This field must not be empty. + string query = 1 [(google.api.field_behavior) = REQUIRED]; + + // Optional. Alerts are considered firing once their PromQL expression was + // evaluated to be "true" for this long. + // Alerts whose PromQL expression was not evaluated to be "true" for + // long enough are considered pending. + // Must be a non-negative duration or missing. + // This field is optional. Its default value is zero. + google.protobuf.Duration duration = 2 + [(google.api.field_behavior) = OPTIONAL]; + + // Optional. How often this rule should be evaluated. + // Must be a positive multiple of 30 seconds or missing. + // This field is optional. Its default value is 30 seconds. + // If this PrometheusQueryLanguageCondition was generated from a + // Prometheus alerting rule, then this value should be taken from the + // enclosing rule group. + google.protobuf.Duration evaluation_interval = 3 + [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Labels to add to or overwrite in the PromQL query result. + // Label names [must be + // valid](https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels). + // Label values can be [templatized by using + // variables](https://cloud.google.com/monitoring/alerts/doc-variables). + // The only available variable names are the names of the labels in the + // PromQL result, including "__name__" and "value". "labels" may be empty. + map labels = 4 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The rule group name of this alert in the corresponding + // Prometheus configuration file. + // + // Some external tools may require this field to be populated correctly + // in order to refer to the original Prometheus configuration file. + // The rule group name and the alert name are necessary to update the + // relevant AlertPolicies in case the definition of the rule group changes + // in the future. + // + // This field is optional. If this field is not empty, then it must + // contain a valid UTF-8 string. + // This field may not exceed 2048 Unicode characters in length. + string rule_group = 5 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The alerting rule name of this alert in the corresponding + // Prometheus configuration file. + // + // Some external tools may require this field to be populated correctly + // in order to refer to the original Prometheus configuration file. + // The rule group name and the alert name are necessary to update the + // relevant AlertPolicies in case the definition of the rule group changes + // in the future. + // + // This field is optional. If this field is not empty, then it must be a + // [valid Prometheus label + // name](https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels). + // This field may not exceed 2048 Unicode characters in length. + string alert_rule = 6 [(google.api.field_behavior) = OPTIONAL]; + } + + // Required if the condition exists. The unique resource name for this + // condition. Its format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[POLICY_ID]/conditions/[CONDITION_ID] + // + // `[CONDITION_ID]` is assigned by Cloud Monitoring when the + // condition is created as part of a new or updated alerting policy. + // + // When calling the + // [alertPolicies.create][google.monitoring.v3.AlertPolicyService.CreateAlertPolicy] + // method, do not include the `name` field in the conditions of the + // requested alerting policy. Cloud Monitoring creates the + // condition identifiers and includes them in the new policy. + // + // When calling the + // [alertPolicies.update][google.monitoring.v3.AlertPolicyService.UpdateAlertPolicy] + // method to update a policy, including a condition `name` causes the + // existing condition to be updated. Conditions without names are added to + // the updated policy. Existing conditions are deleted if they are not + // updated. + // + // Best practice is to preserve `[CONDITION_ID]` if you make only small + // changes, such as those to condition thresholds, durations, or trigger + // values. Otherwise, treat the change as a new condition and let the + // existing condition be deleted. + string name = 12; + + // A short name or phrase used to identify the condition in dashboards, + // notifications, and incidents. To avoid confusion, don't use the same + // display name for multiple conditions in the same policy. + string display_name = 6; + + // Only one of the following condition types will be specified. + oneof condition { + // A condition that compares a time series against a threshold. + MetricThreshold condition_threshold = 1; + + // A condition that checks that a time series continues to + // receive new data points. + MetricAbsence condition_absent = 2; + + // A condition that checks for log messages matching given constraints. If + // set, no other conditions can be present. + LogMatch condition_matched_log = 20; + + // A condition that uses the Monitoring Query Language to define + // alerts. + MonitoringQueryLanguageCondition condition_monitoring_query_language = 19; + + // A condition that uses the Prometheus query language to define alerts. + PrometheusQueryLanguageCondition condition_prometheus_query_language = 21; + } + } + + // Operators for combining conditions. + enum ConditionCombinerType { + // An unspecified combiner. + COMBINE_UNSPECIFIED = 0; + + // Combine conditions using the logical `AND` operator. An + // incident is created only if all the conditions are met + // simultaneously. This combiner is satisfied if all conditions are + // met, even if they are met on completely different resources. + AND = 1; + + // Combine conditions using the logical `OR` operator. An incident + // is created if any of the listed conditions is met. + OR = 2; + + // Combine conditions using logical `AND` operator, but unlike the regular + // `AND` option, an incident is created only if all conditions are met + // simultaneously on at least one resource. + AND_WITH_MATCHING_RESOURCE = 3; + } + + // Control over how the notification channels in `notification_channels` + // are notified when this alert fires. + message AlertStrategy { + // Control over the rate of notifications sent to this alert policy's + // notification channels. + message NotificationRateLimit { + // Not more than one notification per `period`. + google.protobuf.Duration period = 1; + } + + // Control over how the notification channels in `notification_channels` + // are notified when this alert fires, on a per-channel basis. + message NotificationChannelStrategy { + // The full REST resource name for the notification channels that these + // settings apply to. Each of these correspond to the name field in one + // of the NotificationChannel objects referenced in the + // notification_channels field of this AlertPolicy. + // The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/notificationChannels/[CHANNEL_ID] + repeated string notification_channel_names = 1; + + // The frequency at which to send reminder notifications for open + // incidents. + google.protobuf.Duration renotify_interval = 2; + } + + // Required for alert policies with a `LogMatch` condition. + // + // This limit is not implemented for alert policies that are not log-based. + NotificationRateLimit notification_rate_limit = 1; + + // If an alert policy that was active has no data for this long, any open + // incidents will close + google.protobuf.Duration auto_close = 3; + + // Control how notifications will be sent out, on a per-channel basis. + repeated NotificationChannelStrategy notification_channel_strategy = 4; + } + + // An enumeration of possible severity level for an Alert Policy. + enum Severity { + // No severity is specified. This is the default value. + SEVERITY_UNSPECIFIED = 0; + + // This is the highest severity level. Use this if the problem could + // cause significant damage or downtime. + CRITICAL = 1; + + // This is the medium severity level. Use this if the problem could + // cause minor damage or downtime. + ERROR = 2; + + // This is the lowest severity level. Use this if the problem is not causing + // any damage or downtime, but could potentially lead to a problem in the + // future. + WARNING = 3; + } + + // Required if the policy exists. The resource name for this policy. The + // format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[ALERT_POLICY_ID] + // + // `[ALERT_POLICY_ID]` is assigned by Cloud Monitoring when the policy + // is created. When calling the + // [alertPolicies.create][google.monitoring.v3.AlertPolicyService.CreateAlertPolicy] + // method, do not include the `name` field in the alerting policy passed as + // part of the request. + string name = 1; + + // A short name or phrase used to identify the policy in dashboards, + // notifications, and incidents. To avoid confusion, don't use the same + // display name for multiple policies in the same project. The name is + // limited to 512 Unicode characters. + // + // The convention for the display_name of a PrometheusQueryLanguageCondition + // is "{rule group name}/{alert name}", where the {rule group name} and + // {alert name} should be taken from the corresponding Prometheus + // configuration file. This convention is not enforced. + // In any case the display_name is not a unique key of the AlertPolicy. + string display_name = 2; + + // Documentation that is included with notifications and incidents related to + // this policy. Best practice is for the documentation to include information + // to help responders understand, mitigate, escalate, and correct the + // underlying problems detected by the alerting policy. Notification channels + // that have limited capacity might not show this documentation. + Documentation documentation = 13; + + // User-supplied key/value data to be used for organizing and + // identifying the `AlertPolicy` objects. + // + // The field can contain up to 64 entries. Each key and value is limited to + // 63 Unicode characters or 128 bytes, whichever is smaller. Labels and + // values can contain only lowercase letters, numerals, underscores, and + // dashes. Keys must begin with a letter. + // + // Note that Prometheus {alert name} is a + // [valid Prometheus label + // names](https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels), + // whereas Prometheus {rule group} is an unrestricted UTF-8 string. + // This means that they cannot be stored as-is in user labels, because + // they may contain characters that are not allowed in user-label values. + map user_labels = 16; + + // A list of conditions for the policy. The conditions are combined by AND or + // OR according to the `combiner` field. If the combined conditions evaluate + // to true, then an incident is created. A policy can have from one to six + // conditions. + // If `condition_time_series_query_language` is present, it must be the only + // `condition`. + // If `condition_monitoring_query_language` is present, it must be the only + // `condition`. + repeated Condition conditions = 12; + + // How to combine the results of multiple conditions to determine if an + // incident should be opened. + // If `condition_time_series_query_language` is present, this must be + // `COMBINE_UNSPECIFIED`. + ConditionCombinerType combiner = 6; + + // Whether or not the policy is enabled. On write, the default interpretation + // if unset is that the policy is enabled. On read, clients should not make + // any assumption about the state if it has not been populated. The + // field should always be populated on List and Get operations, unless + // a field projection has been specified that strips it out. + google.protobuf.BoolValue enabled = 17; + + // Read-only description of how the alert policy is invalid. This field is + // only set when the alert policy is invalid. An invalid alert policy will not + // generate incidents. + google.rpc.Status validity = 18; + + // Identifies the notification channels to which notifications should be sent + // when incidents are opened or closed or when new violations occur on + // an already opened incident. Each element of this array corresponds to + // the `name` field in each of the + // [`NotificationChannel`][google.monitoring.v3.NotificationChannel] + // objects that are returned from the [`ListNotificationChannels`] + // [google.monitoring.v3.NotificationChannelService.ListNotificationChannels] + // method. The format of the entries in this field is: + // + // projects/[PROJECT_ID_OR_NUMBER]/notificationChannels/[CHANNEL_ID] + repeated string notification_channels = 14; + + // A read-only record of the creation of the alerting policy. If provided + // in a call to create or update, this field will be ignored. + MutationRecord creation_record = 10; + + // A read-only record of the most recent change to the alerting policy. If + // provided in a call to create or update, this field will be ignored. + MutationRecord mutation_record = 11; + + // Control over how this alert policy's notification channels are notified. + AlertStrategy alert_strategy = 21; + + // Optional. The severity of an alert policy indicates how important incidents + // generated by that policy are. The severity level will be displayed on the + // Incident detail page and in notifications. + Severity severity = 22 [(google.api.field_behavior) = OPTIONAL]; +} diff --git a/node_modules/google-gax/build/protos/google/monitoring/v3/alert_service.proto b/node_modules/google-gax/build/protos/google/monitoring/v3/alert_service.proto new file mode 100644 index 0000000..d93ad0b --- /dev/null +++ b/node_modules/google-gax/build/protos/google/monitoring/v3/alert_service.proto @@ -0,0 +1,256 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.monitoring.v3; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/monitoring/v3/alert.proto"; +import "google/protobuf/empty.proto"; +import "google/protobuf/field_mask.proto"; + +option csharp_namespace = "Google.Cloud.Monitoring.V3"; +option go_package = "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb;monitoringpb"; +option java_multiple_files = true; +option java_outer_classname = "AlertServiceProto"; +option java_package = "com.google.monitoring.v3"; +option php_namespace = "Google\\Cloud\\Monitoring\\V3"; +option ruby_package = "Google::Cloud::Monitoring::V3"; + +// The AlertPolicyService API is used to manage (list, create, delete, +// edit) alert policies in Cloud Monitoring. An alerting policy is +// a description of the conditions under which some aspect of your +// system is considered to be "unhealthy" and the ways to notify +// people or services about this state. In addition to using this API, alert +// policies can also be managed through +// [Cloud Monitoring](https://cloud.google.com/monitoring/docs/), +// which can be reached by clicking the "Monitoring" tab in +// [Cloud console](https://console.cloud.google.com/). +service AlertPolicyService { + option (google.api.default_host) = "monitoring.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/monitoring," + "https://www.googleapis.com/auth/monitoring.read"; + + // Lists the existing alerting policies for the workspace. + rpc ListAlertPolicies(ListAlertPoliciesRequest) + returns (ListAlertPoliciesResponse) { + option (google.api.http) = { + get: "/v3/{name=projects/*}/alertPolicies" + }; + option (google.api.method_signature) = "name"; + } + + // Gets a single alerting policy. + rpc GetAlertPolicy(GetAlertPolicyRequest) returns (AlertPolicy) { + option (google.api.http) = { + get: "/v3/{name=projects/*/alertPolicies/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Creates a new alerting policy. + // + // Design your application to single-thread API calls that modify the state of + // alerting policies in a single project. This includes calls to + // CreateAlertPolicy, DeleteAlertPolicy and UpdateAlertPolicy. + rpc CreateAlertPolicy(CreateAlertPolicyRequest) returns (AlertPolicy) { + option (google.api.http) = { + post: "/v3/{name=projects/*}/alertPolicies" + body: "alert_policy" + }; + option (google.api.method_signature) = "name,alert_policy"; + } + + // Deletes an alerting policy. + // + // Design your application to single-thread API calls that modify the state of + // alerting policies in a single project. This includes calls to + // CreateAlertPolicy, DeleteAlertPolicy and UpdateAlertPolicy. + rpc DeleteAlertPolicy(DeleteAlertPolicyRequest) + returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v3/{name=projects/*/alertPolicies/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Updates an alerting policy. You can either replace the entire policy with + // a new one or replace only certain fields in the current alerting policy by + // specifying the fields to be updated via `updateMask`. Returns the + // updated alerting policy. + // + // Design your application to single-thread API calls that modify the state of + // alerting policies in a single project. This includes calls to + // CreateAlertPolicy, DeleteAlertPolicy and UpdateAlertPolicy. + rpc UpdateAlertPolicy(UpdateAlertPolicyRequest) returns (AlertPolicy) { + option (google.api.http) = { + patch: "/v3/{alert_policy.name=projects/*/alertPolicies/*}" + body: "alert_policy" + }; + option (google.api.method_signature) = "update_mask,alert_policy"; + } +} + +// The protocol for the `CreateAlertPolicy` request. +message CreateAlertPolicyRequest { + // Required. The + // [project](https://cloud.google.com/monitoring/api/v3#project_name) in which + // to create the alerting policy. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER] + // + // Note that this field names the parent container in which the alerting + // policy will be written, not the name of the created policy. |name| must be + // a host project of a Metrics Scope, otherwise INVALID_ARGUMENT error will + // return. The alerting policy that is returned will have a name that contains + // a normalized representation of this name as a prefix but adds a suffix of + // the form `/alertPolicies/[ALERT_POLICY_ID]`, identifying the policy in the + // container. + string name = 3 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "monitoring.googleapis.com/AlertPolicy" + } + ]; + + // Required. The requested alerting policy. You should omit the `name` field + // in this policy. The name will be returned in the new policy, including a + // new `[ALERT_POLICY_ID]` value. + AlertPolicy alert_policy = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// The protocol for the `GetAlertPolicy` request. +message GetAlertPolicyRequest { + // Required. The alerting policy to retrieve. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[ALERT_POLICY_ID] + string name = 3 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/AlertPolicy" + } + ]; +} + +// The protocol for the `ListAlertPolicies` request. +message ListAlertPoliciesRequest { + // Required. The + // [project](https://cloud.google.com/monitoring/api/v3#project_name) whose + // alert policies are to be listed. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER] + // + // Note that this field names the parent container in which the alerting + // policies to be listed are stored. To retrieve a single alerting policy + // by name, use the + // [GetAlertPolicy][google.monitoring.v3.AlertPolicyService.GetAlertPolicy] + // operation, instead. + string name = 4 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "monitoring.googleapis.com/AlertPolicy" + } + ]; + + // If provided, this field specifies the criteria that must be met by + // alert policies to be included in the response. + // + // For more details, see [sorting and + // filtering](https://cloud.google.com/monitoring/api/v3/sorting-and-filtering). + string filter = 5; + + // A comma-separated list of fields by which to sort the result. Supports + // the same set of field references as the `filter` field. Entries can be + // prefixed with a minus sign to sort by the field in descending order. + // + // For more details, see [sorting and + // filtering](https://cloud.google.com/monitoring/api/v3/sorting-and-filtering). + string order_by = 6; + + // The maximum number of results to return in a single response. + int32 page_size = 2; + + // If this field is not empty then it must contain the `nextPageToken` value + // returned by a previous call to this method. Using this field causes the + // method to return more results from the previous method call. + string page_token = 3; +} + +// The protocol for the `ListAlertPolicies` response. +message ListAlertPoliciesResponse { + // The returned alert policies. + repeated AlertPolicy alert_policies = 3; + + // If there might be more results than were returned, then this field is set + // to a non-empty value. To see the additional results, + // use that value as `page_token` in the next call to this method. + string next_page_token = 2; + + // The total number of alert policies in all pages. This number is only an + // estimate, and may change in subsequent pages. https://aip.dev/158 + int32 total_size = 4; +} + +// The protocol for the `UpdateAlertPolicy` request. +message UpdateAlertPolicyRequest { + // Optional. A list of alerting policy field names. If this field is not + // empty, each listed field in the existing alerting policy is set to the + // value of the corresponding field in the supplied policy (`alert_policy`), + // or to the field's default value if the field is not in the supplied + // alerting policy. Fields not listed retain their previous value. + // + // Examples of valid field masks include `display_name`, `documentation`, + // `documentation.content`, `documentation.mime_type`, `user_labels`, + // `user_label.nameofkey`, `enabled`, `conditions`, `combiner`, etc. + // + // If this field is empty, then the supplied alerting policy replaces the + // existing policy. It is the same as deleting the existing policy and + // adding the supplied policy, except for the following: + // + // + The new policy will have the same `[ALERT_POLICY_ID]` as the former + // policy. This gives you continuity with the former policy in your + // notifications and incidents. + // + Conditions in the new policy will keep their former `[CONDITION_ID]` if + // the supplied condition includes the `name` field with that + // `[CONDITION_ID]`. If the supplied condition omits the `name` field, + // then a new `[CONDITION_ID]` is created. + google.protobuf.FieldMask update_mask = 2; + + // Required. The updated alerting policy or the updated values for the + // fields listed in `update_mask`. + // If `update_mask` is not empty, any fields in this policy that are + // not in `update_mask` are ignored. + AlertPolicy alert_policy = 3 [(google.api.field_behavior) = REQUIRED]; +} + +// The protocol for the `DeleteAlertPolicy` request. +message DeleteAlertPolicyRequest { + // Required. The alerting policy to delete. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[ALERT_POLICY_ID] + // + // For more information, see [AlertPolicy][google.monitoring.v3.AlertPolicy]. + string name = 3 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/AlertPolicy" + } + ]; +} diff --git a/node_modules/google-gax/build/protos/google/monitoring/v3/common.proto b/node_modules/google-gax/build/protos/google/monitoring/v3/common.proto new file mode 100644 index 0000000..62a189b --- /dev/null +++ b/node_modules/google-gax/build/protos/google/monitoring/v3/common.proto @@ -0,0 +1,488 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.monitoring.v3; + +import "google/api/distribution.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Monitoring.V3"; +option go_package = "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb;monitoringpb"; +option java_multiple_files = true; +option java_outer_classname = "CommonProto"; +option java_package = "com.google.monitoring.v3"; +option php_namespace = "Google\\Cloud\\Monitoring\\V3"; +option ruby_package = "Google::Cloud::Monitoring::V3"; + +// A single strongly-typed value. +message TypedValue { + // The typed value field. + oneof value { + // A Boolean value: `true` or `false`. + bool bool_value = 1; + + // A 64-bit integer. Its range is approximately ±9.2x1018. + int64 int64_value = 2; + + // A 64-bit double-precision floating-point number. Its magnitude + // is approximately ±10±300 and it has 16 + // significant digits of precision. + double double_value = 3; + + // A variable-length string value. + string string_value = 4; + + // A distribution value. + google.api.Distribution distribution_value = 5; + } +} + +// A closed time interval. It extends from the start time to the end time, and includes both: `[startTime, endTime]`. Valid time intervals depend on the [`MetricKind`](https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.metricDescriptors#MetricKind) of the metric value. The end time must not be earlier than the start time. When writing data points, the start time must not be more than 25 hours in the past and the end time must not be more than five minutes in the future. +// +// * For `GAUGE` metrics, the `startTime` value is technically optional; if +// no value is specified, the start time defaults to the value of the +// end time, and the interval represents a single point in time. If both +// start and end times are specified, they must be identical. Such an +// interval is valid only for `GAUGE` metrics, which are point-in-time +// measurements. The end time of a new interval must be at least a +// millisecond after the end time of the previous interval. +// +// * For `DELTA` metrics, the start time and end time must specify a +// non-zero interval, with subsequent points specifying contiguous and +// non-overlapping intervals. For `DELTA` metrics, the start time of +// the next interval must be at least a millisecond after the end time +// of the previous interval. +// +// * For `CUMULATIVE` metrics, the start time and end time must specify a +// non-zero interval, with subsequent points specifying the same +// start time and increasing end times, until an event resets the +// cumulative value to zero and sets a new start time for the following +// points. The new start time must be at least a millisecond after the +// end time of the previous interval. +// +// * The start time of a new interval must be at least a millisecond after the +// end time of the previous interval because intervals are closed. If the +// start time of a new interval is the same as the end time of the previous +// interval, then data written at the new start time could overwrite data +// written at the previous end time. +message TimeInterval { + // Required. The end of the time interval. + google.protobuf.Timestamp end_time = 2; + + // Optional. The beginning of the time interval. The default value + // for the start time is the end time. The start time must not be + // later than the end time. + google.protobuf.Timestamp start_time = 1; +} + +// Describes how to combine multiple time series to provide a different view of +// the data. Aggregation of time series is done in two steps. First, each time +// series in the set is _aligned_ to the same time interval boundaries, then the +// set of time series is optionally _reduced_ in number. +// +// Alignment consists of applying the `per_series_aligner` operation +// to each time series after its data has been divided into regular +// `alignment_period` time intervals. This process takes _all_ of the data +// points in an alignment period, applies a mathematical transformation such as +// averaging, minimum, maximum, delta, etc., and converts them into a single +// data point per period. +// +// Reduction is when the aligned and transformed time series can optionally be +// combined, reducing the number of time series through similar mathematical +// transformations. Reduction involves applying a `cross_series_reducer` to +// all the time series, optionally sorting the time series into subsets with +// `group_by_fields`, and applying the reducer to each subset. +// +// The raw time series data can contain a huge amount of information from +// multiple sources. Alignment and reduction transforms this mass of data into +// a more manageable and representative collection of data, for example "the +// 95% latency across the average of all tasks in a cluster". This +// representative data can be more easily graphed and comprehended, and the +// individual time series data is still available for later drilldown. For more +// details, see [Filtering and +// aggregation](https://cloud.google.com/monitoring/api/v3/aggregation). +message Aggregation { + // The `Aligner` specifies the operation that will be applied to the data + // points in each alignment period in a time series. Except for + // `ALIGN_NONE`, which specifies that no operation be applied, each alignment + // operation replaces the set of data values in each alignment period with + // a single value: the result of applying the operation to the data values. + // An aligned time series has a single data value at the end of each + // `alignment_period`. + // + // An alignment operation can change the data type of the values, too. For + // example, if you apply a counting operation to boolean values, the data + // `value_type` in the original time series is `BOOLEAN`, but the `value_type` + // in the aligned result is `INT64`. + enum Aligner { + // No alignment. Raw data is returned. Not valid if cross-series reduction + // is requested. The `value_type` of the result is the same as the + // `value_type` of the input. + ALIGN_NONE = 0; + + // Align and convert to + // [DELTA][google.api.MetricDescriptor.MetricKind.DELTA]. + // The output is `delta = y1 - y0`. + // + // This alignment is valid for + // [CUMULATIVE][google.api.MetricDescriptor.MetricKind.CUMULATIVE] and + // `DELTA` metrics. If the selected alignment period results in periods + // with no data, then the aligned value for such a period is created by + // interpolation. The `value_type` of the aligned result is the same as + // the `value_type` of the input. + ALIGN_DELTA = 1; + + // Align and convert to a rate. The result is computed as + // `rate = (y1 - y0)/(t1 - t0)`, or "delta over time". + // Think of this aligner as providing the slope of the line that passes + // through the value at the start and at the end of the `alignment_period`. + // + // This aligner is valid for `CUMULATIVE` + // and `DELTA` metrics with numeric values. If the selected alignment + // period results in periods with no data, then the aligned value for + // such a period is created by interpolation. The output is a `GAUGE` + // metric with `value_type` `DOUBLE`. + // + // If, by "rate", you mean "percentage change", see the + // `ALIGN_PERCENT_CHANGE` aligner instead. + ALIGN_RATE = 2; + + // Align by interpolating between adjacent points around the alignment + // period boundary. This aligner is valid for `GAUGE` metrics with + // numeric values. The `value_type` of the aligned result is the same as the + // `value_type` of the input. + ALIGN_INTERPOLATE = 3; + + // Align by moving the most recent data point before the end of the + // alignment period to the boundary at the end of the alignment + // period. This aligner is valid for `GAUGE` metrics. The `value_type` of + // the aligned result is the same as the `value_type` of the input. + ALIGN_NEXT_OLDER = 4; + + // Align the time series by returning the minimum value in each alignment + // period. This aligner is valid for `GAUGE` and `DELTA` metrics with + // numeric values. The `value_type` of the aligned result is the same as + // the `value_type` of the input. + ALIGN_MIN = 10; + + // Align the time series by returning the maximum value in each alignment + // period. This aligner is valid for `GAUGE` and `DELTA` metrics with + // numeric values. The `value_type` of the aligned result is the same as + // the `value_type` of the input. + ALIGN_MAX = 11; + + // Align the time series by returning the mean value in each alignment + // period. This aligner is valid for `GAUGE` and `DELTA` metrics with + // numeric values. The `value_type` of the aligned result is `DOUBLE`. + ALIGN_MEAN = 12; + + // Align the time series by returning the number of values in each alignment + // period. This aligner is valid for `GAUGE` and `DELTA` metrics with + // numeric or Boolean values. The `value_type` of the aligned result is + // `INT64`. + ALIGN_COUNT = 13; + + // Align the time series by returning the sum of the values in each + // alignment period. This aligner is valid for `GAUGE` and `DELTA` + // metrics with numeric and distribution values. The `value_type` of the + // aligned result is the same as the `value_type` of the input. + ALIGN_SUM = 14; + + // Align the time series by returning the standard deviation of the values + // in each alignment period. This aligner is valid for `GAUGE` and + // `DELTA` metrics with numeric values. The `value_type` of the output is + // `DOUBLE`. + ALIGN_STDDEV = 15; + + // Align the time series by returning the number of `True` values in + // each alignment period. This aligner is valid for `GAUGE` metrics with + // Boolean values. The `value_type` of the output is `INT64`. + ALIGN_COUNT_TRUE = 16; + + // Align the time series by returning the number of `False` values in + // each alignment period. This aligner is valid for `GAUGE` metrics with + // Boolean values. The `value_type` of the output is `INT64`. + ALIGN_COUNT_FALSE = 24; + + // Align the time series by returning the ratio of the number of `True` + // values to the total number of values in each alignment period. This + // aligner is valid for `GAUGE` metrics with Boolean values. The output + // value is in the range [0.0, 1.0] and has `value_type` `DOUBLE`. + ALIGN_FRACTION_TRUE = 17; + + // Align the time series by using [percentile + // aggregation](https://en.wikipedia.org/wiki/Percentile). The resulting + // data point in each alignment period is the 99th percentile of all data + // points in the period. This aligner is valid for `GAUGE` and `DELTA` + // metrics with distribution values. The output is a `GAUGE` metric with + // `value_type` `DOUBLE`. + ALIGN_PERCENTILE_99 = 18; + + // Align the time series by using [percentile + // aggregation](https://en.wikipedia.org/wiki/Percentile). The resulting + // data point in each alignment period is the 95th percentile of all data + // points in the period. This aligner is valid for `GAUGE` and `DELTA` + // metrics with distribution values. The output is a `GAUGE` metric with + // `value_type` `DOUBLE`. + ALIGN_PERCENTILE_95 = 19; + + // Align the time series by using [percentile + // aggregation](https://en.wikipedia.org/wiki/Percentile). The resulting + // data point in each alignment period is the 50th percentile of all data + // points in the period. This aligner is valid for `GAUGE` and `DELTA` + // metrics with distribution values. The output is a `GAUGE` metric with + // `value_type` `DOUBLE`. + ALIGN_PERCENTILE_50 = 20; + + // Align the time series by using [percentile + // aggregation](https://en.wikipedia.org/wiki/Percentile). The resulting + // data point in each alignment period is the 5th percentile of all data + // points in the period. This aligner is valid for `GAUGE` and `DELTA` + // metrics with distribution values. The output is a `GAUGE` metric with + // `value_type` `DOUBLE`. + ALIGN_PERCENTILE_05 = 21; + + // Align and convert to a percentage change. This aligner is valid for + // `GAUGE` and `DELTA` metrics with numeric values. This alignment returns + // `((current - previous)/previous) * 100`, where the value of `previous` is + // determined based on the `alignment_period`. + // + // If the values of `current` and `previous` are both 0, then the returned + // value is 0. If only `previous` is 0, the returned value is infinity. + // + // A 10-minute moving mean is computed at each point of the alignment period + // prior to the above calculation to smooth the metric and prevent false + // positives from very short-lived spikes. The moving mean is only + // applicable for data whose values are `>= 0`. Any values `< 0` are + // treated as a missing datapoint, and are ignored. While `DELTA` + // metrics are accepted by this alignment, special care should be taken that + // the values for the metric will always be positive. The output is a + // `GAUGE` metric with `value_type` `DOUBLE`. + ALIGN_PERCENT_CHANGE = 23; + } + + // A Reducer operation describes how to aggregate data points from multiple + // time series into a single time series, where the value of each data point + // in the resulting series is a function of all the already aligned values in + // the input time series. + enum Reducer { + // No cross-time series reduction. The output of the `Aligner` is + // returned. + REDUCE_NONE = 0; + + // Reduce by computing the mean value across time series for each + // alignment period. This reducer is valid for + // [DELTA][google.api.MetricDescriptor.MetricKind.DELTA] and + // [GAUGE][google.api.MetricDescriptor.MetricKind.GAUGE] metrics with + // numeric or distribution values. The `value_type` of the output is + // [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE]. + REDUCE_MEAN = 1; + + // Reduce by computing the minimum value across time series for each + // alignment period. This reducer is valid for `DELTA` and `GAUGE` metrics + // with numeric values. The `value_type` of the output is the same as the + // `value_type` of the input. + REDUCE_MIN = 2; + + // Reduce by computing the maximum value across time series for each + // alignment period. This reducer is valid for `DELTA` and `GAUGE` metrics + // with numeric values. The `value_type` of the output is the same as the + // `value_type` of the input. + REDUCE_MAX = 3; + + // Reduce by computing the sum across time series for each + // alignment period. This reducer is valid for `DELTA` and `GAUGE` metrics + // with numeric and distribution values. The `value_type` of the output is + // the same as the `value_type` of the input. + REDUCE_SUM = 4; + + // Reduce by computing the standard deviation across time series + // for each alignment period. This reducer is valid for `DELTA` and + // `GAUGE` metrics with numeric or distribution values. The `value_type` + // of the output is `DOUBLE`. + REDUCE_STDDEV = 5; + + // Reduce by computing the number of data points across time series + // for each alignment period. This reducer is valid for `DELTA` and + // `GAUGE` metrics of numeric, Boolean, distribution, and string + // `value_type`. The `value_type` of the output is `INT64`. + REDUCE_COUNT = 6; + + // Reduce by computing the number of `True`-valued data points across time + // series for each alignment period. This reducer is valid for `DELTA` and + // `GAUGE` metrics of Boolean `value_type`. The `value_type` of the output + // is `INT64`. + REDUCE_COUNT_TRUE = 7; + + // Reduce by computing the number of `False`-valued data points across time + // series for each alignment period. This reducer is valid for `DELTA` and + // `GAUGE` metrics of Boolean `value_type`. The `value_type` of the output + // is `INT64`. + REDUCE_COUNT_FALSE = 15; + + // Reduce by computing the ratio of the number of `True`-valued data points + // to the total number of data points for each alignment period. This + // reducer is valid for `DELTA` and `GAUGE` metrics of Boolean `value_type`. + // The output value is in the range [0.0, 1.0] and has `value_type` + // `DOUBLE`. + REDUCE_FRACTION_TRUE = 8; + + // Reduce by computing the [99th + // percentile](https://en.wikipedia.org/wiki/Percentile) of data points + // across time series for each alignment period. This reducer is valid for + // `GAUGE` and `DELTA` metrics of numeric and distribution type. The value + // of the output is `DOUBLE`. + REDUCE_PERCENTILE_99 = 9; + + // Reduce by computing the [95th + // percentile](https://en.wikipedia.org/wiki/Percentile) of data points + // across time series for each alignment period. This reducer is valid for + // `GAUGE` and `DELTA` metrics of numeric and distribution type. The value + // of the output is `DOUBLE`. + REDUCE_PERCENTILE_95 = 10; + + // Reduce by computing the [50th + // percentile](https://en.wikipedia.org/wiki/Percentile) of data points + // across time series for each alignment period. This reducer is valid for + // `GAUGE` and `DELTA` metrics of numeric and distribution type. The value + // of the output is `DOUBLE`. + REDUCE_PERCENTILE_50 = 11; + + // Reduce by computing the [5th + // percentile](https://en.wikipedia.org/wiki/Percentile) of data points + // across time series for each alignment period. This reducer is valid for + // `GAUGE` and `DELTA` metrics of numeric and distribution type. The value + // of the output is `DOUBLE`. + REDUCE_PERCENTILE_05 = 12; + } + + // The `alignment_period` specifies a time interval, in seconds, that is used + // to divide the data in all the + // [time series][google.monitoring.v3.TimeSeries] into consistent blocks of + // time. This will be done before the per-series aligner can be applied to + // the data. + // + // The value must be at least 60 seconds. If a per-series + // aligner other than `ALIGN_NONE` is specified, this field is required or an + // error is returned. If no per-series aligner is specified, or the aligner + // `ALIGN_NONE` is specified, then this field is ignored. + // + // The maximum value of the `alignment_period` is 104 weeks (2 years) for + // charts, and 90,000 seconds (25 hours) for alerting policies. + google.protobuf.Duration alignment_period = 1; + + // An `Aligner` describes how to bring the data points in a single + // time series into temporal alignment. Except for `ALIGN_NONE`, all + // alignments cause all the data points in an `alignment_period` to be + // mathematically grouped together, resulting in a single data point for + // each `alignment_period` with end timestamp at the end of the period. + // + // Not all alignment operations may be applied to all time series. The valid + // choices depend on the `metric_kind` and `value_type` of the original time + // series. Alignment can change the `metric_kind` or the `value_type` of + // the time series. + // + // Time series data must be aligned in order to perform cross-time + // series reduction. If `cross_series_reducer` is specified, then + // `per_series_aligner` must be specified and not equal to `ALIGN_NONE` + // and `alignment_period` must be specified; otherwise, an error is + // returned. + Aligner per_series_aligner = 2; + + // The reduction operation to be used to combine time series into a single + // time series, where the value of each data point in the resulting series is + // a function of all the already aligned values in the input time series. + // + // Not all reducer operations can be applied to all time series. The valid + // choices depend on the `metric_kind` and the `value_type` of the original + // time series. Reduction can yield a time series with a different + // `metric_kind` or `value_type` than the input time series. + // + // Time series data must first be aligned (see `per_series_aligner`) in order + // to perform cross-time series reduction. If `cross_series_reducer` is + // specified, then `per_series_aligner` must be specified, and must not be + // `ALIGN_NONE`. An `alignment_period` must also be specified; otherwise, an + // error is returned. + Reducer cross_series_reducer = 4; + + // The set of fields to preserve when `cross_series_reducer` is + // specified. The `group_by_fields` determine how the time series are + // partitioned into subsets prior to applying the aggregation + // operation. Each subset contains time series that have the same + // value for each of the grouping fields. Each individual time + // series is a member of exactly one subset. The + // `cross_series_reducer` is applied to each subset of time series. + // It is not possible to reduce across different resource types, so + // this field implicitly contains `resource.type`. Fields not + // specified in `group_by_fields` are aggregated away. If + // `group_by_fields` is not specified and all the time series have + // the same resource type, then the time series are aggregated into + // a single output time series. If `cross_series_reducer` is not + // defined, this field is ignored. + repeated string group_by_fields = 5; +} + +// Specifies an ordering relationship on two arguments, called `left` and +// `right`. +enum ComparisonType { + // No ordering relationship is specified. + COMPARISON_UNSPECIFIED = 0; + + // True if the left argument is greater than the right argument. + COMPARISON_GT = 1; + + // True if the left argument is greater than or equal to the right argument. + COMPARISON_GE = 2; + + // True if the left argument is less than the right argument. + COMPARISON_LT = 3; + + // True if the left argument is less than or equal to the right argument. + COMPARISON_LE = 4; + + // True if the left argument is equal to the right argument. + COMPARISON_EQ = 5; + + // True if the left argument is not equal to the right argument. + COMPARISON_NE = 6; +} + +// The tier of service for a Workspace. Please see the +// [service tiers +// documentation](https://cloud.google.com/monitoring/workspaces/tiers) for more +// details. +enum ServiceTier { + option deprecated = true; + + // An invalid sentinel value, used to indicate that a tier has not + // been provided explicitly. + SERVICE_TIER_UNSPECIFIED = 0; + + // The Stackdriver Basic tier, a free tier of service that provides basic + // features, a moderate allotment of logs, and access to built-in metrics. + // A number of features are not available in this tier. For more details, + // see [the service tiers + // documentation](https://cloud.google.com/monitoring/workspaces/tiers). + SERVICE_TIER_BASIC = 1; + + // The Stackdriver Premium tier, a higher, more expensive tier of service + // that provides access to all Stackdriver features, lets you use Stackdriver + // with AWS accounts, and has a larger allotments for logs and metrics. For + // more details, see [the service tiers + // documentation](https://cloud.google.com/monitoring/workspaces/tiers). + SERVICE_TIER_PREMIUM = 2; +} diff --git a/node_modules/google-gax/build/protos/google/monitoring/v3/dropped_labels.proto b/node_modules/google-gax/build/protos/google/monitoring/v3/dropped_labels.proto new file mode 100644 index 0000000..6c17669 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/monitoring/v3/dropped_labels.proto @@ -0,0 +1,46 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.monitoring.v3; + +option csharp_namespace = "Google.Cloud.Monitoring.V3"; +option go_package = "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb;monitoringpb"; +option java_multiple_files = true; +option java_outer_classname = "DroppedLabelsProto"; +option java_package = "com.google.monitoring.v3"; +option php_namespace = "Google\\Cloud\\Monitoring\\V3"; +option ruby_package = "Google::Cloud::Monitoring::V3"; + +// A set of (label, value) pairs that were removed from a Distribution +// time series during aggregation and then added as an attachment to a +// Distribution.Exemplar. +// +// The full label set for the exemplars is constructed by using the dropped +// pairs in combination with the label values that remain on the aggregated +// Distribution time series. The constructed full label set can be used to +// identify the specific entity, such as the instance or job, which might be +// contributing to a long-tail. However, with dropped labels, the storage +// requirements are reduced because only the aggregated distribution values for +// a large group of time series are stored. +// +// Note that there are no guarantees on ordering of the labels from +// exemplar-to-exemplar and from distribution-to-distribution in the same +// stream, and there may be duplicates. It is up to clients to resolve any +// ambiguities. +message DroppedLabels { + // Map from label to its value, for all labels dropped in any aggregation. + map label = 1; +} diff --git a/node_modules/google-gax/build/protos/google/monitoring/v3/group.proto b/node_modules/google-gax/build/protos/google/monitoring/v3/group.proto new file mode 100644 index 0000000..ee7a300 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/monitoring/v3/group.proto @@ -0,0 +1,90 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.monitoring.v3; + +import "google/api/resource.proto"; + +option csharp_namespace = "Google.Cloud.Monitoring.V3"; +option go_package = "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb;monitoringpb"; +option java_multiple_files = true; +option java_outer_classname = "GroupProto"; +option java_package = "com.google.monitoring.v3"; +option php_namespace = "Google\\Cloud\\Monitoring\\V3"; +option ruby_package = "Google::Cloud::Monitoring::V3"; + +// The description of a dynamic collection of monitored resources. Each group +// has a filter that is matched against monitored resources and their associated +// metadata. If a group's filter matches an available monitored resource, then +// that resource is a member of that group. Groups can contain any number of +// monitored resources, and each monitored resource can be a member of any +// number of groups. +// +// Groups can be nested in parent-child hierarchies. The `parentName` field +// identifies an optional parent for each group. If a group has a parent, then +// the only monitored resources available to be matched by the group's filter +// are the resources contained in the parent group. In other words, a group +// contains the monitored resources that match its filter and the filters of all +// the group's ancestors. A group without a parent can contain any monitored +// resource. +// +// For example, consider an infrastructure running a set of instances with two +// user-defined tags: `"environment"` and `"role"`. A parent group has a filter, +// `environment="production"`. A child of that parent group has a filter, +// `role="transcoder"`. The parent group contains all instances in the +// production environment, regardless of their roles. The child group contains +// instances that have the transcoder role *and* are in the production +// environment. +// +// The monitored resources contained in a group can change at any moment, +// depending on what resources exist and what filters are associated with the +// group and its ancestors. +message Group { + option (google.api.resource) = { + type: "monitoring.googleapis.com/Group" + pattern: "projects/{project}/groups/{group}" + pattern: "organizations/{organization}/groups/{group}" + pattern: "folders/{folder}/groups/{group}" + pattern: "*" + }; + + // Output only. The name of this group. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] + // + // When creating a group, this field is ignored and a new name is created + // consisting of the project specified in the call to `CreateGroup` + // and a unique `[GROUP_ID]` that is generated automatically. + string name = 1; + + // A user-assigned name for this group, used only for display purposes. + string display_name = 2; + + // The name of the group's parent, if it has one. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] + // + // For groups with no parent, `parent_name` is the empty string, `""`. + string parent_name = 3; + + // The filter used to determine which monitored resources belong to this + // group. + string filter = 5; + + // If true, the members of this group are considered to be a cluster. + // The system can perform additional analysis on groups that are clusters. + bool is_cluster = 6; +} diff --git a/node_modules/google-gax/build/protos/google/monitoring/v3/group_service.proto b/node_modules/google-gax/build/protos/google/monitoring/v3/group_service.proto new file mode 100644 index 0000000..ebe1bd9 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/monitoring/v3/group_service.proto @@ -0,0 +1,290 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.monitoring.v3; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/monitored_resource.proto"; +import "google/api/resource.proto"; +import "google/monitoring/v3/common.proto"; +import "google/monitoring/v3/group.proto"; +import "google/protobuf/empty.proto"; + +option csharp_namespace = "Google.Cloud.Monitoring.V3"; +option go_package = "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb;monitoringpb"; +option java_multiple_files = true; +option java_outer_classname = "GroupServiceProto"; +option java_package = "com.google.monitoring.v3"; +option php_namespace = "Google\\Cloud\\Monitoring\\V3"; +option ruby_package = "Google::Cloud::Monitoring::V3"; + +// The Group API lets you inspect and manage your +// [groups](#google.monitoring.v3.Group). +// +// A group is a named filter that is used to identify +// a collection of monitored resources. Groups are typically used to +// mirror the physical and/or logical topology of the environment. +// Because group membership is computed dynamically, monitored +// resources that are started in the future are automatically placed +// in matching groups. By using a group to name monitored resources in, +// for example, an alert policy, the target of that alert policy is +// updated automatically as monitored resources are added and removed +// from the infrastructure. +service GroupService { + option (google.api.default_host) = "monitoring.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/monitoring," + "https://www.googleapis.com/auth/monitoring.read"; + + // Lists the existing groups. + rpc ListGroups(ListGroupsRequest) returns (ListGroupsResponse) { + option (google.api.http) = { + get: "/v3/{name=projects/*}/groups" + }; + option (google.api.method_signature) = "name"; + } + + // Gets a single group. + rpc GetGroup(GetGroupRequest) returns (Group) { + option (google.api.http) = { + get: "/v3/{name=projects/*/groups/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Creates a new group. + rpc CreateGroup(CreateGroupRequest) returns (Group) { + option (google.api.http) = { + post: "/v3/{name=projects/*}/groups" + body: "group" + }; + option (google.api.method_signature) = "name,group"; + } + + // Updates an existing group. + // You can change any group attributes except `name`. + rpc UpdateGroup(UpdateGroupRequest) returns (Group) { + option (google.api.http) = { + put: "/v3/{group.name=projects/*/groups/*}" + body: "group" + }; + option (google.api.method_signature) = "group"; + } + + // Deletes an existing group. + rpc DeleteGroup(DeleteGroupRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v3/{name=projects/*/groups/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Lists the monitored resources that are members of a group. + rpc ListGroupMembers(ListGroupMembersRequest) returns (ListGroupMembersResponse) { + option (google.api.http) = { + get: "/v3/{name=projects/*/groups/*}/members" + }; + option (google.api.method_signature) = "name"; + } +} + +// The `ListGroup` request. +message ListGroupsRequest { + // Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) + // whose groups are to be listed. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER] + string name = 7 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "monitoring.googleapis.com/Group" + } + ]; + + // An optional filter consisting of a single group name. The filters limit + // the groups returned based on their parent-child relationship with the + // specified group. If no filter is specified, all groups are returned. + oneof filter { + // A group name. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] + // + // Returns groups whose `parent_name` field contains the group + // name. If no groups have this parent, the results are empty. + string children_of_group = 2 [(google.api.resource_reference) = { + type: "monitoring.googleapis.com/Group" + }]; + + // A group name. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] + // + // Returns groups that are ancestors of the specified group. + // The groups are returned in order, starting with the immediate parent and + // ending with the most distant ancestor. If the specified group has no + // immediate parent, the results are empty. + string ancestors_of_group = 3 [(google.api.resource_reference) = { + type: "monitoring.googleapis.com/Group" + }]; + + // A group name. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] + // + // Returns the descendants of the specified group. This is a superset of + // the results returned by the `children_of_group` filter, and includes + // children-of-children, and so forth. + string descendants_of_group = 4 [(google.api.resource_reference) = { + type: "monitoring.googleapis.com/Group" + }]; + } + + // A positive number that is the maximum number of results to return. + int32 page_size = 5; + + // If this field is not empty then it must contain the `next_page_token` value + // returned by a previous call to this method. Using this field causes the + // method to return additional results from the previous method call. + string page_token = 6; +} + +// The `ListGroups` response. +message ListGroupsResponse { + // The groups that match the specified filters. + repeated Group group = 1; + + // If there are more results than have been returned, then this field is set + // to a non-empty value. To see the additional results, + // use that value as `page_token` in the next call to this method. + string next_page_token = 2; +} + +// The `GetGroup` request. +message GetGroupRequest { + // Required. The group to retrieve. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] + string name = 3 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/Group" + } + ]; +} + +// The `CreateGroup` request. +message CreateGroupRequest { + // Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) in + // which to create the group. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER] + string name = 4 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "monitoring.googleapis.com/Group" + } + ]; + + // Required. A group definition. It is an error to define the `name` field because + // the system assigns the name. + Group group = 2 [(google.api.field_behavior) = REQUIRED]; + + // If true, validate this request but do not create the group. + bool validate_only = 3; +} + +// The `UpdateGroup` request. +message UpdateGroupRequest { + // Required. The new definition of the group. All fields of the existing group, + // excepting `name`, are replaced with the corresponding fields of this group. + Group group = 2 [(google.api.field_behavior) = REQUIRED]; + + // If true, validate this request but do not update the existing group. + bool validate_only = 3; +} + +// The `DeleteGroup` request. The default behavior is to be able to delete a +// single group without any descendants. +message DeleteGroupRequest { + // Required. The group to delete. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] + string name = 3 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/Group" + } + ]; + + // If this field is true, then the request means to delete a group with all + // its descendants. Otherwise, the request means to delete a group only when + // it has no descendants. The default value is false. + bool recursive = 4; +} + +// The `ListGroupMembers` request. +message ListGroupMembersRequest { + // Required. The group whose members are listed. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] + string name = 7 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/Group" + } + ]; + + // A positive number that is the maximum number of results to return. + int32 page_size = 3; + + // If this field is not empty then it must contain the `next_page_token` value + // returned by a previous call to this method. Using this field causes the + // method to return additional results from the previous method call. + string page_token = 4; + + // An optional [list + // filter](https://cloud.google.com/monitoring/api/learn_more#filtering) + // describing the members to be returned. The filter may reference the type, + // labels, and metadata of monitored resources that comprise the group. For + // example, to return only resources representing Compute Engine VM instances, + // use this filter: + // + // `resource.type = "gce_instance"` + string filter = 5; + + // An optional time interval for which results should be returned. Only + // members that were part of the group during the specified interval are + // included in the response. If no interval is provided then the group + // membership over the last minute is returned. + TimeInterval interval = 6; +} + +// The `ListGroupMembers` response. +message ListGroupMembersResponse { + // A set of monitored resources in the group. + repeated google.api.MonitoredResource members = 1; + + // If there are more results than have been returned, then this field is + // set to a non-empty value. To see the additional results, use that value as + // `page_token` in the next call to this method. + string next_page_token = 2; + + // The total number of elements matching this request. + int32 total_size = 3; +} diff --git a/node_modules/google-gax/build/protos/google/monitoring/v3/metric.proto b/node_modules/google-gax/build/protos/google/monitoring/v3/metric.proto new file mode 100644 index 0000000..ba55255 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/monitoring/v3/metric.proto @@ -0,0 +1,239 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.monitoring.v3; + +import "google/api/label.proto"; +import "google/api/metric.proto"; +import "google/api/monitored_resource.proto"; +import "google/monitoring/v3/common.proto"; + +option csharp_namespace = "Google.Cloud.Monitoring.V3"; +option go_package = "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb;monitoringpb"; +option java_multiple_files = true; +option java_outer_classname = "MetricProto"; +option java_package = "com.google.monitoring.v3"; +option php_namespace = "Google\\Cloud\\Monitoring\\V3"; +option ruby_package = "Google::Cloud::Monitoring::V3"; + +// A single data point in a time series. +message Point { + // The time interval to which the data point applies. For `GAUGE` metrics, + // the start time is optional, but if it is supplied, it must equal the + // end time. For `DELTA` metrics, the start + // and end time should specify a non-zero interval, with subsequent points + // specifying contiguous and non-overlapping intervals. For `CUMULATIVE` + // metrics, the start and end time should specify a non-zero interval, with + // subsequent points specifying the same start time and increasing end times, + // until an event resets the cumulative value to zero and sets a new start + // time for the following points. + TimeInterval interval = 1; + + // The value of the data point. + TypedValue value = 2; +} + +// A collection of data points that describes the time-varying values +// of a metric. A time series is identified by a combination of a +// fully-specified monitored resource and a fully-specified metric. +// This type is used for both listing and creating time series. +message TimeSeries { + // The associated metric. A fully-specified metric used to identify the time + // series. + google.api.Metric metric = 1; + + // The associated monitored resource. Custom metrics can use only certain + // monitored resource types in their time series data. For more information, + // see [Monitored resources for custom + // metrics](https://cloud.google.com/monitoring/custom-metrics/creating-metrics#custom-metric-resources). + google.api.MonitoredResource resource = 2; + + // Output only. The associated monitored resource metadata. When reading a + // time series, this field will include metadata labels that are explicitly + // named in the reduction. When creating a time series, this field is ignored. + google.api.MonitoredResourceMetadata metadata = 7; + + // The metric kind of the time series. When listing time series, this metric + // kind might be different from the metric kind of the associated metric if + // this time series is an alignment or reduction of other time series. + // + // When creating a time series, this field is optional. If present, it must be + // the same as the metric kind of the associated metric. If the associated + // metric's descriptor must be auto-created, then this field specifies the + // metric kind of the new descriptor and must be either `GAUGE` (the default) + // or `CUMULATIVE`. + google.api.MetricDescriptor.MetricKind metric_kind = 3; + + // The value type of the time series. When listing time series, this value + // type might be different from the value type of the associated metric if + // this time series is an alignment or reduction of other time series. + // + // When creating a time series, this field is optional. If present, it must be + // the same as the type of the data in the `points` field. + google.api.MetricDescriptor.ValueType value_type = 4; + + // The data points of this time series. When listing time series, points are + // returned in reverse time order. + // + // When creating a time series, this field must contain exactly one point and + // the point's type must be the same as the value type of the associated + // metric. If the associated metric's descriptor must be auto-created, then + // the value type of the descriptor is determined by the point's type, which + // must be `BOOL`, `INT64`, `DOUBLE`, or `DISTRIBUTION`. + repeated Point points = 5; + + // The units in which the metric value is reported. It is only applicable + // if the `value_type` is `INT64`, `DOUBLE`, or `DISTRIBUTION`. The `unit` + // defines the representation of the stored metric values. + string unit = 8; +} + +// A descriptor for the labels and points in a time series. +message TimeSeriesDescriptor { + // A descriptor for the value columns in a data point. + message ValueDescriptor { + // The value key. + string key = 1; + + // The value type. + google.api.MetricDescriptor.ValueType value_type = 2; + + // The value stream kind. + google.api.MetricDescriptor.MetricKind metric_kind = 3; + + // The unit in which `time_series` point values are reported. `unit` + // follows the UCUM format for units as seen in + // https://unitsofmeasure.org/ucum.html. + // `unit` is only valid if `value_type` is INTEGER, DOUBLE, DISTRIBUTION. + string unit = 4; + } + + // Descriptors for the labels. + repeated google.api.LabelDescriptor label_descriptors = 1; + + // Descriptors for the point data value columns. + repeated ValueDescriptor point_descriptors = 5; +} + +// Represents the values of a time series associated with a +// TimeSeriesDescriptor. +message TimeSeriesData { + // A point's value columns and time interval. Each point has one or more + // point values corresponding to the entries in `point_descriptors` field in + // the TimeSeriesDescriptor associated with this object. + message PointData { + // The values that make up the point. + repeated TypedValue values = 1; + + // The time interval associated with the point. + TimeInterval time_interval = 2; + } + + // The values of the labels in the time series identifier, given in the same + // order as the `label_descriptors` field of the TimeSeriesDescriptor + // associated with this object. Each value must have a value of the type + // given in the corresponding entry of `label_descriptors`. + repeated LabelValue label_values = 1; + + // The points in the time series. + repeated PointData point_data = 2; +} + +// A label value. +message LabelValue { + // The label value can be a bool, int64, or string. + oneof value { + // A bool label value. + bool bool_value = 1; + + // An int64 label value. + int64 int64_value = 2; + + // A string label value. + string string_value = 3; + } +} + +// An error associated with a query in the time series query language format. +message QueryError { + // The location of the time series query language text that this error applies + // to. + TextLocator locator = 1; + + // The error message. + string message = 2; +} + +// A locator for text. Indicates a particular part of the text of a request or +// of an object referenced in the request. +// +// For example, suppose the request field `text` contains: +// +// text: "The quick brown fox jumps over the lazy dog." +// +// Then the locator: +// +// source: "text" +// start_position { +// line: 1 +// column: 17 +// } +// end_position { +// line: 1 +// column: 19 +// } +// +// refers to the part of the text: "fox". +message TextLocator { + // The position of a byte within the text. + message Position { + // The line, starting with 1, where the byte is positioned. + int32 line = 1; + + // The column within the line, starting with 1, where the byte is + // positioned. This is a byte index even though the text is UTF-8. + int32 column = 2; + } + + // The source of the text. The source may be a field in the request, in which + // case its format is the format of the + // google.rpc.BadRequest.FieldViolation.field field in + // https://cloud.google.com/apis/design/errors#error_details. It may also be + // be a source other than the request field (e.g. a macro definition + // referenced in the text of the query), in which case this is the name of + // the source (e.g. the macro name). + string source = 1; + + // The position of the first byte within the text. + Position start_position = 2; + + // The position of the last byte within the text. + Position end_position = 3; + + // If `source`, `start_position`, and `end_position` describe a call on + // some object (e.g. a macro in the time series query language text) and a + // location is to be designated in that object's text, `nested_locator` + // identifies the location within that object. + TextLocator nested_locator = 4; + + // When `nested_locator` is set, this field gives the reason for the nesting. + // Usually, the reason is a macro invocation. In that case, the macro name + // (including the leading '@') signals the location of the macro call + // in the text and a macro argument name (including the leading '$') signals + // the location of the macro argument inside the macro body that got + // substituted away. + string nesting_reason = 5; +} diff --git a/node_modules/google-gax/build/protos/google/monitoring/v3/metric_service.proto b/node_modules/google-gax/build/protos/google/monitoring/v3/metric_service.proto new file mode 100644 index 0000000..edea2b5 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/monitoring/v3/metric_service.proto @@ -0,0 +1,522 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.monitoring.v3; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/metric.proto"; +import "google/api/monitored_resource.proto"; +import "google/api/resource.proto"; +import "google/monitoring/v3/common.proto"; +import "google/monitoring/v3/metric.proto"; +import "google/protobuf/empty.proto"; +import "google/rpc/status.proto"; + +option csharp_namespace = "Google.Cloud.Monitoring.V3"; +option go_package = "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb;monitoringpb"; +option java_multiple_files = true; +option java_outer_classname = "MetricServiceProto"; +option java_package = "com.google.monitoring.v3"; +option php_namespace = "Google\\Cloud\\Monitoring\\V3"; +option ruby_package = "Google::Cloud::Monitoring::V3"; +option (google.api.resource_definition) = { + type: "monitoring.googleapis.com/MetricDescriptor" + pattern: "projects/{project}/metricDescriptors/{metric_descriptor=**}" + pattern: "organizations/{organization}/metricDescriptors/{metric_descriptor=**}" + pattern: "folders/{folder}/metricDescriptors/{metric_descriptor=**}" + pattern: "*" + history: ORIGINALLY_SINGLE_PATTERN +}; +option (google.api.resource_definition) = { + type: "monitoring.googleapis.com/MonitoredResourceDescriptor" + pattern: "projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}" + pattern: "organizations/{organization}/monitoredResourceDescriptors/{monitored_resource_descriptor}" + pattern: "folders/{folder}/monitoredResourceDescriptors/{monitored_resource_descriptor}" + pattern: "*" + history: ORIGINALLY_SINGLE_PATTERN +}; +option (google.api.resource_definition) = { + type: "monitoring.googleapis.com/Workspace" + pattern: "projects/{project}" + pattern: "workspaces/{workspace}" +}; +option (google.api.resource_definition) = { + type: "monitoring.googleapis.com/TimeSeries" + pattern: "projects/{project}/timeSeries/{time_series}" + pattern: "organizations/{organization}/timeSeries/{time_series}" + pattern: "folders/{folder}/timeSeries/{time_series}" +}; + +// Manages metric descriptors, monitored resource descriptors, and +// time series data. +service MetricService { + option (google.api.default_host) = "monitoring.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/monitoring," + "https://www.googleapis.com/auth/monitoring.read," + "https://www.googleapis.com/auth/monitoring.write"; + + // Lists monitored resource descriptors that match a filter. This method does not require a Workspace. + rpc ListMonitoredResourceDescriptors(ListMonitoredResourceDescriptorsRequest) returns (ListMonitoredResourceDescriptorsResponse) { + option (google.api.http) = { + get: "/v3/{name=projects/*}/monitoredResourceDescriptors" + }; + option (google.api.method_signature) = "name"; + } + + // Gets a single monitored resource descriptor. This method does not require a Workspace. + rpc GetMonitoredResourceDescriptor(GetMonitoredResourceDescriptorRequest) returns (google.api.MonitoredResourceDescriptor) { + option (google.api.http) = { + get: "/v3/{name=projects/*/monitoredResourceDescriptors/**}" + }; + option (google.api.method_signature) = "name"; + } + + // Lists metric descriptors that match a filter. This method does not require a Workspace. + rpc ListMetricDescriptors(ListMetricDescriptorsRequest) returns (ListMetricDescriptorsResponse) { + option (google.api.http) = { + get: "/v3/{name=projects/*}/metricDescriptors" + }; + option (google.api.method_signature) = "name"; + } + + // Gets a single metric descriptor. This method does not require a Workspace. + rpc GetMetricDescriptor(GetMetricDescriptorRequest) returns (google.api.MetricDescriptor) { + option (google.api.http) = { + get: "/v3/{name=projects/*/metricDescriptors/**}" + }; + option (google.api.method_signature) = "name"; + } + + // Creates a new metric descriptor. + // The creation is executed asynchronously and callers may check the returned + // operation to track its progress. + // User-created metric descriptors define + // [custom metrics](https://cloud.google.com/monitoring/custom-metrics). + rpc CreateMetricDescriptor(CreateMetricDescriptorRequest) returns (google.api.MetricDescriptor) { + option (google.api.http) = { + post: "/v3/{name=projects/*}/metricDescriptors" + body: "metric_descriptor" + }; + option (google.api.method_signature) = "name,metric_descriptor"; + } + + // Deletes a metric descriptor. Only user-created + // [custom metrics](https://cloud.google.com/monitoring/custom-metrics) can be + // deleted. + rpc DeleteMetricDescriptor(DeleteMetricDescriptorRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v3/{name=projects/*/metricDescriptors/**}" + }; + option (google.api.method_signature) = "name"; + } + + // Lists time series that match a filter. This method does not require a Workspace. + rpc ListTimeSeries(ListTimeSeriesRequest) returns (ListTimeSeriesResponse) { + option (google.api.http) = { + get: "/v3/{name=projects/*}/timeSeries" + additional_bindings { + get: "/v3/{name=organizations/*}/timeSeries" + } + additional_bindings { + get: "/v3/{name=folders/*}/timeSeries" + } + }; + option (google.api.method_signature) = "name,filter,interval,view"; + } + + // Creates or adds data to one or more time series. + // The response is empty if all time series in the request were written. + // If any time series could not be written, a corresponding failure message is + // included in the error response. + rpc CreateTimeSeries(CreateTimeSeriesRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + post: "/v3/{name=projects/*}/timeSeries" + body: "*" + }; + option (google.api.method_signature) = "name,time_series"; + } + + // Creates or adds data to one or more service time series. A service time + // series is a time series for a metric from a Google Cloud service. The + // response is empty if all time series in the request were written. If any + // time series could not be written, a corresponding failure message is + // included in the error response. This endpoint rejects writes to + // user-defined metrics. + // This method is only for use by Google Cloud services. Use + // [projects.timeSeries.create][google.monitoring.v3.MetricService.CreateTimeSeries] + // instead. + rpc CreateServiceTimeSeries(CreateTimeSeriesRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + post: "/v3/{name=projects/*}/timeSeries:createService" + body: "*" + }; + option (google.api.method_signature) = "name,time_series"; + } +} + +// The `ListMonitoredResourceDescriptors` request. +message ListMonitoredResourceDescriptorsRequest { + // Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) on + // which to execute the request. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER] + string name = 5 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "monitoring.googleapis.com/MonitoredResourceDescriptor" + } + ]; + + // An optional [filter](https://cloud.google.com/monitoring/api/v3/filters) + // describing the descriptors to be returned. The filter can reference the + // descriptor's type and labels. For example, the following filter returns + // only Google Compute Engine descriptors that have an `id` label: + // + // resource.type = starts_with("gce_") AND resource.label:id + string filter = 2; + + // A positive number that is the maximum number of results to return. + int32 page_size = 3; + + // If this field is not empty then it must contain the `nextPageToken` value + // returned by a previous call to this method. Using this field causes the + // method to return additional results from the previous method call. + string page_token = 4; +} + +// The `ListMonitoredResourceDescriptors` response. +message ListMonitoredResourceDescriptorsResponse { + // The monitored resource descriptors that are available to this project + // and that match `filter`, if present. + repeated google.api.MonitoredResourceDescriptor resource_descriptors = 1; + + // If there are more results than have been returned, then this field is set + // to a non-empty value. To see the additional results, + // use that value as `page_token` in the next call to this method. + string next_page_token = 2; +} + +// The `GetMonitoredResourceDescriptor` request. +message GetMonitoredResourceDescriptorRequest { + // Required. The monitored resource descriptor to get. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/monitoredResourceDescriptors/[RESOURCE_TYPE] + // + // The `[RESOURCE_TYPE]` is a predefined type, such as + // `cloudsql_database`. + string name = 3 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/MonitoredResourceDescriptor" + } + ]; +} + +// The `ListMetricDescriptors` request. +message ListMetricDescriptorsRequest { + // Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) on + // which to execute the request. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER] + string name = 5 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "monitoring.googleapis.com/MetricDescriptor" + } + ]; + + // If this field is empty, all custom and + // system-defined metric descriptors are returned. + // Otherwise, the [filter](https://cloud.google.com/monitoring/api/v3/filters) + // specifies which metric descriptors are to be + // returned. For example, the following filter matches all + // [custom metrics](https://cloud.google.com/monitoring/custom-metrics): + // + // metric.type = starts_with("custom.googleapis.com/") + string filter = 2; + + // A positive number that is the maximum number of results to return. + int32 page_size = 3; + + // If this field is not empty then it must contain the `nextPageToken` value + // returned by a previous call to this method. Using this field causes the + // method to return additional results from the previous method call. + string page_token = 4; +} + +// The `ListMetricDescriptors` response. +message ListMetricDescriptorsResponse { + // The metric descriptors that are available to the project + // and that match the value of `filter`, if present. + repeated google.api.MetricDescriptor metric_descriptors = 1; + + // If there are more results than have been returned, then this field is set + // to a non-empty value. To see the additional results, + // use that value as `page_token` in the next call to this method. + string next_page_token = 2; +} + +// The `GetMetricDescriptor` request. +message GetMetricDescriptorRequest { + // Required. The metric descriptor on which to execute the request. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/metricDescriptors/[METRIC_ID] + // + // An example value of `[METRIC_ID]` is + // `"compute.googleapis.com/instance/disk/read_bytes_count"`. + string name = 3 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/MetricDescriptor" + } + ]; +} + +// The `CreateMetricDescriptor` request. +message CreateMetricDescriptorRequest { + // Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) on + // which to execute the request. The format is: + // 4 + // projects/[PROJECT_ID_OR_NUMBER] + string name = 3 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "monitoring.googleapis.com/MetricDescriptor" + } + ]; + + // Required. The new [custom metric](https://cloud.google.com/monitoring/custom-metrics) + // descriptor. + google.api.MetricDescriptor metric_descriptor = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// The `DeleteMetricDescriptor` request. +message DeleteMetricDescriptorRequest { + // Required. The metric descriptor on which to execute the request. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/metricDescriptors/[METRIC_ID] + // + // An example of `[METRIC_ID]` is: + // `"custom.googleapis.com/my_test_metric"`. + string name = 3 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/MetricDescriptor" + } + ]; +} + +// The `ListTimeSeries` request. +message ListTimeSeriesRequest { + // Controls which fields are returned by `ListTimeSeries`. + enum TimeSeriesView { + // Returns the identity of the metric(s), the time series, + // and the time series data. + FULL = 0; + + // Returns the identity of the metric and the time series resource, + // but not the time series data. + HEADERS = 1; + } + + // Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name), + // organization or folder on which to execute the request. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER] + // organizations/[ORGANIZATION_ID] + // folders/[FOLDER_ID] + string name = 10 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "monitoring.googleapis.com/TimeSeries" + } + ]; + + // Required. A [monitoring filter](https://cloud.google.com/monitoring/api/v3/filters) + // that specifies which time series should be returned. The filter must + // specify a single metric type, and can additionally specify metric labels + // and other information. For example: + // + // metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND + // metric.labels.instance_name = "my-instance-name" + string filter = 2 [(google.api.field_behavior) = REQUIRED]; + + // Required. The time interval for which results should be returned. Only time series + // that contain data points in the specified interval are included + // in the response. + TimeInterval interval = 4 [(google.api.field_behavior) = REQUIRED]; + + // Specifies the alignment of data points in individual time series as + // well as how to combine the retrieved time series across specified labels. + // + // By default (if no `aggregation` is explicitly specified), the raw time + // series data is returned. + Aggregation aggregation = 5; + + // Apply a second aggregation after `aggregation` is applied. May only be + // specified if `aggregation` is specified. + Aggregation secondary_aggregation = 11; + + // Unsupported: must be left blank. The points in each time series are + // currently returned in reverse time order (most recent to oldest). + string order_by = 6; + + // Required. Specifies which information is returned about the time series. + TimeSeriesView view = 7 [(google.api.field_behavior) = REQUIRED]; + + // A positive number that is the maximum number of results to return. If + // `page_size` is empty or more than 100,000 results, the effective + // `page_size` is 100,000 results. If `view` is set to `FULL`, this is the + // maximum number of `Points` returned. If `view` is set to `HEADERS`, this is + // the maximum number of `TimeSeries` returned. + int32 page_size = 8; + + // If this field is not empty then it must contain the `nextPageToken` value + // returned by a previous call to this method. Using this field causes the + // method to return additional results from the previous method call. + string page_token = 9; +} + +// The `ListTimeSeries` response. +message ListTimeSeriesResponse { + // One or more time series that match the filter included in the request. + repeated TimeSeries time_series = 1; + + // If there are more results than have been returned, then this field is set + // to a non-empty value. To see the additional results, + // use that value as `page_token` in the next call to this method. + string next_page_token = 2; + + // Query execution errors that may have caused the time series data returned + // to be incomplete. + repeated google.rpc.Status execution_errors = 3; + + // The unit in which all `time_series` point values are reported. `unit` + // follows the UCUM format for units as seen in + // https://unitsofmeasure.org/ucum.html. + // If different `time_series` have different units (for example, because they + // come from different metric types, or a unit is absent), then `unit` will be + // "{not_a_unit}". + string unit = 5; +} + +// The `CreateTimeSeries` request. +message CreateTimeSeriesRequest { + // Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) on + // which to execute the request. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER] + string name = 3 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "cloudresourcemanager.googleapis.com/Project" + } + ]; + + // Required. The new data to be added to a list of time series. + // Adds at most one data point to each of several time series. The new data + // point must be more recent than any other point in its time series. Each + // `TimeSeries` value must fully specify a unique time series by supplying + // all label values for the metric and the monitored resource. + // + // The maximum number of `TimeSeries` objects per `Create` request is 200. + repeated TimeSeries time_series = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// DEPRECATED. Used to hold per-time-series error status. +message CreateTimeSeriesError { + // DEPRECATED. Time series ID that resulted in the `status` error. + TimeSeries time_series = 1 [deprecated = true]; + + // DEPRECATED. The status of the requested write operation for `time_series`. + google.rpc.Status status = 2 [deprecated = true]; +} + +// Summary of the result of a failed request to write data to a time series. +message CreateTimeSeriesSummary { + // Detailed information about an error category. + message Error { + // The status of the requested write operation. + google.rpc.Status status = 1; + + // The number of points that couldn't be written because of `status`. + int32 point_count = 2; + } + + // The number of points in the request. + int32 total_point_count = 1; + + // The number of points that were successfully written. + int32 success_point_count = 2; + + // The number of points that failed to be written. Order is not guaranteed. + repeated Error errors = 3; +} + +// The `QueryTimeSeries` request. +message QueryTimeSeriesRequest { + // Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) on + // which to execute the request. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER] + string name = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The query in the [Monitoring Query + // Language](https://cloud.google.com/monitoring/mql/reference) format. + // The default time zone is in UTC. + string query = 7 [(google.api.field_behavior) = REQUIRED]; + + // A positive number that is the maximum number of time_series_data to return. + int32 page_size = 9; + + // If this field is not empty then it must contain the `nextPageToken` value + // returned by a previous call to this method. Using this field causes the + // method to return additional results from the previous method call. + string page_token = 10; +} + +// The `QueryTimeSeries` response. +message QueryTimeSeriesResponse { + // The descriptor for the time series data. + TimeSeriesDescriptor time_series_descriptor = 8; + + // The time series data. + repeated TimeSeriesData time_series_data = 9; + + // If there are more results than have been returned, then this field is set + // to a non-empty value. To see the additional results, use that value as + // `page_token` in the next call to this method. + string next_page_token = 10; + + // Query execution errors that may have caused the time series data returned + // to be incomplete. The available data will be available in the + // response. + repeated google.rpc.Status partial_errors = 11; +} + +// This is an error detail intended to be used with INVALID_ARGUMENT errors. +message QueryErrorList { + // Errors in parsing the time series query language text. The number of errors + // in the response may be limited. + repeated QueryError errors = 1; + + // A summary of all the errors. + string error_summary = 2; +} diff --git a/node_modules/google-gax/build/protos/google/monitoring/v3/mutation_record.proto b/node_modules/google-gax/build/protos/google/monitoring/v3/mutation_record.proto new file mode 100644 index 0000000..bfad65f --- /dev/null +++ b/node_modules/google-gax/build/protos/google/monitoring/v3/mutation_record.proto @@ -0,0 +1,36 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.monitoring.v3; + +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Monitoring.V3"; +option go_package = "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb;monitoringpb"; +option java_multiple_files = true; +option java_outer_classname = "MutationRecordProto"; +option java_package = "com.google.monitoring.v3"; +option php_namespace = "Google\\Cloud\\Monitoring\\V3"; +option ruby_package = "Google::Cloud::Monitoring::V3"; + +// Describes a change made to a configuration. +message MutationRecord { + // When the change occurred. + google.protobuf.Timestamp mutate_time = 1; + + // The email address of the user making the change. + string mutated_by = 2; +} diff --git a/node_modules/google-gax/build/protos/google/monitoring/v3/notification.proto b/node_modules/google-gax/build/protos/google/monitoring/v3/notification.proto new file mode 100644 index 0000000..67df55b --- /dev/null +++ b/node_modules/google-gax/build/protos/google/monitoring/v3/notification.proto @@ -0,0 +1,195 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.monitoring.v3; + +import "google/api/label.proto"; +import "google/api/launch_stage.proto"; +import "google/api/resource.proto"; +import "google/monitoring/v3/common.proto"; +import "google/monitoring/v3/mutation_record.proto"; +import "google/protobuf/wrappers.proto"; + +option csharp_namespace = "Google.Cloud.Monitoring.V3"; +option go_package = "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb;monitoringpb"; +option java_multiple_files = true; +option java_outer_classname = "NotificationProto"; +option java_package = "com.google.monitoring.v3"; +option php_namespace = "Google\\Cloud\\Monitoring\\V3"; +option ruby_package = "Google::Cloud::Monitoring::V3"; + +// A description of a notification channel. The descriptor includes +// the properties of the channel and the set of labels or fields that +// must be specified to configure channels of a given type. +message NotificationChannelDescriptor { + option (google.api.resource) = { + type: "monitoring.googleapis.com/NotificationChannelDescriptor" + pattern: "projects/{project}/notificationChannelDescriptors/{channel_descriptor}" + pattern: "organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}" + pattern: "folders/{folder}/notificationChannelDescriptors/{channel_descriptor}" + pattern: "*" + }; + + // The full REST resource name for this descriptor. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/notificationChannelDescriptors/[TYPE] + // + // In the above, `[TYPE]` is the value of the `type` field. + string name = 6; + + // The type of notification channel, such as "email" and "sms". To view the + // full list of channels, see + // [Channel + // descriptors](https://cloud.google.com/monitoring/alerts/using-channels-api#ncd). + // Notification channel types are globally unique. + string type = 1; + + // A human-readable name for the notification channel type. This + // form of the name is suitable for a user interface. + string display_name = 2; + + // A human-readable description of the notification channel + // type. The description may include a description of the properties + // of the channel and pointers to external documentation. + string description = 3; + + // The set of labels that must be defined to identify a particular + // channel of the corresponding type. Each label includes a + // description for how that field should be populated. + repeated google.api.LabelDescriptor labels = 4; + + // The tiers that support this notification channel; the project service tier + // must be one of the supported_tiers. + repeated ServiceTier supported_tiers = 5 [deprecated = true]; + + // The product launch stage for channels of this type. + google.api.LaunchStage launch_stage = 7; +} + +// A `NotificationChannel` is a medium through which an alert is +// delivered when a policy violation is detected. Examples of channels +// include email, SMS, and third-party messaging applications. Fields +// containing sensitive information like authentication tokens or +// contact info are only partially populated on retrieval. +message NotificationChannel { + option (google.api.resource) = { + type: "monitoring.googleapis.com/NotificationChannel" + pattern: "projects/{project}/notificationChannels/{notification_channel}" + pattern: "organizations/{organization}/notificationChannels/{notification_channel}" + pattern: "folders/{folder}/notificationChannels/{notification_channel}" + pattern: "*" + }; + + // Indicates whether the channel has been verified or not. It is illegal + // to specify this field in a + // [`CreateNotificationChannel`][google.monitoring.v3.NotificationChannelService.CreateNotificationChannel] + // or an + // [`UpdateNotificationChannel`][google.monitoring.v3.NotificationChannelService.UpdateNotificationChannel] + // operation. + enum VerificationStatus { + // Sentinel value used to indicate that the state is unknown, omitted, or + // is not applicable (as in the case of channels that neither support + // nor require verification in order to function). + VERIFICATION_STATUS_UNSPECIFIED = 0; + + // The channel has yet to be verified and requires verification to function. + // Note that this state also applies to the case where the verification + // process has been initiated by sending a verification code but where + // the verification code has not been submitted to complete the process. + UNVERIFIED = 1; + + // It has been proven that notifications can be received on this + // notification channel and that someone on the project has access + // to messages that are delivered to that channel. + VERIFIED = 2; + } + + // The type of the notification channel. This field matches the + // value of the + // [NotificationChannelDescriptor.type][google.monitoring.v3.NotificationChannelDescriptor.type] + // field. + string type = 1; + + // The full REST resource name for this channel. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/notificationChannels/[CHANNEL_ID] + // + // The `[CHANNEL_ID]` is automatically assigned by the server on creation. + string name = 6; + + // An optional human-readable name for this notification channel. It is + // recommended that you specify a non-empty and unique name in order to + // make it easier to identify the channels in your project, though this is + // not enforced. The display name is limited to 512 Unicode characters. + string display_name = 3; + + // An optional human-readable description of this notification channel. This + // description may provide additional details, beyond the display + // name, for the channel. This may not exceed 1024 Unicode characters. + string description = 4; + + // Configuration fields that define the channel and its behavior. The + // permissible and required labels are specified in the + // [NotificationChannelDescriptor.labels][google.monitoring.v3.NotificationChannelDescriptor.labels] + // of the `NotificationChannelDescriptor` corresponding to the `type` field. + map labels = 5; + + // User-supplied key/value data that does not need to conform to + // the corresponding `NotificationChannelDescriptor`'s schema, unlike + // the `labels` field. This field is intended to be used for organizing + // and identifying the `NotificationChannel` objects. + // + // The field can contain up to 64 entries. Each key and value is limited to + // 63 Unicode characters or 128 bytes, whichever is smaller. Labels and + // values can contain only lowercase letters, numerals, underscores, and + // dashes. Keys must begin with a letter. + map user_labels = 8; + + // Indicates whether this channel has been verified or not. On a + // [`ListNotificationChannels`][google.monitoring.v3.NotificationChannelService.ListNotificationChannels] + // or + // [`GetNotificationChannel`][google.monitoring.v3.NotificationChannelService.GetNotificationChannel] + // operation, this field is expected to be populated. + // + // If the value is `UNVERIFIED`, then it indicates that the channel is + // non-functioning (it both requires verification and lacks verification); + // otherwise, it is assumed that the channel works. + // + // If the channel is neither `VERIFIED` nor `UNVERIFIED`, it implies that + // the channel is of a type that does not require verification or that + // this specific channel has been exempted from verification because it was + // created prior to verification being required for channels of this type. + // + // This field cannot be modified using a standard + // [`UpdateNotificationChannel`][google.monitoring.v3.NotificationChannelService.UpdateNotificationChannel] + // operation. To change the value of this field, you must call + // [`VerifyNotificationChannel`][google.monitoring.v3.NotificationChannelService.VerifyNotificationChannel]. + VerificationStatus verification_status = 9; + + // Whether notifications are forwarded to the described channel. This makes + // it possible to disable delivery of notifications to a particular channel + // without removing the channel from all alerting policies that reference + // the channel. This is a more convenient approach when the change is + // temporary and you want to receive notifications from the same set + // of alerting policies on the channel at some point in the future. + google.protobuf.BoolValue enabled = 11; + + // Record of the creation of this channel. + MutationRecord creation_record = 12; + + // Records of the modification of this channel. + repeated MutationRecord mutation_records = 13; +} diff --git a/node_modules/google-gax/build/protos/google/monitoring/v3/notification_service.proto b/node_modules/google-gax/build/protos/google/monitoring/v3/notification_service.proto new file mode 100644 index 0000000..8b14dcf --- /dev/null +++ b/node_modules/google-gax/build/protos/google/monitoring/v3/notification_service.proto @@ -0,0 +1,448 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.monitoring.v3; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/monitoring/v3/notification.proto"; +import "google/protobuf/empty.proto"; +import "google/protobuf/field_mask.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Monitoring.V3"; +option go_package = "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb;monitoringpb"; +option java_multiple_files = true; +option java_outer_classname = "NotificationServiceProto"; +option java_package = "com.google.monitoring.v3"; +option php_namespace = "Google\\Cloud\\Monitoring\\V3"; +option ruby_package = "Google::Cloud::Monitoring::V3"; + +// The Notification Channel API provides access to configuration that +// controls how messages related to incidents are sent. +service NotificationChannelService { + option (google.api.default_host) = "monitoring.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/monitoring," + "https://www.googleapis.com/auth/monitoring.read"; + + // Lists the descriptors for supported channel types. The use of descriptors + // makes it possible for new channel types to be dynamically added. + rpc ListNotificationChannelDescriptors( + ListNotificationChannelDescriptorsRequest) + returns (ListNotificationChannelDescriptorsResponse) { + option (google.api.http) = { + get: "/v3/{name=projects/*}/notificationChannelDescriptors" + }; + option (google.api.method_signature) = "name"; + } + + // Gets a single channel descriptor. The descriptor indicates which fields + // are expected / permitted for a notification channel of the given type. + rpc GetNotificationChannelDescriptor(GetNotificationChannelDescriptorRequest) + returns (NotificationChannelDescriptor) { + option (google.api.http) = { + get: "/v3/{name=projects/*/notificationChannelDescriptors/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Lists the notification channels that have been created for the project. + // To list the types of notification channels that are supported, use + // the `ListNotificationChannelDescriptors` method. + rpc ListNotificationChannels(ListNotificationChannelsRequest) + returns (ListNotificationChannelsResponse) { + option (google.api.http) = { + get: "/v3/{name=projects/*}/notificationChannels" + }; + option (google.api.method_signature) = "name"; + } + + // Gets a single notification channel. The channel includes the relevant + // configuration details with which the channel was created. However, the + // response may truncate or omit passwords, API keys, or other private key + // matter and thus the response may not be 100% identical to the information + // that was supplied in the call to the create method. + rpc GetNotificationChannel(GetNotificationChannelRequest) + returns (NotificationChannel) { + option (google.api.http) = { + get: "/v3/{name=projects/*/notificationChannels/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Creates a new notification channel, representing a single notification + // endpoint such as an email address, SMS number, or PagerDuty service. + // + // Design your application to single-thread API calls that modify the state of + // notification channels in a single project. This includes calls to + // CreateNotificationChannel, DeleteNotificationChannel and + // UpdateNotificationChannel. + rpc CreateNotificationChannel(CreateNotificationChannelRequest) + returns (NotificationChannel) { + option (google.api.http) = { + post: "/v3/{name=projects/*}/notificationChannels" + body: "notification_channel" + }; + option (google.api.method_signature) = "name,notification_channel"; + } + + // Updates a notification channel. Fields not specified in the field mask + // remain unchanged. + // + // Design your application to single-thread API calls that modify the state of + // notification channels in a single project. This includes calls to + // CreateNotificationChannel, DeleteNotificationChannel and + // UpdateNotificationChannel. + rpc UpdateNotificationChannel(UpdateNotificationChannelRequest) + returns (NotificationChannel) { + option (google.api.http) = { + patch: "/v3/{notification_channel.name=projects/*/notificationChannels/*}" + body: "notification_channel" + }; + option (google.api.method_signature) = "update_mask,notification_channel"; + } + + // Deletes a notification channel. + // + // Design your application to single-thread API calls that modify the state of + // notification channels in a single project. This includes calls to + // CreateNotificationChannel, DeleteNotificationChannel and + // UpdateNotificationChannel. + rpc DeleteNotificationChannel(DeleteNotificationChannelRequest) + returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v3/{name=projects/*/notificationChannels/*}" + }; + option (google.api.method_signature) = "name,force"; + } + + // Causes a verification code to be delivered to the channel. The code + // can then be supplied in `VerifyNotificationChannel` to verify the channel. + rpc SendNotificationChannelVerificationCode( + SendNotificationChannelVerificationCodeRequest) + returns (google.protobuf.Empty) { + option (google.api.http) = { + post: "/v3/{name=projects/*/notificationChannels/*}:sendVerificationCode" + body: "*" + }; + option (google.api.method_signature) = "name"; + } + + // Requests a verification code for an already verified channel that can then + // be used in a call to VerifyNotificationChannel() on a different channel + // with an equivalent identity in the same or in a different project. This + // makes it possible to copy a channel between projects without requiring + // manual reverification of the channel. If the channel is not in the + // verified state, this method will fail (in other words, this may only be + // used if the SendNotificationChannelVerificationCode and + // VerifyNotificationChannel paths have already been used to put the given + // channel into the verified state). + // + // There is no guarantee that the verification codes returned by this method + // will be of a similar structure or form as the ones that are delivered + // to the channel via SendNotificationChannelVerificationCode; while + // VerifyNotificationChannel() will recognize both the codes delivered via + // SendNotificationChannelVerificationCode() and returned from + // GetNotificationChannelVerificationCode(), it is typically the case that + // the verification codes delivered via + // SendNotificationChannelVerificationCode() will be shorter and also + // have a shorter expiration (e.g. codes such as "G-123456") whereas + // GetVerificationCode() will typically return a much longer, websafe base + // 64 encoded string that has a longer expiration time. + rpc GetNotificationChannelVerificationCode( + GetNotificationChannelVerificationCodeRequest) + returns (GetNotificationChannelVerificationCodeResponse) { + option (google.api.http) = { + post: "/v3/{name=projects/*/notificationChannels/*}:getVerificationCode" + body: "*" + }; + option (google.api.method_signature) = "name"; + } + + // Verifies a `NotificationChannel` by proving receipt of the code + // delivered to the channel as a result of calling + // `SendNotificationChannelVerificationCode`. + rpc VerifyNotificationChannel(VerifyNotificationChannelRequest) + returns (NotificationChannel) { + option (google.api.http) = { + post: "/v3/{name=projects/*/notificationChannels/*}:verify" + body: "*" + }; + option (google.api.method_signature) = "name,code"; + } +} + +// The `ListNotificationChannelDescriptors` request. +message ListNotificationChannelDescriptorsRequest { + // Required. The REST resource name of the parent from which to retrieve + // the notification channel descriptors. The expected syntax is: + // + // projects/[PROJECT_ID_OR_NUMBER] + // + // Note that this + // [names](https://cloud.google.com/monitoring/api/v3#project_name) the parent + // container in which to look for the descriptors; to retrieve a single + // descriptor by name, use the + // [GetNotificationChannelDescriptor][google.monitoring.v3.NotificationChannelService.GetNotificationChannelDescriptor] + // operation, instead. + string name = 4 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "monitoring.googleapis.com/NotificationChannelDescriptor" + } + ]; + + // The maximum number of results to return in a single response. If + // not set to a positive number, a reasonable value will be chosen by the + // service. + int32 page_size = 2; + + // If non-empty, `page_token` must contain a value returned as the + // `next_page_token` in a previous response to request the next set + // of results. + string page_token = 3; +} + +// The `ListNotificationChannelDescriptors` response. +message ListNotificationChannelDescriptorsResponse { + // The monitored resource descriptors supported for the specified + // project, optionally filtered. + repeated NotificationChannelDescriptor channel_descriptors = 1; + + // If not empty, indicates that there may be more results that match + // the request. Use the value in the `page_token` field in a + // subsequent request to fetch the next set of results. If empty, + // all results have been returned. + string next_page_token = 2; +} + +// The `GetNotificationChannelDescriptor` response. +message GetNotificationChannelDescriptorRequest { + // Required. The channel type for which to execute the request. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/notificationChannelDescriptors/[CHANNEL_TYPE] + string name = 3 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/NotificationChannelDescriptor" + } + ]; +} + +// The `CreateNotificationChannel` request. +message CreateNotificationChannelRequest { + // Required. The + // [project](https://cloud.google.com/monitoring/api/v3#project_name) on which + // to execute the request. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER] + // + // This names the container into which the channel will be + // written, this does not name the newly created channel. The resulting + // channel's name will have a normalized version of this field as a prefix, + // but will add `/notificationChannels/[CHANNEL_ID]` to identify the channel. + string name = 3 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "monitoring.googleapis.com/NotificationChannel" + } + ]; + + // Required. The definition of the `NotificationChannel` to create. + NotificationChannel notification_channel = 2 + [(google.api.field_behavior) = REQUIRED]; +} + +// The `ListNotificationChannels` request. +message ListNotificationChannelsRequest { + // Required. The + // [project](https://cloud.google.com/monitoring/api/v3#project_name) on which + // to execute the request. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER] + // + // This names the container + // in which to look for the notification channels; it does not name a + // specific channel. To query a specific channel by REST resource name, use + // the + // [`GetNotificationChannel`][google.monitoring.v3.NotificationChannelService.GetNotificationChannel] + // operation. + string name = 5 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "monitoring.googleapis.com/NotificationChannel" + } + ]; + + // If provided, this field specifies the criteria that must be met by + // notification channels to be included in the response. + // + // For more details, see [sorting and + // filtering](https://cloud.google.com/monitoring/api/v3/sorting-and-filtering). + string filter = 6; + + // A comma-separated list of fields by which to sort the result. Supports + // the same set of fields as in `filter`. Entries can be prefixed with + // a minus sign to sort in descending rather than ascending order. + // + // For more details, see [sorting and + // filtering](https://cloud.google.com/monitoring/api/v3/sorting-and-filtering). + string order_by = 7; + + // The maximum number of results to return in a single response. If + // not set to a positive number, a reasonable value will be chosen by the + // service. + int32 page_size = 3; + + // If non-empty, `page_token` must contain a value returned as the + // `next_page_token` in a previous response to request the next set + // of results. + string page_token = 4; +} + +// The `ListNotificationChannels` response. +message ListNotificationChannelsResponse { + // The notification channels defined for the specified project. + repeated NotificationChannel notification_channels = 3; + + // If not empty, indicates that there may be more results that match + // the request. Use the value in the `page_token` field in a + // subsequent request to fetch the next set of results. If empty, + // all results have been returned. + string next_page_token = 2; + + // The total number of notification channels in all pages. This number is only + // an estimate, and may change in subsequent pages. https://aip.dev/158 + int32 total_size = 4; +} + +// The `GetNotificationChannel` request. +message GetNotificationChannelRequest { + // Required. The channel for which to execute the request. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/notificationChannels/[CHANNEL_ID] + string name = 3 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/NotificationChannel" + } + ]; +} + +// The `UpdateNotificationChannel` request. +message UpdateNotificationChannelRequest { + // The fields to update. + google.protobuf.FieldMask update_mask = 2; + + // Required. A description of the changes to be applied to the specified + // notification channel. The description must provide a definition for + // fields to be updated; the names of these fields should also be + // included in the `update_mask`. + NotificationChannel notification_channel = 3 + [(google.api.field_behavior) = REQUIRED]; +} + +// The `DeleteNotificationChannel` request. +message DeleteNotificationChannelRequest { + // Required. The channel for which to execute the request. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/notificationChannels/[CHANNEL_ID] + string name = 3 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/NotificationChannel" + } + ]; + + // If true, the notification channel will be deleted regardless of its + // use in alert policies (the policies will be updated to remove the + // channel). If false, channels that are still referenced by an existing + // alerting policy will fail to be deleted in a delete operation. + bool force = 5; +} + +// The `SendNotificationChannelVerificationCode` request. +message SendNotificationChannelVerificationCodeRequest { + // Required. The notification channel to which to send a verification code. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/NotificationChannel" + } + ]; +} + +// The `GetNotificationChannelVerificationCode` request. +message GetNotificationChannelVerificationCodeRequest { + // Required. The notification channel for which a verification code is to be + // generated and retrieved. This must name a channel that is already verified; + // if the specified channel is not verified, the request will fail. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/NotificationChannel" + } + ]; + + // The desired expiration time. If specified, the API will guarantee that + // the returned code will not be valid after the specified timestamp; + // however, the API cannot guarantee that the returned code will be + // valid for at least as long as the requested time (the API puts an upper + // bound on the amount of time for which a code may be valid). If omitted, + // a default expiration will be used, which may be less than the max + // permissible expiration (so specifying an expiration may extend the + // code's lifetime over omitting an expiration, even though the API does + // impose an upper limit on the maximum expiration that is permitted). + google.protobuf.Timestamp expire_time = 2; +} + +// The `GetNotificationChannelVerificationCode` request. +message GetNotificationChannelVerificationCodeResponse { + // The verification code, which may be used to verify other channels + // that have an equivalent identity (i.e. other channels of the same + // type with the same fingerprint such as other email channels with + // the same email address or other sms channels with the same number). + string code = 1; + + // The expiration time associated with the code that was returned. If + // an expiration was provided in the request, this is the minimum of the + // requested expiration in the request and the max permitted expiration. + google.protobuf.Timestamp expire_time = 2; +} + +// The `VerifyNotificationChannel` request. +message VerifyNotificationChannelRequest { + // Required. The notification channel to verify. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/NotificationChannel" + } + ]; + + // Required. The verification code that was delivered to the channel as + // a result of invoking the `SendNotificationChannelVerificationCode` API + // method or that was retrieved from a verified channel via + // `GetNotificationChannelVerificationCode`. For example, one might have + // "G-123456" or "TKNZGhhd2EyN3I1MnRnMjRv" (in general, one is only + // guaranteed that the code is valid UTF-8; one should not + // make any assumptions regarding the structure or format of the code). + string code = 2 [(google.api.field_behavior) = REQUIRED]; +} diff --git a/node_modules/google-gax/build/protos/google/monitoring/v3/query_service.proto b/node_modules/google-gax/build/protos/google/monitoring/v3/query_service.proto new file mode 100644 index 0000000..5d45124 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/monitoring/v3/query_service.proto @@ -0,0 +1,48 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.monitoring.v3; + +import "google/api/annotations.proto"; +import "google/monitoring/v3/metric_service.proto"; +import "google/api/client.proto"; + +option csharp_namespace = "Google.Cloud.Monitoring.V3"; +option go_package = "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb;monitoringpb"; +option java_multiple_files = true; +option java_outer_classname = "QueryServiceProto"; +option java_package = "com.google.monitoring.v3"; +option php_namespace = "Google\\Cloud\\Monitoring\\V3"; +option ruby_package = "Google::Cloud::Monitoring::V3"; + +// The QueryService API is used to manage time series data in Stackdriver +// Monitoring. Time series data is a collection of data points that describes +// the time-varying values of a metric. +service QueryService { + option (google.api.default_host) = "monitoring.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/monitoring," + "https://www.googleapis.com/auth/monitoring.read"; + + // Queries time series using Monitoring Query Language. This method does not require a Workspace. + rpc QueryTimeSeries(QueryTimeSeriesRequest) returns (QueryTimeSeriesResponse) { + option (google.api.http) = { + post: "/v3/{name=projects/*}/timeSeries:query" + body: "*" + }; + } +} diff --git a/node_modules/google-gax/build/protos/google/monitoring/v3/service.proto b/node_modules/google-gax/build/protos/google/monitoring/v3/service.proto new file mode 100644 index 0000000..ff4dd0c --- /dev/null +++ b/node_modules/google-gax/build/protos/google/monitoring/v3/service.proto @@ -0,0 +1,457 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.monitoring.v3; + +import "google/api/resource.proto"; +import "google/protobuf/duration.proto"; +import "google/type/calendar_period.proto"; + +option csharp_namespace = "Google.Cloud.Monitoring.V3"; +option go_package = "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb;monitoringpb"; +option java_multiple_files = true; +option java_outer_classname = "ServiceMonitoringProto"; +option java_package = "com.google.monitoring.v3"; +option php_namespace = "Google\\Cloud\\Monitoring\\V3"; +option ruby_package = "Google::Cloud::Monitoring::V3"; + +// A `Service` is a discrete, autonomous, and network-accessible unit, designed +// to solve an individual concern +// ([Wikipedia](https://en.wikipedia.org/wiki/Service-orientation)). In +// Cloud Monitoring, a `Service` acts as the root resource under which +// operational aspects of the service are accessible. +message Service { + option (google.api.resource) = { + type: "monitoring.googleapis.com/Service" + pattern: "projects/{project}/services/{service}" + pattern: "organizations/{organization}/services/{service}" + pattern: "folders/{folder}/services/{service}" + pattern: "*" + }; + + // Custom view of service telemetry. Currently a place-holder pending final + // design. + message Custom { + + } + + // App Engine service. Learn more at https://cloud.google.com/appengine. + message AppEngine { + // The ID of the App Engine module underlying this service. Corresponds to + // the `module_id` resource label in the `gae_app` monitored resource: + // https://cloud.google.com/monitoring/api/resources#tag_gae_app + string module_id = 1; + } + + // Cloud Endpoints service. Learn more at https://cloud.google.com/endpoints. + message CloudEndpoints { + // The name of the Cloud Endpoints service underlying this service. + // Corresponds to the `service` resource label in the `api` monitored + // resource: https://cloud.google.com/monitoring/api/resources#tag_api + string service = 1; + } + + // Istio service scoped to a single Kubernetes cluster. Learn more at + // https://istio.io. Clusters running OSS Istio will have their services + // ingested as this type. + message ClusterIstio { + // The location of the Kubernetes cluster in which this Istio service is + // defined. Corresponds to the `location` resource label in `k8s_cluster` + // resources. + string location = 1; + + // The name of the Kubernetes cluster in which this Istio service is + // defined. Corresponds to the `cluster_name` resource label in + // `k8s_cluster` resources. + string cluster_name = 2; + + // The namespace of the Istio service underlying this service. Corresponds + // to the `destination_service_namespace` metric label in Istio metrics. + string service_namespace = 3; + + // The name of the Istio service underlying this service. Corresponds to the + // `destination_service_name` metric label in Istio metrics. + string service_name = 4; + } + + // Istio service scoped to an Istio mesh. Anthos clusters running ASM < 1.6.8 + // will have their services ingested as this type. + message MeshIstio { + // Identifier for the mesh in which this Istio service is defined. + // Corresponds to the `mesh_uid` metric label in Istio metrics. + string mesh_uid = 1; + + // The namespace of the Istio service underlying this service. Corresponds + // to the `destination_service_namespace` metric label in Istio metrics. + string service_namespace = 3; + + // The name of the Istio service underlying this service. Corresponds to the + // `destination_service_name` metric label in Istio metrics. + string service_name = 4; + } + + // Canonical service scoped to an Istio mesh. Anthos clusters running ASM >= + // 1.6.8 will have their services ingested as this type. + message IstioCanonicalService { + // Identifier for the Istio mesh in which this canonical service is defined. + // Corresponds to the `mesh_uid` metric label in + // [Istio metrics](https://cloud.google.com/monitoring/api/metrics_istio). + string mesh_uid = 1; + + // The namespace of the canonical service underlying this service. + // Corresponds to the `destination_canonical_service_namespace` metric + // label in [Istio + // metrics](https://cloud.google.com/monitoring/api/metrics_istio). + string canonical_service_namespace = 3; + + // The name of the canonical service underlying this service. + // Corresponds to the `destination_canonical_service_name` metric label in + // label in [Istio + // metrics](https://cloud.google.com/monitoring/api/metrics_istio). + string canonical_service = 4; + } + + // Configuration for how to query telemetry on a Service. + message Telemetry { + // The full name of the resource that defines this service. Formatted as + // described in https://cloud.google.com/apis/design/resource_names. + string resource_name = 1; + } + + // Resource name for this Service. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID] + string name = 1; + + // Name used for UI elements listing this Service. + string display_name = 2; + + // REQUIRED. Service-identifying atoms specifying the underlying service. + oneof identifier { + // Custom service type. + Custom custom = 6; + + // Type used for App Engine services. + AppEngine app_engine = 7; + + // Type used for Cloud Endpoints services. + CloudEndpoints cloud_endpoints = 8; + + // Type used for Istio services that live in a Kubernetes cluster. + ClusterIstio cluster_istio = 9; + + // Type used for Istio services scoped to an Istio mesh. + MeshIstio mesh_istio = 10; + + // Type used for canonical services scoped to an Istio mesh. + // Metrics for Istio are + // [documented here](https://istio.io/latest/docs/reference/config/metrics/) + IstioCanonicalService istio_canonical_service = 11; + } + + // Configuration for how to query telemetry on a Service. + Telemetry telemetry = 13; + + // Labels which have been used to annotate the service. Label keys must start + // with a letter. Label keys and values may contain lowercase letters, + // numbers, underscores, and dashes. Label keys and values have a maximum + // length of 63 characters, and must be less than 128 bytes in size. Up to 64 + // label entries may be stored. For labels which do not have a semantic value, + // the empty string may be supplied for the label value. + map user_labels = 14; +} + +// A Service-Level Objective (SLO) describes a level of desired good service. It +// consists of a service-level indicator (SLI), a performance goal, and a period +// over which the objective is to be evaluated against that goal. The SLO can +// use SLIs defined in a number of different manners. Typical SLOs might include +// "99% of requests in each rolling week have latency below 200 milliseconds" or +// "99.5% of requests in each calendar month return successfully." +message ServiceLevelObjective { + option (google.api.resource) = { + type: "monitoring.googleapis.com/ServiceLevelObjective" + pattern: "projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}" + pattern: "organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}" + pattern: "folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}" + pattern: "*" + history: ORIGINALLY_SINGLE_PATTERN + }; + + // `ServiceLevelObjective.View` determines what form of + // `ServiceLevelObjective` is returned from `GetServiceLevelObjective`, + // `ListServiceLevelObjectives`, and `ListServiceLevelObjectiveVersions` RPCs. + enum View { + // Same as FULL. + VIEW_UNSPECIFIED = 0; + + // Return the embedded `ServiceLevelIndicator` in the form in which it was + // defined. If it was defined using a `BasicSli`, return that `BasicSli`. + FULL = 2; + + // For `ServiceLevelIndicator`s using `BasicSli` articulation, instead + // return the `ServiceLevelIndicator` with its mode of computation fully + // spelled out as a `RequestBasedSli`. For `ServiceLevelIndicator`s using + // `RequestBasedSli` or `WindowsBasedSli`, return the + // `ServiceLevelIndicator` as it was provided. + EXPLICIT = 1; + } + + // Resource name for this `ServiceLevelObjective`. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID]/serviceLevelObjectives/[SLO_NAME] + string name = 1; + + // Name used for UI elements listing this SLO. + string display_name = 11; + + // The definition of good service, used to measure and calculate the quality + // of the `Service`'s performance with respect to a single aspect of service + // quality. + ServiceLevelIndicator service_level_indicator = 3; + + // The fraction of service that must be good in order for this objective to be + // met. `0 < goal <= 0.999`. + double goal = 4; + + // The time period over which the objective will be evaluated. + oneof period { + // A rolling time period, semantically "in the past ``". + // Must be an integer multiple of 1 day no larger than 30 days. + google.protobuf.Duration rolling_period = 5; + + // A calendar period, semantically "since the start of the current + // ``". At this time, only `DAY`, `WEEK`, `FORTNIGHT`, and + // `MONTH` are supported. + google.type.CalendarPeriod calendar_period = 6; + } + + // Labels which have been used to annotate the service-level objective. Label + // keys must start with a letter. Label keys and values may contain lowercase + // letters, numbers, underscores, and dashes. Label keys and values have a + // maximum length of 63 characters, and must be less than 128 bytes in size. + // Up to 64 label entries may be stored. For labels which do not have a + // semantic value, the empty string may be supplied for the label value. + map user_labels = 12; +} + +// A Service-Level Indicator (SLI) describes the "performance" of a service. For +// some services, the SLI is well-defined. In such cases, the SLI can be +// described easily by referencing the well-known SLI and providing the needed +// parameters. Alternatively, a "custom" SLI can be defined with a query to the +// underlying metric store. An SLI is defined to be `good_service / +// total_service` over any queried time interval. The value of performance +// always falls into the range `0 <= performance <= 1`. A custom SLI describes +// how to compute this ratio, whether this is by dividing values from a pair of +// time series, cutting a `Distribution` into good and bad counts, or counting +// time windows in which the service complies with a criterion. For separation +// of concerns, a single Service-Level Indicator measures performance for only +// one aspect of service quality, such as fraction of successful queries or +// fast-enough queries. +message ServiceLevelIndicator { + // Service level indicators can be grouped by whether the "unit" of service + // being measured is based on counts of good requests or on counts of good + // time windows + oneof type { + // Basic SLI on a well-known service type. + BasicSli basic_sli = 4; + + // Request-based SLIs + RequestBasedSli request_based = 1; + + // Windows-based SLIs + WindowsBasedSli windows_based = 2; + } +} + +// An SLI measuring performance on a well-known service type. Performance will +// be computed on the basis of pre-defined metrics. The type of the +// `service_resource` determines the metrics to use and the +// `service_resource.labels` and `metric_labels` are used to construct a +// monitoring filter to filter that metric down to just the data relevant to +// this service. +message BasicSli { + // Future parameters for the availability SLI. + message AvailabilityCriteria { + + } + + // Parameters for a latency threshold SLI. + message LatencyCriteria { + // Good service is defined to be the count of requests made to this service + // that return in no more than `threshold`. + google.protobuf.Duration threshold = 3; + } + + // OPTIONAL: The set of RPCs to which this SLI is relevant. Telemetry from + // other methods will not be used to calculate performance for this SLI. If + // omitted, this SLI applies to all the Service's methods. For service types + // that don't support breaking down by method, setting this field will result + // in an error. + repeated string method = 7; + + // OPTIONAL: The set of locations to which this SLI is relevant. Telemetry + // from other locations will not be used to calculate performance for this + // SLI. If omitted, this SLI applies to all locations in which the Service has + // activity. For service types that don't support breaking down by location, + // setting this field will result in an error. + repeated string location = 8; + + // OPTIONAL: The set of API versions to which this SLI is relevant. Telemetry + // from other API versions will not be used to calculate performance for this + // SLI. If omitted, this SLI applies to all API versions. For service types + // that don't support breaking down by version, setting this field will result + // in an error. + repeated string version = 9; + + // This SLI can be evaluated on the basis of availability or latency. + oneof sli_criteria { + // Good service is defined to be the count of requests made to this service + // that return successfully. + AvailabilityCriteria availability = 2; + + // Good service is defined to be the count of requests made to this service + // that are fast enough with respect to `latency.threshold`. + LatencyCriteria latency = 3; + } +} + +// Range of numerical values within `min` and `max`. +message Range { + // Range minimum. + double min = 1; + + // Range maximum. + double max = 2; +} + +// Service Level Indicators for which atomic units of service are counted +// directly. +message RequestBasedSli { + // The means to compute a ratio of `good_service` to `total_service`. + oneof method { + // `good_total_ratio` is used when the ratio of `good_service` to + // `total_service` is computed from two `TimeSeries`. + TimeSeriesRatio good_total_ratio = 1; + + // `distribution_cut` is used when `good_service` is a count of values + // aggregated in a `Distribution` that fall into a good range. The + // `total_service` is the total count of all values aggregated in the + // `Distribution`. + DistributionCut distribution_cut = 3; + } +} + +// A `TimeSeriesRatio` specifies two `TimeSeries` to use for computing the +// `good_service / total_service` ratio. The specified `TimeSeries` must have +// `ValueType = DOUBLE` or `ValueType = INT64` and must have `MetricKind = +// DELTA` or `MetricKind = CUMULATIVE`. The `TimeSeriesRatio` must specify +// exactly two of good, bad, and total, and the relationship `good_service + +// bad_service = total_service` will be assumed. +message TimeSeriesRatio { + // A [monitoring filter](https://cloud.google.com/monitoring/api/v3/filters) + // specifying a `TimeSeries` quantifying good service provided. Must have + // `ValueType = DOUBLE` or `ValueType = INT64` and must have `MetricKind = + // DELTA` or `MetricKind = CUMULATIVE`. + string good_service_filter = 4; + + // A [monitoring filter](https://cloud.google.com/monitoring/api/v3/filters) + // specifying a `TimeSeries` quantifying bad service, either demanded service + // that was not provided or demanded service that was of inadequate quality. + // Must have `ValueType = DOUBLE` or `ValueType = INT64` and must have + // `MetricKind = DELTA` or `MetricKind = CUMULATIVE`. + string bad_service_filter = 5; + + // A [monitoring filter](https://cloud.google.com/monitoring/api/v3/filters) + // specifying a `TimeSeries` quantifying total demanded service. Must have + // `ValueType = DOUBLE` or `ValueType = INT64` and must have `MetricKind = + // DELTA` or `MetricKind = CUMULATIVE`. + string total_service_filter = 6; +} + +// A `DistributionCut` defines a `TimeSeries` and thresholds used for measuring +// good service and total service. The `TimeSeries` must have `ValueType = +// DISTRIBUTION` and `MetricKind = DELTA` or `MetricKind = CUMULATIVE`. The +// computed `good_service` will be the estimated count of values in the +// `Distribution` that fall within the specified `min` and `max`. +message DistributionCut { + // A [monitoring filter](https://cloud.google.com/monitoring/api/v3/filters) + // specifying a `TimeSeries` aggregating values. Must have `ValueType = + // DISTRIBUTION` and `MetricKind = DELTA` or `MetricKind = CUMULATIVE`. + string distribution_filter = 4; + + // Range of values considered "good." For a one-sided range, set one bound to + // an infinite value. + Range range = 5; +} + +// A `WindowsBasedSli` defines `good_service` as the count of time windows for +// which the provided service was of good quality. Criteria for determining +// if service was good are embedded in the `window_criterion`. +message WindowsBasedSli { + // A `PerformanceThreshold` is used when each window is good when that window + // has a sufficiently high `performance`. + message PerformanceThreshold { + // The means, either a request-based SLI or a basic SLI, by which to compute + // performance over a window. + oneof type { + // `RequestBasedSli` to evaluate to judge window quality. + RequestBasedSli performance = 1; + + // `BasicSli` to evaluate to judge window quality. + BasicSli basic_sli_performance = 3; + } + + // If window `performance >= threshold`, the window is counted as good. + double threshold = 2; + } + + // A `MetricRange` is used when each window is good when the value x of a + // single `TimeSeries` satisfies `range.min <= x <= range.max`. The provided + // `TimeSeries` must have `ValueType = INT64` or `ValueType = DOUBLE` and + // `MetricKind = GAUGE`. + message MetricRange { + // A [monitoring filter](https://cloud.google.com/monitoring/api/v3/filters) + // specifying the `TimeSeries` to use for evaluating window quality. + string time_series = 1; + + // Range of values considered "good." For a one-sided range, set one bound + // to an infinite value. + Range range = 4; + } + + // The criterion to use for evaluating window goodness. + oneof window_criterion { + // A [monitoring filter](https://cloud.google.com/monitoring/api/v3/filters) + // specifying a `TimeSeries` with `ValueType = BOOL`. The window is good if + // any `true` values appear in the window. + string good_bad_metric_filter = 5; + + // A window is good if its `performance` is high enough. + PerformanceThreshold good_total_ratio_threshold = 2; + + // A window is good if the metric's value is in a good range, averaged + // across returned streams. + MetricRange metric_mean_in_range = 6; + + // A window is good if the metric's value is in a good range, summed across + // returned streams. + MetricRange metric_sum_in_range = 7; + } + + // Duration over which window quality is evaluated. Must be an integer + // fraction of a day and at least `60s`. + google.protobuf.Duration window_period = 4; +} diff --git a/node_modules/google-gax/build/protos/google/monitoring/v3/service_service.proto b/node_modules/google-gax/build/protos/google/monitoring/v3/service_service.proto new file mode 100644 index 0000000..bc55a48 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/monitoring/v3/service_service.proto @@ -0,0 +1,352 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.monitoring.v3; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/monitoring/v3/service.proto"; +import "google/protobuf/empty.proto"; +import "google/protobuf/field_mask.proto"; + +option csharp_namespace = "Google.Cloud.Monitoring.V3"; +option go_package = "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb;monitoringpb"; +option java_multiple_files = true; +option java_outer_classname = "ServiceMonitoringServiceProto"; +option java_package = "com.google.monitoring.v3"; +option php_namespace = "Google\\Cloud\\Monitoring\\V3"; +option ruby_package = "Google::Cloud::Monitoring::V3"; + +// The Cloud Monitoring Service-Oriented Monitoring API has endpoints for +// managing and querying aspects of a workspace's services. These include the +// `Service`'s monitored resources, its Service-Level Objectives, and a taxonomy +// of categorized Health Metrics. +service ServiceMonitoringService { + option (google.api.default_host) = "monitoring.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/monitoring," + "https://www.googleapis.com/auth/monitoring.read"; + + // Create a `Service`. + rpc CreateService(CreateServiceRequest) returns (Service) { + option (google.api.http) = { + post: "/v3/{parent=*/*}/services" + body: "service" + }; + option (google.api.method_signature) = "parent,service"; + } + + // Get the named `Service`. + rpc GetService(GetServiceRequest) returns (Service) { + option (google.api.http) = { + get: "/v3/{name=*/*/services/*}" + }; + option (google.api.method_signature) = "name"; + } + + // List `Service`s for this workspace. + rpc ListServices(ListServicesRequest) returns (ListServicesResponse) { + option (google.api.http) = { + get: "/v3/{parent=*/*}/services" + }; + option (google.api.method_signature) = "parent"; + } + + // Update this `Service`. + rpc UpdateService(UpdateServiceRequest) returns (Service) { + option (google.api.http) = { + patch: "/v3/{service.name=*/*/services/*}" + body: "service" + }; + option (google.api.method_signature) = "service"; + } + + // Soft delete this `Service`. + rpc DeleteService(DeleteServiceRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v3/{name=*/*/services/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Create a `ServiceLevelObjective` for the given `Service`. + rpc CreateServiceLevelObjective(CreateServiceLevelObjectiveRequest) returns (ServiceLevelObjective) { + option (google.api.http) = { + post: "/v3/{parent=*/*/services/*}/serviceLevelObjectives" + body: "service_level_objective" + }; + option (google.api.method_signature) = "parent,service_level_objective"; + } + + // Get a `ServiceLevelObjective` by name. + rpc GetServiceLevelObjective(GetServiceLevelObjectiveRequest) returns (ServiceLevelObjective) { + option (google.api.http) = { + get: "/v3/{name=*/*/services/*/serviceLevelObjectives/*}" + }; + option (google.api.method_signature) = "name"; + } + + // List the `ServiceLevelObjective`s for the given `Service`. + rpc ListServiceLevelObjectives(ListServiceLevelObjectivesRequest) returns (ListServiceLevelObjectivesResponse) { + option (google.api.http) = { + get: "/v3/{parent=*/*/services/*}/serviceLevelObjectives" + }; + option (google.api.method_signature) = "parent"; + } + + // Update the given `ServiceLevelObjective`. + rpc UpdateServiceLevelObjective(UpdateServiceLevelObjectiveRequest) returns (ServiceLevelObjective) { + option (google.api.http) = { + patch: "/v3/{service_level_objective.name=*/*/services/*/serviceLevelObjectives/*}" + body: "service_level_objective" + }; + option (google.api.method_signature) = "service_level_objective"; + } + + // Delete the given `ServiceLevelObjective`. + rpc DeleteServiceLevelObjective(DeleteServiceLevelObjectiveRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v3/{name=*/*/services/*/serviceLevelObjectives/*}" + }; + option (google.api.method_signature) = "name"; + } +} + +// The `CreateService` request. +message CreateServiceRequest { + // Required. Resource [name](https://cloud.google.com/monitoring/api/v3#project_name) of + // the parent workspace. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER] + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "monitoring.googleapis.com/Service" + } + ]; + + // Optional. The Service id to use for this Service. If omitted, an id will be + // generated instead. Must match the pattern `[a-z0-9\-]+` + string service_id = 3; + + // Required. The `Service` to create. + Service service = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// The `GetService` request. +message GetServiceRequest { + // Required. Resource name of the `Service`. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID] + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/Service" + } + ]; +} + +// The `ListServices` request. +message ListServicesRequest { + // Required. Resource name of the parent containing the listed services, either a + // [project](https://cloud.google.com/monitoring/api/v3#project_name) or a + // Monitoring Workspace. The formats are: + // + // projects/[PROJECT_ID_OR_NUMBER] + // workspaces/[HOST_PROJECT_ID_OR_NUMBER] + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "monitoring.googleapis.com/Service" + } + ]; + + // A filter specifying what `Service`s to return. The filter currently + // supports the following fields: + // + // - `identifier_case` + // - `app_engine.module_id` + // - `cloud_endpoints.service` (reserved for future use) + // - `mesh_istio.mesh_uid` + // - `mesh_istio.service_namespace` + // - `mesh_istio.service_name` + // - `cluster_istio.location` (deprecated) + // - `cluster_istio.cluster_name` (deprecated) + // - `cluster_istio.service_namespace` (deprecated) + // - `cluster_istio.service_name` (deprecated) + // + // `identifier_case` refers to which option in the identifier oneof is + // populated. For example, the filter `identifier_case = "CUSTOM"` would match + // all services with a value for the `custom` field. Valid options are + // "CUSTOM", "APP_ENGINE", "MESH_ISTIO", plus "CLUSTER_ISTIO" (deprecated) + // and "CLOUD_ENDPOINTS" (reserved for future use). + string filter = 2; + + // A non-negative number that is the maximum number of results to return. + // When 0, use default page size. + int32 page_size = 3; + + // If this field is not empty then it must contain the `nextPageToken` value + // returned by a previous call to this method. Using this field causes the + // method to return additional results from the previous method call. + string page_token = 4; +} + +// The `ListServices` response. +message ListServicesResponse { + // The `Service`s matching the specified filter. + repeated Service services = 1; + + // If there are more results than have been returned, then this field is set + // to a non-empty value. To see the additional results, + // use that value as `page_token` in the next call to this method. + string next_page_token = 2; +} + +// The `UpdateService` request. +message UpdateServiceRequest { + // Required. The `Service` to draw updates from. + // The given `name` specifies the resource to update. + Service service = 1 [(google.api.field_behavior) = REQUIRED]; + + // A set of field paths defining which fields to use for the update. + google.protobuf.FieldMask update_mask = 2; +} + +// The `DeleteService` request. +message DeleteServiceRequest { + // Required. Resource name of the `Service` to delete. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID] + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/Service" + } + ]; +} + +// The `CreateServiceLevelObjective` request. +message CreateServiceLevelObjectiveRequest { + // Required. Resource name of the parent `Service`. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID] + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/Service" + } + ]; + + // Optional. The ServiceLevelObjective id to use for this + // ServiceLevelObjective. If omitted, an id will be generated instead. Must + // match the pattern `[a-z0-9\-]+` + string service_level_objective_id = 3; + + // Required. The `ServiceLevelObjective` to create. + // The provided `name` will be respected if no `ServiceLevelObjective` exists + // with this name. + ServiceLevelObjective service_level_objective = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// The `GetServiceLevelObjective` request. +message GetServiceLevelObjectiveRequest { + // Required. Resource name of the `ServiceLevelObjective` to get. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID]/serviceLevelObjectives/[SLO_NAME] + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/ServiceLevelObjective" + } + ]; + + // View of the `ServiceLevelObjective` to return. If `DEFAULT`, return the + // `ServiceLevelObjective` as originally defined. If `EXPLICIT` and the + // `ServiceLevelObjective` is defined in terms of a `BasicSli`, replace the + // `BasicSli` with a `RequestBasedSli` spelling out how the SLI is computed. + ServiceLevelObjective.View view = 2; +} + +// The `ListServiceLevelObjectives` request. +message ListServiceLevelObjectivesRequest { + // Required. Resource name of the parent containing the listed SLOs, either a + // project or a Monitoring Workspace. The formats are: + // + // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID] + // workspaces/[HOST_PROJECT_ID_OR_NUMBER]/services/- + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/Service" + } + ]; + + // A filter specifying what `ServiceLevelObjective`s to return. + string filter = 2; + + // A non-negative number that is the maximum number of results to return. + // When 0, use default page size. + int32 page_size = 3; + + // If this field is not empty then it must contain the `nextPageToken` value + // returned by a previous call to this method. Using this field causes the + // method to return additional results from the previous method call. + string page_token = 4; + + // View of the `ServiceLevelObjective`s to return. If `DEFAULT`, return each + // `ServiceLevelObjective` as originally defined. If `EXPLICIT` and the + // `ServiceLevelObjective` is defined in terms of a `BasicSli`, replace the + // `BasicSli` with a `RequestBasedSli` spelling out how the SLI is computed. + ServiceLevelObjective.View view = 5; +} + +// The `ListServiceLevelObjectives` response. +message ListServiceLevelObjectivesResponse { + // The `ServiceLevelObjective`s matching the specified filter. + repeated ServiceLevelObjective service_level_objectives = 1; + + // If there are more results than have been returned, then this field is set + // to a non-empty value. To see the additional results, + // use that value as `page_token` in the next call to this method. + string next_page_token = 2; +} + +// The `UpdateServiceLevelObjective` request. +message UpdateServiceLevelObjectiveRequest { + // Required. The `ServiceLevelObjective` to draw updates from. + // The given `name` specifies the resource to update. + ServiceLevelObjective service_level_objective = 1 [(google.api.field_behavior) = REQUIRED]; + + // A set of field paths defining which fields to use for the update. + google.protobuf.FieldMask update_mask = 2; +} + +// The `DeleteServiceLevelObjective` request. +message DeleteServiceLevelObjectiveRequest { + // Required. Resource name of the `ServiceLevelObjective` to delete. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID]/serviceLevelObjectives/[SLO_NAME] + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/ServiceLevelObjective" + } + ]; +} diff --git a/node_modules/google-gax/build/protos/google/monitoring/v3/snooze.proto b/node_modules/google-gax/build/protos/google/monitoring/v3/snooze.proto new file mode 100644 index 0000000..f20e1a0 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/monitoring/v3/snooze.proto @@ -0,0 +1,78 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.monitoring.v3; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/monitoring/v3/common.proto"; + +option csharp_namespace = "Google.Cloud.Monitoring.V3"; +option go_package = "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb;monitoringpb"; +option java_multiple_files = true; +option java_outer_classname = "SnoozeProto"; +option java_package = "com.google.monitoring.v3"; +option php_namespace = "Google\\Cloud\\Monitoring\\V3"; +option ruby_package = "Google::Cloud::Monitoring::V3"; + +// A `Snooze` will prevent any alerts from being opened, and close any that +// are already open. The `Snooze` will work on alerts that match the +// criteria defined in the `Snooze`. The `Snooze` will be active from +// `interval.start_time` through `interval.end_time`. +message Snooze { + option (google.api.resource) = { + type: "monitoring.googleapis.com/Snooze" + pattern: "projects/{project}/snoozes/{snooze}" + }; + + // Criteria specific to the `AlertPolicy`s that this `Snooze` applies to. The + // `Snooze` will suppress alerts that come from one of the `AlertPolicy`s + // whose names are supplied. + message Criteria { + // The specific `AlertPolicy` names for the alert that should be snoozed. + // The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[POLICY_ID] + // + // There is a limit of 16 policies per snooze. This limit is checked during + // snooze creation. + repeated string policies = 1 [(google.api.resource_reference) = { + type: "monitoring.googleapis.com/AlertPolicy" + }]; + } + + // Required. The name of the `Snooze`. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/snoozes/[SNOOZE_ID] + // + // The ID of the `Snooze` will be generated by the system. + string name = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. This defines the criteria for applying the `Snooze`. See + // `Criteria` for more information. + Criteria criteria = 3 [(google.api.field_behavior) = REQUIRED]; + + // Required. The `Snooze` will be active from `interval.start_time` through + // `interval.end_time`. + // `interval.start_time` cannot be in the past. There is a 15 second clock + // skew to account for the time it takes for a request to reach the API from + // the UI. + TimeInterval interval = 4 [(google.api.field_behavior) = REQUIRED]; + + // Required. A display name for the `Snooze`. This can be, at most, 512 + // unicode characters. + string display_name = 5 [(google.api.field_behavior) = REQUIRED]; +} diff --git a/node_modules/google-gax/build/protos/google/monitoring/v3/snooze_service.proto b/node_modules/google-gax/build/protos/google/monitoring/v3/snooze_service.proto new file mode 100644 index 0000000..286551a --- /dev/null +++ b/node_modules/google-gax/build/protos/google/monitoring/v3/snooze_service.proto @@ -0,0 +1,210 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.monitoring.v3; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/monitoring/v3/snooze.proto"; +import "google/protobuf/field_mask.proto"; + +option csharp_namespace = "Google.Cloud.Monitoring.V3"; +option go_package = "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb;monitoringpb"; +option java_multiple_files = true; +option java_outer_classname = "SnoozeServiceProto"; +option java_package = "com.google.monitoring.v3"; +option php_namespace = "Google\\Cloud\\Monitoring\\V3"; +option ruby_package = "Google::Cloud::Monitoring::V3"; + +// The SnoozeService API is used to temporarily prevent an alert policy from +// generating alerts. A Snooze is a description of the criteria under which one +// or more alert policies should not fire alerts for the specified duration. +service SnoozeService { + option (google.api.default_host) = "monitoring.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/monitoring," + "https://www.googleapis.com/auth/monitoring.read"; + + // Creates a `Snooze` that will prevent alerts, which match the provided + // criteria, from being opened. The `Snooze` applies for a specific time + // interval. + rpc CreateSnooze(CreateSnoozeRequest) returns (Snooze) { + option (google.api.http) = { + post: "/v3/{parent=projects/*}/snoozes" + body: "snooze" + }; + option (google.api.method_signature) = "parent,snooze"; + } + + // Lists the `Snooze`s associated with a project. Can optionally pass in + // `filter`, which specifies predicates to match `Snooze`s. + rpc ListSnoozes(ListSnoozesRequest) returns (ListSnoozesResponse) { + option (google.api.http) = { + get: "/v3/{parent=projects/*}/snoozes" + }; + option (google.api.method_signature) = "parent"; + } + + // Retrieves a `Snooze` by `name`. + rpc GetSnooze(GetSnoozeRequest) returns (Snooze) { + option (google.api.http) = { + get: "/v3/{name=projects/*/snoozes/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Updates a `Snooze`, identified by its `name`, with the parameters in the + // given `Snooze` object. + rpc UpdateSnooze(UpdateSnoozeRequest) returns (Snooze) { + option (google.api.http) = { + patch: "/v3/{snooze.name=projects/*/snoozes/*}" + body: "snooze" + }; + option (google.api.method_signature) = "snooze,update_mask"; + } +} + +// The message definition for creating a `Snooze`. Users must provide the body +// of the `Snooze` to be created but must omit the `Snooze` field, `name`. +message CreateSnoozeRequest { + // Required. The + // [project](https://cloud.google.com/monitoring/api/v3#project_name) in which + // a `Snooze` should be created. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER] + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "monitoring.googleapis.com/Snooze" + } + ]; + + // Required. The `Snooze` to create. Omit the `name` field, as it will be + // filled in by the API. + Snooze snooze = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// The message definition for listing `Snooze`s associated with the given +// `parent`, satisfying the optional `filter`. +message ListSnoozesRequest { + // Required. The + // [project](https://cloud.google.com/monitoring/api/v3#project_name) whose + // `Snooze`s should be listed. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER] + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "monitoring.googleapis.com/Snooze" + } + ]; + + // Optional. Optional filter to restrict results to the given criteria. The + // following fields are supported. + // + // * `interval.start_time` + // * `interval.end_time` + // + // For example: + // + // ``` + // interval.start_time > "2022-03-11T00:00:00-08:00" AND + // interval.end_time < "2022-03-12T00:00:00-08:00" + // ``` + string filter = 2 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The maximum number of results to return for a single query. The + // server may further constrain the maximum number of results returned in a + // single page. The value should be in the range [1, 1000]. If the value given + // is outside this range, the server will decide the number of results to be + // returned. + int32 page_size = 4 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The `next_page_token` from a previous call to + // `ListSnoozesRequest` to get the next page of results. + string page_token = 5 [(google.api.field_behavior) = OPTIONAL]; +} + +// The results of a successful `ListSnoozes` call, containing the matching +// `Snooze`s. +message ListSnoozesResponse { + // `Snooze`s matching this list call. + repeated Snooze snoozes = 1; + + // Page token for repeated calls to `ListSnoozes`, to fetch additional pages + // of results. If this is empty or missing, there are no more pages. + string next_page_token = 2; +} + +// The message definition for retrieving a `Snooze`. Users must specify the +// field, `name`, which identifies the `Snooze`. +message GetSnoozeRequest { + // Required. The ID of the `Snooze` to retrieve. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/snoozes/[SNOOZE_ID] + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/Snooze" + } + ]; +} + +// The message definition for updating a `Snooze`. The field, `snooze.name` +// identifies the `Snooze` to be updated. The remainder of `snooze` gives the +// content the `Snooze` in question will be assigned. +// +// What fields can be updated depends on the start time and end time of the +// `Snooze`. +// +// * end time is in the past: These `Snooze`s are considered +// read-only and cannot be updated. +// * start time is in the past and end time is in the future: `display_name` +// and `interval.end_time` can be updated. +// * start time is in the future: `display_name`, `interval.start_time` and +// `interval.end_time` can be updated. +message UpdateSnoozeRequest { + // Required. The `Snooze` to update. Must have the name field present. + Snooze snooze = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The fields to update. + // + // For each field listed in `update_mask`: + // + // * If the `Snooze` object supplied in the `UpdateSnoozeRequest` has a + // value for that field, the value of the field in the existing `Snooze` + // will be set to the value of the field in the supplied `Snooze`. + // * If the field does not have a value in the supplied `Snooze`, the field + // in the existing `Snooze` is set to its default value. + // + // Fields not listed retain their existing value. + // + // The following are the field names that are accepted in `update_mask`: + // + // * `display_name` + // * `interval.start_time` + // * `interval.end_time` + // + // That said, the start time and end time of the `Snooze` determines which + // fields can legally be updated. Before attempting an update, users should + // consult the documentation for `UpdateSnoozeRequest`, which talks about + // which fields can be updated. + google.protobuf.FieldMask update_mask = 2 + [(google.api.field_behavior) = REQUIRED]; +} diff --git a/node_modules/google-gax/build/protos/google/monitoring/v3/span_context.proto b/node_modules/google-gax/build/protos/google/monitoring/v3/span_context.proto new file mode 100644 index 0000000..2488e5d --- /dev/null +++ b/node_modules/google-gax/build/protos/google/monitoring/v3/span_context.proto @@ -0,0 +1,45 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.monitoring.v3; + +option csharp_namespace = "Google.Cloud.Monitoring.V3"; +option go_package = "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb;monitoringpb"; +option java_multiple_files = true; +option java_outer_classname = "SpanContextProto"; +option java_package = "com.google.monitoring.v3"; +option php_namespace = "Google\\Cloud\\Monitoring\\V3"; +option ruby_package = "Google::Cloud::Monitoring::V3"; + +// The context of a span. This is attached to an +// [Exemplar][google.api.Distribution.Exemplar] +// in [Distribution][google.api.Distribution] values during aggregation. +// +// It contains the name of a span with format: +// +// projects/[PROJECT_ID_OR_NUMBER]/traces/[TRACE_ID]/spans/[SPAN_ID] +message SpanContext { + // The resource name of the span. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/traces/[TRACE_ID]/spans/[SPAN_ID] + // + // `[TRACE_ID]` is a unique identifier for a trace within a project; + // it is a 32-character hexadecimal encoding of a 16-byte array. + // + // `[SPAN_ID]` is a unique identifier for a span within a trace; it + // is a 16-character hexadecimal encoding of an 8-byte array. + string span_name = 1; +} diff --git a/node_modules/google-gax/build/protos/google/monitoring/v3/uptime.proto b/node_modules/google-gax/build/protos/google/monitoring/v3/uptime.proto new file mode 100644 index 0000000..81efb60 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/monitoring/v3/uptime.proto @@ -0,0 +1,564 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.monitoring.v3; + +import "google/api/field_behavior.proto"; +import "google/api/monitored_resource.proto"; +import "google/api/resource.proto"; +import "google/protobuf/duration.proto"; + +option csharp_namespace = "Google.Cloud.Monitoring.V3"; +option go_package = "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb;monitoringpb"; +option java_multiple_files = true; +option java_outer_classname = "UptimeProto"; +option java_package = "com.google.monitoring.v3"; +option php_namespace = "Google\\Cloud\\Monitoring\\V3"; +option ruby_package = "Google::Cloud::Monitoring::V3"; + +// An internal checker allows Uptime checks to run on private/internal GCP +// resources. +message InternalChecker { + option deprecated = true; + + // Operational states for an internal checker. + enum State { + // An internal checker should never be in the unspecified state. + UNSPECIFIED = 0; + + // The checker is being created, provisioned, and configured. A checker in + // this state can be returned by `ListInternalCheckers` or + // `GetInternalChecker`, as well as by examining the [long running + // Operation](https://cloud.google.com/apis/design/design_patterns#long_running_operations) + // that created it. + CREATING = 1; + + // The checker is running and available for use. A checker in this state + // can be returned by `ListInternalCheckers` or `GetInternalChecker` as + // well as by examining the [long running + // Operation](https://cloud.google.com/apis/design/design_patterns#long_running_operations) + // that created it. + // If a checker is being torn down, it is neither visible nor usable, so + // there is no "deleting" or "down" state. + RUNNING = 2; + } + + // A unique resource name for this InternalChecker. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/internalCheckers/[INTERNAL_CHECKER_ID] + // + // `[PROJECT_ID_OR_NUMBER]` is the Cloud Monitoring Metrics Scope project for + // the Uptime check config associated with the internal checker. + string name = 1; + + // The checker's human-readable name. The display name + // should be unique within a Cloud Monitoring Metrics Scope in order to make + // it easier to identify; however, uniqueness is not enforced. + string display_name = 2; + + // The [GCP VPC network](https://cloud.google.com/vpc/docs/vpc) where the + // internal resource lives (ex: "default"). + string network = 3; + + // The GCP zone the Uptime check should egress from. Only respected for + // internal Uptime checks, where internal_network is specified. + string gcp_zone = 4; + + // The GCP project ID where the internal checker lives. Not necessary + // the same as the Metrics Scope project. + string peer_project_id = 6; + + // The current operational state of the internal checker. + State state = 7; +} + +// This message configures which resources and services to monitor for +// availability. +message UptimeCheckConfig { + option (google.api.resource) = { + type: "monitoring.googleapis.com/UptimeCheckConfig" + pattern: "projects/{project}/uptimeCheckConfigs/{uptime_check_config}" + pattern: "organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}" + pattern: "folders/{folder}/uptimeCheckConfigs/{uptime_check_config}" + pattern: "*" + }; + + // The resource submessage for group checks. It can be used instead of a + // monitored resource, when multiple resources are being monitored. + message ResourceGroup { + // The group of resources being monitored. Should be only the `[GROUP_ID]`, + // and not the full-path + // `projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID]`. + string group_id = 1; + + // The resource type of the group members. + GroupResourceType resource_type = 2; + } + + // Information involved in sending ICMP pings alongside public HTTP/TCP + // checks. For HTTP, the pings are performed for each part of the redirect + // chain. + message PingConfig { + // Number of ICMP pings. A maximum of 3 ICMP pings is currently supported. + int32 pings_count = 1; + } + + // Information involved in an HTTP/HTTPS Uptime check request. + message HttpCheck { + // The HTTP request method options. + enum RequestMethod { + // No request method specified. + METHOD_UNSPECIFIED = 0; + + // GET request. + GET = 1; + + // POST request. + POST = 2; + } + + // The authentication parameters to provide to the specified resource or + // URL that requires a username and password. Currently, only + // [Basic HTTP authentication](https://tools.ietf.org/html/rfc7617) is + // supported in Uptime checks. + message BasicAuthentication { + // The username to use when authenticating with the HTTP server. + string username = 1; + + // The password to use when authenticating with the HTTP server. + string password = 2; + } + + // Header options corresponding to the content type of a HTTP request body. + enum ContentType { + // No content type specified. + TYPE_UNSPECIFIED = 0; + + // `body` is in URL-encoded form. Equivalent to setting the `Content-Type` + // to `application/x-www-form-urlencoded` in the HTTP request. + URL_ENCODED = 1; + + // `body` is in `custom_content_type` form. Equivalent to setting the + // `Content-Type` to the contents of `custom_content_type` in the HTTP + // request. + USER_PROVIDED = 2; + } + + // A status to accept. Either a status code class like "2xx", or an integer + // status code like "200". + message ResponseStatusCode { + // An HTTP status code class. + enum StatusClass { + // Default value that matches no status codes. + STATUS_CLASS_UNSPECIFIED = 0; + + // The class of status codes between 100 and 199. + STATUS_CLASS_1XX = 100; + + // The class of status codes between 200 and 299. + STATUS_CLASS_2XX = 200; + + // The class of status codes between 300 and 399. + STATUS_CLASS_3XX = 300; + + // The class of status codes between 400 and 499. + STATUS_CLASS_4XX = 400; + + // The class of status codes between 500 and 599. + STATUS_CLASS_5XX = 500; + + // The class of all status codes. + STATUS_CLASS_ANY = 1000; + } + + // Either a specific value or a class of status codes. + oneof status_code { + // A status code to accept. + int32 status_value = 1; + + // A class of status codes to accept. + StatusClass status_class = 2; + } + } + + // The HTTP request method to use for the check. If set to + // `METHOD_UNSPECIFIED` then `request_method` defaults to `GET`. + RequestMethod request_method = 8; + + // If `true`, use HTTPS instead of HTTP to run the check. + bool use_ssl = 1; + + // Optional (defaults to "/"). The path to the page against which to run + // the check. Will be combined with the `host` (specified within the + // `monitored_resource`) and `port` to construct the full URL. If the + // provided path does not begin with "/", a "/" will be prepended + // automatically. + string path = 2; + + // Optional (defaults to 80 when `use_ssl` is `false`, and 443 when + // `use_ssl` is `true`). The TCP port on the HTTP server against which to + // run the check. Will be combined with host (specified within the + // `monitored_resource`) and `path` to construct the full URL. + int32 port = 3; + + // The authentication information. Optional when creating an HTTP check; + // defaults to empty. + BasicAuthentication auth_info = 4; + + // Boolean specifying whether to encrypt the header information. + // Encryption should be specified for any headers related to authentication + // that you do not wish to be seen when retrieving the configuration. The + // server will be responsible for encrypting the headers. + // On Get/List calls, if `mask_headers` is set to `true` then the headers + // will be obscured with `******.` + bool mask_headers = 5; + + // The list of headers to send as part of the Uptime check request. + // If two headers have the same key and different values, they should + // be entered as a single header, with the value being a comma-separated + // list of all the desired values as described at + // https://www.w3.org/Protocols/rfc2616/rfc2616.txt (page 31). + // Entering two separate headers with the same key in a Create call will + // cause the first to be overwritten by the second. + // The maximum number of headers allowed is 100. + map headers = 6; + + // The content type header to use for the check. The following + // configurations result in errors: + // 1. Content type is specified in both the `headers` field and the + // `content_type` field. + // 2. Request method is `GET` and `content_type` is not `TYPE_UNSPECIFIED` + // 3. Request method is `POST` and `content_type` is `TYPE_UNSPECIFIED`. + // 4. Request method is `POST` and a "Content-Type" header is provided via + // `headers` field. The `content_type` field should be used instead. + ContentType content_type = 9; + + // A user provided content type header to use for the check. The invalid + // configurations outlined in the `content_type` field apply to + // `custom_content_type`, as well as the following: + // 1. `content_type` is `URL_ENCODED` and `custom_content_type` is set. + // 2. `content_type` is `USER_PROVIDED` and `custom_content_type` is not + // set. + string custom_content_type = 13; + + // Boolean specifying whether to include SSL certificate validation as a + // part of the Uptime check. Only applies to checks where + // `monitored_resource` is set to `uptime_url`. If `use_ssl` is `false`, + // setting `validate_ssl` to `true` has no effect. + bool validate_ssl = 7; + + // The request body associated with the HTTP POST request. If `content_type` + // is `URL_ENCODED`, the body passed in must be URL-encoded. Users can + // provide a `Content-Length` header via the `headers` field or the API will + // do so. If the `request_method` is `GET` and `body` is not empty, the API + // will return an error. The maximum byte size is 1 megabyte. + // + // Note: If client libraries aren't used (which performs the conversion + // automatically) base64 encode your `body` data since the field is of + // `bytes` type. + bytes body = 10; + + // If present, the check will only pass if the HTTP response status code is + // in this set of status codes. If empty, the HTTP status code will only + // pass if the HTTP status code is 200-299. + repeated ResponseStatusCode accepted_response_status_codes = 11; + + // Contains information needed to add pings to an HTTP check. + PingConfig ping_config = 12; + } + + // Information required for a TCP Uptime check request. + message TcpCheck { + // The TCP port on the server against which to run the check. Will be + // combined with host (specified within the `monitored_resource`) to + // construct the full URL. Required. + int32 port = 1; + + // Contains information needed to add pings to a TCP check. + PingConfig ping_config = 2; + } + + // Optional. Used to perform content matching. This allows matching based on + // substrings and regular expressions, together with their negations. Only the + // first 4 MB of an HTTP or HTTPS check's response (and the first + // 1 MB of a TCP check's response) are examined for purposes of content + // matching. + message ContentMatcher { + // Options to perform content matching. + enum ContentMatcherOption { + // No content matcher type specified (maintained for backward + // compatibility, but deprecated for future use). + // Treated as `CONTAINS_STRING`. + CONTENT_MATCHER_OPTION_UNSPECIFIED = 0; + + // Selects substring matching. The match succeeds if the output contains + // the `content` string. This is the default value for checks without + // a `matcher` option, or where the value of `matcher` is + // `CONTENT_MATCHER_OPTION_UNSPECIFIED`. + CONTAINS_STRING = 1; + + // Selects negation of substring matching. The match succeeds if the + // output does _NOT_ contain the `content` string. + NOT_CONTAINS_STRING = 2; + + // Selects regular-expression matching. The match succeeds if the output + // matches the regular expression specified in the `content` string. + // Regex matching is only supported for HTTP/HTTPS checks. + MATCHES_REGEX = 3; + + // Selects negation of regular-expression matching. The match succeeds if + // the output does _NOT_ match the regular expression specified in the + // `content` string. Regex matching is only supported for HTTP/HTTPS + // checks. + NOT_MATCHES_REGEX = 4; + + // Selects JSONPath matching. See `JsonPathMatcher` for details on when + // the match succeeds. JSONPath matching is only supported for HTTP/HTTPS + // checks. + MATCHES_JSON_PATH = 5; + + // Selects JSONPath matching. See `JsonPathMatcher` for details on when + // the match succeeds. Succeeds when output does _NOT_ match as specified. + // JSONPath is only supported for HTTP/HTTPS checks. + NOT_MATCHES_JSON_PATH = 6; + } + + // Information needed to perform a JSONPath content match. + // Used for `ContentMatcherOption::MATCHES_JSON_PATH` and + // `ContentMatcherOption::NOT_MATCHES_JSON_PATH`. + message JsonPathMatcher { + // Options to perform JSONPath content matching. + enum JsonPathMatcherOption { + // No JSONPath matcher type specified (not valid). + JSON_PATH_MATCHER_OPTION_UNSPECIFIED = 0; + + // Selects 'exact string' matching. The match succeeds if the content at + // the `json_path` within the output is exactly the same as the + // `content` string. + EXACT_MATCH = 1; + + // Selects regular-expression matching. The match succeeds if the + // content at the `json_path` within the output matches the regular + // expression specified in the `content` string. + REGEX_MATCH = 2; + } + + // JSONPath within the response output pointing to the expected + // `ContentMatcher::content` to match against. + string json_path = 1; + + // The type of JSONPath match that will be applied to the JSON output + // (`ContentMatcher.content`) + JsonPathMatcherOption json_matcher = 2; + } + + // String, regex or JSON content to match. Maximum 1024 bytes. An empty + // `content` string indicates no content matching is to be performed. + string content = 1; + + // The type of content matcher that will be applied to the server output, + // compared to the `content` string when the check is run. + ContentMatcherOption matcher = 2; + + // Certain `ContentMatcherOption` types require additional information. + // `MATCHES_JSON_PATH` or `NOT_MATCHES_JSON_PATH` require a + // `JsonPathMatcher`; not used for other options. + oneof additional_matcher_info { + // Matcher information for `MATCHES_JSON_PATH` and `NOT_MATCHES_JSON_PATH` + JsonPathMatcher json_path_matcher = 3; + } + } + + // What kind of checkers are available to be used by the check. + enum CheckerType { + // The default checker type. Currently converted to `STATIC_IP_CHECKERS` + // on creation, the default conversion behavior may change in the future. + CHECKER_TYPE_UNSPECIFIED = 0; + + // `STATIC_IP_CHECKERS` are used for uptime checks that perform egress + // across the public internet. `STATIC_IP_CHECKERS` use the static IP + // addresses returned by `ListUptimeCheckIps`. + STATIC_IP_CHECKERS = 1; + + // `VPC_CHECKERS` are used for uptime checks that perform egress using + // Service Directory and private network access. When using `VPC_CHECKERS`, + // the monitored resource type must be `servicedirectory_service`. + VPC_CHECKERS = 3; + } + + // A unique resource name for this Uptime check configuration. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/uptimeCheckConfigs/[UPTIME_CHECK_ID] + // + // `[PROJECT_ID_OR_NUMBER]` is the Workspace host project associated with the + // Uptime check. + // + // This field should be omitted when creating the Uptime check configuration; + // on create, the resource name is assigned by the server and included in the + // response. + string name = 1; + + // A human-friendly name for the Uptime check configuration. The display name + // should be unique within a Cloud Monitoring Workspace in order to make it + // easier to identify; however, uniqueness is not enforced. Required. + string display_name = 2; + + // The resource the check is checking. Required. + oneof resource { + // The [monitored + // resource](https://cloud.google.com/monitoring/api/resources) associated + // with the configuration. + // The following monitored resource types are valid for this field: + // `uptime_url`, + // `gce_instance`, + // `gae_app`, + // `aws_ec2_instance`, + // `aws_elb_load_balancer` + // `k8s_service` + // `servicedirectory_service` + // `cloud_run_revision` + google.api.MonitoredResource monitored_resource = 3; + + // The group resource associated with the configuration. + ResourceGroup resource_group = 4; + } + + // The type of Uptime check request. + oneof check_request_type { + // Contains information needed to make an HTTP or HTTPS check. + HttpCheck http_check = 5; + + // Contains information needed to make a TCP check. + TcpCheck tcp_check = 6; + } + + // How often, in seconds, the Uptime check is performed. + // Currently, the only supported values are `60s` (1 minute), `300s` + // (5 minutes), `600s` (10 minutes), and `900s` (15 minutes). Optional, + // defaults to `60s`. + google.protobuf.Duration period = 7; + + // The maximum amount of time to wait for the request to complete (must be + // between 1 and 60 seconds). Required. + google.protobuf.Duration timeout = 8; + + // The content that is expected to appear in the data returned by the target + // server against which the check is run. Currently, only the first entry + // in the `content_matchers` list is supported, and additional entries will + // be ignored. This field is optional and should only be specified if a + // content match is required as part of the/ Uptime check. + repeated ContentMatcher content_matchers = 9; + + // The type of checkers to use to execute the Uptime check. + CheckerType checker_type = 17; + + // The list of regions from which the check will be run. + // Some regions contain one location, and others contain more than one. + // If this field is specified, enough regions must be provided to include a + // minimum of 3 locations. Not specifying this field will result in Uptime + // checks running from all available regions. + repeated UptimeCheckRegion selected_regions = 10; + + // If this is `true`, then checks are made only from the 'internal_checkers'. + // If it is `false`, then checks are made only from the 'selected_regions'. + // It is an error to provide 'selected_regions' when is_internal is `true`, + // or to provide 'internal_checkers' when is_internal is `false`. + bool is_internal = 15 [deprecated = true]; + + // The internal checkers that this check will egress from. If `is_internal` is + // `true` and this list is empty, the check will egress from all the + // InternalCheckers configured for the project that owns this + // `UptimeCheckConfig`. + repeated InternalChecker internal_checkers = 14 [deprecated = true]; + + // User-supplied key/value data to be used for organizing and + // identifying the `UptimeCheckConfig` objects. + // + // The field can contain up to 64 entries. Each key and value is limited to + // 63 Unicode characters or 128 bytes, whichever is smaller. Labels and + // values can contain only lowercase letters, numerals, underscores, and + // dashes. Keys must begin with a letter. + map user_labels = 20; +} + +// Contains the region, location, and list of IP +// addresses where checkers in the location run from. +message UptimeCheckIp { + // A broad region category in which the IP address is located. + UptimeCheckRegion region = 1; + + // A more specific location within the region that typically encodes + // a particular city/town/metro (and its containing state/province or country) + // within the broader umbrella region category. + string location = 2; + + // The IP address from which the Uptime check originates. This is a fully + // specified IP address (not an IP address range). Most IP addresses, as of + // this publication, are in IPv4 format; however, one should not rely on the + // IP addresses being in IPv4 format indefinitely, and should support + // interpreting this field in either IPv4 or IPv6 format. + string ip_address = 3; +} + +// The regions from which an Uptime check can be run. +enum UptimeCheckRegion { + // Default value if no region is specified. Will result in Uptime checks + // running from all regions. + REGION_UNSPECIFIED = 0; + + // Allows checks to run from locations within the United States of America. + USA = 1; + + // Allows checks to run from locations within the continent of Europe. + EUROPE = 2; + + // Allows checks to run from locations within the continent of South + // America. + SOUTH_AMERICA = 3; + + // Allows checks to run from locations within the Asia Pacific area (ex: + // Singapore). + ASIA_PACIFIC = 4; + + // Allows checks to run from locations within the western United States of + // America + USA_OREGON = 5; + + // Allows checks to run from locations within the central United States of + // America + USA_IOWA = 6; + + // Allows checks to run from locations within the eastern United States of + // America + USA_VIRGINIA = 7; +} + +// The supported resource types that can be used as values of +// `group_resource.resource_type`. +// `INSTANCE` includes `gce_instance` and `aws_ec2_instance` resource types. +// The resource types `gae_app` and `uptime_url` are not valid here because +// group checks on App Engine modules and URLs are not allowed. +enum GroupResourceType { + // Default value (not valid). + RESOURCE_TYPE_UNSPECIFIED = 0; + + // A group of instances from Google Cloud Platform (GCP) or + // Amazon Web Services (AWS). + INSTANCE = 1; + + // A group of Amazon ELB load balancers. + AWS_ELB_LOAD_BALANCER = 2; +} diff --git a/node_modules/google-gax/build/protos/google/monitoring/v3/uptime_service.proto b/node_modules/google-gax/build/protos/google/monitoring/v3/uptime_service.proto new file mode 100644 index 0000000..391441b --- /dev/null +++ b/node_modules/google-gax/build/protos/google/monitoring/v3/uptime_service.proto @@ -0,0 +1,259 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.monitoring.v3; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/monitoring/v3/uptime.proto"; +import "google/protobuf/empty.proto"; +import "google/protobuf/field_mask.proto"; + +option csharp_namespace = "Google.Cloud.Monitoring.V3"; +option go_package = "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb;monitoringpb"; +option java_multiple_files = true; +option java_outer_classname = "UptimeServiceProto"; +option java_package = "com.google.monitoring.v3"; +option php_namespace = "Google\\Cloud\\Monitoring\\V3"; +option ruby_package = "Google::Cloud::Monitoring::V3"; + +// The UptimeCheckService API is used to manage (list, create, delete, edit) +// Uptime check configurations in the Cloud Monitoring product. An Uptime +// check is a piece of configuration that determines which resources and +// services to monitor for availability. These configurations can also be +// configured interactively by navigating to the [Cloud console] +// (https://console.cloud.google.com), selecting the appropriate project, +// clicking on "Monitoring" on the left-hand side to navigate to Cloud +// Monitoring, and then clicking on "Uptime". +service UptimeCheckService { + option (google.api.default_host) = "monitoring.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/monitoring," + "https://www.googleapis.com/auth/monitoring.read"; + + // Lists the existing valid Uptime check configurations for the project + // (leaving out any invalid configurations). + rpc ListUptimeCheckConfigs(ListUptimeCheckConfigsRequest) + returns (ListUptimeCheckConfigsResponse) { + option (google.api.http) = { + get: "/v3/{parent=projects/*}/uptimeCheckConfigs" + }; + option (google.api.method_signature) = "parent"; + } + + // Gets a single Uptime check configuration. + rpc GetUptimeCheckConfig(GetUptimeCheckConfigRequest) + returns (UptimeCheckConfig) { + option (google.api.http) = { + get: "/v3/{name=projects/*/uptimeCheckConfigs/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Creates a new Uptime check configuration. + rpc CreateUptimeCheckConfig(CreateUptimeCheckConfigRequest) + returns (UptimeCheckConfig) { + option (google.api.http) = { + post: "/v3/{parent=projects/*}/uptimeCheckConfigs" + body: "uptime_check_config" + }; + option (google.api.method_signature) = "parent,uptime_check_config"; + } + + // Updates an Uptime check configuration. You can either replace the entire + // configuration with a new one or replace only certain fields in the current + // configuration by specifying the fields to be updated via `updateMask`. + // Returns the updated configuration. + rpc UpdateUptimeCheckConfig(UpdateUptimeCheckConfigRequest) + returns (UptimeCheckConfig) { + option (google.api.http) = { + patch: "/v3/{uptime_check_config.name=projects/*/uptimeCheckConfigs/*}" + body: "uptime_check_config" + }; + option (google.api.method_signature) = "uptime_check_config"; + } + + // Deletes an Uptime check configuration. Note that this method will fail + // if the Uptime check configuration is referenced by an alert policy or + // other dependent configs that would be rendered invalid by the deletion. + rpc DeleteUptimeCheckConfig(DeleteUptimeCheckConfigRequest) + returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v3/{name=projects/*/uptimeCheckConfigs/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Returns the list of IP addresses that checkers run from + rpc ListUptimeCheckIps(ListUptimeCheckIpsRequest) + returns (ListUptimeCheckIpsResponse) { + option (google.api.http) = { + get: "/v3/uptimeCheckIps" + }; + } +} + +// The protocol for the `ListUptimeCheckConfigs` request. +message ListUptimeCheckConfigsRequest { + // Required. The + // [project](https://cloud.google.com/monitoring/api/v3#project_name) whose + // Uptime check configurations are listed. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER] + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "monitoring.googleapis.com/UptimeCheckConfig" + } + ]; + + // If provided, this field specifies the criteria that must be met by + // uptime checks to be included in the response. + // + // For more details, see [Filtering + // syntax](https://cloud.google.com/monitoring/api/v3/sorting-and-filtering#filter_syntax). + string filter = 2; + + // The maximum number of results to return in a single response. The server + // may further constrain the maximum number of results returned in a single + // page. If the page_size is <=0, the server will decide the number of results + // to be returned. + int32 page_size = 3; + + // If this field is not empty then it must contain the `nextPageToken` value + // returned by a previous call to this method. Using this field causes the + // method to return more results from the previous method call. + string page_token = 4; +} + +// The protocol for the `ListUptimeCheckConfigs` response. +message ListUptimeCheckConfigsResponse { + // The returned Uptime check configurations. + repeated UptimeCheckConfig uptime_check_configs = 1; + + // This field represents the pagination token to retrieve the next page of + // results. If the value is empty, it means no further results for the + // request. To retrieve the next page of results, the value of the + // next_page_token is passed to the subsequent List method call (in the + // request message's page_token field). + string next_page_token = 2; + + // The total number of Uptime check configurations for the project, + // irrespective of any pagination. + int32 total_size = 3; +} + +// The protocol for the `GetUptimeCheckConfig` request. +message GetUptimeCheckConfigRequest { + // Required. The Uptime check configuration to retrieve. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/uptimeCheckConfigs/[UPTIME_CHECK_ID] + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/UptimeCheckConfig" + } + ]; +} + +// The protocol for the `CreateUptimeCheckConfig` request. +message CreateUptimeCheckConfigRequest { + // Required. The + // [project](https://cloud.google.com/monitoring/api/v3#project_name) in which + // to create the Uptime check. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER] + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "monitoring.googleapis.com/UptimeCheckConfig" + } + ]; + + // Required. The new Uptime check configuration. + UptimeCheckConfig uptime_check_config = 2 + [(google.api.field_behavior) = REQUIRED]; +} + +// The protocol for the `UpdateUptimeCheckConfig` request. +message UpdateUptimeCheckConfigRequest { + // Optional. If present, only the listed fields in the current Uptime check + // configuration are updated with values from the new configuration. If this + // field is empty, then the current configuration is completely replaced with + // the new configuration. + google.protobuf.FieldMask update_mask = 2; + + // Required. If an `updateMask` has been specified, this field gives + // the values for the set of fields mentioned in the `updateMask`. If an + // `updateMask` has not been given, this Uptime check configuration replaces + // the current configuration. If a field is mentioned in `updateMask` but + // the corresponding field is omitted in this partial Uptime check + // configuration, it has the effect of deleting/clearing the field from the + // configuration on the server. + // + // The following fields can be updated: `display_name`, + // `http_check`, `tcp_check`, `timeout`, `content_matchers`, and + // `selected_regions`. + UptimeCheckConfig uptime_check_config = 3 + [(google.api.field_behavior) = REQUIRED]; +} + +// The protocol for the `DeleteUptimeCheckConfig` request. +message DeleteUptimeCheckConfigRequest { + // Required. The Uptime check configuration to delete. The format is: + // + // projects/[PROJECT_ID_OR_NUMBER]/uptimeCheckConfigs/[UPTIME_CHECK_ID] + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "monitoring.googleapis.com/UptimeCheckConfig" + } + ]; +} + +// The protocol for the `ListUptimeCheckIps` request. +message ListUptimeCheckIpsRequest { + // The maximum number of results to return in a single response. The server + // may further constrain the maximum number of results returned in a single + // page. If the page_size is <=0, the server will decide the number of results + // to be returned. + // NOTE: this field is not yet implemented + int32 page_size = 2; + + // If this field is not empty then it must contain the `nextPageToken` value + // returned by a previous call to this method. Using this field causes the + // method to return more results from the previous method call. + // NOTE: this field is not yet implemented + string page_token = 3; +} + +// The protocol for the `ListUptimeCheckIps` response. +message ListUptimeCheckIpsResponse { + // The returned list of IP addresses (including region and location) that the + // checkers run from. + repeated UptimeCheckIp uptime_check_ips = 1; + + // This field represents the pagination token to retrieve the next page of + // results. If the value is empty, it means no further results for the + // request. To retrieve the next page of results, the value of the + // next_page_token is passed to the subsequent List method call (in the + // request message's page_token field). + // NOTE: this field is not yet implemented + string next_page_token = 2; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/any.proto b/node_modules/google-gax/build/protos/google/protobuf/any.proto new file mode 100644 index 0000000..eff44e5 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/any.proto @@ -0,0 +1,162 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option go_package = "google.golang.org/protobuf/types/known/anypb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "AnyProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; + +// `Any` contains an arbitrary serialized protocol buffer message along with a +// URL that describes the type of the serialized message. +// +// Protobuf library provides support to pack/unpack Any values in the form +// of utility functions or additional generated methods of the Any type. +// +// Example 1: Pack and unpack a message in C++. +// +// Foo foo = ...; +// Any any; +// any.PackFrom(foo); +// ... +// if (any.UnpackTo(&foo)) { +// ... +// } +// +// Example 2: Pack and unpack a message in Java. +// +// Foo foo = ...; +// Any any = Any.pack(foo); +// ... +// if (any.is(Foo.class)) { +// foo = any.unpack(Foo.class); +// } +// // or ... +// if (any.isSameTypeAs(Foo.getDefaultInstance())) { +// foo = any.unpack(Foo.getDefaultInstance()); +// } +// +// Example 3: Pack and unpack a message in Python. +// +// foo = Foo(...) +// any = Any() +// any.Pack(foo) +// ... +// if any.Is(Foo.DESCRIPTOR): +// any.Unpack(foo) +// ... +// +// Example 4: Pack and unpack a message in Go +// +// foo := &pb.Foo{...} +// any, err := anypb.New(foo) +// if err != nil { +// ... +// } +// ... +// foo := &pb.Foo{} +// if err := any.UnmarshalTo(foo); err != nil { +// ... +// } +// +// The pack methods provided by protobuf library will by default use +// 'type.googleapis.com/full.type.name' as the type URL and the unpack +// methods only use the fully qualified type name after the last '/' +// in the type URL, for example "foo.bar.com/x/y.z" will yield type +// name "y.z". +// +// JSON +// ==== +// The JSON representation of an `Any` value uses the regular +// representation of the deserialized, embedded message, with an +// additional field `@type` which contains the type URL. Example: +// +// package google.profile; +// message Person { +// string first_name = 1; +// string last_name = 2; +// } +// +// { +// "@type": "type.googleapis.com/google.profile.Person", +// "firstName": , +// "lastName": +// } +// +// If the embedded message type is well-known and has a custom JSON +// representation, that representation will be embedded adding a field +// `value` which holds the custom JSON in addition to the `@type` +// field. Example (for message [google.protobuf.Duration][]): +// +// { +// "@type": "type.googleapis.com/google.protobuf.Duration", +// "value": "1.212s" +// } +// +message Any { + // A URL/resource name that uniquely identifies the type of the serialized + // protocol buffer message. This string must contain at least + // one "/" character. The last segment of the URL's path must represent + // the fully qualified name of the type (as in + // `path/google.protobuf.Duration`). The name should be in a canonical form + // (e.g., leading "." is not accepted). + // + // In practice, teams usually precompile into the binary all types that they + // expect it to use in the context of Any. However, for URLs which use the + // scheme `http`, `https`, or no scheme, one can optionally set up a type + // server that maps type URLs to message definitions as follows: + // + // * If no scheme is provided, `https` is assumed. + // * An HTTP GET on the URL must yield a [google.protobuf.Type][] + // value in binary format, or produce an error. + // * Applications are allowed to cache lookup results based on the + // URL, or have them precompiled into a binary to avoid any + // lookup. Therefore, binary compatibility needs to be preserved + // on changes to types. (Use versioned type names to manage + // breaking changes.) + // + // Note: this functionality is not currently available in the official + // protobuf release, and it is not used for type URLs beginning with + // type.googleapis.com. As of May 2023, there are no widely used type server + // implementations and no plans to implement one. + // + // Schemes other than `http`, `https` (or the empty scheme) might be + // used with implementation specific semantics. + // + string type_url = 1; + + // Must be a valid serialized protocol buffer of the above specified type. + bytes value = 2; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/api.proto b/node_modules/google-gax/build/protos/google/protobuf/api.proto new file mode 100644 index 0000000..4222351 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/api.proto @@ -0,0 +1,207 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +import "google/protobuf/source_context.proto"; +import "google/protobuf/type.proto"; + +option java_package = "com.google.protobuf"; +option java_outer_classname = "ApiProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; +option go_package = "google.golang.org/protobuf/types/known/apipb"; + +// Api is a light-weight descriptor for an API Interface. +// +// Interfaces are also described as "protocol buffer services" in some contexts, +// such as by the "service" keyword in a .proto file, but they are different +// from API Services, which represent a concrete implementation of an interface +// as opposed to simply a description of methods and bindings. They are also +// sometimes simply referred to as "APIs" in other contexts, such as the name of +// this message itself. See https://cloud.google.com/apis/design/glossary for +// detailed terminology. +message Api { + // The fully qualified name of this interface, including package name + // followed by the interface's simple name. + string name = 1; + + // The methods of this interface, in unspecified order. + repeated Method methods = 2; + + // Any metadata attached to the interface. + repeated Option options = 3; + + // A version string for this interface. If specified, must have the form + // `major-version.minor-version`, as in `1.10`. If the minor version is + // omitted, it defaults to zero. If the entire version field is empty, the + // major version is derived from the package name, as outlined below. If the + // field is not empty, the version in the package name will be verified to be + // consistent with what is provided here. + // + // The versioning schema uses [semantic + // versioning](http://semver.org) where the major version number + // indicates a breaking change and the minor version an additive, + // non-breaking change. Both version numbers are signals to users + // what to expect from different versions, and should be carefully + // chosen based on the product plan. + // + // The major version is also reflected in the package name of the + // interface, which must end in `v`, as in + // `google.feature.v1`. For major versions 0 and 1, the suffix can + // be omitted. Zero major versions must only be used for + // experimental, non-GA interfaces. + // + string version = 4; + + // Source context for the protocol buffer service represented by this + // message. + SourceContext source_context = 5; + + // Included interfaces. See [Mixin][]. + repeated Mixin mixins = 6; + + // The source syntax of the service. + Syntax syntax = 7; +} + +// Method represents a method of an API interface. +message Method { + // The simple name of this method. + string name = 1; + + // A URL of the input message type. + string request_type_url = 2; + + // If true, the request is streamed. + bool request_streaming = 3; + + // The URL of the output message type. + string response_type_url = 4; + + // If true, the response is streamed. + bool response_streaming = 5; + + // Any metadata attached to the method. + repeated Option options = 6; + + // The source syntax of this method. + Syntax syntax = 7; +} + +// Declares an API Interface to be included in this interface. The including +// interface must redeclare all the methods from the included interface, but +// documentation and options are inherited as follows: +// +// - If after comment and whitespace stripping, the documentation +// string of the redeclared method is empty, it will be inherited +// from the original method. +// +// - Each annotation belonging to the service config (http, +// visibility) which is not set in the redeclared method will be +// inherited. +// +// - If an http annotation is inherited, the path pattern will be +// modified as follows. Any version prefix will be replaced by the +// version of the including interface plus the [root][] path if +// specified. +// +// Example of a simple mixin: +// +// package google.acl.v1; +// service AccessControl { +// // Get the underlying ACL object. +// rpc GetAcl(GetAclRequest) returns (Acl) { +// option (google.api.http).get = "/v1/{resource=**}:getAcl"; +// } +// } +// +// package google.storage.v2; +// service Storage { +// rpc GetAcl(GetAclRequest) returns (Acl); +// +// // Get a data record. +// rpc GetData(GetDataRequest) returns (Data) { +// option (google.api.http).get = "/v2/{resource=**}"; +// } +// } +// +// Example of a mixin configuration: +// +// apis: +// - name: google.storage.v2.Storage +// mixins: +// - name: google.acl.v1.AccessControl +// +// The mixin construct implies that all methods in `AccessControl` are +// also declared with same name and request/response types in +// `Storage`. A documentation generator or annotation processor will +// see the effective `Storage.GetAcl` method after inherting +// documentation and annotations as follows: +// +// service Storage { +// // Get the underlying ACL object. +// rpc GetAcl(GetAclRequest) returns (Acl) { +// option (google.api.http).get = "/v2/{resource=**}:getAcl"; +// } +// ... +// } +// +// Note how the version in the path pattern changed from `v1` to `v2`. +// +// If the `root` field in the mixin is specified, it should be a +// relative path under which inherited HTTP paths are placed. Example: +// +// apis: +// - name: google.storage.v2.Storage +// mixins: +// - name: google.acl.v1.AccessControl +// root: acls +// +// This implies the following inherited HTTP annotation: +// +// service Storage { +// // Get the underlying ACL object. +// rpc GetAcl(GetAclRequest) returns (Acl) { +// option (google.api.http).get = "/v2/acls/{resource=**}:getAcl"; +// } +// ... +// } +message Mixin { + // The fully qualified name of the interface which is included. + string name = 1; + + // If non-empty specifies a path under which inherited HTTP paths + // are rooted. + string root = 2; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/bridge/message_set.proto b/node_modules/google-gax/build/protos/google/protobuf/bridge/message_set.proto new file mode 100644 index 0000000..83e8bb0 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/bridge/message_set.proto @@ -0,0 +1,76 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2007 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: kenton@google.com (Kenton Varda) +// +// This is proto2's version of MessageSet. See go/messageset to learn what +// MessageSets are and how they are used. +// +// In proto2, we implement MessageSet in terms of extensions, except with a +// special wire format for backwards-compatibility. To define a message that +// goes in a MessageSet in proto2, you must declare within that message's +// scope an extension of MessageSet named "message_set_extension" and with +// the field number matching the type ID. So, for example, this proto1 code: +// message Foo { +// enum TypeId { MESSAGE_TYPE_ID = 1234; } +// } +// becomes this proto2 code: +// message Foo { +// extend google.protobuf.bridge.MessageSet { +// optional Foo message_set_extension = 1234; +// } +// } +// +// Now you can use the usual proto2 extensions accessors to access this +// message. For example, the proto1 code: +// MessageSet mset; +// Foo* foo = mset.get_mutable(); +// becomes this proto2 code: +// google::protobuf::bridge::MessageSet mset; +// Foo* foo = mset.MutableExtension(Foo::message_set_extension); +// +// Of course, new code that doesn't have backwards-compatibility requirements +// should just use extensions themselves and not worry about MessageSet. + +syntax = "proto2"; + +package google.protobuf.bridge; + +option java_outer_classname = "MessageSetProtos"; +option java_multiple_files = true; +option cc_enable_arenas = true; +option objc_class_prefix = "GPB"; + +// This is proto2's version of MessageSet. +message MessageSet { + option message_set_wire_format = true; + + extensions 4 to max [verification = UNVERIFIED]; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/compiler/plugin.proto b/node_modules/google-gax/build/protos/google/protobuf/compiler/plugin.proto new file mode 100644 index 0000000..033fab2 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/compiler/plugin.proto @@ -0,0 +1,180 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +// Author: kenton@google.com (Kenton Varda) +// +// protoc (aka the Protocol Compiler) can be extended via plugins. A plugin is +// just a program that reads a CodeGeneratorRequest from stdin and writes a +// CodeGeneratorResponse to stdout. +// +// Plugins written using C++ can use google/protobuf/compiler/plugin.h instead +// of dealing with the raw protocol defined here. +// +// A plugin executable needs only to be placed somewhere in the path. The +// plugin should be named "protoc-gen-$NAME", and will then be used when the +// flag "--${NAME}_out" is passed to protoc. + +syntax = "proto2"; + +package google.protobuf.compiler; +option java_package = "com.google.protobuf.compiler"; +option java_outer_classname = "PluginProtos"; + +option csharp_namespace = "Google.Protobuf.Compiler"; +option go_package = "google.golang.org/protobuf/types/pluginpb"; + +import "google/protobuf/descriptor.proto"; + +// The version number of protocol compiler. +message Version { + optional int32 major = 1; + optional int32 minor = 2; + optional int32 patch = 3; + // A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should + // be empty for mainline stable releases. + optional string suffix = 4; +} + +// An encoded CodeGeneratorRequest is written to the plugin's stdin. +message CodeGeneratorRequest { + // The .proto files that were explicitly listed on the command-line. The + // code generator should generate code only for these files. Each file's + // descriptor will be included in proto_file, below. + repeated string file_to_generate = 1; + + // The generator parameter passed on the command-line. + optional string parameter = 2; + + // FileDescriptorProtos for all files in files_to_generate and everything + // they import. The files will appear in topological order, so each file + // appears before any file that imports it. + // + // Note: the files listed in files_to_generate will include runtime-retention + // options only, but all other files will include source-retention options. + // The source_file_descriptors field below is available in case you need + // source-retention options for files_to_generate. + // + // protoc guarantees that all proto_files will be written after + // the fields above, even though this is not technically guaranteed by the + // protobuf wire format. This theoretically could allow a plugin to stream + // in the FileDescriptorProtos and handle them one by one rather than read + // the entire set into memory at once. However, as of this writing, this + // is not similarly optimized on protoc's end -- it will store all fields in + // memory at once before sending them to the plugin. + // + // Type names of fields and extensions in the FileDescriptorProto are always + // fully qualified. + repeated FileDescriptorProto proto_file = 15; + + // File descriptors with all options, including source-retention options. + // These descriptors are only provided for the files listed in + // files_to_generate. + repeated FileDescriptorProto source_file_descriptors = 17; + + // The version number of protocol compiler. + optional Version compiler_version = 3; +} + +// The plugin writes an encoded CodeGeneratorResponse to stdout. +message CodeGeneratorResponse { + // Error message. If non-empty, code generation failed. The plugin process + // should exit with status code zero even if it reports an error in this way. + // + // This should be used to indicate errors in .proto files which prevent the + // code generator from generating correct code. Errors which indicate a + // problem in protoc itself -- such as the input CodeGeneratorRequest being + // unparseable -- should be reported by writing a message to stderr and + // exiting with a non-zero status code. + optional string error = 1; + + // A bitmask of supported features that the code generator supports. + // This is a bitwise "or" of values from the Feature enum. + optional uint64 supported_features = 2; + + // Sync with code_generator.h. + enum Feature { + FEATURE_NONE = 0; + FEATURE_PROTO3_OPTIONAL = 1; + FEATURE_SUPPORTS_EDITIONS = 2; + } + + // The minimum edition this plugin supports. This will be treated as an + // Edition enum, but we want to allow unknown values. It should be specified + // according the edition enum value, *not* the edition number. Only takes + // effect for plugins that have FEATURE_SUPPORTS_EDITIONS set. + optional int32 minimum_edition = 3; + + // The maximum edition this plugin supports. This will be treated as an + // Edition enum, but we want to allow unknown values. It should be specified + // according the edition enum value, *not* the edition number. Only takes + // effect for plugins that have FEATURE_SUPPORTS_EDITIONS set. + optional int32 maximum_edition = 4; + + // Represents a single generated file. + message File { + // The file name, relative to the output directory. The name must not + // contain "." or ".." components and must be relative, not be absolute (so, + // the file cannot lie outside the output directory). "/" must be used as + // the path separator, not "\". + // + // If the name is omitted, the content will be appended to the previous + // file. This allows the generator to break large files into small chunks, + // and allows the generated text to be streamed back to protoc so that large + // files need not reside completely in memory at one time. Note that as of + // this writing protoc does not optimize for this -- it will read the entire + // CodeGeneratorResponse before writing files to disk. + optional string name = 1; + + // If non-empty, indicates that the named file should already exist, and the + // content here is to be inserted into that file at a defined insertion + // point. This feature allows a code generator to extend the output + // produced by another code generator. The original generator may provide + // insertion points by placing special annotations in the file that look + // like: + // @@protoc_insertion_point(NAME) + // The annotation can have arbitrary text before and after it on the line, + // which allows it to be placed in a comment. NAME should be replaced with + // an identifier naming the point -- this is what other generators will use + // as the insertion_point. Code inserted at this point will be placed + // immediately above the line containing the insertion point (thus multiple + // insertions to the same point will come out in the order they were added). + // The double-@ is intended to make it unlikely that the generated code + // could contain things that look like insertion points by accident. + // + // For example, the C++ code generator places the following line in the + // .pb.h files that it generates: + // // @@protoc_insertion_point(namespace_scope) + // This line appears within the scope of the file's package namespace, but + // outside of any particular class. Another plugin can then specify the + // insertion_point "namespace_scope" to generate additional classes or + // other declarations that should be placed in this scope. + // + // Note that if the line containing the insertion point begins with + // whitespace, the same whitespace will be added to every line of the + // inserted text. This is useful for languages like Python, where + // indentation matters. In these languages, the insertion point comment + // should be indented the same amount as any inserted code will need to be + // in order to work correctly in that context. + // + // The code generator that generates the initial file and the one which + // inserts into it must both run as part of a single invocation of protoc. + // Code generators are executed in the order in which they appear on the + // command line. + // + // If |insertion_point| is present, |name| must also be present. + optional string insertion_point = 2; + + // The file contents. + optional string content = 15; + + // Information describing the file content being inserted. If an insertion + // point is used, this information will be appropriately offset and inserted + // into the code generation metadata for the generated files. + optional GeneratedCodeInfo generated_code_info = 16; + } + repeated File file = 15; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_code.proto b/node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_code.proto new file mode 100644 index 0000000..2167348 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_code.proto @@ -0,0 +1,77 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto3"; + +package A.B.C; + +import "ruby_generated_code_proto2_import.proto"; + +message TestMessage { + int32 optional_int32 = 1; + int64 optional_int64 = 2; + uint32 optional_uint32 = 3; + uint64 optional_uint64 = 4; + bool optional_bool = 5; + double optional_double = 6; + float optional_float = 7; + string optional_string = 8; + bytes optional_bytes = 9; + TestEnum optional_enum = 10; + TestMessage optional_msg = 11; + TestImportedMessage optional_proto2_submessage = 12; + + repeated int32 repeated_int32 = 21; + repeated int64 repeated_int64 = 22; + repeated uint32 repeated_uint32 = 23; + repeated uint64 repeated_uint64 = 24; + repeated bool repeated_bool = 25; + repeated double repeated_double = 26; + repeated float repeated_float = 27; + repeated string repeated_string = 28; + repeated bytes repeated_bytes = 29; + repeated TestEnum repeated_enum = 30; + repeated TestMessage repeated_msg = 31; + + oneof my_oneof { + int32 oneof_int32 = 41; + int64 oneof_int64 = 42; + uint32 oneof_uint32 = 43; + uint64 oneof_uint64 = 44; + bool oneof_bool = 45; + double oneof_double = 46; + float oneof_float = 47; + string oneof_string = 48; + bytes oneof_bytes = 49; + TestEnum oneof_enum = 50; + TestMessage oneof_msg = 51; + } + + map map_int32_string = 61; + map map_int64_string = 62; + map map_uint32_string = 63; + map map_uint64_string = 64; + map map_bool_string = 65; + map map_string_string = 66; + map map_string_msg = 67; + map map_string_enum = 68; + map map_string_int32 = 69; + map map_string_bool = 70; + + message NestedMessage { + int32 foo = 1; + } + + NestedMessage nested_message = 80; +} + +enum TestEnum { + Default = 0; + A = 1; + B = 2; + C = 3; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_code_proto2.proto b/node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_code_proto2.proto new file mode 100644 index 0000000..067c081 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_code_proto2.proto @@ -0,0 +1,78 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto2"; + +package A.B.C; + +import "ruby_generated_code_proto2_import.proto"; + +message TestMessage { + optional int32 optional_int32 = 1 [default = 1]; + optional int64 optional_int64 = 2 [default = 2]; + optional uint32 optional_uint32 = 3 [default = 3]; + optional uint64 optional_uint64 = 4 [default = 4]; + optional bool optional_bool = 5 [default = true]; + optional double optional_double = 6 [default = 6.0]; + optional float optional_float = 7 [default = 7.0]; + optional string optional_string = 8 [default = "default str"]; + optional bytes optional_bytes = 9 [default = "\0\1\2\100fubar"]; + optional TestEnum optional_enum = 10 [default = A]; + optional TestMessage optional_msg = 11; + optional TestImportedMessage optional_proto2_submessage = 12; + + repeated int32 repeated_int32 = 21; + repeated int64 repeated_int64 = 22; + repeated uint32 repeated_uint32 = 23; + repeated uint64 repeated_uint64 = 24; + repeated bool repeated_bool = 25; + repeated double repeated_double = 26; + repeated float repeated_float = 27; + repeated string repeated_string = 28; + repeated bytes repeated_bytes = 29; + repeated TestEnum repeated_enum = 30; + repeated TestMessage repeated_msg = 31; + + required int32 required_int32 = 41; + required int64 required_int64 = 42; + required uint32 required_uint32 = 43; + required uint64 required_uint64 = 44; + required bool required_bool = 45; + required double required_double = 46; + required float required_float = 47; + required string required_string = 48; + required bytes required_bytes = 49; + required TestEnum required_enum = 50; + required TestMessage required_msg = 51; + + oneof my_oneof { + int32 oneof_int32 = 61; + int64 oneof_int64 = 62; + uint32 oneof_uint32 = 63; + uint64 oneof_uint64 = 64; + bool oneof_bool = 65; + double oneof_double = 66; + float oneof_float = 67; + string oneof_string = 68; + bytes oneof_bytes = 69; + TestEnum oneof_enum = 70; + TestMessage oneof_msg = 71; + } + + message NestedMessage { + optional int32 foo = 1; + } + + optional NestedMessage nested_message = 80; +} + +enum TestEnum { + Default = 0; + A = 1; + B = 2; + C = 3; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_code_proto2_import.proto b/node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_code_proto2_import.proto new file mode 100644 index 0000000..6326ac2 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_code_proto2_import.proto @@ -0,0 +1,12 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto2"; + +package A.B.C; + +message TestImportedMessage {} diff --git a/node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit.proto b/node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit.proto new file mode 100644 index 0000000..a8b2255 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit.proto @@ -0,0 +1,16 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto3"; + +package one.two.a_three; + +option ruby_package = "A::B::C"; + +message Four { + string a_string = 1; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy.proto b/node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy.proto new file mode 100644 index 0000000..e190bf0 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy.proto @@ -0,0 +1,16 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto3"; + +package one.two.a_three.and; + +option ruby_package = "AA.BB.CC"; + +message Four { + string another_string = 1; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_pkg_implicit.proto b/node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_pkg_implicit.proto new file mode 100644 index 0000000..cced640 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/compiler/ruby/ruby_generated_pkg_implicit.proto @@ -0,0 +1,14 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto3"; + +package one.two.a_three; + +message Four { + string a_string = 1; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/cpp_features.proto b/node_modules/google-gax/build/protos/google/protobuf/cpp_features.proto new file mode 100644 index 0000000..64157ee --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/cpp_features.proto @@ -0,0 +1,45 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto2"; + +package pb; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FeatureSet { + optional CppFeatures cpp = 1000; +} + +message CppFeatures { + // Whether or not to treat an enum field as closed. This option is only + // applicable to enum fields, and will be removed in the future. It is + // consistent with the legacy behavior of using proto3 enum types for proto2 + // fields. + optional bool legacy_closed_enum = 1 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_FIELD, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "true" }, + edition_defaults = { edition: EDITION_PROTO3, value: "false" } + ]; + + enum StringType { + STRING_TYPE_UNKNOWN = 0; + VIEW = 1; + CORD = 2; + STRING = 3; + } + + optional StringType string_type = 2 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_FIELD, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "STRING" }, + edition_defaults = { edition: EDITION_2024, value: "VIEW" } + ]; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/descriptor.proto b/node_modules/google-gax/build/protos/google/protobuf/descriptor.proto new file mode 100644 index 0000000..cfd2cd4 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/descriptor.proto @@ -0,0 +1,1225 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. +// +// The messages in this file describe the definitions found in .proto files. +// A valid .proto file can be translated directly to a FileDescriptorProto +// without any other information (e.g. without reading its imports). + +syntax = "proto2"; + +package google.protobuf; + +option go_package = "google.golang.org/protobuf/types/descriptorpb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "DescriptorProtos"; +option csharp_namespace = "Google.Protobuf.Reflection"; +option objc_class_prefix = "GPB"; +option cc_enable_arenas = true; + +// descriptor.proto must be optimized for speed because reflection-based +// algorithms don't work during bootstrapping. +option optimize_for = SPEED; + +// The protocol compiler can output a FileDescriptorSet containing the .proto +// files it parses. +message FileDescriptorSet { + repeated FileDescriptorProto file = 1; +} + +// The full set of known editions. +enum Edition { + // A placeholder for an unknown edition value. + EDITION_UNKNOWN = 0; + + // Legacy syntax "editions". These pre-date editions, but behave much like + // distinct editions. These can't be used to specify the edition of proto + // files, but feature definitions must supply proto2/proto3 defaults for + // backwards compatibility. + EDITION_PROTO2 = 998; + EDITION_PROTO3 = 999; + + // Editions that have been released. The specific values are arbitrary and + // should not be depended on, but they will always be time-ordered for easy + // comparison. + EDITION_2023 = 1000; + EDITION_2024 = 1001; + + // Placeholder editions for testing feature resolution. These should not be + // used or relyed on outside of tests. + EDITION_1_TEST_ONLY = 1; + EDITION_2_TEST_ONLY = 2; + EDITION_99997_TEST_ONLY = 99997; + EDITION_99998_TEST_ONLY = 99998; + EDITION_99999_TEST_ONLY = 99999; + + // Placeholder for specifying unbounded edition support. This should only + // ever be used by plugins that can expect to never require any changes to + // support a new edition. + EDITION_MAX = 0x7FFFFFFF; +} + +// Describes a complete .proto file. +message FileDescriptorProto { + optional string name = 1; // file name, relative to root of source tree + optional string package = 2; // e.g. "foo", "foo.bar", etc. + + // Names of files imported by this file. + repeated string dependency = 3; + // Indexes of the public imported files in the dependency list above. + repeated int32 public_dependency = 10; + // Indexes of the weak imported files in the dependency list. + // For Google-internal migration only. Do not use. + repeated int32 weak_dependency = 11; + + // All top-level definitions in this file. + repeated DescriptorProto message_type = 4; + repeated EnumDescriptorProto enum_type = 5; + repeated ServiceDescriptorProto service = 6; + repeated FieldDescriptorProto extension = 7; + + optional FileOptions options = 8; + + // This field contains optional information about the original source code. + // You may safely remove this entire field without harming runtime + // functionality of the descriptors -- the information is needed only by + // development tools. + optional SourceCodeInfo source_code_info = 9; + + // The syntax of the proto file. + // The supported values are "proto2", "proto3", and "editions". + // + // If `edition` is present, this value must be "editions". + optional string syntax = 12; + + // The edition of the proto file. + optional Edition edition = 14; +} + +// Describes a message type. +message DescriptorProto { + optional string name = 1; + + repeated FieldDescriptorProto field = 2; + repeated FieldDescriptorProto extension = 6; + + repeated DescriptorProto nested_type = 3; + repeated EnumDescriptorProto enum_type = 4; + + message ExtensionRange { + optional int32 start = 1; // Inclusive. + optional int32 end = 2; // Exclusive. + + optional ExtensionRangeOptions options = 3; + } + repeated ExtensionRange extension_range = 5; + + repeated OneofDescriptorProto oneof_decl = 8; + + optional MessageOptions options = 7; + + // Range of reserved tag numbers. Reserved tag numbers may not be used by + // fields or extension ranges in the same message. Reserved ranges may + // not overlap. + message ReservedRange { + optional int32 start = 1; // Inclusive. + optional int32 end = 2; // Exclusive. + } + repeated ReservedRange reserved_range = 9; + // Reserved field names, which may not be used by fields in the same message. + // A given name may only be reserved once. + repeated string reserved_name = 10; +} + +message ExtensionRangeOptions { + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + message Declaration { + // The extension number declared within the extension range. + optional int32 number = 1; + + // The fully-qualified name of the extension field. There must be a leading + // dot in front of the full name. + optional string full_name = 2; + + // The fully-qualified type name of the extension field. Unlike + // Metadata.type, Declaration.type must have a leading dot for messages + // and enums. + optional string type = 3; + + // If true, indicates that the number is reserved in the extension range, + // and any extension field with the number will fail to compile. Set this + // when a declared extension field is deleted. + optional bool reserved = 5; + + // If true, indicates that the extension must be defined as repeated. + // Otherwise the extension must be defined as optional. + optional bool repeated = 6; + + reserved 4; // removed is_repeated + } + + // For external users: DO NOT USE. We are in the process of open sourcing + // extension declaration and executing internal cleanups before it can be + // used externally. + repeated Declaration declaration = 2 [retention = RETENTION_SOURCE]; + + // Any features defined in the specific edition. + optional FeatureSet features = 50; + + // The verification state of the extension range. + enum VerificationState { + // All the extensions of the range must be declared. + DECLARATION = 0; + UNVERIFIED = 1; + } + + // The verification state of the range. + // TODO: flip the default to DECLARATION once all empty ranges + // are marked as UNVERIFIED. + optional VerificationState verification = 3 + [default = UNVERIFIED, retention = RETENTION_SOURCE]; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +// Describes a field within a message. +message FieldDescriptorProto { + enum Type { + // 0 is reserved for errors. + // Order is weird for historical reasons. + TYPE_DOUBLE = 1; + TYPE_FLOAT = 2; + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if + // negative values are likely. + TYPE_INT64 = 3; + TYPE_UINT64 = 4; + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if + // negative values are likely. + TYPE_INT32 = 5; + TYPE_FIXED64 = 6; + TYPE_FIXED32 = 7; + TYPE_BOOL = 8; + TYPE_STRING = 9; + // Tag-delimited aggregate. + // Group type is deprecated and not supported after google.protobuf. However, Proto3 + // implementations should still be able to parse the group wire format and + // treat group fields as unknown fields. In Editions, the group wire format + // can be enabled via the `message_encoding` feature. + TYPE_GROUP = 10; + TYPE_MESSAGE = 11; // Length-delimited aggregate. + + // New in version 2. + TYPE_BYTES = 12; + TYPE_UINT32 = 13; + TYPE_ENUM = 14; + TYPE_SFIXED32 = 15; + TYPE_SFIXED64 = 16; + TYPE_SINT32 = 17; // Uses ZigZag encoding. + TYPE_SINT64 = 18; // Uses ZigZag encoding. + } + + enum Label { + // 0 is reserved for errors + LABEL_OPTIONAL = 1; + LABEL_REPEATED = 3; + // The required label is only allowed in google.protobuf. In proto3 and Editions + // it's explicitly prohibited. In Editions, the `field_presence` feature + // can be used to get this behavior. + LABEL_REQUIRED = 2; + } + + optional string name = 1; + optional int32 number = 3; + optional Label label = 4; + + // If type_name is set, this need not be set. If both this and type_name + // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. + optional Type type = 5; + + // For message and enum types, this is the name of the type. If the name + // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping + // rules are used to find the type (i.e. first the nested types within this + // message are searched, then within the parent, on up to the root + // namespace). + optional string type_name = 6; + + // For extensions, this is the name of the type being extended. It is + // resolved in the same manner as type_name. + optional string extendee = 2; + + // For numeric types, contains the original text representation of the value. + // For booleans, "true" or "false". + // For strings, contains the default text contents (not escaped in any way). + // For bytes, contains the C escaped value. All bytes >= 128 are escaped. + optional string default_value = 7; + + // If set, gives the index of a oneof in the containing type's oneof_decl + // list. This field is a member of that oneof. + optional int32 oneof_index = 9; + + // JSON name of this field. The value is set by protocol compiler. If the + // user has set a "json_name" option on this field, that option's value + // will be used. Otherwise, it's deduced from the field's name by converting + // it to camelCase. + optional string json_name = 10; + + optional FieldOptions options = 8; + + // If true, this is a proto3 "optional". When a proto3 field is optional, it + // tracks presence regardless of field type. + // + // When proto3_optional is true, this field must belong to a oneof to signal + // to old proto3 clients that presence is tracked for this field. This oneof + // is known as a "synthetic" oneof, and this field must be its sole member + // (each proto3 optional field gets its own synthetic oneof). Synthetic oneofs + // exist in the descriptor only, and do not generate any API. Synthetic oneofs + // must be ordered after all "real" oneofs. + // + // For message fields, proto3_optional doesn't create any semantic change, + // since non-repeated message fields always track presence. However it still + // indicates the semantic detail of whether the user wrote "optional" or not. + // This can be useful for round-tripping the .proto file. For consistency we + // give message fields a synthetic oneof also, even though it is not required + // to track presence. This is especially important because the parser can't + // tell if a field is a message or an enum, so it must always create a + // synthetic oneof. + // + // Proto2 optional fields do not set this flag, because they already indicate + // optional with `LABEL_OPTIONAL`. + optional bool proto3_optional = 17; +} + +// Describes a oneof. +message OneofDescriptorProto { + optional string name = 1; + optional OneofOptions options = 2; +} + +// Describes an enum type. +message EnumDescriptorProto { + optional string name = 1; + + repeated EnumValueDescriptorProto value = 2; + + optional EnumOptions options = 3; + + // Range of reserved numeric values. Reserved values may not be used by + // entries in the same enum. Reserved ranges may not overlap. + // + // Note that this is distinct from DescriptorProto.ReservedRange in that it + // is inclusive such that it can appropriately represent the entire int32 + // domain. + message EnumReservedRange { + optional int32 start = 1; // Inclusive. + optional int32 end = 2; // Inclusive. + } + + // Range of reserved numeric values. Reserved numeric values may not be used + // by enum values in the same enum declaration. Reserved ranges may not + // overlap. + repeated EnumReservedRange reserved_range = 4; + + // Reserved enum value names, which may not be reused. A given name may only + // be reserved once. + repeated string reserved_name = 5; +} + +// Describes a value within an enum. +message EnumValueDescriptorProto { + optional string name = 1; + optional int32 number = 2; + + optional EnumValueOptions options = 3; +} + +// Describes a service. +message ServiceDescriptorProto { + optional string name = 1; + repeated MethodDescriptorProto method = 2; + + optional ServiceOptions options = 3; +} + +// Describes a method of a service. +message MethodDescriptorProto { + optional string name = 1; + + // Input and output type names. These are resolved in the same way as + // FieldDescriptorProto.type_name, but must refer to a message type. + optional string input_type = 2; + optional string output_type = 3; + + optional MethodOptions options = 4; + + // Identifies if client streams multiple client messages + optional bool client_streaming = 5 [default = false]; + // Identifies if server streams multiple server messages + optional bool server_streaming = 6 [default = false]; +} + +// =================================================================== +// Options + +// Each of the definitions above may have "options" attached. These are +// just annotations which may cause code to be generated slightly differently +// or may contain hints for code that manipulates protocol messages. +// +// Clients may define custom options as extensions of the *Options messages. +// These extensions may not yet be known at parsing time, so the parser cannot +// store the values in them. Instead it stores them in a field in the *Options +// message called uninterpreted_option. This field must have the same name +// across all *Options messages. We then use this field to populate the +// extensions when we build a descriptor, at which point all protos have been +// parsed and so all extensions are known. +// +// Extension numbers for custom options may be chosen as follows: +// * For options which will only be used within a single application or +// organization, or for experimental options, use field numbers 50000 +// through 99999. It is up to you to ensure that you do not use the +// same number for multiple options. +// * For options which will be published and used publicly by multiple +// independent entities, e-mail protobuf-global-extension-registry@google.com +// to reserve extension numbers. Simply provide your project name (e.g. +// Objective-C plugin) and your project website (if available) -- there's no +// need to explain how you intend to use them. Usually you only need one +// extension number. You can declare multiple options with only one extension +// number by putting them in a sub-message. See the Custom Options section of +// the docs for examples: +// https://developers.google.com/protocol-buffers/docs/proto#options +// If this turns out to be popular, a web service will be set up +// to automatically assign option numbers. + +message FileOptions { + + // Sets the Java package where classes generated from this .proto will be + // placed. By default, the proto package is used, but this is often + // inappropriate because proto packages do not normally start with backwards + // domain names. + optional string java_package = 1; + + // Controls the name of the wrapper Java class generated for the .proto file. + // That class will always contain the .proto file's getDescriptor() method as + // well as any top-level extensions defined in the .proto file. + // If java_multiple_files is disabled, then all the other classes from the + // .proto file will be nested inside the single wrapper outer class. + optional string java_outer_classname = 8; + + // If enabled, then the Java code generator will generate a separate .java + // file for each top-level message, enum, and service defined in the .proto + // file. Thus, these types will *not* be nested inside the wrapper class + // named by java_outer_classname. However, the wrapper class will still be + // generated to contain the file's getDescriptor() method as well as any + // top-level extensions defined in the file. + optional bool java_multiple_files = 10 [default = false]; + + // This option does nothing. + optional bool java_generate_equals_and_hash = 20 [deprecated=true]; + + // A proto2 file can set this to true to opt in to UTF-8 checking for Java, + // which will throw an exception if invalid UTF-8 is parsed from the wire or + // assigned to a string field. + // + // TODO: clarify exactly what kinds of field types this option + // applies to, and update these docs accordingly. + // + // Proto3 files already perform these checks. Setting the option explicitly to + // false has no effect: it cannot be used to opt proto3 files out of UTF-8 + // checks. + optional bool java_string_check_utf8 = 27 [default = false]; + + // Generated classes can be optimized for speed or code size. + enum OptimizeMode { + SPEED = 1; // Generate complete code for parsing, serialization, + // etc. + CODE_SIZE = 2; // Use ReflectionOps to implement these methods. + LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime. + } + optional OptimizeMode optimize_for = 9 [default = SPEED]; + + // Sets the Go package where structs generated from this .proto will be + // placed. If omitted, the Go package will be derived from the following: + // - The basename of the package import path, if provided. + // - Otherwise, the package statement in the .proto file, if present. + // - Otherwise, the basename of the .proto file, without extension. + optional string go_package = 11; + + // Should generic services be generated in each language? "Generic" services + // are not specific to any particular RPC system. They are generated by the + // main code generators in each language (without additional plugins). + // Generic services were the only kind of service generation supported by + // early versions of google.protobuf. + // + // Generic services are now considered deprecated in favor of using plugins + // that generate code specific to your particular RPC system. Therefore, + // these default to false. Old code which depends on generic services should + // explicitly set them to true. + optional bool cc_generic_services = 16 [default = false]; + optional bool java_generic_services = 17 [default = false]; + optional bool py_generic_services = 18 [default = false]; + reserved 42; // removed php_generic_services + + // Is this file deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for everything in the file, or it will be completely ignored; in the very + // least, this is a formalization for deprecating files. + optional bool deprecated = 23 [default = false]; + + // Enables the use of arenas for the proto messages in this file. This applies + // only to generated classes for C++. + optional bool cc_enable_arenas = 31 [default = true]; + + // Sets the objective c class prefix which is prepended to all objective c + // generated classes from this .proto. There is no default. + optional string objc_class_prefix = 36; + + // Namespace for generated classes; defaults to the package. + optional string csharp_namespace = 37; + + // By default Swift generators will take the proto package and CamelCase it + // replacing '.' with underscore and use that to prefix the types/symbols + // defined. When this options is provided, they will use this value instead + // to prefix the types/symbols defined. + optional string swift_prefix = 39; + + // Sets the php class prefix which is prepended to all php generated classes + // from this .proto. Default is empty. + optional string php_class_prefix = 40; + + // Use this option to change the namespace of php generated classes. Default + // is empty. When this option is empty, the package name will be used for + // determining the namespace. + optional string php_namespace = 41; + + // Use this option to change the namespace of php generated metadata classes. + // Default is empty. When this option is empty, the proto file name will be + // used for determining the namespace. + optional string php_metadata_namespace = 44; + + // Use this option to change the package of ruby generated classes. Default + // is empty. When this option is not set, the package name will be used for + // determining the ruby package. + optional string ruby_package = 45; + + // Any features defined in the specific edition. + optional FeatureSet features = 50; + + // The parser stores options it doesn't recognize here. + // See the documentation for the "Options" section above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. + // See the documentation for the "Options" section above. + extensions 1000 to max; + + reserved 38; +} + +message MessageOptions { + // Set true to use the old proto1 MessageSet wire format for extensions. + // This is provided for backwards-compatibility with the MessageSet wire + // format. You should not use this for any other reason: It's less + // efficient, has fewer features, and is more complicated. + // + // The message must be defined exactly as follows: + // message Foo { + // option message_set_wire_format = true; + // extensions 4 to max; + // } + // Note that the message cannot have any defined fields; MessageSets only + // have extensions. + // + // All extensions of your type must be singular messages; e.g. they cannot + // be int32s, enums, or repeated messages. + // + // Because this is an option, the above two restrictions are not enforced by + // the protocol compiler. + optional bool message_set_wire_format = 1 [default = false]; + + // Disables the generation of the standard "descriptor()" accessor, which can + // conflict with a field of the same name. This is meant to make migration + // from proto1 easier; new code should avoid fields named "descriptor". + optional bool no_standard_descriptor_accessor = 2 [default = false]; + + // Is this message deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the message, or it will be completely ignored; in the very least, + // this is a formalization for deprecating messages. + optional bool deprecated = 3 [default = false]; + + reserved 4, 5, 6; + + // Whether the message is an automatically generated map entry type for the + // maps field. + // + // For maps fields: + // map map_field = 1; + // The parsed descriptor looks like: + // message MapFieldEntry { + // option map_entry = true; + // optional KeyType key = 1; + // optional ValueType value = 2; + // } + // repeated MapFieldEntry map_field = 1; + // + // Implementations may choose not to generate the map_entry=true message, but + // use a native map in the target language to hold the keys and values. + // The reflection APIs in such implementations still need to work as + // if the field is a repeated message field. + // + // NOTE: Do not set the option in .proto files. Always use the maps syntax + // instead. The option should only be implicitly set by the proto compiler + // parser. + optional bool map_entry = 7; + + reserved 8; // javalite_serializable + reserved 9; // javanano_as_lite + + // Enable the legacy handling of JSON field name conflicts. This lowercases + // and strips underscored from the fields before comparison in proto3 only. + // The new behavior takes `json_name` into account and applies to proto2 as + // well. + // + // This should only be used as a temporary measure against broken builds due + // to the change in behavior for JSON field name conflicts. + // + // TODO This is legacy behavior we plan to remove once downstream + // teams have had time to migrate. + optional bool deprecated_legacy_json_field_conflicts = 11 [deprecated = true]; + + // Any features defined in the specific edition. + optional FeatureSet features = 12; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message FieldOptions { + // The ctype option instructs the C++ code generator to use a different + // representation of the field than it normally would. See the specific + // options below. This option is only implemented to support use of + // [ctype=CORD] and [ctype=STRING] (the default) on non-repeated fields of + // type "bytes" in the open source release -- sorry, we'll try to include + // other types in a future version! + optional CType ctype = 1 [default = STRING]; + enum CType { + // Default mode. + STRING = 0; + + // The option [ctype=CORD] may be applied to a non-repeated field of type + // "bytes". It indicates that in C++, the data should be stored in a Cord + // instead of a string. For very large strings, this may reduce memory + // fragmentation. It may also allow better performance when parsing from a + // Cord, or when parsing with aliasing enabled, as the parsed Cord may then + // alias the original buffer. + CORD = 1; + + STRING_PIECE = 2; + } + // The packed option can be enabled for repeated primitive fields to enable + // a more efficient representation on the wire. Rather than repeatedly + // writing the tag and type for each element, the entire array is encoded as + // a single length-delimited blob. In proto3, only explicit setting it to + // false will avoid using packed encoding. This option is prohibited in + // Editions, but the `repeated_field_encoding` feature can be used to control + // the behavior. + optional bool packed = 2; + + // The jstype option determines the JavaScript type used for values of the + // field. The option is permitted only for 64 bit integral and fixed types + // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING + // is represented as JavaScript string, which avoids loss of precision that + // can happen when a large value is converted to a floating point JavaScript. + // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to + // use the JavaScript "number" type. The behavior of the default option + // JS_NORMAL is implementation dependent. + // + // This option is an enum to permit additional types to be added, e.g. + // goog.math.Integer. + optional JSType jstype = 6 [default = JS_NORMAL]; + enum JSType { + // Use the default type. + JS_NORMAL = 0; + + // Use JavaScript strings. + JS_STRING = 1; + + // Use JavaScript numbers. + JS_NUMBER = 2; + } + + // Should this field be parsed lazily? Lazy applies only to message-type + // fields. It means that when the outer message is initially parsed, the + // inner message's contents will not be parsed but instead stored in encoded + // form. The inner message will actually be parsed when it is first accessed. + // + // This is only a hint. Implementations are free to choose whether to use + // eager or lazy parsing regardless of the value of this option. However, + // setting this option true suggests that the protocol author believes that + // using lazy parsing on this field is worth the additional bookkeeping + // overhead typically needed to implement it. + // + // This option does not affect the public interface of any generated code; + // all method signatures remain the same. Furthermore, thread-safety of the + // interface is not affected by this option; const methods remain safe to + // call from multiple threads concurrently, while non-const methods continue + // to require exclusive access. + // + // Note that lazy message fields are still eagerly verified to check + // ill-formed wireformat or missing required fields. Calling IsInitialized() + // on the outer message would fail if the inner message has missing required + // fields. Failed verification would result in parsing failure (except when + // uninitialized messages are acceptable). + optional bool lazy = 5 [default = false]; + + // unverified_lazy does no correctness checks on the byte stream. This should + // only be used where lazy with verification is prohibitive for performance + // reasons. + optional bool unverified_lazy = 15 [default = false]; + + // Is this field deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for accessors, or it will be completely ignored; in the very least, this + // is a formalization for deprecating fields. + optional bool deprecated = 3 [default = false]; + + // For Google-internal migration only. Do not use. + optional bool weak = 10 [default = false]; + + // Indicate that the field value should not be printed out when using debug + // formats, e.g. when the field contains sensitive credentials. + optional bool debug_redact = 16 [default = false]; + + // If set to RETENTION_SOURCE, the option will be omitted from the binary. + // Note: as of January 2023, support for this is in progress and does not yet + // have an effect (b/264593489). + enum OptionRetention { + RETENTION_UNKNOWN = 0; + RETENTION_RUNTIME = 1; + RETENTION_SOURCE = 2; + } + + optional OptionRetention retention = 17; + + // This indicates the types of entities that the field may apply to when used + // as an option. If it is unset, then the field may be freely used as an + // option on any kind of entity. Note: as of January 2023, support for this is + // in progress and does not yet have an effect (b/264593489). + enum OptionTargetType { + TARGET_TYPE_UNKNOWN = 0; + TARGET_TYPE_FILE = 1; + TARGET_TYPE_EXTENSION_RANGE = 2; + TARGET_TYPE_MESSAGE = 3; + TARGET_TYPE_FIELD = 4; + TARGET_TYPE_ONEOF = 5; + TARGET_TYPE_ENUM = 6; + TARGET_TYPE_ENUM_ENTRY = 7; + TARGET_TYPE_SERVICE = 8; + TARGET_TYPE_METHOD = 9; + } + + repeated OptionTargetType targets = 19; + + message EditionDefault { + optional Edition edition = 3; + optional string value = 2; // Textproto value. + } + repeated EditionDefault edition_defaults = 20; + + // Any features defined in the specific edition. + optional FeatureSet features = 21; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; + + reserved 4; // removed jtype + reserved 18; // reserve target, target_obsolete_do_not_use +} + +message OneofOptions { + // Any features defined in the specific edition. + optional FeatureSet features = 1; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message EnumOptions { + + // Set this option to true to allow mapping different tag names to the same + // value. + optional bool allow_alias = 2; + + // Is this enum deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the enum, or it will be completely ignored; in the very least, this + // is a formalization for deprecating enums. + optional bool deprecated = 3 [default = false]; + + reserved 5; // javanano_as_lite + + // Enable the legacy handling of JSON field name conflicts. This lowercases + // and strips underscored from the fields before comparison in proto3 only. + // The new behavior takes `json_name` into account and applies to proto2 as + // well. + // TODO Remove this legacy behavior once downstream teams have + // had time to migrate. + optional bool deprecated_legacy_json_field_conflicts = 6 [deprecated = true]; + + // Any features defined in the specific edition. + optional FeatureSet features = 7; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message EnumValueOptions { + // Is this enum value deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the enum value, or it will be completely ignored; in the very least, + // this is a formalization for deprecating enum values. + optional bool deprecated = 1 [default = false]; + + // Any features defined in the specific edition. + optional FeatureSet features = 2; + + // Indicate that fields annotated with this enum value should not be printed + // out when using debug formats, e.g. when the field contains sensitive + // credentials. + optional bool debug_redact = 3 [default = false]; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message ServiceOptions { + + // Any features defined in the specific edition. + optional FeatureSet features = 34; + + // Note: Field numbers 1 through 32 are reserved for Google's internal RPC + // framework. We apologize for hoarding these numbers to ourselves, but + // we were already using them long before we decided to release Protocol + // Buffers. + + // Is this service deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the service, or it will be completely ignored; in the very least, + // this is a formalization for deprecating services. + optional bool deprecated = 33 [default = false]; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message MethodOptions { + + // Note: Field numbers 1 through 32 are reserved for Google's internal RPC + // framework. We apologize for hoarding these numbers to ourselves, but + // we were already using them long before we decided to release Protocol + // Buffers. + + // Is this method deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the method, or it will be completely ignored; in the very least, + // this is a formalization for deprecating methods. + optional bool deprecated = 33 [default = false]; + + // Is this method side-effect-free (or safe in HTTP parlance), or idempotent, + // or neither? HTTP based RPC implementation may choose GET verb for safe + // methods, and PUT verb for idempotent methods instead of the default POST. + enum IdempotencyLevel { + IDEMPOTENCY_UNKNOWN = 0; + NO_SIDE_EFFECTS = 1; // implies idempotent + IDEMPOTENT = 2; // idempotent, but may have side effects + } + optional IdempotencyLevel idempotency_level = 34 + [default = IDEMPOTENCY_UNKNOWN]; + + // Any features defined in the specific edition. + optional FeatureSet features = 35; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +// A message representing a option the parser does not recognize. This only +// appears in options protos created by the compiler::Parser class. +// DescriptorPool resolves these when building Descriptor objects. Therefore, +// options protos in descriptor objects (e.g. returned by Descriptor::options(), +// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions +// in them. +message UninterpretedOption { + // The name of the uninterpreted option. Each string represents a segment in + // a dot-separated name. is_extension is true iff a segment represents an + // extension (denoted with parentheses in options specs in .proto files). + // E.g.,{ ["foo", false], ["bar.baz", true], ["moo", false] } represents + // "foo.(bar.baz).moo". + message NamePart { + required string name_part = 1; + required bool is_extension = 2; + } + repeated NamePart name = 2; + + // The value of the uninterpreted option, in whatever type the tokenizer + // identified it as during parsing. Exactly one of these should be set. + optional string identifier_value = 3; + optional uint64 positive_int_value = 4; + optional int64 negative_int_value = 5; + optional double double_value = 6; + optional bytes string_value = 7; + optional string aggregate_value = 8; +} + +// =================================================================== +// Features + +// TODO Enums in C++ gencode (and potentially other languages) are +// not well scoped. This means that each of the feature enums below can clash +// with each other. The short names we've chosen maximize call-site +// readability, but leave us very open to this scenario. A future feature will +// be designed and implemented to handle this, hopefully before we ever hit a +// conflict here. +message FeatureSet { + enum FieldPresence { + FIELD_PRESENCE_UNKNOWN = 0; + EXPLICIT = 1; + IMPLICIT = 2; + LEGACY_REQUIRED = 3; + } + optional FieldPresence field_presence = 1 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_FIELD, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "EXPLICIT" }, + edition_defaults = { edition: EDITION_PROTO3, value: "IMPLICIT" }, + edition_defaults = { edition: EDITION_2023, value: "EXPLICIT" } + ]; + + enum EnumType { + ENUM_TYPE_UNKNOWN = 0; + OPEN = 1; + CLOSED = 2; + } + optional EnumType enum_type = 2 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_ENUM, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "CLOSED" }, + edition_defaults = { edition: EDITION_PROTO3, value: "OPEN" } + ]; + + enum RepeatedFieldEncoding { + REPEATED_FIELD_ENCODING_UNKNOWN = 0; + PACKED = 1; + EXPANDED = 2; + } + optional RepeatedFieldEncoding repeated_field_encoding = 3 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_FIELD, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "EXPANDED" }, + edition_defaults = { edition: EDITION_PROTO3, value: "PACKED" } + ]; + + enum Utf8Validation { + UTF8_VALIDATION_UNKNOWN = 0; + VERIFY = 2; + NONE = 3; + } + optional Utf8Validation utf8_validation = 4 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_FIELD, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "NONE" }, + edition_defaults = { edition: EDITION_PROTO3, value: "VERIFY" } + ]; + + enum MessageEncoding { + MESSAGE_ENCODING_UNKNOWN = 0; + LENGTH_PREFIXED = 1; + DELIMITED = 2; + } + optional MessageEncoding message_encoding = 5 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_FIELD, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "LENGTH_PREFIXED" } + ]; + + enum JsonFormat { + JSON_FORMAT_UNKNOWN = 0; + ALLOW = 1; + LEGACY_BEST_EFFORT = 2; + } + optional JsonFormat json_format = 6 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_MESSAGE, + targets = TARGET_TYPE_ENUM, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "LEGACY_BEST_EFFORT" }, + edition_defaults = { edition: EDITION_PROTO3, value: "ALLOW" } + ]; + + reserved 999; + + extensions 1000; // for Protobuf C++ + extensions 1001; // for Protobuf Java + extensions 1002; // for Protobuf Go + + extensions 9990; // for deprecated Java Proto1 + + extensions 9995 to 9999; // For internal testing + extensions 10000; // for https://github.com/bufbuild/protobuf-es +} + +// A compiled specification for the defaults of a set of features. These +// messages are generated from FeatureSet extensions and can be used to seed +// feature resolution. The resolution with this object becomes a simple search +// for the closest matching edition, followed by proto merges. +message FeatureSetDefaults { + // A map from every known edition with a unique set of defaults to its + // defaults. Not all editions may be contained here. For a given edition, + // the defaults at the closest matching edition ordered at or before it should + // be used. This field must be in strict ascending order by edition. + message FeatureSetEditionDefault { + optional Edition edition = 3; + optional FeatureSet features = 2; + } + repeated FeatureSetEditionDefault defaults = 1; + + // The minimum supported edition (inclusive) when this was constructed. + // Editions before this will not have defaults. + optional Edition minimum_edition = 4; + + // The maximum known edition (inclusive) when this was constructed. Editions + // after this will not have reliable defaults. + optional Edition maximum_edition = 5; +} + +// =================================================================== +// Optional source code info + +// Encapsulates information about the original source file from which a +// FileDescriptorProto was generated. +message SourceCodeInfo { + // A Location identifies a piece of source code in a .proto file which + // corresponds to a particular definition. This information is intended + // to be useful to IDEs, code indexers, documentation generators, and similar + // tools. + // + // For example, say we have a file like: + // message Foo { + // optional string foo = 1; + // } + // Let's look at just the field definition: + // optional string foo = 1; + // ^ ^^ ^^ ^ ^^^ + // a bc de f ghi + // We have the following locations: + // span path represents + // [a,i) [ 4, 0, 2, 0 ] The whole field definition. + // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). + // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). + // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). + // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). + // + // Notes: + // - A location may refer to a repeated field itself (i.e. not to any + // particular index within it). This is used whenever a set of elements are + // logically enclosed in a single code segment. For example, an entire + // extend block (possibly containing multiple extension definitions) will + // have an outer location whose path refers to the "extensions" repeated + // field without an index. + // - Multiple locations may have the same path. This happens when a single + // logical declaration is spread out across multiple places. The most + // obvious example is the "extend" block again -- there may be multiple + // extend blocks in the same scope, each of which will have the same path. + // - A location's span is not always a subset of its parent's span. For + // example, the "extendee" of an extension declaration appears at the + // beginning of the "extend" block and is shared by all extensions within + // the block. + // - Just because a location's span is a subset of some other location's span + // does not mean that it is a descendant. For example, a "group" defines + // both a type and a field in a single declaration. Thus, the locations + // corresponding to the type and field and their components will overlap. + // - Code which tries to interpret locations should probably be designed to + // ignore those that it doesn't understand, as more types of locations could + // be recorded in the future. + repeated Location location = 1; + message Location { + // Identifies which part of the FileDescriptorProto was defined at this + // location. + // + // Each element is a field number or an index. They form a path from + // the root FileDescriptorProto to the place where the definition appears. + // For example, this path: + // [ 4, 3, 2, 7, 1 ] + // refers to: + // file.message_type(3) // 4, 3 + // .field(7) // 2, 7 + // .name() // 1 + // This is because FileDescriptorProto.message_type has field number 4: + // repeated DescriptorProto message_type = 4; + // and DescriptorProto.field has field number 2: + // repeated FieldDescriptorProto field = 2; + // and FieldDescriptorProto.name has field number 1: + // optional string name = 1; + // + // Thus, the above path gives the location of a field name. If we removed + // the last element: + // [ 4, 3, 2, 7 ] + // this path refers to the whole field declaration (from the beginning + // of the label to the terminating semicolon). + repeated int32 path = 1 [packed = true]; + + // Always has exactly three or four elements: start line, start column, + // end line (optional, otherwise assumed same as start line), end column. + // These are packed into a single field for efficiency. Note that line + // and column numbers are zero-based -- typically you will want to add + // 1 to each before displaying to a user. + repeated int32 span = 2 [packed = true]; + + // If this SourceCodeInfo represents a complete declaration, these are any + // comments appearing before and after the declaration which appear to be + // attached to the declaration. + // + // A series of line comments appearing on consecutive lines, with no other + // tokens appearing on those lines, will be treated as a single comment. + // + // leading_detached_comments will keep paragraphs of comments that appear + // before (but not connected to) the current element. Each paragraph, + // separated by empty lines, will be one comment element in the repeated + // field. + // + // Only the comment content is provided; comment markers (e.g. //) are + // stripped out. For block comments, leading whitespace and an asterisk + // will be stripped from the beginning of each line other than the first. + // Newlines are included in the output. + // + // Examples: + // + // optional int32 foo = 1; // Comment attached to foo. + // // Comment attached to bar. + // optional int32 bar = 2; + // + // optional string baz = 3; + // // Comment attached to baz. + // // Another line attached to baz. + // + // // Comment attached to moo. + // // + // // Another line attached to moo. + // optional double moo = 4; + // + // // Detached comment for corge. This is not leading or trailing comments + // // to moo or corge because there are blank lines separating it from + // // both. + // + // // Detached comment for corge paragraph 2. + // + // optional string corge = 5; + // /* Block comment attached + // * to corge. Leading asterisks + // * will be removed. */ + // /* Block comment attached to + // * grault. */ + // optional int32 grault = 6; + // + // // ignored detached comments. + optional string leading_comments = 3; + optional string trailing_comments = 4; + repeated string leading_detached_comments = 6; + } +} + +// Describes the relationship between generated code and its original source +// file. A GeneratedCodeInfo message is associated with only one generated +// source file, but may contain references to different source .proto files. +message GeneratedCodeInfo { + // An Annotation connects some span of text in generated code to an element + // of its generating .proto file. + repeated Annotation annotation = 1; + message Annotation { + // Identifies the element in the original source .proto file. This field + // is formatted the same as SourceCodeInfo.Location.path. + repeated int32 path = 1 [packed = true]; + + // Identifies the filesystem path to the original source .proto. + optional string source_file = 2; + + // Identifies the starting offset in bytes in the generated code + // that relates to the identified object. + optional int32 begin = 3; + + // Identifies the ending offset in bytes in the generated code that + // relates to the identified object. The end offset should be one past + // the last relevant byte (so the length of the text = end - begin). + optional int32 end = 4; + + // Represents the identified object's effect on the element in the original + // .proto file. + enum Semantic { + // There is no effect or the effect is indescribable. + NONE = 0; + // The element is set or otherwise mutated. + SET = 1; + // An alias to the element is returned. + ALIAS = 2; + } + optional Semantic semantic = 5; + } +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/duration.proto b/node_modules/google-gax/build/protos/google/protobuf/duration.proto new file mode 100644 index 0000000..41f40c2 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/duration.proto @@ -0,0 +1,115 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/protobuf/types/known/durationpb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "DurationProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; + +// A Duration represents a signed, fixed-length span of time represented +// as a count of seconds and fractions of seconds at nanosecond +// resolution. It is independent of any calendar and concepts like "day" +// or "month". It is related to Timestamp in that the difference between +// two Timestamp values is a Duration and it can be added or subtracted +// from a Timestamp. Range is approximately +-10,000 years. +// +// # Examples +// +// Example 1: Compute Duration from two Timestamps in pseudo code. +// +// Timestamp start = ...; +// Timestamp end = ...; +// Duration duration = ...; +// +// duration.seconds = end.seconds - start.seconds; +// duration.nanos = end.nanos - start.nanos; +// +// if (duration.seconds < 0 && duration.nanos > 0) { +// duration.seconds += 1; +// duration.nanos -= 1000000000; +// } else if (duration.seconds > 0 && duration.nanos < 0) { +// duration.seconds -= 1; +// duration.nanos += 1000000000; +// } +// +// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. +// +// Timestamp start = ...; +// Duration duration = ...; +// Timestamp end = ...; +// +// end.seconds = start.seconds + duration.seconds; +// end.nanos = start.nanos + duration.nanos; +// +// if (end.nanos < 0) { +// end.seconds -= 1; +// end.nanos += 1000000000; +// } else if (end.nanos >= 1000000000) { +// end.seconds += 1; +// end.nanos -= 1000000000; +// } +// +// Example 3: Compute Duration from datetime.timedelta in Python. +// +// td = datetime.timedelta(days=3, minutes=10) +// duration = Duration() +// duration.FromTimedelta(td) +// +// # JSON Mapping +// +// In JSON format, the Duration type is encoded as a string rather than an +// object, where the string ends in the suffix "s" (indicating seconds) and +// is preceded by the number of seconds, with nanoseconds expressed as +// fractional seconds. For example, 3 seconds with 0 nanoseconds should be +// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should +// be expressed in JSON format as "3.000000001s", and 3 seconds and 1 +// microsecond should be expressed in JSON format as "3.000001s". +// +message Duration { + // Signed seconds of the span of time. Must be from -315,576,000,000 + // to +315,576,000,000 inclusive. Note: these bounds are computed from: + // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years + int64 seconds = 1; + + // Signed fractions of a second at nanosecond resolution of the span + // of time. Durations less than one second are represented with a 0 + // `seconds` field and a positive or negative `nanos` field. For durations + // of one second or more, a non-zero value for the `nanos` field must be + // of the same sign as the `seconds` field. Must be from -999,999,999 + // to +999,999,999 inclusive. + int32 nanos = 2; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_enum.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_enum.proto new file mode 100644 index 0000000..9f061c2 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_enum.proto @@ -0,0 +1,26 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto2"; + +package protobuf_editions_test.proto2; + +enum Proto2Enum { + BAR = 1; + BAZ = 2; +} + +message Proto2EnumMessage { + optional Proto2Enum enum_field = 1; + optional Proto2Enum enum_field_default = 2 [default = BAZ]; + enum Proto2NestedEnum { + FOO = 1; + BAT = 2; + } + optional Proto2NestedEnum nested_enum_field = 3; + optional Proto2NestedEnum nested_enum_field_default = 4 [default = BAT]; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_group.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_group.proto new file mode 100644 index 0000000..8d807a0 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_group.proto @@ -0,0 +1,18 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto2"; + +package protobuf_editions_test.proto2; + +// LINT: ALLOW_GROUPS + +message Proto2Group { + optional group Groupfield = 2 { + optional int32 int32_field = 1; + } +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_import.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_import.proto new file mode 100644 index 0000000..031d886 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_import.proto @@ -0,0 +1,16 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto2"; + +package protobuf_editions_test.proto2; + +import "google/protobuf/editions/codegen_tests/proto2_optional.proto"; + +message Proto2ImportMessage { + optional Proto2Optional sub_message_field = 1; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_inline_comments.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_inline_comments.proto new file mode 100644 index 0000000..d947bd0 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_inline_comments.proto @@ -0,0 +1,33 @@ +// This is a detached leading comment +// +// With a forced unwrapped line. + +// File detached leading comment + +// Syntax leading comment +syntax = "proto2"; // Syntax trailing comment + +// Package leading comment +package protobuf_editions_test.proto2; // Package trailing comment + +// Leading message comment +message Foo { // Message trailing comment + // Message inner comment + + // Field leading comment + optional int32 field1 = 1; // Field trailing comment + + optional /* card */ int32 /* type */ field2 /* name */ = 2 /* tag */; + + // Message inner trailing comment +} // Message trailing comment + +// Leading message comment +enum Bar { // Enum trailing comment + // Enum inner comment + + // Enum value leading comment + BAR_UNKNOWN = 0; // Enum value trailing comment + + // Enum inner trailing comment +} // Enum trailing comment diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_multiline_comments.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_multiline_comments.proto new file mode 100644 index 0000000..e8e106c --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_multiline_comments.proto @@ -0,0 +1,33 @@ +syntax = "proto2"; + +package protobuf_editions_test.proto2; + +/** +Multiline message comment - no asterisk +*/ +message Message1 { + /** + Multiline field comment - no asterisk + */ + optional string field = 1; +} + +/* + * Multiline message comment - single asterisk + */ +message Message2 { + /* + * Multiline message comment - single asterisk + */ + optional string field = 1; +} + +/** + * Exactly one trait must be set. Extension # is vendor_id + 1. + */ +message Message3 { + /** + * Exactly one trait must be set. Extension # is vendor_id + 1. + */ + optional string field = 1; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_optional.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_optional.proto new file mode 100644 index 0000000..1211a89 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_optional.proto @@ -0,0 +1,65 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto2"; + +package protobuf_editions_test.proto2; + +message Proto2Optional { + optional int32 int32_field = 17; + optional float float_field = 18; + optional double double_field = 19; + optional int64 int64_field = 20; + optional uint32 uint32_field = 21; + optional uint64 uint64_field = 22; + optional sint32 sint32_field = 23; + optional sint64 sint64_field = 24; + optional fixed32 fixed32_field = 25; + optional fixed64 fixed64_field = 26; + optional sfixed32 sfixed32_field = 27; + optional sfixed64 sfixed64_field = 28; + optional bool bool_field = 29; + optional string string_field = 30; + optional bytes bytes_field = 31; + + message SubMessage { + optional int32 int32_field = 17; + optional float float_field = 18; + optional double double_field = 19; + optional int64 int64_field = 20; + optional uint32 uint32_field = 21; + optional uint64 uint64_field = 22; + optional sint32 sint32_field = 23; + optional sint64 sint64_field = 24; + optional fixed32 fixed32_field = 25; + optional fixed64 fixed64_field = 26; + optional sfixed32 sfixed32_field = 27; + optional sfixed64 sfixed64_field = 28; + optional bool bool_field = 29; + optional string string_field = 30; + optional bytes bytes_field = 31; + } + + oneof oneof_field { + int32 int32_oneof_field = 152; + float float_oneof_field = 153; + double double_oneof_field = 154; + int64 int64_oneof_field = 155; + uint32 uint32_oneof_field = 156; + uint64 uint64_oneof_field = 157; + sint32 sint32_oneof_field = 158; + sint64 sint64_oneof_field = 159; + fixed32 fixed32_oneof_field = 160; + fixed64 fixed64_oneof_field = 161; + sfixed32 sfixed32_oneof_field = 162; + sfixed64 sfixed64_oneof_field = 163; + bool bool_oneof_field = 164; + string string_oneof_field = 165; + bytes bytes_oneof_field = 166; + } + optional SubMessage sub_message = 2; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_packed.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_packed.proto new file mode 100644 index 0000000..b7dde2c --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_packed.proto @@ -0,0 +1,14 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto2"; + +package protobuf_editions_test.proto2; + +message Proto2Packed { + repeated int32 int32_field = 1 [packed = true]; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_proto3_enum.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_proto3_enum.proto new file mode 100644 index 0000000..9ffb861 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_proto3_enum.proto @@ -0,0 +1,18 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto2"; + +package protobuf_editions_test.proto2; + +import "google/protobuf/editions/codegen_tests/proto3_enum.proto"; + +message Proto2ImportedEnumMessage { + optional protobuf_editions_test.proto3.Proto3Enum enum_field = 1; + optional protobuf_editions_test.proto3.Proto3Enum enum_field_default = 2 + [default = BAZ]; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_required.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_required.proto new file mode 100644 index 0000000..7f3c6b4 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_required.proto @@ -0,0 +1,47 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto2"; + +package protobuf_editions_test.proto2; + +message Proto2Required { + required int32 int32_field = 17; + required float float_field = 18; + required double double_field = 19; + required int64 int64_field = 20; + required uint32 uint32_field = 21; + required uint64 uint64_field = 22; + required sint32 sint32_field = 23; + required sint64 sint64_field = 24; + required fixed32 fixed32_field = 25; + required fixed64 fixed64_field = 26; + required sfixed32 sfixed32_field = 27; + required sfixed64 sfixed64_field = 28; + required bool bool_field = 29; + required string string_field = 30; + required bytes bytes_field = 31; + + message SubMessage { + required int32 int32_field = 17; + required float float_field = 18; + required double double_field = 19; + required int64 int64_field = 20; + required uint32 uint32_field = 21; + required uint64 uint64_field = 22; + required sint32 sint32_field = 23; + required sint64 sint64_field = 24; + required fixed32 fixed32_field = 25; + required fixed64 fixed64_field = 26; + required sfixed32 sfixed32_field = 27; + required sfixed64 sfixed64_field = 28; + required bool bool_field = 29; + required string string_field = 30; + required bytes bytes_field = 31; + } + required SubMessage sub_message = 2; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_unpacked.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_unpacked.proto new file mode 100644 index 0000000..09e3211 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_unpacked.proto @@ -0,0 +1,19 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto2"; + +package protobuf_editions_test.proto2; + +message Proto2Unpacked { + repeated int32 int32_field = 1; + repeated string string_field = 2; + message SubMessage { + optional int32 int32_field = 1; + } + repeated SubMessage sub_message_field = 3; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_utf8_disabled.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_utf8_disabled.proto new file mode 100644 index 0000000..499ad2f --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_utf8_disabled.proto @@ -0,0 +1,16 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto2"; + +package protobuf_editions_test.proto2; + + +message Proto2Utf8Disabled { + optional string string_field = 1; + map map_field = 2; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_utf8_lite.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_utf8_lite.proto new file mode 100644 index 0000000..7225b1d --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_utf8_lite.proto @@ -0,0 +1,17 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto2"; + +package protobuf_editions_test.proto2; + +option optimize_for = LITE_RUNTIME; + +message Proto2Utf8Lite { + optional string string_field = 1; + map map_field = 2; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_utf8_verify.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_utf8_verify.proto new file mode 100644 index 0000000..5baf47b --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto2_utf8_verify.proto @@ -0,0 +1,14 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto2"; + +package protobuf_editions_test.proto2; + +message Proto2Utf8Verify { + optional string string_field = 1; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_enum.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_enum.proto new file mode 100644 index 0000000..6feab64 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_enum.proto @@ -0,0 +1,26 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto3"; + +package protobuf_editions_test.proto3; + +enum Proto3Enum { + UNKNOWN = 0; + BAR = 1; + BAZ = 2; +} + +message Proto3EnumMessage { + Proto3Enum enum_field = 1; + enum Proto3NestedEnum { + UNKNOWN = 0; + FOO = 1; + BAT = 2; + } + optional Proto3NestedEnum nested_enum_field = 3; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_implicit.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_implicit.proto new file mode 100644 index 0000000..e7f0f53 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_implicit.proto @@ -0,0 +1,65 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto3"; + +package protobuf_editions_test.proto3; + +message Proto3Implicit { + int32 int32_field = 17; + float float_field = 18; + double double_field = 19; + int64 int64_field = 20; + uint32 uint32_field = 21; + uint64 uint64_field = 22; + sint32 sint32_field = 23; + sint64 sint64_field = 24; + fixed32 fixed32_field = 25; + fixed64 fixed64_field = 26; + sfixed32 sfixed32_field = 27; + sfixed64 sfixed64_field = 28; + bool bool_field = 29; + string string_field = 30; + bytes bytes_field = 31; + + message SubMessage { + int32 int32_field = 17; + float float_field = 18; + double double_field = 19; + int64 int64_field = 20; + uint32 uint32_field = 21; + uint64 uint64_field = 22; + sint32 sint32_field = 23; + sint64 sint64_field = 24; + fixed32 fixed32_field = 25; + fixed64 fixed64_field = 26; + sfixed32 sfixed32_field = 27; + sfixed64 sfixed64_field = 28; + bool bool_field = 29; + string string_field = 30; + bytes bytes = 31; + } + + oneof oneof_field { + int32 int32_oneof_field = 152; + float float_oneof_field = 153; + double double_oneof_field = 154; + int64 int64_oneof_field = 155; + uint32 uint32_oneof_field = 156; + uint64 uint64_oneof_field = 157; + sint32 sint32_oneof_field = 158; + sint64 sint64_oneof_field = 159; + fixed32 fixed32_oneof_field = 160; + fixed64 fixed64_oneof_field = 161; + sfixed32 sfixed32_oneof_field = 162; + sfixed64 sfixed64_oneof_field = 163; + bool bool_oneof_field = 164; + string string_oneof_field = 165; + bytes bytes_oneof_field = 166; + } + SubMessage sub_message = 2; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_import.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_import.proto new file mode 100644 index 0000000..75a1d75 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_import.proto @@ -0,0 +1,16 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto3"; + +package protobuf_editions_test.proto3; + +import "google/protobuf/editions/codegen_tests/proto3_implicit.proto"; + +message Proto3ImportMessage { + Proto3Implicit sub_message_field = 1; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_optional.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_optional.proto new file mode 100644 index 0000000..8ab940d --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_optional.proto @@ -0,0 +1,47 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto3"; + +package protobuf_editions_test.proto3; + +message Proto3Optional { + optional int32 int32_field = 17; + optional float float_field = 18; + optional double double_field = 19; + optional int64 int64_field = 20; + optional uint32 uint32_field = 21; + optional uint64 uint64_field = 22; + optional sint32 sint32_field = 23; + optional sint64 sint64_field = 24; + optional fixed32 fixed32_field = 25; + optional fixed64 fixed64_field = 26; + optional sfixed32 sfixed32_field = 27; + optional sfixed64 sfixed64_field = 28; + optional bool bool_field = 29; + optional string string_field = 30; + optional bytes bytes_field = 31; + + message SubMessage { + optional int32 int32_field = 17; + optional float float_field = 18; + optional double double_field = 19; + optional int64 int64_field = 20; + optional uint32 uint32_field = 21; + optional uint64 uint64_field = 22; + optional sint32 sint32_field = 23; + optional sint64 sint64_field = 24; + optional fixed32 fixed32_field = 25; + optional fixed64 fixed64_field = 26; + optional sfixed32 sfixed32_field = 27; + optional sfixed64 sfixed64_field = 28; + optional bool bool_field = 29; + optional string string_field = 30; + optional bytes bytes_field = 31; + } + optional SubMessage optional_message = 2; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_packed.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_packed.proto new file mode 100644 index 0000000..3f511b5 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_packed.proto @@ -0,0 +1,20 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto3"; + +package protobuf_editions_test.proto3; + +message Proto3Packed { + repeated int32 int32_field = 1; + repeated string string_field = 2; + message SubMessage { + int32 int32_field = 1; + } + repeated SubMessage sub_message_field = 3; + repeated int32 explicitly_packed = 4 [packed = true]; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_unpacked.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_unpacked.proto new file mode 100644 index 0000000..8d13b9f --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_unpacked.proto @@ -0,0 +1,19 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto3"; + +package protobuf_editions_test.proto3; + +message Proto3Unpacked { + repeated int32 int32_field = 1 [packed = false]; + repeated string string_field = 2 [packed = false]; + message SubMessage { + int32 int32_field = 1; + } + repeated SubMessage sub_message_field = 3 [packed = false]; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_utf8_strict.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_utf8_strict.proto new file mode 100644 index 0000000..604fc7f --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/codegen_tests/proto3_utf8_strict.proto @@ -0,0 +1,15 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto3"; + +package protobuf_editions_test.proto3; + +message Proto3Utf8Strict { + string string_field = 1; + map map_field = 10; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/golden/editions_transform_proto2.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/golden/editions_transform_proto2.proto new file mode 100644 index 0000000..0e53870 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/golden/editions_transform_proto2.proto @@ -0,0 +1,129 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +edition = "2023"; + +// This file contains various edge cases we've collected from migrating real +// protos in order to lock down the transformations. + +// LINT: ALLOW_GROUPS + +package protobuf_editions_test; + +import "net/proto/proto1_features.proto"; +import "third_party/java_src/protobuf/current/java/com/google/protobuf/java_features.proto"; +import "google/protobuf/cpp_features.proto"; +import "google/protobuf/editions/proto/editions_transform_proto3.proto"; + +option features.repeated_field_encoding = EXPANDED; +option features.utf8_validation = NONE; +option java_multiple_files = true; + +message EmptyMessage { +} + +message EmptyMessage2 { +} + +service EmptyService { +} + +service BasicService { + rpc BasicMethod(EmptyMessage) returns (EmptyMessage) {} +} + +// clang-format off +message UnformattedMessage { + int32 a = 1; + + message Foo { + int32 a = 1; + } + + Foo foo = 2 [ + features.message_encoding = DELIMITED + ]; + + string string_piece_with_zero = 3 [ + ctype = STRING_PIECE, + default = "ab\000c" + ]; + + float long_float_name_wrapped = 4; +} + +// clang-format on + +message ParentMessage { + message ExtendedMessage { + extensions 536860000 to 536869999 [ + declaration = { + number: 536860000 + full_name: ".protobuf_editions_test.extension" + type: ".protobuf_editions_test.EmptyMessage" + } + ]; + } +} + +extend ParentMessage.ExtendedMessage { + EmptyMessage extension = 536860000; +} + +message TestMessage { + string string_field = 1; + map string_map_field = 7; + repeated int32 int_field = 8; + repeated int32 int_field_packed = 9 [ + features.repeated_field_encoding = PACKED, + features.(pb.proto1).legacy_packed = true + ]; + + repeated int32 int_field_unpacked = 10; + repeated int32 options_strip_beginning = 4 [ + /* inline comment */ + debug_redact = true, + deprecated = false + ]; + + repeated int32 options_strip_middle = 5 [ + debug_redact = true, + deprecated = false + ]; + + repeated int32 options_strip_end = 6 [ + debug_redact = true, + deprecated = false + ]; + + message OptionalGroup { + int32 a = 17; + } + + OptionalGroup optionalgroup = 16 [ + features.message_encoding = DELIMITED + ]; +} + +enum TestEnum { + option features.enum_type = CLOSED; + + FOO = 1; // Non-zero default + + BAR = 2; + BAZ = 3; + NEG = -1; // Intentionally negative. +} + +message TestOpenEnumMessage { + TestEnumProto3 open_enum_field = 1 [ + features.(pb.cpp).legacy_closed_enum = true, + features.(pb.java).legacy_closed_enum = true + ]; + + TestEnum closed_enum_field = 2; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/golden/editions_transform_proto2_lite.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/golden/editions_transform_proto2_lite.proto new file mode 100644 index 0000000..ca0d3d8 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/golden/editions_transform_proto2_lite.proto @@ -0,0 +1,19 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +edition = "2023"; + +package protobuf_editions_test; + +option features.utf8_validation = NONE; +option optimize_for = LITE_RUNTIME; + +message TestMessageLite { + string string_field = 1; + map string_map_field = 4; + int32 int_field = 5; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/golden/editions_transform_proto2_utf8_disabled.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/golden/editions_transform_proto2_utf8_disabled.proto new file mode 100644 index 0000000..b0a7086 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/golden/editions_transform_proto2_utf8_disabled.proto @@ -0,0 +1,18 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +edition = "2023"; + +package protobuf_editions_test; + +option features.utf8_validation = NONE; + +message TestMessageUtf8Disabled { + string string_field = 1; + map string_map_field = 4; + int32 int_field = 5; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/golden/editions_transform_proto3.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/golden/editions_transform_proto3.proto new file mode 100644 index 0000000..cbb91d0 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/golden/editions_transform_proto3.proto @@ -0,0 +1,32 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +edition = "2023"; + +package protobuf_editions_test; + +import "net/proto/proto1_features.proto"; + +option features.field_presence = IMPLICIT; + +enum TestEnumProto3 { + TEST_ENUM_PROTO3_UNKNOWN = 0; + TEST_ENUM_PROTO3_VALUE = 1; +} + +message TestMessageProto3 { + string string_field = 1; + map string_map_field = 4; + repeated int32 int_field = 7; + repeated int32 int_field_packed = 8 [ + features.(pb.proto1).legacy_packed = true + ]; + + repeated int32 int_field_unpacked = 9 [ + features.repeated_field_encoding = EXPANDED + ]; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/golden/editions_transform_proto3_utf8_disabled.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/golden/editions_transform_proto3_utf8_disabled.proto new file mode 100644 index 0000000..acb8081 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/golden/editions_transform_proto3_utf8_disabled.proto @@ -0,0 +1,18 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +edition = "2023"; + +package protobuf_editions_test; + +option features.field_presence = IMPLICIT; + +message TestMessageProto3 { + string string_field = 1; + map string_map_field = 4; + repeated int32 int_field = 7; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/golden/simple_proto2.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/golden/simple_proto2.proto new file mode 100644 index 0000000..ff06225 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/golden/simple_proto2.proto @@ -0,0 +1,14 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto2"; + +package protobuf_editions_test.golden; + +message SimpleProto2 { + optional int32 int32_field = 1; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/golden/simple_proto2_import.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/golden/simple_proto2_import.proto new file mode 100644 index 0000000..dc04bc3 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/golden/simple_proto2_import.proto @@ -0,0 +1,16 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto2"; + +package protobuf_editions_test.golden; + +import "google/protobuf/editions/golden/simple_proto2.proto"; + +message AnotherMessage { + optional SimpleProto2 field = 1; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/golden/simple_proto3.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/golden/simple_proto3.proto new file mode 100644 index 0000000..47c8dc1 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/golden/simple_proto3.proto @@ -0,0 +1,14 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto3"; + +package protobuf_editions_test.golden; + +message SimpleProto3 { + optional int32 int32_field = 1; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/proto/editions_transform_proto2.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/proto/editions_transform_proto2.proto new file mode 100644 index 0000000..e502cde --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/proto/editions_transform_proto2.proto @@ -0,0 +1,91 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto2"; + +import "google/protobuf/editions/proto/editions_transform_proto3.proto"; + +// This file contains various edge cases we've collected from migrating real +// protos in order to lock down the transformations. + +// LINT: ALLOW_GROUPS + +package protobuf_editions_test; + +option java_multiple_files = true; +option cc_enable_arenas = true; + +message EmptyMessage {} +message EmptyMessage2 {} + +service EmptyService {} + +service BasicService { + rpc BasicMethod(EmptyMessage) returns (EmptyMessage) {} +} + +// clang-format off +message UnformattedMessage{ + optional int32 a=1 ; + optional group Foo = 2 { optional int32 a = 1; } + optional string string_piece_with_zero = 3 [ctype=STRING_PIECE, + default="ab\000c"]; + optional float + long_float_name_wrapped = 4; + +} +// clang-format on + +message ParentMessage { + message ExtendedMessage { + extensions 536860000 to 536869999 [declaration = { + number: 536860000 + full_name: ".protobuf_editions_test.extension" + type: ".protobuf_editions_test.EmptyMessage" + }]; + } +} + +extend ParentMessage.ExtendedMessage { + optional EmptyMessage extension = 536860000; +} + +message TestMessage { + optional string string_field = 1; + + map string_map_field = 7; + + repeated int32 int_field = 8; + repeated int32 int_field_packed = 9 [packed = true]; + repeated int32 int_field_unpacked = 10 [packed = false]; + + repeated int32 options_strip_beginning = 4 [ + packed = false, + /* inline comment*/ debug_redact = true, + deprecated = false + ]; + repeated int32 options_strip_middle = 5 + [debug_redact = true, packed = false, deprecated = false]; + repeated int32 options_strip_end = 6 + [debug_redact = true, deprecated = false, packed = false]; + + optional group OptionalGroup = 16 { + optional int32 a = 17; + } +} + +enum TestEnum { + FOO = 1; // Non-zero default + BAR = 2; + BAZ = 3; + NEG = -1; // Intentionally negative. +} + +message TestOpenEnumMessage { + optional TestEnumProto3 open_enum_field = 1; + optional TestEnum closed_enum_field = 2; +} \ No newline at end of file diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/proto/editions_transform_proto2_lite.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/proto/editions_transform_proto2_lite.proto new file mode 100644 index 0000000..19b808a --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/proto/editions_transform_proto2_lite.proto @@ -0,0 +1,20 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto2"; + +package protobuf_editions_test; + +option optimize_for = LITE_RUNTIME; + +message TestMessageLite { + optional string string_field = 1; + + map string_map_field = 4; + + optional int32 int_field = 5; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/proto/editions_transform_proto2_utf8_disabled.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/proto/editions_transform_proto2_utf8_disabled.proto new file mode 100644 index 0000000..985f863 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/proto/editions_transform_proto2_utf8_disabled.proto @@ -0,0 +1,19 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto2"; + +package protobuf_editions_test; + + +message TestMessageUtf8Disabled { + optional string string_field = 1; + + map string_map_field = 4; + + optional int32 int_field = 5; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/proto/editions_transform_proto3.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/proto/editions_transform_proto3.proto new file mode 100644 index 0000000..6dc8b4f --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/proto/editions_transform_proto3.proto @@ -0,0 +1,25 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto3"; + +package protobuf_editions_test; + +enum TestEnumProto3 { + TEST_ENUM_PROTO3_UNKNOWN = 0; + TEST_ENUM_PROTO3_VALUE = 1; +} + +message TestMessageProto3 { + string string_field = 1; + + map string_map_field = 4; + + repeated int32 int_field = 7; + repeated int32 int_field_packed = 8 [packed = true]; + repeated int32 int_field_unpacked = 9 [packed = false]; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/editions/proto/editions_transform_proto3_utf8_disabled.proto b/node_modules/google-gax/build/protos/google/protobuf/editions/proto/editions_transform_proto3_utf8_disabled.proto new file mode 100644 index 0000000..b7d2b69 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/editions/proto/editions_transform_proto3_utf8_disabled.proto @@ -0,0 +1,19 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2023 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto3"; + +package protobuf_editions_test; + + +message TestMessageProto3 { + string string_field = 1; + + map string_map_field = 4; + + repeated int32 int_field = 7; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/empty.proto b/node_modules/google-gax/build/protos/google/protobuf/empty.proto new file mode 100644 index 0000000..b87c89d --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/empty.proto @@ -0,0 +1,51 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option go_package = "google.golang.org/protobuf/types/known/emptypb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "EmptyProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; +option cc_enable_arenas = true; + +// A generic empty message that you can re-use to avoid defining duplicated +// empty messages in your APIs. A typical example is to use it as the request +// or the response type of an API method. For instance: +// +// service Foo { +// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); +// } +// +message Empty {} diff --git a/node_modules/google-gax/build/protos/google/protobuf/field_mask.proto b/node_modules/google-gax/build/protos/google/protobuf/field_mask.proto new file mode 100644 index 0000000..b28334b --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/field_mask.proto @@ -0,0 +1,245 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option java_package = "com.google.protobuf"; +option java_outer_classname = "FieldMaskProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; +option go_package = "google.golang.org/protobuf/types/known/fieldmaskpb"; +option cc_enable_arenas = true; + +// `FieldMask` represents a set of symbolic field paths, for example: +// +// paths: "f.a" +// paths: "f.b.d" +// +// Here `f` represents a field in some root message, `a` and `b` +// fields in the message found in `f`, and `d` a field found in the +// message in `f.b`. +// +// Field masks are used to specify a subset of fields that should be +// returned by a get operation or modified by an update operation. +// Field masks also have a custom JSON encoding (see below). +// +// # Field Masks in Projections +// +// When used in the context of a projection, a response message or +// sub-message is filtered by the API to only contain those fields as +// specified in the mask. For example, if the mask in the previous +// example is applied to a response message as follows: +// +// f { +// a : 22 +// b { +// d : 1 +// x : 2 +// } +// y : 13 +// } +// z: 8 +// +// The result will not contain specific values for fields x,y and z +// (their value will be set to the default, and omitted in proto text +// output): +// +// +// f { +// a : 22 +// b { +// d : 1 +// } +// } +// +// A repeated field is not allowed except at the last position of a +// paths string. +// +// If a FieldMask object is not present in a get operation, the +// operation applies to all fields (as if a FieldMask of all fields +// had been specified). +// +// Note that a field mask does not necessarily apply to the +// top-level response message. In case of a REST get operation, the +// field mask applies directly to the response, but in case of a REST +// list operation, the mask instead applies to each individual message +// in the returned resource list. In case of a REST custom method, +// other definitions may be used. Where the mask applies will be +// clearly documented together with its declaration in the API. In +// any case, the effect on the returned resource/resources is required +// behavior for APIs. +// +// # Field Masks in Update Operations +// +// A field mask in update operations specifies which fields of the +// targeted resource are going to be updated. The API is required +// to only change the values of the fields as specified in the mask +// and leave the others untouched. If a resource is passed in to +// describe the updated values, the API ignores the values of all +// fields not covered by the mask. +// +// If a repeated field is specified for an update operation, new values will +// be appended to the existing repeated field in the target resource. Note that +// a repeated field is only allowed in the last position of a `paths` string. +// +// If a sub-message is specified in the last position of the field mask for an +// update operation, then new value will be merged into the existing sub-message +// in the target resource. +// +// For example, given the target message: +// +// f { +// b { +// d: 1 +// x: 2 +// } +// c: [1] +// } +// +// And an update message: +// +// f { +// b { +// d: 10 +// } +// c: [2] +// } +// +// then if the field mask is: +// +// paths: ["f.b", "f.c"] +// +// then the result will be: +// +// f { +// b { +// d: 10 +// x: 2 +// } +// c: [1, 2] +// } +// +// An implementation may provide options to override this default behavior for +// repeated and message fields. +// +// In order to reset a field's value to the default, the field must +// be in the mask and set to the default value in the provided resource. +// Hence, in order to reset all fields of a resource, provide a default +// instance of the resource and set all fields in the mask, or do +// not provide a mask as described below. +// +// If a field mask is not present on update, the operation applies to +// all fields (as if a field mask of all fields has been specified). +// Note that in the presence of schema evolution, this may mean that +// fields the client does not know and has therefore not filled into +// the request will be reset to their default. If this is unwanted +// behavior, a specific service may require a client to always specify +// a field mask, producing an error if not. +// +// As with get operations, the location of the resource which +// describes the updated values in the request message depends on the +// operation kind. In any case, the effect of the field mask is +// required to be honored by the API. +// +// ## Considerations for HTTP REST +// +// The HTTP kind of an update operation which uses a field mask must +// be set to PATCH instead of PUT in order to satisfy HTTP semantics +// (PUT must only be used for full updates). +// +// # JSON Encoding of Field Masks +// +// In JSON, a field mask is encoded as a single string where paths are +// separated by a comma. Fields name in each path are converted +// to/from lower-camel naming conventions. +// +// As an example, consider the following message declarations: +// +// message Profile { +// User user = 1; +// Photo photo = 2; +// } +// message User { +// string display_name = 1; +// string address = 2; +// } +// +// In proto a field mask for `Profile` may look as such: +// +// mask { +// paths: "user.display_name" +// paths: "photo" +// } +// +// In JSON, the same mask is represented as below: +// +// { +// mask: "user.displayName,photo" +// } +// +// # Field Masks and Oneof Fields +// +// Field masks treat fields in oneofs just as regular fields. Consider the +// following message: +// +// message SampleMessage { +// oneof test_oneof { +// string name = 4; +// SubMessage sub_message = 9; +// } +// } +// +// The field mask can be: +// +// mask { +// paths: "name" +// } +// +// Or: +// +// mask { +// paths: "sub_message" +// } +// +// Note that oneof type names ("test_oneof" in this case) cannot be used in +// paths. +// +// ## Field Mask Verification +// +// The implementation of any API method which has a FieldMask type field in the +// request should verify the included field paths, and return an +// `INVALID_ARGUMENT` error if any path is unmappable. +message FieldMask { + // The set of field mask paths. + repeated string paths = 1; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/sample_messages_edition.proto b/node_modules/google-gax/build/protos/google/protobuf/sample_messages_edition.proto new file mode 100644 index 0000000..464a816 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/sample_messages_edition.proto @@ -0,0 +1,427 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd +// +// Sample messages to generate example code. + +edition = "2023"; + +package protobuf_test_messages.edition; + +import "google/protobuf/cpp_features.proto"; + +option optimize_for = SPEED; +option features.(pb.cpp).string_type = VIEW; + +// This proto includes every type of field in both singular and repeated +// forms. +// +// Also, crucially, all messages and enums in this file are eventually +// submessages of this message. So for example, a fuzz test of TestAllTypes +// could trigger bugs that occur in any message type in this file. We verify +// this stays true in a unit test. +message TestAllTypesEdition { + message NestedMessage { + int32 a = 1; + TestAllTypesEdition corecursive = 2; + } + + enum NestedEnum { + FOO = 0; + BAR = 1; + BAZ = 2; + NEG = -1; // Intentionally negative. + } + + // Singular + int32 optional_int32 = 1; + int64 optional_int64 = 2; + uint32 optional_uint32 = 3; + uint64 optional_uint64 = 4; + sint32 optional_sint32 = 5; + sint64 optional_sint64 = 6; + fixed32 optional_fixed32 = 7; + fixed64 optional_fixed64 = 8; + sfixed32 optional_sfixed32 = 9; + sfixed64 optional_sfixed64 = 10; + float optional_float = 11; + double optional_double = 12; + bool optional_bool = 13; + string optional_string = 14; + bytes optional_bytes = 15; + + NestedMessage optional_nested_message = 18; + ForeignMessageEdition optional_foreign_message = 19; + + NestedEnum optional_nested_enum = 21; + ForeignEnumEdition optional_foreign_enum = 22; + + string optional_string_piece = 24 [ctype = STRING_PIECE]; + string optional_cord = 25 [ctype = CORD]; + + TestAllTypesEdition recursive_message = 27; + + // Repeated + repeated int32 repeated_int32 = 31; + repeated int64 repeated_int64 = 32; + repeated uint32 repeated_uint32 = 33; + repeated uint64 repeated_uint64 = 34; + repeated sint32 repeated_sint32 = 35; + repeated sint64 repeated_sint64 = 36; + repeated fixed32 repeated_fixed32 = 37; + repeated fixed64 repeated_fixed64 = 38; + repeated sfixed32 repeated_sfixed32 = 39; + repeated sfixed64 repeated_sfixed64 = 40; + repeated float repeated_float = 41; + repeated double repeated_double = 42; + repeated bool repeated_bool = 43; + repeated string repeated_string = 44; + repeated bytes repeated_bytes = 45; + + repeated NestedMessage repeated_nested_message = 48; + repeated ForeignMessageEdition repeated_foreign_message = 49; + + repeated NestedEnum repeated_nested_enum = 51; + repeated ForeignEnumEdition repeated_foreign_enum = 52; + + repeated string repeated_string_piece = 54 [ctype = STRING_PIECE]; + repeated string repeated_cord = 55 [ctype = CORD]; + + // Packed + repeated int32 packed_int32 = 75 [features.repeated_field_encoding = PACKED]; + repeated int64 packed_int64 = 76 [features.repeated_field_encoding = PACKED]; + repeated uint32 packed_uint32 = 77 + [features.repeated_field_encoding = PACKED]; + repeated uint64 packed_uint64 = 78 + [features.repeated_field_encoding = PACKED]; + repeated sint32 packed_sint32 = 79 + [features.repeated_field_encoding = PACKED]; + repeated sint64 packed_sint64 = 80 + [features.repeated_field_encoding = PACKED]; + repeated fixed32 packed_fixed32 = 81 + [features.repeated_field_encoding = PACKED]; + repeated fixed64 packed_fixed64 = 82 + [features.repeated_field_encoding = PACKED]; + repeated sfixed32 packed_sfixed32 = 83 + [features.repeated_field_encoding = PACKED]; + repeated sfixed64 packed_sfixed64 = 84 + [features.repeated_field_encoding = PACKED]; + repeated float packed_float = 85 [features.repeated_field_encoding = PACKED]; + repeated double packed_double = 86 + [features.repeated_field_encoding = PACKED]; + repeated bool packed_bool = 87 [features.repeated_field_encoding = PACKED]; + repeated NestedEnum packed_nested_enum = 88 + [features.repeated_field_encoding = PACKED]; + + // Unpacked + repeated int32 unpacked_int32 = 89 + [features.repeated_field_encoding = EXPANDED]; + repeated int64 unpacked_int64 = 90 + [features.repeated_field_encoding = EXPANDED]; + repeated uint32 unpacked_uint32 = 91 + [features.repeated_field_encoding = EXPANDED]; + repeated uint64 unpacked_uint64 = 92 + [features.repeated_field_encoding = EXPANDED]; + repeated sint32 unpacked_sint32 = 93 + [features.repeated_field_encoding = EXPANDED]; + repeated sint64 unpacked_sint64 = 94 + [features.repeated_field_encoding = EXPANDED]; + repeated fixed32 unpacked_fixed32 = 95 + [features.repeated_field_encoding = EXPANDED]; + repeated fixed64 unpacked_fixed64 = 96 + [features.repeated_field_encoding = EXPANDED]; + repeated sfixed32 unpacked_sfixed32 = 97 + [features.repeated_field_encoding = EXPANDED]; + repeated sfixed64 unpacked_sfixed64 = 98 + [features.repeated_field_encoding = EXPANDED]; + repeated float unpacked_float = 99 + [features.repeated_field_encoding = EXPANDED]; + repeated double unpacked_double = 100 + [features.repeated_field_encoding = EXPANDED]; + repeated bool unpacked_bool = 101 + [features.repeated_field_encoding = EXPANDED]; + repeated NestedEnum unpacked_nested_enum = 102 + [features.repeated_field_encoding = EXPANDED]; + + // Map + map map_int32_int32 = 56; + map map_int64_int64 = 57; + map map_uint32_uint32 = 58; + map map_uint64_uint64 = 59; + map map_sint32_sint32 = 60; + map map_sint64_sint64 = 61; + map map_fixed32_fixed32 = 62; + map map_fixed64_fixed64 = 63; + map map_sfixed32_sfixed32 = 64; + map map_sfixed64_sfixed64 = 65; + map map_int32_float = 66; + map map_int32_double = 67; + map map_bool_bool = 68; + map map_string_string = 69; + map map_string_bytes = 70; + map map_string_nested_message = 71; + map map_string_foreign_message = 72; + map map_string_nested_enum = 73; + map map_string_foreign_enum = 74; + + oneof oneof_field { + uint32 oneof_uint32 = 111; + NestedMessage oneof_nested_message = 112; + string oneof_string = 113; + bytes oneof_bytes = 114; + bool oneof_bool = 115; + uint64 oneof_uint64 = 116; + float oneof_float = 117; + double oneof_double = 118; + NestedEnum oneof_enum = 119; + } + + // extensions + extensions 120 to 200; + + // groups + message Data { + int32 group_int32 = 202; + uint32 group_uint32 = 203; + } + + Data data = 201 [features.message_encoding = DELIMITED]; + + // default values + int32 default_int32 = 241 [default = -123456789]; + int64 default_int64 = 242 [default = -9123456789123456789]; + uint32 default_uint32 = 243 [default = 2123456789]; + uint64 default_uint64 = 244 [default = 10123456789123456789]; + sint32 default_sint32 = 245 [default = -123456789]; + sint64 default_sint64 = 246 [default = -9123456789123456789]; + fixed32 default_fixed32 = 247 [default = 2123456789]; + fixed64 default_fixed64 = 248 [default = 10123456789123456789]; + sfixed32 default_sfixed32 = 249 [default = -123456789]; + sfixed64 default_sfixed64 = 250 [default = -9123456789123456789]; + float default_float = 251 [default = 9e9]; + double default_double = 252 [default = 7e22]; + bool default_bool = 253 [default = true]; + string default_string = 254 [default = "Rosebud"]; + bytes default_bytes = 255 [default = "joshua"]; + + // Test field-name-to-JSON-name convention. + // (protobuf says names can be any valid C/C++ identifier.) + int32 fieldname1 = 401; + int32 field_name2 = 402; + int32 _field_name3 = 403; + int32 field__name4_ = 404; + int32 field0name5 = 405; + int32 field_0_name6 = 406; + int32 fieldName7 = 407; + int32 FieldName8 = 408; + int32 field_Name9 = 409; + int32 Field_Name10 = 410; + int32 FIELD_NAME11 = 411; + int32 FIELD_name12 = 412; + int32 __field_name13 = 413; + int32 __Field_name14 = 414; + int32 field__name15 = 415; + int32 field__Name16 = 416; + int32 field_name17__ = 417; + int32 Field_name18__ = 418; + + // Reserved for unknown fields test. + reserved 1000 to 9999; + + // message_set test case. + message MessageSetCorrect { + option message_set_wire_format = true; + + extensions 4 to max; + } + + message MessageSetCorrectExtension1 { + extend MessageSetCorrect { + MessageSetCorrectExtension1 message_set_extension = 1547769; + } + string str = 25; + } + + message MessageSetCorrectExtension2 { + extend MessageSetCorrect { + MessageSetCorrectExtension2 message_set_extension = 4135312; + } + int32 i = 9; + } +} + +message ForeignMessageEdition { + int32 c = 1; +} + +enum ForeignEnumEdition { + FOREIGN_FOO = 0; + FOREIGN_BAR = 1; + FOREIGN_BAZ = 2; +} + +extend TestAllTypesEdition { + int32 extension_int32 = 120; +} + +message UnknownToTestAllTypes { + int32 optional_int32 = 1001; + string optional_string = 1002; + ForeignMessageEdition nested_message = 1003; + message OptionalGroup { + int32 a = 1; + } + OptionalGroup optionalgroup = 1004 [features.message_encoding = DELIMITED]; + bool optional_bool = 1006; + repeated int32 repeated_int32 = 1011; +} + +message NullHypothesisEdition {} + +message EnumOnlyEdition { + enum Bool { + kFalse = 0; + kTrue = 1; + } +} + +message OneStringEdition { + string data = 1; +} + +message ProtoWithKeywords { + int32 inline = 1; + string concept = 2; + repeated string requires = 3; +} + +message TestAllRequiredTypesEdition { + message NestedMessage { + int32 a = 1 [features.field_presence = LEGACY_REQUIRED]; + TestAllRequiredTypesEdition corecursive = 2 + [features.field_presence = LEGACY_REQUIRED]; + TestAllRequiredTypesEdition optional_corecursive = 3; + } + + enum NestedEnum { + FOO = 0; + BAR = 1; + BAZ = 2; + NEG = -1; // Intentionally negative. + } + + // Singular + int32 required_int32 = 1 [features.field_presence = LEGACY_REQUIRED]; + int64 required_int64 = 2 [features.field_presence = LEGACY_REQUIRED]; + uint32 required_uint32 = 3 [features.field_presence = LEGACY_REQUIRED]; + uint64 required_uint64 = 4 [features.field_presence = LEGACY_REQUIRED]; + sint32 required_sint32 = 5 [features.field_presence = LEGACY_REQUIRED]; + sint64 required_sint64 = 6 [features.field_presence = LEGACY_REQUIRED]; + fixed32 required_fixed32 = 7 [features.field_presence = LEGACY_REQUIRED]; + fixed64 required_fixed64 = 8 [features.field_presence = LEGACY_REQUIRED]; + sfixed32 required_sfixed32 = 9 [features.field_presence = LEGACY_REQUIRED]; + sfixed64 required_sfixed64 = 10 [features.field_presence = LEGACY_REQUIRED]; + float required_float = 11 [features.field_presence = LEGACY_REQUIRED]; + double required_double = 12 [features.field_presence = LEGACY_REQUIRED]; + bool required_bool = 13 [features.field_presence = LEGACY_REQUIRED]; + string required_string = 14 [features.field_presence = LEGACY_REQUIRED]; + bytes required_bytes = 15 [features.field_presence = LEGACY_REQUIRED]; + + NestedMessage required_nested_message = 18 + [features.field_presence = LEGACY_REQUIRED]; + ForeignMessageEdition required_foreign_message = 19 + [features.field_presence = LEGACY_REQUIRED]; + + NestedEnum required_nested_enum = 21 + [features.field_presence = LEGACY_REQUIRED]; + ForeignEnumEdition required_foreign_enum = 22 + [features.field_presence = LEGACY_REQUIRED]; + + string required_string_piece = 24 + [ctype = STRING_PIECE, features.field_presence = LEGACY_REQUIRED]; + string required_cord = 25 + [ctype = CORD, features.field_presence = LEGACY_REQUIRED]; + + TestAllRequiredTypesEdition recursive_message = 27; + TestAllRequiredTypesEdition optional_recursive_message = 28; + + // extensions + extensions 120 to 200; + + // groups + message Data { + int32 group_int32 = 202 [features.field_presence = LEGACY_REQUIRED]; + uint32 group_uint32 = 203 [features.field_presence = LEGACY_REQUIRED]; + } + + Data data = 201 [features.message_encoding = DELIMITED]; + + // default values + int32 default_int32 = 241 + [default = -123456789, features.field_presence = LEGACY_REQUIRED]; + int64 default_int64 = 242 [ + default = -9123456789123456789, + features.field_presence = LEGACY_REQUIRED + ]; + uint32 default_uint32 = 243 + [default = 2123456789, features.field_presence = LEGACY_REQUIRED]; + uint64 default_uint64 = 244 [ + default = 10123456789123456789, + features.field_presence = LEGACY_REQUIRED + ]; + sint32 default_sint32 = 245 + [default = -123456789, features.field_presence = LEGACY_REQUIRED]; + sint64 default_sint64 = 246 [ + default = -9123456789123456789, + features.field_presence = LEGACY_REQUIRED + ]; + fixed32 default_fixed32 = 247 + [default = 2123456789, features.field_presence = LEGACY_REQUIRED]; + fixed64 default_fixed64 = 248 [ + default = 10123456789123456789, + features.field_presence = LEGACY_REQUIRED + ]; + sfixed32 default_sfixed32 = 249 + [default = -123456789, features.field_presence = LEGACY_REQUIRED]; + sfixed64 default_sfixed64 = 250 [ + default = -9123456789123456789, + features.field_presence = LEGACY_REQUIRED + ]; + float default_float = 251 + [default = 9e9, features.field_presence = LEGACY_REQUIRED]; + double default_double = 252 + [default = 7e22, features.field_presence = LEGACY_REQUIRED]; + bool default_bool = 253 + [default = true, features.field_presence = LEGACY_REQUIRED]; + string default_string = 254 + [default = "Rosebud", features.field_presence = LEGACY_REQUIRED]; + bytes default_bytes = 255 + [default = "joshua", features.field_presence = LEGACY_REQUIRED]; + + // Reserved for unknown fields test. + reserved 1000 to 9999; + + // message_set test case. + message MessageSetCorrect { + option message_set_wire_format = true; + + extensions 4 to max; + } + + message MessageSetCorrectExtension1 { + extend MessageSetCorrect { + MessageSetCorrectExtension1 message_set_extension = 1547769; + } + string str = 25 [features.field_presence = LEGACY_REQUIRED]; + } + + message MessageSetCorrectExtension2 { + extend MessageSetCorrect { + MessageSetCorrectExtension2 message_set_extension = 4135312; + } + int32 i = 9 [features.field_presence = LEGACY_REQUIRED]; + } +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/source_context.proto b/node_modules/google-gax/build/protos/google/protobuf/source_context.proto new file mode 100644 index 0000000..135f50f --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/source_context.proto @@ -0,0 +1,48 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option java_package = "com.google.protobuf"; +option java_outer_classname = "SourceContextProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; +option go_package = "google.golang.org/protobuf/types/known/sourcecontextpb"; + +// `SourceContext` represents information about the source of a +// protobuf element, like the file in which it is defined. +message SourceContext { + // The path-qualified name of the .proto file that contained the associated + // protobuf element. For example: `"google/protobuf/source_context.proto"`. + string file_name = 1; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/struct.proto b/node_modules/google-gax/build/protos/google/protobuf/struct.proto new file mode 100644 index 0000000..1bf0c1a --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/struct.proto @@ -0,0 +1,95 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/protobuf/types/known/structpb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "StructProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; + +// `Struct` represents a structured data value, consisting of fields +// which map to dynamically typed values. In some languages, `Struct` +// might be supported by a native representation. For example, in +// scripting languages like JS a struct is represented as an +// object. The details of that representation are described together +// with the proto support for the language. +// +// The JSON representation for `Struct` is JSON object. +message Struct { + // Unordered map of dynamically typed values. + map fields = 1; +} + +// `Value` represents a dynamically typed value which can be either +// null, a number, a string, a boolean, a recursive struct value, or a +// list of values. A producer of value is expected to set one of these +// variants. Absence of any variant indicates an error. +// +// The JSON representation for `Value` is JSON value. +message Value { + // The kind of value. + oneof kind { + // Represents a null value. + NullValue null_value = 1; + // Represents a double value. + double number_value = 2; + // Represents a string value. + string string_value = 3; + // Represents a boolean value. + bool bool_value = 4; + // Represents a structured value. + Struct struct_value = 5; + // Represents a repeated `Value`. + ListValue list_value = 6; + } +} + +// `NullValue` is a singleton enumeration to represent the null value for the +// `Value` type union. +// +// The JSON representation for `NullValue` is JSON `null`. +enum NullValue { + // Null value. + NULL_VALUE = 0; +} + +// `ListValue` is a wrapper around a repeated field of values. +// +// The JSON representation for `ListValue` is JSON array. +message ListValue { + // Repeated field of dynamically typed values. + repeated Value values = 1; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/timestamp.proto b/node_modules/google-gax/build/protos/google/protobuf/timestamp.proto new file mode 100644 index 0000000..fd0bc07 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/timestamp.proto @@ -0,0 +1,144 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/protobuf/types/known/timestamppb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "TimestampProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; + +// A Timestamp represents a point in time independent of any time zone or local +// calendar, encoded as a count of seconds and fractions of seconds at +// nanosecond resolution. The count is relative to an epoch at UTC midnight on +// January 1, 1970, in the proleptic Gregorian calendar which extends the +// Gregorian calendar backwards to year one. +// +// All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap +// second table is needed for interpretation, using a [24-hour linear +// smear](https://developers.google.com/time/smear). +// +// The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By +// restricting to that range, we ensure that we can convert to and from [RFC +// 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings. +// +// # Examples +// +// Example 1: Compute Timestamp from POSIX `time()`. +// +// Timestamp timestamp; +// timestamp.set_seconds(time(NULL)); +// timestamp.set_nanos(0); +// +// Example 2: Compute Timestamp from POSIX `gettimeofday()`. +// +// struct timeval tv; +// gettimeofday(&tv, NULL); +// +// Timestamp timestamp; +// timestamp.set_seconds(tv.tv_sec); +// timestamp.set_nanos(tv.tv_usec * 1000); +// +// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. +// +// FILETIME ft; +// GetSystemTimeAsFileTime(&ft); +// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; +// +// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z +// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. +// Timestamp timestamp; +// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); +// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); +// +// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. +// +// long millis = System.currentTimeMillis(); +// +// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) +// .setNanos((int) ((millis % 1000) * 1000000)).build(); +// +// Example 5: Compute Timestamp from Java `Instant.now()`. +// +// Instant now = Instant.now(); +// +// Timestamp timestamp = +// Timestamp.newBuilder().setSeconds(now.getEpochSecond()) +// .setNanos(now.getNano()).build(); +// +// Example 6: Compute Timestamp from current time in Python. +// +// timestamp = Timestamp() +// timestamp.GetCurrentTime() +// +// # JSON Mapping +// +// In JSON format, the Timestamp type is encoded as a string in the +// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the +// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" +// where {year} is always expressed using four digits while {month}, {day}, +// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional +// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), +// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone +// is required. A proto3 JSON serializer should always use UTC (as indicated by +// "Z") when printing the Timestamp type and a proto3 JSON parser should be +// able to accept both UTC and other timezones (as indicated by an offset). +// +// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past +// 01:30 UTC on January 15, 2017. +// +// In JavaScript, one can convert a Date object to this format using the +// standard +// [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) +// method. In Python, a standard `datetime.datetime` object can be converted +// to this format using +// [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with +// the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use +// the Joda Time's [`ISODateTimeFormat.dateTime()`]( +// http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime() +// ) to obtain a formatter capable of generating timestamps in this format. +// +message Timestamp { + // Represents seconds of UTC time since Unix epoch + // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + // 9999-12-31T23:59:59Z inclusive. + int64 seconds = 1; + + // Non-negative fractions of a second at nanosecond resolution. Negative + // second values with fractions must still have non-negative nanos values + // that count forward in time. Must be from 0 to 999,999,999 + // inclusive. + int32 nanos = 2; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/type.proto b/node_modules/google-gax/build/protos/google/protobuf/type.proto new file mode 100644 index 0000000..48cb11e --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/type.proto @@ -0,0 +1,193 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +import "google/protobuf/any.proto"; +import "google/protobuf/source_context.proto"; + +option cc_enable_arenas = true; +option java_package = "com.google.protobuf"; +option java_outer_classname = "TypeProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; +option go_package = "google.golang.org/protobuf/types/known/typepb"; + +// A protocol buffer message type. +message Type { + // The fully qualified message name. + string name = 1; + // The list of fields. + repeated Field fields = 2; + // The list of types appearing in `oneof` definitions in this type. + repeated string oneofs = 3; + // The protocol buffer options. + repeated Option options = 4; + // The source context. + SourceContext source_context = 5; + // The source syntax. + Syntax syntax = 6; + // The source edition string, only valid when syntax is SYNTAX_EDITIONS. + string edition = 7; +} + +// A single field of a message type. +message Field { + // Basic field types. + enum Kind { + // Field type unknown. + TYPE_UNKNOWN = 0; + // Field type double. + TYPE_DOUBLE = 1; + // Field type float. + TYPE_FLOAT = 2; + // Field type int64. + TYPE_INT64 = 3; + // Field type uint64. + TYPE_UINT64 = 4; + // Field type int32. + TYPE_INT32 = 5; + // Field type fixed64. + TYPE_FIXED64 = 6; + // Field type fixed32. + TYPE_FIXED32 = 7; + // Field type bool. + TYPE_BOOL = 8; + // Field type string. + TYPE_STRING = 9; + // Field type group. Proto2 syntax only, and deprecated. + TYPE_GROUP = 10; + // Field type message. + TYPE_MESSAGE = 11; + // Field type bytes. + TYPE_BYTES = 12; + // Field type uint32. + TYPE_UINT32 = 13; + // Field type enum. + TYPE_ENUM = 14; + // Field type sfixed32. + TYPE_SFIXED32 = 15; + // Field type sfixed64. + TYPE_SFIXED64 = 16; + // Field type sint32. + TYPE_SINT32 = 17; + // Field type sint64. + TYPE_SINT64 = 18; + } + + // Whether a field is optional, required, or repeated. + enum Cardinality { + // For fields with unknown cardinality. + CARDINALITY_UNKNOWN = 0; + // For optional fields. + CARDINALITY_OPTIONAL = 1; + // For required fields. Proto2 syntax only. + CARDINALITY_REQUIRED = 2; + // For repeated fields. + CARDINALITY_REPEATED = 3; + } + + // The field type. + Kind kind = 1; + // The field cardinality. + Cardinality cardinality = 2; + // The field number. + int32 number = 3; + // The field name. + string name = 4; + // The field type URL, without the scheme, for message or enumeration + // types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`. + string type_url = 6; + // The index of the field type in `Type.oneofs`, for message or enumeration + // types. The first type has index 1; zero means the type is not in the list. + int32 oneof_index = 7; + // Whether to use alternative packed wire representation. + bool packed = 8; + // The protocol buffer options. + repeated Option options = 9; + // The field JSON name. + string json_name = 10; + // The string value of the default value of this field. Proto2 syntax only. + string default_value = 11; +} + +// Enum type definition. +message Enum { + // Enum type name. + string name = 1; + // Enum value definitions. + repeated EnumValue enumvalue = 2; + // Protocol buffer options. + repeated Option options = 3; + // The source context. + SourceContext source_context = 4; + // The source syntax. + Syntax syntax = 5; + // The source edition string, only valid when syntax is SYNTAX_EDITIONS. + string edition = 6; +} + +// Enum value definition. +message EnumValue { + // Enum value name. + string name = 1; + // Enum value number. + int32 number = 2; + // Protocol buffer options. + repeated Option options = 3; +} + +// A protocol buffer option, which can be attached to a message, field, +// enumeration, etc. +message Option { + // The option's name. For protobuf built-in options (options defined in + // descriptor.proto), this is the short name. For example, `"map_entry"`. + // For custom options, it should be the fully-qualified name. For example, + // `"google.api.http"`. + string name = 1; + // The option's value packed in an Any message. If the value is a primitive, + // the corresponding wrapper type defined in google/protobuf/wrappers.proto + // should be used. If the value is an enum, it should be stored as an int32 + // value using the google.protobuf.Int32Value type. + Any value = 2; +} + +// The syntax in which a protocol buffer element is defined. +enum Syntax { + // Syntax `proto2`. + SYNTAX_PROTO2 = 0; + // Syntax `proto3`. + SYNTAX_PROTO3 = 1; + // Syntax `editions`. + SYNTAX_EDITIONS = 2; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/util/json_format.proto b/node_modules/google-gax/build/protos/google/protobuf/util/json_format.proto new file mode 100644 index 0000000..7cb3111 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/util/json_format.proto @@ -0,0 +1,116 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. +// +// A proto file we will use for unit testing. + +syntax = "proto2"; + +package protobuf_unittest; + +message TestFlagsAndStrings { + required int32 A = 1; + repeated group RepeatedGroup = 2 { + required string f = 3; + } +} + +message TestBase64ByteArrays { + required bytes a = 1; +} + +message TestJavaScriptJSON { + optional int32 a = 1; + optional float final = 2; + optional string in = 3; + optional string Var = 4; +} + +message TestJavaScriptOrderJSON1 { + optional int32 d = 1; + optional int32 c = 2; + optional bool x = 3; + optional int32 b = 4; + optional int32 a = 5; +} + +message TestJavaScriptOrderJSON2 { + optional int32 d = 1; + optional int32 c = 2; + optional bool x = 3; + optional int32 b = 4; + optional int32 a = 5; + repeated TestJavaScriptOrderJSON1 z = 6; +} + +message TestLargeInt { + required int64 a = 1; + required uint64 b = 2; +} + +message TestNumbers { + enum MyType { + OK = 0; + WARNING = 1; + ERROR = 2; + } + optional MyType a = 1; + optional int32 b = 2; + optional float c = 3; + optional bool d = 4; + optional double e = 5; + optional uint32 f = 6; +} + +message TestCamelCase { + optional string normal_field = 1; + optional int32 CAPITAL_FIELD = 2; + optional int32 CamelCaseField = 3; +} + +message TestBoolMap { + map bool_map = 1; +} + +message TestRecursion { + optional int32 value = 1; + optional TestRecursion child = 2; +} + +message TestStringMap { + map string_map = 1; +} + +message TestStringSerializer { + optional string scalar_string = 1; + repeated string repeated_string = 2; + map string_map = 3; +} + +message TestMessageWithExtension { + extensions 100 to max; +} + +message TestExtension { + extend TestMessageWithExtension { + optional TestExtension ext = 100; + } + optional string value = 1; +} + +enum EnumValue { + PROTOCOL = 0; + BUFFER = 1; + DEFAULT = 2; +} + +message TestDefaultEnumValue { + optional EnumValue enum_value = 1 [default = DEFAULT]; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/util/json_format_proto3.proto b/node_modules/google-gax/build/protos/google/protobuf/util/json_format_proto3.proto new file mode 100644 index 0000000..e631c2a --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/util/json_format_proto3.proto @@ -0,0 +1,301 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd + +syntax = "proto3"; + +package proto3; + +import "google/protobuf/any.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/field_mask.proto"; +import "google/protobuf/struct.proto"; +import "google/protobuf/timestamp.proto"; +import "google/protobuf/wrappers.proto"; +import "google/protobuf/unittest.proto"; + +option java_package = "com.google.protobuf.util"; +option java_outer_classname = "JsonFormatProto3"; + +enum EnumType { + FOO = 0; + BAR = 1; + TLSv1_2 = 2; +} + +message MessageType { + int32 value = 1; +} + +message TestMessage { + bool bool_value = 1; + int32 int32_value = 2; + int64 int64_value = 3; + uint32 uint32_value = 4; + uint64 uint64_value = 5; + float float_value = 6; + double double_value = 7; + string string_value = 8; + bytes bytes_value = 9; + EnumType enum_value = 10; + MessageType message_value = 11; + + repeated bool repeated_bool_value = 21; + repeated int32 repeated_int32_value = 22; + repeated int64 repeated_int64_value = 23; + repeated uint32 repeated_uint32_value = 24; + repeated uint64 repeated_uint64_value = 25; + repeated float repeated_float_value = 26; + repeated double repeated_double_value = 27; + repeated string repeated_string_value = 28; + repeated bytes repeated_bytes_value = 29; + repeated EnumType repeated_enum_value = 30; + repeated MessageType repeated_message_value = 31; + + optional bool optional_bool_value = 41; + optional int32 optional_int32_value = 42; + optional int64 optional_int64_value = 43; + optional uint32 optional_uint32_value = 44; + optional uint64 optional_uint64_value = 45; + optional float optional_float_value = 46; + optional double optional_double_value = 47; + optional string optional_string_value = 48; + optional bytes optional_bytes_value = 49; + optional EnumType optional_enum_value = 50; + optional MessageType optional_message_value = 51; +} + +message TestOneof { + // In JSON format oneof fields behave mostly the same as optional + // fields except that: + // 1. Oneof fields have field presence information and will be + // printed if it's set no matter whether it's the default value. + // 2. Multiple oneof fields in the same oneof cannot appear at the + // same time in the input. + oneof oneof_value { + int32 oneof_int32_value = 1; + string oneof_string_value = 2; + bytes oneof_bytes_value = 3; + EnumType oneof_enum_value = 4; + MessageType oneof_message_value = 5; + google.protobuf.NullValue oneof_null_value = 6; + } +} + +message TestMap { + map bool_map = 1; + map int32_map = 2; + map int64_map = 3; + map uint32_map = 4; + map uint64_map = 5; + map string_map = 6; +} + +message TestNestedMap { + map bool_map = 1; + map int32_map = 2; + map int64_map = 3; + map uint32_map = 4; + map uint64_map = 5; + map string_map = 6; + map map_map = 7; +} + +message TestStringMap { + map string_map = 1; +} + +message TestWrapper { + google.protobuf.BoolValue bool_value = 1; + google.protobuf.Int32Value int32_value = 2; + google.protobuf.Int64Value int64_value = 3; + google.protobuf.UInt32Value uint32_value = 4; + google.protobuf.UInt64Value uint64_value = 5; + google.protobuf.FloatValue float_value = 6; + google.protobuf.DoubleValue double_value = 7; + google.protobuf.StringValue string_value = 8; + google.protobuf.BytesValue bytes_value = 9; + + repeated google.protobuf.BoolValue repeated_bool_value = 11; + repeated google.protobuf.Int32Value repeated_int32_value = 12; + repeated google.protobuf.Int64Value repeated_int64_value = 13; + repeated google.protobuf.UInt32Value repeated_uint32_value = 14; + repeated google.protobuf.UInt64Value repeated_uint64_value = 15; + repeated google.protobuf.FloatValue repeated_float_value = 16; + repeated google.protobuf.DoubleValue repeated_double_value = 17; + repeated google.protobuf.StringValue repeated_string_value = 18; + repeated google.protobuf.BytesValue repeated_bytes_value = 19; +} + +message TestTimestamp { + google.protobuf.Timestamp value = 1; + repeated google.protobuf.Timestamp repeated_value = 2; +} + +message TestDuration { + google.protobuf.Duration value = 1; + repeated google.protobuf.Duration repeated_value = 2; +} + +message TestFieldMask { + google.protobuf.FieldMask value = 1; +} + +message TestStruct { + google.protobuf.Struct value = 1; + repeated google.protobuf.Struct repeated_value = 2; +} + +message TestAny { + google.protobuf.Any value = 1; + repeated google.protobuf.Any repeated_value = 2; +} + +message TestValue { + google.protobuf.Value value = 1; + repeated google.protobuf.Value repeated_value = 2; +} + +message TestListValue { + google.protobuf.ListValue value = 1; + repeated google.protobuf.ListValue repeated_value = 2; +} + +message TestBoolValue { + bool bool_value = 1; + map bool_map = 2; +} + +message TestNullValue { + google.protobuf.NullValue null_value = 20; + repeated google.protobuf.NullValue repeated_null_value = 21; +} + +message TestCustomJsonName { + int32 value = 1 [json_name = "@value"]; +} + +message TestEvilJson { + int32 regular_value = 1 [json_name = "regular_name"]; + int32 script = 2 [json_name = ""]; + int32 quotes = 3 [json_name = "unbalanced\"quotes"]; + int32 script_and_quotes = 4 + [json_name = "\""]; +} + +message TestExtensions { + .protobuf_unittest.TestAllExtensions extensions = 1; +} + +message TestEnumValue { + EnumType enum_value1 = 1; + EnumType enum_value2 = 2; + EnumType enum_value3 = 3; +} + +message MapsTestCases { + EmptyMap empty_map = 1; + StringtoInt string_to_int = 2; + IntToString int_to_string = 3; + Mixed1 mixed1 = 4; + Mixed2 mixed2 = 5; + MapOfObjects map_of_objects = 6; + + // Empty key tests + StringtoInt empty_key_string_to_int1 = 7; + StringtoInt empty_key_string_to_int2 = 8; + StringtoInt empty_key_string_to_int3 = 9; + BoolToString empty_key_bool_to_string = 10; + IntToString empty_key_int_to_string = 11; + Mixed1 empty_key_mixed = 12; + MapOfObjects empty_key_map_objects = 13; +} + +message EmptyMap { + map map = 1; +} + +message StringtoInt { + map map = 1; +} + +message IntToString { + map map = 1; +} + +message BoolToString { + map map = 1; +} + +message Mixed1 { + string msg = 1; + map map = 2; +} + +message Mixed2 { + enum E { + E0 = 0; + E1 = 1; + E2 = 2; + E3 = 3; + } + map map = 1; + E ee = 2; +} + +message MapOfObjects { + message M { + string inner_text = 1; + } + map map = 1; +} + +message MapIn { + string other = 1; + repeated string things = 2; + map map_input = 3; + map map_any = 4; +} + +message MapOut { + map map1 = 1; + map map2 = 2; + map map3 = 3; + map map4 = 5; + string bar = 4; +} + +// A message with exactly the same wire representation as MapOut, but using +// repeated message fields instead of map fields. We use this message to test +// the wire-format compatibility of the JSON transcoder (e.g., whether it +// handles missing keys correctly). +message MapOutWireFormat { + message Map1Entry { + string key = 1; + MapM value = 2; + } + repeated Map1Entry map1 = 1; + message Map2Entry { + string key = 1; + MapOut value = 2; + } + repeated Map2Entry map2 = 2; + message Map3Entry { + int32 key = 1; + string value = 2; + } + repeated Map3Entry map3 = 3; + message Map4Entry { + bool key = 1; + string value = 2; + } + repeated Map4Entry map4 = 5; + string bar = 4; +} + +message MapM { + string foo = 1; +} diff --git a/node_modules/google-gax/build/protos/google/protobuf/wrappers.proto b/node_modules/google-gax/build/protos/google/protobuf/wrappers.proto new file mode 100644 index 0000000..1959fa5 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/protobuf/wrappers.proto @@ -0,0 +1,123 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Wrappers for primitive (non-message) types. These types are useful +// for embedding primitives in the `google.protobuf.Any` type and for places +// where we need to distinguish between the absence of a primitive +// typed field and its default value. +// +// These wrappers have no meaningful use within repeated fields as they lack +// the ability to detect presence on individual elements. +// These wrappers have no meaningful use within a map or a oneof since +// individual entries of a map or fields of a oneof can already detect presence. + +syntax = "proto3"; + +package google.protobuf; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/protobuf/types/known/wrapperspb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "WrappersProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; + +// Wrapper message for `double`. +// +// The JSON representation for `DoubleValue` is JSON number. +message DoubleValue { + // The double value. + double value = 1; +} + +// Wrapper message for `float`. +// +// The JSON representation for `FloatValue` is JSON number. +message FloatValue { + // The float value. + float value = 1; +} + +// Wrapper message for `int64`. +// +// The JSON representation for `Int64Value` is JSON string. +message Int64Value { + // The int64 value. + int64 value = 1; +} + +// Wrapper message for `uint64`. +// +// The JSON representation for `UInt64Value` is JSON string. +message UInt64Value { + // The uint64 value. + uint64 value = 1; +} + +// Wrapper message for `int32`. +// +// The JSON representation for `Int32Value` is JSON number. +message Int32Value { + // The int32 value. + int32 value = 1; +} + +// Wrapper message for `uint32`. +// +// The JSON representation for `UInt32Value` is JSON number. +message UInt32Value { + // The uint32 value. + uint32 value = 1; +} + +// Wrapper message for `bool`. +// +// The JSON representation for `BoolValue` is JSON `true` and `false`. +message BoolValue { + // The bool value. + bool value = 1; +} + +// Wrapper message for `string`. +// +// The JSON representation for `StringValue` is JSON string. +message StringValue { + // The string value. + string value = 1; +} + +// Wrapper message for `bytes`. +// +// The JSON representation for `BytesValue` is JSON string. +message BytesValue { + // The bytes value. + bytes value = 1; +} diff --git a/node_modules/google-gax/build/protos/google/rpc/code.proto b/node_modules/google-gax/build/protos/google/rpc/code.proto new file mode 100644 index 0000000..7c810af --- /dev/null +++ b/node_modules/google-gax/build/protos/google/rpc/code.proto @@ -0,0 +1,186 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.rpc; + +option go_package = "google.golang.org/genproto/googleapis/rpc/code;code"; +option java_multiple_files = true; +option java_outer_classname = "CodeProto"; +option java_package = "com.google.rpc"; +option objc_class_prefix = "RPC"; + +// The canonical error codes for gRPC APIs. +// +// +// Sometimes multiple error codes may apply. Services should return +// the most specific error code that applies. For example, prefer +// `OUT_OF_RANGE` over `FAILED_PRECONDITION` if both codes apply. +// Similarly prefer `NOT_FOUND` or `ALREADY_EXISTS` over `FAILED_PRECONDITION`. +enum Code { + // Not an error; returned on success. + // + // HTTP Mapping: 200 OK + OK = 0; + + // The operation was cancelled, typically by the caller. + // + // HTTP Mapping: 499 Client Closed Request + CANCELLED = 1; + + // Unknown error. For example, this error may be returned when + // a `Status` value received from another address space belongs to + // an error space that is not known in this address space. Also + // errors raised by APIs that do not return enough error information + // may be converted to this error. + // + // HTTP Mapping: 500 Internal Server Error + UNKNOWN = 2; + + // The client specified an invalid argument. Note that this differs + // from `FAILED_PRECONDITION`. `INVALID_ARGUMENT` indicates arguments + // that are problematic regardless of the state of the system + // (e.g., a malformed file name). + // + // HTTP Mapping: 400 Bad Request + INVALID_ARGUMENT = 3; + + // The deadline expired before the operation could complete. For operations + // that change the state of the system, this error may be returned + // even if the operation has completed successfully. For example, a + // successful response from a server could have been delayed long + // enough for the deadline to expire. + // + // HTTP Mapping: 504 Gateway Timeout + DEADLINE_EXCEEDED = 4; + + // Some requested entity (e.g., file or directory) was not found. + // + // Note to server developers: if a request is denied for an entire class + // of users, such as gradual feature rollout or undocumented allowlist, + // `NOT_FOUND` may be used. If a request is denied for some users within + // a class of users, such as user-based access control, `PERMISSION_DENIED` + // must be used. + // + // HTTP Mapping: 404 Not Found + NOT_FOUND = 5; + + // The entity that a client attempted to create (e.g., file or directory) + // already exists. + // + // HTTP Mapping: 409 Conflict + ALREADY_EXISTS = 6; + + // The caller does not have permission to execute the specified + // operation. `PERMISSION_DENIED` must not be used for rejections + // caused by exhausting some resource (use `RESOURCE_EXHAUSTED` + // instead for those errors). `PERMISSION_DENIED` must not be + // used if the caller can not be identified (use `UNAUTHENTICATED` + // instead for those errors). This error code does not imply the + // request is valid or the requested entity exists or satisfies + // other pre-conditions. + // + // HTTP Mapping: 403 Forbidden + PERMISSION_DENIED = 7; + + // The request does not have valid authentication credentials for the + // operation. + // + // HTTP Mapping: 401 Unauthorized + UNAUTHENTICATED = 16; + + // Some resource has been exhausted, perhaps a per-user quota, or + // perhaps the entire file system is out of space. + // + // HTTP Mapping: 429 Too Many Requests + RESOURCE_EXHAUSTED = 8; + + // The operation was rejected because the system is not in a state + // required for the operation's execution. For example, the directory + // to be deleted is non-empty, an rmdir operation is applied to + // a non-directory, etc. + // + // Service implementors can use the following guidelines to decide + // between `FAILED_PRECONDITION`, `ABORTED`, and `UNAVAILABLE`: + // (a) Use `UNAVAILABLE` if the client can retry just the failing call. + // (b) Use `ABORTED` if the client should retry at a higher level. For + // example, when a client-specified test-and-set fails, indicating the + // client should restart a read-modify-write sequence. + // (c) Use `FAILED_PRECONDITION` if the client should not retry until + // the system state has been explicitly fixed. For example, if an "rmdir" + // fails because the directory is non-empty, `FAILED_PRECONDITION` + // should be returned since the client should not retry unless + // the files are deleted from the directory. + // + // HTTP Mapping: 400 Bad Request + FAILED_PRECONDITION = 9; + + // The operation was aborted, typically due to a concurrency issue such as + // a sequencer check failure or transaction abort. + // + // See the guidelines above for deciding between `FAILED_PRECONDITION`, + // `ABORTED`, and `UNAVAILABLE`. + // + // HTTP Mapping: 409 Conflict + ABORTED = 10; + + // The operation was attempted past the valid range. E.g., seeking or + // reading past end-of-file. + // + // Unlike `INVALID_ARGUMENT`, this error indicates a problem that may + // be fixed if the system state changes. For example, a 32-bit file + // system will generate `INVALID_ARGUMENT` if asked to read at an + // offset that is not in the range [0,2^32-1], but it will generate + // `OUT_OF_RANGE` if asked to read from an offset past the current + // file size. + // + // There is a fair bit of overlap between `FAILED_PRECONDITION` and + // `OUT_OF_RANGE`. We recommend using `OUT_OF_RANGE` (the more specific + // error) when it applies so that callers who are iterating through + // a space can easily look for an `OUT_OF_RANGE` error to detect when + // they are done. + // + // HTTP Mapping: 400 Bad Request + OUT_OF_RANGE = 11; + + // The operation is not implemented or is not supported/enabled in this + // service. + // + // HTTP Mapping: 501 Not Implemented + UNIMPLEMENTED = 12; + + // Internal errors. This means that some invariants expected by the + // underlying system have been broken. This error code is reserved + // for serious errors. + // + // HTTP Mapping: 500 Internal Server Error + INTERNAL = 13; + + // The service is currently unavailable. This is most likely a + // transient condition, which can be corrected by retrying with + // a backoff. Note that it is not always safe to retry + // non-idempotent operations. + // + // See the guidelines above for deciding between `FAILED_PRECONDITION`, + // `ABORTED`, and `UNAVAILABLE`. + // + // HTTP Mapping: 503 Service Unavailable + UNAVAILABLE = 14; + + // Unrecoverable data loss or corruption. + // + // HTTP Mapping: 500 Internal Server Error + DATA_LOSS = 15; +} diff --git a/node_modules/google-gax/build/protos/google/rpc/context/attribute_context.proto b/node_modules/google-gax/build/protos/google/rpc/context/attribute_context.proto new file mode 100644 index 0000000..ef9242e --- /dev/null +++ b/node_modules/google-gax/build/protos/google/rpc/context/attribute_context.proto @@ -0,0 +1,344 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.rpc.context; + +import "google/protobuf/any.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/struct.proto"; +import "google/protobuf/timestamp.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/rpc/context/attribute_context;attribute_context"; +option java_multiple_files = true; +option java_outer_classname = "AttributeContextProto"; +option java_package = "com.google.rpc.context"; + +// This message defines the standard attribute vocabulary for Google APIs. +// +// An attribute is a piece of metadata that describes an activity on a network +// service. For example, the size of an HTTP request, or the status code of +// an HTTP response. +// +// Each attribute has a type and a name, which is logically defined as +// a proto message field in `AttributeContext`. The field type becomes the +// attribute type, and the field path becomes the attribute name. For example, +// the attribute `source.ip` maps to field `AttributeContext.source.ip`. +// +// This message definition is guaranteed not to have any wire breaking change. +// So you can use it directly for passing attributes across different systems. +// +// NOTE: Different system may generate different subset of attributes. Please +// verify the system specification before relying on an attribute generated +// a system. +message AttributeContext { + // This message defines attributes for a node that handles a network request. + // The node can be either a service or an application that sends, forwards, + // or receives the request. Service peers should fill in + // `principal` and `labels` as appropriate. + message Peer { + // The IP address of the peer. + string ip = 1; + + // The network port of the peer. + int64 port = 2; + + // The labels associated with the peer. + map labels = 6; + + // The identity of this peer. Similar to `Request.auth.principal`, but + // relative to the peer instead of the request. For example, the + // identity associated with a load balancer that forwarded the request. + string principal = 7; + + // The CLDR country/region code associated with the above IP address. + // If the IP address is private, the `region_code` should reflect the + // physical location where this peer is running. + string region_code = 8; + } + + // This message defines attributes associated with API operations, such as + // a network API request. The terminology is based on the conventions used + // by Google APIs, Istio, and OpenAPI. + message Api { + // The API service name. It is a logical identifier for a networked API, + // such as "pubsub.googleapis.com". The naming syntax depends on the + // API management system being used for handling the request. + string service = 1; + + // The API operation name. For gRPC requests, it is the fully qualified API + // method name, such as "google.pubsub.v1.Publisher.Publish". For OpenAPI + // requests, it is the `operationId`, such as "getPet". + string operation = 2; + + // The API protocol used for sending the request, such as "http", "https", + // "grpc", or "internal". + string protocol = 3; + + // The API version associated with the API operation above, such as "v1" or + // "v1alpha1". + string version = 4; + } + + // This message defines request authentication attributes. Terminology is + // based on the JSON Web Token (JWT) standard, but the terms also + // correlate to concepts in other standards. + message Auth { + // The authenticated principal. Reflects the issuer (`iss`) and subject + // (`sub`) claims within a JWT. The issuer and subject should be `/` + // delimited, with `/` percent-encoded within the subject fragment. For + // Google accounts, the principal format is: + // "https://accounts.google.com/{id}" + string principal = 1; + + // The intended audience(s) for this authentication information. Reflects + // the audience (`aud`) claim within a JWT. The audience + // value(s) depends on the `issuer`, but typically include one or more of + // the following pieces of information: + // + // * The services intended to receive the credential. For example, + // ["https://pubsub.googleapis.com/", "https://storage.googleapis.com/"]. + // * A set of service-based scopes. For example, + // ["https://www.googleapis.com/auth/cloud-platform"]. + // * The client id of an app, such as the Firebase project id for JWTs + // from Firebase Auth. + // + // Consult the documentation for the credential issuer to determine the + // information provided. + repeated string audiences = 2; + + // The authorized presenter of the credential. Reflects the optional + // Authorized Presenter (`azp`) claim within a JWT or the + // OAuth client id. For example, a Google Cloud Platform client id looks + // as follows: "123456789012.apps.googleusercontent.com". + string presenter = 3; + + // Structured claims presented with the credential. JWTs include + // `{key: value}` pairs for standard and private claims. The following + // is a subset of the standard required and optional claims that would + // typically be presented for a Google-based JWT: + // + // {'iss': 'accounts.google.com', + // 'sub': '113289723416554971153', + // 'aud': ['123456789012', 'pubsub.googleapis.com'], + // 'azp': '123456789012.apps.googleusercontent.com', + // 'email': 'jsmith@example.com', + // 'iat': 1353601026, + // 'exp': 1353604926} + // + // SAML assertions are similarly specified, but with an identity provider + // dependent structure. + google.protobuf.Struct claims = 4; + + // A list of access level resource names that allow resources to be + // accessed by authenticated requester. It is part of Secure GCP processing + // for the incoming request. An access level string has the format: + // "//{api_service_name}/accessPolicies/{policy_id}/accessLevels/{short_name}" + // + // Example: + // "//accesscontextmanager.googleapis.com/accessPolicies/MY_POLICY_ID/accessLevels/MY_LEVEL" + repeated string access_levels = 5; + } + + // This message defines attributes for an HTTP request. If the actual + // request is not an HTTP request, the runtime system should try to map + // the actual request to an equivalent HTTP request. + message Request { + // The unique ID for a request, which can be propagated to downstream + // systems. The ID should have low probability of collision + // within a single day for a specific service. + string id = 1; + + // The HTTP request method, such as `GET`, `POST`. + string method = 2; + + // The HTTP request headers. If multiple headers share the same key, they + // must be merged according to the HTTP spec. All header keys must be + // lowercased, because HTTP header keys are case-insensitive. + map headers = 3; + + // The HTTP URL path, excluding the query parameters. + string path = 4; + + // The HTTP request `Host` header value. + string host = 5; + + // The HTTP URL scheme, such as `http` and `https`. + string scheme = 6; + + // The HTTP URL query in the format of `name1=value1&name2=value2`, as it + // appears in the first line of the HTTP request. No decoding is performed. + string query = 7; + + // The timestamp when the `destination` service receives the last byte of + // the request. + google.protobuf.Timestamp time = 9; + + // The HTTP request size in bytes. If unknown, it must be -1. + int64 size = 10; + + // The network protocol used with the request, such as "http/1.1", + // "spdy/3", "h2", "h2c", "webrtc", "tcp", "udp", "quic". See + // https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids + // for details. + string protocol = 11; + + // A special parameter for request reason. It is used by security systems + // to associate auditing information with a request. + string reason = 12; + + // The request authentication. May be absent for unauthenticated requests. + // Derived from the HTTP request `Authorization` header or equivalent. + Auth auth = 13; + } + + // This message defines attributes for a typical network response. It + // generally models semantics of an HTTP response. + message Response { + // The HTTP response status code, such as `200` and `404`. + int64 code = 1; + + // The HTTP response size in bytes. If unknown, it must be -1. + int64 size = 2; + + // The HTTP response headers. If multiple headers share the same key, they + // must be merged according to HTTP spec. All header keys must be + // lowercased, because HTTP header keys are case-insensitive. + map headers = 3; + + // The timestamp when the `destination` service sends the last byte of + // the response. + google.protobuf.Timestamp time = 4; + + // The amount of time it takes the backend service to fully respond to a + // request. Measured from when the destination service starts to send the + // request to the backend until when the destination service receives the + // complete response from the backend. + google.protobuf.Duration backend_latency = 5; + } + + // This message defines core attributes for a resource. A resource is an + // addressable (named) entity provided by the destination service. For + // example, a file stored on a network storage service. + message Resource { + // The name of the service that this resource belongs to, such as + // `pubsub.googleapis.com`. The service may be different from the DNS + // hostname that actually serves the request. + string service = 1; + + // The stable identifier (name) of a resource on the `service`. A resource + // can be logically identified as "//{resource.service}/{resource.name}". + // The differences between a resource name and a URI are: + // + // * Resource name is a logical identifier, independent of network + // protocol and API version. For example, + // `//pubsub.googleapis.com/projects/123/topics/news-feed`. + // * URI often includes protocol and version information, so it can + // be used directly by applications. For example, + // `https://pubsub.googleapis.com/v1/projects/123/topics/news-feed`. + // + // See https://cloud.google.com/apis/design/resource_names for details. + string name = 2; + + // The type of the resource. The syntax is platform-specific because + // different platforms define their resources differently. + // + // For Google APIs, the type format must be "{service}/{kind}", such as + // "pubsub.googleapis.com/Topic". + string type = 3; + + // The labels or tags on the resource, such as AWS resource tags and + // Kubernetes resource labels. + map labels = 4; + + // The unique identifier of the resource. UID is unique in the time + // and space for this resource within the scope of the service. It is + // typically generated by the server on successful creation of a resource + // and must not be changed. UID is used to uniquely identify resources + // with resource name reuses. This should be a UUID4. + string uid = 5; + + // Annotations is an unstructured key-value map stored with a resource that + // may be set by external tools to store and retrieve arbitrary metadata. + // They are not queryable and should be preserved when modifying objects. + // + // More info: https://kubernetes.io/docs/user-guide/annotations + map annotations = 6; + + // Mutable. The display name set by clients. Must be <= 63 characters. + string display_name = 7; + + // Output only. The timestamp when the resource was created. This may + // be either the time creation was initiated or when it was completed. + google.protobuf.Timestamp create_time = 8; + + // Output only. The timestamp when the resource was last updated. Any + // change to the resource made by users must refresh this value. + // Changes to a resource made by the service should refresh this value. + google.protobuf.Timestamp update_time = 9; + + // Output only. The timestamp when the resource was deleted. + // If the resource is not deleted, this must be empty. + google.protobuf.Timestamp delete_time = 10; + + // Output only. An opaque value that uniquely identifies a version or + // generation of a resource. It can be used to confirm that the client + // and server agree on the ordering of a resource being written. + string etag = 11; + + // Immutable. The location of the resource. The location encoding is + // specific to the service provider, and new encoding may be introduced + // as the service evolves. + // + // For Google Cloud products, the encoding is what is used by Google Cloud + // APIs, such as `us-east1`, `aws-us-east-1`, and `azure-eastus2`. The + // semantics of `location` is identical to the + // `cloud.googleapis.com/location` label used by some Google Cloud APIs. + string location = 12; + } + + // The origin of a network activity. In a multi hop network activity, + // the origin represents the sender of the first hop. For the first hop, + // the `source` and the `origin` must have the same content. + Peer origin = 7; + + // The source of a network activity, such as starting a TCP connection. + // In a multi hop network activity, the source represents the sender of the + // last hop. + Peer source = 1; + + // The destination of a network activity, such as accepting a TCP connection. + // In a multi hop network activity, the destination represents the receiver of + // the last hop. + Peer destination = 2; + + // Represents a network request, such as an HTTP request. + Request request = 3; + + // Represents a network response, such as an HTTP response. + Response response = 4; + + // Represents a target resource that is involved with a network activity. + // If multiple resources are involved with an activity, this must be the + // primary one. + Resource resource = 5; + + // Represents an API operation that is involved to a network activity. + Api api = 6; + + // Supports extensions for advanced use cases, such as logs and metrics. + repeated google.protobuf.Any extensions = 8; +} diff --git a/node_modules/google-gax/build/protos/google/rpc/context/audit_context.proto b/node_modules/google-gax/build/protos/google/rpc/context/audit_context.proto new file mode 100644 index 0000000..7b8b705 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/rpc/context/audit_context.proto @@ -0,0 +1,49 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.rpc.context; + +import "google/protobuf/struct.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/rpc/context;context"; +option java_multiple_files = true; +option java_outer_classname = "AuditContextProto"; +option java_package = "com.google.rpc.context"; + +// `AuditContext` provides information that is needed for audit logging. +message AuditContext { + // Serialized audit log. + bytes audit_log = 1; + + // An API request message that is scrubbed based on the method annotation. + // This field should only be filled if audit_log field is present. + // Service Control will use this to assemble a complete log for Cloud Audit + // Logs and Google internal audit logs. + google.protobuf.Struct scrubbed_request = 2; + + // An API response message that is scrubbed based on the method annotation. + // This field should only be filled if audit_log field is present. + // Service Control will use this to assemble a complete log for Cloud Audit + // Logs and Google internal audit logs. + google.protobuf.Struct scrubbed_response = 3; + + // Number of scrubbed response items. + int32 scrubbed_response_item_count = 4; + + // Audit resource name which is scrubbed. + string target_resource = 5; +} diff --git a/node_modules/google-gax/build/protos/google/rpc/error_details.proto b/node_modules/google-gax/build/protos/google/rpc/error_details.proto new file mode 100644 index 0000000..c489e83 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/rpc/error_details.proto @@ -0,0 +1,285 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.rpc; + +import "google/protobuf/duration.proto"; + +option go_package = "google.golang.org/genproto/googleapis/rpc/errdetails;errdetails"; +option java_multiple_files = true; +option java_outer_classname = "ErrorDetailsProto"; +option java_package = "com.google.rpc"; +option objc_class_prefix = "RPC"; + +// Describes the cause of the error with structured details. +// +// Example of an error when contacting the "pubsub.googleapis.com" API when it +// is not enabled: +// +// { "reason": "API_DISABLED" +// "domain": "googleapis.com" +// "metadata": { +// "resource": "projects/123", +// "service": "pubsub.googleapis.com" +// } +// } +// +// This response indicates that the pubsub.googleapis.com API is not enabled. +// +// Example of an error that is returned when attempting to create a Spanner +// instance in a region that is out of stock: +// +// { "reason": "STOCKOUT" +// "domain": "spanner.googleapis.com", +// "metadata": { +// "availableRegions": "us-central1,us-east2" +// } +// } +message ErrorInfo { + // The reason of the error. This is a constant value that identifies the + // proximate cause of the error. Error reasons are unique within a particular + // domain of errors. This should be at most 63 characters and match a + // regular expression of `[A-Z][A-Z0-9_]+[A-Z0-9]`, which represents + // UPPER_SNAKE_CASE. + string reason = 1; + + // The logical grouping to which the "reason" belongs. The error domain + // is typically the registered service name of the tool or product that + // generates the error. Example: "pubsub.googleapis.com". If the error is + // generated by some common infrastructure, the error domain must be a + // globally unique value that identifies the infrastructure. For Google API + // infrastructure, the error domain is "googleapis.com". + string domain = 2; + + // Additional structured details about this error. + // + // Keys should match /[a-zA-Z0-9-_]/ and be limited to 64 characters in + // length. When identifying the current value of an exceeded limit, the units + // should be contained in the key, not the value. For example, rather than + // {"instanceLimit": "100/request"}, should be returned as, + // {"instanceLimitPerRequest": "100"}, if the client exceeds the number of + // instances that can be created in a single (batch) request. + map metadata = 3; +} + +// Describes when the clients can retry a failed request. Clients could ignore +// the recommendation here or retry when this information is missing from error +// responses. +// +// It's always recommended that clients should use exponential backoff when +// retrying. +// +// Clients should wait until `retry_delay` amount of time has passed since +// receiving the error response before retrying. If retrying requests also +// fail, clients should use an exponential backoff scheme to gradually increase +// the delay between retries based on `retry_delay`, until either a maximum +// number of retries have been reached or a maximum retry delay cap has been +// reached. +message RetryInfo { + // Clients should wait at least this long between retrying the same request. + google.protobuf.Duration retry_delay = 1; +} + +// Describes additional debugging info. +message DebugInfo { + // The stack trace entries indicating where the error occurred. + repeated string stack_entries = 1; + + // Additional debugging information provided by the server. + string detail = 2; +} + +// Describes how a quota check failed. +// +// For example if a daily limit was exceeded for the calling project, +// a service could respond with a QuotaFailure detail containing the project +// id and the description of the quota limit that was exceeded. If the +// calling project hasn't enabled the service in the developer console, then +// a service could respond with the project id and set `service_disabled` +// to true. +// +// Also see RetryInfo and Help types for other details about handling a +// quota failure. +message QuotaFailure { + // A message type used to describe a single quota violation. For example, a + // daily quota or a custom quota that was exceeded. + message Violation { + // The subject on which the quota check failed. + // For example, "clientip:" or "project:". + string subject = 1; + + // A description of how the quota check failed. Clients can use this + // description to find more about the quota configuration in the service's + // public documentation, or find the relevant quota limit to adjust through + // developer console. + // + // For example: "Service disabled" or "Daily Limit for read operations + // exceeded". + string description = 2; + } + + // Describes all quota violations. + repeated Violation violations = 1; +} + +// Describes what preconditions have failed. +// +// For example, if an RPC failed because it required the Terms of Service to be +// acknowledged, it could list the terms of service violation in the +// PreconditionFailure message. +message PreconditionFailure { + // A message type used to describe a single precondition failure. + message Violation { + // The type of PreconditionFailure. We recommend using a service-specific + // enum type to define the supported precondition violation subjects. For + // example, "TOS" for "Terms of Service violation". + string type = 1; + + // The subject, relative to the type, that failed. + // For example, "google.com/cloud" relative to the "TOS" type would indicate + // which terms of service is being referenced. + string subject = 2; + + // A description of how the precondition failed. Developers can use this + // description to understand how to fix the failure. + // + // For example: "Terms of service not accepted". + string description = 3; + } + + // Describes all precondition violations. + repeated Violation violations = 1; +} + +// Describes violations in a client request. This error type focuses on the +// syntactic aspects of the request. +message BadRequest { + // A message type used to describe a single bad request field. + message FieldViolation { + // A path that leads to a field in the request body. The value will be a + // sequence of dot-separated identifiers that identify a protocol buffer + // field. + // + // Consider the following: + // + // message CreateContactRequest { + // message EmailAddress { + // enum Type { + // TYPE_UNSPECIFIED = 0; + // HOME = 1; + // WORK = 2; + // } + // + // optional string email = 1; + // repeated EmailType type = 2; + // } + // + // string full_name = 1; + // repeated EmailAddress email_addresses = 2; + // } + // + // In this example, in proto `field` could take one of the following values: + // + // * `full_name` for a violation in the `full_name` value + // * `email_addresses[1].email` for a violation in the `email` field of the + // first `email_addresses` message + // * `email_addresses[3].type[2]` for a violation in the second `type` + // value in the third `email_addresses` message. + // + // In JSON, the same values are represented as: + // + // * `fullName` for a violation in the `fullName` value + // * `emailAddresses[1].email` for a violation in the `email` field of the + // first `emailAddresses` message + // * `emailAddresses[3].type[2]` for a violation in the second `type` + // value in the third `emailAddresses` message. + string field = 1; + + // A description of why the request element is bad. + string description = 2; + } + + // Describes all violations in a client request. + repeated FieldViolation field_violations = 1; +} + +// Contains metadata about the request that clients can attach when filing a bug +// or providing other forms of feedback. +message RequestInfo { + // An opaque string that should only be interpreted by the service generating + // it. For example, it can be used to identify requests in the service's logs. + string request_id = 1; + + // Any data that was used to serve this request. For example, an encrypted + // stack trace that can be sent back to the service provider for debugging. + string serving_data = 2; +} + +// Describes the resource that is being accessed. +message ResourceInfo { + // A name for the type of resource being accessed, e.g. "sql table", + // "cloud storage bucket", "file", "Google calendar"; or the type URL + // of the resource: e.g. "type.googleapis.com/google.pubsub.v1.Topic". + string resource_type = 1; + + // The name of the resource being accessed. For example, a shared calendar + // name: "example.com_4fghdhgsrgh@group.calendar.google.com", if the current + // error is + // [google.rpc.Code.PERMISSION_DENIED][google.rpc.Code.PERMISSION_DENIED]. + string resource_name = 2; + + // The owner of the resource (optional). + // For example, "user:" or "project:". + string owner = 3; + + // Describes what error is encountered when accessing this resource. + // For example, updating a cloud project may require the `writer` permission + // on the developer console project. + string description = 4; +} + +// Provides links to documentation or for performing an out of band action. +// +// For example, if a quota check failed with an error indicating the calling +// project hasn't enabled the accessed service, this can contain a URL pointing +// directly to the right place in the developer console to flip the bit. +message Help { + // Describes a URL link. + message Link { + // Describes what the link offers. + string description = 1; + + // The URL of the link. + string url = 2; + } + + // URL(s) pointing to additional information on handling the current error. + repeated Link links = 1; +} + +// Provides a localized error message that is safe to return to the user +// which can be attached to an RPC error. +message LocalizedMessage { + // The locale used following the specification defined at + // https://www.rfc-editor.org/rfc/bcp/bcp47.txt. + // Examples are: "en-US", "fr-CH", "es-MX" + string locale = 1; + + // The localized error message in the above locale. + string message = 2; +} diff --git a/node_modules/google-gax/build/protos/google/rpc/http.proto b/node_modules/google-gax/build/protos/google/rpc/http.proto new file mode 100644 index 0000000..299a71f --- /dev/null +++ b/node_modules/google-gax/build/protos/google/rpc/http.proto @@ -0,0 +1,64 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.rpc; + +option go_package = "google.golang.org/genproto/googleapis/rpc/http;http"; +option java_multiple_files = true; +option java_outer_classname = "HttpProto"; +option java_package = "com.google.rpc"; +option objc_class_prefix = "RPC"; + +// Represents an HTTP request. +message HttpRequest { + // The HTTP request method. + string method = 1; + + // The HTTP request URI. + string uri = 2; + + // The HTTP request headers. The ordering of the headers is significant. + // Multiple headers with the same key may present for the request. + repeated HttpHeader headers = 3; + + // The HTTP request body. If the body is not expected, it should be empty. + bytes body = 4; +} + +// Represents an HTTP response. +message HttpResponse { + // The HTTP status code, such as 200 or 404. + int32 status = 1; + + // The HTTP reason phrase, such as "OK" or "Not Found". + string reason = 2; + + // The HTTP response headers. The ordering of the headers is significant. + // Multiple headers with the same key may present for the response. + repeated HttpHeader headers = 3; + + // The HTTP response body. If the body is not expected, it should be empty. + bytes body = 4; +} + +// Represents an HTTP header. +message HttpHeader { + // The HTTP header key. It is case insensitive. + string key = 1; + + // The HTTP header value. + string value = 2; +} diff --git a/node_modules/google-gax/build/protos/google/rpc/status.proto b/node_modules/google-gax/build/protos/google/rpc/status.proto new file mode 100644 index 0000000..923e169 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/rpc/status.proto @@ -0,0 +1,49 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.rpc; + +import "google/protobuf/any.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/rpc/status;status"; +option java_multiple_files = true; +option java_outer_classname = "StatusProto"; +option java_package = "com.google.rpc"; +option objc_class_prefix = "RPC"; + +// The `Status` type defines a logical error model that is suitable for +// different programming environments, including REST APIs and RPC APIs. It is +// used by [gRPC](https://github.com/grpc). Each `Status` message contains +// three pieces of data: error code, error message, and error details. +// +// You can find out more about this error model and how to work with it in the +// [API Design Guide](https://cloud.google.com/apis/design/errors). +message Status { + // The status code, which should be an enum value of + // [google.rpc.Code][google.rpc.Code]. + int32 code = 1; + + // A developer-facing error message, which should be in English. Any + // user-facing error message should be localized and sent in the + // [google.rpc.Status.details][google.rpc.Status.details] field, or localized + // by the client. + string message = 2; + + // A list of messages that carry the error details. There is a common set of + // message types for APIs to use. + repeated google.protobuf.Any details = 3; +} diff --git a/node_modules/google-gax/build/protos/google/type/calendar_period.proto b/node_modules/google-gax/build/protos/google/type/calendar_period.proto new file mode 100644 index 0000000..82f5690 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/type/calendar_period.proto @@ -0,0 +1,56 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/calendarperiod;calendarperiod"; +option java_multiple_files = true; +option java_outer_classname = "CalendarPeriodProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// A `CalendarPeriod` represents the abstract concept of a time period that has +// a canonical start. Grammatically, "the start of the current +// `CalendarPeriod`." All calendar times begin at midnight UTC. +enum CalendarPeriod { + // Undefined period, raises an error. + CALENDAR_PERIOD_UNSPECIFIED = 0; + + // A day. + DAY = 1; + + // A week. Weeks begin on Monday, following + // [ISO 8601](https://en.wikipedia.org/wiki/ISO_week_date). + WEEK = 2; + + // A fortnight. The first calendar fortnight of the year begins at the start + // of week 1 according to + // [ISO 8601](https://en.wikipedia.org/wiki/ISO_week_date). + FORTNIGHT = 3; + + // A month. + MONTH = 4; + + // A quarter. Quarters start on dates 1-Jan, 1-Apr, 1-Jul, and 1-Oct of each + // year. + QUARTER = 5; + + // A half-year. Half-years start on dates 1-Jan and 1-Jul. + HALF = 6; + + // A year. + YEAR = 7; +} diff --git a/node_modules/google-gax/build/protos/google/type/color.proto b/node_modules/google-gax/build/protos/google/type/color.proto new file mode 100644 index 0000000..5dc85a6 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/type/color.proto @@ -0,0 +1,174 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +import "google/protobuf/wrappers.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/type/color;color"; +option java_multiple_files = true; +option java_outer_classname = "ColorProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents a color in the RGBA color space. This representation is designed +// for simplicity of conversion to/from color representations in various +// languages over compactness. For example, the fields of this representation +// can be trivially provided to the constructor of `java.awt.Color` in Java; it +// can also be trivially provided to UIColor's `+colorWithRed:green:blue:alpha` +// method in iOS; and, with just a little work, it can be easily formatted into +// a CSS `rgba()` string in JavaScript. +// +// This reference page doesn't carry information about the absolute color +// space +// that should be used to interpret the RGB value (e.g. sRGB, Adobe RGB, +// DCI-P3, BT.2020, etc.). By default, applications should assume the sRGB color +// space. +// +// When color equality needs to be decided, implementations, unless +// documented otherwise, treat two colors as equal if all their red, +// green, blue, and alpha values each differ by at most 1e-5. +// +// Example (Java): +// +// import com.google.type.Color; +// +// // ... +// public static java.awt.Color fromProto(Color protocolor) { +// float alpha = protocolor.hasAlpha() +// ? protocolor.getAlpha().getValue() +// : 1.0; +// +// return new java.awt.Color( +// protocolor.getRed(), +// protocolor.getGreen(), +// protocolor.getBlue(), +// alpha); +// } +// +// public static Color toProto(java.awt.Color color) { +// float red = (float) color.getRed(); +// float green = (float) color.getGreen(); +// float blue = (float) color.getBlue(); +// float denominator = 255.0; +// Color.Builder resultBuilder = +// Color +// .newBuilder() +// .setRed(red / denominator) +// .setGreen(green / denominator) +// .setBlue(blue / denominator); +// int alpha = color.getAlpha(); +// if (alpha != 255) { +// result.setAlpha( +// FloatValue +// .newBuilder() +// .setValue(((float) alpha) / denominator) +// .build()); +// } +// return resultBuilder.build(); +// } +// // ... +// +// Example (iOS / Obj-C): +// +// // ... +// static UIColor* fromProto(Color* protocolor) { +// float red = [protocolor red]; +// float green = [protocolor green]; +// float blue = [protocolor blue]; +// FloatValue* alpha_wrapper = [protocolor alpha]; +// float alpha = 1.0; +// if (alpha_wrapper != nil) { +// alpha = [alpha_wrapper value]; +// } +// return [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; +// } +// +// static Color* toProto(UIColor* color) { +// CGFloat red, green, blue, alpha; +// if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) { +// return nil; +// } +// Color* result = [[Color alloc] init]; +// [result setRed:red]; +// [result setGreen:green]; +// [result setBlue:blue]; +// if (alpha <= 0.9999) { +// [result setAlpha:floatWrapperWithValue(alpha)]; +// } +// [result autorelease]; +// return result; +// } +// // ... +// +// Example (JavaScript): +// +// // ... +// +// var protoToCssColor = function(rgb_color) { +// var redFrac = rgb_color.red || 0.0; +// var greenFrac = rgb_color.green || 0.0; +// var blueFrac = rgb_color.blue || 0.0; +// var red = Math.floor(redFrac * 255); +// var green = Math.floor(greenFrac * 255); +// var blue = Math.floor(blueFrac * 255); +// +// if (!('alpha' in rgb_color)) { +// return rgbToCssColor(red, green, blue); +// } +// +// var alphaFrac = rgb_color.alpha.value || 0.0; +// var rgbParams = [red, green, blue].join(','); +// return ['rgba(', rgbParams, ',', alphaFrac, ')'].join(''); +// }; +// +// var rgbToCssColor = function(red, green, blue) { +// var rgbNumber = new Number((red << 16) | (green << 8) | blue); +// var hexString = rgbNumber.toString(16); +// var missingZeros = 6 - hexString.length; +// var resultBuilder = ['#']; +// for (var i = 0; i < missingZeros; i++) { +// resultBuilder.push('0'); +// } +// resultBuilder.push(hexString); +// return resultBuilder.join(''); +// }; +// +// // ... +message Color { + // The amount of red in the color as a value in the interval [0, 1]. + float red = 1; + + // The amount of green in the color as a value in the interval [0, 1]. + float green = 2; + + // The amount of blue in the color as a value in the interval [0, 1]. + float blue = 3; + + // The fraction of this color that should be applied to the pixel. That is, + // the final pixel color is defined by the equation: + // + // `pixel color = alpha * (this color) + (1.0 - alpha) * (background color)` + // + // This means that a value of 1.0 corresponds to a solid color, whereas + // a value of 0.0 corresponds to a completely transparent color. This + // uses a wrapper message rather than a simple float scalar so that it is + // possible to distinguish between a default value and the value being unset. + // If omitted, this color object is rendered as a solid color + // (as if the alpha value had been explicitly given a value of 1.0). + google.protobuf.FloatValue alpha = 4; +} diff --git a/node_modules/google-gax/build/protos/google/type/date.proto b/node_modules/google-gax/build/protos/google/type/date.proto new file mode 100644 index 0000000..e4e730e --- /dev/null +++ b/node_modules/google-gax/build/protos/google/type/date.proto @@ -0,0 +1,52 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/type/date;date"; +option java_multiple_files = true; +option java_outer_classname = "DateProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents a whole or partial calendar date, such as a birthday. The time of +// day and time zone are either specified elsewhere or are insignificant. The +// date is relative to the Gregorian Calendar. This can represent one of the +// following: +// +// * A full date, with non-zero year, month, and day values +// * A month and day value, with a zero year, such as an anniversary +// * A year on its own, with zero month and day values +// * A year and month value, with a zero day, such as a credit card expiration +// date +// +// Related types are [google.type.TimeOfDay][google.type.TimeOfDay] and +// `google.protobuf.Timestamp`. +message Date { + // Year of the date. Must be from 1 to 9999, or 0 to specify a date without + // a year. + int32 year = 1; + + // Month of a year. Must be from 1 to 12, or 0 to specify a year without a + // month and day. + int32 month = 2; + + // Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 + // to specify a year by itself or a year and month where the day isn't + // significant. + int32 day = 3; +} diff --git a/node_modules/google-gax/build/protos/google/type/datetime.proto b/node_modules/google-gax/build/protos/google/type/datetime.proto new file mode 100644 index 0000000..cfed85d --- /dev/null +++ b/node_modules/google-gax/build/protos/google/type/datetime.proto @@ -0,0 +1,104 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +import "google/protobuf/duration.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/type/datetime;datetime"; +option java_multiple_files = true; +option java_outer_classname = "DateTimeProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents civil time (or occasionally physical time). +// +// This type can represent a civil time in one of a few possible ways: +// +// * When utc_offset is set and time_zone is unset: a civil time on a calendar +// day with a particular offset from UTC. +// * When time_zone is set and utc_offset is unset: a civil time on a calendar +// day in a particular time zone. +// * When neither time_zone nor utc_offset is set: a civil time on a calendar +// day in local time. +// +// The date is relative to the Proleptic Gregorian Calendar. +// +// If year is 0, the DateTime is considered not to have a specific year. month +// and day must have valid, non-zero values. +// +// This type may also be used to represent a physical time if all the date and +// time fields are set and either case of the `time_offset` oneof is set. +// Consider using `Timestamp` message for physical time instead. If your use +// case also would like to store the user's timezone, that can be done in +// another field. +// +// This type is more flexible than some applications may want. Make sure to +// document and validate your application's limitations. +message DateTime { + // Optional. Year of date. Must be from 1 to 9999, or 0 if specifying a + // datetime without a year. + int32 year = 1; + + // Required. Month of year. Must be from 1 to 12. + int32 month = 2; + + // Required. Day of month. Must be from 1 to 31 and valid for the year and + // month. + int32 day = 3; + + // Required. Hours of day in 24 hour format. Should be from 0 to 23. An API + // may choose to allow the value "24:00:00" for scenarios like business + // closing time. + int32 hours = 4; + + // Required. Minutes of hour of day. Must be from 0 to 59. + int32 minutes = 5; + + // Required. Seconds of minutes of the time. Must normally be from 0 to 59. An + // API may allow the value 60 if it allows leap-seconds. + int32 seconds = 6; + + // Required. Fractions of seconds in nanoseconds. Must be from 0 to + // 999,999,999. + int32 nanos = 7; + + // Optional. Specifies either the UTC offset or the time zone of the DateTime. + // Choose carefully between them, considering that time zone data may change + // in the future (for example, a country modifies their DST start/end dates, + // and future DateTimes in the affected range had already been stored). + // If omitted, the DateTime is considered to be in local time. + oneof time_offset { + // UTC offset. Must be whole seconds, between -18 hours and +18 hours. + // For example, a UTC offset of -4:00 would be represented as + // { seconds: -14400 }. + google.protobuf.Duration utc_offset = 8; + + // Time zone. + TimeZone time_zone = 9; + } +} + +// Represents a time zone from the +// [IANA Time Zone Database](https://www.iana.org/time-zones). +message TimeZone { + // IANA Time Zone Database time zone, e.g. "America/New_York". + string id = 1; + + // Optional. IANA Time Zone Database version number, e.g. "2019a". + string version = 2; +} diff --git a/node_modules/google-gax/build/protos/google/type/dayofweek.proto b/node_modules/google-gax/build/protos/google/type/dayofweek.proto new file mode 100644 index 0000000..4c80c62 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/type/dayofweek.proto @@ -0,0 +1,50 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/dayofweek;dayofweek"; +option java_multiple_files = true; +option java_outer_classname = "DayOfWeekProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents a day of the week. +enum DayOfWeek { + // The day of the week is unspecified. + DAY_OF_WEEK_UNSPECIFIED = 0; + + // Monday + MONDAY = 1; + + // Tuesday + TUESDAY = 2; + + // Wednesday + WEDNESDAY = 3; + + // Thursday + THURSDAY = 4; + + // Friday + FRIDAY = 5; + + // Saturday + SATURDAY = 6; + + // Sunday + SUNDAY = 7; +} diff --git a/node_modules/google-gax/build/protos/google/type/decimal.proto b/node_modules/google-gax/build/protos/google/type/decimal.proto new file mode 100644 index 0000000..beb18a5 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/type/decimal.proto @@ -0,0 +1,95 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/type/decimal;decimal"; +option java_multiple_files = true; +option java_outer_classname = "DecimalProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// A representation of a decimal value, such as 2.5. Clients may convert values +// into language-native decimal formats, such as Java's [BigDecimal][] or +// Python's [decimal.Decimal][]. +// +// [BigDecimal]: +// https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/math/BigDecimal.html +// [decimal.Decimal]: https://docs.python.org/3/library/decimal.html +message Decimal { + // The decimal value, as a string. + // + // The string representation consists of an optional sign, `+` (`U+002B`) + // or `-` (`U+002D`), followed by a sequence of zero or more decimal digits + // ("the integer"), optionally followed by a fraction, optionally followed + // by an exponent. + // + // The fraction consists of a decimal point followed by zero or more decimal + // digits. The string must contain at least one digit in either the integer + // or the fraction. The number formed by the sign, the integer and the + // fraction is referred to as the significand. + // + // The exponent consists of the character `e` (`U+0065`) or `E` (`U+0045`) + // followed by one or more decimal digits. + // + // Services **should** normalize decimal values before storing them by: + // + // - Removing an explicitly-provided `+` sign (`+2.5` -> `2.5`). + // - Replacing a zero-length integer value with `0` (`.5` -> `0.5`). + // - Coercing the exponent character to lower-case (`2.5E8` -> `2.5e8`). + // - Removing an explicitly-provided zero exponent (`2.5e0` -> `2.5`). + // + // Services **may** perform additional normalization based on its own needs + // and the internal decimal implementation selected, such as shifting the + // decimal point and exponent value together (example: `2.5e-1` <-> `0.25`). + // Additionally, services **may** preserve trailing zeroes in the fraction + // to indicate increased precision, but are not required to do so. + // + // Note that only the `.` character is supported to divide the integer + // and the fraction; `,` **should not** be supported regardless of locale. + // Additionally, thousand separators **should not** be supported. If a + // service does support them, values **must** be normalized. + // + // The ENBF grammar is: + // + // DecimalString = + // [Sign] Significand [Exponent]; + // + // Sign = '+' | '-'; + // + // Significand = + // Digits ['.'] [Digits] | [Digits] '.' Digits; + // + // Exponent = ('e' | 'E') [Sign] Digits; + // + // Digits = { '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' }; + // + // Services **should** clearly document the range of supported values, the + // maximum supported precision (total number of digits), and, if applicable, + // the scale (number of digits after the decimal point), as well as how it + // behaves when receiving out-of-bounds values. + // + // Services **may** choose to accept values passed as input even when the + // value has a higher precision or scale than the service supports, and + // **should** round the value to fit the supported scale. Alternatively, the + // service **may** error with `400 Bad Request` (`INVALID_ARGUMENT` in gRPC) + // if precision would be lost. + // + // Services **should** error with `400 Bad Request` (`INVALID_ARGUMENT` in + // gRPC) if the service receives a value outside of the supported range. + string value = 1; +} diff --git a/node_modules/google-gax/build/protos/google/type/expr.proto b/node_modules/google-gax/build/protos/google/type/expr.proto new file mode 100644 index 0000000..af0778c --- /dev/null +++ b/node_modules/google-gax/build/protos/google/type/expr.proto @@ -0,0 +1,73 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/expr;expr"; +option java_multiple_files = true; +option java_outer_classname = "ExprProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents a textual expression in the Common Expression Language (CEL) +// syntax. CEL is a C-like expression language. The syntax and semantics of CEL +// are documented at https://github.com/google/cel-spec. +// +// Example (Comparison): +// +// title: "Summary size limit" +// description: "Determines if a summary is less than 100 chars" +// expression: "document.summary.size() < 100" +// +// Example (Equality): +// +// title: "Requestor is owner" +// description: "Determines if requestor is the document owner" +// expression: "document.owner == request.auth.claims.email" +// +// Example (Logic): +// +// title: "Public documents" +// description: "Determine whether the document should be publicly visible" +// expression: "document.type != 'private' && document.type != 'internal'" +// +// Example (Data Manipulation): +// +// title: "Notification string" +// description: "Create a notification string with a timestamp." +// expression: "'New message received at ' + string(document.create_time)" +// +// The exact variables and functions that may be referenced within an expression +// are determined by the service that evaluates it. See the service +// documentation for additional information. +message Expr { + // Textual representation of an expression in Common Expression Language + // syntax. + string expression = 1; + + // Optional. Title for the expression, i.e. a short string describing + // its purpose. This can be used e.g. in UIs which allow to enter the + // expression. + string title = 2; + + // Optional. Description of the expression. This is a longer text which + // describes the expression, e.g. when hovered over it in a UI. + string description = 3; + + // Optional. String indicating the location of the expression for error + // reporting, e.g. a file name and a position in the file. + string location = 4; +} diff --git a/node_modules/google-gax/build/protos/google/type/fraction.proto b/node_modules/google-gax/build/protos/google/type/fraction.proto new file mode 100644 index 0000000..6c5ae6e --- /dev/null +++ b/node_modules/google-gax/build/protos/google/type/fraction.proto @@ -0,0 +1,33 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/fraction;fraction"; +option java_multiple_files = true; +option java_outer_classname = "FractionProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents a fraction in terms of a numerator divided by a denominator. +message Fraction { + // The numerator in the fraction, e.g. 2 in 2/3. + int64 numerator = 1; + + // The value by which the numerator is divided, e.g. 3 in 2/3. Must be + // positive. + int64 denominator = 2; +} diff --git a/node_modules/google-gax/build/protos/google/type/interval.proto b/node_modules/google-gax/build/protos/google/type/interval.proto new file mode 100644 index 0000000..9702324 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/type/interval.proto @@ -0,0 +1,46 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +import "google/protobuf/timestamp.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/type/interval;interval"; +option java_multiple_files = true; +option java_outer_classname = "IntervalProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents a time interval, encoded as a Timestamp start (inclusive) and a +// Timestamp end (exclusive). +// +// The start must be less than or equal to the end. +// When the start equals the end, the interval is empty (matches no time). +// When both start and end are unspecified, the interval matches any time. +message Interval { + // Optional. Inclusive start of the interval. + // + // If specified, a Timestamp matching this interval will have to be the same + // or after the start. + google.protobuf.Timestamp start_time = 1; + + // Optional. Exclusive end of the interval. + // + // If specified, a Timestamp matching this interval will have to be before the + // end. + google.protobuf.Timestamp end_time = 2; +} diff --git a/node_modules/google-gax/build/protos/google/type/latlng.proto b/node_modules/google-gax/build/protos/google/type/latlng.proto new file mode 100644 index 0000000..9231456 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/type/latlng.proto @@ -0,0 +1,37 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/type/latlng;latlng"; +option java_multiple_files = true; +option java_outer_classname = "LatLngProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// An object that represents a latitude/longitude pair. This is expressed as a +// pair of doubles to represent degrees latitude and degrees longitude. Unless +// specified otherwise, this must conform to the +// WGS84 +// standard. Values must be within normalized ranges. +message LatLng { + // The latitude in degrees. It must be in the range [-90.0, +90.0]. + double latitude = 1; + + // The longitude in degrees. It must be in the range [-180.0, +180.0]. + double longitude = 2; +} diff --git a/node_modules/google-gax/build/protos/google/type/localized_text.proto b/node_modules/google-gax/build/protos/google/type/localized_text.proto new file mode 100644 index 0000000..5c6922b --- /dev/null +++ b/node_modules/google-gax/build/protos/google/type/localized_text.proto @@ -0,0 +1,36 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/type/localized_text;localized_text"; +option java_multiple_files = true; +option java_outer_classname = "LocalizedTextProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Localized variant of a text in a particular language. +message LocalizedText { + // Localized string in the language corresponding to `language_code' below. + string text = 1; + + // The text's BCP-47 language code, such as "en-US" or "sr-Latn". + // + // For more information, see + // http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + string language_code = 2; +} diff --git a/node_modules/google-gax/build/protos/google/type/money.proto b/node_modules/google-gax/build/protos/google/type/money.proto new file mode 100644 index 0000000..98d6494 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/type/money.proto @@ -0,0 +1,42 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/type/money;money"; +option java_multiple_files = true; +option java_outer_classname = "MoneyProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents an amount of money with its currency type. +message Money { + // The three-letter currency code defined in ISO 4217. + string currency_code = 1; + + // The whole units of the amount. + // For example if `currencyCode` is `"USD"`, then 1 unit is one US dollar. + int64 units = 2; + + // Number of nano (10^-9) units of the amount. + // The value must be between -999,999,999 and +999,999,999 inclusive. + // If `units` is positive, `nanos` must be positive or zero. + // If `units` is zero, `nanos` can be positive, zero, or negative. + // If `units` is negative, `nanos` must be negative or zero. + // For example $-1.75 is represented as `units`=-1 and `nanos`=-750,000,000. + int32 nanos = 3; +} diff --git a/node_modules/google-gax/build/protos/google/type/month.proto b/node_modules/google-gax/build/protos/google/type/month.proto new file mode 100644 index 0000000..99e7551 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/type/month.proto @@ -0,0 +1,65 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/month;month"; +option java_multiple_files = true; +option java_outer_classname = "MonthProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents a month in the Gregorian calendar. +enum Month { + // The unspecified month. + MONTH_UNSPECIFIED = 0; + + // The month of January. + JANUARY = 1; + + // The month of February. + FEBRUARY = 2; + + // The month of March. + MARCH = 3; + + // The month of April. + APRIL = 4; + + // The month of May. + MAY = 5; + + // The month of June. + JUNE = 6; + + // The month of July. + JULY = 7; + + // The month of August. + AUGUST = 8; + + // The month of September. + SEPTEMBER = 9; + + // The month of October. + OCTOBER = 10; + + // The month of November. + NOVEMBER = 11; + + // The month of December. + DECEMBER = 12; +} diff --git a/node_modules/google-gax/build/protos/google/type/phone_number.proto b/node_modules/google-gax/build/protos/google/type/phone_number.proto new file mode 100644 index 0000000..7bbb7d8 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/type/phone_number.proto @@ -0,0 +1,113 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/type/phone_number;phone_number"; +option java_multiple_files = true; +option java_outer_classname = "PhoneNumberProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// An object representing a phone number, suitable as an API wire format. +// +// This representation: +// +// - should not be used for locale-specific formatting of a phone number, such +// as "+1 (650) 253-0000 ext. 123" +// +// - is not designed for efficient storage +// - may not be suitable for dialing - specialized libraries (see references) +// should be used to parse the number for that purpose +// +// To do something meaningful with this number, such as format it for various +// use-cases, convert it to an `i18n.phonenumbers.PhoneNumber` object first. +// +// For instance, in Java this would be: +// +// com.google.type.PhoneNumber wireProto = +// com.google.type.PhoneNumber.newBuilder().build(); +// com.google.i18n.phonenumbers.Phonenumber.PhoneNumber phoneNumber = +// PhoneNumberUtil.getInstance().parse(wireProto.getE164Number(), "ZZ"); +// if (!wireProto.getExtension().isEmpty()) { +// phoneNumber.setExtension(wireProto.getExtension()); +// } +// +// Reference(s): +// - https://github.com/google/libphonenumber +message PhoneNumber { + // An object representing a short code, which is a phone number that is + // typically much shorter than regular phone numbers and can be used to + // address messages in MMS and SMS systems, as well as for abbreviated dialing + // (e.g. "Text 611 to see how many minutes you have remaining on your plan."). + // + // Short codes are restricted to a region and are not internationally + // dialable, which means the same short code can exist in different regions, + // with different usage and pricing, even if those regions share the same + // country calling code (e.g. US and CA). + message ShortCode { + // Required. The BCP-47 region code of the location where calls to this + // short code can be made, such as "US" and "BB". + // + // Reference(s): + // - http://www.unicode.org/reports/tr35/#unicode_region_subtag + string region_code = 1; + + // Required. The short code digits, without a leading plus ('+') or country + // calling code, e.g. "611". + string number = 2; + } + + // Required. Either a regular number, or a short code. New fields may be + // added to the oneof below in the future, so clients should ignore phone + // numbers for which none of the fields they coded against are set. + oneof kind { + // The phone number, represented as a leading plus sign ('+'), followed by a + // phone number that uses a relaxed ITU E.164 format consisting of the + // country calling code (1 to 3 digits) and the subscriber number, with no + // additional spaces or formatting, e.g.: + // - correct: "+15552220123" + // - incorrect: "+1 (555) 222-01234 x123". + // + // The ITU E.164 format limits the latter to 12 digits, but in practice not + // all countries respect that, so we relax that restriction here. + // National-only numbers are not allowed. + // + // References: + // - https://www.itu.int/rec/T-REC-E.164-201011-I + // - https://en.wikipedia.org/wiki/E.164. + // - https://en.wikipedia.org/wiki/List_of_country_calling_codes + string e164_number = 1; + + // A short code. + // + // Reference(s): + // - https://en.wikipedia.org/wiki/Short_code + ShortCode short_code = 2; + } + + // The phone number's extension. The extension is not standardized in ITU + // recommendations, except for being defined as a series of numbers with a + // maximum length of 40 digits. Other than digits, some other dialing + // characters such as ',' (indicating a wait) or '#' may be stored here. + // + // Note that no regions currently use extensions with short codes, so this + // field is normally only set in conjunction with an E.164 number. It is held + // separately from the E.164 number to allow for short code extensions in the + // future. + string extension = 3; +} diff --git a/node_modules/google-gax/build/protos/google/type/postal_address.proto b/node_modules/google-gax/build/protos/google/type/postal_address.proto new file mode 100644 index 0000000..c57c7c3 --- /dev/null +++ b/node_modules/google-gax/build/protos/google/type/postal_address.proto @@ -0,0 +1,134 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/type/postaladdress;postaladdress"; +option java_multiple_files = true; +option java_outer_classname = "PostalAddressProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents a postal address, e.g. for postal delivery or payments addresses. +// Given a postal address, a postal service can deliver items to a premise, P.O. +// Box or similar. +// It is not intended to model geographical locations (roads, towns, +// mountains). +// +// In typical usage an address would be created via user input or from importing +// existing data, depending on the type of process. +// +// Advice on address input / editing: +// - Use an i18n-ready address widget such as +// https://github.com/google/libaddressinput) +// - Users should not be presented with UI elements for input or editing of +// fields outside countries where that field is used. +// +// For more guidance on how to use this schema, please see: +// https://support.google.com/business/answer/6397478 +message PostalAddress { + // The schema revision of the `PostalAddress`. This must be set to 0, which is + // the latest revision. + // + // All new revisions **must** be backward compatible with old revisions. + int32 revision = 1; + + // Required. CLDR region code of the country/region of the address. This + // is never inferred and it is up to the user to ensure the value is + // correct. See http://cldr.unicode.org/ and + // http://www.unicode.org/cldr/charts/30/supplemental/territory_information.html + // for details. Example: "CH" for Switzerland. + string region_code = 2; + + // Optional. BCP-47 language code of the contents of this address (if + // known). This is often the UI language of the input form or is expected + // to match one of the languages used in the address' country/region, or their + // transliterated equivalents. + // This can affect formatting in certain countries, but is not critical + // to the correctness of the data and will never affect any validation or + // other non-formatting related operations. + // + // If this value is not known, it should be omitted (rather than specifying a + // possibly incorrect default). + // + // Examples: "zh-Hant", "ja", "ja-Latn", "en". + string language_code = 3; + + // Optional. Postal code of the address. Not all countries use or require + // postal codes to be present, but where they are used, they may trigger + // additional validation with other parts of the address (e.g. state/zip + // validation in the U.S.A.). + string postal_code = 4; + + // Optional. Additional, country-specific, sorting code. This is not used + // in most regions. Where it is used, the value is either a string like + // "CEDEX", optionally followed by a number (e.g. "CEDEX 7"), or just a number + // alone, representing the "sector code" (Jamaica), "delivery area indicator" + // (Malawi) or "post office indicator" (e.g. Côte d'Ivoire). + string sorting_code = 5; + + // Optional. Highest administrative subdivision which is used for postal + // addresses of a country or region. + // For example, this can be a state, a province, an oblast, or a prefecture. + // Specifically, for Spain this is the province and not the autonomous + // community (e.g. "Barcelona" and not "Catalonia"). + // Many countries don't use an administrative area in postal addresses. E.g. + // in Switzerland this should be left unpopulated. + string administrative_area = 6; + + // Optional. Generally refers to the city/town portion of the address. + // Examples: US city, IT comune, UK post town. + // In regions of the world where localities are not well defined or do not fit + // into this structure well, leave locality empty and use address_lines. + string locality = 7; + + // Optional. Sublocality of the address. + // For example, this can be neighborhoods, boroughs, districts. + string sublocality = 8; + + // Unstructured address lines describing the lower levels of an address. + // + // Because values in address_lines do not have type information and may + // sometimes contain multiple values in a single field (e.g. + // "Austin, TX"), it is important that the line order is clear. The order of + // address lines should be "envelope order" for the country/region of the + // address. In places where this can vary (e.g. Japan), address_language is + // used to make it explicit (e.g. "ja" for large-to-small ordering and + // "ja-Latn" or "en" for small-to-large). This way, the most specific line of + // an address can be selected based on the language. + // + // The minimum permitted structural representation of an address consists + // of a region_code with all remaining information placed in the + // address_lines. It would be possible to format such an address very + // approximately without geocoding, but no semantic reasoning could be + // made about any of the address components until it was at least + // partially resolved. + // + // Creating an address only containing a region_code and address_lines, and + // then geocoding is the recommended way to handle completely unstructured + // addresses (as opposed to guessing which parts of the address should be + // localities or administrative areas). + repeated string address_lines = 9; + + // Optional. The recipient at the address. + // This field may, under certain circumstances, contain multiline information. + // For example, it might contain "care of" information. + repeated string recipients = 10; + + // Optional. The name of the organization at the address. + string organization = 11; +} diff --git a/node_modules/google-gax/build/protos/google/type/quaternion.proto b/node_modules/google-gax/build/protos/google/type/quaternion.proto new file mode 100644 index 0000000..dfb822d --- /dev/null +++ b/node_modules/google-gax/build/protos/google/type/quaternion.proto @@ -0,0 +1,94 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/type/quaternion;quaternion"; +option java_multiple_files = true; +option java_outer_classname = "QuaternionProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// A quaternion is defined as the quotient of two directed lines in a +// three-dimensional space or equivalently as the quotient of two Euclidean +// vectors (https://en.wikipedia.org/wiki/Quaternion). +// +// Quaternions are often used in calculations involving three-dimensional +// rotations (https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation), +// as they provide greater mathematical robustness by avoiding the gimbal lock +// problems that can be encountered when using Euler angles +// (https://en.wikipedia.org/wiki/Gimbal_lock). +// +// Quaternions are generally represented in this form: +// +// w + xi + yj + zk +// +// where x, y, z, and w are real numbers, and i, j, and k are three imaginary +// numbers. +// +// Our naming choice `(x, y, z, w)` comes from the desire to avoid confusion for +// those interested in the geometric properties of the quaternion in the 3D +// Cartesian space. Other texts often use alternative names or subscripts, such +// as `(a, b, c, d)`, `(1, i, j, k)`, or `(0, 1, 2, 3)`, which are perhaps +// better suited for mathematical interpretations. +// +// To avoid any confusion, as well as to maintain compatibility with a large +// number of software libraries, the quaternions represented using the protocol +// buffer below *must* follow the Hamilton convention, which defines `ij = k` +// (i.e. a right-handed algebra), and therefore: +// +// i^2 = j^2 = k^2 = ijk = −1 +// ij = −ji = k +// jk = −kj = i +// ki = −ik = j +// +// Please DO NOT use this to represent quaternions that follow the JPL +// convention, or any of the other quaternion flavors out there. +// +// Definitions: +// +// - Quaternion norm (or magnitude): `sqrt(x^2 + y^2 + z^2 + w^2)`. +// - Unit (or normalized) quaternion: a quaternion whose norm is 1. +// - Pure quaternion: a quaternion whose scalar component (`w`) is 0. +// - Rotation quaternion: a unit quaternion used to represent rotation. +// - Orientation quaternion: a unit quaternion used to represent orientation. +// +// A quaternion can be normalized by dividing it by its norm. The resulting +// quaternion maintains the same direction, but has a norm of 1, i.e. it moves +// on the unit sphere. This is generally necessary for rotation and orientation +// quaternions, to avoid rounding errors: +// https://en.wikipedia.org/wiki/Rotation_formalisms_in_three_dimensions +// +// Note that `(x, y, z, w)` and `(-x, -y, -z, -w)` represent the same rotation, +// but normalization would be even more useful, e.g. for comparison purposes, if +// it would produce a unique representation. It is thus recommended that `w` be +// kept positive, which can be achieved by changing all the signs when `w` is +// negative. +// +message Quaternion { + // The x component. + double x = 1; + + // The y component. + double y = 2; + + // The z component. + double z = 3; + + // The scalar component. + double w = 4; +} diff --git a/node_modules/google-gax/build/protos/google/type/timeofday.proto b/node_modules/google-gax/build/protos/google/type/timeofday.proto new file mode 100644 index 0000000..5cb48aa --- /dev/null +++ b/node_modules/google-gax/build/protos/google/type/timeofday.proto @@ -0,0 +1,44 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/type/timeofday;timeofday"; +option java_multiple_files = true; +option java_outer_classname = "TimeOfDayProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents a time of day. The date and time zone are either not significant +// or are specified elsewhere. An API may choose to allow leap seconds. Related +// types are [google.type.Date][google.type.Date] and +// `google.protobuf.Timestamp`. +message TimeOfDay { + // Hours of day in 24 hour format. Should be from 0 to 23. An API may choose + // to allow the value "24:00:00" for scenarios like business closing time. + int32 hours = 1; + + // Minutes of hour of day. Must be from 0 to 59. + int32 minutes = 2; + + // Seconds of minutes of the time. Must normally be from 0 to 59. An API may + // allow the value 60 if it allows leap-seconds. + int32 seconds = 3; + + // Fractions of seconds in nanoseconds. Must be from 0 to 999,999,999. + int32 nanos = 4; +} diff --git a/node_modules/google-gax/build/protos/http.d.ts b/node_modules/google-gax/build/protos/http.d.ts new file mode 100644 index 0000000..1f03560 --- /dev/null +++ b/node_modules/google-gax/build/protos/http.d.ts @@ -0,0 +1,347 @@ +import * as $protobuf from "protobufjs"; +/** Namespace google. */ +export namespace google { + + /** Namespace api. */ + namespace api { + + /** Properties of a Http. */ + interface IHttp { + + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); + + /** Http fully_decode_reserved_expansion */ + fully_decode_reserved_expansion?: (boolean|null); + } + + /** Represents a Http. */ + class Http implements IHttp { + + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); + + /** Http rules. */ + public rules: google.api.IHttpRule[]; + + /** Http fully_decode_reserved_expansion. */ + public fully_decode_reserved_expansion: boolean; + + /** + * Creates a new Http instance using the specified properties. + * @param [properties] Properties to set + * @returns Http instance + */ + public static create(properties?: google.api.IHttp): google.api.Http; + + /** + * Encodes the specified Http message. Does not implicitly {@link google.api.Http.verify|verify} messages. + * @param message Http message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Http message, length delimited. Does not implicitly {@link google.api.Http.verify|verify} messages. + * @param message Http message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Http message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Http + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Http; + + /** + * Decodes a Http message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Http + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Http; + + /** + * Verifies a Http message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a HttpRule. */ + interface IHttpRule { + + /** HttpRule selector */ + selector?: (string|null); + + /** HttpRule get */ + get?: (string|null); + + /** HttpRule put */ + put?: (string|null); + + /** HttpRule post */ + post?: (string|null); + + /** HttpRule delete */ + "delete"?: (string|null); + + /** HttpRule patch */ + patch?: (string|null); + + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body */ + body?: (string|null); + + /** HttpRule response_body */ + response_body?: (string|null); + + /** HttpRule additional_bindings */ + additional_bindings?: (google.api.IHttpRule[]|null); + } + + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { + + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); + + /** HttpRule selector. */ + public selector: string; + + /** HttpRule get. */ + public get: string; + + /** HttpRule put. */ + public put: string; + + /** HttpRule post. */ + public post: string; + + /** HttpRule delete. */ + public delete: string; + + /** HttpRule patch. */ + public patch: string; + + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body. */ + public body: string; + + /** HttpRule response_body. */ + public response_body: string; + + /** HttpRule additional_bindings. */ + public additional_bindings: google.api.IHttpRule[]; + + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + + /** + * Creates a new HttpRule instance using the specified properties. + * @param [properties] Properties to set + * @returns HttpRule instance + */ + public static create(properties?: google.api.IHttpRule): google.api.HttpRule; + + /** + * Encodes the specified HttpRule message. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. + * @param message HttpRule message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified HttpRule message, length delimited. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. + * @param message HttpRule message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a HttpRule message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns HttpRule + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.HttpRule; + + /** + * Decodes a HttpRule message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns HttpRule + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.HttpRule; + + /** + * Verifies a HttpRule message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { + + /** CustomHttpPattern kind */ + kind?: (string|null); + + /** CustomHttpPattern path */ + path?: (string|null); + } + + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { + + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); + + /** CustomHttpPattern kind. */ + public kind: string; + + /** CustomHttpPattern path. */ + public path: string; + + /** + * Creates a new CustomHttpPattern instance using the specified properties. + * @param [properties] Properties to set + * @returns CustomHttpPattern instance + */ + public static create(properties?: google.api.ICustomHttpPattern): google.api.CustomHttpPattern; + + /** + * Encodes the specified CustomHttpPattern message. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. + * @param message CustomHttpPattern message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CustomHttpPattern message, length delimited. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. + * @param message CustomHttpPattern message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CustomHttpPattern message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CustomHttpPattern + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.CustomHttpPattern; + + /** + * Decodes a CustomHttpPattern message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CustomHttpPattern + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.CustomHttpPattern; + + /** + * Verifies a CustomHttpPattern message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } +} diff --git a/node_modules/google-gax/build/protos/http.js b/node_modules/google-gax/build/protos/http.js new file mode 100644 index 0000000..8ad3fc0 --- /dev/null +++ b/node_modules/google-gax/build/protos/http.js @@ -0,0 +1 @@ +(e=>{"function"==typeof define&&define.amd?define(["protobufjs/minimal"],e):"function"==typeof require&&"object"==typeof module&&module&&module.exports&&(module.exports=e(require("protobufjs/minimal")))})(function(e){var t,n,r,i=e.Reader,o=e.Writer,l=e.util,s=e.roots.default||(e.roots.default={});function a(e){if(this.rules=[],e)for(var t=Object.keys(e),n=0;n>>3){case 1:r.rules&&r.rules.length||(r.rules=[]),r.rules.push(s.google.api.HttpRule.decode(e,e.uint32()));break;case 2:r.fully_decode_reserved_expansion=e.bool();break;default:e.skipType(7&o)}}return r},a.decodeDelimited=function(e){return e instanceof i||(e=new i(e)),this.decode(e,e.uint32())},a.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.rules&&e.hasOwnProperty("rules")){if(!Array.isArray(e.rules))return"rules: array expected";for(var t=0;t>>3){case 1:r.selector=e.string();break;case 2:r.get=e.string();break;case 3:r.put=e.string();break;case 4:r.post=e.string();break;case 5:r.delete=e.string();break;case 6:r.patch=e.string();break;case 8:r.custom=s.google.api.CustomHttpPattern.decode(e,e.uint32());break;case 7:r.body=e.string();break;case 12:r.response_body=e.string();break;case 11:r.additional_bindings&&r.additional_bindings.length||(r.additional_bindings=[]),r.additional_bindings.push(s.google.api.HttpRule.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return r},p.decodeDelimited=function(e){return e instanceof i||(e=new i(e)),this.decode(e,e.uint32())},p.verify=function(e){if("object"!=typeof e||null===e)return"object expected";var t={};if(null!=e.selector&&e.hasOwnProperty("selector")&&!l.isString(e.selector))return"selector: string expected";if(null!=e.get&&e.hasOwnProperty("get")&&(t.pattern=1,!l.isString(e.get)))return"get: string expected";if(null!=e.put&&e.hasOwnProperty("put")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,!l.isString(e.put))return"put: string expected"}if(null!=e.post&&e.hasOwnProperty("post")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,!l.isString(e.post))return"post: string expected"}if(null!=e.delete&&e.hasOwnProperty("delete")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,!l.isString(e.delete))return"delete: string expected"}if(null!=e.patch&&e.hasOwnProperty("patch")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,!l.isString(e.patch))return"patch: string expected"}if(null!=e.custom&&e.hasOwnProperty("custom")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,n=s.google.api.CustomHttpPattern.verify(e.custom))return"custom."+n}if(null!=e.body&&e.hasOwnProperty("body")&&!l.isString(e.body))return"body: string expected";if(null!=e.response_body&&e.hasOwnProperty("response_body")&&!l.isString(e.response_body))return"response_body: string expected";if(null!=e.additional_bindings&&e.hasOwnProperty("additional_bindings")){if(!Array.isArray(e.additional_bindings))return"additional_bindings: array expected";for(var n,r=0;r>>3){case 1:r.kind=e.string();break;case 2:r.path=e.string();break;default:e.skipType(7&o)}}return r},u.decodeDelimited=function(e){return e instanceof i||(e=new i(e)),this.decode(e,e.uint32())},u.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.kind&&e.hasOwnProperty("kind")&&!l.isString(e.kind)?"kind: string expected":null!=e.path&&e.hasOwnProperty("path")&&!l.isString(e.path)?"path: string expected":null},u.fromObject=function(e){var t;return e instanceof s.google.api.CustomHttpPattern?e:(t=new s.google.api.CustomHttpPattern,null!=e.kind&&(t.kind=String(e.kind)),null!=e.path&&(t.path=String(e.path)),t)},u.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.kind="",n.path=""),null!=e.kind&&e.hasOwnProperty("kind")&&(n.kind=e.kind),null!=e.path&&e.hasOwnProperty("path")&&(n.path=e.path),n},u.prototype.toJSON=function(){return this.constructor.toObject(this,e.util.toJSONOptions)},u),n),r),s}); \ No newline at end of file diff --git a/node_modules/google-gax/build/protos/iam_service.d.ts b/node_modules/google-gax/build/protos/iam_service.d.ts new file mode 100644 index 0000000..37203e4 --- /dev/null +++ b/node_modules/google-gax/build/protos/iam_service.d.ts @@ -0,0 +1,5035 @@ +/** + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Long = require('long'); +import * as $protobuf from "protobufjs"; +/** Namespace google. */ +export namespace google { + + /** Namespace iam. */ + namespace iam { + + /** Namespace v1. */ + namespace v1 { + + /** Represents a IAMPolicy */ + class IAMPolicy extends $protobuf.rpc.Service { + + /** + * Constructs a new IAMPolicy service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new IAMPolicy service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): IAMPolicy; + + /** + * Calls SetIamPolicy. + * @param request SetIamPolicyRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Policy + */ + public setIamPolicy(request: google.iam.v1.ISetIamPolicyRequest, callback: google.iam.v1.IAMPolicy.SetIamPolicyCallback): void; + + /** + * Calls SetIamPolicy. + * @param request SetIamPolicyRequest message or plain object + * @returns Promise + */ + public setIamPolicy(request: google.iam.v1.ISetIamPolicyRequest): Promise; + + /** + * Calls GetIamPolicy. + * @param request GetIamPolicyRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Policy + */ + public getIamPolicy(request: google.iam.v1.IGetIamPolicyRequest, callback: google.iam.v1.IAMPolicy.GetIamPolicyCallback): void; + + /** + * Calls GetIamPolicy. + * @param request GetIamPolicyRequest message or plain object + * @returns Promise + */ + public getIamPolicy(request: google.iam.v1.IGetIamPolicyRequest): Promise; + + /** + * Calls TestIamPermissions. + * @param request TestIamPermissionsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and TestIamPermissionsResponse + */ + public testIamPermissions(request: google.iam.v1.ITestIamPermissionsRequest, callback: google.iam.v1.IAMPolicy.TestIamPermissionsCallback): void; + + /** + * Calls TestIamPermissions. + * @param request TestIamPermissionsRequest message or plain object + * @returns Promise + */ + public testIamPermissions(request: google.iam.v1.ITestIamPermissionsRequest): Promise; + } + + namespace IAMPolicy { + + /** + * Callback as used by {@link google.iam.v1.IAMPolicy#setIamPolicy}. + * @param error Error, if any + * @param [response] Policy + */ + type SetIamPolicyCallback = (error: (Error|null), response?: google.iam.v1.Policy) => void; + + /** + * Callback as used by {@link google.iam.v1.IAMPolicy#getIamPolicy}. + * @param error Error, if any + * @param [response] Policy + */ + type GetIamPolicyCallback = (error: (Error|null), response?: google.iam.v1.Policy) => void; + + /** + * Callback as used by {@link google.iam.v1.IAMPolicy#testIamPermissions}. + * @param error Error, if any + * @param [response] TestIamPermissionsResponse + */ + type TestIamPermissionsCallback = (error: (Error|null), response?: google.iam.v1.TestIamPermissionsResponse) => void; + } + + /** Properties of a SetIamPolicyRequest. */ + interface ISetIamPolicyRequest { + + /** SetIamPolicyRequest resource */ + resource?: (string|null); + + /** SetIamPolicyRequest policy */ + policy?: (google.iam.v1.IPolicy|null); + } + + /** Represents a SetIamPolicyRequest. */ + class SetIamPolicyRequest implements ISetIamPolicyRequest { + + /** + * Constructs a new SetIamPolicyRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.ISetIamPolicyRequest); + + /** SetIamPolicyRequest resource. */ + public resource: string; + + /** SetIamPolicyRequest policy. */ + public policy?: (google.iam.v1.IPolicy|null); + + /** + * Creates a new SetIamPolicyRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns SetIamPolicyRequest instance + */ + public static create(properties?: google.iam.v1.ISetIamPolicyRequest): google.iam.v1.SetIamPolicyRequest; + + /** + * Encodes the specified SetIamPolicyRequest message. Does not implicitly {@link google.iam.v1.SetIamPolicyRequest.verify|verify} messages. + * @param message SetIamPolicyRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.ISetIamPolicyRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SetIamPolicyRequest message, length delimited. Does not implicitly {@link google.iam.v1.SetIamPolicyRequest.verify|verify} messages. + * @param message SetIamPolicyRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.ISetIamPolicyRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SetIamPolicyRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SetIamPolicyRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.SetIamPolicyRequest; + + /** + * Decodes a SetIamPolicyRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SetIamPolicyRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.SetIamPolicyRequest; + + /** + * Verifies a SetIamPolicyRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SetIamPolicyRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SetIamPolicyRequest + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.SetIamPolicyRequest; + + /** + * Creates a plain object from a SetIamPolicyRequest message. Also converts values to other types if specified. + * @param message SetIamPolicyRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.SetIamPolicyRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SetIamPolicyRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a GetIamPolicyRequest. */ + interface IGetIamPolicyRequest { + + /** GetIamPolicyRequest resource */ + resource?: (string|null); + + /** GetIamPolicyRequest options */ + options?: (google.iam.v1.IGetPolicyOptions|null); + } + + /** Represents a GetIamPolicyRequest. */ + class GetIamPolicyRequest implements IGetIamPolicyRequest { + + /** + * Constructs a new GetIamPolicyRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.IGetIamPolicyRequest); + + /** GetIamPolicyRequest resource. */ + public resource: string; + + /** GetIamPolicyRequest options. */ + public options?: (google.iam.v1.IGetPolicyOptions|null); + + /** + * Creates a new GetIamPolicyRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetIamPolicyRequest instance + */ + public static create(properties?: google.iam.v1.IGetIamPolicyRequest): google.iam.v1.GetIamPolicyRequest; + + /** + * Encodes the specified GetIamPolicyRequest message. Does not implicitly {@link google.iam.v1.GetIamPolicyRequest.verify|verify} messages. + * @param message GetIamPolicyRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.IGetIamPolicyRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetIamPolicyRequest message, length delimited. Does not implicitly {@link google.iam.v1.GetIamPolicyRequest.verify|verify} messages. + * @param message GetIamPolicyRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.IGetIamPolicyRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetIamPolicyRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetIamPolicyRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.GetIamPolicyRequest; + + /** + * Decodes a GetIamPolicyRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetIamPolicyRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.GetIamPolicyRequest; + + /** + * Verifies a GetIamPolicyRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetIamPolicyRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetIamPolicyRequest + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.GetIamPolicyRequest; + + /** + * Creates a plain object from a GetIamPolicyRequest message. Also converts values to other types if specified. + * @param message GetIamPolicyRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.GetIamPolicyRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetIamPolicyRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a TestIamPermissionsRequest. */ + interface ITestIamPermissionsRequest { + + /** TestIamPermissionsRequest resource */ + resource?: (string|null); + + /** TestIamPermissionsRequest permissions */ + permissions?: (string[]|null); + } + + /** Represents a TestIamPermissionsRequest. */ + class TestIamPermissionsRequest implements ITestIamPermissionsRequest { + + /** + * Constructs a new TestIamPermissionsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.ITestIamPermissionsRequest); + + /** TestIamPermissionsRequest resource. */ + public resource: string; + + /** TestIamPermissionsRequest permissions. */ + public permissions: string[]; + + /** + * Creates a new TestIamPermissionsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns TestIamPermissionsRequest instance + */ + public static create(properties?: google.iam.v1.ITestIamPermissionsRequest): google.iam.v1.TestIamPermissionsRequest; + + /** + * Encodes the specified TestIamPermissionsRequest message. Does not implicitly {@link google.iam.v1.TestIamPermissionsRequest.verify|verify} messages. + * @param message TestIamPermissionsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.ITestIamPermissionsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified TestIamPermissionsRequest message, length delimited. Does not implicitly {@link google.iam.v1.TestIamPermissionsRequest.verify|verify} messages. + * @param message TestIamPermissionsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.ITestIamPermissionsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a TestIamPermissionsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns TestIamPermissionsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.TestIamPermissionsRequest; + + /** + * Decodes a TestIamPermissionsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns TestIamPermissionsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.TestIamPermissionsRequest; + + /** + * Verifies a TestIamPermissionsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a TestIamPermissionsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TestIamPermissionsRequest + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.TestIamPermissionsRequest; + + /** + * Creates a plain object from a TestIamPermissionsRequest message. Also converts values to other types if specified. + * @param message TestIamPermissionsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.TestIamPermissionsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TestIamPermissionsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a TestIamPermissionsResponse. */ + interface ITestIamPermissionsResponse { + + /** TestIamPermissionsResponse permissions */ + permissions?: (string[]|null); + } + + /** Represents a TestIamPermissionsResponse. */ + class TestIamPermissionsResponse implements ITestIamPermissionsResponse { + + /** + * Constructs a new TestIamPermissionsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.ITestIamPermissionsResponse); + + /** TestIamPermissionsResponse permissions. */ + public permissions: string[]; + + /** + * Creates a new TestIamPermissionsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns TestIamPermissionsResponse instance + */ + public static create(properties?: google.iam.v1.ITestIamPermissionsResponse): google.iam.v1.TestIamPermissionsResponse; + + /** + * Encodes the specified TestIamPermissionsResponse message. Does not implicitly {@link google.iam.v1.TestIamPermissionsResponse.verify|verify} messages. + * @param message TestIamPermissionsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.ITestIamPermissionsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified TestIamPermissionsResponse message, length delimited. Does not implicitly {@link google.iam.v1.TestIamPermissionsResponse.verify|verify} messages. + * @param message TestIamPermissionsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.ITestIamPermissionsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a TestIamPermissionsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns TestIamPermissionsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.TestIamPermissionsResponse; + + /** + * Decodes a TestIamPermissionsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns TestIamPermissionsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.TestIamPermissionsResponse; + + /** + * Verifies a TestIamPermissionsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a TestIamPermissionsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TestIamPermissionsResponse + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.TestIamPermissionsResponse; + + /** + * Creates a plain object from a TestIamPermissionsResponse message. Also converts values to other types if specified. + * @param message TestIamPermissionsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.TestIamPermissionsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TestIamPermissionsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a GetPolicyOptions. */ + interface IGetPolicyOptions { + + /** GetPolicyOptions requestedPolicyVersion */ + requestedPolicyVersion?: (number|null); + } + + /** Represents a GetPolicyOptions. */ + class GetPolicyOptions implements IGetPolicyOptions { + + /** + * Constructs a new GetPolicyOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.IGetPolicyOptions); + + /** GetPolicyOptions requestedPolicyVersion. */ + public requestedPolicyVersion: number; + + /** + * Creates a new GetPolicyOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns GetPolicyOptions instance + */ + public static create(properties?: google.iam.v1.IGetPolicyOptions): google.iam.v1.GetPolicyOptions; + + /** + * Encodes the specified GetPolicyOptions message. Does not implicitly {@link google.iam.v1.GetPolicyOptions.verify|verify} messages. + * @param message GetPolicyOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.IGetPolicyOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetPolicyOptions message, length delimited. Does not implicitly {@link google.iam.v1.GetPolicyOptions.verify|verify} messages. + * @param message GetPolicyOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.IGetPolicyOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetPolicyOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetPolicyOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.GetPolicyOptions; + + /** + * Decodes a GetPolicyOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetPolicyOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.GetPolicyOptions; + + /** + * Verifies a GetPolicyOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetPolicyOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetPolicyOptions + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.GetPolicyOptions; + + /** + * Creates a plain object from a GetPolicyOptions message. Also converts values to other types if specified. + * @param message GetPolicyOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.GetPolicyOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetPolicyOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a Policy. */ + interface IPolicy { + + /** Policy version */ + version?: (number|null); + + /** Policy bindings */ + bindings?: (google.iam.v1.IBinding[]|null); + + /** Policy etag */ + etag?: (Uint8Array|null); + } + + /** Represents a Policy. */ + class Policy implements IPolicy { + + /** + * Constructs a new Policy. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.IPolicy); + + /** Policy version. */ + public version: number; + + /** Policy bindings. */ + public bindings: google.iam.v1.IBinding[]; + + /** Policy etag. */ + public etag: Uint8Array; + + /** + * Creates a new Policy instance using the specified properties. + * @param [properties] Properties to set + * @returns Policy instance + */ + public static create(properties?: google.iam.v1.IPolicy): google.iam.v1.Policy; + + /** + * Encodes the specified Policy message. Does not implicitly {@link google.iam.v1.Policy.verify|verify} messages. + * @param message Policy message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.IPolicy, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Policy message, length delimited. Does not implicitly {@link google.iam.v1.Policy.verify|verify} messages. + * @param message Policy message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.IPolicy, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Policy message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Policy + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.Policy; + + /** + * Decodes a Policy message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Policy + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.Policy; + + /** + * Verifies a Policy message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Policy message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Policy + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.Policy; + + /** + * Creates a plain object from a Policy message. Also converts values to other types if specified. + * @param message Policy + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.Policy, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Policy to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a Binding. */ + interface IBinding { + + /** Binding role */ + role?: (string|null); + + /** Binding members */ + members?: (string[]|null); + + /** Binding condition */ + condition?: (google.type.IExpr|null); + } + + /** Represents a Binding. */ + class Binding implements IBinding { + + /** + * Constructs a new Binding. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.IBinding); + + /** Binding role. */ + public role: string; + + /** Binding members. */ + public members: string[]; + + /** Binding condition. */ + public condition?: (google.type.IExpr|null); + + /** + * Creates a new Binding instance using the specified properties. + * @param [properties] Properties to set + * @returns Binding instance + */ + public static create(properties?: google.iam.v1.IBinding): google.iam.v1.Binding; + + /** + * Encodes the specified Binding message. Does not implicitly {@link google.iam.v1.Binding.verify|verify} messages. + * @param message Binding message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.IBinding, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Binding message, length delimited. Does not implicitly {@link google.iam.v1.Binding.verify|verify} messages. + * @param message Binding message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.IBinding, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Binding message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Binding + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.Binding; + + /** + * Decodes a Binding message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Binding + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.Binding; + + /** + * Verifies a Binding message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Binding message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Binding + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.Binding; + + /** + * Creates a plain object from a Binding message. Also converts values to other types if specified. + * @param message Binding + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.Binding, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Binding to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a PolicyDelta. */ + interface IPolicyDelta { + + /** PolicyDelta bindingDeltas */ + bindingDeltas?: (google.iam.v1.IBindingDelta[]|null); + + /** PolicyDelta auditConfigDeltas */ + auditConfigDeltas?: (google.iam.v1.IAuditConfigDelta[]|null); + } + + /** Represents a PolicyDelta. */ + class PolicyDelta implements IPolicyDelta { + + /** + * Constructs a new PolicyDelta. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.IPolicyDelta); + + /** PolicyDelta bindingDeltas. */ + public bindingDeltas: google.iam.v1.IBindingDelta[]; + + /** PolicyDelta auditConfigDeltas. */ + public auditConfigDeltas: google.iam.v1.IAuditConfigDelta[]; + + /** + * Creates a new PolicyDelta instance using the specified properties. + * @param [properties] Properties to set + * @returns PolicyDelta instance + */ + public static create(properties?: google.iam.v1.IPolicyDelta): google.iam.v1.PolicyDelta; + + /** + * Encodes the specified PolicyDelta message. Does not implicitly {@link google.iam.v1.PolicyDelta.verify|verify} messages. + * @param message PolicyDelta message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.IPolicyDelta, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PolicyDelta message, length delimited. Does not implicitly {@link google.iam.v1.PolicyDelta.verify|verify} messages. + * @param message PolicyDelta message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.IPolicyDelta, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PolicyDelta message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PolicyDelta + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.PolicyDelta; + + /** + * Decodes a PolicyDelta message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PolicyDelta + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.PolicyDelta; + + /** + * Verifies a PolicyDelta message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PolicyDelta message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PolicyDelta + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.PolicyDelta; + + /** + * Creates a plain object from a PolicyDelta message. Also converts values to other types if specified. + * @param message PolicyDelta + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.PolicyDelta, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PolicyDelta to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a BindingDelta. */ + interface IBindingDelta { + + /** BindingDelta action */ + action?: (google.iam.v1.BindingDelta.Action|null); + + /** BindingDelta role */ + role?: (string|null); + + /** BindingDelta member */ + member?: (string|null); + + /** BindingDelta condition */ + condition?: (google.type.IExpr|null); + } + + /** Represents a BindingDelta. */ + class BindingDelta implements IBindingDelta { + + /** + * Constructs a new BindingDelta. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.IBindingDelta); + + /** BindingDelta action. */ + public action: google.iam.v1.BindingDelta.Action; + + /** BindingDelta role. */ + public role: string; + + /** BindingDelta member. */ + public member: string; + + /** BindingDelta condition. */ + public condition?: (google.type.IExpr|null); + + /** + * Creates a new BindingDelta instance using the specified properties. + * @param [properties] Properties to set + * @returns BindingDelta instance + */ + public static create(properties?: google.iam.v1.IBindingDelta): google.iam.v1.BindingDelta; + + /** + * Encodes the specified BindingDelta message. Does not implicitly {@link google.iam.v1.BindingDelta.verify|verify} messages. + * @param message BindingDelta message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.IBindingDelta, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified BindingDelta message, length delimited. Does not implicitly {@link google.iam.v1.BindingDelta.verify|verify} messages. + * @param message BindingDelta message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.IBindingDelta, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a BindingDelta message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns BindingDelta + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.BindingDelta; + + /** + * Decodes a BindingDelta message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns BindingDelta + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.BindingDelta; + + /** + * Verifies a BindingDelta message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a BindingDelta message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BindingDelta + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.BindingDelta; + + /** + * Creates a plain object from a BindingDelta message. Also converts values to other types if specified. + * @param message BindingDelta + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.BindingDelta, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BindingDelta to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace BindingDelta { + + /** Action enum. */ + enum Action { + ACTION_UNSPECIFIED = 0, + ADD = 1, + REMOVE = 2 + } + } + + /** Properties of an AuditConfigDelta. */ + interface IAuditConfigDelta { + + /** AuditConfigDelta action */ + action?: (google.iam.v1.AuditConfigDelta.Action|null); + + /** AuditConfigDelta service */ + service?: (string|null); + + /** AuditConfigDelta exemptedMember */ + exemptedMember?: (string|null); + + /** AuditConfigDelta logType */ + logType?: (string|null); + } + + /** Represents an AuditConfigDelta. */ + class AuditConfigDelta implements IAuditConfigDelta { + + /** + * Constructs a new AuditConfigDelta. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.IAuditConfigDelta); + + /** AuditConfigDelta action. */ + public action: google.iam.v1.AuditConfigDelta.Action; + + /** AuditConfigDelta service. */ + public service: string; + + /** AuditConfigDelta exemptedMember. */ + public exemptedMember: string; + + /** AuditConfigDelta logType. */ + public logType: string; + + /** + * Creates a new AuditConfigDelta instance using the specified properties. + * @param [properties] Properties to set + * @returns AuditConfigDelta instance + */ + public static create(properties?: google.iam.v1.IAuditConfigDelta): google.iam.v1.AuditConfigDelta; + + /** + * Encodes the specified AuditConfigDelta message. Does not implicitly {@link google.iam.v1.AuditConfigDelta.verify|verify} messages. + * @param message AuditConfigDelta message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.IAuditConfigDelta, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AuditConfigDelta message, length delimited. Does not implicitly {@link google.iam.v1.AuditConfigDelta.verify|verify} messages. + * @param message AuditConfigDelta message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.IAuditConfigDelta, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AuditConfigDelta message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AuditConfigDelta + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.AuditConfigDelta; + + /** + * Decodes an AuditConfigDelta message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AuditConfigDelta + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.AuditConfigDelta; + + /** + * Verifies an AuditConfigDelta message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AuditConfigDelta message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AuditConfigDelta + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.AuditConfigDelta; + + /** + * Creates a plain object from an AuditConfigDelta message. Also converts values to other types if specified. + * @param message AuditConfigDelta + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.AuditConfigDelta, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AuditConfigDelta to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace AuditConfigDelta { + + /** Action enum. */ + enum Action { + ACTION_UNSPECIFIED = 0, + ADD = 1, + REMOVE = 2 + } + } + + /** Namespace logging. */ + namespace logging { + + /** Properties of an AuditData. */ + interface IAuditData { + + /** AuditData policyDelta */ + policyDelta?: (google.iam.v1.IPolicyDelta|null); + } + + /** Represents an AuditData. */ + class AuditData implements IAuditData { + + /** + * Constructs a new AuditData. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.logging.IAuditData); + + /** AuditData policyDelta. */ + public policyDelta?: (google.iam.v1.IPolicyDelta|null); + + /** + * Creates a new AuditData instance using the specified properties. + * @param [properties] Properties to set + * @returns AuditData instance + */ + public static create(properties?: google.iam.v1.logging.IAuditData): google.iam.v1.logging.AuditData; + + /** + * Encodes the specified AuditData message. Does not implicitly {@link google.iam.v1.logging.AuditData.verify|verify} messages. + * @param message AuditData message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.logging.IAuditData, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AuditData message, length delimited. Does not implicitly {@link google.iam.v1.logging.AuditData.verify|verify} messages. + * @param message AuditData message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.logging.IAuditData, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AuditData message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AuditData + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.logging.AuditData; + + /** + * Decodes an AuditData message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AuditData + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.logging.AuditData; + + /** + * Verifies an AuditData message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AuditData message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AuditData + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.logging.AuditData; + + /** + * Creates a plain object from an AuditData message. Also converts values to other types if specified. + * @param message AuditData + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.logging.AuditData, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AuditData to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + } + } + + /** Namespace api. */ + namespace api { + + /** Properties of a Http. */ + interface IHttp { + + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); + + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); + } + + /** Represents a Http. */ + class Http implements IHttp { + + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); + + /** Http rules. */ + public rules: google.api.IHttpRule[]; + + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; + + /** + * Creates a new Http instance using the specified properties. + * @param [properties] Properties to set + * @returns Http instance + */ + public static create(properties?: google.api.IHttp): google.api.Http; + + /** + * Encodes the specified Http message. Does not implicitly {@link google.api.Http.verify|verify} messages. + * @param message Http message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Http message, length delimited. Does not implicitly {@link google.api.Http.verify|verify} messages. + * @param message Http message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Http message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Http + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Http; + + /** + * Decodes a Http message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Http + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Http; + + /** + * Verifies a Http message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a HttpRule. */ + interface IHttpRule { + + /** HttpRule selector */ + selector?: (string|null); + + /** HttpRule get */ + get?: (string|null); + + /** HttpRule put */ + put?: (string|null); + + /** HttpRule post */ + post?: (string|null); + + /** HttpRule delete */ + "delete"?: (string|null); + + /** HttpRule patch */ + patch?: (string|null); + + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body */ + body?: (string|null); + + /** HttpRule responseBody */ + responseBody?: (string|null); + + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); + } + + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { + + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); + + /** HttpRule selector. */ + public selector: string; + + /** HttpRule get. */ + public get: string; + + /** HttpRule put. */ + public put: string; + + /** HttpRule post. */ + public post: string; + + /** HttpRule delete. */ + public delete: string; + + /** HttpRule patch. */ + public patch: string; + + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body. */ + public body: string; + + /** HttpRule responseBody. */ + public responseBody: string; + + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; + + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + + /** + * Creates a new HttpRule instance using the specified properties. + * @param [properties] Properties to set + * @returns HttpRule instance + */ + public static create(properties?: google.api.IHttpRule): google.api.HttpRule; + + /** + * Encodes the specified HttpRule message. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. + * @param message HttpRule message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified HttpRule message, length delimited. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. + * @param message HttpRule message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a HttpRule message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns HttpRule + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.HttpRule; + + /** + * Decodes a HttpRule message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns HttpRule + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.HttpRule; + + /** + * Verifies a HttpRule message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { + + /** CustomHttpPattern kind */ + kind?: (string|null); + + /** CustomHttpPattern path */ + path?: (string|null); + } + + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { + + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); + + /** CustomHttpPattern kind. */ + public kind: string; + + /** CustomHttpPattern path. */ + public path: string; + + /** + * Creates a new CustomHttpPattern instance using the specified properties. + * @param [properties] Properties to set + * @returns CustomHttpPattern instance + */ + public static create(properties?: google.api.ICustomHttpPattern): google.api.CustomHttpPattern; + + /** + * Encodes the specified CustomHttpPattern message. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. + * @param message CustomHttpPattern message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CustomHttpPattern message, length delimited. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. + * @param message CustomHttpPattern message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CustomHttpPattern message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CustomHttpPattern + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.CustomHttpPattern; + + /** + * Decodes a CustomHttpPattern message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CustomHttpPattern + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.CustomHttpPattern; + + /** + * Verifies a CustomHttpPattern message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** FieldBehavior enum. */ + enum FieldBehavior { + FIELD_BEHAVIOR_UNSPECIFIED = 0, + OPTIONAL = 1, + REQUIRED = 2, + OUTPUT_ONLY = 3, + INPUT_ONLY = 4, + IMMUTABLE = 5 + } + + /** Properties of a ResourceDescriptor. */ + interface IResourceDescriptor { + + /** ResourceDescriptor type */ + type?: (string|null); + + /** ResourceDescriptor pattern */ + pattern?: (string[]|null); + + /** ResourceDescriptor nameField */ + nameField?: (string|null); + + /** ResourceDescriptor history */ + history?: (google.api.ResourceDescriptor.History|null); + + /** ResourceDescriptor plural */ + plural?: (string|null); + + /** ResourceDescriptor singular */ + singular?: (string|null); + } + + /** Represents a ResourceDescriptor. */ + class ResourceDescriptor implements IResourceDescriptor { + + /** + * Constructs a new ResourceDescriptor. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceDescriptor); + + /** ResourceDescriptor type. */ + public type: string; + + /** ResourceDescriptor pattern. */ + public pattern: string[]; + + /** ResourceDescriptor nameField. */ + public nameField: string; + + /** ResourceDescriptor history. */ + public history: google.api.ResourceDescriptor.History; + + /** ResourceDescriptor plural. */ + public plural: string; + + /** ResourceDescriptor singular. */ + public singular: string; + + /** + * Creates a new ResourceDescriptor instance using the specified properties. + * @param [properties] Properties to set + * @returns ResourceDescriptor instance + */ + public static create(properties?: google.api.IResourceDescriptor): google.api.ResourceDescriptor; + + /** + * Encodes the specified ResourceDescriptor message. Does not implicitly {@link google.api.ResourceDescriptor.verify|verify} messages. + * @param message ResourceDescriptor message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IResourceDescriptor, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ResourceDescriptor message, length delimited. Does not implicitly {@link google.api.ResourceDescriptor.verify|verify} messages. + * @param message ResourceDescriptor message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IResourceDescriptor, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ResourceDescriptor message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ResourceDescriptor + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.ResourceDescriptor; + + /** + * Decodes a ResourceDescriptor message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ResourceDescriptor + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.ResourceDescriptor; + + /** + * Verifies a ResourceDescriptor message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceDescriptor + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @param message ResourceDescriptor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceDescriptor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace ResourceDescriptor { + + /** History enum. */ + enum History { + HISTORY_UNSPECIFIED = 0, + ORIGINALLY_SINGLE_PATTERN = 1, + FUTURE_MULTI_PATTERN = 2 + } + } + + /** Properties of a ResourceReference. */ + interface IResourceReference { + + /** ResourceReference type */ + type?: (string|null); + + /** ResourceReference childType */ + childType?: (string|null); + } + + /** Represents a ResourceReference. */ + class ResourceReference implements IResourceReference { + + /** + * Constructs a new ResourceReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceReference); + + /** ResourceReference type. */ + public type: string; + + /** ResourceReference childType. */ + public childType: string; + + /** + * Creates a new ResourceReference instance using the specified properties. + * @param [properties] Properties to set + * @returns ResourceReference instance + */ + public static create(properties?: google.api.IResourceReference): google.api.ResourceReference; + + /** + * Encodes the specified ResourceReference message. Does not implicitly {@link google.api.ResourceReference.verify|verify} messages. + * @param message ResourceReference message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IResourceReference, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ResourceReference message, length delimited. Does not implicitly {@link google.api.ResourceReference.verify|verify} messages. + * @param message ResourceReference message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IResourceReference, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ResourceReference message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ResourceReference + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.ResourceReference; + + /** + * Decodes a ResourceReference message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ResourceReference + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.ResourceReference; + + /** + * Verifies a ResourceReference message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceReference + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; + + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @param message ResourceReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Namespace protobuf. */ + namespace protobuf { + + /** Properties of a FileDescriptorSet. */ + interface IFileDescriptorSet { + + /** FileDescriptorSet file */ + file?: (google.protobuf.IFileDescriptorProto[]|null); + } + + /** Represents a FileDescriptorSet. */ + class FileDescriptorSet implements IFileDescriptorSet { + + /** + * Constructs a new FileDescriptorSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorSet); + + /** FileDescriptorSet file. */ + public file: google.protobuf.IFileDescriptorProto[]; + + /** + * Creates a new FileDescriptorSet instance using the specified properties. + * @param [properties] Properties to set + * @returns FileDescriptorSet instance + */ + public static create(properties?: google.protobuf.IFileDescriptorSet): google.protobuf.FileDescriptorSet; + + /** + * Encodes the specified FileDescriptorSet message. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. + * @param message FileDescriptorSet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FileDescriptorSet message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. + * @param message FileDescriptorSet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FileDescriptorSet message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FileDescriptorSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorSet; + + /** + * Decodes a FileDescriptorSet message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FileDescriptorSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorSet; + + /** + * Verifies a FileDescriptorSet message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; + + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @param message FileDescriptorSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a FileDescriptorProto. */ + interface IFileDescriptorProto { + + /** FileDescriptorProto name */ + name?: (string|null); + + /** FileDescriptorProto package */ + "package"?: (string|null); + + /** FileDescriptorProto dependency */ + dependency?: (string[]|null); + + /** FileDescriptorProto publicDependency */ + publicDependency?: (number[]|null); + + /** FileDescriptorProto weakDependency */ + weakDependency?: (number[]|null); + + /** FileDescriptorProto messageType */ + messageType?: (google.protobuf.IDescriptorProto[]|null); + + /** FileDescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** FileDescriptorProto service */ + service?: (google.protobuf.IServiceDescriptorProto[]|null); + + /** FileDescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** FileDescriptorProto options */ + options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo */ + sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax */ + syntax?: (string|null); + } + + /** Represents a FileDescriptorProto. */ + class FileDescriptorProto implements IFileDescriptorProto { + + /** + * Constructs a new FileDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorProto); + + /** FileDescriptorProto name. */ + public name: string; + + /** FileDescriptorProto package. */ + public package: string; + + /** FileDescriptorProto dependency. */ + public dependency: string[]; + + /** FileDescriptorProto publicDependency. */ + public publicDependency: number[]; + + /** FileDescriptorProto weakDependency. */ + public weakDependency: number[]; + + /** FileDescriptorProto messageType. */ + public messageType: google.protobuf.IDescriptorProto[]; + + /** FileDescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** FileDescriptorProto service. */ + public service: google.protobuf.IServiceDescriptorProto[]; + + /** FileDescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** FileDescriptorProto options. */ + public options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo. */ + public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax. */ + public syntax: string; + + /** + * Creates a new FileDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns FileDescriptorProto instance + */ + public static create(properties?: google.protobuf.IFileDescriptorProto): google.protobuf.FileDescriptorProto; + + /** + * Encodes the specified FileDescriptorProto message. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. + * @param message FileDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FileDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. + * @param message FileDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FileDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FileDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorProto; + + /** + * Decodes a FileDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FileDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorProto; + + /** + * Verifies a FileDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; + + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @param message FileDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a DescriptorProto. */ + interface IDescriptorProto { + + /** DescriptorProto name */ + name?: (string|null); + + /** DescriptorProto field */ + field?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto nestedType */ + nestedType?: (google.protobuf.IDescriptorProto[]|null); + + /** DescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** DescriptorProto extensionRange */ + extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); + + /** DescriptorProto oneofDecl */ + oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); + + /** DescriptorProto options */ + options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange */ + reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); + + /** DescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents a DescriptorProto. */ + class DescriptorProto implements IDescriptorProto { + + /** + * Constructs a new DescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDescriptorProto); + + /** DescriptorProto name. */ + public name: string; + + /** DescriptorProto field. */ + public field: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto nestedType. */ + public nestedType: google.protobuf.IDescriptorProto[]; + + /** DescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** DescriptorProto extensionRange. */ + public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; + + /** DescriptorProto oneofDecl. */ + public oneofDecl: google.protobuf.IOneofDescriptorProto[]; + + /** DescriptorProto options. */ + public options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange. */ + public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; + + /** DescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates a new DescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns DescriptorProto instance + */ + public static create(properties?: google.protobuf.IDescriptorProto): google.protobuf.DescriptorProto; + + /** + * Encodes the specified DescriptorProto message. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. + * @param message DescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. + * @param message DescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto; + + /** + * Decodes a DescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto; + + /** + * Verifies a DescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; + + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @param message DescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace DescriptorProto { + + /** Properties of an ExtensionRange. */ + interface IExtensionRange { + + /** ExtensionRange start */ + start?: (number|null); + + /** ExtensionRange end */ + end?: (number|null); + + /** ExtensionRange options */ + options?: (google.protobuf.IExtensionRangeOptions|null); + } + + /** Represents an ExtensionRange. */ + class ExtensionRange implements IExtensionRange { + + /** + * Constructs a new ExtensionRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); + + /** ExtensionRange start. */ + public start: number; + + /** ExtensionRange end. */ + public end: number; + + /** ExtensionRange options. */ + public options?: (google.protobuf.IExtensionRangeOptions|null); + + /** + * Creates a new ExtensionRange instance using the specified properties. + * @param [properties] Properties to set + * @returns ExtensionRange instance + */ + public static create(properties?: google.protobuf.DescriptorProto.IExtensionRange): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Encodes the specified ExtensionRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. + * @param message ExtensionRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExtensionRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. + * @param message ExtensionRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExtensionRange message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExtensionRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Decodes an ExtensionRange message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExtensionRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Verifies an ExtensionRange message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @param message ExtensionRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a ReservedRange. */ + interface IReservedRange { + + /** ReservedRange start */ + start?: (number|null); + + /** ReservedRange end */ + end?: (number|null); + } + + /** Represents a ReservedRange. */ + class ReservedRange implements IReservedRange { + + /** + * Constructs a new ReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); + + /** ReservedRange start. */ + public start: number; + + /** ReservedRange end. */ + public end: number; + + /** + * Creates a new ReservedRange instance using the specified properties. + * @param [properties] Properties to set + * @returns ReservedRange instance + */ + public static create(properties?: google.protobuf.DescriptorProto.IReservedRange): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Encodes the specified ReservedRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. + * @param message ReservedRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReservedRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. + * @param message ReservedRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReservedRange message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Decodes a ReservedRange message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Verifies a ReservedRange message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @param message ReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Properties of an ExtensionRangeOptions. */ + interface IExtensionRangeOptions { + + /** ExtensionRangeOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an ExtensionRangeOptions. */ + class ExtensionRangeOptions implements IExtensionRangeOptions { + + /** + * Constructs a new ExtensionRangeOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IExtensionRangeOptions); + + /** ExtensionRangeOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new ExtensionRangeOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns ExtensionRangeOptions instance + */ + public static create(properties?: google.protobuf.IExtensionRangeOptions): google.protobuf.ExtensionRangeOptions; + + /** + * Encodes the specified ExtensionRangeOptions message. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages. + * @param message ExtensionRangeOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IExtensionRangeOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExtensionRangeOptions message, length delimited. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages. + * @param message ExtensionRangeOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IExtensionRangeOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExtensionRangeOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExtensionRangeOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ExtensionRangeOptions; + + /** + * Decodes an ExtensionRangeOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExtensionRangeOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ExtensionRangeOptions; + + /** + * Verifies an ExtensionRangeOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRangeOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @param message ExtensionRangeOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a FieldDescriptorProto. */ + interface IFieldDescriptorProto { + + /** FieldDescriptorProto name */ + name?: (string|null); + + /** FieldDescriptorProto number */ + number?: (number|null); + + /** FieldDescriptorProto label */ + label?: (google.protobuf.FieldDescriptorProto.Label|null); + + /** FieldDescriptorProto type */ + type?: (google.protobuf.FieldDescriptorProto.Type|null); + + /** FieldDescriptorProto typeName */ + typeName?: (string|null); + + /** FieldDescriptorProto extendee */ + extendee?: (string|null); + + /** FieldDescriptorProto defaultValue */ + defaultValue?: (string|null); + + /** FieldDescriptorProto oneofIndex */ + oneofIndex?: (number|null); + + /** FieldDescriptorProto jsonName */ + jsonName?: (string|null); + + /** FieldDescriptorProto options */ + options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional */ + proto3Optional?: (boolean|null); + } + + /** Represents a FieldDescriptorProto. */ + class FieldDescriptorProto implements IFieldDescriptorProto { + + /** + * Constructs a new FieldDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldDescriptorProto); + + /** FieldDescriptorProto name. */ + public name: string; + + /** FieldDescriptorProto number. */ + public number: number; + + /** FieldDescriptorProto label. */ + public label: google.protobuf.FieldDescriptorProto.Label; + + /** FieldDescriptorProto type. */ + public type: google.protobuf.FieldDescriptorProto.Type; + + /** FieldDescriptorProto typeName. */ + public typeName: string; + + /** FieldDescriptorProto extendee. */ + public extendee: string; + + /** FieldDescriptorProto defaultValue. */ + public defaultValue: string; + + /** FieldDescriptorProto oneofIndex. */ + public oneofIndex: number; + + /** FieldDescriptorProto jsonName. */ + public jsonName: string; + + /** FieldDescriptorProto options. */ + public options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional. */ + public proto3Optional: boolean; + + /** + * Creates a new FieldDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns FieldDescriptorProto instance + */ + public static create(properties?: google.protobuf.IFieldDescriptorProto): google.protobuf.FieldDescriptorProto; + + /** + * Encodes the specified FieldDescriptorProto message. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. + * @param message FieldDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FieldDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. + * @param message FieldDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FieldDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FieldDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldDescriptorProto; + + /** + * Decodes a FieldDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FieldDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldDescriptorProto; + + /** + * Verifies a FieldDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @param message FieldDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace FieldDescriptorProto { + + /** Type enum. */ + enum Type { + TYPE_DOUBLE = 1, + TYPE_FLOAT = 2, + TYPE_INT64 = 3, + TYPE_UINT64 = 4, + TYPE_INT32 = 5, + TYPE_FIXED64 = 6, + TYPE_FIXED32 = 7, + TYPE_BOOL = 8, + TYPE_STRING = 9, + TYPE_GROUP = 10, + TYPE_MESSAGE = 11, + TYPE_BYTES = 12, + TYPE_UINT32 = 13, + TYPE_ENUM = 14, + TYPE_SFIXED32 = 15, + TYPE_SFIXED64 = 16, + TYPE_SINT32 = 17, + TYPE_SINT64 = 18 + } + + /** Label enum. */ + enum Label { + LABEL_OPTIONAL = 1, + LABEL_REQUIRED = 2, + LABEL_REPEATED = 3 + } + } + + /** Properties of an OneofDescriptorProto. */ + interface IOneofDescriptorProto { + + /** OneofDescriptorProto name */ + name?: (string|null); + + /** OneofDescriptorProto options */ + options?: (google.protobuf.IOneofOptions|null); + } + + /** Represents an OneofDescriptorProto. */ + class OneofDescriptorProto implements IOneofDescriptorProto { + + /** + * Constructs a new OneofDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofDescriptorProto); + + /** OneofDescriptorProto name. */ + public name: string; + + /** OneofDescriptorProto options. */ + public options?: (google.protobuf.IOneofOptions|null); + + /** + * Creates a new OneofDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns OneofDescriptorProto instance + */ + public static create(properties?: google.protobuf.IOneofDescriptorProto): google.protobuf.OneofDescriptorProto; + + /** + * Encodes the specified OneofDescriptorProto message. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. + * @param message OneofDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified OneofDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. + * @param message OneofDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an OneofDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns OneofDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofDescriptorProto; + + /** + * Decodes an OneofDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns OneofDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofDescriptorProto; + + /** + * Verifies an OneofDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; + + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @param message OneofDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of an EnumDescriptorProto. */ + interface IEnumDescriptorProto { + + /** EnumDescriptorProto name */ + name?: (string|null); + + /** EnumDescriptorProto value */ + value?: (google.protobuf.IEnumValueDescriptorProto[]|null); + + /** EnumDescriptorProto options */ + options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange */ + reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); + + /** EnumDescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents an EnumDescriptorProto. */ + class EnumDescriptorProto implements IEnumDescriptorProto { + + /** + * Constructs a new EnumDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumDescriptorProto); + + /** EnumDescriptorProto name. */ + public name: string; + + /** EnumDescriptorProto value. */ + public value: google.protobuf.IEnumValueDescriptorProto[]; + + /** EnumDescriptorProto options. */ + public options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange. */ + public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; + + /** EnumDescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates a new EnumDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumDescriptorProto instance + */ + public static create(properties?: google.protobuf.IEnumDescriptorProto): google.protobuf.EnumDescriptorProto; + + /** + * Encodes the specified EnumDescriptorProto message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. + * @param message EnumDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. + * @param message EnumDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto; + + /** + * Decodes an EnumDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto; + + /** + * Verifies an EnumDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; + + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @param message EnumDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace EnumDescriptorProto { + + /** Properties of an EnumReservedRange. */ + interface IEnumReservedRange { + + /** EnumReservedRange start */ + start?: (number|null); + + /** EnumReservedRange end */ + end?: (number|null); + } + + /** Represents an EnumReservedRange. */ + class EnumReservedRange implements IEnumReservedRange { + + /** + * Constructs a new EnumReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); + + /** EnumReservedRange start. */ + public start: number; + + /** EnumReservedRange end. */ + public end: number; + + /** + * Creates a new EnumReservedRange instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumReservedRange instance + */ + public static create(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Encodes the specified EnumReservedRange message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages. + * @param message EnumReservedRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.EnumDescriptorProto.IEnumReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumReservedRange message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages. + * @param message EnumReservedRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.EnumDescriptorProto.IEnumReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumReservedRange message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Decodes an EnumReservedRange message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Verifies an EnumReservedRange message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @param message EnumReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Properties of an EnumValueDescriptorProto. */ + interface IEnumValueDescriptorProto { + + /** EnumValueDescriptorProto name */ + name?: (string|null); + + /** EnumValueDescriptorProto number */ + number?: (number|null); + + /** EnumValueDescriptorProto options */ + options?: (google.protobuf.IEnumValueOptions|null); + } + + /** Represents an EnumValueDescriptorProto. */ + class EnumValueDescriptorProto implements IEnumValueDescriptorProto { + + /** + * Constructs a new EnumValueDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueDescriptorProto); + + /** EnumValueDescriptorProto name. */ + public name: string; + + /** EnumValueDescriptorProto number. */ + public number: number; + + /** EnumValueDescriptorProto options. */ + public options?: (google.protobuf.IEnumValueOptions|null); + + /** + * Creates a new EnumValueDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumValueDescriptorProto instance + */ + public static create(properties?: google.protobuf.IEnumValueDescriptorProto): google.protobuf.EnumValueDescriptorProto; + + /** + * Encodes the specified EnumValueDescriptorProto message. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. + * @param message EnumValueDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumValueDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. + * @param message EnumValueDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumValueDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumValueDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueDescriptorProto; + + /** + * Decodes an EnumValueDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumValueDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueDescriptorProto; + + /** + * Verifies an EnumValueDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; + + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @param message EnumValueDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a ServiceDescriptorProto. */ + interface IServiceDescriptorProto { + + /** ServiceDescriptorProto name */ + name?: (string|null); + + /** ServiceDescriptorProto method */ + method?: (google.protobuf.IMethodDescriptorProto[]|null); + + /** ServiceDescriptorProto options */ + options?: (google.protobuf.IServiceOptions|null); + } + + /** Represents a ServiceDescriptorProto. */ + class ServiceDescriptorProto implements IServiceDescriptorProto { + + /** + * Constructs a new ServiceDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceDescriptorProto); + + /** ServiceDescriptorProto name. */ + public name: string; + + /** ServiceDescriptorProto method. */ + public method: google.protobuf.IMethodDescriptorProto[]; + + /** ServiceDescriptorProto options. */ + public options?: (google.protobuf.IServiceOptions|null); + + /** + * Creates a new ServiceDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns ServiceDescriptorProto instance + */ + public static create(properties?: google.protobuf.IServiceDescriptorProto): google.protobuf.ServiceDescriptorProto; + + /** + * Encodes the specified ServiceDescriptorProto message. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. + * @param message ServiceDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ServiceDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. + * @param message ServiceDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ServiceDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ServiceDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceDescriptorProto; + + /** + * Decodes a ServiceDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ServiceDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceDescriptorProto; + + /** + * Verifies a ServiceDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @param message ServiceDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a MethodDescriptorProto. */ + interface IMethodDescriptorProto { + + /** MethodDescriptorProto name */ + name?: (string|null); + + /** MethodDescriptorProto inputType */ + inputType?: (string|null); + + /** MethodDescriptorProto outputType */ + outputType?: (string|null); + + /** MethodDescriptorProto options */ + options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming */ + clientStreaming?: (boolean|null); + + /** MethodDescriptorProto serverStreaming */ + serverStreaming?: (boolean|null); + } + + /** Represents a MethodDescriptorProto. */ + class MethodDescriptorProto implements IMethodDescriptorProto { + + /** + * Constructs a new MethodDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodDescriptorProto); + + /** MethodDescriptorProto name. */ + public name: string; + + /** MethodDescriptorProto inputType. */ + public inputType: string; + + /** MethodDescriptorProto outputType. */ + public outputType: string; + + /** MethodDescriptorProto options. */ + public options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming. */ + public clientStreaming: boolean; + + /** MethodDescriptorProto serverStreaming. */ + public serverStreaming: boolean; + + /** + * Creates a new MethodDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns MethodDescriptorProto instance + */ + public static create(properties?: google.protobuf.IMethodDescriptorProto): google.protobuf.MethodDescriptorProto; + + /** + * Encodes the specified MethodDescriptorProto message. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. + * @param message MethodDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MethodDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. + * @param message MethodDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MethodDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MethodDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodDescriptorProto; + + /** + * Decodes a MethodDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MethodDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodDescriptorProto; + + /** + * Verifies a MethodDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @param message MethodDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a FileOptions. */ + interface IFileOptions { + + /** FileOptions javaPackage */ + javaPackage?: (string|null); + + /** FileOptions javaOuterClassname */ + javaOuterClassname?: (string|null); + + /** FileOptions javaMultipleFiles */ + javaMultipleFiles?: (boolean|null); + + /** FileOptions javaGenerateEqualsAndHash */ + javaGenerateEqualsAndHash?: (boolean|null); + + /** FileOptions javaStringCheckUtf8 */ + javaStringCheckUtf8?: (boolean|null); + + /** FileOptions optimizeFor */ + optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); + + /** FileOptions goPackage */ + goPackage?: (string|null); + + /** FileOptions ccGenericServices */ + ccGenericServices?: (boolean|null); + + /** FileOptions javaGenericServices */ + javaGenericServices?: (boolean|null); + + /** FileOptions pyGenericServices */ + pyGenericServices?: (boolean|null); + + /** FileOptions phpGenericServices */ + phpGenericServices?: (boolean|null); + + /** FileOptions deprecated */ + deprecated?: (boolean|null); + + /** FileOptions ccEnableArenas */ + ccEnableArenas?: (boolean|null); + + /** FileOptions objcClassPrefix */ + objcClassPrefix?: (string|null); + + /** FileOptions csharpNamespace */ + csharpNamespace?: (string|null); + + /** FileOptions swiftPrefix */ + swiftPrefix?: (string|null); + + /** FileOptions phpClassPrefix */ + phpClassPrefix?: (string|null); + + /** FileOptions phpNamespace */ + phpNamespace?: (string|null); + + /** FileOptions phpMetadataNamespace */ + phpMetadataNamespace?: (string|null); + + /** FileOptions rubyPackage */ + rubyPackage?: (string|null); + + /** FileOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FileOptions .google.api.resourceDefinition */ + ".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null); + } + + /** Represents a FileOptions. */ + class FileOptions implements IFileOptions { + + /** + * Constructs a new FileOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileOptions); + + /** FileOptions javaPackage. */ + public javaPackage: string; + + /** FileOptions javaOuterClassname. */ + public javaOuterClassname: string; + + /** FileOptions javaMultipleFiles. */ + public javaMultipleFiles: boolean; + + /** FileOptions javaGenerateEqualsAndHash. */ + public javaGenerateEqualsAndHash: boolean; + + /** FileOptions javaStringCheckUtf8. */ + public javaStringCheckUtf8: boolean; + + /** FileOptions optimizeFor. */ + public optimizeFor: google.protobuf.FileOptions.OptimizeMode; + + /** FileOptions goPackage. */ + public goPackage: string; + + /** FileOptions ccGenericServices. */ + public ccGenericServices: boolean; + + /** FileOptions javaGenericServices. */ + public javaGenericServices: boolean; + + /** FileOptions pyGenericServices. */ + public pyGenericServices: boolean; + + /** FileOptions phpGenericServices. */ + public phpGenericServices: boolean; + + /** FileOptions deprecated. */ + public deprecated: boolean; + + /** FileOptions ccEnableArenas. */ + public ccEnableArenas: boolean; + + /** FileOptions objcClassPrefix. */ + public objcClassPrefix: string; + + /** FileOptions csharpNamespace. */ + public csharpNamespace: string; + + /** FileOptions swiftPrefix. */ + public swiftPrefix: string; + + /** FileOptions phpClassPrefix. */ + public phpClassPrefix: string; + + /** FileOptions phpNamespace. */ + public phpNamespace: string; + + /** FileOptions phpMetadataNamespace. */ + public phpMetadataNamespace: string; + + /** FileOptions rubyPackage. */ + public rubyPackage: string; + + /** FileOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new FileOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns FileOptions instance + */ + public static create(properties?: google.protobuf.IFileOptions): google.protobuf.FileOptions; + + /** + * Encodes the specified FileOptions message. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. + * @param message FileOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FileOptions message, length delimited. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. + * @param message FileOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FileOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FileOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileOptions; + + /** + * Decodes a FileOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FileOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileOptions; + + /** + * Verifies a FileOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; + + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @param message FileOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace FileOptions { + + /** OptimizeMode enum. */ + enum OptimizeMode { + SPEED = 1, + CODE_SIZE = 2, + LITE_RUNTIME = 3 + } + } + + /** Properties of a MessageOptions. */ + interface IMessageOptions { + + /** MessageOptions messageSetWireFormat */ + messageSetWireFormat?: (boolean|null); + + /** MessageOptions noStandardDescriptorAccessor */ + noStandardDescriptorAccessor?: (boolean|null); + + /** MessageOptions deprecated */ + deprecated?: (boolean|null); + + /** MessageOptions mapEntry */ + mapEntry?: (boolean|null); + + /** MessageOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MessageOptions .google.api.resource */ + ".google.api.resource"?: (google.api.IResourceDescriptor|null); + } + + /** Represents a MessageOptions. */ + class MessageOptions implements IMessageOptions { + + /** + * Constructs a new MessageOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMessageOptions); + + /** MessageOptions messageSetWireFormat. */ + public messageSetWireFormat: boolean; + + /** MessageOptions noStandardDescriptorAccessor. */ + public noStandardDescriptorAccessor: boolean; + + /** MessageOptions deprecated. */ + public deprecated: boolean; + + /** MessageOptions mapEntry. */ + public mapEntry: boolean; + + /** MessageOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new MessageOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns MessageOptions instance + */ + public static create(properties?: google.protobuf.IMessageOptions): google.protobuf.MessageOptions; + + /** + * Encodes the specified MessageOptions message. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. + * @param message MessageOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MessageOptions message, length delimited. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. + * @param message MessageOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MessageOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MessageOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MessageOptions; + + /** + * Decodes a MessageOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MessageOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MessageOptions; + + /** + * Verifies a MessageOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MessageOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; + + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @param message MessageOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MessageOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a FieldOptions. */ + interface IFieldOptions { + + /** FieldOptions ctype */ + ctype?: (google.protobuf.FieldOptions.CType|null); + + /** FieldOptions packed */ + packed?: (boolean|null); + + /** FieldOptions jstype */ + jstype?: (google.protobuf.FieldOptions.JSType|null); + + /** FieldOptions lazy */ + lazy?: (boolean|null); + + /** FieldOptions deprecated */ + deprecated?: (boolean|null); + + /** FieldOptions weak */ + weak?: (boolean|null); + + /** FieldOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FieldOptions .google.api.fieldBehavior */ + ".google.api.fieldBehavior"?: (google.api.FieldBehavior[]|null); + + /** FieldOptions .google.api.resourceReference */ + ".google.api.resourceReference"?: (google.api.IResourceReference|null); + } + + /** Represents a FieldOptions. */ + class FieldOptions implements IFieldOptions { + + /** + * Constructs a new FieldOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldOptions); + + /** FieldOptions ctype. */ + public ctype: google.protobuf.FieldOptions.CType; + + /** FieldOptions packed. */ + public packed: boolean; + + /** FieldOptions jstype. */ + public jstype: google.protobuf.FieldOptions.JSType; + + /** FieldOptions lazy. */ + public lazy: boolean; + + /** FieldOptions deprecated. */ + public deprecated: boolean; + + /** FieldOptions weak. */ + public weak: boolean; + + /** FieldOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new FieldOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns FieldOptions instance + */ + public static create(properties?: google.protobuf.IFieldOptions): google.protobuf.FieldOptions; + + /** + * Encodes the specified FieldOptions message. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. + * @param message FieldOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FieldOptions message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. + * @param message FieldOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FieldOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FieldOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions; + + /** + * Decodes a FieldOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FieldOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions; + + /** + * Verifies a FieldOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; + + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @param message FieldOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace FieldOptions { + + /** CType enum. */ + enum CType { + STRING = 0, + CORD = 1, + STRING_PIECE = 2 + } + + /** JSType enum. */ + enum JSType { + JS_NORMAL = 0, + JS_STRING = 1, + JS_NUMBER = 2 + } + } + + /** Properties of an OneofOptions. */ + interface IOneofOptions { + + /** OneofOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an OneofOptions. */ + class OneofOptions implements IOneofOptions { + + /** + * Constructs a new OneofOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofOptions); + + /** OneofOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new OneofOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns OneofOptions instance + */ + public static create(properties?: google.protobuf.IOneofOptions): google.protobuf.OneofOptions; + + /** + * Encodes the specified OneofOptions message. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. + * @param message OneofOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified OneofOptions message, length delimited. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. + * @param message OneofOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an OneofOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns OneofOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofOptions; + + /** + * Decodes an OneofOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns OneofOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofOptions; + + /** + * Verifies an OneofOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @param message OneofOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of an EnumOptions. */ + interface IEnumOptions { + + /** EnumOptions allowAlias */ + allowAlias?: (boolean|null); + + /** EnumOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumOptions. */ + class EnumOptions implements IEnumOptions { + + /** + * Constructs a new EnumOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumOptions); + + /** EnumOptions allowAlias. */ + public allowAlias: boolean; + + /** EnumOptions deprecated. */ + public deprecated: boolean; + + /** EnumOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new EnumOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumOptions instance + */ + public static create(properties?: google.protobuf.IEnumOptions): google.protobuf.EnumOptions; + + /** + * Encodes the specified EnumOptions message. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. + * @param message EnumOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. + * @param message EnumOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumOptions; + + /** + * Decodes an EnumOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumOptions; + + /** + * Verifies an EnumOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @param message EnumOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of an EnumValueOptions. */ + interface IEnumValueOptions { + + /** EnumValueOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumValueOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumValueOptions. */ + class EnumValueOptions implements IEnumValueOptions { + + /** + * Constructs a new EnumValueOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueOptions); + + /** EnumValueOptions deprecated. */ + public deprecated: boolean; + + /** EnumValueOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new EnumValueOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumValueOptions instance + */ + public static create(properties?: google.protobuf.IEnumValueOptions): google.protobuf.EnumValueOptions; + + /** + * Encodes the specified EnumValueOptions message. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. + * @param message EnumValueOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumValueOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. + * @param message EnumValueOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumValueOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumValueOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueOptions; + + /** + * Decodes an EnumValueOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumValueOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueOptions; + + /** + * Verifies an EnumValueOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; + + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @param message EnumValueOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a ServiceOptions. */ + interface IServiceOptions { + + /** ServiceOptions deprecated */ + deprecated?: (boolean|null); + + /** ServiceOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ServiceOptions .google.api.defaultHost */ + ".google.api.defaultHost"?: (string|null); + + /** ServiceOptions .google.api.oauthScopes */ + ".google.api.oauthScopes"?: (string|null); + } + + /** Represents a ServiceOptions. */ + class ServiceOptions implements IServiceOptions { + + /** + * Constructs a new ServiceOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceOptions); + + /** ServiceOptions deprecated. */ + public deprecated: boolean; + + /** ServiceOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new ServiceOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns ServiceOptions instance + */ + public static create(properties?: google.protobuf.IServiceOptions): google.protobuf.ServiceOptions; + + /** + * Encodes the specified ServiceOptions message. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. + * @param message ServiceOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ServiceOptions message, length delimited. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. + * @param message ServiceOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ServiceOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ServiceOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceOptions; + + /** + * Decodes a ServiceOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ServiceOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceOptions; + + /** + * Verifies a ServiceOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @param message ServiceOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a MethodOptions. */ + interface IMethodOptions { + + /** MethodOptions deprecated */ + deprecated?: (boolean|null); + + /** MethodOptions idempotencyLevel */ + idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); + + /** MethodOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MethodOptions .google.api.http */ + ".google.api.http"?: (google.api.IHttpRule|null); + + /** MethodOptions .google.api.methodSignature */ + ".google.api.methodSignature"?: (string[]|null); + } + + /** Represents a MethodOptions. */ + class MethodOptions implements IMethodOptions { + + /** + * Constructs a new MethodOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodOptions); + + /** MethodOptions deprecated. */ + public deprecated: boolean; + + /** MethodOptions idempotencyLevel. */ + public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; + + /** MethodOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new MethodOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns MethodOptions instance + */ + public static create(properties?: google.protobuf.IMethodOptions): google.protobuf.MethodOptions; + + /** + * Encodes the specified MethodOptions message. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. + * @param message MethodOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MethodOptions message, length delimited. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. + * @param message MethodOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MethodOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MethodOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodOptions; + + /** + * Decodes a MethodOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MethodOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodOptions; + + /** + * Verifies a MethodOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; + + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @param message MethodOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace MethodOptions { + + /** IdempotencyLevel enum. */ + enum IdempotencyLevel { + IDEMPOTENCY_UNKNOWN = 0, + NO_SIDE_EFFECTS = 1, + IDEMPOTENT = 2 + } + } + + /** Properties of an UninterpretedOption. */ + interface IUninterpretedOption { + + /** UninterpretedOption name */ + name?: (google.protobuf.UninterpretedOption.INamePart[]|null); + + /** UninterpretedOption identifierValue */ + identifierValue?: (string|null); + + /** UninterpretedOption positiveIntValue */ + positiveIntValue?: (number|Long|null); + + /** UninterpretedOption negativeIntValue */ + negativeIntValue?: (number|Long|null); + + /** UninterpretedOption doubleValue */ + doubleValue?: (number|null); + + /** UninterpretedOption stringValue */ + stringValue?: (Uint8Array|null); + + /** UninterpretedOption aggregateValue */ + aggregateValue?: (string|null); + } + + /** Represents an UninterpretedOption. */ + class UninterpretedOption implements IUninterpretedOption { + + /** + * Constructs a new UninterpretedOption. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUninterpretedOption); + + /** UninterpretedOption name. */ + public name: google.protobuf.UninterpretedOption.INamePart[]; + + /** UninterpretedOption identifierValue. */ + public identifierValue: string; + + /** UninterpretedOption positiveIntValue. */ + public positiveIntValue: (number|Long); + + /** UninterpretedOption negativeIntValue. */ + public negativeIntValue: (number|Long); + + /** UninterpretedOption doubleValue. */ + public doubleValue: number; + + /** UninterpretedOption stringValue. */ + public stringValue: Uint8Array; + + /** UninterpretedOption aggregateValue. */ + public aggregateValue: string; + + /** + * Creates a new UninterpretedOption instance using the specified properties. + * @param [properties] Properties to set + * @returns UninterpretedOption instance + */ + public static create(properties?: google.protobuf.IUninterpretedOption): google.protobuf.UninterpretedOption; + + /** + * Encodes the specified UninterpretedOption message. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. + * @param message UninterpretedOption message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UninterpretedOption message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. + * @param message UninterpretedOption message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UninterpretedOption message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UninterpretedOption + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption; + + /** + * Decodes an UninterpretedOption message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UninterpretedOption + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption; + + /** + * Verifies an UninterpretedOption message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UninterpretedOption + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @param message UninterpretedOption + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UninterpretedOption to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace UninterpretedOption { + + /** Properties of a NamePart. */ + interface INamePart { + + /** NamePart namePart */ + namePart: string; + + /** NamePart isExtension */ + isExtension: boolean; + } + + /** Represents a NamePart. */ + class NamePart implements INamePart { + + /** + * Constructs a new NamePart. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.UninterpretedOption.INamePart); + + /** NamePart namePart. */ + public namePart: string; + + /** NamePart isExtension. */ + public isExtension: boolean; + + /** + * Creates a new NamePart instance using the specified properties. + * @param [properties] Properties to set + * @returns NamePart instance + */ + public static create(properties?: google.protobuf.UninterpretedOption.INamePart): google.protobuf.UninterpretedOption.NamePart; + + /** + * Encodes the specified NamePart message. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. + * @param message NamePart message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified NamePart message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. + * @param message NamePart message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a NamePart message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns NamePart + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption.NamePart; + + /** + * Decodes a NamePart message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns NamePart + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption.NamePart; + + /** + * Verifies a NamePart message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamePart + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @param message NamePart + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamePart to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Properties of a SourceCodeInfo. */ + interface ISourceCodeInfo { + + /** SourceCodeInfo location */ + location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); + } + + /** Represents a SourceCodeInfo. */ + class SourceCodeInfo implements ISourceCodeInfo { + + /** + * Constructs a new SourceCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ISourceCodeInfo); + + /** SourceCodeInfo location. */ + public location: google.protobuf.SourceCodeInfo.ILocation[]; + + /** + * Creates a new SourceCodeInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns SourceCodeInfo instance + */ + public static create(properties?: google.protobuf.ISourceCodeInfo): google.protobuf.SourceCodeInfo; + + /** + * Encodes the specified SourceCodeInfo message. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. + * @param message SourceCodeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SourceCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. + * @param message SourceCodeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SourceCodeInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SourceCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo; + + /** + * Decodes a SourceCodeInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SourceCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo; + + /** + * Verifies a SourceCodeInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @param message SourceCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace SourceCodeInfo { + + /** Properties of a Location. */ + interface ILocation { + + /** Location path */ + path?: (number[]|null); + + /** Location span */ + span?: (number[]|null); + + /** Location leadingComments */ + leadingComments?: (string|null); + + /** Location trailingComments */ + trailingComments?: (string|null); + + /** Location leadingDetachedComments */ + leadingDetachedComments?: (string[]|null); + } + + /** Represents a Location. */ + class Location implements ILocation { + + /** + * Constructs a new Location. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); + + /** Location path. */ + public path: number[]; + + /** Location span. */ + public span: number[]; + + /** Location leadingComments. */ + public leadingComments: string; + + /** Location trailingComments. */ + public trailingComments: string; + + /** Location leadingDetachedComments. */ + public leadingDetachedComments: string[]; + + /** + * Creates a new Location instance using the specified properties. + * @param [properties] Properties to set + * @returns Location instance + */ + public static create(properties?: google.protobuf.SourceCodeInfo.ILocation): google.protobuf.SourceCodeInfo.Location; + + /** + * Encodes the specified Location message. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. + * @param message Location message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Location message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. + * @param message Location message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Location message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Location + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo.Location; + + /** + * Decodes a Location message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Location + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo.Location; + + /** + * Verifies a Location message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Location + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @param message Location + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Location to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Properties of a GeneratedCodeInfo. */ + interface IGeneratedCodeInfo { + + /** GeneratedCodeInfo annotation */ + annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); + } + + /** Represents a GeneratedCodeInfo. */ + class GeneratedCodeInfo implements IGeneratedCodeInfo { + + /** + * Constructs a new GeneratedCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IGeneratedCodeInfo); + + /** GeneratedCodeInfo annotation. */ + public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; + + /** + * Creates a new GeneratedCodeInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns GeneratedCodeInfo instance + */ + public static create(properties?: google.protobuf.IGeneratedCodeInfo): google.protobuf.GeneratedCodeInfo; + + /** + * Encodes the specified GeneratedCodeInfo message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. + * @param message GeneratedCodeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GeneratedCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. + * @param message GeneratedCodeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GeneratedCodeInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GeneratedCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo; + + /** + * Decodes a GeneratedCodeInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GeneratedCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo; + + /** + * Verifies a GeneratedCodeInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GeneratedCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; + + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @param message GeneratedCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace GeneratedCodeInfo { + + /** Properties of an Annotation. */ + interface IAnnotation { + + /** Annotation path */ + path?: (number[]|null); + + /** Annotation sourceFile */ + sourceFile?: (string|null); + + /** Annotation begin */ + begin?: (number|null); + + /** Annotation end */ + end?: (number|null); + } + + /** Represents an Annotation. */ + class Annotation implements IAnnotation { + + /** + * Constructs a new Annotation. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); + + /** Annotation path. */ + public path: number[]; + + /** Annotation sourceFile. */ + public sourceFile: string; + + /** Annotation begin. */ + public begin: number; + + /** Annotation end. */ + public end: number; + + /** + * Creates a new Annotation instance using the specified properties. + * @param [properties] Properties to set + * @returns Annotation instance + */ + public static create(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Encodes the specified Annotation message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. + * @param message Annotation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Annotation message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. + * @param message Annotation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Annotation message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Annotation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Decodes an Annotation message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Annotation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Verifies an Annotation message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Annotation + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @param message Annotation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Annotation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + } + + /** Namespace type. */ + namespace type { + + /** Properties of an Expr. */ + interface IExpr { + + /** Expr expression */ + expression?: (string|null); + + /** Expr title */ + title?: (string|null); + + /** Expr description */ + description?: (string|null); + + /** Expr location */ + location?: (string|null); + } + + /** Represents an Expr. */ + class Expr implements IExpr { + + /** + * Constructs a new Expr. + * @param [properties] Properties to set + */ + constructor(properties?: google.type.IExpr); + + /** Expr expression. */ + public expression: string; + + /** Expr title. */ + public title: string; + + /** Expr description. */ + public description: string; + + /** Expr location. */ + public location: string; + + /** + * Creates a new Expr instance using the specified properties. + * @param [properties] Properties to set + * @returns Expr instance + */ + public static create(properties?: google.type.IExpr): google.type.Expr; + + /** + * Encodes the specified Expr message. Does not implicitly {@link google.type.Expr.verify|verify} messages. + * @param message Expr message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.type.IExpr, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Expr message, length delimited. Does not implicitly {@link google.type.Expr.verify|verify} messages. + * @param message Expr message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.type.IExpr, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Expr message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Expr + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.type.Expr; + + /** + * Decodes an Expr message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Expr + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.type.Expr; + + /** + * Verifies an Expr message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an Expr message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Expr + */ + public static fromObject(object: { [k: string]: any }): google.type.Expr; + + /** + * Creates a plain object from an Expr message. Also converts values to other types if specified. + * @param message Expr + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.type.Expr, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Expr to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } +} diff --git a/node_modules/google-gax/build/protos/iam_service.js b/node_modules/google-gax/build/protos/iam_service.js new file mode 100644 index 0000000..24d5ecc --- /dev/null +++ b/node_modules/google-gax/build/protos/iam_service.js @@ -0,0 +1 @@ +(e=>{"function"==typeof define&&define.amd?define(["protobufjs/minimal"],e):"function"==typeof require&&"object"==typeof module&&module&&module.exports&&(module.exports=e(require("protobufjs/minimal")))})(function(o){var e,t,n,r,F,a=o.Reader,i=o.Writer,p=o.util,l=o.roots.iam_protos||(o.roots.iam_protos={});function B(e,t,n){o.rpc.Service.call(this,e,t,n)}function s(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:o.resource=e.string();break;case 2:o.policy=l.google.iam.v1.Policy.decode(e,e.uint32());break;default:e.skipType(7&r)}}return o},s.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},s.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.resource&&e.hasOwnProperty("resource")&&!p.isString(e.resource))return"resource: string expected";if(null!=e.policy&&e.hasOwnProperty("policy")){e=l.google.iam.v1.Policy.verify(e.policy);if(e)return"policy."+e}return null},s.fromObject=function(e){if(e instanceof l.google.iam.v1.SetIamPolicyRequest)return e;var t=new l.google.iam.v1.SetIamPolicyRequest;if(null!=e.resource&&(t.resource=String(e.resource)),null!=e.policy){if("object"!=typeof e.policy)throw TypeError(".google.iam.v1.SetIamPolicyRequest.policy: object expected");t.policy=l.google.iam.v1.Policy.fromObject(e.policy)}return t},s.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.resource="",n.policy=null),null!=e.resource&&e.hasOwnProperty("resource")&&(n.resource=e.resource),null!=e.policy&&e.hasOwnProperty("policy")&&(n.policy=l.google.iam.v1.Policy.toObject(e.policy,t)),n},s.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},s),t.GetIamPolicyRequest=(u.prototype.resource="",u.prototype.options=null,u.create=function(e){return new u(e)},u.encode=function(e,t){return t=t||i.create(),null!=e.resource&&Object.hasOwnProperty.call(e,"resource")&&t.uint32(10).string(e.resource),null!=e.options&&Object.hasOwnProperty.call(e,"options")&&l.google.iam.v1.GetPolicyOptions.encode(e.options,t.uint32(18).fork()).ldelim(),t},u.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},u.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new l.google.iam.v1.GetIamPolicyRequest;e.pos>>3){case 1:o.resource=e.string();break;case 2:o.options=l.google.iam.v1.GetPolicyOptions.decode(e,e.uint32());break;default:e.skipType(7&r)}}return o},u.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},u.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.resource&&e.hasOwnProperty("resource")&&!p.isString(e.resource))return"resource: string expected";if(null!=e.options&&e.hasOwnProperty("options")){e=l.google.iam.v1.GetPolicyOptions.verify(e.options);if(e)return"options."+e}return null},u.fromObject=function(e){if(e instanceof l.google.iam.v1.GetIamPolicyRequest)return e;var t=new l.google.iam.v1.GetIamPolicyRequest;if(null!=e.resource&&(t.resource=String(e.resource)),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.iam.v1.GetIamPolicyRequest.options: object expected");t.options=l.google.iam.v1.GetPolicyOptions.fromObject(e.options)}return t},u.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.resource="",n.options=null),null!=e.resource&&e.hasOwnProperty("resource")&&(n.resource=e.resource),null!=e.options&&e.hasOwnProperty("options")&&(n.options=l.google.iam.v1.GetPolicyOptions.toObject(e.options,t)),n},u.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},u),t.TestIamPermissionsRequest=(c.prototype.resource="",c.prototype.permissions=p.emptyArray,c.create=function(e){return new c(e)},c.encode=function(e,t){if(t=t||i.create(),null!=e.resource&&Object.hasOwnProperty.call(e,"resource")&&t.uint32(10).string(e.resource),null!=e.permissions&&e.permissions.length)for(var n=0;n>>3){case 1:o.resource=e.string();break;case 2:o.permissions&&o.permissions.length||(o.permissions=[]),o.permissions.push(e.string());break;default:e.skipType(7&r)}}return o},c.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},c.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.resource&&e.hasOwnProperty("resource")&&!p.isString(e.resource))return"resource: string expected";if(null!=e.permissions&&e.hasOwnProperty("permissions")){if(!Array.isArray(e.permissions))return"permissions: array expected";for(var t=0;t>>3==1?(o.permissions&&o.permissions.length||(o.permissions=[]),o.permissions.push(e.string())):e.skipType(7&r)}return o},G.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},G.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.permissions&&e.hasOwnProperty("permissions")){if(!Array.isArray(e.permissions))return"permissions: array expected";for(var t=0;t>>3==1?o.requestedPolicyVersion=e.int32():e.skipType(7&r)}return o},U.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},U.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.requestedPolicyVersion&&e.hasOwnProperty("requestedPolicyVersion")&&!p.isInteger(e.requestedPolicyVersion)?"requestedPolicyVersion: integer expected":null},U.fromObject=function(e){var t;return e instanceof l.google.iam.v1.GetPolicyOptions?e:(t=new l.google.iam.v1.GetPolicyOptions,null!=e.requestedPolicyVersion&&(t.requestedPolicyVersion=0|e.requestedPolicyVersion),t)},U.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.requestedPolicyVersion=0),null!=e.requestedPolicyVersion&&e.hasOwnProperty("requestedPolicyVersion")&&(n.requestedPolicyVersion=e.requestedPolicyVersion),n},U.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},U),t.Policy=(d.prototype.version=0,d.prototype.bindings=p.emptyArray,d.prototype.etag=p.newBuffer([]),d.create=function(e){return new d(e)},d.encode=function(e,t){if(t=t||i.create(),null!=e.version&&Object.hasOwnProperty.call(e,"version")&&t.uint32(8).int32(e.version),null!=e.etag&&Object.hasOwnProperty.call(e,"etag")&&t.uint32(26).bytes(e.etag),null!=e.bindings&&e.bindings.length)for(var n=0;n>>3){case 1:o.version=e.int32();break;case 4:o.bindings&&o.bindings.length||(o.bindings=[]),o.bindings.push(l.google.iam.v1.Binding.decode(e,e.uint32()));break;case 3:o.etag=e.bytes();break;default:e.skipType(7&r)}}return o},d.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},d.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.version&&e.hasOwnProperty("version")&&!p.isInteger(e.version))return"version: integer expected";if(null!=e.bindings&&e.hasOwnProperty("bindings")){if(!Array.isArray(e.bindings))return"bindings: array expected";for(var t=0;t>>3){case 1:o.role=e.string();break;case 2:o.members&&o.members.length||(o.members=[]),o.members.push(e.string());break;case 3:o.condition=l.google.type.Expr.decode(e,e.uint32());break;default:e.skipType(7&r)}}return o},g.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},g.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.role&&e.hasOwnProperty("role")&&!p.isString(e.role))return"role: string expected";if(null!=e.members&&e.hasOwnProperty("members")){if(!Array.isArray(e.members))return"members: array expected";for(var t=0;t>>3){case 1:o.bindingDeltas&&o.bindingDeltas.length||(o.bindingDeltas=[]),o.bindingDeltas.push(l.google.iam.v1.BindingDelta.decode(e,e.uint32()));break;case 2:o.auditConfigDeltas&&o.auditConfigDeltas.length||(o.auditConfigDeltas=[]),o.auditConfigDeltas.push(l.google.iam.v1.AuditConfigDelta.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return o},M.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},M.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.bindingDeltas&&e.hasOwnProperty("bindingDeltas")){if(!Array.isArray(e.bindingDeltas))return"bindingDeltas: array expected";for(var t=0;t>>3){case 1:o.action=e.int32();break;case 2:o.role=e.string();break;case 3:o.member=e.string();break;case 4:o.condition=l.google.type.Expr.decode(e,e.uint32());break;default:e.skipType(7&r)}}return o},f.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},f.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.action&&e.hasOwnProperty("action"))switch(e.action){default:return"action: enum value expected";case 0:case 1:case 2:}if(null!=e.role&&e.hasOwnProperty("role")&&!p.isString(e.role))return"role: string expected";if(null!=e.member&&e.hasOwnProperty("member")&&!p.isString(e.member))return"member: string expected";if(null!=e.condition&&e.hasOwnProperty("condition")){e=l.google.type.Expr.verify(e.condition);if(e)return"condition."+e}return null},f.fromObject=function(e){if(e instanceof l.google.iam.v1.BindingDelta)return e;var t=new l.google.iam.v1.BindingDelta;switch(e.action){case"ACTION_UNSPECIFIED":case 0:t.action=0;break;case"ADD":case 1:t.action=1;break;case"REMOVE":case 2:t.action=2}if(null!=e.role&&(t.role=String(e.role)),null!=e.member&&(t.member=String(e.member)),null!=e.condition){if("object"!=typeof e.condition)throw TypeError(".google.iam.v1.BindingDelta.condition: object expected");t.condition=l.google.type.Expr.fromObject(e.condition)}return t},f.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.action=t.enums===String?"ACTION_UNSPECIFIED":0,n.role="",n.member="",n.condition=null),null!=e.action&&e.hasOwnProperty("action")&&(n.action=t.enums===String?l.google.iam.v1.BindingDelta.Action[e.action]:e.action),null!=e.role&&e.hasOwnProperty("role")&&(n.role=e.role),null!=e.member&&e.hasOwnProperty("member")&&(n.member=e.member),null!=e.condition&&e.hasOwnProperty("condition")&&(n.condition=l.google.type.Expr.toObject(e.condition,t)),n},f.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},f.Action=(e={},(r=Object.create(e))[e[0]="ACTION_UNSPECIFIED"]=0,r[e[1]="ADD"]=1,r[e[2]="REMOVE"]=2,r),f),t.AuditConfigDelta=(y.prototype.action=0,y.prototype.service="",y.prototype.exemptedMember="",y.prototype.logType="",y.create=function(e){return new y(e)},y.encode=function(e,t){return t=t||i.create(),null!=e.action&&Object.hasOwnProperty.call(e,"action")&&t.uint32(8).int32(e.action),null!=e.service&&Object.hasOwnProperty.call(e,"service")&&t.uint32(18).string(e.service),null!=e.exemptedMember&&Object.hasOwnProperty.call(e,"exemptedMember")&&t.uint32(26).string(e.exemptedMember),null!=e.logType&&Object.hasOwnProperty.call(e,"logType")&&t.uint32(34).string(e.logType),t},y.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},y.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new l.google.iam.v1.AuditConfigDelta;e.pos>>3){case 1:o.action=e.int32();break;case 2:o.service=e.string();break;case 3:o.exemptedMember=e.string();break;case 4:o.logType=e.string();break;default:e.skipType(7&r)}}return o},y.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},y.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.action&&e.hasOwnProperty("action"))switch(e.action){default:return"action: enum value expected";case 0:case 1:case 2:}return null!=e.service&&e.hasOwnProperty("service")&&!p.isString(e.service)?"service: string expected":null!=e.exemptedMember&&e.hasOwnProperty("exemptedMember")&&!p.isString(e.exemptedMember)?"exemptedMember: string expected":null!=e.logType&&e.hasOwnProperty("logType")&&!p.isString(e.logType)?"logType: string expected":null},y.fromObject=function(e){if(e instanceof l.google.iam.v1.AuditConfigDelta)return e;var t=new l.google.iam.v1.AuditConfigDelta;switch(e.action){case"ACTION_UNSPECIFIED":case 0:t.action=0;break;case"ADD":case 1:t.action=1;break;case"REMOVE":case 2:t.action=2}return null!=e.service&&(t.service=String(e.service)),null!=e.exemptedMember&&(t.exemptedMember=String(e.exemptedMember)),null!=e.logType&&(t.logType=String(e.logType)),t},y.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.action=t.enums===String?"ACTION_UNSPECIFIED":0,n.service="",n.exemptedMember="",n.logType=""),null!=e.action&&e.hasOwnProperty("action")&&(n.action=t.enums===String?l.google.iam.v1.AuditConfigDelta.Action[e.action]:e.action),null!=e.service&&e.hasOwnProperty("service")&&(n.service=e.service),null!=e.exemptedMember&&e.hasOwnProperty("exemptedMember")&&(n.exemptedMember=e.exemptedMember),null!=e.logType&&e.hasOwnProperty("logType")&&(n.logType=e.logType),n},y.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},y.Action=(e={},(r=Object.create(e))[e[0]="ACTION_UNSPECIFIED"]=0,r[e[1]="ADD"]=1,r[e[2]="REMOVE"]=2,r),y),t.logging=((e={}).AuditData=(L.prototype.policyDelta=null,L.create=function(e){return new L(e)},L.encode=function(e,t){return t=t||i.create(),null!=e.policyDelta&&Object.hasOwnProperty.call(e,"policyDelta")&&l.google.iam.v1.PolicyDelta.encode(e.policyDelta,t.uint32(18).fork()).ldelim(),t},L.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},L.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new l.google.iam.v1.logging.AuditData;e.pos>>3==2?o.policyDelta=l.google.iam.v1.PolicyDelta.decode(e,e.uint32()):e.skipType(7&r)}return o},L.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},L.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.policyDelta&&e.hasOwnProperty("policyDelta")){e=l.google.iam.v1.PolicyDelta.verify(e.policyDelta);if(e)return"policyDelta."+e}return null},L.fromObject=function(e){if(e instanceof l.google.iam.v1.logging.AuditData)return e;var t=new l.google.iam.v1.logging.AuditData;if(null!=e.policyDelta){if("object"!=typeof e.policyDelta)throw TypeError(".google.iam.v1.logging.AuditData.policyDelta: object expected");t.policyDelta=l.google.iam.v1.PolicyDelta.fromObject(e.policyDelta)}return t},L.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.policyDelta=null),null!=e.policyDelta&&e.hasOwnProperty("policyDelta")&&(n.policyDelta=l.google.iam.v1.PolicyDelta.toObject(e.policyDelta,t)),n},L.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},L),e),t),n),F.api=((r={}).Http=(J.prototype.rules=p.emptyArray,J.prototype.fullyDecodeReservedExpansion=!1,J.create=function(e){return new J(e)},J.encode=function(e,t){if(t=t||i.create(),null!=e.rules&&e.rules.length)for(var n=0;n>>3){case 1:o.rules&&o.rules.length||(o.rules=[]),o.rules.push(l.google.api.HttpRule.decode(e,e.uint32()));break;case 2:o.fullyDecodeReservedExpansion=e.bool();break;default:e.skipType(7&r)}}return o},J.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},J.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.rules&&e.hasOwnProperty("rules")){if(!Array.isArray(e.rules))return"rules: array expected";for(var t=0;t>>3){case 1:o.selector=e.string();break;case 2:o.get=e.string();break;case 3:o.put=e.string();break;case 4:o.post=e.string();break;case 5:o.delete=e.string();break;case 6:o.patch=e.string();break;case 8:o.custom=l.google.api.CustomHttpPattern.decode(e,e.uint32());break;case 7:o.body=e.string();break;case 12:o.responseBody=e.string();break;case 11:o.additionalBindings&&o.additionalBindings.length||(o.additionalBindings=[]),o.additionalBindings.push(l.google.api.HttpRule.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return o},h.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},h.verify=function(e){if("object"!=typeof e||null===e)return"object expected";var t={};if(null!=e.selector&&e.hasOwnProperty("selector")&&!p.isString(e.selector))return"selector: string expected";if(null!=e.get&&e.hasOwnProperty("get")&&(t.pattern=1,!p.isString(e.get)))return"get: string expected";if(null!=e.put&&e.hasOwnProperty("put")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,!p.isString(e.put))return"put: string expected"}if(null!=e.post&&e.hasOwnProperty("post")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,!p.isString(e.post))return"post: string expected"}if(null!=e.delete&&e.hasOwnProperty("delete")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,!p.isString(e.delete))return"delete: string expected"}if(null!=e.patch&&e.hasOwnProperty("patch")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,!p.isString(e.patch))return"patch: string expected"}if(null!=e.custom&&e.hasOwnProperty("custom")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,n=l.google.api.CustomHttpPattern.verify(e.custom))return"custom."+n}if(null!=e.body&&e.hasOwnProperty("body")&&!p.isString(e.body))return"body: string expected";if(null!=e.responseBody&&e.hasOwnProperty("responseBody")&&!p.isString(e.responseBody))return"responseBody: string expected";if(null!=e.additionalBindings&&e.hasOwnProperty("additionalBindings")){if(!Array.isArray(e.additionalBindings))return"additionalBindings: array expected";for(var n,o=0;o>>3){case 1:o.kind=e.string();break;case 2:o.path=e.string();break;default:e.skipType(7&r)}}return o},_.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},_.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.kind&&e.hasOwnProperty("kind")&&!p.isString(e.kind)?"kind: string expected":null!=e.path&&e.hasOwnProperty("path")&&!p.isString(e.path)?"path: string expected":null},_.fromObject=function(e){var t;return e instanceof l.google.api.CustomHttpPattern?e:(t=new l.google.api.CustomHttpPattern,null!=e.kind&&(t.kind=String(e.kind)),null!=e.path&&(t.path=String(e.path)),t)},_.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.kind="",n.path=""),null!=e.kind&&e.hasOwnProperty("kind")&&(n.kind=e.kind),null!=e.path&&e.hasOwnProperty("path")&&(n.path=e.path),n},_.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},_),r.FieldBehavior=(e={},(t=Object.create(e))[e[0]="FIELD_BEHAVIOR_UNSPECIFIED"]=0,t[e[1]="OPTIONAL"]=1,t[e[2]="REQUIRED"]=2,t[e[3]="OUTPUT_ONLY"]=3,t[e[4]="INPUT_ONLY"]=4,t[e[5]="IMMUTABLE"]=5,t),r.ResourceDescriptor=(b.prototype.type="",b.prototype.pattern=p.emptyArray,b.prototype.nameField="",b.prototype.history=0,b.prototype.plural="",b.prototype.singular="",b.create=function(e){return new b(e)},b.encode=function(e,t){if(t=t||i.create(),null!=e.type&&Object.hasOwnProperty.call(e,"type")&&t.uint32(10).string(e.type),null!=e.pattern&&e.pattern.length)for(var n=0;n>>3){case 1:o.type=e.string();break;case 2:o.pattern&&o.pattern.length||(o.pattern=[]),o.pattern.push(e.string());break;case 3:o.nameField=e.string();break;case 4:o.history=e.int32();break;case 5:o.plural=e.string();break;case 6:o.singular=e.string();break;default:e.skipType(7&r)}}return o},b.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},b.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.type&&e.hasOwnProperty("type")&&!p.isString(e.type))return"type: string expected";if(null!=e.pattern&&e.hasOwnProperty("pattern")){if(!Array.isArray(e.pattern))return"pattern: array expected";for(var t=0;t>>3){case 1:o.type=e.string();break;case 2:o.childType=e.string();break;default:e.skipType(7&r)}}return o},H.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},H.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.type&&e.hasOwnProperty("type")&&!p.isString(e.type)?"type: string expected":null!=e.childType&&e.hasOwnProperty("childType")&&!p.isString(e.childType)?"childType: string expected":null},H.fromObject=function(e){var t;return e instanceof l.google.api.ResourceReference?e:(t=new l.google.api.ResourceReference,null!=e.type&&(t.type=String(e.type)),null!=e.childType&&(t.childType=String(e.childType)),t)},H.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.type="",n.childType=""),null!=e.type&&e.hasOwnProperty("type")&&(n.type=e.type),null!=e.childType&&e.hasOwnProperty("childType")&&(n.childType=e.childType),n},H.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},H),r),F.protobuf=((n={}).FileDescriptorSet=(q.prototype.file=p.emptyArray,q.create=function(e){return new q(e)},q.encode=function(e,t){if(t=t||i.create(),null!=e.file&&e.file.length)for(var n=0;n>>3==1?(o.file&&o.file.length||(o.file=[]),o.file.push(l.google.protobuf.FileDescriptorProto.decode(e,e.uint32()))):e.skipType(7&r)}return o},q.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},q.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.file&&e.hasOwnProperty("file")){if(!Array.isArray(e.file))return"file: array expected";for(var t=0;t>>3){case 1:o.name=e.string();break;case 2:o.package=e.string();break;case 3:o.dependency&&o.dependency.length||(o.dependency=[]),o.dependency.push(e.string());break;case 10:if(o.publicDependency&&o.publicDependency.length||(o.publicDependency=[]),2==(7&r))for(var i=e.uint32()+e.pos;e.pos>>3){case 1:o.name=e.string();break;case 2:o.field&&o.field.length||(o.field=[]),o.field.push(l.google.protobuf.FieldDescriptorProto.decode(e,e.uint32()));break;case 6:o.extension&&o.extension.length||(o.extension=[]),o.extension.push(l.google.protobuf.FieldDescriptorProto.decode(e,e.uint32()));break;case 3:o.nestedType&&o.nestedType.length||(o.nestedType=[]),o.nestedType.push(l.google.protobuf.DescriptorProto.decode(e,e.uint32()));break;case 4:o.enumType&&o.enumType.length||(o.enumType=[]),o.enumType.push(l.google.protobuf.EnumDescriptorProto.decode(e,e.uint32()));break;case 5:o.extensionRange&&o.extensionRange.length||(o.extensionRange=[]),o.extensionRange.push(l.google.protobuf.DescriptorProto.ExtensionRange.decode(e,e.uint32()));break;case 8:o.oneofDecl&&o.oneofDecl.length||(o.oneofDecl=[]),o.oneofDecl.push(l.google.protobuf.OneofDescriptorProto.decode(e,e.uint32()));break;case 7:o.options=l.google.protobuf.MessageOptions.decode(e,e.uint32());break;case 9:o.reservedRange&&o.reservedRange.length||(o.reservedRange=[]),o.reservedRange.push(l.google.protobuf.DescriptorProto.ReservedRange.decode(e,e.uint32()));break;case 10:o.reservedName&&o.reservedName.length||(o.reservedName=[]),o.reservedName.push(e.string());break;default:e.skipType(7&r)}}return o},O.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},O.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!p.isString(e.name))return"name: string expected";if(null!=e.field&&e.hasOwnProperty("field")){if(!Array.isArray(e.field))return"field: array expected";for(var t=0;t>>3){case 1:o.start=e.int32();break;case 2:o.end=e.int32();break;case 3:o.options=l.google.protobuf.ExtensionRangeOptions.decode(e,e.uint32());break;default:e.skipType(7&r)}}return o},v.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},v.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.start&&e.hasOwnProperty("start")&&!p.isInteger(e.start))return"start: integer expected";if(null!=e.end&&e.hasOwnProperty("end")&&!p.isInteger(e.end))return"end: integer expected";if(null!=e.options&&e.hasOwnProperty("options")){e=l.google.protobuf.ExtensionRangeOptions.verify(e.options);if(e)return"options."+e}return null},v.fromObject=function(e){if(e instanceof l.google.protobuf.DescriptorProto.ExtensionRange)return e;var t=new l.google.protobuf.DescriptorProto.ExtensionRange;if(null!=e.start&&(t.start=0|e.start),null!=e.end&&(t.end=0|e.end),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.protobuf.DescriptorProto.ExtensionRange.options: object expected");t.options=l.google.protobuf.ExtensionRangeOptions.fromObject(e.options)}return t},v.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.start=0,n.end=0,n.options=null),null!=e.start&&e.hasOwnProperty("start")&&(n.start=e.start),null!=e.end&&e.hasOwnProperty("end")&&(n.end=e.end),null!=e.options&&e.hasOwnProperty("options")&&(n.options=l.google.protobuf.ExtensionRangeOptions.toObject(e.options,t)),n},v.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},v),O.ReservedRange=(Y.prototype.start=0,Y.prototype.end=0,Y.create=function(e){return new Y(e)},Y.encode=function(e,t){return t=t||i.create(),null!=e.start&&Object.hasOwnProperty.call(e,"start")&&t.uint32(8).int32(e.start),null!=e.end&&Object.hasOwnProperty.call(e,"end")&&t.uint32(16).int32(e.end),t},Y.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},Y.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new l.google.protobuf.DescriptorProto.ReservedRange;e.pos>>3){case 1:o.start=e.int32();break;case 2:o.end=e.int32();break;default:e.skipType(7&r)}}return o},Y.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},Y.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.start&&e.hasOwnProperty("start")&&!p.isInteger(e.start)?"start: integer expected":null!=e.end&&e.hasOwnProperty("end")&&!p.isInteger(e.end)?"end: integer expected":null},Y.fromObject=function(e){var t;return e instanceof l.google.protobuf.DescriptorProto.ReservedRange?e:(t=new l.google.protobuf.DescriptorProto.ReservedRange,null!=e.start&&(t.start=0|e.start),null!=e.end&&(t.end=0|e.end),t)},Y.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.start=0,n.end=0),null!=e.start&&e.hasOwnProperty("start")&&(n.start=e.start),null!=e.end&&e.hasOwnProperty("end")&&(n.end=e.end),n},Y.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},Y),O),n.ExtensionRangeOptions=(z.prototype.uninterpretedOption=p.emptyArray,z.create=function(e){return new z(e)},z.encode=function(e,t){if(t=t||i.create(),null!=e.uninterpretedOption&&e.uninterpretedOption.length)for(var n=0;n>>3==999?(o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(l.google.protobuf.UninterpretedOption.decode(e,e.uint32()))):e.skipType(7&r)}return o},z.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},z.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 1:o.name=e.string();break;case 3:o.number=e.int32();break;case 4:o.label=e.int32();break;case 5:o.type=e.int32();break;case 6:o.typeName=e.string();break;case 2:o.extendee=e.string();break;case 7:o.defaultValue=e.string();break;case 9:o.oneofIndex=e.int32();break;case 10:o.jsonName=e.string();break;case 8:o.options=l.google.protobuf.FieldOptions.decode(e,e.uint32());break;case 17:o.proto3Optional=e.bool();break;default:e.skipType(7&r)}}return o},P.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},P.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!p.isString(e.name))return"name: string expected";if(null!=e.number&&e.hasOwnProperty("number")&&!p.isInteger(e.number))return"number: integer expected";if(null!=e.label&&e.hasOwnProperty("label"))switch(e.label){default:return"label: enum value expected";case 1:case 2:case 3:}if(null!=e.type&&e.hasOwnProperty("type"))switch(e.type){default:return"type: enum value expected";case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:case 11:case 12:case 13:case 14:case 15:case 16:case 17:case 18:}if(null!=e.typeName&&e.hasOwnProperty("typeName")&&!p.isString(e.typeName))return"typeName: string expected";if(null!=e.extendee&&e.hasOwnProperty("extendee")&&!p.isString(e.extendee))return"extendee: string expected";if(null!=e.defaultValue&&e.hasOwnProperty("defaultValue")&&!p.isString(e.defaultValue))return"defaultValue: string expected";if(null!=e.oneofIndex&&e.hasOwnProperty("oneofIndex")&&!p.isInteger(e.oneofIndex))return"oneofIndex: integer expected";if(null!=e.jsonName&&e.hasOwnProperty("jsonName")&&!p.isString(e.jsonName))return"jsonName: string expected";if(null!=e.options&&e.hasOwnProperty("options")){var t=l.google.protobuf.FieldOptions.verify(e.options);if(t)return"options."+t}return null!=e.proto3Optional&&e.hasOwnProperty("proto3Optional")&&"boolean"!=typeof e.proto3Optional?"proto3Optional: boolean expected":null},P.fromObject=function(e){if(e instanceof l.google.protobuf.FieldDescriptorProto)return e;var t=new l.google.protobuf.FieldDescriptorProto;switch(null!=e.name&&(t.name=String(e.name)),null!=e.number&&(t.number=0|e.number),e.label){case"LABEL_OPTIONAL":case 1:t.label=1;break;case"LABEL_REQUIRED":case 2:t.label=2;break;case"LABEL_REPEATED":case 3:t.label=3}switch(e.type){case"TYPE_DOUBLE":case 1:t.type=1;break;case"TYPE_FLOAT":case 2:t.type=2;break;case"TYPE_INT64":case 3:t.type=3;break;case"TYPE_UINT64":case 4:t.type=4;break;case"TYPE_INT32":case 5:t.type=5;break;case"TYPE_FIXED64":case 6:t.type=6;break;case"TYPE_FIXED32":case 7:t.type=7;break;case"TYPE_BOOL":case 8:t.type=8;break;case"TYPE_STRING":case 9:t.type=9;break;case"TYPE_GROUP":case 10:t.type=10;break;case"TYPE_MESSAGE":case 11:t.type=11;break;case"TYPE_BYTES":case 12:t.type=12;break;case"TYPE_UINT32":case 13:t.type=13;break;case"TYPE_ENUM":case 14:t.type=14;break;case"TYPE_SFIXED32":case 15:t.type=15;break;case"TYPE_SFIXED64":case 16:t.type=16;break;case"TYPE_SINT32":case 17:t.type=17;break;case"TYPE_SINT64":case 18:t.type=18}if(null!=e.typeName&&(t.typeName=String(e.typeName)),null!=e.extendee&&(t.extendee=String(e.extendee)),null!=e.defaultValue&&(t.defaultValue=String(e.defaultValue)),null!=e.oneofIndex&&(t.oneofIndex=0|e.oneofIndex),null!=e.jsonName&&(t.jsonName=String(e.jsonName)),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.protobuf.FieldDescriptorProto.options: object expected");t.options=l.google.protobuf.FieldOptions.fromObject(e.options)}return null!=e.proto3Optional&&(t.proto3Optional=Boolean(e.proto3Optional)),t},P.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name="",n.extendee="",n.number=0,n.label=t.enums===String?"LABEL_OPTIONAL":1,n.type=t.enums===String?"TYPE_DOUBLE":1,n.typeName="",n.defaultValue="",n.options=null,n.oneofIndex=0,n.jsonName="",n.proto3Optional=!1),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.extendee&&e.hasOwnProperty("extendee")&&(n.extendee=e.extendee),null!=e.number&&e.hasOwnProperty("number")&&(n.number=e.number),null!=e.label&&e.hasOwnProperty("label")&&(n.label=t.enums===String?l.google.protobuf.FieldDescriptorProto.Label[e.label]:e.label),null!=e.type&&e.hasOwnProperty("type")&&(n.type=t.enums===String?l.google.protobuf.FieldDescriptorProto.Type[e.type]:e.type),null!=e.typeName&&e.hasOwnProperty("typeName")&&(n.typeName=e.typeName),null!=e.defaultValue&&e.hasOwnProperty("defaultValue")&&(n.defaultValue=e.defaultValue),null!=e.options&&e.hasOwnProperty("options")&&(n.options=l.google.protobuf.FieldOptions.toObject(e.options,t)),null!=e.oneofIndex&&e.hasOwnProperty("oneofIndex")&&(n.oneofIndex=e.oneofIndex),null!=e.jsonName&&e.hasOwnProperty("jsonName")&&(n.jsonName=e.jsonName),null!=e.proto3Optional&&e.hasOwnProperty("proto3Optional")&&(n.proto3Optional=e.proto3Optional),n},P.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},P.Type=(e={},(t=Object.create(e))[e[1]="TYPE_DOUBLE"]=1,t[e[2]="TYPE_FLOAT"]=2,t[e[3]="TYPE_INT64"]=3,t[e[4]="TYPE_UINT64"]=4,t[e[5]="TYPE_INT32"]=5,t[e[6]="TYPE_FIXED64"]=6,t[e[7]="TYPE_FIXED32"]=7,t[e[8]="TYPE_BOOL"]=8,t[e[9]="TYPE_STRING"]=9,t[e[10]="TYPE_GROUP"]=10,t[e[11]="TYPE_MESSAGE"]=11,t[e[12]="TYPE_BYTES"]=12,t[e[13]="TYPE_UINT32"]=13,t[e[14]="TYPE_ENUM"]=14,t[e[15]="TYPE_SFIXED32"]=15,t[e[16]="TYPE_SFIXED64"]=16,t[e[17]="TYPE_SINT32"]=17,t[e[18]="TYPE_SINT64"]=18,t),P.Label=(e={},(t=Object.create(e))[e[1]="LABEL_OPTIONAL"]=1,t[e[2]="LABEL_REQUIRED"]=2,t[e[3]="LABEL_REPEATED"]=3,t),P),n.OneofDescriptorProto=(W.prototype.name="",W.prototype.options=null,W.create=function(e){return new W(e)},W.encode=function(e,t){return t=t||i.create(),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(10).string(e.name),null!=e.options&&Object.hasOwnProperty.call(e,"options")&&l.google.protobuf.OneofOptions.encode(e.options,t.uint32(18).fork()).ldelim(),t},W.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},W.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new l.google.protobuf.OneofDescriptorProto;e.pos>>3){case 1:o.name=e.string();break;case 2:o.options=l.google.protobuf.OneofOptions.decode(e,e.uint32());break;default:e.skipType(7&r)}}return o},W.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},W.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!p.isString(e.name))return"name: string expected";if(null!=e.options&&e.hasOwnProperty("options")){e=l.google.protobuf.OneofOptions.verify(e.options);if(e)return"options."+e}return null},W.fromObject=function(e){if(e instanceof l.google.protobuf.OneofDescriptorProto)return e;var t=new l.google.protobuf.OneofDescriptorProto;if(null!=e.name&&(t.name=String(e.name)),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.protobuf.OneofDescriptorProto.options: object expected");t.options=l.google.protobuf.OneofOptions.fromObject(e.options)}return t},W.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name="",n.options=null),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.options&&e.hasOwnProperty("options")&&(n.options=l.google.protobuf.OneofOptions.toObject(e.options,t)),n},W.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},W),n.EnumDescriptorProto=(w.prototype.name="",w.prototype.value=p.emptyArray,w.prototype.options=null,w.prototype.reservedRange=p.emptyArray,w.prototype.reservedName=p.emptyArray,w.create=function(e){return new w(e)},w.encode=function(e,t){if(t=t||i.create(),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(10).string(e.name),null!=e.value&&e.value.length)for(var n=0;n>>3){case 1:o.name=e.string();break;case 2:o.value&&o.value.length||(o.value=[]),o.value.push(l.google.protobuf.EnumValueDescriptorProto.decode(e,e.uint32()));break;case 3:o.options=l.google.protobuf.EnumOptions.decode(e,e.uint32());break;case 4:o.reservedRange&&o.reservedRange.length||(o.reservedRange=[]),o.reservedRange.push(l.google.protobuf.EnumDescriptorProto.EnumReservedRange.decode(e,e.uint32()));break;case 5:o.reservedName&&o.reservedName.length||(o.reservedName=[]),o.reservedName.push(e.string());break;default:e.skipType(7&r)}}return o},w.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},w.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!p.isString(e.name))return"name: string expected";if(null!=e.value&&e.hasOwnProperty("value")){if(!Array.isArray(e.value))return"value: array expected";for(var t=0;t>>3){case 1:o.start=e.int32();break;case 2:o.end=e.int32();break;default:e.skipType(7&r)}}return o},X.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},X.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.start&&e.hasOwnProperty("start")&&!p.isInteger(e.start)?"start: integer expected":null!=e.end&&e.hasOwnProperty("end")&&!p.isInteger(e.end)?"end: integer expected":null},X.fromObject=function(e){var t;return e instanceof l.google.protobuf.EnumDescriptorProto.EnumReservedRange?e:(t=new l.google.protobuf.EnumDescriptorProto.EnumReservedRange,null!=e.start&&(t.start=0|e.start),null!=e.end&&(t.end=0|e.end),t)},X.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.start=0,n.end=0),null!=e.start&&e.hasOwnProperty("start")&&(n.start=e.start),null!=e.end&&e.hasOwnProperty("end")&&(n.end=e.end),n},X.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},X),w),n.EnumValueDescriptorProto=(j.prototype.name="",j.prototype.number=0,j.prototype.options=null,j.create=function(e){return new j(e)},j.encode=function(e,t){return t=t||i.create(),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(10).string(e.name),null!=e.number&&Object.hasOwnProperty.call(e,"number")&&t.uint32(16).int32(e.number),null!=e.options&&Object.hasOwnProperty.call(e,"options")&&l.google.protobuf.EnumValueOptions.encode(e.options,t.uint32(26).fork()).ldelim(),t},j.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},j.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new l.google.protobuf.EnumValueDescriptorProto;e.pos>>3){case 1:o.name=e.string();break;case 2:o.number=e.int32();break;case 3:o.options=l.google.protobuf.EnumValueOptions.decode(e,e.uint32());break;default:e.skipType(7&r)}}return o},j.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},j.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!p.isString(e.name))return"name: string expected";if(null!=e.number&&e.hasOwnProperty("number")&&!p.isInteger(e.number))return"number: integer expected";if(null!=e.options&&e.hasOwnProperty("options")){e=l.google.protobuf.EnumValueOptions.verify(e.options);if(e)return"options."+e}return null},j.fromObject=function(e){if(e instanceof l.google.protobuf.EnumValueDescriptorProto)return e;var t=new l.google.protobuf.EnumValueDescriptorProto;if(null!=e.name&&(t.name=String(e.name)),null!=e.number&&(t.number=0|e.number),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.protobuf.EnumValueDescriptorProto.options: object expected");t.options=l.google.protobuf.EnumValueOptions.fromObject(e.options)}return t},j.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name="",n.number=0,n.options=null),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.number&&e.hasOwnProperty("number")&&(n.number=e.number),null!=e.options&&e.hasOwnProperty("options")&&(n.options=l.google.protobuf.EnumValueOptions.toObject(e.options,t)),n},j.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},j),n.ServiceDescriptorProto=(D.prototype.name="",D.prototype.method=p.emptyArray,D.prototype.options=null,D.create=function(e){return new D(e)},D.encode=function(e,t){if(t=t||i.create(),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(10).string(e.name),null!=e.method&&e.method.length)for(var n=0;n>>3){case 1:o.name=e.string();break;case 2:o.method&&o.method.length||(o.method=[]),o.method.push(l.google.protobuf.MethodDescriptorProto.decode(e,e.uint32()));break;case 3:o.options=l.google.protobuf.ServiceOptions.decode(e,e.uint32());break;default:e.skipType(7&r)}}return o},D.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},D.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!p.isString(e.name))return"name: string expected";if(null!=e.method&&e.hasOwnProperty("method")){if(!Array.isArray(e.method))return"method: array expected";for(var t=0;t>>3){case 1:o.name=e.string();break;case 2:o.inputType=e.string();break;case 3:o.outputType=e.string();break;case 4:o.options=l.google.protobuf.MethodOptions.decode(e,e.uint32());break;case 5:o.clientStreaming=e.bool();break;case 6:o.serverStreaming=e.bool();break;default:e.skipType(7&r)}}return o},x.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},x.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!p.isString(e.name))return"name: string expected";if(null!=e.inputType&&e.hasOwnProperty("inputType")&&!p.isString(e.inputType))return"inputType: string expected";if(null!=e.outputType&&e.hasOwnProperty("outputType")&&!p.isString(e.outputType))return"outputType: string expected";if(null!=e.options&&e.hasOwnProperty("options")){var t=l.google.protobuf.MethodOptions.verify(e.options);if(t)return"options."+t}return null!=e.clientStreaming&&e.hasOwnProperty("clientStreaming")&&"boolean"!=typeof e.clientStreaming?"clientStreaming: boolean expected":null!=e.serverStreaming&&e.hasOwnProperty("serverStreaming")&&"boolean"!=typeof e.serverStreaming?"serverStreaming: boolean expected":null},x.fromObject=function(e){if(e instanceof l.google.protobuf.MethodDescriptorProto)return e;var t=new l.google.protobuf.MethodDescriptorProto;if(null!=e.name&&(t.name=String(e.name)),null!=e.inputType&&(t.inputType=String(e.inputType)),null!=e.outputType&&(t.outputType=String(e.outputType)),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.protobuf.MethodDescriptorProto.options: object expected");t.options=l.google.protobuf.MethodOptions.fromObject(e.options)}return null!=e.clientStreaming&&(t.clientStreaming=Boolean(e.clientStreaming)),null!=e.serverStreaming&&(t.serverStreaming=Boolean(e.serverStreaming)),t},x.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name="",n.inputType="",n.outputType="",n.options=null,n.clientStreaming=!1,n.serverStreaming=!1),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.inputType&&e.hasOwnProperty("inputType")&&(n.inputType=e.inputType),null!=e.outputType&&e.hasOwnProperty("outputType")&&(n.outputType=e.outputType),null!=e.options&&e.hasOwnProperty("options")&&(n.options=l.google.protobuf.MethodOptions.toObject(e.options,t)),null!=e.clientStreaming&&e.hasOwnProperty("clientStreaming")&&(n.clientStreaming=e.clientStreaming),null!=e.serverStreaming&&e.hasOwnProperty("serverStreaming")&&(n.serverStreaming=e.serverStreaming),n},x.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},x),n.FileOptions=(S.prototype.javaPackage="",S.prototype.javaOuterClassname="",S.prototype.javaMultipleFiles=!1,S.prototype.javaGenerateEqualsAndHash=!1,S.prototype.javaStringCheckUtf8=!1,S.prototype.optimizeFor=1,S.prototype.goPackage="",S.prototype.ccGenericServices=!1,S.prototype.javaGenericServices=!1,S.prototype.pyGenericServices=!1,S.prototype.phpGenericServices=!1,S.prototype.deprecated=!1,S.prototype.ccEnableArenas=!0,S.prototype.objcClassPrefix="",S.prototype.csharpNamespace="",S.prototype.swiftPrefix="",S.prototype.phpClassPrefix="",S.prototype.phpNamespace="",S.prototype.phpMetadataNamespace="",S.prototype.rubyPackage="",S.prototype.uninterpretedOption=p.emptyArray,S.prototype[".google.api.resourceDefinition"]=p.emptyArray,S.create=function(e){return new S(e)},S.encode=function(e,t){if(t=t||i.create(),null!=e.javaPackage&&Object.hasOwnProperty.call(e,"javaPackage")&&t.uint32(10).string(e.javaPackage),null!=e.javaOuterClassname&&Object.hasOwnProperty.call(e,"javaOuterClassname")&&t.uint32(66).string(e.javaOuterClassname),null!=e.optimizeFor&&Object.hasOwnProperty.call(e,"optimizeFor")&&t.uint32(72).int32(e.optimizeFor),null!=e.javaMultipleFiles&&Object.hasOwnProperty.call(e,"javaMultipleFiles")&&t.uint32(80).bool(e.javaMultipleFiles),null!=e.goPackage&&Object.hasOwnProperty.call(e,"goPackage")&&t.uint32(90).string(e.goPackage),null!=e.ccGenericServices&&Object.hasOwnProperty.call(e,"ccGenericServices")&&t.uint32(128).bool(e.ccGenericServices),null!=e.javaGenericServices&&Object.hasOwnProperty.call(e,"javaGenericServices")&&t.uint32(136).bool(e.javaGenericServices),null!=e.pyGenericServices&&Object.hasOwnProperty.call(e,"pyGenericServices")&&t.uint32(144).bool(e.pyGenericServices),null!=e.javaGenerateEqualsAndHash&&Object.hasOwnProperty.call(e,"javaGenerateEqualsAndHash")&&t.uint32(160).bool(e.javaGenerateEqualsAndHash),null!=e.deprecated&&Object.hasOwnProperty.call(e,"deprecated")&&t.uint32(184).bool(e.deprecated),null!=e.javaStringCheckUtf8&&Object.hasOwnProperty.call(e,"javaStringCheckUtf8")&&t.uint32(216).bool(e.javaStringCheckUtf8),null!=e.ccEnableArenas&&Object.hasOwnProperty.call(e,"ccEnableArenas")&&t.uint32(248).bool(e.ccEnableArenas),null!=e.objcClassPrefix&&Object.hasOwnProperty.call(e,"objcClassPrefix")&&t.uint32(290).string(e.objcClassPrefix),null!=e.csharpNamespace&&Object.hasOwnProperty.call(e,"csharpNamespace")&&t.uint32(298).string(e.csharpNamespace),null!=e.swiftPrefix&&Object.hasOwnProperty.call(e,"swiftPrefix")&&t.uint32(314).string(e.swiftPrefix),null!=e.phpClassPrefix&&Object.hasOwnProperty.call(e,"phpClassPrefix")&&t.uint32(322).string(e.phpClassPrefix),null!=e.phpNamespace&&Object.hasOwnProperty.call(e,"phpNamespace")&&t.uint32(330).string(e.phpNamespace),null!=e.phpGenericServices&&Object.hasOwnProperty.call(e,"phpGenericServices")&&t.uint32(336).bool(e.phpGenericServices),null!=e.phpMetadataNamespace&&Object.hasOwnProperty.call(e,"phpMetadataNamespace")&&t.uint32(354).string(e.phpMetadataNamespace),null!=e.rubyPackage&&Object.hasOwnProperty.call(e,"rubyPackage")&&t.uint32(362).string(e.rubyPackage),null!=e.uninterpretedOption&&e.uninterpretedOption.length)for(var n=0;n>>3){case 1:o.javaPackage=e.string();break;case 8:o.javaOuterClassname=e.string();break;case 10:o.javaMultipleFiles=e.bool();break;case 20:o.javaGenerateEqualsAndHash=e.bool();break;case 27:o.javaStringCheckUtf8=e.bool();break;case 9:o.optimizeFor=e.int32();break;case 11:o.goPackage=e.string();break;case 16:o.ccGenericServices=e.bool();break;case 17:o.javaGenericServices=e.bool();break;case 18:o.pyGenericServices=e.bool();break;case 42:o.phpGenericServices=e.bool();break;case 23:o.deprecated=e.bool();break;case 31:o.ccEnableArenas=e.bool();break;case 36:o.objcClassPrefix=e.string();break;case 37:o.csharpNamespace=e.string();break;case 39:o.swiftPrefix=e.string();break;case 40:o.phpClassPrefix=e.string();break;case 41:o.phpNamespace=e.string();break;case 44:o.phpMetadataNamespace=e.string();break;case 45:o.rubyPackage=e.string();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(l.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;case 1053:o[".google.api.resourceDefinition"]&&o[".google.api.resourceDefinition"].length||(o[".google.api.resourceDefinition"]=[]),o[".google.api.resourceDefinition"].push(l.google.api.ResourceDescriptor.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return o},S.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},S.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.javaPackage&&e.hasOwnProperty("javaPackage")&&!p.isString(e.javaPackage))return"javaPackage: string expected";if(null!=e.javaOuterClassname&&e.hasOwnProperty("javaOuterClassname")&&!p.isString(e.javaOuterClassname))return"javaOuterClassname: string expected";if(null!=e.javaMultipleFiles&&e.hasOwnProperty("javaMultipleFiles")&&"boolean"!=typeof e.javaMultipleFiles)return"javaMultipleFiles: boolean expected";if(null!=e.javaGenerateEqualsAndHash&&e.hasOwnProperty("javaGenerateEqualsAndHash")&&"boolean"!=typeof e.javaGenerateEqualsAndHash)return"javaGenerateEqualsAndHash: boolean expected";if(null!=e.javaStringCheckUtf8&&e.hasOwnProperty("javaStringCheckUtf8")&&"boolean"!=typeof e.javaStringCheckUtf8)return"javaStringCheckUtf8: boolean expected";if(null!=e.optimizeFor&&e.hasOwnProperty("optimizeFor"))switch(e.optimizeFor){default:return"optimizeFor: enum value expected";case 1:case 2:case 3:}if(null!=e.goPackage&&e.hasOwnProperty("goPackage")&&!p.isString(e.goPackage))return"goPackage: string expected";if(null!=e.ccGenericServices&&e.hasOwnProperty("ccGenericServices")&&"boolean"!=typeof e.ccGenericServices)return"ccGenericServices: boolean expected";if(null!=e.javaGenericServices&&e.hasOwnProperty("javaGenericServices")&&"boolean"!=typeof e.javaGenericServices)return"javaGenericServices: boolean expected";if(null!=e.pyGenericServices&&e.hasOwnProperty("pyGenericServices")&&"boolean"!=typeof e.pyGenericServices)return"pyGenericServices: boolean expected";if(null!=e.phpGenericServices&&e.hasOwnProperty("phpGenericServices")&&"boolean"!=typeof e.phpGenericServices)return"phpGenericServices: boolean expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.ccEnableArenas&&e.hasOwnProperty("ccEnableArenas")&&"boolean"!=typeof e.ccEnableArenas)return"ccEnableArenas: boolean expected";if(null!=e.objcClassPrefix&&e.hasOwnProperty("objcClassPrefix")&&!p.isString(e.objcClassPrefix))return"objcClassPrefix: string expected";if(null!=e.csharpNamespace&&e.hasOwnProperty("csharpNamespace")&&!p.isString(e.csharpNamespace))return"csharpNamespace: string expected";if(null!=e.swiftPrefix&&e.hasOwnProperty("swiftPrefix")&&!p.isString(e.swiftPrefix))return"swiftPrefix: string expected";if(null!=e.phpClassPrefix&&e.hasOwnProperty("phpClassPrefix")&&!p.isString(e.phpClassPrefix))return"phpClassPrefix: string expected";if(null!=e.phpNamespace&&e.hasOwnProperty("phpNamespace")&&!p.isString(e.phpNamespace))return"phpNamespace: string expected";if(null!=e.phpMetadataNamespace&&e.hasOwnProperty("phpMetadataNamespace")&&!p.isString(e.phpMetadataNamespace))return"phpMetadataNamespace: string expected";if(null!=e.rubyPackage&&e.hasOwnProperty("rubyPackage")&&!p.isString(e.rubyPackage))return"rubyPackage: string expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 1:o.messageSetWireFormat=e.bool();break;case 2:o.noStandardDescriptorAccessor=e.bool();break;case 3:o.deprecated=e.bool();break;case 7:o.mapEntry=e.bool();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(l.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;case 1053:o[".google.api.resource"]=l.google.api.ResourceDescriptor.decode(e,e.uint32());break;default:e.skipType(7&r)}}return o},k.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},k.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.messageSetWireFormat&&e.hasOwnProperty("messageSetWireFormat")&&"boolean"!=typeof e.messageSetWireFormat)return"messageSetWireFormat: boolean expected";if(null!=e.noStandardDescriptorAccessor&&e.hasOwnProperty("noStandardDescriptorAccessor")&&"boolean"!=typeof e.noStandardDescriptorAccessor)return"noStandardDescriptorAccessor: boolean expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.mapEntry&&e.hasOwnProperty("mapEntry")&&"boolean"!=typeof e.mapEntry)return"mapEntry: boolean expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 1:o.ctype=e.int32();break;case 2:o.packed=e.bool();break;case 6:o.jstype=e.int32();break;case 5:o.lazy=e.bool();break;case 3:o.deprecated=e.bool();break;case 10:o.weak=e.bool();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(l.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;case 1052:if(o[".google.api.fieldBehavior"]&&o[".google.api.fieldBehavior"].length||(o[".google.api.fieldBehavior"]=[]),2==(7&r))for(var i=e.uint32()+e.pos;e.pos>>3==999?(o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(l.google.protobuf.UninterpretedOption.decode(e,e.uint32()))):e.skipType(7&r)}return o},Q.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},Q.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 2:o.allowAlias=e.bool();break;case 3:o.deprecated=e.bool();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(l.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return o},E.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},E.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.allowAlias&&e.hasOwnProperty("allowAlias")&&"boolean"!=typeof e.allowAlias)return"allowAlias: boolean expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 1:o.deprecated=e.bool();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(l.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return o},K.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},K.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 33:o.deprecated=e.bool();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(l.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;case 1049:o[".google.api.defaultHost"]=e.string();break;case 1050:o[".google.api.oauthScopes"]=e.string();break;default:e.skipType(7&r)}}return o},A.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},A.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 33:o.deprecated=e.bool();break;case 34:o.idempotencyLevel=e.int32();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(l.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;case 72295728:o[".google.api.http"]=l.google.api.HttpRule.decode(e,e.uint32());break;case 1051:o[".google.api.methodSignature"]&&o[".google.api.methodSignature"].length||(o[".google.api.methodSignature"]=[]),o[".google.api.methodSignature"].push(e.string());break;default:e.skipType(7&r)}}return o},N.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},N.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.idempotencyLevel&&e.hasOwnProperty("idempotencyLevel"))switch(e.idempotencyLevel){default:return"idempotencyLevel: enum value expected";case 0:case 1:case 2:}if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 2:o.name&&o.name.length||(o.name=[]),o.name.push(l.google.protobuf.UninterpretedOption.NamePart.decode(e,e.uint32()));break;case 3:o.identifierValue=e.string();break;case 4:o.positiveIntValue=e.uint64();break;case 5:o.negativeIntValue=e.int64();break;case 6:o.doubleValue=e.double();break;case 7:o.stringValue=e.bytes();break;case 8:o.aggregateValue=e.string();break;default:e.skipType(7&r)}}return o},R.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},R.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")){if(!Array.isArray(e.name))return"name: array expected";for(var t=0;t>>0,e.positiveIntValue.high>>>0).toNumber(!0))),null!=e.negativeIntValue&&(p.Long?(t.negativeIntValue=p.Long.fromValue(e.negativeIntValue)).unsigned=!1:"string"==typeof e.negativeIntValue?t.negativeIntValue=parseInt(e.negativeIntValue,10):"number"==typeof e.negativeIntValue?t.negativeIntValue=e.negativeIntValue:"object"==typeof e.negativeIntValue&&(t.negativeIntValue=new p.LongBits(e.negativeIntValue.low>>>0,e.negativeIntValue.high>>>0).toNumber())),null!=e.doubleValue&&(t.doubleValue=Number(e.doubleValue)),null!=e.stringValue&&("string"==typeof e.stringValue?p.base64.decode(e.stringValue,t.stringValue=p.newBuffer(p.base64.length(e.stringValue)),0):e.stringValue.length&&(t.stringValue=e.stringValue)),null!=e.aggregateValue&&(t.aggregateValue=String(e.aggregateValue)),t},R.toObject=function(e,t){var n,o={};if(((t=t||{}).arrays||t.defaults)&&(o.name=[]),t.defaults&&(o.identifierValue="",p.Long?(n=new p.Long(0,0,!0),o.positiveIntValue=t.longs===String?n.toString():t.longs===Number?n.toNumber():n):o.positiveIntValue=t.longs===String?"0":0,p.Long?(n=new p.Long(0,0,!1),o.negativeIntValue=t.longs===String?n.toString():t.longs===Number?n.toNumber():n):o.negativeIntValue=t.longs===String?"0":0,o.doubleValue=0,t.bytes===String?o.stringValue="":(o.stringValue=[],t.bytes!==Array&&(o.stringValue=p.newBuffer(o.stringValue))),o.aggregateValue=""),e.name&&e.name.length){o.name=[];for(var r=0;r>>0,e.positiveIntValue.high>>>0).toNumber(!0):e.positiveIntValue),null!=e.negativeIntValue&&e.hasOwnProperty("negativeIntValue")&&("number"==typeof e.negativeIntValue?o.negativeIntValue=t.longs===String?String(e.negativeIntValue):e.negativeIntValue:o.negativeIntValue=t.longs===String?p.Long.prototype.toString.call(e.negativeIntValue):t.longs===Number?new p.LongBits(e.negativeIntValue.low>>>0,e.negativeIntValue.high>>>0).toNumber():e.negativeIntValue),null!=e.doubleValue&&e.hasOwnProperty("doubleValue")&&(o.doubleValue=t.json&&!isFinite(e.doubleValue)?String(e.doubleValue):e.doubleValue),null!=e.stringValue&&e.hasOwnProperty("stringValue")&&(o.stringValue=t.bytes===String?p.base64.encode(e.stringValue,0,e.stringValue.length):t.bytes===Array?Array.prototype.slice.call(e.stringValue):e.stringValue),null!=e.aggregateValue&&e.hasOwnProperty("aggregateValue")&&(o.aggregateValue=e.aggregateValue),o},R.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},R.NamePart=(Z.prototype.namePart="",Z.prototype.isExtension=!1,Z.create=function(e){return new Z(e)},Z.encode=function(e,t){return(t=t||i.create()).uint32(10).string(e.namePart),t.uint32(16).bool(e.isExtension),t},Z.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},Z.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new l.google.protobuf.UninterpretedOption.NamePart;e.pos>>3){case 1:o.namePart=e.string();break;case 2:o.isExtension=e.bool();break;default:e.skipType(7&r)}}if(!o.hasOwnProperty("namePart"))throw p.ProtocolError("missing required 'namePart'",{instance:o});if(o.hasOwnProperty("isExtension"))return o;throw p.ProtocolError("missing required 'isExtension'",{instance:o})},Z.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},Z.verify=function(e){return"object"!=typeof e||null===e?"object expected":p.isString(e.namePart)?"boolean"!=typeof e.isExtension?"isExtension: boolean expected":null:"namePart: string expected"},Z.fromObject=function(e){var t;return e instanceof l.google.protobuf.UninterpretedOption.NamePart?e:(t=new l.google.protobuf.UninterpretedOption.NamePart,null!=e.namePart&&(t.namePart=String(e.namePart)),null!=e.isExtension&&(t.isExtension=Boolean(e.isExtension)),t)},Z.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.namePart="",n.isExtension=!1),null!=e.namePart&&e.hasOwnProperty("namePart")&&(n.namePart=e.namePart),null!=e.isExtension&&e.hasOwnProperty("isExtension")&&(n.isExtension=e.isExtension),n},Z.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},Z),R),n.SourceCodeInfo=($.prototype.location=p.emptyArray,$.create=function(e){return new $(e)},$.encode=function(e,t){if(t=t||i.create(),null!=e.location&&e.location.length)for(var n=0;n>>3==1?(o.location&&o.location.length||(o.location=[]),o.location.push(l.google.protobuf.SourceCodeInfo.Location.decode(e,e.uint32()))):e.skipType(7&r)}return o},$.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},$.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.location&&e.hasOwnProperty("location")){if(!Array.isArray(e.location))return"location: array expected";for(var t=0;t>>3){case 1:if(o.path&&o.path.length||(o.path=[]),2==(7&r))for(var i=e.uint32()+e.pos;e.pos>>3==1?(o.annotation&&o.annotation.length||(o.annotation=[]),o.annotation.push(l.google.protobuf.GeneratedCodeInfo.Annotation.decode(e,e.uint32()))):e.skipType(7&r)}return o},ee.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},ee.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.annotation&&e.hasOwnProperty("annotation")){if(!Array.isArray(e.annotation))return"annotation: array expected";for(var t=0;t>>3){case 1:if(o.path&&o.path.length||(o.path=[]),2==(7&r))for(var i=e.uint32()+e.pos;e.pos>>3){case 1:o.expression=e.string();break;case 2:o.title=e.string();break;case 3:o.description=e.string();break;case 4:o.location=e.string();break;default:e.skipType(7&r)}}return o},V.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},V.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.expression&&e.hasOwnProperty("expression")&&!p.isString(e.expression)?"expression: string expected":null!=e.title&&e.hasOwnProperty("title")&&!p.isString(e.title)?"title: string expected":null!=e.description&&e.hasOwnProperty("description")&&!p.isString(e.description)?"description: string expected":null!=e.location&&e.hasOwnProperty("location")&&!p.isString(e.location)?"location: string expected":null},V.fromObject=function(e){var t;return e instanceof l.google.type.Expr?e:(t=new l.google.type.Expr,null!=e.expression&&(t.expression=String(e.expression)),null!=e.title&&(t.title=String(e.title)),null!=e.description&&(t.description=String(e.description)),null!=e.location&&(t.location=String(e.location)),t)},V.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.expression="",n.title="",n.description="",n.location=""),null!=e.expression&&e.hasOwnProperty("expression")&&(n.expression=e.expression),null!=e.title&&e.hasOwnProperty("title")&&(n.title=e.title),null!=e.description&&e.hasOwnProperty("description")&&(n.description=e.description),null!=e.location&&e.hasOwnProperty("location")&&(n.location=e.location),n},V.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},V),r),F),l}); \ No newline at end of file diff --git a/node_modules/google-gax/build/protos/iam_service.json b/node_modules/google-gax/build/protos/iam_service.json new file mode 100644 index 0000000..f70405c --- /dev/null +++ b/node_modules/google-gax/build/protos/iam_service.json @@ -0,0 +1 @@ +{"nested":{"google":{"nested":{"iam":{"nested":{"v1":{"options":{"cc_enable_arenas":true,"csharp_namespace":"Google.Cloud.Iam.V1","go_package":"google.golang.org/genproto/googleapis/iam/v1;iam","java_multiple_files":true,"java_outer_classname":"PolicyProto","java_package":"com.google.iam.v1","php_namespace":"Google\\Cloud\\Iam\\V1"},"nested":{"IAMPolicy":{"options":{"(google.api.default_host)":"iam-meta-api.googleapis.com"},"methods":{"SetIamPolicy":{"requestType":"SetIamPolicyRequest","responseType":"Policy","options":{"(google.api.http).post":"/v1/{resource=**}:setIamPolicy","(google.api.http).body":"*"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{resource=**}:setIamPolicy","body":"*"}}]},"GetIamPolicy":{"requestType":"GetIamPolicyRequest","responseType":"Policy","options":{"(google.api.http).post":"/v1/{resource=**}:getIamPolicy","(google.api.http).body":"*"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{resource=**}:getIamPolicy","body":"*"}}]},"TestIamPermissions":{"requestType":"TestIamPermissionsRequest","responseType":"TestIamPermissionsResponse","options":{"(google.api.http).post":"/v1/{resource=**}:testIamPermissions","(google.api.http).body":"*"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{resource=**}:testIamPermissions","body":"*"}}]}}},"SetIamPolicyRequest":{"fields":{"resource":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"*"}},"policy":{"type":"Policy","id":2,"options":{"(google.api.field_behavior)":"REQUIRED"}}}},"GetIamPolicyRequest":{"fields":{"resource":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"*"}},"options":{"type":"GetPolicyOptions","id":2}}},"TestIamPermissionsRequest":{"fields":{"resource":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"*"}},"permissions":{"rule":"repeated","type":"string","id":2,"options":{"(google.api.field_behavior)":"REQUIRED"}}}},"TestIamPermissionsResponse":{"fields":{"permissions":{"rule":"repeated","type":"string","id":1}}},"GetPolicyOptions":{"fields":{"requestedPolicyVersion":{"type":"int32","id":1}}},"Policy":{"fields":{"version":{"type":"int32","id":1},"bindings":{"rule":"repeated","type":"Binding","id":4},"etag":{"type":"bytes","id":3}}},"Binding":{"fields":{"role":{"type":"string","id":1},"members":{"rule":"repeated","type":"string","id":2},"condition":{"type":"google.type.Expr","id":3}}},"PolicyDelta":{"fields":{"bindingDeltas":{"rule":"repeated","type":"BindingDelta","id":1},"auditConfigDeltas":{"rule":"repeated","type":"AuditConfigDelta","id":2}}},"BindingDelta":{"fields":{"action":{"type":"Action","id":1},"role":{"type":"string","id":2},"member":{"type":"string","id":3},"condition":{"type":"google.type.Expr","id":4}},"nested":{"Action":{"values":{"ACTION_UNSPECIFIED":0,"ADD":1,"REMOVE":2}}}},"AuditConfigDelta":{"fields":{"action":{"type":"Action","id":1},"service":{"type":"string","id":2},"exemptedMember":{"type":"string","id":3},"logType":{"type":"string","id":4}},"nested":{"Action":{"values":{"ACTION_UNSPECIFIED":0,"ADD":1,"REMOVE":2}}}},"logging":{"options":{"csharp_namespace":"Google.Cloud.Iam.V1.Logging","go_package":"google.golang.org/genproto/googleapis/iam/v1/logging;logging","java_multiple_files":true,"java_outer_classname":"AuditDataProto","java_package":"com.google.iam.v1.logging"},"nested":{"AuditData":{"fields":{"policyDelta":{"type":"google.iam.v1.PolicyDelta","id":2}}}}}}}}},"api":{"options":{"go_package":"google.golang.org/genproto/googleapis/api/annotations;annotations","java_multiple_files":true,"java_outer_classname":"ResourceProto","java_package":"com.google.api","objc_class_prefix":"GAPI","cc_enable_arenas":true},"nested":{"http":{"type":"HttpRule","id":72295728,"extend":"google.protobuf.MethodOptions"},"Http":{"fields":{"rules":{"rule":"repeated","type":"HttpRule","id":1},"fullyDecodeReservedExpansion":{"type":"bool","id":2}}},"HttpRule":{"oneofs":{"pattern":{"oneof":["get","put","post","delete","patch","custom"]}},"fields":{"selector":{"type":"string","id":1},"get":{"type":"string","id":2},"put":{"type":"string","id":3},"post":{"type":"string","id":4},"delete":{"type":"string","id":5},"patch":{"type":"string","id":6},"custom":{"type":"CustomHttpPattern","id":8},"body":{"type":"string","id":7},"responseBody":{"type":"string","id":12},"additionalBindings":{"rule":"repeated","type":"HttpRule","id":11}}},"CustomHttpPattern":{"fields":{"kind":{"type":"string","id":1},"path":{"type":"string","id":2}}},"methodSignature":{"rule":"repeated","type":"string","id":1051,"extend":"google.protobuf.MethodOptions"},"defaultHost":{"type":"string","id":1049,"extend":"google.protobuf.ServiceOptions"},"oauthScopes":{"type":"string","id":1050,"extend":"google.protobuf.ServiceOptions"},"fieldBehavior":{"rule":"repeated","type":"google.api.FieldBehavior","id":1052,"extend":"google.protobuf.FieldOptions"},"FieldBehavior":{"values":{"FIELD_BEHAVIOR_UNSPECIFIED":0,"OPTIONAL":1,"REQUIRED":2,"OUTPUT_ONLY":3,"INPUT_ONLY":4,"IMMUTABLE":5}},"resourceReference":{"type":"google.api.ResourceReference","id":1055,"extend":"google.protobuf.FieldOptions"},"resourceDefinition":{"rule":"repeated","type":"google.api.ResourceDescriptor","id":1053,"extend":"google.protobuf.FileOptions"},"resource":{"type":"google.api.ResourceDescriptor","id":1053,"extend":"google.protobuf.MessageOptions"},"ResourceDescriptor":{"fields":{"type":{"type":"string","id":1},"pattern":{"rule":"repeated","type":"string","id":2},"nameField":{"type":"string","id":3},"history":{"type":"History","id":4},"plural":{"type":"string","id":5},"singular":{"type":"string","id":6}},"nested":{"History":{"values":{"HISTORY_UNSPECIFIED":0,"ORIGINALLY_SINGLE_PATTERN":1,"FUTURE_MULTI_PATTERN":2}}}},"ResourceReference":{"fields":{"type":{"type":"string","id":1},"childType":{"type":"string","id":2}}}}},"protobuf":{"options":{"go_package":"github.com/golang/protobuf/protoc-gen-go/descriptor;descriptor","java_package":"com.google.protobuf","java_outer_classname":"DescriptorProtos","csharp_namespace":"Google.Protobuf.Reflection","objc_class_prefix":"GPB","cc_enable_arenas":true,"optimize_for":"SPEED"},"nested":{"FileDescriptorSet":{"fields":{"file":{"rule":"repeated","type":"FileDescriptorProto","id":1}}},"FileDescriptorProto":{"fields":{"name":{"type":"string","id":1},"package":{"type":"string","id":2},"dependency":{"rule":"repeated","type":"string","id":3},"publicDependency":{"rule":"repeated","type":"int32","id":10,"options":{"packed":false}},"weakDependency":{"rule":"repeated","type":"int32","id":11,"options":{"packed":false}},"messageType":{"rule":"repeated","type":"DescriptorProto","id":4},"enumType":{"rule":"repeated","type":"EnumDescriptorProto","id":5},"service":{"rule":"repeated","type":"ServiceDescriptorProto","id":6},"extension":{"rule":"repeated","type":"FieldDescriptorProto","id":7},"options":{"type":"FileOptions","id":8},"sourceCodeInfo":{"type":"SourceCodeInfo","id":9},"syntax":{"type":"string","id":12}}},"DescriptorProto":{"fields":{"name":{"type":"string","id":1},"field":{"rule":"repeated","type":"FieldDescriptorProto","id":2},"extension":{"rule":"repeated","type":"FieldDescriptorProto","id":6},"nestedType":{"rule":"repeated","type":"DescriptorProto","id":3},"enumType":{"rule":"repeated","type":"EnumDescriptorProto","id":4},"extensionRange":{"rule":"repeated","type":"ExtensionRange","id":5},"oneofDecl":{"rule":"repeated","type":"OneofDescriptorProto","id":8},"options":{"type":"MessageOptions","id":7},"reservedRange":{"rule":"repeated","type":"ReservedRange","id":9},"reservedName":{"rule":"repeated","type":"string","id":10}},"nested":{"ExtensionRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2},"options":{"type":"ExtensionRangeOptions","id":3}}},"ReservedRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2}}}}},"ExtensionRangeOptions":{"fields":{"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]]},"FieldDescriptorProto":{"fields":{"name":{"type":"string","id":1},"number":{"type":"int32","id":3},"label":{"type":"Label","id":4},"type":{"type":"Type","id":5},"typeName":{"type":"string","id":6},"extendee":{"type":"string","id":2},"defaultValue":{"type":"string","id":7},"oneofIndex":{"type":"int32","id":9},"jsonName":{"type":"string","id":10},"options":{"type":"FieldOptions","id":8},"proto3Optional":{"type":"bool","id":17}},"nested":{"Type":{"values":{"TYPE_DOUBLE":1,"TYPE_FLOAT":2,"TYPE_INT64":3,"TYPE_UINT64":4,"TYPE_INT32":5,"TYPE_FIXED64":6,"TYPE_FIXED32":7,"TYPE_BOOL":8,"TYPE_STRING":9,"TYPE_GROUP":10,"TYPE_MESSAGE":11,"TYPE_BYTES":12,"TYPE_UINT32":13,"TYPE_ENUM":14,"TYPE_SFIXED32":15,"TYPE_SFIXED64":16,"TYPE_SINT32":17,"TYPE_SINT64":18}},"Label":{"values":{"LABEL_OPTIONAL":1,"LABEL_REQUIRED":2,"LABEL_REPEATED":3}}}},"OneofDescriptorProto":{"fields":{"name":{"type":"string","id":1},"options":{"type":"OneofOptions","id":2}}},"EnumDescriptorProto":{"fields":{"name":{"type":"string","id":1},"value":{"rule":"repeated","type":"EnumValueDescriptorProto","id":2},"options":{"type":"EnumOptions","id":3},"reservedRange":{"rule":"repeated","type":"EnumReservedRange","id":4},"reservedName":{"rule":"repeated","type":"string","id":5}},"nested":{"EnumReservedRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2}}}}},"EnumValueDescriptorProto":{"fields":{"name":{"type":"string","id":1},"number":{"type":"int32","id":2},"options":{"type":"EnumValueOptions","id":3}}},"ServiceDescriptorProto":{"fields":{"name":{"type":"string","id":1},"method":{"rule":"repeated","type":"MethodDescriptorProto","id":2},"options":{"type":"ServiceOptions","id":3}}},"MethodDescriptorProto":{"fields":{"name":{"type":"string","id":1},"inputType":{"type":"string","id":2},"outputType":{"type":"string","id":3},"options":{"type":"MethodOptions","id":4},"clientStreaming":{"type":"bool","id":5,"options":{"default":false}},"serverStreaming":{"type":"bool","id":6,"options":{"default":false}}}},"FileOptions":{"fields":{"javaPackage":{"type":"string","id":1},"javaOuterClassname":{"type":"string","id":8},"javaMultipleFiles":{"type":"bool","id":10,"options":{"default":false}},"javaGenerateEqualsAndHash":{"type":"bool","id":20,"options":{"deprecated":true}},"javaStringCheckUtf8":{"type":"bool","id":27,"options":{"default":false}},"optimizeFor":{"type":"OptimizeMode","id":9,"options":{"default":"SPEED"}},"goPackage":{"type":"string","id":11},"ccGenericServices":{"type":"bool","id":16,"options":{"default":false}},"javaGenericServices":{"type":"bool","id":17,"options":{"default":false}},"pyGenericServices":{"type":"bool","id":18,"options":{"default":false}},"phpGenericServices":{"type":"bool","id":42,"options":{"default":false}},"deprecated":{"type":"bool","id":23,"options":{"default":false}},"ccEnableArenas":{"type":"bool","id":31,"options":{"default":true}},"objcClassPrefix":{"type":"string","id":36},"csharpNamespace":{"type":"string","id":37},"swiftPrefix":{"type":"string","id":39},"phpClassPrefix":{"type":"string","id":40},"phpNamespace":{"type":"string","id":41},"phpMetadataNamespace":{"type":"string","id":44},"rubyPackage":{"type":"string","id":45},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"reserved":[[38,38]],"nested":{"OptimizeMode":{"values":{"SPEED":1,"CODE_SIZE":2,"LITE_RUNTIME":3}}}},"MessageOptions":{"fields":{"messageSetWireFormat":{"type":"bool","id":1,"options":{"default":false}},"noStandardDescriptorAccessor":{"type":"bool","id":2,"options":{"default":false}},"deprecated":{"type":"bool","id":3,"options":{"default":false}},"mapEntry":{"type":"bool","id":7},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"reserved":[[8,8],[9,9]]},"FieldOptions":{"fields":{"ctype":{"type":"CType","id":1,"options":{"default":"STRING"}},"packed":{"type":"bool","id":2},"jstype":{"type":"JSType","id":6,"options":{"default":"JS_NORMAL"}},"lazy":{"type":"bool","id":5,"options":{"default":false}},"deprecated":{"type":"bool","id":3,"options":{"default":false}},"weak":{"type":"bool","id":10,"options":{"default":false}},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"reserved":[[4,4]],"nested":{"CType":{"values":{"STRING":0,"CORD":1,"STRING_PIECE":2}},"JSType":{"values":{"JS_NORMAL":0,"JS_STRING":1,"JS_NUMBER":2}}}},"OneofOptions":{"fields":{"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]]},"EnumOptions":{"fields":{"allowAlias":{"type":"bool","id":2},"deprecated":{"type":"bool","id":3,"options":{"default":false}},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"reserved":[[5,5]]},"EnumValueOptions":{"fields":{"deprecated":{"type":"bool","id":1,"options":{"default":false}},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]]},"ServiceOptions":{"fields":{"deprecated":{"type":"bool","id":33,"options":{"default":false}},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]]},"MethodOptions":{"fields":{"deprecated":{"type":"bool","id":33,"options":{"default":false}},"idempotencyLevel":{"type":"IdempotencyLevel","id":34,"options":{"default":"IDEMPOTENCY_UNKNOWN"}},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"nested":{"IdempotencyLevel":{"values":{"IDEMPOTENCY_UNKNOWN":0,"NO_SIDE_EFFECTS":1,"IDEMPOTENT":2}}}},"UninterpretedOption":{"fields":{"name":{"rule":"repeated","type":"NamePart","id":2},"identifierValue":{"type":"string","id":3},"positiveIntValue":{"type":"uint64","id":4},"negativeIntValue":{"type":"int64","id":5},"doubleValue":{"type":"double","id":6},"stringValue":{"type":"bytes","id":7},"aggregateValue":{"type":"string","id":8}},"nested":{"NamePart":{"fields":{"namePart":{"rule":"required","type":"string","id":1},"isExtension":{"rule":"required","type":"bool","id":2}}}}},"SourceCodeInfo":{"fields":{"location":{"rule":"repeated","type":"Location","id":1}},"nested":{"Location":{"fields":{"path":{"rule":"repeated","type":"int32","id":1},"span":{"rule":"repeated","type":"int32","id":2},"leadingComments":{"type":"string","id":3},"trailingComments":{"type":"string","id":4},"leadingDetachedComments":{"rule":"repeated","type":"string","id":6}}}}},"GeneratedCodeInfo":{"fields":{"annotation":{"rule":"repeated","type":"Annotation","id":1}},"nested":{"Annotation":{"fields":{"path":{"rule":"repeated","type":"int32","id":1},"sourceFile":{"type":"string","id":2},"begin":{"type":"int32","id":3},"end":{"type":"int32","id":4}}}}}}},"type":{"options":{"go_package":"google.golang.org/genproto/googleapis/type/expr;expr","java_multiple_files":true,"java_outer_classname":"ExprProto","java_package":"com.google.type","objc_class_prefix":"GTP"},"nested":{"Expr":{"fields":{"expression":{"type":"string","id":1},"title":{"type":"string","id":2},"description":{"type":"string","id":3},"location":{"type":"string","id":4}}}}}}}}} \ No newline at end of file diff --git a/node_modules/google-gax/build/protos/locations.d.ts b/node_modules/google-gax/build/protos/locations.d.ts new file mode 100644 index 0000000..501ddb2 --- /dev/null +++ b/node_modules/google-gax/build/protos/locations.d.ts @@ -0,0 +1,4060 @@ +/** + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as $protobuf from "protobufjs"; +import Long = require('long'); +/** Namespace google. */ +export namespace google { + + /** Namespace cloud. */ + namespace cloud { + + /** Namespace location. */ + namespace location { + + /** Represents a Locations */ + class Locations extends $protobuf.rpc.Service { + + /** + * Constructs a new Locations service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new Locations service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): Locations; + + /** + * Calls ListLocations. + * @param request ListLocationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListLocationsResponse + */ + public listLocations(request: google.cloud.location.IListLocationsRequest, callback: google.cloud.location.Locations.ListLocationsCallback): void; + + /** + * Calls ListLocations. + * @param request ListLocationsRequest message or plain object + * @returns Promise + */ + public listLocations(request: google.cloud.location.IListLocationsRequest): Promise; + + /** + * Calls GetLocation. + * @param request GetLocationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Location + */ + public getLocation(request: google.cloud.location.IGetLocationRequest, callback: google.cloud.location.Locations.GetLocationCallback): void; + + /** + * Calls GetLocation. + * @param request GetLocationRequest message or plain object + * @returns Promise + */ + public getLocation(request: google.cloud.location.IGetLocationRequest): Promise; + } + + namespace Locations { + + /** + * Callback as used by {@link google.cloud.location.Locations#listLocations}. + * @param error Error, if any + * @param [response] ListLocationsResponse + */ + type ListLocationsCallback = (error: (Error|null), response?: google.cloud.location.ListLocationsResponse) => void; + + /** + * Callback as used by {@link google.cloud.location.Locations#getLocation}. + * @param error Error, if any + * @param [response] Location + */ + type GetLocationCallback = (error: (Error|null), response?: google.cloud.location.Location) => void; + } + + /** Properties of a ListLocationsRequest. */ + interface IListLocationsRequest { + + /** ListLocationsRequest name */ + name?: (string|null); + + /** ListLocationsRequest filter */ + filter?: (string|null); + + /** ListLocationsRequest pageSize */ + pageSize?: (number|null); + + /** ListLocationsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListLocationsRequest. */ + class ListLocationsRequest implements IListLocationsRequest { + + /** + * Constructs a new ListLocationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.location.IListLocationsRequest); + + /** ListLocationsRequest name. */ + public name: string; + + /** ListLocationsRequest filter. */ + public filter: string; + + /** ListLocationsRequest pageSize. */ + public pageSize: number; + + /** ListLocationsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a new ListLocationsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListLocationsRequest instance + */ + public static create(properties?: google.cloud.location.IListLocationsRequest): google.cloud.location.ListLocationsRequest; + + /** + * Encodes the specified ListLocationsRequest message. Does not implicitly {@link google.cloud.location.ListLocationsRequest.verify|verify} messages. + * @param message ListLocationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.location.IListLocationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListLocationsRequest message, length delimited. Does not implicitly {@link google.cloud.location.ListLocationsRequest.verify|verify} messages. + * @param message ListLocationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.location.IListLocationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListLocationsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListLocationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.location.ListLocationsRequest; + + /** + * Decodes a ListLocationsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListLocationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.location.ListLocationsRequest; + + /** + * Verifies a ListLocationsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListLocationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListLocationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.location.ListLocationsRequest; + + /** + * Creates a plain object from a ListLocationsRequest message. Also converts values to other types if specified. + * @param message ListLocationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.location.ListLocationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListLocationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a ListLocationsResponse. */ + interface IListLocationsResponse { + + /** ListLocationsResponse locations */ + locations?: (google.cloud.location.ILocation[]|null); + + /** ListLocationsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListLocationsResponse. */ + class ListLocationsResponse implements IListLocationsResponse { + + /** + * Constructs a new ListLocationsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.location.IListLocationsResponse); + + /** ListLocationsResponse locations. */ + public locations: google.cloud.location.ILocation[]; + + /** ListLocationsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a new ListLocationsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ListLocationsResponse instance + */ + public static create(properties?: google.cloud.location.IListLocationsResponse): google.cloud.location.ListLocationsResponse; + + /** + * Encodes the specified ListLocationsResponse message. Does not implicitly {@link google.cloud.location.ListLocationsResponse.verify|verify} messages. + * @param message ListLocationsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.location.IListLocationsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListLocationsResponse message, length delimited. Does not implicitly {@link google.cloud.location.ListLocationsResponse.verify|verify} messages. + * @param message ListLocationsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.location.IListLocationsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListLocationsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListLocationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.location.ListLocationsResponse; + + /** + * Decodes a ListLocationsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListLocationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.location.ListLocationsResponse; + + /** + * Verifies a ListLocationsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListLocationsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListLocationsResponse + */ + public static fromObject(object: { [k: string]: any }): google.cloud.location.ListLocationsResponse; + + /** + * Creates a plain object from a ListLocationsResponse message. Also converts values to other types if specified. + * @param message ListLocationsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.location.ListLocationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListLocationsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a GetLocationRequest. */ + interface IGetLocationRequest { + + /** GetLocationRequest name */ + name?: (string|null); + } + + /** Represents a GetLocationRequest. */ + class GetLocationRequest implements IGetLocationRequest { + + /** + * Constructs a new GetLocationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.location.IGetLocationRequest); + + /** GetLocationRequest name. */ + public name: string; + + /** + * Creates a new GetLocationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetLocationRequest instance + */ + public static create(properties?: google.cloud.location.IGetLocationRequest): google.cloud.location.GetLocationRequest; + + /** + * Encodes the specified GetLocationRequest message. Does not implicitly {@link google.cloud.location.GetLocationRequest.verify|verify} messages. + * @param message GetLocationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.location.IGetLocationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetLocationRequest message, length delimited. Does not implicitly {@link google.cloud.location.GetLocationRequest.verify|verify} messages. + * @param message GetLocationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.location.IGetLocationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetLocationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetLocationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.location.GetLocationRequest; + + /** + * Decodes a GetLocationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetLocationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.location.GetLocationRequest; + + /** + * Verifies a GetLocationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetLocationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetLocationRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.location.GetLocationRequest; + + /** + * Creates a plain object from a GetLocationRequest message. Also converts values to other types if specified. + * @param message GetLocationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.location.GetLocationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetLocationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a Location. */ + interface ILocation { + + /** Location name */ + name?: (string|null); + + /** Location locationId */ + locationId?: (string|null); + + /** Location displayName */ + displayName?: (string|null); + + /** Location labels */ + labels?: ({ [k: string]: string }|null); + + /** Location metadata */ + metadata?: (google.protobuf.IAny|null); + } + + /** Represents a Location. */ + class Location implements ILocation { + + /** + * Constructs a new Location. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.location.ILocation); + + /** Location name. */ + public name: string; + + /** Location locationId. */ + public locationId: string; + + /** Location displayName. */ + public displayName: string; + + /** Location labels. */ + public labels: { [k: string]: string }; + + /** Location metadata. */ + public metadata?: (google.protobuf.IAny|null); + + /** + * Creates a new Location instance using the specified properties. + * @param [properties] Properties to set + * @returns Location instance + */ + public static create(properties?: google.cloud.location.ILocation): google.cloud.location.Location; + + /** + * Encodes the specified Location message. Does not implicitly {@link google.cloud.location.Location.verify|verify} messages. + * @param message Location message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.location.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Location message, length delimited. Does not implicitly {@link google.cloud.location.Location.verify|verify} messages. + * @param message Location message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.location.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Location message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Location + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.location.Location; + + /** + * Decodes a Location message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Location + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.location.Location; + + /** + * Verifies a Location message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Location + */ + public static fromObject(object: { [k: string]: any }): google.cloud.location.Location; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @param message Location + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.location.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Location to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + } + + /** Namespace api. */ + namespace api { + + /** Properties of a Http. */ + interface IHttp { + + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); + + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); + } + + /** Represents a Http. */ + class Http implements IHttp { + + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); + + /** Http rules. */ + public rules: google.api.IHttpRule[]; + + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; + + /** + * Creates a new Http instance using the specified properties. + * @param [properties] Properties to set + * @returns Http instance + */ + public static create(properties?: google.api.IHttp): google.api.Http; + + /** + * Encodes the specified Http message. Does not implicitly {@link google.api.Http.verify|verify} messages. + * @param message Http message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Http message, length delimited. Does not implicitly {@link google.api.Http.verify|verify} messages. + * @param message Http message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Http message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Http + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Http; + + /** + * Decodes a Http message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Http + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Http; + + /** + * Verifies a Http message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a HttpRule. */ + interface IHttpRule { + + /** HttpRule selector */ + selector?: (string|null); + + /** HttpRule get */ + get?: (string|null); + + /** HttpRule put */ + put?: (string|null); + + /** HttpRule post */ + post?: (string|null); + + /** HttpRule delete */ + "delete"?: (string|null); + + /** HttpRule patch */ + patch?: (string|null); + + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body */ + body?: (string|null); + + /** HttpRule responseBody */ + responseBody?: (string|null); + + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); + } + + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { + + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); + + /** HttpRule selector. */ + public selector: string; + + /** HttpRule get. */ + public get?: (string|null); + + /** HttpRule put. */ + public put?: (string|null); + + /** HttpRule post. */ + public post?: (string|null); + + /** HttpRule delete. */ + public delete?: (string|null); + + /** HttpRule patch. */ + public patch?: (string|null); + + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body. */ + public body: string; + + /** HttpRule responseBody. */ + public responseBody: string; + + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; + + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + + /** + * Creates a new HttpRule instance using the specified properties. + * @param [properties] Properties to set + * @returns HttpRule instance + */ + public static create(properties?: google.api.IHttpRule): google.api.HttpRule; + + /** + * Encodes the specified HttpRule message. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. + * @param message HttpRule message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified HttpRule message, length delimited. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. + * @param message HttpRule message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a HttpRule message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns HttpRule + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.HttpRule; + + /** + * Decodes a HttpRule message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns HttpRule + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.HttpRule; + + /** + * Verifies a HttpRule message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { + + /** CustomHttpPattern kind */ + kind?: (string|null); + + /** CustomHttpPattern path */ + path?: (string|null); + } + + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { + + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); + + /** CustomHttpPattern kind. */ + public kind: string; + + /** CustomHttpPattern path. */ + public path: string; + + /** + * Creates a new CustomHttpPattern instance using the specified properties. + * @param [properties] Properties to set + * @returns CustomHttpPattern instance + */ + public static create(properties?: google.api.ICustomHttpPattern): google.api.CustomHttpPattern; + + /** + * Encodes the specified CustomHttpPattern message. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. + * @param message CustomHttpPattern message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CustomHttpPattern message, length delimited. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. + * @param message CustomHttpPattern message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CustomHttpPattern message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CustomHttpPattern + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.CustomHttpPattern; + + /** + * Decodes a CustomHttpPattern message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CustomHttpPattern + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.CustomHttpPattern; + + /** + * Verifies a CustomHttpPattern message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Namespace protobuf. */ + namespace protobuf { + + /** Properties of a FileDescriptorSet. */ + interface IFileDescriptorSet { + + /** FileDescriptorSet file */ + file?: (google.protobuf.IFileDescriptorProto[]|null); + } + + /** Represents a FileDescriptorSet. */ + class FileDescriptorSet implements IFileDescriptorSet { + + /** + * Constructs a new FileDescriptorSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorSet); + + /** FileDescriptorSet file. */ + public file: google.protobuf.IFileDescriptorProto[]; + + /** + * Creates a new FileDescriptorSet instance using the specified properties. + * @param [properties] Properties to set + * @returns FileDescriptorSet instance + */ + public static create(properties?: google.protobuf.IFileDescriptorSet): google.protobuf.FileDescriptorSet; + + /** + * Encodes the specified FileDescriptorSet message. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. + * @param message FileDescriptorSet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FileDescriptorSet message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. + * @param message FileDescriptorSet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FileDescriptorSet message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FileDescriptorSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorSet; + + /** + * Decodes a FileDescriptorSet message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FileDescriptorSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorSet; + + /** + * Verifies a FileDescriptorSet message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; + + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @param message FileDescriptorSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a FileDescriptorProto. */ + interface IFileDescriptorProto { + + /** FileDescriptorProto name */ + name?: (string|null); + + /** FileDescriptorProto package */ + "package"?: (string|null); + + /** FileDescriptorProto dependency */ + dependency?: (string[]|null); + + /** FileDescriptorProto publicDependency */ + publicDependency?: (number[]|null); + + /** FileDescriptorProto weakDependency */ + weakDependency?: (number[]|null); + + /** FileDescriptorProto messageType */ + messageType?: (google.protobuf.IDescriptorProto[]|null); + + /** FileDescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** FileDescriptorProto service */ + service?: (google.protobuf.IServiceDescriptorProto[]|null); + + /** FileDescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** FileDescriptorProto options */ + options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo */ + sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax */ + syntax?: (string|null); + } + + /** Represents a FileDescriptorProto. */ + class FileDescriptorProto implements IFileDescriptorProto { + + /** + * Constructs a new FileDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorProto); + + /** FileDescriptorProto name. */ + public name: string; + + /** FileDescriptorProto package. */ + public package: string; + + /** FileDescriptorProto dependency. */ + public dependency: string[]; + + /** FileDescriptorProto publicDependency. */ + public publicDependency: number[]; + + /** FileDescriptorProto weakDependency. */ + public weakDependency: number[]; + + /** FileDescriptorProto messageType. */ + public messageType: google.protobuf.IDescriptorProto[]; + + /** FileDescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** FileDescriptorProto service. */ + public service: google.protobuf.IServiceDescriptorProto[]; + + /** FileDescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** FileDescriptorProto options. */ + public options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo. */ + public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax. */ + public syntax: string; + + /** + * Creates a new FileDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns FileDescriptorProto instance + */ + public static create(properties?: google.protobuf.IFileDescriptorProto): google.protobuf.FileDescriptorProto; + + /** + * Encodes the specified FileDescriptorProto message. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. + * @param message FileDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FileDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. + * @param message FileDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FileDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FileDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorProto; + + /** + * Decodes a FileDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FileDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorProto; + + /** + * Verifies a FileDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; + + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @param message FileDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a DescriptorProto. */ + interface IDescriptorProto { + + /** DescriptorProto name */ + name?: (string|null); + + /** DescriptorProto field */ + field?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto nestedType */ + nestedType?: (google.protobuf.IDescriptorProto[]|null); + + /** DescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** DescriptorProto extensionRange */ + extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); + + /** DescriptorProto oneofDecl */ + oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); + + /** DescriptorProto options */ + options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange */ + reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); + + /** DescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents a DescriptorProto. */ + class DescriptorProto implements IDescriptorProto { + + /** + * Constructs a new DescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDescriptorProto); + + /** DescriptorProto name. */ + public name: string; + + /** DescriptorProto field. */ + public field: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto nestedType. */ + public nestedType: google.protobuf.IDescriptorProto[]; + + /** DescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** DescriptorProto extensionRange. */ + public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; + + /** DescriptorProto oneofDecl. */ + public oneofDecl: google.protobuf.IOneofDescriptorProto[]; + + /** DescriptorProto options. */ + public options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange. */ + public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; + + /** DescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates a new DescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns DescriptorProto instance + */ + public static create(properties?: google.protobuf.IDescriptorProto): google.protobuf.DescriptorProto; + + /** + * Encodes the specified DescriptorProto message. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. + * @param message DescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. + * @param message DescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto; + + /** + * Decodes a DescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto; + + /** + * Verifies a DescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; + + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @param message DescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace DescriptorProto { + + /** Properties of an ExtensionRange. */ + interface IExtensionRange { + + /** ExtensionRange start */ + start?: (number|null); + + /** ExtensionRange end */ + end?: (number|null); + + /** ExtensionRange options */ + options?: (google.protobuf.IExtensionRangeOptions|null); + } + + /** Represents an ExtensionRange. */ + class ExtensionRange implements IExtensionRange { + + /** + * Constructs a new ExtensionRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); + + /** ExtensionRange start. */ + public start: number; + + /** ExtensionRange end. */ + public end: number; + + /** ExtensionRange options. */ + public options?: (google.protobuf.IExtensionRangeOptions|null); + + /** + * Creates a new ExtensionRange instance using the specified properties. + * @param [properties] Properties to set + * @returns ExtensionRange instance + */ + public static create(properties?: google.protobuf.DescriptorProto.IExtensionRange): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Encodes the specified ExtensionRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. + * @param message ExtensionRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExtensionRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. + * @param message ExtensionRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExtensionRange message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExtensionRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Decodes an ExtensionRange message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExtensionRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Verifies an ExtensionRange message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @param message ExtensionRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a ReservedRange. */ + interface IReservedRange { + + /** ReservedRange start */ + start?: (number|null); + + /** ReservedRange end */ + end?: (number|null); + } + + /** Represents a ReservedRange. */ + class ReservedRange implements IReservedRange { + + /** + * Constructs a new ReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); + + /** ReservedRange start. */ + public start: number; + + /** ReservedRange end. */ + public end: number; + + /** + * Creates a new ReservedRange instance using the specified properties. + * @param [properties] Properties to set + * @returns ReservedRange instance + */ + public static create(properties?: google.protobuf.DescriptorProto.IReservedRange): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Encodes the specified ReservedRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. + * @param message ReservedRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReservedRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. + * @param message ReservedRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReservedRange message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Decodes a ReservedRange message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Verifies a ReservedRange message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @param message ReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Properties of an ExtensionRangeOptions. */ + interface IExtensionRangeOptions { + + /** ExtensionRangeOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an ExtensionRangeOptions. */ + class ExtensionRangeOptions implements IExtensionRangeOptions { + + /** + * Constructs a new ExtensionRangeOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IExtensionRangeOptions); + + /** ExtensionRangeOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new ExtensionRangeOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns ExtensionRangeOptions instance + */ + public static create(properties?: google.protobuf.IExtensionRangeOptions): google.protobuf.ExtensionRangeOptions; + + /** + * Encodes the specified ExtensionRangeOptions message. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages. + * @param message ExtensionRangeOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IExtensionRangeOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExtensionRangeOptions message, length delimited. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages. + * @param message ExtensionRangeOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IExtensionRangeOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExtensionRangeOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExtensionRangeOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ExtensionRangeOptions; + + /** + * Decodes an ExtensionRangeOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExtensionRangeOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ExtensionRangeOptions; + + /** + * Verifies an ExtensionRangeOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRangeOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @param message ExtensionRangeOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a FieldDescriptorProto. */ + interface IFieldDescriptorProto { + + /** FieldDescriptorProto name */ + name?: (string|null); + + /** FieldDescriptorProto number */ + number?: (number|null); + + /** FieldDescriptorProto label */ + label?: (google.protobuf.FieldDescriptorProto.Label|null); + + /** FieldDescriptorProto type */ + type?: (google.protobuf.FieldDescriptorProto.Type|null); + + /** FieldDescriptorProto typeName */ + typeName?: (string|null); + + /** FieldDescriptorProto extendee */ + extendee?: (string|null); + + /** FieldDescriptorProto defaultValue */ + defaultValue?: (string|null); + + /** FieldDescriptorProto oneofIndex */ + oneofIndex?: (number|null); + + /** FieldDescriptorProto jsonName */ + jsonName?: (string|null); + + /** FieldDescriptorProto options */ + options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional */ + proto3Optional?: (boolean|null); + } + + /** Represents a FieldDescriptorProto. */ + class FieldDescriptorProto implements IFieldDescriptorProto { + + /** + * Constructs a new FieldDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldDescriptorProto); + + /** FieldDescriptorProto name. */ + public name: string; + + /** FieldDescriptorProto number. */ + public number: number; + + /** FieldDescriptorProto label. */ + public label: google.protobuf.FieldDescriptorProto.Label; + + /** FieldDescriptorProto type. */ + public type: google.protobuf.FieldDescriptorProto.Type; + + /** FieldDescriptorProto typeName. */ + public typeName: string; + + /** FieldDescriptorProto extendee. */ + public extendee: string; + + /** FieldDescriptorProto defaultValue. */ + public defaultValue: string; + + /** FieldDescriptorProto oneofIndex. */ + public oneofIndex: number; + + /** FieldDescriptorProto jsonName. */ + public jsonName: string; + + /** FieldDescriptorProto options. */ + public options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional. */ + public proto3Optional: boolean; + + /** + * Creates a new FieldDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns FieldDescriptorProto instance + */ + public static create(properties?: google.protobuf.IFieldDescriptorProto): google.protobuf.FieldDescriptorProto; + + /** + * Encodes the specified FieldDescriptorProto message. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. + * @param message FieldDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FieldDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. + * @param message FieldDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FieldDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FieldDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldDescriptorProto; + + /** + * Decodes a FieldDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FieldDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldDescriptorProto; + + /** + * Verifies a FieldDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @param message FieldDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace FieldDescriptorProto { + + /** Type enum. */ + enum Type { + TYPE_DOUBLE = 1, + TYPE_FLOAT = 2, + TYPE_INT64 = 3, + TYPE_UINT64 = 4, + TYPE_INT32 = 5, + TYPE_FIXED64 = 6, + TYPE_FIXED32 = 7, + TYPE_BOOL = 8, + TYPE_STRING = 9, + TYPE_GROUP = 10, + TYPE_MESSAGE = 11, + TYPE_BYTES = 12, + TYPE_UINT32 = 13, + TYPE_ENUM = 14, + TYPE_SFIXED32 = 15, + TYPE_SFIXED64 = 16, + TYPE_SINT32 = 17, + TYPE_SINT64 = 18 + } + + /** Label enum. */ + enum Label { + LABEL_OPTIONAL = 1, + LABEL_REQUIRED = 2, + LABEL_REPEATED = 3 + } + } + + /** Properties of an OneofDescriptorProto. */ + interface IOneofDescriptorProto { + + /** OneofDescriptorProto name */ + name?: (string|null); + + /** OneofDescriptorProto options */ + options?: (google.protobuf.IOneofOptions|null); + } + + /** Represents an OneofDescriptorProto. */ + class OneofDescriptorProto implements IOneofDescriptorProto { + + /** + * Constructs a new OneofDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofDescriptorProto); + + /** OneofDescriptorProto name. */ + public name: string; + + /** OneofDescriptorProto options. */ + public options?: (google.protobuf.IOneofOptions|null); + + /** + * Creates a new OneofDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns OneofDescriptorProto instance + */ + public static create(properties?: google.protobuf.IOneofDescriptorProto): google.protobuf.OneofDescriptorProto; + + /** + * Encodes the specified OneofDescriptorProto message. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. + * @param message OneofDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified OneofDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. + * @param message OneofDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an OneofDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns OneofDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofDescriptorProto; + + /** + * Decodes an OneofDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns OneofDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofDescriptorProto; + + /** + * Verifies an OneofDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; + + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @param message OneofDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of an EnumDescriptorProto. */ + interface IEnumDescriptorProto { + + /** EnumDescriptorProto name */ + name?: (string|null); + + /** EnumDescriptorProto value */ + value?: (google.protobuf.IEnumValueDescriptorProto[]|null); + + /** EnumDescriptorProto options */ + options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange */ + reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); + + /** EnumDescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents an EnumDescriptorProto. */ + class EnumDescriptorProto implements IEnumDescriptorProto { + + /** + * Constructs a new EnumDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumDescriptorProto); + + /** EnumDescriptorProto name. */ + public name: string; + + /** EnumDescriptorProto value. */ + public value: google.protobuf.IEnumValueDescriptorProto[]; + + /** EnumDescriptorProto options. */ + public options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange. */ + public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; + + /** EnumDescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates a new EnumDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumDescriptorProto instance + */ + public static create(properties?: google.protobuf.IEnumDescriptorProto): google.protobuf.EnumDescriptorProto; + + /** + * Encodes the specified EnumDescriptorProto message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. + * @param message EnumDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. + * @param message EnumDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto; + + /** + * Decodes an EnumDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto; + + /** + * Verifies an EnumDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; + + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @param message EnumDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace EnumDescriptorProto { + + /** Properties of an EnumReservedRange. */ + interface IEnumReservedRange { + + /** EnumReservedRange start */ + start?: (number|null); + + /** EnumReservedRange end */ + end?: (number|null); + } + + /** Represents an EnumReservedRange. */ + class EnumReservedRange implements IEnumReservedRange { + + /** + * Constructs a new EnumReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); + + /** EnumReservedRange start. */ + public start: number; + + /** EnumReservedRange end. */ + public end: number; + + /** + * Creates a new EnumReservedRange instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumReservedRange instance + */ + public static create(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Encodes the specified EnumReservedRange message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages. + * @param message EnumReservedRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.EnumDescriptorProto.IEnumReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumReservedRange message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages. + * @param message EnumReservedRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.EnumDescriptorProto.IEnumReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumReservedRange message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Decodes an EnumReservedRange message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Verifies an EnumReservedRange message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @param message EnumReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Properties of an EnumValueDescriptorProto. */ + interface IEnumValueDescriptorProto { + + /** EnumValueDescriptorProto name */ + name?: (string|null); + + /** EnumValueDescriptorProto number */ + number?: (number|null); + + /** EnumValueDescriptorProto options */ + options?: (google.protobuf.IEnumValueOptions|null); + } + + /** Represents an EnumValueDescriptorProto. */ + class EnumValueDescriptorProto implements IEnumValueDescriptorProto { + + /** + * Constructs a new EnumValueDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueDescriptorProto); + + /** EnumValueDescriptorProto name. */ + public name: string; + + /** EnumValueDescriptorProto number. */ + public number: number; + + /** EnumValueDescriptorProto options. */ + public options?: (google.protobuf.IEnumValueOptions|null); + + /** + * Creates a new EnumValueDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumValueDescriptorProto instance + */ + public static create(properties?: google.protobuf.IEnumValueDescriptorProto): google.protobuf.EnumValueDescriptorProto; + + /** + * Encodes the specified EnumValueDescriptorProto message. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. + * @param message EnumValueDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumValueDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. + * @param message EnumValueDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumValueDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumValueDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueDescriptorProto; + + /** + * Decodes an EnumValueDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumValueDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueDescriptorProto; + + /** + * Verifies an EnumValueDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; + + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @param message EnumValueDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a ServiceDescriptorProto. */ + interface IServiceDescriptorProto { + + /** ServiceDescriptorProto name */ + name?: (string|null); + + /** ServiceDescriptorProto method */ + method?: (google.protobuf.IMethodDescriptorProto[]|null); + + /** ServiceDescriptorProto options */ + options?: (google.protobuf.IServiceOptions|null); + } + + /** Represents a ServiceDescriptorProto. */ + class ServiceDescriptorProto implements IServiceDescriptorProto { + + /** + * Constructs a new ServiceDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceDescriptorProto); + + /** ServiceDescriptorProto name. */ + public name: string; + + /** ServiceDescriptorProto method. */ + public method: google.protobuf.IMethodDescriptorProto[]; + + /** ServiceDescriptorProto options. */ + public options?: (google.protobuf.IServiceOptions|null); + + /** + * Creates a new ServiceDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns ServiceDescriptorProto instance + */ + public static create(properties?: google.protobuf.IServiceDescriptorProto): google.protobuf.ServiceDescriptorProto; + + /** + * Encodes the specified ServiceDescriptorProto message. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. + * @param message ServiceDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ServiceDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. + * @param message ServiceDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ServiceDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ServiceDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceDescriptorProto; + + /** + * Decodes a ServiceDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ServiceDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceDescriptorProto; + + /** + * Verifies a ServiceDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @param message ServiceDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a MethodDescriptorProto. */ + interface IMethodDescriptorProto { + + /** MethodDescriptorProto name */ + name?: (string|null); + + /** MethodDescriptorProto inputType */ + inputType?: (string|null); + + /** MethodDescriptorProto outputType */ + outputType?: (string|null); + + /** MethodDescriptorProto options */ + options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming */ + clientStreaming?: (boolean|null); + + /** MethodDescriptorProto serverStreaming */ + serverStreaming?: (boolean|null); + } + + /** Represents a MethodDescriptorProto. */ + class MethodDescriptorProto implements IMethodDescriptorProto { + + /** + * Constructs a new MethodDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodDescriptorProto); + + /** MethodDescriptorProto name. */ + public name: string; + + /** MethodDescriptorProto inputType. */ + public inputType: string; + + /** MethodDescriptorProto outputType. */ + public outputType: string; + + /** MethodDescriptorProto options. */ + public options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming. */ + public clientStreaming: boolean; + + /** MethodDescriptorProto serverStreaming. */ + public serverStreaming: boolean; + + /** + * Creates a new MethodDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns MethodDescriptorProto instance + */ + public static create(properties?: google.protobuf.IMethodDescriptorProto): google.protobuf.MethodDescriptorProto; + + /** + * Encodes the specified MethodDescriptorProto message. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. + * @param message MethodDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MethodDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. + * @param message MethodDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MethodDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MethodDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodDescriptorProto; + + /** + * Decodes a MethodDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MethodDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodDescriptorProto; + + /** + * Verifies a MethodDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @param message MethodDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a FileOptions. */ + interface IFileOptions { + + /** FileOptions javaPackage */ + javaPackage?: (string|null); + + /** FileOptions javaOuterClassname */ + javaOuterClassname?: (string|null); + + /** FileOptions javaMultipleFiles */ + javaMultipleFiles?: (boolean|null); + + /** FileOptions javaGenerateEqualsAndHash */ + javaGenerateEqualsAndHash?: (boolean|null); + + /** FileOptions javaStringCheckUtf8 */ + javaStringCheckUtf8?: (boolean|null); + + /** FileOptions optimizeFor */ + optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); + + /** FileOptions goPackage */ + goPackage?: (string|null); + + /** FileOptions ccGenericServices */ + ccGenericServices?: (boolean|null); + + /** FileOptions javaGenericServices */ + javaGenericServices?: (boolean|null); + + /** FileOptions pyGenericServices */ + pyGenericServices?: (boolean|null); + + /** FileOptions phpGenericServices */ + phpGenericServices?: (boolean|null); + + /** FileOptions deprecated */ + deprecated?: (boolean|null); + + /** FileOptions ccEnableArenas */ + ccEnableArenas?: (boolean|null); + + /** FileOptions objcClassPrefix */ + objcClassPrefix?: (string|null); + + /** FileOptions csharpNamespace */ + csharpNamespace?: (string|null); + + /** FileOptions swiftPrefix */ + swiftPrefix?: (string|null); + + /** FileOptions phpClassPrefix */ + phpClassPrefix?: (string|null); + + /** FileOptions phpNamespace */ + phpNamespace?: (string|null); + + /** FileOptions phpMetadataNamespace */ + phpMetadataNamespace?: (string|null); + + /** FileOptions rubyPackage */ + rubyPackage?: (string|null); + + /** FileOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents a FileOptions. */ + class FileOptions implements IFileOptions { + + /** + * Constructs a new FileOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileOptions); + + /** FileOptions javaPackage. */ + public javaPackage: string; + + /** FileOptions javaOuterClassname. */ + public javaOuterClassname: string; + + /** FileOptions javaMultipleFiles. */ + public javaMultipleFiles: boolean; + + /** FileOptions javaGenerateEqualsAndHash. */ + public javaGenerateEqualsAndHash: boolean; + + /** FileOptions javaStringCheckUtf8. */ + public javaStringCheckUtf8: boolean; + + /** FileOptions optimizeFor. */ + public optimizeFor: google.protobuf.FileOptions.OptimizeMode; + + /** FileOptions goPackage. */ + public goPackage: string; + + /** FileOptions ccGenericServices. */ + public ccGenericServices: boolean; + + /** FileOptions javaGenericServices. */ + public javaGenericServices: boolean; + + /** FileOptions pyGenericServices. */ + public pyGenericServices: boolean; + + /** FileOptions phpGenericServices. */ + public phpGenericServices: boolean; + + /** FileOptions deprecated. */ + public deprecated: boolean; + + /** FileOptions ccEnableArenas. */ + public ccEnableArenas: boolean; + + /** FileOptions objcClassPrefix. */ + public objcClassPrefix: string; + + /** FileOptions csharpNamespace. */ + public csharpNamespace: string; + + /** FileOptions swiftPrefix. */ + public swiftPrefix: string; + + /** FileOptions phpClassPrefix. */ + public phpClassPrefix: string; + + /** FileOptions phpNamespace. */ + public phpNamespace: string; + + /** FileOptions phpMetadataNamespace. */ + public phpMetadataNamespace: string; + + /** FileOptions rubyPackage. */ + public rubyPackage: string; + + /** FileOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new FileOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns FileOptions instance + */ + public static create(properties?: google.protobuf.IFileOptions): google.protobuf.FileOptions; + + /** + * Encodes the specified FileOptions message. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. + * @param message FileOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FileOptions message, length delimited. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. + * @param message FileOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FileOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FileOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileOptions; + + /** + * Decodes a FileOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FileOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileOptions; + + /** + * Verifies a FileOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; + + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @param message FileOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace FileOptions { + + /** OptimizeMode enum. */ + enum OptimizeMode { + SPEED = 1, + CODE_SIZE = 2, + LITE_RUNTIME = 3 + } + } + + /** Properties of a MessageOptions. */ + interface IMessageOptions { + + /** MessageOptions messageSetWireFormat */ + messageSetWireFormat?: (boolean|null); + + /** MessageOptions noStandardDescriptorAccessor */ + noStandardDescriptorAccessor?: (boolean|null); + + /** MessageOptions deprecated */ + deprecated?: (boolean|null); + + /** MessageOptions mapEntry */ + mapEntry?: (boolean|null); + + /** MessageOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents a MessageOptions. */ + class MessageOptions implements IMessageOptions { + + /** + * Constructs a new MessageOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMessageOptions); + + /** MessageOptions messageSetWireFormat. */ + public messageSetWireFormat: boolean; + + /** MessageOptions noStandardDescriptorAccessor. */ + public noStandardDescriptorAccessor: boolean; + + /** MessageOptions deprecated. */ + public deprecated: boolean; + + /** MessageOptions mapEntry. */ + public mapEntry: boolean; + + /** MessageOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new MessageOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns MessageOptions instance + */ + public static create(properties?: google.protobuf.IMessageOptions): google.protobuf.MessageOptions; + + /** + * Encodes the specified MessageOptions message. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. + * @param message MessageOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MessageOptions message, length delimited. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. + * @param message MessageOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MessageOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MessageOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MessageOptions; + + /** + * Decodes a MessageOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MessageOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MessageOptions; + + /** + * Verifies a MessageOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MessageOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; + + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @param message MessageOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MessageOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a FieldOptions. */ + interface IFieldOptions { + + /** FieldOptions ctype */ + ctype?: (google.protobuf.FieldOptions.CType|null); + + /** FieldOptions packed */ + packed?: (boolean|null); + + /** FieldOptions jstype */ + jstype?: (google.protobuf.FieldOptions.JSType|null); + + /** FieldOptions lazy */ + lazy?: (boolean|null); + + /** FieldOptions deprecated */ + deprecated?: (boolean|null); + + /** FieldOptions weak */ + weak?: (boolean|null); + + /** FieldOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents a FieldOptions. */ + class FieldOptions implements IFieldOptions { + + /** + * Constructs a new FieldOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldOptions); + + /** FieldOptions ctype. */ + public ctype: google.protobuf.FieldOptions.CType; + + /** FieldOptions packed. */ + public packed: boolean; + + /** FieldOptions jstype. */ + public jstype: google.protobuf.FieldOptions.JSType; + + /** FieldOptions lazy. */ + public lazy: boolean; + + /** FieldOptions deprecated. */ + public deprecated: boolean; + + /** FieldOptions weak. */ + public weak: boolean; + + /** FieldOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new FieldOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns FieldOptions instance + */ + public static create(properties?: google.protobuf.IFieldOptions): google.protobuf.FieldOptions; + + /** + * Encodes the specified FieldOptions message. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. + * @param message FieldOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FieldOptions message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. + * @param message FieldOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FieldOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FieldOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions; + + /** + * Decodes a FieldOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FieldOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions; + + /** + * Verifies a FieldOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; + + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @param message FieldOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace FieldOptions { + + /** CType enum. */ + enum CType { + STRING = 0, + CORD = 1, + STRING_PIECE = 2 + } + + /** JSType enum. */ + enum JSType { + JS_NORMAL = 0, + JS_STRING = 1, + JS_NUMBER = 2 + } + } + + /** Properties of an OneofOptions. */ + interface IOneofOptions { + + /** OneofOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an OneofOptions. */ + class OneofOptions implements IOneofOptions { + + /** + * Constructs a new OneofOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofOptions); + + /** OneofOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new OneofOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns OneofOptions instance + */ + public static create(properties?: google.protobuf.IOneofOptions): google.protobuf.OneofOptions; + + /** + * Encodes the specified OneofOptions message. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. + * @param message OneofOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified OneofOptions message, length delimited. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. + * @param message OneofOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an OneofOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns OneofOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofOptions; + + /** + * Decodes an OneofOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns OneofOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofOptions; + + /** + * Verifies an OneofOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @param message OneofOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of an EnumOptions. */ + interface IEnumOptions { + + /** EnumOptions allowAlias */ + allowAlias?: (boolean|null); + + /** EnumOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumOptions. */ + class EnumOptions implements IEnumOptions { + + /** + * Constructs a new EnumOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumOptions); + + /** EnumOptions allowAlias. */ + public allowAlias: boolean; + + /** EnumOptions deprecated. */ + public deprecated: boolean; + + /** EnumOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new EnumOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumOptions instance + */ + public static create(properties?: google.protobuf.IEnumOptions): google.protobuf.EnumOptions; + + /** + * Encodes the specified EnumOptions message. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. + * @param message EnumOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. + * @param message EnumOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumOptions; + + /** + * Decodes an EnumOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumOptions; + + /** + * Verifies an EnumOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @param message EnumOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of an EnumValueOptions. */ + interface IEnumValueOptions { + + /** EnumValueOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumValueOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumValueOptions. */ + class EnumValueOptions implements IEnumValueOptions { + + /** + * Constructs a new EnumValueOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueOptions); + + /** EnumValueOptions deprecated. */ + public deprecated: boolean; + + /** EnumValueOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new EnumValueOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumValueOptions instance + */ + public static create(properties?: google.protobuf.IEnumValueOptions): google.protobuf.EnumValueOptions; + + /** + * Encodes the specified EnumValueOptions message. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. + * @param message EnumValueOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumValueOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. + * @param message EnumValueOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumValueOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumValueOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueOptions; + + /** + * Decodes an EnumValueOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumValueOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueOptions; + + /** + * Verifies an EnumValueOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; + + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @param message EnumValueOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a ServiceOptions. */ + interface IServiceOptions { + + /** ServiceOptions deprecated */ + deprecated?: (boolean|null); + + /** ServiceOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ServiceOptions .google.api.defaultHost */ + ".google.api.defaultHost"?: (string|null); + + /** ServiceOptions .google.api.oauthScopes */ + ".google.api.oauthScopes"?: (string|null); + } + + /** Represents a ServiceOptions. */ + class ServiceOptions implements IServiceOptions { + + /** + * Constructs a new ServiceOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceOptions); + + /** ServiceOptions deprecated. */ + public deprecated: boolean; + + /** ServiceOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new ServiceOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns ServiceOptions instance + */ + public static create(properties?: google.protobuf.IServiceOptions): google.protobuf.ServiceOptions; + + /** + * Encodes the specified ServiceOptions message. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. + * @param message ServiceOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ServiceOptions message, length delimited. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. + * @param message ServiceOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ServiceOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ServiceOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceOptions; + + /** + * Decodes a ServiceOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ServiceOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceOptions; + + /** + * Verifies a ServiceOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @param message ServiceOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a MethodOptions. */ + interface IMethodOptions { + + /** MethodOptions deprecated */ + deprecated?: (boolean|null); + + /** MethodOptions idempotencyLevel */ + idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); + + /** MethodOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MethodOptions .google.api.http */ + ".google.api.http"?: (google.api.IHttpRule|null); + + /** MethodOptions .google.api.methodSignature */ + ".google.api.methodSignature"?: (string[]|null); + } + + /** Represents a MethodOptions. */ + class MethodOptions implements IMethodOptions { + + /** + * Constructs a new MethodOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodOptions); + + /** MethodOptions deprecated. */ + public deprecated: boolean; + + /** MethodOptions idempotencyLevel. */ + public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; + + /** MethodOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new MethodOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns MethodOptions instance + */ + public static create(properties?: google.protobuf.IMethodOptions): google.protobuf.MethodOptions; + + /** + * Encodes the specified MethodOptions message. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. + * @param message MethodOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MethodOptions message, length delimited. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. + * @param message MethodOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MethodOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MethodOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodOptions; + + /** + * Decodes a MethodOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MethodOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodOptions; + + /** + * Verifies a MethodOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; + + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @param message MethodOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace MethodOptions { + + /** IdempotencyLevel enum. */ + enum IdempotencyLevel { + IDEMPOTENCY_UNKNOWN = 0, + NO_SIDE_EFFECTS = 1, + IDEMPOTENT = 2 + } + } + + /** Properties of an UninterpretedOption. */ + interface IUninterpretedOption { + + /** UninterpretedOption name */ + name?: (google.protobuf.UninterpretedOption.INamePart[]|null); + + /** UninterpretedOption identifierValue */ + identifierValue?: (string|null); + + /** UninterpretedOption positiveIntValue */ + positiveIntValue?: (number|Long|null); + + /** UninterpretedOption negativeIntValue */ + negativeIntValue?: (number|Long|null); + + /** UninterpretedOption doubleValue */ + doubleValue?: (number|null); + + /** UninterpretedOption stringValue */ + stringValue?: (Uint8Array|null); + + /** UninterpretedOption aggregateValue */ + aggregateValue?: (string|null); + } + + /** Represents an UninterpretedOption. */ + class UninterpretedOption implements IUninterpretedOption { + + /** + * Constructs a new UninterpretedOption. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUninterpretedOption); + + /** UninterpretedOption name. */ + public name: google.protobuf.UninterpretedOption.INamePart[]; + + /** UninterpretedOption identifierValue. */ + public identifierValue: string; + + /** UninterpretedOption positiveIntValue. */ + public positiveIntValue: (number|Long); + + /** UninterpretedOption negativeIntValue. */ + public negativeIntValue: (number|Long); + + /** UninterpretedOption doubleValue. */ + public doubleValue: number; + + /** UninterpretedOption stringValue. */ + public stringValue: Uint8Array; + + /** UninterpretedOption aggregateValue. */ + public aggregateValue: string; + + /** + * Creates a new UninterpretedOption instance using the specified properties. + * @param [properties] Properties to set + * @returns UninterpretedOption instance + */ + public static create(properties?: google.protobuf.IUninterpretedOption): google.protobuf.UninterpretedOption; + + /** + * Encodes the specified UninterpretedOption message. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. + * @param message UninterpretedOption message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UninterpretedOption message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. + * @param message UninterpretedOption message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UninterpretedOption message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UninterpretedOption + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption; + + /** + * Decodes an UninterpretedOption message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UninterpretedOption + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption; + + /** + * Verifies an UninterpretedOption message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UninterpretedOption + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @param message UninterpretedOption + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UninterpretedOption to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace UninterpretedOption { + + /** Properties of a NamePart. */ + interface INamePart { + + /** NamePart namePart */ + namePart: string; + + /** NamePart isExtension */ + isExtension: boolean; + } + + /** Represents a NamePart. */ + class NamePart implements INamePart { + + /** + * Constructs a new NamePart. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.UninterpretedOption.INamePart); + + /** NamePart namePart. */ + public namePart: string; + + /** NamePart isExtension. */ + public isExtension: boolean; + + /** + * Creates a new NamePart instance using the specified properties. + * @param [properties] Properties to set + * @returns NamePart instance + */ + public static create(properties?: google.protobuf.UninterpretedOption.INamePart): google.protobuf.UninterpretedOption.NamePart; + + /** + * Encodes the specified NamePart message. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. + * @param message NamePart message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified NamePart message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. + * @param message NamePart message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a NamePart message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns NamePart + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption.NamePart; + + /** + * Decodes a NamePart message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns NamePart + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption.NamePart; + + /** + * Verifies a NamePart message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamePart + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @param message NamePart + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamePart to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Properties of a SourceCodeInfo. */ + interface ISourceCodeInfo { + + /** SourceCodeInfo location */ + location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); + } + + /** Represents a SourceCodeInfo. */ + class SourceCodeInfo implements ISourceCodeInfo { + + /** + * Constructs a new SourceCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ISourceCodeInfo); + + /** SourceCodeInfo location. */ + public location: google.protobuf.SourceCodeInfo.ILocation[]; + + /** + * Creates a new SourceCodeInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns SourceCodeInfo instance + */ + public static create(properties?: google.protobuf.ISourceCodeInfo): google.protobuf.SourceCodeInfo; + + /** + * Encodes the specified SourceCodeInfo message. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. + * @param message SourceCodeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SourceCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. + * @param message SourceCodeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SourceCodeInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SourceCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo; + + /** + * Decodes a SourceCodeInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SourceCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo; + + /** + * Verifies a SourceCodeInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @param message SourceCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace SourceCodeInfo { + + /** Properties of a Location. */ + interface ILocation { + + /** Location path */ + path?: (number[]|null); + + /** Location span */ + span?: (number[]|null); + + /** Location leadingComments */ + leadingComments?: (string|null); + + /** Location trailingComments */ + trailingComments?: (string|null); + + /** Location leadingDetachedComments */ + leadingDetachedComments?: (string[]|null); + } + + /** Represents a Location. */ + class Location implements ILocation { + + /** + * Constructs a new Location. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); + + /** Location path. */ + public path: number[]; + + /** Location span. */ + public span: number[]; + + /** Location leadingComments. */ + public leadingComments: string; + + /** Location trailingComments. */ + public trailingComments: string; + + /** Location leadingDetachedComments. */ + public leadingDetachedComments: string[]; + + /** + * Creates a new Location instance using the specified properties. + * @param [properties] Properties to set + * @returns Location instance + */ + public static create(properties?: google.protobuf.SourceCodeInfo.ILocation): google.protobuf.SourceCodeInfo.Location; + + /** + * Encodes the specified Location message. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. + * @param message Location message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Location message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. + * @param message Location message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Location message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Location + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo.Location; + + /** + * Decodes a Location message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Location + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo.Location; + + /** + * Verifies a Location message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Location + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @param message Location + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Location to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Properties of a GeneratedCodeInfo. */ + interface IGeneratedCodeInfo { + + /** GeneratedCodeInfo annotation */ + annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); + } + + /** Represents a GeneratedCodeInfo. */ + class GeneratedCodeInfo implements IGeneratedCodeInfo { + + /** + * Constructs a new GeneratedCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IGeneratedCodeInfo); + + /** GeneratedCodeInfo annotation. */ + public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; + + /** + * Creates a new GeneratedCodeInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns GeneratedCodeInfo instance + */ + public static create(properties?: google.protobuf.IGeneratedCodeInfo): google.protobuf.GeneratedCodeInfo; + + /** + * Encodes the specified GeneratedCodeInfo message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. + * @param message GeneratedCodeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GeneratedCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. + * @param message GeneratedCodeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GeneratedCodeInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GeneratedCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo; + + /** + * Decodes a GeneratedCodeInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GeneratedCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo; + + /** + * Verifies a GeneratedCodeInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GeneratedCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; + + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @param message GeneratedCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace GeneratedCodeInfo { + + /** Properties of an Annotation. */ + interface IAnnotation { + + /** Annotation path */ + path?: (number[]|null); + + /** Annotation sourceFile */ + sourceFile?: (string|null); + + /** Annotation begin */ + begin?: (number|null); + + /** Annotation end */ + end?: (number|null); + } + + /** Represents an Annotation. */ + class Annotation implements IAnnotation { + + /** + * Constructs a new Annotation. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); + + /** Annotation path. */ + public path: number[]; + + /** Annotation sourceFile. */ + public sourceFile: string; + + /** Annotation begin. */ + public begin: number; + + /** Annotation end. */ + public end: number; + + /** + * Creates a new Annotation instance using the specified properties. + * @param [properties] Properties to set + * @returns Annotation instance + */ + public static create(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Encodes the specified Annotation message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. + * @param message Annotation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Annotation message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. + * @param message Annotation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Annotation message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Annotation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Decodes an Annotation message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Annotation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Verifies an Annotation message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Annotation + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @param message Annotation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Annotation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Properties of an Any. */ + interface IAny { + + /** Any type_url */ + type_url?: (string|null); + + /** Any value */ + value?: (Uint8Array|null); + } + + /** Represents an Any. */ + class Any implements IAny { + + /** + * Constructs a new Any. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IAny); + + /** Any type_url. */ + public type_url: string; + + /** Any value. */ + public value: Uint8Array; + + /** + * Creates a new Any instance using the specified properties. + * @param [properties] Properties to set + * @returns Any instance + */ + public static create(properties?: google.protobuf.IAny): google.protobuf.Any; + + /** + * Encodes the specified Any message. Does not implicitly {@link google.protobuf.Any.verify|verify} messages. + * @param message Any message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Any message, length delimited. Does not implicitly {@link google.protobuf.Any.verify|verify} messages. + * @param message Any message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Any message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Any + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Any; + + /** + * Decodes an Any message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Any + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Any; + + /** + * Verifies an Any message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an Any message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Any + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Any; + + /** + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @param message Any + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Any to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } +} diff --git a/node_modules/google-gax/build/protos/locations.js b/node_modules/google-gax/build/protos/locations.js new file mode 100644 index 0000000..17e0dec --- /dev/null +++ b/node_modules/google-gax/build/protos/locations.js @@ -0,0 +1 @@ +(e=>{"function"==typeof define&&define.amd?define(["protobufjs/minimal"],e):"function"==typeof require&&"object"==typeof module&&module&&module.exports&&(module.exports=e(require("protobufjs/minimal")))})(function(o){var e,t,n,F,s=o.Reader,r=o.Writer,u=o.util,c=o.roots.locations_protos||(o.roots.locations_protos={});function L(e,t,n){o.rpc.Service.call(this,e,t,n)}function i(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:o.name=e.string();break;case 2:o.filter=e.string();break;case 3:o.pageSize=e.int32();break;case 4:o.pageToken=e.string();break;default:e.skipType(7&r)}}return o},i.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},i.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.name&&e.hasOwnProperty("name")&&!u.isString(e.name)?"name: string expected":null!=e.filter&&e.hasOwnProperty("filter")&&!u.isString(e.filter)?"filter: string expected":null!=e.pageSize&&e.hasOwnProperty("pageSize")&&!u.isInteger(e.pageSize)?"pageSize: integer expected":null!=e.pageToken&&e.hasOwnProperty("pageToken")&&!u.isString(e.pageToken)?"pageToken: string expected":null},i.fromObject=function(e){var t;return e instanceof c.google.cloud.location.ListLocationsRequest?e:(t=new c.google.cloud.location.ListLocationsRequest,null!=e.name&&(t.name=String(e.name)),null!=e.filter&&(t.filter=String(e.filter)),null!=e.pageSize&&(t.pageSize=0|e.pageSize),null!=e.pageToken&&(t.pageToken=String(e.pageToken)),t)},i.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name="",n.filter="",n.pageSize=0,n.pageToken=""),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.filter&&e.hasOwnProperty("filter")&&(n.filter=e.filter),null!=e.pageSize&&e.hasOwnProperty("pageSize")&&(n.pageSize=e.pageSize),null!=e.pageToken&&e.hasOwnProperty("pageToken")&&(n.pageToken=e.pageToken),n},i.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},i),e.ListLocationsResponse=(a.prototype.locations=u.emptyArray,a.prototype.nextPageToken="",a.create=function(e){return new a(e)},a.encode=function(e,t){if(t=t||r.create(),null!=e.locations&&e.locations.length)for(var n=0;n>>3){case 1:o.locations&&o.locations.length||(o.locations=[]),o.locations.push(c.google.cloud.location.Location.decode(e,e.uint32()));break;case 2:o.nextPageToken=e.string();break;default:e.skipType(7&r)}}return o},a.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},a.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.locations&&e.hasOwnProperty("locations")){if(!Array.isArray(e.locations))return"locations: array expected";for(var t=0;t>>3==1?o.name=e.string():e.skipType(7&r)}return o},G.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},G.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.name&&e.hasOwnProperty("name")&&!u.isString(e.name)?"name: string expected":null},G.fromObject=function(e){var t;return e instanceof c.google.cloud.location.GetLocationRequest?e:(t=new c.google.cloud.location.GetLocationRequest,null!=e.name&&(t.name=String(e.name)),t)},G.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name=""),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),n},G.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},G),e.Location=(p.prototype.name="",p.prototype.locationId="",p.prototype.displayName="",p.prototype.labels=u.emptyObject,p.prototype.metadata=null,p.create=function(e){return new p(e)},p.encode=function(e,t){if(t=t||r.create(),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(10).string(e.name),null!=e.labels&&Object.hasOwnProperty.call(e,"labels"))for(var n=Object.keys(e.labels),o=0;o>>3){case 1:o.name=e.string();break;case 4:o.locationId=e.string();break;case 5:o.displayName=e.string();break;case 2:o.labels===u.emptyObject&&(o.labels={});for(var i=e.uint32()+e.pos,a="",p="";e.pos>>3){case 1:a=e.string();break;case 2:p=e.string();break;default:e.skipType(7&l)}}o.labels[a]=p;break;case 3:o.metadata=c.google.protobuf.Any.decode(e,e.uint32());break;default:e.skipType(7&r)}}return o},p.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},p.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!u.isString(e.name))return"name: string expected";if(null!=e.locationId&&e.hasOwnProperty("locationId")&&!u.isString(e.locationId))return"locationId: string expected";if(null!=e.displayName&&e.hasOwnProperty("displayName")&&!u.isString(e.displayName))return"displayName: string expected";if(null!=e.labels&&e.hasOwnProperty("labels")){if(!u.isObject(e.labels))return"labels: object expected";for(var t=Object.keys(e.labels),n=0;n>>3){case 1:o.rules&&o.rules.length||(o.rules=[]),o.rules.push(c.google.api.HttpRule.decode(e,e.uint32()));break;case 2:o.fullyDecodeReservedExpansion=e.bool();break;default:e.skipType(7&r)}}return o},l.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},l.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.rules&&e.hasOwnProperty("rules")){if(!Array.isArray(e.rules))return"rules: array expected";for(var t=0;t>>3){case 1:o.selector=e.string();break;case 2:o.get=e.string();break;case 3:o.put=e.string();break;case 4:o.post=e.string();break;case 5:o.delete=e.string();break;case 6:o.patch=e.string();break;case 8:o.custom=c.google.api.CustomHttpPattern.decode(e,e.uint32());break;case 7:o.body=e.string();break;case 12:o.responseBody=e.string();break;case 11:o.additionalBindings&&o.additionalBindings.length||(o.additionalBindings=[]),o.additionalBindings.push(c.google.api.HttpRule.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return o},d.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},d.verify=function(e){if("object"!=typeof e||null===e)return"object expected";var t={};if(null!=e.selector&&e.hasOwnProperty("selector")&&!u.isString(e.selector))return"selector: string expected";if(null!=e.get&&e.hasOwnProperty("get")&&(t.pattern=1,!u.isString(e.get)))return"get: string expected";if(null!=e.put&&e.hasOwnProperty("put")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,!u.isString(e.put))return"put: string expected"}if(null!=e.post&&e.hasOwnProperty("post")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,!u.isString(e.post))return"post: string expected"}if(null!=e.delete&&e.hasOwnProperty("delete")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,!u.isString(e.delete))return"delete: string expected"}if(null!=e.patch&&e.hasOwnProperty("patch")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,!u.isString(e.patch))return"patch: string expected"}if(null!=e.custom&&e.hasOwnProperty("custom")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,n=c.google.api.CustomHttpPattern.verify(e.custom))return"custom."+n}if(null!=e.body&&e.hasOwnProperty("body")&&!u.isString(e.body))return"body: string expected";if(null!=e.responseBody&&e.hasOwnProperty("responseBody")&&!u.isString(e.responseBody))return"responseBody: string expected";if(null!=e.additionalBindings&&e.hasOwnProperty("additionalBindings")){if(!Array.isArray(e.additionalBindings))return"additionalBindings: array expected";for(var n,o=0;o>>3){case 1:o.kind=e.string();break;case 2:o.path=e.string();break;default:e.skipType(7&r)}}return o},g.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},g.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.kind&&e.hasOwnProperty("kind")&&!u.isString(e.kind)?"kind: string expected":null!=e.path&&e.hasOwnProperty("path")&&!u.isString(e.path)?"path: string expected":null},g.fromObject=function(e){var t;return e instanceof c.google.api.CustomHttpPattern?e:(t=new c.google.api.CustomHttpPattern,null!=e.kind&&(t.kind=String(e.kind)),null!=e.path&&(t.path=String(e.path)),t)},g.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.kind="",n.path=""),null!=e.kind&&e.hasOwnProperty("kind")&&(n.kind=e.kind),null!=e.path&&e.hasOwnProperty("path")&&(n.path=e.path),n},g.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},g),e),F.protobuf=((n={}).FileDescriptorSet=(B.prototype.file=u.emptyArray,B.create=function(e){return new B(e)},B.encode=function(e,t){if(t=t||r.create(),null!=e.file&&e.file.length)for(var n=0;n>>3==1?(o.file&&o.file.length||(o.file=[]),o.file.push(c.google.protobuf.FileDescriptorProto.decode(e,e.uint32()))):e.skipType(7&r)}return o},B.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},B.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.file&&e.hasOwnProperty("file")){if(!Array.isArray(e.file))return"file: array expected";for(var t=0;t>>3){case 1:o.name=e.string();break;case 2:o.package=e.string();break;case 3:o.dependency&&o.dependency.length||(o.dependency=[]),o.dependency.push(e.string());break;case 10:if(o.publicDependency&&o.publicDependency.length||(o.publicDependency=[]),2==(7&r))for(var i=e.uint32()+e.pos;e.pos>>3){case 1:o.name=e.string();break;case 2:o.field&&o.field.length||(o.field=[]),o.field.push(c.google.protobuf.FieldDescriptorProto.decode(e,e.uint32()));break;case 6:o.extension&&o.extension.length||(o.extension=[]),o.extension.push(c.google.protobuf.FieldDescriptorProto.decode(e,e.uint32()));break;case 3:o.nestedType&&o.nestedType.length||(o.nestedType=[]),o.nestedType.push(c.google.protobuf.DescriptorProto.decode(e,e.uint32()));break;case 4:o.enumType&&o.enumType.length||(o.enumType=[]),o.enumType.push(c.google.protobuf.EnumDescriptorProto.decode(e,e.uint32()));break;case 5:o.extensionRange&&o.extensionRange.length||(o.extensionRange=[]),o.extensionRange.push(c.google.protobuf.DescriptorProto.ExtensionRange.decode(e,e.uint32()));break;case 8:o.oneofDecl&&o.oneofDecl.length||(o.oneofDecl=[]),o.oneofDecl.push(c.google.protobuf.OneofDescriptorProto.decode(e,e.uint32()));break;case 7:o.options=c.google.protobuf.MessageOptions.decode(e,e.uint32());break;case 9:o.reservedRange&&o.reservedRange.length||(o.reservedRange=[]),o.reservedRange.push(c.google.protobuf.DescriptorProto.ReservedRange.decode(e,e.uint32()));break;case 10:o.reservedName&&o.reservedName.length||(o.reservedName=[]),o.reservedName.push(e.string());break;default:e.skipType(7&r)}}return o},y.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},y.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!u.isString(e.name))return"name: string expected";if(null!=e.field&&e.hasOwnProperty("field")){if(!Array.isArray(e.field))return"field: array expected";for(var t=0;t>>3){case 1:o.start=e.int32();break;case 2:o.end=e.int32();break;case 3:o.options=c.google.protobuf.ExtensionRangeOptions.decode(e,e.uint32());break;default:e.skipType(7&r)}}return o},h.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},h.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.start&&e.hasOwnProperty("start")&&!u.isInteger(e.start))return"start: integer expected";if(null!=e.end&&e.hasOwnProperty("end")&&!u.isInteger(e.end))return"end: integer expected";if(null!=e.options&&e.hasOwnProperty("options")){e=c.google.protobuf.ExtensionRangeOptions.verify(e.options);if(e)return"options."+e}return null},h.fromObject=function(e){if(e instanceof c.google.protobuf.DescriptorProto.ExtensionRange)return e;var t=new c.google.protobuf.DescriptorProto.ExtensionRange;if(null!=e.start&&(t.start=0|e.start),null!=e.end&&(t.end=0|e.end),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.protobuf.DescriptorProto.ExtensionRange.options: object expected");t.options=c.google.protobuf.ExtensionRangeOptions.fromObject(e.options)}return t},h.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.start=0,n.end=0,n.options=null),null!=e.start&&e.hasOwnProperty("start")&&(n.start=e.start),null!=e.end&&e.hasOwnProperty("end")&&(n.end=e.end),null!=e.options&&e.hasOwnProperty("options")&&(n.options=c.google.protobuf.ExtensionRangeOptions.toObject(e.options,t)),n},h.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},h),y.ReservedRange=(b.prototype.start=0,b.prototype.end=0,b.create=function(e){return new b(e)},b.encode=function(e,t){return t=t||r.create(),null!=e.start&&Object.hasOwnProperty.call(e,"start")&&t.uint32(8).int32(e.start),null!=e.end&&Object.hasOwnProperty.call(e,"end")&&t.uint32(16).int32(e.end),t},b.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},b.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new c.google.protobuf.DescriptorProto.ReservedRange;e.pos>>3){case 1:o.start=e.int32();break;case 2:o.end=e.int32();break;default:e.skipType(7&r)}}return o},b.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},b.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.start&&e.hasOwnProperty("start")&&!u.isInteger(e.start)?"start: integer expected":null!=e.end&&e.hasOwnProperty("end")&&!u.isInteger(e.end)?"end: integer expected":null},b.fromObject=function(e){var t;return e instanceof c.google.protobuf.DescriptorProto.ReservedRange?e:(t=new c.google.protobuf.DescriptorProto.ReservedRange,null!=e.start&&(t.start=0|e.start),null!=e.end&&(t.end=0|e.end),t)},b.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.start=0,n.end=0),null!=e.start&&e.hasOwnProperty("start")&&(n.start=e.start),null!=e.end&&e.hasOwnProperty("end")&&(n.end=e.end),n},b.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},b),y),n.ExtensionRangeOptions=(U.prototype.uninterpretedOption=u.emptyArray,U.create=function(e){return new U(e)},U.encode=function(e,t){if(t=t||r.create(),null!=e.uninterpretedOption&&e.uninterpretedOption.length)for(var n=0;n>>3==999?(o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(c.google.protobuf.UninterpretedOption.decode(e,e.uint32()))):e.skipType(7&r)}return o},U.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},U.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 1:o.name=e.string();break;case 3:o.number=e.int32();break;case 4:o.label=e.int32();break;case 5:o.type=e.int32();break;case 6:o.typeName=e.string();break;case 2:o.extendee=e.string();break;case 7:o.defaultValue=e.string();break;case 9:o.oneofIndex=e.int32();break;case 10:o.jsonName=e.string();break;case 8:o.options=c.google.protobuf.FieldOptions.decode(e,e.uint32());break;case 17:o.proto3Optional=e.bool();break;default:e.skipType(7&r)}}return o},O.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},O.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!u.isString(e.name))return"name: string expected";if(null!=e.number&&e.hasOwnProperty("number")&&!u.isInteger(e.number))return"number: integer expected";if(null!=e.label&&e.hasOwnProperty("label"))switch(e.label){default:return"label: enum value expected";case 1:case 2:case 3:}if(null!=e.type&&e.hasOwnProperty("type"))switch(e.type){default:return"type: enum value expected";case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:case 11:case 12:case 13:case 14:case 15:case 16:case 17:case 18:}if(null!=e.typeName&&e.hasOwnProperty("typeName")&&!u.isString(e.typeName))return"typeName: string expected";if(null!=e.extendee&&e.hasOwnProperty("extendee")&&!u.isString(e.extendee))return"extendee: string expected";if(null!=e.defaultValue&&e.hasOwnProperty("defaultValue")&&!u.isString(e.defaultValue))return"defaultValue: string expected";if(null!=e.oneofIndex&&e.hasOwnProperty("oneofIndex")&&!u.isInteger(e.oneofIndex))return"oneofIndex: integer expected";if(null!=e.jsonName&&e.hasOwnProperty("jsonName")&&!u.isString(e.jsonName))return"jsonName: string expected";if(null!=e.options&&e.hasOwnProperty("options")){var t=c.google.protobuf.FieldOptions.verify(e.options);if(t)return"options."+t}return null!=e.proto3Optional&&e.hasOwnProperty("proto3Optional")&&"boolean"!=typeof e.proto3Optional?"proto3Optional: boolean expected":null},O.fromObject=function(e){if(e instanceof c.google.protobuf.FieldDescriptorProto)return e;var t=new c.google.protobuf.FieldDescriptorProto;switch(null!=e.name&&(t.name=String(e.name)),null!=e.number&&(t.number=0|e.number),e.label){case"LABEL_OPTIONAL":case 1:t.label=1;break;case"LABEL_REQUIRED":case 2:t.label=2;break;case"LABEL_REPEATED":case 3:t.label=3}switch(e.type){case"TYPE_DOUBLE":case 1:t.type=1;break;case"TYPE_FLOAT":case 2:t.type=2;break;case"TYPE_INT64":case 3:t.type=3;break;case"TYPE_UINT64":case 4:t.type=4;break;case"TYPE_INT32":case 5:t.type=5;break;case"TYPE_FIXED64":case 6:t.type=6;break;case"TYPE_FIXED32":case 7:t.type=7;break;case"TYPE_BOOL":case 8:t.type=8;break;case"TYPE_STRING":case 9:t.type=9;break;case"TYPE_GROUP":case 10:t.type=10;break;case"TYPE_MESSAGE":case 11:t.type=11;break;case"TYPE_BYTES":case 12:t.type=12;break;case"TYPE_UINT32":case 13:t.type=13;break;case"TYPE_ENUM":case 14:t.type=14;break;case"TYPE_SFIXED32":case 15:t.type=15;break;case"TYPE_SFIXED64":case 16:t.type=16;break;case"TYPE_SINT32":case 17:t.type=17;break;case"TYPE_SINT64":case 18:t.type=18}if(null!=e.typeName&&(t.typeName=String(e.typeName)),null!=e.extendee&&(t.extendee=String(e.extendee)),null!=e.defaultValue&&(t.defaultValue=String(e.defaultValue)),null!=e.oneofIndex&&(t.oneofIndex=0|e.oneofIndex),null!=e.jsonName&&(t.jsonName=String(e.jsonName)),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.protobuf.FieldDescriptorProto.options: object expected");t.options=c.google.protobuf.FieldOptions.fromObject(e.options)}return null!=e.proto3Optional&&(t.proto3Optional=Boolean(e.proto3Optional)),t},O.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name="",n.extendee="",n.number=0,n.label=t.enums===String?"LABEL_OPTIONAL":1,n.type=t.enums===String?"TYPE_DOUBLE":1,n.typeName="",n.defaultValue="",n.options=null,n.oneofIndex=0,n.jsonName="",n.proto3Optional=!1),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.extendee&&e.hasOwnProperty("extendee")&&(n.extendee=e.extendee),null!=e.number&&e.hasOwnProperty("number")&&(n.number=e.number),null!=e.label&&e.hasOwnProperty("label")&&(n.label=t.enums===String?c.google.protobuf.FieldDescriptorProto.Label[e.label]:e.label),null!=e.type&&e.hasOwnProperty("type")&&(n.type=t.enums===String?c.google.protobuf.FieldDescriptorProto.Type[e.type]:e.type),null!=e.typeName&&e.hasOwnProperty("typeName")&&(n.typeName=e.typeName),null!=e.defaultValue&&e.hasOwnProperty("defaultValue")&&(n.defaultValue=e.defaultValue),null!=e.options&&e.hasOwnProperty("options")&&(n.options=c.google.protobuf.FieldOptions.toObject(e.options,t)),null!=e.oneofIndex&&e.hasOwnProperty("oneofIndex")&&(n.oneofIndex=e.oneofIndex),null!=e.jsonName&&e.hasOwnProperty("jsonName")&&(n.jsonName=e.jsonName),null!=e.proto3Optional&&e.hasOwnProperty("proto3Optional")&&(n.proto3Optional=e.proto3Optional),n},O.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},O.Type=(e={},(t=Object.create(e))[e[1]="TYPE_DOUBLE"]=1,t[e[2]="TYPE_FLOAT"]=2,t[e[3]="TYPE_INT64"]=3,t[e[4]="TYPE_UINT64"]=4,t[e[5]="TYPE_INT32"]=5,t[e[6]="TYPE_FIXED64"]=6,t[e[7]="TYPE_FIXED32"]=7,t[e[8]="TYPE_BOOL"]=8,t[e[9]="TYPE_STRING"]=9,t[e[10]="TYPE_GROUP"]=10,t[e[11]="TYPE_MESSAGE"]=11,t[e[12]="TYPE_BYTES"]=12,t[e[13]="TYPE_UINT32"]=13,t[e[14]="TYPE_ENUM"]=14,t[e[15]="TYPE_SFIXED32"]=15,t[e[16]="TYPE_SFIXED64"]=16,t[e[17]="TYPE_SINT32"]=17,t[e[18]="TYPE_SINT64"]=18,t),O.Label=(e={},(t=Object.create(e))[e[1]="LABEL_OPTIONAL"]=1,t[e[2]="LABEL_REQUIRED"]=2,t[e[3]="LABEL_REPEATED"]=3,t),O),n.OneofDescriptorProto=(m.prototype.name="",m.prototype.options=null,m.create=function(e){return new m(e)},m.encode=function(e,t){return t=t||r.create(),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(10).string(e.name),null!=e.options&&Object.hasOwnProperty.call(e,"options")&&c.google.protobuf.OneofOptions.encode(e.options,t.uint32(18).fork()).ldelim(),t},m.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},m.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new c.google.protobuf.OneofDescriptorProto;e.pos>>3){case 1:o.name=e.string();break;case 2:o.options=c.google.protobuf.OneofOptions.decode(e,e.uint32());break;default:e.skipType(7&r)}}return o},m.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},m.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!u.isString(e.name))return"name: string expected";if(null!=e.options&&e.hasOwnProperty("options")){e=c.google.protobuf.OneofOptions.verify(e.options);if(e)return"options."+e}return null},m.fromObject=function(e){if(e instanceof c.google.protobuf.OneofDescriptorProto)return e;var t=new c.google.protobuf.OneofDescriptorProto;if(null!=e.name&&(t.name=String(e.name)),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.protobuf.OneofDescriptorProto.options: object expected");t.options=c.google.protobuf.OneofOptions.fromObject(e.options)}return t},m.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name="",n.options=null),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.options&&e.hasOwnProperty("options")&&(n.options=c.google.protobuf.OneofOptions.toObject(e.options,t)),n},m.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},m),n.EnumDescriptorProto=(v.prototype.name="",v.prototype.value=u.emptyArray,v.prototype.options=null,v.prototype.reservedRange=u.emptyArray,v.prototype.reservedName=u.emptyArray,v.create=function(e){return new v(e)},v.encode=function(e,t){if(t=t||r.create(),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(10).string(e.name),null!=e.value&&e.value.length)for(var n=0;n>>3){case 1:o.name=e.string();break;case 2:o.value&&o.value.length||(o.value=[]),o.value.push(c.google.protobuf.EnumValueDescriptorProto.decode(e,e.uint32()));break;case 3:o.options=c.google.protobuf.EnumOptions.decode(e,e.uint32());break;case 4:o.reservedRange&&o.reservedRange.length||(o.reservedRange=[]),o.reservedRange.push(c.google.protobuf.EnumDescriptorProto.EnumReservedRange.decode(e,e.uint32()));break;case 5:o.reservedName&&o.reservedName.length||(o.reservedName=[]),o.reservedName.push(e.string());break;default:e.skipType(7&r)}}return o},v.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},v.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!u.isString(e.name))return"name: string expected";if(null!=e.value&&e.hasOwnProperty("value")){if(!Array.isArray(e.value))return"value: array expected";for(var t=0;t>>3){case 1:o.start=e.int32();break;case 2:o.end=e.int32();break;default:e.skipType(7&r)}}return o},P.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},P.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.start&&e.hasOwnProperty("start")&&!u.isInteger(e.start)?"start: integer expected":null!=e.end&&e.hasOwnProperty("end")&&!u.isInteger(e.end)?"end: integer expected":null},P.fromObject=function(e){var t;return e instanceof c.google.protobuf.EnumDescriptorProto.EnumReservedRange?e:(t=new c.google.protobuf.EnumDescriptorProto.EnumReservedRange,null!=e.start&&(t.start=0|e.start),null!=e.end&&(t.end=0|e.end),t)},P.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.start=0,n.end=0),null!=e.start&&e.hasOwnProperty("start")&&(n.start=e.start),null!=e.end&&e.hasOwnProperty("end")&&(n.end=e.end),n},P.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},P),v),n.EnumValueDescriptorProto=(w.prototype.name="",w.prototype.number=0,w.prototype.options=null,w.create=function(e){return new w(e)},w.encode=function(e,t){return t=t||r.create(),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(10).string(e.name),null!=e.number&&Object.hasOwnProperty.call(e,"number")&&t.uint32(16).int32(e.number),null!=e.options&&Object.hasOwnProperty.call(e,"options")&&c.google.protobuf.EnumValueOptions.encode(e.options,t.uint32(26).fork()).ldelim(),t},w.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},w.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new c.google.protobuf.EnumValueDescriptorProto;e.pos>>3){case 1:o.name=e.string();break;case 2:o.number=e.int32();break;case 3:o.options=c.google.protobuf.EnumValueOptions.decode(e,e.uint32());break;default:e.skipType(7&r)}}return o},w.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},w.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!u.isString(e.name))return"name: string expected";if(null!=e.number&&e.hasOwnProperty("number")&&!u.isInteger(e.number))return"number: integer expected";if(null!=e.options&&e.hasOwnProperty("options")){e=c.google.protobuf.EnumValueOptions.verify(e.options);if(e)return"options."+e}return null},w.fromObject=function(e){if(e instanceof c.google.protobuf.EnumValueDescriptorProto)return e;var t=new c.google.protobuf.EnumValueDescriptorProto;if(null!=e.name&&(t.name=String(e.name)),null!=e.number&&(t.number=0|e.number),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.protobuf.EnumValueDescriptorProto.options: object expected");t.options=c.google.protobuf.EnumValueOptions.fromObject(e.options)}return t},w.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name="",n.number=0,n.options=null),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.number&&e.hasOwnProperty("number")&&(n.number=e.number),null!=e.options&&e.hasOwnProperty("options")&&(n.options=c.google.protobuf.EnumValueOptions.toObject(e.options,t)),n},w.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},w),n.ServiceDescriptorProto=(j.prototype.name="",j.prototype.method=u.emptyArray,j.prototype.options=null,j.create=function(e){return new j(e)},j.encode=function(e,t){if(t=t||r.create(),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(10).string(e.name),null!=e.method&&e.method.length)for(var n=0;n>>3){case 1:o.name=e.string();break;case 2:o.method&&o.method.length||(o.method=[]),o.method.push(c.google.protobuf.MethodDescriptorProto.decode(e,e.uint32()));break;case 3:o.options=c.google.protobuf.ServiceOptions.decode(e,e.uint32());break;default:e.skipType(7&r)}}return o},j.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},j.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!u.isString(e.name))return"name: string expected";if(null!=e.method&&e.hasOwnProperty("method")){if(!Array.isArray(e.method))return"method: array expected";for(var t=0;t>>3){case 1:o.name=e.string();break;case 2:o.inputType=e.string();break;case 3:o.outputType=e.string();break;case 4:o.options=c.google.protobuf.MethodOptions.decode(e,e.uint32());break;case 5:o.clientStreaming=e.bool();break;case 6:o.serverStreaming=e.bool();break;default:e.skipType(7&r)}}return o},x.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},x.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!u.isString(e.name))return"name: string expected";if(null!=e.inputType&&e.hasOwnProperty("inputType")&&!u.isString(e.inputType))return"inputType: string expected";if(null!=e.outputType&&e.hasOwnProperty("outputType")&&!u.isString(e.outputType))return"outputType: string expected";if(null!=e.options&&e.hasOwnProperty("options")){var t=c.google.protobuf.MethodOptions.verify(e.options);if(t)return"options."+t}return null!=e.clientStreaming&&e.hasOwnProperty("clientStreaming")&&"boolean"!=typeof e.clientStreaming?"clientStreaming: boolean expected":null!=e.serverStreaming&&e.hasOwnProperty("serverStreaming")&&"boolean"!=typeof e.serverStreaming?"serverStreaming: boolean expected":null},x.fromObject=function(e){if(e instanceof c.google.protobuf.MethodDescriptorProto)return e;var t=new c.google.protobuf.MethodDescriptorProto;if(null!=e.name&&(t.name=String(e.name)),null!=e.inputType&&(t.inputType=String(e.inputType)),null!=e.outputType&&(t.outputType=String(e.outputType)),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.protobuf.MethodDescriptorProto.options: object expected");t.options=c.google.protobuf.MethodOptions.fromObject(e.options)}return null!=e.clientStreaming&&(t.clientStreaming=Boolean(e.clientStreaming)),null!=e.serverStreaming&&(t.serverStreaming=Boolean(e.serverStreaming)),t},x.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name="",n.inputType="",n.outputType="",n.options=null,n.clientStreaming=!1,n.serverStreaming=!1),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.inputType&&e.hasOwnProperty("inputType")&&(n.inputType=e.inputType),null!=e.outputType&&e.hasOwnProperty("outputType")&&(n.outputType=e.outputType),null!=e.options&&e.hasOwnProperty("options")&&(n.options=c.google.protobuf.MethodOptions.toObject(e.options,t)),null!=e.clientStreaming&&e.hasOwnProperty("clientStreaming")&&(n.clientStreaming=e.clientStreaming),null!=e.serverStreaming&&e.hasOwnProperty("serverStreaming")&&(n.serverStreaming=e.serverStreaming),n},x.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},x),n.FileOptions=(S.prototype.javaPackage="",S.prototype.javaOuterClassname="",S.prototype.javaMultipleFiles=!1,S.prototype.javaGenerateEqualsAndHash=!1,S.prototype.javaStringCheckUtf8=!1,S.prototype.optimizeFor=1,S.prototype.goPackage="",S.prototype.ccGenericServices=!1,S.prototype.javaGenericServices=!1,S.prototype.pyGenericServices=!1,S.prototype.phpGenericServices=!1,S.prototype.deprecated=!1,S.prototype.ccEnableArenas=!0,S.prototype.objcClassPrefix="",S.prototype.csharpNamespace="",S.prototype.swiftPrefix="",S.prototype.phpClassPrefix="",S.prototype.phpNamespace="",S.prototype.phpMetadataNamespace="",S.prototype.rubyPackage="",S.prototype.uninterpretedOption=u.emptyArray,S.create=function(e){return new S(e)},S.encode=function(e,t){if(t=t||r.create(),null!=e.javaPackage&&Object.hasOwnProperty.call(e,"javaPackage")&&t.uint32(10).string(e.javaPackage),null!=e.javaOuterClassname&&Object.hasOwnProperty.call(e,"javaOuterClassname")&&t.uint32(66).string(e.javaOuterClassname),null!=e.optimizeFor&&Object.hasOwnProperty.call(e,"optimizeFor")&&t.uint32(72).int32(e.optimizeFor),null!=e.javaMultipleFiles&&Object.hasOwnProperty.call(e,"javaMultipleFiles")&&t.uint32(80).bool(e.javaMultipleFiles),null!=e.goPackage&&Object.hasOwnProperty.call(e,"goPackage")&&t.uint32(90).string(e.goPackage),null!=e.ccGenericServices&&Object.hasOwnProperty.call(e,"ccGenericServices")&&t.uint32(128).bool(e.ccGenericServices),null!=e.javaGenericServices&&Object.hasOwnProperty.call(e,"javaGenericServices")&&t.uint32(136).bool(e.javaGenericServices),null!=e.pyGenericServices&&Object.hasOwnProperty.call(e,"pyGenericServices")&&t.uint32(144).bool(e.pyGenericServices),null!=e.javaGenerateEqualsAndHash&&Object.hasOwnProperty.call(e,"javaGenerateEqualsAndHash")&&t.uint32(160).bool(e.javaGenerateEqualsAndHash),null!=e.deprecated&&Object.hasOwnProperty.call(e,"deprecated")&&t.uint32(184).bool(e.deprecated),null!=e.javaStringCheckUtf8&&Object.hasOwnProperty.call(e,"javaStringCheckUtf8")&&t.uint32(216).bool(e.javaStringCheckUtf8),null!=e.ccEnableArenas&&Object.hasOwnProperty.call(e,"ccEnableArenas")&&t.uint32(248).bool(e.ccEnableArenas),null!=e.objcClassPrefix&&Object.hasOwnProperty.call(e,"objcClassPrefix")&&t.uint32(290).string(e.objcClassPrefix),null!=e.csharpNamespace&&Object.hasOwnProperty.call(e,"csharpNamespace")&&t.uint32(298).string(e.csharpNamespace),null!=e.swiftPrefix&&Object.hasOwnProperty.call(e,"swiftPrefix")&&t.uint32(314).string(e.swiftPrefix),null!=e.phpClassPrefix&&Object.hasOwnProperty.call(e,"phpClassPrefix")&&t.uint32(322).string(e.phpClassPrefix),null!=e.phpNamespace&&Object.hasOwnProperty.call(e,"phpNamespace")&&t.uint32(330).string(e.phpNamespace),null!=e.phpGenericServices&&Object.hasOwnProperty.call(e,"phpGenericServices")&&t.uint32(336).bool(e.phpGenericServices),null!=e.phpMetadataNamespace&&Object.hasOwnProperty.call(e,"phpMetadataNamespace")&&t.uint32(354).string(e.phpMetadataNamespace),null!=e.rubyPackage&&Object.hasOwnProperty.call(e,"rubyPackage")&&t.uint32(362).string(e.rubyPackage),null!=e.uninterpretedOption&&e.uninterpretedOption.length)for(var n=0;n>>3){case 1:o.javaPackage=e.string();break;case 8:o.javaOuterClassname=e.string();break;case 10:o.javaMultipleFiles=e.bool();break;case 20:o.javaGenerateEqualsAndHash=e.bool();break;case 27:o.javaStringCheckUtf8=e.bool();break;case 9:o.optimizeFor=e.int32();break;case 11:o.goPackage=e.string();break;case 16:o.ccGenericServices=e.bool();break;case 17:o.javaGenericServices=e.bool();break;case 18:o.pyGenericServices=e.bool();break;case 42:o.phpGenericServices=e.bool();break;case 23:o.deprecated=e.bool();break;case 31:o.ccEnableArenas=e.bool();break;case 36:o.objcClassPrefix=e.string();break;case 37:o.csharpNamespace=e.string();break;case 39:o.swiftPrefix=e.string();break;case 40:o.phpClassPrefix=e.string();break;case 41:o.phpNamespace=e.string();break;case 44:o.phpMetadataNamespace=e.string();break;case 45:o.rubyPackage=e.string();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(c.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return o},S.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},S.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.javaPackage&&e.hasOwnProperty("javaPackage")&&!u.isString(e.javaPackage))return"javaPackage: string expected";if(null!=e.javaOuterClassname&&e.hasOwnProperty("javaOuterClassname")&&!u.isString(e.javaOuterClassname))return"javaOuterClassname: string expected";if(null!=e.javaMultipleFiles&&e.hasOwnProperty("javaMultipleFiles")&&"boolean"!=typeof e.javaMultipleFiles)return"javaMultipleFiles: boolean expected";if(null!=e.javaGenerateEqualsAndHash&&e.hasOwnProperty("javaGenerateEqualsAndHash")&&"boolean"!=typeof e.javaGenerateEqualsAndHash)return"javaGenerateEqualsAndHash: boolean expected";if(null!=e.javaStringCheckUtf8&&e.hasOwnProperty("javaStringCheckUtf8")&&"boolean"!=typeof e.javaStringCheckUtf8)return"javaStringCheckUtf8: boolean expected";if(null!=e.optimizeFor&&e.hasOwnProperty("optimizeFor"))switch(e.optimizeFor){default:return"optimizeFor: enum value expected";case 1:case 2:case 3:}if(null!=e.goPackage&&e.hasOwnProperty("goPackage")&&!u.isString(e.goPackage))return"goPackage: string expected";if(null!=e.ccGenericServices&&e.hasOwnProperty("ccGenericServices")&&"boolean"!=typeof e.ccGenericServices)return"ccGenericServices: boolean expected";if(null!=e.javaGenericServices&&e.hasOwnProperty("javaGenericServices")&&"boolean"!=typeof e.javaGenericServices)return"javaGenericServices: boolean expected";if(null!=e.pyGenericServices&&e.hasOwnProperty("pyGenericServices")&&"boolean"!=typeof e.pyGenericServices)return"pyGenericServices: boolean expected";if(null!=e.phpGenericServices&&e.hasOwnProperty("phpGenericServices")&&"boolean"!=typeof e.phpGenericServices)return"phpGenericServices: boolean expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.ccEnableArenas&&e.hasOwnProperty("ccEnableArenas")&&"boolean"!=typeof e.ccEnableArenas)return"ccEnableArenas: boolean expected";if(null!=e.objcClassPrefix&&e.hasOwnProperty("objcClassPrefix")&&!u.isString(e.objcClassPrefix))return"objcClassPrefix: string expected";if(null!=e.csharpNamespace&&e.hasOwnProperty("csharpNamespace")&&!u.isString(e.csharpNamespace))return"csharpNamespace: string expected";if(null!=e.swiftPrefix&&e.hasOwnProperty("swiftPrefix")&&!u.isString(e.swiftPrefix))return"swiftPrefix: string expected";if(null!=e.phpClassPrefix&&e.hasOwnProperty("phpClassPrefix")&&!u.isString(e.phpClassPrefix))return"phpClassPrefix: string expected";if(null!=e.phpNamespace&&e.hasOwnProperty("phpNamespace")&&!u.isString(e.phpNamespace))return"phpNamespace: string expected";if(null!=e.phpMetadataNamespace&&e.hasOwnProperty("phpMetadataNamespace")&&!u.isString(e.phpMetadataNamespace))return"phpMetadataNamespace: string expected";if(null!=e.rubyPackage&&e.hasOwnProperty("rubyPackage")&&!u.isString(e.rubyPackage))return"rubyPackage: string expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 1:o.messageSetWireFormat=e.bool();break;case 2:o.noStandardDescriptorAccessor=e.bool();break;case 3:o.deprecated=e.bool();break;case 7:o.mapEntry=e.bool();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(c.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return o},k.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},k.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.messageSetWireFormat&&e.hasOwnProperty("messageSetWireFormat")&&"boolean"!=typeof e.messageSetWireFormat)return"messageSetWireFormat: boolean expected";if(null!=e.noStandardDescriptorAccessor&&e.hasOwnProperty("noStandardDescriptorAccessor")&&"boolean"!=typeof e.noStandardDescriptorAccessor)return"noStandardDescriptorAccessor: boolean expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.mapEntry&&e.hasOwnProperty("mapEntry")&&"boolean"!=typeof e.mapEntry)return"mapEntry: boolean expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 1:o.ctype=e.int32();break;case 2:o.packed=e.bool();break;case 6:o.jstype=e.int32();break;case 5:o.lazy=e.bool();break;case 3:o.deprecated=e.bool();break;case 10:o.weak=e.bool();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(c.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return o},D.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},D.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.ctype&&e.hasOwnProperty("ctype"))switch(e.ctype){default:return"ctype: enum value expected";case 0:case 1:case 2:}if(null!=e.packed&&e.hasOwnProperty("packed")&&"boolean"!=typeof e.packed)return"packed: boolean expected";if(null!=e.jstype&&e.hasOwnProperty("jstype"))switch(e.jstype){default:return"jstype: enum value expected";case 0:case 1:case 2:}if(null!=e.lazy&&e.hasOwnProperty("lazy")&&"boolean"!=typeof e.lazy)return"lazy: boolean expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.weak&&e.hasOwnProperty("weak")&&"boolean"!=typeof e.weak)return"weak: boolean expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3==999?(o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(c.google.protobuf.UninterpretedOption.decode(e,e.uint32()))):e.skipType(7&r)}return o},M.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},M.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 2:o.allowAlias=e.bool();break;case 3:o.deprecated=e.bool();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(c.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return o},T.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},T.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.allowAlias&&e.hasOwnProperty("allowAlias")&&"boolean"!=typeof e.allowAlias)return"allowAlias: boolean expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 1:o.deprecated=e.bool();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(c.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return o},E.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},E.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 33:o.deprecated=e.bool();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(c.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;case 1049:o[".google.api.defaultHost"]=e.string();break;case 1050:o[".google.api.oauthScopes"]=e.string();break;default:e.skipType(7&r)}}return o},A.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},A.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 33:o.deprecated=e.bool();break;case 34:o.idempotencyLevel=e.int32();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(c.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;case 72295728:o[".google.api.http"]=c.google.api.HttpRule.decode(e,e.uint32());break;case 1051:o[".google.api.methodSignature"]&&o[".google.api.methodSignature"].length||(o[".google.api.methodSignature"]=[]),o[".google.api.methodSignature"].push(e.string());break;default:e.skipType(7&r)}}return o},N.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},N.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.idempotencyLevel&&e.hasOwnProperty("idempotencyLevel"))switch(e.idempotencyLevel){default:return"idempotencyLevel: enum value expected";case 0:case 1:case 2:}if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 2:o.name&&o.name.length||(o.name=[]),o.name.push(c.google.protobuf.UninterpretedOption.NamePart.decode(e,e.uint32()));break;case 3:o.identifierValue=e.string();break;case 4:o.positiveIntValue=e.uint64();break;case 5:o.negativeIntValue=e.int64();break;case 6:o.doubleValue=e.double();break;case 7:o.stringValue=e.bytes();break;case 8:o.aggregateValue=e.string();break;default:e.skipType(7&r)}}return o},I.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},I.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")){if(!Array.isArray(e.name))return"name: array expected";for(var t=0;t>>0,e.positiveIntValue.high>>>0).toNumber(!0))),null!=e.negativeIntValue&&(u.Long?(t.negativeIntValue=u.Long.fromValue(e.negativeIntValue)).unsigned=!1:"string"==typeof e.negativeIntValue?t.negativeIntValue=parseInt(e.negativeIntValue,10):"number"==typeof e.negativeIntValue?t.negativeIntValue=e.negativeIntValue:"object"==typeof e.negativeIntValue&&(t.negativeIntValue=new u.LongBits(e.negativeIntValue.low>>>0,e.negativeIntValue.high>>>0).toNumber())),null!=e.doubleValue&&(t.doubleValue=Number(e.doubleValue)),null!=e.stringValue&&("string"==typeof e.stringValue?u.base64.decode(e.stringValue,t.stringValue=u.newBuffer(u.base64.length(e.stringValue)),0):e.stringValue.length&&(t.stringValue=e.stringValue)),null!=e.aggregateValue&&(t.aggregateValue=String(e.aggregateValue)),t},I.toObject=function(e,t){var n,o={};if(((t=t||{}).arrays||t.defaults)&&(o.name=[]),t.defaults&&(o.identifierValue="",u.Long?(n=new u.Long(0,0,!0),o.positiveIntValue=t.longs===String?n.toString():t.longs===Number?n.toNumber():n):o.positiveIntValue=t.longs===String?"0":0,u.Long?(n=new u.Long(0,0,!1),o.negativeIntValue=t.longs===String?n.toString():t.longs===Number?n.toNumber():n):o.negativeIntValue=t.longs===String?"0":0,o.doubleValue=0,t.bytes===String?o.stringValue="":(o.stringValue=[],t.bytes!==Array&&(o.stringValue=u.newBuffer(o.stringValue))),o.aggregateValue=""),e.name&&e.name.length){o.name=[];for(var r=0;r>>0,e.positiveIntValue.high>>>0).toNumber(!0):e.positiveIntValue),null!=e.negativeIntValue&&e.hasOwnProperty("negativeIntValue")&&("number"==typeof e.negativeIntValue?o.negativeIntValue=t.longs===String?String(e.negativeIntValue):e.negativeIntValue:o.negativeIntValue=t.longs===String?u.Long.prototype.toString.call(e.negativeIntValue):t.longs===Number?new u.LongBits(e.negativeIntValue.low>>>0,e.negativeIntValue.high>>>0).toNumber():e.negativeIntValue),null!=e.doubleValue&&e.hasOwnProperty("doubleValue")&&(o.doubleValue=t.json&&!isFinite(e.doubleValue)?String(e.doubleValue):e.doubleValue),null!=e.stringValue&&e.hasOwnProperty("stringValue")&&(o.stringValue=t.bytes===String?u.base64.encode(e.stringValue,0,e.stringValue.length):t.bytes===Array?Array.prototype.slice.call(e.stringValue):e.stringValue),null!=e.aggregateValue&&e.hasOwnProperty("aggregateValue")&&(o.aggregateValue=e.aggregateValue),o},I.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},I.NamePart=(R.prototype.namePart="",R.prototype.isExtension=!1,R.create=function(e){return new R(e)},R.encode=function(e,t){return(t=t||r.create()).uint32(10).string(e.namePart),t.uint32(16).bool(e.isExtension),t},R.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},R.decode=function(e,t){e instanceof s||(e=s.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new c.google.protobuf.UninterpretedOption.NamePart;e.pos>>3){case 1:o.namePart=e.string();break;case 2:o.isExtension=e.bool();break;default:e.skipType(7&r)}}if(!o.hasOwnProperty("namePart"))throw u.ProtocolError("missing required 'namePart'",{instance:o});if(o.hasOwnProperty("isExtension"))return o;throw u.ProtocolError("missing required 'isExtension'",{instance:o})},R.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},R.verify=function(e){return"object"!=typeof e||null===e?"object expected":u.isString(e.namePart)?"boolean"!=typeof e.isExtension?"isExtension: boolean expected":null:"namePart: string expected"},R.fromObject=function(e){var t;return e instanceof c.google.protobuf.UninterpretedOption.NamePart?e:(t=new c.google.protobuf.UninterpretedOption.NamePart,null!=e.namePart&&(t.namePart=String(e.namePart)),null!=e.isExtension&&(t.isExtension=Boolean(e.isExtension)),t)},R.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.namePart="",n.isExtension=!1),null!=e.namePart&&e.hasOwnProperty("namePart")&&(n.namePart=e.namePart),null!=e.isExtension&&e.hasOwnProperty("isExtension")&&(n.isExtension=e.isExtension),n},R.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},R),I),n.SourceCodeInfo=(_.prototype.location=u.emptyArray,_.create=function(e){return new _(e)},_.encode=function(e,t){if(t=t||r.create(),null!=e.location&&e.location.length)for(var n=0;n>>3==1?(o.location&&o.location.length||(o.location=[]),o.location.push(c.google.protobuf.SourceCodeInfo.Location.decode(e,e.uint32()))):e.skipType(7&r)}return o},_.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},_.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.location&&e.hasOwnProperty("location")){if(!Array.isArray(e.location))return"location: array expected";for(var t=0;t>>3){case 1:if(o.path&&o.path.length||(o.path=[]),2==(7&r))for(var i=e.uint32()+e.pos;e.pos>>3==1?(o.annotation&&o.annotation.length||(o.annotation=[]),o.annotation.push(c.google.protobuf.GeneratedCodeInfo.Annotation.decode(e,e.uint32()))):e.skipType(7&r)}return o},J.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},J.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.annotation&&e.hasOwnProperty("annotation")){if(!Array.isArray(e.annotation))return"annotation: array expected";for(var t=0;t>>3){case 1:if(o.path&&o.path.length||(o.path=[]),2==(7&r))for(var i=e.uint32()+e.pos;e.pos>>3){case 1:o.type_url=e.string();break;case 2:o.value=e.bytes();break;default:e.skipType(7&r)}}return o},H.decodeDelimited=function(e){return e instanceof s||(e=new s(e)),this.decode(e,e.uint32())},H.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.type_url&&e.hasOwnProperty("type_url")&&!u.isString(e.type_url)?"type_url: string expected":null!=e.value&&e.hasOwnProperty("value")&&!(e.value&&"number"==typeof e.value.length||u.isString(e.value))?"value: buffer expected":null},H.fromObject=function(e){var t;return e instanceof c.google.protobuf.Any?e:(t=new c.google.protobuf.Any,null!=e.type_url&&(t.type_url=String(e.type_url)),null!=e.value&&("string"==typeof e.value?u.base64.decode(e.value,t.value=u.newBuffer(u.base64.length(e.value)),0):e.value.length&&(t.value=e.value)),t)},H.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.type_url="",t.bytes===String?n.value="":(n.value=[],t.bytes!==Array&&(n.value=u.newBuffer(n.value)))),null!=e.type_url&&e.hasOwnProperty("type_url")&&(n.type_url=e.type_url),null!=e.value&&e.hasOwnProperty("value")&&(n.value=t.bytes===String?u.base64.encode(e.value,0,e.value.length):t.bytes===Array?Array.prototype.slice.call(e.value):e.value),n},H.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},H),n),F),c}); \ No newline at end of file diff --git a/node_modules/google-gax/build/protos/locations.json b/node_modules/google-gax/build/protos/locations.json new file mode 100644 index 0000000..31fd40f --- /dev/null +++ b/node_modules/google-gax/build/protos/locations.json @@ -0,0 +1 @@ +{"nested":{"google":{"nested":{"cloud":{"nested":{"location":{"options":{"cc_enable_arenas":true,"go_package":"google.golang.org/genproto/googleapis/cloud/location;location","java_multiple_files":true,"java_outer_classname":"LocationsProto","java_package":"com.google.cloud.location"},"nested":{"Locations":{"options":{"(google.api.default_host)":"cloud.googleapis.com","(google.api.oauth_scopes)":"https://www.googleapis.com/auth/cloud-platform"},"methods":{"ListLocations":{"requestType":"ListLocationsRequest","responseType":"ListLocationsResponse","options":{"(google.api.http).get":"/v1/{name=locations}","(google.api.http).additional_bindings.get":"/v1/{name=projects/*}/locations"},"parsedOptions":[{"(google.api.http)":{"get":"/v1/{name=locations}","additional_bindings":{"get":"/v1/{name=projects/*}/locations"}}}]},"GetLocation":{"requestType":"GetLocationRequest","responseType":"Location","options":{"(google.api.http).get":"/v1/{name=locations/*}","(google.api.http).additional_bindings.get":"/v1/{name=projects/*/locations/*}"},"parsedOptions":[{"(google.api.http)":{"get":"/v1/{name=locations/*}","additional_bindings":{"get":"/v1/{name=projects/*/locations/*}"}}}]}}},"ListLocationsRequest":{"fields":{"name":{"type":"string","id":1},"filter":{"type":"string","id":2},"pageSize":{"type":"int32","id":3},"pageToken":{"type":"string","id":4}}},"ListLocationsResponse":{"fields":{"locations":{"rule":"repeated","type":"Location","id":1},"nextPageToken":{"type":"string","id":2}}},"GetLocationRequest":{"fields":{"name":{"type":"string","id":1}}},"Location":{"fields":{"name":{"type":"string","id":1},"locationId":{"type":"string","id":4},"displayName":{"type":"string","id":5},"labels":{"keyType":"string","type":"string","id":2},"metadata":{"type":"google.protobuf.Any","id":3}}}}}}},"api":{"options":{"go_package":"google.golang.org/genproto/googleapis/api/annotations;annotations","java_multiple_files":true,"java_outer_classname":"ClientProto","java_package":"com.google.api","objc_class_prefix":"GAPI","cc_enable_arenas":true},"nested":{"http":{"type":"HttpRule","id":72295728,"extend":"google.protobuf.MethodOptions"},"Http":{"fields":{"rules":{"rule":"repeated","type":"HttpRule","id":1},"fullyDecodeReservedExpansion":{"type":"bool","id":2}}},"HttpRule":{"oneofs":{"pattern":{"oneof":["get","put","post","delete","patch","custom"]}},"fields":{"selector":{"type":"string","id":1},"get":{"type":"string","id":2},"put":{"type":"string","id":3},"post":{"type":"string","id":4},"delete":{"type":"string","id":5},"patch":{"type":"string","id":6},"custom":{"type":"CustomHttpPattern","id":8},"body":{"type":"string","id":7},"responseBody":{"type":"string","id":12},"additionalBindings":{"rule":"repeated","type":"HttpRule","id":11}}},"CustomHttpPattern":{"fields":{"kind":{"type":"string","id":1},"path":{"type":"string","id":2}}},"methodSignature":{"rule":"repeated","type":"string","id":1051,"extend":"google.protobuf.MethodOptions"},"defaultHost":{"type":"string","id":1049,"extend":"google.protobuf.ServiceOptions"},"oauthScopes":{"type":"string","id":1050,"extend":"google.protobuf.ServiceOptions"}}},"protobuf":{"options":{"go_package":"google.golang.org/protobuf/types/descriptorpb","java_package":"com.google.protobuf","java_outer_classname":"DescriptorProtos","csharp_namespace":"Google.Protobuf.Reflection","objc_class_prefix":"GPB","cc_enable_arenas":true,"optimize_for":"SPEED"},"nested":{"FileDescriptorSet":{"fields":{"file":{"rule":"repeated","type":"FileDescriptorProto","id":1}}},"FileDescriptorProto":{"fields":{"name":{"type":"string","id":1},"package":{"type":"string","id":2},"dependency":{"rule":"repeated","type":"string","id":3},"publicDependency":{"rule":"repeated","type":"int32","id":10,"options":{"packed":false}},"weakDependency":{"rule":"repeated","type":"int32","id":11,"options":{"packed":false}},"messageType":{"rule":"repeated","type":"DescriptorProto","id":4},"enumType":{"rule":"repeated","type":"EnumDescriptorProto","id":5},"service":{"rule":"repeated","type":"ServiceDescriptorProto","id":6},"extension":{"rule":"repeated","type":"FieldDescriptorProto","id":7},"options":{"type":"FileOptions","id":8},"sourceCodeInfo":{"type":"SourceCodeInfo","id":9},"syntax":{"type":"string","id":12}}},"DescriptorProto":{"fields":{"name":{"type":"string","id":1},"field":{"rule":"repeated","type":"FieldDescriptorProto","id":2},"extension":{"rule":"repeated","type":"FieldDescriptorProto","id":6},"nestedType":{"rule":"repeated","type":"DescriptorProto","id":3},"enumType":{"rule":"repeated","type":"EnumDescriptorProto","id":4},"extensionRange":{"rule":"repeated","type":"ExtensionRange","id":5},"oneofDecl":{"rule":"repeated","type":"OneofDescriptorProto","id":8},"options":{"type":"MessageOptions","id":7},"reservedRange":{"rule":"repeated","type":"ReservedRange","id":9},"reservedName":{"rule":"repeated","type":"string","id":10}},"nested":{"ExtensionRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2},"options":{"type":"ExtensionRangeOptions","id":3}}},"ReservedRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2}}}}},"ExtensionRangeOptions":{"fields":{"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]]},"FieldDescriptorProto":{"fields":{"name":{"type":"string","id":1},"number":{"type":"int32","id":3},"label":{"type":"Label","id":4},"type":{"type":"Type","id":5},"typeName":{"type":"string","id":6},"extendee":{"type":"string","id":2},"defaultValue":{"type":"string","id":7},"oneofIndex":{"type":"int32","id":9},"jsonName":{"type":"string","id":10},"options":{"type":"FieldOptions","id":8},"proto3Optional":{"type":"bool","id":17}},"nested":{"Type":{"values":{"TYPE_DOUBLE":1,"TYPE_FLOAT":2,"TYPE_INT64":3,"TYPE_UINT64":4,"TYPE_INT32":5,"TYPE_FIXED64":6,"TYPE_FIXED32":7,"TYPE_BOOL":8,"TYPE_STRING":9,"TYPE_GROUP":10,"TYPE_MESSAGE":11,"TYPE_BYTES":12,"TYPE_UINT32":13,"TYPE_ENUM":14,"TYPE_SFIXED32":15,"TYPE_SFIXED64":16,"TYPE_SINT32":17,"TYPE_SINT64":18}},"Label":{"values":{"LABEL_OPTIONAL":1,"LABEL_REQUIRED":2,"LABEL_REPEATED":3}}}},"OneofDescriptorProto":{"fields":{"name":{"type":"string","id":1},"options":{"type":"OneofOptions","id":2}}},"EnumDescriptorProto":{"fields":{"name":{"type":"string","id":1},"value":{"rule":"repeated","type":"EnumValueDescriptorProto","id":2},"options":{"type":"EnumOptions","id":3},"reservedRange":{"rule":"repeated","type":"EnumReservedRange","id":4},"reservedName":{"rule":"repeated","type":"string","id":5}},"nested":{"EnumReservedRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2}}}}},"EnumValueDescriptorProto":{"fields":{"name":{"type":"string","id":1},"number":{"type":"int32","id":2},"options":{"type":"EnumValueOptions","id":3}}},"ServiceDescriptorProto":{"fields":{"name":{"type":"string","id":1},"method":{"rule":"repeated","type":"MethodDescriptorProto","id":2},"options":{"type":"ServiceOptions","id":3}}},"MethodDescriptorProto":{"fields":{"name":{"type":"string","id":1},"inputType":{"type":"string","id":2},"outputType":{"type":"string","id":3},"options":{"type":"MethodOptions","id":4},"clientStreaming":{"type":"bool","id":5,"options":{"default":false}},"serverStreaming":{"type":"bool","id":6,"options":{"default":false}}}},"FileOptions":{"fields":{"javaPackage":{"type":"string","id":1},"javaOuterClassname":{"type":"string","id":8},"javaMultipleFiles":{"type":"bool","id":10,"options":{"default":false}},"javaGenerateEqualsAndHash":{"type":"bool","id":20,"options":{"deprecated":true}},"javaStringCheckUtf8":{"type":"bool","id":27,"options":{"default":false}},"optimizeFor":{"type":"OptimizeMode","id":9,"options":{"default":"SPEED"}},"goPackage":{"type":"string","id":11},"ccGenericServices":{"type":"bool","id":16,"options":{"default":false}},"javaGenericServices":{"type":"bool","id":17,"options":{"default":false}},"pyGenericServices":{"type":"bool","id":18,"options":{"default":false}},"phpGenericServices":{"type":"bool","id":42,"options":{"default":false}},"deprecated":{"type":"bool","id":23,"options":{"default":false}},"ccEnableArenas":{"type":"bool","id":31,"options":{"default":true}},"objcClassPrefix":{"type":"string","id":36},"csharpNamespace":{"type":"string","id":37},"swiftPrefix":{"type":"string","id":39},"phpClassPrefix":{"type":"string","id":40},"phpNamespace":{"type":"string","id":41},"phpMetadataNamespace":{"type":"string","id":44},"rubyPackage":{"type":"string","id":45},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"reserved":[[38,38]],"nested":{"OptimizeMode":{"values":{"SPEED":1,"CODE_SIZE":2,"LITE_RUNTIME":3}}}},"MessageOptions":{"fields":{"messageSetWireFormat":{"type":"bool","id":1,"options":{"default":false}},"noStandardDescriptorAccessor":{"type":"bool","id":2,"options":{"default":false}},"deprecated":{"type":"bool","id":3,"options":{"default":false}},"mapEntry":{"type":"bool","id":7},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"reserved":[[8,8],[9,9]]},"FieldOptions":{"fields":{"ctype":{"type":"CType","id":1,"options":{"default":"STRING"}},"packed":{"type":"bool","id":2},"jstype":{"type":"JSType","id":6,"options":{"default":"JS_NORMAL"}},"lazy":{"type":"bool","id":5,"options":{"default":false}},"deprecated":{"type":"bool","id":3,"options":{"default":false}},"weak":{"type":"bool","id":10,"options":{"default":false}},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"reserved":[[4,4]],"nested":{"CType":{"values":{"STRING":0,"CORD":1,"STRING_PIECE":2}},"JSType":{"values":{"JS_NORMAL":0,"JS_STRING":1,"JS_NUMBER":2}}}},"OneofOptions":{"fields":{"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]]},"EnumOptions":{"fields":{"allowAlias":{"type":"bool","id":2},"deprecated":{"type":"bool","id":3,"options":{"default":false}},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"reserved":[[5,5]]},"EnumValueOptions":{"fields":{"deprecated":{"type":"bool","id":1,"options":{"default":false}},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]]},"ServiceOptions":{"fields":{"deprecated":{"type":"bool","id":33,"options":{"default":false}},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]]},"MethodOptions":{"fields":{"deprecated":{"type":"bool","id":33,"options":{"default":false}},"idempotencyLevel":{"type":"IdempotencyLevel","id":34,"options":{"default":"IDEMPOTENCY_UNKNOWN"}},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"nested":{"IdempotencyLevel":{"values":{"IDEMPOTENCY_UNKNOWN":0,"NO_SIDE_EFFECTS":1,"IDEMPOTENT":2}}}},"UninterpretedOption":{"fields":{"name":{"rule":"repeated","type":"NamePart","id":2},"identifierValue":{"type":"string","id":3},"positiveIntValue":{"type":"uint64","id":4},"negativeIntValue":{"type":"int64","id":5},"doubleValue":{"type":"double","id":6},"stringValue":{"type":"bytes","id":7},"aggregateValue":{"type":"string","id":8}},"nested":{"NamePart":{"fields":{"namePart":{"rule":"required","type":"string","id":1},"isExtension":{"rule":"required","type":"bool","id":2}}}}},"SourceCodeInfo":{"fields":{"location":{"rule":"repeated","type":"Location","id":1}},"nested":{"Location":{"fields":{"path":{"rule":"repeated","type":"int32","id":1},"span":{"rule":"repeated","type":"int32","id":2},"leadingComments":{"type":"string","id":3},"trailingComments":{"type":"string","id":4},"leadingDetachedComments":{"rule":"repeated","type":"string","id":6}}}}},"GeneratedCodeInfo":{"fields":{"annotation":{"rule":"repeated","type":"Annotation","id":1}},"nested":{"Annotation":{"fields":{"path":{"rule":"repeated","type":"int32","id":1},"sourceFile":{"type":"string","id":2},"begin":{"type":"int32","id":3},"end":{"type":"int32","id":4}}}}},"Any":{"fields":{"type_url":{"type":"string","id":1},"value":{"type":"bytes","id":2}}}}}}}}} \ No newline at end of file diff --git a/node_modules/google-gax/build/protos/operations.d.ts b/node_modules/google-gax/build/protos/operations.d.ts new file mode 100644 index 0000000..b76e34b --- /dev/null +++ b/node_modules/google-gax/build/protos/operations.d.ts @@ -0,0 +1,4783 @@ +/** + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Long = require('long'); +import * as $protobuf from "protobufjs"; +/** Namespace google. */ +export namespace google { + + /** Namespace longrunning. */ + namespace longrunning { + + /** Represents an Operations */ + class Operations extends $protobuf.rpc.Service { + + /** + * Constructs a new Operations service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new Operations service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): Operations; + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListOperationsResponse + */ + public listOperations(request: google.longrunning.IListOperationsRequest, callback: google.longrunning.Operations.ListOperationsCallback): void; + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @returns Promise + */ + public listOperations(request: google.longrunning.IListOperationsRequest): Promise; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public getOperation(request: google.longrunning.IGetOperationRequest, callback: google.longrunning.Operations.GetOperationCallback): void; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @returns Promise + */ + public getOperation(request: google.longrunning.IGetOperationRequest): Promise; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest, callback: google.longrunning.Operations.DeleteOperationCallback): void; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @returns Promise + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest): Promise; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest, callback: google.longrunning.Operations.CancelOperationCallback): void; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @returns Promise + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest): Promise; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest, callback: google.longrunning.Operations.WaitOperationCallback): void; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @returns Promise + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest): Promise; + } + + namespace Operations { + + /** + * Callback as used by {@link google.longrunning.Operations#listOperations}. + * @param error Error, if any + * @param [response] ListOperationsResponse + */ + type ListOperationsCallback = (error: (Error|null), response?: google.longrunning.ListOperationsResponse) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#getOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type GetOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#deleteOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#cancelOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type CancelOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#waitOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type WaitOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + } + + /** Properties of an Operation. */ + interface IOperation { + + /** Operation name */ + name?: (string|null); + + /** Operation metadata */ + metadata?: (google.protobuf.IAny|null); + + /** Operation done */ + done?: (boolean|null); + + /** Operation error */ + error?: (google.rpc.IStatus|null); + + /** Operation response */ + response?: (google.protobuf.IAny|null); + } + + /** Represents an Operation. */ + class Operation implements IOperation { + + /** + * Constructs a new Operation. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperation); + + /** Operation name. */ + public name: string; + + /** Operation metadata. */ + public metadata?: (google.protobuf.IAny|null); + + /** Operation done. */ + public done: boolean; + + /** Operation error. */ + public error?: (google.rpc.IStatus|null); + + /** Operation response. */ + public response?: (google.protobuf.IAny|null); + + /** Operation result. */ + public result?: ("error"|"response"); + + /** + * Creates a new Operation instance using the specified properties. + * @param [properties] Properties to set + * @returns Operation instance + */ + public static create(properties?: google.longrunning.IOperation): google.longrunning.Operation; + + /** + * Encodes the specified Operation message. Does not implicitly {@link google.longrunning.Operation.verify|verify} messages. + * @param message Operation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.longrunning.IOperation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Operation message, length delimited. Does not implicitly {@link google.longrunning.Operation.verify|verify} messages. + * @param message Operation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.longrunning.IOperation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Operation message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Operation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.Operation; + + /** + * Decodes an Operation message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Operation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.Operation; + + /** + * Verifies an Operation message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an Operation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Operation + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.Operation; + + /** + * Creates a plain object from an Operation message. Also converts values to other types if specified. + * @param message Operation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.Operation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Operation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a GetOperationRequest. */ + interface IGetOperationRequest { + + /** GetOperationRequest name */ + name?: (string|null); + } + + /** Represents a GetOperationRequest. */ + class GetOperationRequest implements IGetOperationRequest { + + /** + * Constructs a new GetOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IGetOperationRequest); + + /** GetOperationRequest name. */ + public name: string; + + /** + * Creates a new GetOperationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetOperationRequest instance + */ + public static create(properties?: google.longrunning.IGetOperationRequest): google.longrunning.GetOperationRequest; + + /** + * Encodes the specified GetOperationRequest message. Does not implicitly {@link google.longrunning.GetOperationRequest.verify|verify} messages. + * @param message GetOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.longrunning.IGetOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.GetOperationRequest.verify|verify} messages. + * @param message GetOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.longrunning.IGetOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetOperationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.GetOperationRequest; + + /** + * Decodes a GetOperationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.GetOperationRequest; + + /** + * Verifies a GetOperationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.GetOperationRequest; + + /** + * Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified. + * @param message GetOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.GetOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a ListOperationsRequest. */ + interface IListOperationsRequest { + + /** ListOperationsRequest name */ + name?: (string|null); + + /** ListOperationsRequest filter */ + filter?: (string|null); + + /** ListOperationsRequest pageSize */ + pageSize?: (number|null); + + /** ListOperationsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListOperationsRequest. */ + class ListOperationsRequest implements IListOperationsRequest { + + /** + * Constructs a new ListOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsRequest); + + /** ListOperationsRequest name. */ + public name: string; + + /** ListOperationsRequest filter. */ + public filter: string; + + /** ListOperationsRequest pageSize. */ + public pageSize: number; + + /** ListOperationsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a new ListOperationsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListOperationsRequest instance + */ + public static create(properties?: google.longrunning.IListOperationsRequest): google.longrunning.ListOperationsRequest; + + /** + * Encodes the specified ListOperationsRequest message. Does not implicitly {@link google.longrunning.ListOperationsRequest.verify|verify} messages. + * @param message ListOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.longrunning.IListOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListOperationsRequest message, length delimited. Does not implicitly {@link google.longrunning.ListOperationsRequest.verify|verify} messages. + * @param message ListOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.longrunning.IListOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListOperationsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.ListOperationsRequest; + + /** + * Decodes a ListOperationsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.ListOperationsRequest; + + /** + * Verifies a ListOperationsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsRequest; + + /** + * Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified. + * @param message ListOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a ListOperationsResponse. */ + interface IListOperationsResponse { + + /** ListOperationsResponse operations */ + operations?: (google.longrunning.IOperation[]|null); + + /** ListOperationsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListOperationsResponse. */ + class ListOperationsResponse implements IListOperationsResponse { + + /** + * Constructs a new ListOperationsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsResponse); + + /** ListOperationsResponse operations. */ + public operations: google.longrunning.IOperation[]; + + /** ListOperationsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a new ListOperationsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ListOperationsResponse instance + */ + public static create(properties?: google.longrunning.IListOperationsResponse): google.longrunning.ListOperationsResponse; + + /** + * Encodes the specified ListOperationsResponse message. Does not implicitly {@link google.longrunning.ListOperationsResponse.verify|verify} messages. + * @param message ListOperationsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.longrunning.IListOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListOperationsResponse message, length delimited. Does not implicitly {@link google.longrunning.ListOperationsResponse.verify|verify} messages. + * @param message ListOperationsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.longrunning.IListOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListOperationsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.ListOperationsResponse; + + /** + * Decodes a ListOperationsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.ListOperationsResponse; + + /** + * Verifies a ListOperationsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsResponse + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsResponse; + + /** + * Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified. + * @param message ListOperationsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a CancelOperationRequest. */ + interface ICancelOperationRequest { + + /** CancelOperationRequest name */ + name?: (string|null); + } + + /** Represents a CancelOperationRequest. */ + class CancelOperationRequest implements ICancelOperationRequest { + + /** + * Constructs a new CancelOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.ICancelOperationRequest); + + /** CancelOperationRequest name. */ + public name: string; + + /** + * Creates a new CancelOperationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns CancelOperationRequest instance + */ + public static create(properties?: google.longrunning.ICancelOperationRequest): google.longrunning.CancelOperationRequest; + + /** + * Encodes the specified CancelOperationRequest message. Does not implicitly {@link google.longrunning.CancelOperationRequest.verify|verify} messages. + * @param message CancelOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.longrunning.ICancelOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CancelOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.CancelOperationRequest.verify|verify} messages. + * @param message CancelOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.longrunning.ICancelOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CancelOperationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CancelOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.CancelOperationRequest; + + /** + * Decodes a CancelOperationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CancelOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.CancelOperationRequest; + + /** + * Verifies a CancelOperationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CancelOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.CancelOperationRequest; + + /** + * Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified. + * @param message CancelOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.CancelOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CancelOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a DeleteOperationRequest. */ + interface IDeleteOperationRequest { + + /** DeleteOperationRequest name */ + name?: (string|null); + } + + /** Represents a DeleteOperationRequest. */ + class DeleteOperationRequest implements IDeleteOperationRequest { + + /** + * Constructs a new DeleteOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IDeleteOperationRequest); + + /** DeleteOperationRequest name. */ + public name: string; + + /** + * Creates a new DeleteOperationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteOperationRequest instance + */ + public static create(properties?: google.longrunning.IDeleteOperationRequest): google.longrunning.DeleteOperationRequest; + + /** + * Encodes the specified DeleteOperationRequest message. Does not implicitly {@link google.longrunning.DeleteOperationRequest.verify|verify} messages. + * @param message DeleteOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.longrunning.IDeleteOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.DeleteOperationRequest.verify|verify} messages. + * @param message DeleteOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.longrunning.IDeleteOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteOperationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.DeleteOperationRequest; + + /** + * Decodes a DeleteOperationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.DeleteOperationRequest; + + /** + * Verifies a DeleteOperationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.DeleteOperationRequest; + + /** + * Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified. + * @param message DeleteOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.DeleteOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a WaitOperationRequest. */ + interface IWaitOperationRequest { + + /** WaitOperationRequest name */ + name?: (string|null); + + /** WaitOperationRequest timeout */ + timeout?: (google.protobuf.IDuration|null); + } + + /** Represents a WaitOperationRequest. */ + class WaitOperationRequest implements IWaitOperationRequest { + + /** + * Constructs a new WaitOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IWaitOperationRequest); + + /** WaitOperationRequest name. */ + public name: string; + + /** WaitOperationRequest timeout. */ + public timeout?: (google.protobuf.IDuration|null); + + /** + * Creates a new WaitOperationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns WaitOperationRequest instance + */ + public static create(properties?: google.longrunning.IWaitOperationRequest): google.longrunning.WaitOperationRequest; + + /** + * Encodes the specified WaitOperationRequest message. Does not implicitly {@link google.longrunning.WaitOperationRequest.verify|verify} messages. + * @param message WaitOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.longrunning.IWaitOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified WaitOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.WaitOperationRequest.verify|verify} messages. + * @param message WaitOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.longrunning.IWaitOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a WaitOperationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns WaitOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.WaitOperationRequest; + + /** + * Decodes a WaitOperationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns WaitOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.WaitOperationRequest; + + /** + * Verifies a WaitOperationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WaitOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.WaitOperationRequest; + + /** + * Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified. + * @param message WaitOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.WaitOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WaitOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of an OperationInfo. */ + interface IOperationInfo { + + /** OperationInfo responseType */ + responseType?: (string|null); + + /** OperationInfo metadataType */ + metadataType?: (string|null); + } + + /** Represents an OperationInfo. */ + class OperationInfo implements IOperationInfo { + + /** + * Constructs a new OperationInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperationInfo); + + /** OperationInfo responseType. */ + public responseType: string; + + /** OperationInfo metadataType. */ + public metadataType: string; + + /** + * Creates a new OperationInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns OperationInfo instance + */ + public static create(properties?: google.longrunning.IOperationInfo): google.longrunning.OperationInfo; + + /** + * Encodes the specified OperationInfo message. Does not implicitly {@link google.longrunning.OperationInfo.verify|verify} messages. + * @param message OperationInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.longrunning.IOperationInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified OperationInfo message, length delimited. Does not implicitly {@link google.longrunning.OperationInfo.verify|verify} messages. + * @param message OperationInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.longrunning.IOperationInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an OperationInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns OperationInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.OperationInfo; + + /** + * Decodes an OperationInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns OperationInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.OperationInfo; + + /** + * Verifies an OperationInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an OperationInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OperationInfo + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.OperationInfo; + + /** + * Creates a plain object from an OperationInfo message. Also converts values to other types if specified. + * @param message OperationInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.OperationInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OperationInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Namespace api. */ + namespace api { + + /** Properties of a Http. */ + interface IHttp { + + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); + + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); + } + + /** Represents a Http. */ + class Http implements IHttp { + + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); + + /** Http rules. */ + public rules: google.api.IHttpRule[]; + + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; + + /** + * Creates a new Http instance using the specified properties. + * @param [properties] Properties to set + * @returns Http instance + */ + public static create(properties?: google.api.IHttp): google.api.Http; + + /** + * Encodes the specified Http message. Does not implicitly {@link google.api.Http.verify|verify} messages. + * @param message Http message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Http message, length delimited. Does not implicitly {@link google.api.Http.verify|verify} messages. + * @param message Http message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Http message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Http + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Http; + + /** + * Decodes a Http message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Http + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Http; + + /** + * Verifies a Http message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a HttpRule. */ + interface IHttpRule { + + /** HttpRule selector */ + selector?: (string|null); + + /** HttpRule get */ + get?: (string|null); + + /** HttpRule put */ + put?: (string|null); + + /** HttpRule post */ + post?: (string|null); + + /** HttpRule delete */ + "delete"?: (string|null); + + /** HttpRule patch */ + patch?: (string|null); + + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body */ + body?: (string|null); + + /** HttpRule responseBody */ + responseBody?: (string|null); + + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); + } + + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { + + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); + + /** HttpRule selector. */ + public selector: string; + + /** HttpRule get. */ + public get: string; + + /** HttpRule put. */ + public put: string; + + /** HttpRule post. */ + public post: string; + + /** HttpRule delete. */ + public delete: string; + + /** HttpRule patch. */ + public patch: string; + + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body. */ + public body: string; + + /** HttpRule responseBody. */ + public responseBody: string; + + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; + + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + + /** + * Creates a new HttpRule instance using the specified properties. + * @param [properties] Properties to set + * @returns HttpRule instance + */ + public static create(properties?: google.api.IHttpRule): google.api.HttpRule; + + /** + * Encodes the specified HttpRule message. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. + * @param message HttpRule message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified HttpRule message, length delimited. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. + * @param message HttpRule message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a HttpRule message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns HttpRule + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.HttpRule; + + /** + * Decodes a HttpRule message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns HttpRule + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.HttpRule; + + /** + * Verifies a HttpRule message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { + + /** CustomHttpPattern kind */ + kind?: (string|null); + + /** CustomHttpPattern path */ + path?: (string|null); + } + + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { + + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); + + /** CustomHttpPattern kind. */ + public kind: string; + + /** CustomHttpPattern path. */ + public path: string; + + /** + * Creates a new CustomHttpPattern instance using the specified properties. + * @param [properties] Properties to set + * @returns CustomHttpPattern instance + */ + public static create(properties?: google.api.ICustomHttpPattern): google.api.CustomHttpPattern; + + /** + * Encodes the specified CustomHttpPattern message. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. + * @param message CustomHttpPattern message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CustomHttpPattern message, length delimited. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. + * @param message CustomHttpPattern message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CustomHttpPattern message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CustomHttpPattern + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.CustomHttpPattern; + + /** + * Decodes a CustomHttpPattern message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CustomHttpPattern + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.CustomHttpPattern; + + /** + * Verifies a CustomHttpPattern message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Namespace protobuf. */ + namespace protobuf { + + /** Properties of a FileDescriptorSet. */ + interface IFileDescriptorSet { + + /** FileDescriptorSet file */ + file?: (google.protobuf.IFileDescriptorProto[]|null); + } + + /** Represents a FileDescriptorSet. */ + class FileDescriptorSet implements IFileDescriptorSet { + + /** + * Constructs a new FileDescriptorSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorSet); + + /** FileDescriptorSet file. */ + public file: google.protobuf.IFileDescriptorProto[]; + + /** + * Creates a new FileDescriptorSet instance using the specified properties. + * @param [properties] Properties to set + * @returns FileDescriptorSet instance + */ + public static create(properties?: google.protobuf.IFileDescriptorSet): google.protobuf.FileDescriptorSet; + + /** + * Encodes the specified FileDescriptorSet message. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. + * @param message FileDescriptorSet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FileDescriptorSet message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. + * @param message FileDescriptorSet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FileDescriptorSet message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FileDescriptorSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorSet; + + /** + * Decodes a FileDescriptorSet message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FileDescriptorSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorSet; + + /** + * Verifies a FileDescriptorSet message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; + + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @param message FileDescriptorSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a FileDescriptorProto. */ + interface IFileDescriptorProto { + + /** FileDescriptorProto name */ + name?: (string|null); + + /** FileDescriptorProto package */ + "package"?: (string|null); + + /** FileDescriptorProto dependency */ + dependency?: (string[]|null); + + /** FileDescriptorProto publicDependency */ + publicDependency?: (number[]|null); + + /** FileDescriptorProto weakDependency */ + weakDependency?: (number[]|null); + + /** FileDescriptorProto messageType */ + messageType?: (google.protobuf.IDescriptorProto[]|null); + + /** FileDescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** FileDescriptorProto service */ + service?: (google.protobuf.IServiceDescriptorProto[]|null); + + /** FileDescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** FileDescriptorProto options */ + options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo */ + sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax */ + syntax?: (string|null); + } + + /** Represents a FileDescriptorProto. */ + class FileDescriptorProto implements IFileDescriptorProto { + + /** + * Constructs a new FileDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorProto); + + /** FileDescriptorProto name. */ + public name: string; + + /** FileDescriptorProto package. */ + public package: string; + + /** FileDescriptorProto dependency. */ + public dependency: string[]; + + /** FileDescriptorProto publicDependency. */ + public publicDependency: number[]; + + /** FileDescriptorProto weakDependency. */ + public weakDependency: number[]; + + /** FileDescriptorProto messageType. */ + public messageType: google.protobuf.IDescriptorProto[]; + + /** FileDescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** FileDescriptorProto service. */ + public service: google.protobuf.IServiceDescriptorProto[]; + + /** FileDescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** FileDescriptorProto options. */ + public options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo. */ + public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax. */ + public syntax: string; + + /** + * Creates a new FileDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns FileDescriptorProto instance + */ + public static create(properties?: google.protobuf.IFileDescriptorProto): google.protobuf.FileDescriptorProto; + + /** + * Encodes the specified FileDescriptorProto message. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. + * @param message FileDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FileDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. + * @param message FileDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FileDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FileDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorProto; + + /** + * Decodes a FileDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FileDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorProto; + + /** + * Verifies a FileDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; + + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @param message FileDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a DescriptorProto. */ + interface IDescriptorProto { + + /** DescriptorProto name */ + name?: (string|null); + + /** DescriptorProto field */ + field?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto nestedType */ + nestedType?: (google.protobuf.IDescriptorProto[]|null); + + /** DescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** DescriptorProto extensionRange */ + extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); + + /** DescriptorProto oneofDecl */ + oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); + + /** DescriptorProto options */ + options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange */ + reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); + + /** DescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents a DescriptorProto. */ + class DescriptorProto implements IDescriptorProto { + + /** + * Constructs a new DescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDescriptorProto); + + /** DescriptorProto name. */ + public name: string; + + /** DescriptorProto field. */ + public field: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto nestedType. */ + public nestedType: google.protobuf.IDescriptorProto[]; + + /** DescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** DescriptorProto extensionRange. */ + public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; + + /** DescriptorProto oneofDecl. */ + public oneofDecl: google.protobuf.IOneofDescriptorProto[]; + + /** DescriptorProto options. */ + public options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange. */ + public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; + + /** DescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates a new DescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns DescriptorProto instance + */ + public static create(properties?: google.protobuf.IDescriptorProto): google.protobuf.DescriptorProto; + + /** + * Encodes the specified DescriptorProto message. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. + * @param message DescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. + * @param message DescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto; + + /** + * Decodes a DescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto; + + /** + * Verifies a DescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; + + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @param message DescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace DescriptorProto { + + /** Properties of an ExtensionRange. */ + interface IExtensionRange { + + /** ExtensionRange start */ + start?: (number|null); + + /** ExtensionRange end */ + end?: (number|null); + + /** ExtensionRange options */ + options?: (google.protobuf.IExtensionRangeOptions|null); + } + + /** Represents an ExtensionRange. */ + class ExtensionRange implements IExtensionRange { + + /** + * Constructs a new ExtensionRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); + + /** ExtensionRange start. */ + public start: number; + + /** ExtensionRange end. */ + public end: number; + + /** ExtensionRange options. */ + public options?: (google.protobuf.IExtensionRangeOptions|null); + + /** + * Creates a new ExtensionRange instance using the specified properties. + * @param [properties] Properties to set + * @returns ExtensionRange instance + */ + public static create(properties?: google.protobuf.DescriptorProto.IExtensionRange): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Encodes the specified ExtensionRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. + * @param message ExtensionRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExtensionRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. + * @param message ExtensionRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExtensionRange message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExtensionRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Decodes an ExtensionRange message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExtensionRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Verifies an ExtensionRange message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @param message ExtensionRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a ReservedRange. */ + interface IReservedRange { + + /** ReservedRange start */ + start?: (number|null); + + /** ReservedRange end */ + end?: (number|null); + } + + /** Represents a ReservedRange. */ + class ReservedRange implements IReservedRange { + + /** + * Constructs a new ReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); + + /** ReservedRange start. */ + public start: number; + + /** ReservedRange end. */ + public end: number; + + /** + * Creates a new ReservedRange instance using the specified properties. + * @param [properties] Properties to set + * @returns ReservedRange instance + */ + public static create(properties?: google.protobuf.DescriptorProto.IReservedRange): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Encodes the specified ReservedRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. + * @param message ReservedRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReservedRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. + * @param message ReservedRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReservedRange message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Decodes a ReservedRange message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Verifies a ReservedRange message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @param message ReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Properties of an ExtensionRangeOptions. */ + interface IExtensionRangeOptions { + + /** ExtensionRangeOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an ExtensionRangeOptions. */ + class ExtensionRangeOptions implements IExtensionRangeOptions { + + /** + * Constructs a new ExtensionRangeOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IExtensionRangeOptions); + + /** ExtensionRangeOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new ExtensionRangeOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns ExtensionRangeOptions instance + */ + public static create(properties?: google.protobuf.IExtensionRangeOptions): google.protobuf.ExtensionRangeOptions; + + /** + * Encodes the specified ExtensionRangeOptions message. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages. + * @param message ExtensionRangeOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IExtensionRangeOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExtensionRangeOptions message, length delimited. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages. + * @param message ExtensionRangeOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IExtensionRangeOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExtensionRangeOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExtensionRangeOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ExtensionRangeOptions; + + /** + * Decodes an ExtensionRangeOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExtensionRangeOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ExtensionRangeOptions; + + /** + * Verifies an ExtensionRangeOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRangeOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @param message ExtensionRangeOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a FieldDescriptorProto. */ + interface IFieldDescriptorProto { + + /** FieldDescriptorProto name */ + name?: (string|null); + + /** FieldDescriptorProto number */ + number?: (number|null); + + /** FieldDescriptorProto label */ + label?: (google.protobuf.FieldDescriptorProto.Label|null); + + /** FieldDescriptorProto type */ + type?: (google.protobuf.FieldDescriptorProto.Type|null); + + /** FieldDescriptorProto typeName */ + typeName?: (string|null); + + /** FieldDescriptorProto extendee */ + extendee?: (string|null); + + /** FieldDescriptorProto defaultValue */ + defaultValue?: (string|null); + + /** FieldDescriptorProto oneofIndex */ + oneofIndex?: (number|null); + + /** FieldDescriptorProto jsonName */ + jsonName?: (string|null); + + /** FieldDescriptorProto options */ + options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional */ + proto3Optional?: (boolean|null); + } + + /** Represents a FieldDescriptorProto. */ + class FieldDescriptorProto implements IFieldDescriptorProto { + + /** + * Constructs a new FieldDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldDescriptorProto); + + /** FieldDescriptorProto name. */ + public name: string; + + /** FieldDescriptorProto number. */ + public number: number; + + /** FieldDescriptorProto label. */ + public label: google.protobuf.FieldDescriptorProto.Label; + + /** FieldDescriptorProto type. */ + public type: google.protobuf.FieldDescriptorProto.Type; + + /** FieldDescriptorProto typeName. */ + public typeName: string; + + /** FieldDescriptorProto extendee. */ + public extendee: string; + + /** FieldDescriptorProto defaultValue. */ + public defaultValue: string; + + /** FieldDescriptorProto oneofIndex. */ + public oneofIndex: number; + + /** FieldDescriptorProto jsonName. */ + public jsonName: string; + + /** FieldDescriptorProto options. */ + public options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional. */ + public proto3Optional: boolean; + + /** + * Creates a new FieldDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns FieldDescriptorProto instance + */ + public static create(properties?: google.protobuf.IFieldDescriptorProto): google.protobuf.FieldDescriptorProto; + + /** + * Encodes the specified FieldDescriptorProto message. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. + * @param message FieldDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FieldDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. + * @param message FieldDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FieldDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FieldDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldDescriptorProto; + + /** + * Decodes a FieldDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FieldDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldDescriptorProto; + + /** + * Verifies a FieldDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @param message FieldDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace FieldDescriptorProto { + + /** Type enum. */ + enum Type { + TYPE_DOUBLE = 1, + TYPE_FLOAT = 2, + TYPE_INT64 = 3, + TYPE_UINT64 = 4, + TYPE_INT32 = 5, + TYPE_FIXED64 = 6, + TYPE_FIXED32 = 7, + TYPE_BOOL = 8, + TYPE_STRING = 9, + TYPE_GROUP = 10, + TYPE_MESSAGE = 11, + TYPE_BYTES = 12, + TYPE_UINT32 = 13, + TYPE_ENUM = 14, + TYPE_SFIXED32 = 15, + TYPE_SFIXED64 = 16, + TYPE_SINT32 = 17, + TYPE_SINT64 = 18 + } + + /** Label enum. */ + enum Label { + LABEL_OPTIONAL = 1, + LABEL_REQUIRED = 2, + LABEL_REPEATED = 3 + } + } + + /** Properties of an OneofDescriptorProto. */ + interface IOneofDescriptorProto { + + /** OneofDescriptorProto name */ + name?: (string|null); + + /** OneofDescriptorProto options */ + options?: (google.protobuf.IOneofOptions|null); + } + + /** Represents an OneofDescriptorProto. */ + class OneofDescriptorProto implements IOneofDescriptorProto { + + /** + * Constructs a new OneofDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofDescriptorProto); + + /** OneofDescriptorProto name. */ + public name: string; + + /** OneofDescriptorProto options. */ + public options?: (google.protobuf.IOneofOptions|null); + + /** + * Creates a new OneofDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns OneofDescriptorProto instance + */ + public static create(properties?: google.protobuf.IOneofDescriptorProto): google.protobuf.OneofDescriptorProto; + + /** + * Encodes the specified OneofDescriptorProto message. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. + * @param message OneofDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified OneofDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. + * @param message OneofDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an OneofDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns OneofDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofDescriptorProto; + + /** + * Decodes an OneofDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns OneofDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofDescriptorProto; + + /** + * Verifies an OneofDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; + + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @param message OneofDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of an EnumDescriptorProto. */ + interface IEnumDescriptorProto { + + /** EnumDescriptorProto name */ + name?: (string|null); + + /** EnumDescriptorProto value */ + value?: (google.protobuf.IEnumValueDescriptorProto[]|null); + + /** EnumDescriptorProto options */ + options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange */ + reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); + + /** EnumDescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents an EnumDescriptorProto. */ + class EnumDescriptorProto implements IEnumDescriptorProto { + + /** + * Constructs a new EnumDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumDescriptorProto); + + /** EnumDescriptorProto name. */ + public name: string; + + /** EnumDescriptorProto value. */ + public value: google.protobuf.IEnumValueDescriptorProto[]; + + /** EnumDescriptorProto options. */ + public options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange. */ + public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; + + /** EnumDescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates a new EnumDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumDescriptorProto instance + */ + public static create(properties?: google.protobuf.IEnumDescriptorProto): google.protobuf.EnumDescriptorProto; + + /** + * Encodes the specified EnumDescriptorProto message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. + * @param message EnumDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. + * @param message EnumDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto; + + /** + * Decodes an EnumDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto; + + /** + * Verifies an EnumDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; + + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @param message EnumDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace EnumDescriptorProto { + + /** Properties of an EnumReservedRange. */ + interface IEnumReservedRange { + + /** EnumReservedRange start */ + start?: (number|null); + + /** EnumReservedRange end */ + end?: (number|null); + } + + /** Represents an EnumReservedRange. */ + class EnumReservedRange implements IEnumReservedRange { + + /** + * Constructs a new EnumReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); + + /** EnumReservedRange start. */ + public start: number; + + /** EnumReservedRange end. */ + public end: number; + + /** + * Creates a new EnumReservedRange instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumReservedRange instance + */ + public static create(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Encodes the specified EnumReservedRange message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages. + * @param message EnumReservedRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.EnumDescriptorProto.IEnumReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumReservedRange message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages. + * @param message EnumReservedRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.EnumDescriptorProto.IEnumReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumReservedRange message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Decodes an EnumReservedRange message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Verifies an EnumReservedRange message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @param message EnumReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Properties of an EnumValueDescriptorProto. */ + interface IEnumValueDescriptorProto { + + /** EnumValueDescriptorProto name */ + name?: (string|null); + + /** EnumValueDescriptorProto number */ + number?: (number|null); + + /** EnumValueDescriptorProto options */ + options?: (google.protobuf.IEnumValueOptions|null); + } + + /** Represents an EnumValueDescriptorProto. */ + class EnumValueDescriptorProto implements IEnumValueDescriptorProto { + + /** + * Constructs a new EnumValueDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueDescriptorProto); + + /** EnumValueDescriptorProto name. */ + public name: string; + + /** EnumValueDescriptorProto number. */ + public number: number; + + /** EnumValueDescriptorProto options. */ + public options?: (google.protobuf.IEnumValueOptions|null); + + /** + * Creates a new EnumValueDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumValueDescriptorProto instance + */ + public static create(properties?: google.protobuf.IEnumValueDescriptorProto): google.protobuf.EnumValueDescriptorProto; + + /** + * Encodes the specified EnumValueDescriptorProto message. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. + * @param message EnumValueDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumValueDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. + * @param message EnumValueDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumValueDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumValueDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueDescriptorProto; + + /** + * Decodes an EnumValueDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumValueDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueDescriptorProto; + + /** + * Verifies an EnumValueDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; + + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @param message EnumValueDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a ServiceDescriptorProto. */ + interface IServiceDescriptorProto { + + /** ServiceDescriptorProto name */ + name?: (string|null); + + /** ServiceDescriptorProto method */ + method?: (google.protobuf.IMethodDescriptorProto[]|null); + + /** ServiceDescriptorProto options */ + options?: (google.protobuf.IServiceOptions|null); + } + + /** Represents a ServiceDescriptorProto. */ + class ServiceDescriptorProto implements IServiceDescriptorProto { + + /** + * Constructs a new ServiceDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceDescriptorProto); + + /** ServiceDescriptorProto name. */ + public name: string; + + /** ServiceDescriptorProto method. */ + public method: google.protobuf.IMethodDescriptorProto[]; + + /** ServiceDescriptorProto options. */ + public options?: (google.protobuf.IServiceOptions|null); + + /** + * Creates a new ServiceDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns ServiceDescriptorProto instance + */ + public static create(properties?: google.protobuf.IServiceDescriptorProto): google.protobuf.ServiceDescriptorProto; + + /** + * Encodes the specified ServiceDescriptorProto message. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. + * @param message ServiceDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ServiceDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. + * @param message ServiceDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ServiceDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ServiceDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceDescriptorProto; + + /** + * Decodes a ServiceDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ServiceDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceDescriptorProto; + + /** + * Verifies a ServiceDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @param message ServiceDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a MethodDescriptorProto. */ + interface IMethodDescriptorProto { + + /** MethodDescriptorProto name */ + name?: (string|null); + + /** MethodDescriptorProto inputType */ + inputType?: (string|null); + + /** MethodDescriptorProto outputType */ + outputType?: (string|null); + + /** MethodDescriptorProto options */ + options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming */ + clientStreaming?: (boolean|null); + + /** MethodDescriptorProto serverStreaming */ + serverStreaming?: (boolean|null); + } + + /** Represents a MethodDescriptorProto. */ + class MethodDescriptorProto implements IMethodDescriptorProto { + + /** + * Constructs a new MethodDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodDescriptorProto); + + /** MethodDescriptorProto name. */ + public name: string; + + /** MethodDescriptorProto inputType. */ + public inputType: string; + + /** MethodDescriptorProto outputType. */ + public outputType: string; + + /** MethodDescriptorProto options. */ + public options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming. */ + public clientStreaming: boolean; + + /** MethodDescriptorProto serverStreaming. */ + public serverStreaming: boolean; + + /** + * Creates a new MethodDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns MethodDescriptorProto instance + */ + public static create(properties?: google.protobuf.IMethodDescriptorProto): google.protobuf.MethodDescriptorProto; + + /** + * Encodes the specified MethodDescriptorProto message. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. + * @param message MethodDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MethodDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. + * @param message MethodDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MethodDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MethodDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodDescriptorProto; + + /** + * Decodes a MethodDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MethodDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodDescriptorProto; + + /** + * Verifies a MethodDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @param message MethodDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a FileOptions. */ + interface IFileOptions { + + /** FileOptions javaPackage */ + javaPackage?: (string|null); + + /** FileOptions javaOuterClassname */ + javaOuterClassname?: (string|null); + + /** FileOptions javaMultipleFiles */ + javaMultipleFiles?: (boolean|null); + + /** FileOptions javaGenerateEqualsAndHash */ + javaGenerateEqualsAndHash?: (boolean|null); + + /** FileOptions javaStringCheckUtf8 */ + javaStringCheckUtf8?: (boolean|null); + + /** FileOptions optimizeFor */ + optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); + + /** FileOptions goPackage */ + goPackage?: (string|null); + + /** FileOptions ccGenericServices */ + ccGenericServices?: (boolean|null); + + /** FileOptions javaGenericServices */ + javaGenericServices?: (boolean|null); + + /** FileOptions pyGenericServices */ + pyGenericServices?: (boolean|null); + + /** FileOptions phpGenericServices */ + phpGenericServices?: (boolean|null); + + /** FileOptions deprecated */ + deprecated?: (boolean|null); + + /** FileOptions ccEnableArenas */ + ccEnableArenas?: (boolean|null); + + /** FileOptions objcClassPrefix */ + objcClassPrefix?: (string|null); + + /** FileOptions csharpNamespace */ + csharpNamespace?: (string|null); + + /** FileOptions swiftPrefix */ + swiftPrefix?: (string|null); + + /** FileOptions phpClassPrefix */ + phpClassPrefix?: (string|null); + + /** FileOptions phpNamespace */ + phpNamespace?: (string|null); + + /** FileOptions phpMetadataNamespace */ + phpMetadataNamespace?: (string|null); + + /** FileOptions rubyPackage */ + rubyPackage?: (string|null); + + /** FileOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents a FileOptions. */ + class FileOptions implements IFileOptions { + + /** + * Constructs a new FileOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileOptions); + + /** FileOptions javaPackage. */ + public javaPackage: string; + + /** FileOptions javaOuterClassname. */ + public javaOuterClassname: string; + + /** FileOptions javaMultipleFiles. */ + public javaMultipleFiles: boolean; + + /** FileOptions javaGenerateEqualsAndHash. */ + public javaGenerateEqualsAndHash: boolean; + + /** FileOptions javaStringCheckUtf8. */ + public javaStringCheckUtf8: boolean; + + /** FileOptions optimizeFor. */ + public optimizeFor: google.protobuf.FileOptions.OptimizeMode; + + /** FileOptions goPackage. */ + public goPackage: string; + + /** FileOptions ccGenericServices. */ + public ccGenericServices: boolean; + + /** FileOptions javaGenericServices. */ + public javaGenericServices: boolean; + + /** FileOptions pyGenericServices. */ + public pyGenericServices: boolean; + + /** FileOptions phpGenericServices. */ + public phpGenericServices: boolean; + + /** FileOptions deprecated. */ + public deprecated: boolean; + + /** FileOptions ccEnableArenas. */ + public ccEnableArenas: boolean; + + /** FileOptions objcClassPrefix. */ + public objcClassPrefix: string; + + /** FileOptions csharpNamespace. */ + public csharpNamespace: string; + + /** FileOptions swiftPrefix. */ + public swiftPrefix: string; + + /** FileOptions phpClassPrefix. */ + public phpClassPrefix: string; + + /** FileOptions phpNamespace. */ + public phpNamespace: string; + + /** FileOptions phpMetadataNamespace. */ + public phpMetadataNamespace: string; + + /** FileOptions rubyPackage. */ + public rubyPackage: string; + + /** FileOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new FileOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns FileOptions instance + */ + public static create(properties?: google.protobuf.IFileOptions): google.protobuf.FileOptions; + + /** + * Encodes the specified FileOptions message. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. + * @param message FileOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FileOptions message, length delimited. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. + * @param message FileOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FileOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FileOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileOptions; + + /** + * Decodes a FileOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FileOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileOptions; + + /** + * Verifies a FileOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; + + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @param message FileOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace FileOptions { + + /** OptimizeMode enum. */ + enum OptimizeMode { + SPEED = 1, + CODE_SIZE = 2, + LITE_RUNTIME = 3 + } + } + + /** Properties of a MessageOptions. */ + interface IMessageOptions { + + /** MessageOptions messageSetWireFormat */ + messageSetWireFormat?: (boolean|null); + + /** MessageOptions noStandardDescriptorAccessor */ + noStandardDescriptorAccessor?: (boolean|null); + + /** MessageOptions deprecated */ + deprecated?: (boolean|null); + + /** MessageOptions mapEntry */ + mapEntry?: (boolean|null); + + /** MessageOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents a MessageOptions. */ + class MessageOptions implements IMessageOptions { + + /** + * Constructs a new MessageOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMessageOptions); + + /** MessageOptions messageSetWireFormat. */ + public messageSetWireFormat: boolean; + + /** MessageOptions noStandardDescriptorAccessor. */ + public noStandardDescriptorAccessor: boolean; + + /** MessageOptions deprecated. */ + public deprecated: boolean; + + /** MessageOptions mapEntry. */ + public mapEntry: boolean; + + /** MessageOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new MessageOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns MessageOptions instance + */ + public static create(properties?: google.protobuf.IMessageOptions): google.protobuf.MessageOptions; + + /** + * Encodes the specified MessageOptions message. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. + * @param message MessageOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MessageOptions message, length delimited. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. + * @param message MessageOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MessageOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MessageOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MessageOptions; + + /** + * Decodes a MessageOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MessageOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MessageOptions; + + /** + * Verifies a MessageOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MessageOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; + + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @param message MessageOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MessageOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a FieldOptions. */ + interface IFieldOptions { + + /** FieldOptions ctype */ + ctype?: (google.protobuf.FieldOptions.CType|null); + + /** FieldOptions packed */ + packed?: (boolean|null); + + /** FieldOptions jstype */ + jstype?: (google.protobuf.FieldOptions.JSType|null); + + /** FieldOptions lazy */ + lazy?: (boolean|null); + + /** FieldOptions deprecated */ + deprecated?: (boolean|null); + + /** FieldOptions weak */ + weak?: (boolean|null); + + /** FieldOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents a FieldOptions. */ + class FieldOptions implements IFieldOptions { + + /** + * Constructs a new FieldOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldOptions); + + /** FieldOptions ctype. */ + public ctype: google.protobuf.FieldOptions.CType; + + /** FieldOptions packed. */ + public packed: boolean; + + /** FieldOptions jstype. */ + public jstype: google.protobuf.FieldOptions.JSType; + + /** FieldOptions lazy. */ + public lazy: boolean; + + /** FieldOptions deprecated. */ + public deprecated: boolean; + + /** FieldOptions weak. */ + public weak: boolean; + + /** FieldOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new FieldOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns FieldOptions instance + */ + public static create(properties?: google.protobuf.IFieldOptions): google.protobuf.FieldOptions; + + /** + * Encodes the specified FieldOptions message. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. + * @param message FieldOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FieldOptions message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. + * @param message FieldOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FieldOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FieldOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions; + + /** + * Decodes a FieldOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FieldOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions; + + /** + * Verifies a FieldOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; + + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @param message FieldOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace FieldOptions { + + /** CType enum. */ + enum CType { + STRING = 0, + CORD = 1, + STRING_PIECE = 2 + } + + /** JSType enum. */ + enum JSType { + JS_NORMAL = 0, + JS_STRING = 1, + JS_NUMBER = 2 + } + } + + /** Properties of an OneofOptions. */ + interface IOneofOptions { + + /** OneofOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an OneofOptions. */ + class OneofOptions implements IOneofOptions { + + /** + * Constructs a new OneofOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofOptions); + + /** OneofOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new OneofOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns OneofOptions instance + */ + public static create(properties?: google.protobuf.IOneofOptions): google.protobuf.OneofOptions; + + /** + * Encodes the specified OneofOptions message. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. + * @param message OneofOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified OneofOptions message, length delimited. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. + * @param message OneofOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an OneofOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns OneofOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofOptions; + + /** + * Decodes an OneofOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns OneofOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofOptions; + + /** + * Verifies an OneofOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @param message OneofOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of an EnumOptions. */ + interface IEnumOptions { + + /** EnumOptions allowAlias */ + allowAlias?: (boolean|null); + + /** EnumOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumOptions. */ + class EnumOptions implements IEnumOptions { + + /** + * Constructs a new EnumOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumOptions); + + /** EnumOptions allowAlias. */ + public allowAlias: boolean; + + /** EnumOptions deprecated. */ + public deprecated: boolean; + + /** EnumOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new EnumOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumOptions instance + */ + public static create(properties?: google.protobuf.IEnumOptions): google.protobuf.EnumOptions; + + /** + * Encodes the specified EnumOptions message. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. + * @param message EnumOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. + * @param message EnumOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumOptions; + + /** + * Decodes an EnumOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumOptions; + + /** + * Verifies an EnumOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @param message EnumOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of an EnumValueOptions. */ + interface IEnumValueOptions { + + /** EnumValueOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumValueOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumValueOptions. */ + class EnumValueOptions implements IEnumValueOptions { + + /** + * Constructs a new EnumValueOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueOptions); + + /** EnumValueOptions deprecated. */ + public deprecated: boolean; + + /** EnumValueOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new EnumValueOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumValueOptions instance + */ + public static create(properties?: google.protobuf.IEnumValueOptions): google.protobuf.EnumValueOptions; + + /** + * Encodes the specified EnumValueOptions message. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. + * @param message EnumValueOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumValueOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. + * @param message EnumValueOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumValueOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumValueOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueOptions; + + /** + * Decodes an EnumValueOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumValueOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueOptions; + + /** + * Verifies an EnumValueOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; + + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @param message EnumValueOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a ServiceOptions. */ + interface IServiceOptions { + + /** ServiceOptions deprecated */ + deprecated?: (boolean|null); + + /** ServiceOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ServiceOptions .google.api.defaultHost */ + ".google.api.defaultHost"?: (string|null); + + /** ServiceOptions .google.api.oauthScopes */ + ".google.api.oauthScopes"?: (string|null); + } + + /** Represents a ServiceOptions. */ + class ServiceOptions implements IServiceOptions { + + /** + * Constructs a new ServiceOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceOptions); + + /** ServiceOptions deprecated. */ + public deprecated: boolean; + + /** ServiceOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new ServiceOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns ServiceOptions instance + */ + public static create(properties?: google.protobuf.IServiceOptions): google.protobuf.ServiceOptions; + + /** + * Encodes the specified ServiceOptions message. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. + * @param message ServiceOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ServiceOptions message, length delimited. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. + * @param message ServiceOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ServiceOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ServiceOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceOptions; + + /** + * Decodes a ServiceOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ServiceOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceOptions; + + /** + * Verifies a ServiceOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @param message ServiceOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a MethodOptions. */ + interface IMethodOptions { + + /** MethodOptions deprecated */ + deprecated?: (boolean|null); + + /** MethodOptions idempotencyLevel */ + idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); + + /** MethodOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MethodOptions .google.longrunning.operationInfo */ + ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); + + /** MethodOptions .google.api.http */ + ".google.api.http"?: (google.api.IHttpRule|null); + + /** MethodOptions .google.api.methodSignature */ + ".google.api.methodSignature"?: (string[]|null); + } + + /** Represents a MethodOptions. */ + class MethodOptions implements IMethodOptions { + + /** + * Constructs a new MethodOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodOptions); + + /** MethodOptions deprecated. */ + public deprecated: boolean; + + /** MethodOptions idempotencyLevel. */ + public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; + + /** MethodOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new MethodOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns MethodOptions instance + */ + public static create(properties?: google.protobuf.IMethodOptions): google.protobuf.MethodOptions; + + /** + * Encodes the specified MethodOptions message. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. + * @param message MethodOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MethodOptions message, length delimited. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. + * @param message MethodOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MethodOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MethodOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodOptions; + + /** + * Decodes a MethodOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MethodOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodOptions; + + /** + * Verifies a MethodOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; + + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @param message MethodOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace MethodOptions { + + /** IdempotencyLevel enum. */ + enum IdempotencyLevel { + IDEMPOTENCY_UNKNOWN = 0, + NO_SIDE_EFFECTS = 1, + IDEMPOTENT = 2 + } + } + + /** Properties of an UninterpretedOption. */ + interface IUninterpretedOption { + + /** UninterpretedOption name */ + name?: (google.protobuf.UninterpretedOption.INamePart[]|null); + + /** UninterpretedOption identifierValue */ + identifierValue?: (string|null); + + /** UninterpretedOption positiveIntValue */ + positiveIntValue?: (number|Long|null); + + /** UninterpretedOption negativeIntValue */ + negativeIntValue?: (number|Long|null); + + /** UninterpretedOption doubleValue */ + doubleValue?: (number|null); + + /** UninterpretedOption stringValue */ + stringValue?: (Uint8Array|null); + + /** UninterpretedOption aggregateValue */ + aggregateValue?: (string|null); + } + + /** Represents an UninterpretedOption. */ + class UninterpretedOption implements IUninterpretedOption { + + /** + * Constructs a new UninterpretedOption. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUninterpretedOption); + + /** UninterpretedOption name. */ + public name: google.protobuf.UninterpretedOption.INamePart[]; + + /** UninterpretedOption identifierValue. */ + public identifierValue: string; + + /** UninterpretedOption positiveIntValue. */ + public positiveIntValue: (number|Long); + + /** UninterpretedOption negativeIntValue. */ + public negativeIntValue: (number|Long); + + /** UninterpretedOption doubleValue. */ + public doubleValue: number; + + /** UninterpretedOption stringValue. */ + public stringValue: Uint8Array; + + /** UninterpretedOption aggregateValue. */ + public aggregateValue: string; + + /** + * Creates a new UninterpretedOption instance using the specified properties. + * @param [properties] Properties to set + * @returns UninterpretedOption instance + */ + public static create(properties?: google.protobuf.IUninterpretedOption): google.protobuf.UninterpretedOption; + + /** + * Encodes the specified UninterpretedOption message. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. + * @param message UninterpretedOption message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UninterpretedOption message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. + * @param message UninterpretedOption message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UninterpretedOption message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UninterpretedOption + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption; + + /** + * Decodes an UninterpretedOption message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UninterpretedOption + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption; + + /** + * Verifies an UninterpretedOption message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UninterpretedOption + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @param message UninterpretedOption + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UninterpretedOption to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace UninterpretedOption { + + /** Properties of a NamePart. */ + interface INamePart { + + /** NamePart namePart */ + namePart: string; + + /** NamePart isExtension */ + isExtension: boolean; + } + + /** Represents a NamePart. */ + class NamePart implements INamePart { + + /** + * Constructs a new NamePart. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.UninterpretedOption.INamePart); + + /** NamePart namePart. */ + public namePart: string; + + /** NamePart isExtension. */ + public isExtension: boolean; + + /** + * Creates a new NamePart instance using the specified properties. + * @param [properties] Properties to set + * @returns NamePart instance + */ + public static create(properties?: google.protobuf.UninterpretedOption.INamePart): google.protobuf.UninterpretedOption.NamePart; + + /** + * Encodes the specified NamePart message. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. + * @param message NamePart message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified NamePart message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. + * @param message NamePart message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a NamePart message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns NamePart + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption.NamePart; + + /** + * Decodes a NamePart message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns NamePart + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption.NamePart; + + /** + * Verifies a NamePart message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamePart + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @param message NamePart + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamePart to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Properties of a SourceCodeInfo. */ + interface ISourceCodeInfo { + + /** SourceCodeInfo location */ + location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); + } + + /** Represents a SourceCodeInfo. */ + class SourceCodeInfo implements ISourceCodeInfo { + + /** + * Constructs a new SourceCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ISourceCodeInfo); + + /** SourceCodeInfo location. */ + public location: google.protobuf.SourceCodeInfo.ILocation[]; + + /** + * Creates a new SourceCodeInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns SourceCodeInfo instance + */ + public static create(properties?: google.protobuf.ISourceCodeInfo): google.protobuf.SourceCodeInfo; + + /** + * Encodes the specified SourceCodeInfo message. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. + * @param message SourceCodeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SourceCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. + * @param message SourceCodeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SourceCodeInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SourceCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo; + + /** + * Decodes a SourceCodeInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SourceCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo; + + /** + * Verifies a SourceCodeInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @param message SourceCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace SourceCodeInfo { + + /** Properties of a Location. */ + interface ILocation { + + /** Location path */ + path?: (number[]|null); + + /** Location span */ + span?: (number[]|null); + + /** Location leadingComments */ + leadingComments?: (string|null); + + /** Location trailingComments */ + trailingComments?: (string|null); + + /** Location leadingDetachedComments */ + leadingDetachedComments?: (string[]|null); + } + + /** Represents a Location. */ + class Location implements ILocation { + + /** + * Constructs a new Location. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); + + /** Location path. */ + public path: number[]; + + /** Location span. */ + public span: number[]; + + /** Location leadingComments. */ + public leadingComments: string; + + /** Location trailingComments. */ + public trailingComments: string; + + /** Location leadingDetachedComments. */ + public leadingDetachedComments: string[]; + + /** + * Creates a new Location instance using the specified properties. + * @param [properties] Properties to set + * @returns Location instance + */ + public static create(properties?: google.protobuf.SourceCodeInfo.ILocation): google.protobuf.SourceCodeInfo.Location; + + /** + * Encodes the specified Location message. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. + * @param message Location message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Location message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. + * @param message Location message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Location message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Location + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo.Location; + + /** + * Decodes a Location message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Location + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo.Location; + + /** + * Verifies a Location message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Location + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @param message Location + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Location to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Properties of a GeneratedCodeInfo. */ + interface IGeneratedCodeInfo { + + /** GeneratedCodeInfo annotation */ + annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); + } + + /** Represents a GeneratedCodeInfo. */ + class GeneratedCodeInfo implements IGeneratedCodeInfo { + + /** + * Constructs a new GeneratedCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IGeneratedCodeInfo); + + /** GeneratedCodeInfo annotation. */ + public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; + + /** + * Creates a new GeneratedCodeInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns GeneratedCodeInfo instance + */ + public static create(properties?: google.protobuf.IGeneratedCodeInfo): google.protobuf.GeneratedCodeInfo; + + /** + * Encodes the specified GeneratedCodeInfo message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. + * @param message GeneratedCodeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GeneratedCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. + * @param message GeneratedCodeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GeneratedCodeInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GeneratedCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo; + + /** + * Decodes a GeneratedCodeInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GeneratedCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo; + + /** + * Verifies a GeneratedCodeInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GeneratedCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; + + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @param message GeneratedCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + namespace GeneratedCodeInfo { + + /** Properties of an Annotation. */ + interface IAnnotation { + + /** Annotation path */ + path?: (number[]|null); + + /** Annotation sourceFile */ + sourceFile?: (string|null); + + /** Annotation begin */ + begin?: (number|null); + + /** Annotation end */ + end?: (number|null); + } + + /** Represents an Annotation. */ + class Annotation implements IAnnotation { + + /** + * Constructs a new Annotation. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); + + /** Annotation path. */ + public path: number[]; + + /** Annotation sourceFile. */ + public sourceFile: string; + + /** Annotation begin. */ + public begin: number; + + /** Annotation end. */ + public end: number; + + /** + * Creates a new Annotation instance using the specified properties. + * @param [properties] Properties to set + * @returns Annotation instance + */ + public static create(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Encodes the specified Annotation message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. + * @param message Annotation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Annotation message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. + * @param message Annotation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Annotation message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Annotation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Decodes an Annotation message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Annotation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Verifies an Annotation message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Annotation + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @param message Annotation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Annotation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Properties of an Any. */ + interface IAny { + + /** Any type_url */ + type_url?: (string|null); + + /** Any value */ + value?: (Uint8Array|null); + } + + /** Represents an Any. */ + class Any implements IAny { + + /** + * Constructs a new Any. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IAny); + + /** Any type_url. */ + public type_url: string; + + /** Any value. */ + public value: Uint8Array; + + /** + * Creates a new Any instance using the specified properties. + * @param [properties] Properties to set + * @returns Any instance + */ + public static create(properties?: google.protobuf.IAny): google.protobuf.Any; + + /** + * Encodes the specified Any message. Does not implicitly {@link google.protobuf.Any.verify|verify} messages. + * @param message Any message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Any message, length delimited. Does not implicitly {@link google.protobuf.Any.verify|verify} messages. + * @param message Any message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Any message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Any + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Any; + + /** + * Decodes an Any message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Any + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Any; + + /** + * Verifies an Any message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an Any message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Any + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Any; + + /** + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @param message Any + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Any to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of a Duration. */ + interface IDuration { + + /** Duration seconds */ + seconds?: (number|Long|null); + + /** Duration nanos */ + nanos?: (number|null); + } + + /** Represents a Duration. */ + class Duration implements IDuration { + + /** + * Constructs a new Duration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDuration); + + /** Duration seconds. */ + public seconds: (number|Long); + + /** Duration nanos. */ + public nanos: number; + + /** + * Creates a new Duration instance using the specified properties. + * @param [properties] Properties to set + * @returns Duration instance + */ + public static create(properties?: google.protobuf.IDuration): google.protobuf.Duration; + + /** + * Encodes the specified Duration message. Does not implicitly {@link google.protobuf.Duration.verify|verify} messages. + * @param message Duration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IDuration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Duration message, length delimited. Does not implicitly {@link google.protobuf.Duration.verify|verify} messages. + * @param message Duration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IDuration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Duration message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Duration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Duration; + + /** + * Decodes a Duration message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Duration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Duration; + + /** + * Verifies a Duration message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Duration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; + + /** + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @param message Duration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Duration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + + /** Properties of an Empty. */ + interface IEmpty { + } + + /** Represents an Empty. */ + class Empty implements IEmpty { + + /** + * Constructs a new Empty. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEmpty); + + /** + * Creates a new Empty instance using the specified properties. + * @param [properties] Properties to set + * @returns Empty instance + */ + public static create(properties?: google.protobuf.IEmpty): google.protobuf.Empty; + + /** + * Encodes the specified Empty message. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages. + * @param message Empty message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEmpty, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Empty message, length delimited. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages. + * @param message Empty message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEmpty, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Empty message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Empty + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Empty; + + /** + * Decodes an Empty message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Empty + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Empty; + + /** + * Verifies an Empty message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Empty + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @param message Empty + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Empty to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } + + /** Namespace rpc. */ + namespace rpc { + + /** Properties of a Status. */ + interface IStatus { + + /** Status code */ + code?: (number|null); + + /** Status message */ + message?: (string|null); + + /** Status details */ + details?: (google.protobuf.IAny[]|null); + } + + /** Represents a Status. */ + class Status implements IStatus { + + /** + * Constructs a new Status. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IStatus); + + /** Status code. */ + public code: number; + + /** Status message. */ + public message: string; + + /** Status details. */ + public details: google.protobuf.IAny[]; + + /** + * Creates a new Status instance using the specified properties. + * @param [properties] Properties to set + * @returns Status instance + */ + public static create(properties?: google.rpc.IStatus): google.rpc.Status; + + /** + * Encodes the specified Status message. Does not implicitly {@link google.rpc.Status.verify|verify} messages. + * @param message Status message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.rpc.IStatus, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Status message, length delimited. Does not implicitly {@link google.rpc.Status.verify|verify} messages. + * @param message Status message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.rpc.IStatus, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Status message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Status + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.Status; + + /** + * Decodes a Status message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Status + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.Status; + + /** + * Verifies a Status message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Status message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Status + */ + public static fromObject(object: { [k: string]: any }): google.rpc.Status; + + /** + * Creates a plain object from a Status message. Also converts values to other types if specified. + * @param message Status + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Status to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } + } +} diff --git a/node_modules/google-gax/build/protos/operations.js b/node_modules/google-gax/build/protos/operations.js new file mode 100644 index 0000000..808ce91 --- /dev/null +++ b/node_modules/google-gax/build/protos/operations.js @@ -0,0 +1 @@ +(e=>{"function"==typeof define&&define.amd?define(["protobufjs/minimal"],e):"function"==typeof require&&"object"==typeof module&&module&&module.exports&&(module.exports=e(require("protobufjs/minimal")))})(function(o){var e,t,n,F,a=o.Reader,r=o.Writer,i=o.util,p=o.roots.operations_protos||(o.roots.operations_protos={});function G(e,t,n){o.rpc.Service.call(this,e,t,n)}function l(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:o.name=e.string();break;case 2:o.metadata=p.google.protobuf.Any.decode(e,e.uint32());break;case 3:o.done=e.bool();break;case 4:o.error=p.google.rpc.Status.decode(e,e.uint32());break;case 5:o.response=p.google.protobuf.Any.decode(e,e.uint32());break;default:e.skipType(7&r)}}return o},l.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},l.verify=function(e){if("object"!=typeof e||null===e)return"object expected";var t,n={};if(null!=e.name&&e.hasOwnProperty("name")&&!i.isString(e.name))return"name: string expected";if(null!=e.metadata&&e.hasOwnProperty("metadata")&&(t=p.google.protobuf.Any.verify(e.metadata)))return"metadata."+t;if(null!=e.done&&e.hasOwnProperty("done")&&"boolean"!=typeof e.done)return"done: boolean expected";if(null!=e.error&&e.hasOwnProperty("error")&&(n.result=1,t=p.google.rpc.Status.verify(e.error)))return"error."+t;if(null!=e.response&&e.hasOwnProperty("response")){if(1===n.result)return"result: multiple values";if(n.result=1,t=p.google.protobuf.Any.verify(e.response))return"response."+t}return null},l.fromObject=function(e){if(e instanceof p.google.longrunning.Operation)return e;var t=new p.google.longrunning.Operation;if(null!=e.name&&(t.name=String(e.name)),null!=e.metadata){if("object"!=typeof e.metadata)throw TypeError(".google.longrunning.Operation.metadata: object expected");t.metadata=p.google.protobuf.Any.fromObject(e.metadata)}if(null!=e.done&&(t.done=Boolean(e.done)),null!=e.error){if("object"!=typeof e.error)throw TypeError(".google.longrunning.Operation.error: object expected");t.error=p.google.rpc.Status.fromObject(e.error)}if(null!=e.response){if("object"!=typeof e.response)throw TypeError(".google.longrunning.Operation.response: object expected");t.response=p.google.protobuf.Any.fromObject(e.response)}return t},l.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name="",n.metadata=null,n.done=!1),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.metadata&&e.hasOwnProperty("metadata")&&(n.metadata=p.google.protobuf.Any.toObject(e.metadata,t)),null!=e.done&&e.hasOwnProperty("done")&&(n.done=e.done),null!=e.error&&e.hasOwnProperty("error")&&(n.error=p.google.rpc.Status.toObject(e.error,t),t.oneofs)&&(n.result="error"),null!=e.response&&e.hasOwnProperty("response")&&(n.response=p.google.protobuf.Any.toObject(e.response,t),t.oneofs)&&(n.result="response"),n},l.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},l),t.GetOperationRequest=(B.prototype.name="",B.create=function(e){return new B(e)},B.encode=function(e,t){return t=t||r.create(),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(10).string(e.name),t},B.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},B.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new p.google.longrunning.GetOperationRequest;e.pos>>3==1?o.name=e.string():e.skipType(7&r)}return o},B.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},B.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.name&&e.hasOwnProperty("name")&&!i.isString(e.name)?"name: string expected":null},B.fromObject=function(e){var t;return e instanceof p.google.longrunning.GetOperationRequest?e:(t=new p.google.longrunning.GetOperationRequest,null!=e.name&&(t.name=String(e.name)),t)},B.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name=""),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),n},B.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},B),t.ListOperationsRequest=(s.prototype.name="",s.prototype.filter="",s.prototype.pageSize=0,s.prototype.pageToken="",s.create=function(e){return new s(e)},s.encode=function(e,t){return t=t||r.create(),null!=e.filter&&Object.hasOwnProperty.call(e,"filter")&&t.uint32(10).string(e.filter),null!=e.pageSize&&Object.hasOwnProperty.call(e,"pageSize")&&t.uint32(16).int32(e.pageSize),null!=e.pageToken&&Object.hasOwnProperty.call(e,"pageToken")&&t.uint32(26).string(e.pageToken),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(34).string(e.name),t},s.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},s.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new p.google.longrunning.ListOperationsRequest;e.pos>>3){case 4:o.name=e.string();break;case 1:o.filter=e.string();break;case 2:o.pageSize=e.int32();break;case 3:o.pageToken=e.string();break;default:e.skipType(7&r)}}return o},s.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},s.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.name&&e.hasOwnProperty("name")&&!i.isString(e.name)?"name: string expected":null!=e.filter&&e.hasOwnProperty("filter")&&!i.isString(e.filter)?"filter: string expected":null!=e.pageSize&&e.hasOwnProperty("pageSize")&&!i.isInteger(e.pageSize)?"pageSize: integer expected":null!=e.pageToken&&e.hasOwnProperty("pageToken")&&!i.isString(e.pageToken)?"pageToken: string expected":null},s.fromObject=function(e){var t;return e instanceof p.google.longrunning.ListOperationsRequest?e:(t=new p.google.longrunning.ListOperationsRequest,null!=e.name&&(t.name=String(e.name)),null!=e.filter&&(t.filter=String(e.filter)),null!=e.pageSize&&(t.pageSize=0|e.pageSize),null!=e.pageToken&&(t.pageToken=String(e.pageToken)),t)},s.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.filter="",n.pageSize=0,n.pageToken="",n.name=""),null!=e.filter&&e.hasOwnProperty("filter")&&(n.filter=e.filter),null!=e.pageSize&&e.hasOwnProperty("pageSize")&&(n.pageSize=e.pageSize),null!=e.pageToken&&e.hasOwnProperty("pageToken")&&(n.pageToken=e.pageToken),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),n},s.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},s),t.ListOperationsResponse=(u.prototype.operations=i.emptyArray,u.prototype.nextPageToken="",u.create=function(e){return new u(e)},u.encode=function(e,t){if(t=t||r.create(),null!=e.operations&&e.operations.length)for(var n=0;n>>3){case 1:o.operations&&o.operations.length||(o.operations=[]),o.operations.push(p.google.longrunning.Operation.decode(e,e.uint32()));break;case 2:o.nextPageToken=e.string();break;default:e.skipType(7&r)}}return o},u.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},u.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.operations&&e.hasOwnProperty("operations")){if(!Array.isArray(e.operations))return"operations: array expected";for(var t=0;t>>3==1?o.name=e.string():e.skipType(7&r)}return o},L.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},L.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.name&&e.hasOwnProperty("name")&&!i.isString(e.name)?"name: string expected":null},L.fromObject=function(e){var t;return e instanceof p.google.longrunning.CancelOperationRequest?e:(t=new p.google.longrunning.CancelOperationRequest,null!=e.name&&(t.name=String(e.name)),t)},L.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name=""),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),n},L.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},L),t.DeleteOperationRequest=(U.prototype.name="",U.create=function(e){return new U(e)},U.encode=function(e,t){return t=t||r.create(),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(10).string(e.name),t},U.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},U.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new p.google.longrunning.DeleteOperationRequest;e.pos>>3==1?o.name=e.string():e.skipType(7&r)}return o},U.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},U.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.name&&e.hasOwnProperty("name")&&!i.isString(e.name)?"name: string expected":null},U.fromObject=function(e){var t;return e instanceof p.google.longrunning.DeleteOperationRequest?e:(t=new p.google.longrunning.DeleteOperationRequest,null!=e.name&&(t.name=String(e.name)),t)},U.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name=""),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),n},U.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},U),t.WaitOperationRequest=(c.prototype.name="",c.prototype.timeout=null,c.create=function(e){return new c(e)},c.encode=function(e,t){return t=t||r.create(),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(10).string(e.name),null!=e.timeout&&Object.hasOwnProperty.call(e,"timeout")&&p.google.protobuf.Duration.encode(e.timeout,t.uint32(18).fork()).ldelim(),t},c.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},c.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new p.google.longrunning.WaitOperationRequest;e.pos>>3){case 1:o.name=e.string();break;case 2:o.timeout=p.google.protobuf.Duration.decode(e,e.uint32());break;default:e.skipType(7&r)}}return o},c.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},c.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!i.isString(e.name))return"name: string expected";if(null!=e.timeout&&e.hasOwnProperty("timeout")){e=p.google.protobuf.Duration.verify(e.timeout);if(e)return"timeout."+e}return null},c.fromObject=function(e){if(e instanceof p.google.longrunning.WaitOperationRequest)return e;var t=new p.google.longrunning.WaitOperationRequest;if(null!=e.name&&(t.name=String(e.name)),null!=e.timeout){if("object"!=typeof e.timeout)throw TypeError(".google.longrunning.WaitOperationRequest.timeout: object expected");t.timeout=p.google.protobuf.Duration.fromObject(e.timeout)}return t},c.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name="",n.timeout=null),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.timeout&&e.hasOwnProperty("timeout")&&(n.timeout=p.google.protobuf.Duration.toObject(e.timeout,t)),n},c.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},c),t.OperationInfo=(d.prototype.responseType="",d.prototype.metadataType="",d.create=function(e){return new d(e)},d.encode=function(e,t){return t=t||r.create(),null!=e.responseType&&Object.hasOwnProperty.call(e,"responseType")&&t.uint32(10).string(e.responseType),null!=e.metadataType&&Object.hasOwnProperty.call(e,"metadataType")&&t.uint32(18).string(e.metadataType),t},d.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},d.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new p.google.longrunning.OperationInfo;e.pos>>3){case 1:o.responseType=e.string();break;case 2:o.metadataType=e.string();break;default:e.skipType(7&r)}}return o},d.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},d.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.responseType&&e.hasOwnProperty("responseType")&&!i.isString(e.responseType)?"responseType: string expected":null!=e.metadataType&&e.hasOwnProperty("metadataType")&&!i.isString(e.metadataType)?"metadataType: string expected":null},d.fromObject=function(e){var t;return e instanceof p.google.longrunning.OperationInfo?e:(t=new p.google.longrunning.OperationInfo,null!=e.responseType&&(t.responseType=String(e.responseType)),null!=e.metadataType&&(t.metadataType=String(e.metadataType)),t)},d.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.responseType="",n.metadataType=""),null!=e.responseType&&e.hasOwnProperty("responseType")&&(n.responseType=e.responseType),null!=e.metadataType&&e.hasOwnProperty("metadataType")&&(n.metadataType=e.metadataType),n},d.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},d),t),F.api=((n={}).Http=(g.prototype.rules=i.emptyArray,g.prototype.fullyDecodeReservedExpansion=!1,g.create=function(e){return new g(e)},g.encode=function(e,t){if(t=t||r.create(),null!=e.rules&&e.rules.length)for(var n=0;n>>3){case 1:o.rules&&o.rules.length||(o.rules=[]),o.rules.push(p.google.api.HttpRule.decode(e,e.uint32()));break;case 2:o.fullyDecodeReservedExpansion=e.bool();break;default:e.skipType(7&r)}}return o},g.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},g.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.rules&&e.hasOwnProperty("rules")){if(!Array.isArray(e.rules))return"rules: array expected";for(var t=0;t>>3){case 1:o.selector=e.string();break;case 2:o.get=e.string();break;case 3:o.put=e.string();break;case 4:o.post=e.string();break;case 5:o.delete=e.string();break;case 6:o.patch=e.string();break;case 8:o.custom=p.google.api.CustomHttpPattern.decode(e,e.uint32());break;case 7:o.body=e.string();break;case 12:o.responseBody=e.string();break;case 11:o.additionalBindings&&o.additionalBindings.length||(o.additionalBindings=[]),o.additionalBindings.push(p.google.api.HttpRule.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return o},f.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},f.verify=function(e){if("object"!=typeof e||null===e)return"object expected";var t={};if(null!=e.selector&&e.hasOwnProperty("selector")&&!i.isString(e.selector))return"selector: string expected";if(null!=e.get&&e.hasOwnProperty("get")&&(t.pattern=1,!i.isString(e.get)))return"get: string expected";if(null!=e.put&&e.hasOwnProperty("put")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,!i.isString(e.put))return"put: string expected"}if(null!=e.post&&e.hasOwnProperty("post")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,!i.isString(e.post))return"post: string expected"}if(null!=e.delete&&e.hasOwnProperty("delete")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,!i.isString(e.delete))return"delete: string expected"}if(null!=e.patch&&e.hasOwnProperty("patch")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,!i.isString(e.patch))return"patch: string expected"}if(null!=e.custom&&e.hasOwnProperty("custom")){if(1===t.pattern)return"pattern: multiple values";if(t.pattern=1,n=p.google.api.CustomHttpPattern.verify(e.custom))return"custom."+n}if(null!=e.body&&e.hasOwnProperty("body")&&!i.isString(e.body))return"body: string expected";if(null!=e.responseBody&&e.hasOwnProperty("responseBody")&&!i.isString(e.responseBody))return"responseBody: string expected";if(null!=e.additionalBindings&&e.hasOwnProperty("additionalBindings")){if(!Array.isArray(e.additionalBindings))return"additionalBindings: array expected";for(var n,o=0;o>>3){case 1:o.kind=e.string();break;case 2:o.path=e.string();break;default:e.skipType(7&r)}}return o},y.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},y.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.kind&&e.hasOwnProperty("kind")&&!i.isString(e.kind)?"kind: string expected":null!=e.path&&e.hasOwnProperty("path")&&!i.isString(e.path)?"path: string expected":null},y.fromObject=function(e){var t;return e instanceof p.google.api.CustomHttpPattern?e:(t=new p.google.api.CustomHttpPattern,null!=e.kind&&(t.kind=String(e.kind)),null!=e.path&&(t.path=String(e.path)),t)},y.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.kind="",n.path=""),null!=e.kind&&e.hasOwnProperty("kind")&&(n.kind=e.kind),null!=e.path&&e.hasOwnProperty("path")&&(n.path=e.path),n},y.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},y),n),F.protobuf=((t={}).FileDescriptorSet=(J.prototype.file=i.emptyArray,J.create=function(e){return new J(e)},J.encode=function(e,t){if(t=t||r.create(),null!=e.file&&e.file.length)for(var n=0;n>>3==1?(o.file&&o.file.length||(o.file=[]),o.file.push(p.google.protobuf.FileDescriptorProto.decode(e,e.uint32()))):e.skipType(7&r)}return o},J.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},J.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.file&&e.hasOwnProperty("file")){if(!Array.isArray(e.file))return"file: array expected";for(var t=0;t>>3){case 1:o.name=e.string();break;case 2:o.package=e.string();break;case 3:o.dependency&&o.dependency.length||(o.dependency=[]),o.dependency.push(e.string());break;case 10:if(o.publicDependency&&o.publicDependency.length||(o.publicDependency=[]),2==(7&r))for(var i=e.uint32()+e.pos;e.pos>>3){case 1:o.name=e.string();break;case 2:o.field&&o.field.length||(o.field=[]),o.field.push(p.google.protobuf.FieldDescriptorProto.decode(e,e.uint32()));break;case 6:o.extension&&o.extension.length||(o.extension=[]),o.extension.push(p.google.protobuf.FieldDescriptorProto.decode(e,e.uint32()));break;case 3:o.nestedType&&o.nestedType.length||(o.nestedType=[]),o.nestedType.push(p.google.protobuf.DescriptorProto.decode(e,e.uint32()));break;case 4:o.enumType&&o.enumType.length||(o.enumType=[]),o.enumType.push(p.google.protobuf.EnumDescriptorProto.decode(e,e.uint32()));break;case 5:o.extensionRange&&o.extensionRange.length||(o.extensionRange=[]),o.extensionRange.push(p.google.protobuf.DescriptorProto.ExtensionRange.decode(e,e.uint32()));break;case 8:o.oneofDecl&&o.oneofDecl.length||(o.oneofDecl=[]),o.oneofDecl.push(p.google.protobuf.OneofDescriptorProto.decode(e,e.uint32()));break;case 7:o.options=p.google.protobuf.MessageOptions.decode(e,e.uint32());break;case 9:o.reservedRange&&o.reservedRange.length||(o.reservedRange=[]),o.reservedRange.push(p.google.protobuf.DescriptorProto.ReservedRange.decode(e,e.uint32()));break;case 10:o.reservedName&&o.reservedName.length||(o.reservedName=[]),o.reservedName.push(e.string());break;default:e.skipType(7&r)}}return o},O.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},O.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!i.isString(e.name))return"name: string expected";if(null!=e.field&&e.hasOwnProperty("field")){if(!Array.isArray(e.field))return"field: array expected";for(var t=0;t>>3){case 1:o.start=e.int32();break;case 2:o.end=e.int32();break;case 3:o.options=p.google.protobuf.ExtensionRangeOptions.decode(e,e.uint32());break;default:e.skipType(7&r)}}return o},b.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},b.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.start&&e.hasOwnProperty("start")&&!i.isInteger(e.start))return"start: integer expected";if(null!=e.end&&e.hasOwnProperty("end")&&!i.isInteger(e.end))return"end: integer expected";if(null!=e.options&&e.hasOwnProperty("options")){e=p.google.protobuf.ExtensionRangeOptions.verify(e.options);if(e)return"options."+e}return null},b.fromObject=function(e){if(e instanceof p.google.protobuf.DescriptorProto.ExtensionRange)return e;var t=new p.google.protobuf.DescriptorProto.ExtensionRange;if(null!=e.start&&(t.start=0|e.start),null!=e.end&&(t.end=0|e.end),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.protobuf.DescriptorProto.ExtensionRange.options: object expected");t.options=p.google.protobuf.ExtensionRangeOptions.fromObject(e.options)}return t},b.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.start=0,n.end=0,n.options=null),null!=e.start&&e.hasOwnProperty("start")&&(n.start=e.start),null!=e.end&&e.hasOwnProperty("end")&&(n.end=e.end),null!=e.options&&e.hasOwnProperty("options")&&(n.options=p.google.protobuf.ExtensionRangeOptions.toObject(e.options,t)),n},b.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},b),O.ReservedRange=(m.prototype.start=0,m.prototype.end=0,m.create=function(e){return new m(e)},m.encode=function(e,t){return t=t||r.create(),null!=e.start&&Object.hasOwnProperty.call(e,"start")&&t.uint32(8).int32(e.start),null!=e.end&&Object.hasOwnProperty.call(e,"end")&&t.uint32(16).int32(e.end),t},m.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},m.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new p.google.protobuf.DescriptorProto.ReservedRange;e.pos>>3){case 1:o.start=e.int32();break;case 2:o.end=e.int32();break;default:e.skipType(7&r)}}return o},m.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},m.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.start&&e.hasOwnProperty("start")&&!i.isInteger(e.start)?"start: integer expected":null!=e.end&&e.hasOwnProperty("end")&&!i.isInteger(e.end)?"end: integer expected":null},m.fromObject=function(e){var t;return e instanceof p.google.protobuf.DescriptorProto.ReservedRange?e:(t=new p.google.protobuf.DescriptorProto.ReservedRange,null!=e.start&&(t.start=0|e.start),null!=e.end&&(t.end=0|e.end),t)},m.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.start=0,n.end=0),null!=e.start&&e.hasOwnProperty("start")&&(n.start=e.start),null!=e.end&&e.hasOwnProperty("end")&&(n.end=e.end),n},m.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},m),O),t.ExtensionRangeOptions=(M.prototype.uninterpretedOption=i.emptyArray,M.create=function(e){return new M(e)},M.encode=function(e,t){if(t=t||r.create(),null!=e.uninterpretedOption&&e.uninterpretedOption.length)for(var n=0;n>>3==999?(o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(p.google.protobuf.UninterpretedOption.decode(e,e.uint32()))):e.skipType(7&r)}return o},M.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},M.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 1:o.name=e.string();break;case 3:o.number=e.int32();break;case 4:o.label=e.int32();break;case 5:o.type=e.int32();break;case 6:o.typeName=e.string();break;case 2:o.extendee=e.string();break;case 7:o.defaultValue=e.string();break;case 9:o.oneofIndex=e.int32();break;case 10:o.jsonName=e.string();break;case 8:o.options=p.google.protobuf.FieldOptions.decode(e,e.uint32());break;case 17:o.proto3Optional=e.bool();break;default:e.skipType(7&r)}}return o},v.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},v.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!i.isString(e.name))return"name: string expected";if(null!=e.number&&e.hasOwnProperty("number")&&!i.isInteger(e.number))return"number: integer expected";if(null!=e.label&&e.hasOwnProperty("label"))switch(e.label){default:return"label: enum value expected";case 1:case 2:case 3:}if(null!=e.type&&e.hasOwnProperty("type"))switch(e.type){default:return"type: enum value expected";case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:case 11:case 12:case 13:case 14:case 15:case 16:case 17:case 18:}if(null!=e.typeName&&e.hasOwnProperty("typeName")&&!i.isString(e.typeName))return"typeName: string expected";if(null!=e.extendee&&e.hasOwnProperty("extendee")&&!i.isString(e.extendee))return"extendee: string expected";if(null!=e.defaultValue&&e.hasOwnProperty("defaultValue")&&!i.isString(e.defaultValue))return"defaultValue: string expected";if(null!=e.oneofIndex&&e.hasOwnProperty("oneofIndex")&&!i.isInteger(e.oneofIndex))return"oneofIndex: integer expected";if(null!=e.jsonName&&e.hasOwnProperty("jsonName")&&!i.isString(e.jsonName))return"jsonName: string expected";if(null!=e.options&&e.hasOwnProperty("options")){var t=p.google.protobuf.FieldOptions.verify(e.options);if(t)return"options."+t}return null!=e.proto3Optional&&e.hasOwnProperty("proto3Optional")&&"boolean"!=typeof e.proto3Optional?"proto3Optional: boolean expected":null},v.fromObject=function(e){if(e instanceof p.google.protobuf.FieldDescriptorProto)return e;var t=new p.google.protobuf.FieldDescriptorProto;switch(null!=e.name&&(t.name=String(e.name)),null!=e.number&&(t.number=0|e.number),e.label){case"LABEL_OPTIONAL":case 1:t.label=1;break;case"LABEL_REQUIRED":case 2:t.label=2;break;case"LABEL_REPEATED":case 3:t.label=3}switch(e.type){case"TYPE_DOUBLE":case 1:t.type=1;break;case"TYPE_FLOAT":case 2:t.type=2;break;case"TYPE_INT64":case 3:t.type=3;break;case"TYPE_UINT64":case 4:t.type=4;break;case"TYPE_INT32":case 5:t.type=5;break;case"TYPE_FIXED64":case 6:t.type=6;break;case"TYPE_FIXED32":case 7:t.type=7;break;case"TYPE_BOOL":case 8:t.type=8;break;case"TYPE_STRING":case 9:t.type=9;break;case"TYPE_GROUP":case 10:t.type=10;break;case"TYPE_MESSAGE":case 11:t.type=11;break;case"TYPE_BYTES":case 12:t.type=12;break;case"TYPE_UINT32":case 13:t.type=13;break;case"TYPE_ENUM":case 14:t.type=14;break;case"TYPE_SFIXED32":case 15:t.type=15;break;case"TYPE_SFIXED64":case 16:t.type=16;break;case"TYPE_SINT32":case 17:t.type=17;break;case"TYPE_SINT64":case 18:t.type=18}if(null!=e.typeName&&(t.typeName=String(e.typeName)),null!=e.extendee&&(t.extendee=String(e.extendee)),null!=e.defaultValue&&(t.defaultValue=String(e.defaultValue)),null!=e.oneofIndex&&(t.oneofIndex=0|e.oneofIndex),null!=e.jsonName&&(t.jsonName=String(e.jsonName)),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.protobuf.FieldDescriptorProto.options: object expected");t.options=p.google.protobuf.FieldOptions.fromObject(e.options)}return null!=e.proto3Optional&&(t.proto3Optional=Boolean(e.proto3Optional)),t},v.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name="",n.extendee="",n.number=0,n.label=t.enums===String?"LABEL_OPTIONAL":1,n.type=t.enums===String?"TYPE_DOUBLE":1,n.typeName="",n.defaultValue="",n.options=null,n.oneofIndex=0,n.jsonName="",n.proto3Optional=!1),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.extendee&&e.hasOwnProperty("extendee")&&(n.extendee=e.extendee),null!=e.number&&e.hasOwnProperty("number")&&(n.number=e.number),null!=e.label&&e.hasOwnProperty("label")&&(n.label=t.enums===String?p.google.protobuf.FieldDescriptorProto.Label[e.label]:e.label),null!=e.type&&e.hasOwnProperty("type")&&(n.type=t.enums===String?p.google.protobuf.FieldDescriptorProto.Type[e.type]:e.type),null!=e.typeName&&e.hasOwnProperty("typeName")&&(n.typeName=e.typeName),null!=e.defaultValue&&e.hasOwnProperty("defaultValue")&&(n.defaultValue=e.defaultValue),null!=e.options&&e.hasOwnProperty("options")&&(n.options=p.google.protobuf.FieldOptions.toObject(e.options,t)),null!=e.oneofIndex&&e.hasOwnProperty("oneofIndex")&&(n.oneofIndex=e.oneofIndex),null!=e.jsonName&&e.hasOwnProperty("jsonName")&&(n.jsonName=e.jsonName),null!=e.proto3Optional&&e.hasOwnProperty("proto3Optional")&&(n.proto3Optional=e.proto3Optional),n},v.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},v.Type=(n={},(e=Object.create(n))[n[1]="TYPE_DOUBLE"]=1,e[n[2]="TYPE_FLOAT"]=2,e[n[3]="TYPE_INT64"]=3,e[n[4]="TYPE_UINT64"]=4,e[n[5]="TYPE_INT32"]=5,e[n[6]="TYPE_FIXED64"]=6,e[n[7]="TYPE_FIXED32"]=7,e[n[8]="TYPE_BOOL"]=8,e[n[9]="TYPE_STRING"]=9,e[n[10]="TYPE_GROUP"]=10,e[n[11]="TYPE_MESSAGE"]=11,e[n[12]="TYPE_BYTES"]=12,e[n[13]="TYPE_UINT32"]=13,e[n[14]="TYPE_ENUM"]=14,e[n[15]="TYPE_SFIXED32"]=15,e[n[16]="TYPE_SFIXED64"]=16,e[n[17]="TYPE_SINT32"]=17,e[n[18]="TYPE_SINT64"]=18,e),v.Label=(n={},(e=Object.create(n))[n[1]="LABEL_OPTIONAL"]=1,e[n[2]="LABEL_REQUIRED"]=2,e[n[3]="LABEL_REPEATED"]=3,e),v),t.OneofDescriptorProto=(w.prototype.name="",w.prototype.options=null,w.create=function(e){return new w(e)},w.encode=function(e,t){return t=t||r.create(),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(10).string(e.name),null!=e.options&&Object.hasOwnProperty.call(e,"options")&&p.google.protobuf.OneofOptions.encode(e.options,t.uint32(18).fork()).ldelim(),t},w.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},w.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new p.google.protobuf.OneofDescriptorProto;e.pos>>3){case 1:o.name=e.string();break;case 2:o.options=p.google.protobuf.OneofOptions.decode(e,e.uint32());break;default:e.skipType(7&r)}}return o},w.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},w.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!i.isString(e.name))return"name: string expected";if(null!=e.options&&e.hasOwnProperty("options")){e=p.google.protobuf.OneofOptions.verify(e.options);if(e)return"options."+e}return null},w.fromObject=function(e){if(e instanceof p.google.protobuf.OneofDescriptorProto)return e;var t=new p.google.protobuf.OneofDescriptorProto;if(null!=e.name&&(t.name=String(e.name)),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.protobuf.OneofDescriptorProto.options: object expected");t.options=p.google.protobuf.OneofOptions.fromObject(e.options)}return t},w.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name="",n.options=null),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.options&&e.hasOwnProperty("options")&&(n.options=p.google.protobuf.OneofOptions.toObject(e.options,t)),n},w.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},w),t.EnumDescriptorProto=(P.prototype.name="",P.prototype.value=i.emptyArray,P.prototype.options=null,P.prototype.reservedRange=i.emptyArray,P.prototype.reservedName=i.emptyArray,P.create=function(e){return new P(e)},P.encode=function(e,t){if(t=t||r.create(),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(10).string(e.name),null!=e.value&&e.value.length)for(var n=0;n>>3){case 1:o.name=e.string();break;case 2:o.value&&o.value.length||(o.value=[]),o.value.push(p.google.protobuf.EnumValueDescriptorProto.decode(e,e.uint32()));break;case 3:o.options=p.google.protobuf.EnumOptions.decode(e,e.uint32());break;case 4:o.reservedRange&&o.reservedRange.length||(o.reservedRange=[]),o.reservedRange.push(p.google.protobuf.EnumDescriptorProto.EnumReservedRange.decode(e,e.uint32()));break;case 5:o.reservedName&&o.reservedName.length||(o.reservedName=[]),o.reservedName.push(e.string());break;default:e.skipType(7&r)}}return o},P.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},P.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!i.isString(e.name))return"name: string expected";if(null!=e.value&&e.hasOwnProperty("value")){if(!Array.isArray(e.value))return"value: array expected";for(var t=0;t>>3){case 1:o.start=e.int32();break;case 2:o.end=e.int32();break;default:e.skipType(7&r)}}return o},_.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},_.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.start&&e.hasOwnProperty("start")&&!i.isInteger(e.start)?"start: integer expected":null!=e.end&&e.hasOwnProperty("end")&&!i.isInteger(e.end)?"end: integer expected":null},_.fromObject=function(e){var t;return e instanceof p.google.protobuf.EnumDescriptorProto.EnumReservedRange?e:(t=new p.google.protobuf.EnumDescriptorProto.EnumReservedRange,null!=e.start&&(t.start=0|e.start),null!=e.end&&(t.end=0|e.end),t)},_.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.start=0,n.end=0),null!=e.start&&e.hasOwnProperty("start")&&(n.start=e.start),null!=e.end&&e.hasOwnProperty("end")&&(n.end=e.end),n},_.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},_),P),t.EnumValueDescriptorProto=(j.prototype.name="",j.prototype.number=0,j.prototype.options=null,j.create=function(e){return new j(e)},j.encode=function(e,t){return t=t||r.create(),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(10).string(e.name),null!=e.number&&Object.hasOwnProperty.call(e,"number")&&t.uint32(16).int32(e.number),null!=e.options&&Object.hasOwnProperty.call(e,"options")&&p.google.protobuf.EnumValueOptions.encode(e.options,t.uint32(26).fork()).ldelim(),t},j.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},j.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new p.google.protobuf.EnumValueDescriptorProto;e.pos>>3){case 1:o.name=e.string();break;case 2:o.number=e.int32();break;case 3:o.options=p.google.protobuf.EnumValueOptions.decode(e,e.uint32());break;default:e.skipType(7&r)}}return o},j.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},j.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!i.isString(e.name))return"name: string expected";if(null!=e.number&&e.hasOwnProperty("number")&&!i.isInteger(e.number))return"number: integer expected";if(null!=e.options&&e.hasOwnProperty("options")){e=p.google.protobuf.EnumValueOptions.verify(e.options);if(e)return"options."+e}return null},j.fromObject=function(e){if(e instanceof p.google.protobuf.EnumValueDescriptorProto)return e;var t=new p.google.protobuf.EnumValueDescriptorProto;if(null!=e.name&&(t.name=String(e.name)),null!=e.number&&(t.number=0|e.number),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.protobuf.EnumValueDescriptorProto.options: object expected");t.options=p.google.protobuf.EnumValueOptions.fromObject(e.options)}return t},j.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name="",n.number=0,n.options=null),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.number&&e.hasOwnProperty("number")&&(n.number=e.number),null!=e.options&&e.hasOwnProperty("options")&&(n.options=p.google.protobuf.EnumValueOptions.toObject(e.options,t)),n},j.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},j),t.ServiceDescriptorProto=(S.prototype.name="",S.prototype.method=i.emptyArray,S.prototype.options=null,S.create=function(e){return new S(e)},S.encode=function(e,t){if(t=t||r.create(),null!=e.name&&Object.hasOwnProperty.call(e,"name")&&t.uint32(10).string(e.name),null!=e.method&&e.method.length)for(var n=0;n>>3){case 1:o.name=e.string();break;case 2:o.method&&o.method.length||(o.method=[]),o.method.push(p.google.protobuf.MethodDescriptorProto.decode(e,e.uint32()));break;case 3:o.options=p.google.protobuf.ServiceOptions.decode(e,e.uint32());break;default:e.skipType(7&r)}}return o},S.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},S.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!i.isString(e.name))return"name: string expected";if(null!=e.method&&e.hasOwnProperty("method")){if(!Array.isArray(e.method))return"method: array expected";for(var t=0;t>>3){case 1:o.name=e.string();break;case 2:o.inputType=e.string();break;case 3:o.outputType=e.string();break;case 4:o.options=p.google.protobuf.MethodOptions.decode(e,e.uint32());break;case 5:o.clientStreaming=e.bool();break;case 6:o.serverStreaming=e.bool();break;default:e.skipType(7&r)}}return o},x.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},x.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!i.isString(e.name))return"name: string expected";if(null!=e.inputType&&e.hasOwnProperty("inputType")&&!i.isString(e.inputType))return"inputType: string expected";if(null!=e.outputType&&e.hasOwnProperty("outputType")&&!i.isString(e.outputType))return"outputType: string expected";if(null!=e.options&&e.hasOwnProperty("options")){var t=p.google.protobuf.MethodOptions.verify(e.options);if(t)return"options."+t}return null!=e.clientStreaming&&e.hasOwnProperty("clientStreaming")&&"boolean"!=typeof e.clientStreaming?"clientStreaming: boolean expected":null!=e.serverStreaming&&e.hasOwnProperty("serverStreaming")&&"boolean"!=typeof e.serverStreaming?"serverStreaming: boolean expected":null},x.fromObject=function(e){if(e instanceof p.google.protobuf.MethodDescriptorProto)return e;var t=new p.google.protobuf.MethodDescriptorProto;if(null!=e.name&&(t.name=String(e.name)),null!=e.inputType&&(t.inputType=String(e.inputType)),null!=e.outputType&&(t.outputType=String(e.outputType)),null!=e.options){if("object"!=typeof e.options)throw TypeError(".google.protobuf.MethodDescriptorProto.options: object expected");t.options=p.google.protobuf.MethodOptions.fromObject(e.options)}return null!=e.clientStreaming&&(t.clientStreaming=Boolean(e.clientStreaming)),null!=e.serverStreaming&&(t.serverStreaming=Boolean(e.serverStreaming)),t},x.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.name="",n.inputType="",n.outputType="",n.options=null,n.clientStreaming=!1,n.serverStreaming=!1),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.inputType&&e.hasOwnProperty("inputType")&&(n.inputType=e.inputType),null!=e.outputType&&e.hasOwnProperty("outputType")&&(n.outputType=e.outputType),null!=e.options&&e.hasOwnProperty("options")&&(n.options=p.google.protobuf.MethodOptions.toObject(e.options,t)),null!=e.clientStreaming&&e.hasOwnProperty("clientStreaming")&&(n.clientStreaming=e.clientStreaming),null!=e.serverStreaming&&e.hasOwnProperty("serverStreaming")&&(n.serverStreaming=e.serverStreaming),n},x.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},x),t.FileOptions=(k.prototype.javaPackage="",k.prototype.javaOuterClassname="",k.prototype.javaMultipleFiles=!1,k.prototype.javaGenerateEqualsAndHash=!1,k.prototype.javaStringCheckUtf8=!1,k.prototype.optimizeFor=1,k.prototype.goPackage="",k.prototype.ccGenericServices=!1,k.prototype.javaGenericServices=!1,k.prototype.pyGenericServices=!1,k.prototype.phpGenericServices=!1,k.prototype.deprecated=!1,k.prototype.ccEnableArenas=!0,k.prototype.objcClassPrefix="",k.prototype.csharpNamespace="",k.prototype.swiftPrefix="",k.prototype.phpClassPrefix="",k.prototype.phpNamespace="",k.prototype.phpMetadataNamespace="",k.prototype.rubyPackage="",k.prototype.uninterpretedOption=i.emptyArray,k.create=function(e){return new k(e)},k.encode=function(e,t){if(t=t||r.create(),null!=e.javaPackage&&Object.hasOwnProperty.call(e,"javaPackage")&&t.uint32(10).string(e.javaPackage),null!=e.javaOuterClassname&&Object.hasOwnProperty.call(e,"javaOuterClassname")&&t.uint32(66).string(e.javaOuterClassname),null!=e.optimizeFor&&Object.hasOwnProperty.call(e,"optimizeFor")&&t.uint32(72).int32(e.optimizeFor),null!=e.javaMultipleFiles&&Object.hasOwnProperty.call(e,"javaMultipleFiles")&&t.uint32(80).bool(e.javaMultipleFiles),null!=e.goPackage&&Object.hasOwnProperty.call(e,"goPackage")&&t.uint32(90).string(e.goPackage),null!=e.ccGenericServices&&Object.hasOwnProperty.call(e,"ccGenericServices")&&t.uint32(128).bool(e.ccGenericServices),null!=e.javaGenericServices&&Object.hasOwnProperty.call(e,"javaGenericServices")&&t.uint32(136).bool(e.javaGenericServices),null!=e.pyGenericServices&&Object.hasOwnProperty.call(e,"pyGenericServices")&&t.uint32(144).bool(e.pyGenericServices),null!=e.javaGenerateEqualsAndHash&&Object.hasOwnProperty.call(e,"javaGenerateEqualsAndHash")&&t.uint32(160).bool(e.javaGenerateEqualsAndHash),null!=e.deprecated&&Object.hasOwnProperty.call(e,"deprecated")&&t.uint32(184).bool(e.deprecated),null!=e.javaStringCheckUtf8&&Object.hasOwnProperty.call(e,"javaStringCheckUtf8")&&t.uint32(216).bool(e.javaStringCheckUtf8),null!=e.ccEnableArenas&&Object.hasOwnProperty.call(e,"ccEnableArenas")&&t.uint32(248).bool(e.ccEnableArenas),null!=e.objcClassPrefix&&Object.hasOwnProperty.call(e,"objcClassPrefix")&&t.uint32(290).string(e.objcClassPrefix),null!=e.csharpNamespace&&Object.hasOwnProperty.call(e,"csharpNamespace")&&t.uint32(298).string(e.csharpNamespace),null!=e.swiftPrefix&&Object.hasOwnProperty.call(e,"swiftPrefix")&&t.uint32(314).string(e.swiftPrefix),null!=e.phpClassPrefix&&Object.hasOwnProperty.call(e,"phpClassPrefix")&&t.uint32(322).string(e.phpClassPrefix),null!=e.phpNamespace&&Object.hasOwnProperty.call(e,"phpNamespace")&&t.uint32(330).string(e.phpNamespace),null!=e.phpGenericServices&&Object.hasOwnProperty.call(e,"phpGenericServices")&&t.uint32(336).bool(e.phpGenericServices),null!=e.phpMetadataNamespace&&Object.hasOwnProperty.call(e,"phpMetadataNamespace")&&t.uint32(354).string(e.phpMetadataNamespace),null!=e.rubyPackage&&Object.hasOwnProperty.call(e,"rubyPackage")&&t.uint32(362).string(e.rubyPackage),null!=e.uninterpretedOption&&e.uninterpretedOption.length)for(var n=0;n>>3){case 1:o.javaPackage=e.string();break;case 8:o.javaOuterClassname=e.string();break;case 10:o.javaMultipleFiles=e.bool();break;case 20:o.javaGenerateEqualsAndHash=e.bool();break;case 27:o.javaStringCheckUtf8=e.bool();break;case 9:o.optimizeFor=e.int32();break;case 11:o.goPackage=e.string();break;case 16:o.ccGenericServices=e.bool();break;case 17:o.javaGenericServices=e.bool();break;case 18:o.pyGenericServices=e.bool();break;case 42:o.phpGenericServices=e.bool();break;case 23:o.deprecated=e.bool();break;case 31:o.ccEnableArenas=e.bool();break;case 36:o.objcClassPrefix=e.string();break;case 37:o.csharpNamespace=e.string();break;case 39:o.swiftPrefix=e.string();break;case 40:o.phpClassPrefix=e.string();break;case 41:o.phpNamespace=e.string();break;case 44:o.phpMetadataNamespace=e.string();break;case 45:o.rubyPackage=e.string();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(p.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return o},k.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},k.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.javaPackage&&e.hasOwnProperty("javaPackage")&&!i.isString(e.javaPackage))return"javaPackage: string expected";if(null!=e.javaOuterClassname&&e.hasOwnProperty("javaOuterClassname")&&!i.isString(e.javaOuterClassname))return"javaOuterClassname: string expected";if(null!=e.javaMultipleFiles&&e.hasOwnProperty("javaMultipleFiles")&&"boolean"!=typeof e.javaMultipleFiles)return"javaMultipleFiles: boolean expected";if(null!=e.javaGenerateEqualsAndHash&&e.hasOwnProperty("javaGenerateEqualsAndHash")&&"boolean"!=typeof e.javaGenerateEqualsAndHash)return"javaGenerateEqualsAndHash: boolean expected";if(null!=e.javaStringCheckUtf8&&e.hasOwnProperty("javaStringCheckUtf8")&&"boolean"!=typeof e.javaStringCheckUtf8)return"javaStringCheckUtf8: boolean expected";if(null!=e.optimizeFor&&e.hasOwnProperty("optimizeFor"))switch(e.optimizeFor){default:return"optimizeFor: enum value expected";case 1:case 2:case 3:}if(null!=e.goPackage&&e.hasOwnProperty("goPackage")&&!i.isString(e.goPackage))return"goPackage: string expected";if(null!=e.ccGenericServices&&e.hasOwnProperty("ccGenericServices")&&"boolean"!=typeof e.ccGenericServices)return"ccGenericServices: boolean expected";if(null!=e.javaGenericServices&&e.hasOwnProperty("javaGenericServices")&&"boolean"!=typeof e.javaGenericServices)return"javaGenericServices: boolean expected";if(null!=e.pyGenericServices&&e.hasOwnProperty("pyGenericServices")&&"boolean"!=typeof e.pyGenericServices)return"pyGenericServices: boolean expected";if(null!=e.phpGenericServices&&e.hasOwnProperty("phpGenericServices")&&"boolean"!=typeof e.phpGenericServices)return"phpGenericServices: boolean expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.ccEnableArenas&&e.hasOwnProperty("ccEnableArenas")&&"boolean"!=typeof e.ccEnableArenas)return"ccEnableArenas: boolean expected";if(null!=e.objcClassPrefix&&e.hasOwnProperty("objcClassPrefix")&&!i.isString(e.objcClassPrefix))return"objcClassPrefix: string expected";if(null!=e.csharpNamespace&&e.hasOwnProperty("csharpNamespace")&&!i.isString(e.csharpNamespace))return"csharpNamespace: string expected";if(null!=e.swiftPrefix&&e.hasOwnProperty("swiftPrefix")&&!i.isString(e.swiftPrefix))return"swiftPrefix: string expected";if(null!=e.phpClassPrefix&&e.hasOwnProperty("phpClassPrefix")&&!i.isString(e.phpClassPrefix))return"phpClassPrefix: string expected";if(null!=e.phpNamespace&&e.hasOwnProperty("phpNamespace")&&!i.isString(e.phpNamespace))return"phpNamespace: string expected";if(null!=e.phpMetadataNamespace&&e.hasOwnProperty("phpMetadataNamespace")&&!i.isString(e.phpMetadataNamespace))return"phpMetadataNamespace: string expected";if(null!=e.rubyPackage&&e.hasOwnProperty("rubyPackage")&&!i.isString(e.rubyPackage))return"rubyPackage: string expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 1:o.messageSetWireFormat=e.bool();break;case 2:o.noStandardDescriptorAccessor=e.bool();break;case 3:o.deprecated=e.bool();break;case 7:o.mapEntry=e.bool();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(p.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return o},D.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},D.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.messageSetWireFormat&&e.hasOwnProperty("messageSetWireFormat")&&"boolean"!=typeof e.messageSetWireFormat)return"messageSetWireFormat: boolean expected";if(null!=e.noStandardDescriptorAccessor&&e.hasOwnProperty("noStandardDescriptorAccessor")&&"boolean"!=typeof e.noStandardDescriptorAccessor)return"noStandardDescriptorAccessor: boolean expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.mapEntry&&e.hasOwnProperty("mapEntry")&&"boolean"!=typeof e.mapEntry)return"mapEntry: boolean expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 1:o.ctype=e.int32();break;case 2:o.packed=e.bool();break;case 6:o.jstype=e.int32();break;case 5:o.lazy=e.bool();break;case 3:o.deprecated=e.bool();break;case 10:o.weak=e.bool();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(p.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return o},T.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},T.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.ctype&&e.hasOwnProperty("ctype"))switch(e.ctype){default:return"ctype: enum value expected";case 0:case 1:case 2:}if(null!=e.packed&&e.hasOwnProperty("packed")&&"boolean"!=typeof e.packed)return"packed: boolean expected";if(null!=e.jstype&&e.hasOwnProperty("jstype"))switch(e.jstype){default:return"jstype: enum value expected";case 0:case 1:case 2:}if(null!=e.lazy&&e.hasOwnProperty("lazy")&&"boolean"!=typeof e.lazy)return"lazy: boolean expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.weak&&e.hasOwnProperty("weak")&&"boolean"!=typeof e.weak)return"weak: boolean expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3==999?(o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(p.google.protobuf.UninterpretedOption.decode(e,e.uint32()))):e.skipType(7&r)}return o},H.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},H.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 2:o.allowAlias=e.bool();break;case 3:o.deprecated=e.bool();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(p.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return o},E.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},E.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.allowAlias&&e.hasOwnProperty("allowAlias")&&"boolean"!=typeof e.allowAlias)return"allowAlias: boolean expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 1:o.deprecated=e.bool();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(p.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return o},z.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},z.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 33:o.deprecated=e.bool();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(p.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;case 1049:o[".google.api.defaultHost"]=e.string();break;case 1050:o[".google.api.oauthScopes"]=e.string();break;default:e.skipType(7&r)}}return o},A.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},A.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 33:o.deprecated=e.bool();break;case 34:o.idempotencyLevel=e.int32();break;case 999:o.uninterpretedOption&&o.uninterpretedOption.length||(o.uninterpretedOption=[]),o.uninterpretedOption.push(p.google.protobuf.UninterpretedOption.decode(e,e.uint32()));break;case 1049:o[".google.longrunning.operationInfo"]=p.google.longrunning.OperationInfo.decode(e,e.uint32());break;case 72295728:o[".google.api.http"]=p.google.api.HttpRule.decode(e,e.uint32());break;case 1051:o[".google.api.methodSignature"]&&o[".google.api.methodSignature"].length||(o[".google.api.methodSignature"]=[]),o[".google.api.methodSignature"].push(e.string());break;default:e.skipType(7&r)}}return o},N.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},N.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.deprecated&&e.hasOwnProperty("deprecated")&&"boolean"!=typeof e.deprecated)return"deprecated: boolean expected";if(null!=e.idempotencyLevel&&e.hasOwnProperty("idempotencyLevel"))switch(e.idempotencyLevel){default:return"idempotencyLevel: enum value expected";case 0:case 1:case 2:}if(null!=e.uninterpretedOption&&e.hasOwnProperty("uninterpretedOption")){if(!Array.isArray(e.uninterpretedOption))return"uninterpretedOption: array expected";for(var t=0;t>>3){case 2:o.name&&o.name.length||(o.name=[]),o.name.push(p.google.protobuf.UninterpretedOption.NamePart.decode(e,e.uint32()));break;case 3:o.identifierValue=e.string();break;case 4:o.positiveIntValue=e.uint64();break;case 5:o.negativeIntValue=e.int64();break;case 6:o.doubleValue=e.double();break;case 7:o.stringValue=e.bytes();break;case 8:o.aggregateValue=e.string();break;default:e.skipType(7&r)}}return o},I.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},I.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")){if(!Array.isArray(e.name))return"name: array expected";for(var t=0;t>>0,e.positiveIntValue.high>>>0).toNumber(!0))),null!=e.negativeIntValue&&(i.Long?(t.negativeIntValue=i.Long.fromValue(e.negativeIntValue)).unsigned=!1:"string"==typeof e.negativeIntValue?t.negativeIntValue=parseInt(e.negativeIntValue,10):"number"==typeof e.negativeIntValue?t.negativeIntValue=e.negativeIntValue:"object"==typeof e.negativeIntValue&&(t.negativeIntValue=new i.LongBits(e.negativeIntValue.low>>>0,e.negativeIntValue.high>>>0).toNumber())),null!=e.doubleValue&&(t.doubleValue=Number(e.doubleValue)),null!=e.stringValue&&("string"==typeof e.stringValue?i.base64.decode(e.stringValue,t.stringValue=i.newBuffer(i.base64.length(e.stringValue)),0):e.stringValue.length&&(t.stringValue=e.stringValue)),null!=e.aggregateValue&&(t.aggregateValue=String(e.aggregateValue)),t},I.toObject=function(e,t){var n,o={};if(((t=t||{}).arrays||t.defaults)&&(o.name=[]),t.defaults&&(o.identifierValue="",i.Long?(n=new i.Long(0,0,!0),o.positiveIntValue=t.longs===String?n.toString():t.longs===Number?n.toNumber():n):o.positiveIntValue=t.longs===String?"0":0,i.Long?(n=new i.Long(0,0,!1),o.negativeIntValue=t.longs===String?n.toString():t.longs===Number?n.toNumber():n):o.negativeIntValue=t.longs===String?"0":0,o.doubleValue=0,t.bytes===String?o.stringValue="":(o.stringValue=[],t.bytes!==Array&&(o.stringValue=i.newBuffer(o.stringValue))),o.aggregateValue=""),e.name&&e.name.length){o.name=[];for(var r=0;r>>0,e.positiveIntValue.high>>>0).toNumber(!0):e.positiveIntValue),null!=e.negativeIntValue&&e.hasOwnProperty("negativeIntValue")&&("number"==typeof e.negativeIntValue?o.negativeIntValue=t.longs===String?String(e.negativeIntValue):e.negativeIntValue:o.negativeIntValue=t.longs===String?i.Long.prototype.toString.call(e.negativeIntValue):t.longs===Number?new i.LongBits(e.negativeIntValue.low>>>0,e.negativeIntValue.high>>>0).toNumber():e.negativeIntValue),null!=e.doubleValue&&e.hasOwnProperty("doubleValue")&&(o.doubleValue=t.json&&!isFinite(e.doubleValue)?String(e.doubleValue):e.doubleValue),null!=e.stringValue&&e.hasOwnProperty("stringValue")&&(o.stringValue=t.bytes===String?i.base64.encode(e.stringValue,0,e.stringValue.length):t.bytes===Array?Array.prototype.slice.call(e.stringValue):e.stringValue),null!=e.aggregateValue&&e.hasOwnProperty("aggregateValue")&&(o.aggregateValue=e.aggregateValue),o},I.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},I.NamePart=(q.prototype.namePart="",q.prototype.isExtension=!1,q.create=function(e){return new q(e)},q.encode=function(e,t){return(t=t||r.create()).uint32(10).string(e.namePart),t.uint32(16).bool(e.isExtension),t},q.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},q.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new p.google.protobuf.UninterpretedOption.NamePart;e.pos>>3){case 1:o.namePart=e.string();break;case 2:o.isExtension=e.bool();break;default:e.skipType(7&r)}}if(!o.hasOwnProperty("namePart"))throw i.ProtocolError("missing required 'namePart'",{instance:o});if(o.hasOwnProperty("isExtension"))return o;throw i.ProtocolError("missing required 'isExtension'",{instance:o})},q.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},q.verify=function(e){return"object"!=typeof e||null===e?"object expected":i.isString(e.namePart)?"boolean"!=typeof e.isExtension?"isExtension: boolean expected":null:"namePart: string expected"},q.fromObject=function(e){var t;return e instanceof p.google.protobuf.UninterpretedOption.NamePart?e:(t=new p.google.protobuf.UninterpretedOption.NamePart,null!=e.namePart&&(t.namePart=String(e.namePart)),null!=e.isExtension&&(t.isExtension=Boolean(e.isExtension)),t)},q.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.namePart="",n.isExtension=!1),null!=e.namePart&&e.hasOwnProperty("namePart")&&(n.namePart=e.namePart),null!=e.isExtension&&e.hasOwnProperty("isExtension")&&(n.isExtension=e.isExtension),n},q.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},q),I),t.SourceCodeInfo=(Y.prototype.location=i.emptyArray,Y.create=function(e){return new Y(e)},Y.encode=function(e,t){if(t=t||r.create(),null!=e.location&&e.location.length)for(var n=0;n>>3==1?(o.location&&o.location.length||(o.location=[]),o.location.push(p.google.protobuf.SourceCodeInfo.Location.decode(e,e.uint32()))):e.skipType(7&r)}return o},Y.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},Y.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.location&&e.hasOwnProperty("location")){if(!Array.isArray(e.location))return"location: array expected";for(var t=0;t>>3){case 1:if(o.path&&o.path.length||(o.path=[]),2==(7&r))for(var i=e.uint32()+e.pos;e.pos>>3==1?(o.annotation&&o.annotation.length||(o.annotation=[]),o.annotation.push(p.google.protobuf.GeneratedCodeInfo.Annotation.decode(e,e.uint32()))):e.skipType(7&r)}return o},W.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},W.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.annotation&&e.hasOwnProperty("annotation")){if(!Array.isArray(e.annotation))return"annotation: array expected";for(var t=0;t>>3){case 1:if(o.path&&o.path.length||(o.path=[]),2==(7&r))for(var i=e.uint32()+e.pos;e.pos>>3){case 1:o.type_url=e.string();break;case 2:o.value=e.bytes();break;default:e.skipType(7&r)}}return o},X.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},X.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.type_url&&e.hasOwnProperty("type_url")&&!i.isString(e.type_url)?"type_url: string expected":null!=e.value&&e.hasOwnProperty("value")&&!(e.value&&"number"==typeof e.value.length||i.isString(e.value))?"value: buffer expected":null},X.fromObject=function(e){var t;return e instanceof p.google.protobuf.Any?e:(t=new p.google.protobuf.Any,null!=e.type_url&&(t.type_url=String(e.type_url)),null!=e.value&&("string"==typeof e.value?i.base64.decode(e.value,t.value=i.newBuffer(i.base64.length(e.value)),0):e.value.length&&(t.value=e.value)),t)},X.toObject=function(e,t){var n={};return(t=t||{}).defaults&&(n.type_url="",t.bytes===String?n.value="":(n.value=[],t.bytes!==Array&&(n.value=i.newBuffer(n.value)))),null!=e.type_url&&e.hasOwnProperty("type_url")&&(n.type_url=e.type_url),null!=e.value&&e.hasOwnProperty("value")&&(n.value=t.bytes===String?i.base64.encode(e.value,0,e.value.length):t.bytes===Array?Array.prototype.slice.call(e.value):e.value),n},X.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},X),t.Duration=(K.prototype.seconds=i.Long?i.Long.fromBits(0,0,!1):0,K.prototype.nanos=0,K.create=function(e){return new K(e)},K.encode=function(e,t){return t=t||r.create(),null!=e.seconds&&Object.hasOwnProperty.call(e,"seconds")&&t.uint32(8).int64(e.seconds),null!=e.nanos&&Object.hasOwnProperty.call(e,"nanos")&&t.uint32(16).int32(e.nanos),t},K.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},K.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,o=new p.google.protobuf.Duration;e.pos>>3){case 1:o.seconds=e.int64();break;case 2:o.nanos=e.int32();break;default:e.skipType(7&r)}}return o},K.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},K.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.seconds&&e.hasOwnProperty("seconds")&&!(i.isInteger(e.seconds)||e.seconds&&i.isInteger(e.seconds.low)&&i.isInteger(e.seconds.high))?"seconds: integer|Long expected":null!=e.nanos&&e.hasOwnProperty("nanos")&&!i.isInteger(e.nanos)?"nanos: integer expected":null},K.fromObject=function(e){var t;return e instanceof p.google.protobuf.Duration?e:(t=new p.google.protobuf.Duration,null!=e.seconds&&(i.Long?(t.seconds=i.Long.fromValue(e.seconds)).unsigned=!1:"string"==typeof e.seconds?t.seconds=parseInt(e.seconds,10):"number"==typeof e.seconds?t.seconds=e.seconds:"object"==typeof e.seconds&&(t.seconds=new i.LongBits(e.seconds.low>>>0,e.seconds.high>>>0).toNumber())),null!=e.nanos&&(t.nanos=0|e.nanos),t)},K.toObject=function(e,t){var n,o={};return(t=t||{}).defaults&&(i.Long?(n=new i.Long(0,0,!1),o.seconds=t.longs===String?n.toString():t.longs===Number?n.toNumber():n):o.seconds=t.longs===String?"0":0,o.nanos=0),null!=e.seconds&&e.hasOwnProperty("seconds")&&("number"==typeof e.seconds?o.seconds=t.longs===String?String(e.seconds):e.seconds:o.seconds=t.longs===String?i.Long.prototype.toString.call(e.seconds):t.longs===Number?new i.LongBits(e.seconds.low>>>0,e.seconds.high>>>0).toNumber():e.seconds),null!=e.nanos&&e.hasOwnProperty("nanos")&&(o.nanos=e.nanos),o},K.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},K),t.Empty=(Q.create=function(e){return new Q(e)},Q.encode=function(e,t){return t=t||r.create()},Q.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},Q.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,t=new p.google.protobuf.Empty;e.pos>>3){case 1:o.code=e.int32();break;case 2:o.message=e.string();break;case 3:o.details&&o.details.length||(o.details=[]),o.details.push(p.google.protobuf.Any.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return o},V.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},V.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.code&&e.hasOwnProperty("code")&&!i.isInteger(e.code))return"code: integer expected";if(null!=e.message&&e.hasOwnProperty("message")&&!i.isString(e.message))return"message: string expected";if(null!=e.details&&e.hasOwnProperty("details")){if(!Array.isArray(e.details))return"details: array expected";for(var t=0;t | CancellableStream; +} +export declare function createAPICaller(settings: CallSettings, descriptor: Descriptor | undefined): APICaller; diff --git a/node_modules/google-gax/build/src/apiCaller.js b/node_modules/google-gax/build/src/apiCaller.js new file mode 100644 index 0000000..edd75e1 --- /dev/null +++ b/node_modules/google-gax/build/src/apiCaller.js @@ -0,0 +1,26 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createAPICaller = createAPICaller; +const normalApiCaller_1 = require("./normalCalls/normalApiCaller"); +function createAPICaller(settings, descriptor) { + if (!descriptor) { + return new normalApiCaller_1.NormalApiCaller(); + } + return descriptor.getApiCaller(settings); +} +//# sourceMappingURL=apiCaller.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/apiCaller.js.map b/node_modules/google-gax/build/src/apiCaller.js.map new file mode 100644 index 0000000..0057607 --- /dev/null +++ b/node_modules/google-gax/build/src/apiCaller.js.map @@ -0,0 +1 @@ +{"version":3,"file":"apiCaller.js","sourceRoot":"","sources":["../../src/apiCaller.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAsCH,0CAQC;AAjCD,mEAA8D;AAyB9D,SAAgB,eAAe,CAC7B,QAAsB,EACtB,UAAkC;IAElC,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,IAAI,iCAAe,EAAE,CAAC;IAC/B,CAAC;IACD,OAAO,UAAU,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC;AAC3C,CAAC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/apitypes.d.ts b/node_modules/google-gax/build/src/apitypes.d.ts new file mode 100644 index 0000000..35cb1fc --- /dev/null +++ b/node_modules/google-gax/build/src/apitypes.d.ts @@ -0,0 +1,63 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Duplex } from 'stream'; +import { CancellablePromise } from './call'; +import { CallOptions } from './gax'; +import { GoogleError } from './googleError'; +import { Operation } from './longRunningCalls/longrunning'; +export interface GRPCCallResult { + cancel(): void; +} +export interface RequestType { + [index: string]: string | number | RequestType | Array; +} +export type ResponseType = {} | null; +export type NextPageRequestType = { + [index: string]: string | number | {}; +} | null; +export type RawResponseType = Operation | {} | null; +export type ResultTuple = [ + ResponseType | [ResponseType], + NextPageRequestType | undefined, + RawResponseType | undefined +]; +export interface SimpleCallbackFunction { + (request: RequestType, callback: APICallback): GRPCCallResult; +} +export type APICallback = (err: GoogleError | null, response?: ResponseType, next?: NextPageRequestType, rawResponse?: RawResponseType) => void; +export type UnaryCall = (argument: {}, metadata: {}, options: {}, callback: APICallback) => GRPCCallResult; +export type ServerStreamingCall = (argument: {}, metadata: {}, options: {}) => Duplex & GRPCCallResult; +export type ClientStreamingCall = (metadata: {}, options: {}, callback?: APICallback) => Duplex & GRPCCallResult; +export type BiDiStreamingCall = (metadata: {}, options: {}) => Duplex & GRPCCallResult; +export type GRPCCall = UnaryCall | ServerStreamingCall | ClientStreamingCall | BiDiStreamingCall; +export type CancellableStream = Duplex & GRPCCallResult; +export type GaxCallResult = CancellablePromise | CancellableStream; +export interface GaxCallPromise { + (argument: {}, callOptions?: CallOptions, callback?: APICallback): CancellablePromise; +} +export interface GaxCallStream { + (argument: {}, callOptions?: CallOptions, callback?: APICallback): CancellableStream; +} +export interface GaxCall { + (argument: {}, callOptions?: CallOptions, callback?: APICallback): GaxCallResult; +} +export interface GRPCCallOtherArgs { + options?: { + deadline?: Date; + }; + headers?: {}; + metadataBuilder: (abTests?: {}, headers?: {}) => {}; +} diff --git a/node_modules/google-gax/build/src/apitypes.js b/node_modules/google-gax/build/src/apitypes.js new file mode 100644 index 0000000..1c1a5ce --- /dev/null +++ b/node_modules/google-gax/build/src/apitypes.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=apitypes.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/apitypes.js.map b/node_modules/google-gax/build/src/apitypes.js.map new file mode 100644 index 0000000..079005e --- /dev/null +++ b/node_modules/google-gax/build/src/apitypes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"apitypes.js","sourceRoot":"","sources":["../../src/apitypes.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/bundlingCalls/bundleApiCaller.d.ts b/node_modules/google-gax/build/src/bundlingCalls/bundleApiCaller.d.ts new file mode 100644 index 0000000..697fd9c --- /dev/null +++ b/node_modules/google-gax/build/src/bundlingCalls/bundleApiCaller.d.ts @@ -0,0 +1,34 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { APICaller } from '../apiCaller'; +import { APICallback, GRPCCall, SimpleCallbackFunction } from '../apitypes'; +import { OngoingCall, OngoingCallPromise } from '../call'; +import { CallSettings } from '../gax'; +import { GoogleError } from '../googleError'; +import { BundleExecutor } from './bundleExecutor'; +/** + * An implementation of APICaller for bundled calls. + * Uses BundleExecutor to do bundling. + */ +export declare class BundleApiCaller implements APICaller { + bundler: BundleExecutor; + constructor(bundler: BundleExecutor); + init(callback?: APICallback): OngoingCallPromise | OngoingCall; + wrap(func: GRPCCall): GRPCCall; + call(apiCall: SimpleCallbackFunction, argument: {}, settings: CallSettings, status: OngoingCallPromise): void; + fail(canceller: OngoingCallPromise, err: GoogleError): void; + result(canceller: OngoingCallPromise): import("../call").CancellablePromise; +} diff --git a/node_modules/google-gax/build/src/bundlingCalls/bundleApiCaller.js b/node_modules/google-gax/build/src/bundlingCalls/bundleApiCaller.js new file mode 100644 index 0000000..0b571ee --- /dev/null +++ b/node_modules/google-gax/build/src/bundlingCalls/bundleApiCaller.js @@ -0,0 +1,55 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BundleApiCaller = void 0; +const call_1 = require("../call"); +const googleError_1 = require("../googleError"); +/** + * An implementation of APICaller for bundled calls. + * Uses BundleExecutor to do bundling. + */ +class BundleApiCaller { + constructor(bundler) { + this.bundler = bundler; + } + init(callback) { + if (callback) { + return new call_1.OngoingCall(callback); + } + return new call_1.OngoingCallPromise(); + } + wrap(func) { + return func; + } + call(apiCall, argument, settings, status) { + if (!settings.isBundling) { + throw new googleError_1.GoogleError('Bundling enabled with no isBundling!'); + } + status.call((argument, callback) => { + this.bundler.schedule(apiCall, argument, callback); + return status; + }, argument); + } + fail(canceller, err) { + canceller.callback(err); + } + result(canceller) { + return canceller.promise; + } +} +exports.BundleApiCaller = BundleApiCaller; +//# sourceMappingURL=bundleApiCaller.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/bundlingCalls/bundleApiCaller.js.map b/node_modules/google-gax/build/src/bundlingCalls/bundleApiCaller.js.map new file mode 100644 index 0000000..dc3c2e6 --- /dev/null +++ b/node_modules/google-gax/build/src/bundlingCalls/bundleApiCaller.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bundleApiCaller.js","sourceRoot":"","sources":["../../../src/bundlingCalls/bundleApiCaller.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAIH,kCAAwD;AAExD,gDAA2C;AAK3C;;;GAGG;AACH,MAAa,eAAe;IAG1B,YAAY,OAAuB;QACjC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,IAAI,CAAC,QAAsB;QACzB,IAAI,QAAQ,EAAE,CAAC;YACb,OAAO,IAAI,kBAAW,CAAC,QAAQ,CAAC,CAAC;QACnC,CAAC;QACD,OAAO,IAAI,yBAAkB,EAAE,CAAC;IAClC,CAAC;IAED,IAAI,CAAC,IAAc;QACjB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,CACF,OAA+B,EAC/B,QAAY,EACZ,QAAsB,EACtB,MAA0B;QAE1B,IAAI,CAAC,QAAQ,CAAC,UAAU,EAAE,CAAC;YACzB,MAAM,IAAI,yBAAW,CAAC,sCAAsC,CAAC,CAAC;QAChE,CAAC;QAED,MAAM,CAAC,IAAI,CAAC,CAAC,QAAY,EAAE,QAAsB,EAAE,EAAE;YACnD,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,OAAO,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC;YACnD,OAAO,MAAM,CAAC;QAChB,CAAC,EAAE,QAAQ,CAAC,CAAC;IACf,CAAC;IAED,IAAI,CAAC,SAA6B,EAAE,GAAgB;QAClD,SAAS,CAAC,QAAS,CAAC,GAAG,CAAC,CAAC;IAC3B,CAAC;IAED,MAAM,CAAC,SAA6B;QAClC,OAAO,SAAS,CAAC,OAAO,CAAC;IAC3B,CAAC;CACF;AAzCD,0CAyCC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/bundlingCalls/bundleDescriptor.d.ts b/node_modules/google-gax/build/src/bundlingCalls/bundleDescriptor.d.ts new file mode 100644 index 0000000..6ea401b --- /dev/null +++ b/node_modules/google-gax/build/src/bundlingCalls/bundleDescriptor.d.ts @@ -0,0 +1,57 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Descriptor } from '../descriptor'; +import { CallSettings } from '../gax'; +import { NormalApiCaller } from '../normalCalls/normalApiCaller'; +import { BundleApiCaller } from './bundleApiCaller'; +/** + * A descriptor for calls that can be bundled into one call. + */ +export declare class BundleDescriptor implements Descriptor { + bundledField: string; + requestDiscriminatorFields: string[]; + subresponseField: string | null; + byteLengthFunction: Function; + /** + * Describes the structure of bundled call. + * + * requestDiscriminatorFields may include '.' as a separator, which is used to + * indicate object traversal. This allows fields in nested objects to be used + * to determine what request to bundle. + * + * @property {String} bundledField + * @property {String} requestDiscriminatorFields + * @property {String} subresponseField + * @property {Function} byteLengthFunction + * + * @param {String} bundledField - the repeated field in the request message + * that will have its elements aggregated by bundling. + * @param {String} requestDiscriminatorFields - a list of fields in the + * target request message class that are used to detemrine which request + * messages should be bundled together. + * @param {String} subresponseField - an optional field, when present it + * indicates the field in the response message that should be used to + * demultiplex the response into multiple response messages. + * @param {Function} byteLengthFunction - a function to obtain the byte + * length to be consumed for the bundled field messages. Because Node.JS + * protobuf.js/gRPC uses builtin Objects for the user-visible data and + * internally they are encoded/decoded in protobuf manner, this function + * is actually necessary to calculate the byte length. + * @constructor + */ + constructor(bundledField: string, requestDiscriminatorFields: string[], subresponseField: string | null, byteLengthFunction: Function); + getApiCaller(settings: CallSettings): NormalApiCaller | BundleApiCaller; +} diff --git a/node_modules/google-gax/build/src/bundlingCalls/bundleDescriptor.js b/node_modules/google-gax/build/src/bundlingCalls/bundleDescriptor.js new file mode 100644 index 0000000..f80a309 --- /dev/null +++ b/node_modules/google-gax/build/src/bundlingCalls/bundleDescriptor.js @@ -0,0 +1,73 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BundleDescriptor = void 0; +const normalApiCaller_1 = require("../normalCalls/normalApiCaller"); +const bundleApiCaller_1 = require("./bundleApiCaller"); +const bundleExecutor_1 = require("./bundleExecutor"); +const util_1 = require("../util"); +/** + * A descriptor for calls that can be bundled into one call. + */ +class BundleDescriptor { + /** + * Describes the structure of bundled call. + * + * requestDiscriminatorFields may include '.' as a separator, which is used to + * indicate object traversal. This allows fields in nested objects to be used + * to determine what request to bundle. + * + * @property {String} bundledField + * @property {String} requestDiscriminatorFields + * @property {String} subresponseField + * @property {Function} byteLengthFunction + * + * @param {String} bundledField - the repeated field in the request message + * that will have its elements aggregated by bundling. + * @param {String} requestDiscriminatorFields - a list of fields in the + * target request message class that are used to detemrine which request + * messages should be bundled together. + * @param {String} subresponseField - an optional field, when present it + * indicates the field in the response message that should be used to + * demultiplex the response into multiple response messages. + * @param {Function} byteLengthFunction - a function to obtain the byte + * length to be consumed for the bundled field messages. Because Node.JS + * protobuf.js/gRPC uses builtin Objects for the user-visible data and + * internally they are encoded/decoded in protobuf manner, this function + * is actually necessary to calculate the byte length. + * @constructor + */ + constructor(bundledField, requestDiscriminatorFields, subresponseField, byteLengthFunction) { + if (!byteLengthFunction && typeof subresponseField === 'function') { + byteLengthFunction = subresponseField; + subresponseField = null; + } + this.bundledField = bundledField; + this.requestDiscriminatorFields = + requestDiscriminatorFields.map(util_1.toCamelCase); + this.subresponseField = subresponseField; + this.byteLengthFunction = byteLengthFunction; + } + getApiCaller(settings) { + if (settings.isBundling === false) { + return new normalApiCaller_1.NormalApiCaller(); + } + return new bundleApiCaller_1.BundleApiCaller(new bundleExecutor_1.BundleExecutor(settings.bundleOptions, this)); + } +} +exports.BundleDescriptor = BundleDescriptor; +//# sourceMappingURL=bundleDescriptor.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/bundlingCalls/bundleDescriptor.js.map b/node_modules/google-gax/build/src/bundlingCalls/bundleDescriptor.js.map new file mode 100644 index 0000000..2938b93 --- /dev/null +++ b/node_modules/google-gax/build/src/bundlingCalls/bundleDescriptor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bundleDescriptor.js","sourceRoot":"","sources":["../../../src/bundlingCalls/bundleDescriptor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAIH,oEAA+D;AAE/D,uDAAkD;AAClD,qDAAgD;AAChD,kCAAwD;AAExD;;GAEG;AACH,MAAa,gBAAgB;IAM3B;;;;;;;;;;;;;;;;;;;;;;;;;;OA0BG;IACH,YACE,YAAoB,EACpB,0BAAoC,EACpC,gBAA+B,EAC/B,kBAA4B;QAE5B,IAAI,CAAC,kBAAkB,IAAI,OAAO,gBAAgB,KAAK,UAAU,EAAE,CAAC;YAClE,kBAAkB,GAAG,gBAAgB,CAAC;YACtC,gBAAgB,GAAG,IAAI,CAAC;QAC1B,CAAC;QACD,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,0BAA0B;YAC7B,0BAA0B,CAAC,GAAG,CAAC,kBAAgB,CAAC,CAAC;QACnD,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;QACzC,IAAI,CAAC,kBAAkB,GAAG,kBAAkB,CAAC;IAC/C,CAAC;IAED,YAAY,CAAC,QAAsB;QACjC,IAAI,QAAQ,CAAC,UAAU,KAAK,KAAK,EAAE,CAAC;YAClC,OAAO,IAAI,iCAAe,EAAE,CAAC;QAC/B,CAAC;QACD,OAAO,IAAI,iCAAe,CACxB,IAAI,+BAAc,CAAC,QAAQ,CAAC,aAAc,EAAE,IAAI,CAAC,CAClD,CAAC;IACJ,CAAC;CACF;AA1DD,4CA0DC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/bundlingCalls/bundleExecutor.d.ts b/node_modules/google-gax/build/src/bundlingCalls/bundleExecutor.d.ts new file mode 100644 index 0000000..50b2c80 --- /dev/null +++ b/node_modules/google-gax/build/src/bundlingCalls/bundleExecutor.d.ts @@ -0,0 +1,116 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SimpleCallbackFunction } from '../apitypes'; +import { BundleDescriptor } from './bundleDescriptor'; +import { Task, TaskCallback } from './task'; +/** + * Parameter to configure bundling behavior. + * @typedef {Object} BundleOptions + * @property {number} elementCountThreshold - + * the bundled request will be sent once the count of outstanding elements + * in the repeated field reaches this value. + * @property {number} elementCountLimit - + * represents a hard limit on the number of elements in the repeated field + * of the bundle; if adding a request to a bundle would exceed this value, + * the bundle is sent and the new request is added to a fresh bundle. It is + * invalid for a single request to exceed this limit. + * @property {number} requestByteThreshold - + * the bundled request will be sent once the count of bytes in the request + * reaches this value. Note that this value is pessimistically approximated + * by summing the bytesizes of the elements in the repeated field, and + * therefore may be an under-approximation. + * @property {number} requestByteLimit - + * represents a hard limit on the size of the bundled request; if adding + * a request to a bundle would exceed this value, the bundle is sent and + * the new request is added to a fresh bundle. It is invalid for a single + * request to exceed this limit. Note that this value is pessimistically + * approximated by summing the bytesizes of the elements in the repeated + * field, with a buffer applied to correspond to the resulting + * under-approximation. + * @property {number} delayThreshold - + * the bundled request will be sent this amount of time after the first + * element in the bundle was added to it. + */ +export interface BundleOptions { + elementCountLimit?: number; + requestByteLimit?: number; + elementCountThreshold?: number; + requestByteThreshold?: number; + delayThreshold?: number; +} +/** + * BundleExecutor stores several timers for each bundle (calls are bundled based + * on the options passed, each bundle has unique ID that is calculated based on + * field values). Each timer fires and sends a call after certain amount of + * time, and if a new request comes to the same bundle, the timer can be + * restarted. + */ +export declare class BundleExecutor { + _options: BundleOptions; + _descriptor: BundleDescriptor; + _tasks: { + [index: string]: Task; + }; + _timers: { + [index: string]: ReturnType; + }; + _invocations: { + [index: string]: string; + }; + _invocationId: number; + /** + * Organizes requests for an api service that requires to bundle them. + * + * @param {BundleOptions} bundleOptions - configures strategy this instance + * uses when executing bundled functions. + * @param {BundleDescriptor} bundleDescriptor - the description of the bundling. + * @constructor + */ + constructor(bundleOptions: BundleOptions, bundleDescriptor: BundleDescriptor); + /** + * Schedule a method call. + * + * @param {function} apiCall - the function for an API call. + * @param {Object} request - the request object to be bundled with others. + * @param {APICallback} callback - the callback to be called when the method finished. + * @return {function()} - the function to cancel the scheduled invocation. + */ + schedule(apiCall: SimpleCallbackFunction, request: { + [index: string]: Array<{}> | string; + }, callback?: TaskCallback): import("../apitypes").GRPCCallResult; + /** + * Clears scheduled timeout if it exists. + * + * @param {String} bundleId - the id for the task whose timeout needs to be + * cleared. + * @private + */ + private _maybeClearTimeout; + /** + * Cancels an event. + * + * @param {String} id - The id for the event in the task. + * @private + */ + private _cancel; + /** + * Invokes a task. + * + * @param {String} bundleId - The id for the task. + * @private + */ + _runNow(bundleId: string): void; +} diff --git a/node_modules/google-gax/build/src/bundlingCalls/bundleExecutor.js b/node_modules/google-gax/build/src/bundlingCalls/bundleExecutor.js new file mode 100644 index 0000000..71fc9a5 --- /dev/null +++ b/node_modules/google-gax/build/src/bundlingCalls/bundleExecutor.js @@ -0,0 +1,195 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BundleExecutor = void 0; +const status_1 = require("../status"); +const googleError_1 = require("../googleError"); +const warnings_1 = require("../warnings"); +const bundlingUtils_1 = require("./bundlingUtils"); +const task_1 = require("./task"); +function noop() { } +/** + * BundleExecutor stores several timers for each bundle (calls are bundled based + * on the options passed, each bundle has unique ID that is calculated based on + * field values). Each timer fires and sends a call after certain amount of + * time, and if a new request comes to the same bundle, the timer can be + * restarted. + */ +class BundleExecutor { + /** + * Organizes requests for an api service that requires to bundle them. + * + * @param {BundleOptions} bundleOptions - configures strategy this instance + * uses when executing bundled functions. + * @param {BundleDescriptor} bundleDescriptor - the description of the bundling. + * @constructor + */ + constructor(bundleOptions, bundleDescriptor) { + this._options = bundleOptions; + this._descriptor = bundleDescriptor; + this._tasks = {}; + this._timers = {}; + this._invocations = {}; + this._invocationId = 0; + } + /** + * Schedule a method call. + * + * @param {function} apiCall - the function for an API call. + * @param {Object} request - the request object to be bundled with others. + * @param {APICallback} callback - the callback to be called when the method finished. + * @return {function()} - the function to cancel the scheduled invocation. + */ + schedule(apiCall, request, callback) { + const bundleId = (0, bundlingUtils_1.computeBundleId)(request, this._descriptor.requestDiscriminatorFields); + callback = (callback || noop); + if (bundleId === undefined) { + (0, warnings_1.warn)('bundling_schedule_bundleid_undefined', 'The request does not have enough information for request bundling. ' + + `Invoking immediately. Request: ${JSON.stringify(request)} ` + + `discriminator fields: ${this._descriptor.requestDiscriminatorFields}`); + return apiCall(request, callback); + } + if (request[this._descriptor.bundledField] === undefined) { + (0, warnings_1.warn)('bundling_no_bundled_field', `Request does not contain field ${this._descriptor.bundledField} that must present for bundling. ` + + `Invoking immediately. Request: ${JSON.stringify(request)}`); + return apiCall(request, callback); + } + if (!(bundleId in this._tasks)) { + this._tasks[bundleId] = new task_1.Task(apiCall, request, this._descriptor.bundledField, this._descriptor.subresponseField); + } + let task = this._tasks[bundleId]; + callback.id = String(this._invocationId++); + this._invocations[callback.id] = bundleId; + const bundledField = request[this._descriptor.bundledField]; + const elementCount = bundledField.length; + let requestBytes = 0; + // eslint-disable-next-line @typescript-eslint/no-this-alias + const self = this; + bundledField.forEach(obj => { + requestBytes += this._descriptor.byteLengthFunction(obj); + }); + const countLimit = this._options.elementCountLimit || 0; + const byteLimit = this._options.requestByteLimit || 0; + if ((countLimit > 0 && elementCount > countLimit) || + (byteLimit > 0 && requestBytes >= byteLimit)) { + let message; + if (countLimit > 0 && elementCount > countLimit) { + message = + 'The number of elements ' + + elementCount + + ' exceeds the limit ' + + this._options.elementCountLimit; + } + else { + message = + 'The required bytes ' + + requestBytes + + ' exceeds the limit ' + + this._options.requestByteLimit; + } + const error = new googleError_1.GoogleError(message); + error.code = status_1.Status.INVALID_ARGUMENT; + callback(error); + return { + cancel: noop, + }; + } + const existingCount = task.getElementCount(); + const existingBytes = task.getRequestByteSize(); + if ((countLimit > 0 && elementCount + existingCount >= countLimit) || + (byteLimit > 0 && requestBytes + existingBytes >= byteLimit)) { + this._runNow(bundleId); + this._tasks[bundleId] = new task_1.Task(apiCall, request, this._descriptor.bundledField, this._descriptor.subresponseField); + task = this._tasks[bundleId]; + } + task.extend(bundledField, requestBytes, callback); + const ret = { + cancel() { + self._cancel(callback.id); + }, + }; + const countThreshold = this._options.elementCountThreshold || 0; + const sizeThreshold = this._options.requestByteThreshold || 0; + if ((countThreshold > 0 && task.getElementCount() >= countThreshold) || + (sizeThreshold > 0 && task.getRequestByteSize() >= sizeThreshold)) { + this._runNow(bundleId); + return ret; + } + if (!(bundleId in this._timers) && this._options.delayThreshold > 0) { + this._timers[bundleId] = setTimeout(() => { + delete this._timers[bundleId]; + this._runNow(bundleId); + }, this._options.delayThreshold); + } + return ret; + } + /** + * Clears scheduled timeout if it exists. + * + * @param {String} bundleId - the id for the task whose timeout needs to be + * cleared. + * @private + */ + _maybeClearTimeout(bundleId) { + if (bundleId in this._timers) { + const timerId = this._timers[bundleId]; + delete this._timers[bundleId]; + clearTimeout(timerId); + } + } + /** + * Cancels an event. + * + * @param {String} id - The id for the event in the task. + * @private + */ + _cancel(id) { + if (!(id in this._invocations)) { + return; + } + const bundleId = this._invocations[id]; + if (!(bundleId in this._tasks)) { + return; + } + const task = this._tasks[bundleId]; + delete this._invocations[id]; + if (task.cancel(id)) { + this._maybeClearTimeout(bundleId); + delete this._tasks[bundleId]; + } + } + /** + * Invokes a task. + * + * @param {String} bundleId - The id for the task. + * @private + */ + _runNow(bundleId) { + if (!(bundleId in this._tasks)) { + (0, warnings_1.warn)('bundle_runnow_bundleid_unknown', `No such bundleid: ${bundleId}`); + return; + } + this._maybeClearTimeout(bundleId); + const task = this._tasks[bundleId]; + delete this._tasks[bundleId]; + task.run().forEach(id => { + delete this._invocations[id]; + }); + } +} +exports.BundleExecutor = BundleExecutor; +//# sourceMappingURL=bundleExecutor.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/bundlingCalls/bundleExecutor.js.map b/node_modules/google-gax/build/src/bundlingCalls/bundleExecutor.js.map new file mode 100644 index 0000000..b214acb --- /dev/null +++ b/node_modules/google-gax/build/src/bundlingCalls/bundleExecutor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bundleExecutor.js","sourceRoot":"","sources":["../../../src/bundlingCalls/bundleExecutor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,sCAAiC;AAGjC,gDAA2C;AAC3C,0CAAiC;AAGjC,mDAAgD;AAChD,iCAA0C;AAE1C,SAAS,IAAI,KAAI,CAAC;AAsClB;;;;;;GAMG;AACH,MAAa,cAAc;IAOzB;;;;;;;OAOG;IACH,YACE,aAA4B,EAC5B,gBAAkC;QAElC,IAAI,CAAC,QAAQ,GAAG,aAAa,CAAC;QAC9B,IAAI,CAAC,WAAW,GAAG,gBAAgB,CAAC;QACpC,IAAI,CAAC,MAAM,GAAG,EAAE,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;QAClB,IAAI,CAAC,YAAY,GAAG,EAAE,CAAC;QACvB,IAAI,CAAC,aAAa,GAAG,CAAC,CAAC;IACzB,CAAC;IAED;;;;;;;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,CAAC,CAAC;QAC/B,CAAC;IACH,CAAC;IAED;;;;;OAKG;IACH,OAAO,CAAC,QAAgB;QACtB,IAAI,CAAC,CAAC,QAAQ,IAAI,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;YAC/B,IAAA,eAAI,EAAC,gCAAgC,EAAE,qBAAqB,QAAQ,EAAE,CAAC,CAAC;YACxE,OAAO;QACT,CAAC;QACD,IAAI,CAAC,kBAAkB,CAAC,QAAQ,CAAC,CAAC;QAClC,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QACnC,OAAO,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QAE7B,IAAI,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE;YACtB,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,CAAC,CAAC;QAC/B,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAtND,wCAsNC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/bundlingCalls/bundlingUtils.d.ts b/node_modules/google-gax/build/src/bundlingCalls/bundlingUtils.d.ts new file mode 100644 index 0000000..2948e8a --- /dev/null +++ b/node_modules/google-gax/build/src/bundlingCalls/bundlingUtils.d.ts @@ -0,0 +1,31 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides behavior that supports request bundling. + */ +import { RequestType } from '../apitypes'; +/** + * Compute the identifier of the `obj`. The objects of the same ID + * will be bundled together. + * + * @param {RequestType} obj - The request object. + * @param {String[]} discriminatorFields - The array of field names. + * A field name may include '.' as a separator, which is used to + * indicate object traversal. + * @return {String|undefined} - the identifier string, or undefined if any + * discriminator fields do not exist. + */ +export declare function computeBundleId(obj: RequestType, discriminatorFields: string[]): string | undefined; diff --git a/node_modules/google-gax/build/src/bundlingCalls/bundlingUtils.js b/node_modules/google-gax/build/src/bundlingCalls/bundlingUtils.js new file mode 100644 index 0000000..3db3601 --- /dev/null +++ b/node_modules/google-gax/build/src/bundlingCalls/bundlingUtils.js @@ -0,0 +1,72 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.computeBundleId = computeBundleId; +/** + * Compute the identifier of the `obj`. The objects of the same ID + * will be bundled together. + * + * @param {RequestType} obj - The request object. + * @param {String[]} discriminatorFields - The array of field names. + * A field name may include '.' as a separator, which is used to + * indicate object traversal. + * @return {String|undefined} - the identifier string, or undefined if any + * discriminator fields do not exist. + */ +function computeBundleId(obj, discriminatorFields) { + const ids = []; + let hasIds = false; + for (const field of discriminatorFields) { + const id = at(obj, field); + if (id === undefined) { + ids.push(null); + } + else { + hasIds = true; + ids.push(id); + } + } + if (!hasIds) { + return undefined; + } + return JSON.stringify(ids); +} +/** + * Given an object field path that may contain dots, dig into the obj and find + * the value at the given path. + * @example + * const obj = { + * a: { + * b: 5 + * } + * } + * const id = at(obj, 'a.b'); + * // id = 5 + * @param field Path to the property with `.` notation + * @param obj The object to traverse + * @returns the value at the given path + */ +function at(obj, field) { + const pathParts = field.split('.'); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let currentObj = obj; + for (const pathPart of pathParts) { + currentObj = currentObj === null || currentObj === void 0 ? void 0 : currentObj[pathPart]; + } + return currentObj; +} +//# sourceMappingURL=bundlingUtils.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/bundlingCalls/bundlingUtils.js.map b/node_modules/google-gax/build/src/bundlingCalls/bundlingUtils.js.map new file mode 100644 index 0000000..2bfc3c9 --- /dev/null +++ b/node_modules/google-gax/build/src/bundlingCalls/bundlingUtils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bundlingUtils.js","sourceRoot":"","sources":["../../../src/bundlingCalls/bundlingUtils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAmBH,0CAmBC;AA9BD;;;;;;;;;;GAUG;AACH,SAAgB,eAAe,CAC7B,GAAgB,EAChB,mBAA6B;IAE7B,MAAM,GAAG,GAAc,EAAE,CAAC;IAC1B,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,KAAK,MAAM,KAAK,IAAI,mBAAmB,EAAE,CAAC;QACxC,MAAM,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC1B,IAAI,EAAE,KAAK,SAAS,EAAE,CAAC;YACrB,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACjB,CAAC;aAAM,CAAC;YACN,MAAM,GAAG,IAAI,CAAC;YACd,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACf,CAAC;IACH,CAAC;IACD,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,SAAS,EAAE,CAAC,GAAO,EAAE,KAAa;IAChC,MAAM,SAAS,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnC,8DAA8D;IAC9D,IAAI,UAAU,GAAQ,GAAG,CAAC;IAC1B,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;QACjC,UAAU,GAAG,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAG,QAAQ,CAAC,CAAC;IACtC,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/bundlingCalls/task.d.ts b/node_modules/google-gax/build/src/bundlingCalls/task.d.ts new file mode 100644 index 0000000..6d528b5 --- /dev/null +++ b/node_modules/google-gax/build/src/bundlingCalls/task.d.ts @@ -0,0 +1,98 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { APICallback, GRPCCallResult, SimpleCallbackFunction } from '../apitypes'; +export interface SubResponseInfo { + field: string; + start?: number; + end?: number; +} +export interface TaskData { + elements: {}[]; + bytes: number; + callback: TaskCallback; + cancelled?: boolean; +} +export interface TaskCallback extends APICallback { + id?: string; +} +/** + * Creates a deep copy of the object with the consideration of subresponse + * fields for bundling. + * + * @param {Object} obj - The source object. + * @param {Object?} subresponseInfo - The information to copy the subset of + * the field for the response. Do nothing if it's null. + * @param {String} subresponseInfo.field - The field name. + * @param {number} subresponseInfo.start - The offset where the copying + * element should starts with. + * @param {number} subresponseInfo.end - The ending index where the copying + * region of the elements ends. + * @return {Object} The copied object. + * @private + */ +export declare function deepCopyForResponse(obj: any, subresponseInfo: SubResponseInfo | null): any; +export declare class Task { + _apiCall: SimpleCallbackFunction; + _request: { + [index: string]: {}[]; + }; + _bundledField: string; + _subresponseField?: string | null; + _data: TaskData[]; + callCanceller?: GRPCCallResult; + /** + * A task coordinates the execution of a single bundle. + * + * @param {function} apiCall - The function to conduct calling API. + * @param {Object} bundlingRequest - The base request object to be used + * for the actual API call. + * @param {string} bundledField - The name of the field in bundlingRequest + * to be bundled. + * @param {string=} subresponseField - The name of the field in the response + * to be passed to the callback. + * @constructor + * @private + */ + constructor(apiCall: SimpleCallbackFunction, bundlingRequest: {}, bundledField: string, subresponseField?: string | null); + /** + * Returns the number of elements in a task. + * @return {number} The number of elements. + */ + getElementCount(): number; + /** + * Returns the total byte size of the elements in a task. + * @return {number} The byte size. + */ + getRequestByteSize(): number; + /** + * Invokes the actual API call with current elements. + * @return {string[]} - the list of ids for invocations to be run. + */ + run(): string[]; + /** + * Appends the list of elements into the task. + * @param {Object[]} elements - the new list of elements. + * @param {number} bytes - the byte size required to encode elements in the API. + * @param {APICallback} callback - the callback of the method call. + */ + extend(elements: {}[], bytes: number, callback: TaskCallback): void; + /** + * Cancels a part of elements. + * @param {string} id - The identifier of the part of elements. + * @return {boolean} Whether the entire task will be canceled or not. + */ + cancel(id: string): boolean; +} diff --git a/node_modules/google-gax/build/src/bundlingCalls/task.js b/node_modules/google-gax/build/src/bundlingCalls/task.js new file mode 100644 index 0000000..40e6d5d --- /dev/null +++ b/node_modules/google-gax/build/src/bundlingCalls/task.js @@ -0,0 +1,228 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Task = void 0; +exports.deepCopyForResponse = deepCopyForResponse; +const status_1 = require("../status"); +const googleError_1 = require("../googleError"); +/** + * Creates a deep copy of the object with the consideration of subresponse + * fields for bundling. + * + * @param {Object} obj - The source object. + * @param {Object?} subresponseInfo - The information to copy the subset of + * the field for the response. Do nothing if it's null. + * @param {String} subresponseInfo.field - The field name. + * @param {number} subresponseInfo.start - The offset where the copying + * element should starts with. + * @param {number} subresponseInfo.end - The ending index where the copying + * region of the elements ends. + * @return {Object} The copied object. + * @private + */ +function deepCopyForResponse( +// eslint-disable-next-line @typescript-eslint/no-explicit-any +obj, subresponseInfo) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let result; + if (obj === null) { + return null; + } + if (obj === undefined) { + return undefined; + } + if (Array.isArray(obj)) { + result = []; + obj.forEach(element => { + result.push(deepCopyForResponse(element, null)); + }); + return result; + } + // Some objects (such as ByteBuffer) have copy method. + if (obj.copy !== undefined) { + return obj.copy(); + } + // ArrayBuffer should be copied through slice(). + if (obj instanceof ArrayBuffer) { + return obj.slice(0); + } + if (typeof obj === 'object') { + result = {}; + Object.keys(obj).forEach(key => { + if (subresponseInfo && + key === subresponseInfo.field && + Array.isArray(obj[key])) { + // Note that subresponses are not deep-copied. This is safe because + // those subresponses are not shared among callbacks. + result[key] = obj[key].slice(subresponseInfo.start, subresponseInfo.end); + } + else { + result[key] = deepCopyForResponse(obj[key], null); + } + }); + return result; + } + return obj; +} +class Task { + /** + * A task coordinates the execution of a single bundle. + * + * @param {function} apiCall - The function to conduct calling API. + * @param {Object} bundlingRequest - The base request object to be used + * for the actual API call. + * @param {string} bundledField - The name of the field in bundlingRequest + * to be bundled. + * @param {string=} subresponseField - The name of the field in the response + * to be passed to the callback. + * @constructor + * @private + */ + constructor(apiCall, bundlingRequest, bundledField, subresponseField) { + this._apiCall = apiCall; + this._request = bundlingRequest; + this._bundledField = bundledField; + this._subresponseField = subresponseField; + this._data = []; + } + /** + * Returns the number of elements in a task. + * @return {number} The number of elements. + */ + getElementCount() { + let count = 0; + for (let i = 0; i < this._data.length; ++i) { + count += this._data[i].elements.length; + } + return count; + } + /** + * Returns the total byte size of the elements in a task. + * @return {number} The byte size. + */ + getRequestByteSize() { + let size = 0; + for (let i = 0; i < this._data.length; ++i) { + size += this._data[i].bytes; + } + return size; + } + /** + * Invokes the actual API call with current elements. + * @return {string[]} - the list of ids for invocations to be run. + */ + run() { + if (this._data.length === 0) { + return []; + } + const request = this._request; + const elements = []; + const ids = []; + for (let i = 0; i < this._data.length; ++i) { + elements.push(...this._data[i].elements); + ids.push(this._data[i].callback.id); + } + request[this._bundledField] = elements; + // eslint-disable-next-line @typescript-eslint/no-this-alias + const self = this; + this.callCanceller = this._apiCall(request, (err, response) => { + const responses = []; + if (err) { + self._data.forEach(() => { + responses.push(undefined); + }); + } + else { + let subresponseInfo = null; + if (self._subresponseField) { + subresponseInfo = { + field: self._subresponseField, + start: 0, + }; + } + self._data.forEach(data => { + if (subresponseInfo) { + subresponseInfo.end = + subresponseInfo.start + data.elements.length; + } + responses.push(deepCopyForResponse(response, subresponseInfo)); + if (subresponseInfo) { + subresponseInfo.start = subresponseInfo.end; + } + }); + } + for (let i = 0; i < self._data.length; ++i) { + if (self._data[i].cancelled) { + const error = new googleError_1.GoogleError('cancelled'); + error.code = status_1.Status.CANCELLED; + self._data[i].callback(error); + } + else { + self._data[i].callback(err, responses[i]); + } + } + }); + return ids; + } + /** + * Appends the list of elements into the task. + * @param {Object[]} elements - the new list of elements. + * @param {number} bytes - the byte size required to encode elements in the API. + * @param {APICallback} callback - the callback of the method call. + */ + extend(elements, bytes, callback) { + this._data.push({ + elements, + bytes, + callback, + }); + } + /** + * Cancels a part of elements. + * @param {string} id - The identifier of the part of elements. + * @return {boolean} Whether the entire task will be canceled or not. + */ + cancel(id) { + if (this.callCanceller) { + let allCancelled = true; + this._data.forEach(d => { + if (d.callback.id === id) { + d.cancelled = true; + } + if (!d.cancelled) { + allCancelled = false; + } + }); + if (allCancelled) { + this.callCanceller.cancel(); + } + return allCancelled; + } + for (let i = 0; i < this._data.length; ++i) { + if (this._data[i].callback.id === id) { + const error = new googleError_1.GoogleError('cancelled'); + error.code = status_1.Status.CANCELLED; + this._data[i].callback(error); + this._data.splice(i, 1); + break; + } + } + return this._data.length === 0; + } +} +exports.Task = Task; +//# sourceMappingURL=task.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/bundlingCalls/task.js.map b/node_modules/google-gax/build/src/bundlingCalls/task.js.map new file mode 100644 index 0000000..dac0841 --- /dev/null +++ b/node_modules/google-gax/build/src/bundlingCalls/task.js.map @@ -0,0 +1 @@ +{"version":3,"file":"task.js","sourceRoot":"","sources":["../../../src/bundlingCalls/task.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAuCH,kDAiDC;AAtFD,sCAAiC;AAGjC,gDAA2C;AAmB3C;;;;;;;;;;;;;;GAcG;AACH,SAAgB,mBAAmB;AACjC,8DAA8D;AAC9D,GAAQ,EACR,eAAuC;IAEvC,8DAA8D;IAC9D,IAAI,MAAW,CAAC;IAChB,IAAI,GAAG,KAAK,IAAI,EAAE,CAAC;QACjB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;QACtB,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QACvB,MAAM,GAAG,EAAE,CAAC;QACZ,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;YACpB,MAAM,CAAC,IAAI,CAAC,mBAAmB,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC;QAClD,CAAC,CAAC,CAAC;QACH,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,sDAAsD;IACtD,IAAI,GAAG,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;QAC3B,OAAO,GAAG,CAAC,IAAI,EAAE,CAAC;IACpB,CAAC;IACD,gDAAgD;IAChD,IAAI,GAAG,YAAY,WAAW,EAAE,CAAC;QAC/B,OAAQ,GAAmB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACvC,CAAC;IACD,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;QAC5B,MAAM,GAAG,EAAE,CAAC;QACZ,MAAM,CA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C,EAAE,CAAC,CAAC,CAAC;gBACxB,MAAM;YACR,CAAC;QACH,CAAC;QACD,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC;IACjC,CAAC;CACF;AA7JD,oBA6JC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/call.d.ts b/node_modules/google-gax/build/src/call.d.ts new file mode 100644 index 0000000..b8cba00 --- /dev/null +++ b/node_modules/google-gax/build/src/call.d.ts @@ -0,0 +1,60 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { APICallback, RequestType, ResultTuple, SimpleCallbackFunction } from './apitypes'; +export declare class OngoingCall { + callback: APICallback; + cancelFunc?: () => void; + completed: boolean; + /** + * OngoingCall manages callback, API calls, and cancellation + * of the API calls. + * @param {APICallback=} callback + * The callback to be called asynchronously when the API call + * finishes. + * @constructor + * @property {APICallback} callback + * The callback function to be called. + * @private + */ + constructor(callback: APICallback); + /** + * Cancels the ongoing promise. + */ + cancel(): void; + /** + * Call calls the specified function. Result will be used to fulfill + * the promise. + * + * @param {SimpleCallbackFunction} func + * A function for an API call. + * @param {Object} argument + * A request object. + */ + call(func: SimpleCallbackFunction, argument: RequestType): void; +} +export interface CancellablePromise extends Promise { + cancel(): void; +} +export declare class OngoingCallPromise extends OngoingCall { + promise: CancellablePromise; + /** + * GaxPromise is GRPCCallbackWrapper, but it holds a promise when + * the API call finishes. + * @constructor + * @private + */ + constructor(); +} diff --git a/node_modules/google-gax/build/src/call.js b/node_modules/google-gax/build/src/call.js new file mode 100644 index 0000000..255367c --- /dev/null +++ b/node_modules/google-gax/build/src/call.js @@ -0,0 +1,119 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OngoingCallPromise = exports.OngoingCall = void 0; +const status_1 = require("./status"); +const googleError_1 = require("./googleError"); +class OngoingCall { + /** + * OngoingCall manages callback, API calls, and cancellation + * of the API calls. + * @param {APICallback=} callback + * The callback to be called asynchronously when the API call + * finishes. + * @constructor + * @property {APICallback} callback + * The callback function to be called. + * @private + */ + constructor(callback) { + this.callback = callback; + this.completed = false; + } + /** + * Cancels the ongoing promise. + */ + cancel() { + if (this.completed) { + return; + } + this.completed = true; + if (this.cancelFunc) { + this.cancelFunc(); + } + else { + const error = new googleError_1.GoogleError('cancelled'); + error.code = status_1.Status.CANCELLED; + this.callback(error); + } + } + /** + * Call calls the specified function. Result will be used to fulfill + * the promise. + * + * @param {SimpleCallbackFunction} func + * A function for an API call. + * @param {Object} argument + * A request object. + */ + call(func, argument) { + if (this.completed) { + return; + } + const canceller = func(argument, (err, response, next, rawResponse) => { + this.completed = true; + setImmediate(this.callback, err, response, next, rawResponse); + }); + if (canceller instanceof Promise) { + canceller.catch(err => { + setImmediate(this.callback, new googleError_1.GoogleError(err), null, null, null); + }); + } + this.cancelFunc = () => canceller.cancel(); + } +} +exports.OngoingCall = OngoingCall; +class OngoingCallPromise extends OngoingCall { + /** + * GaxPromise is GRPCCallbackWrapper, but it holds a promise when + * the API call finishes. + * @constructor + * @private + */ + constructor() { + let resolveCallback; + let rejectCallback; + const callback = (err, response, next, rawResponse) => { + if (err) { + // If gRPC metadata exist, parsed google.rpc.status details. + if (err.metadata) { + rejectCallback(googleError_1.GoogleError.parseGRPCStatusDetails(err)); + } + else { + rejectCallback(err); + } + } + else if (response !== undefined) { + resolveCallback([response, next || null, rawResponse || null]); + } + else { + throw new googleError_1.GoogleError('Neither error nor response are defined'); + } + }; + const promise = new Promise((resolve, reject) => { + resolveCallback = resolve; + rejectCallback = reject; + }); + super(callback); + this.promise = promise; + this.promise.cancel = () => { + this.cancel(); + }; + } +} +exports.OngoingCallPromise = OngoingCallPromise; +//# sourceMappingURL=call.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/call.js.map b/node_modules/google-gax/build/src/call.js.map new file mode 100644 index 0000000..4cff9af --- /dev/null +++ b/node_modules/google-gax/build/src/call.js.map @@ -0,0 +1 @@ +{"version":3,"file":"call.js","sourceRoot":"","sources":["../../src/call.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,qCAAgC;AAWhC,+CAA0C;AAE1C,MAAa,WAAW;IAKtB;;;;;;;;;;OAUG;IACH,YAAY,QAAqB;QAC/B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;IACzB,CAAC;IAED;;OAEG;IACH,MAAM;QACJ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACnB,OAAO;QACT,CAAC;QACD,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACpB,IAAI,CAAC,UAAU,EAAE,CAAC;QACpB,CAAC;aAAM,CAAC;YACN,MAAM,KAAK,GAAG,IAAI,yBAAW,CAAC,WAAW,CAAC,CAAC;YAC3C,KAAK,CAAC,IAAI,GAAG,eAAM,CAAC,SAAS,CAAC;YAC9B,IAAI,CAAC,QAAS,CAAC,KAAK,CAAC,CAAC;QACxB,CAAC;IACH,CAAC;IAED;;;;;;;;OAQG;IACH,IAAI,CAAC,IAA4B,EAAE,QAAqB;QACtD,IAAI,IAAI,CAAC,SAA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,IAAI,CAAC,CAAC,CAAC;YACjE,CAAC;iBAAM,CAAC;gBACN,MAAM,IAAI,yBAAW,CAAC,wCAAwC,CAAC,CAAC;YAClE,CAAC;QACH,CAAC,CAAC;QACF,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAC9C,eAAe,GAAG,OAAO,CAAC;YAC1B,cAAc,GAAG,MAAM,CAAC;QAC1B,CAAC,CAAoC,CAAC;QACtC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAChB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,GAAG,EAAE;YACzB,IAAI,CAAC,MAAM,EAAE,CAAC;QAChB,CAAC,CAAC;IACJ,CAAC;CACF;AA1CD,gDA0CC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/clientInterface.d.ts b/node_modules/google-gax/build/src/clientInterface.d.ts new file mode 100644 index 0000000..bb03cc6 --- /dev/null +++ b/node_modules/google-gax/build/src/clientInterface.d.ts @@ -0,0 +1,48 @@ +import { GrpcClientOptions, ClientStubOptions } from './grpc'; +import * as gax from './gax'; +import { GoogleAuthOptions } from 'google-auth-library'; +import { BundleDescriptor, LongrunningDescriptor, PageDescriptor, StreamDescriptor } from './descriptor'; +import * as longrunning from './longRunningCalls/longrunning'; +import * as operationProtos from '../protos/operations'; +export interface ClientOptions extends GrpcClientOptions, GoogleAuthOptions, ClientStubOptions { + libName?: string; + libVersion?: string; + clientConfig?: gax.ClientConfig; + fallback?: boolean | 'rest' | 'proto'; + apiEndpoint?: string; + gaxServerStreamingRetries?: boolean; + universeDomain?: string; + universe_domain?: string; +} +export interface Descriptors { + page: { + [name: string]: PageDescriptor; + }; + stream: { + [name: string]: StreamDescriptor; + }; + longrunning: { + [name: string]: LongrunningDescriptor; + }; + batching?: { + [name: string]: BundleDescriptor; + }; +} +export interface Callback { + (err: Error | null | undefined, value?: ResponseObject | null, nextRequest?: NextRequestObject, rawResponse?: RawResponseObject): void; +} +export interface LROperation extends longrunning.Operation { + promise(): Promise<[ + ResultType, + MetadataType, + operationProtos.google.longrunning.Operation + ]>; +} +export interface PaginationCallback { + (err: Error | null, values?: ResponseType[], nextPageRequest?: RequestObject, rawResponse?: ResponseObject): void; +} +export interface PaginationResponse { + values?: ResponseType[]; + nextPageRequest?: RequestObject; + rawResponse?: ResponseObject; +} diff --git a/node_modules/google-gax/build/src/clientInterface.js b/node_modules/google-gax/build/src/clientInterface.js new file mode 100644 index 0000000..e7b1361 --- /dev/null +++ b/node_modules/google-gax/build/src/clientInterface.js @@ -0,0 +1,20 @@ +"use strict"; +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=clientInterface.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/clientInterface.js.map b/node_modules/google-gax/build/src/clientInterface.js.map new file mode 100644 index 0000000..34b08fb --- /dev/null +++ b/node_modules/google-gax/build/src/clientInterface.js.map @@ -0,0 +1 @@ +{"version":3,"file":"clientInterface.js","sourceRoot":"","sources":["../../src/clientInterface.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AACjC,EAAE;AACF,4EAA4E;AAC5E,iEAAiE;AACjE,qDAAqD"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/createApiCall.d.ts b/node_modules/google-gax/build/src/createApiCall.d.ts new file mode 100644 index 0000000..08978cb --- /dev/null +++ b/node_modules/google-gax/build/src/createApiCall.d.ts @@ -0,0 +1,38 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { GaxCall, GRPCCall } from './apitypes'; +import { Descriptor } from './descriptor'; +import { CallSettings } from './gax'; +/** + * Converts an rpc call into an API call governed by the settings. + * + * In typical usage, `func` will be a promise to a callable used to make an rpc + * request. This will mostly likely be a bound method from a request stub used + * to make an rpc call. It is not a direct function but a Promise instance, + * because of its asynchronism (typically, obtaining the auth information). + * + * The result is a function which manages the API call with the given settings + * and the options on the invocation. + * + * @param {Promise|GRPCCall} func - is either a promise to be used to make + * a bare RPC call, or just a bare RPC call. + * @param {CallSettings} settings - provides the settings for this call + * @param {Descriptor} descriptor - optionally specify the descriptor for + * the method call. + * @return {GaxCall} func - a bound method on a request stub used + * to make an rpc call. + */ +export declare function createApiCall(func: Promise | GRPCCall, settings: CallSettings, descriptor?: Descriptor, _fallback?: boolean | 'proto' | 'rest'): GaxCall; diff --git a/node_modules/google-gax/build/src/createApiCall.js b/node_modules/google-gax/build/src/createApiCall.js new file mode 100644 index 0000000..753c9ae --- /dev/null +++ b/node_modules/google-gax/build/src/createApiCall.js @@ -0,0 +1,122 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createApiCall = createApiCall; +/** + * Provides function wrappers that implement page streaming and retrying. + */ +const apiCaller_1 = require("./apiCaller"); +const gax_1 = require("./gax"); +const retries_1 = require("./normalCalls/retries"); +const timeout_1 = require("./normalCalls/timeout"); +const streamingApiCaller_1 = require("./streamingCalls/streamingApiCaller"); +const warnings_1 = require("./warnings"); +/** + * Converts an rpc call into an API call governed by the settings. + * + * In typical usage, `func` will be a promise to a callable used to make an rpc + * request. This will mostly likely be a bound method from a request stub used + * to make an rpc call. It is not a direct function but a Promise instance, + * because of its asynchronism (typically, obtaining the auth information). + * + * The result is a function which manages the API call with the given settings + * and the options on the invocation. + * + * @param {Promise|GRPCCall} func - is either a promise to be used to make + * a bare RPC call, or just a bare RPC call. + * @param {CallSettings} settings - provides the settings for this call + * @param {Descriptor} descriptor - optionally specify the descriptor for + * the method call. + * @return {GaxCall} func - a bound method on a request stub used + * to make an rpc call. + */ +function createApiCall(func, settings, descriptor, +// eslint-disable-next-line @typescript-eslint/no-unused-vars +_fallback // unused here, used in fallback.ts implementation +) { + // we want to be able to accept both promise resolving to a function and a + // function. Currently client librares are only calling this method with a + // promise, but it will change. + const funcPromise = typeof func === 'function' ? Promise.resolve(func) : func; + // the following apiCaller will be used for all calls of this function... + const apiCaller = (0, apiCaller_1.createAPICaller)(settings, descriptor); + return (request, callOptions, callback) => { + var _a, _b; + let currentApiCaller = apiCaller; + let thisSettings; + if (currentApiCaller instanceof streamingApiCaller_1.StreamingApiCaller) { + const gaxStreamingRetries = (_b = (_a = currentApiCaller.descriptor) === null || _a === void 0 ? void 0 : _a.gaxStreamingRetries) !== null && _b !== void 0 ? _b : false; + // If Gax streaming retries are enabled, check settings passed at call time and convert parameters if needed + const convertedRetryOptions = (0, gax_1.convertRetryOptions)(callOptions, gaxStreamingRetries); + thisSettings = settings.merge(convertedRetryOptions); + } + else { + thisSettings = settings.merge(callOptions); + } + // special case: if bundling is disabled for this one call, + // use default API caller instead + if (settings.isBundling && !thisSettings.isBundling) { + currentApiCaller = (0, apiCaller_1.createAPICaller)(settings, undefined); + } + const ongoingCall = currentApiCaller.init(callback); + funcPromise + .then((func) => { + var _a, _b; + var _c; + // Initially, the function is just what gRPC server stub contains. + func = currentApiCaller.wrap(func); + const streaming = (_a = currentApiCaller.descriptor) === null || _a === void 0 ? void 0 : _a.streaming; + const retry = thisSettings.retry; + if (streaming && retry) { + if (retry.retryCodes.length > 0 && retry.shouldRetryFn) { + (0, warnings_1.warn)('either_retrycodes_or_shouldretryfn', 'Only one of retryCodes or shouldRetryFn may be defined. Ignoring retryCodes.'); + retry.retryCodes = []; + } + if (!currentApiCaller.descriptor + .gaxStreamingRetries && + retry.getResumptionRequestFn) { + throw new Error('getResumptionRequestFn can only be used when gaxStreamingRetries is set to true.'); + } + } + if (!streaming && retry) { + if (retry.shouldRetryFn) { + throw new Error('Using a function to determine retry eligibility is only supported with server streaming calls'); + } + if (retry.getResumptionRequestFn) { + throw new Error('Resumption strategy can only be used with server streaming retries'); + } + if (retry.retryCodes && retry.retryCodes.length > 0) { + (_b = (_c = retry.backoffSettings).initialRpcTimeoutMillis) !== null && _b !== void 0 ? _b : (_c.initialRpcTimeoutMillis = thisSettings.timeout); + return (0, retries_1.retryable)(func, thisSettings.retry, thisSettings.otherArgs, thisSettings.apiName); + } + } + return (0, timeout_1.addTimeoutArg)(func, thisSettings.timeout, thisSettings.otherArgs); + }) + .then((apiCall) => { + // After adding retries / timeouts, the call function becomes simpler: + // it only accepts request and callback. + currentApiCaller.call(apiCall, request, thisSettings, ongoingCall); + }) + .catch(err => { + currentApiCaller.fail(ongoingCall, err); + }); + // Calls normally return a "cancellable promise" that can be used to `await` for the actual result, + // or to cancel the ongoing call. + return currentApiCaller.result(ongoingCall); + }; +} +//# sourceMappingURL=createApiCall.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/createApiCall.js.map b/node_modules/google-gax/build/src/createApiCall.js.map new file mode 100644 index 0000000..723fec0 --- /dev/null +++ b/node_modules/google-gax/build/src/createApiCall.js.map @@ -0,0 +1 @@ +{"version":3,"file":"createApiCall.js","sourceRoot":"","sources":["../../src/createApiCall.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAyCH,sCA+GC;AAtJD;;GAEG;AAEH,2CAA4C;AAU5C,+BAAqE;AACrE,mDAAgD;AAChD,mDAAoD;AACpD,4EAAuE;AACvE,yCAAgC;AAEhC;;;;;;;;;;;;;;;;;;GAkBG;AACH,SAAgB,aAAa,CAC3B,IAAkC,EAClC,QAAsB,EACtB,UAAuB;AACvB,6DAA6D;AAC7D,SAAsC,CAAC,kDAAkD;;IAEzF,0EAA0E;IAC1E,0EAA0E;IAC1E,+BAA+B;IAC/B,MAAM,WAAW,GAAG,OAAO,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IAC9E,yEAAyE;IACzE,MAAM,SAAS,GAAG,IAAA,2BAAe,EAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;IAExD,OAAO,CACL,OAAoB,EACpB,WAAyB,EACzB,QAAsB,EACtB,EAAE;;QACF,IAAI,gBAAgB,GAAG,SAAS,CAAC;QAEjC,IAAI,YAA0B,CAAC;QAC/B,IAAI,gBAAgB,YAAY,uCAAkB,EAAE,CAAC;YACnD,MAAM,mBAAmB,GACvB,MAAA,MAAA,gBAAgB,CAAC,UAAU,0CAAE,mBAAmB,mCAAI,KAAK,CAAC;YAC5D,4GAA4G;YAC5G,MAAM,qBAAqB,GAAG,IAAA,yBAAmB,EAC/C,WAAW,EACX,mBAAmB,CACpB,CAAC;YACF,YAAY,GAAG,QAAQ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,CAAC,sBAAsB,EAAE,CAAC;oBACjC,MAAM,IAAI,KAAK,CACb,oEAAoE,CACrE,CAAC;gBACJ,CAAC;gBACD,IAAI,KAAK,CAAC,UAAU,IAAI,KAAK,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;oBACpD,YAAA,KAAK,CAAC,eAAe,EAAC,uBAAuB,uCAAvB,uBAAuB,GAC3C,YAAY,CAAC,OAAO,EAAC;oBACvB,OAAO,IAAA,mBAAS,EACd,IAAI,EACJ,YAAY,CAAC,KAAM,EACnB,YAAY,CAAC,SAA8B,EAC3C,YAAY,CAAC,OAAO,CACrB,CAAC;gBACJ,CAAC;YACH,CAAC;YACD,OAAO,IAAA,uBAAa,EAClB,IAAI,EACJ,YAAY,CAAC,OAAO,EACpB,YAAY,CAAC,SAA8B,CAC5C,CAAC;QACJ,CAAC,CAAC;aACD,IAAI,CAAC,CAAC,OAA+B,EAAE,EAAE;YACxC,sEAAsE;YACtE,wCAAwC;YACxC,gBAAgB,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,WAAW,CAAC,CAAC;QACrE,CAAC,CAAC;aACD,KAAK,CAAC,GAAG,CAAC,EAAE;YACX,gBAAgB,CAAC,IAAI,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC;QAC1C,CAAC,CAAC,CAAC;QAEL,mGAAmG;QACnG,iCAAiC;QACjC,OAAO,gBAAgB,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IAC9C,CAAC,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/descriptor.d.ts b/node_modules/google-gax/build/src/descriptor.d.ts new file mode 100644 index 0000000..8942d0f --- /dev/null +++ b/node_modules/google-gax/build/src/descriptor.d.ts @@ -0,0 +1,24 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { APICaller } from './apiCaller'; +import { CallSettings } from './gax'; +export interface Descriptor { + getApiCaller(settings: CallSettings): APICaller; +} +export { LongRunningDescriptor as LongrunningDescriptor } from './longRunningCalls/longRunningDescriptor'; +export { PageDescriptor } from './paginationCalls/pageDescriptor'; +export { StreamDescriptor } from './streamingCalls/streamDescriptor'; +export { BundleDescriptor } from './bundlingCalls/bundleDescriptor'; diff --git a/node_modules/google-gax/build/src/descriptor.js b/node_modules/google-gax/build/src/descriptor.js new file mode 100644 index 0000000..93a29f6 --- /dev/null +++ b/node_modules/google-gax/build/src/descriptor.js @@ -0,0 +1,27 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BundleDescriptor = exports.StreamDescriptor = exports.PageDescriptor = exports.LongrunningDescriptor = void 0; +var longRunningDescriptor_1 = require("./longRunningCalls/longRunningDescriptor"); +Object.defineProperty(exports, "LongrunningDescriptor", { enumerable: true, get: function () { return longRunningDescriptor_1.LongRunningDescriptor; } }); +var pageDescriptor_1 = require("./paginationCalls/pageDescriptor"); +Object.defineProperty(exports, "PageDescriptor", { enumerable: true, get: function () { return pageDescriptor_1.PageDescriptor; } }); +var streamDescriptor_1 = require("./streamingCalls/streamDescriptor"); +Object.defineProperty(exports, "StreamDescriptor", { enumerable: true, get: function () { return streamDescriptor_1.StreamDescriptor; } }); +var bundleDescriptor_1 = require("./bundlingCalls/bundleDescriptor"); +Object.defineProperty(exports, "BundleDescriptor", { enumerable: true, get: function () { return bundleDescriptor_1.BundleDescriptor; } }); +//# sourceMappingURL=descriptor.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/descriptor.js.map b/node_modules/google-gax/build/src/descriptor.js.map new file mode 100644 index 0000000..1491378 --- /dev/null +++ b/node_modules/google-gax/build/src/descriptor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"descriptor.js","sourceRoot":"","sources":["../../src/descriptor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAeH,kFAAwG;AAAhG,8HAAA,qBAAqB,OAAyB;AACtD,mEAAgE;AAAxD,gHAAA,cAAc,OAAA;AACtB,sEAAmE;AAA3D,oHAAA,gBAAgB,OAAA;AACxB,qEAAkE;AAA1D,oHAAA,gBAAgB,OAAA"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/fallback.d.ts b/node_modules/google-gax/build/src/fallback.d.ts new file mode 100644 index 0000000..9d3053d --- /dev/null +++ b/node_modules/google-gax/build/src/fallback.d.ts @@ -0,0 +1,166 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { OutgoingHttpHeaders } from 'http'; +import * as protobuf from 'protobufjs'; +import * as gax from './gax'; +import * as routingHeader from './routingHeader'; +import { GoogleAuth, OAuth2Client, Compute, JWT, UserRefreshClient, BaseExternalAccountClient } from 'google-auth-library'; +import { OperationsClientBuilder } from './operationsClient'; +import type { GrpcClientOptions, ClientStubOptions } from './grpc'; +import { GaxCall, GRPCCall } from './apitypes'; +import { Descriptor } from './descriptor'; +import { FallbackServiceError } from './googleError'; +import { google } from '../protos/http'; +import * as IamProtos from '../protos/iam_service'; +import * as LocationProtos from '../protos/locations'; +import * as operationsProtos from '../protos/operations'; +export { FallbackServiceError }; +export { PathTemplate } from './pathTemplate'; +export { routingHeader }; +export { CallSettings, constructSettings, RetryOptions, createDefaultBackoffSettings, } from './gax'; +export declare const version: string; +export { BundleDescriptor, LongrunningDescriptor, PageDescriptor, StreamDescriptor, } from './descriptor'; +export { StreamType } from './streamingCalls/streaming'; +export { OperationsClient } from './operationsClient'; +export { IamClient } from './iamService'; +export { LocationsClient } from './locationService'; +export { makeUUID } from './util'; +export declare const defaultToObjectOptions: { + keepCase: boolean; + longs: StringConstructor; + enums: StringConstructor; + defaults: boolean; + oneofs: boolean; +}; +export interface ServiceMethods { + [name: string]: protobuf.Method; +} +export type AuthClient = OAuth2Client | Compute | JWT | UserRefreshClient | BaseExternalAccountClient; +export declare class GrpcClient { + auth?: OAuth2Client | GoogleAuth; + authClient?: AuthClient; + fallback: boolean; + grpcVersion: string; + private static protoCache; + httpRules?: Array; + numericEnums: boolean; + /** + * In rare cases users might need to deallocate all memory consumed by loaded protos. + * This method will delete the proto cache content. + */ + static clearProtoCache(): void; + /** + * gRPC-fallback version of GrpcClient + * Implements GrpcClient API for a browser using grpc-fallback protocol (sends serialized protobuf to HTTP/1 $rpc endpoint). + * + * @param {Object=} options.auth - An instance of OAuth2Client to use in browser, or an instance of GoogleAuth from google-auth-library + * to use in Node.js. Required for browser, optional for Node.js. + * @constructor + */ + constructor(options?: (GrpcClientOptions | { + auth: OAuth2Client; + }) & { + /** + * Fallback mode to use instead of gRPC. + * A string is accepted for compatibility, all non-empty string values enable the HTTP REST fallback. + */ + fallback?: boolean | string; + }); + /** + * gRPC-fallback version of loadProto + * Loads the protobuf root object from a JSON object created from a proto file + * @param {Object} jsonObject - A JSON version of a protofile created usin protobuf.js + * @returns {Object} Root namespace of proto JSON + */ + loadProto(jsonObject: {}): protobuf.Root; + loadProtoJSON(json: protobuf.INamespace, ignoreCache?: boolean): protobuf.Root; + private static getServiceMethods; + /** + * gRPC-fallback version of constructSettings + * A wrapper of {@link constructSettings} function under the gRPC context. + * + * Most of parameters are common among constructSettings, please take a look. + * @param {string} serviceName - The fullly-qualified name of the service. + * @param {Object} clientConfig - A dictionary of the client config. + * @param {Object} configOverrides - A dictionary of overriding configs. + * @param {Object} headers - A dictionary of additional HTTP header name to + * its value. + * @return {Object} A mapping of method names to CallSettings. + */ + constructSettings(serviceName: string, clientConfig: gax.ClientConfig, configOverrides: gax.ClientConfig, headers: OutgoingHttpHeaders): any; + /** + * gRPC-fallback version of createStub + * Creates a gRPC-fallback stub with authentication headers built from supplied OAuth2Client instance + * + * @param {function} CreateStub - The constructor function of the stub. + * @param {Object} service - A protobufjs Service object (as returned by lookupService) + * @param {Object} opts - Connection options, as described below. + * @param {string} opts.servicePath - The hostname of the API endpoint service. + * @param {number} opts.port - The port of the service. + * @return {Promise} A promise which resolves to a gRPC-fallback service stub, which is a protobuf.js service stub instance modified to match the gRPC stub API + */ + createStub(service: protobuf.Service, opts: ClientStubOptions, customServicePath?: boolean): Promise; + /** + * Creates a 'bytelength' function for a given proto message class. + * + * See {@link BundleDescriptor} about the meaning of the return value. + * + * @param {function} message - a constructor function that is generated by + * protobuf.js. Assumes 'encoder' field in the message. + * @return {function(Object):number} - a function to compute the byte length + * for an object. + */ + static createByteLengthFunction(message: typeof protobuf.Message): (obj: {}) => number; +} +/** + * gRPC-fallback version of lro + * + * @param {Object=} options.auth - An instance of google-auth-library. + * @return {Object} A OperationsClientBuilder that will return a OperationsClient + */ +export declare function lro(options: GrpcClientOptions): OperationsClientBuilder; +export { operationsProtos, IamProtos, LocationProtos }; +/** + * gRPC-fallback version of createApiCall + * + * Converts an rpc call into an API call governed by the settings. + * + * In typical usage, `func` will be a promise to a callable used to make an rpc + * request. This will mostly likely be a bound method from a request stub used + * to make an rpc call. It is not a direct function but a Promise instance, + * because of its asynchronism (typically, obtaining the auth information). + * + * The result is a function which manages the API call with the given settings + * and the options on the invocation. + * + * Throws exception on unsupported streaming calls + * + * @param {Promise|GRPCCall} func - is either a promise to be used to make + * a bare RPC call, or just a bare RPC call. + * @param {CallSettings} settings - provides the settings for this call + * @param {Descriptor} descriptor - optionally specify the descriptor for + * the method call. + * @return {GaxCall} func - a bound method on a request stub used + * to make an rpc call. + */ +export declare function createApiCall(func: Promise | GRPCCall, settings: gax.CallSettings, descriptor?: Descriptor, _fallback?: boolean | string): GaxCall; +export { protobuf }; +export * as protobufMinimal from 'protobufjs/minimal'; +export { warn } from './warnings'; +export { Operation, operation } from './longRunningCalls/longrunning'; +export { GoogleError } from './googleError'; +declare const fallback: any; +export { fallback }; diff --git a/node_modules/google-gax/build/src/fallback.js b/node_modules/google-gax/build/src/fallback.js new file mode 100644 index 0000000..f9e33da --- /dev/null +++ b/node_modules/google-gax/build/src/fallback.js @@ -0,0 +1,350 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fallback = exports.GoogleError = exports.operation = exports.Operation = exports.warn = exports.protobufMinimal = exports.protobuf = exports.LocationProtos = exports.IamProtos = exports.operationsProtos = exports.GrpcClient = exports.defaultToObjectOptions = exports.makeUUID = exports.LocationsClient = exports.IamClient = exports.OperationsClient = exports.StreamType = exports.StreamDescriptor = exports.PageDescriptor = exports.LongrunningDescriptor = exports.BundleDescriptor = exports.version = exports.createDefaultBackoffSettings = exports.RetryOptions = exports.constructSettings = exports.CallSettings = exports.routingHeader = exports.PathTemplate = void 0; +exports.lro = lro; +exports.createApiCall = createApiCall; +const objectHash = require("object-hash"); +const protobuf = require("protobufjs"); +exports.protobuf = protobuf; +const gax = require("./gax"); +const routingHeader = require("./routingHeader"); +exports.routingHeader = routingHeader; +const status_1 = require("./status"); +const google_auth_library_1 = require("google-auth-library"); +const operationsClient_1 = require("./operationsClient"); +const createApiCall_1 = require("./createApiCall"); +const fallbackRest = require("./fallbackRest"); +const featureDetection_1 = require("./featureDetection"); +const fallbackServiceStub_1 = require("./fallbackServiceStub"); +const streaming_1 = require("./streamingCalls/streaming"); +const util_1 = require("./util"); +const IamProtos = require("../protos/iam_service"); +exports.IamProtos = IamProtos; +const LocationProtos = require("../protos/locations"); +exports.LocationProtos = LocationProtos; +const operationsProtos = require("../protos/operations"); +exports.operationsProtos = operationsProtos; +var pathTemplate_1 = require("./pathTemplate"); +Object.defineProperty(exports, "PathTemplate", { enumerable: true, get: function () { return pathTemplate_1.PathTemplate; } }); +var gax_1 = require("./gax"); +Object.defineProperty(exports, "CallSettings", { enumerable: true, get: function () { return gax_1.CallSettings; } }); +Object.defineProperty(exports, "constructSettings", { enumerable: true, get: function () { return gax_1.constructSettings; } }); +Object.defineProperty(exports, "RetryOptions", { enumerable: true, get: function () { return gax_1.RetryOptions; } }); +Object.defineProperty(exports, "createDefaultBackoffSettings", { enumerable: true, get: function () { return gax_1.createDefaultBackoffSettings; } }); +exports.version = require('../../package.json').version + '-fallback'; +var descriptor_1 = require("./descriptor"); +Object.defineProperty(exports, "BundleDescriptor", { enumerable: true, get: function () { return descriptor_1.BundleDescriptor; } }); +Object.defineProperty(exports, "LongrunningDescriptor", { enumerable: true, get: function () { return descriptor_1.LongrunningDescriptor; } }); +Object.defineProperty(exports, "PageDescriptor", { enumerable: true, get: function () { return descriptor_1.PageDescriptor; } }); +Object.defineProperty(exports, "StreamDescriptor", { enumerable: true, get: function () { return descriptor_1.StreamDescriptor; } }); +var streaming_2 = require("./streamingCalls/streaming"); +Object.defineProperty(exports, "StreamType", { enumerable: true, get: function () { return streaming_2.StreamType; } }); +var operationsClient_2 = require("./operationsClient"); +Object.defineProperty(exports, "OperationsClient", { enumerable: true, get: function () { return operationsClient_2.OperationsClient; } }); +var iamService_1 = require("./iamService"); +Object.defineProperty(exports, "IamClient", { enumerable: true, get: function () { return iamService_1.IamClient; } }); +var locationService_1 = require("./locationService"); +Object.defineProperty(exports, "LocationsClient", { enumerable: true, get: function () { return locationService_1.LocationsClient; } }); +var util_2 = require("./util"); +Object.defineProperty(exports, "makeUUID", { enumerable: true, get: function () { return util_2.makeUUID; } }); +exports.defaultToObjectOptions = { + keepCase: false, + longs: String, + enums: String, + defaults: true, + oneofs: true, +}; +const CLIENT_VERSION_HEADER = 'x-goog-api-client'; +class GrpcClient { + /** + * In rare cases users might need to deallocate all memory consumed by loaded protos. + * This method will delete the proto cache content. + */ + static clearProtoCache() { + GrpcClient.protoCache.clear(); + } + /** + * gRPC-fallback version of GrpcClient + * Implements GrpcClient API for a browser using grpc-fallback protocol (sends serialized protobuf to HTTP/1 $rpc endpoint). + * + * @param {Object=} options.auth - An instance of OAuth2Client to use in browser, or an instance of GoogleAuth from google-auth-library + * to use in Node.js. Required for browser, optional for Node.js. + * @constructor + */ + constructor(options = {}) { + var _a; + if (!(0, featureDetection_1.isNodeJS)()) { + if (!options.auth) { + throw new Error(JSON.stringify(options) + + 'You need to pass auth instance to use gRPC-fallback client in browser or other non-Node.js environments. Use OAuth2Client from google-auth-library.'); + } + this.auth = options.auth; + } + else { + this.auth = + options.auth || + new google_auth_library_1.GoogleAuth(options); + } + this.fallback = options.fallback ? true : false; + this.grpcVersion = require('../../package.json').version; + this.httpRules = options.httpRules; + this.numericEnums = (_a = options.numericEnums) !== null && _a !== void 0 ? _a : false; + } + /** + * gRPC-fallback version of loadProto + * Loads the protobuf root object from a JSON object created from a proto file + * @param {Object} jsonObject - A JSON version of a protofile created usin protobuf.js + * @returns {Object} Root namespace of proto JSON + */ + loadProto(jsonObject) { + const rootObject = protobuf.Root.fromJSON(jsonObject); + return rootObject; + } + loadProtoJSON(json, ignoreCache = false) { + const hash = objectHash(JSON.stringify(json)).toString(); + const cached = GrpcClient.protoCache.get(hash); + if (cached && !ignoreCache) { + return cached; + } + const root = protobuf.Root.fromJSON(json); + GrpcClient.protoCache.set(hash, root); + return root; + } + static getServiceMethods(service) { + const methods = {}; + for (const [methodName, methodObject] of Object.entries(service.methods)) { + const methodNameLowerCamelCase = (0, util_1.toLowerCamelCase)(methodName); + methods[methodNameLowerCamelCase] = methodObject; + } + return methods; + } + /** + * gRPC-fallback version of constructSettings + * A wrapper of {@link constructSettings} function under the gRPC context. + * + * Most of parameters are common among constructSettings, please take a look. + * @param {string} serviceName - The fullly-qualified name of the service. + * @param {Object} clientConfig - A dictionary of the client config. + * @param {Object} configOverrides - A dictionary of overriding configs. + * @param {Object} headers - A dictionary of additional HTTP header name to + * its value. + * @return {Object} A mapping of method names to CallSettings. + */ + constructSettings(serviceName, clientConfig, configOverrides, headers) { + function buildMetadata(abTests, moreHeaders) { + const metadata = {}; + if (!headers) { + headers = {}; + } + // Since gRPC expects each header to be an array, + // we are doing the same for fallback here. + for (const key in headers) { + metadata[key] = Array.isArray(headers[key]) + ? headers[key] + : [headers[key]]; + } + // gRPC-fallback request must have 'grpc-web/' in 'x-goog-api-client' + const clientVersions = []; + if (metadata[CLIENT_VERSION_HEADER] && + metadata[CLIENT_VERSION_HEADER][0]) { + clientVersions.push(...metadata[CLIENT_VERSION_HEADER][0].split(' ')); + } + clientVersions.push(`grpc-web/${exports.version}`); + metadata[CLIENT_VERSION_HEADER] = [clientVersions.join(' ')]; + if (!moreHeaders) { + return metadata; + } + for (const key in moreHeaders) { + if (key.toLowerCase() !== CLIENT_VERSION_HEADER) { + const value = moreHeaders[key]; + if (Array.isArray(value)) { + if (metadata[key] === undefined) { + metadata[key] = value; + } + else { + if (Array.isArray(metadata[key])) { + metadata[key].push(...value); + } + else { + throw new Error(`Can not add value ${value} to the call metadata.`); + } + } + } + else { + metadata[key] = [value]; + } + } + } + return metadata; + } + return gax.constructSettings(serviceName, clientConfig, configOverrides, status_1.Status, { metadataBuilder: buildMetadata }); + } + /** + * gRPC-fallback version of createStub + * Creates a gRPC-fallback stub with authentication headers built from supplied OAuth2Client instance + * + * @param {function} CreateStub - The constructor function of the stub. + * @param {Object} service - A protobufjs Service object (as returned by lookupService) + * @param {Object} opts - Connection options, as described below. + * @param {string} opts.servicePath - The hostname of the API endpoint service. + * @param {number} opts.port - The port of the service. + * @return {Promise} A promise which resolves to a gRPC-fallback service stub, which is a protobuf.js service stub instance modified to match the gRPC stub API + */ + async createStub(service, opts, + // For consistency with createStub in grpc.ts, customServicePath is defined: + // eslint-disable-next-line @typescript-eslint/no-unused-vars + customServicePath) { + if (!this.authClient) { + if (this.auth && 'getClient' in this.auth) { + this.authClient = (await this.auth.getClient()); + } + else if (this.auth && 'getRequestHeaders' in this.auth) { + this.authClient = this.auth; + } + } + if (!this.authClient) { + throw new Error('No authentication was provided'); + } + if (!opts.universeDomain) { + opts.universeDomain = 'googleapis.com'; + } + if (opts.universeDomain) { + const universeFromAuth = this.authClient.universeDomain; + if (universeFromAuth && opts.universeDomain !== universeFromAuth) { + throw new Error(`The configured universe domain (${opts.universeDomain}) does not match the universe domain found in the credentials (${universeFromAuth}). ` + + "If you haven't configured the universe domain explicitly, googleapis.com is the default."); + } + } + service.resolveAll(); + const methods = GrpcClient.getServiceMethods(service); + const protocol = opts.protocol || 'https'; + let servicePath = opts.servicePath; + if (!servicePath && + service.options && + service.options['(google.api.default_host)']) { + servicePath = service.options['(google.api.default_host)']; + } + if (!servicePath) { + throw new Error(`Cannot determine service API path for service ${service.name}.`); + } + let servicePort; + const match = servicePath.match(/^(.*):(\d+)$/); + if (match) { + servicePath = match[1]; + servicePort = parseInt(match[2]); + } + if (opts.port) { + servicePort = opts.port; + } + else if (!servicePort) { + servicePort = 443; + } + const encoder = fallbackRest.encodeRequest; + const decoder = fallbackRest.decodeResponse; + const serviceStub = (0, fallbackServiceStub_1.generateServiceStub)(methods, protocol, servicePath, servicePort, this.authClient, encoder, decoder, this.numericEnums); + return serviceStub; + } + /** + * Creates a 'bytelength' function for a given proto message class. + * + * See {@link BundleDescriptor} about the meaning of the return value. + * + * @param {function} message - a constructor function that is generated by + * protobuf.js. Assumes 'encoder' field in the message. + * @return {function(Object):number} - a function to compute the byte length + * for an object. + */ + static createByteLengthFunction(message) { + return gax.createByteLengthFunction(message); + } +} +exports.GrpcClient = GrpcClient; +GrpcClient.protoCache = new Map(); +/** + * gRPC-fallback version of lro + * + * @param {Object=} options.auth - An instance of google-auth-library. + * @return {Object} A OperationsClientBuilder that will return a OperationsClient + */ +function lro(options) { + options = Object.assign({ scopes: [] }, options); + if (options.protoJson) { + options = Object.assign(options, { fallback: true }); + } + const gaxGrpc = new GrpcClient(options); + return new operationsClient_1.OperationsClientBuilder(gaxGrpc, options.protoJson); +} +/** + * gRPC-fallback version of createApiCall + * + * Converts an rpc call into an API call governed by the settings. + * + * In typical usage, `func` will be a promise to a callable used to make an rpc + * request. This will mostly likely be a bound method from a request stub used + * to make an rpc call. It is not a direct function but a Promise instance, + * because of its asynchronism (typically, obtaining the auth information). + * + * The result is a function which manages the API call with the given settings + * and the options on the invocation. + * + * Throws exception on unsupported streaming calls + * + * @param {Promise|GRPCCall} func - is either a promise to be used to make + * a bare RPC call, or just a bare RPC call. + * @param {CallSettings} settings - provides the settings for this call + * @param {Descriptor} descriptor - optionally specify the descriptor for + * the method call. + * @return {GaxCall} func - a bound method on a request stub used + * to make an rpc call. + */ +function createApiCall(func, settings, descriptor, +// eslint-disable-next-line @typescript-eslint/no-unused-vars +_fallback // unused; for compatibility only +) { + if (descriptor && + 'streaming' in descriptor && + descriptor.type !== streaming_1.StreamType.SERVER_STREAMING) { + return () => { + throw new Error('The REST transport currently does not support client-streaming or bidi-stream calls.'); + }; + } + if (descriptor && 'streaming' in descriptor && !(0, featureDetection_1.isNodeJS)()) { + return () => { + throw new Error('Server streaming over the REST transport is only supported in Node.js.'); + }; + } + return (0, createApiCall_1.createApiCall)(func, settings, descriptor); +} +exports.protobufMinimal = require("protobufjs/minimal"); +var warnings_1 = require("./warnings"); +Object.defineProperty(exports, "warn", { enumerable: true, get: function () { return warnings_1.warn; } }); +var longrunning_1 = require("./longRunningCalls/longrunning"); +Object.defineProperty(exports, "Operation", { enumerable: true, get: function () { return longrunning_1.Operation; } }); +Object.defineProperty(exports, "operation", { enumerable: true, get: function () { return longrunning_1.operation; } }); +var googleError_1 = require("./googleError"); +Object.defineProperty(exports, "GoogleError", { enumerable: true, get: function () { return googleError_1.GoogleError; } }); +// Different environments or bundlers may or may not respect "browser" field +// in package.json (e.g. Electron does not respect it, but if you run the code +// through webpack first, it will follow the "browser" field). +// To make it safer and more compatible, let's make sure that if you do +// const gax = require("google-gax"); +// you can always ask for gax.fallback, regardless of "browser" field being +// understood or not. +const fallback = module.exports; +exports.fallback = fallback; +//# sourceMappingURL=fallback.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/fallback.js.map b/node_modules/google-gax/build/src/fallback.js.map new file mode 100644 index 0000000..af1d36b --- /dev/null +++ b/node_modules/google-gax/build/src/fallback.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fallback.js","sourceRoot":"","sources":["../../src/fallback.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAsWH,kBAOC;AA0BD,sCA0BC;AA9ZD,0CAA0C;AAC1C,uCAAuC;AA+Z/B,4BAAQ;AA9ZhB,6BAA6B;AAC7B,iDAAiD;AA6BzC,sCAAa;AA5BrB,qCAAgC;AAChC,6DAQ6B;AAC7B,yDAA2D;AAI3D,mDAAgE;AAEhE,+CAA+C;AAC/C,yDAA4C;AAC5C,+DAA0D;AAC1D,0DAAsD;AACtD,iCAAwC;AAExC,mDAAmD;AAiVzB,8BAAS;AAhVnC,sDAAsD;AAgVjB,wCAAc;AA/UnD,yDAAyD;AA+UjD,4CAAgB;AA5UxB,+CAA4C;AAApC,4GAAA,YAAY,OAAA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AG,IAAI,UAAU,CAAC,OAAO,CAAC,CAAC;IACxC,OAAO,IAAI,0CAAuB,CAAC,OAAO,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;AACjE,CAAC;AAGD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,SAAgB,aAAa,CAC3B,IAAkC,EAClC,QAA0B,EAC1B,UAAuB;AACvB,6DAA6D;AAC7D,SAA4B,CAAC,iCAAiC;;IAE9D,IACE,UAAU;QACV,WAAW,IAAI,UAAU;QACxB,UAA+B,CAAC,IAAI,KAAK,sBAAU,CAAC,gBAAgB,EACrE,CAAC;QACD,OAAO,GAAG,EAAE;YACV,MAAM,IAAI,KAAK,CACb,sFAAsF,CACvF,CAAC;QACJ,CAAC,CAAC;IACJ,CAAC;IACD,IAAI,UAAU,IAAI,WAAW,IAAI,UAAU,IAAI,CAAC,IAAA,2BAAQ,GAAE,EAAE,CAAC;QAC3D,OAAO,GAAG,EAAE;YACV,MAAM,IAAI,KAAK,CACb,wEAAwE,CACzE,CAAC;QACJ,CAAC,CAAC;IACJ,CAAC;IACD,OAAO,IAAA,6BAAc,EAAC,IAAI,EAAE,QAAQ,EAAE,UAAU,CAAC,CAAC;AACpD,CAAC;AAGD,wDAAsD;AAEtD,uCAAgC;AAAxB,gGAAA,IAAI,OAAA;AACZ,8DAAoE;AAA5D,wGAAA,SAAS,OAAA;AAAE,wGAAA,SAAS,OAAA;AAC5B,6CAA0C;AAAlC,0GAAA,WAAW,OAAA;AAEnB,4EAA4E;AAC5E,8EAA8E;AAC9E,8DAA8D;AAC9D,uEAAuE;AACvE,qCAAqC;AACrC,2EAA2E;AAC3E,qBAAqB;AACrB,MAAM,QAAQ,GAAG,MAAM,CAAC,OAAO,CAAC;AACxB,4BAAQ"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/fallbackRest.d.ts b/node_modules/google-gax/build/src/fallbackRest.d.ts new file mode 100644 index 0000000..c21893d --- /dev/null +++ b/node_modules/google-gax/build/src/fallbackRest.d.ts @@ -0,0 +1,18 @@ +/** + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FetchParameters } from './fallbackServiceStub'; +export declare function encodeRequest(rpc: protobuf.Method, protocol: string, servicePath: string, servicePort: number, request: {}, numericEnums: boolean): FetchParameters; +export declare function decodeResponse(rpc: protobuf.Method, ok: boolean, response: Buffer | ArrayBuffer): {}; diff --git a/node_modules/google-gax/build/src/fallbackRest.js b/node_modules/google-gax/build/src/fallbackRest.js new file mode 100644 index 0000000..0b80618 --- /dev/null +++ b/node_modules/google-gax/build/src/fallbackRest.js @@ -0,0 +1,78 @@ +"use strict"; +/** + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeRequest = encodeRequest; +exports.decodeResponse = decodeResponse; +// proto-over-HTTP request encoding and decoding +const serializer = require("proto3-json-serializer"); +const fallback_1 = require("./fallback"); +const googleError_1 = require("./googleError"); +const transcoding_1 = require("./transcoding"); +function encodeRequest(rpc, protocol, servicePath, servicePort, request, numericEnums) { + const headers = { + 'Content-Type': 'application/json', + }; + const message = rpc.resolvedRequestType.fromObject(request); + const json = serializer.toProto3JSON(message, { + numericEnums, + }); + if (!json) { + throw new Error(`Cannot send null request to RPC ${rpc.name}.`); + } + if (typeof json !== 'object' || Array.isArray(json)) { + throw new Error(`Request to RPC ${rpc.name} must be an object.`); + } + const transcoded = (0, transcoding_1.transcode)(json, rpc.parsedOptions); + if (!transcoded) { + throw new Error(`Cannot build HTTP request for ${JSON.stringify(json)}, method: ${rpc.name}`); + } + // If numeric enums feature is requested, add extra parameter to the query string + if (numericEnums) { + transcoded.queryString = + (transcoded.queryString ? `${transcoded.queryString}&` : '') + + '$alt=json%3Benum-encoding=int'; + } + // Converts httpMethod to method that permitted in standard Fetch API spec + // https://fetch.spec.whatwg.org/#methods + const method = transcoded.httpMethod.toUpperCase(); + const body = JSON.stringify(transcoded.data); + const url = `${protocol}://${servicePath}:${servicePort}/${transcoded.url.replace(/^\//, '')}?${transcoded.queryString}`; + return { + method, + url, + headers, + body, + }; +} +function decodeResponse(rpc, ok, response) { + // eslint-disable-next-line n/no-unsupported-features/node-builtins + const decodedString = new TextDecoder().decode(response); + if (!decodedString) { + throw new Error(`Received null response from RPC ${rpc.name}`); + } + const json = JSON.parse(decodedString); + if (!ok) { + const error = googleError_1.GoogleError.parseHttpError(json); + throw error; + } + const message = serializer.fromProto3JSON(rpc.resolvedResponseType, json); + if (!message) { + throw new Error(`Received null or malformed response from JSON serializer from RPC ${rpc.name}`); + } + return rpc.resolvedResponseType.toObject(message, fallback_1.defaultToObjectOptions); +} +//# sourceMappingURL=fallbackRest.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/fallbackRest.js.map b/node_modules/google-gax/build/src/fallbackRest.js.map new file mode 100644 index 0000000..cd2e1f2 --- /dev/null +++ b/node_modules/google-gax/build/src/fallbackRest.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fallbackRest.js","sourceRoot":"","sources":["../../src/fallbackRest.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAUH,sCAsDC;AAED,wCAsBC;AAtFD,gDAAgD;AAEhD,qDAAqD;AACrD,yCAAkD;AAElD,+CAA0C;AAC1C,+CAAwC;AAExC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AU,CAAC,IAAI,CAAC,CAAC;IAC7C,MAAM,GAAG,GAAG,GAAG,QAAQ,MAAM,WAAW,IAAI,WAAW,IAAI,UAAU,CAAC,GAAG,CAAC,OAAO,CAC/E,KAAK,EACL,EAAE,CACH,IAAI,UAAU,CAAC,WAAW,EAAE,CAAC;IAE9B,OAAO;QACL,MAAM;QACN,GAAG;QACH,OAAO;QACP,IAAI;KACL,CAAC;AACJ,CAAC;AAED,SAAgB,cAAc,CAC5B,GAAoB,EACpB,EAAW,EACX,QAA8B;IAE9B,mEAAmE;IACnE,MAAM,aAAa,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IACzD,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CAAC,mCAAmC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;IACjE,CAAC;IACD,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;IACvC,IAAI,CAAC,EAAE,EAAE,CAAC;QACR,MAAM,KAAK,GAAG,yBAAW,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;QAC/C,MAAM,KAAK,CAAC;IACd,CAAC;IACD,MAAM,OAAO,GAAG,UAAU,CAAC,cAAc,CAAC,GAAG,CAAC,oBAAqB,EAAE,IAAI,CAAC,CAAC;IAC3E,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CACb,qEAAqE,GAAG,CAAC,IAAI,EAAE,CAChF,CAAC;IACJ,CAAC;IACD,OAAO,GAAG,CAAC,oBAAqB,CAAC,QAAQ,CAAC,OAAO,EAAE,iCAAsB,CAAC,CAAC;AAC7E,CAAC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/fallbackServiceStub.d.ts b/node_modules/google-gax/build/src/fallbackServiceStub.d.ts new file mode 100644 index 0000000..661b889 --- /dev/null +++ b/node_modules/google-gax/build/src/fallbackServiceStub.d.ts @@ -0,0 +1,34 @@ +/** + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AuthClient } from './fallback'; +import { StreamArrayParser } from './streamArrayParser'; +export interface FallbackServiceStub { + [method: string]: (request: {}, options?: {}, metadata?: {}, callback?: (err?: Error, response?: {} | undefined) => void) => StreamArrayParser | { + cancel: () => void; + }; +} +export type FetchParametersMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; +export interface FetchParameters { + headers: { + [key: string]: string; + }; + body: Buffer | Uint8Array | string; + method: FetchParametersMethod; + url: string; +} +export declare function generateServiceStub(rpcs: { + [name: string]: protobuf.Method; +}, protocol: string, servicePath: string, servicePort: number, authClient: AuthClient, requestEncoder: (rpc: protobuf.Method, protocol: string, servicePath: string, servicePort: number, request: {}, numericEnums: boolean) => FetchParameters, responseDecoder: (rpc: protobuf.Method, ok: boolean, response: Buffer | ArrayBuffer) => {}, numericEnums: boolean): FallbackServiceStub; diff --git a/node_modules/google-gax/build/src/fallbackServiceStub.js b/node_modules/google-gax/build/src/fallbackServiceStub.js new file mode 100644 index 0000000..25687f4 --- /dev/null +++ b/node_modules/google-gax/build/src/fallbackServiceStub.js @@ -0,0 +1,152 @@ +"use strict"; +/** + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.generateServiceStub = generateServiceStub; +/* global window */ +/* global AbortController */ +const node_fetch_1 = require("node-fetch"); +const abort_controller_1 = require("abort-controller"); +const featureDetection_1 = require("./featureDetection"); +const streamArrayParser_1 = require("./streamArrayParser"); +const stream_1 = require("stream"); +function generateServiceStub(rpcs, protocol, servicePath, servicePort, authClient, requestEncoder, responseDecoder, numericEnums) { + const fetch = (0, featureDetection_1.hasWindowFetch)() + ? window.fetch + : node_fetch_1.default; + const serviceStub = { + // close method should close all cancel controllers. If this feature request in the future, we can have a cancelControllerFactory that tracks created cancel controllers, and abort them all in close method. + close: () => { + return { cancel: () => { } }; + }, + }; + for (const [rpcName, rpc] of Object.entries(rpcs)) { + serviceStub[rpcName] = (request, options, _metadata, callback) => { + options !== null && options !== void 0 ? options : (options = {}); + // We cannot use async-await in this function because we need to return the canceller object as soon as possible. + // Using plain old promises instead. + let fetchParameters; + try { + fetchParameters = requestEncoder(rpc, protocol, servicePath, servicePort, request, numericEnums); + } + catch (err) { + // we could not encode parameters; pass error to the callback + // and return a no-op canceler object. + if (callback) { + callback(err); + } + return { + cancel() { }, + }; + } + const cancelController = (0, featureDetection_1.hasAbortController)() + ? new AbortController() + : new abort_controller_1.AbortController(); + const cancelSignal = cancelController.signal; + let cancelRequested = false; + const url = fetchParameters.url; + const headers = fetchParameters.headers; + for (const key of Object.keys(options)) { + headers[key] = options[key][0]; + } + const streamArrayParser = new streamArrayParser_1.StreamArrayParser(rpc); + authClient + .getRequestHeaders() + .then(authHeader => { + const fetchRequest = { + headers: { + ...authHeader, + ...headers, + }, + body: fetchParameters.body, + method: fetchParameters.method, + signal: cancelSignal, + }; + if (fetchParameters.method === 'GET' || + fetchParameters.method === 'DELETE') { + delete fetchRequest['body']; + } + return fetch(url, fetchRequest); + }) + .then((response) => { + if (response.ok && rpc.responseStream) { + (0, stream_1.pipeline)(response.body, streamArrayParser, (err) => { + if (err && + (!cancelRequested || + (err instanceof Error && err.name !== 'AbortError'))) { + if (callback) { + callback(err); + } + streamArrayParser.emit('error', err); + } + }); + return; + } + else { + return Promise.all([ + Promise.resolve(response.ok), + response.arrayBuffer(), + ]) + .then(([ok, buffer]) => { + const response = responseDecoder(rpc, ok, buffer); + callback(null, response); + }) + .catch((err) => { + if (!cancelRequested || err.name !== 'AbortError') { + if (rpc.responseStream) { + if (callback) { + callback(err); + } + streamArrayParser.emit('error', err); + } + else if (callback) { + callback(err); + } + else { + throw err; + } + } + }); + } + }) + .catch((err) => { + if (rpc.responseStream) { + if (callback) { + callback(err); + } + streamArrayParser.emit('error', err); + } + else if (callback) { + callback(err); + } + else { + throw err; + } + }); + if (rpc.responseStream) { + return streamArrayParser; + } + return { + cancel: () => { + cancelRequested = true; + cancelController.abort(); + }, + }; + }; + } + return serviceStub; +} +//# sourceMappingURL=fallbackServiceStub.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/fallbackServiceStub.js.map b/node_modules/google-gax/build/src/fallbackServiceStub.js.map new file mode 100644 index 0000000..967018c --- /dev/null +++ b/node_modules/google-gax/build/src/fallbackServiceStub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fallbackServiceStub.js","sourceRoot":"","sources":["../../src/fallbackServiceStub.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAqCH,kDA0KC;AA7MD,mBAAmB;AACnB,4BAA4B;AAE5B,2CAAmC;AAEnC,uDAAwE;AAExE,yDAAsE;AAEtE,2DAAsD;AACtD,mCAAgD;AAyBhD,SAAgB,mBAAmB,CACjC,IAAuC,EACvC,QAAgB,EAChB,WAAmB,EACnB,WAAmB,EACnB,UAAsB,EACtB,cAOoB,EACpB,eAIO,EACP,YAAqB;IAErB,MAAM,KAAK,GAAG,IAAA,iCAAc,GAAE;QAC5B,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAE,oBAAsC,CAAC;IAE5C,MAAM,WAAW,GAAwB;QACvC,6MAA6M;QAC7M,KAAK,EAAE,GAAG,EAA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C;YAC3B,CAAC;YACD,OAAO;gBACL,MAAM,EAAE,GAAG,EAAE;oBACX,eAAe,GAAG,IAAI,CAAC;oBACvB,gBAAgB,CAAC,KAAK,EAAE,CAAC;gBAC3B,CAAC;aACF,CAAC;QACJ,CAAC,CAAC;IACJ,CAAC;IAED,OAAO,WAAW,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/featureDetection.d.ts b/node_modules/google-gax/build/src/featureDetection.d.ts new file mode 100644 index 0000000..bb67912 --- /dev/null +++ b/node_modules/google-gax/build/src/featureDetection.d.ts @@ -0,0 +1,18 @@ +/** + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare function hasWindowFetch(): boolean; +export declare function isNodeJS(): string | false; +export declare function hasAbortController(): boolean; diff --git a/node_modules/google-gax/build/src/featureDetection.js b/node_modules/google-gax/build/src/featureDetection.js new file mode 100644 index 0000000..b72289a --- /dev/null +++ b/node_modules/google-gax/build/src/featureDetection.js @@ -0,0 +1,43 @@ +"use strict"; +/** + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var _a; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hasWindowFetch = hasWindowFetch; +exports.isNodeJS = isNodeJS; +exports.hasAbortController = hasAbortController; +/* global window */ +const features = { + windowFetch: typeof window !== 'undefined' && + (window === null || window === void 0 ? void 0 : window.fetch) && + typeof (window === null || window === void 0 ? void 0 : window.fetch) === 'function', + // eslint-disable-next-line n/no-unsupported-features/node-builtins + textEncoder: typeof TextEncoder !== 'undefined', + // eslint-disable-next-line n/no-unsupported-features/node-builtins + textDecoder: typeof TextDecoder !== 'undefined', + nodeJS: typeof process !== 'undefined' && ((_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node), + abortController: typeof AbortController !== 'undefined', +}; +function hasWindowFetch() { + return features.windowFetch; +} +function isNodeJS() { + return features.nodeJS; +} +function hasAbortController() { + return features.abortController; +} +//# sourceMappingURL=featureDetection.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/featureDetection.js.map b/node_modules/google-gax/build/src/featureDetection.js.map new file mode 100644 index 0000000..ff2896e --- /dev/null +++ b/node_modules/google-gax/build/src/featureDetection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"featureDetection.js","sourceRoot":"","sources":["../../src/featureDetection.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAiBH,wCAEC;AAED,4BAEC;AAED,gDAEC;AAzBD,mBAAmB;AAEnB,MAAM,QAAQ,GAAG;IACf,WAAW,EACT,OAAO,MAAM,KAAK,WAAW;SAC7B,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,KAAK,CAAA;QACb,OAAO,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,KAAK,CAAA,KAAK,UAAU;IACrC,mEAAmE;IACnE,WAAW,EAAE,OAAO,WAAW,KAAK,WAAW;IAC/C,mEAAmE;IACnE,WAAW,EAAE,OAAO,WAAW,KAAK,WAAW;IAC/C,MAAM,EAAE,OAAO,OAAO,KAAK,WAAW,KAAI,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,QAAQ,0CAAE,IAAI,CAAA;IACjE,eAAe,EAAE,OAAO,eAAe,KAAK,WAAW;CACxD,CAAC;AAEF,SAAgB,cAAc;IAC5B,OAAO,QAAQ,CAAC,WAAW,CAAC;AAC9B,CAAC;AAED,SAAgB,QAAQ;IACtB,OAAO,QAAQ,CAAC,MAAM,CAAC;AACzB,CAAC;AAED,SAAgB,kBAAkB;IAChC,OAAO,QAAQ,CAAC,eAAe,CAAC;AAClC,CAAC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/gax.d.ts b/node_modules/google-gax/build/src/gax.d.ts new file mode 100644 index 0000000..043f98b --- /dev/null +++ b/node_modules/google-gax/build/src/gax.d.ts @@ -0,0 +1,381 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Google API Extensions + */ +import type { Message } from 'protobufjs'; +import { GoogleError } from './googleError'; +import { BundleOptions } from './bundlingCalls/bundleExecutor'; +import { RequestType } from './apitypes'; +/** + * Encapsulates the overridable settings for a particular API call. + * + * ``CallOptions`` is an optional arg for all GAX API calls. It is used to + * configure the settings of a specific API call. + * + * When provided, its values override the GAX service defaults for that + * particular call. + * + * Typically the API clients will accept this as the second to the last + * argument. See the examples below. + * @typedef {Object} CallOptions + * @property {number=} timeout - The client-side timeout for API calls. + * @property {RetryOptions=} retry - determines whether and how to retry + * on transient errors. When set to null, the call will not retry. + * @property {boolean=} autoPaginate - If set to false and the call is + * configured for paged iteration, page unrolling is not performed, instead + * the callback will be called with the response object. + * @property {Object=} pageToken - If set and the call is configured for + * paged iteration, paged iteration is not performed and requested with this + * pageToken. + * @property {number} maxResults - If set and the call is configured for + * paged iteration, the call will stop when the number of response elements + * reaches to the specified size. By default, it will unroll the page to + * the end of the list. + * @property {boolean=} isBundling - If set to false and the call is configured + * for bundling, bundling is not performed. + * @property {BackoffSettings=} longrunning - BackoffSettings used for polling. + * @example + * // suppress bundling for bundled method. + * api.bundlingMethod( + * param, {optParam: aValue, isBundling: false}, function(err, response) { + * // handle response. + * }); + * @example + * // suppress streaming for page-streaming method. + * api.pageStreamingMethod( + * param, {optParam: aValue, autoPaginate: false}, function(err, page) { + * // not returning a stream, but callback is called with the paged response. + * }); + */ +/** + * Per-call configurable settings for retrying upon transient failure. + * @implements {RetryOptionsType} + * @typedef {Object} RetryOptions + * @property {number[]} retryCodes + * @property {BackoffSettings} backoffSettings + * @property {(function)} shouldRetryFn + * @property {(function)} getResumptionRequestFn + */ +export declare class RetryOptions { + retryCodes: number[]; + backoffSettings: BackoffSettings; + shouldRetryFn?: (error: GoogleError) => boolean; + getResumptionRequestFn?: (request: RequestType) => RequestType; + constructor(retryCodes: number[], backoffSettings: BackoffSettings, shouldRetryFn?: (error: GoogleError) => boolean, getResumptionRequestFn?: (request: RequestType) => RequestType); +} +/** + * Per-call configurable settings for working with retry-request + * See the repo README for more about the parameters + * https://github.com/googleapis/retry-request + * Will be deprecated in a future release. Only relevant to server streaming calls + * @typedef {Object} RetryOptions + * @property {boolean} objectMode - when true utilizes object mode in streams + * @property {request} request - the request to retry + * @property {number} noResponseRetries - number of times to retry on no response + * @property {number} currentRetryAttempt - what # retry attempt retry-request is on + * @property {Function} shouldRetryFn - determines whether to retry, returns a boolean + * @property {number} maxRetryDelay - maximum retry delay in seconds + * @property {number} retryDelayMultiplier - multiplier to increase the delay in between completion of failed requests + * @property {number} totalTimeout - total timeout in seconds + */ +export interface RetryRequestOptions { + objectMode?: boolean; + request?: any; + retries?: number; + noResponseRetries?: number; + currentRetryAttempt?: number; + shouldRetryFn?: (error: GoogleError) => boolean; + maxRetryDelay?: number; + retryDelayMultiplier?: number; + totalTimeout?: number; +} +/** + * Parameters to the exponential backoff algorithm for retrying. + * @typedef {Object} BackoffSettings + * @property {number} initialRetryDelayMillis - the initial delay time, + * in milliseconds, between the completion of the first failed request and the + * initiation of the first retrying request. + * @property {number} retryDelayMultiplier - the multiplier by which to + * increase the delay time between the completion of failed requests, and the + * initiation of the subsequent retrying request. + * @property {number} maxRetryDelayMillis - the maximum delay time, in + * milliseconds, between requests. When this value is reached, + * ``retryDelayMultiplier`` will no longer be used to increase delay time. + * @property {number} initialRpcTimeoutMillis - the initial timeout parameter + * to the request. + * @propetry {number} rpcTimeoutMultiplier - the multiplier by which to + * increase the timeout parameter between failed requests. + * @property {number} maxRpcTimeoutMillis - the maximum timeout parameter, in + * milliseconds, for a request. When this value is reached, + * ``rpcTimeoutMultiplier`` will no longer be used to increase the timeout. + * @property {number} totalTimeoutMillis - the total time, in milliseconds, + * starting from when the initial request is sent, after which an error will + * be returned, regardless of the retrying attempts made meanwhile. + */ +export interface BackoffSettings { + maxRetries?: number; + initialRetryDelayMillis: number; + retryDelayMultiplier: number; + maxRetryDelayMillis: number; + initialRpcTimeoutMillis?: number | null; + maxRpcTimeoutMillis?: number | null; + totalTimeoutMillis?: number | null; + rpcTimeoutMultiplier?: number | null; +} +export interface CallOptions { + timeout?: number; + retry?: Partial | null; + autoPaginate?: boolean; + maxResults?: number; + maxRetries?: number; + otherArgs?: { + [index: string]: any; + }; + bundleOptions?: BundleOptions | null; + isBundling?: boolean; + longrunning?: BackoffSettings; + apiName?: string; + retryRequestOptions?: RetryRequestOptions; +} +export declare class CallSettings { + timeout: number; + retry?: RetryOptions | null; + autoPaginate?: boolean; + pageToken?: string; + pageSize?: number; + maxResults?: number; + otherArgs: { + [index: string]: any; + }; + bundleOptions?: BundleOptions | null; + isBundling: boolean; + longrunning?: BackoffSettings; + apiName?: string; + retryRequestOptions?: RetryRequestOptions; + /** + * @param {Object} settings - An object containing parameters of this settings. + * @param {number} settings.timeout - The client-side timeout for API calls. + * This parameter is ignored for retrying calls. + * @param {RetryOptions} settings.retry - The configuration for retrying upon + * transient error. If set to null, this call will not retry. + * @param {boolean} settings.autoPaginate - If there is no `pageDescriptor`, + * this attrbute has no meaning. Otherwise, determines whether a page + * streamed response should make the page structure transparent to the user by + * flattening the repeated field in the returned generator. + * @param {number} settings.pageToken - If there is no `pageDescriptor`, + * this attribute has no meaning. Otherwise, determines the page token used + * in the page streaming request. + * @param {Object} settings.otherArgs - Additional arguments to be passed to + * the API calls. + * + * @constructor + */ + constructor(settings?: CallOptions); + /** + * Returns a new CallSettings merged from this and a CallOptions object. + * + * @param {CallOptions} options - an instance whose values override + * those in this object. If null, ``merge`` returns a copy of this + * object + * @return {CallSettings} The merged CallSettings instance. + */ + merge(options?: CallOptions | null): CallSettings; +} +/** + * Validates passed retry options in preparation for eventual parameter deprecation + * converts retryRequestOptions to retryOptions + * then sets retryRequestOptions to null + * + * @param {CallOptions} options - a list of passed retry option + * @return {CallOptions} A new CallOptions object. + * + */ +export declare function convertRetryOptions(options?: CallOptions, gaxStreamingRetries?: boolean): CallOptions | undefined; +/** + * Per-call configurable settings for retrying upon transient failure. + * @param {number[]} retryCodes - a list of Google API canonical error codes OR a function that returns a boolean to determine retry behavior + * upon which a retry should be attempted. + * @param {BackoffSettings} backoffSettings - configures the retry + * exponential backoff algorithm. + * @param {function} shouldRetryFn - a function that determines whether a call should retry. If this is defined retryCodes must be empty + * @param {function} getResumptionRequestFn - a function with a resumption strategy - only used with server streaming retries + * @return {RetryOptions} A new RetryOptions object. + * + */ +export declare function createRetryOptions(retryCodes: number[], backoffSettings: BackoffSettings, shouldRetryFn?: (error: GoogleError) => boolean, getResumptionRequestFn?: (request: RequestType) => RequestType): RetryOptions; +/** + * Parameters to the exponential backoff algorithm for retrying. + * + * @param {number} initialRetryDelayMillis - the initial delay time, + * in milliseconds, between the completion of the first failed request and the + * initiation of the first retrying request. + * @param {number} retryDelayMultiplier - the multiplier by which to + * increase the delay time between the completion of failed requests, and the + * initiation of the subsequent retrying request. + * @param {number} maxRetryDelayMillis - the maximum delay time, in + * milliseconds, between requests. When this value is reached, + * ``retryDelayMultiplier`` will no longer be used to increase delay time. + * @param {number} initialRpcTimeoutMillis - the initial timeout parameter + * to the request. + * @param {number} rpcTimeoutMultiplier - the multiplier by which to + * increase the timeout parameter between failed requests. + * @param {number} maxRpcTimeoutMillis - the maximum timeout parameter, in + * milliseconds, for a request. When this value is reached, + * ``rpcTimeoutMultiplier`` will no longer be used to increase the timeout. + * @param {number} totalTimeoutMillis - the total time, in milliseconds, + * starting from when the initial request is sent, after which an error will + * be returned, regardless of the retrying attempts made meanwhile. + * @return {BackoffSettings} a new settings. + * + */ +export declare function createBackoffSettings(initialRetryDelayMillis: number, retryDelayMultiplier: number, maxRetryDelayMillis: number, initialRpcTimeoutMillis: number | null, rpcTimeoutMultiplier: number | null, maxRpcTimeoutMillis: number | null, totalTimeoutMillis: number | null): BackoffSettings; +export declare function createDefaultBackoffSettings(): BackoffSettings; +/** + * Parameters to the exponential backoff algorithm for retrying. + * This function is unsupported, and intended for internal use only. + * + * @param {number} initialRetryDelayMillis - the initial delay time, + * in milliseconds, between the completion of the first failed request and the + * initiation of the first retrying request. + * @param {number} retryDelayMultiplier - the multiplier by which to + * increase the delay time between the completion of failed requests, and the + * initiation of the subsequent retrying request. + * @param {number} maxRetryDelayMillis - the maximum delay time, in + * milliseconds, between requests. When this value is reached, + * ``retryDelayMultiplier`` will no longer be used to increase delay time. + * @param {number} initialRpcTimeoutMillis - the initial timeout parameter + * to the request. + * @param {number} rpcTimeoutMultiplier - the multiplier by which to + * increase the timeout parameter between failed requests. + * @param {number} maxRpcTimeoutMillis - the maximum timeout parameter, in + * milliseconds, for a request. When this value is reached, + * ``rpcTimeoutMultiplier`` will no longer be used to increase the timeout. + * @param {number} maxRetries - the maximum number of retrying attempts that + * will be made. If reached, an error will be returned. + * @return {BackoffSettings} a new settings. + * + */ +export declare function createMaxRetriesBackoffSettings(initialRetryDelayMillis: number, retryDelayMultiplier: number, maxRetryDelayMillis: number, initialRpcTimeoutMillis: number, rpcTimeoutMultiplier: number, maxRpcTimeoutMillis: number, maxRetries: number): BackoffSettings; +/** + * Creates a new {@link BundleOptions}. + * + * @private + * @param {Object} options - An object to hold optional parameters. See + * properties for the content of options. + * @return {BundleOptions} - A new options. + */ +export declare function createBundleOptions(options: BundlingConfig): BundleOptions; +export interface ServiceConfig { + retry_codes?: { + [index: string]: string[]; + }; + retry_params?: { + [index: string]: RetryParamsConfig; + }; + methods: { + [index: string]: MethodConfig | null; + }; +} +export interface RetryParamsConfig { + initial_retry_delay_millis: number; + retry_delay_multiplier: number; + max_retry_delay_millis: number; + initial_rpc_timeout_millis: number; + rpc_timeout_multiplier: number; + max_rpc_timeout_millis: number; + total_timeout_millis: number; +} +export interface MethodConfig { + retry_codes_name?: string; + retry_params_name?: string; + bundling?: BundlingConfig | null; + timeout_millis?: number; +} +export interface BundlingConfig { + element_count_threshold: number; + element_count_limit: number; + request_byte_threshold?: number; + request_byte_limit?: number; + delay_threshold_millis?: number; +} +export interface ClientConfig { + interfaces?: { + [index: string]: ServiceConfig; + }; +} +/** + * Constructs a dictionary mapping method names to {@link CallSettings}. + * + * The `clientConfig` parameter is parsed from a client configuration JSON + * file of the form: + * + * { + * "interfaces": { + * "google.fake.v1.ServiceName": { + * "retry_codes": { + * "idempotent": ["UNAVAILABLE", "DEADLINE_EXCEEDED"], + * "non_idempotent": [] + * }, + * "retry_params": { + * "default": { + * "initial_retry_delay_millis": 100, + * "retry_delay_multiplier": 1.2, + * "max_retry_delay_millis": 1000, + * "initial_rpc_timeout_millis": 2000, + * "rpc_timeout_multiplier": 1.5, + * "max_rpc_timeout_millis": 30000, + * "total_timeout_millis": 45000 + * } + * }, + * "methods": { + * "CreateFoo": { + * "retry_codes_name": "idempotent", + * "retry_params_name": "default" + * }, + * "Publish": { + * "retry_codes_name": "non_idempotent", + * "retry_params_name": "default", + * "bundling": { + * "element_count_threshold": 40, + * "element_count_limit": 200, + * "request_byte_threshold": 90000, + * "request_byte_limit": 100000, + * "delay_threshold_millis": 100 + * } + * } + * } + * } + * } + * } + * + * @param {String} serviceName - The fully-qualified name of this + * service, used as a key into the client config file (in the + * example above, this value should be 'google.fake.v1.ServiceName'). + * @param {Object} clientConfig - A dictionary parsed from the + * standard API client config file. + * @param {Object} configOverrides - A dictionary in the same structure of + * client_config to override the settings. + * @param {Object.} retryNames - A dictionary mapping the strings + * referring to response status codes to objects representing + * those codes. + * @param {Object} otherArgs - the non-request arguments to be passed to the API + * calls. + * @return {Object} A mapping from method name to CallSettings, or null if the + * service is not found in the config. + */ +export declare function constructSettings(serviceName: string, clientConfig: ClientConfig, configOverrides: ClientConfig, retryNames: {}, otherArgs?: {}): any; +export declare function createByteLengthFunction(message: typeof Message): (obj: {}) => number; diff --git a/node_modules/google-gax/build/src/gax.js b/node_modules/google-gax/build/src/gax.js new file mode 100644 index 0000000..b149717 --- /dev/null +++ b/node_modules/google-gax/build/src/gax.js @@ -0,0 +1,612 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CallSettings = exports.RetryOptions = void 0; +exports.convertRetryOptions = convertRetryOptions; +exports.createRetryOptions = createRetryOptions; +exports.createBackoffSettings = createBackoffSettings; +exports.createDefaultBackoffSettings = createDefaultBackoffSettings; +exports.createMaxRetriesBackoffSettings = createMaxRetriesBackoffSettings; +exports.createBundleOptions = createBundleOptions; +exports.constructSettings = constructSettings; +exports.createByteLengthFunction = createByteLengthFunction; +const warnings_1 = require("./warnings"); +const util_1 = require("./util"); +const status_1 = require("./status"); +/** + * Encapsulates the overridable settings for a particular API call. + * + * ``CallOptions`` is an optional arg for all GAX API calls. It is used to + * configure the settings of a specific API call. + * + * When provided, its values override the GAX service defaults for that + * particular call. + * + * Typically the API clients will accept this as the second to the last + * argument. See the examples below. + * @typedef {Object} CallOptions + * @property {number=} timeout - The client-side timeout for API calls. + * @property {RetryOptions=} retry - determines whether and how to retry + * on transient errors. When set to null, the call will not retry. + * @property {boolean=} autoPaginate - If set to false and the call is + * configured for paged iteration, page unrolling is not performed, instead + * the callback will be called with the response object. + * @property {Object=} pageToken - If set and the call is configured for + * paged iteration, paged iteration is not performed and requested with this + * pageToken. + * @property {number} maxResults - If set and the call is configured for + * paged iteration, the call will stop when the number of response elements + * reaches to the specified size. By default, it will unroll the page to + * the end of the list. + * @property {boolean=} isBundling - If set to false and the call is configured + * for bundling, bundling is not performed. + * @property {BackoffSettings=} longrunning - BackoffSettings used for polling. + * @example + * // suppress bundling for bundled method. + * api.bundlingMethod( + * param, {optParam: aValue, isBundling: false}, function(err, response) { + * // handle response. + * }); + * @example + * // suppress streaming for page-streaming method. + * api.pageStreamingMethod( + * param, {optParam: aValue, autoPaginate: false}, function(err, page) { + * // not returning a stream, but callback is called with the paged response. + * }); + */ +/** + * Per-call configurable settings for retrying upon transient failure. + * @implements {RetryOptionsType} + * @typedef {Object} RetryOptions + * @property {number[]} retryCodes + * @property {BackoffSettings} backoffSettings + * @property {(function)} shouldRetryFn + * @property {(function)} getResumptionRequestFn + */ +class RetryOptions { + constructor(retryCodes, backoffSettings, shouldRetryFn, getResumptionRequestFn) { + this.retryCodes = retryCodes; + this.backoffSettings = backoffSettings; + this.shouldRetryFn = shouldRetryFn; + this.getResumptionRequestFn = getResumptionRequestFn; + } +} +exports.RetryOptions = RetryOptions; +class CallSettings { + /** + * @param {Object} settings - An object containing parameters of this settings. + * @param {number} settings.timeout - The client-side timeout for API calls. + * This parameter is ignored for retrying calls. + * @param {RetryOptions} settings.retry - The configuration for retrying upon + * transient error. If set to null, this call will not retry. + * @param {boolean} settings.autoPaginate - If there is no `pageDescriptor`, + * this attrbute has no meaning. Otherwise, determines whether a page + * streamed response should make the page structure transparent to the user by + * flattening the repeated field in the returned generator. + * @param {number} settings.pageToken - If there is no `pageDescriptor`, + * this attribute has no meaning. Otherwise, determines the page token used + * in the page streaming request. + * @param {Object} settings.otherArgs - Additional arguments to be passed to + * the API calls. + * + * @constructor + */ + constructor(settings) { + var _a; + settings = settings || {}; + this.timeout = settings.timeout || 30 * 1000; + this.retry = settings.retry; + this.autoPaginate = + 'autoPaginate' in settings ? settings.autoPaginate : true; + this.maxResults = settings.maxResults; + this.otherArgs = settings.otherArgs || {}; + this.bundleOptions = settings.bundleOptions; + this.isBundling = 'isBundling' in settings ? settings.isBundling : true; + this.longrunning = + 'longrunning' in settings ? settings.longrunning : undefined; + this.apiName = (_a = settings.apiName) !== null && _a !== void 0 ? _a : undefined; + this.retryRequestOptions = settings.retryRequestOptions; + } + /** + * Returns a new CallSettings merged from this and a CallOptions object. + * + * @param {CallOptions} options - an instance whose values override + * those in this object. If null, ``merge`` returns a copy of this + * object + * @return {CallSettings} The merged CallSettings instance. + */ + merge(options) { + if (!options) { + return new CallSettings(this); + } + let timeout = this.timeout; + let retry = this.retry; + let autoPaginate = this.autoPaginate; + let maxResults = this.maxResults; + let otherArgs = this.otherArgs; + let isBundling = this.isBundling; + let longrunning = this.longrunning; + let apiName = this.apiName; + let retryRequestOptions = this.retryRequestOptions; + // If the user provides a timeout to the method, that timeout value will be used + // to override the backoff settings. + if ('timeout' in options) { + timeout = options.timeout; + } + // If a method-specific timeout is set in the service config, and the retry codes for that + // method are non-null, then that timeout value will be used to + // override backoff settings. + if (retry === null || retry === void 0 ? void 0 : retry.retryCodes) { + retry.backoffSettings.initialRpcTimeoutMillis = timeout; + retry.backoffSettings.maxRpcTimeoutMillis = timeout; + retry.backoffSettings.totalTimeoutMillis = timeout; + } + if ('retry' in options) { + retry = mergeRetryOptions(retry || {}, options.retry); + } + if ('autoPaginate' in options && !options.autoPaginate) { + autoPaginate = false; + } + if ('maxResults' in options) { + maxResults = options.maxResults; + } + if ('otherArgs' in options) { + otherArgs = {}; + for (const key in this.otherArgs) { + otherArgs[key] = this.otherArgs[key]; + } + for (const optionsKey in options.otherArgs) { + otherArgs[optionsKey] = options.otherArgs[optionsKey]; + } + } + if ('isBundling' in options) { + isBundling = options.isBundling; + } + if ('maxRetries' in options && options.maxRetries !== undefined) { + retry.backoffSettings.maxRetries = options.maxRetries; + delete retry.backoffSettings.totalTimeoutMillis; + } + if ('longrunning' in options) { + longrunning = options.longrunning; + } + if ('apiName' in options) { + apiName = options.apiName; + } + if ('retryRequestOptions' in options) { + retryRequestOptions = options.retryRequestOptions; + } + return new CallSettings({ + timeout, + retry, + bundleOptions: this.bundleOptions, + longrunning, + autoPaginate, + maxResults, + otherArgs, + isBundling, + apiName, + retryRequestOptions, + }); + } +} +exports.CallSettings = CallSettings; +/** + * Validates passed retry options in preparation for eventual parameter deprecation + * converts retryRequestOptions to retryOptions + * then sets retryRequestOptions to null + * + * @param {CallOptions} options - a list of passed retry option + * @return {CallOptions} A new CallOptions object. + * + */ +function convertRetryOptions(options, gaxStreamingRetries) { + var _a, _b, _c, _d; + // options will be undefined if no CallOptions object is passed at call time + if (!options) { + return options; + } + // if a user provided retry AND retryRequestOptions at call time, throw an error + // otherwise, convert supported parameters + if (!gaxStreamingRetries) { + return options; + } + if (options.retry && options.retryRequestOptions) { + throw new Error('Only one of retry or retryRequestOptions may be set'); + } // handles parameter conversion from retryRequestOptions to retryOptions + if (options.retryRequestOptions) { + if (options.retryRequestOptions.objectMode !== undefined) { + (0, warnings_1.warn)('retry_request_options', 'objectMode override is not supported. It is set to true internally by default in gax.', 'UnsupportedParameterWarning'); + } + if (options.retryRequestOptions.noResponseRetries !== undefined) { + (0, warnings_1.warn)('retry_request_options', 'noResponseRetries override is not supported. Please specify retry codes or a function to determine retry eligibility.', 'UnsupportedParameterWarning'); + } + if (options.retryRequestOptions.currentRetryAttempt !== undefined) { + (0, warnings_1.warn)('retry_request_options', 'currentRetryAttempt override is not supported. Retry attempts are tracked internally.', 'UnsupportedParameterWarning'); + } + let retryCodes = [status_1.Status.UNAVAILABLE]; + let shouldRetryFn; + if (options.retryRequestOptions.shouldRetryFn) { + retryCodes = []; + shouldRetryFn = options.retryRequestOptions.shouldRetryFn; + } + //Backoff settings + options.maxRetries = + (_b = (_a = options === null || options === void 0 ? void 0 : options.retryRequestOptions) === null || _a === void 0 ? void 0 : _a.retries) !== null && _b !== void 0 ? _b : options.maxRetries; + // create a default backoff settings object in case the user didn't provide overrides for everything + const backoffSettings = createDefaultBackoffSettings(); + let maxRetryDelayMillis; + let totalTimeoutMillis; + // maxRetryDelay - this is in seconds, need to convert to milliseconds + if (options.retryRequestOptions.maxRetryDelay !== undefined) { + maxRetryDelayMillis = options.retryRequestOptions.maxRetryDelay * 1000; + } + // retryDelayMultiplier - should be a one to one mapping to retryDelayMultiplier + const retryDelayMultiplier = (_d = (_c = options === null || options === void 0 ? void 0 : options.retryRequestOptions) === null || _c === void 0 ? void 0 : _c.retryDelayMultiplier) !== null && _d !== void 0 ? _d : backoffSettings.retryDelayMultiplier; + // this is in seconds and needs to be converted to milliseconds and the totalTimeoutMillis parameter + if (options.retryRequestOptions.totalTimeout !== undefined) { + totalTimeoutMillis = options.retryRequestOptions.totalTimeout * 1000; + } + else { + if (options.maxRetries === undefined) { + totalTimeoutMillis = 30000; + (0, warnings_1.warn)('retry_request_options_no_max_retries_timeout', 'Neither maxRetries nor totalTimeout were passed. Defaulting to totalTimeout of 30000ms.', 'MissingParameterWarning'); + } + } + // for the variables the user wants to override, override in the backoff settings object we made + backoffSettings.maxRetryDelayMillis = + maxRetryDelayMillis !== null && maxRetryDelayMillis !== void 0 ? maxRetryDelayMillis : backoffSettings.maxRetryDelayMillis; + backoffSettings.retryDelayMultiplier = + retryDelayMultiplier !== null && retryDelayMultiplier !== void 0 ? retryDelayMultiplier : backoffSettings.retryDelayMultiplier; + backoffSettings.totalTimeoutMillis = + totalTimeoutMillis !== null && totalTimeoutMillis !== void 0 ? totalTimeoutMillis : backoffSettings.totalTimeoutMillis; + const convertedRetryOptions = createRetryOptions(retryCodes, backoffSettings, shouldRetryFn); + options.retry = convertedRetryOptions; + delete options.retryRequestOptions; // completely remove them to avoid any further confusion + (0, warnings_1.warn)('retry_request_options', 'retryRequestOptions will be deprecated in a future release. Please use retryOptions to pass retry options at call time', 'DeprecationWarning'); + } + return options; +} +/** + * Per-call configurable settings for retrying upon transient failure. + * @param {number[]} retryCodes - a list of Google API canonical error codes OR a function that returns a boolean to determine retry behavior + * upon which a retry should be attempted. + * @param {BackoffSettings} backoffSettings - configures the retry + * exponential backoff algorithm. + * @param {function} shouldRetryFn - a function that determines whether a call should retry. If this is defined retryCodes must be empty + * @param {function} getResumptionRequestFn - a function with a resumption strategy - only used with server streaming retries + * @return {RetryOptions} A new RetryOptions object. + * + */ +function createRetryOptions(retryCodes, backoffSettings, shouldRetryFn, getResumptionRequestFn) { + return { + retryCodes, + backoffSettings, + shouldRetryFn, + getResumptionRequestFn, + }; +} +/** + * Parameters to the exponential backoff algorithm for retrying. + * + * @param {number} initialRetryDelayMillis - the initial delay time, + * in milliseconds, between the completion of the first failed request and the + * initiation of the first retrying request. + * @param {number} retryDelayMultiplier - the multiplier by which to + * increase the delay time between the completion of failed requests, and the + * initiation of the subsequent retrying request. + * @param {number} maxRetryDelayMillis - the maximum delay time, in + * milliseconds, between requests. When this value is reached, + * ``retryDelayMultiplier`` will no longer be used to increase delay time. + * @param {number} initialRpcTimeoutMillis - the initial timeout parameter + * to the request. + * @param {number} rpcTimeoutMultiplier - the multiplier by which to + * increase the timeout parameter between failed requests. + * @param {number} maxRpcTimeoutMillis - the maximum timeout parameter, in + * milliseconds, for a request. When this value is reached, + * ``rpcTimeoutMultiplier`` will no longer be used to increase the timeout. + * @param {number} totalTimeoutMillis - the total time, in milliseconds, + * starting from when the initial request is sent, after which an error will + * be returned, regardless of the retrying attempts made meanwhile. + * @return {BackoffSettings} a new settings. + * + */ +function createBackoffSettings(initialRetryDelayMillis, retryDelayMultiplier, maxRetryDelayMillis, initialRpcTimeoutMillis, rpcTimeoutMultiplier, maxRpcTimeoutMillis, totalTimeoutMillis) { + return { + initialRetryDelayMillis, + retryDelayMultiplier, + maxRetryDelayMillis, + initialRpcTimeoutMillis, + rpcTimeoutMultiplier, + maxRpcTimeoutMillis, + totalTimeoutMillis, + }; +} +function createDefaultBackoffSettings() { + return createBackoffSettings(100, 1.3, 60000, null, null, null, null); +} +/** + * Parameters to the exponential backoff algorithm for retrying. + * This function is unsupported, and intended for internal use only. + * + * @param {number} initialRetryDelayMillis - the initial delay time, + * in milliseconds, between the completion of the first failed request and the + * initiation of the first retrying request. + * @param {number} retryDelayMultiplier - the multiplier by which to + * increase the delay time between the completion of failed requests, and the + * initiation of the subsequent retrying request. + * @param {number} maxRetryDelayMillis - the maximum delay time, in + * milliseconds, between requests. When this value is reached, + * ``retryDelayMultiplier`` will no longer be used to increase delay time. + * @param {number} initialRpcTimeoutMillis - the initial timeout parameter + * to the request. + * @param {number} rpcTimeoutMultiplier - the multiplier by which to + * increase the timeout parameter between failed requests. + * @param {number} maxRpcTimeoutMillis - the maximum timeout parameter, in + * milliseconds, for a request. When this value is reached, + * ``rpcTimeoutMultiplier`` will no longer be used to increase the timeout. + * @param {number} maxRetries - the maximum number of retrying attempts that + * will be made. If reached, an error will be returned. + * @return {BackoffSettings} a new settings. + * + */ +function createMaxRetriesBackoffSettings(initialRetryDelayMillis, retryDelayMultiplier, maxRetryDelayMillis, initialRpcTimeoutMillis, rpcTimeoutMultiplier, maxRpcTimeoutMillis, maxRetries) { + return { + initialRetryDelayMillis, + retryDelayMultiplier, + maxRetryDelayMillis, + initialRpcTimeoutMillis, + rpcTimeoutMultiplier, + maxRpcTimeoutMillis, + maxRetries, + }; +} +/** + * Creates a new {@link BundleOptions}. + * + * @private + * @param {Object} options - An object to hold optional parameters. See + * properties for the content of options. + * @return {BundleOptions} - A new options. + */ +function createBundleOptions(options) { + const params = [ + 'element_count_threshold', + 'element_count_limit', + 'request_byte_threshold', + 'request_byte_limit', + 'delay_threshold_millis', + ]; + params.forEach(param => { + if (param in options && typeof options[param] !== 'number') { + throw new Error(`${param} should be a number`); + } + }); + const elementCountThreshold = options.element_count_threshold || 0; + const elementCountLimit = options.element_count_limit || 0; + const requestByteThreshold = options.request_byte_threshold || 0; + const requestByteLimit = options.request_byte_limit || 0; + const delayThreshold = options.delay_threshold_millis || 0; + if (elementCountThreshold === 0 && + requestByteThreshold === 0 && + delayThreshold === 0) { + throw new Error('one threshold should be > 0'); + } + return { + elementCountThreshold, + elementCountLimit, + requestByteThreshold, + requestByteLimit, + delayThreshold, + }; +} +/** + * Helper for {@link constructSettings} + * + * @private + * + * @param {Object} methodConfig - A dictionary representing a single + * `methods` entry of the standard API client config file. (See + * {@link constructSettings} for information on this yaml.) + * @param {?Object} retryCodes - A dictionary parsed from the + * `retry_codes_def` entry of the standard API client config + * file. (See {@link constructSettings} for information on this yaml.) + * @param {Object} retryParams - A dictionary parsed from the + * `retry_params` entry of the standard API client config + * file. (See {@link constructSettings} for information on this yaml.) + * @param {Object} retryNames - A dictionary mapping the string names + * used in the standard API client config file to API response + * status codes. + * @return {?RetryOptions} The new retry options. + */ +function constructRetry(methodConfig, retryCodes, retryParams, retryNames) { + if (!methodConfig) { + return null; + } + let codes = null; // this is one instance where it will NOT be an array OR a function because we do not allow shouldRetryFn in the client + if (retryCodes && 'retry_codes_name' in methodConfig) { + const retryCodesName = methodConfig['retry_codes_name']; + codes = (retryCodes[retryCodesName] || []).map(name => { + return Number(retryNames[name]); + }); + } + let backoffSettings = null; + if (retryParams && 'retry_params_name' in methodConfig) { + const params = retryParams[methodConfig.retry_params_name]; + backoffSettings = createBackoffSettings(params.initial_retry_delay_millis, params.retry_delay_multiplier, params.max_retry_delay_millis, params.initial_rpc_timeout_millis, params.rpc_timeout_multiplier, params.max_rpc_timeout_millis, params.total_timeout_millis); + } + return createRetryOptions(codes, backoffSettings); +} +/** + * Helper for {@link constructSettings} + * + * Takes two retry options, and merges them into a single RetryOption instance. + * + * @private + * + * @param {RetryOptions} retry - The base RetryOptions. + * @param {RetryOptions} overrides - The RetryOptions used for overriding + * `retry`. Use the values if it is not null. If entire `overrides` is null, + * ignore the base retry and return null. + * @return {?RetryOptions} The merged RetryOptions. + */ +function mergeRetryOptions(retry, overrides) { + if (!overrides) { + return null; + } + if (!overrides.retryCodes && + !overrides.backoffSettings && + !overrides.shouldRetryFn && + !overrides.getResumptionRequestFn) { + return retry; + } + const retryCodes = overrides.retryCodes + ? overrides.retryCodes + : retry.retryCodes; + const backoffSettings = overrides.backoffSettings + ? overrides.backoffSettings + : retry.backoffSettings; + const shouldRetryFn = overrides.shouldRetryFn + ? overrides.shouldRetryFn + : retry.shouldRetryFn; + const getResumptionRequestFn = overrides.getResumptionRequestFn + ? overrides.getResumptionRequestFn + : retry.getResumptionRequestFn; + return createRetryOptions(retryCodes, backoffSettings, shouldRetryFn, getResumptionRequestFn); +} +/** + * Constructs a dictionary mapping method names to {@link CallSettings}. + * + * The `clientConfig` parameter is parsed from a client configuration JSON + * file of the form: + * + * { + * "interfaces": { + * "google.fake.v1.ServiceName": { + * "retry_codes": { + * "idempotent": ["UNAVAILABLE", "DEADLINE_EXCEEDED"], + * "non_idempotent": [] + * }, + * "retry_params": { + * "default": { + * "initial_retry_delay_millis": 100, + * "retry_delay_multiplier": 1.2, + * "max_retry_delay_millis": 1000, + * "initial_rpc_timeout_millis": 2000, + * "rpc_timeout_multiplier": 1.5, + * "max_rpc_timeout_millis": 30000, + * "total_timeout_millis": 45000 + * } + * }, + * "methods": { + * "CreateFoo": { + * "retry_codes_name": "idempotent", + * "retry_params_name": "default" + * }, + * "Publish": { + * "retry_codes_name": "non_idempotent", + * "retry_params_name": "default", + * "bundling": { + * "element_count_threshold": 40, + * "element_count_limit": 200, + * "request_byte_threshold": 90000, + * "request_byte_limit": 100000, + * "delay_threshold_millis": 100 + * } + * } + * } + * } + * } + * } + * + * @param {String} serviceName - The fully-qualified name of this + * service, used as a key into the client config file (in the + * example above, this value should be 'google.fake.v1.ServiceName'). + * @param {Object} clientConfig - A dictionary parsed from the + * standard API client config file. + * @param {Object} configOverrides - A dictionary in the same structure of + * client_config to override the settings. + * @param {Object.} retryNames - A dictionary mapping the strings + * referring to response status codes to objects representing + * those codes. + * @param {Object} otherArgs - the non-request arguments to be passed to the API + * calls. + * @return {Object} A mapping from method name to CallSettings, or null if the + * service is not found in the config. + */ +function constructSettings(serviceName, clientConfig, configOverrides, retryNames, otherArgs) { + otherArgs = otherArgs || {}; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const defaults = {}; + const serviceConfig = (clientConfig.interfaces || {})[serviceName]; + if (!serviceConfig) { + return null; + } + // users can override the config from client side, like bundling options. + // The detailed structure of the clientConfig can be found here: https://github.com/googleapis/gax-nodejs/blob/main/src/gax.ts#L546 + // The way to override bundling options: + // + // const customConfig = {"interfaces": {"service": {"methods": {"methodName": {"bundling": {..}}}}}} + // const client = new Client({ projectId, customConfig }); + const overrides = (configOverrides.interfaces || {})[serviceName] || {}; + const methods = serviceConfig.methods; + const overridingMethods = overrides.methods || {}; + for (const methodName in methods) { + const methodConfig = methods[methodName]; + const jsName = (0, util_1.toLowerCamelCase)(methodName); + let retry = constructRetry(methodConfig, serviceConfig.retry_codes, serviceConfig.retry_params, retryNames); + let bundlingConfig = methodConfig.bundling; + let timeout = methodConfig.timeout_millis; + if (methodName in overridingMethods) { + const overridingMethod = overridingMethods[methodName]; + if (overridingMethod) { + if ('bundling' in overridingMethod) { + bundlingConfig = overridingMethod.bundling; + } + if ('timeout_millis' in overridingMethod) { + timeout = overridingMethod.timeout_millis; + } + } + retry = mergeRetryOptions(retry, constructRetry(overridingMethod, overrides.retry_codes, overrides.retry_params, retryNames)); + } + const apiName = serviceName; + defaults[jsName] = new CallSettings({ + timeout, + retry, + bundleOptions: bundlingConfig + ? createBundleOptions(bundlingConfig) + : null, + otherArgs, + apiName, + }); + } + return defaults; +} +function createByteLengthFunction(message) { + return function getByteLength(obj) { + try { + return message.encode(obj).finish().length; + } + catch (err) { + const stringified = JSON.stringify(obj); + (0, warnings_1.warn)('error_encoding_protobufjs_object', `Cannot encode protobuf.js object: ${stringified}: ${err}`); + // We failed to encode the object properly, let's just return an upper boundary of its length. + // It's only needed for calculating the size of the batch, so it's safe if it's bigger than needed. + return stringified.length; + } + }; +} +//# sourceMappingURL=gax.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/gax.js.map b/node_modules/google-gax/build/src/gax.js.map new file mode 100644 index 0000000..9c74885 --- /dev/null +++ b/node_modules/google-gax/build/src/gax.js.map @@ -0,0 +1 @@ +{"version":3,"file":"gax.js","sourceRoot":"","sources":["../../src/gax.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAsTH,kDAiGC;AAaD,gDAYC;AA2BD,sDAkBC;AAED,oEAEC;AA2BD,0EAkBC;AAUD,kDAkCC;AA2MD,8CAsEC;AAED,4DAeC;AAr1BD,yCAAgC;AAGhC,iCAAwC;AACxC,qCAAgC;AAGhC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAEH;;;;;;;;GAQG;AACH,MAAa,YAAY;IAKvB,YACE,UAAoB,EACpB,eAAgC,EAChC,aAA+C,EAC/C,sBAA8D;QAE9D,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QACvC,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,sBAAsB,GAAG,sBAAsB,CAAC;IACvD,CAAC;CACF;AAhBD,oCAgBC;AA+ED,MAAa,YAAY;IAevB;;;;;;;;;;;;;;;;;OAiBG;IACH,YAAY,QAAsB;;QAChC,QAAQ,GAAG,QAAQ,IAAI,EAAE,CAAC;QAC1B,IAAI,CAAC,OAAO,GAAG,QAAQ,CAAC,OAAO,IAAI,EAAE,GAAG,IAAI,CAAC;QAC7C,IAAI,CAAC,KAAK,GAAG,QAAQ,CAAC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nC,cAAc,GAAG,gBAAgB,CAAC,QAAQ,CAAC;gBAC7C,CAAC;gBACD,IAAI,gBAAgB,IAAI,gBAAgB,EAAE,CAAC;oBACzC,OAAO,GAAG,gBAAgB,CAAC,cAAc,CAAC;gBAC5C,CAAC;YACH,CAAC;YACD,KAAK,GAAG,iBAAiB,CACvB,KAAM,EACN,cAAc,CACZ,gBAAgB,EAChB,SAAS,CAAC,WAAW,EACrB,SAAS,CAAC,YAAY,EACtB,UAAU,CACV,CACH,CAAC;QACJ,CAAC;QACD,MAAM,OAAO,GAAG,WAAW,CAAC;QAC5B,QAAQ,CAAC,MAAM,CAAC,GAAG,IAAI,YAAY,CAAC;YAClC,OAAO;YACP,KAAK;YACL,aAAa,EAAE,cAAc;gBAC3B,CAAC,CAAC,mBAAmB,CAAC,cAAc,CAAC;gBACrC,CAAC,CAAC,IAAI;YACR,SAAS;YACT,OAAO;SACR,CAAC,CAAC;IACL,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,SAAgB,wBAAwB,CAAC,OAAuB;IAC9D,OAAO,SAAS,aAAa,CAAC,GAAO;QACnC,IAAI,CAAC;YACH,OAAO,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,CAAC;QAC7C,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;YACxC,IAAA,eAAI,EACF,kCAAkC,EAClC,qCAAqC,WAAW,KAAK,GAAG,EAAE,CAC3D,CAAC;YACF,8FAA8F;YAC9F,mGAAmG;YACnG,OAAO,WAAW,CAAC,MAAM,CAAC;QAC5B,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/googleError.d.ts b/node_modules/google-gax/build/src/googleError.d.ts new file mode 100644 index 0000000..1373abe --- /dev/null +++ b/node_modules/google-gax/build/src/googleError.d.ts @@ -0,0 +1,74 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Status } from './status'; +import * as protobuf from 'protobufjs'; +import { Metadata } from './grpc'; +import { JSONValue } from 'proto3-json-serializer'; +export declare class GoogleError extends Error { + code?: Status; + note?: string; + metadata?: Metadata; + statusDetails?: string | protobuf.Message<{}>[]; + reason?: string; + domain?: string; + errorInfoMetadata?: { + [propName: string]: string; + }; + static parseGRPCStatusDetails(err: GoogleError): GoogleError; + static parseHttpError(json: any): GoogleError; +} +export type FallbackServiceError = FallbackStatusObject & Error; +interface FallbackStatusObject { + code: Status; + message: string; + statusDetails: Array<{}>; + reason?: string; + domain?: string; + errorInfoMetadata?: { + string: string; + }; +} +interface ProtobufAny { + type_url: string; + value: Uint8Array; +} +interface GRPCStatusDetailsObject { + details: protobuf.Message<{}>[]; + errorInfo?: ErrorInfo; +} +interface ErrorInfo { + reason: string; + domain: string; + metadata: { + string: string; + }; +} +export declare class GoogleErrorDecoder { + root: protobuf.Root; + anyType: protobuf.Type; + statusType: protobuf.Type; + constructor(); + decodeProtobufAny(anyValue: ProtobufAny): protobuf.Message<{}>; + decodeRpcStatus(buffer: Buffer | ArrayBuffer): FallbackStatusObject; + callErrorFromStatus(status: FallbackStatusObject): FallbackServiceError; + decodeErrorFromBuffer(buffer: Buffer | ArrayBuffer): Error; + decodeGRPCStatusDetails(bufferArr: Buffer[] | ArrayBuffer[]): GRPCStatusDetailsObject; + decodeHTTPError(json: JSONValue): { + [k: string]: any; + }; + decodeHttpStatusDetails(rawDetails: Array): GRPCStatusDetailsObject; +} +export {}; diff --git a/node_modules/google-gax/build/src/googleError.js b/node_modules/google-gax/build/src/googleError.js new file mode 100644 index 0000000..50e4d82 --- /dev/null +++ b/node_modules/google-gax/build/src/googleError.js @@ -0,0 +1,225 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GoogleErrorDecoder = exports.GoogleError = void 0; +const status_1 = require("./status"); +const protobuf = require("protobufjs"); +const serializer = require("proto3-json-serializer"); +const fallback_1 = require("./fallback"); +class GoogleError extends Error { + // Parse details field in google.rpc.status wire over gRPC medatadata. + // Promote google.rpc.ErrorInfo if exist. + static parseGRPCStatusDetails(err) { + const decoder = new GoogleErrorDecoder(); + try { + if (err.metadata && err.metadata.get('grpc-status-details-bin')) { + const statusDetailsObj = decoder.decodeGRPCStatusDetails(err.metadata.get('grpc-status-details-bin')); + if (statusDetailsObj && + statusDetailsObj.details && + statusDetailsObj.details.length > 0) { + err.statusDetails = statusDetailsObj.details; + } + if (statusDetailsObj && statusDetailsObj.errorInfo) { + err.reason = statusDetailsObj.errorInfo.reason; + err.domain = statusDetailsObj.errorInfo.domain; + err.errorInfoMetadata = statusDetailsObj.errorInfo.metadata; + } + } + } + catch (decodeErr) { + // ignoring the error + } + return err; + } + // Parse http JSON error and promote google.rpc.ErrorInfo if exist. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static parseHttpError(json) { + if (Array.isArray(json)) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + json = json.find((obj) => { + return 'error' in obj; + }); + } + // fallback logic. + // related issue: https://github.com/googleapis/gax-nodejs/issues/1303 + // google error mapping: https://cloud.google.com/apis/design/errors + // if input json doesn't have 'error' fields, wrap the whole object with 'error' field + if (!json['error']) { + json['error'] = {}; + Object.keys(json) + .filter(key => key !== 'error') + .forEach(key => { + json['error'][key] = json[key]; + delete json[key]; + }); + } + const decoder = new GoogleErrorDecoder(); + const proto3Error = decoder.decodeHTTPError(json['error']); + const error = Object.assign(new GoogleError(json['error']['message']), proto3Error); + // Map Http Status Code to gRPC Status Code + if (json['error']['code']) { + error.code = (0, status_1.rpcCodeFromHttpStatusCode)(json['error']['code']); + } + else { + // If error code is absent, proto3 message default value is 0. We should + // keep error code as undefined. + delete error.code; + } + // Keep consistency with gRPC statusDetails fields. gRPC details has been occupied before. + // Rename "details" to "statusDetails". + if (error.details) { + try { + const statusDetailsObj = decoder.decodeHttpStatusDetails(error.details); + if (statusDetailsObj && + statusDetailsObj.details && + statusDetailsObj.details.length > 0) { + error.statusDetails = statusDetailsObj.details; + } + if (statusDetailsObj && statusDetailsObj.errorInfo) { + error.reason = statusDetailsObj.errorInfo.reason; + error.domain = statusDetailsObj.errorInfo.domain; + // error.metadata has been occupied for gRPC metadata, so we use + // errorInfoMetadata to represent ErrorInfo' metadata field. Keep + // consistency with gRPC ErrorInfo metadata field name. + error.errorInfoMetadata = statusDetailsObj.errorInfo.metadata; + } + } + catch (decodeErr) { + // ignoring the error + } + } + return error; + } +} +exports.GoogleError = GoogleError; +class GoogleErrorDecoder { + constructor() { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const errorProtoJson = require('../../build/protos/status.json'); + this.root = protobuf.Root.fromJSON(errorProtoJson); + this.anyType = this.root.lookupType('google.protobuf.Any'); + this.statusType = this.root.lookupType('google.rpc.Status'); + } + decodeProtobufAny(anyValue) { + const match = anyValue.type_url.match(/^type.googleapis.com\/(.*)/); + if (!match) { + throw new Error(`Unknown type encoded in google.protobuf.any: ${anyValue.type_url}`); + } + const typeName = match[1]; + const type = this.root.lookupType(typeName); + if (!type) { + throw new Error(`Cannot lookup type ${typeName}`); + } + return type.decode(anyValue.value); + } + // Decodes gRPC-fallback error which is an instance of google.rpc.Status. + decodeRpcStatus(buffer) { + const uint8array = new Uint8Array(buffer); + const status = this.statusType.decode(uint8array); + // google.rpc.Status contains an array of google.protobuf.Any + // which need a special treatment + const details = []; + let errorInfo; + for (const detail of status.details) { + try { + const decodedDetail = this.decodeProtobufAny(detail); + details.push(decodedDetail); + if (detail.type_url === 'type.googleapis.com/google.rpc.ErrorInfo') { + errorInfo = decodedDetail; + } + } + catch (err) { + // cannot decode detail, likely because of the unknown type - just skip it + } + } + const result = { + code: status.code, + message: status.message, + statusDetails: details, + reason: errorInfo === null || errorInfo === void 0 ? void 0 : errorInfo.reason, + domain: errorInfo === null || errorInfo === void 0 ? void 0 : errorInfo.domain, + errorInfoMetadata: errorInfo === null || errorInfo === void 0 ? void 0 : errorInfo.metadata, + }; + return result; + } + // Construct an Error from a StatusObject. + // Adapted from https://github.com/grpc/grpc-node/blob/main/packages/grpc-js/src/call.ts#L79 + callErrorFromStatus(status) { + status.message = `${status.code} ${status_1.Status[status.code]}: ${status.message}`; + return Object.assign(new GoogleError(status.message), status); + } + // Decodes gRPC-fallback error which is an instance of google.rpc.Status, + // and puts it into the object similar to gRPC ServiceError object. + decodeErrorFromBuffer(buffer) { + return this.callErrorFromStatus(this.decodeRpcStatus(buffer)); + } + // Decodes gRPC metadata error details which is an instance of google.rpc.Status. + decodeGRPCStatusDetails(bufferArr) { + const details = []; + let errorInfo; + bufferArr.forEach(buffer => { + const uint8array = new Uint8Array(buffer); + const rpcStatus = this.statusType.decode(uint8array); + for (const detail of rpcStatus.details) { + try { + const decodedDetail = this.decodeProtobufAny(detail); + details.push(decodedDetail); + if (detail.type_url === 'type.googleapis.com/google.rpc.ErrorInfo') { + errorInfo = decodedDetail; + } + } + catch (err) { + // cannot decode detail, likely because of the unknown type - just skip it + } + } + }); + const result = { + details, + errorInfo, + }; + return result; + } + // Decodes http error which is an instance of google.rpc.Status. + decodeHTTPError(json) { + const errorMessage = serializer.fromProto3JSON(this.statusType, json); + if (!errorMessage) { + throw new Error(`Received error message ${json}, but failed to serialize as proto3 message`); + } + return this.statusType.toObject(errorMessage, fallback_1.defaultToObjectOptions); + } + // Decodes http error details which is an instance of Array. + decodeHttpStatusDetails(rawDetails) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const details = []; + let errorInfo; + for (const detail of rawDetails) { + try { + const decodedDetail = this.decodeProtobufAny(detail); + details.push(decodedDetail); + if (detail.type_url === 'type.googleapis.com/google.rpc.ErrorInfo') { + errorInfo = decodedDetail; + } + } + catch (err) { + // cannot decode detail, likely because of the unknown type - just skip it + } + } + return { details, errorInfo }; + } +} +exports.GoogleErrorDecoder = GoogleErrorDecoder; +//# sourceMappingURL=googleError.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/googleError.js.map b/node_modules/google-gax/build/src/googleError.js.map new file mode 100644 index 0000000..3ea5deb --- /dev/null +++ b/node_modules/google-gax/build/src/googleError.js.map @@ -0,0 +1 @@ +{"version":3,"file":"googleError.js","sourceRoot":"","sources":["../../src/googleError.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,qCAA2D;AAC3D,uCAAuC;AAEvC,qDAAqD;AACrD,yCAAkD;AAGlD,MAAa,WAAY,SAAQ,KAAK;IASpC,sEAAsE;IACtE,yCAAyC;IACzC,MAAM,CAAC,sBAAsB,CAAC,GAAgB;QAC5C,MAAM,OAAO,GAAG,IAAI,kBAAkB,EAAE,CAAC;QACzC,IAAI,CAAC;YACH,IAAI,GAAG,CAAC,QAAQ,IAAI,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,yBAAyB,CAAC,EAAE,CAAC;gBAChE,MAAM,gBAAgB,GACpB,OAAO,CAAC,uBAAuB,CAC7B,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,yBAAyB,CAAO,CAClD,CAAC;gBACJ,IACE,gBAAgB;oBAChB,gBAAgB,CAAC,OAAO;oBACxB,gBAAgB,CAAC,OAAO,CAAC,MAAM,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AiF;IACjF,uBAAuB,CACrB,UAA8B;QAE9B,6DAA6D;QAC7D,MAAM,OAAO,GAA2B,EAAE,CAAC;QAC3C,IAAI,SAAS,CAAC;QACd,KAAK,MAAM,MAAM,IAAI,UAAU,EAAE,CAAC;YAChC,IAAI,CAAC;gBACH,MAAM,aAAa,GAAG,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC;gBACrD,OAAO,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;gBAC5B,IAAI,MAAM,CAAC,QAAQ,KAAK,0CAA0C,EAAE,CAAC;oBACnE,SAAS,GAAG,aAAqC,CAAC;gBACpD,CAAC;YACH,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,0EAA0E;YAC5E,CAAC;QACH,CAAC;QACD,OAAO,EAAC,OAAO,EAAE,SAAS,EAAC,CAAC;IAC9B,CAAC;CACF;AArID,gDAqIC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/grpc.d.ts b/node_modules/google-gax/build/src/grpc.d.ts new file mode 100644 index 0000000..a99b72d --- /dev/null +++ b/node_modules/google-gax/build/src/grpc.d.ts @@ -0,0 +1,190 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as grpcProtoLoader from '@grpc/proto-loader'; +import { GoogleAuth, GoogleAuthOptions } from 'google-auth-library'; +import * as grpc from '@grpc/grpc-js'; +import { OutgoingHttpHeaders } from 'http'; +import * as protobuf from 'protobufjs'; +import * as gax from './gax'; +import { ClientOptions } from '@grpc/grpc-js/build/src/client'; +import { google } from '../protos/http'; +export interface GrpcClientOptions extends GoogleAuthOptions { + auth?: GoogleAuth; + grpc?: GrpcModule; + protoJson?: protobuf.Root; + httpRules?: Array; + numericEnums?: boolean; + universeDomain?: string; +} +export interface MetadataValue { + equals: Function; +} +export interface Metadata { + new (): Metadata; + set: (key: {}, value?: {} | null) => void; + clone: () => Metadata; + value: MetadataValue; + get: (key: {}) => {}; +} +export type GrpcModule = typeof grpc; +export interface ClientStubOptions { + protocol?: string; + servicePath?: string; + port?: number; + sslCreds?: grpc.ChannelCredentials; + [index: string]: string | number | undefined | {}; + cert?: string; + key?: string; + universeDomain?: string; +} +export declare class ClientStub extends grpc.Client { + [name: string]: Function; +} +export declare class GrpcClient { + auth: GoogleAuth; + grpc: GrpcModule; + grpcVersion: string; + fallback: boolean | 'rest' | 'proto'; + private static protoCache; + httpRules?: Array; + /** + * Key for proto cache map. We are doing our best to make sure we respect + * the options, so if the same proto file is loaded with different set of + * options, the cache won't be used. Since some of the options are + * Functions (e.g. `enums: String` - see below in `loadProto()`), + * they will be omitted from the cache key. If the cache breaks anything + * for you, use the `ignoreCache` parameter of `loadProto()` to disable it. + */ + private static protoCacheKey; + /** + * In rare cases users might need to deallocate all memory consumed by loaded protos. + * This method will delete the proto cache content. + */ + static clearProtoCache(): void; + /** + * A class which keeps the context of gRPC and auth for the gRPC. + * + * @param {Object=} options - The optional parameters. It will be directly + * passed to google-auth-library library, so parameters like keyFile or + * credentials will be valid. + * @param {Object=} options.auth - An instance of google-auth-library. + * When specified, this auth instance will be used instead of creating + * a new one. + * @param {Object=} options.grpc - When specified, this will be used + * for the 'grpc' module in this context. By default, it will load the grpc + * module in the standard way. + * @constructor + */ + constructor(options?: GrpcClientOptions); + /** + * Creates a gRPC credentials. It asks the auth data if necessary. + * @private + * @param {Object} opts - options values for configuring credentials. + * @param {Object=} opts.sslCreds - when specified, this is used instead + * of default channel credentials. + * @return {Promise} The promise which will be resolved to the gRPC credential. + */ + _getCredentials(opts: ClientStubOptions): Promise; + private static defaultOptions; + /** + * Loads the gRPC service from the proto file(s) at the given path and with the + * given options. Caches the loaded protos so the subsequent loads don't do + * any disk reads. + * @param filename The path to the proto file(s). + * @param options Options for loading the proto file. + * @param ignoreCache Defaults to `false`. Set it to `true` if the caching logic + * incorrectly decides that the options object is the same, or if you want to + * re-read the protos from disk for any other reason. + */ + loadFromProto(filename: string | string[], options: grpcProtoLoader.Options, ignoreCache?: boolean): grpc.GrpcObject; + /** + * Load gRPC proto service from a filename looking in googleapis common protos + * when necessary. Caches the loaded protos so the subsequent loads don't do + * any disk reads. + * @param {String} protoPath - The directory to search for the protofile. + * @param {String|String[]} filename - The filename(s) of the proto(s) to be loaded. + * If omitted, protoPath will be treated as a file path to load. + * @param ignoreCache Defaults to `false`. Set it to `true` if the caching logic + * incorrectly decides that the options object is the same, or if you want to + * re-read the protos from disk for any other reason. + * @return {Object} The gRPC loaded result (the toplevel namespace + * object). + */ + loadProto(protoPath: string, filename?: string | string[], ignoreCache?: boolean): grpc.GrpcObject; + static _resolveFile(protoPath: string, filename: string): string; + loadProtoJSON(json: protobuf.INamespace, ignoreCache?: boolean): grpc.GrpcObject; + metadataBuilder(headers: OutgoingHttpHeaders): (abTests?: {}, moreHeaders?: OutgoingHttpHeaders) => grpc.Metadata; + /** + * A wrapper of {@link constructSettings} function under the gRPC context. + * + * Most of parameters are common among constructSettings, please take a look. + * @param {string} serviceName - The fullly-qualified name of the service. + * @param {Object} clientConfig - A dictionary of the client config. + * @param {Object} configOverrides - A dictionary of overriding configs. + * @param {Object} headers - A dictionary of additional HTTP header name to + * its value. + * @return {Object} A mapping of method names to CallSettings. + */ + constructSettings(serviceName: string, clientConfig: gax.ClientConfig, configOverrides: gax.ClientConfig, headers: OutgoingHttpHeaders): any; + /** + * Creates a gRPC stub with current gRPC and auth. + * @param {function} CreateStub - The constructor function of the stub. + * @param {Object} options - The optional arguments to customize + * gRPC connection. This options will be passed to the constructor of + * gRPC client too. + * @param {string} options.servicePath - The name of the server of the service. + * @param {number} options.port - The port of the service. + * @param {grpcTypes.ClientCredentials=} options.sslCreds - The credentials to be used + * to set up gRPC connection. + * @param {string} defaultServicePath - The default service path. + * @return {Promise} A promise which resolves to a gRPC stub instance. + */ + createStub(CreateStub: typeof ClientStub, options: ClientStubOptions, customServicePath?: boolean): Promise; + /** + * Detect mTLS client certificate based on logic described in + * https://google.aip.dev/auth/4114. + * + * @param {object} [options] - The configuration object. + * @returns {Promise} Resolves array of strings representing cert and key. + */ + _detectClientCertificate(opts?: ClientOptions, universeDomain?: string): Promise; + /** + * Return service path, taking into account mTLS logic. + * See: https://google.aip.dev/auth/4114 + * + * @param {string|undefined} servicePath - The path of the service. + * @param {string|undefined} customServicePath - Did the user provide a custom service URL. + * @param {boolean} hasCertificate - Was a certificate found. + * @returns {string} The DNS address for this service. + */ + _mtlsServicePath(servicePath: string | undefined, customServicePath: boolean | undefined, hasCertificate: boolean): string | undefined; + /** + * Creates a 'bytelength' function for a given proto message class. + * + * See {@link BundleDescriptor} about the meaning of the return value. + * + * @param {function} message - a constructor function that is generated by + * protobuf.js. Assumes 'encoder' field in the message. + * @return {function(Object):number} - a function to compute the byte length + * for an object. + */ + static createByteLengthFunction(message: typeof protobuf.Message): (obj: {}) => number; +} +export declare class GoogleProtoFilesRoot extends protobuf.Root { + constructor(...args: Array<{}>); + resolvePath(originPath: string, includePath: string): string; + static _findIncludePath(originPath: string, includePath: string): string; +} diff --git a/node_modules/google-gax/build/src/grpc.js b/node_modules/google-gax/build/src/grpc.js new file mode 100644 index 0000000..3394e69 --- /dev/null +++ b/node_modules/google-gax/build/src/grpc.js @@ -0,0 +1,469 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GoogleProtoFilesRoot = exports.GrpcClient = exports.ClientStub = void 0; +const grpcProtoLoader = require("@grpc/proto-loader"); +const child_process_1 = require("child_process"); +const fs = require("fs"); +const google_auth_library_1 = require("google-auth-library"); +const grpc = require("@grpc/grpc-js"); +const os = require("os"); +const path_1 = require("path"); +const path = require("path"); +const protobuf = require("protobufjs"); +const objectHash = require("object-hash"); +const gax = require("./gax"); +const googleProtoFilesDir = path.join(__dirname, '..', '..', 'build', 'protos'); +// INCLUDE_DIRS is passed to @grpc/proto-loader +const INCLUDE_DIRS = []; +INCLUDE_DIRS.push(googleProtoFilesDir); +// COMMON_PROTO_FILES logic is here for protobufjs loads (see +// GoogleProtoFilesRoot below) +const commonProtoFiles = require("./protosList.json"); +// use the correct path separator for the OS we are running on +const COMMON_PROTO_FILES = commonProtoFiles.map(file => file.replace(/[/\\]/g, path.sep)); +/* + * Async version of readFile. + * + * @returns {Promise} Contents of file at path. + */ +async function readFileAsync(path) { + return new Promise((resolve, reject) => { + fs.readFile(path, 'utf8', (err, content) => { + if (err) + return reject(err); + else + resolve(content); + }); + }); +} +/* + * Async version of execFile. + * + * @returns {Promise} stdout from command execution. + */ +async function execFileAsync(command, args) { + return new Promise((resolve, reject) => { + (0, child_process_1.execFile)(command, args, (err, stdout) => { + if (err) + return reject(err); + else + resolve(stdout); + }); + }); +} +class ClientStub extends grpc.Client { +} +exports.ClientStub = ClientStub; +class GrpcClient { + /** + * Key for proto cache map. We are doing our best to make sure we respect + * the options, so if the same proto file is loaded with different set of + * options, the cache won't be used. Since some of the options are + * Functions (e.g. `enums: String` - see below in `loadProto()`), + * they will be omitted from the cache key. If the cache breaks anything + * for you, use the `ignoreCache` parameter of `loadProto()` to disable it. + */ + static protoCacheKey(filename, options) { + if (!filename || + (Array.isArray(filename) && (filename.length === 0 || !filename[0]))) { + return undefined; + } + return JSON.stringify(filename) + ' ' + JSON.stringify(options); + } + /** + * In rare cases users might need to deallocate all memory consumed by loaded protos. + * This method will delete the proto cache content. + */ + static clearProtoCache() { + GrpcClient.protoCache.clear(); + } + /** + * A class which keeps the context of gRPC and auth for the gRPC. + * + * @param {Object=} options - The optional parameters. It will be directly + * passed to google-auth-library library, so parameters like keyFile or + * credentials will be valid. + * @param {Object=} options.auth - An instance of google-auth-library. + * When specified, this auth instance will be used instead of creating + * a new one. + * @param {Object=} options.grpc - When specified, this will be used + * for the 'grpc' module in this context. By default, it will load the grpc + * module in the standard way. + * @constructor + */ + constructor(options = {}) { + var _a; + this.auth = options.auth || new google_auth_library_1.GoogleAuth(options); + this.fallback = false; + const minimumVersion = 10; + const major = Number((_a = process.version.match(/^v(\d+)/)) === null || _a === void 0 ? void 0 : _a[1]); + if (Number.isNaN(major) || major < minimumVersion) { + const errorMessage = `Node.js v${minimumVersion}.0.0 is a minimum requirement. To learn about legacy version support visit: ` + + 'https://github.com/googleapis/google-cloud-node#supported-nodejs-versions'; + throw new Error(errorMessage); + } + if ('grpc' in options) { + this.grpc = options.grpc; + this.grpcVersion = ''; + } + else { + this.grpc = grpc; + this.grpcVersion = require('@grpc/grpc-js/package.json').version; + } + } + /** + * Creates a gRPC credentials. It asks the auth data if necessary. + * @private + * @param {Object} opts - options values for configuring credentials. + * @param {Object=} opts.sslCreds - when specified, this is used instead + * of default channel credentials. + * @return {Promise} The promise which will be resolved to the gRPC credential. + */ + async _getCredentials(opts) { + if (opts.sslCreds) { + return opts.sslCreds; + } + const grpc = this.grpc; + const sslCreds = opts.cert && opts.key + ? grpc.credentials.createSsl(null, Buffer.from(opts.key), Buffer.from(opts.cert)) + : grpc.credentials.createSsl(); + const client = await this.auth.getClient(); + const credentials = grpc.credentials.combineChannelCredentials(sslCreds, grpc.credentials.createFromGoogleCredential(client)); + return credentials; + } + static defaultOptions() { + // This set of @grpc/proto-loader options + // 'closely approximates the existing behavior of grpc.load' + const includeDirs = INCLUDE_DIRS.slice(); + const options = { + keepCase: false, + longs: String, + enums: String, + defaults: true, + oneofs: true, + includeDirs, + }; + return options; + } + /** + * Loads the gRPC service from the proto file(s) at the given path and with the + * given options. Caches the loaded protos so the subsequent loads don't do + * any disk reads. + * @param filename The path to the proto file(s). + * @param options Options for loading the proto file. + * @param ignoreCache Defaults to `false`. Set it to `true` if the caching logic + * incorrectly decides that the options object is the same, or if you want to + * re-read the protos from disk for any other reason. + */ + loadFromProto(filename, options, ignoreCache = false) { + const cacheKey = GrpcClient.protoCacheKey(filename, options); + let grpcPackage = cacheKey + ? GrpcClient.protoCache.get(cacheKey) + : undefined; + if (ignoreCache || !grpcPackage) { + const packageDef = grpcProtoLoader.loadSync(filename, options); + grpcPackage = this.grpc.loadPackageDefinition(packageDef); + if (cacheKey) { + GrpcClient.protoCache.set(cacheKey, grpcPackage); + } + } + return grpcPackage; + } + /** + * Load gRPC proto service from a filename looking in googleapis common protos + * when necessary. Caches the loaded protos so the subsequent loads don't do + * any disk reads. + * @param {String} protoPath - The directory to search for the protofile. + * @param {String|String[]} filename - The filename(s) of the proto(s) to be loaded. + * If omitted, protoPath will be treated as a file path to load. + * @param ignoreCache Defaults to `false`. Set it to `true` if the caching logic + * incorrectly decides that the options object is the same, or if you want to + * re-read the protos from disk for any other reason. + * @return {Object} The gRPC loaded result (the toplevel namespace + * object). + */ + loadProto(protoPath, filename, ignoreCache = false) { + if (!filename) { + filename = path.basename(protoPath); + protoPath = path.dirname(protoPath); + } + if (Array.isArray(filename) && filename.length === 0) { + return {}; + } + const options = GrpcClient.defaultOptions(); + options.includeDirs.unshift(protoPath); + return this.loadFromProto(filename, options, ignoreCache); + } + static _resolveFile(protoPath, filename) { + if (fs.existsSync(path.join(protoPath, filename))) { + return path.join(protoPath, filename); + } + else if (COMMON_PROTO_FILES.indexOf(filename) > -1) { + return path.join(googleProtoFilesDir, filename); + } + throw new Error(filename + ' could not be found in ' + protoPath); + } + loadProtoJSON(json, ignoreCache = false) { + const hash = objectHash(JSON.stringify(json)).toString(); + const cached = GrpcClient.protoCache.get(hash); + if (cached && !ignoreCache) { + return cached; + } + const options = GrpcClient.defaultOptions(); + const packageDefinition = grpcProtoLoader.fromJSON(json, options); + const grpcPackage = this.grpc.loadPackageDefinition(packageDefinition); + GrpcClient.protoCache.set(hash, grpcPackage); + return grpcPackage; + } + metadataBuilder(headers) { + const Metadata = this.grpc.Metadata; + const baseMetadata = new Metadata(); + for (const key in headers) { + const value = headers[key]; + if (Array.isArray(value)) { + value.forEach(v => baseMetadata.add(key, v)); + } + else { + baseMetadata.set(key, `${value}`); + } + } + return function buildMetadata(abTests, moreHeaders) { + // TODO: bring the A/B testing info into the metadata. + let copied = false; + let metadata = baseMetadata; + if (moreHeaders) { + for (const key in moreHeaders) { + if (key.toLowerCase() !== 'x-goog-api-client') { + if (!copied) { + copied = true; + metadata = metadata.clone(); + } + const value = moreHeaders[key]; + if (Array.isArray(value)) { + value.forEach(v => metadata.add(key, v)); + } + else { + metadata.set(key, `${value}`); + } + } + } + } + return metadata; + }; + } + /** + * A wrapper of {@link constructSettings} function under the gRPC context. + * + * Most of parameters are common among constructSettings, please take a look. + * @param {string} serviceName - The fullly-qualified name of the service. + * @param {Object} clientConfig - A dictionary of the client config. + * @param {Object} configOverrides - A dictionary of overriding configs. + * @param {Object} headers - A dictionary of additional HTTP header name to + * its value. + * @return {Object} A mapping of method names to CallSettings. + */ + constructSettings(serviceName, clientConfig, configOverrides, headers) { + return gax.constructSettings(serviceName, clientConfig, configOverrides, this.grpc.status, { metadataBuilder: this.metadataBuilder(headers) }); + } + /** + * Creates a gRPC stub with current gRPC and auth. + * @param {function} CreateStub - The constructor function of the stub. + * @param {Object} options - The optional arguments to customize + * gRPC connection. This options will be passed to the constructor of + * gRPC client too. + * @param {string} options.servicePath - The name of the server of the service. + * @param {number} options.port - The port of the service. + * @param {grpcTypes.ClientCredentials=} options.sslCreds - The credentials to be used + * to set up gRPC connection. + * @param {string} defaultServicePath - The default service path. + * @return {Promise} A promise which resolves to a gRPC stub instance. + */ + async createStub(CreateStub, options, customServicePath) { + // The following options are understood by grpc-gcp and need a special treatment + // (should be passed without a `grpc.` prefix) + const grpcGcpOptions = [ + 'grpc.callInvocationTransformer', + 'grpc.channelFactoryOverride', + 'grpc.gcpApiConfig', + ]; + const [cert, key] = await this._detectClientCertificate(options, options.universeDomain); + const servicePath = this._mtlsServicePath(options.servicePath, customServicePath, cert && key); + const opts = Object.assign({}, options, { cert, key, servicePath }); + const serviceAddress = servicePath + ':' + opts.port; + if (!options.universeDomain) { + options.universeDomain = 'googleapis.com'; + } + if (options.universeDomain) { + const universeFromAuth = await this.auth.getUniverseDomain(); + if (universeFromAuth && options.universeDomain !== universeFromAuth) { + throw new Error(`The configured universe domain (${options.universeDomain}) does not match the universe domain found in the credentials (${universeFromAuth}). ` + + "If you haven't configured the universe domain explicitly, googleapis.com is the default."); + } + } + const creds = await this._getCredentials(opts); + const grpcOptions = {}; + // @grpc/grpc-js limits max receive/send message length starting from v0.8.0 + // https://github.com/grpc/grpc-node/releases/tag/%40grpc%2Fgrpc-js%400.8.0 + // To keep the existing behavior and avoid libraries breakage, we pass -1 there as suggested. + grpcOptions['grpc.max_receive_message_length'] = -1; + grpcOptions['grpc.max_send_message_length'] = -1; + grpcOptions['grpc.initial_reconnect_backoff_ms'] = 1000; + Object.keys(opts).forEach(key => { + const value = options[key]; + // the older versions had a bug which required users to call an option + // grpc.grpc.* to make it actually pass to gRPC as grpc.*, let's handle + // this here until the next major release + if (key.startsWith('grpc.grpc.')) { + key = key.replace(/^grpc\./, ''); + } + if (key.startsWith('grpc.')) { + if (grpcGcpOptions.includes(key)) { + key = key.replace(/^grpc\./, ''); + } + grpcOptions[key] = value; + } + if (key.startsWith('grpc-node.')) { + grpcOptions[key] = value; + } + }); + const stub = new CreateStub(serviceAddress, creds, grpcOptions); + return stub; + } + /** + * Detect mTLS client certificate based on logic described in + * https://google.aip.dev/auth/4114. + * + * @param {object} [options] - The configuration object. + * @returns {Promise} Resolves array of strings representing cert and key. + */ + async _detectClientCertificate(opts, universeDomain) { + var _a; + const certRegex = /(?-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----)/s; + const keyRegex = /(?-----BEGIN PRIVATE KEY-----.*?-----END PRIVATE KEY-----)/s; + // If GOOGLE_API_USE_CLIENT_CERTIFICATE is true...: + if (typeof process !== 'undefined' && + ((_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a.GOOGLE_API_USE_CLIENT_CERTIFICATE) === 'true') { + if (universeDomain && universeDomain !== 'googleapis.com') { + throw new Error('mTLS is not supported outside of googleapis.com universe domain.'); + } + if ((opts === null || opts === void 0 ? void 0 : opts.cert) && (opts === null || opts === void 0 ? void 0 : opts.key)) { + return [opts.cert, opts.key]; + } + // If context aware metadata exists, run the cert provider command, + // parse the output to extract cert and key, and use this cert/key. + const metadataPath = (0, path_1.join)(os.homedir(), '.secureConnect', 'context_aware_metadata.json'); + const metadata = JSON.parse(await readFileAsync(metadataPath)); + if (!metadata.cert_provider_command) { + throw Error('no cert_provider_command found'); + } + const stdout = await execFileAsync(metadata.cert_provider_command[0], metadata.cert_provider_command.slice(1)); + const matchCert = stdout.toString().match(certRegex); + const matchKey = stdout.toString().match(keyRegex); + if (!((matchCert === null || matchCert === void 0 ? void 0 : matchCert.groups) && (matchKey === null || matchKey === void 0 ? void 0 : matchKey.groups))) { + throw Error('unable to parse certificate and key'); + } + else { + return [matchCert.groups.cert, matchKey.groups.key]; + } + } + // If GOOGLE_API_USE_CLIENT_CERTIFICATE is not set or false, + // use no cert or key: + return [undefined, undefined]; + } + /** + * Return service path, taking into account mTLS logic. + * See: https://google.aip.dev/auth/4114 + * + * @param {string|undefined} servicePath - The path of the service. + * @param {string|undefined} customServicePath - Did the user provide a custom service URL. + * @param {boolean} hasCertificate - Was a certificate found. + * @returns {string} The DNS address for this service. + */ + _mtlsServicePath(servicePath, customServicePath, hasCertificate) { + var _a, _b; + // If user provides a custom service path, return the current service + // path and do not attempt to add mtls subdomain: + if (customServicePath || !servicePath) + return servicePath; + if (typeof process !== 'undefined' && + ((_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a.GOOGLE_API_USE_MTLS_ENDPOINT) === 'never') { + // It was explicitly asked that mtls endpoint not be used: + return servicePath; + } + else if ((typeof process !== 'undefined' && + ((_b = process === null || process === void 0 ? void 0 : process.env) === null || _b === void 0 ? void 0 : _b.GOOGLE_API_USE_MTLS_ENDPOINT) === 'always') || + hasCertificate) { + // Either auto-detect or explicit setting of endpoint: + return servicePath.replace('googleapis.com', 'mtls.googleapis.com'); + } + return servicePath; + } + /** + * Creates a 'bytelength' function for a given proto message class. + * + * See {@link BundleDescriptor} about the meaning of the return value. + * + * @param {function} message - a constructor function that is generated by + * protobuf.js. Assumes 'encoder' field in the message. + * @return {function(Object):number} - a function to compute the byte length + * for an object. + */ + static createByteLengthFunction(message) { + return gax.createByteLengthFunction(message); + } +} +exports.GrpcClient = GrpcClient; +GrpcClient.protoCache = new Map(); +class GoogleProtoFilesRoot extends protobuf.Root { + constructor(...args) { + super(...args); + } + // Causes the loading of an included proto to check if it is a common + // proto. If it is a common proto, use the bundled proto. + resolvePath(originPath, includePath) { + originPath = path.normalize(originPath); + includePath = path.normalize(includePath); + // Fully qualified paths don't need to be resolved. + if (path.isAbsolute(includePath)) { + if (!fs.existsSync(includePath)) { + throw new Error('The include `' + includePath + '` was not found.'); + } + return includePath; + } + if (COMMON_PROTO_FILES.indexOf(includePath) > -1) { + return path.join(googleProtoFilesDir, includePath); + } + return GoogleProtoFilesRoot._findIncludePath(originPath, includePath); + } + static _findIncludePath(originPath, includePath) { + originPath = path.normalize(originPath); + includePath = path.normalize(includePath); + let current = originPath; + let found = fs.existsSync(path.join(current, includePath)); + while (!found && current.length > 0) { + current = current.substring(0, current.lastIndexOf(path.sep)); + found = fs.existsSync(path.join(current, includePath)); + } + if (!found) { + throw new Error('The include `' + includePath + '` was not found.'); + } + return path.join(current, includePath); + } +} +exports.GoogleProtoFilesRoot = GoogleProtoFilesRoot; +//# sourceMappingURL=grpc.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/grpc.js.map b/node_modules/google-gax/build/src/grpc.js.map new file mode 100644 index 0000000..50e6275 --- /dev/null +++ b/node_modules/google-gax/build/src/grpc.js.map @@ -0,0 +1 @@ +{"version":3,"file":"grpc.js","sourceRoot":"","sources":["../../src/grpc.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,sDAAsD;AACtD,iDAAuC;AACvC,yBAAyB;AACzB,6DAAkE;AAClE,sCAAsC;AACtC,yBAAyB;AACzB,+BAA0B;AAE1B,6BAA6B;AAC7B,uCAAuC;AACvC,0CAA0C;AAE1C,6BAA6B;AAG7B,MAAM,mBAAmB,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;AAEhF,+CAA+C;AAC/C,MAAM,YAAY,GAAa,EAAE,CAAC;AAClC,YAAY,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;AAEvC,6DAA6D;AAC7D,8BAA8B;AAC9B,sDAAsD;AAEtD,8DAA8D;AAC9D,MAAM,kBAAkB,GAAa,gBAAgB,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAC/D,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,CAAC,GAAG,CAAC,CACjC,CAAC;AAeF;;;;GAIG;AACH,KAAK,UAAU,aAAa,CAAC,IAAY;IACvC,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE;YACzC,IAAI,GAAG;gBAAE,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;;gBACvB,OAAO,CAAC,OAAO,CAAC,CAAC;QACxB,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAED;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AAC;QAED,IAAI,kBAAkB,CAAC,OAAO,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;YACjD,OAAO,IAAI,CAAC,IAAI,CAAC,mBAAmB,EAAE,WAAW,CAAC,CAAC;QACrD,CAAC;QAED,OAAO,oBAAoB,CAAC,gBAAgB,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;IACxE,CAAC;IAED,MAAM,CAAC,gBAAgB,CAAC,UAAkB,EAAE,WAAmB;QAC7D,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACxC,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;QAE1C,IAAI,OAAO,GAAG,UAAU,CAAC;QACzB,IAAI,KAAK,GAAG,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC,CAAC;QAC3D,OAAO,CAAC,KAAK,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACpC,OAAO,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;YAC9D,KAAK,GAAG,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC,CAAC;QACzD,CAAC;QACD,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,MAAM,IAAI,KAAK,CAAC,eAAe,GAAG,WAAW,GAAG,kBAAkB,CAAC,CAAC;QACtE,CAAC;QACD,OAAO,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;IACzC,CAAC;CACF;AAzCD,oDAyCC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/iamService.d.ts b/node_modules/google-gax/build/src/iamService.d.ts new file mode 100644 index 0000000..b0ec8e0 --- /dev/null +++ b/node_modules/google-gax/build/src/iamService.d.ts @@ -0,0 +1,89 @@ +import * as gax from './gax'; +import type { GrpcClient } from './grpc'; +import type { GrpcClient as FallbackGrpcClient } from './fallback'; +import { GoogleAuth, OAuth2Client } from 'google-auth-library'; +import { ProjectIdCallback } from 'google-auth-library/build/src/auth/googleauth'; +import * as protos from '../protos/iam_service'; +import type { Descriptors, ClientOptions, Callback } from './clientInterface'; +/** + * Google Cloud IAM Client. + * This is manually written for providing methods [setIamPolicy, getIamPolicy, testIamPerssion] to the generated client. + */ +export declare class IamClient { + private _terminated; + private _opts; + private _defaults; + private _protos; + auth?: GoogleAuth | OAuth2Client; + descriptors: Descriptors; + innerApiCalls: { + [name: string]: Function; + }; + iamPolicyStub?: Promise<{ + [name: string]: Function; + }>; + gaxGrpc: GrpcClient | FallbackGrpcClient; + constructor(gaxGrpc: GrpcClient | FallbackGrpcClient, options: ClientOptions); + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize(): Promise<{ + [name: string]: Function; + }>; + /** + * The DNS address for this API service. + */ + static get servicePath(): string; + /** + * The DNS address for this API service - same as servicePath(), + * exists for compatibility reasons. + */ + static get apiEndpoint(): string; + /** + * The port for this API service. + */ + static get port(): number; + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + */ + static get scopes(): string[]; + /** + * Get the project ID used by this class. + * @param {function(Error, string)} callback - the callback to be called with + * the current project Id. + */ + getProjectId(): Promise; + getProjectId(callback: ProjectIdCallback): void; + getIamPolicy(request: protos.google.iam.v1.GetIamPolicyRequest, options?: gax.CallOptions): Promise<[protos.google.iam.v1.Policy]>; + getIamPolicy(request: protos.google.iam.v1.GetIamPolicyRequest, options: gax.CallOptions, callback: Callback): void; + getIamPolicy(request: protos.google.iam.v1.GetIamPolicyRequest, callback: Callback): void; + setIamPolicy(request: protos.google.iam.v1.SetIamPolicyRequest, options?: gax.CallOptions): Promise<[protos.google.iam.v1.Policy]>; + setIamPolicy(request: protos.google.iam.v1.SetIamPolicyRequest, options: gax.CallOptions, callback: Callback): void; + setIamPolicy(request: protos.google.iam.v1.SetIamPolicyRequest, callback: Callback): void; + testIamPermissions(request: protos.google.iam.v1.TestIamPermissionsRequest, options?: gax.CallOptions): Promise<[protos.google.iam.v1.TestIamPermissionsResponse]>; + testIamPermissions(request: protos.google.iam.v1.TestIamPermissionsRequest, callback: Callback): void; + testIamPermissions(request: protos.google.iam.v1.TestIamPermissionsRequest, options: gax.CallOptions, callback: Callback): void; + /** + * Terminate the GRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + */ + close(): Promise; +} +export interface IamClient { + getIamPolicy(request: protos.google.iam.v1.GetIamPolicyRequest): void; + getIamPolicy(request: protos.google.iam.v1.GetIamPolicyRequest, options?: gax.CallOptions | Callback, callback?: Callback): Promise<[protos.google.iam.v1.Policy]>; + setIamPolicy(request: protos.google.iam.v1.SetIamPolicyRequest): void; + setIamPolicy(request: protos.google.iam.v1.SetIamPolicyRequest, options?: gax.CallOptions | Callback, callback?: Callback): Promise<[protos.google.iam.v1.Policy]>; + testIamPermissions(request: protos.google.iam.v1.TestIamPermissionsRequest): void; + testIamPermissions(request: protos.google.iam.v1.TestIamPermissionsRequest, options?: gax.CallOptions | Callback, callback?: Callback): Promise<[protos.google.iam.v1.TestIamPermissionsResponse]>; +} diff --git a/node_modules/google-gax/build/src/iamService.js b/node_modules/google-gax/build/src/iamService.js new file mode 100644 index 0000000..1d77d45 --- /dev/null +++ b/node_modules/google-gax/build/src/iamService.js @@ -0,0 +1,232 @@ +"use strict"; +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IamClient = void 0; +const createApiCall_1 = require("./createApiCall"); +const routingHeader = require("./routingHeader"); +const gapicConfig = require("./iam_policy_service_client_config.json"); +const fallback = require("./fallback"); +let version = require('../../package.json').version; +const jsonProtos = require("../protos/iam_service.json"); +/** + * Google Cloud IAM Client. + * This is manually written for providing methods [setIamPolicy, getIamPolicy, testIamPerssion] to the generated client. + */ +class IamClient { + constructor(gaxGrpc, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + options) { + this._terminated = false; + this.descriptors = { page: {}, stream: {}, longrunning: {} }; + this.innerApiCalls = {}; + this.gaxGrpc = gaxGrpc; + // Ensure that options include the service address and port. + const opts = Object.assign({ + servicePath: options.servicePath, + port: options.port, + clientConfig: options.clientConfig, + apiEndpoint: options.apiEndpoint, + fallback: options.fallback, + }, options); + version = opts.fallback ? fallback.version : version; + opts.scopes = this.constructor.scopes; + // Save options to use in initialize() method. + this._opts = opts; + // Save the auth object to the client, for use by other methods. + this.auth = gaxGrpc.auth; + // Determine the client header string. + const clientHeader = [`gax/${version}`, `gapic/${version}`]; + if (typeof process !== 'undefined' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } + else { + clientHeader.push(`gl-web/${version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this.gaxGrpc.loadProtoJSON(jsonProtos); + // Put together the default options sent with requests. + this._defaults = gaxGrpc.constructSettings('google.iam.v1.IAMPolicy', gapicConfig, opts.clientConfig || {}, { 'x-goog-api-client': clientHeader.join(' ') }); + this.innerApiCalls = {}; + } + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.iamPolicyStub) { + return this.iamPolicyStub; + } + // Put together the "service stub" for + // google.iam.v1.IAMPolicy. + this.iamPolicyStub = this.gaxGrpc.createStub(this._opts.fallback + ? this._protos.lookupService('google.iam.v1.IAMPolicy') + : this._protos.google.iam.v1.IAMPolicy, this._opts); + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const iamPolicyStubMethods = [ + 'getIamPolicy', + 'setIamPolicy', + 'testIamPermissions', + ]; + for (const methodName of iamPolicyStubMethods) { + const innerCallPromise = this.iamPolicyStub.then(stub => (...args) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, (err) => () => { + throw err; + }); + this.innerApiCalls[methodName] = (0, createApiCall_1.createApiCall)(innerCallPromise, this._defaults[methodName], this.descriptors.page[methodName]); + } + return this.iamPolicyStub; + } + /** + * The DNS address for this API service. + */ + static get servicePath() { + return 'cloudkms.googleapis.com'; + } + /** + * The DNS address for this API service - same as servicePath(), + * exists for compatibility reasons. + */ + static get apiEndpoint() { + return 'cloudkms.googleapis.com'; + } + /** + * The port for this API service. + */ + static get port() { + return 443; + } + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', + ]; + } + getProjectId(callback) { + if (this.auth && 'getProjectId' in this.auth) { + return this.auth.getProjectId(callback); + } + if (callback) { + callback(new Error('Cannot determine project ID.')); + } + else { + return Promise.reject('Cannot determine project ID.'); + } + } + getIamPolicy(request, optionsOrCallback, callback) { + let options; + if (optionsOrCallback instanceof Function && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + routingHeader.fromParams({ + resource: request.resource, + }); + this.initialize(); + return this.innerApiCalls.getIamPolicy(request, options, callback); + } + setIamPolicy(request, optionsOrCallback, callback) { + let options; + if (optionsOrCallback instanceof Function && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + routingHeader.fromParams({ + resource: request.resource, + }); + this.initialize(); + return this.innerApiCalls.setIamPolicy(request, options, callback); + } + testIamPermissions(request, optionsOrCallback, callback) { + let options; + if (optionsOrCallback instanceof Function && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + routingHeader.fromParams({ + resource: request.resource, + }); + this.initialize(); + return this.innerApiCalls.testIamPermissions(request, options, callback); + } + /** + * Terminate the GRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + */ + close() { + this.initialize(); + if (!this._terminated) { + return this.iamPolicyStub.then(stub => { + this._terminated = true; + stub.close(); + }); + } + return Promise.resolve(); + } +} +exports.IamClient = IamClient; +//# sourceMappingURL=iamService.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/iamService.js.map b/node_modules/google-gax/build/src/iamService.js.map new file mode 100644 index 0000000..19ac044 --- /dev/null +++ b/node_modules/google-gax/build/src/iamService.js.map @@ -0,0 +1 @@ +{"version":3,"file":"iamService.js","sourceRoot":"","sources":["../../src/iamService.ts"],"names":[],"mappings":";AAAA,4BAA4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C;QACD,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;QACxB,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;QACxB,OAAO,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,EAAE,CAAC;QAC5C,OAAO,CAAC,SAAS,CAAC,OAAO,GAAG,OAAO,CAAC,SAAS,CAAC,OAAO,IAAI,EAAE,CAAC;QAC5D,OAAO,CAAC,SAAS,CAAC,OAAO,CAAC,uBAAuB,CAAC;YAChD,aAAa,CAAC,UAAU,CAAC;gBACvB,QAAQ,EAAE,OAAO,CAAC,QAAQ;aAC3B,CAAC,CAAC;QACL,IAAI,CAAC,UAAU,EAAE,CAAC;QAClB,OAAO,IAAI,CAAC,aAAa,CAAC,kBAAkB,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IAC3E,CAAC;IAED;;;;OAIG;IACH,KAAK;QACH,IAAI,CAAC,UAAU,EAAE,CAAC;QAClB,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC;YACtB,OAAO,IAAI,CAAC,aAAc,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;gBACrC,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;gBACxB,IAAI,CAAC,KAAK,EAAE,CAAC;YACf,CAAC,CAAC,CAAC;QACL,CAAC;QACD,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;CACF;AArWD,8BAqWC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/iam_policy_service_client_config.json b/node_modules/google-gax/build/src/iam_policy_service_client_config.json new file mode 100644 index 0000000..3f341fa --- /dev/null +++ b/node_modules/google-gax/build/src/iam_policy_service_client_config.json @@ -0,0 +1,38 @@ +{ + "interfaces": { + "google.iam.v1.IAMPolicy": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 20000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 20000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "GetIamPolicy": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "SetIamPolicy": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "TestIamPermissions": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } + } diff --git a/node_modules/google-gax/build/src/index.d.ts b/node_modules/google-gax/build/src/index.d.ts new file mode 100644 index 0000000..97b38f1 --- /dev/null +++ b/node_modules/google-gax/build/src/index.d.ts @@ -0,0 +1,58 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as grpc from '@grpc/grpc-js'; +import { GrpcClient, GrpcClientOptions } from './grpc'; +import * as IamProtos from '../protos/iam_service'; +import * as LocationProtos from '../protos/locations'; +import * as operationsProtos from '../protos/operations'; +import * as operationsClient from './operationsClient'; +import * as routingHeader from './routingHeader'; +export { GoogleAuth, GoogleAuthOptions } from 'google-auth-library'; +export { grpc }; +export { CancellablePromise, OngoingCall } from './call'; +export { createApiCall } from './createApiCall'; +export { BundleDescriptor, LongrunningDescriptor, PageDescriptor, StreamDescriptor, } from './descriptor'; +export { CallOptions, CallSettings, ClientConfig, constructSettings, RetryOptions, ServiceConfig, createRetryOptions, createBundleOptions, createBackoffSettings, createDefaultBackoffSettings, createMaxRetriesBackoffSettings, } from './gax'; +export { GoogleError } from './googleError'; +export { ClientStub, ClientStubOptions, GoogleProtoFilesRoot, GrpcClient, GrpcClientOptions, GrpcModule, Metadata, MetadataValue, } from './grpc'; +export { Operation, operation } from './longRunningCalls/longrunning'; +export { PathTemplate } from './pathTemplate'; +export { Status } from './status'; +export { StreamType } from './streamingCalls/streaming'; +export { routingHeader }; +declare function lro(options: GrpcClientOptions): operationsClient.OperationsClientBuilder; +declare namespace lro { + var SERVICE_ADDRESS: string; + var ALL_SCOPES: string[]; +} +export { lro, operationsProtos, IamProtos, LocationProtos }; +export { OperationsClient } from './operationsClient'; +export { IamClient } from './iamService'; +export { LocationsClient } from './locationService'; +export declare const createByteLengthFunction: typeof GrpcClient.createByteLengthFunction; +export declare const version: any; +import * as protobuf from 'protobufjs'; +export { protobuf }; +export * as protobufMinimal from 'protobufjs/minimal'; +import * as fallback from './fallback'; +export { fallback }; +export { APICallback, GRPCCallResult, ServerStreamingCall, ClientStreamingCall, BiDiStreamingCall, UnaryCall, GRPCCall, GaxCall, CancellableStream, } from './apitypes'; +export { ClientOptions, Descriptors, Callback, LROperation, PaginationCallback, PaginationResponse, } from './clientInterface'; +export { makeUUID } from './util'; +export { ServiceError, ChannelCredentials } from '@grpc/grpc-js'; +export { warn } from './warnings'; +import * as serializer from 'proto3-json-serializer'; +export { serializer }; diff --git a/node_modules/google-gax/build/src/index.js b/node_modules/google-gax/build/src/index.js new file mode 100644 index 0000000..eea2dbf --- /dev/null +++ b/node_modules/google-gax/build/src/index.js @@ -0,0 +1,95 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.serializer = exports.warn = exports.ChannelCredentials = exports.makeUUID = exports.fallback = exports.protobufMinimal = exports.protobuf = exports.version = exports.createByteLengthFunction = exports.LocationsClient = exports.IamClient = exports.OperationsClient = exports.LocationProtos = exports.IamProtos = exports.operationsProtos = exports.routingHeader = exports.StreamType = exports.Status = exports.PathTemplate = exports.operation = exports.Operation = exports.GrpcClient = exports.GoogleProtoFilesRoot = exports.ClientStub = exports.GoogleError = exports.createMaxRetriesBackoffSettings = exports.createDefaultBackoffSettings = exports.createBackoffSettings = exports.createBundleOptions = exports.createRetryOptions = exports.RetryOptions = exports.constructSettings = exports.CallSettings = exports.StreamDescriptor = exports.PageDescriptor = exports.LongrunningDescriptor = exports.BundleDescriptor = exports.createApiCall = exports.OngoingCall = exports.grpc = exports.GoogleAuth = void 0; +exports.lro = lro; +const grpc = require("@grpc/grpc-js"); +exports.grpc = grpc; +const grpc_1 = require("./grpc"); +const IamProtos = require("../protos/iam_service"); +exports.IamProtos = IamProtos; +const LocationProtos = require("../protos/locations"); +exports.LocationProtos = LocationProtos; +const operationsProtos = require("../protos/operations"); +exports.operationsProtos = operationsProtos; +const operationsClient = require("./operationsClient"); +const routingHeader = require("./routingHeader"); +exports.routingHeader = routingHeader; +var google_auth_library_1 = require("google-auth-library"); +Object.defineProperty(exports, "GoogleAuth", { enumerable: true, get: function () { return google_auth_library_1.GoogleAuth; } }); +var call_1 = require("./call"); +Object.defineProperty(exports, "OngoingCall", { enumerable: true, get: function () { return call_1.OngoingCall; } }); +var createApiCall_1 = require("./createApiCall"); +Object.defineProperty(exports, "createApiCall", { enumerable: true, get: function () { return createApiCall_1.createApiCall; } }); +var descriptor_1 = require("./descriptor"); +Object.defineProperty(exports, "BundleDescriptor", { enumerable: true, get: function () { return descriptor_1.BundleDescriptor; } }); +Object.defineProperty(exports, "LongrunningDescriptor", { enumerable: true, get: function () { return descriptor_1.LongrunningDescriptor; } }); +Object.defineProperty(exports, "PageDescriptor", { enumerable: true, get: function () { return descriptor_1.PageDescriptor; } }); +Object.defineProperty(exports, "StreamDescriptor", { enumerable: true, get: function () { return descriptor_1.StreamDescriptor; } }); +var gax_1 = require("./gax"); +Object.defineProperty(exports, "CallSettings", { enumerable: true, get: function () { return gax_1.CallSettings; } }); +Object.defineProperty(exports, "constructSettings", { enumerable: true, get: function () { return gax_1.constructSettings; } }); +Object.defineProperty(exports, "RetryOptions", { enumerable: true, get: function () { return gax_1.RetryOptions; } }); +Object.defineProperty(exports, "createRetryOptions", { enumerable: true, get: function () { return gax_1.createRetryOptions; } }); +Object.defineProperty(exports, "createBundleOptions", { enumerable: true, get: function () { return gax_1.createBundleOptions; } }); +Object.defineProperty(exports, "createBackoffSettings", { enumerable: true, get: function () { return gax_1.createBackoffSettings; } }); +Object.defineProperty(exports, "createDefaultBackoffSettings", { enumerable: true, get: function () { return gax_1.createDefaultBackoffSettings; } }); +Object.defineProperty(exports, "createMaxRetriesBackoffSettings", { enumerable: true, get: function () { return gax_1.createMaxRetriesBackoffSettings; } }); +var googleError_1 = require("./googleError"); +Object.defineProperty(exports, "GoogleError", { enumerable: true, get: function () { return googleError_1.GoogleError; } }); +var grpc_2 = require("./grpc"); +Object.defineProperty(exports, "ClientStub", { enumerable: true, get: function () { return grpc_2.ClientStub; } }); +Object.defineProperty(exports, "GoogleProtoFilesRoot", { enumerable: true, get: function () { return grpc_2.GoogleProtoFilesRoot; } }); +Object.defineProperty(exports, "GrpcClient", { enumerable: true, get: function () { return grpc_2.GrpcClient; } }); +var longrunning_1 = require("./longRunningCalls/longrunning"); +Object.defineProperty(exports, "Operation", { enumerable: true, get: function () { return longrunning_1.Operation; } }); +Object.defineProperty(exports, "operation", { enumerable: true, get: function () { return longrunning_1.operation; } }); +var pathTemplate_1 = require("./pathTemplate"); +Object.defineProperty(exports, "PathTemplate", { enumerable: true, get: function () { return pathTemplate_1.PathTemplate; } }); +var status_1 = require("./status"); +Object.defineProperty(exports, "Status", { enumerable: true, get: function () { return status_1.Status; } }); +var streaming_1 = require("./streamingCalls/streaming"); +Object.defineProperty(exports, "StreamType", { enumerable: true, get: function () { return streaming_1.StreamType; } }); +function lro(options) { + options = Object.assign({ scopes: lro.ALL_SCOPES }, options); + const gaxGrpc = new grpc_1.GrpcClient(options); + return new operationsClient.OperationsClientBuilder(gaxGrpc); +} +lro.SERVICE_ADDRESS = operationsClient.SERVICE_ADDRESS; +lro.ALL_SCOPES = operationsClient.ALL_SCOPES; +var operationsClient_1 = require("./operationsClient"); +Object.defineProperty(exports, "OperationsClient", { enumerable: true, get: function () { return operationsClient_1.OperationsClient; } }); +var iamService_1 = require("./iamService"); +Object.defineProperty(exports, "IamClient", { enumerable: true, get: function () { return iamService_1.IamClient; } }); +var locationService_1 = require("./locationService"); +Object.defineProperty(exports, "LocationsClient", { enumerable: true, get: function () { return locationService_1.LocationsClient; } }); +exports.createByteLengthFunction = grpc_1.GrpcClient.createByteLengthFunction; +exports.version = require('../../package.json').version; +const protobuf = require("protobufjs"); +exports.protobuf = protobuf; +exports.protobufMinimal = require("protobufjs/minimal"); +const fallback = require("./fallback"); +exports.fallback = fallback; +var util_1 = require("./util"); +Object.defineProperty(exports, "makeUUID", { enumerable: true, get: function () { return util_1.makeUUID; } }); +var grpc_js_1 = require("@grpc/grpc-js"); +Object.defineProperty(exports, "ChannelCredentials", { enumerable: true, get: function () { return grpc_js_1.ChannelCredentials; } }); +var warnings_1 = require("./warnings"); +Object.defineProperty(exports, "warn", { enumerable: true, get: function () { return warnings_1.warn; } }); +const serializer = require("proto3-json-serializer"); +exports.serializer = serializer; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/index.js.map b/node_modules/google-gax/build/src/index.js.map new file mode 100644 index 0000000..9bcad23 --- /dev/null +++ b/node_modules/google-gax/build/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AA2DK,kBAAG;AAzDX,sCAAsC;AAS9B,oBAAI;AARZ,iCAAqD;AACrD,mDAAmD;AAuDp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,gBAAgB,CAAC,eAAe,CAAC;AACvD,GAAG,CAAC,UAAU,GAAG,gBAAgB,CAAC,UAAU,CAAC;AAG7C,uDAAoD;AAA5C,oHAAA,gBAAgB,OAAA;AACxB,2CAAuC;AAA/B,uGAAA,SAAS,OAAA;AACjB,qDAAkD;AAA1C,kHAAA,eAAe,OAAA;AAEV,QAAA,wBAAwB,GAAG,iBAAU,CAAC,wBAAwB,CAAC;AAC/D,QAAA,OAAO,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO,CAAC;AAE7D,uCAAuC;AAC/B,4BAAQ;AAChB,wDAAsD;AAEtD,uCAAuC;AAC/B,4BAAQ;AAuBhB,+BAAgC;AAAxB,gGAAA,QAAQ,OAAA;AAEhB,yCAA+D;AAAzC,6GAAA,kBAAkB,OAAA;AACxC,uCAAgC;AAAxB,gGAAA,IAAI,OAAA;AAEZ,qDAAqD;AAC7C,gCAAU"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/locationService.d.ts b/node_modules/google-gax/build/src/locationService.d.ts new file mode 100644 index 0000000..432d69d --- /dev/null +++ b/node_modules/google-gax/build/src/locationService.d.ts @@ -0,0 +1,127 @@ +import * as gax from './gax'; +import type { GrpcClient } from './grpc'; +import type { GrpcClient as FallbackGrpcClient } from './fallback'; +import type { GoogleAuth } from 'google-auth-library'; +import * as protos from '../protos/locations'; +import type { Descriptors, ClientOptions, Callback, PaginationCallback } from './clientInterface'; +/** + * Google Cloud Locations Client. + * This is manually written for providing methods [listLocations, getLocations] to the generated client. + */ +export declare class LocationsClient { + private _terminated; + private _opts; + private _providedCustomServicePath; + private _protos; + private _defaults; + auth: GoogleAuth; + descriptors: Descriptors; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: { + [name: string]: Function; + }; + locationsStub?: Promise<{ + [name: string]: Function; + }>; + gaxGrpc: GrpcClient | FallbackGrpcClient; + PageDescriptor: any; + /** + * Construct an instance of LocationsClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param {string} [options.apiEndpoint] - The domain name of the + * API remote host. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP fallback mode. + * In fallback mode, a special browser-compatible transport implementation is used + * instead of gRPC transport. In browser context (if the `window` object is defined) + * the fallback mode is enabled automatically; set `options.fallback` to `false` + * if you need to override this behavior. + */ + constructor(gaxGrpc: GrpcClient | FallbackGrpcClient, opts: ClientOptions); + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize(): Promise<{ + [name: string]: Function; + }>; + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + static get servicePath(): string; + /** + * The DNS address for this API service - same as servicePath(), + * exists for compatibility reasons. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint(): string; + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port(): number; + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes(): string[]; + /** + * Return the project ID used by this class. + * @returns {Promise} A promise that resolves to string containing the project ID. + */ + getProjectId(): Promise; + getProjectId(callback: Callback): void; + getLocation(request?: protos.google.cloud.location.IGetLocationRequest, options?: gax.CallOptions): Promise; + getLocation(request: protos.google.cloud.location.IGetLocationRequest, options: gax.CallOptions, callback: Callback): void; + getLocation(request: protos.google.cloud.location.IGetLocationRequest, callback: Callback): void; + listLocations(request?: protos.google.cloud.location.IListLocationsRequest, options?: gax.CallOptions): Promise<[ + protos.google.cloud.location.ILocation[], + protos.google.cloud.location.IListLocationsRequest | null, + protos.google.cloud.location.IListLocationsResponse + ]>; + listLocations(request: protos.google.cloud.location.IListLocationsRequest, options: gax.CallOptions, callback: PaginationCallback): void; + listLocations(request: protos.google.cloud.location.IListLocationsRequest, callback: PaginationCallback): void; + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise; +} +export interface LocationsClient { + getLocation(request: protos.google.cloud.location.IGetLocationRequest): void; + getLocation(request: protos.google.cloud.location.IGetLocationRequest, options?: gax.CallOptions | Callback, callback?: Callback): Promise; + listLocationsAsync(request: protos.google.cloud.location.IListLocationsRequest, options?: gax.CallOptions): AsyncIterable; +} diff --git a/node_modules/google-gax/build/src/locationService.js b/node_modules/google-gax/build/src/locationService.js new file mode 100644 index 0000000..dad7312 --- /dev/null +++ b/node_modules/google-gax/build/src/locationService.js @@ -0,0 +1,357 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LocationsClient = void 0; +/* global window */ +const gax = require("./gax"); +const warnings_1 = require("./warnings"); +const createApiCall_1 = require("./createApiCall"); +const routingHeader = require("./routingHeader"); +const pageDescriptor_1 = require("./paginationCalls/pageDescriptor"); +const jsonProtos = require("../protos/locations.json"); +/** + * This file defines retry strategy and timeouts for all API methods in this library. + */ +const gapicConfig = require("./locations_client_config.json"); +const version = require('../../package.json').version; +/** + * Google Cloud Locations Client. + * This is manually written for providing methods [listLocations, getLocations] to the generated client. + */ +class LocationsClient { + /** + * Construct an instance of LocationsClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param {string} [options.apiEndpoint] - The domain name of the + * API remote host. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP fallback mode. + * In fallback mode, a special browser-compatible transport implementation is used + * instead of gRPC transport. In browser context (if the `window` object is defined) + * the fallback mode is enabled automatically; set `options.fallback` to `false` + * if you need to override this behavior. + */ + constructor(gaxGrpc, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + opts) { + var _a, _b; + this._terminated = false; + this.descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + // Ensure that options include all the required fields. + this.gaxGrpc = gaxGrpc; + const staticMembers = this.constructor; + const servicePath = (opts === null || opts === void 0 ? void 0 : opts.servicePath) || (opts === null || opts === void 0 ? void 0 : opts.apiEndpoint) || staticMembers.servicePath; + this._providedCustomServicePath = !!((opts === null || opts === void 0 ? void 0 : opts.servicePath) || (opts === null || opts === void 0 ? void 0 : opts.apiEndpoint)); + const port = (opts === null || opts === void 0 ? void 0 : opts.port) || staticMembers.port; + const clientConfig = (_a = opts === null || opts === void 0 ? void 0 : opts.clientConfig) !== null && _a !== void 0 ? _a : {}; + const fallback = (_b = opts === null || opts === void 0 ? void 0 : opts.fallback) !== null && _b !== void 0 ? _b : (typeof window !== 'undefined' && typeof (window === null || window === void 0 ? void 0 : window.fetch) === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); + // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. + if (servicePath !== staticMembers.servicePath && !('scopes' in opts)) { + opts['scopes'] = staticMembers.scopes; + } + // Save options to use in initialize() method. + this._opts = opts; + // Save the auth object to the client, for use by other methods. + this.auth = gaxGrpc.auth; + // Set the default scopes in auth client if needed. + if (servicePath === staticMembers.servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + // Determine the client header string. + const clientHeader = [`gax/${version}`, `gapic/${version}`]; + if (typeof process !== 'undefined' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } + else { + clientHeader.push(`gl-web/${version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); + } + else if (opts.fallback === 'rest') { + clientHeader.push(`rest/${gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = gaxGrpc.loadProtoJSON(jsonProtos); + // Some of the methods on this service return "paged" results, + // (e.g. 50 results at a time, with tokens to get subsequent + // pages). Denote the keys used for pagination and results. + this.descriptors.page = { + listLocations: new pageDescriptor_1.PageDescriptor('pageToken', 'nextPageToken', 'locations'), + }; + // Put together the default options sent with requests. + this._defaults = gaxGrpc.constructSettings('google.cloud.location.Locations', gapicConfig, opts.clientConfig || {}, { 'x-goog-api-client': clientHeader.join(' ') }); + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + // Add a warn function to the client constructor so it can be easily tested. + this.warn = warnings_1.warn; + } + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.locationsStub) { + return this.locationsStub; + } + // Put together the "service stub" for + // google.cloud.location.Locations. + this.locationsStub = this.gaxGrpc.createStub(this._opts.fallback + ? this._protos.lookupService('google.cloud.location.Locations') + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._protos.google.cloud.location.Locations, this._opts, this._providedCustomServicePath); + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const locationsStubMethods = ['listLocations', 'getLocation']; + for (const methodName of locationsStubMethods) { + const callPromise = this.locationsStub.then(stub => (...args) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, (err) => () => { + throw err; + }); + const descriptor = this.descriptors.page[methodName] || undefined; + const apiCall = (0, createApiCall_1.createApiCall)(callPromise, this._defaults[methodName], descriptor); + this.innerApiCalls[methodName] = apiCall; + } + return this.locationsStub; + } + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + static get servicePath() { + return 'cloud.googleapis.com'; + } + /** + * The DNS address for this API service - same as servicePath(), + * exists for compatibility reasons. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint() { + return 'cloud.googleapis.com'; + } + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return ['https://www.googleapis.com/auth/cloud-platform']; + } + getProjectId(callback) { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + /** + * Gets information about a location. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Resource name for the location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing [Location]{@link google.cloud.location.Location}. + * Please see the + * [documentation](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#regular-methods) + * for more details and examples. + * @example + * const [response] = await client.getLocation(request); + */ + getLocation(request, optionsOrCallback, callback) { + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + routingHeader.fromParams({ + name: request.name || '', + }); + this.initialize(); + return this.innerApiCalls.getLocation(request, options, callback); + } + /** + * Lists information about the supported locations for this service. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource that owns the locations collection, if applicable. + * @param {string} request.filter + * The standard list filter. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of [Location]{@link google.cloud.location.Location}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listLocationsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the + * [documentation](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination) + * for more details and examples. + */ + listLocations(request, optionsOrCallback, callback) { + request = request || {}; + let options; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + routingHeader.fromParams({ + name: request.name || '', + }); + this.initialize(); + return this.innerApiCalls.listLocations(request, options, callback); + } + /** + * Equivalent to `listLocations`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource that owns the locations collection, if applicable. + * @param {string} request.filter + * The standard list filter. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows [async iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols). + * When you iterate the returned iterable, each element will be an object representing + * [Location]{@link google.cloud.location.Location}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the + * [documentation](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination) + * for more details and examples. + * @example + * const iterable = client.listLocationsAsync(request); + * for await (const response of iterable) { + * // process response + * } + */ + listLocationsAsync(request, options) { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + routingHeader.fromParams({ + name: request.name || '', + }); + options = options || {}; + const callSettings = new gax.CallSettings(options); + this.initialize(); + return this.descriptors.page.listLocations.asyncIterate(this.innerApiCalls['listLocations'], request, callSettings); + } + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close() { + this.initialize(); + if (!this._terminated) { + return this.locationsStub.then(stub => { + this._terminated = true; + stub.close(); + }); + } + return Promise.resolve(); + } +} +exports.LocationsClient = LocationsClient; +//# sourceMappingURL=locationService.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/locationService.js.map b/node_modules/google-gax/build/src/locationService.js.map new file mode 100644 index 0000000..eab6239 --- /dev/null +++ b/node_modules/google-gax/build/src/locationService.js.map @@ -0,0 +1 @@ +{"version":3,"file":"locationService.js","sourceRoot":"","sources":["../../src/locationService.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAEjC,mBAAmB;AACnB,6BAA6B;AAC7B,yCAAgC;AAGhC,mDAA8C;AAE9C,iDAAiD;AAQjD,qEAAgE;AAChE,uDAAwD;AAIxD;;GAEG;AACH,8DAA8D;AAE9D,MAAM,OAAO,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO,CAAC;AAEtD;;;GAGG;AACH,MAAa,eAAe;IAoB1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAiCG;IACH,YACE,OAAwC;IACxC,8DAA8D;IAC9D,IAAmB;;QAxDb,gBAAW,GAAG,KAAK,CAAC;QAM5B,gBAAW,GAAgB;YACzB,IAAI,EAAE,EAAE;YACR,MAAM,EAAE,EAAE;YACV,WAAW,EAAE,EAAE;YACf,QAAQ,EAAE,EAAE;SACb,CAAC;QA+CA,uDAAuD;QACvD,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB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I,CAAC,IAAI,CAAC,EAAE;gBACrC,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;gBACxB,IAAI,CAAC,KAAK,EAAE,CAAC;YACf,CAAC,CAAC,CAAC;QACL,CAAC;QACD,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;CACF;AAreD,0CAqeC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/locations_client_config.json b/node_modules/google-gax/build/src/locations_client_config.json new file mode 100644 index 0000000..9c1c7d3 --- /dev/null +++ b/node_modules/google-gax/build/src/locations_client_config.json @@ -0,0 +1,35 @@ +{ + "interfaces": { + "google.cloud.location.Locations": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "ListLocations": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetLocation": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } + } + \ No newline at end of file diff --git a/node_modules/google-gax/build/src/longRunningCalls/longRunningApiCaller.d.ts b/node_modules/google-gax/build/src/longRunningCalls/longRunningApiCaller.d.ts new file mode 100644 index 0000000..73e1306 --- /dev/null +++ b/node_modules/google-gax/build/src/longRunningCalls/longRunningApiCaller.d.ts @@ -0,0 +1,40 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { APICaller } from '../apiCaller'; +import { APICallback, GRPCCall, SimpleCallbackFunction } from '../apitypes'; +import { OngoingCall, OngoingCallPromise } from '../call'; +import { CallOptions } from '../gax'; +import { GoogleError } from '../googleError'; +import { LongRunningDescriptor } from './longRunningDescriptor'; +export declare class LongrunningApiCaller implements APICaller { + longrunningDescriptor: LongRunningDescriptor; + /** + * Creates an API caller that performs polling on a long running operation. + * + * @private + * @constructor + * @param {LongRunningDescriptor} longrunningDescriptor - Holds the + * decoders used for unpacking responses and the operationsClient + * used for polling the operation. + */ + constructor(longrunningDescriptor: LongRunningDescriptor); + init(callback?: APICallback): OngoingCallPromise | OngoingCall; + wrap(func: GRPCCall): GRPCCall; + call(apiCall: SimpleCallbackFunction, argument: {}, settings: CallOptions, canceller: OngoingCallPromise): void; + private _wrapOperation; + fail(canceller: OngoingCallPromise, err: GoogleError): void; + result(canceller: OngoingCallPromise): import("../call").CancellablePromise; +} diff --git a/node_modules/google-gax/build/src/longRunningCalls/longRunningApiCaller.js b/node_modules/google-gax/build/src/longRunningCalls/longRunningApiCaller.js new file mode 100644 index 0000000..302a687 --- /dev/null +++ b/node_modules/google-gax/build/src/longRunningCalls/longRunningApiCaller.js @@ -0,0 +1,72 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LongrunningApiCaller = void 0; +const call_1 = require("../call"); +const gax_1 = require("../gax"); +const longrunning_1 = require("./longrunning"); +class LongrunningApiCaller { + /** + * Creates an API caller that performs polling on a long running operation. + * + * @private + * @constructor + * @param {LongRunningDescriptor} longrunningDescriptor - Holds the + * decoders used for unpacking responses and the operationsClient + * used for polling the operation. + */ + constructor(longrunningDescriptor) { + this.longrunningDescriptor = longrunningDescriptor; + } + init(callback) { + if (callback) { + return new call_1.OngoingCall(callback); + } + return new call_1.OngoingCallPromise(); + } + wrap(func) { + return func; + } + call(apiCall, argument, settings, canceller) { + canceller.call((argument, callback) => { + return this._wrapOperation(apiCall, settings, argument, callback); + }, argument); + } + _wrapOperation(apiCall, settings, argument, callback) { + let backoffSettings = settings.longrunning; + if (!backoffSettings) { + backoffSettings = (0, gax_1.createDefaultBackoffSettings)(); + } + const longrunningDescriptor = this.longrunningDescriptor; + return apiCall(argument, (err, rawResponse) => { + if (err) { + callback(err, null, null, rawResponse); + return; + } + const operation = new longrunning_1.Operation(rawResponse, longrunningDescriptor, backoffSettings, settings); + callback(null, operation, rawResponse); + }); + } + fail(canceller, err) { + canceller.callback(err); + } + result(canceller) { + return canceller.promise; + } +} +exports.LongrunningApiCaller = LongrunningApiCaller; +//# sourceMappingURL=longRunningApiCaller.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/longRunningCalls/longRunningApiCaller.js.map b/node_modules/google-gax/build/src/longRunningCalls/longRunningApiCaller.js.map new file mode 100644 index 0000000..8825f68 --- /dev/null +++ b/node_modules/google-gax/build/src/longRunningCalls/longRunningApiCaller.js.map @@ -0,0 +1 @@ +{"version":3,"file":"longRunningApiCaller.js","sourceRoot":"","sources":["../../../src/longRunningCalls/longRunningApiCaller.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAIH,kCAAwD;AACxD,gCAIgB;AAGhB,+CAAwC;AAIxC,MAAa,oBAAoB;IAE/B;;;;;;;;OAQG;IACH,YAAY,qBAA4C;QACtD,IAAI,CAAC,qBAAqB,GAAG,qBAAqB,CAAC;IACrD,CAAC;IAED,IAAI,CAAC,QAAsB;QACzB,IAAI,QAAQ,EAAE,CAAC;YACb,OAAO,IAAI,kBAAW,CAAC,QAAQ,CAAC,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AC;CACF;AA5ED,oDA4EC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/longRunningCalls/longRunningDescriptor.d.ts b/node_modules/google-gax/build/src/longRunningCalls/longRunningDescriptor.d.ts new file mode 100644 index 0000000..84e3de2 --- /dev/null +++ b/node_modules/google-gax/build/src/longRunningCalls/longRunningDescriptor.d.ts @@ -0,0 +1,35 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as protobuf from 'protobufjs'; +import { Descriptor } from '../descriptor'; +import { OperationsClient } from '../operationsClient'; +import { LongrunningApiCaller } from './longRunningApiCaller'; +/** + * A callback to upack a google.protobuf.Any message. + */ +export interface AnyDecoder { + (reader: protobuf.Reader | Uint8Array, length?: number): protobuf.Message<{}>; +} +/** + * A descriptor for long-running operations. + */ +export declare class LongRunningDescriptor implements Descriptor { + operationsClient: OperationsClient; + responseDecoder: AnyDecoder; + metadataDecoder: AnyDecoder; + constructor(operationsClient: OperationsClient, responseDecoder: AnyDecoder, metadataDecoder: AnyDecoder); + getApiCaller(): LongrunningApiCaller; +} diff --git a/node_modules/google-gax/build/src/longRunningCalls/longRunningDescriptor.js b/node_modules/google-gax/build/src/longRunningCalls/longRunningDescriptor.js new file mode 100644 index 0000000..a9ac886 --- /dev/null +++ b/node_modules/google-gax/build/src/longRunningCalls/longRunningDescriptor.js @@ -0,0 +1,34 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LongRunningDescriptor = void 0; +const longRunningApiCaller_1 = require("./longRunningApiCaller"); +/** + * A descriptor for long-running operations. + */ +class LongRunningDescriptor { + constructor(operationsClient, responseDecoder, metadataDecoder) { + this.operationsClient = operationsClient; + this.responseDecoder = responseDecoder; + this.metadataDecoder = metadataDecoder; + } + getApiCaller() { + return new longRunningApiCaller_1.LongrunningApiCaller(this); + } +} +exports.LongRunningDescriptor = LongRunningDescriptor; +//# sourceMappingURL=longRunningDescriptor.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/longRunningCalls/longRunningDescriptor.js.map b/node_modules/google-gax/build/src/longRunningCalls/longRunningDescriptor.js.map new file mode 100644 index 0000000..aeaf9d5 --- /dev/null +++ b/node_modules/google-gax/build/src/longRunningCalls/longRunningDescriptor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"longRunningDescriptor.js","sourceRoot":"","sources":["../../../src/longRunningCalls/longRunningDescriptor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAKH,iEAA4D;AAS5D;;GAEG;AACH,MAAa,qBAAqB;IAKhC,YACE,gBAAkC,EAClC,eAA2B,EAC3B,eAA2B;QAE3B,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;QACzC,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QACvC,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;IACzC,CAAC;IAED,YAAY;QACV,OAAO,IAAI,2CAAoB,CAAC,IAAI,CAAC,CAAC;IACxC,CAAC;CACF;AAlBD,sDAkBC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/longRunningCalls/longrunning.d.ts b/node_modules/google-gax/build/src/longRunningCalls/longrunning.d.ts new file mode 100644 index 0000000..49bbe7f --- /dev/null +++ b/node_modules/google-gax/build/src/longRunningCalls/longrunning.d.ts @@ -0,0 +1,132 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { EventEmitter } from 'events'; +import { ResultTuple } from '../apitypes'; +import { CancellablePromise } from '../call'; +import { BackoffSettings, CallOptions } from '../gax'; +import { GoogleError } from '../googleError'; +import { Metadata } from '../grpc'; +import { LongRunningDescriptor } from './longRunningDescriptor'; +import * as operationProtos from '../../protos/operations'; +/** + * @callback GetOperationCallback + * @param {?Error} error + * @param {?Object} result + * @param {?Object} metadata + * @param {?google.longrunning.Operation} rawResponse + */ +export interface GetOperationCallback { + (err?: Error | null, result?: {}, metadata?: {}, rawResponse?: LROOperation): void; +} +type LROOperation = operationProtos.google.longrunning.Operation; +export declare class Operation extends EventEmitter { + completeListeners: number; + hasActiveListeners: boolean; + latestResponse: LROOperation; + longrunningDescriptor: LongRunningDescriptor; + result: {} | null; + metadata: Metadata | null; + backoffSettings: BackoffSettings; + _callOptions?: CallOptions; + currentCallPromise_?: CancellablePromise; + name?: string; + done?: boolean; + error?: GoogleError; + response?: {}; + /** + * Wrapper for a google.longrunnung.Operation. + * + * @constructor + * + * @param {google.longrunning.Operation} grpcOp - The operation to be wrapped. + * @param {LongRunningDescriptor} longrunningDescriptor - This defines the + * operations service client and unpacking mechanisms for the operation. + * @param {BackoffSettings} backoffSettings - The backoff settings used in + * in polling the operation. + * @param {CallOptions} callOptions - CallOptions used in making get operation + * requests. + */ + constructor(grpcOp: LROOperation, longrunningDescriptor: LongRunningDescriptor, backoffSettings: BackoffSettings, callOptions?: CallOptions); + /** + * Begin listening for events on the operation. This method keeps track of how + * many "complete" listeners are registered and removed, making sure polling + * is handled automatically. + * + * As long as there is one active "complete" listener, the connection is open. + * When there are no more listeners, the polling stops. + * + * @private + */ + _listenForEvents(): void; + /** + * Cancels current polling api call and cancels the operation. + * + * @return {Promise} the promise of the OperationsClient#cancelOperation api + * request. + */ + cancel(): Promise; + /** + * Get the updated status of the operation. If the Operation has previously + * completed, this will use the status of the cached completed operation. + * + * - callback(err): Operation failed + * - callback(null, result, metadata, rawResponse): Operation complete + * - callback(null, null, metadata, rawResponse): Operation incomplete + * + * @param {getOperationCallback} callback - Callback to handle the polled + * operation result and metadata. + * @return {Promise|undefined} - This returns a promise if a callback is not specified. + * The promise resolves to an array where the first element is the unpacked + * result, the second element is the metadata, and the third element is the + * raw response of the api call. The promise rejects if the operation returns + * an error. + */ + getOperation(): Promise<{}>; + getOperation(callback: GetOperationCallback): void; + _unpackResponse(op: LROOperation, callback?: GetOperationCallback): void; + /** + * Poll `getOperation` to check the operation's status. This runs a loop to + * ping using the backoff strategy specified at initialization. + * + * Note: This method is automatically called once a "complete" event handler + * is registered on the operation. + * + * @private + */ + startPolling_(): void; + /** + * Wraps the `complete` and `error` events in a Promise. + * + * @return {promise} - Promise that resolves on operation completion and rejects + * on operation error. + */ + promise(): Promise; +} +/** + * Method used to create Operation objects. + * + * @constructor + * + * @param {google.longrunning.Operation} op - The operation to be wrapped. + * @param {LongRunningDescriptor} longrunningDescriptor - This defines the + * operations service client and unpacking mechanisms for the operation. + * @param {BackoffSettings} backoffSettings - The backoff settings used in + * in polling the operation. + * @param {CallOptions=} callOptions - CallOptions used in making get operation + * requests. + */ +export declare function operation(op: LROOperation, longrunningDescriptor: LongRunningDescriptor, backoffSettings: BackoffSettings, callOptions?: CallOptions): Operation; +export {}; diff --git a/node_modules/google-gax/build/src/longRunningCalls/longrunning.js b/node_modules/google-gax/build/src/longRunningCalls/longrunning.js new file mode 100644 index 0000000..9581588 --- /dev/null +++ b/node_modules/google-gax/build/src/longRunningCalls/longrunning.js @@ -0,0 +1,280 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Operation = void 0; +exports.operation = operation; +const events_1 = require("events"); +const status_1 = require("../status"); +const googleError_1 = require("../googleError"); +const operationProtos = require("../../protos/operations"); +class Operation extends events_1.EventEmitter { + /** + * Wrapper for a google.longrunnung.Operation. + * + * @constructor + * + * @param {google.longrunning.Operation} grpcOp - The operation to be wrapped. + * @param {LongRunningDescriptor} longrunningDescriptor - This defines the + * operations service client and unpacking mechanisms for the operation. + * @param {BackoffSettings} backoffSettings - The backoff settings used in + * in polling the operation. + * @param {CallOptions} callOptions - CallOptions used in making get operation + * requests. + */ + constructor(grpcOp, longrunningDescriptor, backoffSettings, callOptions) { + super(); + this.completeListeners = 0; + this.hasActiveListeners = false; + this.latestResponse = grpcOp; + this.name = this.latestResponse.name; + this.done = this.latestResponse.done; + this.error = this.latestResponse.error; + this.longrunningDescriptor = longrunningDescriptor; + this.result = null; + this.metadata = null; + this.backoffSettings = backoffSettings; + this._unpackResponse(grpcOp); + this._listenForEvents(); + this._callOptions = callOptions; + } + /** + * Begin listening for events on the operation. This method keeps track of how + * many "complete" listeners are registered and removed, making sure polling + * is handled automatically. + * + * As long as there is one active "complete" listener, the connection is open. + * When there are no more listeners, the polling stops. + * + * @private + */ + _listenForEvents() { + this.on('newListener', event => { + if (event === 'complete') { + this.completeListeners++; + if (!this.hasActiveListeners) { + this.hasActiveListeners = true; + this.startPolling_(); + } + } + }); + this.on('removeListener', event => { + if (event === 'complete' && --this.completeListeners === 0) { + this.hasActiveListeners = false; + } + }); + } + /** + * Cancels current polling api call and cancels the operation. + * + * @return {Promise} the promise of the OperationsClient#cancelOperation api + * request. + */ + cancel() { + if (this.currentCallPromise_) { + this.currentCallPromise_.cancel(); + } + const operationsClient = this.longrunningDescriptor.operationsClient; + const cancelRequest = new operationProtos.google.longrunning.CancelOperationRequest(); + cancelRequest.name = this.latestResponse.name; + return operationsClient.cancelOperation(cancelRequest); + } + getOperation(callback) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const self = this; + const operationsClient = this.longrunningDescriptor.operationsClient; + function promisifyResponse() { + if (!callback) { + return new Promise((resolve, reject) => { + if (self.latestResponse.error) { + const error = new googleError_1.GoogleError(self.latestResponse.error.message); + error.code = self.latestResponse.error.code; + reject(error); + } + else { + resolve([self.result, self.metadata, self.latestResponse]); + } + }); + } + return; + } + if (this.latestResponse.done) { + this._unpackResponse(this.latestResponse, callback); + return promisifyResponse(); + } + const request = new operationProtos.google.longrunning.GetOperationRequest(); + request.name = this.latestResponse.name; + this.currentCallPromise_ = operationsClient.getOperationInternal(request, this._callOptions); + const noCallbackPromise = this.currentCallPromise_.then(responses => { + self.latestResponse = responses[0]; + self._unpackResponse(responses[0], callback); + return promisifyResponse(); + }, (err) => { + if (callback) { + callback(err); + return; + } + return Promise.reject(err); + }); + if (!callback) { + return noCallbackPromise; + } + } + _unpackResponse(op, callback) { + const responseDecoder = this.longrunningDescriptor.responseDecoder; + const metadataDecoder = this.longrunningDescriptor.metadataDecoder; + let response; + let metadata; + if (op.done) { + if (op.result === 'error') { + const error = new googleError_1.GoogleError(op.error.message); + error.code = op.error.code; + this.error = error; + if (callback) { + callback(error); + } + return; + } + if (responseDecoder && op.response) { + this.response = op.response; + response = responseDecoder(op.response.value); + this.result = response; + this.done = true; + } + } + if (metadataDecoder && op.metadata) { + metadata = metadataDecoder(op.metadata.value); + this.metadata = metadata; + } + if (callback) { + callback(null, response, metadata, op); + } + } + /** + * Poll `getOperation` to check the operation's status. This runs a loop to + * ping using the backoff strategy specified at initialization. + * + * Note: This method is automatically called once a "complete" event handler + * is registered on the operation. + * + * @private + */ + startPolling_() { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const self = this; + let now = new Date(); + const delayMult = this.backoffSettings.retryDelayMultiplier; + const maxDelay = this.backoffSettings.maxRetryDelayMillis; + let delay = this.backoffSettings.initialRetryDelayMillis; + let deadline = Infinity; + if (this.backoffSettings.totalTimeoutMillis) { + deadline = now.getTime() + this.backoffSettings.totalTimeoutMillis; + } + let previousMetadataBytes; + if (this.latestResponse.metadata) { + previousMetadataBytes = this.latestResponse.metadata.value; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function emit(event, ...args) { + self.emit(event, ...args); + } + // Helper function to replace nodejs buffer's equals() + function arrayEquals(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + for (let i = 0; i < a.byteLength; ++i) { + if (a[i] !== b[i]) + return false; + } + return true; + } + function retry() { + if (!self.hasActiveListeners) { + return; + } + if (now.getTime() >= deadline) { + const error = new googleError_1.GoogleError('Total timeout exceeded before any response was received'); + error.code = status_1.Status.DEADLINE_EXCEEDED; + setImmediate(emit, 'error', error); + return; + } + self.getOperation((err, result, metadata, rawResponse) => { + if (err) { + setImmediate(emit, 'error', err); + return; + } + if (!result) { + if (rawResponse.metadata && + (!previousMetadataBytes || + (rawResponse && + !arrayEquals(rawResponse.metadata.value, previousMetadataBytes)))) { + setImmediate(emit, 'progress', metadata, rawResponse); + previousMetadataBytes = rawResponse.metadata.value; + } + // special case: some APIs fail to set either result or error + // but set done = true (e.g. speech with silent file). + // Some APIs just use this for the normal completion + // (e.g. nodejs-contact-center-insights), so let's just return + // an empty response in this case. + if (rawResponse.done) { + setImmediate(emit, 'complete', {}, metadata, rawResponse); + return; + } + setTimeout(() => { + now = new Date(); + delay = Math.min(delay * delayMult, maxDelay); + retry(); + }, delay); + return; + } + setImmediate(emit, 'complete', result, metadata, rawResponse); + }); + } + retry(); + } + /** + * Wraps the `complete` and `error` events in a Promise. + * + * @return {promise} - Promise that resolves on operation completion and rejects + * on operation error. + */ + promise() { + return new Promise((resolve, reject) => { + this.on('error', reject).on('complete', (result, metadata, rawResponse) => { + resolve([result, metadata, rawResponse]); + }); + }); + } +} +exports.Operation = Operation; +/** + * Method used to create Operation objects. + * + * @constructor + * + * @param {google.longrunning.Operation} op - The operation to be wrapped. + * @param {LongRunningDescriptor} longrunningDescriptor - This defines the + * operations service client and unpacking mechanisms for the operation. + * @param {BackoffSettings} backoffSettings - The backoff settings used in + * in polling the operation. + * @param {CallOptions=} callOptions - CallOptions used in making get operation + * requests. + */ +function operation(op, longrunningDescriptor, backoffSettings, callOptions) { + return new Operation(op, longrunningDescriptor, backoffSettings, callOptions); +} +//# sourceMappingURL=longrunning.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/longRunningCalls/longrunning.js.map b/node_modules/google-gax/build/src/longRunningCalls/longrunning.js.map new file mode 100644 index 0000000..70ea953 --- /dev/null +++ b/node_modules/google-gax/build/src/longRunningCalls/longrunning.js.map @@ -0,0 +1 @@ +{"version":3,"file":"longrunning.js","sourceRoot":"","sources":["../../../src/longRunningCalls/longrunning.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAwWH,8BAOC;AA7WD,mCAAoC;AACpC,sCAAiC;AAKjC,gDAA2C;AAG3C,2DAA2D;AAoB3D,MAAa,SAAU,SAAQ,qBAAY;IAezC;;;;;;;;;;;;OAYG;IACH,YACE,MAAoB,EACpB,qBAA4C,EAC5C,eAAgC,EAChC,WAAyB;QAEzB,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,iBAAiB,GAAG,CAAC,CAAC;QAC3B,IAAI,CAAC,kBAAkB,GAAG,KAAK,CAAC;QAChC,IAAI,CAAC,cAAc,GAAG,MAAM,CAAC;QAC7B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC;QACrC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,cAAc,CAAC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AAE;gBAChC,OAAO,CAAC,CAAC,MAAM,EAAE,QAAQ,EAAE,WAAW,CAAC,CAAC,CAAC;YAC3C,CAAC,CACF,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA1TD,8BA0TC;AAED;;;;;;;;;;;;GAYG;AACH,SAAgB,SAAS,CACvB,EAAgB,EAChB,qBAA4C,EAC5C,eAAgC,EAChC,WAAyB;IAEzB,OAAO,IAAI,SAAS,CAAC,EAAE,EAAE,qBAAqB,EAAE,eAAe,EAAE,WAAW,CAAC,CAAC;AAChF,CAAC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/normalCalls/normalApiCaller.d.ts b/node_modules/google-gax/build/src/normalCalls/normalApiCaller.d.ts new file mode 100644 index 0000000..f3cbab5 --- /dev/null +++ b/node_modules/google-gax/build/src/normalCalls/normalApiCaller.d.ts @@ -0,0 +1,29 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { APICaller } from '../apiCaller'; +import { APICallback, GRPCCall, SimpleCallbackFunction } from '../apitypes'; +import { OngoingCall, OngoingCallPromise } from '../call'; +import { GoogleError } from '../googleError'; +/** + * Creates an API caller for regular unary methods. + */ +export declare class NormalApiCaller implements APICaller { + init(callback?: APICallback): OngoingCallPromise | OngoingCall; + wrap(func: GRPCCall): GRPCCall; + call(apiCall: SimpleCallbackFunction, argument: {}, settings: {}, canceller: OngoingCallPromise): void; + fail(canceller: OngoingCallPromise, err: GoogleError): void; + result(canceller: OngoingCallPromise): import("../call").CancellablePromise; +} diff --git a/node_modules/google-gax/build/src/normalCalls/normalApiCaller.js b/node_modules/google-gax/build/src/normalCalls/normalApiCaller.js new file mode 100644 index 0000000..6181ba4 --- /dev/null +++ b/node_modules/google-gax/build/src/normalCalls/normalApiCaller.js @@ -0,0 +1,44 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NormalApiCaller = void 0; +const call_1 = require("../call"); +/** + * Creates an API caller for regular unary methods. + */ +class NormalApiCaller { + init(callback) { + if (callback) { + return new call_1.OngoingCall(callback); + } + return new call_1.OngoingCallPromise(); + } + wrap(func) { + return func; + } + call(apiCall, argument, settings, canceller) { + canceller.call(apiCall, argument); + } + fail(canceller, err) { + canceller.callback(err); + } + result(canceller) { + return canceller.promise; + } +} +exports.NormalApiCaller = NormalApiCaller; +//# sourceMappingURL=normalApiCaller.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/normalCalls/normalApiCaller.js.map b/node_modules/google-gax/build/src/normalCalls/normalApiCaller.js.map new file mode 100644 index 0000000..31693aa --- /dev/null +++ b/node_modules/google-gax/build/src/normalCalls/normalApiCaller.js.map @@ -0,0 +1 @@ +{"version":3,"file":"normalApiCaller.js","sourceRoot":"","sources":["../../../src/normalCalls/normalApiCaller.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAIH,kCAAwD;AAGxD;;GAEG;AACH,MAAa,eAAe;IAC1B,IAAI,CAAC,QAAsB;QACzB,IAAI,QAAQ,EAAE,CAAC;YACb,OAAO,IAAI,kBAAW,CAAC,QAAQ,CAAC,CAAC;QACnC,CAAC;QACD,OAAO,IAAI,yBAAkB,EAAE,CAAC;IAClC,CAAC;IAED,IAAI,CAAC,IAAc;QACjB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,CACF,OAA+B,EAC/B,QAAY,EACZ,QAAY,EACZ,SAA6B;QAE7B,SAAS,CAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;IACpC,CAAC;IAED,IAAI,CAAC,SAA6B,EAAE,GAAgB;QAClD,SAAS,CAAC,QAAS,CAAC,GAAG,CAAC,CAAC;IAC3B,CAAC;IAED,MAAM,CAAC,SAA6B;QAClC,OAAO,SAAS,CAAC,OAAO,CAAC;IAC3B,CAAC;CACF;AA5BD,0CA4BC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/normalCalls/retries.d.ts b/node_modules/google-gax/build/src/normalCalls/retries.d.ts new file mode 100644 index 0000000..aa0da79 --- /dev/null +++ b/node_modules/google-gax/build/src/normalCalls/retries.d.ts @@ -0,0 +1,31 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { GRPCCall, GRPCCallOtherArgs, SimpleCallbackFunction } from '../apitypes'; +import { RetryOptions } from '../gax'; +/** + * Creates a function equivalent to func, but that retries on certain + * exceptions. + * + * @private + * + * @param {GRPCCall} func - A function. + * @param {RetryOptions} retry - Configures the exceptions upon which the + * function eshould retry, and the parameters to the exponential backoff retry + * algorithm. + * @param {GRPCCallOtherArgs} otherArgs - the additional arguments to be passed to func. + * @return {SimpleCallbackFunction} A function that will retry. + */ +export declare function retryable(func: GRPCCall, retry: RetryOptions, otherArgs: GRPCCallOtherArgs, apiName?: string): SimpleCallbackFunction; diff --git a/node_modules/google-gax/build/src/normalCalls/retries.js b/node_modules/google-gax/build/src/normalCalls/retries.js new file mode 100644 index 0000000..8584f39 --- /dev/null +++ b/node_modules/google-gax/build/src/normalCalls/retries.js @@ -0,0 +1,144 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.retryable = retryable; +const status_1 = require("../status"); +const googleError_1 = require("../googleError"); +const timeout_1 = require("./timeout"); +/** + * Creates a function equivalent to func, but that retries on certain + * exceptions. + * + * @private + * + * @param {GRPCCall} func - A function. + * @param {RetryOptions} retry - Configures the exceptions upon which the + * function eshould retry, and the parameters to the exponential backoff retry + * algorithm. + * @param {GRPCCallOtherArgs} otherArgs - the additional arguments to be passed to func. + * @return {SimpleCallbackFunction} A function that will retry. + */ +function retryable(func, retry, otherArgs, apiName) { + const delayMult = retry.backoffSettings.retryDelayMultiplier; + const maxDelay = retry.backoffSettings.maxRetryDelayMillis; + const timeoutMult = retry.backoffSettings.rpcTimeoutMultiplier; + const maxTimeout = retry.backoffSettings.maxRpcTimeoutMillis; + let delay = retry.backoffSettings.initialRetryDelayMillis; + let timeout = retry.backoffSettings.initialRpcTimeoutMillis; + /** + * Equivalent to ``func``, but retries upon transient failure. + * + * Retrying is done through an exponential backoff algorithm configured + * by the options in ``retry``. + * @param {RequestType} argument The request object. + * @param {APICallback} callback The callback. + * @return {GRPCCall} + */ + return (argument, callback) => { + let canceller; + let timeoutId; + let now = new Date(); + let deadline; + if (retry.backoffSettings.totalTimeoutMillis) { + deadline = now.getTime() + retry.backoffSettings.totalTimeoutMillis; + } + let retries = 0; + const maxRetries = retry.backoffSettings.maxRetries; + // TODO: define A/B testing values for retry behaviors. + /** Repeat the API call as long as necessary. */ + function repeat(err) { + timeoutId = null; + if (deadline && now.getTime() >= deadline) { + const error = new googleError_1.GoogleError(`Total timeout of API ${apiName} exceeded ${retry.backoffSettings.totalTimeoutMillis} milliseconds ${err ? `retrying error ${err} ` : ''} before any response was received.`); + error.code = status_1.Status.DEADLINE_EXCEEDED; + callback(error); + return; + } + if (retries && retries >= maxRetries) { + const error = new googleError_1.GoogleError('Exceeded maximum number of retries ' + + (err ? `retrying error ${err} ` : '') + + 'before any response was received'); + error.code = status_1.Status.DEADLINE_EXCEEDED; + callback(error); + return; + } + retries++; + let lastError = err; + const toCall = (0, timeout_1.addTimeoutArg)(func, timeout, otherArgs); + canceller = toCall(argument, (err, response, next, rawResponse) => { + // Save only the error before deadline exceeded + if (err && err.code !== 4) { + lastError = err; + } + if (!err) { + callback(null, response, next, rawResponse); + return; + } + canceller = null; + if (retry.retryCodes.length > 0 && + retry.retryCodes.indexOf(err.code) < 0) { + err.note = + 'Exception occurred in retry method that was ' + + 'not classified as transient'; + callback(err); + } + else { + const toSleep = Math.random() * delay; + timeoutId = setTimeout(() => { + now = new Date(); + delay = Math.min(delay * delayMult, maxDelay); + const timeoutCal = timeout && timeoutMult ? timeout * timeoutMult : 0; + const rpcTimeout = maxTimeout ? maxTimeout : 0; + const newDeadline = deadline ? deadline - now.getTime() : 0; + timeout = Math.min(timeoutCal, rpcTimeout, newDeadline); + repeat(lastError); + }, toSleep); + } + }); + if (canceller instanceof Promise) { + canceller.catch(err => { + callback(new googleError_1.GoogleError(err)); + }); + } + } + if (maxRetries && deadline) { + const error = new googleError_1.GoogleError('Cannot set both totalTimeoutMillis and maxRetries ' + + 'in backoffSettings.'); + error.code = status_1.Status.INVALID_ARGUMENT; + callback(error); + } + else { + repeat(); + } + return { + cancel() { + if (timeoutId) { + clearTimeout(timeoutId); + } + if (canceller) { + canceller.cancel(); + } + else { + const error = new googleError_1.GoogleError('cancelled'); + error.code = status_1.Status.CANCELLED; + callback(error); + } + }, + }; + }; +} +//# sourceMappingURL=retries.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/normalCalls/retries.js.map b/node_modules/google-gax/build/src/normalCalls/retries.js.map new file mode 100644 index 0000000..292cb91 --- /dev/null +++ b/node_modules/google-gax/build/src/normalCalls/retries.js.map @@ -0,0 +1 @@ +{"version":3,"file":"retries.js","sourceRoot":"","sources":["../../../src/normalCalls/retries.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AA8BH,8BAkIC;AA9JD,sCAAiC;AAWjC,gDAA2C;AAE3C,uCAAwC;AAExC;;;;;;;;;;;;GAYG;AACH,SAAgB,SAAS,CACvB,IAAc,EACd,KAAmB,EACnB,SAA4B,EAC5B,OAAgB;IAEhB,MAAM,SAAS,GAAG,KAAK,CAAC,eAAe,CAAC,oBAAoB,CAAC;IAC7D,MAAM,QAAQ,GAAG,KAAK,CAAC,eAAe,CAAC,mBAAmB,CAAC;IAC3D,MAAM,WAAW,GAAG,KAAK,CAAC,eAAe,CAAC,oBAAoB,CAAC;IAC/D,MAAM,UAAU,GAAG,KAAK,CAAC,eAAe,CAAC,mBAAmB,CAAC;IAE7D,IAAI,KAAK,GAAG,KAAK,CAAC,eAAe,CAAC,uBAAuB,CAAC;IAC1D,IAAI,OAAO,GAAG,KAAK,CAAC,eAAe,CAAC,uBAAuB,CAAC;IAE5D;;;;;;;;OAQG;IACH,OAAO,CAAC,QAAqB,EAAE,QAAqB,EAAE,EAAE;QACtD,IAAI,SAAgC,CAAC;QACrC,IAAI,SAA+C,CAAC;QACpD,IAAI,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;QACrB,IAAI,QAAgB,CAAC;QACrB,IAAI,KAAK,CAAC,eAAe,CAAC,kBAAkB,EAAE,CAAC;YAC7C,QAAQ,GAAG,GAAG,CAAC,OAAO,EAAE,GAAG,KAAK,CAAC,eAAe,CAAC,kBAAkB,CAAC;QACtE,CAAC;QACD,IAA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AC,CAAC,CAAC;YACH,IAAI,SAAS,YAAY,OAAO,EAAE,CAAC;gBACjC,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE;oBACpB,QAAQ,CAAC,IAAI,yBAAW,CAAC,GAAG,CAAC,CAAC,CAAC;gBACjC,CAAC,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAED,IAAI,UAAU,IAAI,QAAS,EAAE,CAAC;YAC5B,MAAM,KAAK,GAAG,IAAI,yBAAW,CAC3B,oDAAoD;gBAClD,qBAAqB,CACxB,CAAC;YACF,KAAK,CAAC,IAAI,GAAG,eAAM,CAAC,gBAAgB,CAAC;YACrC,QAAQ,CAAC,KAAK,CAAC,CAAC;QAClB,CAAC;aAAM,CAAC;YACN,MAAM,EAAE,CAAC;QACX,CAAC;QAED,OAAO;YACL,MAAM;gBACJ,IAAI,SAAS,EAAE,CAAC;oBACd,YAAY,CAAC,SAAS,CAAC,CAAC;gBAC1B,CAAC;gBACD,IAAI,SAAS,EAAE,CAAC;oBACd,SAAS,CAAC,MAAM,EAAE,CAAC;gBACrB,CAAC;qBAAM,CAAC;oBACN,MAAM,KAAK,GAAG,IAAI,yBAAW,CAAC,WAAW,CAAC,CAAC;oBAC3C,KAAK,CAAC,IAAI,GAAG,eAAM,CAAC,SAAS,CAAC;oBAC9B,QAAQ,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC;YACH,CAAC;SACF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/normalCalls/timeout.d.ts b/node_modules/google-gax/build/src/normalCalls/timeout.d.ts new file mode 100644 index 0000000..0125d33 --- /dev/null +++ b/node_modules/google-gax/build/src/normalCalls/timeout.d.ts @@ -0,0 +1,32 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { GRPCCall, GRPCCallOtherArgs, SimpleCallbackFunction } from '../apitypes'; +/** + * Updates func so that it gets called with the timeout as its final arg. + * + * This converts a function, func, into another function with updated deadline. + * + * @private + * + * @param {GRPCCall} func - a function to be updated. + * @param {number} timeout - to be added to the original function as it final + * positional arg. + * @param {Object} otherArgs - the additional arguments to be passed to func. + * @param {Object=} abTests - the A/B testing key/value pairs. + * @return {function(Object, APICallback)} + * the function with other arguments and the timeout. + */ +export declare function addTimeoutArg(func: GRPCCall, timeout: number, otherArgs: GRPCCallOtherArgs, abTests?: {}): SimpleCallbackFunction; diff --git a/node_modules/google-gax/build/src/normalCalls/timeout.js b/node_modules/google-gax/build/src/normalCalls/timeout.js new file mode 100644 index 0000000..42a34fc --- /dev/null +++ b/node_modules/google-gax/build/src/normalCalls/timeout.js @@ -0,0 +1,47 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.addTimeoutArg = addTimeoutArg; +/** + * Updates func so that it gets called with the timeout as its final arg. + * + * This converts a function, func, into another function with updated deadline. + * + * @private + * + * @param {GRPCCall} func - a function to be updated. + * @param {number} timeout - to be added to the original function as it final + * positional arg. + * @param {Object} otherArgs - the additional arguments to be passed to func. + * @param {Object=} abTests - the A/B testing key/value pairs. + * @return {function(Object, APICallback)} + * the function with other arguments and the timeout. + */ +function addTimeoutArg(func, timeout, otherArgs, abTests) { + // TODO: this assumes the other arguments consist of metadata and options, + // which is specific to gRPC calls. Remove the hidden dependency on gRPC. + return (argument, callback) => { + const now = new Date(); + const options = otherArgs.options || {}; + options.deadline = new Date(now.getTime() + timeout); + const metadata = otherArgs.metadataBuilder + ? otherArgs.metadataBuilder(abTests, otherArgs.headers || {}) + : null; + return func(argument, metadata, options, callback); + }; +} +//# sourceMappingURL=timeout.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/normalCalls/timeout.js.map b/node_modules/google-gax/build/src/normalCalls/timeout.js.map new file mode 100644 index 0000000..4636b76 --- /dev/null +++ b/node_modules/google-gax/build/src/normalCalls/timeout.js.map @@ -0,0 +1 @@ +{"version":3,"file":"timeout.js","sourceRoot":"","sources":["../../../src/normalCalls/timeout.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAwBH,sCAiBC;AAhCD;;;;;;;;;;;;;;GAcG;AACH,SAAgB,aAAa,CAC3B,IAAc,EACd,OAAe,EACf,SAA4B,EAC5B,OAAY;IAEZ,0EAA0E;IAC1E,yEAAyE;IACzE,OAAO,CAAC,QAAQ,EAAE,QAAQ,EAAE,EAAE;QAC5B,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,MAAM,OAAO,GAAG,SAAS,CAAC,OAAO,IAAI,EAAE,CAAC;QACxC,OAAO,CAAC,QAAQ,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,OAAO,CAAC,CAAC;QACrD,MAAM,QAAQ,GAAG,SAAS,CAAC,eAAe;YACxC,CAAC,CAAC,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,SAAS,CAAC,OAAO,IAAI,EAAE,CAAC;YAC7D,CAAC,CAAC,IAAI,CAAC;QACT,OAAQ,IAAkB,CAAC,QAAQ,EAAE,QAAS,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IACrE,CAAC,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/operationsClient.d.ts b/node_modules/google-gax/build/src/operationsClient.d.ts new file mode 100644 index 0000000..91b6cd2 --- /dev/null +++ b/node_modules/google-gax/build/src/operationsClient.d.ts @@ -0,0 +1,315 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import type { GoogleAuth, OAuth2Client } from 'google-auth-library'; +import { ProjectIdCallback } from 'google-auth-library/build/src/auth/googleauth'; +import type { ClientOptions, Callback } from './clientInterface'; +import { ResultTuple } from './apitypes'; +import { PageDescriptor } from './descriptor'; +import * as gax from './gax'; +import type { GrpcClient } from './grpc'; +import type { GrpcClient as FallbackGrpcClient } from './fallback'; +import * as protos from '../protos/operations'; +import { Transform } from 'stream'; +import { CancellablePromise } from './call'; +export declare const SERVICE_ADDRESS = "longrunning.googleapis.com"; +/** + * The scopes needed to make gRPC calls to all of the methods defined in + * this service. + */ +export declare const ALL_SCOPES: string[]; +/** + * Manages long-running operations with an API service. + * + * When an API method normally takes long time to complete, it can be designed + * to return {@link Operation} to the client, and the client can use this + * interface to receive the real response asynchronously by polling the + * operation resource, or pass the operation resource to another API (such as + * Google Cloud Pub/Sub API) to receive the response. Any API service that + * returns long-running operations should implement the `Operations` interface + * so developers can have a consistent client experience. + * + * This will be created through a builder function which can be obtained by the + * module. See the following example of how to initialize the module and how to + * access to the builder. + * @see {@link operationsClient} + * + * @class + */ +export declare class OperationsClient { + auth?: GoogleAuth | OAuth2Client; + innerApiCalls: { + [name: string]: Function; + }; + descriptor: { + [method: string]: PageDescriptor; + }; + operationsStub: Promise<{ + [method: string]: Function; + }>; + constructor(gaxGrpc: GrpcClient | FallbackGrpcClient, operationsProtos: any, options: ClientOptions); + /** Closes this operations client. */ + close(): void; + /** + * Get the project ID used by this class. + * @param {function(Error, string)} callback - the callback to be called with + * the current project Id. + */ + getProjectId(): Promise; + getProjectId(callback: ProjectIdCallback): void; + getOperationInternal(request: protos.google.longrunning.GetOperationRequest, options?: gax.CallOptions, callback?: Callback): CancellablePromise; + /** + * Gets the latest state of a long-running operation. Clients can use this + * method to poll the operation result at intervals as recommended by the API + * service. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the + * details. + * @param {function(?Error, ?Object)=} callback + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing + * [google.longrunning.Operation]{@link + * external:"google.longrunning.Operation"}. + * @return {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * [google.longrunning.Operation]{@link + * external:"google.longrunning.Operation"}. The promise has a method named + * "cancel" which cancels the ongoing API call. + * + * @example + * + * const client = longrunning.operationsClient(); + * const name = ''; + * const [response] = await client.getOperation({name}); + * // doThingsWith(response) + */ + getOperation(request: protos.google.longrunning.GetOperationRequest, optionsOrCallback?: gax.CallOptions | Callback, callback?: Callback): Promise<[protos.google.longrunning.Operation]>; + /** + * Lists operations that match the specified filter in the request. If the + * server doesn't support this method, it returns `UNIMPLEMENTED`. + * + * NOTE: the `name` binding below allows API services to override the binding + * to use different resource name schemes. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation collection. + * @param {string} request.filter - The standard list filter. + * @param {number=} request.pageSize + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the + * details. + * @param {function(?Error, ?Array, ?Object, ?Object)=} callback + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is Array of + * [google.longrunning.Operation]{@link + * external:"google.longrunning.Operation"}. + * + * When autoPaginate: false is specified through options, it contains the + * result in a single response. If the response indicates the next page + * exists, the third parameter is set to be used for the next request object. + * The fourth parameter keeps the raw response object of an object + * representing [google.longrunning.ListOperationsResponse]{@link + * external:"google.longrunning.ListOperationsResponse"}. + * @return {Promise} - The promise which resolves to an array. + * The first element of the array is Array of + * [google.longrunning.Operation]{@link + * external:"google.longrunning.Operation"}. + * + * When autoPaginate: false is specified through options, the array has + * three elements. The first element is Array of + * [google.longrunning.Operation]{@link + * external:"google.longrunning.Operation"} in a single response. The second + * element is the next request object if the response indicates the next page + * exists, or null. The third element is an object representing + * [google.longrunning.ListOperationsResponse]{@link + * external:"google.longrunning.ListOperationsResponse"}. + * + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * + * const client = longrunning.operationsClient(); + * const request = { + * name: '', + * filter: '' + * }; + * // Iterate over all elements. + * const [resources] = await client.listOperations(request); + * for (const resource of resources) { + * console.log(resources); + * } + * + * // Or obtain the paged response. + * const options = {autoPaginate: false}; + * let nextRequest = request; + * while(nextRequest) { + * const response = await client.listOperations(nextRequest, options); + * const resources = response[0]; + * nextRequest = response[1]; + * const rawResponse = response[2]; + * for (const resource of resources) { + * // doThingsWith(resource); + * } + * }; + */ + listOperations(request: protos.google.longrunning.ListOperationsRequest, optionsOrCallback?: gax.CallOptions | Callback, callback?: Callback): Promise; + /** + * Equivalent to {@link listOperations}, but returns a NodeJS Stream object. + * + * This fetches the paged responses for {@link listOperations} continuously + * and invokes the callback registered for 'data' event for each element in + * the responses. + * + * The returned object has 'end' method when no more elements are required. + * + * autoPaginate option will be ignored. + * + * @see {@link https://nodejs.org/api/stream.html} + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation collection. + * @param {string} request.filter - The standard list filter. + * @param {number=} request.pageSize - + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the + * details. + * @return {Stream} - An object stream which emits an object representing [google.longrunning.Operation]{@link external:"google.longrunning.Operation"} on 'data' event. + * + * @example + * + * const client = longrunning.operationsClient(); + * const request = { + * name: '', + * filter: '' + * }; + * client.listOperationsStream(request) + * .on('data', element => { + * // doThingsWith(element) + * }) + * .on('error', err => { + * console.error(err); + * }); + */ + listOperationsStream(request: protos.google.longrunning.ListOperationsRequest, options?: gax.CallOptions): Transform; + /** + * Equivalent to {@link listOperations}, but returns an iterable object. + * + * for-await-of syntax is used with the iterable to recursively get response element on-demand. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation collection. + * @param {string} request.filter - The standard list filter. + * @param {number=} request.pageSize - + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the + * details. + * @returns {Object} + * An iterable Object that conforms to @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols. + */ + listOperationsAsync(request: protos.google.longrunning.ListOperationsRequest, options?: gax.CallOptions): AsyncIterable; + /** + * Starts asynchronous cancellation on a long-running operation. The server + * makes a best effort to cancel the operation, but success is not + * guaranteed. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. Clients can use + * {@link Operations.GetOperation} or + * other methods to check whether the cancellation succeeded or whether the + * operation completed despite cancellation. On successful cancellation, + * the operation is not deleted; instead, it becomes an operation with + * an {@link Operation.error} value with a {@link google.rpc.Status.code} of + * 1, corresponding to `Code.CANCELLED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be cancelled. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the + * details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @return {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * + * const client = longrunning.operationsClient(); + * await client.cancelOperation({name: ''}); + */ + cancelOperation(request: protos.google.longrunning.CancelOperationRequest, optionsOrCallback?: gax.CallOptions | Callback, callback?: Callback): Promise; + /** + * Deletes a long-running operation. This method indicates that the client is + * no longer interested in the operation result. It does not cancel the + * operation. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be deleted. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the + * details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @return {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * + * const client = longrunning.operationsClient(); + * await client.deleteOperation({name: ''}); + */ + deleteOperation(request: protos.google.longrunning.DeleteOperationRequest, optionsOrCallback?: gax.CallOptions | Callback, callback?: Callback): Promise; +} +export declare class OperationsClientBuilder { + operationsClient: (opts: ClientOptions) => OperationsClient; + /** + * Builds a new Operations Client + * @param gaxGrpc {GrpcClient} + */ + constructor(gaxGrpc: GrpcClient | FallbackGrpcClient, protoJson?: protobuf.Root); +} diff --git a/node_modules/google-gax/build/src/operationsClient.js b/node_modules/google-gax/build/src/operationsClient.js new file mode 100644 index 0000000..38bb758 --- /dev/null +++ b/node_modules/google-gax/build/src/operationsClient.js @@ -0,0 +1,445 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OperationsClientBuilder = exports.OperationsClient = exports.ALL_SCOPES = exports.SERVICE_ADDRESS = void 0; +const createApiCall_1 = require("./createApiCall"); +const descriptor_1 = require("./descriptor"); +const gax = require("./gax"); +const configData = require("./operations_client_config.json"); +const operationProtoJson = require("../protos/operations.json"); +const transcoding_1 = require("./transcoding"); +exports.SERVICE_ADDRESS = 'longrunning.googleapis.com'; +const version = require('../../package.json').version; +const DEFAULT_SERVICE_PORT = 443; +const CODE_GEN_NAME_VERSION = 'gapic/0.7.1'; +/** + * The scopes needed to make gRPC calls to all of the methods defined in + * this service. + */ +exports.ALL_SCOPES = []; +/** + * Manages long-running operations with an API service. + * + * When an API method normally takes long time to complete, it can be designed + * to return {@link Operation} to the client, and the client can use this + * interface to receive the real response asynchronously by polling the + * operation resource, or pass the operation resource to another API (such as + * Google Cloud Pub/Sub API) to receive the response. Any API service that + * returns long-running operations should implement the `Operations` interface + * so developers can have a consistent client experience. + * + * This will be created through a builder function which can be obtained by the + * module. See the following example of how to initialize the module and how to + * access to the builder. + * @see {@link operationsClient} + * + * @class + */ +class OperationsClient { + constructor(gaxGrpc, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + operationsProtos, options) { + const opts = Object.assign({ + servicePath: exports.SERVICE_ADDRESS, + port: DEFAULT_SERVICE_PORT, + clientConfig: {}, + }, options); + const googleApiClient = ['gl-node/' + process.versions.node]; + if (opts.libName && opts.libVersion) { + googleApiClient.push(opts.libName + '/' + opts.libVersion); + } + googleApiClient.push(CODE_GEN_NAME_VERSION, 'gax/' + version); + if (opts.fallback) { + googleApiClient.push('gl-web/' + version); + } + else { + googleApiClient.push('grpc/' + gaxGrpc.grpcVersion); + } + const defaults = gaxGrpc.constructSettings('google.longrunning.Operations', configData, opts.clientConfig || {}, { 'x-goog-api-client': googleApiClient.join(' ') }); + this.auth = gaxGrpc.auth; + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + this.descriptor = { + listOperations: new descriptor_1.PageDescriptor('pageToken', 'nextPageToken', 'operations'), + }; + // Put together the "service stub" for + // google.longrunning.Operations. + this.operationsStub = gaxGrpc.createStub(opts.fallback + ? operationsProtos.lookupService('google.longrunning.Operations') + : operationsProtos.google.longrunning.Operations, opts); + const operationsStubMethods = [ + 'getOperation', + 'listOperations', + 'cancelOperation', + 'deleteOperation', + ]; + for (const methodName of operationsStubMethods) { + const innerCallPromise = this.operationsStub.then(stub => (...args) => { + const func = stub[methodName]; + return func.apply(stub, args); + }, err => () => { + throw err; + }); + this.innerApiCalls[methodName] = (0, createApiCall_1.createApiCall)(innerCallPromise, defaults[methodName], this.descriptor[methodName]); + } + } + /** Closes this operations client. */ + close() { + this.operationsStub.then(stub => stub.close()); + } + getProjectId(callback) { + if (this.auth && 'getProjectId' in this.auth) { + return this.auth.getProjectId(callback); + } + if (callback) { + callback(new Error('Cannot determine project ID.')); + } + else { + return Promise.reject('Cannot determine project ID.'); + } + } + // Service calls + getOperationInternal(request, options, callback) { + request = request || {}; + options = options || {}; + return this.innerApiCalls.getOperation(request, options, callback); + } + /** + * Gets the latest state of a long-running operation. Clients can use this + * method to poll the operation result at intervals as recommended by the API + * service. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the + * details. + * @param {function(?Error, ?Object)=} callback + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing + * [google.longrunning.Operation]{@link + * external:"google.longrunning.Operation"}. + * @return {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * [google.longrunning.Operation]{@link + * external:"google.longrunning.Operation"}. The promise has a method named + * "cancel" which cancels the ongoing API call. + * + * @example + * + * const client = longrunning.operationsClient(); + * const name = ''; + * const [response] = await client.getOperation({name}); + * // doThingsWith(response) + */ + getOperation(request, optionsOrCallback, callback) { + let options; + if (optionsOrCallback instanceof Function && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + request = request || {}; + options = options || {}; + return this.innerApiCalls.getOperation(request, options, callback); + } + /** + * Lists operations that match the specified filter in the request. If the + * server doesn't support this method, it returns `UNIMPLEMENTED`. + * + * NOTE: the `name` binding below allows API services to override the binding + * to use different resource name schemes. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation collection. + * @param {string} request.filter - The standard list filter. + * @param {number=} request.pageSize + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the + * details. + * @param {function(?Error, ?Array, ?Object, ?Object)=} callback + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is Array of + * [google.longrunning.Operation]{@link + * external:"google.longrunning.Operation"}. + * + * When autoPaginate: false is specified through options, it contains the + * result in a single response. If the response indicates the next page + * exists, the third parameter is set to be used for the next request object. + * The fourth parameter keeps the raw response object of an object + * representing [google.longrunning.ListOperationsResponse]{@link + * external:"google.longrunning.ListOperationsResponse"}. + * @return {Promise} - The promise which resolves to an array. + * The first element of the array is Array of + * [google.longrunning.Operation]{@link + * external:"google.longrunning.Operation"}. + * + * When autoPaginate: false is specified through options, the array has + * three elements. The first element is Array of + * [google.longrunning.Operation]{@link + * external:"google.longrunning.Operation"} in a single response. The second + * element is the next request object if the response indicates the next page + * exists, or null. The third element is an object representing + * [google.longrunning.ListOperationsResponse]{@link + * external:"google.longrunning.ListOperationsResponse"}. + * + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * + * const client = longrunning.operationsClient(); + * const request = { + * name: '', + * filter: '' + * }; + * // Iterate over all elements. + * const [resources] = await client.listOperations(request); + * for (const resource of resources) { + * console.log(resources); + * } + * + * // Or obtain the paged response. + * const options = {autoPaginate: false}; + * let nextRequest = request; + * while(nextRequest) { + * const response = await client.listOperations(nextRequest, options); + * const resources = response[0]; + * nextRequest = response[1]; + * const rawResponse = response[2]; + * for (const resource of resources) { + * // doThingsWith(resource); + * } + * }; + */ + listOperations(request, optionsOrCallback, callback) { + let options; + if (optionsOrCallback instanceof Function && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + request = request || {}; + options = options || {}; + return this.innerApiCalls.listOperations(request, options, callback); + } + /** + * Equivalent to {@link listOperations}, but returns a NodeJS Stream object. + * + * This fetches the paged responses for {@link listOperations} continuously + * and invokes the callback registered for 'data' event for each element in + * the responses. + * + * The returned object has 'end' method when no more elements are required. + * + * autoPaginate option will be ignored. + * + * @see {@link https://nodejs.org/api/stream.html} + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation collection. + * @param {string} request.filter - The standard list filter. + * @param {number=} request.pageSize - + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the + * details. + * @return {Stream} - An object stream which emits an object representing [google.longrunning.Operation]{@link external:"google.longrunning.Operation"} on 'data' event. + * + * @example + * + * const client = longrunning.operationsClient(); + * const request = { + * name: '', + * filter: '' + * }; + * client.listOperationsStream(request) + * .on('data', element => { + * // doThingsWith(element) + * }) + * .on('error', err => { + * console.error(err); + * }); + */ + listOperationsStream(request, options) { + const callSettings = new gax.CallSettings(options); + return this.descriptor.listOperations.createStream(this.innerApiCalls.listOperations, request, callSettings); + } + /** + * Equivalent to {@link listOperations}, but returns an iterable object. + * + * for-await-of syntax is used with the iterable to recursively get response element on-demand. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation collection. + * @param {string} request.filter - The standard list filter. + * @param {number=} request.pageSize - + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the + * details. + * @returns {Object} + * An iterable Object that conforms to @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols. + */ + listOperationsAsync(request, options) { + request = request || {}; + options = options || {}; + const callSettings = new gax.CallSettings(options); + return this.descriptor.listOperations.asyncIterate(this.innerApiCalls.listOperations, request, callSettings); + } + /** + * Starts asynchronous cancellation on a long-running operation. The server + * makes a best effort to cancel the operation, but success is not + * guaranteed. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. Clients can use + * {@link Operations.GetOperation} or + * other methods to check whether the cancellation succeeded or whether the + * operation completed despite cancellation. On successful cancellation, + * the operation is not deleted; instead, it becomes an operation with + * an {@link Operation.error} value with a {@link google.rpc.Status.code} of + * 1, corresponding to `Code.CANCELLED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be cancelled. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the + * details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @return {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * + * const client = longrunning.operationsClient(); + * await client.cancelOperation({name: ''}); + */ + cancelOperation(request, optionsOrCallback, callback) { + let options; + if (optionsOrCallback instanceof Function && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + request = request || {}; + options = options || {}; + return this.innerApiCalls.cancelOperation(request, options, callback); + } + /** + * Deletes a long-running operation. This method indicates that the client is + * no longer interested in the operation result. It does not cancel the + * operation. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be deleted. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the + * details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @return {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * + * const client = longrunning.operationsClient(); + * await client.deleteOperation({name: ''}); + */ + deleteOperation(request, optionsOrCallback, callback) { + let options; + if (optionsOrCallback instanceof Function && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback; + } + request = request || {}; + options = options || {}; + return this.innerApiCalls.deleteOperation(request, options, callback); + } +} +exports.OperationsClient = OperationsClient; +class OperationsClientBuilder { + /** + * Builds a new Operations Client + * @param gaxGrpc {GrpcClient} + */ + constructor(gaxGrpc, protoJson) { + if (protoJson && gaxGrpc.httpRules) { + // overwrite the http rules if provide in service yaml. + (0, transcoding_1.overrideHttpRules)(gaxGrpc.httpRules, protoJson); + } + const operationsProtos = protoJson !== null && protoJson !== void 0 ? protoJson : gaxGrpc.loadProtoJSON(operationProtoJson); + /** + * Build a new instance of {@link OperationsClient}. + * + * @param {Object=} opts - The optional parameters. + * @param {String=} opts.servicePath - Domain name of the API remote host. + * @param {number=} opts.port - The port on which to connect to the remote host. + * @param {grpc.ClientCredentials=} opts.sslCreds - A ClientCredentials for use with an SSL-enabled channel. + * @param {Object=} opts.clientConfig - The customized config to build the call settings. See {@link gax.constructSettings} for the format. + */ + this.operationsClient = opts => { + if (gaxGrpc.fallback) { + opts.fallback = gaxGrpc.fallback; + } + return new OperationsClient(gaxGrpc, operationsProtos, opts); + }; + Object.assign(this.operationsClient, OperationsClient); + } +} +exports.OperationsClientBuilder = OperationsClientBuilder; +//# sourceMappingURL=operationsClient.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/operationsClient.js.map b/node_modules/google-gax/build/src/operationsClient.js.map new file mode 100644 index 0000000..04830ce --- /dev/null +++ b/node_modules/google-gax/build/src/operationsClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"operationsClient.js","sourceRoot":"","sources":["../../src/operationsClient.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAOH,mDAA8C;AAC9C,6CAA4C;AAC5C,6BAA6B;AAI7B,8DAA+D;AAG/D,gEAAiE;AACjE,+CAAgD;AAEnC,QAAA,eAAe,GAAG,4BAA4B,CAAC;AAC5D,MAAM,OAAO,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO,CAAC;AAEtD,MAAM,oBAAoB,GAAG,GAAG,CAAC;AACjC,MAAM,qBAAqB,GAAG,aAAa,CAAC;AAE5C;;;GAGG;AACU,QAAA,UAAU,GAAa,EAAE,CAAC;AAEvC;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAa,gBAAgB;IAK3B,YACE,OAAwC;IACxC,8DAA8D;IAC9D,gBAAqB,EACrB,OAAsB;QAEtB,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CACxB;YACE,W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AM,CAAC,MAAM,CAAC,IAAI,CAAC,gBAAgB,EAAE,gBAAgB,CAAC,CAAC;IACzD,CAAC;CACF;AAnCD,0DAmCC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/operations_client_config.json b/node_modules/google-gax/build/src/operations_client_config.json new file mode 100644 index 0000000..6fd33a4 --- /dev/null +++ b/node_modules/google-gax/build/src/operations_client_config.json @@ -0,0 +1,46 @@ +{ + "interfaces": { + "google.longrunning.Operations": { + "retry_codes": { + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ], + "non_idempotent": [] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 90000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 90000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "GetOperation": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "ListOperations": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "CancelOperation": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "DeleteOperation": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/node_modules/google-gax/build/src/paginationCalls/pageDescriptor.d.ts b/node_modules/google-gax/build/src/paginationCalls/pageDescriptor.d.ts new file mode 100644 index 0000000..c23a093 --- /dev/null +++ b/node_modules/google-gax/build/src/paginationCalls/pageDescriptor.d.ts @@ -0,0 +1,43 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Transform } from 'stream'; +import { APICaller } from '../apiCaller'; +import { GaxCall, RequestType } from '../apitypes'; +import { Descriptor } from '../descriptor'; +import { CallSettings } from '../gax'; +export interface ResponseType { + [index: string]: string; +} +/** + * A descriptor for methods that support pagination. + */ +export declare class PageDescriptor implements Descriptor { + requestPageTokenField: string; + responsePageTokenField: string; + requestPageSizeField?: string; + resourceField: string; + constructor(requestPageTokenField: string, responsePageTokenField: string, resourceField: string); + /** + * Creates a new object Stream which emits the resource on 'data' event. + */ + createStream(apiCall: GaxCall, request: {}, options: CallSettings): Transform; + /** + * Create an async iterable which can be recursively called for data on-demand. + */ + asyncIterate(apiCall: GaxCall, request: RequestType, options?: CallSettings): AsyncIterable<{} | undefined>; + createIterator(apiCall: GaxCall, request: RequestType, options: CallSettings): AsyncIterable<{} | undefined>; + getApiCaller(settings: CallSettings): APICaller; +} diff --git a/node_modules/google-gax/build/src/paginationCalls/pageDescriptor.js b/node_modules/google-gax/build/src/paginationCalls/pageDescriptor.js new file mode 100644 index 0000000..498df80 --- /dev/null +++ b/node_modules/google-gax/build/src/paginationCalls/pageDescriptor.js @@ -0,0 +1,159 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PageDescriptor = void 0; +const stream_1 = require("stream"); +const normalApiCaller_1 = require("../normalCalls/normalApiCaller"); +const warnings_1 = require(".././warnings"); +const pagedApiCaller_1 = require("./pagedApiCaller"); +const maxAttemptsEmptyResponse = 10; +/** + * A descriptor for methods that support pagination. + */ +class PageDescriptor { + constructor(requestPageTokenField, responsePageTokenField, resourceField) { + this.requestPageTokenField = requestPageTokenField; + this.responsePageTokenField = responsePageTokenField; + this.resourceField = resourceField; + } + /** + * Creates a new object Stream which emits the resource on 'data' event. + */ + createStream(apiCall, request, options) { + if (options === null || options === void 0 ? void 0 : options.autoPaginate) { + (0, warnings_1.warn)('autoPaginate true', 'Autopaginate will always be set to false in stream paging methods. See more info at https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination for more information on how to configure paging calls', 'AutopaginateTrueWarning'); + } + const stream = new stream_1.PassThrough({ objectMode: true }); + options = Object.assign({}, options, { autoPaginate: false }); + const maxResults = 'maxResults' in options ? options.maxResults : -1; + let pushCount = 0; + let started = false; + function callback(err, resources, next, apiResp) { + if (err) { + stream.emit('error', err); + return; + } + // emit full api response with every page. + stream.emit('response', apiResp); + for (let i = 0; i < resources.length; ++i) { + // TODO: rewrite without accessing stream internals + if (stream + ._readableState.ended) { + return; + } + if (resources[i] === null) { + continue; + } + stream.push(resources[i]); + pushCount++; + if (pushCount === maxResults) { + stream.end(); + } + } + // TODO: rewrite without accessing stream internals + if (stream._readableState + .ended) { + return; + } + if (!next) { + stream.end(); + return; + } + // When pageToken is specified in the original options, it will overwrite + // the page token field in the next request. Therefore it must be cleared. + if ('pageToken' in options) { + delete options.pageToken; + } + if (stream.isPaused()) { + request = next; + started = false; + } + else { + setImmediate(apiCall, next, options, callback); + } + } + stream.on('resume', () => { + if (!started) { + started = true; + apiCall(request, options, callback); + } + }); + return stream; + } + /** + * Create an async iterable which can be recursively called for data on-demand. + */ + asyncIterate(apiCall, request, options) { + if (options === null || options === void 0 ? void 0 : options.autoPaginate) { + (0, warnings_1.warn)('autoPaginate true', 'Autopaginate will always be set to false in Async paging methods. See more info at https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination for more information on how to configure paging calls', 'AutopaginateTrueWarning'); + } + options = Object.assign({}, options, { autoPaginate: false }); + const iterable = this.createIterator(apiCall, request, options); + return iterable; + } + createIterator(apiCall, request, options) { + const asyncIterable = { + [Symbol.asyncIterator]() { + let nextPageRequest = request; + const cache = []; + return { + async next() { + if (cache.length > 0) { + return Promise.resolve({ + done: false, + value: cache.shift(), + }); + } + let attempts = 0; + while (cache.length === 0 && nextPageRequest) { + let result; + [result, nextPageRequest] = (await apiCall(nextPageRequest, options)); + // For pagination response with protobuf map type, use tuple as representation. + if (result && !Array.isArray(result)) { + for (const [key, value] of Object.entries(result)) { + cache.push([key, value]); + } + } + else { + cache.push(...result); + } + if (cache.length === 0) { + ++attempts; + if (attempts > maxAttemptsEmptyResponse) { + break; + } + } + } + if (cache.length === 0) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: cache.shift() }); + }, + }; + }, + }; + return asyncIterable; + } + getApiCaller(settings) { + if (!settings.autoPaginate) { + return new normalApiCaller_1.NormalApiCaller(); + } + return new pagedApiCaller_1.PagedApiCaller(this); + } +} +exports.PageDescriptor = PageDescriptor; +//# sourceMappingURL=pageDescriptor.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/paginationCalls/pageDescriptor.js.map b/node_modules/google-gax/build/src/paginationCalls/pageDescriptor.js.map new file mode 100644 index 0000000..9710f50 --- /dev/null +++ b/node_modules/google-gax/build/src/paginationCalls/pageDescriptor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pageDescriptor.js","sourceRoot":"","sources":["../../../src/paginationCalls/pageDescriptor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,mCAA8C;AAa9C,oEAA+D;AAC/D,4CAAmC;AAEnC,qDAAgD;AAEhD,MAAM,wBAAwB,GAAG,EAAE,CAAC;AAKpC;;GAEG;AACH,MAAa,cAAc;IAMzB,YACE,qBAA6B,EAC7B,sBAA8B,EAC9B,aAAqB;QAErB,IAAI,CAAC,qBAAqB,GAAG,qBAAqB,CAAC;QACnD,IAAI,CAAC,sBAAsB,GAAG,sBAAsB,CAAC;QACrD,IA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KAAK,CAAC,EAAE,CAAC;gCACvB,EAAE,QAAQ,CAAC;gCACX,IAAI,QAAQ,GAAG,wBAAwB,EAAE,CAAC;oCACxC,MAAM;gCACR,CAAC;4BACH,CAAC;wBACH,CAAC;wBACD,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;4BACvB,OAAO,OAAO,CAAC,OAAO,CAAC,EAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAC,CAAC,CAAC;wBACzD,CAAC;wBACD,OAAO,OAAO,CAAC,OAAO,CAAC,EAAC,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,EAAC,CAAC,CAAC;oBAC9D,CAAC;iBACF,CAAC;YACJ,CAAC;SACF,CAAC;QACF,OAAO,aAAa,CAAC;IACvB,CAAC;IAED,YAAY,CAAC,QAAsB;QACjC,IAAI,CAAC,QAAQ,CAAC,YAAY,EAAE,CAAC;YAC3B,OAAO,IAAI,iCAAe,EAAE,CAAC;QAC/B,CAAC;QACD,OAAO,IAAI,+BAAc,CAAC,IAAI,CAAC,CAAC;IAClC,CAAC;CACF;AA7KD,wCA6KC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/paginationCalls/pagedApiCaller.d.ts b/node_modules/google-gax/build/src/paginationCalls/pagedApiCaller.d.ts new file mode 100644 index 0000000..dc33aca --- /dev/null +++ b/node_modules/google-gax/build/src/paginationCalls/pagedApiCaller.d.ts @@ -0,0 +1,80 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { APICaller } from '../apiCaller'; +import { GRPCCall, SimpleCallbackFunction, RequestType } from '../apitypes'; +import { APICallback } from '../apitypes'; +import { OngoingCall, OngoingCallPromise } from '../call'; +import { CallOptions } from '../gax'; +import { GoogleError } from '../googleError'; +import { PageDescriptor } from './pageDescriptor'; +export declare class PagedApiCaller implements APICaller { + pageDescriptor: PageDescriptor; + /** + * Creates an API caller that returns a stream to performs page-streaming. + * + * @private + * @constructor + * @param {PageDescriptor} pageDescriptor - indicates the structure + * of page streaming to be performed. + */ + constructor(pageDescriptor: PageDescriptor); + /** + * This function translates between regular gRPC calls (that accepts a request and returns a response, + * and does not know anything about pages and page tokens) and the users' callback (that expects + * to see resources from one page, a request to get the next page, and the raw response from the server). + * + * It generates a function that can be passed as a callback function to a gRPC call, will understand + * pagination-specific fields in the response, and call the users' callback after having those fields + * parsed. + * + * @param request Request object. It needs to be passed to all subsequent next page requests + * (the main content of the request object stays unchanged, only the next page token changes) + * @param callback The user's callback that expects the page content, next page request, and raw response. + */ + private generateParseResponseCallback; + /** + * Adds a special ability to understand pagination-specific fields to the existing gRPC call. + * The original gRPC call just calls callback(err, result). + * The wrapped one will call callback(err, resources, nextPageRequest, rawResponse) instead. + * + * @param func gRPC call (normally, a service stub call). The gRPC call is expected to accept four parameters: + * request, metadata, call options, and callback. + */ + wrap(func: GRPCCall): GRPCCall; + /** + * Makes it possible to use both callback-based and promise-based calls. + * Returns an OngoingCall or OngoingCallPromise object. + * Regardless of which one is returned, it always has a `.callback` to call. + * + * @param settings Call settings. Can only be used to replace Promise with another promise implementation. + * @param [callback] Callback to be called, if any. + */ + init(callback?: APICallback): OngoingCall; + /** + * Implements auto-pagination logic. + * + * @param apiCall A function that performs gRPC request and calls its callback with a response or an error. + * It's supposed to be a gRPC service stub function wrapped into several layers of wrappers that make it + * accept just two parameters: (request, callback). + * @param request A request object that came from the user. + * @param settings Call settings. We are interested in `maxResults` and `autoPaginate` (they are optional). + * @param ongoingCall An instance of OngoingCall or OngoingCallPromise that can be used for call cancellation, + * and is used to return results to the user. + */ + call(apiCall: SimpleCallbackFunction, request: RequestType, settings: CallOptions, ongoingCall: OngoingCall): void; + fail(ongoingCall: OngoingCallPromise, err: GoogleError): void; + result(ongoingCall: OngoingCallPromise): import("../call").CancellablePromise; +} diff --git a/node_modules/google-gax/build/src/paginationCalls/pagedApiCaller.js b/node_modules/google-gax/build/src/paginationCalls/pagedApiCaller.js new file mode 100644 index 0000000..1ad178c --- /dev/null +++ b/node_modules/google-gax/build/src/paginationCalls/pagedApiCaller.js @@ -0,0 +1,137 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PagedApiCaller = void 0; +const call_1 = require("../call"); +const googleError_1 = require("../googleError"); +const resourceCollector_1 = require("./resourceCollector"); +const warnings_1 = require(".././warnings"); +class PagedApiCaller { + /** + * Creates an API caller that returns a stream to performs page-streaming. + * + * @private + * @constructor + * @param {PageDescriptor} pageDescriptor - indicates the structure + * of page streaming to be performed. + */ + constructor(pageDescriptor) { + this.pageDescriptor = pageDescriptor; + } + /** + * This function translates between regular gRPC calls (that accepts a request and returns a response, + * and does not know anything about pages and page tokens) and the users' callback (that expects + * to see resources from one page, a request to get the next page, and the raw response from the server). + * + * It generates a function that can be passed as a callback function to a gRPC call, will understand + * pagination-specific fields in the response, and call the users' callback after having those fields + * parsed. + * + * @param request Request object. It needs to be passed to all subsequent next page requests + * (the main content of the request object stays unchanged, only the next page token changes) + * @param callback The user's callback that expects the page content, next page request, and raw response. + */ + generateParseResponseCallback(request, callback) { + const resourceFieldName = this.pageDescriptor.resourceField; + const responsePageTokenFieldName = this.pageDescriptor.responsePageTokenField; + const requestPageTokenFieldName = this.pageDescriptor.requestPageTokenField; + return (err, response) => { + if (err) { + callback(err); + return; + } + if (!request) { + callback(new googleError_1.GoogleError('Undefined request in pagination method callback.')); + return; + } + if (!response) { + callback(new googleError_1.GoogleError('Undefined response in pagination method callback.')); + return; + } + const resources = response[resourceFieldName] || []; + const pageToken = response[responsePageTokenFieldName]; + let nextPageRequest = null; + if (pageToken) { + nextPageRequest = Object.assign({}, request); + nextPageRequest[requestPageTokenFieldName] = pageToken; + } + callback(err, resources, nextPageRequest, response); + }; + } + /** + * Adds a special ability to understand pagination-specific fields to the existing gRPC call. + * The original gRPC call just calls callback(err, result). + * The wrapped one will call callback(err, resources, nextPageRequest, rawResponse) instead. + * + * @param func gRPC call (normally, a service stub call). The gRPC call is expected to accept four parameters: + * request, metadata, call options, and callback. + */ + wrap(func) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const self = this; + return function wrappedCall(argument, metadata, options, callback) { + return func(argument, metadata, options, self.generateParseResponseCallback(argument, callback)); + }; + } + /** + * Makes it possible to use both callback-based and promise-based calls. + * Returns an OngoingCall or OngoingCallPromise object. + * Regardless of which one is returned, it always has a `.callback` to call. + * + * @param settings Call settings. Can only be used to replace Promise with another promise implementation. + * @param [callback] Callback to be called, if any. + */ + init(callback) { + if (callback) { + return new call_1.OngoingCall(callback); + } + return new call_1.OngoingCallPromise(); + } + /** + * Implements auto-pagination logic. + * + * @param apiCall A function that performs gRPC request and calls its callback with a response or an error. + * It's supposed to be a gRPC service stub function wrapped into several layers of wrappers that make it + * accept just two parameters: (request, callback). + * @param request A request object that came from the user. + * @param settings Call settings. We are interested in `maxResults` and `autoPaginate` (they are optional). + * @param ongoingCall An instance of OngoingCall or OngoingCallPromise that can be used for call cancellation, + * and is used to return results to the user. + */ + call(apiCall, request, settings, ongoingCall) { + request = Object.assign({}, request); + if (!settings.autoPaginate) { + // they don't want auto-pagination this time - okay, just call once + ongoingCall.call(apiCall, request); + return; + } + if (request.pageSize && settings.autoPaginate) { + (0, warnings_1.warn)('autoPaginate true', 'Providing a pageSize without setting autoPaginate to false will still return all results. See https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination for more information on how to configure manual paging', 'AutopaginateTrueWarning'); + } + const maxResults = settings.maxResults || -1; + const resourceCollector = new resourceCollector_1.ResourceCollector(apiCall, maxResults); + resourceCollector.processAllPages(request).then(resources => ongoingCall.callback(null, resources), err => ongoingCall.callback(err)); + } + fail(ongoingCall, err) { + ongoingCall.callback(err); + } + result(ongoingCall) { + return ongoingCall.promise; + } +} +exports.PagedApiCaller = PagedApiCaller; +//# sourceMappingURL=pagedApiCaller.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/paginationCalls/pagedApiCaller.js.map b/node_modules/google-gax/build/src/paginationCalls/pagedApiCaller.js.map new file mode 100644 index 0000000..9d6b542 --- /dev/null +++ b/node_modules/google-gax/build/src/paginationCalls/pagedApiCaller.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pagedApiCaller.js","sourceRoot":"","sources":["../../../src/paginationCalls/pagedApiCaller.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAWH,kCAAwD;AAExD,gDAA2C;AAE3C,2DAAsD;AACtD,4CAAmC;AAEnC,MAAa,cAAc;IAEzB;;;;;;;OAOG;IACH,YAAY,cAA8B;QACxC,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;IACvC,CAAC;IAED;;;;;;;;;;;;OAYG;IACK,6BAA6B,CACnC,OAA4B,EAC5B,QAAqB;QAErB,MAAM,iBAAiB,GAAG,IAAI,CAAC,cAAc,CAAC,aAAa,CAAC;QAC5D,MAAM,0BAA0B,GAC9B,IAAI,CAAC,cAAc,CAAC,sBAAsB,CAAC;QAC7C,MAAM,yBAAyB,GAAG,IAAI,CAAC,cAAc,CAAC,qBAAqB,CAAC;QAC5E,OAAO,CAAC,GAAiB,EAAE,QAAyC,EAAE,EAAE;YACtE,IAAI,GAAG,EAAE,CAA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,CAAC;IAClC,CAAC;IAED;;;;;;;;;;OAUG;IACH,IAAI,CACF,OAA+B,EAC/B,OAAoB,EACpB,QAAqB,EACrB,WAAwB;QAExB,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QAErC,IAAI,CAAC,QAAQ,CAAC,YAAY,EAAE,CAAC;YAC3B,mEAAmE;YACnE,WAAW,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACnC,OAAO;QACT,CAAC;QACD,IAAI,OAAO,CAAC,QAAQ,IAAI,QAAQ,CAAC,YAAY,EAAE,CAAC;YAC9C,IAAA,eAAI,EACF,mBAAmB,EACnB,6OAA6O,EAC7O,yBAAyB,CAC1B,CAAC;QACJ,CAAC;QAED,MAAM,UAAU,GAAG,QAAQ,CAAC,UAAU,IAAI,CAAC,CAAC,CAAC;QAE7C,MAAM,iBAAiB,GAAG,IAAI,qCAAiB,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;QACrE,iBAAiB,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,IAAI,CAC7C,SAAS,CAAC,EAAE,CAAC,WAAW,CAAC,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC,EAClD,GAAG,CAAC,EAAE,CAAC,WAAW,CAAC,QAAQ,CAAC,GAAG,CAAC,CACjC,CAAC;IACJ,CAAC;IAED,IAAI,CAAC,WAA+B,EAAE,GAAgB;QACpD,WAAW,CAAC,QAAS,CAAC,GAAG,CAAC,CAAC;IAC7B,CAAC;IAED,MAAM,CAAC,WAA+B;QACpC,OAAO,WAAW,CAAC,OAAO,CAAC;IAC7B,CAAC;CACF;AAnJD,wCAmJC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/paginationCalls/resourceCollector.d.ts b/node_modules/google-gax/build/src/paginationCalls/resourceCollector.d.ts new file mode 100644 index 0000000..77e7c3a --- /dev/null +++ b/node_modules/google-gax/build/src/paginationCalls/resourceCollector.d.ts @@ -0,0 +1,34 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SimpleCallbackFunction, RequestType } from '../apitypes'; +/** + * ResourceCollector class implements asynchronous logic of calling the API call that supports pagination, + * page by page, collecting all resources (up to `maxResults`) in the array. + * + * Usage: + * const resourceCollector = new ResourceCollector(apiCall, maxResults); // -1 for unlimited + * resourceCollector.processAllPages(request).then(resources => ...); + */ +export declare class ResourceCollector { + apiCall: SimpleCallbackFunction; + resources: Array<{}>; + maxResults: number; + resolveCallback?: (resources: Array<{}>) => void; + rejectCallback?: (err: Error) => void; + constructor(apiCall: SimpleCallbackFunction, maxResults?: number); + private callback; + processAllPages(firstRequest: RequestType): Promise>; +} diff --git a/node_modules/google-gax/build/src/paginationCalls/resourceCollector.js b/node_modules/google-gax/build/src/paginationCalls/resourceCollector.js new file mode 100644 index 0000000..2b29a21 --- /dev/null +++ b/node_modules/google-gax/build/src/paginationCalls/resourceCollector.js @@ -0,0 +1,67 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ResourceCollector = void 0; +/** + * ResourceCollector class implements asynchronous logic of calling the API call that supports pagination, + * page by page, collecting all resources (up to `maxResults`) in the array. + * + * Usage: + * const resourceCollector = new ResourceCollector(apiCall, maxResults); // -1 for unlimited + * resourceCollector.processAllPages(request).then(resources => ...); + */ +class ResourceCollector { + constructor(apiCall, maxResults = -1) { + this.apiCall = apiCall; + this.resources = []; + this.maxResults = maxResults; + } + callback(err, resources, nextPageRequest) { + if (err) { + // Something went wrong with this request - failing everything + this.rejectCallback(err); + return; + } + // Process one page + for (const resource of resources) { + this.resources.push(resource); + if (this.resources.length === this.maxResults) { + nextPageRequest = null; + break; + } + } + // All done? + if (!nextPageRequest) { + this.resolveCallback(this.resources); + return; + } + // Schedule the next call + const callback = (...args) => this.callback(...args); + setImmediate(this.apiCall, nextPageRequest, callback); + } + processAllPages(firstRequest) { + return new Promise((resolve, reject) => { + this.resolveCallback = resolve; + this.rejectCallback = reject; + // Schedule the first call + const callback = (...args) => this.callback(...args); + setImmediate(this.apiCall, firstRequest, callback); + }); + } +} +exports.ResourceCollector = ResourceCollector; +//# sourceMappingURL=resourceCollector.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/paginationCalls/resourceCollector.js.map b/node_modules/google-gax/build/src/paginationCalls/resourceCollector.js.map new file mode 100644 index 0000000..8d621ff --- /dev/null +++ b/node_modules/google-gax/build/src/paginationCalls/resourceCollector.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resourceCollector.js","sourceRoot":"","sources":["../../../src/paginationCalls/resourceCollector.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AASH;;;;;;;GAOG;AACH,MAAa,iBAAiB;IAO5B,YAAY,OAA+B,EAAE,UAAU,GAAG,CAAC,CAAC;QAC1D,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;QACpB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IAEO,QAAQ,CACd,GAAiB,EACjB,SAAoB,EACpB,eAAoC;QAEpC,IAAI,GAAG,EAAE,CAAC;YACR,8DAA8D;YAC9D,IAAI,CAAC,cAAe,CAAC,GAAG,CAAC,CAAC;YAC1B,OAAO;QACT,CAAC;QAED,mBAAmB;QACnB,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;YACjC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YAC9B,IAAI,IAAI,CAAC,SAAS,CAAC,MAAM,KAAK,IAAI,CAAC,UAAU,EAAE,CAAC;gBAC9C,eAAe,GAAG,IAAI,CAAC;gBACvB,MAAM;YACR,CAAC;QACH,CAAC;QAED,YAAY;QACZ,IAAI,CAAC,eAAe,EAAE,CAAC;YACrB,IAAI,CAAC,eAAgB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YACtC,OAAO;QACT,CAAC;QAED,yBAAyB;QACzB,MAAM,QAAQ,GAAG,CACf,GAAG,IAAoD,EACvD,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAC,CAAC;QAC5B,YAAY,CAAC,IAAI,CAAC,OAAO,EAAE,eAAe,EAAE,QAAuB,CAAC,CAAC;IACvE,CAAC;IAED,eAAe,CAAC,YAAyB;QACvC,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC;YAC/B,IAAI,CAAC,cAAc,GAAG,MAAM,CAAC;YAE7B,0BAA0B;YAC1B,MAAM,QAAQ,GAAG,CACf,GAAG,IAAoD,EACvD,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAC,CAAC;YAC5B,YAAY,CAAC,IAAI,CAAC,OAAO,EAAE,YAAY,EAAE,QAAuB,CAAC,CAAC;QACpE,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA1DD,8CA0DC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/pathTemplate.d.ts b/node_modules/google-gax/build/src/pathTemplate.d.ts new file mode 100644 index 0000000..1f82ba8 --- /dev/null +++ b/node_modules/google-gax/build/src/pathTemplate.d.ts @@ -0,0 +1,60 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface Bindings { + [index: string]: string | number; +} +export declare class PathTemplate { + private data; + private bindings; + segments: string[]; + size: number; + /** + * @param {String} data the of the template + * + * @constructor + */ + constructor(data: string); + /** + * Matches a fully-qualified path template string. + * + * @param {String} path a fully-qualified path template string + * @return {Object} contains const names matched to binding values + * @throws {TypeError} if path can't be matched to this template + */ + match(path: string): Bindings; + /** + * Renders a path template using the provided bindings. + * + * @param {Object} bindings a mapping of const names to binding strings + * @return {String} a rendered representation of the path template + * @throws {TypeError} if a key is missing, or if a sub-template cannot be + * parsed + */ + render(bindings: Bindings): string; + /** + * Renders the path template. + * + * @return {string} contains const names matched to binding values + */ + inspect(): string; + /** + * Parse the path template. + * + * @return {string[]} return segments of the input path. + * For example: 'buckets/{hello}'' will give back ['buckets', {hello=*}] + */ + private parsePathTemplate; +} diff --git a/node_modules/google-gax/build/src/pathTemplate.js b/node_modules/google-gax/build/src/pathTemplate.js new file mode 100644 index 0000000..b555f8b --- /dev/null +++ b/node_modules/google-gax/build/src/pathTemplate.js @@ -0,0 +1,237 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PathTemplate = void 0; +class PathTemplate { + /** + * @param {String} data the of the template + * + * @constructor + */ + constructor(data) { + this.bindings = {}; + this.data = data; + this.segments = this.parsePathTemplate(data); + this.size = this.segments.length; + } + /** + * Matches a fully-qualified path template string. + * + * @param {String} path a fully-qualified path template string + * @return {Object} contains const names matched to binding values + * @throws {TypeError} if path can't be matched to this template + */ + match(path) { + let pathSegments = path.split('/'); + const bindings = {}; + if (pathSegments.length !== this.segments.length) { + // if the path contains a wildcard, then the length may differ by 1. + if (!this.data.includes('**')) { + throw new TypeError(`This path ${path} does not match path template ${this.data}, the number of parameters is not same.`); + } + else if (pathSegments.length !== this.segments.length + 1) { + throw new TypeError(`This path ${path} does not match path template ${this.data}, the number of parameters is not same with one wildcard.`); + } + } + for (let index = 0; index < this.segments.length && pathSegments.length > 0; index++) { + if (this.segments[index] !== pathSegments[0]) { + if (!this.segments[index].includes('*')) { + throw new TypeError(`segment does not match, ${this.segments[index]} and ${pathSegments[index]}.`); + } + else { + let segment = this.segments[index]; + const matches = segment.match(/\{[$0-9a-zA-Z_]+=.*?\}/g); + if (!matches) { + throw new Error(`Error processing path template segment ${segment}`); + } + const variables = matches.map(str => str.replace(/^\{/, '').replace(/=.*/, '')); + if (segment.includes('**')) { + bindings[variables[0]] = pathSegments[0] + '/' + pathSegments[1]; + pathSegments = pathSegments.slice(2); + } + else { + // atomic resource + if (variables.length === 1) { + bindings[variables[0]] = pathSegments[0]; + } + else { + // non-slash resource + // segment: {blurb_id=*}.{legacy_user=*} to match pathSegments: ['bar.user2'] + // split the match pathSegments[0] -> value: ['bar', 'user2'] + // compare the length of two arrays, and compare array items + const value = pathSegments[0].split(/[-_.~]/); + if (value.length !== variables.length) { + throw new Error(`segment ${segment} does not match ${pathSegments[0]}`); + } + for (const v of variables) { + bindings[v] = value[0]; + segment = segment.replace(`{${v}=*}`, `${value[0]}`); + value.shift(); + } + // segment: {blurb_id=*}.{legacy_user=*} matching pathSegments: ['bar~user2'] should fail + if (segment !== pathSegments[0]) { + throw new TypeError(`non slash resource pattern ${this.segments[index]} and ${pathSegments[0]} should have same separator`); + } + } + pathSegments.shift(); + } + } + } + else { + pathSegments.shift(); + } + } + return bindings; + } + /** + * Renders a path template using the provided bindings. + * + * @param {Object} bindings a mapping of const names to binding strings + * @return {String} a rendered representation of the path template + * @throws {TypeError} if a key is missing, or if a sub-template cannot be + * parsed + */ + render(bindings) { + if (Object.keys(bindings).length !== Object.keys(this.bindings).length) { + throw new TypeError(`The number of variables ${Object.keys(bindings).length} does not match the number of needed variables ${Object.keys(this.bindings).length}`); + } + let path = this.inspect(); + for (const key of Object.keys(bindings)) { + const b = bindings[key].toString(); + if (!this.bindings[key]) { + throw new TypeError(`render fails for not matching ${bindings[key]}`); + } + const variable = this.bindings[key]; + if (variable === '*') { + if (!b.match(/[^/{}]+/)) { + throw new TypeError(`render fails for not matching ${b}`); + } + path = path.replace(`{${key}=*}`, `${b}`); + } + else if (variable === '**') { + if (!b.match(/[^{}]+/)) { + throw new TypeError(`render fails for not matching ${b}`); + } + path = path.replace(`{${key}=**}`, `${b}`); + } + } + return path; + } + /** + * Renders the path template. + * + * @return {string} contains const names matched to binding values + */ + inspect() { + return this.segments.join('/'); + } + /** + * Parse the path template. + * + * @return {string[]} return segments of the input path. + * For example: 'buckets/{hello}'' will give back ['buckets', {hello=*}] + */ + parsePathTemplate(data) { + const pathSegments = splitPathTemplate(data); + let index = 0; + let wildCardCount = 0; + const segments = []; + let matches; + pathSegments.forEach(segment => { + // * or ** -> segments.push('{$0=*}'); + // -> bindings['$0'] = '*' + if (segment === '*' || segment === '**') { + this.bindings[`$${index}`] = segment; + segments.push(`{$${index}=${segment}}`); + index = index + 1; + if (segment === '**') { + ++wildCardCount; + } + } + else if ((matches = segment.match(/\{[0-9a-zA-Z-.~_]+(?:=.*?)?\}/g))) { + for (const subsegment of matches) { + const pairMatch = subsegment.match(/^\{([0-9a-zA-Z-.~_]+)(?:=(.*?))?\}$/); + if (!pairMatch) { + throw new Error(`Cannot process path template segment ${subsegment}`); + } + const key = pairMatch[1]; + let value = pairMatch[2]; + if (!value) { + value = '*'; + segment = segment.replace(key, key + '=*'); + this.bindings[key] = value; + } + else if (value === '*') { + this.bindings[key] = value; + } + else if (value === '**') { + ++wildCardCount; + this.bindings[key] = value; + } + } + segments.push(segment); + } + else if (segment.match(/[0-9a-zA-Z-.~_]+/)) { + segments.push(segment); + } + }); + if (wildCardCount > 1) { + throw new TypeError('Can not have more than one wildcard.'); + } + return segments; + } +} +exports.PathTemplate = PathTemplate; +/** + * Split the path template by `/`. + * It can not be simply splitted by `/` because there might be `/` in the segments. + * For example: 'a/b/{a=hello/world}' we do not want to break the brackets pair + * so above path will be splitted as ['a', 'b', '{a=hello/world}'] + */ +function splitPathTemplate(data) { + let left = 0; + let right = 0; + let bracketCount = 0; + const segments = []; + while (right >= left && right < data.length) { + if (data.charAt(right) === '{') { + bracketCount = bracketCount + 1; + } + else if (data.charAt(right) === '}') { + bracketCount = bracketCount - 1; + } + else if (data.charAt(right) === '/') { + if (right === data.length - 1) { + throw new TypeError('Invalid path, it can not be ended by /'); + } + if (bracketCount === 0) { + // complete bracket, to avoid the case a/b/**/*/{a=hello/world} + segments.push(data.substring(left, right)); + left = right + 1; + } + } + if (right === data.length - 1) { + if (bracketCount !== 0) { + throw new TypeError('Brackets are invalid.'); + } + segments.push(data.substring(left)); + } + right = right + 1; + } + return segments; +} +//# sourceMappingURL=pathTemplate.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/pathTemplate.js.map b/node_modules/google-gax/build/src/pathTemplate.js.map new file mode 100644 index 0000000..d8ccdec --- /dev/null +++ b/node_modules/google-gax/build/src/pathTemplate.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pathTemplate.js","sourceRoot":"","sources":["../../src/pathTemplate.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAUH,MAAa,YAAY;IAKvB;;;;OAIG;IACH,YAA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ACtC,IAAI,KAAK,KAAK,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBAC9B,MAAM,IAAI,SAAS,CAAC,wCAAwC,CAAC,CAAC;YAChE,CAAC;YACD,IAAI,YAAY,KAAK,CAAC,EAAE,CAAC;gBACvB,+DAA+D;gBAC/D,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;gBAC3C,IAAI,GAAG,KAAK,GAAG,CAAC,CAAC;YACnB,CAAC;QACH,CAAC;QACD,IAAI,KAAK,KAAK,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC9B,IAAI,YAAY,KAAK,CAAC,EAAE,CAAC;gBACvB,MAAM,IAAI,SAAS,CAAC,uBAAuB,CAAC,CAAC;YAC/C,CAAC;YACD,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;QACtC,CAAC;QACD,KAAK,GAAG,KAAK,GAAG,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/protobuf.d.ts b/node_modules/google-gax/build/src/protobuf.d.ts new file mode 100644 index 0000000..954161d --- /dev/null +++ b/node_modules/google-gax/build/src/protobuf.d.ts @@ -0,0 +1,16 @@ +/** + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * as protobufMinimal from 'protobufjs/minimal'; diff --git a/node_modules/google-gax/build/src/protobuf.js b/node_modules/google-gax/build/src/protobuf.js new file mode 100644 index 0000000..e99c98d --- /dev/null +++ b/node_modules/google-gax/build/src/protobuf.js @@ -0,0 +1,25 @@ +"use strict"; +/** + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.protobufMinimal = void 0; +// This file is here to re-export protobuf.js so that the proto.js files +// produced by tools/compileProtos.ts did not depend on protobuf.js +// directly. +// Usage: +// const {protobufMinimal} = require('google-gax/build/src/protobuf'); +exports.protobufMinimal = require("protobufjs/minimal"); +//# sourceMappingURL=protobuf.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/protobuf.js.map b/node_modules/google-gax/build/src/protobuf.js.map new file mode 100644 index 0000000..e52e624 --- /dev/null +++ b/node_modules/google-gax/build/src/protobuf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"protobuf.js","sourceRoot":"","sources":["../../src/protobuf.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,wEAAwE;AACxE,mEAAmE;AACnE,YAAY;AACZ,SAAS;AACT,wEAAwE;AAExE,wDAAsD"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/protosList.json b/node_modules/google-gax/build/src/protosList.json new file mode 100644 index 0000000..bde542c --- /dev/null +++ b/node_modules/google-gax/build/src/protosList.json @@ -0,0 +1,137 @@ +[ + "google/api/annotations.proto", + "google/api/apikeys/v2/apikeys.proto", + "google/api/apikeys/v2/resources.proto", + "google/api/auth.proto", + "google/api/backend.proto", + "google/api/billing.proto", + "google/api/client.proto", + "google/api/cloudquotas/v1/cloudquotas.proto", + "google/api/cloudquotas/v1/resources.proto", + "google/api/config_change.proto", + "google/api/consumer.proto", + "google/api/context.proto", + "google/api/control.proto", + "google/api/distribution.proto", + "google/api/documentation.proto", + "google/api/endpoint.proto", + "google/api/error_reason.proto", + "google/api/expr/conformance/v1alpha1/conformance_service.proto", + "google/api/expr/v1alpha1/checked.proto", + "google/api/expr/v1alpha1/eval.proto", + "google/api/expr/v1alpha1/explain.proto", + "google/api/expr/v1alpha1/syntax.proto", + "google/api/expr/v1alpha1/value.proto", + "google/api/expr/v1beta1/decl.proto", + "google/api/expr/v1beta1/eval.proto", + "google/api/expr/v1beta1/expr.proto", + "google/api/expr/v1beta1/source.proto", + "google/api/expr/v1beta1/value.proto", + "google/api/field_behavior.proto", + "google/api/field_info.proto", + "google/api/http.proto", + "google/api/httpbody.proto", + "google/api/label.proto", + "google/api/launch_stage.proto", + "google/api/log.proto", + "google/api/logging.proto", + "google/api/metric.proto", + "google/api/monitored_resource.proto", + "google/api/monitoring.proto", + "google/api/policy.proto", + "google/api/quota.proto", + "google/api/resource.proto", + "google/api/routing.proto", + "google/api/service.proto", + "google/api/servicecontrol/v1/check_error.proto", + "google/api/servicecontrol/v1/distribution.proto", + "google/api/servicecontrol/v1/http_request.proto", + "google/api/servicecontrol/v1/log_entry.proto", + "google/api/servicecontrol/v1/metric_value.proto", + "google/api/servicecontrol/v1/operation.proto", + "google/api/servicecontrol/v1/quota_controller.proto", + "google/api/servicecontrol/v1/service_controller.proto", + "google/api/servicecontrol/v2/service_controller.proto", + "google/api/servicemanagement/v1/resources.proto", + "google/api/servicemanagement/v1/servicemanager.proto", + "google/api/serviceusage/v1/resources.proto", + "google/api/serviceusage/v1/serviceusage.proto", + "google/api/serviceusage/v1beta1/resources.proto", + "google/api/serviceusage/v1beta1/serviceusage.proto", + "google/api/source_info.proto", + "google/api/system_parameter.proto", + "google/api/usage.proto", + "google/api/visibility.proto", + "google/cloud/location/locations.proto", + "google/iam/v1/iam_policy.proto", + "google/iam/v1/logging/audit_data.proto", + "google/iam/v1/options.proto", + "google/iam/v1/policy.proto", + "google/logging/type/http_request.proto", + "google/logging/type/log_severity.proto", + "google/longrunning/operations.proto", + "google/monitoring/v3/alert.proto", + "google/monitoring/v3/alert_service.proto", + "google/monitoring/v3/common.proto", + "google/monitoring/v3/dropped_labels.proto", + "google/monitoring/v3/group.proto", + "google/monitoring/v3/group_service.proto", + "google/monitoring/v3/metric.proto", + "google/monitoring/v3/metric_service.proto", + "google/monitoring/v3/mutation_record.proto", + "google/monitoring/v3/notification.proto", + "google/monitoring/v3/notification_service.proto", + "google/monitoring/v3/query_service.proto", + "google/monitoring/v3/service.proto", + "google/monitoring/v3/service_service.proto", + "google/monitoring/v3/snooze.proto", + "google/monitoring/v3/snooze_service.proto", + "google/monitoring/v3/span_context.proto", + "google/monitoring/v3/uptime.proto", + "google/monitoring/v3/uptime_service.proto", + "google/protobuf/any.proto", + "google/protobuf/api.proto", + "google/protobuf/bridge/message_set.proto", + "google/protobuf/compiler/plugin.proto", + "google/protobuf/compiler/ruby/ruby_generated_code.proto", + "google/protobuf/compiler/ruby/ruby_generated_code_proto2.proto", + "google/protobuf/compiler/ruby/ruby_generated_code_proto2_import.proto", + "google/protobuf/compiler/ruby/ruby_generated_pkg_explicit.proto", + "google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy.proto", + "google/protobuf/compiler/ruby/ruby_generated_pkg_implicit.proto", + "google/protobuf/cpp_features.proto", + "google/protobuf/descriptor.proto", + "google/protobuf/duration.proto", + "google/protobuf/empty.proto", + "google/protobuf/field_mask.proto", + "google/protobuf/source_context.proto", + "google/protobuf/struct.proto", + "google/protobuf/timestamp.proto", + "google/protobuf/type.proto", + "google/protobuf/util/json_format.proto", + "google/protobuf/util/json_format_proto3.proto", + "google/protobuf/wrappers.proto", + "google/rpc/code.proto", + "google/rpc/context/attribute_context.proto", + "google/rpc/context/audit_context.proto", + "google/rpc/error_details.proto", + "google/rpc/http.proto", + "google/rpc/status.proto", + "google/type/calendar_period.proto", + "google/type/color.proto", + "google/type/date.proto", + "google/type/datetime.proto", + "google/type/dayofweek.proto", + "google/type/decimal.proto", + "google/type/expr.proto", + "google/type/fraction.proto", + "google/type/interval.proto", + "google/type/latlng.proto", + "google/type/localized_text.proto", + "google/type/money.proto", + "google/type/month.proto", + "google/type/phone_number.proto", + "google/type/postal_address.proto", + "google/type/quaternion.proto", + "google/type/timeofday.proto" +] diff --git a/node_modules/google-gax/build/src/routingHeader.d.ts b/node_modules/google-gax/build/src/routingHeader.d.ts new file mode 100644 index 0000000..34daa02 --- /dev/null +++ b/node_modules/google-gax/build/src/routingHeader.d.ts @@ -0,0 +1,32 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helpers for constructing routing headers. + * + * These headers are used by Google infrastructure to determine how to route + * requests, especially for services that are regional. + * + * Generally, these headers are specified as gRPC metadata. + */ +/** + * Constructs the routing header from the given params + * + * @param {Object} params - the request header parameters. + * @return {string} the routing header value. + */ +export declare function fromParams(params: { + [index: string]: string | number | boolean; +}): string; diff --git a/node_modules/google-gax/build/src/routingHeader.js b/node_modules/google-gax/build/src/routingHeader.js new file mode 100644 index 0000000..38d5ad4 --- /dev/null +++ b/node_modules/google-gax/build/src/routingHeader.js @@ -0,0 +1,37 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromParams = fromParams; +const querystring = require("querystring"); +/** + * Helpers for constructing routing headers. + * + * These headers are used by Google infrastructure to determine how to route + * requests, especially for services that are regional. + * + * Generally, these headers are specified as gRPC metadata. + */ +/** + * Constructs the routing header from the given params + * + * @param {Object} params - the request header parameters. + * @return {string} the routing header value. + */ +function fromParams(params) { + return querystring.stringify(params); +} +//# sourceMappingURL=routingHeader.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/routingHeader.js.map b/node_modules/google-gax/build/src/routingHeader.js.map new file mode 100644 index 0000000..8917ad3 --- /dev/null +++ b/node_modules/google-gax/build/src/routingHeader.js.map @@ -0,0 +1 @@ +{"version":3,"file":"routingHeader.js","sourceRoot":"","sources":["../../src/routingHeader.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAoBH,gCAIC;AAtBD,2CAA2C;AAE3C;;;;;;;GAOG;AAEH;;;;;GAKG;AAEH,SAAgB,UAAU,CAAC,MAE1B;IACC,OAAO,WAAW,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;AACvC,CAAC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/status.d.ts b/node_modules/google-gax/build/src/status.d.ts new file mode 100644 index 0000000..bdafa63 --- /dev/null +++ b/node_modules/google-gax/build/src/status.d.ts @@ -0,0 +1,36 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare enum Status { + OK = 0, + CANCELLED = 1, + UNKNOWN = 2, + INVALID_ARGUMENT = 3, + DEADLINE_EXCEEDED = 4, + NOT_FOUND = 5, + ALREADY_EXISTS = 6, + PERMISSION_DENIED = 7, + RESOURCE_EXHAUSTED = 8, + FAILED_PRECONDITION = 9, + ABORTED = 10, + OUT_OF_RANGE = 11, + UNIMPLEMENTED = 12, + INTERNAL = 13, + UNAVAILABLE = 14, + DATA_LOSS = 15, + UNAUTHENTICATED = 16 +} +export declare const HttpCodeToRpcCodeMap: Map; +export declare function rpcCodeFromHttpStatusCode(httpStatusCode: number): number; diff --git a/node_modules/google-gax/build/src/status.js b/node_modules/google-gax/build/src/status.js new file mode 100644 index 0000000..238d6ee --- /dev/null +++ b/node_modules/google-gax/build/src/status.js @@ -0,0 +1,77 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HttpCodeToRpcCodeMap = exports.Status = void 0; +exports.rpcCodeFromHttpStatusCode = rpcCodeFromHttpStatusCode; +// The following is a copy of the Status enum defined in @grpc/grpc-js, +// src/constants.ts. We need to use some of these statuses here and there, +// but we don't want to include the whole @grpc/grpc-js into the browser +// bundle just to have this small enum. +var Status; +(function (Status) { + Status[Status["OK"] = 0] = "OK"; + Status[Status["CANCELLED"] = 1] = "CANCELLED"; + Status[Status["UNKNOWN"] = 2] = "UNKNOWN"; + Status[Status["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT"; + Status[Status["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED"; + Status[Status["NOT_FOUND"] = 5] = "NOT_FOUND"; + Status[Status["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS"; + Status[Status["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED"; + Status[Status["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED"; + Status[Status["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION"; + Status[Status["ABORTED"] = 10] = "ABORTED"; + Status[Status["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE"; + Status[Status["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED"; + Status[Status["INTERNAL"] = 13] = "INTERNAL"; + Status[Status["UNAVAILABLE"] = 14] = "UNAVAILABLE"; + Status[Status["DATA_LOSS"] = 15] = "DATA_LOSS"; + Status[Status["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED"; +})(Status || (exports.Status = Status = {})); +exports.HttpCodeToRpcCodeMap = new Map([ + [400, Status.INVALID_ARGUMENT], + [401, Status.UNAUTHENTICATED], + [403, Status.PERMISSION_DENIED], + [404, Status.NOT_FOUND], + [409, Status.ABORTED], + [416, Status.OUT_OF_RANGE], + [429, Status.RESOURCE_EXHAUSTED], + [499, Status.CANCELLED], + [501, Status.UNIMPLEMENTED], + [503, Status.UNAVAILABLE], + [504, Status.DEADLINE_EXCEEDED], +]); +// Maps HTTP status codes to gRPC status codes above. +function rpcCodeFromHttpStatusCode(httpStatusCode) { + if (exports.HttpCodeToRpcCodeMap.has(httpStatusCode)) { + return exports.HttpCodeToRpcCodeMap.get(httpStatusCode); + } + // All 2xx + if (httpStatusCode >= 200 && httpStatusCode < 300) { + return Status.OK; + } + // All other 4xx + if (httpStatusCode >= 400 && httpStatusCode < 500) { + return Status.FAILED_PRECONDITION; + } + // All other 5xx + if (httpStatusCode >= 500 && httpStatusCode < 600) { + return Status.INTERNAL; + } + // Everything else + return Status.UNKNOWN; +} +//# sourceMappingURL=status.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/status.js.map b/node_modules/google-gax/build/src/status.js.map new file mode 100644 index 0000000..362b22c --- /dev/null +++ b/node_modules/google-gax/build/src/status.js.map @@ -0,0 +1 @@ +{"version":3,"file":"status.js","sourceRo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AC,GAAG,CAAC,cAAc,CAAC,EAAE,CAAC;QAC7C,OAAO,4BAAoB,CAAC,GAAG,CAAC,cAAc,CAAE,CAAC;IACnD,CAAC;IACD,UAAU;IACV,IAAI,cAAc,IAAI,GAAG,IAAI,cAAc,GAAG,GAAG,EAAE,CAAC;QAClD,OAAO,MAAM,CAAC,EAAE,CAAC;IACnB,CAAC;IACD,gBAAgB;IAChB,IAAI,cAAc,IAAI,GAAG,IAAI,cAAc,GAAG,GAAG,EAAE,CAAC;QAClD,OAAO,MAAM,CAAC,mBAAmB,CAAC;IACpC,CAAC;IACD,gBAAgB;IAChB,IAAI,cAAc,IAAI,GAAG,IAAI,cAAc,GAAG,GAAG,EAAE,CAAC;QAClD,OAAO,MAAM,CAAC,QAAQ,CAAC;IACzB,CAAC;IACD,kBAAkB;IAClB,OAAO,MAAM,CAAC,OAAO,CAAC;AACxB,CAAC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/streamArrayParser.d.ts b/node_modules/google-gax/build/src/streamArrayParser.d.ts new file mode 100644 index 0000000..0c10701 --- /dev/null +++ b/node_modules/google-gax/build/src/streamArrayParser.d.ts @@ -0,0 +1,53 @@ +/** + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AbortController as NodeAbortController } from 'abort-controller'; +import { Transform } from 'stream'; +export declare class StreamArrayParser extends Transform { + private _done; + private _prevBlock; + private _isInString; + private _isSkipped; + private _level; + rpc: protobuf.Method; + cancelController: AbortController | NodeAbortController; + cancelSignal: AbortSignal; + cancelRequested: boolean; + /** + * StreamArrayParser processes array of valid JSON objects in random chunks + * through readable stream, and produces a stream of plain Javascript objects + * where it converted from the corresponding protobuf message instance. + * + * The default JSON parser decodes the input stream under the + * following rules: + * 1. The stream represents a valid JSON array (must start with a "[" and + * close with the corresponding "]"). Each element of this array is assumed to + * be either an array or an object, and will be decoded as a JS object and + * delivered. + * 2. All JSON elements in the buffer will be decoded and delivered in a + * stream. + * + * @private + * @constructor + * @param {protobuf.Method} rpc - the protobuf method produce array of JSON. + * @param {Object} options - the options pass to Transform Stream. See more + * details + * https://nodejs.org/api/stream.html#stream_new_stream_transform_options. + */ + constructor(rpc: protobuf.Method, options?: {}); + _transform(chunk: Buffer, _: string, callback: Function): void; + _flush(callback: Function): void; + cancel(): void; +} diff --git a/node_modules/google-gax/build/src/streamArrayParser.js b/node_modules/google-gax/build/src/streamArrayParser.js new file mode 100644 index 0000000..0f89674 --- /dev/null +++ b/node_modules/google-gax/build/src/streamArrayParser.js @@ -0,0 +1,150 @@ +"use strict"; +/** + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StreamArrayParser = void 0; +const abort_controller_1 = require("abort-controller"); +const stream_1 = require("stream"); +const fallbackRest_1 = require("./fallbackRest"); +const featureDetection_1 = require("./featureDetection"); +class StreamArrayParser extends stream_1.Transform { + /** + * StreamArrayParser processes array of valid JSON objects in random chunks + * through readable stream, and produces a stream of plain Javascript objects + * where it converted from the corresponding protobuf message instance. + * + * The default JSON parser decodes the input stream under the + * following rules: + * 1. The stream represents a valid JSON array (must start with a "[" and + * close with the corresponding "]"). Each element of this array is assumed to + * be either an array or an object, and will be decoded as a JS object and + * delivered. + * 2. All JSON elements in the buffer will be decoded and delivered in a + * stream. + * + * @private + * @constructor + * @param {protobuf.Method} rpc - the protobuf method produce array of JSON. + * @param {Object} options - the options pass to Transform Stream. See more + * details + * https://nodejs.org/api/stream.html#stream_new_stream_transform_options. + */ + constructor(rpc, options) { + super(Object.assign({}, options, { readableObjectMode: true })); + this._done = false; + this._prevBlock = Buffer.from(''); + this._isInString = false; + this._isSkipped = false; + this._level = 0; + this.rpc = rpc; + this.cancelController = (0, featureDetection_1.hasAbortController)() + ? new AbortController() + : new abort_controller_1.AbortController(); + this.cancelSignal = this.cancelController.signal; + this.cancelRequested = false; + } + _transform(chunk, _, callback) { + let objectStart = 0; + let curIndex = 0; + if (this._level === 0 && curIndex === 0) { + if (String.fromCharCode(chunk[0]) !== '[') { + this.emit('error', new Error(`Internal Error: API service stream data must start with a '[' and close with the corresponding ']', but it start with ${String.fromCharCode(chunk[0])}`)); + } + curIndex++; + this._level++; + } + while (curIndex < chunk.length) { + const curValue = String.fromCharCode(chunk[curIndex]); + if (!this._isSkipped) { + switch (curValue) { + case '{': + // Check if it's in string, we ignore the curly brace in string. + // Otherwise the object level++. + if (!this._isInString) { + this._level++; + } + if (!this._isInString && this._level === 2) { + objectStart = curIndex; + } + break; + case '"': + // Flip the string status + this._isInString = !this._isInString; + break; + case '}': + // check if it's in string + // if true, do nothing + // if false and level = 0, push data + if (!this._isInString) { + this._level--; + } + if (!this._isInString && this._level === 1) { + // find a object + const objBuff = Buffer.concat([ + this._prevBlock, + chunk.slice(objectStart, curIndex + 1), + ]); + try { + // HTTP response.ok is true. + const msgObj = (0, fallbackRest_1.decodeResponse)(this.rpc, true, objBuff); + this.push(msgObj); + } + catch (err) { + this.emit('error', err); + } + objectStart = curIndex + 1; + this._prevBlock = Buffer.from(''); + } + break; + case ']': + if (!this._isInString && this._level === 1) { + this._done = true; + this.push(null); + } + break; + case '\\': + // Escaping escape character. + this._isSkipped = true; + break; + default: + break; + } + } + else { + this._isSkipped = false; + } + curIndex++; + } + if (this._level > 1) { + this._prevBlock = Buffer.concat([ + this._prevBlock, + chunk.slice(objectStart, curIndex), + ]); + } + callback(); + } + _flush(callback) { + callback(); + } + cancel() { + this._done = true; + this.cancelRequested = true; + this.cancelController.abort(); + this.end(); + } +} +exports.StreamArrayParser = StreamArrayParser; +//# sourceMappingURL=streamArrayParser.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/streamArrayParser.js.map b/node_modules/google-gax/build/src/streamArrayParser.js.map new file mode 100644 index 0000000..0f302d6 --- /dev/null +++ b/node_modules/google-gax/build/src/streamArrayParser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"streamArrayParser.js","sourceRoot":"","sources":["../../src/streamArrayParser.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,uDAAwE;AACxE,mCAAiC;AAEjC,iDAA8C;AAC9C,yDAAsD;AAEtD,MAAa,iBAAkB,SAAQ,kBAAS;IAU9C;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,YAAY,GAAoB,EAAE,OAAY;QAC5C,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,OAAO,EAAE,EAAC,kBAAkB,EAAE,IAAI,EAAC,CAAC,CAAC,CAAC;QAC9D,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAClC,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC;QACzB,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC;QACxB,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;QAChB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,gBAAgB,GAAG,IAAA,qCAAkB,GAAE;YAC1C,CAAC,CAAC,IAAI,eAAe,EAAE;YACvB,CAAC,CAAC,IAAI,kCAAmB,EAAE,CAAC;QAC9B,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,gBAAgB,CAAC,MAAqB,CAAC;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,KAAK,CAAC;YAC1B,CAAC;YACD,QAAQ,EAAE,CAAC;QACb,CAAC;QACD,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACpB,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC;gBAC9B,IAAI,CAAC,UAAU;gBACf,KAAK,CAAC,KAAK,CAAC,WAAW,EAAE,QAAQ,CAAC;aACnC,CAAC,CAAC;QACL,CAAC;QACD,QAAQ,EAAE,CAAC;IACb,CAAC;IAED,MAAM,CAAC,QAAkB;QACvB,QAAQ,EAAE,CAAC;IACb,CAAC;IAED,MAAM;QACJ,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC;QAC5B,IAAI,CAAC,gBAAgB,CAAC,KAAK,EAAE,CAAC;QAC9B,IAAI,CAAC,GAAG,EAAE,CAAC;IACb,CAAC;CACF;AA/ID,8CA+IC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/streamingCalls/streamDescriptor.d.ts b/node_modules/google-gax/build/src/streamingCalls/streamDescriptor.d.ts new file mode 100644 index 0000000..3ff836f --- /dev/null +++ b/node_modules/google-gax/build/src/streamingCalls/streamDescriptor.d.ts @@ -0,0 +1,29 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { APICaller } from '../apiCaller'; +import { Descriptor } from '../descriptor'; +import { StreamType } from './streaming'; +/** + * A descriptor for streaming calls. + */ +export declare class StreamDescriptor implements Descriptor { + type: StreamType; + streaming: boolean; + rest?: boolean; + gaxStreamingRetries?: boolean; + constructor(streamType: StreamType, rest?: boolean, gaxStreamingRetries?: boolean); + getApiCaller(): APICaller; +} diff --git a/node_modules/google-gax/build/src/streamingCalls/streamDescriptor.js b/node_modules/google-gax/build/src/streamingCalls/streamDescriptor.js new file mode 100644 index 0000000..a8e775f --- /dev/null +++ b/node_modules/google-gax/build/src/streamingCalls/streamDescriptor.js @@ -0,0 +1,38 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StreamDescriptor = void 0; +const streamingApiCaller_1 = require("./streamingApiCaller"); +/** + * A descriptor for streaming calls. + */ +class StreamDescriptor { + constructor(streamType, rest, gaxStreamingRetries) { + this.type = streamType; + this.streaming = true; + this.rest = rest; + this.gaxStreamingRetries = gaxStreamingRetries; + } + getApiCaller() { + // Right now retrying does not work with gRPC-streaming, because retryable + // assumes an API call returns an event emitter while gRPC-streaming methods + // return Stream. + return new streamingApiCaller_1.StreamingApiCaller(this); + } +} +exports.StreamDescriptor = StreamDescriptor; +//# sourceMappingURL=streamDescriptor.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/streamingCalls/streamDescriptor.js.map b/node_modules/google-gax/build/src/streamingCalls/streamDescriptor.js.map new file mode 100644 index 0000000..a1c209f --- /dev/null +++ b/node_modules/google-gax/build/src/streamingCalls/streamDescriptor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"streamDescriptor.js","sourceRoot":"","sources":["../../../src/streamingCalls/streamDescriptor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAKH,6DAAwD;AAExD;;GAEG;AACH,MAAa,gBAAgB;IAM3B,YACE,UAAsB,EACtB,IAAc,EACd,mBAA6B;QAE7B,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,mBAAmB,GAAG,mBAAmB,CAAC;IACjD,CAAC;IAED,YAAY;QACV,0EAA0E;QAC1E,4EAA4E;QAC5E,iBAAiB;QACjB,OAAO,IAAI,uCAAkB,CAAC,IAAI,CAAC,CAAC;IACtC,CAAC;CACF;AAvBD,4CAuBC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/streamingCalls/streaming.d.ts b/node_modules/google-gax/build/src/streamingCalls/streaming.d.ts new file mode 100644 index 0000000..a1a955f --- /dev/null +++ b/node_modules/google-gax/build/src/streamingCalls/streaming.d.ts @@ -0,0 +1,125 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Duplex, DuplexOptions, Readable, Stream, Writable } from 'stream'; +import { APICallback, CancellableStream, GRPCCallResult, SimpleCallbackFunction } from '../apitypes'; +import { RetryOptions, RetryRequestOptions } from '../gax'; +import { GoogleError } from '../googleError'; +declare const duplexify: DuplexifyConstructor; +export interface DuplexifyOptions extends DuplexOptions { + autoDestroy?: boolean; + end?: boolean; +} +export interface Duplexify extends Duplex { + readonly destroyed: boolean; + setWritable(writable: Writable | false | null): void; + setReadable(readable: Readable | false | null): void; +} +export interface DuplexifyConstructor { + obj(writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify; + new (writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify; + (writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify; +} +/** + * The type of gRPC streaming. + * @enum {number} + */ +export declare enum StreamType { + /** Client sends a single request, server streams responses. */ + SERVER_STREAMING = 1, + /** Client streams requests, server returns a single response. */ + CLIENT_STREAMING = 2, + /** Both client and server stream objects. */ + BIDI_STREAMING = 3 +} +export declare class StreamProxy extends duplexify implements GRPCCallResult { + type: StreamType; + private _callback; + private _isCancelCalled; + stream?: CancellableStream; + private _responseHasSent; + rest?: boolean; + gaxServerStreamingRetries?: boolean; + apiCall?: SimpleCallbackFunction; + argument?: {}; + /** + * StreamProxy is a proxy to gRPC-streaming method. + * + * @private + * @constructor + * @param {StreamType} type - the type of gRPC stream. + * @param {ApiCallback} callback - the callback for further API call. + */ + constructor(type: StreamType, callback: APICallback, rest?: boolean, gaxServerStreamingRetries?: boolean); + private shouldRetryRequest; + cancel(): void; + /** + * Helper function to handle total timeout + max retry check for server streaming retries + * @param {number} deadline - the current retry deadline + * @param {number} maxRetries - maximum total number of retries + * @param {number} totalTimeoutMillis - total timeout in milliseconds used in timeout calculation + * @param {GoogleError} originalError - underlying error received by the stream + * @param {originalTimeout} originalTimeout - the original Timeout set in backoff settings + * @param {retries} retries - the number of retries the call has made so far + */ + throwIfMaxRetriesOrTotalTimeoutExceeded(deadline: number, maxRetries: number, totalTimeoutMillis: number, originalError: GoogleError, originalTimeout: number | undefined, retries: number): void; + /** + * Forwards events from an API request stream to the user's stream. + * @param {Stream} stream - The API request stream. + */ + eventForwardHelper(stream: Stream): void; + /** + * Helper function that emits a response on the stream after either a 'metadata' + * or a 'status' event - this helps streams to behave more like http consumers expect + * @param {Stream} stream - The API request stream. + */ + statusMetadataHelper(stream: Stream): void; + /** + * Forward events from an API request stream to the user's stream. + * @param {Stream} stream - The API request stream. + * @param {RetryOptions} retry - Configures the exceptions upon which the + * function should retry, and the parameters to the exponential backoff retry + * algorithm. + */ + forwardEvents(stream: Stream): void; + /** + * Default mechanism for determining whether a streaming call should retry + * If a user passes in a "shouldRetryFn", this will not be used + * @param {GoogleError} errpr - The error we need to determine is retryable or not + * @param {RetryOptions} retry - Configures the exceptions upon which the + * function should retry, and the parameters to the exponential backoff retry + * algorithm. + */ + defaultShouldRetry(error: GoogleError, retry: RetryOptions): boolean; + /** + * Specifies the target stream. + * @param {ApiCall} apiCall - the API function to be called. + * @param {Object} argument - the argument to be passed to the apiCall. + * @param {RetryOptions} retry - Configures the exceptions upon which the + * function should retry, and the parameters to the exponential backoff retry + * algorithm. + */ + setStream(apiCall: SimpleCallbackFunction, argument: {}, retryRequestOptions: RetryRequestOptions | undefined, retry: RetryOptions): void; + /** + * Creates a new retry request stream - + *inner arrow function "newMakeRequest" handles retrying and resumption + * @param {streamingRetryRequestOptions} opts + * {request} - the request to be made if the stream errors + * {retry} - the retry options associated with the call + * @returns {CancellableStream} - the stream that handles retry logic + */ + private newStreamingRetryRequest; +} +export {}; diff --git a/node_modules/google-gax/build/src/streamingCalls/streaming.js b/node_modules/google-gax/build/src/streamingCalls/streaming.js new file mode 100644 index 0000000..02936f8 --- /dev/null +++ b/node_modules/google-gax/build/src/streamingCalls/streaming.js @@ -0,0 +1,453 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StreamProxy = exports.StreamType = void 0; +const gax_1 = require("../gax"); +const googleError_1 = require("../googleError"); +const status_1 = require("../status"); +const stream_1 = require("stream"); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const duplexify = require('duplexify'); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const retryRequest = require('retry-request'); +/** + * The type of gRPC streaming. + * @enum {number} + */ +var StreamType; +(function (StreamType) { + /** Client sends a single request, server streams responses. */ + StreamType[StreamType["SERVER_STREAMING"] = 1] = "SERVER_STREAMING"; + /** Client streams requests, server returns a single response. */ + StreamType[StreamType["CLIENT_STREAMING"] = 2] = "CLIENT_STREAMING"; + /** Both client and server stream objects. */ + StreamType[StreamType["BIDI_STREAMING"] = 3] = "BIDI_STREAMING"; +})(StreamType || (exports.StreamType = StreamType = {})); +// In retry-request, you could pass parameters to request using the requestOpts parameter +// when we called retry-request from gax, we always passed null +// passing null here removes an unnecessary parameter from this implementation +const requestOps = null; +class StreamProxy extends duplexify { + /** + * StreamProxy is a proxy to gRPC-streaming method. + * + * @private + * @constructor + * @param {StreamType} type - the type of gRPC stream. + * @param {ApiCallback} callback - the callback for further API call. + */ + constructor(type, callback, rest, gaxServerStreamingRetries) { + super(undefined, undefined, { + objectMode: true, + readable: type !== StreamType.CLIENT_STREAMING, + writable: type !== StreamType.SERVER_STREAMING, + }); + this.type = type; + this._callback = callback; + this._isCancelCalled = false; + this._responseHasSent = false; + this.rest = rest; + this.gaxServerStreamingRetries = gaxServerStreamingRetries; + } + shouldRetryRequest(error, retry) { + const e = googleError_1.GoogleError.parseGRPCStatusDetails(error); + let shouldRetry = this.defaultShouldRetry(e, retry); + if (retry.shouldRetryFn) { + shouldRetry = retry.shouldRetryFn(e); + } + return shouldRetry; + } + cancel() { + if (this.stream) { + this.stream.cancel(); + } + else { + this._isCancelCalled = true; + } + } + /** + * Helper function to handle total timeout + max retry check for server streaming retries + * @param {number} deadline - the current retry deadline + * @param {number} maxRetries - maximum total number of retries + * @param {number} totalTimeoutMillis - total timeout in milliseconds used in timeout calculation + * @param {GoogleError} originalError - underlying error received by the stream + * @param {originalTimeout} originalTimeout - the original Timeout set in backoff settings + * @param {retries} retries - the number of retries the call has made so far + */ + throwIfMaxRetriesOrTotalTimeoutExceeded(deadline, maxRetries, totalTimeoutMillis, originalError, originalTimeout, retries) { + const now = new Date(); + const nowTime = now.getTime(); + if (originalTimeout && + (totalTimeoutMillis === 0 || + totalTimeoutMillis < 0 || + (deadline && nowTime >= deadline))) { + const error = new googleError_1.GoogleError(`Total timeout of API exceeded ${originalTimeout} milliseconds ${originalError ? `retrying error ${originalError} ` : ''} before any response was received.`); + error.code = status_1.Status.DEADLINE_EXCEEDED; + throw error; + } + if (maxRetries === 0) { + const error = originalError; + error.note = 'Max retries is set to zero.'; + throw error; + } + if (retries && retries >= maxRetries) { + const error = new googleError_1.GoogleError('Exceeded maximum number of retries ' + + (originalError ? `retrying error ${originalError} ` : '') + + 'before any response was received'); + error.code = status_1.Status.DEADLINE_EXCEEDED; + throw error; + } + } + /** + * Forwards events from an API request stream to the user's stream. + * @param {Stream} stream - The API request stream. + */ + eventForwardHelper(stream) { + const eventsToForward = ['metadata', 'response', 'status']; + eventsToForward.forEach(event => { + stream.on(event, this.emit.bind(this, event)); + }); + } + /** + * Helper function that emits a response on the stream after either a 'metadata' + * or a 'status' event - this helps streams to behave more like http consumers expect + * @param {Stream} stream - The API request stream. + */ + statusMetadataHelper(stream) { + // gRPC is guaranteed emit the 'status' event but not 'metadata', and 'status' is the last event to emit. + // Emit the 'response' event if stream has no 'metadata' event. + // This avoids the stream swallowing the other events, such as 'end'. + stream.on('status', () => { + if (!this._responseHasSent) { + stream.emit('response', { + code: 200, + details: '', + message: 'OK', + }); + } + }); + // We also want to supply the status data as 'response' event to support + // the behavior of google-cloud-node expects. + // see: + // https://github.com/GoogleCloudPlatform/google-cloud-node/pull/1775#issuecomment-259141029 + // https://github.com/GoogleCloudPlatform/google-cloud-node/blob/116436fa789d8b0f7fc5100b19b424e3ec63e6bf/packages/common/src/grpc-service.js#L355 + stream.on('metadata', metadata => { + // Create a response object with succeeds. + // TODO: unify this logic with the decoration of gRPC response when it's + // added. see: https://github.com/googleapis/gax-nodejs/issues/65 + stream.emit('response', { + code: 200, + details: '', + message: 'OK', + metadata, + }); + this._responseHasSent = true; + }); + } + /** + * Forward events from an API request stream to the user's stream. + * @param {Stream} stream - The API request stream. + * @param {RetryOptions} retry - Configures the exceptions upon which the + * function should retry, and the parameters to the exponential backoff retry + * algorithm. + */ + forwardEvents(stream) { + this.eventForwardHelper(stream); + this.statusMetadataHelper(stream); + stream.on('error', error => { + googleError_1.GoogleError.parseGRPCStatusDetails(error); + }); + } + /** + * Default mechanism for determining whether a streaming call should retry + * If a user passes in a "shouldRetryFn", this will not be used + * @param {GoogleError} errpr - The error we need to determine is retryable or not + * @param {RetryOptions} retry - Configures the exceptions upon which the + * function should retry, and the parameters to the exponential backoff retry + * algorithm. + */ + defaultShouldRetry(error, retry) { + if ((retry.retryCodes.length > 0 && + retry.retryCodes.indexOf(error.code) < 0) || + retry.retryCodes.length === 0) { + return false; + } + return true; + } + /** + * Specifies the target stream. + * @param {ApiCall} apiCall - the API function to be called. + * @param {Object} argument - the argument to be passed to the apiCall. + * @param {RetryOptions} retry - Configures the exceptions upon which the + * function should retry, and the parameters to the exponential backoff retry + * algorithm. + */ + setStream(apiCall, argument, retryRequestOptions = {}, retry) { + this.apiCall = apiCall; + this.argument = argument; + if (this.type === StreamType.SERVER_STREAMING) { + if (this.rest) { + const stream = apiCall(argument, this._callback); + this.stream = stream; + this.setReadable(stream); + } + else if (this.gaxServerStreamingRetries) { + const request = () => { + if (this._isCancelCalled) { + if (this.stream) { + this.stream.cancel(); + } + return; + } + const stream = apiCall(argument, this._callback); + return stream; + }; + const retryStream = this.newStreamingRetryRequest({ request, retry }); + this.stream = retryStream; + this.eventForwardHelper(retryStream); + this.setReadable(retryStream); + } + else { + const retryStream = retryRequest(null, { + objectMode: true, + request: () => { + if (this._isCancelCalled) { + if (this.stream) { + this.stream.cancel(); + } + return; + } + const stream = apiCall(argument, this._callback); + this.stream = stream; + this.forwardEvents(stream); + return stream; + }, + retries: retryRequestOptions.retries, + currentRetryAttempt: retryRequestOptions.currentRetryAttempt, + noResponseRetries: retryRequestOptions.noResponseRetries, + shouldRetryFn: retryRequestOptions.shouldRetryFn, + }); + this.setReadable(retryStream); + } + return; + } + const stream = apiCall(argument, this._callback); + this.stream = stream; + this.forwardEvents(stream); + if (this.type === StreamType.CLIENT_STREAMING) { + this.setWritable(stream); + } + if (this.type === StreamType.BIDI_STREAMING) { + this.setReadable(stream); + this.setWritable(stream); + } + if (this._isCancelCalled && this.stream) { + this.stream.cancel(); + } + } + /** + * Creates a new retry request stream - + *inner arrow function "newMakeRequest" handles retrying and resumption + * @param {streamingRetryRequestOptions} opts + * {request} - the request to be made if the stream errors + * {retry} - the retry options associated with the call + * @returns {CancellableStream} - the stream that handles retry logic + */ + newStreamingRetryRequest(opts) { + var _a, _b, _c, _d; + // at this point, it would be unexpected if retry were undefined + // but if it is, provide a logical default so we don't run into trouble + const retry = (_a = opts.retry) !== null && _a !== void 0 ? _a : { + retryCodes: [], + backoffSettings: (0, gax_1.createDefaultBackoffSettings)(), + }; + let retries = 0; + const retryStream = new stream_1.PassThrough({ + objectMode: true, + }); + const totalTimeout = (_b = retry.backoffSettings.totalTimeoutMillis) !== null && _b !== void 0 ? _b : undefined; + const maxRetries = (_c = retry.backoffSettings.maxRetries) !== null && _c !== void 0 ? _c : undefined; + let timeout = (_d = retry.backoffSettings.initialRpcTimeoutMillis) !== null && _d !== void 0 ? _d : undefined; + let now = new Date(); + let deadline = 0; + if (totalTimeout) { + deadline = now.getTime() + totalTimeout; + } + const transientErrorHelper = (error, requestStream) => { + const e = googleError_1.GoogleError.parseGRPCStatusDetails(error); + e.note = + 'Exception occurred in retry method that was ' + + 'not classified as transient'; + // clean up the request stream and retryStreams, silently destroy it on the request stream + // but do raise it on destructin of the retryStream so the consumer can see it + requestStream.destroy(); + retryStream.destroy(e); + return retryStream; + }; + const newMakeRequest = (newopts) => { + let dataEnd = false; + let statusReceived = false; + let enteredError = false; + // make the request + const requestStream = newopts.request(requestOps); + retryStream.cancel = requestStream.cancel; // make sure the retryStream is also cancellable by the user + const eventsToForward = ['metadata', 'response', 'status']; + eventsToForward.forEach(event => { + requestStream.on(event, retryStream.emit.bind(retryStream, event)); + }); + this.statusMetadataHelper(requestStream); + // TODO - b/353262542 address buffer stuff + requestStream.on('data', (data) => { + retries = 0; + this.emit.bind(this, 'data')(data); + }); + /* in retry-request, which previously handled retries, + * "end" could be emitted on a request stream before other gRPC events. + * To ensure it doesn't reach the consumer stream prematurely, retry-request piped + * two streams together (delayStream and retryStream) + * to ensure that "end" only emitted after a "response" event + * + * We are consciously NOT using pipeline or .pipe as part of similar logic here + * because we want more control over what happens during event handoff and we want to + * avoid the undesired behavior that can happen with error events + * if consumers in client libraries are also using pipes + * + * Since "status" is guaranteed to be the last event emitted by gRPC. + * If we have seen an "end" event, the dataEnd boolean will be true and we can safely + * end the stream. + * + * The "statusReceived" boolean covers the opposite case - that we receive the "status" event before + * a successful stream end event - this signals the .on('end') event handler that it's okay to end the stream + * + * + */ + requestStream.on('status', () => { + statusReceived = true; + if (dataEnd) { + retryStream.end(); + } + return retryStream; + }); + requestStream.on('end', () => { + if (!enteredError) { + dataEnd = true; + // in this case, we've already received "status" + // which is the last event from gRPC, so it's cool to end the stream + if (statusReceived) { + retryStream.end(); + } + } + return retryStream; + // there is no else case because if enteredError + // is true, we will handle stream destruction as part of + // either retrying (where we don't want to end the stream) + // or as part of error handling, which will take care of stream destruction + }); + requestStream.on('error', (error) => { + enteredError = true; + // type check for undefined instead of for truthiness in case maxRetries or timeout is equal to zero + if (typeof maxRetries !== undefined || + typeof totalTimeout !== undefined) { + if (this.shouldRetryRequest(error, retry)) { + if (maxRetries && totalTimeout) { + const newError = new googleError_1.GoogleError('Cannot set both totalTimeoutMillis and maxRetries ' + + 'in backoffSettings.'); + newError.code = status_1.Status.INVALID_ARGUMENT; + // clean up the request stream and retryStreams, silently destroy it on the request stream + // but do raise it on destructin of the retryStream so the consumer can see it + requestStream.destroy(); + retryStream.destroy(newError); + return retryStream; + } + else { + // check for exceeding timeout or max retries + try { + this.throwIfMaxRetriesOrTotalTimeoutExceeded(deadline, maxRetries, timeout, error, totalTimeout, retries); + } + catch (error) { + const e = googleError_1.GoogleError.parseGRPCStatusDetails(error); + // clean up the request stream and retryStreams, silently destroy it on the request stream + // but do raise it on destruction of the retryStream so the consumer can see it + requestStream.destroy(); + retryStream.destroy(e); + return retryStream; + } + const delayMult = retry.backoffSettings.retryDelayMultiplier; + const maxDelay = retry.backoffSettings.maxRetryDelayMillis; + const timeoutMult = retry.backoffSettings.rpcTimeoutMultiplier; + const maxTimeout = retry.backoffSettings.maxRpcTimeoutMillis; + let delay = retry.backoffSettings.initialRetryDelayMillis; + // calculate new deadlines + const toSleep = Math.random() * delay; + const calculateTimeoutAndResumptionFunction = () => { + setTimeout(() => { + // only do timeout calculations if not using maxRetries + if (timeout) { + now = new Date(); + delay = Math.min(delay * delayMult, maxDelay); + const timeoutCal = timeout && timeoutMult ? timeout * timeoutMult : 0; + const rpcTimeout = maxTimeout ? maxTimeout : 0; + const newDeadline = deadline ? deadline - now.getTime() : 0; + timeout = Math.min(timeoutCal, rpcTimeout, newDeadline); + } + retries++; + let retryArgument = this.argument; + // if resumption logic is passed, use it to determined the + // new argument for the new request made to the server + // otherwise, the original argument will be passed + if (retry.getResumptionRequestFn !== undefined) { + retryArgument = retry.getResumptionRequestFn(retryArgument); + } + const newRequest = () => { + if (this._isCancelCalled) { + if (this.stream) { + this.stream.cancel(); + } + return; + } + const newStream = this.apiCall(retryArgument, this._callback); + return newStream; + }; + opts.request = newRequest; + // make a request with the updated parameters + // based on the resumption strategy + return newMakeRequest(opts); + }, toSleep); + }; + return calculateTimeoutAndResumptionFunction(); + } + } + else { + // non retryable error + return transientErrorHelper(error, requestStream); + } + } + else { + // neither timeout nor maxRetries are defined, surface the error to the caller + return transientErrorHelper(error, requestStream); + } + }); + // return the stream if we didn't return it as + // part of an error state + return retryStream; + }; + // this is the first make request call with the options the user passed in + return newMakeRequest(opts); + } +} +exports.StreamProxy = StreamProxy; +//# sourceMappingURL=streaming.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/streamingCalls/streaming.js.map b/node_modules/google-gax/build/src/streamingCalls/streaming.js.map new file mode 100644 index 0000000..875a65b --- /dev/null +++ b/node_modules/google-gax/build/src/streamingCalls/streaming.js.map @@ -0,0 +1 @@ +{"version":3,"file":"streaming.js","sourceRoot":"","sources":["../../../src/streamingCalls/streaming.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAaH,gCAIgB;AAChB,gDAA2C;AAC3C,sCAAiC;AACjC,mCAAmC;AAEnC,8DAA8D;AAC9D,MAAM,SAAS,GAAyB,OAAO,CAAC,WAAW,CAAC,CAAC;AAC7D,8DAA8D;AAC9D,MAAM,YAAY,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;AAgC9C;;;GAGG;AACH,IAAY,UASX;AATD,WAAY,UAAU;IACpB,+DAA+D;IAC/D,mEAAoB,CAAA;IAEpB,iEAAiE;IACjE,mEAAoB,CAAA;IAEpB,6CAA6C;IAC7C,+DAAkB,CAAA;AACpB,CAAC,EATW,UAAU,0BAAV,UAAU,QASrB;AAED,yFAAyF;AACzF,+DAA+D;AAC/D,8EAA8E;AAC9E,MAAM,UAAU,GAAG,IAAI,CAAC;AAQxB,MAAa,WAAY,SAAQ,SAAS;IAUxC;;;;;;;OAOG;IACH,YACE,IAAgB,EAChB,QAAqB,EACrB,IAAc,EACd,yBAAmC;QAEnC,KAAK,CAAC,SAAS,EAAE,SAAS,EAAE;YAC1B,UAAU,EAAE,IAAI;YAChB,QAAQ,EAAE,IAAI,KAAK,UAAU,CAAC,gBAAgB;YAC9C,QAAQ,EAAE,IAAI,KAAK,UAAU,CAAC,gBAAgB;SAC9B,CAAC,CAAC;QACpB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC1B,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;QAC7B,IAAI,CAAC,gBAAgB,GAAG,KA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AO;wCACT,CAAC;wCACD,MAAM,SAAS,GAAG,IAAI,CAAC,OAAQ,CAC7B,aAAa,EACb,IAAI,CAAC,SAAS,CACM,CAAC;wCACvB,OAAO,SAAS,CAAC;oCACnB,CAAC,CAAC;oCACF,IAAI,CAAC,OAAO,GAAG,UAAU,CAAC;oCAE1B,6CAA6C;oCAC7C,mCAAmC;oCACnC,OAAO,cAAc,CAAC,IAAI,CAAC,CAAC;gCAC9B,CAAC,EAAE,OAAO,CAAC,CAAC;4BACd,CAAC,CAAC;4BACF,OAAO,qCAAqC,EAAE,CAAC;wBACjD,CAAC;oBACH,CAAC;yBAAM,CAAC;wBACN,sBAAsB;wBACtB,OAAO,oBAAoB,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC;oBACpD,CAAC;gBACH,CAAC;qBAAM,CAAC;oBACN,8EAA8E;oBAC9E,OAAO,oBAAoB,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC;gBACpD,CAAC;YACH,CAAC,CAAC,CAAC;YACH,8CAA8C;YAC9C,yBAAyB;YACzB,OAAO,WAAW,CAAC;QACrB,CAAC,CAAC;QACF,0EAA0E;QAC1E,OAAO,cAAc,CAAC,IAAI,CAAC,CAAC;IAC9B,CAAC;CACF;AA5eD,kCA4eC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/streamingCalls/streamingApiCaller.d.ts b/node_modules/google-gax/build/src/streamingCalls/streamingApiCaller.d.ts new file mode 100644 index 0000000..d4a4c63 --- /dev/null +++ b/node_modules/google-gax/build/src/streamingCalls/streamingApiCaller.d.ts @@ -0,0 +1,35 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { APICaller } from '../apiCaller'; +import { APICallback, CancellableStream, GRPCCall, SimpleCallbackFunction } from '../apitypes'; +import { StreamDescriptor } from './streamDescriptor'; +import { StreamProxy } from './streaming'; +import { CallSettings } from '../gax'; +export declare class StreamingApiCaller implements APICaller { + descriptor: StreamDescriptor; + /** + * An API caller for methods of gRPC streaming. + * @private + * @constructor + * @param {StreamDescriptor} descriptor - the descriptor of the method structure. + */ + constructor(descriptor: StreamDescriptor); + init(callback: APICallback): StreamProxy; + wrap(func: GRPCCall): GRPCCall; + call(apiCall: SimpleCallbackFunction, argument: {}, settings: CallSettings, stream: StreamProxy): void; + fail(stream: CancellableStream, err: Error): void; + result(stream: CancellableStream): CancellableStream; +} diff --git a/node_modules/google-gax/build/src/streamingCalls/streamingApiCaller.js b/node_modules/google-gax/build/src/streamingCalls/streamingApiCaller.js new file mode 100644 index 0000000..81c0d8d --- /dev/null +++ b/node_modules/google-gax/build/src/streamingCalls/streamingApiCaller.js @@ -0,0 +1,64 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StreamingApiCaller = void 0; +const warnings_1 = require("../warnings"); +const streaming_1 = require("./streaming"); +class StreamingApiCaller { + /** + * An API caller for methods of gRPC streaming. + * @private + * @constructor + * @param {StreamDescriptor} descriptor - the descriptor of the method structure. + */ + constructor(descriptor) { + this.descriptor = descriptor; + } + init(callback) { + return new streaming_1.StreamProxy(this.descriptor.type, callback, this.descriptor.rest, this.descriptor.gaxStreamingRetries); + } + wrap(func) { + switch (this.descriptor.type) { + case streaming_1.StreamType.SERVER_STREAMING: + return (argument, metadata, options) => { + return func(argument, metadata, options); + }; + case streaming_1.StreamType.CLIENT_STREAMING: + return (argument, metadata, options, callback) => { + return func(metadata, options, callback); + }; + case streaming_1.StreamType.BIDI_STREAMING: + return (argument, metadata, options) => { + return func(metadata, options); + }; + default: + (0, warnings_1.warn)('streaming_wrap_unknown_stream_type', `Unknown stream type: ${this.descriptor.type}`); + } + return func; + } + call(apiCall, argument, settings, stream) { + stream.setStream(apiCall, argument, settings.retryRequestOptions, settings.retry); + } + fail(stream, err) { + stream.emit('error', err); + } + result(stream) { + return stream; + } +} +exports.StreamingApiCaller = StreamingApiCaller; +//# sourceMappingURL=streamingApiCaller.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/streamingCalls/streamingApiCaller.js.map b/node_modules/google-gax/build/src/streamingCalls/streamingApiCaller.js.map new file mode 100644 index 0000000..f0e8f0e --- /dev/null +++ b/node_modules/google-gax/build/src/streamingCalls/streamingApiCaller.js.map @@ -0,0 +1 @@ +{"version":3,"file":"streamingApiCaller.js","sourceRoot":"","sources":["../../../src/streamingCalls/streamingApiCaller.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAYH,0CAAiC;AAGjC,2CAAoD;AAGpD,MAAa,kBAAkB;IAG7B;;;;;OAKG;IACH,YAAY,UAA4B;QACtC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IAED,IAAI,CAAC,QAAqB;QACxB,OAAO,IAAI,uBAAW,CACpB,IAAI,CAAC,UAAU,CAAC,IAAI,EACpB,QAAQ,EACR,IAAI,CAAC,UAAU,CAAC,IAAI,EACpB,IAAI,CAAC,UAAU,CAAC,mBAAmB,CACpC,CAAC;IACJ,CAAC;IAED,IAAI,CAAC,IAAc;QACjB,QAAQ,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,CAAC;YAC7B,KAAK,sBAAU,CAAC,gBAAgB;gBAC9B,OAAO,CAAC,QAAY,EAAE,QAAY,EAAE,OAAW,EAAE,EAAE;oBACjD,OAAQ,IAA4B,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;gBACpE,CAAC,CAAC;YACJ,KAAK,sBAAU,CAAC,gBAAgB;gBAC9B,OAAO,CACL,QAAY,EACZ,QAAY,EACZ,OAAW,EACX,QAAsB,EACtB,EAAE;oBACF,OAAQ,IAA4B,CAAC,QAAQ,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;gBACpE,CAAC,CAAC;YACJ,KAAK,sBAAU,CAAC,cAAc;gBAC5B,OAAO,CAAC,QAAY,EAAE,QAAY,EAAE,OAAW,EAAE,EAAE;oBACjD,OAAQ,IAA0B,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;gBACxD,CAAC,CAAC;YACJ;gBACE,IAAA,eAAI,EACF,oCAAoC,EACpC,wBAAwB,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,CAC/C,CAAC;QACN,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,CACF,OAA+B,EAC/B,QAAY,EACZ,QAAsB,EACtB,MAAmB;QAEnB,MAAM,CAAC,SAAS,CACd,OAAO,EACP,QAAQ,EACR,QAAQ,CAAC,mBAAmB,EAC5B,QAAQ,CAAC,KAAM,CAChB,CAAC;IACJ,CAAC;IAED,IAAI,CAAC,MAAyB,EAAE,GAAU;QACxC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;IAC5B,CAAC;IAED,MAAM,CAAC,MAAyB;QAC9B,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAvED,gDAuEC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/transcoding.d.ts b/node_modules/google-gax/build/src/transcoding.d.ts new file mode 100644 index 0000000..04b6823 --- /dev/null +++ b/node_modules/google-gax/build/src/transcoding.d.ts @@ -0,0 +1,48 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { JSONObject, JSONValue } from 'proto3-json-serializer'; +import { Field } from 'protobufjs'; +import { google } from '../protos/http'; +export interface TranscodedRequest { + httpMethod: 'get' | 'post' | 'put' | 'patch' | 'delete'; + url: string; + queryString: string; + data: string | {}; +} +declare const httpOptionName = "(google.api.http)"; +type allowedOptions = '(google.api.method_signature)'; +export type ParsedOptionsType = Array<{ + [httpOptionName]?: google.api.IHttpRule; +} & { + [option in allowedOptions]?: {} | string | number; +}>; +export declare function getField(request: JSONObject, field: string, allowObjects?: boolean): JSONValue | undefined; +export declare function deepCopyWithoutMatchedFields(request: JSONObject, fieldsToSkip: Set, fullNamePrefix?: string): JSONObject; +export declare function deleteField(request: JSONObject, field: string): void; +export declare function buildQueryStringComponents(request: JSONObject, prefix?: string): string[]; +export declare function encodeWithSlashes(str: string): string; +export declare function encodeWithoutSlashes(str: string): string; +export declare function applyPattern(pattern: string, fieldValue: string): string | undefined; +interface MatchResult { + matchedFields: string[]; + url: string; +} +export declare function match(request: JSONObject, pattern: string): MatchResult | undefined; +export declare function flattenObject(request: JSONObject): JSONObject; +export declare function isProto3OptionalField(field: Field): any; +export declare function transcode(request: JSONObject, parsedOptions: ParsedOptionsType): TranscodedRequest | undefined; +export declare function overrideHttpRules(httpRules: Array, protoJson: protobuf.Root): void; +export {}; diff --git a/node_modules/google-gax/build/src/transcoding.js b/node_modules/google-gax/build/src/transcoding.js new file mode 100644 index 0000000..68bcd22 --- /dev/null +++ b/node_modules/google-gax/build/src/transcoding.js @@ -0,0 +1,281 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getField = getField; +exports.deepCopyWithoutMatchedFields = deepCopyWithoutMatchedFields; +exports.deleteField = deleteField; +exports.buildQueryStringComponents = buildQueryStringComponents; +exports.encodeWithSlashes = encodeWithSlashes; +exports.encodeWithoutSlashes = encodeWithoutSlashes; +exports.applyPattern = applyPattern; +exports.match = match; +exports.flattenObject = flattenObject; +exports.isProto3OptionalField = isProto3OptionalField; +exports.transcode = transcode; +exports.overrideHttpRules = overrideHttpRules; +const util_1 = require("./util"); +const httpOptionName = '(google.api.http)'; +const proto3OptionalName = 'proto3_optional'; +// List of methods as defined in google/api/http.proto (see HttpRule) +const supportedHttpMethods = ['get', 'post', 'put', 'patch', 'delete']; +function getField(request, field, allowObjects = false // in most cases, we need leaf fields +) { + const parts = field.split('.'); + let value = request; + for (const part of parts) { + if (typeof value !== 'object') { + return undefined; + } + value = value[part]; + } + if (!allowObjects && + typeof value === 'object' && + !Array.isArray(value) && + value !== null) { + return undefined; + } + return value; +} +function deepCopyWithoutMatchedFields(request, fieldsToSkip, fullNamePrefix = '') { + if (typeof request !== 'object' || request === null) { + return request; + } + const copy = Object.assign({}, request); + for (const key in copy) { + if (fieldsToSkip.has(`${fullNamePrefix}${key}`)) { + delete copy[key]; + continue; + } + const nextFullNamePrefix = `${fullNamePrefix}${key}.`; + if (Array.isArray(copy[key])) { + // a field of an array cannot be addressed as "request.field", so we omit the skipping logic for array descendants + copy[key] = copy[key].map(value => deepCopyWithoutMatchedFields(value, new Set())); + } + else if (typeof copy[key] === 'object' && copy[key] !== null) { + copy[key] = deepCopyWithoutMatchedFields(copy[key], fieldsToSkip, nextFullNamePrefix); + } + } + return copy; +} +function deleteField(request, field) { + const parts = field.split('.'); + while (parts.length > 1) { + if (typeof request !== 'object') { + return; + } + const part = parts.shift(); + request = request[part]; + } + const part = parts.shift(); + if (typeof request !== 'object') { + return; + } + delete request[part]; +} +function buildQueryStringComponents(request, prefix = '') { + const resultList = []; + for (const key in request) { + if (Array.isArray(request[key])) { + for (const value of request[key]) { + resultList.push(`${prefix}${encodeWithoutSlashes(key)}=${encodeWithoutSlashes(value.toString())}`); + } + } + else if (typeof request[key] === 'object' && request[key] !== null) { + resultList.push(...buildQueryStringComponents(request[key], `${key}.`)); + } + else { + resultList.push(`${prefix}${encodeWithoutSlashes(key)}=${encodeWithoutSlashes(request[key] === null ? 'null' : request[key].toString())}`); + } + } + return resultList; +} +function encodeWithSlashes(str) { + return str + .split('') + .map(c => (c.match(/[-_.~0-9a-zA-Z]/) ? c : encodeURIComponent(c))) + .join(''); +} +function encodeWithoutSlashes(str) { + return str + .split('') + .map(c => (c.match(/[-_.~0-9a-zA-Z/]/) ? c : encodeURIComponent(c))) + .join(''); +} +function escapeRegExp(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} +function applyPattern(pattern, fieldValue) { + if (!pattern || pattern === '*') { + return encodeWithSlashes(fieldValue); + } + if (!pattern.includes('*') && pattern !== fieldValue) { + return undefined; + } + // since we're converting the pattern to a regex, make necessary precautions: + const regex = new RegExp('^' + + escapeRegExp(pattern) + .replace(/\\\*\\\*/g, '(.+)') + .replace(/\\\*/g, '([^/]+)') + + '$'); + if (!fieldValue.match(regex)) { + return undefined; + } + return encodeWithoutSlashes(fieldValue); +} +function fieldToCamelCase(field) { + const parts = field.split('.'); + return parts.map(part => (0, util_1.toCamelCase)(part)).join('.'); +} +function match(request, pattern) { + let url = pattern; + const matchedFields = []; + for (;;) { + const match = url.match(/^(.*)\{([^}=]+)(?:=([^}]*))?\}(.*)/); + if (!match) { + break; + } + const [, before, field, pattern, after] = match; + const camelCasedField = fieldToCamelCase(field); + matchedFields.push(fieldToCamelCase(camelCasedField)); + const fieldValue = getField(request, camelCasedField); + if (fieldValue === undefined) { + return undefined; + } + const appliedPattern = applyPattern(pattern, fieldValue === null ? 'null' : fieldValue.toString()); + if (appliedPattern === undefined) { + return undefined; + } + url = before + appliedPattern + after; + } + return { matchedFields, url }; +} +function flattenObject(request) { + const result = {}; + for (const key in request) { + if (request[key] === undefined) { + continue; + } + if (Array.isArray(request[key])) { + // According to the http.proto comments, a repeated field may only + // contain primitive types, so no extra recursion here. + result[key] = request[key]; + continue; + } + if (typeof request[key] === 'object' && request[key] !== null) { + const nested = flattenObject(request[key]); + for (const nestedKey in nested) { + result[`${key}.${nestedKey}`] = nested[nestedKey]; + } + continue; + } + result[key] = request[key]; + } + return result; +} +function isProto3OptionalField(field) { + return field && field.options && field.options[proto3OptionalName]; +} +function transcode(request, parsedOptions) { + const httpRules = []; + for (const option of parsedOptions) { + if (!(httpOptionName in option)) { + continue; + } + const httpRule = option[httpOptionName]; + httpRules.push(httpRule); + if (httpRule === null || httpRule === void 0 ? void 0 : httpRule.additional_bindings) { + const additionalBindings = Array.isArray(httpRule.additional_bindings) + ? httpRule.additional_bindings + : [httpRule.additional_bindings]; + httpRules.push(...additionalBindings); + } + } + for (const httpRule of httpRules) { + for (const httpMethod of supportedHttpMethods) { + if (!(httpMethod in httpRule)) { + continue; + } + const pathTemplate = httpRule[httpMethod]; + const matchResult = match(request, pathTemplate); + if (matchResult === undefined) { + continue; + } + const { url, matchedFields } = matchResult; + let data = deepCopyWithoutMatchedFields(request, new Set(matchedFields)); + if (httpRule.body === '*') { + return { httpMethod, url, queryString: '', data }; + } + // one field possibly goes to request data, others go to query string + const queryStringObject = data; + if (httpRule.body) { + data = getField(queryStringObject, fieldToCamelCase(httpRule.body), + /*allowObjects:*/ true); + deleteField(queryStringObject, fieldToCamelCase(httpRule.body)); + } + else { + data = ''; + } + const queryStringComponents = buildQueryStringComponents(queryStringObject); + const queryString = queryStringComponents.join('&'); + if (!data || + (typeof data === 'object' && Object.keys(data).length === 0)) { + data = ''; + } + return { httpMethod, url, queryString, data }; + } + } + return undefined; +} +// Override the protobuf json's the http rules. +function overrideHttpRules(httpRules, protoJson) { + for (const rule of httpRules) { + if (!rule.selector) { + continue; + } + const rpc = protoJson.lookup(rule.selector); + // Not support override on non-exist RPC or a RPC without an annotation. + // We could reconsider if we have the use case later. + if (!rpc || !rpc.parsedOptions) { + continue; + } + for (const item of rpc.parsedOptions) { + if (!(httpOptionName in item)) { + continue; + } + const httpOptions = item[httpOptionName]; + for (const httpMethod in httpOptions) { + if (httpMethod in rule) { + if (httpMethod === 'additional_bindings') { + continue; + } + httpOptions[httpMethod] = + rule[httpMethod]; + } + if (rule.additional_bindings) { + httpOptions['additional_bindings'] = !httpOptions['additional_bindings'] + ? [] + : Array.isArray(httpOptions['additional_bindings']) + ? httpOptions['additional_bindings'] + : [httpOptions['additional_bindings']]; + // Make the additional_binding to be an array if it is not. + httpOptions['additional_bindings'].push(...rule.additional_bindings); + } + } + } + } +} +//# sourceMappingURL=transcoding.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/transcoding.js.map b/node_modules/google-gax/build/src/transcoding.js.map new file mode 100644 index 0000000..292e35e --- /dev/null +++ b/node_modules/google-gax/build/src/transcoding.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transcoding.js","sourceRoot":"","sources":["../../src/transcoding.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAmCH,4BAsBC;AAED,oEA6BC;AAED,kCAcC;AAED,gEA2BC;AAED,8CAKC;AAED,oDAKC;AAMD,oCA0BC;AAYD,sBA6BC;AAED,sCA0BC;AAED,sDAEC;AAED,8BAkEC;AAGD,8CAyCC;AApWD,iCAAuD;AASvD,MAAM,cAAc,GAAG,mBAAmB,CAAC;AAC3C,MAAM,kBAAkB,GAAG,iBAAiB,CAAC;AAK7C,qEAAqE;AACrE,MAAM,oBAAoB,GACxB,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,OAA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CAAC,WAAW,CAC/C,qBAAqB,CACtB;wBACC,CAAC,CAAC,EAAE;wBACJ,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,WAAW,CAAC,qBAAqB,CAAC,CAAC;4BACjD,CAAC,CAAC,WAAW,CAAC,qBAAqB,CAAC;4BACpC,CAAC,CAAC,CAAC,WAAW,CAAC,qBAAqB,CAAC,CAAC,CAAC;oBAC3C,2DAA2D;oBAC3D,WAAW,CAAC,qBAAqB,CAAC,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,mBAAmB,CAAC,CAAC;gBACvE,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/util.d.ts b/node_modules/google-gax/build/src/util.d.ts new file mode 100644 index 0000000..880e80e --- /dev/null +++ b/node_modules/google-gax/build/src/util.d.ts @@ -0,0 +1,21 @@ +/** + * Converts a given string from camelCase (used by protobuf.js and in JSON) + * to snake_case (normally used in proto definitions). + */ +export declare function camelToSnakeCase(str: string): string; +/** + * Converts a given string from snake_case (normally used in proto definitions) or + * PascalCase (also used in proto definitions) to camelCase (used by protobuf.js). + * Preserves capitalization of the first character. + */ +export declare function toCamelCase(str: string): string; +/** + * Converts a given string to lower camel case (forcing the first character to be + * in lower case). + */ +export declare function toLowerCamelCase(str: string): string; +/** + * Converts a given string to lower camel case (forcing the first character to be + * in lower case). + */ +export declare function makeUUID(): string; diff --git a/node_modules/google-gax/build/src/util.js b/node_modules/google-gax/build/src/util.js new file mode 100644 index 0000000..4fa2d1b --- /dev/null +++ b/node_modules/google-gax/build/src/util.js @@ -0,0 +1,110 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.camelToSnakeCase = camelToSnakeCase; +exports.toCamelCase = toCamelCase; +exports.toLowerCamelCase = toLowerCamelCase; +exports.makeUUID = makeUUID; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const uuid_1 = require("uuid"); +function words(str, normalize = false) { + if (normalize) { + // strings like somethingABCSomething are special case for protobuf.js, + // they should be split as "something", "abc", "something". + // Deal with sequences of capital letters first. + str = str.replace(/([A-Z])([A-Z]+)([A-Z])/g, (str) => { + return (str[0] + + str.slice(1, str.length - 1).toLowerCase() + + str[str.length - 1]); + }); + } + // split on spaces, non-alphanumeric, or capital letters + // note: we keep the capitalization of the first word (special case: IPProtocol) + return str + .split(/(?=[A-Z])|[^A-Za-z0-9.]+/) + .filter(w => w.length > 0) + .map((w, index) => (index === 0 ? w : w.toLowerCase())); +} +/** + * Converts the first character of the given string to lower case. + */ +function lowercase(str) { + if (str.length === 0) { + return str; + } + return str[0].toLowerCase() + str.slice(1); +} +/** + * Converts a given string from camelCase (used by protobuf.js and in JSON) + * to snake_case (normally used in proto definitions). + */ +function camelToSnakeCase(str) { + // Keep the first position capitalization, otherwise decapitalize with underscore. + const wordsList = words(str); + if (wordsList.length === 0) { + return str; + } + const result = [wordsList[0]]; + result.push(...wordsList.slice(1).map(lowercase)); + return result.join('_'); +} +/** + * Capitalizes the first character of the given string. + */ +function capitalize(str) { + if (str.length === 0) { + return str; + } + return str[0].toUpperCase() + str.slice(1); +} +/** + * Converts a given string from snake_case (normally used in proto definitions) or + * PascalCase (also used in proto definitions) to camelCase (used by protobuf.js). + * Preserves capitalization of the first character. + */ +function toCamelCase(str) { + const wordsList = words(str, /*normalize:*/ true); + if (wordsList.length === 0) { + return str; + } + const result = [wordsList[0]]; + result.push(...wordsList.slice(1).map(w => { + if (w.match(/^\d+$/)) { + return '_' + w; + } + return capitalize(w); + })); + return result.join(''); +} +/** + * Converts a given string to lower camel case (forcing the first character to be + * in lower case). + */ +function toLowerCamelCase(str) { + const camelCase = toCamelCase(str); + if (camelCase.length === 0) { + return camelCase; + } + return camelCase[0].toLowerCase() + camelCase.slice(1); +} +/** + * Converts a given string to lower camel case (forcing the first character to be + * in lower case). + */ +function makeUUID() { + return (0, uuid_1.v4)(); +} +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/util.js.map b/node_modules/google-gax/build/src/util.js.map new file mode 100644 index 0000000..8782b81 --- /dev/null +++ b/node_modules/google-gax/build/src/util.js.map @@ -0,0 +1 @@ +{"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/util.ts"],"names":[],"mappings":";;AAoDA,4CASC;AAiBD,kCAeC;AAMD,4CAMC;AAMD,4BAEC;AAjHD;;;;;;;;;;;;;;GAcG;AACH,+BAAkC;AAElC,SAAS,KAAK,CAAC,GAAW,EAAE,SAAS,GAAG,KAAK;IAC3C,IAAI,SAAS,EAAE,CAAC;QACd,uEAAuE;QACvE,2DAA2D;QAC3D,gDAAgD;QAChD,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,yBAAyB,EAAE,CAAC,GAAW,EAAE,EAAE;YAC3D,OAAO,CACL,GAAG,CAAC,CAAC,CAAC;gBACN,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,WAAW,EAAE;gBAC1C,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CACpB,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;IACD,wDAAwD;IACxD,gFAAgF;IAChF,OAAO,GAAG;SACP,KAAK,CAAC,0BAA0B,CAAC;SACjC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;SACzB,GAAG,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC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MAAM,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9B,MAAM,CAAC,IAAI,CACT,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE;QAC5B,IAAI,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;YACrB,OAAO,GAAG,GAAG,CAAC,CAAC;QACjB,CAAC;QACD,OAAO,UAAU,CAAC,CAAC,CAAC,CAAC;IACvB,CAAC,CAAC,CACH,CAAC;IACF,OAAO,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AACzB,CAAC;AAED;;;GAGG;AACH,SAAgB,gBAAgB,CAAC,GAAW;IAC1C,MAAM,SAAS,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC;IACnC,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC3B,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,SAAS,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACzD,CAAC;AAED;;;GAGG;AACH,SAAgB,QAAQ;IACtB,OAAO,IAAA,SAAM,GAAE,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/node_modules/google-gax/build/src/warnings.d.ts b/node_modules/google-gax/build/src/warnings.d.ts new file mode 100644 index 0000000..48634d4 --- /dev/null +++ b/node_modules/google-gax/build/src/warnings.d.ts @@ -0,0 +1,16 @@ +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare function warn(code: string, message: string, warnType?: string): void; diff --git a/node_modules/google-gax/build/src/warnings.js b/node_modules/google-gax/build/src/warnings.js new file mode 100644 index 0000000..e1a4a29 --- /dev/null +++ b/node_modules/google-gax/build/src/warnings.js @@ -0,0 +1,40 @@ +"use strict"; +/** + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.warn = warn; +const featureDetection_1 = require("./featureDetection"); +const emittedWarnings = new Set(); +// warnType is the type of warning (e.g. 'DeprecationWarning', 'ExperimentalWarning', etc.) +function warn(code, message, warnType) { + // Only show a given warning once + if (emittedWarnings.has(code)) { + return; + } + emittedWarnings.add(code); + if (!(0, featureDetection_1.isNodeJS)()) { + console.warn(message); + } + else if (typeof warnType !== 'undefined') { + process.emitWarning(message, { + type: warnType, + }); + } + else { + process.emitWarning(message); + } +} +//# sourceMappingURL=warnings.js.map \ No newline at end of file diff --git a/node_modules/google-gax/build/src/warnings.js.map b/node_modules/google-gax/build/src/warnings.js.map new file mode 100644 index 0000000..c5b7fea --- /dev/null +++ b/node_modules/google-gax/build/src/warnings.js.map @@ -0,0 +1 @@ +{"version":3,"file":"warnings.js","sourceRoot":"","sources":["../../src/warnings.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAOH,oBAgBC;AArBD,yDAA4C;AAE5C,MAAM,eAAe,GAAG,IAAI,GAAG,EAAU,CAAC;AAE1C,2FAA2F;AAC3F,SAAgB,IAAI,CAAC,IAAY,EAAE,OAAe,EAAE,QAAiB;IACnE,iCAAiC;IACjC,IAAI,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;QAC9B,OAAO;IACT,CAAC;IACD,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAE1B,IAAI,CAAC,IAAA,2BAAQ,GAAE,EAAE,CAAC;QAChB,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACxB,CAAC;SAAM,IAAI,OAAO,QAAQ,KAAK,WAAW,EAAE,CAAC;QAC3C,OAAO,CAAC,WAAW,CAAC,OAAO,EAAE;YAC3B,IAAI,EAAE,QAAQ;SACf,CAAC,CAAC;IACL,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IAC/B,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/.bin/uuid b/node_modules/google-gax/node_modules/.bin/uuid new file mode 100644 index 0000000..0c2d469 --- /dev/null +++ b/node_modules/google-gax/node_modules/.bin/uuid @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../uuid/dist/bin/uuid" "$@" +else + exec node "$basedir/../uuid/dist/bin/uuid" "$@" +fi diff --git a/node_modules/google-gax/node_modules/.bin/uuid.cmd b/node_modules/google-gax/node_modules/.bin/uuid.cmd new file mode 100644 index 0000000..0f2376e --- /dev/null +++ b/node_modules/google-gax/node_modules/.bin/uuid.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\uuid\dist\bin\uuid" %* diff --git a/node_modules/google-gax/node_modules/.bin/uuid.ps1 b/node_modules/google-gax/node_modules/.bin/uuid.ps1 new file mode 100644 index 0000000..7804628 --- /dev/null +++ b/node_modules/google-gax/node_modules/.bin/uuid.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } else { + & "$basedir/node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } else { + & "node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/google-gax/node_modules/uuid/CHANGELOG.md b/node_modules/google-gax/node_modules/uuid/CHANGELOG.md new file mode 100644 index 0000000..0412ad8 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/CHANGELOG.md @@ -0,0 +1,274 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## [9.0.1](https://github.com/uuidjs/uuid/compare/v9.0.0...v9.0.1) (2023-09-12) + +### build + +- Fix CI to work with Node.js 20.x + +## [9.0.0](https://github.com/uuidjs/uuid/compare/v8.3.2...v9.0.0) (2022-09-05) + +### ⚠ BREAKING CHANGES + +- Drop Node.js 10.x support. This library always aims at supporting one EOLed LTS release which by this time now is 12.x which has reached EOL 30 Apr 2022. + +- Remove the minified UMD build from the package. + + Minified code is hard to audit and since this is a widely used library it seems more appropriate nowadays to optimize for auditability than to ship a legacy module format that, at best, serves educational purposes nowadays. + + For production browser use cases, users should be using a bundler. For educational purposes, today's online sandboxes like replit.com offer convenient ways to load npm modules, so the use case for UMD through repos like UNPKG or jsDelivr has largely vanished. + +- Drop IE 11 and Safari 10 support. Drop support for browsers that don't correctly implement const/let and default arguments, and no longer transpile the browser build to ES2015. + + This also removes the fallback on msCrypto instead of the crypto API. + + Browser tests are run in the first supported version of each supported browser and in the latest (as of this commit) version available on Browserstack. + +### Features + +- optimize uuid.v1 by 1.3x uuid.v4 by 4.3x (430%) ([#597](https://github.com/uuidjs/uuid/issues/597)) ([3a033f6](https://github.com/uuidjs/uuid/commit/3a033f6bab6bb3780ece6d645b902548043280bc)) +- remove UMD build ([#645](https://github.com/uuidjs/uuid/issues/645)) ([e948a0f](https://github.com/uuidjs/uuid/commit/e948a0f22bf22f4619b27bd913885e478e20fe6f)), closes [#620](https://github.com/uuidjs/uuid/issues/620) +- use native crypto.randomUUID when available ([#600](https://github.com/uuidjs/uuid/issues/600)) ([c9e076c](https://github.com/uuidjs/uuid/commit/c9e076c852edad7e9a06baaa1d148cf4eda6c6c4)) + +### Bug Fixes + +- add Jest/jsdom compatibility ([#642](https://github.com/uuidjs/uuid/issues/642)) ([16f9c46](https://github.com/uuidjs/uuid/commit/16f9c469edf46f0786164cdf4dc980743984a6fd)) +- change default export to named function ([#545](https://github.com/uuidjs/uuid/issues/545)) ([c57bc5a](https://github.com/uuidjs/uuid/commit/c57bc5a9a0653273aa639cda9177ce52efabe42a)) +- handle error when parameter is not set in v3 and v5 ([#622](https://github.com/uuidjs/uuid/issues/622)) ([fcd7388](https://github.com/uuidjs/uuid/commit/fcd73881692d9fabb63872576ba28e30ff852091)) +- run npm audit fix ([#644](https://github.com/uuidjs/uuid/issues/644)) ([04686f5](https://github.com/uuidjs/uuid/commit/04686f54c5fed2cfffc1b619f4970c4bb8532353)) +- upgrading from uuid3 broken link ([#568](https://github.com/uuidjs/uuid/issues/568)) ([1c849da](https://github.com/uuidjs/uuid/commit/1c849da6e164259e72e18636726345b13a7eddd6)) + +### build + +- drop Node.js 8.x from babel transpile target ([#603](https://github.com/uuidjs/uuid/issues/603)) ([aa11485](https://github.com/uuidjs/uuid/commit/aa114858260402107ec8a1e1a825dea0a259bcb5)) +- drop support for legacy browsers (IE11, Safari 10) ([#604](https://github.com/uuidjs/uuid/issues/604)) ([0f433e5](https://github.com/uuidjs/uuid/commit/0f433e5ec444edacd53016de67db021102f36148)) + +- drop node 10.x to upgrade dev dependencies ([#653](https://github.com/uuidjs/uuid/issues/653)) ([28a5712](https://github.com/uuidjs/uuid/commit/28a571283f8abda6b9d85e689f95b7d3ee9e282e)), closes [#643](https://github.com/uuidjs/uuid/issues/643) + +### [8.3.2](https://github.com/uuidjs/uuid/compare/v8.3.1...v8.3.2) (2020-12-08) + +### Bug Fixes + +- lazy load getRandomValues ([#537](https://github.com/uuidjs/uuid/issues/537)) ([16c8f6d](https://github.com/uuidjs/uuid/commit/16c8f6df2f6b09b4d6235602d6a591188320a82e)), closes [#536](https://github.com/uuidjs/uuid/issues/536) + +### [8.3.1](https://github.com/uuidjs/uuid/compare/v8.3.0...v8.3.1) (2020-10-04) + +### Bug Fixes + +- support expo>=39.0.0 ([#515](https://github.com/uuidjs/uuid/issues/515)) ([c65a0f3](https://github.com/uuidjs/uuid/commit/c65a0f3fa73b901959d638d1e3591dfacdbed867)), closes [#375](https://github.com/uuidjs/uuid/issues/375) + +## [8.3.0](https://github.com/uuidjs/uuid/compare/v8.2.0...v8.3.0) (2020-07-27) + +### Features + +- add parse/stringify/validate/version/NIL APIs ([#479](https://github.com/uuidjs/uuid/issues/479)) ([0e6c10b](https://github.com/uuidjs/uuid/commit/0e6c10ba1bf9517796ff23c052fc0468eedfd5f4)), closes [#475](https://github.com/uuidjs/uuid/issues/475) [#478](https://github.com/uuidjs/uuid/issues/478) [#480](https://github.com/uuidjs/uuid/issues/480) [#481](https://github.com/uuidjs/uuid/issues/481) [#180](https://github.com/uuidjs/uuid/issues/180) + +## [8.2.0](https://github.com/uuidjs/uuid/compare/v8.1.0...v8.2.0) (2020-06-23) + +### Features + +- improve performance of v1 string representation ([#453](https://github.com/uuidjs/uuid/issues/453)) ([0ee0b67](https://github.com/uuidjs/uuid/commit/0ee0b67c37846529c66089880414d29f3ae132d5)) +- remove deprecated v4 string parameter ([#454](https://github.com/uuidjs/uuid/issues/454)) ([88ce3ca](https://github.com/uuidjs/uuid/commit/88ce3ca0ba046f60856de62c7ce03f7ba98ba46c)), closes [#437](https://github.com/uuidjs/uuid/issues/437) +- support jspm ([#473](https://github.com/uuidjs/uuid/issues/473)) ([e9f2587](https://github.com/uuidjs/uuid/commit/e9f2587a92575cac31bc1d4ae944e17c09756659)) + +### Bug Fixes + +- prepare package exports for webpack 5 ([#468](https://github.com/uuidjs/uuid/issues/468)) ([8d6e6a5](https://github.com/uuidjs/uuid/commit/8d6e6a5f8965ca9575eb4d92e99a43435f4a58a8)) + +## [8.1.0](https://github.com/uuidjs/uuid/compare/v8.0.0...v8.1.0) (2020-05-20) + +### Features + +- improve v4 performance by reusing random number array ([#435](https://github.com/uuidjs/uuid/issues/435)) ([bf4af0d](https://github.com/uuidjs/uuid/commit/bf4af0d711b4d2ed03d1f74fd12ad0baa87dc79d)) +- optimize V8 performance of bytesToUuid ([#434](https://github.com/uuidjs/uuid/issues/434)) ([e156415](https://github.com/uuidjs/uuid/commit/e156415448ec1af2351fa0b6660cfb22581971f2)) + +### Bug Fixes + +- export package.json required by react-native and bundlers ([#449](https://github.com/uuidjs/uuid/issues/449)) ([be1c8fe](https://github.com/uuidjs/uuid/commit/be1c8fe9a3206c358e0059b52fafd7213aa48a52)), closes [ai/nanoevents#44](https://github.com/ai/nanoevents/issues/44#issuecomment-602010343) [#444](https://github.com/uuidjs/uuid/issues/444) + +## [8.0.0](https://github.com/uuidjs/uuid/compare/v7.0.3...v8.0.0) (2020-04-29) + +### ⚠ BREAKING CHANGES + +- For native ECMAScript Module (ESM) usage in Node.js only named exports are exposed, there is no more default export. + + ```diff + -import uuid from 'uuid'; + -console.log(uuid.v4()); // -> 'cd6c3b08-0adc-4f4b-a6ef-36087a1c9869' + +import { v4 as uuidv4 } from 'uuid'; + +uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' + ``` + +- Deep requiring specific algorithms of this library like `require('uuid/v4')`, which has been deprecated in `uuid@7`, is no longer supported. + + Instead use the named exports that this module exports. + + For ECMAScript Modules (ESM): + + ```diff + -import uuidv4 from 'uuid/v4'; + +import { v4 as uuidv4 } from 'uuid'; + uuidv4(); + ``` + + For CommonJS: + + ```diff + -const uuidv4 = require('uuid/v4'); + +const { v4: uuidv4 } = require('uuid'); + uuidv4(); + ``` + +### Features + +- native Node.js ES Modules (wrapper approach) ([#423](https://github.com/uuidjs/uuid/issues/423)) ([2d9f590](https://github.com/uuidjs/uuid/commit/2d9f590ad9701d692625c07ed62f0a0f91227991)), closes [#245](https://github.com/uuidjs/uuid/issues/245) [#419](https://github.com/uuidjs/uuid/issues/419) [#342](https://github.com/uuidjs/uuid/issues/342) +- remove deep requires ([#426](https://github.com/uuidjs/uuid/issues/426)) ([daf72b8](https://github.com/uuidjs/uuid/commit/daf72b84ceb20272a81bb5fbddb05dd95922cbba)) + +### Bug Fixes + +- add CommonJS syntax example to README quickstart section ([#417](https://github.com/uuidjs/uuid/issues/417)) ([e0ec840](https://github.com/uuidjs/uuid/commit/e0ec8402c7ad44b7ef0453036c612f5db513fda0)) + +### [7.0.3](https://github.com/uuidjs/uuid/compare/v7.0.2...v7.0.3) (2020-03-31) + +### Bug Fixes + +- make deep require deprecation warning work in browsers ([#409](https://github.com/uuidjs/uuid/issues/409)) ([4b71107](https://github.com/uuidjs/uuid/commit/4b71107d8c0d2ef56861ede6403fc9dc35a1e6bf)), closes [#408](https://github.com/uuidjs/uuid/issues/408) + +### [7.0.2](https://github.com/uuidjs/uuid/compare/v7.0.1...v7.0.2) (2020-03-04) + +### Bug Fixes + +- make access to msCrypto consistent ([#393](https://github.com/uuidjs/uuid/issues/393)) ([8bf2a20](https://github.com/uuidjs/uuid/commit/8bf2a20f3565df743da7215eebdbada9d2df118c)) +- simplify link in deprecation warning ([#391](https://github.com/uuidjs/uuid/issues/391)) ([bb2c8e4](https://github.com/uuidjs/uuid/commit/bb2c8e4e9f4c5f9c1eaaf3ea59710c633cd90cb7)) +- update links to match content in readme ([#386](https://github.com/uuidjs/uuid/issues/386)) ([44f2f86](https://github.com/uuidjs/uuid/commit/44f2f86e9d2bbf14ee5f0f00f72a3db1292666d4)) + +### [7.0.1](https://github.com/uuidjs/uuid/compare/v7.0.0...v7.0.1) (2020-02-25) + +### Bug Fixes + +- clean up esm builds for node and browser ([#383](https://github.com/uuidjs/uuid/issues/383)) ([59e6a49](https://github.com/uuidjs/uuid/commit/59e6a49e7ce7b3e8fb0f3ee52b9daae72af467dc)) +- provide browser versions independent from module system ([#380](https://github.com/uuidjs/uuid/issues/380)) ([4344a22](https://github.com/uuidjs/uuid/commit/4344a22e7aed33be8627eeaaf05360f256a21753)), closes [#378](https://github.com/uuidjs/uuid/issues/378) + +## [7.0.0](https://github.com/uuidjs/uuid/compare/v3.4.0...v7.0.0) (2020-02-24) + +### ⚠ BREAKING CHANGES + +- The default export, which used to be the v4() method but which was already discouraged in v3.x of this library, has been removed. +- Explicitly note that deep imports of the different uuid version functions are deprecated and no longer encouraged and that ECMAScript module named imports should be used instead. Emit a deprecation warning for people who deep-require the different algorithm variants. +- Remove builtin support for insecure random number generators in the browser. Users who want that will have to supply their own random number generator function. +- Remove support for generating v3 and v5 UUIDs in Node.js<4.x +- Convert code base to ECMAScript Modules (ESM) and release CommonJS build for node and ESM build for browser bundlers. + +### Features + +- add UMD build to npm package ([#357](https://github.com/uuidjs/uuid/issues/357)) ([4e75adf](https://github.com/uuidjs/uuid/commit/4e75adf435196f28e3fbbe0185d654b5ded7ca2c)), closes [#345](https://github.com/uuidjs/uuid/issues/345) +- add various es module and CommonJS examples ([b238510](https://github.com/uuidjs/uuid/commit/b238510bf352463521f74bab175a3af9b7a42555)) +- ensure that docs are up-to-date in CI ([ee5e77d](https://github.com/uuidjs/uuid/commit/ee5e77db547474f5a8f23d6c857a6d399209986b)) +- hybrid CommonJS & ECMAScript modules build ([a3f078f](https://github.com/uuidjs/uuid/commit/a3f078faa0baff69ab41aed08e041f8f9c8993d0)) +- remove insecure fallback random number generator ([3a5842b](https://github.com/uuidjs/uuid/commit/3a5842b141a6e5de0ae338f391661e6b84b167c9)), closes [#173](https://github.com/uuidjs/uuid/issues/173) +- remove support for pre Node.js v4 Buffer API ([#356](https://github.com/uuidjs/uuid/issues/356)) ([b59b5c5](https://github.com/uuidjs/uuid/commit/b59b5c5ecad271c5453f1a156f011671f6d35627)) +- rename repository to github:uuidjs/uuid ([#351](https://github.com/uuidjs/uuid/issues/351)) ([c37a518](https://github.com/uuidjs/uuid/commit/c37a518e367ac4b6d0aa62dba1bc6ce9e85020f7)), closes [#338](https://github.com/uuidjs/uuid/issues/338) + +### Bug Fixes + +- add deep-require proxies for local testing and adjust tests ([#365](https://github.com/uuidjs/uuid/issues/365)) ([7fedc79](https://github.com/uuidjs/uuid/commit/7fedc79ac8fda4bfd1c566c7f05ef4ac13b2db48)) +- add note about removal of default export ([#372](https://github.com/uuidjs/uuid/issues/372)) ([12749b7](https://github.com/uuidjs/uuid/commit/12749b700eb49db8a9759fd306d8be05dbfbd58c)), closes [#370](https://github.com/uuidjs/uuid/issues/370) +- deprecated deep requiring of the different algorithm versions ([#361](https://github.com/uuidjs/uuid/issues/361)) ([c0bdf15](https://github.com/uuidjs/uuid/commit/c0bdf15e417639b1aeb0b247b2fb11f7a0a26b23)) + +## [3.4.0](https://github.com/uuidjs/uuid/compare/v3.3.3...v3.4.0) (2020-01-16) + +### Features + +- rename repository to github:uuidjs/uuid ([#351](https://github.com/uuidjs/uuid/issues/351)) ([e2d7314](https://github.com/uuidjs/uuid/commit/e2d7314)), closes [#338](https://github.com/uuidjs/uuid/issues/338) + +## [3.3.3](https://github.com/uuidjs/uuid/compare/v3.3.2...v3.3.3) (2019-08-19) + +### Bug Fixes + +- no longer run ci tests on node v4 +- upgrade dependencies + +## [3.3.2](https://github.com/uuidjs/uuid/compare/v3.3.1...v3.3.2) (2018-06-28) + +### Bug Fixes + +- typo ([305d877](https://github.com/uuidjs/uuid/commit/305d877)) + +## [3.3.1](https://github.com/uuidjs/uuid/compare/v3.3.0...v3.3.1) (2018-06-28) + +### Bug Fixes + +- fix [#284](https://github.com/uuidjs/uuid/issues/284) by setting function name in try-catch ([f2a60f2](https://github.com/uuidjs/uuid/commit/f2a60f2)) + +# [3.3.0](https://github.com/uuidjs/uuid/compare/v3.2.1...v3.3.0) (2018-06-22) + +### Bug Fixes + +- assignment to readonly property to allow running in strict mode ([#270](https://github.com/uuidjs/uuid/issues/270)) ([d062fdc](https://github.com/uuidjs/uuid/commit/d062fdc)) +- fix [#229](https://github.com/uuidjs/uuid/issues/229) ([c9684d4](https://github.com/uuidjs/uuid/commit/c9684d4)) +- Get correct version of IE11 crypto ([#274](https://github.com/uuidjs/uuid/issues/274)) ([153d331](https://github.com/uuidjs/uuid/commit/153d331)) +- mem issue when generating uuid ([#267](https://github.com/uuidjs/uuid/issues/267)) ([c47702c](https://github.com/uuidjs/uuid/commit/c47702c)) + +### Features + +- enforce Conventional Commit style commit messages ([#282](https://github.com/uuidjs/uuid/issues/282)) ([cc9a182](https://github.com/uuidjs/uuid/commit/cc9a182)) + +## [3.2.1](https://github.com/uuidjs/uuid/compare/v3.2.0...v3.2.1) (2018-01-16) + +### Bug Fixes + +- use msCrypto if available. Fixes [#241](https://github.com/uuidjs/uuid/issues/241) ([#247](https://github.com/uuidjs/uuid/issues/247)) ([1fef18b](https://github.com/uuidjs/uuid/commit/1fef18b)) + +# [3.2.0](https://github.com/uuidjs/uuid/compare/v3.1.0...v3.2.0) (2018-01-16) + +### Bug Fixes + +- remove mistakenly added typescript dependency, rollback version (standard-version will auto-increment) ([09fa824](https://github.com/uuidjs/uuid/commit/09fa824)) +- use msCrypto if available. Fixes [#241](https://github.com/uuidjs/uuid/issues/241) ([#247](https://github.com/uuidjs/uuid/issues/247)) ([1fef18b](https://github.com/uuidjs/uuid/commit/1fef18b)) + +### Features + +- Add v3 Support ([#217](https://github.com/uuidjs/uuid/issues/217)) ([d94f726](https://github.com/uuidjs/uuid/commit/d94f726)) + +# [3.1.0](https://github.com/uuidjs/uuid/compare/v3.1.0...v3.0.1) (2017-06-17) + +### Bug Fixes + +- (fix) Add .npmignore file to exclude test/ and other non-essential files from packing. (#183) +- Fix typo (#178) +- Simple typo fix (#165) + +### Features + +- v5 support in CLI (#197) +- V5 support (#188) + +# 3.0.1 (2016-11-28) + +- split uuid versions into separate files + +# 3.0.0 (2016-11-17) + +- remove .parse and .unparse + +# 2.0.0 + +- Removed uuid.BufferClass + +# 1.4.0 + +- Improved module context detection +- Removed public RNG functions + +# 1.3.2 + +- Improve tests and handling of v1() options (Issue #24) +- Expose RNG option to allow for perf testing with different generators + +# 1.3.0 + +- Support for version 1 ids, thanks to [@ctavan](https://github.com/ctavan)! +- Support for node.js crypto API +- De-emphasizing performance in favor of a) cryptographic quality PRNGs where available and b) more manageable code diff --git a/node_modules/google-gax/node_modules/uuid/CONTRIBUTING.md b/node_modules/google-gax/node_modules/uuid/CONTRIBUTING.md new file mode 100644 index 0000000..4a4503d --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/CONTRIBUTING.md @@ -0,0 +1,18 @@ +# Contributing + +Please feel free to file GitHub Issues or propose Pull Requests. We're always happy to discuss improvements to this library! + +## Testing + +```shell +npm test +``` + +## Releasing + +Releases are supposed to be done from master, version bumping is automated through [`standard-version`](https://github.com/conventional-changelog/standard-version): + +```shell +npm run release -- --dry-run # verify output manually +npm run release # follow the instructions from the output of this command +``` diff --git a/node_modules/google-gax/node_modules/uuid/LICENSE.md b/node_modules/google-gax/node_modules/uuid/LICENSE.md new file mode 100644 index 0000000..3934168 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/LICENSE.md @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2010-2020 Robert Kieffer and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/google-gax/node_modules/uuid/README.md b/node_modules/google-gax/node_modules/uuid/README.md new file mode 100644 index 0000000..4f51e09 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/README.md @@ -0,0 +1,466 @@ + + + +# uuid [![CI](https://github.com/uuidjs/uuid/workflows/CI/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ACI) [![Browser](https://github.com/uuidjs/uuid/workflows/Browser/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ABrowser) + +For the creation of [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) UUIDs + +- **Complete** - Support for RFC4122 version 1, 3, 4, and 5 UUIDs +- **Cross-platform** - Support for ... + - CommonJS, [ECMAScript Modules](#ecmascript-modules) and [CDN builds](#cdn-builds) + - NodeJS 12+ ([LTS releases](https://github.com/nodejs/Release)) + - Chrome, Safari, Firefox, Edge browsers + - Webpack and rollup.js module bundlers + - [React Native / Expo](#react-native--expo) +- **Secure** - Cryptographically-strong random values +- **Small** - Zero-dependency, small footprint, plays nice with "tree shaking" packagers +- **CLI** - Includes the [`uuid` command line](#command-line) utility + +> **Note** Upgrading from `uuid@3`? Your code is probably okay, but check out [Upgrading From `uuid@3`](#upgrading-from-uuid3) for details. + +> **Note** Only interested in creating a version 4 UUID? You might be able to use [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID), eliminating the need to install this library. + +## Quickstart + +To create a random UUID... + +**1. Install** + +```shell +npm install uuid +``` + +**2. Create a UUID** (ES6 module syntax) + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' +``` + +... or using CommonJS syntax: + +```javascript +const { v4: uuidv4 } = require('uuid'); +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +For timestamp UUIDs, namespace UUIDs, and other options read on ... + +## API Summary + +| | | | +| --- | --- | --- | +| [`uuid.NIL`](#uuidnil) | The nil UUID string (all zeros) | New in `uuid@8.3` | +| [`uuid.parse()`](#uuidparsestr) | Convert UUID string to array of bytes | New in `uuid@8.3` | +| [`uuid.stringify()`](#uuidstringifyarr-offset) | Convert array of bytes to UUID string | New in `uuid@8.3` | +| [`uuid.v1()`](#uuidv1options-buffer-offset) | Create a version 1 (timestamp) UUID | | +| [`uuid.v3()`](#uuidv3name-namespace-buffer-offset) | Create a version 3 (namespace w/ MD5) UUID | | +| [`uuid.v4()`](#uuidv4options-buffer-offset) | Create a version 4 (random) UUID | | +| [`uuid.v5()`](#uuidv5name-namespace-buffer-offset) | Create a version 5 (namespace w/ SHA-1) UUID | | +| [`uuid.validate()`](#uuidvalidatestr) | Test a string to see if it is a valid UUID | New in `uuid@8.3` | +| [`uuid.version()`](#uuidversionstr) | Detect RFC version of a UUID | New in `uuid@8.3` | + +## API + +### uuid.NIL + +The nil UUID string (all zeros). + +Example: + +```javascript +import { NIL as NIL_UUID } from 'uuid'; + +NIL_UUID; // ⇨ '00000000-0000-0000-0000-000000000000' +``` + +### uuid.parse(str) + +Convert UUID string to array of bytes + +| | | +| --------- | ---------------------------------------- | +| `str` | A valid UUID `String` | +| _returns_ | `Uint8Array[16]` | +| _throws_ | `TypeError` if `str` is not a valid UUID | + +Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left ↠ right order of hex-pairs in UUID strings. As shown in the example below. + +Example: + +```javascript +import { parse as uuidParse } from 'uuid'; + +// Parse a UUID +const bytes = uuidParse('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); + +// Convert to hex strings to show byte order (for documentation purposes) +[...bytes].map((v) => v.toString(16).padStart(2, '0')); // ⇨ + // [ + // '6e', 'c0', 'bd', '7f', + // '11', 'c0', '43', 'da', + // '97', '5e', '2a', '8a', + // 'd9', 'eb', 'ae', '0b' + // ] +``` + +### uuid.stringify(arr[, offset]) + +Convert array of bytes to UUID string + +| | | +| -------------- | ---------------------------------------------------------------------------- | +| `arr` | `Array`-like collection of 16 values (starting from `offset`) between 0-255. | +| [`offset` = 0] | `Number` Starting index in the Array | +| _returns_ | `String` | +| _throws_ | `TypeError` if a valid UUID string cannot be generated | + +Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left ↠ right order of hex-pairs in UUID strings. As shown in the example below. + +Example: + +```javascript +import { stringify as uuidStringify } from 'uuid'; + +const uuidBytes = [ + 0x6e, 0xc0, 0xbd, 0x7f, 0x11, 0xc0, 0x43, 0xda, 0x97, 0x5e, 0x2a, 0x8a, 0xd9, 0xeb, 0xae, 0x0b, +]; + +uuidStringify(uuidBytes); // ⇨ '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b' +``` + +### uuid.v1([options[, buffer[, offset]]]) + +Create an RFC version 1 (timestamp) UUID + +| | | +| --- | --- | +| [`options`] | `Object` with one or more of the following properties: | +| [`options.node` ] | RFC "node" field as an `Array[6]` of byte values (per 4.1.6) | +| [`options.clockseq`] | RFC "clock sequence" as a `Number` between 0 - 0x3fff | +| [`options.msecs`] | RFC "timestamp" field (`Number` of milliseconds, unix epoch) | +| [`options.nsecs`] | RFC "timestamp" field (`Number` of nanoseconds to add to `msecs`, should be 0-10,000) | +| [`options.random`] | `Array` of 16 random bytes (0-255) | +| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | +| _throws_ | `Error` if more than 10M UUIDs/sec are requested | + +Note: The default [node id](https://tools.ietf.org/html/rfc4122#section-4.1.6) (the last 12 digits in the UUID) is generated once, randomly, on process startup, and then remains unchanged for the duration of the process. + +Note: `options.random` and `options.rng` are only meaningful on the very first call to `v1()`, where they may be passed to initialize the internal `node` and `clockseq` fields. + +Example: + +```javascript +import { v1 as uuidv1 } from 'uuid'; + +uuidv1(); // ⇨ '2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d' +``` + +Example using `options`: + +```javascript +import { v1 as uuidv1 } from 'uuid'; + +const v1options = { + node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab], + clockseq: 0x1234, + msecs: new Date('2011-11-01').getTime(), + nsecs: 5678, +}; +uuidv1(v1options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab' +``` + +### uuid.v3(name, namespace[, buffer[, offset]]) + +Create an RFC version 3 (namespace w/ MD5) UUID + +API is identical to `v5()`, but uses "v3" instead. + +⚠️ Note: Per the RFC, "_If backward compatibility is not an issue, SHA-1 [Version 5] is preferred_." + +### uuid.v4([options[, buffer[, offset]]]) + +Create an RFC version 4 (random) UUID + +| | | +| --- | --- | +| [`options`] | `Object` with one or more of the following properties: | +| [`options.random`] | `Array` of 16 random bytes (0-255) | +| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | + +Example: + +```javascript +import { v4 as uuidv4 } from 'uuid'; + +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +Example using predefined `random` values: + +```javascript +import { v4 as uuidv4 } from 'uuid'; + +const v4options = { + random: [ + 0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea, 0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36, + ], +}; +uuidv4(v4options); // ⇨ '109156be-c4fb-41ea-b1b4-efe1671c5836' +``` + +### uuid.v5(name, namespace[, buffer[, offset]]) + +Create an RFC version 5 (namespace w/ SHA-1) UUID + +| | | +| --- | --- | +| `name` | `String \| Array` | +| `namespace` | `String \| Array[16]` Namespace UUID | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | + +Note: The RFC `DNS` and `URL` namespaces are available as `v5.DNS` and `v5.URL`. + +Example with custom namespace: + +```javascript +import { v5 as uuidv5 } from 'uuid'; + +// Define a custom namespace. Readers, create your own using something like +// https://www.uuidgenerator.net/ +const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; + +uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681' +``` + +Example with RFC `URL` namespace: + +```javascript +import { v5 as uuidv5 } from 'uuid'; + +uuidv5('https://www.w3.org/', uuidv5.URL); // ⇨ 'c106a26a-21bb-5538-8bf2-57095d1976c1' +``` + +### uuid.validate(str) + +Test a string to see if it is a valid UUID + +| | | +| --------- | --------------------------------------------------- | +| `str` | `String` to validate | +| _returns_ | `true` if string is a valid UUID, `false` otherwise | + +Example: + +```javascript +import { validate as uuidValidate } from 'uuid'; + +uuidValidate('not a UUID'); // ⇨ false +uuidValidate('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ true +``` + +Using `validate` and `version` together it is possible to do per-version validation, e.g. validate for only v4 UUIds. + +```javascript +import { version as uuidVersion } from 'uuid'; +import { validate as uuidValidate } from 'uuid'; + +function uuidValidateV4(uuid) { + return uuidValidate(uuid) && uuidVersion(uuid) === 4; +} + +const v1Uuid = 'd9428888-122b-11e1-b85c-61cd3cbb3210'; +const v4Uuid = '109156be-c4fb-41ea-b1b4-efe1671c5836'; + +uuidValidateV4(v4Uuid); // ⇨ true +uuidValidateV4(v1Uuid); // ⇨ false +``` + +### uuid.version(str) + +Detect RFC version of a UUID + +| | | +| --------- | ---------------------------------------- | +| `str` | A valid UUID `String` | +| _returns_ | `Number` The RFC version of the UUID | +| _throws_ | `TypeError` if `str` is not a valid UUID | + +Example: + +```javascript +import { version as uuidVersion } from 'uuid'; + +uuidVersion('45637ec4-c85f-11ea-87d0-0242ac130003'); // ⇨ 1 +uuidVersion('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ 4 +``` + +## Command Line + +UUIDs can be generated from the command line using `uuid`. + +```shell +$ npx uuid +ddeb27fb-d9a0-4624-be4d-4615062daed4 +``` + +The default is to generate version 4 UUIDS, however the other versions are supported. Type `uuid --help` for details: + +```shell +$ npx uuid --help + +Usage: + uuid + uuid v1 + uuid v3 + uuid v4 + uuid v5 + uuid --help + +Note: may be "URL" or "DNS" to use the corresponding UUIDs +defined by RFC4122 +``` + +## ECMAScript Modules + +This library comes with [ECMAScript Modules](https://www.ecma-international.org/ecma-262/6.0/#sec-modules) (ESM) support for Node.js versions that support it ([example](./examples/node-esmodules/)) as well as bundlers like [rollup.js](https://rollupjs.org/guide/en/#tree-shaking) ([example](./examples/browser-rollup/)) and [webpack](https://webpack.js.org/guides/tree-shaking/) ([example](./examples/browser-webpack/)) (targeting both, Node.js and browser environments). + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +To run the examples you must first create a dist build of this library in the module root: + +```shell +npm run build +``` + +## CDN Builds + +### ECMAScript Modules + +To load this module directly into modern browsers that [support loading ECMAScript Modules](https://caniuse.com/#feat=es6-module) you can make use of [jspm](https://jspm.org/): + +```html + +``` + +### UMD + +As of `uuid@9` [UMD (Universal Module Definition)](https://github.com/umdjs/umd) builds are no longer shipped with this library. + +If you need a UMD build of this library, use a bundler like Webpack or Rollup. Alternatively, refer to the documentation of [`uuid@8.3.2`](https://github.com/uuidjs/uuid/blob/v8.3.2/README.md#umd) which was the last version that shipped UMD builds. + +## Known issues + +### Duplicate UUIDs (Googlebot) + +This module may generate duplicate UUIDs when run in clients with _deterministic_ random number generators, such as [Googlebot crawlers](https://developers.google.com/search/docs/advanced/crawling/overview-google-crawlers). This can cause problems for apps that expect client-generated UUIDs to always be unique. Developers should be prepared for this and have a strategy for dealing with possible collisions, such as: + +- Check for duplicate UUIDs, fail gracefully +- Disable write operations for Googlebot clients + +### "getRandomValues() not supported" + +This error occurs in environments where the standard [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) API is not supported. This issue can be resolved by adding an appropriate polyfill: + +### React Native / Expo + +1. Install [`react-native-get-random-values`](https://github.com/LinusU/react-native-get-random-values#readme) +1. Import it _before_ `uuid`. Since `uuid` might also appear as a transitive dependency of some other imports it's safest to just import `react-native-get-random-values` as the very first thing in your entry point: + +```javascript +import 'react-native-get-random-values'; +import { v4 as uuidv4 } from 'uuid'; +``` + +Note: If you are using Expo, you must be using at least `react-native-get-random-values@1.5.0` and `expo@39.0.0`. + +### Web Workers / Service Workers (Edge <= 18) + +[In Edge <= 18, Web Crypto is not supported in Web Workers or Service Workers](https://caniuse.com/#feat=cryptography) and we are not aware of a polyfill (let us know if you find one, please). + +### IE 11 (Internet Explorer) + +Support for IE11 and other legacy browsers has been dropped as of `uuid@9`. If you need to support legacy browsers, you can always transpile the uuid module source yourself (e.g. using [Babel](https://babeljs.io/)). + +## Upgrading From `uuid@7` + +### Only Named Exports Supported When Using with Node.js ESM + +`uuid@7` did not come with native ECMAScript Module (ESM) support for Node.js. Importing it in Node.js ESM consequently imported the CommonJS source with a default export. This library now comes with true Node.js ESM support and only provides named exports. + +Instead of doing: + +```javascript +import uuid from 'uuid'; +uuid.v4(); +``` + +you will now have to use the named exports: + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); +``` + +### Deep Requires No Longer Supported + +Deep requires like `require('uuid/v4')` [which have been deprecated in `uuid@7`](#deep-requires-now-deprecated) are no longer supported. + +## Upgrading From `uuid@3` + +"_Wait... what happened to `uuid@4` thru `uuid@6`?!?_" + +In order to avoid confusion with RFC [version 4](#uuidv4options-buffer-offset) and [version 5](#uuidv5name-namespace-buffer-offset) UUIDs, and a possible [version 6](http://gh.peabody.io/uuidv6/), releases 4 thru 6 of this module have been skipped. + +### Deep Requires Now Deprecated + +`uuid@3` encouraged the use of deep requires to minimize the bundle size of browser builds: + +```javascript +const uuidv4 = require('uuid/v4'); // <== NOW DEPRECATED! +uuidv4(); +``` + +As of `uuid@7` this library now provides ECMAScript modules builds, which allow packagers like Webpack and Rollup to do "tree-shaking" to remove dead code. Instead, use the `import` syntax: + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); +``` + +... or for CommonJS: + +```javascript +const { v4: uuidv4 } = require('uuid'); +uuidv4(); +``` + +### Default Export Removed + +`uuid@3` was exporting the Version 4 UUID method as a default export: + +```javascript +const uuid = require('uuid'); // <== REMOVED! +``` + +This usage pattern was already discouraged in `uuid@3` and has been removed in `uuid@7`. + +--- + +Markdown generated from [README_js.md](README_js.md) by diff --git a/node_modules/google-gax/node_modules/uuid/dist/bin/uuid b/node_modules/google-gax/node_modules/uuid/dist/bin/uuid new file mode 100644 index 0000000..f38d2ee --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/bin/uuid @@ -0,0 +1,2 @@ +#!/usr/bin/env node +require('../uuid-bin'); diff --git a/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/index.js b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/index.js new file mode 100644 index 0000000..5586dd3 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/index.js @@ -0,0 +1,79 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "NIL", { + enumerable: true, + get: function get() { + return _nil.default; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function get() { + return _parse.default; + } +}); +Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function get() { + return _stringify.default; + } +}); +Object.defineProperty(exports, "v1", { + enumerable: true, + get: function get() { + return _v.default; + } +}); +Object.defineProperty(exports, "v3", { + enumerable: true, + get: function get() { + return _v2.default; + } +}); +Object.defineProperty(exports, "v4", { + enumerable: true, + get: function get() { + return _v3.default; + } +}); +Object.defineProperty(exports, "v5", { + enumerable: true, + get: function get() { + return _v4.default; + } +}); +Object.defineProperty(exports, "validate", { + enumerable: true, + get: function get() { + return _validate.default; + } +}); +Object.defineProperty(exports, "version", { + enumerable: true, + get: function get() { + return _version.default; + } +}); + +var _v = _interopRequireDefault(require("./v1.js")); + +var _v2 = _interopRequireDefault(require("./v3.js")); + +var _v3 = _interopRequireDefault(require("./v4.js")); + +var _v4 = _interopRequireDefault(require("./v5.js")); + +var _nil = _interopRequireDefault(require("./nil.js")); + +var _version = _interopRequireDefault(require("./version.js")); + +var _validate = _interopRequireDefault(require("./validate.js")); + +var _stringify = _interopRequireDefault(require("./stringify.js")); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/md5.js b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/md5.js new file mode 100644 index 0000000..7a4582a --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/md5.js @@ -0,0 +1,223 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Uint8Array(msg.length); + + for (let i = 0; i < msg.length; ++i) { + bytes[i] = msg.charCodeAt(i); + } + } + + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); +} +/* + * Convert an array of little-endian words to an array of bytes + */ + + +function md5ToHexEncodedArray(input) { + const output = []; + const length32 = input.length * 32; + const hexTab = '0123456789abcdef'; + + for (let i = 0; i < length32; i += 8) { + const x = input[i >> 5] >>> i % 32 & 0xff; + const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); + } + + return output; +} +/** + * Calculate output length with padding and bit length + */ + + +function getOutputLength(inputLength8) { + return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; +} +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + + +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[getOutputLength(len) - 1] = len; + let a = 1732584193; + let b = -271733879; + let c = -1732584194; + let d = 271733878; + + for (let i = 0; i < x.length; i += 16) { + const olda = a; + const oldb = b; + const oldc = c; + const oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; +} +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + + +function bytesToWords(input) { + if (input.length === 0) { + return []; + } + + const length8 = input.length * 8; + const output = new Uint32Array(getOutputLength(length8)); + + for (let i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } + + return output; +} +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + + +function safeAdd(x, y) { + const lsw = (x & 0xffff) + (y & 0xffff); + const msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; +} +/* + * Bitwise rotate a 32-bit number to the left. + */ + + +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; +} +/* + * These functions implement the four basic operations the algorithm uses. + */ + + +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} + +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); +} + +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); +} + +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} + +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} + +var _default = md5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/native.js b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/native.js new file mode 100644 index 0000000..c2eea59 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/native.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); +var _default = { + randomUUID +}; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/nil.js b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/nil.js new file mode 100644 index 0000000..7ade577 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/nil.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = '00000000-0000-0000-0000-000000000000'; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/parse.js b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/parse.js new file mode 100644 index 0000000..4c69fc3 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/parse.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +var _default = parse; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/regex.js b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/regex.js new file mode 100644 index 0000000..1ef91d6 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/regex.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/rng.js b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/rng.js new file mode 100644 index 0000000..d067cdb --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/rng.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rng; +// Unique ID creation requires a high quality random # generator. In the browser we therefore +// require the crypto API and do not support built-in fallback to lower quality random number +// generators (like Math.random()). +let getRandomValues; +const rnds8 = new Uint8Array(16); + +function rng() { + // lazy load so that environments that need to polyfill have a chance to do so + if (!getRandomValues) { + // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. + 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); +} \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/sha1.js b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/sha1.js new file mode 100644 index 0000000..24cbced --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/sha1.js @@ -0,0 +1,104 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + + case 1: + return x ^ y ^ z; + + case 2: + return x & y ^ x & z ^ y & z; + + case 3: + return x ^ y ^ z; + } +} + +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} + +function sha1(bytes) { + const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = []; + + for (let i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + // Convert Array-like to Array + bytes = Array.prototype.slice.call(bytes); + } + + bytes.push(0x80); + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + + for (let i = 0; i < N; ++i) { + const arr = new Uint32Array(16); + + for (let j = 0; j < 16; ++j) { + arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + } + + M[i] = arr; + } + + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; + + for (let i = 0; i < N; ++i) { + const W = new Uint32Array(80); + + for (let t = 0; t < 16; ++t) { + W[t] = M[i][t]; + } + + for (let t = 16; t < 80; ++t) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } + + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; +} + +var _default = sha1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/stringify.js b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/stringify.js new file mode 100644 index 0000000..390bf89 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/stringify.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +exports.unsafeStringify = unsafeStringify; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} + +function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; +} + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!(0, _validate.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +var _default = stringify; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/v1.js b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/v1.js new file mode 100644 index 0000000..125bc58 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/v1.js @@ -0,0 +1,107 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = require("./stringify.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || _rng.default)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || (0, _stringify.unsafeStringify)(b); +} + +var _default = v1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/v3.js b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/v3.js new file mode 100644 index 0000000..6b47ff5 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/v3.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _md = _interopRequireDefault(require("./md5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/v35.js b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/v35.js new file mode 100644 index 0000000..7c522d9 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/v35.js @@ -0,0 +1,80 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.URL = exports.DNS = void 0; +exports.default = v35; + +var _stringify = require("./stringify.js"); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.DNS = DNS; +const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = URL; + +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 = (0, _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)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return (0, _stringify.unsafeStringify)(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/v4.js b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/v4.js new file mode 100644 index 0000000..959d698 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/v4.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _native = _interopRequireDefault(require("./native.js")); + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = require("./stringify.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function v4(options, buf, offset) { + if (_native.default.randomUUID && !buf && !options) { + return _native.default.randomUUID(); + } + + options = options || {}; + + const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return (0, _stringify.unsafeStringify)(rnds); +} + +var _default = v4; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/v5.js b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/v5.js new file mode 100644 index 0000000..99d615e --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/v5.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _sha = _interopRequireDefault(require("./sha1.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/validate.js b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/validate.js new file mode 100644 index 0000000..fd05215 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/validate.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _regex = _interopRequireDefault(require("./regex.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function validate(uuid) { + return typeof uuid === 'string' && _regex.default.test(uuid); +} + +var _default = validate; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/version.js b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/version.js new file mode 100644 index 0000000..f63af01 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/commonjs-browser/version.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function version(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.slice(14, 15), 16); +} + +var _default = version; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-browser/index.js b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/index.js new file mode 100644 index 0000000..1db6f6d --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/index.js @@ -0,0 +1,9 @@ +export { default as v1 } from './v1.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as NIL } from './nil.js'; +export { default as version } from './version.js'; +export { default as validate } from './validate.js'; +export { default as stringify } from './stringify.js'; +export { default as parse } from './parse.js'; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-browser/md5.js b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/md5.js new file mode 100644 index 0000000..f12212e --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/md5.js @@ -0,0 +1,215 @@ +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Uint8Array(msg.length); + + for (let i = 0; i < msg.length; ++i) { + bytes[i] = msg.charCodeAt(i); + } + } + + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); +} +/* + * Convert an array of little-endian words to an array of bytes + */ + + +function md5ToHexEncodedArray(input) { + const output = []; + const length32 = input.length * 32; + const hexTab = '0123456789abcdef'; + + for (let i = 0; i < length32; i += 8) { + const x = input[i >> 5] >>> i % 32 & 0xff; + const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); + } + + return output; +} +/** + * Calculate output length with padding and bit length + */ + + +function getOutputLength(inputLength8) { + return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; +} +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + + +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[getOutputLength(len) - 1] = len; + let a = 1732584193; + let b = -271733879; + let c = -1732584194; + let d = 271733878; + + for (let i = 0; i < x.length; i += 16) { + const olda = a; + const oldb = b; + const oldc = c; + const oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; +} +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + + +function bytesToWords(input) { + if (input.length === 0) { + return []; + } + + const length8 = input.length * 8; + const output = new Uint32Array(getOutputLength(length8)); + + for (let i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } + + return output; +} +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + + +function safeAdd(x, y) { + const lsw = (x & 0xffff) + (y & 0xffff); + const msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; +} +/* + * Bitwise rotate a 32-bit number to the left. + */ + + +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; +} +/* + * These functions implement the four basic operations the algorithm uses. + */ + + +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} + +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); +} + +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); +} + +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} + +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} + +export default md5; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-browser/native.js b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/native.js new file mode 100644 index 0000000..b22292c --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/native.js @@ -0,0 +1,4 @@ +const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); +export default { + randomUUID +}; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-browser/nil.js b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/nil.js new file mode 100644 index 0000000..b36324c --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/nil.js @@ -0,0 +1 @@ +export default '00000000-0000-0000-0000-000000000000'; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-browser/parse.js b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/parse.js new file mode 100644 index 0000000..6421c5d --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/parse.js @@ -0,0 +1,35 @@ +import validate from './validate.js'; + +function parse(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +export default parse; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-browser/regex.js b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/regex.js new file mode 100644 index 0000000..3da8673 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/regex.js @@ -0,0 +1 @@ +export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-browser/rng.js b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/rng.js new file mode 100644 index 0000000..6e65234 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/rng.js @@ -0,0 +1,18 @@ +// Unique ID creation requires a high quality random # generator. In the browser we therefore +// require the crypto API and do not support built-in fallback to lower quality random number +// generators (like Math.random()). +let getRandomValues; +const rnds8 = new Uint8Array(16); +export default function rng() { + // lazy load so that environments that need to polyfill have a chance to do so + if (!getRandomValues) { + // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. + 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); +} \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-browser/sha1.js b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/sha1.js new file mode 100644 index 0000000..d3c2565 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/sha1.js @@ -0,0 +1,96 @@ +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + + case 1: + return x ^ y ^ z; + + case 2: + return x & y ^ x & z ^ y & z; + + case 3: + return x ^ y ^ z; + } +} + +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} + +function sha1(bytes) { + const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = []; + + for (let i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + // Convert Array-like to Array + bytes = Array.prototype.slice.call(bytes); + } + + bytes.push(0x80); + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + + for (let i = 0; i < N; ++i) { + const arr = new Uint32Array(16); + + for (let j = 0; j < 16; ++j) { + arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + } + + M[i] = arr; + } + + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; + + for (let i = 0; i < N; ++i) { + const W = new Uint32Array(80); + + for (let t = 0; t < 16; ++t) { + W[t] = M[i][t]; + } + + for (let t = 16; t < 80; ++t) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } + + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; +} + +export default sha1; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-browser/stringify.js b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/stringify.js new file mode 100644 index 0000000..a6e4c88 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/stringify.js @@ -0,0 +1,33 @@ +import validate from './validate.js'; +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ + +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} + +export function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; +} + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!validate(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +export default stringify; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-browser/v1.js b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/v1.js new file mode 100644 index 0000000..382e5d7 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/v1.js @@ -0,0 +1,95 @@ +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; // **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || rng)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || unsafeStringify(b); +} + +export default v1; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-browser/v3.js b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/v3.js new file mode 100644 index 0000000..09063b8 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/v3.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import md5 from './md5.js'; +const v3 = v35('v3', 0x30, md5); +export default v3; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-browser/v35.js b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/v35.js new file mode 100644 index 0000000..3355e1f --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/v35.js @@ -0,0 +1,66 @@ +import { unsafeStringify } from './stringify.js'; +import parse from './parse.js'; + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +export const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +export const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +export default 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(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)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return unsafeStringify(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-browser/v4.js b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/v4.js new file mode 100644 index 0000000..95ea879 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/v4.js @@ -0,0 +1,29 @@ +import native from './native.js'; +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; + +function v4(options, buf, offset) { + if (native.randomUUID && !buf && !options) { + return native.randomUUID(); + } + + options = options || {}; + const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return unsafeStringify(rnds); +} + +export default v4; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-browser/v5.js b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/v5.js new file mode 100644 index 0000000..e87fe31 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/v5.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import sha1 from './sha1.js'; +const v5 = v35('v5', 0x50, sha1); +export default v5; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-browser/validate.js b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/validate.js new file mode 100644 index 0000000..f1cdc7a --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/validate.js @@ -0,0 +1,7 @@ +import REGEX from './regex.js'; + +function validate(uuid) { + return typeof uuid === 'string' && REGEX.test(uuid); +} + +export default validate; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-browser/version.js b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/version.js new file mode 100644 index 0000000..9363076 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-browser/version.js @@ -0,0 +1,11 @@ +import validate from './validate.js'; + +function version(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.slice(14, 15), 16); +} + +export default version; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-node/index.js b/node_modules/google-gax/node_modules/uuid/dist/esm-node/index.js new file mode 100644 index 0000000..1db6f6d --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-node/index.js @@ -0,0 +1,9 @@ +export { default as v1 } from './v1.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as NIL } from './nil.js'; +export { default as version } from './version.js'; +export { default as validate } from './validate.js'; +export { default as stringify } from './stringify.js'; +export { default as parse } from './parse.js'; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-node/md5.js b/node_modules/google-gax/node_modules/uuid/dist/esm-node/md5.js new file mode 100644 index 0000000..4d68b04 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-node/md5.js @@ -0,0 +1,13 @@ +import crypto from 'crypto'; + +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return crypto.createHash('md5').update(bytes).digest(); +} + +export default md5; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-node/native.js b/node_modules/google-gax/node_modules/uuid/dist/esm-node/native.js new file mode 100644 index 0000000..f0d1992 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-node/native.js @@ -0,0 +1,4 @@ +import crypto from 'crypto'; +export default { + randomUUID: crypto.randomUUID +}; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-node/nil.js b/node_modules/google-gax/node_modules/uuid/dist/esm-node/nil.js new file mode 100644 index 0000000..b36324c --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-node/nil.js @@ -0,0 +1 @@ +export default '00000000-0000-0000-0000-000000000000'; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-node/parse.js b/node_modules/google-gax/node_modules/uuid/dist/esm-node/parse.js new file mode 100644 index 0000000..6421c5d --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-node/parse.js @@ -0,0 +1,35 @@ +import validate from './validate.js'; + +function parse(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +export default parse; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-node/regex.js b/node_modules/google-gax/node_modules/uuid/dist/esm-node/regex.js new file mode 100644 index 0000000..3da8673 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-node/regex.js @@ -0,0 +1 @@ +export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-node/rng.js b/node_modules/google-gax/node_modules/uuid/dist/esm-node/rng.js new file mode 100644 index 0000000..8006244 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-node/rng.js @@ -0,0 +1,12 @@ +import crypto from 'crypto'; +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate + +let poolPtr = rnds8Pool.length; +export default function rng() { + if (poolPtr > rnds8Pool.length - 16) { + crypto.randomFillSync(rnds8Pool); + poolPtr = 0; + } + + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-node/sha1.js b/node_modules/google-gax/node_modules/uuid/dist/esm-node/sha1.js new file mode 100644 index 0000000..e23850b --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-node/sha1.js @@ -0,0 +1,13 @@ +import crypto from 'crypto'; + +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return crypto.createHash('sha1').update(bytes).digest(); +} + +export default sha1; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-node/stringify.js b/node_modules/google-gax/node_modules/uuid/dist/esm-node/stringify.js new file mode 100644 index 0000000..a6e4c88 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-node/stringify.js @@ -0,0 +1,33 @@ +import validate from './validate.js'; +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ + +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} + +export function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; +} + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!validate(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +export default stringify; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-node/v1.js b/node_modules/google-gax/node_modules/uuid/dist/esm-node/v1.js new file mode 100644 index 0000000..382e5d7 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-node/v1.js @@ -0,0 +1,95 @@ +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; // **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || rng)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || unsafeStringify(b); +} + +export default v1; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-node/v3.js b/node_modules/google-gax/node_modules/uuid/dist/esm-node/v3.js new file mode 100644 index 0000000..09063b8 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-node/v3.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import md5 from './md5.js'; +const v3 = v35('v3', 0x30, md5); +export default v3; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-node/v35.js b/node_modules/google-gax/node_modules/uuid/dist/esm-node/v35.js new file mode 100644 index 0000000..3355e1f --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-node/v35.js @@ -0,0 +1,66 @@ +import { unsafeStringify } from './stringify.js'; +import parse from './parse.js'; + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +export const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +export const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +export default 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(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)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return unsafeStringify(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-node/v4.js b/node_modules/google-gax/node_modules/uuid/dist/esm-node/v4.js new file mode 100644 index 0000000..95ea879 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-node/v4.js @@ -0,0 +1,29 @@ +import native from './native.js'; +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; + +function v4(options, buf, offset) { + if (native.randomUUID && !buf && !options) { + return native.randomUUID(); + } + + options = options || {}; + const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return unsafeStringify(rnds); +} + +export default v4; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-node/v5.js b/node_modules/google-gax/node_modules/uuid/dist/esm-node/v5.js new file mode 100644 index 0000000..e87fe31 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-node/v5.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import sha1 from './sha1.js'; +const v5 = v35('v5', 0x50, sha1); +export default v5; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-node/validate.js b/node_modules/google-gax/node_modules/uuid/dist/esm-node/validate.js new file mode 100644 index 0000000..f1cdc7a --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-node/validate.js @@ -0,0 +1,7 @@ +import REGEX from './regex.js'; + +function validate(uuid) { + return typeof uuid === 'string' && REGEX.test(uuid); +} + +export default validate; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/esm-node/version.js b/node_modules/google-gax/node_modules/uuid/dist/esm-node/version.js new file mode 100644 index 0000000..9363076 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/esm-node/version.js @@ -0,0 +1,11 @@ +import validate from './validate.js'; + +function version(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.slice(14, 15), 16); +} + +export default version; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/index.js b/node_modules/google-gax/node_modules/uuid/dist/index.js new file mode 100644 index 0000000..88d676a --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/index.js @@ -0,0 +1,79 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "NIL", { + enumerable: true, + get: function () { + return _nil.default; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function () { + return _parse.default; + } +}); +Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function () { + return _stringify.default; + } +}); +Object.defineProperty(exports, "v1", { + enumerable: true, + get: function () { + return _v.default; + } +}); +Object.defineProperty(exports, "v3", { + enumerable: true, + get: function () { + return _v2.default; + } +}); +Object.defineProperty(exports, "v4", { + enumerable: true, + get: function () { + return _v3.default; + } +}); +Object.defineProperty(exports, "v5", { + enumerable: true, + get: function () { + return _v4.default; + } +}); +Object.defineProperty(exports, "validate", { + enumerable: true, + get: function () { + return _validate.default; + } +}); +Object.defineProperty(exports, "version", { + enumerable: true, + get: function () { + return _version.default; + } +}); + +var _v = _interopRequireDefault(require("./v1.js")); + +var _v2 = _interopRequireDefault(require("./v3.js")); + +var _v3 = _interopRequireDefault(require("./v4.js")); + +var _v4 = _interopRequireDefault(require("./v5.js")); + +var _nil = _interopRequireDefault(require("./nil.js")); + +var _version = _interopRequireDefault(require("./version.js")); + +var _validate = _interopRequireDefault(require("./validate.js")); + +var _stringify = _interopRequireDefault(require("./stringify.js")); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/md5-browser.js b/node_modules/google-gax/node_modules/uuid/dist/md5-browser.js new file mode 100644 index 0000000..7a4582a --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/md5-browser.js @@ -0,0 +1,223 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Uint8Array(msg.length); + + for (let i = 0; i < msg.length; ++i) { + bytes[i] = msg.charCodeAt(i); + } + } + + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); +} +/* + * Convert an array of little-endian words to an array of bytes + */ + + +function md5ToHexEncodedArray(input) { + const output = []; + const length32 = input.length * 32; + const hexTab = '0123456789abcdef'; + + for (let i = 0; i < length32; i += 8) { + const x = input[i >> 5] >>> i % 32 & 0xff; + const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); + } + + return output; +} +/** + * Calculate output length with padding and bit length + */ + + +function getOutputLength(inputLength8) { + return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; +} +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + + +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[getOutputLength(len) - 1] = len; + let a = 1732584193; + let b = -271733879; + let c = -1732584194; + let d = 271733878; + + for (let i = 0; i < x.length; i += 16) { + const olda = a; + const oldb = b; + const oldc = c; + const oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; +} +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + + +function bytesToWords(input) { + if (input.length === 0) { + return []; + } + + const length8 = input.length * 8; + const output = new Uint32Array(getOutputLength(length8)); + + for (let i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } + + return output; +} +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + + +function safeAdd(x, y) { + const lsw = (x & 0xffff) + (y & 0xffff); + const msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; +} +/* + * Bitwise rotate a 32-bit number to the left. + */ + + +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; +} +/* + * These functions implement the four basic operations the algorithm uses. + */ + + +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} + +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); +} + +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); +} + +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} + +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} + +var _default = md5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/md5.js b/node_modules/google-gax/node_modules/uuid/dist/md5.js new file mode 100644 index 0000000..824d481 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/md5.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return _crypto.default.createHash('md5').update(bytes).digest(); +} + +var _default = md5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/native-browser.js b/node_modules/google-gax/node_modules/uuid/dist/native-browser.js new file mode 100644 index 0000000..c2eea59 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/native-browser.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); +var _default = { + randomUUID +}; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/native.js b/node_modules/google-gax/node_modules/uuid/dist/native.js new file mode 100644 index 0000000..de80469 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/native.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var _default = { + randomUUID: _crypto.default.randomUUID +}; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/nil.js b/node_modules/google-gax/node_modules/uuid/dist/nil.js new file mode 100644 index 0000000..7ade577 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/nil.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = '00000000-0000-0000-0000-000000000000'; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/parse.js b/node_modules/google-gax/node_modules/uuid/dist/parse.js new file mode 100644 index 0000000..4c69fc3 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/parse.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +var _default = parse; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/regex.js b/node_modules/google-gax/node_modules/uuid/dist/regex.js new file mode 100644 index 0000000..1ef91d6 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/regex.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/rng-browser.js b/node_modules/google-gax/node_modules/uuid/dist/rng-browser.js new file mode 100644 index 0000000..d067cdb --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/rng-browser.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rng; +// Unique ID creation requires a high quality random # generator. In the browser we therefore +// require the crypto API and do not support built-in fallback to lower quality random number +// generators (like Math.random()). +let getRandomValues; +const rnds8 = new Uint8Array(16); + +function rng() { + // lazy load so that environments that need to polyfill have a chance to do so + if (!getRandomValues) { + // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. + 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); +} \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/rng.js b/node_modules/google-gax/node_modules/uuid/dist/rng.js new file mode 100644 index 0000000..3507f93 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/rng.js @@ -0,0 +1,24 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rng; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate + +let poolPtr = rnds8Pool.length; + +function rng() { + if (poolPtr > rnds8Pool.length - 16) { + _crypto.default.randomFillSync(rnds8Pool); + + poolPtr = 0; + } + + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/sha1-browser.js b/node_modules/google-gax/node_modules/uuid/dist/sha1-browser.js new file mode 100644 index 0000000..24cbced --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/sha1-browser.js @@ -0,0 +1,104 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + + case 1: + return x ^ y ^ z; + + case 2: + return x & y ^ x & z ^ y & z; + + case 3: + return x ^ y ^ z; + } +} + +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} + +function sha1(bytes) { + const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = []; + + for (let i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + // Convert Array-like to Array + bytes = Array.prototype.slice.call(bytes); + } + + bytes.push(0x80); + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + + for (let i = 0; i < N; ++i) { + const arr = new Uint32Array(16); + + for (let j = 0; j < 16; ++j) { + arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + } + + M[i] = arr; + } + + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; + + for (let i = 0; i < N; ++i) { + const W = new Uint32Array(80); + + for (let t = 0; t < 16; ++t) { + W[t] = M[i][t]; + } + + for (let t = 16; t < 80; ++t) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } + + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; +} + +var _default = sha1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/sha1.js b/node_modules/google-gax/node_modules/uuid/dist/sha1.js new file mode 100644 index 0000000..03bdd63 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/sha1.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return _crypto.default.createHash('sha1').update(bytes).digest(); +} + +var _default = sha1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/stringify.js b/node_modules/google-gax/node_modules/uuid/dist/stringify.js new file mode 100644 index 0000000..390bf89 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/stringify.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +exports.unsafeStringify = unsafeStringify; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} + +function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; +} + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!(0, _validate.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +var _default = stringify; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/uuid-bin.js b/node_modules/google-gax/node_modules/uuid/dist/uuid-bin.js new file mode 100644 index 0000000..50a7a9f --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/uuid-bin.js @@ -0,0 +1,85 @@ +"use strict"; + +var _assert = _interopRequireDefault(require("assert")); + +var _v = _interopRequireDefault(require("./v1.js")); + +var _v2 = _interopRequireDefault(require("./v3.js")); + +var _v3 = _interopRequireDefault(require("./v4.js")); + +var _v4 = _interopRequireDefault(require("./v5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function usage() { + console.log('Usage:'); + console.log(' uuid'); + console.log(' uuid v1'); + console.log(' uuid v3 '); + console.log(' uuid v4'); + console.log(' uuid v5 '); + console.log(' uuid --help'); + console.log('\nNote: may be "URL" or "DNS" to use the corresponding UUIDs defined by RFC4122'); +} + +const args = process.argv.slice(2); + +if (args.indexOf('--help') >= 0) { + usage(); + process.exit(0); +} + +const version = args.shift() || 'v4'; + +switch (version) { + case 'v1': + console.log((0, _v.default)()); + break; + + case 'v3': + { + const name = args.shift(); + let namespace = args.shift(); + (0, _assert.default)(name != null, 'v3 name not specified'); + (0, _assert.default)(namespace != null, 'v3 namespace not specified'); + + if (namespace === 'URL') { + namespace = _v2.default.URL; + } + + if (namespace === 'DNS') { + namespace = _v2.default.DNS; + } + + console.log((0, _v2.default)(name, namespace)); + break; + } + + case 'v4': + console.log((0, _v3.default)()); + break; + + case 'v5': + { + const name = args.shift(); + let namespace = args.shift(); + (0, _assert.default)(name != null, 'v5 name not specified'); + (0, _assert.default)(namespace != null, 'v5 namespace not specified'); + + if (namespace === 'URL') { + namespace = _v4.default.URL; + } + + if (namespace === 'DNS') { + namespace = _v4.default.DNS; + } + + console.log((0, _v4.default)(name, namespace)); + break; + } + + default: + usage(); + process.exit(1); +} \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/v1.js b/node_modules/google-gax/node_modules/uuid/dist/v1.js new file mode 100644 index 0000000..125bc58 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/v1.js @@ -0,0 +1,107 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = require("./stringify.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || _rng.default)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || (0, _stringify.unsafeStringify)(b); +} + +var _default = v1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/v3.js b/node_modules/google-gax/node_modules/uuid/dist/v3.js new file mode 100644 index 0000000..6b47ff5 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/v3.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _md = _interopRequireDefault(require("./md5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/v35.js b/node_modules/google-gax/node_modules/uuid/dist/v35.js new file mode 100644 index 0000000..7c522d9 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/v35.js @@ -0,0 +1,80 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.URL = exports.DNS = void 0; +exports.default = v35; + +var _stringify = require("./stringify.js"); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.DNS = DNS; +const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = URL; + +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 = (0, _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)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return (0, _stringify.unsafeStringify)(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/v4.js b/node_modules/google-gax/node_modules/uuid/dist/v4.js new file mode 100644 index 0000000..959d698 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/v4.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _native = _interopRequireDefault(require("./native.js")); + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = require("./stringify.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function v4(options, buf, offset) { + if (_native.default.randomUUID && !buf && !options) { + return _native.default.randomUUID(); + } + + options = options || {}; + + const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return (0, _stringify.unsafeStringify)(rnds); +} + +var _default = v4; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/v5.js b/node_modules/google-gax/node_modules/uuid/dist/v5.js new file mode 100644 index 0000000..99d615e --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/v5.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _sha = _interopRequireDefault(require("./sha1.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/validate.js b/node_modules/google-gax/node_modules/uuid/dist/validate.js new file mode 100644 index 0000000..fd05215 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/validate.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _regex = _interopRequireDefault(require("./regex.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function validate(uuid) { + return typeof uuid === 'string' && _regex.default.test(uuid); +} + +var _default = validate; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/dist/version.js b/node_modules/google-gax/node_modules/uuid/dist/version.js new file mode 100644 index 0000000..f63af01 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/dist/version.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function version(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.slice(14, 15), 16); +} + +var _default = version; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/google-gax/node_modules/uuid/package.json b/node_modules/google-gax/node_modules/uuid/package.json new file mode 100644 index 0000000..6cc3361 --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/package.json @@ -0,0 +1,135 @@ +{ + "name": "uuid", + "version": "9.0.1", + "description": "RFC4122 (v1, v4, and v5) UUIDs", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "commitlint": { + "extends": [ + "@commitlint/config-conventional" + ] + }, + "keywords": [ + "uuid", + "guid", + "rfc4122" + ], + "license": "MIT", + "bin": { + "uuid": "./dist/bin/uuid" + }, + "sideEffects": false, + "main": "./dist/index.js", + "exports": { + ".": { + "node": { + "module": "./dist/esm-node/index.js", + "require": "./dist/index.js", + "import": "./wrapper.mjs" + }, + "browser": { + "import": "./dist/esm-browser/index.js", + "require": "./dist/commonjs-browser/index.js" + }, + "default": "./dist/esm-browser/index.js" + }, + "./package.json": "./package.json" + }, + "module": "./dist/esm-node/index.js", + "browser": { + "./dist/md5.js": "./dist/md5-browser.js", + "./dist/native.js": "./dist/native-browser.js", + "./dist/rng.js": "./dist/rng-browser.js", + "./dist/sha1.js": "./dist/sha1-browser.js", + "./dist/esm-node/index.js": "./dist/esm-browser/index.js" + }, + "files": [ + "CHANGELOG.md", + "CONTRIBUTING.md", + "LICENSE.md", + "README.md", + "dist", + "wrapper.mjs" + ], + "devDependencies": { + "@babel/cli": "7.18.10", + "@babel/core": "7.18.10", + "@babel/eslint-parser": "7.18.9", + "@babel/preset-env": "7.18.10", + "@commitlint/cli": "17.0.3", + "@commitlint/config-conventional": "17.0.3", + "bundlewatch": "0.3.3", + "eslint": "8.21.0", + "eslint-config-prettier": "8.5.0", + "eslint-config-standard": "17.0.0", + "eslint-plugin-import": "2.26.0", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-prettier": "4.2.1", + "eslint-plugin-promise": "6.0.0", + "husky": "8.0.1", + "jest": "28.1.3", + "lint-staged": "13.0.3", + "npm-run-all": "4.1.5", + "optional-dev-dependency": "2.0.1", + "prettier": "2.7.1", + "random-seed": "0.3.0", + "runmd": "1.3.9", + "standard-version": "9.5.0" + }, + "optionalDevDependencies": { + "@wdio/browserstack-service": "7.16.10", + "@wdio/cli": "7.16.10", + "@wdio/jasmine-framework": "7.16.6", + "@wdio/local-runner": "7.16.10", + "@wdio/spec-reporter": "7.16.9", + "@wdio/static-server-service": "7.16.6" + }, + "scripts": { + "examples:browser:webpack:build": "cd examples/browser-webpack && npm install && npm run build", + "examples:browser:rollup:build": "cd examples/browser-rollup && npm install && npm run build", + "examples:node:commonjs:test": "cd examples/node-commonjs && npm install && npm test", + "examples:node:esmodules:test": "cd examples/node-esmodules && npm install && npm test", + "examples:node:jest:test": "cd examples/node-jest && npm install && npm test", + "prepare": "cd $( git rev-parse --show-toplevel ) && husky install", + "lint": "npm run eslint:check && npm run prettier:check", + "eslint:check": "eslint src/ test/ examples/ *.js", + "eslint:fix": "eslint --fix src/ test/ examples/ *.js", + "pretest": "[ -n $CI ] || npm run build", + "test": "BABEL_ENV=commonjsNode node --throw-deprecation node_modules/.bin/jest test/unit/", + "pretest:browser": "optional-dev-dependency && npm run build && npm-run-all --parallel examples:browser:**", + "test:browser": "wdio run ./wdio.conf.js", + "pretest:node": "npm run build", + "test:node": "npm-run-all --parallel examples:node:**", + "test:pack": "./scripts/testpack.sh", + "pretest:benchmark": "npm run build", + "test:benchmark": "cd examples/benchmark && npm install && npm test", + "prettier:check": "prettier --check '**/*.{js,jsx,json,md}'", + "prettier:fix": "prettier --write '**/*.{js,jsx,json,md}'", + "bundlewatch": "npm run pretest:browser && bundlewatch --config bundlewatch.config.json", + "md": "runmd --watch --output=README.md README_js.md", + "docs": "( node --version | grep -q 'v18' ) && ( npm run build && npx runmd --output=README.md README_js.md )", + "docs:diff": "npm run docs && git diff --quiet README.md", + "build": "./scripts/build.sh", + "prepack": "npm run build", + "release": "standard-version --no-verify" + }, + "repository": { + "type": "git", + "url": "https://github.com/uuidjs/uuid.git" + }, + "lint-staged": { + "*.{js,jsx,json,md}": [ + "prettier --write" + ], + "*.{js,jsx}": [ + "eslint --fix" + ] + }, + "standard-version": { + "scripts": { + "postchangelog": "prettier --write CHANGELOG.md" + } + } +} diff --git a/node_modules/google-gax/node_modules/uuid/wrapper.mjs b/node_modules/google-gax/node_modules/uuid/wrapper.mjs new file mode 100644 index 0000000..c31e9ce --- /dev/null +++ b/node_modules/google-gax/node_modules/uuid/wrapper.mjs @@ -0,0 +1,10 @@ +import uuid from './dist/index.js'; +export const v1 = uuid.v1; +export const v3 = uuid.v3; +export const v4 = uuid.v4; +export const v5 = uuid.v5; +export const NIL = uuid.NIL; +export const version = uuid.version; +export const validate = uuid.validate; +export const stringify = uuid.stringify; +export const parse = uuid.parse; diff --git a/node_modules/google-gax/package.json b/node_modules/google-gax/package.json new file mode 100644 index 0000000..d91f7b8 --- /dev/null +++ b/node_modules/google-gax/package.json @@ -0,0 +1,113 @@ +{ + "name": "google-gax", + "version": "4.6.1", + "description": "Google API Extensions", + "main": "build/src/index.js", + "types": "build/src/index.d.ts", + "files": [ + "build/src", + "build/protos/", + "!build/src/**/*.map" + ], + "dependencies": { + "@grpc/grpc-js": "^1.10.9", + "@grpc/proto-loader": "^0.7.13", + "@types/long": "^4.0.0", + "abort-controller": "^3.0.0", + "duplexify": "^4.0.0", + "google-auth-library": "^9.3.0", + "node-fetch": "^2.7.0", + "object-hash": "^3.0.0", + "proto3-json-serializer": "^2.0.2", + "retry-request": "^7.0.0", + "uuid": "^9.0.1", + "protobufjs": "^7.3.2" + }, + "devDependencies": { + "@types/uuid": "^9.0.7", + "@babel/plugin-proposal-private-methods": "^7.18.6", + "@types/mocha": "^9.0.0", + "@types/ncp": "^2.0.1", + "@types/node": "^20.5.0", + "@types/node-fetch": "^2.6.11", + "@types/object-hash": "^3.0.0", + "@types/proxyquire": "^1.3.28", + "@types/pumpify": "^1.4.1", + "@types/sinon": "^17.0.0", + "@types/uglify-js": "^3.17.0", + "c8": "^9.0.0", + "cheerio": "1.0.0-rc.12", + "codecov": "^3.1.0", + "execa": "^5.0.0", + "glob": "10.4.5", + "google-proto-files": "^4.2.0", + "gts": "^5.0.0", + "jackspeak": "3.4.3", + "jsdoc": "^4.0.0", + "jsdoc-fresh": "^3.0.0", + "jsdoc-region-tag": "^3.0.0", + "linkinator": "^4.0.0", + "lru-cache": "10.4.3", + "long": "^4.0.0", + "mkdirp": "^2.0.0", + "mocha": "^9.0.0", + "ncp": "^2.0.0", + "null-loader": "^4.0.0", + "pdfmake": "0.2.12", + "protobufjs-cli": "1.1.3", + "proxyquire": "^2.0.1", + "pumpify": "^2.0.0", + "sinon": "^18.0.0", + "stream-events": "^1.0.4", + "ts-loader": "^8.0.0", + "typescript": "^5.1.6", + "uglify-js": "^3.17.0", + "walkdir": "^0.4.0", + "webpack": "^4.0.0", + "webpack-cli": "^4.0.0" + }, + "scripts": { + "docs": "jsdoc -c .jsdoc.js", + "pretest": "npm run prepare", + "test": "c8 mocha build/test/unit", + "lint": "gts check src samples test", + "clean": "gts clean", + "compile": "tsc -p . && cp src/*.json build/src && cp -r test/fixtures build/test && cp -r protos build/", + "compile-operation-protos": "pbjs -t json google/longrunning/operations.proto -p ./protos > protos/operations.json && pbjs -t static-module -r operations_protos google/longrunning/operations.proto -p ./protos > protos/operations.js && pbts protos/operations.js -o protos/operations.d.ts", + "compile-compute-operations-protos": "pbjs -t json google/longrunning/compute_operations.proto -p ./protos > protos/compute_operations.json && pbjs -t static-module -r compute_operations_protos google/longrunning/compute_operations.proto -p ./protos > protos/compute_operations.js && pbts protos/compute_operations.js -o protos/compute_operations.d.ts", + "compile-iam-protos": "pbjs -t json google/iam/v1/iam_policy.proto google/iam/v1/options.proto google/iam/v1/policy.proto google/iam/v1/logging/audit_data.proto -p ./protos > protos/iam_service.json && pbjs -t static-module -r iam_protos google/iam/v1/iam_policy.proto google/iam/v1/options.proto google/iam/v1/policy.proto google/iam/v1/logging/audit_data.proto -p ./protos > protos/iam_service.js && pbts protos/iam_service.js -o protos/iam_service.d.ts", + "compile-location-protos": "pbjs -t json google/cloud/location/locations.proto -p ./protos > protos/locations.json && pbjs -t static-module -r locations_protos google/cloud/location/locations.proto -p ./protos > protos/locations.js && pbts protos/locations.js -o protos/locations.d.ts", + "compile-status-protos": "pbjs -t json google/rpc/status.proto google/rpc/error_details.proto -p ./protos > protos/status.json", + "compile-http-protos": "pbjs -t static-module -r http_proto --keep-case google/api/http.proto -p ./protos > protos/http.js && pbts protos/http.js -o protos/http.d.ts", + "fix": "gts fix", + "prepare": "npm run compile && cd ../tools && npm i && npm run compile && cd ../gax && pwd && node ../tools/build/src/prepublish.js . && mkdirp build/protos && cp -r protos/* build/protos/ && npm run minify-proto-json", + "system-test": "c8 mocha build/test/system-test --timeout 600000 && npm run test-application", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "docs-test": "linkinator docs", + "predocs-test": "npm run docs", + "browser-test": "cd test/browser-test && npm run prefetch && npm install && npm test", + "test-application": "cd test/test-application && npm run prefetch && npm install && npm start", + "prelint": "cd samples; npm link ../; npm install", + "precompile": "gts clean", + "update-protos": "cd ../tools && npm i && npm run compile && cd ../gax && node ../tools/build/src/listProtos.js .", + "minify-proto-json": "cd ../tools && npm i && npm run compile && cd ../gax && node ../tools/build/src/minify.js" + }, + "keywords": [ + "grpc" + ], + "repository": { + "type": "git", + "url": "https://github.com/googleapis/gax-nodejs.git", + "directory": "gax" + }, + "author": "Google API Authors", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/googleapis/gax-nodejs/issues" + }, + "homepage": "https://github.com/googleapis/gax-nodejs#readme", + "engines": { + "node": ">=14" + }, + "browser": "build/src/fallback.js" +} diff --git a/node_modules/google-logging-utils/LICENSE b/node_modules/google-logging-utils/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/google-logging-utils/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/google-logging-utils/build/src/colours.d.ts b/node_modules/google-logging-utils/build/src/colours.d.ts new file mode 100644 index 0000000..ff55f9f --- /dev/null +++ b/node_modules/google-logging-utils/build/src/colours.d.ts @@ -0,0 +1,29 @@ +import * as tty from 'node:tty'; +/** + * Handles figuring out if we can use ANSI colours and handing out the escape codes. + * + * This is for package-internal use only, and may change at any time. + * + * @private + * @internal + */ +export declare class Colours { + static enabled: boolean; + static reset: string; + static bright: string; + static dim: string; + static red: string; + static green: string; + static yellow: string; + static blue: string; + static magenta: string; + static cyan: string; + static white: string; + static grey: string; + /** + * @param stream The stream (e.g. process.stderr) + * @returns true if the stream should have colourization enabled + */ + static isEnabled(stream: tty.WriteStream): boolean; + static refresh(): void; +} diff --git a/node_modules/google-logging-utils/build/src/colours.js b/node_modules/google-logging-utils/build/src/colours.js new file mode 100644 index 0000000..5132d72 --- /dev/null +++ b/node_modules/google-logging-utils/build/src/colours.js @@ -0,0 +1,80 @@ +"use strict"; +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Colours = void 0; +/** + * Handles figuring out if we can use ANSI colours and handing out the escape codes. + * + * This is for package-internal use only, and may change at any time. + * + * @private + * @internal + */ +class Colours { + /** + * @param stream The stream (e.g. process.stderr) + * @returns true if the stream should have colourization enabled + */ + static isEnabled(stream) { + return (stream.isTTY && + (typeof stream.getColorDepth === 'function' + ? stream.getColorDepth() > 2 + : true)); + } + static refresh() { + Colours.enabled = Colours.isEnabled(process.stderr); + if (!this.enabled) { + Colours.reset = ''; + Colours.bright = ''; + Colours.dim = ''; + Colours.red = ''; + Colours.green = ''; + Colours.yellow = ''; + Colours.blue = ''; + Colours.magenta = ''; + Colours.cyan = ''; + Colours.white = ''; + Colours.grey = ''; + } + else { + Colours.reset = '\u001b[0m'; + Colours.bright = '\u001b[1m'; + Colours.dim = '\u001b[2m'; + Colours.red = '\u001b[31m'; + Colours.green = '\u001b[32m'; + Colours.yellow = '\u001b[33m'; + Colours.blue = '\u001b[34m'; + Colours.magenta = '\u001b[35m'; + Colours.cyan = '\u001b[36m'; + Colours.white = '\u001b[37m'; + Colours.grey = '\u001b[90m'; + } + } +} +exports.Colours = Colours; +Colours.enabled = false; +Colours.reset = ''; +Colours.bright = ''; +Colours.dim = ''; +Colours.red = ''; +Colours.green = ''; +Colours.yellow = ''; +Colours.blue = ''; +Colours.magenta = ''; +Colours.cyan = ''; +Colours.white = ''; +Colours.grey = ''; +Colours.refresh(); +//# sourceMappingURL=colours.js.map \ No newline at end of file diff --git a/node_modules/google-logging-utils/build/src/colours.js.map b/node_modules/google-logging-utils/build/src/colours.js.map new file mode 100644 index 0000000..dbfe603 --- /dev/null +++ b/node_modules/google-logging-utils/build/src/colours.js.map @@ -0,0 +1 @@ +{"version":3,"file":"colours.js","sourceRoot":"","sources":["../../src/colours.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAUjC;;;;;;;GAOG;AACH,MAAa,OAAO;IAelB;;;OAGG;IACH,MAAM,CAAC,SAAS,CAAC,MAAuB;QACtC,OAAO,CACL,MAAM,CAAC,KAAK;YACZ,CAAC,OAAO,MAAM,CAAC,aAAa,KAAK,UAAU;gBACzC,CAAC,CAAC,MAAM,CAAC,aAAa,EAAE,GAAG,CAAC;gBAC5B,CAAC,CAAC,IAAI,CAAC,CACV,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,OAAO;QACZ,OAAO,CAAC,OAAO,GAAG,OAAO,CAAC,SAAS,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACpD,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAClB,OAAO,CAAC,KAAK,GAAG,EAAE,CAAC;YACnB,OAAO,CAAC,MAAM,GAAG,EAAE,CAAC;YACpB,OAAO,CAAC,GAAG,GAAG,EAAE,CAAC;YACjB,OAAO,CAAC,GAAG,GAAG,EAAE,CAAC;YACjB,OAAO,CAAC,KAAK,GAAG,EAAE,CAAC;YACnB,OAAO,CAAC,MAAM,GAAG,EAAE,CAAC;YACpB,OAAO,CAAC,IAAI,GAAG,EAAE,CAAC;YAClB,OAAO,CAAC,OAAO,GAAG,EAAE,CAAC;YACrB,OAAO,CAAC,IAAI,GAAG,EAAE,CAAC;YAClB,OAAO,CAAC,KAAK,GAAG,EAAE,CAAC;YACnB,OAAO,CAAC,IAAI,GAAG,EAAE,CAAC;QACpB,CAAC;aAAM,CAAC;YACN,OAAO,CAAC,KAAK,GAAG,WAAW,CAAC;YAC5B,OAAO,CAAC,MAAM,GAAG,WAAW,CAAC;YAC7B,OAAO,CAAC,GAAG,GAAG,WAAW,CAAC;YAC1B,OAAO,CAAC,GAAG,GAAG,YAAY,CAAC;YAC3B,OAAO,CAAC,KAAK,GAAG,YAAY,CAAC;YAC7B,OAAO,CAAC,MAAM,GAAG,YAAY,CAAC;YAC9B,OAAO,CAAC,IAAI,GAAG,YAAY,CAAC;YAC5B,OAAO,CAAC,OAAO,GAAG,YAAY,CAAC;YAC/B,OAAO,CAAC,IAAI,GAAG,YAAY,CAAC;YAC5B,OAAO,CAAC,KAAK,GAAG,YAAY,CAAC;YAC7B,OAAO,CAAC,IAAI,GAAG,YAAY,CAAC;QAC9B,CAAC;IACH,CAAC;;AAvDH,0BAwDC;AAvDQ,eAAO,GAAG,KAAK,CAAC;AAChB,aAAK,GAAG,EAAE,CAAC;AACX,cAAM,GAAG,EAAE,CAAC;AACZ,WAAG,GAAG,EAAE,CAAC;AAET,WAAG,GAAG,EAAE,CAAC;AACT,aAAK,GAAG,EAAE,CAAC;AACX,cAAM,GAAG,EAAE,CAAC;AACZ,YAAI,GAAG,EAAE,CAAC;AACV,eAAO,GAAG,EAAE,CAAC;AACb,YAAI,GAAG,EAAE,CAAC;AACV,aAAK,GAAG,EAAE,CAAC;AACX,YAAI,GAAG,EAAE,CAAC;AA6CnB,OAAO,CAAC,OAAO,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/google-logging-utils/build/src/index.d.ts b/node_modules/google-logging-utils/build/src/index.d.ts new file mode 100644 index 0000000..a163f85 --- /dev/null +++ b/node_modules/google-logging-utils/build/src/index.d.ts @@ -0,0 +1 @@ +export * from './logging-utils'; diff --git a/node_modules/google-logging-utils/build/src/index.js b/node_modules/google-logging-utils/build/src/index.js new file mode 100644 index 0000000..a2d5d17 --- /dev/null +++ b/node_modules/google-logging-utils/build/src/index.js @@ -0,0 +1,31 @@ +"use strict"; +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./logging-utils"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/google-logging-utils/build/src/index.js.map b/node_modules/google-logging-utils/build/src/index.js.map new file mode 100644 index 0000000..edf4a2f --- /dev/null +++ b/node_modules/google-logging-utils/build/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;;;;;;;;;;;;;;AAEjC,kDAAgC"} \ No newline at end of file diff --git a/node_modules/google-logging-utils/build/src/logging-utils.d.ts b/node_modules/google-logging-utils/build/src/logging-utils.d.ts new file mode 100644 index 0000000..e0fa8fa --- /dev/null +++ b/node_modules/google-logging-utils/build/src/logging-utils.d.ts @@ -0,0 +1,222 @@ +import { EventEmitter } from 'node:events'; +/** + * This module defines an ad-hoc debug logger for Google Cloud Platform + * client libraries in Node. An ad-hoc debug logger is a tool which lets + * users use an external, unified interface (in this case, environment + * variables) to determine what logging they want to see at runtime. This + * isn't necessarily fed into the console, but is meant to be under the + * control of the user. The kind of logging that will be produced by this + * is more like "call retry happened", not "event you'd want to record + * in Cloud Logger". + * + * More for Googlers implementing libraries with it: + * go/cloud-client-logging-design + */ +/** + * Possible log levels. These are a subset of Cloud Observability levels. + * https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity + */ +export declare enum LogSeverity { + DEFAULT = "DEFAULT", + DEBUG = "DEBUG", + INFO = "INFO", + WARNING = "WARNING", + ERROR = "ERROR" +} +/** + * A set of suggested log metadata fields. + */ +export interface LogFields { + /** + * Log level - undefined/null === DEFAULT. + */ + severity?: LogSeverity; + /** + * If this log is associated with an OpenTelemetry trace, you can put the + * trace ID here to pass on that association. + */ + telemetryTraceId?: string; + /** + * If this log is associated with an OpenTelemetry trace, you can put the + * span ID here to pass on that association. + */ + telemetrySpanId?: string; + /** + * This is a catch-all for any other items you might want to go into + * structured logs. Library implementers, please see the spec docs above + * for the items envisioned to go here. + */ + other?: unknown; +} +/** + * Adds typings for event sinks. + */ +export declare interface AdhocDebugLogger { + on(event: 'log', listener: (fields: LogFields, args: unknown[]) => void): this; + on(event: string, listener: Function): this; +} +/** + * Our logger instance. This actually contains the meat of dealing + * with log lines, including EventEmitter. This contains the function + * that will be passed back to users of the package. + */ +export declare class AdhocDebugLogger extends EventEmitter { + namespace: string; + upstream: AdhocDebugLogCallable; + func: AdhocDebugLogFunction; + /** + * @param upstream The backend will pass a function that will be + * called whenever our logger function is invoked. + */ + constructor(namespace: string, upstream: AdhocDebugLogCallable); + invoke(fields: LogFields, ...args: unknown[]): void; + invokeSeverity(severity: LogSeverity, ...args: unknown[]): void; +} +/** + * This can be used in place of a real logger while waiting for Promises or disabling logging. + */ +export declare const placeholder: AdhocDebugLogFunction; +/** + * When the user receives a log function (below), this will be the basic function + * call interface for it. + */ +export interface AdhocDebugLogCallable { + (fields: LogFields, ...args: unknown[]): void; +} +/** + * Adds typing info for the EventEmitter we're adding to the returned function. + * + * Note that this interface may change at any time, as we're reserving the + * right to add new backends at the logger level. + * + * @private + * @internal + */ +export interface AdhocDebugLogFunction extends AdhocDebugLogCallable { + instance: AdhocDebugLogger; + on(event: 'log', listener: (fields: LogFields, args: unknown[]) => void): this; + debug(...args: unknown[]): void; + info(...args: unknown[]): void; + warn(...args: unknown[]): void; + error(...args: unknown[]): void; + sublog(namespace: string): AdhocDebugLogFunction; +} +/** + * One of these can be passed to support a third-party backend, like "debug". + * We're splitting this out because ESM can complicate optional module loading. + * + * Note that this interface may change at any time, as we're reserving the + * right to add new backends at the logger level. + * + * @private + * @internal + */ +export interface DebugLogBackend { + /** + * Outputs a log to this backend. + * + * @param namespace The "system" that will be used for filtering. This may also + * include a "subsystem" in the form "system:subsystem". + * @param fields Logging fields to be included as metadata. + * @param args Any parameters to passed to a utils.format() type formatter. + */ + log(namespace: string, fields: LogFields, ...args: unknown[]): void; + /** + * Passes in the system/subsystem filters from the global environment variables. + * This lets the backend merge with any native ones. + * + * @param filters A list of wildcards matching systems or system:subsystem pairs. + */ + setFilters(filters: string[]): void; +} +/** + * The base class for debug logging backends. It's possible to use this, but the + * same non-guarantees above still apply (unstable interface, etc). + * + * @private + * @internal + */ +export declare abstract class DebugLogBackendBase implements DebugLogBackend { + cached: Map; + filters: string[]; + filtersSet: boolean; + constructor(); + /** + * Creates a callback function that we can call to send log lines out. + * + * @param namespace The system/subsystem namespace. + */ + abstract makeLogger(namespace: string): AdhocDebugLogCallable; + /** + * Provides a callback for the subclass to hook if it needs to do something + * specific with `this.filters`. + */ + abstract setFilters(): void; + log(namespace: string, fields: LogFields, ...args: unknown[]): void; +} +/** + * @returns A backend based on Node util.debuglog; this is the default. + */ +export declare function getNodeBackend(): DebugLogBackend; +type DebugPackage = any; +/** + * Creates a "debug" package backend. The user must call require('debug') and pass + * the resulting object to this function. + * + * ``` + * setBackend(getDebugBackend(require('debug'))) + * ``` + * + * https://www.npmjs.com/package/debug + * + * Note: Google does not explicitly endorse or recommend this package; it's just + * being provided as an option. + * + * @returns A backend based on the npm "debug" package. + */ +export declare function getDebugBackend(debugPkg: DebugPackage): DebugLogBackend; +/** + * Creates a "structured logging" backend. This pretty much works like the + * Node logger, but it outputs structured logging JSON matching Google + * Cloud's ingestion specs instead of plain text. + * + * ``` + * setBackend(getStructuredBackend()) + * ``` + * + * @param upstream If you want to use something besides the Node backend to + * write the actual log lines into, pass that here. + * @returns A backend based on Google Cloud structured logging. + */ +export declare function getStructuredBackend(upstream?: DebugLogBackend): DebugLogBackend; +/** + * The environment variables that we standardized on, for all ad-hoc logging. + */ +export declare const env: { + /** + * Filter wildcards specific to the Node syntax, and similar to the built-in + * utils.debuglog() environment variable. If missing, disables logging. + */ + nodeEnables: string; +}; +/** + * Set the backend to use for our log output. + * - A backend object + * - null to disable logging + * - undefined for "nothing yet", defaults to the Node backend + * + * @param backend Results from one of the get*Backend() functions. + */ +export declare function setBackend(backend: DebugLogBackend | null): void; +/** + * Creates a logging function. Multiple calls to this with the same namespace + * will produce the same logger, with the same event emitter hooks. + * + * Namespaces can be a simple string ("system" name), or a qualified string + * (system:subsystem), which can be used for filtering, or for "system:*". + * + * @param namespace The namespace, a descriptive text string. + * @returns A function you can call that works similar to console.log(). + */ +export declare function log(namespace: string, parent?: AdhocDebugLogFunction): AdhocDebugLogFunction; +export {}; diff --git a/node_modules/google-logging-utils/build/src/logging-utils.js b/node_modules/google-logging-utils/build/src/logging-utils.js new file mode 100644 index 0000000..1f205b9 --- /dev/null +++ b/node_modules/google-logging-utils/build/src/logging-utils.js @@ -0,0 +1,406 @@ +"use strict"; +// Copyright 2021-2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.env = exports.DebugLogBackendBase = exports.placeholder = exports.AdhocDebugLogger = exports.LogSeverity = void 0; +exports.getNodeBackend = getNodeBackend; +exports.getDebugBackend = getDebugBackend; +exports.getStructuredBackend = getStructuredBackend; +exports.setBackend = setBackend; +exports.log = log; +const node_events_1 = require("node:events"); +const process = __importStar(require("node:process")); +const util = __importStar(require("node:util")); +const colours_1 = require("./colours"); +// Some functions (as noted) are based on the Node standard library, from +// the following file: +// +// https://github.com/nodejs/node/blob/main/lib/internal/util/debuglog.js +/** + * This module defines an ad-hoc debug logger for Google Cloud Platform + * client libraries in Node. An ad-hoc debug logger is a tool which lets + * users use an external, unified interface (in this case, environment + * variables) to determine what logging they want to see at runtime. This + * isn't necessarily fed into the console, but is meant to be under the + * control of the user. The kind of logging that will be produced by this + * is more like "call retry happened", not "event you'd want to record + * in Cloud Logger". + * + * More for Googlers implementing libraries with it: + * go/cloud-client-logging-design + */ +/** + * Possible log levels. These are a subset of Cloud Observability levels. + * https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity + */ +var LogSeverity; +(function (LogSeverity) { + LogSeverity["DEFAULT"] = "DEFAULT"; + LogSeverity["DEBUG"] = "DEBUG"; + LogSeverity["INFO"] = "INFO"; + LogSeverity["WARNING"] = "WARNING"; + LogSeverity["ERROR"] = "ERROR"; +})(LogSeverity || (exports.LogSeverity = LogSeverity = {})); +/** + * Our logger instance. This actually contains the meat of dealing + * with log lines, including EventEmitter. This contains the function + * that will be passed back to users of the package. + */ +class AdhocDebugLogger extends node_events_1.EventEmitter { + /** + * @param upstream The backend will pass a function that will be + * called whenever our logger function is invoked. + */ + constructor(namespace, upstream) { + super(); + this.namespace = namespace; + this.upstream = upstream; + this.func = Object.assign(this.invoke.bind(this), { + // Also add an instance pointer back to us. + instance: this, + // And pull over the EventEmitter functionality. + on: (event, listener) => this.on(event, listener), + }); + // Convenience methods for log levels. + this.func.debug = (...args) => this.invokeSeverity(LogSeverity.DEBUG, ...args); + this.func.info = (...args) => this.invokeSeverity(LogSeverity.INFO, ...args); + this.func.warn = (...args) => this.invokeSeverity(LogSeverity.WARNING, ...args); + this.func.error = (...args) => this.invokeSeverity(LogSeverity.ERROR, ...args); + this.func.sublog = (namespace) => log(namespace, this.func); + } + invoke(fields, ...args) { + // Push out any upstream logger first. + if (this.upstream) { + this.upstream(fields, ...args); + } + // Emit sink events. + this.emit('log', fields, args); + } + invokeSeverity(severity, ...args) { + this.invoke({ severity }, ...args); + } +} +exports.AdhocDebugLogger = AdhocDebugLogger; +/** + * This can be used in place of a real logger while waiting for Promises or disabling logging. + */ +exports.placeholder = new AdhocDebugLogger('', () => { }).func; +/** + * The base class for debug logging backends. It's possible to use this, but the + * same non-guarantees above still apply (unstable interface, etc). + * + * @private + * @internal + */ +class DebugLogBackendBase { + constructor() { + var _a; + this.cached = new Map(); + this.filters = []; + this.filtersSet = false; + // Look for the Node config variable for what systems to enable. We'll store + // these for the log method below, which will call setFilters() once. + let nodeFlag = (_a = process.env[exports.env.nodeEnables]) !== null && _a !== void 0 ? _a : '*'; + if (nodeFlag === 'all') { + nodeFlag = '*'; + } + this.filters = nodeFlag.split(','); + } + log(namespace, fields, ...args) { + try { + if (!this.filtersSet) { + this.setFilters(); + this.filtersSet = true; + } + let logger = this.cached.get(namespace); + if (!logger) { + logger = this.makeLogger(namespace); + this.cached.set(namespace, logger); + } + logger(fields, ...args); + } + catch (e) { + // Silently ignore all errors; we don't want them to interfere with + // the user's running app. + // e; + console.error(e); + } + } +} +exports.DebugLogBackendBase = DebugLogBackendBase; +// The basic backend. This one definitely works, but it's less feature-filled. +// +// Rather than using util.debuglog, this implements the same basic logic directly. +// The reason for this decision is that debuglog checks the value of the +// NODE_DEBUG environment variable before any user code runs; we therefore +// can't pipe our own enables into it (and util.debuglog will never print unless +// the user duplicates it into NODE_DEBUG, which isn't reasonable). +// +class NodeBackend extends DebugLogBackendBase { + constructor() { + super(...arguments); + // Default to allowing all systems, since we gate earlier based on whether the + // variable is empty. + this.enabledRegexp = /.*/g; + } + isEnabled(namespace) { + return this.enabledRegexp.test(namespace); + } + makeLogger(namespace) { + if (!this.enabledRegexp.test(namespace)) { + return () => { }; + } + return (fields, ...args) => { + var _a; + // TODO: `fields` needs to be turned into a string here, one way or another. + const nscolour = `${colours_1.Colours.green}${namespace}${colours_1.Colours.reset}`; + const pid = `${colours_1.Colours.yellow}${process.pid}${colours_1.Colours.reset}`; + let level; + switch (fields.severity) { + case LogSeverity.ERROR: + level = `${colours_1.Colours.red}${fields.severity}${colours_1.Colours.reset}`; + break; + case LogSeverity.INFO: + level = `${colours_1.Colours.magenta}${fields.severity}${colours_1.Colours.reset}`; + break; + case LogSeverity.WARNING: + level = `${colours_1.Colours.yellow}${fields.severity}${colours_1.Colours.reset}`; + break; + default: + level = (_a = fields.severity) !== null && _a !== void 0 ? _a : LogSeverity.DEFAULT; + break; + } + const msg = util.formatWithOptions({ colors: colours_1.Colours.enabled }, ...args); + const filteredFields = Object.assign({}, fields); + delete filteredFields.severity; + const fieldsJson = Object.getOwnPropertyNames(filteredFields).length + ? JSON.stringify(filteredFields) + : ''; + const fieldsColour = fieldsJson + ? `${colours_1.Colours.grey}${fieldsJson}${colours_1.Colours.reset}` + : ''; + console.error('%s [%s|%s] %s%s', pid, nscolour, level, msg, fieldsJson ? ` ${fieldsColour}` : ''); + }; + } + // Regexp patterns below are from here: + // https://github.com/nodejs/node/blob/c0aebed4b3395bd65d54b18d1fd00f071002ac20/lib/internal/util/debuglog.js#L36 + setFilters() { + const totalFilters = this.filters.join(','); + const regexp = totalFilters + .replace(/[|\\{}()[\]^$+?.]/g, '\\$&') + .replace(/\*/g, '.*') + .replace(/,/g, '$|^'); + this.enabledRegexp = new RegExp(`^${regexp}$`, 'i'); + } +} +/** + * @returns A backend based on Node util.debuglog; this is the default. + */ +function getNodeBackend() { + return new NodeBackend(); +} +class DebugBackend extends DebugLogBackendBase { + constructor(pkg) { + super(); + this.debugPkg = pkg; + } + makeLogger(namespace) { + const debugLogger = this.debugPkg(namespace); + return (fields, ...args) => { + // TODO: `fields` needs to be turned into a string here. + debugLogger(args[0], ...args.slice(1)); + }; + } + setFilters() { + var _a; + const existingFilters = (_a = process.env['NODE_DEBUG']) !== null && _a !== void 0 ? _a : ''; + process.env['NODE_DEBUG'] = `${existingFilters}${existingFilters ? ',' : ''}${this.filters.join(',')}`; + } +} +/** + * Creates a "debug" package backend. The user must call require('debug') and pass + * the resulting object to this function. + * + * ``` + * setBackend(getDebugBackend(require('debug'))) + * ``` + * + * https://www.npmjs.com/package/debug + * + * Note: Google does not explicitly endorse or recommend this package; it's just + * being provided as an option. + * + * @returns A backend based on the npm "debug" package. + */ +function getDebugBackend(debugPkg) { + return new DebugBackend(debugPkg); +} +/** + * This pretty much works like the Node logger, but it outputs structured + * logging JSON matching Google Cloud's ingestion specs. Rather than handling + * its own output, it wraps another backend. The passed backend must be a subclass + * of `DebugLogBackendBase` (any of the backends exposed by this package will work). + */ +class StructuredBackend extends DebugLogBackendBase { + constructor(upstream) { + var _a; + super(); + this.upstream = (_a = upstream) !== null && _a !== void 0 ? _a : new NodeBackend(); + } + makeLogger(namespace) { + const debugLogger = this.upstream.makeLogger(namespace); + return (fields, ...args) => { + var _a; + const severity = (_a = fields.severity) !== null && _a !== void 0 ? _a : LogSeverity.INFO; + const json = Object.assign({ + severity, + message: util.format(...args), + }, fields); + const jsonString = JSON.stringify(json); + debugLogger(fields, jsonString); + }; + } + setFilters() { + this.upstream.setFilters(); + } +} +/** + * Creates a "structured logging" backend. This pretty much works like the + * Node logger, but it outputs structured logging JSON matching Google + * Cloud's ingestion specs instead of plain text. + * + * ``` + * setBackend(getStructuredBackend()) + * ``` + * + * @param upstream If you want to use something besides the Node backend to + * write the actual log lines into, pass that here. + * @returns A backend based on Google Cloud structured logging. + */ +function getStructuredBackend(upstream) { + return new StructuredBackend(upstream); +} +/** + * The environment variables that we standardized on, for all ad-hoc logging. + */ +exports.env = { + /** + * Filter wildcards specific to the Node syntax, and similar to the built-in + * utils.debuglog() environment variable. If missing, disables logging. + */ + nodeEnables: 'GOOGLE_SDK_NODE_LOGGING', +}; +// Keep a copy of all namespaced loggers so users can reliably .on() them. +// Note that these cached functions will need to deal with changes in the backend. +const loggerCache = new Map(); +// Our current global backend. This might be: +let cachedBackend = undefined; +/** + * Set the backend to use for our log output. + * - A backend object + * - null to disable logging + * - undefined for "nothing yet", defaults to the Node backend + * + * @param backend Results from one of the get*Backend() functions. + */ +function setBackend(backend) { + cachedBackend = backend; + loggerCache.clear(); +} +/** + * Creates a logging function. Multiple calls to this with the same namespace + * will produce the same logger, with the same event emitter hooks. + * + * Namespaces can be a simple string ("system" name), or a qualified string + * (system:subsystem), which can be used for filtering, or for "system:*". + * + * @param namespace The namespace, a descriptive text string. + * @returns A function you can call that works similar to console.log(). + */ +function log(namespace, parent) { + // If the enable flag isn't set, do nothing. + const enablesFlag = process.env[exports.env.nodeEnables]; + if (!enablesFlag) { + return exports.placeholder; + } + // This might happen mostly if the typings are dropped in a user's code, + // or if they're calling from JavaScript. + if (!namespace) { + return exports.placeholder; + } + // Handle sub-loggers. + if (parent) { + namespace = `${parent.instance.namespace}:${namespace}`; + } + // Reuse loggers so things like event sinks are persistent. + const existing = loggerCache.get(namespace); + if (existing) { + return existing.func; + } + // Do we have a backend yet? + if (cachedBackend === null) { + // Explicitly disabled. + return exports.placeholder; + } + else if (cachedBackend === undefined) { + // One hasn't been made yet, so default to Node. + cachedBackend = getNodeBackend(); + } + // The logger is further wrapped so we can handle the backend changing out. + const logger = (() => { + let previousBackend = undefined; + const newLogger = new AdhocDebugLogger(namespace, (fields, ...args) => { + if (previousBackend !== cachedBackend) { + // Did the user pass a custom backend? + if (cachedBackend === null) { + // Explicitly disabled. + return; + } + else if (cachedBackend === undefined) { + // One hasn't been made yet, so default to Node. + cachedBackend = getNodeBackend(); + } + previousBackend = cachedBackend; + } + cachedBackend === null || cachedBackend === void 0 ? void 0 : cachedBackend.log(namespace, fields, ...args); + }); + return newLogger; + })(); + loggerCache.set(namespace, logger); + return logger.func; +} +//# sourceMappingURL=logging-utils.js.map \ No newline at end of file diff --git a/node_modules/google-logging-utils/build/src/logging-utils.js.map b/node_modules/google-logging-utils/build/src/logging-utils.js.map new file mode 100644 index 0000000..8e3011d --- /dev/null +++ b/node_modules/google-logging-utils/build/src/logging-utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"logging-utils.js","sourceRoot":"","sources":["../../src/logging-utils.ts"],"names":[],"mappings":";AAAA,iCAAiC;AACjC,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,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/google-logging-utils/build/src/temporal.d.ts b/node_modules/google-logging-utils/build/src/temporal.d.ts new file mode 100644 index 0000000..82da9ab --- /dev/null +++ b/node_modules/google-logging-utils/build/src/temporal.d.ts @@ -0,0 +1,45 @@ +/** + * Simplified interface analogous to the tc39 Temporal.Duration + * parameter to from(). This doesn't support the full gamut (years, days). + */ +export interface DurationLike { + hours?: number; + minutes?: number; + seconds?: number; + millis?: number; +} +/** + * Simplified list of values to pass to Duration.totalOf(). This + * list is taken from the tc39 Temporal.Duration proposal, but + * larger and smaller units have been left off. + */ +export type TotalOfUnit = 'hour' | 'minute' | 'second' | 'millisecond'; +/** + * Duration class with an interface similar to the tc39 Temporal + * proposal. Since it's not fully finalized, and polyfills have + * inconsistent compatibility, for now this shim class will be + * used to set durations in Pub/Sub. + * + * This class will remain here for at least the next major version, + * eventually to be replaced by the tc39 Temporal built-in. + * + * https://tc39.es/proposal-temporal/docs/duration.html + */ +export declare class Duration { + private millis; + private static secondInMillis; + private static minuteInMillis; + private static hourInMillis; + private constructor(); + /** + * Calculates the total number of units of type 'totalOf' that would + * fit inside this duration. + */ + totalOf(totalOf: TotalOfUnit): number; + /** + * Creates a Duration from a DurationLike, which is an object + * containing zero or more of the following: hours, seconds, + * minutes, millis. + */ + static from(durationLike: DurationLike): Duration; +} diff --git a/node_modules/google-logging-utils/build/src/temporal.js b/node_modules/google-logging-utils/build/src/temporal.js new file mode 100644 index 0000000..fa59c24 --- /dev/null +++ b/node_modules/google-logging-utils/build/src/temporal.js @@ -0,0 +1,68 @@ +"use strict"; +// Copyright 2022-2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Duration = void 0; +/** + * Duration class with an interface similar to the tc39 Temporal + * proposal. Since it's not fully finalized, and polyfills have + * inconsistent compatibility, for now this shim class will be + * used to set durations in Pub/Sub. + * + * This class will remain here for at least the next major version, + * eventually to be replaced by the tc39 Temporal built-in. + * + * https://tc39.es/proposal-temporal/docs/duration.html + */ +class Duration { + constructor(millis) { + this.millis = millis; + } + /** + * Calculates the total number of units of type 'totalOf' that would + * fit inside this duration. + */ + totalOf(totalOf) { + switch (totalOf) { + case 'hour': + return this.millis / Duration.hourInMillis; + case 'minute': + return this.millis / Duration.minuteInMillis; + case 'second': + return this.millis / Duration.secondInMillis; + case 'millisecond': + return this.millis; + default: + throw new Error(`Invalid unit in call to totalOf(): ${totalOf}`); + } + } + /** + * Creates a Duration from a DurationLike, which is an object + * containing zero or more of the following: hours, seconds, + * minutes, millis. + */ + static from(durationLike) { + var _a, _b, _c, _d; + let millis = (_a = durationLike.millis) !== null && _a !== void 0 ? _a : 0; + millis += ((_b = durationLike.seconds) !== null && _b !== void 0 ? _b : 0) * Duration.secondInMillis; + millis += ((_c = durationLike.minutes) !== null && _c !== void 0 ? _c : 0) * Duration.minuteInMillis; + millis += ((_d = durationLike.hours) !== null && _d !== void 0 ? _d : 0) * Duration.hourInMillis; + return new Duration(millis); + } +} +exports.Duration = Duration; +Duration.secondInMillis = 1000; +Duration.minuteInMillis = Duration.secondInMillis * 60; +Duration.hourInMillis = Duration.minuteInMillis * 60; +//# sourceMappingURL=temporal.js.map \ No newline at end of file diff --git a/node_modules/google-logging-utils/build/src/temporal.js.map b/node_modules/google-logging-utils/build/src/temporal.js.map new file mode 100644 index 0000000..c38c446 --- /dev/null +++ b/node_modules/google-logging-utils/build/src/temporal.js.map @@ -0,0 +1 @@ +{"version":3,"file":"temporal.js","sourceRoot":"","sources":["../../src/temporal.ts"],"names":[],"mappings":";AAAA,iCAAiC;AACjC,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;A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,GAAG,QAAQ,CAAC,cAAc,GAAG,EAAE,CAAC;AAC9C,qBAAY,GAAG,QAAQ,CAAC,cAAc,GAAG,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/google-logging-utils/package.json b/node_modules/google-logging-utils/package.json new file mode 100644 index 0000000..7ffe48d --- /dev/null +++ b/node_modules/google-logging-utils/package.json @@ -0,0 +1,39 @@ +{ + "name": "google-logging-utils", + "version": "0.0.2", + "description": "An ad-hoc debug logger package for other libraries", + "main": "build/src/index.js", + "files": [ + "build/src" + ], + "scripts": { + "pretest": "npm run prepare", + "test": "c8 mocha build/test", + "lint": "gts check test src samples", + "clean": "gts clean", + "compile": "tsc -p . && cp -r test/fixtures build/test", + "fix": "gts fix", + "prepare": "npm run compile", + "precompile": "gts clean", + "samples-test": "echo no samples 🙀", + "system-test": "echo no system tests 🙀" + }, + "author": "Google API Authors", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "https://github.com/googleapis/gax-nodejs.git", + "directory": "logging-utils" + }, + "devDependencies": { + "@types/mocha": "^10.0.10", + "@types/node": "^22.9.1", + "c8": "^9.0.0", + "gts": "^5.0.0", + "mocha": "^9.0.0", + "typescript": "^5.1.6" + }, + "engines": { + "node": ">=14" + } +} diff --git a/node_modules/gopd/.eslintrc b/node_modules/gopd/.eslintrc new file mode 100644 index 0000000..e2550c0 --- /dev/null +++ b/node_modules/gopd/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-style": [2, "declaration"], + "id-length": 0, + "multiline-comment-style": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/node_modules/gopd/.github/FUNDING.yml b/node_modules/gopd/.github/FUNDING.yml new file mode 100644 index 0000000..94a44a8 --- /dev/null +++ b/node_modules/gopd/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/gopd +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/gopd/CHANGELOG.md b/node_modules/gopd/CHANGELOG.md new file mode 100644 index 0000000..87f5727 --- /dev/null +++ b/node_modules/gopd/CHANGELOG.md @@ -0,0 +1,45 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.2.0](https://github.com/ljharb/gopd/compare/v1.1.0...v1.2.0) - 2024-12-03 + +### Commits + +- [New] add `gOPD` entry point; remove `get-intrinsic` [`5b61232`](https://github.com/ljharb/gopd/commit/5b61232dedea4591a314bcf16101b1961cee024e) + +## [v1.1.0](https://github.com/ljharb/gopd/compare/v1.0.1...v1.1.0) - 2024-11-29 + +### Commits + +- [New] add types [`f585e39`](https://github.com/ljharb/gopd/commit/f585e397886d270e4ba84e53d226e4f9ca2eb0e6) +- [Dev Deps] update `@ljharb/eslint-config`, `auto-changelog`, `tape` [`0b8e4fd`](https://github.com/ljharb/gopd/commit/0b8e4fded64397a7726a9daa144a6cc9a5e2edfa) +- [Dev Deps] update `aud`, `npmignore`, `tape` [`48378b2`](https://github.com/ljharb/gopd/commit/48378b2443f09a4f7efbd0fb6c3ee845a6cabcf3) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`78099ee`](https://github.com/ljharb/gopd/commit/78099eeed41bfdc134c912280483689cc8861c31) +- [Tests] replace `aud` with `npm audit` [`4e0d0ac`](https://github.com/ljharb/gopd/commit/4e0d0ac47619d24a75318a8e1f543ee04b2a2632) +- [meta] add missing `engines.node` [`1443316`](https://github.com/ljharb/gopd/commit/14433165d07835c680155b3dfd62d9217d735eca) +- [Deps] update `get-intrinsic` [`eee5f51`](https://github.com/ljharb/gopd/commit/eee5f51769f3dbaf578b70e2a3199116b01aa670) +- [Deps] update `get-intrinsic` [`550c378`](https://github.com/ljharb/gopd/commit/550c3780e3a9c77b62565712a001b4ed64ea61f5) +- [Dev Deps] add missing peer dep [`8c2ecf8`](https://github.com/ljharb/gopd/commit/8c2ecf848122e4e30abfc5b5086fb48b390dce75) + +## [v1.0.1](https://github.com/ljharb/gopd/compare/v1.0.0...v1.0.1) - 2022-11-01 + +### Commits + +- [Fix] actually export gOPD instead of dP [`4b624bf`](https://github.com/ljharb/gopd/commit/4b624bfbeff788c5e3ff16d9443a83627847234f) + +## v1.0.0 - 2022-11-01 + +### Commits + +- Initial implementation, tests, readme [`0911e01`](https://github.com/ljharb/gopd/commit/0911e012cd642092bd88b732c161c58bf4f20bea) +- Initial commit [`b84e33f`](https://github.com/ljharb/gopd/commit/b84e33f5808a805ac57ff88d4247ad935569acbe) +- [actions] add reusable workflows [`12ae28a`](https://github.com/ljharb/gopd/commit/12ae28ae5f50f86e750215b6e2188901646d0119) +- npm init [`280118b`](https://github.com/ljharb/gopd/commit/280118badb45c80b4483836b5cb5315bddf6e582) +- [meta] add `auto-changelog` [`bb78de5`](https://github.com/ljharb/gopd/commit/bb78de5639a180747fb290c28912beaaf1615709) +- [meta] create FUNDING.yml; add `funding` in package.json [`11c22e6`](https://github.com/ljharb/gopd/commit/11c22e6355bb01f24e7fac4c9bb3055eb5b25002) +- [meta] use `npmignore` to autogenerate an npmignore file [`4f4537a`](https://github.com/ljharb/gopd/commit/4f4537a843b39f698c52f072845092e6fca345bb) +- Only apps should have lockfiles [`c567022`](https://github.com/ljharb/gopd/commit/c567022a18573aa7951cf5399445d9840e23e98b) diff --git a/node_modules/gopd/LICENSE b/node_modules/gopd/LICENSE new file mode 100644 index 0000000..6abfe14 --- /dev/null +++ b/node_modules/gopd/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/gopd/README.md b/node_modules/gopd/README.md new file mode 100644 index 0000000..784e56a --- /dev/null +++ b/node_modules/gopd/README.md @@ -0,0 +1,40 @@ +# gopd [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +`Object.getOwnPropertyDescriptor`, but accounts for IE's broken implementation. + +## Usage + +```javascript +var gOPD = require('gopd'); +var assert = require('assert'); + +if (gOPD) { + assert.equal(typeof gOPD, 'function', 'descriptors supported'); + // use gOPD like Object.getOwnPropertyDescriptor here +} else { + assert.ok(!gOPD, 'descriptors not supported'); +} +``` + +[package-url]: https://npmjs.org/package/gopd +[npm-version-svg]: https://versionbadg.es/ljharb/gopd.svg +[deps-svg]: https://david-dm.org/ljharb/gopd.svg +[deps-url]: https://david-dm.org/ljharb/gopd +[dev-deps-svg]: https://david-dm.org/ljharb/gopd/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/gopd#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/gopd.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/gopd.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/gopd.svg +[downloads-url]: https://npm-stat.com/charts.html?package=gopd +[codecov-image]: https://codecov.io/gh/ljharb/gopd/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/gopd/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/gopd +[actions-url]: https://github.com/ljharb/gopd/actions diff --git a/node_modules/gopd/gOPD.d.ts b/node_modules/gopd/gOPD.d.ts new file mode 100644 index 0000000..def48a3 --- /dev/null +++ b/node_modules/gopd/gOPD.d.ts @@ -0,0 +1 @@ +export = Object.getOwnPropertyDescriptor; diff --git a/node_modules/gopd/gOPD.js b/node_modules/gopd/gOPD.js new file mode 100644 index 0000000..cf9616c --- /dev/null +++ b/node_modules/gopd/gOPD.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./gOPD')} */ +module.exports = Object.getOwnPropertyDescriptor; diff --git a/node_modules/gopd/index.d.ts b/node_modules/gopd/index.d.ts new file mode 100644 index 0000000..e228065 --- /dev/null +++ b/node_modules/gopd/index.d.ts @@ -0,0 +1,5 @@ +declare function gOPD(obj: O, prop: K): PropertyDescriptor | undefined; + +declare const fn: typeof gOPD | undefined | null; + +export = fn; \ No newline at end of file diff --git a/node_modules/gopd/index.js b/node_modules/gopd/index.js new file mode 100644 index 0000000..a4081b0 --- /dev/null +++ b/node_modules/gopd/index.js @@ -0,0 +1,15 @@ +'use strict'; + +/** @type {import('.')} */ +var $gOPD = require('./gOPD'); + +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } +} + +module.exports = $gOPD; diff --git a/node_modules/gopd/package.json b/node_modules/gopd/package.json new file mode 100644 index 0000000..01c5ffa --- /dev/null +++ b/node_modules/gopd/package.json @@ -0,0 +1,77 @@ +{ + "name": "gopd", + "version": "1.2.0", + "description": "`Object.getOwnPropertyDescriptor`, but accounts for IE's broken implementation.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./gOPD": "./gOPD.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "tsc -p . && attw -P", + "lint": "eslint --ext=js,mjs .", + "postlint": "evalmd README.md", + "pretest": "npm run lint", + "tests-only": "tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/gopd.git" + }, + "keywords": [ + "ecmascript", + "javascript", + "getownpropertydescriptor", + "property", + "descriptor" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/gopd/issues" + }, + "homepage": "https://github.com/ljharb/gopd#readme", + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.0", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.0", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/gopd/test/index.js b/node_modules/gopd/test/index.js new file mode 100644 index 0000000..6f43453 --- /dev/null +++ b/node_modules/gopd/test/index.js @@ -0,0 +1,36 @@ +'use strict'; + +var test = require('tape'); +var gOPD = require('../'); + +test('gOPD', function (t) { + t.test('supported', { skip: !gOPD }, function (st) { + st.equal(typeof gOPD, 'function', 'is a function'); + + var obj = { x: 1 }; + st.ok('x' in obj, 'property exists'); + + // @ts-expect-error TS can't figure out narrowing from `skip` + var desc = gOPD(obj, 'x'); + st.deepEqual( + desc, + { + configurable: true, + enumerable: true, + value: 1, + writable: true + }, + 'descriptor is as expected' + ); + + st.end(); + }); + + t.test('not supported', { skip: !!gOPD }, function (st) { + st.notOk(gOPD, 'is falsy'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/gopd/tsconfig.json b/node_modules/gopd/tsconfig.json new file mode 100644 index 0000000..d9a6668 --- /dev/null +++ b/node_modules/gopd/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/gtoken/CHANGELOG.md b/node_modules/gtoken/CHANGELOG.md new file mode 100644 index 0000000..6b5ccce --- /dev/null +++ b/node_modules/gtoken/CHANGELOG.md @@ -0,0 +1,372 @@ +# Changelog + +[npm history][1] + +[1]: https://www.npmjs.com/package/gtoken?activeTab=versions + +## [7.1.0](https://github.com/googleapis/node-gtoken/compare/v7.0.1...v7.1.0) (2024-02-01) + + +### Features + +* Enable Token Retries ([#481](https://github.com/googleapis/node-gtoken/issues/481)) ([ed9f91e](https://github.com/googleapis/node-gtoken/commit/ed9f91e4764744426de95fd2510b68ee53677514)) + +## [7.0.1](https://github.com/googleapis/node-gtoken/compare/v7.0.0...v7.0.1) (2023-07-12) + + +### Bug Fixes + +* **deps:** Update gaxios to 6.0.0 ([#462](https://github.com/googleapis/node-gtoken/issues/462)) ([c05a2b3](https://github.com/googleapis/node-gtoken/commit/c05a2b35d1bb369fc54f80784d9361c0d6cbc2e7)) + +## [7.0.0](https://github.com/googleapis/node-gtoken/compare/v6.1.2...v7.0.0) (2023-07-11) + + +### ⚠ BREAKING CHANGES + +* move to node 14 as minimum version ([#457](https://github.com/googleapis/node-gtoken/issues/457)) +* remove support for conversion of *.p12 to *.pem ([#452](https://github.com/googleapis/node-gtoken/issues/452)) + +### Features + +* Remove support for conversion of *.p12 to *.pem ([#452](https://github.com/googleapis/node-gtoken/issues/452)) ([522a96d](https://github.com/googleapis/node-gtoken/commit/522a96dd38ad5d486e9337f72efdf1a5523fded4)) + + +### Miscellaneous Chores + +* Move to node 14 as minimum version ([#457](https://github.com/googleapis/node-gtoken/issues/457)) ([429df81](https://github.com/googleapis/node-gtoken/commit/429df814cd4224d5eacce72cfe8e924e53cc7f30)) + +## [6.1.2](https://github.com/googleapis/node-gtoken/compare/v6.1.1...v6.1.2) (2022-08-23) + + +### Bug Fixes + +* remove pip install statements ([#1546](https://github.com/googleapis/node-gtoken/issues/1546)) ([#440](https://github.com/googleapis/node-gtoken/issues/440)) ([6fb8562](https://github.com/googleapis/node-gtoken/commit/6fb856207b07112096c033adb6d3f0edf5e5093d)) + +## [6.1.1](https://github.com/googleapis/node-gtoken/compare/v6.1.0...v6.1.1) (2022-08-04) + + +### Bug Fixes + +* **deps:** update gaxios to 5.0.1 ([#436](https://github.com/googleapis/node-gtoken/issues/436)) ([0d5d0e9](https://github.com/googleapis/node-gtoken/commit/0d5d0e9c6ec51911f1e44d97c02dc0cd791c7d05)) + +## [6.1.0](https://github.com/googleapis/node-gtoken/compare/v6.0.1...v6.1.0) (2022-06-28) + + +### Features + +* allow customizing the http client ([#426](https://github.com/googleapis/node-gtoken/issues/426)) ([408ad04](https://github.com/googleapis/node-gtoken/commit/408ad048a2595313717bf427fc34aa29a6e7fb3c)) + +## [6.0.1](https://github.com/googleapis/node-gtoken/compare/v6.0.0...v6.0.1) (2022-06-07) + + +### Bug Fixes + +* **deps:** update dependency google-p12-pem to v4 ([#430](https://github.com/googleapis/node-gtoken/issues/430)) ([bd0848b](https://github.com/googleapis/node-gtoken/commit/bd0848b15554742e2fd73b05073bd84e1aec2a3f)) + +## [6.0.0](https://github.com/googleapis/node-gtoken/compare/v5.3.2...v6.0.0) (2022-05-10) + + +### ⚠ BREAKING CHANGES + +* update library to use Node 12 (#428) + +### Build System + +* update library to use Node 12 ([#428](https://github.com/googleapis/node-gtoken/issues/428)) ([288b662](https://github.com/googleapis/node-gtoken/commit/288b662d990ce53a6824ddc67c384253487fdc04)) + +### [5.3.2](https://github.com/googleapis/node-gtoken/compare/v5.3.1...v5.3.2) (2022-01-28) + + +### Bug Fixes + +* upgrade google-p12-pem to 3.1.3 ([#413](https://github.com/googleapis/node-gtoken/issues/413)) ([c3cebaf](https://github.com/googleapis/node-gtoken/commit/c3cebaf620c62f57385804fe5d852ce3e6398dc1)) + +### [5.3.1](https://www.github.com/googleapis/node-gtoken/compare/v5.3.0...v5.3.1) (2021-08-11) + + +### Bug Fixes + +* **build:** migrate to using main branch ([#392](https://www.github.com/googleapis/node-gtoken/issues/392)) ([992e3c5](https://www.github.com/googleapis/node-gtoken/commit/992e3c5e1520a376269b2476e5ce225f6ee96e2b)) + +## [5.3.0](https://www.github.com/googleapis/node-gtoken/compare/v5.2.1...v5.3.0) (2021-06-10) + + +### Features + +* add `gcf-owl-bot[bot]` to `ignoreAuthors` ([#369](https://www.github.com/googleapis/node-gtoken/issues/369)) ([3142215](https://www.github.com/googleapis/node-gtoken/commit/3142215277ae2daa33f7fb3300f09ef438ded01f)) + +### [5.2.1](https://www.github.com/googleapis/node-gtoken/compare/v5.2.0...v5.2.1) (2021-01-26) + + +### Bug Fixes + +* **deps:** remove dependency on mime ([#357](https://www.github.com/googleapis/node-gtoken/issues/357)) ([0a1e6b3](https://www.github.com/googleapis/node-gtoken/commit/0a1e6b32206364106631c0ca8cdd2e325de2af32)) + +## [5.2.0](https://www.github.com/googleapis/node-gtoken/compare/v5.1.0...v5.2.0) (2021-01-14) + + +### Features + +* request new tokens before they expire ([#349](https://www.github.com/googleapis/node-gtoken/issues/349)) ([e84d9a3](https://www.github.com/googleapis/node-gtoken/commit/e84d9a31517c1449141708a0a2cddd9d0129fa95)) + +## [5.1.0](https://www.github.com/googleapis/node-gtoken/compare/v5.0.5...v5.1.0) (2020-11-14) + + +### Features + +* dedupe concurrent requests ([#351](https://www.github.com/googleapis/node-gtoken/issues/351)) ([9001f1d](https://www.github.com/googleapis/node-gtoken/commit/9001f1d00931f480d40fa323c9b527beaef2254a)) + +### [5.0.5](https://www.github.com/googleapis/node-gtoken/compare/v5.0.4...v5.0.5) (2020-10-22) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v4 ([#342](https://www.github.com/googleapis/node-gtoken/issues/342)) ([7954a19](https://www.github.com/googleapis/node-gtoken/commit/7954a197e923469b031f0833a2016fa0378285b1)) + +### [5.0.4](https://www.github.com/googleapis/node-gtoken/compare/v5.0.3...v5.0.4) (2020-10-06) + + +### Bug Fixes + +* **deps:** upgrade google-p12-pem ([#337](https://www.github.com/googleapis/node-gtoken/issues/337)) ([77a749d](https://www.github.com/googleapis/node-gtoken/commit/77a749d646c7ccc68e974f27827a9d538dfea784)) + +### [5.0.3](https://www.github.com/googleapis/node-gtoken/compare/v5.0.2...v5.0.3) (2020-07-27) + + +### Bug Fixes + +* move gitattributes files to node templates ([#322](https://www.github.com/googleapis/node-gtoken/issues/322)) ([1d1786b](https://www.github.com/googleapis/node-gtoken/commit/1d1786b8915cd9a33577237ec6a6148a29e11a88)) + +### [5.0.2](https://www.github.com/googleapis/node-gtoken/compare/v5.0.1...v5.0.2) (2020-07-09) + + +### Bug Fixes + +* typeo in nodejs .gitattribute ([#311](https://www.github.com/googleapis/node-gtoken/issues/311)) ([8e17b4c](https://www.github.com/googleapis/node-gtoken/commit/8e17b4c0757832b2d31178684a6b24e1759d9f76)) + +### [5.0.1](https://www.github.com/googleapis/node-gtoken/compare/v5.0.0...v5.0.1) (2020-04-13) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v3 ([#287](https://www.github.com/googleapis/node-gtoken/issues/287)) ([033731e](https://www.github.com/googleapis/node-gtoken/commit/033731e128fef0034b07b13183044e5060809418)) +* **deps:** update dependency google-p12-pem to v3 ([#280](https://www.github.com/googleapis/node-gtoken/issues/280)) ([25121b0](https://www.github.com/googleapis/node-gtoken/commit/25121b00cc9a4d32854f36ea8bc4bbd2cb77afbb)) +* apache license URL ([#468](https://www.github.com/googleapis/node-gtoken/issues/468)) ([#293](https://www.github.com/googleapis/node-gtoken/issues/293)) ([14a5bcd](https://www.github.com/googleapis/node-gtoken/commit/14a5bcd52d7b18d787c620451471e904784222d9)) + +## [5.0.0](https://www.github.com/googleapis/node-gtoken/compare/v4.1.4...v5.0.0) (2020-03-24) + + +### ⚠ BREAKING CHANGES + +* drop Node 8 from engines (#284) +* typescript@3.7.x introduced breaking changes to compiled code + +### Features + +* drop Node 8 from engines ([#284](https://www.github.com/googleapis/node-gtoken/issues/284)) ([209e007](https://www.github.com/googleapis/node-gtoken/commit/209e00746116a82a3cf9acc158aff12a4971f3d0)) + + +### Build System + +* update gts and typescript ([#283](https://www.github.com/googleapis/node-gtoken/issues/283)) ([ff076dc](https://www.github.com/googleapis/node-gtoken/commit/ff076dcb3da229238e7bed28d739c48986652c78)) + +### [4.1.4](https://www.github.com/googleapis/node-gtoken/compare/v4.1.3...v4.1.4) (2020-01-06) + + +### Bug Fixes + +* **deps:** pin TypeScript below 3.7.0 ([f1ae7b6](https://www.github.com/googleapis/node-gtoken/commit/f1ae7b64ead1c918546ae5bbe8546dfb4ecc788a)) +* **deps:** update dependency jws to v4 ([#251](https://www.github.com/googleapis/node-gtoken/issues/251)) ([e13542f](https://www.github.com/googleapis/node-gtoken/commit/e13542f888a81ed3ced0023e9b78ed25264b1d1c)) + +### [4.1.3](https://www.github.com/googleapis/node-gtoken/compare/v4.1.2...v4.1.3) (2019-11-15) + + +### Bug Fixes + +* **deps:** use typescript ~3.6.0 ([#246](https://www.github.com/googleapis/node-gtoken/issues/246)) ([5f725b7](https://www.github.com/googleapis/node-gtoken/commit/5f725b71f080e83058b1a23340acadc0c8704123)) + +### [4.1.2](https://www.github.com/googleapis/node-gtoken/compare/v4.1.1...v4.1.2) (2019-11-13) + + +### Bug Fixes + +* **docs:** add jsdoc-region-tag plugin ([#242](https://www.github.com/googleapis/node-gtoken/issues/242)) ([994c5cc](https://www.github.com/googleapis/node-gtoken/commit/994c5ccf92731599aa63b84c29a9d5f6b1431cc5)) + +### [4.1.1](https://www.github.com/googleapis/node-gtoken/compare/v4.1.0...v4.1.1) (2019-10-31) + + +### Bug Fixes + +* **deps:** update gaxios to 2.1.0 ([#238](https://www.github.com/googleapis/node-gtoken/issues/238)) ([bb12064](https://www.github.com/googleapis/node-gtoken/commit/bb1206420388399ef8992efe54c70bdb3fdcd965)) + +## [4.1.0](https://www.github.com/googleapis/node-gtoken/compare/v4.0.0...v4.1.0) (2019-09-24) + + +### Features + +* allow upstream libraries to force token refresh ([#229](https://www.github.com/googleapis/node-gtoken/issues/229)) ([1fd4dd1](https://www.github.com/googleapis/node-gtoken/commit/1fd4dd1)) + +## [4.0.0](https://www.github.com/googleapis/node-gtoken/compare/v3.0.2...v4.0.0) (2019-07-09) + + +### ⚠ BREAKING CHANGES + +* This commit creates multiple breaking changes. The `getToken()` +method previously returned `Promise`, where the string was the +`access_token` returned from the response. However, the `oauth2` endpoint could +return a variety of other fields, such as an `id_token` in special cases. + +```js +const token = await getToken(); +// old response: 'some.access.token' +// new response: { access_token: 'some.access.token'} +``` + +To further support this change, the `GoogleToken` class no longer exposes +a `token` variable. It now exposes `rawToken`, `accessToken`, and `idToken` +fields which can be used to access the relevant values returned in the +response. + +### Bug Fixes + +* expose all fields from response ([#218](https://www.github.com/googleapis/node-gtoken/issues/218)) ([d463370](https://www.github.com/googleapis/node-gtoken/commit/d463370)) + +### [3.0.2](https://www.github.com/googleapis/node-gtoken/compare/v3.0.1...v3.0.2) (2019-06-26) + + +### Bug Fixes + +* **docs:** make anchors work in jsdoc ([#215](https://www.github.com/googleapis/node-gtoken/issues/215)) ([c5f6c89](https://www.github.com/googleapis/node-gtoken/commit/c5f6c89)) + +### [3.0.1](https://www.github.com/googleapis/node-gtoken/compare/v3.0.0...v3.0.1) (2019-06-13) + + +### Bug Fixes + +* **docs:** move to new client docs URL ([#212](https://www.github.com/googleapis/node-gtoken/issues/212)) ([b7a8c75](https://www.github.com/googleapis/node-gtoken/commit/b7a8c75)) + +## [3.0.0](https://www.github.com/googleapis/node-gtoken/compare/v2.3.3...v3.0.0) (2019-05-07) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v2 ([#191](https://www.github.com/googleapis/node-gtoken/issues/191)) ([da65ea7](https://www.github.com/googleapis/node-gtoken/commit/da65ea7)) +* **deps:** update dependency google-p12-pem to v2 ([#196](https://www.github.com/googleapis/node-gtoken/issues/196)) ([b510f06](https://www.github.com/googleapis/node-gtoken/commit/b510f06)) +* fs.readFile does not exist in browser ([#186](https://www.github.com/googleapis/node-gtoken/issues/186)) ([a16d8e7](https://www.github.com/googleapis/node-gtoken/commit/a16d8e7)) + + +### Build System + +* upgrade engines field to >=8.10.0 ([#194](https://www.github.com/googleapis/node-gtoken/issues/194)) ([ee4d6c8](https://www.github.com/googleapis/node-gtoken/commit/ee4d6c8)) + + +### BREAKING CHANGES + +* upgrade engines field to >=8.10.0 (#194) + +## v2.3.3 + +03-13-2019 14:54 PDT + +### Bug Fixes +- fix: propagate error message ([#173](https://github.com/google/node-gtoken/pull/173)) + +### Documentation +- docs: update links in contrib guide ([#171](https://github.com/google/node-gtoken/pull/171)) +- docs: move CONTRIBUTING.md to root ([#166](https://github.com/google/node-gtoken/pull/166)) +- docs: add lint/fix example to contributing guide ([#164](https://github.com/google/node-gtoken/pull/164)) + +### Internal / Testing Changes +- build: Add docuploader credentials to node publish jobs ([#176](https://github.com/google/node-gtoken/pull/176)) +- build: use node10 to run samples-test, system-test etc ([#175](https://github.com/google/node-gtoken/pull/175)) +- build: update release configuration +- chore(deps): update dependency mocha to v6 +- build: use linkinator for docs test ([#170](https://github.com/google/node-gtoken/pull/170)) +- build: create docs test npm scripts ([#169](https://github.com/google/node-gtoken/pull/169)) +- build: test using @grpc/grpc-js in CI ([#168](https://github.com/google/node-gtoken/pull/168)) +- build: ignore googleapis.com in doc link check ([#162](https://github.com/google/node-gtoken/pull/162)) +- build: check for 404s on all docs + +## v2.3.2 + +01-09-2019 13:40 PST + +### Documentation +- docs: generate docs with compodoc ([#154](https://github.com/googleapis/node-gtoken/pull/154)) +- docs: fix up the readme ([#153](https://github.com/googleapis/node-gtoken/pull/153)) + +### Internal / Testing Changes +- build: Re-generated to pick up changes in the API or client library generator. ([#158](https://github.com/googleapis/node-gtoken/pull/158)) +- build: check broken links in generated docs ([#152](https://github.com/googleapis/node-gtoken/pull/152)) +- fix: add a system test and get it passing ([#150](https://github.com/googleapis/node-gtoken/pull/150)) +- chore(build): inject yoshi automation key ([#149](https://github.com/googleapis/node-gtoken/pull/149)) + +## v2.3.1 + +12-10-2018 15:28 PST + +### Dependencies +- fix(deps): update dependency pify to v4 ([#87](https://github.com/google/node-gtoken/pull/87)) +- fix(deps): use gaxios for http requests ([#125](https://github.com/google/node-gtoken/pull/125)) + +### Internal / Testing Changes +- build: add Kokoro configs for autorelease ([#143](https://github.com/google/node-gtoken/pull/143)) +- chore: always nyc report before calling codecov ([#141](https://github.com/google/node-gtoken/pull/141)) +- chore: nyc ignore build/test by default ([#140](https://github.com/google/node-gtoken/pull/140)) +- chore: update synth metadata and templates ([#138](https://github.com/google/node-gtoken/pull/138)) +- fix(build): fix system key decryption ([#133](https://github.com/google/node-gtoken/pull/133)) +- chore(deps): update dependency typescript to ~3.2.0 ([#132](https://github.com/google/node-gtoken/pull/132)) +- chore: add a synth.metadata +- chore(deps): update dependency gts to ^0.9.0 ([#127](https://github.com/google/node-gtoken/pull/127)) +- chore: update eslintignore config ([#126](https://github.com/google/node-gtoken/pull/126)) +- chore: use latest npm on Windows ([#124](https://github.com/google/node-gtoken/pull/124)) +- chore: update CircleCI config ([#123](https://github.com/google/node-gtoken/pull/123)) +- chore: include build in eslintignore ([#120](https://github.com/google/node-gtoken/pull/120)) +- chore: update issue templates ([#116](https://github.com/google/node-gtoken/pull/116)) +- chore: remove old issue template ([#114](https://github.com/google/node-gtoken/pull/114)) +- build: run tests on node11 ([#113](https://github.com/google/node-gtoken/pull/113)) +- chore(deps): update dependency nock to v10 ([#111](https://github.com/google/node-gtoken/pull/111)) +- chores(build): do not collect sponge.xml from windows builds ([#112](https://github.com/google/node-gtoken/pull/112)) +- chore(deps): update dependency typescript to ~3.1.0 ([#110](https://github.com/google/node-gtoken/pull/110)) +- chores(build): run codecov on continuous builds ([#109](https://github.com/google/node-gtoken/pull/109)) +- chore: update new issue template ([#108](https://github.com/google/node-gtoken/pull/108)) +- chore: update CI config ([#105](https://github.com/google/node-gtoken/pull/105)) +- Update kokoro config ([#103](https://github.com/google/node-gtoken/pull/103)) +- Update CI config ([#101](https://github.com/google/node-gtoken/pull/101)) +- Don't publish sourcemaps ([#99](https://github.com/google/node-gtoken/pull/99)) +- Update kokoro config ([#97](https://github.com/google/node-gtoken/pull/97)) +- test: remove appveyor config ([#96](https://github.com/google/node-gtoken/pull/96)) +- Update CI config ([#95](https://github.com/google/node-gtoken/pull/95)) +- Enable prefer-const in the eslint config ([#94](https://github.com/google/node-gtoken/pull/94)) +- Enable no-var in eslint ([#93](https://github.com/google/node-gtoken/pull/93)) +- Update CI config ([#92](https://github.com/google/node-gtoken/pull/92)) +- Add synth and update CI config ([#91](https://github.com/google/node-gtoken/pull/91)) +- Retry npm install in CI ([#90](https://github.com/google/node-gtoken/pull/90)) +- chore(deps): update dependency nyc to v13 ([#88](https://github.com/google/node-gtoken/pull/88)) +- chore: ignore package-log.json ([#86](https://github.com/google/node-gtoken/pull/86)) +- chore: update renovate config ([#83](https://github.com/google/node-gtoken/pull/83)) +- chore(deps): lock file maintenance ([#85](https://github.com/google/node-gtoken/pull/85)) +- chore: remove greenkeeper badge ([#82](https://github.com/google/node-gtoken/pull/82)) +- test: throw on deprecation ([#81](https://github.com/google/node-gtoken/pull/81)) +- chore(deps): update dependency typescript to v3 ([#80](https://github.com/google/node-gtoken/pull/80)) +- chore: move mocha options to mocha.opts ([#78](https://github.com/google/node-gtoken/pull/78)) +- chore(deps): lock file maintenance ([#79](https://github.com/google/node-gtoken/pull/79)) +- test: use strictEqual in tests ([#76](https://github.com/google/node-gtoken/pull/76)) +- chore(deps): lock file maintenance ([#77](https://github.com/google/node-gtoken/pull/77)) +- chore(deps): update dependency typescript to ~2.9.0 ([#75](https://github.com/google/node-gtoken/pull/75)) +- chore: Configure Renovate ([#74](https://github.com/google/node-gtoken/pull/74)) +- Update gts to the latest version 🚀 ([#73](https://github.com/google/node-gtoken/pull/73)) +- Add Code of Conduct +- build: start testing against Node 10 ([#69](https://github.com/google/node-gtoken/pull/69)) +- chore(package): update nyc to version 12.0.2 ([#67](https://github.com/google/node-gtoken/pull/67)) +- chore(package): update @types/node to version 10.0.3 ([#65](https://github.com/google/node-gtoken/pull/65)) + +### 2.0.0 +New features: +- API now supports callback and promise based workflows + +Breaking changes: +- `GoogleToken` is now a class type, and must be instantiated. +- `GoogleToken.expires_at` renamed to `GoogleToken.expiresAt` +- `GoogleToken.raw_token` renamed to `GoogleToken.rawToken` +- `GoogleToken.token_expires` renamed to `GoogleToken.tokenExpires` diff --git a/node_modules/gtoken/LICENSE b/node_modules/gtoken/LICENSE new file mode 100644 index 0000000..061e6a6 --- /dev/null +++ b/node_modules/gtoken/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Ryan Seys + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/gtoken/README.md b/node_modules/gtoken/README.md new file mode 100644 index 0000000..9dcb82e --- /dev/null +++ b/node_modules/gtoken/README.md @@ -0,0 +1,187 @@ +Google Cloud Platform logo + +# [node-gtoken](https://github.com/googleapis/node-gtoken) + +[![npm version][npm-image]][npm-url] +[![Known Vulnerabilities][snyk-image]][snyk-url] +[![codecov][codecov-image]][codecov-url] +[![Code Style: Google][gts-image]][gts-url] + +> Node.js Google Authentication Service Account Tokens + +This is a low level utility library used to interact with Google Authentication services. **In most cases, you probably want to use the [google-auth-library](https://github.com/googleapis/google-auth-library-nodejs) instead.** + +* [gtoken API Reference][client-docs] +* [github.com/googleapis/node-gtoken](https://github.com/googleapis/node-gtoken) + +## Installation + +``` sh +npm install gtoken +``` + +## Usage + +### Use with a `.pem` or `.json` key file: + +``` js +const { GoogleToken } = require('gtoken'); +const gtoken = new GoogleToken({ + keyFile: 'path/to/key.pem', // or path to .json key file + email: 'my_service_account_email@developer.gserviceaccount.com', + scope: ['https://scope1', 'https://scope2'], // or space-delimited string of scopes + eagerRefreshThresholdMillis: 5 * 60 * 1000 +}); + +gtoken.getToken((err, tokens) => { + if (err) { + console.log(err); + return; + } + console.log(tokens); + // { + // access_token: 'very-secret-token', + // expires_in: 3600, + // token_type: 'Bearer' + // } +}); +``` + +You can also use the async/await style API: + +``` js +const tokens = await gtoken.getToken() +console.log(tokens); +``` + +Or use promises: + +```js +gtoken.getToken() + .then(tokens => { + console.log(tokens) + }) + .catch(console.error); +``` + +### Use with a service account `.json` key file: + +``` js +const { GoogleToken } = require('gtoken'); +const gtoken = new GoogleToken({ + keyFile: 'path/to/key.json', + scope: ['https://scope1', 'https://scope2'], // or space-delimited string of scopes + eagerRefreshThresholdMillis: 5 * 60 * 1000 +}); + +gtoken.getToken((err, tokens) => { + if (err) { + console.log(err); + return; + } + console.log(tokens); +}); +``` + +### Pass the private key as a string directly: + +``` js +const key = '-----BEGIN RSA PRIVATE KEY-----\nXXXXXXXXXXX...'; +const { GoogleToken } = require('gtoken'); +const gtoken = new GoogleToken({ + email: 'my_service_account_email@developer.gserviceaccount.com', + scope: ['https://scope1', 'https://scope2'], // or space-delimited string of scopes + key: key, + eagerRefreshThresholdMillis: 5 * 60 * 1000 +}); +``` + +## Options + +> Various options that can be set when creating initializing the `gtoken` object. + +- `options.email or options.iss`: The service account email address. +- `options.scope`: An array of scope strings or space-delimited string of scopes. +- `options.sub`: The email address of the user requesting delegated access. +- `options.keyFile`: The filename of `.json` key or `.pem` key. +- `options.key`: The raw RSA private key value, in place of using `options.keyFile`. +- `options.additionalClaims`: Additional claims to include in the JWT when requesting a token. +- `options.eagerRefreshThresholdMillis`: How long must a token be valid for in order to return it from the cache. Defaults to 0. + +### .getToken(callback) + +> Returns the cached tokens or requests a new one and returns it. + +``` js +gtoken.getToken((err, token) => { + console.log(err || token); + // gtoken.rawToken value is also set +}); +``` + +### .getCredentials('path/to/key.json') + +> Given a keyfile, returns the key and (if available) the client email. + +```js +const creds = await gtoken.getCredentials('path/to/key.json'); +``` + +### Properties + +> Various properties set on the gtoken object after call to `.getToken()`. + +- `gtoken.idToken`: The OIDC token returned (if any). +- `gtoken.accessToken`: The access token. +- `gtoken.expiresAt`: The expiry date as milliseconds since 1970/01/01 +- `gtoken.key`: The raw key value. +- `gtoken.rawToken`: Most recent raw token data received from Google. + +### .hasExpired() + +> Returns true if the token has expired, or token does not exist. + +``` js +const tokens = await gtoken.getToken(); +gtoken.hasExpired(); // false +``` + +### .revokeToken() + +> Revoke the token if set. + +``` js +await gtoken.revokeToken(); +console.log('Token revoked!'); +``` + +## Downloading your private `.json` key from Google + +1. Open the [Google Developer Console][gdevconsole]. +2. Open your project and under "APIs & auth", click Credentials. +3. Generate a new `.json` key and download it into your project. + +## Converting your `.p12` key to a `.pem` key + +If you'd like to convert to a `.pem` for use later, use OpenSSL if you have it installed. + +``` sh +$ openssl pkcs12 -in key.p12 -nodes -nocerts > key.pem +``` + +Don't forget, the passphrase when converting these files is the string `'notasecret'` + +## License + +[MIT](https://github.com/googleapis/node-gtoken/blob/main/LICENSE) + +[codecov-image]: https://codecov.io/gh/googleapis/node-gtoken/branch/main/graph/badge.svg +[codecov-url]: https://codecov.io/gh/googleapis/node-gtoken +[gdevconsole]: https://console.developers.google.com +[gts-image]: https://img.shields.io/badge/code%20style-google-blueviolet.svg +[gts-url]: https://www.npmjs.com/package/gts +[npm-image]: https://img.shields.io/npm/v/gtoken.svg +[npm-url]: https://npmjs.org/package/gtoken +[snyk-image]: https://snyk.io/test/github/googleapis/node-gtoken/badge.svg +[snyk-url]: https://snyk.io/test/github/googleapis/node-gtoken +[client-docs]: https://googleapis.dev/nodejs/gtoken/latest/ diff --git a/node_modules/gtoken/build/src/index.d.ts b/node_modules/gtoken/build/src/index.d.ts new file mode 100644 index 0000000..2ffe342 --- /dev/null +++ b/node_modules/gtoken/build/src/index.d.ts @@ -0,0 +1,93 @@ +/** + * Copyright 2018 Google LLC + * + * Distributed under MIT license. + * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT + */ +import { GaxiosOptions, GaxiosPromise } from 'gaxios'; +export interface Transporter { + request(opts: GaxiosOptions): GaxiosPromise; +} +export type GetTokenCallback = (err: Error | null, token?: TokenData) => void; +export interface Credentials { + privateKey: string; + clientEmail?: string; +} +export interface TokenData { + refresh_token?: string; + expires_in?: number; + access_token?: string; + token_type?: string; + id_token?: string; +} +export interface TokenOptions { + keyFile?: string; + key?: string; + email?: string; + iss?: string; + sub?: string; + scope?: string | string[]; + additionalClaims?: {}; + eagerRefreshThresholdMillis?: number; + transporter?: Transporter; +} +export interface GetTokenOptions { + forceRefresh?: boolean; +} +export declare class GoogleToken { + #private; + get accessToken(): string | undefined; + get idToken(): string | undefined; + get tokenType(): string | undefined; + get refreshToken(): string | undefined; + expiresAt?: number; + key?: string; + keyFile?: string; + iss?: string; + sub?: string; + scope?: string; + rawToken?: TokenData; + tokenExpires?: number; + email?: string; + additionalClaims?: {}; + eagerRefreshThresholdMillis?: number; + transporter: Transporter; + /** + * Create a GoogleToken. + * + * @param options Configuration object. + */ + constructor(options?: TokenOptions); + /** + * Returns whether the token has expired. + * + * @return true if the token has expired, false otherwise. + */ + hasExpired(): boolean; + /** + * Returns whether the token will expire within eagerRefreshThresholdMillis + * + * @return true if the token will be expired within eagerRefreshThresholdMillis, false otherwise. + */ + isTokenExpiring(): boolean; + /** + * Returns a cached token or retrieves a new one from Google. + * + * @param callback The callback function. + */ + getToken(opts?: GetTokenOptions): Promise; + getToken(callback: GetTokenCallback, opts?: GetTokenOptions): void; + /** + * Given a keyFile, extract the key and client email if available + * @param keyFile Path to a json, pem, or p12 file that contains the key. + * @returns an object with privateKey and clientEmail properties + */ + getCredentials(keyFile: string): Promise; + /** + * Revoke the token if one is set. + * + * @param callback The callback function. + */ + revokeToken(): Promise; + revokeToken(callback: (err?: Error) => void): void; +} diff --git a/node_modules/gtoken/build/src/index.js b/node_modules/gtoken/build/src/index.js new file mode 100644 index 0000000..bf45042 --- /dev/null +++ b/node_modules/gtoken/build/src/index.js @@ -0,0 +1,276 @@ +"use strict"; +/** + * Copyright 2018 Google LLC + * + * Distributed under MIT license. + * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT + */ +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var _GoogleToken_instances, _GoogleToken_inFlightRequest, _GoogleToken_getTokenAsync, _GoogleToken_getTokenAsyncInner, _GoogleToken_ensureEmail, _GoogleToken_revokeTokenAsync, _GoogleToken_configure, _GoogleToken_requestToken; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GoogleToken = void 0; +const fs = require("fs"); +const gaxios_1 = require("gaxios"); +const jws = require("jws"); +const path = require("path"); +const util_1 = require("util"); +const readFile = fs.readFile + ? (0, util_1.promisify)(fs.readFile) + : async () => { + // if running in the web-browser, fs.readFile may not have been shimmed. + throw new ErrorWithCode('use key rather than keyFile.', 'MISSING_CREDENTIALS'); + }; +const GOOGLE_TOKEN_URL = 'https://www.googleapis.com/oauth2/v4/token'; +const GOOGLE_REVOKE_TOKEN_URL = 'https://accounts.google.com/o/oauth2/revoke?token='; +class ErrorWithCode extends Error { + constructor(message, code) { + super(message); + this.code = code; + } +} +class GoogleToken { + get accessToken() { + return this.rawToken ? this.rawToken.access_token : undefined; + } + get idToken() { + return this.rawToken ? this.rawToken.id_token : undefined; + } + get tokenType() { + return this.rawToken ? this.rawToken.token_type : undefined; + } + get refreshToken() { + return this.rawToken ? this.rawToken.refresh_token : undefined; + } + /** + * Create a GoogleToken. + * + * @param options Configuration object. + */ + constructor(options) { + _GoogleToken_instances.add(this); + this.transporter = { + request: opts => (0, gaxios_1.request)(opts), + }; + _GoogleToken_inFlightRequest.set(this, void 0); + __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_configure).call(this, options); + } + /** + * Returns whether the token has expired. + * + * @return true if the token has expired, false otherwise. + */ + hasExpired() { + const now = new Date().getTime(); + if (this.rawToken && this.expiresAt) { + return now >= this.expiresAt; + } + else { + return true; + } + } + /** + * Returns whether the token will expire within eagerRefreshThresholdMillis + * + * @return true if the token will be expired within eagerRefreshThresholdMillis, false otherwise. + */ + isTokenExpiring() { + var _a; + const now = new Date().getTime(); + const eagerRefreshThresholdMillis = (_a = this.eagerRefreshThresholdMillis) !== null && _a !== void 0 ? _a : 0; + if (this.rawToken && this.expiresAt) { + return this.expiresAt <= now + eagerRefreshThresholdMillis; + } + else { + return true; + } + } + getToken(callback, opts = {}) { + if (typeof callback === 'object') { + opts = callback; + callback = undefined; + } + opts = Object.assign({ + forceRefresh: false, + }, opts); + if (callback) { + const cb = callback; + __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsync).call(this, opts).then(t => cb(null, t), callback); + return; + } + return __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsync).call(this, opts); + } + /** + * Given a keyFile, extract the key and client email if available + * @param keyFile Path to a json, pem, or p12 file that contains the key. + * @returns an object with privateKey and clientEmail properties + */ + async getCredentials(keyFile) { + const ext = path.extname(keyFile); + switch (ext) { + case '.json': { + const key = await readFile(keyFile, 'utf8'); + const body = JSON.parse(key); + const privateKey = body.private_key; + const clientEmail = body.client_email; + if (!privateKey || !clientEmail) { + throw new ErrorWithCode('private_key and client_email are required.', 'MISSING_CREDENTIALS'); + } + return { privateKey, clientEmail }; + } + case '.der': + case '.crt': + case '.pem': { + const privateKey = await readFile(keyFile, 'utf8'); + return { privateKey }; + } + case '.p12': + case '.pfx': { + throw new ErrorWithCode('*.p12 certificates are not supported after v6.1.2. ' + + 'Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.', 'UNKNOWN_CERTIFICATE_TYPE'); + } + default: + throw new ErrorWithCode('Unknown certificate type. Type is determined based on file extension. ' + + 'Current supported extensions are *.json, and *.pem.', 'UNKNOWN_CERTIFICATE_TYPE'); + } + } + revokeToken(callback) { + if (callback) { + __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_revokeTokenAsync).call(this).then(() => callback(), callback); + return; + } + return __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_revokeTokenAsync).call(this); + } +} +exports.GoogleToken = GoogleToken; +_GoogleToken_inFlightRequest = new WeakMap(), _GoogleToken_instances = new WeakSet(), _GoogleToken_getTokenAsync = async function _GoogleToken_getTokenAsync(opts) { + if (__classPrivateFieldGet(this, _GoogleToken_inFlightRequest, "f") && !opts.forceRefresh) { + return __classPrivateFieldGet(this, _GoogleToken_inFlightRequest, "f"); + } + try { + return await (__classPrivateFieldSet(this, _GoogleToken_inFlightRequest, __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsyncInner).call(this, opts), "f")); + } + finally { + __classPrivateFieldSet(this, _GoogleToken_inFlightRequest, undefined, "f"); + } +}, _GoogleToken_getTokenAsyncInner = async function _GoogleToken_getTokenAsyncInner(opts) { + if (this.isTokenExpiring() === false && opts.forceRefresh === false) { + return Promise.resolve(this.rawToken); + } + if (!this.key && !this.keyFile) { + throw new Error('No key or keyFile set.'); + } + if (!this.key && this.keyFile) { + const creds = await this.getCredentials(this.keyFile); + this.key = creds.privateKey; + this.iss = creds.clientEmail || this.iss; + if (!creds.clientEmail) { + __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_ensureEmail).call(this); + } + } + return __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_requestToken).call(this); +}, _GoogleToken_ensureEmail = function _GoogleToken_ensureEmail() { + if (!this.iss) { + throw new ErrorWithCode('email is required.', 'MISSING_CREDENTIALS'); + } +}, _GoogleToken_revokeTokenAsync = async function _GoogleToken_revokeTokenAsync() { + if (!this.accessToken) { + throw new Error('No token to revoke.'); + } + const url = GOOGLE_REVOKE_TOKEN_URL + this.accessToken; + await this.transporter.request({ + url, + retry: true, + }); + __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_configure).call(this, { + email: this.iss, + sub: this.sub, + key: this.key, + keyFile: this.keyFile, + scope: this.scope, + additionalClaims: this.additionalClaims, + }); +}, _GoogleToken_configure = function _GoogleToken_configure(options = {}) { + this.keyFile = options.keyFile; + this.key = options.key; + this.rawToken = undefined; + this.iss = options.email || options.iss; + this.sub = options.sub; + this.additionalClaims = options.additionalClaims; + if (typeof options.scope === 'object') { + this.scope = options.scope.join(' '); + } + else { + this.scope = options.scope; + } + this.eagerRefreshThresholdMillis = options.eagerRefreshThresholdMillis; + if (options.transporter) { + this.transporter = options.transporter; + } +}, _GoogleToken_requestToken = +/** + * Request the token from Google. + */ +async function _GoogleToken_requestToken() { + var _a, _b; + const iat = Math.floor(new Date().getTime() / 1000); + const additionalClaims = this.additionalClaims || {}; + const payload = Object.assign({ + iss: this.iss, + scope: this.scope, + aud: GOOGLE_TOKEN_URL, + exp: iat + 3600, + iat, + sub: this.sub, + }, additionalClaims); + const signedJWT = jws.sign({ + header: { alg: 'RS256' }, + payload, + secret: this.key, + }); + try { + const r = await this.transporter.request({ + method: 'POST', + url: GOOGLE_TOKEN_URL, + data: { + grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', + assertion: signedJWT, + }, + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + responseType: 'json', + retryConfig: { + httpMethodsToRetry: ['POST'], + }, + }); + this.rawToken = r.data; + this.expiresAt = + r.data.expires_in === null || r.data.expires_in === undefined + ? undefined + : (iat + r.data.expires_in) * 1000; + return this.rawToken; + } + catch (e) { + this.rawToken = undefined; + this.tokenExpires = undefined; + const body = e.response && ((_a = e.response) === null || _a === void 0 ? void 0 : _a.data) + ? (_b = e.response) === null || _b === void 0 ? void 0 : _b.data + : {}; + if (body.error) { + const desc = body.error_description + ? `: ${body.error_description}` + : ''; + e.message = `${body.error}${desc}`; + } + throw e; + } +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/gtoken/package.json b/node_modules/gtoken/package.json new file mode 100644 index 0000000..3c76f38 --- /dev/null +++ b/node_modules/gtoken/package.json @@ -0,0 +1,62 @@ +{ + "name": "gtoken", + "version": "7.1.0", + "description": "Node.js Google Authentication Service Account Tokens", + "main": "./build/src/index.js", + "types": "./build/src/index.d.ts", + "engines": { + "node": ">=14.0.0" + }, + "repository": "google/node-gtoken", + "scripts": { + "lint": "gts check", + "clean": "gts clean", + "fix": "gts fix", + "compile": "tsc -p .", + "test": "c8 mocha build/test", + "prepare": "npm run compile", + "pretest": "npm run compile", + "presystem-test": "npm run compile", + "system-test": "mocha build/system-test", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "docs": "compodoc src/", + "docs-test": "linkinator docs", + "predocs-test": "npm run docs", + "prelint": "cd samples; npm link ../; npm install", + "precompile": "gts clean" + }, + "keywords": [ + "google", + "service", + "account", + "api", + "token", + "api", + "auth" + ], + "author": { + "name": "Google, LLC" + }, + "license": "MIT", + "dependencies": { + "gaxios": "^6.0.0", + "jws": "^4.0.0" + }, + "devDependencies": { + "@babel/plugin-proposal-private-methods": "^7.18.6", + "@compodoc/compodoc": "^1.1.7", + "@types/jws": "^3.1.0", + "@types/mocha": "^9.0.0", + "@types/node": "^20.0.0", + "c8": "^9.0.0", + "gts": "^5.0.0", + "linkinator": "^4.0.0", + "mocha": "^9.2.2", + "nock": "^13.0.0", + "typescript": "^5.1.6" + }, + "files": [ + "build/src", + "!build/src/**/*.map" + ] +} diff --git a/node_modules/has-symbols/.eslintrc b/node_modules/has-symbols/.eslintrc new file mode 100644 index 0000000..2d9a66a --- /dev/null +++ b/node_modules/has-symbols/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-statements-per-line": [2, { "max": 2 }], + "no-magic-numbers": 0, + "multiline-comment-style": 0, + } +} diff --git a/node_modules/has-symbols/.github/FUNDING.yml b/node_modules/has-symbols/.github/FUNDING.yml new file mode 100644 index 0000000..04cf87e --- /dev/null +++ b/node_modules/has-symbols/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/has-symbols +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/has-symbols/.nycrc b/node_modules/has-symbols/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/has-symbols/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/has-symbols/CHANGELOG.md b/node_modules/has-symbols/CHANGELOG.md new file mode 100644 index 0000000..cc3cf83 --- /dev/null +++ b/node_modules/has-symbols/CHANGELOG.md @@ -0,0 +1,91 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.0](https://github.com/inspect-js/has-symbols/compare/v1.0.3...v1.1.0) - 2024-12-02 + +### Commits + +- [actions] update workflows [`548c0bf`](https://github.com/inspect-js/has-symbols/commit/548c0bf8c9b1235458df7a1c0490b0064647a282) +- [actions] further shard; update action deps [`bec56bb`](https://github.com/inspect-js/has-symbols/commit/bec56bb0fb44b43a786686b944875a3175cf3ff3) +- [meta] use `npmignore` to autogenerate an npmignore file [`ac81032`](https://github.com/inspect-js/has-symbols/commit/ac81032809157e0a079e5264e9ce9b6f1275777e) +- [New] add types [`6469cbf`](https://github.com/inspect-js/has-symbols/commit/6469cbff1866cfe367b2b3d181d9296ec14b2a3d) +- [actions] update rebase action to use reusable workflow [`9c9d4d0`](https://github.com/inspect-js/has-symbols/commit/9c9d4d0d8938e4b267acdf8e421f4e92d1716d72) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`adb5887`](https://github.com/inspect-js/has-symbols/commit/adb5887ca9444849b08beb5caaa9e1d42320cdfb) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`13ec198`](https://github.com/inspect-js/has-symbols/commit/13ec198ec80f1993a87710af1606a1970b22c7cb) +- [Dev Deps] update `auto-changelog`, `core-js`, `tape` [`941be52`](https://github.com/inspect-js/has-symbols/commit/941be5248387cab1da72509b22acf3fdb223f057) +- [Tests] replace `aud` with `npm audit` [`74f49e9`](https://github.com/inspect-js/has-symbols/commit/74f49e9a9d17a443020784234a1c53ce765b3559) +- [Dev Deps] update `npmignore` [`9c0ac04`](https://github.com/inspect-js/has-symbols/commit/9c0ac0452a834f4c2a4b54044f2d6a89f17e9a70) +- [Dev Deps] add missing peer dep [`52337a5`](https://github.com/inspect-js/has-symbols/commit/52337a5621cced61f846f2afdab7707a8132cc12) + +## [v1.0.3](https://github.com/inspect-js/has-symbols/compare/v1.0.2...v1.0.3) - 2022-03-01 + +### Commits + +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`518b28f`](https://github.com/inspect-js/has-symbols/commit/518b28f6c5a516cbccae30794e40aa9f738b1693) +- [meta] add `bugs` and `homepage` fields; reorder package.json [`c480b13`](https://github.com/inspect-js/has-symbols/commit/c480b13fd6802b557e1cef9749872cb5fdeef744) +- [actions] reuse common workflows [`01d0ee0`](https://github.com/inspect-js/has-symbols/commit/01d0ee0a8d97c0947f5edb73eb722027a77b2b07) +- [actions] update codecov uploader [`6424ebe`](https://github.com/inspect-js/has-symbols/commit/6424ebe86b2c9c7c3d2e9bd4413a4e4f168cb275) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`dfa7e7f`](https://github.com/inspect-js/has-symbols/commit/dfa7e7ff38b594645d8c8222aab895157fa7e282) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`0c8d436`](https://github.com/inspect-js/has-symbols/commit/0c8d43685c45189cea9018191d4fd7eca91c9d02) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`9026554`](https://github.com/inspect-js/has-symbols/commit/902655442a1bf88e72b42345494ef0c60f5d36ab) +- [readme] add actions and codecov badges [`eaa9682`](https://github.com/inspect-js/has-symbols/commit/eaa9682f990f481d3acf7a1c7600bec36f7b3adc) +- [Dev Deps] update `eslint`, `tape` [`bc7a3ba`](https://github.com/inspect-js/has-symbols/commit/bc7a3ba46f27b7743f8a2579732d59d1b9ac791e) +- [Dev Deps] update `eslint`, `auto-changelog` [`0ace00a`](https://github.com/inspect-js/has-symbols/commit/0ace00af08a88cdd1e6ce0d60357d941c60c2d9f) +- [meta] use `prepublishOnly` script for npm 7+ [`093f72b`](https://github.com/inspect-js/has-symbols/commit/093f72bc2b0ed00c781f444922a5034257bf561d) +- [Tests] test on all 16 minors [`9b80d3d`](https://github.com/inspect-js/has-symbols/commit/9b80d3d9102529f04c20ec5b1fcc6e38426c6b03) + +## [v1.0.2](https://github.com/inspect-js/has-symbols/compare/v1.0.1...v1.0.2) - 2021-02-27 + +### Fixed + +- [Fix] use a universal way to get the original Symbol [`#11`](https://github.com/inspect-js/has-symbols/issues/11) + +### Commits + +- [Tests] migrate tests to Github Actions [`90ae798`](https://github.com/inspect-js/has-symbols/commit/90ae79820bdfe7bc703d67f5f3c5e205f98556d3) +- [meta] do not publish github action workflow files [`29e60a1`](https://github.com/inspect-js/has-symbols/commit/29e60a1b7c25c7f1acf7acff4a9320d0d10c49b4) +- [Tests] run `nyc` on all tests [`8476b91`](https://github.com/inspect-js/has-symbols/commit/8476b915650d360915abe2522505abf4b0e8f0ae) +- [readme] fix repo URLs, remove defunct badges [`126288e`](https://github.com/inspect-js/has-symbols/commit/126288ecc1797c0a40247a6b78bcb2e0bc5d7036) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `core-js`, `get-own-property-symbols` [`d84bdfa`](https://github.com/inspect-js/has-symbols/commit/d84bdfa48ac5188abbb4904b42614cd6c030940a) +- [Tests] fix linting errors [`0df3070`](https://github.com/inspect-js/has-symbols/commit/0df3070b981b6c9f2ee530c09189a7f5c6def839) +- [actions] add "Allow Edits" workflow [`1e6bc29`](https://github.com/inspect-js/has-symbols/commit/1e6bc29b188f32b9648657b07eda08504be5aa9c) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`36cea2a`](https://github.com/inspect-js/has-symbols/commit/36cea2addd4e6ec435f35a2656b4e9ef82498e9b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`1278338`](https://github.com/inspect-js/has-symbols/commit/127833801865fbc2cc8979beb9ca869c7bfe8222) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`1493254`](https://github.com/inspect-js/has-symbols/commit/1493254eda13db5fb8fc5e4a3e8324b3d196029d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js` [`b090bf2`](https://github.com/inspect-js/has-symbols/commit/b090bf214d3679a30edc1e2d729d466ab5183e1d) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`4addb7a`](https://github.com/inspect-js/has-symbols/commit/4addb7ab4dc73f927ae99928d68817554fc21dc0) +- [Dev Deps] update `auto-changelog`, `tape` [`81d0baf`](https://github.com/inspect-js/has-symbols/commit/81d0baf3816096a89a8558e8043895f7a7d10d8b) +- [Dev Deps] update `auto-changelog`; add `aud` [`1a4e561`](https://github.com/inspect-js/has-symbols/commit/1a4e5612c25d91c3a03d509721d02630bc4fe3da) +- [readme] remove unused testling URLs [`3000941`](https://github.com/inspect-js/has-symbols/commit/3000941f958046e923ed8152edb1ef4a599e6fcc) +- [Tests] only audit prod deps [`692e974`](https://github.com/inspect-js/has-symbols/commit/692e9743c912410e9440207631a643a34b4741a1) +- [Dev Deps] update `@ljharb/eslint-config` [`51c946c`](https://github.com/inspect-js/has-symbols/commit/51c946c7f6baa793ec5390bb5a45cdce16b4ba76) + +## [v1.0.1](https://github.com/inspect-js/has-symbols/compare/v1.0.0...v1.0.1) - 2019-11-16 + +### Commits + +- [Tests] use shared travis-ci configs [`ce396c9`](https://github.com/inspect-js/has-symbols/commit/ce396c9419ff11c43d0da5d05cdbb79f7fb42229) +- [Tests] up to `node` `v12.4`, `v11.15`, `v10.15`, `v9.11`, `v8.15`, `v7.10`, `v6.17`, `v4.9`; use `nvm install-latest-npm` [`0690732`](https://github.com/inspect-js/has-symbols/commit/0690732801f47ab429f39ba1962f522d5c462d6b) +- [meta] add `auto-changelog` [`2163d0b`](https://github.com/inspect-js/has-symbols/commit/2163d0b7f36343076b8f947cd1667dd1750f26fc) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `safe-publish-latest`, `tape` [`8e0951f`](https://github.com/inspect-js/has-symbols/commit/8e0951f1a7a2e52068222b7bb73511761e6e4d9c) +- [actions] add automatic rebasing / merge commit blocking [`b09cdb7`](https://github.com/inspect-js/has-symbols/commit/b09cdb7cd7ee39e7a769878f56e2d6066f5ccd1d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `core-js`, `get-own-property-symbols`, `tape` [`1dd42cd`](https://github.com/inspect-js/has-symbols/commit/1dd42cd86183ed0c50f99b1062345c458babca91) +- [meta] create FUNDING.yml [`aa57a17`](https://github.com/inspect-js/has-symbols/commit/aa57a17b19708906d1927f821ea8e73394d84ca4) +- Only apps should have lockfiles [`a2d8bea`](https://github.com/inspect-js/has-symbols/commit/a2d8bea23a97d15c09eaf60f5b107fcf9a4d57aa) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`9e96cb7`](https://github.com/inspect-js/has-symbols/commit/9e96cb783746cbed0c10ef78e599a8eaa7ebe193) +- [meta] add `funding` field [`a0b32cf`](https://github.com/inspect-js/has-symbols/commit/a0b32cf68e803f963c1639b6d47b0a9d6440bab0) +- [Dev Deps] update `safe-publish-latest` [`cb9f0a5`](https://github.com/inspect-js/has-symbols/commit/cb9f0a521a3a1790f1064d437edd33bb6c3d6af0) + +## v1.0.0 - 2016-09-19 + +### Commits + +- Tests. [`ecb6eb9`](https://github.com/inspect-js/has-symbols/commit/ecb6eb934e4883137f3f93b965ba5e0a98df430d) +- package.json [`88a337c`](https://github.com/inspect-js/has-symbols/commit/88a337cee0864a0da35f5d19e69ff0ef0150e46a) +- Initial commit [`42e1e55`](https://github.com/inspect-js/has-symbols/commit/42e1e5502536a2b8ac529c9443984acd14836b1c) +- Initial implementation. [`33f5cc6`](https://github.com/inspect-js/has-symbols/commit/33f5cc6cdff86e2194b081ee842bfdc63caf43fb) +- read me [`01f1170`](https://github.com/inspect-js/has-symbols/commit/01f1170188ff7cb1558aa297f6ba5b516c6d7b0c) diff --git a/node_modules/has-symbols/LICENSE b/node_modules/has-symbols/LICENSE new file mode 100644 index 0000000..df31cbf --- /dev/null +++ b/node_modules/has-symbols/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/has-symbols/README.md b/node_modules/has-symbols/README.md new file mode 100644 index 0000000..33905f0 --- /dev/null +++ b/node_modules/has-symbols/README.md @@ -0,0 +1,46 @@ +# has-symbols [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Determine if the JS environment has Symbol support. Supports spec, or shams. + +## Example + +```js +var hasSymbols = require('has-symbols'); + +hasSymbols() === true; // if the environment has native Symbol support. Not polyfillable, not forgeable. + +var hasSymbolsKinda = require('has-symbols/shams'); +hasSymbolsKinda() === true; // if the environment has a Symbol sham that mostly follows the spec. +``` + +## Supported Symbol shams + - get-own-property-symbols [npm](https://www.npmjs.com/package/get-own-property-symbols) | [github](https://github.com/WebReflection/get-own-property-symbols) + - core-js [npm](https://www.npmjs.com/package/core-js) | [github](https://github.com/zloirock/core-js) + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/has-symbols +[2]: https://versionbadg.es/inspect-js/has-symbols.svg +[5]: https://david-dm.org/inspect-js/has-symbols.svg +[6]: https://david-dm.org/inspect-js/has-symbols +[7]: https://david-dm.org/inspect-js/has-symbols/dev-status.svg +[8]: https://david-dm.org/inspect-js/has-symbols#info=devDependencies +[11]: https://nodei.co/npm/has-symbols.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/has-symbols.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/has-symbols.svg +[downloads-url]: https://npm-stat.com/charts.html?package=has-symbols +[codecov-image]: https://codecov.io/gh/inspect-js/has-symbols/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/has-symbols/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-symbols +[actions-url]: https://github.com/inspect-js/has-symbols/actions diff --git a/node_modules/has-symbols/index.d.ts b/node_modules/has-symbols/index.d.ts new file mode 100644 index 0000000..9b98595 --- /dev/null +++ b/node_modules/has-symbols/index.d.ts @@ -0,0 +1,3 @@ +declare function hasNativeSymbols(): boolean; + +export = hasNativeSymbols; \ No newline at end of file diff --git a/node_modules/has-symbols/index.js b/node_modules/has-symbols/index.js new file mode 100644 index 0000000..fa65265 --- /dev/null +++ b/node_modules/has-symbols/index.js @@ -0,0 +1,14 @@ +'use strict'; + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = require('./shams'); + +/** @type {import('.')} */ +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; diff --git a/node_modules/has-symbols/package.json b/node_modules/has-symbols/package.json new file mode 100644 index 0000000..d835e20 --- /dev/null +++ b/node_modules/has-symbols/package.json @@ -0,0 +1,111 @@ +{ + "name": "has-symbols", + "version": "1.1.0", + "description": "Determine if the JS environment has Symbol support. Supports spec, or shams.", + "main": "index.js", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent lint", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "tests-only": "npm run test:stock && npm run test:shams", + "test:stock": "nyc node test", + "test:staging": "nyc node --harmony --es-staging test", + "test:shams": "npm run --silent test:shams:getownpropertysymbols && npm run --silent test:shams:corejs", + "test:shams:corejs": "nyc node test/shams/core-js.js", + "test:shams:getownpropertysymbols": "nyc node test/shams/get-own-property-symbols.js", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && attw -P", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/has-symbols.git" + }, + "keywords": [ + "Symbol", + "symbols", + "typeof", + "sham", + "polyfill", + "native", + "core-js", + "ES6" + ], + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/has-symbols/issues" + }, + "homepage": "https://github.com/ljharb/has-symbols#readme", + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.0", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.0", + "@types/core-js": "^2.5.8", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "core-js": "^2.6.12", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "get-own-property-symbols": "^0.9.5", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "types" + ] + } +} diff --git a/node_modules/has-symbols/shams.d.ts b/node_modules/has-symbols/shams.d.ts new file mode 100644 index 0000000..8d0bf24 --- /dev/null +++ b/node_modules/has-symbols/shams.d.ts @@ -0,0 +1,3 @@ +declare function hasSymbolShams(): boolean; + +export = hasSymbolShams; \ No newline at end of file diff --git a/node_modules/has-symbols/shams.js b/node_modules/has-symbols/shams.js new file mode 100644 index 0000000..f97b474 --- /dev/null +++ b/node_modules/has-symbols/shams.js @@ -0,0 +1,45 @@ +'use strict'; + +/** @type {import('./shams')} */ +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + /** @type {{ [k in symbol]?: unknown }} */ + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (var _ in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + // eslint-disable-next-line no-extra-parens + var descriptor = /** @type {PropertyDescriptor} */ (Object.getOwnPropertyDescriptor(obj, sym)); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; diff --git a/node_modules/has-symbols/test/index.js b/node_modules/has-symbols/test/index.js new file mode 100644 index 0000000..352129c --- /dev/null +++ b/node_modules/has-symbols/test/index.js @@ -0,0 +1,22 @@ +'use strict'; + +var test = require('tape'); +var hasSymbols = require('../'); +var runSymbolTests = require('./tests'); + +test('interface', function (t) { + t.equal(typeof hasSymbols, 'function', 'is a function'); + t.equal(typeof hasSymbols(), 'boolean', 'returns a boolean'); + t.end(); +}); + +test('Symbols are supported', { skip: !hasSymbols() }, function (t) { + runSymbolTests(t); + t.end(); +}); + +test('Symbols are not supported', { skip: hasSymbols() }, function (t) { + t.equal(typeof Symbol, 'undefined', 'global Symbol is undefined'); + t.equal(typeof Object.getOwnPropertySymbols, 'undefined', 'Object.getOwnPropertySymbols does not exist'); + t.end(); +}); diff --git a/node_modules/has-symbols/test/shams/core-js.js b/node_modules/has-symbols/test/shams/core-js.js new file mode 100644 index 0000000..1a29024 --- /dev/null +++ b/node_modules/has-symbols/test/shams/core-js.js @@ -0,0 +1,29 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + test('has native Symbol support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol(), 'symbol'); + t.end(); + }); + // @ts-expect-error TS is stupid and doesn't know about top level return + return; +} + +var hasSymbols = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); + require('core-js/fn/symbol'); + require('core-js/fn/symbol/to-string-tag'); + + require('../tests')(t); + + var hasSymbolsAfter = hasSymbols(); + t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/node_modules/has-symbols/test/shams/get-own-property-symbols.js b/node_modules/has-symbols/test/shams/get-own-property-symbols.js new file mode 100644 index 0000000..e0296f8 --- /dev/null +++ b/node_modules/has-symbols/test/shams/get-own-property-symbols.js @@ -0,0 +1,29 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + test('has native Symbol support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol(), 'symbol'); + t.end(); + }); + // @ts-expect-error TS is stupid and doesn't know about top level return + return; +} + +var hasSymbols = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); + + require('get-own-property-symbols'); + + require('../tests')(t); + + var hasSymbolsAfter = hasSymbols(); + t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/node_modules/has-symbols/test/tests.js b/node_modules/has-symbols/test/tests.js new file mode 100644 index 0000000..66a2cb8 --- /dev/null +++ b/node_modules/has-symbols/test/tests.js @@ -0,0 +1,58 @@ +'use strict'; + +/** @type {(t: import('tape').Test) => false | void} */ +// eslint-disable-next-line consistent-return +module.exports = function runSymbolTests(t) { + t.equal(typeof Symbol, 'function', 'global Symbol is a function'); + + if (typeof Symbol !== 'function') { return false; } + + t.notEqual(Symbol(), Symbol(), 'two symbols are not equal'); + + /* + t.equal( + Symbol.prototype.toString.call(Symbol('foo')), + Symbol.prototype.toString.call(Symbol('foo')), + 'two symbols with the same description stringify the same' + ); + */ + + /* + var foo = Symbol('foo'); + + t.notEqual( + String(foo), + String(Symbol('bar')), + 'two symbols with different descriptions do not stringify the same' + ); + */ + + t.equal(typeof Symbol.prototype.toString, 'function', 'Symbol#toString is a function'); + // t.equal(String(foo), Symbol.prototype.toString.call(foo), 'Symbol#toString equals String of the same symbol'); + + t.equal(typeof Object.getOwnPropertySymbols, 'function', 'Object.getOwnPropertySymbols is a function'); + + /** @type {{ [k in symbol]?: unknown }} */ + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + t.notEqual(typeof sym, 'string', 'Symbol is not a string'); + t.equal(Object.prototype.toString.call(sym), '[object Symbol]', 'symbol primitive Object#toStrings properly'); + t.equal(Object.prototype.toString.call(symObj), '[object Symbol]', 'symbol primitive Object#toStrings properly'); + + var symVal = 42; + obj[sym] = symVal; + // eslint-disable-next-line no-restricted-syntax, no-unused-vars + for (var _ in obj) { t.fail('symbol property key was found in for..in of object'); } + + t.deepEqual(Object.keys(obj), [], 'no enumerable own keys on symbol-valued object'); + t.deepEqual(Object.getOwnPropertyNames(obj), [], 'no own names on symbol-valued object'); + t.deepEqual(Object.getOwnPropertySymbols(obj), [sym], 'one own symbol on symbol-valued object'); + t.equal(Object.prototype.propertyIsEnumerable.call(obj, sym), true, 'symbol is enumerable'); + t.deepEqual(Object.getOwnPropertyDescriptor(obj, sym), { + configurable: true, + enumerable: true, + value: 42, + writable: true + }, 'property descriptor is correct'); +}; diff --git a/node_modules/has-symbols/tsconfig.json b/node_modules/has-symbols/tsconfig.json new file mode 100644 index 0000000..ba99af4 --- /dev/null +++ b/node_modules/has-symbols/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "ES2021", + "maxNodeModuleJsDepth": 0, + }, + "exclude": [ + "coverage" + ] +} diff --git a/node_modules/has-tostringtag/.eslintrc b/node_modules/has-tostringtag/.eslintrc new file mode 100644 index 0000000..3b5d9e9 --- /dev/null +++ b/node_modules/has-tostringtag/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/node_modules/has-tostringtag/.github/FUNDING.yml b/node_modules/has-tostringtag/.github/FUNDING.yml new file mode 100644 index 0000000..7a450e7 --- /dev/null +++ b/node_modules/has-tostringtag/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/has-tostringtag +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/has-tostringtag/.nycrc b/node_modules/has-tostringtag/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/has-tostringtag/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/has-tostringtag/CHANGELOG.md b/node_modules/has-tostringtag/CHANGELOG.md new file mode 100644 index 0000000..eb186ec --- /dev/null +++ b/node_modules/has-tostringtag/CHANGELOG.md @@ -0,0 +1,42 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.2](https://github.com/inspect-js/has-tostringtag/compare/v1.0.1...v1.0.2) - 2024-02-01 + +### Fixed + +- [Fix] move `has-symbols` back to prod deps [`#3`](https://github.com/inspect-js/has-tostringtag/issues/3) + +## [v1.0.1](https://github.com/inspect-js/has-tostringtag/compare/v1.0.0...v1.0.1) - 2024-02-01 + +### Commits + +- [patch] add types [`9276414`](https://github.com/inspect-js/has-tostringtag/commit/9276414b22fab3eeb234688841722c4be113201f) +- [meta] use `npmignore` to autogenerate an npmignore file [`5c0dcd1`](https://github.com/inspect-js/has-tostringtag/commit/5c0dcd1ff66419562a30d1fd88b966cc36bce5fc) +- [actions] reuse common workflows [`dee9509`](https://github.com/inspect-js/has-tostringtag/commit/dee950904ab5719b62cf8d73d2ac950b09093266) +- [actions] update codecov uploader [`b8cb3a0`](https://github.com/inspect-js/has-tostringtag/commit/b8cb3a0b8ffbb1593012c4c2daa45fb25642825d) +- [Tests] generate coverage [`be5b288`](https://github.com/inspect-js/has-tostringtag/commit/be5b28889e2735cdbcef387f84c2829995f2f05e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`69a0827`](https://github.com/inspect-js/has-tostringtag/commit/69a0827974e9b877b2c75b70b057555da8f25a65) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`4c9e210`](https://github.com/inspect-js/has-tostringtag/commit/4c9e210a5682f0557a3235d36b68ce809d7fb825) +- [actions] update rebase action to use reusable workflow [`ca8dcd3`](https://github.com/inspect-js/has-tostringtag/commit/ca8dcd3a6f3f5805d7e3fd461b654aedba0946e7) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `npmignore`, `tape` [`07f3eaf`](https://github.com/inspect-js/has-tostringtag/commit/07f3eafa45dd98208c94479737da77f9a69b94c4) +- [Deps] update `has-symbols` [`999e009`](https://github.com/inspect-js/has-tostringtag/commit/999e0095a7d1749a58f55472ec8bf8108cdfdcf3) +- [Tests] remove staging tests since they fail on modern node [`9d9526b`](https://github.com/inspect-js/has-tostringtag/commit/9d9526b1dc1ca7f2292b52efda4c3d857b0e39bd) + +## v1.0.0 - 2021-08-05 + +### Commits + +- Tests [`6b6f573`](https://github.com/inspect-js/has-tostringtag/commit/6b6f5734dc2058badb300ff0783efdad95fe1a65) +- Initial commit [`2f8190e`](https://github.com/inspect-js/has-tostringtag/commit/2f8190e799fac32ba9b95a076c0255e01d7ce475) +- [meta] do not publish github action workflow files [`6e08cc4`](https://github.com/inspect-js/has-tostringtag/commit/6e08cc4e0fea7ec71ef66e70734b2af2c4a8b71b) +- readme [`94bed6c`](https://github.com/inspect-js/has-tostringtag/commit/94bed6c9560cbbfda034f8d6c260bb7b0db33c1a) +- npm init [`be67840`](https://github.com/inspect-js/has-tostringtag/commit/be67840ab92ee7adb98bcc65261975543f815fa5) +- Implementation [`c4914ec`](https://github.com/inspect-js/has-tostringtag/commit/c4914ecc51ddee692c85b471ae0a5d8123030fbf) +- [meta] use `auto-changelog` [`4aaf768`](https://github.com/inspect-js/has-tostringtag/commit/4aaf76895ae01d7b739f2b19f967ef2372506cd7) +- Only apps should have lockfiles [`bc4d99e`](https://github.com/inspect-js/has-tostringtag/commit/bc4d99e4bf494afbaa235c5f098df6e642edf724) +- [meta] add `safe-publish-latest` [`6523c05`](https://github.com/inspect-js/has-tostringtag/commit/6523c05c9b87140f3ae74c9daf91633dd9ff4e1f) diff --git a/node_modules/has-tostringtag/LICENSE b/node_modules/has-tostringtag/LICENSE new file mode 100644 index 0000000..7948bc0 --- /dev/null +++ b/node_modules/has-tostringtag/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Inspect JS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/has-tostringtag/README.md b/node_modules/has-tostringtag/README.md new file mode 100644 index 0000000..67a5e92 --- /dev/null +++ b/node_modules/has-tostringtag/README.md @@ -0,0 +1,46 @@ +# has-tostringtag [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Determine if the JS environment has `Symbol.toStringTag` support. Supports spec, or shams. + +## Example + +```js +var hasSymbolToStringTag = require('has-tostringtag'); + +hasSymbolToStringTag() === true; // if the environment has native Symbol.toStringTag support. Not polyfillable, not forgeable. + +var hasSymbolToStringTagKinda = require('has-tostringtag/shams'); +hasSymbolToStringTagKinda() === true; // if the environment has a Symbol.toStringTag sham that mostly follows the spec. +``` + +## Supported Symbol shams + - get-own-property-symbols [npm](https://www.npmjs.com/package/get-own-property-symbols) | [github](https://github.com/WebReflection/get-own-property-symbols) + - core-js [npm](https://www.npmjs.com/package/core-js) | [github](https://github.com/zloirock/core-js) + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/has-tostringtag +[2]: https://versionbadg.es/inspect-js/has-tostringtag.svg +[5]: https://david-dm.org/inspect-js/has-tostringtag.svg +[6]: https://david-dm.org/inspect-js/has-tostringtag +[7]: https://david-dm.org/inspect-js/has-tostringtag/dev-status.svg +[8]: https://david-dm.org/inspect-js/has-tostringtag#info=devDependencies +[11]: https://nodei.co/npm/has-tostringtag.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/has-tostringtag.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/has-tostringtag.svg +[downloads-url]: https://npm-stat.com/charts.html?package=has-tostringtag +[codecov-image]: https://codecov.io/gh/inspect-js/has-tostringtag/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/has-tostringtag/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-tostringtag +[actions-url]: https://github.com/inspect-js/has-tostringtag/actions diff --git a/node_modules/has-tostringtag/index.d.ts b/node_modules/has-tostringtag/index.d.ts new file mode 100644 index 0000000..a61bc60 --- /dev/null +++ b/node_modules/has-tostringtag/index.d.ts @@ -0,0 +1,3 @@ +declare function hasToStringTag(): boolean; + +export = hasToStringTag; diff --git a/node_modules/has-tostringtag/index.js b/node_modules/has-tostringtag/index.js new file mode 100644 index 0000000..77bfa00 --- /dev/null +++ b/node_modules/has-tostringtag/index.js @@ -0,0 +1,8 @@ +'use strict'; + +var hasSymbols = require('has-symbols'); + +/** @type {import('.')} */ +module.exports = function hasToStringTag() { + return hasSymbols() && typeof Symbol.toStringTag === 'symbol'; +}; diff --git a/node_modules/has-tostringtag/package.json b/node_modules/has-tostringtag/package.json new file mode 100644 index 0000000..e5b0300 --- /dev/null +++ b/node_modules/has-tostringtag/package.json @@ -0,0 +1,108 @@ +{ + "name": "has-tostringtag", + "version": "1.0.2", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "description": "Determine if the JS environment has `Symbol.toStringTag` support. Supports spec, or shams.", + "license": "MIT", + "main": "index.js", + "types": "./index.d.ts", + "exports": { + ".": [ + { + "types": "./index.d.ts", + "default": "./index.js" + }, + "./index.js" + ], + "./shams": [ + { + "types": "./shams.d.ts", + "default": "./shams.js" + }, + "./shams.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent lint", + "test": "npm run tests-only", + "posttest": "aud --production", + "tests-only": "npm run test:stock && npm run test:shams", + "test:stock": "nyc node test", + "test:staging": "nyc node --harmony --es-staging test", + "test:shams": "npm run --silent test:shams:getownpropertysymbols && npm run --silent test:shams:corejs", + "test:shams:corejs": "nyc node test/shams/core-js.js", + "test:shams:getownpropertysymbols": "nyc node test/shams/get-own-property-symbols.js", + "lint": "eslint --ext=js,mjs .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/has-tostringtag.git" + }, + "bugs": { + "url": "https://github.com/inspect-js/has-tostringtag/issues" + }, + "homepage": "https://github.com/inspect-js/has-tostringtag#readme", + "keywords": [ + "javascript", + "ecmascript", + "symbol", + "symbols", + "tostringtag", + "Symbol.toStringTag" + ], + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@types/has-symbols": "^1.0.2", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "core-js": "^2.6.12", + "eslint": "=8.8.0", + "get-own-property-symbols": "^0.9.5", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.4", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "dependencies": { + "has-symbols": "^1.0.3" + } +} diff --git a/node_modules/has-tostringtag/shams.d.ts b/node_modules/has-tostringtag/shams.d.ts new file mode 100644 index 0000000..ea4aeec --- /dev/null +++ b/node_modules/has-tostringtag/shams.d.ts @@ -0,0 +1,3 @@ +declare function hasToStringTagShams(): boolean; + +export = hasToStringTagShams; diff --git a/node_modules/has-tostringtag/shams.js b/node_modules/has-tostringtag/shams.js new file mode 100644 index 0000000..809580d --- /dev/null +++ b/node_modules/has-tostringtag/shams.js @@ -0,0 +1,8 @@ +'use strict'; + +var hasSymbols = require('has-symbols/shams'); + +/** @type {import('.')} */ +module.exports = function hasToStringTagShams() { + return hasSymbols() && !!Symbol.toStringTag; +}; diff --git a/node_modules/has-tostringtag/test/index.js b/node_modules/has-tostringtag/test/index.js new file mode 100644 index 0000000..0679afd --- /dev/null +++ b/node_modules/has-tostringtag/test/index.js @@ -0,0 +1,21 @@ +'use strict'; + +var test = require('tape'); +var hasSymbolToStringTag = require('../'); +var runSymbolTests = require('./tests'); + +test('interface', function (t) { + t.equal(typeof hasSymbolToStringTag, 'function', 'is a function'); + t.equal(typeof hasSymbolToStringTag(), 'boolean', 'returns a boolean'); + t.end(); +}); + +test('Symbol.toStringTag exists', { skip: !hasSymbolToStringTag() }, function (t) { + runSymbolTests(t); + t.end(); +}); + +test('Symbol.toStringTag does not exist', { skip: hasSymbolToStringTag() }, function (t) { + t.equal(typeof Symbol === 'undefined' ? 'undefined' : typeof Symbol.toStringTag, 'undefined', 'global Symbol.toStringTag is undefined'); + t.end(); +}); diff --git a/node_modules/has-tostringtag/test/shams/core-js.js b/node_modules/has-tostringtag/test/shams/core-js.js new file mode 100644 index 0000000..7ab214d --- /dev/null +++ b/node_modules/has-tostringtag/test/shams/core-js.js @@ -0,0 +1,31 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol') { + test('has native Symbol.toStringTag support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol.toStringTag, 'symbol'); + t.end(); + }); + // @ts-expect-error CJS has top-level return + return; +} + +var hasSymbolToStringTag = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbolToStringTag(), false, 'hasSymbolToStringTag is false before polyfilling'); + // @ts-expect-error no types defined + require('core-js/fn/symbol'); + // @ts-expect-error no types defined + require('core-js/fn/symbol/to-string-tag'); + + require('../tests')(t); + + var hasToStringTagAfter = hasSymbolToStringTag(); + t.equal(hasToStringTagAfter, true, 'hasSymbolToStringTag is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/node_modules/has-tostringtag/test/shams/get-own-property-symbols.js b/node_modules/has-tostringtag/test/shams/get-own-property-symbols.js new file mode 100644 index 0000000..c8af44c --- /dev/null +++ b/node_modules/has-tostringtag/test/shams/get-own-property-symbols.js @@ -0,0 +1,30 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + test('has native Symbol support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol(), 'symbol'); + t.end(); + }); + // @ts-expect-error CJS has top-level return + return; +} + +var hasSymbolToStringTag = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbolToStringTag(), false, 'hasSymbolToStringTag is false before polyfilling'); + + // @ts-expect-error no types defined + require('get-own-property-symbols'); + + require('../tests')(t); + + var hasToStringTagAfter = hasSymbolToStringTag(); + t.equal(hasToStringTagAfter, true, 'hasSymbolToStringTag is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/node_modules/has-tostringtag/test/tests.js b/node_modules/has-tostringtag/test/tests.js new file mode 100644 index 0000000..2aa0d48 --- /dev/null +++ b/node_modules/has-tostringtag/test/tests.js @@ -0,0 +1,15 @@ +'use strict'; + +// eslint-disable-next-line consistent-return +module.exports = /** @type {(t: import('tape').Test) => void | false} */ function runSymbolTests(t) { + t.equal(typeof Symbol, 'function', 'global Symbol is a function'); + t.ok(Symbol.toStringTag, 'Symbol.toStringTag exists'); + + if (typeof Symbol !== 'function' || !Symbol.toStringTag) { return false; } + + /** @type {{ [Symbol.toStringTag]?: 'test'}} */ + var obj = {}; + obj[Symbol.toStringTag] = 'test'; + + t.equal(Object.prototype.toString.call(obj), '[object test]'); +}; diff --git a/node_modules/has-tostringtag/tsconfig.json b/node_modules/has-tostringtag/tsconfig.json new file mode 100644 index 0000000..2002ce5 --- /dev/null +++ b/node_modules/has-tostringtag/tsconfig.json @@ -0,0 +1,49 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + + /* Language and Environment */ + "target": "ESNext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + "typeRoots": ["types"], /* Specify multiple folders that act like './node_modules/@types'. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 0, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + + /* Completeness */ + //"skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": [ + "coverage" + ] +} diff --git a/node_modules/hasown/.eslintrc b/node_modules/hasown/.eslintrc new file mode 100644 index 0000000..3b5d9e9 --- /dev/null +++ b/node_modules/hasown/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/node_modules/hasown/.github/FUNDING.yml b/node_modules/hasown/.github/FUNDING.yml new file mode 100644 index 0000000..d68c8b7 --- /dev/null +++ b/node_modules/hasown/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/hasown +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/hasown/.nycrc b/node_modules/hasown/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/hasown/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/hasown/CHANGELOG.md b/node_modules/hasown/CHANGELOG.md new file mode 100644 index 0000000..2b0a980 --- /dev/null +++ b/node_modules/hasown/CHANGELOG.md @@ -0,0 +1,40 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v2.0.2](https://github.com/inspect-js/hasOwn/compare/v2.0.1...v2.0.2) - 2024-03-10 + +### Commits + +- [types] use shared config [`68e9d4d`](https://github.com/inspect-js/hasOwn/commit/68e9d4dab6facb4f05f02c6baea94a3f2a4e44b2) +- [actions] remove redundant finisher; use reusable workflow [`241a68e`](https://github.com/inspect-js/hasOwn/commit/241a68e13ea1fe52bec5ba7f74144befc31fae7b) +- [Tests] increase coverage [`4125c0d`](https://github.com/inspect-js/hasOwn/commit/4125c0d6121db56ae30e38346dfb0c000b04f0a7) +- [Tests] skip `npm ls` in old node due to TS [`01b9282`](https://github.com/inspect-js/hasOwn/commit/01b92822f9971dea031eafdd14767df41d61c202) +- [types] improve predicate type [`d340f85`](https://github.com/inspect-js/hasOwn/commit/d340f85ce02e286ef61096cbbb6697081d40a12b) +- [Dev Deps] update `tape` [`70089fc`](https://github.com/inspect-js/hasOwn/commit/70089fcf544e64acc024cbe60f5a9b00acad86de) +- [Tests] use `@arethetypeswrong/cli` [`50b272c`](https://github.com/inspect-js/hasOwn/commit/50b272c829f40d053a3dd91c9796e0ac0b2af084) + +## [v2.0.1](https://github.com/inspect-js/hasOwn/compare/v2.0.0...v2.0.1) - 2024-02-10 + +### Commits + +- [types] use a handwritten d.ts file; fix exported type [`012b989`](https://github.com/inspect-js/hasOwn/commit/012b9898ccf91dc441e2ebf594ff70270a5fda58) +- [Dev Deps] update `@types/function-bind`, `@types/mock-property`, `@types/tape`, `aud`, `mock-property`, `npmignore`, `tape`, `typescript` [`977a56f`](https://github.com/inspect-js/hasOwn/commit/977a56f51a1f8b20566f3c471612137894644025) +- [meta] add `sideEffects` flag [`3a60b7b`](https://github.com/inspect-js/hasOwn/commit/3a60b7bf42fccd8c605e5f145a6fcc83b13cb46f) + +## [v2.0.0](https://github.com/inspect-js/hasOwn/compare/v1.0.1...v2.0.0) - 2023-10-19 + +### Commits + +- revamped implementation, tests, readme [`72bf8b3`](https://github.com/inspect-js/hasOwn/commit/72bf8b338e77a638f0a290c63ffaed18339c36b4) +- [meta] revamp package.json [`079775f`](https://github.com/inspect-js/hasOwn/commit/079775fb1ec72c1c6334069593617a0be3847458) +- Only apps should have lockfiles [`6640e23`](https://github.com/inspect-js/hasOwn/commit/6640e233d1bb8b65260880f90787637db157d215) + +## v1.0.1 - 2023-10-10 + +### Commits + +- Initial commit [`8dbfde6`](https://github.com/inspect-js/hasOwn/commit/8dbfde6e8fb0ebb076fab38d138f2984eb340a62) diff --git a/node_modules/hasown/LICENSE b/node_modules/hasown/LICENSE new file mode 100644 index 0000000..0314929 --- /dev/null +++ b/node_modules/hasown/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Jordan Harband and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/hasown/README.md b/node_modules/hasown/README.md new file mode 100644 index 0000000..f759b8a --- /dev/null +++ b/node_modules/hasown/README.md @@ -0,0 +1,40 @@ +# hasown [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +A robust, ES3 compatible, "has own property" predicate. + +## Example + +```js +const assert = require('assert'); +const hasOwn = require('hasown'); + +assert.equal(hasOwn({}, 'toString'), false); +assert.equal(hasOwn([], 'length'), true); +assert.equal(hasOwn({ a: 42 }, 'a'), true); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/hasown +[npm-version-svg]: https://versionbadg.es/inspect-js/hasown.svg +[deps-svg]: https://david-dm.org/inspect-js/hasOwn.svg +[deps-url]: https://david-dm.org/inspect-js/hasOwn +[dev-deps-svg]: https://david-dm.org/inspect-js/hasOwn/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/hasOwn#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/hasown.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/hasown.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/hasown.svg +[downloads-url]: https://npm-stat.com/charts.html?package=hasown +[codecov-image]: https://codecov.io/gh/inspect-js/hasOwn/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/hasOwn/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/hasOwn +[actions-url]: https://github.com/inspect-js/hasOwn/actions diff --git a/node_modules/hasown/index.d.ts b/node_modules/hasown/index.d.ts new file mode 100644 index 0000000..aafdf3b --- /dev/null +++ b/node_modules/hasown/index.d.ts @@ -0,0 +1,3 @@ +declare function hasOwn(o: O, p: K): o is O & Record; + +export = hasOwn; diff --git a/node_modules/hasown/index.js b/node_modules/hasown/index.js new file mode 100644 index 0000000..34e6059 --- /dev/null +++ b/node_modules/hasown/index.js @@ -0,0 +1,8 @@ +'use strict'; + +var call = Function.prototype.call; +var $hasOwn = Object.prototype.hasOwnProperty; +var bind = require('function-bind'); + +/** @type {import('.')} */ +module.exports = bind.call(call, $hasOwn); diff --git a/node_modules/hasown/package.json b/node_modules/hasown/package.json new file mode 100644 index 0000000..8502e13 --- /dev/null +++ b/node_modules/hasown/package.json @@ -0,0 +1,92 @@ +{ + "name": "hasown", + "version": "2.0.2", + "description": "A robust, ES3 compatible, \"has own property\" predicate.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "types": "index.d.ts", + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "npm run tsc", + "pretest": "npm run lint", + "tsc": "tsc -p .", + "posttsc": "attw -P", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/hasOwn.git" + }, + "keywords": [ + "has", + "hasOwnProperty", + "hasOwn", + "has-own", + "own", + "has", + "property", + "in", + "javascript", + "ecmascript" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/hasOwn/issues" + }, + "homepage": "https://github.com/inspect-js/hasOwn#readme", + "dependencies": { + "function-bind": "^1.1.2" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.15.1", + "@ljharb/eslint-config": "^21.1.0", + "@ljharb/tsconfig": "^0.2.0", + "@types/function-bind": "^1.1.10", + "@types/mock-property": "^1.0.2", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "mock-property": "^1.0.3", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.5", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "test" + ] + } +} diff --git a/node_modules/hasown/tsconfig.json b/node_modules/hasown/tsconfig.json new file mode 100644 index 0000000..0930c56 --- /dev/null +++ b/node_modules/hasown/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "@ljharb/tsconfig", + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/html-entities/LICENSE b/node_modules/html-entities/LICENSE new file mode 100644 index 0000000..d565fb3 --- /dev/null +++ b/node_modules/html-entities/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2021 Dulin Marat + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/html-entities/README.md b/node_modules/html-entities/README.md new file mode 100644 index 0000000..06576a7 --- /dev/null +++ b/node_modules/html-entities/README.md @@ -0,0 +1,220 @@ +html-entities +============= + +Fastest HTML entities library. + +Comes with both TypeScript and Flow types. + +Installation +------------ + +```bash +$ npm install html-entities +``` + +Usage +----- + +### encode(text, options) + +Encodes text replacing HTML special characters (`<>&"'`) and/or other character ranges depending on `mode` option value. + +```js +import {encode} from 'html-entities'; + +encode('< > " \' & © ∆'); +// -> '< > " ' & © ∆' + +encode('< ©', {mode: 'nonAsciiPrintable'}); +// -> '< ©' + +encode('< ©', {mode: 'nonAsciiPrintable', level: 'xml'}); +// -> '< ©' + +encode('< > " \' & ©', {mode: 'nonAsciiPrintableOnly', level: 'xml'}); +// -> '< > " \' & ©' +``` + +Options: + +#### level + + * `all` alias to `html5` (default). + * `html5` uses `HTML5` named references. + * `html4` uses `HTML4` named references. + * `xml` uses `XML` named references. + +#### mode + + * `specialChars` encodes only HTML special characters (default). + * `nonAscii` encodes HTML special characters and everything outside the [ASCII character range](https://en.wikipedia.org/wiki/ASCII). + * `nonAsciiPrintable` encodes HTML special characters and everything outiside of the [ASCII printable characters](https://en.wikipedia.org/wiki/ASCII#Printable_characters). + * `nonAsciiPrintableOnly` everything outiside of the [ASCII printable characters](https://en.wikipedia.org/wiki/ASCII#Printable_characters) keeping HTML special characters intact. + * `extensive` encodes all non-printable characters, non-ASCII characters and all characters with named references. + +#### numeric + + * `decimal` uses decimal numbers when encoding html entities. i.e. `©` (default). + * `hexadecimal` uses hexadecimal numbers when encoding html entities. i.e. `©`. + + +### decode(text, options) + +Decodes text replacing entities to characters. Unknown entities are left as is. + +```js +import {decode} from 'html-entities'; + +decode('< > " ' & © ∆'); +// -> '< > " \' & © ∆' + +decode('©', {level: 'html5'}); +// -> '©' + +decode('©', {level: 'xml'}); +// -> '©' +``` + +Options: + +#### level + + * `all` alias to `html5` (default). + * `html5` uses `HTML5` named references. + * `html4` uses `HTML4` named references. + * `xml` uses `XML` named references. + +#### scope + + * `body` emulates behavior of browser when parsing tag bodies: entities without semicolon are also replaced (default). + * `attribute` emulates behavior of browser when parsing tag attributes: entities without semicolon are replaced when not followed by equality sign `=`. + * `strict` ignores entities without semicolon. + +### decodeEntity(text, options) + +Decodes a single HTML entity. Unknown entitiy is left as is. + +```js +import {decodeEntity} from 'html-entities'; + +decodeEntity('<'); +// -> '<' + +decodeEntity('©', {level: 'html5'}); +// -> '©' + +decodeEntity('©', {level: 'xml'}); +// -> '©' +``` + +Options: + +#### level + + * `all` alias to `html5` (default). + * `html5` uses `HTML5` named references. + * `html4` uses `HTML4` named references. + * `xml` uses `XML` named references. + +Performance +----------- + +Statistically significant comparison with other libraries using `benchmark.js`. +Results by this library are marked with `*`. +The source code of the benchmark is available at `benchmark/benchmark.ts`. + +``` +Common + + Initialization / Load speed + + #1: he x 516 ops/sec ±5.71% (78 runs sampled) + * #2: html-entities x 407 ops/sec ±5.64% (81 runs sampled) + #3: entities x 352 ops/sec ±4.16% (80 runs sampled) + +HTML5 + + Encode test + + * #1: html-entities.encode - html5, extensive x 437,236 ops/sec ±0.90% (98 runs sampled) + #2: entities.encodeHTML x 335,714 ops/sec ±0.87% (92 runs sampled) + + Encode non-ASCII test + + * #1: html-entities.encode - html5, nonAscii x 749,246 ops/sec ±0.61% (96 runs sampled) + #2: entities.encodeNonAsciiHTML x 706,984 ops/sec ±1.06% (98 runs sampled) + * #3: html-entities.encode - html5, nonAsciiPrintable x 691,193 ops/sec ±4.47% (90 runs sampled) + #4: he.encode x 141,105 ops/sec ±0.87% (92 runs sampled) + + Decode test + + #1: entities.decodeHTML x 678,595 ops/sec ±1.28% (92 runs sampled) + #2: entities.decodeHTMLStrict x 684,372 ops/sec ±2.76% (82 runs sampled) + * #3: html-entities.decode - html5, strict x 485,664 ops/sec ±0.80% (94 runs sampled) + * #4: html-entities.decode - html5, body x 463,074 ops/sec ±1.11% (93 runs sampled) + * #5: html-entities.decode - html5, attribute x 456,185 ops/sec ±2.24% (91 runs sampled) + #6: he.decode x 302,668 ops/sec ±2.73% (90 runs sampled) + +HTML4 + + Encode test + + * #1: html-entities.encode - html4, nonAscii x 737,475 ops/sec ±1.04% (95 runs sampled) + * #2: html-entities.encode - html4, nonAsciiPrintable x 649,866 ops/sec ±4.28% (79 runs sampled) + * #3: html-entities.encode - html4, extensive x 202,337 ops/sec ±3.66% (64 runs sampled) + + Decode test + + * #1: html-entities.decode - html4, attribute x 529,674 ops/sec ±0.90% (90 runs sampled) + * #2: html-entities.decode - html4, body x 499,135 ops/sec ±2.27% (80 runs sampled) + * #3: html-entities.decode - html4, strict x 489,806 ops/sec ±4.37% (84 runs sampled) + +XML + + Encode test + + * #1: html-entities.encode - xml, nonAscii x 823,097 ops/sec ±0.75% (81 runs sampled) + * #2: html-entities.encode - xml, nonAsciiPrintable x 764,638 ops/sec ±0.93% (93 runs sampled) + #3: entities.encodeXML x 672,186 ops/sec ±1.51% (92 runs sampled) + * #4: html-entities.encode - xml, extensive x 376,870 ops/sec ±0.76% (77 runs sampled) + + Decode test + + #1: entities.decodeXML x 930,758 ops/sec ±2.90% (90 runs sampled) + * #2: html-entities.decode - xml, body x 617,321 ops/sec ±0.74% (83 runs sampled) + * #3: html-entities.decode - xml, attribute x 611,598 ops/sec ±0.50% (92 runs sampled) + * #4: html-entities.decode - xml, strict x 607,191 ops/sec ±2.30% (85 runs sampled) + +Escaping + + Escape test + + #1: entities.escapeUTF8 x 1,930,874 ops/sec ±0.80% (95 runs sampled) + #2: he.escape x 1,717,522 ops/sec ±0.75% (84 runs sampled) + * #3: html-entities.encode - xml, specialChars x 1,611,374 ops/sec ±1.30% (92 runs sampled) + #4: entities.escape x 673,710 ops/sec ±1.30% (94 runs sampled) +``` + +License +------- + +MIT + +Security contact information +---------------------------- + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). Tidelift will +coordinate the fix and disclosure. + +`html-entities` for enterprise +------------------------------ + +Available as part of the Tidelift Subscription + +The maintainers of `html-entities` and thousands of other packages are working with +Tidelift to deliver commercial support and maintenance for the open source +dependencies you use to build your applications. Save time, reduce risk, and +improve code health, while paying the maintainers of the exact dependencies you +use. +[Learn more.](https://tidelift.com/subscription/pkg/npm-html-entities?utm_source=npm-html-entities&utm_medium=referral&utm_campaign=enterprise) diff --git a/node_modules/html-entities/dist/commonjs/index.d.ts b/node_modules/html-entities/dist/commonjs/index.d.ts new file mode 100644 index 0000000..733c6ee --- /dev/null +++ b/node_modules/html-entities/dist/commonjs/index.d.ts @@ -0,0 +1,20 @@ +export type Level = 'xml' | 'html4' | 'html5' | 'all'; +interface CommonOptions { + level?: Level; +} +export type EncodeMode = 'specialChars' | 'nonAscii' | 'nonAsciiPrintable' | 'nonAsciiPrintableOnly' | 'extensive'; +export interface EncodeOptions extends CommonOptions { + mode?: EncodeMode; + numeric?: 'decimal' | 'hexadecimal'; +} +export type DecodeScope = 'strict' | 'body' | 'attribute'; +export interface DecodeOptions extends CommonOptions { + scope?: DecodeScope; +} +/** Encodes all the necessary (specified by `level`) characters in the text */ +export declare function encode(text: string | undefined | null, { mode, numeric, level }?: EncodeOptions): string; +/** Decodes a single entity */ +export declare function decodeEntity(entity: string | undefined | null, { level }?: CommonOptions): string; +/** Decodes all entities in the text */ +export declare function decode(text: string | undefined | null, { level, scope }?: DecodeOptions): string; +export {}; diff --git a/node_modules/html-entities/dist/commonjs/index.js b/node_modules/html-entities/dist/commonjs/index.js new file mode 100644 index 0000000..f871ed4 --- /dev/null +++ b/node_modules/html-entities/dist/commonjs/index.js @@ -0,0 +1,129 @@ +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encode = encode; +exports.decodeEntity = decodeEntity; +exports.decode = decode; +var named_references_js_1 = require("./named-references.js"); +var numeric_unicode_map_js_1 = require("./numeric-unicode-map.js"); +var surrogate_pairs_js_1 = require("./surrogate-pairs.js"); +var allNamedReferences = __assign(__assign({}, named_references_js_1.namedReferences), { all: named_references_js_1.namedReferences.html5 }); +var encodeRegExps = { + specialChars: /[<>'"&]/g, + nonAscii: /[<>'"&\u0080-\uD7FF\uE000-\uFFFF\uDC00-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g, + nonAsciiPrintable: /[<>'"&\x01-\x08\x11-\x15\x17-\x1F\x7f-\uD7FF\uE000-\uFFFF\uDC00-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g, + nonAsciiPrintableOnly: /[\x01-\x08\x11-\x15\x17-\x1F\x7f-\uD7FF\uE000-\uFFFF\uDC00-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g, + extensive: /[\x01-\x0c\x0e-\x1f\x21-\x2c\x2e-\x2f\x3a-\x40\x5b-\x60\x7b-\x7d\x7f-\uD7FF\uE000-\uFFFF\uDC00-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g +}; +var defaultEncodeOptions = { + mode: 'specialChars', + level: 'all', + numeric: 'decimal' +}; +/** Encodes all the necessary (specified by `level`) characters in the text */ +function encode(text, _a) { + var _b = _a === void 0 ? defaultEncodeOptions : _a, _c = _b.mode, mode = _c === void 0 ? 'specialChars' : _c, _d = _b.numeric, numeric = _d === void 0 ? 'decimal' : _d, _e = _b.level, level = _e === void 0 ? 'all' : _e; + if (!text) { + return ''; + } + var encodeRegExp = encodeRegExps[mode]; + var references = allNamedReferences[level].characters; + var isHex = numeric === 'hexadecimal'; + return String.prototype.replace.call(text, encodeRegExp, function (input) { + var result = references[input]; + if (!result) { + var code = input.length > 1 ? (0, surrogate_pairs_js_1.getCodePoint)(input, 0) : input.charCodeAt(0); + result = (isHex ? '&#x' + code.toString(16) : '&#' + code) + ';'; + } + return result; + }); +} +var defaultDecodeOptions = { + scope: 'body', + level: 'all' +}; +var strict = /&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);/g; +var attribute = /&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+)[;=]?/g; +var baseDecodeRegExps = { + xml: { + strict: strict, + attribute: attribute, + body: named_references_js_1.bodyRegExps.xml + }, + html4: { + strict: strict, + attribute: attribute, + body: named_references_js_1.bodyRegExps.html4 + }, + html5: { + strict: strict, + attribute: attribute, + body: named_references_js_1.bodyRegExps.html5 + } +}; +var decodeRegExps = __assign(__assign({}, baseDecodeRegExps), { all: baseDecodeRegExps.html5 }); +var fromCharCode = String.fromCharCode; +var outOfBoundsChar = fromCharCode(65533); +var defaultDecodeEntityOptions = { + level: 'all' +}; +function getDecodedEntity(entity, references, isAttribute, isStrict) { + var decodeResult = entity; + var decodeEntityLastChar = entity[entity.length - 1]; + if (isAttribute && decodeEntityLastChar === '=') { + decodeResult = entity; + } + else if (isStrict && decodeEntityLastChar !== ';') { + decodeResult = entity; + } + else { + var decodeResultByReference = references[entity]; + if (decodeResultByReference) { + decodeResult = decodeResultByReference; + } + else if (entity[0] === '&' && entity[1] === '#') { + var decodeSecondChar = entity[2]; + var decodeCode = decodeSecondChar == 'x' || decodeSecondChar == 'X' + ? parseInt(entity.substr(3), 16) + : parseInt(entity.substr(2)); + decodeResult = + decodeCode >= 0x10ffff + ? outOfBoundsChar + : decodeCode > 65535 + ? (0, surrogate_pairs_js_1.fromCodePoint)(decodeCode) + : fromCharCode(numeric_unicode_map_js_1.numericUnicodeMap[decodeCode] || decodeCode); + } + } + return decodeResult; +} +/** Decodes a single entity */ +function decodeEntity(entity, _a) { + var _b = _a === void 0 ? defaultDecodeEntityOptions : _a, _c = _b.level, level = _c === void 0 ? 'all' : _c; + if (!entity) { + return ''; + } + return getDecodedEntity(entity, allNamedReferences[level].entities, false, false); +} +/** Decodes all entities in the text */ +function decode(text, _a) { + var _b = _a === void 0 ? defaultDecodeOptions : _a, _c = _b.level, level = _c === void 0 ? 'all' : _c, _d = _b.scope, scope = _d === void 0 ? level === 'xml' ? 'strict' : 'body' : _d; + if (!text) { + return ''; + } + var decodeRegExp = decodeRegExps[level][scope]; + var references = allNamedReferences[level].entities; + var isAttribute = scope === 'attribute'; + var isStrict = scope === 'strict'; + return text.replace(decodeRegExp, function (entity) { return getDecodedEntity(entity, references, isAttribute, isStrict); }); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/html-entities/dist/commonjs/index.js.flow b/node_modules/html-entities/dist/commonjs/index.js.flow new file mode 100644 index 0000000..7311bd2 --- /dev/null +++ b/node_modules/html-entities/dist/commonjs/index.js.flow @@ -0,0 +1,52 @@ +/** + * Flowtype definitions for index + * Generated by Flowgen from a Typescript Definition + * Flowgen v1.13.0 + * @flow + */ + +export type Level = "xml" | "html4" | "html5" | "all"; +declare interface CommonOptions { + level?: Level; +} +export type EncodeMode = + | "specialChars" + | "nonAscii" + | "nonAsciiPrintable" + | "nonAsciiPrintableOnly" + | "extensive"; +export type EncodeOptions = { + mode?: EncodeMode, + numeric?: "decimal" | "hexadecimal", + ... +} & CommonOptions; +export type DecodeScope = "strict" | "body" | "attribute"; +export type DecodeOptions = { + scope?: DecodeScope, + ... +} & CommonOptions; + +/** + * Encodes all the necessary (specified by `level`) characters in the text + */ +declare export function encode( + text: string | void | null, + x?: EncodeOptions +): string; + +/** + * Decodes a single entity + */ +declare export function decodeEntity( + entity: string | void | null, + x?: CommonOptions +): string; + +/** + * Decodes all entities in the text + */ +declare export function decode( + text: string | void | null, + x?: DecodeOptions +): string; +declare export {}; diff --git a/node_modules/html-entities/dist/commonjs/index.js.map b/node_modules/html-entities/dist/commonjs/index.js.map new file mode 100644 index 0000000..1dba6ac --- /dev/null +++ b/node_modules/html-entities/dist/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;AA2CA,wBAoBC;AA2ED,oCAQC;AAGD,wBAcC;AAnKD,6DAAmE;AACnE,mEAA2D;AAC3D,2DAAiE;AAEjE,IAAM,kBAAkB,yBACjB,qCAAe,KAClB,GAAG,EAAE,qCAAe,CAAC,KAAK,GAC7B,CAAC;AAqBF,IAAM,aAAa,GAA+B;IAC9C,YAAY,EAAE,UAAU;IACxB,QAAQ,EAAE,iFAAiF;IAC3F,iBAAiB,EAAE,0GAA0G;IAC7H,qBAAqB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K,KAAK,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,KAAA;IAE3D,IAAI,CAAC,IAAI,EAAE,CAAC;QACR,OAAO,EAAE,CAAC;IACd,CAAC;IAED,IAAM,YAAY,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;IACjD,IAAM,UAAU,GAAG,kBAAkB,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC;IACtD,IAAM,WAAW,GAAG,KAAK,KAAK,WAAW,CAAC;IAC1C,IAAM,QAAQ,GAAG,KAAK,KAAK,QAAQ,CAAC;IAEpC,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY,EAAE,UAAC,MAAM,IAAK,OAAA,gBAAgB,CAAC,MAAM,EAAE,UAAU,EAAE,WAAW,EAAE,QAAQ,CAAC,EAA3D,CAA2D,CAAC,CAAC;AAC/G,CAAC"} \ No newline at end of file diff --git a/node_modules/html-entities/dist/commonjs/named-references.js b/node_modules/html-entities/dist/commonjs/named-references.js new file mode 100644 index 0000000..cfa831f --- /dev/null +++ b/node_modules/html-entities/dist/commonjs/named-references.js @@ -0,0 +1,50 @@ +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.namedReferences = exports.bodyRegExps = void 0; +// This file is autogenerated by tools/process-named-references.ts +var pairDivider = "~"; +var blockDivider = "~~"; +function generateNamedReferences(input, prev) { + var entities = {}; + var characters = {}; + var blocks = input.split(blockDivider); + var isOptionalBlock = false; + for (var i = 0; blocks.length > i; i++) { + var entries = blocks[i].split(pairDivider); + for (var j = 0; j < entries.length; j += 2) { + var entity = entries[j]; + var character = entries[j + 1]; + var fullEntity = '&' + entity + ';'; + entities[fullEntity] = character; + if (isOptionalBlock) { + entities['&' + entity] = character; + } + characters[character] = fullEntity; + } + isOptionalBlock = true; + } + return prev ? + { entities: __assign(__assign({}, entities), prev.entities), characters: __assign(__assign({}, characters), prev.characters) } : + { entities: entities, characters: characters }; +} +exports.bodyRegExps = { + xml: /&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g, + html4: /∉|&(?:nbsp|iexcl|cent|pound|curren|yen|brvbar|sect|uml|copy|ordf|laquo|not|shy|reg|macr|deg|plusmn|sup2|sup3|acute|micro|para|middot|cedil|sup1|ordm|raquo|frac14|frac12|frac34|iquest|Agrave|Aacute|Acirc|Atilde|Auml|Aring|AElig|Ccedil|Egrave|Eacute|Ecirc|Euml|Igrave|Iacute|Icirc|Iuml|ETH|Ntilde|Ograve|Oacute|Ocirc|Otilde|Ouml|times|Oslash|Ugrave|Uacute|Ucirc|Uuml|Yacute|THORN|szlig|agrave|aacute|acirc|atilde|auml|aring|aelig|ccedil|egrave|eacute|ecirc|euml|igrave|iacute|icirc|iuml|eth|ntilde|ograve|oacute|ocirc|otilde|ouml|divide|oslash|ugrave|uacute|ucirc|uuml|yacute|thorn|yuml|quot|amp|lt|gt|#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g, + html5: /·|℗|⋇|⪧|⩺|⋗|⦕|⩼|⪆|⥸|⋗|⋛|⪌|≷|≳|⪦|⩹|⋖|⋋|⋉|⥶|⩻|⦖|◃|⊴|◂|∉|⋹̸|⋵̸|∉|⋷|⋶|∌|∌|⋾|⋽|∥|⊠|⨱|⨰|&(?:AElig|AMP|Aacute|Acirc|Agrave|Aring|Atilde|Auml|COPY|Ccedil|ETH|Eacute|Ecirc|Egrave|Euml|GT|Iacute|Icirc|Igrave|Iuml|LT|Ntilde|Oacute|Ocirc|Ograve|Oslash|Otilde|Ouml|QUOT|REG|THORN|Uacute|Ucirc|Ugrave|Uuml|Yacute|aacute|acirc|acute|aelig|agrave|amp|aring|atilde|auml|brvbar|ccedil|cedil|cent|copy|curren|deg|divide|eacute|ecirc|egrave|eth|euml|frac12|frac14|frac34|gt|iacute|icirc|iexcl|igrave|iquest|iuml|laquo|lt|macr|micro|middot|nbsp|not|ntilde|oacute|ocirc|ograve|ordf|ordm|oslash|otilde|ouml|para|plusmn|pound|quot|raquo|reg|sect|shy|sup1|sup2|sup3|szlig|thorn|times|uacute|ucirc|ugrave|uml|uuml|yacute|yen|yuml|#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g +}; +exports.namedReferences = {}; +exports.namedReferences['xml'] = generateNamedReferences("lt~<~gt~>~quot~\"~apos~'~amp~&"); +exports.namedReferences['html4'] = generateNamedReferences("apos~'~OElig~Œ~oelig~œ~Scaron~Š~scaron~š~Yuml~Ÿ~circ~ˆ~tilde~˜~ensp~ ~emsp~ ~thinsp~ ~zwnj~‌~zwj~‍~lrm~‎~rlm~‏~ndash~–~mdash~—~lsquo~‘~rsquo~’~sbquo~‚~ldquo~“~rdquo~”~bdquo~„~dagger~†~Dagger~‡~permil~‰~lsaquo~‹~rsaquo~›~euro~€~fnof~ƒ~Alpha~Α~Beta~Β~Gamma~Γ~Delta~Δ~Epsilon~Ε~Zeta~Ζ~Eta~Η~Theta~Θ~Iota~Ι~Kappa~Κ~Lambda~Λ~Mu~Μ~Nu~Ν~Xi~Ξ~Omicron~Ο~Pi~Π~Rho~Ρ~Sigma~Σ~Tau~Τ~Upsilon~Υ~Phi~Φ~Chi~Χ~Psi~Ψ~Omega~Ω~alpha~α~beta~β~gamma~γ~delta~δ~epsilon~ε~zeta~ζ~eta~η~theta~θ~iota~ι~kappa~κ~lambda~λ~mu~μ~nu~ν~xi~ξ~omicron~ο~pi~π~rho~ρ~sigmaf~ς~sigma~σ~tau~τ~upsilon~υ~phi~φ~chi~χ~psi~ψ~omega~ω~thetasym~ϑ~upsih~ϒ~piv~ϖ~bull~•~hellip~…~prime~′~Prime~″~oline~‾~frasl~⁄~weierp~℘~image~ℑ~real~ℜ~trade~™~alefsym~ℵ~larr~←~uarr~↑~rarr~→~darr~↓~harr~↔~crarr~↵~lArr~⇐~uArr~⇑~rArr~⇒~dArr~⇓~hArr~⇔~forall~∀~part~∂~exist~∃~empty~∅~nabla~∇~isin~∈~notin~∉~ni~∋~prod~∏~sum~∑~minus~−~lowast~∗~radic~√~prop~∝~infin~∞~ang~∠~and~∧~or~∨~cap~∩~cup~∪~int~∫~there4~∴~sim~∼~cong~≅~asymp~≈~ne~≠~equiv~≡~le~≤~ge~≥~sub~⊂~sup~⊃~nsub~⊄~sube~⊆~supe~⊇~oplus~⊕~otimes~⊗~perp~⊥~sdot~⋅~lceil~⌈~rceil~⌉~lfloor~⌊~rfloor~⌋~lang~〈~rang~〉~loz~◊~spades~♠~clubs~♣~hearts~♥~diams~♦~~nbsp~ ~iexcl~¡~cent~¢~pound~£~curren~¤~yen~¥~brvbar~¦~sect~§~uml~¨~copy~©~ordf~ª~laquo~«~not~¬~shy~­~reg~®~macr~¯~deg~°~plusmn~±~sup2~²~sup3~³~acute~´~micro~µ~para~¶~middot~·~cedil~¸~sup1~¹~ordm~º~raquo~»~frac14~¼~frac12~½~frac34~¾~iquest~¿~Agrave~À~Aacute~Á~Acirc~Â~Atilde~Ã~Auml~Ä~Aring~Å~AElig~Æ~Ccedil~Ç~Egrave~È~Eacute~É~Ecirc~Ê~Euml~Ë~Igrave~Ì~Iacute~Í~Icirc~Î~Iuml~Ï~ETH~Ð~Ntilde~Ñ~Ograve~Ò~Oacute~Ó~Ocirc~Ô~Otilde~Õ~Ouml~Ö~times~×~Oslash~Ø~Ugrave~Ù~Uacute~Ú~Ucirc~Û~Uuml~Ü~Yacute~Ý~THORN~Þ~szlig~ß~agrave~à~aacute~á~acirc~â~atilde~ã~auml~ä~aring~å~aelig~æ~ccedil~ç~egrave~è~eacute~é~ecirc~ê~euml~ë~igrave~ì~iacute~í~icirc~î~iuml~ï~eth~ð~ntilde~ñ~ograve~ò~oacute~ó~ocirc~ô~otilde~õ~ouml~ö~divide~÷~oslash~ø~ugrave~ù~uacute~ú~ucirc~û~uuml~ü~yacute~ý~thorn~þ~yuml~ÿ~quot~\"~amp~&~lt~<~gt~>"); +exports.namedReferences['html5'] = generateNamedReferences("Abreve~Ă~Acy~А~Afr~𝔄~Amacr~Ā~And~⩓~Aogon~Ą~Aopf~𝔸~ApplyFunction~⁡~Ascr~𝒜~Assign~≔~Backslash~∖~Barv~⫧~Barwed~⌆~Bcy~Б~Because~∵~Bernoullis~ℬ~Bfr~𝔅~Bopf~𝔹~Breve~˘~Bscr~ℬ~Bumpeq~≎~CHcy~Ч~Cacute~Ć~Cap~⋒~CapitalDifferentialD~ⅅ~Cayleys~ℭ~Ccaron~Č~Ccirc~Ĉ~Cconint~∰~Cdot~Ċ~Cedilla~¸~CenterDot~·~Cfr~ℭ~CircleDot~⊙~CircleMinus~⊖~CirclePlus~⊕~CircleTimes~⊗~ClockwiseContourIntegral~∲~CloseCurlyDoubleQuote~”~CloseCurlyQuote~’~Colon~∷~Colone~⩴~Congruent~≡~Conint~∯~ContourIntegral~∮~Copf~ℂ~Coproduct~∐~CounterClockwiseContourIntegral~∳~Cross~⨯~Cscr~𝒞~Cup~⋓~CupCap~≍~DD~ⅅ~DDotrahd~⤑~DJcy~Ђ~DScy~Ѕ~DZcy~Џ~Darr~↡~Dashv~⫤~Dcaron~Ď~Dcy~Д~Del~∇~Dfr~𝔇~DiacriticalAcute~´~DiacriticalDot~˙~DiacriticalDoubleAcute~˝~DiacriticalGrave~`~DiacriticalTilde~˜~Diamond~⋄~DifferentialD~ⅆ~Dopf~𝔻~Dot~¨~DotDot~⃜~DotEqual~≐~DoubleContourIntegral~∯~DoubleDot~¨~DoubleDownArrow~⇓~DoubleLeftArrow~⇐~DoubleLeftRightArrow~⇔~DoubleLeftTee~⫤~DoubleLongLeftArrow~⟸~DoubleLongLeftRightArrow~⟺~DoubleLongRightArrow~⟹~DoubleRightArrow~⇒~DoubleRightTee~⊨~DoubleUpArrow~⇑~DoubleUpDownArrow~⇕~DoubleVerticalBar~∥~DownArrow~↓~DownArrowBar~⤓~DownArrowUpArrow~⇵~DownBreve~̑~DownLeftRightVector~⥐~DownLeftTeeVector~⥞~DownLeftVector~↽~DownLeftVectorBar~⥖~DownRightTeeVector~⥟~DownRightVector~⇁~DownRightVectorBar~⥗~DownTee~⊤~DownTeeArrow~↧~Downarrow~⇓~Dscr~𝒟~Dstrok~Đ~ENG~Ŋ~Ecaron~Ě~Ecy~Э~Edot~Ė~Efr~𝔈~Element~∈~Emacr~Ē~EmptySmallSquare~◻~EmptyVerySmallSquare~▫~Eogon~Ę~Eopf~𝔼~Equal~⩵~EqualTilde~≂~Equilibrium~⇌~Escr~ℰ~Esim~⩳~Exists~∃~ExponentialE~ⅇ~Fcy~Ф~Ffr~𝔉~FilledSmallSquare~◼~FilledVerySmallSquare~▪~Fopf~𝔽~ForAll~∀~Fouriertrf~ℱ~Fscr~ℱ~GJcy~Ѓ~Gammad~Ϝ~Gbreve~Ğ~Gcedil~Ģ~Gcirc~Ĝ~Gcy~Г~Gdot~Ġ~Gfr~𝔊~Gg~⋙~Gopf~𝔾~GreaterEqual~≥~GreaterEqualLess~⋛~GreaterFullEqual~≧~GreaterGreater~⪢~GreaterLess~≷~GreaterSlantEqual~⩾~GreaterTilde~≳~Gscr~𝒢~Gt~≫~HARDcy~Ъ~Hacek~ˇ~Hat~^~Hcirc~Ĥ~Hfr~ℌ~HilbertSpace~ℋ~Hopf~ℍ~HorizontalLine~─~Hscr~ℋ~Hstrok~Ħ~HumpDownHump~≎~HumpEqual~≏~IEcy~Е~IJlig~IJ~IOcy~Ё~Icy~И~Idot~İ~Ifr~ℑ~Im~ℑ~Imacr~Ī~ImaginaryI~ⅈ~Implies~⇒~Int~∬~Integral~∫~Intersection~⋂~InvisibleComma~⁣~InvisibleTimes~⁢~Iogon~Į~Iopf~𝕀~Iscr~ℐ~Itilde~Ĩ~Iukcy~І~Jcirc~Ĵ~Jcy~Й~Jfr~𝔍~Jopf~𝕁~Jscr~𝒥~Jsercy~Ј~Jukcy~Є~KHcy~Х~KJcy~Ќ~Kcedil~Ķ~Kcy~К~Kfr~𝔎~Kopf~𝕂~Kscr~𝒦~LJcy~Љ~Lacute~Ĺ~Lang~⟪~Laplacetrf~ℒ~Larr~↞~Lcaron~Ľ~Lcedil~Ļ~Lcy~Л~LeftAngleBracket~⟨~LeftArrow~←~LeftArrowBar~⇤~LeftArrowRightArrow~⇆~LeftCeiling~⌈~LeftDoubleBracket~⟦~LeftDownTeeVector~⥡~LeftDownVector~⇃~LeftDownVectorBar~⥙~LeftFloor~⌊~LeftRightArrow~↔~LeftRightVector~⥎~LeftTee~⊣~LeftTeeArrow~↤~LeftTeeVector~⥚~LeftTriangle~⊲~LeftTriangleBar~⧏~LeftTriangleEqual~⊴~LeftUpDownVector~⥑~LeftUpTeeVector~⥠~LeftUpVector~↿~LeftUpVectorBar~⥘~LeftVector~↼~LeftVectorBar~⥒~Leftarrow~⇐~Leftrightarrow~⇔~LessEqualGreater~⋚~LessFullEqual~≦~LessGreater~≶~LessLess~⪡~LessSlantEqual~⩽~LessTilde~≲~Lfr~𝔏~Ll~⋘~Lleftarrow~⇚~Lmidot~Ŀ~LongLeftArrow~⟵~LongLeftRightArrow~⟷~LongRightArrow~⟶~Longleftarrow~⟸~Longleftrightarrow~⟺~Longrightarrow~⟹~Lopf~𝕃~LowerLeftArrow~↙~LowerRightArrow~↘~Lscr~ℒ~Lsh~↰~Lstrok~Ł~Lt~≪~Map~⤅~Mcy~М~MediumSpace~ ~Mellintrf~ℳ~Mfr~𝔐~MinusPlus~∓~Mopf~𝕄~Mscr~ℳ~NJcy~Њ~Nacute~Ń~Ncaron~Ň~Ncedil~Ņ~Ncy~Н~NegativeMediumSpace~​~NegativeThickSpace~​~NegativeThinSpace~​~NegativeVeryThinSpace~​~NestedGreaterGreater~≫~NestedLessLess~≪~NewLine~\n~Nfr~𝔑~NoBreak~⁠~NonBreakingSpace~ ~Nopf~ℕ~Not~⫬~NotCongruent~≢~NotCupCap~≭~NotDoubleVerticalBar~∦~NotElement~∉~NotEqual~≠~NotEqualTilde~≂̸~NotExists~∄~NotGreater~≯~NotGreaterEqual~≱~NotGreaterFullEqual~≧̸~NotGreaterGreater~≫̸~NotGreaterLess~≹~NotGreaterSlantEqual~⩾̸~NotGreaterTilde~≵~NotHumpDownHump~≎̸~NotHumpEqual~≏̸~NotLeftTriangle~⋪~NotLeftTriangleBar~⧏̸~NotLeftTriangleEqual~⋬~NotLess~≮~NotLessEqual~≰~NotLessGreater~≸~NotLessLess~≪̸~NotLessSlantEqual~⩽̸~NotLessTilde~≴~NotNestedGreaterGreater~⪢̸~NotNestedLessLess~⪡̸~NotPrecedes~⊀~NotPrecedesEqual~⪯̸~NotPrecedesSlantEqual~⋠~NotReverseElement~∌~NotRightTriangle~⋫~NotRightTriangleBar~⧐̸~NotRightTriangleEqual~⋭~NotSquareSubset~⊏̸~NotSquareSubsetEqual~⋢~NotSquareSuperset~⊐̸~NotSquareSupersetEqual~⋣~NotSubset~⊂⃒~NotSubsetEqual~⊈~NotSucceeds~⊁~NotSucceedsEqual~⪰̸~NotSucceedsSlantEqual~⋡~NotSucceedsTilde~≿̸~NotSuperset~⊃⃒~NotSupersetEqual~⊉~NotTilde~≁~NotTildeEqual~≄~NotTildeFullEqual~≇~NotTildeTilde~≉~NotVerticalBar~∤~Nscr~𝒩~Ocy~О~Odblac~Ő~Ofr~𝔒~Omacr~Ō~Oopf~𝕆~OpenCurlyDoubleQuote~“~OpenCurlyQuote~‘~Or~⩔~Oscr~𝒪~Otimes~⨷~OverBar~‾~OverBrace~⏞~OverBracket~⎴~OverParenthesis~⏜~PartialD~∂~Pcy~П~Pfr~𝔓~PlusMinus~±~Poincareplane~ℌ~Popf~ℙ~Pr~⪻~Precedes~≺~PrecedesEqual~⪯~PrecedesSlantEqual~≼~PrecedesTilde~≾~Product~∏~Proportion~∷~Proportional~∝~Pscr~𝒫~Qfr~𝔔~Qopf~ℚ~Qscr~𝒬~RBarr~⤐~Racute~Ŕ~Rang~⟫~Rarr~↠~Rarrtl~⤖~Rcaron~Ř~Rcedil~Ŗ~Rcy~Р~Re~ℜ~ReverseElement~∋~ReverseEquilibrium~⇋~ReverseUpEquilibrium~⥯~Rfr~ℜ~RightAngleBracket~⟩~RightArrow~→~RightArrowBar~⇥~RightArrowLeftArrow~⇄~RightCeiling~⌉~RightDoubleBracket~⟧~RightDownTeeVector~⥝~RightDownVector~⇂~RightDownVectorBar~⥕~RightFloor~⌋~RightTee~⊢~RightTeeArrow~↦~RightTeeVector~⥛~RightTriangle~⊳~RightTriangleBar~⧐~RightTriangleEqual~⊵~RightUpDownVector~⥏~RightUpTeeVector~⥜~RightUpVector~↾~RightUpVectorBar~⥔~RightVector~⇀~RightVectorBar~⥓~Rightarrow~⇒~Ropf~ℝ~RoundImplies~⥰~Rrightarrow~⇛~Rscr~ℛ~Rsh~↱~RuleDelayed~⧴~SHCHcy~Щ~SHcy~Ш~SOFTcy~Ь~Sacute~Ś~Sc~⪼~Scedil~Ş~Scirc~Ŝ~Scy~С~Sfr~𝔖~ShortDownArrow~↓~ShortLeftArrow~←~ShortRightArrow~→~ShortUpArrow~↑~SmallCircle~∘~Sopf~𝕊~Sqrt~√~Square~□~SquareIntersection~⊓~SquareSubset~⊏~SquareSubsetEqual~⊑~SquareSuperset~⊐~SquareSupersetEqual~⊒~SquareUnion~⊔~Sscr~𝒮~Star~⋆~Sub~⋐~Subset~⋐~SubsetEqual~⊆~Succeeds~≻~SucceedsEqual~⪰~SucceedsSlantEqual~≽~SucceedsTilde~≿~SuchThat~∋~Sum~∑~Sup~⋑~Superset~⊃~SupersetEqual~⊇~Supset~⋑~TRADE~™~TSHcy~Ћ~TScy~Ц~Tab~\t~Tcaron~Ť~Tcedil~Ţ~Tcy~Т~Tfr~𝔗~Therefore~∴~ThickSpace~  ~ThinSpace~ ~Tilde~∼~TildeEqual~≃~TildeFullEqual~≅~TildeTilde~≈~Topf~𝕋~TripleDot~⃛~Tscr~𝒯~Tstrok~Ŧ~Uarr~↟~Uarrocir~⥉~Ubrcy~Ў~Ubreve~Ŭ~Ucy~У~Udblac~Ű~Ufr~𝔘~Umacr~Ū~UnderBar~_~UnderBrace~⏟~UnderBracket~⎵~UnderParenthesis~⏝~Union~⋃~UnionPlus~⊎~Uogon~Ų~Uopf~𝕌~UpArrow~↑~UpArrowBar~⤒~UpArrowDownArrow~⇅~UpDownArrow~↕~UpEquilibrium~⥮~UpTee~⊥~UpTeeArrow~↥~Uparrow~⇑~Updownarrow~⇕~UpperLeftArrow~↖~UpperRightArrow~↗~Upsi~ϒ~Uring~Ů~Uscr~𝒰~Utilde~Ũ~VDash~⊫~Vbar~⫫~Vcy~В~Vdash~⊩~Vdashl~⫦~Vee~⋁~Verbar~‖~Vert~‖~VerticalBar~∣~VerticalLine~|~VerticalSeparator~❘~VerticalTilde~≀~VeryThinSpace~ ~Vfr~𝔙~Vopf~𝕍~Vscr~𝒱~Vvdash~⊪~Wcirc~Ŵ~Wedge~⋀~Wfr~𝔚~Wopf~𝕎~Wscr~𝒲~Xfr~𝔛~Xopf~𝕏~Xscr~𝒳~YAcy~Я~YIcy~Ї~YUcy~Ю~Ycirc~Ŷ~Ycy~Ы~Yfr~𝔜~Yopf~𝕐~Yscr~𝒴~ZHcy~Ж~Zacute~Ź~Zcaron~Ž~Zcy~З~Zdot~Ż~ZeroWidthSpace~​~Zfr~ℨ~Zopf~ℤ~Zscr~𝒵~abreve~ă~ac~∾~acE~∾̳~acd~∿~acy~а~af~⁡~afr~𝔞~aleph~ℵ~amacr~ā~amalg~⨿~andand~⩕~andd~⩜~andslope~⩘~andv~⩚~ange~⦤~angle~∠~angmsd~∡~angmsdaa~⦨~angmsdab~⦩~angmsdac~⦪~angmsdad~⦫~angmsdae~⦬~angmsdaf~⦭~angmsdag~⦮~angmsdah~⦯~angrt~∟~angrtvb~⊾~angrtvbd~⦝~angsph~∢~angst~Å~angzarr~⍼~aogon~ą~aopf~𝕒~ap~≈~apE~⩰~apacir~⩯~ape~≊~apid~≋~approx~≈~approxeq~≊~ascr~𝒶~ast~*~asympeq~≍~awconint~∳~awint~⨑~bNot~⫭~backcong~≌~backepsilon~϶~backprime~‵~backsim~∽~backsimeq~⋍~barvee~⊽~barwed~⌅~barwedge~⌅~bbrk~⎵~bbrktbrk~⎶~bcong~≌~bcy~б~becaus~∵~because~∵~bemptyv~⦰~bepsi~϶~bernou~ℬ~beth~ℶ~between~≬~bfr~𝔟~bigcap~⋂~bigcirc~◯~bigcup~⋃~bigodot~⨀~bigoplus~⨁~bigotimes~⨂~bigsqcup~⨆~bigstar~★~bigtriangledown~▽~bigtriangleup~△~biguplus~⨄~bigvee~⋁~bigwedge~⋀~bkarow~⤍~blacklozenge~⧫~blacksquare~▪~blacktriangle~▴~blacktriangledown~▾~blacktriangleleft~◂~blacktriangleright~▸~blank~␣~blk12~▒~blk14~░~blk34~▓~block~█~bne~=⃥~bnequiv~≡⃥~bnot~⌐~bopf~𝕓~bot~⊥~bottom~⊥~bowtie~⋈~boxDL~╗~boxDR~╔~boxDl~╖~boxDr~╓~boxH~═~boxHD~╦~boxHU~╩~boxHd~╤~boxHu~╧~boxUL~╝~boxUR~╚~boxUl~╜~boxUr~╙~boxV~║~boxVH~╬~boxVL~╣~boxVR~╠~boxVh~╫~boxVl~╢~boxVr~╟~boxbox~⧉~boxdL~╕~boxdR~╒~boxdl~┐~boxdr~┌~boxh~─~boxhD~╥~boxhU~╨~boxhd~┬~boxhu~┴~boxminus~⊟~boxplus~⊞~boxtimes~⊠~boxuL~╛~boxuR~╘~boxul~┘~boxur~└~boxv~│~boxvH~╪~boxvL~╡~boxvR~╞~boxvh~┼~boxvl~┤~boxvr~├~bprime~‵~breve~˘~bscr~𝒷~bsemi~⁏~bsim~∽~bsime~⋍~bsol~\\~bsolb~⧅~bsolhsub~⟈~bullet~•~bump~≎~bumpE~⪮~bumpe~≏~bumpeq~≏~cacute~ć~capand~⩄~capbrcup~⩉~capcap~⩋~capcup~⩇~capdot~⩀~caps~∩︀~caret~⁁~caron~ˇ~ccaps~⩍~ccaron~č~ccirc~ĉ~ccups~⩌~ccupssm~⩐~cdot~ċ~cemptyv~⦲~centerdot~·~cfr~𝔠~chcy~ч~check~✓~checkmark~✓~cir~○~cirE~⧃~circeq~≗~circlearrowleft~↺~circlearrowright~↻~circledR~®~circledS~Ⓢ~circledast~⊛~circledcirc~⊚~circleddash~⊝~cire~≗~cirfnint~⨐~cirmid~⫯~cirscir~⧂~clubsuit~♣~colon~:~colone~≔~coloneq~≔~comma~,~commat~@~comp~∁~compfn~∘~complement~∁~complexes~ℂ~congdot~⩭~conint~∮~copf~𝕔~coprod~∐~copysr~℗~cross~✗~cscr~𝒸~csub~⫏~csube~⫑~csup~⫐~csupe~⫒~ctdot~⋯~cudarrl~⤸~cudarrr~⤵~cuepr~⋞~cuesc~⋟~cularr~↶~cularrp~⤽~cupbrcap~⩈~cupcap~⩆~cupcup~⩊~cupdot~⊍~cupor~⩅~cups~∪︀~curarr~↷~curarrm~⤼~curlyeqprec~⋞~curlyeqsucc~⋟~curlyvee~⋎~curlywedge~⋏~curvearrowleft~↶~curvearrowright~↷~cuvee~⋎~cuwed~⋏~cwconint~∲~cwint~∱~cylcty~⌭~dHar~⥥~daleth~ℸ~dash~‐~dashv~⊣~dbkarow~⤏~dblac~˝~dcaron~ď~dcy~д~dd~ⅆ~ddagger~‡~ddarr~⇊~ddotseq~⩷~demptyv~⦱~dfisht~⥿~dfr~𝔡~dharl~⇃~dharr~⇂~diam~⋄~diamond~⋄~diamondsuit~♦~die~¨~digamma~ϝ~disin~⋲~div~÷~divideontimes~⋇~divonx~⋇~djcy~ђ~dlcorn~⌞~dlcrop~⌍~dollar~$~dopf~𝕕~dot~˙~doteq~≐~doteqdot~≑~dotminus~∸~dotplus~∔~dotsquare~⊡~doublebarwedge~⌆~downarrow~↓~downdownarrows~⇊~downharpoonleft~⇃~downharpoonright~⇂~drbkarow~⤐~drcorn~⌟~drcrop~⌌~dscr~𝒹~dscy~ѕ~dsol~⧶~dstrok~đ~dtdot~⋱~dtri~▿~dtrif~▾~duarr~⇵~duhar~⥯~dwangle~⦦~dzcy~џ~dzigrarr~⟿~eDDot~⩷~eDot~≑~easter~⩮~ecaron~ě~ecir~≖~ecolon~≕~ecy~э~edot~ė~ee~ⅇ~efDot~≒~efr~𝔢~eg~⪚~egs~⪖~egsdot~⪘~el~⪙~elinters~⏧~ell~ℓ~els~⪕~elsdot~⪗~emacr~ē~emptyset~∅~emptyv~∅~emsp13~ ~emsp14~ ~eng~ŋ~eogon~ę~eopf~𝕖~epar~⋕~eparsl~⧣~eplus~⩱~epsi~ε~epsiv~ϵ~eqcirc~≖~eqcolon~≕~eqsim~≂~eqslantgtr~⪖~eqslantless~⪕~equals~=~equest~≟~equivDD~⩸~eqvparsl~⧥~erDot~≓~erarr~⥱~escr~ℯ~esdot~≐~esim~≂~excl~!~expectation~ℰ~exponentiale~ⅇ~fallingdotseq~≒~fcy~ф~female~♀~ffilig~ffi~fflig~ff~ffllig~ffl~ffr~𝔣~filig~fi~fjlig~fj~flat~♭~fllig~fl~fltns~▱~fopf~𝕗~fork~⋔~forkv~⫙~fpartint~⨍~frac13~⅓~frac15~⅕~frac16~⅙~frac18~⅛~frac23~⅔~frac25~⅖~frac35~⅗~frac38~⅜~frac45~⅘~frac56~⅚~frac58~⅝~frac78~⅞~frown~⌢~fscr~𝒻~gE~≧~gEl~⪌~gacute~ǵ~gammad~ϝ~gap~⪆~gbreve~ğ~gcirc~ĝ~gcy~г~gdot~ġ~gel~⋛~geq~≥~geqq~≧~geqslant~⩾~ges~⩾~gescc~⪩~gesdot~⪀~gesdoto~⪂~gesdotol~⪄~gesl~⋛︀~gesles~⪔~gfr~𝔤~gg~≫~ggg~⋙~gimel~ℷ~gjcy~ѓ~gl~≷~glE~⪒~gla~⪥~glj~⪤~gnE~≩~gnap~⪊~gnapprox~⪊~gne~⪈~gneq~⪈~gneqq~≩~gnsim~⋧~gopf~𝕘~grave~`~gscr~ℊ~gsim~≳~gsime~⪎~gsiml~⪐~gtcc~⪧~gtcir~⩺~gtdot~⋗~gtlPar~⦕~gtquest~⩼~gtrapprox~⪆~gtrarr~⥸~gtrdot~⋗~gtreqless~⋛~gtreqqless~⪌~gtrless~≷~gtrsim~≳~gvertneqq~≩︀~gvnE~≩︀~hairsp~ ~half~½~hamilt~ℋ~hardcy~ъ~harrcir~⥈~harrw~↭~hbar~ℏ~hcirc~ĥ~heartsuit~♥~hercon~⊹~hfr~𝔥~hksearow~⤥~hkswarow~⤦~hoarr~⇿~homtht~∻~hookleftarrow~↩~hookrightarrow~↪~hopf~𝕙~horbar~―~hscr~𝒽~hslash~ℏ~hstrok~ħ~hybull~⁃~hyphen~‐~ic~⁣~icy~и~iecy~е~iff~⇔~ifr~𝔦~ii~ⅈ~iiiint~⨌~iiint~∭~iinfin~⧜~iiota~℩~ijlig~ij~imacr~ī~imagline~ℐ~imagpart~ℑ~imath~ı~imof~⊷~imped~Ƶ~in~∈~incare~℅~infintie~⧝~inodot~ı~intcal~⊺~integers~ℤ~intercal~⊺~intlarhk~⨗~intprod~⨼~iocy~ё~iogon~į~iopf~𝕚~iprod~⨼~iscr~𝒾~isinE~⋹~isindot~⋵~isins~⋴~isinsv~⋳~isinv~∈~it~⁢~itilde~ĩ~iukcy~і~jcirc~ĵ~jcy~й~jfr~𝔧~jmath~ȷ~jopf~𝕛~jscr~𝒿~jsercy~ј~jukcy~є~kappav~ϰ~kcedil~ķ~kcy~к~kfr~𝔨~kgreen~ĸ~khcy~х~kjcy~ќ~kopf~𝕜~kscr~𝓀~lAarr~⇚~lAtail~⤛~lBarr~⤎~lE~≦~lEg~⪋~lHar~⥢~lacute~ĺ~laemptyv~⦴~lagran~ℒ~langd~⦑~langle~⟨~lap~⪅~larrb~⇤~larrbfs~⤟~larrfs~⤝~larrhk~↩~larrlp~↫~larrpl~⤹~larrsim~⥳~larrtl~↢~lat~⪫~latail~⤙~late~⪭~lates~⪭︀~lbarr~⤌~lbbrk~❲~lbrace~{~lbrack~[~lbrke~⦋~lbrksld~⦏~lbrkslu~⦍~lcaron~ľ~lcedil~ļ~lcub~{~lcy~л~ldca~⤶~ldquor~„~ldrdhar~⥧~ldrushar~⥋~ldsh~↲~leftarrow~←~leftarrowtail~↢~leftharpoondown~↽~leftharpoonup~↼~leftleftarrows~⇇~leftrightarrow~↔~leftrightarrows~⇆~leftrightharpoons~⇋~leftrightsquigarrow~↭~leftthreetimes~⋋~leg~⋚~leq~≤~leqq~≦~leqslant~⩽~les~⩽~lescc~⪨~lesdot~⩿~lesdoto~⪁~lesdotor~⪃~lesg~⋚︀~lesges~⪓~lessapprox~⪅~lessdot~⋖~lesseqgtr~⋚~lesseqqgtr~⪋~lessgtr~≶~lesssim~≲~lfisht~⥼~lfr~𝔩~lg~≶~lgE~⪑~lhard~↽~lharu~↼~lharul~⥪~lhblk~▄~ljcy~љ~ll~≪~llarr~⇇~llcorner~⌞~llhard~⥫~lltri~◺~lmidot~ŀ~lmoust~⎰~lmoustache~⎰~lnE~≨~lnap~⪉~lnapprox~⪉~lne~⪇~lneq~⪇~lneqq~≨~lnsim~⋦~loang~⟬~loarr~⇽~lobrk~⟦~longleftarrow~⟵~longleftrightarrow~⟷~longmapsto~⟼~longrightarrow~⟶~looparrowleft~↫~looparrowright~↬~lopar~⦅~lopf~𝕝~loplus~⨭~lotimes~⨴~lowbar~_~lozenge~◊~lozf~⧫~lpar~(~lparlt~⦓~lrarr~⇆~lrcorner~⌟~lrhar~⇋~lrhard~⥭~lrtri~⊿~lscr~𝓁~lsh~↰~lsim~≲~lsime~⪍~lsimg~⪏~lsqb~[~lsquor~‚~lstrok~ł~ltcc~⪦~ltcir~⩹~ltdot~⋖~lthree~⋋~ltimes~⋉~ltlarr~⥶~ltquest~⩻~ltrPar~⦖~ltri~◃~ltrie~⊴~ltrif~◂~lurdshar~⥊~luruhar~⥦~lvertneqq~≨︀~lvnE~≨︀~mDDot~∺~male~♂~malt~✠~maltese~✠~map~↦~mapsto~↦~mapstodown~↧~mapstoleft~↤~mapstoup~↥~marker~▮~mcomma~⨩~mcy~м~measuredangle~∡~mfr~𝔪~mho~℧~mid~∣~midast~*~midcir~⫰~minusb~⊟~minusd~∸~minusdu~⨪~mlcp~⫛~mldr~…~mnplus~∓~models~⊧~mopf~𝕞~mp~∓~mscr~𝓂~mstpos~∾~multimap~⊸~mumap~⊸~nGg~⋙̸~nGt~≫⃒~nGtv~≫̸~nLeftarrow~⇍~nLeftrightarrow~⇎~nLl~⋘̸~nLt~≪⃒~nLtv~≪̸~nRightarrow~⇏~nVDash~⊯~nVdash~⊮~nacute~ń~nang~∠⃒~nap~≉~napE~⩰̸~napid~≋̸~napos~ʼn~napprox~≉~natur~♮~natural~♮~naturals~ℕ~nbump~≎̸~nbumpe~≏̸~ncap~⩃~ncaron~ň~ncedil~ņ~ncong~≇~ncongdot~⩭̸~ncup~⩂~ncy~н~neArr~⇗~nearhk~⤤~nearr~↗~nearrow~↗~nedot~≐̸~nequiv~≢~nesear~⤨~nesim~≂̸~nexist~∄~nexists~∄~nfr~𝔫~ngE~≧̸~nge~≱~ngeq~≱~ngeqq~≧̸~ngeqslant~⩾̸~nges~⩾̸~ngsim~≵~ngt~≯~ngtr~≯~nhArr~⇎~nharr~↮~nhpar~⫲~nis~⋼~nisd~⋺~niv~∋~njcy~њ~nlArr~⇍~nlE~≦̸~nlarr~↚~nldr~‥~nle~≰~nleftarrow~↚~nleftrightarrow~↮~nleq~≰~nleqq~≦̸~nleqslant~⩽̸~nles~⩽̸~nless~≮~nlsim~≴~nlt~≮~nltri~⋪~nltrie~⋬~nmid~∤~nopf~𝕟~notinE~⋹̸~notindot~⋵̸~notinva~∉~notinvb~⋷~notinvc~⋶~notni~∌~notniva~∌~notnivb~⋾~notnivc~⋽~npar~∦~nparallel~∦~nparsl~⫽⃥~npart~∂̸~npolint~⨔~npr~⊀~nprcue~⋠~npre~⪯̸~nprec~⊀~npreceq~⪯̸~nrArr~⇏~nrarr~↛~nrarrc~⤳̸~nrarrw~↝̸~nrightarrow~↛~nrtri~⋫~nrtrie~⋭~nsc~⊁~nsccue~⋡~nsce~⪰̸~nscr~𝓃~nshortmid~∤~nshortparallel~∦~nsim~≁~nsime~≄~nsimeq~≄~nsmid~∤~nspar~∦~nsqsube~⋢~nsqsupe~⋣~nsubE~⫅̸~nsube~⊈~nsubset~⊂⃒~nsubseteq~⊈~nsubseteqq~⫅̸~nsucc~⊁~nsucceq~⪰̸~nsup~⊅~nsupE~⫆̸~nsupe~⊉~nsupset~⊃⃒~nsupseteq~⊉~nsupseteqq~⫆̸~ntgl~≹~ntlg~≸~ntriangleleft~⋪~ntrianglelefteq~⋬~ntriangleright~⋫~ntrianglerighteq~⋭~num~#~numero~№~numsp~ ~nvDash~⊭~nvHarr~⤄~nvap~≍⃒~nvdash~⊬~nvge~≥⃒~nvgt~>⃒~nvinfin~⧞~nvlArr~⤂~nvle~≤⃒~nvlt~<⃒~nvltrie~⊴⃒~nvrArr~⤃~nvrtrie~⊵⃒~nvsim~∼⃒~nwArr~⇖~nwarhk~⤣~nwarr~↖~nwarrow~↖~nwnear~⤧~oS~Ⓢ~oast~⊛~ocir~⊚~ocy~о~odash~⊝~odblac~ő~odiv~⨸~odot~⊙~odsold~⦼~ofcir~⦿~ofr~𝔬~ogon~˛~ogt~⧁~ohbar~⦵~ohm~Ω~oint~∮~olarr~↺~olcir~⦾~olcross~⦻~olt~⧀~omacr~ō~omid~⦶~ominus~⊖~oopf~𝕠~opar~⦷~operp~⦹~orarr~↻~ord~⩝~order~ℴ~orderof~ℴ~origof~⊶~oror~⩖~orslope~⩗~orv~⩛~oscr~ℴ~osol~⊘~otimesas~⨶~ovbar~⌽~par~∥~parallel~∥~parsim~⫳~parsl~⫽~pcy~п~percnt~%~period~.~pertenk~‱~pfr~𝔭~phiv~ϕ~phmmat~ℳ~phone~☎~pitchfork~⋔~planck~ℏ~planckh~ℎ~plankv~ℏ~plus~+~plusacir~⨣~plusb~⊞~pluscir~⨢~plusdo~∔~plusdu~⨥~pluse~⩲~plussim~⨦~plustwo~⨧~pm~±~pointint~⨕~popf~𝕡~pr~≺~prE~⪳~prap~⪷~prcue~≼~pre~⪯~prec~≺~precapprox~⪷~preccurlyeq~≼~preceq~⪯~precnapprox~⪹~precneqq~⪵~precnsim~⋨~precsim~≾~primes~ℙ~prnE~⪵~prnap~⪹~prnsim~⋨~profalar~⌮~profline~⌒~profsurf~⌓~propto~∝~prsim~≾~prurel~⊰~pscr~𝓅~puncsp~ ~qfr~𝔮~qint~⨌~qopf~𝕢~qprime~⁗~qscr~𝓆~quaternions~ℍ~quatint~⨖~quest~?~questeq~≟~rAarr~⇛~rAtail~⤜~rBarr~⤏~rHar~⥤~race~∽̱~racute~ŕ~raemptyv~⦳~rangd~⦒~range~⦥~rangle~⟩~rarrap~⥵~rarrb~⇥~rarrbfs~⤠~rarrc~⤳~rarrfs~⤞~rarrhk~↪~rarrlp~↬~rarrpl~⥅~rarrsim~⥴~rarrtl~↣~rarrw~↝~ratail~⤚~ratio~∶~rationals~ℚ~rbarr~⤍~rbbrk~❳~rbrace~}~rbrack~]~rbrke~⦌~rbrksld~⦎~rbrkslu~⦐~rcaron~ř~rcedil~ŗ~rcub~}~rcy~р~rdca~⤷~rdldhar~⥩~rdquor~”~rdsh~↳~realine~ℛ~realpart~ℜ~reals~ℝ~rect~▭~rfisht~⥽~rfr~𝔯~rhard~⇁~rharu~⇀~rharul~⥬~rhov~ϱ~rightarrow~→~rightarrowtail~↣~rightharpoondown~⇁~rightharpoonup~⇀~rightleftarrows~⇄~rightleftharpoons~⇌~rightrightarrows~⇉~rightsquigarrow~↝~rightthreetimes~⋌~ring~˚~risingdotseq~≓~rlarr~⇄~rlhar~⇌~rmoust~⎱~rmoustache~⎱~rnmid~⫮~roang~⟭~roarr~⇾~robrk~⟧~ropar~⦆~ropf~𝕣~roplus~⨮~rotimes~⨵~rpar~)~rpargt~⦔~rppolint~⨒~rrarr~⇉~rscr~𝓇~rsh~↱~rsqb~]~rsquor~’~rthree~⋌~rtimes~⋊~rtri~▹~rtrie~⊵~rtrif~▸~rtriltri~⧎~ruluhar~⥨~rx~℞~sacute~ś~sc~≻~scE~⪴~scap~⪸~sccue~≽~sce~⪰~scedil~ş~scirc~ŝ~scnE~⪶~scnap~⪺~scnsim~⋩~scpolint~⨓~scsim~≿~scy~с~sdotb~⊡~sdote~⩦~seArr~⇘~searhk~⤥~searr~↘~searrow~↘~semi~;~seswar~⤩~setminus~∖~setmn~∖~sext~✶~sfr~𝔰~sfrown~⌢~sharp~♯~shchcy~щ~shcy~ш~shortmid~∣~shortparallel~∥~sigmav~ς~simdot~⩪~sime~≃~simeq~≃~simg~⪞~simgE~⪠~siml~⪝~simlE~⪟~simne~≆~simplus~⨤~simrarr~⥲~slarr~←~smallsetminus~∖~smashp~⨳~smeparsl~⧤~smid~∣~smile~⌣~smt~⪪~smte~⪬~smtes~⪬︀~softcy~ь~sol~/~solb~⧄~solbar~⌿~sopf~𝕤~spadesuit~♠~spar~∥~sqcap~⊓~sqcaps~⊓︀~sqcup~⊔~sqcups~⊔︀~sqsub~⊏~sqsube~⊑~sqsubset~⊏~sqsubseteq~⊑~sqsup~⊐~sqsupe~⊒~sqsupset~⊐~sqsupseteq~⊒~squ~□~square~□~squarf~▪~squf~▪~srarr~→~sscr~𝓈~ssetmn~∖~ssmile~⌣~sstarf~⋆~star~☆~starf~★~straightepsilon~ϵ~straightphi~ϕ~strns~¯~subE~⫅~subdot~⪽~subedot~⫃~submult~⫁~subnE~⫋~subne~⊊~subplus~⪿~subrarr~⥹~subset~⊂~subseteq~⊆~subseteqq~⫅~subsetneq~⊊~subsetneqq~⫋~subsim~⫇~subsub~⫕~subsup~⫓~succ~≻~succapprox~⪸~succcurlyeq~≽~succeq~⪰~succnapprox~⪺~succneqq~⪶~succnsim~⋩~succsim~≿~sung~♪~supE~⫆~supdot~⪾~supdsub~⫘~supedot~⫄~suphsol~⟉~suphsub~⫗~suplarr~⥻~supmult~⫂~supnE~⫌~supne~⊋~supplus~⫀~supset~⊃~supseteq~⊇~supseteqq~⫆~supsetneq~⊋~supsetneqq~⫌~supsim~⫈~supsub~⫔~supsup~⫖~swArr~⇙~swarhk~⤦~swarr~↙~swarrow~↙~swnwar~⤪~target~⌖~tbrk~⎴~tcaron~ť~tcedil~ţ~tcy~т~tdot~⃛~telrec~⌕~tfr~𝔱~therefore~∴~thetav~ϑ~thickapprox~≈~thicksim~∼~thkap~≈~thksim~∼~timesb~⊠~timesbar~⨱~timesd~⨰~tint~∭~toea~⤨~top~⊤~topbot~⌶~topcir~⫱~topf~𝕥~topfork~⫚~tosa~⤩~tprime~‴~triangle~▵~triangledown~▿~triangleleft~◃~trianglelefteq~⊴~triangleq~≜~triangleright~▹~trianglerighteq~⊵~tridot~◬~trie~≜~triminus~⨺~triplus~⨹~trisb~⧍~tritime~⨻~trpezium~⏢~tscr~𝓉~tscy~ц~tshcy~ћ~tstrok~ŧ~twixt~≬~twoheadleftarrow~↞~twoheadrightarrow~↠~uHar~⥣~ubrcy~ў~ubreve~ŭ~ucy~у~udarr~⇅~udblac~ű~udhar~⥮~ufisht~⥾~ufr~𝔲~uharl~↿~uharr~↾~uhblk~▀~ulcorn~⌜~ulcorner~⌜~ulcrop~⌏~ultri~◸~umacr~ū~uogon~ų~uopf~𝕦~uparrow~↑~updownarrow~↕~upharpoonleft~↿~upharpoonright~↾~uplus~⊎~upsi~υ~upuparrows~⇈~urcorn~⌝~urcorner~⌝~urcrop~⌎~uring~ů~urtri~◹~uscr~𝓊~utdot~⋰~utilde~ũ~utri~▵~utrif~▴~uuarr~⇈~uwangle~⦧~vArr~⇕~vBar~⫨~vBarv~⫩~vDash~⊨~vangrt~⦜~varepsilon~ϵ~varkappa~ϰ~varnothing~∅~varphi~ϕ~varpi~ϖ~varpropto~∝~varr~↕~varrho~ϱ~varsigma~ς~varsubsetneq~⊊︀~varsubsetneqq~⫋︀~varsupsetneq~⊋︀~varsupsetneqq~⫌︀~vartheta~ϑ~vartriangleleft~⊲~vartriangleright~⊳~vcy~в~vdash~⊢~vee~∨~veebar~⊻~veeeq~≚~vellip~⋮~verbar~|~vert~|~vfr~𝔳~vltri~⊲~vnsub~⊂⃒~vnsup~⊃⃒~vopf~𝕧~vprop~∝~vrtri~⊳~vscr~𝓋~vsubnE~⫋︀~vsubne~⊊︀~vsupnE~⫌︀~vsupne~⊋︀~vzigzag~⦚~wcirc~ŵ~wedbar~⩟~wedge~∧~wedgeq~≙~wfr~𝔴~wopf~𝕨~wp~℘~wr~≀~wreath~≀~wscr~𝓌~xcap~⋂~xcirc~◯~xcup~⋃~xdtri~▽~xfr~𝔵~xhArr~⟺~xharr~⟷~xlArr~⟸~xlarr~⟵~xmap~⟼~xnis~⋻~xodot~⨀~xopf~𝕩~xoplus~⨁~xotime~⨂~xrArr~⟹~xrarr~⟶~xscr~𝓍~xsqcup~⨆~xuplus~⨄~xutri~△~xvee~⋁~xwedge~⋀~yacy~я~ycirc~ŷ~ycy~ы~yfr~𝔶~yicy~ї~yopf~𝕪~yscr~𝓎~yucy~ю~zacute~ź~zcaron~ž~zcy~з~zdot~ż~zeetrf~ℨ~zfr~𝔷~zhcy~ж~zigrarr~⇝~zopf~𝕫~zscr~𝓏~~AMP~&~COPY~©~GT~>~LT~<~QUOT~\"~REG~®", exports.namedReferences['html4']); +//# sourceMappingURL=named-references.js.map \ No newline at end of file diff --git a/node_modules/html-entities/dist/commonjs/named-references.js.map b/node_modules/html-entities/dist/commonjs/named-references.js.map new file mode 100644 index 0000000..8147a52 --- /dev/null +++ b/node_modules/html-entities/dist/commonjs/named-references.js.map @@ -0,0 +1 @@ +{"version":3,"file":"named-references.js","sourceRoot":"","sources":["../../src/named-references.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,kEAAkE;AAClE,IAAM,WAAW,GAAG,GAAG,CAAC;AACxB,IAAM,YAAY,GAAG,IAAI,CAAC;AAO1B,SAAS,uBAAuB,CAAC,KAAa,EAAE,IAA0B;IACtE,IAAM,QAAQ,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hCAAmhC;CAC7hC,CAAC;AACW,QAAA,eAAe,GAAG,EAAqB,CAAC;AACrD,uBAAe,CAAC,KAAK,CAAC,GAAG,uBAAuB,CAAC,gCAAgC,CAAC,CAAC;AACnF,uBAAe,CAAC,OAAO,CAAC,GAAG,uBAAuB,CAAC,04DAA04D,CAAC,CAAC;AAC/7D,uBAAe,CAAC,OAAO,CAAC,GAAG,uBAAuB,CAAC,4vkBAA4vkB,EAAE,uBAAe,CAAC,OAAO,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/html-entities/dist/commonjs/numeric-unicode-map.js b/node_modules/html-entities/dist/commonjs/numeric-unicode-map.js new file mode 100644 index 0000000..7eed025 --- /dev/null +++ b/node_modules/html-entities/dist/commonjs/numeric-unicode-map.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.numericUnicodeMap = void 0; +exports.numericUnicodeMap = { + 0: 65533, + 128: 8364, + 130: 8218, + 131: 402, + 132: 8222, + 133: 8230, + 134: 8224, + 135: 8225, + 136: 710, + 137: 8240, + 138: 352, + 139: 8249, + 140: 338, + 142: 381, + 145: 8216, + 146: 8217, + 147: 8220, + 148: 8221, + 149: 8226, + 150: 8211, + 151: 8212, + 152: 732, + 153: 8482, + 154: 353, + 155: 8250, + 156: 339, + 158: 382, + 159: 376 +}; +//# sourceMappingURL=numeric-unicode-map.js.map \ No newline at end of file diff --git a/node_modules/html-entities/dist/commonjs/numeric-unicode-map.js.map b/node_modules/html-entities/dist/commonjs/numeric-unicode-map.js.map new file mode 100644 index 0000000..2f7e93f --- /dev/null +++ b/node_modules/html-entities/dist/commonjs/numeric-unicode-map.js.map @@ -0,0 +1 @@ +{"version":3,"file":"numeric-unicode-map.js","sourceRoot":"","sources":["../../src/numeric-unicode-map.ts"],"names":[],"mappings":";;;AAAa,QAAA,iBAAiB,GAA2B;IACrD,CAAC,EAAE,KAAK;IACR,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,GAAG;CACX,CAAC"} \ No newline at end of file diff --git a/node_modules/html-entities/dist/commonjs/package.json b/node_modules/html-entities/dist/commonjs/package.json new file mode 100644 index 0000000..5bbefff --- /dev/null +++ b/node_modules/html-entities/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/html-entities/dist/commonjs/surrogate-pairs.js b/node_modules/html-entities/dist/commonjs/surrogate-pairs.js new file mode 100644 index 0000000..bc329f0 --- /dev/null +++ b/node_modules/html-entities/dist/commonjs/surrogate-pairs.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.highSurrogateTo = exports.highSurrogateFrom = exports.getCodePoint = exports.fromCodePoint = void 0; +exports.fromCodePoint = String.fromCodePoint || + function (astralCodePoint) { + return String.fromCharCode(Math.floor((astralCodePoint - 0x10000) / 0x400) + 0xd800, ((astralCodePoint - 0x10000) % 0x400) + 0xdc00); + }; +// @ts-expect-error - String.prototype.codePointAt might not exist in older node versions +exports.getCodePoint = String.prototype.codePointAt + ? function (input, position) { + return input.codePointAt(position); + } + : function (input, position) { + return (input.charCodeAt(position) - 0xd800) * 0x400 + input.charCodeAt(position + 1) - 0xdc00 + 0x10000; + }; +exports.highSurrogateFrom = 0xd800; +exports.highSurrogateTo = 0xdbff; +//# sourceMappingURL=surrogate-pairs.js.map \ No newline at end of file diff --git a/node_modules/html-entities/dist/commonjs/surrogate-pairs.js.map b/node_modules/html-entities/dist/commonjs/surrogate-pairs.js.map new file mode 100644 index 0000000..9c91f33 --- /dev/null +++ b/node_modules/html-entities/dist/commonjs/surrogate-pairs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"surrogate-pairs.js","sourceRoot":"","sources":["../../src/surrogate-pairs.ts"],"names":[],"mappings":";;;AAAa,QAAA,aAAa,GACtB,MAAM,CAAC,aAAa;IACpB,UAAU,eAAuB;QAC7B,OAAO,MAAM,CAAC,YAAY,CACtB,IAAI,CAAC,KAAK,CAAC,CAAC,eAAe,GAAG,OAAO,CAAC,GAAG,KAAK,CAAC,GAAG,MAAM,EACxD,CAAC,CAAC,eAAe,GAAG,OAAO,CAAC,GAAG,KAAK,CAAC,GAAG,MAAM,CACjD,CAAC;IACN,CAAC,CAAC;AAEN,yFAAyF;AAC5E,QAAA,YAAY,GAAG,MAAM,CAAC,SAAS,CAAC,WAAW;IACpD,CAAC,CAAC,UAAU,KAAa,EAAE,QAAgB;QACrC,OAAO,KAAK,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;IACvC,CAAC;IACH,CAAC,CAAC,UAAU,KAAa,EAAE,QAAgB;QACrC,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC,GAAG,KAAK,GAAG,KAAK,CAAC,UAAU,CAAC,QAAQ,GAAG,CAAC,CAAC,GAAG,MAAM,GAAG,OAAO,CAAC;IAC7G,CAAC,CAAC;AAEK,QAAA,iBAAiB,GAAG,MAAM,CAAC;AAC3B,QAAA,eAAe,GAAG,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/html-entities/dist/esm/index.d.ts b/node_modules/html-entities/dist/esm/index.d.ts new file mode 100644 index 0000000..733c6ee --- /dev/null +++ b/node_modules/html-entities/dist/esm/index.d.ts @@ -0,0 +1,20 @@ +export type Level = 'xml' | 'html4' | 'html5' | 'all'; +interface CommonOptions { + level?: Level; +} +export type EncodeMode = 'specialChars' | 'nonAscii' | 'nonAsciiPrintable' | 'nonAsciiPrintableOnly' | 'extensive'; +export interface EncodeOptions extends CommonOptions { + mode?: EncodeMode; + numeric?: 'decimal' | 'hexadecimal'; +} +export type DecodeScope = 'strict' | 'body' | 'attribute'; +export interface DecodeOptions extends CommonOptions { + scope?: DecodeScope; +} +/** Encodes all the necessary (specified by `level`) characters in the text */ +export declare function encode(text: string | undefined | null, { mode, numeric, level }?: EncodeOptions): string; +/** Decodes a single entity */ +export declare function decodeEntity(entity: string | undefined | null, { level }?: CommonOptions): string; +/** Decodes all entities in the text */ +export declare function decode(text: string | undefined | null, { level, scope }?: DecodeOptions): string; +export {}; diff --git a/node_modules/html-entities/dist/esm/index.js b/node_modules/html-entities/dist/esm/index.js new file mode 100644 index 0000000..4161497 --- /dev/null +++ b/node_modules/html-entities/dist/esm/index.js @@ -0,0 +1,124 @@ +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +import { bodyRegExps, namedReferences } from './named-references.js'; +import { numericUnicodeMap } from './numeric-unicode-map.js'; +import { fromCodePoint, getCodePoint } from './surrogate-pairs.js'; +var allNamedReferences = __assign(__assign({}, namedReferences), { all: namedReferences.html5 }); +var encodeRegExps = { + specialChars: /[<>'"&]/g, + nonAscii: /[<>'"&\u0080-\uD7FF\uE000-\uFFFF\uDC00-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g, + nonAsciiPrintable: /[<>'"&\x01-\x08\x11-\x15\x17-\x1F\x7f-\uD7FF\uE000-\uFFFF\uDC00-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g, + nonAsciiPrintableOnly: /[\x01-\x08\x11-\x15\x17-\x1F\x7f-\uD7FF\uE000-\uFFFF\uDC00-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g, + extensive: /[\x01-\x0c\x0e-\x1f\x21-\x2c\x2e-\x2f\x3a-\x40\x5b-\x60\x7b-\x7d\x7f-\uD7FF\uE000-\uFFFF\uDC00-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g +}; +var defaultEncodeOptions = { + mode: 'specialChars', + level: 'all', + numeric: 'decimal' +}; +/** Encodes all the necessary (specified by `level`) characters in the text */ +export function encode(text, _a) { + var _b = _a === void 0 ? defaultEncodeOptions : _a, _c = _b.mode, mode = _c === void 0 ? 'specialChars' : _c, _d = _b.numeric, numeric = _d === void 0 ? 'decimal' : _d, _e = _b.level, level = _e === void 0 ? 'all' : _e; + if (!text) { + return ''; + } + var encodeRegExp = encodeRegExps[mode]; + var references = allNamedReferences[level].characters; + var isHex = numeric === 'hexadecimal'; + return String.prototype.replace.call(text, encodeRegExp, function (input) { + var result = references[input]; + if (!result) { + var code = input.length > 1 ? getCodePoint(input, 0) : input.charCodeAt(0); + result = (isHex ? '&#x' + code.toString(16) : '&#' + code) + ';'; + } + return result; + }); +} +var defaultDecodeOptions = { + scope: 'body', + level: 'all' +}; +var strict = /&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);/g; +var attribute = /&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+)[;=]?/g; +var baseDecodeRegExps = { + xml: { + strict: strict, + attribute: attribute, + body: bodyRegExps.xml + }, + html4: { + strict: strict, + attribute: attribute, + body: bodyRegExps.html4 + }, + html5: { + strict: strict, + attribute: attribute, + body: bodyRegExps.html5 + } +}; +var decodeRegExps = __assign(__assign({}, baseDecodeRegExps), { all: baseDecodeRegExps.html5 }); +var fromCharCode = String.fromCharCode; +var outOfBoundsChar = fromCharCode(65533); +var defaultDecodeEntityOptions = { + level: 'all' +}; +function getDecodedEntity(entity, references, isAttribute, isStrict) { + var decodeResult = entity; + var decodeEntityLastChar = entity[entity.length - 1]; + if (isAttribute && decodeEntityLastChar === '=') { + decodeResult = entity; + } + else if (isStrict && decodeEntityLastChar !== ';') { + decodeResult = entity; + } + else { + var decodeResultByReference = references[entity]; + if (decodeResultByReference) { + decodeResult = decodeResultByReference; + } + else if (entity[0] === '&' && entity[1] === '#') { + var decodeSecondChar = entity[2]; + var decodeCode = decodeSecondChar == 'x' || decodeSecondChar == 'X' + ? parseInt(entity.substr(3), 16) + : parseInt(entity.substr(2)); + decodeResult = + decodeCode >= 0x10ffff + ? outOfBoundsChar + : decodeCode > 65535 + ? fromCodePoint(decodeCode) + : fromCharCode(numericUnicodeMap[decodeCode] || decodeCode); + } + } + return decodeResult; +} +/** Decodes a single entity */ +export function decodeEntity(entity, _a) { + var _b = _a === void 0 ? defaultDecodeEntityOptions : _a, _c = _b.level, level = _c === void 0 ? 'all' : _c; + if (!entity) { + return ''; + } + return getDecodedEntity(entity, allNamedReferences[level].entities, false, false); +} +/** Decodes all entities in the text */ +export function decode(text, _a) { + var _b = _a === void 0 ? defaultDecodeOptions : _a, _c = _b.level, level = _c === void 0 ? 'all' : _c, _d = _b.scope, scope = _d === void 0 ? level === 'xml' ? 'strict' : 'body' : _d; + if (!text) { + return ''; + } + var decodeRegExp = decodeRegExps[level][scope]; + var references = allNamedReferences[level].entities; + var isAttribute = scope === 'attribute'; + var isStrict = scope === 'strict'; + return text.replace(decodeRegExp, function (entity) { return getDecodedEntity(entity, references, isAttribute, isStrict); }); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/html-entities/dist/esm/index.js.map b/node_modules/html-entities/dist/esm/index.js.map new file mode 100644 index 0000000..645ace8 --- /dev/null +++ b/node_modules/html-entities/dist/esm/index.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Y,CACxB,MAAiC,EACjC,EAA2D;QAA3D,qBAAiC,0BAA0B,KAAA,EAA1D,aAAa,EAAb,KAAK,mBAAG,KAAK,KAAA;IAEd,IAAI,CAAC,MAAM,EAAE,CAAC;QACV,OAAO,EAAE,CAAC;IACd,CAAC;IACD,OAAO,gBAAgB,CAAC,MAAM,EAAE,kBAAkB,CAAC,KAAK,CAAC,CAAC,QAAQ,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;AACtF,CAAC;AAED,uCAAuC;AACvC,MAAM,UAAU,MAAM,CAClB,IAA+B,EAC/B,EAAkG;QAAlG,qBAA8E,oBAAoB,KAAA,EAAjG,aAAa,EAAb,KAAK,mBAAG,KAAK,KAAA,EAAE,aAA2C,EAA3C,KAAK,mBAAG,KAAK,KAAK,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,KAAA;IAE3D,IAAI,CAAC,IAAI,EAAE,CAAC;QACR,OAAO,EAAE,CAAC;IACd,CAAC;IAED,IAAM,YAAY,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;IACjD,IAAM,UAAU,GAAG,kBAAkB,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC;IACtD,IAAM,WAAW,GAAG,KAAK,KAAK,WAAW,CAAC;IAC1C,IAAM,QAAQ,GAAG,KAAK,KAAK,QAAQ,CAAC;IAEpC,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY,EAAE,UAAC,MAAM,IAAK,OAAA,gBAAgB,CAAC,MAAM,EAAE,UAAU,EAAE,WAAW,EAAE,QAAQ,CAAC,EAA3D,CAA2D,CAAC,CAAC;AAC/G,CAAC"} \ No newline at end of file diff --git a/node_modules/html-entities/dist/esm/named-references.js b/node_modules/html-entities/dist/esm/named-references.js new file mode 100644 index 0000000..aef4403 --- /dev/null +++ b/node_modules/html-entities/dist/esm/named-references.js @@ -0,0 +1,47 @@ +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +// This file is autogenerated by tools/process-named-references.ts +var pairDivider = "~"; +var blockDivider = "~~"; +function generateNamedReferences(input, prev) { + var entities = {}; + var characters = {}; + var blocks = input.split(blockDivider); + var isOptionalBlock = false; + for (var i = 0; blocks.length > i; i++) { + var entries = blocks[i].split(pairDivider); + for (var j = 0; j < entries.length; j += 2) { + var entity = entries[j]; + var character = entries[j + 1]; + var fullEntity = '&' + entity + ';'; + entities[fullEntity] = character; + if (isOptionalBlock) { + entities['&' + entity] = character; + } + characters[character] = fullEntity; + } + isOptionalBlock = true; + } + return prev ? + { entities: __assign(__assign({}, entities), prev.entities), characters: __assign(__assign({}, characters), prev.characters) } : + { entities: entities, characters: characters }; +} +export var bodyRegExps = { + xml: /&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g, + html4: /∉|&(?:nbsp|iexcl|cent|pound|curren|yen|brvbar|sect|uml|copy|ordf|laquo|not|shy|reg|macr|deg|plusmn|sup2|sup3|acute|micro|para|middot|cedil|sup1|ordm|raquo|frac14|frac12|frac34|iquest|Agrave|Aacute|Acirc|Atilde|Auml|Aring|AElig|Ccedil|Egrave|Eacute|Ecirc|Euml|Igrave|Iacute|Icirc|Iuml|ETH|Ntilde|Ograve|Oacute|Ocirc|Otilde|Ouml|times|Oslash|Ugrave|Uacute|Ucirc|Uuml|Yacute|THORN|szlig|agrave|aacute|acirc|atilde|auml|aring|aelig|ccedil|egrave|eacute|ecirc|euml|igrave|iacute|icirc|iuml|eth|ntilde|ograve|oacute|ocirc|otilde|ouml|divide|oslash|ugrave|uacute|ucirc|uuml|yacute|thorn|yuml|quot|amp|lt|gt|#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g, + html5: /·|℗|⋇|⪧|⩺|⋗|⦕|⩼|⪆|⥸|⋗|⋛|⪌|≷|≳|⪦|⩹|⋖|⋋|⋉|⥶|⩻|⦖|◃|⊴|◂|∉|⋹̸|⋵̸|∉|⋷|⋶|∌|∌|⋾|⋽|∥|⊠|⨱|⨰|&(?:AElig|AMP|Aacute|Acirc|Agrave|Aring|Atilde|Auml|COPY|Ccedil|ETH|Eacute|Ecirc|Egrave|Euml|GT|Iacute|Icirc|Igrave|Iuml|LT|Ntilde|Oacute|Ocirc|Ograve|Oslash|Otilde|Ouml|QUOT|REG|THORN|Uacute|Ucirc|Ugrave|Uuml|Yacute|aacute|acirc|acute|aelig|agrave|amp|aring|atilde|auml|brvbar|ccedil|cedil|cent|copy|curren|deg|divide|eacute|ecirc|egrave|eth|euml|frac12|frac14|frac34|gt|iacute|icirc|iexcl|igrave|iquest|iuml|laquo|lt|macr|micro|middot|nbsp|not|ntilde|oacute|ocirc|ograve|ordf|ordm|oslash|otilde|ouml|para|plusmn|pound|quot|raquo|reg|sect|shy|sup1|sup2|sup3|szlig|thorn|times|uacute|ucirc|ugrave|uml|uuml|yacute|yen|yuml|#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g +}; +export var namedReferences = {}; +namedReferences['xml'] = generateNamedReferences("lt~<~gt~>~quot~\"~apos~'~amp~&"); +namedReferences['html4'] = generateNamedReferences("apos~'~OElig~Œ~oelig~œ~Scaron~Š~scaron~š~Yuml~Ÿ~circ~ˆ~tilde~˜~ensp~ ~emsp~ ~thinsp~ ~zwnj~‌~zwj~‍~lrm~‎~rlm~‏~ndash~–~mdash~—~lsquo~‘~rsquo~’~sbquo~‚~ldquo~“~rdquo~”~bdquo~„~dagger~†~Dagger~‡~permil~‰~lsaquo~‹~rsaquo~›~euro~€~fnof~ƒ~Alpha~Α~Beta~Β~Gamma~Γ~Delta~Δ~Epsilon~Ε~Zeta~Ζ~Eta~Η~Theta~Θ~Iota~Ι~Kappa~Κ~Lambda~Λ~Mu~Μ~Nu~Ν~Xi~Ξ~Omicron~Ο~Pi~Π~Rho~Ρ~Sigma~Σ~Tau~Τ~Upsilon~Υ~Phi~Φ~Chi~Χ~Psi~Ψ~Omega~Ω~alpha~α~beta~β~gamma~γ~delta~δ~epsilon~ε~zeta~ζ~eta~η~theta~θ~iota~ι~kappa~κ~lambda~λ~mu~μ~nu~ν~xi~ξ~omicron~ο~pi~π~rho~ρ~sigmaf~ς~sigma~σ~tau~τ~upsilon~υ~phi~φ~chi~χ~psi~ψ~omega~ω~thetasym~ϑ~upsih~ϒ~piv~ϖ~bull~•~hellip~…~prime~′~Prime~″~oline~‾~frasl~⁄~weierp~℘~image~ℑ~real~ℜ~trade~™~alefsym~ℵ~larr~←~uarr~↑~rarr~→~darr~↓~harr~↔~crarr~↵~lArr~⇐~uArr~⇑~rArr~⇒~dArr~⇓~hArr~⇔~forall~∀~part~∂~exist~∃~empty~∅~nabla~∇~isin~∈~notin~∉~ni~∋~prod~∏~sum~∑~minus~−~lowast~∗~radic~√~prop~∝~infin~∞~ang~∠~and~∧~or~∨~cap~∩~cup~∪~int~∫~there4~∴~sim~∼~cong~≅~asymp~≈~ne~≠~equiv~≡~le~≤~ge~≥~sub~⊂~sup~⊃~nsub~⊄~sube~⊆~supe~⊇~oplus~⊕~otimes~⊗~perp~⊥~sdot~⋅~lceil~⌈~rceil~⌉~lfloor~⌊~rfloor~⌋~lang~〈~rang~〉~loz~◊~spades~♠~clubs~♣~hearts~♥~diams~♦~~nbsp~ ~iexcl~¡~cent~¢~pound~£~curren~¤~yen~¥~brvbar~¦~sect~§~uml~¨~copy~©~ordf~ª~laquo~«~not~¬~shy~­~reg~®~macr~¯~deg~°~plusmn~±~sup2~²~sup3~³~acute~´~micro~µ~para~¶~middot~·~cedil~¸~sup1~¹~ordm~º~raquo~»~frac14~¼~frac12~½~frac34~¾~iquest~¿~Agrave~À~Aacute~Á~Acirc~Â~Atilde~Ã~Auml~Ä~Aring~Å~AElig~Æ~Ccedil~Ç~Egrave~È~Eacute~É~Ecirc~Ê~Euml~Ë~Igrave~Ì~Iacute~Í~Icirc~Î~Iuml~Ï~ETH~Ð~Ntilde~Ñ~Ograve~Ò~Oacute~Ó~Ocirc~Ô~Otilde~Õ~Ouml~Ö~times~×~Oslash~Ø~Ugrave~Ù~Uacute~Ú~Ucirc~Û~Uuml~Ü~Yacute~Ý~THORN~Þ~szlig~ß~agrave~à~aacute~á~acirc~â~atilde~ã~auml~ä~aring~å~aelig~æ~ccedil~ç~egrave~è~eacute~é~ecirc~ê~euml~ë~igrave~ì~iacute~í~icirc~î~iuml~ï~eth~ð~ntilde~ñ~ograve~ò~oacute~ó~ocirc~ô~otilde~õ~ouml~ö~divide~÷~oslash~ø~ugrave~ù~uacute~ú~ucirc~û~uuml~ü~yacute~ý~thorn~þ~yuml~ÿ~quot~\"~amp~&~lt~<~gt~>"); +namedReferences['html5'] = generateNamedReferences("Abreve~Ă~Acy~А~Afr~𝔄~Amacr~Ā~And~⩓~Aogon~Ą~Aopf~𝔸~ApplyFunction~⁡~Ascr~𝒜~Assign~≔~Backslash~∖~Barv~⫧~Barwed~⌆~Bcy~Б~Because~∵~Bernoullis~ℬ~Bfr~𝔅~Bopf~𝔹~Breve~˘~Bscr~ℬ~Bumpeq~≎~CHcy~Ч~Cacute~Ć~Cap~⋒~CapitalDifferentialD~ⅅ~Cayleys~ℭ~Ccaron~Č~Ccirc~Ĉ~Cconint~∰~Cdot~Ċ~Cedilla~¸~CenterDot~·~Cfr~ℭ~CircleDot~⊙~CircleMinus~⊖~CirclePlus~⊕~CircleTimes~⊗~ClockwiseContourIntegral~∲~CloseCurlyDoubleQuote~”~CloseCurlyQuote~’~Colon~∷~Colone~⩴~Congruent~≡~Conint~∯~ContourIntegral~∮~Copf~ℂ~Coproduct~∐~CounterClockwiseContourIntegral~∳~Cross~⨯~Cscr~𝒞~Cup~⋓~CupCap~≍~DD~ⅅ~DDotrahd~⤑~DJcy~Ђ~DScy~Ѕ~DZcy~Џ~Darr~↡~Dashv~⫤~Dcaron~Ď~Dcy~Д~Del~∇~Dfr~𝔇~DiacriticalAcute~´~DiacriticalDot~˙~DiacriticalDoubleAcute~˝~DiacriticalGrave~`~DiacriticalTilde~˜~Diamond~⋄~DifferentialD~ⅆ~Dopf~𝔻~Dot~¨~DotDot~⃜~DotEqual~≐~DoubleContourIntegral~∯~DoubleDot~¨~DoubleDownArrow~⇓~DoubleLeftArrow~⇐~DoubleLeftRightArrow~⇔~DoubleLeftTee~⫤~DoubleLongLeftArrow~⟸~DoubleLongLeftRightArrow~⟺~DoubleLongRightArrow~⟹~DoubleRightArrow~⇒~DoubleRightTee~⊨~DoubleUpArrow~⇑~DoubleUpDownArrow~⇕~DoubleVerticalBar~∥~DownArrow~↓~DownArrowBar~⤓~DownArrowUpArrow~⇵~DownBreve~̑~DownLeftRightVector~⥐~DownLeftTeeVector~⥞~DownLeftVector~↽~DownLeftVectorBar~⥖~DownRightTeeVector~⥟~DownRightVector~⇁~DownRightVectorBar~⥗~DownTee~⊤~DownTeeArrow~↧~Downarrow~⇓~Dscr~𝒟~Dstrok~Đ~ENG~Ŋ~Ecaron~Ě~Ecy~Э~Edot~Ė~Efr~𝔈~Element~∈~Emacr~Ē~EmptySmallSquare~◻~EmptyVerySmallSquare~▫~Eogon~Ę~Eopf~𝔼~Equal~⩵~EqualTilde~≂~Equilibrium~⇌~Escr~ℰ~Esim~⩳~Exists~∃~ExponentialE~ⅇ~Fcy~Ф~Ffr~𝔉~FilledSmallSquare~◼~FilledVerySmallSquare~▪~Fopf~𝔽~ForAll~∀~Fouriertrf~ℱ~Fscr~ℱ~GJcy~Ѓ~Gammad~Ϝ~Gbreve~Ğ~Gcedil~Ģ~Gcirc~Ĝ~Gcy~Г~Gdot~Ġ~Gfr~𝔊~Gg~⋙~Gopf~𝔾~GreaterEqual~≥~GreaterEqualLess~⋛~GreaterFullEqual~≧~GreaterGreater~⪢~GreaterLess~≷~GreaterSlantEqual~⩾~GreaterTilde~≳~Gscr~𝒢~Gt~≫~HARDcy~Ъ~Hacek~ˇ~Hat~^~Hcirc~Ĥ~Hfr~ℌ~HilbertSpace~ℋ~Hopf~ℍ~HorizontalLine~─~Hscr~ℋ~Hstrok~Ħ~HumpDownHump~≎~HumpEqual~≏~IEcy~Е~IJlig~IJ~IOcy~Ё~Icy~И~Idot~İ~Ifr~ℑ~Im~ℑ~Imacr~Ī~ImaginaryI~ⅈ~Implies~⇒~Int~∬~Integral~∫~Intersection~⋂~InvisibleComma~⁣~InvisibleTimes~⁢~Iogon~Į~Iopf~𝕀~Iscr~ℐ~Itilde~Ĩ~Iukcy~І~Jcirc~Ĵ~Jcy~Й~Jfr~𝔍~Jopf~𝕁~Jscr~𝒥~Jsercy~Ј~Jukcy~Є~KHcy~Х~KJcy~Ќ~Kcedil~Ķ~Kcy~К~Kfr~𝔎~Kopf~𝕂~Kscr~𝒦~LJcy~Љ~Lacute~Ĺ~Lang~⟪~Laplacetrf~ℒ~Larr~↞~Lcaron~Ľ~Lcedil~Ļ~Lcy~Л~LeftAngleBracket~⟨~LeftArrow~←~LeftArrowBar~⇤~LeftArrowRightArrow~⇆~LeftCeiling~⌈~LeftDoubleBracket~⟦~LeftDownTeeVector~⥡~LeftDownVector~⇃~LeftDownVectorBar~⥙~LeftFloor~⌊~LeftRightArrow~↔~LeftRightVector~⥎~LeftTee~⊣~LeftTeeArrow~↤~LeftTeeVector~⥚~LeftTriangle~⊲~LeftTriangleBar~⧏~LeftTriangleEqual~⊴~LeftUpDownVector~⥑~LeftUpTeeVector~⥠~LeftUpVector~↿~LeftUpVectorBar~⥘~LeftVector~↼~LeftVectorBar~⥒~Leftarrow~⇐~Leftrightarrow~⇔~LessEqualGreater~⋚~LessFullEqual~≦~LessGreater~≶~LessLess~⪡~LessSlantEqual~⩽~LessTilde~≲~Lfr~𝔏~Ll~⋘~Lleftarrow~⇚~Lmidot~Ŀ~LongLeftArrow~⟵~LongLeftRightArrow~⟷~LongRightArrow~⟶~Longleftarrow~⟸~Longleftrightarrow~⟺~Longrightarrow~⟹~Lopf~𝕃~LowerLeftArrow~↙~LowerRightArrow~↘~Lscr~ℒ~Lsh~↰~Lstrok~Ł~Lt~≪~Map~⤅~Mcy~М~MediumSpace~ ~Mellintrf~ℳ~Mfr~𝔐~MinusPlus~∓~Mopf~𝕄~Mscr~ℳ~NJcy~Њ~Nacute~Ń~Ncaron~Ň~Ncedil~Ņ~Ncy~Н~NegativeMediumSpace~​~NegativeThickSpace~​~NegativeThinSpace~​~NegativeVeryThinSpace~​~NestedGreaterGreater~≫~NestedLessLess~≪~NewLine~\n~Nfr~𝔑~NoBreak~⁠~NonBreakingSpace~ ~Nopf~ℕ~Not~⫬~NotCongruent~≢~NotCupCap~≭~NotDoubleVerticalBar~∦~NotElement~∉~NotEqual~≠~NotEqualTilde~≂̸~NotExists~∄~NotGreater~≯~NotGreaterEqual~≱~NotGreaterFullEqual~≧̸~NotGreaterGreater~≫̸~NotGreaterLess~≹~NotGreaterSlantEqual~⩾̸~NotGreaterTilde~≵~NotHumpDownHump~≎̸~NotHumpEqual~≏̸~NotLeftTriangle~⋪~NotLeftTriangleBar~⧏̸~NotLeftTriangleEqual~⋬~NotLess~≮~NotLessEqual~≰~NotLessGreater~≸~NotLessLess~≪̸~NotLessSlantEqual~⩽̸~NotLessTilde~≴~NotNestedGreaterGreater~⪢̸~NotNestedLessLess~⪡̸~NotPrecedes~⊀~NotPrecedesEqual~⪯̸~NotPrecedesSlantEqual~⋠~NotReverseElement~∌~NotRightTriangle~⋫~NotRightTriangleBar~⧐̸~NotRightTriangleEqual~⋭~NotSquareSubset~⊏̸~NotSquareSubsetEqual~⋢~NotSquareSuperset~⊐̸~NotSquareSupersetEqual~⋣~NotSubset~⊂⃒~NotSubsetEqual~⊈~NotSucceeds~⊁~NotSucceedsEqual~⪰̸~NotSucceedsSlantEqual~⋡~NotSucceedsTilde~≿̸~NotSuperset~⊃⃒~NotSupersetEqual~⊉~NotTilde~≁~NotTildeEqual~≄~NotTildeFullEqual~≇~NotTildeTilde~≉~NotVerticalBar~∤~Nscr~𝒩~Ocy~О~Odblac~Ő~Ofr~𝔒~Omacr~Ō~Oopf~𝕆~OpenCurlyDoubleQuote~“~OpenCurlyQuote~‘~Or~⩔~Oscr~𝒪~Otimes~⨷~OverBar~‾~OverBrace~⏞~OverBracket~⎴~OverParenthesis~⏜~PartialD~∂~Pcy~П~Pfr~𝔓~PlusMinus~±~Poincareplane~ℌ~Popf~ℙ~Pr~⪻~Precedes~≺~PrecedesEqual~⪯~PrecedesSlantEqual~≼~PrecedesTilde~≾~Product~∏~Proportion~∷~Proportional~∝~Pscr~𝒫~Qfr~𝔔~Qopf~ℚ~Qscr~𝒬~RBarr~⤐~Racute~Ŕ~Rang~⟫~Rarr~↠~Rarrtl~⤖~Rcaron~Ř~Rcedil~Ŗ~Rcy~Р~Re~ℜ~ReverseElement~∋~ReverseEquilibrium~⇋~ReverseUpEquilibrium~⥯~Rfr~ℜ~RightAngleBracket~⟩~RightArrow~→~RightArrowBar~⇥~RightArrowLeftArrow~⇄~RightCeiling~⌉~RightDoubleBracket~⟧~RightDownTeeVector~⥝~RightDownVector~⇂~RightDownVectorBar~⥕~RightFloor~⌋~RightTee~⊢~RightTeeArrow~↦~RightTeeVector~⥛~RightTriangle~⊳~RightTriangleBar~⧐~RightTriangleEqual~⊵~RightUpDownVector~⥏~RightUpTeeVector~⥜~RightUpVector~↾~RightUpVectorBar~⥔~RightVector~⇀~RightVectorBar~⥓~Rightarrow~⇒~Ropf~ℝ~RoundImplies~⥰~Rrightarrow~⇛~Rscr~ℛ~Rsh~↱~RuleDelayed~⧴~SHCHcy~Щ~SHcy~Ш~SOFTcy~Ь~Sacute~Ś~Sc~⪼~Scedil~Ş~Scirc~Ŝ~Scy~С~Sfr~𝔖~ShortDownArrow~↓~ShortLeftArrow~←~ShortRightArrow~→~ShortUpArrow~↑~SmallCircle~∘~Sopf~𝕊~Sqrt~√~Square~□~SquareIntersection~⊓~SquareSubset~⊏~SquareSubsetEqual~⊑~SquareSuperset~⊐~SquareSupersetEqual~⊒~SquareUnion~⊔~Sscr~𝒮~Star~⋆~Sub~⋐~Subset~⋐~SubsetEqual~⊆~Succeeds~≻~SucceedsEqual~⪰~SucceedsSlantEqual~≽~SucceedsTilde~≿~SuchThat~∋~Sum~∑~Sup~⋑~Superset~⊃~SupersetEqual~⊇~Supset~⋑~TRADE~™~TSHcy~Ћ~TScy~Ц~Tab~\t~Tcaron~Ť~Tcedil~Ţ~Tcy~Т~Tfr~𝔗~Therefore~∴~ThickSpace~  ~ThinSpace~ ~Tilde~∼~TildeEqual~≃~TildeFullEqual~≅~TildeTilde~≈~Topf~𝕋~TripleDot~⃛~Tscr~𝒯~Tstrok~Ŧ~Uarr~↟~Uarrocir~⥉~Ubrcy~Ў~Ubreve~Ŭ~Ucy~У~Udblac~Ű~Ufr~𝔘~Umacr~Ū~UnderBar~_~UnderBrace~⏟~UnderBracket~⎵~UnderParenthesis~⏝~Union~⋃~UnionPlus~⊎~Uogon~Ų~Uopf~𝕌~UpArrow~↑~UpArrowBar~⤒~UpArrowDownArrow~⇅~UpDownArrow~↕~UpEquilibrium~⥮~UpTee~⊥~UpTeeArrow~↥~Uparrow~⇑~Updownarrow~⇕~UpperLeftArrow~↖~UpperRightArrow~↗~Upsi~ϒ~Uring~Ů~Uscr~𝒰~Utilde~Ũ~VDash~⊫~Vbar~⫫~Vcy~В~Vdash~⊩~Vdashl~⫦~Vee~⋁~Verbar~‖~Vert~‖~VerticalBar~∣~VerticalLine~|~VerticalSeparator~❘~VerticalTilde~≀~VeryThinSpace~ ~Vfr~𝔙~Vopf~𝕍~Vscr~𝒱~Vvdash~⊪~Wcirc~Ŵ~Wedge~⋀~Wfr~𝔚~Wopf~𝕎~Wscr~𝒲~Xfr~𝔛~Xopf~𝕏~Xscr~𝒳~YAcy~Я~YIcy~Ї~YUcy~Ю~Ycirc~Ŷ~Ycy~Ы~Yfr~𝔜~Yopf~𝕐~Yscr~𝒴~ZHcy~Ж~Zacute~Ź~Zcaron~Ž~Zcy~З~Zdot~Ż~ZeroWidthSpace~​~Zfr~ℨ~Zopf~ℤ~Zscr~𝒵~abreve~ă~ac~∾~acE~∾̳~acd~∿~acy~а~af~⁡~afr~𝔞~aleph~ℵ~amacr~ā~amalg~⨿~andand~⩕~andd~⩜~andslope~⩘~andv~⩚~ange~⦤~angle~∠~angmsd~∡~angmsdaa~⦨~angmsdab~⦩~angmsdac~⦪~angmsdad~⦫~angmsdae~⦬~angmsdaf~⦭~angmsdag~⦮~angmsdah~⦯~angrt~∟~angrtvb~⊾~angrtvbd~⦝~angsph~∢~angst~Å~angzarr~⍼~aogon~ą~aopf~𝕒~ap~≈~apE~⩰~apacir~⩯~ape~≊~apid~≋~approx~≈~approxeq~≊~ascr~𝒶~ast~*~asympeq~≍~awconint~∳~awint~⨑~bNot~⫭~backcong~≌~backepsilon~϶~backprime~‵~backsim~∽~backsimeq~⋍~barvee~⊽~barwed~⌅~barwedge~⌅~bbrk~⎵~bbrktbrk~⎶~bcong~≌~bcy~б~becaus~∵~because~∵~bemptyv~⦰~bepsi~϶~bernou~ℬ~beth~ℶ~between~≬~bfr~𝔟~bigcap~⋂~bigcirc~◯~bigcup~⋃~bigodot~⨀~bigoplus~⨁~bigotimes~⨂~bigsqcup~⨆~bigstar~★~bigtriangledown~▽~bigtriangleup~△~biguplus~⨄~bigvee~⋁~bigwedge~⋀~bkarow~⤍~blacklozenge~⧫~blacksquare~▪~blacktriangle~▴~blacktriangledown~▾~blacktriangleleft~◂~blacktriangleright~▸~blank~␣~blk12~▒~blk14~░~blk34~▓~block~█~bne~=⃥~bnequiv~≡⃥~bnot~⌐~bopf~𝕓~bot~⊥~bottom~⊥~bowtie~⋈~boxDL~╗~boxDR~╔~boxDl~╖~boxDr~╓~boxH~═~boxHD~╦~boxHU~╩~boxHd~╤~boxHu~╧~boxUL~╝~boxUR~╚~boxUl~╜~boxUr~╙~boxV~║~boxVH~╬~boxVL~╣~boxVR~╠~boxVh~╫~boxVl~╢~boxVr~╟~boxbox~⧉~boxdL~╕~boxdR~╒~boxdl~┐~boxdr~┌~boxh~─~boxhD~╥~boxhU~╨~boxhd~┬~boxhu~┴~boxminus~⊟~boxplus~⊞~boxtimes~⊠~boxuL~╛~boxuR~╘~boxul~┘~boxur~└~boxv~│~boxvH~╪~boxvL~╡~boxvR~╞~boxvh~┼~boxvl~┤~boxvr~├~bprime~‵~breve~˘~bscr~𝒷~bsemi~⁏~bsim~∽~bsime~⋍~bsol~\\~bsolb~⧅~bsolhsub~⟈~bullet~•~bump~≎~bumpE~⪮~bumpe~≏~bumpeq~≏~cacute~ć~capand~⩄~capbrcup~⩉~capcap~⩋~capcup~⩇~capdot~⩀~caps~∩︀~caret~⁁~caron~ˇ~ccaps~⩍~ccaron~č~ccirc~ĉ~ccups~⩌~ccupssm~⩐~cdot~ċ~cemptyv~⦲~centerdot~·~cfr~𝔠~chcy~ч~check~✓~checkmark~✓~cir~○~cirE~⧃~circeq~≗~circlearrowleft~↺~circlearrowright~↻~circledR~®~circledS~Ⓢ~circledast~⊛~circledcirc~⊚~circleddash~⊝~cire~≗~cirfnint~⨐~cirmid~⫯~cirscir~⧂~clubsuit~♣~colon~:~colone~≔~coloneq~≔~comma~,~commat~@~comp~∁~compfn~∘~complement~∁~complexes~ℂ~congdot~⩭~conint~∮~copf~𝕔~coprod~∐~copysr~℗~cross~✗~cscr~𝒸~csub~⫏~csube~⫑~csup~⫐~csupe~⫒~ctdot~⋯~cudarrl~⤸~cudarrr~⤵~cuepr~⋞~cuesc~⋟~cularr~↶~cularrp~⤽~cupbrcap~⩈~cupcap~⩆~cupcup~⩊~cupdot~⊍~cupor~⩅~cups~∪︀~curarr~↷~curarrm~⤼~curlyeqprec~⋞~curlyeqsucc~⋟~curlyvee~⋎~curlywedge~⋏~curvearrowleft~↶~curvearrowright~↷~cuvee~⋎~cuwed~⋏~cwconint~∲~cwint~∱~cylcty~⌭~dHar~⥥~daleth~ℸ~dash~‐~dashv~⊣~dbkarow~⤏~dblac~˝~dcaron~ď~dcy~д~dd~ⅆ~ddagger~‡~ddarr~⇊~ddotseq~⩷~demptyv~⦱~dfisht~⥿~dfr~𝔡~dharl~⇃~dharr~⇂~diam~⋄~diamond~⋄~diamondsuit~♦~die~¨~digamma~ϝ~disin~⋲~div~÷~divideontimes~⋇~divonx~⋇~djcy~ђ~dlcorn~⌞~dlcrop~⌍~dollar~$~dopf~𝕕~dot~˙~doteq~≐~doteqdot~≑~dotminus~∸~dotplus~∔~dotsquare~⊡~doublebarwedge~⌆~downarrow~↓~downdownarrows~⇊~downharpoonleft~⇃~downharpoonright~⇂~drbkarow~⤐~drcorn~⌟~drcrop~⌌~dscr~𝒹~dscy~ѕ~dsol~⧶~dstrok~đ~dtdot~⋱~dtri~▿~dtrif~▾~duarr~⇵~duhar~⥯~dwangle~⦦~dzcy~џ~dzigrarr~⟿~eDDot~⩷~eDot~≑~easter~⩮~ecaron~ě~ecir~≖~ecolon~≕~ecy~э~edot~ė~ee~ⅇ~efDot~≒~efr~𝔢~eg~⪚~egs~⪖~egsdot~⪘~el~⪙~elinters~⏧~ell~ℓ~els~⪕~elsdot~⪗~emacr~ē~emptyset~∅~emptyv~∅~emsp13~ ~emsp14~ ~eng~ŋ~eogon~ę~eopf~𝕖~epar~⋕~eparsl~⧣~eplus~⩱~epsi~ε~epsiv~ϵ~eqcirc~≖~eqcolon~≕~eqsim~≂~eqslantgtr~⪖~eqslantless~⪕~equals~=~equest~≟~equivDD~⩸~eqvparsl~⧥~erDot~≓~erarr~⥱~escr~ℯ~esdot~≐~esim~≂~excl~!~expectation~ℰ~exponentiale~ⅇ~fallingdotseq~≒~fcy~ф~female~♀~ffilig~ffi~fflig~ff~ffllig~ffl~ffr~𝔣~filig~fi~fjlig~fj~flat~♭~fllig~fl~fltns~▱~fopf~𝕗~fork~⋔~forkv~⫙~fpartint~⨍~frac13~⅓~frac15~⅕~frac16~⅙~frac18~⅛~frac23~⅔~frac25~⅖~frac35~⅗~frac38~⅜~frac45~⅘~frac56~⅚~frac58~⅝~frac78~⅞~frown~⌢~fscr~𝒻~gE~≧~gEl~⪌~gacute~ǵ~gammad~ϝ~gap~⪆~gbreve~ğ~gcirc~ĝ~gcy~г~gdot~ġ~gel~⋛~geq~≥~geqq~≧~geqslant~⩾~ges~⩾~gescc~⪩~gesdot~⪀~gesdoto~⪂~gesdotol~⪄~gesl~⋛︀~gesles~⪔~gfr~𝔤~gg~≫~ggg~⋙~gimel~ℷ~gjcy~ѓ~gl~≷~glE~⪒~gla~⪥~glj~⪤~gnE~≩~gnap~⪊~gnapprox~⪊~gne~⪈~gneq~⪈~gneqq~≩~gnsim~⋧~gopf~𝕘~grave~`~gscr~ℊ~gsim~≳~gsime~⪎~gsiml~⪐~gtcc~⪧~gtcir~⩺~gtdot~⋗~gtlPar~⦕~gtquest~⩼~gtrapprox~⪆~gtrarr~⥸~gtrdot~⋗~gtreqless~⋛~gtreqqless~⪌~gtrless~≷~gtrsim~≳~gvertneqq~≩︀~gvnE~≩︀~hairsp~ ~half~½~hamilt~ℋ~hardcy~ъ~harrcir~⥈~harrw~↭~hbar~ℏ~hcirc~ĥ~heartsuit~♥~hercon~⊹~hfr~𝔥~hksearow~⤥~hkswarow~⤦~hoarr~⇿~homtht~∻~hookleftarrow~↩~hookrightarrow~↪~hopf~𝕙~horbar~―~hscr~𝒽~hslash~ℏ~hstrok~ħ~hybull~⁃~hyphen~‐~ic~⁣~icy~и~iecy~е~iff~⇔~ifr~𝔦~ii~ⅈ~iiiint~⨌~iiint~∭~iinfin~⧜~iiota~℩~ijlig~ij~imacr~ī~imagline~ℐ~imagpart~ℑ~imath~ı~imof~⊷~imped~Ƶ~in~∈~incare~℅~infintie~⧝~inodot~ı~intcal~⊺~integers~ℤ~intercal~⊺~intlarhk~⨗~intprod~⨼~iocy~ё~iogon~į~iopf~𝕚~iprod~⨼~iscr~𝒾~isinE~⋹~isindot~⋵~isins~⋴~isinsv~⋳~isinv~∈~it~⁢~itilde~ĩ~iukcy~і~jcirc~ĵ~jcy~й~jfr~𝔧~jmath~ȷ~jopf~𝕛~jscr~𝒿~jsercy~ј~jukcy~є~kappav~ϰ~kcedil~ķ~kcy~к~kfr~𝔨~kgreen~ĸ~khcy~х~kjcy~ќ~kopf~𝕜~kscr~𝓀~lAarr~⇚~lAtail~⤛~lBarr~⤎~lE~≦~lEg~⪋~lHar~⥢~lacute~ĺ~laemptyv~⦴~lagran~ℒ~langd~⦑~langle~⟨~lap~⪅~larrb~⇤~larrbfs~⤟~larrfs~⤝~larrhk~↩~larrlp~↫~larrpl~⤹~larrsim~⥳~larrtl~↢~lat~⪫~latail~⤙~late~⪭~lates~⪭︀~lbarr~⤌~lbbrk~❲~lbrace~{~lbrack~[~lbrke~⦋~lbrksld~⦏~lbrkslu~⦍~lcaron~ľ~lcedil~ļ~lcub~{~lcy~л~ldca~⤶~ldquor~„~ldrdhar~⥧~ldrushar~⥋~ldsh~↲~leftarrow~←~leftarrowtail~↢~leftharpoondown~↽~leftharpoonup~↼~leftleftarrows~⇇~leftrightarrow~↔~leftrightarrows~⇆~leftrightharpoons~⇋~leftrightsquigarrow~↭~leftthreetimes~⋋~leg~⋚~leq~≤~leqq~≦~leqslant~⩽~les~⩽~lescc~⪨~lesdot~⩿~lesdoto~⪁~lesdotor~⪃~lesg~⋚︀~lesges~⪓~lessapprox~⪅~lessdot~⋖~lesseqgtr~⋚~lesseqqgtr~⪋~lessgtr~≶~lesssim~≲~lfisht~⥼~lfr~𝔩~lg~≶~lgE~⪑~lhard~↽~lharu~↼~lharul~⥪~lhblk~▄~ljcy~љ~ll~≪~llarr~⇇~llcorner~⌞~llhard~⥫~lltri~◺~lmidot~ŀ~lmoust~⎰~lmoustache~⎰~lnE~≨~lnap~⪉~lnapprox~⪉~lne~⪇~lneq~⪇~lneqq~≨~lnsim~⋦~loang~⟬~loarr~⇽~lobrk~⟦~longleftarrow~⟵~longleftrightarrow~⟷~longmapsto~⟼~longrightarrow~⟶~looparrowleft~↫~looparrowright~↬~lopar~⦅~lopf~𝕝~loplus~⨭~lotimes~⨴~lowbar~_~lozenge~◊~lozf~⧫~lpar~(~lparlt~⦓~lrarr~⇆~lrcorner~⌟~lrhar~⇋~lrhard~⥭~lrtri~⊿~lscr~𝓁~lsh~↰~lsim~≲~lsime~⪍~lsimg~⪏~lsqb~[~lsquor~‚~lstrok~ł~ltcc~⪦~ltcir~⩹~ltdot~⋖~lthree~⋋~ltimes~⋉~ltlarr~⥶~ltquest~⩻~ltrPar~⦖~ltri~◃~ltrie~⊴~ltrif~◂~lurdshar~⥊~luruhar~⥦~lvertneqq~≨︀~lvnE~≨︀~mDDot~∺~male~♂~malt~✠~maltese~✠~map~↦~mapsto~↦~mapstodown~↧~mapstoleft~↤~mapstoup~↥~marker~▮~mcomma~⨩~mcy~м~measuredangle~∡~mfr~𝔪~mho~℧~mid~∣~midast~*~midcir~⫰~minusb~⊟~minusd~∸~minusdu~⨪~mlcp~⫛~mldr~…~mnplus~∓~models~⊧~mopf~𝕞~mp~∓~mscr~𝓂~mstpos~∾~multimap~⊸~mumap~⊸~nGg~⋙̸~nGt~≫⃒~nGtv~≫̸~nLeftarrow~⇍~nLeftrightarrow~⇎~nLl~⋘̸~nLt~≪⃒~nLtv~≪̸~nRightarrow~⇏~nVDash~⊯~nVdash~⊮~nacute~ń~nang~∠⃒~nap~≉~napE~⩰̸~napid~≋̸~napos~ʼn~napprox~≉~natur~♮~natural~♮~naturals~ℕ~nbump~≎̸~nbumpe~≏̸~ncap~⩃~ncaron~ň~ncedil~ņ~ncong~≇~ncongdot~⩭̸~ncup~⩂~ncy~н~neArr~⇗~nearhk~⤤~nearr~↗~nearrow~↗~nedot~≐̸~nequiv~≢~nesear~⤨~nesim~≂̸~nexist~∄~nexists~∄~nfr~𝔫~ngE~≧̸~nge~≱~ngeq~≱~ngeqq~≧̸~ngeqslant~⩾̸~nges~⩾̸~ngsim~≵~ngt~≯~ngtr~≯~nhArr~⇎~nharr~↮~nhpar~⫲~nis~⋼~nisd~⋺~niv~∋~njcy~њ~nlArr~⇍~nlE~≦̸~nlarr~↚~nldr~‥~nle~≰~nleftarrow~↚~nleftrightarrow~↮~nleq~≰~nleqq~≦̸~nleqslant~⩽̸~nles~⩽̸~nless~≮~nlsim~≴~nlt~≮~nltri~⋪~nltrie~⋬~nmid~∤~nopf~𝕟~notinE~⋹̸~notindot~⋵̸~notinva~∉~notinvb~⋷~notinvc~⋶~notni~∌~notniva~∌~notnivb~⋾~notnivc~⋽~npar~∦~nparallel~∦~nparsl~⫽⃥~npart~∂̸~npolint~⨔~npr~⊀~nprcue~⋠~npre~⪯̸~nprec~⊀~npreceq~⪯̸~nrArr~⇏~nrarr~↛~nrarrc~⤳̸~nrarrw~↝̸~nrightarrow~↛~nrtri~⋫~nrtrie~⋭~nsc~⊁~nsccue~⋡~nsce~⪰̸~nscr~𝓃~nshortmid~∤~nshortparallel~∦~nsim~≁~nsime~≄~nsimeq~≄~nsmid~∤~nspar~∦~nsqsube~⋢~nsqsupe~⋣~nsubE~⫅̸~nsube~⊈~nsubset~⊂⃒~nsubseteq~⊈~nsubseteqq~⫅̸~nsucc~⊁~nsucceq~⪰̸~nsup~⊅~nsupE~⫆̸~nsupe~⊉~nsupset~⊃⃒~nsupseteq~⊉~nsupseteqq~⫆̸~ntgl~≹~ntlg~≸~ntriangleleft~⋪~ntrianglelefteq~⋬~ntriangleright~⋫~ntrianglerighteq~⋭~num~#~numero~№~numsp~ ~nvDash~⊭~nvHarr~⤄~nvap~≍⃒~nvdash~⊬~nvge~≥⃒~nvgt~>⃒~nvinfin~⧞~nvlArr~⤂~nvle~≤⃒~nvlt~<⃒~nvltrie~⊴⃒~nvrArr~⤃~nvrtrie~⊵⃒~nvsim~∼⃒~nwArr~⇖~nwarhk~⤣~nwarr~↖~nwarrow~↖~nwnear~⤧~oS~Ⓢ~oast~⊛~ocir~⊚~ocy~о~odash~⊝~odblac~ő~odiv~⨸~odot~⊙~odsold~⦼~ofcir~⦿~ofr~𝔬~ogon~˛~ogt~⧁~ohbar~⦵~ohm~Ω~oint~∮~olarr~↺~olcir~⦾~olcross~⦻~olt~⧀~omacr~ō~omid~⦶~ominus~⊖~oopf~𝕠~opar~⦷~operp~⦹~orarr~↻~ord~⩝~order~ℴ~orderof~ℴ~origof~⊶~oror~⩖~orslope~⩗~orv~⩛~oscr~ℴ~osol~⊘~otimesas~⨶~ovbar~⌽~par~∥~parallel~∥~parsim~⫳~parsl~⫽~pcy~п~percnt~%~period~.~pertenk~‱~pfr~𝔭~phiv~ϕ~phmmat~ℳ~phone~☎~pitchfork~⋔~planck~ℏ~planckh~ℎ~plankv~ℏ~plus~+~plusacir~⨣~plusb~⊞~pluscir~⨢~plusdo~∔~plusdu~⨥~pluse~⩲~plussim~⨦~plustwo~⨧~pm~±~pointint~⨕~popf~𝕡~pr~≺~prE~⪳~prap~⪷~prcue~≼~pre~⪯~prec~≺~precapprox~⪷~preccurlyeq~≼~preceq~⪯~precnapprox~⪹~precneqq~⪵~precnsim~⋨~precsim~≾~primes~ℙ~prnE~⪵~prnap~⪹~prnsim~⋨~profalar~⌮~profline~⌒~profsurf~⌓~propto~∝~prsim~≾~prurel~⊰~pscr~𝓅~puncsp~ ~qfr~𝔮~qint~⨌~qopf~𝕢~qprime~⁗~qscr~𝓆~quaternions~ℍ~quatint~⨖~quest~?~questeq~≟~rAarr~⇛~rAtail~⤜~rBarr~⤏~rHar~⥤~race~∽̱~racute~ŕ~raemptyv~⦳~rangd~⦒~range~⦥~rangle~⟩~rarrap~⥵~rarrb~⇥~rarrbfs~⤠~rarrc~⤳~rarrfs~⤞~rarrhk~↪~rarrlp~↬~rarrpl~⥅~rarrsim~⥴~rarrtl~↣~rarrw~↝~ratail~⤚~ratio~∶~rationals~ℚ~rbarr~⤍~rbbrk~❳~rbrace~}~rbrack~]~rbrke~⦌~rbrksld~⦎~rbrkslu~⦐~rcaron~ř~rcedil~ŗ~rcub~}~rcy~р~rdca~⤷~rdldhar~⥩~rdquor~”~rdsh~↳~realine~ℛ~realpart~ℜ~reals~ℝ~rect~▭~rfisht~⥽~rfr~𝔯~rhard~⇁~rharu~⇀~rharul~⥬~rhov~ϱ~rightarrow~→~rightarrowtail~↣~rightharpoondown~⇁~rightharpoonup~⇀~rightleftarrows~⇄~rightleftharpoons~⇌~rightrightarrows~⇉~rightsquigarrow~↝~rightthreetimes~⋌~ring~˚~risingdotseq~≓~rlarr~⇄~rlhar~⇌~rmoust~⎱~rmoustache~⎱~rnmid~⫮~roang~⟭~roarr~⇾~robrk~⟧~ropar~⦆~ropf~𝕣~roplus~⨮~rotimes~⨵~rpar~)~rpargt~⦔~rppolint~⨒~rrarr~⇉~rscr~𝓇~rsh~↱~rsqb~]~rsquor~’~rthree~⋌~rtimes~⋊~rtri~▹~rtrie~⊵~rtrif~▸~rtriltri~⧎~ruluhar~⥨~rx~℞~sacute~ś~sc~≻~scE~⪴~scap~⪸~sccue~≽~sce~⪰~scedil~ş~scirc~ŝ~scnE~⪶~scnap~⪺~scnsim~⋩~scpolint~⨓~scsim~≿~scy~с~sdotb~⊡~sdote~⩦~seArr~⇘~searhk~⤥~searr~↘~searrow~↘~semi~;~seswar~⤩~setminus~∖~setmn~∖~sext~✶~sfr~𝔰~sfrown~⌢~sharp~♯~shchcy~щ~shcy~ш~shortmid~∣~shortparallel~∥~sigmav~ς~simdot~⩪~sime~≃~simeq~≃~simg~⪞~simgE~⪠~siml~⪝~simlE~⪟~simne~≆~simplus~⨤~simrarr~⥲~slarr~←~smallsetminus~∖~smashp~⨳~smeparsl~⧤~smid~∣~smile~⌣~smt~⪪~smte~⪬~smtes~⪬︀~softcy~ь~sol~/~solb~⧄~solbar~⌿~sopf~𝕤~spadesuit~♠~spar~∥~sqcap~⊓~sqcaps~⊓︀~sqcup~⊔~sqcups~⊔︀~sqsub~⊏~sqsube~⊑~sqsubset~⊏~sqsubseteq~⊑~sqsup~⊐~sqsupe~⊒~sqsupset~⊐~sqsupseteq~⊒~squ~□~square~□~squarf~▪~squf~▪~srarr~→~sscr~𝓈~ssetmn~∖~ssmile~⌣~sstarf~⋆~star~☆~starf~★~straightepsilon~ϵ~straightphi~ϕ~strns~¯~subE~⫅~subdot~⪽~subedot~⫃~submult~⫁~subnE~⫋~subne~⊊~subplus~⪿~subrarr~⥹~subset~⊂~subseteq~⊆~subseteqq~⫅~subsetneq~⊊~subsetneqq~⫋~subsim~⫇~subsub~⫕~subsup~⫓~succ~≻~succapprox~⪸~succcurlyeq~≽~succeq~⪰~succnapprox~⪺~succneqq~⪶~succnsim~⋩~succsim~≿~sung~♪~supE~⫆~supdot~⪾~supdsub~⫘~supedot~⫄~suphsol~⟉~suphsub~⫗~suplarr~⥻~supmult~⫂~supnE~⫌~supne~⊋~supplus~⫀~supset~⊃~supseteq~⊇~supseteqq~⫆~supsetneq~⊋~supsetneqq~⫌~supsim~⫈~supsub~⫔~supsup~⫖~swArr~⇙~swarhk~⤦~swarr~↙~swarrow~↙~swnwar~⤪~target~⌖~tbrk~⎴~tcaron~ť~tcedil~ţ~tcy~т~tdot~⃛~telrec~⌕~tfr~𝔱~therefore~∴~thetav~ϑ~thickapprox~≈~thicksim~∼~thkap~≈~thksim~∼~timesb~⊠~timesbar~⨱~timesd~⨰~tint~∭~toea~⤨~top~⊤~topbot~⌶~topcir~⫱~topf~𝕥~topfork~⫚~tosa~⤩~tprime~‴~triangle~▵~triangledown~▿~triangleleft~◃~trianglelefteq~⊴~triangleq~≜~triangleright~▹~trianglerighteq~⊵~tridot~◬~trie~≜~triminus~⨺~triplus~⨹~trisb~⧍~tritime~⨻~trpezium~⏢~tscr~𝓉~tscy~ц~tshcy~ћ~tstrok~ŧ~twixt~≬~twoheadleftarrow~↞~twoheadrightarrow~↠~uHar~⥣~ubrcy~ў~ubreve~ŭ~ucy~у~udarr~⇅~udblac~ű~udhar~⥮~ufisht~⥾~ufr~𝔲~uharl~↿~uharr~↾~uhblk~▀~ulcorn~⌜~ulcorner~⌜~ulcrop~⌏~ultri~◸~umacr~ū~uogon~ų~uopf~𝕦~uparrow~↑~updownarrow~↕~upharpoonleft~↿~upharpoonright~↾~uplus~⊎~upsi~υ~upuparrows~⇈~urcorn~⌝~urcorner~⌝~urcrop~⌎~uring~ů~urtri~◹~uscr~𝓊~utdot~⋰~utilde~ũ~utri~▵~utrif~▴~uuarr~⇈~uwangle~⦧~vArr~⇕~vBar~⫨~vBarv~⫩~vDash~⊨~vangrt~⦜~varepsilon~ϵ~varkappa~ϰ~varnothing~∅~varphi~ϕ~varpi~ϖ~varpropto~∝~varr~↕~varrho~ϱ~varsigma~ς~varsubsetneq~⊊︀~varsubsetneqq~⫋︀~varsupsetneq~⊋︀~varsupsetneqq~⫌︀~vartheta~ϑ~vartriangleleft~⊲~vartriangleright~⊳~vcy~в~vdash~⊢~vee~∨~veebar~⊻~veeeq~≚~vellip~⋮~verbar~|~vert~|~vfr~𝔳~vltri~⊲~vnsub~⊂⃒~vnsup~⊃⃒~vopf~𝕧~vprop~∝~vrtri~⊳~vscr~𝓋~vsubnE~⫋︀~vsubne~⊊︀~vsupnE~⫌︀~vsupne~⊋︀~vzigzag~⦚~wcirc~ŵ~wedbar~⩟~wedge~∧~wedgeq~≙~wfr~𝔴~wopf~𝕨~wp~℘~wr~≀~wreath~≀~wscr~𝓌~xcap~⋂~xcirc~◯~xcup~⋃~xdtri~▽~xfr~𝔵~xhArr~⟺~xharr~⟷~xlArr~⟸~xlarr~⟵~xmap~⟼~xnis~⋻~xodot~⨀~xopf~𝕩~xoplus~⨁~xotime~⨂~xrArr~⟹~xrarr~⟶~xscr~𝓍~xsqcup~⨆~xuplus~⨄~xutri~△~xvee~⋁~xwedge~⋀~yacy~я~ycirc~ŷ~ycy~ы~yfr~𝔶~yicy~ї~yopf~𝕪~yscr~𝓎~yucy~ю~zacute~ź~zcaron~ž~zcy~з~zdot~ż~zeetrf~ℨ~zfr~𝔷~zhcy~ж~zigrarr~⇝~zopf~𝕫~zscr~𝓏~~AMP~&~COPY~©~GT~>~LT~<~QUOT~\"~REG~®", namedReferences['html4']); +//# sourceMappingURL=named-references.js.map \ No newline at end of file diff --git a/node_modules/html-entities/dist/esm/named-references.js.map b/node_modules/html-entities/dist/esm/named-references.js.map new file mode 100644 index 0000000..c0431a0 --- /dev/null +++ b/node_modules/html-entities/dist/esm/named-references.js.map @@ -0,0 +1 @@ +{"version":3,"file":"named-references.js","sourceRoot":"","sources":["../../src/named-references.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,kEAAkE;AAClE,IAAM,WAAW,GAAG,GAAG,CAAC;AACxB,IAAM,YAAY,GAAG,IAAI,CAAC;AAO1B,SAAS,uBAAuB,CAAC,KAAa,EAAE,IAA0B;IACtE,IAAM,QAAQ,GAA2B,EAAE,CAAC;IAC5C,IAAM,UAAU,GAA2B,EAAE,CAAC;IAC9C,IAAM,MAAM,GAAG,KAAK,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACzC,IAAI,eAAe,GAAG,KAAK,CAAC;IAC5B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QACrC,IAAM,OAAO,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;QAC7C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,IAAE,CAAC,EAAE,CAAC;YACvC,IAAM,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;YAC1B,IAAM,SAAS,GAAG,OAAO,CAAC,CAAC,GAAC,CAAC,CAAC,CAAC;YAC/B,IAAM,UAAU,GAAG,GAAG,GAAG,MAAM,GAAG,GAAG,CAAC;YACtC,QAAQ,CAAC,UAAU,CAAC,GAAG,SAAS,CAAC;YACjC,IAAI,eAAe,EAAE,CAAC;gBAClB,QAAQ,CAAC,GAAG,GAAG,MAAM,CAAC,GAAG,SAAS,CAAC;YACvC,CAAC;YACD,UAAU,CAAC,SAAS,CAAC,GAAG,UAAU,CAAC;QACvC,CAAC;QACD,eAAe,GAAG,IAAI,CAAC;IAC3B,CAAC;IACD,OAAO,IAAI,CAAC,CAAC;QACT,EAAC,QAAQ,wBAAM,QAAQ,GAAK,IAAI,CAAC,QAAQ,CAAC,EAAE,UAAU,wBAAM,UAAU,GAAK,IAAI,CAAC,UAAU,CAAC,EAAC,CAAC,CAAC;QAC9F,EAAC,QAAQ,UAAA,EAAE,UAAU,YAAA,EAAC,CAAC;AAC/B,CAAC;AAQD,MAAM,CAAC,IAAM,WAAW,GAAG;IACvB,GAAG,EAAE,4CAA4C;IACjD,KAAK,EAAE,soBAAsoB;IAC7oB,KAAK,EAAE,mhCAAmhC;CAC7hC,CAAC;AACF,MAAM,CAAC,IAAM,eAAe,GAAG,EAAqB,CAAC;AACrD,eAAe,CAAC,KAAK,CAAC,GAAG,uBAAuB,CAAC,gCAAgC,CAAC,CAAC;AACnF,eAAe,CAAC,OAAO,CAAC,GAAG,uBAAuB,CAAC,04DAA04D,CAAC,CAAC;AAC/7D,eAAe,CAAC,OAAO,CAAC,GAAG,uBAAuB,CAAC,4vkBAA4vkB,EAAE,eAAe,CAAC,OAAO,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/html-entities/dist/esm/numeric-unicode-map.js b/node_modules/html-entities/dist/esm/numeric-unicode-map.js new file mode 100644 index 0000000..f28203c --- /dev/null +++ b/node_modules/html-entities/dist/esm/numeric-unicode-map.js @@ -0,0 +1,31 @@ +export var numericUnicodeMap = { + 0: 65533, + 128: 8364, + 130: 8218, + 131: 402, + 132: 8222, + 133: 8230, + 134: 8224, + 135: 8225, + 136: 710, + 137: 8240, + 138: 352, + 139: 8249, + 140: 338, + 142: 381, + 145: 8216, + 146: 8217, + 147: 8220, + 148: 8221, + 149: 8226, + 150: 8211, + 151: 8212, + 152: 732, + 153: 8482, + 154: 353, + 155: 8250, + 156: 339, + 158: 382, + 159: 376 +}; +//# sourceMappingURL=numeric-unicode-map.js.map \ No newline at end of file diff --git a/node_modules/html-entities/dist/esm/numeric-unicode-map.js.map b/node_modules/html-entities/dist/esm/numeric-unicode-map.js.map new file mode 100644 index 0000000..578e95c --- /dev/null +++ b/node_modules/html-entities/dist/esm/numeric-unicode-map.js.map @@ -0,0 +1 @@ +{"version":3,"file":"numeric-unicode-map.js","sourceRoot":"","sources":["../../src/numeric-unicode-map.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,IAAM,iBAAiB,GAA2B;IACrD,CAAC,EAAE,KAAK;IACR,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,GAAG;CACX,CAAC"} \ No newline at end of file diff --git a/node_modules/html-entities/dist/esm/package.json b/node_modules/html-entities/dist/esm/package.json new file mode 100644 index 0000000..3dbc1ca --- /dev/null +++ b/node_modules/html-entities/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/html-entities/dist/esm/surrogate-pairs.js b/node_modules/html-entities/dist/esm/surrogate-pairs.js new file mode 100644 index 0000000..8c67d9f --- /dev/null +++ b/node_modules/html-entities/dist/esm/surrogate-pairs.js @@ -0,0 +1,15 @@ +export var fromCodePoint = String.fromCodePoint || + function (astralCodePoint) { + return String.fromCharCode(Math.floor((astralCodePoint - 0x10000) / 0x400) + 0xd800, ((astralCodePoint - 0x10000) % 0x400) + 0xdc00); + }; +// @ts-expect-error - String.prototype.codePointAt might not exist in older node versions +export var getCodePoint = String.prototype.codePointAt + ? function (input, position) { + return input.codePointAt(position); + } + : function (input, position) { + return (input.charCodeAt(position) - 0xd800) * 0x400 + input.charCodeAt(position + 1) - 0xdc00 + 0x10000; + }; +export var highSurrogateFrom = 0xd800; +export var highSurrogateTo = 0xdbff; +//# sourceMappingURL=surrogate-pairs.js.map \ No newline at end of file diff --git a/node_modules/html-entities/dist/esm/surrogate-pairs.js.map b/node_modules/html-entities/dist/esm/surrogate-pairs.js.map new file mode 100644 index 0000000..bb4e623 --- /dev/null +++ b/node_modules/html-entities/dist/esm/surrogate-pairs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"surrogate-pairs.js","sourceRoot":"","sources":["../../src/surrogate-pairs.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,IAAM,aAAa,GACtB,MAAM,CAAC,aAAa;IACpB,UAAU,eAAuB;QAC7B,OAAO,MAAM,CAAC,YAAY,CACtB,IAAI,CAAC,KAAK,CAAC,CAAC,eAAe,GAAG,OAAO,CAAC,GAAG,KAAK,CAAC,GAAG,MAAM,EACxD,CAAC,CAAC,eAAe,GAAG,OAAO,CAAC,GAAG,KAAK,CAAC,GAAG,MAAM,CACjD,CAAC;IACN,CAAC,CAAC;AAEN,yFAAyF;AACzF,MAAM,CAAC,IAAM,YAAY,GAAG,MAAM,CAAC,SAAS,CAAC,WAAW;IACpD,CAAC,CAAC,UAAU,KAAa,EAAE,QAAgB;QACrC,OAAO,KAAK,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;IACvC,CAAC;IACH,CAAC,CAAC,UAAU,KAAa,EAAE,QAAgB;QACrC,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC,GAAG,KAAK,GAAG,KAAK,CAAC,UAAU,CAAC,QAAQ,GAAG,CAAC,CAAC,GAAG,MAAM,GAAG,OAAO,CAAC;IAC7G,CAAC,CAAC;AAER,MAAM,CAAC,IAAM,iBAAiB,GAAG,MAAM,CAAC;AACxC,MAAM,CAAC,IAAM,eAAe,GAAG,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/html-entities/package.json b/node_modules/html-entities/package.json new file mode 100644 index 0000000..1fd93b0 --- /dev/null +++ b/node_modules/html-entities/package.json @@ -0,0 +1,106 @@ +{ + "name": "html-entities", + "version": "2.6.0", + "description": "Fastest HTML entities encode/decode library.", + "keywords": [ + "html", + "html entities", + "html entities encode", + "html entities decode", + "entities", + "entities encode", + "entities decode" + ], + "author": { + "name": "Marat Dulin", + "email": "mdevils@yandex.ru" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/mdevils" + }, + { + "type": "patreon", + "url": "https://patreon.com/mdevils" + } + ], + "devDependencies": { + "@commitlint/cli": "^17.6.6", + "@commitlint/config-conventional": "^17.6.6", + "@types/benchmark": "^2.1.0", + "@types/he": "^1.1.1", + "@types/jest": "^29.5.14", + "@types/node": "^22.13.14", + "benchmark": "^2.1.4", + "entities": "^6.0.0", + "eslint": "^9.23.0", + "eslint-config-prettier": "^10.1.1", + "eslint-plugin-import": "^2.31.0", + "flowgen": "^1.13.0", + "he": "^1.2.0", + "husky": "^4.3.6", + "prettier": "^3.5.3", + "standard-version": "^9.5.0", + "ts-jest": "^29.3.0", + "tshy": "^3.0.2", + "tsx": "^4.19.3", + "typescript": "^5.8.2", + "typescript-eslint": "^8.28.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/mdevils/html-entities.git" + }, + "sideEffects": false, + "main": "./dist/commonjs/index.js", + "typings": "./dist/commonjs/index.d.ts", + "types": "./dist/commonjs/index.d.ts", + "scripts": { + "test": "jest", + "test:watch": "jest --watch", + "test:dist": "npm run test:dist:commonjs && npm run test:dist:esm", + "test:dist:commonjs": "TEST_DIST=commonjs npm run test", + "test:dist:esm": "TEST_DIST=esm node --experimental-vm-modules node_modules/.bin/jest", + "benchmark": "tsx benchmark/benchmark", + "lint": "eslint src/**.ts", + "flow-type-gen": "flowgen --add-flow-header dist/esm/index.d.ts -o dist/commonjs/index.js.flow", + "remove-unused-declarations": "find dist -type f \\( -name '*.d.ts' ! -name index.d.ts \\) | xargs rm", + "build": "rm -Rf dist && tsc --noEmit && tshy && tsc --declaration --emitDeclarationOnly -p tsconfig.json && tsc --emitDeclarationOnly -p tsconfig.esm.json && npm run remove-unused-declarations && npm run flow-type-gen", + "prepublishOnly": "npm run build && npm run test && npm run test:dist", + "release": "standard-version" + }, + "files": [ + "dist", + "src", + "LICENSE" + ], + "husky": { + "hooks": { + "pre-commit": "npm run lint && npm run test" + } + }, + "license": "MIT", + "type": "module", + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + }, + "selfLink": false + }, + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + } + }, + "module": "./dist/esm/index.js" +} diff --git a/node_modules/html-entities/src/index.ts b/node_modules/html-entities/src/index.ts new file mode 100644 index 0000000..197413e --- /dev/null +++ b/node_modules/html-entities/src/index.ts @@ -0,0 +1,164 @@ +import {bodyRegExps, namedReferences} from './named-references.js'; +import {numericUnicodeMap} from './numeric-unicode-map.js'; +import {fromCodePoint, getCodePoint} from './surrogate-pairs.js'; + +const allNamedReferences = { + ...namedReferences, + all: namedReferences.html5 +}; + +export type Level = 'xml' | 'html4' | 'html5' | 'all'; + +interface CommonOptions { + level?: Level; +} + +export type EncodeMode = 'specialChars' | 'nonAscii' | 'nonAsciiPrintable' | 'nonAsciiPrintableOnly' | 'extensive'; + +export interface EncodeOptions extends CommonOptions { + mode?: EncodeMode; + numeric?: 'decimal' | 'hexadecimal'; +} + +export type DecodeScope = 'strict' | 'body' | 'attribute'; + +export interface DecodeOptions extends CommonOptions { + scope?: DecodeScope; +} + +const encodeRegExps: Record = { + specialChars: /[<>'"&]/g, + nonAscii: /[<>'"&\u0080-\uD7FF\uE000-\uFFFF\uDC00-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g, + nonAsciiPrintable: /[<>'"&\x01-\x08\x11-\x15\x17-\x1F\x7f-\uD7FF\uE000-\uFFFF\uDC00-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g, + nonAsciiPrintableOnly: /[\x01-\x08\x11-\x15\x17-\x1F\x7f-\uD7FF\uE000-\uFFFF\uDC00-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g, + extensive: /[\x01-\x0c\x0e-\x1f\x21-\x2c\x2e-\x2f\x3a-\x40\x5b-\x60\x7b-\x7d\x7f-\uD7FF\uE000-\uFFFF\uDC00-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g +}; + +const defaultEncodeOptions: EncodeOptions = { + mode: 'specialChars', + level: 'all', + numeric: 'decimal' +}; + +/** Encodes all the necessary (specified by `level`) characters in the text */ +export function encode( + text: string | undefined | null, + {mode = 'specialChars', numeric = 'decimal', level = 'all'}: EncodeOptions = defaultEncodeOptions +) { + if (!text) { + return ''; + } + + const encodeRegExp = encodeRegExps[mode]; + const references = allNamedReferences[level].characters; + const isHex = numeric === 'hexadecimal'; + + return String.prototype.replace.call(text, encodeRegExp, (input) => { + let result = references[input]; + if (!result) { + const code = input.length > 1 ? getCodePoint(input, 0)! : input.charCodeAt(0); + result = (isHex ? '&#x' + code.toString(16) : '&#' + code) + ';'; + } + return result; + }); +} + +const defaultDecodeOptions: DecodeOptions = { + scope: 'body', + level: 'all' +}; + +const strict = /&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);/g; +const attribute = /&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+)[;=]?/g; + +const baseDecodeRegExps: Record, Record> = { + xml: { + strict, + attribute, + body: bodyRegExps.xml + }, + html4: { + strict, + attribute, + body: bodyRegExps.html4 + }, + html5: { + strict, + attribute, + body: bodyRegExps.html5 + } +}; + +const decodeRegExps: Record> = { + ...baseDecodeRegExps, + all: baseDecodeRegExps.html5 +}; + +const fromCharCode = String.fromCharCode; +const outOfBoundsChar = fromCharCode(65533); + +const defaultDecodeEntityOptions: CommonOptions = { + level: 'all' +}; + +function getDecodedEntity( + entity: string, + references: Record, + isAttribute: boolean, + isStrict: boolean +): string { + let decodeResult = entity; + const decodeEntityLastChar = entity[entity.length - 1]; + if (isAttribute && decodeEntityLastChar === '=') { + decodeResult = entity; + } else if (isStrict && decodeEntityLastChar !== ';') { + decodeResult = entity; + } else { + const decodeResultByReference = references[entity]; + if (decodeResultByReference) { + decodeResult = decodeResultByReference; + } else if (entity[0] === '&' && entity[1] === '#') { + const decodeSecondChar = entity[2]; + const decodeCode = + decodeSecondChar == 'x' || decodeSecondChar == 'X' + ? parseInt(entity.substr(3), 16) + : parseInt(entity.substr(2)); + + decodeResult = + decodeCode >= 0x10ffff + ? outOfBoundsChar + : decodeCode > 65535 + ? fromCodePoint(decodeCode) + : fromCharCode(numericUnicodeMap[decodeCode] || decodeCode); + } + } + return decodeResult; +} + +/** Decodes a single entity */ +export function decodeEntity( + entity: string | undefined | null, + {level = 'all'}: CommonOptions = defaultDecodeEntityOptions +): string { + if (!entity) { + return ''; + } + return getDecodedEntity(entity, allNamedReferences[level].entities, false, false); +} + +/** Decodes all entities in the text */ +export function decode( + text: string | undefined | null, + {level = 'all', scope = level === 'xml' ? 'strict' : 'body'}: DecodeOptions = defaultDecodeOptions +) { + if (!text) { + return ''; + } + + const decodeRegExp = decodeRegExps[level][scope]; + const references = allNamedReferences[level].entities; + const isAttribute = scope === 'attribute'; + const isStrict = scope === 'strict'; + + return text.replace(decodeRegExp, (entity) => getDecodedEntity(entity, references, isAttribute, isStrict)); +} diff --git a/node_modules/html-entities/src/named-references.ts b/node_modules/html-entities/src/named-references.ts new file mode 100644 index 0000000..82a69aa --- /dev/null +++ b/node_modules/html-entities/src/named-references.ts @@ -0,0 +1,48 @@ +// This file is autogenerated by tools/process-named-references.ts +const pairDivider = "~"; +const blockDivider = "~~"; + +type GeneratedReferences = { + entities: Record; + characters: Record; +}; + +function generateNamedReferences(input: string, prev?: GeneratedReferences): GeneratedReferences { + const entities: Record = {}; + const characters: Record = {}; + const blocks = input.split(blockDivider); + let isOptionalBlock = false; + for (let i = 0; blocks.length > i; i++) { + const entries = blocks[i].split(pairDivider); + for (let j = 0; j < entries.length; j+=2) { + const entity = entries[j]; + const character = entries[j+1]; + const fullEntity = '&' + entity + ';'; + entities[fullEntity] = character; + if (isOptionalBlock) { + entities['&' + entity] = character; + } + characters[character] = fullEntity; + } + isOptionalBlock = true; + } + return prev ? + {entities: {...entities, ...prev.entities}, characters: {...characters, ...prev.characters}} : + {entities, characters}; +} + +export type NamedReferences = { + [K in 'xml' | 'html4' | 'html5']: { + entities: Record; + characters: Record; + } +}; +export const bodyRegExps = { + xml: /&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g, + html4: /∉|&(?:nbsp|iexcl|cent|pound|curren|yen|brvbar|sect|uml|copy|ordf|laquo|not|shy|reg|macr|deg|plusmn|sup2|sup3|acute|micro|para|middot|cedil|sup1|ordm|raquo|frac14|frac12|frac34|iquest|Agrave|Aacute|Acirc|Atilde|Auml|Aring|AElig|Ccedil|Egrave|Eacute|Ecirc|Euml|Igrave|Iacute|Icirc|Iuml|ETH|Ntilde|Ograve|Oacute|Ocirc|Otilde|Ouml|times|Oslash|Ugrave|Uacute|Ucirc|Uuml|Yacute|THORN|szlig|agrave|aacute|acirc|atilde|auml|aring|aelig|ccedil|egrave|eacute|ecirc|euml|igrave|iacute|icirc|iuml|eth|ntilde|ograve|oacute|ocirc|otilde|ouml|divide|oslash|ugrave|uacute|ucirc|uuml|yacute|thorn|yuml|quot|amp|lt|gt|#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g, + html5: /·|℗|⋇|⪧|⩺|⋗|⦕|⩼|⪆|⥸|⋗|⋛|⪌|≷|≳|⪦|⩹|⋖|⋋|⋉|⥶|⩻|⦖|◃|⊴|◂|∉|⋹̸|⋵̸|∉|⋷|⋶|∌|∌|⋾|⋽|∥|⊠|⨱|⨰|&(?:AElig|AMP|Aacute|Acirc|Agrave|Aring|Atilde|Auml|COPY|Ccedil|ETH|Eacute|Ecirc|Egrave|Euml|GT|Iacute|Icirc|Igrave|Iuml|LT|Ntilde|Oacute|Ocirc|Ograve|Oslash|Otilde|Ouml|QUOT|REG|THORN|Uacute|Ucirc|Ugrave|Uuml|Yacute|aacute|acirc|acute|aelig|agrave|amp|aring|atilde|auml|brvbar|ccedil|cedil|cent|copy|curren|deg|divide|eacute|ecirc|egrave|eth|euml|frac12|frac14|frac34|gt|iacute|icirc|iexcl|igrave|iquest|iuml|laquo|lt|macr|micro|middot|nbsp|not|ntilde|oacute|ocirc|ograve|ordf|ordm|oslash|otilde|ouml|para|plusmn|pound|quot|raquo|reg|sect|shy|sup1|sup2|sup3|szlig|thorn|times|uacute|ucirc|ugrave|uml|uuml|yacute|yen|yuml|#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g +}; +export const namedReferences = {} as NamedReferences; +namedReferences['xml'] = generateNamedReferences("lt~<~gt~>~quot~\"~apos~'~amp~&"); +namedReferences['html4'] = generateNamedReferences("apos~'~OElig~Œ~oelig~œ~Scaron~Š~scaron~š~Yuml~Ÿ~circ~ˆ~tilde~˜~ensp~ ~emsp~ ~thinsp~ ~zwnj~‌~zwj~‍~lrm~‎~rlm~‏~ndash~–~mdash~—~lsquo~‘~rsquo~’~sbquo~‚~ldquo~“~rdquo~”~bdquo~„~dagger~†~Dagger~‡~permil~‰~lsaquo~‹~rsaquo~›~euro~€~fnof~ƒ~Alpha~Α~Beta~Β~Gamma~Γ~Delta~Δ~Epsilon~Ε~Zeta~Ζ~Eta~Η~Theta~Θ~Iota~Ι~Kappa~Κ~Lambda~Λ~Mu~Μ~Nu~Ν~Xi~Ξ~Omicron~Ο~Pi~Π~Rho~Ρ~Sigma~Σ~Tau~Τ~Upsilon~Υ~Phi~Φ~Chi~Χ~Psi~Ψ~Omega~Ω~alpha~α~beta~β~gamma~γ~delta~δ~epsilon~ε~zeta~ζ~eta~η~theta~θ~iota~ι~kappa~κ~lambda~λ~mu~μ~nu~ν~xi~ξ~omicron~ο~pi~π~rho~ρ~sigmaf~ς~sigma~σ~tau~τ~upsilon~υ~phi~φ~chi~χ~psi~ψ~omega~ω~thetasym~ϑ~upsih~ϒ~piv~ϖ~bull~•~hellip~…~prime~′~Prime~″~oline~‾~frasl~⁄~weierp~℘~image~ℑ~real~ℜ~trade~™~alefsym~ℵ~larr~←~uarr~↑~rarr~→~darr~↓~harr~↔~crarr~↵~lArr~⇐~uArr~⇑~rArr~⇒~dArr~⇓~hArr~⇔~forall~∀~part~∂~exist~∃~empty~∅~nabla~∇~isin~∈~notin~∉~ni~∋~prod~∏~sum~∑~minus~−~lowast~∗~radic~√~prop~∝~infin~∞~ang~∠~and~∧~or~∨~cap~∩~cup~∪~int~∫~there4~∴~sim~∼~cong~≅~asymp~≈~ne~≠~equiv~≡~le~≤~ge~≥~sub~⊂~sup~⊃~nsub~⊄~sube~⊆~supe~⊇~oplus~⊕~otimes~⊗~perp~⊥~sdot~⋅~lceil~⌈~rceil~⌉~lfloor~⌊~rfloor~⌋~lang~〈~rang~〉~loz~◊~spades~♠~clubs~♣~hearts~♥~diams~♦~~nbsp~ ~iexcl~¡~cent~¢~pound~£~curren~¤~yen~¥~brvbar~¦~sect~§~uml~¨~copy~©~ordf~ª~laquo~«~not~¬~shy~­~reg~®~macr~¯~deg~°~plusmn~±~sup2~²~sup3~³~acute~´~micro~µ~para~¶~middot~·~cedil~¸~sup1~¹~ordm~º~raquo~»~frac14~¼~frac12~½~frac34~¾~iquest~¿~Agrave~À~Aacute~Á~Acirc~Â~Atilde~Ã~Auml~Ä~Aring~Å~AElig~Æ~Ccedil~Ç~Egrave~È~Eacute~É~Ecirc~Ê~Euml~Ë~Igrave~Ì~Iacute~Í~Icirc~Î~Iuml~Ï~ETH~Ð~Ntilde~Ñ~Ograve~Ò~Oacute~Ó~Ocirc~Ô~Otilde~Õ~Ouml~Ö~times~×~Oslash~Ø~Ugrave~Ù~Uacute~Ú~Ucirc~Û~Uuml~Ü~Yacute~Ý~THORN~Þ~szlig~ß~agrave~à~aacute~á~acirc~â~atilde~ã~auml~ä~aring~å~aelig~æ~ccedil~ç~egrave~è~eacute~é~ecirc~ê~euml~ë~igrave~ì~iacute~í~icirc~î~iuml~ï~eth~ð~ntilde~ñ~ograve~ò~oacute~ó~ocirc~ô~otilde~õ~ouml~ö~divide~÷~oslash~ø~ugrave~ù~uacute~ú~ucirc~û~uuml~ü~yacute~ý~thorn~þ~yuml~ÿ~quot~\"~amp~&~lt~<~gt~>"); +namedReferences['html5'] = generateNamedReferences("Abreve~Ă~Acy~А~Afr~𝔄~Amacr~Ā~And~⩓~Aogon~Ą~Aopf~𝔸~ApplyFunction~⁡~Ascr~𝒜~Assign~≔~Backslash~∖~Barv~⫧~Barwed~⌆~Bcy~Б~Because~∵~Bernoullis~ℬ~Bfr~𝔅~Bopf~𝔹~Breve~˘~Bscr~ℬ~Bumpeq~≎~CHcy~Ч~Cacute~Ć~Cap~⋒~CapitalDifferentialD~ⅅ~Cayleys~ℭ~Ccaron~Č~Ccirc~Ĉ~Cconint~∰~Cdot~Ċ~Cedilla~¸~CenterDot~·~Cfr~ℭ~CircleDot~⊙~CircleMinus~⊖~CirclePlus~⊕~CircleTimes~⊗~ClockwiseContourIntegral~∲~CloseCurlyDoubleQuote~”~CloseCurlyQuote~’~Colon~∷~Colone~⩴~Congruent~≡~Conint~∯~ContourIntegral~∮~Copf~ℂ~Coproduct~∐~CounterClockwiseContourIntegral~∳~Cross~⨯~Cscr~𝒞~Cup~⋓~CupCap~≍~DD~ⅅ~DDotrahd~⤑~DJcy~Ђ~DScy~Ѕ~DZcy~Џ~Darr~↡~Dashv~⫤~Dcaron~Ď~Dcy~Д~Del~∇~Dfr~𝔇~DiacriticalAcute~´~DiacriticalDot~˙~DiacriticalDoubleAcute~˝~DiacriticalGrave~`~DiacriticalTilde~˜~Diamond~⋄~DifferentialD~ⅆ~Dopf~𝔻~Dot~¨~DotDot~⃜~DotEqual~≐~DoubleContourIntegral~∯~DoubleDot~¨~DoubleDownArrow~⇓~DoubleLeftArrow~⇐~DoubleLeftRightArrow~⇔~DoubleLeftTee~⫤~DoubleLongLeftArrow~⟸~DoubleLongLeftRightArrow~⟺~DoubleLongRightArrow~⟹~DoubleRightArrow~⇒~DoubleRightTee~⊨~DoubleUpArrow~⇑~DoubleUpDownArrow~⇕~DoubleVerticalBar~∥~DownArrow~↓~DownArrowBar~⤓~DownArrowUpArrow~⇵~DownBreve~̑~DownLeftRightVector~⥐~DownLeftTeeVector~⥞~DownLeftVector~↽~DownLeftVectorBar~⥖~DownRightTeeVector~⥟~DownRightVector~⇁~DownRightVectorBar~⥗~DownTee~⊤~DownTeeArrow~↧~Downarrow~⇓~Dscr~𝒟~Dstrok~Đ~ENG~Ŋ~Ecaron~Ě~Ecy~Э~Edot~Ė~Efr~𝔈~Element~∈~Emacr~Ē~EmptySmallSquare~◻~EmptyVerySmallSquare~▫~Eogon~Ę~Eopf~𝔼~Equal~⩵~EqualTilde~≂~Equilibrium~⇌~Escr~ℰ~Esim~⩳~Exists~∃~ExponentialE~ⅇ~Fcy~Ф~Ffr~𝔉~FilledSmallSquare~◼~FilledVerySmallSquare~▪~Fopf~𝔽~ForAll~∀~Fouriertrf~ℱ~Fscr~ℱ~GJcy~Ѓ~Gammad~Ϝ~Gbreve~Ğ~Gcedil~Ģ~Gcirc~Ĝ~Gcy~Г~Gdot~Ġ~Gfr~𝔊~Gg~⋙~Gopf~𝔾~GreaterEqual~≥~GreaterEqualLess~⋛~GreaterFullEqual~≧~GreaterGreater~⪢~GreaterLess~≷~GreaterSlantEqual~⩾~GreaterTilde~≳~Gscr~𝒢~Gt~≫~HARDcy~Ъ~Hacek~ˇ~Hat~^~Hcirc~Ĥ~Hfr~ℌ~HilbertSpace~ℋ~Hopf~ℍ~HorizontalLine~─~Hscr~ℋ~Hstrok~Ħ~HumpDownHump~≎~HumpEqual~≏~IEcy~Е~IJlig~IJ~IOcy~Ё~Icy~И~Idot~İ~Ifr~ℑ~Im~ℑ~Imacr~Ī~ImaginaryI~ⅈ~Implies~⇒~Int~∬~Integral~∫~Intersection~⋂~InvisibleComma~⁣~InvisibleTimes~⁢~Iogon~Į~Iopf~𝕀~Iscr~ℐ~Itilde~Ĩ~Iukcy~І~Jcirc~Ĵ~Jcy~Й~Jfr~𝔍~Jopf~𝕁~Jscr~𝒥~Jsercy~Ј~Jukcy~Є~KHcy~Х~KJcy~Ќ~Kcedil~Ķ~Kcy~К~Kfr~𝔎~Kopf~𝕂~Kscr~𝒦~LJcy~Љ~Lacute~Ĺ~Lang~⟪~Laplacetrf~ℒ~Larr~↞~Lcaron~Ľ~Lcedil~Ļ~Lcy~Л~LeftAngleBracket~⟨~LeftArrow~←~LeftArrowBar~⇤~LeftArrowRightArrow~⇆~LeftCeiling~⌈~LeftDoubleBracket~⟦~LeftDownTeeVector~⥡~LeftDownVector~⇃~LeftDownVectorBar~⥙~LeftFloor~⌊~LeftRightArrow~↔~LeftRightVector~⥎~LeftTee~⊣~LeftTeeArrow~↤~LeftTeeVector~⥚~LeftTriangle~⊲~LeftTriangleBar~⧏~LeftTriangleEqual~⊴~LeftUpDownVector~⥑~LeftUpTeeVector~⥠~LeftUpVector~↿~LeftUpVectorBar~⥘~LeftVector~↼~LeftVectorBar~⥒~Leftarrow~⇐~Leftrightarrow~⇔~LessEqualGreater~⋚~LessFullEqual~≦~LessGreater~≶~LessLess~⪡~LessSlantEqual~⩽~LessTilde~≲~Lfr~𝔏~Ll~⋘~Lleftarrow~⇚~Lmidot~Ŀ~LongLeftArrow~⟵~LongLeftRightArrow~⟷~LongRightArrow~⟶~Longleftarrow~⟸~Longleftrightarrow~⟺~Longrightarrow~⟹~Lopf~𝕃~LowerLeftArrow~↙~LowerRightArrow~↘~Lscr~ℒ~Lsh~↰~Lstrok~Ł~Lt~≪~Map~⤅~Mcy~М~MediumSpace~ ~Mellintrf~ℳ~Mfr~𝔐~MinusPlus~∓~Mopf~𝕄~Mscr~ℳ~NJcy~Њ~Nacute~Ń~Ncaron~Ň~Ncedil~Ņ~Ncy~Н~NegativeMediumSpace~​~NegativeThickSpace~​~NegativeThinSpace~​~NegativeVeryThinSpace~​~NestedGreaterGreater~≫~NestedLessLess~≪~NewLine~\n~Nfr~𝔑~NoBreak~⁠~NonBreakingSpace~ ~Nopf~ℕ~Not~⫬~NotCongruent~≢~NotCupCap~≭~NotDoubleVerticalBar~∦~NotElement~∉~NotEqual~≠~NotEqualTilde~≂̸~NotExists~∄~NotGreater~≯~NotGreaterEqual~≱~NotGreaterFullEqual~≧̸~NotGreaterGreater~≫̸~NotGreaterLess~≹~NotGreaterSlantEqual~⩾̸~NotGreaterTilde~≵~NotHumpDownHump~≎̸~NotHumpEqual~≏̸~NotLeftTriangle~⋪~NotLeftTriangleBar~⧏̸~NotLeftTriangleEqual~⋬~NotLess~≮~NotLessEqual~≰~NotLessGreater~≸~NotLessLess~≪̸~NotLessSlantEqual~⩽̸~NotLessTilde~≴~NotNestedGreaterGreater~⪢̸~NotNestedLessLess~⪡̸~NotPrecedes~⊀~NotPrecedesEqual~⪯̸~NotPrecedesSlantEqual~⋠~NotReverseElement~∌~NotRightTriangle~⋫~NotRightTriangleBar~⧐̸~NotRightTriangleEqual~⋭~NotSquareSubset~⊏̸~NotSquareSubsetEqual~⋢~NotSquareSuperset~⊐̸~NotSquareSupersetEqual~⋣~NotSubset~⊂⃒~NotSubsetEqual~⊈~NotSucceeds~⊁~NotSucceedsEqual~⪰̸~NotSucceedsSlantEqual~⋡~NotSucceedsTilde~≿̸~NotSuperset~⊃⃒~NotSupersetEqual~⊉~NotTilde~≁~NotTildeEqual~≄~NotTildeFullEqual~≇~NotTildeTilde~≉~NotVerticalBar~∤~Nscr~𝒩~Ocy~О~Odblac~Ő~Ofr~𝔒~Omacr~Ō~Oopf~𝕆~OpenCurlyDoubleQuote~“~OpenCurlyQuote~‘~Or~⩔~Oscr~𝒪~Otimes~⨷~OverBar~‾~OverBrace~⏞~OverBracket~⎴~OverParenthesis~⏜~PartialD~∂~Pcy~П~Pfr~𝔓~PlusMinus~±~Poincareplane~ℌ~Popf~ℙ~Pr~⪻~Precedes~≺~PrecedesEqual~⪯~PrecedesSlantEqual~≼~PrecedesTilde~≾~Product~∏~Proportion~∷~Proportional~∝~Pscr~𝒫~Qfr~𝔔~Qopf~ℚ~Qscr~𝒬~RBarr~⤐~Racute~Ŕ~Rang~⟫~Rarr~↠~Rarrtl~⤖~Rcaron~Ř~Rcedil~Ŗ~Rcy~Р~Re~ℜ~ReverseElement~∋~ReverseEquilibrium~⇋~ReverseUpEquilibrium~⥯~Rfr~ℜ~RightAngleBracket~⟩~RightArrow~→~RightArrowBar~⇥~RightArrowLeftArrow~⇄~RightCeiling~⌉~RightDoubleBracket~⟧~RightDownTeeVector~⥝~RightDownVector~⇂~RightDownVectorBar~⥕~RightFloor~⌋~RightTee~⊢~RightTeeArrow~↦~RightTeeVector~⥛~RightTriangle~⊳~RightTriangleBar~⧐~RightTriangleEqual~⊵~RightUpDownVector~⥏~RightUpTeeVector~⥜~RightUpVector~↾~RightUpVectorBar~⥔~RightVector~⇀~RightVectorBar~⥓~Rightarrow~⇒~Ropf~ℝ~RoundImplies~⥰~Rrightarrow~⇛~Rscr~ℛ~Rsh~↱~RuleDelayed~⧴~SHCHcy~Щ~SHcy~Ш~SOFTcy~Ь~Sacute~Ś~Sc~⪼~Scedil~Ş~Scirc~Ŝ~Scy~С~Sfr~𝔖~ShortDownArrow~↓~ShortLeftArrow~←~ShortRightArrow~→~ShortUpArrow~↑~SmallCircle~∘~Sopf~𝕊~Sqrt~√~Square~□~SquareIntersection~⊓~SquareSubset~⊏~SquareSubsetEqual~⊑~SquareSuperset~⊐~SquareSupersetEqual~⊒~SquareUnion~⊔~Sscr~𝒮~Star~⋆~Sub~⋐~Subset~⋐~SubsetEqual~⊆~Succeeds~≻~SucceedsEqual~⪰~SucceedsSlantEqual~≽~SucceedsTilde~≿~SuchThat~∋~Sum~∑~Sup~⋑~Superset~⊃~SupersetEqual~⊇~Supset~⋑~TRADE~™~TSHcy~Ћ~TScy~Ц~Tab~\t~Tcaron~Ť~Tcedil~Ţ~Tcy~Т~Tfr~𝔗~Therefore~∴~ThickSpace~  ~ThinSpace~ ~Tilde~∼~TildeEqual~≃~TildeFullEqual~≅~TildeTilde~≈~Topf~𝕋~TripleDot~⃛~Tscr~𝒯~Tstrok~Ŧ~Uarr~↟~Uarrocir~⥉~Ubrcy~Ў~Ubreve~Ŭ~Ucy~У~Udblac~Ű~Ufr~𝔘~Umacr~Ū~UnderBar~_~UnderBrace~⏟~UnderBracket~⎵~UnderParenthesis~⏝~Union~⋃~UnionPlus~⊎~Uogon~Ų~Uopf~𝕌~UpArrow~↑~UpArrowBar~⤒~UpArrowDownArrow~⇅~UpDownArrow~↕~UpEquilibrium~⥮~UpTee~⊥~UpTeeArrow~↥~Uparrow~⇑~Updownarrow~⇕~UpperLeftArrow~↖~UpperRightArrow~↗~Upsi~ϒ~Uring~Ů~Uscr~𝒰~Utilde~Ũ~VDash~⊫~Vbar~⫫~Vcy~В~Vdash~⊩~Vdashl~⫦~Vee~⋁~Verbar~‖~Vert~‖~VerticalBar~∣~VerticalLine~|~VerticalSeparator~❘~VerticalTilde~≀~VeryThinSpace~ ~Vfr~𝔙~Vopf~𝕍~Vscr~𝒱~Vvdash~⊪~Wcirc~Ŵ~Wedge~⋀~Wfr~𝔚~Wopf~𝕎~Wscr~𝒲~Xfr~𝔛~Xopf~𝕏~Xscr~𝒳~YAcy~Я~YIcy~Ї~YUcy~Ю~Ycirc~Ŷ~Ycy~Ы~Yfr~𝔜~Yopf~𝕐~Yscr~𝒴~ZHcy~Ж~Zacute~Ź~Zcaron~Ž~Zcy~З~Zdot~Ż~ZeroWidthSpace~​~Zfr~ℨ~Zopf~ℤ~Zscr~𝒵~abreve~ă~ac~∾~acE~∾̳~acd~∿~acy~а~af~⁡~afr~𝔞~aleph~ℵ~amacr~ā~amalg~⨿~andand~⩕~andd~⩜~andslope~⩘~andv~⩚~ange~⦤~angle~∠~angmsd~∡~angmsdaa~⦨~angmsdab~⦩~angmsdac~⦪~angmsdad~⦫~angmsdae~⦬~angmsdaf~⦭~angmsdag~⦮~angmsdah~⦯~angrt~∟~angrtvb~⊾~angrtvbd~⦝~angsph~∢~angst~Å~angzarr~⍼~aogon~ą~aopf~𝕒~ap~≈~apE~⩰~apacir~⩯~ape~≊~apid~≋~approx~≈~approxeq~≊~ascr~𝒶~ast~*~asympeq~≍~awconint~∳~awint~⨑~bNot~⫭~backcong~≌~backepsilon~϶~backprime~‵~backsim~∽~backsimeq~⋍~barvee~⊽~barwed~⌅~barwedge~⌅~bbrk~⎵~bbrktbrk~⎶~bcong~≌~bcy~б~becaus~∵~because~∵~bemptyv~⦰~bepsi~϶~bernou~ℬ~beth~ℶ~between~≬~bfr~𝔟~bigcap~⋂~bigcirc~◯~bigcup~⋃~bigodot~⨀~bigoplus~⨁~bigotimes~⨂~bigsqcup~⨆~bigstar~★~bigtriangledown~▽~bigtriangleup~△~biguplus~⨄~bigvee~⋁~bigwedge~⋀~bkarow~⤍~blacklozenge~⧫~blacksquare~▪~blacktriangle~▴~blacktriangledown~▾~blacktriangleleft~◂~blacktriangleright~▸~blank~␣~blk12~▒~blk14~░~blk34~▓~block~█~bne~=⃥~bnequiv~≡⃥~bnot~⌐~bopf~𝕓~bot~⊥~bottom~⊥~bowtie~⋈~boxDL~╗~boxDR~╔~boxDl~╖~boxDr~╓~boxH~═~boxHD~╦~boxHU~╩~boxHd~╤~boxHu~╧~boxUL~╝~boxUR~╚~boxUl~╜~boxUr~╙~boxV~║~boxVH~╬~boxVL~╣~boxVR~╠~boxVh~╫~boxVl~╢~boxVr~╟~boxbox~⧉~boxdL~╕~boxdR~╒~boxdl~┐~boxdr~┌~boxh~─~boxhD~╥~boxhU~╨~boxhd~┬~boxhu~┴~boxminus~⊟~boxplus~⊞~boxtimes~⊠~boxuL~╛~boxuR~╘~boxul~┘~boxur~└~boxv~│~boxvH~╪~boxvL~╡~boxvR~╞~boxvh~┼~boxvl~┤~boxvr~├~bprime~‵~breve~˘~bscr~𝒷~bsemi~⁏~bsim~∽~bsime~⋍~bsol~\\~bsolb~⧅~bsolhsub~⟈~bullet~•~bump~≎~bumpE~⪮~bumpe~≏~bumpeq~≏~cacute~ć~capand~⩄~capbrcup~⩉~capcap~⩋~capcup~⩇~capdot~⩀~caps~∩︀~caret~⁁~caron~ˇ~ccaps~⩍~ccaron~č~ccirc~ĉ~ccups~⩌~ccupssm~⩐~cdot~ċ~cemptyv~⦲~centerdot~·~cfr~𝔠~chcy~ч~check~✓~checkmark~✓~cir~○~cirE~⧃~circeq~≗~circlearrowleft~↺~circlearrowright~↻~circledR~®~circledS~Ⓢ~circledast~⊛~circledcirc~⊚~circleddash~⊝~cire~≗~cirfnint~⨐~cirmid~⫯~cirscir~⧂~clubsuit~♣~colon~:~colone~≔~coloneq~≔~comma~,~commat~@~comp~∁~compfn~∘~complement~∁~complexes~ℂ~congdot~⩭~conint~∮~copf~𝕔~coprod~∐~copysr~℗~cross~✗~cscr~𝒸~csub~⫏~csube~⫑~csup~⫐~csupe~⫒~ctdot~⋯~cudarrl~⤸~cudarrr~⤵~cuepr~⋞~cuesc~⋟~cularr~↶~cularrp~⤽~cupbrcap~⩈~cupcap~⩆~cupcup~⩊~cupdot~⊍~cupor~⩅~cups~∪︀~curarr~↷~curarrm~⤼~curlyeqprec~⋞~curlyeqsucc~⋟~curlyvee~⋎~curlywedge~⋏~curvearrowleft~↶~curvearrowright~↷~cuvee~⋎~cuwed~⋏~cwconint~∲~cwint~∱~cylcty~⌭~dHar~⥥~daleth~ℸ~dash~‐~dashv~⊣~dbkarow~⤏~dblac~˝~dcaron~ď~dcy~д~dd~ⅆ~ddagger~‡~ddarr~⇊~ddotseq~⩷~demptyv~⦱~dfisht~⥿~dfr~𝔡~dharl~⇃~dharr~⇂~diam~⋄~diamond~⋄~diamondsuit~♦~die~¨~digamma~ϝ~disin~⋲~div~÷~divideontimes~⋇~divonx~⋇~djcy~ђ~dlcorn~⌞~dlcrop~⌍~dollar~$~dopf~𝕕~dot~˙~doteq~≐~doteqdot~≑~dotminus~∸~dotplus~∔~dotsquare~⊡~doublebarwedge~⌆~downarrow~↓~downdownarrows~⇊~downharpoonleft~⇃~downharpoonright~⇂~drbkarow~⤐~drcorn~⌟~drcrop~⌌~dscr~𝒹~dscy~ѕ~dsol~⧶~dstrok~đ~dtdot~⋱~dtri~▿~dtrif~▾~duarr~⇵~duhar~⥯~dwangle~⦦~dzcy~џ~dzigrarr~⟿~eDDot~⩷~eDot~≑~easter~⩮~ecaron~ě~ecir~≖~ecolon~≕~ecy~э~edot~ė~ee~ⅇ~efDot~≒~efr~𝔢~eg~⪚~egs~⪖~egsdot~⪘~el~⪙~elinters~⏧~ell~ℓ~els~⪕~elsdot~⪗~emacr~ē~emptyset~∅~emptyv~∅~emsp13~ ~emsp14~ ~eng~ŋ~eogon~ę~eopf~𝕖~epar~⋕~eparsl~⧣~eplus~⩱~epsi~ε~epsiv~ϵ~eqcirc~≖~eqcolon~≕~eqsim~≂~eqslantgtr~⪖~eqslantless~⪕~equals~=~equest~≟~equivDD~⩸~eqvparsl~⧥~erDot~≓~erarr~⥱~escr~ℯ~esdot~≐~esim~≂~excl~!~expectation~ℰ~exponentiale~ⅇ~fallingdotseq~≒~fcy~ф~female~♀~ffilig~ffi~fflig~ff~ffllig~ffl~ffr~𝔣~filig~fi~fjlig~fj~flat~♭~fllig~fl~fltns~▱~fopf~𝕗~fork~⋔~forkv~⫙~fpartint~⨍~frac13~⅓~frac15~⅕~frac16~⅙~frac18~⅛~frac23~⅔~frac25~⅖~frac35~⅗~frac38~⅜~frac45~⅘~frac56~⅚~frac58~⅝~frac78~⅞~frown~⌢~fscr~𝒻~gE~≧~gEl~⪌~gacute~ǵ~gammad~ϝ~gap~⪆~gbreve~ğ~gcirc~ĝ~gcy~г~gdot~ġ~gel~⋛~geq~≥~geqq~≧~geqslant~⩾~ges~⩾~gescc~⪩~gesdot~⪀~gesdoto~⪂~gesdotol~⪄~gesl~⋛︀~gesles~⪔~gfr~𝔤~gg~≫~ggg~⋙~gimel~ℷ~gjcy~ѓ~gl~≷~glE~⪒~gla~⪥~glj~⪤~gnE~≩~gnap~⪊~gnapprox~⪊~gne~⪈~gneq~⪈~gneqq~≩~gnsim~⋧~gopf~𝕘~grave~`~gscr~ℊ~gsim~≳~gsime~⪎~gsiml~⪐~gtcc~⪧~gtcir~⩺~gtdot~⋗~gtlPar~⦕~gtquest~⩼~gtrapprox~⪆~gtrarr~⥸~gtrdot~⋗~gtreqless~⋛~gtreqqless~⪌~gtrless~≷~gtrsim~≳~gvertneqq~≩︀~gvnE~≩︀~hairsp~ ~half~½~hamilt~ℋ~hardcy~ъ~harrcir~⥈~harrw~↭~hbar~ℏ~hcirc~ĥ~heartsuit~♥~hercon~⊹~hfr~𝔥~hksearow~⤥~hkswarow~⤦~hoarr~⇿~homtht~∻~hookleftarrow~↩~hookrightarrow~↪~hopf~𝕙~horbar~―~hscr~𝒽~hslash~ℏ~hstrok~ħ~hybull~⁃~hyphen~‐~ic~⁣~icy~и~iecy~е~iff~⇔~ifr~𝔦~ii~ⅈ~iiiint~⨌~iiint~∭~iinfin~⧜~iiota~℩~ijlig~ij~imacr~ī~imagline~ℐ~imagpart~ℑ~imath~ı~imof~⊷~imped~Ƶ~in~∈~incare~℅~infintie~⧝~inodot~ı~intcal~⊺~integers~ℤ~intercal~⊺~intlarhk~⨗~intprod~⨼~iocy~ё~iogon~į~iopf~𝕚~iprod~⨼~iscr~𝒾~isinE~⋹~isindot~⋵~isins~⋴~isinsv~⋳~isinv~∈~it~⁢~itilde~ĩ~iukcy~і~jcirc~ĵ~jcy~й~jfr~𝔧~jmath~ȷ~jopf~𝕛~jscr~𝒿~jsercy~ј~jukcy~є~kappav~ϰ~kcedil~ķ~kcy~к~kfr~𝔨~kgreen~ĸ~khcy~х~kjcy~ќ~kopf~𝕜~kscr~𝓀~lAarr~⇚~lAtail~⤛~lBarr~⤎~lE~≦~lEg~⪋~lHar~⥢~lacute~ĺ~laemptyv~⦴~lagran~ℒ~langd~⦑~langle~⟨~lap~⪅~larrb~⇤~larrbfs~⤟~larrfs~⤝~larrhk~↩~larrlp~↫~larrpl~⤹~larrsim~⥳~larrtl~↢~lat~⪫~latail~⤙~late~⪭~lates~⪭︀~lbarr~⤌~lbbrk~❲~lbrace~{~lbrack~[~lbrke~⦋~lbrksld~⦏~lbrkslu~⦍~lcaron~ľ~lcedil~ļ~lcub~{~lcy~л~ldca~⤶~ldquor~„~ldrdhar~⥧~ldrushar~⥋~ldsh~↲~leftarrow~←~leftarrowtail~↢~leftharpoondown~↽~leftharpoonup~↼~leftleftarrows~⇇~leftrightarrow~↔~leftrightarrows~⇆~leftrightharpoons~⇋~leftrightsquigarrow~↭~leftthreetimes~⋋~leg~⋚~leq~≤~leqq~≦~leqslant~⩽~les~⩽~lescc~⪨~lesdot~⩿~lesdoto~⪁~lesdotor~⪃~lesg~⋚︀~lesges~⪓~lessapprox~⪅~lessdot~⋖~lesseqgtr~⋚~lesseqqgtr~⪋~lessgtr~≶~lesssim~≲~lfisht~⥼~lfr~𝔩~lg~≶~lgE~⪑~lhard~↽~lharu~↼~lharul~⥪~lhblk~▄~ljcy~љ~ll~≪~llarr~⇇~llcorner~⌞~llhard~⥫~lltri~◺~lmidot~ŀ~lmoust~⎰~lmoustache~⎰~lnE~≨~lnap~⪉~lnapprox~⪉~lne~⪇~lneq~⪇~lneqq~≨~lnsim~⋦~loang~⟬~loarr~⇽~lobrk~⟦~longleftarrow~⟵~longleftrightarrow~⟷~longmapsto~⟼~longrightarrow~⟶~looparrowleft~↫~looparrowright~↬~lopar~⦅~lopf~𝕝~loplus~⨭~lotimes~⨴~lowbar~_~lozenge~◊~lozf~⧫~lpar~(~lparlt~⦓~lrarr~⇆~lrcorner~⌟~lrhar~⇋~lrhard~⥭~lrtri~⊿~lscr~𝓁~lsh~↰~lsim~≲~lsime~⪍~lsimg~⪏~lsqb~[~lsquor~‚~lstrok~ł~ltcc~⪦~ltcir~⩹~ltdot~⋖~lthree~⋋~ltimes~⋉~ltlarr~⥶~ltquest~⩻~ltrPar~⦖~ltri~◃~ltrie~⊴~ltrif~◂~lurdshar~⥊~luruhar~⥦~lvertneqq~≨︀~lvnE~≨︀~mDDot~∺~male~♂~malt~✠~maltese~✠~map~↦~mapsto~↦~mapstodown~↧~mapstoleft~↤~mapstoup~↥~marker~▮~mcomma~⨩~mcy~м~measuredangle~∡~mfr~𝔪~mho~℧~mid~∣~midast~*~midcir~⫰~minusb~⊟~minusd~∸~minusdu~⨪~mlcp~⫛~mldr~…~mnplus~∓~models~⊧~mopf~𝕞~mp~∓~mscr~𝓂~mstpos~∾~multimap~⊸~mumap~⊸~nGg~⋙̸~nGt~≫⃒~nGtv~≫̸~nLeftarrow~⇍~nLeftrightarrow~⇎~nLl~⋘̸~nLt~≪⃒~nLtv~≪̸~nRightarrow~⇏~nVDash~⊯~nVdash~⊮~nacute~ń~nang~∠⃒~nap~≉~napE~⩰̸~napid~≋̸~napos~ʼn~napprox~≉~natur~♮~natural~♮~naturals~ℕ~nbump~≎̸~nbumpe~≏̸~ncap~⩃~ncaron~ň~ncedil~ņ~ncong~≇~ncongdot~⩭̸~ncup~⩂~ncy~н~neArr~⇗~nearhk~⤤~nearr~↗~nearrow~↗~nedot~≐̸~nequiv~≢~nesear~⤨~nesim~≂̸~nexist~∄~nexists~∄~nfr~𝔫~ngE~≧̸~nge~≱~ngeq~≱~ngeqq~≧̸~ngeqslant~⩾̸~nges~⩾̸~ngsim~≵~ngt~≯~ngtr~≯~nhArr~⇎~nharr~↮~nhpar~⫲~nis~⋼~nisd~⋺~niv~∋~njcy~њ~nlArr~⇍~nlE~≦̸~nlarr~↚~nldr~‥~nle~≰~nleftarrow~↚~nleftrightarrow~↮~nleq~≰~nleqq~≦̸~nleqslant~⩽̸~nles~⩽̸~nless~≮~nlsim~≴~nlt~≮~nltri~⋪~nltrie~⋬~nmid~∤~nopf~𝕟~notinE~⋹̸~notindot~⋵̸~notinva~∉~notinvb~⋷~notinvc~⋶~notni~∌~notniva~∌~notnivb~⋾~notnivc~⋽~npar~∦~nparallel~∦~nparsl~⫽⃥~npart~∂̸~npolint~⨔~npr~⊀~nprcue~⋠~npre~⪯̸~nprec~⊀~npreceq~⪯̸~nrArr~⇏~nrarr~↛~nrarrc~⤳̸~nrarrw~↝̸~nrightarrow~↛~nrtri~⋫~nrtrie~⋭~nsc~⊁~nsccue~⋡~nsce~⪰̸~nscr~𝓃~nshortmid~∤~nshortparallel~∦~nsim~≁~nsime~≄~nsimeq~≄~nsmid~∤~nspar~∦~nsqsube~⋢~nsqsupe~⋣~nsubE~⫅̸~nsube~⊈~nsubset~⊂⃒~nsubseteq~⊈~nsubseteqq~⫅̸~nsucc~⊁~nsucceq~⪰̸~nsup~⊅~nsupE~⫆̸~nsupe~⊉~nsupset~⊃⃒~nsupseteq~⊉~nsupseteqq~⫆̸~ntgl~≹~ntlg~≸~ntriangleleft~⋪~ntrianglelefteq~⋬~ntriangleright~⋫~ntrianglerighteq~⋭~num~#~numero~№~numsp~ ~nvDash~⊭~nvHarr~⤄~nvap~≍⃒~nvdash~⊬~nvge~≥⃒~nvgt~>⃒~nvinfin~⧞~nvlArr~⤂~nvle~≤⃒~nvlt~<⃒~nvltrie~⊴⃒~nvrArr~⤃~nvrtrie~⊵⃒~nvsim~∼⃒~nwArr~⇖~nwarhk~⤣~nwarr~↖~nwarrow~↖~nwnear~⤧~oS~Ⓢ~oast~⊛~ocir~⊚~ocy~о~odash~⊝~odblac~ő~odiv~⨸~odot~⊙~odsold~⦼~ofcir~⦿~ofr~𝔬~ogon~˛~ogt~⧁~ohbar~⦵~ohm~Ω~oint~∮~olarr~↺~olcir~⦾~olcross~⦻~olt~⧀~omacr~ō~omid~⦶~ominus~⊖~oopf~𝕠~opar~⦷~operp~⦹~orarr~↻~ord~⩝~order~ℴ~orderof~ℴ~origof~⊶~oror~⩖~orslope~⩗~orv~⩛~oscr~ℴ~osol~⊘~otimesas~⨶~ovbar~⌽~par~∥~parallel~∥~parsim~⫳~parsl~⫽~pcy~п~percnt~%~period~.~pertenk~‱~pfr~𝔭~phiv~ϕ~phmmat~ℳ~phone~☎~pitchfork~⋔~planck~ℏ~planckh~ℎ~plankv~ℏ~plus~+~plusacir~⨣~plusb~⊞~pluscir~⨢~plusdo~∔~plusdu~⨥~pluse~⩲~plussim~⨦~plustwo~⨧~pm~±~pointint~⨕~popf~𝕡~pr~≺~prE~⪳~prap~⪷~prcue~≼~pre~⪯~prec~≺~precapprox~⪷~preccurlyeq~≼~preceq~⪯~precnapprox~⪹~precneqq~⪵~precnsim~⋨~precsim~≾~primes~ℙ~prnE~⪵~prnap~⪹~prnsim~⋨~profalar~⌮~profline~⌒~profsurf~⌓~propto~∝~prsim~≾~prurel~⊰~pscr~𝓅~puncsp~ ~qfr~𝔮~qint~⨌~qopf~𝕢~qprime~⁗~qscr~𝓆~quaternions~ℍ~quatint~⨖~quest~?~questeq~≟~rAarr~⇛~rAtail~⤜~rBarr~⤏~rHar~⥤~race~∽̱~racute~ŕ~raemptyv~⦳~rangd~⦒~range~⦥~rangle~⟩~rarrap~⥵~rarrb~⇥~rarrbfs~⤠~rarrc~⤳~rarrfs~⤞~rarrhk~↪~rarrlp~↬~rarrpl~⥅~rarrsim~⥴~rarrtl~↣~rarrw~↝~ratail~⤚~ratio~∶~rationals~ℚ~rbarr~⤍~rbbrk~❳~rbrace~}~rbrack~]~rbrke~⦌~rbrksld~⦎~rbrkslu~⦐~rcaron~ř~rcedil~ŗ~rcub~}~rcy~р~rdca~⤷~rdldhar~⥩~rdquor~”~rdsh~↳~realine~ℛ~realpart~ℜ~reals~ℝ~rect~▭~rfisht~⥽~rfr~𝔯~rhard~⇁~rharu~⇀~rharul~⥬~rhov~ϱ~rightarrow~→~rightarrowtail~↣~rightharpoondown~⇁~rightharpoonup~⇀~rightleftarrows~⇄~rightleftharpoons~⇌~rightrightarrows~⇉~rightsquigarrow~↝~rightthreetimes~⋌~ring~˚~risingdotseq~≓~rlarr~⇄~rlhar~⇌~rmoust~⎱~rmoustache~⎱~rnmid~⫮~roang~⟭~roarr~⇾~robrk~⟧~ropar~⦆~ropf~𝕣~roplus~⨮~rotimes~⨵~rpar~)~rpargt~⦔~rppolint~⨒~rrarr~⇉~rscr~𝓇~rsh~↱~rsqb~]~rsquor~’~rthree~⋌~rtimes~⋊~rtri~▹~rtrie~⊵~rtrif~▸~rtriltri~⧎~ruluhar~⥨~rx~℞~sacute~ś~sc~≻~scE~⪴~scap~⪸~sccue~≽~sce~⪰~scedil~ş~scirc~ŝ~scnE~⪶~scnap~⪺~scnsim~⋩~scpolint~⨓~scsim~≿~scy~с~sdotb~⊡~sdote~⩦~seArr~⇘~searhk~⤥~searr~↘~searrow~↘~semi~;~seswar~⤩~setminus~∖~setmn~∖~sext~✶~sfr~𝔰~sfrown~⌢~sharp~♯~shchcy~щ~shcy~ш~shortmid~∣~shortparallel~∥~sigmav~ς~simdot~⩪~sime~≃~simeq~≃~simg~⪞~simgE~⪠~siml~⪝~simlE~⪟~simne~≆~simplus~⨤~simrarr~⥲~slarr~←~smallsetminus~∖~smashp~⨳~smeparsl~⧤~smid~∣~smile~⌣~smt~⪪~smte~⪬~smtes~⪬︀~softcy~ь~sol~/~solb~⧄~solbar~⌿~sopf~𝕤~spadesuit~♠~spar~∥~sqcap~⊓~sqcaps~⊓︀~sqcup~⊔~sqcups~⊔︀~sqsub~⊏~sqsube~⊑~sqsubset~⊏~sqsubseteq~⊑~sqsup~⊐~sqsupe~⊒~sqsupset~⊐~sqsupseteq~⊒~squ~□~square~□~squarf~▪~squf~▪~srarr~→~sscr~𝓈~ssetmn~∖~ssmile~⌣~sstarf~⋆~star~☆~starf~★~straightepsilon~ϵ~straightphi~ϕ~strns~¯~subE~⫅~subdot~⪽~subedot~⫃~submult~⫁~subnE~⫋~subne~⊊~subplus~⪿~subrarr~⥹~subset~⊂~subseteq~⊆~subseteqq~⫅~subsetneq~⊊~subsetneqq~⫋~subsim~⫇~subsub~⫕~subsup~⫓~succ~≻~succapprox~⪸~succcurlyeq~≽~succeq~⪰~succnapprox~⪺~succneqq~⪶~succnsim~⋩~succsim~≿~sung~♪~supE~⫆~supdot~⪾~supdsub~⫘~supedot~⫄~suphsol~⟉~suphsub~⫗~suplarr~⥻~supmult~⫂~supnE~⫌~supne~⊋~supplus~⫀~supset~⊃~supseteq~⊇~supseteqq~⫆~supsetneq~⊋~supsetneqq~⫌~supsim~⫈~supsub~⫔~supsup~⫖~swArr~⇙~swarhk~⤦~swarr~↙~swarrow~↙~swnwar~⤪~target~⌖~tbrk~⎴~tcaron~ť~tcedil~ţ~tcy~т~tdot~⃛~telrec~⌕~tfr~𝔱~therefore~∴~thetav~ϑ~thickapprox~≈~thicksim~∼~thkap~≈~thksim~∼~timesb~⊠~timesbar~⨱~timesd~⨰~tint~∭~toea~⤨~top~⊤~topbot~⌶~topcir~⫱~topf~𝕥~topfork~⫚~tosa~⤩~tprime~‴~triangle~▵~triangledown~▿~triangleleft~◃~trianglelefteq~⊴~triangleq~≜~triangleright~▹~trianglerighteq~⊵~tridot~◬~trie~≜~triminus~⨺~triplus~⨹~trisb~⧍~tritime~⨻~trpezium~⏢~tscr~𝓉~tscy~ц~tshcy~ћ~tstrok~ŧ~twixt~≬~twoheadleftarrow~↞~twoheadrightarrow~↠~uHar~⥣~ubrcy~ў~ubreve~ŭ~ucy~у~udarr~⇅~udblac~ű~udhar~⥮~ufisht~⥾~ufr~𝔲~uharl~↿~uharr~↾~uhblk~▀~ulcorn~⌜~ulcorner~⌜~ulcrop~⌏~ultri~◸~umacr~ū~uogon~ų~uopf~𝕦~uparrow~↑~updownarrow~↕~upharpoonleft~↿~upharpoonright~↾~uplus~⊎~upsi~υ~upuparrows~⇈~urcorn~⌝~urcorner~⌝~urcrop~⌎~uring~ů~urtri~◹~uscr~𝓊~utdot~⋰~utilde~ũ~utri~▵~utrif~▴~uuarr~⇈~uwangle~⦧~vArr~⇕~vBar~⫨~vBarv~⫩~vDash~⊨~vangrt~⦜~varepsilon~ϵ~varkappa~ϰ~varnothing~∅~varphi~ϕ~varpi~ϖ~varpropto~∝~varr~↕~varrho~ϱ~varsigma~ς~varsubsetneq~⊊︀~varsubsetneqq~⫋︀~varsupsetneq~⊋︀~varsupsetneqq~⫌︀~vartheta~ϑ~vartriangleleft~⊲~vartriangleright~⊳~vcy~в~vdash~⊢~vee~∨~veebar~⊻~veeeq~≚~vellip~⋮~verbar~|~vert~|~vfr~𝔳~vltri~⊲~vnsub~⊂⃒~vnsup~⊃⃒~vopf~𝕧~vprop~∝~vrtri~⊳~vscr~𝓋~vsubnE~⫋︀~vsubne~⊊︀~vsupnE~⫌︀~vsupne~⊋︀~vzigzag~⦚~wcirc~ŵ~wedbar~⩟~wedge~∧~wedgeq~≙~wfr~𝔴~wopf~𝕨~wp~℘~wr~≀~wreath~≀~wscr~𝓌~xcap~⋂~xcirc~◯~xcup~⋃~xdtri~▽~xfr~𝔵~xhArr~⟺~xharr~⟷~xlArr~⟸~xlarr~⟵~xmap~⟼~xnis~⋻~xodot~⨀~xopf~𝕩~xoplus~⨁~xotime~⨂~xrArr~⟹~xrarr~⟶~xscr~𝓍~xsqcup~⨆~xuplus~⨄~xutri~△~xvee~⋁~xwedge~⋀~yacy~я~ycirc~ŷ~ycy~ы~yfr~𝔶~yicy~ї~yopf~𝕪~yscr~𝓎~yucy~ю~zacute~ź~zcaron~ž~zcy~з~zdot~ż~zeetrf~ℨ~zfr~𝔷~zhcy~ж~zigrarr~⇝~zopf~𝕫~zscr~𝓏~~AMP~&~COPY~©~GT~>~LT~<~QUOT~\"~REG~®", namedReferences['html4']); diff --git a/node_modules/html-entities/src/numeric-unicode-map.ts b/node_modules/html-entities/src/numeric-unicode-map.ts new file mode 100644 index 0000000..1906d71 --- /dev/null +++ b/node_modules/html-entities/src/numeric-unicode-map.ts @@ -0,0 +1,30 @@ +export const numericUnicodeMap: Record = { + 0: 65533, + 128: 8364, + 130: 8218, + 131: 402, + 132: 8222, + 133: 8230, + 134: 8224, + 135: 8225, + 136: 710, + 137: 8240, + 138: 352, + 139: 8249, + 140: 338, + 142: 381, + 145: 8216, + 146: 8217, + 147: 8220, + 148: 8221, + 149: 8226, + 150: 8211, + 151: 8212, + 152: 732, + 153: 8482, + 154: 353, + 155: 8250, + 156: 339, + 158: 382, + 159: 376 +}; diff --git a/node_modules/html-entities/src/surrogate-pairs.ts b/node_modules/html-entities/src/surrogate-pairs.ts new file mode 100644 index 0000000..ee604c1 --- /dev/null +++ b/node_modules/html-entities/src/surrogate-pairs.ts @@ -0,0 +1,20 @@ +export const fromCodePoint = + String.fromCodePoint || + function (astralCodePoint: number) { + return String.fromCharCode( + Math.floor((astralCodePoint - 0x10000) / 0x400) + 0xd800, + ((astralCodePoint - 0x10000) % 0x400) + 0xdc00 + ); + }; + +// @ts-expect-error - String.prototype.codePointAt might not exist in older node versions +export const getCodePoint = String.prototype.codePointAt + ? function (input: string, position: number) { + return input.codePointAt(position); + } + : function (input: string, position: number) { + return (input.charCodeAt(position) - 0xd800) * 0x400 + input.charCodeAt(position + 1) - 0xdc00 + 0x10000; + }; + +export const highSurrogateFrom = 0xd800; +export const highSurrogateTo = 0xdbff; diff --git a/node_modules/http-parser-js/LICENSE.md b/node_modules/http-parser-js/LICENSE.md new file mode 100644 index 0000000..91e8ce1 --- /dev/null +++ b/node_modules/http-parser-js/LICENSE.md @@ -0,0 +1,110 @@ +Copyright (c) 2015 Tim Caswell (https://github.com/creationix) and other +contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +Some files from the tests folder are from joyent/node and mscedex/io.js, a fork +of nodejs/io.js: + +- tests/iojs/test-http-parser-durability.js + + This file is from https://github.com/mscdex/io.js/blob/js-http-parser/test/pummel/test-http-parser-durability.js + with modifications by Jan Schär (jscissr). + + """ + Copyright io.js contributors. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to + deal in the Software without restriction, including without limitation the + rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + sell copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + IN THE SOFTWARE. + """ + +- tests/fixtures/* + tests/parallel/* + tests/testpy/* + tests/common.js + tests/test.py + tests/utils.py + + These files are from https://github.com/nodejs/node with changes by + Jan Schär (jscissr). + + Node.js is licensed for use as follows: + + """ + Copyright Node.js contributors. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to + deal in the Software without restriction, including without limitation the + rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + sell copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + IN THE SOFTWARE. + """ + + This license applies to parts of Node.js originating from the + https://github.com/joyent/node repository: + + """ + Copyright Joyent, Inc. and other Node contributors. All rights reserved. + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to + deal in the Software without restriction, including without limitation the + rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + sell copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + IN THE SOFTWARE. + """ + \ No newline at end of file diff --git a/node_modules/http-parser-js/README.md b/node_modules/http-parser-js/README.md new file mode 100644 index 0000000..6c7fce0 --- /dev/null +++ b/node_modules/http-parser-js/README.md @@ -0,0 +1,43 @@ +![Node](https://github.com/creationix/http-parser-js/workflows/Node/badge.svg) +![Node-v12](https://github.com/creationix/http-parser-js/workflows/Node-v12/badge.svg) + +# HTTP Parser + +This library parses HTTP protocol for requests and responses. +It was created to replace `http_parser.c` since calling C++ functions from JS is really slow in V8. +However, it is now primarily useful in having a more flexible/tolerant HTTP parser when dealing with legacy services that do not meet the strict HTTP parsing rules Node's parser follows. + +This is packaged as a standalone npm module. +To use in node, monkeypatch HTTPParser. + +```js +// Monkey patch before you require http for the first time. +process.binding('http_parser').HTTPParser = require('http-parser-js').HTTPParser; + +var http = require('http'); +// ... +``` + +## Testing + +Simply run `npm test`. +The tests are copied from node and mscedex/io.js, with some modifcations. + +## Status + +This should now be usable in any node application, it now supports (nearly) everything `http_parser.c` does while still being tolerant with corrupted headers, and other kinds of malformed data. + +### Node versions + +`http-parser-js` should work via monkey-patching on Node v6-v11, and v13-14. + +Node v12.x renamed the internal http parser, and did not expose it for monkey-patching, so to be able to monkey-patch on Node v12, you must run `node --http-parser=legacy file.js` to opt in to the old, monkey-patchable http_parser binding. + +## Standalone usage + +While this module is intended to be used as a replacement for the internal Node.js parser, it can be used as a standalone parser. The [`standalone-example.js`](standalone-example.js) demonstrates how to use the somewhat awkward API (coming from compatibility with the Node.js internals) to parse HTTP from raw Buffers. + +## License + +MIT. +See [LICENSE.md](LICENSE.md) diff --git a/node_modules/http-parser-js/http-parser.d.ts b/node_modules/http-parser-js/http-parser.d.ts new file mode 100644 index 0000000..9a8ac57 --- /dev/null +++ b/node_modules/http-parser-js/http-parser.d.ts @@ -0,0 +1,181 @@ +type ParserType = + | 'REQUEST' + | 'RESPONSE' + +type RequestMethod = + | 'DELETE' + | 'GET' + | 'HEAD' + | 'POST' + | 'PUT' + | 'CONNECT' + | 'OPTIONS' + | 'TRACE' + | 'COPY' + | 'LOCK' + | 'MKCOL' + | 'MOVE' + | 'PROPFIND' + | 'PROPPATCH' + | 'SEARCH' + | 'UNLOCK' + | 'BIND' + | 'REBIND' + | 'UNBIND' + | 'ACL' + | 'REPORT' + | 'MKACTIVITY' + | 'CHECKOUT' + | 'MERGE' + | 'M-SEARCH' + | 'NOTIFY' + | 'SUBSCRIBE' + | 'UNSUBSCRIBE' + | 'PATCH' + | 'PURGE' + | 'MKCALENDAR' + | 'LINK' + | 'UNLINK' + | string + +type StateHeaderKey = + | 'REQUEST_LINE' + | 'RESPONSE_LINE' + | 'HEADER' + +type StateFinishAllowedKey = + | 'REQUEST_LINE' + | 'RESPONSE_LINE' + | 'BODY_RAW' + +type HeaderObject = Array +type noop = ()=> T + +type HeaderInfo
                          = { + versionMajor: number + versionMinor: number + headers: HEADER + method: number + url: string + statusCode: number + statusMessage: string + upgrade: boolean + shouldKeepAlive: boolean +} +export type OnHeadersCompleteParser
                          = Mode_0_12 extends true + ? (info: HeaderInfo
                          )=> number | void + : ( + versionMajor: number, + versionMinor: number, + headers: HEADER, + method: number, + url: string, + statusCode: number, + statusMessage: string, + upgrade: boolean, + shouldKeepAlive: boolean, + )=> number | void +export type OnBodyParser = (chunk: Buffer, offset: number, length: number)=> void +// Only called in the slow case where slow means +// that the request headers were either fragmented +// across multiple TCP packets or too large to be +// processed in a single run. This method is also +// called to process trailing HTTP headers. +export type OnHeadersParser = (headers: string[], url: string)=> void + +declare class HTTPParserJS { + initialize(type: ParserType, async_resource?: unknown): void + + // Some handler stubs, needed for compatibility + [HTTPParser.kOnHeaders]: OnHeadersParser + [HTTPParser.kOnHeadersComplete]: OnHeadersCompleteParser + [HTTPParser.kOnBody]: OnBodyParser + [HTTPParser.kOnMessageComplete]: noop + + /** + * Max number of bytes that will be parsed as headers, 80kb by default + * @default 81920 + */ + maxHeaderSize: number + + reinitialize: HTTPParserConstructor + close: noop + pause: noop + resume: noop + free: noop + private _compatMode0_11: false | boolean + getAsyncId: noop<0> + + execute(chunk: Buffer, start?: number, length?: number): number | Error + finish(): void | Error + + // These three methods are used for an internal speed optimization, and it also + // works if theses are noops. Basically consume() asks us to read the bytes + // ourselves, but if we don't do it we get them through execute(). + consume: noop + unconsume: noop + getCurrentBuffer: noop + + /** + * For correct error handling - see HTTPParser#execute + * @example this.userCall()(userFunction('arg')); + */ + userCall(): (ret?: T)=> T + private nextRequest: noop + private consumeLine: noop + parseHeader(line: string, headers: string[]): void + private REQUEST_LINE: noop + private RESPONSE_LINE: noop + shouldKeepAlive(): boolean + /** + * For older versions of node (v6.x and older?), that return `skipBody=1` or `skipBody=true`, need this `return true;` if it's an upgrade request. + */ + private HEADER(): void | boolean + private BODY_CHUNKHEAD(): void + private BODY_CHUNK(): void + private BODY_CHUNKEMPTYLINE(): void + private BODY_CHUNKTRAILERS(): void + private BODY_RAW(): void + private BODY_SIZED(): void + + get onHeaders(): OnHeadersParser + set onHeaders(to: OnHeadersParser) + + get onHeadersComplete(): OnHeadersCompleteParser + set onHeadersComplete(to: OnHeadersCompleteParser) + + get onBody(): OnBodyParser + set onBody(to: OnBodyParser) + + get onMessageComplete(): noop + set onMessageComplete(to: noop) +} + +interface HTTPParserConstructor extends Function { + new(type?: ParserType): HTTPParserJS + (type?: ParserType): void + + readonly prototype: HTTPParserJS + + readonly REQUEST: 'REQUEST' + readonly RESPONSE: 'RESPONSE' + readonly methods: RequestMethod[] + + encoding: 'ascii'|string + /** + * maxHeaderSize (in bytes) is configurable, but 80kb by default; + * @default 80 * 1024 = 80kb + */ + maxHeaderSize: 81920|number + + // Note: *not* starting with kOnHeaders=0 line the Node parser, because any + // newly added constants (kOnTimeout in Node v12.19.0) will overwrite 0! + readonly kOnHeaders: 1 + readonly kOnHeadersComplete: 2 + readonly kOnBody: 3 + readonly kOnMessageComplete: 4 + + kOnExecute(): void +} +export const HTTPParser: HTTPParserConstructor +export const methods: RequestMethod[] diff --git a/node_modules/http-parser-js/http-parser.js b/node_modules/http-parser-js/http-parser.js new file mode 100644 index 0000000..3e98ab9 --- /dev/null +++ b/node_modules/http-parser-js/http-parser.js @@ -0,0 +1,470 @@ +/*jshint node:true */ + +exports.HTTPParser = HTTPParser; +function HTTPParser(type) { + if (type !== undefined && type !== HTTPParser.REQUEST && type !== HTTPParser.RESPONSE) { + throw new Error('type must be REQUEST or RESPONSE'); + } + if (type === undefined) { + // Node v12+ + } else { + this.initialize(type); + } + this.maxHeaderSize=HTTPParser.maxHeaderSize +} +HTTPParser.prototype.initialize = function (type, async_resource) { + if (type !== HTTPParser.REQUEST && type !== HTTPParser.RESPONSE) { + throw new Error('type must be REQUEST or RESPONSE'); + } + this.type = type; + this.state = type + '_LINE'; + this.info = { + headers: [], + upgrade: false + }; + this.trailers = []; + this.line = ''; + this.isChunked = false; + this.connection = ''; + this.headerSize = 0; // for preventing too big headers + this.body_bytes = null; + this.isUserCall = false; + this.hadError = false; +}; + +HTTPParser.encoding = 'ascii'; +HTTPParser.maxHeaderSize = 80 * 1024; // maxHeaderSize (in bytes) is configurable, but 80kb by default; +HTTPParser.REQUEST = 'REQUEST'; +HTTPParser.RESPONSE = 'RESPONSE'; + +// Note: *not* starting with kOnHeaders=0 line the Node parser, because any +// newly added constants (kOnTimeout in Node v12.19.0) will overwrite 0! +var kOnHeaders = HTTPParser.kOnHeaders = 1; +var kOnHeadersComplete = HTTPParser.kOnHeadersComplete = 2; +var kOnBody = HTTPParser.kOnBody = 3; +var kOnMessageComplete = HTTPParser.kOnMessageComplete = 4; + +// Some handler stubs, needed for compatibility +HTTPParser.prototype[kOnHeaders] = +HTTPParser.prototype[kOnHeadersComplete] = +HTTPParser.prototype[kOnBody] = +HTTPParser.prototype[kOnMessageComplete] = function () {}; + +var compatMode0_12 = true; +Object.defineProperty(HTTPParser, 'kOnExecute', { + get: function () { + // hack for backward compatibility + compatMode0_12 = false; + return 99; + } + }); + +var methods = exports.methods = HTTPParser.methods = [ + 'DELETE', + 'GET', + 'HEAD', + 'POST', + 'PUT', + 'CONNECT', + 'OPTIONS', + 'TRACE', + 'COPY', + 'LOCK', + 'MKCOL', + 'MOVE', + 'PROPFIND', + 'PROPPATCH', + 'SEARCH', + 'UNLOCK', + 'BIND', + 'REBIND', + 'UNBIND', + 'ACL', + 'REPORT', + 'MKACTIVITY', + 'CHECKOUT', + 'MERGE', + 'M-SEARCH', + 'NOTIFY', + 'SUBSCRIBE', + 'UNSUBSCRIBE', + 'PATCH', + 'PURGE', + 'MKCALENDAR', + 'LINK', + 'UNLINK', + 'SOURCE', +]; +var method_connect = methods.indexOf('CONNECT'); +HTTPParser.prototype.reinitialize = HTTPParser; +HTTPParser.prototype.close = +HTTPParser.prototype.pause = +HTTPParser.prototype.resume = +HTTPParser.prototype.remove = +HTTPParser.prototype.free = function () {}; +HTTPParser.prototype._compatMode0_11 = false; +HTTPParser.prototype.getAsyncId = function() { return 0; }; + +var headerState = { + REQUEST_LINE: true, + RESPONSE_LINE: true, + HEADER: true +}; +HTTPParser.prototype.execute = function (chunk, start, length) { + if (!(this instanceof HTTPParser)) { + throw new TypeError('not a HTTPParser'); + } + + // backward compat to node < 0.11.4 + // Note: the start and length params were removed in newer version + start = start || 0; + length = typeof length === 'number' ? length : chunk.length; + + this.chunk = chunk; + this.offset = start; + var end = this.end = start + length; + try { + while (this.offset < end) { + if (this[this.state]()) { + break; + } + } + } catch (err) { + if (this.isUserCall) { + throw err; + } + this.hadError = true; + return err; + } + this.chunk = null; + length = this.offset - start; + if (headerState[this.state]) { + this.headerSize += length; + if (this.headerSize > (this.maxHeaderSize||HTTPParser.maxHeaderSize)) { + return new Error('max header size exceeded'); + } + } + return length; +}; + +var stateFinishAllowed = { + REQUEST_LINE: true, + RESPONSE_LINE: true, + BODY_RAW: true +}; +HTTPParser.prototype.finish = function () { + if (this.hadError) { + return; + } + if (!stateFinishAllowed[this.state]) { + return new Error('invalid state for EOF'); + } + if (this.state === 'BODY_RAW') { + this.userCall()(this[kOnMessageComplete]()); + } +}; + +// These three methods are used for an internal speed optimization, and it also +// works if theses are noops. Basically consume() asks us to read the bytes +// ourselves, but if we don't do it we get them through execute(). +HTTPParser.prototype.consume = +HTTPParser.prototype.unconsume = +HTTPParser.prototype.getCurrentBuffer = function () {}; + +//For correct error handling - see HTTPParser#execute +//Usage: this.userCall()(userFunction('arg')); +HTTPParser.prototype.userCall = function () { + this.isUserCall = true; + var self = this; + return function (ret) { + self.isUserCall = false; + return ret; + }; +}; + +HTTPParser.prototype.nextRequest = function () { + this.userCall()(this[kOnMessageComplete]()); + this.reinitialize(this.type); +}; + +HTTPParser.prototype.consumeLine = function () { + var end = this.end, + chunk = this.chunk; + for (var i = this.offset; i < end; i++) { + if (chunk[i] === 0x0a) { // \n + var line = this.line + chunk.toString(HTTPParser.encoding, this.offset, i); + if (line.charAt(line.length - 1) === '\r') { + line = line.substr(0, line.length - 1); + } + this.line = ''; + this.offset = i + 1; + return line; + } + } + //line split over multiple chunks + this.line += chunk.toString(HTTPParser.encoding, this.offset, this.end); + this.offset = this.end; +}; + +var headerExp = /^([^: \t]+):[ \t]*((?:.*[^ \t])|)/; +var headerContinueExp = /^[ \t]+(.*[^ \t])/; +HTTPParser.prototype.parseHeader = function (line, headers) { + if (line.indexOf('\r') !== -1) { + throw parseErrorCode('HPE_LF_EXPECTED'); + } + + var match = headerExp.exec(line); + var k = match && match[1]; + if (k) { // skip empty string (malformed header) + headers.push(k); + headers.push(match[2]); + } else { + var matchContinue = headerContinueExp.exec(line); + if (matchContinue && headers.length) { + if (headers[headers.length - 1]) { + headers[headers.length - 1] += ' '; + } + headers[headers.length - 1] += matchContinue[1]; + } + } +}; + +var requestExp = /^([A-Z-]+) ([^ ]+) HTTP\/(\d)\.(\d)$/; +HTTPParser.prototype.REQUEST_LINE = function () { + var line = this.consumeLine(); + if (!line) { + return; + } + var match = requestExp.exec(line); + if (match === null) { + throw parseErrorCode('HPE_INVALID_CONSTANT'); + } + this.info.method = this._compatMode0_11 ? match[1] : methods.indexOf(match[1]); + if (this.info.method === -1) { + throw new Error('invalid request method'); + } + this.info.url = match[2]; + this.info.versionMajor = +match[3]; + this.info.versionMinor = +match[4]; + this.body_bytes = 0; + this.state = 'HEADER'; +}; + +var responseExp = /^HTTP\/(\d)\.(\d) (\d{3}) ?(.*)$/; +HTTPParser.prototype.RESPONSE_LINE = function () { + var line = this.consumeLine(); + if (!line) { + return; + } + var match = responseExp.exec(line); + if (match === null) { + throw parseErrorCode('HPE_INVALID_CONSTANT'); + } + this.info.versionMajor = +match[1]; + this.info.versionMinor = +match[2]; + var statusCode = this.info.statusCode = +match[3]; + this.info.statusMessage = match[4]; + // Implied zero length. + if ((statusCode / 100 | 0) === 1 || statusCode === 204 || statusCode === 304) { + this.body_bytes = 0; + } + this.state = 'HEADER'; +}; + +HTTPParser.prototype.shouldKeepAlive = function () { + if (this.info.versionMajor > 0 && this.info.versionMinor > 0) { + if (this.connection.indexOf('close') !== -1) { + return false; + } + } else if (this.connection.indexOf('keep-alive') === -1) { + return false; + } + if (this.body_bytes !== null || this.isChunked) { // || skipBody + return true; + } + return false; +}; + +HTTPParser.prototype.HEADER = function () { + var line = this.consumeLine(); + if (line === undefined) { + return; + } + var info = this.info; + if (line) { + this.parseHeader(line, info.headers); + } else { + var headers = info.headers; + var hasContentLength = false; + var currentContentLengthValue; + var hasUpgradeHeader = false; + for (var i = 0; i < headers.length; i += 2) { + switch (headers[i].toLowerCase()) { + case 'transfer-encoding': + this.isChunked = headers[i + 1].toLowerCase() === 'chunked'; + break; + case 'content-length': + currentContentLengthValue = +headers[i + 1]; + if (hasContentLength) { + // Fix duplicate Content-Length header with same values. + // Throw error only if values are different. + // Known issues: + // https://github.com/request/request/issues/2091#issuecomment-328715113 + // https://github.com/nodejs/node/issues/6517#issuecomment-216263771 + if (currentContentLengthValue !== this.body_bytes) { + throw parseErrorCode('HPE_UNEXPECTED_CONTENT_LENGTH'); + } + } else { + hasContentLength = true; + this.body_bytes = currentContentLengthValue; + } + break; + case 'connection': + this.connection += headers[i + 1].toLowerCase(); + break; + case 'upgrade': + hasUpgradeHeader = true; + break; + } + } + + // if both isChunked and hasContentLength, isChunked wins + // This is required so the body is parsed using the chunked method, and matches + // Chrome's behavior. We could, maybe, ignore them both (would get chunked + // encoding into the body), and/or disable shouldKeepAlive to be more + // resilient. + if (this.isChunked && hasContentLength) { + hasContentLength = false; + this.body_bytes = null; + } + + // Logic from https://github.com/nodejs/http-parser/blob/921d5585515a153fa00e411cf144280c59b41f90/http_parser.c#L1727-L1737 + // "For responses, "Upgrade: foo" and "Connection: upgrade" are + // mandatory only when it is a 101 Switching Protocols response, + // otherwise it is purely informational, to announce support. + if (hasUpgradeHeader && this.connection.indexOf('upgrade') != -1) { + info.upgrade = this.type === HTTPParser.REQUEST || info.statusCode === 101; + } else { + info.upgrade = info.method === method_connect; + } + + if (this.isChunked && info.upgrade) { + this.isChunked = false; + } + + info.shouldKeepAlive = this.shouldKeepAlive(); + //problem which also exists in original node: we should know skipBody before calling onHeadersComplete + var skipBody; + if (compatMode0_12) { + skipBody = this.userCall()(this[kOnHeadersComplete](info)); + } else { + skipBody = this.userCall()(this[kOnHeadersComplete](info.versionMajor, + info.versionMinor, info.headers, info.method, info.url, info.statusCode, + info.statusMessage, info.upgrade, info.shouldKeepAlive)); + } + if (skipBody === 2) { + this.nextRequest(); + return true; + } else if (this.isChunked && !skipBody) { + this.state = 'BODY_CHUNKHEAD'; + } else if (skipBody || this.body_bytes === 0) { + this.nextRequest(); + // For older versions of node (v6.x and older?), that return skipBody=1 or skipBody=true, + // need this "return true;" if it's an upgrade request. + return info.upgrade; + } else if (this.body_bytes === null) { + this.state = 'BODY_RAW'; + } else { + this.state = 'BODY_SIZED'; + } + } +}; + +HTTPParser.prototype.BODY_CHUNKHEAD = function () { + var line = this.consumeLine(); + if (line === undefined) { + return; + } + this.body_bytes = parseInt(line, 16); + if (!this.body_bytes) { + this.state = 'BODY_CHUNKTRAILERS'; + } else { + this.state = 'BODY_CHUNK'; + } +}; + +HTTPParser.prototype.BODY_CHUNK = function () { + var length = Math.min(this.end - this.offset, this.body_bytes); + // 0, length are for backwards compatibility. See: https://github.com/creationix/http-parser-js/pull/98 + this.userCall()(this[kOnBody](this.chunk.slice(this.offset, this.offset + length), 0, length)); + this.offset += length; + this.body_bytes -= length; + if (!this.body_bytes) { + this.state = 'BODY_CHUNKEMPTYLINE'; + } +}; + +HTTPParser.prototype.BODY_CHUNKEMPTYLINE = function () { + var line = this.consumeLine(); + if (line === undefined) { + return; + } + if (line !== '') { + throw new Error('Expected empty line'); + } + this.state = 'BODY_CHUNKHEAD'; +}; + +HTTPParser.prototype.BODY_CHUNKTRAILERS = function () { + var line = this.consumeLine(); + if (line === undefined) { + return; + } + if (line) { + this.parseHeader(line, this.trailers); + } else { + if (this.trailers.length) { + this.userCall()(this[kOnHeaders](this.trailers, '')); + } + this.nextRequest(); + } +}; + +HTTPParser.prototype.BODY_RAW = function () { + // 0, length are for backwards compatibility. See: https://github.com/creationix/http-parser-js/pull/98 + this.userCall()(this[kOnBody](this.chunk.slice(this.offset, this.end), 0, this.end - this.offset)); + this.offset = this.end; +}; + +HTTPParser.prototype.BODY_SIZED = function () { + var length = Math.min(this.end - this.offset, this.body_bytes); + // 0, length are for backwards compatibility. See: https://github.com/creationix/http-parser-js/pull/98 + this.userCall()(this[kOnBody](this.chunk.slice(this.offset, this.offset + length), 0, length)); + this.offset += length; + this.body_bytes -= length; + if (!this.body_bytes) { + this.nextRequest(); + } +}; + +// backward compat to node < 0.11.6 +['Headers', 'HeadersComplete', 'Body', 'MessageComplete'].forEach(function (name) { + var k = HTTPParser['kOn' + name]; + Object.defineProperty(HTTPParser.prototype, 'on' + name, { + get: function () { + return this[k]; + }, + set: function (to) { + // hack for backward compatibility + this._compatMode0_11 = true; + method_connect = 'CONNECT'; + return (this[k] = to); + } + }); +}); + +function parseErrorCode(code) { + var err = new Error('Parse Error'); + err.code = code; + return err; +} diff --git a/node_modules/http-parser-js/package.json b/node_modules/http-parser-js/package.json new file mode 100644 index 0000000..f1a1c24 --- /dev/null +++ b/node_modules/http-parser-js/package.json @@ -0,0 +1,30 @@ +{ + "name": "http-parser-js", + "version": "0.5.10", + "description": "A pure JS HTTP parser for node.", + "main": "http-parser.js", + "types": "http-parser.d.ts", + "scripts": { + "test": "python tests/test.py && node tests/iojs/test-http-parser-durability.js", + "testv12": "python tests/test.py --node-args=\"--http-parser=legacy\" && node --http-parser=legacy tests/iojs/test-http-parser-durability.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/creationix/http-parser-js.git" + }, + "files": [ + "http-parser.js", + "http-parser.d.ts" + ], + "keywords": [ + "http" + ], + "author": "Tim Caswell (https://github.com/creationix)", + "contributors": [ + "Jimb Esser (https://github.com/Jimbly)", + "Lawrence Rowe (https://github.com/lrowe)", + "Jan Schär (https://github.com/jscissr)", + "Paul Rütter (https://github.com/paulrutter)" + ], + "license": "MIT" +} diff --git a/node_modules/http-proxy-agent/README.md b/node_modules/http-proxy-agent/README.md new file mode 100644 index 0000000..d60e206 --- /dev/null +++ b/node_modules/http-proxy-agent/README.md @@ -0,0 +1,74 @@ +http-proxy-agent +================ +### An HTTP(s) proxy `http.Agent` implementation for HTTP +[![Build Status](https://github.com/TooTallNate/node-http-proxy-agent/workflows/Node%20CI/badge.svg)](https://github.com/TooTallNate/node-http-proxy-agent/actions?workflow=Node+CI) + +This module provides an `http.Agent` implementation that connects to a specified +HTTP or HTTPS proxy server, and can be used with the built-in `http` module. + +__Note:__ For HTTP proxy usage with the `https` module, check out +[`node-https-proxy-agent`](https://github.com/TooTallNate/node-https-proxy-agent). + +Installation +------------ + +Install with `npm`: + +``` bash +$ npm install http-proxy-agent +``` + + +Example +------- + +``` js +var url = require('url'); +var http = require('http'); +var HttpProxyAgent = require('http-proxy-agent'); + +// HTTP/HTTPS proxy to connect to +var proxy = process.env.http_proxy || 'http://168.63.76.32:3128'; +console.log('using proxy server %j', proxy); + +// HTTP endpoint for the proxy to connect to +var endpoint = process.argv[2] || 'http://nodejs.org/api/'; +console.log('attempting to GET %j', endpoint); +var opts = url.parse(endpoint); + +// create an instance of the `HttpProxyAgent` class with the proxy server information +var agent = new HttpProxyAgent(proxy); +opts.agent = agent; + +http.get(opts, function (res) { + console.log('"response" event!', res.headers); + res.pipe(process.stdout); +}); +``` + + +License +------- + +(The MIT License) + +Copyright (c) 2013 Nathan Rajlich <nathan@tootallnate.net> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/http-proxy-agent/dist/agent.d.ts b/node_modules/http-proxy-agent/dist/agent.d.ts new file mode 100644 index 0000000..3f043f7 --- /dev/null +++ b/node_modules/http-proxy-agent/dist/agent.d.ts @@ -0,0 +1,32 @@ +/// +import net from 'net'; +import { Agent, ClientRequest, RequestOptions } from 'agent-base'; +import { HttpProxyAgentOptions } from '.'; +interface HttpProxyAgentClientRequest extends ClientRequest { + path: string; + output?: string[]; + outputData?: { + data: string; + }[]; + _header?: string | null; + _implicitHeader(): void; +} +/** + * The `HttpProxyAgent` implements an HTTP Agent subclass that connects + * to the specified "HTTP proxy server" in order to proxy HTTP requests. + * + * @api public + */ +export default class HttpProxyAgent extends Agent { + private secureProxy; + private proxy; + constructor(_opts: string | HttpProxyAgentOptions); + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + * + * @api protected + */ + callback(req: HttpProxyAgentClientRequest, opts: RequestOptions): Promise; +} +export {}; diff --git a/node_modules/http-proxy-agent/dist/agent.js b/node_modules/http-proxy-agent/dist/agent.js new file mode 100644 index 0000000..aca8280 --- /dev/null +++ b/node_modules/http-proxy-agent/dist/agent.js @@ -0,0 +1,145 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const net_1 = __importDefault(require("net")); +const tls_1 = __importDefault(require("tls")); +const url_1 = __importDefault(require("url")); +const debug_1 = __importDefault(require("debug")); +const once_1 = __importDefault(require("@tootallnate/once")); +const agent_base_1 = require("agent-base"); +const debug = (0, debug_1.default)('http-proxy-agent'); +function isHTTPS(protocol) { + return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; +} +/** + * The `HttpProxyAgent` implements an HTTP Agent subclass that connects + * to the specified "HTTP proxy server" in order to proxy HTTP requests. + * + * @api public + */ +class HttpProxyAgent extends agent_base_1.Agent { + constructor(_opts) { + let opts; + if (typeof _opts === 'string') { + opts = url_1.default.parse(_opts); + } + else { + opts = _opts; + } + if (!opts) { + throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); + } + debug('Creating new HttpProxyAgent instance: %o', opts); + super(opts); + const proxy = Object.assign({}, opts); + // If `true`, then connect to the proxy server over TLS. + // Defaults to `false`. + this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); + // Prefer `hostname` over `host`, and set the `port` if needed. + proxy.host = proxy.hostname || proxy.host; + if (typeof proxy.port === 'string') { + proxy.port = parseInt(proxy.port, 10); + } + if (!proxy.port && proxy.host) { + proxy.port = this.secureProxy ? 443 : 80; + } + if (proxy.host && proxy.path) { + // If both a `host` and `path` are specified then it's most likely + // the result of a `url.parse()` call... we need to remove the + // `path` portion so that `net.connect()` doesn't attempt to open + // that as a Unix socket file. + delete proxy.path; + delete proxy.pathname; + } + this.proxy = proxy; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + * + * @api protected + */ + callback(req, opts) { + return __awaiter(this, void 0, void 0, function* () { + const { proxy, secureProxy } = this; + const parsed = url_1.default.parse(req.path); + if (!parsed.protocol) { + parsed.protocol = 'http:'; + } + if (!parsed.hostname) { + parsed.hostname = opts.hostname || opts.host || null; + } + if (parsed.port == null && typeof opts.port) { + parsed.port = String(opts.port); + } + if (parsed.port === '80') { + // if port is 80, then we can remove the port so that the + // ":80" portion is not on the produced URL + parsed.port = ''; + } + // Change the `http.ClientRequest` instance's "path" field + // to the absolute path of the URL that will be requested. + req.path = url_1.default.format(parsed); + // Inject the `Proxy-Authorization` header if necessary. + if (proxy.auth) { + req.setHeader('Proxy-Authorization', `Basic ${Buffer.from(proxy.auth).toString('base64')}`); + } + // Create a socket connection to the proxy server. + let socket; + if (secureProxy) { + debug('Creating `tls.Socket`: %o', proxy); + socket = tls_1.default.connect(proxy); + } + else { + debug('Creating `net.Socket`: %o', proxy); + socket = net_1.default.connect(proxy); + } + // At this point, the http ClientRequest's internal `_header` field + // might have already been set. If this is the case then we'll need + // to re-generate the string since we just changed the `req.path`. + if (req._header) { + let first; + let endOfHeaders; + debug('Regenerating stored HTTP header string for request'); + req._header = null; + req._implicitHeader(); + if (req.output && req.output.length > 0) { + // Node < 12 + debug('Patching connection write() output buffer with updated header'); + first = req.output[0]; + endOfHeaders = first.indexOf('\r\n\r\n') + 4; + req.output[0] = req._header + first.substring(endOfHeaders); + debug('Output buffer: %o', req.output); + } + else if (req.outputData && req.outputData.length > 0) { + // Node >= 12 + debug('Patching connection write() output buffer with updated header'); + first = req.outputData[0].data; + endOfHeaders = first.indexOf('\r\n\r\n') + 4; + req.outputData[0].data = + req._header + first.substring(endOfHeaders); + debug('Output buffer: %o', req.outputData[0].data); + } + } + // Wait for the socket's `connect` event, so that this `callback()` + // function throws instead of the `http` request machinery. This is + // important for i.e. `PacProxyAgent` which determines a failed proxy + // connection via the `callback()` function throwing. + yield (0, once_1.default)(socket, 'connect'); + return socket; + }); + } +} +exports.default = HttpProxyAgent; +//# sourceMappingURL=agent.js.map \ No newline at end of file diff --git a/node_modules/http-proxy-agent/dist/agent.js.map b/node_modules/http-proxy-agent/dist/agent.js.map new file mode 100644 index 0000000..bd3b56a --- /dev/null +++ b/node_modules/http-proxy-agent/dist/agent.js.map @@ -0,0 +1 @@ +{"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,8CAAsB;AACtB,8CAAsB;AACtB,8CAAsB;AACtB,kDAAgC;AAChC,6DAAqC;AACrC,2CAAkE;AAGlE,MAAM,KAAK,GAAG,IAAA,eAAW,EAAC,kBAAkB,CAAC,CAAC;AAY9C,SAAS,OAAO,CAAC,QAAwB;IACxC,OAAO,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC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UAAU,CAAC,CAAC,CAAC,CAAC,IAAI;wBACrB,GAAG,CAAC,OAAO,GAAG,KAAK,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;oBAC7C,KAAK,CAAC,mBAAmB,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;iBACnD;aACD;YAED,mEAAmE;YACnE,mEAAmE;YACnE,qEAAqE;YACrE,qDAAqD;YACrD,MAAM,IAAA,cAAI,EAAC,MAAM,EAAE,SAAS,CAAC,CAAC;YAE9B,OAAO,MAAM,CAAC;QACf,CAAC;KAAA;CACD;AA1ID,iCA0IC"} \ No newline at end of file diff --git a/node_modules/http-proxy-agent/dist/index.d.ts b/node_modules/http-proxy-agent/dist/index.d.ts new file mode 100644 index 0000000..24bdb52 --- /dev/null +++ b/node_modules/http-proxy-agent/dist/index.d.ts @@ -0,0 +1,21 @@ +/// +import net from 'net'; +import tls from 'tls'; +import { Url } from 'url'; +import { AgentOptions } from 'agent-base'; +import _HttpProxyAgent from './agent'; +declare function createHttpProxyAgent(opts: string | createHttpProxyAgent.HttpProxyAgentOptions): _HttpProxyAgent; +declare namespace createHttpProxyAgent { + interface BaseHttpProxyAgentOptions { + secureProxy?: boolean; + host?: string | null; + path?: string | null; + port?: string | number | null; + } + export interface HttpProxyAgentOptions extends AgentOptions, BaseHttpProxyAgentOptions, Partial> { + } + export type HttpProxyAgent = _HttpProxyAgent; + export const HttpProxyAgent: typeof _HttpProxyAgent; + export {}; +} +export = createHttpProxyAgent; diff --git a/node_modules/http-proxy-agent/dist/index.js b/node_modules/http-proxy-agent/dist/index.js new file mode 100644 index 0000000..0a71180 --- /dev/null +++ b/node_modules/http-proxy-agent/dist/index.js @@ -0,0 +1,14 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const agent_1 = __importDefault(require("./agent")); +function createHttpProxyAgent(opts) { + return new agent_1.default(opts); +} +(function (createHttpProxyAgent) { + createHttpProxyAgent.HttpProxyAgent = agent_1.default; + createHttpProxyAgent.prototype = agent_1.default.prototype; +})(createHttpProxyAgent || (createHttpProxyAgent = {})); +module.exports = createHttpProxyAgent; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/http-proxy-agent/dist/index.js.map b/node_modules/http-proxy-agent/dist/index.js.map new file mode 100644 index 0000000..e07dae5 --- /dev/null +++ b/node_modules/http-proxy-agent/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;AAIA,oDAAsC;AAEtC,SAAS,oBAAoB,CAC5B,IAAyD;IAEzD,OAAO,IAAI,eAAe,CAAC,IAAI,CAAC,CAAC;AAClC,CAAC;AAED,WAAU,oBAAoB;IAmBhB,mCAAc,GAAG,eAAe,CAAC;IAE9C,oBAAoB,CAAC,SAAS,GAAG,eAAe,CAAC,SAAS,CAAC;AAC5D,CAAC,EAtBS,oBAAoB,KAApB,oBAAoB,QAsB7B;AAED,iBAAS,oBAAoB,CAAC"} \ No newline at end of file diff --git a/node_modules/http-proxy-agent/node_modules/agent-base/README.md b/node_modules/http-proxy-agent/node_modules/agent-base/README.md new file mode 100644 index 0000000..256f1f3 --- /dev/null +++ b/node_modules/http-proxy-agent/node_modules/agent-base/README.md @@ -0,0 +1,145 @@ +agent-base +========== +### Turn a function into an [`http.Agent`][http.Agent] instance +[![Build Status](https://github.com/TooTallNate/node-agent-base/workflows/Node%20CI/badge.svg)](https://github.com/TooTallNate/node-agent-base/actions?workflow=Node+CI) + +This module provides an `http.Agent` generator. That is, you pass it an async +callback function, and it returns a new `http.Agent` instance that will invoke the +given callback function when sending outbound HTTP requests. + +#### Some subclasses: + +Here's some more interesting uses of `agent-base`. +Send a pull request to list yours! + + * [`http-proxy-agent`][http-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTP endpoints + * [`https-proxy-agent`][https-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTPS endpoints + * [`pac-proxy-agent`][pac-proxy-agent]: A PAC file proxy `http.Agent` implementation for HTTP and HTTPS + * [`socks-proxy-agent`][socks-proxy-agent]: A SOCKS proxy `http.Agent` implementation for HTTP and HTTPS + + +Installation +------------ + +Install with `npm`: + +``` bash +$ npm install agent-base +``` + + +Example +------- + +Here's a minimal example that creates a new `net.Socket` connection to the server +for every HTTP request (i.e. the equivalent of `agent: false` option): + +```js +var net = require('net'); +var tls = require('tls'); +var url = require('url'); +var http = require('http'); +var agent = require('agent-base'); + +var endpoint = 'http://nodejs.org/api/'; +var parsed = url.parse(endpoint); + +// This is the important part! +parsed.agent = agent(function (req, opts) { + var socket; + // `secureEndpoint` is true when using the https module + if (opts.secureEndpoint) { + socket = tls.connect(opts); + } else { + socket = net.connect(opts); + } + return socket; +}); + +// Everything else works just like normal... +http.get(parsed, function (res) { + console.log('"response" event!', res.headers); + res.pipe(process.stdout); +}); +``` + +Returning a Promise or using an `async` function is also supported: + +```js +agent(async function (req, opts) { + await sleep(1000); + // etc… +}); +``` + +Return another `http.Agent` instance to "pass through" the responsibility +for that HTTP request to that agent: + +```js +agent(function (req, opts) { + return opts.secureEndpoint ? https.globalAgent : http.globalAgent; +}); +``` + + +API +--- + +## Agent(Function callback[, Object options]) → [http.Agent][] + +Creates a base `http.Agent` that will execute the callback function `callback` +for every HTTP request that it is used as the `agent` for. The callback function +is responsible for creating a `stream.Duplex` instance of some kind that will be +used as the underlying socket in the HTTP request. + +The `options` object accepts the following properties: + + * `timeout` - Number - Timeout for the `callback()` function in milliseconds. Defaults to Infinity (optional). + +The callback function should have the following signature: + +### callback(http.ClientRequest req, Object options, Function cb) → undefined + +The ClientRequest `req` can be accessed to read request headers and +and the path, etc. The `options` object contains the options passed +to the `http.request()`/`https.request()` function call, and is formatted +to be directly passed to `net.connect()`/`tls.connect()`, or however +else you want a Socket to be created. Pass the created socket to +the callback function `cb` once created, and the HTTP request will +continue to proceed. + +If the `https` module is used to invoke the HTTP request, then the +`secureEndpoint` property on `options` _will be set to `true`_. + + +License +------- + +(The MIT License) + +Copyright (c) 2013 Nathan Rajlich <nathan@tootallnate.net> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +[http-proxy-agent]: https://github.com/TooTallNate/node-http-proxy-agent +[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent +[pac-proxy-agent]: https://github.com/TooTallNate/node-pac-proxy-agent +[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent +[http.Agent]: https://nodejs.org/api/http.html#http_class_http_agent diff --git a/node_modules/http-proxy-agent/node_modules/agent-base/dist/src/index.d.ts b/node_modules/http-proxy-agent/node_modules/agent-base/dist/src/index.d.ts new file mode 100644 index 0000000..bc4ab74 --- /dev/null +++ b/node_modules/http-proxy-agent/node_modules/agent-base/dist/src/index.d.ts @@ -0,0 +1,78 @@ +/// +import net from 'net'; +import http from 'http'; +import https from 'https'; +import { Duplex } from 'stream'; +import { EventEmitter } from 'events'; +declare function createAgent(opts?: createAgent.AgentOptions): createAgent.Agent; +declare function createAgent(callback: createAgent.AgentCallback, opts?: createAgent.AgentOptions): createAgent.Agent; +declare namespace createAgent { + interface ClientRequest extends http.ClientRequest { + _last?: boolean; + _hadError?: boolean; + method: string; + } + interface AgentRequestOptions { + host?: string; + path?: string; + port: number; + } + interface HttpRequestOptions extends AgentRequestOptions, Omit { + secureEndpoint: false; + } + interface HttpsRequestOptions extends AgentRequestOptions, Omit { + secureEndpoint: true; + } + type RequestOptions = HttpRequestOptions | HttpsRequestOptions; + type AgentLike = Pick | http.Agent; + type AgentCallbackReturn = Duplex | AgentLike; + type AgentCallbackCallback = (err?: Error | null, socket?: createAgent.AgentCallbackReturn) => void; + type AgentCallbackPromise = (req: createAgent.ClientRequest, opts: createAgent.RequestOptions) => createAgent.AgentCallbackReturn | Promise; + type AgentCallback = typeof Agent.prototype.callback; + type AgentOptions = { + timeout?: number; + }; + /** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + * + * @param {Function} callback + * @api public + */ + class Agent extends EventEmitter { + timeout: number | null; + maxFreeSockets: number; + maxTotalSockets: number; + maxSockets: number; + sockets: { + [key: string]: net.Socket[]; + }; + freeSockets: { + [key: string]: net.Socket[]; + }; + requests: { + [key: string]: http.IncomingMessage[]; + }; + options: https.AgentOptions; + private promisifiedCallback?; + private explicitDefaultPort?; + private explicitProtocol?; + constructor(callback?: createAgent.AgentCallback | createAgent.AgentOptions, _opts?: createAgent.AgentOptions); + get defaultPort(): number; + set defaultPort(v: number); + get protocol(): string; + set protocol(v: string); + callback(req: createAgent.ClientRequest, opts: createAgent.RequestOptions, fn: createAgent.AgentCallbackCallback): void; + callback(req: createAgent.ClientRequest, opts: createAgent.RequestOptions): createAgent.AgentCallbackReturn | Promise; + /** + * Called by node-core's "_http_client.js" module when creating + * a new HTTP request with this Agent instance. + * + * @api public + */ + addRequest(req: ClientRequest, _opts: RequestOptions): void; + freeSocket(socket: net.Socket, opts: AgentOptions): void; + destroy(): void; + } +} +export = createAgent; diff --git a/node_modules/http-proxy-agent/node_modules/agent-base/dist/src/index.js b/node_modules/http-proxy-agent/node_modules/agent-base/dist/src/index.js new file mode 100644 index 0000000..bfd9e22 --- /dev/null +++ b/node_modules/http-proxy-agent/node_modules/agent-base/dist/src/index.js @@ -0,0 +1,203 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const events_1 = require("events"); +const debug_1 = __importDefault(require("debug")); +const promisify_1 = __importDefault(require("./promisify")); +const debug = debug_1.default('agent-base'); +function isAgent(v) { + return Boolean(v) && typeof v.addRequest === 'function'; +} +function isSecureEndpoint() { + const { stack } = new Error(); + if (typeof stack !== 'string') + return false; + return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); +} +function createAgent(callback, opts) { + return new createAgent.Agent(callback, opts); +} +(function (createAgent) { + /** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + * + * @param {Function} callback + * @api public + */ + class Agent extends events_1.EventEmitter { + constructor(callback, _opts) { + super(); + let opts = _opts; + if (typeof callback === 'function') { + this.callback = callback; + } + else if (callback) { + opts = callback; + } + // Timeout for the socket to be returned from the callback + this.timeout = null; + if (opts && typeof opts.timeout === 'number') { + this.timeout = opts.timeout; + } + // These aren't actually used by `agent-base`, but are required + // for the TypeScript definition files in `@types/node` :/ + this.maxFreeSockets = 1; + this.maxSockets = 1; + this.maxTotalSockets = Infinity; + this.sockets = {}; + this.freeSockets = {}; + this.requests = {}; + this.options = {}; + } + get defaultPort() { + if (typeof this.explicitDefaultPort === 'number') { + return this.explicitDefaultPort; + } + return isSecureEndpoint() ? 443 : 80; + } + set defaultPort(v) { + this.explicitDefaultPort = v; + } + get protocol() { + if (typeof this.explicitProtocol === 'string') { + return this.explicitProtocol; + } + return isSecureEndpoint() ? 'https:' : 'http:'; + } + set protocol(v) { + this.explicitProtocol = v; + } + callback(req, opts, fn) { + throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); + } + /** + * Called by node-core's "_http_client.js" module when creating + * a new HTTP request with this Agent instance. + * + * @api public + */ + addRequest(req, _opts) { + const opts = Object.assign({}, _opts); + if (typeof opts.secureEndpoint !== 'boolean') { + opts.secureEndpoint = isSecureEndpoint(); + } + if (opts.host == null) { + opts.host = 'localhost'; + } + if (opts.port == null) { + opts.port = opts.secureEndpoint ? 443 : 80; + } + if (opts.protocol == null) { + opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; + } + if (opts.host && opts.path) { + // If both a `host` and `path` are specified then it's most + // likely the result of a `url.parse()` call... we need to + // remove the `path` portion so that `net.connect()` doesn't + // attempt to open that as a unix socket file. + delete opts.path; + } + delete opts.agent; + delete opts.hostname; + delete opts._defaultAgent; + delete opts.defaultPort; + delete opts.createConnection; + // Hint to use "Connection: close" + // XXX: non-documented `http` module API :( + req._last = true; + req.shouldKeepAlive = false; + let timedOut = false; + let timeoutId = null; + const timeoutMs = opts.timeout || this.timeout; + const onerror = (err) => { + if (req._hadError) + return; + req.emit('error', err); + // For Safety. Some additional errors might fire later on + // and we need to make sure we don't double-fire the error event. + req._hadError = true; + }; + const ontimeout = () => { + timeoutId = null; + timedOut = true; + const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); + err.code = 'ETIMEOUT'; + onerror(err); + }; + const callbackError = (err) => { + if (timedOut) + return; + if (timeoutId !== null) { + clearTimeout(timeoutId); + timeoutId = null; + } + onerror(err); + }; + const onsocket = (socket) => { + if (timedOut) + return; + if (timeoutId != null) { + clearTimeout(timeoutId); + timeoutId = null; + } + if (isAgent(socket)) { + // `socket` is actually an `http.Agent` instance, so + // relinquish responsibility for this `req` to the Agent + // from here on + debug('Callback returned another Agent instance %o', socket.constructor.name); + socket.addRequest(req, opts); + return; + } + if (socket) { + socket.once('free', () => { + this.freeSocket(socket, opts); + }); + req.onSocket(socket); + return; + } + const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); + onerror(err); + }; + if (typeof this.callback !== 'function') { + onerror(new Error('`callback` is not defined')); + return; + } + if (!this.promisifiedCallback) { + if (this.callback.length >= 3) { + debug('Converting legacy callback function to promise'); + this.promisifiedCallback = promisify_1.default(this.callback); + } + else { + this.promisifiedCallback = this.callback; + } + } + if (typeof timeoutMs === 'number' && timeoutMs > 0) { + timeoutId = setTimeout(ontimeout, timeoutMs); + } + if ('port' in opts && typeof opts.port !== 'number') { + opts.port = Number(opts.port); + } + try { + debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`); + Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); + } + catch (err) { + Promise.reject(err).catch(callbackError); + } + } + freeSocket(socket, opts) { + debug('Freeing socket %o %o', socket.constructor.name, opts); + socket.destroy(); + } + destroy() { + debug('Destroying agent %o', this.constructor.name); + } + } + createAgent.Agent = Agent; + // So that `instanceof` works correctly + createAgent.prototype = createAgent.Agent.prototype; +})(createAgent || (createAgent = {})); +module.exports = createAgent; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/http-proxy-agent/node_modules/agent-base/dist/src/index.js.map b/node_modules/http-proxy-agent/node_modules/agent-base/dist/src/index.js.map new file mode 100644 index 0000000..bd118ab --- /dev/null +++ b/node_modules/http-proxy-agent/node_modules/agent-base/dist/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;AAIA,mCAAsC;AACtC,kDAAgC;AAChC,4DAAoC;AAEpC,MAAM,KAAK,GAAG,eAAW,CAAC,YAAY,CAAC,CAAC;AAExC,SAAS,OAAO,CAAC,CAAM;IACtB,OAAO,OAAO,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,CAAC,UAAU,KAAK,UAAU,CAAC;AACzD,CAAC;AAED,SAAS,gBAAgB;IACxB,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,KAAK,EAAE,CAAC;IAC9B,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC5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,IAAI,CAAC,CAAC;QACrD,CAAC;KACD;IAxPY,iBAAK,QAwPjB,CAAA;IAED,uCAAuC;IACvC,WAAW,CAAC,SAAS,GAAG,WAAW,CAAC,KAAK,CAAC,SAAS,CAAC;AACrD,CAAC,EAtTS,WAAW,KAAX,WAAW,QAsTpB;AAED,iBAAS,WAAW,CAAC"} \ No newline at end of file diff --git a/node_modules/http-proxy-agent/node_modules/agent-base/dist/src/promisify.d.ts b/node_modules/http-proxy-agent/node_modules/agent-base/dist/src/promisify.d.ts new file mode 100644 index 0000000..0268869 --- /dev/null +++ b/node_modules/http-proxy-agent/node_modules/agent-base/dist/src/promisify.d.ts @@ -0,0 +1,4 @@ +import { ClientRequest, RequestOptions, AgentCallbackCallback, AgentCallbackPromise } from './index'; +declare type LegacyCallback = (req: ClientRequest, opts: RequestOptions, fn: AgentCallbackCallback) => void; +export default function promisify(fn: LegacyCallback): AgentCallbackPromise; +export {}; diff --git a/node_modules/http-proxy-agent/node_modules/agent-base/dist/src/promisify.js b/node_modules/http-proxy-agent/node_modules/agent-base/dist/src/promisify.js new file mode 100644 index 0000000..b2f6132 --- /dev/null +++ b/node_modules/http-proxy-agent/node_modules/agent-base/dist/src/promisify.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +function promisify(fn) { + return function (req, opts) { + return new Promise((resolve, reject) => { + fn.call(this, req, opts, (err, rtn) => { + if (err) { + reject(err); + } + else { + resolve(rtn); + } + }); + }); + }; +} +exports.default = promisify; +//# sourceMappingURL=promisify.js.map \ No newline at end of file diff --git a/node_modules/http-proxy-agent/node_modules/agent-base/dist/src/promisify.js.map b/node_modules/http-proxy-agent/node_modules/agent-base/dist/src/promisify.js.map new file mode 100644 index 0000000..4bff9bf --- /dev/null +++ b/node_modules/http-proxy-agent/node_modules/agent-base/dist/src/promisify.js.map @@ -0,0 +1 @@ +{"version":3,"file":"promisify.js","sourceRoot":"","sources":["../../src/promisify.ts"],"names":[],"mappings":";;AAeA,SAAwB,SAAS,CAAC,EAAkB;IACnD,OAAO,UAAsB,GAAkB,EAAE,IAAoB;QACpE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACtC,EAAE,CAAC,IAAI,CACN,IAAI,EACJ,GAAG,EACH,IAAI,EACJ,CAAC,GAA6B,EAAE,GAAyB,EAAE,EAAE;gBAC5D,IAAI,GAAG,EAAE;oBACR,MAAM,CAAC,GAAG,CAAC,CAAC;iBACZ;qBAAM;oBACN,OAAO,CAAC,GAAG,CAAC,CAAC;iBACb;YACF,CAAC,CACD,CAAC;QACH,CAAC,CAAC,CAAC;IACJ,CAAC,CAAC;AACH,CAAC;AAjBD,4BAiBC"} \ No newline at end of file diff --git a/node_modules/http-proxy-agent/node_modules/agent-base/package.json b/node_modules/http-proxy-agent/node_modules/agent-base/package.json new file mode 100644 index 0000000..fadce3a --- /dev/null +++ b/node_modules/http-proxy-agent/node_modules/agent-base/package.json @@ -0,0 +1,64 @@ +{ + "name": "agent-base", + "version": "6.0.2", + "description": "Turn a function into an `http.Agent` instance", + "main": "dist/src/index", + "typings": "dist/src/index", + "files": [ + "dist/src", + "src" + ], + "scripts": { + "prebuild": "rimraf dist", + "build": "tsc", + "postbuild": "cpy --parents src test '!**/*.ts' dist", + "test": "mocha --reporter spec dist/test/*.js", + "test-lint": "eslint src --ext .js,.ts", + "prepublishOnly": "npm run build" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/node-agent-base.git" + }, + "keywords": [ + "http", + "agent", + "base", + "barebones", + "https" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/node-agent-base/issues" + }, + "dependencies": { + "debug": "4" + }, + "devDependencies": { + "@types/debug": "4", + "@types/mocha": "^5.2.7", + "@types/node": "^14.0.20", + "@types/semver": "^7.1.0", + "@types/ws": "^6.0.3", + "@typescript-eslint/eslint-plugin": "1.6.0", + "@typescript-eslint/parser": "1.1.0", + "async-listen": "^1.2.0", + "cpy-cli": "^2.0.0", + "eslint": "5.16.0", + "eslint-config-airbnb": "17.1.0", + "eslint-config-prettier": "4.1.0", + "eslint-import-resolver-typescript": "1.1.1", + "eslint-plugin-import": "2.16.0", + "eslint-plugin-jsx-a11y": "6.2.1", + "eslint-plugin-react": "7.12.4", + "mocha": "^6.2.0", + "rimraf": "^3.0.0", + "semver": "^7.1.2", + "typescript": "^3.5.3", + "ws": "^3.0.0" + }, + "engines": { + "node": ">= 6.0.0" + } +} diff --git a/node_modules/http-proxy-agent/node_modules/agent-base/src/index.ts b/node_modules/http-proxy-agent/node_modules/agent-base/src/index.ts new file mode 100644 index 0000000..a47ccd4 --- /dev/null +++ b/node_modules/http-proxy-agent/node_modules/agent-base/src/index.ts @@ -0,0 +1,345 @@ +import net from 'net'; +import http from 'http'; +import https from 'https'; +import { Duplex } from 'stream'; +import { EventEmitter } from 'events'; +import createDebug from 'debug'; +import promisify from './promisify'; + +const debug = createDebug('agent-base'); + +function isAgent(v: any): v is createAgent.AgentLike { + return Boolean(v) && typeof v.addRequest === 'function'; +} + +function isSecureEndpoint(): boolean { + const { stack } = new Error(); + if (typeof stack !== 'string') return false; + return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); +} + +function createAgent(opts?: createAgent.AgentOptions): createAgent.Agent; +function createAgent( + callback: createAgent.AgentCallback, + opts?: createAgent.AgentOptions +): createAgent.Agent; +function createAgent( + callback?: createAgent.AgentCallback | createAgent.AgentOptions, + opts?: createAgent.AgentOptions +) { + return new createAgent.Agent(callback, opts); +} + +namespace createAgent { + export interface ClientRequest extends http.ClientRequest { + _last?: boolean; + _hadError?: boolean; + method: string; + } + + export interface AgentRequestOptions { + host?: string; + path?: string; + // `port` on `http.RequestOptions` can be a string or undefined, + // but `net.TcpNetConnectOpts` expects only a number + port: number; + } + + export interface HttpRequestOptions + extends AgentRequestOptions, + Omit { + secureEndpoint: false; + } + + export interface HttpsRequestOptions + extends AgentRequestOptions, + Omit { + secureEndpoint: true; + } + + export type RequestOptions = HttpRequestOptions | HttpsRequestOptions; + + export type AgentLike = Pick | http.Agent; + + export type AgentCallbackReturn = Duplex | AgentLike; + + export type AgentCallbackCallback = ( + err?: Error | null, + socket?: createAgent.AgentCallbackReturn + ) => void; + + export type AgentCallbackPromise = ( + req: createAgent.ClientRequest, + opts: createAgent.RequestOptions + ) => + | createAgent.AgentCallbackReturn + | Promise; + + export type AgentCallback = typeof Agent.prototype.callback; + + export type AgentOptions = { + timeout?: number; + }; + + /** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + * + * @param {Function} callback + * @api public + */ + export class Agent extends EventEmitter { + public timeout: number | null; + public maxFreeSockets: number; + public maxTotalSockets: number; + public maxSockets: number; + public sockets: { + [key: string]: net.Socket[]; + }; + public freeSockets: { + [key: string]: net.Socket[]; + }; + public requests: { + [key: string]: http.IncomingMessage[]; + }; + public options: https.AgentOptions; + private promisifiedCallback?: createAgent.AgentCallbackPromise; + private explicitDefaultPort?: number; + private explicitProtocol?: string; + + constructor( + callback?: createAgent.AgentCallback | createAgent.AgentOptions, + _opts?: createAgent.AgentOptions + ) { + super(); + + let opts = _opts; + if (typeof callback === 'function') { + this.callback = callback; + } else if (callback) { + opts = callback; + } + + // Timeout for the socket to be returned from the callback + this.timeout = null; + if (opts && typeof opts.timeout === 'number') { + this.timeout = opts.timeout; + } + + // These aren't actually used by `agent-base`, but are required + // for the TypeScript definition files in `@types/node` :/ + this.maxFreeSockets = 1; + this.maxSockets = 1; + this.maxTotalSockets = Infinity; + this.sockets = {}; + this.freeSockets = {}; + this.requests = {}; + this.options = {}; + } + + get defaultPort(): number { + if (typeof this.explicitDefaultPort === 'number') { + return this.explicitDefaultPort; + } + return isSecureEndpoint() ? 443 : 80; + } + + set defaultPort(v: number) { + this.explicitDefaultPort = v; + } + + get protocol(): string { + if (typeof this.explicitProtocol === 'string') { + return this.explicitProtocol; + } + return isSecureEndpoint() ? 'https:' : 'http:'; + } + + set protocol(v: string) { + this.explicitProtocol = v; + } + + callback( + req: createAgent.ClientRequest, + opts: createAgent.RequestOptions, + fn: createAgent.AgentCallbackCallback + ): void; + callback( + req: createAgent.ClientRequest, + opts: createAgent.RequestOptions + ): + | createAgent.AgentCallbackReturn + | Promise; + callback( + req: createAgent.ClientRequest, + opts: createAgent.AgentOptions, + fn?: createAgent.AgentCallbackCallback + ): + | createAgent.AgentCallbackReturn + | Promise + | void { + throw new Error( + '"agent-base" has no default implementation, you must subclass and override `callback()`' + ); + } + + /** + * Called by node-core's "_http_client.js" module when creating + * a new HTTP request with this Agent instance. + * + * @api public + */ + addRequest(req: ClientRequest, _opts: RequestOptions): void { + const opts: RequestOptions = { ..._opts }; + + if (typeof opts.secureEndpoint !== 'boolean') { + opts.secureEndpoint = isSecureEndpoint(); + } + + if (opts.host == null) { + opts.host = 'localhost'; + } + + if (opts.port == null) { + opts.port = opts.secureEndpoint ? 443 : 80; + } + + if (opts.protocol == null) { + opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; + } + + if (opts.host && opts.path) { + // If both a `host` and `path` are specified then it's most + // likely the result of a `url.parse()` call... we need to + // remove the `path` portion so that `net.connect()` doesn't + // attempt to open that as a unix socket file. + delete opts.path; + } + + delete opts.agent; + delete opts.hostname; + delete opts._defaultAgent; + delete opts.defaultPort; + delete opts.createConnection; + + // Hint to use "Connection: close" + // XXX: non-documented `http` module API :( + req._last = true; + req.shouldKeepAlive = false; + + let timedOut = false; + let timeoutId: ReturnType | null = null; + const timeoutMs = opts.timeout || this.timeout; + + const onerror = (err: NodeJS.ErrnoException) => { + if (req._hadError) return; + req.emit('error', err); + // For Safety. Some additional errors might fire later on + // and we need to make sure we don't double-fire the error event. + req._hadError = true; + }; + + const ontimeout = () => { + timeoutId = null; + timedOut = true; + const err: NodeJS.ErrnoException = new Error( + `A "socket" was not created for HTTP request before ${timeoutMs}ms` + ); + err.code = 'ETIMEOUT'; + onerror(err); + }; + + const callbackError = (err: NodeJS.ErrnoException) => { + if (timedOut) return; + if (timeoutId !== null) { + clearTimeout(timeoutId); + timeoutId = null; + } + onerror(err); + }; + + const onsocket = (socket: AgentCallbackReturn) => { + if (timedOut) return; + if (timeoutId != null) { + clearTimeout(timeoutId); + timeoutId = null; + } + + if (isAgent(socket)) { + // `socket` is actually an `http.Agent` instance, so + // relinquish responsibility for this `req` to the Agent + // from here on + debug( + 'Callback returned another Agent instance %o', + socket.constructor.name + ); + (socket as createAgent.Agent).addRequest(req, opts); + return; + } + + if (socket) { + socket.once('free', () => { + this.freeSocket(socket as net.Socket, opts); + }); + req.onSocket(socket as net.Socket); + return; + } + + const err = new Error( + `no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\`` + ); + onerror(err); + }; + + if (typeof this.callback !== 'function') { + onerror(new Error('`callback` is not defined')); + return; + } + + if (!this.promisifiedCallback) { + if (this.callback.length >= 3) { + debug('Converting legacy callback function to promise'); + this.promisifiedCallback = promisify(this.callback); + } else { + this.promisifiedCallback = this.callback; + } + } + + if (typeof timeoutMs === 'number' && timeoutMs > 0) { + timeoutId = setTimeout(ontimeout, timeoutMs); + } + + if ('port' in opts && typeof opts.port !== 'number') { + opts.port = Number(opts.port); + } + + try { + debug( + 'Resolving socket for %o request: %o', + opts.protocol, + `${req.method} ${req.path}` + ); + Promise.resolve(this.promisifiedCallback(req, opts)).then( + onsocket, + callbackError + ); + } catch (err) { + Promise.reject(err).catch(callbackError); + } + } + + freeSocket(socket: net.Socket, opts: AgentOptions) { + debug('Freeing socket %o %o', socket.constructor.name, opts); + socket.destroy(); + } + + destroy() { + debug('Destroying agent %o', this.constructor.name); + } + } + + // So that `instanceof` works correctly + createAgent.prototype = createAgent.Agent.prototype; +} + +export = createAgent; diff --git a/node_modules/http-proxy-agent/node_modules/agent-base/src/promisify.ts b/node_modules/http-proxy-agent/node_modules/agent-base/src/promisify.ts new file mode 100644 index 0000000..60cc662 --- /dev/null +++ b/node_modules/http-proxy-agent/node_modules/agent-base/src/promisify.ts @@ -0,0 +1,33 @@ +import { + Agent, + ClientRequest, + RequestOptions, + AgentCallbackCallback, + AgentCallbackPromise, + AgentCallbackReturn +} from './index'; + +type LegacyCallback = ( + req: ClientRequest, + opts: RequestOptions, + fn: AgentCallbackCallback +) => void; + +export default function promisify(fn: LegacyCallback): AgentCallbackPromise { + return function(this: Agent, req: ClientRequest, opts: RequestOptions) { + return new Promise((resolve, reject) => { + fn.call( + this, + req, + opts, + (err: Error | null | undefined, rtn?: AgentCallbackReturn) => { + if (err) { + reject(err); + } else { + resolve(rtn); + } + } + ); + }); + }; +} diff --git a/node_modules/http-proxy-agent/package.json b/node_modules/http-proxy-agent/package.json new file mode 100644 index 0000000..659d6e1 --- /dev/null +++ b/node_modules/http-proxy-agent/package.json @@ -0,0 +1,57 @@ +{ + "name": "http-proxy-agent", + "version": "5.0.0", + "description": "An HTTP(s) proxy `http.Agent` implementation for HTTP", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "scripts": { + "prebuild": "rimraf dist", + "build": "tsc", + "test": "mocha", + "test-lint": "eslint src --ext .js,.ts", + "prepublishOnly": "npm run build" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/node-http-proxy-agent.git" + }, + "keywords": [ + "http", + "proxy", + "endpoint", + "agent" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/node-http-proxy-agent/issues" + }, + "dependencies": { + "@tootallnate/once": "2", + "agent-base": "6", + "debug": "4" + }, + "devDependencies": { + "@types/debug": "4", + "@types/node": "^12.19.2", + "@typescript-eslint/eslint-plugin": "1.6.0", + "@typescript-eslint/parser": "1.1.0", + "eslint": "5.16.0", + "eslint-config-airbnb": "17.1.0", + "eslint-config-prettier": "4.1.0", + "eslint-import-resolver-typescript": "1.1.1", + "eslint-plugin-import": "2.16.0", + "eslint-plugin-jsx-a11y": "6.2.1", + "eslint-plugin-react": "7.12.4", + "mocha": "^6.2.2", + "proxy": "1", + "rimraf": "^3.0.0", + "typescript": "^4.4.3" + }, + "engines": { + "node": ">= 6" + } +} diff --git a/node_modules/https-proxy-agent/LICENSE b/node_modules/https-proxy-agent/LICENSE new file mode 100644 index 0000000..008728c --- /dev/null +++ b/node_modules/https-proxy-agent/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2013 Nathan Rajlich + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/https-proxy-agent/README.md b/node_modules/https-proxy-agent/README.md new file mode 100644 index 0000000..ebc53cf --- /dev/null +++ b/node_modules/https-proxy-agent/README.md @@ -0,0 +1,70 @@ +https-proxy-agent +================ +### An HTTP(s) proxy `http.Agent` implementation for HTTPS + +This module provides an `http.Agent` implementation that connects to a specified +HTTP or HTTPS proxy server, and can be used with the built-in `https` module. + +Specifically, this `Agent` implementation connects to an intermediary "proxy" +server and issues the [CONNECT HTTP method][CONNECT], which tells the proxy to +open a direct TCP connection to the destination server. + +Since this agent implements the CONNECT HTTP method, it also works with other +protocols that use this method when connecting over proxies (i.e. WebSockets). +See the "Examples" section below for more. + +Examples +-------- + +#### `https` module example + +```ts +import * as https from 'https'; +import { HttpsProxyAgent } from 'https-proxy-agent'; + +const agent = new HttpsProxyAgent('http://168.63.76.32:3128'); + +https.get('https://example.com', { agent }, (res) => { + console.log('"response" event!', res.headers); + res.pipe(process.stdout); +}); +``` + +#### `ws` WebSocket connection example + +```ts +import WebSocket from 'ws'; +import { HttpsProxyAgent } from 'https-proxy-agent'; + +const agent = new HttpsProxyAgent('http://168.63.76.32:3128'); +const socket = new WebSocket('ws://echo.websocket.org', { agent }); + +socket.on('open', function () { + console.log('"open" event!'); + socket.send('hello world'); +}); + +socket.on('message', function (data, flags) { + console.log('"message" event! %j %j', data, flags); + socket.close(); +}); +``` + +API +--- + +### new HttpsProxyAgent(proxy: string | URL, options?: HttpsProxyAgentOptions) + +The `HttpsProxyAgent` class implements an `http.Agent` subclass that connects +to the specified "HTTP(s) proxy server" in order to proxy HTTPS and/or WebSocket +requests. This is achieved by using the [HTTP `CONNECT` method][CONNECT]. + +The `proxy` argument is the URL for the proxy server. + +The `options` argument accepts the usual `http.Agent` constructor options, and +some additional properties: + + * `headers` - Object containing additional headers to send to the proxy server + in the `CONNECT` request. + +[CONNECT]: http://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_Tunneling diff --git a/node_modules/https-proxy-agent/dist/index.d.ts b/node_modules/https-proxy-agent/dist/index.d.ts new file mode 100644 index 0000000..8cd1151 --- /dev/null +++ b/node_modules/https-proxy-agent/dist/index.d.ts @@ -0,0 +1,47 @@ +/// +/// +/// +/// +import * as net from 'net'; +import * as tls from 'tls'; +import * as http from 'http'; +import { Agent, AgentConnectOpts } from 'agent-base'; +import { URL } from 'url'; +import type { OutgoingHttpHeaders } from 'http'; +type Protocol = T extends `${infer Protocol}:${infer _}` ? Protocol : never; +type ConnectOptsMap = { + http: Omit; + https: Omit; +}; +type ConnectOpts = { + [P in keyof ConnectOptsMap]: Protocol extends P ? ConnectOptsMap[P] : never; +}[keyof ConnectOptsMap]; +export type HttpsProxyAgentOptions = ConnectOpts & http.AgentOptions & { + headers?: OutgoingHttpHeaders | (() => OutgoingHttpHeaders); +}; +/** + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. + * + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. + */ +export declare class HttpsProxyAgent extends Agent { + static protocols: readonly ["http", "https"]; + readonly proxy: URL; + proxyHeaders: OutgoingHttpHeaders | (() => OutgoingHttpHeaders); + connectOpts: net.TcpNetConnectOpts & tls.ConnectionOptions; + constructor(proxy: Uri | URL, opts?: HttpsProxyAgentOptions); + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + */ + connect(req: http.ClientRequest, opts: AgentConnectOpts): Promise; +} +export {}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/https-proxy-agent/dist/index.d.ts.map b/node_modules/https-proxy-agent/dist/index.d.ts.map new file mode 100644 index 0000000..c23c3a0 --- /dev/null +++ b/node_modules/https-proxy-agent/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;AAAA,OAAO,KAAK,GAAG,MAAM,KAAK,CAAC;AAC3B,OAAO,KAAK,GAAG,MAAM,KAAK,CAAC;AAC3B,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAG7B,OAAO,EAAE,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC;AAE1B,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,MAAM,CAAC;AAuBhD,KAAK,QAAQ,CAAC,CAAC,IAAI,CAAC,S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js b/node_modules/https-proxy-agent/dist/index.js new file mode 100644 index 0000000..1857f46 --- /dev/null +++ b/node_modules/https-proxy-agent/dist/index.js @@ -0,0 +1,180 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HttpsProxyAgent = void 0; +const net = __importStar(require("net")); +const tls = __importStar(require("tls")); +const assert_1 = __importDefault(require("assert")); +const debug_1 = __importDefault(require("debug")); +const agent_base_1 = require("agent-base"); +const url_1 = require("url"); +const parse_proxy_response_1 = require("./parse-proxy-response"); +const debug = (0, debug_1.default)('https-proxy-agent'); +const setServernameFromNonIpHost = (options) => { + if (options.servername === undefined && + options.host && + !net.isIP(options.host)) { + return { + ...options, + servername: options.host, + }; + } + return options; +}; +/** + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. + * + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. + */ +class HttpsProxyAgent extends agent_base_1.Agent { + constructor(proxy, opts) { + super(opts); + this.options = { path: undefined }; + this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href); + // Trim off the brackets from IPv6 addresses + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); + const port = this.proxy.port + ? parseInt(this.proxy.port, 10) + : this.proxy.protocol === 'https:' + ? 443 + : 80; + this.connectOpts = { + // Attempt to negotiate http/1.1 for proxy servers that support http/2 + ALPNProtocols: ['http/1.1'], + ...(opts ? omit(opts, 'headers') : null), + host, + port, + }; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + */ + async connect(req, opts) { + const { proxy } = this; + if (!opts.host) { + throw new TypeError('No "host" provided'); + } + // Create a socket connection to the proxy server. + let socket; + if (proxy.protocol === 'https:') { + debug('Creating `tls.Socket`: %o', this.connectOpts); + socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); + } + else { + debug('Creating `net.Socket`: %o', this.connectOpts); + socket = net.connect(this.connectOpts); + } + const headers = typeof this.proxyHeaders === 'function' + ? this.proxyHeaders() + : { ...this.proxyHeaders }; + const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; + let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`; + // Inject the `Proxy-Authorization` header if necessary. + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; + } + headers.Host = `${host}:${opts.port}`; + if (!headers['Proxy-Connection']) { + headers['Proxy-Connection'] = this.keepAlive + ? 'Keep-Alive' + : 'close'; + } + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r\n`; + } + const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); + socket.write(`${payload}\r\n`); + const { connect, buffered } = await proxyResponsePromise; + req.emit('proxyConnect', connect); + this.emit('proxyConnect', connect, req); + if (connect.statusCode === 200) { + req.once('socket', resume); + if (opts.secureEndpoint) { + // The proxy is connecting to a TLS server, so upgrade + // this socket connection to a TLS connection. + debug('Upgrading socket connection to TLS'); + return tls.connect({ + ...omit(setServernameFromNonIpHost(opts), 'host', 'path', 'port'), + socket, + }); + } + return socket; + } + // Some other status code that's not 200... need to re-play the HTTP + // header "data" events onto the socket once the HTTP machinery is + // attached so that the node core `http` can parse and handle the + // error status code. + // Close the original socket, and a new "fake" socket is returned + // instead, so that the proxy doesn't get the HTTP request + // written to it (which may contain `Authorization` headers or other + // sensitive data). + // + // See: https://hackerone.com/reports/541502 + socket.destroy(); + const fakeSocket = new net.Socket({ writable: false }); + fakeSocket.readable = true; + // Need to wait for the "socket" event to re-play the "data" events. + req.once('socket', (s) => { + debug('Replaying proxy buffer for failed request'); + (0, assert_1.default)(s.listenerCount('data') > 0); + // Replay the "buffered" Buffer onto the fake `socket`, since at + // this point the HTTP module machinery has been hooked up for + // the user. + s.push(buffered); + s.push(null); + }); + return fakeSocket; + } +} +HttpsProxyAgent.protocols = ['http', 'https']; +exports.HttpsProxyAgent = HttpsProxyAgent; +function resume(socket) { + socket.resume(); +} +function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/https-proxy-agent/dist/index.js.map b/node_modules/https-proxy-agent/dist/index.js.map new file mode 100644 index 0000000..ea7d2f3 --- /dev/null +++ b/node_modules/https-proxy-agent/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yCAA2B;AAC3B,yCAA2B;AAE3B,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AAI,CACZ,GAAM,EACN,GAAG,IAAO;IAIV,MAAM,GAAG,GAAG,EAEX,CAAC;IACF,IAAI,GAAqB,CAAC;IAC1B,KAAK,GAAG,IAAI,GAAG,EAAE;QAChB,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;YACxB,GAAG,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;SACpB;KACD;IACD,OAAO,GAAG,CAAC;AACZ,CAAC"} \ No newline at end of file diff --git a/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts b/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts new file mode 100644 index 0000000..84d5a9c --- /dev/null +++ b/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts @@ -0,0 +1,15 @@ +/// +/// +/// +import { IncomingHttpHeaders } from 'http'; +import { Readable } from 'stream'; +export interface ConnectResponse { + statusCode: number; + statusText: string; + headers: IncomingHttpHeaders; +} +export declare function parseProxyResponse(socket: Readable): Promise<{ + connect: ConnectResponse; + buffered: Buffer; +}>; +//# sourceMappingURL=parse-proxy-response.d.ts.map \ No newline at end of file diff --git a/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts.map b/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts.map new file mode 100644 index 0000000..414df55 --- /dev/null +++ b/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parse-proxy-response.d.ts","sourceRoot":"","sources":["../src/parse-proxy-response.ts"],"names":[],"mappings":";;;AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,MAAM,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAIlC,MAAM,WAAW,eAAe;IAC/B,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,mBAAmB,CAAC;CAC7B;AAED,wBAAgB,kBAAkB,CACjC,MAAM,EAAE,QAAQ,GACd,OAAO,CAAC;IAAE,OAAO,EAAE,eAAe,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC,CAyGzD"} \ No newline at end of file diff --git a/node_modules/https-proxy-agent/dist/parse-proxy-response.js b/node_modules/https-proxy-agent/dist/parse-proxy-response.js new file mode 100644 index 0000000..d3f506f --- /dev/null +++ b/node_modules/https-proxy-agent/dist/parse-proxy-response.js @@ -0,0 +1,101 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseProxyResponse = void 0; +const debug_1 = __importDefault(require("debug")); +const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response'); +function parseProxyResponse(socket) { + return new Promise((resolve, reject) => { + // we need to buffer any HTTP traffic that happens with the proxy before we get + // the CONNECT response, so that if the response is anything other than an "200" + // response code, then we can re-play the "data" events on the socket once the + // HTTP parser is hooked up... + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once('readable', read); + } + function cleanup() { + socket.removeListener('end', onend); + socket.removeListener('error', onerror); + socket.removeListener('readable', read); + } + function onend() { + cleanup(); + debug('onend'); + reject(new Error('Proxy connection ended before receiving CONNECT response')); + } + function onerror(err) { + cleanup(); + debug('onerror %o', err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf('\r\n\r\n'); + if (endOfHeaders === -1) { + // keep buffering + debug('have not received end of HTTP headers yet...'); + read(); + return; + } + const headerParts = buffered + .slice(0, endOfHeaders) + .toString('ascii') + .split('\r\n'); + const firstLine = headerParts.shift(); + if (!firstLine) { + socket.destroy(); + return reject(new Error('No header received from proxy CONNECT response')); + } + const firstLineParts = firstLine.split(' '); + const statusCode = +firstLineParts[1]; + const statusText = firstLineParts.slice(2).join(' '); + const headers = {}; + for (const header of headerParts) { + if (!header) + continue; + const firstColon = header.indexOf(':'); + if (firstColon === -1) { + socket.destroy(); + return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); + } + const key = header.slice(0, firstColon).toLowerCase(); + const value = header.slice(firstColon + 1).trimStart(); + const current = headers[key]; + if (typeof current === 'string') { + headers[key] = [current, value]; + } + else if (Array.isArray(current)) { + current.push(value); + } + else { + headers[key] = value; + } + } + debug('got proxy server response: %o %o', firstLine, headers); + cleanup(); + resolve({ + connect: { + statusCode, + statusText, + headers, + }, + buffered, + }); + } + socket.on('error', onerror); + socket.on('end', onend); + read(); + }); +} +exports.parseProxyResponse = parseProxyResponse; +//# sourceMappingURL=parse-proxy-response.js.map \ No newline at end of file diff --git a/node_modules/https-proxy-agent/dist/parse-proxy-response.js.map b/node_modules/https-proxy-agent/dist/parse-proxy-response.js.map new file mode 100644 index 0000000..71b58bb --- /dev/null +++ b/node_modules/https-proxy-agent/dist/parse-proxy-response.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parse-proxy-response.js","sourceRoot":"","sources":["../src/parse-proxy-response.ts"],"names":[],"mappings":";;;;;;AAAA,kDAAgC;AAIhC,MAAM,KAAK,GAAG,IAAA,eAAW,EAAC,wCAAwC,CAAC,CAAC;AAQpE,SAAgB,kBAAkB,CACjC,MAAgB;IAEhB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACtC,+EAA+E;QAC/E,gFAAgF;QAChF,8EAA8E;QAC9E,8BAA8B;QAC9B,IAAI,aAAa,GAAG,CAAC,CAAC;QACtB,MAAM,OAAO,GAAa,EAAE,CAAC;QAE7B,SAAS,IAAI;YACZ,MAAM,CAAC,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC;YACxB,IAAI,CAAC;gBAAE,MAAM,CAAC,CAAC,CAAC,CAAC;;gBACZ,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;QACpC,CAAC;QAED,SAAS,OAAO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gBACP,OAAO,EAAE;oBACR,UAAU;oBACV,UAAU;oBACV,OAAO;iBACP;gBACD,QAAQ;aACR,CAAC,CAAC;QACJ,CAAC;QAED,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC5B,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QAExB,IAAI,EAAE,CAAC;IACR,CAAC,CAAC,CAAC;AACJ,CAAC;AA3GD,gDA2GC"} \ No newline at end of file diff --git a/node_modules/https-proxy-agent/package.json b/node_modules/https-proxy-agent/package.json new file mode 100644 index 0000000..51b7e11 --- /dev/null +++ b/node_modules/https-proxy-agent/package.json @@ -0,0 +1,50 @@ +{ + "name": "https-proxy-agent", + "version": "7.0.6", + "description": "An HTTP(s) proxy `http.Agent` implementation for HTTPS", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "repository": { + "type": "git", + "url": "https://github.com/TooTallNate/proxy-agents.git", + "directory": "packages/https-proxy-agent" + }, + "keywords": [ + "https", + "proxy", + "endpoint", + "agent" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "devDependencies": { + "@types/async-retry": "^1.4.5", + "@types/debug": "4", + "@types/jest": "^29.5.1", + "@types/node": "^14.18.45", + "async-listen": "^3.0.0", + "async-retry": "^1.3.3", + "jest": "^29.5.0", + "ts-jest": "^29.1.0", + "typescript": "^5.0.4", + "proxy": "2.2.0", + "tsconfig": "0.0.0" + }, + "engines": { + "node": ">= 14" + }, + "scripts": { + "build": "tsc", + "test": "jest --env node --verbose --bail test/test.ts", + "test-e2e": "jest --env node --verbose --bail test/e2e.test.ts", + "lint": "eslint --ext .ts", + "pack": "node ../../scripts/pack.mjs" + } +} \ No newline at end of file diff --git a/node_modules/inherits/LICENSE b/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/inherits/README.md b/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/inherits/inherits.js b/node_modules/inherits/inherits.js new file mode 100644 index 0000000..f71f2d9 --- /dev/null +++ b/node_modules/inherits/inherits.js @@ -0,0 +1,9 @@ +try { + var util = require('util'); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = require('./inherits_browser.js'); +} diff --git a/node_modules/inherits/inherits_browser.js b/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..86bbb3d --- /dev/null +++ b/node_modules/inherits/inherits_browser.js @@ -0,0 +1,27 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} diff --git a/node_modules/inherits/package.json b/node_modules/inherits/package.json new file mode 100644 index 0000000..37b4366 --- /dev/null +++ b/node_modules/inherits/package.json @@ -0,0 +1,29 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.4", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": "git://github.com/isaacs/inherits", + "license": "ISC", + "scripts": { + "test": "tap" + }, + "devDependencies": { + "tap": "^14.2.4" + }, + "files": [ + "inherits.js", + "inherits_browser.js" + ] +} diff --git a/node_modules/is-fullwidth-code-point/index.d.ts b/node_modules/is-fullwidth-code-point/index.d.ts new file mode 100644 index 0000000..729d202 --- /dev/null +++ b/node_modules/is-fullwidth-code-point/index.d.ts @@ -0,0 +1,17 @@ +/** +Check if the character represented by a given [Unicode code point](https://en.wikipedia.org/wiki/Code_point) is [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms). + +@param codePoint - The [code point](https://en.wikipedia.org/wiki/Code_point) of a character. + +@example +``` +import isFullwidthCodePoint from 'is-fullwidth-code-point'; + +isFullwidthCodePoint('谢'.codePointAt(0)); +//=> true + +isFullwidthCodePoint('a'.codePointAt(0)); +//=> false +``` +*/ +export default function isFullwidthCodePoint(codePoint: number): boolean; diff --git a/node_modules/is-fullwidth-code-point/index.js b/node_modules/is-fullwidth-code-point/index.js new file mode 100644 index 0000000..671f97f --- /dev/null +++ b/node_modules/is-fullwidth-code-point/index.js @@ -0,0 +1,50 @@ +/* eslint-disable yoda */ +'use strict'; + +const isFullwidthCodePoint = codePoint => { + if (Number.isNaN(codePoint)) { + return false; + } + + // Code points are derived from: + // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt + if ( + codePoint >= 0x1100 && ( + codePoint <= 0x115F || // Hangul Jamo + codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET + codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || + // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + (0x3250 <= codePoint && codePoint <= 0x4DBF) || + // CJK Unified Ideographs .. Yi Radicals + (0x4E00 <= codePoint && codePoint <= 0xA4C6) || + // Hangul Jamo Extended-A + (0xA960 <= codePoint && codePoint <= 0xA97C) || + // Hangul Syllables + (0xAC00 <= codePoint && codePoint <= 0xD7A3) || + // CJK Compatibility Ideographs + (0xF900 <= codePoint && codePoint <= 0xFAFF) || + // Vertical Forms + (0xFE10 <= codePoint && codePoint <= 0xFE19) || + // CJK Compatibility Forms .. Small Form Variants + (0xFE30 <= codePoint && codePoint <= 0xFE6B) || + // Halfwidth and Fullwidth Forms + (0xFF01 <= codePoint && codePoint <= 0xFF60) || + (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || + // Kana Supplement + (0x1B000 <= codePoint && codePoint <= 0x1B001) || + // Enclosed Ideographic Supplement + (0x1F200 <= codePoint && codePoint <= 0x1F251) || + // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + (0x20000 <= codePoint && codePoint <= 0x3FFFD) + ) + ) { + return true; + } + + return false; +}; + +module.exports = isFullwidthCodePoint; +module.exports.default = isFullwidthCodePoint; diff --git a/node_modules/is-fullwidth-code-point/license b/node_modules/is-fullwidth-code-point/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/is-fullwidth-code-point/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/is-fullwidth-code-point/package.json b/node_modules/is-fullwidth-code-point/package.json new file mode 100644 index 0000000..2137e88 --- /dev/null +++ b/node_modules/is-fullwidth-code-point/package.json @@ -0,0 +1,42 @@ +{ + "name": "is-fullwidth-code-point", + "version": "3.0.0", + "description": "Check if the character represented by a given Unicode code point is fullwidth", + "license": "MIT", + "repository": "sindresorhus/is-fullwidth-code-point", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd-check" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "fullwidth", + "full-width", + "full", + "width", + "unicode", + "character", + "string", + "codepoint", + "code", + "point", + "is", + "detect", + "check" + ], + "devDependencies": { + "ava": "^1.3.1", + "tsd-check": "^0.5.0", + "xo": "^0.24.0" + } +} diff --git a/node_modules/is-fullwidth-code-point/readme.md b/node_modules/is-fullwidth-code-point/readme.md new file mode 100644 index 0000000..4236bba --- /dev/null +++ b/node_modules/is-fullwidth-code-point/readme.md @@ -0,0 +1,39 @@ +# is-fullwidth-code-point [![Build Status](https://travis-ci.org/sindresorhus/is-fullwidth-code-point.svg?branch=master)](https://travis-ci.org/sindresorhus/is-fullwidth-code-point) + +> Check if the character represented by a given [Unicode code point](https://en.wikipedia.org/wiki/Code_point) is [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) + + +## Install + +``` +$ npm install is-fullwidth-code-point +``` + + +## Usage + +```js +const isFullwidthCodePoint = require('is-fullwidth-code-point'); + +isFullwidthCodePoint('谢'.codePointAt(0)); +//=> true + +isFullwidthCodePoint('a'.codePointAt(0)); +//=> false +``` + + +## API + +### isFullwidthCodePoint(codePoint) + +#### codePoint + +Type: `number` + +The [code point](https://en.wikipedia.org/wiki/Code_point) of a character. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/is-stream/index.d.ts b/node_modules/is-stream/index.d.ts new file mode 100644 index 0000000..eee2e83 --- /dev/null +++ b/node_modules/is-stream/index.d.ts @@ -0,0 +1,79 @@ +import * as stream from 'stream'; + +declare const isStream: { + /** + @returns Whether `stream` is a [`Stream`](https://nodejs.org/api/stream.html#stream_stream). + + @example + ``` + import * as fs from 'fs'; + import isStream = require('is-stream'); + + isStream(fs.createReadStream('unicorn.png')); + //=> true + + isStream({}); + //=> false + ``` + */ + (stream: unknown): stream is stream.Stream; + + /** + @returns Whether `stream` is a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable). + + @example + ``` + import * as fs from 'fs'; + import isStream = require('is-stream'); + + isStream.writable(fs.createWriteStrem('unicorn.txt')); + //=> true + ``` + */ + writable(stream: unknown): stream is stream.Writable; + + /** + @returns Whether `stream` is a [`stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable). + + @example + ``` + import * as fs from 'fs'; + import isStream = require('is-stream'); + + isStream.readable(fs.createReadStream('unicorn.png')); + //=> true + ``` + */ + readable(stream: unknown): stream is stream.Readable; + + /** + @returns Whether `stream` is a [`stream.Duplex`](https://nodejs.org/api/stream.html#stream_class_stream_duplex). + + @example + ``` + import {Duplex} from 'stream'; + import isStream = require('is-stream'); + + isStream.duplex(new Duplex()); + //=> true + ``` + */ + duplex(stream: unknown): stream is stream.Duplex; + + /** + @returns Whether `stream` is a [`stream.Transform`](https://nodejs.org/api/stream.html#stream_class_stream_transform). + + @example + ``` + import * as fs from 'fs'; + import Stringify = require('streaming-json-stringify'); + import isStream = require('is-stream'); + + isStream.transform(Stringify()); + //=> true + ``` + */ + transform(input: unknown): input is stream.Transform; +}; + +export = isStream; diff --git a/node_modules/is-stream/index.js b/node_modules/is-stream/index.js new file mode 100644 index 0000000..2e43434 --- /dev/null +++ b/node_modules/is-stream/index.js @@ -0,0 +1,28 @@ +'use strict'; + +const isStream = stream => + stream !== null && + typeof stream === 'object' && + typeof stream.pipe === 'function'; + +isStream.writable = stream => + isStream(stream) && + stream.writable !== false && + typeof stream._write === 'function' && + typeof stream._writableState === 'object'; + +isStream.readable = stream => + isStream(stream) && + stream.readable !== false && + typeof stream._read === 'function' && + typeof stream._readableState === 'object'; + +isStream.duplex = stream => + isStream.writable(stream) && + isStream.readable(stream); + +isStream.transform = stream => + isStream.duplex(stream) && + typeof stream._transform === 'function'; + +module.exports = isStream; diff --git a/node_modules/is-stream/license b/node_modules/is-stream/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/is-stream/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/is-stream/package.json b/node_modules/is-stream/package.json new file mode 100644 index 0000000..c3b5673 --- /dev/null +++ b/node_modules/is-stream/package.json @@ -0,0 +1,42 @@ +{ + "name": "is-stream", + "version": "2.0.1", + "description": "Check if something is a Node.js stream", + "license": "MIT", + "repository": "sindresorhus/is-stream", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "stream", + "type", + "streams", + "writable", + "readable", + "duplex", + "transform", + "check", + "detect", + "is" + ], + "devDependencies": { + "@types/node": "^11.13.6", + "ava": "^1.4.1", + "tempy": "^0.3.0", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/is-stream/readme.md b/node_modules/is-stream/readme.md new file mode 100644 index 0000000..19308e7 --- /dev/null +++ b/node_modules/is-stream/readme.md @@ -0,0 +1,60 @@ +# is-stream + +> Check if something is a [Node.js stream](https://nodejs.org/api/stream.html) + +## Install + +``` +$ npm install is-stream +``` + +## Usage + +```js +const fs = require('fs'); +const isStream = require('is-stream'); + +isStream(fs.createReadStream('unicorn.png')); +//=> true + +isStream({}); +//=> false +``` + +## API + +### isStream(stream) + +Returns a `boolean` for whether it's a [`Stream`](https://nodejs.org/api/stream.html#stream_stream). + +#### isStream.writable(stream) + +Returns a `boolean` for whether it's a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable). + +#### isStream.readable(stream) + +Returns a `boolean` for whether it's a [`stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable). + +#### isStream.duplex(stream) + +Returns a `boolean` for whether it's a [`stream.Duplex`](https://nodejs.org/api/stream.html#stream_class_stream_duplex). + +#### isStream.transform(stream) + +Returns a `boolean` for whether it's a [`stream.Transform`](https://nodejs.org/api/stream.html#stream_class_stream_transform). + +## Related + +- [is-file-stream](https://github.com/jamestalmage/is-file-stream) - Detect if a stream is a file stream + +--- + +
                          + + Get professional support for this package with a Tidelift subscription + +
                          + + Tidelift helps make open source sustainable for maintainers while giving companies
                          assurances about security, maintenance, and licensing for their dependencies. +
                          +
                          diff --git a/node_modules/jose/LICENSE.md b/node_modules/jose/LICENSE.md new file mode 100644 index 0000000..d0ec038 --- /dev/null +++ b/node_modules/jose/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018 Filip Skokan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jose/README.md b/node_modules/jose/README.md new file mode 100644 index 0000000..1ab05b6 --- /dev/null +++ b/node_modules/jose/README.md @@ -0,0 +1,132 @@ +# jose + +`jose` is JavaScript module for JSON Object Signing and Encryption, providing support for JSON Web Tokens (JWT), JSON Web Signature (JWS), JSON Web Encryption (JWE), JSON Web Key (JWK), JSON Web Key Set (JWKS), and more. The module is designed to work across various Web-interoperable runtimes including Node.js, browsers, Cloudflare Workers, Deno, Bun, and others. + +## [💗 Help the project](https://github.com/sponsors/panva) + +Support from the community to continue maintaining and improving this module is welcome. If you find the module useful, please consider supporting the project by [becoming a sponsor](https://github.com/sponsors/panva). + +## Dependencies: 0 + +`jose` has no dependencies and it exports tree-shakeable ESM. CJS is also supported. + +## Documentation + +`jose` is distributed via [npmjs.com](https://www.npmjs.com/package/jose), [deno.land/x](https://deno.land/x/jose), [cdnjs.com](https://cdnjs.com/libraries/jose), [jsdelivr.com](https://www.jsdelivr.com/package/npm/jose), and [github.com](https://github.com/panva/jose). + +**`example`** ESM import +```js +import * as jose from 'jose' +``` + +**`example`** CJS require +```js +const jose = require('jose') +``` + +### JSON Web Tokens (JWT) + +The `jose` module supports JSON Web Tokens (JWT) and provides functionality for signing and verifying tokens, as well as their JWT Claims Set validation. + +- [Signing](docs/classes/jwt_sign.SignJWT.md) using the `SignJWT` class +- [Verification & JWT Claims Set Validation](docs/functions/jwt_verify.jwtVerify.md) using the `jwtVerify` function + - [Using a remote JWKS](docs/functions/jwks_remote.createRemoteJWKSet.md) + - [Using a local JWKS](docs/functions/jwks_local.createLocalJWKSet.md) +- Utility functions + - [Decoding Token's Protected Header](docs/functions/util_decode_protected_header.decodeProtectedHeader.md) + - [Decoding JWT Claims Set](docs/functions/util_decode_jwt.decodeJwt.md) prior to its validation + +### Encrypted JSON Web Tokens + +The `jose` module supports encrypted JSON Web Tokens and provides functionality for encrypting and decrypting tokens, as well as their JWT Claims Set validation. + +- [Encryption](docs/classes/jwt_encrypt.EncryptJWT.md) using the `EncryptJWT` class +- [Decryption & JWT Claims Set Validation](docs/functions/jwt_decrypt.jwtDecrypt.md) using the `jwtDecrypt` function +- Utility functions + - [Decoding Token's Protected Header](docs/functions/util_decode_protected_header.decodeProtectedHeader.md) + +### Key Utilities + +The `jose` module supports importing, exporting, and generating keys and secrets in various formats, including PEM formats like SPKI, X.509 certificate, and PKCS #8, as well as JSON Web Key (JWK). + +- Key Import Functions + - [JWK Import](docs/functions/key_import.importJWK.md) + - [Public Key Import (SPKI)](docs/functions/key_import.importSPKI.md) + - [Public Key Import (X.509 Certificate)](docs/functions/key_import.importX509.md) + - [Private Key Import (PKCS #8)](docs/functions/key_import.importPKCS8.md) +- Key and Secret Generation Functions + - [Asymmetric Key Pair Generation](docs/functions/key_generate_key_pair.generateKeyPair.md) + - [Symmetric Secret Generation](docs/functions/key_generate_secret.generateSecret.md) +- Key Export Functions + - [JWK Export](docs/functions/key_export.exportJWK.md) + - [Private Key Export](docs/functions/key_export.exportPKCS8.md) + - [Public Key Export](docs/functions/key_export.exportSPKI.md) + +### JSON Web Signature (JWS) + +The `jose` module supports signing and verification of JWS messages with arbitrary payloads in Compact, Flattened JSON, and General JSON serialization syntaxes. + +- Signing - [Compact](docs/classes/jws_compact_sign.CompactSign.md), [Flattened JSON](docs/classes/jws_flattened_sign.FlattenedSign.md), [General JSON](docs/classes/jws_general_sign.GeneralSign.md) +- Verification - [Compact](docs/functions/jws_compact_verify.compactVerify.md), [Flattened JSON](docs/functions/jws_flattened_verify.flattenedVerify.md), [General JSON](docs/functions/jws_general_verify.generalVerify.md) + - [Verify using a remote JWKS](docs/functions/jwks_remote.createRemoteJWKSet.md) + - [Verify using a local JWKS](docs/functions/jwks_local.createLocalJWKSet.md) +- Utility functions + - [Decoding Token's Protected Header](docs/functions/util_decode_protected_header.decodeProtectedHeader.md) + +### JSON Web Encryption (JWE) + +The `jose` module supports encryption and decryption of JWE messages with arbitrary plaintext in Compact, Flattened JSON, and General JSON serialization syntaxes. + +- Encryption - [Compact](docs/classes/jwe_compact_encrypt.CompactEncrypt.md), [Flattened JSON](docs/classes/jwe_flattened_encrypt.FlattenedEncrypt.md), [General JSON](docs/classes/jwe_general_encrypt.GeneralEncrypt.md) +- Decryption - [Compact](docs/functions/jwe_compact_decrypt.compactDecrypt.md), [Flattened JSON](docs/functions/jwe_flattened_decrypt.flattenedDecrypt.md), [General JSON](docs/functions/jwe_general_decrypt.generalDecrypt.md) +- Utility functions + - [Decoding Token's Protected Header](docs/functions/util_decode_protected_header.decodeProtectedHeader.md) + +### Other + +The following are additional features and utilities provided by the `jose` module: + +- [Calculating JWK Thumbprint](docs/functions/jwk_thumbprint.calculateJwkThumbprint.md) +- [Calculating JWK Thumbprint URI](docs/functions/jwk_thumbprint.calculateJwkThumbprintUri.md) +- [Verification using a JWK Embedded in a JWS Header](docs/functions/jwk_embedded.EmbeddedJWK.md) +- [Unsecured JWT](docs/classes/jwt_unsecured.UnsecuredJWT.md) +- [JOSE Errors](docs/modules/util_errors.md) + +## Implemented specifications + +The `jose` module implements the following specifications: + +- JSON Web Signature (JWS) - [RFC7515](https://www.rfc-editor.org/rfc/rfc7515) +- JSON Web Encryption (JWE) - [RFC7516](https://www.rfc-editor.org/rfc/rfc7516) +- JSON Web Key (JWK) - [RFC7517](https://www.rfc-editor.org/rfc/rfc7517) +- JSON Web Algorithms (JWA) - [RFC7518](https://www.rfc-editor.org/rfc/rfc7518) +- JSON Web Token (JWT) - [RFC7519](https://www.rfc-editor.org/rfc/rfc7519) +- JSON Web Key Thumbprint - [RFC7638](https://www.rfc-editor.org/rfc/rfc7638) +- JSON Web Key Thumbprint URI - [RFC9278](https://www.rfc-editor.org/rfc/rfc9278) +- JWS Unencoded Payload Option - [RFC7797](https://www.rfc-editor.org/rfc/rfc7797) +- CFRG Elliptic Curve ECDH and Signatures - [RFC8037](https://www.rfc-editor.org/rfc/rfc8037) +- secp256k1 EC Key curve support - [RFC8812](https://www.rfc-editor.org/rfc/rfc8812) + +The algorithm implementations have been tested using test vectors from their respective specifications as well as [RFC7520](https://www.rfc-editor.org/rfc/rfc7520). + +## Supported Runtimes + +The `jose` module is compatible with JavaScript runtimes that support the utilized Web API globals and standard built-in objects or are Node.js. + +The following runtimes are supported _(this is not an exhaustive list)_: +- [Bun](https://github.com/panva/jose/issues/471) +- [Browsers](https://github.com/panva/jose/issues/263) +- [Cloudflare Workers](https://github.com/panva/jose/issues/265) +- [Deno](https://github.com/panva/jose/issues/266) +- [Electron](https://github.com/panva/jose/issues/264) +- [Node.js](https://github.com/panva/jose/issues/262) +- [Vercel's Edge Runtime](https://github.com/panva/jose/issues/301) + +Please note that certain algorithms may not be available depending on the runtime used. You can find a list of available algorithms for each runtime in the specific issue links provided above. + +## Supported Versions + +| Version | Security Fixes 🔑 | Other Bug Fixes 🐞 | New Features ⭐ | +| ------- | --------- | -------- | -------- | +| [v4.x](https://github.com/panva/jose/tree/v4.x) | ✅ | ✅ | ✅ | +| [v2.x](https://github.com/panva/jose/tree/v2.x) | ✅ | ❌ | ❌ | diff --git a/node_modules/jose/dist/browser/index.js b/node_modules/jose/dist/browser/index.js new file mode 100644 index 0000000..a31b3a2 --- /dev/null +++ b/node_modules/jose/dist/browser/index.js @@ -0,0 +1,32 @@ +export { compactDecrypt } from './jwe/compact/decrypt.js'; +export { flattenedDecrypt } from './jwe/flattened/decrypt.js'; +export { generalDecrypt } from './jwe/general/decrypt.js'; +export { GeneralEncrypt } from './jwe/general/encrypt.js'; +export { compactVerify } from './jws/compact/verify.js'; +export { flattenedVerify } from './jws/flattened/verify.js'; +export { generalVerify } from './jws/general/verify.js'; +export { jwtVerify } from './jwt/verify.js'; +export { jwtDecrypt } from './jwt/decrypt.js'; +export { CompactEncrypt } from './jwe/compact/encrypt.js'; +export { FlattenedEncrypt } from './jwe/flattened/encrypt.js'; +export { CompactSign } from './jws/compact/sign.js'; +export { FlattenedSign } from './jws/flattened/sign.js'; +export { GeneralSign } from './jws/general/sign.js'; +export { SignJWT } from './jwt/sign.js'; +export { EncryptJWT } from './jwt/encrypt.js'; +export { calculateJwkThumbprint, calculateJwkThumbprintUri } from './jwk/thumbprint.js'; +export { EmbeddedJWK } from './jwk/embedded.js'; +export { createLocalJWKSet } from './jwks/local.js'; +export { createRemoteJWKSet } from './jwks/remote.js'; +export { UnsecuredJWT } from './jwt/unsecured.js'; +export { exportPKCS8, exportSPKI, exportJWK } from './key/export.js'; +export { importSPKI, importPKCS8, importX509, importJWK } from './key/import.js'; +export { decodeProtectedHeader } from './util/decode_protected_header.js'; +export { decodeJwt } from './util/decode_jwt.js'; +import * as errors_1 from './util/errors.js'; +export { errors_1 as errors }; +export { generateKeyPair } from './key/generate_key_pair.js'; +export { generateSecret } from './key/generate_secret.js'; +import * as base64url_1 from './util/base64url.js'; +export { base64url_1 as base64url }; +export { default as cryptoRuntime } from './util/runtime.js'; diff --git a/node_modules/jose/dist/browser/jwe/compact/decrypt.js b/node_modules/jose/dist/browser/jwe/compact/decrypt.js new file mode 100644 index 0000000..129aeb6 --- /dev/null +++ b/node_modules/jose/dist/browser/jwe/compact/decrypt.js @@ -0,0 +1,27 @@ +import { flattenedDecrypt } from '../flattened/decrypt.js'; +import { JWEInvalid } from '../../util/errors.js'; +import { decoder } from '../../lib/buffer_utils.js'; +export async function compactDecrypt(jwe, key, options) { + if (jwe instanceof Uint8Array) { + jwe = decoder.decode(jwe); + } + if (typeof jwe !== 'string') { + throw new JWEInvalid('Compact JWE must be a string or Uint8Array'); + } + const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length, } = jwe.split('.'); + if (length !== 5) { + throw new JWEInvalid('Invalid Compact JWE'); + } + const decrypted = await flattenedDecrypt({ + ciphertext, + iv: (iv || undefined), + protected: protectedHeader || undefined, + tag: (tag || undefined), + encrypted_key: encryptedKey || undefined, + }, key, options); + const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; + if (typeof key === 'function') { + return { ...result, key: decrypted.key }; + } + return result; +} diff --git a/node_modules/jose/dist/browser/jwe/compact/encrypt.js b/node_modules/jose/dist/browser/jwe/compact/encrypt.js new file mode 100644 index 0000000..e689139 --- /dev/null +++ b/node_modules/jose/dist/browser/jwe/compact/encrypt.js @@ -0,0 +1,26 @@ +import { FlattenedEncrypt } from '../flattened/encrypt.js'; +export class CompactEncrypt { + constructor(plaintext) { + this._flattened = new FlattenedEncrypt(plaintext); + } + setContentEncryptionKey(cek) { + this._flattened.setContentEncryptionKey(cek); + return this; + } + setInitializationVector(iv) { + this._flattened.setInitializationVector(iv); + return this; + } + setProtectedHeader(protectedHeader) { + this._flattened.setProtectedHeader(protectedHeader); + return this; + } + setKeyManagementParameters(parameters) { + this._flattened.setKeyManagementParameters(parameters); + return this; + } + async encrypt(key, options) { + const jwe = await this._flattened.encrypt(key, options); + return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.'); + } +} diff --git a/node_modules/jose/dist/browser/jwe/flattened/decrypt.js b/node_modules/jose/dist/browser/jwe/flattened/decrypt.js new file mode 100644 index 0000000..3b1173c --- /dev/null +++ b/node_modules/jose/dist/browser/jwe/flattened/decrypt.js @@ -0,0 +1,166 @@ +import { decode as base64url } from '../../runtime/base64url.js'; +import decrypt from '../../runtime/decrypt.js'; +import { inflate } from '../../runtime/zlib.js'; +import { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from '../../util/errors.js'; +import isDisjoint from '../../lib/is_disjoint.js'; +import isObject from '../../lib/is_object.js'; +import decryptKeyManagement from '../../lib/decrypt_key_management.js'; +import { encoder, decoder, concat } from '../../lib/buffer_utils.js'; +import generateCek from '../../lib/cek.js'; +import validateCrit from '../../lib/validate_crit.js'; +import validateAlgorithms from '../../lib/validate_algorithms.js'; +export async function flattenedDecrypt(jwe, key, options) { + var _a; + if (!isObject(jwe)) { + throw new JWEInvalid('Flattened JWE must be an object'); + } + if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) { + throw new JWEInvalid('JOSE Header missing'); + } + if (typeof jwe.iv !== 'string') { + throw new JWEInvalid('JWE Initialization Vector missing or incorrect type'); + } + if (typeof jwe.ciphertext !== 'string') { + throw new JWEInvalid('JWE Ciphertext missing or incorrect type'); + } + if (typeof jwe.tag !== 'string') { + throw new JWEInvalid('JWE Authentication Tag missing or incorrect type'); + } + if (jwe.protected !== undefined && typeof jwe.protected !== 'string') { + throw new JWEInvalid('JWE Protected Header incorrect type'); + } + if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') { + throw new JWEInvalid('JWE Encrypted Key incorrect type'); + } + if (jwe.aad !== undefined && typeof jwe.aad !== 'string') { + throw new JWEInvalid('JWE AAD incorrect type'); + } + if (jwe.header !== undefined && !isObject(jwe.header)) { + throw new JWEInvalid('JWE Shared Unprotected Header incorrect type'); + } + if (jwe.unprotected !== undefined && !isObject(jwe.unprotected)) { + throw new JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type'); + } + let parsedProt; + if (jwe.protected) { + try { + const protectedHeader = base64url(jwe.protected); + parsedProt = JSON.parse(decoder.decode(protectedHeader)); + } + catch (_b) { + throw new JWEInvalid('JWE Protected Header is invalid'); + } + } + if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) { + throw new JWEInvalid('JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint'); + } + const joseHeader = { + ...parsedProt, + ...jwe.header, + ...jwe.unprotected, + }; + validateCrit(JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader); + if (joseHeader.zip !== undefined) { + if (!parsedProt || !parsedProt.zip) { + throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); + } + if (joseHeader.zip !== 'DEF') { + throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value'); + } + } + const { alg, enc } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new JWEInvalid('missing JWE Algorithm (alg) in JWE Header'); + } + if (typeof enc !== 'string' || !enc) { + throw new JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header'); + } + const keyManagementAlgorithms = options && validateAlgorithms('keyManagementAlgorithms', options.keyManagementAlgorithms); + const contentEncryptionAlgorithms = options && + validateAlgorithms('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms); + if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) { + throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed'); + } + if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) { + throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter not allowed'); + } + let encryptedKey; + if (jwe.encrypted_key !== undefined) { + try { + encryptedKey = base64url(jwe.encrypted_key); + } + catch (_c) { + throw new JWEInvalid('Failed to base64url decode the encrypted_key'); + } + } + let resolvedKey = false; + if (typeof key === 'function') { + key = await key(parsedProt, jwe); + resolvedKey = true; + } + let cek; + try { + cek = await decryptKeyManagement(alg, key, encryptedKey, joseHeader, options); + } + catch (err) { + if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) { + throw err; + } + cek = generateCek(enc); + } + let iv; + let tag; + try { + iv = base64url(jwe.iv); + } + catch (_d) { + throw new JWEInvalid('Failed to base64url decode the iv'); + } + try { + tag = base64url(jwe.tag); + } + catch (_e) { + throw new JWEInvalid('Failed to base64url decode the tag'); + } + const protectedHeader = encoder.encode((_a = jwe.protected) !== null && _a !== void 0 ? _a : ''); + let additionalData; + if (jwe.aad !== undefined) { + additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(jwe.aad)); + } + else { + additionalData = protectedHeader; + } + let ciphertext; + try { + ciphertext = base64url(jwe.ciphertext); + } + catch (_f) { + throw new JWEInvalid('Failed to base64url decode the ciphertext'); + } + let plaintext = await decrypt(enc, cek, ciphertext, iv, tag, additionalData); + if (joseHeader.zip === 'DEF') { + plaintext = await ((options === null || options === void 0 ? void 0 : options.inflateRaw) || inflate)(plaintext); + } + const result = { plaintext }; + if (jwe.protected !== undefined) { + result.protectedHeader = parsedProt; + } + if (jwe.aad !== undefined) { + try { + result.additionalAuthenticatedData = base64url(jwe.aad); + } + catch (_g) { + throw new JWEInvalid('Failed to base64url decode the aad'); + } + } + if (jwe.unprotected !== undefined) { + result.sharedUnprotectedHeader = jwe.unprotected; + } + if (jwe.header !== undefined) { + result.unprotectedHeader = jwe.header; + } + if (resolvedKey) { + return { ...result, key }; + } + return result; +} diff --git a/node_modules/jose/dist/browser/jwe/flattened/encrypt.js b/node_modules/jose/dist/browser/jwe/flattened/encrypt.js new file mode 100644 index 0000000..1e60ecd --- /dev/null +++ b/node_modules/jose/dist/browser/jwe/flattened/encrypt.js @@ -0,0 +1,175 @@ +import { encode as base64url } from '../../runtime/base64url.js'; +import encrypt from '../../runtime/encrypt.js'; +import { deflate } from '../../runtime/zlib.js'; +import generateIv from '../../lib/iv.js'; +import encryptKeyManagement from '../../lib/encrypt_key_management.js'; +import { JOSENotSupported, JWEInvalid } from '../../util/errors.js'; +import isDisjoint from '../../lib/is_disjoint.js'; +import { encoder, decoder, concat } from '../../lib/buffer_utils.js'; +import validateCrit from '../../lib/validate_crit.js'; +export const unprotected = Symbol(); +export class FlattenedEncrypt { + constructor(plaintext) { + if (!(plaintext instanceof Uint8Array)) { + throw new TypeError('plaintext must be an instance of Uint8Array'); + } + this._plaintext = plaintext; + } + setKeyManagementParameters(parameters) { + if (this._keyManagementParameters) { + throw new TypeError('setKeyManagementParameters can only be called once'); + } + this._keyManagementParameters = parameters; + return this; + } + setProtectedHeader(protectedHeader) { + if (this._protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this._protectedHeader = protectedHeader; + return this; + } + setSharedUnprotectedHeader(sharedUnprotectedHeader) { + if (this._sharedUnprotectedHeader) { + throw new TypeError('setSharedUnprotectedHeader can only be called once'); + } + this._sharedUnprotectedHeader = sharedUnprotectedHeader; + return this; + } + setUnprotectedHeader(unprotectedHeader) { + if (this._unprotectedHeader) { + throw new TypeError('setUnprotectedHeader can only be called once'); + } + this._unprotectedHeader = unprotectedHeader; + return this; + } + setAdditionalAuthenticatedData(aad) { + this._aad = aad; + return this; + } + setContentEncryptionKey(cek) { + if (this._cek) { + throw new TypeError('setContentEncryptionKey can only be called once'); + } + this._cek = cek; + return this; + } + setInitializationVector(iv) { + if (this._iv) { + throw new TypeError('setInitializationVector can only be called once'); + } + this._iv = iv; + return this; + } + async encrypt(key, options) { + if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) { + throw new JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()'); + } + if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) { + throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); + } + const joseHeader = { + ...this._protectedHeader, + ...this._unprotectedHeader, + ...this._sharedUnprotectedHeader, + }; + validateCrit(JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader); + if (joseHeader.zip !== undefined) { + if (!this._protectedHeader || !this._protectedHeader.zip) { + throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); + } + if (joseHeader.zip !== 'DEF') { + throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value'); + } + } + const { alg, enc } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); + } + if (typeof enc !== 'string' || !enc) { + throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); + } + let encryptedKey; + if (alg === 'dir') { + if (this._cek) { + throw new TypeError('setContentEncryptionKey cannot be called when using Direct Encryption'); + } + } + else if (alg === 'ECDH-ES') { + if (this._cek) { + throw new TypeError('setContentEncryptionKey cannot be called when using Direct Key Agreement'); + } + } + let cek; + { + let parameters; + ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, key, this._cek, this._keyManagementParameters)); + if (parameters) { + if (options && unprotected in options) { + if (!this._unprotectedHeader) { + this.setUnprotectedHeader(parameters); + } + else { + this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters }; + } + } + else { + if (!this._protectedHeader) { + this.setProtectedHeader(parameters); + } + else { + this._protectedHeader = { ...this._protectedHeader, ...parameters }; + } + } + } + } + this._iv || (this._iv = generateIv(enc)); + let additionalData; + let protectedHeader; + let aadMember; + if (this._protectedHeader) { + protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader))); + } + else { + protectedHeader = encoder.encode(''); + } + if (this._aad) { + aadMember = base64url(this._aad); + additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(aadMember)); + } + else { + additionalData = protectedHeader; + } + let ciphertext; + let tag; + if (joseHeader.zip === 'DEF') { + const deflated = await ((options === null || options === void 0 ? void 0 : options.deflateRaw) || deflate)(this._plaintext); + ({ ciphertext, tag } = await encrypt(enc, deflated, cek, this._iv, additionalData)); + } + else { + ; + ({ ciphertext, tag } = await encrypt(enc, this._plaintext, cek, this._iv, additionalData)); + } + const jwe = { + ciphertext: base64url(ciphertext), + iv: base64url(this._iv), + tag: base64url(tag), + }; + if (encryptedKey) { + jwe.encrypted_key = base64url(encryptedKey); + } + if (aadMember) { + jwe.aad = aadMember; + } + if (this._protectedHeader) { + jwe.protected = decoder.decode(protectedHeader); + } + if (this._sharedUnprotectedHeader) { + jwe.unprotected = this._sharedUnprotectedHeader; + } + if (this._unprotectedHeader) { + jwe.header = this._unprotectedHeader; + } + return jwe; + } +} diff --git a/node_modules/jose/dist/browser/jwe/general/decrypt.js b/node_modules/jose/dist/browser/jwe/general/decrypt.js new file mode 100644 index 0000000..d21b6d1 --- /dev/null +++ b/node_modules/jose/dist/browser/jwe/general/decrypt.js @@ -0,0 +1,31 @@ +import { flattenedDecrypt } from '../flattened/decrypt.js'; +import { JWEDecryptionFailed, JWEInvalid } from '../../util/errors.js'; +import isObject from '../../lib/is_object.js'; +export async function generalDecrypt(jwe, key, options) { + if (!isObject(jwe)) { + throw new JWEInvalid('General JWE must be an object'); + } + if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) { + throw new JWEInvalid('JWE Recipients missing or incorrect type'); + } + if (!jwe.recipients.length) { + throw new JWEInvalid('JWE Recipients has no members'); + } + for (const recipient of jwe.recipients) { + try { + return await flattenedDecrypt({ + aad: jwe.aad, + ciphertext: jwe.ciphertext, + encrypted_key: recipient.encrypted_key, + header: recipient.header, + iv: jwe.iv, + protected: jwe.protected, + tag: jwe.tag, + unprotected: jwe.unprotected, + }, key, options); + } + catch (_a) { + } + } + throw new JWEDecryptionFailed(); +} diff --git a/node_modules/jose/dist/browser/jwe/general/encrypt.js b/node_modules/jose/dist/browser/jwe/general/encrypt.js new file mode 100644 index 0000000..3ee53de --- /dev/null +++ b/node_modules/jose/dist/browser/jwe/general/encrypt.js @@ -0,0 +1,178 @@ +import { FlattenedEncrypt, unprotected } from '../flattened/encrypt.js'; +import { JWEInvalid } from '../../util/errors.js'; +import generateCek from '../../lib/cek.js'; +import isDisjoint from '../../lib/is_disjoint.js'; +import encryptKeyManagement from '../../lib/encrypt_key_management.js'; +import { encode as base64url } from '../../runtime/base64url.js'; +import validateCrit from '../../lib/validate_crit.js'; +class IndividualRecipient { + constructor(enc, key, options) { + this.parent = enc; + this.key = key; + this.options = options; + } + setUnprotectedHeader(unprotectedHeader) { + if (this.unprotectedHeader) { + throw new TypeError('setUnprotectedHeader can only be called once'); + } + this.unprotectedHeader = unprotectedHeader; + return this; + } + addRecipient(...args) { + return this.parent.addRecipient(...args); + } + encrypt(...args) { + return this.parent.encrypt(...args); + } + done() { + return this.parent; + } +} +export class GeneralEncrypt { + constructor(plaintext) { + this._recipients = []; + this._plaintext = plaintext; + } + addRecipient(key, options) { + const recipient = new IndividualRecipient(this, key, { crit: options === null || options === void 0 ? void 0 : options.crit }); + this._recipients.push(recipient); + return recipient; + } + setProtectedHeader(protectedHeader) { + if (this._protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this._protectedHeader = protectedHeader; + return this; + } + setSharedUnprotectedHeader(sharedUnprotectedHeader) { + if (this._unprotectedHeader) { + throw new TypeError('setSharedUnprotectedHeader can only be called once'); + } + this._unprotectedHeader = sharedUnprotectedHeader; + return this; + } + setAdditionalAuthenticatedData(aad) { + this._aad = aad; + return this; + } + async encrypt(options) { + var _a, _b, _c; + if (!this._recipients.length) { + throw new JWEInvalid('at least one recipient must be added'); + } + options = { deflateRaw: options === null || options === void 0 ? void 0 : options.deflateRaw }; + if (this._recipients.length === 1) { + const [recipient] = this._recipients; + const flattened = await new FlattenedEncrypt(this._plaintext) + .setAdditionalAuthenticatedData(this._aad) + .setProtectedHeader(this._protectedHeader) + .setSharedUnprotectedHeader(this._unprotectedHeader) + .setUnprotectedHeader(recipient.unprotectedHeader) + .encrypt(recipient.key, { ...recipient.options, ...options }); + let jwe = { + ciphertext: flattened.ciphertext, + iv: flattened.iv, + recipients: [{}], + tag: flattened.tag, + }; + if (flattened.aad) + jwe.aad = flattened.aad; + if (flattened.protected) + jwe.protected = flattened.protected; + if (flattened.unprotected) + jwe.unprotected = flattened.unprotected; + if (flattened.encrypted_key) + jwe.recipients[0].encrypted_key = flattened.encrypted_key; + if (flattened.header) + jwe.recipients[0].header = flattened.header; + return jwe; + } + let enc; + for (let i = 0; i < this._recipients.length; i++) { + const recipient = this._recipients[i]; + if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) { + throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); + } + const joseHeader = { + ...this._protectedHeader, + ...this._unprotectedHeader, + ...recipient.unprotectedHeader, + }; + const { alg } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); + } + if (alg === 'dir' || alg === 'ECDH-ES') { + throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient'); + } + if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) { + throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); + } + if (!enc) { + enc = joseHeader.enc; + } + else if (enc !== joseHeader.enc) { + throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients'); + } + validateCrit(JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader); + if (joseHeader.zip !== undefined) { + if (!this._protectedHeader || !this._protectedHeader.zip) { + throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); + } + } + } + const cek = generateCek(enc); + let jwe = { + ciphertext: '', + iv: '', + recipients: [], + tag: '', + }; + for (let i = 0; i < this._recipients.length; i++) { + const recipient = this._recipients[i]; + const target = {}; + jwe.recipients.push(target); + const joseHeader = { + ...this._protectedHeader, + ...this._unprotectedHeader, + ...recipient.unprotectedHeader, + }; + const p2c = joseHeader.alg.startsWith('PBES2') ? 2048 + i : undefined; + if (i === 0) { + const flattened = await new FlattenedEncrypt(this._plaintext) + .setAdditionalAuthenticatedData(this._aad) + .setContentEncryptionKey(cek) + .setProtectedHeader(this._protectedHeader) + .setSharedUnprotectedHeader(this._unprotectedHeader) + .setUnprotectedHeader(recipient.unprotectedHeader) + .setKeyManagementParameters({ p2c }) + .encrypt(recipient.key, { + ...recipient.options, + ...options, + [unprotected]: true, + }); + jwe.ciphertext = flattened.ciphertext; + jwe.iv = flattened.iv; + jwe.tag = flattened.tag; + if (flattened.aad) + jwe.aad = flattened.aad; + if (flattened.protected) + jwe.protected = flattened.protected; + if (flattened.unprotected) + jwe.unprotected = flattened.unprotected; + target.encrypted_key = flattened.encrypted_key; + if (flattened.header) + target.header = flattened.header; + continue; + } + const { encryptedKey, parameters } = await encryptKeyManagement(((_a = recipient.unprotectedHeader) === null || _a === void 0 ? void 0 : _a.alg) || + ((_b = this._protectedHeader) === null || _b === void 0 ? void 0 : _b.alg) || + ((_c = this._unprotectedHeader) === null || _c === void 0 ? void 0 : _c.alg), enc, recipient.key, cek, { p2c }); + target.encrypted_key = base64url(encryptedKey); + if (recipient.unprotectedHeader || parameters) + target.header = { ...recipient.unprotectedHeader, ...parameters }; + } + return jwe; + } +} diff --git a/node_modules/jose/dist/browser/jwk/embedded.js b/node_modules/jose/dist/browser/jwk/embedded.js new file mode 100644 index 0000000..561ae25 --- /dev/null +++ b/node_modules/jose/dist/browser/jwk/embedded.js @@ -0,0 +1,17 @@ +import { importJWK } from '../key/import.js'; +import isObject from '../lib/is_object.js'; +import { JWSInvalid } from '../util/errors.js'; +export async function EmbeddedJWK(protectedHeader, token) { + const joseHeader = { + ...protectedHeader, + ...token === null || token === void 0 ? void 0 : token.header, + }; + if (!isObject(joseHeader.jwk)) { + throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object'); + } + const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg, true); + if (key instanceof Uint8Array || key.type !== 'public') { + throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key'); + } + return key; +} diff --git a/node_modules/jose/dist/browser/jwk/thumbprint.js b/node_modules/jose/dist/browser/jwk/thumbprint.js new file mode 100644 index 0000000..49f86b1 --- /dev/null +++ b/node_modules/jose/dist/browser/jwk/thumbprint.js @@ -0,0 +1,53 @@ +import digest from '../runtime/digest.js'; +import { encode as base64url } from '../runtime/base64url.js'; +import { JOSENotSupported, JWKInvalid } from '../util/errors.js'; +import { encoder } from '../lib/buffer_utils.js'; +import isObject from '../lib/is_object.js'; +const check = (value, description) => { + if (typeof value !== 'string' || !value) { + throw new JWKInvalid(`${description} missing or invalid`); + } +}; +export async function calculateJwkThumbprint(jwk, digestAlgorithm) { + if (!isObject(jwk)) { + throw new TypeError('JWK must be an object'); + } + digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256'); + if (digestAlgorithm !== 'sha256' && + digestAlgorithm !== 'sha384' && + digestAlgorithm !== 'sha512') { + throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); + } + let components; + switch (jwk.kty) { + case 'EC': + check(jwk.crv, '"crv" (Curve) Parameter'); + check(jwk.x, '"x" (X Coordinate) Parameter'); + check(jwk.y, '"y" (Y Coordinate) Parameter'); + components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; + break; + case 'OKP': + check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); + check(jwk.x, '"x" (Public Key) Parameter'); + components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; + break; + case 'RSA': + check(jwk.e, '"e" (Exponent) Parameter'); + check(jwk.n, '"n" (Modulus) Parameter'); + components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; + break; + case 'oct': + check(jwk.k, '"k" (Key Value) Parameter'); + components = { k: jwk.k, kty: jwk.kty }; + break; + default: + throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); + } + const data = encoder.encode(JSON.stringify(components)); + return base64url(await digest(digestAlgorithm, data)); +} +export async function calculateJwkThumbprintUri(jwk, digestAlgorithm) { + digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256'); + const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm); + return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`; +} diff --git a/node_modules/jose/dist/browser/jwks/local.js b/node_modules/jose/dist/browser/jwks/local.js new file mode 100644 index 0000000..292aa27 --- /dev/null +++ b/node_modules/jose/dist/browser/jwks/local.js @@ -0,0 +1,116 @@ +import { importJWK } from '../key/import.js'; +import { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, } from '../util/errors.js'; +import isObject from '../lib/is_object.js'; +function getKtyFromAlg(alg) { + switch (typeof alg === 'string' && alg.slice(0, 2)) { + case 'RS': + case 'PS': + return 'RSA'; + case 'ES': + return 'EC'; + case 'Ed': + return 'OKP'; + default: + throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); + } +} +export function isJWKSLike(jwks) { + return (jwks && + typeof jwks === 'object' && + Array.isArray(jwks.keys) && + jwks.keys.every(isJWKLike)); +} +function isJWKLike(key) { + return isObject(key); +} +function clone(obj) { + if (typeof structuredClone === 'function') { + return structuredClone(obj); + } + return JSON.parse(JSON.stringify(obj)); +} +export class LocalJWKSet { + constructor(jwks) { + this._cached = new WeakMap(); + if (!isJWKSLike(jwks)) { + throw new JWKSInvalid('JSON Web Key Set malformed'); + } + this._jwks = clone(jwks); + } + async getKey(protectedHeader, token) { + const { alg, kid } = { ...protectedHeader, ...token === null || token === void 0 ? void 0 : token.header }; + const kty = getKtyFromAlg(alg); + const candidates = this._jwks.keys.filter((jwk) => { + let candidate = kty === jwk.kty; + if (candidate && typeof kid === 'string') { + candidate = kid === jwk.kid; + } + if (candidate && typeof jwk.alg === 'string') { + candidate = alg === jwk.alg; + } + if (candidate && typeof jwk.use === 'string') { + candidate = jwk.use === 'sig'; + } + if (candidate && Array.isArray(jwk.key_ops)) { + candidate = jwk.key_ops.includes('verify'); + } + if (candidate && alg === 'EdDSA') { + candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448'; + } + if (candidate) { + switch (alg) { + case 'ES256': + candidate = jwk.crv === 'P-256'; + break; + case 'ES256K': + candidate = jwk.crv === 'secp256k1'; + break; + case 'ES384': + candidate = jwk.crv === 'P-384'; + break; + case 'ES512': + candidate = jwk.crv === 'P-521'; + break; + } + } + return candidate; + }); + const { 0: jwk, length } = candidates; + if (length === 0) { + throw new JWKSNoMatchingKey(); + } + else if (length !== 1) { + const error = new JWKSMultipleMatchingKeys(); + const { _cached } = this; + error[Symbol.asyncIterator] = async function* () { + for (const jwk of candidates) { + try { + yield await importWithAlgCache(_cached, jwk, alg); + } + catch (_a) { + continue; + } + } + }; + throw error; + } + return importWithAlgCache(this._cached, jwk, alg); + } +} +async function importWithAlgCache(cache, jwk, alg) { + const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk); + if (cached[alg] === undefined) { + const key = await importJWK({ ...jwk, ext: true }, alg); + if (key instanceof Uint8Array || key.type !== 'public') { + throw new JWKSInvalid('JSON Web Key Set members must be public keys'); + } + cached[alg] = key; + } + return cached[alg]; +} +export function createLocalJWKSet(jwks) { + const set = new LocalJWKSet(jwks); + return async function (protectedHeader, token) { + return set.getKey(protectedHeader, token); + }; +} diff --git a/node_modules/jose/dist/browser/jwks/remote.js b/node_modules/jose/dist/browser/jwks/remote.js new file mode 100644 index 0000000..405f753 --- /dev/null +++ b/node_modules/jose/dist/browser/jwks/remote.js @@ -0,0 +1,76 @@ +import fetchJwks from '../runtime/fetch_jwks.js'; +import { JWKSInvalid, JWKSNoMatchingKey } from '../util/errors.js'; +import { isJWKSLike, LocalJWKSet } from './local.js'; +function isCloudflareWorkers() { + return (typeof WebSocketPair !== 'undefined' || + (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') || + (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel')); +} +class RemoteJWKSet extends LocalJWKSet { + constructor(url, options) { + super({ keys: [] }); + this._jwks = undefined; + if (!(url instanceof URL)) { + throw new TypeError('url must be an instance of URL'); + } + this._url = new URL(url.href); + this._options = { agent: options === null || options === void 0 ? void 0 : options.agent, headers: options === null || options === void 0 ? void 0 : options.headers }; + this._timeoutDuration = + typeof (options === null || options === void 0 ? void 0 : options.timeoutDuration) === 'number' ? options === null || options === void 0 ? void 0 : options.timeoutDuration : 5000; + this._cooldownDuration = + typeof (options === null || options === void 0 ? void 0 : options.cooldownDuration) === 'number' ? options === null || options === void 0 ? void 0 : options.cooldownDuration : 30000; + this._cacheMaxAge = typeof (options === null || options === void 0 ? void 0 : options.cacheMaxAge) === 'number' ? options === null || options === void 0 ? void 0 : options.cacheMaxAge : 600000; + } + coolingDown() { + return typeof this._jwksTimestamp === 'number' + ? Date.now() < this._jwksTimestamp + this._cooldownDuration + : false; + } + fresh() { + return typeof this._jwksTimestamp === 'number' + ? Date.now() < this._jwksTimestamp + this._cacheMaxAge + : false; + } + async getKey(protectedHeader, token) { + if (!this._jwks || !this.fresh()) { + await this.reload(); + } + try { + return await super.getKey(protectedHeader, token); + } + catch (err) { + if (err instanceof JWKSNoMatchingKey) { + if (this.coolingDown() === false) { + await this.reload(); + return super.getKey(protectedHeader, token); + } + } + throw err; + } + } + async reload() { + if (this._pendingFetch && isCloudflareWorkers()) { + this._pendingFetch = undefined; + } + this._pendingFetch || (this._pendingFetch = fetchJwks(this._url, this._timeoutDuration, this._options) + .then((json) => { + if (!isJWKSLike(json)) { + throw new JWKSInvalid('JSON Web Key Set malformed'); + } + this._jwks = { keys: json.keys }; + this._jwksTimestamp = Date.now(); + this._pendingFetch = undefined; + }) + .catch((err) => { + this._pendingFetch = undefined; + throw err; + })); + await this._pendingFetch; + } +} +export function createRemoteJWKSet(url, options) { + const set = new RemoteJWKSet(url, options); + return async function (protectedHeader, token) { + return set.getKey(protectedHeader, token); + }; +} diff --git a/node_modules/jose/dist/browser/jws/compact/sign.js b/node_modules/jose/dist/browser/jws/compact/sign.js new file mode 100644 index 0000000..b8e5ba0 --- /dev/null +++ b/node_modules/jose/dist/browser/jws/compact/sign.js @@ -0,0 +1,17 @@ +import { FlattenedSign } from '../flattened/sign.js'; +export class CompactSign { + constructor(payload) { + this._flattened = new FlattenedSign(payload); + } + setProtectedHeader(protectedHeader) { + this._flattened.setProtectedHeader(protectedHeader); + return this; + } + async sign(key, options) { + const jws = await this._flattened.sign(key, options); + if (jws.payload === undefined) { + throw new TypeError('use the flattened module for creating JWS with b64: false'); + } + return `${jws.protected}.${jws.payload}.${jws.signature}`; + } +} diff --git a/node_modules/jose/dist/browser/jws/compact/verify.js b/node_modules/jose/dist/browser/jws/compact/verify.js new file mode 100644 index 0000000..c651ffb --- /dev/null +++ b/node_modules/jose/dist/browser/jws/compact/verify.js @@ -0,0 +1,21 @@ +import { flattenedVerify } from '../flattened/verify.js'; +import { JWSInvalid } from '../../util/errors.js'; +import { decoder } from '../../lib/buffer_utils.js'; +export async function compactVerify(jws, key, options) { + if (jws instanceof Uint8Array) { + jws = decoder.decode(jws); + } + if (typeof jws !== 'string') { + throw new JWSInvalid('Compact JWS must be a string or Uint8Array'); + } + const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.'); + if (length !== 3) { + throw new JWSInvalid('Invalid Compact JWS'); + } + const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options); + const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; + if (typeof key === 'function') { + return { ...result, key: verified.key }; + } + return result; +} diff --git a/node_modules/jose/dist/browser/jws/flattened/sign.js b/node_modules/jose/dist/browser/jws/flattened/sign.js new file mode 100644 index 0000000..76ae289 --- /dev/null +++ b/node_modules/jose/dist/browser/jws/flattened/sign.js @@ -0,0 +1,81 @@ +import { encode as base64url } from '../../runtime/base64url.js'; +import sign from '../../runtime/sign.js'; +import isDisjoint from '../../lib/is_disjoint.js'; +import { JWSInvalid } from '../../util/errors.js'; +import { encoder, decoder, concat } from '../../lib/buffer_utils.js'; +import checkKeyType from '../../lib/check_key_type.js'; +import validateCrit from '../../lib/validate_crit.js'; +export class FlattenedSign { + constructor(payload) { + if (!(payload instanceof Uint8Array)) { + throw new TypeError('payload must be an instance of Uint8Array'); + } + this._payload = payload; + } + setProtectedHeader(protectedHeader) { + if (this._protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this._protectedHeader = protectedHeader; + return this; + } + setUnprotectedHeader(unprotectedHeader) { + if (this._unprotectedHeader) { + throw new TypeError('setUnprotectedHeader can only be called once'); + } + this._unprotectedHeader = unprotectedHeader; + return this; + } + async sign(key, options) { + if (!this._protectedHeader && !this._unprotectedHeader) { + throw new JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()'); + } + if (!isDisjoint(this._protectedHeader, this._unprotectedHeader)) { + throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); + } + const joseHeader = { + ...this._protectedHeader, + ...this._unprotectedHeader, + }; + const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader); + let b64 = true; + if (extensions.has('b64')) { + b64 = this._protectedHeader.b64; + if (typeof b64 !== 'boolean') { + throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); + } + } + const { alg } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); + } + checkKeyType(alg, key, 'sign'); + let payload = this._payload; + if (b64) { + payload = encoder.encode(base64url(payload)); + } + let protectedHeader; + if (this._protectedHeader) { + protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader))); + } + else { + protectedHeader = encoder.encode(''); + } + const data = concat(protectedHeader, encoder.encode('.'), payload); + const signature = await sign(alg, key, data); + const jws = { + signature: base64url(signature), + payload: '', + }; + if (b64) { + jws.payload = decoder.decode(payload); + } + if (this._unprotectedHeader) { + jws.header = this._unprotectedHeader; + } + if (this._protectedHeader) { + jws.protected = decoder.decode(protectedHeader); + } + return jws; + } +} diff --git a/node_modules/jose/dist/browser/jws/flattened/verify.js b/node_modules/jose/dist/browser/jws/flattened/verify.js new file mode 100644 index 0000000..403eaad --- /dev/null +++ b/node_modules/jose/dist/browser/jws/flattened/verify.js @@ -0,0 +1,115 @@ +import { decode as base64url } from '../../runtime/base64url.js'; +import verify from '../../runtime/verify.js'; +import { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js'; +import { concat, encoder, decoder } from '../../lib/buffer_utils.js'; +import isDisjoint from '../../lib/is_disjoint.js'; +import isObject from '../../lib/is_object.js'; +import checkKeyType from '../../lib/check_key_type.js'; +import validateCrit from '../../lib/validate_crit.js'; +import validateAlgorithms from '../../lib/validate_algorithms.js'; +export async function flattenedVerify(jws, key, options) { + var _a; + if (!isObject(jws)) { + throw new JWSInvalid('Flattened JWS must be an object'); + } + if (jws.protected === undefined && jws.header === undefined) { + throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); + } + if (jws.protected !== undefined && typeof jws.protected !== 'string') { + throw new JWSInvalid('JWS Protected Header incorrect type'); + } + if (jws.payload === undefined) { + throw new JWSInvalid('JWS Payload missing'); + } + if (typeof jws.signature !== 'string') { + throw new JWSInvalid('JWS Signature missing or incorrect type'); + } + if (jws.header !== undefined && !isObject(jws.header)) { + throw new JWSInvalid('JWS Unprotected Header incorrect type'); + } + let parsedProt = {}; + if (jws.protected) { + try { + const protectedHeader = base64url(jws.protected); + parsedProt = JSON.parse(decoder.decode(protectedHeader)); + } + catch (_b) { + throw new JWSInvalid('JWS Protected Header is invalid'); + } + } + if (!isDisjoint(parsedProt, jws.header)) { + throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); + } + const joseHeader = { + ...parsedProt, + ...jws.header, + }; + const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader); + let b64 = true; + if (extensions.has('b64')) { + b64 = parsedProt.b64; + if (typeof b64 !== 'boolean') { + throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); + } + } + const { alg } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); + } + const algorithms = options && validateAlgorithms('algorithms', options.algorithms); + if (algorithms && !algorithms.has(alg)) { + throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed'); + } + if (b64) { + if (typeof jws.payload !== 'string') { + throw new JWSInvalid('JWS Payload must be a string'); + } + } + else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) { + throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance'); + } + let resolvedKey = false; + if (typeof key === 'function') { + key = await key(parsedProt, jws); + resolvedKey = true; + } + checkKeyType(alg, key, 'verify'); + const data = concat(encoder.encode((_a = jws.protected) !== null && _a !== void 0 ? _a : ''), encoder.encode('.'), typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload); + let signature; + try { + signature = base64url(jws.signature); + } + catch (_c) { + throw new JWSInvalid('Failed to base64url decode the signature'); + } + const verified = await verify(alg, key, signature, data); + if (!verified) { + throw new JWSSignatureVerificationFailed(); + } + let payload; + if (b64) { + try { + payload = base64url(jws.payload); + } + catch (_d) { + throw new JWSInvalid('Failed to base64url decode the payload'); + } + } + else if (typeof jws.payload === 'string') { + payload = encoder.encode(jws.payload); + } + else { + payload = jws.payload; + } + const result = { payload }; + if (jws.protected !== undefined) { + result.protectedHeader = parsedProt; + } + if (jws.header !== undefined) { + result.unprotectedHeader = jws.header; + } + if (resolvedKey) { + return { ...result, key }; + } + return result; +} diff --git a/node_modules/jose/dist/browser/jws/general/sign.js b/node_modules/jose/dist/browser/jws/general/sign.js new file mode 100644 index 0000000..0e0d645 --- /dev/null +++ b/node_modules/jose/dist/browser/jws/general/sign.js @@ -0,0 +1,67 @@ +import { FlattenedSign } from '../flattened/sign.js'; +import { JWSInvalid } from '../../util/errors.js'; +class IndividualSignature { + constructor(sig, key, options) { + this.parent = sig; + this.key = key; + this.options = options; + } + setProtectedHeader(protectedHeader) { + if (this.protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this.protectedHeader = protectedHeader; + return this; + } + setUnprotectedHeader(unprotectedHeader) { + if (this.unprotectedHeader) { + throw new TypeError('setUnprotectedHeader can only be called once'); + } + this.unprotectedHeader = unprotectedHeader; + return this; + } + addSignature(...args) { + return this.parent.addSignature(...args); + } + sign(...args) { + return this.parent.sign(...args); + } + done() { + return this.parent; + } +} +export class GeneralSign { + constructor(payload) { + this._signatures = []; + this._payload = payload; + } + addSignature(key, options) { + const signature = new IndividualSignature(this, key, options); + this._signatures.push(signature); + return signature; + } + async sign() { + if (!this._signatures.length) { + throw new JWSInvalid('at least one signature must be added'); + } + const jws = { + signatures: [], + payload: '', + }; + for (let i = 0; i < this._signatures.length; i++) { + const signature = this._signatures[i]; + const flattened = new FlattenedSign(this._payload); + flattened.setProtectedHeader(signature.protectedHeader); + flattened.setUnprotectedHeader(signature.unprotectedHeader); + const { payload, ...rest } = await flattened.sign(signature.key, signature.options); + if (i === 0) { + jws.payload = payload; + } + else if (jws.payload !== payload) { + throw new JWSInvalid('inconsistent use of JWS Unencoded Payload (RFC7797)'); + } + jws.signatures.push(rest); + } + return jws; + } +} diff --git a/node_modules/jose/dist/browser/jws/general/verify.js b/node_modules/jose/dist/browser/jws/general/verify.js new file mode 100644 index 0000000..459090a --- /dev/null +++ b/node_modules/jose/dist/browser/jws/general/verify.js @@ -0,0 +1,24 @@ +import { flattenedVerify } from '../flattened/verify.js'; +import { JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js'; +import isObject from '../../lib/is_object.js'; +export async function generalVerify(jws, key, options) { + if (!isObject(jws)) { + throw new JWSInvalid('General JWS must be an object'); + } + if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) { + throw new JWSInvalid('JWS Signatures missing or incorrect type'); + } + for (const signature of jws.signatures) { + try { + return await flattenedVerify({ + header: signature.header, + payload: jws.payload, + protected: signature.protected, + signature: signature.signature, + }, key, options); + } + catch (_a) { + } + } + throw new JWSSignatureVerificationFailed(); +} diff --git a/node_modules/jose/dist/browser/jwt/decrypt.js b/node_modules/jose/dist/browser/jwt/decrypt.js new file mode 100644 index 0000000..1ec2be2 --- /dev/null +++ b/node_modules/jose/dist/browser/jwt/decrypt.js @@ -0,0 +1,23 @@ +import { compactDecrypt } from '../jwe/compact/decrypt.js'; +import jwtPayload from '../lib/jwt_claims_set.js'; +import { JWTClaimValidationFailed } from '../util/errors.js'; +export async function jwtDecrypt(jwt, key, options) { + const decrypted = await compactDecrypt(jwt, key, options); + const payload = jwtPayload(decrypted.protectedHeader, decrypted.plaintext, options); + const { protectedHeader } = decrypted; + if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) { + throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', 'iss', 'mismatch'); + } + if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) { + throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', 'sub', 'mismatch'); + } + if (protectedHeader.aud !== undefined && + JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) { + throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', 'aud', 'mismatch'); + } + const result = { payload, protectedHeader }; + if (typeof key === 'function') { + return { ...result, key: decrypted.key }; + } + return result; +} diff --git a/node_modules/jose/dist/browser/jwt/encrypt.js b/node_modules/jose/dist/browser/jwt/encrypt.js new file mode 100644 index 0000000..1525295 --- /dev/null +++ b/node_modules/jose/dist/browser/jwt/encrypt.js @@ -0,0 +1,68 @@ +import { CompactEncrypt } from '../jwe/compact/encrypt.js'; +import { encoder } from '../lib/buffer_utils.js'; +import { ProduceJWT } from './produce.js'; +export class EncryptJWT extends ProduceJWT { + setProtectedHeader(protectedHeader) { + if (this._protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this._protectedHeader = protectedHeader; + return this; + } + setKeyManagementParameters(parameters) { + if (this._keyManagementParameters) { + throw new TypeError('setKeyManagementParameters can only be called once'); + } + this._keyManagementParameters = parameters; + return this; + } + setContentEncryptionKey(cek) { + if (this._cek) { + throw new TypeError('setContentEncryptionKey can only be called once'); + } + this._cek = cek; + return this; + } + setInitializationVector(iv) { + if (this._iv) { + throw new TypeError('setInitializationVector can only be called once'); + } + this._iv = iv; + return this; + } + replicateIssuerAsHeader() { + this._replicateIssuerAsHeader = true; + return this; + } + replicateSubjectAsHeader() { + this._replicateSubjectAsHeader = true; + return this; + } + replicateAudienceAsHeader() { + this._replicateAudienceAsHeader = true; + return this; + } + async encrypt(key, options) { + const enc = new CompactEncrypt(encoder.encode(JSON.stringify(this._payload))); + if (this._replicateIssuerAsHeader) { + this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss }; + } + if (this._replicateSubjectAsHeader) { + this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub }; + } + if (this._replicateAudienceAsHeader) { + this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud }; + } + enc.setProtectedHeader(this._protectedHeader); + if (this._iv) { + enc.setInitializationVector(this._iv); + } + if (this._cek) { + enc.setContentEncryptionKey(this._cek); + } + if (this._keyManagementParameters) { + enc.setKeyManagementParameters(this._keyManagementParameters); + } + return enc.encrypt(key, options); + } +} diff --git a/node_modules/jose/dist/browser/jwt/produce.js b/node_modules/jose/dist/browser/jwt/produce.js new file mode 100644 index 0000000..31c929a --- /dev/null +++ b/node_modules/jose/dist/browser/jwt/produce.js @@ -0,0 +1,54 @@ +import epoch from '../lib/epoch.js'; +import isObject from '../lib/is_object.js'; +import secs from '../lib/secs.js'; +export class ProduceJWT { + constructor(payload) { + if (!isObject(payload)) { + throw new TypeError('JWT Claims Set MUST be an object'); + } + this._payload = payload; + } + setIssuer(issuer) { + this._payload = { ...this._payload, iss: issuer }; + return this; + } + setSubject(subject) { + this._payload = { ...this._payload, sub: subject }; + return this; + } + setAudience(audience) { + this._payload = { ...this._payload, aud: audience }; + return this; + } + setJti(jwtId) { + this._payload = { ...this._payload, jti: jwtId }; + return this; + } + setNotBefore(input) { + if (typeof input === 'number') { + this._payload = { ...this._payload, nbf: input }; + } + else { + this._payload = { ...this._payload, nbf: epoch(new Date()) + secs(input) }; + } + return this; + } + setExpirationTime(input) { + if (typeof input === 'number') { + this._payload = { ...this._payload, exp: input }; + } + else { + this._payload = { ...this._payload, exp: epoch(new Date()) + secs(input) }; + } + return this; + } + setIssuedAt(input) { + if (typeof input === 'undefined') { + this._payload = { ...this._payload, iat: epoch(new Date()) }; + } + else { + this._payload = { ...this._payload, iat: input }; + } + return this; + } +} diff --git a/node_modules/jose/dist/browser/jwt/sign.js b/node_modules/jose/dist/browser/jwt/sign.js new file mode 100644 index 0000000..62352fb --- /dev/null +++ b/node_modules/jose/dist/browser/jwt/sign.js @@ -0,0 +1,21 @@ +import { CompactSign } from '../jws/compact/sign.js'; +import { JWTInvalid } from '../util/errors.js'; +import { encoder } from '../lib/buffer_utils.js'; +import { ProduceJWT } from './produce.js'; +export class SignJWT extends ProduceJWT { + setProtectedHeader(protectedHeader) { + this._protectedHeader = protectedHeader; + return this; + } + async sign(key, options) { + var _a; + const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload))); + sig.setProtectedHeader(this._protectedHeader); + if (Array.isArray((_a = this._protectedHeader) === null || _a === void 0 ? void 0 : _a.crit) && + this._protectedHeader.crit.includes('b64') && + this._protectedHeader.b64 === false) { + throw new JWTInvalid('JWTs MUST NOT use unencoded payload'); + } + return sig.sign(key, options); + } +} diff --git a/node_modules/jose/dist/browser/jwt/unsecured.js b/node_modules/jose/dist/browser/jwt/unsecured.js new file mode 100644 index 0000000..b027651 --- /dev/null +++ b/node_modules/jose/dist/browser/jwt/unsecured.js @@ -0,0 +1,32 @@ +import * as base64url from '../runtime/base64url.js'; +import { decoder } from '../lib/buffer_utils.js'; +import { JWTInvalid } from '../util/errors.js'; +import jwtPayload from '../lib/jwt_claims_set.js'; +import { ProduceJWT } from './produce.js'; +export class UnsecuredJWT extends ProduceJWT { + encode() { + const header = base64url.encode(JSON.stringify({ alg: 'none' })); + const payload = base64url.encode(JSON.stringify(this._payload)); + return `${header}.${payload}.`; + } + static decode(jwt, options) { + if (typeof jwt !== 'string') { + throw new JWTInvalid('Unsecured JWT must be a string'); + } + const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.'); + if (length !== 3 || signature !== '') { + throw new JWTInvalid('Invalid Unsecured JWT'); + } + let header; + try { + header = JSON.parse(decoder.decode(base64url.decode(encodedHeader))); + if (header.alg !== 'none') + throw new Error(); + } + catch (_a) { + throw new JWTInvalid('Invalid Unsecured JWT'); + } + const payload = jwtPayload(header, base64url.decode(encodedPayload), options); + return { payload, header }; + } +} diff --git a/node_modules/jose/dist/browser/jwt/verify.js b/node_modules/jose/dist/browser/jwt/verify.js new file mode 100644 index 0000000..89571c1 --- /dev/null +++ b/node_modules/jose/dist/browser/jwt/verify.js @@ -0,0 +1,16 @@ +import { compactVerify } from '../jws/compact/verify.js'; +import jwtPayload from '../lib/jwt_claims_set.js'; +import { JWTInvalid } from '../util/errors.js'; +export async function jwtVerify(jwt, key, options) { + var _a; + const verified = await compactVerify(jwt, key, options); + if (((_a = verified.protectedHeader.crit) === null || _a === void 0 ? void 0 : _a.includes('b64')) && verified.protectedHeader.b64 === false) { + throw new JWTInvalid('JWTs MUST NOT use unencoded payload'); + } + const payload = jwtPayload(verified.protectedHeader, verified.payload, options); + const result = { payload, protectedHeader: verified.protectedHeader }; + if (typeof key === 'function') { + return { ...result, key: verified.key }; + } + return result; +} diff --git a/node_modules/jose/dist/browser/key/export.js b/node_modules/jose/dist/browser/key/export.js new file mode 100644 index 0000000..e401704 --- /dev/null +++ b/node_modules/jose/dist/browser/key/export.js @@ -0,0 +1,12 @@ +import { toSPKI as exportPublic } from '../runtime/asn1.js'; +import { toPKCS8 as exportPrivate } from '../runtime/asn1.js'; +import keyToJWK from '../runtime/key_to_jwk.js'; +export async function exportSPKI(key) { + return exportPublic(key); +} +export async function exportPKCS8(key) { + return exportPrivate(key); +} +export async function exportJWK(key) { + return keyToJWK(key); +} diff --git a/node_modules/jose/dist/browser/key/generate_key_pair.js b/node_modules/jose/dist/browser/key/generate_key_pair.js new file mode 100644 index 0000000..03b9ee5 --- /dev/null +++ b/node_modules/jose/dist/browser/key/generate_key_pair.js @@ -0,0 +1,4 @@ +import { generateKeyPair as generate } from '../runtime/generate.js'; +export async function generateKeyPair(alg, options) { + return generate(alg, options); +} diff --git a/node_modules/jose/dist/browser/key/generate_secret.js b/node_modules/jose/dist/browser/key/generate_secret.js new file mode 100644 index 0000000..58f308a --- /dev/null +++ b/node_modules/jose/dist/browser/key/generate_secret.js @@ -0,0 +1,4 @@ +import { generateSecret as generate } from '../runtime/generate.js'; +export async function generateSecret(alg, options) { + return generate(alg, options); +} diff --git a/node_modules/jose/dist/browser/key/import.js b/node_modules/jose/dist/browser/key/import.js new file mode 100644 index 0000000..25bb0e1 --- /dev/null +++ b/node_modules/jose/dist/browser/key/import.js @@ -0,0 +1,50 @@ +import { decode as decodeBase64URL } from '../runtime/base64url.js'; +import { fromSPKI, fromPKCS8, fromX509 } from '../runtime/asn1.js'; +import asKeyObject from '../runtime/jwk_to_key.js'; +import { JOSENotSupported } from '../util/errors.js'; +import isObject from '../lib/is_object.js'; +export async function importSPKI(spki, alg, options) { + if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) { + throw new TypeError('"spki" must be SPKI formatted string'); + } + return fromSPKI(spki, alg, options); +} +export async function importX509(x509, alg, options) { + if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) { + throw new TypeError('"x509" must be X.509 formatted string'); + } + return fromX509(x509, alg, options); +} +export async function importPKCS8(pkcs8, alg, options) { + if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) { + throw new TypeError('"pkcs8" must be PKCS#8 formatted string'); + } + return fromPKCS8(pkcs8, alg, options); +} +export async function importJWK(jwk, alg, octAsKeyObject) { + var _a; + if (!isObject(jwk)) { + throw new TypeError('JWK must be an object'); + } + alg || (alg = jwk.alg); + switch (jwk.kty) { + case 'oct': + if (typeof jwk.k !== 'string' || !jwk.k) { + throw new TypeError('missing "k" (Key Value) Parameter value'); + } + octAsKeyObject !== null && octAsKeyObject !== void 0 ? octAsKeyObject : (octAsKeyObject = jwk.ext !== true); + if (octAsKeyObject) { + return asKeyObject({ ...jwk, alg, ext: (_a = jwk.ext) !== null && _a !== void 0 ? _a : false }); + } + return decodeBase64URL(jwk.k); + case 'RSA': + if (jwk.oth !== undefined) { + throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); + } + case 'EC': + case 'OKP': + return asKeyObject({ ...jwk, alg }); + default: + throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); + } +} diff --git a/node_modules/jose/dist/browser/lib/aesgcmkw.js b/node_modules/jose/dist/browser/lib/aesgcmkw.js new file mode 100644 index 0000000..de3f4f9 --- /dev/null +++ b/node_modules/jose/dist/browser/lib/aesgcmkw.js @@ -0,0 +1,14 @@ +import encrypt from '../runtime/encrypt.js'; +import decrypt from '../runtime/decrypt.js'; +import generateIv from './iv.js'; +import { encode as base64url } from '../runtime/base64url.js'; +export async function wrap(alg, key, cek, iv) { + const jweAlgorithm = alg.slice(0, 7); + iv || (iv = generateIv(jweAlgorithm)); + const { ciphertext: encryptedKey, tag } = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array(0)); + return { encryptedKey, iv: base64url(iv), tag: base64url(tag) }; +} +export async function unwrap(alg, key, encryptedKey, iv, tag) { + const jweAlgorithm = alg.slice(0, 7); + return decrypt(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0)); +} diff --git a/node_modules/jose/dist/browser/lib/buffer_utils.js b/node_modules/jose/dist/browser/lib/buffer_utils.js new file mode 100644 index 0000000..5a1a7b3 --- /dev/null +++ b/node_modules/jose/dist/browser/lib/buffer_utils.js @@ -0,0 +1,51 @@ +import digest from '../runtime/digest.js'; +export const encoder = new TextEncoder(); +export const decoder = new TextDecoder(); +const MAX_INT32 = 2 ** 32; +export function concat(...buffers) { + const size = buffers.reduce((acc, { length }) => acc + length, 0); + const buf = new Uint8Array(size); + let i = 0; + buffers.forEach((buffer) => { + buf.set(buffer, i); + i += buffer.length; + }); + return buf; +} +export function p2s(alg, p2sInput) { + return concat(encoder.encode(alg), new Uint8Array([0]), p2sInput); +} +function writeUInt32BE(buf, value, offset) { + if (value < 0 || value >= MAX_INT32) { + throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); + } + buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset); +} +export function uint64be(value) { + const high = Math.floor(value / MAX_INT32); + const low = value % MAX_INT32; + const buf = new Uint8Array(8); + writeUInt32BE(buf, high, 0); + writeUInt32BE(buf, low, 4); + return buf; +} +export function uint32be(value) { + const buf = new Uint8Array(4); + writeUInt32BE(buf, value); + return buf; +} +export function lengthAndInput(input) { + return concat(uint32be(input.length), input); +} +export async function concatKdf(secret, bits, value) { + const iterations = Math.ceil((bits >> 3) / 32); + const res = new Uint8Array(iterations * 32); + for (let iter = 0; iter < iterations; iter++) { + const buf = new Uint8Array(4 + secret.length + value.length); + buf.set(uint32be(iter + 1)); + buf.set(secret, 4); + buf.set(value, 4 + secret.length); + res.set(await digest('sha256', buf), iter * 32); + } + return res.slice(0, bits >> 3); +} diff --git a/node_modules/jose/dist/browser/lib/cek.js b/node_modules/jose/dist/browser/lib/cek.js new file mode 100644 index 0000000..34697d3 --- /dev/null +++ b/node_modules/jose/dist/browser/lib/cek.js @@ -0,0 +1,20 @@ +import { JOSENotSupported } from '../util/errors.js'; +import random from '../runtime/random.js'; +export function bitLength(alg) { + switch (alg) { + case 'A128GCM': + return 128; + case 'A192GCM': + return 192; + case 'A256GCM': + case 'A128CBC-HS256': + return 256; + case 'A192CBC-HS384': + return 384; + case 'A256CBC-HS512': + return 512; + default: + throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); + } +} +export default (alg) => random(new Uint8Array(bitLength(alg) >> 3)); diff --git a/node_modules/jose/dist/browser/lib/check_iv_length.js b/node_modules/jose/dist/browser/lib/check_iv_length.js new file mode 100644 index 0000000..dcd28d3 --- /dev/null +++ b/node_modules/jose/dist/browser/lib/check_iv_length.js @@ -0,0 +1,8 @@ +import { JWEInvalid } from '../util/errors.js'; +import { bitLength } from './iv.js'; +const checkIvLength = (enc, iv) => { + if (iv.length << 3 !== bitLength(enc)) { + throw new JWEInvalid('Invalid Initialization Vector length'); + } +}; +export default checkIvLength; diff --git a/node_modules/jose/dist/browser/lib/check_key_type.js b/node_modules/jose/dist/browser/lib/check_key_type.js new file mode 100644 index 0000000..43f3dcb --- /dev/null +++ b/node_modules/jose/dist/browser/lib/check_key_type.js @@ -0,0 +1,45 @@ +import { withAlg as invalidKeyInput } from './invalid_key_input.js'; +import isKeyLike, { types } from '../runtime/is_key_like.js'; +const symmetricTypeCheck = (alg, key) => { + if (key instanceof Uint8Array) + return; + if (!isKeyLike(key)) { + throw new TypeError(invalidKeyInput(alg, key, ...types, 'Uint8Array')); + } + if (key.type !== 'secret') { + throw new TypeError(`${types.join(' or ')} instances for symmetric algorithms must be of type "secret"`); + } +}; +const asymmetricTypeCheck = (alg, key, usage) => { + if (!isKeyLike(key)) { + throw new TypeError(invalidKeyInput(alg, key, ...types)); + } + if (key.type === 'secret') { + throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithms must not be of type "secret"`); + } + if (usage === 'sign' && key.type === 'public') { + throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm signing must be of type "private"`); + } + if (usage === 'decrypt' && key.type === 'public') { + throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm decryption must be of type "private"`); + } + if (key.algorithm && usage === 'verify' && key.type === 'private') { + throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm verifying must be of type "public"`); + } + if (key.algorithm && usage === 'encrypt' && key.type === 'private') { + throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm encryption must be of type "public"`); + } +}; +const checkKeyType = (alg, key, usage) => { + const symmetric = alg.startsWith('HS') || + alg === 'dir' || + alg.startsWith('PBES2') || + /^A\d{3}(?:GCM)?KW$/.test(alg); + if (symmetric) { + symmetricTypeCheck(alg, key); + } + else { + asymmetricTypeCheck(alg, key, usage); + } +}; +export default checkKeyType; diff --git a/node_modules/jose/dist/browser/lib/check_p2s.js b/node_modules/jose/dist/browser/lib/check_p2s.js new file mode 100644 index 0000000..a65289f --- /dev/null +++ b/node_modules/jose/dist/browser/lib/check_p2s.js @@ -0,0 +1,6 @@ +import { JWEInvalid } from '../util/errors.js'; +export default function checkP2s(p2s) { + if (!(p2s instanceof Uint8Array) || p2s.length < 8) { + throw new JWEInvalid('PBES2 Salt Input must be 8 or more octets'); + } +} diff --git a/node_modules/jose/dist/browser/lib/crypto_key.js b/node_modules/jose/dist/browser/lib/crypto_key.js new file mode 100644 index 0000000..807e951 --- /dev/null +++ b/node_modules/jose/dist/browser/lib/crypto_key.js @@ -0,0 +1,152 @@ +function unusable(name, prop = 'algorithm.name') { + return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); +} +function isAlgorithm(algorithm, name) { + return algorithm.name === name; +} +function getHashLength(hash) { + return parseInt(hash.name.slice(4), 10); +} +function getNamedCurve(alg) { + switch (alg) { + case 'ES256': + return 'P-256'; + case 'ES384': + return 'P-384'; + case 'ES512': + return 'P-521'; + default: + throw new Error('unreachable'); + } +} +function checkUsage(key, usages) { + if (usages.length && !usages.some((expected) => key.usages.includes(expected))) { + let msg = 'CryptoKey does not support this operation, its usages must include '; + if (usages.length > 2) { + const last = usages.pop(); + msg += `one of ${usages.join(', ')}, or ${last}.`; + } + else if (usages.length === 2) { + msg += `one of ${usages[0]} or ${usages[1]}.`; + } + else { + msg += `${usages[0]}.`; + } + throw new TypeError(msg); + } +} +export function checkSigCryptoKey(key, alg, ...usages) { + switch (alg) { + case 'HS256': + case 'HS384': + case 'HS512': { + if (!isAlgorithm(key.algorithm, 'HMAC')) + throw unusable('HMAC'); + const expected = parseInt(alg.slice(2), 10); + const actual = getHashLength(key.algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, 'algorithm.hash'); + break; + } + case 'RS256': + case 'RS384': + case 'RS512': { + if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5')) + throw unusable('RSASSA-PKCS1-v1_5'); + const expected = parseInt(alg.slice(2), 10); + const actual = getHashLength(key.algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, 'algorithm.hash'); + break; + } + case 'PS256': + case 'PS384': + case 'PS512': { + if (!isAlgorithm(key.algorithm, 'RSA-PSS')) + throw unusable('RSA-PSS'); + const expected = parseInt(alg.slice(2), 10); + const actual = getHashLength(key.algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, 'algorithm.hash'); + break; + } + case 'EdDSA': { + if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') { + throw unusable('Ed25519 or Ed448'); + } + break; + } + case 'ES256': + case 'ES384': + case 'ES512': { + if (!isAlgorithm(key.algorithm, 'ECDSA')) + throw unusable('ECDSA'); + const expected = getNamedCurve(alg); + const actual = key.algorithm.namedCurve; + if (actual !== expected) + throw unusable(expected, 'algorithm.namedCurve'); + break; + } + default: + throw new TypeError('CryptoKey does not support this operation'); + } + checkUsage(key, usages); +} +export function checkEncCryptoKey(key, alg, ...usages) { + switch (alg) { + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': { + if (!isAlgorithm(key.algorithm, 'AES-GCM')) + throw unusable('AES-GCM'); + const expected = parseInt(alg.slice(1, 4), 10); + const actual = key.algorithm.length; + if (actual !== expected) + throw unusable(expected, 'algorithm.length'); + break; + } + case 'A128KW': + case 'A192KW': + case 'A256KW': { + if (!isAlgorithm(key.algorithm, 'AES-KW')) + throw unusable('AES-KW'); + const expected = parseInt(alg.slice(1, 4), 10); + const actual = key.algorithm.length; + if (actual !== expected) + throw unusable(expected, 'algorithm.length'); + break; + } + case 'ECDH': { + switch (key.algorithm.name) { + case 'ECDH': + case 'X25519': + case 'X448': + break; + default: + throw unusable('ECDH, X25519, or X448'); + } + break; + } + case 'PBES2-HS256+A128KW': + case 'PBES2-HS384+A192KW': + case 'PBES2-HS512+A256KW': + if (!isAlgorithm(key.algorithm, 'PBKDF2')) + throw unusable('PBKDF2'); + break; + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': { + if (!isAlgorithm(key.algorithm, 'RSA-OAEP')) + throw unusable('RSA-OAEP'); + const expected = parseInt(alg.slice(9), 10) || 1; + const actual = getHashLength(key.algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, 'algorithm.hash'); + break; + } + default: + throw new TypeError('CryptoKey does not support this operation'); + } + checkUsage(key, usages); +} diff --git a/node_modules/jose/dist/browser/lib/decrypt_key_management.js b/node_modules/jose/dist/browser/lib/decrypt_key_management.js new file mode 100644 index 0000000..847929f --- /dev/null +++ b/node_modules/jose/dist/browser/lib/decrypt_key_management.js @@ -0,0 +1,127 @@ +import { unwrap as aesKw } from '../runtime/aeskw.js'; +import * as ECDH from '../runtime/ecdhes.js'; +import { decrypt as pbes2Kw } from '../runtime/pbes2kw.js'; +import { decrypt as rsaEs } from '../runtime/rsaes.js'; +import { decode as base64url } from '../runtime/base64url.js'; +import { JOSENotSupported, JWEInvalid } from '../util/errors.js'; +import { bitLength as cekLength } from '../lib/cek.js'; +import { importJWK } from '../key/import.js'; +import checkKeyType from './check_key_type.js'; +import isObject from './is_object.js'; +import { unwrap as aesGcmKw } from './aesgcmkw.js'; +async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) { + checkKeyType(alg, key, 'decrypt'); + switch (alg) { + case 'dir': { + if (encryptedKey !== undefined) + throw new JWEInvalid('Encountered unexpected JWE Encrypted Key'); + return key; + } + case 'ECDH-ES': + if (encryptedKey !== undefined) + throw new JWEInvalid('Encountered unexpected JWE Encrypted Key'); + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': { + if (!isObject(joseHeader.epk)) + throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); + if (!ECDH.ecdhAllowed(key)) + throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); + const epk = await importJWK(joseHeader.epk, alg); + let partyUInfo; + let partyVInfo; + if (joseHeader.apu !== undefined) { + if (typeof joseHeader.apu !== 'string') + throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); + try { + partyUInfo = base64url(joseHeader.apu); + } + catch (_a) { + throw new JWEInvalid('Failed to base64url decode the apu'); + } + } + if (joseHeader.apv !== undefined) { + if (typeof joseHeader.apv !== 'string') + throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); + try { + partyVInfo = base64url(joseHeader.apv); + } + catch (_b) { + throw new JWEInvalid('Failed to base64url decode the apv'); + } + } + const sharedSecret = await ECDH.deriveKey(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? cekLength(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo); + if (alg === 'ECDH-ES') + return sharedSecret; + if (encryptedKey === undefined) + throw new JWEInvalid('JWE Encrypted Key missing'); + return aesKw(alg.slice(-6), sharedSecret, encryptedKey); + } + case 'RSA1_5': + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': { + if (encryptedKey === undefined) + throw new JWEInvalid('JWE Encrypted Key missing'); + return rsaEs(alg, key, encryptedKey); + } + case 'PBES2-HS256+A128KW': + case 'PBES2-HS384+A192KW': + case 'PBES2-HS512+A256KW': { + if (encryptedKey === undefined) + throw new JWEInvalid('JWE Encrypted Key missing'); + if (typeof joseHeader.p2c !== 'number') + throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`); + const p2cLimit = (options === null || options === void 0 ? void 0 : options.maxPBES2Count) || 10000; + if (joseHeader.p2c > p2cLimit) + throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`); + if (typeof joseHeader.p2s !== 'string') + throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`); + let p2s; + try { + p2s = base64url(joseHeader.p2s); + } + catch (_c) { + throw new JWEInvalid('Failed to base64url decode the p2s'); + } + return pbes2Kw(alg, key, encryptedKey, joseHeader.p2c, p2s); + } + case 'A128KW': + case 'A192KW': + case 'A256KW': { + if (encryptedKey === undefined) + throw new JWEInvalid('JWE Encrypted Key missing'); + return aesKw(alg, key, encryptedKey); + } + case 'A128GCMKW': + case 'A192GCMKW': + case 'A256GCMKW': { + if (encryptedKey === undefined) + throw new JWEInvalid('JWE Encrypted Key missing'); + if (typeof joseHeader.iv !== 'string') + throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`); + if (typeof joseHeader.tag !== 'string') + throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`); + let iv; + try { + iv = base64url(joseHeader.iv); + } + catch (_d) { + throw new JWEInvalid('Failed to base64url decode the iv'); + } + let tag; + try { + tag = base64url(joseHeader.tag); + } + catch (_e) { + throw new JWEInvalid('Failed to base64url decode the tag'); + } + return aesGcmKw(alg, key, encryptedKey, iv, tag); + } + default: { + throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); + } + } +} +export default decryptKeyManagement; diff --git a/node_modules/jose/dist/browser/lib/encrypt_key_management.js b/node_modules/jose/dist/browser/lib/encrypt_key_management.js new file mode 100644 index 0000000..eb9022c --- /dev/null +++ b/node_modules/jose/dist/browser/lib/encrypt_key_management.js @@ -0,0 +1,87 @@ +import { wrap as aesKw } from '../runtime/aeskw.js'; +import * as ECDH from '../runtime/ecdhes.js'; +import { encrypt as pbes2Kw } from '../runtime/pbes2kw.js'; +import { encrypt as rsaEs } from '../runtime/rsaes.js'; +import { encode as base64url } from '../runtime/base64url.js'; +import generateCek, { bitLength as cekLength } from '../lib/cek.js'; +import { JOSENotSupported } from '../util/errors.js'; +import { exportJWK } from '../key/export.js'; +import checkKeyType from './check_key_type.js'; +import { wrap as aesGcmKw } from './aesgcmkw.js'; +async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) { + let encryptedKey; + let parameters; + let cek; + checkKeyType(alg, key, 'encrypt'); + switch (alg) { + case 'dir': { + cek = key; + break; + } + case 'ECDH-ES': + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': { + if (!ECDH.ecdhAllowed(key)) { + throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); + } + const { apu, apv } = providedParameters; + let { epk: ephemeralKey } = providedParameters; + ephemeralKey || (ephemeralKey = (await ECDH.generateEpk(key)).privateKey); + const { x, y, crv, kty } = await exportJWK(ephemeralKey); + const sharedSecret = await ECDH.deriveKey(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv); + parameters = { epk: { x, crv, kty } }; + if (kty === 'EC') + parameters.epk.y = y; + if (apu) + parameters.apu = base64url(apu); + if (apv) + parameters.apv = base64url(apv); + if (alg === 'ECDH-ES') { + cek = sharedSecret; + break; + } + cek = providedCek || generateCek(enc); + const kwAlg = alg.slice(-6); + encryptedKey = await aesKw(kwAlg, sharedSecret, cek); + break; + } + case 'RSA1_5': + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': { + cek = providedCek || generateCek(enc); + encryptedKey = await rsaEs(alg, key, cek); + break; + } + case 'PBES2-HS256+A128KW': + case 'PBES2-HS384+A192KW': + case 'PBES2-HS512+A256KW': { + cek = providedCek || generateCek(enc); + const { p2c, p2s } = providedParameters; + ({ encryptedKey, ...parameters } = await pbes2Kw(alg, key, cek, p2c, p2s)); + break; + } + case 'A128KW': + case 'A192KW': + case 'A256KW': { + cek = providedCek || generateCek(enc); + encryptedKey = await aesKw(alg, key, cek); + break; + } + case 'A128GCMKW': + case 'A192GCMKW': + case 'A256GCMKW': { + cek = providedCek || generateCek(enc); + const { iv } = providedParameters; + ({ encryptedKey, ...parameters } = await aesGcmKw(alg, key, cek, iv)); + break; + } + default: { + throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); + } + } + return { cek, encryptedKey, parameters }; +} +export default encryptKeyManagement; diff --git a/node_modules/jose/dist/browser/lib/epoch.js b/node_modules/jose/dist/browser/lib/epoch.js new file mode 100644 index 0000000..e405e4b --- /dev/null +++ b/node_modules/jose/dist/browser/lib/epoch.js @@ -0,0 +1 @@ +export default (date) => Math.floor(date.getTime() / 1000); diff --git a/node_modules/jose/dist/browser/lib/format_pem.js b/node_modules/jose/dist/browser/lib/format_pem.js new file mode 100644 index 0000000..81673f2 --- /dev/null +++ b/node_modules/jose/dist/browser/lib/format_pem.js @@ -0,0 +1,4 @@ +export default (b64, descriptor) => { + const newlined = (b64.match(/.{1,64}/g) || []).join('\n'); + return `-----BEGIN ${descriptor}-----\n${newlined}\n-----END ${descriptor}-----`; +}; diff --git a/node_modules/jose/dist/browser/lib/invalid_key_input.js b/node_modules/jose/dist/browser/lib/invalid_key_input.js new file mode 100644 index 0000000..049e66e --- /dev/null +++ b/node_modules/jose/dist/browser/lib/invalid_key_input.js @@ -0,0 +1,30 @@ +function message(msg, actual, ...types) { + if (types.length > 2) { + const last = types.pop(); + msg += `one of type ${types.join(', ')}, or ${last}.`; + } + else if (types.length === 2) { + msg += `one of type ${types[0]} or ${types[1]}.`; + } + else { + msg += `of type ${types[0]}.`; + } + if (actual == null) { + msg += ` Received ${actual}`; + } + else if (typeof actual === 'function' && actual.name) { + msg += ` Received function ${actual.name}`; + } + else if (typeof actual === 'object' && actual != null) { + if (actual.constructor && actual.constructor.name) { + msg += ` Received an instance of ${actual.constructor.name}`; + } + } + return msg; +} +export default (actual, ...types) => { + return message('Key must be ', actual, ...types); +}; +export function withAlg(alg, actual, ...types) { + return message(`Key for the ${alg} algorithm must be `, actual, ...types); +} diff --git a/node_modules/jose/dist/browser/lib/is_disjoint.js b/node_modules/jose/dist/browser/lib/is_disjoint.js new file mode 100644 index 0000000..6f64350 --- /dev/null +++ b/node_modules/jose/dist/browser/lib/is_disjoint.js @@ -0,0 +1,22 @@ +const isDisjoint = (...headers) => { + const sources = headers.filter(Boolean); + if (sources.length === 0 || sources.length === 1) { + return true; + } + let acc; + for (const header of sources) { + const parameters = Object.keys(header); + if (!acc || acc.size === 0) { + acc = new Set(parameters); + continue; + } + for (const parameter of parameters) { + if (acc.has(parameter)) { + return false; + } + acc.add(parameter); + } + } + return true; +}; +export default isDisjoint; diff --git a/node_modules/jose/dist/browser/lib/is_object.js b/node_modules/jose/dist/browser/lib/is_object.js new file mode 100644 index 0000000..4955e93 --- /dev/null +++ b/node_modules/jose/dist/browser/lib/is_object.js @@ -0,0 +1,16 @@ +function isObjectLike(value) { + return typeof value === 'object' && value !== null; +} +export default function isObject(input) { + if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') { + return false; + } + if (Object.getPrototypeOf(input) === null) { + return true; + } + let proto = input; + while (Object.getPrototypeOf(proto) !== null) { + proto = Object.getPrototypeOf(proto); + } + return Object.getPrototypeOf(input) === proto; +} diff --git a/node_modules/jose/dist/browser/lib/iv.js b/node_modules/jose/dist/browser/lib/iv.js new file mode 100644 index 0000000..cab2a12 --- /dev/null +++ b/node_modules/jose/dist/browser/lib/iv.js @@ -0,0 +1,20 @@ +import { JOSENotSupported } from '../util/errors.js'; +import random from '../runtime/random.js'; +export function bitLength(alg) { + switch (alg) { + case 'A128GCM': + case 'A128GCMKW': + case 'A192GCM': + case 'A192GCMKW': + case 'A256GCM': + case 'A256GCMKW': + return 96; + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + return 128; + default: + throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); + } +} +export default (alg) => random(new Uint8Array(bitLength(alg) >> 3)); diff --git a/node_modules/jose/dist/browser/lib/jwt_claims_set.js b/node_modules/jose/dist/browser/lib/jwt_claims_set.js new file mode 100644 index 0000000..fc92a3b --- /dev/null +++ b/node_modules/jose/dist/browser/lib/jwt_claims_set.js @@ -0,0 +1,102 @@ +import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js'; +import { decoder } from './buffer_utils.js'; +import epoch from './epoch.js'; +import secs from './secs.js'; +import isObject from './is_object.js'; +const normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, ''); +const checkAudiencePresence = (audPayload, audOption) => { + if (typeof audPayload === 'string') { + return audOption.includes(audPayload); + } + if (Array.isArray(audPayload)) { + return audOption.some(Set.prototype.has.bind(new Set(audPayload))); + } + return false; +}; +export default (protectedHeader, encodedPayload, options = {}) => { + const { typ } = options; + if (typ && + (typeof protectedHeader.typ !== 'string' || + normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { + throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', 'typ', 'check_failed'); + } + let payload; + try { + payload = JSON.parse(decoder.decode(encodedPayload)); + } + catch (_a) { + } + if (!isObject(payload)) { + throw new JWTInvalid('JWT Claims Set must be a top-level JSON object'); + } + const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; + if (maxTokenAge !== undefined) + requiredClaims.push('iat'); + if (audience !== undefined) + requiredClaims.push('aud'); + if (subject !== undefined) + requiredClaims.push('sub'); + if (issuer !== undefined) + requiredClaims.push('iss'); + for (const claim of new Set(requiredClaims.reverse())) { + if (!(claim in payload)) { + throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, claim, 'missing'); + } + } + if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { + throw new JWTClaimValidationFailed('unexpected "iss" claim value', 'iss', 'check_failed'); + } + if (subject && payload.sub !== subject) { + throw new JWTClaimValidationFailed('unexpected "sub" claim value', 'sub', 'check_failed'); + } + if (audience && + !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) { + throw new JWTClaimValidationFailed('unexpected "aud" claim value', 'aud', 'check_failed'); + } + let tolerance; + switch (typeof options.clockTolerance) { + case 'string': + tolerance = secs(options.clockTolerance); + break; + case 'number': + tolerance = options.clockTolerance; + break; + case 'undefined': + tolerance = 0; + break; + default: + throw new TypeError('Invalid clockTolerance option type'); + } + const { currentDate } = options; + const now = epoch(currentDate || new Date()); + if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') { + throw new JWTClaimValidationFailed('"iat" claim must be a number', 'iat', 'invalid'); + } + if (payload.nbf !== undefined) { + if (typeof payload.nbf !== 'number') { + throw new JWTClaimValidationFailed('"nbf" claim must be a number', 'nbf', 'invalid'); + } + if (payload.nbf > now + tolerance) { + throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', 'nbf', 'check_failed'); + } + } + if (payload.exp !== undefined) { + if (typeof payload.exp !== 'number') { + throw new JWTClaimValidationFailed('"exp" claim must be a number', 'exp', 'invalid'); + } + if (payload.exp <= now - tolerance) { + throw new JWTExpired('"exp" claim timestamp check failed', 'exp', 'check_failed'); + } + } + if (maxTokenAge) { + const age = now - payload.iat; + const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge); + if (age - tolerance > max) { + throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', 'iat', 'check_failed'); + } + if (age < 0 - tolerance) { + throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', 'iat', 'check_failed'); + } + } + return payload; +}; diff --git a/node_modules/jose/dist/browser/lib/secs.js b/node_modules/jose/dist/browser/lib/secs.js new file mode 100644 index 0000000..cf470ed --- /dev/null +++ b/node_modules/jose/dist/browser/lib/secs.js @@ -0,0 +1,44 @@ +const minute = 60; +const hour = minute * 60; +const day = hour * 24; +const week = day * 7; +const year = day * 365.25; +const REGEX = /^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i; +export default (str) => { + const matched = REGEX.exec(str); + if (!matched) { + throw new TypeError('Invalid time period format'); + } + const value = parseFloat(matched[1]); + const unit = matched[2].toLowerCase(); + switch (unit) { + case 'sec': + case 'secs': + case 'second': + case 'seconds': + case 's': + return Math.round(value); + case 'minute': + case 'minutes': + case 'min': + case 'mins': + case 'm': + return Math.round(value * minute); + case 'hour': + case 'hours': + case 'hr': + case 'hrs': + case 'h': + return Math.round(value * hour); + case 'day': + case 'days': + case 'd': + return Math.round(value * day); + case 'week': + case 'weeks': + case 'w': + return Math.round(value * week); + default: + return Math.round(value * year); + } +}; diff --git a/node_modules/jose/dist/browser/lib/validate_algorithms.js b/node_modules/jose/dist/browser/lib/validate_algorithms.js new file mode 100644 index 0000000..a6a7918 --- /dev/null +++ b/node_modules/jose/dist/browser/lib/validate_algorithms.js @@ -0,0 +1,11 @@ +const validateAlgorithms = (option, algorithms) => { + if (algorithms !== undefined && + (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) { + throw new TypeError(`"${option}" option must be an array of strings`); + } + if (!algorithms) { + return undefined; + } + return new Set(algorithms); +}; +export default validateAlgorithms; diff --git a/node_modules/jose/dist/browser/lib/validate_crit.js b/node_modules/jose/dist/browser/lib/validate_crit.js new file mode 100644 index 0000000..68c69f1 --- /dev/null +++ b/node_modules/jose/dist/browser/lib/validate_crit.js @@ -0,0 +1,34 @@ +import { JOSENotSupported } from '../util/errors.js'; +function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { + if (joseHeader.crit !== undefined && protectedHeader.crit === undefined) { + throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); + } + if (!protectedHeader || protectedHeader.crit === undefined) { + return new Set(); + } + if (!Array.isArray(protectedHeader.crit) || + protectedHeader.crit.length === 0 || + protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) { + throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); + } + let recognized; + if (recognizedOption !== undefined) { + recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); + } + else { + recognized = recognizedDefault; + } + for (const parameter of protectedHeader.crit) { + if (!recognized.has(parameter)) { + throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); + } + if (joseHeader[parameter] === undefined) { + throw new Err(`Extension Header Parameter "${parameter}" is missing`); + } + else if (recognized.get(parameter) && protectedHeader[parameter] === undefined) { + throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); + } + } + return new Set(protectedHeader.crit); +} +export default validateCrit; diff --git a/node_modules/jose/dist/browser/package.json b/node_modules/jose/dist/browser/package.json new file mode 100644 index 0000000..8fb7e8f --- /dev/null +++ b/node_modules/jose/dist/browser/package.json @@ -0,0 +1 @@ +{"type":"module","sideEffects":false} diff --git a/node_modules/jose/dist/browser/runtime/aeskw.js b/node_modules/jose/dist/browser/runtime/aeskw.js new file mode 100644 index 0000000..bb7dff8 --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/aeskw.js @@ -0,0 +1,32 @@ +import bogusWebCrypto from './bogus.js'; +import crypto, { isCryptoKey } from './webcrypto.js'; +import { checkEncCryptoKey } from '../lib/crypto_key.js'; +import invalidKeyInput from '../lib/invalid_key_input.js'; +import { types } from './is_key_like.js'; +function checkKeySize(key, alg) { + if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) { + throw new TypeError(`Invalid key size for alg: ${alg}`); + } +} +function getCryptoKey(key, alg, usage) { + if (isCryptoKey(key)) { + checkEncCryptoKey(key, alg, usage); + return key; + } + if (key instanceof Uint8Array) { + return crypto.subtle.importKey('raw', key, 'AES-KW', true, [usage]); + } + throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); +} +export const wrap = async (alg, key, cek) => { + const cryptoKey = await getCryptoKey(key, alg, 'wrapKey'); + checkKeySize(cryptoKey, alg); + const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, ...bogusWebCrypto); + return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, cryptoKey, 'AES-KW')); +}; +export const unwrap = async (alg, key, encryptedKey) => { + const cryptoKey = await getCryptoKey(key, alg, 'unwrapKey'); + checkKeySize(cryptoKey, alg); + const cryptoKeyCek = await crypto.subtle.unwrapKey('raw', encryptedKey, cryptoKey, 'AES-KW', ...bogusWebCrypto); + return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek)); +}; diff --git a/node_modules/jose/dist/browser/runtime/asn1.js b/node_modules/jose/dist/browser/runtime/asn1.js new file mode 100644 index 0000000..fa5b81b --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/asn1.js @@ -0,0 +1,202 @@ +import crypto, { isCryptoKey } from './webcrypto.js'; +import invalidKeyInput from '../lib/invalid_key_input.js'; +import { encodeBase64, decodeBase64 } from './base64url.js'; +import formatPEM from '../lib/format_pem.js'; +import { JOSENotSupported } from '../util/errors.js'; +import { types } from './is_key_like.js'; +const genericExport = async (keyType, keyFormat, key) => { + if (!isCryptoKey(key)) { + throw new TypeError(invalidKeyInput(key, ...types)); + } + if (!key.extractable) { + throw new TypeError('CryptoKey is not extractable'); + } + if (key.type !== keyType) { + throw new TypeError(`key is not a ${keyType} key`); + } + return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`); +}; +export const toSPKI = (key) => { + return genericExport('public', 'spki', key); +}; +export const toPKCS8 = (key) => { + return genericExport('private', 'pkcs8', key); +}; +const findOid = (keyData, oid, from = 0) => { + if (from === 0) { + oid.unshift(oid.length); + oid.unshift(0x06); + } + let i = keyData.indexOf(oid[0], from); + if (i === -1) + return false; + const sub = keyData.subarray(i, i + oid.length); + if (sub.length !== oid.length) + return false; + return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1); +}; +const getNamedCurve = (keyData) => { + switch (true) { + case findOid(keyData, [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07]): + return 'P-256'; + case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x22]): + return 'P-384'; + case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x23]): + return 'P-521'; + case findOid(keyData, [0x2b, 0x65, 0x6e]): + return 'X25519'; + case findOid(keyData, [0x2b, 0x65, 0x6f]): + return 'X448'; + case findOid(keyData, [0x2b, 0x65, 0x70]): + return 'Ed25519'; + case findOid(keyData, [0x2b, 0x65, 0x71]): + return 'Ed448'; + default: + throw new JOSENotSupported('Invalid or unsupported EC Key Curve or OKP Key Sub Type'); + } +}; +const genericImport = async (replace, keyFormat, pem, alg, options) => { + var _a; + let algorithm; + let keyUsages; + const keyData = new Uint8Array(atob(pem.replace(replace, '')) + .split('') + .map((c) => c.charCodeAt(0))); + const isPublic = keyFormat === 'spki'; + switch (alg) { + case 'PS256': + case 'PS384': + case 'PS512': + algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` }; + keyUsages = isPublic ? ['verify'] : ['sign']; + break; + case 'RS256': + case 'RS384': + case 'RS512': + algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` }; + keyUsages = isPublic ? ['verify'] : ['sign']; + break; + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': + algorithm = { + name: 'RSA-OAEP', + hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`, + }; + keyUsages = isPublic ? ['encrypt', 'wrapKey'] : ['decrypt', 'unwrapKey']; + break; + case 'ES256': + algorithm = { name: 'ECDSA', namedCurve: 'P-256' }; + keyUsages = isPublic ? ['verify'] : ['sign']; + break; + case 'ES384': + algorithm = { name: 'ECDSA', namedCurve: 'P-384' }; + keyUsages = isPublic ? ['verify'] : ['sign']; + break; + case 'ES512': + algorithm = { name: 'ECDSA', namedCurve: 'P-521' }; + keyUsages = isPublic ? ['verify'] : ['sign']; + break; + case 'ECDH-ES': + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': { + const namedCurve = getNamedCurve(keyData); + algorithm = namedCurve.startsWith('P-') ? { name: 'ECDH', namedCurve } : { name: namedCurve }; + keyUsages = isPublic ? [] : ['deriveBits']; + break; + } + case 'EdDSA': + algorithm = { name: getNamedCurve(keyData) }; + keyUsages = isPublic ? ['verify'] : ['sign']; + break; + default: + throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value'); + } + return crypto.subtle.importKey(keyFormat, keyData, algorithm, (_a = options === null || options === void 0 ? void 0 : options.extractable) !== null && _a !== void 0 ? _a : false, keyUsages); +}; +export const fromPKCS8 = (pem, alg, options) => { + return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, 'pkcs8', pem, alg, options); +}; +export const fromSPKI = (pem, alg, options) => { + return genericImport(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, 'spki', pem, alg, options); +}; +function getElement(seq) { + let result = []; + let next = 0; + while (next < seq.length) { + let nextPart = parseElement(seq.subarray(next)); + result.push(nextPart); + next += nextPart.byteLength; + } + return result; +} +function parseElement(bytes) { + let position = 0; + let tag = bytes[0] & 0x1f; + position++; + if (tag === 0x1f) { + tag = 0; + while (bytes[position] >= 0x80) { + tag = tag * 128 + bytes[position] - 0x80; + position++; + } + tag = tag * 128 + bytes[position] - 0x80; + position++; + } + let length = 0; + if (bytes[position] < 0x80) { + length = bytes[position]; + position++; + } + else if (length === 0x80) { + length = 0; + while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) { + if (length > bytes.byteLength) { + throw new TypeError('invalid indefinite form length'); + } + length++; + } + const byteLength = position + length + 2; + return { + byteLength, + contents: bytes.subarray(position, position + length), + raw: bytes.subarray(0, byteLength), + }; + } + else { + let numberOfDigits = bytes[position] & 0x7f; + position++; + length = 0; + for (let i = 0; i < numberOfDigits; i++) { + length = length * 256 + bytes[position]; + position++; + } + } + const byteLength = position + length; + return { + byteLength, + contents: bytes.subarray(position, byteLength), + raw: bytes.subarray(0, byteLength), + }; +} +function spkiFromX509(buf) { + const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents); + return encodeBase64(tbsCertificate[tbsCertificate[0].raw[0] === 0xa0 ? 6 : 5].raw); +} +function getSPKI(x509) { + const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, ''); + const raw = decodeBase64(pem); + return formatPEM(spkiFromX509(raw), 'PUBLIC KEY'); +} +export const fromX509 = (pem, alg, options) => { + let spki; + try { + spki = getSPKI(pem); + } + catch (cause) { + throw new TypeError('Failed to parse the X.509 certificate', { cause }); + } + return fromSPKI(spki, alg, options); +}; diff --git a/node_modules/jose/dist/browser/runtime/base64url.js b/node_modules/jose/dist/browser/runtime/base64url.js new file mode 100644 index 0000000..32df82b --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/base64url.js @@ -0,0 +1,37 @@ +import { encoder, decoder } from '../lib/buffer_utils.js'; +export const encodeBase64 = (input) => { + let unencoded = input; + if (typeof unencoded === 'string') { + unencoded = encoder.encode(unencoded); + } + const CHUNK_SIZE = 0x8000; + const arr = []; + for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) { + arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE))); + } + return btoa(arr.join('')); +}; +export const encode = (input) => { + return encodeBase64(input).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); +}; +export const decodeBase64 = (encoded) => { + const binary = atob(encoded); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i); + } + return bytes; +}; +export const decode = (input) => { + let encoded = input; + if (encoded instanceof Uint8Array) { + encoded = decoder.decode(encoded); + } + encoded = encoded.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, ''); + try { + return decodeBase64(encoded); + } + catch (_a) { + throw new TypeError('The input to be decoded is not correctly encoded.'); + } +}; diff --git a/node_modules/jose/dist/browser/runtime/bogus.js b/node_modules/jose/dist/browser/runtime/bogus.js new file mode 100644 index 0000000..8fde604 --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/bogus.js @@ -0,0 +1,6 @@ +const bogusWebCrypto = [ + { hash: 'SHA-256', name: 'HMAC' }, + true, + ['sign'], +]; +export default bogusWebCrypto; diff --git a/node_modules/jose/dist/browser/runtime/check_cek_length.js b/node_modules/jose/dist/browser/runtime/check_cek_length.js new file mode 100644 index 0000000..ae89001 --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/check_cek_length.js @@ -0,0 +1,8 @@ +import { JWEInvalid } from '../util/errors.js'; +const checkCekLength = (cek, expected) => { + const actual = cek.byteLength << 3; + if (actual !== expected) { + throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); + } +}; +export default checkCekLength; diff --git a/node_modules/jose/dist/browser/runtime/check_key_length.js b/node_modules/jose/dist/browser/runtime/check_key_length.js new file mode 100644 index 0000000..3397006 --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/check_key_length.js @@ -0,0 +1,8 @@ +export default (alg, key) => { + if (alg.startsWith('RS') || alg.startsWith('PS')) { + const { modulusLength } = key.algorithm; + if (typeof modulusLength !== 'number' || modulusLength < 2048) { + throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); + } + } +}; diff --git a/node_modules/jose/dist/browser/runtime/decrypt.js b/node_modules/jose/dist/browser/runtime/decrypt.js new file mode 100644 index 0000000..68f9f7c --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/decrypt.js @@ -0,0 +1,85 @@ +import { concat, uint64be } from '../lib/buffer_utils.js'; +import checkIvLength from '../lib/check_iv_length.js'; +import checkCekLength from './check_cek_length.js'; +import timingSafeEqual from './timing_safe_equal.js'; +import { JOSENotSupported, JWEDecryptionFailed } from '../util/errors.js'; +import crypto, { isCryptoKey } from './webcrypto.js'; +import { checkEncCryptoKey } from '../lib/crypto_key.js'; +import invalidKeyInput from '../lib/invalid_key_input.js'; +import { types } from './is_key_like.js'; +async function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) { + if (!(cek instanceof Uint8Array)) { + throw new TypeError(invalidKeyInput(cek, 'Uint8Array')); + } + const keySize = parseInt(enc.slice(1, 4), 10); + const encKey = await crypto.subtle.importKey('raw', cek.subarray(keySize >> 3), 'AES-CBC', false, ['decrypt']); + const macKey = await crypto.subtle.importKey('raw', cek.subarray(0, keySize >> 3), { + hash: `SHA-${keySize << 1}`, + name: 'HMAC', + }, false, ['sign']); + const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); + const expectedTag = new Uint8Array((await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3)); + let macCheckPassed; + try { + macCheckPassed = timingSafeEqual(tag, expectedTag); + } + catch (_a) { + } + if (!macCheckPassed) { + throw new JWEDecryptionFailed(); + } + let plaintext; + try { + plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv, name: 'AES-CBC' }, encKey, ciphertext)); + } + catch (_b) { + } + if (!plaintext) { + throw new JWEDecryptionFailed(); + } + return plaintext; +} +async function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) { + let encKey; + if (cek instanceof Uint8Array) { + encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['decrypt']); + } + else { + checkEncCryptoKey(cek, enc, 'decrypt'); + encKey = cek; + } + try { + return new Uint8Array(await crypto.subtle.decrypt({ + additionalData: aad, + iv, + name: 'AES-GCM', + tagLength: 128, + }, encKey, concat(ciphertext, tag))); + } + catch (_a) { + throw new JWEDecryptionFailed(); + } +} +const decrypt = async (enc, cek, ciphertext, iv, tag, aad) => { + if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { + throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array')); + } + checkIvLength(enc, iv); + switch (enc) { + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + if (cek instanceof Uint8Array) + checkCekLength(cek, parseInt(enc.slice(-3), 10)); + return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad); + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': + if (cek instanceof Uint8Array) + checkCekLength(cek, parseInt(enc.slice(1, 4), 10)); + return gcmDecrypt(enc, cek, ciphertext, iv, tag, aad); + default: + throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); + } +}; +export default decrypt; diff --git a/node_modules/jose/dist/browser/runtime/digest.js b/node_modules/jose/dist/browser/runtime/digest.js new file mode 100644 index 0000000..39099d3 --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/digest.js @@ -0,0 +1,6 @@ +import crypto from './webcrypto.js'; +const digest = async (algorithm, data) => { + const subtleDigest = `SHA-${algorithm.slice(-3)}`; + return new Uint8Array(await crypto.subtle.digest(subtleDigest, data)); +}; +export default digest; diff --git a/node_modules/jose/dist/browser/runtime/ecdhes.js b/node_modules/jose/dist/browser/runtime/ecdhes.js new file mode 100644 index 0000000..b4f515e --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/ecdhes.js @@ -0,0 +1,46 @@ +import { encoder, concat, uint32be, lengthAndInput, concatKdf } from '../lib/buffer_utils.js'; +import crypto, { isCryptoKey } from './webcrypto.js'; +import { checkEncCryptoKey } from '../lib/crypto_key.js'; +import invalidKeyInput from '../lib/invalid_key_input.js'; +import { types } from './is_key_like.js'; +export async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) { + if (!isCryptoKey(publicKey)) { + throw new TypeError(invalidKeyInput(publicKey, ...types)); + } + checkEncCryptoKey(publicKey, 'ECDH'); + if (!isCryptoKey(privateKey)) { + throw new TypeError(invalidKeyInput(privateKey, ...types)); + } + checkEncCryptoKey(privateKey, 'ECDH', 'deriveBits'); + const value = concat(lengthAndInput(encoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength)); + let length; + if (publicKey.algorithm.name === 'X25519') { + length = 256; + } + else if (publicKey.algorithm.name === 'X448') { + length = 448; + } + else { + length = + Math.ceil(parseInt(publicKey.algorithm.namedCurve.substr(-3), 10) / 8) << 3; + } + const sharedSecret = new Uint8Array(await crypto.subtle.deriveBits({ + name: publicKey.algorithm.name, + public: publicKey, + }, privateKey, length)); + return concatKdf(sharedSecret, keyLength, value); +} +export async function generateEpk(key) { + if (!isCryptoKey(key)) { + throw new TypeError(invalidKeyInput(key, ...types)); + } + return crypto.subtle.generateKey(key.algorithm, true, ['deriveBits']); +} +export function ecdhAllowed(key) { + if (!isCryptoKey(key)) { + throw new TypeError(invalidKeyInput(key, ...types)); + } + return (['P-256', 'P-384', 'P-521'].includes(key.algorithm.namedCurve) || + key.algorithm.name === 'X25519' || + key.algorithm.name === 'X448'); +} diff --git a/node_modules/jose/dist/browser/runtime/encrypt.js b/node_modules/jose/dist/browser/runtime/encrypt.js new file mode 100644 index 0000000..c2ec0ef --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/encrypt.js @@ -0,0 +1,68 @@ +import { concat, uint64be } from '../lib/buffer_utils.js'; +import checkIvLength from '../lib/check_iv_length.js'; +import checkCekLength from './check_cek_length.js'; +import crypto, { isCryptoKey } from './webcrypto.js'; +import { checkEncCryptoKey } from '../lib/crypto_key.js'; +import invalidKeyInput from '../lib/invalid_key_input.js'; +import { JOSENotSupported } from '../util/errors.js'; +import { types } from './is_key_like.js'; +async function cbcEncrypt(enc, plaintext, cek, iv, aad) { + if (!(cek instanceof Uint8Array)) { + throw new TypeError(invalidKeyInput(cek, 'Uint8Array')); + } + const keySize = parseInt(enc.slice(1, 4), 10); + const encKey = await crypto.subtle.importKey('raw', cek.subarray(keySize >> 3), 'AES-CBC', false, ['encrypt']); + const macKey = await crypto.subtle.importKey('raw', cek.subarray(0, keySize >> 3), { + hash: `SHA-${keySize << 1}`, + name: 'HMAC', + }, false, ['sign']); + const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ + iv, + name: 'AES-CBC', + }, encKey, plaintext)); + const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); + const tag = new Uint8Array((await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3)); + return { ciphertext, tag }; +} +async function gcmEncrypt(enc, plaintext, cek, iv, aad) { + let encKey; + if (cek instanceof Uint8Array) { + encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt']); + } + else { + checkEncCryptoKey(cek, enc, 'encrypt'); + encKey = cek; + } + const encrypted = new Uint8Array(await crypto.subtle.encrypt({ + additionalData: aad, + iv, + name: 'AES-GCM', + tagLength: 128, + }, encKey, plaintext)); + const tag = encrypted.slice(-16); + const ciphertext = encrypted.slice(0, -16); + return { ciphertext, tag }; +} +const encrypt = async (enc, plaintext, cek, iv, aad) => { + if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { + throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array')); + } + checkIvLength(enc, iv); + switch (enc) { + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + if (cek instanceof Uint8Array) + checkCekLength(cek, parseInt(enc.slice(-3), 10)); + return cbcEncrypt(enc, plaintext, cek, iv, aad); + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': + if (cek instanceof Uint8Array) + checkCekLength(cek, parseInt(enc.slice(1, 4), 10)); + return gcmEncrypt(enc, plaintext, cek, iv, aad); + default: + throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); + } +}; +export default encrypt; diff --git a/node_modules/jose/dist/browser/runtime/fetch_jwks.js b/node_modules/jose/dist/browser/runtime/fetch_jwks.js new file mode 100644 index 0000000..85d58b6 --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/fetch_jwks.js @@ -0,0 +1,34 @@ +import { JOSEError, JWKSTimeout } from '../util/errors.js'; +const fetchJwks = async (url, timeout, options) => { + let controller; + let id; + let timedOut = false; + if (typeof AbortController === 'function') { + controller = new AbortController(); + id = setTimeout(() => { + timedOut = true; + controller.abort(); + }, timeout); + } + const response = await fetch(url.href, { + signal: controller ? controller.signal : undefined, + redirect: 'manual', + headers: options.headers, + }).catch((err) => { + if (timedOut) + throw new JWKSTimeout(); + throw err; + }); + if (id !== undefined) + clearTimeout(id); + if (response.status !== 200) { + throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response'); + } + try { + return await response.json(); + } + catch (_a) { + throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON'); + } +}; +export default fetchJwks; diff --git a/node_modules/jose/dist/browser/runtime/generate.js b/node_modules/jose/dist/browser/runtime/generate.js new file mode 100644 index 0000000..589b8fb --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/generate.js @@ -0,0 +1,141 @@ +import crypto from './webcrypto.js'; +import { JOSENotSupported } from '../util/errors.js'; +import random from './random.js'; +export async function generateSecret(alg, options) { + var _a; + let length; + let algorithm; + let keyUsages; + switch (alg) { + case 'HS256': + case 'HS384': + case 'HS512': + length = parseInt(alg.slice(-3), 10); + algorithm = { name: 'HMAC', hash: `SHA-${length}`, length }; + keyUsages = ['sign', 'verify']; + break; + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + length = parseInt(alg.slice(-3), 10); + return random(new Uint8Array(length >> 3)); + case 'A128KW': + case 'A192KW': + case 'A256KW': + length = parseInt(alg.slice(1, 4), 10); + algorithm = { name: 'AES-KW', length }; + keyUsages = ['wrapKey', 'unwrapKey']; + break; + case 'A128GCMKW': + case 'A192GCMKW': + case 'A256GCMKW': + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': + length = parseInt(alg.slice(1, 4), 10); + algorithm = { name: 'AES-GCM', length }; + keyUsages = ['encrypt', 'decrypt']; + break; + default: + throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + } + return crypto.subtle.generateKey(algorithm, (_a = options === null || options === void 0 ? void 0 : options.extractable) !== null && _a !== void 0 ? _a : false, keyUsages); +} +function getModulusLengthOption(options) { + var _a; + const modulusLength = (_a = options === null || options === void 0 ? void 0 : options.modulusLength) !== null && _a !== void 0 ? _a : 2048; + if (typeof modulusLength !== 'number' || modulusLength < 2048) { + throw new JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used'); + } + return modulusLength; +} +export async function generateKeyPair(alg, options) { + var _a, _b, _c; + let algorithm; + let keyUsages; + switch (alg) { + case 'PS256': + case 'PS384': + case 'PS512': + algorithm = { + name: 'RSA-PSS', + hash: `SHA-${alg.slice(-3)}`, + publicExponent: new Uint8Array([0x01, 0x00, 0x01]), + modulusLength: getModulusLengthOption(options), + }; + keyUsages = ['sign', 'verify']; + break; + case 'RS256': + case 'RS384': + case 'RS512': + algorithm = { + name: 'RSASSA-PKCS1-v1_5', + hash: `SHA-${alg.slice(-3)}`, + publicExponent: new Uint8Array([0x01, 0x00, 0x01]), + modulusLength: getModulusLengthOption(options), + }; + keyUsages = ['sign', 'verify']; + break; + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': + algorithm = { + name: 'RSA-OAEP', + hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`, + publicExponent: new Uint8Array([0x01, 0x00, 0x01]), + modulusLength: getModulusLengthOption(options), + }; + keyUsages = ['decrypt', 'unwrapKey', 'encrypt', 'wrapKey']; + break; + case 'ES256': + algorithm = { name: 'ECDSA', namedCurve: 'P-256' }; + keyUsages = ['sign', 'verify']; + break; + case 'ES384': + algorithm = { name: 'ECDSA', namedCurve: 'P-384' }; + keyUsages = ['sign', 'verify']; + break; + case 'ES512': + algorithm = { name: 'ECDSA', namedCurve: 'P-521' }; + keyUsages = ['sign', 'verify']; + break; + case 'EdDSA': + keyUsages = ['sign', 'verify']; + const crv = (_a = options === null || options === void 0 ? void 0 : options.crv) !== null && _a !== void 0 ? _a : 'Ed25519'; + switch (crv) { + case 'Ed25519': + case 'Ed448': + algorithm = { name: crv }; + break; + default: + throw new JOSENotSupported('Invalid or unsupported crv option provided'); + } + break; + case 'ECDH-ES': + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': { + keyUsages = ['deriveKey', 'deriveBits']; + const crv = (_b = options === null || options === void 0 ? void 0 : options.crv) !== null && _b !== void 0 ? _b : 'P-256'; + switch (crv) { + case 'P-256': + case 'P-384': + case 'P-521': { + algorithm = { name: 'ECDH', namedCurve: crv }; + break; + } + case 'X25519': + case 'X448': + algorithm = { name: crv }; + break; + default: + throw new JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448'); + } + break; + } + default: + throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + } + return (crypto.subtle.generateKey(algorithm, (_c = options === null || options === void 0 ? void 0 : options.extractable) !== null && _c !== void 0 ? _c : false, keyUsages)); +} diff --git a/node_modules/jose/dist/browser/runtime/get_sign_verify_key.js b/node_modules/jose/dist/browser/runtime/get_sign_verify_key.js new file mode 100644 index 0000000..db34ae8 --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/get_sign_verify_key.js @@ -0,0 +1,17 @@ +import crypto, { isCryptoKey } from './webcrypto.js'; +import { checkSigCryptoKey } from '../lib/crypto_key.js'; +import invalidKeyInput from '../lib/invalid_key_input.js'; +import { types } from './is_key_like.js'; +export default function getCryptoKey(alg, key, usage) { + if (isCryptoKey(key)) { + checkSigCryptoKey(key, alg, usage); + return key; + } + if (key instanceof Uint8Array) { + if (!alg.startsWith('HS')) { + throw new TypeError(invalidKeyInput(key, ...types)); + } + return crypto.subtle.importKey('raw', key, { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' }, false, [usage]); + } + throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); +} diff --git a/node_modules/jose/dist/browser/runtime/is_key_like.js b/node_modules/jose/dist/browser/runtime/is_key_like.js new file mode 100644 index 0000000..8d35fdc --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/is_key_like.js @@ -0,0 +1,5 @@ +import { isCryptoKey } from './webcrypto.js'; +export default (key) => { + return isCryptoKey(key); +}; +export const types = ['CryptoKey']; diff --git a/node_modules/jose/dist/browser/runtime/jwk_to_key.js b/node_modules/jose/dist/browser/runtime/jwk_to_key.js new file mode 100644 index 0000000..0274ecc --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/jwk_to_key.js @@ -0,0 +1,143 @@ +import crypto from './webcrypto.js'; +import { JOSENotSupported } from '../util/errors.js'; +import { decode as base64url } from './base64url.js'; +function subtleMapping(jwk) { + let algorithm; + let keyUsages; + switch (jwk.kty) { + case 'oct': { + switch (jwk.alg) { + case 'HS256': + case 'HS384': + case 'HS512': + algorithm = { name: 'HMAC', hash: `SHA-${jwk.alg.slice(-3)}` }; + keyUsages = ['sign', 'verify']; + break; + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + throw new JOSENotSupported(`${jwk.alg} keys cannot be imported as CryptoKey instances`); + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': + case 'A128GCMKW': + case 'A192GCMKW': + case 'A256GCMKW': + algorithm = { name: 'AES-GCM' }; + keyUsages = ['encrypt', 'decrypt']; + break; + case 'A128KW': + case 'A192KW': + case 'A256KW': + algorithm = { name: 'AES-KW' }; + keyUsages = ['wrapKey', 'unwrapKey']; + break; + case 'PBES2-HS256+A128KW': + case 'PBES2-HS384+A192KW': + case 'PBES2-HS512+A256KW': + algorithm = { name: 'PBKDF2' }; + keyUsages = ['deriveBits']; + break; + default: + throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + } + break; + } + case 'RSA': { + switch (jwk.alg) { + case 'PS256': + case 'PS384': + case 'PS512': + algorithm = { name: 'RSA-PSS', hash: `SHA-${jwk.alg.slice(-3)}` }; + keyUsages = jwk.d ? ['sign'] : ['verify']; + break; + case 'RS256': + case 'RS384': + case 'RS512': + algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${jwk.alg.slice(-3)}` }; + keyUsages = jwk.d ? ['sign'] : ['verify']; + break; + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': + algorithm = { + name: 'RSA-OAEP', + hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`, + }; + keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey']; + break; + default: + throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + } + break; + } + case 'EC': { + switch (jwk.alg) { + case 'ES256': + algorithm = { name: 'ECDSA', namedCurve: 'P-256' }; + keyUsages = jwk.d ? ['sign'] : ['verify']; + break; + case 'ES384': + algorithm = { name: 'ECDSA', namedCurve: 'P-384' }; + keyUsages = jwk.d ? ['sign'] : ['verify']; + break; + case 'ES512': + algorithm = { name: 'ECDSA', namedCurve: 'P-521' }; + keyUsages = jwk.d ? ['sign'] : ['verify']; + break; + case 'ECDH-ES': + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': + algorithm = { name: 'ECDH', namedCurve: jwk.crv }; + keyUsages = jwk.d ? ['deriveBits'] : []; + break; + default: + throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + } + break; + } + case 'OKP': { + switch (jwk.alg) { + case 'EdDSA': + algorithm = { name: jwk.crv }; + keyUsages = jwk.d ? ['sign'] : ['verify']; + break; + case 'ECDH-ES': + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': + algorithm = { name: jwk.crv }; + keyUsages = jwk.d ? ['deriveBits'] : []; + break; + default: + throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + } + break; + } + default: + throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value'); + } + return { algorithm, keyUsages }; +} +const parse = async (jwk) => { + var _a, _b; + if (!jwk.alg) { + throw new TypeError('"alg" argument is required when "jwk.alg" is not present'); + } + const { algorithm, keyUsages } = subtleMapping(jwk); + const rest = [ + algorithm, + (_a = jwk.ext) !== null && _a !== void 0 ? _a : false, + (_b = jwk.key_ops) !== null && _b !== void 0 ? _b : keyUsages, + ]; + if (algorithm.name === 'PBKDF2') { + return crypto.subtle.importKey('raw', base64url(jwk.k), ...rest); + } + const keyData = { ...jwk }; + delete keyData.alg; + delete keyData.use; + return crypto.subtle.importKey('jwk', keyData, ...rest); +}; +export default parse; diff --git a/node_modules/jose/dist/browser/runtime/key_to_jwk.js b/node_modules/jose/dist/browser/runtime/key_to_jwk.js new file mode 100644 index 0000000..438edfe --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/key_to_jwk.js @@ -0,0 +1,21 @@ +import crypto, { isCryptoKey } from './webcrypto.js'; +import invalidKeyInput from '../lib/invalid_key_input.js'; +import { encode as base64url } from './base64url.js'; +import { types } from './is_key_like.js'; +const keyToJWK = async (key) => { + if (key instanceof Uint8Array) { + return { + kty: 'oct', + k: base64url(key), + }; + } + if (!isCryptoKey(key)) { + throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); + } + if (!key.extractable) { + throw new TypeError('non-extractable CryptoKey cannot be exported as a JWK'); + } + const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey('jwk', key); + return jwk; +}; +export default keyToJWK; diff --git a/node_modules/jose/dist/browser/runtime/pbes2kw.js b/node_modules/jose/dist/browser/runtime/pbes2kw.js new file mode 100644 index 0000000..575304a --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/pbes2kw.js @@ -0,0 +1,51 @@ +import random from './random.js'; +import { p2s as concatSalt } from '../lib/buffer_utils.js'; +import { encode as base64url } from './base64url.js'; +import { wrap, unwrap } from './aeskw.js'; +import checkP2s from '../lib/check_p2s.js'; +import crypto, { isCryptoKey } from './webcrypto.js'; +import { checkEncCryptoKey } from '../lib/crypto_key.js'; +import invalidKeyInput from '../lib/invalid_key_input.js'; +import { types } from './is_key_like.js'; +function getCryptoKey(key, alg) { + if (key instanceof Uint8Array) { + return crypto.subtle.importKey('raw', key, 'PBKDF2', false, ['deriveBits']); + } + if (isCryptoKey(key)) { + checkEncCryptoKey(key, alg, 'deriveBits', 'deriveKey'); + return key; + } + throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); +} +async function deriveKey(p2s, alg, p2c, key) { + checkP2s(p2s); + const salt = concatSalt(alg, p2s); + const keylen = parseInt(alg.slice(13, 16), 10); + const subtleAlg = { + hash: `SHA-${alg.slice(8, 11)}`, + iterations: p2c, + name: 'PBKDF2', + salt, + }; + const wrapAlg = { + length: keylen, + name: 'AES-KW', + }; + const cryptoKey = await getCryptoKey(key, alg); + if (cryptoKey.usages.includes('deriveBits')) { + return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen)); + } + if (cryptoKey.usages.includes('deriveKey')) { + return crypto.subtle.deriveKey(subtleAlg, cryptoKey, wrapAlg, false, ['wrapKey', 'unwrapKey']); + } + throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"'); +} +export const encrypt = async (alg, key, cek, p2c = 2048, p2s = random(new Uint8Array(16))) => { + const derived = await deriveKey(p2s, alg, p2c, key); + const encryptedKey = await wrap(alg.slice(-6), derived, cek); + return { encryptedKey, p2c, p2s: base64url(p2s) }; +}; +export const decrypt = async (alg, key, encryptedKey, p2c, p2s) => { + const derived = await deriveKey(p2s, alg, p2c, key); + return unwrap(alg.slice(-6), derived, encryptedKey); +}; diff --git a/node_modules/jose/dist/browser/runtime/random.js b/node_modules/jose/dist/browser/runtime/random.js new file mode 100644 index 0000000..e8e4611 --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/random.js @@ -0,0 +1,2 @@ +import crypto from './webcrypto.js'; +export default crypto.getRandomValues.bind(crypto); diff --git a/node_modules/jose/dist/browser/runtime/rsaes.js b/node_modules/jose/dist/browser/runtime/rsaes.js new file mode 100644 index 0000000..a173376 --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/rsaes.js @@ -0,0 +1,37 @@ +import subtleAlgorithm from './subtle_rsaes.js'; +import bogusWebCrypto from './bogus.js'; +import crypto, { isCryptoKey } from './webcrypto.js'; +import { checkEncCryptoKey } from '../lib/crypto_key.js'; +import checkKeyLength from './check_key_length.js'; +import invalidKeyInput from '../lib/invalid_key_input.js'; +import { types } from './is_key_like.js'; +export const encrypt = async (alg, key, cek) => { + if (!isCryptoKey(key)) { + throw new TypeError(invalidKeyInput(key, ...types)); + } + checkEncCryptoKey(key, alg, 'encrypt', 'wrapKey'); + checkKeyLength(alg, key); + if (key.usages.includes('encrypt')) { + return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek)); + } + if (key.usages.includes('wrapKey')) { + const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, ...bogusWebCrypto); + return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, key, subtleAlgorithm(alg))); + } + throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation'); +}; +export const decrypt = async (alg, key, encryptedKey) => { + if (!isCryptoKey(key)) { + throw new TypeError(invalidKeyInput(key, ...types)); + } + checkEncCryptoKey(key, alg, 'decrypt', 'unwrapKey'); + checkKeyLength(alg, key); + if (key.usages.includes('decrypt')) { + return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey)); + } + if (key.usages.includes('unwrapKey')) { + const cryptoKeyCek = await crypto.subtle.unwrapKey('raw', encryptedKey, key, subtleAlgorithm(alg), ...bogusWebCrypto); + return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek)); + } + throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation'); +}; diff --git a/node_modules/jose/dist/browser/runtime/runtime.js b/node_modules/jose/dist/browser/runtime/runtime.js new file mode 100644 index 0000000..f449e82 --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/runtime.js @@ -0,0 +1 @@ +export default 'WebCryptoAPI'; diff --git a/node_modules/jose/dist/browser/runtime/sign.js b/node_modules/jose/dist/browser/runtime/sign.js new file mode 100644 index 0000000..3ccb9e1 --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/sign.js @@ -0,0 +1,11 @@ +import subtleAlgorithm from './subtle_dsa.js'; +import crypto from './webcrypto.js'; +import checkKeyLength from './check_key_length.js'; +import getSignKey from './get_sign_verify_key.js'; +const sign = async (alg, key, data) => { + const cryptoKey = await getSignKey(alg, key, 'sign'); + checkKeyLength(alg, cryptoKey); + const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data); + return new Uint8Array(signature); +}; +export default sign; diff --git a/node_modules/jose/dist/browser/runtime/subtle_dsa.js b/node_modules/jose/dist/browser/runtime/subtle_dsa.js new file mode 100644 index 0000000..4658669 --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/subtle_dsa.js @@ -0,0 +1,26 @@ +import { JOSENotSupported } from '../util/errors.js'; +export default function subtleDsa(alg, algorithm) { + const hash = `SHA-${alg.slice(-3)}`; + switch (alg) { + case 'HS256': + case 'HS384': + case 'HS512': + return { hash, name: 'HMAC' }; + case 'PS256': + case 'PS384': + case 'PS512': + return { hash, name: 'RSA-PSS', saltLength: alg.slice(-3) >> 3 }; + case 'RS256': + case 'RS384': + case 'RS512': + return { hash, name: 'RSASSA-PKCS1-v1_5' }; + case 'ES256': + case 'ES384': + case 'ES512': + return { hash, name: 'ECDSA', namedCurve: algorithm.namedCurve }; + case 'EdDSA': + return { name: algorithm.name }; + default: + throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } +} diff --git a/node_modules/jose/dist/browser/runtime/subtle_rsaes.js b/node_modules/jose/dist/browser/runtime/subtle_rsaes.js new file mode 100644 index 0000000..3a399bc --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/subtle_rsaes.js @@ -0,0 +1,12 @@ +import { JOSENotSupported } from '../util/errors.js'; +export default function subtleRsaEs(alg) { + switch (alg) { + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': + return 'RSA-OAEP'; + default: + throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } +} diff --git a/node_modules/jose/dist/browser/runtime/timing_safe_equal.js b/node_modules/jose/dist/browser/runtime/timing_safe_equal.js new file mode 100644 index 0000000..442cdcc --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/timing_safe_equal.js @@ -0,0 +1,19 @@ +const timingSafeEqual = (a, b) => { + if (!(a instanceof Uint8Array)) { + throw new TypeError('First argument must be a buffer'); + } + if (!(b instanceof Uint8Array)) { + throw new TypeError('Second argument must be a buffer'); + } + if (a.length !== b.length) { + throw new TypeError('Input buffers must have the same length'); + } + const len = a.length; + let out = 0; + let i = -1; + while (++i < len) { + out |= a[i] ^ b[i]; + } + return out === 0; +}; +export default timingSafeEqual; diff --git a/node_modules/jose/dist/browser/runtime/verify.js b/node_modules/jose/dist/browser/runtime/verify.js new file mode 100644 index 0000000..2ad4c7f --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/verify.js @@ -0,0 +1,16 @@ +import subtleAlgorithm from './subtle_dsa.js'; +import crypto from './webcrypto.js'; +import checkKeyLength from './check_key_length.js'; +import getVerifyKey from './get_sign_verify_key.js'; +const verify = async (alg, key, signature, data) => { + const cryptoKey = await getVerifyKey(alg, key, 'verify'); + checkKeyLength(alg, cryptoKey); + const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm); + try { + return await crypto.subtle.verify(algorithm, cryptoKey, signature, data); + } + catch (_a) { + return false; + } +}; +export default verify; diff --git a/node_modules/jose/dist/browser/runtime/webcrypto.js b/node_modules/jose/dist/browser/runtime/webcrypto.js new file mode 100644 index 0000000..f9e1e91 --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/webcrypto.js @@ -0,0 +1,2 @@ +export default crypto; +export const isCryptoKey = (key) => key instanceof CryptoKey; diff --git a/node_modules/jose/dist/browser/runtime/zlib.js b/node_modules/jose/dist/browser/runtime/zlib.js new file mode 100644 index 0000000..e47cb53 --- /dev/null +++ b/node_modules/jose/dist/browser/runtime/zlib.js @@ -0,0 +1,7 @@ +import { JOSENotSupported } from '../util/errors.js'; +export const inflate = async () => { + throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `inflateRaw` decrypt option to provide Inflate Raw implementation.'); +}; +export const deflate = async () => { + throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `deflateRaw` encrypt option to provide Deflate Raw implementation.'); +}; diff --git a/node_modules/jose/dist/browser/util/base64url.js b/node_modules/jose/dist/browser/util/base64url.js new file mode 100644 index 0000000..88ce755 --- /dev/null +++ b/node_modules/jose/dist/browser/util/base64url.js @@ -0,0 +1,3 @@ +import * as base64url from '../runtime/base64url.js'; +export const encode = base64url.encode; +export const decode = base64url.decode; diff --git a/node_modules/jose/dist/browser/util/decode_jwt.js b/node_modules/jose/dist/browser/util/decode_jwt.js new file mode 100644 index 0000000..93fe162 --- /dev/null +++ b/node_modules/jose/dist/browser/util/decode_jwt.js @@ -0,0 +1,32 @@ +import { decode as base64url } from './base64url.js'; +import { decoder } from '../lib/buffer_utils.js'; +import isObject from '../lib/is_object.js'; +import { JWTInvalid } from './errors.js'; +export function decodeJwt(jwt) { + if (typeof jwt !== 'string') + throw new JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string'); + const { 1: payload, length } = jwt.split('.'); + if (length === 5) + throw new JWTInvalid('Only JWTs using Compact JWS serialization can be decoded'); + if (length !== 3) + throw new JWTInvalid('Invalid JWT'); + if (!payload) + throw new JWTInvalid('JWTs must contain a payload'); + let decoded; + try { + decoded = base64url(payload); + } + catch (_a) { + throw new JWTInvalid('Failed to base64url decode the payload'); + } + let result; + try { + result = JSON.parse(decoder.decode(decoded)); + } + catch (_b) { + throw new JWTInvalid('Failed to parse the decoded payload as JSON'); + } + if (!isObject(result)) + throw new JWTInvalid('Invalid JWT Claims Set'); + return result; +} diff --git a/node_modules/jose/dist/browser/util/decode_protected_header.js b/node_modules/jose/dist/browser/util/decode_protected_header.js new file mode 100644 index 0000000..aecbfe2 --- /dev/null +++ b/node_modules/jose/dist/browser/util/decode_protected_header.js @@ -0,0 +1,34 @@ +import { decode as base64url } from './base64url.js'; +import { decoder } from '../lib/buffer_utils.js'; +import isObject from '../lib/is_object.js'; +export function decodeProtectedHeader(token) { + let protectedB64u; + if (typeof token === 'string') { + const parts = token.split('.'); + if (parts.length === 3 || parts.length === 5) { + ; + [protectedB64u] = parts; + } + } + else if (typeof token === 'object' && token) { + if ('protected' in token) { + protectedB64u = token.protected; + } + else { + throw new TypeError('Token does not contain a Protected Header'); + } + } + try { + if (typeof protectedB64u !== 'string' || !protectedB64u) { + throw new Error(); + } + const result = JSON.parse(decoder.decode(base64url(protectedB64u))); + if (!isObject(result)) { + throw new Error(); + } + return result; + } + catch (_a) { + throw new TypeError('Invalid Token or Protected Header formatting'); + } +} diff --git a/node_modules/jose/dist/browser/util/errors.js b/node_modules/jose/dist/browser/util/errors.js new file mode 100644 index 0000000..2998faf --- /dev/null +++ b/node_modules/jose/dist/browser/util/errors.js @@ -0,0 +1,158 @@ +export class JOSEError extends Error { + static get code() { + return 'ERR_JOSE_GENERIC'; + } + constructor(message) { + var _a; + super(message); + this.code = 'ERR_JOSE_GENERIC'; + this.name = this.constructor.name; + (_a = Error.captureStackTrace) === null || _a === void 0 ? void 0 : _a.call(Error, this, this.constructor); + } +} +export class JWTClaimValidationFailed extends JOSEError { + static get code() { + return 'ERR_JWT_CLAIM_VALIDATION_FAILED'; + } + constructor(message, claim = 'unspecified', reason = 'unspecified') { + super(message); + this.code = 'ERR_JWT_CLAIM_VALIDATION_FAILED'; + this.claim = claim; + this.reason = reason; + } +} +export class JWTExpired extends JOSEError { + static get code() { + return 'ERR_JWT_EXPIRED'; + } + constructor(message, claim = 'unspecified', reason = 'unspecified') { + super(message); + this.code = 'ERR_JWT_EXPIRED'; + this.claim = claim; + this.reason = reason; + } +} +export class JOSEAlgNotAllowed extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JOSE_ALG_NOT_ALLOWED'; + } + static get code() { + return 'ERR_JOSE_ALG_NOT_ALLOWED'; + } +} +export class JOSENotSupported extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JOSE_NOT_SUPPORTED'; + } + static get code() { + return 'ERR_JOSE_NOT_SUPPORTED'; + } +} +export class JWEDecryptionFailed extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWE_DECRYPTION_FAILED'; + this.message = 'decryption operation failed'; + } + static get code() { + return 'ERR_JWE_DECRYPTION_FAILED'; + } +} +export class JWEDecompressionFailed extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWE_DECOMPRESSION_FAILED'; + this.message = 'decompression operation failed'; + } + static get code() { + return 'ERR_JWE_DECOMPRESSION_FAILED'; + } +} +export class JWEInvalid extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWE_INVALID'; + } + static get code() { + return 'ERR_JWE_INVALID'; + } +} +export class JWSInvalid extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWS_INVALID'; + } + static get code() { + return 'ERR_JWS_INVALID'; + } +} +export class JWTInvalid extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWT_INVALID'; + } + static get code() { + return 'ERR_JWT_INVALID'; + } +} +export class JWKInvalid extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWK_INVALID'; + } + static get code() { + return 'ERR_JWK_INVALID'; + } +} +export class JWKSInvalid extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWKS_INVALID'; + } + static get code() { + return 'ERR_JWKS_INVALID'; + } +} +export class JWKSNoMatchingKey extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWKS_NO_MATCHING_KEY'; + this.message = 'no applicable key found in the JSON Web Key Set'; + } + static get code() { + return 'ERR_JWKS_NO_MATCHING_KEY'; + } +} +export class JWKSMultipleMatchingKeys extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; + this.message = 'multiple matching keys found in the JSON Web Key Set'; + } + static get code() { + return 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; + } +} +Symbol.asyncIterator; +export class JWKSTimeout extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWKS_TIMEOUT'; + this.message = 'request timed out'; + } + static get code() { + return 'ERR_JWKS_TIMEOUT'; + } +} +export class JWSSignatureVerificationFailed extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; + this.message = 'signature verification failed'; + } + static get code() { + return 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; + } +} diff --git a/node_modules/jose/dist/browser/util/runtime.js b/node_modules/jose/dist/browser/util/runtime.js new file mode 100644 index 0000000..2a4718b --- /dev/null +++ b/node_modules/jose/dist/browser/util/runtime.js @@ -0,0 +1,2 @@ +import value from '../runtime/runtime.js'; +export default value; diff --git a/node_modules/jose/dist/node/cjs/index.js b/node_modules/jose/dist/node/cjs/index.js new file mode 100644 index 0000000..d7aa55c --- /dev/null +++ b/node_modules/jose/dist/node/cjs/index.js @@ -0,0 +1,67 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.cryptoRuntime = exports.base64url = exports.generateSecret = exports.generateKeyPair = exports.errors = exports.decodeJwt = exports.decodeProtectedHeader = exports.importJWK = exports.importX509 = exports.importPKCS8 = exports.importSPKI = exports.exportJWK = exports.exportSPKI = exports.exportPKCS8 = exports.UnsecuredJWT = exports.createRemoteJWKSet = exports.createLocalJWKSet = exports.EmbeddedJWK = exports.calculateJwkThumbprintUri = exports.calculateJwkThumbprint = exports.EncryptJWT = exports.SignJWT = exports.GeneralSign = exports.FlattenedSign = exports.CompactSign = exports.FlattenedEncrypt = exports.CompactEncrypt = exports.jwtDecrypt = exports.jwtVerify = exports.generalVerify = exports.flattenedVerify = exports.compactVerify = exports.GeneralEncrypt = exports.generalDecrypt = exports.flattenedDecrypt = exports.compactDecrypt = void 0; +var decrypt_js_1 = require("./jwe/compact/decrypt.js"); +Object.defineProperty(exports, "compactDecrypt", { enumerable: true, get: function () { return decrypt_js_1.compactDecrypt; } }); +var decrypt_js_2 = require("./jwe/flattened/decrypt.js"); +Object.defineProperty(exports, "flattenedDecrypt", { enumerable: true, get: function () { return decrypt_js_2.flattenedDecrypt; } }); +var decrypt_js_3 = require("./jwe/general/decrypt.js"); +Object.defineProperty(exports, "generalDecrypt", { enumerable: true, get: function () { return decrypt_js_3.generalDecrypt; } }); +var encrypt_js_1 = require("./jwe/general/encrypt.js"); +Object.defineProperty(exports, "GeneralEncrypt", { enumerable: true, get: function () { return encrypt_js_1.GeneralEncrypt; } }); +var verify_js_1 = require("./jws/compact/verify.js"); +Object.defineProperty(exports, "compactVerify", { enumerable: true, get: function () { return verify_js_1.compactVerify; } }); +var verify_js_2 = require("./jws/flattened/verify.js"); +Object.defineProperty(exports, "flattenedVerify", { enumerable: true, get: function () { return verify_js_2.flattenedVerify; } }); +var verify_js_3 = require("./jws/general/verify.js"); +Object.defineProperty(exports, "generalVerify", { enumerable: true, get: function () { return verify_js_3.generalVerify; } }); +var verify_js_4 = require("./jwt/verify.js"); +Object.defineProperty(exports, "jwtVerify", { enumerable: true, get: function () { return verify_js_4.jwtVerify; } }); +var decrypt_js_4 = require("./jwt/decrypt.js"); +Object.defineProperty(exports, "jwtDecrypt", { enumerable: true, get: function () { return decrypt_js_4.jwtDecrypt; } }); +var encrypt_js_2 = require("./jwe/compact/encrypt.js"); +Object.defineProperty(exports, "CompactEncrypt", { enumerable: true, get: function () { return encrypt_js_2.CompactEncrypt; } }); +var encrypt_js_3 = require("./jwe/flattened/encrypt.js"); +Object.defineProperty(exports, "FlattenedEncrypt", { enumerable: true, get: function () { return encrypt_js_3.FlattenedEncrypt; } }); +var sign_js_1 = require("./jws/compact/sign.js"); +Object.defineProperty(exports, "CompactSign", { enumerable: true, get: function () { return sign_js_1.CompactSign; } }); +var sign_js_2 = require("./jws/flattened/sign.js"); +Object.defineProperty(exports, "FlattenedSign", { enumerable: true, get: function () { return sign_js_2.FlattenedSign; } }); +var sign_js_3 = require("./jws/general/sign.js"); +Object.defineProperty(exports, "GeneralSign", { enumerable: true, get: function () { return sign_js_3.GeneralSign; } }); +var sign_js_4 = require("./jwt/sign.js"); +Object.defineProperty(exports, "SignJWT", { enumerable: true, get: function () { return sign_js_4.SignJWT; } }); +var encrypt_js_4 = require("./jwt/encrypt.js"); +Object.defineProperty(exports, "EncryptJWT", { enumerable: true, get: function () { return encrypt_js_4.EncryptJWT; } }); +var thumbprint_js_1 = require("./jwk/thumbprint.js"); +Object.defineProperty(exports, "calculateJwkThumbprint", { enumerable: true, get: function () { return thumbprint_js_1.calculateJwkThumbprint; } }); +Object.defineProperty(exports, "calculateJwkThumbprintUri", { enumerable: true, get: function () { return thumbprint_js_1.calculateJwkThumbprintUri; } }); +var embedded_js_1 = require("./jwk/embedded.js"); +Object.defineProperty(exports, "EmbeddedJWK", { enumerable: true, get: function () { return embedded_js_1.EmbeddedJWK; } }); +var local_js_1 = require("./jwks/local.js"); +Object.defineProperty(exports, "createLocalJWKSet", { enumerable: true, get: function () { return local_js_1.createLocalJWKSet; } }); +var remote_js_1 = require("./jwks/remote.js"); +Object.defineProperty(exports, "createRemoteJWKSet", { enumerable: true, get: function () { return remote_js_1.createRemoteJWKSet; } }); +var unsecured_js_1 = require("./jwt/unsecured.js"); +Object.defineProperty(exports, "UnsecuredJWT", { enumerable: true, get: function () { return unsecured_js_1.UnsecuredJWT; } }); +var export_js_1 = require("./key/export.js"); +Object.defineProperty(exports, "exportPKCS8", { enumerable: true, get: function () { return export_js_1.exportPKCS8; } }); +Object.defineProperty(exports, "exportSPKI", { enumerable: true, get: function () { return export_js_1.exportSPKI; } }); +Object.defineProperty(exports, "exportJWK", { enumerable: true, get: function () { return export_js_1.exportJWK; } }); +var import_js_1 = require("./key/import.js"); +Object.defineProperty(exports, "importSPKI", { enumerable: true, get: function () { return import_js_1.importSPKI; } }); +Object.defineProperty(exports, "importPKCS8", { enumerable: true, get: function () { return import_js_1.importPKCS8; } }); +Object.defineProperty(exports, "importX509", { enumerable: true, get: function () { return import_js_1.importX509; } }); +Object.defineProperty(exports, "importJWK", { enumerable: true, get: function () { return import_js_1.importJWK; } }); +var decode_protected_header_js_1 = require("./util/decode_protected_header.js"); +Object.defineProperty(exports, "decodeProtectedHeader", { enumerable: true, get: function () { return decode_protected_header_js_1.decodeProtectedHeader; } }); +var decode_jwt_js_1 = require("./util/decode_jwt.js"); +Object.defineProperty(exports, "decodeJwt", { enumerable: true, get: function () { return decode_jwt_js_1.decodeJwt; } }); +exports.errors = require("./util/errors.js"); +var generate_key_pair_js_1 = require("./key/generate_key_pair.js"); +Object.defineProperty(exports, "generateKeyPair", { enumerable: true, get: function () { return generate_key_pair_js_1.generateKeyPair; } }); +var generate_secret_js_1 = require("./key/generate_secret.js"); +Object.defineProperty(exports, "generateSecret", { enumerable: true, get: function () { return generate_secret_js_1.generateSecret; } }); +exports.base64url = require("./util/base64url.js"); +var runtime_js_1 = require("./util/runtime.js"); +Object.defineProperty(exports, "cryptoRuntime", { enumerable: true, get: function () { return runtime_js_1.default; } }); diff --git a/node_modules/jose/dist/node/cjs/jwe/compact/decrypt.js b/node_modules/jose/dist/node/cjs/jwe/compact/decrypt.js new file mode 100644 index 0000000..055b3c4 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jwe/compact/decrypt.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.compactDecrypt = void 0; +const decrypt_js_1 = require("../flattened/decrypt.js"); +const errors_js_1 = require("../../util/errors.js"); +const buffer_utils_js_1 = require("../../lib/buffer_utils.js"); +async function compactDecrypt(jwe, key, options) { + if (jwe instanceof Uint8Array) { + jwe = buffer_utils_js_1.decoder.decode(jwe); + } + if (typeof jwe !== 'string') { + throw new errors_js_1.JWEInvalid('Compact JWE must be a string or Uint8Array'); + } + const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length, } = jwe.split('.'); + if (length !== 5) { + throw new errors_js_1.JWEInvalid('Invalid Compact JWE'); + } + const decrypted = await (0, decrypt_js_1.flattenedDecrypt)({ + ciphertext, + iv: (iv || undefined), + protected: protectedHeader || undefined, + tag: (tag || undefined), + encrypted_key: encryptedKey || undefined, + }, key, options); + const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; + if (typeof key === 'function') { + return { ...result, key: decrypted.key }; + } + return result; +} +exports.compactDecrypt = compactDecrypt; diff --git a/node_modules/jose/dist/node/cjs/jwe/compact/encrypt.js b/node_modules/jose/dist/node/cjs/jwe/compact/encrypt.js new file mode 100644 index 0000000..949fbb6 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jwe/compact/encrypt.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CompactEncrypt = void 0; +const encrypt_js_1 = require("../flattened/encrypt.js"); +class CompactEncrypt { + constructor(plaintext) { + this._flattened = new encrypt_js_1.FlattenedEncrypt(plaintext); + } + setContentEncryptionKey(cek) { + this._flattened.setContentEncryptionKey(cek); + return this; + } + setInitializationVector(iv) { + this._flattened.setInitializationVector(iv); + return this; + } + setProtectedHeader(protectedHeader) { + this._flattened.setProtectedHeader(protectedHeader); + return this; + } + setKeyManagementParameters(parameters) { + this._flattened.setKeyManagementParameters(parameters); + return this; + } + async encrypt(key, options) { + const jwe = await this._flattened.encrypt(key, options); + return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.'); + } +} +exports.CompactEncrypt = CompactEncrypt; diff --git a/node_modules/jose/dist/node/cjs/jwe/flattened/decrypt.js b/node_modules/jose/dist/node/cjs/jwe/flattened/decrypt.js new file mode 100644 index 0000000..6281eb0 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jwe/flattened/decrypt.js @@ -0,0 +1,170 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.flattenedDecrypt = void 0; +const base64url_js_1 = require("../../runtime/base64url.js"); +const decrypt_js_1 = require("../../runtime/decrypt.js"); +const zlib_js_1 = require("../../runtime/zlib.js"); +const errors_js_1 = require("../../util/errors.js"); +const is_disjoint_js_1 = require("../../lib/is_disjoint.js"); +const is_object_js_1 = require("../../lib/is_object.js"); +const decrypt_key_management_js_1 = require("../../lib/decrypt_key_management.js"); +const buffer_utils_js_1 = require("../../lib/buffer_utils.js"); +const cek_js_1 = require("../../lib/cek.js"); +const validate_crit_js_1 = require("../../lib/validate_crit.js"); +const validate_algorithms_js_1 = require("../../lib/validate_algorithms.js"); +async function flattenedDecrypt(jwe, key, options) { + var _a; + if (!(0, is_object_js_1.default)(jwe)) { + throw new errors_js_1.JWEInvalid('Flattened JWE must be an object'); + } + if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) { + throw new errors_js_1.JWEInvalid('JOSE Header missing'); + } + if (typeof jwe.iv !== 'string') { + throw new errors_js_1.JWEInvalid('JWE Initialization Vector missing or incorrect type'); + } + if (typeof jwe.ciphertext !== 'string') { + throw new errors_js_1.JWEInvalid('JWE Ciphertext missing or incorrect type'); + } + if (typeof jwe.tag !== 'string') { + throw new errors_js_1.JWEInvalid('JWE Authentication Tag missing or incorrect type'); + } + if (jwe.protected !== undefined && typeof jwe.protected !== 'string') { + throw new errors_js_1.JWEInvalid('JWE Protected Header incorrect type'); + } + if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') { + throw new errors_js_1.JWEInvalid('JWE Encrypted Key incorrect type'); + } + if (jwe.aad !== undefined && typeof jwe.aad !== 'string') { + throw new errors_js_1.JWEInvalid('JWE AAD incorrect type'); + } + if (jwe.header !== undefined && !(0, is_object_js_1.default)(jwe.header)) { + throw new errors_js_1.JWEInvalid('JWE Shared Unprotected Header incorrect type'); + } + if (jwe.unprotected !== undefined && !(0, is_object_js_1.default)(jwe.unprotected)) { + throw new errors_js_1.JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type'); + } + let parsedProt; + if (jwe.protected) { + try { + const protectedHeader = (0, base64url_js_1.decode)(jwe.protected); + parsedProt = JSON.parse(buffer_utils_js_1.decoder.decode(protectedHeader)); + } + catch { + throw new errors_js_1.JWEInvalid('JWE Protected Header is invalid'); + } + } + if (!(0, is_disjoint_js_1.default)(parsedProt, jwe.header, jwe.unprotected)) { + throw new errors_js_1.JWEInvalid('JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint'); + } + const joseHeader = { + ...parsedProt, + ...jwe.header, + ...jwe.unprotected, + }; + (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader); + if (joseHeader.zip !== undefined) { + if (!parsedProt || !parsedProt.zip) { + throw new errors_js_1.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); + } + if (joseHeader.zip !== 'DEF') { + throw new errors_js_1.JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value'); + } + } + const { alg, enc } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new errors_js_1.JWEInvalid('missing JWE Algorithm (alg) in JWE Header'); + } + if (typeof enc !== 'string' || !enc) { + throw new errors_js_1.JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header'); + } + const keyManagementAlgorithms = options && (0, validate_algorithms_js_1.default)('keyManagementAlgorithms', options.keyManagementAlgorithms); + const contentEncryptionAlgorithms = options && + (0, validate_algorithms_js_1.default)('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms); + if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) { + throw new errors_js_1.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed'); + } + if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) { + throw new errors_js_1.JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter not allowed'); + } + let encryptedKey; + if (jwe.encrypted_key !== undefined) { + try { + encryptedKey = (0, base64url_js_1.decode)(jwe.encrypted_key); + } + catch { + throw new errors_js_1.JWEInvalid('Failed to base64url decode the encrypted_key'); + } + } + let resolvedKey = false; + if (typeof key === 'function') { + key = await key(parsedProt, jwe); + resolvedKey = true; + } + let cek; + try { + cek = await (0, decrypt_key_management_js_1.default)(alg, key, encryptedKey, joseHeader, options); + } + catch (err) { + if (err instanceof TypeError || err instanceof errors_js_1.JWEInvalid || err instanceof errors_js_1.JOSENotSupported) { + throw err; + } + cek = (0, cek_js_1.default)(enc); + } + let iv; + let tag; + try { + iv = (0, base64url_js_1.decode)(jwe.iv); + } + catch { + throw new errors_js_1.JWEInvalid('Failed to base64url decode the iv'); + } + try { + tag = (0, base64url_js_1.decode)(jwe.tag); + } + catch { + throw new errors_js_1.JWEInvalid('Failed to base64url decode the tag'); + } + const protectedHeader = buffer_utils_js_1.encoder.encode((_a = jwe.protected) !== null && _a !== void 0 ? _a : ''); + let additionalData; + if (jwe.aad !== undefined) { + additionalData = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), buffer_utils_js_1.encoder.encode(jwe.aad)); + } + else { + additionalData = protectedHeader; + } + let ciphertext; + try { + ciphertext = (0, base64url_js_1.decode)(jwe.ciphertext); + } + catch { + throw new errors_js_1.JWEInvalid('Failed to base64url decode the ciphertext'); + } + let plaintext = await (0, decrypt_js_1.default)(enc, cek, ciphertext, iv, tag, additionalData); + if (joseHeader.zip === 'DEF') { + plaintext = await ((options === null || options === void 0 ? void 0 : options.inflateRaw) || zlib_js_1.inflate)(plaintext); + } + const result = { plaintext }; + if (jwe.protected !== undefined) { + result.protectedHeader = parsedProt; + } + if (jwe.aad !== undefined) { + try { + result.additionalAuthenticatedData = (0, base64url_js_1.decode)(jwe.aad); + } + catch { + throw new errors_js_1.JWEInvalid('Failed to base64url decode the aad'); + } + } + if (jwe.unprotected !== undefined) { + result.sharedUnprotectedHeader = jwe.unprotected; + } + if (jwe.header !== undefined) { + result.unprotectedHeader = jwe.header; + } + if (resolvedKey) { + return { ...result, key }; + } + return result; +} +exports.flattenedDecrypt = flattenedDecrypt; diff --git a/node_modules/jose/dist/node/cjs/jwe/flattened/encrypt.js b/node_modules/jose/dist/node/cjs/jwe/flattened/encrypt.js new file mode 100644 index 0000000..8a69ccf --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jwe/flattened/encrypt.js @@ -0,0 +1,179 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FlattenedEncrypt = exports.unprotected = void 0; +const base64url_js_1 = require("../../runtime/base64url.js"); +const encrypt_js_1 = require("../../runtime/encrypt.js"); +const zlib_js_1 = require("../../runtime/zlib.js"); +const iv_js_1 = require("../../lib/iv.js"); +const encrypt_key_management_js_1 = require("../../lib/encrypt_key_management.js"); +const errors_js_1 = require("../../util/errors.js"); +const is_disjoint_js_1 = require("../../lib/is_disjoint.js"); +const buffer_utils_js_1 = require("../../lib/buffer_utils.js"); +const validate_crit_js_1 = require("../../lib/validate_crit.js"); +exports.unprotected = Symbol(); +class FlattenedEncrypt { + constructor(plaintext) { + if (!(plaintext instanceof Uint8Array)) { + throw new TypeError('plaintext must be an instance of Uint8Array'); + } + this._plaintext = plaintext; + } + setKeyManagementParameters(parameters) { + if (this._keyManagementParameters) { + throw new TypeError('setKeyManagementParameters can only be called once'); + } + this._keyManagementParameters = parameters; + return this; + } + setProtectedHeader(protectedHeader) { + if (this._protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this._protectedHeader = protectedHeader; + return this; + } + setSharedUnprotectedHeader(sharedUnprotectedHeader) { + if (this._sharedUnprotectedHeader) { + throw new TypeError('setSharedUnprotectedHeader can only be called once'); + } + this._sharedUnprotectedHeader = sharedUnprotectedHeader; + return this; + } + setUnprotectedHeader(unprotectedHeader) { + if (this._unprotectedHeader) { + throw new TypeError('setUnprotectedHeader can only be called once'); + } + this._unprotectedHeader = unprotectedHeader; + return this; + } + setAdditionalAuthenticatedData(aad) { + this._aad = aad; + return this; + } + setContentEncryptionKey(cek) { + if (this._cek) { + throw new TypeError('setContentEncryptionKey can only be called once'); + } + this._cek = cek; + return this; + } + setInitializationVector(iv) { + if (this._iv) { + throw new TypeError('setInitializationVector can only be called once'); + } + this._iv = iv; + return this; + } + async encrypt(key, options) { + if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) { + throw new errors_js_1.JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()'); + } + if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) { + throw new errors_js_1.JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); + } + const joseHeader = { + ...this._protectedHeader, + ...this._unprotectedHeader, + ...this._sharedUnprotectedHeader, + }; + (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader); + if (joseHeader.zip !== undefined) { + if (!this._protectedHeader || !this._protectedHeader.zip) { + throw new errors_js_1.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); + } + if (joseHeader.zip !== 'DEF') { + throw new errors_js_1.JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value'); + } + } + const { alg, enc } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new errors_js_1.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); + } + if (typeof enc !== 'string' || !enc) { + throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); + } + let encryptedKey; + if (alg === 'dir') { + if (this._cek) { + throw new TypeError('setContentEncryptionKey cannot be called when using Direct Encryption'); + } + } + else if (alg === 'ECDH-ES') { + if (this._cek) { + throw new TypeError('setContentEncryptionKey cannot be called when using Direct Key Agreement'); + } + } + let cek; + { + let parameters; + ({ cek, encryptedKey, parameters } = await (0, encrypt_key_management_js_1.default)(alg, enc, key, this._cek, this._keyManagementParameters)); + if (parameters) { + if (options && exports.unprotected in options) { + if (!this._unprotectedHeader) { + this.setUnprotectedHeader(parameters); + } + else { + this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters }; + } + } + else { + if (!this._protectedHeader) { + this.setProtectedHeader(parameters); + } + else { + this._protectedHeader = { ...this._protectedHeader, ...parameters }; + } + } + } + } + this._iv || (this._iv = (0, iv_js_1.default)(enc)); + let additionalData; + let protectedHeader; + let aadMember; + if (this._protectedHeader) { + protectedHeader = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(JSON.stringify(this._protectedHeader))); + } + else { + protectedHeader = buffer_utils_js_1.encoder.encode(''); + } + if (this._aad) { + aadMember = (0, base64url_js_1.encode)(this._aad); + additionalData = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), buffer_utils_js_1.encoder.encode(aadMember)); + } + else { + additionalData = protectedHeader; + } + let ciphertext; + let tag; + if (joseHeader.zip === 'DEF') { + const deflated = await ((options === null || options === void 0 ? void 0 : options.deflateRaw) || zlib_js_1.deflate)(this._plaintext); + ({ ciphertext, tag } = await (0, encrypt_js_1.default)(enc, deflated, cek, this._iv, additionalData)); + } + else { + ; + ({ ciphertext, tag } = await (0, encrypt_js_1.default)(enc, this._plaintext, cek, this._iv, additionalData)); + } + const jwe = { + ciphertext: (0, base64url_js_1.encode)(ciphertext), + iv: (0, base64url_js_1.encode)(this._iv), + tag: (0, base64url_js_1.encode)(tag), + }; + if (encryptedKey) { + jwe.encrypted_key = (0, base64url_js_1.encode)(encryptedKey); + } + if (aadMember) { + jwe.aad = aadMember; + } + if (this._protectedHeader) { + jwe.protected = buffer_utils_js_1.decoder.decode(protectedHeader); + } + if (this._sharedUnprotectedHeader) { + jwe.unprotected = this._sharedUnprotectedHeader; + } + if (this._unprotectedHeader) { + jwe.header = this._unprotectedHeader; + } + return jwe; + } +} +exports.FlattenedEncrypt = FlattenedEncrypt; diff --git a/node_modules/jose/dist/node/cjs/jwe/general/decrypt.js b/node_modules/jose/dist/node/cjs/jwe/general/decrypt.js new file mode 100644 index 0000000..accb23a --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jwe/general/decrypt.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.generalDecrypt = void 0; +const decrypt_js_1 = require("../flattened/decrypt.js"); +const errors_js_1 = require("../../util/errors.js"); +const is_object_js_1 = require("../../lib/is_object.js"); +async function generalDecrypt(jwe, key, options) { + if (!(0, is_object_js_1.default)(jwe)) { + throw new errors_js_1.JWEInvalid('General JWE must be an object'); + } + if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(is_object_js_1.default)) { + throw new errors_js_1.JWEInvalid('JWE Recipients missing or incorrect type'); + } + if (!jwe.recipients.length) { + throw new errors_js_1.JWEInvalid('JWE Recipients has no members'); + } + for (const recipient of jwe.recipients) { + try { + return await (0, decrypt_js_1.flattenedDecrypt)({ + aad: jwe.aad, + ciphertext: jwe.ciphertext, + encrypted_key: recipient.encrypted_key, + header: recipient.header, + iv: jwe.iv, + protected: jwe.protected, + tag: jwe.tag, + unprotected: jwe.unprotected, + }, key, options); + } + catch { + } + } + throw new errors_js_1.JWEDecryptionFailed(); +} +exports.generalDecrypt = generalDecrypt; diff --git a/node_modules/jose/dist/node/cjs/jwe/general/encrypt.js b/node_modules/jose/dist/node/cjs/jwe/general/encrypt.js new file mode 100644 index 0000000..3caa084 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jwe/general/encrypt.js @@ -0,0 +1,182 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GeneralEncrypt = void 0; +const encrypt_js_1 = require("../flattened/encrypt.js"); +const errors_js_1 = require("../../util/errors.js"); +const cek_js_1 = require("../../lib/cek.js"); +const is_disjoint_js_1 = require("../../lib/is_disjoint.js"); +const encrypt_key_management_js_1 = require("../../lib/encrypt_key_management.js"); +const base64url_js_1 = require("../../runtime/base64url.js"); +const validate_crit_js_1 = require("../../lib/validate_crit.js"); +class IndividualRecipient { + constructor(enc, key, options) { + this.parent = enc; + this.key = key; + this.options = options; + } + setUnprotectedHeader(unprotectedHeader) { + if (this.unprotectedHeader) { + throw new TypeError('setUnprotectedHeader can only be called once'); + } + this.unprotectedHeader = unprotectedHeader; + return this; + } + addRecipient(...args) { + return this.parent.addRecipient(...args); + } + encrypt(...args) { + return this.parent.encrypt(...args); + } + done() { + return this.parent; + } +} +class GeneralEncrypt { + constructor(plaintext) { + this._recipients = []; + this._plaintext = plaintext; + } + addRecipient(key, options) { + const recipient = new IndividualRecipient(this, key, { crit: options === null || options === void 0 ? void 0 : options.crit }); + this._recipients.push(recipient); + return recipient; + } + setProtectedHeader(protectedHeader) { + if (this._protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this._protectedHeader = protectedHeader; + return this; + } + setSharedUnprotectedHeader(sharedUnprotectedHeader) { + if (this._unprotectedHeader) { + throw new TypeError('setSharedUnprotectedHeader can only be called once'); + } + this._unprotectedHeader = sharedUnprotectedHeader; + return this; + } + setAdditionalAuthenticatedData(aad) { + this._aad = aad; + return this; + } + async encrypt(options) { + var _a, _b, _c; + if (!this._recipients.length) { + throw new errors_js_1.JWEInvalid('at least one recipient must be added'); + } + options = { deflateRaw: options === null || options === void 0 ? void 0 : options.deflateRaw }; + if (this._recipients.length === 1) { + const [recipient] = this._recipients; + const flattened = await new encrypt_js_1.FlattenedEncrypt(this._plaintext) + .setAdditionalAuthenticatedData(this._aad) + .setProtectedHeader(this._protectedHeader) + .setSharedUnprotectedHeader(this._unprotectedHeader) + .setUnprotectedHeader(recipient.unprotectedHeader) + .encrypt(recipient.key, { ...recipient.options, ...options }); + let jwe = { + ciphertext: flattened.ciphertext, + iv: flattened.iv, + recipients: [{}], + tag: flattened.tag, + }; + if (flattened.aad) + jwe.aad = flattened.aad; + if (flattened.protected) + jwe.protected = flattened.protected; + if (flattened.unprotected) + jwe.unprotected = flattened.unprotected; + if (flattened.encrypted_key) + jwe.recipients[0].encrypted_key = flattened.encrypted_key; + if (flattened.header) + jwe.recipients[0].header = flattened.header; + return jwe; + } + let enc; + for (let i = 0; i < this._recipients.length; i++) { + const recipient = this._recipients[i]; + if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) { + throw new errors_js_1.JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); + } + const joseHeader = { + ...this._protectedHeader, + ...this._unprotectedHeader, + ...recipient.unprotectedHeader, + }; + const { alg } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new errors_js_1.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); + } + if (alg === 'dir' || alg === 'ECDH-ES') { + throw new errors_js_1.JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient'); + } + if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) { + throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); + } + if (!enc) { + enc = joseHeader.enc; + } + else if (enc !== joseHeader.enc) { + throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients'); + } + (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader); + if (joseHeader.zip !== undefined) { + if (!this._protectedHeader || !this._protectedHeader.zip) { + throw new errors_js_1.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); + } + } + } + const cek = (0, cek_js_1.default)(enc); + let jwe = { + ciphertext: '', + iv: '', + recipients: [], + tag: '', + }; + for (let i = 0; i < this._recipients.length; i++) { + const recipient = this._recipients[i]; + const target = {}; + jwe.recipients.push(target); + const joseHeader = { + ...this._protectedHeader, + ...this._unprotectedHeader, + ...recipient.unprotectedHeader, + }; + const p2c = joseHeader.alg.startsWith('PBES2') ? 2048 + i : undefined; + if (i === 0) { + const flattened = await new encrypt_js_1.FlattenedEncrypt(this._plaintext) + .setAdditionalAuthenticatedData(this._aad) + .setContentEncryptionKey(cek) + .setProtectedHeader(this._protectedHeader) + .setSharedUnprotectedHeader(this._unprotectedHeader) + .setUnprotectedHeader(recipient.unprotectedHeader) + .setKeyManagementParameters({ p2c }) + .encrypt(recipient.key, { + ...recipient.options, + ...options, + [encrypt_js_1.unprotected]: true, + }); + jwe.ciphertext = flattened.ciphertext; + jwe.iv = flattened.iv; + jwe.tag = flattened.tag; + if (flattened.aad) + jwe.aad = flattened.aad; + if (flattened.protected) + jwe.protected = flattened.protected; + if (flattened.unprotected) + jwe.unprotected = flattened.unprotected; + target.encrypted_key = flattened.encrypted_key; + if (flattened.header) + target.header = flattened.header; + continue; + } + const { encryptedKey, parameters } = await (0, encrypt_key_management_js_1.default)(((_a = recipient.unprotectedHeader) === null || _a === void 0 ? void 0 : _a.alg) || + ((_b = this._protectedHeader) === null || _b === void 0 ? void 0 : _b.alg) || + ((_c = this._unprotectedHeader) === null || _c === void 0 ? void 0 : _c.alg), enc, recipient.key, cek, { p2c }); + target.encrypted_key = (0, base64url_js_1.encode)(encryptedKey); + if (recipient.unprotectedHeader || parameters) + target.header = { ...recipient.unprotectedHeader, ...parameters }; + } + return jwe; + } +} +exports.GeneralEncrypt = GeneralEncrypt; diff --git a/node_modules/jose/dist/node/cjs/jwk/embedded.js b/node_modules/jose/dist/node/cjs/jwk/embedded.js new file mode 100644 index 0000000..47f534f --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jwk/embedded.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EmbeddedJWK = void 0; +const import_js_1 = require("../key/import.js"); +const is_object_js_1 = require("../lib/is_object.js"); +const errors_js_1 = require("../util/errors.js"); +async function EmbeddedJWK(protectedHeader, token) { + const joseHeader = { + ...protectedHeader, + ...token === null || token === void 0 ? void 0 : token.header, + }; + if (!(0, is_object_js_1.default)(joseHeader.jwk)) { + throw new errors_js_1.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object'); + } + const key = await (0, import_js_1.importJWK)({ ...joseHeader.jwk, ext: true }, joseHeader.alg, true); + if (key instanceof Uint8Array || key.type !== 'public') { + throw new errors_js_1.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key'); + } + return key; +} +exports.EmbeddedJWK = EmbeddedJWK; diff --git a/node_modules/jose/dist/node/cjs/jwk/thumbprint.js b/node_modules/jose/dist/node/cjs/jwk/thumbprint.js new file mode 100644 index 0000000..d50e2ba --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jwk/thumbprint.js @@ -0,0 +1,58 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.calculateJwkThumbprintUri = exports.calculateJwkThumbprint = void 0; +const digest_js_1 = require("../runtime/digest.js"); +const base64url_js_1 = require("../runtime/base64url.js"); +const errors_js_1 = require("../util/errors.js"); +const buffer_utils_js_1 = require("../lib/buffer_utils.js"); +const is_object_js_1 = require("../lib/is_object.js"); +const check = (value, description) => { + if (typeof value !== 'string' || !value) { + throw new errors_js_1.JWKInvalid(`${description} missing or invalid`); + } +}; +async function calculateJwkThumbprint(jwk, digestAlgorithm) { + if (!(0, is_object_js_1.default)(jwk)) { + throw new TypeError('JWK must be an object'); + } + digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256'); + if (digestAlgorithm !== 'sha256' && + digestAlgorithm !== 'sha384' && + digestAlgorithm !== 'sha512') { + throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); + } + let components; + switch (jwk.kty) { + case 'EC': + check(jwk.crv, '"crv" (Curve) Parameter'); + check(jwk.x, '"x" (X Coordinate) Parameter'); + check(jwk.y, '"y" (Y Coordinate) Parameter'); + components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; + break; + case 'OKP': + check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); + check(jwk.x, '"x" (Public Key) Parameter'); + components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; + break; + case 'RSA': + check(jwk.e, '"e" (Exponent) Parameter'); + check(jwk.n, '"n" (Modulus) Parameter'); + components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; + break; + case 'oct': + check(jwk.k, '"k" (Key Value) Parameter'); + components = { k: jwk.k, kty: jwk.kty }; + break; + default: + throw new errors_js_1.JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); + } + const data = buffer_utils_js_1.encoder.encode(JSON.stringify(components)); + return (0, base64url_js_1.encode)(await (0, digest_js_1.default)(digestAlgorithm, data)); +} +exports.calculateJwkThumbprint = calculateJwkThumbprint; +async function calculateJwkThumbprintUri(jwk, digestAlgorithm) { + digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256'); + const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm); + return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`; +} +exports.calculateJwkThumbprintUri = calculateJwkThumbprintUri; diff --git a/node_modules/jose/dist/node/cjs/jwks/local.js b/node_modules/jose/dist/node/cjs/jwks/local.js new file mode 100644 index 0000000..f6a7617 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jwks/local.js @@ -0,0 +1,122 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createLocalJWKSet = exports.LocalJWKSet = exports.isJWKSLike = void 0; +const import_js_1 = require("../key/import.js"); +const errors_js_1 = require("../util/errors.js"); +const is_object_js_1 = require("../lib/is_object.js"); +function getKtyFromAlg(alg) { + switch (typeof alg === 'string' && alg.slice(0, 2)) { + case 'RS': + case 'PS': + return 'RSA'; + case 'ES': + return 'EC'; + case 'Ed': + return 'OKP'; + default: + throw new errors_js_1.JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); + } +} +function isJWKSLike(jwks) { + return (jwks && + typeof jwks === 'object' && + Array.isArray(jwks.keys) && + jwks.keys.every(isJWKLike)); +} +exports.isJWKSLike = isJWKSLike; +function isJWKLike(key) { + return (0, is_object_js_1.default)(key); +} +function clone(obj) { + if (typeof structuredClone === 'function') { + return structuredClone(obj); + } + return JSON.parse(JSON.stringify(obj)); +} +class LocalJWKSet { + constructor(jwks) { + this._cached = new WeakMap(); + if (!isJWKSLike(jwks)) { + throw new errors_js_1.JWKSInvalid('JSON Web Key Set malformed'); + } + this._jwks = clone(jwks); + } + async getKey(protectedHeader, token) { + const { alg, kid } = { ...protectedHeader, ...token === null || token === void 0 ? void 0 : token.header }; + const kty = getKtyFromAlg(alg); + const candidates = this._jwks.keys.filter((jwk) => { + let candidate = kty === jwk.kty; + if (candidate && typeof kid === 'string') { + candidate = kid === jwk.kid; + } + if (candidate && typeof jwk.alg === 'string') { + candidate = alg === jwk.alg; + } + if (candidate && typeof jwk.use === 'string') { + candidate = jwk.use === 'sig'; + } + if (candidate && Array.isArray(jwk.key_ops)) { + candidate = jwk.key_ops.includes('verify'); + } + if (candidate && alg === 'EdDSA') { + candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448'; + } + if (candidate) { + switch (alg) { + case 'ES256': + candidate = jwk.crv === 'P-256'; + break; + case 'ES256K': + candidate = jwk.crv === 'secp256k1'; + break; + case 'ES384': + candidate = jwk.crv === 'P-384'; + break; + case 'ES512': + candidate = jwk.crv === 'P-521'; + break; + } + } + return candidate; + }); + const { 0: jwk, length } = candidates; + if (length === 0) { + throw new errors_js_1.JWKSNoMatchingKey(); + } + else if (length !== 1) { + const error = new errors_js_1.JWKSMultipleMatchingKeys(); + const { _cached } = this; + error[Symbol.asyncIterator] = async function* () { + for (const jwk of candidates) { + try { + yield await importWithAlgCache(_cached, jwk, alg); + } + catch { + continue; + } + } + }; + throw error; + } + return importWithAlgCache(this._cached, jwk, alg); + } +} +exports.LocalJWKSet = LocalJWKSet; +async function importWithAlgCache(cache, jwk, alg) { + const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk); + if (cached[alg] === undefined) { + const key = await (0, import_js_1.importJWK)({ ...jwk, ext: true }, alg); + if (key instanceof Uint8Array || key.type !== 'public') { + throw new errors_js_1.JWKSInvalid('JSON Web Key Set members must be public keys'); + } + cached[alg] = key; + } + return cached[alg]; +} +function createLocalJWKSet(jwks) { + const set = new LocalJWKSet(jwks); + return async function (protectedHeader, token) { + return set.getKey(protectedHeader, token); + }; +} +exports.createLocalJWKSet = createLocalJWKSet; diff --git a/node_modules/jose/dist/node/cjs/jwks/remote.js b/node_modules/jose/dist/node/cjs/jwks/remote.js new file mode 100644 index 0000000..9e35571 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jwks/remote.js @@ -0,0 +1,80 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createRemoteJWKSet = void 0; +const fetch_jwks_js_1 = require("../runtime/fetch_jwks.js"); +const errors_js_1 = require("../util/errors.js"); +const local_js_1 = require("./local.js"); +function isCloudflareWorkers() { + return (typeof WebSocketPair !== 'undefined' || + (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') || + (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel')); +} +class RemoteJWKSet extends local_js_1.LocalJWKSet { + constructor(url, options) { + super({ keys: [] }); + this._jwks = undefined; + if (!(url instanceof URL)) { + throw new TypeError('url must be an instance of URL'); + } + this._url = new URL(url.href); + this._options = { agent: options === null || options === void 0 ? void 0 : options.agent, headers: options === null || options === void 0 ? void 0 : options.headers }; + this._timeoutDuration = + typeof (options === null || options === void 0 ? void 0 : options.timeoutDuration) === 'number' ? options === null || options === void 0 ? void 0 : options.timeoutDuration : 5000; + this._cooldownDuration = + typeof (options === null || options === void 0 ? void 0 : options.cooldownDuration) === 'number' ? options === null || options === void 0 ? void 0 : options.cooldownDuration : 30000; + this._cacheMaxAge = typeof (options === null || options === void 0 ? void 0 : options.cacheMaxAge) === 'number' ? options === null || options === void 0 ? void 0 : options.cacheMaxAge : 600000; + } + coolingDown() { + return typeof this._jwksTimestamp === 'number' + ? Date.now() < this._jwksTimestamp + this._cooldownDuration + : false; + } + fresh() { + return typeof this._jwksTimestamp === 'number' + ? Date.now() < this._jwksTimestamp + this._cacheMaxAge + : false; + } + async getKey(protectedHeader, token) { + if (!this._jwks || !this.fresh()) { + await this.reload(); + } + try { + return await super.getKey(protectedHeader, token); + } + catch (err) { + if (err instanceof errors_js_1.JWKSNoMatchingKey) { + if (this.coolingDown() === false) { + await this.reload(); + return super.getKey(protectedHeader, token); + } + } + throw err; + } + } + async reload() { + if (this._pendingFetch && isCloudflareWorkers()) { + this._pendingFetch = undefined; + } + this._pendingFetch || (this._pendingFetch = (0, fetch_jwks_js_1.default)(this._url, this._timeoutDuration, this._options) + .then((json) => { + if (!(0, local_js_1.isJWKSLike)(json)) { + throw new errors_js_1.JWKSInvalid('JSON Web Key Set malformed'); + } + this._jwks = { keys: json.keys }; + this._jwksTimestamp = Date.now(); + this._pendingFetch = undefined; + }) + .catch((err) => { + this._pendingFetch = undefined; + throw err; + })); + await this._pendingFetch; + } +} +function createRemoteJWKSet(url, options) { + const set = new RemoteJWKSet(url, options); + return async function (protectedHeader, token) { + return set.getKey(protectedHeader, token); + }; +} +exports.createRemoteJWKSet = createRemoteJWKSet; diff --git a/node_modules/jose/dist/node/cjs/jws/compact/sign.js b/node_modules/jose/dist/node/cjs/jws/compact/sign.js new file mode 100644 index 0000000..e960ade --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jws/compact/sign.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CompactSign = void 0; +const sign_js_1 = require("../flattened/sign.js"); +class CompactSign { + constructor(payload) { + this._flattened = new sign_js_1.FlattenedSign(payload); + } + setProtectedHeader(protectedHeader) { + this._flattened.setProtectedHeader(protectedHeader); + return this; + } + async sign(key, options) { + const jws = await this._flattened.sign(key, options); + if (jws.payload === undefined) { + throw new TypeError('use the flattened module for creating JWS with b64: false'); + } + return `${jws.protected}.${jws.payload}.${jws.signature}`; + } +} +exports.CompactSign = CompactSign; diff --git a/node_modules/jose/dist/node/cjs/jws/compact/verify.js b/node_modules/jose/dist/node/cjs/jws/compact/verify.js new file mode 100644 index 0000000..b7e6724 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jws/compact/verify.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.compactVerify = void 0; +const verify_js_1 = require("../flattened/verify.js"); +const errors_js_1 = require("../../util/errors.js"); +const buffer_utils_js_1 = require("../../lib/buffer_utils.js"); +async function compactVerify(jws, key, options) { + if (jws instanceof Uint8Array) { + jws = buffer_utils_js_1.decoder.decode(jws); + } + if (typeof jws !== 'string') { + throw new errors_js_1.JWSInvalid('Compact JWS must be a string or Uint8Array'); + } + const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.'); + if (length !== 3) { + throw new errors_js_1.JWSInvalid('Invalid Compact JWS'); + } + const verified = await (0, verify_js_1.flattenedVerify)({ payload, protected: protectedHeader, signature }, key, options); + const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; + if (typeof key === 'function') { + return { ...result, key: verified.key }; + } + return result; +} +exports.compactVerify = compactVerify; diff --git a/node_modules/jose/dist/node/cjs/jws/flattened/sign.js b/node_modules/jose/dist/node/cjs/jws/flattened/sign.js new file mode 100644 index 0000000..2281e97 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jws/flattened/sign.js @@ -0,0 +1,85 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FlattenedSign = void 0; +const base64url_js_1 = require("../../runtime/base64url.js"); +const sign_js_1 = require("../../runtime/sign.js"); +const is_disjoint_js_1 = require("../../lib/is_disjoint.js"); +const errors_js_1 = require("../../util/errors.js"); +const buffer_utils_js_1 = require("../../lib/buffer_utils.js"); +const check_key_type_js_1 = require("../../lib/check_key_type.js"); +const validate_crit_js_1 = require("../../lib/validate_crit.js"); +class FlattenedSign { + constructor(payload) { + if (!(payload instanceof Uint8Array)) { + throw new TypeError('payload must be an instance of Uint8Array'); + } + this._payload = payload; + } + setProtectedHeader(protectedHeader) { + if (this._protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this._protectedHeader = protectedHeader; + return this; + } + setUnprotectedHeader(unprotectedHeader) { + if (this._unprotectedHeader) { + throw new TypeError('setUnprotectedHeader can only be called once'); + } + this._unprotectedHeader = unprotectedHeader; + return this; + } + async sign(key, options) { + if (!this._protectedHeader && !this._unprotectedHeader) { + throw new errors_js_1.JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()'); + } + if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader)) { + throw new errors_js_1.JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); + } + const joseHeader = { + ...this._protectedHeader, + ...this._unprotectedHeader, + }; + const extensions = (0, validate_crit_js_1.default)(errors_js_1.JWSInvalid, new Map([['b64', true]]), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader); + let b64 = true; + if (extensions.has('b64')) { + b64 = this._protectedHeader.b64; + if (typeof b64 !== 'boolean') { + throw new errors_js_1.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); + } + } + const { alg } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new errors_js_1.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); + } + (0, check_key_type_js_1.default)(alg, key, 'sign'); + let payload = this._payload; + if (b64) { + payload = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(payload)); + } + let protectedHeader; + if (this._protectedHeader) { + protectedHeader = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(JSON.stringify(this._protectedHeader))); + } + else { + protectedHeader = buffer_utils_js_1.encoder.encode(''); + } + const data = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), payload); + const signature = await (0, sign_js_1.default)(alg, key, data); + const jws = { + signature: (0, base64url_js_1.encode)(signature), + payload: '', + }; + if (b64) { + jws.payload = buffer_utils_js_1.decoder.decode(payload); + } + if (this._unprotectedHeader) { + jws.header = this._unprotectedHeader; + } + if (this._protectedHeader) { + jws.protected = buffer_utils_js_1.decoder.decode(protectedHeader); + } + return jws; + } +} +exports.FlattenedSign = FlattenedSign; diff --git a/node_modules/jose/dist/node/cjs/jws/flattened/verify.js b/node_modules/jose/dist/node/cjs/jws/flattened/verify.js new file mode 100644 index 0000000..58e78dd --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jws/flattened/verify.js @@ -0,0 +1,119 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.flattenedVerify = void 0; +const base64url_js_1 = require("../../runtime/base64url.js"); +const verify_js_1 = require("../../runtime/verify.js"); +const errors_js_1 = require("../../util/errors.js"); +const buffer_utils_js_1 = require("../../lib/buffer_utils.js"); +const is_disjoint_js_1 = require("../../lib/is_disjoint.js"); +const is_object_js_1 = require("../../lib/is_object.js"); +const check_key_type_js_1 = require("../../lib/check_key_type.js"); +const validate_crit_js_1 = require("../../lib/validate_crit.js"); +const validate_algorithms_js_1 = require("../../lib/validate_algorithms.js"); +async function flattenedVerify(jws, key, options) { + var _a; + if (!(0, is_object_js_1.default)(jws)) { + throw new errors_js_1.JWSInvalid('Flattened JWS must be an object'); + } + if (jws.protected === undefined && jws.header === undefined) { + throw new errors_js_1.JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); + } + if (jws.protected !== undefined && typeof jws.protected !== 'string') { + throw new errors_js_1.JWSInvalid('JWS Protected Header incorrect type'); + } + if (jws.payload === undefined) { + throw new errors_js_1.JWSInvalid('JWS Payload missing'); + } + if (typeof jws.signature !== 'string') { + throw new errors_js_1.JWSInvalid('JWS Signature missing or incorrect type'); + } + if (jws.header !== undefined && !(0, is_object_js_1.default)(jws.header)) { + throw new errors_js_1.JWSInvalid('JWS Unprotected Header incorrect type'); + } + let parsedProt = {}; + if (jws.protected) { + try { + const protectedHeader = (0, base64url_js_1.decode)(jws.protected); + parsedProt = JSON.parse(buffer_utils_js_1.decoder.decode(protectedHeader)); + } + catch { + throw new errors_js_1.JWSInvalid('JWS Protected Header is invalid'); + } + } + if (!(0, is_disjoint_js_1.default)(parsedProt, jws.header)) { + throw new errors_js_1.JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); + } + const joseHeader = { + ...parsedProt, + ...jws.header, + }; + const extensions = (0, validate_crit_js_1.default)(errors_js_1.JWSInvalid, new Map([['b64', true]]), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader); + let b64 = true; + if (extensions.has('b64')) { + b64 = parsedProt.b64; + if (typeof b64 !== 'boolean') { + throw new errors_js_1.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); + } + } + const { alg } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new errors_js_1.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); + } + const algorithms = options && (0, validate_algorithms_js_1.default)('algorithms', options.algorithms); + if (algorithms && !algorithms.has(alg)) { + throw new errors_js_1.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed'); + } + if (b64) { + if (typeof jws.payload !== 'string') { + throw new errors_js_1.JWSInvalid('JWS Payload must be a string'); + } + } + else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) { + throw new errors_js_1.JWSInvalid('JWS Payload must be a string or an Uint8Array instance'); + } + let resolvedKey = false; + if (typeof key === 'function') { + key = await key(parsedProt, jws); + resolvedKey = true; + } + (0, check_key_type_js_1.default)(alg, key, 'verify'); + const data = (0, buffer_utils_js_1.concat)(buffer_utils_js_1.encoder.encode((_a = jws.protected) !== null && _a !== void 0 ? _a : ''), buffer_utils_js_1.encoder.encode('.'), typeof jws.payload === 'string' ? buffer_utils_js_1.encoder.encode(jws.payload) : jws.payload); + let signature; + try { + signature = (0, base64url_js_1.decode)(jws.signature); + } + catch { + throw new errors_js_1.JWSInvalid('Failed to base64url decode the signature'); + } + const verified = await (0, verify_js_1.default)(alg, key, signature, data); + if (!verified) { + throw new errors_js_1.JWSSignatureVerificationFailed(); + } + let payload; + if (b64) { + try { + payload = (0, base64url_js_1.decode)(jws.payload); + } + catch { + throw new errors_js_1.JWSInvalid('Failed to base64url decode the payload'); + } + } + else if (typeof jws.payload === 'string') { + payload = buffer_utils_js_1.encoder.encode(jws.payload); + } + else { + payload = jws.payload; + } + const result = { payload }; + if (jws.protected !== undefined) { + result.protectedHeader = parsedProt; + } + if (jws.header !== undefined) { + result.unprotectedHeader = jws.header; + } + if (resolvedKey) { + return { ...result, key }; + } + return result; +} +exports.flattenedVerify = flattenedVerify; diff --git a/node_modules/jose/dist/node/cjs/jws/general/sign.js b/node_modules/jose/dist/node/cjs/jws/general/sign.js new file mode 100644 index 0000000..b5362cf --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jws/general/sign.js @@ -0,0 +1,71 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GeneralSign = void 0; +const sign_js_1 = require("../flattened/sign.js"); +const errors_js_1 = require("../../util/errors.js"); +class IndividualSignature { + constructor(sig, key, options) { + this.parent = sig; + this.key = key; + this.options = options; + } + setProtectedHeader(protectedHeader) { + if (this.protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this.protectedHeader = protectedHeader; + return this; + } + setUnprotectedHeader(unprotectedHeader) { + if (this.unprotectedHeader) { + throw new TypeError('setUnprotectedHeader can only be called once'); + } + this.unprotectedHeader = unprotectedHeader; + return this; + } + addSignature(...args) { + return this.parent.addSignature(...args); + } + sign(...args) { + return this.parent.sign(...args); + } + done() { + return this.parent; + } +} +class GeneralSign { + constructor(payload) { + this._signatures = []; + this._payload = payload; + } + addSignature(key, options) { + const signature = new IndividualSignature(this, key, options); + this._signatures.push(signature); + return signature; + } + async sign() { + if (!this._signatures.length) { + throw new errors_js_1.JWSInvalid('at least one signature must be added'); + } + const jws = { + signatures: [], + payload: '', + }; + for (let i = 0; i < this._signatures.length; i++) { + const signature = this._signatures[i]; + const flattened = new sign_js_1.FlattenedSign(this._payload); + flattened.setProtectedHeader(signature.protectedHeader); + flattened.setUnprotectedHeader(signature.unprotectedHeader); + const { payload, ...rest } = await flattened.sign(signature.key, signature.options); + if (i === 0) { + jws.payload = payload; + } + else if (jws.payload !== payload) { + throw new errors_js_1.JWSInvalid('inconsistent use of JWS Unencoded Payload (RFC7797)'); + } + jws.signatures.push(rest); + } + return jws; + } +} +exports.GeneralSign = GeneralSign; diff --git a/node_modules/jose/dist/node/cjs/jws/general/verify.js b/node_modules/jose/dist/node/cjs/jws/general/verify.js new file mode 100644 index 0000000..9d4a07a --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jws/general/verify.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.generalVerify = void 0; +const verify_js_1 = require("../flattened/verify.js"); +const errors_js_1 = require("../../util/errors.js"); +const is_object_js_1 = require("../../lib/is_object.js"); +async function generalVerify(jws, key, options) { + if (!(0, is_object_js_1.default)(jws)) { + throw new errors_js_1.JWSInvalid('General JWS must be an object'); + } + if (!Array.isArray(jws.signatures) || !jws.signatures.every(is_object_js_1.default)) { + throw new errors_js_1.JWSInvalid('JWS Signatures missing or incorrect type'); + } + for (const signature of jws.signatures) { + try { + return await (0, verify_js_1.flattenedVerify)({ + header: signature.header, + payload: jws.payload, + protected: signature.protected, + signature: signature.signature, + }, key, options); + } + catch { + } + } + throw new errors_js_1.JWSSignatureVerificationFailed(); +} +exports.generalVerify = generalVerify; diff --git a/node_modules/jose/dist/node/cjs/jwt/decrypt.js b/node_modules/jose/dist/node/cjs/jwt/decrypt.js new file mode 100644 index 0000000..3539cea --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jwt/decrypt.js @@ -0,0 +1,27 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.jwtDecrypt = void 0; +const decrypt_js_1 = require("../jwe/compact/decrypt.js"); +const jwt_claims_set_js_1 = require("../lib/jwt_claims_set.js"); +const errors_js_1 = require("../util/errors.js"); +async function jwtDecrypt(jwt, key, options) { + const decrypted = await (0, decrypt_js_1.compactDecrypt)(jwt, key, options); + const payload = (0, jwt_claims_set_js_1.default)(decrypted.protectedHeader, decrypted.plaintext, options); + const { protectedHeader } = decrypted; + if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) { + throw new errors_js_1.JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', 'iss', 'mismatch'); + } + if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) { + throw new errors_js_1.JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', 'sub', 'mismatch'); + } + if (protectedHeader.aud !== undefined && + JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) { + throw new errors_js_1.JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', 'aud', 'mismatch'); + } + const result = { payload, protectedHeader }; + if (typeof key === 'function') { + return { ...result, key: decrypted.key }; + } + return result; +} +exports.jwtDecrypt = jwtDecrypt; diff --git a/node_modules/jose/dist/node/cjs/jwt/encrypt.js b/node_modules/jose/dist/node/cjs/jwt/encrypt.js new file mode 100644 index 0000000..8ce18f1 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jwt/encrypt.js @@ -0,0 +1,72 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EncryptJWT = void 0; +const encrypt_js_1 = require("../jwe/compact/encrypt.js"); +const buffer_utils_js_1 = require("../lib/buffer_utils.js"); +const produce_js_1 = require("./produce.js"); +class EncryptJWT extends produce_js_1.ProduceJWT { + setProtectedHeader(protectedHeader) { + if (this._protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this._protectedHeader = protectedHeader; + return this; + } + setKeyManagementParameters(parameters) { + if (this._keyManagementParameters) { + throw new TypeError('setKeyManagementParameters can only be called once'); + } + this._keyManagementParameters = parameters; + return this; + } + setContentEncryptionKey(cek) { + if (this._cek) { + throw new TypeError('setContentEncryptionKey can only be called once'); + } + this._cek = cek; + return this; + } + setInitializationVector(iv) { + if (this._iv) { + throw new TypeError('setInitializationVector can only be called once'); + } + this._iv = iv; + return this; + } + replicateIssuerAsHeader() { + this._replicateIssuerAsHeader = true; + return this; + } + replicateSubjectAsHeader() { + this._replicateSubjectAsHeader = true; + return this; + } + replicateAudienceAsHeader() { + this._replicateAudienceAsHeader = true; + return this; + } + async encrypt(key, options) { + const enc = new encrypt_js_1.CompactEncrypt(buffer_utils_js_1.encoder.encode(JSON.stringify(this._payload))); + if (this._replicateIssuerAsHeader) { + this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss }; + } + if (this._replicateSubjectAsHeader) { + this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub }; + } + if (this._replicateAudienceAsHeader) { + this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud }; + } + enc.setProtectedHeader(this._protectedHeader); + if (this._iv) { + enc.setInitializationVector(this._iv); + } + if (this._cek) { + enc.setContentEncryptionKey(this._cek); + } + if (this._keyManagementParameters) { + enc.setKeyManagementParameters(this._keyManagementParameters); + } + return enc.encrypt(key, options); + } +} +exports.EncryptJWT = EncryptJWT; diff --git a/node_modules/jose/dist/node/cjs/jwt/produce.js b/node_modules/jose/dist/node/cjs/jwt/produce.js new file mode 100644 index 0000000..54d9ccb --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jwt/produce.js @@ -0,0 +1,58 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProduceJWT = void 0; +const epoch_js_1 = require("../lib/epoch.js"); +const is_object_js_1 = require("../lib/is_object.js"); +const secs_js_1 = require("../lib/secs.js"); +class ProduceJWT { + constructor(payload) { + if (!(0, is_object_js_1.default)(payload)) { + throw new TypeError('JWT Claims Set MUST be an object'); + } + this._payload = payload; + } + setIssuer(issuer) { + this._payload = { ...this._payload, iss: issuer }; + return this; + } + setSubject(subject) { + this._payload = { ...this._payload, sub: subject }; + return this; + } + setAudience(audience) { + this._payload = { ...this._payload, aud: audience }; + return this; + } + setJti(jwtId) { + this._payload = { ...this._payload, jti: jwtId }; + return this; + } + setNotBefore(input) { + if (typeof input === 'number') { + this._payload = { ...this._payload, nbf: input }; + } + else { + this._payload = { ...this._payload, nbf: (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input) }; + } + return this; + } + setExpirationTime(input) { + if (typeof input === 'number') { + this._payload = { ...this._payload, exp: input }; + } + else { + this._payload = { ...this._payload, exp: (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input) }; + } + return this; + } + setIssuedAt(input) { + if (typeof input === 'undefined') { + this._payload = { ...this._payload, iat: (0, epoch_js_1.default)(new Date()) }; + } + else { + this._payload = { ...this._payload, iat: input }; + } + return this; + } +} +exports.ProduceJWT = ProduceJWT; diff --git a/node_modules/jose/dist/node/cjs/jwt/sign.js b/node_modules/jose/dist/node/cjs/jwt/sign.js new file mode 100644 index 0000000..ad9193c --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jwt/sign.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SignJWT = void 0; +const sign_js_1 = require("../jws/compact/sign.js"); +const errors_js_1 = require("../util/errors.js"); +const buffer_utils_js_1 = require("../lib/buffer_utils.js"); +const produce_js_1 = require("./produce.js"); +class SignJWT extends produce_js_1.ProduceJWT { + setProtectedHeader(protectedHeader) { + this._protectedHeader = protectedHeader; + return this; + } + async sign(key, options) { + var _a; + const sig = new sign_js_1.CompactSign(buffer_utils_js_1.encoder.encode(JSON.stringify(this._payload))); + sig.setProtectedHeader(this._protectedHeader); + if (Array.isArray((_a = this._protectedHeader) === null || _a === void 0 ? void 0 : _a.crit) && + this._protectedHeader.crit.includes('b64') && + this._protectedHeader.b64 === false) { + throw new errors_js_1.JWTInvalid('JWTs MUST NOT use unencoded payload'); + } + return sig.sign(key, options); + } +} +exports.SignJWT = SignJWT; diff --git a/node_modules/jose/dist/node/cjs/jwt/unsecured.js b/node_modules/jose/dist/node/cjs/jwt/unsecured.js new file mode 100644 index 0000000..482782f --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jwt/unsecured.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UnsecuredJWT = void 0; +const base64url = require("../runtime/base64url.js"); +const buffer_utils_js_1 = require("../lib/buffer_utils.js"); +const errors_js_1 = require("../util/errors.js"); +const jwt_claims_set_js_1 = require("../lib/jwt_claims_set.js"); +const produce_js_1 = require("./produce.js"); +class UnsecuredJWT extends produce_js_1.ProduceJWT { + encode() { + const header = base64url.encode(JSON.stringify({ alg: 'none' })); + const payload = base64url.encode(JSON.stringify(this._payload)); + return `${header}.${payload}.`; + } + static decode(jwt, options) { + if (typeof jwt !== 'string') { + throw new errors_js_1.JWTInvalid('Unsecured JWT must be a string'); + } + const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.'); + if (length !== 3 || signature !== '') { + throw new errors_js_1.JWTInvalid('Invalid Unsecured JWT'); + } + let header; + try { + header = JSON.parse(buffer_utils_js_1.decoder.decode(base64url.decode(encodedHeader))); + if (header.alg !== 'none') + throw new Error(); + } + catch { + throw new errors_js_1.JWTInvalid('Invalid Unsecured JWT'); + } + const payload = (0, jwt_claims_set_js_1.default)(header, base64url.decode(encodedPayload), options); + return { payload, header }; + } +} +exports.UnsecuredJWT = UnsecuredJWT; diff --git a/node_modules/jose/dist/node/cjs/jwt/verify.js b/node_modules/jose/dist/node/cjs/jwt/verify.js new file mode 100644 index 0000000..d77bb96 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/jwt/verify.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.jwtVerify = void 0; +const verify_js_1 = require("../jws/compact/verify.js"); +const jwt_claims_set_js_1 = require("../lib/jwt_claims_set.js"); +const errors_js_1 = require("../util/errors.js"); +async function jwtVerify(jwt, key, options) { + var _a; + const verified = await (0, verify_js_1.compactVerify)(jwt, key, options); + if (((_a = verified.protectedHeader.crit) === null || _a === void 0 ? void 0 : _a.includes('b64')) && verified.protectedHeader.b64 === false) { + throw new errors_js_1.JWTInvalid('JWTs MUST NOT use unencoded payload'); + } + const payload = (0, jwt_claims_set_js_1.default)(verified.protectedHeader, verified.payload, options); + const result = { payload, protectedHeader: verified.protectedHeader }; + if (typeof key === 'function') { + return { ...result, key: verified.key }; + } + return result; +} +exports.jwtVerify = jwtVerify; diff --git a/node_modules/jose/dist/node/cjs/key/export.js b/node_modules/jose/dist/node/cjs/key/export.js new file mode 100644 index 0000000..1c083ef --- /dev/null +++ b/node_modules/jose/dist/node/cjs/key/export.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.exportJWK = exports.exportPKCS8 = exports.exportSPKI = void 0; +const asn1_js_1 = require("../runtime/asn1.js"); +const asn1_js_2 = require("../runtime/asn1.js"); +const key_to_jwk_js_1 = require("../runtime/key_to_jwk.js"); +async function exportSPKI(key) { + return (0, asn1_js_1.toSPKI)(key); +} +exports.exportSPKI = exportSPKI; +async function exportPKCS8(key) { + return (0, asn1_js_2.toPKCS8)(key); +} +exports.exportPKCS8 = exportPKCS8; +async function exportJWK(key) { + return (0, key_to_jwk_js_1.default)(key); +} +exports.exportJWK = exportJWK; diff --git a/node_modules/jose/dist/node/cjs/key/generate_key_pair.js b/node_modules/jose/dist/node/cjs/key/generate_key_pair.js new file mode 100644 index 0000000..3d14da5 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/key/generate_key_pair.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.generateKeyPair = void 0; +const generate_js_1 = require("../runtime/generate.js"); +async function generateKeyPair(alg, options) { + return (0, generate_js_1.generateKeyPair)(alg, options); +} +exports.generateKeyPair = generateKeyPair; diff --git a/node_modules/jose/dist/node/cjs/key/generate_secret.js b/node_modules/jose/dist/node/cjs/key/generate_secret.js new file mode 100644 index 0000000..5f3c9ba --- /dev/null +++ b/node_modules/jose/dist/node/cjs/key/generate_secret.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.generateSecret = void 0; +const generate_js_1 = require("../runtime/generate.js"); +async function generateSecret(alg, options) { + return (0, generate_js_1.generateSecret)(alg, options); +} +exports.generateSecret = generateSecret; diff --git a/node_modules/jose/dist/node/cjs/key/import.js b/node_modules/jose/dist/node/cjs/key/import.js new file mode 100644 index 0000000..e12b288 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/key/import.js @@ -0,0 +1,57 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.importJWK = exports.importPKCS8 = exports.importX509 = exports.importSPKI = void 0; +const base64url_js_1 = require("../runtime/base64url.js"); +const asn1_js_1 = require("../runtime/asn1.js"); +const jwk_to_key_js_1 = require("../runtime/jwk_to_key.js"); +const errors_js_1 = require("../util/errors.js"); +const is_object_js_1 = require("../lib/is_object.js"); +async function importSPKI(spki, alg, options) { + if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) { + throw new TypeError('"spki" must be SPKI formatted string'); + } + return (0, asn1_js_1.fromSPKI)(spki, alg, options); +} +exports.importSPKI = importSPKI; +async function importX509(x509, alg, options) { + if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) { + throw new TypeError('"x509" must be X.509 formatted string'); + } + return (0, asn1_js_1.fromX509)(x509, alg, options); +} +exports.importX509 = importX509; +async function importPKCS8(pkcs8, alg, options) { + if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) { + throw new TypeError('"pkcs8" must be PKCS#8 formatted string'); + } + return (0, asn1_js_1.fromPKCS8)(pkcs8, alg, options); +} +exports.importPKCS8 = importPKCS8; +async function importJWK(jwk, alg, octAsKeyObject) { + var _a; + if (!(0, is_object_js_1.default)(jwk)) { + throw new TypeError('JWK must be an object'); + } + alg || (alg = jwk.alg); + switch (jwk.kty) { + case 'oct': + if (typeof jwk.k !== 'string' || !jwk.k) { + throw new TypeError('missing "k" (Key Value) Parameter value'); + } + octAsKeyObject !== null && octAsKeyObject !== void 0 ? octAsKeyObject : (octAsKeyObject = jwk.ext !== true); + if (octAsKeyObject) { + return (0, jwk_to_key_js_1.default)({ ...jwk, alg, ext: (_a = jwk.ext) !== null && _a !== void 0 ? _a : false }); + } + return (0, base64url_js_1.decode)(jwk.k); + case 'RSA': + if (jwk.oth !== undefined) { + throw new errors_js_1.JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); + } + case 'EC': + case 'OKP': + return (0, jwk_to_key_js_1.default)({ ...jwk, alg }); + default: + throw new errors_js_1.JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); + } +} +exports.importJWK = importJWK; diff --git a/node_modules/jose/dist/node/cjs/lib/aesgcmkw.js b/node_modules/jose/dist/node/cjs/lib/aesgcmkw.js new file mode 100644 index 0000000..c3e61e8 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/lib/aesgcmkw.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.unwrap = exports.wrap = void 0; +const encrypt_js_1 = require("../runtime/encrypt.js"); +const decrypt_js_1 = require("../runtime/decrypt.js"); +const iv_js_1 = require("./iv.js"); +const base64url_js_1 = require("../runtime/base64url.js"); +async function wrap(alg, key, cek, iv) { + const jweAlgorithm = alg.slice(0, 7); + iv || (iv = (0, iv_js_1.default)(jweAlgorithm)); + const { ciphertext: encryptedKey, tag } = await (0, encrypt_js_1.default)(jweAlgorithm, cek, key, iv, new Uint8Array(0)); + return { encryptedKey, iv: (0, base64url_js_1.encode)(iv), tag: (0, base64url_js_1.encode)(tag) }; +} +exports.wrap = wrap; +async function unwrap(alg, key, encryptedKey, iv, tag) { + const jweAlgorithm = alg.slice(0, 7); + return (0, decrypt_js_1.default)(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0)); +} +exports.unwrap = unwrap; diff --git a/node_modules/jose/dist/node/cjs/lib/buffer_utils.js b/node_modules/jose/dist/node/cjs/lib/buffer_utils.js new file mode 100644 index 0000000..7932178 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/lib/buffer_utils.js @@ -0,0 +1,60 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.concatKdf = exports.lengthAndInput = exports.uint32be = exports.uint64be = exports.p2s = exports.concat = exports.decoder = exports.encoder = void 0; +const digest_js_1 = require("../runtime/digest.js"); +exports.encoder = new TextEncoder(); +exports.decoder = new TextDecoder(); +const MAX_INT32 = 2 ** 32; +function concat(...buffers) { + const size = buffers.reduce((acc, { length }) => acc + length, 0); + const buf = new Uint8Array(size); + let i = 0; + buffers.forEach((buffer) => { + buf.set(buffer, i); + i += buffer.length; + }); + return buf; +} +exports.concat = concat; +function p2s(alg, p2sInput) { + return concat(exports.encoder.encode(alg), new Uint8Array([0]), p2sInput); +} +exports.p2s = p2s; +function writeUInt32BE(buf, value, offset) { + if (value < 0 || value >= MAX_INT32) { + throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); + } + buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset); +} +function uint64be(value) { + const high = Math.floor(value / MAX_INT32); + const low = value % MAX_INT32; + const buf = new Uint8Array(8); + writeUInt32BE(buf, high, 0); + writeUInt32BE(buf, low, 4); + return buf; +} +exports.uint64be = uint64be; +function uint32be(value) { + const buf = new Uint8Array(4); + writeUInt32BE(buf, value); + return buf; +} +exports.uint32be = uint32be; +function lengthAndInput(input) { + return concat(uint32be(input.length), input); +} +exports.lengthAndInput = lengthAndInput; +async function concatKdf(secret, bits, value) { + const iterations = Math.ceil((bits >> 3) / 32); + const res = new Uint8Array(iterations * 32); + for (let iter = 0; iter < iterations; iter++) { + const buf = new Uint8Array(4 + secret.length + value.length); + buf.set(uint32be(iter + 1)); + buf.set(secret, 4); + buf.set(value, 4 + secret.length); + res.set(await (0, digest_js_1.default)('sha256', buf), iter * 32); + } + return res.slice(0, bits >> 3); +} +exports.concatKdf = concatKdf; diff --git a/node_modules/jose/dist/node/cjs/lib/cek.js b/node_modules/jose/dist/node/cjs/lib/cek.js new file mode 100644 index 0000000..e4a0133 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/lib/cek.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bitLength = void 0; +const errors_js_1 = require("../util/errors.js"); +const random_js_1 = require("../runtime/random.js"); +function bitLength(alg) { + switch (alg) { + case 'A128GCM': + return 128; + case 'A192GCM': + return 192; + case 'A256GCM': + case 'A128CBC-HS256': + return 256; + case 'A192CBC-HS384': + return 384; + case 'A256CBC-HS512': + return 512; + default: + throw new errors_js_1.JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); + } +} +exports.bitLength = bitLength; +exports.default = (alg) => (0, random_js_1.default)(new Uint8Array(bitLength(alg) >> 3)); diff --git a/node_modules/jose/dist/node/cjs/lib/check_iv_length.js b/node_modules/jose/dist/node/cjs/lib/check_iv_length.js new file mode 100644 index 0000000..3fbee85 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/lib/check_iv_length.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const errors_js_1 = require("../util/errors.js"); +const iv_js_1 = require("./iv.js"); +const checkIvLength = (enc, iv) => { + if (iv.length << 3 !== (0, iv_js_1.bitLength)(enc)) { + throw new errors_js_1.JWEInvalid('Invalid Initialization Vector length'); + } +}; +exports.default = checkIvLength; diff --git a/node_modules/jose/dist/node/cjs/lib/check_key_type.js b/node_modules/jose/dist/node/cjs/lib/check_key_type.js new file mode 100644 index 0000000..5035f81 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/lib/check_key_type.js @@ -0,0 +1,47 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const invalid_key_input_js_1 = require("./invalid_key_input.js"); +const is_key_like_js_1 = require("../runtime/is_key_like.js"); +const symmetricTypeCheck = (alg, key) => { + if (key instanceof Uint8Array) + return; + if (!(0, is_key_like_js_1.default)(key)) { + throw new TypeError((0, invalid_key_input_js_1.withAlg)(alg, key, ...is_key_like_js_1.types, 'Uint8Array')); + } + if (key.type !== 'secret') { + throw new TypeError(`${is_key_like_js_1.types.join(' or ')} instances for symmetric algorithms must be of type "secret"`); + } +}; +const asymmetricTypeCheck = (alg, key, usage) => { + if (!(0, is_key_like_js_1.default)(key)) { + throw new TypeError((0, invalid_key_input_js_1.withAlg)(alg, key, ...is_key_like_js_1.types)); + } + if (key.type === 'secret') { + throw new TypeError(`${is_key_like_js_1.types.join(' or ')} instances for asymmetric algorithms must not be of type "secret"`); + } + if (usage === 'sign' && key.type === 'public') { + throw new TypeError(`${is_key_like_js_1.types.join(' or ')} instances for asymmetric algorithm signing must be of type "private"`); + } + if (usage === 'decrypt' && key.type === 'public') { + throw new TypeError(`${is_key_like_js_1.types.join(' or ')} instances for asymmetric algorithm decryption must be of type "private"`); + } + if (key.algorithm && usage === 'verify' && key.type === 'private') { + throw new TypeError(`${is_key_like_js_1.types.join(' or ')} instances for asymmetric algorithm verifying must be of type "public"`); + } + if (key.algorithm && usage === 'encrypt' && key.type === 'private') { + throw new TypeError(`${is_key_like_js_1.types.join(' or ')} instances for asymmetric algorithm encryption must be of type "public"`); + } +}; +const checkKeyType = (alg, key, usage) => { + const symmetric = alg.startsWith('HS') || + alg === 'dir' || + alg.startsWith('PBES2') || + /^A\d{3}(?:GCM)?KW$/.test(alg); + if (symmetric) { + symmetricTypeCheck(alg, key); + } + else { + asymmetricTypeCheck(alg, key, usage); + } +}; +exports.default = checkKeyType; diff --git a/node_modules/jose/dist/node/cjs/lib/check_p2s.js b/node_modules/jose/dist/node/cjs/lib/check_p2s.js new file mode 100644 index 0000000..4bdeaa7 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/lib/check_p2s.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const errors_js_1 = require("../util/errors.js"); +function checkP2s(p2s) { + if (!(p2s instanceof Uint8Array) || p2s.length < 8) { + throw new errors_js_1.JWEInvalid('PBES2 Salt Input must be 8 or more octets'); + } +} +exports.default = checkP2s; diff --git a/node_modules/jose/dist/node/cjs/lib/crypto_key.js b/node_modules/jose/dist/node/cjs/lib/crypto_key.js new file mode 100644 index 0000000..b1acdbd --- /dev/null +++ b/node_modules/jose/dist/node/cjs/lib/crypto_key.js @@ -0,0 +1,157 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.checkEncCryptoKey = exports.checkSigCryptoKey = void 0; +function unusable(name, prop = 'algorithm.name') { + return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); +} +function isAlgorithm(algorithm, name) { + return algorithm.name === name; +} +function getHashLength(hash) { + return parseInt(hash.name.slice(4), 10); +} +function getNamedCurve(alg) { + switch (alg) { + case 'ES256': + return 'P-256'; + case 'ES384': + return 'P-384'; + case 'ES512': + return 'P-521'; + default: + throw new Error('unreachable'); + } +} +function checkUsage(key, usages) { + if (usages.length && !usages.some((expected) => key.usages.includes(expected))) { + let msg = 'CryptoKey does not support this operation, its usages must include '; + if (usages.length > 2) { + const last = usages.pop(); + msg += `one of ${usages.join(', ')}, or ${last}.`; + } + else if (usages.length === 2) { + msg += `one of ${usages[0]} or ${usages[1]}.`; + } + else { + msg += `${usages[0]}.`; + } + throw new TypeError(msg); + } +} +function checkSigCryptoKey(key, alg, ...usages) { + switch (alg) { + case 'HS256': + case 'HS384': + case 'HS512': { + if (!isAlgorithm(key.algorithm, 'HMAC')) + throw unusable('HMAC'); + const expected = parseInt(alg.slice(2), 10); + const actual = getHashLength(key.algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, 'algorithm.hash'); + break; + } + case 'RS256': + case 'RS384': + case 'RS512': { + if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5')) + throw unusable('RSASSA-PKCS1-v1_5'); + const expected = parseInt(alg.slice(2), 10); + const actual = getHashLength(key.algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, 'algorithm.hash'); + break; + } + case 'PS256': + case 'PS384': + case 'PS512': { + if (!isAlgorithm(key.algorithm, 'RSA-PSS')) + throw unusable('RSA-PSS'); + const expected = parseInt(alg.slice(2), 10); + const actual = getHashLength(key.algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, 'algorithm.hash'); + break; + } + case 'EdDSA': { + if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') { + throw unusable('Ed25519 or Ed448'); + } + break; + } + case 'ES256': + case 'ES384': + case 'ES512': { + if (!isAlgorithm(key.algorithm, 'ECDSA')) + throw unusable('ECDSA'); + const expected = getNamedCurve(alg); + const actual = key.algorithm.namedCurve; + if (actual !== expected) + throw unusable(expected, 'algorithm.namedCurve'); + break; + } + default: + throw new TypeError('CryptoKey does not support this operation'); + } + checkUsage(key, usages); +} +exports.checkSigCryptoKey = checkSigCryptoKey; +function checkEncCryptoKey(key, alg, ...usages) { + switch (alg) { + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': { + if (!isAlgorithm(key.algorithm, 'AES-GCM')) + throw unusable('AES-GCM'); + const expected = parseInt(alg.slice(1, 4), 10); + const actual = key.algorithm.length; + if (actual !== expected) + throw unusable(expected, 'algorithm.length'); + break; + } + case 'A128KW': + case 'A192KW': + case 'A256KW': { + if (!isAlgorithm(key.algorithm, 'AES-KW')) + throw unusable('AES-KW'); + const expected = parseInt(alg.slice(1, 4), 10); + const actual = key.algorithm.length; + if (actual !== expected) + throw unusable(expected, 'algorithm.length'); + break; + } + case 'ECDH': { + switch (key.algorithm.name) { + case 'ECDH': + case 'X25519': + case 'X448': + break; + default: + throw unusable('ECDH, X25519, or X448'); + } + break; + } + case 'PBES2-HS256+A128KW': + case 'PBES2-HS384+A192KW': + case 'PBES2-HS512+A256KW': + if (!isAlgorithm(key.algorithm, 'PBKDF2')) + throw unusable('PBKDF2'); + break; + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': { + if (!isAlgorithm(key.algorithm, 'RSA-OAEP')) + throw unusable('RSA-OAEP'); + const expected = parseInt(alg.slice(9), 10) || 1; + const actual = getHashLength(key.algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, 'algorithm.hash'); + break; + } + default: + throw new TypeError('CryptoKey does not support this operation'); + } + checkUsage(key, usages); +} +exports.checkEncCryptoKey = checkEncCryptoKey; diff --git a/node_modules/jose/dist/node/cjs/lib/decrypt_key_management.js b/node_modules/jose/dist/node/cjs/lib/decrypt_key_management.js new file mode 100644 index 0000000..aea5c89 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/lib/decrypt_key_management.js @@ -0,0 +1,129 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const aeskw_js_1 = require("../runtime/aeskw.js"); +const ECDH = require("../runtime/ecdhes.js"); +const pbes2kw_js_1 = require("../runtime/pbes2kw.js"); +const rsaes_js_1 = require("../runtime/rsaes.js"); +const base64url_js_1 = require("../runtime/base64url.js"); +const errors_js_1 = require("../util/errors.js"); +const cek_js_1 = require("../lib/cek.js"); +const import_js_1 = require("../key/import.js"); +const check_key_type_js_1 = require("./check_key_type.js"); +const is_object_js_1 = require("./is_object.js"); +const aesgcmkw_js_1 = require("./aesgcmkw.js"); +async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) { + (0, check_key_type_js_1.default)(alg, key, 'decrypt'); + switch (alg) { + case 'dir': { + if (encryptedKey !== undefined) + throw new errors_js_1.JWEInvalid('Encountered unexpected JWE Encrypted Key'); + return key; + } + case 'ECDH-ES': + if (encryptedKey !== undefined) + throw new errors_js_1.JWEInvalid('Encountered unexpected JWE Encrypted Key'); + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': { + if (!(0, is_object_js_1.default)(joseHeader.epk)) + throw new errors_js_1.JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); + if (!ECDH.ecdhAllowed(key)) + throw new errors_js_1.JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); + const epk = await (0, import_js_1.importJWK)(joseHeader.epk, alg); + let partyUInfo; + let partyVInfo; + if (joseHeader.apu !== undefined) { + if (typeof joseHeader.apu !== 'string') + throw new errors_js_1.JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); + try { + partyUInfo = (0, base64url_js_1.decode)(joseHeader.apu); + } + catch { + throw new errors_js_1.JWEInvalid('Failed to base64url decode the apu'); + } + } + if (joseHeader.apv !== undefined) { + if (typeof joseHeader.apv !== 'string') + throw new errors_js_1.JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); + try { + partyVInfo = (0, base64url_js_1.decode)(joseHeader.apv); + } + catch { + throw new errors_js_1.JWEInvalid('Failed to base64url decode the apv'); + } + } + const sharedSecret = await ECDH.deriveKey(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? (0, cek_js_1.bitLength)(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo); + if (alg === 'ECDH-ES') + return sharedSecret; + if (encryptedKey === undefined) + throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); + return (0, aeskw_js_1.unwrap)(alg.slice(-6), sharedSecret, encryptedKey); + } + case 'RSA1_5': + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': { + if (encryptedKey === undefined) + throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); + return (0, rsaes_js_1.decrypt)(alg, key, encryptedKey); + } + case 'PBES2-HS256+A128KW': + case 'PBES2-HS384+A192KW': + case 'PBES2-HS512+A256KW': { + if (encryptedKey === undefined) + throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); + if (typeof joseHeader.p2c !== 'number') + throw new errors_js_1.JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`); + const p2cLimit = (options === null || options === void 0 ? void 0 : options.maxPBES2Count) || 10000; + if (joseHeader.p2c > p2cLimit) + throw new errors_js_1.JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`); + if (typeof joseHeader.p2s !== 'string') + throw new errors_js_1.JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`); + let p2s; + try { + p2s = (0, base64url_js_1.decode)(joseHeader.p2s); + } + catch { + throw new errors_js_1.JWEInvalid('Failed to base64url decode the p2s'); + } + return (0, pbes2kw_js_1.decrypt)(alg, key, encryptedKey, joseHeader.p2c, p2s); + } + case 'A128KW': + case 'A192KW': + case 'A256KW': { + if (encryptedKey === undefined) + throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); + return (0, aeskw_js_1.unwrap)(alg, key, encryptedKey); + } + case 'A128GCMKW': + case 'A192GCMKW': + case 'A256GCMKW': { + if (encryptedKey === undefined) + throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); + if (typeof joseHeader.iv !== 'string') + throw new errors_js_1.JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`); + if (typeof joseHeader.tag !== 'string') + throw new errors_js_1.JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`); + let iv; + try { + iv = (0, base64url_js_1.decode)(joseHeader.iv); + } + catch { + throw new errors_js_1.JWEInvalid('Failed to base64url decode the iv'); + } + let tag; + try { + tag = (0, base64url_js_1.decode)(joseHeader.tag); + } + catch { + throw new errors_js_1.JWEInvalid('Failed to base64url decode the tag'); + } + return (0, aesgcmkw_js_1.unwrap)(alg, key, encryptedKey, iv, tag); + } + default: { + throw new errors_js_1.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); + } + } +} +exports.default = decryptKeyManagement; diff --git a/node_modules/jose/dist/node/cjs/lib/encrypt_key_management.js b/node_modules/jose/dist/node/cjs/lib/encrypt_key_management.js new file mode 100644 index 0000000..709364b --- /dev/null +++ b/node_modules/jose/dist/node/cjs/lib/encrypt_key_management.js @@ -0,0 +1,89 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const aeskw_js_1 = require("../runtime/aeskw.js"); +const ECDH = require("../runtime/ecdhes.js"); +const pbes2kw_js_1 = require("../runtime/pbes2kw.js"); +const rsaes_js_1 = require("../runtime/rsaes.js"); +const base64url_js_1 = require("../runtime/base64url.js"); +const cek_js_1 = require("../lib/cek.js"); +const errors_js_1 = require("../util/errors.js"); +const export_js_1 = require("../key/export.js"); +const check_key_type_js_1 = require("./check_key_type.js"); +const aesgcmkw_js_1 = require("./aesgcmkw.js"); +async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) { + let encryptedKey; + let parameters; + let cek; + (0, check_key_type_js_1.default)(alg, key, 'encrypt'); + switch (alg) { + case 'dir': { + cek = key; + break; + } + case 'ECDH-ES': + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': { + if (!ECDH.ecdhAllowed(key)) { + throw new errors_js_1.JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); + } + const { apu, apv } = providedParameters; + let { epk: ephemeralKey } = providedParameters; + ephemeralKey || (ephemeralKey = (await ECDH.generateEpk(key)).privateKey); + const { x, y, crv, kty } = await (0, export_js_1.exportJWK)(ephemeralKey); + const sharedSecret = await ECDH.deriveKey(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? (0, cek_js_1.bitLength)(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv); + parameters = { epk: { x, crv, kty } }; + if (kty === 'EC') + parameters.epk.y = y; + if (apu) + parameters.apu = (0, base64url_js_1.encode)(apu); + if (apv) + parameters.apv = (0, base64url_js_1.encode)(apv); + if (alg === 'ECDH-ES') { + cek = sharedSecret; + break; + } + cek = providedCek || (0, cek_js_1.default)(enc); + const kwAlg = alg.slice(-6); + encryptedKey = await (0, aeskw_js_1.wrap)(kwAlg, sharedSecret, cek); + break; + } + case 'RSA1_5': + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': { + cek = providedCek || (0, cek_js_1.default)(enc); + encryptedKey = await (0, rsaes_js_1.encrypt)(alg, key, cek); + break; + } + case 'PBES2-HS256+A128KW': + case 'PBES2-HS384+A192KW': + case 'PBES2-HS512+A256KW': { + cek = providedCek || (0, cek_js_1.default)(enc); + const { p2c, p2s } = providedParameters; + ({ encryptedKey, ...parameters } = await (0, pbes2kw_js_1.encrypt)(alg, key, cek, p2c, p2s)); + break; + } + case 'A128KW': + case 'A192KW': + case 'A256KW': { + cek = providedCek || (0, cek_js_1.default)(enc); + encryptedKey = await (0, aeskw_js_1.wrap)(alg, key, cek); + break; + } + case 'A128GCMKW': + case 'A192GCMKW': + case 'A256GCMKW': { + cek = providedCek || (0, cek_js_1.default)(enc); + const { iv } = providedParameters; + ({ encryptedKey, ...parameters } = await (0, aesgcmkw_js_1.wrap)(alg, key, cek, iv)); + break; + } + default: { + throw new errors_js_1.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); + } + } + return { cek, encryptedKey, parameters }; +} +exports.default = encryptKeyManagement; diff --git a/node_modules/jose/dist/node/cjs/lib/epoch.js b/node_modules/jose/dist/node/cjs/lib/epoch.js new file mode 100644 index 0000000..a0792b4 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/lib/epoch.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = (date) => Math.floor(date.getTime() / 1000); diff --git a/node_modules/jose/dist/node/cjs/lib/invalid_key_input.js b/node_modules/jose/dist/node/cjs/lib/invalid_key_input.js new file mode 100644 index 0000000..e1d5fc1 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/lib/invalid_key_input.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.withAlg = void 0; +function message(msg, actual, ...types) { + if (types.length > 2) { + const last = types.pop(); + msg += `one of type ${types.join(', ')}, or ${last}.`; + } + else if (types.length === 2) { + msg += `one of type ${types[0]} or ${types[1]}.`; + } + else { + msg += `of type ${types[0]}.`; + } + if (actual == null) { + msg += ` Received ${actual}`; + } + else if (typeof actual === 'function' && actual.name) { + msg += ` Received function ${actual.name}`; + } + else if (typeof actual === 'object' && actual != null) { + if (actual.constructor && actual.constructor.name) { + msg += ` Received an instance of ${actual.constructor.name}`; + } + } + return msg; +} +exports.default = (actual, ...types) => { + return message('Key must be ', actual, ...types); +}; +function withAlg(alg, actual, ...types) { + return message(`Key for the ${alg} algorithm must be `, actual, ...types); +} +exports.withAlg = withAlg; diff --git a/node_modules/jose/dist/node/cjs/lib/is_disjoint.js b/node_modules/jose/dist/node/cjs/lib/is_disjoint.js new file mode 100644 index 0000000..66c2fc6 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/lib/is_disjoint.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const isDisjoint = (...headers) => { + const sources = headers.filter(Boolean); + if (sources.length === 0 || sources.length === 1) { + return true; + } + let acc; + for (const header of sources) { + const parameters = Object.keys(header); + if (!acc || acc.size === 0) { + acc = new Set(parameters); + continue; + } + for (const parameter of parameters) { + if (acc.has(parameter)) { + return false; + } + acc.add(parameter); + } + } + return true; +}; +exports.default = isDisjoint; diff --git a/node_modules/jose/dist/node/cjs/lib/is_object.js b/node_modules/jose/dist/node/cjs/lib/is_object.js new file mode 100644 index 0000000..870938b --- /dev/null +++ b/node_modules/jose/dist/node/cjs/lib/is_object.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +function isObjectLike(value) { + return typeof value === 'object' && value !== null; +} +function isObject(input) { + if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') { + return false; + } + if (Object.getPrototypeOf(input) === null) { + return true; + } + let proto = input; + while (Object.getPrototypeOf(proto) !== null) { + proto = Object.getPrototypeOf(proto); + } + return Object.getPrototypeOf(input) === proto; +} +exports.default = isObject; diff --git a/node_modules/jose/dist/node/cjs/lib/iv.js b/node_modules/jose/dist/node/cjs/lib/iv.js new file mode 100644 index 0000000..db7d3a5 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/lib/iv.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bitLength = void 0; +const errors_js_1 = require("../util/errors.js"); +const random_js_1 = require("../runtime/random.js"); +function bitLength(alg) { + switch (alg) { + case 'A128GCM': + case 'A128GCMKW': + case 'A192GCM': + case 'A192GCMKW': + case 'A256GCM': + case 'A256GCMKW': + return 96; + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + return 128; + default: + throw new errors_js_1.JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); + } +} +exports.bitLength = bitLength; +exports.default = (alg) => (0, random_js_1.default)(new Uint8Array(bitLength(alg) >> 3)); diff --git a/node_modules/jose/dist/node/cjs/lib/jwt_claims_set.js b/node_modules/jose/dist/node/cjs/lib/jwt_claims_set.js new file mode 100644 index 0000000..30b31e4 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/lib/jwt_claims_set.js @@ -0,0 +1,104 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const errors_js_1 = require("../util/errors.js"); +const buffer_utils_js_1 = require("./buffer_utils.js"); +const epoch_js_1 = require("./epoch.js"); +const secs_js_1 = require("./secs.js"); +const is_object_js_1 = require("./is_object.js"); +const normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, ''); +const checkAudiencePresence = (audPayload, audOption) => { + if (typeof audPayload === 'string') { + return audOption.includes(audPayload); + } + if (Array.isArray(audPayload)) { + return audOption.some(Set.prototype.has.bind(new Set(audPayload))); + } + return false; +}; +exports.default = (protectedHeader, encodedPayload, options = {}) => { + const { typ } = options; + if (typ && + (typeof protectedHeader.typ !== 'string' || + normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { + throw new errors_js_1.JWTClaimValidationFailed('unexpected "typ" JWT header value', 'typ', 'check_failed'); + } + let payload; + try { + payload = JSON.parse(buffer_utils_js_1.decoder.decode(encodedPayload)); + } + catch { + } + if (!(0, is_object_js_1.default)(payload)) { + throw new errors_js_1.JWTInvalid('JWT Claims Set must be a top-level JSON object'); + } + const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; + if (maxTokenAge !== undefined) + requiredClaims.push('iat'); + if (audience !== undefined) + requiredClaims.push('aud'); + if (subject !== undefined) + requiredClaims.push('sub'); + if (issuer !== undefined) + requiredClaims.push('iss'); + for (const claim of new Set(requiredClaims.reverse())) { + if (!(claim in payload)) { + throw new errors_js_1.JWTClaimValidationFailed(`missing required "${claim}" claim`, claim, 'missing'); + } + } + if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { + throw new errors_js_1.JWTClaimValidationFailed('unexpected "iss" claim value', 'iss', 'check_failed'); + } + if (subject && payload.sub !== subject) { + throw new errors_js_1.JWTClaimValidationFailed('unexpected "sub" claim value', 'sub', 'check_failed'); + } + if (audience && + !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) { + throw new errors_js_1.JWTClaimValidationFailed('unexpected "aud" claim value', 'aud', 'check_failed'); + } + let tolerance; + switch (typeof options.clockTolerance) { + case 'string': + tolerance = (0, secs_js_1.default)(options.clockTolerance); + break; + case 'number': + tolerance = options.clockTolerance; + break; + case 'undefined': + tolerance = 0; + break; + default: + throw new TypeError('Invalid clockTolerance option type'); + } + const { currentDate } = options; + const now = (0, epoch_js_1.default)(currentDate || new Date()); + if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') { + throw new errors_js_1.JWTClaimValidationFailed('"iat" claim must be a number', 'iat', 'invalid'); + } + if (payload.nbf !== undefined) { + if (typeof payload.nbf !== 'number') { + throw new errors_js_1.JWTClaimValidationFailed('"nbf" claim must be a number', 'nbf', 'invalid'); + } + if (payload.nbf > now + tolerance) { + throw new errors_js_1.JWTClaimValidationFailed('"nbf" claim timestamp check failed', 'nbf', 'check_failed'); + } + } + if (payload.exp !== undefined) { + if (typeof payload.exp !== 'number') { + throw new errors_js_1.JWTClaimValidationFailed('"exp" claim must be a number', 'exp', 'invalid'); + } + if (payload.exp <= now - tolerance) { + throw new errors_js_1.JWTExpired('"exp" claim timestamp check failed', 'exp', 'check_failed'); + } + } + if (maxTokenAge) { + const age = now - payload.iat; + const max = typeof maxTokenAge === 'number' ? maxTokenAge : (0, secs_js_1.default)(maxTokenAge); + if (age - tolerance > max) { + throw new errors_js_1.JWTExpired('"iat" claim timestamp check failed (too far in the past)', 'iat', 'check_failed'); + } + if (age < 0 - tolerance) { + throw new errors_js_1.JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', 'iat', 'check_failed'); + } + } + return payload; +}; diff --git a/node_modules/jose/dist/node/cjs/lib/secs.js b/node_modules/jose/dist/node/cjs/lib/secs.js new file mode 100644 index 0000000..f1b6a0c --- /dev/null +++ b/node_modules/jose/dist/node/cjs/lib/secs.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const minute = 60; +const hour = minute * 60; +const day = hour * 24; +const week = day * 7; +const year = day * 365.25; +const REGEX = /^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i; +exports.default = (str) => { + const matched = REGEX.exec(str); + if (!matched) { + throw new TypeError('Invalid time period format'); + } + const value = parseFloat(matched[1]); + const unit = matched[2].toLowerCase(); + switch (unit) { + case 'sec': + case 'secs': + case 'second': + case 'seconds': + case 's': + return Math.round(value); + case 'minute': + case 'minutes': + case 'min': + case 'mins': + case 'm': + return Math.round(value * minute); + case 'hour': + case 'hours': + case 'hr': + case 'hrs': + case 'h': + return Math.round(value * hour); + case 'day': + case 'days': + case 'd': + return Math.round(value * day); + case 'week': + case 'weeks': + case 'w': + return Math.round(value * week); + default: + return Math.round(value * year); + } +}; diff --git a/node_modules/jose/dist/node/cjs/lib/validate_algorithms.js b/node_modules/jose/dist/node/cjs/lib/validate_algorithms.js new file mode 100644 index 0000000..29f4e80 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/lib/validate_algorithms.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const validateAlgorithms = (option, algorithms) => { + if (algorithms !== undefined && + (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) { + throw new TypeError(`"${option}" option must be an array of strings`); + } + if (!algorithms) { + return undefined; + } + return new Set(algorithms); +}; +exports.default = validateAlgorithms; diff --git a/node_modules/jose/dist/node/cjs/lib/validate_crit.js b/node_modules/jose/dist/node/cjs/lib/validate_crit.js new file mode 100644 index 0000000..b0229e3 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/lib/validate_crit.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const errors_js_1 = require("../util/errors.js"); +function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { + if (joseHeader.crit !== undefined && protectedHeader.crit === undefined) { + throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); + } + if (!protectedHeader || protectedHeader.crit === undefined) { + return new Set(); + } + if (!Array.isArray(protectedHeader.crit) || + protectedHeader.crit.length === 0 || + protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) { + throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); + } + let recognized; + if (recognizedOption !== undefined) { + recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); + } + else { + recognized = recognizedDefault; + } + for (const parameter of protectedHeader.crit) { + if (!recognized.has(parameter)) { + throw new errors_js_1.JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); + } + if (joseHeader[parameter] === undefined) { + throw new Err(`Extension Header Parameter "${parameter}" is missing`); + } + else if (recognized.get(parameter) && protectedHeader[parameter] === undefined) { + throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); + } + } + return new Set(protectedHeader.crit); +} +exports.default = validateCrit; diff --git a/node_modules/jose/dist/node/cjs/runtime/aeskw.js b/node_modules/jose/dist/node/cjs/runtime/aeskw.js new file mode 100644 index 0000000..ca26086 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/aeskw.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.unwrap = exports.wrap = void 0; +const buffer_1 = require("buffer"); +const crypto_1 = require("crypto"); +const errors_js_1 = require("../util/errors.js"); +const buffer_utils_js_1 = require("../lib/buffer_utils.js"); +const webcrypto_js_1 = require("./webcrypto.js"); +const crypto_key_js_1 = require("../lib/crypto_key.js"); +const is_key_object_js_1 = require("./is_key_object.js"); +const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); +const ciphers_js_1 = require("./ciphers.js"); +const is_key_like_js_1 = require("./is_key_like.js"); +function checkKeySize(key, alg) { + if (key.symmetricKeySize << 3 !== parseInt(alg.slice(1, 4), 10)) { + throw new TypeError(`Invalid key size for alg: ${alg}`); + } +} +function ensureKeyObject(key, alg, usage) { + if ((0, is_key_object_js_1.default)(key)) { + return key; + } + if (key instanceof Uint8Array) { + return (0, crypto_1.createSecretKey)(key); + } + if ((0, webcrypto_js_1.isCryptoKey)(key)) { + (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, usage); + return crypto_1.KeyObject.from(key); + } + throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array')); +} +const wrap = (alg, key, cek) => { + const size = parseInt(alg.slice(1, 4), 10); + const algorithm = `aes${size}-wrap`; + if (!(0, ciphers_js_1.default)(algorithm)) { + throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } + const keyObject = ensureKeyObject(key, alg, 'wrapKey'); + checkKeySize(keyObject, alg); + const cipher = (0, crypto_1.createCipheriv)(algorithm, keyObject, buffer_1.Buffer.alloc(8, 0xa6)); + return (0, buffer_utils_js_1.concat)(cipher.update(cek), cipher.final()); +}; +exports.wrap = wrap; +const unwrap = (alg, key, encryptedKey) => { + const size = parseInt(alg.slice(1, 4), 10); + const algorithm = `aes${size}-wrap`; + if (!(0, ciphers_js_1.default)(algorithm)) { + throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } + const keyObject = ensureKeyObject(key, alg, 'unwrapKey'); + checkKeySize(keyObject, alg); + const cipher = (0, crypto_1.createDecipheriv)(algorithm, keyObject, buffer_1.Buffer.alloc(8, 0xa6)); + return (0, buffer_utils_js_1.concat)(cipher.update(encryptedKey), cipher.final()); +}; +exports.unwrap = unwrap; diff --git a/node_modules/jose/dist/node/cjs/runtime/asn1.js b/node_modules/jose/dist/node/cjs/runtime/asn1.js new file mode 100644 index 0000000..3695dae --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/asn1.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromX509 = exports.fromSPKI = exports.fromPKCS8 = exports.toPKCS8 = exports.toSPKI = void 0; +const crypto_1 = require("crypto"); +const buffer_1 = require("buffer"); +const webcrypto_js_1 = require("./webcrypto.js"); +const is_key_object_js_1 = require("./is_key_object.js"); +const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); +const is_key_like_js_1 = require("./is_key_like.js"); +const genericExport = (keyType, keyFormat, key) => { + let keyObject; + if ((0, webcrypto_js_1.isCryptoKey)(key)) { + if (!key.extractable) { + throw new TypeError('CryptoKey is not extractable'); + } + keyObject = crypto_1.KeyObject.from(key); + } + else if ((0, is_key_object_js_1.default)(key)) { + keyObject = key; + } + else { + throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types)); + } + if (keyObject.type !== keyType) { + throw new TypeError(`key is not a ${keyType} key`); + } + return keyObject.export({ format: 'pem', type: keyFormat }); +}; +const toSPKI = (key) => { + return genericExport('public', 'spki', key); +}; +exports.toSPKI = toSPKI; +const toPKCS8 = (key) => { + return genericExport('private', 'pkcs8', key); +}; +exports.toPKCS8 = toPKCS8; +const fromPKCS8 = (pem) => (0, crypto_1.createPrivateKey)({ + key: buffer_1.Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, ''), 'base64'), + type: 'pkcs8', + format: 'der', +}); +exports.fromPKCS8 = fromPKCS8; +const fromSPKI = (pem) => (0, crypto_1.createPublicKey)({ + key: buffer_1.Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, ''), 'base64'), + type: 'spki', + format: 'der', +}); +exports.fromSPKI = fromSPKI; +const fromX509 = (pem) => (0, crypto_1.createPublicKey)({ + key: pem, + type: 'spki', + format: 'pem', +}); +exports.fromX509 = fromX509; diff --git a/node_modules/jose/dist/node/cjs/runtime/asn1_sequence_decoder.js b/node_modules/jose/dist/node/cjs/runtime/asn1_sequence_decoder.js new file mode 100644 index 0000000..4f96522 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/asn1_sequence_decoder.js @@ -0,0 +1,47 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tagInteger = 0x02; +const tagSequence = 0x30; +class Asn1SequenceDecoder { + constructor(buffer) { + if (buffer[0] !== tagSequence) { + throw new TypeError(); + } + this.buffer = buffer; + this.offset = 1; + const len = this.decodeLength(); + if (len !== buffer.length - this.offset) { + throw new TypeError(); + } + } + decodeLength() { + let length = this.buffer[this.offset++]; + if (length & 0x80) { + const nBytes = length & ~0x80; + length = 0; + for (let i = 0; i < nBytes; i++) + length = (length << 8) | this.buffer[this.offset + i]; + this.offset += nBytes; + } + return length; + } + unsignedInteger() { + if (this.buffer[this.offset++] !== tagInteger) { + throw new TypeError(); + } + let length = this.decodeLength(); + if (this.buffer[this.offset] === 0) { + this.offset++; + length--; + } + const result = this.buffer.slice(this.offset, this.offset + length); + this.offset += length; + return result; + } + end() { + if (this.offset !== this.buffer.length) { + throw new TypeError(); + } + } +} +exports.default = Asn1SequenceDecoder; diff --git a/node_modules/jose/dist/node/cjs/runtime/asn1_sequence_encoder.js b/node_modules/jose/dist/node/cjs/runtime/asn1_sequence_encoder.js new file mode 100644 index 0000000..8b71d6d --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/asn1_sequence_encoder.js @@ -0,0 +1,91 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const buffer_1 = require("buffer"); +const errors_js_1 = require("../util/errors.js"); +const tagInteger = 0x02; +const tagBitStr = 0x03; +const tagOctStr = 0x04; +const tagSequence = 0x30; +const bZero = buffer_1.Buffer.from([0x00]); +const bTagInteger = buffer_1.Buffer.from([tagInteger]); +const bTagBitStr = buffer_1.Buffer.from([tagBitStr]); +const bTagSequence = buffer_1.Buffer.from([tagSequence]); +const bTagOctStr = buffer_1.Buffer.from([tagOctStr]); +const encodeLength = (len) => { + if (len < 128) + return buffer_1.Buffer.from([len]); + const buffer = buffer_1.Buffer.alloc(5); + buffer.writeUInt32BE(len, 1); + let offset = 1; + while (buffer[offset] === 0) + offset++; + buffer[offset - 1] = 0x80 | (5 - offset); + return buffer.slice(offset - 1); +}; +const oids = new Map([ + ['P-256', buffer_1.Buffer.from('06 08 2A 86 48 CE 3D 03 01 07'.replace(/ /g, ''), 'hex')], + ['secp256k1', buffer_1.Buffer.from('06 05 2B 81 04 00 0A'.replace(/ /g, ''), 'hex')], + ['P-384', buffer_1.Buffer.from('06 05 2B 81 04 00 22'.replace(/ /g, ''), 'hex')], + ['P-521', buffer_1.Buffer.from('06 05 2B 81 04 00 23'.replace(/ /g, ''), 'hex')], + ['ecPublicKey', buffer_1.Buffer.from('06 07 2A 86 48 CE 3D 02 01'.replace(/ /g, ''), 'hex')], + ['X25519', buffer_1.Buffer.from('06 03 2B 65 6E'.replace(/ /g, ''), 'hex')], + ['X448', buffer_1.Buffer.from('06 03 2B 65 6F'.replace(/ /g, ''), 'hex')], + ['Ed25519', buffer_1.Buffer.from('06 03 2B 65 70'.replace(/ /g, ''), 'hex')], + ['Ed448', buffer_1.Buffer.from('06 03 2B 65 71'.replace(/ /g, ''), 'hex')], +]); +class DumbAsn1Encoder { + constructor() { + this.length = 0; + this.elements = []; + } + oidFor(oid) { + const bOid = oids.get(oid); + if (!bOid) { + throw new errors_js_1.JOSENotSupported('Invalid or unsupported OID'); + } + this.elements.push(bOid); + this.length += bOid.length; + } + zero() { + this.elements.push(bTagInteger, buffer_1.Buffer.from([0x01]), bZero); + this.length += 3; + } + one() { + this.elements.push(bTagInteger, buffer_1.Buffer.from([0x01]), buffer_1.Buffer.from([0x01])); + this.length += 3; + } + unsignedInteger(integer) { + if (integer[0] & 0x80) { + const len = encodeLength(integer.length + 1); + this.elements.push(bTagInteger, len, bZero, integer); + this.length += 2 + len.length + integer.length; + } + else { + let i = 0; + while (integer[i] === 0 && (integer[i + 1] & 0x80) === 0) + i++; + const len = encodeLength(integer.length - i); + this.elements.push(bTagInteger, encodeLength(integer.length - i), integer.slice(i)); + this.length += 1 + len.length + integer.length - i; + } + } + octStr(octStr) { + const len = encodeLength(octStr.length); + this.elements.push(bTagOctStr, encodeLength(octStr.length), octStr); + this.length += 1 + len.length + octStr.length; + } + bitStr(bitS) { + const len = encodeLength(bitS.length + 1); + this.elements.push(bTagBitStr, encodeLength(bitS.length + 1), bZero, bitS); + this.length += 1 + len.length + bitS.length + 1; + } + add(seq) { + this.elements.push(seq); + this.length += seq.length; + } + end(tag = bTagSequence) { + const len = encodeLength(this.length); + return buffer_1.Buffer.concat([tag, len, ...this.elements], 1 + len.length + this.length); + } +} +exports.default = DumbAsn1Encoder; diff --git a/node_modules/jose/dist/node/cjs/runtime/base64url.js b/node_modules/jose/dist/node/cjs/runtime/base64url.js new file mode 100644 index 0000000..3e357cb --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/base64url.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decode = exports.encode = exports.encodeBase64 = exports.decodeBase64 = void 0; +const buffer_1 = require("buffer"); +const buffer_utils_js_1 = require("../lib/buffer_utils.js"); +let encode; +function normalize(input) { + let encoded = input; + if (encoded instanceof Uint8Array) { + encoded = buffer_utils_js_1.decoder.decode(encoded); + } + return encoded; +} +if (buffer_1.Buffer.isEncoding('base64url')) { + exports.encode = encode = (input) => buffer_1.Buffer.from(input).toString('base64url'); +} +else { + exports.encode = encode = (input) => buffer_1.Buffer.from(input).toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); +} +const decodeBase64 = (input) => buffer_1.Buffer.from(input, 'base64'); +exports.decodeBase64 = decodeBase64; +const encodeBase64 = (input) => buffer_1.Buffer.from(input).toString('base64'); +exports.encodeBase64 = encodeBase64; +const decode = (input) => buffer_1.Buffer.from(normalize(input), 'base64'); +exports.decode = decode; diff --git a/node_modules/jose/dist/node/cjs/runtime/cbc_tag.js b/node_modules/jose/dist/node/cjs/runtime/cbc_tag.js new file mode 100644 index 0000000..03412c2 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/cbc_tag.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const crypto_1 = require("crypto"); +const buffer_utils_js_1 = require("../lib/buffer_utils.js"); +function cbcTag(aad, iv, ciphertext, macSize, macKey, keySize) { + const macData = (0, buffer_utils_js_1.concat)(aad, iv, ciphertext, (0, buffer_utils_js_1.uint64be)(aad.length << 3)); + const hmac = (0, crypto_1.createHmac)(`sha${macSize}`, macKey); + hmac.update(macData); + return hmac.digest().slice(0, keySize >> 3); +} +exports.default = cbcTag; diff --git a/node_modules/jose/dist/node/cjs/runtime/check_cek_length.js b/node_modules/jose/dist/node/cjs/runtime/check_cek_length.js new file mode 100644 index 0000000..5192e75 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/check_cek_length.js @@ -0,0 +1,37 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const errors_js_1 = require("../util/errors.js"); +const is_key_object_js_1 = require("./is_key_object.js"); +const checkCekLength = (enc, cek) => { + let expected; + switch (enc) { + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + expected = parseInt(enc.slice(-3), 10); + break; + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': + expected = parseInt(enc.slice(1, 4), 10); + break; + default: + throw new errors_js_1.JOSENotSupported(`Content Encryption Algorithm ${enc} is not supported either by JOSE or your javascript runtime`); + } + if (cek instanceof Uint8Array) { + const actual = cek.byteLength << 3; + if (actual !== expected) { + throw new errors_js_1.JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); + } + return; + } + if ((0, is_key_object_js_1.default)(cek) && cek.type === 'secret') { + const actual = cek.symmetricKeySize << 3; + if (actual !== expected) { + throw new errors_js_1.JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); + } + return; + } + throw new TypeError('Invalid Content Encryption Key type'); +}; +exports.default = checkCekLength; diff --git a/node_modules/jose/dist/node/cjs/runtime/check_modulus_length.js b/node_modules/jose/dist/node/cjs/runtime/check_modulus_length.js new file mode 100644 index 0000000..72c670e --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/check_modulus_length.js @@ -0,0 +1,52 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setModulusLength = exports.weakMap = void 0; +exports.weakMap = new WeakMap(); +const getLength = (buf, index) => { + let len = buf.readUInt8(1); + if ((len & 0x80) === 0) { + if (index === 0) { + return len; + } + return getLength(buf.subarray(2 + len), index - 1); + } + const num = len & 0x7f; + len = 0; + for (let i = 0; i < num; i++) { + len <<= 8; + const j = buf.readUInt8(2 + i); + len |= j; + } + if (index === 0) { + return len; + } + return getLength(buf.subarray(2 + len), index - 1); +}; +const getLengthOfSeqIndex = (sequence, index) => { + const len = sequence.readUInt8(1); + if ((len & 0x80) === 0) { + return getLength(sequence.subarray(2), index); + } + const num = len & 0x7f; + return getLength(sequence.subarray(2 + num), index); +}; +const getModulusLength = (key) => { + var _a, _b; + if (exports.weakMap.has(key)) { + return exports.weakMap.get(key); + } + const modulusLength = (_b = (_a = key.asymmetricKeyDetails) === null || _a === void 0 ? void 0 : _a.modulusLength) !== null && _b !== void 0 ? _b : (getLengthOfSeqIndex(key.export({ format: 'der', type: 'pkcs1' }), key.type === 'private' ? 1 : 0) - + 1) << + 3; + exports.weakMap.set(key, modulusLength); + return modulusLength; +}; +const setModulusLength = (keyObject, modulusLength) => { + exports.weakMap.set(keyObject, modulusLength); +}; +exports.setModulusLength = setModulusLength; +exports.default = (key, alg) => { + if (getModulusLength(key) < 2048) { + throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); + } +}; diff --git a/node_modules/jose/dist/node/cjs/runtime/ciphers.js b/node_modules/jose/dist/node/cjs/runtime/ciphers.js new file mode 100644 index 0000000..e004c84 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/ciphers.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const crypto_1 = require("crypto"); +let ciphers; +exports.default = (algorithm) => { + ciphers || (ciphers = new Set((0, crypto_1.getCiphers)())); + return ciphers.has(algorithm); +}; diff --git a/node_modules/jose/dist/node/cjs/runtime/decrypt.js b/node_modules/jose/dist/node/cjs/runtime/decrypt.js new file mode 100644 index 0000000..6e0de6d --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/decrypt.js @@ -0,0 +1,97 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const crypto_1 = require("crypto"); +const check_iv_length_js_1 = require("../lib/check_iv_length.js"); +const check_cek_length_js_1 = require("./check_cek_length.js"); +const buffer_utils_js_1 = require("../lib/buffer_utils.js"); +const errors_js_1 = require("../util/errors.js"); +const timing_safe_equal_js_1 = require("./timing_safe_equal.js"); +const cbc_tag_js_1 = require("./cbc_tag.js"); +const webcrypto_js_1 = require("./webcrypto.js"); +const crypto_key_js_1 = require("../lib/crypto_key.js"); +const is_key_object_js_1 = require("./is_key_object.js"); +const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); +const ciphers_js_1 = require("./ciphers.js"); +const is_key_like_js_1 = require("./is_key_like.js"); +function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) { + const keySize = parseInt(enc.slice(1, 4), 10); + if ((0, is_key_object_js_1.default)(cek)) { + cek = cek.export(); + } + const encKey = cek.subarray(keySize >> 3); + const macKey = cek.subarray(0, keySize >> 3); + const macSize = parseInt(enc.slice(-3), 10); + const algorithm = `aes-${keySize}-cbc`; + if (!(0, ciphers_js_1.default)(algorithm)) { + throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); + } + const expectedTag = (0, cbc_tag_js_1.default)(aad, iv, ciphertext, macSize, macKey, keySize); + let macCheckPassed; + try { + macCheckPassed = (0, timing_safe_equal_js_1.default)(tag, expectedTag); + } + catch { + } + if (!macCheckPassed) { + throw new errors_js_1.JWEDecryptionFailed(); + } + let plaintext; + try { + const decipher = (0, crypto_1.createDecipheriv)(algorithm, encKey, iv); + plaintext = (0, buffer_utils_js_1.concat)(decipher.update(ciphertext), decipher.final()); + } + catch { + } + if (!plaintext) { + throw new errors_js_1.JWEDecryptionFailed(); + } + return plaintext; +} +function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) { + const keySize = parseInt(enc.slice(1, 4), 10); + const algorithm = `aes-${keySize}-gcm`; + if (!(0, ciphers_js_1.default)(algorithm)) { + throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); + } + try { + const decipher = (0, crypto_1.createDecipheriv)(algorithm, cek, iv, { authTagLength: 16 }); + decipher.setAuthTag(tag); + if (aad.byteLength) { + decipher.setAAD(aad, { plaintextLength: ciphertext.length }); + } + const plaintext = decipher.update(ciphertext); + decipher.final(); + return plaintext; + } + catch { + throw new errors_js_1.JWEDecryptionFailed(); + } +} +const decrypt = (enc, cek, ciphertext, iv, tag, aad) => { + let key; + if ((0, webcrypto_js_1.isCryptoKey)(cek)) { + (0, crypto_key_js_1.checkEncCryptoKey)(cek, enc, 'decrypt'); + key = crypto_1.KeyObject.from(cek); + } + else if (cek instanceof Uint8Array || (0, is_key_object_js_1.default)(cek)) { + key = cek; + } + else { + throw new TypeError((0, invalid_key_input_js_1.default)(cek, ...is_key_like_js_1.types, 'Uint8Array')); + } + (0, check_cek_length_js_1.default)(enc, key); + (0, check_iv_length_js_1.default)(enc, iv); + switch (enc) { + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + return cbcDecrypt(enc, key, ciphertext, iv, tag, aad); + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': + return gcmDecrypt(enc, key, ciphertext, iv, tag, aad); + default: + throw new errors_js_1.JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); + } +}; +exports.default = decrypt; diff --git a/node_modules/jose/dist/node/cjs/runtime/digest.js b/node_modules/jose/dist/node/cjs/runtime/digest.js new file mode 100644 index 0000000..13c194a --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/digest.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const crypto_1 = require("crypto"); +const digest = (algorithm, data) => (0, crypto_1.createHash)(algorithm).update(data).digest(); +exports.default = digest; diff --git a/node_modules/jose/dist/node/cjs/runtime/dsa_digest.js b/node_modules/jose/dist/node/cjs/runtime/dsa_digest.js new file mode 100644 index 0000000..fde4883 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/dsa_digest.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const errors_js_1 = require("../util/errors.js"); +function dsaDigest(alg) { + switch (alg) { + case 'PS256': + case 'RS256': + case 'ES256': + case 'ES256K': + return 'sha256'; + case 'PS384': + case 'RS384': + case 'ES384': + return 'sha384'; + case 'PS512': + case 'RS512': + case 'ES512': + return 'sha512'; + case 'EdDSA': + return undefined; + default: + throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } +} +exports.default = dsaDigest; diff --git a/node_modules/jose/dist/node/cjs/runtime/ecdhes.js b/node_modules/jose/dist/node/cjs/runtime/ecdhes.js new file mode 100644 index 0000000..d769af7 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/ecdhes.js @@ -0,0 +1,70 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ecdhAllowed = exports.generateEpk = exports.deriveKey = void 0; +const crypto_1 = require("crypto"); +const util_1 = require("util"); +const get_named_curve_js_1 = require("./get_named_curve.js"); +const buffer_utils_js_1 = require("../lib/buffer_utils.js"); +const errors_js_1 = require("../util/errors.js"); +const webcrypto_js_1 = require("./webcrypto.js"); +const crypto_key_js_1 = require("../lib/crypto_key.js"); +const is_key_object_js_1 = require("./is_key_object.js"); +const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); +const is_key_like_js_1 = require("./is_key_like.js"); +const generateKeyPair = (0, util_1.promisify)(crypto_1.generateKeyPair); +async function deriveKey(publicKee, privateKee, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) { + let publicKey; + if ((0, webcrypto_js_1.isCryptoKey)(publicKee)) { + (0, crypto_key_js_1.checkEncCryptoKey)(publicKee, 'ECDH'); + publicKey = crypto_1.KeyObject.from(publicKee); + } + else if ((0, is_key_object_js_1.default)(publicKee)) { + publicKey = publicKee; + } + else { + throw new TypeError((0, invalid_key_input_js_1.default)(publicKee, ...is_key_like_js_1.types)); + } + let privateKey; + if ((0, webcrypto_js_1.isCryptoKey)(privateKee)) { + (0, crypto_key_js_1.checkEncCryptoKey)(privateKee, 'ECDH', 'deriveBits'); + privateKey = crypto_1.KeyObject.from(privateKee); + } + else if ((0, is_key_object_js_1.default)(privateKee)) { + privateKey = privateKee; + } + else { + throw new TypeError((0, invalid_key_input_js_1.default)(privateKee, ...is_key_like_js_1.types)); + } + const value = (0, buffer_utils_js_1.concat)((0, buffer_utils_js_1.lengthAndInput)(buffer_utils_js_1.encoder.encode(algorithm)), (0, buffer_utils_js_1.lengthAndInput)(apu), (0, buffer_utils_js_1.lengthAndInput)(apv), (0, buffer_utils_js_1.uint32be)(keyLength)); + const sharedSecret = (0, crypto_1.diffieHellman)({ privateKey, publicKey }); + return (0, buffer_utils_js_1.concatKdf)(sharedSecret, keyLength, value); +} +exports.deriveKey = deriveKey; +async function generateEpk(kee) { + let key; + if ((0, webcrypto_js_1.isCryptoKey)(kee)) { + key = crypto_1.KeyObject.from(kee); + } + else if ((0, is_key_object_js_1.default)(kee)) { + key = kee; + } + else { + throw new TypeError((0, invalid_key_input_js_1.default)(kee, ...is_key_like_js_1.types)); + } + switch (key.asymmetricKeyType) { + case 'x25519': + return generateKeyPair('x25519'); + case 'x448': { + return generateKeyPair('x448'); + } + case 'ec': { + const namedCurve = (0, get_named_curve_js_1.default)(key); + return generateKeyPair('ec', { namedCurve }); + } + default: + throw new errors_js_1.JOSENotSupported('Invalid or unsupported EPK'); + } +} +exports.generateEpk = generateEpk; +const ecdhAllowed = (key) => ['P-256', 'P-384', 'P-521', 'X25519', 'X448'].includes((0, get_named_curve_js_1.default)(key)); +exports.ecdhAllowed = ecdhAllowed; diff --git a/node_modules/jose/dist/node/cjs/runtime/encrypt.js b/node_modules/jose/dist/node/cjs/runtime/encrypt.js new file mode 100644 index 0000000..940a1ed --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/encrypt.js @@ -0,0 +1,74 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const crypto_1 = require("crypto"); +const check_iv_length_js_1 = require("../lib/check_iv_length.js"); +const check_cek_length_js_1 = require("./check_cek_length.js"); +const buffer_utils_js_1 = require("../lib/buffer_utils.js"); +const cbc_tag_js_1 = require("./cbc_tag.js"); +const webcrypto_js_1 = require("./webcrypto.js"); +const crypto_key_js_1 = require("../lib/crypto_key.js"); +const is_key_object_js_1 = require("./is_key_object.js"); +const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); +const errors_js_1 = require("../util/errors.js"); +const ciphers_js_1 = require("./ciphers.js"); +const is_key_like_js_1 = require("./is_key_like.js"); +function cbcEncrypt(enc, plaintext, cek, iv, aad) { + const keySize = parseInt(enc.slice(1, 4), 10); + if ((0, is_key_object_js_1.default)(cek)) { + cek = cek.export(); + } + const encKey = cek.subarray(keySize >> 3); + const macKey = cek.subarray(0, keySize >> 3); + const algorithm = `aes-${keySize}-cbc`; + if (!(0, ciphers_js_1.default)(algorithm)) { + throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); + } + const cipher = (0, crypto_1.createCipheriv)(algorithm, encKey, iv); + const ciphertext = (0, buffer_utils_js_1.concat)(cipher.update(plaintext), cipher.final()); + const macSize = parseInt(enc.slice(-3), 10); + const tag = (0, cbc_tag_js_1.default)(aad, iv, ciphertext, macSize, macKey, keySize); + return { ciphertext, tag }; +} +function gcmEncrypt(enc, plaintext, cek, iv, aad) { + const keySize = parseInt(enc.slice(1, 4), 10); + const algorithm = `aes-${keySize}-gcm`; + if (!(0, ciphers_js_1.default)(algorithm)) { + throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); + } + const cipher = (0, crypto_1.createCipheriv)(algorithm, cek, iv, { authTagLength: 16 }); + if (aad.byteLength) { + cipher.setAAD(aad, { plaintextLength: plaintext.length }); + } + const ciphertext = cipher.update(plaintext); + cipher.final(); + const tag = cipher.getAuthTag(); + return { ciphertext, tag }; +} +const encrypt = (enc, plaintext, cek, iv, aad) => { + let key; + if ((0, webcrypto_js_1.isCryptoKey)(cek)) { + (0, crypto_key_js_1.checkEncCryptoKey)(cek, enc, 'encrypt'); + key = crypto_1.KeyObject.from(cek); + } + else if (cek instanceof Uint8Array || (0, is_key_object_js_1.default)(cek)) { + key = cek; + } + else { + throw new TypeError((0, invalid_key_input_js_1.default)(cek, ...is_key_like_js_1.types, 'Uint8Array')); + } + (0, check_cek_length_js_1.default)(enc, key); + (0, check_iv_length_js_1.default)(enc, iv); + switch (enc) { + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + return cbcEncrypt(enc, plaintext, key, iv, aad); + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': + return gcmEncrypt(enc, plaintext, key, iv, aad); + default: + throw new errors_js_1.JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); + } +}; +exports.default = encrypt; diff --git a/node_modules/jose/dist/node/cjs/runtime/fetch_jwks.js b/node_modules/jose/dist/node/cjs/runtime/fetch_jwks.js new file mode 100644 index 0000000..b034fd5 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/fetch_jwks.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const http = require("http"); +const https = require("https"); +const events_1 = require("events"); +const errors_js_1 = require("../util/errors.js"); +const buffer_utils_js_1 = require("../lib/buffer_utils.js"); +const fetchJwks = async (url, timeout, options) => { + let get; + switch (url.protocol) { + case 'https:': + get = https.get; + break; + case 'http:': + get = http.get; + break; + default: + throw new TypeError('Unsupported URL protocol.'); + } + const { agent, headers } = options; + const req = get(url.href, { + agent, + timeout, + headers, + }); + const [response] = (await Promise.race([(0, events_1.once)(req, 'response'), (0, events_1.once)(req, 'timeout')])); + if (!response) { + req.destroy(); + throw new errors_js_1.JWKSTimeout(); + } + if (response.statusCode !== 200) { + throw new errors_js_1.JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response'); + } + const parts = []; + for await (const part of response) { + parts.push(part); + } + try { + return JSON.parse(buffer_utils_js_1.decoder.decode((0, buffer_utils_js_1.concat)(...parts))); + } + catch { + throw new errors_js_1.JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON'); + } +}; +exports.default = fetchJwks; diff --git a/node_modules/jose/dist/node/cjs/runtime/flags.js b/node_modules/jose/dist/node/cjs/runtime/flags.js new file mode 100644 index 0000000..7a4e64d --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/flags.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.jwkImport = exports.jwkExport = exports.rsaPssParams = exports.oneShotCallback = void 0; +const [major, minor] = process.versions.node.split('.').map((str) => parseInt(str, 10)); +exports.oneShotCallback = major >= 16 || (major === 15 && minor >= 13); +exports.rsaPssParams = !('electron' in process.versions) && (major >= 17 || (major === 16 && minor >= 9)); +exports.jwkExport = major >= 16 || (major === 15 && minor >= 9); +exports.jwkImport = major >= 16 || (major === 15 && minor >= 12); diff --git a/node_modules/jose/dist/node/cjs/runtime/generate.js b/node_modules/jose/dist/node/cjs/runtime/generate.js new file mode 100644 index 0000000..38aa92b --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/generate.js @@ -0,0 +1,105 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.generateKeyPair = exports.generateSecret = void 0; +const crypto_1 = require("crypto"); +const util_1 = require("util"); +const random_js_1 = require("./random.js"); +const check_modulus_length_js_1 = require("./check_modulus_length.js"); +const errors_js_1 = require("../util/errors.js"); +const generate = (0, util_1.promisify)(crypto_1.generateKeyPair); +async function generateSecret(alg, options) { + let length; + switch (alg) { + case 'HS256': + case 'HS384': + case 'HS512': + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + length = parseInt(alg.slice(-3), 10); + break; + case 'A128KW': + case 'A192KW': + case 'A256KW': + case 'A128GCMKW': + case 'A192GCMKW': + case 'A256GCMKW': + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': + length = parseInt(alg.slice(1, 4), 10); + break; + default: + throw new errors_js_1.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + } + return (0, crypto_1.createSecretKey)((0, random_js_1.default)(new Uint8Array(length >> 3))); +} +exports.generateSecret = generateSecret; +async function generateKeyPair(alg, options) { + var _a, _b; + switch (alg) { + case 'RS256': + case 'RS384': + case 'RS512': + case 'PS256': + case 'PS384': + case 'PS512': + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': + case 'RSA1_5': { + const modulusLength = (_a = options === null || options === void 0 ? void 0 : options.modulusLength) !== null && _a !== void 0 ? _a : 2048; + if (typeof modulusLength !== 'number' || modulusLength < 2048) { + throw new errors_js_1.JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used'); + } + const keypair = await generate('rsa', { + modulusLength, + publicExponent: 0x10001, + }); + (0, check_modulus_length_js_1.setModulusLength)(keypair.privateKey, modulusLength); + (0, check_modulus_length_js_1.setModulusLength)(keypair.publicKey, modulusLength); + return keypair; + } + case 'ES256': + return generate('ec', { namedCurve: 'P-256' }); + case 'ES256K': + return generate('ec', { namedCurve: 'secp256k1' }); + case 'ES384': + return generate('ec', { namedCurve: 'P-384' }); + case 'ES512': + return generate('ec', { namedCurve: 'P-521' }); + case 'EdDSA': { + switch (options === null || options === void 0 ? void 0 : options.crv) { + case undefined: + case 'Ed25519': + return generate('ed25519'); + case 'Ed448': + return generate('ed448'); + default: + throw new errors_js_1.JOSENotSupported('Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448'); + } + } + case 'ECDH-ES': + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': + const crv = (_b = options === null || options === void 0 ? void 0 : options.crv) !== null && _b !== void 0 ? _b : 'P-256'; + switch (crv) { + case undefined: + case 'P-256': + case 'P-384': + case 'P-521': + return generate('ec', { namedCurve: crv }); + case 'X25519': + return generate('x25519'); + case 'X448': + return generate('x448'); + default: + throw new errors_js_1.JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448'); + } + default: + throw new errors_js_1.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + } +} +exports.generateKeyPair = generateKeyPair; diff --git a/node_modules/jose/dist/node/cjs/runtime/get_named_curve.js b/node_modules/jose/dist/node/cjs/runtime/get_named_curve.js new file mode 100644 index 0000000..bb46729 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/get_named_curve.js @@ -0,0 +1,95 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setCurve = exports.weakMap = void 0; +const buffer_1 = require("buffer"); +const crypto_1 = require("crypto"); +const errors_js_1 = require("../util/errors.js"); +const webcrypto_js_1 = require("./webcrypto.js"); +const is_key_object_js_1 = require("./is_key_object.js"); +const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); +const is_key_like_js_1 = require("./is_key_like.js"); +const p256 = buffer_1.Buffer.from([42, 134, 72, 206, 61, 3, 1, 7]); +const p384 = buffer_1.Buffer.from([43, 129, 4, 0, 34]); +const p521 = buffer_1.Buffer.from([43, 129, 4, 0, 35]); +const secp256k1 = buffer_1.Buffer.from([43, 129, 4, 0, 10]); +exports.weakMap = new WeakMap(); +const namedCurveToJOSE = (namedCurve) => { + switch (namedCurve) { + case 'prime256v1': + return 'P-256'; + case 'secp384r1': + return 'P-384'; + case 'secp521r1': + return 'P-521'; + case 'secp256k1': + return 'secp256k1'; + default: + throw new errors_js_1.JOSENotSupported('Unsupported key curve for this operation'); + } +}; +const getNamedCurve = (kee, raw) => { + var _a; + let key; + if ((0, webcrypto_js_1.isCryptoKey)(kee)) { + key = crypto_1.KeyObject.from(kee); + } + else if ((0, is_key_object_js_1.default)(kee)) { + key = kee; + } + else { + throw new TypeError((0, invalid_key_input_js_1.default)(kee, ...is_key_like_js_1.types)); + } + if (key.type === 'secret') { + throw new TypeError('only "private" or "public" type keys can be used for this operation'); + } + switch (key.asymmetricKeyType) { + case 'ed25519': + case 'ed448': + return `Ed${key.asymmetricKeyType.slice(2)}`; + case 'x25519': + case 'x448': + return `X${key.asymmetricKeyType.slice(1)}`; + case 'ec': { + if (exports.weakMap.has(key)) { + return exports.weakMap.get(key); + } + let namedCurve = (_a = key.asymmetricKeyDetails) === null || _a === void 0 ? void 0 : _a.namedCurve; + if (!namedCurve && key.type === 'private') { + namedCurve = getNamedCurve((0, crypto_1.createPublicKey)(key), true); + } + else if (!namedCurve) { + const buf = key.export({ format: 'der', type: 'spki' }); + const i = buf[1] < 128 ? 14 : 15; + const len = buf[i]; + const curveOid = buf.slice(i + 1, i + 1 + len); + if (curveOid.equals(p256)) { + namedCurve = 'prime256v1'; + } + else if (curveOid.equals(p384)) { + namedCurve = 'secp384r1'; + } + else if (curveOid.equals(p521)) { + namedCurve = 'secp521r1'; + } + else if (curveOid.equals(secp256k1)) { + namedCurve = 'secp256k1'; + } + else { + throw new errors_js_1.JOSENotSupported('Unsupported key curve for this operation'); + } + } + if (raw) + return namedCurve; + const curve = namedCurveToJOSE(namedCurve); + exports.weakMap.set(key, curve); + return curve; + } + default: + throw new TypeError('Invalid asymmetric key type for this operation'); + } +}; +function setCurve(keyObject, curve) { + exports.weakMap.set(keyObject, curve); +} +exports.setCurve = setCurve; +exports.default = getNamedCurve; diff --git a/node_modules/jose/dist/node/cjs/runtime/get_sign_verify_key.js b/node_modules/jose/dist/node/cjs/runtime/get_sign_verify_key.js new file mode 100644 index 0000000..fea98c7 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/get_sign_verify_key.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const crypto_1 = require("crypto"); +const webcrypto_js_1 = require("./webcrypto.js"); +const crypto_key_js_1 = require("../lib/crypto_key.js"); +const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); +const is_key_like_js_1 = require("./is_key_like.js"); +function getSignVerifyKey(alg, key, usage) { + if (key instanceof Uint8Array) { + if (!alg.startsWith('HS')) { + throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types)); + } + return (0, crypto_1.createSecretKey)(key); + } + if (key instanceof crypto_1.KeyObject) { + return key; + } + if ((0, webcrypto_js_1.isCryptoKey)(key)) { + (0, crypto_key_js_1.checkSigCryptoKey)(key, alg, usage); + return crypto_1.KeyObject.from(key); + } + throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array')); +} +exports.default = getSignVerifyKey; diff --git a/node_modules/jose/dist/node/cjs/runtime/hmac_digest.js b/node_modules/jose/dist/node/cjs/runtime/hmac_digest.js new file mode 100644 index 0000000..c393512 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/hmac_digest.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const errors_js_1 = require("../util/errors.js"); +function hmacDigest(alg) { + switch (alg) { + case 'HS256': + return 'sha256'; + case 'HS384': + return 'sha384'; + case 'HS512': + return 'sha512'; + default: + throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } +} +exports.default = hmacDigest; diff --git a/node_modules/jose/dist/node/cjs/runtime/is_key_like.js b/node_modules/jose/dist/node/cjs/runtime/is_key_like.js new file mode 100644 index 0000000..cd157df --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/is_key_like.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.types = void 0; +const webcrypto_js_1 = require("./webcrypto.js"); +const is_key_object_js_1 = require("./is_key_object.js"); +exports.default = (key) => (0, is_key_object_js_1.default)(key) || (0, webcrypto_js_1.isCryptoKey)(key); +const types = ['KeyObject']; +exports.types = types; +if (globalThis.CryptoKey || (webcrypto_js_1.default === null || webcrypto_js_1.default === void 0 ? void 0 : webcrypto_js_1.default.CryptoKey)) { + types.push('CryptoKey'); +} diff --git a/node_modules/jose/dist/node/cjs/runtime/is_key_object.js b/node_modules/jose/dist/node/cjs/runtime/is_key_object.js new file mode 100644 index 0000000..54b02cc --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/is_key_object.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const crypto_1 = require("crypto"); +const util = require("util"); +exports.default = util.types.isKeyObject + ? (obj) => util.types.isKeyObject(obj) + : (obj) => obj != null && obj instanceof crypto_1.KeyObject; diff --git a/node_modules/jose/dist/node/cjs/runtime/jwk_to_key.js b/node_modules/jose/dist/node/cjs/runtime/jwk_to_key.js new file mode 100644 index 0000000..8a3ead7 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/jwk_to_key.js @@ -0,0 +1,118 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const buffer_1 = require("buffer"); +const crypto_1 = require("crypto"); +const base64url_js_1 = require("./base64url.js"); +const errors_js_1 = require("../util/errors.js"); +const get_named_curve_js_1 = require("./get_named_curve.js"); +const check_modulus_length_js_1 = require("./check_modulus_length.js"); +const asn1_sequence_encoder_js_1 = require("./asn1_sequence_encoder.js"); +const flags_js_1 = require("./flags.js"); +const parse = (jwk) => { + if (flags_js_1.jwkImport && jwk.kty !== 'oct') { + return jwk.d + ? (0, crypto_1.createPrivateKey)({ format: 'jwk', key: jwk }) + : (0, crypto_1.createPublicKey)({ format: 'jwk', key: jwk }); + } + switch (jwk.kty) { + case 'oct': { + return (0, crypto_1.createSecretKey)((0, base64url_js_1.decode)(jwk.k)); + } + case 'RSA': { + const enc = new asn1_sequence_encoder_js_1.default(); + const isPrivate = jwk.d !== undefined; + const modulus = buffer_1.Buffer.from(jwk.n, 'base64'); + const exponent = buffer_1.Buffer.from(jwk.e, 'base64'); + if (isPrivate) { + enc.zero(); + enc.unsignedInteger(modulus); + enc.unsignedInteger(exponent); + enc.unsignedInteger(buffer_1.Buffer.from(jwk.d, 'base64')); + enc.unsignedInteger(buffer_1.Buffer.from(jwk.p, 'base64')); + enc.unsignedInteger(buffer_1.Buffer.from(jwk.q, 'base64')); + enc.unsignedInteger(buffer_1.Buffer.from(jwk.dp, 'base64')); + enc.unsignedInteger(buffer_1.Buffer.from(jwk.dq, 'base64')); + enc.unsignedInteger(buffer_1.Buffer.from(jwk.qi, 'base64')); + } + else { + enc.unsignedInteger(modulus); + enc.unsignedInteger(exponent); + } + const der = enc.end(); + const createInput = { + key: der, + format: 'der', + type: 'pkcs1', + }; + const keyObject = isPrivate ? (0, crypto_1.createPrivateKey)(createInput) : (0, crypto_1.createPublicKey)(createInput); + (0, check_modulus_length_js_1.setModulusLength)(keyObject, modulus.length << 3); + return keyObject; + } + case 'EC': { + const enc = new asn1_sequence_encoder_js_1.default(); + const isPrivate = jwk.d !== undefined; + const pub = buffer_1.Buffer.concat([ + buffer_1.Buffer.alloc(1, 4), + buffer_1.Buffer.from(jwk.x, 'base64'), + buffer_1.Buffer.from(jwk.y, 'base64'), + ]); + if (isPrivate) { + enc.zero(); + const enc$1 = new asn1_sequence_encoder_js_1.default(); + enc$1.oidFor('ecPublicKey'); + enc$1.oidFor(jwk.crv); + enc.add(enc$1.end()); + const enc$2 = new asn1_sequence_encoder_js_1.default(); + enc$2.one(); + enc$2.octStr(buffer_1.Buffer.from(jwk.d, 'base64')); + const enc$3 = new asn1_sequence_encoder_js_1.default(); + enc$3.bitStr(pub); + const f2 = enc$3.end(buffer_1.Buffer.from([0xa1])); + enc$2.add(f2); + const f = enc$2.end(); + const enc$4 = new asn1_sequence_encoder_js_1.default(); + enc$4.add(f); + const f3 = enc$4.end(buffer_1.Buffer.from([0x04])); + enc.add(f3); + const der = enc.end(); + const keyObject = (0, crypto_1.createPrivateKey)({ key: der, format: 'der', type: 'pkcs8' }); + (0, get_named_curve_js_1.setCurve)(keyObject, jwk.crv); + return keyObject; + } + const enc$1 = new asn1_sequence_encoder_js_1.default(); + enc$1.oidFor('ecPublicKey'); + enc$1.oidFor(jwk.crv); + enc.add(enc$1.end()); + enc.bitStr(pub); + const der = enc.end(); + const keyObject = (0, crypto_1.createPublicKey)({ key: der, format: 'der', type: 'spki' }); + (0, get_named_curve_js_1.setCurve)(keyObject, jwk.crv); + return keyObject; + } + case 'OKP': { + const enc = new asn1_sequence_encoder_js_1.default(); + const isPrivate = jwk.d !== undefined; + if (isPrivate) { + enc.zero(); + const enc$1 = new asn1_sequence_encoder_js_1.default(); + enc$1.oidFor(jwk.crv); + enc.add(enc$1.end()); + const enc$2 = new asn1_sequence_encoder_js_1.default(); + enc$2.octStr(buffer_1.Buffer.from(jwk.d, 'base64')); + const f = enc$2.end(buffer_1.Buffer.from([0x04])); + enc.add(f); + const der = enc.end(); + return (0, crypto_1.createPrivateKey)({ key: der, format: 'der', type: 'pkcs8' }); + } + const enc$1 = new asn1_sequence_encoder_js_1.default(); + enc$1.oidFor(jwk.crv); + enc.add(enc$1.end()); + enc.bitStr(buffer_1.Buffer.from(jwk.x, 'base64')); + const der = enc.end(); + return (0, crypto_1.createPublicKey)({ key: der, format: 'der', type: 'spki' }); + } + default: + throw new errors_js_1.JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value'); + } +}; +exports.default = parse; diff --git a/node_modules/jose/dist/node/cjs/runtime/key_to_jwk.js b/node_modules/jose/dist/node/cjs/runtime/key_to_jwk.js new file mode 100644 index 0000000..6ee2127 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/key_to_jwk.js @@ -0,0 +1,160 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const crypto_1 = require("crypto"); +const base64url_js_1 = require("./base64url.js"); +const asn1_sequence_decoder_js_1 = require("./asn1_sequence_decoder.js"); +const errors_js_1 = require("../util/errors.js"); +const get_named_curve_js_1 = require("./get_named_curve.js"); +const webcrypto_js_1 = require("./webcrypto.js"); +const is_key_object_js_1 = require("./is_key_object.js"); +const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); +const is_key_like_js_1 = require("./is_key_like.js"); +const flags_js_1 = require("./flags.js"); +const keyToJWK = (key) => { + let keyObject; + if ((0, webcrypto_js_1.isCryptoKey)(key)) { + if (!key.extractable) { + throw new TypeError('CryptoKey is not extractable'); + } + keyObject = crypto_1.KeyObject.from(key); + } + else if ((0, is_key_object_js_1.default)(key)) { + keyObject = key; + } + else if (key instanceof Uint8Array) { + return { + kty: 'oct', + k: (0, base64url_js_1.encode)(key), + }; + } + else { + throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array')); + } + if (flags_js_1.jwkExport) { + if (keyObject.type !== 'secret' && + !['rsa', 'ec', 'ed25519', 'x25519', 'ed448', 'x448'].includes(keyObject.asymmetricKeyType)) { + throw new errors_js_1.JOSENotSupported('Unsupported key asymmetricKeyType'); + } + return keyObject.export({ format: 'jwk' }); + } + switch (keyObject.type) { + case 'secret': + return { + kty: 'oct', + k: (0, base64url_js_1.encode)(keyObject.export()), + }; + case 'private': + case 'public': { + switch (keyObject.asymmetricKeyType) { + case 'rsa': { + const der = keyObject.export({ format: 'der', type: 'pkcs1' }); + const dec = new asn1_sequence_decoder_js_1.default(der); + if (keyObject.type === 'private') { + dec.unsignedInteger(); + } + const n = (0, base64url_js_1.encode)(dec.unsignedInteger()); + const e = (0, base64url_js_1.encode)(dec.unsignedInteger()); + let jwk; + if (keyObject.type === 'private') { + jwk = { + d: (0, base64url_js_1.encode)(dec.unsignedInteger()), + p: (0, base64url_js_1.encode)(dec.unsignedInteger()), + q: (0, base64url_js_1.encode)(dec.unsignedInteger()), + dp: (0, base64url_js_1.encode)(dec.unsignedInteger()), + dq: (0, base64url_js_1.encode)(dec.unsignedInteger()), + qi: (0, base64url_js_1.encode)(dec.unsignedInteger()), + }; + } + dec.end(); + return { kty: 'RSA', n, e, ...jwk }; + } + case 'ec': { + const crv = (0, get_named_curve_js_1.default)(keyObject); + let len; + let offset; + let correction; + switch (crv) { + case 'secp256k1': + len = 64; + offset = 31 + 2; + correction = -1; + break; + case 'P-256': + len = 64; + offset = 34 + 2; + correction = -1; + break; + case 'P-384': + len = 96; + offset = 33 + 2; + correction = -3; + break; + case 'P-521': + len = 132; + offset = 33 + 2; + correction = -3; + break; + default: + throw new errors_js_1.JOSENotSupported('Unsupported curve'); + } + if (keyObject.type === 'public') { + const der = keyObject.export({ type: 'spki', format: 'der' }); + return { + kty: 'EC', + crv, + x: (0, base64url_js_1.encode)(der.subarray(-len, -len / 2)), + y: (0, base64url_js_1.encode)(der.subarray(-len / 2)), + }; + } + const der = keyObject.export({ type: 'pkcs8', format: 'der' }); + if (der.length < 100) { + offset += correction; + } + return { + ...keyToJWK((0, crypto_1.createPublicKey)(keyObject)), + d: (0, base64url_js_1.encode)(der.subarray(offset, offset + len / 2)), + }; + } + case 'ed25519': + case 'x25519': { + const crv = (0, get_named_curve_js_1.default)(keyObject); + if (keyObject.type === 'public') { + const der = keyObject.export({ type: 'spki', format: 'der' }); + return { + kty: 'OKP', + crv, + x: (0, base64url_js_1.encode)(der.subarray(-32)), + }; + } + const der = keyObject.export({ type: 'pkcs8', format: 'der' }); + return { + ...keyToJWK((0, crypto_1.createPublicKey)(keyObject)), + d: (0, base64url_js_1.encode)(der.subarray(-32)), + }; + } + case 'ed448': + case 'x448': { + const crv = (0, get_named_curve_js_1.default)(keyObject); + if (keyObject.type === 'public') { + const der = keyObject.export({ type: 'spki', format: 'der' }); + return { + kty: 'OKP', + crv, + x: (0, base64url_js_1.encode)(der.subarray(crv === 'Ed448' ? -57 : -56)), + }; + } + const der = keyObject.export({ type: 'pkcs8', format: 'der' }); + return { + ...keyToJWK((0, crypto_1.createPublicKey)(keyObject)), + d: (0, base64url_js_1.encode)(der.subarray(crv === 'Ed448' ? -57 : -56)), + }; + } + default: + throw new errors_js_1.JOSENotSupported('Unsupported key asymmetricKeyType'); + } + } + default: + throw new errors_js_1.JOSENotSupported('Unsupported key type'); + } +}; +exports.default = keyToJWK; diff --git a/node_modules/jose/dist/node/cjs/runtime/node_key.js b/node_modules/jose/dist/node/cjs/runtime/node_key.js new file mode 100644 index 0000000..df67562 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/node_key.js @@ -0,0 +1,78 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const crypto_1 = require("crypto"); +const get_named_curve_js_1 = require("./get_named_curve.js"); +const errors_js_1 = require("../util/errors.js"); +const check_modulus_length_js_1 = require("./check_modulus_length.js"); +const flags_js_1 = require("./flags.js"); +const PSS = { + padding: crypto_1.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto_1.constants.RSA_PSS_SALTLEN_DIGEST, +}; +const ecCurveAlgMap = new Map([ + ['ES256', 'P-256'], + ['ES256K', 'secp256k1'], + ['ES384', 'P-384'], + ['ES512', 'P-521'], +]); +function keyForCrypto(alg, key) { + switch (alg) { + case 'EdDSA': + if (!['ed25519', 'ed448'].includes(key.asymmetricKeyType)) { + throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448'); + } + return key; + case 'RS256': + case 'RS384': + case 'RS512': + if (key.asymmetricKeyType !== 'rsa') { + throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa'); + } + (0, check_modulus_length_js_1.default)(key, alg); + return key; + case flags_js_1.rsaPssParams && 'PS256': + case flags_js_1.rsaPssParams && 'PS384': + case flags_js_1.rsaPssParams && 'PS512': + if (key.asymmetricKeyType === 'rsa-pss') { + const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = key.asymmetricKeyDetails; + const length = parseInt(alg.slice(-3), 10); + if (hashAlgorithm !== undefined && + (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm)) { + throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${alg}`); + } + if (saltLength !== undefined && saltLength > length >> 3) { + throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${alg}`); + } + } + else if (key.asymmetricKeyType !== 'rsa') { + throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss'); + } + (0, check_modulus_length_js_1.default)(key, alg); + return { key, ...PSS }; + case !flags_js_1.rsaPssParams && 'PS256': + case !flags_js_1.rsaPssParams && 'PS384': + case !flags_js_1.rsaPssParams && 'PS512': + if (key.asymmetricKeyType !== 'rsa') { + throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa'); + } + (0, check_modulus_length_js_1.default)(key, alg); + return { key, ...PSS }; + case 'ES256': + case 'ES256K': + case 'ES384': + case 'ES512': { + if (key.asymmetricKeyType !== 'ec') { + throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ec'); + } + const actual = (0, get_named_curve_js_1.default)(key); + const expected = ecCurveAlgMap.get(alg); + if (actual !== expected) { + throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${expected}, got ${actual}`); + } + return { dsaEncoding: 'ieee-p1363', key }; + } + default: + throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } +} +exports.default = keyForCrypto; diff --git a/node_modules/jose/dist/node/cjs/runtime/pbes2kw.js b/node_modules/jose/dist/node/cjs/runtime/pbes2kw.js new file mode 100644 index 0000000..8298b0e --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/pbes2kw.js @@ -0,0 +1,48 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decrypt = exports.encrypt = void 0; +const util_1 = require("util"); +const crypto_1 = require("crypto"); +const random_js_1 = require("./random.js"); +const buffer_utils_js_1 = require("../lib/buffer_utils.js"); +const base64url_js_1 = require("./base64url.js"); +const aeskw_js_1 = require("./aeskw.js"); +const check_p2s_js_1 = require("../lib/check_p2s.js"); +const webcrypto_js_1 = require("./webcrypto.js"); +const crypto_key_js_1 = require("../lib/crypto_key.js"); +const is_key_object_js_1 = require("./is_key_object.js"); +const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); +const is_key_like_js_1 = require("./is_key_like.js"); +const pbkdf2 = (0, util_1.promisify)(crypto_1.pbkdf2); +function getPassword(key, alg) { + if ((0, is_key_object_js_1.default)(key)) { + return key.export(); + } + if (key instanceof Uint8Array) { + return key; + } + if ((0, webcrypto_js_1.isCryptoKey)(key)) { + (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, 'deriveBits', 'deriveKey'); + return crypto_1.KeyObject.from(key).export(); + } + throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array')); +} +const encrypt = async (alg, key, cek, p2c = 2048, p2s = (0, random_js_1.default)(new Uint8Array(16))) => { + (0, check_p2s_js_1.default)(p2s); + const salt = (0, buffer_utils_js_1.p2s)(alg, p2s); + const keylen = parseInt(alg.slice(13, 16), 10) >> 3; + const password = getPassword(key, alg); + const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`); + const encryptedKey = await (0, aeskw_js_1.wrap)(alg.slice(-6), derivedKey, cek); + return { encryptedKey, p2c, p2s: (0, base64url_js_1.encode)(p2s) }; +}; +exports.encrypt = encrypt; +const decrypt = async (alg, key, encryptedKey, p2c, p2s) => { + (0, check_p2s_js_1.default)(p2s); + const salt = (0, buffer_utils_js_1.p2s)(alg, p2s); + const keylen = parseInt(alg.slice(13, 16), 10) >> 3; + const password = getPassword(key, alg); + const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`); + return (0, aeskw_js_1.unwrap)(alg.slice(-6), derivedKey, encryptedKey); +}; +exports.decrypt = decrypt; diff --git a/node_modules/jose/dist/node/cjs/runtime/random.js b/node_modules/jose/dist/node/cjs/runtime/random.js new file mode 100644 index 0000000..459da2b --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/random.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = void 0; +var crypto_1 = require("crypto"); +Object.defineProperty(exports, "default", { enumerable: true, get: function () { return crypto_1.randomFillSync; } }); diff --git a/node_modules/jose/dist/node/cjs/runtime/rsaes.js b/node_modules/jose/dist/node/cjs/runtime/rsaes.js new file mode 100644 index 0000000..4e62522 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/rsaes.js @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decrypt = exports.encrypt = void 0; +const crypto_1 = require("crypto"); +const check_modulus_length_js_1 = require("./check_modulus_length.js"); +const webcrypto_js_1 = require("./webcrypto.js"); +const crypto_key_js_1 = require("../lib/crypto_key.js"); +const is_key_object_js_1 = require("./is_key_object.js"); +const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); +const is_key_like_js_1 = require("./is_key_like.js"); +const checkKey = (key, alg) => { + if (key.asymmetricKeyType !== 'rsa') { + throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa'); + } + (0, check_modulus_length_js_1.default)(key, alg); +}; +const resolvePadding = (alg) => { + switch (alg) { + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': + return crypto_1.constants.RSA_PKCS1_OAEP_PADDING; + case 'RSA1_5': + return crypto_1.constants.RSA_PKCS1_PADDING; + default: + return undefined; + } +}; +const resolveOaepHash = (alg) => { + switch (alg) { + case 'RSA-OAEP': + return 'sha1'; + case 'RSA-OAEP-256': + return 'sha256'; + case 'RSA-OAEP-384': + return 'sha384'; + case 'RSA-OAEP-512': + return 'sha512'; + default: + return undefined; + } +}; +function ensureKeyObject(key, alg, ...usages) { + if ((0, is_key_object_js_1.default)(key)) { + return key; + } + if ((0, webcrypto_js_1.isCryptoKey)(key)) { + (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, ...usages); + return crypto_1.KeyObject.from(key); + } + throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types)); +} +const encrypt = (alg, key, cek) => { + const padding = resolvePadding(alg); + const oaepHash = resolveOaepHash(alg); + const keyObject = ensureKeyObject(key, alg, 'wrapKey', 'encrypt'); + checkKey(keyObject, alg); + return (0, crypto_1.publicEncrypt)({ key: keyObject, oaepHash, padding }, cek); +}; +exports.encrypt = encrypt; +const decrypt = (alg, key, encryptedKey) => { + const padding = resolvePadding(alg); + const oaepHash = resolveOaepHash(alg); + const keyObject = ensureKeyObject(key, alg, 'unwrapKey', 'decrypt'); + checkKey(keyObject, alg); + return (0, crypto_1.privateDecrypt)({ key: keyObject, oaepHash, padding }, encryptedKey); +}; +exports.decrypt = decrypt; diff --git a/node_modules/jose/dist/node/cjs/runtime/runtime.js b/node_modules/jose/dist/node/cjs/runtime/runtime.js new file mode 100644 index 0000000..89c48ad --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/runtime.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = 'node:crypto'; diff --git a/node_modules/jose/dist/node/cjs/runtime/sign.js b/node_modules/jose/dist/node/cjs/runtime/sign.js new file mode 100644 index 0000000..cc19300 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/sign.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const crypto = require("crypto"); +const util_1 = require("util"); +const dsa_digest_js_1 = require("./dsa_digest.js"); +const hmac_digest_js_1 = require("./hmac_digest.js"); +const node_key_js_1 = require("./node_key.js"); +const get_sign_verify_key_js_1 = require("./get_sign_verify_key.js"); +let oneShotSign; +if (crypto.sign.length > 3) { + oneShotSign = (0, util_1.promisify)(crypto.sign); +} +else { + oneShotSign = crypto.sign; +} +const sign = async (alg, key, data) => { + const keyObject = (0, get_sign_verify_key_js_1.default)(alg, key, 'sign'); + if (alg.startsWith('HS')) { + const hmac = crypto.createHmac((0, hmac_digest_js_1.default)(alg), keyObject); + hmac.update(data); + return hmac.digest(); + } + return oneShotSign((0, dsa_digest_js_1.default)(alg), data, (0, node_key_js_1.default)(alg, keyObject)); +}; +exports.default = sign; diff --git a/node_modules/jose/dist/node/cjs/runtime/timing_safe_equal.js b/node_modules/jose/dist/node/cjs/runtime/timing_safe_equal.js new file mode 100644 index 0000000..e1e4ef6 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/timing_safe_equal.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const crypto_1 = require("crypto"); +const timingSafeEqual = crypto_1.timingSafeEqual; +exports.default = timingSafeEqual; diff --git a/node_modules/jose/dist/node/cjs/runtime/verify.js b/node_modules/jose/dist/node/cjs/runtime/verify.js new file mode 100644 index 0000000..c9a1549 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/verify.js @@ -0,0 +1,38 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const crypto = require("crypto"); +const util_1 = require("util"); +const dsa_digest_js_1 = require("./dsa_digest.js"); +const node_key_js_1 = require("./node_key.js"); +const sign_js_1 = require("./sign.js"); +const get_sign_verify_key_js_1 = require("./get_sign_verify_key.js"); +const flags_js_1 = require("./flags.js"); +let oneShotVerify; +if (crypto.verify.length > 4 && flags_js_1.oneShotCallback) { + oneShotVerify = (0, util_1.promisify)(crypto.verify); +} +else { + oneShotVerify = crypto.verify; +} +const verify = async (alg, key, signature, data) => { + const keyObject = (0, get_sign_verify_key_js_1.default)(alg, key, 'verify'); + if (alg.startsWith('HS')) { + const expected = await (0, sign_js_1.default)(alg, keyObject, data); + const actual = signature; + try { + return crypto.timingSafeEqual(actual, expected); + } + catch { + return false; + } + } + const algorithm = (0, dsa_digest_js_1.default)(alg); + const keyInput = (0, node_key_js_1.default)(alg, keyObject); + try { + return await oneShotVerify(algorithm, data, keyInput, signature); + } + catch { + return false; + } +}; +exports.default = verify; diff --git a/node_modules/jose/dist/node/cjs/runtime/webcrypto.js b/node_modules/jose/dist/node/cjs/runtime/webcrypto.js new file mode 100644 index 0000000..8a3e72e --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/webcrypto.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isCryptoKey = void 0; +const crypto = require("crypto"); +const util = require("util"); +const webcrypto = crypto.webcrypto; +exports.default = webcrypto; +exports.isCryptoKey = util.types.isCryptoKey + ? (key) => util.types.isCryptoKey(key) + : + (key) => false; diff --git a/node_modules/jose/dist/node/cjs/runtime/zlib.js b/node_modules/jose/dist/node/cjs/runtime/zlib.js new file mode 100644 index 0000000..9d9485a --- /dev/null +++ b/node_modules/jose/dist/node/cjs/runtime/zlib.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.deflate = exports.inflate = void 0; +const util_1 = require("util"); +const zlib_1 = require("zlib"); +const errors_js_1 = require("../util/errors.js"); +const inflateRaw = (0, util_1.promisify)(zlib_1.inflateRaw); +const deflateRaw = (0, util_1.promisify)(zlib_1.deflateRaw); +const inflate = (input) => inflateRaw(input, { maxOutputLength: 250000 }).catch(() => { + throw new errors_js_1.JWEDecompressionFailed(); +}); +exports.inflate = inflate; +const deflate = (input) => deflateRaw(input); +exports.deflate = deflate; diff --git a/node_modules/jose/dist/node/cjs/util/base64url.js b/node_modules/jose/dist/node/cjs/util/base64url.js new file mode 100644 index 0000000..4d383b5 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/util/base64url.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decode = exports.encode = void 0; +const base64url = require("../runtime/base64url.js"); +exports.encode = base64url.encode; +exports.decode = base64url.decode; diff --git a/node_modules/jose/dist/node/cjs/util/decode_jwt.js b/node_modules/jose/dist/node/cjs/util/decode_jwt.js new file mode 100644 index 0000000..d481e77 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/util/decode_jwt.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeJwt = void 0; +const base64url_js_1 = require("./base64url.js"); +const buffer_utils_js_1 = require("../lib/buffer_utils.js"); +const is_object_js_1 = require("../lib/is_object.js"); +const errors_js_1 = require("./errors.js"); +function decodeJwt(jwt) { + if (typeof jwt !== 'string') + throw new errors_js_1.JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string'); + const { 1: payload, length } = jwt.split('.'); + if (length === 5) + throw new errors_js_1.JWTInvalid('Only JWTs using Compact JWS serialization can be decoded'); + if (length !== 3) + throw new errors_js_1.JWTInvalid('Invalid JWT'); + if (!payload) + throw new errors_js_1.JWTInvalid('JWTs must contain a payload'); + let decoded; + try { + decoded = (0, base64url_js_1.decode)(payload); + } + catch { + throw new errors_js_1.JWTInvalid('Failed to base64url decode the payload'); + } + let result; + try { + result = JSON.parse(buffer_utils_js_1.decoder.decode(decoded)); + } + catch { + throw new errors_js_1.JWTInvalid('Failed to parse the decoded payload as JSON'); + } + if (!(0, is_object_js_1.default)(result)) + throw new errors_js_1.JWTInvalid('Invalid JWT Claims Set'); + return result; +} +exports.decodeJwt = decodeJwt; diff --git a/node_modules/jose/dist/node/cjs/util/decode_protected_header.js b/node_modules/jose/dist/node/cjs/util/decode_protected_header.js new file mode 100644 index 0000000..601ebb7 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/util/decode_protected_header.js @@ -0,0 +1,38 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeProtectedHeader = void 0; +const base64url_js_1 = require("./base64url.js"); +const buffer_utils_js_1 = require("../lib/buffer_utils.js"); +const is_object_js_1 = require("../lib/is_object.js"); +function decodeProtectedHeader(token) { + let protectedB64u; + if (typeof token === 'string') { + const parts = token.split('.'); + if (parts.length === 3 || parts.length === 5) { + ; + [protectedB64u] = parts; + } + } + else if (typeof token === 'object' && token) { + if ('protected' in token) { + protectedB64u = token.protected; + } + else { + throw new TypeError('Token does not contain a Protected Header'); + } + } + try { + if (typeof protectedB64u !== 'string' || !protectedB64u) { + throw new Error(); + } + const result = JSON.parse(buffer_utils_js_1.decoder.decode((0, base64url_js_1.decode)(protectedB64u))); + if (!(0, is_object_js_1.default)(result)) { + throw new Error(); + } + return result; + } + catch { + throw new TypeError('Invalid Token or Protected Header formatting'); + } +} +exports.decodeProtectedHeader = decodeProtectedHeader; diff --git a/node_modules/jose/dist/node/cjs/util/errors.js b/node_modules/jose/dist/node/cjs/util/errors.js new file mode 100644 index 0000000..de6e53f --- /dev/null +++ b/node_modules/jose/dist/node/cjs/util/errors.js @@ -0,0 +1,177 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.JWSSignatureVerificationFailed = exports.JWKSTimeout = exports.JWKSMultipleMatchingKeys = exports.JWKSNoMatchingKey = exports.JWKSInvalid = exports.JWKInvalid = exports.JWTInvalid = exports.JWSInvalid = exports.JWEInvalid = exports.JWEDecompressionFailed = exports.JWEDecryptionFailed = exports.JOSENotSupported = exports.JOSEAlgNotAllowed = exports.JWTExpired = exports.JWTClaimValidationFailed = exports.JOSEError = void 0; +class JOSEError extends Error { + static get code() { + return 'ERR_JOSE_GENERIC'; + } + constructor(message) { + var _a; + super(message); + this.code = 'ERR_JOSE_GENERIC'; + this.name = this.constructor.name; + (_a = Error.captureStackTrace) === null || _a === void 0 ? void 0 : _a.call(Error, this, this.constructor); + } +} +exports.JOSEError = JOSEError; +class JWTClaimValidationFailed extends JOSEError { + static get code() { + return 'ERR_JWT_CLAIM_VALIDATION_FAILED'; + } + constructor(message, claim = 'unspecified', reason = 'unspecified') { + super(message); + this.code = 'ERR_JWT_CLAIM_VALIDATION_FAILED'; + this.claim = claim; + this.reason = reason; + } +} +exports.JWTClaimValidationFailed = JWTClaimValidationFailed; +class JWTExpired extends JOSEError { + static get code() { + return 'ERR_JWT_EXPIRED'; + } + constructor(message, claim = 'unspecified', reason = 'unspecified') { + super(message); + this.code = 'ERR_JWT_EXPIRED'; + this.claim = claim; + this.reason = reason; + } +} +exports.JWTExpired = JWTExpired; +class JOSEAlgNotAllowed extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JOSE_ALG_NOT_ALLOWED'; + } + static get code() { + return 'ERR_JOSE_ALG_NOT_ALLOWED'; + } +} +exports.JOSEAlgNotAllowed = JOSEAlgNotAllowed; +class JOSENotSupported extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JOSE_NOT_SUPPORTED'; + } + static get code() { + return 'ERR_JOSE_NOT_SUPPORTED'; + } +} +exports.JOSENotSupported = JOSENotSupported; +class JWEDecryptionFailed extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWE_DECRYPTION_FAILED'; + this.message = 'decryption operation failed'; + } + static get code() { + return 'ERR_JWE_DECRYPTION_FAILED'; + } +} +exports.JWEDecryptionFailed = JWEDecryptionFailed; +class JWEDecompressionFailed extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWE_DECOMPRESSION_FAILED'; + this.message = 'decompression operation failed'; + } + static get code() { + return 'ERR_JWE_DECOMPRESSION_FAILED'; + } +} +exports.JWEDecompressionFailed = JWEDecompressionFailed; +class JWEInvalid extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWE_INVALID'; + } + static get code() { + return 'ERR_JWE_INVALID'; + } +} +exports.JWEInvalid = JWEInvalid; +class JWSInvalid extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWS_INVALID'; + } + static get code() { + return 'ERR_JWS_INVALID'; + } +} +exports.JWSInvalid = JWSInvalid; +class JWTInvalid extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWT_INVALID'; + } + static get code() { + return 'ERR_JWT_INVALID'; + } +} +exports.JWTInvalid = JWTInvalid; +class JWKInvalid extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWK_INVALID'; + } + static get code() { + return 'ERR_JWK_INVALID'; + } +} +exports.JWKInvalid = JWKInvalid; +class JWKSInvalid extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWKS_INVALID'; + } + static get code() { + return 'ERR_JWKS_INVALID'; + } +} +exports.JWKSInvalid = JWKSInvalid; +class JWKSNoMatchingKey extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWKS_NO_MATCHING_KEY'; + this.message = 'no applicable key found in the JSON Web Key Set'; + } + static get code() { + return 'ERR_JWKS_NO_MATCHING_KEY'; + } +} +exports.JWKSNoMatchingKey = JWKSNoMatchingKey; +class JWKSMultipleMatchingKeys extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; + this.message = 'multiple matching keys found in the JSON Web Key Set'; + } + static get code() { + return 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; + } +} +exports.JWKSMultipleMatchingKeys = JWKSMultipleMatchingKeys; +Symbol.asyncIterator; +class JWKSTimeout extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWKS_TIMEOUT'; + this.message = 'request timed out'; + } + static get code() { + return 'ERR_JWKS_TIMEOUT'; + } +} +exports.JWKSTimeout = JWKSTimeout; +class JWSSignatureVerificationFailed extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; + this.message = 'signature verification failed'; + } + static get code() { + return 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; + } +} +exports.JWSSignatureVerificationFailed = JWSSignatureVerificationFailed; diff --git a/node_modules/jose/dist/node/cjs/util/runtime.js b/node_modules/jose/dist/node/cjs/util/runtime.js new file mode 100644 index 0000000..ac211f8 --- /dev/null +++ b/node_modules/jose/dist/node/cjs/util/runtime.js @@ -0,0 +1,4 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const runtime_js_1 = require("../runtime/runtime.js"); +exports.default = runtime_js_1.default; diff --git a/node_modules/jose/dist/node/esm/index.js b/node_modules/jose/dist/node/esm/index.js new file mode 100644 index 0000000..1ba3720 --- /dev/null +++ b/node_modules/jose/dist/node/esm/index.js @@ -0,0 +1,30 @@ +export { compactDecrypt } from './jwe/compact/decrypt.js'; +export { flattenedDecrypt } from './jwe/flattened/decrypt.js'; +export { generalDecrypt } from './jwe/general/decrypt.js'; +export { GeneralEncrypt } from './jwe/general/encrypt.js'; +export { compactVerify } from './jws/compact/verify.js'; +export { flattenedVerify } from './jws/flattened/verify.js'; +export { generalVerify } from './jws/general/verify.js'; +export { jwtVerify } from './jwt/verify.js'; +export { jwtDecrypt } from './jwt/decrypt.js'; +export { CompactEncrypt } from './jwe/compact/encrypt.js'; +export { FlattenedEncrypt } from './jwe/flattened/encrypt.js'; +export { CompactSign } from './jws/compact/sign.js'; +export { FlattenedSign } from './jws/flattened/sign.js'; +export { GeneralSign } from './jws/general/sign.js'; +export { SignJWT } from './jwt/sign.js'; +export { EncryptJWT } from './jwt/encrypt.js'; +export { calculateJwkThumbprint, calculateJwkThumbprintUri } from './jwk/thumbprint.js'; +export { EmbeddedJWK } from './jwk/embedded.js'; +export { createLocalJWKSet } from './jwks/local.js'; +export { createRemoteJWKSet } from './jwks/remote.js'; +export { UnsecuredJWT } from './jwt/unsecured.js'; +export { exportPKCS8, exportSPKI, exportJWK } from './key/export.js'; +export { importSPKI, importPKCS8, importX509, importJWK } from './key/import.js'; +export { decodeProtectedHeader } from './util/decode_protected_header.js'; +export { decodeJwt } from './util/decode_jwt.js'; +export * as errors from './util/errors.js'; +export { generateKeyPair } from './key/generate_key_pair.js'; +export { generateSecret } from './key/generate_secret.js'; +export * as base64url from './util/base64url.js'; +export { default as cryptoRuntime } from './util/runtime.js'; diff --git a/node_modules/jose/dist/node/esm/jwe/compact/decrypt.js b/node_modules/jose/dist/node/esm/jwe/compact/decrypt.js new file mode 100644 index 0000000..129aeb6 --- /dev/null +++ b/node_modules/jose/dist/node/esm/jwe/compact/decrypt.js @@ -0,0 +1,27 @@ +import { flattenedDecrypt } from '../flattened/decrypt.js'; +import { JWEInvalid } from '../../util/errors.js'; +import { decoder } from '../../lib/buffer_utils.js'; +export async function compactDecrypt(jwe, key, options) { + if (jwe instanceof Uint8Array) { + jwe = decoder.decode(jwe); + } + if (typeof jwe !== 'string') { + throw new JWEInvalid('Compact JWE must be a string or Uint8Array'); + } + const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length, } = jwe.split('.'); + if (length !== 5) { + throw new JWEInvalid('Invalid Compact JWE'); + } + const decrypted = await flattenedDecrypt({ + ciphertext, + iv: (iv || undefined), + protected: protectedHeader || undefined, + tag: (tag || undefined), + encrypted_key: encryptedKey || undefined, + }, key, options); + const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; + if (typeof key === 'function') { + return { ...result, key: decrypted.key }; + } + return result; +} diff --git a/node_modules/jose/dist/node/esm/jwe/compact/encrypt.js b/node_modules/jose/dist/node/esm/jwe/compact/encrypt.js new file mode 100644 index 0000000..e689139 --- /dev/null +++ b/node_modules/jose/dist/node/esm/jwe/compact/encrypt.js @@ -0,0 +1,26 @@ +import { FlattenedEncrypt } from '../flattened/encrypt.js'; +export class CompactEncrypt { + constructor(plaintext) { + this._flattened = new FlattenedEncrypt(plaintext); + } + setContentEncryptionKey(cek) { + this._flattened.setContentEncryptionKey(cek); + return this; + } + setInitializationVector(iv) { + this._flattened.setInitializationVector(iv); + return this; + } + setProtectedHeader(protectedHeader) { + this._flattened.setProtectedHeader(protectedHeader); + return this; + } + setKeyManagementParameters(parameters) { + this._flattened.setKeyManagementParameters(parameters); + return this; + } + async encrypt(key, options) { + const jwe = await this._flattened.encrypt(key, options); + return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.'); + } +} diff --git a/node_modules/jose/dist/node/esm/jwe/flattened/decrypt.js b/node_modules/jose/dist/node/esm/jwe/flattened/decrypt.js new file mode 100644 index 0000000..254fdcc --- /dev/null +++ b/node_modules/jose/dist/node/esm/jwe/flattened/decrypt.js @@ -0,0 +1,166 @@ +import { decode as base64url } from '../../runtime/base64url.js'; +import decrypt from '../../runtime/decrypt.js'; +import { inflate } from '../../runtime/zlib.js'; +import { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from '../../util/errors.js'; +import isDisjoint from '../../lib/is_disjoint.js'; +import isObject from '../../lib/is_object.js'; +import decryptKeyManagement from '../../lib/decrypt_key_management.js'; +import { encoder, decoder, concat } from '../../lib/buffer_utils.js'; +import generateCek from '../../lib/cek.js'; +import validateCrit from '../../lib/validate_crit.js'; +import validateAlgorithms from '../../lib/validate_algorithms.js'; +export async function flattenedDecrypt(jwe, key, options) { + var _a; + if (!isObject(jwe)) { + throw new JWEInvalid('Flattened JWE must be an object'); + } + if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) { + throw new JWEInvalid('JOSE Header missing'); + } + if (typeof jwe.iv !== 'string') { + throw new JWEInvalid('JWE Initialization Vector missing or incorrect type'); + } + if (typeof jwe.ciphertext !== 'string') { + throw new JWEInvalid('JWE Ciphertext missing or incorrect type'); + } + if (typeof jwe.tag !== 'string') { + throw new JWEInvalid('JWE Authentication Tag missing or incorrect type'); + } + if (jwe.protected !== undefined && typeof jwe.protected !== 'string') { + throw new JWEInvalid('JWE Protected Header incorrect type'); + } + if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') { + throw new JWEInvalid('JWE Encrypted Key incorrect type'); + } + if (jwe.aad !== undefined && typeof jwe.aad !== 'string') { + throw new JWEInvalid('JWE AAD incorrect type'); + } + if (jwe.header !== undefined && !isObject(jwe.header)) { + throw new JWEInvalid('JWE Shared Unprotected Header incorrect type'); + } + if (jwe.unprotected !== undefined && !isObject(jwe.unprotected)) { + throw new JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type'); + } + let parsedProt; + if (jwe.protected) { + try { + const protectedHeader = base64url(jwe.protected); + parsedProt = JSON.parse(decoder.decode(protectedHeader)); + } + catch { + throw new JWEInvalid('JWE Protected Header is invalid'); + } + } + if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) { + throw new JWEInvalid('JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint'); + } + const joseHeader = { + ...parsedProt, + ...jwe.header, + ...jwe.unprotected, + }; + validateCrit(JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader); + if (joseHeader.zip !== undefined) { + if (!parsedProt || !parsedProt.zip) { + throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); + } + if (joseHeader.zip !== 'DEF') { + throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value'); + } + } + const { alg, enc } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new JWEInvalid('missing JWE Algorithm (alg) in JWE Header'); + } + if (typeof enc !== 'string' || !enc) { + throw new JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header'); + } + const keyManagementAlgorithms = options && validateAlgorithms('keyManagementAlgorithms', options.keyManagementAlgorithms); + const contentEncryptionAlgorithms = options && + validateAlgorithms('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms); + if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) { + throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed'); + } + if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) { + throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter not allowed'); + } + let encryptedKey; + if (jwe.encrypted_key !== undefined) { + try { + encryptedKey = base64url(jwe.encrypted_key); + } + catch { + throw new JWEInvalid('Failed to base64url decode the encrypted_key'); + } + } + let resolvedKey = false; + if (typeof key === 'function') { + key = await key(parsedProt, jwe); + resolvedKey = true; + } + let cek; + try { + cek = await decryptKeyManagement(alg, key, encryptedKey, joseHeader, options); + } + catch (err) { + if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) { + throw err; + } + cek = generateCek(enc); + } + let iv; + let tag; + try { + iv = base64url(jwe.iv); + } + catch { + throw new JWEInvalid('Failed to base64url decode the iv'); + } + try { + tag = base64url(jwe.tag); + } + catch { + throw new JWEInvalid('Failed to base64url decode the tag'); + } + const protectedHeader = encoder.encode((_a = jwe.protected) !== null && _a !== void 0 ? _a : ''); + let additionalData; + if (jwe.aad !== undefined) { + additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(jwe.aad)); + } + else { + additionalData = protectedHeader; + } + let ciphertext; + try { + ciphertext = base64url(jwe.ciphertext); + } + catch { + throw new JWEInvalid('Failed to base64url decode the ciphertext'); + } + let plaintext = await decrypt(enc, cek, ciphertext, iv, tag, additionalData); + if (joseHeader.zip === 'DEF') { + plaintext = await ((options === null || options === void 0 ? void 0 : options.inflateRaw) || inflate)(plaintext); + } + const result = { plaintext }; + if (jwe.protected !== undefined) { + result.protectedHeader = parsedProt; + } + if (jwe.aad !== undefined) { + try { + result.additionalAuthenticatedData = base64url(jwe.aad); + } + catch { + throw new JWEInvalid('Failed to base64url decode the aad'); + } + } + if (jwe.unprotected !== undefined) { + result.sharedUnprotectedHeader = jwe.unprotected; + } + if (jwe.header !== undefined) { + result.unprotectedHeader = jwe.header; + } + if (resolvedKey) { + return { ...result, key }; + } + return result; +} diff --git a/node_modules/jose/dist/node/esm/jwe/flattened/encrypt.js b/node_modules/jose/dist/node/esm/jwe/flattened/encrypt.js new file mode 100644 index 0000000..1e60ecd --- /dev/null +++ b/node_modules/jose/dist/node/esm/jwe/flattened/encrypt.js @@ -0,0 +1,175 @@ +import { encode as base64url } from '../../runtime/base64url.js'; +import encrypt from '../../runtime/encrypt.js'; +import { deflate } from '../../runtime/zlib.js'; +import generateIv from '../../lib/iv.js'; +import encryptKeyManagement from '../../lib/encrypt_key_management.js'; +import { JOSENotSupported, JWEInvalid } from '../../util/errors.js'; +import isDisjoint from '../../lib/is_disjoint.js'; +import { encoder, decoder, concat } from '../../lib/buffer_utils.js'; +import validateCrit from '../../lib/validate_crit.js'; +export const unprotected = Symbol(); +export class FlattenedEncrypt { + constructor(plaintext) { + if (!(plaintext instanceof Uint8Array)) { + throw new TypeError('plaintext must be an instance of Uint8Array'); + } + this._plaintext = plaintext; + } + setKeyManagementParameters(parameters) { + if (this._keyManagementParameters) { + throw new TypeError('setKeyManagementParameters can only be called once'); + } + this._keyManagementParameters = parameters; + return this; + } + setProtectedHeader(protectedHeader) { + if (this._protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this._protectedHeader = protectedHeader; + return this; + } + setSharedUnprotectedHeader(sharedUnprotectedHeader) { + if (this._sharedUnprotectedHeader) { + throw new TypeError('setSharedUnprotectedHeader can only be called once'); + } + this._sharedUnprotectedHeader = sharedUnprotectedHeader; + return this; + } + setUnprotectedHeader(unprotectedHeader) { + if (this._unprotectedHeader) { + throw new TypeError('setUnprotectedHeader can only be called once'); + } + this._unprotectedHeader = unprotectedHeader; + return this; + } + setAdditionalAuthenticatedData(aad) { + this._aad = aad; + return this; + } + setContentEncryptionKey(cek) { + if (this._cek) { + throw new TypeError('setContentEncryptionKey can only be called once'); + } + this._cek = cek; + return this; + } + setInitializationVector(iv) { + if (this._iv) { + throw new TypeError('setInitializationVector can only be called once'); + } + this._iv = iv; + return this; + } + async encrypt(key, options) { + if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) { + throw new JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()'); + } + if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) { + throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); + } + const joseHeader = { + ...this._protectedHeader, + ...this._unprotectedHeader, + ...this._sharedUnprotectedHeader, + }; + validateCrit(JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader); + if (joseHeader.zip !== undefined) { + if (!this._protectedHeader || !this._protectedHeader.zip) { + throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); + } + if (joseHeader.zip !== 'DEF') { + throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value'); + } + } + const { alg, enc } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); + } + if (typeof enc !== 'string' || !enc) { + throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); + } + let encryptedKey; + if (alg === 'dir') { + if (this._cek) { + throw new TypeError('setContentEncryptionKey cannot be called when using Direct Encryption'); + } + } + else if (alg === 'ECDH-ES') { + if (this._cek) { + throw new TypeError('setContentEncryptionKey cannot be called when using Direct Key Agreement'); + } + } + let cek; + { + let parameters; + ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, key, this._cek, this._keyManagementParameters)); + if (parameters) { + if (options && unprotected in options) { + if (!this._unprotectedHeader) { + this.setUnprotectedHeader(parameters); + } + else { + this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters }; + } + } + else { + if (!this._protectedHeader) { + this.setProtectedHeader(parameters); + } + else { + this._protectedHeader = { ...this._protectedHeader, ...parameters }; + } + } + } + } + this._iv || (this._iv = generateIv(enc)); + let additionalData; + let protectedHeader; + let aadMember; + if (this._protectedHeader) { + protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader))); + } + else { + protectedHeader = encoder.encode(''); + } + if (this._aad) { + aadMember = base64url(this._aad); + additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(aadMember)); + } + else { + additionalData = protectedHeader; + } + let ciphertext; + let tag; + if (joseHeader.zip === 'DEF') { + const deflated = await ((options === null || options === void 0 ? void 0 : options.deflateRaw) || deflate)(this._plaintext); + ({ ciphertext, tag } = await encrypt(enc, deflated, cek, this._iv, additionalData)); + } + else { + ; + ({ ciphertext, tag } = await encrypt(enc, this._plaintext, cek, this._iv, additionalData)); + } + const jwe = { + ciphertext: base64url(ciphertext), + iv: base64url(this._iv), + tag: base64url(tag), + }; + if (encryptedKey) { + jwe.encrypted_key = base64url(encryptedKey); + } + if (aadMember) { + jwe.aad = aadMember; + } + if (this._protectedHeader) { + jwe.protected = decoder.decode(protectedHeader); + } + if (this._sharedUnprotectedHeader) { + jwe.unprotected = this._sharedUnprotectedHeader; + } + if (this._unprotectedHeader) { + jwe.header = this._unprotectedHeader; + } + return jwe; + } +} diff --git a/node_modules/jose/dist/node/esm/jwe/general/decrypt.js b/node_modules/jose/dist/node/esm/jwe/general/decrypt.js new file mode 100644 index 0000000..659958a --- /dev/null +++ b/node_modules/jose/dist/node/esm/jwe/general/decrypt.js @@ -0,0 +1,31 @@ +import { flattenedDecrypt } from '../flattened/decrypt.js'; +import { JWEDecryptionFailed, JWEInvalid } from '../../util/errors.js'; +import isObject from '../../lib/is_object.js'; +export async function generalDecrypt(jwe, key, options) { + if (!isObject(jwe)) { + throw new JWEInvalid('General JWE must be an object'); + } + if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) { + throw new JWEInvalid('JWE Recipients missing or incorrect type'); + } + if (!jwe.recipients.length) { + throw new JWEInvalid('JWE Recipients has no members'); + } + for (const recipient of jwe.recipients) { + try { + return await flattenedDecrypt({ + aad: jwe.aad, + ciphertext: jwe.ciphertext, + encrypted_key: recipient.encrypted_key, + header: recipient.header, + iv: jwe.iv, + protected: jwe.protected, + tag: jwe.tag, + unprotected: jwe.unprotected, + }, key, options); + } + catch { + } + } + throw new JWEDecryptionFailed(); +} diff --git a/node_modules/jose/dist/node/esm/jwe/general/encrypt.js b/node_modules/jose/dist/node/esm/jwe/general/encrypt.js new file mode 100644 index 0000000..3ee53de --- /dev/null +++ b/node_modules/jose/dist/node/esm/jwe/general/encrypt.js @@ -0,0 +1,178 @@ +import { FlattenedEncrypt, unprotected } from '../flattened/encrypt.js'; +import { JWEInvalid } from '../../util/errors.js'; +import generateCek from '../../lib/cek.js'; +import isDisjoint from '../../lib/is_disjoint.js'; +import encryptKeyManagement from '../../lib/encrypt_key_management.js'; +import { encode as base64url } from '../../runtime/base64url.js'; +import validateCrit from '../../lib/validate_crit.js'; +class IndividualRecipient { + constructor(enc, key, options) { + this.parent = enc; + this.key = key; + this.options = options; + } + setUnprotectedHeader(unprotectedHeader) { + if (this.unprotectedHeader) { + throw new TypeError('setUnprotectedHeader can only be called once'); + } + this.unprotectedHeader = unprotectedHeader; + return this; + } + addRecipient(...args) { + return this.parent.addRecipient(...args); + } + encrypt(...args) { + return this.parent.encrypt(...args); + } + done() { + return this.parent; + } +} +export class GeneralEncrypt { + constructor(plaintext) { + this._recipients = []; + this._plaintext = plaintext; + } + addRecipient(key, options) { + const recipient = new IndividualRecipient(this, key, { crit: options === null || options === void 0 ? void 0 : options.crit }); + this._recipients.push(recipient); + return recipient; + } + setProtectedHeader(protectedHeader) { + if (this._protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this._protectedHeader = protectedHeader; + return this; + } + setSharedUnprotectedHeader(sharedUnprotectedHeader) { + if (this._unprotectedHeader) { + throw new TypeError('setSharedUnprotectedHeader can only be called once'); + } + this._unprotectedHeader = sharedUnprotectedHeader; + return this; + } + setAdditionalAuthenticatedData(aad) { + this._aad = aad; + return this; + } + async encrypt(options) { + var _a, _b, _c; + if (!this._recipients.length) { + throw new JWEInvalid('at least one recipient must be added'); + } + options = { deflateRaw: options === null || options === void 0 ? void 0 : options.deflateRaw }; + if (this._recipients.length === 1) { + const [recipient] = this._recipients; + const flattened = await new FlattenedEncrypt(this._plaintext) + .setAdditionalAuthenticatedData(this._aad) + .setProtectedHeader(this._protectedHeader) + .setSharedUnprotectedHeader(this._unprotectedHeader) + .setUnprotectedHeader(recipient.unprotectedHeader) + .encrypt(recipient.key, { ...recipient.options, ...options }); + let jwe = { + ciphertext: flattened.ciphertext, + iv: flattened.iv, + recipients: [{}], + tag: flattened.tag, + }; + if (flattened.aad) + jwe.aad = flattened.aad; + if (flattened.protected) + jwe.protected = flattened.protected; + if (flattened.unprotected) + jwe.unprotected = flattened.unprotected; + if (flattened.encrypted_key) + jwe.recipients[0].encrypted_key = flattened.encrypted_key; + if (flattened.header) + jwe.recipients[0].header = flattened.header; + return jwe; + } + let enc; + for (let i = 0; i < this._recipients.length; i++) { + const recipient = this._recipients[i]; + if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) { + throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); + } + const joseHeader = { + ...this._protectedHeader, + ...this._unprotectedHeader, + ...recipient.unprotectedHeader, + }; + const { alg } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); + } + if (alg === 'dir' || alg === 'ECDH-ES') { + throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient'); + } + if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) { + throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); + } + if (!enc) { + enc = joseHeader.enc; + } + else if (enc !== joseHeader.enc) { + throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients'); + } + validateCrit(JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader); + if (joseHeader.zip !== undefined) { + if (!this._protectedHeader || !this._protectedHeader.zip) { + throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); + } + } + } + const cek = generateCek(enc); + let jwe = { + ciphertext: '', + iv: '', + recipients: [], + tag: '', + }; + for (let i = 0; i < this._recipients.length; i++) { + const recipient = this._recipients[i]; + const target = {}; + jwe.recipients.push(target); + const joseHeader = { + ...this._protectedHeader, + ...this._unprotectedHeader, + ...recipient.unprotectedHeader, + }; + const p2c = joseHeader.alg.startsWith('PBES2') ? 2048 + i : undefined; + if (i === 0) { + const flattened = await new FlattenedEncrypt(this._plaintext) + .setAdditionalAuthenticatedData(this._aad) + .setContentEncryptionKey(cek) + .setProtectedHeader(this._protectedHeader) + .setSharedUnprotectedHeader(this._unprotectedHeader) + .setUnprotectedHeader(recipient.unprotectedHeader) + .setKeyManagementParameters({ p2c }) + .encrypt(recipient.key, { + ...recipient.options, + ...options, + [unprotected]: true, + }); + jwe.ciphertext = flattened.ciphertext; + jwe.iv = flattened.iv; + jwe.tag = flattened.tag; + if (flattened.aad) + jwe.aad = flattened.aad; + if (flattened.protected) + jwe.protected = flattened.protected; + if (flattened.unprotected) + jwe.unprotected = flattened.unprotected; + target.encrypted_key = flattened.encrypted_key; + if (flattened.header) + target.header = flattened.header; + continue; + } + const { encryptedKey, parameters } = await encryptKeyManagement(((_a = recipient.unprotectedHeader) === null || _a === void 0 ? void 0 : _a.alg) || + ((_b = this._protectedHeader) === null || _b === void 0 ? void 0 : _b.alg) || + ((_c = this._unprotectedHeader) === null || _c === void 0 ? void 0 : _c.alg), enc, recipient.key, cek, { p2c }); + target.encrypted_key = base64url(encryptedKey); + if (recipient.unprotectedHeader || parameters) + target.header = { ...recipient.unprotectedHeader, ...parameters }; + } + return jwe; + } +} diff --git a/node_modules/jose/dist/node/esm/jwk/embedded.js b/node_modules/jose/dist/node/esm/jwk/embedded.js new file mode 100644 index 0000000..561ae25 --- /dev/null +++ b/node_modules/jose/dist/node/esm/jwk/embedded.js @@ -0,0 +1,17 @@ +import { importJWK } from '../key/import.js'; +import isObject from '../lib/is_object.js'; +import { JWSInvalid } from '../util/errors.js'; +export async function EmbeddedJWK(protectedHeader, token) { + const joseHeader = { + ...protectedHeader, + ...token === null || token === void 0 ? void 0 : token.header, + }; + if (!isObject(joseHeader.jwk)) { + throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object'); + } + const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg, true); + if (key instanceof Uint8Array || key.type !== 'public') { + throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key'); + } + return key; +} diff --git a/node_modules/jose/dist/node/esm/jwk/thumbprint.js b/node_modules/jose/dist/node/esm/jwk/thumbprint.js new file mode 100644 index 0000000..49f86b1 --- /dev/null +++ b/node_modules/jose/dist/node/esm/jwk/thumbprint.js @@ -0,0 +1,53 @@ +import digest from '../runtime/digest.js'; +import { encode as base64url } from '../runtime/base64url.js'; +import { JOSENotSupported, JWKInvalid } from '../util/errors.js'; +import { encoder } from '../lib/buffer_utils.js'; +import isObject from '../lib/is_object.js'; +const check = (value, description) => { + if (typeof value !== 'string' || !value) { + throw new JWKInvalid(`${description} missing or invalid`); + } +}; +export async function calculateJwkThumbprint(jwk, digestAlgorithm) { + if (!isObject(jwk)) { + throw new TypeError('JWK must be an object'); + } + digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256'); + if (digestAlgorithm !== 'sha256' && + digestAlgorithm !== 'sha384' && + digestAlgorithm !== 'sha512') { + throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); + } + let components; + switch (jwk.kty) { + case 'EC': + check(jwk.crv, '"crv" (Curve) Parameter'); + check(jwk.x, '"x" (X Coordinate) Parameter'); + check(jwk.y, '"y" (Y Coordinate) Parameter'); + components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; + break; + case 'OKP': + check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); + check(jwk.x, '"x" (Public Key) Parameter'); + components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; + break; + case 'RSA': + check(jwk.e, '"e" (Exponent) Parameter'); + check(jwk.n, '"n" (Modulus) Parameter'); + components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; + break; + case 'oct': + check(jwk.k, '"k" (Key Value) Parameter'); + components = { k: jwk.k, kty: jwk.kty }; + break; + default: + throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); + } + const data = encoder.encode(JSON.stringify(components)); + return base64url(await digest(digestAlgorithm, data)); +} +export async function calculateJwkThumbprintUri(jwk, digestAlgorithm) { + digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256'); + const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm); + return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`; +} diff --git a/node_modules/jose/dist/node/esm/jwks/local.js b/node_modules/jose/dist/node/esm/jwks/local.js new file mode 100644 index 0000000..2356751 --- /dev/null +++ b/node_modules/jose/dist/node/esm/jwks/local.js @@ -0,0 +1,116 @@ +import { importJWK } from '../key/import.js'; +import { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, } from '../util/errors.js'; +import isObject from '../lib/is_object.js'; +function getKtyFromAlg(alg) { + switch (typeof alg === 'string' && alg.slice(0, 2)) { + case 'RS': + case 'PS': + return 'RSA'; + case 'ES': + return 'EC'; + case 'Ed': + return 'OKP'; + default: + throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); + } +} +export function isJWKSLike(jwks) { + return (jwks && + typeof jwks === 'object' && + Array.isArray(jwks.keys) && + jwks.keys.every(isJWKLike)); +} +function isJWKLike(key) { + return isObject(key); +} +function clone(obj) { + if (typeof structuredClone === 'function') { + return structuredClone(obj); + } + return JSON.parse(JSON.stringify(obj)); +} +export class LocalJWKSet { + constructor(jwks) { + this._cached = new WeakMap(); + if (!isJWKSLike(jwks)) { + throw new JWKSInvalid('JSON Web Key Set malformed'); + } + this._jwks = clone(jwks); + } + async getKey(protectedHeader, token) { + const { alg, kid } = { ...protectedHeader, ...token === null || token === void 0 ? void 0 : token.header }; + const kty = getKtyFromAlg(alg); + const candidates = this._jwks.keys.filter((jwk) => { + let candidate = kty === jwk.kty; + if (candidate && typeof kid === 'string') { + candidate = kid === jwk.kid; + } + if (candidate && typeof jwk.alg === 'string') { + candidate = alg === jwk.alg; + } + if (candidate && typeof jwk.use === 'string') { + candidate = jwk.use === 'sig'; + } + if (candidate && Array.isArray(jwk.key_ops)) { + candidate = jwk.key_ops.includes('verify'); + } + if (candidate && alg === 'EdDSA') { + candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448'; + } + if (candidate) { + switch (alg) { + case 'ES256': + candidate = jwk.crv === 'P-256'; + break; + case 'ES256K': + candidate = jwk.crv === 'secp256k1'; + break; + case 'ES384': + candidate = jwk.crv === 'P-384'; + break; + case 'ES512': + candidate = jwk.crv === 'P-521'; + break; + } + } + return candidate; + }); + const { 0: jwk, length } = candidates; + if (length === 0) { + throw new JWKSNoMatchingKey(); + } + else if (length !== 1) { + const error = new JWKSMultipleMatchingKeys(); + const { _cached } = this; + error[Symbol.asyncIterator] = async function* () { + for (const jwk of candidates) { + try { + yield await importWithAlgCache(_cached, jwk, alg); + } + catch { + continue; + } + } + }; + throw error; + } + return importWithAlgCache(this._cached, jwk, alg); + } +} +async function importWithAlgCache(cache, jwk, alg) { + const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk); + if (cached[alg] === undefined) { + const key = await importJWK({ ...jwk, ext: true }, alg); + if (key instanceof Uint8Array || key.type !== 'public') { + throw new JWKSInvalid('JSON Web Key Set members must be public keys'); + } + cached[alg] = key; + } + return cached[alg]; +} +export function createLocalJWKSet(jwks) { + const set = new LocalJWKSet(jwks); + return async function (protectedHeader, token) { + return set.getKey(protectedHeader, token); + }; +} diff --git a/node_modules/jose/dist/node/esm/jwks/remote.js b/node_modules/jose/dist/node/esm/jwks/remote.js new file mode 100644 index 0000000..405f753 --- /dev/null +++ b/node_modules/jose/dist/node/esm/jwks/remote.js @@ -0,0 +1,76 @@ +import fetchJwks from '../runtime/fetch_jwks.js'; +import { JWKSInvalid, JWKSNoMatchingKey } from '../util/errors.js'; +import { isJWKSLike, LocalJWKSet } from './local.js'; +function isCloudflareWorkers() { + return (typeof WebSocketPair !== 'undefined' || + (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') || + (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel')); +} +class RemoteJWKSet extends LocalJWKSet { + constructor(url, options) { + super({ keys: [] }); + this._jwks = undefined; + if (!(url instanceof URL)) { + throw new TypeError('url must be an instance of URL'); + } + this._url = new URL(url.href); + this._options = { agent: options === null || options === void 0 ? void 0 : options.agent, headers: options === null || options === void 0 ? void 0 : options.headers }; + this._timeoutDuration = + typeof (options === null || options === void 0 ? void 0 : options.timeoutDuration) === 'number' ? options === null || options === void 0 ? void 0 : options.timeoutDuration : 5000; + this._cooldownDuration = + typeof (options === null || options === void 0 ? void 0 : options.cooldownDuration) === 'number' ? options === null || options === void 0 ? void 0 : options.cooldownDuration : 30000; + this._cacheMaxAge = typeof (options === null || options === void 0 ? void 0 : options.cacheMaxAge) === 'number' ? options === null || options === void 0 ? void 0 : options.cacheMaxAge : 600000; + } + coolingDown() { + return typeof this._jwksTimestamp === 'number' + ? Date.now() < this._jwksTimestamp + this._cooldownDuration + : false; + } + fresh() { + return typeof this._jwksTimestamp === 'number' + ? Date.now() < this._jwksTimestamp + this._cacheMaxAge + : false; + } + async getKey(protectedHeader, token) { + if (!this._jwks || !this.fresh()) { + await this.reload(); + } + try { + return await super.getKey(protectedHeader, token); + } + catch (err) { + if (err instanceof JWKSNoMatchingKey) { + if (this.coolingDown() === false) { + await this.reload(); + return super.getKey(protectedHeader, token); + } + } + throw err; + } + } + async reload() { + if (this._pendingFetch && isCloudflareWorkers()) { + this._pendingFetch = undefined; + } + this._pendingFetch || (this._pendingFetch = fetchJwks(this._url, this._timeoutDuration, this._options) + .then((json) => { + if (!isJWKSLike(json)) { + throw new JWKSInvalid('JSON Web Key Set malformed'); + } + this._jwks = { keys: json.keys }; + this._jwksTimestamp = Date.now(); + this._pendingFetch = undefined; + }) + .catch((err) => { + this._pendingFetch = undefined; + throw err; + })); + await this._pendingFetch; + } +} +export function createRemoteJWKSet(url, options) { + const set = new RemoteJWKSet(url, options); + return async function (protectedHeader, token) { + return set.getKey(protectedHeader, token); + }; +} diff --git a/node_modules/jose/dist/node/esm/jws/compact/sign.js b/node_modules/jose/dist/node/esm/jws/compact/sign.js new file mode 100644 index 0000000..b8e5ba0 --- /dev/null +++ b/node_modules/jose/dist/node/esm/jws/compact/sign.js @@ -0,0 +1,17 @@ +import { FlattenedSign } from '../flattened/sign.js'; +export class CompactSign { + constructor(payload) { + this._flattened = new FlattenedSign(payload); + } + setProtectedHeader(protectedHeader) { + this._flattened.setProtectedHeader(protectedHeader); + return this; + } + async sign(key, options) { + const jws = await this._flattened.sign(key, options); + if (jws.payload === undefined) { + throw new TypeError('use the flattened module for creating JWS with b64: false'); + } + return `${jws.protected}.${jws.payload}.${jws.signature}`; + } +} diff --git a/node_modules/jose/dist/node/esm/jws/compact/verify.js b/node_modules/jose/dist/node/esm/jws/compact/verify.js new file mode 100644 index 0000000..c651ffb --- /dev/null +++ b/node_modules/jose/dist/node/esm/jws/compact/verify.js @@ -0,0 +1,21 @@ +import { flattenedVerify } from '../flattened/verify.js'; +import { JWSInvalid } from '../../util/errors.js'; +import { decoder } from '../../lib/buffer_utils.js'; +export async function compactVerify(jws, key, options) { + if (jws instanceof Uint8Array) { + jws = decoder.decode(jws); + } + if (typeof jws !== 'string') { + throw new JWSInvalid('Compact JWS must be a string or Uint8Array'); + } + const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.'); + if (length !== 3) { + throw new JWSInvalid('Invalid Compact JWS'); + } + const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options); + const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; + if (typeof key === 'function') { + return { ...result, key: verified.key }; + } + return result; +} diff --git a/node_modules/jose/dist/node/esm/jws/flattened/sign.js b/node_modules/jose/dist/node/esm/jws/flattened/sign.js new file mode 100644 index 0000000..76ae289 --- /dev/null +++ b/node_modules/jose/dist/node/esm/jws/flattened/sign.js @@ -0,0 +1,81 @@ +import { encode as base64url } from '../../runtime/base64url.js'; +import sign from '../../runtime/sign.js'; +import isDisjoint from '../../lib/is_disjoint.js'; +import { JWSInvalid } from '../../util/errors.js'; +import { encoder, decoder, concat } from '../../lib/buffer_utils.js'; +import checkKeyType from '../../lib/check_key_type.js'; +import validateCrit from '../../lib/validate_crit.js'; +export class FlattenedSign { + constructor(payload) { + if (!(payload instanceof Uint8Array)) { + throw new TypeError('payload must be an instance of Uint8Array'); + } + this._payload = payload; + } + setProtectedHeader(protectedHeader) { + if (this._protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this._protectedHeader = protectedHeader; + return this; + } + setUnprotectedHeader(unprotectedHeader) { + if (this._unprotectedHeader) { + throw new TypeError('setUnprotectedHeader can only be called once'); + } + this._unprotectedHeader = unprotectedHeader; + return this; + } + async sign(key, options) { + if (!this._protectedHeader && !this._unprotectedHeader) { + throw new JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()'); + } + if (!isDisjoint(this._protectedHeader, this._unprotectedHeader)) { + throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); + } + const joseHeader = { + ...this._protectedHeader, + ...this._unprotectedHeader, + }; + const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader); + let b64 = true; + if (extensions.has('b64')) { + b64 = this._protectedHeader.b64; + if (typeof b64 !== 'boolean') { + throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); + } + } + const { alg } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); + } + checkKeyType(alg, key, 'sign'); + let payload = this._payload; + if (b64) { + payload = encoder.encode(base64url(payload)); + } + let protectedHeader; + if (this._protectedHeader) { + protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader))); + } + else { + protectedHeader = encoder.encode(''); + } + const data = concat(protectedHeader, encoder.encode('.'), payload); + const signature = await sign(alg, key, data); + const jws = { + signature: base64url(signature), + payload: '', + }; + if (b64) { + jws.payload = decoder.decode(payload); + } + if (this._unprotectedHeader) { + jws.header = this._unprotectedHeader; + } + if (this._protectedHeader) { + jws.protected = decoder.decode(protectedHeader); + } + return jws; + } +} diff --git a/node_modules/jose/dist/node/esm/jws/flattened/verify.js b/node_modules/jose/dist/node/esm/jws/flattened/verify.js new file mode 100644 index 0000000..10c9b4d --- /dev/null +++ b/node_modules/jose/dist/node/esm/jws/flattened/verify.js @@ -0,0 +1,115 @@ +import { decode as base64url } from '../../runtime/base64url.js'; +import verify from '../../runtime/verify.js'; +import { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js'; +import { concat, encoder, decoder } from '../../lib/buffer_utils.js'; +import isDisjoint from '../../lib/is_disjoint.js'; +import isObject from '../../lib/is_object.js'; +import checkKeyType from '../../lib/check_key_type.js'; +import validateCrit from '../../lib/validate_crit.js'; +import validateAlgorithms from '../../lib/validate_algorithms.js'; +export async function flattenedVerify(jws, key, options) { + var _a; + if (!isObject(jws)) { + throw new JWSInvalid('Flattened JWS must be an object'); + } + if (jws.protected === undefined && jws.header === undefined) { + throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); + } + if (jws.protected !== undefined && typeof jws.protected !== 'string') { + throw new JWSInvalid('JWS Protected Header incorrect type'); + } + if (jws.payload === undefined) { + throw new JWSInvalid('JWS Payload missing'); + } + if (typeof jws.signature !== 'string') { + throw new JWSInvalid('JWS Signature missing or incorrect type'); + } + if (jws.header !== undefined && !isObject(jws.header)) { + throw new JWSInvalid('JWS Unprotected Header incorrect type'); + } + let parsedProt = {}; + if (jws.protected) { + try { + const protectedHeader = base64url(jws.protected); + parsedProt = JSON.parse(decoder.decode(protectedHeader)); + } + catch { + throw new JWSInvalid('JWS Protected Header is invalid'); + } + } + if (!isDisjoint(parsedProt, jws.header)) { + throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); + } + const joseHeader = { + ...parsedProt, + ...jws.header, + }; + const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader); + let b64 = true; + if (extensions.has('b64')) { + b64 = parsedProt.b64; + if (typeof b64 !== 'boolean') { + throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); + } + } + const { alg } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); + } + const algorithms = options && validateAlgorithms('algorithms', options.algorithms); + if (algorithms && !algorithms.has(alg)) { + throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed'); + } + if (b64) { + if (typeof jws.payload !== 'string') { + throw new JWSInvalid('JWS Payload must be a string'); + } + } + else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) { + throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance'); + } + let resolvedKey = false; + if (typeof key === 'function') { + key = await key(parsedProt, jws); + resolvedKey = true; + } + checkKeyType(alg, key, 'verify'); + const data = concat(encoder.encode((_a = jws.protected) !== null && _a !== void 0 ? _a : ''), encoder.encode('.'), typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload); + let signature; + try { + signature = base64url(jws.signature); + } + catch { + throw new JWSInvalid('Failed to base64url decode the signature'); + } + const verified = await verify(alg, key, signature, data); + if (!verified) { + throw new JWSSignatureVerificationFailed(); + } + let payload; + if (b64) { + try { + payload = base64url(jws.payload); + } + catch { + throw new JWSInvalid('Failed to base64url decode the payload'); + } + } + else if (typeof jws.payload === 'string') { + payload = encoder.encode(jws.payload); + } + else { + payload = jws.payload; + } + const result = { payload }; + if (jws.protected !== undefined) { + result.protectedHeader = parsedProt; + } + if (jws.header !== undefined) { + result.unprotectedHeader = jws.header; + } + if (resolvedKey) { + return { ...result, key }; + } + return result; +} diff --git a/node_modules/jose/dist/node/esm/jws/general/sign.js b/node_modules/jose/dist/node/esm/jws/general/sign.js new file mode 100644 index 0000000..0e0d645 --- /dev/null +++ b/node_modules/jose/dist/node/esm/jws/general/sign.js @@ -0,0 +1,67 @@ +import { FlattenedSign } from '../flattened/sign.js'; +import { JWSInvalid } from '../../util/errors.js'; +class IndividualSignature { + constructor(sig, key, options) { + this.parent = sig; + this.key = key; + this.options = options; + } + setProtectedHeader(protectedHeader) { + if (this.protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this.protectedHeader = protectedHeader; + return this; + } + setUnprotectedHeader(unprotectedHeader) { + if (this.unprotectedHeader) { + throw new TypeError('setUnprotectedHeader can only be called once'); + } + this.unprotectedHeader = unprotectedHeader; + return this; + } + addSignature(...args) { + return this.parent.addSignature(...args); + } + sign(...args) { + return this.parent.sign(...args); + } + done() { + return this.parent; + } +} +export class GeneralSign { + constructor(payload) { + this._signatures = []; + this._payload = payload; + } + addSignature(key, options) { + const signature = new IndividualSignature(this, key, options); + this._signatures.push(signature); + return signature; + } + async sign() { + if (!this._signatures.length) { + throw new JWSInvalid('at least one signature must be added'); + } + const jws = { + signatures: [], + payload: '', + }; + for (let i = 0; i < this._signatures.length; i++) { + const signature = this._signatures[i]; + const flattened = new FlattenedSign(this._payload); + flattened.setProtectedHeader(signature.protectedHeader); + flattened.setUnprotectedHeader(signature.unprotectedHeader); + const { payload, ...rest } = await flattened.sign(signature.key, signature.options); + if (i === 0) { + jws.payload = payload; + } + else if (jws.payload !== payload) { + throw new JWSInvalid('inconsistent use of JWS Unencoded Payload (RFC7797)'); + } + jws.signatures.push(rest); + } + return jws; + } +} diff --git a/node_modules/jose/dist/node/esm/jws/general/verify.js b/node_modules/jose/dist/node/esm/jws/general/verify.js new file mode 100644 index 0000000..c511b72 --- /dev/null +++ b/node_modules/jose/dist/node/esm/jws/general/verify.js @@ -0,0 +1,24 @@ +import { flattenedVerify } from '../flattened/verify.js'; +import { JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js'; +import isObject from '../../lib/is_object.js'; +export async function generalVerify(jws, key, options) { + if (!isObject(jws)) { + throw new JWSInvalid('General JWS must be an object'); + } + if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) { + throw new JWSInvalid('JWS Signatures missing or incorrect type'); + } + for (const signature of jws.signatures) { + try { + return await flattenedVerify({ + header: signature.header, + payload: jws.payload, + protected: signature.protected, + signature: signature.signature, + }, key, options); + } + catch { + } + } + throw new JWSSignatureVerificationFailed(); +} diff --git a/node_modules/jose/dist/node/esm/jwt/decrypt.js b/node_modules/jose/dist/node/esm/jwt/decrypt.js new file mode 100644 index 0000000..1ec2be2 --- /dev/null +++ b/node_modules/jose/dist/node/esm/jwt/decrypt.js @@ -0,0 +1,23 @@ +import { compactDecrypt } from '../jwe/compact/decrypt.js'; +import jwtPayload from '../lib/jwt_claims_set.js'; +import { JWTClaimValidationFailed } from '../util/errors.js'; +export async function jwtDecrypt(jwt, key, options) { + const decrypted = await compactDecrypt(jwt, key, options); + const payload = jwtPayload(decrypted.protectedHeader, decrypted.plaintext, options); + const { protectedHeader } = decrypted; + if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) { + throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', 'iss', 'mismatch'); + } + if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) { + throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', 'sub', 'mismatch'); + } + if (protectedHeader.aud !== undefined && + JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) { + throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', 'aud', 'mismatch'); + } + const result = { payload, protectedHeader }; + if (typeof key === 'function') { + return { ...result, key: decrypted.key }; + } + return result; +} diff --git a/node_modules/jose/dist/node/esm/jwt/encrypt.js b/node_modules/jose/dist/node/esm/jwt/encrypt.js new file mode 100644 index 0000000..1525295 --- /dev/null +++ b/node_modules/jose/dist/node/esm/jwt/encrypt.js @@ -0,0 +1,68 @@ +import { CompactEncrypt } from '../jwe/compact/encrypt.js'; +import { encoder } from '../lib/buffer_utils.js'; +import { ProduceJWT } from './produce.js'; +export class EncryptJWT extends ProduceJWT { + setProtectedHeader(protectedHeader) { + if (this._protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this._protectedHeader = protectedHeader; + return this; + } + setKeyManagementParameters(parameters) { + if (this._keyManagementParameters) { + throw new TypeError('setKeyManagementParameters can only be called once'); + } + this._keyManagementParameters = parameters; + return this; + } + setContentEncryptionKey(cek) { + if (this._cek) { + throw new TypeError('setContentEncryptionKey can only be called once'); + } + this._cek = cek; + return this; + } + setInitializationVector(iv) { + if (this._iv) { + throw new TypeError('setInitializationVector can only be called once'); + } + this._iv = iv; + return this; + } + replicateIssuerAsHeader() { + this._replicateIssuerAsHeader = true; + return this; + } + replicateSubjectAsHeader() { + this._replicateSubjectAsHeader = true; + return this; + } + replicateAudienceAsHeader() { + this._replicateAudienceAsHeader = true; + return this; + } + async encrypt(key, options) { + const enc = new CompactEncrypt(encoder.encode(JSON.stringify(this._payload))); + if (this._replicateIssuerAsHeader) { + this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss }; + } + if (this._replicateSubjectAsHeader) { + this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub }; + } + if (this._replicateAudienceAsHeader) { + this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud }; + } + enc.setProtectedHeader(this._protectedHeader); + if (this._iv) { + enc.setInitializationVector(this._iv); + } + if (this._cek) { + enc.setContentEncryptionKey(this._cek); + } + if (this._keyManagementParameters) { + enc.setKeyManagementParameters(this._keyManagementParameters); + } + return enc.encrypt(key, options); + } +} diff --git a/node_modules/jose/dist/node/esm/jwt/produce.js b/node_modules/jose/dist/node/esm/jwt/produce.js new file mode 100644 index 0000000..31c929a --- /dev/null +++ b/node_modules/jose/dist/node/esm/jwt/produce.js @@ -0,0 +1,54 @@ +import epoch from '../lib/epoch.js'; +import isObject from '../lib/is_object.js'; +import secs from '../lib/secs.js'; +export class ProduceJWT { + constructor(payload) { + if (!isObject(payload)) { + throw new TypeError('JWT Claims Set MUST be an object'); + } + this._payload = payload; + } + setIssuer(issuer) { + this._payload = { ...this._payload, iss: issuer }; + return this; + } + setSubject(subject) { + this._payload = { ...this._payload, sub: subject }; + return this; + } + setAudience(audience) { + this._payload = { ...this._payload, aud: audience }; + return this; + } + setJti(jwtId) { + this._payload = { ...this._payload, jti: jwtId }; + return this; + } + setNotBefore(input) { + if (typeof input === 'number') { + this._payload = { ...this._payload, nbf: input }; + } + else { + this._payload = { ...this._payload, nbf: epoch(new Date()) + secs(input) }; + } + return this; + } + setExpirationTime(input) { + if (typeof input === 'number') { + this._payload = { ...this._payload, exp: input }; + } + else { + this._payload = { ...this._payload, exp: epoch(new Date()) + secs(input) }; + } + return this; + } + setIssuedAt(input) { + if (typeof input === 'undefined') { + this._payload = { ...this._payload, iat: epoch(new Date()) }; + } + else { + this._payload = { ...this._payload, iat: input }; + } + return this; + } +} diff --git a/node_modules/jose/dist/node/esm/jwt/sign.js b/node_modules/jose/dist/node/esm/jwt/sign.js new file mode 100644 index 0000000..62352fb --- /dev/null +++ b/node_modules/jose/dist/node/esm/jwt/sign.js @@ -0,0 +1,21 @@ +import { CompactSign } from '../jws/compact/sign.js'; +import { JWTInvalid } from '../util/errors.js'; +import { encoder } from '../lib/buffer_utils.js'; +import { ProduceJWT } from './produce.js'; +export class SignJWT extends ProduceJWT { + setProtectedHeader(protectedHeader) { + this._protectedHeader = protectedHeader; + return this; + } + async sign(key, options) { + var _a; + const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload))); + sig.setProtectedHeader(this._protectedHeader); + if (Array.isArray((_a = this._protectedHeader) === null || _a === void 0 ? void 0 : _a.crit) && + this._protectedHeader.crit.includes('b64') && + this._protectedHeader.b64 === false) { + throw new JWTInvalid('JWTs MUST NOT use unencoded payload'); + } + return sig.sign(key, options); + } +} diff --git a/node_modules/jose/dist/node/esm/jwt/unsecured.js b/node_modules/jose/dist/node/esm/jwt/unsecured.js new file mode 100644 index 0000000..41c7c33 --- /dev/null +++ b/node_modules/jose/dist/node/esm/jwt/unsecured.js @@ -0,0 +1,32 @@ +import * as base64url from '../runtime/base64url.js'; +import { decoder } from '../lib/buffer_utils.js'; +import { JWTInvalid } from '../util/errors.js'; +import jwtPayload from '../lib/jwt_claims_set.js'; +import { ProduceJWT } from './produce.js'; +export class UnsecuredJWT extends ProduceJWT { + encode() { + const header = base64url.encode(JSON.stringify({ alg: 'none' })); + const payload = base64url.encode(JSON.stringify(this._payload)); + return `${header}.${payload}.`; + } + static decode(jwt, options) { + if (typeof jwt !== 'string') { + throw new JWTInvalid('Unsecured JWT must be a string'); + } + const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.'); + if (length !== 3 || signature !== '') { + throw new JWTInvalid('Invalid Unsecured JWT'); + } + let header; + try { + header = JSON.parse(decoder.decode(base64url.decode(encodedHeader))); + if (header.alg !== 'none') + throw new Error(); + } + catch { + throw new JWTInvalid('Invalid Unsecured JWT'); + } + const payload = jwtPayload(header, base64url.decode(encodedPayload), options); + return { payload, header }; + } +} diff --git a/node_modules/jose/dist/node/esm/jwt/verify.js b/node_modules/jose/dist/node/esm/jwt/verify.js new file mode 100644 index 0000000..89571c1 --- /dev/null +++ b/node_modules/jose/dist/node/esm/jwt/verify.js @@ -0,0 +1,16 @@ +import { compactVerify } from '../jws/compact/verify.js'; +import jwtPayload from '../lib/jwt_claims_set.js'; +import { JWTInvalid } from '../util/errors.js'; +export async function jwtVerify(jwt, key, options) { + var _a; + const verified = await compactVerify(jwt, key, options); + if (((_a = verified.protectedHeader.crit) === null || _a === void 0 ? void 0 : _a.includes('b64')) && verified.protectedHeader.b64 === false) { + throw new JWTInvalid('JWTs MUST NOT use unencoded payload'); + } + const payload = jwtPayload(verified.protectedHeader, verified.payload, options); + const result = { payload, protectedHeader: verified.protectedHeader }; + if (typeof key === 'function') { + return { ...result, key: verified.key }; + } + return result; +} diff --git a/node_modules/jose/dist/node/esm/key/export.js b/node_modules/jose/dist/node/esm/key/export.js new file mode 100644 index 0000000..e401704 --- /dev/null +++ b/node_modules/jose/dist/node/esm/key/export.js @@ -0,0 +1,12 @@ +import { toSPKI as exportPublic } from '../runtime/asn1.js'; +import { toPKCS8 as exportPrivate } from '../runtime/asn1.js'; +import keyToJWK from '../runtime/key_to_jwk.js'; +export async function exportSPKI(key) { + return exportPublic(key); +} +export async function exportPKCS8(key) { + return exportPrivate(key); +} +export async function exportJWK(key) { + return keyToJWK(key); +} diff --git a/node_modules/jose/dist/node/esm/key/generate_key_pair.js b/node_modules/jose/dist/node/esm/key/generate_key_pair.js new file mode 100644 index 0000000..03b9ee5 --- /dev/null +++ b/node_modules/jose/dist/node/esm/key/generate_key_pair.js @@ -0,0 +1,4 @@ +import { generateKeyPair as generate } from '../runtime/generate.js'; +export async function generateKeyPair(alg, options) { + return generate(alg, options); +} diff --git a/node_modules/jose/dist/node/esm/key/generate_secret.js b/node_modules/jose/dist/node/esm/key/generate_secret.js new file mode 100644 index 0000000..58f308a --- /dev/null +++ b/node_modules/jose/dist/node/esm/key/generate_secret.js @@ -0,0 +1,4 @@ +import { generateSecret as generate } from '../runtime/generate.js'; +export async function generateSecret(alg, options) { + return generate(alg, options); +} diff --git a/node_modules/jose/dist/node/esm/key/import.js b/node_modules/jose/dist/node/esm/key/import.js new file mode 100644 index 0000000..25bb0e1 --- /dev/null +++ b/node_modules/jose/dist/node/esm/key/import.js @@ -0,0 +1,50 @@ +import { decode as decodeBase64URL } from '../runtime/base64url.js'; +import { fromSPKI, fromPKCS8, fromX509 } from '../runtime/asn1.js'; +import asKeyObject from '../runtime/jwk_to_key.js'; +import { JOSENotSupported } from '../util/errors.js'; +import isObject from '../lib/is_object.js'; +export async function importSPKI(spki, alg, options) { + if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) { + throw new TypeError('"spki" must be SPKI formatted string'); + } + return fromSPKI(spki, alg, options); +} +export async function importX509(x509, alg, options) { + if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) { + throw new TypeError('"x509" must be X.509 formatted string'); + } + return fromX509(x509, alg, options); +} +export async function importPKCS8(pkcs8, alg, options) { + if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) { + throw new TypeError('"pkcs8" must be PKCS#8 formatted string'); + } + return fromPKCS8(pkcs8, alg, options); +} +export async function importJWK(jwk, alg, octAsKeyObject) { + var _a; + if (!isObject(jwk)) { + throw new TypeError('JWK must be an object'); + } + alg || (alg = jwk.alg); + switch (jwk.kty) { + case 'oct': + if (typeof jwk.k !== 'string' || !jwk.k) { + throw new TypeError('missing "k" (Key Value) Parameter value'); + } + octAsKeyObject !== null && octAsKeyObject !== void 0 ? octAsKeyObject : (octAsKeyObject = jwk.ext !== true); + if (octAsKeyObject) { + return asKeyObject({ ...jwk, alg, ext: (_a = jwk.ext) !== null && _a !== void 0 ? _a : false }); + } + return decodeBase64URL(jwk.k); + case 'RSA': + if (jwk.oth !== undefined) { + throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); + } + case 'EC': + case 'OKP': + return asKeyObject({ ...jwk, alg }); + default: + throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); + } +} diff --git a/node_modules/jose/dist/node/esm/lib/aesgcmkw.js b/node_modules/jose/dist/node/esm/lib/aesgcmkw.js new file mode 100644 index 0000000..de3f4f9 --- /dev/null +++ b/node_modules/jose/dist/node/esm/lib/aesgcmkw.js @@ -0,0 +1,14 @@ +import encrypt from '../runtime/encrypt.js'; +import decrypt from '../runtime/decrypt.js'; +import generateIv from './iv.js'; +import { encode as base64url } from '../runtime/base64url.js'; +export async function wrap(alg, key, cek, iv) { + const jweAlgorithm = alg.slice(0, 7); + iv || (iv = generateIv(jweAlgorithm)); + const { ciphertext: encryptedKey, tag } = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array(0)); + return { encryptedKey, iv: base64url(iv), tag: base64url(tag) }; +} +export async function unwrap(alg, key, encryptedKey, iv, tag) { + const jweAlgorithm = alg.slice(0, 7); + return decrypt(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0)); +} diff --git a/node_modules/jose/dist/node/esm/lib/buffer_utils.js b/node_modules/jose/dist/node/esm/lib/buffer_utils.js new file mode 100644 index 0000000..5a1a7b3 --- /dev/null +++ b/node_modules/jose/dist/node/esm/lib/buffer_utils.js @@ -0,0 +1,51 @@ +import digest from '../runtime/digest.js'; +export const encoder = new TextEncoder(); +export const decoder = new TextDecoder(); +const MAX_INT32 = 2 ** 32; +export function concat(...buffers) { + const size = buffers.reduce((acc, { length }) => acc + length, 0); + const buf = new Uint8Array(size); + let i = 0; + buffers.forEach((buffer) => { + buf.set(buffer, i); + i += buffer.length; + }); + return buf; +} +export function p2s(alg, p2sInput) { + return concat(encoder.encode(alg), new Uint8Array([0]), p2sInput); +} +function writeUInt32BE(buf, value, offset) { + if (value < 0 || value >= MAX_INT32) { + throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); + } + buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset); +} +export function uint64be(value) { + const high = Math.floor(value / MAX_INT32); + const low = value % MAX_INT32; + const buf = new Uint8Array(8); + writeUInt32BE(buf, high, 0); + writeUInt32BE(buf, low, 4); + return buf; +} +export function uint32be(value) { + const buf = new Uint8Array(4); + writeUInt32BE(buf, value); + return buf; +} +export function lengthAndInput(input) { + return concat(uint32be(input.length), input); +} +export async function concatKdf(secret, bits, value) { + const iterations = Math.ceil((bits >> 3) / 32); + const res = new Uint8Array(iterations * 32); + for (let iter = 0; iter < iterations; iter++) { + const buf = new Uint8Array(4 + secret.length + value.length); + buf.set(uint32be(iter + 1)); + buf.set(secret, 4); + buf.set(value, 4 + secret.length); + res.set(await digest('sha256', buf), iter * 32); + } + return res.slice(0, bits >> 3); +} diff --git a/node_modules/jose/dist/node/esm/lib/cek.js b/node_modules/jose/dist/node/esm/lib/cek.js new file mode 100644 index 0000000..34697d3 --- /dev/null +++ b/node_modules/jose/dist/node/esm/lib/cek.js @@ -0,0 +1,20 @@ +import { JOSENotSupported } from '../util/errors.js'; +import random from '../runtime/random.js'; +export function bitLength(alg) { + switch (alg) { + case 'A128GCM': + return 128; + case 'A192GCM': + return 192; + case 'A256GCM': + case 'A128CBC-HS256': + return 256; + case 'A192CBC-HS384': + return 384; + case 'A256CBC-HS512': + return 512; + default: + throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); + } +} +export default (alg) => random(new Uint8Array(bitLength(alg) >> 3)); diff --git a/node_modules/jose/dist/node/esm/lib/check_iv_length.js b/node_modules/jose/dist/node/esm/lib/check_iv_length.js new file mode 100644 index 0000000..dcd28d3 --- /dev/null +++ b/node_modules/jose/dist/node/esm/lib/check_iv_length.js @@ -0,0 +1,8 @@ +import { JWEInvalid } from '../util/errors.js'; +import { bitLength } from './iv.js'; +const checkIvLength = (enc, iv) => { + if (iv.length << 3 !== bitLength(enc)) { + throw new JWEInvalid('Invalid Initialization Vector length'); + } +}; +export default checkIvLength; diff --git a/node_modules/jose/dist/node/esm/lib/check_key_type.js b/node_modules/jose/dist/node/esm/lib/check_key_type.js new file mode 100644 index 0000000..43f3dcb --- /dev/null +++ b/node_modules/jose/dist/node/esm/lib/check_key_type.js @@ -0,0 +1,45 @@ +import { withAlg as invalidKeyInput } from './invalid_key_input.js'; +import isKeyLike, { types } from '../runtime/is_key_like.js'; +const symmetricTypeCheck = (alg, key) => { + if (key instanceof Uint8Array) + return; + if (!isKeyLike(key)) { + throw new TypeError(invalidKeyInput(alg, key, ...types, 'Uint8Array')); + } + if (key.type !== 'secret') { + throw new TypeError(`${types.join(' or ')} instances for symmetric algorithms must be of type "secret"`); + } +}; +const asymmetricTypeCheck = (alg, key, usage) => { + if (!isKeyLike(key)) { + throw new TypeError(invalidKeyInput(alg, key, ...types)); + } + if (key.type === 'secret') { + throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithms must not be of type "secret"`); + } + if (usage === 'sign' && key.type === 'public') { + throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm signing must be of type "private"`); + } + if (usage === 'decrypt' && key.type === 'public') { + throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm decryption must be of type "private"`); + } + if (key.algorithm && usage === 'verify' && key.type === 'private') { + throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm verifying must be of type "public"`); + } + if (key.algorithm && usage === 'encrypt' && key.type === 'private') { + throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm encryption must be of type "public"`); + } +}; +const checkKeyType = (alg, key, usage) => { + const symmetric = alg.startsWith('HS') || + alg === 'dir' || + alg.startsWith('PBES2') || + /^A\d{3}(?:GCM)?KW$/.test(alg); + if (symmetric) { + symmetricTypeCheck(alg, key); + } + else { + asymmetricTypeCheck(alg, key, usage); + } +}; +export default checkKeyType; diff --git a/node_modules/jose/dist/node/esm/lib/check_p2s.js b/node_modules/jose/dist/node/esm/lib/check_p2s.js new file mode 100644 index 0000000..a65289f --- /dev/null +++ b/node_modules/jose/dist/node/esm/lib/check_p2s.js @@ -0,0 +1,6 @@ +import { JWEInvalid } from '../util/errors.js'; +export default function checkP2s(p2s) { + if (!(p2s instanceof Uint8Array) || p2s.length < 8) { + throw new JWEInvalid('PBES2 Salt Input must be 8 or more octets'); + } +} diff --git a/node_modules/jose/dist/node/esm/lib/crypto_key.js b/node_modules/jose/dist/node/esm/lib/crypto_key.js new file mode 100644 index 0000000..807e951 --- /dev/null +++ b/node_modules/jose/dist/node/esm/lib/crypto_key.js @@ -0,0 +1,152 @@ +function unusable(name, prop = 'algorithm.name') { + return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); +} +function isAlgorithm(algorithm, name) { + return algorithm.name === name; +} +function getHashLength(hash) { + return parseInt(hash.name.slice(4), 10); +} +function getNamedCurve(alg) { + switch (alg) { + case 'ES256': + return 'P-256'; + case 'ES384': + return 'P-384'; + case 'ES512': + return 'P-521'; + default: + throw new Error('unreachable'); + } +} +function checkUsage(key, usages) { + if (usages.length && !usages.some((expected) => key.usages.includes(expected))) { + let msg = 'CryptoKey does not support this operation, its usages must include '; + if (usages.length > 2) { + const last = usages.pop(); + msg += `one of ${usages.join(', ')}, or ${last}.`; + } + else if (usages.length === 2) { + msg += `one of ${usages[0]} or ${usages[1]}.`; + } + else { + msg += `${usages[0]}.`; + } + throw new TypeError(msg); + } +} +export function checkSigCryptoKey(key, alg, ...usages) { + switch (alg) { + case 'HS256': + case 'HS384': + case 'HS512': { + if (!isAlgorithm(key.algorithm, 'HMAC')) + throw unusable('HMAC'); + const expected = parseInt(alg.slice(2), 10); + const actual = getHashLength(key.algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, 'algorithm.hash'); + break; + } + case 'RS256': + case 'RS384': + case 'RS512': { + if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5')) + throw unusable('RSASSA-PKCS1-v1_5'); + const expected = parseInt(alg.slice(2), 10); + const actual = getHashLength(key.algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, 'algorithm.hash'); + break; + } + case 'PS256': + case 'PS384': + case 'PS512': { + if (!isAlgorithm(key.algorithm, 'RSA-PSS')) + throw unusable('RSA-PSS'); + const expected = parseInt(alg.slice(2), 10); + const actual = getHashLength(key.algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, 'algorithm.hash'); + break; + } + case 'EdDSA': { + if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') { + throw unusable('Ed25519 or Ed448'); + } + break; + } + case 'ES256': + case 'ES384': + case 'ES512': { + if (!isAlgorithm(key.algorithm, 'ECDSA')) + throw unusable('ECDSA'); + const expected = getNamedCurve(alg); + const actual = key.algorithm.namedCurve; + if (actual !== expected) + throw unusable(expected, 'algorithm.namedCurve'); + break; + } + default: + throw new TypeError('CryptoKey does not support this operation'); + } + checkUsage(key, usages); +} +export function checkEncCryptoKey(key, alg, ...usages) { + switch (alg) { + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': { + if (!isAlgorithm(key.algorithm, 'AES-GCM')) + throw unusable('AES-GCM'); + const expected = parseInt(alg.slice(1, 4), 10); + const actual = key.algorithm.length; + if (actual !== expected) + throw unusable(expected, 'algorithm.length'); + break; + } + case 'A128KW': + case 'A192KW': + case 'A256KW': { + if (!isAlgorithm(key.algorithm, 'AES-KW')) + throw unusable('AES-KW'); + const expected = parseInt(alg.slice(1, 4), 10); + const actual = key.algorithm.length; + if (actual !== expected) + throw unusable(expected, 'algorithm.length'); + break; + } + case 'ECDH': { + switch (key.algorithm.name) { + case 'ECDH': + case 'X25519': + case 'X448': + break; + default: + throw unusable('ECDH, X25519, or X448'); + } + break; + } + case 'PBES2-HS256+A128KW': + case 'PBES2-HS384+A192KW': + case 'PBES2-HS512+A256KW': + if (!isAlgorithm(key.algorithm, 'PBKDF2')) + throw unusable('PBKDF2'); + break; + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': { + if (!isAlgorithm(key.algorithm, 'RSA-OAEP')) + throw unusable('RSA-OAEP'); + const expected = parseInt(alg.slice(9), 10) || 1; + const actual = getHashLength(key.algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, 'algorithm.hash'); + break; + } + default: + throw new TypeError('CryptoKey does not support this operation'); + } + checkUsage(key, usages); +} diff --git a/node_modules/jose/dist/node/esm/lib/decrypt_key_management.js b/node_modules/jose/dist/node/esm/lib/decrypt_key_management.js new file mode 100644 index 0000000..24729d7 --- /dev/null +++ b/node_modules/jose/dist/node/esm/lib/decrypt_key_management.js @@ -0,0 +1,127 @@ +import { unwrap as aesKw } from '../runtime/aeskw.js'; +import * as ECDH from '../runtime/ecdhes.js'; +import { decrypt as pbes2Kw } from '../runtime/pbes2kw.js'; +import { decrypt as rsaEs } from '../runtime/rsaes.js'; +import { decode as base64url } from '../runtime/base64url.js'; +import { JOSENotSupported, JWEInvalid } from '../util/errors.js'; +import { bitLength as cekLength } from '../lib/cek.js'; +import { importJWK } from '../key/import.js'; +import checkKeyType from './check_key_type.js'; +import isObject from './is_object.js'; +import { unwrap as aesGcmKw } from './aesgcmkw.js'; +async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) { + checkKeyType(alg, key, 'decrypt'); + switch (alg) { + case 'dir': { + if (encryptedKey !== undefined) + throw new JWEInvalid('Encountered unexpected JWE Encrypted Key'); + return key; + } + case 'ECDH-ES': + if (encryptedKey !== undefined) + throw new JWEInvalid('Encountered unexpected JWE Encrypted Key'); + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': { + if (!isObject(joseHeader.epk)) + throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); + if (!ECDH.ecdhAllowed(key)) + throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); + const epk = await importJWK(joseHeader.epk, alg); + let partyUInfo; + let partyVInfo; + if (joseHeader.apu !== undefined) { + if (typeof joseHeader.apu !== 'string') + throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); + try { + partyUInfo = base64url(joseHeader.apu); + } + catch { + throw new JWEInvalid('Failed to base64url decode the apu'); + } + } + if (joseHeader.apv !== undefined) { + if (typeof joseHeader.apv !== 'string') + throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); + try { + partyVInfo = base64url(joseHeader.apv); + } + catch { + throw new JWEInvalid('Failed to base64url decode the apv'); + } + } + const sharedSecret = await ECDH.deriveKey(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? cekLength(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo); + if (alg === 'ECDH-ES') + return sharedSecret; + if (encryptedKey === undefined) + throw new JWEInvalid('JWE Encrypted Key missing'); + return aesKw(alg.slice(-6), sharedSecret, encryptedKey); + } + case 'RSA1_5': + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': { + if (encryptedKey === undefined) + throw new JWEInvalid('JWE Encrypted Key missing'); + return rsaEs(alg, key, encryptedKey); + } + case 'PBES2-HS256+A128KW': + case 'PBES2-HS384+A192KW': + case 'PBES2-HS512+A256KW': { + if (encryptedKey === undefined) + throw new JWEInvalid('JWE Encrypted Key missing'); + if (typeof joseHeader.p2c !== 'number') + throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`); + const p2cLimit = (options === null || options === void 0 ? void 0 : options.maxPBES2Count) || 10000; + if (joseHeader.p2c > p2cLimit) + throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`); + if (typeof joseHeader.p2s !== 'string') + throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`); + let p2s; + try { + p2s = base64url(joseHeader.p2s); + } + catch { + throw new JWEInvalid('Failed to base64url decode the p2s'); + } + return pbes2Kw(alg, key, encryptedKey, joseHeader.p2c, p2s); + } + case 'A128KW': + case 'A192KW': + case 'A256KW': { + if (encryptedKey === undefined) + throw new JWEInvalid('JWE Encrypted Key missing'); + return aesKw(alg, key, encryptedKey); + } + case 'A128GCMKW': + case 'A192GCMKW': + case 'A256GCMKW': { + if (encryptedKey === undefined) + throw new JWEInvalid('JWE Encrypted Key missing'); + if (typeof joseHeader.iv !== 'string') + throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`); + if (typeof joseHeader.tag !== 'string') + throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`); + let iv; + try { + iv = base64url(joseHeader.iv); + } + catch { + throw new JWEInvalid('Failed to base64url decode the iv'); + } + let tag; + try { + tag = base64url(joseHeader.tag); + } + catch { + throw new JWEInvalid('Failed to base64url decode the tag'); + } + return aesGcmKw(alg, key, encryptedKey, iv, tag); + } + default: { + throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); + } + } +} +export default decryptKeyManagement; diff --git a/node_modules/jose/dist/node/esm/lib/encrypt_key_management.js b/node_modules/jose/dist/node/esm/lib/encrypt_key_management.js new file mode 100644 index 0000000..eb9022c --- /dev/null +++ b/node_modules/jose/dist/node/esm/lib/encrypt_key_management.js @@ -0,0 +1,87 @@ +import { wrap as aesKw } from '../runtime/aeskw.js'; +import * as ECDH from '../runtime/ecdhes.js'; +import { encrypt as pbes2Kw } from '../runtime/pbes2kw.js'; +import { encrypt as rsaEs } from '../runtime/rsaes.js'; +import { encode as base64url } from '../runtime/base64url.js'; +import generateCek, { bitLength as cekLength } from '../lib/cek.js'; +import { JOSENotSupported } from '../util/errors.js'; +import { exportJWK } from '../key/export.js'; +import checkKeyType from './check_key_type.js'; +import { wrap as aesGcmKw } from './aesgcmkw.js'; +async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) { + let encryptedKey; + let parameters; + let cek; + checkKeyType(alg, key, 'encrypt'); + switch (alg) { + case 'dir': { + cek = key; + break; + } + case 'ECDH-ES': + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': { + if (!ECDH.ecdhAllowed(key)) { + throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); + } + const { apu, apv } = providedParameters; + let { epk: ephemeralKey } = providedParameters; + ephemeralKey || (ephemeralKey = (await ECDH.generateEpk(key)).privateKey); + const { x, y, crv, kty } = await exportJWK(ephemeralKey); + const sharedSecret = await ECDH.deriveKey(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv); + parameters = { epk: { x, crv, kty } }; + if (kty === 'EC') + parameters.epk.y = y; + if (apu) + parameters.apu = base64url(apu); + if (apv) + parameters.apv = base64url(apv); + if (alg === 'ECDH-ES') { + cek = sharedSecret; + break; + } + cek = providedCek || generateCek(enc); + const kwAlg = alg.slice(-6); + encryptedKey = await aesKw(kwAlg, sharedSecret, cek); + break; + } + case 'RSA1_5': + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': { + cek = providedCek || generateCek(enc); + encryptedKey = await rsaEs(alg, key, cek); + break; + } + case 'PBES2-HS256+A128KW': + case 'PBES2-HS384+A192KW': + case 'PBES2-HS512+A256KW': { + cek = providedCek || generateCek(enc); + const { p2c, p2s } = providedParameters; + ({ encryptedKey, ...parameters } = await pbes2Kw(alg, key, cek, p2c, p2s)); + break; + } + case 'A128KW': + case 'A192KW': + case 'A256KW': { + cek = providedCek || generateCek(enc); + encryptedKey = await aesKw(alg, key, cek); + break; + } + case 'A128GCMKW': + case 'A192GCMKW': + case 'A256GCMKW': { + cek = providedCek || generateCek(enc); + const { iv } = providedParameters; + ({ encryptedKey, ...parameters } = await aesGcmKw(alg, key, cek, iv)); + break; + } + default: { + throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); + } + } + return { cek, encryptedKey, parameters }; +} +export default encryptKeyManagement; diff --git a/node_modules/jose/dist/node/esm/lib/epoch.js b/node_modules/jose/dist/node/esm/lib/epoch.js new file mode 100644 index 0000000..e405e4b --- /dev/null +++ b/node_modules/jose/dist/node/esm/lib/epoch.js @@ -0,0 +1 @@ +export default (date) => Math.floor(date.getTime() / 1000); diff --git a/node_modules/jose/dist/node/esm/lib/invalid_key_input.js b/node_modules/jose/dist/node/esm/lib/invalid_key_input.js new file mode 100644 index 0000000..049e66e --- /dev/null +++ b/node_modules/jose/dist/node/esm/lib/invalid_key_input.js @@ -0,0 +1,30 @@ +function message(msg, actual, ...types) { + if (types.length > 2) { + const last = types.pop(); + msg += `one of type ${types.join(', ')}, or ${last}.`; + } + else if (types.length === 2) { + msg += `one of type ${types[0]} or ${types[1]}.`; + } + else { + msg += `of type ${types[0]}.`; + } + if (actual == null) { + msg += ` Received ${actual}`; + } + else if (typeof actual === 'function' && actual.name) { + msg += ` Received function ${actual.name}`; + } + else if (typeof actual === 'object' && actual != null) { + if (actual.constructor && actual.constructor.name) { + msg += ` Received an instance of ${actual.constructor.name}`; + } + } + return msg; +} +export default (actual, ...types) => { + return message('Key must be ', actual, ...types); +}; +export function withAlg(alg, actual, ...types) { + return message(`Key for the ${alg} algorithm must be `, actual, ...types); +} diff --git a/node_modules/jose/dist/node/esm/lib/is_disjoint.js b/node_modules/jose/dist/node/esm/lib/is_disjoint.js new file mode 100644 index 0000000..6f64350 --- /dev/null +++ b/node_modules/jose/dist/node/esm/lib/is_disjoint.js @@ -0,0 +1,22 @@ +const isDisjoint = (...headers) => { + const sources = headers.filter(Boolean); + if (sources.length === 0 || sources.length === 1) { + return true; + } + let acc; + for (const header of sources) { + const parameters = Object.keys(header); + if (!acc || acc.size === 0) { + acc = new Set(parameters); + continue; + } + for (const parameter of parameters) { + if (acc.has(parameter)) { + return false; + } + acc.add(parameter); + } + } + return true; +}; +export default isDisjoint; diff --git a/node_modules/jose/dist/node/esm/lib/is_object.js b/node_modules/jose/dist/node/esm/lib/is_object.js new file mode 100644 index 0000000..4955e93 --- /dev/null +++ b/node_modules/jose/dist/node/esm/lib/is_object.js @@ -0,0 +1,16 @@ +function isObjectLike(value) { + return typeof value === 'object' && value !== null; +} +export default function isObject(input) { + if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') { + return false; + } + if (Object.getPrototypeOf(input) === null) { + return true; + } + let proto = input; + while (Object.getPrototypeOf(proto) !== null) { + proto = Object.getPrototypeOf(proto); + } + return Object.getPrototypeOf(input) === proto; +} diff --git a/node_modules/jose/dist/node/esm/lib/iv.js b/node_modules/jose/dist/node/esm/lib/iv.js new file mode 100644 index 0000000..cab2a12 --- /dev/null +++ b/node_modules/jose/dist/node/esm/lib/iv.js @@ -0,0 +1,20 @@ +import { JOSENotSupported } from '../util/errors.js'; +import random from '../runtime/random.js'; +export function bitLength(alg) { + switch (alg) { + case 'A128GCM': + case 'A128GCMKW': + case 'A192GCM': + case 'A192GCMKW': + case 'A256GCM': + case 'A256GCMKW': + return 96; + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + return 128; + default: + throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); + } +} +export default (alg) => random(new Uint8Array(bitLength(alg) >> 3)); diff --git a/node_modules/jose/dist/node/esm/lib/jwt_claims_set.js b/node_modules/jose/dist/node/esm/lib/jwt_claims_set.js new file mode 100644 index 0000000..6bc6140 --- /dev/null +++ b/node_modules/jose/dist/node/esm/lib/jwt_claims_set.js @@ -0,0 +1,102 @@ +import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js'; +import { decoder } from './buffer_utils.js'; +import epoch from './epoch.js'; +import secs from './secs.js'; +import isObject from './is_object.js'; +const normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, ''); +const checkAudiencePresence = (audPayload, audOption) => { + if (typeof audPayload === 'string') { + return audOption.includes(audPayload); + } + if (Array.isArray(audPayload)) { + return audOption.some(Set.prototype.has.bind(new Set(audPayload))); + } + return false; +}; +export default (protectedHeader, encodedPayload, options = {}) => { + const { typ } = options; + if (typ && + (typeof protectedHeader.typ !== 'string' || + normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { + throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', 'typ', 'check_failed'); + } + let payload; + try { + payload = JSON.parse(decoder.decode(encodedPayload)); + } + catch { + } + if (!isObject(payload)) { + throw new JWTInvalid('JWT Claims Set must be a top-level JSON object'); + } + const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; + if (maxTokenAge !== undefined) + requiredClaims.push('iat'); + if (audience !== undefined) + requiredClaims.push('aud'); + if (subject !== undefined) + requiredClaims.push('sub'); + if (issuer !== undefined) + requiredClaims.push('iss'); + for (const claim of new Set(requiredClaims.reverse())) { + if (!(claim in payload)) { + throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, claim, 'missing'); + } + } + if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { + throw new JWTClaimValidationFailed('unexpected "iss" claim value', 'iss', 'check_failed'); + } + if (subject && payload.sub !== subject) { + throw new JWTClaimValidationFailed('unexpected "sub" claim value', 'sub', 'check_failed'); + } + if (audience && + !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) { + throw new JWTClaimValidationFailed('unexpected "aud" claim value', 'aud', 'check_failed'); + } + let tolerance; + switch (typeof options.clockTolerance) { + case 'string': + tolerance = secs(options.clockTolerance); + break; + case 'number': + tolerance = options.clockTolerance; + break; + case 'undefined': + tolerance = 0; + break; + default: + throw new TypeError('Invalid clockTolerance option type'); + } + const { currentDate } = options; + const now = epoch(currentDate || new Date()); + if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') { + throw new JWTClaimValidationFailed('"iat" claim must be a number', 'iat', 'invalid'); + } + if (payload.nbf !== undefined) { + if (typeof payload.nbf !== 'number') { + throw new JWTClaimValidationFailed('"nbf" claim must be a number', 'nbf', 'invalid'); + } + if (payload.nbf > now + tolerance) { + throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', 'nbf', 'check_failed'); + } + } + if (payload.exp !== undefined) { + if (typeof payload.exp !== 'number') { + throw new JWTClaimValidationFailed('"exp" claim must be a number', 'exp', 'invalid'); + } + if (payload.exp <= now - tolerance) { + throw new JWTExpired('"exp" claim timestamp check failed', 'exp', 'check_failed'); + } + } + if (maxTokenAge) { + const age = now - payload.iat; + const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge); + if (age - tolerance > max) { + throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', 'iat', 'check_failed'); + } + if (age < 0 - tolerance) { + throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', 'iat', 'check_failed'); + } + } + return payload; +}; diff --git a/node_modules/jose/dist/node/esm/lib/secs.js b/node_modules/jose/dist/node/esm/lib/secs.js new file mode 100644 index 0000000..cf470ed --- /dev/null +++ b/node_modules/jose/dist/node/esm/lib/secs.js @@ -0,0 +1,44 @@ +const minute = 60; +const hour = minute * 60; +const day = hour * 24; +const week = day * 7; +const year = day * 365.25; +const REGEX = /^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i; +export default (str) => { + const matched = REGEX.exec(str); + if (!matched) { + throw new TypeError('Invalid time period format'); + } + const value = parseFloat(matched[1]); + const unit = matched[2].toLowerCase(); + switch (unit) { + case 'sec': + case 'secs': + case 'second': + case 'seconds': + case 's': + return Math.round(value); + case 'minute': + case 'minutes': + case 'min': + case 'mins': + case 'm': + return Math.round(value * minute); + case 'hour': + case 'hours': + case 'hr': + case 'hrs': + case 'h': + return Math.round(value * hour); + case 'day': + case 'days': + case 'd': + return Math.round(value * day); + case 'week': + case 'weeks': + case 'w': + return Math.round(value * week); + default: + return Math.round(value * year); + } +}; diff --git a/node_modules/jose/dist/node/esm/lib/validate_algorithms.js b/node_modules/jose/dist/node/esm/lib/validate_algorithms.js new file mode 100644 index 0000000..a6a7918 --- /dev/null +++ b/node_modules/jose/dist/node/esm/lib/validate_algorithms.js @@ -0,0 +1,11 @@ +const validateAlgorithms = (option, algorithms) => { + if (algorithms !== undefined && + (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) { + throw new TypeError(`"${option}" option must be an array of strings`); + } + if (!algorithms) { + return undefined; + } + return new Set(algorithms); +}; +export default validateAlgorithms; diff --git a/node_modules/jose/dist/node/esm/lib/validate_crit.js b/node_modules/jose/dist/node/esm/lib/validate_crit.js new file mode 100644 index 0000000..68c69f1 --- /dev/null +++ b/node_modules/jose/dist/node/esm/lib/validate_crit.js @@ -0,0 +1,34 @@ +import { JOSENotSupported } from '../util/errors.js'; +function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { + if (joseHeader.crit !== undefined && protectedHeader.crit === undefined) { + throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); + } + if (!protectedHeader || protectedHeader.crit === undefined) { + return new Set(); + } + if (!Array.isArray(protectedHeader.crit) || + protectedHeader.crit.length === 0 || + protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) { + throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); + } + let recognized; + if (recognizedOption !== undefined) { + recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); + } + else { + recognized = recognizedDefault; + } + for (const parameter of protectedHeader.crit) { + if (!recognized.has(parameter)) { + throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); + } + if (joseHeader[parameter] === undefined) { + throw new Err(`Extension Header Parameter "${parameter}" is missing`); + } + else if (recognized.get(parameter) && protectedHeader[parameter] === undefined) { + throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); + } + } + return new Set(protectedHeader.crit); +} +export default validateCrit; diff --git a/node_modules/jose/dist/node/esm/package.json b/node_modules/jose/dist/node/esm/package.json new file mode 100644 index 0000000..8fb7e8f --- /dev/null +++ b/node_modules/jose/dist/node/esm/package.json @@ -0,0 +1 @@ +{"type":"module","sideEffects":false} diff --git a/node_modules/jose/dist/node/esm/runtime/aeskw.js b/node_modules/jose/dist/node/esm/runtime/aeskw.js new file mode 100644 index 0000000..722b8b3 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/aeskw.js @@ -0,0 +1,50 @@ +import { Buffer } from 'buffer'; +import { KeyObject, createDecipheriv, createCipheriv, createSecretKey } from 'crypto'; +import { JOSENotSupported } from '../util/errors.js'; +import { concat } from '../lib/buffer_utils.js'; +import { isCryptoKey } from './webcrypto.js'; +import { checkEncCryptoKey } from '../lib/crypto_key.js'; +import isKeyObject from './is_key_object.js'; +import invalidKeyInput from '../lib/invalid_key_input.js'; +import supported from './ciphers.js'; +import { types } from './is_key_like.js'; +function checkKeySize(key, alg) { + if (key.symmetricKeySize << 3 !== parseInt(alg.slice(1, 4), 10)) { + throw new TypeError(`Invalid key size for alg: ${alg}`); + } +} +function ensureKeyObject(key, alg, usage) { + if (isKeyObject(key)) { + return key; + } + if (key instanceof Uint8Array) { + return createSecretKey(key); + } + if (isCryptoKey(key)) { + checkEncCryptoKey(key, alg, usage); + return KeyObject.from(key); + } + throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); +} +export const wrap = (alg, key, cek) => { + const size = parseInt(alg.slice(1, 4), 10); + const algorithm = `aes${size}-wrap`; + if (!supported(algorithm)) { + throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } + const keyObject = ensureKeyObject(key, alg, 'wrapKey'); + checkKeySize(keyObject, alg); + const cipher = createCipheriv(algorithm, keyObject, Buffer.alloc(8, 0xa6)); + return concat(cipher.update(cek), cipher.final()); +}; +export const unwrap = (alg, key, encryptedKey) => { + const size = parseInt(alg.slice(1, 4), 10); + const algorithm = `aes${size}-wrap`; + if (!supported(algorithm)) { + throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } + const keyObject = ensureKeyObject(key, alg, 'unwrapKey'); + checkKeySize(keyObject, alg); + const cipher = createDecipheriv(algorithm, keyObject, Buffer.alloc(8, 0xa6)); + return concat(cipher.update(encryptedKey), cipher.final()); +}; diff --git a/node_modules/jose/dist/node/esm/runtime/asn1.js b/node_modules/jose/dist/node/esm/runtime/asn1.js new file mode 100644 index 0000000..d6f447e --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/asn1.js @@ -0,0 +1,46 @@ +import { createPrivateKey, createPublicKey, KeyObject } from 'crypto'; +import { Buffer } from 'buffer'; +import { isCryptoKey } from './webcrypto.js'; +import isKeyObject from './is_key_object.js'; +import invalidKeyInput from '../lib/invalid_key_input.js'; +import { types } from './is_key_like.js'; +const genericExport = (keyType, keyFormat, key) => { + let keyObject; + if (isCryptoKey(key)) { + if (!key.extractable) { + throw new TypeError('CryptoKey is not extractable'); + } + keyObject = KeyObject.from(key); + } + else if (isKeyObject(key)) { + keyObject = key; + } + else { + throw new TypeError(invalidKeyInput(key, ...types)); + } + if (keyObject.type !== keyType) { + throw new TypeError(`key is not a ${keyType} key`); + } + return keyObject.export({ format: 'pem', type: keyFormat }); +}; +export const toSPKI = (key) => { + return genericExport('public', 'spki', key); +}; +export const toPKCS8 = (key) => { + return genericExport('private', 'pkcs8', key); +}; +export const fromPKCS8 = (pem) => createPrivateKey({ + key: Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, ''), 'base64'), + type: 'pkcs8', + format: 'der', +}); +export const fromSPKI = (pem) => createPublicKey({ + key: Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, ''), 'base64'), + type: 'spki', + format: 'der', +}); +export const fromX509 = (pem) => createPublicKey({ + key: pem, + type: 'spki', + format: 'pem', +}); diff --git a/node_modules/jose/dist/node/esm/runtime/asn1_sequence_decoder.js b/node_modules/jose/dist/node/esm/runtime/asn1_sequence_decoder.js new file mode 100644 index 0000000..61ba4c3 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/asn1_sequence_decoder.js @@ -0,0 +1,44 @@ +const tagInteger = 0x02; +const tagSequence = 0x30; +export default class Asn1SequenceDecoder { + constructor(buffer) { + if (buffer[0] !== tagSequence) { + throw new TypeError(); + } + this.buffer = buffer; + this.offset = 1; + const len = this.decodeLength(); + if (len !== buffer.length - this.offset) { + throw new TypeError(); + } + } + decodeLength() { + let length = this.buffer[this.offset++]; + if (length & 0x80) { + const nBytes = length & ~0x80; + length = 0; + for (let i = 0; i < nBytes; i++) + length = (length << 8) | this.buffer[this.offset + i]; + this.offset += nBytes; + } + return length; + } + unsignedInteger() { + if (this.buffer[this.offset++] !== tagInteger) { + throw new TypeError(); + } + let length = this.decodeLength(); + if (this.buffer[this.offset] === 0) { + this.offset++; + length--; + } + const result = this.buffer.slice(this.offset, this.offset + length); + this.offset += length; + return result; + } + end() { + if (this.offset !== this.buffer.length) { + throw new TypeError(); + } + } +} diff --git a/node_modules/jose/dist/node/esm/runtime/asn1_sequence_encoder.js b/node_modules/jose/dist/node/esm/runtime/asn1_sequence_encoder.js new file mode 100644 index 0000000..ac67277 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/asn1_sequence_encoder.js @@ -0,0 +1,88 @@ +import { Buffer } from 'buffer'; +import { JOSENotSupported } from '../util/errors.js'; +const tagInteger = 0x02; +const tagBitStr = 0x03; +const tagOctStr = 0x04; +const tagSequence = 0x30; +const bZero = Buffer.from([0x00]); +const bTagInteger = Buffer.from([tagInteger]); +const bTagBitStr = Buffer.from([tagBitStr]); +const bTagSequence = Buffer.from([tagSequence]); +const bTagOctStr = Buffer.from([tagOctStr]); +const encodeLength = (len) => { + if (len < 128) + return Buffer.from([len]); + const buffer = Buffer.alloc(5); + buffer.writeUInt32BE(len, 1); + let offset = 1; + while (buffer[offset] === 0) + offset++; + buffer[offset - 1] = 0x80 | (5 - offset); + return buffer.slice(offset - 1); +}; +const oids = new Map([ + ['P-256', Buffer.from('06 08 2A 86 48 CE 3D 03 01 07'.replace(/ /g, ''), 'hex')], + ['secp256k1', Buffer.from('06 05 2B 81 04 00 0A'.replace(/ /g, ''), 'hex')], + ['P-384', Buffer.from('06 05 2B 81 04 00 22'.replace(/ /g, ''), 'hex')], + ['P-521', Buffer.from('06 05 2B 81 04 00 23'.replace(/ /g, ''), 'hex')], + ['ecPublicKey', Buffer.from('06 07 2A 86 48 CE 3D 02 01'.replace(/ /g, ''), 'hex')], + ['X25519', Buffer.from('06 03 2B 65 6E'.replace(/ /g, ''), 'hex')], + ['X448', Buffer.from('06 03 2B 65 6F'.replace(/ /g, ''), 'hex')], + ['Ed25519', Buffer.from('06 03 2B 65 70'.replace(/ /g, ''), 'hex')], + ['Ed448', Buffer.from('06 03 2B 65 71'.replace(/ /g, ''), 'hex')], +]); +export default class DumbAsn1Encoder { + constructor() { + this.length = 0; + this.elements = []; + } + oidFor(oid) { + const bOid = oids.get(oid); + if (!bOid) { + throw new JOSENotSupported('Invalid or unsupported OID'); + } + this.elements.push(bOid); + this.length += bOid.length; + } + zero() { + this.elements.push(bTagInteger, Buffer.from([0x01]), bZero); + this.length += 3; + } + one() { + this.elements.push(bTagInteger, Buffer.from([0x01]), Buffer.from([0x01])); + this.length += 3; + } + unsignedInteger(integer) { + if (integer[0] & 0x80) { + const len = encodeLength(integer.length + 1); + this.elements.push(bTagInteger, len, bZero, integer); + this.length += 2 + len.length + integer.length; + } + else { + let i = 0; + while (integer[i] === 0 && (integer[i + 1] & 0x80) === 0) + i++; + const len = encodeLength(integer.length - i); + this.elements.push(bTagInteger, encodeLength(integer.length - i), integer.slice(i)); + this.length += 1 + len.length + integer.length - i; + } + } + octStr(octStr) { + const len = encodeLength(octStr.length); + this.elements.push(bTagOctStr, encodeLength(octStr.length), octStr); + this.length += 1 + len.length + octStr.length; + } + bitStr(bitS) { + const len = encodeLength(bitS.length + 1); + this.elements.push(bTagBitStr, encodeLength(bitS.length + 1), bZero, bitS); + this.length += 1 + len.length + bitS.length + 1; + } + add(seq) { + this.elements.push(seq); + this.length += seq.length; + } + end(tag = bTagSequence) { + const len = encodeLength(this.length); + return Buffer.concat([tag, len, ...this.elements], 1 + len.length + this.length); + } +} diff --git a/node_modules/jose/dist/node/esm/runtime/base64url.js b/node_modules/jose/dist/node/esm/runtime/base64url.js new file mode 100644 index 0000000..1579359 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/base64url.js @@ -0,0 +1,20 @@ +import { Buffer } from 'buffer'; +import { decoder } from '../lib/buffer_utils.js'; +let encode; +function normalize(input) { + let encoded = input; + if (encoded instanceof Uint8Array) { + encoded = decoder.decode(encoded); + } + return encoded; +} +if (Buffer.isEncoding('base64url')) { + encode = (input) => Buffer.from(input).toString('base64url'); +} +else { + encode = (input) => Buffer.from(input).toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); +} +export const decodeBase64 = (input) => Buffer.from(input, 'base64'); +export const encodeBase64 = (input) => Buffer.from(input).toString('base64'); +export { encode }; +export const decode = (input) => Buffer.from(normalize(input), 'base64'); diff --git a/node_modules/jose/dist/node/esm/runtime/cbc_tag.js b/node_modules/jose/dist/node/esm/runtime/cbc_tag.js new file mode 100644 index 0000000..fa58c38 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/cbc_tag.js @@ -0,0 +1,8 @@ +import { createHmac } from 'crypto'; +import { concat, uint64be } from '../lib/buffer_utils.js'; +export default function cbcTag(aad, iv, ciphertext, macSize, macKey, keySize) { + const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); + const hmac = createHmac(`sha${macSize}`, macKey); + hmac.update(macData); + return hmac.digest().slice(0, keySize >> 3); +} diff --git a/node_modules/jose/dist/node/esm/runtime/check_cek_length.js b/node_modules/jose/dist/node/esm/runtime/check_cek_length.js new file mode 100644 index 0000000..60884c0 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/check_cek_length.js @@ -0,0 +1,35 @@ +import { JWEInvalid, JOSENotSupported } from '../util/errors.js'; +import isKeyObject from './is_key_object.js'; +const checkCekLength = (enc, cek) => { + let expected; + switch (enc) { + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + expected = parseInt(enc.slice(-3), 10); + break; + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': + expected = parseInt(enc.slice(1, 4), 10); + break; + default: + throw new JOSENotSupported(`Content Encryption Algorithm ${enc} is not supported either by JOSE or your javascript runtime`); + } + if (cek instanceof Uint8Array) { + const actual = cek.byteLength << 3; + if (actual !== expected) { + throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); + } + return; + } + if (isKeyObject(cek) && cek.type === 'secret') { + const actual = cek.symmetricKeySize << 3; + if (actual !== expected) { + throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); + } + return; + } + throw new TypeError('Invalid Content Encryption Key type'); +}; +export default checkCekLength; diff --git a/node_modules/jose/dist/node/esm/runtime/check_modulus_length.js b/node_modules/jose/dist/node/esm/runtime/check_modulus_length.js new file mode 100644 index 0000000..690f809 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/check_modulus_length.js @@ -0,0 +1,48 @@ +export const weakMap = new WeakMap(); +const getLength = (buf, index) => { + let len = buf.readUInt8(1); + if ((len & 0x80) === 0) { + if (index === 0) { + return len; + } + return getLength(buf.subarray(2 + len), index - 1); + } + const num = len & 0x7f; + len = 0; + for (let i = 0; i < num; i++) { + len <<= 8; + const j = buf.readUInt8(2 + i); + len |= j; + } + if (index === 0) { + return len; + } + return getLength(buf.subarray(2 + len), index - 1); +}; +const getLengthOfSeqIndex = (sequence, index) => { + const len = sequence.readUInt8(1); + if ((len & 0x80) === 0) { + return getLength(sequence.subarray(2), index); + } + const num = len & 0x7f; + return getLength(sequence.subarray(2 + num), index); +}; +const getModulusLength = (key) => { + var _a, _b; + if (weakMap.has(key)) { + return weakMap.get(key); + } + const modulusLength = (_b = (_a = key.asymmetricKeyDetails) === null || _a === void 0 ? void 0 : _a.modulusLength) !== null && _b !== void 0 ? _b : (getLengthOfSeqIndex(key.export({ format: 'der', type: 'pkcs1' }), key.type === 'private' ? 1 : 0) - + 1) << + 3; + weakMap.set(key, modulusLength); + return modulusLength; +}; +export const setModulusLength = (keyObject, modulusLength) => { + weakMap.set(keyObject, modulusLength); +}; +export default (key, alg) => { + if (getModulusLength(key) < 2048) { + throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); + } +}; diff --git a/node_modules/jose/dist/node/esm/runtime/ciphers.js b/node_modules/jose/dist/node/esm/runtime/ciphers.js new file mode 100644 index 0000000..daded1d --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/ciphers.js @@ -0,0 +1,6 @@ +import { getCiphers } from 'crypto'; +let ciphers; +export default (algorithm) => { + ciphers || (ciphers = new Set(getCiphers())); + return ciphers.has(algorithm); +}; diff --git a/node_modules/jose/dist/node/esm/runtime/decrypt.js b/node_modules/jose/dist/node/esm/runtime/decrypt.js new file mode 100644 index 0000000..8a611d1 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/decrypt.js @@ -0,0 +1,95 @@ +import { createDecipheriv, KeyObject } from 'crypto'; +import checkIvLength from '../lib/check_iv_length.js'; +import checkCekLength from './check_cek_length.js'; +import { concat } from '../lib/buffer_utils.js'; +import { JOSENotSupported, JWEDecryptionFailed } from '../util/errors.js'; +import timingSafeEqual from './timing_safe_equal.js'; +import cbcTag from './cbc_tag.js'; +import { isCryptoKey } from './webcrypto.js'; +import { checkEncCryptoKey } from '../lib/crypto_key.js'; +import isKeyObject from './is_key_object.js'; +import invalidKeyInput from '../lib/invalid_key_input.js'; +import supported from './ciphers.js'; +import { types } from './is_key_like.js'; +function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) { + const keySize = parseInt(enc.slice(1, 4), 10); + if (isKeyObject(cek)) { + cek = cek.export(); + } + const encKey = cek.subarray(keySize >> 3); + const macKey = cek.subarray(0, keySize >> 3); + const macSize = parseInt(enc.slice(-3), 10); + const algorithm = `aes-${keySize}-cbc`; + if (!supported(algorithm)) { + throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); + } + const expectedTag = cbcTag(aad, iv, ciphertext, macSize, macKey, keySize); + let macCheckPassed; + try { + macCheckPassed = timingSafeEqual(tag, expectedTag); + } + catch { + } + if (!macCheckPassed) { + throw new JWEDecryptionFailed(); + } + let plaintext; + try { + const decipher = createDecipheriv(algorithm, encKey, iv); + plaintext = concat(decipher.update(ciphertext), decipher.final()); + } + catch { + } + if (!plaintext) { + throw new JWEDecryptionFailed(); + } + return plaintext; +} +function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) { + const keySize = parseInt(enc.slice(1, 4), 10); + const algorithm = `aes-${keySize}-gcm`; + if (!supported(algorithm)) { + throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); + } + try { + const decipher = createDecipheriv(algorithm, cek, iv, { authTagLength: 16 }); + decipher.setAuthTag(tag); + if (aad.byteLength) { + decipher.setAAD(aad, { plaintextLength: ciphertext.length }); + } + const plaintext = decipher.update(ciphertext); + decipher.final(); + return plaintext; + } + catch { + throw new JWEDecryptionFailed(); + } +} +const decrypt = (enc, cek, ciphertext, iv, tag, aad) => { + let key; + if (isCryptoKey(cek)) { + checkEncCryptoKey(cek, enc, 'decrypt'); + key = KeyObject.from(cek); + } + else if (cek instanceof Uint8Array || isKeyObject(cek)) { + key = cek; + } + else { + throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array')); + } + checkCekLength(enc, key); + checkIvLength(enc, iv); + switch (enc) { + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + return cbcDecrypt(enc, key, ciphertext, iv, tag, aad); + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': + return gcmDecrypt(enc, key, ciphertext, iv, tag, aad); + default: + throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); + } +}; +export default decrypt; diff --git a/node_modules/jose/dist/node/esm/runtime/digest.js b/node_modules/jose/dist/node/esm/runtime/digest.js new file mode 100644 index 0000000..0facde6 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/digest.js @@ -0,0 +1,3 @@ +import { createHash } from 'crypto'; +const digest = (algorithm, data) => createHash(algorithm).update(data).digest(); +export default digest; diff --git a/node_modules/jose/dist/node/esm/runtime/dsa_digest.js b/node_modules/jose/dist/node/esm/runtime/dsa_digest.js new file mode 100644 index 0000000..ce7215b --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/dsa_digest.js @@ -0,0 +1,22 @@ +import { JOSENotSupported } from '../util/errors.js'; +export default function dsaDigest(alg) { + switch (alg) { + case 'PS256': + case 'RS256': + case 'ES256': + case 'ES256K': + return 'sha256'; + case 'PS384': + case 'RS384': + case 'ES384': + return 'sha384'; + case 'PS512': + case 'RS512': + case 'ES512': + return 'sha512'; + case 'EdDSA': + return undefined; + default: + throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } +} diff --git a/node_modules/jose/dist/node/esm/runtime/ecdhes.js b/node_modules/jose/dist/node/esm/runtime/ecdhes.js new file mode 100644 index 0000000..d3faef4 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/ecdhes.js @@ -0,0 +1,64 @@ +import { diffieHellman, generateKeyPair as generateKeyPairCb, KeyObject } from 'crypto'; +import { promisify } from 'util'; +import getNamedCurve from './get_named_curve.js'; +import { encoder, concat, uint32be, lengthAndInput, concatKdf } from '../lib/buffer_utils.js'; +import { JOSENotSupported } from '../util/errors.js'; +import { isCryptoKey } from './webcrypto.js'; +import { checkEncCryptoKey } from '../lib/crypto_key.js'; +import isKeyObject from './is_key_object.js'; +import invalidKeyInput from '../lib/invalid_key_input.js'; +import { types } from './is_key_like.js'; +const generateKeyPair = promisify(generateKeyPairCb); +export async function deriveKey(publicKee, privateKee, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) { + let publicKey; + if (isCryptoKey(publicKee)) { + checkEncCryptoKey(publicKee, 'ECDH'); + publicKey = KeyObject.from(publicKee); + } + else if (isKeyObject(publicKee)) { + publicKey = publicKee; + } + else { + throw new TypeError(invalidKeyInput(publicKee, ...types)); + } + let privateKey; + if (isCryptoKey(privateKee)) { + checkEncCryptoKey(privateKee, 'ECDH', 'deriveBits'); + privateKey = KeyObject.from(privateKee); + } + else if (isKeyObject(privateKee)) { + privateKey = privateKee; + } + else { + throw new TypeError(invalidKeyInput(privateKee, ...types)); + } + const value = concat(lengthAndInput(encoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength)); + const sharedSecret = diffieHellman({ privateKey, publicKey }); + return concatKdf(sharedSecret, keyLength, value); +} +export async function generateEpk(kee) { + let key; + if (isCryptoKey(kee)) { + key = KeyObject.from(kee); + } + else if (isKeyObject(kee)) { + key = kee; + } + else { + throw new TypeError(invalidKeyInput(kee, ...types)); + } + switch (key.asymmetricKeyType) { + case 'x25519': + return generateKeyPair('x25519'); + case 'x448': { + return generateKeyPair('x448'); + } + case 'ec': { + const namedCurve = getNamedCurve(key); + return generateKeyPair('ec', { namedCurve }); + } + default: + throw new JOSENotSupported('Invalid or unsupported EPK'); + } +} +export const ecdhAllowed = (key) => ['P-256', 'P-384', 'P-521', 'X25519', 'X448'].includes(getNamedCurve(key)); diff --git a/node_modules/jose/dist/node/esm/runtime/encrypt.js b/node_modules/jose/dist/node/esm/runtime/encrypt.js new file mode 100644 index 0000000..8dfb87b --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/encrypt.js @@ -0,0 +1,72 @@ +import { createCipheriv, KeyObject } from 'crypto'; +import checkIvLength from '../lib/check_iv_length.js'; +import checkCekLength from './check_cek_length.js'; +import { concat } from '../lib/buffer_utils.js'; +import cbcTag from './cbc_tag.js'; +import { isCryptoKey } from './webcrypto.js'; +import { checkEncCryptoKey } from '../lib/crypto_key.js'; +import isKeyObject from './is_key_object.js'; +import invalidKeyInput from '../lib/invalid_key_input.js'; +import { JOSENotSupported } from '../util/errors.js'; +import supported from './ciphers.js'; +import { types } from './is_key_like.js'; +function cbcEncrypt(enc, plaintext, cek, iv, aad) { + const keySize = parseInt(enc.slice(1, 4), 10); + if (isKeyObject(cek)) { + cek = cek.export(); + } + const encKey = cek.subarray(keySize >> 3); + const macKey = cek.subarray(0, keySize >> 3); + const algorithm = `aes-${keySize}-cbc`; + if (!supported(algorithm)) { + throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); + } + const cipher = createCipheriv(algorithm, encKey, iv); + const ciphertext = concat(cipher.update(plaintext), cipher.final()); + const macSize = parseInt(enc.slice(-3), 10); + const tag = cbcTag(aad, iv, ciphertext, macSize, macKey, keySize); + return { ciphertext, tag }; +} +function gcmEncrypt(enc, plaintext, cek, iv, aad) { + const keySize = parseInt(enc.slice(1, 4), 10); + const algorithm = `aes-${keySize}-gcm`; + if (!supported(algorithm)) { + throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); + } + const cipher = createCipheriv(algorithm, cek, iv, { authTagLength: 16 }); + if (aad.byteLength) { + cipher.setAAD(aad, { plaintextLength: plaintext.length }); + } + const ciphertext = cipher.update(plaintext); + cipher.final(); + const tag = cipher.getAuthTag(); + return { ciphertext, tag }; +} +const encrypt = (enc, plaintext, cek, iv, aad) => { + let key; + if (isCryptoKey(cek)) { + checkEncCryptoKey(cek, enc, 'encrypt'); + key = KeyObject.from(cek); + } + else if (cek instanceof Uint8Array || isKeyObject(cek)) { + key = cek; + } + else { + throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array')); + } + checkCekLength(enc, key); + checkIvLength(enc, iv); + switch (enc) { + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + return cbcEncrypt(enc, plaintext, key, iv, aad); + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': + return gcmEncrypt(enc, plaintext, key, iv, aad); + default: + throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); + } +}; +export default encrypt; diff --git a/node_modules/jose/dist/node/esm/runtime/fetch_jwks.js b/node_modules/jose/dist/node/esm/runtime/fetch_jwks.js new file mode 100644 index 0000000..5853424 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/fetch_jwks.js @@ -0,0 +1,43 @@ +import * as http from 'http'; +import * as https from 'https'; +import { once } from 'events'; +import { JOSEError, JWKSTimeout } from '../util/errors.js'; +import { concat, decoder } from '../lib/buffer_utils.js'; +const fetchJwks = async (url, timeout, options) => { + let get; + switch (url.protocol) { + case 'https:': + get = https.get; + break; + case 'http:': + get = http.get; + break; + default: + throw new TypeError('Unsupported URL protocol.'); + } + const { agent, headers } = options; + const req = get(url.href, { + agent, + timeout, + headers, + }); + const [response] = (await Promise.race([once(req, 'response'), once(req, 'timeout')])); + if (!response) { + req.destroy(); + throw new JWKSTimeout(); + } + if (response.statusCode !== 200) { + throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response'); + } + const parts = []; + for await (const part of response) { + parts.push(part); + } + try { + return JSON.parse(decoder.decode(concat(...parts))); + } + catch { + throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON'); + } +}; +export default fetchJwks; diff --git a/node_modules/jose/dist/node/esm/runtime/flags.js b/node_modules/jose/dist/node/esm/runtime/flags.js new file mode 100644 index 0000000..3902995 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/flags.js @@ -0,0 +1,5 @@ +const [major, minor] = process.versions.node.split('.').map((str) => parseInt(str, 10)); +export const oneShotCallback = major >= 16 || (major === 15 && minor >= 13); +export const rsaPssParams = !('electron' in process.versions) && (major >= 17 || (major === 16 && minor >= 9)); +export const jwkExport = major >= 16 || (major === 15 && minor >= 9); +export const jwkImport = major >= 16 || (major === 15 && minor >= 12); diff --git a/node_modules/jose/dist/node/esm/runtime/generate.js b/node_modules/jose/dist/node/esm/runtime/generate.js new file mode 100644 index 0000000..64f7696 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/generate.js @@ -0,0 +1,100 @@ +import { createSecretKey, generateKeyPair as generateKeyPairCb } from 'crypto'; +import { promisify } from 'util'; +import random from './random.js'; +import { setModulusLength } from './check_modulus_length.js'; +import { JOSENotSupported } from '../util/errors.js'; +const generate = promisify(generateKeyPairCb); +export async function generateSecret(alg, options) { + let length; + switch (alg) { + case 'HS256': + case 'HS384': + case 'HS512': + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + length = parseInt(alg.slice(-3), 10); + break; + case 'A128KW': + case 'A192KW': + case 'A256KW': + case 'A128GCMKW': + case 'A192GCMKW': + case 'A256GCMKW': + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': + length = parseInt(alg.slice(1, 4), 10); + break; + default: + throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + } + return createSecretKey(random(new Uint8Array(length >> 3))); +} +export async function generateKeyPair(alg, options) { + var _a, _b; + switch (alg) { + case 'RS256': + case 'RS384': + case 'RS512': + case 'PS256': + case 'PS384': + case 'PS512': + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': + case 'RSA1_5': { + const modulusLength = (_a = options === null || options === void 0 ? void 0 : options.modulusLength) !== null && _a !== void 0 ? _a : 2048; + if (typeof modulusLength !== 'number' || modulusLength < 2048) { + throw new JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used'); + } + const keypair = await generate('rsa', { + modulusLength, + publicExponent: 0x10001, + }); + setModulusLength(keypair.privateKey, modulusLength); + setModulusLength(keypair.publicKey, modulusLength); + return keypair; + } + case 'ES256': + return generate('ec', { namedCurve: 'P-256' }); + case 'ES256K': + return generate('ec', { namedCurve: 'secp256k1' }); + case 'ES384': + return generate('ec', { namedCurve: 'P-384' }); + case 'ES512': + return generate('ec', { namedCurve: 'P-521' }); + case 'EdDSA': { + switch (options === null || options === void 0 ? void 0 : options.crv) { + case undefined: + case 'Ed25519': + return generate('ed25519'); + case 'Ed448': + return generate('ed448'); + default: + throw new JOSENotSupported('Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448'); + } + } + case 'ECDH-ES': + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': + const crv = (_b = options === null || options === void 0 ? void 0 : options.crv) !== null && _b !== void 0 ? _b : 'P-256'; + switch (crv) { + case undefined: + case 'P-256': + case 'P-384': + case 'P-521': + return generate('ec', { namedCurve: crv }); + case 'X25519': + return generate('x25519'); + case 'X448': + return generate('x448'); + default: + throw new JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448'); + } + default: + throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + } +} diff --git a/node_modules/jose/dist/node/esm/runtime/get_named_curve.js b/node_modules/jose/dist/node/esm/runtime/get_named_curve.js new file mode 100644 index 0000000..e453a66 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/get_named_curve.js @@ -0,0 +1,91 @@ +import { Buffer } from 'buffer'; +import { createPublicKey, KeyObject } from 'crypto'; +import { JOSENotSupported } from '../util/errors.js'; +import { isCryptoKey } from './webcrypto.js'; +import isKeyObject from './is_key_object.js'; +import invalidKeyInput from '../lib/invalid_key_input.js'; +import { types } from './is_key_like.js'; +const p256 = Buffer.from([42, 134, 72, 206, 61, 3, 1, 7]); +const p384 = Buffer.from([43, 129, 4, 0, 34]); +const p521 = Buffer.from([43, 129, 4, 0, 35]); +const secp256k1 = Buffer.from([43, 129, 4, 0, 10]); +export const weakMap = new WeakMap(); +const namedCurveToJOSE = (namedCurve) => { + switch (namedCurve) { + case 'prime256v1': + return 'P-256'; + case 'secp384r1': + return 'P-384'; + case 'secp521r1': + return 'P-521'; + case 'secp256k1': + return 'secp256k1'; + default: + throw new JOSENotSupported('Unsupported key curve for this operation'); + } +}; +const getNamedCurve = (kee, raw) => { + var _a; + let key; + if (isCryptoKey(kee)) { + key = KeyObject.from(kee); + } + else if (isKeyObject(kee)) { + key = kee; + } + else { + throw new TypeError(invalidKeyInput(kee, ...types)); + } + if (key.type === 'secret') { + throw new TypeError('only "private" or "public" type keys can be used for this operation'); + } + switch (key.asymmetricKeyType) { + case 'ed25519': + case 'ed448': + return `Ed${key.asymmetricKeyType.slice(2)}`; + case 'x25519': + case 'x448': + return `X${key.asymmetricKeyType.slice(1)}`; + case 'ec': { + if (weakMap.has(key)) { + return weakMap.get(key); + } + let namedCurve = (_a = key.asymmetricKeyDetails) === null || _a === void 0 ? void 0 : _a.namedCurve; + if (!namedCurve && key.type === 'private') { + namedCurve = getNamedCurve(createPublicKey(key), true); + } + else if (!namedCurve) { + const buf = key.export({ format: 'der', type: 'spki' }); + const i = buf[1] < 128 ? 14 : 15; + const len = buf[i]; + const curveOid = buf.slice(i + 1, i + 1 + len); + if (curveOid.equals(p256)) { + namedCurve = 'prime256v1'; + } + else if (curveOid.equals(p384)) { + namedCurve = 'secp384r1'; + } + else if (curveOid.equals(p521)) { + namedCurve = 'secp521r1'; + } + else if (curveOid.equals(secp256k1)) { + namedCurve = 'secp256k1'; + } + else { + throw new JOSENotSupported('Unsupported key curve for this operation'); + } + } + if (raw) + return namedCurve; + const curve = namedCurveToJOSE(namedCurve); + weakMap.set(key, curve); + return curve; + } + default: + throw new TypeError('Invalid asymmetric key type for this operation'); + } +}; +export function setCurve(keyObject, curve) { + weakMap.set(keyObject, curve); +} +export default getNamedCurve; diff --git a/node_modules/jose/dist/node/esm/runtime/get_sign_verify_key.js b/node_modules/jose/dist/node/esm/runtime/get_sign_verify_key.js new file mode 100644 index 0000000..46aa2b4 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/get_sign_verify_key.js @@ -0,0 +1,21 @@ +import { KeyObject, createSecretKey } from 'crypto'; +import { isCryptoKey } from './webcrypto.js'; +import { checkSigCryptoKey } from '../lib/crypto_key.js'; +import invalidKeyInput from '../lib/invalid_key_input.js'; +import { types } from './is_key_like.js'; +export default function getSignVerifyKey(alg, key, usage) { + if (key instanceof Uint8Array) { + if (!alg.startsWith('HS')) { + throw new TypeError(invalidKeyInput(key, ...types)); + } + return createSecretKey(key); + } + if (key instanceof KeyObject) { + return key; + } + if (isCryptoKey(key)) { + checkSigCryptoKey(key, alg, usage); + return KeyObject.from(key); + } + throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); +} diff --git a/node_modules/jose/dist/node/esm/runtime/hmac_digest.js b/node_modules/jose/dist/node/esm/runtime/hmac_digest.js new file mode 100644 index 0000000..29d55c3 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/hmac_digest.js @@ -0,0 +1,13 @@ +import { JOSENotSupported } from '../util/errors.js'; +export default function hmacDigest(alg) { + switch (alg) { + case 'HS256': + return 'sha256'; + case 'HS384': + return 'sha384'; + case 'HS512': + return 'sha512'; + default: + throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } +} diff --git a/node_modules/jose/dist/node/esm/runtime/is_key_like.js b/node_modules/jose/dist/node/esm/runtime/is_key_like.js new file mode 100644 index 0000000..af0d0a0 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/is_key_like.js @@ -0,0 +1,8 @@ +import webcrypto, { isCryptoKey } from './webcrypto.js'; +import isKeyObject from './is_key_object.js'; +export default (key) => isKeyObject(key) || isCryptoKey(key); +const types = ['KeyObject']; +if (globalThis.CryptoKey || (webcrypto === null || webcrypto === void 0 ? void 0 : webcrypto.CryptoKey)) { + types.push('CryptoKey'); +} +export { types }; diff --git a/node_modules/jose/dist/node/esm/runtime/is_key_object.js b/node_modules/jose/dist/node/esm/runtime/is_key_object.js new file mode 100644 index 0000000..3a28cd8 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/is_key_object.js @@ -0,0 +1,5 @@ +import { KeyObject } from 'crypto'; +import * as util from 'util'; +export default util.types.isKeyObject + ? (obj) => util.types.isKeyObject(obj) + : (obj) => obj != null && obj instanceof KeyObject; diff --git a/node_modules/jose/dist/node/esm/runtime/jwk_to_key.js b/node_modules/jose/dist/node/esm/runtime/jwk_to_key.js new file mode 100644 index 0000000..8cb31d6 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/jwk_to_key.js @@ -0,0 +1,116 @@ +import { Buffer } from 'buffer'; +import { createPrivateKey, createPublicKey, createSecretKey } from 'crypto'; +import { decode as base64url } from './base64url.js'; +import { JOSENotSupported } from '../util/errors.js'; +import { setCurve } from './get_named_curve.js'; +import { setModulusLength } from './check_modulus_length.js'; +import Asn1SequenceEncoder from './asn1_sequence_encoder.js'; +import { jwkImport } from './flags.js'; +const parse = (jwk) => { + if (jwkImport && jwk.kty !== 'oct') { + return jwk.d + ? createPrivateKey({ format: 'jwk', key: jwk }) + : createPublicKey({ format: 'jwk', key: jwk }); + } + switch (jwk.kty) { + case 'oct': { + return createSecretKey(base64url(jwk.k)); + } + case 'RSA': { + const enc = new Asn1SequenceEncoder(); + const isPrivate = jwk.d !== undefined; + const modulus = Buffer.from(jwk.n, 'base64'); + const exponent = Buffer.from(jwk.e, 'base64'); + if (isPrivate) { + enc.zero(); + enc.unsignedInteger(modulus); + enc.unsignedInteger(exponent); + enc.unsignedInteger(Buffer.from(jwk.d, 'base64')); + enc.unsignedInteger(Buffer.from(jwk.p, 'base64')); + enc.unsignedInteger(Buffer.from(jwk.q, 'base64')); + enc.unsignedInteger(Buffer.from(jwk.dp, 'base64')); + enc.unsignedInteger(Buffer.from(jwk.dq, 'base64')); + enc.unsignedInteger(Buffer.from(jwk.qi, 'base64')); + } + else { + enc.unsignedInteger(modulus); + enc.unsignedInteger(exponent); + } + const der = enc.end(); + const createInput = { + key: der, + format: 'der', + type: 'pkcs1', + }; + const keyObject = isPrivate ? createPrivateKey(createInput) : createPublicKey(createInput); + setModulusLength(keyObject, modulus.length << 3); + return keyObject; + } + case 'EC': { + const enc = new Asn1SequenceEncoder(); + const isPrivate = jwk.d !== undefined; + const pub = Buffer.concat([ + Buffer.alloc(1, 4), + Buffer.from(jwk.x, 'base64'), + Buffer.from(jwk.y, 'base64'), + ]); + if (isPrivate) { + enc.zero(); + const enc$1 = new Asn1SequenceEncoder(); + enc$1.oidFor('ecPublicKey'); + enc$1.oidFor(jwk.crv); + enc.add(enc$1.end()); + const enc$2 = new Asn1SequenceEncoder(); + enc$2.one(); + enc$2.octStr(Buffer.from(jwk.d, 'base64')); + const enc$3 = new Asn1SequenceEncoder(); + enc$3.bitStr(pub); + const f2 = enc$3.end(Buffer.from([0xa1])); + enc$2.add(f2); + const f = enc$2.end(); + const enc$4 = new Asn1SequenceEncoder(); + enc$4.add(f); + const f3 = enc$4.end(Buffer.from([0x04])); + enc.add(f3); + const der = enc.end(); + const keyObject = createPrivateKey({ key: der, format: 'der', type: 'pkcs8' }); + setCurve(keyObject, jwk.crv); + return keyObject; + } + const enc$1 = new Asn1SequenceEncoder(); + enc$1.oidFor('ecPublicKey'); + enc$1.oidFor(jwk.crv); + enc.add(enc$1.end()); + enc.bitStr(pub); + const der = enc.end(); + const keyObject = createPublicKey({ key: der, format: 'der', type: 'spki' }); + setCurve(keyObject, jwk.crv); + return keyObject; + } + case 'OKP': { + const enc = new Asn1SequenceEncoder(); + const isPrivate = jwk.d !== undefined; + if (isPrivate) { + enc.zero(); + const enc$1 = new Asn1SequenceEncoder(); + enc$1.oidFor(jwk.crv); + enc.add(enc$1.end()); + const enc$2 = new Asn1SequenceEncoder(); + enc$2.octStr(Buffer.from(jwk.d, 'base64')); + const f = enc$2.end(Buffer.from([0x04])); + enc.add(f); + const der = enc.end(); + return createPrivateKey({ key: der, format: 'der', type: 'pkcs8' }); + } + const enc$1 = new Asn1SequenceEncoder(); + enc$1.oidFor(jwk.crv); + enc.add(enc$1.end()); + enc.bitStr(Buffer.from(jwk.x, 'base64')); + const der = enc.end(); + return createPublicKey({ key: der, format: 'der', type: 'spki' }); + } + default: + throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value'); + } +}; +export default parse; diff --git a/node_modules/jose/dist/node/esm/runtime/key_to_jwk.js b/node_modules/jose/dist/node/esm/runtime/key_to_jwk.js new file mode 100644 index 0000000..755564c --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/key_to_jwk.js @@ -0,0 +1,158 @@ +import { KeyObject, createPublicKey } from 'crypto'; +import { encode as base64url } from './base64url.js'; +import Asn1SequenceDecoder from './asn1_sequence_decoder.js'; +import { JOSENotSupported } from '../util/errors.js'; +import getNamedCurve from './get_named_curve.js'; +import { isCryptoKey } from './webcrypto.js'; +import isKeyObject from './is_key_object.js'; +import invalidKeyInput from '../lib/invalid_key_input.js'; +import { types } from './is_key_like.js'; +import { jwkExport } from './flags.js'; +const keyToJWK = (key) => { + let keyObject; + if (isCryptoKey(key)) { + if (!key.extractable) { + throw new TypeError('CryptoKey is not extractable'); + } + keyObject = KeyObject.from(key); + } + else if (isKeyObject(key)) { + keyObject = key; + } + else if (key instanceof Uint8Array) { + return { + kty: 'oct', + k: base64url(key), + }; + } + else { + throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); + } + if (jwkExport) { + if (keyObject.type !== 'secret' && + !['rsa', 'ec', 'ed25519', 'x25519', 'ed448', 'x448'].includes(keyObject.asymmetricKeyType)) { + throw new JOSENotSupported('Unsupported key asymmetricKeyType'); + } + return keyObject.export({ format: 'jwk' }); + } + switch (keyObject.type) { + case 'secret': + return { + kty: 'oct', + k: base64url(keyObject.export()), + }; + case 'private': + case 'public': { + switch (keyObject.asymmetricKeyType) { + case 'rsa': { + const der = keyObject.export({ format: 'der', type: 'pkcs1' }); + const dec = new Asn1SequenceDecoder(der); + if (keyObject.type === 'private') { + dec.unsignedInteger(); + } + const n = base64url(dec.unsignedInteger()); + const e = base64url(dec.unsignedInteger()); + let jwk; + if (keyObject.type === 'private') { + jwk = { + d: base64url(dec.unsignedInteger()), + p: base64url(dec.unsignedInteger()), + q: base64url(dec.unsignedInteger()), + dp: base64url(dec.unsignedInteger()), + dq: base64url(dec.unsignedInteger()), + qi: base64url(dec.unsignedInteger()), + }; + } + dec.end(); + return { kty: 'RSA', n, e, ...jwk }; + } + case 'ec': { + const crv = getNamedCurve(keyObject); + let len; + let offset; + let correction; + switch (crv) { + case 'secp256k1': + len = 64; + offset = 31 + 2; + correction = -1; + break; + case 'P-256': + len = 64; + offset = 34 + 2; + correction = -1; + break; + case 'P-384': + len = 96; + offset = 33 + 2; + correction = -3; + break; + case 'P-521': + len = 132; + offset = 33 + 2; + correction = -3; + break; + default: + throw new JOSENotSupported('Unsupported curve'); + } + if (keyObject.type === 'public') { + const der = keyObject.export({ type: 'spki', format: 'der' }); + return { + kty: 'EC', + crv, + x: base64url(der.subarray(-len, -len / 2)), + y: base64url(der.subarray(-len / 2)), + }; + } + const der = keyObject.export({ type: 'pkcs8', format: 'der' }); + if (der.length < 100) { + offset += correction; + } + return { + ...keyToJWK(createPublicKey(keyObject)), + d: base64url(der.subarray(offset, offset + len / 2)), + }; + } + case 'ed25519': + case 'x25519': { + const crv = getNamedCurve(keyObject); + if (keyObject.type === 'public') { + const der = keyObject.export({ type: 'spki', format: 'der' }); + return { + kty: 'OKP', + crv, + x: base64url(der.subarray(-32)), + }; + } + const der = keyObject.export({ type: 'pkcs8', format: 'der' }); + return { + ...keyToJWK(createPublicKey(keyObject)), + d: base64url(der.subarray(-32)), + }; + } + case 'ed448': + case 'x448': { + const crv = getNamedCurve(keyObject); + if (keyObject.type === 'public') { + const der = keyObject.export({ type: 'spki', format: 'der' }); + return { + kty: 'OKP', + crv, + x: base64url(der.subarray(crv === 'Ed448' ? -57 : -56)), + }; + } + const der = keyObject.export({ type: 'pkcs8', format: 'der' }); + return { + ...keyToJWK(createPublicKey(keyObject)), + d: base64url(der.subarray(crv === 'Ed448' ? -57 : -56)), + }; + } + default: + throw new JOSENotSupported('Unsupported key asymmetricKeyType'); + } + } + default: + throw new JOSENotSupported('Unsupported key type'); + } +}; +export default keyToJWK; diff --git a/node_modules/jose/dist/node/esm/runtime/node_key.js b/node_modules/jose/dist/node/esm/runtime/node_key.js new file mode 100644 index 0000000..3535dd8 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/node_key.js @@ -0,0 +1,75 @@ +import { constants } from 'crypto'; +import getNamedCurve from './get_named_curve.js'; +import { JOSENotSupported } from '../util/errors.js'; +import checkModulusLength from './check_modulus_length.js'; +import { rsaPssParams } from './flags.js'; +const PSS = { + padding: constants.RSA_PKCS1_PSS_PADDING, + saltLength: constants.RSA_PSS_SALTLEN_DIGEST, +}; +const ecCurveAlgMap = new Map([ + ['ES256', 'P-256'], + ['ES256K', 'secp256k1'], + ['ES384', 'P-384'], + ['ES512', 'P-521'], +]); +export default function keyForCrypto(alg, key) { + switch (alg) { + case 'EdDSA': + if (!['ed25519', 'ed448'].includes(key.asymmetricKeyType)) { + throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448'); + } + return key; + case 'RS256': + case 'RS384': + case 'RS512': + if (key.asymmetricKeyType !== 'rsa') { + throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa'); + } + checkModulusLength(key, alg); + return key; + case rsaPssParams && 'PS256': + case rsaPssParams && 'PS384': + case rsaPssParams && 'PS512': + if (key.asymmetricKeyType === 'rsa-pss') { + const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = key.asymmetricKeyDetails; + const length = parseInt(alg.slice(-3), 10); + if (hashAlgorithm !== undefined && + (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm)) { + throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${alg}`); + } + if (saltLength !== undefined && saltLength > length >> 3) { + throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${alg}`); + } + } + else if (key.asymmetricKeyType !== 'rsa') { + throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss'); + } + checkModulusLength(key, alg); + return { key, ...PSS }; + case !rsaPssParams && 'PS256': + case !rsaPssParams && 'PS384': + case !rsaPssParams && 'PS512': + if (key.asymmetricKeyType !== 'rsa') { + throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa'); + } + checkModulusLength(key, alg); + return { key, ...PSS }; + case 'ES256': + case 'ES256K': + case 'ES384': + case 'ES512': { + if (key.asymmetricKeyType !== 'ec') { + throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ec'); + } + const actual = getNamedCurve(key); + const expected = ecCurveAlgMap.get(alg); + if (actual !== expected) { + throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${expected}, got ${actual}`); + } + return { dsaEncoding: 'ieee-p1363', key }; + } + default: + throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } +} diff --git a/node_modules/jose/dist/node/esm/runtime/pbes2kw.js b/node_modules/jose/dist/node/esm/runtime/pbes2kw.js new file mode 100644 index 0000000..63122e0 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/pbes2kw.js @@ -0,0 +1,43 @@ +import { promisify } from 'util'; +import { KeyObject, pbkdf2 as pbkdf2cb } from 'crypto'; +import random from './random.js'; +import { p2s as concatSalt } from '../lib/buffer_utils.js'; +import { encode as base64url } from './base64url.js'; +import { wrap, unwrap } from './aeskw.js'; +import checkP2s from '../lib/check_p2s.js'; +import { isCryptoKey } from './webcrypto.js'; +import { checkEncCryptoKey } from '../lib/crypto_key.js'; +import isKeyObject from './is_key_object.js'; +import invalidKeyInput from '../lib/invalid_key_input.js'; +import { types } from './is_key_like.js'; +const pbkdf2 = promisify(pbkdf2cb); +function getPassword(key, alg) { + if (isKeyObject(key)) { + return key.export(); + } + if (key instanceof Uint8Array) { + return key; + } + if (isCryptoKey(key)) { + checkEncCryptoKey(key, alg, 'deriveBits', 'deriveKey'); + return KeyObject.from(key).export(); + } + throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); +} +export const encrypt = async (alg, key, cek, p2c = 2048, p2s = random(new Uint8Array(16))) => { + checkP2s(p2s); + const salt = concatSalt(alg, p2s); + const keylen = parseInt(alg.slice(13, 16), 10) >> 3; + const password = getPassword(key, alg); + const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`); + const encryptedKey = await wrap(alg.slice(-6), derivedKey, cek); + return { encryptedKey, p2c, p2s: base64url(p2s) }; +}; +export const decrypt = async (alg, key, encryptedKey, p2c, p2s) => { + checkP2s(p2s); + const salt = concatSalt(alg, p2s); + const keylen = parseInt(alg.slice(13, 16), 10) >> 3; + const password = getPassword(key, alg); + const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`); + return unwrap(alg.slice(-6), derivedKey, encryptedKey); +}; diff --git a/node_modules/jose/dist/node/esm/runtime/random.js b/node_modules/jose/dist/node/esm/runtime/random.js new file mode 100644 index 0000000..80478ea --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/random.js @@ -0,0 +1 @@ +export { randomFillSync as default } from 'crypto'; diff --git a/node_modules/jose/dist/node/esm/runtime/rsaes.js b/node_modules/jose/dist/node/esm/runtime/rsaes.js new file mode 100644 index 0000000..3556fe3 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/rsaes.js @@ -0,0 +1,64 @@ +import { KeyObject, publicEncrypt, constants, privateDecrypt } from 'crypto'; +import checkModulusLength from './check_modulus_length.js'; +import { isCryptoKey } from './webcrypto.js'; +import { checkEncCryptoKey } from '../lib/crypto_key.js'; +import isKeyObject from './is_key_object.js'; +import invalidKeyInput from '../lib/invalid_key_input.js'; +import { types } from './is_key_like.js'; +const checkKey = (key, alg) => { + if (key.asymmetricKeyType !== 'rsa') { + throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa'); + } + checkModulusLength(key, alg); +}; +const resolvePadding = (alg) => { + switch (alg) { + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': + return constants.RSA_PKCS1_OAEP_PADDING; + case 'RSA1_5': + return constants.RSA_PKCS1_PADDING; + default: + return undefined; + } +}; +const resolveOaepHash = (alg) => { + switch (alg) { + case 'RSA-OAEP': + return 'sha1'; + case 'RSA-OAEP-256': + return 'sha256'; + case 'RSA-OAEP-384': + return 'sha384'; + case 'RSA-OAEP-512': + return 'sha512'; + default: + return undefined; + } +}; +function ensureKeyObject(key, alg, ...usages) { + if (isKeyObject(key)) { + return key; + } + if (isCryptoKey(key)) { + checkEncCryptoKey(key, alg, ...usages); + return KeyObject.from(key); + } + throw new TypeError(invalidKeyInput(key, ...types)); +} +export const encrypt = (alg, key, cek) => { + const padding = resolvePadding(alg); + const oaepHash = resolveOaepHash(alg); + const keyObject = ensureKeyObject(key, alg, 'wrapKey', 'encrypt'); + checkKey(keyObject, alg); + return publicEncrypt({ key: keyObject, oaepHash, padding }, cek); +}; +export const decrypt = (alg, key, encryptedKey) => { + const padding = resolvePadding(alg); + const oaepHash = resolveOaepHash(alg); + const keyObject = ensureKeyObject(key, alg, 'unwrapKey', 'decrypt'); + checkKey(keyObject, alg); + return privateDecrypt({ key: keyObject, oaepHash, padding }, encryptedKey); +}; diff --git a/node_modules/jose/dist/node/esm/runtime/runtime.js b/node_modules/jose/dist/node/esm/runtime/runtime.js new file mode 100644 index 0000000..7bf56f6 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/runtime.js @@ -0,0 +1 @@ +export default 'node:crypto'; diff --git a/node_modules/jose/dist/node/esm/runtime/sign.js b/node_modules/jose/dist/node/esm/runtime/sign.js new file mode 100644 index 0000000..8902d41 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/sign.js @@ -0,0 +1,23 @@ +import * as crypto from 'crypto'; +import { promisify } from 'util'; +import nodeDigest from './dsa_digest.js'; +import hmacDigest from './hmac_digest.js'; +import nodeKey from './node_key.js'; +import getSignKey from './get_sign_verify_key.js'; +let oneShotSign; +if (crypto.sign.length > 3) { + oneShotSign = promisify(crypto.sign); +} +else { + oneShotSign = crypto.sign; +} +const sign = async (alg, key, data) => { + const keyObject = getSignKey(alg, key, 'sign'); + if (alg.startsWith('HS')) { + const hmac = crypto.createHmac(hmacDigest(alg), keyObject); + hmac.update(data); + return hmac.digest(); + } + return oneShotSign(nodeDigest(alg), data, nodeKey(alg, keyObject)); +}; +export default sign; diff --git a/node_modules/jose/dist/node/esm/runtime/timing_safe_equal.js b/node_modules/jose/dist/node/esm/runtime/timing_safe_equal.js new file mode 100644 index 0000000..901ae38 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/timing_safe_equal.js @@ -0,0 +1,3 @@ +import { timingSafeEqual as impl } from 'crypto'; +const timingSafeEqual = impl; +export default timingSafeEqual; diff --git a/node_modules/jose/dist/node/esm/runtime/verify.js b/node_modules/jose/dist/node/esm/runtime/verify.js new file mode 100644 index 0000000..e514e1c --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/verify.js @@ -0,0 +1,36 @@ +import * as crypto from 'crypto'; +import { promisify } from 'util'; +import nodeDigest from './dsa_digest.js'; +import nodeKey from './node_key.js'; +import sign from './sign.js'; +import getVerifyKey from './get_sign_verify_key.js'; +import { oneShotCallback } from './flags.js'; +let oneShotVerify; +if (crypto.verify.length > 4 && oneShotCallback) { + oneShotVerify = promisify(crypto.verify); +} +else { + oneShotVerify = crypto.verify; +} +const verify = async (alg, key, signature, data) => { + const keyObject = getVerifyKey(alg, key, 'verify'); + if (alg.startsWith('HS')) { + const expected = await sign(alg, keyObject, data); + const actual = signature; + try { + return crypto.timingSafeEqual(actual, expected); + } + catch { + return false; + } + } + const algorithm = nodeDigest(alg); + const keyInput = nodeKey(alg, keyObject); + try { + return await oneShotVerify(algorithm, data, keyInput, signature); + } + catch { + return false; + } +}; +export default verify; diff --git a/node_modules/jose/dist/node/esm/runtime/webcrypto.js b/node_modules/jose/dist/node/esm/runtime/webcrypto.js new file mode 100644 index 0000000..a2fdb2a --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/webcrypto.js @@ -0,0 +1,8 @@ +import * as crypto from 'crypto'; +import * as util from 'util'; +const webcrypto = crypto.webcrypto; +export default webcrypto; +export const isCryptoKey = util.types.isCryptoKey + ? (key) => util.types.isCryptoKey(key) + : + (key) => false; diff --git a/node_modules/jose/dist/node/esm/runtime/zlib.js b/node_modules/jose/dist/node/esm/runtime/zlib.js new file mode 100644 index 0000000..ac67d82 --- /dev/null +++ b/node_modules/jose/dist/node/esm/runtime/zlib.js @@ -0,0 +1,9 @@ +import { promisify } from 'util'; +import { inflateRaw as inflateRawCb, deflateRaw as deflateRawCb } from 'zlib'; +import { JWEDecompressionFailed } from '../util/errors.js'; +const inflateRaw = promisify(inflateRawCb); +const deflateRaw = promisify(deflateRawCb); +export const inflate = (input) => inflateRaw(input, { maxOutputLength: 250000 }).catch(() => { + throw new JWEDecompressionFailed(); +}); +export const deflate = (input) => deflateRaw(input); diff --git a/node_modules/jose/dist/node/esm/util/base64url.js b/node_modules/jose/dist/node/esm/util/base64url.js new file mode 100644 index 0000000..88ce755 --- /dev/null +++ b/node_modules/jose/dist/node/esm/util/base64url.js @@ -0,0 +1,3 @@ +import * as base64url from '../runtime/base64url.js'; +export const encode = base64url.encode; +export const decode = base64url.decode; diff --git a/node_modules/jose/dist/node/esm/util/decode_jwt.js b/node_modules/jose/dist/node/esm/util/decode_jwt.js new file mode 100644 index 0000000..b6f2602 --- /dev/null +++ b/node_modules/jose/dist/node/esm/util/decode_jwt.js @@ -0,0 +1,32 @@ +import { decode as base64url } from './base64url.js'; +import { decoder } from '../lib/buffer_utils.js'; +import isObject from '../lib/is_object.js'; +import { JWTInvalid } from './errors.js'; +export function decodeJwt(jwt) { + if (typeof jwt !== 'string') + throw new JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string'); + const { 1: payload, length } = jwt.split('.'); + if (length === 5) + throw new JWTInvalid('Only JWTs using Compact JWS serialization can be decoded'); + if (length !== 3) + throw new JWTInvalid('Invalid JWT'); + if (!payload) + throw new JWTInvalid('JWTs must contain a payload'); + let decoded; + try { + decoded = base64url(payload); + } + catch { + throw new JWTInvalid('Failed to base64url decode the payload'); + } + let result; + try { + result = JSON.parse(decoder.decode(decoded)); + } + catch { + throw new JWTInvalid('Failed to parse the decoded payload as JSON'); + } + if (!isObject(result)) + throw new JWTInvalid('Invalid JWT Claims Set'); + return result; +} diff --git a/node_modules/jose/dist/node/esm/util/decode_protected_header.js b/node_modules/jose/dist/node/esm/util/decode_protected_header.js new file mode 100644 index 0000000..04be31d --- /dev/null +++ b/node_modules/jose/dist/node/esm/util/decode_protected_header.js @@ -0,0 +1,34 @@ +import { decode as base64url } from './base64url.js'; +import { decoder } from '../lib/buffer_utils.js'; +import isObject from '../lib/is_object.js'; +export function decodeProtectedHeader(token) { + let protectedB64u; + if (typeof token === 'string') { + const parts = token.split('.'); + if (parts.length === 3 || parts.length === 5) { + ; + [protectedB64u] = parts; + } + } + else if (typeof token === 'object' && token) { + if ('protected' in token) { + protectedB64u = token.protected; + } + else { + throw new TypeError('Token does not contain a Protected Header'); + } + } + try { + if (typeof protectedB64u !== 'string' || !protectedB64u) { + throw new Error(); + } + const result = JSON.parse(decoder.decode(base64url(protectedB64u))); + if (!isObject(result)) { + throw new Error(); + } + return result; + } + catch { + throw new TypeError('Invalid Token or Protected Header formatting'); + } +} diff --git a/node_modules/jose/dist/node/esm/util/errors.js b/node_modules/jose/dist/node/esm/util/errors.js new file mode 100644 index 0000000..2998faf --- /dev/null +++ b/node_modules/jose/dist/node/esm/util/errors.js @@ -0,0 +1,158 @@ +export class JOSEError extends Error { + static get code() { + return 'ERR_JOSE_GENERIC'; + } + constructor(message) { + var _a; + super(message); + this.code = 'ERR_JOSE_GENERIC'; + this.name = this.constructor.name; + (_a = Error.captureStackTrace) === null || _a === void 0 ? void 0 : _a.call(Error, this, this.constructor); + } +} +export class JWTClaimValidationFailed extends JOSEError { + static get code() { + return 'ERR_JWT_CLAIM_VALIDATION_FAILED'; + } + constructor(message, claim = 'unspecified', reason = 'unspecified') { + super(message); + this.code = 'ERR_JWT_CLAIM_VALIDATION_FAILED'; + this.claim = claim; + this.reason = reason; + } +} +export class JWTExpired extends JOSEError { + static get code() { + return 'ERR_JWT_EXPIRED'; + } + constructor(message, claim = 'unspecified', reason = 'unspecified') { + super(message); + this.code = 'ERR_JWT_EXPIRED'; + this.claim = claim; + this.reason = reason; + } +} +export class JOSEAlgNotAllowed extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JOSE_ALG_NOT_ALLOWED'; + } + static get code() { + return 'ERR_JOSE_ALG_NOT_ALLOWED'; + } +} +export class JOSENotSupported extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JOSE_NOT_SUPPORTED'; + } + static get code() { + return 'ERR_JOSE_NOT_SUPPORTED'; + } +} +export class JWEDecryptionFailed extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWE_DECRYPTION_FAILED'; + this.message = 'decryption operation failed'; + } + static get code() { + return 'ERR_JWE_DECRYPTION_FAILED'; + } +} +export class JWEDecompressionFailed extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWE_DECOMPRESSION_FAILED'; + this.message = 'decompression operation failed'; + } + static get code() { + return 'ERR_JWE_DECOMPRESSION_FAILED'; + } +} +export class JWEInvalid extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWE_INVALID'; + } + static get code() { + return 'ERR_JWE_INVALID'; + } +} +export class JWSInvalid extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWS_INVALID'; + } + static get code() { + return 'ERR_JWS_INVALID'; + } +} +export class JWTInvalid extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWT_INVALID'; + } + static get code() { + return 'ERR_JWT_INVALID'; + } +} +export class JWKInvalid extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWK_INVALID'; + } + static get code() { + return 'ERR_JWK_INVALID'; + } +} +export class JWKSInvalid extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWKS_INVALID'; + } + static get code() { + return 'ERR_JWKS_INVALID'; + } +} +export class JWKSNoMatchingKey extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWKS_NO_MATCHING_KEY'; + this.message = 'no applicable key found in the JSON Web Key Set'; + } + static get code() { + return 'ERR_JWKS_NO_MATCHING_KEY'; + } +} +export class JWKSMultipleMatchingKeys extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; + this.message = 'multiple matching keys found in the JSON Web Key Set'; + } + static get code() { + return 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; + } +} +Symbol.asyncIterator; +export class JWKSTimeout extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWKS_TIMEOUT'; + this.message = 'request timed out'; + } + static get code() { + return 'ERR_JWKS_TIMEOUT'; + } +} +export class JWSSignatureVerificationFailed extends JOSEError { + constructor() { + super(...arguments); + this.code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; + this.message = 'signature verification failed'; + } + static get code() { + return 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; + } +} diff --git a/node_modules/jose/dist/node/esm/util/runtime.js b/node_modules/jose/dist/node/esm/util/runtime.js new file mode 100644 index 0000000..2a4718b --- /dev/null +++ b/node_modules/jose/dist/node/esm/util/runtime.js @@ -0,0 +1,2 @@ +import value from '../runtime/runtime.js'; +export default value; diff --git a/node_modules/jose/dist/types/index.d.ts b/node_modules/jose/dist/types/index.d.ts new file mode 100644 index 0000000..0c68218 --- /dev/null +++ b/node_modules/jose/dist/types/index.d.ts @@ -0,0 +1,48 @@ +export { compactDecrypt } from './jwe/compact/decrypt'; +export type { CompactDecryptGetKey } from './jwe/compact/decrypt'; +export { flattenedDecrypt } from './jwe/flattened/decrypt'; +export type { FlattenedDecryptGetKey } from './jwe/flattened/decrypt'; +export { generalDecrypt } from './jwe/general/decrypt'; +export type { GeneralDecryptGetKey } from './jwe/general/decrypt'; +export { GeneralEncrypt } from './jwe/general/encrypt'; +export type { Recipient } from './jwe/general/encrypt'; +export { compactVerify } from './jws/compact/verify'; +export type { CompactVerifyGetKey } from './jws/compact/verify'; +export { flattenedVerify } from './jws/flattened/verify'; +export type { FlattenedVerifyGetKey } from './jws/flattened/verify'; +export { generalVerify } from './jws/general/verify'; +export type { GeneralVerifyGetKey } from './jws/general/verify'; +export { jwtVerify } from './jwt/verify'; +export type { JWTVerifyOptions, JWTVerifyGetKey } from './jwt/verify'; +export { jwtDecrypt } from './jwt/decrypt'; +export type { JWTDecryptOptions, JWTDecryptGetKey } from './jwt/decrypt'; +export type { ProduceJWT } from './jwt/produce'; +export { CompactEncrypt } from './jwe/compact/encrypt'; +export { FlattenedEncrypt } from './jwe/flattened/encrypt'; +export { CompactSign } from './jws/compact/sign'; +export { FlattenedSign } from './jws/flattened/sign'; +export { GeneralSign } from './jws/general/sign'; +export type { Signature } from './jws/general/sign'; +export { SignJWT } from './jwt/sign'; +export { EncryptJWT } from './jwt/encrypt'; +export { calculateJwkThumbprint, calculateJwkThumbprintUri } from './jwk/thumbprint'; +export { EmbeddedJWK } from './jwk/embedded'; +export { createLocalJWKSet } from './jwks/local'; +export { createRemoteJWKSet } from './jwks/remote'; +export type { RemoteJWKSetOptions } from './jwks/remote'; +export { UnsecuredJWT } from './jwt/unsecured'; +export type { UnsecuredResult } from './jwt/unsecured'; +export { exportPKCS8, exportSPKI, exportJWK } from './key/export'; +export { importSPKI, importPKCS8, importX509, importJWK } from './key/import'; +export type { PEMImportOptions } from './key/import'; +export { decodeProtectedHeader } from './util/decode_protected_header'; +export { decodeJwt } from './util/decode_jwt'; +export type { ProtectedHeaderParameters } from './util/decode_protected_header'; +export * as errors from './util/errors'; +export { generateKeyPair } from './key/generate_key_pair'; +export type { GenerateKeyPairResult, GenerateKeyPairOptions } from './key/generate_key_pair'; +export { generateSecret } from './key/generate_secret'; +export type { GenerateSecretOptions } from './key/generate_secret'; +export * as base64url from './util/base64url'; +export type { KeyLike, JWK, FlattenedJWSInput, GeneralJWSInput, FlattenedJWS, GeneralJWS, JoseHeaderParameters, JWSHeaderParameters, JWEKeyManagementHeaderParameters, FlattenedJWE, GeneralJWE, JWEHeaderParameters, CritOption, DeflateOption, DecryptOptions, EncryptOptions, JWTClaimVerificationOptions, VerifyOptions, SignOptions, JWTPayload, DeflateFunction, InflateFunction, FlattenedDecryptResult, GeneralDecryptResult, CompactDecryptResult, FlattenedVerifyResult, GeneralVerifyResult, CompactVerifyResult, JWTVerifyResult, JWTDecryptResult, ResolvedKey, CompactJWEHeaderParameters, CompactJWSHeaderParameters, JWTHeaderParameters, JSONWebKeySet, CryptoRuntime, GetKeyFunction, } from './types'; +export { default as cryptoRuntime } from './util/runtime'; diff --git a/node_modules/jose/dist/types/jwe/compact/decrypt.d.ts b/node_modules/jose/dist/types/jwe/compact/decrypt.d.ts new file mode 100644 index 0000000..14b2680 --- /dev/null +++ b/node_modules/jose/dist/types/jwe/compact/decrypt.d.ts @@ -0,0 +1,23 @@ +import type { KeyLike, DecryptOptions, CompactJWEHeaderParameters, GetKeyFunction, FlattenedJWE, CompactDecryptResult, ResolvedKey } from '../../types'; +/** + * Interface for Compact JWE Decryption dynamic key resolution. No token components have been + * verified at the time of this function call. + */ +export interface CompactDecryptGetKey extends GetKeyFunction { +} +/** + * Decrypts a Compact JWE. + * + * @param jwe Compact JWE. + * @param key Private Key or Secret to decrypt the JWE with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWE Decryption options. + */ +export declare function compactDecrypt(jwe: string | Uint8Array, key: KeyLike | Uint8Array, options?: DecryptOptions): Promise; +/** + * @param jwe Compact JWE. + * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWE Decryption options. + */ +export declare function compactDecrypt(jwe: string | Uint8Array, getKey: CompactDecryptGetKey, options?: DecryptOptions): Promise>; diff --git a/node_modules/jose/dist/types/jwe/compact/encrypt.d.ts b/node_modules/jose/dist/types/jwe/compact/encrypt.d.ts new file mode 100644 index 0000000..f3a5af6 --- /dev/null +++ b/node_modules/jose/dist/types/jwe/compact/encrypt.d.ts @@ -0,0 +1,52 @@ +import type { KeyLike, JWEKeyManagementHeaderParameters, CompactJWEHeaderParameters, EncryptOptions } from '../../types'; +/** + * The CompactEncrypt class is used to build and encrypt Compact JWE strings. + * + */ +export declare class CompactEncrypt { + private _flattened; + /** @param plaintext Binary representation of the plaintext to encrypt. */ + constructor(plaintext: Uint8Array); + /** + * Sets a content encryption key to use, by default a random suitable one is generated for the JWE + * enc" (Encryption Algorithm) Header Parameter. + * + * @deprecated You should not use this method. It is only really intended for test and vector + * validation purposes. + * + * @param cek JWE Content Encryption Key. + */ + setContentEncryptionKey(cek: Uint8Array): this; + /** + * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable + * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. + * + * @deprecated You should not use this method. It is only really intended for test and vector + * validation purposes. + * + * @param iv JWE Initialization Vector. + */ + setInitializationVector(iv: Uint8Array): this; + /** + * Sets the JWE Protected Header on the CompactEncrypt object. + * + * @param protectedHeader JWE Protected Header object. + */ + setProtectedHeader(protectedHeader: CompactJWEHeaderParameters): this; + /** + * Sets the JWE Key Management parameters to be used when encrypting the Content Encryption Key. + * You do not need to invoke this method, it is only really intended for test and vector + * validation purposes. + * + * @param parameters JWE Key Management parameters. + */ + setKeyManagementParameters(parameters: JWEKeyManagementHeaderParameters): this; + /** + * Encrypts and resolves the value of the Compact JWE string. + * + * @param key Public Key or Secret to encrypt the JWE with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWE Encryption options. + */ + encrypt(key: KeyLike | Uint8Array, options?: EncryptOptions): Promise; +} diff --git a/node_modules/jose/dist/types/jwe/flattened/decrypt.d.ts b/node_modules/jose/dist/types/jwe/flattened/decrypt.d.ts new file mode 100644 index 0000000..8726df6 --- /dev/null +++ b/node_modules/jose/dist/types/jwe/flattened/decrypt.d.ts @@ -0,0 +1,23 @@ +import type { FlattenedDecryptResult, KeyLike, FlattenedJWE, JWEHeaderParameters, DecryptOptions, GetKeyFunction, ResolvedKey } from '../../types'; +/** + * Interface for Flattened JWE Decryption dynamic key resolution. No token components have been + * verified at the time of this function call. + */ +export interface FlattenedDecryptGetKey extends GetKeyFunction { +} +/** + * Decrypts a Flattened JWE. + * + * @param jwe Flattened JWE. + * @param key Private Key or Secret to decrypt the JWE with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWE Decryption options. + */ +export declare function flattenedDecrypt(jwe: FlattenedJWE, key: KeyLike | Uint8Array, options?: DecryptOptions): Promise; +/** + * @param jwe Flattened JWE. + * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWE Decryption options. + */ +export declare function flattenedDecrypt(jwe: FlattenedJWE, getKey: FlattenedDecryptGetKey, options?: DecryptOptions): Promise>; diff --git a/node_modules/jose/dist/types/jwe/flattened/encrypt.d.ts b/node_modules/jose/dist/types/jwe/flattened/encrypt.d.ts new file mode 100644 index 0000000..d2a214d --- /dev/null +++ b/node_modules/jose/dist/types/jwe/flattened/encrypt.d.ts @@ -0,0 +1,80 @@ +import type { KeyLike, FlattenedJWE, JWEHeaderParameters, JWEKeyManagementHeaderParameters, EncryptOptions } from '../../types'; +/** @private */ +export declare const unprotected: unique symbol; +/** + * The FlattenedEncrypt class is used to build and encrypt Flattened JWE objects. + * + */ +export declare class FlattenedEncrypt { + private _plaintext; + private _protectedHeader; + private _sharedUnprotectedHeader; + private _unprotectedHeader; + private _aad; + private _cek; + private _iv; + private _keyManagementParameters; + /** @param plaintext Binary representation of the plaintext to encrypt. */ + constructor(plaintext: Uint8Array); + /** + * Sets the JWE Key Management parameters to be used when encrypting. Use of this is method is + * really only needed for ECDH based algorithms when utilizing the Agreement PartyUInfo or + * Agreement PartyVInfo parameters. Other parameters will always be randomly generated when needed + * and missing. + * + * @param parameters JWE Key Management parameters. + */ + setKeyManagementParameters(parameters: JWEKeyManagementHeaderParameters): this; + /** + * Sets the JWE Protected Header on the FlattenedEncrypt object. + * + * @param protectedHeader JWE Protected Header. + */ + setProtectedHeader(protectedHeader: JWEHeaderParameters): this; + /** + * Sets the JWE Shared Unprotected Header on the FlattenedEncrypt object. + * + * @param sharedUnprotectedHeader JWE Shared Unprotected Header. + */ + setSharedUnprotectedHeader(sharedUnprotectedHeader: JWEHeaderParameters): this; + /** + * Sets the JWE Per-Recipient Unprotected Header on the FlattenedEncrypt object. + * + * @param unprotectedHeader JWE Per-Recipient Unprotected Header. + */ + setUnprotectedHeader(unprotectedHeader: JWEHeaderParameters): this; + /** + * Sets the Additional Authenticated Data on the FlattenedEncrypt object. + * + * @param aad Additional Authenticated Data. + */ + setAdditionalAuthenticatedData(aad: Uint8Array): this; + /** + * Sets a content encryption key to use, by default a random suitable one is generated for the JWE + * enc" (Encryption Algorithm) Header Parameter. + * + * @deprecated You should not use this method. It is only really intended for test and vector + * validation purposes. + * + * @param cek JWE Content Encryption Key. + */ + setContentEncryptionKey(cek: Uint8Array): this; + /** + * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable + * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. + * + * @deprecated You should not use this method. It is only really intended for test and vector + * validation purposes. + * + * @param iv JWE Initialization Vector. + */ + setInitializationVector(iv: Uint8Array): this; + /** + * Encrypts and resolves the value of the Flattened JWE object. + * + * @param key Public Key or Secret to encrypt the JWE with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWE Encryption options. + */ + encrypt(key: KeyLike | Uint8Array, options?: EncryptOptions): Promise; +} diff --git a/node_modules/jose/dist/types/jwe/general/decrypt.d.ts b/node_modules/jose/dist/types/jwe/general/decrypt.d.ts new file mode 100644 index 0000000..26fc8b6 --- /dev/null +++ b/node_modules/jose/dist/types/jwe/general/decrypt.d.ts @@ -0,0 +1,23 @@ +import type { KeyLike, DecryptOptions, JWEHeaderParameters, GetKeyFunction, FlattenedJWE, GeneralJWE, GeneralDecryptResult, ResolvedKey } from '../../types'; +/** + * Interface for General JWE Decryption dynamic key resolution. No token components have been + * verified at the time of this function call. + */ +export interface GeneralDecryptGetKey extends GetKeyFunction { +} +/** + * Decrypts a General JWE. + * + * @param jwe General JWE. + * @param key Private Key or Secret to decrypt the JWE with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWE Decryption options. + */ +export declare function generalDecrypt(jwe: GeneralJWE, key: KeyLike | Uint8Array, options?: DecryptOptions): Promise; +/** + * @param jwe General JWE. + * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWE Decryption options. + */ +export declare function generalDecrypt(jwe: GeneralJWE, getKey: GeneralDecryptGetKey, options?: DecryptOptions): Promise>; diff --git a/node_modules/jose/dist/types/jwe/general/encrypt.d.ts b/node_modules/jose/dist/types/jwe/general/encrypt.d.ts new file mode 100644 index 0000000..8cecd3a --- /dev/null +++ b/node_modules/jose/dist/types/jwe/general/encrypt.d.ts @@ -0,0 +1,60 @@ +import type { KeyLike, GeneralJWE, JWEHeaderParameters, CritOption, DeflateOption } from '../../types'; +export interface Recipient { + /** + * Sets the JWE Per-Recipient Unprotected Header on the Recipient object. + * + * @param unprotectedHeader JWE Per-Recipient Unprotected Header. + */ + setUnprotectedHeader(unprotectedHeader: JWEHeaderParameters): Recipient; + /** A shorthand for calling addRecipient() on the enclosing GeneralEncrypt instance */ + addRecipient(...args: Parameters): Recipient; + /** A shorthand for calling encrypt() on the enclosing GeneralEncrypt instance */ + encrypt(...args: Parameters): Promise; + /** Returns the enclosing GeneralEncrypt */ + done(): GeneralEncrypt; +} +/** + * The GeneralEncrypt class is used to build and encrypt General JWE objects. + * + */ +export declare class GeneralEncrypt { + private _plaintext; + private _recipients; + private _protectedHeader; + private _unprotectedHeader; + private _aad; + /** @param plaintext Binary representation of the plaintext to encrypt. */ + constructor(plaintext: Uint8Array); + /** + * Adds an additional recipient for the General JWE object. + * + * @param key Public Key or Secret to encrypt the Content Encryption Key for the recipient with. + * See {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWE Encryption options. + */ + addRecipient(key: KeyLike | Uint8Array, options?: CritOption): Recipient; + /** + * Sets the JWE Protected Header on the GeneralEncrypt object. + * + * @param protectedHeader JWE Protected Header object. + */ + setProtectedHeader(protectedHeader: JWEHeaderParameters): this; + /** + * Sets the JWE Shared Unprotected Header on the GeneralEncrypt object. + * + * @param sharedUnprotectedHeader JWE Shared Unprotected Header object. + */ + setSharedUnprotectedHeader(sharedUnprotectedHeader: JWEHeaderParameters): this; + /** + * Sets the Additional Authenticated Data on the GeneralEncrypt object. + * + * @param aad Additional Authenticated Data. + */ + setAdditionalAuthenticatedData(aad: Uint8Array): this; + /** + * Encrypts and resolves the value of the General JWE object. + * + * @param options JWE Encryption options. + */ + encrypt(options?: DeflateOption): Promise; +} diff --git a/node_modules/jose/dist/types/jwk/embedded.d.ts b/node_modules/jose/dist/types/jwk/embedded.d.ts new file mode 100644 index 0000000..e655097 --- /dev/null +++ b/node_modules/jose/dist/types/jwk/embedded.d.ts @@ -0,0 +1,9 @@ +import type { KeyLike, FlattenedJWSInput, JWSHeaderParameters } from '../types'; +/** + * EmbeddedJWK is an implementation of a GetKeyFunction intended to be used with the JWS/JWT verify + * operations whenever you need to opt-in to verify signatures with a public key embedded in the + * token's "jwk" (JSON Web Key) Header Parameter. It is recommended to combine this with the verify + * function's `algorithms` option to define accepted JWS "alg" (Algorithm) Header Parameter values. + * + */ +export declare function EmbeddedJWK(protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput): Promise; diff --git a/node_modules/jose/dist/types/jwk/thumbprint.d.ts b/node_modules/jose/dist/types/jwk/thumbprint.d.ts new file mode 100644 index 0000000..0f550c2 --- /dev/null +++ b/node_modules/jose/dist/types/jwk/thumbprint.d.ts @@ -0,0 +1,21 @@ +import type { JWK } from '../types'; +/** + * Calculates a base64url-encoded JSON Web Key (JWK) Thumbprint + * + * @param jwk JSON Web Key. + * @param digestAlgorithm Digest Algorithm to use for calculating the thumbprint. Default is + * "sha256". + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7638 RFC7638} + */ +export declare function calculateJwkThumbprint(jwk: JWK, digestAlgorithm?: 'sha256' | 'sha384' | 'sha512'): Promise; +/** + * Calculates a JSON Web Key (JWK) Thumbprint URI + * + * @param jwk JSON Web Key. + * @param digestAlgorithm Digest Algorithm to use for calculating the thumbprint. Default is + * "sha256". + * + * @see {@link https://www.rfc-editor.org/rfc/rfc9278 RFC9278} + */ +export declare function calculateJwkThumbprintUri(jwk: JWK, digestAlgorithm?: 'sha256' | 'sha384' | 'sha512'): Promise; diff --git a/node_modules/jose/dist/types/jwks/local.d.ts b/node_modules/jose/dist/types/jwks/local.d.ts new file mode 100644 index 0000000..475ae40 --- /dev/null +++ b/node_modules/jose/dist/types/jwks/local.d.ts @@ -0,0 +1,26 @@ +import type { KeyLike, JWSHeaderParameters, JSONWebKeySet, FlattenedJWSInput } from '../types'; +/** @private */ +export declare function isJWKSLike(jwks: unknown): jwks is JSONWebKeySet; +/** @private */ +export declare class LocalJWKSet { + protected _jwks?: JSONWebKeySet; + private _cached; + constructor(jwks: unknown); + getKey(protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput): Promise; +} +/** + * Returns a function that resolves to a key object from a locally stored, or otherwise available, + * JSON Web Key Set. + * + * It uses the "alg" (JWS Algorithm) Header Parameter to determine the right JWK "kty" (Key Type), + * then proceeds to match the JWK "kid" (Key ID) with one found in the JWS Header Parameters (if + * there is one) while also respecting the JWK "use" (Public Key Use) and JWK "key_ops" (Key + * Operations) Parameters (if they are present on the JWK). + * + * Only a single public key must match the selection process. As shown in the example below when + * multiple keys get matched it is possible to opt-in to iterate over the matched keys and attempt + * verification in an iterative manner. + * + * @param jwks JSON Web Key Set formatted object. + */ +export declare function createLocalJWKSet(jwks: JSONWebKeySet): (protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput) => Promise; diff --git a/node_modules/jose/dist/types/jwks/remote.d.ts b/node_modules/jose/dist/types/jwks/remote.d.ts new file mode 100644 index 0000000..7fd5fe1 --- /dev/null +++ b/node_modules/jose/dist/types/jwks/remote.d.ts @@ -0,0 +1,49 @@ +import type { KeyLike, JWSHeaderParameters, FlattenedJWSInput } from '../types'; +/** Options for the remote JSON Web Key Set. */ +export interface RemoteJWKSetOptions { + /** + * Timeout (in milliseconds) for the HTTP request. When reached the request will be aborted and + * the verification will fail. Default is 5000 (5 seconds). + */ + timeoutDuration?: number; + /** + * Duration (in milliseconds) for which no more HTTP requests will be triggered after a previous + * successful fetch. Default is 30000 (30 seconds). + */ + cooldownDuration?: number; + /** + * Maximum time (in milliseconds) between successful HTTP requests. Default is 600000 (10 + * minutes). + */ + cacheMaxAge?: number | typeof Infinity; + /** + * An instance of {@link https://nodejs.org/api/http.html#class-httpagent http.Agent} or + * {@link https://nodejs.org/api/https.html#class-httpsagent https.Agent} to pass to the + * {@link https://nodejs.org/api/http.html#httpgetoptions-callback http.get} or + * {@link https://nodejs.org/api/https.html#httpsgetoptions-callback https.get} method's options. + * Use when behind an http(s) proxy. This is a Node.js runtime specific option, it is ignored when + * used outside of Node.js runtime. + */ + agent?: any; + /** Optional headers to be sent with the HTTP request. */ + headers?: Record; +} +/** + * Returns a function that resolves to a key object downloaded from a remote endpoint returning a + * JSON Web Key Set, that is, for example, an OAuth 2.0 or OIDC jwks_uri. The JSON Web Key Set is + * fetched when no key matches the selection process but only as frequently as the + * `cooldownDuration` option allows to prevent abuse. + * + * It uses the "alg" (JWS Algorithm) Header Parameter to determine the right JWK "kty" (Key Type), + * then proceeds to match the JWK "kid" (Key ID) with one found in the JWS Header Parameters (if + * there is one) while also respecting the JWK "use" (Public Key Use) and JWK "key_ops" (Key + * Operations) Parameters (if they are present on the JWK). + * + * Only a single public key must match the selection process. As shown in the example below when + * multiple keys get matched it is possible to opt-in to iterate over the matched keys and attempt + * verification in an iterative manner. + * + * @param url URL to fetch the JSON Web Key Set from. + * @param options Options for the remote JSON Web Key Set. + */ +export declare function createRemoteJWKSet(url: URL, options?: RemoteJWKSetOptions): (protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput) => Promise; diff --git a/node_modules/jose/dist/types/jws/compact/sign.d.ts b/node_modules/jose/dist/types/jws/compact/sign.d.ts new file mode 100644 index 0000000..9e2ecb8 --- /dev/null +++ b/node_modules/jose/dist/types/jws/compact/sign.d.ts @@ -0,0 +1,24 @@ +import type { CompactJWSHeaderParameters, KeyLike, SignOptions } from '../../types'; +/** + * The CompactSign class is used to build and sign Compact JWS strings. + * + */ +export declare class CompactSign { + private _flattened; + /** @param payload Binary representation of the payload to sign. */ + constructor(payload: Uint8Array); + /** + * Sets the JWS Protected Header on the Sign object. + * + * @param protectedHeader JWS Protected Header. + */ + setProtectedHeader(protectedHeader: CompactJWSHeaderParameters): this; + /** + * Signs and resolves the value of the Compact JWS string. + * + * @param key Private Key or Secret to sign the JWS with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWS Sign options. + */ + sign(key: KeyLike | Uint8Array, options?: SignOptions): Promise; +} diff --git a/node_modules/jose/dist/types/jws/compact/verify.d.ts b/node_modules/jose/dist/types/jws/compact/verify.d.ts new file mode 100644 index 0000000..89e784f --- /dev/null +++ b/node_modules/jose/dist/types/jws/compact/verify.d.ts @@ -0,0 +1,25 @@ +import type { CompactVerifyResult, FlattenedJWSInput, GetKeyFunction, CompactJWSHeaderParameters, KeyLike, VerifyOptions, ResolvedKey } from '../../types'; +/** + * Interface for Compact JWS Verification dynamic key resolution. No token components have been + * verified at the time of this function call. + * + * @see [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) to verify using a remote JSON Web Key Set. + */ +export interface CompactVerifyGetKey extends GetKeyFunction { +} +/** + * Verifies the signature and format of and afterwards decodes the Compact JWS. + * + * @param jws Compact JWS. + * @param key Key to verify the JWS with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWS Verify options. + */ +export declare function compactVerify(jws: string | Uint8Array, key: KeyLike | Uint8Array, options?: VerifyOptions): Promise; +/** + * @param jws Compact JWS. + * @param getKey Function resolving a key to verify the JWS with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWS Verify options. + */ +export declare function compactVerify(jws: string | Uint8Array, getKey: CompactVerifyGetKey, options?: VerifyOptions): Promise>; diff --git a/node_modules/jose/dist/types/jws/flattened/sign.d.ts b/node_modules/jose/dist/types/jws/flattened/sign.d.ts new file mode 100644 index 0000000..09f1242 --- /dev/null +++ b/node_modules/jose/dist/types/jws/flattened/sign.d.ts @@ -0,0 +1,32 @@ +import type { KeyLike, FlattenedJWS, JWSHeaderParameters, SignOptions } from '../../types'; +/** + * The FlattenedSign class is used to build and sign Flattened JWS objects. + * + */ +export declare class FlattenedSign { + private _payload; + private _protectedHeader; + private _unprotectedHeader; + /** @param payload Binary representation of the payload to sign. */ + constructor(payload: Uint8Array); + /** + * Sets the JWS Protected Header on the FlattenedSign object. + * + * @param protectedHeader JWS Protected Header. + */ + setProtectedHeader(protectedHeader: JWSHeaderParameters): this; + /** + * Sets the JWS Unprotected Header on the FlattenedSign object. + * + * @param unprotectedHeader JWS Unprotected Header. + */ + setUnprotectedHeader(unprotectedHeader: JWSHeaderParameters): this; + /** + * Signs and resolves the value of the Flattened JWS object. + * + * @param key Private Key or Secret to sign the JWS with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWS Sign options. + */ + sign(key: KeyLike | Uint8Array, options?: SignOptions): Promise; +} diff --git a/node_modules/jose/dist/types/jws/flattened/verify.d.ts b/node_modules/jose/dist/types/jws/flattened/verify.d.ts new file mode 100644 index 0000000..161b322 --- /dev/null +++ b/node_modules/jose/dist/types/jws/flattened/verify.d.ts @@ -0,0 +1,25 @@ +import type { FlattenedVerifyResult, KeyLike, FlattenedJWSInput, JWSHeaderParameters, VerifyOptions, GetKeyFunction, ResolvedKey } from '../../types'; +/** + * Interface for Flattened JWS Verification dynamic key resolution. No token components have been + * verified at the time of this function call. + * + * @see [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) to verify using a remote JSON Web Key Set. + */ +export interface FlattenedVerifyGetKey extends GetKeyFunction { +} +/** + * Verifies the signature and format of and afterwards decodes the Flattened JWS. + * + * @param jws Flattened JWS. + * @param key Key to verify the JWS with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWS Verify options. + */ +export declare function flattenedVerify(jws: FlattenedJWSInput, key: KeyLike | Uint8Array, options?: VerifyOptions): Promise; +/** + * @param jws Flattened JWS. + * @param getKey Function resolving a key to verify the JWS with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWS Verify options. + */ +export declare function flattenedVerify(jws: FlattenedJWSInput, getKey: FlattenedVerifyGetKey, options?: VerifyOptions): Promise>; diff --git a/node_modules/jose/dist/types/jws/general/sign.d.ts b/node_modules/jose/dist/types/jws/general/sign.d.ts new file mode 100644 index 0000000..e79ca7f --- /dev/null +++ b/node_modules/jose/dist/types/jws/general/sign.d.ts @@ -0,0 +1,41 @@ +import type { KeyLike, GeneralJWS, JWSHeaderParameters, SignOptions } from '../../types'; +export interface Signature { + /** + * Sets the JWS Protected Header on the Signature object. + * + * @param protectedHeader JWS Protected Header. + */ + setProtectedHeader(protectedHeader: JWSHeaderParameters): Signature; + /** + * Sets the JWS Unprotected Header on the Signature object. + * + * @param unprotectedHeader JWS Unprotected Header. + */ + setUnprotectedHeader(unprotectedHeader: JWSHeaderParameters): Signature; + /** A shorthand for calling addSignature() on the enclosing GeneralSign instance */ + addSignature(...args: Parameters): Signature; + /** A shorthand for calling encrypt() on the enclosing GeneralSign instance */ + sign(...args: Parameters): Promise; + /** Returns the enclosing GeneralSign */ + done(): GeneralSign; +} +/** + * The GeneralSign class is used to build and sign General JWS objects. + * + */ +export declare class GeneralSign { + private _payload; + private _signatures; + /** @param payload Binary representation of the payload to sign. */ + constructor(payload: Uint8Array); + /** + * Adds an additional signature for the General JWS object. + * + * @param key Private Key or Secret to sign the individual JWS signature with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWS Sign options. + */ + addSignature(key: KeyLike | Uint8Array, options?: SignOptions): Signature; + /** Signs and resolves the value of the General JWS object. */ + sign(): Promise; +} diff --git a/node_modules/jose/dist/types/jws/general/verify.d.ts b/node_modules/jose/dist/types/jws/general/verify.d.ts new file mode 100644 index 0000000..1d4eaed --- /dev/null +++ b/node_modules/jose/dist/types/jws/general/verify.d.ts @@ -0,0 +1,25 @@ +import type { GeneralJWSInput, GeneralVerifyResult, FlattenedJWSInput, GetKeyFunction, JWSHeaderParameters, KeyLike, VerifyOptions, ResolvedKey } from '../../types'; +/** + * Interface for General JWS Verification dynamic key resolution. No token components have been + * verified at the time of this function call. + * + * @see [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) to verify using a remote JSON Web Key Set. + */ +export interface GeneralVerifyGetKey extends GetKeyFunction { +} +/** + * Verifies the signature and format of and afterwards decodes the General JWS. + * + * @param jws General JWS. + * @param key Key to verify the JWS with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWS Verify options. + */ +export declare function generalVerify(jws: GeneralJWSInput, key: KeyLike | Uint8Array, options?: VerifyOptions): Promise; +/** + * @param jws General JWS. + * @param getKey Function resolving a key to verify the JWS with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWS Verify options. + */ +export declare function generalVerify(jws: GeneralJWSInput, getKey: GeneralVerifyGetKey, options?: VerifyOptions): Promise>; diff --git a/node_modules/jose/dist/types/jwt/decrypt.d.ts b/node_modules/jose/dist/types/jwt/decrypt.d.ts new file mode 100644 index 0000000..ae163fe --- /dev/null +++ b/node_modules/jose/dist/types/jwt/decrypt.d.ts @@ -0,0 +1,27 @@ +import type { KeyLike, DecryptOptions, JWTClaimVerificationOptions, GetKeyFunction, CompactJWEHeaderParameters, FlattenedJWE, JWTDecryptResult, ResolvedKey } from '../types'; +/** Combination of JWE Decryption options and JWT Claims Set verification options. */ +export interface JWTDecryptOptions extends DecryptOptions, JWTClaimVerificationOptions { +} +/** + * Interface for JWT Decryption dynamic key resolution. No token components have been verified at + * the time of this function call. + */ +export interface JWTDecryptGetKey extends GetKeyFunction { +} +/** + * Verifies the JWT format (to be a JWE Compact format), decrypts the ciphertext, validates the JWT + * Claims Set. + * + * @param jwt JSON Web Token value (encoded as JWE). + * @param key Private Key or Secret to decrypt and verify the JWT with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWT Decryption and JWT Claims Set validation options. + */ +export declare function jwtDecrypt(jwt: string | Uint8Array, key: KeyLike | Uint8Array, options?: JWTDecryptOptions): Promise; +/** + * @param jwt JSON Web Token value (encoded as JWE). + * @param getKey Function resolving Private Key or Secret to decrypt and verify the JWT with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWT Decryption and JWT Claims Set validation options. + */ +export declare function jwtDecrypt(jwt: string | Uint8Array, getKey: JWTDecryptGetKey, options?: JWTDecryptOptions): Promise>; diff --git a/node_modules/jose/dist/types/jwt/encrypt.d.ts b/node_modules/jose/dist/types/jwt/encrypt.d.ts new file mode 100644 index 0000000..b9df62f --- /dev/null +++ b/node_modules/jose/dist/types/jwt/encrypt.d.ts @@ -0,0 +1,77 @@ +import type { EncryptOptions, CompactJWEHeaderParameters, JWEKeyManagementHeaderParameters, KeyLike } from '../types'; +import { ProduceJWT } from './produce'; +/** + * The EncryptJWT class is used to build and encrypt Compact JWE formatted JSON Web Tokens. + * + */ +export declare class EncryptJWT extends ProduceJWT { + private _cek; + private _iv; + private _keyManagementParameters; + private _protectedHeader; + private _replicateIssuerAsHeader; + private _replicateSubjectAsHeader; + private _replicateAudienceAsHeader; + /** + * Sets the JWE Protected Header on the EncryptJWT object. + * + * @param protectedHeader JWE Protected Header. Must contain an "alg" (JWE Algorithm) and "enc" + * (JWE Encryption Algorithm) properties. + */ + setProtectedHeader(protectedHeader: CompactJWEHeaderParameters): this; + /** + * Sets the JWE Key Management parameters to be used when encrypting. Use of this is method is + * really only needed for ECDH based algorithms when utilizing the Agreement PartyUInfo or + * Agreement PartyVInfo parameters. Other parameters will always be randomly generated when needed + * and missing. + * + * @param parameters JWE Key Management parameters. + */ + setKeyManagementParameters(parameters: JWEKeyManagementHeaderParameters): this; + /** + * Sets a content encryption key to use, by default a random suitable one is generated for the JWE + * enc" (Encryption Algorithm) Header Parameter. + * + * @deprecated You should not use this method. It is only really intended for test and vector + * validation purposes. + * + * @param cek JWE Content Encryption Key. + */ + setContentEncryptionKey(cek: Uint8Array): this; + /** + * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable + * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. + * + * @deprecated You should not use this method. It is only really intended for test and vector + * validation purposes. + * + * @param iv JWE Initialization Vector. + */ + setInitializationVector(iv: Uint8Array): this; + /** + * Replicates the "iss" (Issuer) Claim as a JWE Protected Header Parameter. + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3} + */ + replicateIssuerAsHeader(): this; + /** + * Replicates the "sub" (Subject) Claim as a JWE Protected Header Parameter. + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3} + */ + replicateSubjectAsHeader(): this; + /** + * Replicates the "aud" (Audience) Claim as a JWE Protected Header Parameter. + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3} + */ + replicateAudienceAsHeader(): this; + /** + * Encrypts and returns the JWT. + * + * @param key Public Key or Secret to encrypt the JWT with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWE Encryption options. + */ + encrypt(key: KeyLike | Uint8Array, options?: EncryptOptions): Promise; +} diff --git a/node_modules/jose/dist/types/jwt/produce.d.ts b/node_modules/jose/dist/types/jwt/produce.d.ts new file mode 100644 index 0000000..5563a06 --- /dev/null +++ b/node_modules/jose/dist/types/jwt/produce.d.ts @@ -0,0 +1,54 @@ +import type { JWTPayload } from '../types'; +/** Generic class for JWT producing. */ +export declare class ProduceJWT { + protected _payload: JWTPayload; + /** @param payload The JWT Claims Set object. */ + constructor(payload: JWTPayload); + /** + * Set "iss" (Issuer) Claim. + * + * @param issuer "Issuer" Claim value to set on the JWT Claims Set. + */ + setIssuer(issuer: string): this; + /** + * Set "sub" (Subject) Claim. + * + * @param subject "sub" (Subject) Claim value to set on the JWT Claims Set. + */ + setSubject(subject: string): this; + /** + * Set "aud" (Audience) Claim. + * + * @param audience "aud" (Audience) Claim value to set on the JWT Claims Set. + */ + setAudience(audience: string | string[]): this; + /** + * Set "jti" (JWT ID) Claim. + * + * @param jwtId "jti" (JWT ID) Claim value to set on the JWT Claims Set. + */ + setJti(jwtId: string): this; + /** + * Set "nbf" (Not Before) Claim. + * + * @param input "nbf" (Not Before) Claim value to set on the JWT Claims Set. When number is passed + * that is used as a value, when string is passed it is resolved to a time span and added to the + * current timestamp. + */ + setNotBefore(input: number | string): this; + /** + * Set "exp" (Expiration Time) Claim. + * + * @param input "exp" (Expiration Time) Claim value to set on the JWT Claims Set. When number is + * passed that is used as a value, when string is passed it is resolved to a time span and added + * to the current timestamp. + */ + setExpirationTime(input: number | string): this; + /** + * Set "iat" (Issued At) Claim. + * + * @param input "iat" (Issued At) Claim value to set on the JWT Claims Set. Default is current + * timestamp. + */ + setIssuedAt(input?: number): this; +} diff --git a/node_modules/jose/dist/types/jwt/sign.d.ts b/node_modules/jose/dist/types/jwt/sign.d.ts new file mode 100644 index 0000000..f11661d --- /dev/null +++ b/node_modules/jose/dist/types/jwt/sign.d.ts @@ -0,0 +1,23 @@ +import type { JWTHeaderParameters, KeyLike, SignOptions } from '../types'; +import { ProduceJWT } from './produce'; +/** + * The SignJWT class is used to build and sign Compact JWS formatted JSON Web Tokens. + * + */ +export declare class SignJWT extends ProduceJWT { + private _protectedHeader; + /** + * Sets the JWS Protected Header on the SignJWT object. + * + * @param protectedHeader JWS Protected Header. Must contain an "alg" (JWS Algorithm) property. + */ + setProtectedHeader(protectedHeader: JWTHeaderParameters): this; + /** + * Signs and returns the JWT. + * + * @param key Private Key or Secret to sign the JWT with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWT Sign options. + */ + sign(key: KeyLike | Uint8Array, options?: SignOptions): Promise; +} diff --git a/node_modules/jose/dist/types/jwt/unsecured.d.ts b/node_modules/jose/dist/types/jwt/unsecured.d.ts new file mode 100644 index 0000000..14fe856 --- /dev/null +++ b/node_modules/jose/dist/types/jwt/unsecured.d.ts @@ -0,0 +1,21 @@ +import type { JWSHeaderParameters, JWTClaimVerificationOptions, JWTPayload } from '../types'; +import { ProduceJWT } from './produce'; +export interface UnsecuredResult { + payload: JWTPayload; + header: JWSHeaderParameters; +} +/** + * The UnsecuredJWT class is a utility for dealing with `{ "alg": "none" }` Unsecured JWTs. + * + */ +export declare class UnsecuredJWT extends ProduceJWT { + /** Encodes the Unsecured JWT. */ + encode(): string; + /** + * Decodes an unsecured JWT. + * + * @param jwt Unsecured JWT to decode the payload of. + * @param options JWT Claims Set validation options. + */ + static decode(jwt: string, options?: JWTClaimVerificationOptions): UnsecuredResult; +} diff --git a/node_modules/jose/dist/types/jwt/verify.d.ts b/node_modules/jose/dist/types/jwt/verify.d.ts new file mode 100644 index 0000000..1d98ebe --- /dev/null +++ b/node_modules/jose/dist/types/jwt/verify.d.ts @@ -0,0 +1,29 @@ +import type { KeyLike, VerifyOptions, JWTClaimVerificationOptions, JWTHeaderParameters, GetKeyFunction, FlattenedJWSInput, JWTVerifyResult, ResolvedKey } from '../types'; +/** Combination of JWS Verification options and JWT Claims Set verification options. */ +export interface JWTVerifyOptions extends VerifyOptions, JWTClaimVerificationOptions { +} +/** + * Interface for JWT Verification dynamic key resolution. No token components have been verified at + * the time of this function call. + * + * @see [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) to verify using a remote JSON Web Key Set. + */ +export interface JWTVerifyGetKey extends GetKeyFunction { +} +/** + * Verifies the JWT format (to be a JWS Compact format), verifies the JWS signature, validates the + * JWT Claims Set. + * + * @param jwt JSON Web Token value (encoded as JWS). + * @param key Key to verify the JWT with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWT Decryption and JWT Claims Set validation options. + */ +export declare function jwtVerify(jwt: string | Uint8Array, key: KeyLike | Uint8Array, options?: JWTVerifyOptions): Promise; +/** + * @param jwt JSON Web Token value (encoded as JWS). + * @param getKey Function resolving a key to verify the JWT with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWT Decryption and JWT Claims Set validation options. + */ +export declare function jwtVerify(jwt: string | Uint8Array, getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): Promise>; diff --git a/node_modules/jose/dist/types/key/export.d.ts b/node_modules/jose/dist/types/key/export.d.ts new file mode 100644 index 0000000..32cd6c0 --- /dev/null +++ b/node_modules/jose/dist/types/key/export.d.ts @@ -0,0 +1,21 @@ +import type { JWK, KeyLike } from '../types'; +/** + * Exports a runtime-specific public key representation (KeyObject or CryptoKey) to a PEM-encoded + * SPKI string format. + * + * @param key Key representation to transform to a PEM-encoded SPKI string format. + */ +export declare function exportSPKI(key: KeyLike): Promise; +/** + * Exports a runtime-specific private key representation (KeyObject or CryptoKey) to a PEM-encoded + * PKCS8 string format. + * + * @param key Key representation to transform to a PEM-encoded PKCS8 string format. + */ +export declare function exportPKCS8(key: KeyLike): Promise; +/** + * Exports a runtime-specific key representation (KeyLike) to a JWK. + * + * @param key Key representation to export as JWK. + */ +export declare function exportJWK(key: KeyLike | Uint8Array): Promise; diff --git a/node_modules/jose/dist/types/key/generate_key_pair.d.ts b/node_modules/jose/dist/types/key/generate_key_pair.d.ts new file mode 100644 index 0000000..73849ce --- /dev/null +++ b/node_modules/jose/dist/types/key/generate_key_pair.d.ts @@ -0,0 +1,36 @@ +import type { KeyLike } from '../types'; +export interface GenerateKeyPairResult { + /** The generated Private Key. */ + privateKey: T; + /** Public Key corresponding to the generated Private Key. */ + publicKey: T; +} +export interface GenerateKeyPairOptions { + /** + * The EC "crv" (Curve) or OKP "crv" (Subtype of Key Pair) value to generate. The curve must be + * both supported on the runtime as well as applicable for the given JWA algorithm identifier. + */ + crv?: string; + /** + * A hint for RSA algorithms to generate an RSA key of a given `modulusLength` (Key size in bits). + * JOSE requires 2048 bits or larger. Default is 2048. + */ + modulusLength?: number; + /** + * (Only effective in Web Crypto API runtimes) The value to use as + * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey SubtleCrypto.generateKey()} + * `extractable` argument. Default is false. + */ + extractable?: boolean; +} +/** + * Generates a private and a public key for a given JWA algorithm identifier. This can only generate + * asymmetric key pairs. For symmetric secrets use the `generateSecret` function. + * + * Note: Under Web Crypto API runtime the `privateKey` is generated with `extractable` set to + * `false` by default. + * + * @param alg JWA Algorithm Identifier to be used with the generated key pair. + * @param options Additional options passed down to the key pair generation. + */ +export declare function generateKeyPair(alg: string, options?: GenerateKeyPairOptions): Promise>; diff --git a/node_modules/jose/dist/types/key/generate_secret.d.ts b/node_modules/jose/dist/types/key/generate_secret.d.ts new file mode 100644 index 0000000..fc498b9 --- /dev/null +++ b/node_modules/jose/dist/types/key/generate_secret.d.ts @@ -0,0 +1,19 @@ +import type { KeyLike } from '../types'; +export interface GenerateSecretOptions { + /** + * (Only effective in Web Crypto API runtimes) The value to use as + * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey SubtleCrypto.generateKey()} + * `extractable` argument. Default is false. + */ + extractable?: boolean; +} +/** + * Generates a symmetric secret key for a given JWA algorithm identifier. + * + * Note: Under Web Crypto API runtime the secret key is generated with `extractable` set to `false` + * by default. + * + * @param alg JWA Algorithm Identifier to be used with the generated secret. + * @param options Additional options passed down to the secret generation. + */ +export declare function generateSecret(alg: string, options?: GenerateSecretOptions): Promise; diff --git a/node_modules/jose/dist/types/key/import.d.ts b/node_modules/jose/dist/types/key/import.d.ts new file mode 100644 index 0000000..02275f3 --- /dev/null +++ b/node_modules/jose/dist/types/key/import.d.ts @@ -0,0 +1,54 @@ +import type { JWK, KeyLike } from '../types'; +export interface PEMImportOptions { + /** + * (Only effective in Web Crypto API runtimes) The value to use as + * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey SubtleCrypto.importKey()} + * `extractable` argument. Default is false. + */ + extractable?: boolean; +} +/** + * Imports a PEM-encoded SPKI string as a runtime-specific public key representation (KeyObject or + * CryptoKey). + * + * @param pem PEM-encoded SPKI string + * @param alg (Only effective in Web Crypto API runtimes) JSON Web Algorithm identifier to be used + * with the imported key, its presence is only enforced in Web Crypto API runtimes. See + * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}. + */ +export declare function importSPKI(spki: string, alg: string, options?: PEMImportOptions): Promise; +/** + * Imports the SPKI from an X.509 string certificate as a runtime-specific public key representation + * (KeyObject or CryptoKey). + * + * @param pem X.509 certificate string + * @param alg (Only effective in Web Crypto API runtimes) JSON Web Algorithm identifier to be used + * with the imported key, its presence is only enforced in Web Crypto API runtimes. See + * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}. + */ +export declare function importX509(x509: string, alg: string, options?: PEMImportOptions): Promise; +/** + * Imports a PEM-encoded PKCS#8 string as a runtime-specific private key representation (KeyObject + * or CryptoKey). + * + * @param pem PEM-encoded PKCS#8 string + * @param alg (Only effective in Web Crypto API runtimes) JSON Web Algorithm identifier to be used + * with the imported key, its presence is only enforced in Web Crypto API runtimes. See + * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}. + */ +export declare function importPKCS8(pkcs8: string, alg: string, options?: PEMImportOptions): Promise; +/** + * Imports a JWK to a runtime-specific key representation (KeyLike). Either JWK "alg" (Algorithm) + * Parameter must be present or the optional "alg" argument. When running on a runtime using + * {@link https://www.w3.org/TR/WebCryptoAPI/ Web Cryptography API} the jwk parameters "use", + * "key_ops", and "ext" are also used in the resulting `CryptoKey`. + * + * @param jwk JSON Web Key. + * @param alg (Only effective in Web Crypto API runtimes) JSON Web Algorithm identifier to be used + * with the imported key. Default is the "alg" property on the JWK, its presence is only enforced + * in Web Crypto API runtimes. See + * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}. + * @param octAsKeyObject Forces a symmetric key to be imported to a KeyObject or CryptoKey. Default + * is true unless JWK "ext" (Extractable) is true. + */ +export declare function importJWK(jwk: JWK, alg?: string, octAsKeyObject?: boolean): Promise; diff --git a/node_modules/jose/dist/types/types.d.ts b/node_modules/jose/dist/types/types.d.ts new file mode 100644 index 0000000..3c49f54 --- /dev/null +++ b/node_modules/jose/dist/types/types.d.ts @@ -0,0 +1,610 @@ +/** + * KeyLike are runtime-specific classes representing asymmetric keys or symmetric secrets. These are + * instances of {@link https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey CryptoKey} and + * additionally {@link https://nodejs.org/api/crypto.html#class-keyobject KeyObject} in Node.js + * runtime. + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array Uint8Array} + * instances are also accepted as symmetric secret representation only. + * + * [Key Import Functions](../modules/key_import.md) can be used to import PEM, or JWK formatted + * asymmetric keys and certificates to these runtime-specific representations. + * + * In Node.js the {@link https://nodejs.org/api/buffer.html#buffer Buffer} class is a subclass of + * Uint8Array and so Buffer can be provided for symmetric secrets as well. + * + * {@link https://nodejs.org/api/crypto.html#class-keyobject KeyObject} is a representation of a + * key/secret available in the Node.js runtime. In addition to the import functions of this library + * you may use the runtime APIs + * {@link https://nodejs.org/api/crypto.html#cryptocreatepublickeykey crypto.createPublicKey}, + * {@link https://nodejs.org/api/crypto.html#cryptocreateprivatekeykey crypto.createPrivateKey}, and + * {@link https://nodejs.org/api/crypto.html#cryptocreatesecretkeykey-encoding crypto.createSecretKey} + * to obtain a `KeyObject` from your existing key material. + * + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey CryptoKey} is a representation + * of a key/secret available in the Browser and Web-interoperable runtimes. In addition to the + * import functions of this library you may use the + * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey SubtleCrypto.importKey} + * API to obtain a CryptoKey from your existing key material. + * + */ +export type KeyLike = { type: string } + +/** + * JSON Web Key ({@link https://www.rfc-editor.org/rfc/rfc7517 JWK}). "RSA", "EC", "OKP", and "oct" + * key types are supported. + */ +export interface JWK { + /** JWK "alg" (Algorithm) Parameter. */ + alg?: string + crv?: string + d?: string + dp?: string + dq?: string + e?: string + /** JWK "ext" (Extractable) Parameter. */ + ext?: boolean + k?: string + /** JWK "key_ops" (Key Operations) Parameter. */ + key_ops?: string[] + /** JWK "kid" (Key ID) Parameter. */ + kid?: string + /** JWK "kty" (Key Type) Parameter. */ + kty?: string + n?: string + oth?: Array<{ + d?: string + r?: string + t?: string + }> + p?: string + q?: string + qi?: string + /** JWK "use" (Public Key Use) Parameter. */ + use?: string + x?: string + y?: string + /** JWK "x5c" (X.509 Certificate Chain) Parameter. */ + x5c?: string[] + /** JWK "x5t" (X.509 Certificate SHA-1 Thumbprint) Parameter. */ + x5t?: string + /** "x5t#S256" (X.509 Certificate SHA-256 Thumbprint) Parameter. */ + 'x5t#S256'?: string + /** JWK "x5u" (X.509 URL) Parameter. */ + x5u?: string + + [propName: string]: unknown +} + +/** + * Generic Interface for consuming operations dynamic key resolution. + * + * @param IProtectedHeader Type definition of the JWE or JWS Protected Header. + * @param IToken Type definition of the consumed JWE or JWS token. + */ +export interface GetKeyFunction { + /** + * Dynamic key resolution function. No token components have been verified at the time of this + * function call. + * + * If you cannot match a key suitable for the token, throw an error instead. + * + * @param protectedHeader JWE or JWS Protected Header. + * @param token The consumed JWE or JWS token. + */ + ( + protectedHeader: IProtectedHeader, + token: IToken, + ): Promise | KeyLike | Uint8Array +} + +/** + * Flattened JWS definition for verify function inputs, allows payload as Uint8Array for detached + * signature validation. + */ +export interface FlattenedJWSInput { + /** + * The "header" member MUST be present and contain the value JWS Unprotected Header when the JWS + * Unprotected Header value is non- empty; otherwise, it MUST be absent. This value is represented + * as an unencoded JSON object, rather than as a string. These Header Parameter values are not + * integrity protected. + */ + header?: JWSHeaderParameters + + /** + * The "payload" member MUST be present and contain the value BASE64URL(JWS Payload). When RFC7797 + * "b64": false is used the value passed may also be a Uint8Array. + */ + payload: string | Uint8Array + + /** + * The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWS Protected + * Header)) when the JWS Protected Header value is non-empty; otherwise, it MUST be absent. These + * Header Parameter values are integrity protected. + */ + protected?: string + + /** The "signature" member MUST be present and contain the value BASE64URL(JWS Signature). */ + signature: string +} + +/** + * General JWS definition for verify function inputs, allows payload as Uint8Array for detached + * signature validation. + */ +export interface GeneralJWSInput { + /** + * The "payload" member MUST be present and contain the value BASE64URL(JWS Payload). When when + * JWS Unencoded Payload ({@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}) "b64": false is + * used the value passed may also be a Uint8Array. + */ + payload: string | Uint8Array + + /** + * The "signatures" member value MUST be an array of JSON objects. Each object represents a + * signature or MAC over the JWS Payload and the JWS Protected Header. + */ + signatures: Omit[] +} + +/** + * Flattened JWS definition. Payload is returned as an empty string when JWS Unencoded Payload + * ({@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}) is used. + */ +export interface FlattenedJWS extends Partial { + payload: string + signature: string +} + +/** + * General JWS definition. Payload is returned as an empty string when JWS Unencoded Payload + * ({@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}) is used. + */ +export interface GeneralJWS { + payload: string + signatures: Omit[] +} + +export interface JoseHeaderParameters { + /** "kid" (Key ID) Header Parameter. */ + kid?: string + + /** "x5t" (X.509 Certificate SHA-1 Thumbprint) Header Parameter. */ + x5t?: string + + /** "x5c" (X.509 Certificate Chain) Header Parameter. */ + x5c?: string[] + + /** "x5u" (X.509 URL) Header Parameter. */ + x5u?: string + + /** "jku" (JWK Set URL) Header Parameter. */ + jku?: string + + /** "jwk" (JSON Web Key) Header Parameter. */ + jwk?: Pick + + /** "typ" (Type) Header Parameter. */ + typ?: string + + /** "cty" (Content Type) Header Parameter. */ + cty?: string +} + +/** Recognized JWS Header Parameters, any other Header Members may also be present. */ +export interface JWSHeaderParameters extends JoseHeaderParameters { + /** JWS "alg" (Algorithm) Header Parameter. */ + alg?: string + + /** + * This JWS Extension Header Parameter modifies the JWS Payload representation and the JWS Signing + * Input computation as per {@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}. + */ + b64?: boolean + + /** JWS "crit" (Critical) Header Parameter. */ + crit?: string[] + + /** Any other JWS Header member. */ + [propName: string]: unknown +} + +/** Recognized JWE Key Management-related Header Parameters. */ +export interface JWEKeyManagementHeaderParameters { + apu?: Uint8Array + apv?: Uint8Array + /** + * @deprecated You should not use this parameter. It is only really intended for test and vector + * validation purposes. + */ + p2c?: number + /** + * @deprecated You should not use this parameter. It is only really intended for test and vector + * validation purposes. + */ + p2s?: Uint8Array + /** + * @deprecated You should not use this parameter. It is only really intended for test and vector + * validation purposes. + */ + iv?: Uint8Array + /** + * @deprecated You should not use this parameter. It is only really intended for test and vector + * validation purposes. + */ + epk?: KeyLike +} + +/** Flattened JWE definition. */ +export interface FlattenedJWE { + /** + * The "aad" member MUST be present and contain the value BASE64URL(JWE AAD)) when the JWE AAD + * value is non-empty; otherwise, it MUST be absent. A JWE AAD value can be included to supply a + * base64url-encoded value to be integrity protected but not encrypted. + */ + aad?: string + + /** The "ciphertext" member MUST be present and contain the value BASE64URL(JWE Ciphertext). */ + ciphertext: string + + /** + * The "encrypted_key" member MUST be present and contain the value BASE64URL(JWE Encrypted Key) + * when the JWE Encrypted Key value is non-empty; otherwise, it MUST be absent. + */ + encrypted_key?: string + + /** + * The "header" member MUST be present and contain the value JWE Per- Recipient Unprotected Header + * when the JWE Per-Recipient Unprotected Header value is non-empty; otherwise, it MUST be absent. + * This value is represented as an unencoded JSON object, rather than as a string. These Header + * Parameter values are not integrity protected. + */ + header?: JWEHeaderParameters + + /** + * The "iv" member MUST be present and contain the value BASE64URL(JWE Initialization Vector) when + * the JWE Initialization Vector value is non-empty; otherwise, it MUST be absent. + */ + iv: string + + /** + * The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWE Protected + * Header)) when the JWE Protected Header value is non-empty; otherwise, it MUST be absent. These + * Header Parameter values are integrity protected. + */ + protected?: string + + /** + * The "tag" member MUST be present and contain the value BASE64URL(JWE Authentication Tag) when + * the JWE Authentication Tag value is non-empty; otherwise, it MUST be absent. + */ + tag: string + + /** + * The "unprotected" member MUST be present and contain the value JWE Shared Unprotected Header + * when the JWE Shared Unprotected Header value is non-empty; otherwise, it MUST be absent. This + * value is represented as an unencoded JSON object, rather than as a string. These Header + * Parameter values are not integrity protected. + */ + unprotected?: JWEHeaderParameters +} + +export interface GeneralJWE extends Omit { + recipients: Pick[] +} + +/** Recognized JWE Header Parameters, any other Header members may also be present. */ +export interface JWEHeaderParameters extends JoseHeaderParameters { + /** JWE "alg" (Algorithm) Header Parameter. */ + alg?: string + + /** JWE "enc" (Encryption Algorithm) Header Parameter. */ + enc?: string + + /** JWE "crit" (Critical) Header Parameter. */ + crit?: string[] + + /** + * JWE "zip" (Compression Algorithm) Header Parameter. + * + * @deprecated Compression of data SHOULD NOT be done before encryption, because such compressed + * data often reveals information about the plaintext. + * + * @see {@link https://www.rfc-editor.org/rfc/rfc8725#name-avoid-compression-of-encryp Avoid Compression of Encryption Inputs} + */ + zip?: string + + /** Any other JWE Header member. */ + [propName: string]: unknown +} + +/** Shared Interface with a "crit" property for all sign, verify, encrypt and decrypt operations. */ +export interface CritOption { + /** + * An object with keys representing recognized "crit" (Critical) Header Parameter names. The value + * for those is either `true` or `false`. `true` when the Header Parameter MUST be integrity + * protected, `false` when it's irrelevant. + * + * This makes the "Extension Header Parameter "..." is not recognized" error go away. + * + * Use this when a given JWS/JWT/JWE profile requires the use of proprietary non-registered "crit" + * (Critical) Header Parameters. This will only make sure the Header Parameter is syntactically + * correct when provided and that it is optionally integrity protected. It will not process the + * Header Parameter in any way or reject the operation if it is missing. You MUST still verify the + * Header Parameter was present and process it according to the profile's validation steps after + * the operation succeeds. + * + * The JWS extension Header Parameter `b64` is always recognized and processed properly. No other + * registered Header Parameters that need this kind of default built-in treatment are currently + * available. + */ + crit?: { + [propName: string]: boolean + } +} + +/** JWE Decryption options. */ +export interface DecryptOptions extends CritOption { + /** A list of accepted JWE "alg" (Algorithm) Header Parameter values. */ + keyManagementAlgorithms?: string[] + + /** + * A list of accepted JWE "enc" (Encryption Algorithm) Header Parameter values. By default all + * "enc" (Encryption Algorithm) values applicable for the used key/secret are allowed. + */ + contentEncryptionAlgorithms?: string[] + + /** + * In a browser runtime you have to provide an implementation for Inflate Raw when you expect JWEs + * with compressed plaintext. + */ + inflateRaw?: InflateFunction + + /** + * (PBES2 Key Management Algorithms only) Maximum allowed "p2c" (PBES2 Count) Header Parameter + * value. The PBKDF2 iteration count defines the algorithm's computational expense. By default + * this value is set to 10000. + */ + maxPBES2Count?: number +} + +/** JWE Deflate option. */ +export interface DeflateOption { + /** + * In a browser runtime you have to provide an implementation for Deflate Raw when you will be + * producing JWEs with compressed plaintext. + */ + deflateRaw?: DeflateFunction +} + +/** JWE Encryption options. */ +export interface EncryptOptions extends CritOption, DeflateOption {} + +/** JWT Claims Set verification options. */ +export interface JWTClaimVerificationOptions { + /** Expected JWT "aud" (Audience) Claim value(s). */ + audience?: string | string[] + + /** + * Expected clock tolerance + * + * - In seconds when number (e.g. 5) + * - Parsed as seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours"). + */ + clockTolerance?: string | number + + /** Expected JWT "iss" (Issuer) Claim value(s). */ + issuer?: string | string[] + + /** + * Maximum time elapsed (in seconds) from the JWT "iat" (Issued At) Claim value. + * + * - In seconds when number (e.g. 5) + * - Parsed as seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours"). + */ + maxTokenAge?: string | number + + /** Expected JWT "sub" (Subject) Claim value. */ + subject?: string + + /** Expected JWT "typ" (Type) Header Parameter value. */ + typ?: string + + /** Date to use when comparing NumericDate claims, defaults to `new Date()`. */ + currentDate?: Date + + /** + * Array of required Claim Names that must be present in the JWT Claims Set. Default is that: if + * the {@link JWTClaimVerificationOptions.issuer issuer option} is set, then "iss" must be present; + * if the {@link JWTClaimVerificationOptions.audience audience option} is set, then "aud" must be + * present; if the {@link JWTClaimVerificationOptions.subject subject option} is set, then "sub" + * must be present; if the {@link JWTClaimVerificationOptions.maxTokenAge maxTokenAge option} is + * set, then "iat" must be present. + */ + requiredClaims?: string[] +} + +/** JWS Verification options. */ +export interface VerifyOptions extends CritOption { + /** + * A list of accepted JWS "alg" (Algorithm) Header Parameter values. By default all "alg" + * (Algorithm) values applicable for the used key/secret are allowed. Note: "none" is never + * accepted. + */ + algorithms?: string[] +} + +/** JWS Signing options. */ +export interface SignOptions extends CritOption {} + +/** Recognized JWT Claims Set members, any other members may also be present. */ +export interface JWTPayload { + /** + * JWT Issuer + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.1 RFC7519#section-4.1.1} + */ + iss?: string + + /** + * JWT Subject + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.2 RFC7519#section-4.1.2} + */ + sub?: string + + /** + * JWT Audience + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.3 RFC7519#section-4.1.3} + */ + aud?: string | string[] + + /** + * JWT ID + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7 RFC7519#section-4.1.7} + */ + jti?: string + + /** + * JWT Not Before + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.5 RFC7519#section-4.1.5} + */ + nbf?: number + + /** + * JWT Expiration Time + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4 RFC7519#section-4.1.4} + */ + exp?: number + + /** + * JWT Issued At + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 RFC7519#section-4.1.6} + */ + iat?: number + + /** Any other JWT Claim Set member. */ + [propName: string]: unknown +} + +/** + * Deflate Raw implementation, e.g. promisified + * {@link https://nodejs.org/api/zlib.html#zlibdeflaterawbuffer-options-callback zlib.deflateRaw}. + * + * @deprecated Compression of data SHOULD NOT be done before encryption, because such compressed + * data often reveals information about the plaintext. + * + * @see {@link https://www.rfc-editor.org/rfc/rfc8725#name-avoid-compression-of-encryp Avoid Compression of Encryption Inputs} + */ +export interface DeflateFunction { + (input: Uint8Array): Promise +} + +/** + * Inflate Raw implementation, e.g. promisified + * {@link https://nodejs.org/api/zlib.html#zlibinflaterawbuffer-options-callback zlib.inflateRaw}. + * + * @deprecated Compression of data SHOULD NOT be done before encryption, because such compressed + * data often reveals information about the plaintext. + * + * @see {@link https://www.rfc-editor.org/rfc/rfc8725#name-avoid-compression-of-encryp Avoid Compression of Encryption Inputs} + */ +export interface InflateFunction { + (input: Uint8Array): Promise +} + +export interface FlattenedDecryptResult { + /** JWE AAD. */ + additionalAuthenticatedData?: Uint8Array + + /** Plaintext. */ + plaintext: Uint8Array + + /** JWE Protected Header. */ + protectedHeader?: JWEHeaderParameters + + /** JWE Shared Unprotected Header. */ + sharedUnprotectedHeader?: JWEHeaderParameters + + /** JWE Per-Recipient Unprotected Header. */ + unprotectedHeader?: JWEHeaderParameters +} + +export interface GeneralDecryptResult extends FlattenedDecryptResult {} + +export interface CompactDecryptResult { + /** Plaintext. */ + plaintext: Uint8Array + + /** JWE Protected Header. */ + protectedHeader: CompactJWEHeaderParameters +} + +export interface FlattenedVerifyResult { + /** JWS Payload. */ + payload: Uint8Array + + /** JWS Protected Header. */ + protectedHeader?: JWSHeaderParameters + + /** JWS Unprotected Header. */ + unprotectedHeader?: JWSHeaderParameters +} + +export interface GeneralVerifyResult extends FlattenedVerifyResult {} + +export interface CompactVerifyResult { + /** JWS Payload. */ + payload: Uint8Array + + /** JWS Protected Header. */ + protectedHeader: CompactJWSHeaderParameters +} + +export interface JWTVerifyResult { + /** JWT Claims Set. */ + payload: JWTPayload + + /** JWS Protected Header. */ + protectedHeader: JWTHeaderParameters +} + +export interface JWTDecryptResult { + /** JWT Claims Set. */ + payload: JWTPayload + + /** JWE Protected Header. */ + protectedHeader: CompactJWEHeaderParameters +} + +export interface ResolvedKey { + /** Key resolved from the key resolver function. */ + key: T | Uint8Array +} + +/** Recognized Compact JWS Header Parameters, any other Header Members may also be present. */ +export interface CompactJWSHeaderParameters extends JWSHeaderParameters { + alg: string +} + +/** Recognized Signed JWT Header Parameters, any other Header Members may also be present. */ +export interface JWTHeaderParameters extends CompactJWSHeaderParameters { + b64?: true +} + +/** Recognized Compact JWE Header Parameters, any other Header Members may also be present. */ +export interface CompactJWEHeaderParameters extends JWEHeaderParameters { + alg: string + enc: string +} + +/** JSON Web Key Set */ +export interface JSONWebKeySet { + keys: JWK[] +} + +export type CryptoRuntime = 'WebCryptoAPI' | 'node:crypto' diff --git a/node_modules/jose/dist/types/util/base64url.d.ts b/node_modules/jose/dist/types/util/base64url.d.ts new file mode 100644 index 0000000..ec08361 --- /dev/null +++ b/node_modules/jose/dist/types/util/base64url.d.ts @@ -0,0 +1,19 @@ +/** + * Utility function to encode a string or Uint8Array as a base64url string. + * + * @param input Value that will be base64url-encoded. + */ +interface Base64UrlEncode { + (input: Uint8Array | string): string; +} +/** + * Utility function to decode a base64url encoded string. + * + * @param input Value that will be base64url-decoded. + */ +interface Base64UrlDecode { + (input: Uint8Array | string): Uint8Array; +} +export declare const encode: Base64UrlEncode; +export declare const decode: Base64UrlDecode; +export {}; diff --git a/node_modules/jose/dist/types/util/decode_jwt.d.ts b/node_modules/jose/dist/types/util/decode_jwt.d.ts new file mode 100644 index 0000000..7ed6327 --- /dev/null +++ b/node_modules/jose/dist/types/util/decode_jwt.d.ts @@ -0,0 +1,10 @@ +import type { JWTPayload } from '../types'; +/** + * Decodes a signed JSON Web Token payload. This does not validate the JWT Claims Set types or + * values. This does not validate the JWS Signature. For a proper Signed JWT Claims Set validation + * and JWS signature verification use `jose.jwtVerify()`. For an encrypted JWT Claims Set validation + * and JWE decryption use `jose.jwtDecrypt()`. + * + * @param jwt JWT token in compact JWS serialization. + */ +export declare function decodeJwt(jwt: string): JWTPayload; diff --git a/node_modules/jose/dist/types/util/decode_protected_header.d.ts b/node_modules/jose/dist/types/util/decode_protected_header.d.ts new file mode 100644 index 0000000..b29c4d7 --- /dev/null +++ b/node_modules/jose/dist/types/util/decode_protected_header.d.ts @@ -0,0 +1,8 @@ +import type { JWSHeaderParameters, JWEHeaderParameters } from '../types'; +export type ProtectedHeaderParameters = JWSHeaderParameters & JWEHeaderParameters; +/** + * Decodes the Protected Header of a JWE/JWS/JWT token utilizing any JOSE serialization. + * + * @param token JWE/JWS/JWT token in any JOSE serialization. + */ +export declare function decodeProtectedHeader(token: string | object): ProtectedHeaderParameters; diff --git a/node_modules/jose/dist/types/util/errors.d.ts b/node_modules/jose/dist/types/util/errors.d.ts new file mode 100644 index 0000000..6c71968 --- /dev/null +++ b/node_modules/jose/dist/types/util/errors.d.ts @@ -0,0 +1,151 @@ +import type { KeyLike } from '../types'; +/** + * A generic Error that all other JOSE specific Error subclasses extend. + * + */ +export declare class JOSEError extends Error { + /** A unique error code for the particular error subclass. */ + static get code(): string; + /** A unique error code for the particular error subclass. */ + code: string; + constructor(message?: string); +} +/** + * An error subclass thrown when a JWT Claim Set member validation fails. + * + */ +export declare class JWTClaimValidationFailed extends JOSEError { + static get code(): 'ERR_JWT_CLAIM_VALIDATION_FAILED'; + code: string; + /** The Claim for which the validation failed. */ + claim: string; + /** Reason code for the validation failure. */ + reason: string; + constructor(message: string, claim?: string, reason?: string); +} +/** + * An error subclass thrown when a JWT is expired. + * + */ +export declare class JWTExpired extends JOSEError implements JWTClaimValidationFailed { + static get code(): 'ERR_JWT_EXPIRED'; + code: string; + /** The Claim for which the validation failed. */ + claim: string; + /** Reason code for the validation failure. */ + reason: string; + constructor(message: string, claim?: string, reason?: string); +} +/** + * An error subclass thrown when a JOSE Algorithm is not allowed per developer preference. + * + */ +export declare class JOSEAlgNotAllowed extends JOSEError { + static get code(): 'ERR_JOSE_ALG_NOT_ALLOWED'; + code: string; +} +/** + * An error subclass thrown when a particular feature or algorithm is not supported by this + * implementation or JOSE in general. + * + */ +export declare class JOSENotSupported extends JOSEError { + static get code(): 'ERR_JOSE_NOT_SUPPORTED'; + code: string; +} +/** + * An error subclass thrown when a JWE ciphertext decryption fails. + * + */ +export declare class JWEDecryptionFailed extends JOSEError { + static get code(): 'ERR_JWE_DECRYPTION_FAILED'; + code: string; + message: string; +} +/** + * An error subclass thrown when a JWE ciphertext decompression fails. + * + */ +export declare class JWEDecompressionFailed extends JOSEError { + static get code(): 'ERR_JWE_DECOMPRESSION_FAILED'; + code: string; + message: string; +} +/** + * An error subclass thrown when a JWE is invalid. + * + */ +export declare class JWEInvalid extends JOSEError { + static get code(): 'ERR_JWE_INVALID'; + code: string; +} +/** + * An error subclass thrown when a JWS is invalid. + * + */ +export declare class JWSInvalid extends JOSEError { + static get code(): 'ERR_JWS_INVALID'; + code: string; +} +/** + * An error subclass thrown when a JWT is invalid. + * + */ +export declare class JWTInvalid extends JOSEError { + static get code(): 'ERR_JWT_INVALID'; + code: string; +} +/** + * An error subclass thrown when a JWK is invalid. + * + */ +export declare class JWKInvalid extends JOSEError { + static get code(): 'ERR_JWK_INVALID'; + code: string; +} +/** + * An error subclass thrown when a JWKS is invalid. + * + */ +export declare class JWKSInvalid extends JOSEError { + static get code(): 'ERR_JWKS_INVALID'; + code: string; +} +/** + * An error subclass thrown when no keys match from a JWKS. + * + */ +export declare class JWKSNoMatchingKey extends JOSEError { + static get code(): 'ERR_JWKS_NO_MATCHING_KEY'; + code: string; + message: string; +} +/** + * An error subclass thrown when multiple keys match from a JWKS. + * + */ +export declare class JWKSMultipleMatchingKeys extends JOSEError { + /** @ignore */ + [Symbol.asyncIterator]: () => AsyncIterableIterator; + static get code(): 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; + code: string; + message: string; +} +/** + * Timeout was reached when retrieving the JWKS response. + * + */ +export declare class JWKSTimeout extends JOSEError { + static get code(): 'ERR_JWKS_TIMEOUT'; + code: string; + message: string; +} +/** + * An error subclass thrown when JWS signature verification fails. + * + */ +export declare class JWSSignatureVerificationFailed extends JOSEError { + static get code(): 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; + code: string; + message: string; +} diff --git a/node_modules/jose/dist/types/util/runtime.d.ts b/node_modules/jose/dist/types/util/runtime.d.ts new file mode 100644 index 0000000..f8b9f66 --- /dev/null +++ b/node_modules/jose/dist/types/util/runtime.d.ts @@ -0,0 +1,3 @@ +import type { CryptoRuntime } from '../types'; +declare const _default: CryptoRuntime; +export default _default; diff --git a/node_modules/jose/package.json b/node_modules/jose/package.json new file mode 100644 index 0000000..14c7687 --- /dev/null +++ b/node_modules/jose/package.json @@ -0,0 +1,90 @@ +{ + "name": "jose", + "version": "4.15.9", + "description": "'JSON Web Almost Everything' - JWA, JWS, JWE, JWT, JWK, JWKS for Node.js, Browser, Cloudflare Workers, Deno, Bun, and other Web-interoperable runtimes", + "keywords": [ + "browser", + "bun", + "cloudflare", + "compact", + "decode", + "decrypt", + "deno", + "detached", + "ec", + "ecdsa", + "eddsa", + "edge", + "electron", + "embedded", + "encrypt", + "flattened", + "general", + "jose", + "json web token", + "jsonwebtoken", + "jwa", + "jwe", + "jwk", + "jwks", + "jws", + "jwt", + "netlify", + "next", + "nextjs", + "oct", + "okp", + "payload", + "pem", + "pkcs8", + "rsa", + "secp256k1", + "sign", + "signature", + "spki", + "validate", + "vercel", + "verify", + "webcrypto", + "workerd", + "workers", + "x509" + ], + "homepage": "https://github.com/panva/jose", + "repository": "panva/jose", + "funding": { + "url": "https://github.com/sponsors/panva" + }, + "license": "MIT", + "author": "Filip Skokan ", + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/types/index.d.ts", + "bun": "./dist/browser/index.js", + "deno": "./dist/browser/index.js", + "browser": "./dist/browser/index.js", + "worker": "./dist/browser/index.js", + "workerd": "./dist/browser/index.js", + "import": "./dist/node/esm/index.js", + "require": "./dist/node/cjs/index.js" + }, + "./package.json": "./package.json" + }, + "main": "./dist/node/cjs/index.js", + "browser": "./dist/browser/index.js", + "types": "./dist/types/index.d.ts", + "files": [ + "dist/**/package.json", + "dist/**/*.js", + "dist/types/**/*.d.ts", + "!dist/**/*.bundle.js", + "!dist/**/*.umd.js", + "!dist/**/*.min.js", + "!dist/node/webcrypto/**/*", + "!dist/types/runtime/*", + "!dist/types/lib/*", + "!dist/deno/**/*" + ], + "deno": "./dist/browser/index.js" +} diff --git a/node_modules/json-bigint/LICENSE b/node_modules/json-bigint/LICENSE new file mode 100644 index 0000000..9ab4d83 --- /dev/null +++ b/node_modules/json-bigint/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013 Andrey Sidorov + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/json-bigint/README.md b/node_modules/json-bigint/README.md new file mode 100644 index 0000000..e7335c7 --- /dev/null +++ b/node_modules/json-bigint/README.md @@ -0,0 +1,240 @@ +# json-bigint + +[![Build Status](https://secure.travis-ci.org/sidorares/json-bigint.png)](http://travis-ci.org/sidorares/json-bigint) +[![NPM](https://nodei.co/npm/json-bigint.png?downloads=true&stars=true)](https://nodei.co/npm/json-bigint/) + +JSON.parse/stringify with bigints support. Based on Douglas Crockford [JSON.js](https://github.com/douglascrockford/JSON-js) package and [bignumber.js](https://github.com/MikeMcl/bignumber.js) library. + +Native `Bigint` was added to JS recently, so we added an option to leverage it instead of `bignumber.js`. However, the parsing with native `BigInt` is kept an option for backward compability. + +While most JSON parsers assume numeric values have same precision restrictions as IEEE 754 double, JSON specification _does not_ say anything about number precision. Any floating point number in decimal (optionally scientific) notation is valid JSON value. It's a good idea to serialize values which might fall out of IEEE 754 integer precision as strings in your JSON api, but `{ "value" : 9223372036854775807}`, for example, is still a valid RFC4627 JSON string, and in most JS runtimes the result of `JSON.parse` is this object: `{ value: 9223372036854776000 }` + +========== + +example: + +```js +var JSONbig = require('json-bigint'); + +var json = '{ "value" : 9223372036854775807, "v2": 123 }'; +console.log('Input:', json); +console.log(''); + +console.log('node.js built-in JSON:'); +var r = JSON.parse(json); +console.log('JSON.parse(input).value : ', r.value.toString()); +console.log('JSON.stringify(JSON.parse(input)):', JSON.stringify(r)); + +console.log('\n\nbig number JSON:'); +var r1 = JSONbig.parse(json); +console.log('JSONbig.parse(input).value : ', r1.value.toString()); +console.log('JSONbig.stringify(JSONbig.parse(input)):', JSONbig.stringify(r1)); +``` + +Output: + +``` +Input: { "value" : 9223372036854775807, "v2": 123 } + +node.js built-in JSON: +JSON.parse(input).value : 9223372036854776000 +JSON.stringify(JSON.parse(input)): {"value":9223372036854776000,"v2":123} + + +big number JSON: +JSONbig.parse(input).value : 9223372036854775807 +JSONbig.stringify(JSONbig.parse(input)): {"value":9223372036854775807,"v2":123} +``` + +### Options + +The behaviour of the parser is somewhat configurable through 'options' + +#### options.strict, boolean, default false + +Specifies the parsing should be "strict" towards reporting duplicate-keys in the parsed string. +The default follows what is allowed in standard json and resembles the behavior of JSON.parse, but overwrites any previous values with the last one assigned to the duplicate-key. + +Setting options.strict = true will fail-fast on such duplicate-key occurances and thus warn you upfront of possible lost information. + +example: + +```js +var JSONbig = require('json-bigint'); +var JSONstrict = require('json-bigint')({ strict: true }); + +var dupkeys = '{ "dupkey": "value 1", "dupkey": "value 2"}'; +console.log('\n\nDuplicate Key test with both lenient and strict JSON parsing'); +console.log('Input:', dupkeys); +var works = JSONbig.parse(dupkeys); +console.log('JSON.parse(dupkeys).dupkey: %s', works.dupkey); +var fails = 'will stay like this'; +try { + fails = JSONstrict.parse(dupkeys); + console.log('ERROR!! Should never get here'); +} catch (e) { + console.log( + 'Succesfully catched expected exception on duplicate keys: %j', + e + ); +} +``` + +Output + +``` +Duplicate Key test with big number JSON +Input: { "dupkey": "value 1", "dupkey": "value 2"} +JSON.parse(dupkeys).dupkey: value 2 +Succesfully catched expected exception on duplicate keys: {"name":"SyntaxError","message":"Duplicate key \"dupkey\"","at":33,"text":"{ \"dupkey\": \"value 1\", \"dupkey\": \"value 2\"}"} + +``` + +#### options.storeAsString, boolean, default false + +Specifies if BigInts should be stored in the object as a string, rather than the default BigNumber. + +Note that this is a dangerous behavior as it breaks the default functionality of being able to convert back-and-forth without data type changes (as this will convert all BigInts to be-and-stay strings). + +example: + +```js +var JSONbig = require('json-bigint'); +var JSONbigString = require('json-bigint')({ storeAsString: true }); +var key = '{ "key": 1234567890123456789 }'; +console.log('\n\nStoring the BigInt as a string, instead of a BigNumber'); +console.log('Input:', key); +var withInt = JSONbig.parse(key); +var withString = JSONbigString.parse(key); +console.log( + 'Default type: %s, With option type: %s', + typeof withInt.key, + typeof withString.key +); +``` + +Output + +``` +Storing the BigInt as a string, instead of a BigNumber +Input: { "key": 1234567890123456789 } +Default type: object, With option type: string + +``` + +#### options.useNativeBigInt, boolean, default false + +Specifies if parser uses native BigInt instead of bignumber.js + +example: + +```js +var JSONbig = require('json-bigint'); +var JSONbigNative = require('json-bigint')({ useNativeBigInt: true }); +var key = '{ "key": 993143214321423154315154321 }'; +console.log(`\n\nStoring the Number as native BigInt, instead of a BigNumber`); +console.log('Input:', key); +var normal = JSONbig.parse(key); +var nativeBigInt = JSONbigNative.parse(key); +console.log( + 'Default type: %s, With option type: %s', + typeof normal.key, + typeof nativeBigInt.key +); +``` + +Output + +``` +Storing the Number as native BigInt, instead of a BigNumber +Input: { "key": 993143214321423154315154321 } +Default type: object, With option type: bigint + +``` + +#### options.alwaysParseAsBig, boolean, default false + +Specifies if all numbers should be stored as BigNumber. + +Note that this is a dangerous behavior as it breaks the default functionality of being able to convert back-and-forth without data type changes (as this will convert all Number to be-and-stay BigNumber) + +example: + +```js +var JSONbig = require('json-bigint'); +var JSONbigAlways = require('json-bigint')({ alwaysParseAsBig: true }); +var key = '{ "key": 123 }'; // there is no need for BigNumber by default, but we're forcing it +console.log(`\n\nStoring the Number as a BigNumber, instead of a Number`); +console.log('Input:', key); +var normal = JSONbig.parse(key); +var always = JSONbigAlways.parse(key); +console.log( + 'Default type: %s, With option type: %s', + typeof normal.key, + typeof always.key +); +``` + +Output + +``` +Storing the Number as a BigNumber, instead of a Number +Input: { "key": 123 } +Default type: number, With option type: object + +``` + +If you want to force all numbers to be parsed as native `BigInt` +(you probably do! Otherwise any calulations become a real headache): + +```js +var JSONbig = require('json-bigint')({ + alwaysParseAsBig: true, + useNativeBigInt: true, +}); +``` + +#### options.protoAction, boolean, default: "error". Possible values: "error", "ignore", "preserve" + +#### options.constructorAction, boolean, default: "error". Possible values: "error", "ignore", "preserve" + +Controls how `__proto__` and `constructor` properties are treated. If set to "error" they are not allowed and +parse() call will throw an error. If set to "ignore" the prroperty and it;s value is skipped from parsing and object building. +If set to "preserve" the `__proto__` property is set. One should be extra careful and make sure any other library consuming generated data +is not vulnerable to prototype poisoning attacks. + +example: + +```js +var JSONbigAlways = require('json-bigint')({ protoAction: 'ignore' }); +const user = JSONbig.parse('{ "__proto__": { "admin": true }, "id": 12345 }'); +// => result is { id: 12345 } +``` + +### Links: + +- [RFC4627: The application/json Media Type for JavaScript Object Notation (JSON)](http://www.ietf.org/rfc/rfc4627.txt) +- [Re: \[Json\] Limitations on number size?](http://www.ietf.org/mail-archive/web/json/current/msg00297.html) +- [Is there any proper way to parse JSON with large numbers? (long, bigint, int64)](http://stackoverflow.com/questions/18755125/node-js-is-there-any-proper-way-to-parse-json-with-large-numbers-long-bigint) +- [What is JavaScript's Max Int? What's the highest Integer value a Number can go to without losing precision?](http://stackoverflow.com/questions/307179/what-is-javascripts-max-int-whats-the-highest-integer-value-a-number-can-go-t) +- [Large numbers erroneously rounded in Javascript](http://stackoverflow.com/questions/1379934/large-numbers-erroneously-rounded-in-javascript) + +### Note on native BigInt support + +#### Stringifying + +Full support out-of-the-box, stringifies BigInts as pure numbers (no quotes, no `n`) + +#### Limitations + +- Roundtrip operations + +`s === JSONbig.stringify(JSONbig.parse(s))` but + +`o !== JSONbig.parse(JSONbig.stringify(o))` + +when `o` has a value with something like `123n`. + +`JSONbig` stringify `123n` as `123`, which becomes `number` (aka `123` not `123n`) by default when being reparsed. + +There is currently no consistent way to deal with this issue, so we decided to leave it, handling this specific case is then up to users. diff --git a/node_modules/json-bigint/index.js b/node_modules/json-bigint/index.js new file mode 100644 index 0000000..4757600 --- /dev/null +++ b/node_modules/json-bigint/index.js @@ -0,0 +1,12 @@ +var json_stringify = require('./lib/stringify.js').stringify; +var json_parse = require('./lib/parse.js'); + +module.exports = function(options) { + return { + parse: json_parse(options), + stringify: json_stringify + } +}; +//create the default method members with no options applied for backwards compatibility +module.exports.parse = json_parse(); +module.exports.stringify = json_stringify; diff --git a/node_modules/json-bigint/lib/parse.js b/node_modules/json-bigint/lib/parse.js new file mode 100644 index 0000000..bb4e5eb --- /dev/null +++ b/node_modules/json-bigint/lib/parse.js @@ -0,0 +1,443 @@ +var BigNumber = null; + +// regexpxs extracted from +// (c) BSD-3-Clause +// https://github.com/fastify/secure-json-parse/graphs/contributors and https://github.com/hapijs/bourne/graphs/contributors + +const suspectProtoRx = /(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/; +const suspectConstructorRx = /(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/; + +/* + json_parse.js + 2012-06-20 + + Public Domain. + + NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + + This file creates a json_parse function. + During create you can (optionally) specify some behavioural switches + + require('json-bigint')(options) + + The optional options parameter holds switches that drive certain + aspects of the parsing process: + * options.strict = true will warn about duplicate-key usage in the json. + The default (strict = false) will silently ignore those and overwrite + values for keys that are in duplicate use. + + The resulting function follows this signature: + json_parse(text, reviver) + This method parses a JSON text to produce an object or array. + It can throw a SyntaxError exception. + + The optional reviver parameter is a function that can filter and + transform the results. It receives each of the keys and values, + and its return value is used instead of the original value. + If it returns what it received, then the structure is not modified. + If it returns undefined then the member is deleted. + + Example: + + // Parse the text. Values that look like ISO date strings will + // be converted to Date objects. + + myData = json_parse(text, function (key, value) { + var a; + if (typeof value === 'string') { + a = +/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); + if (a) { + return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], + +a[5], +a[6])); + } + } + return value; + }); + + This is a reference implementation. You are free to copy, modify, or + redistribute. + + This code should be minified before deployment. + See http://javascript.crockford.com/jsmin.html + + USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO + NOT CONTROL. +*/ + +/*members "", "\"", "\/", "\\", at, b, call, charAt, f, fromCharCode, + hasOwnProperty, message, n, name, prototype, push, r, t, text +*/ + +var json_parse = function (options) { + 'use strict'; + + // This is a function that can parse a JSON text, producing a JavaScript + // data structure. It is a simple, recursive descent parser. It does not use + // eval or regular expressions, so it can be used as a model for implementing + // a JSON parser in other languages. + + // We are defining the function inside of another function to avoid creating + // global variables. + + // Default options one can override by passing options to the parse() + var _options = { + strict: false, // not being strict means do not generate syntax errors for "duplicate key" + storeAsString: false, // toggles whether the values should be stored as BigNumber (default) or a string + alwaysParseAsBig: false, // toggles whether all numbers should be Big + useNativeBigInt: false, // toggles whether to use native BigInt instead of bignumber.js + protoAction: 'error', + constructorAction: 'error', + }; + + // If there are options, then use them to override the default _options + if (options !== undefined && options !== null) { + if (options.strict === true) { + _options.strict = true; + } + if (options.storeAsString === true) { + _options.storeAsString = true; + } + _options.alwaysParseAsBig = + options.alwaysParseAsBig === true ? options.alwaysParseAsBig : false; + _options.useNativeBigInt = + options.useNativeBigInt === true ? options.useNativeBigInt : false; + + if (typeof options.constructorAction !== 'undefined') { + if ( + options.constructorAction === 'error' || + options.constructorAction === 'ignore' || + options.constructorAction === 'preserve' + ) { + _options.constructorAction = options.constructorAction; + } else { + throw new Error( + `Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${options.constructorAction}` + ); + } + } + + if (typeof options.protoAction !== 'undefined') { + if ( + options.protoAction === 'error' || + options.protoAction === 'ignore' || + options.protoAction === 'preserve' + ) { + _options.protoAction = options.protoAction; + } else { + throw new Error( + `Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${options.protoAction}` + ); + } + } + } + + var at, // The index of the current character + ch, // The current character + escapee = { + '"': '"', + '\\': '\\', + '/': '/', + b: '\b', + f: '\f', + n: '\n', + r: '\r', + t: '\t', + }, + text, + error = function (m) { + // Call error when something is wrong. + + throw { + name: 'SyntaxError', + message: m, + at: at, + text: text, + }; + }, + next = function (c) { + // If a c parameter is provided, verify that it matches the current character. + + if (c && c !== ch) { + error("Expected '" + c + "' instead of '" + ch + "'"); + } + + // Get the next character. When there are no more characters, + // return the empty string. + + ch = text.charAt(at); + at += 1; + return ch; + }, + number = function () { + // Parse a number value. + + var number, + string = ''; + + if (ch === '-') { + string = '-'; + next('-'); + } + while (ch >= '0' && ch <= '9') { + string += ch; + next(); + } + if (ch === '.') { + string += '.'; + while (next() && ch >= '0' && ch <= '9') { + string += ch; + } + } + if (ch === 'e' || ch === 'E') { + string += ch; + next(); + if (ch === '-' || ch === '+') { + string += ch; + next(); + } + while (ch >= '0' && ch <= '9') { + string += ch; + next(); + } + } + number = +string; + if (!isFinite(number)) { + error('Bad number'); + } else { + if (BigNumber == null) BigNumber = require('bignumber.js'); + //if (number > 9007199254740992 || number < -9007199254740992) + // Bignumber has stricter check: everything with length > 15 digits disallowed + if (string.length > 15) + return _options.storeAsString + ? string + : _options.useNativeBigInt + ? BigInt(string) + : new BigNumber(string); + else + return !_options.alwaysParseAsBig + ? number + : _options.useNativeBigInt + ? BigInt(number) + : new BigNumber(number); + } + }, + string = function () { + // Parse a string value. + + var hex, + i, + string = '', + uffff; + + // When parsing for string values, we must look for " and \ characters. + + if (ch === '"') { + var startAt = at; + while (next()) { + if (ch === '"') { + if (at - 1 > startAt) string += text.substring(startAt, at - 1); + next(); + return string; + } + if (ch === '\\') { + if (at - 1 > startAt) string += text.substring(startAt, at - 1); + next(); + if (ch === 'u') { + uffff = 0; + for (i = 0; i < 4; i += 1) { + hex = parseInt(next(), 16); + if (!isFinite(hex)) { + break; + } + uffff = uffff * 16 + hex; + } + string += String.fromCharCode(uffff); + } else if (typeof escapee[ch] === 'string') { + string += escapee[ch]; + } else { + break; + } + startAt = at; + } + } + } + error('Bad string'); + }, + white = function () { + // Skip whitespace. + + while (ch && ch <= ' ') { + next(); + } + }, + word = function () { + // true, false, or null. + + switch (ch) { + case 't': + next('t'); + next('r'); + next('u'); + next('e'); + return true; + case 'f': + next('f'); + next('a'); + next('l'); + next('s'); + next('e'); + return false; + case 'n': + next('n'); + next('u'); + next('l'); + next('l'); + return null; + } + error("Unexpected '" + ch + "'"); + }, + value, // Place holder for the value function. + array = function () { + // Parse an array value. + + var array = []; + + if (ch === '[') { + next('['); + white(); + if (ch === ']') { + next(']'); + return array; // empty array + } + while (ch) { + array.push(value()); + white(); + if (ch === ']') { + next(']'); + return array; + } + next(','); + white(); + } + } + error('Bad array'); + }, + object = function () { + // Parse an object value. + + var key, + object = Object.create(null); + + if (ch === '{') { + next('{'); + white(); + if (ch === '}') { + next('}'); + return object; // empty object + } + while (ch) { + key = string(); + white(); + next(':'); + if ( + _options.strict === true && + Object.hasOwnProperty.call(object, key) + ) { + error('Duplicate key "' + key + '"'); + } + + if (suspectProtoRx.test(key) === true) { + if (_options.protoAction === 'error') { + error('Object contains forbidden prototype property'); + } else if (_options.protoAction === 'ignore') { + value(); + } else { + object[key] = value(); + } + } else if (suspectConstructorRx.test(key) === true) { + if (_options.constructorAction === 'error') { + error('Object contains forbidden constructor property'); + } else if (_options.constructorAction === 'ignore') { + value(); + } else { + object[key] = value(); + } + } else { + object[key] = value(); + } + + white(); + if (ch === '}') { + next('}'); + return object; + } + next(','); + white(); + } + } + error('Bad object'); + }; + + value = function () { + // Parse a JSON value. It could be an object, an array, a string, a number, + // or a word. + + white(); + switch (ch) { + case '{': + return object(); + case '[': + return array(); + case '"': + return string(); + case '-': + return number(); + default: + return ch >= '0' && ch <= '9' ? number() : word(); + } + }; + + // Return the json_parse function. It will have access to all of the above + // functions and variables. + + return function (source, reviver) { + var result; + + text = source + ''; + at = 0; + ch = ' '; + result = value(); + white(); + if (ch) { + error('Syntax error'); + } + + // If there is a reviver function, we recursively walk the new structure, + // passing each name/value pair to the reviver function for possible + // transformation, starting with a temporary root object that holds the result + // in an empty key. If there is not a reviver function, we simply return the + // result. + + return typeof reviver === 'function' + ? (function walk(holder, key) { + var k, + v, + value = holder[key]; + if (value && typeof value === 'object') { + Object.keys(value).forEach(function (k) { + v = walk(value, k); + if (v !== undefined) { + value[k] = v; + } else { + delete value[k]; + } + }); + } + return reviver.call(holder, key, value); + })({ '': result }, '') + : result; + }; +}; + +module.exports = json_parse; diff --git a/node_modules/json-bigint/lib/stringify.js b/node_modules/json-bigint/lib/stringify.js new file mode 100644 index 0000000..3bd5269 --- /dev/null +++ b/node_modules/json-bigint/lib/stringify.js @@ -0,0 +1,384 @@ +var BigNumber = require('bignumber.js'); + +/* + json2.js + 2013-05-26 + + Public Domain. + + NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + + See http://www.JSON.org/js.html + + + This code should be minified before deployment. + See http://javascript.crockford.com/jsmin.html + + USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO + NOT CONTROL. + + + This file creates a global JSON object containing two methods: stringify + and parse. + + JSON.stringify(value, replacer, space) + value any JavaScript value, usually an object or array. + + replacer an optional parameter that determines how object + values are stringified for objects. It can be a + function or an array of strings. + + space an optional parameter that specifies the indentation + of nested structures. If it is omitted, the text will + be packed without extra whitespace. If it is a number, + it will specify the number of spaces to indent at each + level. If it is a string (such as '\t' or ' '), + it contains the characters used to indent at each level. + + This method produces a JSON text from a JavaScript value. + + When an object value is found, if the object contains a toJSON + method, its toJSON method will be called and the result will be + stringified. A toJSON method does not serialize: it returns the + value represented by the name/value pair that should be serialized, + or undefined if nothing should be serialized. The toJSON method + will be passed the key associated with the value, and this will be + bound to the value + + For example, this would serialize Dates as ISO strings. + + Date.prototype.toJSON = function (key) { + function f(n) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } + + return this.getUTCFullYear() + '-' + + f(this.getUTCMonth() + 1) + '-' + + f(this.getUTCDate()) + 'T' + + f(this.getUTCHours()) + ':' + + f(this.getUTCMinutes()) + ':' + + f(this.getUTCSeconds()) + 'Z'; + }; + + You can provide an optional replacer method. It will be passed the + key and value of each member, with this bound to the containing + object. The value that is returned from your method will be + serialized. If your method returns undefined, then the member will + be excluded from the serialization. + + If the replacer parameter is an array of strings, then it will be + used to select the members to be serialized. It filters the results + such that only members with keys listed in the replacer array are + stringified. + + Values that do not have JSON representations, such as undefined or + functions, will not be serialized. Such values in objects will be + dropped; in arrays they will be replaced with null. You can use + a replacer function to replace those with JSON values. + JSON.stringify(undefined) returns undefined. + + The optional space parameter produces a stringification of the + value that is filled with line breaks and indentation to make it + easier to read. + + If the space parameter is a non-empty string, then that string will + be used for indentation. If the space parameter is a number, then + the indentation will be that many spaces. + + Example: + + text = JSON.stringify(['e', {pluribus: 'unum'}]); + // text is '["e",{"pluribus":"unum"}]' + + + text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); + // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' + + text = JSON.stringify([new Date()], function (key, value) { + return this[key] instanceof Date ? + 'Date(' + this[key] + ')' : value; + }); + // text is '["Date(---current time---)"]' + + + JSON.parse(text, reviver) + This method parses a JSON text to produce an object or array. + It can throw a SyntaxError exception. + + The optional reviver parameter is a function that can filter and + transform the results. It receives each of the keys and values, + and its return value is used instead of the original value. + If it returns what it received, then the structure is not modified. + If it returns undefined then the member is deleted. + + Example: + + // Parse the text. Values that look like ISO date strings will + // be converted to Date objects. + + myData = JSON.parse(text, function (key, value) { + var a; + if (typeof value === 'string') { + a = +/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); + if (a) { + return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], + +a[5], +a[6])); + } + } + return value; + }); + + myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { + var d; + if (typeof value === 'string' && + value.slice(0, 5) === 'Date(' && + value.slice(-1) === ')') { + d = new Date(value.slice(5, -1)); + if (d) { + return d; + } + } + return value; + }); + + + This is a reference implementation. You are free to copy, modify, or + redistribute. +*/ + +/*jslint evil: true, regexp: true */ + +/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, + call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, + getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, + lastIndex, length, parse, prototype, push, replace, slice, stringify, + test, toJSON, toString, valueOf +*/ + + +// Create a JSON object only if one does not already exist. We create the +// methods in a closure to avoid creating global variables. + +var JSON = module.exports; + +(function () { + 'use strict'; + + function f(n) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } + + var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + gap, + indent, + meta = { // table of character substitutions + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '"' : '\\"', + '\\': '\\\\' + }, + rep; + + + function quote(string) { + +// If the string contains no control characters, no quote characters, and no +// backslash characters, then we can safely slap some quotes around it. +// Otherwise we must also replace the offending characters with safe escape +// sequences. + + escapable.lastIndex = 0; + return escapable.test(string) ? '"' + string.replace(escapable, function (a) { + var c = meta[a]; + return typeof c === 'string' + ? c + : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"' : '"' + string + '"'; + } + + + function str(key, holder) { + +// Produce a string from holder[key]. + + var i, // The loop counter. + k, // The member key. + v, // The member value. + length, + mind = gap, + partial, + value = holder[key], + isBigNumber = value != null && (value instanceof BigNumber || BigNumber.isBigNumber(value)); + +// If the value has a toJSON method, call it to obtain a replacement value. + + if (value && typeof value === 'object' && + typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + +// If we were called with a replacer function, then call the replacer to +// obtain a replacement value. + + if (typeof rep === 'function') { + value = rep.call(holder, key, value); + } + +// What happens next depends on the value's type. + + switch (typeof value) { + case 'string': + if (isBigNumber) { + return value; + } else { + return quote(value); + } + + case 'number': + +// JSON numbers must be finite. Encode non-finite numbers as null. + + return isFinite(value) ? String(value) : 'null'; + + case 'boolean': + case 'null': + case 'bigint': + +// If the value is a boolean or null, convert it to a string. Note: +// typeof null does not produce 'null'. The case is included here in +// the remote chance that this gets fixed someday. + + return String(value); + +// If the type is 'object', we might be dealing with an object or an array or +// null. + + case 'object': + +// Due to a specification blunder in ECMAScript, typeof null is 'object', +// so watch out for that case. + + if (!value) { + return 'null'; + } + +// Make an array to hold the partial results of stringifying this object value. + + gap += indent; + partial = []; + +// Is the value an array? + + if (Object.prototype.toString.apply(value) === '[object Array]') { + +// The value is an array. Stringify every element. Use null as a placeholder +// for non-JSON values. + + length = value.length; + for (i = 0; i < length; i += 1) { + partial[i] = str(i, value) || 'null'; + } + +// Join all of the elements together, separated with commas, and wrap them in +// brackets. + + v = partial.length === 0 + ? '[]' + : gap + ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' + : '[' + partial.join(',') + ']'; + gap = mind; + return v; + } + +// If the replacer is an array, use it to select the members to be stringified. + + if (rep && typeof rep === 'object') { + length = rep.length; + for (i = 0; i < length; i += 1) { + if (typeof rep[i] === 'string') { + k = rep[i]; + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } else { + +// Otherwise, iterate through all of the keys in the object. + + Object.keys(value).forEach(function(k) { + var v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + }); + } + +// Join all of the member texts together, separated with commas, +// and wrap them in braces. + + v = partial.length === 0 + ? '{}' + : gap + ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' + : '{' + partial.join(',') + '}'; + gap = mind; + return v; + } + } + +// If the JSON object does not yet have a stringify method, give it one. + + if (typeof JSON.stringify !== 'function') { + JSON.stringify = function (value, replacer, space) { + +// The stringify method takes a value and an optional replacer, and an optional +// space parameter, and returns a JSON text. The replacer can be a function +// that can replace values, or an array of strings that will select the keys. +// A default replacer method can be provided. Use of the space parameter can +// produce text that is more easily readable. + + var i; + gap = ''; + indent = ''; + +// If the space parameter is a number, make an indent string containing that +// many spaces. + + if (typeof space === 'number') { + for (i = 0; i < space; i += 1) { + indent += ' '; + } + +// If the space parameter is a string, it will be used as the indent string. + + } else if (typeof space === 'string') { + indent = space; + } + +// If there is a replacer, it must be a function or an array. +// Otherwise, throw an error. + + rep = replacer; + if (replacer && typeof replacer !== 'function' && + (typeof replacer !== 'object' || + typeof replacer.length !== 'number')) { + throw new Error('JSON.stringify'); + } + +// Make a fake root object containing our value under the key of ''. +// Return the result of stringifying the value. + + return str('', {'': value}); + }; + } +}()); diff --git a/node_modules/json-bigint/package.json b/node_modules/json-bigint/package.json new file mode 100644 index 0000000..9309f6b --- /dev/null +++ b/node_modules/json-bigint/package.json @@ -0,0 +1,34 @@ +{ + "name": "json-bigint", + "version": "1.0.0", + "description": "JSON.parse with bigints support", + "main": "index.js", + "files": [ + "index.js", + "lib/parse.js", + "lib/stringify.js" + ], + "scripts": { + "test": "./node_modules/mocha/bin/mocha -R spec --check-leaks test/*-test.js" + }, + "repository": { + "type": "git", + "url": "git@github.com:sidorares/json-bigint.git" + }, + "keywords": [ + "JSON", + "bigint", + "bignumber", + "parse", + "json" + ], + "author": "Andrey Sidorov ", + "license": "MIT", + "dependencies": { + "bignumber.js": "^9.0.0" + }, + "devDependencies": { + "chai": "4.2.0", + "mocha": "8.0.1" + } +} diff --git a/node_modules/jsonwebtoken/LICENSE b/node_modules/jsonwebtoken/LICENSE new file mode 100644 index 0000000..bcd1854 --- /dev/null +++ b/node_modules/jsonwebtoken/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Auth0, Inc. (http://auth0.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jsonwebtoken/README.md b/node_modules/jsonwebtoken/README.md new file mode 100644 index 0000000..4e20dd9 --- /dev/null +++ b/node_modules/jsonwebtoken/README.md @@ -0,0 +1,396 @@ +# jsonwebtoken + +| **Build** | **Dependency** | +|-----------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------| +| [![Build Status](https://secure.travis-ci.org/auth0/node-jsonwebtoken.svg?branch=master)](http://travis-ci.org/auth0/node-jsonwebtoken) | [![Dependency Status](https://david-dm.org/auth0/node-jsonwebtoken.svg)](https://david-dm.org/auth0/node-jsonwebtoken) | + + +An implementation of [JSON Web Tokens](https://tools.ietf.org/html/rfc7519). + +This was developed against `draft-ietf-oauth-json-web-token-08`. It makes use of [node-jws](https://github.com/brianloveswords/node-jws) + +# Install + +```bash +$ npm install jsonwebtoken +``` + +# Migration notes + +* [From v8 to v9](https://github.com/auth0/node-jsonwebtoken/wiki/Migration-Notes:-v8-to-v9) +* [From v7 to v8](https://github.com/auth0/node-jsonwebtoken/wiki/Migration-Notes:-v7-to-v8) + +# Usage + +### jwt.sign(payload, secretOrPrivateKey, [options, callback]) + +(Asynchronous) If a callback is supplied, the callback is called with the `err` or the JWT. + +(Synchronous) Returns the JsonWebToken as string + +`payload` could be an object literal, buffer or string representing valid JSON. +> **Please _note_ that** `exp` or any other claim is only set if the payload is an object literal. Buffer or string payloads are not checked for JSON validity. + +> If `payload` is not a buffer or a string, it will be coerced into a string using `JSON.stringify`. + +`secretOrPrivateKey` is a string (utf-8 encoded), buffer, object, or KeyObject containing either the secret for HMAC algorithms or the PEM +encoded private key for RSA and ECDSA. In case of a private key with passphrase an object `{ key, passphrase }` can be used (based on [crypto documentation](https://nodejs.org/api/crypto.html#crypto_sign_sign_private_key_output_format)), in this case be sure you pass the `algorithm` option. +When signing with RSA algorithms the minimum modulus length is 2048 except when the allowInsecureKeySizes option is set to true. Private keys below this size will be rejected with an error. + +`options`: + +* `algorithm` (default: `HS256`) +* `expiresIn`: expressed in seconds or a string describing a time span [vercel/ms](https://github.com/vercel/ms). + > Eg: `60`, `"2 days"`, `"10h"`, `"7d"`. A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (`"120"` is equal to `"120ms"`). +* `notBefore`: expressed in seconds or a string describing a time span [vercel/ms](https://github.com/vercel/ms). + > Eg: `60`, `"2 days"`, `"10h"`, `"7d"`. A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (`"120"` is equal to `"120ms"`). +* `audience` +* `issuer` +* `jwtid` +* `subject` +* `noTimestamp` +* `header` +* `keyid` +* `mutatePayload`: if true, the sign function will modify the payload object directly. This is useful if you need a raw reference to the payload after claims have been applied to it but before it has been encoded into a token. +* `allowInsecureKeySizes`: if true allows private keys with a modulus below 2048 to be used for RSA +* `allowInvalidAsymmetricKeyTypes`: if true, allows asymmetric keys which do not match the specified algorithm. This option is intended only for backwards compatability and should be avoided. + + + +> There are no default values for `expiresIn`, `notBefore`, `audience`, `subject`, `issuer`. These claims can also be provided in the payload directly with `exp`, `nbf`, `aud`, `sub` and `iss` respectively, but you **_can't_** include in both places. + +Remember that `exp`, `nbf` and `iat` are **NumericDate**, see related [Token Expiration (exp claim)](#token-expiration-exp-claim) + + +The header can be customized via the `options.header` object. + +Generated jwts will include an `iat` (issued at) claim by default unless `noTimestamp` is specified. If `iat` is inserted in the payload, it will be used instead of the real timestamp for calculating other things like `exp` given a timespan in `options.expiresIn`. + +Synchronous Sign with default (HMAC SHA256) + +```js +var jwt = require('jsonwebtoken'); +var token = jwt.sign({ foo: 'bar' }, 'shhhhh'); +``` + +Synchronous Sign with RSA SHA256 +```js +// sign with RSA SHA256 +var privateKey = fs.readFileSync('private.key'); +var token = jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' }); +``` + +Sign asynchronously +```js +jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' }, function(err, token) { + console.log(token); +}); +``` + +Backdate a jwt 30 seconds +```js +var older_token = jwt.sign({ foo: 'bar', iat: Math.floor(Date.now() / 1000) - 30 }, 'shhhhh'); +``` + +#### Token Expiration (exp claim) + +The standard for JWT defines an `exp` claim for expiration. The expiration is represented as a **NumericDate**: + +> A JSON numeric value representing the number of seconds from 1970-01-01T00:00:00Z UTC until the specified UTC date/time, ignoring leap seconds. This is equivalent to the IEEE Std 1003.1, 2013 Edition [POSIX.1] definition "Seconds Since the Epoch", in which each day is accounted for by exactly 86400 seconds, other than that non-integer values can be represented. See RFC 3339 [RFC3339] for details regarding date/times in general and UTC in particular. + +This means that the `exp` field should contain the number of seconds since the epoch. + +Signing a token with 1 hour of expiration: + +```javascript +jwt.sign({ + exp: Math.floor(Date.now() / 1000) + (60 * 60), + data: 'foobar' +}, 'secret'); +``` + +Another way to generate a token like this with this library is: + +```javascript +jwt.sign({ + data: 'foobar' +}, 'secret', { expiresIn: 60 * 60 }); + +//or even better: + +jwt.sign({ + data: 'foobar' +}, 'secret', { expiresIn: '1h' }); +``` + +### jwt.verify(token, secretOrPublicKey, [options, callback]) + +(Asynchronous) If a callback is supplied, function acts asynchronously. The callback is called with the decoded payload if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will be called with the error. + +(Synchronous) If a callback is not supplied, function acts synchronously. Returns the payload decoded if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will throw the error. + +> __Warning:__ When the token comes from an untrusted source (e.g. user input or external requests), the returned decoded payload should be treated like any other user input; please make sure to sanitize and only work with properties that are expected + +`token` is the JsonWebToken string + +`secretOrPublicKey` is a string (utf-8 encoded), buffer, or KeyObject containing either the secret for HMAC algorithms, or the PEM +encoded public key for RSA and ECDSA. +If `jwt.verify` is called asynchronous, `secretOrPublicKey` can be a function that should fetch the secret or public key. See below for a detailed example + +As mentioned in [this comment](https://github.com/auth0/node-jsonwebtoken/issues/208#issuecomment-231861138), there are other libraries that expect base64 encoded secrets (random bytes encoded using base64), if that is your case you can pass `Buffer.from(secret, 'base64')`, by doing this the secret will be decoded using base64 and the token verification will use the original random bytes. + +`options` + +* `algorithms`: List of strings with the names of the allowed algorithms. For instance, `["HS256", "HS384"]`. + > If not specified a defaults will be used based on the type of key provided + > * secret - ['HS256', 'HS384', 'HS512'] + > * rsa - ['RS256', 'RS384', 'RS512'] + > * ec - ['ES256', 'ES384', 'ES512'] + > * default - ['RS256', 'RS384', 'RS512'] +* `audience`: if you want to check audience (`aud`), provide a value here. The audience can be checked against a string, a regular expression or a list of strings and/or regular expressions. + > Eg: `"urn:foo"`, `/urn:f[o]{2}/`, `[/urn:f[o]{2}/, "urn:bar"]` +* `complete`: return an object with the decoded `{ payload, header, signature }` instead of only the usual content of the payload. +* `issuer` (optional): string or array of strings of valid values for the `iss` field. +* `jwtid` (optional): if you want to check JWT ID (`jti`), provide a string value here. +* `ignoreExpiration`: if `true` do not validate the expiration of the token. +* `ignoreNotBefore`... +* `subject`: if you want to check subject (`sub`), provide a value here +* `clockTolerance`: number of seconds to tolerate when checking the `nbf` and `exp` claims, to deal with small clock differences among different servers +* `maxAge`: the maximum allowed age for tokens to still be valid. It is expressed in seconds or a string describing a time span [vercel/ms](https://github.com/vercel/ms). + > Eg: `1000`, `"2 days"`, `"10h"`, `"7d"`. A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (`"120"` is equal to `"120ms"`). +* `clockTimestamp`: the time in seconds that should be used as the current time for all necessary comparisons. +* `nonce`: if you want to check `nonce` claim, provide a string value here. It is used on Open ID for the ID Tokens. ([Open ID implementation notes](https://openid.net/specs/openid-connect-core-1_0.html#NonceNotes)) +* `allowInvalidAsymmetricKeyTypes`: if true, allows asymmetric keys which do not match the specified algorithm. This option is intended only for backwards compatability and should be avoided. + +```js +// verify a token symmetric - synchronous +var decoded = jwt.verify(token, 'shhhhh'); +console.log(decoded.foo) // bar + +// verify a token symmetric +jwt.verify(token, 'shhhhh', function(err, decoded) { + console.log(decoded.foo) // bar +}); + +// invalid token - synchronous +try { + var decoded = jwt.verify(token, 'wrong-secret'); +} catch(err) { + // err +} + +// invalid token +jwt.verify(token, 'wrong-secret', function(err, decoded) { + // err + // decoded undefined +}); + +// verify a token asymmetric +var cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, function(err, decoded) { + console.log(decoded.foo) // bar +}); + +// verify audience +var cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, { audience: 'urn:foo' }, function(err, decoded) { + // if audience mismatch, err == invalid audience +}); + +// verify issuer +var cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer' }, function(err, decoded) { + // if issuer mismatch, err == invalid issuer +}); + +// verify jwt id +var cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer', jwtid: 'jwtid' }, function(err, decoded) { + // if jwt id mismatch, err == invalid jwt id +}); + +// verify subject +var cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer', jwtid: 'jwtid', subject: 'subject' }, function(err, decoded) { + // if subject mismatch, err == invalid subject +}); + +// alg mismatch +var cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, { algorithms: ['RS256'] }, function (err, payload) { + // if token alg != RS256, err == invalid signature +}); + +// Verify using getKey callback +// Example uses https://github.com/auth0/node-jwks-rsa as a way to fetch the keys. +var jwksClient = require('jwks-rsa'); +var client = jwksClient({ + jwksUri: 'https://sandrino.auth0.com/.well-known/jwks.json' +}); +function getKey(header, callback){ + client.getSigningKey(header.kid, function(err, key) { + var signingKey = key.publicKey || key.rsaPublicKey; + callback(null, signingKey); + }); +} + +jwt.verify(token, getKey, options, function(err, decoded) { + console.log(decoded.foo) // bar +}); + +``` + +
                          +Need to peek into a JWT without verifying it? (Click to expand) + +### jwt.decode(token [, options]) + +(Synchronous) Returns the decoded payload without verifying if the signature is valid. + +> __Warning:__ This will __not__ verify whether the signature is valid. You should __not__ use this for untrusted messages. You most likely want to use `jwt.verify` instead. + +> __Warning:__ When the token comes from an untrusted source (e.g. user input or external request), the returned decoded payload should be treated like any other user input; please make sure to sanitize and only work with properties that are expected + + +`token` is the JsonWebToken string + +`options`: + +* `json`: force JSON.parse on the payload even if the header doesn't contain `"typ":"JWT"`. +* `complete`: return an object with the decoded payload and header. + +Example + +```js +// get the decoded payload ignoring signature, no secretOrPrivateKey needed +var decoded = jwt.decode(token); + +// get the decoded payload and header +var decoded = jwt.decode(token, {complete: true}); +console.log(decoded.header); +console.log(decoded.payload) +``` + +
                          + +## Errors & Codes +Possible thrown errors during verification. +Error is the first argument of the verification callback. + +### TokenExpiredError + +Thrown error if the token is expired. + +Error object: + +* name: 'TokenExpiredError' +* message: 'jwt expired' +* expiredAt: [ExpDate] + +```js +jwt.verify(token, 'shhhhh', function(err, decoded) { + if (err) { + /* + err = { + name: 'TokenExpiredError', + message: 'jwt expired', + expiredAt: 1408621000 + } + */ + } +}); +``` + +### JsonWebTokenError +Error object: + +* name: 'JsonWebTokenError' +* message: + * 'invalid token' - the header or payload could not be parsed + * 'jwt malformed' - the token does not have three components (delimited by a `.`) + * 'jwt signature is required' + * 'invalid signature' + * 'jwt audience invalid. expected: [OPTIONS AUDIENCE]' + * 'jwt issuer invalid. expected: [OPTIONS ISSUER]' + * 'jwt id invalid. expected: [OPTIONS JWT ID]' + * 'jwt subject invalid. expected: [OPTIONS SUBJECT]' + +```js +jwt.verify(token, 'shhhhh', function(err, decoded) { + if (err) { + /* + err = { + name: 'JsonWebTokenError', + message: 'jwt malformed' + } + */ + } +}); +``` + +### NotBeforeError +Thrown if current time is before the nbf claim. + +Error object: + +* name: 'NotBeforeError' +* message: 'jwt not active' +* date: 2018-10-04T16:10:44.000Z + +```js +jwt.verify(token, 'shhhhh', function(err, decoded) { + if (err) { + /* + err = { + name: 'NotBeforeError', + message: 'jwt not active', + date: 2018-10-04T16:10:44.000Z + } + */ + } +}); +``` + + +## Algorithms supported + +Array of supported algorithms. The following algorithms are currently supported. + +| alg Parameter Value | Digital Signature or MAC Algorithm | +|---------------------|------------------------------------------------------------------------| +| HS256 | HMAC using SHA-256 hash algorithm | +| HS384 | HMAC using SHA-384 hash algorithm | +| HS512 | HMAC using SHA-512 hash algorithm | +| RS256 | RSASSA-PKCS1-v1_5 using SHA-256 hash algorithm | +| RS384 | RSASSA-PKCS1-v1_5 using SHA-384 hash algorithm | +| RS512 | RSASSA-PKCS1-v1_5 using SHA-512 hash algorithm | +| PS256 | RSASSA-PSS using SHA-256 hash algorithm (only node ^6.12.0 OR >=8.0.0) | +| PS384 | RSASSA-PSS using SHA-384 hash algorithm (only node ^6.12.0 OR >=8.0.0) | +| PS512 | RSASSA-PSS using SHA-512 hash algorithm (only node ^6.12.0 OR >=8.0.0) | +| ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm | +| ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm | +| ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm | +| none | No digital signature or MAC value included | + +## Refreshing JWTs + +First of all, we recommend you to think carefully if auto-refreshing a JWT will not introduce any vulnerability in your system. + +We are not comfortable including this as part of the library, however, you can take a look at [this example](https://gist.github.com/ziluvatar/a3feb505c4c0ec37059054537b38fc48) to show how this could be accomplished. +Apart from that example there are [an issue](https://github.com/auth0/node-jsonwebtoken/issues/122) and [a pull request](https://github.com/auth0/node-jsonwebtoken/pull/172) to get more knowledge about this topic. + +# TODO + +* X.509 certificate chain is not checked + +## Issue Reporting + +If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/whitehat) details the procedure for disclosing security issues. + +## Author + +[Auth0](https://auth0.com) + +## License + +This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info. diff --git a/node_modules/jsonwebtoken/decode.js b/node_modules/jsonwebtoken/decode.js new file mode 100644 index 0000000..8fe1adc --- /dev/null +++ b/node_modules/jsonwebtoken/decode.js @@ -0,0 +1,30 @@ +var jws = require('jws'); + +module.exports = function (jwt, options) { + options = options || {}; + var decoded = jws.decode(jwt, options); + if (!decoded) { return null; } + var payload = decoded.payload; + + //try parse the payload + if(typeof payload === 'string') { + try { + var obj = JSON.parse(payload); + if(obj !== null && typeof obj === 'object') { + payload = obj; + } + } catch (e) { } + } + + //return header if `complete` option is enabled. header includes claims + //such as `kid` and `alg` used to select the key within a JWKS needed to + //verify the signature + if (options.complete === true) { + return { + header: decoded.header, + payload: payload, + signature: decoded.signature + }; + } + return payload; +}; diff --git a/node_modules/jsonwebtoken/index.js b/node_modules/jsonwebtoken/index.js new file mode 100644 index 0000000..161eb2d --- /dev/null +++ b/node_modules/jsonwebtoken/index.js @@ -0,0 +1,8 @@ +module.exports = { + decode: require('./decode'), + verify: require('./verify'), + sign: require('./sign'), + JsonWebTokenError: require('./lib/JsonWebTokenError'), + NotBeforeError: require('./lib/NotBeforeError'), + TokenExpiredError: require('./lib/TokenExpiredError'), +}; diff --git a/node_modules/jsonwebtoken/lib/JsonWebTokenError.js b/node_modules/jsonwebtoken/lib/JsonWebTokenError.js new file mode 100644 index 0000000..e068222 --- /dev/null +++ b/node_modules/jsonwebtoken/lib/JsonWebTokenError.js @@ -0,0 +1,14 @@ +var JsonWebTokenError = function (message, error) { + Error.call(this, message); + if(Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = 'JsonWebTokenError'; + this.message = message; + if (error) this.inner = error; +}; + +JsonWebTokenError.prototype = Object.create(Error.prototype); +JsonWebTokenError.prototype.constructor = JsonWebTokenError; + +module.exports = JsonWebTokenError; diff --git a/node_modules/jsonwebtoken/lib/NotBeforeError.js b/node_modules/jsonwebtoken/lib/NotBeforeError.js new file mode 100644 index 0000000..7b30084 --- /dev/null +++ b/node_modules/jsonwebtoken/lib/NotBeforeError.js @@ -0,0 +1,13 @@ +var JsonWebTokenError = require('./JsonWebTokenError'); + +var NotBeforeError = function (message, date) { + JsonWebTokenError.call(this, message); + this.name = 'NotBeforeError'; + this.date = date; +}; + +NotBeforeError.prototype = Object.create(JsonWebTokenError.prototype); + +NotBeforeError.prototype.constructor = NotBeforeError; + +module.exports = NotBeforeError; \ No newline at end of file diff --git a/node_modules/jsonwebtoken/lib/TokenExpiredError.js b/node_modules/jsonwebtoken/lib/TokenExpiredError.js new file mode 100644 index 0000000..abb704f --- /dev/null +++ b/node_modules/jsonwebtoken/lib/TokenExpiredError.js @@ -0,0 +1,13 @@ +var JsonWebTokenError = require('./JsonWebTokenError'); + +var TokenExpiredError = function (message, expiredAt) { + JsonWebTokenError.call(this, message); + this.name = 'TokenExpiredError'; + this.expiredAt = expiredAt; +}; + +TokenExpiredError.prototype = Object.create(JsonWebTokenError.prototype); + +TokenExpiredError.prototype.constructor = TokenExpiredError; + +module.exports = TokenExpiredError; \ No newline at end of file diff --git a/node_modules/jsonwebtoken/lib/asymmetricKeyDetailsSupported.js b/node_modules/jsonwebtoken/lib/asymmetricKeyDetailsSupported.js new file mode 100644 index 0000000..a6ede56 --- /dev/null +++ b/node_modules/jsonwebtoken/lib/asymmetricKeyDetailsSupported.js @@ -0,0 +1,3 @@ +const semver = require('semver'); + +module.exports = semver.satisfies(process.version, '>=15.7.0'); diff --git a/node_modules/jsonwebtoken/lib/psSupported.js b/node_modules/jsonwebtoken/lib/psSupported.js new file mode 100644 index 0000000..8c04144 --- /dev/null +++ b/node_modules/jsonwebtoken/lib/psSupported.js @@ -0,0 +1,3 @@ +var semver = require('semver'); + +module.exports = semver.satisfies(process.version, '^6.12.0 || >=8.0.0'); diff --git a/node_modules/jsonwebtoken/lib/rsaPssKeyDetailsSupported.js b/node_modules/jsonwebtoken/lib/rsaPssKeyDetailsSupported.js new file mode 100644 index 0000000..7fcf368 --- /dev/null +++ b/node_modules/jsonwebtoken/lib/rsaPssKeyDetailsSupported.js @@ -0,0 +1,3 @@ +const semver = require('semver'); + +module.exports = semver.satisfies(process.version, '>=16.9.0'); diff --git a/node_modules/jsonwebtoken/lib/timespan.js b/node_modules/jsonwebtoken/lib/timespan.js new file mode 100644 index 0000000..e509869 --- /dev/null +++ b/node_modules/jsonwebtoken/lib/timespan.js @@ -0,0 +1,18 @@ +var ms = require('ms'); + +module.exports = function (time, iat) { + var timestamp = iat || Math.floor(Date.now() / 1000); + + if (typeof time === 'string') { + var milliseconds = ms(time); + if (typeof milliseconds === 'undefined') { + return; + } + return Math.floor(timestamp + milliseconds / 1000); + } else if (typeof time === 'number') { + return timestamp + time; + } else { + return; + } + +}; \ No newline at end of file diff --git a/node_modules/jsonwebtoken/lib/validateAsymmetricKey.js b/node_modules/jsonwebtoken/lib/validateAsymmetricKey.js new file mode 100644 index 0000000..c10340b --- /dev/null +++ b/node_modules/jsonwebtoken/lib/validateAsymmetricKey.js @@ -0,0 +1,66 @@ +const ASYMMETRIC_KEY_DETAILS_SUPPORTED = require('./asymmetricKeyDetailsSupported'); +const RSA_PSS_KEY_DETAILS_SUPPORTED = require('./rsaPssKeyDetailsSupported'); + +const allowedAlgorithmsForKeys = { + 'ec': ['ES256', 'ES384', 'ES512'], + 'rsa': ['RS256', 'PS256', 'RS384', 'PS384', 'RS512', 'PS512'], + 'rsa-pss': ['PS256', 'PS384', 'PS512'] +}; + +const allowedCurves = { + ES256: 'prime256v1', + ES384: 'secp384r1', + ES512: 'secp521r1', +}; + +module.exports = function(algorithm, key) { + if (!algorithm || !key) return; + + const keyType = key.asymmetricKeyType; + if (!keyType) return; + + const allowedAlgorithms = allowedAlgorithmsForKeys[keyType]; + + if (!allowedAlgorithms) { + throw new Error(`Unknown key type "${keyType}".`); + } + + if (!allowedAlgorithms.includes(algorithm)) { + throw new Error(`"alg" parameter for "${keyType}" key type must be one of: ${allowedAlgorithms.join(', ')}.`) + } + + /* + * Ignore the next block from test coverage because it gets executed + * conditionally depending on the Node version. Not ignoring it would + * prevent us from reaching the target % of coverage for versions of + * Node under 15.7.0. + */ + /* istanbul ignore next */ + if (ASYMMETRIC_KEY_DETAILS_SUPPORTED) { + switch (keyType) { + case 'ec': + const keyCurve = key.asymmetricKeyDetails.namedCurve; + const allowedCurve = allowedCurves[algorithm]; + + if (keyCurve !== allowedCurve) { + throw new Error(`"alg" parameter "${algorithm}" requires curve "${allowedCurve}".`); + } + break; + + case 'rsa-pss': + if (RSA_PSS_KEY_DETAILS_SUPPORTED) { + const length = parseInt(algorithm.slice(-3), 10); + const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = key.asymmetricKeyDetails; + + if (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm) { + throw new Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${algorithm}.`); + } + + if (saltLength !== undefined && saltLength > length >> 3) { + throw new Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${algorithm}.`) + } + } + break; + } + } +} diff --git a/node_modules/jsonwebtoken/package.json b/node_modules/jsonwebtoken/package.json new file mode 100644 index 0000000..eab30c0 --- /dev/null +++ b/node_modules/jsonwebtoken/package.json @@ -0,0 +1,70 @@ +{ + "name": "jsonwebtoken", + "version": "9.0.3", + "description": "JSON Web Token implementation (symmetric and asymmetric)", + "main": "index.js", + "nyc": { + "check-coverage": true, + "lines": 95, + "statements": 95, + "functions": 100, + "branches": 95, + "exclude": [ + "./test/**" + ], + "reporter": [ + "json", + "lcov", + "text-summary" + ] + }, + "scripts": { + "lint": "eslint .", + "coverage": "nyc mocha --use_strict", + "test": "mocha" + }, + "repository": { + "type": "git", + "url": "https://github.com/auth0/node-jsonwebtoken" + }, + "keywords": [ + "jwt" + ], + "author": "auth0", + "license": "MIT", + "bugs": { + "url": "https://github.com/auth0/node-jsonwebtoken/issues" + }, + "dependencies": { + "jws": "^4.0.1", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "devDependencies": { + "atob": "^2.1.2", + "chai": "^4.1.2", + "conventional-changelog": "~1.1.0", + "eslint": "^4.19.1", + "mocha": "^5.2.0", + "nsp": "^2.6.2", + "nyc": "^11.9.0", + "sinon": "^6.0.0" + }, + "engines": { + "npm": ">=6", + "node": ">=12" + }, + "files": [ + "lib", + "decode.js", + "sign.js", + "verify.js" + ] +} diff --git a/node_modules/jsonwebtoken/sign.js b/node_modules/jsonwebtoken/sign.js new file mode 100644 index 0000000..82bf526 --- /dev/null +++ b/node_modules/jsonwebtoken/sign.js @@ -0,0 +1,253 @@ +const timespan = require('./lib/timespan'); +const PS_SUPPORTED = require('./lib/psSupported'); +const validateAsymmetricKey = require('./lib/validateAsymmetricKey'); +const jws = require('jws'); +const includes = require('lodash.includes'); +const isBoolean = require('lodash.isboolean'); +const isInteger = require('lodash.isinteger'); +const isNumber = require('lodash.isnumber'); +const isPlainObject = require('lodash.isplainobject'); +const isString = require('lodash.isstring'); +const once = require('lodash.once'); +const { KeyObject, createSecretKey, createPrivateKey } = require('crypto') + +const SUPPORTED_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512', 'none']; +if (PS_SUPPORTED) { + SUPPORTED_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); +} + +const sign_options_schema = { + expiresIn: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"expiresIn" should be a number of seconds or string representing a timespan' }, + notBefore: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"notBefore" should be a number of seconds or string representing a timespan' }, + audience: { isValid: function(value) { return isString(value) || Array.isArray(value); }, message: '"audience" must be a string or array' }, + algorithm: { isValid: includes.bind(null, SUPPORTED_ALGS), message: '"algorithm" must be a valid string enum value' }, + header: { isValid: isPlainObject, message: '"header" must be an object' }, + encoding: { isValid: isString, message: '"encoding" must be a string' }, + issuer: { isValid: isString, message: '"issuer" must be a string' }, + subject: { isValid: isString, message: '"subject" must be a string' }, + jwtid: { isValid: isString, message: '"jwtid" must be a string' }, + noTimestamp: { isValid: isBoolean, message: '"noTimestamp" must be a boolean' }, + keyid: { isValid: isString, message: '"keyid" must be a string' }, + mutatePayload: { isValid: isBoolean, message: '"mutatePayload" must be a boolean' }, + allowInsecureKeySizes: { isValid: isBoolean, message: '"allowInsecureKeySizes" must be a boolean'}, + allowInvalidAsymmetricKeyTypes: { isValid: isBoolean, message: '"allowInvalidAsymmetricKeyTypes" must be a boolean'} +}; + +const registered_claims_schema = { + iat: { isValid: isNumber, message: '"iat" should be a number of seconds' }, + exp: { isValid: isNumber, message: '"exp" should be a number of seconds' }, + nbf: { isValid: isNumber, message: '"nbf" should be a number of seconds' } +}; + +function validate(schema, allowUnknown, object, parameterName) { + if (!isPlainObject(object)) { + throw new Error('Expected "' + parameterName + '" to be a plain object.'); + } + Object.keys(object) + .forEach(function(key) { + const validator = schema[key]; + if (!validator) { + if (!allowUnknown) { + throw new Error('"' + key + '" is not allowed in "' + parameterName + '"'); + } + return; + } + if (!validator.isValid(object[key])) { + throw new Error(validator.message); + } + }); +} + +function validateOptions(options) { + return validate(sign_options_schema, false, options, 'options'); +} + +function validatePayload(payload) { + return validate(registered_claims_schema, true, payload, 'payload'); +} + +const options_to_payload = { + 'audience': 'aud', + 'issuer': 'iss', + 'subject': 'sub', + 'jwtid': 'jti' +}; + +const options_for_objects = [ + 'expiresIn', + 'notBefore', + 'noTimestamp', + 'audience', + 'issuer', + 'subject', + 'jwtid', +]; + +module.exports = function (payload, secretOrPrivateKey, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } else { + options = options || {}; + } + + const isObjectPayload = typeof payload === 'object' && + !Buffer.isBuffer(payload); + + const header = Object.assign({ + alg: options.algorithm || 'HS256', + typ: isObjectPayload ? 'JWT' : undefined, + kid: options.keyid + }, options.header); + + function failure(err) { + if (callback) { + return callback(err); + } + throw err; + } + + if (!secretOrPrivateKey && options.algorithm !== 'none') { + return failure(new Error('secretOrPrivateKey must have a value')); + } + + if (secretOrPrivateKey != null && !(secretOrPrivateKey instanceof KeyObject)) { + try { + secretOrPrivateKey = createPrivateKey(secretOrPrivateKey) + } catch (_) { + try { + secretOrPrivateKey = createSecretKey(typeof secretOrPrivateKey === 'string' ? Buffer.from(secretOrPrivateKey) : secretOrPrivateKey) + } catch (_) { + return failure(new Error('secretOrPrivateKey is not valid key material')); + } + } + } + + if (header.alg.startsWith('HS') && secretOrPrivateKey.type !== 'secret') { + return failure(new Error((`secretOrPrivateKey must be a symmetric key when using ${header.alg}`))) + } else if (/^(?:RS|PS|ES)/.test(header.alg)) { + if (secretOrPrivateKey.type !== 'private') { + return failure(new Error((`secretOrPrivateKey must be an asymmetric key when using ${header.alg}`))) + } + if (!options.allowInsecureKeySizes && + !header.alg.startsWith('ES') && + secretOrPrivateKey.asymmetricKeyDetails !== undefined && //KeyObject.asymmetricKeyDetails is supported in Node 15+ + secretOrPrivateKey.asymmetricKeyDetails.modulusLength < 2048) { + return failure(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`)); + } + } + + if (typeof payload === 'undefined') { + return failure(new Error('payload is required')); + } else if (isObjectPayload) { + try { + validatePayload(payload); + } + catch (error) { + return failure(error); + } + if (!options.mutatePayload) { + payload = Object.assign({},payload); + } + } else { + const invalid_options = options_for_objects.filter(function (opt) { + return typeof options[opt] !== 'undefined'; + }); + + if (invalid_options.length > 0) { + return failure(new Error('invalid ' + invalid_options.join(',') + ' option for ' + (typeof payload ) + ' payload')); + } + } + + if (typeof payload.exp !== 'undefined' && typeof options.expiresIn !== 'undefined') { + return failure(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.')); + } + + if (typeof payload.nbf !== 'undefined' && typeof options.notBefore !== 'undefined') { + return failure(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.')); + } + + try { + validateOptions(options); + } + catch (error) { + return failure(error); + } + + if (!options.allowInvalidAsymmetricKeyTypes) { + try { + validateAsymmetricKey(header.alg, secretOrPrivateKey); + } catch (error) { + return failure(error); + } + } + + const timestamp = payload.iat || Math.floor(Date.now() / 1000); + + if (options.noTimestamp) { + delete payload.iat; + } else if (isObjectPayload) { + payload.iat = timestamp; + } + + if (typeof options.notBefore !== 'undefined') { + try { + payload.nbf = timespan(options.notBefore, timestamp); + } + catch (err) { + return failure(err); + } + if (typeof payload.nbf === 'undefined') { + return failure(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + } + + if (typeof options.expiresIn !== 'undefined' && typeof payload === 'object') { + try { + payload.exp = timespan(options.expiresIn, timestamp); + } + catch (err) { + return failure(err); + } + if (typeof payload.exp === 'undefined') { + return failure(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + } + + Object.keys(options_to_payload).forEach(function (key) { + const claim = options_to_payload[key]; + if (typeof options[key] !== 'undefined') { + if (typeof payload[claim] !== 'undefined') { + return failure(new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.')); + } + payload[claim] = options[key]; + } + }); + + const encoding = options.encoding || 'utf8'; + + if (typeof callback === 'function') { + callback = callback && once(callback); + + jws.createSign({ + header: header, + privateKey: secretOrPrivateKey, + payload: payload, + encoding: encoding + }).once('error', callback) + .once('done', function (signature) { + // TODO: Remove in favor of the modulus length check before signing once node 15+ is the minimum supported version + if(!options.allowInsecureKeySizes && /^(?:RS|PS)/.test(header.alg) && signature.length < 256) { + return callback(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`)) + } + callback(null, signature); + }); + } else { + let signature = jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding}); + // TODO: Remove in favor of the modulus length check before signing once node 15+ is the minimum supported version + if(!options.allowInsecureKeySizes && /^(?:RS|PS)/.test(header.alg) && signature.length < 256) { + throw new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`) + } + return signature + } +}; diff --git a/node_modules/jsonwebtoken/verify.js b/node_modules/jsonwebtoken/verify.js new file mode 100644 index 0000000..cdbfdc4 --- /dev/null +++ b/node_modules/jsonwebtoken/verify.js @@ -0,0 +1,263 @@ +const JsonWebTokenError = require('./lib/JsonWebTokenError'); +const NotBeforeError = require('./lib/NotBeforeError'); +const TokenExpiredError = require('./lib/TokenExpiredError'); +const decode = require('./decode'); +const timespan = require('./lib/timespan'); +const validateAsymmetricKey = require('./lib/validateAsymmetricKey'); +const PS_SUPPORTED = require('./lib/psSupported'); +const jws = require('jws'); +const {KeyObject, createSecretKey, createPublicKey} = require("crypto"); + +const PUB_KEY_ALGS = ['RS256', 'RS384', 'RS512']; +const EC_KEY_ALGS = ['ES256', 'ES384', 'ES512']; +const RSA_KEY_ALGS = ['RS256', 'RS384', 'RS512']; +const HS_ALGS = ['HS256', 'HS384', 'HS512']; + +if (PS_SUPPORTED) { + PUB_KEY_ALGS.splice(PUB_KEY_ALGS.length, 0, 'PS256', 'PS384', 'PS512'); + RSA_KEY_ALGS.splice(RSA_KEY_ALGS.length, 0, 'PS256', 'PS384', 'PS512'); +} + +module.exports = function (jwtString, secretOrPublicKey, options, callback) { + if ((typeof options === 'function') && !callback) { + callback = options; + options = {}; + } + + if (!options) { + options = {}; + } + + //clone this object since we are going to mutate it. + options = Object.assign({}, options); + + let done; + + if (callback) { + done = callback; + } else { + done = function(err, data) { + if (err) throw err; + return data; + }; + } + + if (options.clockTimestamp && typeof options.clockTimestamp !== 'number') { + return done(new JsonWebTokenError('clockTimestamp must be a number')); + } + + if (options.nonce !== undefined && (typeof options.nonce !== 'string' || options.nonce.trim() === '')) { + return done(new JsonWebTokenError('nonce must be a non-empty string')); + } + + if (options.allowInvalidAsymmetricKeyTypes !== undefined && typeof options.allowInvalidAsymmetricKeyTypes !== 'boolean') { + return done(new JsonWebTokenError('allowInvalidAsymmetricKeyTypes must be a boolean')); + } + + const clockTimestamp = options.clockTimestamp || Math.floor(Date.now() / 1000); + + if (!jwtString){ + return done(new JsonWebTokenError('jwt must be provided')); + } + + if (typeof jwtString !== 'string') { + return done(new JsonWebTokenError('jwt must be a string')); + } + + const parts = jwtString.split('.'); + + if (parts.length !== 3){ + return done(new JsonWebTokenError('jwt malformed')); + } + + let decodedToken; + + try { + decodedToken = decode(jwtString, { complete: true }); + } catch(err) { + return done(err); + } + + if (!decodedToken) { + return done(new JsonWebTokenError('invalid token')); + } + + const header = decodedToken.header; + let getSecret; + + if(typeof secretOrPublicKey === 'function') { + if(!callback) { + return done(new JsonWebTokenError('verify must be called asynchronous if secret or public key is provided as a callback')); + } + + getSecret = secretOrPublicKey; + } + else { + getSecret = function(header, secretCallback) { + return secretCallback(null, secretOrPublicKey); + }; + } + + return getSecret(header, function(err, secretOrPublicKey) { + if(err) { + return done(new JsonWebTokenError('error in secret or public key callback: ' + err.message)); + } + + const hasSignature = parts[2].trim() !== ''; + + if (!hasSignature && secretOrPublicKey){ + return done(new JsonWebTokenError('jwt signature is required')); + } + + if (hasSignature && !secretOrPublicKey) { + return done(new JsonWebTokenError('secret or public key must be provided')); + } + + if (!hasSignature && !options.algorithms) { + return done(new JsonWebTokenError('please specify "none" in "algorithms" to verify unsigned tokens')); + } + + if (secretOrPublicKey != null && !(secretOrPublicKey instanceof KeyObject)) { + try { + secretOrPublicKey = createPublicKey(secretOrPublicKey); + } catch (_) { + try { + secretOrPublicKey = createSecretKey(typeof secretOrPublicKey === 'string' ? Buffer.from(secretOrPublicKey) : secretOrPublicKey); + } catch (_) { + return done(new JsonWebTokenError('secretOrPublicKey is not valid key material')) + } + } + } + + if (!options.algorithms) { + if (secretOrPublicKey.type === 'secret') { + options.algorithms = HS_ALGS; + } else if (['rsa', 'rsa-pss'].includes(secretOrPublicKey.asymmetricKeyType)) { + options.algorithms = RSA_KEY_ALGS + } else if (secretOrPublicKey.asymmetricKeyType === 'ec') { + options.algorithms = EC_KEY_ALGS + } else { + options.algorithms = PUB_KEY_ALGS + } + } + + if (options.algorithms.indexOf(decodedToken.header.alg) === -1) { + return done(new JsonWebTokenError('invalid algorithm')); + } + + if (header.alg.startsWith('HS') && secretOrPublicKey.type !== 'secret') { + return done(new JsonWebTokenError((`secretOrPublicKey must be a symmetric key when using ${header.alg}`))) + } else if (/^(?:RS|PS|ES)/.test(header.alg) && secretOrPublicKey.type !== 'public') { + return done(new JsonWebTokenError((`secretOrPublicKey must be an asymmetric key when using ${header.alg}`))) + } + + if (!options.allowInvalidAsymmetricKeyTypes) { + try { + validateAsymmetricKey(header.alg, secretOrPublicKey); + } catch (e) { + return done(e); + } + } + + let valid; + + try { + valid = jws.verify(jwtString, decodedToken.header.alg, secretOrPublicKey); + } catch (e) { + return done(e); + } + + if (!valid) { + return done(new JsonWebTokenError('invalid signature')); + } + + const payload = decodedToken.payload; + + if (typeof payload.nbf !== 'undefined' && !options.ignoreNotBefore) { + if (typeof payload.nbf !== 'number') { + return done(new JsonWebTokenError('invalid nbf value')); + } + if (payload.nbf > clockTimestamp + (options.clockTolerance || 0)) { + return done(new NotBeforeError('jwt not active', new Date(payload.nbf * 1000))); + } + } + + if (typeof payload.exp !== 'undefined' && !options.ignoreExpiration) { + if (typeof payload.exp !== 'number') { + return done(new JsonWebTokenError('invalid exp value')); + } + if (clockTimestamp >= payload.exp + (options.clockTolerance || 0)) { + return done(new TokenExpiredError('jwt expired', new Date(payload.exp * 1000))); + } + } + + if (options.audience) { + const audiences = Array.isArray(options.audience) ? options.audience : [options.audience]; + const target = Array.isArray(payload.aud) ? payload.aud : [payload.aud]; + + const match = target.some(function (targetAudience) { + return audiences.some(function (audience) { + return audience instanceof RegExp ? audience.test(targetAudience) : audience === targetAudience; + }); + }); + + if (!match) { + return done(new JsonWebTokenError('jwt audience invalid. expected: ' + audiences.join(' or '))); + } + } + + if (options.issuer) { + const invalid_issuer = + (typeof options.issuer === 'string' && payload.iss !== options.issuer) || + (Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1); + + if (invalid_issuer) { + return done(new JsonWebTokenError('jwt issuer invalid. expected: ' + options.issuer)); + } + } + + if (options.subject) { + if (payload.sub !== options.subject) { + return done(new JsonWebTokenError('jwt subject invalid. expected: ' + options.subject)); + } + } + + if (options.jwtid) { + if (payload.jti !== options.jwtid) { + return done(new JsonWebTokenError('jwt jwtid invalid. expected: ' + options.jwtid)); + } + } + + if (options.nonce) { + if (payload.nonce !== options.nonce) { + return done(new JsonWebTokenError('jwt nonce invalid. expected: ' + options.nonce)); + } + } + + if (options.maxAge) { + if (typeof payload.iat !== 'number') { + return done(new JsonWebTokenError('iat required when maxAge is specified')); + } + + const maxAgeTimestamp = timespan(options.maxAge, payload.iat); + if (typeof maxAgeTimestamp === 'undefined') { + return done(new JsonWebTokenError('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + if (clockTimestamp >= maxAgeTimestamp + (options.clockTolerance || 0)) { + return done(new TokenExpiredError('maxAge exceeded', new Date(maxAgeTimestamp * 1000))); + } + } + + if (options.complete === true) { + const signature = decodedToken.signature; + + return done(null, { + header: header, + payload: payload, + signature: signature + }); + } + + return done(null, payload); + }); +}; diff --git a/node_modules/jwa/LICENSE b/node_modules/jwa/LICENSE new file mode 100644 index 0000000..caeb849 --- /dev/null +++ b/node_modules/jwa/LICENSE @@ -0,0 +1,17 @@ +Copyright (c) 2013 Brian J. Brennan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the +Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/jwa/README.md b/node_modules/jwa/README.md new file mode 100644 index 0000000..09e9648 --- /dev/null +++ b/node_modules/jwa/README.md @@ -0,0 +1,150 @@ +# node-jwa [![Build Status](https://travis-ci.org/brianloveswords/node-jwa.svg?branch=master)](https://travis-ci.org/brianloveswords/node-jwa) + +A +[JSON Web Algorithms](http://tools.ietf.org/id/draft-ietf-jose-json-web-algorithms-08.html) +implementation focusing (exclusively, at this point) on the algorithms necessary for +[JSON Web Signatures](http://self-issued.info/docs/draft-ietf-jose-json-web-signature.html). + +This library supports all of the required, recommended and optional cryptographic algorithms for JWS: + +alg Parameter Value | Digital Signature or MAC Algorithm +----------------|---------------------------- +HS256 | HMAC using SHA-256 hash algorithm +HS384 | HMAC using SHA-384 hash algorithm +HS512 | HMAC using SHA-512 hash algorithm +RS256 | RSASSA using SHA-256 hash algorithm +RS384 | RSASSA using SHA-384 hash algorithm +RS512 | RSASSA using SHA-512 hash algorithm +PS256 | RSASSA-PSS using SHA-256 hash algorithm +PS384 | RSASSA-PSS using SHA-384 hash algorithm +PS512 | RSASSA-PSS using SHA-512 hash algorithm +ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm +ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm +ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm +none | No digital signature or MAC value included + +Please note that PS* only works on Node 6.12+ (excluding 7.x). + +# Requirements + +In order to run the tests, a recent version of OpenSSL is +required. **The version that comes with OS X (OpenSSL 0.9.8r 8 Feb +2011) is not recent enough**, as it does not fully support ECDSA +keys. You'll need to use a version > 1.0.0; I tested with OpenSSL 1.0.1c 10 May 2012. + +# Testing + +To run the tests, do + +```bash +$ npm test +``` + +This will generate a bunch of keypairs to use in testing. If you want to +generate new keypairs, do `make clean` before running `npm test` again. + +## Methodology + +I spawn `openssl dgst -sign` to test OpenSSL sign → JS verify and +`openssl dgst -verify` to test JS sign → OpenSSL verify for each of the +RSA and ECDSA algorithms. + +# Usage + +## jwa(algorithm) + +Creates a new `jwa` object with `sign` and `verify` methods for the +algorithm. Valid values for algorithm can be found in the table above +(`'HS256'`, `'HS384'`, etc) and are case-sensitive. Passing an invalid +algorithm value will throw a `TypeError`. + + +## jwa#sign(input, secretOrPrivateKey) + +Sign some input with either a secret for HMAC algorithms, or a private +key for RSA and ECDSA algorithms. + +If input is not already a string or buffer, `JSON.stringify` will be +called on it to attempt to coerce it. + +For the HMAC algorithm, `secretOrPrivateKey` should be a string or a +buffer. For ECDSA and RSA, the value should be a string representing a +PEM encoded **private** key. + +Output [base64url](http://en.wikipedia.org/wiki/Base64#URL_applications) +formatted. This is for convenience as JWS expects the signature in this +format. If your application needs the output in a different format, +[please open an issue](https://github.com/brianloveswords/node-jwa/issues). In +the meantime, you can use +[brianloveswords/base64url](https://github.com/brianloveswords/base64url) +to decode the signature. + +As of nodejs *v0.11.8*, SPKAC support was introduce. If your nodeJs +version satisfies, then you can pass an object `{ key: '..', passphrase: '...' }` + + +## jwa#verify(input, signature, secretOrPublicKey) + +Verify a signature. Returns `true` or `false`. + +`signature` should be a base64url encoded string. + +For the HMAC algorithm, `secretOrPublicKey` should be a string or a +buffer. For ECDSA and RSA, the value should be a string represented a +PEM encoded **public** key. + + +# Example + +HMAC +```js +const jwa = require('jwa'); + +const hmac = jwa('HS256'); +const input = 'super important stuff'; +const secret = 'shhhhhh'; + +const signature = hmac.sign(input, secret); +hmac.verify(input, signature, secret) // === true +hmac.verify(input, signature, 'trickery!') // === false +``` + +With keys +```js +const fs = require('fs'); +const jwa = require('jwa'); +const privateKey = fs.readFileSync(__dirname + '/ecdsa-p521-private.pem'); +const publicKey = fs.readFileSync(__dirname + '/ecdsa-p521-public.pem'); + +const ecdsa = jwa('ES512'); +const input = 'very important stuff'; + +const signature = ecdsa.sign(input, privateKey); +ecdsa.verify(input, signature, publicKey) // === true +``` +## License + +MIT + +``` +Copyright (c) 2013 Brian J. Brennan + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` diff --git a/node_modules/jwa/index.js b/node_modules/jwa/index.js new file mode 100644 index 0000000..5072c34 --- /dev/null +++ b/node_modules/jwa/index.js @@ -0,0 +1,266 @@ +var Buffer = require('safe-buffer').Buffer; +var crypto = require('crypto'); +var formatEcdsa = require('ecdsa-sig-formatter'); +var util = require('util'); + +var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".' +var MSG_INVALID_SECRET = 'secret must be a string or buffer'; +var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer'; +var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object'; + +var supportsKeyObjects = typeof crypto.createPublicKey === 'function'; +if (supportsKeyObjects) { + MSG_INVALID_VERIFIER_KEY += ' or a KeyObject'; + MSG_INVALID_SECRET += 'or a KeyObject'; +} + +function checkIsPublicKey(key) { + if (Buffer.isBuffer(key)) { + return; + } + + if (typeof key === 'string') { + return; + } + + if (!supportsKeyObjects) { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key !== 'object') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key.type !== 'string') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key.asymmetricKeyType !== 'string') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key.export !== 'function') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } +}; + +function checkIsPrivateKey(key) { + if (Buffer.isBuffer(key)) { + return; + } + + if (typeof key === 'string') { + return; + } + + if (typeof key === 'object') { + return; + } + + throw typeError(MSG_INVALID_SIGNER_KEY); +}; + +function checkIsSecretKey(key) { + if (Buffer.isBuffer(key)) { + return; + } + + if (typeof key === 'string') { + return key; + } + + if (!supportsKeyObjects) { + throw typeError(MSG_INVALID_SECRET); + } + + if (typeof key !== 'object') { + throw typeError(MSG_INVALID_SECRET); + } + + if (key.type !== 'secret') { + throw typeError(MSG_INVALID_SECRET); + } + + if (typeof key.export !== 'function') { + throw typeError(MSG_INVALID_SECRET); + } +} + +function fromBase64(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} + +function toBase64(base64url) { + base64url = base64url.toString(); + + var padding = 4 - base64url.length % 4; + if (padding !== 4) { + for (var i = 0; i < padding; ++i) { + base64url += '='; + } + } + + return base64url + .replace(/\-/g, '+') + .replace(/_/g, '/'); +} + +function typeError(template) { + var args = [].slice.call(arguments, 1); + var errMsg = util.format.bind(util, template).apply(null, args); + return new TypeError(errMsg); +} + +function bufferOrString(obj) { + return Buffer.isBuffer(obj) || typeof obj === 'string'; +} + +function normalizeInput(thing) { + if (!bufferOrString(thing)) + thing = JSON.stringify(thing); + return thing; +} + +function createHmacSigner(bits) { + return function sign(thing, secret) { + checkIsSecretKey(secret); + thing = normalizeInput(thing); + var hmac = crypto.createHmac('sha' + bits, secret); + var sig = (hmac.update(thing), hmac.digest('base64')) + return fromBase64(sig); + } +} + +var bufferEqual; +var timingSafeEqual = 'timingSafeEqual' in crypto ? function timingSafeEqual(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + + return crypto.timingSafeEqual(a, b) +} : function timingSafeEqual(a, b) { + if (!bufferEqual) { + bufferEqual = require('buffer-equal-constant-time'); + } + + return bufferEqual(a, b) +} + +function createHmacVerifier(bits) { + return function verify(thing, signature, secret) { + var computedSig = createHmacSigner(bits)(thing, secret); + return timingSafeEqual(Buffer.from(signature), Buffer.from(computedSig)); + } +} + +function createKeySigner(bits) { + return function sign(thing, privateKey) { + checkIsPrivateKey(privateKey); + thing = normalizeInput(thing); + // Even though we are specifying "RSA" here, this works with ECDSA + // keys as well. + var signer = crypto.createSign('RSA-SHA' + bits); + var sig = (signer.update(thing), signer.sign(privateKey, 'base64')); + return fromBase64(sig); + } +} + +function createKeyVerifier(bits) { + return function verify(thing, signature, publicKey) { + checkIsPublicKey(publicKey); + thing = normalizeInput(thing); + signature = toBase64(signature); + var verifier = crypto.createVerify('RSA-SHA' + bits); + verifier.update(thing); + return verifier.verify(publicKey, signature, 'base64'); + } +} + +function createPSSKeySigner(bits) { + return function sign(thing, privateKey) { + checkIsPrivateKey(privateKey); + thing = normalizeInput(thing); + var signer = crypto.createSign('RSA-SHA' + bits); + var sig = (signer.update(thing), signer.sign({ + key: privateKey, + padding: crypto.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST + }, 'base64')); + return fromBase64(sig); + } +} + +function createPSSKeyVerifier(bits) { + return function verify(thing, signature, publicKey) { + checkIsPublicKey(publicKey); + thing = normalizeInput(thing); + signature = toBase64(signature); + var verifier = crypto.createVerify('RSA-SHA' + bits); + verifier.update(thing); + return verifier.verify({ + key: publicKey, + padding: crypto.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST + }, signature, 'base64'); + } +} + +function createECDSASigner(bits) { + var inner = createKeySigner(bits); + return function sign() { + var signature = inner.apply(null, arguments); + signature = formatEcdsa.derToJose(signature, 'ES' + bits); + return signature; + }; +} + +function createECDSAVerifer(bits) { + var inner = createKeyVerifier(bits); + return function verify(thing, signature, publicKey) { + signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64'); + var result = inner(thing, signature, publicKey); + return result; + }; +} + +function createNoneSigner() { + return function sign() { + return ''; + } +} + +function createNoneVerifier() { + return function verify(thing, signature) { + return signature === ''; + } +} + +module.exports = function jwa(algorithm) { + var signerFactories = { + hs: createHmacSigner, + rs: createKeySigner, + ps: createPSSKeySigner, + es: createECDSASigner, + none: createNoneSigner, + } + var verifierFactories = { + hs: createHmacVerifier, + rs: createKeyVerifier, + ps: createPSSKeyVerifier, + es: createECDSAVerifer, + none: createNoneVerifier, + } + var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/); + if (!match) + throw typeError(MSG_INVALID_ALGORITHM, algorithm); + var algo = (match[1] || match[3]).toLowerCase(); + var bits = match[2]; + + return { + sign: signerFactories[algo](bits), + verify: verifierFactories[algo](bits), + } +}; diff --git a/node_modules/jwa/opslevel.yml b/node_modules/jwa/opslevel.yml new file mode 100644 index 0000000..aeeeea7 --- /dev/null +++ b/node_modules/jwa/opslevel.yml @@ -0,0 +1,6 @@ +--- +version: 1 +repository: + owner: iam_protocols + tier: + tags: diff --git a/node_modules/jwa/package.json b/node_modules/jwa/package.json new file mode 100644 index 0000000..fd5824a --- /dev/null +++ b/node_modules/jwa/package.json @@ -0,0 +1,37 @@ +{ + "name": "jwa", + "version": "2.0.1", + "description": "JWA implementation (supports all JWS algorithms)", + "main": "index.js", + "directories": { + "test": "test" + }, + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + }, + "devDependencies": { + "base64url": "^2.0.0", + "jwk-to-pem": "^2.0.1", + "semver": "4.3.6", + "tap": "6.2.0" + }, + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/brianloveswords/node-jwa.git" + }, + "keywords": [ + "jwa", + "jws", + "jwt", + "rsa", + "ecdsa", + "hmac" + ], + "author": "Brian J. Brennan ", + "license": "MIT" +} diff --git a/node_modules/jwks-rsa/LICENSE b/node_modules/jwks-rsa/LICENSE new file mode 100644 index 0000000..006c80b --- /dev/null +++ b/node_modules/jwks-rsa/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Sandrino Di Mattia + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jwks-rsa/README.md b/node_modules/jwks-rsa/README.md new file mode 100644 index 0000000..52c9f64 --- /dev/null +++ b/node_modules/jwks-rsa/README.md @@ -0,0 +1,83 @@ +![A library to retrieve signing keys from a JWKS (JSON Web Key Set) endpoint.](https://cdn.auth0.com/website/sdks/banner/node-jwks-rsa-banner.png) + +![Release](https://img.shields.io/npm/v/jwks-rsa) +[![Codecov](https://img.shields.io/codecov/c/github/auth0/node-jwks-rsa)](https://codecov.io/gh/auth0/node-jwks-rsa) +![Downloads](https://img.shields.io/npm/dw/jwks-rsa) +[![License](https://img.shields.io/:license-mit-blue.svg?style=flat)](https://opensource.org/licenses/MIT) +![CircleCI](https://img.shields.io/circleci/build/github/auth0/node-jwks-rsa) + +📚 [Documentation](#documentation) - 🚀 [Getting Started](#getting-started) - 💬 [Feedback](#feedback) + +## Documentation + +- [Examples](https://github.com/auth0/node-jwks-rsa/blob/master/EXAMPLES.md) - documentation of the options and code samples for common scenarios. +- [Docs Site](https://auth0.com/docs) - explore our Docs site and learn more about Auth0. + +## Getting Started + +### Installation + +Using [npm](https://npmjs.org) in your project directory run the following command: + +````bash +npm install --save jwks-rsa +```` + +Supports all currently registered JWK types and JWS Algorithms, see [panva/jose#262](https://github.com/panva/jose/issues/262) for more information. + +### Configure the client + +Provide a JWKS endpoint which exposes your signing keys. + +````js +const jwksClient = require('jwks-rsa'); + +const client = jwksClient({ + jwksUri: 'https://sandrino.auth0.com/.well-known/jwks.json', + requestHeaders: {}, // Optional + timeout: 30000 // Defaults to 30s +}); +```` + +### Retrieve a key + +Then use `getSigningKey` to retrieve a signing key that matches a specific `kid`. + +````js +const kid = 'RkI5MjI5OUY5ODc1N0Q4QzM0OUYzNkVGMTJDOUEzQkFCOTU3NjE2Rg'; +const key = await client.getSigningKey(kid); +const signingKey = key.getPublicKey(); +```` + +## Feedback + +### Contributing + +We appreciate feedback and contribution to this repo! Before you get started, please see the following: + +- [Auth0's general contribution guidelines](https://github.com/auth0/open-source-template/blob/master/GENERAL-CONTRIBUTING.md) +- [Auth0's code of conduct guidelines](https://github.com/auth0/open-source-template/blob/master/CODE-OF-CONDUCT.md) + +### Raise an issue + +To provide feedback or report a bug, please [raise an issue on our issue tracker](https://github.com/auth0/node-jwks-rsa/issues). + +### Vulnerability Reporting + +Please do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/whitehat) details the procedure for disclosing security issues. + +## What is Auth0? + +

                          + + + + Auth0 Logo + +

                          +

                          + Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0? +

                          +

                          + This project is licensed under the MIT license. See the LICENSE file for more info. +

                          diff --git a/node_modules/jwks-rsa/index.d.ts b/node_modules/jwks-rsa/index.d.ts new file mode 100644 index 0000000..82db08d --- /dev/null +++ b/node_modules/jwks-rsa/index.d.ts @@ -0,0 +1,130 @@ +import { Agent as HttpAgent } from 'http'; +import { Agent as HttpsAgent } from 'https'; +import type {Jwt, Secret} from 'jsonwebtoken' +import Express = require('express') + +declare function JwksRsa(options: JwksRsa.Options): JwksRsa.JwksClient; + +declare namespace JwksRsa { + class JwksClient { + constructor(options: Options); + + getKeys(): Promise; + getSigningKeys(): Promise; + getSigningKey(kid?: string | null | undefined): Promise; + getSigningKey(kid: string | null | undefined, cb: (err: Error | null, key?: SigningKey) => void): void; + } + + interface Headers { + [key: string]: string; + } + + interface Options { + jwksUri: string; + rateLimit?: boolean; + cache?: boolean; + cacheMaxEntries?: number; + cacheMaxAge?: number; + jwksRequestsPerMinute?: number; + proxy?: string; + requestHeaders?: Headers; + timeout?: number; + requestAgent?: HttpAgent | HttpsAgent; + fetcher?(jwksUri: string): Promise<{ keys: any }>; + getKeysInterceptor?(): Promise; + } + + interface JSONWebKey { + kid: string, + alg: string, + [key: string]: any + } + + interface CertSigningKey { + kid: string; + alg: string; + getPublicKey(): string; + publicKey: string; + } + + interface RsaSigningKey { + kid: string; + alg: string; + getPublicKey(): string; + rsaPublicKey: string; + } + + type SigningKey = CertSigningKey | RsaSigningKey; + + /** + * Types are duplicated from express-jwt@6/7 + * due to numerous breaking changes in the lib's types + * whilst this lib supportd both <=6 & >=7 implementations + * + * express-jwt's installed version (or its @types) + * will be the types used at transpilation time + */ + + /** Types from express-jwt@<=6 */ + type secretType = string|Buffer; + type SecretCallbackLong = (req: unknown, header: any, payload: any, done: (err: any, secret?: secretType) => void) => void; + type SecretCallback = (req: unknown, payload: any, done: (err: any, secret?: secretType) => void) => void; + + /** Types from express-jwt@>=7 */ + type GetVerificationKey = (req: unknown, token: Jwt | undefined) => Secret | undefined | Promise; + + function expressJwtSecret(options: ExpressJwtOptions): SecretCallbackLong & GetVerificationKey; + + function passportJwtSecret(options: ExpressJwtOptions): SecretCallback; + + interface ExpressJwtOptions extends Options { + handleSigningKeyError?: (err: Error | null, cb: (err: Error | null) => void) => void; + } + + function hapiJwt2Key(options: HapiJwtOptions): (decodedToken: DecodedToken, cb: HapiCallback) => void; + + interface HapiJwtOptions extends Options { + handleSigningKeyError?: (err: Error | null, cb: HapiCallback) => void; + } + + type HapiCallback = (err: Error | null, publicKey: string, signingKey: SigningKey) => void; + + interface DecodedToken { + header: TokenHeader; + } + + interface TokenHeader { + alg: string; + kid: string; + } + + function hapiJwt2KeyAsync(options: HapiJwtOptions): (decodedToken: DecodedToken) => Promise<{ key: string }>; + + function koaJwtSecret(options: KoaJwtOptions): (header: TokenHeader) => Promise; + + interface KoaJwtOptions extends Options { + handleSigningKeyError?(err: Error | null): Promise; + } + + class ArgumentError extends Error { + name: 'ArgumentError'; + constructor(message: string); + } + + class JwksError extends Error { + name: 'JwksError'; + constructor(message: string); + } + + class JwksRateLimitError extends Error { + name: 'JwksRateLimitError'; + constructor(message: string); + } + + class SigningKeyNotFoundError extends Error { + name: 'SigningKeyNotFoundError'; + constructor(message: string); + } +} + +export = JwksRsa; diff --git a/node_modules/jwks-rsa/package.json b/node_modules/jwks-rsa/package.json new file mode 100644 index 0000000..b9d3ff1 --- /dev/null +++ b/node_modules/jwks-rsa/package.json @@ -0,0 +1,74 @@ +{ + "name": "jwks-rsa", + "version": "3.2.0", + "description": "Library to retrieve RSA public keys from a JWKS endpoint", + "main": "src/index.js", + "files": [ + "src", + "index.d.ts" + ], + "types": "index.d.ts", + "engines": { + "node": ">=14" + }, + "dependencies": { + "@types/express": "^4.17.20", + "@types/jsonwebtoken": "^9.0.4", + "debug": "^4.3.4", + "jose": "^4.15.4", + "limiter": "^1.1.5", + "lru-memoizer": "^2.2.0" + }, + "devDependencies": { + "@types/chai": "^4.3.9", + "@types/express-jwt-v6": "npm:@types/express-jwt@^6.0.4", + "@types/mocha": "^10.0.3", + "@types/nock": "^11.0.0", + "@types/node": "^20.8.10", + "chai": "^4.3.10", + "chai-as-promised": "^7.1.1", + "eslint": "^8.52.0", + "express": "^4.18.2", + "express-jwt": "^8.4.1", + "express-jwt-v6": "npm:express-jwt@^6.1.2", + "express-jwt-v7": "npm:express-jwt@^7.5.0", + "jose2": "npm:jose@^2.0.6", + "jsonwebtoken": "^9.0.2", + "koa": "^2.14.2", + "koa-jwt": "^4.0.4", + "mocha": "^10.2.0", + "nock": "^13.3.7", + "nyc": "^15.1.0", + "passport": "^0.6.0", + "passport-jwt": "^4.0.1", + "rimraf": "^5.0.5", + "supertest": "^6.3.3", + "ts-node": "^10.9.1", + "typescript": "^5.2.2" + }, + "scripts": { + "clean:ts": "rimraf ts-output/", + "lint": "eslint ./src ./tests", + "test:ts": "npm run clean:ts && tsc && NODE_ENV=test mocha --exit --timeout 5000 $(find ./ts-output -name *.tests.js)", + "test:js": "NODE_ENV=test mocha --exit --timeout 5000 $(find ./tests -name *.tests.js)", + "test": "npm run test:js && npm run test:ts", + "test:ci": "nyc --reporter=lcov npm test", + "test-watch": "NODE_ENV=test mocha --exit --timeout 5000 $(find ./tests -name *.tests.js) --watch", + "release": "git tag $npm_package_version && git push && git push --tags && npm publish" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/auth0/node-jwks-rsa.git" + }, + "keywords": [ + "jwks", + "rsa", + "jwt" + ], + "author": "Auth0", + "license": "MIT", + "bugs": { + "url": "https://github.com/auth0/node-jwks-rsa/issues" + }, + "homepage": "https://github.com/auth0/node-jwks-rsa#readme" +} diff --git a/node_modules/jwks-rsa/src/JwksClient.js b/node_modules/jwks-rsa/src/JwksClient.js new file mode 100644 index 0000000..80f290a --- /dev/null +++ b/node_modules/jwks-rsa/src/JwksClient.js @@ -0,0 +1,91 @@ +const logger = require('debug')('jwks'); +const { retrieveSigningKeys } = require('./utils') ; +const { request, cacheSigningKey, rateLimitSigningKey, getKeysInterceptor, callbackSupport } = require('./wrappers'); +const JwksError = require('./errors/JwksError'); +const SigningKeyNotFoundError = require('./errors/SigningKeyNotFoundError'); + +class JwksClient { + constructor(options) { + this.options = { + rateLimit: false, + cache: true, + timeout: 30000, + ...options + }; + + // Initialize wrappers. + if (this.options.getKeysInterceptor) { + this.getSigningKey = getKeysInterceptor(this, options); + } + + if (this.options.rateLimit) { + this.getSigningKey = rateLimitSigningKey(this, options); + } + if (this.options.cache) { + this.getSigningKey = cacheSigningKey(this, options); + } + + this.getSigningKey = callbackSupport(this, options); + } + + async getKeys() { + logger(`Fetching keys from '${this.options.jwksUri}'`); + + try { + const res = await request({ + uri: this.options.jwksUri, + headers: this.options.requestHeaders, + agent: this.options.requestAgent, + timeout: this.options.timeout, + fetcher: this.options.fetcher + }); + + logger('Keys:', res.keys); + return res.keys; + } catch (err) { + const { errorMsg } = err; + logger('Failure:', errorMsg || err); + throw (errorMsg ? new JwksError(errorMsg) : err); + } + } + + async getSigningKeys() { + const keys = await this.getKeys(); + + if (!keys || !keys.length) { + throw new JwksError('The JWKS endpoint did not contain any keys'); + } + + const signingKeys = await retrieveSigningKeys(keys); + + if (!signingKeys.length) { + throw new JwksError('The JWKS endpoint did not contain any signing keys'); + } + + logger('Signing Keys:', signingKeys); + return signingKeys; + } + + async getSigningKey (kid) { + logger(`Fetching signing key for '${kid}'`); + const keys = await this.getSigningKeys(); + + const kidDefined = kid !== undefined && kid !== null; + if (!kidDefined && keys.length > 1) { + logger('No KID specified and JWKS endpoint returned more than 1 key'); + throw new SigningKeyNotFoundError('No KID specified and JWKS endpoint returned more than 1 key'); + } + + const key = keys.find(k => !kidDefined || k.kid === kid); + if (key) { + return key; + } else { + logger(`Unable to find a signing key that matches '${kid}'`); + throw new SigningKeyNotFoundError(`Unable to find a signing key that matches '${kid}'`); + } + } +} + +module.exports = { + JwksClient +}; diff --git a/node_modules/jwks-rsa/src/errors/ArgumentError.js b/node_modules/jwks-rsa/src/errors/ArgumentError.js new file mode 100644 index 0000000..d9bcd75 --- /dev/null +++ b/node_modules/jwks-rsa/src/errors/ArgumentError.js @@ -0,0 +1,10 @@ +function ArgumentError(message) { + Error.call(this, message); + Error.captureStackTrace(this, this.constructor); + this.name = 'ArgumentError'; + this.message = message; +} + +ArgumentError.prototype = Object.create(Error.prototype); +ArgumentError.prototype.constructor = ArgumentError; +module.exports = ArgumentError; diff --git a/node_modules/jwks-rsa/src/errors/JwksError.js b/node_modules/jwks-rsa/src/errors/JwksError.js new file mode 100644 index 0000000..26fb9a8 --- /dev/null +++ b/node_modules/jwks-rsa/src/errors/JwksError.js @@ -0,0 +1,10 @@ +function JwksError(message) { + Error.call(this, message); + Error.captureStackTrace(this, this.constructor); + this.name = 'JwksError'; + this.message = message; +} + +JwksError.prototype = Object.create(Error.prototype); +JwksError.prototype.constructor = JwksError; +module.exports = JwksError; diff --git a/node_modules/jwks-rsa/src/errors/JwksRateLimitError.js b/node_modules/jwks-rsa/src/errors/JwksRateLimitError.js new file mode 100644 index 0000000..4d0cad3 --- /dev/null +++ b/node_modules/jwks-rsa/src/errors/JwksRateLimitError.js @@ -0,0 +1,10 @@ +function JwksRateLimitError(message) { + Error.call(this, message); + Error.captureStackTrace(this, this.constructor); + this.name = 'JwksRateLimitError'; + this.message = message; +} + +JwksRateLimitError.prototype = Object.create(Error.prototype); +JwksRateLimitError.prototype.constructor = JwksRateLimitError; +module.exports = JwksRateLimitError; diff --git a/node_modules/jwks-rsa/src/errors/SigningKeyNotFoundError.js b/node_modules/jwks-rsa/src/errors/SigningKeyNotFoundError.js new file mode 100644 index 0000000..9b8bdcd --- /dev/null +++ b/node_modules/jwks-rsa/src/errors/SigningKeyNotFoundError.js @@ -0,0 +1,10 @@ +function SigningKeyNotFoundError(message) { + Error.call(this, message); + Error.captureStackTrace(this, this.constructor); + this.name = 'SigningKeyNotFoundError'; + this.message = message; +} + +SigningKeyNotFoundError.prototype = Object.create(Error.prototype); +SigningKeyNotFoundError.prototype.constructor = SigningKeyNotFoundError; +module.exports = SigningKeyNotFoundError; diff --git a/node_modules/jwks-rsa/src/errors/index.js b/node_modules/jwks-rsa/src/errors/index.js new file mode 100644 index 0000000..8fc3d9a --- /dev/null +++ b/node_modules/jwks-rsa/src/errors/index.js @@ -0,0 +1,6 @@ +module.exports = { + ArgumentError: require('./ArgumentError'), + JwksError: require('./JwksError'), + JwksRateLimitError: require('./JwksRateLimitError'), + SigningKeyNotFoundError: require('./SigningKeyNotFoundError') +}; diff --git a/node_modules/jwks-rsa/src/index.js b/node_modules/jwks-rsa/src/index.js new file mode 100644 index 0000000..74fb91b --- /dev/null +++ b/node_modules/jwks-rsa/src/index.js @@ -0,0 +1,22 @@ +const { JwksClient } = require('./JwksClient'); +const errors = require('./errors'); +const { hapiJwt2Key, hapiJwt2KeyAsync } = require('./integrations/hapi'); +const { expressJwtSecret } = require('./integrations/express'); +const { koaJwtSecret } = require('./integrations/koa'); +const { passportJwtSecret } = require('./integrations/passport'); + +module.exports = (options) => { + return new JwksClient(options); +}; +module.exports.JwksClient = JwksClient; + +module.exports.ArgumentError = errors.ArgumentError; +module.exports.JwksError = errors.JwksError; +module.exports.JwksRateLimitError = errors.JwksRateLimitError; +module.exports.SigningKeyNotFoundError = errors.SigningKeyNotFoundError; + +module.exports.expressJwtSecret = expressJwtSecret; +module.exports.hapiJwt2Key = hapiJwt2Key; +module.exports.hapiJwt2KeyAsync = hapiJwt2KeyAsync; +module.exports.koaJwtSecret = koaJwtSecret; +module.exports.passportJwtSecret = passportJwtSecret; diff --git a/node_modules/jwks-rsa/src/integrations/config.js b/node_modules/jwks-rsa/src/integrations/config.js new file mode 100644 index 0000000..498a582 --- /dev/null +++ b/node_modules/jwks-rsa/src/integrations/config.js @@ -0,0 +1,15 @@ +const allowedSignatureAlg = [ + 'RS256', + 'RS384', + 'RS512', + 'PS256', + 'PS384', + 'PS512', + 'ES256', + 'ES256K', + 'ES384', + 'ES512', + 'EdDSA' +]; + +module.exports = allowedSignatureAlg; diff --git a/node_modules/jwks-rsa/src/integrations/express.js b/node_modules/jwks-rsa/src/integrations/express.js new file mode 100644 index 0000000..ecacf65 --- /dev/null +++ b/node_modules/jwks-rsa/src/integrations/express.js @@ -0,0 +1,60 @@ +const { ArgumentError } = require('../errors'); +const { JwksClient } = require('../JwksClient'); +const supportedAlg = require('./config'); + +const handleSigningKeyError = (err, cb) => { + // If we didn't find a match, can't provide a key. + if (err && err.name === 'SigningKeyNotFoundError') { + return cb(null); + } + + // If an error occured like rate limiting or HTTP issue, we'll bubble up the error. + if (err) { + return cb(err); + } +}; + +module.exports.expressJwtSecret = function (options) { + if (options === null || options === undefined) { + throw new ArgumentError('An options object must be provided when initializing expressJwtSecret'); + } + + const client = new JwksClient(options); + const onError = options.handleSigningKeyError || handleSigningKeyError; + + const expressJwt7Provider = async (req, token) => { + if (!token) { return; } + const header = token.header; + if (!header || !supportedAlg.includes(header.alg)) { + return; + } + try { + const key = await client.getSigningKey(header.kid); + return key.publicKey || key.rsaPublicKey; + } catch (err) { + return new Promise((resolve, reject) => { + onError(err, (newError) => { + if (!newError) { return resolve(); } + reject(newError); + }); + }); + } + }; + + return function secretProvider(req, header, payload, cb) { + //This function has 4 parameters to make it work with express-jwt@6 + //but it also supports express-jwt@7 which only has 2. + if (arguments.length === 4) { + expressJwt7Provider(req, { header }) + .then(key => { + setImmediate(cb, null, key); + }).catch(err => { + setImmediate(cb, err); + }); + + return; + } + + return expressJwt7Provider(req, arguments[1]); + }; +}; diff --git a/node_modules/jwks-rsa/src/integrations/hapi.js b/node_modules/jwks-rsa/src/integrations/hapi.js new file mode 100644 index 0000000..cf53972 --- /dev/null +++ b/node_modules/jwks-rsa/src/integrations/hapi.js @@ -0,0 +1,59 @@ +const { ArgumentError } = require('../errors'); +const { JwksClient } = require('../JwksClient'); +const supportedAlg = require('./config'); + +const handleSigningKeyError = (err, cb) => { + // If we didn't find a match, can't provide a key. + if (err && err.name === 'SigningKeyNotFoundError') { + return cb(err, null, null); + } + + // If an error occured like rate limiting or HTTP issue, we'll bubble up the error. + if (err) { + return cb(err, null, null); + } +}; + +/** + * Call hapiJwt2Key as a Promise + * @param {object} options + * @returns {Promise} + */ +module.exports.hapiJwt2KeyAsync = (options) => { + const secretProvider = module.exports.hapiJwt2Key(options); + return function(decoded) { + return new Promise((resolve, reject) => { + const cb = (err, key) => { + (!key || err) ? reject(err) : resolve({ key }); + }; + secretProvider(decoded, cb); + }); + }; +}; + +module.exports.hapiJwt2Key = function (options) { + if (options === null || options === undefined) { + throw new ArgumentError('An options object must be provided when initializing hapiJwt2Key'); + } + + const client = new JwksClient(options); + const onError = options.handleSigningKeyError || handleSigningKeyError; + + return function secretProvider(decoded, cb) { + // We cannot find a signing certificate if there is no header (no kid). + if (!decoded || !decoded.header) { + return cb(new Error('Cannot find a signing certificate if there is no header'), null, null); + } + + if (!supportedAlg.includes(decoded.header.alg)) { + return cb(new Error('Unsupported algorithm ' + decoded.header.alg + ' supplied.'), null, null); + } + + client.getSigningKey(decoded.header.kid) + .then(key => { + return cb(null, key.publicKey || key.rsaPublicKey, key); + }).catch(err => { + return onError(err, (newError) => cb(newError, null, null)); + }); + }; +}; diff --git a/node_modules/jwks-rsa/src/integrations/koa.js b/node_modules/jwks-rsa/src/integrations/koa.js new file mode 100644 index 0000000..9185bfc --- /dev/null +++ b/node_modules/jwks-rsa/src/integrations/koa.js @@ -0,0 +1,30 @@ +const { ArgumentError } = require('../errors'); +const { JwksClient } = require('../JwksClient'); +const supportedAlg = require('./config'); + +module.exports.koaJwtSecret = function (options = {}) { + if (!options.jwksUri) { + throw new ArgumentError('No JWKS provided. Please provide a jwksUri'); + } + + const client = new JwksClient(options); + + return function secretProvider({ alg, kid } = {}) { + return new Promise((resolve, reject) => { + if (!supportedAlg.includes(alg)) { + return reject(new Error('Missing / invalid token algorithm')); + } + + client.getSigningKey(kid) + .then(key => { + resolve(key.publicKey || key.rsaPublicKey); + }).catch(err => { + if (options.handleSigningKeyError) { + return options.handleSigningKeyError(err).then(reject); + } + + return reject(err); + }); + }); + }; +}; diff --git a/node_modules/jwks-rsa/src/integrations/passport.js b/node_modules/jwks-rsa/src/integrations/passport.js new file mode 100644 index 0000000..79d75da --- /dev/null +++ b/node_modules/jwks-rsa/src/integrations/passport.js @@ -0,0 +1,52 @@ +const jose = require('jose'); +const { ArgumentError } = require('../errors'); +const { JwksClient } = require('../JwksClient'); +const supportedAlg = require('./config'); + +const handleSigningKeyError = (err, cb) => { + // If we didn't find a match, can't provide a key. + if (err && err.name === 'SigningKeyNotFoundError') { + return cb(null); + } + + // If an error occured like rate limiting or HTTP issue, we'll bubble up the error. + if (err) { + return cb(err); + } +}; + +module.exports.passportJwtSecret = function (options) { + if (options === null || options === undefined) { + throw new ArgumentError('An options object must be provided when initializing passportJwtSecret'); + } + + if (!options.jwksUri) { + throw new ArgumentError('No JWKS provided. Please provide a jwksUri'); + } + + const client = new JwksClient(options); + const onError = options.handleSigningKeyError || handleSigningKeyError; + + return function secretProvider(req, rawJwtToken, cb) { + let decoded; + try { + decoded = { + payload: jose.decodeJwt(rawJwtToken), + header: jose.decodeProtectedHeader(rawJwtToken) + }; + } catch (err) { + decoded = null; + } + + if (!decoded || !supportedAlg.includes(decoded.header.alg)) { + return cb(null, null); + } + + client.getSigningKey(decoded.header.kid) + .then(key => { + cb(null, key.publicKey || key.rsaPublicKey); + }).catch(err => { + onError(err, (newError) => cb(newError, null)); + }); + }; +}; diff --git a/node_modules/jwks-rsa/src/utils.js b/node_modules/jwks-rsa/src/utils.js new file mode 100644 index 0000000..3b82d11 --- /dev/null +++ b/node_modules/jwks-rsa/src/utils.js @@ -0,0 +1,80 @@ +const jose = require('jose'); +const JwksError = require('./errors/JwksError'); + +function resolveAlg(jwk) { + if (jwk.alg) { + return jwk.alg; + } + + if (jwk.kty === 'RSA') { + return 'RS256'; + } + + if (jwk.kty === 'EC') { + switch (jwk.crv) { + case 'P-256': + return 'ES256'; + case 'secp256k1': + return 'ES256K'; + case 'P-384': + return 'ES384'; + case 'P-521': + return 'ES512'; + } + } + + if (jwk.kty === 'OKP') { + switch (jwk.crv) { + case 'Ed25519': + case 'Ed448': + return 'EdDSA'; + } + } + + throw new JwksError('Unsupported JWK'); +} + +async function retrieveSigningKeys(jwks) { + const results = []; + + jwks = jwks + .filter(({ use }) => use === 'sig' || use === undefined) + .filter(({ kty }) => kty === 'RSA' || kty === 'EC' || kty === 'OKP'); + + for (const jwk of jwks) { + try { + const key = await jose.importJWK({ ...jwk, ext: true }, resolveAlg(jwk)); + if (key.type !== 'public') { + continue; + } + let getSpki; + switch (key[Symbol.toStringTag]) { + case 'CryptoKey': { + const spki = await jose.exportSPKI(key); + getSpki = () => spki; + break; + } + case 'KeyObject': + // Assume legacy Node.js version without the Symbol.toStringTag backported + // Fall through + default: + getSpki = () => key.export({ format: 'pem', type: 'spki' }); + } + results.push({ + get publicKey() { return getSpki(); }, + get rsaPublicKey() { return getSpki(); }, + getPublicKey() { return getSpki(); }, + ...(typeof jwk.kid === 'string' && jwk.kid ? { kid: jwk.kid } : undefined), + ...(typeof jwk.alg === 'string' && jwk.alg ? { alg: jwk.alg } : undefined) + }); + } catch (err) { + continue; + } + } + + return results; +} + +module.exports = { + retrieveSigningKeys +}; diff --git a/node_modules/jwks-rsa/src/wrappers/cache.js b/node_modules/jwks-rsa/src/wrappers/cache.js new file mode 100644 index 0000000..37387ff --- /dev/null +++ b/node_modules/jwks-rsa/src/wrappers/cache.js @@ -0,0 +1,15 @@ +const logger = require('debug')('jwks'); +const memoizer = require('lru-memoizer'); +const { promisify, callbackify } = require('util'); + +function cacheWrapper(client, { cacheMaxEntries = 5, cacheMaxAge = 600000 }) { + logger(`Configured caching of signing keys. Max: ${cacheMaxEntries} / Age: ${cacheMaxAge}`); + return promisify(memoizer({ + hash: (kid) => kid, + load: callbackify(client.getSigningKey.bind(client)), + maxAge: cacheMaxAge, + max: cacheMaxEntries + })); +} + +module.exports.default = cacheWrapper; diff --git a/node_modules/jwks-rsa/src/wrappers/callbackSupport.js b/node_modules/jwks-rsa/src/wrappers/callbackSupport.js new file mode 100644 index 0000000..3748476 --- /dev/null +++ b/node_modules/jwks-rsa/src/wrappers/callbackSupport.js @@ -0,0 +1,16 @@ +const { callbackify } = require('util'); + +const callbackSupport = (client) => { + const getSigningKey = client.getSigningKey.bind(client); + + return (kid, cb) => { + if (cb) { + const callbackFunc = callbackify(getSigningKey); + return callbackFunc(kid, cb); + } + + return getSigningKey(kid); + }; +}; + +module.exports.default = callbackSupport; diff --git a/node_modules/jwks-rsa/src/wrappers/index.js b/node_modules/jwks-rsa/src/wrappers/index.js new file mode 100644 index 0000000..8b9d118 --- /dev/null +++ b/node_modules/jwks-rsa/src/wrappers/index.js @@ -0,0 +1,7 @@ +module.exports = { + request: require('./request').default, + cacheSigningKey: require('./cache').default, + rateLimitSigningKey: require('./rateLimit').default, + getKeysInterceptor: require('./interceptor').default, + callbackSupport: require('./callbackSupport').default +}; diff --git a/node_modules/jwks-rsa/src/wrappers/interceptor.js b/node_modules/jwks-rsa/src/wrappers/interceptor.js new file mode 100644 index 0000000..219b0e8 --- /dev/null +++ b/node_modules/jwks-rsa/src/wrappers/interceptor.js @@ -0,0 +1,30 @@ +const retrieveSigningKeys = require('../utils').retrieveSigningKeys; + +/** + * Uses getKeysInterceptor to allow users to retrieve keys from a file, + * external cache, or provided object before falling back to the jwksUri endpoint + */ +function getKeysInterceptor(client, { getKeysInterceptor }) { + const getSigningKey = client.getSigningKey.bind(client); + + return async (kid) => { + const keys = await getKeysInterceptor(); + + let signingKeys; + if (keys && keys.length) { + signingKeys = await retrieveSigningKeys(keys); + } + + if (signingKeys && signingKeys.length) { + const key = signingKeys.find(k => !kid || k.kid === kid); + + if (key) { + return key; + } + } + + return getSigningKey(kid); + }; +} + +module.exports.default = getKeysInterceptor; diff --git a/node_modules/jwks-rsa/src/wrappers/rateLimit.js b/node_modules/jwks-rsa/src/wrappers/rateLimit.js new file mode 100644 index 0000000..b1837c4 --- /dev/null +++ b/node_modules/jwks-rsa/src/wrappers/rateLimit.js @@ -0,0 +1,34 @@ +const logger = require('debug')('jwks'); +const { RateLimiter } = require('limiter'); + +const JwksRateLimitError = require('../errors/JwksRateLimitError'); + +function rateLimitWrapper(client, { jwksRequestsPerMinute = 10 }) { + const getSigningKey = client.getSigningKey.bind(client); + + const limiter = new RateLimiter(jwksRequestsPerMinute, 'minute', true); + logger(`Configured rate limiting to JWKS endpoint at ${jwksRequestsPerMinute}/minute`); + + return async (kid) => await new Promise((resolve, reject) => { + limiter.removeTokens(1, async (err, remaining) => { + if (err) { + reject(err); + } + + logger('Requests to the JWKS endpoint available for the next minute:', remaining); + if (remaining < 0) { + logger('Too many requests to the JWKS endpoint'); + reject(new JwksRateLimitError('Too many requests to the JWKS endpoint')); + } else { + try { + const key = await getSigningKey(kid); + resolve(key); + } catch (error) { + reject(error); + } + } + }); + }); +} + +module.exports.default = rateLimitWrapper; diff --git a/node_modules/jwks-rsa/src/wrappers/request.js b/node_modules/jwks-rsa/src/wrappers/request.js new file mode 100644 index 0000000..b453c2b --- /dev/null +++ b/node_modules/jwks-rsa/src/wrappers/request.js @@ -0,0 +1,52 @@ +const http = require('http'); +const https = require('https'); +const urlUtil = require('url'); + +module.exports.default = (options) => { + if (options.fetcher) { + return options.fetcher(options.uri); + } + + return new Promise((resolve, reject) => { + const { + hostname, + path, + port, + protocol + } = urlUtil.parse(options.uri); + + const requestOptions = { + hostname, + path, + port, + method: 'GET', + ...(options.headers && { headers: { ...options.headers } }), + ...(options.timeout && { timeout: options.timeout }), + ...(options.agent && { agent: options.agent }) + }; + + const httpRequestLib = protocol === 'https:' ? https : http; + const httpRequest = httpRequestLib.request(requestOptions, (res) => { + let rawData = ''; + res.setEncoding('utf8'); + res.on('data', (chunk) => { rawData += chunk; }); + res.on('end', () => { + if (res.statusCode < 200 || res.statusCode >= 300) { + const errorMsg = res.body && (res.body.message || res.body) || res.statusMessage || `Http Error ${res.statusCode}`; + reject({ errorMsg }); + } else { + try { + resolve(rawData && JSON.parse(rawData)); + } catch (error) { + reject(error); + } + } + }); + }); + + httpRequest + .on('timeout', () => httpRequest.destroy()) + .on('error', (e) => reject(e)) + .end(); + }); +}; diff --git a/node_modules/jws/CHANGELOG.md b/node_modules/jws/CHANGELOG.md new file mode 100644 index 0000000..18078df --- /dev/null +++ b/node_modules/jws/CHANGELOG.md @@ -0,0 +1,56 @@ +# Change Log + +All notable changes to this project will be documented in this file. + +## [4.0.1] + +### Changed + +- Fix advisory GHSA-869p-cjfg-cm3x: createSign and createVerify now require + that a non empty secret is provided (via opts.secret, opts.privateKey or opts.key) + when using HMAC algorithms. +- Upgrading JWA version to 2.0.1, adressing a compatibility issue for Node >= 25. + +## [3.2.3] + +### Changed + +- Fix advisory GHSA-869p-cjfg-cm3x: createSign and createVerify now require + that a non empty secret is provided (via opts.secret, opts.privateKey or opts.key) + when using HMAC algorithms. +- Upgrading JWA version to 1.4.2, adressing a compatibility issue for Node >= 25. + +## [3.0.0] + +### Changed + +- **BREAKING**: `jwt.verify` now requires an `algorithm` parameter, and + `jws.createVerify` requires an `algorithm` option. The `"alg"` field + signature headers is ignored. This mitigates a critical security flaw + in the library which would allow an attacker to generate signatures with + arbitrary contents that would be accepted by `jwt.verify`. See + https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/ + for details. + +## [2.0.0] - 2015-01-30 + +### Changed + +- **BREAKING**: Default payload encoding changed from `binary` to + `utf8`. `utf8` is a is a more sensible default than `binary` because + many payloads, as far as I can tell, will contain user-facing + strings that could be in any language. ([6b6de48]) + +- Code reorganization, thanks [@fearphage]! ([7880050]) + +### Added + +- Option in all relevant methods for `encoding`. For those few users + that might be depending on a `binary` encoding of the messages, this + is for them. ([6b6de48]) + +[unreleased]: https://github.com/brianloveswords/node-jws/compare/v2.0.0...HEAD +[2.0.0]: https://github.com/brianloveswords/node-jws/compare/v1.0.1...v2.0.0 +[7880050]: https://github.com/brianloveswords/node-jws/commit/7880050 +[6b6de48]: https://github.com/brianloveswords/node-jws/commit/6b6de48 +[@fearphage]: https://github.com/fearphage diff --git a/node_modules/jws/LICENSE b/node_modules/jws/LICENSE new file mode 100644 index 0000000..caeb849 --- /dev/null +++ b/node_modules/jws/LICENSE @@ -0,0 +1,17 @@ +Copyright (c) 2013 Brian J. Brennan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the +Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/jws/index.js b/node_modules/jws/index.js new file mode 100644 index 0000000..8c8da93 --- /dev/null +++ b/node_modules/jws/index.js @@ -0,0 +1,22 @@ +/*global exports*/ +var SignStream = require('./lib/sign-stream'); +var VerifyStream = require('./lib/verify-stream'); + +var ALGORITHMS = [ + 'HS256', 'HS384', 'HS512', + 'RS256', 'RS384', 'RS512', + 'PS256', 'PS384', 'PS512', + 'ES256', 'ES384', 'ES512' +]; + +exports.ALGORITHMS = ALGORITHMS; +exports.sign = SignStream.sign; +exports.verify = VerifyStream.verify; +exports.decode = VerifyStream.decode; +exports.isValid = VerifyStream.isValid; +exports.createSign = function createSign(opts) { + return new SignStream(opts); +}; +exports.createVerify = function createVerify(opts) { + return new VerifyStream(opts); +}; diff --git a/node_modules/jws/lib/data-stream.js b/node_modules/jws/lib/data-stream.js new file mode 100644 index 0000000..3535d31 --- /dev/null +++ b/node_modules/jws/lib/data-stream.js @@ -0,0 +1,55 @@ +/*global module, process*/ +var Buffer = require('safe-buffer').Buffer; +var Stream = require('stream'); +var util = require('util'); + +function DataStream(data) { + this.buffer = null; + this.writable = true; + this.readable = true; + + // No input + if (!data) { + this.buffer = Buffer.alloc(0); + return this; + } + + // Stream + if (typeof data.pipe === 'function') { + this.buffer = Buffer.alloc(0); + data.pipe(this); + return this; + } + + // Buffer or String + // or Object (assumedly a passworded key) + if (data.length || typeof data === 'object') { + this.buffer = data; + this.writable = false; + process.nextTick(function () { + this.emit('end', data); + this.readable = false; + this.emit('close'); + }.bind(this)); + return this; + } + + throw new TypeError('Unexpected data type ('+ typeof data + ')'); +} +util.inherits(DataStream, Stream); + +DataStream.prototype.write = function write(data) { + this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]); + this.emit('data', data); +}; + +DataStream.prototype.end = function end(data) { + if (data) + this.write(data); + this.emit('end', data); + this.emit('close'); + this.writable = false; + this.readable = false; +}; + +module.exports = DataStream; diff --git a/node_modules/jws/lib/sign-stream.js b/node_modules/jws/lib/sign-stream.js new file mode 100644 index 0000000..4a7b288 --- /dev/null +++ b/node_modules/jws/lib/sign-stream.js @@ -0,0 +1,83 @@ +/*global module*/ +var Buffer = require('safe-buffer').Buffer; +var DataStream = require('./data-stream'); +var jwa = require('jwa'); +var Stream = require('stream'); +var toString = require('./tostring'); +var util = require('util'); + +function base64url(string, encoding) { + return Buffer + .from(string, encoding) + .toString('base64') + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} + +function jwsSecuredInput(header, payload, encoding) { + encoding = encoding || 'utf8'; + var encodedHeader = base64url(toString(header), 'binary'); + var encodedPayload = base64url(toString(payload), encoding); + return util.format('%s.%s', encodedHeader, encodedPayload); +} + +function jwsSign(opts) { + var header = opts.header; + var payload = opts.payload; + var secretOrKey = opts.secret || opts.privateKey; + var encoding = opts.encoding; + var algo = jwa(header.alg); + var securedInput = jwsSecuredInput(header, payload, encoding); + var signature = algo.sign(securedInput, secretOrKey); + return util.format('%s.%s', securedInput, signature); +} + +function SignStream(opts) { + var secret = opts.secret; + secret = secret == null ? opts.privateKey : secret; + secret = secret == null ? opts.key : secret; + if (/^hs/i.test(opts.header.alg) === true && secret == null) { + throw new TypeError('secret must be a string or buffer or a KeyObject') + } + var secretStream = new DataStream(secret); + this.readable = true; + this.header = opts.header; + this.encoding = opts.encoding; + this.secret = this.privateKey = this.key = secretStream; + this.payload = new DataStream(opts.payload); + this.secret.once('close', function () { + if (!this.payload.writable && this.readable) + this.sign(); + }.bind(this)); + + this.payload.once('close', function () { + if (!this.secret.writable && this.readable) + this.sign(); + }.bind(this)); +} +util.inherits(SignStream, Stream); + +SignStream.prototype.sign = function sign() { + try { + var signature = jwsSign({ + header: this.header, + payload: this.payload.buffer, + secret: this.secret.buffer, + encoding: this.encoding + }); + this.emit('done', signature); + this.emit('data', signature); + this.emit('end'); + this.readable = false; + return signature; + } catch (e) { + this.readable = false; + this.emit('error', e); + this.emit('close'); + } +}; + +SignStream.sign = jwsSign; + +module.exports = SignStream; diff --git a/node_modules/jws/lib/tostring.js b/node_modules/jws/lib/tostring.js new file mode 100644 index 0000000..f5a49a3 --- /dev/null +++ b/node_modules/jws/lib/tostring.js @@ -0,0 +1,10 @@ +/*global module*/ +var Buffer = require('buffer').Buffer; + +module.exports = function toString(obj) { + if (typeof obj === 'string') + return obj; + if (typeof obj === 'number' || Buffer.isBuffer(obj)) + return obj.toString(); + return JSON.stringify(obj); +}; diff --git a/node_modules/jws/lib/verify-stream.js b/node_modules/jws/lib/verify-stream.js new file mode 100644 index 0000000..bb1cb00 --- /dev/null +++ b/node_modules/jws/lib/verify-stream.js @@ -0,0 +1,125 @@ +/*global module*/ +var Buffer = require('safe-buffer').Buffer; +var DataStream = require('./data-stream'); +var jwa = require('jwa'); +var Stream = require('stream'); +var toString = require('./tostring'); +var util = require('util'); +var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; + +function isObject(thing) { + return Object.prototype.toString.call(thing) === '[object Object]'; +} + +function safeJsonParse(thing) { + if (isObject(thing)) + return thing; + try { return JSON.parse(thing); } + catch (e) { return undefined; } +} + +function headerFromJWS(jwsSig) { + var encodedHeader = jwsSig.split('.', 1)[0]; + return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary')); +} + +function securedInputFromJWS(jwsSig) { + return jwsSig.split('.', 2).join('.'); +} + +function signatureFromJWS(jwsSig) { + return jwsSig.split('.')[2]; +} + +function payloadFromJWS(jwsSig, encoding) { + encoding = encoding || 'utf8'; + var payload = jwsSig.split('.')[1]; + return Buffer.from(payload, 'base64').toString(encoding); +} + +function isValidJws(string) { + return JWS_REGEX.test(string) && !!headerFromJWS(string); +} + +function jwsVerify(jwsSig, algorithm, secretOrKey) { + if (!algorithm) { + var err = new Error("Missing algorithm parameter for jws.verify"); + err.code = "MISSING_ALGORITHM"; + throw err; + } + jwsSig = toString(jwsSig); + var signature = signatureFromJWS(jwsSig); + var securedInput = securedInputFromJWS(jwsSig); + var algo = jwa(algorithm); + return algo.verify(securedInput, signature, secretOrKey); +} + +function jwsDecode(jwsSig, opts) { + opts = opts || {}; + jwsSig = toString(jwsSig); + + if (!isValidJws(jwsSig)) + return null; + + var header = headerFromJWS(jwsSig); + + if (!header) + return null; + + var payload = payloadFromJWS(jwsSig); + if (header.typ === 'JWT' || opts.json) + payload = JSON.parse(payload, opts.encoding); + + return { + header: header, + payload: payload, + signature: signatureFromJWS(jwsSig) + }; +} + +function VerifyStream(opts) { + opts = opts || {}; + var secretOrKey = opts.secret; + secretOrKey = secretOrKey == null ? opts.publicKey : secretOrKey; + secretOrKey = secretOrKey == null ? opts.key : secretOrKey; + if (/^hs/i.test(opts.algorithm) === true && secretOrKey == null) { + throw new TypeError('secret must be a string or buffer or a KeyObject') + } + var secretStream = new DataStream(secretOrKey); + this.readable = true; + this.algorithm = opts.algorithm; + this.encoding = opts.encoding; + this.secret = this.publicKey = this.key = secretStream; + this.signature = new DataStream(opts.signature); + this.secret.once('close', function () { + if (!this.signature.writable && this.readable) + this.verify(); + }.bind(this)); + + this.signature.once('close', function () { + if (!this.secret.writable && this.readable) + this.verify(); + }.bind(this)); +} +util.inherits(VerifyStream, Stream); +VerifyStream.prototype.verify = function verify() { + try { + var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer); + var obj = jwsDecode(this.signature.buffer, this.encoding); + this.emit('done', valid, obj); + this.emit('data', valid); + this.emit('end'); + this.readable = false; + return valid; + } catch (e) { + this.readable = false; + this.emit('error', e); + this.emit('close'); + } +}; + +VerifyStream.decode = jwsDecode; +VerifyStream.isValid = isValidJws; +VerifyStream.verify = jwsVerify; + +module.exports = VerifyStream; diff --git a/node_modules/jws/opslevel.yml b/node_modules/jws/opslevel.yml new file mode 100644 index 0000000..aeeeea7 --- /dev/null +++ b/node_modules/jws/opslevel.yml @@ -0,0 +1,6 @@ +--- +version: 1 +repository: + owner: iam_protocols + tier: + tags: diff --git a/node_modules/jws/package.json b/node_modules/jws/package.json new file mode 100644 index 0000000..464d72b --- /dev/null +++ b/node_modules/jws/package.json @@ -0,0 +1,34 @@ +{ + "name": "jws", + "version": "4.0.1", + "description": "Implementation of JSON Web Signatures", + "main": "index.js", + "directories": { + "test": "test" + }, + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/brianloveswords/node-jws.git" + }, + "keywords": [ + "jws", + "json", + "web", + "signatures" + ], + "author": "Brian J Brennan", + "license": "MIT", + "readmeFilename": "readme.md", + "gitHead": "c0f6b27bcea5a2ad2e304d91c2e842e4076a6b03", + "dependencies": { + "jwa": "^2.0.1", + "safe-buffer": "^5.0.1" + }, + "devDependencies": { + "semver": "^5.1.0", + "tape": "~2.14.0" + } +} diff --git a/node_modules/jws/readme.md b/node_modules/jws/readme.md new file mode 100644 index 0000000..2f32dca --- /dev/null +++ b/node_modules/jws/readme.md @@ -0,0 +1,255 @@ +# node-jws [![Build Status](https://secure.travis-ci.org/brianloveswords/node-jws.svg)](http://travis-ci.org/brianloveswords/node-jws) + +An implementation of [JSON Web Signatures](http://self-issued.info/docs/draft-ietf-jose-json-web-signature.html). + +This was developed against `draft-ietf-jose-json-web-signature-08` and +implements the entire spec **except** X.509 Certificate Chain +signing/verifying (patches welcome). + +There are both synchronous (`jws.sign`, `jws.verify`) and streaming +(`jws.createSign`, `jws.createVerify`) APIs. + +# Install + +```bash +$ npm install jws +``` + +# Usage + +## jws.ALGORITHMS + +Array of supported algorithms. The following algorithms are currently supported. + +alg Parameter Value | Digital Signature or MAC Algorithm +----------------|---------------------------- +HS256 | HMAC using SHA-256 hash algorithm +HS384 | HMAC using SHA-384 hash algorithm +HS512 | HMAC using SHA-512 hash algorithm +RS256 | RSASSA using SHA-256 hash algorithm +RS384 | RSASSA using SHA-384 hash algorithm +RS512 | RSASSA using SHA-512 hash algorithm +PS256 | RSASSA-PSS using SHA-256 hash algorithm +PS384 | RSASSA-PSS using SHA-384 hash algorithm +PS512 | RSASSA-PSS using SHA-512 hash algorithm +ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm +ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm +ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm +none | No digital signature or MAC value included + +## jws.sign(options) + +(Synchronous) Return a JSON Web Signature for a header and a payload. + +Options: + +* `header` +* `payload` +* `secret` or `privateKey` +* `encoding` (Optional, defaults to 'utf8') + +`header` must be an object with an `alg` property. `header.alg` must be +one a value found in `jws.ALGORITHMS`. See above for a table of +supported algorithms. + +If `payload` is not a buffer or a string, it will be coerced into a string +using `JSON.stringify`. + +Example + +```js +const signature = jws.sign({ + header: { alg: 'HS256' }, + payload: 'h. jon benjamin', + secret: 'has a van', +}); +``` + +## jws.verify(signature, algorithm, secretOrKey) + +(Synchronous) Returns `true` or `false` for whether a signature matches a +secret or key. + +`signature` is a JWS Signature. `header.alg` must be a value found in `jws.ALGORITHMS`. +See above for a table of supported algorithms. `secretOrKey` is a string or +buffer containing either the secret for HMAC algorithms, or the PEM +encoded public key for RSA and ECDSA. + +Note that the `"alg"` value from the signature header is ignored. + + +## jws.decode(signature) + +(Synchronous) Returns the decoded header, decoded payload, and signature +parts of the JWS Signature. + +Returns an object with three properties, e.g. +```js +{ header: { alg: 'HS256' }, + payload: 'h. jon benjamin', + signature: 'YOWPewyGHKu4Y_0M_vtlEnNlqmFOclqp4Hy6hVHfFT4' +} +``` + +## jws.createSign(options) + +Returns a new SignStream object. + +Options: + +* `header` (required) +* `payload` +* `key` || `privateKey` || `secret` +* `encoding` (Optional, defaults to 'utf8') + +Other than `header`, all options expect a string or a buffer when the +value is known ahead of time, or a stream for convenience. +`key`/`privateKey`/`secret` may also be an object when using an encrypted +private key, see the [crypto documentation][encrypted-key-docs]. + +Example: + +```js + +// This... +jws.createSign({ + header: { alg: 'RS256' }, + privateKey: privateKeyStream, + payload: payloadStream, +}).on('done', function(signature) { + // ... +}); + +// is equivalent to this: +const signer = jws.createSign({ + header: { alg: 'RS256' }, +}); +privateKeyStream.pipe(signer.privateKey); +payloadStream.pipe(signer.payload); +signer.on('done', function(signature) { + // ... +}); +``` + +## jws.createVerify(options) + +Returns a new VerifyStream object. + +Options: + +* `signature` +* `algorithm` +* `key` || `publicKey` || `secret` +* `encoding` (Optional, defaults to 'utf8') + +All options expect a string or a buffer when the value is known ahead of +time, or a stream for convenience. + +Example: + +```js + +// This... +jws.createVerify({ + publicKey: pubKeyStream, + signature: sigStream, +}).on('done', function(verified, obj) { + // ... +}); + +// is equivilant to this: +const verifier = jws.createVerify(); +pubKeyStream.pipe(verifier.publicKey); +sigStream.pipe(verifier.signature); +verifier.on('done', function(verified, obj) { + // ... +}); +``` + +## Class: SignStream + +A `Readable Stream` that emits a single data event (the calculated +signature) when done. + +### Event: 'done' +`function (signature) { }` + +### signer.payload + +A `Writable Stream` that expects the JWS payload. Do *not* use if you +passed a `payload` option to the constructor. + +Example: + +```js +payloadStream.pipe(signer.payload); +``` + +### signer.secret
                          signer.key
                          signer.privateKey + +A `Writable Stream`. Expects the JWS secret for HMAC, or the privateKey +for ECDSA and RSA. Do *not* use if you passed a `secret` or `key` option +to the constructor. + +Example: + +```js +privateKeyStream.pipe(signer.privateKey); +``` + +## Class: VerifyStream + +This is a `Readable Stream` that emits a single data event, the result +of whether or not that signature was valid. + +### Event: 'done' +`function (valid, obj) { }` + +`valid` is a boolean for whether or not the signature is valid. + +### verifier.signature + +A `Writable Stream` that expects a JWS Signature. Do *not* use if you +passed a `signature` option to the constructor. + +### verifier.secret
                          verifier.key
                          verifier.publicKey + +A `Writable Stream` that expects a public key or secret. Do *not* use if you +passed a `key` or `secret` option to the constructor. + +# TODO + +* It feels like there should be some convenience options/APIs for + defining the algorithm rather than having to define a header object + with `{ alg: 'ES512' }` or whatever every time. + +* X.509 support, ugh + +# License + +MIT + +``` +Copyright (c) 2013-2015 Brian J. Brennan + +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. +``` + +[encrypted-key-docs]: https://nodejs.org/api/crypto.html#crypto_sign_sign_private_key_output_format diff --git a/node_modules/limiter/.travis.yml b/node_modules/limiter/.travis.yml new file mode 100644 index 0000000..380b4d6 --- /dev/null +++ b/node_modules/limiter/.travis.yml @@ -0,0 +1,9 @@ +language: node_js + +node_js: + - "0.12" + - "0.10" + +notifications: + email: + - "jhurliman@jhurliman.org" diff --git a/node_modules/limiter/LICENSE.txt b/node_modules/limiter/LICENSE.txt new file mode 100644 index 0000000..7a52222 --- /dev/null +++ b/node_modules/limiter/LICENSE.txt @@ -0,0 +1,19 @@ +Copyright (C) 2011 by John Hurliman + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/limiter/README.md b/node_modules/limiter/README.md new file mode 100644 index 0000000..bdd43db --- /dev/null +++ b/node_modules/limiter/README.md @@ -0,0 +1,140 @@ +# limiter # + +[![Build Status](https://travis-ci.org/jhurliman/node-rate-limiter.png)](https://travis-ci.org/jhurliman/node-rate-limiter) +[![NPM Downloads](https://img.shields.io/npm/dm/limiter.svg?style=flat)](https://www.npmjs.com/package/limiter) + +Provides a generic rate limiter for node.js. Useful for API clients, web +crawling, or other tasks that need to be throttled. Two classes are exposed, +RateLimiter and TokenBucket. TokenBucket provides a lower level interface to +rate limiting with a configurable burst rate and drip rate. RateLimiter sits +on top of the token bucket and adds a restriction on the maximum number of +tokens that can be removed each interval to comply with common API +restrictions like "150 requests per hour maximum". + +## Installation ## + +Use NPM to install: + + npm install limiter + +## Usage ## + +A simple example allowing 150 requests per hour: + +```javascript +var RateLimiter = require('limiter').RateLimiter; +// Allow 150 requests per hour (the Twitter search limit). Also understands +// 'second', 'minute', 'day', or a number of milliseconds +var limiter = new RateLimiter(150, 'hour'); + +// Throttle requests +limiter.removeTokens(1, function(err, remainingRequests) { + // err will only be set if we request more than the maximum number of + // requests we set in the constructor + + // remainingRequests tells us how many additional requests could be sent + // right this moment + + callMyRequestSendingFunction(...); +}); +``` + +Another example allowing one message to be sent every 250ms: + +```javascript +var RateLimiter = require('limiter').RateLimiter; +var limiter = new RateLimiter(1, 250); + +limiter.removeTokens(1, function() { + callMyMessageSendingFunction(...); +}); +``` + +The default behaviour is to wait for the duration of the rate limiting +that’s currently in effect before the callback is fired, but if you +pass in ```true``` as the third parameter, the callback will be fired +immediately with remainingRequests set to -1: + +```javascript +var RateLimiter = require('limiter').RateLimiter; +var limiter = new RateLimiter(150, 'hour', true); // fire CB immediately + +// Immediately send 429 header to client when rate limiting is in effect +limiter.removeTokens(1, function(err, remainingRequests) { + if (remainingRequests < 1) { + response.writeHead(429, {'Content-Type': 'text/plain;charset=UTF-8'}); + response.end('429 Too Many Requests - your IP is being rate limited'); + } else { + callMyMessageSendingFunction(...); + } +}); +``` + +A synchronous method, tryRemoveTokens(), is available in both RateLimiter and TokenBucket. This will return immediately with a boolean value indicating if the token removal was successful. +```javascript +var RateLimiter = require('limiter').RateLimiter; +var limiter = new RateLimiter(10, 'second'); + +if (limiter.tryRemoveTokens(5)) + console.log('Tokens removed'); +else + console.log('No tokens removed'); +``` + +To get the number of remaining tokens **outside** the `removeTokens`-callback +simply use the `getTokensRemaining`-method. +```javascript +var RateLimiter = require('limiter').RateLimiter; +var limiter = new RateLimiter(1, 250); + +// returns 1 since we did not remove a token and our number of tokens per interval is 1 +limiter.getTokensRemaining(); +``` + +Using the token bucket directly to throttle at the byte level: + +```javascript +var BURST_RATE = 1024 * 1024 * 150; // 150KB/sec burst rate +var FILL_RATE = 1024 * 1024 * 50; // 50KB/sec sustained rate +var TokenBucket = require('limiter').TokenBucket; +// We could also pass a parent token bucket in as the last parameter to +// create a hierarchical token bucket +var bucket = new TokenBucket(BURST_RATE, FILL_RATE, 'second', null); + +bucket.removeTokens(myData.byteLength, function() { + sendMyData(myData); +}); +``` + +## Additional Notes ## + +Both the token bucket and rate limiter should be used with a message queue or +some way of preventing multiple simultaneous calls to removeTokens(). +Otherwise, earlier messages may get held up for long periods of time if more +recent messages are continually draining the token bucket. This can lead to +out of order messages or the appearance of "lost" messages under heavy load. + +## License ## + +(The MIT License) + +Copyright (c) 2013 John Hurliman. <jhurliman@jhurliman.org> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/limiter/bower.json b/node_modules/limiter/bower.json new file mode 100644 index 0000000..b4a443d --- /dev/null +++ b/node_modules/limiter/bower.json @@ -0,0 +1,22 @@ +{ + "name": "limiter", + "main": "index.js", + "version": "1.0.5", + "homepage": "https://github.com/jhurliman/node-rate-limiter", + "authors": [ + "John Hurliman " + ], + "description": "A generic rate limiter for node.js. Useful for API clients, web crawling, or other tasks that need to be throttled", + "moduleType": [ + "node" + ], + "keywords": [ + "rate", + "limiting", + "throttling" + ], + "license": "MIT", + "ignore": [ + "package.json" + ] +} diff --git a/node_modules/limiter/index.d.ts b/node_modules/limiter/index.d.ts new file mode 100644 index 0000000..0496f8e --- /dev/null +++ b/node_modules/limiter/index.d.ts @@ -0,0 +1,22 @@ +export type TokenBucketError = string +export type Fail = (error: T) => void +export type Success = (error: null, data: T) => void +export type RemoveTokensCallback = Fail | Success + +type Interval = number | 'second' | 'sec' | 'minute' | 'min' | 'hour' | 'hr' | 'day' + +export declare class TokenBucket { + constructor(bucketSize: number, tokensPerInterval: number, interval: Interval, parentBucket?: TokenBucket) + + removeTokens(count: number, callback: RemoveTokensCallback): void + tryRemoveTokens(count: number): boolean + drip(): boolean +} + +export declare class RateLimiter { + constructor(tokensPerInterval: number, interval: Interval, fireImmediately?: boolean) + + removeTokens(count: number, callback: RemoveTokensCallback): void + tryRemoveTokens(count: number): boolean + getTokensRemaining(): number +} diff --git a/node_modules/limiter/index.js b/node_modules/limiter/index.js new file mode 100644 index 0000000..cd29aa4 --- /dev/null +++ b/node_modules/limiter/index.js @@ -0,0 +1,3 @@ + +exports.RateLimiter = require('./lib/rateLimiter'); +exports.TokenBucket = require('./lib/tokenBucket'); diff --git a/node_modules/limiter/lib/clock.js b/node_modules/limiter/lib/clock.js new file mode 100644 index 0000000..38d8c53 --- /dev/null +++ b/node_modules/limiter/lib/clock.js @@ -0,0 +1,13 @@ +var getMilliseconds = function() { + if (typeof process !== 'undefined' && process.hrtime) { + var hrtime = process.hrtime(); + var seconds = hrtime[0]; + var nanoseconds = hrtime[1]; + + return seconds * 1e3 + Math.floor(nanoseconds / 1e6); + } + + return new Date().getTime(); +} + +module.exports = getMilliseconds; diff --git a/node_modules/limiter/lib/rateLimiter.js b/node_modules/limiter/lib/rateLimiter.js new file mode 100644 index 0000000..4fbcc66 --- /dev/null +++ b/node_modules/limiter/lib/rateLimiter.js @@ -0,0 +1,137 @@ +var TokenBucket = require('./tokenBucket'); +var getMilliseconds = require('./clock'); + +/** + * A generic rate limiter. Underneath the hood, this uses a token bucket plus + * an additional check to limit how many tokens we can remove each interval. + * @author John Hurliman + * + * @param {Number} tokensPerInterval Maximum number of tokens that can be + * removed at any given moment and over the course of one interval. + * @param {String|Number} interval The interval length in milliseconds, or as + * one of the following strings: 'second', 'minute', 'hour', day'. + * @param {Boolean} fireImmediately Optional. Whether or not the callback + * will fire immediately when rate limiting is in effect (default is false). + */ +var RateLimiter = function(tokensPerInterval, interval, fireImmediately) { + this.tokenBucket = new TokenBucket(tokensPerInterval, tokensPerInterval, + interval, null); + + // Fill the token bucket to start + this.tokenBucket.content = tokensPerInterval; + + this.curIntervalStart = getMilliseconds(); + this.tokensThisInterval = 0; + this.fireImmediately = fireImmediately; +}; + +RateLimiter.prototype = { + tokenBucket: null, + curIntervalStart: 0, + tokensThisInterval: 0, + fireImmediately: false, + + /** + * Remove the requested number of tokens and fire the given callback. If the + * rate limiter contains enough tokens and we haven't spent too many tokens + * in this interval already, this will happen immediately. Otherwise, the + * removal and callback will happen when enough tokens become available. + * @param {Number} count The number of tokens to remove. + * @param {Function} callback(err, remainingTokens) + * @returns {Boolean} True if the callback was fired immediately, otherwise + * false. + */ + removeTokens: function(count, callback) { + // Make sure the request isn't for more than we can handle + if (count > this.tokenBucket.bucketSize) { + process.nextTick(callback.bind(null, 'Requested tokens ' + count + + ' exceeds maximum tokens per interval ' + this.tokenBucket.bucketSize, + null)); + return false; + } + + var self = this; + var now = getMilliseconds(); + + // Advance the current interval and reset the current interval token count + // if needed + if (now < this.curIntervalStart + || now - this.curIntervalStart >= this.tokenBucket.interval) { + this.curIntervalStart = now; + this.tokensThisInterval = 0; + } + + // If we don't have enough tokens left in this interval, wait until the + // next interval + if (count > this.tokenBucket.tokensPerInterval - this.tokensThisInterval) { + if (this.fireImmediately) { + process.nextTick(callback.bind(null, null, -1)); + } else { + var waitInterval = Math.ceil( + this.curIntervalStart + this.tokenBucket.interval - now); + + setTimeout(function() { + self.tokenBucket.removeTokens(count, afterTokensRemoved); + }, waitInterval); + } + return false; + } + + // Remove the requested number of tokens from the token bucket + return this.tokenBucket.removeTokens(count, afterTokensRemoved); + + function afterTokensRemoved(err, tokensRemaining) { + if (err) return callback(err, null); + + self.tokensThisInterval += count; + callback(null, tokensRemaining); + } + }, + + /** + * Attempt to remove the requested number of tokens and return immediately. + * If the bucket (and any parent buckets) contains enough tokens and we + * haven't spent too many tokens in this interval already, this will return + * true. Otherwise, false is returned. + * @param {Number} count The number of tokens to remove. + * @param {Boolean} True if the tokens were successfully removed, otherwise + * false. + */ + tryRemoveTokens: function(count) { + // Make sure the request isn't for more than we can handle + if (count > this.tokenBucket.bucketSize) + return false; + + var now = getMilliseconds(); + + // Advance the current interval and reset the current interval token count + // if needed + if (now < this.curIntervalStart + || now - this.curIntervalStart >= this.tokenBucket.interval) { + this.curIntervalStart = now; + this.tokensThisInterval = 0; + } + + // If we don't have enough tokens left in this interval, return false + if (count > this.tokenBucket.tokensPerInterval - this.tokensThisInterval) + return false; + + // Try to remove the requested number of tokens from the token bucket + var removed = this.tokenBucket.tryRemoveTokens(count); + if (removed) { + this.tokensThisInterval += count; + } + return removed; + }, + + /** + * Returns the number of tokens remaining in the TokenBucket. + * @returns {Number} The number of tokens remaining. + */ + getTokensRemaining: function () { + this.tokenBucket.drip(); + return this.tokenBucket.content; + } +}; + +module.exports = RateLimiter; diff --git a/node_modules/limiter/lib/tokenBucket.js b/node_modules/limiter/lib/tokenBucket.js new file mode 100644 index 0000000..bac8c5b --- /dev/null +++ b/node_modules/limiter/lib/tokenBucket.js @@ -0,0 +1,167 @@ + +/** + * A hierarchical token bucket for rate limiting. See + * http://en.wikipedia.org/wiki/Token_bucket for more information. + * @author John Hurliman + * + * @param {Number} bucketSize Maximum number of tokens to hold in the bucket. + * Also known as the burst rate. + * @param {Number} tokensPerInterval Number of tokens to drip into the bucket + * over the course of one interval. + * @param {String|Number} interval The interval length in milliseconds, or as + * one of the following strings: 'second', 'minute', 'hour', day'. + * @param {TokenBucket} parentBucket Optional. A token bucket that will act as + * the parent of this bucket. + */ +var TokenBucket = function(bucketSize, tokensPerInterval, interval, parentBucket) { + this.bucketSize = bucketSize; + this.tokensPerInterval = tokensPerInterval; + + if (typeof interval === 'string') { + switch (interval) { + case 'sec': case 'second': + this.interval = 1000; break; + case 'min': case 'minute': + this.interval = 1000 * 60; break; + case 'hr': case 'hour': + this.interval = 1000 * 60 * 60; break; + case 'day': + this.interval = 1000 * 60 * 60 * 24; break; + default: + throw new Error('Invaid interval ' + interval); + } + } else { + this.interval = interval; + } + + this.parentBucket = parentBucket; + this.content = 0; + this.lastDrip = +new Date(); +}; + +TokenBucket.prototype = { + bucketSize: 1, + tokensPerInterval: 1, + interval: 1000, + parentBucket: null, + content: 0, + lastDrip: 0, + + /** + * Remove the requested number of tokens and fire the given callback. If the + * bucket (and any parent buckets) contains enough tokens this will happen + * immediately. Otherwise, the removal and callback will happen when enough + * tokens become available. + * @param {Number} count The number of tokens to remove. + * @param {Function} callback(err, remainingTokens) + * @returns {Boolean} True if the callback was fired immediately, otherwise + * false. + */ + removeTokens: function(count, callback) { + var self = this; + + // Is this an infinite size bucket? + if (!this.bucketSize) { + process.nextTick(callback.bind(null, null, count, Number.POSITIVE_INFINITY)); + return true; + } + + // Make sure the bucket can hold the requested number of tokens + if (count > this.bucketSize) { + process.nextTick(callback.bind(null, 'Requested tokens ' + count + ' exceeds bucket size ' + + this.bucketSize, null)); + return false; + } + + // Drip new tokens into this bucket + this.drip(); + + // If we don't have enough tokens in this bucket, come back later + if (count > this.content) + return comeBackLater(); + + if (this.parentBucket) { + // Remove the requested from the parent bucket first + return this.parentBucket.removeTokens(count, function(err, remainingTokens) { + if (err) return callback(err, null); + + // Check that we still have enough tokens in this bucket + if (count > self.content) + return comeBackLater(); + + // Tokens were removed from the parent bucket, now remove them from + // this bucket and fire the callback. Note that we look at the current + // bucket and parent bucket's remaining tokens and return the smaller + // of the two values + self.content -= count; + callback(null, Math.min(remainingTokens, self.content)); + }); + } else { + // Remove the requested tokens from this bucket and fire the callback + this.content -= count; + process.nextTick(callback.bind(null, null, this.content)); + return true; + } + + function comeBackLater() { + // How long do we need to wait to make up the difference in tokens? + var waitInterval = Math.ceil( + (count - self.content) * (self.interval / self.tokensPerInterval)); + setTimeout(function() { self.removeTokens(count, callback); }, waitInterval); + return false; + } + }, + + /** + * Attempt to remove the requested number of tokens and return immediately. + * If the bucket (and any parent buckets) contains enough tokens this will + * return true, otherwise false is returned. + * @param {Number} count The number of tokens to remove. + * @param {Boolean} True if the tokens were successfully removed, otherwise + * false. + */ + tryRemoveTokens: function(count) { + // Is this an infinite size bucket? + if (!this.bucketSize) + return true; + + // Make sure the bucket can hold the requested number of tokens + if (count > this.bucketSize) + return false; + + // Drip new tokens into this bucket + this.drip(); + + // If we don't have enough tokens in this bucket, return false + if (count > this.content) + return false; + + // Try to remove the requested tokens from the parent bucket + if (this.parentBucket && !this.parentBucket.tryRemoveTokens(count)) + return false; + + // Remove the requested tokens from this bucket and return + this.content -= count; + return true; + }, + + /** + * Add any new tokens to the bucket since the last drip. + * @returns {Boolean} True if new tokens were added, otherwise false. + */ + drip: function() { + if (!this.tokensPerInterval) { + this.content = this.bucketSize; + return; + } + + var now = +new Date(); + var deltaMS = Math.max(now - this.lastDrip, 0); + this.lastDrip = now; + + var dripAmount = deltaMS * (this.tokensPerInterval / this.interval); + this.content = Math.min(this.content + dripAmount, this.bucketSize); + } +}; + +module.exports = TokenBucket; diff --git a/node_modules/limiter/package.json b/node_modules/limiter/package.json new file mode 100644 index 0000000..1c71cfd --- /dev/null +++ b/node_modules/limiter/package.json @@ -0,0 +1,25 @@ +{ + "name": "limiter", + "description": "A generic rate limiter for node.js. Useful for API clients, web crawling, or other tasks that need to be throttled", + "version": "1.1.5", + "author": "John Hurliman ", + "scripts": { + "test": "vows --spec" + }, + "dependencies": { + }, + "devDependencies": { + "assert": "1.3.0", + "vows": "0.8.1" + }, + "keywords": ["rate", "limiting", "throttling"], + "repository": "git://github.com/jhurliman/node-rate-limiter", + "bugs": { "url": "http://github.com/jhurliman/node-rate-limiter/issues" }, + "directories": { "lib": "./lib/" }, + "main": "./index.js", + "types": "./index.d.ts", + "licenses": [{ + "type": "MIT", + "url": "http://github.com/jhurliman/node-rate-limiter/raw/master/LICENSE.txt" + }] +} diff --git a/node_modules/limiter/test/ratelimiter-test.js b/node_modules/limiter/test/ratelimiter-test.js new file mode 100644 index 0000000..3250c21 --- /dev/null +++ b/node_modules/limiter/test/ratelimiter-test.js @@ -0,0 +1,20 @@ +var vows = require('vows'); +var assert = require('assert'); +var RateLimiter = require('../lib/rateLimiter'); + +vows.describe('RateLimiter').addBatch({ + 'interval validation': { + 'invalid interval': function() { + assert.throws(function() { new RateLimiter(1, 'junk'); }, /interval/); + }, + 'valid intervals': function() { + assert.doesNotThrow(function() { new RateLimiter(1, 'sec'); }); + assert.doesNotThrow(function() { new RateLimiter(1, 'second'); }); + assert.doesNotThrow(function() { new RateLimiter(1, 'min'); }); + assert.doesNotThrow(function() { new RateLimiter(1, 'minute'); }); + assert.doesNotThrow(function() { new RateLimiter(1, 'hr'); }); + assert.doesNotThrow(function() { new RateLimiter(1, 'hour'); }); + assert.doesNotThrow(function() { new RateLimiter(1, 'day'); }); + } + } +}).export(module); diff --git a/node_modules/limiter/test/tokenbucket-test.js b/node_modules/limiter/test/tokenbucket-test.js new file mode 100644 index 0000000..032761d --- /dev/null +++ b/node_modules/limiter/test/tokenbucket-test.js @@ -0,0 +1,67 @@ +var vows = require('vows'); +var assert = require('assert'); + +var TIMING_EPSILON = 10; + +var TokenBucket = require('../lib/tokenBucket'); + +vows.describe('TokenBucket').addBatch({ + 'capacity 10, 1 per 100ms': { + topic: new TokenBucket(10, 1, 100), + + 'is initialized empty': function(bucket) { + assert.equal(bucket.bucketSize, 10); + assert.equal(bucket.tokensPerInterval, 1); + assert.equal(bucket.content, 0); + }, + 'removing 10 tokens': { + topic: function(bucket) { + this.gStart = +new Date(); + bucket.removeTokens(10, this.callback); + }, + 'takes 1 second': function(remainingTokens) { + var duration = +new Date() - this.gStart; + var diff = Math.abs(1000 - duration); + assert.ok(diff < TIMING_EPSILON, diff+''); + assert.equal(remainingTokens, 0); + }, + 'and removing another 10 tokens': { + topic: function(_, bucket) { + this.gStart = +new Date(); + assert.equal(bucket.content, 0); + bucket.removeTokens(10, this.callback); + }, + 'takes 1 second': function() { + var duration = +new Date() - this.gStart; + var diff = Math.abs(1000 - duration); + assert.ok(diff < TIMING_EPSILON, diff+''); + } + }, + 'and waiting 2 seconds': { + topic: function(_, bucket) { + var self = this; + setTimeout(function() { + self.gStart = +new Date(); + bucket.removeTokens(10, self.callback); + }, 2000); + }, + 'gives us only 10 tokens': function(remainingTokens) { + var duration = +new Date() - this.gStart; + assert.ok(duration < TIMING_EPSILON, duration+''); + assert.equal(remainingTokens, 0); + }, + 'and removing 1 token': { + topic: function(_, _, bucket) { + this.gStart = +new Date(); + bucket.removeTokens(1, this.callback); + }, + 'takes 100ms': function() { + var duration = +new Date() - this.gStart; + var diff = Math.abs(100 - duration); + assert.ok(diff < TIMING_EPSILON, diff+''); + } + } + } + } + }, +}).export(module); diff --git a/node_modules/lodash.camelcase/LICENSE b/node_modules/lodash.camelcase/LICENSE new file mode 100644 index 0000000..e0c69d5 --- /dev/null +++ b/node_modules/lodash.camelcase/LICENSE @@ -0,0 +1,47 @@ +Copyright jQuery Foundation and other contributors + +Based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/lodash/lodash + +The following license applies to all parts of this software except as +documented below: + +==== + +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. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +Files located in the node_modules and vendor directories are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/node_modules/lodash.camelcase/README.md b/node_modules/lodash.camelcase/README.md new file mode 100644 index 0000000..333d437 --- /dev/null +++ b/node_modules/lodash.camelcase/README.md @@ -0,0 +1,18 @@ +# lodash.camelcase v4.3.0 + +The [lodash](https://lodash.com/) method `_.camelCase` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.camelcase +``` + +In Node.js: +```js +var camelCase = require('lodash.camelcase'); +``` + +See the [documentation](https://lodash.com/docs#camelCase) or [package source](https://github.com/lodash/lodash/blob/4.3.0-npm-packages/lodash.camelcase) for more details. diff --git a/node_modules/lodash.camelcase/index.js b/node_modules/lodash.camelcase/index.js new file mode 100644 index 0000000..b6d8b3c --- /dev/null +++ b/node_modules/lodash.camelcase/index.js @@ -0,0 +1,599 @@ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** Used to match words composed of alphanumeric characters. */ +var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + +/** Used to match Latin Unicode letters (excluding mathematical operators). */ +var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + +/** Used to compose unicode character classes. */ +var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23', + rsComboSymbolsRange = '\\u20d0-\\u20f0', + rsDingbatRange = '\\u2700-\\u27bf', + rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', + rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', + rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', + rsPunctuationRange = '\\u2000-\\u206f', + rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + rsVarRange = '\\ufe0e\\ufe0f', + rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + +/** Used to compose unicode capture groups. */ +var rsApos = "['\u2019]", + rsAstral = '[' + rsAstralRange + ']', + rsBreak = '[' + rsBreakRange + ']', + rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']', + rsDigits = '\\d+', + rsDingbat = '[' + rsDingbatRange + ']', + rsLower = '[' + rsLowerRange + ']', + rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsUpper = '[' + rsUpperRange + ']', + rsZWJ = '\\u200d'; + +/** Used to compose unicode regexes. */ +var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')', + rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')', + rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', + rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', + reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + +/** Used to match apostrophes. */ +var reApos = RegExp(rsApos, 'g'); + +/** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ +var reComboMark = RegExp(rsCombo, 'g'); + +/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ +var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + +/** Used to match complex or compound words. */ +var reUnicodeWord = RegExp([ + rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', + rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')', + rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr, + rsUpper + '+' + rsOptUpperContr, + rsDigits, + rsEmoji +].join('|'), 'g'); + +/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ +var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']'); + +/** Used to detect strings that need a more robust regexp to match words. */ +var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + +/** Used to map Latin Unicode letters to basic Latin letters. */ +var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 'ss' +}; + +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +/** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ +function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array ? array.length : 0; + + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; +} + +/** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function asciiToArray(string) { + return string.split(''); +} + +/** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ +function asciiWords(string) { + return string.match(reAsciiWord) || []; +} + +/** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ +function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; +} + +/** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ +var deburrLetter = basePropertyOf(deburredLetters); + +/** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ +function hasUnicode(string) { + return reHasUnicode.test(string); +} + +/** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */ +function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); +} + +/** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); +} + +/** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function unicodeToArray(string) { + return string.match(reUnicode) || []; +} + +/** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ +function unicodeWords(string) { + return string.match(reUnicodeWord) || []; +} + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** Built-in value references. */ +var Symbol = root.Symbol; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + +/** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ +function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; +} + +/** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ +function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +} + +/** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ +function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); +} + +/** + * Creates a function like `_.lowerFirst`. + * + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. + */ +function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + + var strSymbols = hasUnicode(string) + ? stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; +} + +/** + * Creates a function like `_.camelCase`. + * + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ +function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} + +/** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {string} Returns the string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ +function toString(value) { + return value == null ? '' : baseToString(value); +} + +/** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar--'); + * // => 'fooBar' + * + * _.camelCase('__FOO_BAR__'); + * // => 'fooBar' + */ +var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize(word) : word); +}); + +/** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('FRED'); + * // => 'Fred' + */ +function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); +} + +/** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ +function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); +} + +/** + * Converts the first character of `string` to upper case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.upperFirst('fred'); + * // => 'Fred' + * + * _.upperFirst('FRED'); + * // => 'FRED' + */ +var upperFirst = createCaseFirst('toUpperCase'); + +/** + * Splits `string` into an array of its words. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {RegExp|string} [pattern] The pattern to match words. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the words of `string`. + * @example + * + * _.words('fred, barney, & pebbles'); + * // => ['fred', 'barney', 'pebbles'] + * + * _.words('fred, barney, & pebbles', /[^, ]+/g); + * // => ['fred', 'barney', '&', 'pebbles'] + */ +function words(string, pattern, guard) { + string = toString(string); + pattern = guard ? undefined : pattern; + + if (pattern === undefined) { + return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); + } + return string.match(pattern) || []; +} + +module.exports = camelCase; diff --git a/node_modules/lodash.camelcase/package.json b/node_modules/lodash.camelcase/package.json new file mode 100644 index 0000000..aca63e0 --- /dev/null +++ b/node_modules/lodash.camelcase/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.camelcase", + "version": "4.3.0", + "description": "The lodash method `_.camelCase` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, camelcase", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lodash.clonedeep/LICENSE b/node_modules/lodash.clonedeep/LICENSE new file mode 100644 index 0000000..e0c69d5 --- /dev/null +++ b/node_modules/lodash.clonedeep/LICENSE @@ -0,0 +1,47 @@ +Copyright jQuery Foundation and other contributors + +Based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/lodash/lodash + +The following license applies to all parts of this software except as +documented below: + +==== + +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. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +Files located in the node_modules and vendor directories are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/node_modules/lodash.clonedeep/README.md b/node_modules/lodash.clonedeep/README.md new file mode 100644 index 0000000..fee48e4 --- /dev/null +++ b/node_modules/lodash.clonedeep/README.md @@ -0,0 +1,18 @@ +# lodash.clonedeep v4.5.0 + +The [lodash](https://lodash.com/) method `_.cloneDeep` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.clonedeep +``` + +In Node.js: +```js +var cloneDeep = require('lodash.clonedeep'); +``` + +See the [documentation](https://lodash.com/docs#cloneDeep) or [package source](https://github.com/lodash/lodash/blob/4.5.0-npm-packages/lodash.clonedeep) for more details. diff --git a/node_modules/lodash.clonedeep/index.js b/node_modules/lodash.clonedeep/index.js new file mode 100644 index 0000000..1b0e502 --- /dev/null +++ b/node_modules/lodash.clonedeep/index.js @@ -0,0 +1,1748 @@ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + weakMapTag = '[object WeakMap]'; + +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + +/** Used to match `RegExp` flags from their coerced string values. */ +var reFlags = /\w*$/; + +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** Used to identify `toStringTag` values supported by `_.clone`. */ +var cloneableTags = {}; +cloneableTags[argsTag] = cloneableTags[arrayTag] = +cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = +cloneableTags[boolTag] = cloneableTags[dateTag] = +cloneableTags[float32Tag] = cloneableTags[float64Tag] = +cloneableTags[int8Tag] = cloneableTags[int16Tag] = +cloneableTags[int32Tag] = cloneableTags[mapTag] = +cloneableTags[numberTag] = cloneableTags[objectTag] = +cloneableTags[regexpTag] = cloneableTags[setTag] = +cloneableTags[stringTag] = cloneableTags[symbolTag] = +cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = +cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; +cloneableTags[errorTag] = cloneableTags[funcTag] = +cloneableTags[weakMapTag] = false; + +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +/** Detect free variable `exports`. */ +var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; + +/** + * Adds the key-value `pair` to `map`. + * + * @private + * @param {Object} map The map to modify. + * @param {Array} pair The key-value pair to add. + * @returns {Object} Returns `map`. + */ +function addMapEntry(map, pair) { + // Don't return `map.set` because it's not chainable in IE 11. + map.set(pair[0], pair[1]); + return map; +} + +/** + * Adds `value` to `set`. + * + * @private + * @param {Object} set The set to modify. + * @param {*} value The value to add. + * @returns {Object} Returns `set`. + */ +function addSetEntry(set, value) { + // Don't return `set.add` because it's not chainable in IE 11. + set.add(value); + return set; +} + +/** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ +function arrayEach(array, iteratee) { + var index = -1, + length = array ? array.length : 0; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; +} + +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; +} + +/** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ +function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array ? array.length : 0; + + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; +} + +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function getValue(object, key) { + return object == null ? undefined : object[key]; +} + +/** + * Checks if `value` is a host object in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + */ +function isHostObject(value) { + // Many host objects are `Object` objects that can coerce to strings + // despite having improperly defined `toString` methods. + var result = false; + if (value != null && typeof value.toString != 'function') { + try { + result = !!(value + ''); + } catch (e) {} + } + return result; +} + +/** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ +function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; +} + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +/** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ +function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; +} + +/** Used for built-in method references. */ +var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + +/** Used to detect overreaching core-js shims. */ +var coreJsData = root['__core-js_shared__']; + +/** Used to detect methods masquerading as native. */ +var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; +}()); + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); + +/** Built-in value references. */ +var Buffer = moduleExports ? root.Buffer : undefined, + Symbol = root.Symbol, + Uint8Array = root.Uint8Array, + getPrototype = overArg(Object.getPrototypeOf, Object), + objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeKeys = overArg(Object.keys, Object); + +/* Built-in method references that are verified to be native. */ +var DataView = getNative(root, 'DataView'), + Map = getNative(root, 'Map'), + Promise = getNative(root, 'Promise'), + Set = getNative(root, 'Set'), + WeakMap = getNative(root, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); + +/** Used to detect maps, sets, and weakmaps. */ +var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; + +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; +} + +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + return this.has(key) && delete this.__data__[key]; +} + +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; +} + +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas(key) { + var data = this.__data__; + return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); +} + +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ +function hashSet(key, value) { + var data = this.__data__; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; +} + +// Add methods to `Hash`. +Hash.prototype.clear = hashClear; +Hash.prototype['delete'] = hashDelete; +Hash.prototype.get = hashGet; +Hash.prototype.has = hashHas; +Hash.prototype.set = hashSet; + +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function ListCache(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; +} + +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + return true; +} + +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; +} + +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; +} + +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; +} + +// Add methods to `ListCache`. +ListCache.prototype.clear = listCacheClear; +ListCache.prototype['delete'] = listCacheDelete; +ListCache.prototype.get = listCacheGet; +ListCache.prototype.has = listCacheHas; +ListCache.prototype.set = listCacheSet; + +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapCacheClear() { + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; +} + +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function mapCacheDelete(key) { + return getMapData(this, key)['delete'](key); +} + +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function mapCacheGet(key) { + return getMapData(this, key).get(key); +} + +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function mapCacheHas(key) { + return getMapData(this, key).has(key); +} + +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ +function mapCacheSet(key, value) { + getMapData(this, key).set(key, value); + return this; +} + +// Add methods to `MapCache`. +MapCache.prototype.clear = mapCacheClear; +MapCache.prototype['delete'] = mapCacheDelete; +MapCache.prototype.get = mapCacheGet; +MapCache.prototype.has = mapCacheHas; +MapCache.prototype.set = mapCacheSet; + +/** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Stack(entries) { + this.__data__ = new ListCache(entries); +} + +/** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ +function stackClear() { + this.__data__ = new ListCache; +} + +/** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function stackDelete(key) { + return this.__data__['delete'](key); +} + +/** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function stackGet(key) { + return this.__data__.get(key); +} + +/** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function stackHas(key) { + return this.__data__.has(key); +} + +/** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ +function stackSet(key, value) { + var cache = this.__data__; + if (cache instanceof ListCache) { + var pairs = cache.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + return this; + } + cache = this.__data__ = new MapCache(pairs); + } + cache.set(key, value); + return this; +} + +// Add methods to `Stack`. +Stack.prototype.clear = stackClear; +Stack.prototype['delete'] = stackDelete; +Stack.prototype.get = stackGet; +Stack.prototype.has = stackHas; +Stack.prototype.set = stackSet; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = (isArray(value) || isArguments(value)) + ? baseTimes(value.length, String) + : []; + + var length = result.length, + skipIndexes = !!length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && (key == 'length' || isIndex(key, length)))) { + result.push(key); + } + } + return result; +} + +/** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + object[key] = value; + } +} + +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; +} + +/** + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ +function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); +} + +/** + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @param {boolean} [isFull] Specify a clone including symbols. + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. + */ +function baseClone(value, isDeep, isFull, customizer, key, object, stack) { + var result; + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result); + } + } else { + var tag = getTag(value), + isFunc = tag == funcTag || tag == genTag; + + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + if (isHostObject(value)) { + return object ? value : {}; + } + result = initCloneObject(isFunc ? {} : value); + if (!isDeep) { + return copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, baseClone, isDeep); + } + } + // Check for circular references and return its corresponding clone. + stack || (stack = new Stack); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + + if (!isArr) { + var props = isFull ? getAllKeys(value) : keys(value); + } + arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + // Recursively populate clone (susceptible to call stack limits). + assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack)); + }); + return result; +} + +/** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} prototype The object to inherit from. + * @returns {Object} Returns the new object. + */ +function baseCreate(proto) { + return isObject(proto) ? objectCreate(proto) : {}; +} + +/** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ +function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); +} + +/** + * The base implementation of `getTag`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function baseGetTag(value) { + return objectToString.call(value); +} + +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ +function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); +} + +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} + +/** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ +function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var result = new buffer.constructor(buffer.length); + buffer.copy(result); + return result; +} + +/** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ +function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; +} + +/** + * Creates a clone of `dataView`. + * + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */ +function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); +} + +/** + * Creates a clone of `map`. + * + * @private + * @param {Object} map The map to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned map. + */ +function cloneMap(map, isDeep, cloneFunc) { + var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map); + return arrayReduce(array, addMapEntry, new map.constructor); +} + +/** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */ +function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; +} + +/** + * Creates a clone of `set`. + * + * @private + * @param {Object} set The set to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned set. + */ +function cloneSet(set, isDeep, cloneFunc) { + var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set); + return arrayReduce(array, addSetEntry, new set.constructor); +} + +/** + * Creates a clone of the `symbol` object. + * + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */ +function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; +} + +/** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ +function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); +} + +/** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ +function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; +} + +/** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ +function copyObject(source, props, object, customizer) { + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + assignValue(object, key, newValue === undefined ? source[key] : newValue); + } + return object; +} + +/** + * Copies own symbol properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ +function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); +} + +/** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ +function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); +} + +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; +} + +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; +} + +/** + * Creates an array of the own enumerable symbol properties of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ +var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray; + +/** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +var getTag = baseGetTag; + +// Fallback for data views, maps, sets, and weak maps in IE 11, +// for data views in Edge < 14, and promises in Node.js. +if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = objectToString.call(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : undefined; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; +} + +/** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ +function initCloneArray(array) { + var length = array.length, + result = array.constructor(length); + + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; +} + +/** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ +function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; +} + +/** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ +function initCloneByTag(object, tag, cloneFunc, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case dataViewTag: + return cloneDataView(object, isDeep); + + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + return cloneTypedArray(object, isDeep); + + case mapTag: + return cloneMap(object, isDeep, cloneFunc); + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + return cloneRegExp(object); + + case setTag: + return cloneSet(object, isDeep, cloneFunc); + + case symbolTag: + return cloneSymbol(object); + } +} + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} + +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} + +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); +} + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; +} + +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to process. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; +} + +/** + * This method is like `_.clone` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false + */ +function cloneDeep(value) { + return baseClone(value, true, true); +} + +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} + +/** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ +var isBuffer = nativeIsBuffer || stubFalse; + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} + +/** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ +function stubArray() { + return []; +} + +/** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ +function stubFalse() { + return false; +} + +module.exports = cloneDeep; diff --git a/node_modules/lodash.clonedeep/package.json b/node_modules/lodash.clonedeep/package.json new file mode 100644 index 0000000..fb1d626 --- /dev/null +++ b/node_modules/lodash.clonedeep/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.clonedeep", + "version": "4.5.0", + "description": "The lodash method `_.cloneDeep` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, clonedeep", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lodash.includes/LICENSE b/node_modules/lodash.includes/LICENSE new file mode 100644 index 0000000..e0c69d5 --- /dev/null +++ b/node_modules/lodash.includes/LICENSE @@ -0,0 +1,47 @@ +Copyright jQuery Foundation and other contributors + +Based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/lodash/lodash + +The following license applies to all parts of this software except as +documented below: + +==== + +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. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +Files located in the node_modules and vendor directories are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/node_modules/lodash.includes/README.md b/node_modules/lodash.includes/README.md new file mode 100644 index 0000000..26e9377 --- /dev/null +++ b/node_modules/lodash.includes/README.md @@ -0,0 +1,18 @@ +# lodash.includes v4.3.0 + +The [lodash](https://lodash.com/) method `_.includes` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.includes +``` + +In Node.js: +```js +var includes = require('lodash.includes'); +``` + +See the [documentation](https://lodash.com/docs#includes) or [package source](https://github.com/lodash/lodash/blob/4.3.0-npm-packages/lodash.includes) for more details. diff --git a/node_modules/lodash.includes/index.js b/node_modules/lodash.includes/index.js new file mode 100644 index 0000000..e88d533 --- /dev/null +++ b/node_modules/lodash.includes/index.js @@ -0,0 +1,745 @@ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + stringTag = '[object String]', + symbolTag = '[object Symbol]'; + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; + +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array ? array.length : 0, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; +} + +/** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; +} + +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOf(array, value, fromIndex) { + if (value !== value) { + return baseFindIndex(array, baseIsNaN, fromIndex); + } + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; +} + +/** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ +function baseIsNaN(value) { + return value !== value; +} + +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +/** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ +function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); +} + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = (isArray(value) || isArguments(value)) + ? baseTimes(value.length, String) + : []; + + var length = result.length, + skipIndexes = !!length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && (key == 'length' || isIndex(key, length)))) { + result.push(key); + } + } + return result; +} + +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; +} + +/** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ +function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); +} + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ +function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); +} + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} + +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; +} + +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; +} + +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} + +/** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ +function values(object) { + return object ? baseValues(object, keys(object)) : []; +} + +module.exports = includes; diff --git a/node_modules/lodash.includes/package.json b/node_modules/lodash.includes/package.json new file mode 100644 index 0000000..a02e645 --- /dev/null +++ b/node_modules/lodash.includes/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.includes", + "version": "4.3.0", + "description": "The lodash method `_.includes` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, includes", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lodash.isboolean/LICENSE b/node_modules/lodash.isboolean/LICENSE new file mode 100644 index 0000000..b054ca5 --- /dev/null +++ b/node_modules/lodash.isboolean/LICENSE @@ -0,0 +1,22 @@ +Copyright 2012-2016 The Dojo Foundation +Based on Underscore.js, copyright 2009-2016 Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/lodash.isboolean/README.md b/node_modules/lodash.isboolean/README.md new file mode 100644 index 0000000..b3c476b --- /dev/null +++ b/node_modules/lodash.isboolean/README.md @@ -0,0 +1,18 @@ +# lodash.isboolean v3.0.3 + +The [lodash](https://lodash.com/) method `_.isBoolean` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.isboolean +``` + +In Node.js: +```js +var isBoolean = require('lodash.isboolean'); +``` + +See the [documentation](https://lodash.com/docs#isBoolean) or [package source](https://github.com/lodash/lodash/blob/3.0.3-npm-packages/lodash.isboolean) for more details. diff --git a/node_modules/lodash.isboolean/index.js b/node_modules/lodash.isboolean/index.js new file mode 100644 index 0000000..23bbabd --- /dev/null +++ b/node_modules/lodash.isboolean/index.js @@ -0,0 +1,70 @@ +/** + * lodash 3.0.3 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ + +/** `Object#toString` result references. */ +var boolTag = '[object Boolean]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ +function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && objectToString.call(value) == boolTag); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +module.exports = isBoolean; diff --git a/node_modules/lodash.isboolean/package.json b/node_modules/lodash.isboolean/package.json new file mode 100644 index 0000000..01d6e8b --- /dev/null +++ b/node_modules/lodash.isboolean/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.isboolean", + "version": "3.0.3", + "description": "The lodash method `_.isBoolean` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, isboolean", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lodash.isinteger/LICENSE b/node_modules/lodash.isinteger/LICENSE new file mode 100644 index 0000000..e0c69d5 --- /dev/null +++ b/node_modules/lodash.isinteger/LICENSE @@ -0,0 +1,47 @@ +Copyright jQuery Foundation and other contributors + +Based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/lodash/lodash + +The following license applies to all parts of this software except as +documented below: + +==== + +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. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +Files located in the node_modules and vendor directories are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/node_modules/lodash.isinteger/README.md b/node_modules/lodash.isinteger/README.md new file mode 100644 index 0000000..3a78567 --- /dev/null +++ b/node_modules/lodash.isinteger/README.md @@ -0,0 +1,18 @@ +# lodash.isinteger v4.0.4 + +The [lodash](https://lodash.com/) method `_.isInteger` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.isinteger +``` + +In Node.js: +```js +var isInteger = require('lodash.isinteger'); +``` + +See the [documentation](https://lodash.com/docs#isInteger) or [package source](https://github.com/lodash/lodash/blob/4.0.4-npm-packages/lodash.isinteger) for more details. diff --git a/node_modules/lodash.isinteger/index.js b/node_modules/lodash.isinteger/index.js new file mode 100644 index 0000000..3bf06f0 --- /dev/null +++ b/node_modules/lodash.isinteger/index.js @@ -0,0 +1,265 @@ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ +function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} + +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; +} + +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; +} + +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} + +module.exports = isInteger; diff --git a/node_modules/lodash.isinteger/package.json b/node_modules/lodash.isinteger/package.json new file mode 100644 index 0000000..92db256 --- /dev/null +++ b/node_modules/lodash.isinteger/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.isinteger", + "version": "4.0.4", + "description": "The lodash method `_.isInteger` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, isinteger", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lodash.isnumber/LICENSE b/node_modules/lodash.isnumber/LICENSE new file mode 100644 index 0000000..b054ca5 --- /dev/null +++ b/node_modules/lodash.isnumber/LICENSE @@ -0,0 +1,22 @@ +Copyright 2012-2016 The Dojo Foundation +Based on Underscore.js, copyright 2009-2016 Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/lodash.isnumber/README.md b/node_modules/lodash.isnumber/README.md new file mode 100644 index 0000000..a1d434d --- /dev/null +++ b/node_modules/lodash.isnumber/README.md @@ -0,0 +1,18 @@ +# lodash.isnumber v3.0.3 + +The [lodash](https://lodash.com/) method `_.isNumber` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.isnumber +``` + +In Node.js: +```js +var isNumber = require('lodash.isnumber'); +``` + +See the [documentation](https://lodash.com/docs#isNumber) or [package source](https://github.com/lodash/lodash/blob/3.0.3-npm-packages/lodash.isnumber) for more details. diff --git a/node_modules/lodash.isnumber/index.js b/node_modules/lodash.isnumber/index.js new file mode 100644 index 0000000..35a8573 --- /dev/null +++ b/node_modules/lodash.isnumber/index.js @@ -0,0 +1,79 @@ +/** + * lodash 3.0.3 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ + +/** `Object#toString` result references. */ +var numberTag = '[object Number]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified + * as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ +function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && objectToString.call(value) == numberTag); +} + +module.exports = isNumber; diff --git a/node_modules/lodash.isnumber/package.json b/node_modules/lodash.isnumber/package.json new file mode 100644 index 0000000..4c33c2a --- /dev/null +++ b/node_modules/lodash.isnumber/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.isnumber", + "version": "3.0.3", + "description": "The lodash method `_.isNumber` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, isnumber", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lodash.isplainobject/LICENSE b/node_modules/lodash.isplainobject/LICENSE new file mode 100644 index 0000000..e0c69d5 --- /dev/null +++ b/node_modules/lodash.isplainobject/LICENSE @@ -0,0 +1,47 @@ +Copyright jQuery Foundation and other contributors + +Based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/lodash/lodash + +The following license applies to all parts of this software except as +documented below: + +==== + +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. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +Files located in the node_modules and vendor directories are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/node_modules/lodash.isplainobject/README.md b/node_modules/lodash.isplainobject/README.md new file mode 100644 index 0000000..aeefd74 --- /dev/null +++ b/node_modules/lodash.isplainobject/README.md @@ -0,0 +1,18 @@ +# lodash.isplainobject v4.0.6 + +The [lodash](https://lodash.com/) method `_.isPlainObject` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.isplainobject +``` + +In Node.js: +```js +var isPlainObject = require('lodash.isplainobject'); +``` + +See the [documentation](https://lodash.com/docs#isPlainObject) or [package source](https://github.com/lodash/lodash/blob/4.0.6-npm-packages/lodash.isplainobject) for more details. diff --git a/node_modules/lodash.isplainobject/index.js b/node_modules/lodash.isplainobject/index.js new file mode 100644 index 0000000..0f820ee --- /dev/null +++ b/node_modules/lodash.isplainobject/index.js @@ -0,0 +1,139 @@ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** `Object#toString` result references. */ +var objectTag = '[object Object]'; + +/** + * Checks if `value` is a host object in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + */ +function isHostObject(value) { + // Many host objects are `Object` objects that can coerce to strings + // despite having improperly defined `toString` methods. + var result = false; + if (value != null && typeof value.toString != 'function') { + try { + result = !!(value + ''); + } catch (e) {} + } + return result; +} + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +/** Used for built-in method references. */ +var funcProto = Function.prototype, + objectProto = Object.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** Used to infer the `Object` constructor. */ +var objectCtorString = funcToString.call(Object); + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** Built-in value references. */ +var getPrototype = overArg(Object.getPrototypeOf, Object); + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ +function isPlainObject(value) { + if (!isObjectLike(value) || + objectToString.call(value) != objectTag || isHostObject(value)) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return (typeof Ctor == 'function' && + Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); +} + +module.exports = isPlainObject; diff --git a/node_modules/lodash.isplainobject/package.json b/node_modules/lodash.isplainobject/package.json new file mode 100644 index 0000000..86f6a07 --- /dev/null +++ b/node_modules/lodash.isplainobject/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.isplainobject", + "version": "4.0.6", + "description": "The lodash method `_.isPlainObject` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, isplainobject", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lodash.isstring/LICENSE b/node_modules/lodash.isstring/LICENSE new file mode 100644 index 0000000..b054ca5 --- /dev/null +++ b/node_modules/lodash.isstring/LICENSE @@ -0,0 +1,22 @@ +Copyright 2012-2016 The Dojo Foundation +Based on Underscore.js, copyright 2009-2016 Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/lodash.isstring/README.md b/node_modules/lodash.isstring/README.md new file mode 100644 index 0000000..f184029 --- /dev/null +++ b/node_modules/lodash.isstring/README.md @@ -0,0 +1,18 @@ +# lodash.isstring v4.0.1 + +The [lodash](https://lodash.com/) method `_.isString` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.isstring +``` + +In Node.js: +```js +var isString = require('lodash.isstring'); +``` + +See the [documentation](https://lodash.com/docs#isString) or [package source](https://github.com/lodash/lodash/blob/4.0.1-npm-packages/lodash.isstring) for more details. diff --git a/node_modules/lodash.isstring/index.js b/node_modules/lodash.isstring/index.js new file mode 100644 index 0000000..408225c --- /dev/null +++ b/node_modules/lodash.isstring/index.js @@ -0,0 +1,95 @@ +/** + * lodash 4.0.1 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ + +/** `Object#toString` result references. */ +var stringTag = '[object String]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @type Function + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ +function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); +} + +module.exports = isString; diff --git a/node_modules/lodash.isstring/package.json b/node_modules/lodash.isstring/package.json new file mode 100644 index 0000000..1331535 --- /dev/null +++ b/node_modules/lodash.isstring/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.isstring", + "version": "4.0.1", + "description": "The lodash method `_.isString` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, isstring", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/lodash.once/LICENSE b/node_modules/lodash.once/LICENSE new file mode 100644 index 0000000..e0c69d5 --- /dev/null +++ b/node_modules/lodash.once/LICENSE @@ -0,0 +1,47 @@ +Copyright jQuery Foundation and other contributors + +Based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/lodash/lodash + +The following license applies to all parts of this software except as +documented below: + +==== + +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. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +Files located in the node_modules and vendor directories are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/node_modules/lodash.once/README.md b/node_modules/lodash.once/README.md new file mode 100644 index 0000000..c4a2f16 --- /dev/null +++ b/node_modules/lodash.once/README.md @@ -0,0 +1,18 @@ +# lodash.once v4.1.1 + +The [lodash](https://lodash.com/) method `_.once` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.once +``` + +In Node.js: +```js +var once = require('lodash.once'); +``` + +See the [documentation](https://lodash.com/docs#once) or [package source](https://github.com/lodash/lodash/blob/4.1.1-npm-packages/lodash.once) for more details. diff --git a/node_modules/lodash.once/index.js b/node_modules/lodash.once/index.js new file mode 100644 index 0000000..414ceb3 --- /dev/null +++ b/node_modules/lodash.once/index.js @@ -0,0 +1,294 @@ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ +function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; +} + +/** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ +function once(func) { + return before(2, func); +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} + +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; +} + +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; +} + +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} + +module.exports = once; diff --git a/node_modules/lodash.once/package.json b/node_modules/lodash.once/package.json new file mode 100644 index 0000000..fae782c --- /dev/null +++ b/node_modules/lodash.once/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.once", + "version": "4.1.1", + "description": "The lodash method `_.once` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, once", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/long/LICENSE b/node_modules/long/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/long/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/long/README.md b/node_modules/long/README.md new file mode 100644 index 0000000..ca4b2f8 --- /dev/null +++ b/node_modules/long/README.md @@ -0,0 +1,286 @@ +# long.js + +A Long class for representing a 64 bit two's-complement integer value derived from the [Closure Library](https://github.com/google/closure-library) +for stand-alone use and extended with unsigned support. + +[![Build Status](https://img.shields.io/github/actions/workflow/status/dcodeIO/long.js/test.yml?branch=main&label=test&logo=github)](https://github.com/dcodeIO/long.js/actions/workflows/test.yml) [![Publish Status](https://img.shields.io/github/actions/workflow/status/dcodeIO/long.js/publish.yml?branch=main&label=publish&logo=github)](https://github.com/dcodeIO/long.js/actions/workflows/publish.yml) [![npm](https://img.shields.io/npm/v/long.svg?label=npm&color=007acc&logo=npm)](https://www.npmjs.com/package/long) + +## Background + +As of [ECMA-262 5th Edition](http://ecma262-5.com/ELS5_HTML.htm#Section_8.5), "all the positive and negative integers +whose magnitude is no greater than 253 are representable in the Number type", which is "representing the +doubleprecision 64-bit format IEEE 754 values as specified in the IEEE Standard for Binary Floating-Point Arithmetic". +The [maximum safe integer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) +in JavaScript is 253-1. + +Example: 264-1 is 1844674407370955**1615** but in JavaScript it evaluates to 1844674407370955**2000**. + +Furthermore, bitwise operators in JavaScript "deal only with integers in the range −231 through +231−1, inclusive, or in the range 0 through 232−1, inclusive. These operators accept any value of +the Number type but first convert each such value to one of 232 integer values." + +In some use cases, however, it is required to be able to reliably work with and perform bitwise operations on the full +64 bits. This is where long.js comes into play. + +## Usage + +The package exports an ECMAScript module with an UMD fallback. + +``` +$> npm install long +``` + +```js +import Long from "long"; + +var value = new Long(0xFFFFFFFF, 0x7FFFFFFF); +console.log(value.toString()); +... +``` + +Note that mixing ESM and CommonJS is not recommended as it yields different classes, albeit with the same functionality. + +### Usage with a CDN + +- From GitHub via [jsDelivr](https://www.jsdelivr.com):
                          + `https://cdn.jsdelivr.net/gh/dcodeIO/long.js@TAG/index.js` (ESM) +- From npm via [jsDelivr](https://www.jsdelivr.com):
                          + `https://cdn.jsdelivr.net/npm/long@VERSION/index.js` (ESM)
                          + `https://cdn.jsdelivr.net/npm/long@VERSION/umd/index.js` (UMD) +- From npm via [unpkg](https://unpkg.com):
                          + `https://unpkg.com/long@VERSION/index.js` (ESM)
                          + `https://unpkg.com/long@VERSION/umd/index.js` (UMD) + +Replace `TAG` respectively `VERSION` with a [specific version](https://github.com/dcodeIO/long.js/releases) or omit it (not recommended in production) to use main/latest. + +## API + +### Constructor + +- new **Long**(low: `number`, high?: `number`, unsigned?: `boolean`)
                          + Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as _signed_ integers. See the from\* functions below for more convenient ways of constructing Longs. + +### Fields + +- Long#**low**: `number`
                          + The low 32 bits as a signed value. + +- Long#**high**: `number`
                          + The high 32 bits as a signed value. + +- Long#**unsigned**: `boolean`
                          + Whether unsigned or not. + +### Constants + +- Long.**ZERO**: `Long`
                          + Signed zero. + +- Long.**ONE**: `Long`
                          + Signed one. + +- Long.**NEG_ONE**: `Long`
                          + Signed negative one. + +- Long.**UZERO**: `Long`
                          + Unsigned zero. + +- Long.**UONE**: `Long`
                          + Unsigned one. + +- Long.**MAX_VALUE**: `Long`
                          + Maximum signed value. + +- Long.**MIN_VALUE**: `Long`
                          + Minimum signed value. + +- Long.**MAX_UNSIGNED_VALUE**: `Long`
                          + Maximum unsigned value. + +### Utility + +- type **LongLike**: `Long | number | bigint | string`
                          + Any value or object that either is or can be converted to a Long. + +- Long.**isLong**(obj: `any`): `boolean`
                          + Tests if the specified object is a Long. + +- Long.**fromBits**(lowBits: `number`, highBits: `number`, unsigned?: `boolean`): `Long`
                          + Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is assumed to use 32 bits. + +- Long.**fromBytes**(bytes: `number[]`, unsigned?: `boolean`, le?: `boolean`): `Long`
                          + Creates a Long from its byte representation. + +- Long.**fromBytesLE**(bytes: `number[]`, unsigned?: `boolean`): `Long`
                          + Creates a Long from its little endian byte representation. + +- Long.**fromBytesBE**(bytes: `number[]`, unsigned?: `boolean`): `Long`
                          + Creates a Long from its big endian byte representation. + +- Long.**fromInt**(value: `number`, unsigned?: `boolean`): `Long`
                          + Returns a Long representing the given 32 bit integer value. + +- Long.**fromNumber**(value: `number`, unsigned?: `boolean`): `Long`
                          + Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + +- Long.**fromBigInt**(value: `bigint`, unsigned?: `boolean`): `Long`
                          + Returns a Long representing the given big integer. + +- Long.**fromString**(str: `string`, unsigned?: `boolean`, radix?: `number`)
                          + Long.**fromString**(str: `string`, radix: `number`)
                          + Returns a Long representation of the given string, written using the specified radix. + +- Long.**fromValue**(val: `LongLike`, unsigned?: `boolean`): `Long`
                          + Converts the specified value to a Long using the appropriate from\* function for its type. + +### Methods + +- Long#**add**(addend: `LongLike`): `Long`
                          + Returns the sum of this and the specified Long. + +- Long#**and**(other: `LongLike`): `Long`
                          + Returns the bitwise AND of this Long and the specified. + +- Long#**compare**/**comp**(other: `LongLike`): `number`
                          + Compares this Long's value with the specified's. Returns `0` if they are the same, `1` if the this is greater and `-1` if the given one is greater. + +- Long#**divide**/**div**(divisor: `LongLike`): `Long`
                          + Returns this Long divided by the specified. + +- Long#**equals**/**eq**(other: `LongLike`): `boolean`
                          + Tests if this Long's value equals the specified's. + +- Long#**getHighBits**(): `number`
                          + Gets the high 32 bits as a signed integer. + +- Long#**getHighBitsUnsigned**(): `number`
                          + Gets the high 32 bits as an unsigned integer. + +- Long#**getLowBits**(): `number`
                          + Gets the low 32 bits as a signed integer. + +- Long#**getLowBitsUnsigned**(): `number`
                          + Gets the low 32 bits as an unsigned integer. + +- Long#**getNumBitsAbs**(): `number`
                          + Gets the number of bits needed to represent the absolute value of this Long. + +- Long#**greaterThan**/**gt**(other: `LongLike`): `boolean`
                          + Tests if this Long's value is greater than the specified's. + +- Long#**greaterThanOrEqual**/**gte**/**ge**(other: `LongLike`): `boolean`
                          + Tests if this Long's value is greater than or equal the specified's. + +- Long#**isEven**(): `boolean`
                          + Tests if this Long's value is even. + +- Long#**isNegative**(): `boolean`
                          + Tests if this Long's value is negative. + +- Long#**isOdd**(): `boolean`
                          + Tests if this Long's value is odd. + +- Long#**isPositive**(): `boolean`
                          + Tests if this Long's value is positive or zero. + +- Long#**isSafeInteger**(): `boolean`
                          + Tests if this Long can be safely represented as a JavaScript number. + +- Long#**isZero**/**eqz**(): `boolean`
                          + Tests if this Long's value equals zero. + +- Long#**lessThan**/**lt**(other: `LongLike`): `boolean`
                          + Tests if this Long's value is less than the specified's. + +- Long#**lessThanOrEqual**/**lte**/**le**(other: `LongLike`): `boolean`
                          + Tests if this Long's value is less than or equal the specified's. + +- Long#**modulo**/**mod**/**rem**(divisor: `LongLike`): `Long`
                          + Returns this Long modulo the specified. + +- Long#**multiply**/**mul**(multiplier: `LongLike`): `Long`
                          + Returns the product of this and the specified Long. + +- Long#**negate**/**neg**(): `Long`
                          + Negates this Long's value. + +- Long#**not**(): `Long`
                          + Returns the bitwise NOT of this Long. + +- Long#**countLeadingZeros**/**clz**(): `number`
                          + Returns count leading zeros of this Long. + +- Long#**countTrailingZeros**/**ctz**(): `number`
                          + Returns count trailing zeros of this Long. + +- Long#**notEquals**/**neq**/**ne**(other: `LongLike`): `boolean`
                          + Tests if this Long's value differs from the specified's. + +- Long#**or**(other: `LongLike`): `Long`
                          + Returns the bitwise OR of this Long and the specified. + +- Long#**shiftLeft**/**shl**(numBits: `Long | number`): `Long`
                          + Returns this Long with bits shifted to the left by the given amount. + +- Long#**shiftRight**/**shr**(numBits: `Long | number`): `Long`
                          + Returns this Long with bits arithmetically shifted to the right by the given amount. + +- Long#**shiftRightUnsigned**/**shru**/**shr_u**(numBits: `Long | number`): `Long`
                          + Returns this Long with bits logically shifted to the right by the given amount. + +- Long#**rotateLeft**/**rotl**(numBits: `Long | number`): `Long`
                          + Returns this Long with bits rotated to the left by the given amount. + +- Long#**rotateRight**/**rotr**(numBits: `Long | number`): `Long`
                          + Returns this Long with bits rotated to the right by the given amount. + +- Long#**subtract**/**sub**(subtrahend: `LongLike`): `Long`
                          + Returns the difference of this and the specified Long. + +- Long#**toBytes**(le?: `boolean`): `number[]`
                          + Converts this Long to its byte representation. + +- Long#**toBytesLE**(): `number[]`
                          + Converts this Long to its little endian byte representation. + +- Long#**toBytesBE**(): `number[]`
                          + Converts this Long to its big endian byte representation. + +- Long#**toInt**(): `number`
                          + Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. + +- Long#**toNumber**(): `number`
                          + Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). + +- Long#**toBigInt**(): `bigint`
                          + Converts the Long to its big integer representation. + +- Long#**toSigned**(): `Long`
                          + Converts this Long to signed. + +- Long#**toString**(radix?: `number`): `string`
                          + Converts the Long to a string written in the specified radix. + +- Long#**toUnsigned**(): `Long`
                          + Converts this Long to unsigned. + +- Long#**xor**(other: `Long | number | string`): `Long`
                          + Returns the bitwise XOR of this Long and the given one. + +## WebAssembly support + +[WebAssembly](http://webassembly.org) supports 64-bit integer arithmetic out of the box, hence a [tiny WebAssembly module](./wasm.wat) is used to compute operations like multiplication, division and remainder more efficiently (slow operations like division are around twice as fast), falling back to floating point based computations in JavaScript where WebAssembly is not yet supported, e.g., in older versions of node. + +## Building + +Building the UMD fallback: + +``` +$> npm run build +``` + +Running the [tests](./tests): + +``` +$> npm test +``` diff --git a/node_modules/long/index.d.ts b/node_modules/long/index.d.ts new file mode 100644 index 0000000..7d4b017 --- /dev/null +++ b/node_modules/long/index.d.ts @@ -0,0 +1,2 @@ +import { Long } from "./types.js"; +export default Long; diff --git a/node_modules/long/index.js b/node_modules/long/index.js new file mode 100644 index 0000000..4983233 --- /dev/null +++ b/node_modules/long/index.js @@ -0,0 +1,1581 @@ +/** + * @license + * Copyright 2009 The Closure Library Authors + * Copyright 2020 Daniel Wirtz / The long.js Authors. + * + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +// WebAssembly optimizations to do native i64 multiplication and divide +var wasm = null; +try { + wasm = new WebAssembly.Instance( + new WebAssembly.Module( + new Uint8Array([ + // \0asm + 0, 97, 115, 109, + // version 1 + 1, 0, 0, 0, + + // section "type" + 1, 13, 2, + // 0, () => i32 + 96, 0, 1, 127, + // 1, (i32, i32, i32, i32) => i32 + 96, 4, 127, 127, 127, 127, 1, 127, + + // section "function" + 3, 7, 6, + // 0, type 0 + 0, + // 1, type 1 + 1, + // 2, type 1 + 1, + // 3, type 1 + 1, + // 4, type 1 + 1, + // 5, type 1 + 1, + + // section "global" + 6, 6, 1, + // 0, "high", mutable i32 + 127, 1, 65, 0, 11, + + // section "export" + 7, 50, 6, + // 0, "mul" + 3, 109, 117, 108, 0, 1, + // 1, "div_s" + 5, 100, 105, 118, 95, 115, 0, 2, + // 2, "div_u" + 5, 100, 105, 118, 95, 117, 0, 3, + // 3, "rem_s" + 5, 114, 101, 109, 95, 115, 0, 4, + // 4, "rem_u" + 5, 114, 101, 109, 95, 117, 0, 5, + // 5, "get_high" + 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, + + // section "code" + 10, 191, 1, 6, + // 0, "get_high" + 4, 0, 35, 0, 11, + // 1, "mul" + 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, + 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, + 167, 11, + // 2, "div_s" + 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, + 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, + 167, 11, + // 3, "div_u" + 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, + 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, + 167, 11, + // 4, "rem_s" + 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, + 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, + 167, 11, + // 5, "rem_u" + 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, + 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, + 167, 11, + ]), + ), + {}, + ).exports; +} catch { + // no wasm support :( +} + +/** + * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. + * See the from* functions below for more convenient ways of constructing Longs. + * @exports Long + * @class A Long class for representing a 64 bit two's-complement integer value. + * @param {number} low The low (signed) 32 bits of the long + * @param {number} high The high (signed) 32 bits of the long + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @constructor + */ +function Long(low, high, unsigned) { + /** + * The low 32 bits as a signed value. + * @type {number} + */ + this.low = low | 0; + + /** + * The high 32 bits as a signed value. + * @type {number} + */ + this.high = high | 0; + + /** + * Whether unsigned or not. + * @type {boolean} + */ + this.unsigned = !!unsigned; +} + +// The internal representation of a long is the two given signed, 32-bit values. +// We use 32-bit pieces because these are the size of integers on which +// Javascript performs bit-operations. For operations like addition and +// multiplication, we split each number into 16 bit pieces, which can easily be +// multiplied within Javascript's floating-point representation without overflow +// or change in sign. +// +// In the algorithms below, we frequently reduce the negative case to the +// positive case by negating the input(s) and then post-processing the result. +// Note that we must ALWAYS check specially whether those values are MIN_VALUE +// (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as +// a positive number, it overflows back into a negative). Not handling this +// case would often result in infinite recursion. +// +// Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from* +// methods on which they depend. + +/** + * An indicator used to reliably determine if an object is a Long or not. + * @type {boolean} + * @const + * @private + */ +Long.prototype.__isLong__; + +Object.defineProperty(Long.prototype, "__isLong__", { value: true }); + +/** + * @function + * @param {*} obj Object + * @returns {boolean} + * @inner + */ +function isLong(obj) { + return (obj && obj["__isLong__"]) === true; +} + +/** + * @function + * @param {*} value number + * @returns {number} + * @inner + */ +function ctz32(value) { + var c = Math.clz32(value & -value); + return value ? 31 - c : c; +} + +/** + * Tests if the specified object is a Long. + * @function + * @param {*} obj Object + * @returns {boolean} + */ +Long.isLong = isLong; + +/** + * A cache of the Long representations of small integer values. + * @type {!Object} + * @inner + */ +var INT_CACHE = {}; + +/** + * A cache of the Long representations of small unsigned integer values. + * @type {!Object} + * @inner + */ +var UINT_CACHE = {}; + +/** + * @param {number} value + * @param {boolean=} unsigned + * @returns {!Long} + * @inner + */ +function fromInt(value, unsigned) { + var obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if ((cache = 0 <= value && value < 256)) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) return cachedObj; + } + obj = fromBits(value, 0, true); + if (cache) UINT_CACHE[value] = obj; + return obj; + } else { + value |= 0; + if ((cache = -128 <= value && value < 128)) { + cachedObj = INT_CACHE[value]; + if (cachedObj) return cachedObj; + } + obj = fromBits(value, value < 0 ? -1 : 0, false); + if (cache) INT_CACHE[value] = obj; + return obj; + } +} + +/** + * Returns a Long representing the given 32 bit integer value. + * @function + * @param {number} value The 32 bit integer in question + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} The corresponding Long value + */ +Long.fromInt = fromInt; + +/** + * @param {number} value + * @param {boolean=} unsigned + * @returns {!Long} + * @inner + */ +function fromNumber(value, unsigned) { + if (isNaN(value)) return unsigned ? UZERO : ZERO; + if (unsigned) { + if (value < 0) return UZERO; + if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE; + } else { + if (value <= -TWO_PWR_63_DBL) return MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) return MAX_VALUE; + } + if (value < 0) return fromNumber(-value, unsigned).neg(); + return fromBits( + value % TWO_PWR_32_DBL | 0, + (value / TWO_PWR_32_DBL) | 0, + unsigned, + ); +} + +/** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @function + * @param {number} value The number in question + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} The corresponding Long value + */ +Long.fromNumber = fromNumber; + +/** + * @param {number} lowBits + * @param {number} highBits + * @param {boolean=} unsigned + * @returns {!Long} + * @inner + */ +function fromBits(lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); +} + +/** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is + * assumed to use 32 bits. + * @function + * @param {number} lowBits The low 32 bits + * @param {number} highBits The high 32 bits + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} The corresponding Long value + */ +Long.fromBits = fromBits; + +/** + * @function + * @param {number} base + * @param {number} exponent + * @returns {number} + * @inner + */ +var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4) + +/** + * @param {string} str + * @param {(boolean|number)=} unsigned + * @param {number=} radix + * @returns {!Long} + * @inner + */ +function fromString(str, unsigned, radix) { + if (str.length === 0) throw Error("empty string"); + if (typeof unsigned === "number") { + // For goog.math.long compatibility + radix = unsigned; + unsigned = false; + } else { + unsigned = !!unsigned; + } + if ( + str === "NaN" || + str === "Infinity" || + str === "+Infinity" || + str === "-Infinity" + ) + return unsigned ? UZERO : ZERO; + radix = radix || 10; + if (radix < 2 || 36 < radix) throw RangeError("radix"); + + var p; + if ((p = str.indexOf("-")) > 0) throw Error("interior hyphen"); + else if (p === 0) { + return fromString(str.substring(1), unsigned, radix).neg(); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = fromNumber(pow_dbl(radix, 8)); + + var result = ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i), + value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = fromNumber(pow_dbl(radix, size)); + result = result.mul(power).add(fromNumber(value)); + } else { + result = result.mul(radixToPower); + result = result.add(fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; +} + +/** + * Returns a Long representation of the given string, written using the specified radix. + * @function + * @param {string} str The textual representation of the Long + * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to signed + * @param {number=} radix The radix in which the text is written (2-36), defaults to 10 + * @returns {!Long} The corresponding Long value + */ +Long.fromString = fromString; + +/** + * @function + * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val + * @param {boolean=} unsigned + * @returns {!Long} + * @inner + */ +function fromValue(val, unsigned) { + if (typeof val === "number") return fromNumber(val, unsigned); + if (typeof val === "string") return fromString(val, unsigned); + // Throws for non-objects, converts non-instanceof Long: + return fromBits( + val.low, + val.high, + typeof unsigned === "boolean" ? unsigned : val.unsigned, + ); +} + +/** + * Converts the specified value to a Long using the appropriate from* function for its type. + * @function + * @param {!Long|number|bigint|string|!{low: number, high: number, unsigned: boolean}} val Value + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} + */ +Long.fromValue = fromValue; + +// NOTE: the compiler should inline these constant values below and then remove these variables, so there should be +// no runtime penalty for these. + +/** + * @type {number} + * @const + * @inner + */ +var TWO_PWR_16_DBL = 1 << 16; + +/** + * @type {number} + * @const + * @inner + */ +var TWO_PWR_24_DBL = 1 << 24; + +/** + * @type {number} + * @const + * @inner + */ +var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; + +/** + * @type {number} + * @const + * @inner + */ +var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; + +/** + * @type {number} + * @const + * @inner + */ +var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; + +/** + * @type {!Long} + * @const + * @inner + */ +var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL); + +/** + * @type {!Long} + * @inner + */ +var ZERO = fromInt(0); + +/** + * Signed zero. + * @type {!Long} + */ +Long.ZERO = ZERO; + +/** + * @type {!Long} + * @inner + */ +var UZERO = fromInt(0, true); + +/** + * Unsigned zero. + * @type {!Long} + */ +Long.UZERO = UZERO; + +/** + * @type {!Long} + * @inner + */ +var ONE = fromInt(1); + +/** + * Signed one. + * @type {!Long} + */ +Long.ONE = ONE; + +/** + * @type {!Long} + * @inner + */ +var UONE = fromInt(1, true); + +/** + * Unsigned one. + * @type {!Long} + */ +Long.UONE = UONE; + +/** + * @type {!Long} + * @inner + */ +var NEG_ONE = fromInt(-1); + +/** + * Signed negative one. + * @type {!Long} + */ +Long.NEG_ONE = NEG_ONE; + +/** + * @type {!Long} + * @inner + */ +var MAX_VALUE = fromBits(0xffffffff | 0, 0x7fffffff | 0, false); + +/** + * Maximum signed value. + * @type {!Long} + */ +Long.MAX_VALUE = MAX_VALUE; + +/** + * @type {!Long} + * @inner + */ +var MAX_UNSIGNED_VALUE = fromBits(0xffffffff | 0, 0xffffffff | 0, true); + +/** + * Maximum unsigned value. + * @type {!Long} + */ +Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE; + +/** + * @type {!Long} + * @inner + */ +var MIN_VALUE = fromBits(0, 0x80000000 | 0, false); + +/** + * Minimum signed value. + * @type {!Long} + */ +Long.MIN_VALUE = MIN_VALUE; + +/** + * @alias Long.prototype + * @inner + */ +var LongPrototype = Long.prototype; + +/** + * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. + * @this {!Long} + * @returns {number} + */ +LongPrototype.toInt = function toInt() { + return this.unsigned ? this.low >>> 0 : this.low; +}; + +/** + * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). + * @this {!Long} + * @returns {number} + */ +LongPrototype.toNumber = function toNumber() { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); +}; + +/** + * Converts the Long to a string written in the specified radix. + * @this {!Long} + * @param {number=} radix Radix (2-36), defaults to 10 + * @returns {string} + * @override + * @throws {RangeError} If `radix` is out of range + */ +LongPrototype.toString = function toString(radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) throw RangeError("radix"); + if (this.isZero()) return "0"; + if (this.isNegative()) { + // Unsigned Longs are never negative + if (this.eq(MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = fromNumber(radix), + div = this.div(radixLong), + rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } else return "-" + this.neg().toString(radix); + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), + rem = this; + var result = ""; + while (true) { + var remDiv = rem.div(radixToPower), + intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, + digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) return digits + result; + else { + while (digits.length < 6) digits = "0" + digits; + result = "" + digits + result; + } + } +}; + +/** + * Gets the high 32 bits as a signed integer. + * @this {!Long} + * @returns {number} Signed high bits + */ +LongPrototype.getHighBits = function getHighBits() { + return this.high; +}; + +/** + * Gets the high 32 bits as an unsigned integer. + * @this {!Long} + * @returns {number} Unsigned high bits + */ +LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() { + return this.high >>> 0; +}; + +/** + * Gets the low 32 bits as a signed integer. + * @this {!Long} + * @returns {number} Signed low bits + */ +LongPrototype.getLowBits = function getLowBits() { + return this.low; +}; + +/** + * Gets the low 32 bits as an unsigned integer. + * @this {!Long} + * @returns {number} Unsigned low bits + */ +LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() { + return this.low >>> 0; +}; + +/** + * Gets the number of bits needed to represent the absolute value of this Long. + * @this {!Long} + * @returns {number} + */ +LongPrototype.getNumBitsAbs = function getNumBitsAbs() { + if (this.isNegative()) + // Unsigned Longs are never negative + return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + var val = this.high != 0 ? this.high : this.low; + for (var bit = 31; bit > 0; bit--) if ((val & (1 << bit)) != 0) break; + return this.high != 0 ? bit + 33 : bit + 1; +}; + +/** + * Tests if this Long can be safely represented as a JavaScript number. + * @this {!Long} + * @returns {boolean} + */ +LongPrototype.isSafeInteger = function isSafeInteger() { + // 2^53-1 is the maximum safe value + var top11Bits = this.high >> 21; + // [0, 2^53-1] + if (!top11Bits) return true; + // > 2^53-1 + if (this.unsigned) return false; + // [-2^53, -1] except -2^53 + return top11Bits === -1 && !(this.low === 0 && this.high === -0x200000); +}; + +/** + * Tests if this Long's value equals zero. + * @this {!Long} + * @returns {boolean} + */ +LongPrototype.isZero = function isZero() { + return this.high === 0 && this.low === 0; +}; + +/** + * Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}. + * @returns {boolean} + */ +LongPrototype.eqz = LongPrototype.isZero; + +/** + * Tests if this Long's value is negative. + * @this {!Long} + * @returns {boolean} + */ +LongPrototype.isNegative = function isNegative() { + return !this.unsigned && this.high < 0; +}; + +/** + * Tests if this Long's value is positive or zero. + * @this {!Long} + * @returns {boolean} + */ +LongPrototype.isPositive = function isPositive() { + return this.unsigned || this.high >= 0; +}; + +/** + * Tests if this Long's value is odd. + * @this {!Long} + * @returns {boolean} + */ +LongPrototype.isOdd = function isOdd() { + return (this.low & 1) === 1; +}; + +/** + * Tests if this Long's value is even. + * @this {!Long} + * @returns {boolean} + */ +LongPrototype.isEven = function isEven() { + return (this.low & 1) === 0; +}; + +/** + * Tests if this Long's value equals the specified's. + * @this {!Long} + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ +LongPrototype.equals = function equals(other) { + if (!isLong(other)) other = fromValue(other); + if ( + this.unsigned !== other.unsigned && + this.high >>> 31 === 1 && + other.high >>> 31 === 1 + ) + return false; + return this.high === other.high && this.low === other.low; +}; + +/** + * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}. + * @function + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ +LongPrototype.eq = LongPrototype.equals; + +/** + * Tests if this Long's value differs from the specified's. + * @this {!Long} + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ +LongPrototype.notEquals = function notEquals(other) { + return !this.eq(/* validates */ other); +}; + +/** + * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}. + * @function + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ +LongPrototype.neq = LongPrototype.notEquals; + +/** + * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}. + * @function + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ +LongPrototype.ne = LongPrototype.notEquals; + +/** + * Tests if this Long's value is less than the specified's. + * @this {!Long} + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ +LongPrototype.lessThan = function lessThan(other) { + return this.comp(/* validates */ other) < 0; +}; + +/** + * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}. + * @function + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ +LongPrototype.lt = LongPrototype.lessThan; + +/** + * Tests if this Long's value is less than or equal the specified's. + * @this {!Long} + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ +LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) { + return this.comp(/* validates */ other) <= 0; +}; + +/** + * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}. + * @function + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ +LongPrototype.lte = LongPrototype.lessThanOrEqual; + +/** + * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}. + * @function + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ +LongPrototype.le = LongPrototype.lessThanOrEqual; + +/** + * Tests if this Long's value is greater than the specified's. + * @this {!Long} + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ +LongPrototype.greaterThan = function greaterThan(other) { + return this.comp(/* validates */ other) > 0; +}; + +/** + * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}. + * @function + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ +LongPrototype.gt = LongPrototype.greaterThan; + +/** + * Tests if this Long's value is greater than or equal the specified's. + * @this {!Long} + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ +LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) { + return this.comp(/* validates */ other) >= 0; +}; + +/** + * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}. + * @function + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ +LongPrototype.gte = LongPrototype.greaterThanOrEqual; + +/** + * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}. + * @function + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ +LongPrototype.ge = LongPrototype.greaterThanOrEqual; + +/** + * Compares this Long's value with the specified's. + * @this {!Long} + * @param {!Long|number|bigint|string} other Other value + * @returns {number} 0 if they are the same, 1 if the this is greater and -1 + * if the given one is greater + */ +LongPrototype.compare = function compare(other) { + if (!isLong(other)) other = fromValue(other); + if (this.eq(other)) return 0; + var thisNeg = this.isNegative(), + otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) return -1; + if (!thisNeg && otherNeg) return 1; + // At this point the sign bits are the same + if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1; + // Both are positive if at least one is unsigned + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; +}; + +/** + * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}. + * @function + * @param {!Long|number|bigint|string} other Other value + * @returns {number} 0 if they are the same, 1 if the this is greater and -1 + * if the given one is greater + */ +LongPrototype.comp = LongPrototype.compare; + +/** + * Negates this Long's value. + * @this {!Long} + * @returns {!Long} Negated Long + */ +LongPrototype.negate = function negate() { + if (!this.unsigned && this.eq(MIN_VALUE)) return MIN_VALUE; + return this.not().add(ONE); +}; + +/** + * Negates this Long's value. This is an alias of {@link Long#negate}. + * @function + * @returns {!Long} Negated Long + */ +LongPrototype.neg = LongPrototype.negate; + +/** + * Returns the sum of this and the specified Long. + * @this {!Long} + * @param {!Long|number|bigint|string} addend Addend + * @returns {!Long} Sum + */ +LongPrototype.add = function add(addend) { + if (!isLong(addend)) addend = fromValue(addend); + + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high >>> 16; + var a32 = this.high & 0xffff; + var a16 = this.low >>> 16; + var a00 = this.low & 0xffff; + + var b48 = addend.high >>> 16; + var b32 = addend.high & 0xffff; + var b16 = addend.low >>> 16; + var b00 = addend.low & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); +}; + +/** + * Returns the difference of this and the specified Long. + * @this {!Long} + * @param {!Long|number|bigint|string} subtrahend Subtrahend + * @returns {!Long} Difference + */ +LongPrototype.subtract = function subtract(subtrahend) { + if (!isLong(subtrahend)) subtrahend = fromValue(subtrahend); + return this.add(subtrahend.neg()); +}; + +/** + * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}. + * @function + * @param {!Long|number|bigint|string} subtrahend Subtrahend + * @returns {!Long} Difference + */ +LongPrototype.sub = LongPrototype.subtract; + +/** + * Returns the product of this and the specified Long. + * @this {!Long} + * @param {!Long|number|bigint|string} multiplier Multiplier + * @returns {!Long} Product + */ +LongPrototype.multiply = function multiply(multiplier) { + if (this.isZero()) return this; + if (!isLong(multiplier)) multiplier = fromValue(multiplier); + + // use wasm support if present + if (wasm) { + var low = wasm["mul"](this.low, this.high, multiplier.low, multiplier.high); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + + if (multiplier.isZero()) return this.unsigned ? UZERO : ZERO; + if (this.eq(MIN_VALUE)) return multiplier.isOdd() ? MIN_VALUE : ZERO; + if (multiplier.eq(MIN_VALUE)) return this.isOdd() ? MIN_VALUE : ZERO; + + if (this.isNegative()) { + if (multiplier.isNegative()) return this.neg().mul(multiplier.neg()); + else return this.neg().mul(multiplier).neg(); + } else if (multiplier.isNegative()) return this.mul(multiplier.neg()).neg(); + + // If both longs are small, use float multiplication + if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24)) + return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + + // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high >>> 16; + var a32 = this.high & 0xffff; + var a16 = this.low >>> 16; + var a00 = this.low & 0xffff; + + var b48 = multiplier.high >>> 16; + var b32 = multiplier.high & 0xffff; + var b16 = multiplier.low >>> 16; + var b00 = multiplier.low & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); +}; + +/** + * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}. + * @function + * @param {!Long|number|bigint|string} multiplier Multiplier + * @returns {!Long} Product + */ +LongPrototype.mul = LongPrototype.multiply; + +/** + * Returns this Long divided by the specified. The result is signed if this Long is signed or + * unsigned if this Long is unsigned. + * @this {!Long} + * @param {!Long|number|bigint|string} divisor Divisor + * @returns {!Long} Quotient + */ +LongPrototype.divide = function divide(divisor) { + if (!isLong(divisor)) divisor = fromValue(divisor); + if (divisor.isZero()) throw Error("division by zero"); + + // use wasm support if present + if (wasm) { + // guard against signed division overflow: the largest + // negative number / -1 would be 1 larger than the largest + // positive number, due to two's complement. + if ( + !this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1 + ) { + // be consistent with non-wasm code path + return this; + } + var low = (this.unsigned ? wasm["div_u"] : wasm["div_s"])( + this.low, + this.high, + divisor.low, + divisor.high, + ); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + + if (this.isZero()) return this.unsigned ? UZERO : ZERO; + var approx, rem, res; + if (!this.unsigned) { + // This section is only relevant for signed longs and is derived from the + // closure library as a whole. + if (this.eq(MIN_VALUE)) { + if (divisor.eq(ONE) || divisor.eq(NEG_ONE)) + return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + else if (divisor.eq(MIN_VALUE)) return ONE; + else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(ZERO)) { + return divisor.isNegative() ? ONE : NEG_ONE; + } else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } else if (divisor.eq(MIN_VALUE)) return this.unsigned ? UZERO : ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } else if (divisor.isNegative()) return this.div(divisor.neg()).neg(); + res = ZERO; + } else { + // The algorithm below has not been made for unsigned longs. It's therefore + // required to take special care of the MSB prior to running it. + if (!divisor.unsigned) divisor = divisor.toUnsigned(); + if (divisor.gt(this)) return UZERO; + if (divisor.gt(this.shru(1))) + // 15 >>> 1 = 7 ; with divisor = 8 ; true + return UONE; + res = UZERO; + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + rem = this; + while (rem.gte(divisor)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2), + delta = log2 <= 48 ? 1 : pow_dbl(2, log2 - 48), + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + approxRes = fromNumber(approx), + approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) approxRes = ONE; + + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; +}; + +/** + * Returns this Long divided by the specified. This is an alias of {@link Long#divide}. + * @function + * @param {!Long|number|bigint|string} divisor Divisor + * @returns {!Long} Quotient + */ +LongPrototype.div = LongPrototype.divide; + +/** + * Returns this Long modulo the specified. + * @this {!Long} + * @param {!Long|number|bigint|string} divisor Divisor + * @returns {!Long} Remainder + */ +LongPrototype.modulo = function modulo(divisor) { + if (!isLong(divisor)) divisor = fromValue(divisor); + + // use wasm support if present + if (wasm) { + var low = (this.unsigned ? wasm["rem_u"] : wasm["rem_s"])( + this.low, + this.high, + divisor.low, + divisor.high, + ); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + + return this.sub(this.div(divisor).mul(divisor)); +}; + +/** + * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}. + * @function + * @param {!Long|number|bigint|string} divisor Divisor + * @returns {!Long} Remainder + */ +LongPrototype.mod = LongPrototype.modulo; + +/** + * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}. + * @function + * @param {!Long|number|bigint|string} divisor Divisor + * @returns {!Long} Remainder + */ +LongPrototype.rem = LongPrototype.modulo; + +/** + * Returns the bitwise NOT of this Long. + * @this {!Long} + * @returns {!Long} + */ +LongPrototype.not = function not() { + return fromBits(~this.low, ~this.high, this.unsigned); +}; + +/** + * Returns count leading zeros of this Long. + * @this {!Long} + * @returns {!number} + */ +LongPrototype.countLeadingZeros = function countLeadingZeros() { + return this.high ? Math.clz32(this.high) : Math.clz32(this.low) + 32; +}; + +/** + * Returns count leading zeros. This is an alias of {@link Long#countLeadingZeros}. + * @function + * @param {!Long} + * @returns {!number} + */ +LongPrototype.clz = LongPrototype.countLeadingZeros; + +/** + * Returns count trailing zeros of this Long. + * @this {!Long} + * @returns {!number} + */ +LongPrototype.countTrailingZeros = function countTrailingZeros() { + return this.low ? ctz32(this.low) : ctz32(this.high) + 32; +}; + +/** + * Returns count trailing zeros. This is an alias of {@link Long#countTrailingZeros}. + * @function + * @param {!Long} + * @returns {!number} + */ +LongPrototype.ctz = LongPrototype.countTrailingZeros; + +/** + * Returns the bitwise AND of this Long and the specified. + * @this {!Long} + * @param {!Long|number|bigint|string} other Other Long + * @returns {!Long} + */ +LongPrototype.and = function and(other) { + if (!isLong(other)) other = fromValue(other); + return fromBits(this.low & other.low, this.high & other.high, this.unsigned); +}; + +/** + * Returns the bitwise OR of this Long and the specified. + * @this {!Long} + * @param {!Long|number|bigint|string} other Other Long + * @returns {!Long} + */ +LongPrototype.or = function or(other) { + if (!isLong(other)) other = fromValue(other); + return fromBits(this.low | other.low, this.high | other.high, this.unsigned); +}; + +/** + * Returns the bitwise XOR of this Long and the given one. + * @this {!Long} + * @param {!Long|number|bigint|string} other Other Long + * @returns {!Long} + */ +LongPrototype.xor = function xor(other) { + if (!isLong(other)) other = fromValue(other); + return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); +}; + +/** + * Returns this Long with bits shifted to the left by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shiftLeft = function shiftLeft(numBits) { + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + else if (numBits < 32) + return fromBits( + this.low << numBits, + (this.high << numBits) | (this.low >>> (32 - numBits)), + this.unsigned, + ); + else return fromBits(0, this.low << (numBits - 32), this.unsigned); +}; + +/** + * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shl = LongPrototype.shiftLeft; + +/** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shiftRight = function shiftRight(numBits) { + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + else if (numBits < 32) + return fromBits( + (this.low >>> numBits) | (this.high << (32 - numBits)), + this.high >> numBits, + this.unsigned, + ); + else + return fromBits( + this.high >> (numBits - 32), + this.high >= 0 ? 0 : -1, + this.unsigned, + ); +}; + +/** + * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shr = LongPrototype.shiftRight; + +/** + * Returns this Long with bits logically shifted to the right by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) { + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + if (numBits < 32) + return fromBits( + (this.low >>> numBits) | (this.high << (32 - numBits)), + this.high >>> numBits, + this.unsigned, + ); + if (numBits === 32) return fromBits(this.high, 0, this.unsigned); + return fromBits(this.high >>> (numBits - 32), 0, this.unsigned); +}; + +/** + * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shru = LongPrototype.shiftRightUnsigned; + +/** + * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shr_u = LongPrototype.shiftRightUnsigned; + +/** + * Returns this Long with bits rotated to the left by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Rotated Long + */ +LongPrototype.rotateLeft = function rotateLeft(numBits) { + var b; + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); + if (numBits < 32) { + b = 32 - numBits; + return fromBits( + (this.low << numBits) | (this.high >>> b), + (this.high << numBits) | (this.low >>> b), + this.unsigned, + ); + } + numBits -= 32; + b = 32 - numBits; + return fromBits( + (this.high << numBits) | (this.low >>> b), + (this.low << numBits) | (this.high >>> b), + this.unsigned, + ); +}; +/** + * Returns this Long with bits rotated to the left by the given amount. This is an alias of {@link Long#rotateLeft}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Rotated Long + */ +LongPrototype.rotl = LongPrototype.rotateLeft; + +/** + * Returns this Long with bits rotated to the right by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Rotated Long + */ +LongPrototype.rotateRight = function rotateRight(numBits) { + var b; + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); + if (numBits < 32) { + b = 32 - numBits; + return fromBits( + (this.high << b) | (this.low >>> numBits), + (this.low << b) | (this.high >>> numBits), + this.unsigned, + ); + } + numBits -= 32; + b = 32 - numBits; + return fromBits( + (this.low << b) | (this.high >>> numBits), + (this.high << b) | (this.low >>> numBits), + this.unsigned, + ); +}; +/** + * Returns this Long with bits rotated to the right by the given amount. This is an alias of {@link Long#rotateRight}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Rotated Long + */ +LongPrototype.rotr = LongPrototype.rotateRight; + +/** + * Converts this Long to signed. + * @this {!Long} + * @returns {!Long} Signed long + */ +LongPrototype.toSigned = function toSigned() { + if (!this.unsigned) return this; + return fromBits(this.low, this.high, false); +}; + +/** + * Converts this Long to unsigned. + * @this {!Long} + * @returns {!Long} Unsigned long + */ +LongPrototype.toUnsigned = function toUnsigned() { + if (this.unsigned) return this; + return fromBits(this.low, this.high, true); +}; + +/** + * Converts this Long to its byte representation. + * @param {boolean=} le Whether little or big endian, defaults to big endian + * @this {!Long} + * @returns {!Array.} Byte representation + */ +LongPrototype.toBytes = function toBytes(le) { + return le ? this.toBytesLE() : this.toBytesBE(); +}; + +/** + * Converts this Long to its little endian byte representation. + * @this {!Long} + * @returns {!Array.} Little endian byte representation + */ +LongPrototype.toBytesLE = function toBytesLE() { + var hi = this.high, + lo = this.low; + return [ + lo & 0xff, + (lo >>> 8) & 0xff, + (lo >>> 16) & 0xff, + lo >>> 24, + hi & 0xff, + (hi >>> 8) & 0xff, + (hi >>> 16) & 0xff, + hi >>> 24, + ]; +}; + +/** + * Converts this Long to its big endian byte representation. + * @this {!Long} + * @returns {!Array.} Big endian byte representation + */ +LongPrototype.toBytesBE = function toBytesBE() { + var hi = this.high, + lo = this.low; + return [ + hi >>> 24, + (hi >>> 16) & 0xff, + (hi >>> 8) & 0xff, + hi & 0xff, + lo >>> 24, + (lo >>> 16) & 0xff, + (lo >>> 8) & 0xff, + lo & 0xff, + ]; +}; + +/** + * Creates a Long from its byte representation. + * @param {!Array.} bytes Byte representation + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @param {boolean=} le Whether little or big endian, defaults to big endian + * @returns {Long} The corresponding Long value + */ +Long.fromBytes = function fromBytes(bytes, unsigned, le) { + return le + ? Long.fromBytesLE(bytes, unsigned) + : Long.fromBytesBE(bytes, unsigned); +}; + +/** + * Creates a Long from its little endian byte representation. + * @param {!Array.} bytes Little endian byte representation + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {Long} The corresponding Long value + */ +Long.fromBytesLE = function fromBytesLE(bytes, unsigned) { + return new Long( + bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), + bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), + unsigned, + ); +}; + +/** + * Creates a Long from its big endian byte representation. + * @param {!Array.} bytes Big endian byte representation + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {Long} The corresponding Long value + */ +Long.fromBytesBE = function fromBytesBE(bytes, unsigned) { + return new Long( + (bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], + (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], + unsigned, + ); +}; + +// Support conversion to/from BigInt where available +if (typeof BigInt === "function") { + /** + * Returns a Long representing the given big integer. + * @function + * @param {number} value The big integer value + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} The corresponding Long value + */ + Long.fromBigInt = function fromBigInt(value, unsigned) { + var lowBits = Number(BigInt.asIntN(32, value)); + var highBits = Number(BigInt.asIntN(32, value >> BigInt(32))); + return fromBits(lowBits, highBits, unsigned); + }; + + // Override + Long.fromValue = function fromValueWithBigInt(value, unsigned) { + if (typeof value === "bigint") return Long.fromBigInt(value, unsigned); + return fromValue(value, unsigned); + }; + + /** + * Converts the Long to its big integer representation. + * @this {!Long} + * @returns {bigint} + */ + LongPrototype.toBigInt = function toBigInt() { + var lowBigInt = BigInt(this.low >>> 0); + var highBigInt = BigInt(this.unsigned ? this.high >>> 0 : this.high); + return (highBigInt << BigInt(32)) | lowBigInt; + }; +} + +export default Long; diff --git a/node_modules/long/package.json b/node_modules/long/package.json new file mode 100644 index 0000000..c617736 --- /dev/null +++ b/node_modules/long/package.json @@ -0,0 +1,58 @@ +{ + "name": "long", + "version": "5.3.2", + "author": "Daniel Wirtz ", + "description": "A Long class for representing a 64-bit two's-complement integer value.", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/long.js.git" + }, + "bugs": { + "url": "https://github.com/dcodeIO/long.js/issues" + }, + "keywords": [ + "math", + "long", + "int64" + ], + "license": "Apache-2.0", + "type": "module", + "main": "umd/index.js", + "types": "umd/index.d.ts", + "exports": { + ".": { + "import": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "require": { + "types": "./umd/index.d.ts", + "default": "./umd/index.js" + } + } + }, + "scripts": { + "build": "node scripts/build.js", + "lint": "prettier --check .", + "format": "prettier --write .", + "test": "npm run test:unit && npm run test:typescript", + "test:unit": "node tests", + "test:typescript": "tsc --project tests/typescript/tsconfig.esnext.json && tsc --project tests/typescript/tsconfig.nodenext.json && tsc --project tests/typescript/tsconfig.commonjs.json && tsc --project tests/typescript/tsconfig.global.json" + }, + "files": [ + "index.js", + "index.d.ts", + "types.d.ts", + "umd/index.js", + "umd/index.d.ts", + "umd/types.d.ts", + "umd/package.json", + "LICENSE", + "README.md" + ], + "devDependencies": { + "esm2umd": "^0.3.1", + "prettier": "^3.5.0", + "typescript": "^5.7.3" + } +} diff --git a/node_modules/long/types.d.ts b/node_modules/long/types.d.ts new file mode 100644 index 0000000..7693ca4 --- /dev/null +++ b/node_modules/long/types.d.ts @@ -0,0 +1,474 @@ +// Common type definitions for both the ESM and UMD variants. The ESM variant +// reexports the Long class as its default export, whereas the UMD variant makes +// the Long class a whole-module export with a global variable fallback. + +type LongLike = + | Long + | number + | bigint + | string + | { low: number; high: number; unsigned: boolean }; + +export declare class Long { + /** + * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as signed integers. See the from* functions below for more convenient ways of constructing Longs. + */ + constructor(low: number, high?: number, unsigned?: boolean); + + /** + * Maximum unsigned value. + */ + static MAX_UNSIGNED_VALUE: Long; + + /** + * Maximum signed value. + */ + static MAX_VALUE: Long; + + /** + * Minimum signed value. + */ + static MIN_VALUE: Long; + + /** + * Signed negative one. + */ + static NEG_ONE: Long; + + /** + * Signed one. + */ + static ONE: Long; + + /** + * Unsigned one. + */ + static UONE: Long; + + /** + * Unsigned zero. + */ + static UZERO: Long; + + /** + * Signed zero + */ + static ZERO: Long; + + /** + * The high 32 bits as a signed value. + */ + high: number; + + /** + * The low 32 bits as a signed value. + */ + low: number; + + /** + * Whether unsigned or not. + */ + unsigned: boolean; + + /** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is assumed to use 32 bits. + */ + static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long; + + /** + * Returns a Long representing the given 32 bit integer value. + */ + static fromInt(value: number, unsigned?: boolean): Long; + + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + */ + static fromNumber(value: number, unsigned?: boolean): Long; + + /** + * Returns a Long representing the given big integer value. + */ + static fromBigInt(value: bigint, unsigned?: boolean): Long; + + /** + * Returns a Long representation of the given string, written using the specified radix. + */ + static fromString( + str: string, + unsigned?: boolean | number, + radix?: number, + ): Long; + + /** + * Creates a Long from its byte representation. + */ + static fromBytes(bytes: number[], unsigned?: boolean, le?: boolean): Long; + + /** + * Creates a Long from its little endian byte representation. + */ + static fromBytesLE(bytes: number[], unsigned?: boolean): Long; + + /** + * Creates a Long from its big endian byte representation. + */ + static fromBytesBE(bytes: number[], unsigned?: boolean): Long; + + /** + * Tests if the specified object is a Long. + */ + static isLong(obj: any): obj is Long; + + /** + * Converts the specified value to a Long. + */ + static fromValue(val: LongLike, unsigned?: boolean): Long; + + /** + * Returns the sum of this and the specified Long. + */ + add(addend: LongLike): Long; + + /** + * Returns the bitwise AND of this Long and the specified. + */ + and(other: LongLike): Long; + + /** + * Compares this Long's value with the specified's. + */ + compare(other: LongLike): number; + + /** + * Compares this Long's value with the specified's. + */ + comp(other: LongLike): number; + + /** + * Returns this Long divided by the specified. + */ + divide(divisor: LongLike): Long; + + /** + * Returns this Long divided by the specified. + */ + div(divisor: LongLike): Long; + + /** + * Tests if this Long's value equals the specified's. + */ + equals(other: LongLike): boolean; + + /** + * Tests if this Long's value equals the specified's. + */ + eq(other: LongLike): boolean; + + /** + * Gets the high 32 bits as a signed integer. + */ + getHighBits(): number; + + /** + * Gets the high 32 bits as an unsigned integer. + */ + getHighBitsUnsigned(): number; + + /** + * Gets the low 32 bits as a signed integer. + */ + getLowBits(): number; + + /** + * Gets the low 32 bits as an unsigned integer. + */ + getLowBitsUnsigned(): number; + + /** + * Gets the number of bits needed to represent the absolute value of this Long. + */ + getNumBitsAbs(): number; + + /** + * Tests if this Long's value is greater than the specified's. + */ + greaterThan(other: LongLike): boolean; + + /** + * Tests if this Long's value is greater than the specified's. + */ + gt(other: LongLike): boolean; + + /** + * Tests if this Long's value is greater than or equal the specified's. + */ + greaterThanOrEqual(other: LongLike): boolean; + + /** + * Tests if this Long's value is greater than or equal the specified's. + */ + gte(other: LongLike): boolean; + + /** + * Tests if this Long's value is greater than or equal the specified's. + */ + ge(other: LongLike): boolean; + + /** + * Tests if this Long's value is even. + */ + isEven(): boolean; + + /** + * Tests if this Long's value is negative. + */ + isNegative(): boolean; + + /** + * Tests if this Long's value is odd. + */ + isOdd(): boolean; + + /** + * Tests if this Long's value is positive or zero. + */ + isPositive(): boolean; + + /** + * Tests if this Long can be safely represented as a JavaScript number. + */ + isSafeInteger(): boolean; + + /** + * Tests if this Long's value equals zero. + */ + isZero(): boolean; + + /** + * Tests if this Long's value equals zero. + */ + eqz(): boolean; + + /** + * Tests if this Long's value is less than the specified's. + */ + lessThan(other: LongLike): boolean; + + /** + * Tests if this Long's value is less than the specified's. + */ + lt(other: LongLike): boolean; + + /** + * Tests if this Long's value is less than or equal the specified's. + */ + lessThanOrEqual(other: LongLike): boolean; + + /** + * Tests if this Long's value is less than or equal the specified's. + */ + lte(other: LongLike): boolean; + + /** + * Tests if this Long's value is less than or equal the specified's. + */ + le(other: LongLike): boolean; + + /** + * Returns this Long modulo the specified. + */ + modulo(other: LongLike): Long; + + /** + * Returns this Long modulo the specified. + */ + mod(other: LongLike): Long; + + /** + * Returns this Long modulo the specified. + */ + rem(other: LongLike): Long; + + /** + * Returns the product of this and the specified Long. + */ + multiply(multiplier: LongLike): Long; + + /** + * Returns the product of this and the specified Long. + */ + mul(multiplier: LongLike): Long; + + /** + * Negates this Long's value. + */ + negate(): Long; + + /** + * Negates this Long's value. + */ + neg(): Long; + + /** + * Returns the bitwise NOT of this Long. + */ + not(): Long; + + /** + * Returns count leading zeros of this Long. + */ + countLeadingZeros(): number; + + /** + * Returns count leading zeros of this Long. + */ + clz(): number; + + /** + * Returns count trailing zeros of this Long. + */ + countTrailingZeros(): number; + + /** + * Returns count trailing zeros of this Long. + */ + ctz(): number; + + /** + * Tests if this Long's value differs from the specified's. + */ + notEquals(other: LongLike): boolean; + + /** + * Tests if this Long's value differs from the specified's. + */ + neq(other: LongLike): boolean; + + /** + * Tests if this Long's value differs from the specified's. + */ + ne(other: LongLike): boolean; + + /** + * Returns the bitwise OR of this Long and the specified. + */ + or(other: LongLike): Long; + + /** + * Returns this Long with bits shifted to the left by the given amount. + */ + shiftLeft(numBits: number | Long): Long; + + /** + * Returns this Long with bits shifted to the left by the given amount. + */ + shl(numBits: number | Long): Long; + + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + */ + shiftRight(numBits: number | Long): Long; + + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + */ + shr(numBits: number | Long): Long; + + /** + * Returns this Long with bits logically shifted to the right by the given amount. + */ + shiftRightUnsigned(numBits: number | Long): Long; + + /** + * Returns this Long with bits logically shifted to the right by the given amount. + */ + shru(numBits: number | Long): Long; + + /** + * Returns this Long with bits logically shifted to the right by the given amount. + */ + shr_u(numBits: number | Long): Long; + + /** + * Returns this Long with bits rotated to the left by the given amount. + */ + rotateLeft(numBits: number | Long): Long; + + /** + * Returns this Long with bits rotated to the left by the given amount. + */ + rotl(numBits: number | Long): Long; + + /** + * Returns this Long with bits rotated to the right by the given amount. + */ + rotateRight(numBits: number | Long): Long; + + /** + * Returns this Long with bits rotated to the right by the given amount. + */ + rotr(numBits: number | Long): Long; + + /** + * Returns the difference of this and the specified Long. + */ + subtract(subtrahend: LongLike): Long; + + /** + * Returns the difference of this and the specified Long. + */ + sub(subtrahend: LongLike): Long; + + /** + * Converts the Long to a big integer. + */ + toBigInt(): bigint; + + /** + * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. + */ + toInt(): number; + + /** + * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). + */ + toNumber(): number; + + /** + * Converts this Long to its byte representation. + */ + + toBytes(le?: boolean): number[]; + + /** + * Converts this Long to its little endian byte representation. + */ + + toBytesLE(): number[]; + + /** + * Converts this Long to its big endian byte representation. + */ + + toBytesBE(): number[]; + + /** + * Converts this Long to signed. + */ + toSigned(): Long; + + /** + * Converts the Long to a string written in the specified radix. + */ + toString(radix?: number): string; + + /** + * Converts this Long to unsigned. + */ + toUnsigned(): Long; + + /** + * Returns the bitwise XOR of this Long and the given one. + */ + xor(other: LongLike): Long; +} diff --git a/node_modules/long/umd/index.d.ts b/node_modules/long/umd/index.d.ts new file mode 100644 index 0000000..5036689 --- /dev/null +++ b/node_modules/long/umd/index.d.ts @@ -0,0 +1,3 @@ +import { Long } from "./types.js"; +export = Long; +export as namespace Long; diff --git a/node_modules/long/umd/index.js b/node_modules/long/umd/index.js new file mode 100644 index 0000000..7136988 --- /dev/null +++ b/node_modules/long/umd/index.js @@ -0,0 +1,1622 @@ +// GENERATED FILE. DO NOT EDIT. +(function (global, factory) { + function preferDefault(exports) { + return exports.default || exports; + } + if (typeof define === "function" && define.amd) { + define([], function () { + var exports = {}; + factory(exports); + return preferDefault(exports); + }); + } else if (typeof exports === "object") { + factory(exports); + if (typeof module === "object") module.exports = preferDefault(exports); + } else { + (function () { + var exports = {}; + factory(exports); + global.Long = preferDefault(exports); + })(); + } +})( + typeof globalThis !== "undefined" + ? globalThis + : typeof self !== "undefined" + ? self + : this, + function (_exports) { + "use strict"; + + Object.defineProperty(_exports, "__esModule", { + value: true, + }); + _exports.default = void 0; + /** + * @license + * Copyright 2009 The Closure Library Authors + * Copyright 2020 Daniel Wirtz / The long.js Authors. + * + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + // WebAssembly optimizations to do native i64 multiplication and divide + var wasm = null; + try { + wasm = new WebAssembly.Instance( + new WebAssembly.Module( + new Uint8Array([ + // \0asm + 0, 97, 115, 109, + // version 1 + 1, 0, 0, 0, + // section "type" + 1, 13, 2, + // 0, () => i32 + 96, 0, 1, 127, + // 1, (i32, i32, i32, i32) => i32 + 96, 4, 127, 127, 127, 127, 1, 127, + // section "function" + 3, 7, 6, + // 0, type 0 + 0, + // 1, type 1 + 1, + // 2, type 1 + 1, + // 3, type 1 + 1, + // 4, type 1 + 1, + // 5, type 1 + 1, + // section "global" + 6, 6, 1, + // 0, "high", mutable i32 + 127, 1, 65, 0, 11, + // section "export" + 7, 50, 6, + // 0, "mul" + 3, 109, 117, 108, 0, 1, + // 1, "div_s" + 5, 100, 105, 118, 95, 115, 0, 2, + // 2, "div_u" + 5, 100, 105, 118, 95, 117, 0, 3, + // 3, "rem_s" + 5, 114, 101, 109, 95, 115, 0, 4, + // 4, "rem_u" + 5, 114, 101, 109, 95, 117, 0, 5, + // 5, "get_high" + 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, + // section "code" + 10, 191, 1, 6, + // 0, "get_high" + 4, 0, 35, 0, 11, + // 1, "mul" + 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, + 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, + 32, 4, 167, 11, + // 2, "div_s" + 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, + 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, + 32, 4, 167, 11, + // 3, "div_u" + 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, + 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, + 32, 4, 167, 11, + // 4, "rem_s" + 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, + 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, + 32, 4, 167, 11, + // 5, "rem_u" + 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, + 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, + 32, 4, 167, 11, + ]), + ), + {}, + ).exports; + } catch { + // no wasm support :( + } + + /** + * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. + * See the from* functions below for more convenient ways of constructing Longs. + * @exports Long + * @class A Long class for representing a 64 bit two's-complement integer value. + * @param {number} low The low (signed) 32 bits of the long + * @param {number} high The high (signed) 32 bits of the long + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @constructor + */ + function Long(low, high, unsigned) { + /** + * The low 32 bits as a signed value. + * @type {number} + */ + this.low = low | 0; + + /** + * The high 32 bits as a signed value. + * @type {number} + */ + this.high = high | 0; + + /** + * Whether unsigned or not. + * @type {boolean} + */ + this.unsigned = !!unsigned; + } + + // The internal representation of a long is the two given signed, 32-bit values. + // We use 32-bit pieces because these are the size of integers on which + // Javascript performs bit-operations. For operations like addition and + // multiplication, we split each number into 16 bit pieces, which can easily be + // multiplied within Javascript's floating-point representation without overflow + // or change in sign. + // + // In the algorithms below, we frequently reduce the negative case to the + // positive case by negating the input(s) and then post-processing the result. + // Note that we must ALWAYS check specially whether those values are MIN_VALUE + // (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + // a positive number, it overflows back into a negative). Not handling this + // case would often result in infinite recursion. + // + // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from* + // methods on which they depend. + + /** + * An indicator used to reliably determine if an object is a Long or not. + * @type {boolean} + * @const + * @private + */ + Long.prototype.__isLong__; + Object.defineProperty(Long.prototype, "__isLong__", { + value: true, + }); + + /** + * @function + * @param {*} obj Object + * @returns {boolean} + * @inner + */ + function isLong(obj) { + return (obj && obj["__isLong__"]) === true; + } + + /** + * @function + * @param {*} value number + * @returns {number} + * @inner + */ + function ctz32(value) { + var c = Math.clz32(value & -value); + return value ? 31 - c : c; + } + + /** + * Tests if the specified object is a Long. + * @function + * @param {*} obj Object + * @returns {boolean} + */ + Long.isLong = isLong; + + /** + * A cache of the Long representations of small integer values. + * @type {!Object} + * @inner + */ + var INT_CACHE = {}; + + /** + * A cache of the Long representations of small unsigned integer values. + * @type {!Object} + * @inner + */ + var UINT_CACHE = {}; + + /** + * @param {number} value + * @param {boolean=} unsigned + * @returns {!Long} + * @inner + */ + function fromInt(value, unsigned) { + var obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if ((cache = 0 <= value && value < 256)) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) return cachedObj; + } + obj = fromBits(value, 0, true); + if (cache) UINT_CACHE[value] = obj; + return obj; + } else { + value |= 0; + if ((cache = -128 <= value && value < 128)) { + cachedObj = INT_CACHE[value]; + if (cachedObj) return cachedObj; + } + obj = fromBits(value, value < 0 ? -1 : 0, false); + if (cache) INT_CACHE[value] = obj; + return obj; + } + } + + /** + * Returns a Long representing the given 32 bit integer value. + * @function + * @param {number} value The 32 bit integer in question + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} The corresponding Long value + */ + Long.fromInt = fromInt; + + /** + * @param {number} value + * @param {boolean=} unsigned + * @returns {!Long} + * @inner + */ + function fromNumber(value, unsigned) { + if (isNaN(value)) return unsigned ? UZERO : ZERO; + if (unsigned) { + if (value < 0) return UZERO; + if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE; + } else { + if (value <= -TWO_PWR_63_DBL) return MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) return MAX_VALUE; + } + if (value < 0) return fromNumber(-value, unsigned).neg(); + return fromBits( + value % TWO_PWR_32_DBL | 0, + (value / TWO_PWR_32_DBL) | 0, + unsigned, + ); + } + + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @function + * @param {number} value The number in question + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} The corresponding Long value + */ + Long.fromNumber = fromNumber; + + /** + * @param {number} lowBits + * @param {number} highBits + * @param {boolean=} unsigned + * @returns {!Long} + * @inner + */ + function fromBits(lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + } + + /** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is + * assumed to use 32 bits. + * @function + * @param {number} lowBits The low 32 bits + * @param {number} highBits The high 32 bits + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} The corresponding Long value + */ + Long.fromBits = fromBits; + + /** + * @function + * @param {number} base + * @param {number} exponent + * @returns {number} + * @inner + */ + var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4) + + /** + * @param {string} str + * @param {(boolean|number)=} unsigned + * @param {number=} radix + * @returns {!Long} + * @inner + */ + function fromString(str, unsigned, radix) { + if (str.length === 0) throw Error("empty string"); + if (typeof unsigned === "number") { + // For goog.math.long compatibility + radix = unsigned; + unsigned = false; + } else { + unsigned = !!unsigned; + } + if ( + str === "NaN" || + str === "Infinity" || + str === "+Infinity" || + str === "-Infinity" + ) + return unsigned ? UZERO : ZERO; + radix = radix || 10; + if (radix < 2 || 36 < radix) throw RangeError("radix"); + var p; + if ((p = str.indexOf("-")) > 0) throw Error("interior hyphen"); + else if (p === 0) { + return fromString(str.substring(1), unsigned, radix).neg(); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = fromNumber(pow_dbl(radix, 8)); + var result = ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i), + value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = fromNumber(pow_dbl(radix, size)); + result = result.mul(power).add(fromNumber(value)); + } else { + result = result.mul(radixToPower); + result = result.add(fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; + } + + /** + * Returns a Long representation of the given string, written using the specified radix. + * @function + * @param {string} str The textual representation of the Long + * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to signed + * @param {number=} radix The radix in which the text is written (2-36), defaults to 10 + * @returns {!Long} The corresponding Long value + */ + Long.fromString = fromString; + + /** + * @function + * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val + * @param {boolean=} unsigned + * @returns {!Long} + * @inner + */ + function fromValue(val, unsigned) { + if (typeof val === "number") return fromNumber(val, unsigned); + if (typeof val === "string") return fromString(val, unsigned); + // Throws for non-objects, converts non-instanceof Long: + return fromBits( + val.low, + val.high, + typeof unsigned === "boolean" ? unsigned : val.unsigned, + ); + } + + /** + * Converts the specified value to a Long using the appropriate from* function for its type. + * @function + * @param {!Long|number|bigint|string|!{low: number, high: number, unsigned: boolean}} val Value + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} + */ + Long.fromValue = fromValue; + + // NOTE: the compiler should inline these constant values below and then remove these variables, so there should be + // no runtime penalty for these. + + /** + * @type {number} + * @const + * @inner + */ + var TWO_PWR_16_DBL = 1 << 16; + + /** + * @type {number} + * @const + * @inner + */ + var TWO_PWR_24_DBL = 1 << 24; + + /** + * @type {number} + * @const + * @inner + */ + var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; + + /** + * @type {number} + * @const + * @inner + */ + var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; + + /** + * @type {number} + * @const + * @inner + */ + var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; + + /** + * @type {!Long} + * @const + * @inner + */ + var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL); + + /** + * @type {!Long} + * @inner + */ + var ZERO = fromInt(0); + + /** + * Signed zero. + * @type {!Long} + */ + Long.ZERO = ZERO; + + /** + * @type {!Long} + * @inner + */ + var UZERO = fromInt(0, true); + + /** + * Unsigned zero. + * @type {!Long} + */ + Long.UZERO = UZERO; + + /** + * @type {!Long} + * @inner + */ + var ONE = fromInt(1); + + /** + * Signed one. + * @type {!Long} + */ + Long.ONE = ONE; + + /** + * @type {!Long} + * @inner + */ + var UONE = fromInt(1, true); + + /** + * Unsigned one. + * @type {!Long} + */ + Long.UONE = UONE; + + /** + * @type {!Long} + * @inner + */ + var NEG_ONE = fromInt(-1); + + /** + * Signed negative one. + * @type {!Long} + */ + Long.NEG_ONE = NEG_ONE; + + /** + * @type {!Long} + * @inner + */ + var MAX_VALUE = fromBits(0xffffffff | 0, 0x7fffffff | 0, false); + + /** + * Maximum signed value. + * @type {!Long} + */ + Long.MAX_VALUE = MAX_VALUE; + + /** + * @type {!Long} + * @inner + */ + var MAX_UNSIGNED_VALUE = fromBits(0xffffffff | 0, 0xffffffff | 0, true); + + /** + * Maximum unsigned value. + * @type {!Long} + */ + Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE; + + /** + * @type {!Long} + * @inner + */ + var MIN_VALUE = fromBits(0, 0x80000000 | 0, false); + + /** + * Minimum signed value. + * @type {!Long} + */ + Long.MIN_VALUE = MIN_VALUE; + + /** + * @alias Long.prototype + * @inner + */ + var LongPrototype = Long.prototype; + + /** + * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. + * @this {!Long} + * @returns {number} + */ + LongPrototype.toInt = function toInt() { + return this.unsigned ? this.low >>> 0 : this.low; + }; + + /** + * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). + * @this {!Long} + * @returns {number} + */ + LongPrototype.toNumber = function toNumber() { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + }; + + /** + * Converts the Long to a string written in the specified radix. + * @this {!Long} + * @param {number=} radix Radix (2-36), defaults to 10 + * @returns {string} + * @override + * @throws {RangeError} If `radix` is out of range + */ + LongPrototype.toString = function toString(radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) throw RangeError("radix"); + if (this.isZero()) return "0"; + if (this.isNegative()) { + // Unsigned Longs are never negative + if (this.eq(MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = fromNumber(radix), + div = this.div(radixLong), + rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } else return "-" + this.neg().toString(radix); + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), + rem = this; + var result = ""; + while (true) { + var remDiv = rem.div(radixToPower), + intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, + digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) return digits + result; + else { + while (digits.length < 6) digits = "0" + digits; + result = "" + digits + result; + } + } + }; + + /** + * Gets the high 32 bits as a signed integer. + * @this {!Long} + * @returns {number} Signed high bits + */ + LongPrototype.getHighBits = function getHighBits() { + return this.high; + }; + + /** + * Gets the high 32 bits as an unsigned integer. + * @this {!Long} + * @returns {number} Unsigned high bits + */ + LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() { + return this.high >>> 0; + }; + + /** + * Gets the low 32 bits as a signed integer. + * @this {!Long} + * @returns {number} Signed low bits + */ + LongPrototype.getLowBits = function getLowBits() { + return this.low; + }; + + /** + * Gets the low 32 bits as an unsigned integer. + * @this {!Long} + * @returns {number} Unsigned low bits + */ + LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() { + return this.low >>> 0; + }; + + /** + * Gets the number of bits needed to represent the absolute value of this Long. + * @this {!Long} + * @returns {number} + */ + LongPrototype.getNumBitsAbs = function getNumBitsAbs() { + if (this.isNegative()) + // Unsigned Longs are never negative + return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + var val = this.high != 0 ? this.high : this.low; + for (var bit = 31; bit > 0; bit--) if ((val & (1 << bit)) != 0) break; + return this.high != 0 ? bit + 33 : bit + 1; + }; + + /** + * Tests if this Long can be safely represented as a JavaScript number. + * @this {!Long} + * @returns {boolean} + */ + LongPrototype.isSafeInteger = function isSafeInteger() { + // 2^53-1 is the maximum safe value + var top11Bits = this.high >> 21; + // [0, 2^53-1] + if (!top11Bits) return true; + // > 2^53-1 + if (this.unsigned) return false; + // [-2^53, -1] except -2^53 + return top11Bits === -1 && !(this.low === 0 && this.high === -0x200000); + }; + + /** + * Tests if this Long's value equals zero. + * @this {!Long} + * @returns {boolean} + */ + LongPrototype.isZero = function isZero() { + return this.high === 0 && this.low === 0; + }; + + /** + * Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}. + * @returns {boolean} + */ + LongPrototype.eqz = LongPrototype.isZero; + + /** + * Tests if this Long's value is negative. + * @this {!Long} + * @returns {boolean} + */ + LongPrototype.isNegative = function isNegative() { + return !this.unsigned && this.high < 0; + }; + + /** + * Tests if this Long's value is positive or zero. + * @this {!Long} + * @returns {boolean} + */ + LongPrototype.isPositive = function isPositive() { + return this.unsigned || this.high >= 0; + }; + + /** + * Tests if this Long's value is odd. + * @this {!Long} + * @returns {boolean} + */ + LongPrototype.isOdd = function isOdd() { + return (this.low & 1) === 1; + }; + + /** + * Tests if this Long's value is even. + * @this {!Long} + * @returns {boolean} + */ + LongPrototype.isEven = function isEven() { + return (this.low & 1) === 0; + }; + + /** + * Tests if this Long's value equals the specified's. + * @this {!Long} + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ + LongPrototype.equals = function equals(other) { + if (!isLong(other)) other = fromValue(other); + if ( + this.unsigned !== other.unsigned && + this.high >>> 31 === 1 && + other.high >>> 31 === 1 + ) + return false; + return this.high === other.high && this.low === other.low; + }; + + /** + * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}. + * @function + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ + LongPrototype.eq = LongPrototype.equals; + + /** + * Tests if this Long's value differs from the specified's. + * @this {!Long} + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ + LongPrototype.notEquals = function notEquals(other) { + return !this.eq(/* validates */ other); + }; + + /** + * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}. + * @function + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ + LongPrototype.neq = LongPrototype.notEquals; + + /** + * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}. + * @function + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ + LongPrototype.ne = LongPrototype.notEquals; + + /** + * Tests if this Long's value is less than the specified's. + * @this {!Long} + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ + LongPrototype.lessThan = function lessThan(other) { + return this.comp(/* validates */ other) < 0; + }; + + /** + * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}. + * @function + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ + LongPrototype.lt = LongPrototype.lessThan; + + /** + * Tests if this Long's value is less than or equal the specified's. + * @this {!Long} + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ + LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) { + return this.comp(/* validates */ other) <= 0; + }; + + /** + * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}. + * @function + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ + LongPrototype.lte = LongPrototype.lessThanOrEqual; + + /** + * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}. + * @function + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ + LongPrototype.le = LongPrototype.lessThanOrEqual; + + /** + * Tests if this Long's value is greater than the specified's. + * @this {!Long} + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ + LongPrototype.greaterThan = function greaterThan(other) { + return this.comp(/* validates */ other) > 0; + }; + + /** + * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}. + * @function + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ + LongPrototype.gt = LongPrototype.greaterThan; + + /** + * Tests if this Long's value is greater than or equal the specified's. + * @this {!Long} + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ + LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) { + return this.comp(/* validates */ other) >= 0; + }; + + /** + * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}. + * @function + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ + LongPrototype.gte = LongPrototype.greaterThanOrEqual; + + /** + * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}. + * @function + * @param {!Long|number|bigint|string} other Other value + * @returns {boolean} + */ + LongPrototype.ge = LongPrototype.greaterThanOrEqual; + + /** + * Compares this Long's value with the specified's. + * @this {!Long} + * @param {!Long|number|bigint|string} other Other value + * @returns {number} 0 if they are the same, 1 if the this is greater and -1 + * if the given one is greater + */ + LongPrototype.compare = function compare(other) { + if (!isLong(other)) other = fromValue(other); + if (this.eq(other)) return 0; + var thisNeg = this.isNegative(), + otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) return -1; + if (!thisNeg && otherNeg) return 1; + // At this point the sign bits are the same + if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1; + // Both are positive if at least one is unsigned + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + }; + + /** + * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}. + * @function + * @param {!Long|number|bigint|string} other Other value + * @returns {number} 0 if they are the same, 1 if the this is greater and -1 + * if the given one is greater + */ + LongPrototype.comp = LongPrototype.compare; + + /** + * Negates this Long's value. + * @this {!Long} + * @returns {!Long} Negated Long + */ + LongPrototype.negate = function negate() { + if (!this.unsigned && this.eq(MIN_VALUE)) return MIN_VALUE; + return this.not().add(ONE); + }; + + /** + * Negates this Long's value. This is an alias of {@link Long#negate}. + * @function + * @returns {!Long} Negated Long + */ + LongPrototype.neg = LongPrototype.negate; + + /** + * Returns the sum of this and the specified Long. + * @this {!Long} + * @param {!Long|number|bigint|string} addend Addend + * @returns {!Long} Sum + */ + LongPrototype.add = function add(addend) { + if (!isLong(addend)) addend = fromValue(addend); + + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high >>> 16; + var a32 = this.high & 0xffff; + var a16 = this.low >>> 16; + var a00 = this.low & 0xffff; + var b48 = addend.high >>> 16; + var b32 = addend.high & 0xffff; + var b16 = addend.low >>> 16; + var b00 = addend.low & 0xffff; + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + }; + + /** + * Returns the difference of this and the specified Long. + * @this {!Long} + * @param {!Long|number|bigint|string} subtrahend Subtrahend + * @returns {!Long} Difference + */ + LongPrototype.subtract = function subtract(subtrahend) { + if (!isLong(subtrahend)) subtrahend = fromValue(subtrahend); + return this.add(subtrahend.neg()); + }; + + /** + * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}. + * @function + * @param {!Long|number|bigint|string} subtrahend Subtrahend + * @returns {!Long} Difference + */ + LongPrototype.sub = LongPrototype.subtract; + + /** + * Returns the product of this and the specified Long. + * @this {!Long} + * @param {!Long|number|bigint|string} multiplier Multiplier + * @returns {!Long} Product + */ + LongPrototype.multiply = function multiply(multiplier) { + if (this.isZero()) return this; + if (!isLong(multiplier)) multiplier = fromValue(multiplier); + + // use wasm support if present + if (wasm) { + var low = wasm["mul"]( + this.low, + this.high, + multiplier.low, + multiplier.high, + ); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + if (multiplier.isZero()) return this.unsigned ? UZERO : ZERO; + if (this.eq(MIN_VALUE)) return multiplier.isOdd() ? MIN_VALUE : ZERO; + if (multiplier.eq(MIN_VALUE)) return this.isOdd() ? MIN_VALUE : ZERO; + if (this.isNegative()) { + if (multiplier.isNegative()) return this.neg().mul(multiplier.neg()); + else return this.neg().mul(multiplier).neg(); + } else if (multiplier.isNegative()) + return this.mul(multiplier.neg()).neg(); + + // If both longs are small, use float multiplication + if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24)) + return fromNumber( + this.toNumber() * multiplier.toNumber(), + this.unsigned, + ); + + // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high >>> 16; + var a32 = this.high & 0xffff; + var a16 = this.low >>> 16; + var a00 = this.low & 0xffff; + var b48 = multiplier.high >>> 16; + var b32 = multiplier.high & 0xffff; + var b16 = multiplier.low >>> 16; + var b00 = multiplier.low & 0xffff; + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + }; + + /** + * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}. + * @function + * @param {!Long|number|bigint|string} multiplier Multiplier + * @returns {!Long} Product + */ + LongPrototype.mul = LongPrototype.multiply; + + /** + * Returns this Long divided by the specified. The result is signed if this Long is signed or + * unsigned if this Long is unsigned. + * @this {!Long} + * @param {!Long|number|bigint|string} divisor Divisor + * @returns {!Long} Quotient + */ + LongPrototype.divide = function divide(divisor) { + if (!isLong(divisor)) divisor = fromValue(divisor); + if (divisor.isZero()) throw Error("division by zero"); + + // use wasm support if present + if (wasm) { + // guard against signed division overflow: the largest + // negative number / -1 would be 1 larger than the largest + // positive number, due to two's complement. + if ( + !this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1 + ) { + // be consistent with non-wasm code path + return this; + } + var low = (this.unsigned ? wasm["div_u"] : wasm["div_s"])( + this.low, + this.high, + divisor.low, + divisor.high, + ); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + if (this.isZero()) return this.unsigned ? UZERO : ZERO; + var approx, rem, res; + if (!this.unsigned) { + // This section is only relevant for signed longs and is derived from the + // closure library as a whole. + if (this.eq(MIN_VALUE)) { + if (divisor.eq(ONE) || divisor.eq(NEG_ONE)) + return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + else if (divisor.eq(MIN_VALUE)) return ONE; + else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(ZERO)) { + return divisor.isNegative() ? ONE : NEG_ONE; + } else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } else if (divisor.eq(MIN_VALUE)) return this.unsigned ? UZERO : ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } else if (divisor.isNegative()) return this.div(divisor.neg()).neg(); + res = ZERO; + } else { + // The algorithm below has not been made for unsigned longs. It's therefore + // required to take special care of the MSB prior to running it. + if (!divisor.unsigned) divisor = divisor.toUnsigned(); + if (divisor.gt(this)) return UZERO; + if (divisor.gt(this.shru(1))) + // 15 >>> 1 = 7 ; with divisor = 8 ; true + return UONE; + res = UZERO; + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + rem = this; + while (rem.gte(divisor)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2), + delta = log2 <= 48 ? 1 : pow_dbl(2, log2 - 48), + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + approxRes = fromNumber(approx), + approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) approxRes = ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + }; + + /** + * Returns this Long divided by the specified. This is an alias of {@link Long#divide}. + * @function + * @param {!Long|number|bigint|string} divisor Divisor + * @returns {!Long} Quotient + */ + LongPrototype.div = LongPrototype.divide; + + /** + * Returns this Long modulo the specified. + * @this {!Long} + * @param {!Long|number|bigint|string} divisor Divisor + * @returns {!Long} Remainder + */ + LongPrototype.modulo = function modulo(divisor) { + if (!isLong(divisor)) divisor = fromValue(divisor); + + // use wasm support if present + if (wasm) { + var low = (this.unsigned ? wasm["rem_u"] : wasm["rem_s"])( + this.low, + this.high, + divisor.low, + divisor.high, + ); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + return this.sub(this.div(divisor).mul(divisor)); + }; + + /** + * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}. + * @function + * @param {!Long|number|bigint|string} divisor Divisor + * @returns {!Long} Remainder + */ + LongPrototype.mod = LongPrototype.modulo; + + /** + * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}. + * @function + * @param {!Long|number|bigint|string} divisor Divisor + * @returns {!Long} Remainder + */ + LongPrototype.rem = LongPrototype.modulo; + + /** + * Returns the bitwise NOT of this Long. + * @this {!Long} + * @returns {!Long} + */ + LongPrototype.not = function not() { + return fromBits(~this.low, ~this.high, this.unsigned); + }; + + /** + * Returns count leading zeros of this Long. + * @this {!Long} + * @returns {!number} + */ + LongPrototype.countLeadingZeros = function countLeadingZeros() { + return this.high ? Math.clz32(this.high) : Math.clz32(this.low) + 32; + }; + + /** + * Returns count leading zeros. This is an alias of {@link Long#countLeadingZeros}. + * @function + * @param {!Long} + * @returns {!number} + */ + LongPrototype.clz = LongPrototype.countLeadingZeros; + + /** + * Returns count trailing zeros of this Long. + * @this {!Long} + * @returns {!number} + */ + LongPrototype.countTrailingZeros = function countTrailingZeros() { + return this.low ? ctz32(this.low) : ctz32(this.high) + 32; + }; + + /** + * Returns count trailing zeros. This is an alias of {@link Long#countTrailingZeros}. + * @function + * @param {!Long} + * @returns {!number} + */ + LongPrototype.ctz = LongPrototype.countTrailingZeros; + + /** + * Returns the bitwise AND of this Long and the specified. + * @this {!Long} + * @param {!Long|number|bigint|string} other Other Long + * @returns {!Long} + */ + LongPrototype.and = function and(other) { + if (!isLong(other)) other = fromValue(other); + return fromBits( + this.low & other.low, + this.high & other.high, + this.unsigned, + ); + }; + + /** + * Returns the bitwise OR of this Long and the specified. + * @this {!Long} + * @param {!Long|number|bigint|string} other Other Long + * @returns {!Long} + */ + LongPrototype.or = function or(other) { + if (!isLong(other)) other = fromValue(other); + return fromBits( + this.low | other.low, + this.high | other.high, + this.unsigned, + ); + }; + + /** + * Returns the bitwise XOR of this Long and the given one. + * @this {!Long} + * @param {!Long|number|bigint|string} other Other Long + * @returns {!Long} + */ + LongPrototype.xor = function xor(other) { + if (!isLong(other)) other = fromValue(other); + return fromBits( + this.low ^ other.low, + this.high ^ other.high, + this.unsigned, + ); + }; + + /** + * Returns this Long with bits shifted to the left by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ + LongPrototype.shiftLeft = function shiftLeft(numBits) { + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + else if (numBits < 32) + return fromBits( + this.low << numBits, + (this.high << numBits) | (this.low >>> (32 - numBits)), + this.unsigned, + ); + else return fromBits(0, this.low << (numBits - 32), this.unsigned); + }; + + /** + * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ + LongPrototype.shl = LongPrototype.shiftLeft; + + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ + LongPrototype.shiftRight = function shiftRight(numBits) { + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + else if (numBits < 32) + return fromBits( + (this.low >>> numBits) | (this.high << (32 - numBits)), + this.high >> numBits, + this.unsigned, + ); + else + return fromBits( + this.high >> (numBits - 32), + this.high >= 0 ? 0 : -1, + this.unsigned, + ); + }; + + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ + LongPrototype.shr = LongPrototype.shiftRight; + + /** + * Returns this Long with bits logically shifted to the right by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ + LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) { + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + if (numBits < 32) + return fromBits( + (this.low >>> numBits) | (this.high << (32 - numBits)), + this.high >>> numBits, + this.unsigned, + ); + if (numBits === 32) return fromBits(this.high, 0, this.unsigned); + return fromBits(this.high >>> (numBits - 32), 0, this.unsigned); + }; + + /** + * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ + LongPrototype.shru = LongPrototype.shiftRightUnsigned; + + /** + * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ + LongPrototype.shr_u = LongPrototype.shiftRightUnsigned; + + /** + * Returns this Long with bits rotated to the left by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Rotated Long + */ + LongPrototype.rotateLeft = function rotateLeft(numBits) { + var b; + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); + if (numBits < 32) { + b = 32 - numBits; + return fromBits( + (this.low << numBits) | (this.high >>> b), + (this.high << numBits) | (this.low >>> b), + this.unsigned, + ); + } + numBits -= 32; + b = 32 - numBits; + return fromBits( + (this.high << numBits) | (this.low >>> b), + (this.low << numBits) | (this.high >>> b), + this.unsigned, + ); + }; + /** + * Returns this Long with bits rotated to the left by the given amount. This is an alias of {@link Long#rotateLeft}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Rotated Long + */ + LongPrototype.rotl = LongPrototype.rotateLeft; + + /** + * Returns this Long with bits rotated to the right by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Rotated Long + */ + LongPrototype.rotateRight = function rotateRight(numBits) { + var b; + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); + if (numBits < 32) { + b = 32 - numBits; + return fromBits( + (this.high << b) | (this.low >>> numBits), + (this.low << b) | (this.high >>> numBits), + this.unsigned, + ); + } + numBits -= 32; + b = 32 - numBits; + return fromBits( + (this.low << b) | (this.high >>> numBits), + (this.high << b) | (this.low >>> numBits), + this.unsigned, + ); + }; + /** + * Returns this Long with bits rotated to the right by the given amount. This is an alias of {@link Long#rotateRight}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Rotated Long + */ + LongPrototype.rotr = LongPrototype.rotateRight; + + /** + * Converts this Long to signed. + * @this {!Long} + * @returns {!Long} Signed long + */ + LongPrototype.toSigned = function toSigned() { + if (!this.unsigned) return this; + return fromBits(this.low, this.high, false); + }; + + /** + * Converts this Long to unsigned. + * @this {!Long} + * @returns {!Long} Unsigned long + */ + LongPrototype.toUnsigned = function toUnsigned() { + if (this.unsigned) return this; + return fromBits(this.low, this.high, true); + }; + + /** + * Converts this Long to its byte representation. + * @param {boolean=} le Whether little or big endian, defaults to big endian + * @this {!Long} + * @returns {!Array.} Byte representation + */ + LongPrototype.toBytes = function toBytes(le) { + return le ? this.toBytesLE() : this.toBytesBE(); + }; + + /** + * Converts this Long to its little endian byte representation. + * @this {!Long} + * @returns {!Array.} Little endian byte representation + */ + LongPrototype.toBytesLE = function toBytesLE() { + var hi = this.high, + lo = this.low; + return [ + lo & 0xff, + (lo >>> 8) & 0xff, + (lo >>> 16) & 0xff, + lo >>> 24, + hi & 0xff, + (hi >>> 8) & 0xff, + (hi >>> 16) & 0xff, + hi >>> 24, + ]; + }; + + /** + * Converts this Long to its big endian byte representation. + * @this {!Long} + * @returns {!Array.} Big endian byte representation + */ + LongPrototype.toBytesBE = function toBytesBE() { + var hi = this.high, + lo = this.low; + return [ + hi >>> 24, + (hi >>> 16) & 0xff, + (hi >>> 8) & 0xff, + hi & 0xff, + lo >>> 24, + (lo >>> 16) & 0xff, + (lo >>> 8) & 0xff, + lo & 0xff, + ]; + }; + + /** + * Creates a Long from its byte representation. + * @param {!Array.} bytes Byte representation + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @param {boolean=} le Whether little or big endian, defaults to big endian + * @returns {Long} The corresponding Long value + */ + Long.fromBytes = function fromBytes(bytes, unsigned, le) { + return le + ? Long.fromBytesLE(bytes, unsigned) + : Long.fromBytesBE(bytes, unsigned); + }; + + /** + * Creates a Long from its little endian byte representation. + * @param {!Array.} bytes Little endian byte representation + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {Long} The corresponding Long value + */ + Long.fromBytesLE = function fromBytesLE(bytes, unsigned) { + return new Long( + bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), + bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), + unsigned, + ); + }; + + /** + * Creates a Long from its big endian byte representation. + * @param {!Array.} bytes Big endian byte representation + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {Long} The corresponding Long value + */ + Long.fromBytesBE = function fromBytesBE(bytes, unsigned) { + return new Long( + (bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], + (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], + unsigned, + ); + }; + + // Support conversion to/from BigInt where available + if (typeof BigInt === "function") { + /** + * Returns a Long representing the given big integer. + * @function + * @param {number} value The big integer value + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} The corresponding Long value + */ + Long.fromBigInt = function fromBigInt(value, unsigned) { + var lowBits = Number(BigInt.asIntN(32, value)); + var highBits = Number(BigInt.asIntN(32, value >> BigInt(32))); + return fromBits(lowBits, highBits, unsigned); + }; + + // Override + Long.fromValue = function fromValueWithBigInt(value, unsigned) { + if (typeof value === "bigint") return Long.fromBigInt(value, unsigned); + return fromValue(value, unsigned); + }; + + /** + * Converts the Long to its big integer representation. + * @this {!Long} + * @returns {bigint} + */ + LongPrototype.toBigInt = function toBigInt() { + var lowBigInt = BigInt(this.low >>> 0); + var highBigInt = BigInt(this.unsigned ? this.high >>> 0 : this.high); + return (highBigInt << BigInt(32)) | lowBigInt; + }; + } + var _default = (_exports.default = Long); + }, +); diff --git a/node_modules/long/umd/package.json b/node_modules/long/umd/package.json new file mode 100644 index 0000000..5bbefff --- /dev/null +++ b/node_modules/long/umd/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/long/umd/types.d.ts b/node_modules/long/umd/types.d.ts new file mode 100644 index 0000000..7693ca4 --- /dev/null +++ b/node_modules/long/umd/types.d.ts @@ -0,0 +1,474 @@ +// Common type definitions for both the ESM and UMD variants. The ESM variant +// reexports the Long class as its default export, whereas the UMD variant makes +// the Long class a whole-module export with a global variable fallback. + +type LongLike = + | Long + | number + | bigint + | string + | { low: number; high: number; unsigned: boolean }; + +export declare class Long { + /** + * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as signed integers. See the from* functions below for more convenient ways of constructing Longs. + */ + constructor(low: number, high?: number, unsigned?: boolean); + + /** + * Maximum unsigned value. + */ + static MAX_UNSIGNED_VALUE: Long; + + /** + * Maximum signed value. + */ + static MAX_VALUE: Long; + + /** + * Minimum signed value. + */ + static MIN_VALUE: Long; + + /** + * Signed negative one. + */ + static NEG_ONE: Long; + + /** + * Signed one. + */ + static ONE: Long; + + /** + * Unsigned one. + */ + static UONE: Long; + + /** + * Unsigned zero. + */ + static UZERO: Long; + + /** + * Signed zero + */ + static ZERO: Long; + + /** + * The high 32 bits as a signed value. + */ + high: number; + + /** + * The low 32 bits as a signed value. + */ + low: number; + + /** + * Whether unsigned or not. + */ + unsigned: boolean; + + /** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is assumed to use 32 bits. + */ + static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long; + + /** + * Returns a Long representing the given 32 bit integer value. + */ + static fromInt(value: number, unsigned?: boolean): Long; + + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + */ + static fromNumber(value: number, unsigned?: boolean): Long; + + /** + * Returns a Long representing the given big integer value. + */ + static fromBigInt(value: bigint, unsigned?: boolean): Long; + + /** + * Returns a Long representation of the given string, written using the specified radix. + */ + static fromString( + str: string, + unsigned?: boolean | number, + radix?: number, + ): Long; + + /** + * Creates a Long from its byte representation. + */ + static fromBytes(bytes: number[], unsigned?: boolean, le?: boolean): Long; + + /** + * Creates a Long from its little endian byte representation. + */ + static fromBytesLE(bytes: number[], unsigned?: boolean): Long; + + /** + * Creates a Long from its big endian byte representation. + */ + static fromBytesBE(bytes: number[], unsigned?: boolean): Long; + + /** + * Tests if the specified object is a Long. + */ + static isLong(obj: any): obj is Long; + + /** + * Converts the specified value to a Long. + */ + static fromValue(val: LongLike, unsigned?: boolean): Long; + + /** + * Returns the sum of this and the specified Long. + */ + add(addend: LongLike): Long; + + /** + * Returns the bitwise AND of this Long and the specified. + */ + and(other: LongLike): Long; + + /** + * Compares this Long's value with the specified's. + */ + compare(other: LongLike): number; + + /** + * Compares this Long's value with the specified's. + */ + comp(other: LongLike): number; + + /** + * Returns this Long divided by the specified. + */ + divide(divisor: LongLike): Long; + + /** + * Returns this Long divided by the specified. + */ + div(divisor: LongLike): Long; + + /** + * Tests if this Long's value equals the specified's. + */ + equals(other: LongLike): boolean; + + /** + * Tests if this Long's value equals the specified's. + */ + eq(other: LongLike): boolean; + + /** + * Gets the high 32 bits as a signed integer. + */ + getHighBits(): number; + + /** + * Gets the high 32 bits as an unsigned integer. + */ + getHighBitsUnsigned(): number; + + /** + * Gets the low 32 bits as a signed integer. + */ + getLowBits(): number; + + /** + * Gets the low 32 bits as an unsigned integer. + */ + getLowBitsUnsigned(): number; + + /** + * Gets the number of bits needed to represent the absolute value of this Long. + */ + getNumBitsAbs(): number; + + /** + * Tests if this Long's value is greater than the specified's. + */ + greaterThan(other: LongLike): boolean; + + /** + * Tests if this Long's value is greater than the specified's. + */ + gt(other: LongLike): boolean; + + /** + * Tests if this Long's value is greater than or equal the specified's. + */ + greaterThanOrEqual(other: LongLike): boolean; + + /** + * Tests if this Long's value is greater than or equal the specified's. + */ + gte(other: LongLike): boolean; + + /** + * Tests if this Long's value is greater than or equal the specified's. + */ + ge(other: LongLike): boolean; + + /** + * Tests if this Long's value is even. + */ + isEven(): boolean; + + /** + * Tests if this Long's value is negative. + */ + isNegative(): boolean; + + /** + * Tests if this Long's value is odd. + */ + isOdd(): boolean; + + /** + * Tests if this Long's value is positive or zero. + */ + isPositive(): boolean; + + /** + * Tests if this Long can be safely represented as a JavaScript number. + */ + isSafeInteger(): boolean; + + /** + * Tests if this Long's value equals zero. + */ + isZero(): boolean; + + /** + * Tests if this Long's value equals zero. + */ + eqz(): boolean; + + /** + * Tests if this Long's value is less than the specified's. + */ + lessThan(other: LongLike): boolean; + + /** + * Tests if this Long's value is less than the specified's. + */ + lt(other: LongLike): boolean; + + /** + * Tests if this Long's value is less than or equal the specified's. + */ + lessThanOrEqual(other: LongLike): boolean; + + /** + * Tests if this Long's value is less than or equal the specified's. + */ + lte(other: LongLike): boolean; + + /** + * Tests if this Long's value is less than or equal the specified's. + */ + le(other: LongLike): boolean; + + /** + * Returns this Long modulo the specified. + */ + modulo(other: LongLike): Long; + + /** + * Returns this Long modulo the specified. + */ + mod(other: LongLike): Long; + + /** + * Returns this Long modulo the specified. + */ + rem(other: LongLike): Long; + + /** + * Returns the product of this and the specified Long. + */ + multiply(multiplier: LongLike): Long; + + /** + * Returns the product of this and the specified Long. + */ + mul(multiplier: LongLike): Long; + + /** + * Negates this Long's value. + */ + negate(): Long; + + /** + * Negates this Long's value. + */ + neg(): Long; + + /** + * Returns the bitwise NOT of this Long. + */ + not(): Long; + + /** + * Returns count leading zeros of this Long. + */ + countLeadingZeros(): number; + + /** + * Returns count leading zeros of this Long. + */ + clz(): number; + + /** + * Returns count trailing zeros of this Long. + */ + countTrailingZeros(): number; + + /** + * Returns count trailing zeros of this Long. + */ + ctz(): number; + + /** + * Tests if this Long's value differs from the specified's. + */ + notEquals(other: LongLike): boolean; + + /** + * Tests if this Long's value differs from the specified's. + */ + neq(other: LongLike): boolean; + + /** + * Tests if this Long's value differs from the specified's. + */ + ne(other: LongLike): boolean; + + /** + * Returns the bitwise OR of this Long and the specified. + */ + or(other: LongLike): Long; + + /** + * Returns this Long with bits shifted to the left by the given amount. + */ + shiftLeft(numBits: number | Long): Long; + + /** + * Returns this Long with bits shifted to the left by the given amount. + */ + shl(numBits: number | Long): Long; + + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + */ + shiftRight(numBits: number | Long): Long; + + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + */ + shr(numBits: number | Long): Long; + + /** + * Returns this Long with bits logically shifted to the right by the given amount. + */ + shiftRightUnsigned(numBits: number | Long): Long; + + /** + * Returns this Long with bits logically shifted to the right by the given amount. + */ + shru(numBits: number | Long): Long; + + /** + * Returns this Long with bits logically shifted to the right by the given amount. + */ + shr_u(numBits: number | Long): Long; + + /** + * Returns this Long with bits rotated to the left by the given amount. + */ + rotateLeft(numBits: number | Long): Long; + + /** + * Returns this Long with bits rotated to the left by the given amount. + */ + rotl(numBits: number | Long): Long; + + /** + * Returns this Long with bits rotated to the right by the given amount. + */ + rotateRight(numBits: number | Long): Long; + + /** + * Returns this Long with bits rotated to the right by the given amount. + */ + rotr(numBits: number | Long): Long; + + /** + * Returns the difference of this and the specified Long. + */ + subtract(subtrahend: LongLike): Long; + + /** + * Returns the difference of this and the specified Long. + */ + sub(subtrahend: LongLike): Long; + + /** + * Converts the Long to a big integer. + */ + toBigInt(): bigint; + + /** + * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. + */ + toInt(): number; + + /** + * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). + */ + toNumber(): number; + + /** + * Converts this Long to its byte representation. + */ + + toBytes(le?: boolean): number[]; + + /** + * Converts this Long to its little endian byte representation. + */ + + toBytesLE(): number[]; + + /** + * Converts this Long to its big endian byte representation. + */ + + toBytesBE(): number[]; + + /** + * Converts this Long to signed. + */ + toSigned(): Long; + + /** + * Converts the Long to a string written in the specified radix. + */ + toString(radix?: number): string; + + /** + * Converts this Long to unsigned. + */ + toUnsigned(): Long; + + /** + * Returns the bitwise XOR of this Long and the given one. + */ + xor(other: LongLike): Long; +} diff --git a/node_modules/lru-cache/LICENSE b/node_modules/lru-cache/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/lru-cache/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/lru-cache/README.md b/node_modules/lru-cache/README.md new file mode 100644 index 0000000..435dfeb --- /dev/null +++ b/node_modules/lru-cache/README.md @@ -0,0 +1,166 @@ +# lru cache + +A cache object that deletes the least-recently-used items. + +[![Build Status](https://travis-ci.org/isaacs/node-lru-cache.svg?branch=master)](https://travis-ci.org/isaacs/node-lru-cache) [![Coverage Status](https://coveralls.io/repos/isaacs/node-lru-cache/badge.svg?service=github)](https://coveralls.io/github/isaacs/node-lru-cache) + +## Installation: + +```javascript +npm install lru-cache --save +``` + +## Usage: + +```javascript +var LRU = require("lru-cache") + , options = { max: 500 + , length: function (n, key) { return n * 2 + key.length } + , dispose: function (key, n) { n.close() } + , maxAge: 1000 * 60 * 60 } + , cache = new LRU(options) + , otherCache = new LRU(50) // sets just the max size + +cache.set("key", "value") +cache.get("key") // "value" + +// non-string keys ARE fully supported +// but note that it must be THE SAME object, not +// just a JSON-equivalent object. +var someObject = { a: 1 } +cache.set(someObject, 'a value') +// Object keys are not toString()-ed +cache.set('[object Object]', 'a different value') +assert.equal(cache.get(someObject), 'a value') +// A similar object with same keys/values won't work, +// because it's a different object identity +assert.equal(cache.get({ a: 1 }), undefined) + +cache.reset() // empty the cache +``` + +If you put more stuff in it, then items will fall out. + +If you try to put an oversized thing in it, then it'll fall out right +away. + +## Options + +* `max` The maximum size of the cache, checked by applying the length + function to all values in the cache. Not setting this is kind of + silly, since that's the whole purpose of this lib, but it defaults + to `Infinity`. Setting it to a non-number or negative number will + throw a `TypeError`. Setting it to 0 makes it be `Infinity`. +* `maxAge` Maximum age in ms. Items are not pro-actively pruned out + as they age, but if you try to get an item that is too old, it'll + drop it and return undefined instead of giving it to you. + Setting this to a negative value will make everything seem old! + Setting it to a non-number will throw a `TypeError`. +* `length` Function that is used to calculate the length of stored + items. If you're storing strings or buffers, then you probably want + to do something like `function(n, key){return n.length}`. The default is + `function(){return 1}`, which is fine if you want to store `max` + like-sized things. The item is passed as the first argument, and + the key is passed as the second argumnet. +* `dispose` Function that is called on items when they are dropped + from the cache. This can be handy if you want to close file + descriptors or do other cleanup tasks when items are no longer + accessible. Called with `key, value`. It's called *before* + actually removing the item from the internal cache, so if you want + to immediately put it back in, you'll have to do that in a + `nextTick` or `setTimeout` callback or it won't do anything. +* `stale` By default, if you set a `maxAge`, it'll only actually pull + stale items out of the cache when you `get(key)`. (That is, it's + not pre-emptively doing a `setTimeout` or anything.) If you set + `stale:true`, it'll return the stale value before deleting it. If + you don't set this, then it'll return `undefined` when you try to + get a stale entry, as if it had already been deleted. +* `noDisposeOnSet` By default, if you set a `dispose()` method, then + it'll be called whenever a `set()` operation overwrites an existing + key. If you set this option, `dispose()` will only be called when a + key falls out of the cache, not when it is overwritten. +* `updateAgeOnGet` When using time-expiring entries with `maxAge`, + setting this to `true` will make each item's effective time update + to the current time whenever it is retrieved from cache, causing it + to not expire. (It can still fall out of cache based on recency of + use, of course.) + +## API + +* `set(key, value, maxAge)` +* `get(key) => value` + + Both of these will update the "recently used"-ness of the key. + They do what you think. `maxAge` is optional and overrides the + cache `maxAge` option if provided. + + If the key is not found, `get()` will return `undefined`. + + The key and val can be any value. + +* `peek(key)` + + Returns the key value (or `undefined` if not found) without + updating the "recently used"-ness of the key. + + (If you find yourself using this a lot, you *might* be using the + wrong sort of data structure, but there are some use cases where + it's handy.) + +* `del(key)` + + Deletes a key out of the cache. + +* `reset()` + + Clear the cache entirely, throwing away all values. + +* `has(key)` + + Check if a key is in the cache, without updating the recent-ness + or deleting it for being stale. + +* `forEach(function(value,key,cache), [thisp])` + + Just like `Array.prototype.forEach`. Iterates over all the keys + in the cache, in order of recent-ness. (Ie, more recently used + items are iterated over first.) + +* `rforEach(function(value,key,cache), [thisp])` + + The same as `cache.forEach(...)` but items are iterated over in + reverse order. (ie, less recently used items are iterated over + first.) + +* `keys()` + + Return an array of the keys in the cache. + +* `values()` + + Return an array of the values in the cache. + +* `length` + + Return total length of objects in cache taking into account + `length` options function. + +* `itemCount` + + Return total quantity of objects currently in cache. Note, that + `stale` (see options) items are returned as part of this item + count. + +* `dump()` + + Return an array of the cache entries ready for serialization and usage + with 'destinationCache.load(arr)`. + +* `load(cacheEntriesArray)` + + Loads another cache entries array, obtained with `sourceCache.dump()`, + into the cache. The destination cache is reset before loading new entries + +* `prune()` + + Manually iterates over the entire cache proactively pruning old entries diff --git a/node_modules/lru-cache/index.js b/node_modules/lru-cache/index.js new file mode 100644 index 0000000..573b6b8 --- /dev/null +++ b/node_modules/lru-cache/index.js @@ -0,0 +1,334 @@ +'use strict' + +// A linked list to keep track of recently-used-ness +const Yallist = require('yallist') + +const MAX = Symbol('max') +const LENGTH = Symbol('length') +const LENGTH_CALCULATOR = Symbol('lengthCalculator') +const ALLOW_STALE = Symbol('allowStale') +const MAX_AGE = Symbol('maxAge') +const DISPOSE = Symbol('dispose') +const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') +const LRU_LIST = Symbol('lruList') +const CACHE = Symbol('cache') +const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') + +const naiveLength = () => 1 + +// lruList is a yallist where the head is the youngest +// item, and the tail is the oldest. the list contains the Hit +// objects as the entries. +// Each Hit object has a reference to its Yallist.Node. This +// never changes. +// +// cache is a Map (or PseudoMap) that matches the keys to +// the Yallist.Node object. +class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options } + + if (!options) + options = {} + + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + const max = this[MAX] = options.max || Infinity + + const lc = options.length || naiveLength + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc + this[ALLOW_STALE] = options.stale || false + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0 + this[DISPOSE] = options.dispose + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false + this.reset() + } + + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') + + this[MAX] = mL || Infinity + trim(this) + } + get max () { + return this[MAX] + } + + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale + } + get allowStale () { + return this[ALLOW_STALE] + } + + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') + + this[MAX_AGE] = mA + trim(this) + } + get maxAge () { + return this[MAX_AGE] + } + + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC + this[LENGTH] = 0 + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) + this[LENGTH] += hit.length + }) + } + trim(this) + } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } + + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } + + rforEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev + forEachStep(this, fn, walker, thisp) + walker = prev + } + } + + forEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next + forEachStep(this, fn, walker, thisp) + walker = next + } + } + + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } + + values () { + return this[LRU_LIST].toArray().map(k => k.value) + } + + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) + } + + this[CACHE] = new Map() // hash of items by key + this[LRU_LIST] = new Yallist() // list of items in order of use recency + this[LENGTH] = 0 // length of items in the list + } + + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } + + dumpLru () { + return this[LRU_LIST] + } + + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE] + + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') + + const now = maxAge ? Date.now() : 0 + const len = this[LENGTH_CALCULATOR](value, key) + + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)) + return false + } + + const node = this[CACHE].get(key) + const item = node.value + + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value) + } + + item.now = now + item.maxAge = maxAge + item.value = value + this[LENGTH] += len - item.length + item.length = len + this.get(key) + trim(this) + return true + } + + const hit = new Entry(key, value, len, now, maxAge) + + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value) + + return false + } + + this[LENGTH] += hit.length + this[LRU_LIST].unshift(hit) + this[CACHE].set(key, this[LRU_LIST].head) + trim(this) + return true + } + + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value + return !isStale(this, hit) + } + + get (key) { + return get(this, key, true) + } + + peek (key) { + return get(this, key, false) + } + + pop () { + const node = this[LRU_LIST].tail + if (!node) + return null + + del(this, node) + return node.value + } + + del (key) { + del(this, this[CACHE].get(key)) + } + + load (arr) { + // reset the cache + this.reset() + + const now = Date.now() + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l] + const expiresAt = hit.e || 0 + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v) + else { + const maxAge = expiresAt - now + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge) + } + } + } + } + + prune () { + this[CACHE].forEach((value, key) => get(this, key, false)) + } +} + +const get = (self, key, doUse) => { + const node = self[CACHE].get(key) + if (node) { + const hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now() + self[LRU_LIST].unshiftNode(node) + } + } + return hit.value + } +} + +const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false + + const diff = Date.now() - hit.now + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) +} + +const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev + del(self, walker) + walker = prev + } + } +} + +const del = (self, node) => { + if (node) { + const hit = node.value + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value) + + self[LENGTH] -= hit.length + self[CACHE].delete(hit.key) + self[LRU_LIST].removeNode(node) + } +} + +class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key + this.value = value + this.length = length + this.now = now + this.maxAge = maxAge || 0 + } +} + +const forEachStep = (self, fn, node, thisp) => { + let hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + hit = undefined + } + if (hit) + fn.call(thisp, hit.value, hit.key, self) +} + +module.exports = LRUCache diff --git a/node_modules/lru-cache/package.json b/node_modules/lru-cache/package.json new file mode 100644 index 0000000..43b7502 --- /dev/null +++ b/node_modules/lru-cache/package.json @@ -0,0 +1,34 @@ +{ + "name": "lru-cache", + "description": "A cache object that deletes the least-recently-used items.", + "version": "6.0.0", + "author": "Isaac Z. Schlueter ", + "keywords": [ + "mru", + "lru", + "cache" + ], + "scripts": { + "test": "tap", + "snap": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags" + }, + "main": "index.js", + "repository": "git://github.com/isaacs/node-lru-cache.git", + "devDependencies": { + "benchmark": "^2.1.4", + "tap": "^14.10.7" + }, + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "files": [ + "index.js" + ], + "engines": { + "node": ">=10" + } +} diff --git a/node_modules/lru-memoizer/.jshintrc b/node_modules/lru-memoizer/.jshintrc new file mode 100644 index 0000000..0d64641 --- /dev/null +++ b/node_modules/lru-memoizer/.jshintrc @@ -0,0 +1,41 @@ +{ + "camelcase": false, + "curly": false, + + "node": true, + "esnext": true, + "bitwise": true, + "eqeqeq": true, + "immed": true, + "indent": 2, + "latedef": false, + "newcap": true, + "noarg": true, + "regexp": true, + "undef": true, + "strict": false, + "smarttabs": true, + "expr": true, + + "evil": true, + "browser": true, + "regexdash": true, + "wsh": true, + "trailing": true, + "sub": true, + "unused": true, + "laxcomma": true, + "nonbsp": true, + + "newcap": false, + + "globals": { + "after": false, + "before": false, + "afterEach": false, + "beforeEach": false, + "describe": false, + "it": false, + "escape": false + } +} diff --git a/node_modules/lru-memoizer/LICENSE b/node_modules/lru-memoizer/LICENSE new file mode 100644 index 0000000..a860b49 --- /dev/null +++ b/node_modules/lru-memoizer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 JOSE FERNANDO ROMANIELLO (http://joseoncode.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/lru-memoizer/README.md b/node_modules/lru-memoizer/README.md new file mode 100644 index 0000000..b8a82b5 --- /dev/null +++ b/node_modules/lru-memoizer/README.md @@ -0,0 +1,88 @@ +Memoize functions results using an lru-cache. + +## Installation + +``` +npm i lru-memoizer --save +``` + +## Intro + +This module uses an [lru-cache](https://github.com/isaacs/node-lru-cache) internally to cache the results of an async function. + +The `load` function can have N parameters and the last one must be a callback. The callback should be an errback (first parameter is `err`). + +The `hash` function purpose is generate a custom hash for storing results. It has all the arguments applied to it minus the callback, and must return an string synchronous. + +The `disable` function allows you to conditionally disable the use of the cache. Useful for test environments. + +The `freeze` option (defaults to **false**) allows you to deep-freeze the result of the async function. + +The `clone` option (defaults to **false**) allows you to deep-clone the result every time is returned from the cache. + +## Usage + +```javascript + +var memoizer = require('lru-memoizer'); + +var memoizedGet = memoizer({ + //defines how to load the resource when + //it is not in the cache. + load: function (options, callback) { + request.get(options, callback); + }, + + //defines how to create a cache key from the params. + hash: function (options) { + return options.url + qs.stringify(options.qs); + }, + + //don't cache in test environment + disable: isTestEnv(), + + //all other params for the LRU cache. + max: 100, + maxAge: 1000 * 60 +}); + +memoizedGet({ + url: 'https://google.com', + qs: { foo: 123 } +}, function (err, result, body) { + //console.log(body); +}) + +``` + +## Sync lru-memoizer + +Use `memoizer.sync` to cache things that are slow to calculate or methods returning promises. + +``` +var memoizer = require('lru-memoizer'); +var memoizedGet = memoizer.sync({ + //defines how to load the resource when + //it is not in the cache. + load: function (params) { + //return something_hard_to_compute;s + }, + + //defines how to create a cache key from the params. + hash: function (params) { + return params.foo; + }, + + //all other params for the LRU cache. + max: 100, + maxAge: 1000 * 60 +}); +``` + +## Similar modules + +This module is very similar to [async-cache](https://github.com/isaacs/async-cache), the main difference is the `hash` function. + +## License + +MIT 2016 - José F. Romaniello diff --git a/node_modules/lru-memoizer/lib/async.d.ts b/node_modules/lru-memoizer/lib/async.d.ts new file mode 100644 index 0000000..8db4ccf --- /dev/null +++ b/node_modules/lru-memoizer/lib/async.d.ts @@ -0,0 +1,85 @@ +import { syncMemoizer } from './sync'; +import { INodeStyleCallBack as CB, ResultBase, IParamsBase0, IParamsBase1, IParamsBase2, IParamsBase3, IParamsBase4, IParamsBase5, IParamsBase6 } from './util'; +export interface IMemoized extends ResultBase { + (cb: CB): void; + (a1: T1, cb: CB): void; + (a1: T1, a2: T2, cb: CB): void; + (a1: T1, a2: T2, a3: T3, cb: CB): void; + (a1: T1, a2: T2, a3: T3, a4: T4, cb: CB): void; + (a1: T1, a2: T2, a3: T3, a4: T4, a5: T5, cb: CB): void; + (a1: T1, a2: T2, a3: T3, a4: T4, a5: T5, a6: T6, cb: CB): void; +} +interface IMemoizableFunction0 { + (cb: CB): void; +} +interface IMemoizableFunction1 { + (a1: T1, cb: CB): void; +} +interface IMemoizableFunction2 { + (a1: T1, a2: T2, cb: CB): void; +} +interface IMemoizableFunction3 { + (a1: T1, a2: T2, a3: T3, cb: CB): void; +} +interface IMemoizableFunction4 { + (a1: T1, a2: T2, a3: T3, a4: T4, cb: CB): void; +} +interface IMemoizableFunction5 { + (a1: T1, a2: T2, a3: T3, a4: T4, a5: T5, cb: CB): void; +} +interface IMemoizableFunction6 { + (a1: T1, a2: T2, a3: T3, a4: T4, a5: T5, a6: T6, cb: CB): void; +} +interface AsyncParams0 extends IParamsBase0 { + load: IMemoizableFunction0; +} +interface AsyncParams1 extends IParamsBase1 { + load: IMemoizableFunction1; +} +interface AsyncParams2 extends IParamsBase2 { + load: IMemoizableFunction2; +} +interface AsyncParams3 extends IParamsBase3 { + load: IMemoizableFunction3; +} +interface AsyncParams4 extends IParamsBase4 { + load: IMemoizableFunction4; +} +interface AsyncParams5 extends IParamsBase5 { + load: IMemoizableFunction5; +} +interface AsyncParams6 extends IParamsBase6 { + /** + * The function that loads the resource when is not in the cache. + */ + load: IMemoizableFunction6; +} +declare function asyncMemoizer(options: AsyncParams0): IMemoized; +declare namespace asyncMemoizer { + var sync: typeof syncMemoizer; +} +declare function asyncMemoizer(options: AsyncParams1): IMemoized; +declare namespace asyncMemoizer { + var sync: typeof syncMemoizer; +} +declare function asyncMemoizer(options: AsyncParams2): IMemoized; +declare namespace asyncMemoizer { + var sync: typeof syncMemoizer; +} +declare function asyncMemoizer(options: AsyncParams3): IMemoized; +declare namespace asyncMemoizer { + var sync: typeof syncMemoizer; +} +declare function asyncMemoizer(options: AsyncParams4): IMemoized; +declare namespace asyncMemoizer { + var sync: typeof syncMemoizer; +} +declare function asyncMemoizer(options: AsyncParams5): IMemoized; +declare namespace asyncMemoizer { + var sync: typeof syncMemoizer; +} +declare function asyncMemoizer(options: AsyncParams6): IMemoized; +declare namespace asyncMemoizer { + var sync: typeof syncMemoizer; +} +export { asyncMemoizer }; diff --git a/node_modules/lru-memoizer/lib/async.js b/node_modules/lru-memoizer/lib/async.js new file mode 100644 index 0000000..2f93b30 --- /dev/null +++ b/node_modules/lru-memoizer/lib/async.js @@ -0,0 +1,178 @@ +"use strict"; +var __read = (this && this.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +}; +var __spread = (this && this.__spread) || function () { + for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); + return ar; +}; +var __values = (this && this.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.asyncMemoizer = void 0; +var lru_cache_1 = __importDefault(require("lru-cache")); +var events_1 = require("events"); +var lodash_clonedeep_1 = __importDefault(require("lodash.clonedeep")); +var freeze_1 = require("./freeze"); +var sync_1 = require("./sync"); +function asyncMemoizer(options) { + var cache = new lru_cache_1.default(options); + var load = options.load; + var hash = options.hash; + var bypass = options.bypass; + var itemMaxAge = options.itemMaxAge; + var freeze = options.freeze; + var clone = options.clone; + var queueMaxAge = options.queueMaxAge || 1000; + var loading = new Map(); + var emitter = new events_1.EventEmitter(); + var memoizerMethods = Object.assign({ + del: del, + reset: function () { return cache.reset(); }, + keys: cache.keys.bind(cache), + on: emitter.on.bind(emitter), + once: emitter.once.bind(emitter) + }, options); + if (options.disable) { + return Object.assign(load, memoizerMethods); + } + function del() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var key = hash.apply(void 0, __spread(args)); + cache.del(key); + } + function add(key, parameters, result) { + if (freeze) { + result.forEach(freeze_1.deepFreeze); + } + if (itemMaxAge) { + cache.set(key, result, itemMaxAge.apply(void 0, __spread(parameters.concat(result)))); + } + else { + cache.set(key, result); + } + } + function runCallbacks(callbacks, args) { + var e_1, _a; + try { + for (var callbacks_1 = __values(callbacks), callbacks_1_1 = callbacks_1.next(); !callbacks_1_1.done; callbacks_1_1 = callbacks_1.next()) { + var callback = callbacks_1_1.value; + // Simulate async call when returning from cache + // and yield between callback resolution + if (clone) { + setImmediate.apply(void 0, __spread([callback], args.map(lodash_clonedeep_1.default))); + } + else { + setImmediate.apply(void 0, __spread([callback], args)); + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (callbacks_1_1 && !callbacks_1_1.done && (_a = callbacks_1.return)) _a.call(callbacks_1); + } + finally { if (e_1) throw e_1.error; } + } + } + function emit(event) { + var parameters = []; + for (var _i = 1; _i < arguments.length; _i++) { + parameters[_i - 1] = arguments[_i]; + } + emitter.emit.apply(emitter, __spread([event], parameters)); + } + function memoizedFunction() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var parameters = args.slice(0, -1); + var callback = args.slice(-1).pop(); + var key; + if (bypass && bypass.apply(void 0, __spread(parameters))) { + emit.apply(void 0, __spread(['miss'], parameters)); + return load.apply(void 0, __spread(args)); + } + if (parameters.length === 0 && !hash) { + //the load function only receives callback. + key = '_'; + } + else { + key = hash.apply(void 0, __spread(parameters)); + } + var fromCache = cache.get(key); + if (fromCache) { + emit.apply(void 0, __spread(['hit'], parameters)); + // found, invoke callback + return runCallbacks([callback], [null].concat(fromCache)); + } + var pendingLoad = loading.get(key); + if (pendingLoad && pendingLoad.expiresAt > Date.now()) { + // request already in progress, queue and return + pendingLoad.queue.push(callback); + emit.apply(void 0, __spread(['queue'], parameters)); + return; + } + emit.apply(void 0, __spread(['miss'], parameters)); + var started = Date.now(); + // no pending request or not resolved before expiration + // create a new queue and invoke load + var queue = [callback]; + loading.set(key, { + queue: queue, + expiresAt: started + queueMaxAge + }); + var loadHandler = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var err = args[0]; + if (!err) { + add(key, parameters, args.slice(1)); + } + // this can potentially delete a different queue than `queue` if + // this callback was called after expiration. + // that will only cause a new call to be performed and a new queue to be + // created + loading.delete(key); + emit.apply(void 0, __spread(['loaded', Date.now() - started], parameters)); + runCallbacks(queue, args); + }; + load.apply(void 0, __spread(parameters, [loadHandler])); + } + ; + return Object.assign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file diff --git a/node_modules/lru-memoizer/lib/freeze.d.ts b/node_modules/lru-memoizer/lib/freeze.d.ts new file mode 100644 index 0000000..86b5533 --- /dev/null +++ b/node_modules/lru-memoizer/lib/freeze.d.ts @@ -0,0 +1 @@ +export declare function deepFreeze(o: any): any; diff --git a/node_modules/lru-memoizer/lib/freeze.js b/node_modules/lru-memoizer/lib/freeze.js new file mode 100644 index 0000000..4c147b3 --- /dev/null +++ b/node_modules/lru-memoizer/lib/freeze.js @@ -0,0 +1,23 @@ +"use strict"; +// From https://raw.githubusercontent.com/nikoskalogridis/deep-freeze/fb921b32064dce1645197be2bf975fe0385450b0/index.js +// which is sadly, no longer maintained +Object.defineProperty(exports, "__esModule", { value: true }); +exports.deepFreeze = void 0; +function deepFreeze(o) { + if (o) { + Object.freeze(o); + Object.getOwnPropertyNames(o).forEach(function (prop) { + if (o.hasOwnProperty(prop) + && o[prop] !== null + && (typeof o[prop] === 'object' || typeof o[prop] === 'function') + && (o[prop].constructor !== Buffer) + && !Object.isFrozen(o[prop])) { + deepFreeze(o[prop]); + } + }); + } + return o; +} +exports.deepFreeze = deepFreeze; +; +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZnJlZXplLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2ZyZWV6ZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsdUhBQXVIO0FBQ3ZILHVDQUF1Qzs7O0FBRXZDLFNBQWdCLFVBQVUsQ0FBRSxDQUFNO0lBQ2hDLElBQUksQ0FBQyxFQUFFO1FBQ0wsTUFBTSxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQztRQUVqQixNQUFNLENBQUMsbUJBQW1CLENBQUMsQ0FBQyxDQUFDLENBQUMsT0FBTyxDQUFDLFVBQVUsSUFBSTtZQUNsRCxJQUFJLENBQUMsQ0FBQyxjQUFjLENBQUMsSUFBSSxDQUFDO21CQUNyQixDQUFDLENBQUMsSUFBSSxDQUFDLEtBQUssSUFBSTttQkFDaEIsQ0FBQyxPQUFPLENBQUMsQ0FBQyxJQUFJLENBQUMsS0FBSyxRQUFRLElBQUksT0FBTyxDQUFDLENBQUMsSUFBSSxDQUFDLEtBQUssVUFBVSxDQUFDO21CQUM5RCxDQUFDLENBQUMsQ0FBQyxJQUFJLENBQUMsQ0FBQyxXQUFXLEtBQUssTUFBTSxDQUFDO21CQUNoQyxDQUFDLE1BQU0sQ0FBQyxRQUFRLENBQUMsQ0FBQyxDQUFDLElBQUksQ0FBQyxDQUFDLEVBQUU7Z0JBQzVCLFVBQVUsQ0FBQyxDQUFDLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQzthQUNyQjtRQUNMLENBQUMsQ0FBQyxDQUFDO0tBQ0o7SUFFRCxPQUFPLENBQUMsQ0FBQztBQUNYLENBQUM7QUFoQkQsZ0NBZ0JDO0FBQUEsQ0FBQyJ9 \ No newline at end of file diff --git a/node_modules/lru-memoizer/lib/index.d.ts b/node_modules/lru-memoizer/lib/index.d.ts new file mode 100644 index 0000000..a6be116 --- /dev/null +++ b/node_modules/lru-memoizer/lib/index.d.ts @@ -0,0 +1,2 @@ +import { asyncMemoizer } from './async'; +export = asyncMemoizer; diff --git a/node_modules/lru-memoizer/lib/index.js b/node_modules/lru-memoizer/lib/index.js new file mode 100644 index 0000000..c8a336b --- /dev/null +++ b/node_modules/lru-memoizer/lib/index.js @@ -0,0 +1,4 @@ +"use strict"; +var async_1 = require("./async"); +module.exports = async_1.asyncMemoizer; +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLGlDQUF3QztBQUV4QyxpQkFBUyxxQkFBYSxDQUFDIn0= \ No newline at end of file diff --git a/node_modules/lru-memoizer/lib/sync.d.ts b/node_modules/lru-memoizer/lib/sync.d.ts new file mode 100644 index 0000000..1042dc6 --- /dev/null +++ b/node_modules/lru-memoizer/lib/sync.d.ts @@ -0,0 +1,65 @@ +import { ResultBase, IParamsBase0, IParamsBase1, IParamsBase2, IParamsBase3, IParamsBase4, IParamsBase5, IParamsBase6, IParamsBasePlus } from './util'; +interface IMemoizedSync extends ResultBase { + (arg1: T1): TResult; + (arg1: T1, arg2: T2): TResult; + (arg1: T1, arg2: T2, arg3: T3): TResult; + (arg1: T1, arg2: T2, arg3: T3, arg4: T4): TResult; + (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5): TResult; + (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6): TResult; +} +interface IMemoizableFunctionSync0 { + (): TResult; +} +interface IMemoizableFunctionSync1 { + (arg1: T1): TResult; +} +interface IMemoizableFunctionSync2 { + (arg1: T1, arg2: T2): TResult; +} +interface IMemoizableFunctionSync3 { + (arg1: T1, arg2: T2, arg3: T3): TResult; +} +interface IMemoizableFunctionSync4 { + (arg1: T1, arg2: T2, arg3: T3, arg4: T4): TResult; +} +interface IMemoizableFunctionSync5 { + (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5): TResult; +} +interface IMemoizableFunctionSync6 { + (a1: T1, a2: T2, a3: T3, a4: T4, a5: T5, a6: T6): TResult; +} +interface IMemoizableFunctionSyncPlus { + (...args: any[]): TResult; +} +export interface SyncParams0 extends IParamsBase0 { + load: IMemoizableFunctionSync0; +} +export interface SyncParams1 extends IParamsBase1 { + load: IMemoizableFunctionSync1; +} +export interface SyncParams2 extends IParamsBase2 { + load: IMemoizableFunctionSync2; +} +export interface SyncParams3 extends IParamsBase3 { + load: IMemoizableFunctionSync3; +} +export interface SyncParams4 extends IParamsBase4 { + load: IMemoizableFunctionSync4; +} +export interface SyncParams5 extends IParamsBase5 { + load: IMemoizableFunctionSync5; +} +export interface SyncParams6 extends IParamsBase6 { + load: IMemoizableFunctionSync6; +} +export interface SyncParamsPlus extends IParamsBasePlus { + load: IMemoizableFunctionSyncPlus; +} +export declare function syncMemoizer(options: SyncParams0): IMemoizedSync; +export declare function syncMemoizer(options: SyncParams1): IMemoizedSync; +export declare function syncMemoizer(options: SyncParams2): IMemoizedSync; +export declare function syncMemoizer(options: SyncParams3): IMemoizedSync; +export declare function syncMemoizer(options: SyncParams4): IMemoizedSync; +export declare function syncMemoizer(options: SyncParams5): IMemoizedSync; +export declare function syncMemoizer(options: SyncParams6): IMemoizedSync; +export {}; diff --git a/node_modules/lru-memoizer/lib/sync.js b/node_modules/lru-memoizer/lib/sync.js new file mode 100644 index 0000000..e36c40d --- /dev/null +++ b/node_modules/lru-memoizer/lib/sync.js @@ -0,0 +1,114 @@ +"use strict"; +var __read = (this && this.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +}; +var __spread = (this && this.__spread) || function () { + for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); + return ar; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.syncMemoizer = void 0; +var lru_cache_1 = __importDefault(require("lru-cache")); +var events_1 = require("events"); +var lodash_clonedeep_1 = __importDefault(require("lodash.clonedeep")); +var freeze_1 = require("./freeze"); +function syncMemoizer(options) { + var cache = new lru_cache_1.default(options); + var load = options.load; + var hash = options.hash; + var bypass = options.bypass; + var itemMaxAge = options.itemMaxAge; + var freeze = options.freeze; + var clone = options.clone; + var emitter = new events_1.EventEmitter(); + var defaultResult = Object.assign({ + del: del, + reset: function () { return cache.reset(); }, + keys: cache.keys.bind(cache), + on: emitter.on.bind(emitter), + once: emitter.once.bind(emitter), + }, options); + if (options.disable) { + return Object.assign(load, defaultResult); + } + function del() { + var key = hash.apply(void 0, __spread(arguments)); + cache.del(key); + } + function emit(event) { + var parameters = []; + for (var _i = 1; _i < arguments.length; _i++) { + parameters[_i - 1] = arguments[_i]; + } + emitter.emit.apply(emitter, __spread([event], parameters)); + } + function isPromise(result) { + // detect native, bluebird, A+ promises + return result && result.then && typeof result.then === 'function'; + } + function processResult(result) { + var res = result; + if (clone) { + if (isPromise(res)) { + res = res.then(lodash_clonedeep_1.default); + } + else { + res = lodash_clonedeep_1.default(res); + } + } + if (freeze) { + if (isPromise(res)) { + res = res.then(freeze_1.deepFreeze); + } + else { + freeze_1.deepFreeze(res); + } + } + return res; + } + var result = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (bypass && bypass.apply(void 0, __spread(args))) { + emit.apply(void 0, __spread(['miss'], args)); + return load.apply(void 0, __spread(args)); + } + var key = hash.apply(void 0, __spread(args)); + var fromCache = cache.get(key); + if (fromCache) { + emit.apply(void 0, __spread(['hit'], args)); + return processResult(fromCache); + } + emit.apply(void 0, __spread(['miss'], args)); + var result = load.apply(void 0, __spread(args)); + if (itemMaxAge) { + // @ts-ignore + cache.set(key, result, itemMaxAge.apply(void 0, __spread(args.concat([result])))); + } + else { + cache.set(key, result); + } + return processResult(result); + }; + return Object.assign(result, defaultRes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LHdCQUFJLElBQUksQ0FBQyxNQUFNLENBQUMsQ0FBRSxNQUFNLENBQUUsQ0FBQyxHQUFFLENBQUM7U0FDaEU7YUFBTTtZQUNMLEtBQUssQ0FBQyxHQUFHLENBQUMsR0FBRyxFQUFFLE1BQU0sQ0FBQyxDQUFDO1NBQ3hCO1FBRUQsT0FBTyxhQUFhLENBQUMsTUFBTSxDQUFDLENBQUM7SUFDL0IsQ0FBQyxDQUFDO0lBRUYsT0FBTyxNQUFNLENBQUMsTUFBTSxDQUFDLE1BQU0sRUFBRSxhQUFhLENBQVEsQ0FBQztBQUNyRCxDQUFDO0FBNUZELG9DQTRGQyJ9 \ No newline at end of file diff --git a/node_modules/lru-memoizer/lib/util.d.ts b/node_modules/lru-memoizer/lib/util.d.ts new file mode 100644 index 0000000..0509667 --- /dev/null +++ b/node_modules/lru-memoizer/lib/util.d.ts @@ -0,0 +1,162 @@ +import LRU from 'lru-cache'; +export declare type Listener = (...as: any[]) => void; +export declare type INodeStyleCallBack = (err: Error | null, result?: Success) => void; +export interface ResultBase { + /** + * Returns all keys in the cache. + */ + keys: () => string[]; + /** + * Clear the cache. + */ + reset: () => void; + /** + * Delete an item given the parameters. + */ + del: (a1?: T1, a2?: T2, a3?: T3, a4?: T4, a5?: T5, a6?: T6) => void; + on(event: 'hit', handler: Listener): void; + on(event: 'miss', handler: Listener): void; + on(event: 'queue', handler: Listener): void; +} +export interface IHashingFunction0 { + (): string; +} +export interface IHashingFunction1 { + (a1: T1): string; +} +export interface IHashingFunction2 { + (a1: T1, a2: T2): string; +} +export interface IHashingFunction3 { + (a1: T1, a2: T2, a3: T3): string; +} +export interface IHashingFunction4 { + (a1: T1, a2: T2, a3: T3, a4: T4): string; +} +export interface IHashingFunction5 { + (a1: T1, a2: T2, a3: T3, a4: T4, a5: T5): string; +} +export interface IHashingFunction6 { + (a1: T1, a2: T2, a3: T3, a4: T4, a5: T5, a6: T6): string; +} +export interface IHashingFunctionPlus { + (...rest: any[]): string; +} +export interface IBypassFunction0 { + (): boolean; +} +export interface IBypassFunction1 { + (a1: T1): boolean; +} +export interface IBypassFunction2 { + (a1: T1, a2: T2): boolean; +} +export interface IBypassFunction3 { + (a1: T1, a2: T2, a3: T3): boolean; +} +export interface IBypassFunction4 { + (a1: T1, a2: T2, a3: T3, a4: T4): boolean; +} +export interface IBypassFunction5 { + (a1: T1, a2: T2, a3: T3, a4: T4, a5: T5): boolean; +} +export interface IBypassFunction6 { + (a1: T1, a2: T2, a3: T3, a4: T4, a5: T5, a6: T6): boolean; +} +export interface IBypassFunctionPlus { + (...rest: any[]): boolean; +} +export interface IMaxAgeFunction0 { + (res: TResult): number; +} +export interface IMaxAgeFunction1 { + (a1: T1, res: TResult): number; +} +export interface IMaxAgeFunction2 { + (a1: T1, a2: T2, res: TResult): number; +} +export interface IMaxAgeFunction3 { + (a1: T1, a2: T2, a3: T3, res: TResult): number; +} +export interface IMaxAgeFunction4 { + (a1: T1, a2: T2, a3: T3, a4: T4, res: TResult): number; +} +export interface IMaxAgeFunction5 { + (a1: T1, a2: T2, a3: T3, a4: T4, a5: T5, res: TResult): number; +} +export interface IMaxAgeFunction6 { + (a1: T1, a2: T2, a3: T3, a4: T4, a5: T5, a6: T6, res: TResult): number; +} +export interface IMaxAgeFunctionPlus { + (...rest: any[]): number; +} +export interface IParamsBase0 extends IParamsBaseCommons { + hash: IHashingFunction0; + bypass?: IBypassFunction0; + itemMaxAge?: IMaxAgeFunction0; +} +export interface IParamsBase1 extends IParamsBaseCommons { + hash: IHashingFunction1; + bypass?: IBypassFunction1; + itemMaxAge?: IMaxAgeFunction1; +} +export interface IParamsBase2 extends IParamsBaseCommons { + hash: IHashingFunction2; + bypass?: IBypassFunction2; + itemMaxAge?: IMaxAgeFunction2; +} +export interface IParamsBase3 extends IParamsBaseCommons { + hash: IHashingFunction3; + bypass?: IBypassFunction3; + itemMaxAge?: IMaxAgeFunction3; +} +export interface IParamsBase4 extends IParamsBaseCommons { + hash: IHashingFunction4; + bypass?: IBypassFunction4; + itemMaxAge?: IMaxAgeFunction4; +} +export interface IParamsBase5 extends IParamsBaseCommons { + hash: IHashingFunction5; + bypass?: IBypassFunction5; + itemMaxAge?: IMaxAgeFunction5; +} +export interface IParamsBase6 extends IParamsBaseCommons { + /** + * A function to generate the key of the cache. + */ + hash: IHashingFunction6; + /** + * Return true if the result should not be retrieved from the cache. + */ + bypass?: IBypassFunction6; + /** + * An optional function to indicate the maxAge of an specific item. + */ + itemMaxAge?: IMaxAgeFunction6; +} +export interface IParamsBasePlus extends IParamsBaseCommons { + hash: IHashingFunctionPlus; + bypass?: IBypassFunctionPlus; + itemMaxAge?: IMaxAgeFunctionPlus; +} +interface IParamsBaseCommons extends LRU.Options { + /** + * Indicates if the resource should be freezed. + */ + freeze?: boolean; + /** + * Indicates if the resource should be cloned before is returned. + */ + clone?: boolean; + /** + * Disable the cache and executes the load logic directly. + */ + disable?: boolean; + /** + * Do not queue requests if initial call is more than `queueMaxAge` milliseconds old. + * Instead, invoke `load` again and create a new queue. + * Defaults to 1000ms. + */ + queueMaxAge?: number; +} +export {}; diff --git a/node_modules/lru-memoizer/lib/util.js b/node_modules/lru-memoizer/lib/util.js new file mode 100644 index 0000000..8d86e9f --- /dev/null +++ b/node_modules/lru-memoizer/lib/util.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidXRpbC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3NyYy91dGlsLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiIifQ== \ No newline at end of file diff --git a/node_modules/lru-memoizer/package.json b/node_modules/lru-memoizer/package.json new file mode 100644 index 0000000..1147e63 --- /dev/null +++ b/node_modules/lru-memoizer/package.json @@ -0,0 +1,34 @@ +{ + "name": "lru-memoizer", + "description": "Memoize functions results using an lru-cache.", + "version": "2.3.0", + "author": "José F. Romaniello (http://joseoncode.com)", + "repository": { + "url": "git://github.com/jfromaniello/lru-memoizer.git" + }, + "keywords": [ + "cache", + "memoize", + "lru" + ], + "main": "./lib/index.js", + "types": "./lib/index.d.ts", + "scripts": { + "prepare": "tsc", + "test": "npm run prepare && mocha" + }, + "dependencies": { + "lodash.clonedeep": "^4.5.0", + "lru-cache": "6.0.0" + }, + "license": "MIT", + "devDependencies": { + "@types/lodash.clonedeep": "^4.5.9", + "@types/lru-cache": "^5.1.0", + "@types/node": "^12.0.10", + "chai": "^3.5.0", + "mocha": "^10.4.0", + "sinon": "^7.3.2", + "typescript": "^3.5.2" + } +} diff --git a/node_modules/lru-memoizer/test/lru-memoizer.bypass.test.js b/node_modules/lru-memoizer/test/lru-memoizer.bypass.test.js new file mode 100644 index 0000000..b70cee3 --- /dev/null +++ b/node_modules/lru-memoizer/test/lru-memoizer.bypass.test.js @@ -0,0 +1,39 @@ +const memoizer = require('../lib/index.js'); +const assert = require('chai').assert; + +describe('lru-memoizer (bypass)', function () { + var loadTimes = 0, memoized; + + beforeEach(function () { + loadTimes = 0; + + memoized = memoizer({ + load: function (a, b, callback) { + loadTimes++; + callback(null, a + b); + }, + hash: function (a, b) { + return a + '-' + b; + }, + bypass: function (a, b) { + return a < b; + }, + max: 10 + }); + + + }); + + it('should call the load function every time', function (done) { + memoized(1, 2, function (err) { + assert.isNull(err); + assert.strictEqual(loadTimes, 1); + memoized(1, 2, function (err) { + assert.isNull(err); + assert.strictEqual(loadTimes, 2); + done(); + }); + }); + }); +}); + diff --git a/node_modules/lru-memoizer/test/lru-memoizer.clone.test.js b/node_modules/lru-memoizer/test/lru-memoizer.clone.test.js new file mode 100644 index 0000000..9560eea --- /dev/null +++ b/node_modules/lru-memoizer/test/lru-memoizer.clone.test.js @@ -0,0 +1,44 @@ +const memoizer = require('./..'); +const assert = require('chai').assert; + +describe('lru-memoizer (clone)', () => { + let loadTimes = 0, memoized; + + beforeEach(() => { + loadTimes = 0; + + memoized = memoizer({ + load: (key, callback) => { + loadTimes++; + callback(null, { foo: key, buffer: Buffer.from('1234') }); + }, + hash: (key) => { + return key; + }, + clone: true + }); + }); + + it('should return a clone every time with the same cached structure', (done) => { + memoized('bar', (err, r1) => { + + assert.isNull(err); + assert.strictEqual(loadTimes, 1); + assert.equal(r1.foo, 'bar'); + r1.foo = 'bax'; + + memoized('bar', (err, r2) => { + assert.isNull(err); + + assert.strictEqual(loadTimes, 1); + assert.equal(r2.foo, 'bar'); + assert.notStrictEqual(r1, r2); + assert.notEqual(r1, r2); + + done(); + }); + }); + }); + +}); + diff --git a/node_modules/lru-memoizer/test/lru-memoizer.disable.test.js b/node_modules/lru-memoizer/test/lru-memoizer.disable.test.js new file mode 100644 index 0000000..e92630d --- /dev/null +++ b/node_modules/lru-memoizer/test/lru-memoizer.disable.test.js @@ -0,0 +1,49 @@ +const memoizer = require('./..'); +const assert = require('chai').assert; + +describe('lru-memoizer (disabled)', function () { + var loadTimes = 0, memoized; + + beforeEach(function () { + loadTimes = 0; + + memoized = memoizer({ + disable: true, + load: function (a, b, callback) { + loadTimes++; + return setTimeout(function () { + if (a === 0) { + return callback(new Error('a cant be 0')); + } + callback(null, a+b); + }, 10); + }, + hash: function (a, b) { + return a + '-' + b; + }, + max: 10 + }); + }); + + it('should call the load function every time', function (done) { + memoized(1,2, function (err, result) { + assert.isNull(err); + assert.strictEqual(result, 3); + assert.strictEqual(loadTimes, 1); + memoized(1,2, function (err, result) { + assert.isNull(err); + assert.strictEqual(result, 3); + assert.strictEqual(loadTimes, 2); + done(); + }); + }); + + }); + + + it('should expose hash function', function() { + assert.equal(memoized.hash(1, 2), '1-2'); + }); + +}); + diff --git a/node_modules/lru-memoizer/test/lru-memoizer.events.test.js b/node_modules/lru-memoizer/test/lru-memoizer.events.test.js new file mode 100644 index 0000000..b54defe --- /dev/null +++ b/node_modules/lru-memoizer/test/lru-memoizer.events.test.js @@ -0,0 +1,132 @@ +const memoizer = require('./..'); +const sinon = require('sinon'); + +describe('lru-memoizer (events)', function () { + let memoized; + let onMiss, onHit, onQueue; + + beforeEach(function () { + loadTimes = 0; + onMiss = sinon.stub(); + onHit = sinon.stub(); + onQueue = sinon.stub(); + memoized = memoizer({ + load: function (a, b, bypass, callback) { + return setTimeout(function () { + if (a === 0) { + return callback(new Error('a cant be 0')); + } + callback(null, a+b); + }, 10); + }, + hash: function (a, b) { + return a + '-' + b; + }, + bypass: function(a, b, bypass) { + return bypass; + }, + max: 10 + }); + memoized.on('hit', onHit); + memoized.on('miss', onMiss); + memoized.on('queue', onQueue); + }); + + describe('when the result is not in the cache', () => { + beforeEach((done) => { + memoized(1, 2, false, done); + }); + + it('should not call onHit', () => { + sinon.assert.notCalled(onHit); + }); + + it('should not call onQueue', () => { + sinon.assert.notCalled(onQueue); + }); + + it('should call onMiss with the load arguments', () => { + sinon.assert.calledOnce(onMiss); + sinon.assert.calledWith(onMiss, 1, 2, false); + }); + }); + + describe('when the result is in the cache', () => { + beforeEach((done) => { + memoized(1,2, false, () => { + onHit.reset(); + onMiss.reset(); + onQueue.reset(); + memoized(1, 2, false, done); + }); + }); + + it('should call onHit with the load arguments', () => { + sinon.assert.calledOnce(onHit); + sinon.assert.calledWith(onHit, 1, 2, false); + }); + + it('should not call onQueue', () => { + sinon.assert.notCalled(onQueue); + }); + + it('should not call onMiss', () => { + sinon.assert.notCalled(onQueue); + }); + }); + + describe('when the cache is by passed', () => { + beforeEach((done) => { + memoized(1,2, false, () => { + onHit.reset(); + onMiss.reset(); + onQueue.reset(); + memoized(1, 2, true, done); + }); + }); + + it('should not call onHit', () => { + sinon.assert.notCalled(onHit); + }); + + it('should not call onQueue', () => { + sinon.assert.notCalled(onQueue); + }); + + it('should call onMiss with the load arguments', () => { + sinon.assert.calledOnce(onMiss); + sinon.assert.calledWith(onMiss, 1, 2, true); + }); + }); + + describe('when the result is pending', () => { + beforeEach((done) => { + let pending = 2; + function onDone() { + pending -= 1; + if (pending === 0) { + done(); + } + } + memoized(1, 2, false, onDone); + onHit.reset(); + onMiss.reset(); + onQueue.reset(); + memoized(1, 2, false, onDone); + }); + + it('should not call onHit', () => { + sinon.assert.notCalled(onHit); + }); + + it('should call onQueue with the load arguments', () => { + sinon.assert.calledOnce(onQueue); + sinon.assert.calledWith(onQueue, 1, 2, false); + }); + + it('should not call onMiss', () => { + sinon.assert.notCalled(onMiss); + }); + }); +}); + diff --git a/node_modules/lru-memoizer/test/lru-memoizer.freeze.test.js b/node_modules/lru-memoizer/test/lru-memoizer.freeze.test.js new file mode 100644 index 0000000..7dd76d8 --- /dev/null +++ b/node_modules/lru-memoizer/test/lru-memoizer.freeze.test.js @@ -0,0 +1,43 @@ +const memoizer = require("./.."); +const assert = require("chai").assert; + +describe("lru-memoizer (freeze)", function () { + var loadTimes = 0, + memoized; + + beforeEach(function () { + loadTimes = 0; + + memoized = memoizer({ + load: function (key, callback) { + loadTimes++; + callback(null, { foo: "bar", buffer: Buffer.from("1234") }); + }, + hash: function (key) { + return key; + }, + freeze: true, + }); + }); + + it("should return a freeze every time with the same cached structure", function (done) { + memoized("test", function (err, r1) { + assert.isNull(err); + assert.strictEqual(loadTimes, 1); + assert.equal(r1.foo, "bar"); + r1.foo = "bax"; + assert.isFrozen(r1); + + memoized("test", function (err, r2) { + assert.isNull(err); + + assert.strictEqual(loadTimes, 1); + assert.equal(r2.foo, "bar"); + assert.strictEqual(r1, r2); + assert.isFrozen(r2); + + done(); + }); + }); + }); +}); diff --git a/node_modules/lru-memoizer/test/lru-memoizer.itemmaxage.test.js b/node_modules/lru-memoizer/test/lru-memoizer.itemmaxage.test.js new file mode 100644 index 0000000..4b5a3a2 --- /dev/null +++ b/node_modules/lru-memoizer/test/lru-memoizer.itemmaxage.test.js @@ -0,0 +1,204 @@ +var memoizer = require('./..'); +var assert = require('chai').assert; + +describe('lru-memoizer (itemMaxAge)', function () { + var loadTimes = 0, memoized; + + beforeEach(function () { + loadTimes = 0; + }); + + it('should use default behavior if not configured', function (done) { + memoized = memoizer({ + load: function (a, b, callback) { + loadTimes++; + setTimeout(function () { + callback(null, a + b); + }, 100); + }, + hash: function (a, b) { + return a + '-' + b; + }, + max: 10, + maxAge: 500 + }); + + memoized(1,2, function (err, result) { + assert.isNull(err); + assert.strictEqual(result, 3); + assert.strictEqual(loadTimes, 1); + + // Not expired yet. + setTimeout(function() { + memoized(1,2, function (err, result) { + assert.isNull(err); + assert.strictEqual(result, 3); + assert.strictEqual(loadTimes, 1); + + // Expired, load times will increase. + setTimeout(function() { + memoized(1,2, function (err, result) { + assert.isNull(err); + assert.strictEqual(result, 3); + assert.strictEqual(loadTimes, 2); + done(); + }); + }, 200); + }); + }, 400); + }); + }); + + it('should return all args and the result in the itemMaxAge function', function (done) { + var args; + memoized = memoizer({ + load: function (a, b, callback) { + loadTimes++; + setTimeout(function () { + callback(null, a + b); + }, 100); + }, + itemMaxAge: function (a, b, result) { + args = arguments; + return 1000; + }, + hash: function (a, b) { + return a + '-' + b; + }, + max: 10, + maxAge: 600 + }); + + memoized(1,2, function (err, result) { + assert.isNull(err); + assert.strictEqual(args[0], 1); + assert.strictEqual(args[1], 2); + assert.strictEqual(args[2], 3); + done(); + }); + }); + + it('should overwrite the default behavior if configured', function (done) { + var maxAge = 0; + var lastKey = null; + memoized = memoizer({ + load: function (a, b, callback) { + loadTimes++; + setTimeout(function () { + callback(null, a + b); + }, 100); + }, + itemMaxAge: function (a, b, result) { + lastKey = a + '-' + b; + // In this test, we set the maxAge of the current item to (result*100). + // If the result is 3, the max age of this item will be 300. + maxAge = result * 100; + return maxAge; + }, + hash: function (a, b) { + return a + '-' + b; + }, + max: 10, + maxAge: 600 + }); + + memoized(1,2, function (err, result) { + assert.isNull(err); + assert.strictEqual(maxAge, 300); + assert.strictEqual(lastKey, '1-2'); + assert.strictEqual(result, 3); + assert.strictEqual(loadTimes, 1); + + // Not expired yet after 200 ms, because the expiration is 300 + setTimeout(function() { + memoized(1,2, function (err, result) { + assert.isNull(err); + assert.strictEqual(maxAge, 300); + assert.strictEqual(lastKey, '1-2'); + assert.strictEqual(result, 3); + assert.strictEqual(loadTimes, 1); + + // Expired because now we are at 350 ms (even though gloabl expiration has been set to 600) + setTimeout(function() { + memoized(1,2, function (err, result) { + assert.isNull(err); + assert.strictEqual(maxAge, 300); + assert.strictEqual(lastKey, '1-2'); + assert.strictEqual(result, 3); + assert.strictEqual(loadTimes, 2); + + // Expired again, because 350ms have passed again. + setTimeout(function() { + memoized(1,2, function (err, result) { + assert.isNull(err); + assert.strictEqual(maxAge, 300); + assert.strictEqual(lastKey, '1-2'); + assert.strictEqual(result, 3); + assert.strictEqual(loadTimes, 3); + done(); + }); + }, 350); + }); + }, 150); + }); + }, 200); + }); + }); + + it('should overwrite the default behavior if configured (sync)', function (done) { + var maxAge = 0; + var lastKey = null; + memoized = memoizer.sync({ + load: function (a, b) { + loadTimes++; + return a + b; + }, + itemMaxAge: function (a, b, result) { + lastKey = a + '-' + b; + // In this test, we set the maxAge of the current item to (result*100). + // If the result is 3, the max age of this item will be 300. + maxAge = result * 100; + return maxAge; + }, + hash: function (a, b) { + return a + '-' + b; + }, + max: 10, + maxAge: 600 + }); + + var result = memoized(1, 2); + assert.strictEqual(maxAge, 300); + assert.strictEqual(lastKey, '1-2'); + assert.strictEqual(result, 3); + assert.strictEqual(loadTimes, 1); + + // Not expired yet after 200 ms, because the expiration is 300 + setTimeout(function() { + result = memoized(1, 2); + assert.strictEqual(maxAge, 300); + assert.strictEqual(lastKey, '1-2'); + assert.strictEqual(result, 3); + assert.strictEqual(loadTimes, 1); + + // Expired because now we are at 350 ms (even though gloabl expiration has been set to 600) + setTimeout(function() { + result = memoized(1,2); + assert.strictEqual(maxAge, 300); + assert.strictEqual(lastKey, '1-2'); + assert.strictEqual(result, 3); + assert.strictEqual(loadTimes, 2); + + // Expired again, because 350ms have passed again. + setTimeout(function() { + result = memoized(1,2); + assert.strictEqual(maxAge, 300); + assert.strictEqual(lastKey, '1-2'); + assert.strictEqual(result, 3); + assert.strictEqual(loadTimes, 3); + done(); + }, 350); + }, 150); + }, 200); + }); +}); diff --git a/node_modules/lru-memoizer/test/lru-memoizer.lock.test.js b/node_modules/lru-memoizer/test/lru-memoizer.lock.test.js new file mode 100644 index 0000000..bef0598 --- /dev/null +++ b/node_modules/lru-memoizer/test/lru-memoizer.lock.test.js @@ -0,0 +1,36 @@ +const memoizer = require('./..'); +const assert = require('chai').assert; +const _ = require('lodash'); + +describe('lru-simultaneos calls', function () { + var loadTimes = 0, memoized; + + beforeEach(function () { + loadTimes = 0; + + memoized = memoizer({ + load: function (a, b, callback) { + loadTimes++; + setTimeout(function () { + callback(null, a + b); + }, 100); + }, + hash: function (a, b) { + return a + '-' + b; + }, + max: 10 + }); + }); + + it('should call once', function (done) { + memoized(1, 2, _.noop); + memoized(1, 2, _.noop); + memoized(1, 2, function (err, result) { + if (err) { return done(err); } + assert.strictEqual(loadTimes, 1); + assert.strictEqual(result, 3); + done(); + }); + }); + +}); diff --git a/node_modules/lru-memoizer/test/lru-memoizer.nokey.test.js b/node_modules/lru-memoizer/test/lru-memoizer.nokey.test.js new file mode 100644 index 0000000..df478a9 --- /dev/null +++ b/node_modules/lru-memoizer/test/lru-memoizer.nokey.test.js @@ -0,0 +1,43 @@ +var memoizer = require('./..'); +var assert = require('chai').assert; + +describe('lru-memoizer (no key)', function () { + var loadTimes = 0, memoized; + + beforeEach(function () { + loadTimes = 0; + + memoized = memoizer({ + load: function (callback) { + loadTimes++; + return setTimeout(function () { + callback(null, loadTimes); + }, 10); + } + }); + }); + + it('should cache the result of an async function', function (done) { + memoized(function (err, result) { + assert.isNull(err); + assert.equal(result, 1); + assert.equal(loadTimes, 1); + memoized(function (err, result) { + assert.isNull(err); + assert.equal(result, 1); + assert.equal(loadTimes, 1); + done(); + }); + }); + + }); + + it('should use the hash function for keys', function (done) { + memoized(function () { + memoized(function () { + assert.includeMembers(memoized.keys(), ['_']); + done(); + }); + }); + }); +}); diff --git a/node_modules/lru-memoizer/test/lru-memoizer.queumaxage.test.js b/node_modules/lru-memoizer/test/lru-memoizer.queumaxage.test.js new file mode 100644 index 0000000..ab5c5fa --- /dev/null +++ b/node_modules/lru-memoizer/test/lru-memoizer.queumaxage.test.js @@ -0,0 +1,110 @@ +var memoizer = require('./..'); +var assert = require('chai').assert; + +describe('lru-memoizer (queueMaxAge)', function () { + var loadTimes = 0, memoized; + + beforeEach(function () { + loadTimes = 0; + }); + + function observer() { + const listeners = []; + return { + listen(listener) { + listeners.push(listener); + }, + trigger() { + listeners.forEach(listener => listener()); + } + } + } + + it('should create a new queue once expired', function (done) { + memoized = memoizer({ + load: function (a, b, onResolve, callback) { + loadTimes++; + onResolve(() => callback(null, a + b)); + }, + queueMaxAge: 10, + hash: function (a, b) { + return a + '-' + b; + } + }); + + const observer1 = observer(); + const observer2 = observer(); + const observer3 = observer(); + const resolved = []; + + memoized(1, 2, observer1.listen, function (err, result) { + assert.isNull(err); + assert.strictEqual(result, 3); + resolved.push('A'); + }); + + assert.strictEqual(loadTimes, 1); + + memoized(1, 2, assert.fail, function (err, result) { + assert.isNull(err); + assert.strictEqual(result, 3); + resolved.push('B'); + }); + + assert.strictEqual(loadTimes, 1); + + setTimeout(() => { + // previous queue expired, this calls will be added to a new queue. + memoized(1, 2, observer2.listen, function (err, result) { + assert.isNull(err); + assert.strictEqual(result, 3); + resolved.push('C'); + }); + + memoized(1, 2, assert.fail, function (err, result) { + assert.isNull(err); + assert.strictEqual(result, 3); + resolved.push('D'); + }); + + // only one new invocation to load + assert.strictEqual(loadTimes, 2); + + setTimeout(() => { + // second queue expired, this calls will be added to a third queue. + memoized(1, 2, observer3.listen, function (err, result) { + assert.isNull(err); + assert.strictEqual(result, 3); + resolved.push('E'); + }); + + memoized(1, 2, assert.fail.listen, function (err, result) { + assert.isNull(err); + assert.strictEqual(result, 3); + resolved.push('F'); + }); + + assert.strictEqual(loadTimes, 3); + + observer1.trigger(); + setImmediate(() => { + // first queue was resolved + assert.deepEqual(['A', 'B'], resolved); + + observer3.trigger(); + setImmediate(() => { + // third queue was resolved + assert.deepEqual(['A', 'B', 'E', 'F'], resolved); + + observer2.trigger(); + setImmediate(() => { + // second queue was resolved + assert.deepEqual(['A', 'B', 'E', 'F', 'C', 'D'], resolved); + done(); + }); + }); + }); + }, 100); + }, 100); + }); +}); diff --git a/node_modules/lru-memoizer/test/lru-memoizer.sync.clone.test.js b/node_modules/lru-memoizer/test/lru-memoizer.sync.clone.test.js new file mode 100644 index 0000000..252446c --- /dev/null +++ b/node_modules/lru-memoizer/test/lru-memoizer.sync.clone.test.js @@ -0,0 +1,76 @@ +const memoizer = require('./..'); +const assert = require('chai').assert; + +describe('lru-memoizer sync (clone)', () => { + + describe('call', () => { + let loadTimes = 0, memoized; + + beforeEach(() => { + loadTimes = 0; + + memoized = memoizer.sync({ + load: (key) => { + loadTimes++; + return { foo: key , buffer: Buffer.from('1234') }; + }, + hash: (key) => { + return key; + }, + clone: true + }); + }); + + it('should return a clone every time with the same cached structure', () => { + const r1 = memoized('bar'); + assert.strictEqual(loadTimes, 1); + assert.equal(r1.foo, 'bar'); + r1.foo = 'bax'; + + const r2 = memoized('bar'); + assert.strictEqual(loadTimes, 1); + assert.equal(r2.foo, 'bar'); + assert.notStrictEqual(r1, r2); + assert.notEqual(r1, r2); + }); + }); + + describe('Promise', () => { + let loadTimes = 0, memoized; + + beforeEach(() => { + loadTimes = 0; + + memoized = memoizer.sync({ + load: (key) => { + loadTimes++; + return Promise.resolve({ foo: key, buffer: Buffer.from('1234') }); + }, + hash: (key) => { + return key; + }, + clone: true + }); + }); + + it('should return a clone every time with the same cached structure', (done) => { + memoized('bar').then(r1 => { + assert.strictEqual(loadTimes, 1); + assert.equal(r1.foo, 'bar'); + r1.foo = 'bax'; + + memoized('bar').then(r2 => { + assert.strictEqual(loadTimes, 1); + assert.equal(r2.foo, 'bar'); + assert.notStrictEqual(r1, r2); + assert.notEqual(r1, r2); + + done(); + }); + }) + .catch(done); + }); + }); + +}); + diff --git a/node_modules/lru-memoizer/test/lru-memoizer.sync.events.test.js b/node_modules/lru-memoizer/test/lru-memoizer.sync.events.test.js new file mode 100644 index 0000000..717e89b --- /dev/null +++ b/node_modules/lru-memoizer/test/lru-memoizer.sync.events.test.js @@ -0,0 +1,95 @@ +const memoizer = require('./..'); +const sinon = require('sinon'); + +describe('lru-memoizer sync (events)', function () { + let memoized; + let onMiss, onHit, onQueue; + + beforeEach(function () { + loadTimes = 0; + onMiss = sinon.stub(); + onHit = sinon.stub(); + onQueue = sinon.stub(); + memoized = memoizer.sync({ + load: function (a, b, bypass) { + return a + b; + }, + hash: function (a, b, bypass) { + return a + '-' + b; + }, + bypass: function(a, b, bypass) { + return bypass; + }, + max: 10 + }); + memoized.on('hit', onHit); + memoized.on('miss', onMiss); + memoized.on('queue', onQueue); + }); + + describe('when the result is not in the cache', () => { + beforeEach(() => { + memoized(1, 2, false); + }); + + it('should not call onHit', () => { + sinon.assert.notCalled(onHit); + }); + + it('should not call onQueue', () => { + sinon.assert.notCalled(onQueue); + }); + + it('should call onMiss with the load arguments', () => { + sinon.assert.calledOnce(onMiss); + sinon.assert.calledWith(onMiss, 1, 2, false); + }); + }); + + describe('when the result is in the cache', () => { + beforeEach(() => { + memoized(1,2, false); + onHit.reset(); + onMiss.reset(); + onQueue.reset(); + memoized(1, 2, false); + }); + + it('should call onHit with the load arguments', () => { + sinon.assert.calledOnce(onHit); + sinon.assert.calledWith(onHit, 1, 2, false); + }); + + it('should not call onQueue', () => { + sinon.assert.notCalled(onQueue); + }); + + it('should not call onMiss', () => { + sinon.assert.notCalled(onQueue); + }); + }); + + describe('when the cache is by passed', () => { + beforeEach(() => { + memoized(1,2, false); + onHit.reset(); + onMiss.reset(); + onQueue.reset(); + memoized(1, 2, true); + }); + + it('should not call onHit', () => { + sinon.assert.notCalled(onHit); + }); + + it('should not call onQueue', () => { + sinon.assert.notCalled(onQueue); + }); + + it('should call onMiss with the load arguments', () => { + sinon.assert.calledOnce(onMiss); + sinon.assert.calledWith(onMiss, 1, 2, true); + }); + }); +}); + diff --git a/node_modules/lru-memoizer/test/lru-memoizer.sync.freeze.js b/node_modules/lru-memoizer/test/lru-memoizer.sync.freeze.js new file mode 100644 index 0000000..98f0ff9 --- /dev/null +++ b/node_modules/lru-memoizer/test/lru-memoizer.sync.freeze.js @@ -0,0 +1,74 @@ +const memoizer = require('./..'); +const assert = require('chai').assert; + +describe('lru-memoizer sync (freeze)', () => { + + describe('call', () => { + let loadTimes = 0, memoized; + + beforeEach(() => { + loadTimes = 0; + + memoized = memoizer.sync({ + load: (key) => { + loadTimes++; + return { foo: key , buffer: Buffer.from('1234') }; + }, + hash: (key) => { + return key; + }, + freeze: true + }); + }); + + it('should return a freeze every time with the same cached structure', () => { + const r1 = memoized('bar'); + assert.strictEqual(loadTimes, 1); + assert.equal(r1.foo, 'bar'); + assert.isFrozen(r1); + + const r2 = memoized('bar'); + assert.strictEqual(loadTimes, 1); + assert.equal(r2.foo, 'bar'); + assert.isFrozen(r2); + }); + }); + + describe('Promise', () => { + let loadTimes = 0, memoized; + + beforeEach(() => { + loadTimes = 0; + + memoized = memoizer.sync({ + load: (key) => { + loadTimes++; + return Promise.resolve({ foo: key, buffer: Buffer.from('1234') }); + }, + hash: (key) => { + return key; + }, + freeze: true + }); + }); + + it('should return a freeze every time with the same cached structure', (done) => { + memoized('bar').then(r1 => { + assert.strictEqual(loadTimes, 1); + assert.equal(r1.foo, 'bar'); + assert.isFrozen(r1); + + memoized('bar').then(r2 => { + assert.strictEqual(loadTimes, 1); + assert.equal(r2.foo, 'bar'); + assert.isFrozen(r2); + + done(); + }); + }) + .catch(done); + }); + }); + +}); + diff --git a/node_modules/lru-memoizer/test/lru-memoizer.sync.test.js b/node_modules/lru-memoizer/test/lru-memoizer.sync.test.js new file mode 100644 index 0000000..ece570a --- /dev/null +++ b/node_modules/lru-memoizer/test/lru-memoizer.sync.test.js @@ -0,0 +1,47 @@ +var memoizer = require('./..'); +var assert = require('chai').assert; + +describe('lru-memoizer sync', function () { + var loadTimes = 0, memoized; + + beforeEach(function () { + loadTimes = 0; + + memoized = memoizer.sync({ + load: function (a, b) { + loadTimes++; + if (a === 0) { + throw new Error('a cant be 0'); + } + return a + b; + }, + hash: function (a, b) { + return a + '-' + b; + }, + max: 10 + }); + }); + + it('should cache the result of an async function', function () { + var result = memoized(1, 2); + assert.equal(result, 3); + assert.equal(loadTimes, 1); + + var result2 = memoized(1,2); + assert.equal(result2, 3); + assert.equal(loadTimes, 1); + }); + + it('shuld use the hash function for keys', function () { + memoized(1, 2); + memoized(2, 3); + assert.includeMembers(memoized.keys(), ['1-2', '2-3']); + }); + + it('should not cache errored funcs', function () { + try { + memoized(0, 2); + } catch(err) {} + assert.notInclude(memoized.keys(), ['0-2']); + }); +}); \ No newline at end of file diff --git a/node_modules/lru-memoizer/test/lru-memoizer.test.js b/node_modules/lru-memoizer/test/lru-memoizer.test.js new file mode 100644 index 0000000..a9ece9a --- /dev/null +++ b/node_modules/lru-memoizer/test/lru-memoizer.test.js @@ -0,0 +1,88 @@ +var memoizer = require('./..'); +var assert = require('chai').assert; + +describe('lru-memoizer', function () { + var loadTimes = 0, memoized; + + beforeEach(function () { + loadTimes = 0; + + memoized = memoizer({ + load: function (a, b, callback) { + loadTimes++; + return setTimeout(function () { + if (a === 0) { + return callback(new Error('a cant be 0')); + } + callback(null, a+b); + }, 10); + }, + hash: function (a, b) { + return a + '-' + b; + }, + max: 10 + }); + }); + + it('should cache the result of an async function', function (done) { + memoized(1,2, function (err, result) { + assert.isNull(err); + assert.strictEqual(result, 3); + assert.strictEqual(loadTimes, 1); + memoized(1,2, function (err, result) { + assert.isNull(err); + assert.strictEqual(result, 3); + assert.strictEqual(loadTimes, 1); + done(); + }); + }); + + }); + + it('should use the hash function for keys', function (done) { + memoized(1, 2, function () { + memoized(2,3, function () { + assert.includeMembers(memoized.keys(), ['1-2', '2-3']); + done(); + }); + }); + }); + + it('should not cache errored funcs', function (done) { + memoized(0, 2, function (err) { + assert.isNotNull(err); + assert.notInclude(memoized.keys(), ['0-2']); + done(); + }); + }); + + it('should expose the hash function', function() { + assert.equal(memoized.hash(0, 2), '0-2'); + }); + + it('should expose the load function', function(done) { + memoized.load(1, 2, (err, result) => { + assert.equal(result, 3); + done(); + }); + }); + + it('should expose the max prop', function() { + assert.equal(memoized.max, 10); + }); + + it('should allow to del a key', function(done) { + memoized(1,2, () => { + assert.strictEqual(loadTimes, 1); + memoized.del(1,2); + memoized(1,2, (err, result) => { + assert.isNull(err); + assert.strictEqual(result, 3); + assert.strictEqual(loadTimes, 2); + done(); + }); + }); + }); + +}); + diff --git a/node_modules/lru-memoizer/tsconfig.json b/node_modules/lru-memoizer/tsconfig.json new file mode 100644 index 0000000..5fb8304 --- /dev/null +++ b/node_modules/lru-memoizer/tsconfig.json @@ -0,0 +1,59 @@ +{ + "compilerOptions": { + /* Basic Options */ + "target": "ES5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ + "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ + "lib": ["es2015", "es2017"], /* Specify library files to be included in the compilation. */ + // "allowJs": true, /* Allow javascript files to be compiled. */ + // "checkJs": true, /* Report errors in .js files. */ + // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ + "declaration": true, /* Generates corresponding '.d.ts' file. */ + // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ + // "sourceMap": true, /* Generates corresponding '.map' file. */ + // "outFile": "./", /* Concatenate and emit output to single file. */ + "outDir": "./lib", /* Redirect output structure to the directory. */ + // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ + // "composite": true, /* Enable project compilation */ + // "removeComments": true, /* Do not emit comments to output. */ + // "noEmit": true, /* Do not emit outputs. */ + // "importHelpers": true, /* Import emit helpers from 'tslib'. */ + "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ + // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ + + /* Strict Type-Checking Options */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ + "strictNullChecks": false, /* Enable strict null checks. */ + // "strictFunctionTypes": true, /* Enable strict checking of function types. */ + // "strictPropertyInitialization": false, /* Enable strict checking of property initialization in classes. */ + // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ + // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ + + /* Additional Checks */ + // "noUnusedLocals": true, /* Report errors on unused locals. */ + // "noUnusedParameters": true, /* Report errors on unused parameters. */ + // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + + /* Module Resolution Options */ + // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ + // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ + // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ + // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ + // "typeRoots": [], /* List of folders to include type definitions from. */ + // "types": [], /* Type declaration files to be included in compilation. */ + // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ + "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ + // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + + /* Source Map Options */ + // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ + // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ + + /* Experimental Options */ + // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ + // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + } +} diff --git a/node_modules/math-intrinsics/.eslintrc b/node_modules/math-intrinsics/.eslintrc new file mode 100644 index 0000000..d90a1bc --- /dev/null +++ b/node_modules/math-intrinsics/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "eqeqeq": ["error", "allow-null"], + "id-length": "off", + "new-cap": ["error", { + "capIsNewExceptions": [ + "RequireObjectCoercible", + "ToObject", + ], + }], + }, +} diff --git a/node_modules/math-intrinsics/.github/FUNDING.yml b/node_modules/math-intrinsics/.github/FUNDING.yml new file mode 100644 index 0000000..868f4ff --- /dev/null +++ b/node_modules/math-intrinsics/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/math-intrinsics +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/math-intrinsics/CHANGELOG.md b/node_modules/math-intrinsics/CHANGELOG.md new file mode 100644 index 0000000..9cf48f5 --- /dev/null +++ b/node_modules/math-intrinsics/CHANGELOG.md @@ -0,0 +1,24 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.0](https://github.com/es-shims/math-intrinsics/compare/v1.0.0...v1.1.0) - 2024-12-18 + +### Commits + +- [New] add `round` [`7cfb044`](https://github.com/es-shims/math-intrinsics/commit/7cfb04460c0fbdf1ca101eecbac3f59d11994130) +- [Tests] add attw [`e96be8f`](https://github.com/es-shims/math-intrinsics/commit/e96be8fbf58449eafe976446a0470e6ea561ad8d) +- [Dev Deps] update `@types/tape` [`30d0023`](https://github.com/es-shims/math-intrinsics/commit/30d00234ce8a3fa0094a61cd55d6686eb91e36ec) + +## v1.0.0 - 2024-12-11 + +### Commits + +- Initial implementation, tests, readme, types [`b898caa`](https://github.com/es-shims/math-intrinsics/commit/b898caae94e9994a94a42b8740f7bbcfd0a868fe) +- Initial commit [`02745b0`](https://github.com/es-shims/math-intrinsics/commit/02745b03a62255af8a332771987b55d127538d9c) +- [New] add `constants/maxArrayLength`, `mod` [`b978178`](https://github.com/es-shims/math-intrinsics/commit/b978178a57685bd23ed1c7efe2137f3784f5fcc5) +- npm init [`a39fc57`](https://github.com/es-shims/math-intrinsics/commit/a39fc57e5639a645d0bd52a0dc56202480223be2) +- Only apps should have lockfiles [`9451580`](https://github.com/es-shims/math-intrinsics/commit/94515800fb34db4f3cc7e99290042d45609ac7bd) diff --git a/node_modules/math-intrinsics/LICENSE b/node_modules/math-intrinsics/LICENSE new file mode 100644 index 0000000..34995e7 --- /dev/null +++ b/node_modules/math-intrinsics/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 ECMAScript Shims + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/math-intrinsics/README.md b/node_modules/math-intrinsics/README.md new file mode 100644 index 0000000..4a66dcf --- /dev/null +++ b/node_modules/math-intrinsics/README.md @@ -0,0 +1,50 @@ +# math-intrinsics [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +ES Math-related intrinsics and helpers, robustly cached. + + - `abs` + - `floor` + - `isFinite` + - `isInteger` + - `isNaN` + - `isNegativeZero` + - `max` + - `min` + - `mod` + - `pow` + - `round` + - `sign` + - `constants/maxArrayLength` + - `constants/maxSafeInteger` + - `constants/maxValue` + + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/math-intrinsics +[npm-version-svg]: https://versionbadg.es/es-shims/math-intrinsics.svg +[deps-svg]: https://david-dm.org/es-shims/math-intrinsics.svg +[deps-url]: https://david-dm.org/es-shims/math-intrinsics +[dev-deps-svg]: https://david-dm.org/es-shims/math-intrinsics/dev-status.svg +[dev-deps-url]: https://david-dm.org/es-shims/math-intrinsics#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/math-intrinsics.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/math-intrinsics.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/es-object.svg +[downloads-url]: https://npm-stat.com/charts.html?package=math-intrinsics +[codecov-image]: https://codecov.io/gh/es-shims/math-intrinsics/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/es-shims/math-intrinsics/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/es-shims/math-intrinsics +[actions-url]: https://github.com/es-shims/math-intrinsics/actions diff --git a/node_modules/math-intrinsics/abs.d.ts b/node_modules/math-intrinsics/abs.d.ts new file mode 100644 index 0000000..14ad9c6 --- /dev/null +++ b/node_modules/math-intrinsics/abs.d.ts @@ -0,0 +1 @@ +export = Math.abs; \ No newline at end of file diff --git a/node_modules/math-intrinsics/abs.js b/node_modules/math-intrinsics/abs.js new file mode 100644 index 0000000..a751424 --- /dev/null +++ b/node_modules/math-intrinsics/abs.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./abs')} */ +module.exports = Math.abs; diff --git a/node_modules/math-intrinsics/constants/maxArrayLength.d.ts b/node_modules/math-intrinsics/constants/maxArrayLength.d.ts new file mode 100644 index 0000000..b92d46b --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxArrayLength.d.ts @@ -0,0 +1,3 @@ +declare const MAX_ARRAY_LENGTH: 4294967295; + +export = MAX_ARRAY_LENGTH; \ No newline at end of file diff --git a/node_modules/math-intrinsics/constants/maxArrayLength.js b/node_modules/math-intrinsics/constants/maxArrayLength.js new file mode 100644 index 0000000..cfc6aff --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxArrayLength.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./maxArrayLength')} */ +module.exports = 4294967295; // Math.pow(2, 32) - 1; diff --git a/node_modules/math-intrinsics/constants/maxSafeInteger.d.ts b/node_modules/math-intrinsics/constants/maxSafeInteger.d.ts new file mode 100644 index 0000000..fee3f62 --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxSafeInteger.d.ts @@ -0,0 +1,3 @@ +declare const MAX_SAFE_INTEGER: 9007199254740991; + +export = MAX_SAFE_INTEGER; \ No newline at end of file diff --git a/node_modules/math-intrinsics/constants/maxSafeInteger.js b/node_modules/math-intrinsics/constants/maxSafeInteger.js new file mode 100644 index 0000000..b568ad3 --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxSafeInteger.js @@ -0,0 +1,5 @@ +'use strict'; + +/** @type {import('./maxSafeInteger')} */ +// eslint-disable-next-line no-extra-parens +module.exports = /** @type {import('./maxSafeInteger')} */ (Number.MAX_SAFE_INTEGER) || 9007199254740991; // Math.pow(2, 53) - 1; diff --git a/node_modules/math-intrinsics/constants/maxValue.d.ts b/node_modules/math-intrinsics/constants/maxValue.d.ts new file mode 100644 index 0000000..292cb82 --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxValue.d.ts @@ -0,0 +1,3 @@ +declare const MAX_VALUE: 1.7976931348623157e+308; + +export = MAX_VALUE; diff --git a/node_modules/math-intrinsics/constants/maxValue.js b/node_modules/math-intrinsics/constants/maxValue.js new file mode 100644 index 0000000..a2202dc --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxValue.js @@ -0,0 +1,5 @@ +'use strict'; + +/** @type {import('./maxValue')} */ +// eslint-disable-next-line no-extra-parens +module.exports = /** @type {import('./maxValue')} */ (Number.MAX_VALUE) || 1.7976931348623157e+308; diff --git a/node_modules/math-intrinsics/floor.d.ts b/node_modules/math-intrinsics/floor.d.ts new file mode 100644 index 0000000..9265236 --- /dev/null +++ b/node_modules/math-intrinsics/floor.d.ts @@ -0,0 +1 @@ +export = Math.floor; \ No newline at end of file diff --git a/node_modules/math-intrinsics/floor.js b/node_modules/math-intrinsics/floor.js new file mode 100644 index 0000000..ab0e5d7 --- /dev/null +++ b/node_modules/math-intrinsics/floor.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./floor')} */ +module.exports = Math.floor; diff --git a/node_modules/math-intrinsics/isFinite.d.ts b/node_modules/math-intrinsics/isFinite.d.ts new file mode 100644 index 0000000..6daae33 --- /dev/null +++ b/node_modules/math-intrinsics/isFinite.d.ts @@ -0,0 +1,3 @@ +declare function isFinite(x: unknown): x is number | bigint; + +export = isFinite; \ No newline at end of file diff --git a/node_modules/math-intrinsics/isFinite.js b/node_modules/math-intrinsics/isFinite.js new file mode 100644 index 0000000..b201a5a --- /dev/null +++ b/node_modules/math-intrinsics/isFinite.js @@ -0,0 +1,12 @@ +'use strict'; + +var $isNaN = require('./isNaN'); + +/** @type {import('./isFinite')} */ +module.exports = function isFinite(x) { + return (typeof x === 'number' || typeof x === 'bigint') + && !$isNaN(x) + && x !== Infinity + && x !== -Infinity; +}; + diff --git a/node_modules/math-intrinsics/isInteger.d.ts b/node_modules/math-intrinsics/isInteger.d.ts new file mode 100644 index 0000000..13935a8 --- /dev/null +++ b/node_modules/math-intrinsics/isInteger.d.ts @@ -0,0 +1,3 @@ +declare function isInteger(argument: unknown): argument is number; + +export = isInteger; \ No newline at end of file diff --git a/node_modules/math-intrinsics/isInteger.js b/node_modules/math-intrinsics/isInteger.js new file mode 100644 index 0000000..4b1b9a5 --- /dev/null +++ b/node_modules/math-intrinsics/isInteger.js @@ -0,0 +1,16 @@ +'use strict'; + +var $abs = require('./abs'); +var $floor = require('./floor'); + +var $isNaN = require('./isNaN'); +var $isFinite = require('./isFinite'); + +/** @type {import('./isInteger')} */ +module.exports = function isInteger(argument) { + if (typeof argument !== 'number' || $isNaN(argument) || !$isFinite(argument)) { + return false; + } + var absValue = $abs(argument); + return $floor(absValue) === absValue; +}; diff --git a/node_modules/math-intrinsics/isNaN.d.ts b/node_modules/math-intrinsics/isNaN.d.ts new file mode 100644 index 0000000..c1d4c55 --- /dev/null +++ b/node_modules/math-intrinsics/isNaN.d.ts @@ -0,0 +1 @@ +export = Number.isNaN; \ No newline at end of file diff --git a/node_modules/math-intrinsics/isNaN.js b/node_modules/math-intrinsics/isNaN.js new file mode 100644 index 0000000..e36475c --- /dev/null +++ b/node_modules/math-intrinsics/isNaN.js @@ -0,0 +1,6 @@ +'use strict'; + +/** @type {import('./isNaN')} */ +module.exports = Number.isNaN || function isNaN(a) { + return a !== a; +}; diff --git a/node_modules/math-intrinsics/isNegativeZero.d.ts b/node_modules/math-intrinsics/isNegativeZero.d.ts new file mode 100644 index 0000000..7ad8819 --- /dev/null +++ b/node_modules/math-intrinsics/isNegativeZero.d.ts @@ -0,0 +1,3 @@ +declare function isNegativeZero(x: unknown): boolean; + +export = isNegativeZero; \ No newline at end of file diff --git a/node_modules/math-intrinsics/isNegativeZero.js b/node_modules/math-intrinsics/isNegativeZero.js new file mode 100644 index 0000000..b69adcc --- /dev/null +++ b/node_modules/math-intrinsics/isNegativeZero.js @@ -0,0 +1,6 @@ +'use strict'; + +/** @type {import('./isNegativeZero')} */ +module.exports = function isNegativeZero(x) { + return x === 0 && 1 / x === 1 / -0; +}; diff --git a/node_modules/math-intrinsics/max.d.ts b/node_modules/math-intrinsics/max.d.ts new file mode 100644 index 0000000..ad6f43e --- /dev/null +++ b/node_modules/math-intrinsics/max.d.ts @@ -0,0 +1 @@ +export = Math.max; \ No newline at end of file diff --git a/node_modules/math-intrinsics/max.js b/node_modules/math-intrinsics/max.js new file mode 100644 index 0000000..edb55df --- /dev/null +++ b/node_modules/math-intrinsics/max.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./max')} */ +module.exports = Math.max; diff --git a/node_modules/math-intrinsics/min.d.ts b/node_modules/math-intrinsics/min.d.ts new file mode 100644 index 0000000..fd90f2d --- /dev/null +++ b/node_modules/math-intrinsics/min.d.ts @@ -0,0 +1 @@ +export = Math.min; \ No newline at end of file diff --git a/node_modules/math-intrinsics/min.js b/node_modules/math-intrinsics/min.js new file mode 100644 index 0000000..5a4a7c7 --- /dev/null +++ b/node_modules/math-intrinsics/min.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./min')} */ +module.exports = Math.min; diff --git a/node_modules/math-intrinsics/mod.d.ts b/node_modules/math-intrinsics/mod.d.ts new file mode 100644 index 0000000..549dbd4 --- /dev/null +++ b/node_modules/math-intrinsics/mod.d.ts @@ -0,0 +1,3 @@ +declare function mod(number: number, modulo: number): number; + +export = mod; \ No newline at end of file diff --git a/node_modules/math-intrinsics/mod.js b/node_modules/math-intrinsics/mod.js new file mode 100644 index 0000000..4a98362 --- /dev/null +++ b/node_modules/math-intrinsics/mod.js @@ -0,0 +1,9 @@ +'use strict'; + +var $floor = require('./floor'); + +/** @type {import('./mod')} */ +module.exports = function mod(number, modulo) { + var remain = number % modulo; + return $floor(remain >= 0 ? remain : remain + modulo); +}; diff --git a/node_modules/math-intrinsics/package.json b/node_modules/math-intrinsics/package.json new file mode 100644 index 0000000..0676273 --- /dev/null +++ b/node_modules/math-intrinsics/package.json @@ -0,0 +1,86 @@ +{ + "name": "math-intrinsics", + "version": "1.1.0", + "description": "ES Math-related intrinsics and helpers, robustly cached.", + "main": false, + "exports": { + "./abs": "./abs.js", + "./floor": "./floor.js", + "./isFinite": "./isFinite.js", + "./isInteger": "./isInteger.js", + "./isNaN": "./isNaN.js", + "./isNegativeZero": "./isNegativeZero.js", + "./max": "./max.js", + "./min": "./min.js", + "./mod": "./mod.js", + "./pow": "./pow.js", + "./sign": "./sign.js", + "./round": "./round.js", + "./constants/maxArrayLength": "./constants/maxArrayLength.js", + "./constants/maxSafeInteger": "./constants/maxSafeInteger.js", + "./constants/maxValue": "./constants/maxValue.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'", + "posttest": "npx npm@'>= 10.2' audit --production", + "prelint": "evalmd README.md && eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git' | grep -v dist/)", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc && attw -P", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/es-shims/math-intrinsics.git" + }, + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/es-shims/math-intrinsics/issues" + }, + "homepage": "https://github.com/es-shims/math-intrinsics#readme", + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.1", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/for-each": "^0.3.3", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.8.0", + "auto-changelog": "^2.5.0", + "eclint": "^2.8.1", + "es-value-fixtures": "^1.5.0", + "eslint": "^8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.3", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/math-intrinsics/pow.d.ts b/node_modules/math-intrinsics/pow.d.ts new file mode 100644 index 0000000..5873c44 --- /dev/null +++ b/node_modules/math-intrinsics/pow.d.ts @@ -0,0 +1 @@ +export = Math.pow; \ No newline at end of file diff --git a/node_modules/math-intrinsics/pow.js b/node_modules/math-intrinsics/pow.js new file mode 100644 index 0000000..c0a4103 --- /dev/null +++ b/node_modules/math-intrinsics/pow.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./pow')} */ +module.exports = Math.pow; diff --git a/node_modules/math-intrinsics/round.d.ts b/node_modules/math-intrinsics/round.d.ts new file mode 100644 index 0000000..da1fde3 --- /dev/null +++ b/node_modules/math-intrinsics/round.d.ts @@ -0,0 +1 @@ +export = Math.round; \ No newline at end of file diff --git a/node_modules/math-intrinsics/round.js b/node_modules/math-intrinsics/round.js new file mode 100644 index 0000000..b792156 --- /dev/null +++ b/node_modules/math-intrinsics/round.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./round')} */ +module.exports = Math.round; diff --git a/node_modules/math-intrinsics/sign.d.ts b/node_modules/math-intrinsics/sign.d.ts new file mode 100644 index 0000000..c49ceca --- /dev/null +++ b/node_modules/math-intrinsics/sign.d.ts @@ -0,0 +1,3 @@ +declare function sign(x: number): number; + +export = sign; \ No newline at end of file diff --git a/node_modules/math-intrinsics/sign.js b/node_modules/math-intrinsics/sign.js new file mode 100644 index 0000000..9e5173c --- /dev/null +++ b/node_modules/math-intrinsics/sign.js @@ -0,0 +1,11 @@ +'use strict'; + +var $isNaN = require('./isNaN'); + +/** @type {import('./sign')} */ +module.exports = function sign(number) { + if ($isNaN(number) || number === 0) { + return number; + } + return number < 0 ? -1 : +1; +}; diff --git a/node_modules/math-intrinsics/test/index.js b/node_modules/math-intrinsics/test/index.js new file mode 100644 index 0000000..0f90a5d --- /dev/null +++ b/node_modules/math-intrinsics/test/index.js @@ -0,0 +1,192 @@ +'use strict'; + +var test = require('tape'); +var v = require('es-value-fixtures'); +var forEach = require('for-each'); +var inspect = require('object-inspect'); + +var abs = require('../abs'); +var floor = require('../floor'); +var isFinite = require('../isFinite'); +var isInteger = require('../isInteger'); +var isNaN = require('../isNaN'); +var isNegativeZero = require('../isNegativeZero'); +var max = require('../max'); +var min = require('../min'); +var mod = require('../mod'); +var pow = require('../pow'); +var round = require('../round'); +var sign = require('../sign'); + +var maxArrayLength = require('../constants/maxArrayLength'); +var maxSafeInteger = require('../constants/maxSafeInteger'); +var maxValue = require('../constants/maxValue'); + +test('abs', function (t) { + t.equal(abs(-1), 1, 'abs(-1) === 1'); + t.equal(abs(+1), 1, 'abs(+1) === 1'); + t.equal(abs(+0), +0, 'abs(+0) === +0'); + t.equal(abs(-0), +0, 'abs(-0) === +0'); + + t.end(); +}); + +test('floor', function (t) { + t.equal(floor(-1.1), -2, 'floor(-1.1) === -2'); + t.equal(floor(+1.1), 1, 'floor(+1.1) === 1'); + t.equal(floor(+0), +0, 'floor(+0) === +0'); + t.equal(floor(-0), -0, 'floor(-0) === -0'); + t.equal(floor(-Infinity), -Infinity, 'floor(-Infinity) === -Infinity'); + t.equal(floor(Number(Infinity)), Number(Infinity), 'floor(+Infinity) === +Infinity'); + t.equal(floor(NaN), NaN, 'floor(NaN) === NaN'); + t.equal(floor(0), +0, 'floor(0) === +0'); + t.equal(floor(-0), -0, 'floor(-0) === -0'); + t.equal(floor(1), 1, 'floor(1) === 1'); + t.equal(floor(-1), -1, 'floor(-1) === -1'); + t.equal(floor(1.1), 1, 'floor(1.1) === 1'); + t.equal(floor(-1.1), -2, 'floor(-1.1) === -2'); + t.equal(floor(maxValue), maxValue, 'floor(maxValue) === maxValue'); + t.equal(floor(maxSafeInteger), maxSafeInteger, 'floor(maxSafeInteger) === maxSafeInteger'); + + t.end(); +}); + +test('isFinite', function (t) { + t.equal(isFinite(0), true, 'isFinite(+0) === true'); + t.equal(isFinite(-0), true, 'isFinite(-0) === true'); + t.equal(isFinite(1), true, 'isFinite(1) === true'); + t.equal(isFinite(Infinity), false, 'isFinite(Infinity) === false'); + t.equal(isFinite(-Infinity), false, 'isFinite(-Infinity) === false'); + t.equal(isFinite(NaN), false, 'isFinite(NaN) === false'); + + forEach(v.nonNumbers, function (nonNumber) { + t.equal(isFinite(nonNumber), false, 'isFinite(' + inspect(nonNumber) + ') === false'); + }); + + t.end(); +}); + +test('isInteger', function (t) { + forEach([].concat( + // @ts-expect-error TS sucks with concat + v.nonNumbers, + v.nonIntegerNumbers + ), function (nonInteger) { + t.equal(isInteger(nonInteger), false, 'isInteger(' + inspect(nonInteger) + ') === false'); + }); + + t.end(); +}); + +test('isNaN', function (t) { + forEach([].concat( + // @ts-expect-error TS sucks with concat + v.nonNumbers, + v.infinities, + v.zeroes, + v.integerNumbers + ), function (nonNaN) { + t.equal(isNaN(nonNaN), false, 'isNaN(' + inspect(nonNaN) + ') === false'); + }); + + t.equal(isNaN(NaN), true, 'isNaN(NaN) === true'); + + t.end(); +}); + +test('isNegativeZero', function (t) { + t.equal(isNegativeZero(-0), true, 'isNegativeZero(-0) === true'); + t.equal(isNegativeZero(+0), false, 'isNegativeZero(+0) === false'); + t.equal(isNegativeZero(1), false, 'isNegativeZero(1) === false'); + t.equal(isNegativeZero(-1), false, 'isNegativeZero(-1) === false'); + t.equal(isNegativeZero(NaN), false, 'isNegativeZero(NaN) === false'); + t.equal(isNegativeZero(Infinity), false, 'isNegativeZero(Infinity) === false'); + t.equal(isNegativeZero(-Infinity), false, 'isNegativeZero(-Infinity) === false'); + + forEach(v.nonNumbers, function (nonNumber) { + t.equal(isNegativeZero(nonNumber), false, 'isNegativeZero(' + inspect(nonNumber) + ') === false'); + }); + + t.end(); +}); + +test('max', function (t) { + t.equal(max(1, 2), 2, 'max(1, 2) === 2'); + t.equal(max(1, 2, 3), 3, 'max(1, 2, 3) === 3'); + t.equal(max(1, 2, 3, 4), 4, 'max(1, 2, 3, 4) === 4'); + t.equal(max(1, 2, 3, 4, 5), 5, 'max(1, 2, 3, 4, 5) === 5'); + t.equal(max(1, 2, 3, 4, 5, 6), 6, 'max(1, 2, 3, 4, 5, 6) === 6'); + t.equal(max(1, 2, 3, 4, 5, 6, 7), 7, 'max(1, 2, 3, 4, 5, 6, 7) === 7'); + + t.end(); +}); + +test('min', function (t) { + t.equal(min(1, 2), 1, 'min(1, 2) === 1'); + t.equal(min(1, 2, 3), 1, 'min(1, 2, 3) === 1'); + t.equal(min(1, 2, 3, 4), 1, 'min(1, 2, 3, 4) === 1'); + t.equal(min(1, 2, 3, 4, 5), 1, 'min(1, 2, 3, 4, 5) === 1'); + t.equal(min(1, 2, 3, 4, 5, 6), 1, 'min(1, 2, 3, 4, 5, 6) === 1'); + + t.end(); +}); + +test('mod', function (t) { + t.equal(mod(1, 2), 1, 'mod(1, 2) === 1'); + t.equal(mod(2, 2), 0, 'mod(2, 2) === 0'); + t.equal(mod(3, 2), 1, 'mod(3, 2) === 1'); + t.equal(mod(4, 2), 0, 'mod(4, 2) === 0'); + t.equal(mod(5, 2), 1, 'mod(5, 2) === 1'); + t.equal(mod(6, 2), 0, 'mod(6, 2) === 0'); + t.equal(mod(7, 2), 1, 'mod(7, 2) === 1'); + t.equal(mod(8, 2), 0, 'mod(8, 2) === 0'); + t.equal(mod(9, 2), 1, 'mod(9, 2) === 1'); + t.equal(mod(10, 2), 0, 'mod(10, 2) === 0'); + t.equal(mod(11, 2), 1, 'mod(11, 2) === 1'); + + t.end(); +}); + +test('pow', function (t) { + t.equal(pow(2, 2), 4, 'pow(2, 2) === 4'); + t.equal(pow(2, 3), 8, 'pow(2, 3) === 8'); + t.equal(pow(2, 4), 16, 'pow(2, 4) === 16'); + t.equal(pow(2, 5), 32, 'pow(2, 5) === 32'); + t.equal(pow(2, 6), 64, 'pow(2, 6) === 64'); + t.equal(pow(2, 7), 128, 'pow(2, 7) === 128'); + t.equal(pow(2, 8), 256, 'pow(2, 8) === 256'); + t.equal(pow(2, 9), 512, 'pow(2, 9) === 512'); + t.equal(pow(2, 10), 1024, 'pow(2, 10) === 1024'); + + t.end(); +}); + +test('round', function (t) { + t.equal(round(1.1), 1, 'round(1.1) === 1'); + t.equal(round(1.5), 2, 'round(1.5) === 2'); + t.equal(round(1.9), 2, 'round(1.9) === 2'); + + t.end(); +}); + +test('sign', function (t) { + t.equal(sign(-1), -1, 'sign(-1) === -1'); + t.equal(sign(+1), +1, 'sign(+1) === +1'); + t.equal(sign(+0), +0, 'sign(+0) === +0'); + t.equal(sign(-0), -0, 'sign(-0) === -0'); + t.equal(sign(NaN), NaN, 'sign(NaN) === NaN'); + t.equal(sign(Infinity), +1, 'sign(Infinity) === +1'); + t.equal(sign(-Infinity), -1, 'sign(-Infinity) === -1'); + t.equal(sign(maxValue), +1, 'sign(maxValue) === +1'); + t.equal(sign(maxSafeInteger), +1, 'sign(maxSafeInteger) === +1'); + + t.end(); +}); + +test('constants', function (t) { + t.equal(typeof maxArrayLength, 'number', 'typeof maxArrayLength === "number"'); + t.equal(typeof maxSafeInteger, 'number', 'typeof maxSafeInteger === "number"'); + t.equal(typeof maxValue, 'number', 'typeof maxValue === "number"'); + + t.end(); +}); diff --git a/node_modules/math-intrinsics/tsconfig.json b/node_modules/math-intrinsics/tsconfig.json new file mode 100644 index 0000000..b131000 --- /dev/null +++ b/node_modules/math-intrinsics/tsconfig.json @@ -0,0 +1,3 @@ +{ + "extends": "@ljharb/tsconfig", +} diff --git a/node_modules/mime-db/HISTORY.md b/node_modules/mime-db/HISTORY.md new file mode 100644 index 0000000..7436f64 --- /dev/null +++ b/node_modules/mime-db/HISTORY.md @@ -0,0 +1,507 @@ +1.52.0 / 2022-02-21 +=================== + + * Add extensions from IANA for more `image/*` types + * Add extension `.asc` to `application/pgp-keys` + * Add extensions to various XML types + * Add new upstream MIME types + +1.51.0 / 2021-11-08 +=================== + + * Add new upstream MIME types + * Mark `image/vnd.microsoft.icon` as compressible + * Mark `image/vnd.ms-dds` as compressible + +1.50.0 / 2021-09-15 +=================== + + * Add deprecated iWorks mime types and extensions + * Add new upstream MIME types + +1.49.0 / 2021-07-26 +=================== + + * Add extension `.trig` to `application/trig` + * Add new upstream MIME types + +1.48.0 / 2021-05-30 +=================== + + * Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + * Add new upstream MIME types + * Mark `text/yaml` as compressible + +1.47.0 / 2021-04-01 +=================== + + * Add new upstream MIME types + * Remove ambigious extensions from IANA for `application/*+xml` types + * Update primary extension to `.es` for `application/ecmascript` + +1.46.0 / 2021-02-13 +=================== + + * Add extension `.amr` to `audio/amr` + * Add extension `.m4s` to `video/iso.segment` + * Add extension `.opus` to `audio/ogg` + * Add new upstream MIME types + +1.45.0 / 2020-09-22 +=================== + + * Add `application/ubjson` with extension `.ubj` + * Add `image/avif` with extension `.avif` + * Add `image/ktx2` with extension `.ktx2` + * Add extension `.dbf` to `application/vnd.dbf` + * Add extension `.rar` to `application/vnd.rar` + * Add extension `.td` to `application/urc-targetdesc+xml` + * Add new upstream MIME types + * Fix extension of `application/vnd.apple.keynote` to be `.key` + +1.44.0 / 2020-04-22 +=================== + + * Add charsets from IANA + * Add extension `.cjs` to `application/node` + * Add new upstream MIME types + +1.43.0 / 2020-01-05 +=================== + + * Add `application/x-keepass2` with extension `.kdbx` + * Add extension `.mxmf` to `audio/mobile-xmf` + * Add extensions from IANA for `application/*+xml` types + * Add new upstream MIME types + +1.42.0 / 2019-09-25 +=================== + + * Add `image/vnd.ms-dds` with extension `.dds` + * Add new upstream MIME types + * Remove compressible from `multipart/mixed` + +1.41.0 / 2019-08-30 +=================== + + * Add new upstream MIME types + * Add `application/toml` with extension `.toml` + * Mark `font/ttf` as compressible + +1.40.0 / 2019-04-20 +=================== + + * Add extensions from IANA for `model/*` types + * Add `text/mdx` with extension `.mdx` + +1.39.0 / 2019-04-04 +=================== + + * Add extensions `.siv` and `.sieve` to `application/sieve` + * Add new upstream MIME types + +1.38.0 / 2019-02-04 +=================== + + * Add extension `.nq` to `application/n-quads` + * Add extension `.nt` to `application/n-triples` + * Add new upstream MIME types + * Mark `text/less` as compressible + +1.37.0 / 2018-10-19 +=================== + + * Add extensions to HEIC image types + * Add new upstream MIME types + +1.36.0 / 2018-08-20 +=================== + + * Add Apple file extensions from IANA + * Add extensions from IANA for `image/*` types + * Add new upstream MIME types + +1.35.0 / 2018-07-15 +=================== + + * Add extension `.owl` to `application/rdf+xml` + * Add new upstream MIME types + - Removes extension `.woff` from `application/font-woff` + +1.34.0 / 2018-06-03 +=================== + + * Add extension `.csl` to `application/vnd.citationstyles.style+xml` + * Add extension `.es` to `application/ecmascript` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/turtle` + * Mark all XML-derived types as compressible + +1.33.0 / 2018-02-15 +=================== + + * Add extensions from IANA for `message/*` types + * Add new upstream MIME types + * Fix some incorrect OOXML types + * Remove `application/font-woff2` + +1.32.0 / 2017-11-29 +=================== + + * Add new upstream MIME types + * Update `text/hjson` to registered `application/hjson` + * Add `text/shex` with extension `.shex` + +1.31.0 / 2017-10-25 +=================== + + * Add `application/raml+yaml` with extension `.raml` + * Add `application/wasm` with extension `.wasm` + * Add new `font` type from IANA + * Add new upstream font extensions + * Add new upstream MIME types + * Add extensions for JPEG-2000 images + +1.30.0 / 2017-08-27 +=================== + + * Add `application/vnd.ms-outlook` + * Add `application/x-arj` + * Add extension `.mjs` to `application/javascript` + * Add glTF types and extensions + * Add new upstream MIME types + * Add `text/x-org` + * Add VirtualBox MIME types + * Fix `source` records for `video/*` types that are IANA + * Update `font/opentype` to registered `font/otf` + +1.29.0 / 2017-07-10 +=================== + + * Add `application/fido.trusted-apps+json` + * Add extension `.wadl` to `application/vnd.sun.wadl+xml` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/css` + +1.28.0 / 2017-05-14 +=================== + + * Add new upstream MIME types + * Add extension `.gz` to `application/gzip` + * Update extensions `.md` and `.markdown` to be `text/markdown` + +1.27.0 / 2017-03-16 +=================== + + * Add new upstream MIME types + * Add `image/apng` with extension `.apng` + +1.26.0 / 2017-01-14 +=================== + + * Add new upstream MIME types + * Add extension `.geojson` to `application/geo+json` + +1.25.0 / 2016-11-11 +=================== + + * Add new upstream MIME types + +1.24.0 / 2016-09-18 +=================== + + * Add `audio/mp3` + * Add new upstream MIME types + +1.23.0 / 2016-05-01 +=================== + + * Add new upstream MIME types + * Add extension `.3gpp` to `audio/3gpp` + +1.22.0 / 2016-02-15 +=================== + + * Add `text/slim` + * Add extension `.rng` to `application/xml` + * Add new upstream MIME types + * Fix extension of `application/dash+xml` to be `.mpd` + * Update primary extension to `.m4a` for `audio/mp4` + +1.21.0 / 2016-01-06 +=================== + + * Add Google document types + * Add new upstream MIME types + +1.20.0 / 2015-11-10 +=================== + + * Add `text/x-suse-ymp` + * Add new upstream MIME types + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.apple.pkpass` + * Add new upstream MIME types + +1.18.0 / 2015-09-03 +=================== + + * Add new upstream MIME types + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +1.13.0 / 2015-06-07 +=================== + + * Add nginx as a source + * Add `application/x-cocoa` + * Add `application/x-java-archive-diff` + * Add `application/x-makeself` + * Add `application/x-perl` + * Add `application/x-pilot` + * Add `application/x-redhat-package-manager` + * Add `application/x-sea` + * Add `audio/x-m4a` + * Add `audio/x-realaudio` + * Add `image/x-jng` + * Add `text/mathml` + +1.12.0 / 2015-06-05 +=================== + + * Add `application/bdoc` + * Add `application/vnd.hyperdrive+json` + * Add `application/x-bdoc` + * Add extension `.rtf` to `text/rtf` + +1.11.0 / 2015-05-31 +=================== + + * Add `audio/wav` + * Add `audio/wave` + * Add extension `.litcoffee` to `text/coffeescript` + * Add extension `.sfd-hdstx` to `application/vnd.hydrostatix.sof-data` + * Add extension `.n-gage` to `application/vnd.nokia.n-gage.symbian.install` + +1.10.0 / 2015-05-19 +=================== + + * Add `application/vnd.balsamiq.bmpr` + * Add `application/vnd.microsoft.portable-executable` + * Add `application/x-ns-proxy-autoconfig` + +1.9.1 / 2015-04-19 +================== + + * Remove `.json` extension from `application/manifest+json` + - This is causing bugs downstream + +1.9.0 / 2015-04-19 +================== + + * Add `application/manifest+json` + * Add `application/vnd.micro+json` + * Add `image/vnd.zbrush.pcx` + * Add `image/x-ms-bmp` + +1.8.0 / 2015-03-13 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/node_modules/mime-db/LICENSE b/node_modules/mime-db/LICENSE new file mode 100644 index 0000000..0751cb1 --- /dev/null +++ b/node_modules/mime-db/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015-2022 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mime-db/README.md b/node_modules/mime-db/README.md new file mode 100644 index 0000000..5a8fcfe --- /dev/null +++ b/node_modules/mime-db/README.md @@ -0,0 +1,100 @@ +# mime-db + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +This is a large database of mime types and information about them. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +It aggregates data from the following sources: + +- http://www.iana.org/assignments/media-types/media-types.xhtml +- http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types +- http://hg.nginx.org/nginx/raw-file/default/conf/mime.types + +## Installation + +```bash +npm install mime-db +``` + +### Database Download + +If you're crazy enough to use this in the browser, you can just grab the +JSON file using [jsDelivr](https://www.jsdelivr.com/). It is recommended to +replace `master` with [a release tag](https://github.com/jshttp/mime-db/tags) +as the JSON format may change in the future. + +``` +https://cdn.jsdelivr.net/gh/jshttp/mime-db@master/db.json +``` + +## Usage + +```js +var db = require('mime-db') + +// grab data on .js files +var data = db['application/javascript'] +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + If not set, it's probably a custom media type. + - `apache` - [Apache common media types](http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) + - `iana` - [IANA-defined media types](http://www.iana.org/assignments/media-types/media-types.xhtml) + - `nginx` - [nginx media types](http://hg.nginx.org/nginx/raw-file/default/conf/mime.types) +- `.extensions[]` - known extensions associated with this mime type. +- `.compressible` - whether a file of this type can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Contributing + +To edit the database, only make PRs against `src/custom-types.json` or +`src/custom-suffix.json`. + +The `src/custom-types.json` file is a JSON object with the MIME type as the +keys and the values being an object with the following keys: + +- `compressible` - leave out if you don't know, otherwise `true`/`false` to + indicate whether the data represented by the type is typically compressible. +- `extensions` - include an array of file extensions that are associated with + the type. +- `notes` - human-readable notes about the type, typically what the type is. +- `sources` - include an array of URLs of where the MIME type and the associated + extensions are sourced from. This needs to be a [primary source](https://en.wikipedia.org/wiki/Primary_source); + links to type aggregating sites and Wikipedia are _not acceptable_. + +To update the build, run `npm run build`. + +### Adding Custom Media Types + +The best way to get new media types included in this library is to register +them with the IANA. The community registration procedure is outlined in +[RFC 6838 section 5](http://tools.ietf.org/html/rfc6838#section-5). Types +registered with the IANA are automatically pulled into this library. + +If that is not possible / feasible, they can be added directly here as a +"custom" type. To do this, it is required to have a primary source that +definitively lists the media type. If an extension is going to be listed as +associateed with this media type, the source must definitively link the +media type and extension as well. + +[ci-image]: https://badgen.net/github/checks/jshttp/mime-db/master?label=ci +[ci-url]: https://github.com/jshttp/mime-db/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-db/master +[coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master +[node-image]: https://badgen.net/npm/node/mime-db +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mime-db +[npm-url]: https://npmjs.org/package/mime-db +[npm-version-image]: https://badgen.net/npm/v/mime-db diff --git a/node_modules/mime-db/db.json b/node_modules/mime-db/db.json new file mode 100644 index 0000000..eb9c42c --- /dev/null +++ b/node_modules/mime-db/db.json @@ -0,0 +1,8519 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/3gpp-ims+xml": { + "source": "iana", + "compressible": true + }, + "application/3gpphal+json": { + "source": "iana", + "compressible": true + }, + "application/3gpphalforms+json": { + "source": "iana", + "compressible": true + }, + "application/a2l": { + "source": "iana" + }, + "application/ace+cbor": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/activity+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-updatestreamcontrol+json": { + "source": "iana", + "compressible": true + }, + "application/alto-updatestreamparams+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/at+jwt": { + "source": "iana" + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomdeleted"] + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomsvc"] + }, + "application/atsc-dwd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dwd"] + }, + "application/atsc-dynamic-event-message": { + "source": "iana" + }, + "application/atsc-held+xml": { + "source": "iana", + "compressible": true, + "extensions": ["held"] + }, + "application/atsc-rdt+json": { + "source": "iana", + "compressible": true + }, + "application/atsc-rsat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rsat"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana", + "compressible": true + }, + "application/bacnet-xdd+zip": { + "source": "iana", + "compressible": false + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xcs"] + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/captive+json": { + "source": "iana", + "compressible": true + }, + "application/cbor": { + "source": "iana" + }, + "application/cbor-seq": { + "source": "iana" + }, + "application/cccex": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana", + "compressible": true + }, + "application/ccxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ccxml"] + }, + "application/cdfx+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdfx"] + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana", + "compressible": true + }, + "application/cellml+xml": { + "source": "iana", + "compressible": true + }, + "application/cfw": { + "source": "iana" + }, + "application/city+json": { + "source": "iana", + "compressible": true + }, + "application/clr": { + "source": "iana" + }, + "application/clue+xml": { + "source": "iana", + "compressible": true + }, + "application/clue_info+xml": { + "source": "iana", + "compressible": true + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana", + "compressible": true + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/coap-payload": { + "source": "iana" + }, + "application/commonground": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/cose": { + "source": "iana" + }, + "application/cose-key": { + "source": "iana" + }, + "application/cose-key-set": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cpl"] + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana", + "compressible": true + }, + "application/cstadata+xml": { + "source": "iana", + "compressible": true + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cwt": { + "source": "iana" + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpd"] + }, + "application/dash-patch+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpp"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "compressible": true, + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana", + "compressible": true + }, + "application/dicom": { + "source": "iana" + }, + "application/dicom+json": { + "source": "iana", + "compressible": true + }, + "application/dicom+xml": { + "source": "iana", + "compressible": true + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/dns+json": { + "source": "iana", + "compressible": true + }, + "application/dns-message": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dbk"] + }, + "application/dots+cbor": { + "source": "iana" + }, + "application/dskpp+xml": { + "source": "iana", + "compressible": true + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/ecmascript": { + "source": "iana", + "compressible": true, + "extensions": ["es","ecma"] + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/efi": { + "source": "iana" + }, + "application/elm+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/elm+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.cap+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/emergencycalldata.comment+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.control+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.ecall.msd": { + "source": "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.veds+xml": { + "source": "iana", + "compressible": true + }, + "application/emma+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emotionml"] + }, + "application/encaprtp": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana", + "compressible": true + }, + "application/epub+zip": { + "source": "iana", + "compressible": false, + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/expect-ct-report+json": { + "source": "iana", + "compressible": true + }, + "application/express": { + "source": "iana", + "extensions": ["exp"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["fdt"] + }, + "application/fhir+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/fhir+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/fido.trusted-apps+json": { + "compressible": true + }, + "application/fits": { + "source": "iana" + }, + "application/flexfec": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false + }, + "application/framework-attributes+xml": { + "source": "iana", + "compressible": true + }, + "application/geo+json": { + "source": "iana", + "compressible": true, + "extensions": ["geojson"] + }, + "application/geo+json-seq": { + "source": "iana" + }, + "application/geopackage+sqlite3": { + "source": "iana" + }, + "application/geoxacml+xml": { + "source": "iana", + "compressible": true + }, + "application/gltf-buffer": { + "source": "iana" + }, + "application/gml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["gml"] + }, + "application/gpx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["gpx"] + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false, + "extensions": ["gz"] + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana", + "compressible": true + }, + "application/hjson": { + "extensions": ["hjson"] + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pkg-reply+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana", + "compressible": true, + "extensions": ["its"] + }, + "application/java-archive": { + "source": "apache", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js","mjs"] + }, + "application/jf2feed+json": { + "source": "iana", + "compressible": true + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/jscalendar+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana", + "compressible": true + }, + "application/kpml-response+xml": { + "source": "iana", + "compressible": true + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/lgr+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lgr"] + }, + "application/link-format": { + "source": "iana" + }, + "application/load-control+xml": { + "source": "iana", + "compressible": true + }, + "application/lost+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana", + "compressible": true + }, + "application/lpf+zip": { + "source": "iana", + "compressible": false + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mads"] + }, + "application/manifest+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana", + "compressible": true + }, + "application/mathml-presentation+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-deregister+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-envelope+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-protection-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-reception-report+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-schedule+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-user-service-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpf"] + }, + "application/media_control+xml": { + "source": "iana", + "compressible": true + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "compressible": true, + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "compressible": true, + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mipc": { + "source": "iana" + }, + "application/missing-blocks+cbor-seq": { + "source": "iana" + }, + "application/mmt-aei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["maei"] + }, + "application/mmt-usd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musd"] + }, + "application/mods+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana", + "compressible": true + }, + "application/mrb-publish+xml": { + "source": "iana", + "compressible": true + }, + "application/msc-ivr+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/msc-mixer+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mud+json": { + "source": "iana", + "compressible": true + }, + "application/multipart-core": { + "source": "iana" + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/n-quads": { + "source": "iana", + "extensions": ["nq"] + }, + "application/n-triples": { + "source": "iana", + "extensions": ["nt"] + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana", + "charset": "US-ASCII" + }, + "application/news-groupinfo": { + "source": "iana", + "charset": "US-ASCII" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana", + "compressible": true + }, + "application/node": { + "source": "iana", + "extensions": ["cjs"] + }, + "application/nss": { + "source": "iana" + }, + "application/oauth-authz-req+jwt": { + "source": "iana" + }, + "application/oblivious-dns-message": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": false, + "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"] + }, + "application/oda": { + "source": "iana", + "extensions": ["oda"] + }, + "application/odm+xml": { + "source": "iana", + "compressible": true + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/omdoc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg"] + }, + "application/opc-nodeset+xml": { + "source": "iana", + "compressible": true + }, + "application/oscore": { + "source": "iana" + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p21": { + "source": "iana" + }, + "application/p21+zip": { + "source": "iana", + "compressible": false + }, + "application/p2p-overlay+xml": { + "source": "iana", + "compressible": true, + "extensions": ["relo"] + }, + "application/parityfec": { + "source": "iana" + }, + "application/passport": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pem-certificate-chain": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana", + "extensions": ["asc"] + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["asc","sig"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/pidf-diff+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkcs8-encrypted": { + "source": "iana" + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/ppsp-tracker+json": { + "source": "iana", + "compressible": true + }, + "application/problem+json": { + "source": "iana", + "compressible": true + }, + "application/problem+xml": { + "source": "iana", + "compressible": true + }, + "application/provenance+xml": { + "source": "iana", + "compressible": true, + "extensions": ["provx"] + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.cyn": { + "source": "iana", + "charset": "7-BIT" + }, + "application/prs.hpub+zip": { + "source": "iana", + "compressible": false + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana", + "compressible": true + }, + "application/pskc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pskcxml"] + }, + "application/pvd+json": { + "source": "iana", + "compressible": true + }, + "application/qsig": { + "source": "iana" + }, + "application/raml+yaml": { + "compressible": true, + "extensions": ["raml"] + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf","owl"] + }, + "application/reginfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "iana" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resource-lists+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana", + "compressible": true + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana", + "compressible": true + }, + "application/rls-services+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rs"] + }, + "application/route-apd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rapd"] + }, + "application/route-s-tsid+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sls"] + }, + "application/route-usd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rusd"] + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-publication": { + "source": "iana" + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana", + "compressible": true + }, + "application/samlmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/sarif+json": { + "source": "iana", + "compressible": true + }, + "application/sarif-external-properties+json": { + "source": "iana", + "compressible": true + }, + "application/sbe": { + "source": "iana" + }, + "application/sbml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana", + "compressible": true + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/secevent+jwt": { + "source": "iana" + }, + "application/senml+cbor": { + "source": "iana" + }, + "application/senml+json": { + "source": "iana", + "compressible": true + }, + "application/senml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["senmlx"] + }, + "application/senml-etch+cbor": { + "source": "iana" + }, + "application/senml-etch+json": { + "source": "iana", + "compressible": true + }, + "application/senml-exi": { + "source": "iana" + }, + "application/sensml+cbor": { + "source": "iana" + }, + "application/sensml+json": { + "source": "iana", + "compressible": true + }, + "application/sensml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sensmlx"] + }, + "application/sensml-exi": { + "source": "iana" + }, + "application/sep+xml": { + "source": "iana", + "compressible": true + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana", + "extensions": ["siv","sieve"] + }, + "application/simple-filter+xml": { + "source": "iana", + "compressible": true + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/sipc": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "iana" + }, + "application/smil+xml": { + "source": "iana", + "compressible": true, + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "compressible": true, + "extensions": ["srx"] + }, + "application/spdx+json": { + "source": "iana", + "compressible": true + }, + "application/spirits-event+xml": { + "source": "iana", + "compressible": true + }, + "application/sql": { + "source": "iana" + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ssdl"] + }, + "application/ssml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ssml"] + }, + "application/stix+json": { + "source": "iana", + "compressible": true + }, + "application/swid+xml": { + "source": "iana", + "compressible": true, + "extensions": ["swidtag"] + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/taxii+json": { + "source": "iana", + "compressible": true + }, + "application/td+json": { + "source": "iana", + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tei","teicorpus"] + }, + "application/tetra_isi": { + "source": "iana" + }, + "application/thraud+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/tlsrpt+gzip": { + "source": "iana" + }, + "application/tlsrpt+json": { + "source": "iana", + "compressible": true + }, + "application/tnauthlist": { + "source": "iana" + }, + "application/token-introspection+jwt": { + "source": "iana" + }, + "application/toml": { + "compressible": true, + "extensions": ["toml"] + }, + "application/trickle-ice-sdpfrag": { + "source": "iana" + }, + "application/trig": { + "source": "iana", + "extensions": ["trig"] + }, + "application/ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ttml"] + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/tzif": { + "source": "iana" + }, + "application/tzif-leap": { + "source": "iana" + }, + "application/ubjson": { + "compressible": false, + "extensions": ["ubj"] + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/urc-ressheet+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rsheet"] + }, + "application/urc-targetdesc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["td"] + }, + "application/urc-uisocketdesc+xml": { + "source": "iana", + "compressible": true + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana", + "compressible": true + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.1000minds.decision-model+xml": { + "source": "iana", + "compressible": true, + "extensions": ["1km"] + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-v2x-local-service-information": { + "source": "iana" + }, + "application/vnd.3gpp.5gnas": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gmop+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gtpc": { + "source": "iana" + }, + "application/vnd.3gpp.interworking-data": { + "source": "iana" + }, + "application/vnd.3gpp.lpp": { + "source": "iana" + }, + "application/vnd.3gpp.mc-signalling-ear": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-payload": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-signalling": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-floor-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-signed+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-ue-init-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-affiliation-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-transmission-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ngap": { + "source": "iana" + }, + "application/vnd.3gpp.pfcp": { + "source": "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.s1ap": { + "source": "iana" + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.sms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3lightssoftware.imagescal": { + "source": "iana" + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "compressible": false, + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata-pagedef": { + "source": "iana" + }, + "application/vnd.afpc.cmoca-cmresource": { + "source": "iana" + }, + "application/vnd.afpc.foca-charset": { + "source": "iana" + }, + "application/vnd.afpc.foca-codedfont": { + "source": "iana" + }, + "application/vnd.afpc.foca-codepage": { + "source": "iana" + }, + "application/vnd.afpc.modca": { + "source": "iana" + }, + "application/vnd.afpc.modca-cmtable": { + "source": "iana" + }, + "application/vnd.afpc.modca-formdef": { + "source": "iana" + }, + "application/vnd.afpc.modca-mediummap": { + "source": "iana" + }, + "application/vnd.afpc.modca-objectcontainer": { + "source": "iana" + }, + "application/vnd.afpc.modca-overlay": { + "source": "iana" + }, + "application/vnd.afpc.modca-pagesegment": { + "source": "iana" + }, + "application/vnd.age": { + "source": "iana", + "extensions": ["age"] + }, + "application/vnd.ah-barcode": { + "source": "iana" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amadeus+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.amazon.mobi8-ebook": { + "source": "iana" + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.android.ota": { + "source": "iana" + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.arrow.file": { + "source": "iana" + }, + "application/vnd.apache.arrow.stream": { + "source": "iana" + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.aplextor.warrp+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apothekende.reservation+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpkg"] + }, + "application/vnd.apple.keynote": { + "source": "iana", + "extensions": ["key"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.numbers": { + "source": "iana", + "extensions": ["numbers"] + }, + "application/vnd.apple.pages": { + "source": "iana", + "extensions": ["pages"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "iana" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artisan+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avalon+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.avistar+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["bmml"] + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.banana-accounting": { + "source": "iana" + }, + "application/vnd.bbf.usp.error": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bint.med-content": { + "source": "iana" + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.blink-idb-value-wrapper": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.bpf": { + "source": "iana" + }, + "application/vnd.bpf3": { + "source": "iana" + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.byu.uapi+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.capasystems-pg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdxml"] + }, + "application/vnd.chess-pgn": { + "source": "iana" + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.ciedi": { + "source": "iana" + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana", + "compressible": true, + "extensions": ["csl"] + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet-template": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.comicbook+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.comicbook-rar": { + "source": "iana" + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.coreos.ignition+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wbs"] + }, + "application/vnd.cryptii.pipe+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.crypto-shade-file": { + "source": "iana" + }, + "application/vnd.cryptomator.encrypted": { + "source": "iana" + }, + "application/vnd.cryptomator.vault": { + "source": "iana" + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.cyclonedx+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cyclonedx+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.d2l.coursepackage1p0+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.d3m-dataset": { + "source": "iana" + }, + "application/vnd.d3m-problem": { + "source": "iana" + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.datapackage+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dataresource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dbf": { + "source": "iana", + "extensions": ["dbf"] + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume.movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbisl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecip.rlp": { + "source": "iana" + }, + "application/vnd.eclipse.ditto+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.efi.img": { + "source": "iana" + }, + "application/vnd.efi.iso": { + "source": "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.espass-espass+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "compressible": true, + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.cug+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.sci+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eu.kasparian.car+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.evolv.ecig.profile": { + "source": "iana" + }, + "application/vnd.evolv.ecig.settings": { + "source": "iana" + }, + "application/vnd.evolv.ecig.theme": { + "source": "iana" + }, + "application/vnd.exstream-empower+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.exstream-package": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.familysearch.gedcom+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.ficlab.flb+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.frogans.fnc": { + "source": "iana", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "iana", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujifilm.fb.docuworks": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.docuworks.binder": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.jfi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.futoin+cbor": { + "source": "iana" + }, + "application/vnd.futoin+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.gentics.grd+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geo+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.slides": { + "source": "iana" + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "compressible": true, + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.hdt": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hl7cda+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.hl7v2+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyper+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyper-item+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "iana" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "iana", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.imagemeter.folder+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.imagemeter.image+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.informix-visionary": { + "source": "iana" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.iso11783-10+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las": { + "source": "iana" + }, + "application/vnd.las.las+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.las.las+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lasxml"] + }, + "application/vnd.laszip": { + "source": "iana" + }, + "application/vnd.leap+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.liberty-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lbe"] + }, + "application/vnd.logipipe.circuit+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.loom": { + "source": "iana" + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana", + "extensions": ["mvt"] + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxar.archive.3tz+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.microsoft.windows.thumbnail-cache": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-outlook": { + "compressible": false, + "extensions": ["msg"] + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-printschematicket+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.nacamar.ybrid+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nearst.inv+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.nebumind.line": { + "source": "iana" + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nimn": { + "source": "iana" + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ac"] + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "iana", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "iana", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.ocf+cbor": { + "source": "iana" + }, + "application/vnd.oci.image.manifest.v1+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+cbor": { + "source": "iana" + }, + "application/vnd.oma.lwm2m+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+tlv": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.omads-email+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omads-file+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omads-folder+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.onepager": { + "source": "iana" + }, + "application/vnd.onepagertamp": { + "source": "iana" + }, + "application/vnd.onepagertamx": { + "source": "iana" + }, + "application/vnd.onepagertat": { + "source": "iana" + }, + "application/vnd.onepagertatp": { + "source": "iana" + }, + "application/vnd.onepagertatx": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana", + "compressible": true, + "extensions": ["obgx"] + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openstreetmap.data+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osm"] + }, + "application/vnd.opentimestamps.ots": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "iana", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "iana", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "iana", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "iana" + }, + "application/vnd.patentdive": { + "source": "iana" + }, + "application/vnd.patientecommsdoc": { + "source": "iana" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.psfs": { + "source": "iana" + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quarantainenet": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.rar": { + "source": "iana", + "extensions": ["rar"] + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.resilient.logic": { + "source": "iana" + }, + "application/vnd.restful+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "compressible": true, + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sar": { + "source": "iana" + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.seis+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shade-save-file": { + "source": "iana" + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.shootproof+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.shopkick+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.shp": { + "source": "iana" + }, + "application/vnd.shx": { + "source": "iana" + }, + "application/vnd.sigrok.session": { + "source": "iana" + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.snesdev-page-table": { + "source": "iana" + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana", + "compressible": true, + "extensions": ["fo"] + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sqlite3": { + "source": "iana" + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wadl"] + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.sycle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.syft+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["ddf"] + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tableschema+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.think-cell.ppttc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.tri.onesource": { + "source": "iana" + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uoml"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.vel+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.veritone.aion+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.veryant.thin": { + "source": "iana" + }, + "application/vnd.ves.encrypted": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.dpp": { + "source": "iana" + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.wv.ssp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.youtube.yt": { + "source": "iana" + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["vxml"] + }, + "application/voucher-cms+json": { + "source": "iana", + "compressible": true + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/wasm": { + "source": "iana", + "compressible": true, + "extensions": ["wasm"] + }, + "application/watcherinfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wif"] + }, + "application/webpush-options+json": { + "source": "iana", + "compressible": true + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-arj": { + "compressible": false, + "extensions": ["arj"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "compressible": true, + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-iwork-keynote-sffkey": { + "extensions": ["key"] + }, + "application/x-iwork-numbers-sffnumbers": { + "extensions": ["numbers"] + }, + "application/x-iwork-pages-sffpages": { + "extensions": ["pages"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-keepass2": { + "extensions": ["kdbx"] + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "source": "apache", + "extensions": ["nc","cdf"] + }, + "application/x-ns-proxy-autoconfig": { + "compressible": true, + "extensions": ["pac"] + }, + "application/x-nzb": { + "source": "apache", + "extensions": ["nzb"] + }, + "application/x-perl": { + "source": "nginx", + "extensions": ["pl","pm"] + }, + "application/x-pilot": { + "source": "nginx", + "extensions": ["prc","pdb"] + }, + "application/x-pkcs12": { + "source": "apache", + "compressible": false, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-pki-message": { + "source": "iana" + }, + "application/x-rar-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["rar"] + }, + "application/x-redhat-package-manager": { + "source": "nginx", + "extensions": ["rpm"] + }, + "application/x-research-info-systems": { + "source": "apache", + "extensions": ["ris"] + }, + "application/x-sea": { + "source": "nginx", + "extensions": ["sea"] + }, + "application/x-sh": { + "source": "apache", + "compressible": true, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-virtualbox-hdd": { + "compressible": true, + "extensions": ["hdd"] + }, + "application/x-virtualbox-ova": { + "compressible": true, + "extensions": ["ova"] + }, + "application/x-virtualbox-ovf": { + "compressible": true, + "extensions": ["ovf"] + }, + "application/x-virtualbox-vbox": { + "compressible": true, + "extensions": ["vbox"] + }, + "application/x-virtualbox-vbox-extpack": { + "compressible": false, + "extensions": ["vbox-extpack"] + }, + "application/x-virtualbox-vdi": { + "compressible": true, + "extensions": ["vdi"] + }, + "application/x-virtualbox-vhd": { + "compressible": true, + "extensions": ["vhd"] + }, + "application/x-virtualbox-vmdk": { + "compressible": true, + "extensions": ["vmdk"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "iana", + "extensions": ["der","crt","pem"] + }, + "application/x-x509-ca-ra-cert": { + "source": "iana" + }, + "application/x-x509-next-ca-cert": { + "source": "iana" + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana", + "compressible": true + }, + "application/xaml+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xav"] + }, + "application/xcap-caps+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xca"] + }, + "application/xcap-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xel"] + }, + "application/xcap-error+xml": { + "source": "iana", + "compressible": true + }, + "application/xcap-ns+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xns"] + }, + "application/xcon-conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana", + "compressible": true + }, + "application/xenc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xenc"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache", + "compressible": true + }, + "application/xliff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xlf"] + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd","rng"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/xmpp+xml": { + "source": "iana", + "compressible": true + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xsl","xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yang-data+json": { + "source": "iana", + "compressible": true + }, + "application/yang-data+xml": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+json": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/yin+xml": { + "source": "iana", + "compressible": true, + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zlib": { + "source": "iana" + }, + "application/zstd": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana", + "compressible": false, + "extensions": ["3gpp"] + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/aac": { + "source": "iana" + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana", + "extensions": ["amr"] + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/flexfec": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/melp": { + "source": "iana" + }, + "audio/melp1200": { + "source": "iana" + }, + "audio/melp2400": { + "source": "iana" + }, + "audio/melp600": { + "source": "iana" + }, + "audio/mhas": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/mobile-xmf": { + "source": "iana", + "extensions": ["mxmf"] + }, + "audio/mp3": { + "compressible": false, + "extensions": ["mp3"] + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["m4a","mp4a"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx","opus"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/scip": { + "source": "iana" + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sofa": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tetra_acelp": { + "source": "iana" + }, + "audio/tetra_acelp_bb": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/tsvcis": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/usac": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dts.uhd": { + "source": "iana" + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.presonus.multitrack": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/collection": { + "source": "iana", + "extensions": ["ttc"] + }, + "font/otf": { + "source": "iana", + "compressible": true, + "extensions": ["otf"] + }, + "font/sfnt": { + "source": "iana" + }, + "font/ttf": { + "source": "iana", + "compressible": true, + "extensions": ["ttf"] + }, + "font/woff": { + "source": "iana", + "extensions": ["woff"] + }, + "font/woff2": { + "source": "iana", + "extensions": ["woff2"] + }, + "image/aces": { + "source": "iana", + "extensions": ["exr"] + }, + "image/apng": { + "compressible": false, + "extensions": ["apng"] + }, + "image/avci": { + "source": "iana", + "extensions": ["avci"] + }, + "image/avcs": { + "source": "iana", + "extensions": ["avcs"] + }, + "image/avif": { + "source": "iana", + "compressible": false, + "extensions": ["avif"] + }, + "image/bmp": { + "source": "iana", + "compressible": true, + "extensions": ["bmp"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/dicom-rle": { + "source": "iana", + "extensions": ["drle"] + }, + "image/emf": { + "source": "iana", + "extensions": ["emf"] + }, + "image/fits": { + "source": "iana", + "extensions": ["fits"] + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/heic": { + "source": "iana", + "extensions": ["heic"] + }, + "image/heic-sequence": { + "source": "iana", + "extensions": ["heics"] + }, + "image/heif": { + "source": "iana", + "extensions": ["heif"] + }, + "image/heif-sequence": { + "source": "iana", + "extensions": ["heifs"] + }, + "image/hej2k": { + "source": "iana", + "extensions": ["hej2"] + }, + "image/hsj2": { + "source": "iana", + "extensions": ["hsj2"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/jls": { + "source": "iana", + "extensions": ["jls"] + }, + "image/jp2": { + "source": "iana", + "compressible": false, + "extensions": ["jp2","jpg2"] + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpeg","jpg","jpe"] + }, + "image/jph": { + "source": "iana", + "extensions": ["jph"] + }, + "image/jphc": { + "source": "iana", + "extensions": ["jhc"] + }, + "image/jpm": { + "source": "iana", + "compressible": false, + "extensions": ["jpm"] + }, + "image/jpx": { + "source": "iana", + "compressible": false, + "extensions": ["jpx","jpf"] + }, + "image/jxr": { + "source": "iana", + "extensions": ["jxr"] + }, + "image/jxra": { + "source": "iana", + "extensions": ["jxra"] + }, + "image/jxrs": { + "source": "iana", + "extensions": ["jxrs"] + }, + "image/jxs": { + "source": "iana", + "extensions": ["jxs"] + }, + "image/jxsc": { + "source": "iana", + "extensions": ["jxsc"] + }, + "image/jxsi": { + "source": "iana", + "extensions": ["jxsi"] + }, + "image/jxss": { + "source": "iana", + "extensions": ["jxss"] + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/ktx2": { + "source": "iana", + "extensions": ["ktx2"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif"] + }, + "image/prs.pti": { + "source": "iana", + "extensions": ["pti"] + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana", + "extensions": ["t38"] + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tif","tiff"] + }, + "image/tiff-fx": { + "source": "iana", + "extensions": ["tfx"] + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana", + "extensions": ["azv"] + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana", + "compressible": true, + "extensions": ["ico"] + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-dds": { + "compressible": true, + "extensions": ["dds"] + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.pco.b16": { + "source": "iana", + "extensions": ["b16"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana", + "extensions": ["tap"] + }, + "image/vnd.valve.source.texture": { + "source": "iana", + "extensions": ["vtf"] + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana", + "extensions": ["pcx"] + }, + "image/webp": { + "source": "apache", + "extensions": ["webp"] + }, + "image/wmf": { + "source": "iana", + "extensions": ["wmf"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "compressible": true, + "extensions": ["ico"] + }, + "image/x-jng": { + "source": "nginx", + "extensions": ["jng"] + }, + "image/x-mrsid-image": { + "source": "apache", + "extensions": ["sid"] + }, + "image/x-ms-bmp": { + "source": "nginx", + "compressible": true, + "extensions": ["bmp"] + }, + "image/x-pcx": { + "source": "apache", + "extensions": ["pcx"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana", + "extensions": [ + "disposition-notification" + ] + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana", + "extensions": ["u8msg"] + }, + "message/global-delivery-status": { + "source": "iana", + "extensions": ["u8dsn"] + }, + "message/global-disposition-notification": { + "source": "iana", + "extensions": ["u8mdn"] + }, + "message/global-headers": { + "source": "iana", + "extensions": ["u8hdr"] + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/news": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime"] + }, + "message/s-http": { + "source": "iana" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "iana" + }, + "message/vnd.wfa.wsc": { + "source": "iana", + "extensions": ["wsc"] + }, + "model/3mf": { + "source": "iana", + "extensions": ["3mf"] + }, + "model/e57": { + "source": "iana" + }, + "model/gltf+json": { + "source": "iana", + "compressible": true, + "extensions": ["gltf"] + }, + "model/gltf-binary": { + "source": "iana", + "compressible": true, + "extensions": ["glb"] + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/mtl": { + "source": "iana", + "extensions": ["mtl"] + }, + "model/obj": { + "source": "iana", + "extensions": ["obj"] + }, + "model/step": { + "source": "iana" + }, + "model/step+xml": { + "source": "iana", + "compressible": true, + "extensions": ["stpx"] + }, + "model/step+zip": { + "source": "iana", + "compressible": false, + "extensions": ["stpz"] + }, + "model/step-xml+zip": { + "source": "iana", + "compressible": false, + "extensions": ["stpxz"] + }, + "model/stl": { + "source": "iana", + "extensions": ["stl"] + }, + "model/vnd.collada+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana", + "compressible": true + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana", + "extensions": ["ogex"] + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana", + "extensions": ["x_b"] + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana", + "extensions": ["x_t"] + }, + "model/vnd.pytha.pyox": { + "source": "iana" + }, + "model/vnd.rosette.annotated-data-model": { + "source": "iana" + }, + "model/vnd.sap.vds": { + "source": "iana", + "extensions": ["vds"] + }, + "model/vnd.usdz+zip": { + "source": "iana", + "compressible": false, + "extensions": ["usdz"] + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana", + "extensions": ["bsp"] + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana", + "extensions": ["x3db"] + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana", + "extensions": ["x3dv"] + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana" + }, + "multipart/multilingual": { + "source": "iana" + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/vnd.bint.med-plus": { + "source": "iana" + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/cql": { + "source": "iana" + }, + "text/cql-expression": { + "source": "iana" + }, + "text/cql-identifier": { + "source": "iana" + }, + "text/css": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "iana" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fhirpath": { + "source": "iana" + }, + "text/flexfec": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/gff3": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "compressible": true + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "compressible": true, + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana", + "compressible": true, + "extensions": ["markdown","md"] + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mdx": { + "compressible": true, + "extensions": ["mdx"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana", + "charset": "UTF-8" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana", + "charset": "UTF-8" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/prs.prop.logic": { + "source": "iana" + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/shaclc": { + "source": "iana" + }, + "text/shex": { + "source": "iana", + "extensions": ["shex"] + }, + "text/slim": { + "extensions": ["slim","slm"] + }, + "text/spdx": { + "source": "iana", + "extensions": ["spdx"] + }, + "text/strings": { + "source": "iana" + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.ascii-art": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.familysearch.gedcom": { + "source": "iana", + "extensions": ["ged"] + }, + "text/vnd.ficlab.flt": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.gml": { + "source": "iana" + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.hans": { + "source": "iana" + }, + "text/vnd.hgl": { + "source": "iana" + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.senx.warpscript": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "iana" + }, + "text/vnd.sosi": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vtt": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-org": { + "compressible": true, + "extensions": ["org"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "compressible": true, + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "iana" + }, + "video/3gpp": { + "source": "iana", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "iana" + }, + "video/3gpp2": { + "source": "iana", + "extensions": ["3g2"] + }, + "video/av1": { + "source": "iana" + }, + "video/bmpeg": { + "source": "iana" + }, + "video/bt656": { + "source": "iana" + }, + "video/celb": { + "source": "iana" + }, + "video/dv": { + "source": "iana" + }, + "video/encaprtp": { + "source": "iana" + }, + "video/ffv1": { + "source": "iana" + }, + "video/flexfec": { + "source": "iana" + }, + "video/h261": { + "source": "iana", + "extensions": ["h261"] + }, + "video/h263": { + "source": "iana", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "iana" + }, + "video/h263-2000": { + "source": "iana" + }, + "video/h264": { + "source": "iana", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "iana" + }, + "video/h264-svc": { + "source": "iana" + }, + "video/h265": { + "source": "iana" + }, + "video/iso.segment": { + "source": "iana", + "extensions": ["m4s"] + }, + "video/jpeg": { + "source": "iana", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "iana" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/jxsv": { + "source": "iana" + }, + "video/mj2": { + "source": "iana", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "iana" + }, + "video/mp2p": { + "source": "iana" + }, + "video/mp2t": { + "source": "iana", + "extensions": ["ts"] + }, + "video/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "iana" + }, + "video/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "iana" + }, + "video/mpv": { + "source": "iana" + }, + "video/nv": { + "source": "iana" + }, + "video/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "iana" + }, + "video/pointer": { + "source": "iana" + }, + "video/quicktime": { + "source": "iana", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raptorfec": { + "source": "iana" + }, + "video/raw": { + "source": "iana" + }, + "video/rtp-enc-aescm128": { + "source": "iana" + }, + "video/rtploopback": { + "source": "iana" + }, + "video/rtx": { + "source": "iana" + }, + "video/scip": { + "source": "iana" + }, + "video/smpte291": { + "source": "iana" + }, + "video/smpte292m": { + "source": "iana" + }, + "video/ulpfec": { + "source": "iana" + }, + "video/vc1": { + "source": "iana" + }, + "video/vc2": { + "source": "iana" + }, + "video/vnd.cctv": { + "source": "iana" + }, + "video/vnd.dece.hd": { + "source": "iana", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "iana", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "iana" + }, + "video/vnd.dece.pd": { + "source": "iana", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "iana", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "iana", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "iana" + }, + "video/vnd.directv.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dvb.file": { + "source": "iana", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "iana", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "iana" + }, + "video/vnd.motorola.video": { + "source": "iana" + }, + "video/vnd.motorola.videop": { + "source": "iana" + }, + "video/vnd.mpegurl": { + "source": "iana", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "iana", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "iana" + }, + "video/vnd.nokia.mp4vr": { + "source": "iana" + }, + "video/vnd.nokia.videovoip": { + "source": "iana" + }, + "video/vnd.objectvideo": { + "source": "iana" + }, + "video/vnd.radgamettools.bink": { + "source": "iana" + }, + "video/vnd.radgamettools.smacker": { + "source": "iana" + }, + "video/vnd.sealed.mpeg1": { + "source": "iana" + }, + "video/vnd.sealed.mpeg4": { + "source": "iana" + }, + "video/vnd.sealed.swf": { + "source": "iana" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "iana" + }, + "video/vnd.uvvu.mp4": { + "source": "iana", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "iana", + "extensions": ["viv"] + }, + "video/vnd.youtube.yt": { + "source": "iana" + }, + "video/vp8": { + "source": "iana" + }, + "video/vp9": { + "source": "iana" + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/node_modules/mime-db/index.js b/node_modules/mime-db/index.js new file mode 100644 index 0000000..ec2be30 --- /dev/null +++ b/node_modules/mime-db/index.js @@ -0,0 +1,12 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/node_modules/mime-db/package.json b/node_modules/mime-db/package.json new file mode 100644 index 0000000..32c14b8 --- /dev/null +++ b/node_modules/mime-db/package.json @@ -0,0 +1,60 @@ +{ + "name": "mime-db", + "description": "Media Type Database", + "version": "1.52.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)", + "Robert Kieffer (http://github.com/broofa)" + ], + "license": "MIT", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "repository": "jshttp/mime-db", + "devDependencies": { + "bluebird": "3.7.2", + "co": "4.6.0", + "cogent": "1.0.1", + "csv-parse": "4.16.3", + "eslint": "7.32.0", + "eslint-config-standard": "15.0.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.1.1", + "eslint-plugin-standard": "4.1.0", + "gnode": "0.1.2", + "media-typer": "1.1.0", + "mocha": "9.2.1", + "nyc": "15.1.0", + "raw-body": "2.5.0", + "stream-to-array": "2.3.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build", + "fetch": "node scripts/fetch-apache && gnode scripts/fetch-iana && node scripts/fetch-nginx", + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "update": "npm run fetch && npm run build", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/mime-types/HISTORY.md b/node_modules/mime-types/HISTORY.md new file mode 100644 index 0000000..c5043b7 --- /dev/null +++ b/node_modules/mime-types/HISTORY.md @@ -0,0 +1,397 @@ +2.1.35 / 2022-03-12 +=================== + + * deps: mime-db@1.52.0 + - Add extensions from IANA for more `image/*` types + - Add extension `.asc` to `application/pgp-keys` + - Add extensions to various XML types + - Add new upstream MIME types + +2.1.34 / 2021-11-08 +=================== + + * deps: mime-db@1.51.0 + - Add new upstream MIME types + +2.1.33 / 2021-10-01 +=================== + + * deps: mime-db@1.50.0 + - Add deprecated iWorks mime types and extensions + - Add new upstream MIME types + +2.1.32 / 2021-07-27 +=================== + + * deps: mime-db@1.49.0 + - Add extension `.trig` to `application/trig` + - Add new upstream MIME types + +2.1.31 / 2021-06-01 +=================== + + * deps: mime-db@1.48.0 + - Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + - Add new upstream MIME types + +2.1.30 / 2021-04-02 +=================== + + * deps: mime-db@1.47.0 + - Add extension `.amr` to `audio/amr` + - Remove ambigious extensions from IANA for `application/*+xml` types + - Update primary extension to `.es` for `application/ecmascript` + +2.1.29 / 2021-02-17 +=================== + + * deps: mime-db@1.46.0 + - Add extension `.amr` to `audio/amr` + - Add extension `.m4s` to `video/iso.segment` + - Add extension `.opus` to `audio/ogg` + - Add new upstream MIME types + +2.1.28 / 2021-01-01 +=================== + + * deps: mime-db@1.45.0 + - Add `application/ubjson` with extension `.ubj` + - Add `image/avif` with extension `.avif` + - Add `image/ktx2` with extension `.ktx2` + - Add extension `.dbf` to `application/vnd.dbf` + - Add extension `.rar` to `application/vnd.rar` + - Add extension `.td` to `application/urc-targetdesc+xml` + - Add new upstream MIME types + - Fix extension of `application/vnd.apple.keynote` to be `.key` + +2.1.27 / 2020-04-23 +=================== + + * deps: mime-db@1.44.0 + - Add charsets from IANA + - Add extension `.cjs` to `application/node` + - Add new upstream MIME types + +2.1.26 / 2020-01-05 +=================== + + * deps: mime-db@1.43.0 + - Add `application/x-keepass2` with extension `.kdbx` + - Add extension `.mxmf` to `audio/mobile-xmf` + - Add extensions from IANA for `application/*+xml` types + - Add new upstream MIME types + +2.1.25 / 2019-11-12 +=================== + + * deps: mime-db@1.42.0 + - Add new upstream MIME types + - Add `application/toml` with extension `.toml` + - Add `image/vnd.ms-dds` with extension `.dds` + +2.1.24 / 2019-04-20 +=================== + + * deps: mime-db@1.40.0 + - Add extensions from IANA for `model/*` types + - Add `text/mdx` with extension `.mdx` + +2.1.23 / 2019-04-17 +=================== + + * deps: mime-db@~1.39.0 + - Add extensions `.siv` and `.sieve` to `application/sieve` + - Add new upstream MIME types + +2.1.22 / 2019-02-14 +=================== + + * deps: mime-db@~1.38.0 + - Add extension `.nq` to `application/n-quads` + - Add extension `.nt` to `application/n-triples` + - Add new upstream MIME types + +2.1.21 / 2018-10-19 +=================== + + * deps: mime-db@~1.37.0 + - Add extensions to HEIC image types + - Add new upstream MIME types + +2.1.20 / 2018-08-26 +=================== + + * deps: mime-db@~1.36.0 + - Add Apple file extensions from IANA + - Add extensions from IANA for `image/*` types + - Add new upstream MIME types + +2.1.19 / 2018-07-17 +=================== + + * deps: mime-db@~1.35.0 + - Add extension `.csl` to `application/vnd.citationstyles.style+xml` + - Add extension `.es` to `application/ecmascript` + - Add extension `.owl` to `application/rdf+xml` + - Add new upstream MIME types + - Add UTF-8 as default charset for `text/turtle` + +2.1.18 / 2018-02-16 +=================== + + * deps: mime-db@~1.33.0 + - Add `application/raml+yaml` with extension `.raml` + - Add `application/wasm` with extension `.wasm` + - Add `text/shex` with extension `.shex` + - Add extensions for JPEG-2000 images + - Add extensions from IANA for `message/*` types + - Add new upstream MIME types + - Update font MIME types + - Update `text/hjson` to registered `application/hjson` + +2.1.17 / 2017-09-01 +=================== + + * deps: mime-db@~1.30.0 + - Add `application/vnd.ms-outlook` + - Add `application/x-arj` + - Add extension `.mjs` to `application/javascript` + - Add glTF types and extensions + - Add new upstream MIME types + - Add `text/x-org` + - Add VirtualBox MIME types + - Fix `source` records for `video/*` types that are IANA + - Update `font/opentype` to registered `font/otf` + +2.1.16 / 2017-07-24 +=================== + + * deps: mime-db@~1.29.0 + - Add `application/fido.trusted-apps+json` + - Add extension `.wadl` to `application/vnd.sun.wadl+xml` + - Add extension `.gz` to `application/gzip` + - Add new upstream MIME types + - Update extensions `.md` and `.markdown` to be `text/markdown` + +2.1.15 / 2017-03-23 +=================== + + * deps: mime-db@~1.27.0 + - Add new mime types + - Add `image/apng` + +2.1.14 / 2017-01-14 +=================== + + * deps: mime-db@~1.26.0 + - Add new mime types + +2.1.13 / 2016-11-18 +=================== + + * deps: mime-db@~1.25.0 + - Add new mime types + +2.1.12 / 2016-09-18 +=================== + + * deps: mime-db@~1.24.0 + - Add new mime types + - Add `audio/mp3` + +2.1.11 / 2016-05-01 +=================== + + * deps: mime-db@~1.23.0 + - Add new mime types + +2.1.10 / 2016-02-15 +=================== + + * deps: mime-db@~1.22.0 + - Add new mime types + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +2.1.1 / 2015-06-08 +================== + + * perf: fix deopt during mapping + +2.1.0 / 2015-06-07 +================== + + * Fix incorrectly treating extension-less file name as extension + - i.e. `'path/to/json'` will no longer return `application/json` + * Fix `.charset(type)` to accept parameters + * Fix `.charset(type)` to match case-insensitive + * Improve generation of extension to MIME mapping + * Refactor internals for readability and no argument reassignment + * Prefer `application/*` MIME types from the same source + * Prefer any type over `application/octet-stream` + * deps: mime-db@~1.13.0 + - Add nginx as a source + - Add new mime types + +2.0.14 / 2015-06-06 +=================== + + * deps: mime-db@~1.12.0 + - Add new mime types + +2.0.13 / 2015-05-31 +=================== + + * deps: mime-db@~1.11.0 + - Add new mime types + +2.0.12 / 2015-05-19 +=================== + + * deps: mime-db@~1.10.0 + - Add new mime types + +2.0.11 / 2015-05-05 +=================== + + * deps: mime-db@~1.9.1 + - Add new mime types + +2.0.10 / 2015-03-13 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/node_modules/mime-types/LICENSE b/node_modules/mime-types/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/node_modules/mime-types/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mime-types/README.md b/node_modules/mime-types/README.md new file mode 100644 index 0000000..48d2fb4 --- /dev/null +++ b/node_modules/mime-types/README.md @@ -0,0 +1,113 @@ +# mime-types + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +The ultimate javascript content-type utility. + +Similar to [the `mime@1.x` module](https://www.npmjs.com/package/mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, + `mime-types` simply returns `false`, so do + `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- No `.define()` functionality +- Bug fixes for `.lookup(path)` + +Otherwise, the API is compatible with `mime` 1.x. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install mime-types +``` + +## Adding Types + +All mime types are based on [mime-db](https://www.npmjs.com/package/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. +When given an extension, `mime.lookup` is used to get the matching +content-type, otherwise the given content-type is used. Then if the +content-type does not already have a `charset` parameter, `mime.charset` +is used to get the default charset and add to the returned content-type. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' +mime.contentType('text/html') // 'text/html; charset=utf-8' +mime.contentType('text/html; charset=iso-8859-1') // 'text/html; charset=iso-8859-1' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/mime-types/master?label=ci +[ci-url]: https://github.com/jshttp/mime-types/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-types/master +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types?branch=master +[node-version-image]: https://badgen.net/npm/node/mime-types +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mime-types +[npm-url]: https://npmjs.org/package/mime-types +[npm-version-image]: https://badgen.net/npm/v/mime-types diff --git a/node_modules/mime-types/index.js b/node_modules/mime-types/index.js new file mode 100644 index 0000000..b9f34d5 --- /dev/null +++ b/node_modules/mime-types/index.js @@ -0,0 +1,188 @@ +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var db = require('mime-db') +var extname = require('path').extname + +/** + * Module variables. + * @private + */ + +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i + +/** + * Module exports. + * @public + */ + +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] + + if (mime && mime.charset) { + return mime.charset + } + + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ + +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } + + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str + + if (!mime) { + return false + } + + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } + + return mime +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] + + if (!exts || !exts.length) { + return false + } + + return exts[0] +} + +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ + +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } + + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) + + if (!extension) { + return false + } + + return exports.types[extension] || false +} + +/** + * Populate the extensions and types maps. + * @private + */ + +function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] + + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions + + if (!exts || !exts.length) { + return + } + + // mime -> extensions + extensions[type] = exts + + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] + + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) + + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} diff --git a/node_modules/mime-types/package.json b/node_modules/mime-types/package.json new file mode 100644 index 0000000..bbef696 --- /dev/null +++ b/node_modules/mime-types/package.json @@ -0,0 +1,44 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "2.1.35", + "contributors": [ + "Douglas Christopher Wilson ", + "Jeremiah Senkpiel (https://searchbeam.jit.su)", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "mime", + "types" + ], + "repository": "jshttp/mime-types", + "dependencies": { + "mime-db": "1.52.0" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.2", + "nyc": "15.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec test/test.js", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/mime/CHANGELOG.md b/node_modules/mime/CHANGELOG.md new file mode 100644 index 0000000..cdf9be5 --- /dev/null +++ b/node_modules/mime/CHANGELOG.md @@ -0,0 +1,312 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## [3.0.0](https://github.com/broofa/mime/compare/v2.6.0...v3.0.0) (2021-11-03) + + +### ⚠ BREAKING CHANGES + +* drop support for node < 10.x + +### Bug Fixes + +* skypack.dev for direct browser import, fixes [#263](https://github.com/broofa/mime/issues/263) ([41db4c0](https://github.com/broofa/mime/commit/41db4c042ccf50ea7baf3d2160ea37dcca37998d)) + + +### update + +* drop support for node < 10.x ([8857363](https://github.com/broofa/mime/commit/8857363ae0446ed0229b17291cf4483cf801f0d0)) + +## [2.6.0](https://github.com/broofa/mime/compare/v2.5.2...v2.6.0) (2021-11-02) + + +### Features + +* mime-db@1.50.0 ([cef0cc4](https://github.com/broofa/mime/commit/cef0cc484ff6d05ff1e12b54ca3e8b856fbc14d8)) + +### [2.5.2](https://github.com/broofa/mime/compare/v2.5.0...v2.5.2) (2021-02-17) + + +### Bug Fixes + +* update to mime-db@1.46.0, fixes [#253](https://github.com/broofa/mime/issues/253) ([f10e6aa](https://github.com/broofa/mime/commit/f10e6aa62e1356de7e2491d7fb4374c8dac65800)) + +## [2.5.0](https://github.com/broofa/mime/compare/v2.4.7...v2.5.0) (2021-01-16) + + +### Features + +* improved CLI ([#244](https://github.com/broofa/mime/issues/244)) ([c8a8356](https://github.com/broofa/mime/commit/c8a8356e3b27f3ef46b64b89b428fdb547b14d5f)) + +### [2.4.7](https://github.com/broofa/mime/compare/v2.4.6...v2.4.7) (2020-12-16) + + +### Bug Fixes + +* update to latest mime-db ([43b09ef](https://github.com/broofa/mime/commit/43b09eff0233eacc449af2b1f99a19ba9e104a44)) + +### [2.4.6](https://github.com/broofa/mime/compare/v2.4.5...v2.4.6) (2020-05-27) + + +### Bug Fixes + +* add cli.js to package.json files ([#237](https://github.com/broofa/mime/issues/237)) ([6c070bc](https://github.com/broofa/mime/commit/6c070bc298fa12a48e2ed126fbb9de641a1e7ebc)) + +### [2.4.5](https://github.com/broofa/mime/compare/v2.4.4...v2.4.5) (2020-05-01) + + +### Bug Fixes + +* fix [#236](https://github.com/broofa/mime/issues/236) ([7f4ecd0](https://github.com/broofa/mime/commit/7f4ecd0d850ed22c9e3bfda2c11fc74e4dde12a7)) +* update to latest mime-db ([c5cb3f2](https://github.com/broofa/mime/commit/c5cb3f2ab8b07642a066efbde1142af1b90c927b)) + +### [2.4.4](https://github.com/broofa/mime/compare/v2.4.3...v2.4.4) (2019-06-07) + + + +### [2.4.3](https://github.com/broofa/mime/compare/v2.4.2...v2.4.3) (2019-05-15) + + + +### [2.4.2](https://github.com/broofa/mime/compare/v2.4.1...v2.4.2) (2019-04-07) + + +### Bug Fixes + +* don't use arrow function introduced in 2.4.1 ([2e00b5c](https://github.com/broofa/mime/commit/2e00b5c)) + + + +### [2.4.1](https://github.com/broofa/mime/compare/v2.4.0...v2.4.1) (2019-04-03) + + +### Bug Fixes + +* update MDN and mime-db types ([3e567a9](https://github.com/broofa/mime/commit/3e567a9)) + + + +# [2.4.0](https://github.com/broofa/mime/compare/v2.3.1...v2.4.0) (2018-11-26) + + +### Features + +* Bind exported methods ([9d2a7b8](https://github.com/broofa/mime/commit/9d2a7b8)) +* update to mime-db@1.37.0 ([49e6e41](https://github.com/broofa/mime/commit/49e6e41)) + + + +### [2.3.1](https://github.com/broofa/mime/compare/v2.3.0...v2.3.1) (2018-04-11) + + +### Bug Fixes + +* fix [#198](https://github.com/broofa/mime/issues/198) ([25ca180](https://github.com/broofa/mime/commit/25ca180)) + + + +# [2.3.0](https://github.com/broofa/mime/compare/v2.2.2...v2.3.0) (2018-04-11) + + +### Bug Fixes + +* fix [#192](https://github.com/broofa/mime/issues/192) ([5c35df6](https://github.com/broofa/mime/commit/5c35df6)) + + +### Features + +* add travis-ci testing ([d64160f](https://github.com/broofa/mime/commit/d64160f)) + + + +### [2.2.2](https://github.com/broofa/mime/compare/v2.2.1...v2.2.2) (2018-03-30) + + +### Bug Fixes + +* update types files to mime-db@1.32.0 ([85aac16](https://github.com/broofa/mime/commit/85aac16)) + + +### [2.2.1](https://github.com/broofa/mime/compare/v2.2.0...v2.2.1) (2018-03-30) + + +### Bug Fixes + +* Retain type->extension mappings for non-default types. Fixes [#180](https://github.com/broofa/mime/issues/180) ([b5c83fb](https://github.com/broofa/mime/commit/b5c83fb)) + + + +# [2.2.0](https://github.com/broofa/mime/compare/v2.1.0...v2.2.0) (2018-01-04) + + +### Features + +* Retain type->extension mappings for non-default types. Fixes [#180](https://github.com/broofa/mime/issues/180) ([10f82ac](https://github.com/broofa/mime/commit/10f82ac)) + + + +# [2.1.0](https://github.com/broofa/mime/compare/v2.0.5...v2.1.0) (2017-12-22) + + +### Features + +* Upgrade to mime-db@1.32.0. Fixes [#185](https://github.com/broofa/mime/issues/185) ([3f775ba](https://github.com/broofa/mime/commit/3f775ba)) + + + +### [2.0.5](https://github.com/broofa/mime/compare/v2.0.1...v2.0.5) (2017-12-22) + + +### Bug Fixes + +* ES5 support (back to node v0.4) ([f14ccb6](https://github.com/broofa/mime/commit/f14ccb6)) + + + +# Changelog + +### v2.0.4 (24/11/2017) +- [**closed**] Switch to mime-score module for resolving extension contention issues. [#182](https://github.com/broofa/mime/issues/182) +- [**closed**] Update mime-db to 1.31.0 in v1.x branch [#181](https://github.com/broofa/mime/issues/181) + +--- + +## v1.5.0 (22/11/2017) +- [**closed**] need ES5 version ready in npm package [#179](https://github.com/broofa/mime/issues/179) +- [**closed**] mime-db no trace of iWork - pages / numbers / etc. [#178](https://github.com/broofa/mime/issues/178) +- [**closed**] How it works in brownser ? [#176](https://github.com/broofa/mime/issues/176) +- [**closed**] Missing `./Mime` [#175](https://github.com/broofa/mime/issues/175) +- [**closed**] Vulnerable Regular Expression [#167](https://github.com/broofa/mime/issues/167) + +--- + +### v2.0.3 (25/09/2017) +*No changelog for this release.* + +--- + +### v1.4.1 (25/09/2017) +- [**closed**] Issue when bundling with webpack [#172](https://github.com/broofa/mime/issues/172) + +--- + +### v2.0.2 (15/09/2017) +- [**V2**] fs.readFileSync is not a function [#165](https://github.com/broofa/mime/issues/165) +- [**closed**] The extension for video/quicktime should map to .mov, not .qt [#164](https://github.com/broofa/mime/issues/164) +- [**V2**] [v2 Feedback request] Mime class API [#163](https://github.com/broofa/mime/issues/163) +- [**V2**] [v2 Feedback request] Resolving conflicts over extensions [#162](https://github.com/broofa/mime/issues/162) +- [**V2**] Allow callers to load module with official, full, or no defined types. [#161](https://github.com/broofa/mime/issues/161) +- [**V2**] Use "facets" to resolve extension conflicts [#160](https://github.com/broofa/mime/issues/160) +- [**V2**] Remove fs and path dependencies [#152](https://github.com/broofa/mime/issues/152) +- [**V2**] Default content-type should not be application/octet-stream [#139](https://github.com/broofa/mime/issues/139) +- [**V2**] reset mime-types [#124](https://github.com/broofa/mime/issues/124) +- [**V2**] Extensionless paths should return null or false [#113](https://github.com/broofa/mime/issues/113) + +--- + +### v2.0.1 (14/09/2017) +- [**closed**] Changelog for v2.0 does not mention breaking changes [#171](https://github.com/broofa/mime/issues/171) +- [**closed**] MIME breaking with 'class' declaration as it is without 'use strict mode' [#170](https://github.com/broofa/mime/issues/170) + +--- + +## v2.0.0 (12/09/2017) +- [**closed**] woff and woff2 [#168](https://github.com/broofa/mime/issues/168) + +--- + +## v1.4.0 (28/08/2017) +- [**closed**] support for ac3 voc files [#159](https://github.com/broofa/mime/issues/159) +- [**closed**] Help understanding change from application/xml to text/xml [#158](https://github.com/broofa/mime/issues/158) +- [**closed**] no longer able to override mimetype [#157](https://github.com/broofa/mime/issues/157) +- [**closed**] application/vnd.adobe.photoshop [#147](https://github.com/broofa/mime/issues/147) +- [**closed**] Directories should appear as something other than application/octet-stream [#135](https://github.com/broofa/mime/issues/135) +- [**closed**] requested features [#131](https://github.com/broofa/mime/issues/131) +- [**closed**] Make types.json loading optional? [#129](https://github.com/broofa/mime/issues/129) +- [**closed**] Cannot find module './types.json' [#120](https://github.com/broofa/mime/issues/120) +- [**V2**] .wav files show up as "audio/x-wav" instead of "audio/x-wave" [#118](https://github.com/broofa/mime/issues/118) +- [**closed**] Don't be a pain in the ass for node community [#108](https://github.com/broofa/mime/issues/108) +- [**closed**] don't make default_type global [#78](https://github.com/broofa/mime/issues/78) +- [**closed**] mime.extension() fails if the content-type is parameterized [#74](https://github.com/broofa/mime/issues/74) + +--- + +### v1.3.6 (11/05/2017) +- [**closed**] .md should be text/markdown as of March 2016 [#154](https://github.com/broofa/mime/issues/154) +- [**closed**] Error while installing mime [#153](https://github.com/broofa/mime/issues/153) +- [**closed**] application/manifest+json [#149](https://github.com/broofa/mime/issues/149) +- [**closed**] Dynamic adaptive streaming over HTTP (DASH) file extension typo [#141](https://github.com/broofa/mime/issues/141) +- [**closed**] charsets image/png undefined [#140](https://github.com/broofa/mime/issues/140) +- [**closed**] Mime-db dependency out of date [#130](https://github.com/broofa/mime/issues/130) +- [**closed**] how to support plist? [#126](https://github.com/broofa/mime/issues/126) +- [**closed**] how does .types file format look like? [#123](https://github.com/broofa/mime/issues/123) +- [**closed**] Feature: support for expanding MIME patterns [#121](https://github.com/broofa/mime/issues/121) +- [**closed**] DEBUG_MIME doesn't work [#117](https://github.com/broofa/mime/issues/117) + +--- + +### v1.3.4 (06/02/2015) +*No changelog for this release.* + +--- + +### v1.3.3 (06/02/2015) +*No changelog for this release.* + +--- + +### v1.3.1 (05/02/2015) +- [**closed**] Consider adding support for Handlebars .hbs file ending [#111](https://github.com/broofa/mime/issues/111) +- [**closed**] Consider adding support for hjson. [#110](https://github.com/broofa/mime/issues/110) +- [**closed**] Add mime type for Opus audio files [#94](https://github.com/broofa/mime/issues/94) +- [**closed**] Consider making the `Requesting New Types` information more visible [#77](https://github.com/broofa/mime/issues/77) + +--- + +## v1.3.0 (05/02/2015) +- [**closed**] Add common name? [#114](https://github.com/broofa/mime/issues/114) +- [**closed**] application/x-yaml [#104](https://github.com/broofa/mime/issues/104) +- [**closed**] Add mime type for WOFF file format 2.0 [#102](https://github.com/broofa/mime/issues/102) +- [**closed**] application/x-msi for .msi [#99](https://github.com/broofa/mime/issues/99) +- [**closed**] Add mimetype for gettext translation files [#98](https://github.com/broofa/mime/issues/98) +- [**closed**] collaborators [#88](https://github.com/broofa/mime/issues/88) +- [**closed**] getting errot in installation of mime module...any1 can help? [#87](https://github.com/broofa/mime/issues/87) +- [**closed**] should application/json's charset be utf8? [#86](https://github.com/broofa/mime/issues/86) +- [**closed**] Add "license" and "licenses" to package.json [#81](https://github.com/broofa/mime/issues/81) +- [**closed**] lookup with extension-less file on Windows returns wrong type [#68](https://github.com/broofa/mime/issues/68) + +--- + +### v1.2.11 (15/08/2013) +- [**closed**] Update mime.types [#65](https://github.com/broofa/mime/issues/65) +- [**closed**] Publish a new version [#63](https://github.com/broofa/mime/issues/63) +- [**closed**] README should state upfront that "application/octet-stream" is default for unknown extension [#55](https://github.com/broofa/mime/issues/55) +- [**closed**] Suggested improvement to the charset API [#52](https://github.com/broofa/mime/issues/52) + +--- + +### v1.2.10 (25/07/2013) +- [**closed**] Mime type for woff files should be application/font-woff and not application/x-font-woff [#62](https://github.com/broofa/mime/issues/62) +- [**closed**] node.types in conflict with mime.types [#51](https://github.com/broofa/mime/issues/51) + +--- + +### v1.2.9 (17/01/2013) +- [**closed**] Please update "mime" NPM [#49](https://github.com/broofa/mime/issues/49) +- [**closed**] Please add semicolon [#46](https://github.com/broofa/mime/issues/46) +- [**closed**] parse full mime types [#43](https://github.com/broofa/mime/issues/43) + +--- + +### v1.2.8 (10/01/2013) +- [**closed**] /js directory mime is application/javascript. Is it correct? [#47](https://github.com/broofa/mime/issues/47) +- [**closed**] Add mime types for lua code. [#45](https://github.com/broofa/mime/issues/45) + +--- + +### v1.2.7 (19/10/2012) +- [**closed**] cannot install 1.2.7 via npm [#41](https://github.com/broofa/mime/issues/41) +- [**closed**] Transfer ownership to @broofa [#36](https://github.com/broofa/mime/issues/36) +- [**closed**] it's wrong to set charset to UTF-8 for text [#30](https://github.com/broofa/mime/issues/30) +- [**closed**] Allow multiple instances of MIME types container [#27](https://github.com/broofa/mime/issues/27) diff --git a/node_modules/mime/LICENSE b/node_modules/mime/LICENSE new file mode 100644 index 0000000..d3f46f7 --- /dev/null +++ b/node_modules/mime/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2010 Benjamin Thomas, Robert Kieffer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/mime/Mime.js b/node_modules/mime/Mime.js new file mode 100644 index 0000000..969a66e --- /dev/null +++ b/node_modules/mime/Mime.js @@ -0,0 +1,97 @@ +'use strict'; + +/** + * @param typeMap [Object] Map of MIME type -> Array[extensions] + * @param ... + */ +function Mime() { + this._types = Object.create(null); + this._extensions = Object.create(null); + + for (let i = 0; i < arguments.length; i++) { + this.define(arguments[i]); + } + + this.define = this.define.bind(this); + this.getType = this.getType.bind(this); + this.getExtension = this.getExtension.bind(this); +} + +/** + * Define mimetype -> extension mappings. Each key is a mime-type that maps + * to an array of extensions associated with the type. The first extension is + * used as the default extension for the type. + * + * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); + * + * If a type declares an extension that has already been defined, an error will + * be thrown. To suppress this error and force the extension to be associated + * with the new type, pass `force`=true. Alternatively, you may prefix the + * extension with "*" to map the type to extension, without mapping the + * extension to the type. + * + * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']}); + * + * + * @param map (Object) type definitions + * @param force (Boolean) if true, force overriding of existing definitions + */ +Mime.prototype.define = function(typeMap, force) { + for (let type in typeMap) { + let extensions = typeMap[type].map(function(t) { + return t.toLowerCase(); + }); + type = type.toLowerCase(); + + for (let i = 0; i < extensions.length; i++) { + const ext = extensions[i]; + + // '*' prefix = not the preferred type for this extension. So fixup the + // extension, and skip it. + if (ext[0] === '*') { + continue; + } + + if (!force && (ext in this._types)) { + throw new Error( + 'Attempt to change mapping for "' + ext + + '" extension from "' + this._types[ext] + '" to "' + type + + '". Pass `force=true` to allow this, otherwise remove "' + ext + + '" from the list of extensions for "' + type + '".' + ); + } + + this._types[ext] = type; + } + + // Use first extension as default + if (force || !this._extensions[type]) { + const ext = extensions[0]; + this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1); + } + } +}; + +/** + * Lookup a mime type based on extension + */ +Mime.prototype.getType = function(path) { + path = String(path); + let last = path.replace(/^.*[/\\]/, '').toLowerCase(); + let ext = last.replace(/^.*\./, '').toLowerCase(); + + let hasPath = last.length < path.length; + let hasDot = ext.length < last.length - 1; + + return (hasDot || !hasPath) && this._types[ext] || null; +}; + +/** + * Return file extension associated with a mime type + */ +Mime.prototype.getExtension = function(type) { + type = /^\s*([^;\s]*)/.test(type) && RegExp.$1; + return type && this._extensions[type.toLowerCase()] || null; +}; + +module.exports = Mime; diff --git a/node_modules/mime/README.md b/node_modules/mime/README.md new file mode 100644 index 0000000..fc816cb --- /dev/null +++ b/node_modules/mime/README.md @@ -0,0 +1,178 @@ + +# Mime + +A comprehensive, compact MIME type module. + +[![Build Status](https://travis-ci.org/broofa/mime.svg?branch=master)](https://travis-ci.org/broofa/mime) + +## Install + +### NPM +``` +npm install mime +``` + +### Browser + +It is recommended that you use a bundler such as +[webpack](https://webpack.github.io/) or [browserify](http://browserify.org/) to +package your code. However, browser-ready versions are available via +skypack.dev as follows: +``` +// Full version + +``` + +``` +// "lite" version + +``` + +## Quick Start + +For the full version (800+ MIME types, 1,000+ extensions): + +```javascript +const mime = require('mime'); + +mime.getType('txt'); // ⇨ 'text/plain' +mime.getExtension('text/plain'); // ⇨ 'txt' +``` + +See [Mime API](#mime-api) below for API details. + +## Lite Version + +The "lite" version of this module omits vendor-specific (`*/vnd.*`) and +experimental (`*/x-*`) types. It weighs in at ~2.5KB, compared to 8KB for the +full version. To load the lite version: + +```javascript +const mime = require('mime/lite'); +``` + +## Mime .vs. mime-types .vs. mime-db modules + +For those of you wondering about the difference between these [popular] NPM modules, +here's a brief rundown ... + +[`mime-db`](https://github.com/jshttp/mime-db) is "the source of +truth" for MIME type information. It is not an API. Rather, it is a canonical +dataset of mime type definitions pulled from IANA, Apache, NGINX, and custom mappings +submitted by the Node.js community. + +[`mime-types`](https://github.com/jshttp/mime-types) is a thin +wrapper around mime-db that provides an API drop-in compatible(ish) with `mime @ < v1.3.6` API. + +`mime` is, as of v2, a self-contained module bundled with a pre-optimized version +of the `mime-db` dataset. It provides a simplified API with the following characteristics: + +* Intelligently resolved type conflicts (See [mime-score](https://github.com/broofa/mime-score) for details) +* Method naming consistent with industry best-practices +* Compact footprint. E.g. The minified+compressed sizes of the various modules: + +Module | Size +--- | --- +`mime-db` | 18 KB +`mime-types` | same as mime-db +`mime` | 8 KB +`mime/lite` | 2 KB + +## Mime API + +Both `require('mime')` and `require('mime/lite')` return instances of the MIME +class, documented below. + +Note: Inputs to this API are case-insensitive. Outputs (returned values) will +be lowercase. + +### new Mime(typeMap, ... more maps) + +Most users of this module will not need to create Mime instances directly. +However if you would like to create custom mappings, you may do so as follows +... + +```javascript +// Require Mime class +const Mime = require('mime/Mime'); + +// Define mime type -> extensions map +const typeMap = { + 'text/abc': ['abc', 'alpha', 'bet'], + 'text/def': ['leppard'] +}; + +// Create and use Mime instance +const myMime = new Mime(typeMap); +myMime.getType('abc'); // ⇨ 'text/abc' +myMime.getExtension('text/def'); // ⇨ 'leppard' +``` + +If more than one map argument is provided, each map is `define()`ed (see below), in order. + +### mime.getType(pathOrExtension) + +Get mime type for the given path or extension. E.g. + +```javascript +mime.getType('js'); // ⇨ 'application/javascript' +mime.getType('json'); // ⇨ 'application/json' + +mime.getType('txt'); // ⇨ 'text/plain' +mime.getType('dir/text.txt'); // ⇨ 'text/plain' +mime.getType('dir\\text.txt'); // ⇨ 'text/plain' +mime.getType('.text.txt'); // ⇨ 'text/plain' +mime.getType('.txt'); // ⇨ 'text/plain' +``` + +`null` is returned in cases where an extension is not detected or recognized + +```javascript +mime.getType('foo/txt'); // ⇨ null +mime.getType('bogus_type'); // ⇨ null +``` + +### mime.getExtension(type) +Get extension for the given mime type. Charset options (often included in +Content-Type headers) are ignored. + +```javascript +mime.getExtension('text/plain'); // ⇨ 'txt' +mime.getExtension('application/json'); // ⇨ 'json' +mime.getExtension('text/html; charset=utf8'); // ⇨ 'html' +``` + +### mime.define(typeMap[, force = false]) + +Define [more] type mappings. + +`typeMap` is a map of type -> extensions, as documented in `new Mime`, above. + +By default this method will throw an error if you try to map a type to an +extension that is already assigned to another type. Passing `true` for the +`force` argument will suppress this behavior (overriding any previous mapping). + +```javascript +mime.define({'text/x-abc': ['abc', 'abcd']}); + +mime.getType('abcd'); // ⇨ 'text/x-abc' +mime.getExtension('text/x-abc') // ⇨ 'abc' +``` + +## Command Line + + mime [path_or_extension] + +E.g. + + > mime scripts/jquery.js + application/javascript + +---- +Markdown generated from [src/README_js.md](src/README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd) \ No newline at end of file diff --git a/node_modules/mime/cli.js b/node_modules/mime/cli.js new file mode 100644 index 0000000..ab70a49 --- /dev/null +++ b/node_modules/mime/cli.js @@ -0,0 +1,46 @@ +#!/usr/bin/env node + +'use strict'; + +process.title = 'mime'; +let mime = require('.'); +let pkg = require('./package.json'); +let args = process.argv.splice(2); + +if (args.includes('--version') || args.includes('-v') || args.includes('--v')) { + console.log(pkg.version); + process.exit(0); +} else if (args.includes('--name') || args.includes('-n') || args.includes('--n')) { + console.log(pkg.name); + process.exit(0); +} else if (args.includes('--help') || args.includes('-h') || args.includes('--h')) { + console.log(pkg.name + ' - ' + pkg.description + '\n'); + console.log(`Usage: + + mime [flags] [path_or_extension] + + Flags: + --help, -h Show this message + --version, -v Display the version + --name, -n Print the name of the program + + Note: the command will exit after it executes if a command is specified + The path_or_extension is the path to the file or the extension of the file. + + Examples: + mime --help + mime --version + mime --name + mime -v + mime src/log.js + mime new.py + mime foo.sh + `); + process.exit(0); +} + +let file = args[0]; +let type = mime.getType(file); + +process.stdout.write(type + '\n'); + diff --git a/node_modules/mime/index.js b/node_modules/mime/index.js new file mode 100644 index 0000000..fadcf8d --- /dev/null +++ b/node_modules/mime/index.js @@ -0,0 +1,4 @@ +'use strict'; + +let Mime = require('./Mime'); +module.exports = new Mime(require('./types/standard'), require('./types/other')); diff --git a/node_modules/mime/lite.js b/node_modules/mime/lite.js new file mode 100644 index 0000000..835cffb --- /dev/null +++ b/node_modules/mime/lite.js @@ -0,0 +1,4 @@ +'use strict'; + +let Mime = require('./Mime'); +module.exports = new Mime(require('./types/standard')); diff --git a/node_modules/mime/package.json b/node_modules/mime/package.json new file mode 100644 index 0000000..84f5132 --- /dev/null +++ b/node_modules/mime/package.json @@ -0,0 +1,52 @@ +{ + "author": { + "name": "Robert Kieffer", + "url": "http://github.com/broofa", + "email": "robert@broofa.com" + }, + "engines": { + "node": ">=10.0.0" + }, + "bin": { + "mime": "cli.js" + }, + "contributors": [], + "description": "A comprehensive library for mime-type mapping", + "license": "MIT", + "dependencies": {}, + "devDependencies": { + "benchmark": "*", + "chalk": "4.1.2", + "eslint": "8.1.0", + "mime-db": "1.50.0", + "mime-score": "1.2.0", + "mime-types": "2.1.33", + "mocha": "9.1.3", + "runmd": "*", + "standard-version": "9.3.2" + }, + "files": [ + "index.js", + "lite.js", + "Mime.js", + "cli.js", + "/types" + ], + "scripts": { + "prepare": "node src/build.js && runmd --output README.md src/README_js.md", + "release": "standard-version", + "benchmark": "node src/benchmark.js", + "md": "runmd --watch --output README.md src/README_js.md", + "test": "mocha src/test.js" + }, + "keywords": [ + "util", + "mime" + ], + "name": "mime", + "repository": { + "url": "https://github.com/broofa/mime", + "type": "git" + }, + "version": "3.0.0" +} diff --git a/node_modules/mime/types/other.js b/node_modules/mime/types/other.js new file mode 100644 index 0000000..bb6a035 --- /dev/null +++ b/node_modules/mime/types/other.js @@ -0,0 +1 @@ +module.exports = {"application/prs.cww":["cww"],"application/vnd.1000minds.decision-model+xml":["1km"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.keynote":["key"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.balsamiq.bmml+xml":["bmml"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.citationstyles.style+xml":["csl"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dbf":["dbf"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mapbox-vector-tile":["mvt"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["*stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.ac+xml":["*ac"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openblox.game+xml":["obgx"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openstreetmap.data+xml":["osm"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.rar":["rar"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.software602.filler.form+xml":["fo"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.syncml.dmddf+xml":["ddf"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["*dmg"],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":["*bdoc"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["*deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["*iso"],"application/x-iwork-keynote-sffkey":["*key"],"application/x-iwork-numbers-sffnumbers":["*numbers"],"application/x-iwork-pages-sffpages":["*pages"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-keepass2":["kdbx"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":["*exe"],"application/x-msdownload":["*exe","*dll","com","bat","*msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["*wmf","*wmz","*emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":["*prc","*pdb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["*rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["*obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["*xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["*m4a"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":["*ra"],"audio/x-wav":["*wav"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/prs.btif":["btif"],"image/prs.pti":["pti"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.airzip.accelerator.azv":["azv"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["*sub"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.microsoft.icon":["ico"],"image/vnd.ms-dds":["dds"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.pco.b16":["b16"],"image/vnd.tencent.tap":["tap"],"image/vnd.valve.source.texture":["vtf"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/vnd.zbrush.pcx":["pcx"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["*ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":["*bmp"],"image/x-pcx":["*pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/vnd.wfa.wsc":["wsc"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.opengex":["ogex"],"model/vnd.parasolid.transmit.binary":["x_b"],"model/vnd.parasolid.transmit.text":["x_t"],"model/vnd.sap.vds":["vds"],"model/vnd.usdz+zip":["usdz"],"model/vnd.valve.source.compiled-map":["bsp"],"model/vnd.vtu":["vtu"],"text/prs.lines.tag":["dsc"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":["*org"],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]}; \ No newline at end of file diff --git a/node_modules/mime/types/standard.js b/node_modules/mime/types/standard.js new file mode 100644 index 0000000..5ee9937 --- /dev/null +++ b/node_modules/mime/types/standard.js @@ -0,0 +1 @@ +module.exports = {"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["es","ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]}; \ No newline at end of file diff --git a/node_modules/ms/index.js b/node_modules/ms/index.js new file mode 100644 index 0000000..ea734fb --- /dev/null +++ b/node_modules/ms/index.js @@ -0,0 +1,162 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function (val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} diff --git a/node_modules/ms/license.md b/node_modules/ms/license.md new file mode 100644 index 0000000..fa5d39b --- /dev/null +++ b/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Vercel, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/ms/package.json b/node_modules/ms/package.json new file mode 100644 index 0000000..4997189 --- /dev/null +++ b/node_modules/ms/package.json @@ -0,0 +1,38 @@ +{ + "name": "ms", + "version": "2.1.3", + "description": "Tiny millisecond conversion utility", + "repository": "vercel/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "4.18.2", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1", + "prettier": "2.0.5" + } +} diff --git a/node_modules/ms/readme.md b/node_modules/ms/readme.md new file mode 100644 index 0000000..0fc1abb --- /dev/null +++ b/node_modules/ms/readme.md @@ -0,0 +1,59 @@ +# ms + +![CI](https://github.com/vercel/ms/workflows/CI/badge.svg) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +ms('-3 days') // -259200000 +ms('-1h') // -3600000 +ms('-200') // -200 +``` + +### Convert from Milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(-3 * 60000) // "-3m" +ms(ms('10 hours')) // "10h" +``` + +### Time Format Written-Out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(-3 * 60000, { long: true }) // "-3 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [Node.js](https://nodejs.org) and in the browser +- If a number is supplied to `ms`, a string with a unit is returned +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) +- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned + +## Related Packages + +- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. + +## Caught a Bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/node-fetch/LICENSE.md b/node_modules/node-fetch/LICENSE.md new file mode 100644 index 0000000..660ffec --- /dev/null +++ b/node_modules/node-fetch/LICENSE.md @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 David Frank + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/node-fetch/README.md b/node_modules/node-fetch/README.md new file mode 100644 index 0000000..55f09b7 --- /dev/null +++ b/node_modules/node-fetch/README.md @@ -0,0 +1,634 @@ +node-fetch +========== + +[![npm version][npm-image]][npm-url] +[![build status][travis-image]][travis-url] +[![coverage status][codecov-image]][codecov-url] +[![install size][install-size-image]][install-size-url] +[![Discord][discord-image]][discord-url] + +A light-weight module that brings `window.fetch` to Node.js + +(We are looking for [v2 maintainers and collaborators](https://github.com/bitinn/node-fetch/issues/567)) + +[![Backers][opencollective-image]][opencollective-url] + + + +- [Motivation](#motivation) +- [Features](#features) +- [Difference from client-side fetch](#difference-from-client-side-fetch) +- [Installation](#installation) +- [Loading and configuring the module](#loading-and-configuring-the-module) +- [Common Usage](#common-usage) + - [Plain text or HTML](#plain-text-or-html) + - [JSON](#json) + - [Simple Post](#simple-post) + - [Post with JSON](#post-with-json) + - [Post with form parameters](#post-with-form-parameters) + - [Handling exceptions](#handling-exceptions) + - [Handling client and server errors](#handling-client-and-server-errors) +- [Advanced Usage](#advanced-usage) + - [Streams](#streams) + - [Buffer](#buffer) + - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data) + - [Extract Set-Cookie Header](#extract-set-cookie-header) + - [Post data using a file stream](#post-data-using-a-file-stream) + - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart) + - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal) +- [API](#api) + - [fetch(url[, options])](#fetchurl-options) + - [Options](#options) + - [Class: Request](#class-request) + - [Class: Response](#class-response) + - [Class: Headers](#class-headers) + - [Interface: Body](#interface-body) + - [Class: FetchError](#class-fetcherror) +- [License](#license) +- [Acknowledgement](#acknowledgement) + + + +## Motivation + +Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime. + +See Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side). + +## Features + +- Stay consistent with `window.fetch` API. +- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences. +- Use native promise but allow substituting it with [insert your favorite promise library]. +- Use native Node streams for body on both request and response. +- Decode content encoding (gzip/deflate) properly and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically. +- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors](ERROR-HANDLING.md) for troubleshooting. + +## Difference from client-side fetch + +- See [Known Differences](LIMITS.md) for details. +- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue. +- Pull requests are welcomed too! + +## Installation + +Current stable release (`2.x`) + +```sh +$ npm install node-fetch +``` + +## Loading and configuring the module +We suggest you load the module via `require` until the stabilization of ES modules in node: +```js +const fetch = require('node-fetch'); +``` + +If you are using a Promise library other than native, set it through `fetch.Promise`: +```js +const Bluebird = require('bluebird'); + +fetch.Promise = Bluebird; +``` + +## Common Usage + +NOTE: The documentation below is up-to-date with `2.x` releases; see the [`1.x` readme](https://github.com/bitinn/node-fetch/blob/1.x/README.md), [changelog](https://github.com/bitinn/node-fetch/blob/1.x/CHANGELOG.md) and [2.x upgrade guide](UPGRADE-GUIDE.md) for the differences. + +#### Plain text or HTML +```js +fetch('https://github.com/') + .then(res => res.text()) + .then(body => console.log(body)); +``` + +#### JSON + +```js + +fetch('https://api.github.com/users/github') + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Simple Post +```js +fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' }) + .then(res => res.json()) // expecting a json response + .then(json => console.log(json)); +``` + +#### Post with JSON + +```js +const body = { a: 1 }; + +fetch('https://httpbin.org/post', { + method: 'post', + body: JSON.stringify(body), + headers: { 'Content-Type': 'application/json' }, + }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Post with form parameters +`URLSearchParams` is available in Node.js as of v7.5.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods. + +NOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such: + +```js +const { URLSearchParams } = require('url'); + +const params = new URLSearchParams(); +params.append('a', 1); + +fetch('https://httpbin.org/post', { method: 'POST', body: params }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Handling exceptions +NOTE: 3xx-5xx responses are *NOT* exceptions and should be handled in `then()`; see the next section for more information. + +Adding a catch to the fetch promise chain will catch *all* exceptions, such as errors originating from node core libraries, network errors and operational errors, which are instances of FetchError. See the [error handling document](ERROR-HANDLING.md) for more details. + +```js +fetch('https://domain.invalid/') + .catch(err => console.error(err)); +``` + +#### Handling client and server errors +It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses: + +```js +function checkStatus(res) { + if (res.ok) { // res.status >= 200 && res.status < 300 + return res; + } else { + throw MyCustomError(res.statusText); + } +} + +fetch('https://httpbin.org/status/400') + .then(checkStatus) + .then(res => console.log('will not get here...')) +``` + +## Advanced Usage + +#### Streams +The "Node.js way" is to use streams when possible: + +```js +fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') + .then(res => { + const dest = fs.createWriteStream('./octocat.png'); + res.body.pipe(dest); + }); +``` + +In Node.js 14 you can also use async iterators to read `body`; however, be careful to catch +errors -- the longer a response runs, the more likely it is to encounter an error. + +```js +const fetch = require('node-fetch'); +const response = await fetch('https://httpbin.org/stream/3'); +try { + for await (const chunk of response.body) { + console.dir(JSON.parse(chunk.toString())); + } +} catch (err) { + console.error(err.stack); +} +``` + +In Node.js 12 you can also use async iterators to read `body`; however, async iterators with streams +did not mature until Node.js 14, so you need to do some extra work to ensure you handle errors +directly from the stream and wait on it response to fully close. + +```js +const fetch = require('node-fetch'); +const read = async body => { + let error; + body.on('error', err => { + error = err; + }); + for await (const chunk of body) { + console.dir(JSON.parse(chunk.toString())); + } + return new Promise((resolve, reject) => { + body.on('close', () => { + error ? reject(error) : resolve(); + }); + }); +}; +try { + const response = await fetch('https://httpbin.org/stream/3'); + await read(response.body); +} catch (err) { + console.error(err.stack); +} +``` + +#### Buffer +If you prefer to cache binary data in full, use buffer(). (NOTE: `buffer()` is a `node-fetch`-only API) + +```js +const fileType = require('file-type'); + +fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') + .then(res => res.buffer()) + .then(buffer => fileType(buffer)) + .then(type => { /* ... */ }); +``` + +#### Accessing Headers and other Meta data +```js +fetch('https://github.com/') + .then(res => { + console.log(res.ok); + console.log(res.status); + console.log(res.statusText); + console.log(res.headers.raw()); + console.log(res.headers.get('content-type')); + }); +``` + +#### Extract Set-Cookie Header + +Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API. + +```js +fetch(url).then(res => { + // returns an array of values, instead of a string of comma-separated values + console.log(res.headers.raw()['set-cookie']); +}); +``` + +#### Post data using a file stream + +```js +const { createReadStream } = require('fs'); + +const stream = createReadStream('input.txt'); + +fetch('https://httpbin.org/post', { method: 'POST', body: stream }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Post with form-data (detect multipart) + +```js +const FormData = require('form-data'); + +const form = new FormData(); +form.append('a', 1); + +fetch('https://httpbin.org/post', { method: 'POST', body: form }) + .then(res => res.json()) + .then(json => console.log(json)); + +// OR, using custom headers +// NOTE: getHeaders() is non-standard API + +const form = new FormData(); +form.append('a', 1); + +const options = { + method: 'POST', + body: form, + headers: form.getHeaders() +} + +fetch('https://httpbin.org/post', options) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Request cancellation with AbortSignal + +> NOTE: You may cancel streamed requests only on Node >= v8.0.0 + +You may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller). + +An example of timing out a request after 150ms could be achieved as the following: + +```js +import AbortController from 'abort-controller'; + +const controller = new AbortController(); +const timeout = setTimeout( + () => { controller.abort(); }, + 150, +); + +fetch(url, { signal: controller.signal }) + .then(res => res.json()) + .then( + data => { + useData(data) + }, + err => { + if (err.name === 'AbortError') { + // request was aborted + } + }, + ) + .finally(() => { + clearTimeout(timeout); + }); +``` + +See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) for more examples. + + +## API + +### fetch(url[, options]) + +- `url` A string representing the URL for fetching +- `options` [Options](#fetch-options) for the HTTP(S) request +- Returns: Promise<[Response](#class-response)> + +Perform an HTTP(S) fetch. + +`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`. + + +### Options + +The default values are shown after each option key. + +```js +{ + // These properties are part of the Fetch Standard + method: 'GET', + headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below) + body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream + redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect + signal: null, // pass an instance of AbortSignal to optionally abort requests + + // The following properties are node-fetch extensions + follow: 20, // maximum redirect count. 0 to not follow redirect + timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead. + compress: true, // support gzip/deflate content encoding. false to disable + size: 0, // maximum response body size in bytes. 0 to disable + agent: null // http(s).Agent instance or function that returns an instance (see below) +} +``` + +##### Default Headers + +If no values are set, the following request headers will be sent automatically: + +Header | Value +------------------- | -------------------------------------------------------- +`Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ +`Accept` | `*/*` +`Content-Length` | _(automatically calculated, if possible)_ +`Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ +`User-Agent` | `node-fetch/1.0 (+https://github.com/bitinn/node-fetch)` + +Note: when `body` is a `Stream`, `Content-Length` is not set automatically. + +##### Custom Agent + +The `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following: + +- Support self-signed certificate +- Use only IPv4 or IPv6 +- Custom DNS Lookup + +See [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information. + +If no agent is specified, the default agent provided by Node.js is used. Note that [this changed in Node.js 19](https://github.com/nodejs/node/blob/4267b92604ad78584244488e7f7508a690cb80d0/lib/_http_agent.js#L564) to have `keepalive` true by default. If you wish to enable `keepalive` in an earlier version of Node.js, you can override the agent as per the following code sample. + +In addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol. + +```js +const httpAgent = new http.Agent({ + keepAlive: true +}); +const httpsAgent = new https.Agent({ + keepAlive: true +}); + +const options = { + agent: function (_parsedURL) { + if (_parsedURL.protocol == 'http:') { + return httpAgent; + } else { + return httpsAgent; + } + } +} +``` + + +### Class: Request + +An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface. + +Due to the nature of Node.js, the following properties are not implemented at this moment: + +- `type` +- `destination` +- `referrer` +- `referrerPolicy` +- `mode` +- `credentials` +- `cache` +- `integrity` +- `keepalive` + +The following node-fetch extension properties are provided: + +- `follow` +- `compress` +- `counter` +- `agent` + +See [options](#fetch-options) for exact meaning of these extensions. + +#### new Request(input[, options]) + +*(spec-compliant)* + +- `input` A string representing a URL, or another `Request` (which will be cloned) +- `options` [Options][#fetch-options] for the HTTP(S) request + +Constructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request). + +In most cases, directly `fetch(url, options)` is simpler than creating a `Request` object. + + +### Class: Response + +An HTTP(S) response. This class implements the [Body](#iface-body) interface. + +The following properties are not implemented in node-fetch at this moment: + +- `Response.error()` +- `Response.redirect()` +- `type` +- `trailer` + +#### new Response([body[, options]]) + +*(spec-compliant)* + +- `body` A `String` or [`Readable` stream][node-readable] +- `options` A [`ResponseInit`][response-init] options dictionary + +Constructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response). + +Because Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly. + +#### response.ok + +*(spec-compliant)* + +Convenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300. + +#### response.redirected + +*(spec-compliant)* + +Convenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0. + + +### Class: Headers + +This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented. + +#### new Headers([init]) + +*(spec-compliant)* + +- `init` Optional argument to pre-fill the `Headers` object + +Construct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object. + +```js +// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class + +const meta = { + 'Content-Type': 'text/xml', + 'Breaking-Bad': '<3' +}; +const headers = new Headers(meta); + +// The above is equivalent to +const meta = [ + [ 'Content-Type', 'text/xml' ], + [ 'Breaking-Bad', '<3' ] +]; +const headers = new Headers(meta); + +// You can in fact use any iterable objects, like a Map or even another Headers +const meta = new Map(); +meta.set('Content-Type', 'text/xml'); +meta.set('Breaking-Bad', '<3'); +const headers = new Headers(meta); +const copyOfHeaders = new Headers(headers); +``` + + +### Interface: Body + +`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes. + +The following methods are not yet implemented in node-fetch at this moment: + +- `formData()` + +#### body.body + +*(deviation from spec)* + +* Node.js [`Readable` stream][node-readable] + +Data are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable]. + +#### body.bodyUsed + +*(spec-compliant)* + +* `Boolean` + +A boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again. + +#### body.arrayBuffer() +#### body.blob() +#### body.json() +#### body.text() + +*(spec-compliant)* + +* Returns: Promise + +Consume the body and return a promise that will resolve to one of these formats. + +#### body.buffer() + +*(node-fetch extension)* + +* Returns: Promise<Buffer> + +Consume the body and return a promise that will resolve to a Buffer. + +#### body.textConverted() + +*(node-fetch extension)* + +* Returns: Promise<String> + +Identical to `body.text()`, except instead of always converting to UTF-8, encoding sniffing will be performed and text converted to UTF-8 if possible. + +(This API requires an optional dependency of the npm package [encoding](https://www.npmjs.com/package/encoding), which you need to install manually. `webpack` users may see [a warning message](https://github.com/bitinn/node-fetch/issues/412#issuecomment-379007792) due to this optional dependency.) + + +### Class: FetchError + +*(node-fetch extension)* + +An operational error in the fetching process. See [ERROR-HANDLING.md][] for more info. + + +### Class: AbortError + +*(node-fetch extension)* + +An Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info. + +## Acknowledgement + +Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference. + +`node-fetch` v1 was maintained by [@bitinn](https://github.com/bitinn); v2 was maintained by [@TimothyGu](https://github.com/timothygu), [@bitinn](https://github.com/bitinn) and [@jimmywarting](https://github.com/jimmywarting); v2 readme is written by [@jkantr](https://github.com/jkantr). + +## License + +MIT + +[npm-image]: https://flat.badgen.net/npm/v/node-fetch +[npm-url]: https://www.npmjs.com/package/node-fetch +[travis-image]: https://flat.badgen.net/travis/bitinn/node-fetch +[travis-url]: https://travis-ci.org/bitinn/node-fetch +[codecov-image]: https://flat.badgen.net/codecov/c/github/bitinn/node-fetch/master +[codecov-url]: https://codecov.io/gh/bitinn/node-fetch +[install-size-image]: https://flat.badgen.net/packagephobia/install/node-fetch +[install-size-url]: https://packagephobia.now.sh/result?p=node-fetch +[discord-image]: https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord&style=flat-square +[discord-url]: https://discord.gg/Zxbndcm +[opencollective-image]: https://opencollective.com/node-fetch/backers.svg +[opencollective-url]: https://opencollective.com/node-fetch +[whatwg-fetch]: https://fetch.spec.whatwg.org/ +[response-init]: https://fetch.spec.whatwg.org/#responseinit +[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams +[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers +[LIMITS.md]: https://github.com/bitinn/node-fetch/blob/master/LIMITS.md +[ERROR-HANDLING.md]: https://github.com/bitinn/node-fetch/blob/master/ERROR-HANDLING.md +[UPGRADE-GUIDE.md]: https://github.com/bitinn/node-fetch/blob/master/UPGRADE-GUIDE.md diff --git a/node_modules/node-fetch/browser.js b/node_modules/node-fetch/browser.js new file mode 100644 index 0000000..ee86265 --- /dev/null +++ b/node_modules/node-fetch/browser.js @@ -0,0 +1,25 @@ +"use strict"; + +// ref: https://github.com/tc39/proposal-global +var getGlobal = function () { + // the only reliable means to get the global object is + // `Function('return this')()` + // However, this causes CSP violations in Chrome apps. + if (typeof self !== 'undefined') { return self; } + if (typeof window !== 'undefined') { return window; } + if (typeof global !== 'undefined') { return global; } + throw new Error('unable to locate global object'); +} + +var globalObject = getGlobal(); + +module.exports = exports = globalObject.fetch; + +// Needed for TypeScript and Webpack. +if (globalObject.fetch) { + exports.default = globalObject.fetch.bind(globalObject); +} + +exports.Headers = globalObject.Headers; +exports.Request = globalObject.Request; +exports.Response = globalObject.Response; diff --git a/node_modules/node-fetch/lib/index.es.js b/node_modules/node-fetch/lib/index.es.js new file mode 100644 index 0000000..aae9799 --- /dev/null +++ b/node_modules/node-fetch/lib/index.es.js @@ -0,0 +1,1777 @@ +process.emitWarning("The .es.js file is deprecated. Use .mjs instead."); + +import Stream from 'stream'; +import http from 'http'; +import Url from 'url'; +import whatwgUrl from 'whatwg-url'; +import https from 'https'; +import zlib from 'zlib'; + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +export default fetch; +export { Headers, Request, Response, FetchError, AbortError }; diff --git a/node_modules/node-fetch/lib/index.js b/node_modules/node-fetch/lib/index.js new file mode 100644 index 0000000..567ff5d --- /dev/null +++ b/node_modules/node-fetch/lib/index.js @@ -0,0 +1,1787 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var Stream = _interopDefault(require('stream')); +var http = _interopDefault(require('http')); +var Url = _interopDefault(require('url')); +var whatwgUrl = _interopDefault(require('whatwg-url')); +var https = _interopDefault(require('https')); +var zlib = _interopDefault(require('zlib')); + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +module.exports = exports = fetch; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = exports; +exports.Headers = Headers; +exports.Request = Request; +exports.Response = Response; +exports.FetchError = FetchError; +exports.AbortError = AbortError; diff --git a/node_modules/node-fetch/lib/index.mjs b/node_modules/node-fetch/lib/index.mjs new file mode 100644 index 0000000..2863dd9 --- /dev/null +++ b/node_modules/node-fetch/lib/index.mjs @@ -0,0 +1,1775 @@ +import Stream from 'stream'; +import http from 'http'; +import Url from 'url'; +import whatwgUrl from 'whatwg-url'; +import https from 'https'; +import zlib from 'zlib'; + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +export default fetch; +export { Headers, Request, Response, FetchError, AbortError }; diff --git a/node_modules/node-fetch/package.json b/node_modules/node-fetch/package.json new file mode 100644 index 0000000..e0be176 --- /dev/null +++ b/node_modules/node-fetch/package.json @@ -0,0 +1,89 @@ +{ + "name": "node-fetch", + "version": "2.7.0", + "description": "A light-weight module that brings window.fetch to node.js", + "main": "lib/index.js", + "browser": "./browser.js", + "module": "lib/index.mjs", + "files": [ + "lib/index.js", + "lib/index.mjs", + "lib/index.es.js", + "browser.js" + ], + "engines": { + "node": "4.x || >=6.0.0" + }, + "scripts": { + "build": "cross-env BABEL_ENV=rollup rollup -c", + "prepare": "npm run build", + "test": "cross-env BABEL_ENV=test mocha --require babel-register --throw-deprecation test/test.js", + "report": "cross-env BABEL_ENV=coverage nyc --reporter lcov --reporter text mocha -R spec test/test.js", + "coverage": "cross-env BABEL_ENV=coverage nyc --reporter json --reporter text mocha -R spec test/test.js && codecov -f coverage/coverage-final.json" + }, + "repository": { + "type": "git", + "url": "https://github.com/bitinn/node-fetch.git" + }, + "keywords": [ + "fetch", + "http", + "promise" + ], + "author": "David Frank", + "license": "MIT", + "bugs": { + "url": "https://github.com/bitinn/node-fetch/issues" + }, + "homepage": "https://github.com/bitinn/node-fetch", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + }, + "devDependencies": { + "@ungap/url-search-params": "^0.1.2", + "abort-controller": "^1.1.0", + "abortcontroller-polyfill": "^1.3.0", + "babel-core": "^6.26.3", + "babel-plugin-istanbul": "^4.1.6", + "babel-plugin-transform-async-generator-functions": "^6.24.1", + "babel-polyfill": "^6.26.0", + "babel-preset-env": "1.4.0", + "babel-register": "^6.16.3", + "chai": "^3.5.0", + "chai-as-promised": "^7.1.1", + "chai-iterator": "^1.1.1", + "chai-string": "~1.3.0", + "codecov": "3.3.0", + "cross-env": "^5.2.0", + "form-data": "^2.3.3", + "is-builtin-module": "^1.0.0", + "mocha": "^5.0.0", + "nyc": "11.9.0", + "parted": "^0.1.1", + "promise": "^8.0.3", + "resumer": "0.0.0", + "rollup": "^0.63.4", + "rollup-plugin-babel": "^3.0.7", + "string-to-arraybuffer": "^1.0.2", + "teeny-request": "3.7.0" + }, + "release": { + "branches": [ + "+([0-9]).x", + "main", + "next", + { + "name": "beta", + "prerelease": true + } + ] + } +} diff --git a/node_modules/node-forge/LICENSE b/node_modules/node-forge/LICENSE new file mode 100644 index 0000000..2b48a95 --- /dev/null +++ b/node_modules/node-forge/LICENSE @@ -0,0 +1,331 @@ +You may use the Forge project under the terms of either the BSD License or the +GNU General Public License (GPL) Version 2. + +The BSD License is recommended for most projects. It is simple and easy to +understand and it places almost no restrictions on what you can do with the +Forge project. + +If the GPL suits your project better you are also free to use Forge under +that license. + +You don't have to do anything special to choose one license or the other and +you don't have to notify anyone which license you are using. You are free to +use this project in commercial projects as long as the copyright header is +left intact. + +If you are a commercial entity and use this set of libraries in your +commercial software then reasonable payment to Digital Bazaar, if you can +afford it, is not required but is expected and would be appreciated. If this +library saves you time, then it's saving you money. The cost of developing +the Forge software was on the order of several hundred hours and tens of +thousands of dollars. We are attempting to strike a balance between helping +the development community while not being taken advantage of by lucrative +commercial entities for our efforts. + +------------------------------------------------------------------------------- +New BSD License (3-clause) +Copyright (c) 2010, Digital Bazaar, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Digital Bazaar, Inc. nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL DIGITAL BAZAAR BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------------------- + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + diff --git a/node_modules/node-forge/README.md b/node_modules/node-forge/README.md new file mode 100644 index 0000000..06cff04 --- /dev/null +++ b/node_modules/node-forge/README.md @@ -0,0 +1,2071 @@ +# Forge + +[![npm package](https://nodei.co/npm/node-forge.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/node-forge/) + +[![Build Status](https://github.com/digitalbazaar/forge/workflows/Main%20Checks/badge.svg)](https://github.com/digitalbazaar/forge/actions?query=workflow%3A%22Main+Checks%22) + +A native implementation of [TLS][] (and various other cryptographic tools) in +[JavaScript][]. + +Introduction +------------ + +The Forge software is a fully native implementation of the [TLS][] protocol +in JavaScript, a set of cryptography utilities, and a set of tools for +developing Web Apps that utilize many network resources. + +Performance +------------ + +Forge is fast. Benchmarks against other popular JavaScript cryptography +libraries can be found here: + +* http://dominictarr.github.io/crypto-bench/ +* http://cryptojs.altervista.org/test/simulate-threading-speed_test.html + +Documentation +------------- + +* [Introduction](#introduction) +* [Performance](#performance) +* [Installation](#installation) +* [Testing](#testing) +* [Contributing](#contributing) + +### API + +* [Options](#options) + +### Transports + +* [TLS](#tls) +* [HTTP](#http) +* [SSH](#ssh) +* [XHR](#xhr) +* [Sockets](#socket) + +### Ciphers + +* [CIPHER](#cipher) +* [AES](#aes) +* [DES](#des) +* [RC2](#rc2) + +### PKI + +* [ED25519](#ed25519) +* [RSA](#rsa) +* [RSA-KEM](#rsakem) +* [X.509](#x509) +* [PKCS#5](#pkcs5) +* [PKCS#7](#pkcs7) +* [PKCS#8](#pkcs8) +* [PKCS#10](#pkcs10) +* [PKCS#12](#pkcs12) +* [ASN.1](#asn) + +### Message Digests + +* [SHA1](#sha1) +* [SHA256](#sha256) +* [SHA384](#sha384) +* [SHA512](#sha512) +* [MD5](#md5) +* [HMAC](#hmac) + +### Utilities + +* [Prime](#prime) +* [PRNG](#prng) +* [Tasks](#task) +* [Utilities](#util) +* [Logging](#log) +* [Flash Networking Support](#flash) + +### Other + +* [Security Considerations](#security-considerations) +* [Library Background](#library-background) +* [Contact](#contact) +* [Donations](#donations) + +--------------------------------------- + +Installation +------------ + +**Note**: Please see the [Security Considerations](#security-considerations) +section before using packaging systems and pre-built files. + +Forge uses a [CommonJS][] module structure with a build process for browser +bundles. The older [0.6.x][] branch with standalone files is available but will +not be regularly updated. + +### Node.js + +If you want to use forge with [Node.js][], it is available through `npm`: + +https://www.npmjs.com/package/node-forge + +Installation: + + npm install node-forge + +You can then use forge as a regular module: + +```js +var forge = require('node-forge'); +``` + +The npm package includes pre-built `forge.min.js`, `forge.all.min.js`, and +`prime.worker.min.js` using the [UMD][] format. + +### jsDelivr CDN + +To use it via [jsDelivr](https://www.jsdelivr.com/package/npm/node-forge) include this in your html: + +```html + +``` + +### unpkg CDN + +To use it via [unpkg](https://unpkg.com/#/) include this in your html: + +```html + +``` + +### Development Requirements + +The core JavaScript has the following requirements to build and test: + +* Building a browser bundle: + * Node.js + * npm +* Testing + * Node.js + * npm + * Chrome, Firefox, Safari (optional) + +Some special networking features can optionally use a Flash component. See the +[Flash README](./flash/README.md) for details. + +### Building for a web browser + +To create single file bundles for use with browsers run the following: + + npm install + npm run build + +This will create single non-minimized and minimized files that can be +included in the browser: + + dist/forge.js + dist/forge.min.js + +A bundle that adds some utilities and networking support is also available: + + dist/forge.all.js + dist/forge.all.min.js + +Include the file via: + +```html + +``` +or +```html + +``` + +The above bundles will synchronously create a global 'forge' object. + +**Note**: These bundles will not include any WebWorker scripts (eg: +`dist/prime.worker.js`), so these will need to be accessible from the browser +if any WebWorkers are used. + +### Building a custom browser bundle + +The build process uses [webpack][] and the [config](./webpack.config.js) file +can be modified to generate a file or files that only contain the parts of +forge you need. + +[Browserify][] override support is also present in `package.json`. + +Testing +------- + +### Prepare to run tests + + npm install + +### Running automated tests with Node.js + +Forge natively runs in a [Node.js][] environment: + + npm test + +### Running automated tests with Headless Chrome + +Automated testing is done via [Karma][]. By default it will run the tests with +Headless Chrome. + + npm run test-karma + +Is 'mocha' reporter output too verbose? Other reporters are available. Try +'dots', 'progress', or 'tap'. + + npm run test-karma -- --reporters progress + +By default [webpack][] is used. [Browserify][] can also be used. + + BUNDLER=browserify npm run test-karma + +### Running automated tests with one or more browsers + +You can also specify one or more browsers to use. + + npm run test-karma -- --browsers Chrome,Firefox,Safari,ChromeHeadless + +The reporter option and `BUNDLER` environment variable can also be used. + +### Running manual tests in a browser + +Testing in a browser uses [webpack][] to combine forge and all tests and then +loading the result in a browser. A simple web server is provided that will +output the HTTP or HTTPS URLs to load. It also will start a simple Flash Policy +Server. Unit tests and older legacy tests are provided. Custom ports can be +used by running `node tests/server.js` manually. + +To run the unit tests in a browser a special forge build is required: + + npm run test-build + +To run legacy browser based tests the main forge build is required: + + npm run build + +The tests are run with a custom server that prints out the URLs to use: + + npm run test-server + +### Running other tests + +There are some other random tests and benchmarks available in the tests +directory. + +### Coverage testing + +To perform coverage testing of the unit tests, run the following. The results +will be put in the `coverage/` directory. Note that coverage testing can slow +down some tests considerably. + + npm install + npm run coverage + +Contributing +------------ + +Any contributions (eg: PRs) that are accepted will be brought under the same +license used by the rest of the Forge project. This license allows Forge to +be used under the terms of either the BSD License or the GNU General Public +License (GPL) Version 2. + +See: [LICENSE](https://github.com/digitalbazaar/forge/blob/cbebca3780658703d925b61b2caffb1d263a6c1d/LICENSE) + +If a contribution contains 3rd party source code with its own license, it +may retain it, so long as that license is compatible with the Forge license. + +API +--- + + + +### Options + +If at any time you wish to disable the use of native code, where available, +for particular forge features like its secure random number generator, you +may set the ```forge.options.usePureJavaScript``` flag to ```true```. It is +not recommended that you set this flag as native code is typically more +performant and may have stronger security properties. It may be useful to +set this flag to test certain features that you plan to run in environments +that are different from your testing environment. + +To disable native code when including forge in the browser: + +```js +// run this *after* including the forge script +forge.options.usePureJavaScript = true; +``` + +To disable native code when using Node.js: + +```js +var forge = require('node-forge'); +forge.options.usePureJavaScript = true; +``` + +Transports +---------- + + + +### TLS + +Provides a native javascript client and server-side [TLS][] implementation. + +__Examples__ + +```js +// create TLS client +var client = forge.tls.createConnection({ + server: false, + caStore: /* Array of PEM-formatted certs or a CA store object */, + sessionCache: {}, + // supported cipher suites in order of preference + cipherSuites: [ + forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA, + forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA], + virtualHost: 'example.com', + verify: function(connection, verified, depth, certs) { + if(depth === 0) { + var cn = certs[0].subject.getField('CN').value; + if(cn !== 'example.com') { + verified = { + alert: forge.tls.Alert.Description.bad_certificate, + message: 'Certificate common name does not match hostname.' + }; + } + } + return verified; + }, + connected: function(connection) { + console.log('connected'); + // send message to server + connection.prepare(forge.util.encodeUtf8('Hi server!')); + /* NOTE: experimental, start heartbeat retransmission timer + myHeartbeatTimer = setInterval(function() { + connection.prepareHeartbeatRequest(forge.util.createBuffer('1234')); + }, 5*60*1000);*/ + }, + /* provide a client-side cert if you want + getCertificate: function(connection, hint) { + return myClientCertificate; + }, + /* the private key for the client-side cert if provided */ + getPrivateKey: function(connection, cert) { + return myClientPrivateKey; + }, + tlsDataReady: function(connection) { + // TLS data (encrypted) is ready to be sent to the server + sendToServerSomehow(connection.tlsData.getBytes()); + // if you were communicating with the server below, you'd do: + // server.process(connection.tlsData.getBytes()); + }, + dataReady: function(connection) { + // clear data from the server is ready + console.log('the server sent: ' + + forge.util.decodeUtf8(connection.data.getBytes())); + // close connection + connection.close(); + }, + /* NOTE: experimental + heartbeatReceived: function(connection, payload) { + // restart retransmission timer, look at payload + clearInterval(myHeartbeatTimer); + myHeartbeatTimer = setInterval(function() { + connection.prepareHeartbeatRequest(forge.util.createBuffer('1234')); + }, 5*60*1000); + payload.getBytes(); + },*/ + closed: function(connection) { + console.log('disconnected'); + }, + error: function(connection, error) { + console.log('uh oh', error); + } +}); + +// start the handshake process +client.handshake(); + +// when encrypted TLS data is received from the server, process it +client.process(encryptedBytesFromServer); + +// create TLS server +var server = forge.tls.createConnection({ + server: true, + caStore: /* Array of PEM-formatted certs or a CA store object */, + sessionCache: {}, + // supported cipher suites in order of preference + cipherSuites: [ + forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA, + forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA], + // require a client-side certificate if you want + verifyClient: true, + verify: function(connection, verified, depth, certs) { + if(depth === 0) { + var cn = certs[0].subject.getField('CN').value; + if(cn !== 'the-client') { + verified = { + alert: forge.tls.Alert.Description.bad_certificate, + message: 'Certificate common name does not match expected client.' + }; + } + } + return verified; + }, + connected: function(connection) { + console.log('connected'); + // send message to client + connection.prepare(forge.util.encodeUtf8('Hi client!')); + /* NOTE: experimental, start heartbeat retransmission timer + myHeartbeatTimer = setInterval(function() { + connection.prepareHeartbeatRequest(forge.util.createBuffer('1234')); + }, 5*60*1000);*/ + }, + getCertificate: function(connection, hint) { + return myServerCertificate; + }, + getPrivateKey: function(connection, cert) { + return myServerPrivateKey; + }, + tlsDataReady: function(connection) { + // TLS data (encrypted) is ready to be sent to the client + sendToClientSomehow(connection.tlsData.getBytes()); + // if you were communicating with the client above you'd do: + // client.process(connection.tlsData.getBytes()); + }, + dataReady: function(connection) { + // clear data from the client is ready + console.log('the client sent: ' + + forge.util.decodeUtf8(connection.data.getBytes())); + // close connection + connection.close(); + }, + /* NOTE: experimental + heartbeatReceived: function(connection, payload) { + // restart retransmission timer, look at payload + clearInterval(myHeartbeatTimer); + myHeartbeatTimer = setInterval(function() { + connection.prepareHeartbeatRequest(forge.util.createBuffer('1234')); + }, 5*60*1000); + payload.getBytes(); + },*/ + closed: function(connection) { + console.log('disconnected'); + }, + error: function(connection, error) { + console.log('uh oh', error); + } +}); + +// when encrypted TLS data is received from the client, process it +server.process(encryptedBytesFromClient); +``` + +Connect to a TLS server using node's net.Socket: + +```js +var socket = new net.Socket(); + +var client = forge.tls.createConnection({ + server: false, + verify: function(connection, verified, depth, certs) { + // skip verification for testing + console.log('[tls] server certificate verified'); + return true; + }, + connected: function(connection) { + console.log('[tls] connected'); + // prepare some data to send (note that the string is interpreted as + // 'binary' encoded, which works for HTTP which only uses ASCII, use + // forge.util.encodeUtf8(str) otherwise + client.prepare('GET / HTTP/1.0\r\n\r\n'); + }, + tlsDataReady: function(connection) { + // encrypted data is ready to be sent to the server + var data = connection.tlsData.getBytes(); + socket.write(data, 'binary'); // encoding should be 'binary' + }, + dataReady: function(connection) { + // clear data from the server is ready + var data = connection.data.getBytes(); + console.log('[tls] data received from the server: ' + data); + }, + closed: function() { + console.log('[tls] disconnected'); + }, + error: function(connection, error) { + console.log('[tls] error', error); + } +}); + +socket.on('connect', function() { + console.log('[socket] connected'); + client.handshake(); +}); +socket.on('data', function(data) { + client.process(data.toString('binary')); // encoding should be 'binary' +}); +socket.on('end', function() { + console.log('[socket] disconnected'); +}); + +// connect to google.com +socket.connect(443, 'google.com'); + +// or connect to gmail's imap server (but don't send the HTTP header above) +//socket.connect(993, 'imap.gmail.com'); +``` + + + +### HTTP + +Provides a native [JavaScript][] mini-implementation of an http client that +uses pooled sockets. + +__Examples__ + +```js +// create an HTTP GET request +var request = forge.http.createRequest({method: 'GET', path: url.path}); + +// send the request somewhere +sendSomehow(request.toString()); + +// receive response +var buffer = forge.util.createBuffer(); +var response = forge.http.createResponse(); +var someAsyncDataHandler = function(bytes) { + if(!response.bodyReceived) { + buffer.putBytes(bytes); + if(!response.headerReceived) { + if(response.readHeader(buffer)) { + console.log('HTTP response header: ' + response.toString()); + } + } + if(response.headerReceived && !response.bodyReceived) { + if(response.readBody(buffer)) { + console.log('HTTP response body: ' + response.body); + } + } + } +}; +``` + + + +### SSH + +Provides some SSH utility functions. + +__Examples__ + +```js +// encodes (and optionally encrypts) a private RSA key as a Putty PPK file +forge.ssh.privateKeyToPutty(privateKey, passphrase, comment); + +// encodes a public RSA key as an OpenSSH file +forge.ssh.publicKeyToOpenSSH(key, comment); + +// encodes a private RSA key as an OpenSSH file +forge.ssh.privateKeyToOpenSSH(privateKey, passphrase); + +// gets the SSH public key fingerprint in a byte buffer +forge.ssh.getPublicKeyFingerprint(key); + +// gets a hex-encoded, colon-delimited SSH public key fingerprint +forge.ssh.getPublicKeyFingerprint(key, {encoding: 'hex', delimiter: ':'}); +``` + + + +### XHR + +Provides an XmlHttpRequest implementation using forge.http as a backend. + +__Examples__ + +```js +// TODO +``` + + + +### Sockets + +Provides an interface to create and use raw sockets provided via Flash. + +__Examples__ + +```js +// TODO +``` + +Ciphers +------- + + + +### CIPHER + +Provides a basic API for block encryption and decryption. There is built-in +support for the ciphers: [AES][], [3DES][], and [DES][], and for the modes +of operation: [ECB][], [CBC][], [CFB][], [OFB][], [CTR][], and [GCM][]. + +These algorithms are currently supported: + +* AES-ECB +* AES-CBC +* AES-CFB +* AES-OFB +* AES-CTR +* AES-GCM +* 3DES-ECB +* 3DES-CBC +* DES-ECB +* DES-CBC + +When using an [AES][] algorithm, the key size will determine whether +AES-128, AES-192, or AES-256 is used (all are supported). When a [DES][] +algorithm is used, the key size will determine whether [3DES][] or regular +[DES][] is used. Use a [3DES][] algorithm to enforce Triple-DES. + +__Examples__ + +```js +// generate a random key and IV +// Note: a key size of 16 bytes will use AES-128, 24 => AES-192, 32 => AES-256 +var key = forge.random.getBytesSync(16); +var iv = forge.random.getBytesSync(16); + +/* alternatively, generate a password-based 16-byte key +var salt = forge.random.getBytesSync(128); +var key = forge.pkcs5.pbkdf2('password', salt, numIterations, 16); +*/ + +// encrypt some bytes using CBC mode +// (other modes include: ECB, CFB, OFB, CTR, and GCM) +// Note: CBC and ECB modes use PKCS#7 padding as default +var cipher = forge.cipher.createCipher('AES-CBC', key); +cipher.start({iv: iv}); +cipher.update(forge.util.createBuffer(someBytes)); +cipher.finish(); +var encrypted = cipher.output; +// outputs encrypted hex +console.log(encrypted.toHex()); + +// decrypt some bytes using CBC mode +// (other modes include: CFB, OFB, CTR, and GCM) +var decipher = forge.cipher.createDecipher('AES-CBC', key); +decipher.start({iv: iv}); +decipher.update(encrypted); +var result = decipher.finish(); // check 'result' for true/false +// outputs decrypted hex +console.log(decipher.output.toHex()); + +// decrypt bytes using CBC mode and streaming +// Performance can suffer for large multi-MB inputs due to buffer +// manipulations. Stream processing in chunks can offer significant +// improvement. CPU intensive update() calls could also be performed with +// setImmediate/setTimeout to avoid blocking the main browser UI thread (not +// shown here). Optimal block size depends on the JavaScript VM and other +// factors. Encryption can use a simple technique for increased performance. +var encryptedBytes = encrypted.bytes(); +var decipher = forge.cipher.createDecipher('AES-CBC', key); +decipher.start({iv: iv}); +var length = encryptedBytes.length; +var chunkSize = 1024 * 64; +var index = 0; +var decrypted = ''; +do { + decrypted += decipher.output.getBytes(); + var buf = forge.util.createBuffer(encryptedBytes.substr(index, chunkSize)); + decipher.update(buf); + index += chunkSize; +} while(index < length); +var result = decipher.finish(); +assert(result); +decrypted += decipher.output.getBytes(); +console.log(forge.util.bytesToHex(decrypted)); + +// encrypt some bytes using GCM mode +var cipher = forge.cipher.createCipher('AES-GCM', key); +cipher.start({ + iv: iv, // should be a 12-byte binary-encoded string or byte buffer + additionalData: 'binary-encoded string', // optional + tagLength: 128 // optional, defaults to 128 bits +}); +cipher.update(forge.util.createBuffer(someBytes)); +cipher.finish(); +var encrypted = cipher.output; +var tag = cipher.mode.tag; +// outputs encrypted hex +console.log(encrypted.toHex()); +// outputs authentication tag +console.log(tag.toHex()); + +// decrypt some bytes using GCM mode +var decipher = forge.cipher.createDecipher('AES-GCM', key); +decipher.start({ + iv: iv, + additionalData: 'binary-encoded string', // optional + tagLength: 128, // optional, defaults to 128 bits + tag: tag // authentication tag from encryption +}); +decipher.update(encrypted); +var pass = decipher.finish(); +// pass is false if there was a failure (eg: authentication tag didn't match) +if(pass) { + // outputs decrypted hex + console.log(decipher.output.toHex()); +} +``` + +Using forge in Node.js to match openssl's "enc" command line tool (**Note**: OpenSSL "enc" uses a non-standard file format with a custom key derivation function and a fixed iteration count of 1, which some consider less secure than alternatives such as [OpenPGP](https://tools.ietf.org/html/rfc4880)/[GnuPG](https://www.gnupg.org/)): + +```js +var forge = require('node-forge'); +var fs = require('fs'); + +// openssl enc -des3 -in input.txt -out input.enc +function encrypt(password) { + var input = fs.readFileSync('input.txt', {encoding: 'binary'}); + + // 3DES key and IV sizes + var keySize = 24; + var ivSize = 8; + + // get derived bytes + // Notes: + // 1. If using an alternative hash (eg: "-md sha1") pass + // "forge.md.sha1.create()" as the final parameter. + // 2. If using "-nosalt", set salt to null. + var salt = forge.random.getBytesSync(8); + // var md = forge.md.sha1.create(); // "-md sha1" + var derivedBytes = forge.pbe.opensslDeriveBytes( + password, salt, keySize + ivSize/*, md*/); + var buffer = forge.util.createBuffer(derivedBytes); + var key = buffer.getBytes(keySize); + var iv = buffer.getBytes(ivSize); + + var cipher = forge.cipher.createCipher('3DES-CBC', key); + cipher.start({iv: iv}); + cipher.update(forge.util.createBuffer(input, 'binary')); + cipher.finish(); + + var output = forge.util.createBuffer(); + + // if using a salt, prepend this to the output: + if(salt !== null) { + output.putBytes('Salted__'); // (add to match openssl tool output) + output.putBytes(salt); + } + output.putBuffer(cipher.output); + + fs.writeFileSync('input.enc', output.getBytes(), {encoding: 'binary'}); +} + +// openssl enc -d -des3 -in input.enc -out input.dec.txt +function decrypt(password) { + var input = fs.readFileSync('input.enc', {encoding: 'binary'}); + + // parse salt from input + input = forge.util.createBuffer(input, 'binary'); + // skip "Salted__" (if known to be present) + input.getBytes('Salted__'.length); + // read 8-byte salt + var salt = input.getBytes(8); + + // Note: if using "-nosalt", skip above parsing and use + // var salt = null; + + // 3DES key and IV sizes + var keySize = 24; + var ivSize = 8; + + var derivedBytes = forge.pbe.opensslDeriveBytes( + password, salt, keySize + ivSize); + var buffer = forge.util.createBuffer(derivedBytes); + var key = buffer.getBytes(keySize); + var iv = buffer.getBytes(ivSize); + + var decipher = forge.cipher.createDecipher('3DES-CBC', key); + decipher.start({iv: iv}); + decipher.update(input); + var result = decipher.finish(); // check 'result' for true/false + + fs.writeFileSync( + 'input.dec.txt', decipher.output.getBytes(), {encoding: 'binary'}); +} +``` + + + +### AES + +Provides [AES][] encryption and decryption in [CBC][], [CFB][], [OFB][], +[CTR][], and [GCM][] modes. See [CIPHER](#cipher) for examples. + + + +### DES + +Provides [3DES][] and [DES][] encryption and decryption in [ECB][] and +[CBC][] modes. See [CIPHER](#cipher) for examples. + + + +### RC2 + +__Examples__ + +```js +// generate a random key and IV +var key = forge.random.getBytesSync(16); +var iv = forge.random.getBytesSync(8); + +// encrypt some bytes +var cipher = forge.rc2.createEncryptionCipher(key); +cipher.start(iv); +cipher.update(forge.util.createBuffer(someBytes)); +cipher.finish(); +var encrypted = cipher.output; +// outputs encrypted hex +console.log(encrypted.toHex()); + +// decrypt some bytes +var cipher = forge.rc2.createDecryptionCipher(key); +cipher.start(iv); +cipher.update(encrypted); +cipher.finish(); +// outputs decrypted hex +console.log(cipher.output.toHex()); +``` + +PKI +--- + +Provides [X.509][] certificate support, ED25519 key generation and +signing/verifying, and RSA public and private key encoding, decoding, +encryption/decryption, and signing/verifying. + + + +### ED25519 + +Special thanks to [TweetNaCl.js][] for providing the bulk of the implementation. + +__Examples__ + +```js +var ed25519 = forge.pki.ed25519; + +// generate a random ED25519 keypair +var keypair = ed25519.generateKeyPair(); +// `keypair.publicKey` is a node.js Buffer or Uint8Array +// `keypair.privateKey` is a node.js Buffer or Uint8Array + +// generate a random ED25519 keypair based on a random 32-byte seed +var seed = forge.random.getBytesSync(32); +var keypair = ed25519.generateKeyPair({seed: seed}); + +// generate a random ED25519 keypair based on a "password" 32-byte seed +var password = 'Mai9ohgh6ahxee0jutheew0pungoozil'; +var seed = new forge.util.ByteBuffer(password, 'utf8'); +var keypair = ed25519.generateKeyPair({seed: seed}); + +// sign a UTF-8 message +var signature = ED25519.sign({ + message: 'test', + // also accepts `binary` if you want to pass a binary string + encoding: 'utf8', + // node.js Buffer, Uint8Array, forge ByteBuffer, binary string + privateKey: privateKey +}); +// `signature` is a node.js Buffer or Uint8Array + +// sign a message passed as a buffer +var signature = ED25519.sign({ + // also accepts a forge ByteBuffer or Uint8Array + message: Buffer.from('test', 'utf8'), + privateKey: privateKey +}); + +// sign a message digest (shorter "message" == better performance) +var md = forge.md.sha256.create(); +md.update('test', 'utf8'); +var signature = ED25519.sign({ + md: md, + privateKey: privateKey +}); + +// verify a signature on a UTF-8 message +var verified = ED25519.verify({ + message: 'test', + encoding: 'utf8', + // node.js Buffer, Uint8Array, forge ByteBuffer, or binary string + signature: signature, + // node.js Buffer, Uint8Array, forge ByteBuffer, or binary string + publicKey: publicKey +}); +// `verified` is true/false + +// sign a message passed as a buffer +var verified = ED25519.verify({ + // also accepts a forge ByteBuffer or Uint8Array + message: Buffer.from('test', 'utf8'), + // node.js Buffer, Uint8Array, forge ByteBuffer, or binary string + signature: signature, + // node.js Buffer, Uint8Array, forge ByteBuffer, or binary string + publicKey: publicKey +}); + +// verify a signature on a message digest +var md = forge.md.sha256.create(); +md.update('test', 'utf8'); +var verified = ED25519.verify({ + md: md, + // node.js Buffer, Uint8Array, forge ByteBuffer, or binary string + signature: signature, + // node.js Buffer, Uint8Array, forge ByteBuffer, or binary string + publicKey: publicKey +}); +``` + + + +### RSA + +__Examples__ + +```js +var rsa = forge.pki.rsa; + +// generate an RSA key pair synchronously +// *NOT RECOMMENDED*: Can be significantly slower than async and may block +// JavaScript execution. Will use native Node.js 10.12.0+ API if possible. +var keypair = rsa.generateKeyPair({bits: 2048, e: 0x10001}); + +// generate an RSA key pair asynchronously (uses web workers if available) +// use workers: -1 to run a fast core estimator to optimize # of workers +// *RECOMMENDED*: Can be significantly faster than sync. Will use native +// Node.js 10.12.0+ or WebCrypto API if possible. +rsa.generateKeyPair({bits: 2048, workers: 2}, function(err, keypair) { + // keypair.privateKey, keypair.publicKey +}); + +// generate an RSA key pair in steps that attempt to run for a specified period +// of time on the main JS thread +var state = rsa.createKeyPairGenerationState(2048, 0x10001); +var step = function() { + // run for 100 ms + if(!rsa.stepKeyPairGenerationState(state, 100)) { + setTimeout(step, 1); + } + else { + // done, turn off progress indicator, use state.keys + } +}; +// turn on progress indicator, schedule generation to run +setTimeout(step); + +// sign data with a private key and output DigestInfo DER-encoded bytes +// (defaults to RSASSA PKCS#1 v1.5) +var md = forge.md.sha1.create(); +md.update('sign this', 'utf8'); +var signature = privateKey.sign(md); + +// verify data with a public key +// (defaults to RSASSA PKCS#1 v1.5) +var verified = publicKey.verify(md.digest().bytes(), signature); + +// sign data using RSASSA-PSS where PSS uses a SHA-1 hash, a SHA-1 based +// masking function MGF1, and a 20 byte salt +var md = forge.md.sha1.create(); +md.update('sign this', 'utf8'); +var pss = forge.pss.create({ + md: forge.md.sha1.create(), + mgf: forge.mgf.mgf1.create(forge.md.sha1.create()), + saltLength: 20 + // optionally pass 'prng' with a custom PRNG implementation + // optionalls pass 'salt' with a forge.util.ByteBuffer w/custom salt +}); +var signature = privateKey.sign(md, pss); + +// verify RSASSA-PSS signature +var pss = forge.pss.create({ + md: forge.md.sha1.create(), + mgf: forge.mgf.mgf1.create(forge.md.sha1.create()), + saltLength: 20 + // optionally pass 'prng' with a custom PRNG implementation +}); +var md = forge.md.sha1.create(); +md.update('sign this', 'utf8'); +publicKey.verify(md.digest().getBytes(), signature, pss); + +// encrypt data with a public key (defaults to RSAES PKCS#1 v1.5) +var encrypted = publicKey.encrypt(bytes); + +// decrypt data with a private key (defaults to RSAES PKCS#1 v1.5) +var decrypted = privateKey.decrypt(encrypted); + +// encrypt data with a public key using RSAES PKCS#1 v1.5 +var encrypted = publicKey.encrypt(bytes, 'RSAES-PKCS1-V1_5'); + +// decrypt data with a private key using RSAES PKCS#1 v1.5 +var decrypted = privateKey.decrypt(encrypted, 'RSAES-PKCS1-V1_5'); + +// encrypt data with a public key using RSAES-OAEP +var encrypted = publicKey.encrypt(bytes, 'RSA-OAEP'); + +// decrypt data with a private key using RSAES-OAEP +var decrypted = privateKey.decrypt(encrypted, 'RSA-OAEP'); + +// encrypt data with a public key using RSAES-OAEP/SHA-256 +var encrypted = publicKey.encrypt(bytes, 'RSA-OAEP', { + md: forge.md.sha256.create() +}); + +// decrypt data with a private key using RSAES-OAEP/SHA-256 +var decrypted = privateKey.decrypt(encrypted, 'RSA-OAEP', { + md: forge.md.sha256.create() +}); + +// encrypt data with a public key using RSAES-OAEP/SHA-256/MGF1-SHA-1 +// compatible with Java's RSA/ECB/OAEPWithSHA-256AndMGF1Padding +var encrypted = publicKey.encrypt(bytes, 'RSA-OAEP', { + md: forge.md.sha256.create(), + mgf1: { + md: forge.md.sha1.create() + } +}); + +// decrypt data with a private key using RSAES-OAEP/SHA-256/MGF1-SHA-1 +// compatible with Java's RSA/ECB/OAEPWithSHA-256AndMGF1Padding +var decrypted = privateKey.decrypt(encrypted, 'RSA-OAEP', { + md: forge.md.sha256.create(), + mgf1: { + md: forge.md.sha1.create() + } +}); + +``` + + + +### RSA-KEM + +__Examples__ + +```js +// generate an RSA key pair asynchronously (uses web workers if available) +// use workers: -1 to run a fast core estimator to optimize # of workers +forge.rsa.generateKeyPair({bits: 2048, workers: -1}, function(err, keypair) { + // keypair.privateKey, keypair.publicKey +}); + +// generate and encapsulate a 16-byte secret key +var kdf1 = new forge.kem.kdf1(forge.md.sha1.create()); +var kem = forge.kem.rsa.create(kdf1); +var result = kem.encrypt(keypair.publicKey, 16); +// result has 'encapsulation' and 'key' + +// encrypt some bytes +var iv = forge.random.getBytesSync(12); +var someBytes = 'hello world!'; +var cipher = forge.cipher.createCipher('AES-GCM', result.key); +cipher.start({iv: iv}); +cipher.update(forge.util.createBuffer(someBytes)); +cipher.finish(); +var encrypted = cipher.output.getBytes(); +var tag = cipher.mode.tag.getBytes(); + +// send 'encrypted', 'iv', 'tag', and result.encapsulation to recipient + +// decrypt encapsulated 16-byte secret key +var kdf1 = new forge.kem.kdf1(forge.md.sha1.create()); +var kem = forge.kem.rsa.create(kdf1); +var key = kem.decrypt(keypair.privateKey, result.encapsulation, 16); + +// decrypt some bytes +var decipher = forge.cipher.createDecipher('AES-GCM', key); +decipher.start({iv: iv, tag: tag}); +decipher.update(forge.util.createBuffer(encrypted)); +var pass = decipher.finish(); +// pass is false if there was a failure (eg: authentication tag didn't match) +if(pass) { + // outputs 'hello world!' + console.log(decipher.output.getBytes()); +} + +``` + + + +### X.509 + +__Examples__ + +```js +var pki = forge.pki; + +// convert a PEM-formatted public key to a Forge public key +var publicKey = pki.publicKeyFromPem(pem); + +// convert a Forge public key to PEM-format +var pem = pki.publicKeyToPem(publicKey); + +// convert an ASN.1 SubjectPublicKeyInfo to a Forge public key +var publicKey = pki.publicKeyFromAsn1(subjectPublicKeyInfo); + +// convert a Forge public key to an ASN.1 SubjectPublicKeyInfo +var subjectPublicKeyInfo = pki.publicKeyToAsn1(publicKey); + +// gets a SHA-1 RSAPublicKey fingerprint a byte buffer +pki.getPublicKeyFingerprint(key); + +// gets a SHA-1 SubjectPublicKeyInfo fingerprint a byte buffer +pki.getPublicKeyFingerprint(key, {type: 'SubjectPublicKeyInfo'}); + +// gets a hex-encoded, colon-delimited SHA-1 RSAPublicKey public key fingerprint +pki.getPublicKeyFingerprint(key, {encoding: 'hex', delimiter: ':'}); + +// gets a hex-encoded, colon-delimited SHA-1 SubjectPublicKeyInfo public key fingerprint +pki.getPublicKeyFingerprint(key, { + type: 'SubjectPublicKeyInfo', + encoding: 'hex', + delimiter: ':' +}); + +// gets a hex-encoded, colon-delimited MD5 RSAPublicKey public key fingerprint +pki.getPublicKeyFingerprint(key, { + md: forge.md.md5.create(), + encoding: 'hex', + delimiter: ':' +}); + +// creates a CA store +var caStore = pki.createCaStore([/* PEM-encoded cert */, ...]); + +// add a certificate to the CA store +caStore.addCertificate(certObjectOrPemString); + +// gets the issuer (its certificate) for the given certificate +var issuerCert = caStore.getIssuer(subjectCert); + +// verifies a certificate chain against a CA store +pki.verifyCertificateChain(caStore, chain, customVerifyCallback); + +// signs a certificate using the given private key +cert.sign(privateKey); + +// signs a certificate using SHA-256 instead of SHA-1 +cert.sign(privateKey, forge.md.sha256.create()); + +// verifies an issued certificate using the certificates public key +var verified = issuer.verify(issued); + +// generate a keypair and create an X.509v3 certificate +var keys = pki.rsa.generateKeyPair(2048); +var cert = pki.createCertificate(); +cert.publicKey = keys.publicKey; +// alternatively set public key from a csr +//cert.publicKey = csr.publicKey; +// NOTE: serialNumber is the hex encoded value of an ASN.1 INTEGER. +// Conforming CAs should ensure serialNumber is: +// - no more than 20 octets +// - non-negative (prefix a '00' if your value starts with a '1' bit) +cert.serialNumber = '01'; +cert.validity.notBefore = new Date(); +cert.validity.notAfter = new Date(); +cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1); +var attrs = [{ + name: 'commonName', + value: 'example.org' +}, { + name: 'countryName', + value: 'US' +}, { + shortName: 'ST', + value: 'Virginia' +}, { + name: 'localityName', + value: 'Blacksburg' +}, { + name: 'organizationName', + value: 'Test' +}, { + shortName: 'OU', + value: 'Test' +}]; +cert.setSubject(attrs); +// alternatively set subject from a csr +//cert.setSubject(csr.subject.attributes); +cert.setIssuer(attrs); +cert.setExtensions([{ + name: 'basicConstraints', + cA: true +}, { + name: 'keyUsage', + keyCertSign: true, + digitalSignature: true, + nonRepudiation: true, + keyEncipherment: true, + dataEncipherment: true +}, { + name: 'extKeyUsage', + serverAuth: true, + clientAuth: true, + codeSigning: true, + emailProtection: true, + timeStamping: true +}, { + name: 'nsCertType', + client: true, + server: true, + email: true, + objsign: true, + sslCA: true, + emailCA: true, + objCA: true +}, { + name: 'subjectAltName', + altNames: [{ + type: 6, // URI + value: 'http://example.org/webid#me' + }, { + type: 7, // IP + ip: '127.0.0.1' + }] +}, { + name: 'subjectKeyIdentifier' +}]); +/* alternatively set extensions from a csr +var extensions = csr.getAttribute({name: 'extensionRequest'}).extensions; +// optionally add more extensions +extensions.push.apply(extensions, [{ + name: 'basicConstraints', + cA: true +}, { + name: 'keyUsage', + keyCertSign: true, + digitalSignature: true, + nonRepudiation: true, + keyEncipherment: true, + dataEncipherment: true +}]); +cert.setExtensions(extensions); +*/ +// self-sign certificate +cert.sign(keys.privateKey); + +// convert a Forge certificate to PEM +var pem = pki.certificateToPem(cert); + +// convert a Forge certificate from PEM +var cert = pki.certificateFromPem(pem); + +// convert an ASN.1 X.509x3 object to a Forge certificate +var cert = pki.certificateFromAsn1(obj); + +// convert a Forge certificate to an ASN.1 X.509v3 object +var asn1Cert = pki.certificateToAsn1(cert); +``` + + + +### PKCS#5 + +Provides the password-based key-derivation function from [PKCS#5][]. + +__Examples__ + +```js +// generate a password-based 16-byte key +// note an optional message digest can be passed as the final parameter +var salt = forge.random.getBytesSync(128); +var derivedKey = forge.pkcs5.pbkdf2('password', salt, numIterations, 16); + +// generate key asynchronously +// note an optional message digest can be passed before the callback +forge.pkcs5.pbkdf2('password', salt, numIterations, 16, function(err, derivedKey) { + // do something w/derivedKey +}); +``` + + + +### PKCS#7 + +Provides cryptographically protected messages from [PKCS#7][]. + +__Examples__ + +```js +// convert a message from PEM +var p7 = forge.pkcs7.messageFromPem(pem); +// look at p7.recipients + +// find a recipient by the issuer of a certificate +var recipient = p7.findRecipient(cert); + +// decrypt +p7.decrypt(p7.recipients[0], privateKey); + +// create a p7 enveloped message +var p7 = forge.pkcs7.createEnvelopedData(); + +// add a recipient +var cert = forge.pki.certificateFromPem(certPem); +p7.addRecipient(cert); + +// set content +p7.content = forge.util.createBuffer('Hello'); + +// encrypt +p7.encrypt(); + +// convert message to PEM +var pem = forge.pkcs7.messageToPem(p7); + +// create a degenerate PKCS#7 certificate container +// (CRLs not currently supported, only certificates) +var p7 = forge.pkcs7.createSignedData(); +p7.addCertificate(certOrCertPem1); +p7.addCertificate(certOrCertPem2); +var pem = forge.pkcs7.messageToPem(p7); + +// create PKCS#7 signed data with authenticatedAttributes +// attributes include: PKCS#9 content-type, message-digest, and signing-time +var p7 = forge.pkcs7.createSignedData(); +p7.content = forge.util.createBuffer('Some content to be signed.', 'utf8'); +p7.addCertificate(certOrCertPem); +p7.addSigner({ + key: privateKeyAssociatedWithCert, + certificate: certOrCertPem, + digestAlgorithm: forge.pki.oids.sha256, + authenticatedAttributes: [{ + type: forge.pki.oids.contentType, + value: forge.pki.oids.data + }, { + type: forge.pki.oids.messageDigest + // value will be auto-populated at signing time + }, { + type: forge.pki.oids.signingTime, + // value can also be auto-populated at signing time + value: new Date() + }] +}); +p7.sign(); +var pem = forge.pkcs7.messageToPem(p7); + +// PKCS#7 Sign in detached mode. +// Includes the signature and certificate without the signed data. +p7.sign({detached: true}); + +``` + + + +### PKCS#8 + +__Examples__ + +```js +var pki = forge.pki; + +// convert a PEM-formatted private key to a Forge private key +var privateKey = pki.privateKeyFromPem(pem); + +// convert a Forge private key to PEM-format +var pem = pki.privateKeyToPem(privateKey); + +// convert an ASN.1 PrivateKeyInfo or RSAPrivateKey to a Forge private key +var privateKey = pki.privateKeyFromAsn1(rsaPrivateKey); + +// convert a Forge private key to an ASN.1 RSAPrivateKey +var rsaPrivateKey = pki.privateKeyToAsn1(privateKey); + +// wrap an RSAPrivateKey ASN.1 object in a PKCS#8 ASN.1 PrivateKeyInfo +var privateKeyInfo = pki.wrapRsaPrivateKey(rsaPrivateKey); + +// convert a PKCS#8 ASN.1 PrivateKeyInfo to PEM +var pem = pki.privateKeyInfoToPem(privateKeyInfo); + +// encrypts a PrivateKeyInfo using a custom password and +// outputs an EncryptedPrivateKeyInfo +var encryptedPrivateKeyInfo = pki.encryptPrivateKeyInfo( + privateKeyInfo, 'myCustomPasswordHere', { + algorithm: 'aes256', // 'aes128', 'aes192', 'aes256', '3des' + }); + +// decrypts an ASN.1 EncryptedPrivateKeyInfo that was encrypted +// with a custom password +var privateKeyInfo = pki.decryptPrivateKeyInfo( + encryptedPrivateKeyInfo, 'myCustomPasswordHere'); + +// converts an EncryptedPrivateKeyInfo to PEM +var pem = pki.encryptedPrivateKeyToPem(encryptedPrivateKeyInfo); + +// converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format +var encryptedPrivateKeyInfo = pki.encryptedPrivateKeyFromPem(pem); + +// wraps and encrypts a Forge private key and outputs it in PEM format +var pem = pki.encryptRsaPrivateKey(privateKey, 'password'); + +// encrypts a Forge private key and outputs it in PEM format using OpenSSL's +// proprietary legacy format + encapsulated PEM headers (DEK-Info) +var pem = pki.encryptRsaPrivateKey(privateKey, 'password', {legacy: true}); + +// decrypts a PEM-formatted, encrypted private key +var privateKey = pki.decryptRsaPrivateKey(pem, 'password'); + +// sets an RSA public key from a private key +var publicKey = pki.setRsaPublicKey(privateKey.n, privateKey.e); +``` + + + +### PKCS#10 + +Provides certification requests or certificate signing requests (CSR) from +[PKCS#10][]. + +__Examples__ + +```js +// generate a key pair +var keys = forge.pki.rsa.generateKeyPair(2048); + +// create a certification request (CSR) +var csr = forge.pki.createCertificationRequest(); +csr.publicKey = keys.publicKey; +csr.setSubject([{ + name: 'commonName', + value: 'example.org' +}, { + name: 'countryName', + value: 'US' +}, { + shortName: 'ST', + value: 'Virginia' +}, { + name: 'localityName', + value: 'Blacksburg' +}, { + name: 'organizationName', + value: 'Test' +}, { + shortName: 'OU', + value: 'Test' +}]); +// set (optional) attributes +csr.setAttributes([{ + name: 'challengePassword', + value: 'password' +}, { + name: 'unstructuredName', + value: 'My Company, Inc.' +}, { + name: 'extensionRequest', + extensions: [{ + name: 'subjectAltName', + altNames: [{ + // 2 is DNS type + type: 2, + value: 'test.domain.com' + }, { + type: 2, + value: 'other.domain.com', + }, { + type: 2, + value: 'www.domain.net' + }] + }] +}]); + +// sign certification request +csr.sign(keys.privateKey); + +// verify certification request +var verified = csr.verify(); + +// convert certification request to PEM-format +var pem = forge.pki.certificationRequestToPem(csr); + +// convert a Forge certification request from PEM-format +var csr = forge.pki.certificationRequestFromPem(pem); + +// get an attribute +csr.getAttribute({name: 'challengePassword'}); + +// get extensions array +csr.getAttribute({name: 'extensionRequest'}).extensions; + +``` + + + +### PKCS#12 + +Provides the cryptographic archive file format from [PKCS#12][]. + +**Note for Chrome/Firefox/iOS/similar users**: If you have trouble importing +a PKCS#12 container, try using the TripleDES algorithm. It can be passed +to `forge.pkcs12.toPkcs12Asn1` using the `{algorithm: '3des'}` option. + +__Examples__ + +```js +// decode p12 from base64 +var p12Der = forge.util.decode64(p12b64); +// get p12 as ASN.1 object +var p12Asn1 = forge.asn1.fromDer(p12Der); +// decrypt p12 using the password 'password' +var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, 'password'); +// decrypt p12 using non-strict parsing mode (resolves some ASN.1 parse errors) +var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, false, 'password'); +// decrypt p12 using literally no password (eg: Mac OS X/apple push) +var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1); +// decrypt p12 using an "empty" password (eg: OpenSSL with no password input) +var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, ''); +// p12.safeContents is an array of safe contents, each of +// which contains an array of safeBags + +// get bags by friendlyName +var bags = p12.getBags({friendlyName: 'test'}); +// bags are key'd by attribute type (here "friendlyName") +// and the key values are an array of matching objects +var cert = bags.friendlyName[0]; + +// get bags by localKeyId +var bags = p12.getBags({localKeyId: buffer}); +// bags are key'd by attribute type (here "localKeyId") +// and the key values are an array of matching objects +var cert = bags.localKeyId[0]; + +// get bags by localKeyId (input in hex) +var bags = p12.getBags({localKeyIdHex: '7b59377ff142d0be4565e9ac3d396c01401cd879'}); +// bags are key'd by attribute type (here "localKeyId", *not* "localKeyIdHex") +// and the key values are an array of matching objects +var cert = bags.localKeyId[0]; + +// get bags by type +var bags = p12.getBags({bagType: forge.pki.oids.certBag}); +// bags are key'd by bagType and each bagType key's value +// is an array of matches (in this case, certificate objects) +var cert = bags[forge.pki.oids.certBag][0]; + +// get bags by friendlyName and filter on bag type +var bags = p12.getBags({ + friendlyName: 'test', + bagType: forge.pki.oids.certBag +}); + +// get key bags +var bags = p12.getBags({bagType: forge.pki.oids.keyBag}); +// get key +var bag = bags[forge.pki.oids.keyBag][0]; +var key = bag.key; +// if the key is in a format unrecognized by forge then +// bag.key will be `null`, use bag.asn1 to get the ASN.1 +// representation of the key +if(bag.key === null) { + var keyAsn1 = bag.asn1; + // can now convert back to DER/PEM/etc for export +} + +// generate a p12 using AES (default) +var p12Asn1 = forge.pkcs12.toPkcs12Asn1( + privateKey, certificateChain, 'password'); + +// generate a p12 that can be imported by Chrome/Firefox/iOS +// (requires the use of Triple DES instead of AES) +var p12Asn1 = forge.pkcs12.toPkcs12Asn1( + privateKey, certificateChain, 'password', + {algorithm: '3des'}); + +// base64-encode p12 +var p12Der = forge.asn1.toDer(p12Asn1).getBytes(); +var p12b64 = forge.util.encode64(p12Der); + +// create download link for p12 +var a = document.createElement('a'); +a.download = 'example.p12'; +a.setAttribute('href', 'data:application/x-pkcs12;base64,' + p12b64); +a.appendChild(document.createTextNode('Download')); +``` + + + +### ASN.1 + +Provides [ASN.1][] DER encoding and decoding. + +__Examples__ + +```js +var asn1 = forge.asn1; + +// create a SubjectPublicKeyInfo +var subjectPublicKeyInfo = + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids['rsaEncryption']).getBytes()), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]), + // subjectPublicKey + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [ + // RSAPublicKey + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // modulus (n) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.n)), + // publicExponent (e) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.e)) + ]) + ]) + ]); + +// serialize an ASN.1 object to DER format +var derBuffer = asn1.toDer(subjectPublicKeyInfo); + +// deserialize to an ASN.1 object from a byte buffer filled with DER data +var object = asn1.fromDer(derBuffer); + +// convert an OID dot-separated string to a byte buffer +var derOidBuffer = asn1.oidToDer('1.2.840.113549.1.1.5'); + +// convert a byte buffer with a DER-encoded OID to a dot-separated string +console.log(asn1.derToOid(derOidBuffer)); +// output: 1.2.840.113549.1.1.5 + +// validates that an ASN.1 object matches a particular ASN.1 structure and +// captures data of interest from that structure for easy access +var publicKeyValidator = { + name: 'SubjectPublicKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'subjectPublicKeyInfo', + value: [{ + name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'publicKeyOid' + }] + }, { + // subjectPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + value: [{ + // RSAPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: 'rsaPublicKey' + }] + }] +}; + +var capture = {}; +var errors = []; +if(!asn1.validate( + publicKeyValidator, subjectPublicKeyInfo, validator, capture, errors)) { + throw 'ASN.1 object is not a SubjectPublicKeyInfo.'; +} +// capture.subjectPublicKeyInfo contains the full ASN.1 object +// capture.rsaPublicKey contains the full ASN.1 object for the RSA public key +// capture.publicKeyOid only contains the value for the OID +var oid = asn1.derToOid(capture.publicKeyOid); +if(oid !== pki.oids['rsaEncryption']) { + throw 'Unsupported OID.'; +} + +// pretty print an ASN.1 object to a string for debugging purposes +asn1.prettyPrint(object); +``` + +Message Digests +---------------- + + + +### SHA1 + +Provides [SHA-1][] message digests. + +__Examples__ + +```js +var md = forge.md.sha1.create(); +md.update('The quick brown fox jumps over the lazy dog'); +console.log(md.digest().toHex()); +// output: 2fd4e1c67a2d28fced849ee1bb76e7391b93eb12 +``` + + + +### SHA256 + +Provides [SHA-256][] message digests. + +__Examples__ + +```js +var md = forge.md.sha256.create(); +md.update('The quick brown fox jumps over the lazy dog'); +console.log(md.digest().toHex()); +// output: d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592 +``` + + + +### SHA384 + +Provides [SHA-384][] message digests. + +__Examples__ + +```js +var md = forge.md.sha384.create(); +md.update('The quick brown fox jumps over the lazy dog'); +console.log(md.digest().toHex()); +// output: ca737f1014a48f4c0b6dd43cb177b0afd9e5169367544c494011e3317dbf9a509cb1e5dc1e85a941bbee3d7f2afbc9b1 +``` + + + +### SHA512 + +Provides [SHA-512][] message digests. + +__Examples__ + +```js +// SHA-512 +var md = forge.md.sha512.create(); +md.update('The quick brown fox jumps over the lazy dog'); +console.log(md.digest().toHex()); +// output: 07e547d9586f6a73f73fbac0435ed76951218fb7d0c8d788a309d785436bbb642e93a252a954f23912547d1e8a3b5ed6e1bfd7097821233fa0538f3db854fee6 + +// SHA-512/224 +var md = forge.md.sha512.sha224.create(); +md.update('The quick brown fox jumps over the lazy dog'); +console.log(md.digest().toHex()); +// output: 944cd2847fb54558d4775db0485a50003111c8e5daa63fe722c6aa37 + +// SHA-512/256 +var md = forge.md.sha512.sha256.create(); +md.update('The quick brown fox jumps over the lazy dog'); +console.log(md.digest().toHex()); +// output: dd9d67b371519c339ed8dbd25af90e976a1eeefd4ad3d889005e532fc5bef04d +``` + + + +### MD5 + +Provides [MD5][] message digests. + +__Examples__ + +```js +var md = forge.md.md5.create(); +md.update('The quick brown fox jumps over the lazy dog'); +console.log(md.digest().toHex()); +// output: 9e107d9d372bb6826bd81d3542a419d6 +``` + + + +### HMAC + +Provides [HMAC][] w/any supported message digest algorithm. + +__Examples__ + +```js +var hmac = forge.hmac.create(); +hmac.start('sha1', 'Jefe'); +hmac.update('what do ya want for nothing?'); +console.log(hmac.digest().toHex()); +// output: effcdf6ae5eb2fa2d27416d5f184df9c259a7c79 +``` + +Utilities +--------- + + + +### Prime + +Provides an API for generating large, random, probable primes. + +__Examples__ + +```js +// generate a random prime on the main JS thread +var bits = 1024; +forge.prime.generateProbablePrime(bits, function(err, num) { + console.log('random prime', num.toString(16)); +}); + +// generate a random prime using Web Workers (if available, otherwise +// falls back to the main thread) +var bits = 1024; +var options = { + algorithm: { + name: 'PRIMEINC', + workers: -1 // auto-optimize # of workers + } +}; +forge.prime.generateProbablePrime(bits, options, function(err, num) { + console.log('random prime', num.toString(16)); +}); +``` + + + +### PRNG + +Provides a [Fortuna][]-based cryptographically-secure pseudo-random number +generator, to be used with a cryptographic function backend, e.g. [AES][]. An +implementation using [AES][] as a backend is provided. An API for collecting +entropy is given, though if window.crypto.getRandomValues is available, it will +be used automatically. + +__Examples__ + +```js +// get some random bytes synchronously +var bytes = forge.random.getBytesSync(32); +console.log(forge.util.bytesToHex(bytes)); + +// get some random bytes asynchronously +forge.random.getBytes(32, function(err, bytes) { + console.log(forge.util.bytesToHex(bytes)); +}); + +// collect some entropy if you'd like +forge.random.collect(someRandomBytes); +jQuery().mousemove(function(e) { + forge.random.collectInt(e.clientX, 16); + forge.random.collectInt(e.clientY, 16); +}); + +// specify a seed file for use with the synchronous API if you'd like +forge.random.seedFileSync = function(needed) { + // get 'needed' number of random bytes from somewhere + return fetchedRandomBytes; +}; + +// specify a seed file for use with the asynchronous API if you'd like +forge.random.seedFile = function(needed, callback) { + // get the 'needed' number of random bytes from somewhere + callback(null, fetchedRandomBytes); +}); + +// register the main thread to send entropy or a Web Worker to receive +// entropy on demand from the main thread +forge.random.registerWorker(self); + +// generate a new instance of a PRNG with no collected entropy +var myPrng = forge.random.createInstance(); +``` + + + +### Tasks + +Provides queuing and synchronizing tasks in a web application. + +__Examples__ + +```js +// TODO +``` + + + +### Utilities + +Provides utility functions, including byte buffer support, base64, +bytes to/from hex, zlib inflate/deflate, etc. + +__Examples__ + +```js +// encode/decode base64 +var encoded = forge.util.encode64(str); +var str = forge.util.decode64(encoded); + +// encode/decode UTF-8 +var encoded = forge.util.encodeUtf8(str); +var str = forge.util.decodeUtf8(encoded); + +// bytes to/from hex +var bytes = forge.util.hexToBytes(hex); +var hex = forge.util.bytesToHex(bytes); + +// create an empty byte buffer +var buffer = forge.util.createBuffer(); +// create a byte buffer from raw binary bytes +var buffer = forge.util.createBuffer(input, 'raw'); +// create a byte buffer from utf8 bytes +var buffer = forge.util.createBuffer(input, 'utf8'); + +// get the length of the buffer in bytes +buffer.length(); +// put bytes into the buffer +buffer.putBytes(bytes); +// put a 32-bit integer into the buffer +buffer.putInt32(10); +// buffer to hex +buffer.toHex(); +// get a copy of the bytes in the buffer +bytes.bytes(/* count */); +// empty this buffer and get its contents +bytes.getBytes(/* count */); + +// convert a forge buffer into a Node.js Buffer +// make sure you specify the encoding as 'binary' +var forgeBuffer = forge.util.createBuffer(); +var nodeBuffer = Buffer.from(forgeBuffer.getBytes(), 'binary'); + +// convert a Node.js Buffer into a forge buffer +// make sure you specify the encoding as 'binary' +var nodeBuffer = Buffer.from('CAFE', 'hex'); +var forgeBuffer = forge.util.createBuffer(nodeBuffer.toString('binary')); +``` + + + +### Logging + +Provides logging to a javascript console using various categories and +levels of verbosity. + +__Examples__ + +```js +// TODO +``` + + + +### Flash Networking Support + +The [flash README](./flash/README.md) provides details on rebuilding the +optional Flash component used for networking. It also provides details on +Policy Server support. + +Security Considerations +----------------------- + +When using this code please keep the following in mind: + +- Cryptography is hard. Please review and test this code before depending on it + for critical functionality. +- The nature of JavaScript is that execution of this code depends on trusting a + very large set of JavaScript tools and systems. Consider runtime variations, + runtime characteristics, runtime optimization, code optimization, code + minimization, code obfuscation, bundling tools, possible bugs, the Forge code + itself, and so on. +- If using pre-built bundles from [NPM][], another CDN, or similar, be aware + someone else ran the tools to create those files. +- Use a secure transport channel such as [TLS][] to load scripts and consider + using additional security mechanisms such as [Subresource Integrity][] script + attributes. +- Use "native" functionality where possible. This can be critical when dealing + with performance and random number generation. Note that the JavaScript + random number algorithms should perform well if given suitable entropy. +- Understand possible attacks against cryptographic systems. For instance side + channel and timing attacks may be possible due to the difficulty in + implementing constant time algorithms in pure JavaScript. +- Certain features in this library are less susceptible to attacks depending on + usage. This primarily includes features that deal with data format + manipulation or those that are not involved in communication. + +Library Background +------------------ + +* https://digitalbazaar.com/2010/07/20/javascript-tls-1/ +* https://digitalbazaar.com/2010/07/20/javascript-tls-2/ + +Contact +------- + +* Code: https://github.com/digitalbazaar/forge +* Bugs: https://github.com/digitalbazaar/forge/issues +* Email: support@digitalbazaar.com +* IRC: [#forgejs][] on [Libera.Chat][] (people may also be on [freenode][] for + historical reasons). + +Donations +--------- + +Financial support is welcome and helps contribute to further development: + +* For [PayPal][] please send to paypal@digitalbazaar.com. +* Something else? Please contact support@digitalbazaar.com. + +[#forgejs]: https://webchat.freenode.net/?channels=#forgejs +[0.6.x]: https://github.com/digitalbazaar/forge/tree/0.6.x +[3DES]: https://en.wikipedia.org/wiki/Triple_DES +[AES]: https://en.wikipedia.org/wiki/Advanced_Encryption_Standard +[ASN.1]: https://en.wikipedia.org/wiki/ASN.1 +[Browserify]: http://browserify.org/ +[CBC]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation +[CFB]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation +[CTR]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation +[CommonJS]: https://en.wikipedia.org/wiki/CommonJS +[DES]: https://en.wikipedia.org/wiki/Data_Encryption_Standard +[ECB]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation +[Fortuna]: https://en.wikipedia.org/wiki/Fortuna_(PRNG) +[GCM]: https://en.wikipedia.org/wiki/GCM_mode +[HMAC]: https://en.wikipedia.org/wiki/HMAC +[JavaScript]: https://en.wikipedia.org/wiki/JavaScript +[Karma]: https://karma-runner.github.io/ +[Libera.Chat]: https://libera.chat/ +[MD5]: https://en.wikipedia.org/wiki/MD5 +[NPM]: https://www.npmjs.com/ +[Node.js]: https://nodejs.org/ +[OFB]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation +[PKCS#10]: https://en.wikipedia.org/wiki/Certificate_signing_request +[PKCS#12]: https://en.wikipedia.org/wiki/PKCS_%E2%99%AF12 +[PKCS#5]: https://en.wikipedia.org/wiki/PKCS +[PKCS#7]: https://en.wikipedia.org/wiki/Cryptographic_Message_Syntax +[PayPal]: https://www.paypal.com/ +[RC2]: https://en.wikipedia.org/wiki/RC2 +[SHA-1]: https://en.wikipedia.org/wiki/SHA-1 +[SHA-256]: https://en.wikipedia.org/wiki/SHA-256 +[SHA-384]: https://en.wikipedia.org/wiki/SHA-384 +[SHA-512]: https://en.wikipedia.org/wiki/SHA-512 +[Subresource Integrity]: https://www.w3.org/TR/SRI/ +[TLS]: https://en.wikipedia.org/wiki/Transport_Layer_Security +[UMD]: https://github.com/umdjs/umd +[X.509]: https://en.wikipedia.org/wiki/X.509 +[freenode]: https://freenode.net/ +[unpkg]: https://unpkg.com/ +[webpack]: https://webpack.github.io/ +[TweetNaCl.js]: https://github.com/dchest/tweetnacl-js diff --git a/node_modules/node-forge/dist/forge.all.min.js b/node_modules/node-forge/dist/forge.all.min.js new file mode 100644 index 0000000..43a14fa --- /dev/null +++ b/node_modules/node-forge/dist/forge.all.min.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.forge=t():e.forge=t()}(window,(function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var a=t[n]={i:n,l:!1,exports:{}};return e[n].call(a.exports,a,a.exports,r),a.l=!0,a.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)r.d(n,a,function(t){return e[t]}.bind(null,a));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=34)}([function(e,t){e.exports={options:{usePureJavaScript:!1}}},function(e,t,r){(function(t){var n=r(0),a=r(38),i=e.exports=n.util=n.util||{};function s(e){if(8!==e&&16!==e&&24!==e&&32!==e)throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}function o(e){if(this.data="",this.read=0,"string"==typeof e)this.data=e;else if(i.isArrayBuffer(e)||i.isArrayBufferView(e))if("undefined"!=typeof Buffer&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch(e){for(var r=0;r15?(r=Date.now(),s(e)):(t.push(e),1===t.length&&a.setAttribute("a",n=!n))}}i.nextTick=i.setImmediate}(),i.isNodejs="undefined"!=typeof process&&process.versions&&process.versions.node,i.globalScope=i.isNodejs?t:"undefined"==typeof self?window:self,i.isArray=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},i.isArrayBuffer=function(e){return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer},i.isArrayBufferView=function(e){return e&&i.isArrayBuffer(e.buffer)&&void 0!==e.byteLength},i.ByteBuffer=o,i.ByteStringBuffer=o;i.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>4096&&(this.data.substr(0,1),this._constructedStringLength=0)},i.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},i.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},i.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))},i.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var r=this.data;t>0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return this.data=r,this._optimizeConstructedString(t),this},i.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this},i.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(i.encodeUtf8(e))},i.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},i.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},i.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},i.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255))},i.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))},i.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))},i.ByteStringBuffer.prototype.putInt=function(e,t){s(t);var r="";do{t-=8,r+=String.fromCharCode(e>>t&255)}while(t>0);return this.putBytes(r)},i.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<0);return t},i.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},i.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},i.ByteStringBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},i.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)},i.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this},i.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},i.ByteStringBuffer.prototype.copy=function(){var e=i.createBuffer(this.data);return e.read=this.read,e},i.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},i.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},i.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this},i.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t=e)return this;t=Math.max(t||this.growSize,e);var r=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),n=new Uint8Array(this.length()+t);return n.set(r),this.data=new DataView(n.buffer),this},i.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this},i.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var r=0;r>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this},i.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this},i.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this},i.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this},i.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this},i.DataBuffer.prototype.putInt=function(e,t){s(t),this.accommodate(t/8);do{t-=8,this.data.setInt8(this.write++,e>>t&255)}while(t>0);return this},i.DataBuffer.prototype.putSignedInt=function(e,t){return s(t),this.accommodate(t/8),e<0&&(e+=2<0);return t},i.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},i.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},i.DataBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},i.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)},i.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this},i.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},i.DataBuffer.prototype.copy=function(){return new i.DataBuffer(this)},i.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this},i.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},i.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this},i.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return r},i.xorBytes=function(e,t,r){for(var n="",a="",i="",s=0,o=0;r>0;--r,++s)a=e.charCodeAt(s)^t.charCodeAt(s),o>=10&&(n+=i,i="",o=0),i+=String.fromCharCode(a),++o;return n+=i},i.hexToBytes=function(e){var t="",r=0;for(!0&e.length&&(r=1,t+=String.fromCharCode(parseInt(e[0],16)));r>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e)};var c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",u=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,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,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],l="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";i.encode64=function(e,t){for(var r,n,a,i="",s="",o=0;o>2),i+=c.charAt((3&r)<<4|n>>4),isNaN(n)?i+="==":(i+=c.charAt((15&n)<<2|a>>6),i+=isNaN(a)?"=":c.charAt(63&a)),t&&i.length>t&&(s+=i.substr(0,t)+"\r\n",i=i.substr(t));return s+=i},i.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t,r,n,a,i="",s=0;s>4),64!==n&&(i+=String.fromCharCode((15&r)<<4|n>>2),64!==a&&(i+=String.fromCharCode((3&n)<<6|a)));return i},i.encodeUtf8=function(e){return unescape(encodeURIComponent(e))},i.decodeUtf8=function(e){return decodeURIComponent(escape(e))},i.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:a.encode,decode:a.decode}},i.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)},i.binary.raw.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(e.length));for(var a=r=r||0,i=0;i>2),i+=c.charAt((3&r)<<4|n>>4),isNaN(n)?i+="==":(i+=c.charAt((15&n)<<2|a>>6),i+=isNaN(a)?"=":c.charAt(63&a)),t&&i.length>t&&(s+=i.substr(0,t)+"\r\n",i=i.substr(t));return s+=i},i.binary.base64.decode=function(e,t,r){var n,a,i,s,o=t;o||(o=new Uint8Array(3*Math.ceil(e.length/4))),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var c=0,l=r=r||0;c>4,64!==i&&(o[l++]=(15&a)<<4|i>>2,64!==s&&(o[l++]=(3&i)<<6|s));return t?l-r:o.subarray(0,l)},i.binary.base58.encode=function(e,t){return i.binary.baseN.encode(e,l,t)},i.binary.base58.decode=function(e,t){return i.binary.baseN.decode(e,l,t)},i.text={utf8:{},utf16:{}},i.text.utf8.encode=function(e,t,r){e=i.encodeUtf8(e);var n=t;n||(n=new Uint8Array(e.length));for(var a=r=r||0,s=0;s0&&i.push(r),s=n.lastIndex;var o=t[0][1];switch(o){case"s":case"o":a");break;case"%":i.push("%");break;default:i.push("<%"+o+"?>")}}return i.push(e.substring(s)),i.join("")},i.formatNumber=function(e,t,r,n){var a=e,i=isNaN(t=Math.abs(t))?2:t,s=void 0===r?",":r,o=void 0===n?".":n,c=a<0?"-":"",u=parseInt(a=Math.abs(+a||0).toFixed(i),10)+"",l=u.length>3?u.length%3:0;return c+(l?u.substr(0,l)+o:"")+u.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+o)+(i?s+Math.abs(a-u).toFixed(i).slice(2):"")},i.formatSize=function(e){return e=e>=1073741824?i.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?i.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?i.formatNumber(e/1024,0)+" KiB":i.formatNumber(e,0)+" bytes"},i.bytesFromIP=function(e){return-1!==e.indexOf(".")?i.bytesFromIPv4(e):-1!==e.indexOf(":")?i.bytesFromIPv6(e):null},i.bytesFromIPv4=function(e){if(4!==(e=e.split(".")).length)return null;for(var t=i.createBuffer(),r=0;rr[n].end-r[n].start&&(n=r.length-1)):r.push({start:c,end:c})}t.push(s)}if(r.length>0){var u=r[n];u.end-u.start>0&&(t.splice(u.start,u.end-u.start+1,""),0===u.start&&t.unshift(""),7===u.end&&t.push(""))}return t.join(":")},i.estimateCores=function(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},"cores"in i&&!e.update)return t(null,i.cores);if("undefined"!=typeof navigator&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return i.cores=navigator.hardwareConcurrency,t(null,i.cores);if("undefined"==typeof Worker)return i.cores=1,t(null,i.cores);if("undefined"==typeof Blob)return i.cores=2,t(null,i.cores);var r=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",(function(e){for(var t=Date.now(),r=t+4;Date.now()o.st&&a.sta.st&&o.stt){var n=new Error("Too few bytes to parse DER.");throw n.available=e.length(),n.remaining=t,n.requested=r,n}}a.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},a.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30},a.maxDepth=256,a.create=function(e,t,r,i,s){if(n.util.isArray(i)){for(var o=[],c=0;c=s.maxDepth)throw new Error("ASN.1 parsing error: Max depth exceeded.");var o;i(t,r,2);var c=t.getByte();r--;var u=192&c,l=31&c;o=t.length();var p,f,h=function(e,t){var r=e.getByte();if(t--,128!==r){var n;if(128&r){var a=127&r;i(e,t,a),n=e.getInt(a<<3)}else n=r;if(n<0)throw new Error("Negative length: "+n);return n}}(t,r);if(r-=o-t.length(),void 0!==h&&h>r){if(s.strict){var d=new Error("Too few bytes to read ASN.1 value.");throw d.available=t.length(),d.remaining=r,d.requested=h,d}h=r}var y=32==(32&c);if(y)if(p=[],void 0===h)for(;;){if(i(t,r,2),t.bytes(2)===String.fromCharCode(0,0)){t.getBytes(2),r-=2;break}o=t.length(),p.push(e(t,r,n+1,s)),r-=o-t.length()}else for(;h>0;)o=t.length(),p.push(e(t,h,n+1,s)),r-=o-t.length(),h-=o-t.length();void 0===p&&u===a.Class.UNIVERSAL&&l===a.Type.BITSTRING&&(f=t.bytes(h));if(void 0===p&&s.decodeBitStrings&&u===a.Class.UNIVERSAL&&l===a.Type.BITSTRING&&h>1){var g=t.read,v=r,m=0;if(l===a.Type.BITSTRING&&(i(t,r,1),m=t.getByte(),r--),0===m)try{o=t.length();var C=e(t,r,n+1,{strict:!0,decodeBitStrings:!0}),E=o-t.length();r-=E,l==a.Type.BITSTRING&&E++;var S=C.tagClass;E!==h||S!==a.Class.UNIVERSAL&&S!==a.Class.CONTEXT_SPECIFIC||(p=[C])}catch(e){}void 0===p&&(t.read=g,r=v)}if(void 0===p){if(void 0===h){if(s.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");h=r}if(l===a.Type.BMPSTRING)for(p="";h>0;h-=2)i(t,r,2),p+=String.fromCharCode(t.getInt16()),r-=2;else p=t.getBytes(h),r-=h}var T=void 0===f?null:{bitStringContents:f};return a.create(u,l,y,p,T)}(e,e.length(),0,t);if(t.parseAllBytes&&0!==e.length()){var o=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw o.byteCount=r,o.remaining=e.length(),o}return s},a.toDer=function(e){var t=n.util.createBuffer(),r=e.tagClass|e.type,i=n.util.createBuffer(),s=!1;if("bitStringContents"in e&&(s=!0,e.original&&(s=a.equals(e,e.original))),s)i.putBytes(e.bitStringContents);else if(e.composed){e.constructed?r|=32:i.putByte(0);for(var o=0;o1&&(0===e.value.charCodeAt(0)&&0==(128&e.value.charCodeAt(1))||255===e.value.charCodeAt(0)&&128==(128&e.value.charCodeAt(1)))?i.putBytes(e.value.substr(1)):i.putBytes(e.value);if(t.putByte(r),i.length()<=127)t.putByte(127&i.length());else{var c=i.length(),u="";do{u+=String.fromCharCode(255&c),c>>>=8}while(c>0);t.putByte(128|u.length);for(o=u.length-1;o>=0;--o)t.putByte(u.charCodeAt(o))}return t.putBuffer(i),t},a.oidToDer=function(e){var t,r,a,i,s=e.split("."),o=n.util.createBuffer();o.putByte(40*parseInt(s[0],10)+parseInt(s[1],10));for(var c=2;c4294967295)throw new Error("OID value too large; max is 32-bits.");do{i=127&a,a>>>=7,t||(i|=128),r.push(i),t=!1}while(a>0);for(var u=r.length-1;u>=0;--u)o.putByte(r[u])}return o},a.derToOid=function(e){var t;"string"==typeof e&&(e=n.util.createBuffer(e));var r=e.getByte();t=Math.floor(r/40)+"."+r%40;for(var a=0;e.length()>0;){if(a>70368744177663)throw new Error("OID value too large; max is 53-bits.");a*=128,128&(r=e.getByte())?a+=127&r:(t+="."+(a+r),a=0)}return t},a.utcTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,2),10);r=r>=50?1900+r:2e3+r;var n=parseInt(e.substr(2,2),10)-1,a=parseInt(e.substr(4,2),10),i=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),o=0;if(e.length>11){var c=e.charAt(10),u=10;"+"!==c&&"-"!==c&&(o=parseInt(e.substr(10,2),10),u+=2)}if(t.setUTCFullYear(r,n,a),t.setUTCHours(i,s,o,0),u&&("+"===(c=e.charAt(u))||"-"===c)){var l=60*parseInt(e.substr(u+1,2),10)+parseInt(e.substr(u+4,2),10);l*=6e4,"+"===c?t.setTime(+t-l):t.setTime(+t+l)}return t},a.generalizedTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,4),10),n=parseInt(e.substr(4,2),10)-1,a=parseInt(e.substr(6,2),10),i=parseInt(e.substr(8,2),10),s=parseInt(e.substr(10,2),10),o=parseInt(e.substr(12,2),10),c=0,u=0,l=!1;"Z"===e.charAt(e.length-1)&&(l=!0);var p=e.length-5,f=e.charAt(p);"+"!==f&&"-"!==f||(u=60*parseInt(e.substr(p+1,2),10)+parseInt(e.substr(p+4,2),10),u*=6e4,"+"===f&&(u*=-1),l=!0);return"."===e.charAt(14)&&(c=1e3*parseFloat(e.substr(14),10)),l?(t.setUTCFullYear(r,n,a),t.setUTCHours(i,s,o,c),t.setTime(+t+u)):(t.setFullYear(r,n,a),t.setHours(i,s,o,c)),t},a.dateToUtcTime=function(e){if("string"==typeof e)return e;var t="",r=[];r.push((""+e.getUTCFullYear()).substr(2)),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var n=0;n=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putSignedInt(e,24);if(e>=-2147483648&&e<2147483648)return t.putSignedInt(e,32);var r=new Error("Integer too large; max is 32-bits.");throw r.integer=e,r},a.derToInteger=function(e){"string"==typeof e&&(e=n.util.createBuffer(e));var t=8*e.length();if(t>32)throw new Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)},a.validate=function(e,t,r,i){var s=!1;if(e.tagClass!==t.tagClass&&void 0!==t.tagClass||e.type!==t.type&&void 0!==t.type)i&&(e.tagClass!==t.tagClass&&i.push("["+t.name+'] Expected tag class "'+t.tagClass+'", got "'+e.tagClass+'"'),e.type!==t.type&&i.push("["+t.name+'] Expected type "'+t.type+'", got "'+e.type+'"'));else if(e.constructed===t.constructed||void 0===t.constructed){if(s=!0,t.value&&n.util.isArray(t.value))for(var o=0,c=0;s&&c0&&(i+="\n");for(var o="",c=0;c1?i+="0x"+n.util.bytesToHex(e.value.slice(1)):i+="(none)",e.value.length>0){var f=e.value.charCodeAt(0);1==f?i+=" (1 unused bit shown)":f>1&&(i+=" ("+f+" unused bits shown)")}}else if(e.type===a.Type.OCTETSTRING)s.test(e.value)||(i+="("+e.value+") "),i+="0x"+n.util.bytesToHex(e.value);else if(e.type===a.Type.UTF8)try{i+=n.util.decodeUtf8(e.value)}catch(t){if("URI malformed"!==t.message)throw t;i+="0x"+n.util.bytesToHex(e.value)+" (malformed UTF8)"}else e.type===a.Type.PRINTABLESTRING||e.type===a.Type.IA5String?i+=e.value:s.test(e.value)?i+="0x"+n.util.bytesToHex(e.value):0===e.value.length?i+="[null]":i+=e.value}return i}},function(e,t,r){var n=r(0);e.exports=n.md=n.md||{},n.md.algorithms=n.md.algorithms||{}},function(e,t,r){var n=r(0);function a(e,t){n.cipher.registerAlgorithm(e,(function(){return new n.aes.Algorithm(e,t)}))}r(14),r(20),r(1),e.exports=n.aes=n.aes||{},n.aes.startEncrypting=function(e,t,r,n){var a=d({key:e,output:r,decrypt:!1,mode:n});return a.start(t),a},n.aes.createEncryptionCipher=function(e,t){return d({key:e,output:null,decrypt:!1,mode:t})},n.aes.startDecrypting=function(e,t,r,n){var a=d({key:e,output:r,decrypt:!0,mode:n});return a.start(t),a},n.aes.createDecryptionCipher=function(e,t){return d({key:e,output:null,decrypt:!0,mode:t})},n.aes.Algorithm=function(e,t){l||p();var r=this;r.name=e,r.mode=new t({blockSize:16,cipher:{encrypt:function(e,t){return h(r._w,e,t,!1)},decrypt:function(e,t){return h(r._w,e,t,!0)}}}),r._init=!1},n.aes.Algorithm.prototype.initialize=function(e){if(!this._init){var t,r=e.key;if("string"!=typeof r||16!==r.length&&24!==r.length&&32!==r.length){if(n.util.isArray(r)&&(16===r.length||24===r.length||32===r.length)){t=r,r=n.util.createBuffer();for(var a=0;a>>=2;for(a=0;a>8^255&p^99,i[y]=p,s[p]=y,h=(f=e[p])<<24^p<<16^p<<8^p^f,d=((r=e[y])^(n=e[r])^(a=e[n]))<<24^(y^a)<<16^(y^n^a)<<8^y^r^a;for(var v=0;v<4;++v)c[v][y]=h,u[v][p]=d,h=h<<24|h>>>8,d=d<<24|d>>>8;0===y?y=g=1:(y=r^e[e[e[r^a]]],g^=e[e[g]])}}function f(e,t){for(var r,n=e.slice(0),a=1,s=n.length,c=4*(s+6+1),l=s;l>>16&255]<<24^i[r>>>8&255]<<16^i[255&r]<<8^i[r>>>24]^o[a]<<24,a++):s>6&&l%s==4&&(r=i[r>>>24]<<24^i[r>>>16&255]<<16^i[r>>>8&255]<<8^i[255&r]),n[l]=n[l-s]^r;if(t){for(var p,f=u[0],h=u[1],d=u[2],y=u[3],g=n.slice(0),v=(l=0,(c=n.length)-4);l>>24]]^h[i[p>>>16&255]]^d[i[p>>>8&255]]^y[i[255&p]];n=g}return n}function h(e,t,r,n){var a,o,l,p,f,h,d,y,g,v,m,C,E=e.length/4-1;n?(a=u[0],o=u[1],l=u[2],p=u[3],f=s):(a=c[0],o=c[1],l=c[2],p=c[3],f=i),h=t[0]^e[0],d=t[n?3:1]^e[1],y=t[2]^e[2],g=t[n?1:3]^e[3];for(var S=3,T=1;T>>24]^o[d>>>16&255]^l[y>>>8&255]^p[255&g]^e[++S],m=a[d>>>24]^o[y>>>16&255]^l[g>>>8&255]^p[255&h]^e[++S],C=a[y>>>24]^o[g>>>16&255]^l[h>>>8&255]^p[255&d]^e[++S],g=a[g>>>24]^o[h>>>16&255]^l[d>>>8&255]^p[255&y]^e[++S],h=v,d=m,y=C;r[0]=f[h>>>24]<<24^f[d>>>16&255]<<16^f[y>>>8&255]<<8^f[255&g]^e[++S],r[n?3:1]=f[d>>>24]<<24^f[y>>>16&255]<<16^f[g>>>8&255]<<8^f[255&h]^e[++S],r[2]=f[y>>>24]<<24^f[g>>>16&255]<<16^f[h>>>8&255]<<8^f[255&d]^e[++S],r[n?1:3]=f[g>>>24]<<24^f[h>>>16&255]<<16^f[d>>>8&255]<<8^f[255&y]^e[++S]}function d(e){var t,r="AES-"+((e=e||{}).mode||"CBC").toUpperCase(),a=(t=e.decrypt?n.cipher.createDecipher(r,e.key):n.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var i=null;r instanceof n.util.ByteBuffer&&(i=r,r={}),(r=r||{}).output=i,r.iv=e,a.call(t,r)},t}},function(e,t,r){var n=r(0);n.pki=n.pki||{};var a=e.exports=n.pki.oids=n.oids=n.oids||{};function i(e,t){a[e]=t,a[t]=e}function s(e,t){a[e]=t}i("1.2.840.113549.1.1.1","rsaEncryption"),i("1.2.840.113549.1.1.4","md5WithRSAEncryption"),i("1.2.840.113549.1.1.5","sha1WithRSAEncryption"),i("1.2.840.113549.1.1.7","RSAES-OAEP"),i("1.2.840.113549.1.1.8","mgf1"),i("1.2.840.113549.1.1.9","pSpecified"),i("1.2.840.113549.1.1.10","RSASSA-PSS"),i("1.2.840.113549.1.1.11","sha256WithRSAEncryption"),i("1.2.840.113549.1.1.12","sha384WithRSAEncryption"),i("1.2.840.113549.1.1.13","sha512WithRSAEncryption"),i("1.3.101.112","EdDSA25519"),i("1.2.840.10040.4.3","dsa-with-sha1"),i("1.3.14.3.2.7","desCBC"),i("1.3.14.3.2.26","sha1"),i("1.3.14.3.2.29","sha1WithRSASignature"),i("2.16.840.1.101.3.4.2.1","sha256"),i("2.16.840.1.101.3.4.2.2","sha384"),i("2.16.840.1.101.3.4.2.3","sha512"),i("2.16.840.1.101.3.4.2.4","sha224"),i("2.16.840.1.101.3.4.2.5","sha512-224"),i("2.16.840.1.101.3.4.2.6","sha512-256"),i("1.2.840.113549.2.2","md2"),i("1.2.840.113549.2.5","md5"),i("1.2.840.113549.1.7.1","data"),i("1.2.840.113549.1.7.2","signedData"),i("1.2.840.113549.1.7.3","envelopedData"),i("1.2.840.113549.1.7.4","signedAndEnvelopedData"),i("1.2.840.113549.1.7.5","digestedData"),i("1.2.840.113549.1.7.6","encryptedData"),i("1.2.840.113549.1.9.1","emailAddress"),i("1.2.840.113549.1.9.2","unstructuredName"),i("1.2.840.113549.1.9.3","contentType"),i("1.2.840.113549.1.9.4","messageDigest"),i("1.2.840.113549.1.9.5","signingTime"),i("1.2.840.113549.1.9.6","counterSignature"),i("1.2.840.113549.1.9.7","challengePassword"),i("1.2.840.113549.1.9.8","unstructuredAddress"),i("1.2.840.113549.1.9.14","extensionRequest"),i("1.2.840.113549.1.9.20","friendlyName"),i("1.2.840.113549.1.9.21","localKeyId"),i("1.2.840.113549.1.9.22.1","x509Certificate"),i("1.2.840.113549.1.12.10.1.1","keyBag"),i("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag"),i("1.2.840.113549.1.12.10.1.3","certBag"),i("1.2.840.113549.1.12.10.1.4","crlBag"),i("1.2.840.113549.1.12.10.1.5","secretBag"),i("1.2.840.113549.1.12.10.1.6","safeContentsBag"),i("1.2.840.113549.1.5.13","pkcs5PBES2"),i("1.2.840.113549.1.5.12","pkcs5PBKDF2"),i("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4"),i("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4"),i("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC"),i("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC"),i("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC"),i("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC"),i("1.2.840.113549.2.7","hmacWithSHA1"),i("1.2.840.113549.2.8","hmacWithSHA224"),i("1.2.840.113549.2.9","hmacWithSHA256"),i("1.2.840.113549.2.10","hmacWithSHA384"),i("1.2.840.113549.2.11","hmacWithSHA512"),i("1.2.840.113549.3.7","des-EDE3-CBC"),i("2.16.840.1.101.3.4.1.2","aes128-CBC"),i("2.16.840.1.101.3.4.1.22","aes192-CBC"),i("2.16.840.1.101.3.4.1.42","aes256-CBC"),i("2.5.4.3","commonName"),i("2.5.4.4","surname"),i("2.5.4.5","serialNumber"),i("2.5.4.6","countryName"),i("2.5.4.7","localityName"),i("2.5.4.8","stateOrProvinceName"),i("2.5.4.9","streetAddress"),i("2.5.4.10","organizationName"),i("2.5.4.11","organizationalUnitName"),i("2.5.4.12","title"),i("2.5.4.13","description"),i("2.5.4.15","businessCategory"),i("2.5.4.17","postalCode"),i("2.5.4.42","givenName"),i("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName"),i("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName"),i("2.16.840.1.113730.1.1","nsCertType"),i("2.16.840.1.113730.1.13","nsComment"),s("2.5.29.1","authorityKeyIdentifier"),s("2.5.29.2","keyAttributes"),s("2.5.29.3","certificatePolicies"),s("2.5.29.4","keyUsageRestriction"),s("2.5.29.5","policyMapping"),s("2.5.29.6","subtreesConstraint"),s("2.5.29.7","subjectAltName"),s("2.5.29.8","issuerAltName"),s("2.5.29.9","subjectDirectoryAttributes"),s("2.5.29.10","basicConstraints"),s("2.5.29.11","nameConstraints"),s("2.5.29.12","policyConstraints"),s("2.5.29.13","basicConstraints"),i("2.5.29.14","subjectKeyIdentifier"),i("2.5.29.15","keyUsage"),s("2.5.29.16","privateKeyUsagePeriod"),i("2.5.29.17","subjectAltName"),i("2.5.29.18","issuerAltName"),i("2.5.29.19","basicConstraints"),s("2.5.29.20","cRLNumber"),s("2.5.29.21","cRLReason"),s("2.5.29.22","expirationDate"),s("2.5.29.23","instructionCode"),s("2.5.29.24","invalidityDate"),s("2.5.29.25","cRLDistributionPoints"),s("2.5.29.26","issuingDistributionPoint"),s("2.5.29.27","deltaCRLIndicator"),s("2.5.29.28","issuingDistributionPoint"),s("2.5.29.29","certificateIssuer"),s("2.5.29.30","nameConstraints"),i("2.5.29.31","cRLDistributionPoints"),i("2.5.29.32","certificatePolicies"),s("2.5.29.33","policyMappings"),s("2.5.29.34","policyConstraints"),i("2.5.29.35","authorityKeyIdentifier"),s("2.5.29.36","policyConstraints"),i("2.5.29.37","extKeyUsage"),s("2.5.29.46","freshestCRL"),s("2.5.29.54","inhibitAnyPolicy"),i("1.3.6.1.4.1.11129.2.4.2","timestampList"),i("1.3.6.1.5.5.7.1.1","authorityInfoAccess"),i("1.3.6.1.5.5.7.3.1","serverAuth"),i("1.3.6.1.5.5.7.3.2","clientAuth"),i("1.3.6.1.5.5.7.3.3","codeSigning"),i("1.3.6.1.5.5.7.3.4","emailProtection"),i("1.3.6.1.5.5.7.3.8","timeStamping")},function(e,t,r){var n=r(0);r(1);var a=e.exports=n.pem=n.pem||{};function i(e){for(var t=e.name+": ",r=[],n=function(e,t){return" "+t},a=0;a65&&-1!==s){var o=t[s];","===o?(++s,t=t.substr(0,s)+"\r\n "+t.substr(s)):t=t.substr(0,s)+"\r\n"+o+t.substr(s+1),i=a-s-1,s=-1,++a}else" "!==t[a]&&"\t"!==t[a]&&","!==t[a]||(s=a);return t}function s(e){return e.replace(/^\s+/,"")}a.encode=function(e,t){t=t||{};var r,a="-----BEGIN "+e.type+"-----\r\n";if(e.procType&&(a+=i(r={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]})),e.contentDomain&&(a+=i(r={name:"Content-Domain",values:[e.contentDomain]})),e.dekInfo&&(r={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters&&r.values.push(e.dekInfo.parameters),a+=i(r)),e.headers)for(var s=0;st.blockLength&&(t.start(),t.update(s.bytes()),s=t.digest()),r=n.util.createBuffer(),a=n.util.createBuffer(),u=s.length();for(c=0;c>>0,c>>>0];for(var u=a.fullMessageLength.length-1;u>=0;--u)a.fullMessageLength[u]+=c[1],c[1]=c[0]+(a.fullMessageLength[u]/4294967296>>>0),a.fullMessageLength[u]=a.fullMessageLength[u]>>>0,c[0]=c[1]/4294967296>>>0;return t.putBytes(i),o(e,r,t),(t.read>2048||0===t.length())&&t.compact(),a},a.digest=function(){var s=n.util.createBuffer();s.putBytes(t.bytes());var c,u=a.fullMessageLength[a.fullMessageLength.length-1]+a.messageLengthSize&a.blockLength-1;s.putBytes(i.substr(0,a.blockLength-u));for(var l=8*a.fullMessageLength[0],p=0;p>>0,s.putInt32(l>>>0),l=c>>>0;s.putInt32(l);var f={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};o(f,r,s);var h=n.util.createBuffer();return h.putInt32(f.h0),h.putInt32(f.h1),h.putInt32(f.h2),h.putInt32(f.h3),h.putInt32(f.h4),h},a};var i=null,s=!1;function o(e,t,r){for(var n,a,i,s,o,c,u,l=r.length();l>=64;){for(a=e.h0,i=e.h1,s=e.h2,o=e.h3,c=e.h4,u=0;u<16;++u)n=r.getInt32(),t[u]=n,n=(a<<5|a>>>27)+(o^i&(s^o))+c+1518500249+n,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=a,a=n;for(;u<20;++u)n=(n=t[u-3]^t[u-8]^t[u-14]^t[u-16])<<1|n>>>31,t[u]=n,n=(a<<5|a>>>27)+(o^i&(s^o))+c+1518500249+n,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=a,a=n;for(;u<32;++u)n=(n=t[u-3]^t[u-8]^t[u-14]^t[u-16])<<1|n>>>31,t[u]=n,n=(a<<5|a>>>27)+(i^s^o)+c+1859775393+n,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=a,a=n;for(;u<40;++u)n=(n=t[u-6]^t[u-16]^t[u-28]^t[u-32])<<2|n>>>30,t[u]=n,n=(a<<5|a>>>27)+(i^s^o)+c+1859775393+n,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=a,a=n;for(;u<60;++u)n=(n=t[u-6]^t[u-16]^t[u-28]^t[u-32])<<2|n>>>30,t[u]=n,n=(a<<5|a>>>27)+(i&s|o&(i^s))+c+2400959708+n,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=a,a=n;for(;u<80;++u)n=(n=t[u-6]^t[u-16]^t[u-28]^t[u-32])<<2|n>>>30,t[u]=n,n=(a<<5|a>>>27)+(i^s^o)+c+3395469782+n,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=a,a=n;e.h0=e.h0+a|0,e.h1=e.h1+i|0,e.h2=e.h2+s|0,e.h3=e.h3+o|0,e.h4=e.h4+c|0,l-=64}}},function(e,t,r){var n=r(0);r(3),r(8),r(15),r(7),r(21),r(2),r(9),r(1);var a=function(e,t,r,a){var i=n.util.createBuffer(),s=e.length>>1,o=s+(1&e.length),c=e.substr(0,o),u=e.substr(s,o),l=n.util.createBuffer(),p=n.hmac.create();r=t+r;var f=Math.ceil(a/16),h=Math.ceil(a/20);p.start("MD5",c);var d=n.util.createBuffer();l.putBytes(r);for(var y=0;y0&&(u.queue(e,u.createAlert(e,{level:u.Alert.Level.warning,description:u.Alert.Description.no_renegotiation})),u.flush(e)),e.process()},u.parseHelloMessage=function(e,t,r){var a=null,i=e.entity===u.ConnectionEnd.client;if(r<38)e.error(e,{message:i?"Invalid ServerHello message. Message too short.":"Invalid ClientHello message. Message too short.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.illegal_parameter}});else{var s=t.fragment,c=s.length();if(a={version:{major:s.getByte(),minor:s.getByte()},random:n.util.createBuffer(s.getBytes(32)),session_id:o(s,1),extensions:[]},i?(a.cipher_suite=s.getBytes(2),a.compression_method=s.getByte()):(a.cipher_suites=o(s,2),a.compression_methods=o(s,1)),(c=r-(c-s.length()))>0){for(var l=o(s,2);l.length()>0;)a.extensions.push({type:[l.getByte(),l.getByte()],data:o(l,2)});if(!i)for(var p=0;p0;){if(0!==h.getByte())break;e.session.extensions.server_name.serverNameList.push(o(h,2).getBytes())}}}if(e.session.version&&(a.version.major!==e.session.version.major||a.version.minor!==e.session.version.minor))return e.error(e,{message:"TLS version change is disallowed during renegotiation.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.protocol_version}});if(i)e.session.cipherSuite=u.getCipherSuite(a.cipher_suite);else for(var d=n.util.createBuffer(a.cipher_suites.bytes());d.length()>0&&(e.session.cipherSuite=u.getCipherSuite(d.getBytes(2)),null===e.session.cipherSuite););if(null===e.session.cipherSuite)return e.error(e,{message:"No cipher suites in common.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.handshake_failure},cipherSuite:n.util.bytesToHex(a.cipher_suite)});e.session.compressionMethod=i?a.compression_method:u.CompressionMethod.none}return a},u.createSecurityParameters=function(e,t){var r=e.entity===u.ConnectionEnd.client,n=t.random.bytes(),a=r?e.session.sp.client_random:n,i=r?n:u.createRandom().getBytes();e.session.sp={entity:e.entity,prf_algorithm:u.PRFAlgorithm.tls_prf_sha256,bulk_cipher_algorithm:null,cipher_type:null,enc_key_length:null,block_length:null,fixed_iv_length:null,record_iv_length:null,mac_algorithm:null,mac_length:null,mac_key_length:null,compression_algorithm:e.session.compressionMethod,pre_master_secret:null,master_secret:null,client_random:a,server_random:i}},u.handleServerHello=function(e,t,r){var n=u.parseHelloMessage(e,t,r);if(!e.fail){if(!(n.version.minor<=e.version.minor))return e.error(e,{message:"Incompatible TLS version.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.protocol_version}});e.version.minor=n.version.minor,e.session.version=e.version;var a=n.session_id.bytes();a.length>0&&a===e.session.id?(e.expect=d,e.session.resuming=!0,e.session.sp.server_random=n.random.bytes()):(e.expect=l,e.session.resuming=!1,u.createSecurityParameters(e,n)),e.session.id=a,e.process()}},u.handleClientHello=function(e,t,r){var a=u.parseHelloMessage(e,t,r);if(!e.fail){var i=a.session_id.bytes(),s=null;if(e.sessionCache&&(null===(s=e.sessionCache.getSession(i))?i="":(s.version.major!==a.version.major||s.version.minor>a.version.minor)&&(s=null,i="")),0===i.length&&(i=n.random.getBytes(32)),e.session.id=i,e.session.clientHelloVersion=a.version,e.session.sp={},s)e.version=e.session.version=s.version,e.session.sp=s.sp;else{for(var o,c=1;c0;)a=o(c.certificate_list,3),i=n.asn1.fromDer(a),a=n.pki.certificateFromAsn1(i,!0),l.push(a)}catch(t){return e.error(e,{message:"Could not parse certificate list.",cause:t,send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.bad_certificate}})}var f=e.entity===u.ConnectionEnd.client;!f&&!0!==e.verifyClient||0!==l.length?0===l.length?e.expect=f?p:C:(f?e.session.serverCertificate=l[0]:e.session.clientCertificate=l[0],u.verifyCertificateChain(e,l)&&(e.expect=f?p:C)):e.error(e,{message:f?"No server certificate provided.":"No client certificate provided.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.illegal_parameter}}),e.process()},u.handleServerKeyExchange=function(e,t,r){if(r>0)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.unsupported_certificate}});e.expect=f,e.process()},u.handleClientKeyExchange=function(e,t,r){if(r<48)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.unsupported_certificate}});var a=t.fragment,i={enc_pre_master_secret:o(a,2).getBytes()},s=null;if(e.getPrivateKey)try{s=e.getPrivateKey(e,e.session.serverCertificate),s=n.pki.privateKeyFromPem(s)}catch(t){e.error(e,{message:"Could not get private key.",cause:t,send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.internal_error}})}if(null===s)return e.error(e,{message:"No private key set.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.internal_error}});try{var c=e.session.sp;c.pre_master_secret=s.decrypt(i.enc_pre_master_secret);var l=e.session.clientHelloVersion;if(l.major!==c.pre_master_secret.charCodeAt(0)||l.minor!==c.pre_master_secret.charCodeAt(1))throw new Error("TLS version rollback attack detected.")}catch(e){c.pre_master_secret=n.random.getBytes(48)}e.expect=S,null!==e.session.clientCertificate&&(e.expect=E),e.process()},u.handleCertificateRequest=function(e,t,r){if(r<3)return e.error(e,{message:"Invalid CertificateRequest. Message too short.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.illegal_parameter}});var n=t.fragment,a={certificate_types:o(n,1),certificate_authorities:o(n,2)};e.session.certificateRequest=a,e.expect=h,e.process()},u.handleCertificateVerify=function(e,t,r){if(r<2)return e.error(e,{message:"Invalid CertificateVerify. Message too short.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.illegal_parameter}});var a=t.fragment;a.read-=4;var i=a.bytes();a.read+=4;var s={signature:o(a,2).getBytes()},c=n.util.createBuffer();c.putBuffer(e.session.md5.digest()),c.putBuffer(e.session.sha1.digest()),c=c.getBytes();try{if(!e.session.clientCertificate.publicKey.verify(c,s.signature,"NONE"))throw new Error("CertificateVerify signature does not match.");e.session.md5.update(i),e.session.sha1.update(i)}catch(t){return e.error(e,{message:"Bad signature in CertificateVerify.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.handshake_failure}})}e.expect=S,e.process()},u.handleServerHelloDone=function(e,t,r){if(r>0)return e.error(e,{message:"Invalid ServerHelloDone message. Invalid length.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.record_overflow}});if(null===e.serverCertificate){var a={message:"No server certificate provided. Not enough security.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.insufficient_security}},i=e.verify(e,a.alert.description,0,[]);if(!0!==i)return(i||0===i)&&("object"!=typeof i||n.util.isArray(i)?"number"==typeof i&&(a.alert.description=i):(i.message&&(a.message=i.message),i.alert&&(a.alert.description=i.alert))),e.error(e,a)}null!==e.session.certificateRequest&&(t=u.createRecord(e,{type:u.ContentType.handshake,data:u.createCertificate(e)}),u.queue(e,t)),t=u.createRecord(e,{type:u.ContentType.handshake,data:u.createClientKeyExchange(e)}),u.queue(e,t),e.expect=v;var s=function(e,t){null!==e.session.certificateRequest&&null!==e.session.clientCertificate&&u.queue(e,u.createRecord(e,{type:u.ContentType.handshake,data:u.createCertificateVerify(e,t)})),u.queue(e,u.createRecord(e,{type:u.ContentType.change_cipher_spec,data:u.createChangeCipherSpec()})),e.state.pending=u.createConnectionState(e),e.state.current.write=e.state.pending.write,u.queue(e,u.createRecord(e,{type:u.ContentType.handshake,data:u.createFinished(e)})),e.expect=d,u.flush(e),e.process()};if(null===e.session.certificateRequest||null===e.session.clientCertificate)return s(e,null);u.getClientSignature(e,s)},u.handleChangeCipherSpec=function(e,t){if(1!==t.fragment.getByte())return e.error(e,{message:"Invalid ChangeCipherSpec message received.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.illegal_parameter}});var r=e.entity===u.ConnectionEnd.client;(e.session.resuming&&r||!e.session.resuming&&!r)&&(e.state.pending=u.createConnectionState(e)),e.state.current.read=e.state.pending.read,(!e.session.resuming&&r||e.session.resuming&&!r)&&(e.state.pending=null),e.expect=r?y:T,e.process()},u.handleFinished=function(e,t,r){var i=t.fragment;i.read-=4;var s=i.bytes();i.read+=4;var o=t.fragment.getBytes();(i=n.util.createBuffer()).putBuffer(e.session.md5.digest()),i.putBuffer(e.session.sha1.digest());var c=e.entity===u.ConnectionEnd.client,l=c?"server finished":"client finished",p=e.session.sp;if((i=a(p.master_secret,l,i.getBytes(),12)).getBytes()!==o)return e.error(e,{message:"Invalid verify_data in Finished message.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.decrypt_error}});e.session.md5.update(s),e.session.sha1.update(s),(e.session.resuming&&c||!e.session.resuming&&!c)&&(u.queue(e,u.createRecord(e,{type:u.ContentType.change_cipher_spec,data:u.createChangeCipherSpec()})),e.state.current.write=e.state.pending.write,e.state.pending=null,u.queue(e,u.createRecord(e,{type:u.ContentType.handshake,data:u.createFinished(e)}))),e.expect=c?g:I,e.handshaking=!1,++e.handshakes,e.peerCertificate=c?e.session.serverCertificate:e.session.clientCertificate,u.flush(e),e.isConnected=!0,e.connected(e),e.process()},u.handleAlert=function(e,t){var r,n=t.fragment,a={level:n.getByte(),description:n.getByte()};switch(a.description){case u.Alert.Description.close_notify:r="Connection closed.";break;case u.Alert.Description.unexpected_message:r="Unexpected message.";break;case u.Alert.Description.bad_record_mac:r="Bad record MAC.";break;case u.Alert.Description.decryption_failed:r="Decryption failed.";break;case u.Alert.Description.record_overflow:r="Record overflow.";break;case u.Alert.Description.decompression_failure:r="Decompression failed.";break;case u.Alert.Description.handshake_failure:r="Handshake failure.";break;case u.Alert.Description.bad_certificate:r="Bad certificate.";break;case u.Alert.Description.unsupported_certificate:r="Unsupported certificate.";break;case u.Alert.Description.certificate_revoked:r="Certificate revoked.";break;case u.Alert.Description.certificate_expired:r="Certificate expired.";break;case u.Alert.Description.certificate_unknown:r="Certificate unknown.";break;case u.Alert.Description.illegal_parameter:r="Illegal parameter.";break;case u.Alert.Description.unknown_ca:r="Unknown certificate authority.";break;case u.Alert.Description.access_denied:r="Access denied.";break;case u.Alert.Description.decode_error:r="Decode error.";break;case u.Alert.Description.decrypt_error:r="Decrypt error.";break;case u.Alert.Description.export_restriction:r="Export restriction.";break;case u.Alert.Description.protocol_version:r="Unsupported protocol version.";break;case u.Alert.Description.insufficient_security:r="Insufficient security.";break;case u.Alert.Description.internal_error:r="Internal error.";break;case u.Alert.Description.user_canceled:r="User canceled.";break;case u.Alert.Description.no_renegotiation:r="Renegotiation not supported.";break;default:r="Unknown error."}if(a.description===u.Alert.Description.close_notify)return e.close();e.error(e,{message:r,send:!1,origin:e.entity===u.ConnectionEnd.client?"server":"client",alert:a}),e.process()},u.handleHandshake=function(e,t){var r=t.fragment,a=r.getByte(),i=r.getInt24();if(i>r.length())return e.fragmented=t,t.fragment=n.util.createBuffer(),r.read-=4,e.process();e.fragmented=null,r.read-=4;var s=r.bytes(i+4);r.read+=4,a in x[e.entity][e.expect]?(e.entity!==u.ConnectionEnd.server||e.open||e.fail||(e.handshaking=!0,e.session={version:null,extensions:{server_name:{serverNameList:[]}},cipherSuite:null,compressionMethod:null,serverCertificate:null,clientCertificate:null,md5:n.md.md5.create(),sha1:n.md.sha1.create()}),a!==u.HandshakeType.hello_request&&a!==u.HandshakeType.certificate_verify&&a!==u.HandshakeType.finished&&(e.session.md5.update(s),e.session.sha1.update(s)),x[e.entity][e.expect][a](e,t,i)):u.handleUnexpected(e,t)},u.handleApplicationData=function(e,t){e.data.putBuffer(t.fragment),e.dataReady(e),e.process()},u.handleHeartbeat=function(e,t){var r=t.fragment,a=r.getByte(),i=r.getInt16(),s=r.getBytes(i);if(a===u.HeartbeatMessageType.heartbeat_request){if(e.handshaking||i>s.length)return e.process();u.queue(e,u.createRecord(e,{type:u.ContentType.heartbeat,data:u.createHeartbeat(u.HeartbeatMessageType.heartbeat_response,s)})),u.flush(e)}else if(a===u.HeartbeatMessageType.heartbeat_response){if(s!==e.expectedHeartbeatPayload)return e.process();e.heartbeatReceived&&e.heartbeatReceived(e,n.util.createBuffer(s))}e.process()};var l=1,p=2,f=3,h=4,d=5,y=6,g=7,v=8,m=1,C=2,E=3,S=4,T=5,I=6,b=u.handleUnexpected,A=u.handleChangeCipherSpec,B=u.handleAlert,N=u.handleHandshake,k=u.handleApplicationData,w=u.handleHeartbeat,R=[];R[u.ConnectionEnd.client]=[[b,B,N,b,w],[b,B,N,b,w],[b,B,N,b,w],[b,B,N,b,w],[b,B,N,b,w],[A,B,b,b,w],[b,B,N,b,w],[b,B,N,k,w],[b,B,N,b,w]],R[u.ConnectionEnd.server]=[[b,B,N,b,w],[b,B,N,b,w],[b,B,N,b,w],[b,B,N,b,w],[A,B,b,b,w],[b,B,N,b,w],[b,B,N,k,w],[b,B,N,b,w]];var L=u.handleHelloRequest,_=u.handleServerHello,U=u.handleCertificate,D=u.handleServerKeyExchange,P=u.handleCertificateRequest,V=u.handleServerHelloDone,O=u.handleFinished,x=[];x[u.ConnectionEnd.client]=[[b,b,_,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b],[L,b,b,b,b,b,b,b,b,b,b,U,D,P,V,b,b,b,b,b,b],[L,b,b,b,b,b,b,b,b,b,b,b,D,P,V,b,b,b,b,b,b],[L,b,b,b,b,b,b,b,b,b,b,b,b,P,V,b,b,b,b,b,b],[L,b,b,b,b,b,b,b,b,b,b,b,b,b,V,b,b,b,b,b,b],[L,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b],[L,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,O],[L,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b],[L,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b]];var K=u.handleClientHello,M=u.handleClientKeyExchange,F=u.handleCertificateVerify;x[u.ConnectionEnd.server]=[[b,K,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b],[b,b,b,b,b,b,b,b,b,b,b,U,b,b,b,b,b,b,b,b,b],[b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,M,b,b,b,b],[b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,F,b,b,b,b,b],[b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b],[b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,O],[b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b],[b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b]],u.generateKeys=function(e,t){var r=a,n=t.client_random+t.server_random;e.session.resuming||(t.master_secret=r(t.pre_master_secret,"master secret",n,48).bytes(),t.pre_master_secret=null),n=t.server_random+t.client_random;var i=2*t.mac_key_length+2*t.enc_key_length,s=e.version.major===u.Versions.TLS_1_0.major&&e.version.minor===u.Versions.TLS_1_0.minor;s&&(i+=2*t.fixed_iv_length);var o=r(t.master_secret,"key expansion",n,i),c={client_write_MAC_key:o.getBytes(t.mac_key_length),server_write_MAC_key:o.getBytes(t.mac_key_length),client_write_key:o.getBytes(t.enc_key_length),server_write_key:o.getBytes(t.enc_key_length)};return s&&(c.client_write_IV=o.getBytes(t.fixed_iv_length),c.server_write_IV=o.getBytes(t.fixed_iv_length)),c},u.createConnectionState=function(e){var t=e.entity===u.ConnectionEnd.client,r=function(){var e={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(e){return!0},compressionState:null,compressFunction:function(e){return!0},updateSequenceNumber:function(){4294967295===e.sequenceNumber[1]?(e.sequenceNumber[1]=0,++e.sequenceNumber[0]):++e.sequenceNumber[1]}};return e},n={read:r(),write:r()};if(n.read.update=function(e,t){return n.read.cipherFunction(t,n.read)?n.read.compressFunction(e,t,n.read)||e.error(e,{message:"Could not decompress record.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.decompression_failure}}):e.error(e,{message:"Could not decrypt record or bad MAC.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.bad_record_mac}}),!e.fail},n.write.update=function(e,t){return n.write.compressFunction(e,t,n.write)?n.write.cipherFunction(t,n.write)||e.error(e,{message:"Could not encrypt record.",send:!1,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.internal_error}}):e.error(e,{message:"Could not compress record.",send:!1,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.internal_error}}),!e.fail},e.session){var a=e.session.sp;switch(e.session.cipherSuite.initSecurityParameters(a),a.keys=u.generateKeys(e,a),n.read.macKey=t?a.keys.server_write_MAC_key:a.keys.client_write_MAC_key,n.write.macKey=t?a.keys.client_write_MAC_key:a.keys.server_write_MAC_key,e.session.cipherSuite.initConnectionState(n,e,a),a.compression_algorithm){case u.CompressionMethod.none:break;case u.CompressionMethod.deflate:n.read.compressFunction=s,n.write.compressFunction=i;break;default:throw new Error("Unsupported compression algorithm.")}}return n},u.createRandom=function(){var e=new Date,t=+e+6e4*e.getTimezoneOffset(),r=n.util.createBuffer();return r.putInt32(t),r.putBytes(n.random.getBytes(28)),r},u.createRecord=function(e,t){return t.data?{type:t.type,version:{major:e.version.major,minor:e.version.minor},length:t.data.length(),fragment:t.data}:null},u.createAlert=function(e,t){var r=n.util.createBuffer();return r.putByte(t.level),r.putByte(t.description),u.createRecord(e,{type:u.ContentType.alert,data:r})},u.createClientHello=function(e){e.session.clientHelloVersion={major:e.version.major,minor:e.version.minor};for(var t=n.util.createBuffer(),r=0;r0&&(d+=2);var y=e.session.id,g=y.length+1+2+4+28+2+i+1+o+d,v=n.util.createBuffer();return v.putByte(u.HandshakeType.client_hello),v.putInt24(g),v.putByte(e.version.major),v.putByte(e.version.minor),v.putBytes(e.session.sp.client_random),c(v,1,n.util.createBuffer(y)),c(v,2,t),c(v,1,s),d>0&&c(v,2,l),v},u.createServerHello=function(e){var t=e.session.id,r=t.length+1+2+4+28+2+1,a=n.util.createBuffer();return a.putByte(u.HandshakeType.server_hello),a.putInt24(r),a.putByte(e.version.major),a.putByte(e.version.minor),a.putBytes(e.session.sp.server_random),c(a,1,n.util.createBuffer(t)),a.putByte(e.session.cipherSuite.id[0]),a.putByte(e.session.cipherSuite.id[1]),a.putByte(e.session.compressionMethod),a},u.createCertificate=function(e){var t,r=e.entity===u.ConnectionEnd.client,a=null;e.getCertificate&&(t=r?e.session.certificateRequest:e.session.extensions.server_name.serverNameList,a=e.getCertificate(e,t));var i=n.util.createBuffer();if(null!==a)try{n.util.isArray(a)||(a=[a]);for(var s=null,o=0;ou.MaxFragment;)a.push(u.createRecord(e,{type:t.type,data:n.util.createBuffer(i.slice(0,u.MaxFragment))})),i=i.slice(u.MaxFragment);i.length>0&&a.push(u.createRecord(e,{type:t.type,data:n.util.createBuffer(i)}))}for(var s=0;s0&&(a=r.order[0]),null!==a&&a in r.cache)for(var i in t=r.cache[a],delete r.cache[a],r.order)if(r.order[i]===a){r.order.splice(i,1);break}return t},r.setSession=function(e,t){if(r.order.length===r.capacity){var a=r.order.shift();delete r.cache[a]}a=n.util.bytesToHex(e);r.order.push(a),r.cache[a]=t}}return r},u.createConnection=function(e){var t=null;t=e.caStore?n.util.isArray(e.caStore)?n.pki.createCaStore(e.caStore):e.caStore:n.pki.createCaStore();var r=e.cipherSuites||null;if(null===r)for(var a in r=[],u.CipherSuites)r.push(u.CipherSuites[a]);var i=e.server?u.ConnectionEnd.server:u.ConnectionEnd.client,s=e.sessionCache?u.createSessionCache(e.sessionCache):null,o={version:{major:u.Version.major,minor:u.Version.minor},entity:i,sessionId:e.sessionId,caStore:t,sessionCache:s,cipherSuites:r,connected:e.connected,virtualHost:e.virtualHost||null,verifyClient:e.verifyClient||!1,verify:e.verify||function(e,t,r,n){return t},verifyOptions:e.verifyOptions||{},getCertificate:e.getCertificate||null,getPrivateKey:e.getPrivateKey||null,getSignature:e.getSignature||null,input:n.util.createBuffer(),tlsData:n.util.createBuffer(),data:n.util.createBuffer(),tlsDataReady:e.tlsDataReady,dataReady:e.dataReady,heartbeatReceived:e.heartbeatReceived,closed:e.closed,error:function(t,r){r.origin=r.origin||(t.entity===u.ConnectionEnd.client?"client":"server"),r.send&&(u.queue(t,u.createAlert(t,r.alert)),u.flush(t));var n=!1!==r.fatal;n&&(t.fail=!0),e.error(t,r),n&&t.close(!1)},deflate:e.deflate||null,inflate:e.inflate||null,reset:function(e){o.version={major:u.Version.major,minor:u.Version.minor},o.record=null,o.session=null,o.peerCertificate=null,o.state={pending:null,current:null},o.expect=(o.entity,u.ConnectionEnd.client,0),o.fragmented=null,o.records=[],o.open=!1,o.handshakes=0,o.handshaking=!1,o.isConnected=!1,o.fail=!(e||void 0===e),o.input.clear(),o.tlsData.clear(),o.data.clear(),o.state.current=u.createConnectionState(o)}};o.reset();return o.handshake=function(e){if(o.entity!==u.ConnectionEnd.client)o.error(o,{message:"Cannot initiate handshake as a server.",fatal:!1});else if(o.handshaking)o.error(o,{message:"Handshake already in progress.",fatal:!1});else{o.fail&&!o.open&&0===o.handshakes&&(o.fail=!1),o.handshaking=!0;var t=null;(e=e||"").length>0&&(o.sessionCache&&(t=o.sessionCache.getSession(e)),null===t&&(e="")),0===e.length&&o.sessionCache&&null!==(t=o.sessionCache.getSession())&&(e=t.id),o.session={id:e,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:n.md.md5.create(),sha1:n.md.sha1.create()},t&&(o.version=t.version,o.session.sp=t.sp),o.session.sp.client_random=u.createRandom().getBytes(),o.open=!0,u.queue(o,u.createRecord(o,{type:u.ContentType.handshake,data:u.createClientHello(o)})),u.flush(o)}},o.process=function(e){var t=0;return e&&o.input.putBytes(e),o.fail||(null!==o.record&&o.record.ready&&o.record.fragment.isEmpty()&&(o.record=null),null===o.record&&(t=function(e){var t=0,r=e.input,a=r.length();if(a<5)t=5-a;else{e.record={type:r.getByte(),version:{major:r.getByte(),minor:r.getByte()},length:r.getInt16(),fragment:n.util.createBuffer(),ready:!1};var i=e.record.version.major===e.version.major;i&&e.session&&e.session.version&&(i=e.record.version.minor===e.version.minor),i||e.error(e,{message:"Incompatible TLS version.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.protocol_version}})}return t}(o)),o.fail||null===o.record||o.record.ready||(t=function(e){var t=0,r=e.input,n=r.length();n8?3:1,v=[],m=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],C=0,E=0;E>>4^T))<<4,S^=t=65535&((T^=t)>>>-16^S),S^=(t=858993459&(S>>>2^(T^=t<<-16)))<<2,S^=t=65535&((T^=t)>>>-16^S),S^=(t=1431655765&(S>>>1^(T^=t<<-16)))<<1,S^=t=16711935&((T^=t)>>>8^S),t=(S^=(t=1431655765&(S>>>1^(T^=t<<8)))<<1)<<8|(T^=t)>>>20&240,S=T<<24|T<<8&16711680|T>>>8&65280|T>>>24&240,T=t;for(var I=0;I>>26,T=T<<2|T>>>26):(S=S<<1|S>>>27,T=T<<1|T>>>27);var b=r[(S&=-15)>>>28]|n[S>>>24&15]|a[S>>>20&15]|i[S>>>16&15]|s[S>>>12&15]|o[S>>>8&15]|c[S>>>4&15],A=u[(T&=-15)>>>28]|l[T>>>24&15]|p[T>>>20&15]|f[T>>>16&15]|h[T>>>12&15]|d[T>>>8&15]|y[T>>>4&15];t=65535&(A>>>16^b),v[C++]=b^t,v[C++]=A^t<<16}}return v}(t),this._init=!0}},a("DES-ECB",n.cipher.modes.ecb),a("DES-CBC",n.cipher.modes.cbc),a("DES-CFB",n.cipher.modes.cfb),a("DES-OFB",n.cipher.modes.ofb),a("DES-CTR",n.cipher.modes.ctr),a("3DES-ECB",n.cipher.modes.ecb),a("3DES-CBC",n.cipher.modes.cbc),a("3DES-CFB",n.cipher.modes.cfb),a("3DES-OFB",n.cipher.modes.ofb),a("3DES-CTR",n.cipher.modes.ctr);var i=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],s=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],o=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],c=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],u=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],l=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],p=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],f=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function h(e,t,r,n){var a,h,d=32===e.length?3:9;a=3===d?n?[30,-2,-2]:[0,32,2]:n?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var y=t[0],g=t[1];y^=(h=252645135&(y>>>4^g))<<4,y^=(h=65535&(y>>>16^(g^=h)))<<16,y^=h=858993459&((g^=h)>>>2^y),y^=h=16711935&((g^=h<<2)>>>8^y),y=(y^=(h=1431655765&(y>>>1^(g^=h<<8)))<<1)<<1|y>>>31,g=(g^=h)<<1|g>>>31;for(var v=0;v>>4|g<<28)^e[E+1];h=y,y=g,g=h^(s[S>>>24&63]|c[S>>>16&63]|l[S>>>8&63]|f[63&S]|i[T>>>24&63]|o[T>>>16&63]|u[T>>>8&63]|p[63&T])}h=y,y=g,g=h}g=g>>>1|g<<31,g^=h=1431655765&((y=y>>>1|y<<31)>>>1^g),g^=(h=16711935&(g>>>8^(y^=h<<1)))<<8,g^=(h=858993459&(g>>>2^(y^=h)))<<2,g^=h=65535&((y^=h)>>>16^g),g^=h=252645135&((y^=h<<16)>>>4^g),y^=h<<4,r[0]=y,r[1]=g}function d(e){var t,r="DES-"+((e=e||{}).mode||"CBC").toUpperCase(),a=(t=e.decrypt?n.cipher.createDecipher(r,e.key):n.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var i=null;r instanceof n.util.ByteBuffer&&(i=r,r={}),(r=r||{}).output=i,r.iv=e,a.call(t,r)},t}},function(e,t,r){var n=r(0);if(r(3),r(13),r(6),r(26),r(27),r(2),r(1),void 0===a)var a=n.jsbn.BigInteger;var i=n.util.isNodejs?r(17):null,s=n.asn1,o=n.util;n.pki=n.pki||{},e.exports=n.pki.rsa=n.rsa=n.rsa||{};var c=n.pki,u=[6,4,2,4,2,4,6,2],l={name:"PrivateKeyInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},p={name:"RSAPrivateKey",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},f={name:"RSAPublicKey",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},h=n.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:s.Class.UNIVERSAL,type:s.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},d={name:"DigestInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:s.Class.UNIVERSAL,type:s.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},y=function(e){var t;if(!(e.algorithm in c.oids)){var r=new Error("Unknown message digest algorithm.");throw r.algorithm=e.algorithm,r}t=c.oids[e.algorithm];var n=s.oidToDer(t).getBytes(),a=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[]),i=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[]);i.value.push(s.create(s.Class.UNIVERSAL,s.Type.OID,!1,n)),i.value.push(s.create(s.Class.UNIVERSAL,s.Type.NULL,!1,""));var o=s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,e.digest().getBytes());return a.value.push(i),a.value.push(o),s.toDer(a).getBytes()},g=function(e,t,r){if(r)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);var i;t.dP||(t.dP=t.d.mod(t.p.subtract(a.ONE))),t.dQ||(t.dQ=t.d.mod(t.q.subtract(a.ONE))),t.qInv||(t.qInv=t.q.modInverse(t.p));do{i=new a(n.util.bytesToHex(n.random.getBytes(t.n.bitLength()/8)),16)}while(i.compareTo(t.n)>=0||!i.gcd(t.n).equals(a.ONE));for(var s=(e=e.multiply(i.modPow(t.e,t.n)).mod(t.n)).mod(t.p).modPow(t.dP,t.p),o=e.mod(t.q).modPow(t.dQ,t.q);s.compareTo(o)<0;)s=s.add(t.p);var c=s.subtract(o).multiply(t.qInv).mod(t.p).multiply(t.q).add(o);return c=c.multiply(i.modInverse(t.n)).mod(t.n)};function v(e,t,r){var a=n.util.createBuffer(),i=Math.ceil(t.n.bitLength()/8);if(e.length>i-11){var s=new Error("Message is too long for PKCS#1 v1.5 padding.");throw s.length=e.length,s.max=i-11,s}a.putByte(0),a.putByte(r);var o,c=i-3-e.length;if(0===r||1===r){o=0===r?0:255;for(var u=0;u0;){var l=0,p=n.random.getBytes(c);for(u=0;u1;){if(255!==s.getByte()){--s.read;break}++u}else if(2===c)for(u=0;s.length()>1;){if(0===s.getByte()){--s.read;break}++u}if(0!==s.getByte()||u!==i-3-s.length())throw new Error("Encryption block is invalid.");return s.getBytes()}function C(e,t,r){"function"==typeof t&&(r=t,t={});var i={algorithm:{name:(t=t||{}).algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};function s(){o(e.pBits,(function(t,n){return t?r(t):(e.p=n,null!==e.q?u(t,e.q):void o(e.qBits,u))}))}function o(e,t){n.prime.generateProbablePrime(e,i,t)}function u(t,n){if(t)return r(t);if(e.q=n,e.p.compareTo(e.q)<0){var i=e.p;e.p=e.q,e.q=i}if(0!==e.p.subtract(a.ONE).gcd(e.e).compareTo(a.ONE))return e.p=null,void s();if(0!==e.q.subtract(a.ONE).gcd(e.e).compareTo(a.ONE))return e.q=null,void o(e.qBits,u);if(e.p1=e.p.subtract(a.ONE),e.q1=e.q.subtract(a.ONE),e.phi=e.p1.multiply(e.q1),0!==e.phi.gcd(e.e).compareTo(a.ONE))return e.p=e.q=null,void s();if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits)return e.q=null,void o(e.qBits,u);var l=e.e.modInverse(e.phi);e.keys={privateKey:c.rsa.setPrivateKey(e.n,e.e,l,e.p,e.q,l.mod(e.p1),l.mod(e.q1),e.q.modInverse(e.p)),publicKey:c.rsa.setPublicKey(e.n,e.e)},r(null,e.keys)}"prng"in t&&(i.prng=t.prng),s()}function E(e){var t=e.toString(16);t[0]>="8"&&(t="00"+t);var r=n.util.hexToBytes(t);return r.length>1&&(0===r.charCodeAt(0)&&0==(128&r.charCodeAt(1))||255===r.charCodeAt(0)&&128==(128&r.charCodeAt(1)))?r.substr(1):r}function S(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}function T(e){return n.util.isNodejs&&"function"==typeof i[e]}function I(e){return void 0!==o.globalScope&&"object"==typeof o.globalScope.crypto&&"object"==typeof o.globalScope.crypto.subtle&&"function"==typeof o.globalScope.crypto.subtle[e]}function b(e){return void 0!==o.globalScope&&"object"==typeof o.globalScope.msCrypto&&"object"==typeof o.globalScope.msCrypto.subtle&&"function"==typeof o.globalScope.msCrypto.subtle[e]}function A(e){for(var t=n.util.hexToBytes(e.toString(16)),r=new Uint8Array(t.length),a=0;a0;)l.putByte(0),--p;return l.putBytes(n.util.hexToBytes(u)),l.getBytes()},c.rsa.decrypt=function(e,t,r,i){var s=Math.ceil(t.n.bitLength()/8);if(e.length!==s){var o=new Error("Encrypted message length is invalid.");throw o.length=e.length,o.expected=s,o}var c=new a(n.util.createBuffer(e).toHex(),16);if(c.compareTo(t.n)>=0)throw new Error("Encrypted message is invalid.");for(var u=g(c,t,r).toString(16),l=n.util.createBuffer(),p=s-Math.ceil(u.length/2);p>0;)l.putByte(0),--p;return l.putBytes(n.util.hexToBytes(u)),!1!==i?m(l.getBytes(),t,r):l.getBytes()},c.rsa.createKeyPairGenerationState=function(e,t,r){"string"==typeof e&&(e=parseInt(e,10)),e=e||2048;var i,s=(r=r||{}).prng||n.random,o={nextBytes:function(e){for(var t=s.getBytesSync(e.length),r=0;r>1,pBits:e-(e>>1),pqState:0,num:null,keys:null}).e.fromInt(i.eInt),i},c.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var r=new a(null);r.fromInt(30);for(var n,i=0,s=function(e,t){return e|t},o=+new Date,l=0;null===e.keys&&(t<=0||lp?e.pqState=0:e.num.isProbablePrime(S(e.num.bitLength()))?++e.pqState:e.num.dAddOffset(u[i++%8],0):2===e.pqState?e.pqState=0===e.num.subtract(a.ONE).gcd(e.e).compareTo(a.ONE)?3:0:3===e.pqState&&(e.pqState=0,null===e.p?e.p=e.num:e.q=e.num,null!==e.p&&null!==e.q&&++e.state,e.num=null)}else if(1===e.state)e.p.compareTo(e.q)<0&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(2===e.state)e.p1=e.p.subtract(a.ONE),e.q1=e.q.subtract(a.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(3===e.state)0===e.phi.gcd(e.e).compareTo(a.ONE)?++e.state:(e.p=null,e.q=null,e.state=0);else if(4===e.state)e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits?++e.state:(e.q=null,e.state=0);else if(5===e.state){var h=e.e.modInverse(e.phi);e.keys={privateKey:c.rsa.setPrivateKey(e.n,e.e,h,e.p,e.q,h.mod(e.p1),h.mod(e.q1),e.q.modInverse(e.p)),publicKey:c.rsa.setPublicKey(e.n,e.e)}}l+=(n=+new Date)-o,o=n}return null!==e.keys},c.rsa.generateKeyPair=function(e,t,r,a){if(1===arguments.length?"object"==typeof e?(r=e,e=void 0):"function"==typeof e&&(a=e,e=void 0):2===arguments.length?"number"==typeof e?"function"==typeof t?(a=t,t=void 0):"number"!=typeof t&&(r=t,t=void 0):(r=e,a=t,e=void 0,t=void 0):3===arguments.length&&("number"==typeof t?"function"==typeof r&&(a=r,r=void 0):(a=r,r=t,t=void 0)),r=r||{},void 0===e&&(e=r.bits||2048),void 0===t&&(t=r.e||65537),!n.options.usePureJavaScript&&!r.prng&&e>=256&&e<=16384&&(65537===t||3===t))if(a){if(T("generateKeyPair"))return i.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},(function(e,t,r){if(e)return a(e);a(null,{privateKey:c.privateKeyFromPem(r),publicKey:c.publicKeyFromPem(t)})}));if(I("generateKey")&&I("exportKey"))return o.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:A(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then((function(e){return o.globalScope.crypto.subtle.exportKey("pkcs8",e.privateKey)})).then(void 0,(function(e){a(e)})).then((function(e){if(e){var t=c.privateKeyFromAsn1(s.fromDer(n.util.createBuffer(e)));a(null,{privateKey:t,publicKey:c.setRsaPublicKey(t.n,t.e)})}}));if(b("generateKey")&&b("exportKey")){var u=o.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:A(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);return u.oncomplete=function(e){var t=e.target.result,r=o.globalScope.msCrypto.subtle.exportKey("pkcs8",t.privateKey);r.oncomplete=function(e){var t=e.target.result,r=c.privateKeyFromAsn1(s.fromDer(n.util.createBuffer(t)));a(null,{privateKey:r,publicKey:c.setRsaPublicKey(r.n,r.e)})},r.onerror=function(e){a(e)}},void(u.onerror=function(e){a(e)})}}else if(T("generateKeyPairSync")){var l=i.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:c.privateKeyFromPem(l.privateKey),publicKey:c.publicKeyFromPem(l.publicKey)}}var p=c.rsa.createKeyPairGenerationState(e,t,r);if(!a)return c.rsa.stepKeyPairGenerationState(p,0),p.keys;C(p,r,a)},c.setRsaPublicKey=c.rsa.setPublicKey=function(e,t){var r={n:e,e:t,encrypt:function(e,t,a){if("string"==typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5"),"RSAES-PKCS1-V1_5"===t)t={encode:function(e,t,r){return v(e,t,2).getBytes()}};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={encode:function(e,t){return n.pkcs1.encode_rsa_oaep(t,e,a)}};else if(-1!==["RAW","NONE","NULL",null].indexOf(t))t={encode:function(e){return e}};else if("string"==typeof t)throw new Error('Unsupported encryption scheme: "'+t+'".');var i=t.encode(e,r,!0);return c.rsa.encrypt(i,r,!0)},verify:function(e,t,a,i){"string"==typeof a?a=a.toUpperCase():void 0===a&&(a="RSASSA-PKCS1-V1_5"),void 0===i&&(i={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in i||(i._parseAllDigestBytes=!0),"RSASSA-PKCS1-V1_5"===a?a={verify:function(e,t){t=m(t,r,!0);var a=s.fromDer(t,{parseAllBytes:i._parseAllDigestBytes}),o={},c=[];if(!s.validate(a,d,o,c))throw(u=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.")).errors=c,u;var u,l=s.derToOid(o.algorithmIdentifier);if(l!==n.oids.md2&&l!==n.oids.md5&&l!==n.oids.sha1&&l!==n.oids.sha224&&l!==n.oids.sha256&&l!==n.oids.sha384&&l!==n.oids.sha512&&l!==n.oids["sha512-224"]&&l!==n.oids["sha512-256"])throw(u=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.")).oid=l,u;if((l===n.oids.md2||l===n.oids.md5)&&!("parameters"in o))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifier NULL parameters.");return e===o.digest}}:"NONE"!==a&&"NULL"!==a&&null!==a||(a={verify:function(e,t){return e===(t=m(t,r,!0))}});var o=c.rsa.decrypt(t,r,!0,!1);return a.verify(e,o,r.n.bitLength())}};return r},c.setRsaPrivateKey=c.rsa.setPrivateKey=function(e,t,r,a,i,s,o,u){var l={n:e,e:t,d:r,p:a,q:i,dP:s,dQ:o,qInv:u,decrypt:function(e,t,r){"string"==typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5");var a=c.rsa.decrypt(e,l,!1,!1);if("RSAES-PKCS1-V1_5"===t)t={decode:m};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={decode:function(e,t){return n.pkcs1.decode_rsa_oaep(t,e,r)}};else{if(-1===["RAW","NONE","NULL",null].indexOf(t))throw new Error('Unsupported encryption scheme: "'+t+'".');t={decode:function(e){return e}}}return t.decode(a,l,!1)},sign:function(e,t){var r=!1;"string"==typeof t&&(t=t.toUpperCase()),void 0===t||"RSASSA-PKCS1-V1_5"===t?(t={encode:y},r=1):"NONE"!==t&&"NULL"!==t&&null!==t||(t={encode:function(){return e}},r=1);var n=t.encode(e,l.n.bitLength());return c.rsa.encrypt(n,l,r)}};return l},c.wrapRsaPrivateKey=function(e){return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,s.integerToDer(0).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(c.oids.rsaEncryption).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.NULL,!1,"")]),s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,s.toDer(e).getBytes())])},c.privateKeyFromAsn1=function(e){var t,r,i,o,u,f,h,d,y={},g=[];if(s.validate(e,l,y,g)&&(e=s.fromDer(n.util.createBuffer(y.privateKey))),y={},g=[],!s.validate(e,p,y,g)){var v=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw v.errors=g,v}return t=n.util.createBuffer(y.privateKeyModulus).toHex(),r=n.util.createBuffer(y.privateKeyPublicExponent).toHex(),i=n.util.createBuffer(y.privateKeyPrivateExponent).toHex(),o=n.util.createBuffer(y.privateKeyPrime1).toHex(),u=n.util.createBuffer(y.privateKeyPrime2).toHex(),f=n.util.createBuffer(y.privateKeyExponent1).toHex(),h=n.util.createBuffer(y.privateKeyExponent2).toHex(),d=n.util.createBuffer(y.privateKeyCoefficient).toHex(),c.setRsaPrivateKey(new a(t,16),new a(r,16),new a(i,16),new a(o,16),new a(u,16),new a(f,16),new a(h,16),new a(d,16))},c.privateKeyToAsn1=c.privateKeyToRSAPrivateKey=function(e){return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,s.integerToDer(0).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,E(e.n)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,E(e.e)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,E(e.d)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,E(e.p)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,E(e.q)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,E(e.dP)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,E(e.dQ)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,E(e.qInv))])},c.publicKeyFromAsn1=function(e){var t={},r=[];if(s.validate(e,h,t,r)){var i,o=s.derToOid(t.publicKeyOid);if(o!==c.oids.rsaEncryption)throw(i=new Error("Cannot read public key. Unknown OID.")).oid=o,i;e=t.rsaPublicKey}if(r=[],!s.validate(e,f,t,r))throw(i=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.")).errors=r,i;var u=n.util.createBuffer(t.publicKeyModulus).toHex(),l=n.util.createBuffer(t.publicKeyExponent).toHex();return c.setRsaPublicKey(new a(u,16),new a(l,16))},c.publicKeyToAsn1=c.publicKeyToSubjectPublicKeyInfo=function(e){return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(c.oids.rsaEncryption).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.NULL,!1,"")]),s.create(s.Class.UNIVERSAL,s.Type.BITSTRING,!1,[c.publicKeyToRSAPublicKey(e)])])},c.publicKeyToRSAPublicKey=function(e){return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,E(e.n)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,E(e.e))])}},function(e,t,r){var n,a=r(0);e.exports=a.jsbn=a.jsbn||{};function i(e,t,r){this.data=[],null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function s(){return new i(null)}function o(e,t,r,n,a,i){for(var s=16383&t,o=t>>14;--i>=0;){var c=16383&this.data[e],u=this.data[e++]>>14,l=o*c+u*s;a=((c=s*c+((16383&l)<<14)+r.data[n]+a)>>28)+(l>>14)+o*u,r.data[n++]=268435455&c}return a}a.jsbn.BigInteger=i,"undefined"==typeof navigator?(i.prototype.am=o,n=28):"Microsoft Internet Explorer"==navigator.appName?(i.prototype.am=function(e,t,r,n,a,i){for(var s=32767&t,o=t>>15;--i>=0;){var c=32767&this.data[e],u=this.data[e++]>>15,l=o*c+u*s;a=((c=s*c+((32767&l)<<15)+r.data[n]+(1073741823&a))>>>30)+(l>>>15)+o*u+(a>>>30),r.data[n++]=1073741823&c}return a},n=30):"Netscape"!=navigator.appName?(i.prototype.am=function(e,t,r,n,a,i){for(;--i>=0;){var s=t*this.data[e++]+r.data[n]+a;a=Math.floor(s/67108864),r.data[n++]=67108863&s}return a},n=26):(i.prototype.am=o,n=28),i.prototype.DB=n,i.prototype.DM=(1<>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function y(e){this.m=e}function g(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<>=16,t+=16),0==(255&e)&&(e>>=8,t+=8),0==(15&e)&&(e>>=4,t+=4),0==(3&e)&&(e>>=2,t+=2),0==(1&e)&&++t,t}function T(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function I(){}function b(e){return e}function A(e){this.r2=s(),this.q3=s(),i.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}y.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},y.prototype.revert=function(e){return e},y.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},y.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},y.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},g.prototype.convert=function(e){var t=s();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(i.ZERO)>0&&this.m.subTo(t,t),t},g.prototype.revert=function(e){var t=s();return e.copyTo(t),this.reduce(t),t},g.prototype.reduce=function(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(r=t+this.m.t,e.data[r]+=this.m.am(0,n,e,t,0,this.m.t);e.data[r]>=e.DV;)e.data[r]-=e.DV,e.data[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},g.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},g.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},i.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s},i.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+this.DV:this.t=0},i.prototype.fromString=function(e,t){var r;if(16==t)r=4;else if(8==t)r=3;else if(256==t)r=8;else if(2==t)r=1;else if(32==t)r=5;else{if(4!=t)return void this.fromRadix(e,t);r=2}this.t=0,this.s=0;for(var n=e.length,a=!1,s=0;--n>=0;){var o=8==r?255&e[n]:f(e,n);o<0?"-"==e.charAt(n)&&(a=!0):(a=!1,0==s?this.data[this.t++]=o:s+r>this.DB?(this.data[this.t-1]|=(o&(1<>this.DB-s):this.data[this.t-1]|=o<=this.DB&&(s-=this.DB))}8==r&&0!=(128&e[0])&&(this.s=-1,s>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==e;)--this.t},i.prototype.dlShiftTo=function(e,t){var r;for(r=this.t-1;r>=0;--r)t.data[r+e]=this.data[r];for(r=e-1;r>=0;--r)t.data[r]=0;t.t=this.t+e,t.s=this.s},i.prototype.drShiftTo=function(e,t){for(var r=e;r=0;--r)t.data[r+s+1]=this.data[r]>>a|o,o=(this.data[r]&i)<=0;--r)t.data[r]=0;t.data[s]=o,t.t=this.t+s+1,t.s=this.s,t.clamp()},i.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var n=e%this.DB,a=this.DB-n,i=(1<>n;for(var s=r+1;s>n;n>0&&(t.data[this.t-r-1]|=(this.s&i)<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t.data[r++]=this.DV+n:n>0&&(t.data[r++]=n),t.t=r,t.clamp()},i.prototype.multiplyTo=function(e,t){var r=this.abs(),n=e.abs(),a=r.t;for(t.t=a+n.t;--a>=0;)t.data[a]=0;for(a=0;a=0;)e.data[r]=0;for(r=0;r=t.DV&&(e.data[r+t.t]-=t.DV,e.data[r+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(r,t.data[r],e,2*r,0,1)),e.s=0,e.clamp()},i.prototype.divRemTo=function(e,t,r){var n=e.abs();if(!(n.t<=0)){var a=this.abs();if(a.t0?(n.lShiftTo(l,o),a.lShiftTo(l,r)):(n.copyTo(o),a.copyTo(r));var p=o.t,f=o.data[p-1];if(0!=f){var h=f*(1<1?o.data[p-2]>>this.F2:0),y=this.FV/h,g=(1<=0&&(r.data[r.t++]=1,r.subTo(E,r)),i.ONE.dlShiftTo(p,E),E.subTo(o,o);o.t=0;){var S=r.data[--m]==f?this.DM:Math.floor(r.data[m]*y+(r.data[m-1]+v)*g);if((r.data[m]+=o.am(0,S,r,C,0,p))0&&r.rShiftTo(l,r),c<0&&i.ZERO.subTo(r,r)}}},i.prototype.invDigit=function(){if(this.t<1)return 0;var e=this.data[0];if(0==(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},i.prototype.isEven=function(){return 0==(this.t>0?1&this.data[0]:this.s)},i.prototype.exp=function(e,t){if(e>4294967295||e<1)return i.ONE;var r=s(),n=s(),a=t.convert(this),o=d(e)-1;for(a.copyTo(r);--o>=0;)if(t.sqrTo(r,n),(e&1<0)t.mulTo(n,a,r);else{var c=r;r=n,n=c}return t.revert(r)},i.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,n=(1<0)for(o>o)>0&&(a=!0,i=p(r));s>=0;)o>(o+=this.DB-t)):(r=this.data[s]>>(o-=t)&n,o<=0&&(o+=this.DB,--s)),r>0&&(a=!0),a&&(i+=p(r));return a?i:"0"},i.prototype.negate=function(){var e=s();return i.ZERO.subTo(this,e),e},i.prototype.abs=function(){return this.s<0?this.negate():this},i.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this.data[r]-e.data[r]))return t;return 0},i.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+d(this.data[this.t-1]^this.s&this.DM)},i.prototype.mod=function(e){var t=s();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(i.ZERO)>0&&e.subTo(t,t),t},i.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new y(t):new g(t),this.exp(e,r)},i.ZERO=h(0),i.ONE=h(1),I.prototype.convert=b,I.prototype.revert=b,I.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},I.prototype.sqrTo=function(e,t){e.squareTo(t)},A.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=s();return e.copyTo(t),this.reduce(t),t},A.prototype.revert=function(e){return e},A.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},A.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},A.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var B=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],N=(1<<26)/B[B.length-1];i.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},i.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),n=h(r),a=s(),i=s(),o="";for(this.divRemTo(n,a,i);a.signum()>0;)o=(r+i.intValue()).toString(e).substr(1)+o,a.divRemTo(n,a,i);return i.intValue().toString(e)+o},i.prototype.fromRadix=function(e,t){this.fromInt(0),null==t&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),a=!1,s=0,o=0,c=0;c=r&&(this.dMultiply(n),this.dAddOffset(o,0),s=0,o=0))}s>0&&(this.dMultiply(Math.pow(t,s)),this.dAddOffset(o,0)),a&&i.ZERO.subTo(this,this)},i.prototype.fromNumber=function(e,t,r){if("number"==typeof t)if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(i.ONE.shiftLeft(e-1),m,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(i.ONE.shiftLeft(e-1),this);else{var n=new Array,a=7&e;n.length=1+(e>>3),t.nextBytes(n),a>0?n[0]&=(1<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t.data[r++]=n:n<-1&&(t.data[r++]=this.DV+n),t.t=r,t.clamp()},i.prototype.dMultiply=function(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},i.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this.data[this.t++]=0;for(this.data[t]+=e;this.data[t]>=this.DV;)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}},i.prototype.multiplyLowerTo=function(e,t,r){var n,a=Math.min(this.t+e.t,t);for(r.s=0,r.t=a;a>0;)r.data[--a]=0;for(n=r.t-this.t;a=0;)r.data[n]=0;for(n=Math.max(t-this.t,0);n0)if(0==t)r=this.data[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this.data[n])%e;return r},i.prototype.millerRabin=function(e){var t=this.subtract(i.ONE),r=t.getLowestSetBit();if(r<=0)return!1;for(var n,a=t.shiftRight(r),s={nextBytes:function(e){for(var t=0;t=0);var c=n.modPow(a,this);if(0!=c.compareTo(i.ONE)&&0!=c.compareTo(t)){for(var u=1;u++>24},i.prototype.shortValue=function(){return 0==this.t?this.s:this.data[0]<<16>>16},i.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this.data[0]<=0?0:1},i.prototype.toByteArray=function(){var e=this.t,t=new Array;t[0]=this.s;var r,n=this.DB-e*this.DB%8,a=0;if(e-- >0)for(n>n)!=(this.s&this.DM)>>n&&(t[a++]=r|this.s<=0;)n<8?(r=(this.data[e]&(1<>(n+=this.DB-8)):(r=this.data[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),0!=(128&r)&&(r|=-256),0==a&&(128&this.s)!=(128&r)&&++a,(a>0||r!=this.s)&&(t[a++]=r);return t},i.prototype.equals=function(e){return 0==this.compareTo(e)},i.prototype.min=function(e){return this.compareTo(e)<0?this:e},i.prototype.max=function(e){return this.compareTo(e)>0?this:e},i.prototype.and=function(e){var t=s();return this.bitwiseTo(e,v,t),t},i.prototype.or=function(e){var t=s();return this.bitwiseTo(e,m,t),t},i.prototype.xor=function(e){var t=s();return this.bitwiseTo(e,C,t),t},i.prototype.andNot=function(e){var t=s();return this.bitwiseTo(e,E,t),t},i.prototype.not=function(){for(var e=s(),t=0;t=this.t?0!=this.s:0!=(this.data[t]&1<1){var p=s();for(n.sqrTo(o[1],p);c<=l;)o[c]=s(),n.mulTo(p,o[c-2],o[c]),c+=2}var f,v,m=e.t-1,C=!0,E=s();for(a=d(e.data[m])-1;m>=0;){for(a>=u?f=e.data[m]>>a-u&l:(f=(e.data[m]&(1<0&&(f|=e.data[m-1]>>this.DB+a-u)),c=r;0==(1&f);)f>>=1,--c;if((a-=c)<0&&(a+=this.DB,--m),C)o[f].copyTo(i),C=!1;else{for(;c>1;)n.sqrTo(i,E),n.sqrTo(E,i),c-=2;c>0?n.sqrTo(i,E):(v=i,i=E,E=v),n.mulTo(E,o[f],i)}for(;m>=0&&0==(e.data[m]&1<=0?(r.subTo(n,r),t&&a.subTo(o,a),s.subTo(c,s)):(n.subTo(r,n),t&&o.subTo(a,o),c.subTo(s,c))}return 0!=n.compareTo(i.ONE)?i.ZERO:c.compareTo(e)>=0?c.subtract(e):c.signum()<0?(c.addTo(e,c),c.signum()<0?c.add(e):c):c},i.prototype.pow=function(e){return this.exp(e,new I)},i.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var n=t;t=r,r=n}var a=t.getLowestSetBit(),i=r.getLowestSetBit();if(i<0)return t;for(a0&&(t.rShiftTo(i,t),r.rShiftTo(i,r));t.signum()>0;)(a=t.getLowestSetBit())>0&&t.rShiftTo(a,t),(a=r.getLowestSetBit())>0&&r.rShiftTo(a,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return i>0&&r.lShiftTo(i,r),r},i.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r.data[0]<=B[B.length-1]){for(t=0;t>>0,o>>>0];for(var c=a.fullMessageLength.length-1;c>=0;--c)a.fullMessageLength[c]+=o[1],o[1]=o[0]+(a.fullMessageLength[c]/4294967296>>>0),a.fullMessageLength[c]=a.fullMessageLength[c]>>>0,o[0]=o[1]/4294967296>>>0;return t.putBytes(i),l(e,r,t),(t.read>2048||0===t.length())&&t.compact(),a},a.digest=function(){var s=n.util.createBuffer();s.putBytes(t.bytes());var o=a.fullMessageLength[a.fullMessageLength.length-1]+a.messageLengthSize&a.blockLength-1;s.putBytes(i.substr(0,a.blockLength-o));for(var c,u=0,p=a.fullMessageLength.length-1;p>=0;--p)u=(c=8*a.fullMessageLength[p]+u)/4294967296>>>0,s.putInt32Le(c>>>0);var f={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3};l(f,r,s);var h=n.util.createBuffer();return h.putInt32Le(f.h0),h.putInt32Le(f.h1),h.putInt32Le(f.h2),h.putInt32Le(f.h3),h},a};var i=null,s=null,o=null,c=null,u=!1;function l(e,t,r){for(var n,a,i,u,l,p,f,h=r.length();h>=64;){for(a=e.h0,i=e.h1,u=e.h2,l=e.h3,f=0;f<16;++f)t[f]=r.getInt32Le(),n=a+(l^i&(u^l))+c[f]+t[f],a=l,l=u,u=i,i+=n<<(p=o[f])|n>>>32-p;for(;f<32;++f)n=a+(u^l&(i^u))+c[f]+t[s[f]],a=l,l=u,u=i,i+=n<<(p=o[f])|n>>>32-p;for(;f<48;++f)n=a+(i^u^l)+c[f]+t[s[f]],a=l,l=u,u=i,i+=n<<(p=o[f])|n>>>32-p;for(;f<64;++f)n=a+(u^(i|~l))+c[f]+t[s[f]],a=l,l=u,u=i,i+=n<<(p=o[f])|n>>>32-p;e.h0=e.h0+a|0,e.h1=e.h1+i|0,e.h2=e.h2+u|0,e.h3=e.h3+l|0,h-=64}}},function(e,t,r){var n=r(0);r(8),r(4),r(1);var a,i=n.pkcs5=n.pkcs5||{};n.util.isNodejs&&!n.options.usePureJavaScript&&(a=r(17)),e.exports=n.pbkdf2=i.pbkdf2=function(e,t,r,i,s,o){if("function"==typeof s&&(o=s,s=null),n.util.isNodejs&&!n.options.usePureJavaScript&&a.pbkdf2&&(null===s||"object"!=typeof s)&&(a.pbkdf2Sync.length>4||!s||"sha1"===s))return"string"!=typeof s&&(s="sha1"),e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),o?4===a.pbkdf2Sync.length?a.pbkdf2(e,t,r,i,(function(e,t){if(e)return o(e);o(null,t.toString("binary"))})):a.pbkdf2(e,t,r,i,s,(function(e,t){if(e)return o(e);o(null,t.toString("binary"))})):4===a.pbkdf2Sync.length?a.pbkdf2Sync(e,t,r,i).toString("binary"):a.pbkdf2Sync(e,t,r,i,s).toString("binary");if(null==s&&(s="sha1"),"string"==typeof s){if(!(s in n.md.algorithms))throw new Error("Unknown hash algorithm: "+s);s=n.md[s].create()}var c=s.digestLength;if(i>4294967295*c){var u=new Error("Derived key is too long.");if(o)return o(u);throw u}var l=Math.ceil(i/c),p=i-(l-1)*c,f=n.hmac.create();f.start(s,e);var h,d,y,g="";if(!o){for(var v=1;v<=l;++v){f.start(null,null),f.update(t),f.update(n.util.int32ToBytes(v)),h=y=f.digest().getBytes();for(var m=2;m<=r;++m)f.start(null,null),f.update(y),d=f.digest().getBytes(),h=n.util.xorBytes(h,d,c),y=d;g+=vl)return o(null,g);f.start(null,null),f.update(t),f.update(n.util.int32ToBytes(v)),h=y=f.digest().getBytes(),m=2,E()}function E(){if(m<=r)return f.start(null,null),f.update(y),d=f.digest().getBytes(),h=n.util.xorBytes(h,d,c),y=d,++m,n.util.setImmediate(E);g+=v128)throw new Error('Invalid "nsComment" content.');e.value=a.create(a.Class.UNIVERSAL,a.Type.IA5STRING,!1,e.comment)}else if("subjectKeyIdentifier"===e.name&&t.cert){var h=t.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=h.toHex(),e.value=a.create(a.Class.UNIVERSAL,a.Type.OCTETSTRING,!1,h.getBytes())}else if("authorityKeyIdentifier"===e.name&&t.cert){e.value=a.create(a.Class.UNIVERSAL,a.Type.SEQUENCE,!0,[]);l=e.value.value;if(e.keyIdentifier){var d=!0===e.keyIdentifier?t.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;l.push(a.create(a.Class.CONTEXT_SPECIFIC,0,!1,d))}if(e.authorityCertIssuer){var y=[a.create(a.Class.CONTEXT_SPECIFIC,4,!0,[v(!0===e.authorityCertIssuer?t.cert.issuer:e.authorityCertIssuer)])];l.push(a.create(a.Class.CONTEXT_SPECIFIC,1,!0,y))}if(e.serialNumber){var g=n.util.hexToBytes(!0===e.serialNumber?t.cert.serialNumber:e.serialNumber);l.push(a.create(a.Class.CONTEXT_SPECIFIC,2,!1,g))}}else if("cRLDistributionPoints"===e.name){e.value=a.create(a.Class.UNIVERSAL,a.Type.SEQUENCE,!0,[]);l=e.value.value;var m,C=a.create(a.Class.UNIVERSAL,a.Type.SEQUENCE,!0,[]),E=a.create(a.Class.CONTEXT_SPECIFIC,0,!0,[]);for(f=0;f2)throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(p.length<2)throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(c.validity.notBefore=p[0],c.validity.notAfter=p[1],c.tbsCertificate=r.tbsCertificate,t){c.md=y({signatureOid:c.signatureOid,type:"certificate"});var f=a.toDer(c.tbsCertificate);c.md.update(f.getBytes())}var g=n.md.sha1.create(),v=a.toDer(r.certIssuer);g.update(v.getBytes()),c.issuer.getField=function(e){return h(c.issuer,e)},c.issuer.addField=function(e){m([e]),c.issuer.attributes.push(e)},c.issuer.attributes=i.RDNAttributesAsArray(r.certIssuer),r.certIssuerUniqueId&&(c.issuer.uniqueId=r.certIssuerUniqueId),c.issuer.hash=g.digest().toHex();var C=n.md.sha1.create(),E=a.toDer(r.certSubject);return C.update(E.getBytes()),c.subject.getField=function(e){return h(c.subject,e)},c.subject.addField=function(e){m([e]),c.subject.attributes.push(e)},c.subject.attributes=i.RDNAttributesAsArray(r.certSubject),r.certSubjectUniqueId&&(c.subject.uniqueId=r.certSubjectUniqueId),c.subject.hash=C.digest().toHex(),r.certExtensions?c.extensions=i.certificateExtensionsFromAsn1(r.certExtensions):c.extensions=[],c.publicKey=i.publicKeyFromAsn1(r.subjectPublicKeyInfo),c},i.certificateExtensionsFromAsn1=function(e){for(var t=[],r=0;r1&&(r=c.value.charCodeAt(1),i=c.value.length>2?c.value.charCodeAt(2):0),t.digitalSignature=128==(128&r),t.nonRepudiation=64==(64&r),t.keyEncipherment=32==(32&r),t.dataEncipherment=16==(16&r),t.keyAgreement=8==(8&r),t.keyCertSign=4==(4&r),t.cRLSign=2==(2&r),t.encipherOnly=1==(1&r),t.decipherOnly=128==(128&i)}else if("basicConstraints"===t.name){(c=a.fromDer(t.value)).value.length>0&&c.value[0].type===a.Type.BOOLEAN?t.cA=0!==c.value[0].value.charCodeAt(0):t.cA=!1;var o=null;c.value.length>0&&c.value[0].type===a.Type.INTEGER?o=c.value[0].value:c.value.length>1&&(o=c.value[1].value),null!==o&&(t.pathLenConstraint=a.derToInteger(o))}else if("extKeyUsage"===t.name)for(var c=a.fromDer(t.value),u=0;u1&&(r=c.value.charCodeAt(1)),t.client=128==(128&r),t.server=64==(64&r),t.email=32==(32&r),t.objsign=16==(16&r),t.reserved=8==(8&r),t.sslCA=4==(4&r),t.emailCA=2==(2&r),t.objCA=1==(1&r)}else if("subjectAltName"===t.name||"issuerAltName"===t.name){var p;t.altNames=[];c=a.fromDer(t.value);for(var f=0;f=T&&e0&&s.value.push(i.certificateExtensionsToAsn1(e.extensions)),s},i.getCertificationRequestInfo=function(e){return a.create(a.Class.UNIVERSAL,a.Type.SEQUENCE,!0,[a.create(a.Class.UNIVERSAL,a.Type.INTEGER,!1,a.integerToDer(e.version).getBytes()),v(e.subject),i.publicKeyToAsn1(e.publicKey),S(e)])},i.distinguishedNameToAsn1=function(e){return v(e)},i.certificateToAsn1=function(e){var t=e.tbsCertificate||i.getTBSCertificate(e);return a.create(a.Class.UNIVERSAL,a.Type.SEQUENCE,!0,[t,a.create(a.Class.UNIVERSAL,a.Type.SEQUENCE,!0,[a.create(a.Class.UNIVERSAL,a.Type.OID,!1,a.oidToDer(e.signatureOid).getBytes()),E(e.signatureOid,e.signatureParameters)]),a.create(a.Class.UNIVERSAL,a.Type.BITSTRING,!1,String.fromCharCode(0)+e.signature)])},i.certificateExtensionsToAsn1=function(e){var t=a.create(a.Class.CONTEXT_SPECIFIC,3,!0,[]),r=a.create(a.Class.UNIVERSAL,a.Type.SEQUENCE,!0,[]);t.value.push(r);for(var n=0;nl.validity.notAfter)&&(c={message:"Certificate is not valid yet or has expired.",error:i.certificateError.certificate_expired,notBefore:l.validity.notBefore,notAfter:l.validity.notAfter,now:s}),null===c){if(null===(p=t[0]||e.getIssuer(l))&&l.isIssuer(l)&&(f=!0,p=l),p){var h=p;n.util.isArray(h)||(h=[h]);for(var d=!1;!d&&h.length>0;){p=h.shift();try{d=p.verify(l)}catch(e){}}d||(c={message:"Certificate signature is invalid.",error:i.certificateError.bad_certificate})}null!==c||p&&!f||e.hasCertificate(l)||(c={message:"Certificate is not trusted.",error:i.certificateError.unknown_ca})}if(null===c&&p&&!l.isIssuer(p)&&(c={message:"Certificate issuer is invalid.",error:i.certificateError.bad_certificate}),null===c)for(var y={keyUsage:!0,basicConstraints:!0},g=0;null===c&&gm.pathLenConstraint&&(c={message:"Certificate basicConstraints pathLenConstraint violated.",error:i.certificateError.bad_certificate})}var E=null===c||c.error,S=r.verify?r.verify(E,u,a):E;if(!0!==S)throw!0===E&&(c={message:"The application rejected the certificate.",error:i.certificateError.bad_certificate}),(S||0===S)&&("object"!=typeof S||n.util.isArray(S)?"string"==typeof S&&(c.error=S):(S.message&&(c.message=S.message),S.error&&(c.error=S.error))),c;c=null,o=!1,++u}while(t.length>0);return!0}},function(e,t,r){var n=r(0);r(2),r(1),(e.exports=n.pss=n.pss||{}).create=function(e){3===arguments.length&&(e={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]});var t,r=e.md,a=e.mgf,i=r.digestLength,s=e.salt||null;if("string"==typeof s&&(s=n.util.createBuffer(s)),"saltLength"in e)t=e.saltLength;else{if(null===s)throw new Error("Salt length not specified or specific salt not given.");t=s.length()}if(null!==s&&s.length()!==t)throw new Error("Given salt length does not match length of given salt.");var o=e.prng||n.random,c={encode:function(e,c){var u,l,p=c-1,f=Math.ceil(p/8),h=e.digest().getBytes();if(f>8*f-p&255;return(E=String.fromCharCode(E.charCodeAt(0)&~S)+E.substr(1))+y+String.fromCharCode(188)},verify:function(e,s,o){var c,u=o-1,l=Math.ceil(u/8);if(s=s.substr(-l),l>8*l-u&255;if(0!=(f.charCodeAt(0)&d))throw new Error("Bits beyond keysize not zero as expected.");var y=a.generate(h,p),g="";for(c=0;c4){var r=e;e=n.util.createBuffer();for(var a=0;a0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2)&&(e.truncate(n),!0)},a.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},a.cbc.prototype.start=function(e){if(null===e.iv){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else{if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=i(e.iv,this.blockSize),this._prev=this._iv.slice(0)}},a.cbc.prototype.encrypt=function(e,t,r){if(e.length()0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2)&&(e.truncate(n),!0)},a.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},a.cfb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=i(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},a.cfb.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var a=0;a0&&(i=this.blockSize-i),this._partialOutput.clear();for(a=0;a0)e.read-=this.blockSize;else for(a=0;a0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},a.cfb.prototype.decrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var a=0;a0&&(i=this.blockSize-i),this._partialOutput.clear();for(a=0;a0)e.read-=this.blockSize;else for(a=0;a0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},a.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},a.ofb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=i(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},a.ofb.prototype.encrypt=function(e,t,r){var n=e.length();if(0===e.length())return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var a=0;a0&&(i=this.blockSize-i),this._partialOutput.clear();for(a=0;a0)e.read-=this.blockSize;else for(a=0;a0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},a.ofb.prototype.decrypt=a.ofb.prototype.encrypt,a.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},a.ctr.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=i(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},a.ctr.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var a=0;a0&&(i=this.blockSize-i),this._partialOutput.clear();for(a=0;a0&&(e.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}s(this._inBlock)},a.ctr.prototype.decrypt=a.ctr.prototype.encrypt,a.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0,this._R=3774873600},a.gcm.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");var t,r=n.util.createBuffer(e.iv);if(this._cipherLength=0,t="additionalData"in e?n.util.createBuffer(e.additionalData):n.util.createBuffer(),this._tagLength="tagLength"in e?e.tagLength:128,this._tag=null,e.decrypt&&(this._tag=n.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var a=r.length();if(12===a)this._j0=[r.getInt32(),r.getInt32(),r.getInt32(),1];else{for(this._j0=[0,0,0,0];r.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[r.getInt32(),r.getInt32(),r.getInt32(),r.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(o(8*a)))}this._inBlock=this._j0.slice(0),s(this._inBlock),this._partialBytes=0,t=n.util.createBuffer(t),this._aDataLength=o(8*t.length());var i=t.length()%this.blockSize;for(i&&t.fillWithByte(0,this.blockSize-i),this._s=[0,0,0,0];t.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()])},a.gcm.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize){for(var a=0;a0&&(i=this.blockSize-i),this._partialOutput.clear();for(a=0;a0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),s(this._inBlock)},a.gcm.prototype.decrypt=function(e,t,r){var n=e.length();if(n0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),s(this._inBlock),this._hashBlock[0]=e.getInt32(),this._hashBlock[1]=e.getInt32(),this._hashBlock[2]=e.getInt32(),this._hashBlock[3]=e.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var a=0;a0;--n)t[n]=e[n]>>>1|(1&e[n-1])<<31;t[0]=e[0]>>>1,r&&(t[0]^=this._R)},a.gcm.prototype.tableMultiply=function(e){for(var t=[0,0,0,0],r=0;r<32;++r){var n=e[r/8|0]>>>4*(7-r%8)&15,a=this._m[r][n];t[0]^=a[0],t[1]^=a[1],t[2]^=a[2],t[3]^=a[3]}return t},a.gcm.prototype.ghash=function(e,t,r){return t[0]^=r[0],t[1]^=r[1],t[2]^=r[2],t[3]^=r[3],this.tableMultiply(t)},a.gcm.prototype.generateHashTable=function(e,t){for(var r=8/t,n=4*r,a=16*r,i=new Array(a),s=0;s>>1,a=new Array(r);a[n]=e.slice(0);for(var i=n>>>1;i>0;)this.pow(a[2*i],a[i]=[]),i>>=1;for(i=2;i=0;c--)w>>=8,w+=A.at(c)+k.at(c),k.setAt(c,255&w);N.putBuffer(k)}E=N,p.putBuffer(I)}return p.truncate(p.length()-i),p},s.pbe.getCipher=function(e,t,r){switch(e){case s.oids.pkcs5PBES2:return s.pbe.getCipherForPBES2(e,t,r);case s.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case s.oids["pbewithSHAAnd40BitRC2-CBC"]:return s.pbe.getCipherForPKCS12PBE(e,t,r);default:var n=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw n.oid=e,n.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],n}},s.pbe.getCipherForPBES2=function(e,t,r){var a,o={},c=[];if(!i.validate(t,u,o,c))throw(a=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=c,a;if((e=i.derToOid(o.kdfOid))!==s.oids.pkcs5PBKDF2)throw(a=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.")).oid=e,a.supportedOids=["pkcs5PBKDF2"],a;if((e=i.derToOid(o.encOid))!==s.oids["aes128-CBC"]&&e!==s.oids["aes192-CBC"]&&e!==s.oids["aes256-CBC"]&&e!==s.oids["des-EDE3-CBC"]&&e!==s.oids.desCBC)throw(a=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.")).oid=e,a.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],a;var l,p,h=o.kdfSalt,d=n.util.createBuffer(o.kdfIterationCount);switch(d=d.getInt(d.length()<<3),s.oids[e]){case"aes128-CBC":l=16,p=n.aes.createDecryptionCipher;break;case"aes192-CBC":l=24,p=n.aes.createDecryptionCipher;break;case"aes256-CBC":l=32,p=n.aes.createDecryptionCipher;break;case"des-EDE3-CBC":l=24,p=n.des.createDecryptionCipher;break;case"desCBC":l=8,p=n.des.createDecryptionCipher}var y=f(o.prfOid),g=n.pkcs5.pbkdf2(r,h,d,l,y),v=o.encIv,m=p(g);return m.start(v),m},s.pbe.getCipherForPKCS12PBE=function(e,t,r){var a={},o=[];if(!i.validate(t,l,a,o))throw(y=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=o,y;var c,u,p,h=n.util.createBuffer(a.salt),d=n.util.createBuffer(a.iterations);switch(d=d.getInt(d.length()<<3),e){case s.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,u=8,p=n.des.startDecrypting;break;case s.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,u=8,p=function(e,t){var r=n.rc2.createDecryptionCipher(e,40);return r.start(t,null),r};break;default:var y;throw(y=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.")).oid=e,y}var g=f(a.prfOid),v=s.pbe.generatePkcs12Key(r,h,1,d,c,g);return g.start(),p(v,s.pbe.generatePkcs12Key(r,h,2,d,u,g))},s.pbe.opensslDeriveBytes=function(e,t,r,a){if(null==a){if(!("md5"in n.md))throw new Error('"md5" hash algorithm unavailable.');a=n.md.md5.create()}null===t&&(t="");for(var i=[p(a,e+t)],s=16,o=1;s>>0,o>>>0];for(var u=a.fullMessageLength.length-1;u>=0;--u)a.fullMessageLength[u]+=o[1],o[1]=o[0]+(a.fullMessageLength[u]/4294967296>>>0),a.fullMessageLength[u]=a.fullMessageLength[u]>>>0,o[0]=o[1]/4294967296>>>0;return t.putBytes(i),c(e,r,t),(t.read>2048||0===t.length())&&t.compact(),a},a.digest=function(){var s=n.util.createBuffer();s.putBytes(t.bytes());var o,u=a.fullMessageLength[a.fullMessageLength.length-1]+a.messageLengthSize&a.blockLength-1;s.putBytes(i.substr(0,a.blockLength-u));for(var l=8*a.fullMessageLength[0],p=0;p>>0,s.putInt32(l>>>0),l=o>>>0;s.putInt32(l);var f={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};c(f,r,s);var h=n.util.createBuffer();return h.putInt32(f.h0),h.putInt32(f.h1),h.putInt32(f.h2),h.putInt32(f.h3),h.putInt32(f.h4),h.putInt32(f.h5),h.putInt32(f.h6),h.putInt32(f.h7),h},a};var i=null,s=!1,o=null;function c(e,t,r){for(var n,a,i,s,c,u,l,p,f,h,d,y,g,v=r.length();v>=64;){for(c=0;c<16;++c)t[c]=r.getInt32();for(;c<64;++c)n=((n=t[c-2])>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,a=((a=t[c-15])>>>7|a<<25)^(a>>>18|a<<14)^a>>>3,t[c]=n+t[c-7]+a+t[c-16]|0;for(u=e.h0,l=e.h1,p=e.h2,f=e.h3,h=e.h4,d=e.h5,y=e.h6,g=e.h7,c=0;c<64;++c)i=(u>>>2|u<<30)^(u>>>13|u<<19)^(u>>>22|u<<10),s=u&l|p&(u^l),n=g+((h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7))+(y^h&(d^y))+o[c]+t[c],g=y,y=d,d=h,h=f+n>>>0,f=p,p=l,l=u,u=n+(a=i+s)>>>0;e.h0=e.h0+u|0,e.h1=e.h1+l|0,e.h2=e.h2+p|0,e.h3=e.h3+f|0,e.h4=e.h4+h|0,e.h5=e.h5+d|0,e.h6=e.h6+y|0,e.h7=e.h7+g|0,v-=64}}},function(e,t,r){var n=r(0);r(1);var a=null;!n.util.isNodejs||n.options.usePureJavaScript||process.versions["node-webkit"]||(a=r(17)),(e.exports=n.prng=n.prng||{}).create=function(e){for(var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},r=e.md,i=new Array(32),s=0;s<32;++s)i[s]=r.create();function o(){if(t.pools[0].messageLength>=32)return c();var e=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(e)),c()}function c(){t.reseeds=4294967295===t.reseeds?0:t.reseeds+1;var e=t.plugin.md.create();e.update(t.keyBytes);for(var r=1,n=0;n<32;++n)t.reseeds%r==0&&(e.update(t.pools[n].digest().getBytes()),t.pools[n].start()),r<<=1;t.keyBytes=e.digest().getBytes(),e.start(),e.update(t.keyBytes);var a=e.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(a),t.generated=0}function u(e){var t=null,r=n.util.globalScope,a=r.crypto||r.msCrypto;a&&a.getRandomValues&&(t=function(e){return a.getRandomValues(e)});var i=n.util.createBuffer();if(t)for(;i.length()>16)))<<16,f=4294967295&(l=(2147483647&(l+=u>>15))+(l>>31));for(c=0;c<3;++c)p=f>>>(c<<3),p^=Math.floor(256*Math.random()),i.putByte(255&p)}return i.getBytes(e)}return t.pools=i,t.pool=0,t.generate=function(e,r){if(!r)return t.generateSync(e);var a=t.plugin.cipher,i=t.plugin.increment,s=t.plugin.formatKey,o=t.plugin.formatSeed,u=n.util.createBuffer();t.key=null,function l(p){if(p)return r(p);if(u.length()>=e)return r(null,u.getBytes(e));t.generated>1048575&&(t.key=null);if(null===t.key)return n.util.nextTick((function(){!function(e){if(t.pools[0].messageLength>=32)return c(),e();var r=32-t.pools[0].messageLength<<5;t.seedFile(r,(function(r,n){if(r)return e(r);t.collect(n),c(),e()}))}(l)}));var f=a(t.key,t.seed);t.generated+=f.length,u.putBytes(f),t.key=s(a(t.key,i(t.seed))),t.seed=o(a(t.key,t.seed)),n.util.setImmediate(l)}()},t.generateSync=function(e){var r=t.plugin.cipher,a=t.plugin.increment,i=t.plugin.formatKey,s=t.plugin.formatSeed;t.key=null;for(var c=n.util.createBuffer();c.length()1048575&&(t.key=null),null===t.key&&o();var u=r(t.key,t.seed);t.generated+=u.length,c.putBytes(u),t.key=i(r(t.key,a(t.seed))),t.seed=s(r(t.key,t.seed))}return c.getBytes(e)},a?(t.seedFile=function(e,t){a.randomBytes(e,(function(e,r){if(e)return t(e);t(null,r.toString())}))},t.seedFileSync=function(e){return a.randomBytes(e).toString()}):(t.seedFile=function(e,t){try{t(null,u(e))}catch(e){t(e)}},t.seedFileSync=u),t.collect=function(e){for(var r=e.length,n=0;n>a&255);t.collect(n)},t.registerWorker=function(e){if(e===self)t.seedFile=function(e,t){self.addEventListener("message",(function e(r){var n=r.data;n.forge&&n.forge.prng&&(self.removeEventListener("message",e),t(n.forge.prng.err,n.forge.prng.bytes))})),self.postMessage({forge:{prng:{needed:e}}})};else{e.addEventListener("message",(function(r){var n=r.data;n.forge&&n.forge.prng&&t.seedFile(n.forge.prng.needed,(function(t,r){e.postMessage({forge:{prng:{err:t,bytes:r}}})}))}))}},t}},function(e,t,r){var n=r(0);r(1);var a=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],i=[1,2,3,5],s=function(e,t){return e<>16-t},o=function(e,t){return(65535&e)>>t|e<<16-t&65535};e.exports=n.rc2=n.rc2||{},n.rc2.expandKey=function(e,t){"string"==typeof e&&(e=n.util.createBuffer(e)),t=t||128;var r,i=e,s=e.length(),o=t,c=Math.ceil(o/8),u=255>>(7&o);for(r=s;r<128;r++)i.putByte(a[i.at(r-1)+i.at(r-s)&255]);for(i.setAt(128-c,a[i.at(128-c)&u]),r=127-c;r>=0;r--)i.setAt(r,a[i.at(r+1)^i.at(r+c)]);return i};var c=function(e,t,r){var a,c,u,l,p=!1,f=null,h=null,d=null,y=[];for(e=n.rc2.expandKey(e,t),u=0;u<64;u++)y.push(e.getInt16Le());r?(a=function(e){for(u=0;u<4;u++)e[u]+=y[l]+(e[(u+3)%4]&e[(u+2)%4])+(~e[(u+3)%4]&e[(u+1)%4]),e[u]=s(e[u],i[u]),l++},c=function(e){for(u=0;u<4;u++)e[u]+=y[63&e[(u+3)%4]]}):(a=function(e){for(u=3;u>=0;u--)e[u]=o(e[u],i[u]),e[u]-=y[l]+(e[(u+3)%4]&e[(u+2)%4])+(~e[(u+3)%4]&e[(u+1)%4]),l--},c=function(e){for(u=3;u>=0;u--)e[u]-=y[63&e[(u+3)%4]]});var g=function(e){var t=[];for(u=0;u<4;u++){var n=f.getInt16Le();null!==d&&(r?n^=d.getInt16Le():d.putInt16Le(n)),t.push(65535&n)}l=r?0:63;for(var a=0;a=8;)g([[5,a],[1,c],[6,a],[1,c],[5,a]])},finish:function(e){var t=!0;if(r)if(e)t=e(8,f,!r);else{var n=8===f.length()?8:8-f.length();f.fillWithByte(n,n)}if(t&&(p=!0,v.update()),!r&&(t=0===f.length()))if(e)t=e(8,h,!r);else{var a=h.length(),i=h.at(a-1);i>a?t=!1:h.truncate(i)}return t}}};n.rc2.startEncrypting=function(e,t,r){var a=n.rc2.createEncryptionCipher(e,128);return a.start(t,r),a},n.rc2.createEncryptionCipher=function(e,t){return c(e,t,!0)},n.rc2.startDecrypting=function(e,t,r){var a=n.rc2.createDecryptionCipher(e,128);return a.start(t,r),a},n.rc2.createDecryptionCipher=function(e,t){return c(e,t,!1)}},function(e,t,r){var n=r(0);r(1),r(2),r(9);var a=e.exports=n.pkcs1=n.pkcs1||{};function i(e,t,r){r||(r=n.md.sha1.create());for(var a="",i=Math.ceil(t/r.digestLength),s=0;s>24&255,s>>16&255,s>>8&255,255&s);r.start(),r.update(e+o),a+=r.digest().getBytes()}return a.substring(0,t)}a.encode_rsa_oaep=function(e,t,r){var a,s,o,c;"string"==typeof r?(a=r,s=arguments[3]||void 0,o=arguments[4]||void 0):r&&(a=r.label||void 0,s=r.seed||void 0,o=r.md||void 0,r.mgf1&&r.mgf1.md&&(c=r.mgf1.md)),o?o.start():o=n.md.sha1.create(),c||(c=o);var u=Math.ceil(e.n.bitLength()/8),l=u-2*o.digestLength-2;if(t.length>l)throw(g=new Error("RSAES-OAEP input message length is too long.")).length=t.length,g.maxLength=l,g;a||(a=""),o.update(a,"raw");for(var p=o.digest(),f="",h=l-t.length,d=0;de&&(s=c(e,t));var h=s.toString(16);a.target.postMessage({hex:h,workLoad:l}),s.dAddOffset(p,0)}}}h()}(e,t,a,i);return o(e,t,a,i)}(e,u,i.options,a);throw new Error("Invalid prime generation algorithm: "+i.name)}}function o(e,t,r,i){var s=c(e,t),o=function(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}(s.bitLength());"millerRabinTests"in r&&(o=r.millerRabinTests);var u=10;"maxBlockTime"in r&&(u=r.maxBlockTime),function e(t,r,i,s,o,u,l){var p=+new Date;do{if(t.bitLength()>r&&(t=c(r,i)),t.isProbablePrime(o))return l(null,t);t.dAddOffset(a[s++%8],0)}while(u<0||+new Date-p=0&&a.push(o):a.push(o))}return a}function h(e){if(e.composed||e.constructed){for(var t=n.util.createBuffer(),r=0;r2)throw new Error("Invalid PKCS#12. macData field present but MAC was not validated.");return function(e,t,r,n){if((t=a.fromDer(t,r)).tagClass!==a.Class.UNIVERSAL||t.type!==a.Type.SEQUENCE||!0!==t.constructed)throw new Error("PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo");for(var s=0;s0&&(c=a.create(a.Class.UNIVERSAL,a.Type.SET,!0,p));var f=[],h=[];null!==t&&(h=n.util.isArray(t)?t:[t]);for(var d=[],y=0;y0){var C=a.create(a.Class.UNIVERSAL,a.Type.SEQUENCE,!0,d),E=a.create(a.Class.UNIVERSAL,a.Type.SEQUENCE,!0,[a.create(a.Class.UNIVERSAL,a.Type.OID,!1,a.oidToDer(i.oids.data).getBytes()),a.create(a.Class.CONTEXT_SPECIFIC,0,!0,[a.create(a.Class.UNIVERSAL,a.Type.OCTETSTRING,!1,a.toDer(C).getBytes())])]);f.push(E)}var S=null;if(null!==e){var T=i.wrapRsaPrivateKey(i.privateKeyToAsn1(e));S=null===r?a.create(a.Class.UNIVERSAL,a.Type.SEQUENCE,!0,[a.create(a.Class.UNIVERSAL,a.Type.OID,!1,a.oidToDer(i.oids.keyBag).getBytes()),a.create(a.Class.CONTEXT_SPECIFIC,0,!0,[T]),c]):a.create(a.Class.UNIVERSAL,a.Type.SEQUENCE,!0,[a.create(a.Class.UNIVERSAL,a.Type.OID,!1,a.oidToDer(i.oids.pkcs8ShroudedKeyBag).getBytes()),a.create(a.Class.CONTEXT_SPECIFIC,0,!0,[i.encryptPrivateKeyInfo(T,r,o)]),c]);var I=a.create(a.Class.UNIVERSAL,a.Type.SEQUENCE,!0,[S]),b=a.create(a.Class.UNIVERSAL,a.Type.SEQUENCE,!0,[a.create(a.Class.UNIVERSAL,a.Type.OID,!1,a.oidToDer(i.oids.data).getBytes()),a.create(a.Class.CONTEXT_SPECIFIC,0,!0,[a.create(a.Class.UNIVERSAL,a.Type.OCTETSTRING,!1,a.toDer(I).getBytes())])]);f.push(b)}var A,B=a.create(a.Class.UNIVERSAL,a.Type.SEQUENCE,!0,f);if(o.useMac){var N=n.md.sha1.create(),k=new n.util.ByteBuffer(n.random.getBytes(o.saltSize)),w=o.count,R=(e=s.generateKey(r,k,3,w,20),n.hmac.create());R.start(N,e),R.update(a.toDer(B).getBytes());var L=R.getMac();A=a.create(a.Class.UNIVERSAL,a.Type.SEQUENCE,!0,[a.create(a.Class.UNIVERSAL,a.Type.SEQUENCE,!0,[a.create(a.Class.UNIVERSAL,a.Type.SEQUENCE,!0,[a.create(a.Class.UNIVERSAL,a.Type.OID,!1,a.oidToDer(i.oids.sha1).getBytes()),a.create(a.Class.UNIVERSAL,a.Type.NULL,!1,"")]),a.create(a.Class.UNIVERSAL,a.Type.OCTETSTRING,!1,L.getBytes())]),a.create(a.Class.UNIVERSAL,a.Type.OCTETSTRING,!1,k.getBytes()),a.create(a.Class.UNIVERSAL,a.Type.INTEGER,!1,a.integerToDer(w).getBytes())])}return a.create(a.Class.UNIVERSAL,a.Type.SEQUENCE,!0,[a.create(a.Class.UNIVERSAL,a.Type.INTEGER,!1,a.integerToDer(3).getBytes()),a.create(a.Class.UNIVERSAL,a.Type.SEQUENCE,!0,[a.create(a.Class.UNIVERSAL,a.Type.OID,!1,a.oidToDer(i.oids.data).getBytes()),a.create(a.Class.CONTEXT_SPECIFIC,0,!0,[a.create(a.Class.UNIVERSAL,a.Type.OCTETSTRING,!1,a.toDer(B).getBytes())])]),A])},s.generateKey=n.pbe.generatePkcs12Key},function(e,t,r){var n=r(0);r(3),r(1);var a=n.asn1,i=e.exports=n.pkcs7asn1=n.pkcs7asn1||{};n.pkcs7=n.pkcs7||{},n.pkcs7.asn1=i;var s={name:"ContentInfo",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:a.Class.UNIVERSAL,type:a.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:a.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};i.contentInfoValidator=s;var o={name:"EncryptedContentInfo",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:a.Class.UNIVERSAL,type:a.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:a.Class.UNIVERSAL,type:a.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:a.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:a.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};i.envelopedDataValidator={name:"EnvelopedData",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:a.Class.UNIVERSAL,type:a.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:a.Class.UNIVERSAL,type:a.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(o)},i.encryptedDataValidator={name:"EncryptedData",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:a.Class.UNIVERSAL,type:a.Type.INTEGER,constructed:!1,capture:"version"}].concat(o)};var c={name:"SignerInfo",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:a.Class.UNIVERSAL,type:a.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:a.Class.UNIVERSAL,type:a.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:a.Class.UNIVERSAL,type:a.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:a.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:a.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:a.Class.UNIVERSAL,type:a.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:a.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};i.signedDataValidator={name:"SignedData",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:a.Class.UNIVERSAL,type:a.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:a.Class.UNIVERSAL,type:a.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},s,{name:"SignedData.Certificates",tagClass:a.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:a.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:a.Class.UNIVERSAL,type:a.Type.SET,capture:"signerInfos",optional:!0,value:[c]}]},i.recipientInfoValidator={name:"RecipientInfo",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:a.Class.UNIVERSAL,type:a.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:a.Class.UNIVERSAL,type:a.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:a.Class.UNIVERSAL,type:a.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:a.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:a.Class.UNIVERSAL,type:a.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}},function(e,t,r){var n=r(0);r(1),n.mgf=n.mgf||{},(e.exports=n.mgf.mgf1=n.mgf1=n.mgf1||{}).create=function(e){return{generate:function(t,r){for(var a=new n.util.ByteBuffer,i=Math.ceil(r/e.digestLength),s=0;s>>0,s>>>0];for(var o=h.fullMessageLength.length-1;o>=0;--o)h.fullMessageLength[o]+=s[1],s[1]=s[0]+(h.fullMessageLength[o]/4294967296>>>0),h.fullMessageLength[o]=h.fullMessageLength[o]>>>0,s[0]=s[1]/4294967296>>>0;return a.putBytes(e),l(r,i,a),(a.read>2048||0===a.length())&&a.compact(),h},h.digest=function(){var t=n.util.createBuffer();t.putBytes(a.bytes());var o,c=h.fullMessageLength[h.fullMessageLength.length-1]+h.messageLengthSize&h.blockLength-1;t.putBytes(s.substr(0,h.blockLength-c));for(var u=8*h.fullMessageLength[0],p=0;p>>0,t.putInt32(u>>>0),u=o>>>0;t.putInt32(u);var f=new Array(r.length);for(p=0;p=128;){for(R=0;R<16;++R)t[R][0]=r.getInt32()>>>0,t[R][1]=r.getInt32()>>>0;for(;R<80;++R)n=(((L=(U=t[R-2])[0])>>>19|(_=U[1])<<13)^(_>>>29|L<<3)^L>>>6)>>>0,a=((L<<13|_>>>19)^(_<<3|L>>>29)^(L<<26|_>>>6))>>>0,i=(((L=(P=t[R-15])[0])>>>1|(_=P[1])<<31)^(L>>>8|_<<24)^L>>>7)>>>0,s=((L<<31|_>>>1)^(L<<24|_>>>8)^(L<<25|_>>>7))>>>0,D=t[R-7],V=t[R-16],_=a+D[1]+s+V[1],t[R][0]=n+D[0]+i+V[0]+(_/4294967296>>>0)>>>0,t[R][1]=_>>>0;for(d=e[0][0],y=e[0][1],g=e[1][0],v=e[1][1],m=e[2][0],C=e[2][1],E=e[3][0],S=e[3][1],T=e[4][0],I=e[4][1],b=e[5][0],A=e[5][1],B=e[6][0],N=e[6][1],k=e[7][0],w=e[7][1],R=0;R<80;++R)l=((T>>>14|I<<18)^(T>>>18|I<<14)^(I>>>9|T<<23))>>>0,p=(B^T&(b^B))>>>0,o=((d>>>28|y<<4)^(y>>>2|d<<30)^(y>>>7|d<<25))>>>0,u=((d<<4|y>>>28)^(y<<30|d>>>2)^(y<<25|d>>>7))>>>0,f=(d&g|m&(d^g))>>>0,h=(y&v|C&(y^v))>>>0,_=w+(((T<<18|I>>>14)^(T<<14|I>>>18)^(I<<23|T>>>9))>>>0)+((N^I&(A^N))>>>0)+c[R][1]+t[R][1],n=k+l+p+c[R][0]+t[R][0]+(_/4294967296>>>0)>>>0,a=_>>>0,i=o+f+((_=u+h)/4294967296>>>0)>>>0,s=_>>>0,k=B,w=N,B=b,N=A,b=T,A=I,T=E+n+((_=S+a)/4294967296>>>0)>>>0,I=_>>>0,E=m,S=C,m=g,C=v,g=d,v=y,d=n+i+((_=a+s)/4294967296>>>0)>>>0,y=_>>>0;_=e[0][1]+y,e[0][0]=e[0][0]+d+(_/4294967296>>>0)>>>0,e[0][1]=_>>>0,_=e[1][1]+v,e[1][0]=e[1][0]+g+(_/4294967296>>>0)>>>0,e[1][1]=_>>>0,_=e[2][1]+C,e[2][0]=e[2][0]+m+(_/4294967296>>>0)>>>0,e[2][1]=_>>>0,_=e[3][1]+S,e[3][0]=e[3][0]+E+(_/4294967296>>>0)>>>0,e[3][1]=_>>>0,_=e[4][1]+I,e[4][0]=e[4][0]+T+(_/4294967296>>>0)>>>0,e[4][1]=_>>>0,_=e[5][1]+A,e[5][0]=e[5][0]+b+(_/4294967296>>>0)>>>0,e[5][1]=_>>>0,_=e[6][1]+N,e[6][0]=e[6][0]+B+(_/4294967296>>>0)>>>0,e[6][1]=_>>>0,_=e[7][1]+w,e[7][0]=e[7][0]+k+(_/4294967296>>>0)>>>0,e[7][1]=_>>>0,O-=128}}},function(e,t,r){var n=r(0);r(1);var a=e.exports=n.net=n.net||{};a.socketPools={},a.createSocketPool=function(e){e.msie=e.msie||!1;var t=e.flashId,r=document.getElementById(t);r.init({marshallExceptions:!e.msie});var i={id:t,flashApi:r,sockets:{},policyPort:e.policyPort||0,policyUrl:e.policyUrl||null};a.socketPools[t]=i,!0===e.msie?i.handler=function(e){if(e.id in i.sockets){var t;switch(e.type){case"connect":t="connected";break;case"close":t="closed";break;case"socketData":t="data";break;default:t="error"}setTimeout((function(){i.sockets[e.id][t](e)}),0)}}:i.handler=function(e){if(e.id in i.sockets){var t;switch(e.type){case"connect":t="connected";break;case"close":t="closed";break;case"socketData":t="data";break;default:t="error"}i.sockets[e.id][t](e)}};var s="forge.net.socketPools['"+t+"'].handler";return r.subscribe("connect",s),r.subscribe("close",s),r.subscribe("socketData",s),r.subscribe("ioError",s),r.subscribe("securityError",s),i.destroy=function(){for(var t in delete a.socketPools[e.flashId],i.sockets)i.sockets[t].destroy();i.sockets={},r.cleanup()},i.createSocket=function(e){e=e||{};var t=r.create(),a={id:t,connected:e.connected||function(e){},closed:e.closed||function(e){},data:e.data||function(e){},error:e.error||function(e){},destroy:function(){r.destroy(t),delete i.sockets[t]},connect:function(e){var n=e.policyUrl||null,a=0;null===n&&0!==e.policyPort&&(a=e.policyPort||i.policyPort),r.connect(t,e.host,e.port,a,n)},close:function(){r.close(t),a.closed({id:a.id,type:"close",bytesAvailable:0})},isConnected:function(){return r.isConnected(t)},send:function(e){return r.send(t,n.util.encode64(e))},receive:function(e){var a=r.receive(t,e).rval;return null===a?null:n.util.decode64(a)},bytesAvailable:function(){return r.getBytesAvailable(t)}};return i.sockets[t]=a,a},i},a.destroySocketPool=function(e){e.flashId in a.socketPools&&a.socketPools[e.flashId].destroy()},a.createSocket=function(e){var t=null;e.flashId in a.socketPools&&(t=a.socketPools[e.flashId].createSocket(e));return t}},function(e,t,r){var n=r(0);r(10),r(1);var a=e.exports=n.http=n.http||{},i=function(e){return e.toLowerCase().replace(/(^.)|(-.)/g,(function(e){return e.toUpperCase()}))},s=function(e){return"forge.http."+e.url.protocol.slice(0,-1)+"."+e.url.hostname+"."+e.url.port},o=function(e){if(e.persistCookies)try{var t=n.util.getItem(e.socketPool.flashApi,s(e),"cookies");e.cookies=t||{}}catch(e){}},c=function(e){if(e.persistCookies)try{n.util.setItem(e.socketPool.flashApi,s(e),"cookies",e.cookies)}catch(e){}o(e)},u=function(e,t){t.isConnected()?(t.options.request.connectTime=+new Date,t.connected({type:"connect",id:t.id})):(t.options.request.connectTime=+new Date,t.connect({host:e.url.hostname,port:e.url.port,policyPort:e.policyPort,policyUrl:e.policyUrl}))},l=function(e,t){t.buffer.clear();for(var r=null;null===r&&e.requests.length>0;)(r=e.requests.shift()).request.aborted&&(r=null);null===r?(null!==t.options&&(t.options=null),e.idle.push(t)):(t.retries=1,t.options=r,u(e,t))},p=function(e,t,r){t.options=null,t.connected=function(r){if(null===t.options)l(e,t);else{var n=t.options.request;if(n.connectTime=+new Date-n.connectTime,r.socket=t,t.options.connected(r),n.aborted)t.close();else{var a=n.toString();n.body&&(a+=n.body),n.time=+new Date,t.send(a),n.time=+new Date-n.time,t.options.response.time=+new Date,t.sending=!0}}},t.closed=function(r){if(t.sending)t.sending=!1,t.retries>0?(--t.retries,u(e,t)):t.error({id:t.id,type:"ioError",message:"Connection closed during send. Broken pipe.",bytesAvailable:0});else{var n=t.options.response;n.readBodyUntilClose&&(n.time=+new Date-n.time,n.bodyReceived=!0,t.options.bodyReady({request:t.options.request,response:n,socket:t})),t.options.closed(r),l(e,t)}},t.data=function(r){if(t.sending=!1,t.options.request.aborted)t.close();else{var n=t.options.response,a=t.receive(r.bytesAvailable);if(null!==a)if(t.buffer.putBytes(a),n.headerReceived||(n.readHeader(t.buffer),n.headerReceived&&t.options.headerReady({request:t.options.request,response:n,socket:t})),n.headerReceived&&!n.bodyReceived&&n.readBody(t.buffer),n.bodyReceived)t.options.bodyReady({request:t.options.request,response:n,socket:t}),-1!=(n.getField("Connection")||"").indexOf("close")||"HTTP/1.0"===n.version&&null===n.getField("Keep-Alive")?t.close():l(e,t)}},t.error=function(e){t.options.error({type:e.type,message:e.message,request:t.options.request,response:t.options.response,socket:t}),t.close()},r?((t=n.tls.wrapSocket({sessionId:null,sessionCache:{},caStore:r.caStore,cipherSuites:r.cipherSuites,socket:t,virtualHost:r.virtualHost,verify:r.verify,getCertificate:r.getCertificate,getPrivateKey:r.getPrivateKey,getSignature:r.getSignature,deflate:r.deflate||null,inflate:r.inflate||null})).options=null,t.buffer=n.util.createBuffer(),e.sockets.push(t),r.prime?t.connect({host:e.url.hostname,port:e.url.port,policyPort:e.policyPort,policyUrl:e.policyUrl}):e.idle.push(t)):(t.buffer=n.util.createBuffer(),e.sockets.push(t),e.idle.push(t))},f=function(e){var t=!1;if(-1!==e.maxAge){var r=y(new Date);e.created+e.maxAge<=r&&(t=!0)}return t};a.createClient=function(e){var t,r=null;e.caCerts&&(r=n.pki.createCaStore(e.caCerts)),e.url=e.url||window.location.protocol+"//"+window.location.host;try{t=new URL(e.url)}catch(t){var i=new Error("Invalid url.");throw i.details={url:e.url},i}e.connections=e.connections||1;var l=e.socketPool,h={url:t,socketPool:l,policyPort:e.policyPort,policyUrl:e.policyUrl,requests:[],sockets:[],idle:[],secure:"https:"===t.protocol,cookies:{},persistCookies:void 0===e.persistCookies||e.persistCookies};o(h);var d=null;h.secure&&(d={caStore:r,cipherSuites:e.cipherSuites||null,virtualHost:e.virtualHost||t.hostname,verify:e.verify||function(e,t,r,n){if(0===r&&!0===t){var a=n[r].subject.getField("CN");null!==a&&h.url.hostname===a.value||(t={message:"Certificate common name does not match url host."})}return t},getCertificate:e.getCertificate||null,getPrivateKey:e.getPrivateKey||null,getSignature:e.getSignature||null,prime:e.primeTlsSockets||!1},null!==l.flashApi&&(d.deflate=function(e){return n.util.deflate(l.flashApi,e,!0)},d.inflate=function(e){return n.util.inflate(l.flashApi,e,!0)}));for(var g=0;g100?(t.body=n.util.deflate(t.flashApi,t.body),t.bodyDeflated=!0,t.setField("Content-Encoding","deflate"),t.setField("Content-Length",t.body.length)):null!==t.body&&t.setField("Content-Length",t.body.length);var e=t.method.toUpperCase()+" "+t.path+" "+t.version+"\r\n";for(var r in t.fields)for(var a=t.fields[r],i=0;i=3)){var o=new Error("Invalid http response header.");throw o.details={line:r},o}a.version=n[0],a.code=parseInt(n[1],10),a.message=n.slice(2).join(" ")}else 0===r.length?a.headerReceived=!0:s(r);return a.headerReceived};return a.readBody=function(e){var o=a.getField("Content-Length"),c=a.getField("Transfer-Encoding");if(null!==o&&(o=parseInt(o)),null!==o&&o>=0)a.body=a.body||"",a.body+=e.getBytes(o),a.bodyReceived=a.body.length===o;else if(null!==c){if(-1==c.indexOf("chunked")){var u=new Error("Unknown Transfer-Encoding.");throw u.details={transferEncoding:c},u}a.body=a.body||"",function(e){for(var n="";null!==n&&e.length()>0;)if(t>0){if(t+2>e.length())break;a.body+=e.getBytes(t),e.getBytes(2),t=0}else if(r)for(n=i(e);null!==n;)n.length>0?(s(n),n=i(e)):(a.bodyReceived=!0,n=null);else null!==(n=i(e))&&(t=parseInt(n.split(";",1)[0],16),r=0===t);a.bodyReceived}(e)}else null!==o&&o<0||null===o&&null!==a.getField("Content-Type")?(a.body=a.body||"",a.body+=e.getBytes(),a.readBodyUntilClose=!0):(a.body=null,a.bodyReceived=!0);return a.bodyReceived&&(a.time=+new Date-a.time),null!==a.flashApi&&a.bodyReceived&&null!==a.body&&"deflate"===a.getField("Content-Encoding")&&(a.body=n.util.inflate(a.flashApi,a.body)),a.bodyReceived},a.getCookies=function(){var e=[];if("Set-Cookie"in a.fields)for(var t=a.fields["Set-Cookie"],r=+new Date/1e3,n=/\s*([^=]*)=?([^;]*)(;|$)/g,i=0;i0;)o.push(u%i),u=u/i|0}for(a=0;0===e[a]&&a=0;--a)n+=t[o[a]]}else n=function(e,t){var r=0,n=t.length,a=t.charAt(0),i=[0];for(r=0;r0;)i.push(o%n),o=o/n|0}var c="";for(r=0;0===e.at(r)&&r=0;--r)c+=t[i[r]];return c}(e,t);if(r){var l=new RegExp(".{1,"+r+"}","g");n=n.match(l).join("\r\n")}return n},r.decode=function(e,t){if("string"!=typeof e)throw new TypeError('"input" must be a string.');if("string"!=typeof t)throw new TypeError('"alphabet" must be a string.');var r=n[t];if(!r){r=n[t]=[];for(var a=0;a>=8;for(;l>0;)o.push(255&l),l>>=8}for(var p=0;e[p]===s&&p=a.Versions.TLS_1_1.minor&&c.output.putBytes(r),c.update(e.fragment),c.finish(o)&&(e.fragment=c.output,e.length=e.fragment.length(),i=!0),i}function o(e,t,r){if(!r){var n=e-t.length()%e;t.fillWithByte(n-1,n)}return!0}function c(e,t,r){var n=!0;if(r){for(var a=t.length(),i=t.last(),s=a-1-i;s=o?(e.fragment=s.output.getBytes(l-o),u=s.output.getBytes(o)):e.fragment=s.output.getBytes(),e.fragment=n.util.createBuffer(e.fragment),e.length=e.fragment.length();var p=t.macFunction(t.macKey,t.sequenceNumber,e);return t.updateSequenceNumber(),i=function(e,t,r){var a=n.hmac.create();return a.start("SHA1",e),a.update(t),t=a.digest().getBytes(),a.start(null,null),a.update(r),r=a.digest().getBytes(),t===r}(t.macKey,u,p)&&i}a.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA={id:[0,47],name:"TLS_RSA_WITH_AES_128_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=a.BulkCipherAlgorithm.aes,e.cipher_type=a.CipherType.block,e.enc_key_length=16,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=a.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:i},a.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA={id:[0,53],name:"TLS_RSA_WITH_AES_256_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=a.BulkCipherAlgorithm.aes,e.cipher_type=a.CipherType.block,e.enc_key_length=32,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=a.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:i}},function(e,t,r){var n=r(0);r(30),e.exports=n.mgf=n.mgf||{},n.mgf.mgf1=n.mgf1},function(e,t,r){var n=r(0);r(13),r(2),r(31),r(1);var a=r(42),i=a.publicKeyValidator,s=a.privateKeyValidator;if(void 0===o)var o=n.jsbn.BigInteger;var c=n.util.ByteBuffer,u="undefined"==typeof Buffer?Uint8Array:Buffer;n.pki=n.pki||{},e.exports=n.pki.ed25519=n.ed25519=n.ed25519||{};var l=n.ed25519;function p(e){var t=e.message;if(t instanceof Uint8Array||t instanceof u)return t;var r=e.encoding;if(void 0===t){if(!e.md)throw new TypeError('"options.message" or "options.md" not specified.');t=e.md.digest().getBytes(),r="binary"}if("string"==typeof t&&!r)throw new TypeError('"options.encoding" must be "binary" or "utf8".');if("string"==typeof t){if("undefined"!=typeof Buffer)return Buffer.from(t,r);t=new c(t,r)}else if(!(t instanceof c))throw new TypeError('"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.');for(var n=new u(t.length()),a=0;a=0;--r)x(n,n),1!==r&&K(n,n,t);for(r=0;r<16;++r)e[r]=n[r]}(r,r),K(r,r,a),K(r,r,i),K(r,r,i),K(e[0],r,i),x(n,e[0]),K(n,n,i),N(n,a)&&K(e[0],e[0],C);if(x(n,e[0]),K(n,n,i),N(n,a))return-1;w(e[0])===t[31]>>7&&O(e[0],f,e[0]);return K(e[3],e[0],e[1]),0}(o,n))return-1;for(a=0;a=0};var f=P(),h=P([1]),d=P([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),y=P([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),g=P([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),v=P([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),m=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]),C=P([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function E(e,t){var r=n.md.sha512.create(),a=new c(e);r.update(a.getBytes(t),"binary");var i=r.digest().getBytes();if("undefined"!=typeof Buffer)return Buffer.from(i,"binary");for(var s=new u(l.constants.HASH_BYTE_LENGTH),o=0;o<64;++o)s[o]=i.charCodeAt(o);return s}function S(e,t){var r,n,a,i;for(n=63;n>=32;--n){for(r=0,a=n-32,i=n-12;a>8,t[a]-=256*r;t[a]+=r,t[n]=0}for(r=0,a=0;a<32;++a)t[a]+=r-(t[31]>>4)*m[a],r=t[a]>>8,t[a]&=255;for(a=0;a<32;++a)t[a]-=r*m[a];for(n=0;n<32;++n)t[n+1]+=t[n]>>8,e[n]=255&t[n]}function T(e){for(var t=new Float64Array(64),r=0;r<64;++r)t[r]=e[r],e[r]=0;S(e,t)}function I(e,t){var r=P(),n=P(),a=P(),i=P(),s=P(),o=P(),c=P(),u=P(),l=P();O(r,e[1],e[0]),O(l,t[1],t[0]),K(r,r,l),V(n,e[0],e[1]),V(l,t[0],t[1]),K(n,n,l),K(a,e[3],t[3]),K(a,a,y),K(i,e[2],t[2]),V(i,i,i),O(s,n,r),O(o,i,a),V(c,i,a),V(u,n,r),K(e[0],s,o),K(e[1],u,c),K(e[2],c,o),K(e[3],s,u)}function b(e,t,r){for(var n=0;n<4;++n)D(e[n],t[n],r)}function A(e,t){var r=P(),n=P(),a=P();!function(e,t){var r,n=P();for(r=0;r<16;++r)n[r]=t[r];for(r=253;r>=0;--r)x(n,n),2!==r&&4!==r&&K(n,n,t);for(r=0;r<16;++r)e[r]=n[r]}(a,t[2]),K(r,t[0],a),K(n,t[1],a),B(e,n),e[31]^=w(r)<<7}function B(e,t){var r,n,a,i=P(),s=P();for(r=0;r<16;++r)s[r]=t[r];for(U(s),U(s),U(s),n=0;n<2;++n){for(i[0]=s[0]-65517,r=1;r<15;++r)i[r]=s[r]-65535-(i[r-1]>>16&1),i[r-1]&=65535;i[15]=s[15]-32767-(i[14]>>16&1),a=i[15]>>16&1,i[14]&=65535,D(s,i,1-a)}for(r=0;r<16;r++)e[2*r]=255&s[r],e[2*r+1]=s[r]>>8}function N(e,t){var r=new u(32),n=new u(32);return B(r,e),B(n,t),k(r,0,n,0)}function k(e,t,r,n){return function(e,t,r,n,a){var i,s=0;for(i=0;i>>8)-1}(e,t,r,n,32)}function w(e){var t=new u(32);return B(t,e),1&t[0]}function R(e,t,r){var n,a;for(_(e[0],f),_(e[1],h),_(e[2],h),_(e[3],f),a=255;a>=0;--a)b(e,t,n=r[a/8|0]>>(7&a)&1),I(t,e),I(e,e),b(e,t,n)}function L(e,t){var r=[P(),P(),P(),P()];_(r[0],g),_(r[1],v),_(r[2],h),K(r[3],g,v),R(e,r,t)}function _(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function U(e){var t,r,n=1;for(t=0;t<16;++t)r=e[t]+n+65535,n=Math.floor(r/65536),e[t]=r-65536*n;e[0]+=n-1+37*(n-1)}function D(e,t,r){for(var n,a=~(r-1),i=0;i<16;++i)n=a&(e[i]^t[i]),e[i]^=n,t[i]^=n}function P(e){var t,r=new Float64Array(16);if(e)for(t=0;t0&&(s=n.util.fillString(String.fromCharCode(0),c)+s),{encapsulation:t.encrypt(s,"NONE"),key:e.generate(s,i)}},decrypt:function(t,r,n){var a=t.decrypt(r,"NONE");return e.generate(a,n)}};return i},n.kem.kdf1=function(e,t){i(this,e,0,t||e.digestLength)},n.kem.kdf2=function(e,t){i(this,e,1,t||e.digestLength)}},function(e,t,r){var n=r(0);r(1),e.exports=n.log=n.log||{},n.log.levels=["none","error","warning","info","debug","verbose","max"];var a={},i=[],s=null;n.log.LEVEL_LOCKED=2,n.log.NO_LEVEL_CHECK=4,n.log.INTERPOLATE=8;for(var o=0;o0){for(var r=a.create(a.Class.CONTEXT_SPECIFIC,1,!0,[]),i=0;i=r&&s0&&s.value[0].value.push(a.create(a.Class.CONTEXT_SPECIFIC,0,!0,t)),i.length>0&&s.value[0].value.push(a.create(a.Class.CONTEXT_SPECIFIC,1,!0,i)),s.value[0].value.push(a.create(a.Class.UNIVERSAL,a.Type.SET,!0,e.signerInfos)),a.create(a.Class.UNIVERSAL,a.Type.SEQUENCE,!0,[a.create(a.Class.UNIVERSAL,a.Type.OID,!1,a.oidToDer(e.type).getBytes()),s])},addSigner:function(t){var r=t.issuer,a=t.serialNumber;if(t.certificate){var i=t.certificate;"string"==typeof i&&(i=n.pki.certificateFromPem(i)),r=i.issuer.attributes,a=i.serialNumber}var s=t.key;if(!s)throw new Error("Could not add PKCS#7 signer; no private key specified.");"string"==typeof s&&(s=n.pki.privateKeyFromPem(s));var o=t.digestAlgorithm||n.pki.oids.sha1;switch(o){case n.pki.oids.sha1:case n.pki.oids.sha256:case n.pki.oids.sha384:case n.pki.oids.sha512:case n.pki.oids.md5:break;default:throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+o)}var c=t.authenticatedAttributes||[];if(c.length>0){for(var u=!1,l=!1,p=0;p="8"&&(r="00"+r);var a=n.util.hexToBytes(r);e.putInt32(a.length),e.putBytes(a)}function s(e,t){e.putInt32(t.length),e.putString(t)}function o(){for(var e=n.md.sha1.create(),t=arguments.length,r=0;r0&&r.push(t[1]),t.length>=2&&r.push(t[2]);return 0===r.length&&r.push(e),r}(t))})),t=s,n.each(t,(function(a,s){if(i&&0!==s.length&&s in i&&(s=i[s]),0===s.length&&(s=e.length),e[s])a==t.length-1?(n.isArray(e[s])||(e[s]=[e[s]]),e[s].push(r)):e=e[s];else if(a==t.length-1)e[s]=r;else{var o=t[a+1];if(0===o.length)e[s]=[];else{var c=o-0==o&&o.length>0;e[s]=c?[]:{}}e=e[s]}}))},o.serialize=function(e,t,r){var a={};return t=t||".",n.each(e.serializeArray(),(function(){i(a,this.name.split(t),this.value||"",r)})),a}},function(e,t,r){var n=r(0);r(10),n.tls.wrapSocket=function(e){var t=e.socket,r={id:t.id,connected:t.connected||function(e){},closed:t.closed||function(e){},data:t.data||function(e){},error:t.error||function(e){}},a=n.tls.createConnection({server:!1,sessionId:e.sessionId||null,caStore:e.caStore||[],sessionCache:e.sessionCache||null,cipherSuites:e.cipherSuites||null,virtualHost:e.virtualHost,verify:e.verify,getCertificate:e.getCertificate,getPrivateKey:e.getPrivateKey,getSignature:e.getSignature,deflate:e.deflate,inflate:e.inflate,connected:function(e){1===e.handshakes&&r.connected({id:t.id,type:"connect",bytesAvailable:e.data.length()})},tlsDataReady:function(e){return t.send(e.tlsData.getBytes())},dataReady:function(e){r.data({id:t.id,type:"socketData",bytesAvailable:e.data.length()})},closed:function(e){t.close()},error:function(e,n){r.error({id:t.id,type:"tlsError",message:n.message,bytesAvailable:0,error:n}),t.close()}});t.connected=function(t){a.handshake(e.sessionId)},t.closed=function(e){a.open&&a.handshaking&&r.error({id:t.id,type:"ioError",message:"Connection closed during handshake.",bytesAvailable:0}),a.close(),r.closed({id:t.id,type:"close",bytesAvailable:0})},t.error=function(e){r.error({id:t.id,type:e.type,message:e.message,bytesAvailable:0}),a.close()};var i=0;return t.data=function(e){if(a.open){if(e.bytesAvailable>=i){var r=Math.max(e.bytesAvailable,i),n=t.receive(r);null!==n&&(i=a.process(n))}}else t.receive(e.bytesAvailable)},r.destroy=function(){t.destroy()},r.setSessionCache=function(e){a.sessionCache=tls.createSessionCache(e)},r.connect=function(e){t.connect(e)},r.close=function(){a.close()},r.isConnected=function(){return a.isConnected&&t.isConnected()},r.send=function(e){return a.prepare(e)},r.receive=function(e){return a.data.getBytes(e)},r.bytesAvailable=function(){return a.data.length()},r}},function(e,t,r){var n=r(0);r(32),r(33);var a,i,s,o,c,u,l,p,f,h,d=e.exports=n.xhr=n.xhr||{};a=jQuery,i="forge.xhr",s=null,o=0,c=null,u=null,l={},p=10,f=n.net,h=n.http,d.init=function(e){n.log.debug(i,"initializing",e),o=e.policyPort||o,c=e.policyUrl||c,p=e.connections||p,s=f.createSocketPool({flashId:e.flashId,policyPort:o,policyUrl:c,msie:e.msie||!1}),u=h.createClient({url:e.url||window.location.protocol+"//"+window.location.host,socketPool:s,policyPort:o,policyUrl:c,connections:e.connections||p,caCerts:e.caCerts,cipherSuites:e.cipherSuites,persistCookies:e.persistCookies||!0,primeTlsSockets:e.primeTlsSockets||!1,verify:e.verify,getCertificate:e.getCertificate,getPrivateKey:e.getPrivateKey,getSignature:e.getSignature}),l[u.url.origin]=u,n.log.debug(i,"ready")},d.cleanup=function(){for(var e in l)l[e].destroy();l={},u=null,s.destroy(),s=null},d.setCookie=function(e){if(e.maxAge=e.maxAge||-1,e.domain)for(var t in l){var r=l[t];h.withinCookieDomain(r.url,e)&&r.secure===e.secure&&r.setCookie(e)}else u.setCookie(e)},d.getCookie=function(e,t,r){var a=null;if(r)for(var i in l){var s=l[i];if(h.withinCookieDomain(s.url,r)){var o=s.getCookie(e,t);null!==o&&(null===a?a=o:n.util.isArray(a)?a.push(o):a=[a,o])}}else a=u.getCookie(e,t);return a},d.removeCookie=function(e,t,r){var n=!1;if(r)for(var a in l){var i=l[a];h.withinCookieDomain(i.url,r)&&i.removeCookie(e,t)&&(n=!0)}else n=u.removeCookie(e,t);return n},d.create=function(e){e=a.extend({logWarningOnError:!0,verbose:!1,logError:function(){},logWarning:function(){},logDebug:function(){},logVerbose:function(){},url:null},e||{});var t={client:null,request:null,response:null,asynchronous:!0,sendFlag:!1,errorFlag:!1},r={error:e.logError||n.log.error,warning:e.logWarning||n.log.warning,debug:e.logDebug||n.log.debug,verbose:e.logVerbose||n.log.verbose},f={onreadystatechange:null,readyState:0,responseText:"",responseXML:null,status:0,statusText:""};if(null===e.url)t.client=u;else{var d;try{d=new URL(e.url)}catch(t){new Error("Invalid url.").details={url:e.url}}d.origin in l?t.client=l[d.origin]:(t.client=h.createClient({url:e.url,socketPool:s,policyPort:e.policyPort||o,policyUrl:e.policyUrl||c,connections:e.connections||p,caCerts:e.caCerts,cipherSuites:e.cipherSuites,persistCookies:e.persistCookies||!0,primeTlsSockets:e.primeTlsSockets||!1,verify:e.verify,getCertificate:e.getCertificate,getPrivateKey:e.getPrivateKey,getSignature:e.getSignature}),l[d.origin]=t.client)}return f.open=function(e,r,n,a,i){switch(e){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"PATCH":case"POST":case"PUT":break;case"CONNECT":case"TRACE":case"TRACK":throw new Error("CONNECT, TRACE and TRACK methods are disallowed");default:throw new Error("Invalid method: "+e)}t.sendFlag=!1,f.responseText="",f.responseXML=null,f.status=0,f.statusText="",t.request=h.createRequest({method:e,path:r}),f.readyState=1,f.onreadystatechange&&f.onreadystatechange()},f.setRequestHeader=function(e,r){if(1!=f.readyState||t.sendFlag)throw new Error("XHR not open or sending");t.request.setField(e,r)},f.send=function(e){if(1!=f.readyState||t.sendFlag)throw new Error("XHR not open or sending");if(e&&"GET"!==t.request.method&&"HEAD"!==t.request.method)if("undefined"!=typeof XMLSerializer)if(e instanceof Document){var n=new XMLSerializer;t.request.body=n.serializeToString(e)}else t.request.body=e;else void 0!==e.xml?t.request.body=e.xml:t.request.body=e;t.errorFlag=!1,t.sendFlag=!0,f.onreadystatechange&&f.onreadystatechange();var a={};a.request=t.request,a.headerReady=function(e){f.cookies=t.client.cookies,f.readyState=2,f.status=e.response.code,f.statusText=e.response.message,t.response=e.response,f.onreadystatechange&&f.onreadystatechange(),t.response.aborted||(f.readyState=3,f.onreadystatechange&&f.onreadystatechange())},a.bodyReady=function(e){f.readyState=4;var n=e.response.getField("Content-Type");if(n&&(0===n.indexOf("text/xml")||0===n.indexOf("application/xml")||-1!==n.indexOf("+xml")))try{var s=new ActiveXObject("MicrosoftXMLDOM");s.async=!1,s.loadXML(e.response.body),f.responseXML=s}catch(e){var o=new DOMParser;f.responseXML=o.parseFromString(e.body,"text/xml")}var c=0;null!==e.response.body&&(f.responseText=e.response.body,c=e.response.body.length);var u=t.request,l=u.method+" "+u.path+" "+f.status+" "+f.statusText+" "+c+"B "+(e.request.connectTime+e.request.time+e.response.time)+"ms";a.verbose?(f.status>=400&&a.logWarningOnError?r.warning:r.verbose)(i,l,e,e.response.body?"\n"+e.response.body:"\nNo content"):(f.status>=400&&a.logWarningOnError?r.warning:r.debug)(i,l),f.onreadystatechange&&f.onreadystatechange()},a.error=function(e){var n=t.request;r.error(i,n.method+" "+n.path,e),f.responseText="",f.responseXML=null,t.errorFlag=!0,f.status=0,f.statusText="",f.readyState=4,f.onreadystatechange&&f.onreadystatechange()},t.client.send(a)},f.abort=function(){t.request.abort(),f.responseText="",f.responseXML=null,t.errorFlag=!0,f.status=0,f.statusText="",t.request=null,t.response=null,4===f.readyState||0===f.readyState||1===f.readyState&&!t.sendFlag||(f.readyState=4,t.sendFlag=!1,f.onreadystatechange&&f.onreadystatechange()),f.readyState=0},f.getAllResponseHeaders=function(){var e="";if(null!==t.response){var r=t.response.fields;a.each(r,(function(t,r){a.each(r,(function(r,n){e+=t+": "+n+"\r\n"}))}))}return e},f.getResponseHeader=function(e){var r=null;return null!==t.response&&e in t.response.fields&&(r=t.response.fields[e],n.util.isArray(r)&&(r=r.join())),r},f}}])})); +//# sourceMappingURL=forge.all.min.js.map \ No newline at end of file diff --git a/node_modules/node-forge/dist/forge.all.min.js.map b/node_modules/node-forge/dist/forge.all.min.js.map new file mode 100644 index 0000000..225d220 --- /dev/null +++ b/node_modules/node-forge/dist/forge.all.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"forge.all.min.js","sources":["webpack://[name]/forge.all.min.js"],"mappings":"AAAA","sourceRoot":""} \ No newline at end of file diff --git a/node_modules/node-forge/dist/forge.min.js b/node_modules/node-forge/dist/forge.min.js new file mode 100644 index 0000000..b25c210 --- /dev/null +++ b/node_modules/node-forge/dist/forge.min.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.forge=t():e.forge=t()}(window,(function(){return function(e){var t={};function r(a){if(t[a])return t[a].exports;var n=t[a]={i:a,l:!1,exports:{}};return e[a].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=e,r.c=t,r.d=function(e,t,a){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:a})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var a=Object.create(null);if(r.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)r.d(a,n,function(t){return e[t]}.bind(null,n));return a},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=32)}([function(e,t){e.exports={options:{usePureJavaScript:!1}}},function(e,t,r){(function(t){var a=r(0),n=r(35),i=e.exports=a.util=a.util||{};function s(e){if(8!==e&&16!==e&&24!==e&&32!==e)throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}function o(e){if(this.data="",this.read=0,"string"==typeof e)this.data=e;else if(i.isArrayBuffer(e)||i.isArrayBufferView(e))if("undefined"!=typeof Buffer&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch(e){for(var r=0;r15?(r=Date.now(),s(e)):(t.push(e),1===t.length&&n.setAttribute("a",a=!a))}}i.nextTick=i.setImmediate}(),i.isNodejs="undefined"!=typeof process&&process.versions&&process.versions.node,i.globalScope=i.isNodejs?t:"undefined"==typeof self?window:self,i.isArray=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},i.isArrayBuffer=function(e){return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer},i.isArrayBufferView=function(e){return e&&i.isArrayBuffer(e.buffer)&&void 0!==e.byteLength},i.ByteBuffer=o,i.ByteStringBuffer=o;i.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>4096&&(this.data.substr(0,1),this._constructedStringLength=0)},i.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},i.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},i.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))},i.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var r=this.data;t>0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return this.data=r,this._optimizeConstructedString(t),this},i.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this},i.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(i.encodeUtf8(e))},i.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},i.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},i.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},i.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255))},i.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))},i.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))},i.ByteStringBuffer.prototype.putInt=function(e,t){s(t);var r="";do{t-=8,r+=String.fromCharCode(e>>t&255)}while(t>0);return this.putBytes(r)},i.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<0);return t},i.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},i.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},i.ByteStringBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},i.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)},i.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this},i.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},i.ByteStringBuffer.prototype.copy=function(){var e=i.createBuffer(this.data);return e.read=this.read,e},i.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},i.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},i.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this},i.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t=e)return this;t=Math.max(t||this.growSize,e);var r=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),a=new Uint8Array(this.length()+t);return a.set(r),this.data=new DataView(a.buffer),this},i.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this},i.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var r=0;r>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this},i.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this},i.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this},i.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this},i.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this},i.DataBuffer.prototype.putInt=function(e,t){s(t),this.accommodate(t/8);do{t-=8,this.data.setInt8(this.write++,e>>t&255)}while(t>0);return this},i.DataBuffer.prototype.putSignedInt=function(e,t){return s(t),this.accommodate(t/8),e<0&&(e+=2<0);return t},i.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},i.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},i.DataBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},i.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)},i.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this},i.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},i.DataBuffer.prototype.copy=function(){return new i.DataBuffer(this)},i.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this},i.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},i.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this},i.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return r},i.xorBytes=function(e,t,r){for(var a="",n="",i="",s=0,o=0;r>0;--r,++s)n=e.charCodeAt(s)^t.charCodeAt(s),o>=10&&(a+=i,i="",o=0),i+=String.fromCharCode(n),++o;return a+=i},i.hexToBytes=function(e){var t="",r=0;for(!0&e.length&&(r=1,t+=String.fromCharCode(parseInt(e[0],16)));r>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e)};var c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",u=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,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,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],l="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";i.encode64=function(e,t){for(var r,a,n,i="",s="",o=0;o>2),i+=c.charAt((3&r)<<4|a>>4),isNaN(a)?i+="==":(i+=c.charAt((15&a)<<2|n>>6),i+=isNaN(n)?"=":c.charAt(63&n)),t&&i.length>t&&(s+=i.substr(0,t)+"\r\n",i=i.substr(t));return s+=i},i.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t,r,a,n,i="",s=0;s>4),64!==a&&(i+=String.fromCharCode((15&r)<<4|a>>2),64!==n&&(i+=String.fromCharCode((3&a)<<6|n)));return i},i.encodeUtf8=function(e){return unescape(encodeURIComponent(e))},i.decodeUtf8=function(e){return decodeURIComponent(escape(e))},i.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:n.encode,decode:n.decode}},i.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)},i.binary.raw.decode=function(e,t,r){var a=t;a||(a=new Uint8Array(e.length));for(var n=r=r||0,i=0;i>2),i+=c.charAt((3&r)<<4|a>>4),isNaN(a)?i+="==":(i+=c.charAt((15&a)<<2|n>>6),i+=isNaN(n)?"=":c.charAt(63&n)),t&&i.length>t&&(s+=i.substr(0,t)+"\r\n",i=i.substr(t));return s+=i},i.binary.base64.decode=function(e,t,r){var a,n,i,s,o=t;o||(o=new Uint8Array(3*Math.ceil(e.length/4))),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var c=0,l=r=r||0;c>4,64!==i&&(o[l++]=(15&n)<<4|i>>2,64!==s&&(o[l++]=(3&i)<<6|s));return t?l-r:o.subarray(0,l)},i.binary.base58.encode=function(e,t){return i.binary.baseN.encode(e,l,t)},i.binary.base58.decode=function(e,t){return i.binary.baseN.decode(e,l,t)},i.text={utf8:{},utf16:{}},i.text.utf8.encode=function(e,t,r){e=i.encodeUtf8(e);var a=t;a||(a=new Uint8Array(e.length));for(var n=r=r||0,s=0;s0&&i.push(r),s=a.lastIndex;var o=t[0][1];switch(o){case"s":case"o":n");break;case"%":i.push("%");break;default:i.push("<%"+o+"?>")}}return i.push(e.substring(s)),i.join("")},i.formatNumber=function(e,t,r,a){var n=e,i=isNaN(t=Math.abs(t))?2:t,s=void 0===r?",":r,o=void 0===a?".":a,c=n<0?"-":"",u=parseInt(n=Math.abs(+n||0).toFixed(i),10)+"",l=u.length>3?u.length%3:0;return c+(l?u.substr(0,l)+o:"")+u.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+o)+(i?s+Math.abs(n-u).toFixed(i).slice(2):"")},i.formatSize=function(e){return e=e>=1073741824?i.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?i.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?i.formatNumber(e/1024,0)+" KiB":i.formatNumber(e,0)+" bytes"},i.bytesFromIP=function(e){return-1!==e.indexOf(".")?i.bytesFromIPv4(e):-1!==e.indexOf(":")?i.bytesFromIPv6(e):null},i.bytesFromIPv4=function(e){if(4!==(e=e.split(".")).length)return null;for(var t=i.createBuffer(),r=0;rr[a].end-r[a].start&&(a=r.length-1)):r.push({start:c,end:c})}t.push(s)}if(r.length>0){var u=r[a];u.end-u.start>0&&(t.splice(u.start,u.end-u.start+1,""),0===u.start&&t.unshift(""),7===u.end&&t.push(""))}return t.join(":")},i.estimateCores=function(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},"cores"in i&&!e.update)return t(null,i.cores);if("undefined"!=typeof navigator&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return i.cores=navigator.hardwareConcurrency,t(null,i.cores);if("undefined"==typeof Worker)return i.cores=1,t(null,i.cores);if("undefined"==typeof Blob)return i.cores=2,t(null,i.cores);var r=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",(function(e){for(var t=Date.now(),r=t+4;Date.now()o.st&&n.stn.st&&o.stt){var a=new Error("Too few bytes to parse DER.");throw a.available=e.length(),a.remaining=t,a.requested=r,a}}n.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},n.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30},n.maxDepth=256,n.create=function(e,t,r,i,s){if(a.util.isArray(i)){for(var o=[],c=0;c=s.maxDepth)throw new Error("ASN.1 parsing error: Max depth exceeded.");var o;i(t,r,2);var c=t.getByte();r--;var u=192&c,l=31&c;o=t.length();var p,f,h=function(e,t){var r=e.getByte();if(t--,128!==r){var a;if(128&r){var n=127&r;i(e,t,n),a=e.getInt(n<<3)}else a=r;if(a<0)throw new Error("Negative length: "+a);return a}}(t,r);if(r-=o-t.length(),void 0!==h&&h>r){if(s.strict){var d=new Error("Too few bytes to read ASN.1 value.");throw d.available=t.length(),d.remaining=r,d.requested=h,d}h=r}var y=32==(32&c);if(y)if(p=[],void 0===h)for(;;){if(i(t,r,2),t.bytes(2)===String.fromCharCode(0,0)){t.getBytes(2),r-=2;break}o=t.length(),p.push(e(t,r,a+1,s)),r-=o-t.length()}else for(;h>0;)o=t.length(),p.push(e(t,h,a+1,s)),r-=o-t.length(),h-=o-t.length();void 0===p&&u===n.Class.UNIVERSAL&&l===n.Type.BITSTRING&&(f=t.bytes(h));if(void 0===p&&s.decodeBitStrings&&u===n.Class.UNIVERSAL&&l===n.Type.BITSTRING&&h>1){var g=t.read,v=r,m=0;if(l===n.Type.BITSTRING&&(i(t,r,1),m=t.getByte(),r--),0===m)try{o=t.length();var C=e(t,r,a+1,{strict:!0,decodeBitStrings:!0}),E=o-t.length();r-=E,l==n.Type.BITSTRING&&E++;var S=C.tagClass;E!==h||S!==n.Class.UNIVERSAL&&S!==n.Class.CONTEXT_SPECIFIC||(p=[C])}catch(e){}void 0===p&&(t.read=g,r=v)}if(void 0===p){if(void 0===h){if(s.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");h=r}if(l===n.Type.BMPSTRING)for(p="";h>0;h-=2)i(t,r,2),p+=String.fromCharCode(t.getInt16()),r-=2;else p=t.getBytes(h),r-=h}var T=void 0===f?null:{bitStringContents:f};return n.create(u,l,y,p,T)}(e,e.length(),0,t);if(t.parseAllBytes&&0!==e.length()){var o=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw o.byteCount=r,o.remaining=e.length(),o}return s},n.toDer=function(e){var t=a.util.createBuffer(),r=e.tagClass|e.type,i=a.util.createBuffer(),s=!1;if("bitStringContents"in e&&(s=!0,e.original&&(s=n.equals(e,e.original))),s)i.putBytes(e.bitStringContents);else if(e.composed){e.constructed?r|=32:i.putByte(0);for(var o=0;o1&&(0===e.value.charCodeAt(0)&&0==(128&e.value.charCodeAt(1))||255===e.value.charCodeAt(0)&&128==(128&e.value.charCodeAt(1)))?i.putBytes(e.value.substr(1)):i.putBytes(e.value);if(t.putByte(r),i.length()<=127)t.putByte(127&i.length());else{var c=i.length(),u="";do{u+=String.fromCharCode(255&c),c>>>=8}while(c>0);t.putByte(128|u.length);for(o=u.length-1;o>=0;--o)t.putByte(u.charCodeAt(o))}return t.putBuffer(i),t},n.oidToDer=function(e){var t,r,n,i,s=e.split("."),o=a.util.createBuffer();o.putByte(40*parseInt(s[0],10)+parseInt(s[1],10));for(var c=2;c4294967295)throw new Error("OID value too large; max is 32-bits.");do{i=127&n,n>>>=7,t||(i|=128),r.push(i),t=!1}while(n>0);for(var u=r.length-1;u>=0;--u)o.putByte(r[u])}return o},n.derToOid=function(e){var t;"string"==typeof e&&(e=a.util.createBuffer(e));var r=e.getByte();t=Math.floor(r/40)+"."+r%40;for(var n=0;e.length()>0;){if(n>70368744177663)throw new Error("OID value too large; max is 53-bits.");n*=128,128&(r=e.getByte())?n+=127&r:(t+="."+(n+r),n=0)}return t},n.utcTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,2),10);r=r>=50?1900+r:2e3+r;var a=parseInt(e.substr(2,2),10)-1,n=parseInt(e.substr(4,2),10),i=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),o=0;if(e.length>11){var c=e.charAt(10),u=10;"+"!==c&&"-"!==c&&(o=parseInt(e.substr(10,2),10),u+=2)}if(t.setUTCFullYear(r,a,n),t.setUTCHours(i,s,o,0),u&&("+"===(c=e.charAt(u))||"-"===c)){var l=60*parseInt(e.substr(u+1,2),10)+parseInt(e.substr(u+4,2),10);l*=6e4,"+"===c?t.setTime(+t-l):t.setTime(+t+l)}return t},n.generalizedTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,4),10),a=parseInt(e.substr(4,2),10)-1,n=parseInt(e.substr(6,2),10),i=parseInt(e.substr(8,2),10),s=parseInt(e.substr(10,2),10),o=parseInt(e.substr(12,2),10),c=0,u=0,l=!1;"Z"===e.charAt(e.length-1)&&(l=!0);var p=e.length-5,f=e.charAt(p);"+"!==f&&"-"!==f||(u=60*parseInt(e.substr(p+1,2),10)+parseInt(e.substr(p+4,2),10),u*=6e4,"+"===f&&(u*=-1),l=!0);return"."===e.charAt(14)&&(c=1e3*parseFloat(e.substr(14),10)),l?(t.setUTCFullYear(r,a,n),t.setUTCHours(i,s,o,c),t.setTime(+t+u)):(t.setFullYear(r,a,n),t.setHours(i,s,o,c)),t},n.dateToUtcTime=function(e){if("string"==typeof e)return e;var t="",r=[];r.push((""+e.getUTCFullYear()).substr(2)),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var a=0;a=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putSignedInt(e,24);if(e>=-2147483648&&e<2147483648)return t.putSignedInt(e,32);var r=new Error("Integer too large; max is 32-bits.");throw r.integer=e,r},n.derToInteger=function(e){"string"==typeof e&&(e=a.util.createBuffer(e));var t=8*e.length();if(t>32)throw new Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)},n.validate=function(e,t,r,i){var s=!1;if(e.tagClass!==t.tagClass&&void 0!==t.tagClass||e.type!==t.type&&void 0!==t.type)i&&(e.tagClass!==t.tagClass&&i.push("["+t.name+'] Expected tag class "'+t.tagClass+'", got "'+e.tagClass+'"'),e.type!==t.type&&i.push("["+t.name+'] Expected type "'+t.type+'", got "'+e.type+'"'));else if(e.constructed===t.constructed||void 0===t.constructed){if(s=!0,t.value&&a.util.isArray(t.value))for(var o=0,c=0;s&&c0&&(i+="\n");for(var o="",c=0;c1?i+="0x"+a.util.bytesToHex(e.value.slice(1)):i+="(none)",e.value.length>0){var f=e.value.charCodeAt(0);1==f?i+=" (1 unused bit shown)":f>1&&(i+=" ("+f+" unused bits shown)")}}else if(e.type===n.Type.OCTETSTRING)s.test(e.value)||(i+="("+e.value+") "),i+="0x"+a.util.bytesToHex(e.value);else if(e.type===n.Type.UTF8)try{i+=a.util.decodeUtf8(e.value)}catch(t){if("URI malformed"!==t.message)throw t;i+="0x"+a.util.bytesToHex(e.value)+" (malformed UTF8)"}else e.type===n.Type.PRINTABLESTRING||e.type===n.Type.IA5String?i+=e.value:s.test(e.value)?i+="0x"+a.util.bytesToHex(e.value):0===e.value.length?i+="[null]":i+=e.value}return i}},function(e,t,r){var a=r(0);e.exports=a.md=a.md||{},a.md.algorithms=a.md.algorithms||{}},function(e,t,r){var a=r(0);function n(e,t){a.cipher.registerAlgorithm(e,(function(){return new a.aes.Algorithm(e,t)}))}r(13),r(19),r(1),e.exports=a.aes=a.aes||{},a.aes.startEncrypting=function(e,t,r,a){var n=d({key:e,output:r,decrypt:!1,mode:a});return n.start(t),n},a.aes.createEncryptionCipher=function(e,t){return d({key:e,output:null,decrypt:!1,mode:t})},a.aes.startDecrypting=function(e,t,r,a){var n=d({key:e,output:r,decrypt:!0,mode:a});return n.start(t),n},a.aes.createDecryptionCipher=function(e,t){return d({key:e,output:null,decrypt:!0,mode:t})},a.aes.Algorithm=function(e,t){l||p();var r=this;r.name=e,r.mode=new t({blockSize:16,cipher:{encrypt:function(e,t){return h(r._w,e,t,!1)},decrypt:function(e,t){return h(r._w,e,t,!0)}}}),r._init=!1},a.aes.Algorithm.prototype.initialize=function(e){if(!this._init){var t,r=e.key;if("string"!=typeof r||16!==r.length&&24!==r.length&&32!==r.length){if(a.util.isArray(r)&&(16===r.length||24===r.length||32===r.length)){t=r,r=a.util.createBuffer();for(var n=0;n>>=2;for(n=0;n>8^255&p^99,i[y]=p,s[p]=y,h=(f=e[p])<<24^p<<16^p<<8^p^f,d=((r=e[y])^(a=e[r])^(n=e[a]))<<24^(y^n)<<16^(y^a^n)<<8^y^r^n;for(var v=0;v<4;++v)c[v][y]=h,u[v][p]=d,h=h<<24|h>>>8,d=d<<24|d>>>8;0===y?y=g=1:(y=r^e[e[e[r^n]]],g^=e[e[g]])}}function f(e,t){for(var r,a=e.slice(0),n=1,s=a.length,c=4*(s+6+1),l=s;l>>16&255]<<24^i[r>>>8&255]<<16^i[255&r]<<8^i[r>>>24]^o[n]<<24,n++):s>6&&l%s==4&&(r=i[r>>>24]<<24^i[r>>>16&255]<<16^i[r>>>8&255]<<8^i[255&r]),a[l]=a[l-s]^r;if(t){for(var p,f=u[0],h=u[1],d=u[2],y=u[3],g=a.slice(0),v=(l=0,(c=a.length)-4);l>>24]]^h[i[p>>>16&255]]^d[i[p>>>8&255]]^y[i[255&p]];a=g}return a}function h(e,t,r,a){var n,o,l,p,f,h,d,y,g,v,m,C,E=e.length/4-1;a?(n=u[0],o=u[1],l=u[2],p=u[3],f=s):(n=c[0],o=c[1],l=c[2],p=c[3],f=i),h=t[0]^e[0],d=t[a?3:1]^e[1],y=t[2]^e[2],g=t[a?1:3]^e[3];for(var S=3,T=1;T>>24]^o[d>>>16&255]^l[y>>>8&255]^p[255&g]^e[++S],m=n[d>>>24]^o[y>>>16&255]^l[g>>>8&255]^p[255&h]^e[++S],C=n[y>>>24]^o[g>>>16&255]^l[h>>>8&255]^p[255&d]^e[++S],g=n[g>>>24]^o[h>>>16&255]^l[d>>>8&255]^p[255&y]^e[++S],h=v,d=m,y=C;r[0]=f[h>>>24]<<24^f[d>>>16&255]<<16^f[y>>>8&255]<<8^f[255&g]^e[++S],r[a?3:1]=f[d>>>24]<<24^f[y>>>16&255]<<16^f[g>>>8&255]<<8^f[255&h]^e[++S],r[2]=f[y>>>24]<<24^f[g>>>16&255]<<16^f[h>>>8&255]<<8^f[255&d]^e[++S],r[a?1:3]=f[g>>>24]<<24^f[h>>>16&255]<<16^f[d>>>8&255]<<8^f[255&y]^e[++S]}function d(e){var t,r="AES-"+((e=e||{}).mode||"CBC").toUpperCase(),n=(t=e.decrypt?a.cipher.createDecipher(r,e.key):a.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var i=null;r instanceof a.util.ByteBuffer&&(i=r,r={}),(r=r||{}).output=i,r.iv=e,n.call(t,r)},t}},function(e,t,r){var a=r(0);a.pki=a.pki||{};var n=e.exports=a.pki.oids=a.oids=a.oids||{};function i(e,t){n[e]=t,n[t]=e}function s(e,t){n[e]=t}i("1.2.840.113549.1.1.1","rsaEncryption"),i("1.2.840.113549.1.1.4","md5WithRSAEncryption"),i("1.2.840.113549.1.1.5","sha1WithRSAEncryption"),i("1.2.840.113549.1.1.7","RSAES-OAEP"),i("1.2.840.113549.1.1.8","mgf1"),i("1.2.840.113549.1.1.9","pSpecified"),i("1.2.840.113549.1.1.10","RSASSA-PSS"),i("1.2.840.113549.1.1.11","sha256WithRSAEncryption"),i("1.2.840.113549.1.1.12","sha384WithRSAEncryption"),i("1.2.840.113549.1.1.13","sha512WithRSAEncryption"),i("1.3.101.112","EdDSA25519"),i("1.2.840.10040.4.3","dsa-with-sha1"),i("1.3.14.3.2.7","desCBC"),i("1.3.14.3.2.26","sha1"),i("1.3.14.3.2.29","sha1WithRSASignature"),i("2.16.840.1.101.3.4.2.1","sha256"),i("2.16.840.1.101.3.4.2.2","sha384"),i("2.16.840.1.101.3.4.2.3","sha512"),i("2.16.840.1.101.3.4.2.4","sha224"),i("2.16.840.1.101.3.4.2.5","sha512-224"),i("2.16.840.1.101.3.4.2.6","sha512-256"),i("1.2.840.113549.2.2","md2"),i("1.2.840.113549.2.5","md5"),i("1.2.840.113549.1.7.1","data"),i("1.2.840.113549.1.7.2","signedData"),i("1.2.840.113549.1.7.3","envelopedData"),i("1.2.840.113549.1.7.4","signedAndEnvelopedData"),i("1.2.840.113549.1.7.5","digestedData"),i("1.2.840.113549.1.7.6","encryptedData"),i("1.2.840.113549.1.9.1","emailAddress"),i("1.2.840.113549.1.9.2","unstructuredName"),i("1.2.840.113549.1.9.3","contentType"),i("1.2.840.113549.1.9.4","messageDigest"),i("1.2.840.113549.1.9.5","signingTime"),i("1.2.840.113549.1.9.6","counterSignature"),i("1.2.840.113549.1.9.7","challengePassword"),i("1.2.840.113549.1.9.8","unstructuredAddress"),i("1.2.840.113549.1.9.14","extensionRequest"),i("1.2.840.113549.1.9.20","friendlyName"),i("1.2.840.113549.1.9.21","localKeyId"),i("1.2.840.113549.1.9.22.1","x509Certificate"),i("1.2.840.113549.1.12.10.1.1","keyBag"),i("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag"),i("1.2.840.113549.1.12.10.1.3","certBag"),i("1.2.840.113549.1.12.10.1.4","crlBag"),i("1.2.840.113549.1.12.10.1.5","secretBag"),i("1.2.840.113549.1.12.10.1.6","safeContentsBag"),i("1.2.840.113549.1.5.13","pkcs5PBES2"),i("1.2.840.113549.1.5.12","pkcs5PBKDF2"),i("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4"),i("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4"),i("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC"),i("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC"),i("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC"),i("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC"),i("1.2.840.113549.2.7","hmacWithSHA1"),i("1.2.840.113549.2.8","hmacWithSHA224"),i("1.2.840.113549.2.9","hmacWithSHA256"),i("1.2.840.113549.2.10","hmacWithSHA384"),i("1.2.840.113549.2.11","hmacWithSHA512"),i("1.2.840.113549.3.7","des-EDE3-CBC"),i("2.16.840.1.101.3.4.1.2","aes128-CBC"),i("2.16.840.1.101.3.4.1.22","aes192-CBC"),i("2.16.840.1.101.3.4.1.42","aes256-CBC"),i("2.5.4.3","commonName"),i("2.5.4.4","surname"),i("2.5.4.5","serialNumber"),i("2.5.4.6","countryName"),i("2.5.4.7","localityName"),i("2.5.4.8","stateOrProvinceName"),i("2.5.4.9","streetAddress"),i("2.5.4.10","organizationName"),i("2.5.4.11","organizationalUnitName"),i("2.5.4.12","title"),i("2.5.4.13","description"),i("2.5.4.15","businessCategory"),i("2.5.4.17","postalCode"),i("2.5.4.42","givenName"),i("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName"),i("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName"),i("2.16.840.1.113730.1.1","nsCertType"),i("2.16.840.1.113730.1.13","nsComment"),s("2.5.29.1","authorityKeyIdentifier"),s("2.5.29.2","keyAttributes"),s("2.5.29.3","certificatePolicies"),s("2.5.29.4","keyUsageRestriction"),s("2.5.29.5","policyMapping"),s("2.5.29.6","subtreesConstraint"),s("2.5.29.7","subjectAltName"),s("2.5.29.8","issuerAltName"),s("2.5.29.9","subjectDirectoryAttributes"),s("2.5.29.10","basicConstraints"),s("2.5.29.11","nameConstraints"),s("2.5.29.12","policyConstraints"),s("2.5.29.13","basicConstraints"),i("2.5.29.14","subjectKeyIdentifier"),i("2.5.29.15","keyUsage"),s("2.5.29.16","privateKeyUsagePeriod"),i("2.5.29.17","subjectAltName"),i("2.5.29.18","issuerAltName"),i("2.5.29.19","basicConstraints"),s("2.5.29.20","cRLNumber"),s("2.5.29.21","cRLReason"),s("2.5.29.22","expirationDate"),s("2.5.29.23","instructionCode"),s("2.5.29.24","invalidityDate"),s("2.5.29.25","cRLDistributionPoints"),s("2.5.29.26","issuingDistributionPoint"),s("2.5.29.27","deltaCRLIndicator"),s("2.5.29.28","issuingDistributionPoint"),s("2.5.29.29","certificateIssuer"),s("2.5.29.30","nameConstraints"),i("2.5.29.31","cRLDistributionPoints"),i("2.5.29.32","certificatePolicies"),s("2.5.29.33","policyMappings"),s("2.5.29.34","policyConstraints"),i("2.5.29.35","authorityKeyIdentifier"),s("2.5.29.36","policyConstraints"),i("2.5.29.37","extKeyUsage"),s("2.5.29.46","freshestCRL"),s("2.5.29.54","inhibitAnyPolicy"),i("1.3.6.1.4.1.11129.2.4.2","timestampList"),i("1.3.6.1.5.5.7.1.1","authorityInfoAccess"),i("1.3.6.1.5.5.7.3.1","serverAuth"),i("1.3.6.1.5.5.7.3.2","clientAuth"),i("1.3.6.1.5.5.7.3.3","codeSigning"),i("1.3.6.1.5.5.7.3.4","emailProtection"),i("1.3.6.1.5.5.7.3.8","timeStamping")},function(e,t,r){var a=r(0);r(1);var n=e.exports=a.pem=a.pem||{};function i(e){for(var t=e.name+": ",r=[],a=function(e,t){return" "+t},n=0;n65&&-1!==s){var o=t[s];","===o?(++s,t=t.substr(0,s)+"\r\n "+t.substr(s)):t=t.substr(0,s)+"\r\n"+o+t.substr(s+1),i=n-s-1,s=-1,++n}else" "!==t[n]&&"\t"!==t[n]&&","!==t[n]||(s=n);return t}function s(e){return e.replace(/^\s+/,"")}n.encode=function(e,t){t=t||{};var r,n="-----BEGIN "+e.type+"-----\r\n";if(e.procType&&(n+=i(r={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]})),e.contentDomain&&(n+=i(r={name:"Content-Domain",values:[e.contentDomain]})),e.dekInfo&&(r={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters&&r.values.push(e.dekInfo.parameters),n+=i(r)),e.headers)for(var s=0;st.blockLength&&(t.start(),t.update(s.bytes()),s=t.digest()),r=a.util.createBuffer(),n=a.util.createBuffer(),u=s.length();for(c=0;c>>0,c>>>0];for(var u=n.fullMessageLength.length-1;u>=0;--u)n.fullMessageLength[u]+=c[1],c[1]=c[0]+(n.fullMessageLength[u]/4294967296>>>0),n.fullMessageLength[u]=n.fullMessageLength[u]>>>0,c[0]=c[1]/4294967296>>>0;return t.putBytes(i),o(e,r,t),(t.read>2048||0===t.length())&&t.compact(),n},n.digest=function(){var s=a.util.createBuffer();s.putBytes(t.bytes());var c,u=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize&n.blockLength-1;s.putBytes(i.substr(0,n.blockLength-u));for(var l=8*n.fullMessageLength[0],p=0;p>>0,s.putInt32(l>>>0),l=c>>>0;s.putInt32(l);var f={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};o(f,r,s);var h=a.util.createBuffer();return h.putInt32(f.h0),h.putInt32(f.h1),h.putInt32(f.h2),h.putInt32(f.h3),h.putInt32(f.h4),h},n};var i=null,s=!1;function o(e,t,r){for(var a,n,i,s,o,c,u,l=r.length();l>=64;){for(n=e.h0,i=e.h1,s=e.h2,o=e.h3,c=e.h4,u=0;u<16;++u)a=r.getInt32(),t[u]=a,a=(n<<5|n>>>27)+(o^i&(s^o))+c+1518500249+a,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=a;for(;u<20;++u)a=(a=t[u-3]^t[u-8]^t[u-14]^t[u-16])<<1|a>>>31,t[u]=a,a=(n<<5|n>>>27)+(o^i&(s^o))+c+1518500249+a,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=a;for(;u<32;++u)a=(a=t[u-3]^t[u-8]^t[u-14]^t[u-16])<<1|a>>>31,t[u]=a,a=(n<<5|n>>>27)+(i^s^o)+c+1859775393+a,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=a;for(;u<40;++u)a=(a=t[u-6]^t[u-16]^t[u-28]^t[u-32])<<2|a>>>30,t[u]=a,a=(n<<5|n>>>27)+(i^s^o)+c+1859775393+a,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=a;for(;u<60;++u)a=(a=t[u-6]^t[u-16]^t[u-28]^t[u-32])<<2|a>>>30,t[u]=a,a=(n<<5|n>>>27)+(i&s|o&(i^s))+c+2400959708+a,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=a;for(;u<80;++u)a=(a=t[u-6]^t[u-16]^t[u-28]^t[u-32])<<2|a>>>30,t[u]=a,a=(n<<5|n>>>27)+(i^s^o)+c+3395469782+a,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=a;e.h0=e.h0+n|0,e.h1=e.h1+i|0,e.h2=e.h2+s|0,e.h3=e.h3+o|0,e.h4=e.h4+c|0,l-=64}}},function(e,t,r){var a=r(0);function n(e,t){a.cipher.registerAlgorithm(e,(function(){return new a.des.Algorithm(e,t)}))}r(13),r(19),r(1),e.exports=a.des=a.des||{},a.des.startEncrypting=function(e,t,r,a){var n=d({key:e,output:r,decrypt:!1,mode:a||(null===t?"ECB":"CBC")});return n.start(t),n},a.des.createEncryptionCipher=function(e,t){return d({key:e,output:null,decrypt:!1,mode:t})},a.des.startDecrypting=function(e,t,r,a){var n=d({key:e,output:r,decrypt:!0,mode:a||(null===t?"ECB":"CBC")});return n.start(t),n},a.des.createDecryptionCipher=function(e,t){return d({key:e,output:null,decrypt:!0,mode:t})},a.des.Algorithm=function(e,t){var r=this;r.name=e,r.mode=new t({blockSize:8,cipher:{encrypt:function(e,t){return h(r._keys,e,t,!1)},decrypt:function(e,t){return h(r._keys,e,t,!0)}}}),r._init=!1},a.des.Algorithm.prototype.initialize=function(e){if(!this._init){var t=a.util.createBuffer(e.key);if(0===this.name.indexOf("3DES")&&24!==t.length())throw new Error("Invalid Triple-DES key size: "+8*t.length());this._keys=function(e){for(var t,r=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],a=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],n=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],i=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],s=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],o=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],c=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],u=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],l=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],p=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],f=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],h=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],d=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],y=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],g=e.length()>8?3:1,v=[],m=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],C=0,E=0;E>>4^T))<<4,S^=t=65535&((T^=t)>>>-16^S),S^=(t=858993459&(S>>>2^(T^=t<<-16)))<<2,S^=t=65535&((T^=t)>>>-16^S),S^=(t=1431655765&(S>>>1^(T^=t<<-16)))<<1,S^=t=16711935&((T^=t)>>>8^S),t=(S^=(t=1431655765&(S>>>1^(T^=t<<8)))<<1)<<8|(T^=t)>>>20&240,S=T<<24|T<<8&16711680|T>>>8&65280|T>>>24&240,T=t;for(var I=0;I>>26,T=T<<2|T>>>26):(S=S<<1|S>>>27,T=T<<1|T>>>27);var A=r[(S&=-15)>>>28]|a[S>>>24&15]|n[S>>>20&15]|i[S>>>16&15]|s[S>>>12&15]|o[S>>>8&15]|c[S>>>4&15],B=u[(T&=-15)>>>28]|l[T>>>24&15]|p[T>>>20&15]|f[T>>>16&15]|h[T>>>12&15]|d[T>>>8&15]|y[T>>>4&15];t=65535&(B>>>16^A),v[C++]=A^t,v[C++]=B^t<<16}}return v}(t),this._init=!0}},n("DES-ECB",a.cipher.modes.ecb),n("DES-CBC",a.cipher.modes.cbc),n("DES-CFB",a.cipher.modes.cfb),n("DES-OFB",a.cipher.modes.ofb),n("DES-CTR",a.cipher.modes.ctr),n("3DES-ECB",a.cipher.modes.ecb),n("3DES-CBC",a.cipher.modes.cbc),n("3DES-CFB",a.cipher.modes.cfb),n("3DES-OFB",a.cipher.modes.ofb),n("3DES-CTR",a.cipher.modes.ctr);var i=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],s=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],o=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],c=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],u=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],l=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],p=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],f=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function h(e,t,r,a){var n,h,d=32===e.length?3:9;n=3===d?a?[30,-2,-2]:[0,32,2]:a?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var y=t[0],g=t[1];y^=(h=252645135&(y>>>4^g))<<4,y^=(h=65535&(y>>>16^(g^=h)))<<16,y^=h=858993459&((g^=h)>>>2^y),y^=h=16711935&((g^=h<<2)>>>8^y),y=(y^=(h=1431655765&(y>>>1^(g^=h<<8)))<<1)<<1|y>>>31,g=(g^=h)<<1|g>>>31;for(var v=0;v>>4|g<<28)^e[E+1];h=y,y=g,g=h^(s[S>>>24&63]|c[S>>>16&63]|l[S>>>8&63]|f[63&S]|i[T>>>24&63]|o[T>>>16&63]|u[T>>>8&63]|p[63&T])}h=y,y=g,g=h}g=g>>>1|g<<31,g^=h=1431655765&((y=y>>>1|y<<31)>>>1^g),g^=(h=16711935&(g>>>8^(y^=h<<1)))<<8,g^=(h=858993459&(g>>>2^(y^=h)))<<2,g^=h=65535&((y^=h)>>>16^g),g^=h=252645135&((y^=h<<16)>>>4^g),y^=h<<4,r[0]=y,r[1]=g}function d(e){var t,r="DES-"+((e=e||{}).mode||"CBC").toUpperCase(),n=(t=e.decrypt?a.cipher.createDecipher(r,e.key):a.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var i=null;r instanceof a.util.ByteBuffer&&(i=r,r={}),(r=r||{}).output=i,r.iv=e,n.call(t,r)},t}},function(e,t,r){var a=r(0);if(r(3),r(12),r(6),r(26),r(27),r(2),r(1),void 0===n)var n=a.jsbn.BigInteger;var i=a.util.isNodejs?r(16):null,s=a.asn1,o=a.util;a.pki=a.pki||{},e.exports=a.pki.rsa=a.rsa=a.rsa||{};var c=a.pki,u=[6,4,2,4,2,4,6,2],l={name:"PrivateKeyInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},p={name:"RSAPrivateKey",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},f={name:"RSAPublicKey",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},h=a.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:s.Class.UNIVERSAL,type:s.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},d={name:"DigestInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:s.Class.UNIVERSAL,type:s.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},y=function(e){var t;if(!(e.algorithm in c.oids)){var r=new Error("Unknown message digest algorithm.");throw r.algorithm=e.algorithm,r}t=c.oids[e.algorithm];var a=s.oidToDer(t).getBytes(),n=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[]),i=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[]);i.value.push(s.create(s.Class.UNIVERSAL,s.Type.OID,!1,a)),i.value.push(s.create(s.Class.UNIVERSAL,s.Type.NULL,!1,""));var o=s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,e.digest().getBytes());return n.value.push(i),n.value.push(o),s.toDer(n).getBytes()},g=function(e,t,r){if(r)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);var i;t.dP||(t.dP=t.d.mod(t.p.subtract(n.ONE))),t.dQ||(t.dQ=t.d.mod(t.q.subtract(n.ONE))),t.qInv||(t.qInv=t.q.modInverse(t.p));do{i=new n(a.util.bytesToHex(a.random.getBytes(t.n.bitLength()/8)),16)}while(i.compareTo(t.n)>=0||!i.gcd(t.n).equals(n.ONE));for(var s=(e=e.multiply(i.modPow(t.e,t.n)).mod(t.n)).mod(t.p).modPow(t.dP,t.p),o=e.mod(t.q).modPow(t.dQ,t.q);s.compareTo(o)<0;)s=s.add(t.p);var c=s.subtract(o).multiply(t.qInv).mod(t.p).multiply(t.q).add(o);return c=c.multiply(i.modInverse(t.n)).mod(t.n)};function v(e,t,r){var n=a.util.createBuffer(),i=Math.ceil(t.n.bitLength()/8);if(e.length>i-11){var s=new Error("Message is too long for PKCS#1 v1.5 padding.");throw s.length=e.length,s.max=i-11,s}n.putByte(0),n.putByte(r);var o,c=i-3-e.length;if(0===r||1===r){o=0===r?0:255;for(var u=0;u0;){var l=0,p=a.random.getBytes(c);for(u=0;u1;){if(255!==s.getByte()){--s.read;break}++u}else if(2===c)for(u=0;s.length()>1;){if(0===s.getByte()){--s.read;break}++u}if(0!==s.getByte()||u!==i-3-s.length())throw new Error("Encryption block is invalid.");return s.getBytes()}function C(e,t,r){"function"==typeof t&&(r=t,t={});var i={algorithm:{name:(t=t||{}).algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};function s(){o(e.pBits,(function(t,a){return t?r(t):(e.p=a,null!==e.q?u(t,e.q):void o(e.qBits,u))}))}function o(e,t){a.prime.generateProbablePrime(e,i,t)}function u(t,a){if(t)return r(t);if(e.q=a,e.p.compareTo(e.q)<0){var i=e.p;e.p=e.q,e.q=i}if(0!==e.p.subtract(n.ONE).gcd(e.e).compareTo(n.ONE))return e.p=null,void s();if(0!==e.q.subtract(n.ONE).gcd(e.e).compareTo(n.ONE))return e.q=null,void o(e.qBits,u);if(e.p1=e.p.subtract(n.ONE),e.q1=e.q.subtract(n.ONE),e.phi=e.p1.multiply(e.q1),0!==e.phi.gcd(e.e).compareTo(n.ONE))return e.p=e.q=null,void s();if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits)return e.q=null,void o(e.qBits,u);var l=e.e.modInverse(e.phi);e.keys={privateKey:c.rsa.setPrivateKey(e.n,e.e,l,e.p,e.q,l.mod(e.p1),l.mod(e.q1),e.q.modInverse(e.p)),publicKey:c.rsa.setPublicKey(e.n,e.e)},r(null,e.keys)}"prng"in t&&(i.prng=t.prng),s()}function E(e){var t=e.toString(16);t[0]>="8"&&(t="00"+t);var r=a.util.hexToBytes(t);return r.length>1&&(0===r.charCodeAt(0)&&0==(128&r.charCodeAt(1))||255===r.charCodeAt(0)&&128==(128&r.charCodeAt(1)))?r.substr(1):r}function S(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}function T(e){return a.util.isNodejs&&"function"==typeof i[e]}function I(e){return void 0!==o.globalScope&&"object"==typeof o.globalScope.crypto&&"object"==typeof o.globalScope.crypto.subtle&&"function"==typeof o.globalScope.crypto.subtle[e]}function A(e){return void 0!==o.globalScope&&"object"==typeof o.globalScope.msCrypto&&"object"==typeof o.globalScope.msCrypto.subtle&&"function"==typeof o.globalScope.msCrypto.subtle[e]}function B(e){for(var t=a.util.hexToBytes(e.toString(16)),r=new Uint8Array(t.length),n=0;n0;)l.putByte(0),--p;return l.putBytes(a.util.hexToBytes(u)),l.getBytes()},c.rsa.decrypt=function(e,t,r,i){var s=Math.ceil(t.n.bitLength()/8);if(e.length!==s){var o=new Error("Encrypted message length is invalid.");throw o.length=e.length,o.expected=s,o}var c=new n(a.util.createBuffer(e).toHex(),16);if(c.compareTo(t.n)>=0)throw new Error("Encrypted message is invalid.");for(var u=g(c,t,r).toString(16),l=a.util.createBuffer(),p=s-Math.ceil(u.length/2);p>0;)l.putByte(0),--p;return l.putBytes(a.util.hexToBytes(u)),!1!==i?m(l.getBytes(),t,r):l.getBytes()},c.rsa.createKeyPairGenerationState=function(e,t,r){"string"==typeof e&&(e=parseInt(e,10)),e=e||2048;var i,s=(r=r||{}).prng||a.random,o={nextBytes:function(e){for(var t=s.getBytesSync(e.length),r=0;r>1,pBits:e-(e>>1),pqState:0,num:null,keys:null}).e.fromInt(i.eInt),i},c.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var r=new n(null);r.fromInt(30);for(var a,i=0,s=function(e,t){return e|t},o=+new Date,l=0;null===e.keys&&(t<=0||lp?e.pqState=0:e.num.isProbablePrime(S(e.num.bitLength()))?++e.pqState:e.num.dAddOffset(u[i++%8],0):2===e.pqState?e.pqState=0===e.num.subtract(n.ONE).gcd(e.e).compareTo(n.ONE)?3:0:3===e.pqState&&(e.pqState=0,null===e.p?e.p=e.num:e.q=e.num,null!==e.p&&null!==e.q&&++e.state,e.num=null)}else if(1===e.state)e.p.compareTo(e.q)<0&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(2===e.state)e.p1=e.p.subtract(n.ONE),e.q1=e.q.subtract(n.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(3===e.state)0===e.phi.gcd(e.e).compareTo(n.ONE)?++e.state:(e.p=null,e.q=null,e.state=0);else if(4===e.state)e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits?++e.state:(e.q=null,e.state=0);else if(5===e.state){var h=e.e.modInverse(e.phi);e.keys={privateKey:c.rsa.setPrivateKey(e.n,e.e,h,e.p,e.q,h.mod(e.p1),h.mod(e.q1),e.q.modInverse(e.p)),publicKey:c.rsa.setPublicKey(e.n,e.e)}}l+=(a=+new Date)-o,o=a}return null!==e.keys},c.rsa.generateKeyPair=function(e,t,r,n){if(1===arguments.length?"object"==typeof e?(r=e,e=void 0):"function"==typeof e&&(n=e,e=void 0):2===arguments.length?"number"==typeof e?"function"==typeof t?(n=t,t=void 0):"number"!=typeof t&&(r=t,t=void 0):(r=e,n=t,e=void 0,t=void 0):3===arguments.length&&("number"==typeof t?"function"==typeof r&&(n=r,r=void 0):(n=r,r=t,t=void 0)),r=r||{},void 0===e&&(e=r.bits||2048),void 0===t&&(t=r.e||65537),!a.options.usePureJavaScript&&!r.prng&&e>=256&&e<=16384&&(65537===t||3===t))if(n){if(T("generateKeyPair"))return i.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},(function(e,t,r){if(e)return n(e);n(null,{privateKey:c.privateKeyFromPem(r),publicKey:c.publicKeyFromPem(t)})}));if(I("generateKey")&&I("exportKey"))return o.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:B(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then((function(e){return o.globalScope.crypto.subtle.exportKey("pkcs8",e.privateKey)})).then(void 0,(function(e){n(e)})).then((function(e){if(e){var t=c.privateKeyFromAsn1(s.fromDer(a.util.createBuffer(e)));n(null,{privateKey:t,publicKey:c.setRsaPublicKey(t.n,t.e)})}}));if(A("generateKey")&&A("exportKey")){var u=o.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:B(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);return u.oncomplete=function(e){var t=e.target.result,r=o.globalScope.msCrypto.subtle.exportKey("pkcs8",t.privateKey);r.oncomplete=function(e){var t=e.target.result,r=c.privateKeyFromAsn1(s.fromDer(a.util.createBuffer(t)));n(null,{privateKey:r,publicKey:c.setRsaPublicKey(r.n,r.e)})},r.onerror=function(e){n(e)}},void(u.onerror=function(e){n(e)})}}else if(T("generateKeyPairSync")){var l=i.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:c.privateKeyFromPem(l.privateKey),publicKey:c.publicKeyFromPem(l.publicKey)}}var p=c.rsa.createKeyPairGenerationState(e,t,r);if(!n)return c.rsa.stepKeyPairGenerationState(p,0),p.keys;C(p,r,n)},c.setRsaPublicKey=c.rsa.setPublicKey=function(e,t){var r={n:e,e:t,encrypt:function(e,t,n){if("string"==typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5"),"RSAES-PKCS1-V1_5"===t)t={encode:function(e,t,r){return v(e,t,2).getBytes()}};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={encode:function(e,t){return a.pkcs1.encode_rsa_oaep(t,e,n)}};else if(-1!==["RAW","NONE","NULL",null].indexOf(t))t={encode:function(e){return e}};else if("string"==typeof t)throw new Error('Unsupported encryption scheme: "'+t+'".');var i=t.encode(e,r,!0);return c.rsa.encrypt(i,r,!0)},verify:function(e,t,n,i){"string"==typeof n?n=n.toUpperCase():void 0===n&&(n="RSASSA-PKCS1-V1_5"),void 0===i&&(i={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in i||(i._parseAllDigestBytes=!0),"RSASSA-PKCS1-V1_5"===n?n={verify:function(e,t){t=m(t,r,!0);var n=s.fromDer(t,{parseAllBytes:i._parseAllDigestBytes}),o={},c=[];if(!s.validate(n,d,o,c))throw(u=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.")).errors=c,u;var u,l=s.derToOid(o.algorithmIdentifier);if(l!==a.oids.md2&&l!==a.oids.md5&&l!==a.oids.sha1&&l!==a.oids.sha224&&l!==a.oids.sha256&&l!==a.oids.sha384&&l!==a.oids.sha512&&l!==a.oids["sha512-224"]&&l!==a.oids["sha512-256"])throw(u=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.")).oid=l,u;if((l===a.oids.md2||l===a.oids.md5)&&!("parameters"in o))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifier NULL parameters.");return e===o.digest}}:"NONE"!==n&&"NULL"!==n&&null!==n||(n={verify:function(e,t){return e===(t=m(t,r,!0))}});var o=c.rsa.decrypt(t,r,!0,!1);return n.verify(e,o,r.n.bitLength())}};return r},c.setRsaPrivateKey=c.rsa.setPrivateKey=function(e,t,r,n,i,s,o,u){var l={n:e,e:t,d:r,p:n,q:i,dP:s,dQ:o,qInv:u,decrypt:function(e,t,r){"string"==typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5");var n=c.rsa.decrypt(e,l,!1,!1);if("RSAES-PKCS1-V1_5"===t)t={decode:m};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={decode:function(e,t){return a.pkcs1.decode_rsa_oaep(t,e,r)}};else{if(-1===["RAW","NONE","NULL",null].indexOf(t))throw new Error('Unsupported encryption scheme: "'+t+'".');t={decode:function(e){return e}}}return t.decode(n,l,!1)},sign:function(e,t){var r=!1;"string"==typeof t&&(t=t.toUpperCase()),void 0===t||"RSASSA-PKCS1-V1_5"===t?(t={encode:y},r=1):"NONE"!==t&&"NULL"!==t&&null!==t||(t={encode:function(){return e}},r=1);var a=t.encode(e,l.n.bitLength());return c.rsa.encrypt(a,l,r)}};return l},c.wrapRsaPrivateKey=function(e){return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,s.integerToDer(0).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(c.oids.rsaEncryption).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.NULL,!1,"")]),s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,s.toDer(e).getBytes())])},c.privateKeyFromAsn1=function(e){var t,r,i,o,u,f,h,d,y={},g=[];if(s.validate(e,l,y,g)&&(e=s.fromDer(a.util.createBuffer(y.privateKey))),y={},g=[],!s.validate(e,p,y,g)){var v=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw v.errors=g,v}return t=a.util.createBuffer(y.privateKeyModulus).toHex(),r=a.util.createBuffer(y.privateKeyPublicExponent).toHex(),i=a.util.createBuffer(y.privateKeyPrivateExponent).toHex(),o=a.util.createBuffer(y.privateKeyPrime1).toHex(),u=a.util.createBuffer(y.privateKeyPrime2).toHex(),f=a.util.createBuffer(y.privateKeyExponent1).toHex(),h=a.util.createBuffer(y.privateKeyExponent2).toHex(),d=a.util.createBuffer(y.privateKeyCoefficient).toHex(),c.setRsaPrivateKey(new n(t,16),new n(r,16),new n(i,16),new n(o,16),new n(u,16),new n(f,16),new n(h,16),new n(d,16))},c.privateKeyToAsn1=c.privateKeyToRSAPrivateKey=function(e){return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,s.integerToDer(0).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,E(e.n)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,E(e.e)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,E(e.d)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,E(e.p)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,E(e.q)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,E(e.dP)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,E(e.dQ)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,E(e.qInv))])},c.publicKeyFromAsn1=function(e){var t={},r=[];if(s.validate(e,h,t,r)){var i,o=s.derToOid(t.publicKeyOid);if(o!==c.oids.rsaEncryption)throw(i=new Error("Cannot read public key. Unknown OID.")).oid=o,i;e=t.rsaPublicKey}if(r=[],!s.validate(e,f,t,r))throw(i=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.")).errors=r,i;var u=a.util.createBuffer(t.publicKeyModulus).toHex(),l=a.util.createBuffer(t.publicKeyExponent).toHex();return c.setRsaPublicKey(new n(u,16),new n(l,16))},c.publicKeyToAsn1=c.publicKeyToSubjectPublicKeyInfo=function(e){return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(c.oids.rsaEncryption).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.NULL,!1,"")]),s.create(s.Class.UNIVERSAL,s.Type.BITSTRING,!1,[c.publicKeyToRSAPublicKey(e)])])},c.publicKeyToRSAPublicKey=function(e){return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,E(e.n)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,E(e.e))])}},function(e,t,r){var a,n=r(0);e.exports=n.jsbn=n.jsbn||{};function i(e,t,r){this.data=[],null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function s(){return new i(null)}function o(e,t,r,a,n,i){for(var s=16383&t,o=t>>14;--i>=0;){var c=16383&this.data[e],u=this.data[e++]>>14,l=o*c+u*s;n=((c=s*c+((16383&l)<<14)+r.data[a]+n)>>28)+(l>>14)+o*u,r.data[a++]=268435455&c}return n}n.jsbn.BigInteger=i,"undefined"==typeof navigator?(i.prototype.am=o,a=28):"Microsoft Internet Explorer"==navigator.appName?(i.prototype.am=function(e,t,r,a,n,i){for(var s=32767&t,o=t>>15;--i>=0;){var c=32767&this.data[e],u=this.data[e++]>>15,l=o*c+u*s;n=((c=s*c+((32767&l)<<15)+r.data[a]+(1073741823&n))>>>30)+(l>>>15)+o*u+(n>>>30),r.data[a++]=1073741823&c}return n},a=30):"Netscape"!=navigator.appName?(i.prototype.am=function(e,t,r,a,n,i){for(;--i>=0;){var s=t*this.data[e++]+r.data[a]+n;n=Math.floor(s/67108864),r.data[a++]=67108863&s}return n},a=26):(i.prototype.am=o,a=28),i.prototype.DB=a,i.prototype.DM=(1<>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function y(e){this.m=e}function g(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<>=16,t+=16),0==(255&e)&&(e>>=8,t+=8),0==(15&e)&&(e>>=4,t+=4),0==(3&e)&&(e>>=2,t+=2),0==(1&e)&&++t,t}function T(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function I(){}function A(e){return e}function B(e){this.r2=s(),this.q3=s(),i.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}y.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},y.prototype.revert=function(e){return e},y.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},y.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},y.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},g.prototype.convert=function(e){var t=s();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(i.ZERO)>0&&this.m.subTo(t,t),t},g.prototype.revert=function(e){var t=s();return e.copyTo(t),this.reduce(t),t},g.prototype.reduce=function(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(r=t+this.m.t,e.data[r]+=this.m.am(0,a,e,t,0,this.m.t);e.data[r]>=e.DV;)e.data[r]-=e.DV,e.data[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},g.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},g.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},i.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s},i.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+this.DV:this.t=0},i.prototype.fromString=function(e,t){var r;if(16==t)r=4;else if(8==t)r=3;else if(256==t)r=8;else if(2==t)r=1;else if(32==t)r=5;else{if(4!=t)return void this.fromRadix(e,t);r=2}this.t=0,this.s=0;for(var a=e.length,n=!1,s=0;--a>=0;){var o=8==r?255&e[a]:f(e,a);o<0?"-"==e.charAt(a)&&(n=!0):(n=!1,0==s?this.data[this.t++]=o:s+r>this.DB?(this.data[this.t-1]|=(o&(1<>this.DB-s):this.data[this.t-1]|=o<=this.DB&&(s-=this.DB))}8==r&&0!=(128&e[0])&&(this.s=-1,s>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==e;)--this.t},i.prototype.dlShiftTo=function(e,t){var r;for(r=this.t-1;r>=0;--r)t.data[r+e]=this.data[r];for(r=e-1;r>=0;--r)t.data[r]=0;t.t=this.t+e,t.s=this.s},i.prototype.drShiftTo=function(e,t){for(var r=e;r=0;--r)t.data[r+s+1]=this.data[r]>>n|o,o=(this.data[r]&i)<=0;--r)t.data[r]=0;t.data[s]=o,t.t=this.t+s+1,t.s=this.s,t.clamp()},i.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var a=e%this.DB,n=this.DB-a,i=(1<>a;for(var s=r+1;s>a;a>0&&(t.data[this.t-r-1]|=(this.s&i)<>=this.DB;if(e.t>=this.DB;a+=this.s}else{for(a+=this.s;r>=this.DB;a-=e.s}t.s=a<0?-1:0,a<-1?t.data[r++]=this.DV+a:a>0&&(t.data[r++]=a),t.t=r,t.clamp()},i.prototype.multiplyTo=function(e,t){var r=this.abs(),a=e.abs(),n=r.t;for(t.t=n+a.t;--n>=0;)t.data[n]=0;for(n=0;n=0;)e.data[r]=0;for(r=0;r=t.DV&&(e.data[r+t.t]-=t.DV,e.data[r+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(r,t.data[r],e,2*r,0,1)),e.s=0,e.clamp()},i.prototype.divRemTo=function(e,t,r){var a=e.abs();if(!(a.t<=0)){var n=this.abs();if(n.t0?(a.lShiftTo(l,o),n.lShiftTo(l,r)):(a.copyTo(o),n.copyTo(r));var p=o.t,f=o.data[p-1];if(0!=f){var h=f*(1<1?o.data[p-2]>>this.F2:0),y=this.FV/h,g=(1<=0&&(r.data[r.t++]=1,r.subTo(E,r)),i.ONE.dlShiftTo(p,E),E.subTo(o,o);o.t=0;){var S=r.data[--m]==f?this.DM:Math.floor(r.data[m]*y+(r.data[m-1]+v)*g);if((r.data[m]+=o.am(0,S,r,C,0,p))0&&r.rShiftTo(l,r),c<0&&i.ZERO.subTo(r,r)}}},i.prototype.invDigit=function(){if(this.t<1)return 0;var e=this.data[0];if(0==(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},i.prototype.isEven=function(){return 0==(this.t>0?1&this.data[0]:this.s)},i.prototype.exp=function(e,t){if(e>4294967295||e<1)return i.ONE;var r=s(),a=s(),n=t.convert(this),o=d(e)-1;for(n.copyTo(r);--o>=0;)if(t.sqrTo(r,a),(e&1<0)t.mulTo(a,n,r);else{var c=r;r=a,a=c}return t.revert(r)},i.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,a=(1<0)for(o>o)>0&&(n=!0,i=p(r));s>=0;)o>(o+=this.DB-t)):(r=this.data[s]>>(o-=t)&a,o<=0&&(o+=this.DB,--s)),r>0&&(n=!0),n&&(i+=p(r));return n?i:"0"},i.prototype.negate=function(){var e=s();return i.ZERO.subTo(this,e),e},i.prototype.abs=function(){return this.s<0?this.negate():this},i.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this.data[r]-e.data[r]))return t;return 0},i.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+d(this.data[this.t-1]^this.s&this.DM)},i.prototype.mod=function(e){var t=s();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(i.ZERO)>0&&e.subTo(t,t),t},i.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new y(t):new g(t),this.exp(e,r)},i.ZERO=h(0),i.ONE=h(1),I.prototype.convert=A,I.prototype.revert=A,I.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},I.prototype.sqrTo=function(e,t){e.squareTo(t)},B.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=s();return e.copyTo(t),this.reduce(t),t},B.prototype.revert=function(e){return e},B.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},B.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},B.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var b=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],N=(1<<26)/b[b.length-1];i.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},i.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),a=h(r),n=s(),i=s(),o="";for(this.divRemTo(a,n,i);n.signum()>0;)o=(r+i.intValue()).toString(e).substr(1)+o,n.divRemTo(a,n,i);return i.intValue().toString(e)+o},i.prototype.fromRadix=function(e,t){this.fromInt(0),null==t&&(t=10);for(var r=this.chunkSize(t),a=Math.pow(t,r),n=!1,s=0,o=0,c=0;c=r&&(this.dMultiply(a),this.dAddOffset(o,0),s=0,o=0))}s>0&&(this.dMultiply(Math.pow(t,s)),this.dAddOffset(o,0)),n&&i.ZERO.subTo(this,this)},i.prototype.fromNumber=function(e,t,r){if("number"==typeof t)if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(i.ONE.shiftLeft(e-1),m,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(i.ONE.shiftLeft(e-1),this);else{var a=new Array,n=7&e;a.length=1+(e>>3),t.nextBytes(a),n>0?a[0]&=(1<>=this.DB;if(e.t>=this.DB;a+=this.s}else{for(a+=this.s;r>=this.DB;a+=e.s}t.s=a<0?-1:0,a>0?t.data[r++]=a:a<-1&&(t.data[r++]=this.DV+a),t.t=r,t.clamp()},i.prototype.dMultiply=function(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},i.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this.data[this.t++]=0;for(this.data[t]+=e;this.data[t]>=this.DV;)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}},i.prototype.multiplyLowerTo=function(e,t,r){var a,n=Math.min(this.t+e.t,t);for(r.s=0,r.t=n;n>0;)r.data[--n]=0;for(a=r.t-this.t;n=0;)r.data[a]=0;for(a=Math.max(t-this.t,0);a0)if(0==t)r=this.data[0]%e;else for(var a=this.t-1;a>=0;--a)r=(t*r+this.data[a])%e;return r},i.prototype.millerRabin=function(e){var t=this.subtract(i.ONE),r=t.getLowestSetBit();if(r<=0)return!1;for(var a,n=t.shiftRight(r),s={nextBytes:function(e){for(var t=0;t=0);var c=a.modPow(n,this);if(0!=c.compareTo(i.ONE)&&0!=c.compareTo(t)){for(var u=1;u++>24},i.prototype.shortValue=function(){return 0==this.t?this.s:this.data[0]<<16>>16},i.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this.data[0]<=0?0:1},i.prototype.toByteArray=function(){var e=this.t,t=new Array;t[0]=this.s;var r,a=this.DB-e*this.DB%8,n=0;if(e-- >0)for(a>a)!=(this.s&this.DM)>>a&&(t[n++]=r|this.s<=0;)a<8?(r=(this.data[e]&(1<>(a+=this.DB-8)):(r=this.data[e]>>(a-=8)&255,a<=0&&(a+=this.DB,--e)),0!=(128&r)&&(r|=-256),0==n&&(128&this.s)!=(128&r)&&++n,(n>0||r!=this.s)&&(t[n++]=r);return t},i.prototype.equals=function(e){return 0==this.compareTo(e)},i.prototype.min=function(e){return this.compareTo(e)<0?this:e},i.prototype.max=function(e){return this.compareTo(e)>0?this:e},i.prototype.and=function(e){var t=s();return this.bitwiseTo(e,v,t),t},i.prototype.or=function(e){var t=s();return this.bitwiseTo(e,m,t),t},i.prototype.xor=function(e){var t=s();return this.bitwiseTo(e,C,t),t},i.prototype.andNot=function(e){var t=s();return this.bitwiseTo(e,E,t),t},i.prototype.not=function(){for(var e=s(),t=0;t=this.t?0!=this.s:0!=(this.data[t]&1<1){var p=s();for(a.sqrTo(o[1],p);c<=l;)o[c]=s(),a.mulTo(p,o[c-2],o[c]),c+=2}var f,v,m=e.t-1,C=!0,E=s();for(n=d(e.data[m])-1;m>=0;){for(n>=u?f=e.data[m]>>n-u&l:(f=(e.data[m]&(1<0&&(f|=e.data[m-1]>>this.DB+n-u)),c=r;0==(1&f);)f>>=1,--c;if((n-=c)<0&&(n+=this.DB,--m),C)o[f].copyTo(i),C=!1;else{for(;c>1;)a.sqrTo(i,E),a.sqrTo(E,i),c-=2;c>0?a.sqrTo(i,E):(v=i,i=E,E=v),a.mulTo(E,o[f],i)}for(;m>=0&&0==(e.data[m]&1<=0?(r.subTo(a,r),t&&n.subTo(o,n),s.subTo(c,s)):(a.subTo(r,a),t&&o.subTo(n,o),c.subTo(s,c))}return 0!=a.compareTo(i.ONE)?i.ZERO:c.compareTo(e)>=0?c.subtract(e):c.signum()<0?(c.addTo(e,c),c.signum()<0?c.add(e):c):c},i.prototype.pow=function(e){return this.exp(e,new I)},i.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var a=t;t=r,r=a}var n=t.getLowestSetBit(),i=r.getLowestSetBit();if(i<0)return t;for(n0&&(t.rShiftTo(i,t),r.rShiftTo(i,r));t.signum()>0;)(n=t.getLowestSetBit())>0&&t.rShiftTo(n,t),(n=r.getLowestSetBit())>0&&r.rShiftTo(n,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return i>0&&r.lShiftTo(i,r),r},i.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r.data[0]<=b[b.length-1]){for(t=0;t>>0,o>>>0];for(var c=n.fullMessageLength.length-1;c>=0;--c)n.fullMessageLength[c]+=o[1],o[1]=o[0]+(n.fullMessageLength[c]/4294967296>>>0),n.fullMessageLength[c]=n.fullMessageLength[c]>>>0,o[0]=o[1]/4294967296>>>0;return t.putBytes(i),l(e,r,t),(t.read>2048||0===t.length())&&t.compact(),n},n.digest=function(){var s=a.util.createBuffer();s.putBytes(t.bytes());var o=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize&n.blockLength-1;s.putBytes(i.substr(0,n.blockLength-o));for(var c,u=0,p=n.fullMessageLength.length-1;p>=0;--p)u=(c=8*n.fullMessageLength[p]+u)/4294967296>>>0,s.putInt32Le(c>>>0);var f={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3};l(f,r,s);var h=a.util.createBuffer();return h.putInt32Le(f.h0),h.putInt32Le(f.h1),h.putInt32Le(f.h2),h.putInt32Le(f.h3),h},n};var i=null,s=null,o=null,c=null,u=!1;function l(e,t,r){for(var a,n,i,u,l,p,f,h=r.length();h>=64;){for(n=e.h0,i=e.h1,u=e.h2,l=e.h3,f=0;f<16;++f)t[f]=r.getInt32Le(),a=n+(l^i&(u^l))+c[f]+t[f],n=l,l=u,u=i,i+=a<<(p=o[f])|a>>>32-p;for(;f<32;++f)a=n+(u^l&(i^u))+c[f]+t[s[f]],n=l,l=u,u=i,i+=a<<(p=o[f])|a>>>32-p;for(;f<48;++f)a=n+(i^u^l)+c[f]+t[s[f]],n=l,l=u,u=i,i+=a<<(p=o[f])|a>>>32-p;for(;f<64;++f)a=n+(u^(i|~l))+c[f]+t[s[f]],n=l,l=u,u=i,i+=a<<(p=o[f])|a>>>32-p;e.h0=e.h0+n|0,e.h1=e.h1+i|0,e.h2=e.h2+u|0,e.h3=e.h3+l|0,h-=64}}},function(e,t,r){var a=r(0);r(8),r(4),r(1);var n,i=a.pkcs5=a.pkcs5||{};a.util.isNodejs&&!a.options.usePureJavaScript&&(n=r(16)),e.exports=a.pbkdf2=i.pbkdf2=function(e,t,r,i,s,o){if("function"==typeof s&&(o=s,s=null),a.util.isNodejs&&!a.options.usePureJavaScript&&n.pbkdf2&&(null===s||"object"!=typeof s)&&(n.pbkdf2Sync.length>4||!s||"sha1"===s))return"string"!=typeof s&&(s="sha1"),e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),o?4===n.pbkdf2Sync.length?n.pbkdf2(e,t,r,i,(function(e,t){if(e)return o(e);o(null,t.toString("binary"))})):n.pbkdf2(e,t,r,i,s,(function(e,t){if(e)return o(e);o(null,t.toString("binary"))})):4===n.pbkdf2Sync.length?n.pbkdf2Sync(e,t,r,i).toString("binary"):n.pbkdf2Sync(e,t,r,i,s).toString("binary");if(null==s&&(s="sha1"),"string"==typeof s){if(!(s in a.md.algorithms))throw new Error("Unknown hash algorithm: "+s);s=a.md[s].create()}var c=s.digestLength;if(i>4294967295*c){var u=new Error("Derived key is too long.");if(o)return o(u);throw u}var l=Math.ceil(i/c),p=i-(l-1)*c,f=a.hmac.create();f.start(s,e);var h,d,y,g="";if(!o){for(var v=1;v<=l;++v){f.start(null,null),f.update(t),f.update(a.util.int32ToBytes(v)),h=y=f.digest().getBytes();for(var m=2;m<=r;++m)f.start(null,null),f.update(y),d=f.digest().getBytes(),h=a.util.xorBytes(h,d,c),y=d;g+=vl)return o(null,g);f.start(null,null),f.update(t),f.update(a.util.int32ToBytes(v)),h=y=f.digest().getBytes(),m=2,E()}function E(){if(m<=r)return f.start(null,null),f.update(y),d=f.digest().getBytes(),h=a.util.xorBytes(h,d,c),y=d,++m,a.util.setImmediate(E);g+=v128)throw new Error('Invalid "nsComment" content.');e.value=n.create(n.Class.UNIVERSAL,n.Type.IA5STRING,!1,e.comment)}else if("subjectKeyIdentifier"===e.name&&t.cert){var h=t.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=h.toHex(),e.value=n.create(n.Class.UNIVERSAL,n.Type.OCTETSTRING,!1,h.getBytes())}else if("authorityKeyIdentifier"===e.name&&t.cert){e.value=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[]);l=e.value.value;if(e.keyIdentifier){var d=!0===e.keyIdentifier?t.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;l.push(n.create(n.Class.CONTEXT_SPECIFIC,0,!1,d))}if(e.authorityCertIssuer){var y=[n.create(n.Class.CONTEXT_SPECIFIC,4,!0,[v(!0===e.authorityCertIssuer?t.cert.issuer:e.authorityCertIssuer)])];l.push(n.create(n.Class.CONTEXT_SPECIFIC,1,!0,y))}if(e.serialNumber){var g=a.util.hexToBytes(!0===e.serialNumber?t.cert.serialNumber:e.serialNumber);l.push(n.create(n.Class.CONTEXT_SPECIFIC,2,!1,g))}}else if("cRLDistributionPoints"===e.name){e.value=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[]);l=e.value.value;var m,C=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[]),E=n.create(n.Class.CONTEXT_SPECIFIC,0,!0,[]);for(f=0;f2)throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(p.length<2)throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(c.validity.notBefore=p[0],c.validity.notAfter=p[1],c.tbsCertificate=r.tbsCertificate,t){c.md=y({signatureOid:c.signatureOid,type:"certificate"});var f=n.toDer(c.tbsCertificate);c.md.update(f.getBytes())}var g=a.md.sha1.create(),v=n.toDer(r.certIssuer);g.update(v.getBytes()),c.issuer.getField=function(e){return h(c.issuer,e)},c.issuer.addField=function(e){m([e]),c.issuer.attributes.push(e)},c.issuer.attributes=i.RDNAttributesAsArray(r.certIssuer),r.certIssuerUniqueId&&(c.issuer.uniqueId=r.certIssuerUniqueId),c.issuer.hash=g.digest().toHex();var C=a.md.sha1.create(),E=n.toDer(r.certSubject);return C.update(E.getBytes()),c.subject.getField=function(e){return h(c.subject,e)},c.subject.addField=function(e){m([e]),c.subject.attributes.push(e)},c.subject.attributes=i.RDNAttributesAsArray(r.certSubject),r.certSubjectUniqueId&&(c.subject.uniqueId=r.certSubjectUniqueId),c.subject.hash=C.digest().toHex(),r.certExtensions?c.extensions=i.certificateExtensionsFromAsn1(r.certExtensions):c.extensions=[],c.publicKey=i.publicKeyFromAsn1(r.subjectPublicKeyInfo),c},i.certificateExtensionsFromAsn1=function(e){for(var t=[],r=0;r1&&(r=c.value.charCodeAt(1),i=c.value.length>2?c.value.charCodeAt(2):0),t.digitalSignature=128==(128&r),t.nonRepudiation=64==(64&r),t.keyEncipherment=32==(32&r),t.dataEncipherment=16==(16&r),t.keyAgreement=8==(8&r),t.keyCertSign=4==(4&r),t.cRLSign=2==(2&r),t.encipherOnly=1==(1&r),t.decipherOnly=128==(128&i)}else if("basicConstraints"===t.name){(c=n.fromDer(t.value)).value.length>0&&c.value[0].type===n.Type.BOOLEAN?t.cA=0!==c.value[0].value.charCodeAt(0):t.cA=!1;var o=null;c.value.length>0&&c.value[0].type===n.Type.INTEGER?o=c.value[0].value:c.value.length>1&&(o=c.value[1].value),null!==o&&(t.pathLenConstraint=n.derToInteger(o))}else if("extKeyUsage"===t.name)for(var c=n.fromDer(t.value),u=0;u1&&(r=c.value.charCodeAt(1)),t.client=128==(128&r),t.server=64==(64&r),t.email=32==(32&r),t.objsign=16==(16&r),t.reserved=8==(8&r),t.sslCA=4==(4&r),t.emailCA=2==(2&r),t.objCA=1==(1&r)}else if("subjectAltName"===t.name||"issuerAltName"===t.name){var p;t.altNames=[];c=n.fromDer(t.value);for(var f=0;f=T&&e0&&s.value.push(i.certificateExtensionsToAsn1(e.extensions)),s},i.getCertificationRequestInfo=function(e){return n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.INTEGER,!1,n.integerToDer(e.version).getBytes()),v(e.subject),i.publicKeyToAsn1(e.publicKey),S(e)])},i.distinguishedNameToAsn1=function(e){return v(e)},i.certificateToAsn1=function(e){var t=e.tbsCertificate||i.getTBSCertificate(e);return n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[t,n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.OID,!1,n.oidToDer(e.signatureOid).getBytes()),E(e.signatureOid,e.signatureParameters)]),n.create(n.Class.UNIVERSAL,n.Type.BITSTRING,!1,String.fromCharCode(0)+e.signature)])},i.certificateExtensionsToAsn1=function(e){var t=n.create(n.Class.CONTEXT_SPECIFIC,3,!0,[]),r=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[]);t.value.push(r);for(var a=0;al.validity.notAfter)&&(c={message:"Certificate is not valid yet or has expired.",error:i.certificateError.certificate_expired,notBefore:l.validity.notBefore,notAfter:l.validity.notAfter,now:s}),null===c){if(null===(p=t[0]||e.getIssuer(l))&&l.isIssuer(l)&&(f=!0,p=l),p){var h=p;a.util.isArray(h)||(h=[h]);for(var d=!1;!d&&h.length>0;){p=h.shift();try{d=p.verify(l)}catch(e){}}d||(c={message:"Certificate signature is invalid.",error:i.certificateError.bad_certificate})}null!==c||p&&!f||e.hasCertificate(l)||(c={message:"Certificate is not trusted.",error:i.certificateError.unknown_ca})}if(null===c&&p&&!l.isIssuer(p)&&(c={message:"Certificate issuer is invalid.",error:i.certificateError.bad_certificate}),null===c)for(var y={keyUsage:!0,basicConstraints:!0},g=0;null===c&&gm.pathLenConstraint&&(c={message:"Certificate basicConstraints pathLenConstraint violated.",error:i.certificateError.bad_certificate})}var E=null===c||c.error,S=r.verify?r.verify(E,u,n):E;if(!0!==S)throw!0===E&&(c={message:"The application rejected the certificate.",error:i.certificateError.bad_certificate}),(S||0===S)&&("object"!=typeof S||a.util.isArray(S)?"string"==typeof S&&(c.error=S):(S.message&&(c.message=S.message),S.error&&(c.error=S.error))),c;c=null,o=!1,++u}while(t.length>0);return!0}},function(e,t,r){var a=r(0);r(2),r(1),(e.exports=a.pss=a.pss||{}).create=function(e){3===arguments.length&&(e={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]});var t,r=e.md,n=e.mgf,i=r.digestLength,s=e.salt||null;if("string"==typeof s&&(s=a.util.createBuffer(s)),"saltLength"in e)t=e.saltLength;else{if(null===s)throw new Error("Salt length not specified or specific salt not given.");t=s.length()}if(null!==s&&s.length()!==t)throw new Error("Given salt length does not match length of given salt.");var o=e.prng||a.random,c={encode:function(e,c){var u,l,p=c-1,f=Math.ceil(p/8),h=e.digest().getBytes();if(f>8*f-p&255;return(E=String.fromCharCode(E.charCodeAt(0)&~S)+E.substr(1))+y+String.fromCharCode(188)},verify:function(e,s,o){var c,u=o-1,l=Math.ceil(u/8);if(s=s.substr(-l),l>8*l-u&255;if(0!=(f.charCodeAt(0)&d))throw new Error("Bits beyond keysize not zero as expected.");var y=n.generate(h,p),g="";for(c=0;c4){var r=e;e=a.util.createBuffer();for(var n=0;n0))return!0;for(var a=0;a0))return!0;for(var a=0;a0)return!1;var r=e.length(),a=e.at(r-1);return!(a>this.blockSize<<2)&&(e.truncate(a),!0)},n.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},n.cbc.prototype.start=function(e){if(null===e.iv){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else{if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=i(e.iv,this.blockSize),this._prev=this._iv.slice(0)}},n.cbc.prototype.encrypt=function(e,t,r){if(e.length()0))return!0;for(var a=0;a0))return!0;for(var a=0;a0)return!1;var r=e.length(),a=e.at(r-1);return!(a>this.blockSize<<2)&&(e.truncate(a),!0)},n.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=a.util.createBuffer(),this._partialBytes=0},n.cfb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=i(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},n.cfb.prototype.encrypt=function(e,t,r){var a=e.length();if(0===a)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&a>=this.blockSize)for(var n=0;n0&&(i=this.blockSize-i),this._partialOutput.clear();for(n=0;n0)e.read-=this.blockSize;else for(n=0;n0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=0}},n.cfb.prototype.decrypt=function(e,t,r){var a=e.length();if(0===a)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&a>=this.blockSize)for(var n=0;n0&&(i=this.blockSize-i),this._partialOutput.clear();for(n=0;n0)e.read-=this.blockSize;else for(n=0;n0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=0}},n.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=a.util.createBuffer(),this._partialBytes=0},n.ofb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=i(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},n.ofb.prototype.encrypt=function(e,t,r){var a=e.length();if(0===e.length())return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&a>=this.blockSize)for(var n=0;n0&&(i=this.blockSize-i),this._partialOutput.clear();for(n=0;n0)e.read-=this.blockSize;else for(n=0;n0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=0}},n.ofb.prototype.decrypt=n.ofb.prototype.encrypt,n.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=a.util.createBuffer(),this._partialBytes=0},n.ctr.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=i(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},n.ctr.prototype.encrypt=function(e,t,r){var a=e.length();if(0===a)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&a>=this.blockSize)for(var n=0;n0&&(i=this.blockSize-i),this._partialOutput.clear();for(n=0;n0&&(e.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=0}s(this._inBlock)},n.ctr.prototype.decrypt=n.ctr.prototype.encrypt,n.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=a.util.createBuffer(),this._partialBytes=0,this._R=3774873600},n.gcm.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");var t,r=a.util.createBuffer(e.iv);if(this._cipherLength=0,t="additionalData"in e?a.util.createBuffer(e.additionalData):a.util.createBuffer(),this._tagLength="tagLength"in e?e.tagLength:128,this._tag=null,e.decrypt&&(this._tag=a.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var n=r.length();if(12===n)this._j0=[r.getInt32(),r.getInt32(),r.getInt32(),1];else{for(this._j0=[0,0,0,0];r.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[r.getInt32(),r.getInt32(),r.getInt32(),r.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(o(8*n)))}this._inBlock=this._j0.slice(0),s(this._inBlock),this._partialBytes=0,t=a.util.createBuffer(t),this._aDataLength=o(8*t.length());var i=t.length()%this.blockSize;for(i&&t.fillWithByte(0,this.blockSize-i),this._s=[0,0,0,0];t.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()])},n.gcm.prototype.encrypt=function(e,t,r){var a=e.length();if(0===a)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&a>=this.blockSize){for(var n=0;n0&&(i=this.blockSize-i),this._partialOutput.clear();for(n=0;n0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),s(this._inBlock)},n.gcm.prototype.decrypt=function(e,t,r){var a=e.length();if(a0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),s(this._inBlock),this._hashBlock[0]=e.getInt32(),this._hashBlock[1]=e.getInt32(),this._hashBlock[2]=e.getInt32(),this._hashBlock[3]=e.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var n=0;n0;--a)t[a]=e[a]>>>1|(1&e[a-1])<<31;t[0]=e[0]>>>1,r&&(t[0]^=this._R)},n.gcm.prototype.tableMultiply=function(e){for(var t=[0,0,0,0],r=0;r<32;++r){var a=e[r/8|0]>>>4*(7-r%8)&15,n=this._m[r][a];t[0]^=n[0],t[1]^=n[1],t[2]^=n[2],t[3]^=n[3]}return t},n.gcm.prototype.ghash=function(e,t,r){return t[0]^=r[0],t[1]^=r[1],t[2]^=r[2],t[3]^=r[3],this.tableMultiply(t)},n.gcm.prototype.generateHashTable=function(e,t){for(var r=8/t,a=4*r,n=16*r,i=new Array(n),s=0;s>>1,n=new Array(r);n[a]=e.slice(0);for(var i=a>>>1;i>0;)this.pow(n[2*i],n[i]=[]),i>>=1;for(i=2;i>1,o=s+(1&e.length),c=e.substr(0,o),u=e.substr(s,o),l=a.util.createBuffer(),p=a.hmac.create();r=t+r;var f=Math.ceil(n/16),h=Math.ceil(n/20);p.start("MD5",c);var d=a.util.createBuffer();l.putBytes(r);for(var y=0;y0&&(u.queue(e,u.createAlert(e,{level:u.Alert.Level.warning,description:u.Alert.Description.no_renegotiation})),u.flush(e)),e.process()},u.parseHelloMessage=function(e,t,r){var n=null,i=e.entity===u.ConnectionEnd.client;if(r<38)e.error(e,{message:i?"Invalid ServerHello message. Message too short.":"Invalid ClientHello message. Message too short.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.illegal_parameter}});else{var s=t.fragment,c=s.length();if(n={version:{major:s.getByte(),minor:s.getByte()},random:a.util.createBuffer(s.getBytes(32)),session_id:o(s,1),extensions:[]},i?(n.cipher_suite=s.getBytes(2),n.compression_method=s.getByte()):(n.cipher_suites=o(s,2),n.compression_methods=o(s,1)),(c=r-(c-s.length()))>0){for(var l=o(s,2);l.length()>0;)n.extensions.push({type:[l.getByte(),l.getByte()],data:o(l,2)});if(!i)for(var p=0;p0;){if(0!==h.getByte())break;e.session.extensions.server_name.serverNameList.push(o(h,2).getBytes())}}}if(e.session.version&&(n.version.major!==e.session.version.major||n.version.minor!==e.session.version.minor))return e.error(e,{message:"TLS version change is disallowed during renegotiation.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.protocol_version}});if(i)e.session.cipherSuite=u.getCipherSuite(n.cipher_suite);else for(var d=a.util.createBuffer(n.cipher_suites.bytes());d.length()>0&&(e.session.cipherSuite=u.getCipherSuite(d.getBytes(2)),null===e.session.cipherSuite););if(null===e.session.cipherSuite)return e.error(e,{message:"No cipher suites in common.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.handshake_failure},cipherSuite:a.util.bytesToHex(n.cipher_suite)});e.session.compressionMethod=i?n.compression_method:u.CompressionMethod.none}return n},u.createSecurityParameters=function(e,t){var r=e.entity===u.ConnectionEnd.client,a=t.random.bytes(),n=r?e.session.sp.client_random:a,i=r?a:u.createRandom().getBytes();e.session.sp={entity:e.entity,prf_algorithm:u.PRFAlgorithm.tls_prf_sha256,bulk_cipher_algorithm:null,cipher_type:null,enc_key_length:null,block_length:null,fixed_iv_length:null,record_iv_length:null,mac_algorithm:null,mac_length:null,mac_key_length:null,compression_algorithm:e.session.compressionMethod,pre_master_secret:null,master_secret:null,client_random:n,server_random:i}},u.handleServerHello=function(e,t,r){var a=u.parseHelloMessage(e,t,r);if(!e.fail){if(!(a.version.minor<=e.version.minor))return e.error(e,{message:"Incompatible TLS version.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.protocol_version}});e.version.minor=a.version.minor,e.session.version=e.version;var n=a.session_id.bytes();n.length>0&&n===e.session.id?(e.expect=d,e.session.resuming=!0,e.session.sp.server_random=a.random.bytes()):(e.expect=l,e.session.resuming=!1,u.createSecurityParameters(e,a)),e.session.id=n,e.process()}},u.handleClientHello=function(e,t,r){var n=u.parseHelloMessage(e,t,r);if(!e.fail){var i=n.session_id.bytes(),s=null;if(e.sessionCache&&(null===(s=e.sessionCache.getSession(i))?i="":(s.version.major!==n.version.major||s.version.minor>n.version.minor)&&(s=null,i="")),0===i.length&&(i=a.random.getBytes(32)),e.session.id=i,e.session.clientHelloVersion=n.version,e.session.sp={},s)e.version=e.session.version=s.version,e.session.sp=s.sp;else{for(var o,c=1;c0;)n=o(c.certificate_list,3),i=a.asn1.fromDer(n),n=a.pki.certificateFromAsn1(i,!0),l.push(n)}catch(t){return e.error(e,{message:"Could not parse certificate list.",cause:t,send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.bad_certificate}})}var f=e.entity===u.ConnectionEnd.client;!f&&!0!==e.verifyClient||0!==l.length?0===l.length?e.expect=f?p:C:(f?e.session.serverCertificate=l[0]:e.session.clientCertificate=l[0],u.verifyCertificateChain(e,l)&&(e.expect=f?p:C)):e.error(e,{message:f?"No server certificate provided.":"No client certificate provided.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.illegal_parameter}}),e.process()},u.handleServerKeyExchange=function(e,t,r){if(r>0)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.unsupported_certificate}});e.expect=f,e.process()},u.handleClientKeyExchange=function(e,t,r){if(r<48)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.unsupported_certificate}});var n=t.fragment,i={enc_pre_master_secret:o(n,2).getBytes()},s=null;if(e.getPrivateKey)try{s=e.getPrivateKey(e,e.session.serverCertificate),s=a.pki.privateKeyFromPem(s)}catch(t){e.error(e,{message:"Could not get private key.",cause:t,send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.internal_error}})}if(null===s)return e.error(e,{message:"No private key set.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.internal_error}});try{var c=e.session.sp;c.pre_master_secret=s.decrypt(i.enc_pre_master_secret);var l=e.session.clientHelloVersion;if(l.major!==c.pre_master_secret.charCodeAt(0)||l.minor!==c.pre_master_secret.charCodeAt(1))throw new Error("TLS version rollback attack detected.")}catch(e){c.pre_master_secret=a.random.getBytes(48)}e.expect=S,null!==e.session.clientCertificate&&(e.expect=E),e.process()},u.handleCertificateRequest=function(e,t,r){if(r<3)return e.error(e,{message:"Invalid CertificateRequest. Message too short.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.illegal_parameter}});var a=t.fragment,n={certificate_types:o(a,1),certificate_authorities:o(a,2)};e.session.certificateRequest=n,e.expect=h,e.process()},u.handleCertificateVerify=function(e,t,r){if(r<2)return e.error(e,{message:"Invalid CertificateVerify. Message too short.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.illegal_parameter}});var n=t.fragment;n.read-=4;var i=n.bytes();n.read+=4;var s={signature:o(n,2).getBytes()},c=a.util.createBuffer();c.putBuffer(e.session.md5.digest()),c.putBuffer(e.session.sha1.digest()),c=c.getBytes();try{if(!e.session.clientCertificate.publicKey.verify(c,s.signature,"NONE"))throw new Error("CertificateVerify signature does not match.");e.session.md5.update(i),e.session.sha1.update(i)}catch(t){return e.error(e,{message:"Bad signature in CertificateVerify.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.handshake_failure}})}e.expect=S,e.process()},u.handleServerHelloDone=function(e,t,r){if(r>0)return e.error(e,{message:"Invalid ServerHelloDone message. Invalid length.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.record_overflow}});if(null===e.serverCertificate){var n={message:"No server certificate provided. Not enough security.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.insufficient_security}},i=e.verify(e,n.alert.description,0,[]);if(!0!==i)return(i||0===i)&&("object"!=typeof i||a.util.isArray(i)?"number"==typeof i&&(n.alert.description=i):(i.message&&(n.message=i.message),i.alert&&(n.alert.description=i.alert))),e.error(e,n)}null!==e.session.certificateRequest&&(t=u.createRecord(e,{type:u.ContentType.handshake,data:u.createCertificate(e)}),u.queue(e,t)),t=u.createRecord(e,{type:u.ContentType.handshake,data:u.createClientKeyExchange(e)}),u.queue(e,t),e.expect=v;var s=function(e,t){null!==e.session.certificateRequest&&null!==e.session.clientCertificate&&u.queue(e,u.createRecord(e,{type:u.ContentType.handshake,data:u.createCertificateVerify(e,t)})),u.queue(e,u.createRecord(e,{type:u.ContentType.change_cipher_spec,data:u.createChangeCipherSpec()})),e.state.pending=u.createConnectionState(e),e.state.current.write=e.state.pending.write,u.queue(e,u.createRecord(e,{type:u.ContentType.handshake,data:u.createFinished(e)})),e.expect=d,u.flush(e),e.process()};if(null===e.session.certificateRequest||null===e.session.clientCertificate)return s(e,null);u.getClientSignature(e,s)},u.handleChangeCipherSpec=function(e,t){if(1!==t.fragment.getByte())return e.error(e,{message:"Invalid ChangeCipherSpec message received.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.illegal_parameter}});var r=e.entity===u.ConnectionEnd.client;(e.session.resuming&&r||!e.session.resuming&&!r)&&(e.state.pending=u.createConnectionState(e)),e.state.current.read=e.state.pending.read,(!e.session.resuming&&r||e.session.resuming&&!r)&&(e.state.pending=null),e.expect=r?y:T,e.process()},u.handleFinished=function(e,t,r){var i=t.fragment;i.read-=4;var s=i.bytes();i.read+=4;var o=t.fragment.getBytes();(i=a.util.createBuffer()).putBuffer(e.session.md5.digest()),i.putBuffer(e.session.sha1.digest());var c=e.entity===u.ConnectionEnd.client,l=c?"server finished":"client finished",p=e.session.sp;if((i=n(p.master_secret,l,i.getBytes(),12)).getBytes()!==o)return e.error(e,{message:"Invalid verify_data in Finished message.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.decrypt_error}});e.session.md5.update(s),e.session.sha1.update(s),(e.session.resuming&&c||!e.session.resuming&&!c)&&(u.queue(e,u.createRecord(e,{type:u.ContentType.change_cipher_spec,data:u.createChangeCipherSpec()})),e.state.current.write=e.state.pending.write,e.state.pending=null,u.queue(e,u.createRecord(e,{type:u.ContentType.handshake,data:u.createFinished(e)}))),e.expect=c?g:I,e.handshaking=!1,++e.handshakes,e.peerCertificate=c?e.session.serverCertificate:e.session.clientCertificate,u.flush(e),e.isConnected=!0,e.connected(e),e.process()},u.handleAlert=function(e,t){var r,a=t.fragment,n={level:a.getByte(),description:a.getByte()};switch(n.description){case u.Alert.Description.close_notify:r="Connection closed.";break;case u.Alert.Description.unexpected_message:r="Unexpected message.";break;case u.Alert.Description.bad_record_mac:r="Bad record MAC.";break;case u.Alert.Description.decryption_failed:r="Decryption failed.";break;case u.Alert.Description.record_overflow:r="Record overflow.";break;case u.Alert.Description.decompression_failure:r="Decompression failed.";break;case u.Alert.Description.handshake_failure:r="Handshake failure.";break;case u.Alert.Description.bad_certificate:r="Bad certificate.";break;case u.Alert.Description.unsupported_certificate:r="Unsupported certificate.";break;case u.Alert.Description.certificate_revoked:r="Certificate revoked.";break;case u.Alert.Description.certificate_expired:r="Certificate expired.";break;case u.Alert.Description.certificate_unknown:r="Certificate unknown.";break;case u.Alert.Description.illegal_parameter:r="Illegal parameter.";break;case u.Alert.Description.unknown_ca:r="Unknown certificate authority.";break;case u.Alert.Description.access_denied:r="Access denied.";break;case u.Alert.Description.decode_error:r="Decode error.";break;case u.Alert.Description.decrypt_error:r="Decrypt error.";break;case u.Alert.Description.export_restriction:r="Export restriction.";break;case u.Alert.Description.protocol_version:r="Unsupported protocol version.";break;case u.Alert.Description.insufficient_security:r="Insufficient security.";break;case u.Alert.Description.internal_error:r="Internal error.";break;case u.Alert.Description.user_canceled:r="User canceled.";break;case u.Alert.Description.no_renegotiation:r="Renegotiation not supported.";break;default:r="Unknown error."}if(n.description===u.Alert.Description.close_notify)return e.close();e.error(e,{message:r,send:!1,origin:e.entity===u.ConnectionEnd.client?"server":"client",alert:n}),e.process()},u.handleHandshake=function(e,t){var r=t.fragment,n=r.getByte(),i=r.getInt24();if(i>r.length())return e.fragmented=t,t.fragment=a.util.createBuffer(),r.read-=4,e.process();e.fragmented=null,r.read-=4;var s=r.bytes(i+4);r.read+=4,n in K[e.entity][e.expect]?(e.entity!==u.ConnectionEnd.server||e.open||e.fail||(e.handshaking=!0,e.session={version:null,extensions:{server_name:{serverNameList:[]}},cipherSuite:null,compressionMethod:null,serverCertificate:null,clientCertificate:null,md5:a.md.md5.create(),sha1:a.md.sha1.create()}),n!==u.HandshakeType.hello_request&&n!==u.HandshakeType.certificate_verify&&n!==u.HandshakeType.finished&&(e.session.md5.update(s),e.session.sha1.update(s)),K[e.entity][e.expect][n](e,t,i)):u.handleUnexpected(e,t)},u.handleApplicationData=function(e,t){e.data.putBuffer(t.fragment),e.dataReady(e),e.process()},u.handleHeartbeat=function(e,t){var r=t.fragment,n=r.getByte(),i=r.getInt16(),s=r.getBytes(i);if(n===u.HeartbeatMessageType.heartbeat_request){if(e.handshaking||i>s.length)return e.process();u.queue(e,u.createRecord(e,{type:u.ContentType.heartbeat,data:u.createHeartbeat(u.HeartbeatMessageType.heartbeat_response,s)})),u.flush(e)}else if(n===u.HeartbeatMessageType.heartbeat_response){if(s!==e.expectedHeartbeatPayload)return e.process();e.heartbeatReceived&&e.heartbeatReceived(e,a.util.createBuffer(s))}e.process()};var l=1,p=2,f=3,h=4,d=5,y=6,g=7,v=8,m=1,C=2,E=3,S=4,T=5,I=6,A=u.handleUnexpected,B=u.handleChangeCipherSpec,b=u.handleAlert,N=u.handleHandshake,R=u.handleApplicationData,w=u.handleHeartbeat,_=[];_[u.ConnectionEnd.client]=[[A,b,N,A,w],[A,b,N,A,w],[A,b,N,A,w],[A,b,N,A,w],[A,b,N,A,w],[B,b,A,A,w],[A,b,N,A,w],[A,b,N,R,w],[A,b,N,A,w]],_[u.ConnectionEnd.server]=[[A,b,N,A,w],[A,b,N,A,w],[A,b,N,A,w],[A,b,N,A,w],[B,b,A,A,w],[A,b,N,A,w],[A,b,N,R,w],[A,b,N,A,w]];var L=u.handleHelloRequest,k=u.handleServerHello,U=u.handleCertificate,D=u.handleServerKeyExchange,P=u.handleCertificateRequest,V=u.handleServerHelloDone,O=u.handleFinished,K=[];K[u.ConnectionEnd.client]=[[A,A,k,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A],[L,A,A,A,A,A,A,A,A,A,A,U,D,P,V,A,A,A,A,A,A],[L,A,A,A,A,A,A,A,A,A,A,A,D,P,V,A,A,A,A,A,A],[L,A,A,A,A,A,A,A,A,A,A,A,A,P,V,A,A,A,A,A,A],[L,A,A,A,A,A,A,A,A,A,A,A,A,A,V,A,A,A,A,A,A],[L,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A],[L,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,O],[L,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A],[L,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A]];var x=u.handleClientHello,M=u.handleClientKeyExchange,F=u.handleCertificateVerify;K[u.ConnectionEnd.server]=[[A,x,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A],[A,A,A,A,A,A,A,A,A,A,A,U,A,A,A,A,A,A,A,A,A],[A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,M,A,A,A,A],[A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,F,A,A,A,A,A],[A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A],[A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,O],[A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A],[A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A]],u.generateKeys=function(e,t){var r=n,a=t.client_random+t.server_random;e.session.resuming||(t.master_secret=r(t.pre_master_secret,"master secret",a,48).bytes(),t.pre_master_secret=null),a=t.server_random+t.client_random;var i=2*t.mac_key_length+2*t.enc_key_length,s=e.version.major===u.Versions.TLS_1_0.major&&e.version.minor===u.Versions.TLS_1_0.minor;s&&(i+=2*t.fixed_iv_length);var o=r(t.master_secret,"key expansion",a,i),c={client_write_MAC_key:o.getBytes(t.mac_key_length),server_write_MAC_key:o.getBytes(t.mac_key_length),client_write_key:o.getBytes(t.enc_key_length),server_write_key:o.getBytes(t.enc_key_length)};return s&&(c.client_write_IV=o.getBytes(t.fixed_iv_length),c.server_write_IV=o.getBytes(t.fixed_iv_length)),c},u.createConnectionState=function(e){var t=e.entity===u.ConnectionEnd.client,r=function(){var e={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(e){return!0},compressionState:null,compressFunction:function(e){return!0},updateSequenceNumber:function(){4294967295===e.sequenceNumber[1]?(e.sequenceNumber[1]=0,++e.sequenceNumber[0]):++e.sequenceNumber[1]}};return e},a={read:r(),write:r()};if(a.read.update=function(e,t){return a.read.cipherFunction(t,a.read)?a.read.compressFunction(e,t,a.read)||e.error(e,{message:"Could not decompress record.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.decompression_failure}}):e.error(e,{message:"Could not decrypt record or bad MAC.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.bad_record_mac}}),!e.fail},a.write.update=function(e,t){return a.write.compressFunction(e,t,a.write)?a.write.cipherFunction(t,a.write)||e.error(e,{message:"Could not encrypt record.",send:!1,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.internal_error}}):e.error(e,{message:"Could not compress record.",send:!1,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.internal_error}}),!e.fail},e.session){var n=e.session.sp;switch(e.session.cipherSuite.initSecurityParameters(n),n.keys=u.generateKeys(e,n),a.read.macKey=t?n.keys.server_write_MAC_key:n.keys.client_write_MAC_key,a.write.macKey=t?n.keys.client_write_MAC_key:n.keys.server_write_MAC_key,e.session.cipherSuite.initConnectionState(a,e,n),n.compression_algorithm){case u.CompressionMethod.none:break;case u.CompressionMethod.deflate:a.read.compressFunction=s,a.write.compressFunction=i;break;default:throw new Error("Unsupported compression algorithm.")}}return a},u.createRandom=function(){var e=new Date,t=+e+6e4*e.getTimezoneOffset(),r=a.util.createBuffer();return r.putInt32(t),r.putBytes(a.random.getBytes(28)),r},u.createRecord=function(e,t){return t.data?{type:t.type,version:{major:e.version.major,minor:e.version.minor},length:t.data.length(),fragment:t.data}:null},u.createAlert=function(e,t){var r=a.util.createBuffer();return r.putByte(t.level),r.putByte(t.description),u.createRecord(e,{type:u.ContentType.alert,data:r})},u.createClientHello=function(e){e.session.clientHelloVersion={major:e.version.major,minor:e.version.minor};for(var t=a.util.createBuffer(),r=0;r0&&(d+=2);var y=e.session.id,g=y.length+1+2+4+28+2+i+1+o+d,v=a.util.createBuffer();return v.putByte(u.HandshakeType.client_hello),v.putInt24(g),v.putByte(e.version.major),v.putByte(e.version.minor),v.putBytes(e.session.sp.client_random),c(v,1,a.util.createBuffer(y)),c(v,2,t),c(v,1,s),d>0&&c(v,2,l),v},u.createServerHello=function(e){var t=e.session.id,r=t.length+1+2+4+28+2+1,n=a.util.createBuffer();return n.putByte(u.HandshakeType.server_hello),n.putInt24(r),n.putByte(e.version.major),n.putByte(e.version.minor),n.putBytes(e.session.sp.server_random),c(n,1,a.util.createBuffer(t)),n.putByte(e.session.cipherSuite.id[0]),n.putByte(e.session.cipherSuite.id[1]),n.putByte(e.session.compressionMethod),n},u.createCertificate=function(e){var t,r=e.entity===u.ConnectionEnd.client,n=null;e.getCertificate&&(t=r?e.session.certificateRequest:e.session.extensions.server_name.serverNameList,n=e.getCertificate(e,t));var i=a.util.createBuffer();if(null!==n)try{a.util.isArray(n)||(n=[n]);for(var s=null,o=0;ou.MaxFragment;)n.push(u.createRecord(e,{type:t.type,data:a.util.createBuffer(i.slice(0,u.MaxFragment))})),i=i.slice(u.MaxFragment);i.length>0&&n.push(u.createRecord(e,{type:t.type,data:a.util.createBuffer(i)}))}for(var s=0;s0&&(n=r.order[0]),null!==n&&n in r.cache)for(var i in t=r.cache[n],delete r.cache[n],r.order)if(r.order[i]===n){r.order.splice(i,1);break}return t},r.setSession=function(e,t){if(r.order.length===r.capacity){var n=r.order.shift();delete r.cache[n]}n=a.util.bytesToHex(e);r.order.push(n),r.cache[n]=t}}return r},u.createConnection=function(e){var t=null;t=e.caStore?a.util.isArray(e.caStore)?a.pki.createCaStore(e.caStore):e.caStore:a.pki.createCaStore();var r=e.cipherSuites||null;if(null===r)for(var n in r=[],u.CipherSuites)r.push(u.CipherSuites[n]);var i=e.server?u.ConnectionEnd.server:u.ConnectionEnd.client,s=e.sessionCache?u.createSessionCache(e.sessionCache):null,o={version:{major:u.Version.major,minor:u.Version.minor},entity:i,sessionId:e.sessionId,caStore:t,sessionCache:s,cipherSuites:r,connected:e.connected,virtualHost:e.virtualHost||null,verifyClient:e.verifyClient||!1,verify:e.verify||function(e,t,r,a){return t},verifyOptions:e.verifyOptions||{},getCertificate:e.getCertificate||null,getPrivateKey:e.getPrivateKey||null,getSignature:e.getSignature||null,input:a.util.createBuffer(),tlsData:a.util.createBuffer(),data:a.util.createBuffer(),tlsDataReady:e.tlsDataReady,dataReady:e.dataReady,heartbeatReceived:e.heartbeatReceived,closed:e.closed,error:function(t,r){r.origin=r.origin||(t.entity===u.ConnectionEnd.client?"client":"server"),r.send&&(u.queue(t,u.createAlert(t,r.alert)),u.flush(t));var a=!1!==r.fatal;a&&(t.fail=!0),e.error(t,r),a&&t.close(!1)},deflate:e.deflate||null,inflate:e.inflate||null,reset:function(e){o.version={major:u.Version.major,minor:u.Version.minor},o.record=null,o.session=null,o.peerCertificate=null,o.state={pending:null,current:null},o.expect=(o.entity,u.ConnectionEnd.client,0),o.fragmented=null,o.records=[],o.open=!1,o.handshakes=0,o.handshaking=!1,o.isConnected=!1,o.fail=!(e||void 0===e),o.input.clear(),o.tlsData.clear(),o.data.clear(),o.state.current=u.createConnectionState(o)}};o.reset();return o.handshake=function(e){if(o.entity!==u.ConnectionEnd.client)o.error(o,{message:"Cannot initiate handshake as a server.",fatal:!1});else if(o.handshaking)o.error(o,{message:"Handshake already in progress.",fatal:!1});else{o.fail&&!o.open&&0===o.handshakes&&(o.fail=!1),o.handshaking=!0;var t=null;(e=e||"").length>0&&(o.sessionCache&&(t=o.sessionCache.getSession(e)),null===t&&(e="")),0===e.length&&o.sessionCache&&null!==(t=o.sessionCache.getSession())&&(e=t.id),o.session={id:e,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:a.md.md5.create(),sha1:a.md.sha1.create()},t&&(o.version=t.version,o.session.sp=t.sp),o.session.sp.client_random=u.createRandom().getBytes(),o.open=!0,u.queue(o,u.createRecord(o,{type:u.ContentType.handshake,data:u.createClientHello(o)})),u.flush(o)}},o.process=function(e){var t=0;return e&&o.input.putBytes(e),o.fail||(null!==o.record&&o.record.ready&&o.record.fragment.isEmpty()&&(o.record=null),null===o.record&&(t=function(e){var t=0,r=e.input,n=r.length();if(n<5)t=5-n;else{e.record={type:r.getByte(),version:{major:r.getByte(),minor:r.getByte()},length:r.getInt16(),fragment:a.util.createBuffer(),ready:!1};var i=e.record.version.major===e.version.major;i&&e.session&&e.session.version&&(i=e.record.version.minor===e.version.minor),i||e.error(e,{message:"Incompatible TLS version.",send:!0,alert:{level:u.Alert.Level.fatal,description:u.Alert.Description.protocol_version}})}return t}(o)),o.fail||null===o.record||o.record.ready||(t=function(e){var t=0,r=e.input,a=r.length();a=0;c--)w>>=8,w+=B.at(c)+R.at(c),R.setAt(c,255&w);N.putBuffer(R)}E=N,p.putBuffer(I)}return p.truncate(p.length()-i),p},s.pbe.getCipher=function(e,t,r){switch(e){case s.oids.pkcs5PBES2:return s.pbe.getCipherForPBES2(e,t,r);case s.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case s.oids["pbewithSHAAnd40BitRC2-CBC"]:return s.pbe.getCipherForPKCS12PBE(e,t,r);default:var a=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw a.oid=e,a.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],a}},s.pbe.getCipherForPBES2=function(e,t,r){var n,o={},c=[];if(!i.validate(t,u,o,c))throw(n=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=c,n;if((e=i.derToOid(o.kdfOid))!==s.oids.pkcs5PBKDF2)throw(n=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.")).oid=e,n.supportedOids=["pkcs5PBKDF2"],n;if((e=i.derToOid(o.encOid))!==s.oids["aes128-CBC"]&&e!==s.oids["aes192-CBC"]&&e!==s.oids["aes256-CBC"]&&e!==s.oids["des-EDE3-CBC"]&&e!==s.oids.desCBC)throw(n=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.")).oid=e,n.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],n;var l,p,h=o.kdfSalt,d=a.util.createBuffer(o.kdfIterationCount);switch(d=d.getInt(d.length()<<3),s.oids[e]){case"aes128-CBC":l=16,p=a.aes.createDecryptionCipher;break;case"aes192-CBC":l=24,p=a.aes.createDecryptionCipher;break;case"aes256-CBC":l=32,p=a.aes.createDecryptionCipher;break;case"des-EDE3-CBC":l=24,p=a.des.createDecryptionCipher;break;case"desCBC":l=8,p=a.des.createDecryptionCipher}var y=f(o.prfOid),g=a.pkcs5.pbkdf2(r,h,d,l,y),v=o.encIv,m=p(g);return m.start(v),m},s.pbe.getCipherForPKCS12PBE=function(e,t,r){var n={},o=[];if(!i.validate(t,l,n,o))throw(y=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=o,y;var c,u,p,h=a.util.createBuffer(n.salt),d=a.util.createBuffer(n.iterations);switch(d=d.getInt(d.length()<<3),e){case s.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,u=8,p=a.des.startDecrypting;break;case s.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,u=8,p=function(e,t){var r=a.rc2.createDecryptionCipher(e,40);return r.start(t,null),r};break;default:var y;throw(y=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.")).oid=e,y}var g=f(n.prfOid),v=s.pbe.generatePkcs12Key(r,h,1,d,c,g);return g.start(),p(v,s.pbe.generatePkcs12Key(r,h,2,d,u,g))},s.pbe.opensslDeriveBytes=function(e,t,r,n){if(null==n){if(!("md5"in a.md))throw new Error('"md5" hash algorithm unavailable.');n=a.md.md5.create()}null===t&&(t="");for(var i=[p(n,e+t)],s=16,o=1;s>>0,o>>>0];for(var u=n.fullMessageLength.length-1;u>=0;--u)n.fullMessageLength[u]+=o[1],o[1]=o[0]+(n.fullMessageLength[u]/4294967296>>>0),n.fullMessageLength[u]=n.fullMessageLength[u]>>>0,o[0]=o[1]/4294967296>>>0;return t.putBytes(i),c(e,r,t),(t.read>2048||0===t.length())&&t.compact(),n},n.digest=function(){var s=a.util.createBuffer();s.putBytes(t.bytes());var o,u=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize&n.blockLength-1;s.putBytes(i.substr(0,n.blockLength-u));for(var l=8*n.fullMessageLength[0],p=0;p>>0,s.putInt32(l>>>0),l=o>>>0;s.putInt32(l);var f={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};c(f,r,s);var h=a.util.createBuffer();return h.putInt32(f.h0),h.putInt32(f.h1),h.putInt32(f.h2),h.putInt32(f.h3),h.putInt32(f.h4),h.putInt32(f.h5),h.putInt32(f.h6),h.putInt32(f.h7),h},n};var i=null,s=!1,o=null;function c(e,t,r){for(var a,n,i,s,c,u,l,p,f,h,d,y,g,v=r.length();v>=64;){for(c=0;c<16;++c)t[c]=r.getInt32();for(;c<64;++c)a=((a=t[c-2])>>>17|a<<15)^(a>>>19|a<<13)^a>>>10,n=((n=t[c-15])>>>7|n<<25)^(n>>>18|n<<14)^n>>>3,t[c]=a+t[c-7]+n+t[c-16]|0;for(u=e.h0,l=e.h1,p=e.h2,f=e.h3,h=e.h4,d=e.h5,y=e.h6,g=e.h7,c=0;c<64;++c)i=(u>>>2|u<<30)^(u>>>13|u<<19)^(u>>>22|u<<10),s=u&l|p&(u^l),a=g+((h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7))+(y^h&(d^y))+o[c]+t[c],g=y,y=d,d=h,h=f+a>>>0,f=p,p=l,l=u,u=a+(n=i+s)>>>0;e.h0=e.h0+u|0,e.h1=e.h1+l|0,e.h2=e.h2+p|0,e.h3=e.h3+f|0,e.h4=e.h4+h|0,e.h5=e.h5+d|0,e.h6=e.h6+y|0,e.h7=e.h7+g|0,v-=64}}},function(e,t,r){var a=r(0);r(1);var n=null;!a.util.isNodejs||a.options.usePureJavaScript||process.versions["node-webkit"]||(n=r(16)),(e.exports=a.prng=a.prng||{}).create=function(e){for(var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},r=e.md,i=new Array(32),s=0;s<32;++s)i[s]=r.create();function o(){if(t.pools[0].messageLength>=32)return c();var e=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(e)),c()}function c(){t.reseeds=4294967295===t.reseeds?0:t.reseeds+1;var e=t.plugin.md.create();e.update(t.keyBytes);for(var r=1,a=0;a<32;++a)t.reseeds%r==0&&(e.update(t.pools[a].digest().getBytes()),t.pools[a].start()),r<<=1;t.keyBytes=e.digest().getBytes(),e.start(),e.update(t.keyBytes);var n=e.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(n),t.generated=0}function u(e){var t=null,r=a.util.globalScope,n=r.crypto||r.msCrypto;n&&n.getRandomValues&&(t=function(e){return n.getRandomValues(e)});var i=a.util.createBuffer();if(t)for(;i.length()>16)))<<16,f=4294967295&(l=(2147483647&(l+=u>>15))+(l>>31));for(c=0;c<3;++c)p=f>>>(c<<3),p^=Math.floor(256*Math.random()),i.putByte(255&p)}return i.getBytes(e)}return t.pools=i,t.pool=0,t.generate=function(e,r){if(!r)return t.generateSync(e);var n=t.plugin.cipher,i=t.plugin.increment,s=t.plugin.formatKey,o=t.plugin.formatSeed,u=a.util.createBuffer();t.key=null,function l(p){if(p)return r(p);if(u.length()>=e)return r(null,u.getBytes(e));t.generated>1048575&&(t.key=null);if(null===t.key)return a.util.nextTick((function(){!function(e){if(t.pools[0].messageLength>=32)return c(),e();var r=32-t.pools[0].messageLength<<5;t.seedFile(r,(function(r,a){if(r)return e(r);t.collect(a),c(),e()}))}(l)}));var f=n(t.key,t.seed);t.generated+=f.length,u.putBytes(f),t.key=s(n(t.key,i(t.seed))),t.seed=o(n(t.key,t.seed)),a.util.setImmediate(l)}()},t.generateSync=function(e){var r=t.plugin.cipher,n=t.plugin.increment,i=t.plugin.formatKey,s=t.plugin.formatSeed;t.key=null;for(var c=a.util.createBuffer();c.length()1048575&&(t.key=null),null===t.key&&o();var u=r(t.key,t.seed);t.generated+=u.length,c.putBytes(u),t.key=i(r(t.key,n(t.seed))),t.seed=s(r(t.key,t.seed))}return c.getBytes(e)},n?(t.seedFile=function(e,t){n.randomBytes(e,(function(e,r){if(e)return t(e);t(null,r.toString())}))},t.seedFileSync=function(e){return n.randomBytes(e).toString()}):(t.seedFile=function(e,t){try{t(null,u(e))}catch(e){t(e)}},t.seedFileSync=u),t.collect=function(e){for(var r=e.length,a=0;a>n&255);t.collect(a)},t.registerWorker=function(e){if(e===self)t.seedFile=function(e,t){self.addEventListener("message",(function e(r){var a=r.data;a.forge&&a.forge.prng&&(self.removeEventListener("message",e),t(a.forge.prng.err,a.forge.prng.bytes))})),self.postMessage({forge:{prng:{needed:e}}})};else{e.addEventListener("message",(function(r){var a=r.data;a.forge&&a.forge.prng&&t.seedFile(a.forge.prng.needed,(function(t,r){e.postMessage({forge:{prng:{err:t,bytes:r}}})}))}))}},t}},function(e,t,r){var a=r(0);r(1);var n=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],i=[1,2,3,5],s=function(e,t){return e<>16-t},o=function(e,t){return(65535&e)>>t|e<<16-t&65535};e.exports=a.rc2=a.rc2||{},a.rc2.expandKey=function(e,t){"string"==typeof e&&(e=a.util.createBuffer(e)),t=t||128;var r,i=e,s=e.length(),o=t,c=Math.ceil(o/8),u=255>>(7&o);for(r=s;r<128;r++)i.putByte(n[i.at(r-1)+i.at(r-s)&255]);for(i.setAt(128-c,n[i.at(128-c)&u]),r=127-c;r>=0;r--)i.setAt(r,n[i.at(r+1)^i.at(r+c)]);return i};var c=function(e,t,r){var n,c,u,l,p=!1,f=null,h=null,d=null,y=[];for(e=a.rc2.expandKey(e,t),u=0;u<64;u++)y.push(e.getInt16Le());r?(n=function(e){for(u=0;u<4;u++)e[u]+=y[l]+(e[(u+3)%4]&e[(u+2)%4])+(~e[(u+3)%4]&e[(u+1)%4]),e[u]=s(e[u],i[u]),l++},c=function(e){for(u=0;u<4;u++)e[u]+=y[63&e[(u+3)%4]]}):(n=function(e){for(u=3;u>=0;u--)e[u]=o(e[u],i[u]),e[u]-=y[l]+(e[(u+3)%4]&e[(u+2)%4])+(~e[(u+3)%4]&e[(u+1)%4]),l--},c=function(e){for(u=3;u>=0;u--)e[u]-=y[63&e[(u+3)%4]]});var g=function(e){var t=[];for(u=0;u<4;u++){var a=f.getInt16Le();null!==d&&(r?a^=d.getInt16Le():d.putInt16Le(a)),t.push(65535&a)}l=r?0:63;for(var n=0;n=8;)g([[5,n],[1,c],[6,n],[1,c],[5,n]])},finish:function(e){var t=!0;if(r)if(e)t=e(8,f,!r);else{var a=8===f.length()?8:8-f.length();f.fillWithByte(a,a)}if(t&&(p=!0,v.update()),!r&&(t=0===f.length()))if(e)t=e(8,h,!r);else{var n=h.length(),i=h.at(n-1);i>n?t=!1:h.truncate(i)}return t}}};a.rc2.startEncrypting=function(e,t,r){var n=a.rc2.createEncryptionCipher(e,128);return n.start(t,r),n},a.rc2.createEncryptionCipher=function(e,t){return c(e,t,!0)},a.rc2.startDecrypting=function(e,t,r){var n=a.rc2.createDecryptionCipher(e,128);return n.start(t,r),n},a.rc2.createDecryptionCipher=function(e,t){return c(e,t,!1)}},function(e,t,r){var a=r(0);r(1),r(2),r(9);var n=e.exports=a.pkcs1=a.pkcs1||{};function i(e,t,r){r||(r=a.md.sha1.create());for(var n="",i=Math.ceil(t/r.digestLength),s=0;s>24&255,s>>16&255,s>>8&255,255&s);r.start(),r.update(e+o),n+=r.digest().getBytes()}return n.substring(0,t)}n.encode_rsa_oaep=function(e,t,r){var n,s,o,c;"string"==typeof r?(n=r,s=arguments[3]||void 0,o=arguments[4]||void 0):r&&(n=r.label||void 0,s=r.seed||void 0,o=r.md||void 0,r.mgf1&&r.mgf1.md&&(c=r.mgf1.md)),o?o.start():o=a.md.sha1.create(),c||(c=o);var u=Math.ceil(e.n.bitLength()/8),l=u-2*o.digestLength-2;if(t.length>l)throw(g=new Error("RSAES-OAEP input message length is too long.")).length=t.length,g.maxLength=l,g;n||(n=""),o.update(n,"raw");for(var p=o.digest(),f="",h=l-t.length,d=0;de&&(s=c(e,t));var h=s.toString(16);n.target.postMessage({hex:h,workLoad:l}),s.dAddOffset(p,0)}}}h()}(e,t,n,i);return o(e,t,n,i)}(e,u,i.options,n);throw new Error("Invalid prime generation algorithm: "+i.name)}}function o(e,t,r,i){var s=c(e,t),o=function(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}(s.bitLength());"millerRabinTests"in r&&(o=r.millerRabinTests);var u=10;"maxBlockTime"in r&&(u=r.maxBlockTime),function e(t,r,i,s,o,u,l){var p=+new Date;do{if(t.bitLength()>r&&(t=c(r,i)),t.isProbablePrime(o))return l(null,t);t.dAddOffset(n[s++%8],0)}while(u<0||+new Date-p=0&&n.push(o):n.push(o))}return n}function h(e){if(e.composed||e.constructed){for(var t=a.util.createBuffer(),r=0;r2)throw new Error("Invalid PKCS#12. macData field present but MAC was not validated.");return function(e,t,r,a){if((t=n.fromDer(t,r)).tagClass!==n.Class.UNIVERSAL||t.type!==n.Type.SEQUENCE||!0!==t.constructed)throw new Error("PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo");for(var s=0;s0&&(c=n.create(n.Class.UNIVERSAL,n.Type.SET,!0,p));var f=[],h=[];null!==t&&(h=a.util.isArray(t)?t:[t]);for(var d=[],y=0;y0){var C=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,d),E=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.OID,!1,n.oidToDer(i.oids.data).getBytes()),n.create(n.Class.CONTEXT_SPECIFIC,0,!0,[n.create(n.Class.UNIVERSAL,n.Type.OCTETSTRING,!1,n.toDer(C).getBytes())])]);f.push(E)}var S=null;if(null!==e){var T=i.wrapRsaPrivateKey(i.privateKeyToAsn1(e));S=null===r?n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.OID,!1,n.oidToDer(i.oids.keyBag).getBytes()),n.create(n.Class.CONTEXT_SPECIFIC,0,!0,[T]),c]):n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.OID,!1,n.oidToDer(i.oids.pkcs8ShroudedKeyBag).getBytes()),n.create(n.Class.CONTEXT_SPECIFIC,0,!0,[i.encryptPrivateKeyInfo(T,r,o)]),c]);var I=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[S]),A=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.OID,!1,n.oidToDer(i.oids.data).getBytes()),n.create(n.Class.CONTEXT_SPECIFIC,0,!0,[n.create(n.Class.UNIVERSAL,n.Type.OCTETSTRING,!1,n.toDer(I).getBytes())])]);f.push(A)}var B,b=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,f);if(o.useMac){var N=a.md.sha1.create(),R=new a.util.ByteBuffer(a.random.getBytes(o.saltSize)),w=o.count,_=(e=s.generateKey(r,R,3,w,20),a.hmac.create());_.start(N,e),_.update(n.toDer(b).getBytes());var L=_.getMac();B=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.OID,!1,n.oidToDer(i.oids.sha1).getBytes()),n.create(n.Class.UNIVERSAL,n.Type.NULL,!1,"")]),n.create(n.Class.UNIVERSAL,n.Type.OCTETSTRING,!1,L.getBytes())]),n.create(n.Class.UNIVERSAL,n.Type.OCTETSTRING,!1,R.getBytes()),n.create(n.Class.UNIVERSAL,n.Type.INTEGER,!1,n.integerToDer(w).getBytes())])}return n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.INTEGER,!1,n.integerToDer(3).getBytes()),n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.OID,!1,n.oidToDer(i.oids.data).getBytes()),n.create(n.Class.CONTEXT_SPECIFIC,0,!0,[n.create(n.Class.UNIVERSAL,n.Type.OCTETSTRING,!1,n.toDer(b).getBytes())])]),B])},s.generateKey=a.pbe.generatePkcs12Key},function(e,t,r){var a=r(0);r(3),r(1);var n=a.asn1,i=e.exports=a.pkcs7asn1=a.pkcs7asn1||{};a.pkcs7=a.pkcs7||{},a.pkcs7.asn1=i;var s={name:"ContentInfo",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:n.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};i.contentInfoValidator=s;var o={name:"EncryptedContentInfo",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:n.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:n.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};i.envelopedDataValidator={name:"EnvelopedData",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:n.Class.UNIVERSAL,type:n.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(o)},i.encryptedDataValidator={name:"EncryptedData",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"version"}].concat(o)};var c={name:"SignerInfo",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:n.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:n.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:n.Class.UNIVERSAL,type:n.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:n.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};i.signedDataValidator={name:"SignedData",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:n.Class.UNIVERSAL,type:n.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},s,{name:"SignedData.Certificates",tagClass:n.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:n.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:n.Class.UNIVERSAL,type:n.Type.SET,capture:"signerInfos",optional:!0,value:[c]}]},i.recipientInfoValidator={name:"RecipientInfo",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:n.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:n.Class.UNIVERSAL,type:n.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}},function(e,t,r){var a=r(0);r(1),a.mgf=a.mgf||{},(e.exports=a.mgf.mgf1=a.mgf1=a.mgf1||{}).create=function(e){return{generate:function(t,r){for(var n=new a.util.ByteBuffer,i=Math.ceil(r/e.digestLength),s=0;s>>0,s>>>0];for(var o=h.fullMessageLength.length-1;o>=0;--o)h.fullMessageLength[o]+=s[1],s[1]=s[0]+(h.fullMessageLength[o]/4294967296>>>0),h.fullMessageLength[o]=h.fullMessageLength[o]>>>0,s[0]=s[1]/4294967296>>>0;return n.putBytes(e),l(r,i,n),(n.read>2048||0===n.length())&&n.compact(),h},h.digest=function(){var t=a.util.createBuffer();t.putBytes(n.bytes());var o,c=h.fullMessageLength[h.fullMessageLength.length-1]+h.messageLengthSize&h.blockLength-1;t.putBytes(s.substr(0,h.blockLength-c));for(var u=8*h.fullMessageLength[0],p=0;p>>0,t.putInt32(u>>>0),u=o>>>0;t.putInt32(u);var f=new Array(r.length);for(p=0;p=128;){for(_=0;_<16;++_)t[_][0]=r.getInt32()>>>0,t[_][1]=r.getInt32()>>>0;for(;_<80;++_)a=(((L=(U=t[_-2])[0])>>>19|(k=U[1])<<13)^(k>>>29|L<<3)^L>>>6)>>>0,n=((L<<13|k>>>19)^(k<<3|L>>>29)^(L<<26|k>>>6))>>>0,i=(((L=(P=t[_-15])[0])>>>1|(k=P[1])<<31)^(L>>>8|k<<24)^L>>>7)>>>0,s=((L<<31|k>>>1)^(L<<24|k>>>8)^(L<<25|k>>>7))>>>0,D=t[_-7],V=t[_-16],k=n+D[1]+s+V[1],t[_][0]=a+D[0]+i+V[0]+(k/4294967296>>>0)>>>0,t[_][1]=k>>>0;for(d=e[0][0],y=e[0][1],g=e[1][0],v=e[1][1],m=e[2][0],C=e[2][1],E=e[3][0],S=e[3][1],T=e[4][0],I=e[4][1],A=e[5][0],B=e[5][1],b=e[6][0],N=e[6][1],R=e[7][0],w=e[7][1],_=0;_<80;++_)l=((T>>>14|I<<18)^(T>>>18|I<<14)^(I>>>9|T<<23))>>>0,p=(b^T&(A^b))>>>0,o=((d>>>28|y<<4)^(y>>>2|d<<30)^(y>>>7|d<<25))>>>0,u=((d<<4|y>>>28)^(y<<30|d>>>2)^(y<<25|d>>>7))>>>0,f=(d&g|m&(d^g))>>>0,h=(y&v|C&(y^v))>>>0,k=w+(((T<<18|I>>>14)^(T<<14|I>>>18)^(I<<23|T>>>9))>>>0)+((N^I&(B^N))>>>0)+c[_][1]+t[_][1],a=R+l+p+c[_][0]+t[_][0]+(k/4294967296>>>0)>>>0,n=k>>>0,i=o+f+((k=u+h)/4294967296>>>0)>>>0,s=k>>>0,R=b,w=N,b=A,N=B,A=T,B=I,T=E+a+((k=S+n)/4294967296>>>0)>>>0,I=k>>>0,E=m,S=C,m=g,C=v,g=d,v=y,d=a+i+((k=n+s)/4294967296>>>0)>>>0,y=k>>>0;k=e[0][1]+y,e[0][0]=e[0][0]+d+(k/4294967296>>>0)>>>0,e[0][1]=k>>>0,k=e[1][1]+v,e[1][0]=e[1][0]+g+(k/4294967296>>>0)>>>0,e[1][1]=k>>>0,k=e[2][1]+C,e[2][0]=e[2][0]+m+(k/4294967296>>>0)>>>0,e[2][1]=k>>>0,k=e[3][1]+S,e[3][0]=e[3][0]+E+(k/4294967296>>>0)>>>0,e[3][1]=k>>>0,k=e[4][1]+I,e[4][0]=e[4][0]+T+(k/4294967296>>>0)>>>0,e[4][1]=k>>>0,k=e[5][1]+B,e[5][0]=e[5][0]+A+(k/4294967296>>>0)>>>0,e[5][1]=k>>>0,k=e[6][1]+N,e[6][0]=e[6][0]+b+(k/4294967296>>>0)>>>0,e[6][1]=k>>>0,k=e[7][1]+w,e[7][0]=e[7][0]+R+(k/4294967296>>>0)>>>0,e[7][1]=k>>>0,O-=128}}},function(e,t,r){e.exports=r(33)},function(e,t,r){e.exports=r(0),r(5),r(36),r(3),r(13),r(10),r(38),r(8),r(40),r(41),r(42),r(30),r(15),r(7),r(26),r(28),r(43),r(21),r(27),r(24),r(18),r(2),r(25),r(44),r(20),r(1)},function(e,t){var r;r=function(){return this}();try{r=r||new Function("return this")()}catch(e){"object"==typeof window&&(r=window)}e.exports=r},function(e,t){var r={};e.exports=r;var a={};r.encode=function(e,t,r){if("string"!=typeof t)throw new TypeError('"alphabet" must be a string.');if(void 0!==r&&"number"!=typeof r)throw new TypeError('"maxline" must be a number.');var a="";if(e instanceof Uint8Array){var n=0,i=t.length,s=t.charAt(0),o=[0];for(n=0;n0;)o.push(u%i),u=u/i|0}for(n=0;0===e[n]&&n=0;--n)a+=t[o[n]]}else a=function(e,t){var r=0,a=t.length,n=t.charAt(0),i=[0];for(r=0;r0;)i.push(o%a),o=o/a|0}var c="";for(r=0;0===e.at(r)&&r=0;--r)c+=t[i[r]];return c}(e,t);if(r){var l=new RegExp(".{1,"+r+"}","g");a=a.match(l).join("\r\n")}return a},r.decode=function(e,t){if("string"!=typeof e)throw new TypeError('"input" must be a string.');if("string"!=typeof t)throw new TypeError('"alphabet" must be a string.');var r=a[t];if(!r){r=a[t]=[];for(var n=0;n>=8;for(;l>0;)o.push(255&l),l>>=8}for(var p=0;e[p]===s&&p=n.Versions.TLS_1_1.minor&&c.output.putBytes(r),c.update(e.fragment),c.finish(o)&&(e.fragment=c.output,e.length=e.fragment.length(),i=!0),i}function o(e,t,r){if(!r){var a=e-t.length()%e;t.fillWithByte(a-1,a)}return!0}function c(e,t,r){var a=!0;if(r){for(var n=t.length(),i=t.last(),s=n-1-i;s=o?(e.fragment=s.output.getBytes(l-o),u=s.output.getBytes(o)):e.fragment=s.output.getBytes(),e.fragment=a.util.createBuffer(e.fragment),e.length=e.fragment.length();var p=t.macFunction(t.macKey,t.sequenceNumber,e);return t.updateSequenceNumber(),i=function(e,t,r){var n=a.hmac.create();return n.start("SHA1",e),n.update(t),t=n.digest().getBytes(),n.start(null,null),n.update(r),r=n.digest().getBytes(),t===r}(t.macKey,u,p)&&i}n.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA={id:[0,47],name:"TLS_RSA_WITH_AES_128_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=n.BulkCipherAlgorithm.aes,e.cipher_type=n.CipherType.block,e.enc_key_length=16,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=n.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:i},n.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA={id:[0,53],name:"TLS_RSA_WITH_AES_256_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=n.BulkCipherAlgorithm.aes,e.cipher_type=n.CipherType.block,e.enc_key_length=32,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=n.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:i}},function(e,t,r){var a=r(0);r(30),e.exports=a.mgf=a.mgf||{},a.mgf.mgf1=a.mgf1},function(e,t,r){var a=r(0);r(12),r(2),r(31),r(1);var n=r(39),i=n.publicKeyValidator,s=n.privateKeyValidator;if(void 0===o)var o=a.jsbn.BigInteger;var c=a.util.ByteBuffer,u="undefined"==typeof Buffer?Uint8Array:Buffer;a.pki=a.pki||{},e.exports=a.pki.ed25519=a.ed25519=a.ed25519||{};var l=a.ed25519;function p(e){var t=e.message;if(t instanceof Uint8Array||t instanceof u)return t;var r=e.encoding;if(void 0===t){if(!e.md)throw new TypeError('"options.message" or "options.md" not specified.');t=e.md.digest().getBytes(),r="binary"}if("string"==typeof t&&!r)throw new TypeError('"options.encoding" must be "binary" or "utf8".');if("string"==typeof t){if("undefined"!=typeof Buffer)return Buffer.from(t,r);t=new c(t,r)}else if(!(t instanceof c))throw new TypeError('"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.');for(var a=new u(t.length()),n=0;n=0;--r)K(a,a),1!==r&&x(a,a,t);for(r=0;r<16;++r)e[r]=a[r]}(r,r),x(r,r,n),x(r,r,i),x(r,r,i),x(e[0],r,i),K(a,e[0]),x(a,a,i),N(a,n)&&x(e[0],e[0],C);if(K(a,e[0]),x(a,a,i),N(a,n))return-1;w(e[0])===t[31]>>7&&O(e[0],f,e[0]);return x(e[3],e[0],e[1]),0}(o,a))return-1;for(n=0;n=0};var f=P(),h=P([1]),d=P([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),y=P([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),g=P([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),v=P([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),m=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]),C=P([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function E(e,t){var r=a.md.sha512.create(),n=new c(e);r.update(n.getBytes(t),"binary");var i=r.digest().getBytes();if("undefined"!=typeof Buffer)return Buffer.from(i,"binary");for(var s=new u(l.constants.HASH_BYTE_LENGTH),o=0;o<64;++o)s[o]=i.charCodeAt(o);return s}function S(e,t){var r,a,n,i;for(a=63;a>=32;--a){for(r=0,n=a-32,i=a-12;n>8,t[n]-=256*r;t[n]+=r,t[a]=0}for(r=0,n=0;n<32;++n)t[n]+=r-(t[31]>>4)*m[n],r=t[n]>>8,t[n]&=255;for(n=0;n<32;++n)t[n]-=r*m[n];for(a=0;a<32;++a)t[a+1]+=t[a]>>8,e[a]=255&t[a]}function T(e){for(var t=new Float64Array(64),r=0;r<64;++r)t[r]=e[r],e[r]=0;S(e,t)}function I(e,t){var r=P(),a=P(),n=P(),i=P(),s=P(),o=P(),c=P(),u=P(),l=P();O(r,e[1],e[0]),O(l,t[1],t[0]),x(r,r,l),V(a,e[0],e[1]),V(l,t[0],t[1]),x(a,a,l),x(n,e[3],t[3]),x(n,n,y),x(i,e[2],t[2]),V(i,i,i),O(s,a,r),O(o,i,n),V(c,i,n),V(u,a,r),x(e[0],s,o),x(e[1],u,c),x(e[2],c,o),x(e[3],s,u)}function A(e,t,r){for(var a=0;a<4;++a)D(e[a],t[a],r)}function B(e,t){var r=P(),a=P(),n=P();!function(e,t){var r,a=P();for(r=0;r<16;++r)a[r]=t[r];for(r=253;r>=0;--r)K(a,a),2!==r&&4!==r&&x(a,a,t);for(r=0;r<16;++r)e[r]=a[r]}(n,t[2]),x(r,t[0],n),x(a,t[1],n),b(e,a),e[31]^=w(r)<<7}function b(e,t){var r,a,n,i=P(),s=P();for(r=0;r<16;++r)s[r]=t[r];for(U(s),U(s),U(s),a=0;a<2;++a){for(i[0]=s[0]-65517,r=1;r<15;++r)i[r]=s[r]-65535-(i[r-1]>>16&1),i[r-1]&=65535;i[15]=s[15]-32767-(i[14]>>16&1),n=i[15]>>16&1,i[14]&=65535,D(s,i,1-n)}for(r=0;r<16;r++)e[2*r]=255&s[r],e[2*r+1]=s[r]>>8}function N(e,t){var r=new u(32),a=new u(32);return b(r,e),b(a,t),R(r,0,a,0)}function R(e,t,r,a){return function(e,t,r,a,n){var i,s=0;for(i=0;i>>8)-1}(e,t,r,a,32)}function w(e){var t=new u(32);return b(t,e),1&t[0]}function _(e,t,r){var a,n;for(k(e[0],f),k(e[1],h),k(e[2],h),k(e[3],f),n=255;n>=0;--n)A(e,t,a=r[n/8|0]>>(7&n)&1),I(t,e),I(e,e),A(e,t,a)}function L(e,t){var r=[P(),P(),P(),P()];k(r[0],g),k(r[1],v),k(r[2],h),x(r[3],g,v),_(e,r,t)}function k(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function U(e){var t,r,a=1;for(t=0;t<16;++t)r=e[t]+a+65535,a=Math.floor(r/65536),e[t]=r-65536*a;e[0]+=a-1+37*(a-1)}function D(e,t,r){for(var a,n=~(r-1),i=0;i<16;++i)a=n&(e[i]^t[i]),e[i]^=a,t[i]^=a}function P(e){var t,r=new Float64Array(16);if(e)for(t=0;t0&&(s=a.util.fillString(String.fromCharCode(0),c)+s),{encapsulation:t.encrypt(s,"NONE"),key:e.generate(s,i)}},decrypt:function(t,r,a){var n=t.decrypt(r,"NONE");return e.generate(n,a)}};return i},a.kem.kdf1=function(e,t){i(this,e,0,t||e.digestLength)},a.kem.kdf2=function(e,t){i(this,e,1,t||e.digestLength)}},function(e,t,r){var a=r(0);r(1),e.exports=a.log=a.log||{},a.log.levels=["none","error","warning","info","debug","verbose","max"];var n={},i=[],s=null;a.log.LEVEL_LOCKED=2,a.log.NO_LEVEL_CHECK=4,a.log.INTERPOLATE=8;for(var o=0;o0){for(var r=n.create(n.Class.CONTEXT_SPECIFIC,1,!0,[]),i=0;i=r&&s0&&s.value[0].value.push(n.create(n.Class.CONTEXT_SPECIFIC,0,!0,t)),i.length>0&&s.value[0].value.push(n.create(n.Class.CONTEXT_SPECIFIC,1,!0,i)),s.value[0].value.push(n.create(n.Class.UNIVERSAL,n.Type.SET,!0,e.signerInfos)),n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.OID,!1,n.oidToDer(e.type).getBytes()),s])},addSigner:function(t){var r=t.issuer,n=t.serialNumber;if(t.certificate){var i=t.certificate;"string"==typeof i&&(i=a.pki.certificateFromPem(i)),r=i.issuer.attributes,n=i.serialNumber}var s=t.key;if(!s)throw new Error("Could not add PKCS#7 signer; no private key specified.");"string"==typeof s&&(s=a.pki.privateKeyFromPem(s));var o=t.digestAlgorithm||a.pki.oids.sha1;switch(o){case a.pki.oids.sha1:case a.pki.oids.sha256:case a.pki.oids.sha384:case a.pki.oids.sha512:case a.pki.oids.md5:break;default:throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+o)}var c=t.authenticatedAttributes||[];if(c.length>0){for(var u=!1,l=!1,p=0;p="8"&&(r="00"+r);var n=a.util.hexToBytes(r);e.putInt32(n.length),e.putBytes(n)}function s(e,t){e.putInt32(t.length),e.putString(t)}function o(){for(var e=a.md.sha1.create(),t=arguments.length,r=0;r=0);var u=o.modPow(s,t);if(0!==u.compareTo(a.ONE)&&0!==u.compareTo(i)){for(var f=r;--f;){if(0===(u=u.modPowInt(2,t)).compareTo(a.ONE))return!1;if(0===u.compareTo(i))break}if(0===f)return!1}}var p;return!0}(t)}},function(t,i,r){var o,s=r(0);t.exports=s.jsbn=s.jsbn||{};function e(t,i,r){this.data=[],null!=t&&("number"==typeof t?this.fromNumber(t,i,r):null==i&&"string"!=typeof t?this.fromString(t,256):this.fromString(t,i))}function a(){return new e(null)}function n(t,i,r,o,s,e){for(var a=16383&i,n=i>>14;--e>=0;){var h=16383&this.data[t],u=this.data[t++]>>14,f=n*h+u*a;s=((h=a*h+((16383&f)<<14)+r.data[o]+s)>>28)+(f>>14)+n*u,r.data[o++]=268435455&h}return s}s.jsbn.BigInteger=e,"undefined"==typeof navigator?(e.prototype.am=n,o=28):"Microsoft Internet Explorer"==navigator.appName?(e.prototype.am=function(t,i,r,o,s,e){for(var a=32767&i,n=i>>15;--e>=0;){var h=32767&this.data[t],u=this.data[t++]>>15,f=n*h+u*a;s=((h=a*h+((32767&f)<<15)+r.data[o]+(1073741823&s))>>>30)+(f>>>15)+n*u+(s>>>30),r.data[o++]=1073741823&h}return s},o=30):"Netscape"!=navigator.appName?(e.prototype.am=function(t,i,r,o,s,e){for(;--e>=0;){var a=i*this.data[t++]+r.data[o]+s;s=Math.floor(a/67108864),r.data[o++]=67108863&a}return s},o=26):(e.prototype.am=n,o=28),e.prototype.DB=o,e.prototype.DM=(1<>>16)&&(t=i,r+=16),0!=(i=t>>8)&&(t=i,r+=8),0!=(i=t>>4)&&(t=i,r+=4),0!=(i=t>>2)&&(t=i,r+=2),0!=(i=t>>1)&&(t=i,r+=1),r}function l(t){this.m=t}function v(t){this.m=t,this.mp=t.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<>=16,i+=16),0==(255&t)&&(t>>=8,i+=8),0==(15&t)&&(t>>=4,i+=4),0==(3&t)&&(t>>=2,i+=2),0==(1&t)&&++i,i}function B(t){for(var i=0;0!=t;)t&=t-1,++i;return i}function S(){}function M(t){return t}function w(t){this.r2=a(),this.q3=a(),e.ONE.dlShiftTo(2*t.t,this.r2),this.mu=this.r2.divide(t),this.m=t}l.prototype.convert=function(t){return t.s<0||t.compareTo(this.m)>=0?t.mod(this.m):t},l.prototype.revert=function(t){return t},l.prototype.reduce=function(t){t.divRemTo(this.m,null,t)},l.prototype.mulTo=function(t,i,r){t.multiplyTo(i,r),this.reduce(r)},l.prototype.sqrTo=function(t,i){t.squareTo(i),this.reduce(i)},v.prototype.convert=function(t){var i=a();return t.abs().dlShiftTo(this.m.t,i),i.divRemTo(this.m,null,i),t.s<0&&i.compareTo(e.ZERO)>0&&this.m.subTo(i,i),i},v.prototype.revert=function(t){var i=a();return t.copyTo(i),this.reduce(i),i},v.prototype.reduce=function(t){for(;t.t<=this.mt2;)t.data[t.t++]=0;for(var i=0;i>15)*this.mpl&this.um)<<15)&t.DM;for(r=i+this.m.t,t.data[r]+=this.m.am(0,o,t,i,0,this.m.t);t.data[r]>=t.DV;)t.data[r]-=t.DV,t.data[++r]++}t.clamp(),t.drShiftTo(this.m.t,t),t.compareTo(this.m)>=0&&t.subTo(this.m,t)},v.prototype.mulTo=function(t,i,r){t.multiplyTo(i,r),this.reduce(r)},v.prototype.sqrTo=function(t,i){t.squareTo(i),this.reduce(i)},e.prototype.copyTo=function(t){for(var i=this.t-1;i>=0;--i)t.data[i]=this.data[i];t.t=this.t,t.s=this.s},e.prototype.fromInt=function(t){this.t=1,this.s=t<0?-1:0,t>0?this.data[0]=t:t<-1?this.data[0]=t+this.DV:this.t=0},e.prototype.fromString=function(t,i){var r;if(16==i)r=4;else if(8==i)r=3;else if(256==i)r=8;else if(2==i)r=1;else if(32==i)r=5;else{if(4!=i)return void this.fromRadix(t,i);r=2}this.t=0,this.s=0;for(var o=t.length,s=!1,a=0;--o>=0;){var n=8==r?255&t[o]:d(t,o);n<0?"-"==t.charAt(o)&&(s=!0):(s=!1,0==a?this.data[this.t++]=n:a+r>this.DB?(this.data[this.t-1]|=(n&(1<>this.DB-a):this.data[this.t-1]|=n<=this.DB&&(a-=this.DB))}8==r&&0!=(128&t[0])&&(this.s=-1,a>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==t;)--this.t},e.prototype.dlShiftTo=function(t,i){var r;for(r=this.t-1;r>=0;--r)i.data[r+t]=this.data[r];for(r=t-1;r>=0;--r)i.data[r]=0;i.t=this.t+t,i.s=this.s},e.prototype.drShiftTo=function(t,i){for(var r=t;r=0;--r)i.data[r+a+1]=this.data[r]>>s|n,n=(this.data[r]&e)<=0;--r)i.data[r]=0;i.data[a]=n,i.t=this.t+a+1,i.s=this.s,i.clamp()},e.prototype.rShiftTo=function(t,i){i.s=this.s;var r=Math.floor(t/this.DB);if(r>=this.t)i.t=0;else{var o=t%this.DB,s=this.DB-o,e=(1<>o;for(var a=r+1;a>o;o>0&&(i.data[this.t-r-1]|=(this.s&e)<>=this.DB;if(t.t>=this.DB;o+=this.s}else{for(o+=this.s;r>=this.DB;o-=t.s}i.s=o<0?-1:0,o<-1?i.data[r++]=this.DV+o:o>0&&(i.data[r++]=o),i.t=r,i.clamp()},e.prototype.multiplyTo=function(t,i){var r=this.abs(),o=t.abs(),s=r.t;for(i.t=s+o.t;--s>=0;)i.data[s]=0;for(s=0;s=0;)t.data[r]=0;for(r=0;r=i.DV&&(t.data[r+i.t]-=i.DV,t.data[r+i.t+1]=1)}t.t>0&&(t.data[t.t-1]+=i.am(r,i.data[r],t,2*r,0,1)),t.s=0,t.clamp()},e.prototype.divRemTo=function(t,i,r){var o=t.abs();if(!(o.t<=0)){var s=this.abs();if(s.t0?(o.lShiftTo(f,n),s.lShiftTo(f,r)):(o.copyTo(n),s.copyTo(r));var p=n.t,d=n.data[p-1];if(0!=d){var c=d*(1<1?n.data[p-2]>>this.F2:0),l=this.FV/c,v=(1<=0&&(r.data[r.t++]=1,r.subTo(g,r)),e.ONE.dlShiftTo(p,g),g.subTo(n,n);n.t=0;){var D=r.data[--y]==d?this.DM:Math.floor(r.data[y]*l+(r.data[y-1]+T)*v);if((r.data[y]+=n.am(0,D,r,b,0,p))0&&r.rShiftTo(f,r),h<0&&e.ZERO.subTo(r,r)}}},e.prototype.invDigit=function(){if(this.t<1)return 0;var t=this.data[0];if(0==(1&t))return 0;var i=3&t;return(i=(i=(i=(i=i*(2-(15&t)*i)&15)*(2-(255&t)*i)&255)*(2-((65535&t)*i&65535))&65535)*(2-t*i%this.DV)%this.DV)>0?this.DV-i:-i},e.prototype.isEven=function(){return 0==(this.t>0?1&this.data[0]:this.s)},e.prototype.exp=function(t,i){if(t>4294967295||t<1)return e.ONE;var r=a(),o=a(),s=i.convert(this),n=m(t)-1;for(s.copyTo(r);--n>=0;)if(i.sqrTo(r,o),(t&1<0)i.mulTo(o,s,r);else{var h=r;r=o,o=h}return i.revert(r)},e.prototype.toString=function(t){if(this.s<0)return"-"+this.negate().toString(t);var i;if(16==t)i=4;else if(8==t)i=3;else if(2==t)i=1;else if(32==t)i=5;else{if(4!=t)return this.toRadix(t);i=2}var r,o=(1<0)for(n>n)>0&&(s=!0,e=p(r));a>=0;)n>(n+=this.DB-i)):(r=this.data[a]>>(n-=i)&o,n<=0&&(n+=this.DB,--a)),r>0&&(s=!0),s&&(e+=p(r));return s?e:"0"},e.prototype.negate=function(){var t=a();return e.ZERO.subTo(this,t),t},e.prototype.abs=function(){return this.s<0?this.negate():this},e.prototype.compareTo=function(t){var i=this.s-t.s;if(0!=i)return i;var r=this.t;if(0!=(i=r-t.t))return this.s<0?-i:i;for(;--r>=0;)if(0!=(i=this.data[r]-t.data[r]))return i;return 0},e.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+m(this.data[this.t-1]^this.s&this.DM)},e.prototype.mod=function(t){var i=a();return this.abs().divRemTo(t,null,i),this.s<0&&i.compareTo(e.ZERO)>0&&t.subTo(i,i),i},e.prototype.modPowInt=function(t,i){var r;return r=t<256||i.isEven()?new l(i):new v(i),this.exp(t,r)},e.ZERO=c(0),e.ONE=c(1),S.prototype.convert=M,S.prototype.revert=M,S.prototype.mulTo=function(t,i,r){t.multiplyTo(i,r)},S.prototype.sqrTo=function(t,i){t.squareTo(i)},w.prototype.convert=function(t){if(t.s<0||t.t>2*this.m.t)return t.mod(this.m);if(t.compareTo(this.m)<0)return t;var i=a();return t.copyTo(i),this.reduce(i),i},w.prototype.revert=function(t){return t},w.prototype.reduce=function(t){for(t.drShiftTo(this.m.t-1,this.r2),t.t>this.m.t+1&&(t.t=this.m.t+1,t.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);t.compareTo(this.r2)<0;)t.dAddOffset(1,this.m.t+1);for(t.subTo(this.r2,t);t.compareTo(this.m)>=0;)t.subTo(this.m,t)},w.prototype.mulTo=function(t,i,r){t.multiplyTo(i,r),this.reduce(r)},w.prototype.sqrTo=function(t,i){t.squareTo(i),this.reduce(i)};var E=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],O=(1<<26)/E[E.length-1];e.prototype.chunkSize=function(t){return Math.floor(Math.LN2*this.DB/Math.log(t))},e.prototype.toRadix=function(t){if(null==t&&(t=10),0==this.signum()||t<2||t>36)return"0";var i=this.chunkSize(t),r=Math.pow(t,i),o=c(r),s=a(),e=a(),n="";for(this.divRemTo(o,s,e);s.signum()>0;)n=(r+e.intValue()).toString(t).substr(1)+n,s.divRemTo(o,s,e);return e.intValue().toString(t)+n},e.prototype.fromRadix=function(t,i){this.fromInt(0),null==i&&(i=10);for(var r=this.chunkSize(i),o=Math.pow(i,r),s=!1,a=0,n=0,h=0;h=r&&(this.dMultiply(o),this.dAddOffset(n,0),a=0,n=0))}a>0&&(this.dMultiply(Math.pow(i,a)),this.dAddOffset(n,0)),s&&e.ZERO.subTo(this,this)},e.prototype.fromNumber=function(t,i,r){if("number"==typeof i)if(t<2)this.fromInt(1);else for(this.fromNumber(t,r),this.testBit(t-1)||this.bitwiseTo(e.ONE.shiftLeft(t-1),y,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(i);)this.dAddOffset(2,0),this.bitLength()>t&&this.subTo(e.ONE.shiftLeft(t-1),this);else{var o=new Array,s=7&t;o.length=1+(t>>3),i.nextBytes(o),s>0?o[0]&=(1<>=this.DB;if(t.t>=this.DB;o+=this.s}else{for(o+=this.s;r>=this.DB;o+=t.s}i.s=o<0?-1:0,o>0?i.data[r++]=o:o<-1&&(i.data[r++]=this.DV+o),i.t=r,i.clamp()},e.prototype.dMultiply=function(t){this.data[this.t]=this.am(0,t-1,this,0,0,this.t),++this.t,this.clamp()},e.prototype.dAddOffset=function(t,i){if(0!=t){for(;this.t<=i;)this.data[this.t++]=0;for(this.data[i]+=t;this.data[i]>=this.DV;)this.data[i]-=this.DV,++i>=this.t&&(this.data[this.t++]=0),++this.data[i]}},e.prototype.multiplyLowerTo=function(t,i,r){var o,s=Math.min(this.t+t.t,i);for(r.s=0,r.t=s;s>0;)r.data[--s]=0;for(o=r.t-this.t;s=0;)r.data[o]=0;for(o=Math.max(i-this.t,0);o0)if(0==i)r=this.data[0]%t;else for(var o=this.t-1;o>=0;--o)r=(i*r+this.data[o])%t;return r},e.prototype.millerRabin=function(t){var i=this.subtract(e.ONE),r=i.getLowestSetBit();if(r<=0)return!1;for(var o,s=i.shiftRight(r),a={nextBytes:function(t){for(var i=0;i=0);var h=o.modPow(s,this);if(0!=h.compareTo(e.ONE)&&0!=h.compareTo(i)){for(var u=1;u++>24},e.prototype.shortValue=function(){return 0==this.t?this.s:this.data[0]<<16>>16},e.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this.data[0]<=0?0:1},e.prototype.toByteArray=function(){var t=this.t,i=new Array;i[0]=this.s;var r,o=this.DB-t*this.DB%8,s=0;if(t-- >0)for(o>o)!=(this.s&this.DM)>>o&&(i[s++]=r|this.s<=0;)o<8?(r=(this.data[t]&(1<>(o+=this.DB-8)):(r=this.data[t]>>(o-=8)&255,o<=0&&(o+=this.DB,--t)),0!=(128&r)&&(r|=-256),0==s&&(128&this.s)!=(128&r)&&++s,(s>0||r!=this.s)&&(i[s++]=r);return i},e.prototype.equals=function(t){return 0==this.compareTo(t)},e.prototype.min=function(t){return this.compareTo(t)<0?this:t},e.prototype.max=function(t){return this.compareTo(t)>0?this:t},e.prototype.and=function(t){var i=a();return this.bitwiseTo(t,T,i),i},e.prototype.or=function(t){var i=a();return this.bitwiseTo(t,y,i),i},e.prototype.xor=function(t){var i=a();return this.bitwiseTo(t,b,i),i},e.prototype.andNot=function(t){var i=a();return this.bitwiseTo(t,g,i),i},e.prototype.not=function(){for(var t=a(),i=0;i=this.t?0!=this.s:0!=(this.data[i]&1<1){var p=a();for(o.sqrTo(n[1],p);h<=f;)n[h]=a(),o.mulTo(p,n[h-2],n[h]),h+=2}var d,T,y=t.t-1,b=!0,g=a();for(s=m(t.data[y])-1;y>=0;){for(s>=u?d=t.data[y]>>s-u&f:(d=(t.data[y]&(1<0&&(d|=t.data[y-1]>>this.DB+s-u)),h=r;0==(1&d);)d>>=1,--h;if((s-=h)<0&&(s+=this.DB,--y),b)n[d].copyTo(e),b=!1;else{for(;h>1;)o.sqrTo(e,g),o.sqrTo(g,e),h-=2;h>0?o.sqrTo(e,g):(T=e,e=g,g=T),o.mulTo(g,n[d],e)}for(;y>=0&&0==(t.data[y]&1<=0?(r.subTo(o,r),i&&s.subTo(n,s),a.subTo(h,a)):(o.subTo(r,o),i&&n.subTo(s,n),h.subTo(a,h))}return 0!=o.compareTo(e.ONE)?e.ZERO:h.compareTo(t)>=0?h.subtract(t):h.signum()<0?(h.addTo(t,h),h.signum()<0?h.add(t):h):h},e.prototype.pow=function(t){return this.exp(t,new S)},e.prototype.gcd=function(t){var i=this.s<0?this.negate():this.clone(),r=t.s<0?t.negate():t.clone();if(i.compareTo(r)<0){var o=i;i=r,r=o}var s=i.getLowestSetBit(),e=r.getLowestSetBit();if(e<0)return i;for(s0&&(i.rShiftTo(e,i),r.rShiftTo(e,r));i.signum()>0;)(s=i.getLowestSetBit())>0&&i.rShiftTo(s,i),(s=r.getLowestSetBit())>0&&r.rShiftTo(s,r),i.compareTo(r)>=0?(i.subTo(r,i),i.r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2*MAm4#}Z}`G7FET)W5PJjp z5#%T78^|vvy)`rH*@EsbYQALfm4dG`-1j7|96j`_VZ!s!lZmnO;%G09!u=XCj+U%C zo5M5A{$}W2I2m3>WqeyidPzayS#3wKJy+B#`KvxM4x;70)tVF_{XHznt*dP3fWNEL z<0HGS`FIsyR9b8QIc}j4wy;)ft6yuYJ|qHna`nMTV6LH>l3w>$Q;W@Kg8@Ia_;jd- z6FK}M5&&P2wb{L@?ZI_eVO@%X?b++$x>Q%v-uJRMLasY$li8ag^K8;S#O-lOMcd5A zaJu5V%v3pNt$Q_-H^+fgb|H~;P4iaozuSk9#M<@v|^GR}HxJFYi& zitA4)6F2eA8#PC=p~6?GlFjW&8@1|dct{hS5tX>_**k42$qyhj&`z~A{0CK(WOSE@ zzsGiQ*&!9~m3A7JIcjQKhJJ??GAo~oGNo{zD=+wtsF;%6k!+%+T97ZRzJx!RkR|q` zD%z76xU8vO)+xcKA5*xMeUgP%bn3MVBpq)zv=b^?09^^KDV4Mph(4+QX909ksSZE( zQuK0eUIjHfr-D^Gsi5;T)0nL)jO~JgRZQSva=)^(IQx`}cBSSgu-0?h@sr@sIDQ)Z zS;tqwpL6^y_z&a*9L<+?BH+BMFoy~k96t|!$?*%|msPZ7uNL-xTheaBZ!Y1j{wDW{ N=}kMC{SRmsVf86^2=M>_ literal 0 HcmV?d00001 diff --git a/node_modules/node-forge/lib/aes.js b/node_modules/node-forge/lib/aes.js new file mode 100644 index 0000000..5bdd2ac --- /dev/null +++ b/node_modules/node-forge/lib/aes.js @@ -0,0 +1,1091 @@ +/** + * Advanced Encryption Standard (AES) implementation. + * + * This implementation is based on the public domain library 'jscrypto' which + * was written by: + * + * Emily Stark (estark@stanford.edu) + * Mike Hamburg (mhamburg@stanford.edu) + * Dan Boneh (dabo@cs.stanford.edu) + * + * Parts of this code are based on the OpenSSL implementation of AES: + * http://www.openssl.org + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./cipher'); +require('./cipherModes'); +require('./util'); + +/* AES API */ +module.exports = forge.aes = forge.aes || {}; + +/** + * Deprecated. Instead, use: + * + * var cipher = forge.cipher.createCipher('AES-', key); + * cipher.start({iv: iv}); + * + * Creates an AES cipher object to encrypt data using the given symmetric key. + * The output will be stored in the 'output' member of the returned cipher. + * + * The key and iv may be given as a string of bytes, an array of bytes, + * a byte buffer, or an array of 32-bit words. + * + * @param key the symmetric key to use. + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge.aes.startEncrypting = function(key, iv, output, mode) { + var cipher = _createCipher({ + key: key, + output: output, + decrypt: false, + mode: mode + }); + cipher.start(iv); + return cipher; +}; + +/** + * Deprecated. Instead, use: + * + * var cipher = forge.cipher.createCipher('AES-', key); + * + * Creates an AES cipher object to encrypt data using the given symmetric key. + * + * The key may be given as a string of bytes, an array of bytes, a + * byte buffer, or an array of 32-bit words. + * + * @param key the symmetric key to use. + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge.aes.createEncryptionCipher = function(key, mode) { + return _createCipher({ + key: key, + output: null, + decrypt: false, + mode: mode + }); +}; + +/** + * Deprecated. Instead, use: + * + * var decipher = forge.cipher.createDecipher('AES-', key); + * decipher.start({iv: iv}); + * + * Creates an AES cipher object to decrypt data using the given symmetric key. + * The output will be stored in the 'output' member of the returned cipher. + * + * The key and iv may be given as a string of bytes, an array of bytes, + * a byte buffer, or an array of 32-bit words. + * + * @param key the symmetric key to use. + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge.aes.startDecrypting = function(key, iv, output, mode) { + var cipher = _createCipher({ + key: key, + output: output, + decrypt: true, + mode: mode + }); + cipher.start(iv); + return cipher; +}; + +/** + * Deprecated. Instead, use: + * + * var decipher = forge.cipher.createDecipher('AES-', key); + * + * Creates an AES cipher object to decrypt data using the given symmetric key. + * + * The key may be given as a string of bytes, an array of bytes, a + * byte buffer, or an array of 32-bit words. + * + * @param key the symmetric key to use. + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge.aes.createDecryptionCipher = function(key, mode) { + return _createCipher({ + key: key, + output: null, + decrypt: true, + mode: mode + }); +}; + +/** + * Creates a new AES cipher algorithm object. + * + * @param name the name of the algorithm. + * @param mode the mode factory function. + * + * @return the AES algorithm object. + */ +forge.aes.Algorithm = function(name, mode) { + if(!init) { + initialize(); + } + var self = this; + self.name = name; + self.mode = new mode({ + blockSize: 16, + cipher: { + encrypt: function(inBlock, outBlock) { + return _updateBlock(self._w, inBlock, outBlock, false); + }, + decrypt: function(inBlock, outBlock) { + return _updateBlock(self._w, inBlock, outBlock, true); + } + } + }); + self._init = false; +}; + +/** + * Initializes this AES algorithm by expanding its key. + * + * @param options the options to use. + * key the key to use with this algorithm. + * decrypt true if the algorithm should be initialized for decryption, + * false for encryption. + */ +forge.aes.Algorithm.prototype.initialize = function(options) { + if(this._init) { + return; + } + + var key = options.key; + var tmp; + + /* Note: The key may be a string of bytes, an array of bytes, a byte + buffer, or an array of 32-bit integers. If the key is in bytes, then + it must be 16, 24, or 32 bytes in length. If it is in 32-bit + integers, it must be 4, 6, or 8 integers long. */ + + if(typeof key === 'string' && + (key.length === 16 || key.length === 24 || key.length === 32)) { + // convert key string into byte buffer + key = forge.util.createBuffer(key); + } else if(forge.util.isArray(key) && + (key.length === 16 || key.length === 24 || key.length === 32)) { + // convert key integer array into byte buffer + tmp = key; + key = forge.util.createBuffer(); + for(var i = 0; i < tmp.length; ++i) { + key.putByte(tmp[i]); + } + } + + // convert key byte buffer into 32-bit integer array + if(!forge.util.isArray(key)) { + tmp = key; + key = []; + + // key lengths of 16, 24, 32 bytes allowed + var len = tmp.length(); + if(len === 16 || len === 24 || len === 32) { + len = len >>> 2; + for(var i = 0; i < len; ++i) { + key.push(tmp.getInt32()); + } + } + } + + // key must be an array of 32-bit integers by now + if(!forge.util.isArray(key) || + !(key.length === 4 || key.length === 6 || key.length === 8)) { + throw new Error('Invalid key parameter.'); + } + + // encryption operation is always used for these modes + var mode = this.mode.name; + var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1); + + // do key expansion + this._w = _expandKey(key, options.decrypt && !encryptOp); + this._init = true; +}; + +/** + * Expands a key. Typically only used for testing. + * + * @param key the symmetric key to expand, as an array of 32-bit words. + * @param decrypt true to expand for decryption, false for encryption. + * + * @return the expanded key. + */ +forge.aes._expandKey = function(key, decrypt) { + if(!init) { + initialize(); + } + return _expandKey(key, decrypt); +}; + +/** + * Updates a single block. Typically only used for testing. + * + * @param w the expanded key to use. + * @param input an array of block-size 32-bit words. + * @param output an array of block-size 32-bit words. + * @param decrypt true to decrypt, false to encrypt. + */ +forge.aes._updateBlock = _updateBlock; + +/** Register AES algorithms **/ + +registerAlgorithm('AES-ECB', forge.cipher.modes.ecb); +registerAlgorithm('AES-CBC', forge.cipher.modes.cbc); +registerAlgorithm('AES-CFB', forge.cipher.modes.cfb); +registerAlgorithm('AES-OFB', forge.cipher.modes.ofb); +registerAlgorithm('AES-CTR', forge.cipher.modes.ctr); +registerAlgorithm('AES-GCM', forge.cipher.modes.gcm); + +function registerAlgorithm(name, mode) { + var factory = function() { + return new forge.aes.Algorithm(name, mode); + }; + forge.cipher.registerAlgorithm(name, factory); +} + +/** AES implementation **/ + +var init = false; // not yet initialized +var Nb = 4; // number of words comprising the state (AES = 4) +var sbox; // non-linear substitution table used in key expansion +var isbox; // inversion of sbox +var rcon; // round constant word array +var mix; // mix-columns table +var imix; // inverse mix-columns table + +/** + * Performs initialization, ie: precomputes tables to optimize for speed. + * + * One way to understand how AES works is to imagine that 'addition' and + * 'multiplication' are interfaces that require certain mathematical + * properties to hold true (ie: they are associative) but they might have + * different implementations and produce different kinds of results ... + * provided that their mathematical properties remain true. AES defines + * its own methods of addition and multiplication but keeps some important + * properties the same, ie: associativity and distributivity. The + * explanation below tries to shed some light on how AES defines addition + * and multiplication of bytes and 32-bit words in order to perform its + * encryption and decryption algorithms. + * + * The basics: + * + * The AES algorithm views bytes as binary representations of polynomials + * that have either 1 or 0 as the coefficients. It defines the addition + * or subtraction of two bytes as the XOR operation. It also defines the + * multiplication of two bytes as a finite field referred to as GF(2^8) + * (Note: 'GF' means "Galois Field" which is a field that contains a finite + * number of elements so GF(2^8) has 256 elements). + * + * This means that any two bytes can be represented as binary polynomials; + * when they multiplied together and modularly reduced by an irreducible + * polynomial of the 8th degree, the results are the field GF(2^8). The + * specific irreducible polynomial that AES uses in hexadecimal is 0x11b. + * This multiplication is associative with 0x01 as the identity: + * + * (b * 0x01 = GF(b, 0x01) = b). + * + * The operation GF(b, 0x02) can be performed at the byte level by left + * shifting b once and then XOR'ing it (to perform the modular reduction) + * with 0x11b if b is >= 128. Repeated application of the multiplication + * of 0x02 can be used to implement the multiplication of any two bytes. + * + * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can + * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these + * factors can each be multiplied by 0x57 and then added together. To do + * the multiplication, values for 0x57 multiplied by each of these 3 factors + * can be precomputed and stored in a table. To add them, the values from + * the table are XOR'd together. + * + * AES also defines addition and multiplication of words, that is 4-byte + * numbers represented as polynomials of 3 degrees where the coefficients + * are the values of the bytes. + * + * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0. + * + * Addition is performed by XOR'ing like powers of x. Multiplication + * is performed in two steps, the first is an algebraic expansion as + * you would do normally (where addition is XOR). But the result is + * a polynomial larger than 3 degrees and thus it cannot fit in a word. So + * next the result is modularly reduced by an AES-specific polynomial of + * degree 4 which will always produce a polynomial of less than 4 degrees + * such that it will fit in a word. In AES, this polynomial is x^4 + 1. + * + * The modular product of two polynomials 'a' and 'b' is thus: + * + * d(x) = d3x^3 + d2x^2 + d1x + d0 + * with + * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3) + * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3) + * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3) + * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3) + * + * As a matrix: + * + * [d0] = [a0 a3 a2 a1][b0] + * [d1] [a1 a0 a3 a2][b1] + * [d2] [a2 a1 a0 a3][b2] + * [d3] [a3 a2 a1 a0][b3] + * + * Special polynomials defined by AES (0x02 == {02}): + * a(x) = {03}x^3 + {01}x^2 + {01}x + {02} + * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}. + * + * These polynomials are used in the MixColumns() and InverseMixColumns() + * operations, respectively, to cause each element in the state to affect + * the output (referred to as diffusing). + * + * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the + * polynomial x3. + * + * The ShiftRows() method modifies the last 3 rows in the state (where + * the state is 4 words with 4 bytes per word) by shifting bytes cyclically. + * The 1st byte in the second row is moved to the end of the row. The 1st + * and 2nd bytes in the third row are moved to the end of the row. The 1st, + * 2nd, and 3rd bytes are moved in the fourth row. + * + * More details on how AES arithmetic works: + * + * In the polynomial representation of binary numbers, XOR performs addition + * and subtraction and multiplication in GF(2^8) denoted as GF(a, b) + * corresponds with the multiplication of polynomials modulo an irreducible + * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply + * polynomial 'a' with polynomial 'b' and then do a modular reduction by + * an AES-specific irreducible polynomial of degree 8. + * + * A polynomial is irreducible if its only divisors are one and itself. For + * the AES algorithm, this irreducible polynomial is: + * + * m(x) = x^8 + x^4 + x^3 + x + 1, + * + * or {01}{1b} in hexadecimal notation, where each coefficient is a bit: + * 100011011 = 283 = 0x11b. + * + * For example, GF(0x57, 0x83) = 0xc1 because + * + * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 1 + * 0x85 = 131 = 10000101 = x^7 + x + 1 + * + * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1) + * = x^13 + x^11 + x^9 + x^8 + x^7 + + * x^7 + x^5 + x^3 + x^2 + x + + * x^6 + x^4 + x^2 + x + 1 + * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y + * y modulo (x^8 + x^4 + x^3 + x + 1) + * = x^7 + x^6 + 1. + * + * The modular reduction by m(x) guarantees the result will be a binary + * polynomial of less than degree 8, so that it can fit in a byte. + * + * The operation to multiply a binary polynomial b with x (the polynomial + * x in binary representation is 00000010) is: + * + * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^1 + * + * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the + * most significant bit is 0 in b) then the result is already reduced. If + * it is 1, then we can reduce it by subtracting m(x) via an XOR. + * + * It follows that multiplication by x (00000010 or 0x02) can be implemented + * by performing a left shift followed by a conditional bitwise XOR with + * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by + * higher powers of x can be implemented by repeated application of xtime(). + * + * By adding intermediate results, multiplication by any constant can be + * implemented. For instance: + * + * GF(0x57, 0x13) = 0xfe because: + * + * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1) + * + * Note: We XOR with 0x11b instead of 0x1b because in javascript our + * datatype for b can be larger than 1 byte, so a left shift will not + * automatically eliminate bits that overflow a byte ... by XOR'ing the + * overflow bit with 1 (the extra one from 0x11b) we zero it out. + * + * GF(0x57, 0x02) = xtime(0x57) = 0xae + * GF(0x57, 0x04) = xtime(0xae) = 0x47 + * GF(0x57, 0x08) = xtime(0x47) = 0x8e + * GF(0x57, 0x10) = xtime(0x8e) = 0x07 + * + * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10)) + * + * And by the distributive property (since XOR is addition and GF() is + * multiplication): + * + * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10) + * = 0x57 ^ 0xae ^ 0x07 + * = 0xfe. + */ +function initialize() { + init = true; + + /* Populate the Rcon table. These are the values given by + [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02) + in the field of GF(2^8), where i starts at 1. + + rcon[0] = [0x00, 0x00, 0x00, 0x00] + rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 1 + rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 2 + ... + rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B + rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x36 + + We only store the first byte because it is the only one used. + */ + rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36]; + + // compute xtime table which maps i onto GF(i, 0x02) + var xtime = new Array(256); + for(var i = 0; i < 128; ++i) { + xtime[i] = i << 1; + xtime[i + 128] = (i + 128) << 1 ^ 0x11B; + } + + // compute all other tables + sbox = new Array(256); + isbox = new Array(256); + mix = new Array(4); + imix = new Array(4); + for(var i = 0; i < 4; ++i) { + mix[i] = new Array(256); + imix[i] = new Array(256); + } + var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime; + for(var i = 0; i < 256; ++i) { + /* We need to generate the SubBytes() sbox and isbox tables so that + we can perform byte substitutions. This requires us to traverse + all of the elements in GF, find their multiplicative inverses, + and apply to each the following affine transformation: + + bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^ + b(i + 7) mod 8 ^ ci + for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the + ith bit of a byte c with the value {63} or {01100011}. + + It is possible to traverse every possible value in a Galois field + using what is referred to as a 'generator'. There are many + generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully + traverse GF we iterate 255 times, multiplying by our generator + each time. + + On each iteration we can determine the multiplicative inverse for + the current element. + + Suppose there is an element in GF 'e'. For a given generator 'g', + e = g^x. The multiplicative inverse of e is g^(255 - x). It turns + out that if use the inverse of a generator as another generator + it will produce all of the corresponding multiplicative inverses + at the same time. For this reason, we choose 5 as our inverse + generator because it only requires 2 multiplies and 1 add and its + inverse, 82, requires relatively few operations as well. + + In order to apply the affine transformation, the multiplicative + inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a + bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and + 'x'. Then 's' is left shifted and the high bit of 's' is made the + low bit. The resulting value is stored in 's'. Then 'x' is XOR'd + with 's' and stored in 'x'. On each subsequent iteration the same + operation is performed. When 4 iterations are complete, 'x' is + XOR'd with 'c' (0x63) and the transformed value is stored in 'x'. + For example: + + s = 01000001 + x = 01000001 + + iteration 1: s = 10000010, x ^= s + iteration 2: s = 00000101, x ^= s + iteration 3: s = 00001010, x ^= s + iteration 4: s = 00010100, x ^= s + x ^= 0x63 + + This can be done with a loop where s = (s << 1) | (s >> 7). However, + it can also be done by using a single 16-bit (in this case 32-bit) + number 'sx'. Since XOR is an associative operation, we can set 'sx' + to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times. + The most significant bits will flow into the high 8 bit positions + and be correctly XOR'd with one another. All that remains will be + to cycle the high 8 bits by XOR'ing them all with the lower 8 bits + afterwards. + + At the same time we're populating sbox and isbox we can precompute + the multiplication we'll need to do to do MixColumns() later. + */ + + // apply affine transformation + sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4); + sx = (sx >> 8) ^ (sx & 255) ^ 0x63; + + // update tables + sbox[e] = sx; + isbox[sx] = e; + + /* Mixing columns is done using matrix multiplication. The columns + that are to be mixed are each a single word in the current state. + The state has Nb columns (4 columns). Therefore each column is a + 4 byte word. So to mix the columns in a single column 'c' where + its rows are r0, r1, r2, and r3, we use the following matrix + multiplication: + + [2 3 1 1]*[r0,c]=[r'0,c] + [1 2 3 1] [r1,c] [r'1,c] + [1 1 2 3] [r2,c] [r'2,c] + [3 1 1 2] [r3,c] [r'3,c] + + r0, r1, r2, and r3 are each 1 byte of one of the words in the + state (a column). To do matrix multiplication for each mixed + column c' we multiply the corresponding row from the left matrix + with the corresponding column from the right matrix. In total, we + get 4 equations: + + r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c + r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c + r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c + r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c + + As usual, the multiplication is as previously defined and the + addition is XOR. In order to optimize mixing columns we can store + the multiplication results in tables. If you think of the whole + column as a word (it might help to visualize by mentally rotating + the equations above by counterclockwise 90 degrees) then you can + see that it would be useful to map the multiplications performed on + each byte (r0, r1, r2, r3) onto a word as well. For instance, we + could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the + highest 8 bits and 3*r0 in the lowest 8 bits (with the other two + respectively in the middle). This means that a table can be + constructed that uses r0 as an index to the word. We can do the + same with r1, r2, and r3, creating a total of 4 tables. + + To construct a full c', we can just look up each byte of c in + their respective tables and XOR the results together. + + Also, to build each table we only have to calculate the word + for 2,1,1,3 for every byte ... which we can do on each iteration + of this loop since we will iterate over every byte. After we have + calculated 2,1,1,3 we can get the results for the other tables + by cycling the byte at the end to the beginning. For instance + we can take the result of table 2,1,1,3 and produce table 3,2,1,1 + by moving the right most byte to the left most position just like + how you can imagine the 3 moved out of 2,1,1,3 and to the front + to produce 3,2,1,1. + + There is another optimization in that the same multiples of + the current element we need in order to advance our generator + to the next iteration can be reused in performing the 2,1,1,3 + calculation. We also calculate the inverse mix column tables, + with e,9,d,b being the inverse of 2,1,1,3. + + When we're done, and we need to actually mix columns, the first + byte of each state word should be put through mix[0] (2,1,1,3), + the second through mix[1] (3,2,1,1) and so forth. Then they should + be XOR'd together to produce the fully mixed column. + */ + + // calculate mix and imix table values + sx2 = xtime[sx]; + e2 = xtime[e]; + e4 = xtime[e2]; + e8 = xtime[e4]; + me = + (sx2 << 24) ^ // 2 + (sx << 16) ^ // 1 + (sx << 8) ^ // 1 + (sx ^ sx2); // 3 + ime = + (e2 ^ e4 ^ e8) << 24 ^ // E (14) + (e ^ e8) << 16 ^ // 9 + (e ^ e4 ^ e8) << 8 ^ // D (13) + (e ^ e2 ^ e8); // B (11) + // produce each of the mix tables by rotating the 2,1,1,3 value + for(var n = 0; n < 4; ++n) { + mix[n][e] = me; + imix[n][sx] = ime; + // cycle the right most byte to the left most position + // ie: 2,1,1,3 becomes 3,2,1,1 + me = me << 24 | me >>> 8; + ime = ime << 24 | ime >>> 8; + } + + // get next element and inverse + if(e === 0) { + // 1 is the inverse of 1 + e = ei = 1; + } else { + // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator) + // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator) + e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]]; + ei ^= xtime[xtime[ei]]; + } + } +} + +/** + * Generates a key schedule using the AES key expansion algorithm. + * + * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion + * routine to generate a key schedule. The Key Expansion generates a total + * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words, + * and each of the Nr rounds requires Nb words of key data. The resulting + * key schedule consists of a linear array of 4-byte words, denoted [wi ], + * with i in the range 0 <= i < Nb(Nr + 1). + * + * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk) + * AES-128 (Nb=4, Nk=4, Nr=10) + * AES-192 (Nb=4, Nk=6, Nr=12) + * AES-256 (Nb=4, Nk=8, Nr=14) + * Note: Nr=Nk+6. + * + * Nb is the number of columns (32-bit words) comprising the State (or + * number of bytes in a block). For AES, Nb=4. + * + * @param key the key to schedule (as an array of 32-bit words). + * @param decrypt true to modify the key schedule to decrypt, false not to. + * + * @return the generated key schedule. + */ +function _expandKey(key, decrypt) { + // copy the key's words to initialize the key schedule + var w = key.slice(0); + + /* RotWord() will rotate a word, moving the first byte to the last + byte's position (shifting the other bytes left). + + We will be getting the value of Rcon at i / Nk. 'i' will iterate + from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in + a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from + 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will + increase by 1. We use a counter iNk to keep track of this. + */ + + // go through the rounds expanding the key + var temp, iNk = 1; + var Nk = w.length; + var Nr1 = Nk + 6 + 1; + var end = Nb * Nr1; + for(var i = Nk; i < end; ++i) { + temp = w[i - 1]; + if(i % Nk === 0) { + // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk] + temp = + sbox[temp >>> 16 & 255] << 24 ^ + sbox[temp >>> 8 & 255] << 16 ^ + sbox[temp & 255] << 8 ^ + sbox[temp >>> 24] ^ (rcon[iNk] << 24); + iNk++; + } else if(Nk > 6 && (i % Nk === 4)) { + // temp = SubWord(temp) + temp = + sbox[temp >>> 24] << 24 ^ + sbox[temp >>> 16 & 255] << 16 ^ + sbox[temp >>> 8 & 255] << 8 ^ + sbox[temp & 255]; + } + w[i] = w[i - Nk] ^ temp; + } + + /* When we are updating a cipher block we always use the code path for + encryption whether we are decrypting or not (to shorten code and + simplify the generation of look up tables). However, because there + are differences in the decryption algorithm, other than just swapping + in different look up tables, we must transform our key schedule to + account for these changes: + + 1. The decryption algorithm gets its key rounds in reverse order. + 2. The decryption algorithm adds the round key before mixing columns + instead of afterwards. + + We don't need to modify our key schedule to handle the first case, + we can just traverse the key schedule in reverse order when decrypting. + + The second case requires a little work. + + The tables we built for performing rounds will take an input and then + perform SubBytes() and MixColumns() or, for the decrypt version, + InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires + us to AddRoundKey() before InvMixColumns(). This means we'll need to + apply some transformations to the round key to inverse-mix its columns + so they'll be correct for moving AddRoundKey() to after the state has + had its columns inverse-mixed. + + To inverse-mix the columns of the state when we're decrypting we use a + lookup table that will apply InvSubBytes() and InvMixColumns() at the + same time. However, the round key's bytes are not inverse-substituted + in the decryption algorithm. To get around this problem, we can first + substitute the bytes in the round key so that when we apply the + transformation via the InvSubBytes()+InvMixColumns() table, it will + undo our substitution leaving us with the original value that we + want -- and then inverse-mix that value. + + This change will correctly alter our key schedule so that we can XOR + each round key with our already transformed decryption state. This + allows us to use the same code path as the encryption algorithm. + + We make one more change to the decryption key. Since the decryption + algorithm runs in reverse from the encryption algorithm, we reverse + the order of the round keys to avoid having to iterate over the key + schedule backwards when running the encryption algorithm later in + decryption mode. In addition to reversing the order of the round keys, + we also swap each round key's 2nd and 4th rows. See the comments + section where rounds are performed for more details about why this is + done. These changes are done inline with the other substitution + described above. + */ + if(decrypt) { + var tmp; + var m0 = imix[0]; + var m1 = imix[1]; + var m2 = imix[2]; + var m3 = imix[3]; + var wnew = w.slice(0); + end = w.length; + for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) { + // do not sub the first or last round key (round keys are Nb + // words) as no column mixing is performed before they are added, + // but do change the key order + if(i === 0 || i === (end - Nb)) { + wnew[i] = w[wi]; + wnew[i + 1] = w[wi + 3]; + wnew[i + 2] = w[wi + 2]; + wnew[i + 3] = w[wi + 1]; + } else { + // substitute each round key byte because the inverse-mix + // table will inverse-substitute it (effectively cancel the + // substitution because round key bytes aren't sub'd in + // decryption mode) and swap indexes 3 and 1 + for(var n = 0; n < Nb; ++n) { + tmp = w[wi + n]; + wnew[i + (3&-n)] = + m0[sbox[tmp >>> 24]] ^ + m1[sbox[tmp >>> 16 & 255]] ^ + m2[sbox[tmp >>> 8 & 255]] ^ + m3[sbox[tmp & 255]]; + } + } + } + w = wnew; + } + + return w; +} + +/** + * Updates a single block (16 bytes) using AES. The update will either + * encrypt or decrypt the block. + * + * @param w the key schedule. + * @param input the input block (an array of 32-bit words). + * @param output the updated output block. + * @param decrypt true to decrypt the block, false to encrypt it. + */ +function _updateBlock(w, input, output, decrypt) { + /* + Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)]) + begin + byte state[4,Nb] + state = in + AddRoundKey(state, w[0, Nb-1]) + for round = 1 step 1 to Nr-1 + SubBytes(state) + ShiftRows(state) + MixColumns(state) + AddRoundKey(state, w[round*Nb, (round+1)*Nb-1]) + end for + SubBytes(state) + ShiftRows(state) + AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) + out = state + end + + InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)]) + begin + byte state[4,Nb] + state = in + AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) + for round = Nr-1 step -1 downto 1 + InvShiftRows(state) + InvSubBytes(state) + AddRoundKey(state, w[round*Nb, (round+1)*Nb-1]) + InvMixColumns(state) + end for + InvShiftRows(state) + InvSubBytes(state) + AddRoundKey(state, w[0, Nb-1]) + out = state + end + */ + + // Encrypt: AddRoundKey(state, w[0, Nb-1]) + // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) + var Nr = w.length / 4 - 1; + var m0, m1, m2, m3, sub; + if(decrypt) { + m0 = imix[0]; + m1 = imix[1]; + m2 = imix[2]; + m3 = imix[3]; + sub = isbox; + } else { + m0 = mix[0]; + m1 = mix[1]; + m2 = mix[2]; + m3 = mix[3]; + sub = sbox; + } + var a, b, c, d, a2, b2, c2; + a = input[0] ^ w[0]; + b = input[decrypt ? 3 : 1] ^ w[1]; + c = input[2] ^ w[2]; + d = input[decrypt ? 1 : 3] ^ w[3]; + var i = 3; + + /* In order to share code we follow the encryption algorithm when both + encrypting and decrypting. To account for the changes required in the + decryption algorithm, we use different lookup tables when decrypting + and use a modified key schedule to account for the difference in the + order of transformations applied when performing rounds. We also get + key rounds in reverse order (relative to encryption). */ + for(var round = 1; round < Nr; ++round) { + /* As described above, we'll be using table lookups to perform the + column mixing. Each column is stored as a word in the state (the + array 'input' has one column as a word at each index). In order to + mix a column, we perform these transformations on each row in c, + which is 1 byte in each word. The new column for c0 is c'0: + + m0 m1 m2 m3 + r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c0 + r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c0 + r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c0 + r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c0 + + So using mix tables where c0 is a word with r0 being its upper + 8 bits and r3 being its lower 8 bits: + + m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0] + ... + m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3] + + Therefore to mix the columns in each word in the state we + do the following (& 255 omitted for brevity): + c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] + c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] + c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] + c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] + + However, before mixing, the algorithm requires us to perform + ShiftRows(). The ShiftRows() transformation cyclically shifts the + last 3 rows of the state over different offsets. The first row + (r = 0) is not shifted. + + s'_r,c = s_r,(c + shift(r, Nb) mod Nb + for 0 < r < 4 and 0 <= c < Nb and + shift(1, 4) = 1 + shift(2, 4) = 2 + shift(3, 4) = 3. + + This causes the first byte in r = 1 to be moved to the end of + the row, the first 2 bytes in r = 2 to be moved to the end of + the row, the first 3 bytes in r = 3 to be moved to the end of + the row: + + r1: [c0 c1 c2 c3] => [c1 c2 c3 c0] + r2: [c0 c1 c2 c3] [c2 c3 c0 c1] + r3: [c0 c1 c2 c3] [c3 c0 c1 c2] + + We can make these substitutions inline with our column mixing to + generate an updated set of equations to produce each word in the + state (note the columns have changed positions): + + c0 c1 c2 c3 => c0 c1 c2 c3 + c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte) + c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes) + c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes) + + Therefore: + + c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c3 + c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c3 + c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c3 + c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c3 + + c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c0 + c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c0 + c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c0 + c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c0 + + ... and so forth for c'2 and c'3. The important distinction is + that the columns are cycling, with c0 being used with the m0 + map when calculating c0, but c1 being used with the m0 map when + calculating c1 ... and so forth. + + When performing the inverse we transform the mirror image and + skip the bottom row, instead of the top one, and move upwards: + + c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption + c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes) + c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption + c3 c2 c1 c0 c3 c2 c1 c0 + + If you compare the resulting matrices for ShiftRows()+MixColumns() + and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are + different (in encrypt mode vs. decrypt mode). So in order to use + the same code to handle both encryption and decryption, we will + need to do some mapping. + + If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r be + a row number in the state, then the resulting matrix in encryption + mode for applying the above transformations would be: + + r1: a b c d + r2: b c d a + r3: c d a b + r4: d a b c + + If we did the same in decryption mode we would get: + + r1: a d c b + r2: b a d c + r3: c b a d + r4: d c b a + + If instead we swap d and b (set b=c3 and d=c1), then we get: + + r1: a b c d + r2: d a b c + r3: c d a b + r4: b c d a + + Now the 1st and 3rd rows are the same as the encryption matrix. All + we need to do then to make the mapping exactly the same is to swap + the 2nd and 4th rows when in decryption mode. To do this without + having to do it on each iteration, we swapped the 2nd and 4th rows + in the decryption key schedule. We also have to do the swap above + when we first pull in the input and when we set the final output. */ + a2 = + m0[a >>> 24] ^ + m1[b >>> 16 & 255] ^ + m2[c >>> 8 & 255] ^ + m3[d & 255] ^ w[++i]; + b2 = + m0[b >>> 24] ^ + m1[c >>> 16 & 255] ^ + m2[d >>> 8 & 255] ^ + m3[a & 255] ^ w[++i]; + c2 = + m0[c >>> 24] ^ + m1[d >>> 16 & 255] ^ + m2[a >>> 8 & 255] ^ + m3[b & 255] ^ w[++i]; + d = + m0[d >>> 24] ^ + m1[a >>> 16 & 255] ^ + m2[b >>> 8 & 255] ^ + m3[c & 255] ^ w[++i]; + a = a2; + b = b2; + c = c2; + } + + /* + Encrypt: + SubBytes(state) + ShiftRows(state) + AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) + + Decrypt: + InvShiftRows(state) + InvSubBytes(state) + AddRoundKey(state, w[0, Nb-1]) + */ + // Note: rows are shifted inline + output[0] = + (sub[a >>> 24] << 24) ^ + (sub[b >>> 16 & 255] << 16) ^ + (sub[c >>> 8 & 255] << 8) ^ + (sub[d & 255]) ^ w[++i]; + output[decrypt ? 3 : 1] = + (sub[b >>> 24] << 24) ^ + (sub[c >>> 16 & 255] << 16) ^ + (sub[d >>> 8 & 255] << 8) ^ + (sub[a & 255]) ^ w[++i]; + output[2] = + (sub[c >>> 24] << 24) ^ + (sub[d >>> 16 & 255] << 16) ^ + (sub[a >>> 8 & 255] << 8) ^ + (sub[b & 255]) ^ w[++i]; + output[decrypt ? 1 : 3] = + (sub[d >>> 24] << 24) ^ + (sub[a >>> 16 & 255] << 16) ^ + (sub[b >>> 8 & 255] << 8) ^ + (sub[c & 255]) ^ w[++i]; +} + +/** + * Deprecated. Instead, use: + * + * forge.cipher.createCipher('AES-', key); + * forge.cipher.createDecipher('AES-', key); + * + * Creates a deprecated AES cipher object. This object's mode will default to + * CBC (cipher-block-chaining). + * + * The key and iv may be given as a string of bytes, an array of bytes, a + * byte buffer, or an array of 32-bit words. + * + * @param options the options to use. + * key the symmetric key to use. + * output the buffer to write to. + * decrypt true for decryption, false for encryption. + * mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +function _createCipher(options) { + options = options || {}; + var mode = (options.mode || 'CBC').toUpperCase(); + var algorithm = 'AES-' + mode; + + var cipher; + if(options.decrypt) { + cipher = forge.cipher.createDecipher(algorithm, options.key); + } else { + cipher = forge.cipher.createCipher(algorithm, options.key); + } + + // backwards compatible start API + var start = cipher.start; + cipher.start = function(iv, options) { + // backwards compatibility: support second arg as output buffer + var output = null; + if(options instanceof forge.util.ByteBuffer) { + output = options; + options = {}; + } + options = options || {}; + options.output = output; + options.iv = iv; + start.call(cipher, options); + }; + + return cipher; +} diff --git a/node_modules/node-forge/lib/aesCipherSuites.js b/node_modules/node-forge/lib/aesCipherSuites.js new file mode 100644 index 0000000..fed60f3 --- /dev/null +++ b/node_modules/node-forge/lib/aesCipherSuites.js @@ -0,0 +1,282 @@ +/** + * A Javascript implementation of AES Cipher Suites for TLS. + * + * @author Dave Longley + * + * Copyright (c) 2009-2015 Digital Bazaar, Inc. + * + */ +var forge = require('./forge'); +require('./aes'); +require('./tls'); + +var tls = module.exports = forge.tls; + +/** + * Supported cipher suites. + */ +tls.CipherSuites['TLS_RSA_WITH_AES_128_CBC_SHA'] = { + id: [0x00, 0x2f], + name: 'TLS_RSA_WITH_AES_128_CBC_SHA', + initSecurityParameters: function(sp) { + sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; + sp.cipher_type = tls.CipherType.block; + sp.enc_key_length = 16; + sp.block_length = 16; + sp.fixed_iv_length = 16; + sp.record_iv_length = 16; + sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; + sp.mac_length = 20; + sp.mac_key_length = 20; + }, + initConnectionState: initConnectionState +}; +tls.CipherSuites['TLS_RSA_WITH_AES_256_CBC_SHA'] = { + id: [0x00, 0x35], + name: 'TLS_RSA_WITH_AES_256_CBC_SHA', + initSecurityParameters: function(sp) { + sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; + sp.cipher_type = tls.CipherType.block; + sp.enc_key_length = 32; + sp.block_length = 16; + sp.fixed_iv_length = 16; + sp.record_iv_length = 16; + sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; + sp.mac_length = 20; + sp.mac_key_length = 20; + }, + initConnectionState: initConnectionState +}; + +function initConnectionState(state, c, sp) { + var client = (c.entity === forge.tls.ConnectionEnd.client); + + // cipher setup + state.read.cipherState = { + init: false, + cipher: forge.cipher.createDecipher('AES-CBC', client ? + sp.keys.server_write_key : sp.keys.client_write_key), + iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV + }; + state.write.cipherState = { + init: false, + cipher: forge.cipher.createCipher('AES-CBC', client ? + sp.keys.client_write_key : sp.keys.server_write_key), + iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV + }; + state.read.cipherFunction = decrypt_aes_cbc_sha1; + state.write.cipherFunction = encrypt_aes_cbc_sha1; + + // MAC setup + state.read.macLength = state.write.macLength = sp.mac_length; + state.read.macFunction = state.write.macFunction = tls.hmac_sha1; +} + +/** + * Encrypts the TLSCompressed record into a TLSCipherText record using AES + * in CBC mode. + * + * @param record the TLSCompressed record to encrypt. + * @param s the ConnectionState to use. + * + * @return true on success, false on failure. + */ +function encrypt_aes_cbc_sha1(record, s) { + var rval = false; + + // append MAC to fragment, update sequence number + var mac = s.macFunction(s.macKey, s.sequenceNumber, record); + record.fragment.putBytes(mac); + s.updateSequenceNumber(); + + // TLS 1.1+ use an explicit IV every time to protect against CBC attacks + var iv; + if(record.version.minor === tls.Versions.TLS_1_0.minor) { + // use the pre-generated IV when initializing for TLS 1.0, otherwise use + // the residue from the previous encryption + iv = s.cipherState.init ? null : s.cipherState.iv; + } else { + iv = forge.random.getBytesSync(16); + } + + s.cipherState.init = true; + + // start cipher + var cipher = s.cipherState.cipher; + cipher.start({iv: iv}); + + // TLS 1.1+ write IV into output + if(record.version.minor >= tls.Versions.TLS_1_1.minor) { + cipher.output.putBytes(iv); + } + + // do encryption (default padding is appropriate) + cipher.update(record.fragment); + if(cipher.finish(encrypt_aes_cbc_sha1_padding)) { + // set record fragment to encrypted output + record.fragment = cipher.output; + record.length = record.fragment.length(); + rval = true; + } + + return rval; +} + +/** + * Handles padding for aes_cbc_sha1 in encrypt mode. + * + * @param blockSize the block size. + * @param input the input buffer. + * @param decrypt true in decrypt mode, false in encrypt mode. + * + * @return true on success, false on failure. + */ +function encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) { + /* The encrypted data length (TLSCiphertext.length) is one more than the sum + of SecurityParameters.block_length, TLSCompressed.length, + SecurityParameters.mac_length, and padding_length. + + The padding may be any length up to 255 bytes long, as long as it results in + the TLSCiphertext.length being an integral multiple of the block length. + Lengths longer than necessary might be desirable to frustrate attacks on a + protocol based on analysis of the lengths of exchanged messages. Each uint8 + in the padding data vector must be filled with the padding length value. + + The padding length should be such that the total size of the + GenericBlockCipher structure is a multiple of the cipher's block length. + Legal values range from zero to 255, inclusive. This length specifies the + length of the padding field exclusive of the padding_length field itself. + + This is slightly different from PKCS#7 because the padding value is 1 + less than the actual number of padding bytes if you include the + padding_length uint8 itself as a padding byte. */ + if(!decrypt) { + // get the number of padding bytes required to reach the blockSize and + // subtract 1 for the padding value (to make room for the padding_length + // uint8) + var padding = blockSize - (input.length() % blockSize); + input.fillWithByte(padding - 1, padding); + } + return true; +} + +/** + * Handles padding for aes_cbc_sha1 in decrypt mode. + * + * @param blockSize the block size. + * @param output the output buffer. + * @param decrypt true in decrypt mode, false in encrypt mode. + * + * @return true on success, false on failure. + */ +function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) { + var rval = true; + if(decrypt) { + /* The last byte in the output specifies the number of padding bytes not + including itself. Each of the padding bytes has the same value as that + last byte (known as the padding_length). Here we check all padding + bytes to ensure they have the value of padding_length even if one of + them is bad in order to ward-off timing attacks. */ + var len = output.length(); + var paddingLength = output.last(); + for(var i = len - 1 - paddingLength; i < len - 1; ++i) { + rval = rval && (output.at(i) == paddingLength); + } + if(rval) { + // trim off padding bytes and last padding length byte + output.truncate(paddingLength + 1); + } + } + return rval; +} + +/** + * Decrypts a TLSCipherText record into a TLSCompressed record using + * AES in CBC mode. + * + * @param record the TLSCipherText record to decrypt. + * @param s the ConnectionState to use. + * + * @return true on success, false on failure. + */ +function decrypt_aes_cbc_sha1(record, s) { + var rval = false; + + var iv; + if(record.version.minor === tls.Versions.TLS_1_0.minor) { + // use pre-generated IV when initializing for TLS 1.0, otherwise use the + // residue from the previous decryption + iv = s.cipherState.init ? null : s.cipherState.iv; + } else { + // TLS 1.1+ use an explicit IV every time to protect against CBC attacks + // that is appended to the record fragment + iv = record.fragment.getBytes(16); + } + + s.cipherState.init = true; + + // start cipher + var cipher = s.cipherState.cipher; + cipher.start({iv: iv}); + + // do decryption + cipher.update(record.fragment); + rval = cipher.finish(decrypt_aes_cbc_sha1_padding); + + // even if decryption fails, keep going to minimize timing attacks + + // decrypted data: + // first (len - 20) bytes = application data + // last 20 bytes = MAC + var macLen = s.macLength; + + // create a random MAC to check against should the mac length check fail + // Note: do this regardless of the failure to keep timing consistent + var mac = forge.random.getBytesSync(macLen); + + // get fragment and mac + var len = cipher.output.length(); + if(len >= macLen) { + record.fragment = cipher.output.getBytes(len - macLen); + mac = cipher.output.getBytes(macLen); + } else { + // bad data, but get bytes anyway to try to keep timing consistent + record.fragment = cipher.output.getBytes(); + } + record.fragment = forge.util.createBuffer(record.fragment); + record.length = record.fragment.length(); + + // see if data integrity checks out, update sequence number + var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record); + s.updateSequenceNumber(); + rval = compareMacs(s.macKey, mac, mac2) && rval; + return rval; +} + +/** + * Safely compare two MACs. This function will compare two MACs in a way + * that protects against timing attacks. + * + * TODO: Expose elsewhere as a utility API. + * + * See: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/february/double-hmac-verification/ + * + * @param key the MAC key to use. + * @param mac1 as a binary-encoded string of bytes. + * @param mac2 as a binary-encoded string of bytes. + * + * @return true if the MACs are the same, false if not. + */ +function compareMacs(key, mac1, mac2) { + var hmac = forge.hmac.create(); + + hmac.start('SHA1', key); + hmac.update(mac1); + mac1 = hmac.digest().getBytes(); + + hmac.start(null, null); + hmac.update(mac2); + mac2 = hmac.digest().getBytes(); + + return mac1 === mac2; +} diff --git a/node_modules/node-forge/lib/asn1-validator.js b/node_modules/node-forge/lib/asn1-validator.js new file mode 100644 index 0000000..2be3285 --- /dev/null +++ b/node_modules/node-forge/lib/asn1-validator.js @@ -0,0 +1,91 @@ +/** + * Copyright (c) 2019 Digital Bazaar, Inc. + */ + +var forge = require('./forge'); +require('./asn1'); +var asn1 = forge.asn1; + +exports.privateKeyValidator = { + // PrivateKeyInfo + name: 'PrivateKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // Version (INTEGER) + name: 'PrivateKeyInfo.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyVersion' + }, { + // privateKeyAlgorithm + name: 'PrivateKeyInfo.privateKeyAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'privateKeyOid' + }] + }, { + // PrivateKey + name: 'PrivateKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'privateKey' + }] +}; + +exports.publicKeyValidator = { + name: 'SubjectPublicKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'subjectPublicKeyInfo', + value: [{ + name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'publicKeyOid' + }] + }, + // capture group for ed25519PublicKey + { + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + composed: true, + captureBitStringValue: 'ed25519PublicKey' + } + // FIXME: this is capture group for rsaPublicKey, use it in this API or + // discard? + /* { + // subjectPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + value: [{ + // RSAPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: 'rsaPublicKey' + }] + } */ + ] +}; diff --git a/node_modules/node-forge/lib/asn1.js b/node_modules/node-forge/lib/asn1.js new file mode 100644 index 0000000..e3cb500 --- /dev/null +++ b/node_modules/node-forge/lib/asn1.js @@ -0,0 +1,1503 @@ +/** + * Javascript implementation of Abstract Syntax Notation Number One. + * + * @author Dave Longley + * + * Copyright (c) 2010-2015 Digital Bazaar, Inc. + * + * An API for storing data using the Abstract Syntax Notation Number One + * format using DER (Distinguished Encoding Rules) encoding. This encoding is + * commonly used to store data for PKI, i.e. X.509 Certificates, and this + * implementation exists for that purpose. + * + * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract + * syntax of information without restricting the way the information is encoded + * for transmission. It provides a standard that allows for open systems + * communication. ASN.1 defines the syntax of information data and a number of + * simple data types as well as a notation for describing them and specifying + * values for them. + * + * The RSA algorithm creates public and private keys that are often stored in + * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This + * class provides the most basic functionality required to store and load DSA + * keys that are encoded according to ASN.1. + * + * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules) + * and DER (Distinguished Encoding Rules). DER is just a subset of BER that + * has stricter requirements for how data must be encoded. + * + * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type) + * and a byte array for the value of this ASN1 structure which may be data or a + * list of ASN.1 structures. + * + * Each ASN.1 structure using BER is (Tag-Length-Value): + * + * | byte 0 | bytes X | bytes Y | + * |--------|---------|---------- + * | tag | length | value | + * + * ASN.1 allows for tags to be of "High-tag-number form" which allows a tag to + * be two or more octets, but that is not supported by this class. A tag is + * only 1 byte. Bits 1-5 give the tag number (ie the data type within a + * particular 'class'), 6 indicates whether or not the ASN.1 value is + * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If + * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set, + * then the class is APPLICATION. If only bit 8 is set, then the class is + * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE. + * The tag numbers for the data types for the class UNIVERSAL are listed below: + * + * UNIVERSAL 0 Reserved for use by the encoding rules + * UNIVERSAL 1 Boolean type + * UNIVERSAL 2 Integer type + * UNIVERSAL 3 Bitstring type + * UNIVERSAL 4 Octetstring type + * UNIVERSAL 5 Null type + * UNIVERSAL 6 Object identifier type + * UNIVERSAL 7 Object descriptor type + * UNIVERSAL 8 External type and Instance-of type + * UNIVERSAL 9 Real type + * UNIVERSAL 10 Enumerated type + * UNIVERSAL 11 Embedded-pdv type + * UNIVERSAL 12 UTF8String type + * UNIVERSAL 13 Relative object identifier type + * UNIVERSAL 14-15 Reserved for future editions + * UNIVERSAL 16 Sequence and Sequence-of types + * UNIVERSAL 17 Set and Set-of types + * UNIVERSAL 18-22, 25-30 Character string types + * UNIVERSAL 23-24 Time types + * + * The length of an ASN.1 structure is specified after the tag identifier. + * There is a definite form and an indefinite form. The indefinite form may + * be used if the encoding is constructed and not all immediately available. + * The indefinite form is encoded using a length byte with only the 8th bit + * set. The end of the constructed object is marked using end-of-contents + * octets (two zero bytes). + * + * The definite form looks like this: + * + * The length may take up 1 or more bytes, it depends on the length of the + * value of the ASN.1 structure. DER encoding requires that if the ASN.1 + * structure has a value that has a length greater than 127, more than 1 byte + * will be used to store its length, otherwise just one byte will be used. + * This is strict. + * + * In the case that the length of the ASN.1 value is less than 127, 1 octet + * (byte) is used to store the "short form" length. The 8th bit has a value of + * 0 indicating the length is "short form" and not "long form" and bits 7-1 + * give the length of the data. (The 8th bit is the left-most, most significant + * bit: also known as big endian or network format). + * + * In the case that the length of the ASN.1 value is greater than 127, 2 to + * 127 octets (bytes) are used to store the "long form" length. The first + * byte's 8th bit is set to 1 to indicate the length is "long form." Bits 7-1 + * give the number of additional octets. All following octets are in base 256 + * with the most significant digit first (typical big-endian binary unsigned + * integer storage). So, for instance, if the length of a value was 257, the + * first byte would be set to: + * + * 10000010 = 130 = 0x82. + * + * This indicates there are 2 octets (base 256) for the length. The second and + * third bytes (the octets just mentioned) would store the length in base 256: + * + * octet 2: 00000001 = 1 * 256^1 = 256 + * octet 3: 00000001 = 1 * 256^0 = 1 + * total = 257 + * + * The algorithm for converting a js integer value of 257 to base-256 is: + * + * var value = 257; + * var bytes = []; + * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first + * bytes[1] = value & 0xFF; // least significant byte last + * + * On the ASN.1 UNIVERSAL Object Identifier (OID) type: + * + * An OID can be written like: "value1.value2.value3...valueN" + * + * The DER encoding rules: + * + * The first byte has the value 40 * value1 + value2. + * The following bytes, if any, encode the remaining values. Each value is + * encoded in base 128, most significant digit first (big endian), with as + * few digits as possible, and the most significant bit of each byte set + * to 1 except the last in each value's encoding. For example: Given the + * OID "1.2.840.113549", its DER encoding is (remember each byte except the + * last one in each encoding is OR'd with 0x80): + * + * byte 1: 40 * 1 + 2 = 42 = 0x2A. + * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x8648 + * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D + * + * The final value is: 0x2A864886F70D. + * The full OID (including ASN.1 tag and length of 6 bytes) is: + * 0x06062A864886F70D + */ +var forge = require('./forge'); +require('./util'); +require('./oids'); + +/* ASN.1 API */ +var asn1 = module.exports = forge.asn1 = forge.asn1 || {}; + +/** + * ASN.1 classes. + */ +asn1.Class = { + UNIVERSAL: 0x00, + APPLICATION: 0x40, + CONTEXT_SPECIFIC: 0x80, + PRIVATE: 0xC0 +}; + +/** + * ASN.1 types. Not all types are supported by this implementation, only + * those necessary to implement a simple PKI are implemented. + */ +asn1.Type = { + NONE: 0, + BOOLEAN: 1, + INTEGER: 2, + BITSTRING: 3, + OCTETSTRING: 4, + NULL: 5, + OID: 6, + ODESC: 7, + EXTERNAL: 8, + REAL: 9, + ENUMERATED: 10, + EMBEDDED: 11, + UTF8: 12, + ROID: 13, + SEQUENCE: 16, + SET: 17, + PRINTABLESTRING: 19, + IA5STRING: 22, + UTCTIME: 23, + GENERALIZEDTIME: 24, + BMPSTRING: 30 +}; + +/** + * Sets the default maximum recursion depth when parsing ASN.1 structures. + */ +asn1.maxDepth = 256; + +/** + * Creates a new asn1 object. + * + * @param tagClass the tag class for the object. + * @param type the data type (tag number) for the object. + * @param constructed true if the asn1 object is in constructed form. + * @param value the value for the object, if it is not constructed. + * @param [options] the options to use: + * [bitStringContents] the plain BIT STRING content including padding + * byte. + * + * @return the asn1 object. + */ +asn1.create = function(tagClass, type, constructed, value, options) { + /* An asn1 object has a tagClass, a type, a constructed flag, and a + value. The value's type depends on the constructed flag. If + constructed, it will contain a list of other asn1 objects. If not, + it will contain the ASN.1 value as an array of bytes formatted + according to the ASN.1 data type. */ + + // remove undefined values + if(forge.util.isArray(value)) { + var tmp = []; + for(var i = 0; i < value.length; ++i) { + if(value[i] !== undefined) { + tmp.push(value[i]); + } + } + value = tmp; + } + + var obj = { + tagClass: tagClass, + type: type, + constructed: constructed, + composed: constructed || forge.util.isArray(value), + value: value + }; + if(options && 'bitStringContents' in options) { + // TODO: copy byte buffer if it's a buffer not a string + obj.bitStringContents = options.bitStringContents; + // TODO: add readonly flag to avoid this overhead + // save copy to detect changes + obj.original = asn1.copy(obj); + } + return obj; +}; + +/** + * Copies an asn1 object. + * + * @param obj the asn1 object. + * @param [options] copy options: + * [excludeBitStringContents] true to not copy bitStringContents + * + * @return the a copy of the asn1 object. + */ +asn1.copy = function(obj, options) { + var copy; + + if(forge.util.isArray(obj)) { + copy = []; + for(var i = 0; i < obj.length; ++i) { + copy.push(asn1.copy(obj[i], options)); + } + return copy; + } + + if(typeof obj === 'string') { + // TODO: copy byte buffer if it's a buffer not a string + return obj; + } + + copy = { + tagClass: obj.tagClass, + type: obj.type, + constructed: obj.constructed, + composed: obj.composed, + value: asn1.copy(obj.value, options) + }; + if(options && !options.excludeBitStringContents) { + // TODO: copy byte buffer if it's a buffer not a string + copy.bitStringContents = obj.bitStringContents; + } + return copy; +}; + +/** + * Compares asn1 objects for equality. + * + * Note this function does not run in constant time. + * + * @param obj1 the first asn1 object. + * @param obj2 the second asn1 object. + * @param [options] compare options: + * [includeBitStringContents] true to compare bitStringContents + * + * @return true if the asn1 objects are equal. + */ +asn1.equals = function(obj1, obj2, options) { + if(forge.util.isArray(obj1)) { + if(!forge.util.isArray(obj2)) { + return false; + } + if(obj1.length !== obj2.length) { + return false; + } + for(var i = 0; i < obj1.length; ++i) { + if(!asn1.equals(obj1[i], obj2[i])) { + return false; + } + } + return true; + } + + if(typeof obj1 !== typeof obj2) { + return false; + } + + if(typeof obj1 === 'string') { + return obj1 === obj2; + } + + var equal = obj1.tagClass === obj2.tagClass && + obj1.type === obj2.type && + obj1.constructed === obj2.constructed && + obj1.composed === obj2.composed && + asn1.equals(obj1.value, obj2.value); + if(options && options.includeBitStringContents) { + equal = equal && (obj1.bitStringContents === obj2.bitStringContents); + } + + return equal; +}; + +/** + * Gets the length of a BER-encoded ASN.1 value. + * + * In case the length is not specified, undefined is returned. + * + * @param b the BER-encoded ASN.1 byte buffer, starting with the first + * length byte. + * + * @return the length of the BER-encoded ASN.1 value or undefined. + */ +asn1.getBerValueLength = function(b) { + // TODO: move this function and related DER/BER functions to a der.js + // file; better abstract ASN.1 away from der/ber. + var b2 = b.getByte(); + if(b2 === 0x80) { + return undefined; + } + + // see if the length is "short form" or "long form" (bit 8 set) + var length; + var longForm = b2 & 0x80; + if(!longForm) { + // length is just the first byte + length = b2; + } else { + // the number of bytes the length is specified in bits 7 through 1 + // and each length byte is in big-endian base-256 + length = b.getInt((b2 & 0x7F) << 3); + } + return length; +}; + +/** + * Check if the byte buffer has enough bytes. Throws an Error if not. + * + * @param bytes the byte buffer to parse from. + * @param remaining the bytes remaining in the current parsing state. + * @param n the number of bytes the buffer must have. + */ +function _checkBufferLength(bytes, remaining, n) { + if(n > remaining) { + var error = new Error('Too few bytes to parse DER.'); + error.available = bytes.length(); + error.remaining = remaining; + error.requested = n; + throw error; + } +} + +/** + * Gets the length of a BER-encoded ASN.1 value. + * + * In case the length is not specified, undefined is returned. + * + * @param bytes the byte buffer to parse from. + * @param remaining the bytes remaining in the current parsing state. + * + * @return the length of the BER-encoded ASN.1 value or undefined. + */ +var _getValueLength = function(bytes, remaining) { + // TODO: move this function and related DER/BER functions to a der.js + // file; better abstract ASN.1 away from der/ber. + // fromDer already checked that this byte exists + var b2 = bytes.getByte(); + remaining--; + if(b2 === 0x80) { + return undefined; + } + + // see if the length is "short form" or "long form" (bit 8 set) + var length; + var longForm = b2 & 0x80; + if(!longForm) { + // length is just the first byte + length = b2; + } else { + // the number of bytes the length is specified in bits 7 through 1 + // and each length byte is in big-endian base-256 + var longFormBytes = b2 & 0x7F; + _checkBufferLength(bytes, remaining, longFormBytes); + length = bytes.getInt(longFormBytes << 3); + } + // FIXME: this will only happen for 32 bit getInt with high bit set + if(length < 0) { + throw new Error('Negative length: ' + length); + } + return length; +}; + +/** + * Parses an asn1 object from a byte buffer in DER format. + * + * @param bytes the byte buffer to parse from. + * @param [strict] true to be strict when checking value lengths, false to + * allow truncated values (default: true). + * @param [options] object with options or boolean strict flag + * [strict] true to be strict when checking value lengths, false to + * allow truncated values (default: true). + * [parseAllBytes] true to ensure all bytes are parsed + * (default: true) + * [decodeBitStrings] true to attempt to decode the content of + * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that + * without schema support to understand the data context this can + * erroneously decode values that happen to be valid ASN.1. This + * flag will be deprecated or removed as soon as schema support is + * available. (default: true) + * [maxDepth] override asn1.maxDepth recursion limit + * (default: asn1.maxDepth) + * + * @throws Will throw an error for various malformed input conditions. + * + * @return the parsed asn1 object. + */ +asn1.fromDer = function(bytes, options) { + if(options === undefined) { + options = { + strict: true, + parseAllBytes: true, + decodeBitStrings: true + }; + } + if(typeof options === 'boolean') { + options = { + strict: options, + parseAllBytes: true, + decodeBitStrings: true + }; + } + if(!('strict' in options)) { + options.strict = true; + } + if(!('parseAllBytes' in options)) { + options.parseAllBytes = true; + } + if(!('decodeBitStrings' in options)) { + options.decodeBitStrings = true; + } + if(!('maxDepth' in options)) { + options.maxDepth = asn1.maxDepth; + } + + // wrap in buffer if needed + if(typeof bytes === 'string') { + bytes = forge.util.createBuffer(bytes); + } + + var byteCount = bytes.length(); + var value = _fromDer(bytes, bytes.length(), 0, options); + if(options.parseAllBytes && bytes.length() !== 0) { + var error = new Error('Unparsed DER bytes remain after ASN.1 parsing.'); + error.byteCount = byteCount; + error.remaining = bytes.length(); + throw error; + } + return value; +}; + +/** + * Internal function to parse an asn1 object from a byte buffer in DER format. + * + * @param bytes the byte buffer to parse from. + * @param remaining the number of bytes remaining for this chunk. + * @param depth the current parsing depth. + * @param options object with same options as fromDer(). + * + * @return the parsed asn1 object. + */ +function _fromDer(bytes, remaining, depth, options) { + + // check depth limit + if(depth >= options.maxDepth) { + throw new Error('ASN.1 parsing error: Max depth exceeded.'); + } + + // temporary storage for consumption calculations + var start; + + // minimum length for ASN.1 DER structure is 2 + _checkBufferLength(bytes, remaining, 2); + + // get the first byte + var b1 = bytes.getByte(); + // consumed one byte + remaining--; + + // get the tag class + var tagClass = (b1 & 0xC0); + + // get the type (bits 1-5) + var type = b1 & 0x1F; + + // get the variable value length and adjust remaining bytes + start = bytes.length(); + var length = _getValueLength(bytes, remaining); + remaining -= start - bytes.length(); + + // ensure there are enough bytes to get the value + if(length !== undefined && length > remaining) { + if(options.strict) { + var error = new Error('Too few bytes to read ASN.1 value.'); + error.available = bytes.length(); + error.remaining = remaining; + error.requested = length; + throw error; + } + // Note: be lenient with truncated values and use remaining state bytes + length = remaining; + } + + // value storage + var value; + // possible BIT STRING contents storage + var bitStringContents; + + // constructed flag is bit 6 (32 = 0x20) of the first byte + var constructed = ((b1 & 0x20) === 0x20); + if(constructed) { + // parse child asn1 objects from the value + value = []; + if(length === undefined) { + // asn1 object of indefinite length, read until end tag + for(;;) { + _checkBufferLength(bytes, remaining, 2); + if(bytes.bytes(2) === String.fromCharCode(0, 0)) { + bytes.getBytes(2); + remaining -= 2; + break; + } + start = bytes.length(); + value.push(_fromDer(bytes, remaining, depth + 1, options)); + remaining -= start - bytes.length(); + } + } else { + // parsing asn1 object of definite length + while(length > 0) { + start = bytes.length(); + value.push(_fromDer(bytes, length, depth + 1, options)); + remaining -= start - bytes.length(); + length -= start - bytes.length(); + } + } + } + + // if a BIT STRING, save the contents including padding + if(value === undefined && tagClass === asn1.Class.UNIVERSAL && + type === asn1.Type.BITSTRING) { + bitStringContents = bytes.bytes(length); + } + + // determine if a non-constructed value should be decoded as a composed + // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs) + // can be used this way. + if(value === undefined && options.decodeBitStrings && + tagClass === asn1.Class.UNIVERSAL && + // FIXME: OCTET STRINGs not yet supported here + // .. other parts of forge expect to decode OCTET STRINGs manually + (type === asn1.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) && + length > 1) { + // save read position + var savedRead = bytes.read; + var savedRemaining = remaining; + var unused = 0; + if(type === asn1.Type.BITSTRING) { + /* The first octet gives the number of bits by which the length of the + bit string is less than the next multiple of eight (this is called + the "number of unused bits"). + + The second and following octets give the value of the bit string + converted to an octet string. */ + _checkBufferLength(bytes, remaining, 1); + unused = bytes.getByte(); + remaining--; + } + // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs + if(unused === 0) { + try { + // attempt to parse child asn1 object from the value + // (stored in array to signal composed value) + start = bytes.length(); + var subOptions = { + // enforce strict mode to avoid parsing ASN.1 from plain data + strict: true, + decodeBitStrings: true + }; + var composed = _fromDer(bytes, remaining, depth + 1, subOptions); + var used = start - bytes.length(); + remaining -= used; + if(type == asn1.Type.BITSTRING) { + used++; + } + + // if the data all decoded and the class indicates UNIVERSAL or + // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object + var tc = composed.tagClass; + if(used === length && + (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) { + value = [composed]; + } + } catch(ex) { + } + } + if(value === undefined) { + // restore read position + bytes.read = savedRead; + remaining = savedRemaining; + } + } + + if(value === undefined) { + // asn1 not constructed or composed, get raw value + // TODO: do DER to OID conversion and vice-versa in .toDer? + + if(length === undefined) { + if(options.strict) { + throw new Error('Non-constructed ASN.1 object of indefinite length.'); + } + // be lenient and use remaining state bytes + length = remaining; + } + + if(type === asn1.Type.BMPSTRING) { + value = ''; + for(; length > 0; length -= 2) { + _checkBufferLength(bytes, remaining, 2); + value += String.fromCharCode(bytes.getInt16()); + remaining -= 2; + } + } else { + value = bytes.getBytes(length); + remaining -= length; + } + } + + // add BIT STRING contents if available + var asn1Options = bitStringContents === undefined ? null : { + bitStringContents: bitStringContents + }; + + // create and return asn1 object + return asn1.create(tagClass, type, constructed, value, asn1Options); +} + +/** + * Converts the given asn1 object to a buffer of bytes in DER format. + * + * @param asn1 the asn1 object to convert to bytes. + * + * @return the buffer of bytes. + */ +asn1.toDer = function(obj) { + var bytes = forge.util.createBuffer(); + + // build the first byte + var b1 = obj.tagClass | obj.type; + + // for storing the ASN.1 value + var value = forge.util.createBuffer(); + + // use BIT STRING contents if available and data not changed + var useBitStringContents = false; + if('bitStringContents' in obj) { + useBitStringContents = true; + if(obj.original) { + useBitStringContents = asn1.equals(obj, obj.original); + } + } + + if(useBitStringContents) { + value.putBytes(obj.bitStringContents); + } else if(obj.composed) { + // if composed, use each child asn1 object's DER bytes as value + // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed + // from other asn1 objects + if(obj.constructed) { + b1 |= 0x20; + } else { + // type is a bit string, add unused bits of 0x00 + value.putByte(0x00); + } + + // add all of the child DER bytes together + for(var i = 0; i < obj.value.length; ++i) { + if(obj.value[i] !== undefined) { + value.putBuffer(asn1.toDer(obj.value[i])); + } + } + } else { + // use asn1.value directly + if(obj.type === asn1.Type.BMPSTRING) { + for(var i = 0; i < obj.value.length; ++i) { + value.putInt16(obj.value.charCodeAt(i)); + } + } else { + // ensure integer is minimally-encoded + // TODO: should all leading bytes be stripped vs just one? + // .. ex '00 00 01' => '01'? + if(obj.type === asn1.Type.INTEGER && + obj.value.length > 1 && + // leading 0x00 for positive integer + ((obj.value.charCodeAt(0) === 0 && + (obj.value.charCodeAt(1) & 0x80) === 0) || + // leading 0xFF for negative integer + (obj.value.charCodeAt(0) === 0xFF && + (obj.value.charCodeAt(1) & 0x80) === 0x80))) { + value.putBytes(obj.value.substr(1)); + } else { + value.putBytes(obj.value); + } + } + } + + // add tag byte + bytes.putByte(b1); + + // use "short form" encoding + if(value.length() <= 127) { + // one byte describes the length + // bit 8 = 0 and bits 7-1 = length + bytes.putByte(value.length() & 0x7F); + } else { + // use "long form" encoding + // 2 to 127 bytes describe the length + // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes + // other bytes: length in base 256, big-endian + var len = value.length(); + var lenBytes = ''; + do { + lenBytes += String.fromCharCode(len & 0xFF); + len = len >>> 8; + } while(len > 0); + + // set first byte to # bytes used to store the length and turn on + // bit 8 to indicate long-form length is used + bytes.putByte(lenBytes.length | 0x80); + + // concatenate length bytes in reverse since they were generated + // little endian and we need big endian + for(var i = lenBytes.length - 1; i >= 0; --i) { + bytes.putByte(lenBytes.charCodeAt(i)); + } + } + + // concatenate value bytes + bytes.putBuffer(value); + return bytes; +}; + +/** + * Converts an OID dot-separated string to a byte buffer. The byte buffer + * contains only the DER-encoded value, not any tag or length bytes. + * + * @param oid the OID dot-separated string. + * + * @return the byte buffer. + */ +asn1.oidToDer = function(oid) { + // split OID into individual values + var values = oid.split('.'); + var bytes = forge.util.createBuffer(); + + // first byte is 40 * value1 + value2 + bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10)); + // other bytes are each value in base 128 with 8th bit set except for + // the last byte for each value + var last, valueBytes, value, b; + for(var i = 2; i < values.length; ++i) { + // produce value bytes in reverse because we don't know how many + // bytes it will take to store the value + last = true; + valueBytes = []; + value = parseInt(values[i], 10); + // TODO: Change bitwise logic to allow larger values. + if(value > 0xffffffff) { + throw new Error('OID value too large; max is 32-bits.'); + } + do { + b = value & 0x7F; + value = value >>> 7; + // if value is not last, then turn on 8th bit + if(!last) { + b |= 0x80; + } + valueBytes.push(b); + last = false; + } while(value > 0); + + // add value bytes in reverse (needs to be in big endian) + for(var n = valueBytes.length - 1; n >= 0; --n) { + bytes.putByte(valueBytes[n]); + } + } + + return bytes; +}; + +/** + * Converts a DER-encoded byte buffer to an OID dot-separated string. The + * byte buffer should contain only the DER-encoded value, not any tag or + * length bytes. + * + * @param bytes the byte buffer. + * + * @return the OID dot-separated string. + */ +asn1.derToOid = function(bytes) { + var oid; + + // wrap in buffer if needed + if(typeof bytes === 'string') { + bytes = forge.util.createBuffer(bytes); + } + + // first byte is 40 * value1 + value2 + var b = bytes.getByte(); + oid = Math.floor(b / 40) + '.' + (b % 40); + + // other bytes are each value in base 128 with 8th bit set except for + // the last byte for each value + var value = 0; + while(bytes.length() > 0) { + // error if 7b shift would exceed Number.MAX_SAFE_INTEGER + // (Number.MAX_SAFE_INTEGER / 128) + if(value > 0x3fffffffffff) { + throw new Error('OID value too large; max is 53-bits.'); + } + b = bytes.getByte(); + value = value * 128; + // not the last byte for the value + if(b & 0x80) { + value += b & 0x7F; + } else { + // last byte + oid += '.' + (value + b); + value = 0; + } + } + + return oid; +}; + +/** + * Converts a UTCTime value to a date. + * + * Note: GeneralizedTime has 4 digits for the year and is used for X.509 + * dates past 2049. Parsing that structure hasn't been implemented yet. + * + * @param utc the UTCTime value to convert. + * + * @return the date. + */ +asn1.utcTimeToDate = function(utc) { + /* The following formats can be used: + + YYMMDDhhmmZ + YYMMDDhhmm+hh'mm' + YYMMDDhhmm-hh'mm' + YYMMDDhhmmssZ + YYMMDDhhmmss+hh'mm' + YYMMDDhhmmss-hh'mm' + + Where: + + YY is the least significant two digits of the year + MM is the month (01 to 12) + DD is the day (01 to 31) + hh is the hour (00 to 23) + mm are the minutes (00 to 59) + ss are the seconds (00 to 59) + Z indicates that local time is GMT, + indicates that local time is + later than GMT, and - indicates that local time is earlier than GMT + hh' is the absolute value of the offset from GMT in hours + mm' is the absolute value of the offset from GMT in minutes */ + var date = new Date(); + + // if YY >= 50 use 19xx, if YY < 50 use 20xx + var year = parseInt(utc.substr(0, 2), 10); + year = (year >= 50) ? 1900 + year : 2000 + year; + var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month + var DD = parseInt(utc.substr(4, 2), 10); + var hh = parseInt(utc.substr(6, 2), 10); + var mm = parseInt(utc.substr(8, 2), 10); + var ss = 0; + + // not just YYMMDDhhmmZ + if(utc.length > 11) { + // get character after minutes + var c = utc.charAt(10); + var end = 10; + + // see if seconds are present + if(c !== '+' && c !== '-') { + // get seconds + ss = parseInt(utc.substr(10, 2), 10); + end += 2; + } + } + + // update date + date.setUTCFullYear(year, MM, DD); + date.setUTCHours(hh, mm, ss, 0); + + if(end) { + // get +/- after end of time + c = utc.charAt(end); + if(c === '+' || c === '-') { + // get hours+minutes offset + var hhoffset = parseInt(utc.substr(end + 1, 2), 10); + var mmoffset = parseInt(utc.substr(end + 4, 2), 10); + + // calculate offset in milliseconds + var offset = hhoffset * 60 + mmoffset; + offset *= 60000; + + // apply offset + if(c === '+') { + date.setTime(+date - offset); + } else { + date.setTime(+date + offset); + } + } + } + + return date; +}; + +/** + * Converts a GeneralizedTime value to a date. + * + * @param gentime the GeneralizedTime value to convert. + * + * @return the date. + */ +asn1.generalizedTimeToDate = function(gentime) { + /* The following formats can be used: + + YYYYMMDDHHMMSS + YYYYMMDDHHMMSS.fff + YYYYMMDDHHMMSSZ + YYYYMMDDHHMMSS.fffZ + YYYYMMDDHHMMSS+hh'mm' + YYYYMMDDHHMMSS.fff+hh'mm' + YYYYMMDDHHMMSS-hh'mm' + YYYYMMDDHHMMSS.fff-hh'mm' + + Where: + + YYYY is the year + MM is the month (01 to 12) + DD is the day (01 to 31) + hh is the hour (00 to 23) + mm are the minutes (00 to 59) + ss are the seconds (00 to 59) + .fff is the second fraction, accurate to three decimal places + Z indicates that local time is GMT, + indicates that local time is + later than GMT, and - indicates that local time is earlier than GMT + hh' is the absolute value of the offset from GMT in hours + mm' is the absolute value of the offset from GMT in minutes */ + var date = new Date(); + + var YYYY = parseInt(gentime.substr(0, 4), 10); + var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month + var DD = parseInt(gentime.substr(6, 2), 10); + var hh = parseInt(gentime.substr(8, 2), 10); + var mm = parseInt(gentime.substr(10, 2), 10); + var ss = parseInt(gentime.substr(12, 2), 10); + var fff = 0; + var offset = 0; + var isUTC = false; + + if(gentime.charAt(gentime.length - 1) === 'Z') { + isUTC = true; + } + + var end = gentime.length - 5, c = gentime.charAt(end); + if(c === '+' || c === '-') { + // get hours+minutes offset + var hhoffset = parseInt(gentime.substr(end + 1, 2), 10); + var mmoffset = parseInt(gentime.substr(end + 4, 2), 10); + + // calculate offset in milliseconds + offset = hhoffset * 60 + mmoffset; + offset *= 60000; + + // apply offset + if(c === '+') { + offset *= -1; + } + + isUTC = true; + } + + // check for second fraction + if(gentime.charAt(14) === '.') { + fff = parseFloat(gentime.substr(14), 10) * 1000; + } + + if(isUTC) { + date.setUTCFullYear(YYYY, MM, DD); + date.setUTCHours(hh, mm, ss, fff); + + // apply offset + date.setTime(+date + offset); + } else { + date.setFullYear(YYYY, MM, DD); + date.setHours(hh, mm, ss, fff); + } + + return date; +}; + +/** + * Converts a date to a UTCTime value. + * + * Note: GeneralizedTime has 4 digits for the year and is used for X.509 + * dates past 2049. Converting to a GeneralizedTime hasn't been + * implemented yet. + * + * @param date the date to convert. + * + * @return the UTCTime value. + */ +asn1.dateToUtcTime = function(date) { + // TODO: validate; currently assumes proper format + if(typeof date === 'string') { + return date; + } + + var rval = ''; + + // create format YYMMDDhhmmssZ + var format = []; + format.push(('' + date.getUTCFullYear()).substr(2)); + format.push('' + (date.getUTCMonth() + 1)); + format.push('' + date.getUTCDate()); + format.push('' + date.getUTCHours()); + format.push('' + date.getUTCMinutes()); + format.push('' + date.getUTCSeconds()); + + // ensure 2 digits are used for each format entry + for(var i = 0; i < format.length; ++i) { + if(format[i].length < 2) { + rval += '0'; + } + rval += format[i]; + } + rval += 'Z'; + + return rval; +}; + +/** + * Converts a date to a GeneralizedTime value. + * + * @param date the date to convert. + * + * @return the GeneralizedTime value as a string. + */ +asn1.dateToGeneralizedTime = function(date) { + // TODO: validate; currently assumes proper format + if(typeof date === 'string') { + return date; + } + + var rval = ''; + + // create format YYYYMMDDHHMMSSZ + var format = []; + format.push('' + date.getUTCFullYear()); + format.push('' + (date.getUTCMonth() + 1)); + format.push('' + date.getUTCDate()); + format.push('' + date.getUTCHours()); + format.push('' + date.getUTCMinutes()); + format.push('' + date.getUTCSeconds()); + + // ensure 2 digits are used for each format entry + for(var i = 0; i < format.length; ++i) { + if(format[i].length < 2) { + rval += '0'; + } + rval += format[i]; + } + rval += 'Z'; + + return rval; +}; + +/** + * Converts a javascript integer to a DER-encoded byte buffer to be used + * as the value for an INTEGER type. + * + * @param x the integer. + * + * @return the byte buffer. + */ +asn1.integerToDer = function(x) { + var rval = forge.util.createBuffer(); + if(x >= -0x80 && x < 0x80) { + return rval.putSignedInt(x, 8); + } + if(x >= -0x8000 && x < 0x8000) { + return rval.putSignedInt(x, 16); + } + if(x >= -0x800000 && x < 0x800000) { + return rval.putSignedInt(x, 24); + } + if(x >= -0x80000000 && x < 0x80000000) { + return rval.putSignedInt(x, 32); + } + var error = new Error('Integer too large; max is 32-bits.'); + error.integer = x; + throw error; +}; + +/** + * Converts a DER-encoded byte buffer to a javascript integer. This is + * typically used to decode the value of an INTEGER type. + * + * @param bytes the byte buffer. + * + * @return the integer. + */ +asn1.derToInteger = function(bytes) { + // wrap in buffer if needed + if(typeof bytes === 'string') { + bytes = forge.util.createBuffer(bytes); + } + + var n = bytes.length() * 8; + if(n > 32) { + throw new Error('Integer too large; max is 32-bits.'); + } + return bytes.getSignedInt(n); +}; + +/** + * Validates that the given ASN.1 object is at least a super set of the + * given ASN.1 structure. Only tag classes and types are checked. An + * optional map may also be provided to capture ASN.1 values while the + * structure is checked. + * + * To capture an ASN.1 value, set an object in the validator's 'capture' + * parameter to the key to use in the capture map. To capture the full + * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including + * the leading unused bits counter byte, specify 'captureBitStringContents'. + * To capture BIT STRING bytes, without the leading unused bits counter byte, + * specify 'captureBitStringValue'. + * + * Objects in the validator may set a field 'optional' to true to indicate + * that it isn't necessary to pass validation. + * + * @param obj the ASN.1 object to validate. + * @param v the ASN.1 structure validator. + * @param capture an optional map to capture values in. + * @param errors an optional array for storing validation errors. + * + * @return true on success, false on failure. + */ +asn1.validate = function(obj, v, capture, errors) { + var rval = false; + + // ensure tag class and type are the same if specified + if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') && + (obj.type === v.type || typeof(v.type) === 'undefined')) { + // ensure constructed flag is the same if specified + if(obj.constructed === v.constructed || + typeof(v.constructed) === 'undefined') { + rval = true; + + // handle sub values + if(v.value && forge.util.isArray(v.value)) { + var j = 0; + for(var i = 0; rval && i < v.value.length; ++i) { + var schemaItem = v.value[i]; + rval = !!schemaItem.optional; + + // current child in the object + var objChild = obj.value[j]; + + // if there is no child left to match + if(!objChild) { + // if optional, ok (rval already true), else fail below + if(!schemaItem.optional) { + rval = false; + if(errors) { + errors.push('[' + v.name + '] ' + + 'Missing required element. Expected tag class "' + + schemaItem.tagClass + '", type "' + schemaItem.type + '"'); + } + } + continue; + } + + // If schema explicitly specifies tagClass/type, do a quick structural check + // to avoid unnecessary recursion/side-effects when tags clearly don't match. + var schemaHasTag = (typeof schemaItem.tagClass !== 'undefined' && + typeof schemaItem.type !== 'undefined'); + + if(schemaHasTag && + (objChild.tagClass !== schemaItem.tagClass || objChild.type !== schemaItem.type)) { + // Tags do not match. + if(schemaItem.optional) { + // Skip this schema element (don't consume objChild; don't call recursive validate). + rval = true; + continue; + } else { + // Required schema item mismatched - fail. + rval = false; + if(errors) { + errors.push('[' + v.name + '] ' + + 'Tag mismatch. Expected (' + + schemaItem.tagClass + ',' + schemaItem.type + '), got (' + + objChild.tagClass + ',' + objChild.type + ')'); + } + break; + } + } + + // Tags are compatible (or schema did not declare tags) - dive into recursive validate. + var childRval = asn1.validate(objChild, schemaItem, capture, errors); + if(childRval) { + // consume this child + ++j; + rval = true; + } else if(schemaItem.optional) { + // validation failed but element is optional => skip schema item (don't consume child) + rval = true; + } else { + // required item failed + rval = false; + // errors should already be populated by recursive call; keep failing + break; + } + } + } + + if(rval && capture) { + if(v.capture) { + capture[v.capture] = obj.value; + } + if(v.captureAsn1) { + capture[v.captureAsn1] = obj; + } + if(v.captureBitStringContents && 'bitStringContents' in obj) { + capture[v.captureBitStringContents] = obj.bitStringContents; + } + if(v.captureBitStringValue && 'bitStringContents' in obj) { + var value; + if(obj.bitStringContents.length < 2) { + capture[v.captureBitStringValue] = ''; + } else { + // FIXME: support unused bits with data shifting + var unused = obj.bitStringContents.charCodeAt(0); + if(unused !== 0) { + throw new Error( + 'captureBitStringValue only supported for zero unused bits'); + } + capture[v.captureBitStringValue] = obj.bitStringContents.slice(1); + } + } + } + } else if(errors) { + errors.push( + '[' + v.name + '] ' + + 'Expected constructed "' + v.constructed + '", got "' + + obj.constructed + '"'); + } + } else if(errors) { + if(obj.tagClass !== v.tagClass) { + errors.push( + '[' + v.name + '] ' + + 'Expected tag class "' + v.tagClass + '", got "' + + obj.tagClass + '"'); + } + if(obj.type !== v.type) { + errors.push( + '[' + v.name + '] ' + + 'Expected type "' + v.type + '", got "' + + obj.type + '"'); + } + } + return rval; +}; + +// regex for testing for non-latin characters +var _nonLatinRegex = /[^\\u0000-\\u00ff]/; + +/** + * Pretty prints an ASN.1 object to a string. + * + * @param obj the object to write out. + * @param level the level in the tree. + * @param indentation the indentation to use. + * + * @return the string. + */ +asn1.prettyPrint = function(obj, level, indentation) { + var rval = ''; + + // set default level and indentation + level = level || 0; + indentation = indentation || 2; + + // start new line for deep levels + if(level > 0) { + rval += '\n'; + } + + // create indent + var indent = ''; + for(var i = 0; i < level * indentation; ++i) { + indent += ' '; + } + + // print class:type + rval += indent + 'Tag: '; + switch(obj.tagClass) { + case asn1.Class.UNIVERSAL: + rval += 'Universal:'; + break; + case asn1.Class.APPLICATION: + rval += 'Application:'; + break; + case asn1.Class.CONTEXT_SPECIFIC: + rval += 'Context-Specific:'; + break; + case asn1.Class.PRIVATE: + rval += 'Private:'; + break; + } + + if(obj.tagClass === asn1.Class.UNIVERSAL) { + rval += obj.type; + + // known types + switch(obj.type) { + case asn1.Type.NONE: + rval += ' (None)'; + break; + case asn1.Type.BOOLEAN: + rval += ' (Boolean)'; + break; + case asn1.Type.INTEGER: + rval += ' (Integer)'; + break; + case asn1.Type.BITSTRING: + rval += ' (Bit string)'; + break; + case asn1.Type.OCTETSTRING: + rval += ' (Octet string)'; + break; + case asn1.Type.NULL: + rval += ' (Null)'; + break; + case asn1.Type.OID: + rval += ' (Object Identifier)'; + break; + case asn1.Type.ODESC: + rval += ' (Object Descriptor)'; + break; + case asn1.Type.EXTERNAL: + rval += ' (External or Instance of)'; + break; + case asn1.Type.REAL: + rval += ' (Real)'; + break; + case asn1.Type.ENUMERATED: + rval += ' (Enumerated)'; + break; + case asn1.Type.EMBEDDED: + rval += ' (Embedded PDV)'; + break; + case asn1.Type.UTF8: + rval += ' (UTF8)'; + break; + case asn1.Type.ROID: + rval += ' (Relative Object Identifier)'; + break; + case asn1.Type.SEQUENCE: + rval += ' (Sequence)'; + break; + case asn1.Type.SET: + rval += ' (Set)'; + break; + case asn1.Type.PRINTABLESTRING: + rval += ' (Printable String)'; + break; + case asn1.Type.IA5String: + rval += ' (IA5String (ASCII))'; + break; + case asn1.Type.UTCTIME: + rval += ' (UTC time)'; + break; + case asn1.Type.GENERALIZEDTIME: + rval += ' (Generalized time)'; + break; + case asn1.Type.BMPSTRING: + rval += ' (BMP String)'; + break; + } + } else { + rval += obj.type; + } + + rval += '\n'; + rval += indent + 'Constructed: ' + obj.constructed + '\n'; + + if(obj.composed) { + var subvalues = 0; + var sub = ''; + for(var i = 0; i < obj.value.length; ++i) { + if(obj.value[i] !== undefined) { + subvalues += 1; + sub += asn1.prettyPrint(obj.value[i], level + 1, indentation); + if((i + 1) < obj.value.length) { + sub += ','; + } + } + } + rval += indent + 'Sub values: ' + subvalues + sub; + } else { + rval += indent + 'Value: '; + if(obj.type === asn1.Type.OID) { + var oid = asn1.derToOid(obj.value); + rval += oid; + if(forge.pki && forge.pki.oids) { + if(oid in forge.pki.oids) { + rval += ' (' + forge.pki.oids[oid] + ') '; + } + } + } + if(obj.type === asn1.Type.INTEGER) { + try { + rval += asn1.derToInteger(obj.value); + } catch(ex) { + rval += '0x' + forge.util.bytesToHex(obj.value); + } + } else if(obj.type === asn1.Type.BITSTRING) { + // TODO: shift bits as needed to display without padding + if(obj.value.length > 1) { + // remove unused bits field + rval += '0x' + forge.util.bytesToHex(obj.value.slice(1)); + } else { + rval += '(none)'; + } + // show unused bit count + if(obj.value.length > 0) { + var unused = obj.value.charCodeAt(0); + if(unused == 1) { + rval += ' (1 unused bit shown)'; + } else if(unused > 1) { + rval += ' (' + unused + ' unused bits shown)'; + } + } + } else if(obj.type === asn1.Type.OCTETSTRING) { + if(!_nonLatinRegex.test(obj.value)) { + rval += '(' + obj.value + ') '; + } + rval += '0x' + forge.util.bytesToHex(obj.value); + } else if(obj.type === asn1.Type.UTF8) { + try { + rval += forge.util.decodeUtf8(obj.value); + } catch(e) { + if(e.message === 'URI malformed') { + rval += + '0x' + forge.util.bytesToHex(obj.value) + ' (malformed UTF8)'; + } else { + throw e; + } + } + } else if(obj.type === asn1.Type.PRINTABLESTRING || + obj.type === asn1.Type.IA5String) { + rval += obj.value; + } else if(_nonLatinRegex.test(obj.value)) { + rval += '0x' + forge.util.bytesToHex(obj.value); + } else if(obj.value.length === 0) { + rval += '[null]'; + } else { + rval += obj.value; + } + } + + return rval; +}; diff --git a/node_modules/node-forge/lib/baseN.js b/node_modules/node-forge/lib/baseN.js new file mode 100644 index 0000000..824fa36 --- /dev/null +++ b/node_modules/node-forge/lib/baseN.js @@ -0,0 +1,186 @@ +/** + * Base-N/Base-X encoding/decoding functions. + * + * Original implementation from base-x: + * https://github.com/cryptocoinjs/base-x + * + * Which is MIT licensed: + * + * The MIT License (MIT) + * + * Copyright base-x contributors (c) 2016 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ +var api = {}; +module.exports = api; + +// baseN alphabet indexes +var _reverseAlphabets = {}; + +/** + * BaseN-encodes a Uint8Array using the given alphabet. + * + * @param input the Uint8Array to encode. + * @param maxline the maximum number of encoded characters per line to use, + * defaults to none. + * + * @return the baseN-encoded output string. + */ +api.encode = function(input, alphabet, maxline) { + if(typeof alphabet !== 'string') { + throw new TypeError('"alphabet" must be a string.'); + } + if(maxline !== undefined && typeof maxline !== 'number') { + throw new TypeError('"maxline" must be a number.'); + } + + var output = ''; + + if(!(input instanceof Uint8Array)) { + // assume forge byte buffer + output = _encodeWithByteBuffer(input, alphabet); + } else { + var i = 0; + var base = alphabet.length; + var first = alphabet.charAt(0); + var digits = [0]; + for(i = 0; i < input.length; ++i) { + for(var j = 0, carry = input[i]; j < digits.length; ++j) { + carry += digits[j] << 8; + digits[j] = carry % base; + carry = (carry / base) | 0; + } + + while(carry > 0) { + digits.push(carry % base); + carry = (carry / base) | 0; + } + } + + // deal with leading zeros + for(i = 0; input[i] === 0 && i < input.length - 1; ++i) { + output += first; + } + // convert digits to a string + for(i = digits.length - 1; i >= 0; --i) { + output += alphabet[digits[i]]; + } + } + + if(maxline) { + var regex = new RegExp('.{1,' + maxline + '}', 'g'); + output = output.match(regex).join('\r\n'); + } + + return output; +}; + +/** + * Decodes a baseN-encoded (using the given alphabet) string to a + * Uint8Array. + * + * @param input the baseN-encoded input string. + * + * @return the Uint8Array. + */ +api.decode = function(input, alphabet) { + if(typeof input !== 'string') { + throw new TypeError('"input" must be a string.'); + } + if(typeof alphabet !== 'string') { + throw new TypeError('"alphabet" must be a string.'); + } + + var table = _reverseAlphabets[alphabet]; + if(!table) { + // compute reverse alphabet + table = _reverseAlphabets[alphabet] = []; + for(var i = 0; i < alphabet.length; ++i) { + table[alphabet.charCodeAt(i)] = i; + } + } + + // remove whitespace characters + input = input.replace(/\s/g, ''); + + var base = alphabet.length; + var first = alphabet.charAt(0); + var bytes = [0]; + for(var i = 0; i < input.length; i++) { + var value = table[input.charCodeAt(i)]; + if(value === undefined) { + return; + } + + for(var j = 0, carry = value; j < bytes.length; ++j) { + carry += bytes[j] * base; + bytes[j] = carry & 0xff; + carry >>= 8; + } + + while(carry > 0) { + bytes.push(carry & 0xff); + carry >>= 8; + } + } + + // deal with leading zeros + for(var k = 0; input[k] === first && k < input.length - 1; ++k) { + bytes.push(0); + } + + if(typeof Buffer !== 'undefined') { + return Buffer.from(bytes.reverse()); + } + + return new Uint8Array(bytes.reverse()); +}; + +function _encodeWithByteBuffer(input, alphabet) { + var i = 0; + var base = alphabet.length; + var first = alphabet.charAt(0); + var digits = [0]; + for(i = 0; i < input.length(); ++i) { + for(var j = 0, carry = input.at(i); j < digits.length; ++j) { + carry += digits[j] << 8; + digits[j] = carry % base; + carry = (carry / base) | 0; + } + + while(carry > 0) { + digits.push(carry % base); + carry = (carry / base) | 0; + } + } + + var output = ''; + + // deal with leading zeros + for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) { + output += first; + } + // convert digits to a string + for(i = digits.length - 1; i >= 0; --i) { + output += alphabet[digits[i]]; + } + + return output; +} diff --git a/node_modules/node-forge/lib/cipher.js b/node_modules/node-forge/lib/cipher.js new file mode 100644 index 0000000..f2c36e6 --- /dev/null +++ b/node_modules/node-forge/lib/cipher.js @@ -0,0 +1,230 @@ +/** + * Cipher base API. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./util'); + +module.exports = forge.cipher = forge.cipher || {}; + +// registered algorithms +forge.cipher.algorithms = forge.cipher.algorithms || {}; + +/** + * Creates a cipher object that can be used to encrypt data using the given + * algorithm and key. The algorithm may be provided as a string value for a + * previously registered algorithm or it may be given as a cipher algorithm + * API object. + * + * @param algorithm the algorithm to use, either a string or an algorithm API + * object. + * @param key the key to use, as a binary-encoded string of bytes or a + * byte buffer. + * + * @return the cipher. + */ +forge.cipher.createCipher = function(algorithm, key) { + var api = algorithm; + if(typeof api === 'string') { + api = forge.cipher.getAlgorithm(api); + if(api) { + api = api(); + } + } + if(!api) { + throw new Error('Unsupported algorithm: ' + algorithm); + } + + // assume block cipher + return new forge.cipher.BlockCipher({ + algorithm: api, + key: key, + decrypt: false + }); +}; + +/** + * Creates a decipher object that can be used to decrypt data using the given + * algorithm and key. The algorithm may be provided as a string value for a + * previously registered algorithm or it may be given as a cipher algorithm + * API object. + * + * @param algorithm the algorithm to use, either a string or an algorithm API + * object. + * @param key the key to use, as a binary-encoded string of bytes or a + * byte buffer. + * + * @return the cipher. + */ +forge.cipher.createDecipher = function(algorithm, key) { + var api = algorithm; + if(typeof api === 'string') { + api = forge.cipher.getAlgorithm(api); + if(api) { + api = api(); + } + } + if(!api) { + throw new Error('Unsupported algorithm: ' + algorithm); + } + + // assume block cipher + return new forge.cipher.BlockCipher({ + algorithm: api, + key: key, + decrypt: true + }); +}; + +/** + * Registers an algorithm by name. If the name was already registered, the + * algorithm API object will be overwritten. + * + * @param name the name of the algorithm. + * @param algorithm the algorithm API object. + */ +forge.cipher.registerAlgorithm = function(name, algorithm) { + name = name.toUpperCase(); + forge.cipher.algorithms[name] = algorithm; +}; + +/** + * Gets a registered algorithm by name. + * + * @param name the name of the algorithm. + * + * @return the algorithm, if found, null if not. + */ +forge.cipher.getAlgorithm = function(name) { + name = name.toUpperCase(); + if(name in forge.cipher.algorithms) { + return forge.cipher.algorithms[name]; + } + return null; +}; + +var BlockCipher = forge.cipher.BlockCipher = function(options) { + this.algorithm = options.algorithm; + this.mode = this.algorithm.mode; + this.blockSize = this.mode.blockSize; + this._finish = false; + this._input = null; + this.output = null; + this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt; + this._decrypt = options.decrypt; + this.algorithm.initialize(options); +}; + +/** + * Starts or restarts the encryption or decryption process, whichever + * was previously configured. + * + * For non-GCM mode, the IV may be a binary-encoded string of bytes, an array + * of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in + * bytes, then it must be Nb (16) bytes in length. If the IV is given in as + * 32-bit integers, then it must be 4 integers long. + * + * Note: an IV is not required or used in ECB mode. + * + * For GCM-mode, the IV must be given as a binary-encoded string of bytes or + * a byte buffer. The number of bytes should be 12 (96 bits) as recommended + * by NIST SP-800-38D but another length may be given. + * + * @param options the options to use: + * iv the initialization vector to use as a binary-encoded string of + * bytes, null to reuse the last ciphered block from a previous + * update() (this "residue" method is for legacy support only). + * additionalData additional authentication data as a binary-encoded + * string of bytes, for 'GCM' mode, (default: none). + * tagLength desired length of authentication tag, in bits, for + * 'GCM' mode (0-128, default: 128). + * tag the authentication tag to check if decrypting, as a + * binary-encoded string of bytes. + * output the output the buffer to write to, null to create one. + */ +BlockCipher.prototype.start = function(options) { + options = options || {}; + var opts = {}; + for(var key in options) { + opts[key] = options[key]; + } + opts.decrypt = this._decrypt; + this._finish = false; + this._input = forge.util.createBuffer(); + this.output = options.output || forge.util.createBuffer(); + this.mode.start(opts); +}; + +/** + * Updates the next block according to the cipher mode. + * + * @param input the buffer to read from. + */ +BlockCipher.prototype.update = function(input) { + if(input) { + // input given, so empty it into the input buffer + this._input.putBuffer(input); + } + + // do cipher operation until it needs more input and not finished + while(!this._op.call(this.mode, this._input, this.output, this._finish) && + !this._finish) {} + + // free consumed memory from input buffer + this._input.compact(); +}; + +/** + * Finishes encrypting or decrypting. + * + * @param pad a padding function to use in CBC mode, null for default, + * signature(blockSize, buffer, decrypt). + * + * @return true if successful, false on error. + */ +BlockCipher.prototype.finish = function(pad) { + // backwards-compatibility w/deprecated padding API + // Note: will overwrite padding functions even after another start() call + if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) { + this.mode.pad = function(input) { + return pad(this.blockSize, input, false); + }; + this.mode.unpad = function(output) { + return pad(this.blockSize, output, true); + }; + } + + // build options for padding and afterFinish functions + var options = {}; + options.decrypt = this._decrypt; + + // get # of bytes that won't fill a block + options.overflow = this._input.length() % this.blockSize; + + if(!this._decrypt && this.mode.pad) { + if(!this.mode.pad(this._input, options)) { + return false; + } + } + + // do final update + this._finish = true; + this.update(); + + if(this._decrypt && this.mode.unpad) { + if(!this.mode.unpad(this.output, options)) { + return false; + } + } + + if(this.mode.afterFinish) { + if(!this.mode.afterFinish(this.output, options)) { + return false; + } + } + + return true; +}; diff --git a/node_modules/node-forge/lib/cipherModes.js b/node_modules/node-forge/lib/cipherModes.js new file mode 100644 index 0000000..339915c --- /dev/null +++ b/node_modules/node-forge/lib/cipherModes.js @@ -0,0 +1,999 @@ +/** + * Supported cipher modes. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./util'); + +forge.cipher = forge.cipher || {}; + +// supported cipher modes +var modes = module.exports = forge.cipher.modes = forge.cipher.modes || {}; + +/** Electronic codebook (ECB) (Don't use this; it's not secure) **/ + +modes.ecb = function(options) { + options = options || {}; + this.name = 'ECB'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); +}; + +modes.ecb.prototype.start = function(options) {}; + +modes.ecb.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + if(input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + + // get next block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + } + + // encrypt block + this.cipher.encrypt(this._inBlock, this._outBlock); + + // write output + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); + } +}; + +modes.ecb.prototype.decrypt = function(input, output, finish) { + // not enough input to decrypt + if(input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + + // get next block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + } + + // decrypt block + this.cipher.decrypt(this._inBlock, this._outBlock); + + // write output + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); + } +}; + +modes.ecb.prototype.pad = function(input, options) { + // add PKCS#7 padding to block (each pad byte is the + // value of the number of pad bytes) + var padding = (input.length() === this.blockSize ? + this.blockSize : (this.blockSize - input.length())); + input.fillWithByte(padding, padding); + return true; +}; + +modes.ecb.prototype.unpad = function(output, options) { + // check for error: input data not a multiple of blockSize + if(options.overflow > 0) { + return false; + } + + // ensure padding byte count is valid + var len = output.length(); + var count = output.at(len - 1); + if(count > (this.blockSize << 2)) { + return false; + } + + // trim off padding bytes + output.truncate(count); + return true; +}; + +/** Cipher-block Chaining (CBC) **/ + +modes.cbc = function(options) { + options = options || {}; + this.name = 'CBC'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); +}; + +modes.cbc.prototype.start = function(options) { + // Note: legacy support for using IV residue (has security flaws) + // if IV is null, reuse block from previous processing + if(options.iv === null) { + // must have a previous block + if(!this._prev) { + throw new Error('Invalid IV parameter.'); + } + this._iv = this._prev.slice(0); + } else if(!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } else { + // save IV as "previous" block + this._iv = transformIV(options.iv, this.blockSize); + this._prev = this._iv.slice(0); + } +}; + +modes.cbc.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + if(input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + + // get next block + // CBC XOR's IV (or previous block) with plaintext + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._prev[i] ^ input.getInt32(); + } + + // encrypt block + this.cipher.encrypt(this._inBlock, this._outBlock); + + // write output, save previous block + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); + } + this._prev = this._outBlock; +}; + +modes.cbc.prototype.decrypt = function(input, output, finish) { + // not enough input to decrypt + if(input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + + // get next block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + } + + // decrypt block + this.cipher.decrypt(this._inBlock, this._outBlock); + + // write output, save previous ciphered block + // CBC XOR's IV (or previous block) with ciphertext + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._prev[i] ^ this._outBlock[i]); + } + this._prev = this._inBlock.slice(0); +}; + +modes.cbc.prototype.pad = function(input, options) { + // add PKCS#7 padding to block (each pad byte is the + // value of the number of pad bytes) + var padding = (input.length() === this.blockSize ? + this.blockSize : (this.blockSize - input.length())); + input.fillWithByte(padding, padding); + return true; +}; + +modes.cbc.prototype.unpad = function(output, options) { + // check for error: input data not a multiple of blockSize + if(options.overflow > 0) { + return false; + } + + // ensure padding byte count is valid + var len = output.length(); + var count = output.at(len - 1); + if(count > (this.blockSize << 2)) { + return false; + } + + // trim off padding bytes + output.truncate(count); + return true; +}; + +/** Cipher feedback (CFB) **/ + +modes.cfb = function(options) { + options = options || {}; + this.name = 'CFB'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; +}; + +modes.cfb.prototype.start = function(options) { + if(!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } + // use IV as first input + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; +}; + +modes.cfb.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + var inputLength = input.length(); + if(inputLength === 0) { + return true; + } + + // encrypt block + this.cipher.encrypt(this._inBlock, this._outBlock); + + // handle full block + if(this._partialBytes === 0 && inputLength >= this.blockSize) { + // XOR input with output, write input as output + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32() ^ this._outBlock[i]; + output.putInt32(this._inBlock[i]); + } + return; + } + + // handle partial block + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if(partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + + // XOR input with output, write input as partial output + this._partialOutput.clear(); + for(var i = 0; i < this._ints; ++i) { + this._partialBlock[i] = input.getInt32() ^ this._outBlock[i]; + this._partialOutput.putInt32(this._partialBlock[i]); + } + + if(partialBytes > 0) { + // block still incomplete, restore input buffer + input.read -= this.blockSize; + } else { + // block complete, update input block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._partialBlock[i]; + } + } + + // skip any previous partial bytes + if(this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + + if(partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes)); + this._partialBytes = 0; +}; + +modes.cfb.prototype.decrypt = function(input, output, finish) { + // not enough input to decrypt + var inputLength = input.length(); + if(inputLength === 0) { + return true; + } + + // encrypt block (CFB always uses encryption mode) + this.cipher.encrypt(this._inBlock, this._outBlock); + + // handle full block + if(this._partialBytes === 0 && inputLength >= this.blockSize) { + // XOR input with output, write input as output + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + output.putInt32(this._inBlock[i] ^ this._outBlock[i]); + } + return; + } + + // handle partial block + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if(partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + + // XOR input with output, write input as partial output + this._partialOutput.clear(); + for(var i = 0; i < this._ints; ++i) { + this._partialBlock[i] = input.getInt32(); + this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]); + } + + if(partialBytes > 0) { + // block still incomplete, restore input buffer + input.read -= this.blockSize; + } else { + // block complete, update input block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._partialBlock[i]; + } + } + + // skip any previous partial bytes + if(this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + + if(partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes)); + this._partialBytes = 0; +}; + +/** Output feedback (OFB) **/ + +modes.ofb = function(options) { + options = options || {}; + this.name = 'OFB'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; +}; + +modes.ofb.prototype.start = function(options) { + if(!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } + // use IV as first input + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; +}; + +modes.ofb.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + var inputLength = input.length(); + if(input.length() === 0) { + return true; + } + + // encrypt block (OFB always uses encryption mode) + this.cipher.encrypt(this._inBlock, this._outBlock); + + // handle full block + if(this._partialBytes === 0 && inputLength >= this.blockSize) { + // XOR input with output and update next input + for(var i = 0; i < this._ints; ++i) { + output.putInt32(input.getInt32() ^ this._outBlock[i]); + this._inBlock[i] = this._outBlock[i]; + } + return; + } + + // handle partial block + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if(partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + + // XOR input with output + this._partialOutput.clear(); + for(var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); + } + + if(partialBytes > 0) { + // block still incomplete, restore input buffer + input.read -= this.blockSize; + } else { + // block complete, update input block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._outBlock[i]; + } + } + + // skip any previous partial bytes + if(this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + + if(partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes)); + this._partialBytes = 0; +}; + +modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt; + +/** Counter (CTR) **/ + +modes.ctr = function(options) { + options = options || {}; + this.name = 'CTR'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; +}; + +modes.ctr.prototype.start = function(options) { + if(!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } + // use IV as first input + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; +}; + +modes.ctr.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + var inputLength = input.length(); + if(inputLength === 0) { + return true; + } + + // encrypt block (CTR always uses encryption mode) + this.cipher.encrypt(this._inBlock, this._outBlock); + + // handle full block + if(this._partialBytes === 0 && inputLength >= this.blockSize) { + // XOR input with output + for(var i = 0; i < this._ints; ++i) { + output.putInt32(input.getInt32() ^ this._outBlock[i]); + } + } else { + // handle partial block + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if(partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + + // XOR input with output + this._partialOutput.clear(); + for(var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); + } + + if(partialBytes > 0) { + // block still incomplete, restore input buffer + input.read -= this.blockSize; + } + + // skip any previous partial bytes + if(this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + + if(partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes)); + this._partialBytes = 0; + } + + // block complete, increment counter (input block) + inc32(this._inBlock); +}; + +modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt; + +/** Galois/Counter Mode (GCM) **/ + +modes.gcm = function(options) { + options = options || {}; + this.name = 'GCM'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; + + // R is actually this value concatenated with 120 more zero bits, but + // we only XOR against R so the other zeros have no effect -- we just + // apply this value to the first integer in a block + this._R = 0xE1000000; +}; + +modes.gcm.prototype.start = function(options) { + if(!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } + // ensure IV is a byte buffer + var iv = forge.util.createBuffer(options.iv); + + // no ciphered data processed yet + this._cipherLength = 0; + + // default additional data is none + var additionalData; + if('additionalData' in options) { + additionalData = forge.util.createBuffer(options.additionalData); + } else { + additionalData = forge.util.createBuffer(); + } + + // default tag length is 128 bits + if('tagLength' in options) { + this._tagLength = options.tagLength; + } else { + this._tagLength = 128; + } + + // if tag is given, ensure tag matches tag length + this._tag = null; + if(options.decrypt) { + // save tag to check later + this._tag = forge.util.createBuffer(options.tag).getBytes(); + if(this._tag.length !== (this._tagLength / 8)) { + throw new Error('Authentication tag does not match tag length.'); + } + } + + // create tmp storage for hash calculation + this._hashBlock = new Array(this._ints); + + // no tag generated yet + this.tag = null; + + // generate hash subkey + // (apply block cipher to "zero" block) + this._hashSubkey = new Array(this._ints); + this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey); + + // generate table M + // use 4-bit tables (32 component decomposition of a 16 byte value) + // 8-bit tables take more space and are known to have security + // vulnerabilities (in native implementations) + this.componentBits = 4; + this._m = this.generateHashTable(this._hashSubkey, this.componentBits); + + // Note: support IV length different from 96 bits? (only supporting + // 96 bits is recommended by NIST SP-800-38D) + // generate J_0 + var ivLength = iv.length(); + if(ivLength === 12) { + // 96-bit IV + this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1]; + } else { + // IV is NOT 96-bits + this._j0 = [0, 0, 0, 0]; + while(iv.length() > 0) { + this._j0 = this.ghash( + this._hashSubkey, this._j0, + [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]); + } + this._j0 = this.ghash( + this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8))); + } + + // generate ICB (initial counter block) + this._inBlock = this._j0.slice(0); + inc32(this._inBlock); + this._partialBytes = 0; + + // consume authentication data + additionalData = forge.util.createBuffer(additionalData); + // save additional data length as a BE 64-bit number + this._aDataLength = from64To32(additionalData.length() * 8); + // pad additional data to 128 bit (16 byte) block size + var overflow = additionalData.length() % this.blockSize; + if(overflow) { + additionalData.fillWithByte(0, this.blockSize - overflow); + } + this._s = [0, 0, 0, 0]; + while(additionalData.length() > 0) { + this._s = this.ghash(this._hashSubkey, this._s, [ + additionalData.getInt32(), + additionalData.getInt32(), + additionalData.getInt32(), + additionalData.getInt32() + ]); + } +}; + +modes.gcm.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + var inputLength = input.length(); + if(inputLength === 0) { + return true; + } + + // encrypt block + this.cipher.encrypt(this._inBlock, this._outBlock); + + // handle full block + if(this._partialBytes === 0 && inputLength >= this.blockSize) { + // XOR input with output + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i] ^= input.getInt32()); + } + this._cipherLength += this.blockSize; + } else { + // handle partial block + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if(partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + + // XOR input with output + this._partialOutput.clear(); + for(var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); + } + + if(partialBytes <= 0 || finish) { + // handle overflow prior to hashing + if(finish) { + // get block overflow + var overflow = inputLength % this.blockSize; + this._cipherLength += overflow; + // truncate for hash function + this._partialOutput.truncate(this.blockSize - overflow); + } else { + this._cipherLength += this.blockSize; + } + + // get output block for hashing + for(var i = 0; i < this._ints; ++i) { + this._outBlock[i] = this._partialOutput.getInt32(); + } + this._partialOutput.read -= this.blockSize; + } + + // skip any previous partial bytes + if(this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + + if(partialBytes > 0 && !finish) { + // block still incomplete, restore input buffer, get partial output, + // and return early + input.read -= this.blockSize; + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes)); + this._partialBytes = 0; + } + + // update hash block S + this._s = this.ghash(this._hashSubkey, this._s, this._outBlock); + + // increment counter (input block) + inc32(this._inBlock); +}; + +modes.gcm.prototype.decrypt = function(input, output, finish) { + // not enough input to decrypt + var inputLength = input.length(); + if(inputLength < this.blockSize && !(finish && inputLength > 0)) { + return true; + } + + // encrypt block (GCM always uses encryption mode) + this.cipher.encrypt(this._inBlock, this._outBlock); + + // increment counter (input block) + inc32(this._inBlock); + + // update hash block S + this._hashBlock[0] = input.getInt32(); + this._hashBlock[1] = input.getInt32(); + this._hashBlock[2] = input.getInt32(); + this._hashBlock[3] = input.getInt32(); + this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock); + + // XOR hash input with output + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i] ^ this._hashBlock[i]); + } + + // increment cipher data length + if(inputLength < this.blockSize) { + this._cipherLength += inputLength % this.blockSize; + } else { + this._cipherLength += this.blockSize; + } +}; + +modes.gcm.prototype.afterFinish = function(output, options) { + var rval = true; + + // handle overflow + if(options.decrypt && options.overflow) { + output.truncate(this.blockSize - options.overflow); + } + + // handle authentication tag + this.tag = forge.util.createBuffer(); + + // concatenate additional data length with cipher length + var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8)); + + // include lengths in hash + this._s = this.ghash(this._hashSubkey, this._s, lengths); + + // do GCTR(J_0, S) + var tag = []; + this.cipher.encrypt(this._j0, tag); + for(var i = 0; i < this._ints; ++i) { + this.tag.putInt32(this._s[i] ^ tag[i]); + } + + // trim tag to length + this.tag.truncate(this.tag.length() % (this._tagLength / 8)); + + // check authentication tag + if(options.decrypt && this.tag.bytes() !== this._tag) { + rval = false; + } + + return rval; +}; + +/** + * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois + * field multiplication. The field, GF(2^128), is defined by the polynomial: + * + * x^128 + x^7 + x^2 + x + 1 + * + * Which is represented in little-endian binary form as: 11100001 (0xe1). When + * the value of a coefficient is 1, a bit is set. The value R, is the + * concatenation of this value and 120 zero bits, yielding a 128-bit value + * which matches the block size. + * + * This function will multiply two elements (vectors of bytes), X and Y, in + * the field GF(2^128). The result is initialized to zero. For each bit of + * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd) + * by the current value of Y. For each bit, the value of Y will be raised by + * a power of x (multiplied by the polynomial x). This can be achieved by + * shifting Y once to the right. If the current value of Y, prior to being + * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial. + * Otherwise, we must divide by R after shifting to find the remainder. + * + * @param x the first block to multiply by the second. + * @param y the second block to multiply by the first. + * + * @return the block result of the multiplication. + */ +modes.gcm.prototype.multiply = function(x, y) { + var z_i = [0, 0, 0, 0]; + var v_i = y.slice(0); + + // calculate Z_128 (block has 128 bits) + for(var i = 0; i < 128; ++i) { + // if x_i is 0, Z_{i+1} = Z_i (unchanged) + // else Z_{i+1} = Z_i ^ V_i + // get x_i by finding 32-bit int position, then left shift 1 by remainder + var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32)); + if(x_i) { + z_i[0] ^= v_i[0]; + z_i[1] ^= v_i[1]; + z_i[2] ^= v_i[2]; + z_i[3] ^= v_i[3]; + } + + // if LSB(V_i) is 1, V_i = V_i >> 1 + // else V_i = (V_i >> 1) ^ R + this.pow(v_i, v_i); + } + + return z_i; +}; + +modes.gcm.prototype.pow = function(x, out) { + // if LSB(x) is 1, x = x >>> 1 + // else x = (x >>> 1) ^ R + var lsb = x[3] & 1; + + // always do x >>> 1: + // starting with the rightmost integer, shift each integer to the right + // one bit, pulling in the bit from the integer to the left as its top + // most bit (do this for the last 3 integers) + for(var i = 3; i > 0; --i) { + out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31); + } + // shift the first integer normally + out[0] = x[0] >>> 1; + + // if lsb was not set, then polynomial had a degree of 127 and doesn't + // need to divided; otherwise, XOR with R to find the remainder; we only + // need to XOR the first integer since R technically ends w/120 zero bits + if(lsb) { + out[0] ^= this._R; + } +}; + +modes.gcm.prototype.tableMultiply = function(x) { + // assumes 4-bit tables are used + var z = [0, 0, 0, 0]; + for(var i = 0; i < 32; ++i) { + var idx = (i / 8) | 0; + var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF; + var ah = this._m[i][x_i]; + z[0] ^= ah[0]; + z[1] ^= ah[1]; + z[2] ^= ah[2]; + z[3] ^= ah[3]; + } + return z; +}; + +/** + * A continuing version of the GHASH algorithm that operates on a single + * block. The hash block, last hash value (Ym) and the new block to hash + * are given. + * + * @param h the hash block. + * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash. + * @param x the block to hash. + * + * @return the hashed value (Ym). + */ +modes.gcm.prototype.ghash = function(h, y, x) { + y[0] ^= x[0]; + y[1] ^= x[1]; + y[2] ^= x[2]; + y[3] ^= x[3]; + return this.tableMultiply(y); + //return this.multiply(y, h); +}; + +/** + * Precomputes a table for multiplying against the hash subkey. This + * mechanism provides a substantial speed increase over multiplication + * performed without a table. The table-based multiplication this table is + * for solves X * H by multiplying each component of X by H and then + * composing the results together using XOR. + * + * This function can be used to generate tables with different bit sizes + * for the components, however, this implementation assumes there are + * 32 components of X (which is a 16 byte vector), therefore each component + * takes 4-bits (so the table is constructed with bits=4). + * + * @param h the hash subkey. + * @param bits the bit size for a component. + */ +modes.gcm.prototype.generateHashTable = function(h, bits) { + // TODO: There are further optimizations that would use only the + // first table M_0 (or some variant) along with a remainder table; + // this can be explored in the future + var multiplier = 8 / bits; + var perInt = 4 * multiplier; + var size = 16 * multiplier; + var m = new Array(size); + for(var i = 0; i < size; ++i) { + var tmp = [0, 0, 0, 0]; + var idx = (i / perInt) | 0; + var shft = ((perInt - 1 - (i % perInt)) * bits); + tmp[idx] = (1 << (bits - 1)) << shft; + m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits); + } + return m; +}; + +/** + * Generates a table for multiplying against the hash subkey for one + * particular component (out of all possible component values). + * + * @param mid the pre-multiplied value for the middle key of the table. + * @param bits the bit size for a component. + */ +modes.gcm.prototype.generateSubHashTable = function(mid, bits) { + // compute the table quickly by minimizing the number of + // POW operations -- they only need to be performed for powers of 2, + // all other entries can be composed from those powers using XOR + var size = 1 << bits; + var half = size >>> 1; + var m = new Array(size); + m[half] = mid.slice(0); + var i = half >>> 1; + while(i > 0) { + // raise m0[2 * i] and store in m0[i] + this.pow(m[2 * i], m[i] = []); + i >>= 1; + } + i = 2; + while(i < half) { + for(var j = 1; j < i; ++j) { + var m_i = m[i]; + var m_j = m[j]; + m[i + j] = [ + m_i[0] ^ m_j[0], + m_i[1] ^ m_j[1], + m_i[2] ^ m_j[2], + m_i[3] ^ m_j[3] + ]; + } + i *= 2; + } + m[0] = [0, 0, 0, 0]; + /* Note: We could avoid storing these by doing composition during multiply + calculate top half using composition by speed is preferred. */ + for(i = half + 1; i < size; ++i) { + var c = m[i ^ half]; + m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]]; + } + return m; +}; + +/** Utility functions */ + +function transformIV(iv, blockSize) { + if(typeof iv === 'string') { + // convert iv string into byte buffer + iv = forge.util.createBuffer(iv); + } + + if(forge.util.isArray(iv) && iv.length > 4) { + // convert iv byte array into byte buffer + var tmp = iv; + iv = forge.util.createBuffer(); + for(var i = 0; i < tmp.length; ++i) { + iv.putByte(tmp[i]); + } + } + + if(iv.length() < blockSize) { + throw new Error( + 'Invalid IV length; got ' + iv.length() + + ' bytes and expected ' + blockSize + ' bytes.'); + } + + if(!forge.util.isArray(iv)) { + // convert iv byte buffer into 32-bit integer array + var ints = []; + var blocks = blockSize / 4; + for(var i = 0; i < blocks; ++i) { + ints.push(iv.getInt32()); + } + iv = ints; + } + + return iv; +} + +function inc32(block) { + // increment last 32 bits of block only + block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF; +} + +function from64To32(num) { + // convert 64-bit number to two BE Int32s + return [(num / 0x100000000) | 0, num & 0xFFFFFFFF]; +} diff --git a/node_modules/node-forge/lib/des.js b/node_modules/node-forge/lib/des.js new file mode 100644 index 0000000..ed8239a --- /dev/null +++ b/node_modules/node-forge/lib/des.js @@ -0,0 +1,496 @@ +/** + * DES (Data Encryption Standard) implementation. + * + * This implementation supports DES as well as 3DES-EDE in ECB and CBC mode. + * It is based on the BSD-licensed implementation by Paul Tero: + * + * Paul Tero, July 2001 + * http://www.tero.co.uk/des/ + * + * Optimised for performance with large blocks by + * Michael Hayworth, November 2001 + * http://www.netdealing.com + * + * THIS SOFTWARE IS PROVIDED "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @author Stefan Siegl + * @author Dave Longley + * + * Copyright (c) 2012 Stefan Siegl + * Copyright (c) 2012-2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./cipher'); +require('./cipherModes'); +require('./util'); + +/* DES API */ +module.exports = forge.des = forge.des || {}; + +/** + * Deprecated. Instead, use: + * + * var cipher = forge.cipher.createCipher('DES-', key); + * cipher.start({iv: iv}); + * + * Creates an DES cipher object to encrypt data using the given symmetric key. + * The output will be stored in the 'output' member of the returned cipher. + * + * The key and iv may be given as binary-encoded strings of bytes or + * byte buffers. + * + * @param key the symmetric key to use (64 or 192 bits). + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * @param mode the cipher mode to use (default: 'CBC' if IV is + * given, 'ECB' if null). + * + * @return the cipher. + */ +forge.des.startEncrypting = function(key, iv, output, mode) { + var cipher = _createCipher({ + key: key, + output: output, + decrypt: false, + mode: mode || (iv === null ? 'ECB' : 'CBC') + }); + cipher.start(iv); + return cipher; +}; + +/** + * Deprecated. Instead, use: + * + * var cipher = forge.cipher.createCipher('DES-', key); + * + * Creates an DES cipher object to encrypt data using the given symmetric key. + * + * The key may be given as a binary-encoded string of bytes or a byte buffer. + * + * @param key the symmetric key to use (64 or 192 bits). + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge.des.createEncryptionCipher = function(key, mode) { + return _createCipher({ + key: key, + output: null, + decrypt: false, + mode: mode + }); +}; + +/** + * Deprecated. Instead, use: + * + * var decipher = forge.cipher.createDecipher('DES-', key); + * decipher.start({iv: iv}); + * + * Creates an DES cipher object to decrypt data using the given symmetric key. + * The output will be stored in the 'output' member of the returned cipher. + * + * The key and iv may be given as binary-encoded strings of bytes or + * byte buffers. + * + * @param key the symmetric key to use (64 or 192 bits). + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * @param mode the cipher mode to use (default: 'CBC' if IV is + * given, 'ECB' if null). + * + * @return the cipher. + */ +forge.des.startDecrypting = function(key, iv, output, mode) { + var cipher = _createCipher({ + key: key, + output: output, + decrypt: true, + mode: mode || (iv === null ? 'ECB' : 'CBC') + }); + cipher.start(iv); + return cipher; +}; + +/** + * Deprecated. Instead, use: + * + * var decipher = forge.cipher.createDecipher('DES-', key); + * + * Creates an DES cipher object to decrypt data using the given symmetric key. + * + * The key may be given as a binary-encoded string of bytes or a byte buffer. + * + * @param key the symmetric key to use (64 or 192 bits). + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge.des.createDecryptionCipher = function(key, mode) { + return _createCipher({ + key: key, + output: null, + decrypt: true, + mode: mode + }); +}; + +/** + * Creates a new DES cipher algorithm object. + * + * @param name the name of the algorithm. + * @param mode the mode factory function. + * + * @return the DES algorithm object. + */ +forge.des.Algorithm = function(name, mode) { + var self = this; + self.name = name; + self.mode = new mode({ + blockSize: 8, + cipher: { + encrypt: function(inBlock, outBlock) { + return _updateBlock(self._keys, inBlock, outBlock, false); + }, + decrypt: function(inBlock, outBlock) { + return _updateBlock(self._keys, inBlock, outBlock, true); + } + } + }); + self._init = false; +}; + +/** + * Initializes this DES algorithm by expanding its key. + * + * @param options the options to use. + * key the key to use with this algorithm. + * decrypt true if the algorithm should be initialized for decryption, + * false for encryption. + */ +forge.des.Algorithm.prototype.initialize = function(options) { + if(this._init) { + return; + } + + var key = forge.util.createBuffer(options.key); + if(this.name.indexOf('3DES') === 0) { + if(key.length() !== 24) { + throw new Error('Invalid Triple-DES key size: ' + key.length() * 8); + } + } + + // do key expansion to 16 or 48 subkeys (single or triple DES) + this._keys = _createKeys(key); + this._init = true; +}; + +/** Register DES algorithms **/ + +registerAlgorithm('DES-ECB', forge.cipher.modes.ecb); +registerAlgorithm('DES-CBC', forge.cipher.modes.cbc); +registerAlgorithm('DES-CFB', forge.cipher.modes.cfb); +registerAlgorithm('DES-OFB', forge.cipher.modes.ofb); +registerAlgorithm('DES-CTR', forge.cipher.modes.ctr); + +registerAlgorithm('3DES-ECB', forge.cipher.modes.ecb); +registerAlgorithm('3DES-CBC', forge.cipher.modes.cbc); +registerAlgorithm('3DES-CFB', forge.cipher.modes.cfb); +registerAlgorithm('3DES-OFB', forge.cipher.modes.ofb); +registerAlgorithm('3DES-CTR', forge.cipher.modes.ctr); + +function registerAlgorithm(name, mode) { + var factory = function() { + return new forge.des.Algorithm(name, mode); + }; + forge.cipher.registerAlgorithm(name, factory); +} + +/** DES implementation **/ + +var spfunction1 = [0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004]; +var spfunction2 = [-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000]; +var spfunction3 = [0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200]; +var spfunction4 = [0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080]; +var spfunction5 = [0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100]; +var spfunction6 = [0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010]; +var spfunction7 = [0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002]; +var spfunction8 = [0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000]; + +/** + * Create necessary sub keys. + * + * @param key the 64-bit or 192-bit key. + * + * @return the expanded keys. + */ +function _createKeys(key) { + var pc2bytes0 = [0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204], + pc2bytes1 = [0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101], + pc2bytes2 = [0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808], + pc2bytes3 = [0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000], + pc2bytes4 = [0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010], + pc2bytes5 = [0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420], + pc2bytes6 = [0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002], + pc2bytes7 = [0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800], + pc2bytes8 = [0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002], + pc2bytes9 = [0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408], + pc2bytes10 = [0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020], + pc2bytes11 = [0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200], + pc2bytes12 = [0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010], + pc2bytes13 = [0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105]; + + // how many iterations (1 for des, 3 for triple des) + // changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys + var iterations = key.length() > 8 ? 3 : 1; + + // stores the return keys + var keys = []; + + // now define the left shifts which need to be done + var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; + + var n = 0, tmp; + for(var j = 0; j < iterations; j++) { + var left = key.getInt32(); + var right = key.getInt32(); + + tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= tmp; + left ^= (tmp << 4); + + tmp = ((right >>> -16) ^ left) & 0x0000ffff; + left ^= tmp; + right ^= (tmp << -16); + + tmp = ((left >>> 2) ^ right) & 0x33333333; + right ^= tmp; + left ^= (tmp << 2); + + tmp = ((right >>> -16) ^ left) & 0x0000ffff; + left ^= tmp; + right ^= (tmp << -16); + + tmp = ((left >>> 1) ^ right) & 0x55555555; + right ^= tmp; + left ^= (tmp << 1); + + tmp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= tmp; + right ^= (tmp << 8); + + tmp = ((left >>> 1) ^ right) & 0x55555555; + right ^= tmp; + left ^= (tmp << 1); + + // right needs to be shifted and OR'd with last four bits of left + tmp = (left << 8) | ((right >>> 20) & 0x000000f0); + + // left needs to be put upside down + left = ((right << 24) | ((right << 8) & 0xff0000) | + ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0)); + right = tmp; + + // now go through and perform these shifts on the left and right keys + for(var i = 0; i < shifts.length; ++i) { + //shift the keys either one or two bits to the left + if(shifts[i]) { + left = (left << 2) | (left >>> 26); + right = (right << 2) | (right >>> 26); + } else { + left = (left << 1) | (left >>> 27); + right = (right << 1) | (right >>> 27); + } + left &= -0xf; + right &= -0xf; + + // now apply PC-2, in such a way that E is easier when encrypting or + // decrypting this conversion will look like PC-2 except only the last 6 + // bits of each byte are used rather than 48 consecutive bits and the + // order of lines will be according to how the S selection functions will + // be applied: S2, S4, S6, S8, S1, S3, S5, S7 + var lefttmp = ( + pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | + pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf] | + pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | + pc2bytes6[(left >>> 4) & 0xf]); + var righttmp = ( + pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | + pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf] | + pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] | + pc2bytes13[(right >>> 4) & 0xf]); + tmp = ((righttmp >>> 16) ^ lefttmp) & 0x0000ffff; + keys[n++] = lefttmp ^ tmp; + keys[n++] = righttmp ^ (tmp << 16); + } + } + + return keys; +} + +/** + * Updates a single block (1 byte) using DES. The update will either + * encrypt or decrypt the block. + * + * @param keys the expanded keys. + * @param input the input block (an array of 32-bit words). + * @param output the updated output block. + * @param decrypt true to decrypt the block, false to encrypt it. + */ +function _updateBlock(keys, input, output, decrypt) { + // set up loops for single or triple DES + var iterations = keys.length === 32 ? 3 : 9; + var looping; + if(iterations === 3) { + looping = decrypt ? [30, -2, -2] : [0, 32, 2]; + } else { + looping = (decrypt ? + [94, 62, -2, 32, 64, 2, 30, -2, -2] : + [0, 32, 2, 62, 30, -2, 64, 96, 2]); + } + + var tmp; + + var left = input[0]; + var right = input[1]; + + // first each 64 bit chunk of the message must be permuted according to IP + tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= tmp; + left ^= (tmp << 4); + + tmp = ((left >>> 16) ^ right) & 0x0000ffff; + right ^= tmp; + left ^= (tmp << 16); + + tmp = ((right >>> 2) ^ left) & 0x33333333; + left ^= tmp; + right ^= (tmp << 2); + + tmp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= tmp; + right ^= (tmp << 8); + + tmp = ((left >>> 1) ^ right) & 0x55555555; + right ^= tmp; + left ^= (tmp << 1); + + // rotate left 1 bit + left = ((left << 1) | (left >>> 31)); + right = ((right << 1) | (right >>> 31)); + + for(var j = 0; j < iterations; j += 3) { + var endloop = looping[j + 1]; + var loopinc = looping[j + 2]; + + // now go through and perform the encryption or decryption + for(var i = looping[j]; i != endloop; i += loopinc) { + var right1 = right ^ keys[i]; + var right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1]; + + // passing these bytes through the S selection functions + tmp = left; + left = right; + right = tmp ^ ( + spfunction2[(right1 >>> 24) & 0x3f] | + spfunction4[(right1 >>> 16) & 0x3f] | + spfunction6[(right1 >>> 8) & 0x3f] | + spfunction8[right1 & 0x3f] | + spfunction1[(right2 >>> 24) & 0x3f] | + spfunction3[(right2 >>> 16) & 0x3f] | + spfunction5[(right2 >>> 8) & 0x3f] | + spfunction7[right2 & 0x3f]); + } + // unreverse left and right + tmp = left; + left = right; + right = tmp; + } + + // rotate right 1 bit + left = ((left >>> 1) | (left << 31)); + right = ((right >>> 1) | (right << 31)); + + // now perform IP-1, which is IP in the opposite direction + tmp = ((left >>> 1) ^ right) & 0x55555555; + right ^= tmp; + left ^= (tmp << 1); + + tmp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= tmp; + right ^= (tmp << 8); + + tmp = ((right >>> 2) ^ left) & 0x33333333; + left ^= tmp; + right ^= (tmp << 2); + + tmp = ((left >>> 16) ^ right) & 0x0000ffff; + right ^= tmp; + left ^= (tmp << 16); + + tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= tmp; + left ^= (tmp << 4); + + output[0] = left; + output[1] = right; +} + +/** + * Deprecated. Instead, use: + * + * forge.cipher.createCipher('DES-', key); + * forge.cipher.createDecipher('DES-', key); + * + * Creates a deprecated DES cipher object. This object's mode will default to + * CBC (cipher-block-chaining). + * + * The key may be given as a binary-encoded string of bytes or a byte buffer. + * + * @param options the options to use. + * key the symmetric key to use (64 or 192 bits). + * output the buffer to write to. + * decrypt true for decryption, false for encryption. + * mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +function _createCipher(options) { + options = options || {}; + var mode = (options.mode || 'CBC').toUpperCase(); + var algorithm = 'DES-' + mode; + + var cipher; + if(options.decrypt) { + cipher = forge.cipher.createDecipher(algorithm, options.key); + } else { + cipher = forge.cipher.createCipher(algorithm, options.key); + } + + // backwards compatible start API + var start = cipher.start; + cipher.start = function(iv, options) { + // backwards compatibility: support second arg as output buffer + var output = null; + if(options instanceof forge.util.ByteBuffer) { + output = options; + options = {}; + } + options = options || {}; + options.output = output; + options.iv = iv; + start.call(cipher, options); + }; + + return cipher; +} diff --git a/node_modules/node-forge/lib/ed25519.js b/node_modules/node-forge/lib/ed25519.js new file mode 100644 index 0000000..f3e6faa --- /dev/null +++ b/node_modules/node-forge/lib/ed25519.js @@ -0,0 +1,1072 @@ +/** + * JavaScript implementation of Ed25519. + * + * Copyright (c) 2017-2019 Digital Bazaar, Inc. + * + * This implementation is based on the most excellent TweetNaCl which is + * in the public domain. Many thanks to its contributors: + * + * https://github.com/dchest/tweetnacl-js + */ +var forge = require('./forge'); +require('./jsbn'); +require('./random'); +require('./sha512'); +require('./util'); +var asn1Validator = require('./asn1-validator'); +var publicKeyValidator = asn1Validator.publicKeyValidator; +var privateKeyValidator = asn1Validator.privateKeyValidator; + +if(typeof BigInteger === 'undefined') { + var BigInteger = forge.jsbn.BigInteger; +} + +var ByteBuffer = forge.util.ByteBuffer; +var NativeBuffer = typeof Buffer === 'undefined' ? Uint8Array : Buffer; + +/* + * Ed25519 algorithms, see RFC 8032: + * https://tools.ietf.org/html/rfc8032 + */ +forge.pki = forge.pki || {}; +module.exports = forge.pki.ed25519 = forge.ed25519 = forge.ed25519 || {}; +var ed25519 = forge.ed25519; + +ed25519.constants = {}; +ed25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32; +ed25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64; +ed25519.constants.SEED_BYTE_LENGTH = 32; +ed25519.constants.SIGN_BYTE_LENGTH = 64; +ed25519.constants.HASH_BYTE_LENGTH = 64; + +ed25519.generateKeyPair = function(options) { + options = options || {}; + var seed = options.seed; + if(seed === undefined) { + // generate seed + seed = forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH); + } else if(typeof seed === 'string') { + if(seed.length !== ed25519.constants.SEED_BYTE_LENGTH) { + throw new TypeError( + '"seed" must be ' + ed25519.constants.SEED_BYTE_LENGTH + + ' bytes in length.'); + } + } else if(!(seed instanceof Uint8Array)) { + throw new TypeError( + '"seed" must be a node.js Buffer, Uint8Array, or a binary string.'); + } + + seed = messageToNativeBuffer({message: seed, encoding: 'binary'}); + + var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); + var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); + for(var i = 0; i < 32; ++i) { + sk[i] = seed[i]; + } + crypto_sign_keypair(pk, sk); + return {publicKey: pk, privateKey: sk}; +}; + +/** + * Converts a private key from a RFC8410 ASN.1 encoding. + * + * @param obj - The asn1 representation of a private key. + * + * @returns {Object} keyInfo - The key information. + * @returns {Buffer|Uint8Array} keyInfo.privateKeyBytes - 32 private key bytes. + */ +ed25519.privateKeyFromAsn1 = function(obj) { + var capture = {}; + var errors = []; + var valid = forge.asn1.validate(obj, privateKeyValidator, capture, errors); + if(!valid) { + var error = new Error('Invalid Key.'); + error.errors = errors; + throw error; + } + var oid = forge.asn1.derToOid(capture.privateKeyOid); + var ed25519Oid = forge.oids.EdDSA25519; + if(oid !== ed25519Oid) { + throw new Error('Invalid OID "' + oid + '"; OID must be "' + + ed25519Oid + '".'); + } + var privateKey = capture.privateKey; + // manually extract the private key bytes from nested octet string, see FIXME: + // https://github.com/digitalbazaar/forge/blob/master/lib/asn1.js#L542 + var privateKeyBytes = messageToNativeBuffer({ + message: forge.asn1.fromDer(privateKey).value, + encoding: 'binary' + }); + // TODO: RFC8410 specifies a format for encoding the public key bytes along + // with the private key bytes. `publicKeyBytes` can be returned in the + // future. https://tools.ietf.org/html/rfc8410#section-10.3 + return {privateKeyBytes: privateKeyBytes}; +}; + +/** + * Converts a public key from a RFC8410 ASN.1 encoding. + * + * @param obj - The asn1 representation of a public key. + * + * @return {Buffer|Uint8Array} - 32 public key bytes. + */ +ed25519.publicKeyFromAsn1 = function(obj) { + // get SubjectPublicKeyInfo + var capture = {}; + var errors = []; + var valid = forge.asn1.validate(obj, publicKeyValidator, capture, errors); + if(!valid) { + var error = new Error('Invalid Key.'); + error.errors = errors; + throw error; + } + var oid = forge.asn1.derToOid(capture.publicKeyOid); + var ed25519Oid = forge.oids.EdDSA25519; + if(oid !== ed25519Oid) { + throw new Error('Invalid OID "' + oid + '"; OID must be "' + + ed25519Oid + '".'); + } + var publicKeyBytes = capture.ed25519PublicKey; + if(publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { + throw new Error('Key length is invalid.'); + } + return messageToNativeBuffer({ + message: publicKeyBytes, + encoding: 'binary' + }); +}; + +ed25519.publicKeyFromPrivateKey = function(options) { + options = options || {}; + var privateKey = messageToNativeBuffer({ + message: options.privateKey, encoding: 'binary' + }); + if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { + throw new TypeError( + '"options.privateKey" must have a byte length of ' + + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); + } + + var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); + for(var i = 0; i < pk.length; ++i) { + pk[i] = privateKey[32 + i]; + } + return pk; +}; + +ed25519.sign = function(options) { + options = options || {}; + var msg = messageToNativeBuffer(options); + var privateKey = messageToNativeBuffer({ + message: options.privateKey, + encoding: 'binary' + }); + if(privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) { + var keyPair = ed25519.generateKeyPair({seed: privateKey}); + privateKey = keyPair.privateKey; + } else if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { + throw new TypeError( + '"options.privateKey" must have a byte length of ' + + ed25519.constants.SEED_BYTE_LENGTH + ' or ' + + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); + } + + var signedMsg = new NativeBuffer( + ed25519.constants.SIGN_BYTE_LENGTH + msg.length); + crypto_sign(signedMsg, msg, msg.length, privateKey); + + var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH); + for(var i = 0; i < sig.length; ++i) { + sig[i] = signedMsg[i]; + } + return sig; +}; + +ed25519.verify = function(options) { + options = options || {}; + var msg = messageToNativeBuffer(options); + if(options.signature === undefined) { + throw new TypeError( + '"options.signature" must be a node.js Buffer, a Uint8Array, a forge ' + + 'ByteBuffer, or a binary string.'); + } + var sig = messageToNativeBuffer({ + message: options.signature, + encoding: 'binary' + }); + if(sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) { + throw new TypeError( + '"options.signature" must have a byte length of ' + + ed25519.constants.SIGN_BYTE_LENGTH); + } + var publicKey = messageToNativeBuffer({ + message: options.publicKey, + encoding: 'binary' + }); + if(publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { + throw new TypeError( + '"options.publicKey" must have a byte length of ' + + ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); + } + + var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); + var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); + var i; + for(i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) { + sm[i] = sig[i]; + } + for(i = 0; i < msg.length; ++i) { + sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i]; + } + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +}; + +function messageToNativeBuffer(options) { + var message = options.message; + if(message instanceof Uint8Array || message instanceof NativeBuffer) { + return message; + } + + var encoding = options.encoding; + if(message === undefined) { + if(options.md) { + // TODO: more rigorous validation that `md` is a MessageDigest + message = options.md.digest().getBytes(); + encoding = 'binary'; + } else { + throw new TypeError('"options.message" or "options.md" not specified.'); + } + } + + if(typeof message === 'string' && !encoding) { + throw new TypeError('"options.encoding" must be "binary" or "utf8".'); + } + + if(typeof message === 'string') { + if(typeof Buffer !== 'undefined') { + return Buffer.from(message, encoding); + } + message = new ByteBuffer(message, encoding); + } else if(!(message instanceof ByteBuffer)) { + throw new TypeError( + '"options.message" must be a node.js Buffer, a Uint8Array, a forge ' + + 'ByteBuffer, or a string with "options.encoding" specifying its ' + + 'encoding.'); + } + + // convert to native buffer + var buffer = new NativeBuffer(message.length()); + for(var i = 0; i < buffer.length; ++i) { + buffer[i] = message.at(i); + } + return buffer; +} + +var gf0 = gf(); +var gf1 = gf([1]); +var D = gf([ + 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, + 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]); +var D2 = gf([ + 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, + 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]); +var X = gf([ + 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, + 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]); +var Y = gf([ + 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, + 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]); +var L = new Float64Array([ + 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, + 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); +var I = gf([ + 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, + 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); + +// TODO: update forge buffer implementation to use `Buffer` or `Uint8Array`, +// whichever is available, to improve performance +function sha512(msg, msgLen) { + // Note: `out` and `msg` are NativeBuffer + var md = forge.md.sha512.create(); + var buffer = new ByteBuffer(msg); + md.update(buffer.getBytes(msgLen), 'binary'); + var hash = md.digest().getBytes(); + if(typeof Buffer !== 'undefined') { + return Buffer.from(hash, 'binary'); + } + var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH); + for(var i = 0; i < 64; ++i) { + out[i] = hash.charCodeAt(i); + } + return out; +} + +function crypto_sign_keypair(pk, sk) { + var p = [gf(), gf(), gf(), gf()]; + var i; + + var d = sha512(sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + scalarbase(p, d); + pack(pk, p); + + for(i = 0; i < 32; ++i) { + sk[i + 32] = pk[i]; + } + return 0; +} + +// Note: difference from C - smlen returned, not passed as argument. +function crypto_sign(sm, m, n, sk) { + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; + + var d = sha512(sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + var smlen = n + 64; + for(i = 0; i < n; ++i) { + sm[64 + i] = m[i]; + } + for(i = 0; i < 32; ++i) { + sm[32 + i] = d[32 + i]; + } + + var r = sha512(sm.subarray(32), n + 32); + reduce(r); + scalarbase(p, r); + pack(sm, p); + + for(i = 32; i < 64; ++i) { + sm[i] = sk[i]; + } + var h = sha512(sm, n + 64); + reduce(h); + + for(i = 32; i < 64; ++i) { + x[i] = 0; + } + for(i = 0; i < 32; ++i) { + x[i] = r[i]; + } + for(i = 0; i < 32; ++i) { + for(j = 0; j < 32; j++) { + x[i + j] += h[i] * d[j]; + } + } + + modL(sm.subarray(32), x); + return smlen; +} + +function crypto_sign_open(m, sm, n, pk) { + var i, mlen; + var t = new NativeBuffer(32); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; + + mlen = -1; + if(n < 64) { + return -1; + } + + if(unpackneg(q, pk)) { + return -1; + } + + for(i = 0; i < n; ++i) { + m[i] = sm[i]; + } + for(i = 0; i < 32; ++i) { + m[i + 32] = pk[i]; + } + var h = sha512(m, n); + reduce(h); + scalarmult(p, q, h); + + scalarbase(q, sm.subarray(32)); + add(p, q); + pack(t, p); + + n -= 64; + if(crypto_verify_32(sm, 0, t, 0)) { + for(i = 0; i < n; ++i) { + m[i] = 0; + } + return -1; + } + + for(i = 0; i < n; ++i) { + m[i] = sm[i + 64]; + } + mlen = n; + return mlen; +} + +function modL(r, x) { + var carry, i, j, k; + for(i = 63; i >= 32; --i) { + carry = 0; + for(j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = (x[j] + 128) >> 8; + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for(j = 0; j < 32; ++j) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for(j = 0; j < 32; ++j) { + x[j] -= carry * L[j]; + } + for(i = 0; i < 32; ++i) { + x[i + 1] += x[i] >> 8; + r[i] = x[i] & 255; + } +} + +function reduce(r) { + var x = new Float64Array(64); + for(var i = 0; i < 64; ++i) { + x[i] = r[i]; + r[i] = 0; + } + modL(r, x); +} + +function add(p, q) { + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); + + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); + + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); +} + +function cswap(p, q, b) { + for(var i = 0; i < 4; ++i) { + sel25519(p[i], q[i], b); + } +} + +function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; +} + +function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for(i = 0; i < 16; ++i) { + t[i] = n[i]; + } + car25519(t); + car25519(t); + car25519(t); + for(j = 0; j < 2; ++j) { + m[0] = t[0] - 0xffed; + for(i = 1; i < 15; ++i) { + m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1); + m[i-1] &= 0xffff; + } + m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1); + b = (m[15] >> 16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1 - b); + } + for (i = 0; i < 16; i++) { + o[2 * i] = t[i] & 0xff; + o[2 * i + 1] = t[i] >> 8; + } +} + +function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); + + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + + S(chk, r[0]); + M(chk, chk, den); + if(neq25519(chk, num)) { + M(r[0], r[0], I); + } + + S(chk, r[0]); + M(chk, chk, den); + if(neq25519(chk, num)) { + return -1; + } + + if(par25519(r[0]) === (p[31] >> 7)) { + Z(r[0], gf0, r[0]); + } + + M(r[3], r[0], r[1]); + return 0; +} + +function unpack25519(o, n) { + var i; + for(i = 0; i < 16; ++i) { + o[i] = n[2 * i] + (n[2 * i + 1] << 8); + } + o[15] &= 0x7fff; +} + +function pow2523(o, i) { + var c = gf(); + var a; + for(a = 0; a < 16; ++a) { + c[a] = i[a]; + } + for(a = 250; a >= 0; --a) { + S(c, c); + if(a !== 1) { + M(c, c, i); + } + } + for(a = 0; a < 16; ++a) { + o[a] = c[a]; + } +} + +function neq25519(a, b) { + var c = new NativeBuffer(32); + var d = new NativeBuffer(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); +} + +function crypto_verify_32(x, xi, y, yi) { + return vn(x, xi, y, yi, 32); +} + +function vn(x, xi, y, yi, n) { + var i, d = 0; + for(i = 0; i < n; ++i) { + d |= x[xi + i] ^ y[yi + i]; + } + return (1 & ((d - 1) >>> 8)) - 1; +} + +function par25519(a) { + var d = new NativeBuffer(32); + pack25519(d, a); + return d[0] & 1; +} + +function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for(i = 255; i >= 0; --i) { + b = (s[(i / 8)|0] >> (i & 7)) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); + } +} + +function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); +} + +function set25519(r, a) { + var i; + for(i = 0; i < 16; i++) { + r[i] = a[i] | 0; + } +} + +function inv25519(o, i) { + var c = gf(); + var a; + for(a = 0; a < 16; ++a) { + c[a] = i[a]; + } + for(a = 253; a >= 0; --a) { + S(c, c); + if(a !== 2 && a !== 4) { + M(c, c, i); + } + } + for(a = 0; a < 16; ++a) { + o[a] = c[a]; + } +} + +function car25519(o) { + var i, v, c = 1; + for(i = 0; i < 16; ++i) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c - 1 + 37 * (c - 1); +} + +function sel25519(p, q, b) { + var t, c = ~(b - 1); + for(var i = 0; i < 16; ++i) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } +} + +function gf(init) { + var i, r = new Float64Array(16); + if(init) { + for(i = 0; i < init.length; ++i) { + r[i] = init[i]; + } + } + return r; +} + +function A(o, a, b) { + for(var i = 0; i < 16; ++i) { + o[i] = a[i] + b[i]; + } +} + +function Z(o, a, b) { + for(var i = 0; i < 16; ++i) { + o[i] = a[i] - b[i]; + } +} + +function S(o, a) { + M(o, a, a); +} + +function M(o, a, b) { + var v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; + + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; + + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is + + // first car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + // second car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + o[ 0] = t0; + o[ 1] = t1; + o[ 2] = t2; + o[ 3] = t3; + o[ 4] = t4; + o[ 5] = t5; + o[ 6] = t6; + o[ 7] = t7; + o[ 8] = t8; + o[ 9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; +} diff --git a/node_modules/node-forge/lib/forge.js b/node_modules/node-forge/lib/forge.js new file mode 100644 index 0000000..2e243a9 --- /dev/null +++ b/node_modules/node-forge/lib/forge.js @@ -0,0 +1,13 @@ +/** + * Node.js module for Forge. + * + * @author Dave Longley + * + * Copyright 2011-2016 Digital Bazaar, Inc. + */ +module.exports = { + // default options + options: { + usePureJavaScript: false + } +}; diff --git a/node_modules/node-forge/lib/form.js b/node_modules/node-forge/lib/form.js new file mode 100644 index 0000000..4d7843a --- /dev/null +++ b/node_modules/node-forge/lib/form.js @@ -0,0 +1,149 @@ +/** + * Functions for manipulating web forms. + * + * @author David I. Lehn + * @author Dave Longley + * @author Mike Johnson + * + * Copyright (c) 2011-2014 Digital Bazaar, Inc. All rights reserved. + */ +var forge = require('./forge'); + +/* Form API */ +var form = module.exports = forge.form = forge.form || {}; + +(function($) { + +/** + * Regex for parsing a single name property (handles array brackets). + */ +var _regex = /([^\[]*?)\[(.*?)\]/g; + +/** + * Parses a single name property into an array with the name and any + * array indices. + * + * @param name the name to parse. + * + * @return the array of the name and its array indices in order. + */ +var _parseName = function(name) { + var rval = []; + + var matches; + while(!!(matches = _regex.exec(name))) { + if(matches[1].length > 0) { + rval.push(matches[1]); + } + if(matches.length >= 2) { + rval.push(matches[2]); + } + } + if(rval.length === 0) { + rval.push(name); + } + + return rval; +}; + +/** + * Adds a field from the given form to the given object. + * + * @param obj the object. + * @param names the field as an array of object property names. + * @param value the value of the field. + * @param dict a dictionary of names to replace. + */ +var _addField = function(obj, names, value, dict) { + // combine array names that fall within square brackets + var tmp = []; + for(var i = 0; i < names.length; ++i) { + // check name for starting square bracket but no ending one + var name = names[i]; + if(name.indexOf('[') !== -1 && name.indexOf(']') === -1 && + i < names.length - 1) { + do { + name += '.' + names[++i]; + } while(i < names.length - 1 && names[i].indexOf(']') === -1); + } + tmp.push(name); + } + names = tmp; + + // split out array indexes + var tmp = []; + $.each(names, function(n, name) { + tmp = tmp.concat(_parseName(name)); + }); + names = tmp; + + // iterate over object property names until value is set + $.each(names, function(n, name) { + // do dictionary name replacement + if(dict && name.length !== 0 && name in dict) { + name = dict[name]; + } + + // blank name indicates appending to an array, set name to + // new last index of array + if(name.length === 0) { + name = obj.length; + } + + // value already exists, append value + if(obj[name]) { + // last name in the field + if(n == names.length - 1) { + // more than one value, so convert into an array + if(!$.isArray(obj[name])) { + obj[name] = [obj[name]]; + } + obj[name].push(value); + } else { + // not last name, go deeper into object + obj = obj[name]; + } + } else if(n == names.length - 1) { + // new value, last name in the field, set value + obj[name] = value; + } else { + // new value, not last name, go deeper + // get next name + var next = names[n + 1]; + + // blank next value indicates array-appending, so create array + if(next.length === 0) { + obj[name] = []; + } else { + // if next name is a number create an array, otherwise a map + var isNum = ((next - 0) == next && next.length > 0); + obj[name] = isNum ? [] : {}; + } + obj = obj[name]; + } + }); +}; + +/** + * Serializes a form to a JSON object. Object properties will be separated + * using the given separator (defaults to '.') and by square brackets. + * + * @param input the jquery form to serialize. + * @param sep the object-property separator (defaults to '.'). + * @param dict a dictionary of names to replace (name=replace). + * + * @return the JSON-serialized form. + */ +form.serialize = function(input, sep, dict) { + var rval = {}; + + // add all fields in the form to the object + sep = sep || '.'; + $.each(input.serializeArray(), function() { + _addField(rval, this.name.split(sep), this.value || '', dict); + }); + + return rval; +}; + +})(jQuery); diff --git a/node_modules/node-forge/lib/hmac.js b/node_modules/node-forge/lib/hmac.js new file mode 100644 index 0000000..b155f24 --- /dev/null +++ b/node_modules/node-forge/lib/hmac.js @@ -0,0 +1,146 @@ +/** + * Hash-based Message Authentication Code implementation. Requires a message + * digest object that can be obtained, for example, from forge.md.sha1 or + * forge.md.md5. + * + * @author Dave Longley + * + * Copyright (c) 2010-2012 Digital Bazaar, Inc. All rights reserved. + */ +var forge = require('./forge'); +require('./md'); +require('./util'); + +/* HMAC API */ +var hmac = module.exports = forge.hmac = forge.hmac || {}; + +/** + * Creates an HMAC object that uses the given message digest object. + * + * @return an HMAC object. + */ +hmac.create = function() { + // the hmac key to use + var _key = null; + + // the message digest to use + var _md = null; + + // the inner padding + var _ipadding = null; + + // the outer padding + var _opadding = null; + + // hmac context + var ctx = {}; + + /** + * Starts or restarts the HMAC with the given key and message digest. + * + * @param md the message digest to use, null to reuse the previous one, + * a string to use builtin 'sha1', 'md5', 'sha256'. + * @param key the key to use as a string, array of bytes, byte buffer, + * or null to reuse the previous key. + */ + ctx.start = function(md, key) { + if(md !== null) { + if(typeof md === 'string') { + // create builtin message digest + md = md.toLowerCase(); + if(md in forge.md.algorithms) { + _md = forge.md.algorithms[md].create(); + } else { + throw new Error('Unknown hash algorithm "' + md + '"'); + } + } else { + // store message digest + _md = md; + } + } + + if(key === null) { + // reuse previous key + key = _key; + } else { + if(typeof key === 'string') { + // convert string into byte buffer + key = forge.util.createBuffer(key); + } else if(forge.util.isArray(key)) { + // convert byte array into byte buffer + var tmp = key; + key = forge.util.createBuffer(); + for(var i = 0; i < tmp.length; ++i) { + key.putByte(tmp[i]); + } + } + + // if key is longer than blocksize, hash it + var keylen = key.length(); + if(keylen > _md.blockLength) { + _md.start(); + _md.update(key.bytes()); + key = _md.digest(); + } + + // mix key into inner and outer padding + // ipadding = [0x36 * blocksize] ^ key + // opadding = [0x5C * blocksize] ^ key + _ipadding = forge.util.createBuffer(); + _opadding = forge.util.createBuffer(); + keylen = key.length(); + for(var i = 0; i < keylen; ++i) { + var tmp = key.at(i); + _ipadding.putByte(0x36 ^ tmp); + _opadding.putByte(0x5C ^ tmp); + } + + // if key is shorter than blocksize, add additional padding + if(keylen < _md.blockLength) { + var tmp = _md.blockLength - keylen; + for(var i = 0; i < tmp; ++i) { + _ipadding.putByte(0x36); + _opadding.putByte(0x5C); + } + } + _key = key; + _ipadding = _ipadding.bytes(); + _opadding = _opadding.bytes(); + } + + // digest is done like so: hash(opadding | hash(ipadding | message)) + + // prepare to do inner hash + // hash(ipadding | message) + _md.start(); + _md.update(_ipadding); + }; + + /** + * Updates the HMAC with the given message bytes. + * + * @param bytes the bytes to update with. + */ + ctx.update = function(bytes) { + _md.update(bytes); + }; + + /** + * Produces the Message Authentication Code (MAC). + * + * @return a byte buffer containing the digest value. + */ + ctx.getMac = function() { + // digest is done like so: hash(opadding | hash(ipadding | message)) + // here we do the outer hashing + var inner = _md.digest().bytes(); + _md.start(); + _md.update(_opadding); + _md.update(inner); + return _md.digest(); + }; + // alias for getMac + ctx.digest = ctx.getMac; + + return ctx; +}; diff --git a/node_modules/node-forge/lib/http.js b/node_modules/node-forge/lib/http.js new file mode 100644 index 0000000..fe52986 --- /dev/null +++ b/node_modules/node-forge/lib/http.js @@ -0,0 +1,1346 @@ +/** + * HTTP client-side implementation that uses forge.net sockets. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. All rights reserved. + */ +var forge = require('./forge'); +require('./tls'); +require('./util'); + +// define http namespace +var http = module.exports = forge.http = forge.http || {}; + +// logging category +var cat = 'forge.http'; + +// normalizes an http header field name +var _normalize = function(name) { + return name.toLowerCase().replace(/(^.)|(-.)/g, + function(a) {return a.toUpperCase();}); +}; + +/** + * Gets the local storage ID for the given client. + * + * @param client the client to get the local storage ID for. + * + * @return the local storage ID to use. + */ +var _getStorageId = function(client) { + // TODO: include browser in ID to avoid sharing cookies between + // browsers (if this is undesirable) + // navigator.userAgent + return 'forge.http.' + + client.url.protocol.slice(0, -1) + '.' + + client.url.hostname + '.' + + client.url.port; +}; + +/** + * Loads persistent cookies from disk for the given client. + * + * @param client the client. + */ +var _loadCookies = function(client) { + if(client.persistCookies) { + try { + var cookies = forge.util.getItem( + client.socketPool.flashApi, + _getStorageId(client), 'cookies'); + client.cookies = cookies || {}; + } catch(ex) { + // no flash storage available, just silently fail + // TODO: i assume we want this logged somewhere or + // should it actually generate an error + //forge.log.error(cat, ex); + } + } +}; + +/** + * Saves persistent cookies on disk for the given client. + * + * @param client the client. + */ +var _saveCookies = function(client) { + if(client.persistCookies) { + try { + forge.util.setItem( + client.socketPool.flashApi, + _getStorageId(client), 'cookies', client.cookies); + } catch(ex) { + // no flash storage available, just silently fail + // TODO: i assume we want this logged somewhere or + // should it actually generate an error + //forge.log.error(cat, ex); + } + } + + // FIXME: remove me + _loadCookies(client); +}; + +/** + * Clears persistent cookies on disk for the given client. + * + * @param client the client. + */ +var _clearCookies = function(client) { + if(client.persistCookies) { + try { + // only thing stored is 'cookies', so clear whole storage + forge.util.clearItems( + client.socketPool.flashApi, + _getStorageId(client)); + } catch(ex) { + // no flash storage available, just silently fail + // TODO: i assume we want this logged somewhere or + // should it actually generate an error + //forge.log.error(cat, ex); + } + } +}; + +/** + * Connects and sends a request. + * + * @param client the http client. + * @param socket the socket to use. + */ +var _doRequest = function(client, socket) { + if(socket.isConnected()) { + // already connected + socket.options.request.connectTime = +new Date(); + socket.connected({ + type: 'connect', + id: socket.id + }); + } else { + // connect + socket.options.request.connectTime = +new Date(); + socket.connect({ + host: client.url.hostname, + port: client.url.port, + policyPort: client.policyPort, + policyUrl: client.policyUrl + }); + } +}; + +/** + * Handles the next request or marks a socket as idle. + * + * @param client the http client. + * @param socket the socket. + */ +var _handleNextRequest = function(client, socket) { + // clear buffer + socket.buffer.clear(); + + // get pending request + var pending = null; + while(pending === null && client.requests.length > 0) { + pending = client.requests.shift(); + if(pending.request.aborted) { + pending = null; + } + } + + // mark socket idle if no pending requests + if(pending === null) { + if(socket.options !== null) { + socket.options = null; + } + client.idle.push(socket); + } else { + // handle pending request, allow 1 retry + socket.retries = 1; + socket.options = pending; + _doRequest(client, socket); + } +}; + +/** + * Sets up a socket for use with an http client. + * + * @param client the parent http client. + * @param socket the socket to set up. + * @param tlsOptions if the socket must use TLS, the TLS options. + */ +var _initSocket = function(client, socket, tlsOptions) { + // no socket options yet + socket.options = null; + + // set up handlers + socket.connected = function(e) { + // socket primed by caching TLS session, handle next request + if(socket.options === null) { + _handleNextRequest(client, socket); + } else { + // socket in use + var request = socket.options.request; + request.connectTime = +new Date() - request.connectTime; + e.socket = socket; + socket.options.connected(e); + if(request.aborted) { + socket.close(); + } else { + var out = request.toString(); + if(request.body) { + out += request.body; + } + request.time = +new Date(); + socket.send(out); + request.time = +new Date() - request.time; + socket.options.response.time = +new Date(); + socket.sending = true; + } + } + }; + socket.closed = function(e) { + if(socket.sending) { + socket.sending = false; + if(socket.retries > 0) { + --socket.retries; + _doRequest(client, socket); + } else { + // error, closed during send + socket.error({ + id: socket.id, + type: 'ioError', + message: 'Connection closed during send. Broken pipe.', + bytesAvailable: 0 + }); + } + } else { + // handle unspecified content-length transfer + var response = socket.options.response; + if(response.readBodyUntilClose) { + response.time = +new Date() - response.time; + response.bodyReceived = true; + socket.options.bodyReady({ + request: socket.options.request, + response: response, + socket: socket + }); + } + socket.options.closed(e); + _handleNextRequest(client, socket); + } + }; + socket.data = function(e) { + socket.sending = false; + var request = socket.options.request; + if(request.aborted) { + socket.close(); + } else { + // receive all bytes available + var response = socket.options.response; + var bytes = socket.receive(e.bytesAvailable); + if(bytes !== null) { + // receive header and then body + socket.buffer.putBytes(bytes); + if(!response.headerReceived) { + response.readHeader(socket.buffer); + if(response.headerReceived) { + socket.options.headerReady({ + request: socket.options.request, + response: response, + socket: socket + }); + } + } + if(response.headerReceived && !response.bodyReceived) { + response.readBody(socket.buffer); + } + if(response.bodyReceived) { + socket.options.bodyReady({ + request: socket.options.request, + response: response, + socket: socket + }); + // close connection if requested or by default on http/1.0 + var value = response.getField('Connection') || ''; + if(value.indexOf('close') != -1 || + (response.version === 'HTTP/1.0' && + response.getField('Keep-Alive') === null)) { + socket.close(); + } else { + _handleNextRequest(client, socket); + } + } + } + } + }; + socket.error = function(e) { + // do error callback, include request + socket.options.error({ + type: e.type, + message: e.message, + request: socket.options.request, + response: socket.options.response, + socket: socket + }); + socket.close(); + }; + + // wrap socket for TLS + if(tlsOptions) { + socket = forge.tls.wrapSocket({ + sessionId: null, + sessionCache: {}, + caStore: tlsOptions.caStore, + cipherSuites: tlsOptions.cipherSuites, + socket: socket, + virtualHost: tlsOptions.virtualHost, + verify: tlsOptions.verify, + getCertificate: tlsOptions.getCertificate, + getPrivateKey: tlsOptions.getPrivateKey, + getSignature: tlsOptions.getSignature, + deflate: tlsOptions.deflate || null, + inflate: tlsOptions.inflate || null + }); + + socket.options = null; + socket.buffer = forge.util.createBuffer(); + client.sockets.push(socket); + if(tlsOptions.prime) { + // prime socket by connecting and caching TLS session, will do + // next request from there + socket.connect({ + host: client.url.hostname, + port: client.url.port, + policyPort: client.policyPort, + policyUrl: client.policyUrl + }); + } else { + // do not prime socket, just add as idle + client.idle.push(socket); + } + } else { + // no need to prime non-TLS sockets + socket.buffer = forge.util.createBuffer(); + client.sockets.push(socket); + client.idle.push(socket); + } +}; + +/** + * Checks to see if the given cookie has expired. If the cookie's max-age + * plus its created time is less than the time now, it has expired, unless + * its max-age is set to -1 which indicates it will never expire. + * + * @param cookie the cookie to check. + * + * @return true if it has expired, false if not. + */ +var _hasCookieExpired = function(cookie) { + var rval = false; + + if(cookie.maxAge !== -1) { + var now = _getUtcTime(new Date()); + var expires = cookie.created + cookie.maxAge; + if(expires <= now) { + rval = true; + } + } + + return rval; +}; + +/** + * Adds cookies in the given client to the given request. + * + * @param client the client. + * @param request the request. + */ +var _writeCookies = function(client, request) { + var expired = []; + var url = client.url; + var cookies = client.cookies; + for(var name in cookies) { + // get cookie paths + var paths = cookies[name]; + for(var p in paths) { + var cookie = paths[p]; + if(_hasCookieExpired(cookie)) { + // store for clean up + expired.push(cookie); + } else if(request.path.indexOf(cookie.path) === 0) { + // path or path's ancestor must match cookie.path + request.addCookie(cookie); + } + } + } + + // clean up expired cookies + for(var i = 0; i < expired.length; ++i) { + var cookie = expired[i]; + client.removeCookie(cookie.name, cookie.path); + } +}; + +/** + * Gets cookies from the given response and adds the to the given client. + * + * @param client the client. + * @param response the response. + */ +var _readCookies = function(client, response) { + var cookies = response.getCookies(); + for(var i = 0; i < cookies.length; ++i) { + try { + client.setCookie(cookies[i]); + } catch(ex) { + // ignore failure to add other-domain, etc. cookies + } + } +}; + +/** + * Creates an http client that uses forge.net sockets as a backend and + * forge.tls for security. + * + * @param options: + * url: the url to connect to (scheme://host:port). + * socketPool: the flash socket pool to use. + * policyPort: the flash policy port to use (if other than the + * socket pool default), use 0 for flash default. + * policyUrl: the flash policy file URL to use (if provided will + * be used instead of a policy port). + * connections: number of connections to use to handle requests. + * caCerts: an array of certificates to trust for TLS, certs may + * be PEM-formatted or cert objects produced via forge.pki. + * cipherSuites: an optional array of cipher suites to use, + * see forge.tls.CipherSuites. + * virtualHost: the virtual server name to use in a TLS SNI + * extension, if not provided the url host will be used. + * verify: a custom TLS certificate verify callback to use. + * getCertificate: an optional callback used to get a client-side + * certificate (see forge.tls for details). + * getPrivateKey: an optional callback used to get a client-side + * private key (see forge.tls for details). + * getSignature: an optional callback used to get a client-side + * signature (see forge.tls for details). + * persistCookies: true to use persistent cookies via flash local + * storage, false to only keep cookies in javascript. + * primeTlsSockets: true to immediately connect TLS sockets on + * their creation so that they will cache TLS sessions for reuse. + * + * @return the client. + */ +http.createClient = function(options) { + // create CA store to share with all TLS connections + var caStore = null; + if(options.caCerts) { + caStore = forge.pki.createCaStore(options.caCerts); + } + + // get scheme, host, and port from url + options.url = (options.url || + window.location.protocol + '//' + window.location.host); + var url; + try { + url = new URL(options.url); + } catch(e) { + var error = new Error('Invalid url.'); + error.details = {url: options.url}; + throw error; + } + + // default to 1 connection + options.connections = options.connections || 1; + + // create client + var sp = options.socketPool; + var client = { + // url + url: url, + // socket pool + socketPool: sp, + // the policy port to use + policyPort: options.policyPort, + // policy url to use + policyUrl: options.policyUrl, + // queue of requests to service + requests: [], + // all sockets + sockets: [], + // idle sockets + idle: [], + // whether or not the connections are secure + secure: (url.protocol === 'https:'), + // cookie jar (key'd off of name and then path, there is only 1 domain + // and one setting for secure per client so name+path is unique) + cookies: {}, + // default to flash storage of cookies + persistCookies: (typeof(options.persistCookies) === 'undefined') ? + true : options.persistCookies + }; + + // load cookies from disk + _loadCookies(client); + + /** + * A default certificate verify function that checks a certificate common + * name against the client's URL host. + * + * @param c the TLS connection. + * @param verified true if cert is verified, otherwise alert number. + * @param depth the chain depth. + * @param certs the cert chain. + * + * @return true if verified and the common name matches the host, error + * otherwise. + */ + var _defaultCertificateVerify = function(c, verified, depth, certs) { + if(depth === 0 && verified === true) { + // compare common name to url host + var cn = certs[depth].subject.getField('CN'); + if(cn === null || client.url.hostname !== cn.value) { + verified = { + message: 'Certificate common name does not match url host.' + }; + } + } + return verified; + }; + + // determine if TLS is used + var tlsOptions = null; + if(client.secure) { + tlsOptions = { + caStore: caStore, + cipherSuites: options.cipherSuites || null, + virtualHost: options.virtualHost || url.hostname, + verify: options.verify || _defaultCertificateVerify, + getCertificate: options.getCertificate || null, + getPrivateKey: options.getPrivateKey || null, + getSignature: options.getSignature || null, + prime: options.primeTlsSockets || false + }; + + // if socket pool uses a flash api, then add deflate support to TLS + if(sp.flashApi !== null) { + tlsOptions.deflate = function(bytes) { + // strip 2 byte zlib header and 4 byte trailer + return forge.util.deflate(sp.flashApi, bytes, true); + }; + tlsOptions.inflate = function(bytes) { + return forge.util.inflate(sp.flashApi, bytes, true); + }; + } + } + + // create and initialize sockets + for(var i = 0; i < options.connections; ++i) { + _initSocket(client, sp.createSocket(), tlsOptions); + } + + /** + * Sends a request. A method 'abort' will be set on the request that + * can be called to attempt to abort the request. + * + * @param options: + * request: the request to send. + * connected: a callback for when the connection is open. + * closed: a callback for when the connection is closed. + * headerReady: a callback for when the response header arrives. + * bodyReady: a callback for when the response body arrives. + * error: a callback for if an error occurs. + */ + client.send = function(options) { + // add host header if not set + if(options.request.getField('Host') === null) { + options.request.setField('Host', client.url.origin); + } + + // set default dummy handlers + var opts = {}; + opts.request = options.request; + opts.connected = options.connected || function() {}; + opts.closed = options.close || function() {}; + opts.headerReady = function(e) { + // read cookies + _readCookies(client, e.response); + if(options.headerReady) { + options.headerReady(e); + } + }; + opts.bodyReady = options.bodyReady || function() {}; + opts.error = options.error || function() {}; + + // create response + opts.response = http.createResponse(); + opts.response.time = 0; + opts.response.flashApi = client.socketPool.flashApi; + opts.request.flashApi = client.socketPool.flashApi; + + // create abort function + opts.request.abort = function() { + // set aborted, clear handlers + opts.request.aborted = true; + opts.connected = function() {}; + opts.closed = function() {}; + opts.headerReady = function() {}; + opts.bodyReady = function() {}; + opts.error = function() {}; + }; + + // add cookies to request + _writeCookies(client, opts.request); + + // queue request options if there are no idle sockets + if(client.idle.length === 0) { + client.requests.push(opts); + } else { + // use an idle socket, prefer an idle *connected* socket first + var socket = null; + var len = client.idle.length; + for(var i = 0; socket === null && i < len; ++i) { + socket = client.idle[i]; + if(socket.isConnected()) { + client.idle.splice(i, 1); + } else { + socket = null; + } + } + // no connected socket available, get unconnected socket + if(socket === null) { + socket = client.idle.pop(); + } + socket.options = opts; + _doRequest(client, socket); + } + }; + + /** + * Destroys this client. + */ + client.destroy = function() { + // clear pending requests, close and destroy sockets + client.requests = []; + for(var i = 0; i < client.sockets.length; ++i) { + client.sockets[i].close(); + client.sockets[i].destroy(); + } + client.socketPool = null; + client.sockets = []; + client.idle = []; + }; + + /** + * Sets a cookie for use with all connections made by this client. Any + * cookie with the same name will be replaced. If the cookie's value + * is undefined, null, or the blank string, the cookie will be removed. + * + * If the cookie's domain doesn't match this client's url host or the + * cookie's secure flag doesn't match this client's url scheme, then + * setting the cookie will fail with an exception. + * + * @param cookie the cookie with parameters: + * name: the name of the cookie. + * value: the value of the cookie. + * comment: an optional comment string. + * maxAge: the age of the cookie in seconds relative to created time. + * secure: true if the cookie must be sent over a secure protocol. + * httpOnly: true to restrict access to the cookie from javascript + * (inaffective since the cookies are stored in javascript). + * path: the path for the cookie. + * domain: optional domain the cookie belongs to (must start with dot). + * version: optional version of the cookie. + * created: creation time, in UTC seconds, of the cookie. + */ + client.setCookie = function(cookie) { + var rval; + if(typeof(cookie.name) !== 'undefined') { + if(cookie.value === null || typeof(cookie.value) === 'undefined' || + cookie.value === '') { + // remove cookie + rval = client.removeCookie(cookie.name, cookie.path); + } else { + // set cookie defaults + cookie.comment = cookie.comment || ''; + cookie.maxAge = cookie.maxAge || 0; + cookie.secure = (typeof(cookie.secure) === 'undefined') ? + true : cookie.secure; + cookie.httpOnly = cookie.httpOnly || true; + cookie.path = cookie.path || '/'; + cookie.domain = cookie.domain || null; + cookie.version = cookie.version || null; + cookie.created = _getUtcTime(new Date()); + + // do secure check + if(cookie.secure !== client.secure) { + var error = new Error('Http client url scheme is incompatible ' + + 'with cookie secure flag.'); + error.url = client.url; + error.cookie = cookie; + throw error; + } + // make sure url host is within cookie.domain + if(!http.withinCookieDomain(client.url, cookie)) { + var error = new Error('Http client url scheme is incompatible ' + + 'with cookie secure flag.'); + error.url = client.url; + error.cookie = cookie; + throw error; + } + + // add new cookie + if(!(cookie.name in client.cookies)) { + client.cookies[cookie.name] = {}; + } + client.cookies[cookie.name][cookie.path] = cookie; + rval = true; + + // save cookies + _saveCookies(client); + } + } + + return rval; + }; + + /** + * Gets a cookie by its name. + * + * @param name the name of the cookie to retrieve. + * @param path an optional path for the cookie (if there are multiple + * cookies with the same name but different paths). + * + * @return the cookie or null if not found. + */ + client.getCookie = function(name, path) { + var rval = null; + if(name in client.cookies) { + var paths = client.cookies[name]; + + // get path-specific cookie + if(path) { + if(path in paths) { + rval = paths[path]; + } + } else { + // get first cookie + for(var p in paths) { + rval = paths[p]; + break; + } + } + } + return rval; + }; + + /** + * Removes a cookie. + * + * @param name the name of the cookie to remove. + * @param path an optional path for the cookie (if there are multiple + * cookies with the same name but different paths). + * + * @return true if a cookie was removed, false if not. + */ + client.removeCookie = function(name, path) { + var rval = false; + if(name in client.cookies) { + // delete the specific path + if(path) { + var paths = client.cookies[name]; + if(path in paths) { + rval = true; + delete client.cookies[name][path]; + // clean up entry if empty + var empty = true; + for(var i in client.cookies[name]) { + empty = false; + break; + } + if(empty) { + delete client.cookies[name]; + } + } + } else { + // delete all cookies with the given name + rval = true; + delete client.cookies[name]; + } + } + if(rval) { + // save cookies + _saveCookies(client); + } + return rval; + }; + + /** + * Clears all cookies stored in this client. + */ + client.clearCookies = function() { + client.cookies = {}; + _clearCookies(client); + }; + + if(forge.log) { + forge.log.debug('forge.http', 'created client', options); + } + + return client; +}; + +/** + * Trims the whitespace off of the beginning and end of a string. + * + * @param str the string to trim. + * + * @return the trimmed string. + */ +var _trimString = function(str) { + return str.replace(/^\s*/, '').replace(/\s*$/, ''); +}; + +/** + * Creates an http header object. + * + * @return the http header object. + */ +var _createHeader = function() { + var header = { + fields: {}, + setField: function(name, value) { + // normalize field name, trim value + header.fields[_normalize(name)] = [_trimString('' + value)]; + }, + appendField: function(name, value) { + name = _normalize(name); + if(!(name in header.fields)) { + header.fields[name] = []; + } + header.fields[name].push(_trimString('' + value)); + }, + getField: function(name, index) { + var rval = null; + name = _normalize(name); + if(name in header.fields) { + index = index || 0; + rval = header.fields[name][index]; + } + return rval; + } + }; + return header; +}; + +/** + * Gets the time in utc seconds given a date. + * + * @param d the date to use. + * + * @return the time in utc seconds. + */ +var _getUtcTime = function(d) { + var utc = +d + d.getTimezoneOffset() * 60000; + return Math.floor(+new Date() / 1000); +}; + +/** + * Creates an http request. + * + * @param options: + * version: the version. + * method: the method. + * path: the path. + * body: the body. + * headers: custom header fields to add, + * eg: [{'Content-Length': 0}]. + * + * @return the http request. + */ +http.createRequest = function(options) { + options = options || {}; + var request = _createHeader(); + request.version = options.version || 'HTTP/1.1'; + request.method = options.method || null; + request.path = options.path || null; + request.body = options.body || null; + request.bodyDeflated = false; + request.flashApi = null; + + // add custom headers + var headers = options.headers || []; + if(!forge.util.isArray(headers)) { + headers = [headers]; + } + for(var i = 0; i < headers.length; ++i) { + for(var name in headers[i]) { + request.appendField(name, headers[i][name]); + } + } + + /** + * Adds a cookie to the request 'Cookie' header. + * + * @param cookie a cookie to add. + */ + request.addCookie = function(cookie) { + var value = ''; + var field = request.getField('Cookie'); + if(field !== null) { + // separate cookies by semi-colons + value = field + '; '; + } + + // get current time in utc seconds + var now = _getUtcTime(new Date()); + + // output cookie name and value + value += cookie.name + '=' + cookie.value; + request.setField('Cookie', value); + }; + + /** + * Converts an http request into a string that can be sent as an + * HTTP request. Does not include any data. + * + * @return the string representation of the request. + */ + request.toString = function() { + /* Sample request header: + GET /some/path/?query HTTP/1.1 + Host: www.someurl.com + Connection: close + Accept-Encoding: deflate + Accept: image/gif, text/html + User-Agent: Mozilla 4.0 + */ + + // set default headers + if(request.getField('User-Agent') === null) { + request.setField('User-Agent', 'forge.http 1.0'); + } + if(request.getField('Accept') === null) { + request.setField('Accept', '*/*'); + } + if(request.getField('Connection') === null) { + request.setField('Connection', 'keep-alive'); + request.setField('Keep-Alive', '115'); + } + + // add Accept-Encoding if not specified + if(request.flashApi !== null && + request.getField('Accept-Encoding') === null) { + request.setField('Accept-Encoding', 'deflate'); + } + + // if the body isn't null, deflate it if its larger than 100 bytes + if(request.flashApi !== null && request.body !== null && + request.getField('Content-Encoding') === null && + !request.bodyDeflated && request.body.length > 100) { + // use flash to compress data + request.body = forge.util.deflate(request.flashApi, request.body); + request.bodyDeflated = true; + request.setField('Content-Encoding', 'deflate'); + request.setField('Content-Length', request.body.length); + } else if(request.body !== null) { + // set content length for body + request.setField('Content-Length', request.body.length); + } + + // build start line + var rval = + request.method.toUpperCase() + ' ' + request.path + ' ' + + request.version + '\r\n'; + + // add each header + for(var name in request.fields) { + var fields = request.fields[name]; + for(var i = 0; i < fields.length; ++i) { + rval += name + ': ' + fields[i] + '\r\n'; + } + } + // final terminating CRLF + rval += '\r\n'; + + return rval; + }; + + return request; +}; + +/** + * Creates an empty http response header. + * + * @return the empty http response header. + */ +http.createResponse = function() { + // private vars + var _first = true; + var _chunkSize = 0; + var _chunksFinished = false; + + // create response + var response = _createHeader(); + response.version = null; + response.code = 0; + response.message = null; + response.body = null; + response.headerReceived = false; + response.bodyReceived = false; + response.flashApi = null; + + /** + * Reads a line that ends in CRLF from a byte buffer. + * + * @param b the byte buffer. + * + * @return the line or null if none was found. + */ + var _readCrlf = function(b) { + var line = null; + var i = b.data.indexOf('\r\n', b.read); + if(i != -1) { + // read line, skip CRLF + line = b.getBytes(i - b.read); + b.getBytes(2); + } + return line; + }; + + /** + * Parses a header field and appends it to the response. + * + * @param line the header field line. + */ + var _parseHeader = function(line) { + var tmp = line.indexOf(':'); + var name = line.substring(0, tmp++); + response.appendField( + name, (tmp < line.length) ? line.substring(tmp) : ''); + }; + + /** + * Reads an http response header from a buffer of bytes. + * + * @param b the byte buffer to parse the header from. + * + * @return true if the whole header was read, false if not. + */ + response.readHeader = function(b) { + // read header lines (each ends in CRLF) + var line = ''; + while(!response.headerReceived && line !== null) { + line = _readCrlf(b); + if(line !== null) { + // parse first line + if(_first) { + _first = false; + var tmp = line.split(' '); + if(tmp.length >= 3) { + response.version = tmp[0]; + response.code = parseInt(tmp[1], 10); + response.message = tmp.slice(2).join(' '); + } else { + // invalid header + var error = new Error('Invalid http response header.'); + error.details = {'line': line}; + throw error; + } + } else if(line.length === 0) { + // handle final line, end of header + response.headerReceived = true; + } else { + _parseHeader(line); + } + } + } + + return response.headerReceived; + }; + + /** + * Reads some chunked http response entity-body from the given buffer of + * bytes. + * + * @param b the byte buffer to read from. + * + * @return true if the whole body was read, false if not. + */ + var _readChunkedBody = function(b) { + /* Chunked transfer-encoding sends data in a series of chunks, + followed by a set of 0-N http trailers. + The format is as follows: + + chunk-size (in hex) CRLF + chunk data (with "chunk-size" many bytes) CRLF + ... (N many chunks) + chunk-size (of 0 indicating the last chunk) CRLF + N many http trailers followed by CRLF + blank line + CRLF (terminates the trailers) + + If there are no http trailers, then after the chunk-size of 0, + there is still a single CRLF (indicating the blank line + CRLF + that terminates the trailers). In other words, you always terminate + the trailers with blank line + CRLF, regardless of 0-N trailers. */ + + /* From RFC-2616, section 3.6.1, here is the pseudo-code for + implementing chunked transfer-encoding: + + length := 0 + read chunk-size, chunk-extension (if any) and CRLF + while (chunk-size > 0) { + read chunk-data and CRLF + append chunk-data to entity-body + length := length + chunk-size + read chunk-size and CRLF + } + read entity-header + while (entity-header not empty) { + append entity-header to existing header fields + read entity-header + } + Content-Length := length + Remove "chunked" from Transfer-Encoding + */ + + var line = ''; + while(line !== null && b.length() > 0) { + // if in the process of reading a chunk + if(_chunkSize > 0) { + // if there are not enough bytes to read chunk and its + // trailing CRLF, we must wait for more data to be received + if(_chunkSize + 2 > b.length()) { + break; + } + + // read chunk data, skip CRLF + response.body += b.getBytes(_chunkSize); + b.getBytes(2); + _chunkSize = 0; + } else if(!_chunksFinished) { + // more chunks, read next chunk-size line + line = _readCrlf(b); + if(line !== null) { + // parse chunk-size (ignore any chunk extension) + _chunkSize = parseInt(line.split(';', 1)[0], 16); + _chunksFinished = (_chunkSize === 0); + } + } else { + // chunks finished, read next trailer + line = _readCrlf(b); + while(line !== null) { + if(line.length > 0) { + // parse trailer + _parseHeader(line); + // read next trailer + line = _readCrlf(b); + } else { + // body received + response.bodyReceived = true; + line = null; + } + } + } + } + + return response.bodyReceived; + }; + + /** + * Reads an http response body from a buffer of bytes. + * + * @param b the byte buffer to read from. + * + * @return true if the whole body was read, false if not. + */ + response.readBody = function(b) { + var contentLength = response.getField('Content-Length'); + var transferEncoding = response.getField('Transfer-Encoding'); + if(contentLength !== null) { + contentLength = parseInt(contentLength); + } + + // read specified length + if(contentLength !== null && contentLength >= 0) { + response.body = response.body || ''; + response.body += b.getBytes(contentLength); + response.bodyReceived = (response.body.length === contentLength); + } else if(transferEncoding !== null) { + // read chunked encoding + if(transferEncoding.indexOf('chunked') != -1) { + response.body = response.body || ''; + _readChunkedBody(b); + } else { + var error = new Error('Unknown Transfer-Encoding.'); + error.details = {'transferEncoding': transferEncoding}; + throw error; + } + } else if((contentLength !== null && contentLength < 0) || + (contentLength === null && + response.getField('Content-Type') !== null)) { + // read all data in the buffer + response.body = response.body || ''; + response.body += b.getBytes(); + response.readBodyUntilClose = true; + } else { + // no body + response.body = null; + response.bodyReceived = true; + } + + if(response.bodyReceived) { + response.time = +new Date() - response.time; + } + + if(response.flashApi !== null && + response.bodyReceived && response.body !== null && + response.getField('Content-Encoding') === 'deflate') { + // inflate using flash api + response.body = forge.util.inflate( + response.flashApi, response.body); + } + + return response.bodyReceived; + }; + + /** + * Parses an array of cookies from the 'Set-Cookie' field, if present. + * + * @return the array of cookies. + */ + response.getCookies = function() { + var rval = []; + + // get Set-Cookie field + if('Set-Cookie' in response.fields) { + var field = response.fields['Set-Cookie']; + + // get current local time in seconds + var now = +new Date() / 1000; + + // regex for parsing 'name1=value1; name2=value2; name3' + var regex = /\s*([^=]*)=?([^;]*)(;|$)/g; + + // examples: + // Set-Cookie: cookie1_name=cookie1_value; max-age=0; path=/ + // Set-Cookie: c2=v2; expires=Thu, 21-Aug-2008 23:47:25 GMT; path=/ + for(var i = 0; i < field.length; ++i) { + var fv = field[i]; + var m; + regex.lastIndex = 0; + var first = true; + var cookie = {}; + do { + m = regex.exec(fv); + if(m !== null) { + var name = _trimString(m[1]); + var value = _trimString(m[2]); + + // cookie_name=value + if(first) { + cookie.name = name; + cookie.value = value; + first = false; + } else { + // property_name=value + name = name.toLowerCase(); + switch(name) { + case 'expires': + // replace hyphens w/spaces so date will parse + value = value.replace(/-/g, ' '); + var secs = Date.parse(value) / 1000; + cookie.maxAge = Math.max(0, secs - now); + break; + case 'max-age': + cookie.maxAge = parseInt(value, 10); + break; + case 'secure': + cookie.secure = true; + break; + case 'httponly': + cookie.httpOnly = true; + break; + default: + if(name !== '') { + cookie[name] = value; + } + } + } + } + } while(m !== null && m[0] !== ''); + rval.push(cookie); + } + } + + return rval; + }; + + /** + * Converts an http response into a string that can be sent as an + * HTTP response. Does not include any data. + * + * @return the string representation of the response. + */ + response.toString = function() { + /* Sample response header: + HTTP/1.0 200 OK + Host: www.someurl.com + Connection: close + */ + + // build start line + var rval = + response.version + ' ' + response.code + ' ' + response.message + '\r\n'; + + // add each header + for(var name in response.fields) { + var fields = response.fields[name]; + for(var i = 0; i < fields.length; ++i) { + rval += name + ': ' + fields[i] + '\r\n'; + } + } + // final terminating CRLF + rval += '\r\n'; + + return rval; + }; + + return response; +}; + +/** + * Returns true if the given url is within the given cookie's domain. + * + * @param url the url to check. + * @param cookie the cookie or cookie domain to check. + */ +http.withinCookieDomain = function(url, cookie) { + var rval = false; + + // cookie may be null, a cookie object, or a domain string + var domain = (cookie === null || typeof cookie === 'string') ? + cookie : cookie.domain; + + // any domain will do + if(domain === null) { + rval = true; + } else if(domain.charAt(0) === '.') { + // ensure domain starts with a '.' + // parse URL as necessary + if(typeof url === 'string') { + url = new URL(url); + } + + // add '.' to front of URL hostname to match against domain + var host = '.' + url.hostname; + + // if the host ends with domain then it falls within it + var idx = host.lastIndexOf(domain); + if(idx !== -1 && (idx + domain.length === host.length)) { + rval = true; + } + } + + return rval; +}; diff --git a/node_modules/node-forge/lib/index.all.js b/node_modules/node-forge/lib/index.all.js new file mode 100644 index 0000000..22ba72b --- /dev/null +++ b/node_modules/node-forge/lib/index.all.js @@ -0,0 +1,16 @@ +/** + * Node.js module for Forge with extra utils and networking. + * + * @author Dave Longley + * + * Copyright 2011-2016 Digital Bazaar, Inc. + */ +module.exports = require('./forge'); +// require core forge +require('./index'); +// additional utils and networking support +require('./form'); +require('./socket'); +require('./tlssocket'); +require('./http'); +require('./xhr'); diff --git a/node_modules/node-forge/lib/index.js b/node_modules/node-forge/lib/index.js new file mode 100644 index 0000000..6cdd5a9 --- /dev/null +++ b/node_modules/node-forge/lib/index.js @@ -0,0 +1,33 @@ +/** + * Node.js module for Forge. + * + * @author Dave Longley + * + * Copyright 2011-2016 Digital Bazaar, Inc. + */ +module.exports = require('./forge'); +require('./aes'); +require('./aesCipherSuites'); +require('./asn1'); +require('./cipher'); +require('./des'); +require('./ed25519'); +require('./hmac'); +require('./kem'); +require('./log'); +require('./md.all'); +require('./mgf1'); +require('./pbkdf2'); +require('./pem'); +require('./pkcs1'); +require('./pkcs12'); +require('./pkcs7'); +require('./pki'); +require('./prime'); +require('./prng'); +require('./pss'); +require('./random'); +require('./rc2'); +require('./ssh'); +require('./tls'); +require('./util'); diff --git a/node_modules/node-forge/lib/jsbn.js b/node_modules/node-forge/lib/jsbn.js new file mode 100644 index 0000000..11f965c --- /dev/null +++ b/node_modules/node-forge/lib/jsbn.js @@ -0,0 +1,1264 @@ +// Copyright (c) 2005 Tom Wu +// All Rights Reserved. +// See "LICENSE" for details. + +// Basic JavaScript BN library - subset useful for RSA encryption. + +/* +Licensing (LICENSE) +------------------- + +This software is covered under the following copyright: +*/ +/* + * Copyright (c) 2003-2005 Tom Wu + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, + * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF + * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * In addition, the following condition applies: + * + * All redistributions must retain an intact copy of this copyright notice + * and disclaimer. + */ +/* +Address all questions regarding this license to: + + Tom Wu + tjw@cs.Stanford.EDU +*/ +var forge = require('./forge'); + +module.exports = forge.jsbn = forge.jsbn || {}; + +// Bits per digit +var dbits; + +// JavaScript engine analysis +var canary = 0xdeadbeefcafe; +var j_lm = ((canary&0xffffff)==0xefcafe); + +// (public) Constructor +function BigInteger(a,b,c) { + this.data = []; + if(a != null) + if("number" == typeof a) this.fromNumber(a,b,c); + else if(b == null && "string" != typeof a) this.fromString(a,256); + else this.fromString(a,b); +} +forge.jsbn.BigInteger = BigInteger; + +// return new, unset BigInteger +function nbi() { return new BigInteger(null); } + +// am: Compute w_j += (x*this_i), propagate carries, +// c is initial carry, returns final carry. +// c < 3*dvalue, x < 2*dvalue, this_i < dvalue +// We need to select the fastest one that works in this environment. + +// am1: use a single mult and divide to get the high bits, +// max digit bits should be 26 because +// max internal value = 2*dvalue^2-2*dvalue (< 2^53) +function am1(i,x,w,j,c,n) { + while(--n >= 0) { + var v = x*this.data[i++]+w.data[j]+c; + c = Math.floor(v/0x4000000); + w.data[j++] = v&0x3ffffff; + } + return c; +} +// am2 avoids a big mult-and-extract completely. +// Max digit bits should be <= 30 because we do bitwise ops +// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) +function am2(i,x,w,j,c,n) { + var xl = x&0x7fff, xh = x>>15; + while(--n >= 0) { + var l = this.data[i]&0x7fff; + var h = this.data[i++]>>15; + var m = xh*l+h*xl; + l = xl*l+((m&0x7fff)<<15)+w.data[j]+(c&0x3fffffff); + c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); + w.data[j++] = l&0x3fffffff; + } + return c; +} +// Alternately, set max digit bits to 28 since some +// browsers slow down when dealing with 32-bit numbers. +function am3(i,x,w,j,c,n) { + var xl = x&0x3fff, xh = x>>14; + while(--n >= 0) { + var l = this.data[i]&0x3fff; + var h = this.data[i++]>>14; + var m = xh*l+h*xl; + l = xl*l+((m&0x3fff)<<14)+w.data[j]+c; + c = (l>>28)+(m>>14)+xh*h; + w.data[j++] = l&0xfffffff; + } + return c; +} + +// node.js (no browser) +if(typeof(navigator) === 'undefined') +{ + BigInteger.prototype.am = am3; + dbits = 28; +} else if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) { + BigInteger.prototype.am = am2; + dbits = 30; +} else if(j_lm && (navigator.appName != "Netscape")) { + BigInteger.prototype.am = am1; + dbits = 26; +} else { // Mozilla/Netscape seems to prefer am3 + BigInteger.prototype.am = am3; + dbits = 28; +} + +BigInteger.prototype.DB = dbits; +BigInteger.prototype.DM = ((1<= 0; --i) r.data[i] = this.data[i]; + r.t = this.t; + r.s = this.s; +} + +// (protected) set from integer value x, -DV <= x < DV +function bnpFromInt(x) { + this.t = 1; + this.s = (x<0)?-1:0; + if(x > 0) this.data[0] = x; + else if(x < -1) this.data[0] = x+this.DV; + else this.t = 0; +} + +// return bigint initialized to value +function nbv(i) { var r = nbi(); r.fromInt(i); return r; } + +// (protected) set from string and radix +function bnpFromString(s,b) { + var k; + if(b == 16) k = 4; + else if(b == 8) k = 3; + else if(b == 256) k = 8; // byte array + else if(b == 2) k = 1; + else if(b == 32) k = 5; + else if(b == 4) k = 2; + else { this.fromRadix(s,b); return; } + this.t = 0; + this.s = 0; + var i = s.length, mi = false, sh = 0; + while(--i >= 0) { + var x = (k==8)?s[i]&0xff:intAt(s,i); + if(x < 0) { + if(s.charAt(i) == "-") mi = true; + continue; + } + mi = false; + if(sh == 0) + this.data[this.t++] = x; + else if(sh+k > this.DB) { + this.data[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh)); + } else + this.data[this.t-1] |= x<= this.DB) sh -= this.DB; + } + if(k == 8 && (s[0]&0x80) != 0) { + this.s = -1; + if(sh > 0) this.data[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this.data[this.t-1] == c) --this.t; +} + +// (public) return string representation in given radix +function bnToString(b) { + if(this.s < 0) return "-"+this.negate().toString(b); + var k; + if(b == 16) k = 4; + else if(b == 8) k = 3; + else if(b == 2) k = 1; + else if(b == 32) k = 5; + else if(b == 4) k = 2; + else return this.toRadix(b); + var km = (1< 0) { + if(p < this.DB && (d = this.data[i]>>p) > 0) { m = true; r = int2char(d); } + while(i >= 0) { + if(p < k) { + d = (this.data[i]&((1<>(p+=this.DB-k); + } else { + d = (this.data[i]>>(p-=k))&km; + if(p <= 0) { p += this.DB; --i; } + } + if(d > 0) m = true; + if(m) r += int2char(d); + } + } + return m?r:"0"; +} + +// (public) -this +function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } + +// (public) |this| +function bnAbs() { return (this.s<0)?this.negate():this; } + +// (public) return + if this > a, - if this < a, 0 if equal +function bnCompareTo(a) { + var r = this.s-a.s; + if(r != 0) return r; + var i = this.t; + r = i-a.t; + if(r != 0) return (this.s<0)?-r:r; + while(--i >= 0) if((r=this.data[i]-a.data[i]) != 0) return r; + return 0; +} + +// returns bit length of the integer x +function nbits(x) { + var r = 1, t; + if((t=x>>>16) != 0) { x = t; r += 16; } + if((t=x>>8) != 0) { x = t; r += 8; } + if((t=x>>4) != 0) { x = t; r += 4; } + if((t=x>>2) != 0) { x = t; r += 2; } + if((t=x>>1) != 0) { x = t; r += 1; } + return r; +} + +// (public) return the number of bits in "this" +function bnBitLength() { + if(this.t <= 0) return 0; + return this.DB*(this.t-1)+nbits(this.data[this.t-1]^(this.s&this.DM)); +} + +// (protected) r = this << n*DB +function bnpDLShiftTo(n,r) { + var i; + for(i = this.t-1; i >= 0; --i) r.data[i+n] = this.data[i]; + for(i = n-1; i >= 0; --i) r.data[i] = 0; + r.t = this.t+n; + r.s = this.s; +} + +// (protected) r = this >> n*DB +function bnpDRShiftTo(n,r) { + for(var i = n; i < this.t; ++i) r.data[i-n] = this.data[i]; + r.t = Math.max(this.t-n,0); + r.s = this.s; +} + +// (protected) r = this << n +function bnpLShiftTo(n,r) { + var bs = n%this.DB; + var cbs = this.DB-bs; + var bm = (1<= 0; --i) { + r.data[i+ds+1] = (this.data[i]>>cbs)|c; + c = (this.data[i]&bm)<= 0; --i) r.data[i] = 0; + r.data[ds] = c; + r.t = this.t+ds+1; + r.s = this.s; + r.clamp(); +} + +// (protected) r = this >> n +function bnpRShiftTo(n,r) { + r.s = this.s; + var ds = Math.floor(n/this.DB); + if(ds >= this.t) { r.t = 0; return; } + var bs = n%this.DB; + var cbs = this.DB-bs; + var bm = (1<>bs; + for(var i = ds+1; i < this.t; ++i) { + r.data[i-ds-1] |= (this.data[i]&bm)<>bs; + } + if(bs > 0) r.data[this.t-ds-1] |= (this.s&bm)<>= this.DB; + } + if(a.t < this.t) { + c -= a.s; + while(i < this.t) { + c += this.data[i]; + r.data[i++] = c&this.DM; + c >>= this.DB; + } + c += this.s; + } else { + c += this.s; + while(i < a.t) { + c -= a.data[i]; + r.data[i++] = c&this.DM; + c >>= this.DB; + } + c -= a.s; + } + r.s = (c<0)?-1:0; + if(c < -1) r.data[i++] = this.DV+c; + else if(c > 0) r.data[i++] = c; + r.t = i; + r.clamp(); +} + +// (protected) r = this * a, r != this,a (HAC 14.12) +// "this" should be the larger one if appropriate. +function bnpMultiplyTo(a,r) { + var x = this.abs(), y = a.abs(); + var i = x.t; + r.t = i+y.t; + while(--i >= 0) r.data[i] = 0; + for(i = 0; i < y.t; ++i) r.data[i+x.t] = x.am(0,y.data[i],r,i,0,x.t); + r.s = 0; + r.clamp(); + if(this.s != a.s) BigInteger.ZERO.subTo(r,r); +} + +// (protected) r = this^2, r != this (HAC 14.16) +function bnpSquareTo(r) { + var x = this.abs(); + var i = r.t = 2*x.t; + while(--i >= 0) r.data[i] = 0; + for(i = 0; i < x.t-1; ++i) { + var c = x.am(i,x.data[i],r,2*i,0,1); + if((r.data[i+x.t]+=x.am(i+1,2*x.data[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { + r.data[i+x.t] -= x.DV; + r.data[i+x.t+1] = 1; + } + } + if(r.t > 0) r.data[r.t-1] += x.am(i,x.data[i],r,2*i,0,1); + r.s = 0; + r.clamp(); +} + +// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) +// r != q, this != m. q or r may be null. +function bnpDivRemTo(m,q,r) { + var pm = m.abs(); + if(pm.t <= 0) return; + var pt = this.abs(); + if(pt.t < pm.t) { + if(q != null) q.fromInt(0); + if(r != null) this.copyTo(r); + return; + } + if(r == null) r = nbi(); + var y = nbi(), ts = this.s, ms = m.s; + var nsh = this.DB-nbits(pm.data[pm.t-1]); // normalize modulus + if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } + var ys = y.t; + var y0 = y.data[ys-1]; + if(y0 == 0) return; + var yt = y0*(1<1)?y.data[ys-2]>>this.F2:0); + var d1 = this.FV/yt, d2 = (1<= 0) { + r.data[r.t++] = 1; + r.subTo(t,r); + } + BigInteger.ONE.dlShiftTo(ys,t); + t.subTo(y,y); // "negative" y so we can replace sub with am later + while(y.t < ys) y.data[y.t++] = 0; + while(--j >= 0) { + // Estimate quotient digit + var qd = (r.data[--i]==y0)?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2); + if((r.data[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out + y.dlShiftTo(j,t); + r.subTo(t,r); + while(r.data[i] < --qd) r.subTo(t,r); + } + } + if(q != null) { + r.drShiftTo(ys,q); + if(ts != ms) BigInteger.ZERO.subTo(q,q); + } + r.t = ys; + r.clamp(); + if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder + if(ts < 0) BigInteger.ZERO.subTo(r,r); +} + +// (public) this mod a +function bnMod(a) { + var r = nbi(); + this.abs().divRemTo(a,null,r); + if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); + return r; +} + +// Modular reduction using "classic" algorithm +function Classic(m) { this.m = m; } +function cConvert(x) { + if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); + else return x; +} +function cRevert(x) { return x; } +function cReduce(x) { x.divRemTo(this.m,null,x); } +function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } +function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + +Classic.prototype.convert = cConvert; +Classic.prototype.revert = cRevert; +Classic.prototype.reduce = cReduce; +Classic.prototype.mulTo = cMulTo; +Classic.prototype.sqrTo = cSqrTo; + +// (protected) return "-1/this % 2^DB"; useful for Mont. reduction +// justification: +// xy == 1 (mod m) +// xy = 1+km +// xy(2-xy) = (1+km)(1-km) +// x[y(2-xy)] = 1-k^2m^2 +// x[y(2-xy)] == 1 (mod m^2) +// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 +// should reduce x and y(2-xy) by m^2 at each step to keep size bounded. +// JS multiply "overflows" differently from C/C++, so care is needed here. +function bnpInvDigit() { + if(this.t < 1) return 0; + var x = this.data[0]; + if((x&1) == 0) return 0; + var y = x&3; // y == 1/x mod 2^2 + y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 + y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 + y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 + // last step - calculate inverse mod DV directly; + // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints + y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits + // we really want the negative inverse, and -DV < y < DV + return (y>0)?this.DV-y:-y; +} + +// Montgomery reduction +function Montgomery(m) { + this.m = m; + this.mp = m.invDigit(); + this.mpl = this.mp&0x7fff; + this.mph = this.mp>>15; + this.um = (1<<(m.DB-15))-1; + this.mt2 = 2*m.t; +} + +// xR mod m +function montConvert(x) { + var r = nbi(); + x.abs().dlShiftTo(this.m.t,r); + r.divRemTo(this.m,null,r); + if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); + return r; +} + +// x/R mod m +function montRevert(x) { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; +} + +// x = x/R mod m (HAC 14.32) +function montReduce(x) { + while(x.t <= this.mt2) // pad x so am has enough room later + x.data[x.t++] = 0; + for(var i = 0; i < this.m.t; ++i) { + // faster way of calculating u0 = x.data[i]*mp mod DV + var j = x.data[i]&0x7fff; + var u0 = (j*this.mpl+(((j*this.mph+(x.data[i]>>15)*this.mpl)&this.um)<<15))&x.DM; + // use am to combine the multiply-shift-add into one call + j = i+this.m.t; + x.data[j] += this.m.am(0,u0,x,i,0,this.m.t); + // propagate carry + while(x.data[j] >= x.DV) { x.data[j] -= x.DV; x.data[++j]++; } + } + x.clamp(); + x.drShiftTo(this.m.t,x); + if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); +} + +// r = "x^2/R mod m"; x != r +function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + +// r = "xy/R mod m"; x,y != r +function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } + +Montgomery.prototype.convert = montConvert; +Montgomery.prototype.revert = montRevert; +Montgomery.prototype.reduce = montReduce; +Montgomery.prototype.mulTo = montMulTo; +Montgomery.prototype.sqrTo = montSqrTo; + +// (protected) true iff this is even +function bnpIsEven() { return ((this.t>0)?(this.data[0]&1):this.s) == 0; } + +// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) +function bnpExp(e,z) { + if(e > 0xffffffff || e < 1) return BigInteger.ONE; + var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; + g.copyTo(r); + while(--i >= 0) { + z.sqrTo(r,r2); + if((e&(1< 0) z.mulTo(r2,g,r); + else { var t = r; r = r2; r2 = t; } + } + return z.revert(r); +} + +// (public) this^e % m, 0 <= e < 2^32 +function bnModPowInt(e,m) { + var z; + if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); + return this.exp(e,z); +} + +// protected +BigInteger.prototype.copyTo = bnpCopyTo; +BigInteger.prototype.fromInt = bnpFromInt; +BigInteger.prototype.fromString = bnpFromString; +BigInteger.prototype.clamp = bnpClamp; +BigInteger.prototype.dlShiftTo = bnpDLShiftTo; +BigInteger.prototype.drShiftTo = bnpDRShiftTo; +BigInteger.prototype.lShiftTo = bnpLShiftTo; +BigInteger.prototype.rShiftTo = bnpRShiftTo; +BigInteger.prototype.subTo = bnpSubTo; +BigInteger.prototype.multiplyTo = bnpMultiplyTo; +BigInteger.prototype.squareTo = bnpSquareTo; +BigInteger.prototype.divRemTo = bnpDivRemTo; +BigInteger.prototype.invDigit = bnpInvDigit; +BigInteger.prototype.isEven = bnpIsEven; +BigInteger.prototype.exp = bnpExp; + +// public +BigInteger.prototype.toString = bnToString; +BigInteger.prototype.negate = bnNegate; +BigInteger.prototype.abs = bnAbs; +BigInteger.prototype.compareTo = bnCompareTo; +BigInteger.prototype.bitLength = bnBitLength; +BigInteger.prototype.mod = bnMod; +BigInteger.prototype.modPowInt = bnModPowInt; + +// "constants" +BigInteger.ZERO = nbv(0); +BigInteger.ONE = nbv(1); + +// jsbn2 lib + +//Copyright (c) 2005-2009 Tom Wu +//All Rights Reserved. +//See "LICENSE" for details (See jsbn.js for LICENSE). + +//Extended JavaScript BN functions, required for RSA private ops. + +//Version 1.1: new BigInteger("0", 10) returns "proper" zero + +//(public) +function bnClone() { var r = nbi(); this.copyTo(r); return r; } + +//(public) return value as integer +function bnIntValue() { +if(this.s < 0) { + if(this.t == 1) return this.data[0]-this.DV; + else if(this.t == 0) return -1; +} else if(this.t == 1) return this.data[0]; +else if(this.t == 0) return 0; +// assumes 16 < DB < 32 +return ((this.data[1]&((1<<(32-this.DB))-1))<>24; } + +//(public) return value as short (assumes DB>=16) +function bnShortValue() { return (this.t==0)?this.s:(this.data[0]<<16)>>16; } + +//(protected) return x s.t. r^x < DV +function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } + +//(public) 0 if this == 0, 1 if this > 0 +function bnSigNum() { +if(this.s < 0) return -1; +else if(this.t <= 0 || (this.t == 1 && this.data[0] <= 0)) return 0; +else return 1; +} + +//(protected) convert to radix string +function bnpToRadix(b) { +if(b == null) b = 10; +if(this.signum() == 0 || b < 2 || b > 36) return "0"; +var cs = this.chunkSize(b); +var a = Math.pow(b,cs); +var d = nbv(a), y = nbi(), z = nbi(), r = ""; +this.divRemTo(d,y,z); +while(y.signum() > 0) { + r = (a+z.intValue()).toString(b).substr(1) + r; + y.divRemTo(d,y,z); +} +return z.intValue().toString(b) + r; +} + +//(protected) convert from radix string +function bnpFromRadix(s,b) { +this.fromInt(0); +if(b == null) b = 10; +var cs = this.chunkSize(b); +var d = Math.pow(b,cs), mi = false, j = 0, w = 0; +for(var i = 0; i < s.length; ++i) { + var x = intAt(s,i); + if(x < 0) { + if(s.charAt(i) == "-" && this.signum() == 0) mi = true; + continue; + } + w = b*w+x; + if(++j >= cs) { + this.dMultiply(d); + this.dAddOffset(w,0); + j = 0; + w = 0; + } +} +if(j > 0) { + this.dMultiply(Math.pow(b,j)); + this.dAddOffset(w,0); +} +if(mi) BigInteger.ZERO.subTo(this,this); +} + +//(protected) alternate constructor +function bnpFromNumber(a,b,c) { +if("number" == typeof b) { + // new BigInteger(int,int,RNG) + if(a < 2) this.fromInt(1); + else { + this.fromNumber(a,c); + if(!this.testBit(a-1)) // force MSB set + this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); + if(this.isEven()) this.dAddOffset(1,0); // force odd + while(!this.isProbablePrime(b)) { + this.dAddOffset(2,0); + if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); + } + } +} else { + // new BigInteger(int,RNG) + var x = new Array(), t = a&7; + x.length = (a>>3)+1; + b.nextBytes(x); + if(t > 0) x[0] &= ((1< 0) { + if(p < this.DB && (d = this.data[i]>>p) != (this.s&this.DM)>>p) + r[k++] = d|(this.s<<(this.DB-p)); + while(i >= 0) { + if(p < 8) { + d = (this.data[i]&((1<>(p+=this.DB-8); + } else { + d = (this.data[i]>>(p-=8))&0xff; + if(p <= 0) { p += this.DB; --i; } + } + if((d&0x80) != 0) d |= -256; + if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; + if(k > 0 || d != this.s) r[k++] = d; + } +} +return r; +} + +function bnEquals(a) { return(this.compareTo(a)==0); } +function bnMin(a) { return(this.compareTo(a)<0)?this:a; } +function bnMax(a) { return(this.compareTo(a)>0)?this:a; } + +//(protected) r = this op a (bitwise) +function bnpBitwiseTo(a,op,r) { +var i, f, m = Math.min(a.t,this.t); +for(i = 0; i < m; ++i) r.data[i] = op(this.data[i],a.data[i]); +if(a.t < this.t) { + f = a.s&this.DM; + for(i = m; i < this.t; ++i) r.data[i] = op(this.data[i],f); + r.t = this.t; +} else { + f = this.s&this.DM; + for(i = m; i < a.t; ++i) r.data[i] = op(f,a.data[i]); + r.t = a.t; +} +r.s = op(this.s,a.s); +r.clamp(); +} + +//(public) this & a +function op_and(x,y) { return x&y; } +function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } + +//(public) this | a +function op_or(x,y) { return x|y; } +function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } + +//(public) this ^ a +function op_xor(x,y) { return x^y; } +function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } + +//(public) this & ~a +function op_andnot(x,y) { return x&~y; } +function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } + +//(public) ~this +function bnNot() { +var r = nbi(); +for(var i = 0; i < this.t; ++i) r.data[i] = this.DM&~this.data[i]; +r.t = this.t; +r.s = ~this.s; +return r; +} + +//(public) this << n +function bnShiftLeft(n) { +var r = nbi(); +if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); +return r; +} + +//(public) this >> n +function bnShiftRight(n) { +var r = nbi(); +if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); +return r; +} + +//return index of lowest 1-bit in x, x < 2^31 +function lbit(x) { +if(x == 0) return -1; +var r = 0; +if((x&0xffff) == 0) { x >>= 16; r += 16; } +if((x&0xff) == 0) { x >>= 8; r += 8; } +if((x&0xf) == 0) { x >>= 4; r += 4; } +if((x&3) == 0) { x >>= 2; r += 2; } +if((x&1) == 0) ++r; +return r; +} + +//(public) returns index of lowest 1-bit (or -1 if none) +function bnGetLowestSetBit() { +for(var i = 0; i < this.t; ++i) + if(this.data[i] != 0) return i*this.DB+lbit(this.data[i]); +if(this.s < 0) return this.t*this.DB; +return -1; +} + +//return number of 1 bits in x +function cbit(x) { +var r = 0; +while(x != 0) { x &= x-1; ++r; } +return r; +} + +//(public) return number of set bits +function bnBitCount() { +var r = 0, x = this.s&this.DM; +for(var i = 0; i < this.t; ++i) r += cbit(this.data[i]^x); +return r; +} + +//(public) true iff nth bit is set +function bnTestBit(n) { +var j = Math.floor(n/this.DB); +if(j >= this.t) return(this.s!=0); +return((this.data[j]&(1<<(n%this.DB)))!=0); +} + +//(protected) this op (1<>= this.DB; +} +if(a.t < this.t) { + c += a.s; + while(i < this.t) { + c += this.data[i]; + r.data[i++] = c&this.DM; + c >>= this.DB; + } + c += this.s; +} else { + c += this.s; + while(i < a.t) { + c += a.data[i]; + r.data[i++] = c&this.DM; + c >>= this.DB; + } + c += a.s; +} +r.s = (c<0)?-1:0; +if(c > 0) r.data[i++] = c; +else if(c < -1) r.data[i++] = this.DV+c; +r.t = i; +r.clamp(); +} + +//(public) this + a +function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } + +//(public) this - a +function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } + +//(public) this * a +function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } + +//(public) this / a +function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } + +//(public) this % a +function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } + +//(public) [this/a,this%a] +function bnDivideAndRemainder(a) { +var q = nbi(), r = nbi(); +this.divRemTo(a,q,r); +return new Array(q,r); +} + +//(protected) this *= n, this >= 0, 1 < n < DV +function bnpDMultiply(n) { +this.data[this.t] = this.am(0,n-1,this,0,0,this.t); +++this.t; +this.clamp(); +} + +//(protected) this += n << w words, this >= 0 +function bnpDAddOffset(n,w) { +if(n == 0) return; +while(this.t <= w) this.data[this.t++] = 0; +this.data[w] += n; +while(this.data[w] >= this.DV) { + this.data[w] -= this.DV; + if(++w >= this.t) this.data[this.t++] = 0; + ++this.data[w]; +} +} + +//A "null" reducer +function NullExp() {} +function nNop(x) { return x; } +function nMulTo(x,y,r) { x.multiplyTo(y,r); } +function nSqrTo(x,r) { x.squareTo(r); } + +NullExp.prototype.convert = nNop; +NullExp.prototype.revert = nNop; +NullExp.prototype.mulTo = nMulTo; +NullExp.prototype.sqrTo = nSqrTo; + +//(public) this^e +function bnPow(e) { return this.exp(e,new NullExp()); } + +//(protected) r = lower n words of "this * a", a.t <= n +//"this" should be the larger one if appropriate. +function bnpMultiplyLowerTo(a,n,r) { +var i = Math.min(this.t+a.t,n); +r.s = 0; // assumes a,this >= 0 +r.t = i; +while(i > 0) r.data[--i] = 0; +var j; +for(j = r.t-this.t; i < j; ++i) r.data[i+this.t] = this.am(0,a.data[i],r,i,0,this.t); +for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a.data[i],r,i,0,n-i); +r.clamp(); +} + +//(protected) r = "this * a" without lower n words, n > 0 +//"this" should be the larger one if appropriate. +function bnpMultiplyUpperTo(a,n,r) { +--n; +var i = r.t = this.t+a.t-n; +r.s = 0; // assumes a,this >= 0 +while(--i >= 0) r.data[i] = 0; +for(i = Math.max(n-this.t,0); i < a.t; ++i) + r.data[this.t+i-n] = this.am(n-i,a.data[i],r,0,0,this.t+i-n); +r.clamp(); +r.drShiftTo(1,r); +} + +//Barrett modular reduction +function Barrett(m) { +// setup Barrett +this.r2 = nbi(); +this.q3 = nbi(); +BigInteger.ONE.dlShiftTo(2*m.t,this.r2); +this.mu = this.r2.divide(m); +this.m = m; +} + +function barrettConvert(x) { +if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); +else if(x.compareTo(this.m) < 0) return x; +else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } +} + +function barrettRevert(x) { return x; } + +//x = x mod m (HAC 14.42) +function barrettReduce(x) { +x.drShiftTo(this.m.t-1,this.r2); +if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } +this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); +this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); +while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); +x.subTo(this.r2,x); +while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); +} + +//r = x^2 mod m; x != r +function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + +//r = x*y mod m; x,y != r +function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } + +Barrett.prototype.convert = barrettConvert; +Barrett.prototype.revert = barrettRevert; +Barrett.prototype.reduce = barrettReduce; +Barrett.prototype.mulTo = barrettMulTo; +Barrett.prototype.sqrTo = barrettSqrTo; + +//(public) this^e % m (HAC 14.85) +function bnModPow(e,m) { +var i = e.bitLength(), k, r = nbv(1), z; +if(i <= 0) return r; +else if(i < 18) k = 1; +else if(i < 48) k = 3; +else if(i < 144) k = 4; +else if(i < 768) k = 5; +else k = 6; +if(i < 8) + z = new Classic(m); +else if(m.isEven()) + z = new Barrett(m); +else + z = new Montgomery(m); + +// precomputation +var g = new Array(), n = 3, k1 = k-1, km = (1< 1) { + var g2 = nbi(); + z.sqrTo(g[1],g2); + while(n <= km) { + g[n] = nbi(); + z.mulTo(g2,g[n-2],g[n]); + n += 2; + } +} + +var j = e.t-1, w, is1 = true, r2 = nbi(), t; +i = nbits(e.data[j])-1; +while(j >= 0) { + if(i >= k1) w = (e.data[j]>>(i-k1))&km; + else { + w = (e.data[j]&((1<<(i+1))-1))<<(k1-i); + if(j > 0) w |= e.data[j-1]>>(this.DB+i-k1); + } + + n = k; + while((w&1) == 0) { w >>= 1; --n; } + if((i -= n) < 0) { i += this.DB; --j; } + if(is1) { // ret == 1, don't bother squaring or multiplying it + g[w].copyTo(r); + is1 = false; + } else { + while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } + if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } + z.mulTo(r2,g[w],r); + } + + while(j >= 0 && (e.data[j]&(1< 0) { + x.rShiftTo(g,x); + y.rShiftTo(g,y); +} +while(x.signum() > 0) { + if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); + if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); + if(x.compareTo(y) >= 0) { + x.subTo(y,x); + x.rShiftTo(1,x); + } else { + y.subTo(x,y); + y.rShiftTo(1,y); + } +} +if(g > 0) y.lShiftTo(g,y); +return y; +} + +//(protected) this % n, n < 2^26 +function bnpModInt(n) { +if(n <= 0) return 0; +var d = this.DV%n, r = (this.s<0)?n-1:0; +if(this.t > 0) + if(d == 0) r = this.data[0]%n; + else for(var i = this.t-1; i >= 0; --i) r = (d*r+this.data[i])%n; +return r; +} + +//(public) 1/this % m (HAC 14.61) +function bnModInverse(m) { +var ac = m.isEven(); +if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; +var u = m.clone(), v = this.clone(); +var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); +while(u.signum() != 0) { + while(u.isEven()) { + u.rShiftTo(1,u); + if(ac) { + if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } + a.rShiftTo(1,a); + } else if(!b.isEven()) b.subTo(m,b); + b.rShiftTo(1,b); + } + while(v.isEven()) { + v.rShiftTo(1,v); + if(ac) { + if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } + c.rShiftTo(1,c); + } else if(!d.isEven()) d.subTo(m,d); + d.rShiftTo(1,d); + } + if(u.compareTo(v) >= 0) { + u.subTo(v,u); + if(ac) a.subTo(c,a); + b.subTo(d,b); + } else { + v.subTo(u,v); + if(ac) c.subTo(a,c); + d.subTo(b,d); + } +} +if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; +if(d.compareTo(m) >= 0) return d.subtract(m); +if(d.signum() < 0) d.addTo(m,d); else return d; +if(d.signum() < 0) return d.add(m); else return d; +} + +var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; +var lplim = (1<<26)/lowprimes[lowprimes.length-1]; + +//(public) test primality with certainty >= 1-.5^t +function bnIsProbablePrime(t) { +var i, x = this.abs(); +if(x.t == 1 && x.data[0] <= lowprimes[lowprimes.length-1]) { + for(i = 0; i < lowprimes.length; ++i) + if(x.data[0] == lowprimes[i]) return true; + return false; +} +if(x.isEven()) return false; +i = 1; +while(i < lowprimes.length) { + var m = lowprimes[i], j = i+1; + while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; + m = x.modInt(m); + while(i < j) if(m%lowprimes[i++] == 0) return false; +} +return x.millerRabin(t); +} + +//(protected) true if probably prime (HAC 4.24, Miller-Rabin) +function bnpMillerRabin(t) { +var n1 = this.subtract(BigInteger.ONE); +var k = n1.getLowestSetBit(); +if(k <= 0) return false; +var r = n1.shiftRight(k); +var prng = bnGetPrng(); +var a; +for(var i = 0; i < t; ++i) { + // select witness 'a' at random from between 1 and n1 + do { + a = new BigInteger(this.bitLength(), prng); + } + while(a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0); + var y = a.modPow(r,this); + if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1; + while(j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2,this); + if(y.compareTo(BigInteger.ONE) == 0) return false; + } + if(y.compareTo(n1) != 0) return false; + } +} +return true; +} + +// get pseudo random number generator +function bnGetPrng() { + // create prng with api that matches BigInteger secure random + return { + // x is an array to fill with bytes + nextBytes: function(x) { + for(var i = 0; i < x.length; ++i) { + x[i] = Math.floor(Math.random() * 0x0100); + } + } + }; +} + +//protected +BigInteger.prototype.chunkSize = bnpChunkSize; +BigInteger.prototype.toRadix = bnpToRadix; +BigInteger.prototype.fromRadix = bnpFromRadix; +BigInteger.prototype.fromNumber = bnpFromNumber; +BigInteger.prototype.bitwiseTo = bnpBitwiseTo; +BigInteger.prototype.changeBit = bnpChangeBit; +BigInteger.prototype.addTo = bnpAddTo; +BigInteger.prototype.dMultiply = bnpDMultiply; +BigInteger.prototype.dAddOffset = bnpDAddOffset; +BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; +BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; +BigInteger.prototype.modInt = bnpModInt; +BigInteger.prototype.millerRabin = bnpMillerRabin; + +//public +BigInteger.prototype.clone = bnClone; +BigInteger.prototype.intValue = bnIntValue; +BigInteger.prototype.byteValue = bnByteValue; +BigInteger.prototype.shortValue = bnShortValue; +BigInteger.prototype.signum = bnSigNum; +BigInteger.prototype.toByteArray = bnToByteArray; +BigInteger.prototype.equals = bnEquals; +BigInteger.prototype.min = bnMin; +BigInteger.prototype.max = bnMax; +BigInteger.prototype.and = bnAnd; +BigInteger.prototype.or = bnOr; +BigInteger.prototype.xor = bnXor; +BigInteger.prototype.andNot = bnAndNot; +BigInteger.prototype.not = bnNot; +BigInteger.prototype.shiftLeft = bnShiftLeft; +BigInteger.prototype.shiftRight = bnShiftRight; +BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; +BigInteger.prototype.bitCount = bnBitCount; +BigInteger.prototype.testBit = bnTestBit; +BigInteger.prototype.setBit = bnSetBit; +BigInteger.prototype.clearBit = bnClearBit; +BigInteger.prototype.flipBit = bnFlipBit; +BigInteger.prototype.add = bnAdd; +BigInteger.prototype.subtract = bnSubtract; +BigInteger.prototype.multiply = bnMultiply; +BigInteger.prototype.divide = bnDivide; +BigInteger.prototype.remainder = bnRemainder; +BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; +BigInteger.prototype.modPow = bnModPow; +BigInteger.prototype.modInverse = bnModInverse; +BigInteger.prototype.pow = bnPow; +BigInteger.prototype.gcd = bnGCD; +BigInteger.prototype.isProbablePrime = bnIsProbablePrime; + +//BigInteger interfaces not implemented in jsbn: + +//BigInteger(int signum, byte[] magnitude) +//double doubleValue() +//float floatValue() +//int hashCode() +//long longValue() +//static BigInteger valueOf(long val) diff --git a/node_modules/node-forge/lib/kem.js b/node_modules/node-forge/lib/kem.js new file mode 100644 index 0000000..1967016 --- /dev/null +++ b/node_modules/node-forge/lib/kem.js @@ -0,0 +1,168 @@ +/** + * Javascript implementation of RSA-KEM. + * + * @author Lautaro Cozzani Rodriguez + * @author Dave Longley + * + * Copyright (c) 2014 Lautaro Cozzani + * Copyright (c) 2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./util'); +require('./random'); +require('./jsbn'); + +module.exports = forge.kem = forge.kem || {}; + +var BigInteger = forge.jsbn.BigInteger; + +/** + * The API for the RSA Key Encapsulation Mechanism (RSA-KEM) from ISO 18033-2. + */ +forge.kem.rsa = {}; + +/** + * Creates an RSA KEM API object for generating a secret asymmetric key. + * + * The symmetric key may be generated via a call to 'encrypt', which will + * produce a ciphertext to be transmitted to the recipient and a key to be + * kept secret. The ciphertext is a parameter to be passed to 'decrypt' which + * will produce the same secret key for the recipient to use to decrypt a + * message that was encrypted with the secret key. + * + * @param kdf the KDF API to use (eg: new forge.kem.kdf1()). + * @param options the options to use. + * [prng] a custom crypto-secure pseudo-random number generator to use, + * that must define "getBytesSync". + */ +forge.kem.rsa.create = function(kdf, options) { + options = options || {}; + var prng = options.prng || forge.random; + + var kem = {}; + + /** + * Generates a secret key and its encapsulation. + * + * @param publicKey the RSA public key to encrypt with. + * @param keyLength the length, in bytes, of the secret key to generate. + * + * @return an object with: + * encapsulation: the ciphertext for generating the secret key, as a + * binary-encoded string of bytes. + * key: the secret key to use for encrypting a message. + */ + kem.encrypt = function(publicKey, keyLength) { + // generate a random r where 1 < r < n + var byteLength = Math.ceil(publicKey.n.bitLength() / 8); + var r; + do { + r = new BigInteger( + forge.util.bytesToHex(prng.getBytesSync(byteLength)), + 16).mod(publicKey.n); + } while(r.compareTo(BigInteger.ONE) <= 0); + + // prepend r with zeros + r = forge.util.hexToBytes(r.toString(16)); + var zeros = byteLength - r.length; + if(zeros > 0) { + r = forge.util.fillString(String.fromCharCode(0), zeros) + r; + } + + // encrypt the random + var encapsulation = publicKey.encrypt(r, 'NONE'); + + // generate the secret key + var key = kdf.generate(r, keyLength); + + return {encapsulation: encapsulation, key: key}; + }; + + /** + * Decrypts an encapsulated secret key. + * + * @param privateKey the RSA private key to decrypt with. + * @param encapsulation the ciphertext for generating the secret key, as + * a binary-encoded string of bytes. + * @param keyLength the length, in bytes, of the secret key to generate. + * + * @return the secret key as a binary-encoded string of bytes. + */ + kem.decrypt = function(privateKey, encapsulation, keyLength) { + // decrypt the encapsulation and generate the secret key + var r = privateKey.decrypt(encapsulation, 'NONE'); + return kdf.generate(r, keyLength); + }; + + return kem; +}; + +// TODO: add forge.kem.kdf.create('KDF1', {md: ..., ...}) API? + +/** + * Creates a key derivation API object that implements KDF1 per ISO 18033-2. + * + * @param md the hash API to use. + * @param [digestLength] an optional digest length that must be positive and + * less than or equal to md.digestLength. + * + * @return a KDF1 API object. + */ +forge.kem.kdf1 = function(md, digestLength) { + _createKDF(this, md, 0, digestLength || md.digestLength); +}; + +/** + * Creates a key derivation API object that implements KDF2 per ISO 18033-2. + * + * @param md the hash API to use. + * @param [digestLength] an optional digest length that must be positive and + * less than or equal to md.digestLength. + * + * @return a KDF2 API object. + */ +forge.kem.kdf2 = function(md, digestLength) { + _createKDF(this, md, 1, digestLength || md.digestLength); +}; + +/** + * Creates a KDF1 or KDF2 API object. + * + * @param md the hash API to use. + * @param counterStart the starting index for the counter. + * @param digestLength the digest length to use. + * + * @return the KDF API object. + */ +function _createKDF(kdf, md, counterStart, digestLength) { + /** + * Generate a key of the specified length. + * + * @param x the binary-encoded byte string to generate a key from. + * @param length the number of bytes to generate (the size of the key). + * + * @return the key as a binary-encoded string. + */ + kdf.generate = function(x, length) { + var key = new forge.util.ByteBuffer(); + + // run counter from counterStart to ceil(length / Hash.len) + var k = Math.ceil(length / digestLength) + counterStart; + + var c = new forge.util.ByteBuffer(); + for(var i = counterStart; i < k; ++i) { + // I2OSP(i, 4): convert counter to an octet string of 4 octets + c.putInt32(i); + + // digest 'x' and the counter and add the result to the key + md.start(); + md.update(x + c.getBytes()); + var hash = md.digest(); + key.putBytes(hash.getBytes(digestLength)); + } + + // truncate to the correct key length + key.truncate(key.length() - length); + return key.getBytes(); + }; +} diff --git a/node_modules/node-forge/lib/log.js b/node_modules/node-forge/lib/log.js new file mode 100644 index 0000000..4ef7005 --- /dev/null +++ b/node_modules/node-forge/lib/log.js @@ -0,0 +1,319 @@ +/** + * Cross-browser support for logging in a web application. + * + * @author David I. Lehn + * + * Copyright (c) 2008-2013 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./util'); + +/* LOG API */ +module.exports = forge.log = forge.log || {}; + +/** + * Application logging system. + * + * Each logger level available as it's own function of the form: + * forge.log.level(category, args...) + * The category is an arbitrary string, and the args are the same as + * Firebug's console.log API. By default the call will be output as: + * 'LEVEL [category] , args[1], ...' + * This enables proper % formatting via the first argument. + * Each category is enabled by default but can be enabled or disabled with + * the setCategoryEnabled() function. + */ +// list of known levels +forge.log.levels = [ + 'none', 'error', 'warning', 'info', 'debug', 'verbose', 'max']; +// info on the levels indexed by name: +// index: level index +// name: uppercased display name +var sLevelInfo = {}; +// list of loggers +var sLoggers = []; +/** + * Standard console logger. If no console support is enabled this will + * remain null. Check before using. + */ +var sConsoleLogger = null; + +// logger flags +/** + * Lock the level at the current value. Used in cases where user config may + * set the level such that only critical messages are seen but more verbose + * messages are needed for debugging or other purposes. + */ +forge.log.LEVEL_LOCKED = (1 << 1); +/** + * Always call log function. By default, the logging system will check the + * message level against logger.level before calling the log function. This + * flag allows the function to do its own check. + */ +forge.log.NO_LEVEL_CHECK = (1 << 2); +/** + * Perform message interpolation with the passed arguments. "%" style + * fields in log messages will be replaced by arguments as needed. Some + * loggers, such as Firebug, may do this automatically. The original log + * message will be available as 'message' and the interpolated version will + * be available as 'fullMessage'. + */ +forge.log.INTERPOLATE = (1 << 3); + +// setup each log level +for(var i = 0; i < forge.log.levels.length; ++i) { + var level = forge.log.levels[i]; + sLevelInfo[level] = { + index: i, + name: level.toUpperCase() + }; +} + +/** + * Message logger. Will dispatch a message to registered loggers as needed. + * + * @param message message object + */ +forge.log.logMessage = function(message) { + var messageLevelIndex = sLevelInfo[message.level].index; + for(var i = 0; i < sLoggers.length; ++i) { + var logger = sLoggers[i]; + if(logger.flags & forge.log.NO_LEVEL_CHECK) { + logger.f(message); + } else { + // get logger level + var loggerLevelIndex = sLevelInfo[logger.level].index; + // check level + if(messageLevelIndex <= loggerLevelIndex) { + // message critical enough, call logger + logger.f(logger, message); + } + } + } +}; + +/** + * Sets the 'standard' key on a message object to: + * "LEVEL [category] " + message + * + * @param message a message log object + */ +forge.log.prepareStandard = function(message) { + if(!('standard' in message)) { + message.standard = + sLevelInfo[message.level].name + + //' ' + +message.timestamp + + ' [' + message.category + '] ' + + message.message; + } +}; + +/** + * Sets the 'full' key on a message object to the original message + * interpolated via % formatting with the message arguments. + * + * @param message a message log object. + */ +forge.log.prepareFull = function(message) { + if(!('full' in message)) { + // copy args and insert message at the front + var args = [message.message]; + args = args.concat([] || message['arguments']); + // format the message + message.full = forge.util.format.apply(this, args); + } +}; + +/** + * Applies both preparseStandard() and prepareFull() to a message object and + * store result in 'standardFull'. + * + * @param message a message log object. + */ +forge.log.prepareStandardFull = function(message) { + if(!('standardFull' in message)) { + // FIXME implement 'standardFull' logging + forge.log.prepareStandard(message); + message.standardFull = message.standard; + } +}; + +// create log level functions +if(true) { + // levels for which we want functions + var levels = ['error', 'warning', 'info', 'debug', 'verbose']; + for(var i = 0; i < levels.length; ++i) { + // wrap in a function to ensure proper level var is passed + (function(level) { + // create function for this level + forge.log[level] = function(category, message/*, args...*/) { + // convert arguments to real array, remove category and message + var args = Array.prototype.slice.call(arguments).slice(2); + // create message object + // Note: interpolation and standard formatting is done lazily + var msg = { + timestamp: new Date(), + level: level, + category: category, + message: message, + 'arguments': args + /*standard*/ + /*full*/ + /*fullMessage*/ + }; + // process this message + forge.log.logMessage(msg); + }; + })(levels[i]); + } +} + +/** + * Creates a new logger with specified custom logging function. + * + * The logging function has a signature of: + * function(logger, message) + * logger: current logger + * message: object: + * level: level id + * category: category + * message: string message + * arguments: Array of extra arguments + * fullMessage: interpolated message and arguments if INTERPOLATE flag set + * + * @param logFunction a logging function which takes a log message object + * as a parameter. + * + * @return a logger object. + */ +forge.log.makeLogger = function(logFunction) { + var logger = { + flags: 0, + f: logFunction + }; + forge.log.setLevel(logger, 'none'); + return logger; +}; + +/** + * Sets the current log level on a logger. + * + * @param logger the target logger. + * @param level the new maximum log level as a string. + * + * @return true if set, false if not. + */ +forge.log.setLevel = function(logger, level) { + var rval = false; + if(logger && !(logger.flags & forge.log.LEVEL_LOCKED)) { + for(var i = 0; i < forge.log.levels.length; ++i) { + var aValidLevel = forge.log.levels[i]; + if(level == aValidLevel) { + // set level + logger.level = level; + rval = true; + break; + } + } + } + + return rval; +}; + +/** + * Locks the log level at its current value. + * + * @param logger the target logger. + * @param lock boolean lock value, default to true. + */ +forge.log.lock = function(logger, lock) { + if(typeof lock === 'undefined' || lock) { + logger.flags |= forge.log.LEVEL_LOCKED; + } else { + logger.flags &= ~forge.log.LEVEL_LOCKED; + } +}; + +/** + * Adds a logger. + * + * @param logger the logger object. + */ +forge.log.addLogger = function(logger) { + sLoggers.push(logger); +}; + +// setup the console logger if possible, else create fake console.log +if(typeof(console) !== 'undefined' && 'log' in console) { + var logger; + if(console.error && console.warn && console.info && console.debug) { + // looks like Firebug-style logging is available + // level handlers map + var levelHandlers = { + error: console.error, + warning: console.warn, + info: console.info, + debug: console.debug, + verbose: console.debug + }; + var f = function(logger, message) { + forge.log.prepareStandard(message); + var handler = levelHandlers[message.level]; + // prepend standard message and concat args + var args = [message.standard]; + args = args.concat(message['arguments'].slice()); + // apply to low-level console function + handler.apply(console, args); + }; + logger = forge.log.makeLogger(f); + } else { + // only appear to have basic console.log + var f = function(logger, message) { + forge.log.prepareStandardFull(message); + console.log(message.standardFull); + }; + logger = forge.log.makeLogger(f); + } + forge.log.setLevel(logger, 'debug'); + forge.log.addLogger(logger); + sConsoleLogger = logger; +} else { + // define fake console.log to avoid potential script errors on + // browsers that do not have console logging + console = { + log: function() {} + }; +} + +/* + * Check for logging control query vars in current URL. + * + * console.level= + * Set's the console log level by name. Useful to override defaults and + * allow more verbose logging before a user config is loaded. + * + * console.lock= + * Lock the console log level at whatever level it is set at. This is run + * after console.level is processed. Useful to force a level of verbosity + * that could otherwise be limited by a user config. + */ +if(sConsoleLogger !== null && + typeof window !== 'undefined' && window.location +) { + var query = new URL(window.location.href).searchParams; + if(query.has('console.level')) { + // set with last value + forge.log.setLevel( + sConsoleLogger, query.get('console.level').slice(-1)[0]); + } + if(query.has('console.lock')) { + // set with last value + var lock = query.get('console.lock').slice(-1)[0]; + if(lock == 'true') { + forge.log.lock(sConsoleLogger); + } + } +} + +// provide public access to console logger +forge.log.consoleLogger = sConsoleLogger; diff --git a/node_modules/node-forge/lib/md.all.js b/node_modules/node-forge/lib/md.all.js new file mode 100644 index 0000000..4e0974b --- /dev/null +++ b/node_modules/node-forge/lib/md.all.js @@ -0,0 +1,13 @@ +/** + * Node.js module for all known Forge message digests. + * + * @author Dave Longley + * + * Copyright 2011-2017 Digital Bazaar, Inc. + */ +module.exports = require('./md'); + +require('./md5'); +require('./sha1'); +require('./sha256'); +require('./sha512'); diff --git a/node_modules/node-forge/lib/md.js b/node_modules/node-forge/lib/md.js new file mode 100644 index 0000000..e4a280c --- /dev/null +++ b/node_modules/node-forge/lib/md.js @@ -0,0 +1,11 @@ +/** + * Node.js module for Forge message digests. + * + * @author Dave Longley + * + * Copyright 2011-2017 Digital Bazaar, Inc. + */ +var forge = require('./forge'); + +module.exports = forge.md = forge.md || {}; +forge.md.algorithms = forge.md.algorithms || {}; diff --git a/node_modules/node-forge/lib/md5.js b/node_modules/node-forge/lib/md5.js new file mode 100644 index 0000000..d0ba8f6 --- /dev/null +++ b/node_modules/node-forge/lib/md5.js @@ -0,0 +1,289 @@ +/** + * Message Digest Algorithm 5 with 128-bit digest (MD5) implementation. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./md'); +require('./util'); + +var md5 = module.exports = forge.md5 = forge.md5 || {}; +forge.md.md5 = forge.md.algorithms.md5 = md5; + +/** + * Creates an MD5 message digest object. + * + * @return a message digest object. + */ +md5.create = function() { + // do initialization as necessary + if(!_initialized) { + _init(); + } + + // MD5 state contains four 32-bit integers + var _state = null; + + // input buffer + var _input = forge.util.createBuffer(); + + // used for word storage + var _w = new Array(16); + + // message digest object + var md = { + algorithm: 'md5', + blockLength: 64, + digestLength: 16, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 8 + }; + + /** + * Starts the digest. + * + * @return this digest object. + */ + md.start = function() { + // up to 56-bit message length for convenience + md.messageLength = 0; + + // full message length (set md.messageLength64 for backwards-compatibility) + md.fullMessageLength = md.messageLength64 = []; + var int32s = md.messageLengthSize / 4; + for(var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _state = { + h0: 0x67452301, + h1: 0xEFCDAB89, + h2: 0x98BADCFE, + h3: 0x10325476 + }; + return md; + }; + // start digest automatically for first time + md.start(); + + /** + * Updates the digest with the given message input. The given input can + * treated as raw input (no encoding will be applied) or an encoding of + * 'utf8' maybe given to encode the input using UTF-8. + * + * @param msg the message input to update with. + * @param encoding the encoding to use (default: 'raw', other: 'utf8'). + * + * @return this digest object. + */ + md.update = function(msg, encoding) { + if(encoding === 'utf8') { + msg = forge.util.encodeUtf8(msg); + } + + // update message length + var len = msg.length; + md.messageLength += len; + len = [(len / 0x100000000) >>> 0, len >>> 0]; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = (len[1] / 0x100000000) >>> 0; + } + + // add bytes to input buffer + _input.putBytes(msg); + + // process bytes + _update(_state, _w, _input); + + // compact input buffer every 2K or if empty + if(_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + + return md; + }; + + /** + * Produces the digest. + * + * @return a byte buffer containing the digest value. + */ + md.digest = function() { + /* Note: Here we copy the remaining bytes in the input buffer and + add the appropriate MD5 padding. Then we do the final update + on a copy of the state so that if the user wants to get + intermediate digests they can do so. */ + + /* Determine the number of bytes that must be added to the message + to ensure its length is congruent to 448 mod 512. In other words, + the data to be digested must be a multiple of 512 bits (or 128 bytes). + This data includes the message, some padding, and the length of the + message. Since the length of the message will be encoded as 8 bytes (64 + bits), that means that the last segment of the data must have 56 bytes + (448 bits) of message and padding. Therefore, the length of the message + plus the padding must be congruent to 448 mod 512 because + 512 - 128 = 448. + + In order to fill up the message length it must be filled with + padding that begins with 1 bit followed by all 0 bits. Padding + must *always* be present, so if the message length is already + congruent to 448 mod 512, then 512 padding bits must be added. */ + + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + + // compute remaining size to be digested (include message length size) + var remaining = ( + md.fullMessageLength[md.fullMessageLength.length - 1] + + md.messageLengthSize); + + // add padding for overflow blockSize - overflow + // _padding starts with 1 byte with first bit is set (byte value 128), then + // there may be up to (blockSize - 1) other pad bytes + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + + // serialize message length in bits in little-endian order; since length + // is stored in bytes we multiply by 8 and add carry + var bits, carry = 0; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + bits = md.fullMessageLength[i] * 8 + carry; + carry = (bits / 0x100000000) >>> 0; + finalBlock.putInt32Le(bits >>> 0); + } + + var s2 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3 + }; + _update(s2, _w, finalBlock); + var rval = forge.util.createBuffer(); + rval.putInt32Le(s2.h0); + rval.putInt32Le(s2.h1); + rval.putInt32Le(s2.h2); + rval.putInt32Le(s2.h3); + return rval; + }; + + return md; +}; + +// padding, constant tables for calculating md5 +var _padding = null; +var _g = null; +var _r = null; +var _k = null; +var _initialized = false; + +/** + * Initializes the constant tables. + */ +function _init() { + // create padding + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0x00), 64); + + // g values + _g = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, + 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, + 0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11, 2, 9]; + + // rounds table + _r = [ + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]; + + // get the result of abs(sin(i + 1)) as a 32-bit integer + _k = new Array(64); + for(var i = 0; i < 64; ++i) { + _k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 0x100000000); + } + + // now initialized + _initialized = true; +} + +/** + * Updates an MD5 state with the given byte buffer. + * + * @param s the MD5 state to update. + * @param w the array to use to store words. + * @param bytes the byte buffer to update with. + */ +function _update(s, w, bytes) { + // consume 512 bit (64 byte) chunks + var t, a, b, c, d, f, r, i; + var len = bytes.length(); + while(len >= 64) { + // initialize hash value for this chunk + a = s.h0; + b = s.h1; + c = s.h2; + d = s.h3; + + // round 1 + for(i = 0; i < 16; ++i) { + w[i] = bytes.getInt32Le(); + f = d ^ (b & (c ^ d)); + t = (a + f + _k[i] + w[i]); + r = _r[i]; + a = d; + d = c; + c = b; + b += (t << r) | (t >>> (32 - r)); + } + // round 2 + for(; i < 32; ++i) { + f = c ^ (d & (b ^ c)); + t = (a + f + _k[i] + w[_g[i]]); + r = _r[i]; + a = d; + d = c; + c = b; + b += (t << r) | (t >>> (32 - r)); + } + // round 3 + for(; i < 48; ++i) { + f = b ^ c ^ d; + t = (a + f + _k[i] + w[_g[i]]); + r = _r[i]; + a = d; + d = c; + c = b; + b += (t << r) | (t >>> (32 - r)); + } + // round 4 + for(; i < 64; ++i) { + f = c ^ (b | ~d); + t = (a + f + _k[i] + w[_g[i]]); + r = _r[i]; + a = d; + d = c; + c = b; + b += (t << r) | (t >>> (32 - r)); + } + + // update hash state + s.h0 = (s.h0 + a) | 0; + s.h1 = (s.h1 + b) | 0; + s.h2 = (s.h2 + c) | 0; + s.h3 = (s.h3 + d) | 0; + + len -= 64; + } +} diff --git a/node_modules/node-forge/lib/mgf.js b/node_modules/node-forge/lib/mgf.js new file mode 100644 index 0000000..0223bc3 --- /dev/null +++ b/node_modules/node-forge/lib/mgf.js @@ -0,0 +1,12 @@ +/** + * Node.js module for Forge mask generation functions. + * + * @author Stefan Siegl + * + * Copyright 2012 Stefan Siegl + */ +var forge = require('./forge'); +require('./mgf1'); + +module.exports = forge.mgf = forge.mgf || {}; +forge.mgf.mgf1 = forge.mgf1; diff --git a/node_modules/node-forge/lib/mgf1.js b/node_modules/node-forge/lib/mgf1.js new file mode 100644 index 0000000..25ed1f7 --- /dev/null +++ b/node_modules/node-forge/lib/mgf1.js @@ -0,0 +1,57 @@ +/** + * Javascript implementation of mask generation function MGF1. + * + * @author Stefan Siegl + * @author Dave Longley + * + * Copyright (c) 2012 Stefan Siegl + * Copyright (c) 2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./util'); + +forge.mgf = forge.mgf || {}; +var mgf1 = module.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {}; + +/** + * Creates a MGF1 mask generation function object. + * + * @param md the message digest API to use (eg: forge.md.sha1.create()). + * + * @return a mask generation function object. + */ +mgf1.create = function(md) { + var mgf = { + /** + * Generate mask of specified length. + * + * @param {String} seed The seed for mask generation. + * @param maskLen Number of bytes to generate. + * @return {String} The generated mask. + */ + generate: function(seed, maskLen) { + /* 2. Let T be the empty octet string. */ + var t = new forge.util.ByteBuffer(); + + /* 3. For counter from 0 to ceil(maskLen / hLen), do the following: */ + var len = Math.ceil(maskLen / md.digestLength); + for(var i = 0; i < len; i++) { + /* a. Convert counter to an octet string C of length 4 octets */ + var c = new forge.util.ByteBuffer(); + c.putInt32(i); + + /* b. Concatenate the hash of the seed mgfSeed and C to the octet + * string T: */ + md.start(); + md.update(seed + c.getBytes()); + t.putBuffer(md.digest()); + } + + /* Output the leading maskLen octets of T as the octet string mask. */ + t.truncate(t.length() - maskLen); + return t.getBytes(); + } + }; + + return mgf; +}; diff --git a/node_modules/node-forge/lib/oids.js b/node_modules/node-forge/lib/oids.js new file mode 100644 index 0000000..d1504eb --- /dev/null +++ b/node_modules/node-forge/lib/oids.js @@ -0,0 +1,179 @@ +/** + * Object IDs for ASN.1. + * + * @author Dave Longley + * + * Copyright (c) 2010-2013 Digital Bazaar, Inc. + */ +var forge = require('./forge'); + +forge.pki = forge.pki || {}; +var oids = module.exports = forge.pki.oids = forge.oids = forge.oids || {}; + +// set id to name mapping and name to id mapping +function _IN(id, name) { + oids[id] = name; + oids[name] = id; +} +// set id to name mapping only +function _I_(id, name) { + oids[id] = name; +} + +// algorithm OIDs +_IN('1.2.840.113549.1.1.1', 'rsaEncryption'); +// Note: md2 & md4 not implemented +//_IN('1.2.840.113549.1.1.2', 'md2WithRSAEncryption'); +//_IN('1.2.840.113549.1.1.3', 'md4WithRSAEncryption'); +_IN('1.2.840.113549.1.1.4', 'md5WithRSAEncryption'); +_IN('1.2.840.113549.1.1.5', 'sha1WithRSAEncryption'); +_IN('1.2.840.113549.1.1.7', 'RSAES-OAEP'); +_IN('1.2.840.113549.1.1.8', 'mgf1'); +_IN('1.2.840.113549.1.1.9', 'pSpecified'); +_IN('1.2.840.113549.1.1.10', 'RSASSA-PSS'); +_IN('1.2.840.113549.1.1.11', 'sha256WithRSAEncryption'); +_IN('1.2.840.113549.1.1.12', 'sha384WithRSAEncryption'); +_IN('1.2.840.113549.1.1.13', 'sha512WithRSAEncryption'); +// Edwards-curve Digital Signature Algorithm (EdDSA) Ed25519 +_IN('1.3.101.112', 'EdDSA25519'); + +_IN('1.2.840.10040.4.3', 'dsa-with-sha1'); + +_IN('1.3.14.3.2.7', 'desCBC'); + +_IN('1.3.14.3.2.26', 'sha1'); +// Deprecated equivalent of sha1WithRSAEncryption +_IN('1.3.14.3.2.29', 'sha1WithRSASignature'); +_IN('2.16.840.1.101.3.4.2.1', 'sha256'); +_IN('2.16.840.1.101.3.4.2.2', 'sha384'); +_IN('2.16.840.1.101.3.4.2.3', 'sha512'); +_IN('2.16.840.1.101.3.4.2.4', 'sha224'); +_IN('2.16.840.1.101.3.4.2.5', 'sha512-224'); +_IN('2.16.840.1.101.3.4.2.6', 'sha512-256'); +_IN('1.2.840.113549.2.2', 'md2'); +_IN('1.2.840.113549.2.5', 'md5'); + +// pkcs#7 content types +_IN('1.2.840.113549.1.7.1', 'data'); +_IN('1.2.840.113549.1.7.2', 'signedData'); +_IN('1.2.840.113549.1.7.3', 'envelopedData'); +_IN('1.2.840.113549.1.7.4', 'signedAndEnvelopedData'); +_IN('1.2.840.113549.1.7.5', 'digestedData'); +_IN('1.2.840.113549.1.7.6', 'encryptedData'); + +// pkcs#9 oids +_IN('1.2.840.113549.1.9.1', 'emailAddress'); +_IN('1.2.840.113549.1.9.2', 'unstructuredName'); +_IN('1.2.840.113549.1.9.3', 'contentType'); +_IN('1.2.840.113549.1.9.4', 'messageDigest'); +_IN('1.2.840.113549.1.9.5', 'signingTime'); +_IN('1.2.840.113549.1.9.6', 'counterSignature'); +_IN('1.2.840.113549.1.9.7', 'challengePassword'); +_IN('1.2.840.113549.1.9.8', 'unstructuredAddress'); +_IN('1.2.840.113549.1.9.14', 'extensionRequest'); + +_IN('1.2.840.113549.1.9.20', 'friendlyName'); +_IN('1.2.840.113549.1.9.21', 'localKeyId'); +_IN('1.2.840.113549.1.9.22.1', 'x509Certificate'); + +// pkcs#12 safe bags +_IN('1.2.840.113549.1.12.10.1.1', 'keyBag'); +_IN('1.2.840.113549.1.12.10.1.2', 'pkcs8ShroudedKeyBag'); +_IN('1.2.840.113549.1.12.10.1.3', 'certBag'); +_IN('1.2.840.113549.1.12.10.1.4', 'crlBag'); +_IN('1.2.840.113549.1.12.10.1.5', 'secretBag'); +_IN('1.2.840.113549.1.12.10.1.6', 'safeContentsBag'); + +// password-based-encryption for pkcs#12 +_IN('1.2.840.113549.1.5.13', 'pkcs5PBES2'); +_IN('1.2.840.113549.1.5.12', 'pkcs5PBKDF2'); + +_IN('1.2.840.113549.1.12.1.1', 'pbeWithSHAAnd128BitRC4'); +_IN('1.2.840.113549.1.12.1.2', 'pbeWithSHAAnd40BitRC4'); +_IN('1.2.840.113549.1.12.1.3', 'pbeWithSHAAnd3-KeyTripleDES-CBC'); +_IN('1.2.840.113549.1.12.1.4', 'pbeWithSHAAnd2-KeyTripleDES-CBC'); +_IN('1.2.840.113549.1.12.1.5', 'pbeWithSHAAnd128BitRC2-CBC'); +_IN('1.2.840.113549.1.12.1.6', 'pbewithSHAAnd40BitRC2-CBC'); + +// hmac OIDs +_IN('1.2.840.113549.2.7', 'hmacWithSHA1'); +_IN('1.2.840.113549.2.8', 'hmacWithSHA224'); +_IN('1.2.840.113549.2.9', 'hmacWithSHA256'); +_IN('1.2.840.113549.2.10', 'hmacWithSHA384'); +_IN('1.2.840.113549.2.11', 'hmacWithSHA512'); + +// symmetric key algorithm oids +_IN('1.2.840.113549.3.7', 'des-EDE3-CBC'); +_IN('2.16.840.1.101.3.4.1.2', 'aes128-CBC'); +_IN('2.16.840.1.101.3.4.1.22', 'aes192-CBC'); +_IN('2.16.840.1.101.3.4.1.42', 'aes256-CBC'); + +// certificate issuer/subject OIDs +_IN('2.5.4.3', 'commonName'); +_IN('2.5.4.4', 'surname'); +_IN('2.5.4.5', 'serialNumber'); +_IN('2.5.4.6', 'countryName'); +_IN('2.5.4.7', 'localityName'); +_IN('2.5.4.8', 'stateOrProvinceName'); +_IN('2.5.4.9', 'streetAddress'); +_IN('2.5.4.10', 'organizationName'); +_IN('2.5.4.11', 'organizationalUnitName'); +_IN('2.5.4.12', 'title'); +_IN('2.5.4.13', 'description'); +_IN('2.5.4.15', 'businessCategory'); +_IN('2.5.4.17', 'postalCode'); +_IN('2.5.4.42', 'givenName'); +_IN('1.3.6.1.4.1.311.60.2.1.2', 'jurisdictionOfIncorporationStateOrProvinceName'); +_IN('1.3.6.1.4.1.311.60.2.1.3', 'jurisdictionOfIncorporationCountryName'); + +// X.509 extension OIDs +_IN('2.16.840.1.113730.1.1', 'nsCertType'); +_IN('2.16.840.1.113730.1.13', 'nsComment'); // deprecated in theory; still widely used +_I_('2.5.29.1', 'authorityKeyIdentifier'); // deprecated, use .35 +_I_('2.5.29.2', 'keyAttributes'); // obsolete use .37 or .15 +_I_('2.5.29.3', 'certificatePolicies'); // deprecated, use .32 +_I_('2.5.29.4', 'keyUsageRestriction'); // obsolete use .37 or .15 +_I_('2.5.29.5', 'policyMapping'); // deprecated use .33 +_I_('2.5.29.6', 'subtreesConstraint'); // obsolete use .30 +_I_('2.5.29.7', 'subjectAltName'); // deprecated use .17 +_I_('2.5.29.8', 'issuerAltName'); // deprecated use .18 +_I_('2.5.29.9', 'subjectDirectoryAttributes'); +_I_('2.5.29.10', 'basicConstraints'); // deprecated use .19 +_I_('2.5.29.11', 'nameConstraints'); // deprecated use .30 +_I_('2.5.29.12', 'policyConstraints'); // deprecated use .36 +_I_('2.5.29.13', 'basicConstraints'); // deprecated use .19 +_IN('2.5.29.14', 'subjectKeyIdentifier'); +_IN('2.5.29.15', 'keyUsage'); +_I_('2.5.29.16', 'privateKeyUsagePeriod'); +_IN('2.5.29.17', 'subjectAltName'); +_IN('2.5.29.18', 'issuerAltName'); +_IN('2.5.29.19', 'basicConstraints'); +_I_('2.5.29.20', 'cRLNumber'); +_I_('2.5.29.21', 'cRLReason'); +_I_('2.5.29.22', 'expirationDate'); +_I_('2.5.29.23', 'instructionCode'); +_I_('2.5.29.24', 'invalidityDate'); +_I_('2.5.29.25', 'cRLDistributionPoints'); // deprecated use .31 +_I_('2.5.29.26', 'issuingDistributionPoint'); // deprecated use .28 +_I_('2.5.29.27', 'deltaCRLIndicator'); +_I_('2.5.29.28', 'issuingDistributionPoint'); +_I_('2.5.29.29', 'certificateIssuer'); +_I_('2.5.29.30', 'nameConstraints'); +_IN('2.5.29.31', 'cRLDistributionPoints'); +_IN('2.5.29.32', 'certificatePolicies'); +_I_('2.5.29.33', 'policyMappings'); +_I_('2.5.29.34', 'policyConstraints'); // deprecated use .36 +_IN('2.5.29.35', 'authorityKeyIdentifier'); +_I_('2.5.29.36', 'policyConstraints'); +_IN('2.5.29.37', 'extKeyUsage'); +_I_('2.5.29.46', 'freshestCRL'); +_I_('2.5.29.54', 'inhibitAnyPolicy'); + +// extKeyUsage purposes +_IN('1.3.6.1.4.1.11129.2.4.2', 'timestampList'); +_IN('1.3.6.1.5.5.7.1.1', 'authorityInfoAccess'); +_IN('1.3.6.1.5.5.7.3.1', 'serverAuth'); +_IN('1.3.6.1.5.5.7.3.2', 'clientAuth'); +_IN('1.3.6.1.5.5.7.3.3', 'codeSigning'); +_IN('1.3.6.1.5.5.7.3.4', 'emailProtection'); +_IN('1.3.6.1.5.5.7.3.8', 'timeStamping'); diff --git a/node_modules/node-forge/lib/pbe.js b/node_modules/node-forge/lib/pbe.js new file mode 100644 index 0000000..f3cfa70 --- /dev/null +++ b/node_modules/node-forge/lib/pbe.js @@ -0,0 +1,1023 @@ +/** + * Password-based encryption functions. + * + * @author Dave Longley + * @author Stefan Siegl + * + * Copyright (c) 2010-2013 Digital Bazaar, Inc. + * Copyright (c) 2012 Stefan Siegl + * + * An EncryptedPrivateKeyInfo: + * + * EncryptedPrivateKeyInfo ::= SEQUENCE { + * encryptionAlgorithm EncryptionAlgorithmIdentifier, + * encryptedData EncryptedData } + * + * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier + * + * EncryptedData ::= OCTET STRING + */ +var forge = require('./forge'); +require('./aes'); +require('./asn1'); +require('./des'); +require('./md'); +require('./oids'); +require('./pbkdf2'); +require('./pem'); +require('./random'); +require('./rc2'); +require('./rsa'); +require('./util'); + +if(typeof BigInteger === 'undefined') { + var BigInteger = forge.jsbn.BigInteger; +} + +// shortcut for asn.1 API +var asn1 = forge.asn1; + +/* Password-based encryption implementation. */ +var pki = forge.pki = forge.pki || {}; +module.exports = pki.pbe = forge.pbe = forge.pbe || {}; +var oids = pki.oids; + +// validator for an EncryptedPrivateKeyInfo structure +// Note: Currently only works w/algorithm params +var encryptedPrivateKeyValidator = { + name: 'EncryptedPrivateKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'EncryptedPrivateKeyInfo.encryptionAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'encryptionOid' + }, { + name: 'AlgorithmIdentifier.parameters', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'encryptionParams' + }] + }, { + // encryptedData + name: 'EncryptedPrivateKeyInfo.encryptedData', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'encryptedData' + }] +}; + +// validator for a PBES2Algorithms structure +// Note: Currently only works w/PBKDF2 + AES encryption schemes +var PBES2AlgorithmsValidator = { + name: 'PBES2Algorithms', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'PBES2Algorithms.keyDerivationFunc', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'PBES2Algorithms.keyDerivationFunc.oid', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'kdfOid' + }, { + name: 'PBES2Algorithms.params', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'PBES2Algorithms.params.salt', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'kdfSalt' + }, { + name: 'PBES2Algorithms.params.iterationCount', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'kdfIterationCount' + }, { + name: 'PBES2Algorithms.params.keyLength', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + optional: true, + capture: 'keyLength' + }, { + // prf + name: 'PBES2Algorithms.params.prf', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + value: [{ + name: 'PBES2Algorithms.params.prf.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'prfOid' + }] + }] + }] + }, { + name: 'PBES2Algorithms.encryptionScheme', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'PBES2Algorithms.encryptionScheme.oid', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'encOid' + }, { + name: 'PBES2Algorithms.encryptionScheme.iv', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'encIv' + }] + }] +}; + +var pkcs12PbeParamsValidator = { + name: 'pkcs-12PbeParams', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'pkcs-12PbeParams.salt', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'salt' + }, { + name: 'pkcs-12PbeParams.iterations', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'iterations' + }] +}; + +/** + * Encrypts a ASN.1 PrivateKeyInfo object, producing an EncryptedPrivateKeyInfo. + * + * PBES2Algorithms ALGORITHM-IDENTIFIER ::= + * { {PBES2-params IDENTIFIED BY id-PBES2}, ...} + * + * id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13} + * + * PBES2-params ::= SEQUENCE { + * keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}}, + * encryptionScheme AlgorithmIdentifier {{PBES2-Encs}} + * } + * + * PBES2-KDFs ALGORITHM-IDENTIFIER ::= + * { {PBKDF2-params IDENTIFIED BY id-PBKDF2}, ... } + * + * PBES2-Encs ALGORITHM-IDENTIFIER ::= { ... } + * + * PBKDF2-params ::= SEQUENCE { + * salt CHOICE { + * specified OCTET STRING, + * otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}} + * }, + * iterationCount INTEGER (1..MAX), + * keyLength INTEGER (1..MAX) OPTIONAL, + * prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1 + * } + * + * @param obj the ASN.1 PrivateKeyInfo object. + * @param password the password to encrypt with. + * @param options: + * algorithm the encryption algorithm to use + * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'. + * count the iteration count to use. + * saltSize the salt size to use. + * prfAlgorithm the PRF message digest algorithm to use + * ('sha1', 'sha224', 'sha256', 'sha384', 'sha512') + * + * @return the ASN.1 EncryptedPrivateKeyInfo. + */ +pki.encryptPrivateKeyInfo = function(obj, password, options) { + // set default options + options = options || {}; + options.saltSize = options.saltSize || 8; + options.count = options.count || 2048; + options.algorithm = options.algorithm || 'aes128'; + options.prfAlgorithm = options.prfAlgorithm || 'sha1'; + + // generate PBE params + var salt = forge.random.getBytesSync(options.saltSize); + var count = options.count; + var countBytes = asn1.integerToDer(count); + var dkLen; + var encryptionAlgorithm; + var encryptedData; + if(options.algorithm.indexOf('aes') === 0 || options.algorithm === 'des') { + // do PBES2 + var ivLen, encOid, cipherFn; + switch(options.algorithm) { + case 'aes128': + dkLen = 16; + ivLen = 16; + encOid = oids['aes128-CBC']; + cipherFn = forge.aes.createEncryptionCipher; + break; + case 'aes192': + dkLen = 24; + ivLen = 16; + encOid = oids['aes192-CBC']; + cipherFn = forge.aes.createEncryptionCipher; + break; + case 'aes256': + dkLen = 32; + ivLen = 16; + encOid = oids['aes256-CBC']; + cipherFn = forge.aes.createEncryptionCipher; + break; + case 'des': + dkLen = 8; + ivLen = 8; + encOid = oids['desCBC']; + cipherFn = forge.des.createEncryptionCipher; + break; + default: + var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.'); + error.algorithm = options.algorithm; + throw error; + } + + // get PRF message digest + var prfAlgorithm = 'hmacWith' + options.prfAlgorithm.toUpperCase(); + var md = prfAlgorithmToMessageDigest(prfAlgorithm); + + // encrypt private key using pbe SHA-1 and AES/DES + var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md); + var iv = forge.random.getBytesSync(ivLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(asn1.toDer(obj)); + cipher.finish(); + encryptedData = cipher.output.getBytes(); + + // get PBKDF2-params + var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm); + + encryptionAlgorithm = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(oids['pkcs5PBES2']).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // keyDerivationFunc + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(oids['pkcs5PBKDF2']).getBytes()), + // PBKDF2-params + params + ]), + // encryptionScheme + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(encOid).getBytes()), + // iv + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, iv) + ]) + ]) + ]); + } else if(options.algorithm === '3des') { + // Do PKCS12 PBE + dkLen = 24; + + var saltBytes = new forge.util.ByteBuffer(salt); + var dk = pki.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen); + var iv = pki.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen); + var cipher = forge.des.createEncryptionCipher(dk); + cipher.start(iv); + cipher.update(asn1.toDer(obj)); + cipher.finish(); + encryptedData = cipher.output.getBytes(); + + encryptionAlgorithm = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(oids['pbeWithSHAAnd3-KeyTripleDES-CBC']).getBytes()), + // pkcs-12PbeParams + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // salt + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt), + // iteration count + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + countBytes.getBytes()) + ]) + ]); + } else { + var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.'); + error.algorithm = options.algorithm; + throw error; + } + + // EncryptedPrivateKeyInfo + var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // encryptionAlgorithm + encryptionAlgorithm, + // encryptedData + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, encryptedData) + ]); + return rval; +}; + +/** + * Decrypts a ASN.1 PrivateKeyInfo object. + * + * @param obj the ASN.1 EncryptedPrivateKeyInfo object. + * @param password the password to decrypt with. + * + * @return the ASN.1 PrivateKeyInfo on success, null on failure. + */ +pki.decryptPrivateKeyInfo = function(obj, password) { + var rval = null; + + // get PBE params + var capture = {}; + var errors = []; + if(!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) { + var error = new Error('Cannot read encrypted private key. ' + + 'ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); + error.errors = errors; + throw error; + } + + // get cipher + var oid = asn1.derToOid(capture.encryptionOid); + var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password); + + // get encrypted data + var encrypted = forge.util.createBuffer(capture.encryptedData); + + cipher.update(encrypted); + if(cipher.finish()) { + rval = asn1.fromDer(cipher.output); + } + + return rval; +}; + +/** + * Converts a EncryptedPrivateKeyInfo to PEM format. + * + * @param epki the EncryptedPrivateKeyInfo. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted encrypted private key. + */ +pki.encryptedPrivateKeyToPem = function(epki, maxline) { + // convert to DER, then PEM-encode + var msg = { + type: 'ENCRYPTED PRIVATE KEY', + body: asn1.toDer(epki).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; + +/** + * Converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format. Decryption + * is not performed. + * + * @param pem the EncryptedPrivateKeyInfo in PEM-format. + * + * @return the ASN.1 EncryptedPrivateKeyInfo. + */ +pki.encryptedPrivateKeyFromPem = function(pem) { + var msg = forge.pem.decode(pem)[0]; + + if(msg.type !== 'ENCRYPTED PRIVATE KEY') { + var error = new Error('Could not convert encrypted private key from PEM; ' + + 'PEM header type is "ENCRYPTED PRIVATE KEY".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert encrypted private key from PEM; ' + + 'PEM is encrypted.'); + } + + // convert DER to ASN.1 object + return asn1.fromDer(msg.body); +}; + +/** + * Encrypts an RSA private key. By default, the key will be wrapped in + * a PrivateKeyInfo and encrypted to produce a PKCS#8 EncryptedPrivateKeyInfo. + * This is the standard, preferred way to encrypt a private key. + * + * To produce a non-standard PEM-encrypted private key that uses encapsulated + * headers to indicate the encryption algorithm (old-style non-PKCS#8 OpenSSL + * private key encryption), set the 'legacy' option to true. Note: Using this + * option will cause the iteration count to be forced to 1. + * + * Note: The 'des' algorithm is supported, but it is not considered to be + * secure because it only uses a single 56-bit key. If possible, it is highly + * recommended that a different algorithm be used. + * + * @param rsaKey the RSA key to encrypt. + * @param password the password to use. + * @param options: + * algorithm: the encryption algorithm to use + * ('aes128', 'aes192', 'aes256', '3des', 'des'). + * count: the iteration count to use. + * saltSize: the salt size to use. + * legacy: output an old non-PKCS#8 PEM-encrypted+encapsulated + * headers (DEK-Info) private key. + * + * @return the PEM-encoded ASN.1 EncryptedPrivateKeyInfo. + */ +pki.encryptRsaPrivateKey = function(rsaKey, password, options) { + // standard PKCS#8 + options = options || {}; + if(!options.legacy) { + // encrypt PrivateKeyInfo + var rval = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey)); + rval = pki.encryptPrivateKeyInfo(rval, password, options); + return pki.encryptedPrivateKeyToPem(rval); + } + + // legacy non-PKCS#8 + var algorithm; + var iv; + var dkLen; + var cipherFn; + switch(options.algorithm) { + case 'aes128': + algorithm = 'AES-128-CBC'; + dkLen = 16; + iv = forge.random.getBytesSync(16); + cipherFn = forge.aes.createEncryptionCipher; + break; + case 'aes192': + algorithm = 'AES-192-CBC'; + dkLen = 24; + iv = forge.random.getBytesSync(16); + cipherFn = forge.aes.createEncryptionCipher; + break; + case 'aes256': + algorithm = 'AES-256-CBC'; + dkLen = 32; + iv = forge.random.getBytesSync(16); + cipherFn = forge.aes.createEncryptionCipher; + break; + case '3des': + algorithm = 'DES-EDE3-CBC'; + dkLen = 24; + iv = forge.random.getBytesSync(8); + cipherFn = forge.des.createEncryptionCipher; + break; + case 'des': + algorithm = 'DES-CBC'; + dkLen = 8; + iv = forge.random.getBytesSync(8); + cipherFn = forge.des.createEncryptionCipher; + break; + default: + var error = new Error('Could not encrypt RSA private key; unsupported ' + + 'encryption algorithm "' + options.algorithm + '".'); + error.algorithm = options.algorithm; + throw error; + } + + // encrypt private key using OpenSSL legacy key derivation + var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey))); + cipher.finish(); + + var msg = { + type: 'RSA PRIVATE KEY', + procType: { + version: '4', + type: 'ENCRYPTED' + }, + dekInfo: { + algorithm: algorithm, + parameters: forge.util.bytesToHex(iv).toUpperCase() + }, + body: cipher.output.getBytes() + }; + return forge.pem.encode(msg); +}; + +/** + * Decrypts an RSA private key. + * + * @param pem the PEM-formatted EncryptedPrivateKeyInfo to decrypt. + * @param password the password to use. + * + * @return the RSA key on success, null on failure. + */ +pki.decryptRsaPrivateKey = function(pem, password) { + var rval = null; + + var msg = forge.pem.decode(pem)[0]; + + if(msg.type !== 'ENCRYPTED PRIVATE KEY' && + msg.type !== 'PRIVATE KEY' && + msg.type !== 'RSA PRIVATE KEY') { + var error = new Error('Could not convert private key from PEM; PEM header type ' + + 'is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".'); + error.headerType = error; + throw error; + } + + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + var dkLen; + var cipherFn; + switch(msg.dekInfo.algorithm) { + case 'DES-CBC': + dkLen = 8; + cipherFn = forge.des.createDecryptionCipher; + break; + case 'DES-EDE3-CBC': + dkLen = 24; + cipherFn = forge.des.createDecryptionCipher; + break; + case 'AES-128-CBC': + dkLen = 16; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'AES-192-CBC': + dkLen = 24; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'AES-256-CBC': + dkLen = 32; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'RC2-40-CBC': + dkLen = 5; + cipherFn = function(key) { + return forge.rc2.createDecryptionCipher(key, 40); + }; + break; + case 'RC2-64-CBC': + dkLen = 8; + cipherFn = function(key) { + return forge.rc2.createDecryptionCipher(key, 64); + }; + break; + case 'RC2-128-CBC': + dkLen = 16; + cipherFn = function(key) { + return forge.rc2.createDecryptionCipher(key, 128); + }; + break; + default: + var error = new Error('Could not decrypt private key; unsupported ' + + 'encryption algorithm "' + msg.dekInfo.algorithm + '".'); + error.algorithm = msg.dekInfo.algorithm; + throw error; + } + + // use OpenSSL legacy key derivation + var iv = forge.util.hexToBytes(msg.dekInfo.parameters); + var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(forge.util.createBuffer(msg.body)); + if(cipher.finish()) { + rval = cipher.output.getBytes(); + } else { + return rval; + } + } else { + rval = msg.body; + } + + if(msg.type === 'ENCRYPTED PRIVATE KEY') { + rval = pki.decryptPrivateKeyInfo(asn1.fromDer(rval), password); + } else { + // decryption already performed above + rval = asn1.fromDer(rval); + } + + if(rval !== null) { + rval = pki.privateKeyFromAsn1(rval); + } + + return rval; +}; + +/** + * Derives a PKCS#12 key. + * + * @param password the password to derive the key material from, null or + * undefined for none. + * @param salt the salt, as a ByteBuffer, to use. + * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC). + * @param iter the iteration count. + * @param n the number of bytes to derive from the password. + * @param md the message digest to use, defaults to SHA-1. + * + * @return a ByteBuffer with the bytes derived from the password. + */ +pki.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) { + var j, l; + + if(typeof md === 'undefined' || md === null) { + if(!('sha1' in forge.md)) { + throw new Error('"sha1" hash algorithm unavailable.'); + } + md = forge.md.sha1.create(); + } + + var u = md.digestLength; + var v = md.blockLength; + var result = new forge.util.ByteBuffer(); + + /* Convert password to Unicode byte buffer + trailing 0-byte. */ + var passBuf = new forge.util.ByteBuffer(); + if(password !== null && password !== undefined) { + for(l = 0; l < password.length; l++) { + passBuf.putInt16(password.charCodeAt(l)); + } + passBuf.putInt16(0); + } + + /* Length of salt and password in BYTES. */ + var p = passBuf.length(); + var s = salt.length(); + + /* 1. Construct a string, D (the "diversifier"), by concatenating + v copies of ID. */ + var D = new forge.util.ByteBuffer(); + D.fillWithByte(id, v); + + /* 2. Concatenate copies of the salt together to create a string S of length + v * ceil(s / v) bytes (the final copy of the salt may be truncated + to create S). + Note that if the salt is the empty string, then so is S. */ + var Slen = v * Math.ceil(s / v); + var S = new forge.util.ByteBuffer(); + for(l = 0; l < Slen; l++) { + S.putByte(salt.at(l % s)); + } + + /* 3. Concatenate copies of the password together to create a string P of + length v * ceil(p / v) bytes (the final copy of the password may be + truncated to create P). + Note that if the password is the empty string, then so is P. */ + var Plen = v * Math.ceil(p / v); + var P = new forge.util.ByteBuffer(); + for(l = 0; l < Plen; l++) { + P.putByte(passBuf.at(l % p)); + } + + /* 4. Set I=S||P to be the concatenation of S and P. */ + var I = S; + I.putBuffer(P); + + /* 5. Set c=ceil(n / u). */ + var c = Math.ceil(n / u); + + /* 6. For i=1, 2, ..., c, do the following: */ + for(var i = 1; i <= c; i++) { + /* a) Set Ai=H^r(D||I). (l.e. the rth hash of D||I, H(H(H(...H(D||I)))) */ + var buf = new forge.util.ByteBuffer(); + buf.putBytes(D.bytes()); + buf.putBytes(I.bytes()); + for(var round = 0; round < iter; round++) { + md.start(); + md.update(buf.getBytes()); + buf = md.digest(); + } + + /* b) Concatenate copies of Ai to create a string B of length v bytes (the + final copy of Ai may be truncated to create B). */ + var B = new forge.util.ByteBuffer(); + for(l = 0; l < v; l++) { + B.putByte(buf.at(l % u)); + } + + /* c) Treating I as a concatenation I0, I1, ..., Ik-1 of v-byte blocks, + where k=ceil(s / v) + ceil(p / v), modify I by setting + Ij=(Ij+B+1) mod 2v for each j. */ + var k = Math.ceil(s / v) + Math.ceil(p / v); + var Inew = new forge.util.ByteBuffer(); + for(j = 0; j < k; j++) { + var chunk = new forge.util.ByteBuffer(I.getBytes(v)); + var x = 0x1ff; + for(l = B.length() - 1; l >= 0; l--) { + x = x >> 8; + x += B.at(l) + chunk.at(l); + chunk.setAt(l, x & 0xff); + } + Inew.putBuffer(chunk); + } + I = Inew; + + /* Add Ai to A. */ + result.putBuffer(buf); + } + + result.truncate(result.length() - n); + return result; +}; + +/** + * Get new Forge cipher object instance. + * + * @param oid the OID (in string notation). + * @param params the ASN.1 params object. + * @param password the password to decrypt with. + * + * @return new cipher object instance. + */ +pki.pbe.getCipher = function(oid, params, password) { + switch(oid) { + case pki.oids['pkcs5PBES2']: + return pki.pbe.getCipherForPBES2(oid, params, password); + + case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']: + case pki.oids['pbewithSHAAnd40BitRC2-CBC']: + return pki.pbe.getCipherForPKCS12PBE(oid, params, password); + + default: + var error = new Error('Cannot read encrypted PBE data block. Unsupported OID.'); + error.oid = oid; + error.supportedOids = [ + 'pkcs5PBES2', + 'pbeWithSHAAnd3-KeyTripleDES-CBC', + 'pbewithSHAAnd40BitRC2-CBC' + ]; + throw error; + } +}; + +/** + * Get new Forge cipher object instance according to PBES2 params block. + * + * The returned cipher instance is already started using the IV + * from PBES2 parameter block. + * + * @param oid the PKCS#5 PBKDF2 OID (in string notation). + * @param params the ASN.1 PBES2-params object. + * @param password the password to decrypt with. + * + * @return new cipher object instance. + */ +pki.pbe.getCipherForPBES2 = function(oid, params, password) { + // get PBE params + var capture = {}; + var errors = []; + if(!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) { + var error = new Error('Cannot read password-based-encryption algorithm ' + + 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); + error.errors = errors; + throw error; + } + + // check oids + oid = asn1.derToOid(capture.kdfOid); + if(oid !== pki.oids['pkcs5PBKDF2']) { + var error = new Error('Cannot read encrypted private key. ' + + 'Unsupported key derivation function OID.'); + error.oid = oid; + error.supportedOids = ['pkcs5PBKDF2']; + throw error; + } + oid = asn1.derToOid(capture.encOid); + if(oid !== pki.oids['aes128-CBC'] && + oid !== pki.oids['aes192-CBC'] && + oid !== pki.oids['aes256-CBC'] && + oid !== pki.oids['des-EDE3-CBC'] && + oid !== pki.oids['desCBC']) { + var error = new Error('Cannot read encrypted private key. ' + + 'Unsupported encryption scheme OID.'); + error.oid = oid; + error.supportedOids = [ + 'aes128-CBC', 'aes192-CBC', 'aes256-CBC', 'des-EDE3-CBC', 'desCBC']; + throw error; + } + + // set PBE params + var salt = capture.kdfSalt; + var count = forge.util.createBuffer(capture.kdfIterationCount); + count = count.getInt(count.length() << 3); + var dkLen; + var cipherFn; + switch(pki.oids[oid]) { + case 'aes128-CBC': + dkLen = 16; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'aes192-CBC': + dkLen = 24; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'aes256-CBC': + dkLen = 32; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'des-EDE3-CBC': + dkLen = 24; + cipherFn = forge.des.createDecryptionCipher; + break; + case 'desCBC': + dkLen = 8; + cipherFn = forge.des.createDecryptionCipher; + break; + } + + // get PRF message digest + var md = prfOidToMessageDigest(capture.prfOid); + + // decrypt private key using pbe with chosen PRF and AES/DES + var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md); + var iv = capture.encIv; + var cipher = cipherFn(dk); + cipher.start(iv); + + return cipher; +}; + +/** + * Get new Forge cipher object instance for PKCS#12 PBE. + * + * The returned cipher instance is already started using the key & IV + * derived from the provided password and PKCS#12 PBE salt. + * + * @param oid The PKCS#12 PBE OID (in string notation). + * @param params The ASN.1 PKCS#12 PBE-params object. + * @param password The password to decrypt with. + * + * @return the new cipher object instance. + */ +pki.pbe.getCipherForPKCS12PBE = function(oid, params, password) { + // get PBE params + var capture = {}; + var errors = []; + if(!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) { + var error = new Error('Cannot read password-based-encryption algorithm ' + + 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); + error.errors = errors; + throw error; + } + + var salt = forge.util.createBuffer(capture.salt); + var count = forge.util.createBuffer(capture.iterations); + count = count.getInt(count.length() << 3); + + var dkLen, dIvLen, cipherFn; + switch(oid) { + case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']: + dkLen = 24; + dIvLen = 8; + cipherFn = forge.des.startDecrypting; + break; + + case pki.oids['pbewithSHAAnd40BitRC2-CBC']: + dkLen = 5; + dIvLen = 8; + cipherFn = function(key, iv) { + var cipher = forge.rc2.createDecryptionCipher(key, 40); + cipher.start(iv, null); + return cipher; + }; + break; + + default: + var error = new Error('Cannot read PKCS #12 PBE data block. Unsupported OID.'); + error.oid = oid; + throw error; + } + + // get PRF message digest + var md = prfOidToMessageDigest(capture.prfOid); + var key = pki.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md); + md.start(); + var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md); + + return cipherFn(key, iv); +}; + +/** + * OpenSSL's legacy key derivation function. + * + * See: http://www.openssl.org/docs/crypto/EVP_BytesToKey.html + * + * @param password the password to derive the key from. + * @param salt the salt to use, null for none. + * @param dkLen the number of bytes needed for the derived key. + * @param [options] the options to use: + * [md] an optional message digest object to use. + */ +pki.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) { + if(typeof md === 'undefined' || md === null) { + if(!('md5' in forge.md)) { + throw new Error('"md5" hash algorithm unavailable.'); + } + md = forge.md.md5.create(); + } + if(salt === null) { + salt = ''; + } + var digests = [hash(md, password + salt)]; + for(var length = 16, i = 1; length < dkLen; ++i, length += 16) { + digests.push(hash(md, digests[i - 1] + password + salt)); + } + return digests.join('').substr(0, dkLen); +}; + +function hash(md, bytes) { + return md.start().update(bytes).digest().getBytes(); +} + +function prfOidToMessageDigest(prfOid) { + // get PRF algorithm, default to SHA-1 + var prfAlgorithm; + if(!prfOid) { + prfAlgorithm = 'hmacWithSHA1'; + } else { + prfAlgorithm = pki.oids[asn1.derToOid(prfOid)]; + if(!prfAlgorithm) { + var error = new Error('Unsupported PRF OID.'); + error.oid = prfOid; + error.supported = [ + 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384', + 'hmacWithSHA512']; + throw error; + } + } + return prfAlgorithmToMessageDigest(prfAlgorithm); +} + +function prfAlgorithmToMessageDigest(prfAlgorithm) { + var factory = forge.md; + switch(prfAlgorithm) { + case 'hmacWithSHA224': + factory = forge.md.sha512; + case 'hmacWithSHA1': + case 'hmacWithSHA256': + case 'hmacWithSHA384': + case 'hmacWithSHA512': + prfAlgorithm = prfAlgorithm.substr(8).toLowerCase(); + break; + default: + var error = new Error('Unsupported PRF algorithm.'); + error.algorithm = prfAlgorithm; + error.supported = [ + 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384', + 'hmacWithSHA512']; + throw error; + } + if(!factory || !(prfAlgorithm in factory)) { + throw new Error('Unknown hash algorithm: ' + prfAlgorithm); + } + return factory[prfAlgorithm].create(); +} + +function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) { + var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // salt + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt), + // iteration count + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + countBytes.getBytes()) + ]); + // when PRF algorithm is not SHA-1 default, add key length and PRF algorithm + if(prfAlgorithm !== 'hmacWithSHA1') { + params.value.push( + // key length + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + forge.util.hexToBytes(dkLen.toString(16))), + // AlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ])); + } + return params; +} diff --git a/node_modules/node-forge/lib/pbkdf2.js b/node_modules/node-forge/lib/pbkdf2.js new file mode 100644 index 0000000..714560e --- /dev/null +++ b/node_modules/node-forge/lib/pbkdf2.js @@ -0,0 +1,211 @@ +/** + * Password-Based Key-Derivation Function #2 implementation. + * + * See RFC 2898 for details. + * + * @author Dave Longley + * + * Copyright (c) 2010-2013 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./hmac'); +require('./md'); +require('./util'); + +var pkcs5 = forge.pkcs5 = forge.pkcs5 || {}; + +var crypto; +if(forge.util.isNodejs && !forge.options.usePureJavaScript) { + crypto = require('crypto'); +} + +/** + * Derives a key from a password. + * + * @param p the password as a binary-encoded string of bytes. + * @param s the salt as a binary-encoded string of bytes. + * @param c the iteration count, a positive integer. + * @param dkLen the intended length, in bytes, of the derived key, + * (max: 2^32 - 1) * hash length of the PRF. + * @param [md] the message digest (or algorithm identifier as a string) to use + * in the PRF, defaults to SHA-1. + * @param [callback(err, key)] presence triggers asynchronous version, called + * once the operation completes. + * + * @return the derived key, as a binary-encoded string of bytes, for the + * synchronous version (if no callback is specified). + */ +module.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function( + p, s, c, dkLen, md, callback) { + if(typeof md === 'function') { + callback = md; + md = null; + } + + // use native implementation if possible and not disabled, note that + // some node versions only support SHA-1, others allow digest to be changed + if(forge.util.isNodejs && !forge.options.usePureJavaScript && + crypto.pbkdf2 && (md === null || typeof md !== 'object') && + (crypto.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) { + if(typeof md !== 'string') { + // default prf to SHA-1 + md = 'sha1'; + } + p = Buffer.from(p, 'binary'); + s = Buffer.from(s, 'binary'); + if(!callback) { + if(crypto.pbkdf2Sync.length === 4) { + return crypto.pbkdf2Sync(p, s, c, dkLen).toString('binary'); + } + return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString('binary'); + } + if(crypto.pbkdf2Sync.length === 4) { + return crypto.pbkdf2(p, s, c, dkLen, function(err, key) { + if(err) { + return callback(err); + } + callback(null, key.toString('binary')); + }); + } + return crypto.pbkdf2(p, s, c, dkLen, md, function(err, key) { + if(err) { + return callback(err); + } + callback(null, key.toString('binary')); + }); + } + + if(typeof md === 'undefined' || md === null) { + // default prf to SHA-1 + md = 'sha1'; + } + if(typeof md === 'string') { + if(!(md in forge.md.algorithms)) { + throw new Error('Unknown hash algorithm: ' + md); + } + md = forge.md[md].create(); + } + + var hLen = md.digestLength; + + /* 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and + stop. */ + if(dkLen > (0xFFFFFFFF * hLen)) { + var err = new Error('Derived key is too long.'); + if(callback) { + return callback(err); + } + throw err; + } + + /* 2. Let len be the number of hLen-octet blocks in the derived key, + rounding up, and let r be the number of octets in the last + block: + + len = CEIL(dkLen / hLen), + r = dkLen - (len - 1) * hLen. */ + var len = Math.ceil(dkLen / hLen); + var r = dkLen - (len - 1) * hLen; + + /* 3. For each block of the derived key apply the function F defined + below to the password P, the salt S, the iteration count c, and + the block index to compute the block: + + T_1 = F(P, S, c, 1), + T_2 = F(P, S, c, 2), + ... + T_len = F(P, S, c, len), + + where the function F is defined as the exclusive-or sum of the + first c iterates of the underlying pseudorandom function PRF + applied to the password P and the concatenation of the salt S + and the block index i: + + F(P, S, c, i) = u_1 XOR u_2 XOR ... XOR u_c + + where + + u_1 = PRF(P, S || INT(i)), + u_2 = PRF(P, u_1), + ... + u_c = PRF(P, u_{c-1}). + + Here, INT(i) is a four-octet encoding of the integer i, most + significant octet first. */ + var prf = forge.hmac.create(); + prf.start(md, p); + var dk = ''; + var xor, u_c, u_c1; + + // sync version + if(!callback) { + for(var i = 1; i <= len; ++i) { + // PRF(P, S || INT(i)) (first iteration) + prf.start(null, null); + prf.update(s); + prf.update(forge.util.int32ToBytes(i)); + xor = u_c1 = prf.digest().getBytes(); + + // PRF(P, u_{c-1}) (other iterations) + for(var j = 2; j <= c; ++j) { + prf.start(null, null); + prf.update(u_c1); + u_c = prf.digest().getBytes(); + // F(p, s, c, i) + xor = forge.util.xorBytes(xor, u_c, hLen); + u_c1 = u_c; + } + + /* 4. Concatenate the blocks and extract the first dkLen octets to + produce a derived key DK: + + DK = T_1 || T_2 || ... || T_len<0..r-1> */ + dk += (i < len) ? xor : xor.substr(0, r); + } + /* 5. Output the derived key DK. */ + return dk; + } + + // async version + var i = 1, j; + function outer() { + if(i > len) { + // done + return callback(null, dk); + } + + // PRF(P, S || INT(i)) (first iteration) + prf.start(null, null); + prf.update(s); + prf.update(forge.util.int32ToBytes(i)); + xor = u_c1 = prf.digest().getBytes(); + + // PRF(P, u_{c-1}) (other iterations) + j = 2; + inner(); + } + + function inner() { + if(j <= c) { + prf.start(null, null); + prf.update(u_c1); + u_c = prf.digest().getBytes(); + // F(p, s, c, i) + xor = forge.util.xorBytes(xor, u_c, hLen); + u_c1 = u_c; + ++j; + return forge.util.setImmediate(inner); + } + + /* 4. Concatenate the blocks and extract the first dkLen octets to + produce a derived key DK: + + DK = T_1 || T_2 || ... || T_len<0..r-1> */ + dk += (i < len) ? xor : xor.substr(0, r); + + ++i; + outer(); + } + + outer(); +}; diff --git a/node_modules/node-forge/lib/pem.js b/node_modules/node-forge/lib/pem.js new file mode 100644 index 0000000..1992bc7 --- /dev/null +++ b/node_modules/node-forge/lib/pem.js @@ -0,0 +1,237 @@ +/** + * Javascript implementation of basic PEM (Privacy Enhanced Mail) algorithms. + * + * See: RFC 1421. + * + * @author Dave Longley + * + * Copyright (c) 2013-2014 Digital Bazaar, Inc. + * + * A Forge PEM object has the following fields: + * + * type: identifies the type of message (eg: "RSA PRIVATE KEY"). + * + * procType: identifies the type of processing performed on the message, + * it has two subfields: version and type, eg: 4,ENCRYPTED. + * + * contentDomain: identifies the type of content in the message, typically + * only uses the value: "RFC822". + * + * dekInfo: identifies the message encryption algorithm and mode and includes + * any parameters for the algorithm, it has two subfields: algorithm and + * parameters, eg: DES-CBC,F8143EDE5960C597. + * + * headers: contains all other PEM encapsulated headers -- where order is + * significant (for pairing data like recipient ID + key info). + * + * body: the binary-encoded body. + */ +var forge = require('./forge'); +require('./util'); + +// shortcut for pem API +var pem = module.exports = forge.pem = forge.pem || {}; + +/** + * Encodes (serializes) the given PEM object. + * + * @param msg the PEM message object to encode. + * @param options the options to use: + * maxline the maximum characters per line for the body, (default: 64). + * + * @return the PEM-formatted string. + */ +pem.encode = function(msg, options) { + options = options || {}; + var rval = '-----BEGIN ' + msg.type + '-----\r\n'; + + // encode special headers + var header; + if(msg.procType) { + header = { + name: 'Proc-Type', + values: [String(msg.procType.version), msg.procType.type] + }; + rval += foldHeader(header); + } + if(msg.contentDomain) { + header = {name: 'Content-Domain', values: [msg.contentDomain]}; + rval += foldHeader(header); + } + if(msg.dekInfo) { + header = {name: 'DEK-Info', values: [msg.dekInfo.algorithm]}; + if(msg.dekInfo.parameters) { + header.values.push(msg.dekInfo.parameters); + } + rval += foldHeader(header); + } + + if(msg.headers) { + // encode all other headers + for(var i = 0; i < msg.headers.length; ++i) { + rval += foldHeader(msg.headers[i]); + } + } + + // terminate header + if(msg.procType) { + rval += '\r\n'; + } + + // add body + rval += forge.util.encode64(msg.body, options.maxline || 64) + '\r\n'; + + rval += '-----END ' + msg.type + '-----\r\n'; + return rval; +}; + +/** + * Decodes (deserializes) all PEM messages found in the given string. + * + * @param str the PEM-formatted string to decode. + * + * @return the PEM message objects in an array. + */ +pem.decode = function(str) { + var rval = []; + + // split string into PEM messages (be lenient w/EOF on BEGIN line) + var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g; + var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/; + var rCRLF = /\r?\n/; + var match; + while(true) { + match = rMessage.exec(str); + if(!match) { + break; + } + + // accept "NEW CERTIFICATE REQUEST" as "CERTIFICATE REQUEST" + // https://datatracker.ietf.org/doc/html/rfc7468#section-7 + var type = match[1]; + if(type === 'NEW CERTIFICATE REQUEST') { + type = 'CERTIFICATE REQUEST'; + } + + var msg = { + type: type, + procType: null, + contentDomain: null, + dekInfo: null, + headers: [], + body: forge.util.decode64(match[3]) + }; + rval.push(msg); + + // no headers + if(!match[2]) { + continue; + } + + // parse headers + var lines = match[2].split(rCRLF); + var li = 0; + while(match && li < lines.length) { + // get line, trim any rhs whitespace + var line = lines[li].replace(/\s+$/, ''); + + // RFC2822 unfold any following folded lines + for(var nl = li + 1; nl < lines.length; ++nl) { + var next = lines[nl]; + if(!/\s/.test(next[0])) { + break; + } + line += next; + li = nl; + } + + // parse header + match = line.match(rHeader); + if(match) { + var header = {name: match[1], values: []}; + var values = match[2].split(','); + for(var vi = 0; vi < values.length; ++vi) { + header.values.push(ltrim(values[vi])); + } + + // Proc-Type must be the first header + if(!msg.procType) { + if(header.name !== 'Proc-Type') { + throw new Error('Invalid PEM formatted message. The first ' + + 'encapsulated header must be "Proc-Type".'); + } else if(header.values.length !== 2) { + throw new Error('Invalid PEM formatted message. The "Proc-Type" ' + + 'header must have two subfields.'); + } + msg.procType = {version: values[0], type: values[1]}; + } else if(!msg.contentDomain && header.name === 'Content-Domain') { + // special-case Content-Domain + msg.contentDomain = values[0] || ''; + } else if(!msg.dekInfo && header.name === 'DEK-Info') { + // special-case DEK-Info + if(header.values.length === 0) { + throw new Error('Invalid PEM formatted message. The "DEK-Info" ' + + 'header must have at least one subfield.'); + } + msg.dekInfo = {algorithm: values[0], parameters: values[1] || null}; + } else { + msg.headers.push(header); + } + } + + ++li; + } + + if(msg.procType === 'ENCRYPTED' && !msg.dekInfo) { + throw new Error('Invalid PEM formatted message. The "DEK-Info" ' + + 'header must be present if "Proc-Type" is "ENCRYPTED".'); + } + } + + if(rval.length === 0) { + throw new Error('Invalid PEM formatted message.'); + } + + return rval; +}; + +function foldHeader(header) { + var rval = header.name + ': '; + + // ensure values with CRLF are folded + var values = []; + var insertSpace = function(match, $1) { + return ' ' + $1; + }; + for(var i = 0; i < header.values.length; ++i) { + values.push(header.values[i].replace(/^(\S+\r\n)/, insertSpace)); + } + rval += values.join(',') + '\r\n'; + + // do folding + var length = 0; + var candidate = -1; + for(var i = 0; i < rval.length; ++i, ++length) { + if(length > 65 && candidate !== -1) { + var insert = rval[candidate]; + if(insert === ',') { + ++candidate; + rval = rval.substr(0, candidate) + '\r\n ' + rval.substr(candidate); + } else { + rval = rval.substr(0, candidate) + + '\r\n' + insert + rval.substr(candidate + 1); + } + length = (i - candidate - 1); + candidate = -1; + ++i; + } else if(rval[i] === ' ' || rval[i] === '\t' || rval[i] === ',') { + candidate = i; + } + } + + return rval; +} + +function ltrim(str) { + return str.replace(/^\s+/, ''); +} diff --git a/node_modules/node-forge/lib/pkcs1.js b/node_modules/node-forge/lib/pkcs1.js new file mode 100644 index 0000000..a3af924 --- /dev/null +++ b/node_modules/node-forge/lib/pkcs1.js @@ -0,0 +1,276 @@ +/** + * Partial implementation of PKCS#1 v2.2: RSA-OEAP + * + * Modified but based on the following MIT and BSD licensed code: + * + * https://github.com/kjur/jsjws/blob/master/rsa.js: + * + * The 'jsjws'(JSON Web Signature JavaScript Library) License + * + * Copyright (c) 2012 Kenji Urushima + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * http://webrsa.cvs.sourceforge.net/viewvc/webrsa/Client/RSAES-OAEP.js?content-type=text%2Fplain: + * + * RSAES-OAEP.js + * $Id: RSAES-OAEP.js,v 1.1.1.1 2003/03/19 15:37:20 ellispritchard Exp $ + * JavaScript Implementation of PKCS #1 v2.1 RSA CRYPTOGRAPHY STANDARD (RSA Laboratories, June 14, 2002) + * Copyright (C) Ellis Pritchard, Guardian Unlimited 2003. + * Contact: ellis@nukinetics.com + * Distributed under the BSD License. + * + * Official documentation: http://www.rsa.com/rsalabs/node.asp?id=2125 + * + * @author Evan Jones (http://evanjones.ca/) + * @author Dave Longley + * + * Copyright (c) 2013-2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./util'); +require('./random'); +require('./sha1'); + +// shortcut for PKCS#1 API +var pkcs1 = module.exports = forge.pkcs1 = forge.pkcs1 || {}; + +/** + * Encode the given RSAES-OAEP message (M) using key, with optional label (L) + * and seed. + * + * This method does not perform RSA encryption, it only encodes the message + * using RSAES-OAEP. + * + * @param key the RSA key to use. + * @param message the message to encode. + * @param options the options to use: + * label an optional label to use. + * seed the seed to use. + * md the message digest object to use, undefined for SHA-1. + * mgf1 optional mgf1 parameters: + * md the message digest object to use for MGF1. + * + * @return the encoded message bytes. + */ +pkcs1.encode_rsa_oaep = function(key, message, options) { + // parse arguments + var label; + var seed; + var md; + var mgf1Md; + // legacy args (label, seed, md) + if(typeof options === 'string') { + label = options; + seed = arguments[3] || undefined; + md = arguments[4] || undefined; + } else if(options) { + label = options.label || undefined; + seed = options.seed || undefined; + md = options.md || undefined; + if(options.mgf1 && options.mgf1.md) { + mgf1Md = options.mgf1.md; + } + } + + // default OAEP to SHA-1 message digest + if(!md) { + md = forge.md.sha1.create(); + } else { + md.start(); + } + + // default MGF-1 to same as OAEP + if(!mgf1Md) { + mgf1Md = md; + } + + // compute length in bytes and check output + var keyLength = Math.ceil(key.n.bitLength() / 8); + var maxLength = keyLength - 2 * md.digestLength - 2; + if(message.length > maxLength) { + var error = new Error('RSAES-OAEP input message length is too long.'); + error.length = message.length; + error.maxLength = maxLength; + throw error; + } + + if(!label) { + label = ''; + } + md.update(label, 'raw'); + var lHash = md.digest(); + + var PS = ''; + var PS_length = maxLength - message.length; + for(var i = 0; i < PS_length; i++) { + PS += '\x00'; + } + + var DB = lHash.getBytes() + PS + '\x01' + message; + + if(!seed) { + seed = forge.random.getBytes(md.digestLength); + } else if(seed.length !== md.digestLength) { + var error = new Error('Invalid RSAES-OAEP seed. The seed length must ' + + 'match the digest length.'); + error.seedLength = seed.length; + error.digestLength = md.digestLength; + throw error; + } + + var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); + var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length); + + var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); + var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length); + + // return encoded message + return '\x00' + maskedSeed + maskedDB; +}; + +/** + * Decode the given RSAES-OAEP encoded message (EM) using key, with optional + * label (L). + * + * This method does not perform RSA decryption, it only decodes the message + * using RSAES-OAEP. + * + * @param key the RSA key to use. + * @param em the encoded message to decode. + * @param options the options to use: + * label an optional label to use. + * md the message digest object to use for OAEP, undefined for SHA-1. + * mgf1 optional mgf1 parameters: + * md the message digest object to use for MGF1. + * + * @return the decoded message bytes. + */ +pkcs1.decode_rsa_oaep = function(key, em, options) { + // parse args + var label; + var md; + var mgf1Md; + // legacy args + if(typeof options === 'string') { + label = options; + md = arguments[3] || undefined; + } else if(options) { + label = options.label || undefined; + md = options.md || undefined; + if(options.mgf1 && options.mgf1.md) { + mgf1Md = options.mgf1.md; + } + } + + // compute length in bytes + var keyLength = Math.ceil(key.n.bitLength() / 8); + + if(em.length !== keyLength) { + var error = new Error('RSAES-OAEP encoded message length is invalid.'); + error.length = em.length; + error.expectedLength = keyLength; + throw error; + } + + // default OAEP to SHA-1 message digest + if(md === undefined) { + md = forge.md.sha1.create(); + } else { + md.start(); + } + + // default MGF-1 to same as OAEP + if(!mgf1Md) { + mgf1Md = md; + } + + if(keyLength < 2 * md.digestLength + 2) { + throw new Error('RSAES-OAEP key is too short for the hash function.'); + } + + if(!label) { + label = ''; + } + md.update(label, 'raw'); + var lHash = md.digest().getBytes(); + + // split the message into its parts + var y = em.charAt(0); + var maskedSeed = em.substring(1, md.digestLength + 1); + var maskedDB = em.substring(1 + md.digestLength); + + var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); + var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length); + + var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); + var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length); + + var lHashPrime = db.substring(0, md.digestLength); + + // constant time check that all values match what is expected + var error = (y !== '\x00'); + + // constant time check lHash vs lHashPrime + for(var i = 0; i < md.digestLength; ++i) { + error |= (lHash.charAt(i) !== lHashPrime.charAt(i)); + } + + // "constant time" find the 0x1 byte separating the padding (zeros) from the + // message + // TODO: It must be possible to do this in a better/smarter way? + var in_ps = 1; + var index = md.digestLength; + for(var j = md.digestLength; j < db.length; j++) { + var code = db.charCodeAt(j); + + var is_0 = (code & 0x1) ^ 0x1; + + // non-zero if not 0 or 1 in the ps section + var error_mask = in_ps ? 0xfffe : 0x0000; + error |= (code & error_mask); + + // latch in_ps to zero after we find 0x1 + in_ps = in_ps & is_0; + index += in_ps; + } + + if(error || db.charCodeAt(index) !== 0x1) { + throw new Error('Invalid RSAES-OAEP padding.'); + } + + return db.substring(index + 1); +}; + +function rsa_mgf1(seed, maskLength, hash) { + // default to SHA-1 message digest + if(!hash) { + hash = forge.md.sha1.create(); + } + var t = ''; + var count = Math.ceil(maskLength / hash.digestLength); + for(var i = 0; i < count; ++i) { + var c = String.fromCharCode( + (i >> 24) & 0xFF, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF); + hash.start(); + hash.update(seed + c); + t += hash.digest().getBytes(); + } + return t.substring(0, maskLength); +} diff --git a/node_modules/node-forge/lib/pkcs12.js b/node_modules/node-forge/lib/pkcs12.js new file mode 100644 index 0000000..c184229 --- /dev/null +++ b/node_modules/node-forge/lib/pkcs12.js @@ -0,0 +1,1078 @@ +/** + * Javascript implementation of PKCS#12. + * + * @author Dave Longley + * @author Stefan Siegl + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + * Copyright (c) 2012 Stefan Siegl + * + * The ASN.1 representation of PKCS#12 is as follows + * (see ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12-tc1.pdf for details) + * + * PFX ::= SEQUENCE { + * version INTEGER {v3(3)}(v3,...), + * authSafe ContentInfo, + * macData MacData OPTIONAL + * } + * + * MacData ::= SEQUENCE { + * mac DigestInfo, + * macSalt OCTET STRING, + * iterations INTEGER DEFAULT 1 + * } + * Note: The iterations default is for historical reasons and its use is + * deprecated. A higher value, like 1024, is recommended. + * + * DigestInfo is defined in PKCS#7 as follows: + * + * DigestInfo ::= SEQUENCE { + * digestAlgorithm DigestAlgorithmIdentifier, + * digest Digest + * } + * + * DigestAlgorithmIdentifier ::= AlgorithmIdentifier + * + * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters + * for the algorithm, if any. In the case of SHA1 there is none. + * + * AlgorithmIdentifer ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters ANY DEFINED BY algorithm OPTIONAL + * } + * + * Digest ::= OCTET STRING + * + * + * ContentInfo ::= SEQUENCE { + * contentType ContentType, + * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL + * } + * + * ContentType ::= OBJECT IDENTIFIER + * + * AuthenticatedSafe ::= SEQUENCE OF ContentInfo + * -- Data if unencrypted + * -- EncryptedData if password-encrypted + * -- EnvelopedData if public key-encrypted + * + * + * SafeContents ::= SEQUENCE OF SafeBag + * + * SafeBag ::= SEQUENCE { + * bagId BAG-TYPE.&id ({PKCS12BagSet}) + * bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}), + * bagAttributes SET OF PKCS12Attribute OPTIONAL + * } + * + * PKCS12Attribute ::= SEQUENCE { + * attrId ATTRIBUTE.&id ({PKCS12AttrSet}), + * attrValues SET OF ATTRIBUTE.&Type ({PKCS12AttrSet}{@attrId}) + * } -- This type is compatible with the X.500 type 'Attribute' + * + * PKCS12AttrSet ATTRIBUTE ::= { + * friendlyName | -- from PKCS #9 + * localKeyId, -- from PKCS #9 + * ... -- Other attributes are allowed + * } + * + * CertBag ::= SEQUENCE { + * certId BAG-TYPE.&id ({CertTypes}), + * certValue [0] EXPLICIT BAG-TYPE.&Type ({CertTypes}{@certId}) + * } + * + * x509Certificate BAG-TYPE ::= {OCTET STRING IDENTIFIED BY {certTypes 1}} + * -- DER-encoded X.509 certificate stored in OCTET STRING + * + * sdsiCertificate BAG-TYPE ::= {IA5String IDENTIFIED BY {certTypes 2}} + * -- Base64-encoded SDSI certificate stored in IA5String + * + * CertTypes BAG-TYPE ::= { + * x509Certificate | + * sdsiCertificate, + * ... -- For future extensions + * } + */ +var forge = require('./forge'); +require('./asn1'); +require('./hmac'); +require('./oids'); +require('./pkcs7asn1'); +require('./pbe'); +require('./random'); +require('./rsa'); +require('./sha1'); +require('./util'); +require('./x509'); + +// shortcut for asn.1 & PKI API +var asn1 = forge.asn1; +var pki = forge.pki; + +// shortcut for PKCS#12 API +var p12 = module.exports = forge.pkcs12 = forge.pkcs12 || {}; + +var contentInfoValidator = { + name: 'ContentInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, // a ContentInfo + constructed: true, + value: [{ + name: 'ContentInfo.contentType', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'contentType' + }, { + name: 'ContentInfo.content', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + constructed: true, + captureAsn1: 'content' + }] +}; + +var pfxValidator = { + name: 'PFX', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'PFX.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'version' + }, + contentInfoValidator, { + name: 'PFX.macData', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: 'mac', + value: [{ + name: 'PFX.macData.mac', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, // DigestInfo + constructed: true, + value: [{ + name: 'PFX.macData.mac.digestAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, // DigestAlgorithmIdentifier + constructed: true, + value: [{ + name: 'PFX.macData.mac.digestAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'macAlgorithm' + }, { + name: 'PFX.macData.mac.digestAlgorithm.parameters', + optional: true, + tagClass: asn1.Class.UNIVERSAL, + captureAsn1: 'macAlgorithmParameters' + }] + }, { + name: 'PFX.macData.mac.digest', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'macDigest' + }] + }, { + name: 'PFX.macData.macSalt', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'macSalt' + }, { + name: 'PFX.macData.iterations', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + optional: true, + capture: 'macIterations' + }] + }] +}; + +var safeBagValidator = { + name: 'SafeBag', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'SafeBag.bagId', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'bagId' + }, { + name: 'SafeBag.bagValue', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + constructed: true, + captureAsn1: 'bagValue' + }, { + name: 'SafeBag.bagAttributes', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + optional: true, + capture: 'bagAttributes' + }] +}; + +var attributeValidator = { + name: 'Attribute', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'Attribute.attrId', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'oid' + }, { + name: 'Attribute.attrValues', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + capture: 'values' + }] +}; + +var certBagValidator = { + name: 'CertBag', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'CertBag.certId', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'certId' + }, { + name: 'CertBag.certValue', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + constructed: true, + /* So far we only support X.509 certificates (which are wrapped in + an OCTET STRING, hence hard code that here). */ + value: [{ + name: 'CertBag.certValue[0]', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.OCTETSTRING, + constructed: false, + capture: 'cert' + }] + }] +}; + +/** + * Search SafeContents structure for bags with matching attributes. + * + * The search can optionally be narrowed by a certain bag type. + * + * @param safeContents the SafeContents structure to search in. + * @param attrName the name of the attribute to compare against. + * @param attrValue the attribute value to search for. + * @param [bagType] bag type to narrow search by. + * + * @return an array of matching bags. + */ +function _getBagsByAttribute(safeContents, attrName, attrValue, bagType) { + var result = []; + + for(var i = 0; i < safeContents.length; i++) { + for(var j = 0; j < safeContents[i].safeBags.length; j++) { + var bag = safeContents[i].safeBags[j]; + if(bagType !== undefined && bag.type !== bagType) { + continue; + } + // only filter by bag type, no attribute specified + if(attrName === null) { + result.push(bag); + continue; + } + if(bag.attributes[attrName] !== undefined && + bag.attributes[attrName].indexOf(attrValue) >= 0) { + result.push(bag); + } + } + } + + return result; +} + +/** + * Converts a PKCS#12 PFX in ASN.1 notation into a PFX object. + * + * @param obj The PKCS#12 PFX in ASN.1 notation. + * @param strict true to use strict DER decoding, false not to (default: true). + * @param {String} password Password to decrypt with (optional). + * + * @return PKCS#12 PFX object. + */ +p12.pkcs12FromAsn1 = function(obj, strict, password) { + // handle args + if(typeof strict === 'string') { + password = strict; + strict = true; + } else if(strict === undefined) { + strict = true; + } + + // validate PFX and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(obj, pfxValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#12 PFX. ' + + 'ASN.1 object is not an PKCS#12 PFX.'); + error.errors = error; + throw error; + } + + var pfx = { + version: capture.version.charCodeAt(0), + safeContents: [], + + /** + * Gets bags with matching attributes. + * + * @param filter the attributes to filter by: + * [localKeyId] the localKeyId to search for. + * [localKeyIdHex] the localKeyId in hex to search for. + * [friendlyName] the friendly name to search for. + * [bagType] bag type to narrow each attribute search by. + * + * @return a map of attribute type to an array of matching bags or, if no + * attribute was given but a bag type, the map key will be the + * bag type. + */ + getBags: function(filter) { + var rval = {}; + + var localKeyId; + if('localKeyId' in filter) { + localKeyId = filter.localKeyId; + } else if('localKeyIdHex' in filter) { + localKeyId = forge.util.hexToBytes(filter.localKeyIdHex); + } + + // filter on bagType only + if(localKeyId === undefined && !('friendlyName' in filter) && + 'bagType' in filter) { + rval[filter.bagType] = _getBagsByAttribute( + pfx.safeContents, null, null, filter.bagType); + } + + if(localKeyId !== undefined) { + rval.localKeyId = _getBagsByAttribute( + pfx.safeContents, 'localKeyId', + localKeyId, filter.bagType); + } + if('friendlyName' in filter) { + rval.friendlyName = _getBagsByAttribute( + pfx.safeContents, 'friendlyName', + filter.friendlyName, filter.bagType); + } + + return rval; + }, + + /** + * DEPRECATED: use getBags() instead. + * + * Get bags with matching friendlyName attribute. + * + * @param friendlyName the friendly name to search for. + * @param [bagType] bag type to narrow search by. + * + * @return an array of bags with matching friendlyName attribute. + */ + getBagsByFriendlyName: function(friendlyName, bagType) { + return _getBagsByAttribute( + pfx.safeContents, 'friendlyName', friendlyName, bagType); + }, + + /** + * DEPRECATED: use getBags() instead. + * + * Get bags with matching localKeyId attribute. + * + * @param localKeyId the localKeyId to search for. + * @param [bagType] bag type to narrow search by. + * + * @return an array of bags with matching localKeyId attribute. + */ + getBagsByLocalKeyId: function(localKeyId, bagType) { + return _getBagsByAttribute( + pfx.safeContents, 'localKeyId', localKeyId, bagType); + } + }; + + if(capture.version.charCodeAt(0) !== 3) { + var error = new Error('PKCS#12 PFX of version other than 3 not supported.'); + error.version = capture.version.charCodeAt(0); + throw error; + } + + if(asn1.derToOid(capture.contentType) !== pki.oids.data) { + var error = new Error('Only PKCS#12 PFX in password integrity mode supported.'); + error.oid = asn1.derToOid(capture.contentType); + throw error; + } + + var data = capture.content.value[0]; + if(data.tagClass !== asn1.Class.UNIVERSAL || + data.type !== asn1.Type.OCTETSTRING) { + throw new Error('PKCS#12 authSafe content data is not an OCTET STRING.'); + } + data = _decodePkcs7Data(data); + + // check for MAC + if(capture.mac) { + var md = null; + var macKeyBytes = 0; + var macAlgorithm = asn1.derToOid(capture.macAlgorithm); + switch(macAlgorithm) { + case pki.oids.sha1: + md = forge.md.sha1.create(); + macKeyBytes = 20; + break; + case pki.oids.sha256: + md = forge.md.sha256.create(); + macKeyBytes = 32; + break; + case pki.oids.sha384: + md = forge.md.sha384.create(); + macKeyBytes = 48; + break; + case pki.oids.sha512: + md = forge.md.sha512.create(); + macKeyBytes = 64; + break; + case pki.oids.md5: + md = forge.md.md5.create(); + macKeyBytes = 16; + break; + } + if(md === null) { + throw new Error('PKCS#12 uses unsupported MAC algorithm: ' + macAlgorithm); + } + + // verify MAC (iterations default to 1) + var macSalt = new forge.util.ByteBuffer(capture.macSalt); + var macIterations = (('macIterations' in capture) ? + parseInt(forge.util.bytesToHex(capture.macIterations), 16) : 1); + var macKey = p12.generateKey( + password, macSalt, 3, macIterations, macKeyBytes, md); + var mac = forge.hmac.create(); + mac.start(md, macKey); + mac.update(data.value); + var macValue = mac.getMac(); + if(macValue.getBytes() !== capture.macDigest) { + throw new Error('PKCS#12 MAC could not be verified. Invalid password?'); + } + } else if(Array.isArray(obj.value) && obj.value.length > 2) { + /* This is pfx data that should have mac and verify macDigest */ + throw new Error('Invalid PKCS#12. macData field present but MAC was not validated.'); + } + + _decodeAuthenticatedSafe(pfx, data.value, strict, password); + return pfx; +}; + +/** + * Decodes PKCS#7 Data. PKCS#7 (RFC 2315) defines "Data" as an OCTET STRING, + * but it is sometimes an OCTET STRING that is composed/constructed of chunks, + * each its own OCTET STRING. This is BER-encoding vs. DER-encoding. This + * function transforms this corner-case into the usual simple, + * non-composed/constructed OCTET STRING. + * + * This function may be moved to ASN.1 at some point to better deal with + * more BER-encoding issues, should they arise. + * + * @param data the ASN.1 Data object to transform. + */ +function _decodePkcs7Data(data) { + // handle special case of "chunked" data content: an octet string composed + // of other octet strings + if(data.composed || data.constructed) { + var value = forge.util.createBuffer(); + for(var i = 0; i < data.value.length; ++i) { + value.putBytes(data.value[i].value); + } + data.composed = data.constructed = false; + data.value = value.getBytes(); + } + return data; +} + +/** + * Decode PKCS#12 AuthenticatedSafe (BER encoded) into PFX object. + * + * The AuthenticatedSafe is a BER-encoded SEQUENCE OF ContentInfo. + * + * @param pfx The PKCS#12 PFX object to fill. + * @param {String} authSafe BER-encoded AuthenticatedSafe. + * @param strict true to use strict DER decoding, false not to. + * @param {String} password Password to decrypt with (optional). + */ +function _decodeAuthenticatedSafe(pfx, authSafe, strict, password) { + authSafe = asn1.fromDer(authSafe, strict); /* actually it's BER encoded */ + + if(authSafe.tagClass !== asn1.Class.UNIVERSAL || + authSafe.type !== asn1.Type.SEQUENCE || + authSafe.constructed !== true) { + throw new Error('PKCS#12 AuthenticatedSafe expected to be a ' + + 'SEQUENCE OF ContentInfo'); + } + + for(var i = 0; i < authSafe.value.length; i++) { + var contentInfo = authSafe.value[i]; + + // validate contentInfo and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(contentInfo, contentInfoValidator, capture, errors)) { + var error = new Error('Cannot read ContentInfo.'); + error.errors = errors; + throw error; + } + + var obj = { + encrypted: false + }; + var safeContents = null; + var data = capture.content.value[0]; + switch(asn1.derToOid(capture.contentType)) { + case pki.oids.data: + if(data.tagClass !== asn1.Class.UNIVERSAL || + data.type !== asn1.Type.OCTETSTRING) { + throw new Error('PKCS#12 SafeContents Data is not an OCTET STRING.'); + } + safeContents = _decodePkcs7Data(data).value; + break; + case pki.oids.encryptedData: + safeContents = _decryptSafeContents(data, password); + obj.encrypted = true; + break; + default: + var error = new Error('Unsupported PKCS#12 contentType.'); + error.contentType = asn1.derToOid(capture.contentType); + throw error; + } + + obj.safeBags = _decodeSafeContents(safeContents, strict, password); + pfx.safeContents.push(obj); + } +} + +/** + * Decrypt PKCS#7 EncryptedData structure. + * + * @param data ASN.1 encoded EncryptedContentInfo object. + * @param password The user-provided password. + * + * @return The decrypted SafeContents (ASN.1 object). + */ +function _decryptSafeContents(data, password) { + var capture = {}; + var errors = []; + if(!asn1.validate( + data, forge.pkcs7.asn1.encryptedDataValidator, capture, errors)) { + var error = new Error('Cannot read EncryptedContentInfo.'); + error.errors = errors; + throw error; + } + + var oid = asn1.derToOid(capture.contentType); + if(oid !== pki.oids.data) { + var error = new Error( + 'PKCS#12 EncryptedContentInfo ContentType is not Data.'); + error.oid = oid; + throw error; + } + + // get cipher + oid = asn1.derToOid(capture.encAlgorithm); + var cipher = pki.pbe.getCipher(oid, capture.encParameter, password); + + // get encrypted data + var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1); + var encrypted = forge.util.createBuffer(encryptedContentAsn1.value); + + cipher.update(encrypted); + if(!cipher.finish()) { + throw new Error('Failed to decrypt PKCS#12 SafeContents.'); + } + + return cipher.output.getBytes(); +} + +/** + * Decode PKCS#12 SafeContents (BER-encoded) into array of Bag objects. + * + * The safeContents is a BER-encoded SEQUENCE OF SafeBag. + * + * @param {String} safeContents BER-encoded safeContents. + * @param strict true to use strict DER decoding, false not to. + * @param {String} password Password to decrypt with (optional). + * + * @return {Array} Array of Bag objects. + */ +function _decodeSafeContents(safeContents, strict, password) { + // if strict and no safe contents, return empty safes + if(!strict && safeContents.length === 0) { + return []; + } + + // actually it's BER-encoded + safeContents = asn1.fromDer(safeContents, strict); + + if(safeContents.tagClass !== asn1.Class.UNIVERSAL || + safeContents.type !== asn1.Type.SEQUENCE || + safeContents.constructed !== true) { + throw new Error( + 'PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.'); + } + + var res = []; + for(var i = 0; i < safeContents.value.length; i++) { + var safeBag = safeContents.value[i]; + + // validate SafeBag and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(safeBag, safeBagValidator, capture, errors)) { + var error = new Error('Cannot read SafeBag.'); + error.errors = errors; + throw error; + } + + /* Create bag object and push to result array. */ + var bag = { + type: asn1.derToOid(capture.bagId), + attributes: _decodeBagAttributes(capture.bagAttributes) + }; + res.push(bag); + + var validator, decoder; + var bagAsn1 = capture.bagValue.value[0]; + switch(bag.type) { + case pki.oids.pkcs8ShroudedKeyBag: + /* bagAsn1 has a EncryptedPrivateKeyInfo, which we need to decrypt. + Afterwards we can handle it like a keyBag, + which is a PrivateKeyInfo. */ + bagAsn1 = pki.decryptPrivateKeyInfo(bagAsn1, password); + if(bagAsn1 === null) { + throw new Error( + 'Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?'); + } + + /* fall through */ + case pki.oids.keyBag: + /* A PKCS#12 keyBag is a simple PrivateKeyInfo as understood by our + PKI module, hence we don't have to do validation/capturing here, + just pass what we already got. */ + try { + bag.key = pki.privateKeyFromAsn1(bagAsn1); + } catch(e) { + // ignore unknown key type, pass asn1 value + bag.key = null; + bag.asn1 = bagAsn1; + } + continue; /* Nothing more to do. */ + + case pki.oids.certBag: + /* A PKCS#12 certBag can wrap both X.509 and sdsi certificates. + Therefore put the SafeBag content through another validator to + capture the fields. Afterwards check & store the results. */ + validator = certBagValidator; + decoder = function() { + if(asn1.derToOid(capture.certId) !== pki.oids.x509Certificate) { + var error = new Error( + 'Unsupported certificate type, only X.509 supported.'); + error.oid = asn1.derToOid(capture.certId); + throw error; + } + + // true=produce cert hash + var certAsn1 = asn1.fromDer(capture.cert, strict); + try { + bag.cert = pki.certificateFromAsn1(certAsn1, true); + } catch(e) { + // ignore unknown cert type, pass asn1 value + bag.cert = null; + bag.asn1 = certAsn1; + } + }; + break; + + default: + var error = new Error('Unsupported PKCS#12 SafeBag type.'); + error.oid = bag.type; + throw error; + } + + /* Validate SafeBag value (i.e. CertBag, etc.) and capture data if needed. */ + if(validator !== undefined && + !asn1.validate(bagAsn1, validator, capture, errors)) { + var error = new Error('Cannot read PKCS#12 ' + validator.name); + error.errors = errors; + throw error; + } + + /* Call decoder function from above to store the results. */ + decoder(); + } + + return res; +} + +/** + * Decode PKCS#12 SET OF PKCS12Attribute into JavaScript object. + * + * @param attributes SET OF PKCS12Attribute (ASN.1 object). + * + * @return the decoded attributes. + */ +function _decodeBagAttributes(attributes) { + var decodedAttrs = {}; + + if(attributes !== undefined) { + for(var i = 0; i < attributes.length; ++i) { + var capture = {}; + var errors = []; + if(!asn1.validate(attributes[i], attributeValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#12 BagAttribute.'); + error.errors = errors; + throw error; + } + + var oid = asn1.derToOid(capture.oid); + if(pki.oids[oid] === undefined) { + // unsupported attribute type, ignore. + continue; + } + + decodedAttrs[pki.oids[oid]] = []; + for(var j = 0; j < capture.values.length; ++j) { + decodedAttrs[pki.oids[oid]].push(capture.values[j].value); + } + } + } + + return decodedAttrs; +} + +/** + * Wraps a private key and certificate in a PKCS#12 PFX wrapper. If a + * password is provided then the private key will be encrypted. + * + * An entire certificate chain may also be included. To do this, pass + * an array for the "cert" parameter where the first certificate is + * the one that is paired with the private key and each subsequent one + * verifies the previous one. The certificates may be in PEM format or + * have been already parsed by Forge. + * + * @todo implement password-based-encryption for the whole package + * + * @param key the private key. + * @param cert the certificate (may be an array of certificates in order + * to specify a certificate chain). + * @param password the password to use, null for none. + * @param options: + * algorithm the encryption algorithm to use + * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'. + * count the iteration count to use. + * saltSize the salt size to use. + * useMac true to include a MAC, false not to, defaults to true. + * localKeyId the local key ID to use, in hex. + * friendlyName the friendly name to use. + * generateLocalKeyId true to generate a random local key ID, + * false not to, defaults to true. + * + * @return the PKCS#12 PFX ASN.1 object. + */ +p12.toPkcs12Asn1 = function(key, cert, password, options) { + // set default options + options = options || {}; + options.saltSize = options.saltSize || 8; + options.count = options.count || 2048; + options.algorithm = options.algorithm || options.encAlgorithm || 'aes128'; + if(!('useMac' in options)) { + options.useMac = true; + } + if(!('localKeyId' in options)) { + options.localKeyId = null; + } + if(!('generateLocalKeyId' in options)) { + options.generateLocalKeyId = true; + } + + var localKeyId = options.localKeyId; + var bagAttrs; + if(localKeyId !== null) { + localKeyId = forge.util.hexToBytes(localKeyId); + } else if(options.generateLocalKeyId) { + // use SHA-1 of paired cert, if available + if(cert) { + var pairedCert = forge.util.isArray(cert) ? cert[0] : cert; + if(typeof pairedCert === 'string') { + pairedCert = pki.certificateFromPem(pairedCert); + } + var sha1 = forge.md.sha1.create(); + sha1.update(asn1.toDer(pki.certificateToAsn1(pairedCert)).getBytes()); + localKeyId = sha1.digest().getBytes(); + } else { + // FIXME: consider using SHA-1 of public key (which can be generated + // from private key components), see: cert.generateSubjectKeyIdentifier + // generate random bytes + localKeyId = forge.random.getBytes(20); + } + } + + var attrs = []; + if(localKeyId !== null) { + attrs.push( + // localKeyID + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // attrId + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.localKeyId).getBytes()), + // attrValues + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + localKeyId) + ]) + ])); + } + if('friendlyName' in options) { + attrs.push( + // friendlyName + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // attrId + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.friendlyName).getBytes()), + // attrValues + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BMPSTRING, false, + options.friendlyName) + ]) + ])); + } + + if(attrs.length > 0) { + bagAttrs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, attrs); + } + + // collect contents for AuthenticatedSafe + var contents = []; + + // create safe bag(s) for certificate chain + var chain = []; + if(cert !== null) { + if(forge.util.isArray(cert)) { + chain = cert; + } else { + chain = [cert]; + } + } + + var certSafeBags = []; + for(var i = 0; i < chain.length; ++i) { + // convert cert from PEM as necessary + cert = chain[i]; + if(typeof cert === 'string') { + cert = pki.certificateFromPem(cert); + } + + // SafeBag + var certBagAttrs = (i === 0) ? bagAttrs : undefined; + var certAsn1 = pki.certificateToAsn1(cert); + var certSafeBag = + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // bagId + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.certBag).getBytes()), + // bagValue + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // CertBag + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // certId + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.x509Certificate).getBytes()), + // certValue (x509Certificate) + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + asn1.toDer(certAsn1).getBytes()) + ])])]), + // bagAttributes (OPTIONAL) + certBagAttrs + ]); + certSafeBags.push(certSafeBag); + } + + if(certSafeBags.length > 0) { + // SafeContents + var certSafeContents = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, certSafeBags); + + // ContentInfo + var certCI = + // PKCS#7 ContentInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // contentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + // OID for the content type is 'data' + asn1.oidToDer(pki.oids.data).getBytes()), + // content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + asn1.toDer(certSafeContents).getBytes()) + ]) + ]); + contents.push(certCI); + } + + // create safe contents for private key + var keyBag = null; + if(key !== null) { + // SafeBag + var pkAsn1 = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key)); + if(password === null) { + // no encryption + keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // bagId + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.keyBag).getBytes()), + // bagValue + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // PrivateKeyInfo + pkAsn1 + ]), + // bagAttributes (OPTIONAL) + bagAttrs + ]); + } else { + // encrypted PrivateKeyInfo + keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // bagId + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes()), + // bagValue + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // EncryptedPrivateKeyInfo + pki.encryptPrivateKeyInfo(pkAsn1, password, options) + ]), + // bagAttributes (OPTIONAL) + bagAttrs + ]); + } + + // SafeContents + var keySafeContents = + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [keyBag]); + + // ContentInfo + var keyCI = + // PKCS#7 ContentInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // contentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + // OID for the content type is 'data' + asn1.oidToDer(pki.oids.data).getBytes()), + // content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + asn1.toDer(keySafeContents).getBytes()) + ]) + ]); + contents.push(keyCI); + } + + // create AuthenticatedSafe by stringing together the contents + var safe = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, contents); + + var macData; + if(options.useMac) { + // MacData + var sha1 = forge.md.sha1.create(); + var macSalt = new forge.util.ByteBuffer( + forge.random.getBytes(options.saltSize)); + var count = options.count; + // 160-bit key + var key = p12.generateKey(password, macSalt, 3, count, 20); + var mac = forge.hmac.create(); + mac.start(sha1, key); + mac.update(asn1.toDer(safe).getBytes()); + var macValue = mac.getMac(); + macData = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // mac DigestInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // digestAlgorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm = SHA-1 + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.sha1).getBytes()), + // parameters = Null + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]), + // digest + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, + false, macValue.getBytes()) + ]), + // macSalt OCTET STRING + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, macSalt.getBytes()), + // iterations INTEGER (XXX: Only support count < 65536) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(count).getBytes() + ) + ]); + } + + // PFX + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version (3) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(3).getBytes()), + // PKCS#7 ContentInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // contentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + // OID for the content type is 'data' + asn1.oidToDer(pki.oids.data).getBytes()), + // content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + asn1.toDer(safe).getBytes()) + ]) + ]), + macData + ]); +}; + +/** + * Derives a PKCS#12 key. + * + * @param password the password to derive the key material from, null or + * undefined for none. + * @param salt the salt, as a ByteBuffer, to use. + * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC). + * @param iter the iteration count. + * @param n the number of bytes to derive from the password. + * @param md the message digest to use, defaults to SHA-1. + * + * @return a ByteBuffer with the bytes derived from the password. + */ +p12.generateKey = forge.pbe.generatePkcs12Key; diff --git a/node_modules/node-forge/lib/pkcs7.js b/node_modules/node-forge/lib/pkcs7.js new file mode 100644 index 0000000..3a5d845 --- /dev/null +++ b/node_modules/node-forge/lib/pkcs7.js @@ -0,0 +1,1260 @@ +/** + * Javascript implementation of PKCS#7 v1.5. + * + * @author Stefan Siegl + * @author Dave Longley + * + * Copyright (c) 2012 Stefan Siegl + * Copyright (c) 2012-2015 Digital Bazaar, Inc. + * + * Currently this implementation only supports ContentType of EnvelopedData, + * EncryptedData, or SignedData at the root level. The top level elements may + * contain only a ContentInfo of ContentType Data, i.e. plain data. Further + * nesting is not (yet) supported. + * + * The Forge validators for PKCS #7's ASN.1 structures are available from + * a separate file pkcs7asn1.js, since those are referenced from other + * PKCS standards like PKCS #12. + */ +var forge = require('./forge'); +require('./aes'); +require('./asn1'); +require('./des'); +require('./oids'); +require('./pem'); +require('./pkcs7asn1'); +require('./random'); +require('./util'); +require('./x509'); + +// shortcut for ASN.1 API +var asn1 = forge.asn1; + +// shortcut for PKCS#7 API +var p7 = module.exports = forge.pkcs7 = forge.pkcs7 || {}; + +/** + * Converts a PKCS#7 message from PEM format. + * + * @param pem the PEM-formatted PKCS#7 message. + * + * @return the PKCS#7 message. + */ +p7.messageFromPem = function(pem) { + var msg = forge.pem.decode(pem)[0]; + + if(msg.type !== 'PKCS7') { + var error = new Error('Could not convert PKCS#7 message from PEM; PEM ' + + 'header type is not "PKCS#7".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert PKCS#7 message from PEM; PEM is encrypted.'); + } + + // convert DER to ASN.1 object + var obj = asn1.fromDer(msg.body); + + return p7.messageFromAsn1(obj); +}; + +/** + * Converts a PKCS#7 message to PEM format. + * + * @param msg The PKCS#7 message object + * @param maxline The maximum characters per line, defaults to 64. + * + * @return The PEM-formatted PKCS#7 message. + */ +p7.messageToPem = function(msg, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var pemObj = { + type: 'PKCS7', + body: asn1.toDer(msg.toAsn1()).getBytes() + }; + return forge.pem.encode(pemObj, {maxline: maxline}); +}; + +/** + * Converts a PKCS#7 message from an ASN.1 object. + * + * @param obj the ASN.1 representation of a ContentInfo. + * + * @return the PKCS#7 message. + */ +p7.messageFromAsn1 = function(obj) { + // validate root level ContentInfo and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#7 message. ' + + 'ASN.1 object is not an PKCS#7 ContentInfo.'); + error.errors = errors; + throw error; + } + + var contentType = asn1.derToOid(capture.contentType); + var msg; + + switch(contentType) { + case forge.pki.oids.envelopedData: + msg = p7.createEnvelopedData(); + break; + + case forge.pki.oids.encryptedData: + msg = p7.createEncryptedData(); + break; + + case forge.pki.oids.signedData: + msg = p7.createSignedData(); + break; + + default: + throw new Error('Cannot read PKCS#7 message. ContentType with OID ' + + contentType + ' is not (yet) supported.'); + } + + msg.fromAsn1(capture.content.value[0]); + return msg; +}; + +p7.createSignedData = function() { + var msg = null; + msg = { + type: forge.pki.oids.signedData, + version: 1, + certificates: [], + crls: [], + // TODO: add json-formatted signer stuff here? + signers: [], + // populated during sign() + digestAlgorithmIdentifiers: [], + contentInfo: null, + signerInfos: [], + + fromAsn1: function(obj) { + // validate SignedData content block and capture data. + _fromAsn1(msg, obj, p7.asn1.signedDataValidator); + msg.certificates = []; + msg.crls = []; + msg.digestAlgorithmIdentifiers = []; + msg.contentInfo = null; + msg.signerInfos = []; + + if(msg.rawCapture.certificates) { + var certs = msg.rawCapture.certificates.value; + for(var i = 0; i < certs.length; ++i) { + msg.certificates.push(forge.pki.certificateFromAsn1(certs[i])); + } + } + + // TODO: parse crls + }, + + toAsn1: function() { + // degenerate case with no content + if(!msg.contentInfo) { + msg.sign(); + } + + var certs = []; + for(var i = 0; i < msg.certificates.length; ++i) { + certs.push(forge.pki.certificateToAsn1(msg.certificates[i])); + } + + var crls = []; + // TODO: implement CRLs + + // [0] SignedData + var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Version + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(msg.version).getBytes()), + // DigestAlgorithmIdentifiers + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SET, true, + msg.digestAlgorithmIdentifiers), + // ContentInfo + msg.contentInfo + ]) + ]); + if(certs.length > 0) { + // [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL + signedData.value[0].value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs)); + } + if(crls.length > 0) { + // [1] IMPLICIT CertificateRevocationLists OPTIONAL + signedData.value[0].value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls)); + } + // SignerInfos + signedData.value[0].value.push( + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, + msg.signerInfos)); + + // ContentInfo + return asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // ContentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(msg.type).getBytes()), + // [0] SignedData + signedData + ]); + }, + + /** + * Add (another) entity to list of signers. + * + * Note: If authenticatedAttributes are provided, then, per RFC 2315, + * they must include at least two attributes: content type and + * message digest. The message digest attribute value will be + * auto-calculated during signing and will be ignored if provided. + * + * Here's an example of providing these two attributes: + * + * forge.pkcs7.createSignedData(); + * p7.addSigner({ + * issuer: cert.issuer.attributes, + * serialNumber: cert.serialNumber, + * key: privateKey, + * digestAlgorithm: forge.pki.oids.sha1, + * authenticatedAttributes: [{ + * type: forge.pki.oids.contentType, + * value: forge.pki.oids.data + * }, { + * type: forge.pki.oids.messageDigest + * }] + * }); + * + * TODO: Support [subjectKeyIdentifier] as signer's ID. + * + * @param signer the signer information: + * key the signer's private key. + * [certificate] a certificate containing the public key + * associated with the signer's private key; use this option as + * an alternative to specifying signer.issuer and + * signer.serialNumber. + * [issuer] the issuer attributes (eg: cert.issuer.attributes). + * [serialNumber] the signer's certificate's serial number in + * hexadecimal (eg: cert.serialNumber). + * [digestAlgorithm] the message digest OID, as a string, to use + * (eg: forge.pki.oids.sha1). + * [authenticatedAttributes] an optional array of attributes + * to also sign along with the content. + */ + addSigner: function(signer) { + var issuer = signer.issuer; + var serialNumber = signer.serialNumber; + if(signer.certificate) { + var cert = signer.certificate; + if(typeof cert === 'string') { + cert = forge.pki.certificateFromPem(cert); + } + issuer = cert.issuer.attributes; + serialNumber = cert.serialNumber; + } + var key = signer.key; + if(!key) { + throw new Error( + 'Could not add PKCS#7 signer; no private key specified.'); + } + if(typeof key === 'string') { + key = forge.pki.privateKeyFromPem(key); + } + + // ensure OID known for digest algorithm + var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1; + switch(digestAlgorithm) { + case forge.pki.oids.sha1: + case forge.pki.oids.sha256: + case forge.pki.oids.sha384: + case forge.pki.oids.sha512: + case forge.pki.oids.md5: + break; + default: + throw new Error( + 'Could not add PKCS#7 signer; unknown message digest algorithm: ' + + digestAlgorithm); + } + + // if authenticatedAttributes is present, then the attributes + // must contain at least PKCS #9 content-type and message-digest + var authenticatedAttributes = signer.authenticatedAttributes || []; + if(authenticatedAttributes.length > 0) { + var contentType = false; + var messageDigest = false; + for(var i = 0; i < authenticatedAttributes.length; ++i) { + var attr = authenticatedAttributes[i]; + if(!contentType && attr.type === forge.pki.oids.contentType) { + contentType = true; + if(messageDigest) { + break; + } + continue; + } + if(!messageDigest && attr.type === forge.pki.oids.messageDigest) { + messageDigest = true; + if(contentType) { + break; + } + continue; + } + } + + if(!contentType || !messageDigest) { + throw new Error('Invalid signer.authenticatedAttributes. If ' + + 'signer.authenticatedAttributes is specified, then it must ' + + 'contain at least two attributes, PKCS #9 content-type and ' + + 'PKCS #9 message-digest.'); + } + } + + msg.signers.push({ + key: key, + version: 1, + issuer: issuer, + serialNumber: serialNumber, + digestAlgorithm: digestAlgorithm, + signatureAlgorithm: forge.pki.oids.rsaEncryption, + signature: null, + authenticatedAttributes: authenticatedAttributes, + unauthenticatedAttributes: [] + }); + }, + + /** + * Signs the content. + * @param options Options to apply when signing: + * [detached] boolean. If signing should be done in detached mode. Defaults to false. + */ + sign: function(options) { + options = options || {}; + // auto-generate content info + if(typeof msg.content !== 'object' || msg.contentInfo === null) { + // use Data ContentInfo + msg.contentInfo = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // ContentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(forge.pki.oids.data).getBytes()) + ]); + + // add actual content, if present + if('content' in msg) { + var content; + if(msg.content instanceof forge.util.ByteBuffer) { + content = msg.content.bytes(); + } else if(typeof msg.content === 'string') { + content = forge.util.encodeUtf8(msg.content); + } + + if (options.detached) { + msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content); + } else { + msg.contentInfo.value.push( + // [0] EXPLICIT content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + content) + ])); + } + } + } + + // no signers, return early (degenerate case for certificate container) + if(msg.signers.length === 0) { + return; + } + + // generate digest algorithm identifiers + var mds = addDigestAlgorithmIds(); + + // generate signerInfos + addSignerInfos(mds); + }, + + verify: function() { + throw new Error('PKCS#7 signature verification not yet implemented.'); + }, + + /** + * Add a certificate. + * + * @param cert the certificate to add. + */ + addCertificate: function(cert) { + // convert from PEM + if(typeof cert === 'string') { + cert = forge.pki.certificateFromPem(cert); + } + msg.certificates.push(cert); + }, + + /** + * Add a certificate revokation list. + * + * @param crl the certificate revokation list to add. + */ + addCertificateRevokationList: function(crl) { + throw new Error('PKCS#7 CRL support not yet implemented.'); + } + }; + return msg; + + function addDigestAlgorithmIds() { + var mds = {}; + + for(var i = 0; i < msg.signers.length; ++i) { + var signer = msg.signers[i]; + var oid = signer.digestAlgorithm; + if(!(oid in mds)) { + // content digest + mds[oid] = forge.md[forge.pki.oids[oid]].create(); + } + if(signer.authenticatedAttributes.length === 0) { + // no custom attributes to digest; use content message digest + signer.md = mds[oid]; + } else { + // custom attributes to be digested; use own message digest + // TODO: optimize to just copy message digest state if that + // feature is ever supported with message digests + signer.md = forge.md[forge.pki.oids[oid]].create(); + } + } + + // add unique digest algorithm identifiers + msg.digestAlgorithmIdentifiers = []; + for(var oid in mds) { + msg.digestAlgorithmIdentifiers.push( + // AlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(oid).getBytes()), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ])); + } + + return mds; + } + + function addSignerInfos(mds) { + var content; + + if (msg.detachedContent) { + // Signature has been made in detached mode. + content = msg.detachedContent; + } else { + // Note: ContentInfo is a SEQUENCE with 2 values, second value is + // the content field and is optional for a ContentInfo but required here + // since signers are present + // get ContentInfo content + content = msg.contentInfo.value[1]; + // skip [0] EXPLICIT content wrapper + content = content.value[0]; + } + + if(!content) { + throw new Error( + 'Could not sign PKCS#7 message; there is no content to sign.'); + } + + // get ContentInfo content type + var contentType = asn1.derToOid(msg.contentInfo.value[0].value); + + // serialize content + var bytes = asn1.toDer(content); + + // skip identifier and length per RFC 2315 9.3 + // skip identifier (1 byte) + bytes.getByte(); + // read and discard length bytes + asn1.getBerValueLength(bytes); + bytes = bytes.getBytes(); + + // digest content DER value bytes + for(var oid in mds) { + mds[oid].start().update(bytes); + } + + // sign content + var signingTime = new Date(); + for(var i = 0; i < msg.signers.length; ++i) { + var signer = msg.signers[i]; + + if(signer.authenticatedAttributes.length === 0) { + // if ContentInfo content type is not "Data", then + // authenticatedAttributes must be present per RFC 2315 + if(contentType !== forge.pki.oids.data) { + throw new Error( + 'Invalid signer; authenticatedAttributes must be present ' + + 'when the ContentInfo content type is not PKCS#7 Data.'); + } + } else { + // process authenticated attributes + // [0] IMPLICIT + signer.authenticatedAttributesAsn1 = asn1.create( + asn1.Class.CONTEXT_SPECIFIC, 0, true, []); + + // per RFC 2315, attributes are to be digested using a SET container + // not the above [0] IMPLICIT container + var attrsAsn1 = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SET, true, []); + + for(var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) { + var attr = signer.authenticatedAttributes[ai]; + if(attr.type === forge.pki.oids.messageDigest) { + // use content message digest as value + attr.value = mds[signer.digestAlgorithm].digest(); + } else if(attr.type === forge.pki.oids.signingTime) { + // auto-populate signing time if not already set + if(!attr.value) { + attr.value = signingTime; + } + } + + // convert to ASN.1 and push onto Attributes SET (for signing) and + // onto authenticatedAttributesAsn1 to complete SignedData ASN.1 + // TODO: optimize away duplication + attrsAsn1.value.push(_attributeToAsn1(attr)); + signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr)); + } + + // DER-serialize and digest SET OF attributes only + bytes = asn1.toDer(attrsAsn1).getBytes(); + signer.md.start().update(bytes); + } + + // sign digest + signer.signature = signer.key.sign(signer.md, 'RSASSA-PKCS1-V1_5'); + } + + // add signer info + msg.signerInfos = _signersToAsn1(msg.signers); + } +}; + +/** + * Creates an empty PKCS#7 message of type EncryptedData. + * + * @return the message. + */ +p7.createEncryptedData = function() { + var msg = null; + msg = { + type: forge.pki.oids.encryptedData, + version: 0, + encryptedContent: { + algorithm: forge.pki.oids['aes256-CBC'] + }, + + /** + * Reads an EncryptedData content block (in ASN.1 format) + * + * @param obj The ASN.1 representation of the EncryptedData content block + */ + fromAsn1: function(obj) { + // Validate EncryptedData content block and capture data. + _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator); + }, + + /** + * Decrypt encrypted content + * + * @param key The (symmetric) key as a byte buffer + */ + decrypt: function(key) { + if(key !== undefined) { + msg.encryptedContent.key = key; + } + _decryptContent(msg); + } + }; + return msg; +}; + +/** + * Creates an empty PKCS#7 message of type EnvelopedData. + * + * @return the message. + */ +p7.createEnvelopedData = function() { + var msg = null; + msg = { + type: forge.pki.oids.envelopedData, + version: 0, + recipients: [], + encryptedContent: { + algorithm: forge.pki.oids['aes256-CBC'] + }, + + /** + * Reads an EnvelopedData content block (in ASN.1 format) + * + * @param obj the ASN.1 representation of the EnvelopedData content block. + */ + fromAsn1: function(obj) { + // validate EnvelopedData content block and capture data + var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator); + msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value); + }, + + toAsn1: function() { + // ContentInfo + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // ContentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(msg.type).getBytes()), + // [0] EnvelopedData + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Version + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(msg.version).getBytes()), + // RecipientInfos + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, + _recipientsToAsn1(msg.recipients)), + // EncryptedContentInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, + _encryptedContentToAsn1(msg.encryptedContent)) + ]) + ]) + ]); + }, + + /** + * Find recipient by X.509 certificate's issuer. + * + * @param cert the certificate with the issuer to look for. + * + * @return the recipient object. + */ + findRecipient: function(cert) { + var sAttr = cert.issuer.attributes; + + for(var i = 0; i < msg.recipients.length; ++i) { + var r = msg.recipients[i]; + var rAttr = r.issuer; + + if(r.serialNumber !== cert.serialNumber) { + continue; + } + + if(rAttr.length !== sAttr.length) { + continue; + } + + var match = true; + for(var j = 0; j < sAttr.length; ++j) { + if(rAttr[j].type !== sAttr[j].type || + rAttr[j].value !== sAttr[j].value) { + match = false; + break; + } + } + + if(match) { + return r; + } + } + + return null; + }, + + /** + * Decrypt enveloped content + * + * @param recipient The recipient object related to the private key + * @param privKey The (RSA) private key object + */ + decrypt: function(recipient, privKey) { + if(msg.encryptedContent.key === undefined && recipient !== undefined && + privKey !== undefined) { + switch(recipient.encryptedContent.algorithm) { + case forge.pki.oids.rsaEncryption: + case forge.pki.oids.desCBC: + var key = privKey.decrypt(recipient.encryptedContent.content); + msg.encryptedContent.key = forge.util.createBuffer(key); + break; + + default: + throw new Error('Unsupported asymmetric cipher, ' + + 'OID ' + recipient.encryptedContent.algorithm); + } + } + + _decryptContent(msg); + }, + + /** + * Add (another) entity to list of recipients. + * + * @param cert The certificate of the entity to add. + */ + addRecipient: function(cert) { + msg.recipients.push({ + version: 0, + issuer: cert.issuer.attributes, + serialNumber: cert.serialNumber, + encryptedContent: { + // We simply assume rsaEncryption here, since forge.pki only + // supports RSA so far. If the PKI module supports other + // ciphers one day, we need to modify this one as well. + algorithm: forge.pki.oids.rsaEncryption, + key: cert.publicKey + } + }); + }, + + /** + * Encrypt enveloped content. + * + * This function supports two optional arguments, cipher and key, which + * can be used to influence symmetric encryption. Unless cipher is + * provided, the cipher specified in encryptedContent.algorithm is used + * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key + * is (re-)used. If that one's not set, a random key will be generated + * automatically. + * + * @param [key] The key to be used for symmetric encryption. + * @param [cipher] The OID of the symmetric cipher to use. + */ + encrypt: function(key, cipher) { + // Part 1: Symmetric encryption + if(msg.encryptedContent.content === undefined) { + cipher = cipher || msg.encryptedContent.algorithm; + key = key || msg.encryptedContent.key; + + var keyLen, ivLen, ciphFn; + switch(cipher) { + case forge.pki.oids['aes128-CBC']: + keyLen = 16; + ivLen = 16; + ciphFn = forge.aes.createEncryptionCipher; + break; + + case forge.pki.oids['aes192-CBC']: + keyLen = 24; + ivLen = 16; + ciphFn = forge.aes.createEncryptionCipher; + break; + + case forge.pki.oids['aes256-CBC']: + keyLen = 32; + ivLen = 16; + ciphFn = forge.aes.createEncryptionCipher; + break; + + case forge.pki.oids['des-EDE3-CBC']: + keyLen = 24; + ivLen = 8; + ciphFn = forge.des.createEncryptionCipher; + break; + + default: + throw new Error('Unsupported symmetric cipher, OID ' + cipher); + } + + if(key === undefined) { + key = forge.util.createBuffer(forge.random.getBytes(keyLen)); + } else if(key.length() != keyLen) { + throw new Error('Symmetric key has wrong length; ' + + 'got ' + key.length() + ' bytes, expected ' + keyLen + '.'); + } + + // Keep a copy of the key & IV in the object, so the caller can + // use it for whatever reason. + msg.encryptedContent.algorithm = cipher; + msg.encryptedContent.key = key; + msg.encryptedContent.parameter = forge.util.createBuffer( + forge.random.getBytes(ivLen)); + + var ciph = ciphFn(key); + ciph.start(msg.encryptedContent.parameter.copy()); + ciph.update(msg.content); + + // The finish function does PKCS#7 padding by default, therefore + // no action required by us. + if(!ciph.finish()) { + throw new Error('Symmetric encryption failed.'); + } + + msg.encryptedContent.content = ciph.output; + } + + // Part 2: asymmetric encryption for each recipient + for(var i = 0; i < msg.recipients.length; ++i) { + var recipient = msg.recipients[i]; + + // Nothing to do, encryption already done. + if(recipient.encryptedContent.content !== undefined) { + continue; + } + + switch(recipient.encryptedContent.algorithm) { + case forge.pki.oids.rsaEncryption: + recipient.encryptedContent.content = + recipient.encryptedContent.key.encrypt( + msg.encryptedContent.key.data); + break; + + default: + throw new Error('Unsupported asymmetric cipher, OID ' + + recipient.encryptedContent.algorithm); + } + } + } + }; + return msg; +}; + +/** + * Converts a single recipient from an ASN.1 object. + * + * @param obj the ASN.1 RecipientInfo. + * + * @return the recipient object. + */ +function _recipientFromAsn1(obj) { + // validate EnvelopedData content block and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#7 RecipientInfo. ' + + 'ASN.1 object is not an PKCS#7 RecipientInfo.'); + error.errors = errors; + throw error; + } + + return { + version: capture.version.charCodeAt(0), + issuer: forge.pki.RDNAttributesAsArray(capture.issuer), + serialNumber: forge.util.createBuffer(capture.serial).toHex(), + encryptedContent: { + algorithm: asn1.derToOid(capture.encAlgorithm), + parameter: capture.encParameter ? capture.encParameter.value : undefined, + content: capture.encKey + } + }; +} + +/** + * Converts a single recipient object to an ASN.1 object. + * + * @param obj the recipient object. + * + * @return the ASN.1 RecipientInfo. + */ +function _recipientToAsn1(obj) { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Version + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(obj.version).getBytes()), + // IssuerAndSerialNumber + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Name + forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}), + // Serial + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + forge.util.hexToBytes(obj.serialNumber)) + ]), + // KeyEncryptionAlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()), + // Parameter, force NULL, only RSA supported for now. + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]), + // EncryptedKey + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + obj.encryptedContent.content) + ]); +} + +/** + * Map a set of RecipientInfo ASN.1 objects to recipient objects. + * + * @param infos an array of ASN.1 representations RecipientInfo (i.e. SET OF). + * + * @return an array of recipient objects. + */ +function _recipientsFromAsn1(infos) { + var ret = []; + for(var i = 0; i < infos.length; ++i) { + ret.push(_recipientFromAsn1(infos[i])); + } + return ret; +} + +/** + * Map an array of recipient objects to ASN.1 RecipientInfo objects. + * + * @param recipients an array of recipientInfo objects. + * + * @return an array of ASN.1 RecipientInfos. + */ +function _recipientsToAsn1(recipients) { + var ret = []; + for(var i = 0; i < recipients.length; ++i) { + ret.push(_recipientToAsn1(recipients[i])); + } + return ret; +} + +/** + * Converts a single signer from an ASN.1 object. + * + * @param obj the ASN.1 representation of a SignerInfo. + * + * @return the signer object. + */ +function _signerFromAsn1(obj) { + // validate EnvelopedData content block and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(obj, p7.asn1.signerInfoValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#7 SignerInfo. ' + + 'ASN.1 object is not an PKCS#7 SignerInfo.'); + error.errors = errors; + throw error; + } + + var rval = { + version: capture.version.charCodeAt(0), + issuer: forge.pki.RDNAttributesAsArray(capture.issuer), + serialNumber: forge.util.createBuffer(capture.serial).toHex(), + digestAlgorithm: asn1.derToOid(capture.digestAlgorithm), + signatureAlgorithm: asn1.derToOid(capture.signatureAlgorithm), + signature: capture.signature, + authenticatedAttributes: [], + unauthenticatedAttributes: [] + }; + + // TODO: convert attributes + var authenticatedAttributes = capture.authenticatedAttributes || []; + var unauthenticatedAttributes = capture.unauthenticatedAttributes || []; + + return rval; +} + +/** + * Converts a single signerInfo object to an ASN.1 object. + * + * @param obj the signerInfo object. + * + * @return the ASN.1 representation of a SignerInfo. + */ +function _signerToAsn1(obj) { + // SignerInfo + var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(obj.version).getBytes()), + // issuerAndSerialNumber + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // name + forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}), + // serial + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + forge.util.hexToBytes(obj.serialNumber)) + ]), + // digestAlgorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(obj.digestAlgorithm).getBytes()), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]) + ]); + + // authenticatedAttributes (OPTIONAL) + if(obj.authenticatedAttributesAsn1) { + // add ASN.1 previously generated during signing + rval.value.push(obj.authenticatedAttributesAsn1); + } + + // digestEncryptionAlgorithm + rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(obj.signatureAlgorithm).getBytes()), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ])); + + // encryptedDigest + rval.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature)); + + // unauthenticatedAttributes (OPTIONAL) + if(obj.unauthenticatedAttributes.length > 0) { + // [1] IMPLICIT + var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []); + for(var i = 0; i < obj.unauthenticatedAttributes.length; ++i) { + var attr = obj.unauthenticatedAttributes[i]; + attrsAsn1.values.push(_attributeToAsn1(attr)); + } + rval.value.push(attrsAsn1); + } + + return rval; +} + +/** + * Map a set of SignerInfo ASN.1 objects to an array of signer objects. + * + * @param signerInfoAsn1s an array of ASN.1 SignerInfos (i.e. SET OF). + * + * @return an array of signers objects. + */ +function _signersFromAsn1(signerInfoAsn1s) { + var ret = []; + for(var i = 0; i < signerInfoAsn1s.length; ++i) { + ret.push(_signerFromAsn1(signerInfoAsn1s[i])); + } + return ret; +} + +/** + * Map an array of signer objects to ASN.1 objects. + * + * @param signers an array of signer objects. + * + * @return an array of ASN.1 SignerInfos. + */ +function _signersToAsn1(signers) { + var ret = []; + for(var i = 0; i < signers.length; ++i) { + ret.push(_signerToAsn1(signers[i])); + } + return ret; +} + +/** + * Convert an attribute object to an ASN.1 Attribute. + * + * @param attr the attribute object. + * + * @return the ASN.1 Attribute. + */ +function _attributeToAsn1(attr) { + var value; + + // TODO: generalize to support more attributes + if(attr.type === forge.pki.oids.contentType) { + value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(attr.value).getBytes()); + } else if(attr.type === forge.pki.oids.messageDigest) { + value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + attr.value.bytes()); + } else if(attr.type === forge.pki.oids.signingTime) { + /* Note per RFC 2985: Dates between 1 January 1950 and 31 December 2049 + (inclusive) MUST be encoded as UTCTime. Any dates with year values + before 1950 or after 2049 MUST be encoded as GeneralizedTime. [Further,] + UTCTime values MUST be expressed in Greenwich Mean Time (Zulu) and MUST + include seconds (i.e., times are YYMMDDHHMMSSZ), even where the + number of seconds is zero. Midnight (GMT) must be represented as + "YYMMDD000000Z". */ + // TODO: make these module-level constants + var jan_1_1950 = new Date('1950-01-01T00:00:00Z'); + var jan_1_2050 = new Date('2050-01-01T00:00:00Z'); + var date = attr.value; + if(typeof date === 'string') { + // try to parse date + var timestamp = Date.parse(date); + if(!isNaN(timestamp)) { + date = new Date(timestamp); + } else if(date.length === 13) { + // YYMMDDHHMMSSZ (13 chars for UTCTime) + date = asn1.utcTimeToDate(date); + } else { + // assume generalized time + date = asn1.generalizedTimeToDate(date); + } + } + + if(date >= jan_1_1950 && date < jan_1_2050) { + value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false, + asn1.dateToUtcTime(date)); + } else { + value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false, + asn1.dateToGeneralizedTime(date)); + } + } + + // TODO: expose as common API call + // create a RelativeDistinguishedName set + // each value in the set is an AttributeTypeAndValue first + // containing the type (an OID) and second the value + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AttributeType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(attr.type).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + // AttributeValue + value + ]) + ]); +} + +/** + * Map messages encrypted content to ASN.1 objects. + * + * @param ec The encryptedContent object of the message. + * + * @return ASN.1 representation of the encryptedContent object (SEQUENCE). + */ +function _encryptedContentToAsn1(ec) { + return [ + // ContentType, always Data for the moment + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(forge.pki.oids.data).getBytes()), + // ContentEncryptionAlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(ec.algorithm).getBytes()), + // Parameters (IV) + !ec.parameter ? + undefined : + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + ec.parameter.getBytes()) + ]), + // [0] EncryptedContent + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + ec.content.getBytes()) + ]) + ]; +} + +/** + * Reads the "common part" of an PKCS#7 content block (in ASN.1 format) + * + * This function reads the "common part" of the PKCS#7 content blocks + * EncryptedData and EnvelopedData, i.e. version number and symmetrically + * encrypted content block. + * + * The result of the ASN.1 validate and capture process is returned + * to allow the caller to extract further data, e.g. the list of recipients + * in case of a EnvelopedData object. + * + * @param msg the PKCS#7 object to read the data to. + * @param obj the ASN.1 representation of the content block. + * @param validator the ASN.1 structure validator object to use. + * + * @return the value map captured by validator object. + */ +function _fromAsn1(msg, obj, validator) { + var capture = {}; + var errors = []; + if(!asn1.validate(obj, validator, capture, errors)) { + var error = new Error('Cannot read PKCS#7 message. ' + + 'ASN.1 object is not a supported PKCS#7 message.'); + error.errors = error; + throw error; + } + + // Check contentType, so far we only support (raw) Data. + var contentType = asn1.derToOid(capture.contentType); + if(contentType !== forge.pki.oids.data) { + throw new Error('Unsupported PKCS#7 message. ' + + 'Only wrapped ContentType Data supported.'); + } + + if(capture.encryptedContent) { + var content = ''; + if(forge.util.isArray(capture.encryptedContent)) { + for(var i = 0; i < capture.encryptedContent.length; ++i) { + if(capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) { + throw new Error('Malformed PKCS#7 message, expecting encrypted ' + + 'content constructed of only OCTET STRING objects.'); + } + content += capture.encryptedContent[i].value; + } + } else { + content = capture.encryptedContent; + } + msg.encryptedContent = { + algorithm: asn1.derToOid(capture.encAlgorithm), + parameter: forge.util.createBuffer(capture.encParameter.value), + content: forge.util.createBuffer(content) + }; + } + + if(capture.content) { + var content = ''; + if(forge.util.isArray(capture.content)) { + for(var i = 0; i < capture.content.length; ++i) { + if(capture.content[i].type !== asn1.Type.OCTETSTRING) { + throw new Error('Malformed PKCS#7 message, expecting ' + + 'content constructed of only OCTET STRING objects.'); + } + content += capture.content[i].value; + } + } else { + content = capture.content; + } + msg.content = forge.util.createBuffer(content); + } + + msg.version = capture.version.charCodeAt(0); + msg.rawCapture = capture; + + return capture; +} + +/** + * Decrypt the symmetrically encrypted content block of the PKCS#7 message. + * + * Decryption is skipped in case the PKCS#7 message object already has a + * (decrypted) content attribute. The algorithm, key and cipher parameters + * (probably the iv) are taken from the encryptedContent attribute of the + * message object. + * + * @param The PKCS#7 message object. + */ +function _decryptContent(msg) { + if(msg.encryptedContent.key === undefined) { + throw new Error('Symmetric key not available.'); + } + + if(msg.content === undefined) { + var ciph; + + switch(msg.encryptedContent.algorithm) { + case forge.pki.oids['aes128-CBC']: + case forge.pki.oids['aes192-CBC']: + case forge.pki.oids['aes256-CBC']: + ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key); + break; + + case forge.pki.oids['desCBC']: + case forge.pki.oids['des-EDE3-CBC']: + ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key); + break; + + default: + throw new Error('Unsupported symmetric cipher, OID ' + + msg.encryptedContent.algorithm); + } + ciph.start(msg.encryptedContent.parameter); + ciph.update(msg.encryptedContent.content); + + if(!ciph.finish()) { + throw new Error('Symmetric decryption failed.'); + } + + msg.content = ciph.output; + } +} diff --git a/node_modules/node-forge/lib/pkcs7asn1.js b/node_modules/node-forge/lib/pkcs7asn1.js new file mode 100644 index 0000000..0e13c89 --- /dev/null +++ b/node_modules/node-forge/lib/pkcs7asn1.js @@ -0,0 +1,410 @@ +/** + * Javascript implementation of ASN.1 validators for PKCS#7 v1.5. + * + * @author Dave Longley + * @author Stefan Siegl + * + * Copyright (c) 2012-2015 Digital Bazaar, Inc. + * Copyright (c) 2012 Stefan Siegl + * + * The ASN.1 representation of PKCS#7 is as follows + * (see RFC #2315 for details, http://www.ietf.org/rfc/rfc2315.txt): + * + * A PKCS#7 message consists of a ContentInfo on root level, which may + * contain any number of further ContentInfo nested into it. + * + * ContentInfo ::= SEQUENCE { + * contentType ContentType, + * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL + * } + * + * ContentType ::= OBJECT IDENTIFIER + * + * EnvelopedData ::= SEQUENCE { + * version Version, + * recipientInfos RecipientInfos, + * encryptedContentInfo EncryptedContentInfo + * } + * + * EncryptedData ::= SEQUENCE { + * version Version, + * encryptedContentInfo EncryptedContentInfo + * } + * + * id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2) + * us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 } + * + * SignedData ::= SEQUENCE { + * version INTEGER, + * digestAlgorithms DigestAlgorithmIdentifiers, + * contentInfo ContentInfo, + * certificates [0] IMPLICIT Certificates OPTIONAL, + * crls [1] IMPLICIT CertificateRevocationLists OPTIONAL, + * signerInfos SignerInfos + * } + * + * SignerInfos ::= SET OF SignerInfo + * + * SignerInfo ::= SEQUENCE { + * version Version, + * issuerAndSerialNumber IssuerAndSerialNumber, + * digestAlgorithm DigestAlgorithmIdentifier, + * authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL, + * digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier, + * encryptedDigest EncryptedDigest, + * unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL + * } + * + * EncryptedDigest ::= OCTET STRING + * + * Attributes ::= SET OF Attribute + * + * Attribute ::= SEQUENCE { + * attrType OBJECT IDENTIFIER, + * attrValues SET OF AttributeValue + * } + * + * AttributeValue ::= ANY + * + * Version ::= INTEGER + * + * RecipientInfos ::= SET OF RecipientInfo + * + * EncryptedContentInfo ::= SEQUENCE { + * contentType ContentType, + * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier, + * encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL + * } + * + * ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier + * + * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters + * for the algorithm, if any. In the case of AES and DES3, there is only one, + * the IV. + * + * AlgorithmIdentifer ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters ANY DEFINED BY algorithm OPTIONAL + * } + * + * EncryptedContent ::= OCTET STRING + * + * RecipientInfo ::= SEQUENCE { + * version Version, + * issuerAndSerialNumber IssuerAndSerialNumber, + * keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier, + * encryptedKey EncryptedKey + * } + * + * IssuerAndSerialNumber ::= SEQUENCE { + * issuer Name, + * serialNumber CertificateSerialNumber + * } + * + * CertificateSerialNumber ::= INTEGER + * + * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier + * + * EncryptedKey ::= OCTET STRING + */ +var forge = require('./forge'); +require('./asn1'); +require('./util'); + +// shortcut for ASN.1 API +var asn1 = forge.asn1; + +// shortcut for PKCS#7 API +var p7v = module.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {}; +forge.pkcs7 = forge.pkcs7 || {}; +forge.pkcs7.asn1 = p7v; + +var contentInfoValidator = { + name: 'ContentInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'ContentInfo.ContentType', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'contentType' + }, { + name: 'ContentInfo.content', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + captureAsn1: 'content' + }] +}; +p7v.contentInfoValidator = contentInfoValidator; + +var encryptedContentInfoValidator = { + name: 'EncryptedContentInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'EncryptedContentInfo.contentType', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'contentType' + }, { + name: 'EncryptedContentInfo.contentEncryptionAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'EncryptedContentInfo.contentEncryptionAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'encAlgorithm' + }, { + name: 'EncryptedContentInfo.contentEncryptionAlgorithm.parameter', + tagClass: asn1.Class.UNIVERSAL, + captureAsn1: 'encParameter' + }] + }, { + name: 'EncryptedContentInfo.encryptedContent', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + /* The PKCS#7 structure output by OpenSSL somewhat differs from what + * other implementations do generate. + * + * OpenSSL generates a structure like this: + * SEQUENCE { + * ... + * [0] + * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 + * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 + * ... + * } + * + * Whereas other implementations (and this PKCS#7 module) generate: + * SEQUENCE { + * ... + * [0] { + * OCTET STRING + * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 + * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 + * ... + * } + * } + * + * In order to support both, we just capture the context specific + * field here. The OCTET STRING bit is removed below. + */ + capture: 'encryptedContent', + captureAsn1: 'encryptedContentAsn1' + }] +}; + +p7v.envelopedDataValidator = { + name: 'EnvelopedData', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'EnvelopedData.Version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'version' + }, { + name: 'EnvelopedData.RecipientInfos', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + captureAsn1: 'recipientInfos' + }].concat(encryptedContentInfoValidator) +}; + +p7v.encryptedDataValidator = { + name: 'EncryptedData', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'EncryptedData.Version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'version' + }].concat(encryptedContentInfoValidator) +}; + +var signerValidator = { + name: 'SignerInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'SignerInfo.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false + }, { + name: 'SignerInfo.issuerAndSerialNumber', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'SignerInfo.issuerAndSerialNumber.issuer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'issuer' + }, { + name: 'SignerInfo.issuerAndSerialNumber.serialNumber', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'serial' + }] + }, { + name: 'SignerInfo.digestAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'SignerInfo.digestAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'digestAlgorithm' + }, { + name: 'SignerInfo.digestAlgorithm.parameter', + tagClass: asn1.Class.UNIVERSAL, + constructed: false, + captureAsn1: 'digestParameter', + optional: true + }] + }, { + name: 'SignerInfo.authenticatedAttributes', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + capture: 'authenticatedAttributes' + }, { + name: 'SignerInfo.digestEncryptionAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + capture: 'signatureAlgorithm' + }, { + name: 'SignerInfo.encryptedDigest', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'signature' + }, { + name: 'SignerInfo.unauthenticatedAttributes', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + optional: true, + capture: 'unauthenticatedAttributes' + }] +}; + +p7v.signedDataValidator = { + name: 'SignedData', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'SignedData.Version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'version' + }, { + name: 'SignedData.DigestAlgorithms', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + captureAsn1: 'digestAlgorithms' + }, + contentInfoValidator, + { + name: 'SignedData.Certificates', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + optional: true, + captureAsn1: 'certificates' + }, { + name: 'SignedData.CertificateRevocationLists', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + optional: true, + captureAsn1: 'crls' + }, { + name: 'SignedData.SignerInfos', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + capture: 'signerInfos', + optional: true, + value: [signerValidator] + }] +}; + +p7v.recipientInfoValidator = { + name: 'RecipientInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'RecipientInfo.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'version' + }, { + name: 'RecipientInfo.issuerAndSerial', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'RecipientInfo.issuerAndSerial.issuer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'issuer' + }, { + name: 'RecipientInfo.issuerAndSerial.serialNumber', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'serial' + }] + }, { + name: 'RecipientInfo.keyEncryptionAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'RecipientInfo.keyEncryptionAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'encAlgorithm' + }, { + name: 'RecipientInfo.keyEncryptionAlgorithm.parameter', + tagClass: asn1.Class.UNIVERSAL, + constructed: false, + captureAsn1: 'encParameter', + optional: true + }] + }, { + name: 'RecipientInfo.encryptedKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'encKey' + }] +}; diff --git a/node_modules/node-forge/lib/pki.js b/node_modules/node-forge/lib/pki.js new file mode 100644 index 0000000..ee82ff1 --- /dev/null +++ b/node_modules/node-forge/lib/pki.js @@ -0,0 +1,102 @@ +/** + * Javascript implementation of a basic Public Key Infrastructure, including + * support for RSA public and private keys. + * + * @author Dave Longley + * + * Copyright (c) 2010-2013 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./asn1'); +require('./oids'); +require('./pbe'); +require('./pem'); +require('./pbkdf2'); +require('./pkcs12'); +require('./pss'); +require('./rsa'); +require('./util'); +require('./x509'); + +// shortcut for asn.1 API +var asn1 = forge.asn1; + +/* Public Key Infrastructure (PKI) implementation. */ +var pki = module.exports = forge.pki = forge.pki || {}; + +/** + * NOTE: THIS METHOD IS DEPRECATED. Use pem.decode() instead. + * + * Converts PEM-formatted data to DER. + * + * @param pem the PEM-formatted data. + * + * @return the DER-formatted data. + */ +pki.pemToDer = function(pem) { + var msg = forge.pem.decode(pem)[0]; + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert PEM to DER; PEM is encrypted.'); + } + return forge.util.createBuffer(msg.body); +}; + +/** + * Converts an RSA private key from PEM format. + * + * @param pem the PEM-formatted private key. + * + * @return the private key. + */ +pki.privateKeyFromPem = function(pem) { + var msg = forge.pem.decode(pem)[0]; + + if(msg.type !== 'PRIVATE KEY' && msg.type !== 'RSA PRIVATE KEY') { + var error = new Error('Could not convert private key from PEM; PEM ' + + 'header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert private key from PEM; PEM is encrypted.'); + } + + // convert DER to ASN.1 object + var obj = asn1.fromDer(msg.body); + + return pki.privateKeyFromAsn1(obj); +}; + +/** + * Converts an RSA private key to PEM format. + * + * @param key the private key. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted private key. + */ +pki.privateKeyToPem = function(key, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var msg = { + type: 'RSA PRIVATE KEY', + body: asn1.toDer(pki.privateKeyToAsn1(key)).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; + +/** + * Converts a PrivateKeyInfo to PEM format. + * + * @param pki the PrivateKeyInfo. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted private key. + */ +pki.privateKeyInfoToPem = function(pki, maxline) { + // convert to DER, then PEM-encode + var msg = { + type: 'PRIVATE KEY', + body: asn1.toDer(pki).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; diff --git a/node_modules/node-forge/lib/prime.js b/node_modules/node-forge/lib/prime.js new file mode 100644 index 0000000..3d51473 --- /dev/null +++ b/node_modules/node-forge/lib/prime.js @@ -0,0 +1,297 @@ +/** + * Prime number generation API. + * + * @author Dave Longley + * + * Copyright (c) 2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./util'); +require('./jsbn'); +require('./random'); + +(function() { + +// forge.prime already defined +if(forge.prime) { + module.exports = forge.prime; + return; +} + +/* PRIME API */ +var prime = module.exports = forge.prime = forge.prime || {}; + +var BigInteger = forge.jsbn.BigInteger; + +// primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29 +var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; +var THIRTY = new BigInteger(null); +THIRTY.fromInt(30); +var op_or = function(x, y) {return x|y;}; + +/** + * Generates a random probable prime with the given number of bits. + * + * Alternative algorithms can be specified by name as a string or as an + * object with custom options like so: + * + * { + * name: 'PRIMEINC', + * options: { + * maxBlockTime: , + * millerRabinTests: , + * workerScript: , + * workers: . + * workLoad: the size of the work load, ie: number of possible prime + * numbers for each web worker to check per work assignment, + * (default: 100). + * } + * } + * + * @param bits the number of bits for the prime number. + * @param options the options to use. + * [algorithm] the algorithm to use (default: 'PRIMEINC'). + * [prng] a custom crypto-secure pseudo-random number generator to use, + * that must define "getBytesSync". + * + * @return callback(err, num) called once the operation completes. + */ +prime.generateProbablePrime = function(bits, options, callback) { + if(typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + + // default to PRIMEINC algorithm + var algorithm = options.algorithm || 'PRIMEINC'; + if(typeof algorithm === 'string') { + algorithm = {name: algorithm}; + } + algorithm.options = algorithm.options || {}; + + // create prng with api that matches BigInteger secure random + var prng = options.prng || forge.random; + var rng = { + // x is an array to fill with bytes + nextBytes: function(x) { + var b = prng.getBytesSync(x.length); + for(var i = 0; i < x.length; ++i) { + x[i] = b.charCodeAt(i); + } + } + }; + + if(algorithm.name === 'PRIMEINC') { + return primeincFindPrime(bits, rng, algorithm.options, callback); + } + + throw new Error('Invalid prime generation algorithm: ' + algorithm.name); +}; + +function primeincFindPrime(bits, rng, options, callback) { + if('workers' in options) { + return primeincFindPrimeWithWorkers(bits, rng, options, callback); + } + return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); +} + +function primeincFindPrimeWithoutWorkers(bits, rng, options, callback) { + // initialize random number + var num = generateRandom(bits, rng); + + /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The + number we are given is always aligned at 30k + 1. Each time the number is + determined not to be prime we add to get to the next 'i', eg: if the number + was at 30k + 1 we add 6. */ + var deltaIdx = 0; + + // get required number of MR tests + var mrTests = getMillerRabinTests(num.bitLength()); + if('millerRabinTests' in options) { + mrTests = options.millerRabinTests; + } + + // find prime nearest to 'num' for maxBlockTime ms + // 10 ms gives 5ms of leeway for other calculations before dropping + // below 60fps (1000/60 == 16.67), but in reality, the number will + // likely be higher due to an 'atomic' big int modPow + var maxBlockTime = 10; + if('maxBlockTime' in options) { + maxBlockTime = options.maxBlockTime; + } + + _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); +} + +function _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) { + var start = +new Date(); + do { + // overflow, regenerate random number + if(num.bitLength() > bits) { + num = generateRandom(bits, rng); + } + // do primality test + if(num.isProbablePrime(mrTests)) { + return callback(null, num); + } + // get next potential prime + num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); + } while(maxBlockTime < 0 || (+new Date() - start < maxBlockTime)); + + // keep trying later + forge.util.setImmediate(function() { + _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); + }); +} + +// NOTE: This algorithm is indeterminate in nature because workers +// run in parallel looking at different segments of numbers. Even if this +// algorithm is run twice with the same input from a predictable RNG, it +// may produce different outputs. +function primeincFindPrimeWithWorkers(bits, rng, options, callback) { + // web workers unavailable + if(typeof Worker === 'undefined') { + return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); + } + + // initialize random number + var num = generateRandom(bits, rng); + + // use web workers to generate keys + var numWorkers = options.workers; + var workLoad = options.workLoad || 100; + var range = workLoad * 30 / 8; + var workerScript = options.workerScript || 'forge/prime.worker.js'; + if(numWorkers === -1) { + return forge.util.estimateCores(function(err, cores) { + if(err) { + // default to 2 + cores = 2; + } + numWorkers = cores - 1; + generate(); + }); + } + generate(); + + function generate() { + // require at least 1 worker + numWorkers = Math.max(1, numWorkers); + + // TODO: consider optimizing by starting workers outside getPrime() ... + // note that in order to clean up they will have to be made internally + // asynchronous which may actually be slower + + // start workers immediately + var workers = []; + for(var i = 0; i < numWorkers; ++i) { + // FIXME: fix path or use blob URLs + workers[i] = new Worker(workerScript); + } + var running = numWorkers; + + // listen for requests from workers and assign ranges to find prime + for(var i = 0; i < numWorkers; ++i) { + workers[i].addEventListener('message', workerMessage); + } + + /* Note: The distribution of random numbers is unknown. Therefore, each + web worker is continuously allocated a range of numbers to check for a + random number until one is found. + + Every 30 numbers will be checked just 8 times, because prime numbers + have the form: + + 30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this) + + Therefore, if we want a web worker to run N checks before asking for + a new range of numbers, each range must contain N*30/8 numbers. + + For 100 checks (workLoad), this is a range of 375. */ + + var found = false; + function workerMessage(e) { + // ignore message, prime already found + if(found) { + return; + } + + --running; + var data = e.data; + if(data.found) { + // terminate all workers + for(var i = 0; i < workers.length; ++i) { + workers[i].terminate(); + } + found = true; + return callback(null, new BigInteger(data.prime, 16)); + } + + // overflow, regenerate random number + if(num.bitLength() > bits) { + num = generateRandom(bits, rng); + } + + // assign new range to check + var hex = num.toString(16); + + // start prime search + e.target.postMessage({ + hex: hex, + workLoad: workLoad + }); + + num.dAddOffset(range, 0); + } + } +} + +/** + * Generates a random number using the given number of bits and RNG. + * + * @param bits the number of bits for the number. + * @param rng the random number generator to use. + * + * @return the random number. + */ +function generateRandom(bits, rng) { + var num = new BigInteger(bits, rng); + // force MSB set + var bits1 = bits - 1; + if(!num.testBit(bits1)) { + num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num); + } + // align number on 30k+1 boundary + num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0); + return num; +} + +/** + * Returns the required number of Miller-Rabin tests to generate a + * prime with an error probability of (1/2)^80. + * + * See Handbook of Applied Cryptography Chapter 4, Table 4.4. + * + * @param bits the bit size. + * + * @return the required number of iterations. + */ +function getMillerRabinTests(bits) { + if(bits <= 100) return 27; + if(bits <= 150) return 18; + if(bits <= 200) return 15; + if(bits <= 250) return 12; + if(bits <= 300) return 9; + if(bits <= 350) return 8; + if(bits <= 400) return 7; + if(bits <= 500) return 6; + if(bits <= 600) return 5; + if(bits <= 800) return 4; + if(bits <= 1250) return 3; + return 2; +} + +})(); diff --git a/node_modules/node-forge/lib/prime.worker.js b/node_modules/node-forge/lib/prime.worker.js new file mode 100644 index 0000000..b145f8a --- /dev/null +++ b/node_modules/node-forge/lib/prime.worker.js @@ -0,0 +1,168 @@ +/** + * RSA Key Generation Worker. + * + * @author Dave Longley + * + * Copyright (c) 2013 Digital Bazaar, Inc. + */ +// worker is built using CommonJS syntax to include all code in one worker file +//importScripts('jsbn.js'); +var forge = require('./forge'); +require('./jsbn'); + +// prime constants +var LOW_PRIMES = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997]; +var LP_LIMIT = (1 << 26) / LOW_PRIMES[LOW_PRIMES.length - 1]; + +var BigInteger = forge.jsbn.BigInteger; +var BIG_TWO = new BigInteger(null); +BIG_TWO.fromInt(2); + +self.addEventListener('message', function(e) { + var result = findPrime(e.data); + self.postMessage(result); +}); + +// start receiving ranges to check +self.postMessage({found: false}); + +// primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29 +var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; + +function findPrime(data) { + // TODO: abstract based on data.algorithm (PRIMEINC vs. others) + + // create BigInteger from given random bytes + var num = new BigInteger(data.hex, 16); + + /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The + number we are given is always aligned at 30k + 1. Each time the number is + determined not to be prime we add to get to the next 'i', eg: if the number + was at 30k + 1 we add 6. */ + var deltaIdx = 0; + + // find nearest prime + var workLoad = data.workLoad; + for(var i = 0; i < workLoad; ++i) { + // do primality test + if(isProbablePrime(num)) { + return {found: true, prime: num.toString(16)}; + } + // get next potential prime + num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); + } + + return {found: false}; +} + +function isProbablePrime(n) { + // divide by low primes, ignore even checks, etc (n already aligned properly) + var i = 1; + while(i < LOW_PRIMES.length) { + var m = LOW_PRIMES[i]; + var j = i + 1; + while(j < LOW_PRIMES.length && m < LP_LIMIT) { + m *= LOW_PRIMES[j++]; + } + m = n.modInt(m); + while(i < j) { + if(m % LOW_PRIMES[i++] === 0) { + return false; + } + } + } + return runMillerRabin(n); +} + +// HAC 4.24, Miller-Rabin +function runMillerRabin(n) { + // n1 = n - 1 + var n1 = n.subtract(BigInteger.ONE); + + // get s and d such that n1 = 2^s * d + var s = n1.getLowestSetBit(); + if(s <= 0) { + return false; + } + var d = n1.shiftRight(s); + + var k = _getMillerRabinTests(n.bitLength()); + var prng = getPrng(); + var a; + for(var i = 0; i < k; ++i) { + // select witness 'a' at random from between 1 and n - 1 + do { + a = new BigInteger(n.bitLength(), prng); + } while(a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0); + + /* See if 'a' is a composite witness. */ + + // x = a^d mod n + var x = a.modPow(d, n); + + // probably prime + if(x.compareTo(BigInteger.ONE) === 0 || x.compareTo(n1) === 0) { + continue; + } + + var j = s; + while(--j) { + // x = x^2 mod a + x = x.modPowInt(2, n); + + // 'n' is composite because no previous x == -1 mod n + if(x.compareTo(BigInteger.ONE) === 0) { + return false; + } + // x == -1 mod n, so probably prime + if(x.compareTo(n1) === 0) { + break; + } + } + + // 'x' is first_x^(n1/2) and is not +/- 1, so 'n' is not prime + if(j === 0) { + return false; + } + } + + return true; +} + +// get pseudo random number generator +function getPrng() { + // create prng with api that matches BigInteger secure random + return { + // x is an array to fill with bytes + nextBytes: function(x) { + for(var i = 0; i < x.length; ++i) { + x[i] = Math.floor(Math.random() * 0xFF); + } + } + }; +} + +/** + * Returns the required number of Miller-Rabin tests to generate a + * prime with an error probability of (1/2)^80. + * + * See Handbook of Applied Cryptography Chapter 4, Table 4.4. + * + * @param bits the bit size. + * + * @return the required number of iterations. + */ +function _getMillerRabinTests(bits) { + if(bits <= 100) return 27; + if(bits <= 150) return 18; + if(bits <= 200) return 15; + if(bits <= 250) return 12; + if(bits <= 300) return 9; + if(bits <= 350) return 8; + if(bits <= 400) return 7; + if(bits <= 500) return 6; + if(bits <= 600) return 5; + if(bits <= 800) return 4; + if(bits <= 1250) return 3; + return 2; +} diff --git a/node_modules/node-forge/lib/prng.js b/node_modules/node-forge/lib/prng.js new file mode 100644 index 0000000..d3bd22e --- /dev/null +++ b/node_modules/node-forge/lib/prng.js @@ -0,0 +1,419 @@ +/** + * A javascript implementation of a cryptographically-secure + * Pseudo Random Number Generator (PRNG). The Fortuna algorithm is followed + * here though the use of SHA-256 is not enforced; when generating an + * a PRNG context, the hashing algorithm and block cipher used for + * the generator are specified via a plugin. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./util'); + +var _crypto = null; +if(forge.util.isNodejs && !forge.options.usePureJavaScript && + !process.versions['node-webkit']) { + _crypto = require('crypto'); +} + +/* PRNG API */ +var prng = module.exports = forge.prng = forge.prng || {}; + +/** + * Creates a new PRNG context. + * + * A PRNG plugin must be passed in that will provide: + * + * 1. A function that initializes the key and seed of a PRNG context. It + * will be given a 16 byte key and a 16 byte seed. Any key expansion + * or transformation of the seed from a byte string into an array of + * integers (or similar) should be performed. + * 2. The cryptographic function used by the generator. It takes a key and + * a seed. + * 3. A seed increment function. It takes the seed and returns seed + 1. + * 4. An api to create a message digest. + * + * For an example, see random.js. + * + * @param plugin the PRNG plugin to use. + */ +prng.create = function(plugin) { + var ctx = { + plugin: plugin, + key: null, + seed: null, + time: null, + // number of reseeds so far + reseeds: 0, + // amount of data generated so far + generated: 0, + // no initial key bytes + keyBytes: '' + }; + + // create 32 entropy pools (each is a message digest) + var md = plugin.md; + var pools = new Array(32); + for(var i = 0; i < 32; ++i) { + pools[i] = md.create(); + } + ctx.pools = pools; + + // entropy pools are written to cyclically, starting at index 0 + ctx.pool = 0; + + /** + * Generates random bytes. The bytes may be generated synchronously or + * asynchronously. Web workers must use the asynchronous interface or + * else the behavior is undefined. + * + * @param count the number of random bytes to generate. + * @param [callback(err, bytes)] called once the operation completes. + * + * @return count random bytes as a string. + */ + ctx.generate = function(count, callback) { + // do synchronously + if(!callback) { + return ctx.generateSync(count); + } + + // simple generator using counter-based CBC + var cipher = ctx.plugin.cipher; + var increment = ctx.plugin.increment; + var formatKey = ctx.plugin.formatKey; + var formatSeed = ctx.plugin.formatSeed; + var b = forge.util.createBuffer(); + + // paranoid deviation from Fortuna: + // reset key for every request to protect previously + // generated random bytes should the key be discovered; + // there is no 100ms based reseeding because of this + // forced reseed for every `generate` call + ctx.key = null; + + generate(); + + function generate(err) { + if(err) { + return callback(err); + } + + // sufficient bytes generated + if(b.length() >= count) { + return callback(null, b.getBytes(count)); + } + + // if amount of data generated is greater than 1 MiB, trigger reseed + if(ctx.generated > 0xfffff) { + ctx.key = null; + } + + if(ctx.key === null) { + // prevent stack overflow + return forge.util.nextTick(function() { + _reseed(generate); + }); + } + + // generate the random bytes + var bytes = cipher(ctx.key, ctx.seed); + ctx.generated += bytes.length; + b.putBytes(bytes); + + // generate bytes for a new key and seed + ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); + ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); + + forge.util.setImmediate(generate); + } + }; + + /** + * Generates random bytes synchronously. + * + * @param count the number of random bytes to generate. + * + * @return count random bytes as a string. + */ + ctx.generateSync = function(count) { + // simple generator using counter-based CBC + var cipher = ctx.plugin.cipher; + var increment = ctx.plugin.increment; + var formatKey = ctx.plugin.formatKey; + var formatSeed = ctx.plugin.formatSeed; + + // paranoid deviation from Fortuna: + // reset key for every request to protect previously + // generated random bytes should the key be discovered; + // there is no 100ms based reseeding because of this + // forced reseed for every `generateSync` call + ctx.key = null; + + var b = forge.util.createBuffer(); + while(b.length() < count) { + // if amount of data generated is greater than 1 MiB, trigger reseed + if(ctx.generated > 0xfffff) { + ctx.key = null; + } + + if(ctx.key === null) { + _reseedSync(); + } + + // generate the random bytes + var bytes = cipher(ctx.key, ctx.seed); + ctx.generated += bytes.length; + b.putBytes(bytes); + + // generate bytes for a new key and seed + ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); + ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); + } + + return b.getBytes(count); + }; + + /** + * Private function that asynchronously reseeds a generator. + * + * @param callback(err) called once the operation completes. + */ + function _reseed(callback) { + if(ctx.pools[0].messageLength >= 32) { + _seed(); + return callback(); + } + // not enough seed data... + var needed = (32 - ctx.pools[0].messageLength) << 5; + ctx.seedFile(needed, function(err, bytes) { + if(err) { + return callback(err); + } + ctx.collect(bytes); + _seed(); + callback(); + }); + } + + /** + * Private function that synchronously reseeds a generator. + */ + function _reseedSync() { + if(ctx.pools[0].messageLength >= 32) { + return _seed(); + } + // not enough seed data... + var needed = (32 - ctx.pools[0].messageLength) << 5; + ctx.collect(ctx.seedFileSync(needed)); + _seed(); + } + + /** + * Private function that seeds a generator once enough bytes are available. + */ + function _seed() { + // update reseed count + ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1; + + // goal is to update `key` via: + // key = hash(key + s) + // where 's' is all collected entropy from selected pools, then... + + // create a plugin-based message digest + var md = ctx.plugin.md.create(); + + // consume current key bytes + md.update(ctx.keyBytes); + + // digest the entropy of pools whose index k meet the + // condition 'n mod 2^k == 0' where n is the number of reseeds + var _2powK = 1; + for(var k = 0; k < 32; ++k) { + if(ctx.reseeds % _2powK === 0) { + md.update(ctx.pools[k].digest().getBytes()); + ctx.pools[k].start(); + } + _2powK = _2powK << 1; + } + + // get digest for key bytes + ctx.keyBytes = md.digest().getBytes(); + + // paranoid deviation from Fortuna: + // update `seed` via `seed = hash(key)` + // instead of initializing to zero once and only + // ever incrementing it + md.start(); + md.update(ctx.keyBytes); + var seedBytes = md.digest().getBytes(); + + // update state + ctx.key = ctx.plugin.formatKey(ctx.keyBytes); + ctx.seed = ctx.plugin.formatSeed(seedBytes); + ctx.generated = 0; + } + + /** + * The built-in default seedFile. This seedFile is used when entropy + * is needed immediately. + * + * @param needed the number of bytes that are needed. + * + * @return the random bytes. + */ + function defaultSeedFile(needed) { + // use window.crypto.getRandomValues strong source of entropy if available + var getRandomValues = null; + var globalScope = forge.util.globalScope; + var _crypto = globalScope.crypto || globalScope.msCrypto; + if(_crypto && _crypto.getRandomValues) { + getRandomValues = function(arr) { + return _crypto.getRandomValues(arr); + }; + } + + var b = forge.util.createBuffer(); + if(getRandomValues) { + while(b.length() < needed) { + // max byte length is 65536 before QuotaExceededError is thrown + // http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues + var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4); + var entropy = new Uint32Array(Math.floor(count)); + try { + getRandomValues(entropy); + for(var i = 0; i < entropy.length; ++i) { + b.putInt32(entropy[i]); + } + } catch(e) { + /* only ignore QuotaExceededError */ + if(!(typeof QuotaExceededError !== 'undefined' && + e instanceof QuotaExceededError)) { + throw e; + } + } + } + } + + // be sad and add some weak random data + if(b.length() < needed) { + /* Draws from Park-Miller "minimal standard" 31 bit PRNG, + implemented with David G. Carta's optimization: with 32 bit math + and without division (Public Domain). */ + var hi, lo, next; + var seed = Math.floor(Math.random() * 0x010000); + while(b.length() < needed) { + lo = 16807 * (seed & 0xFFFF); + hi = 16807 * (seed >> 16); + lo += (hi & 0x7FFF) << 16; + lo += hi >> 15; + lo = (lo & 0x7FFFFFFF) + (lo >> 31); + seed = lo & 0xFFFFFFFF; + + // consume lower 3 bytes of seed + for(var i = 0; i < 3; ++i) { + // throw in more pseudo random + next = seed >>> (i << 3); + next ^= Math.floor(Math.random() * 0x0100); + b.putByte(next & 0xFF); + } + } + } + + return b.getBytes(needed); + } + // initialize seed file APIs + if(_crypto) { + // use nodejs async API + ctx.seedFile = function(needed, callback) { + _crypto.randomBytes(needed, function(err, bytes) { + if(err) { + return callback(err); + } + callback(null, bytes.toString()); + }); + }; + // use nodejs sync API + ctx.seedFileSync = function(needed) { + return _crypto.randomBytes(needed).toString(); + }; + } else { + ctx.seedFile = function(needed, callback) { + try { + callback(null, defaultSeedFile(needed)); + } catch(e) { + callback(e); + } + }; + ctx.seedFileSync = defaultSeedFile; + } + + /** + * Adds entropy to a prng ctx's accumulator. + * + * @param bytes the bytes of entropy as a string. + */ + ctx.collect = function(bytes) { + // iterate over pools distributing entropy cyclically + var count = bytes.length; + for(var i = 0; i < count; ++i) { + ctx.pools[ctx.pool].update(bytes.substr(i, 1)); + ctx.pool = (ctx.pool === 31) ? 0 : ctx.pool + 1; + } + }; + + /** + * Collects an integer of n bits. + * + * @param i the integer entropy. + * @param n the number of bits in the integer. + */ + ctx.collectInt = function(i, n) { + var bytes = ''; + for(var x = 0; x < n; x += 8) { + bytes += String.fromCharCode((i >> x) & 0xFF); + } + ctx.collect(bytes); + }; + + /** + * Registers a Web Worker to receive immediate entropy from the main thread. + * This method is required until Web Workers can access the native crypto + * API. This method should be called twice for each created worker, once in + * the main thread, and once in the worker itself. + * + * @param worker the worker to register. + */ + ctx.registerWorker = function(worker) { + // worker receives random bytes + if(worker === self) { + ctx.seedFile = function(needed, callback) { + function listener(e) { + var data = e.data; + if(data.forge && data.forge.prng) { + self.removeEventListener('message', listener); + callback(data.forge.prng.err, data.forge.prng.bytes); + } + } + self.addEventListener('message', listener); + self.postMessage({forge: {prng: {needed: needed}}}); + }; + } else { + // main thread sends random bytes upon request + var listener = function(e) { + var data = e.data; + if(data.forge && data.forge.prng) { + ctx.seedFile(data.forge.prng.needed, function(err, bytes) { + worker.postMessage({forge: {prng: {err: err, bytes: bytes}}}); + }); + } + }; + // TODO: do we need to remove the event listener when the worker dies? + worker.addEventListener('message', listener); + } + }; + + return ctx; +}; diff --git a/node_modules/node-forge/lib/pss.js b/node_modules/node-forge/lib/pss.js new file mode 100644 index 0000000..2596693 --- /dev/null +++ b/node_modules/node-forge/lib/pss.js @@ -0,0 +1,241 @@ +/** + * Javascript implementation of PKCS#1 PSS signature padding. + * + * @author Stefan Siegl + * + * Copyright (c) 2012 Stefan Siegl + */ +var forge = require('./forge'); +require('./random'); +require('./util'); + +// shortcut for PSS API +var pss = module.exports = forge.pss = forge.pss || {}; + +/** + * Creates a PSS signature scheme object. + * + * There are several ways to provide a salt for encoding: + * + * 1. Specify the saltLength only and the built-in PRNG will generate it. + * 2. Specify the saltLength and a custom PRNG with 'getBytesSync' defined that + * will be used. + * 3. Specify the salt itself as a forge.util.ByteBuffer. + * + * @param options the options to use: + * md the message digest object to use, a forge md instance. + * mgf the mask generation function to use, a forge mgf instance. + * [saltLength] the length of the salt in octets. + * [prng] the pseudo-random number generator to use to produce a salt. + * [salt] the salt to use when encoding. + * + * @return a signature scheme object. + */ +pss.create = function(options) { + // backwards compatibility w/legacy args: hash, mgf, sLen + if(arguments.length === 3) { + options = { + md: arguments[0], + mgf: arguments[1], + saltLength: arguments[2] + }; + } + + var hash = options.md; + var mgf = options.mgf; + var hLen = hash.digestLength; + + var salt_ = options.salt || null; + if(typeof salt_ === 'string') { + // assume binary-encoded string + salt_ = forge.util.createBuffer(salt_); + } + + var sLen; + if('saltLength' in options) { + sLen = options.saltLength; + } else if(salt_ !== null) { + sLen = salt_.length(); + } else { + throw new Error('Salt length not specified or specific salt not given.'); + } + + if(salt_ !== null && salt_.length() !== sLen) { + throw new Error('Given salt length does not match length of given salt.'); + } + + var prng = options.prng || forge.random; + + var pssobj = {}; + + /** + * Encodes a PSS signature. + * + * This function implements EMSA-PSS-ENCODE as per RFC 3447, section 9.1.1. + * + * @param md the message digest object with the hash to sign. + * @param modsBits the length of the RSA modulus in bits. + * + * @return the encoded message as a binary-encoded string of length + * ceil((modBits - 1) / 8). + */ + pssobj.encode = function(md, modBits) { + var i; + var emBits = modBits - 1; + var emLen = Math.ceil(emBits / 8); + + /* 2. Let mHash = Hash(M), an octet string of length hLen. */ + var mHash = md.digest().getBytes(); + + /* 3. If emLen < hLen + sLen + 2, output "encoding error" and stop. */ + if(emLen < hLen + sLen + 2) { + throw new Error('Message is too long to encrypt.'); + } + + /* 4. Generate a random octet string salt of length sLen; if sLen = 0, + * then salt is the empty string. */ + var salt; + if(salt_ === null) { + salt = prng.getBytesSync(sLen); + } else { + salt = salt_.bytes(); + } + + /* 5. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt; */ + var m_ = new forge.util.ByteBuffer(); + m_.fillWithByte(0, 8); + m_.putBytes(mHash); + m_.putBytes(salt); + + /* 6. Let H = Hash(M'), an octet string of length hLen. */ + hash.start(); + hash.update(m_.getBytes()); + var h = hash.digest().getBytes(); + + /* 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2 + * zero octets. The length of PS may be 0. */ + var ps = new forge.util.ByteBuffer(); + ps.fillWithByte(0, emLen - sLen - hLen - 2); + + /* 8. Let DB = PS || 0x01 || salt; DB is an octet string of length + * emLen - hLen - 1. */ + ps.putByte(0x01); + ps.putBytes(salt); + var db = ps.getBytes(); + + /* 9. Let dbMask = MGF(H, emLen - hLen - 1). */ + var maskLen = emLen - hLen - 1; + var dbMask = mgf.generate(h, maskLen); + + /* 10. Let maskedDB = DB \xor dbMask. */ + var maskedDB = ''; + for(i = 0; i < maskLen; i++) { + maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i)); + } + + /* 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in + * maskedDB to zero. */ + var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF; + maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) + + maskedDB.substr(1); + + /* 12. Let EM = maskedDB || H || 0xbc. + * 13. Output EM. */ + return maskedDB + h + String.fromCharCode(0xbc); + }; + + /** + * Verifies a PSS signature. + * + * This function implements EMSA-PSS-VERIFY as per RFC 3447, section 9.1.2. + * + * @param mHash the message digest hash, as a binary-encoded string, to + * compare against the signature. + * @param em the encoded message, as a binary-encoded string + * (RSA decryption result). + * @param modsBits the length of the RSA modulus in bits. + * + * @return true if the signature was verified, false if not. + */ + pssobj.verify = function(mHash, em, modBits) { + var i; + var emBits = modBits - 1; + var emLen = Math.ceil(emBits / 8); + + /* c. Convert the message representative m to an encoded message EM + * of length emLen = ceil((modBits - 1) / 8) octets, where modBits + * is the length in bits of the RSA modulus n */ + em = em.substr(-emLen); + + /* 3. If emLen < hLen + sLen + 2, output "inconsistent" and stop. */ + if(emLen < hLen + sLen + 2) { + throw new Error('Inconsistent parameters to PSS signature verification.'); + } + + /* 4. If the rightmost octet of EM does not have hexadecimal value + * 0xbc, output "inconsistent" and stop. */ + if(em.charCodeAt(emLen - 1) !== 0xbc) { + throw new Error('Encoded message does not end in 0xBC.'); + } + + /* 5. Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and + * let H be the next hLen octets. */ + var maskLen = emLen - hLen - 1; + var maskedDB = em.substr(0, maskLen); + var h = em.substr(maskLen, hLen); + + /* 6. If the leftmost 8emLen - emBits bits of the leftmost octet in + * maskedDB are not all equal to zero, output "inconsistent" and stop. */ + var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF; + if((maskedDB.charCodeAt(0) & mask) !== 0) { + throw new Error('Bits beyond keysize not zero as expected.'); + } + + /* 7. Let dbMask = MGF(H, emLen - hLen - 1). */ + var dbMask = mgf.generate(h, maskLen); + + /* 8. Let DB = maskedDB \xor dbMask. */ + var db = ''; + for(i = 0; i < maskLen; i++) { + db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i)); + } + + /* 9. Set the leftmost 8emLen - emBits bits of the leftmost octet + * in DB to zero. */ + db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1); + + /* 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero + * or if the octet at position emLen - hLen - sLen - 1 (the leftmost + * position is "position 1") does not have hexadecimal value 0x01, + * output "inconsistent" and stop. */ + var checkLen = emLen - hLen - sLen - 2; + for(i = 0; i < checkLen; i++) { + if(db.charCodeAt(i) !== 0x00) { + throw new Error('Leftmost octets not zero as expected'); + } + } + + if(db.charCodeAt(checkLen) !== 0x01) { + throw new Error('Inconsistent PSS signature, 0x01 marker not found'); + } + + /* 11. Let salt be the last sLen octets of DB. */ + var salt = db.substr(-sLen); + + /* 12. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */ + var m_ = new forge.util.ByteBuffer(); + m_.fillWithByte(0, 8); + m_.putBytes(mHash); + m_.putBytes(salt); + + /* 13. Let H' = Hash(M'), an octet string of length hLen. */ + hash.start(); + hash.update(m_.getBytes()); + var h_ = hash.digest().getBytes(); + + /* 14. If H = H', output "consistent." Otherwise, output "inconsistent." */ + return h === h_; + }; + + return pssobj; +}; diff --git a/node_modules/node-forge/lib/random.js b/node_modules/node-forge/lib/random.js new file mode 100644 index 0000000..d4e4bea --- /dev/null +++ b/node_modules/node-forge/lib/random.js @@ -0,0 +1,191 @@ +/** + * An API for getting cryptographically-secure random bytes. The bytes are + * generated using the Fortuna algorithm devised by Bruce Schneier and + * Niels Ferguson. + * + * Getting strong random bytes is not yet easy to do in javascript. The only + * truish random entropy that can be collected is from the mouse, keyboard, or + * from timing with respect to page loads, etc. This generator makes a poor + * attempt at providing random bytes when those sources haven't yet provided + * enough entropy to initially seed or to reseed the PRNG. + * + * @author Dave Longley + * + * Copyright (c) 2009-2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./aes'); +require('./sha256'); +require('./prng'); +require('./util'); + +(function() { + +// forge.random already defined +if(forge.random && forge.random.getBytes) { + module.exports = forge.random; + return; +} + +(function(jQuery) { + +// the default prng plugin, uses AES-128 +var prng_aes = {}; +var _prng_aes_output = new Array(4); +var _prng_aes_buffer = forge.util.createBuffer(); +prng_aes.formatKey = function(key) { + // convert the key into 32-bit integers + var tmp = forge.util.createBuffer(key); + key = new Array(4); + key[0] = tmp.getInt32(); + key[1] = tmp.getInt32(); + key[2] = tmp.getInt32(); + key[3] = tmp.getInt32(); + + // return the expanded key + return forge.aes._expandKey(key, false); +}; +prng_aes.formatSeed = function(seed) { + // convert seed into 32-bit integers + var tmp = forge.util.createBuffer(seed); + seed = new Array(4); + seed[0] = tmp.getInt32(); + seed[1] = tmp.getInt32(); + seed[2] = tmp.getInt32(); + seed[3] = tmp.getInt32(); + return seed; +}; +prng_aes.cipher = function(key, seed) { + forge.aes._updateBlock(key, seed, _prng_aes_output, false); + _prng_aes_buffer.putInt32(_prng_aes_output[0]); + _prng_aes_buffer.putInt32(_prng_aes_output[1]); + _prng_aes_buffer.putInt32(_prng_aes_output[2]); + _prng_aes_buffer.putInt32(_prng_aes_output[3]); + return _prng_aes_buffer.getBytes(); +}; +prng_aes.increment = function(seed) { + // FIXME: do we care about carry or signed issues? + ++seed[3]; + return seed; +}; +prng_aes.md = forge.md.sha256; + +/** + * Creates a new PRNG. + */ +function spawnPrng() { + var ctx = forge.prng.create(prng_aes); + + /** + * Gets random bytes. If a native secure crypto API is unavailable, this + * method tries to make the bytes more unpredictable by drawing from data that + * can be collected from the user of the browser, eg: mouse movement. + * + * If a callback is given, this method will be called asynchronously. + * + * @param count the number of random bytes to get. + * @param [callback(err, bytes)] called once the operation completes. + * + * @return the random bytes in a string. + */ + ctx.getBytes = function(count, callback) { + return ctx.generate(count, callback); + }; + + /** + * Gets random bytes asynchronously. If a native secure crypto API is + * unavailable, this method tries to make the bytes more unpredictable by + * drawing from data that can be collected from the user of the browser, + * eg: mouse movement. + * + * @param count the number of random bytes to get. + * + * @return the random bytes in a string. + */ + ctx.getBytesSync = function(count) { + return ctx.generate(count); + }; + + return ctx; +} + +// create default prng context +var _ctx = spawnPrng(); + +// add other sources of entropy only if window.crypto.getRandomValues is not +// available -- otherwise this source will be automatically used by the prng +var getRandomValues = null; +var globalScope = forge.util.globalScope; +var _crypto = globalScope.crypto || globalScope.msCrypto; +if(_crypto && _crypto.getRandomValues) { + getRandomValues = function(arr) { + return _crypto.getRandomValues(arr); + }; +} + +if(forge.options.usePureJavaScript || + (!forge.util.isNodejs && !getRandomValues)) { + // if this is a web worker, do not use weak entropy, instead register to + // receive strong entropy asynchronously from the main thread + if(typeof window === 'undefined' || window.document === undefined) { + // FIXME: + } + + // get load time entropy + _ctx.collectInt(+new Date(), 32); + + // add some entropy from navigator object + if(typeof(navigator) !== 'undefined') { + var _navBytes = ''; + for(var key in navigator) { + try { + if(typeof(navigator[key]) == 'string') { + _navBytes += navigator[key]; + } + } catch(e) { + /* Some navigator keys might not be accessible, e.g. the geolocation + attribute throws an exception if touched in Mozilla chrome:// + context. + + Silently ignore this and just don't use this as a source of + entropy. */ + } + } + _ctx.collect(_navBytes); + _navBytes = null; + } + + // add mouse and keyboard collectors if jquery is available + if(jQuery) { + // set up mouse entropy capture + jQuery().mousemove(function(e) { + // add mouse coords + _ctx.collectInt(e.clientX, 16); + _ctx.collectInt(e.clientY, 16); + }); + + // set up keyboard entropy capture + jQuery().keypress(function(e) { + _ctx.collectInt(e.charCode, 8); + }); + } +} + +/* Random API */ +if(!forge.random) { + forge.random = _ctx; +} else { + // extend forge.random with _ctx + for(var key in _ctx) { + forge.random[key] = _ctx[key]; + } +} + +// expose spawn PRNG +forge.random.createInstance = spawnPrng; + +module.exports = forge.random; + +})(typeof(jQuery) !== 'undefined' ? jQuery : null); + +})(); diff --git a/node_modules/node-forge/lib/rc2.js b/node_modules/node-forge/lib/rc2.js new file mode 100644 index 0000000..e33f78a --- /dev/null +++ b/node_modules/node-forge/lib/rc2.js @@ -0,0 +1,410 @@ +/** + * RC2 implementation. + * + * @author Stefan Siegl + * + * Copyright (c) 2012 Stefan Siegl + * + * Information on the RC2 cipher is available from RFC #2268, + * http://www.ietf.org/rfc/rfc2268.txt + */ +var forge = require('./forge'); +require('./util'); + +var piTable = [ + 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d, + 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2, + 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32, + 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82, + 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc, + 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26, + 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03, + 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7, + 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a, + 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec, + 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39, + 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31, + 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9, + 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9, + 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e, + 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad +]; + +var s = [1, 2, 3, 5]; + +/** + * Rotate a word left by given number of bits. + * + * Bits that are shifted out on the left are put back in on the right + * hand side. + * + * @param word The word to shift left. + * @param bits The number of bits to shift by. + * @return The rotated word. + */ +var rol = function(word, bits) { + return ((word << bits) & 0xffff) | ((word & 0xffff) >> (16 - bits)); +}; + +/** + * Rotate a word right by given number of bits. + * + * Bits that are shifted out on the right are put back in on the left + * hand side. + * + * @param word The word to shift right. + * @param bits The number of bits to shift by. + * @return The rotated word. + */ +var ror = function(word, bits) { + return ((word & 0xffff) >> bits) | ((word << (16 - bits)) & 0xffff); +}; + +/* RC2 API */ +module.exports = forge.rc2 = forge.rc2 || {}; + +/** + * Perform RC2 key expansion as per RFC #2268, section 2. + * + * @param key variable-length user key (between 1 and 128 bytes) + * @param effKeyBits number of effective key bits (default: 128) + * @return the expanded RC2 key (ByteBuffer of 128 bytes) + */ +forge.rc2.expandKey = function(key, effKeyBits) { + if(typeof key === 'string') { + key = forge.util.createBuffer(key); + } + effKeyBits = effKeyBits || 128; + + /* introduce variables that match the names used in RFC #2268 */ + var L = key; + var T = key.length(); + var T1 = effKeyBits; + var T8 = Math.ceil(T1 / 8); + var TM = 0xff >> (T1 & 0x07); + var i; + + for(i = T; i < 128; i++) { + L.putByte(piTable[(L.at(i - 1) + L.at(i - T)) & 0xff]); + } + + L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]); + + for(i = 127 - T8; i >= 0; i--) { + L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]); + } + + return L; +}; + +/** + * Creates a RC2 cipher object. + * + * @param key the symmetric key to use (as base for key generation). + * @param bits the number of effective key bits. + * @param encrypt false for decryption, true for encryption. + * + * @return the cipher. + */ +var createCipher = function(key, bits, encrypt) { + var _finish = false, _input = null, _output = null, _iv = null; + var mixRound, mashRound; + var i, j, K = []; + + /* Expand key and fill into K[] Array */ + key = forge.rc2.expandKey(key, bits); + for(i = 0; i < 64; i++) { + K.push(key.getInt16Le()); + } + + if(encrypt) { + /** + * Perform one mixing round "in place". + * + * @param R Array of four words to perform mixing on. + */ + mixRound = function(R) { + for(i = 0; i < 4; i++) { + R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + + ((~R[(i + 3) % 4]) & R[(i + 1) % 4]); + R[i] = rol(R[i], s[i]); + j++; + } + }; + + /** + * Perform one mashing round "in place". + * + * @param R Array of four words to perform mashing on. + */ + mashRound = function(R) { + for(i = 0; i < 4; i++) { + R[i] += K[R[(i + 3) % 4] & 63]; + } + }; + } else { + /** + * Perform one r-mixing round "in place". + * + * @param R Array of four words to perform mixing on. + */ + mixRound = function(R) { + for(i = 3; i >= 0; i--) { + R[i] = ror(R[i], s[i]); + R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + + ((~R[(i + 3) % 4]) & R[(i + 1) % 4]); + j--; + } + }; + + /** + * Perform one r-mashing round "in place". + * + * @param R Array of four words to perform mashing on. + */ + mashRound = function(R) { + for(i = 3; i >= 0; i--) { + R[i] -= K[R[(i + 3) % 4] & 63]; + } + }; + } + + /** + * Run the specified cipher execution plan. + * + * This function takes four words from the input buffer, applies the IV on + * it (if requested) and runs the provided execution plan. + * + * The plan must be put together in form of a array of arrays. Where the + * outer one is simply a list of steps to perform and the inner one needs + * to have two elements: the first one telling how many rounds to perform, + * the second one telling what to do (i.e. the function to call). + * + * @param {Array} plan The plan to execute. + */ + var runPlan = function(plan) { + var R = []; + + /* Get data from input buffer and fill the four words into R */ + for(i = 0; i < 4; i++) { + var val = _input.getInt16Le(); + + if(_iv !== null) { + if(encrypt) { + /* We're encrypting, apply the IV first. */ + val ^= _iv.getInt16Le(); + } else { + /* We're decryption, keep cipher text for next block. */ + _iv.putInt16Le(val); + } + } + + R.push(val & 0xffff); + } + + /* Reset global "j" variable as per spec. */ + j = encrypt ? 0 : 63; + + /* Run execution plan. */ + for(var ptr = 0; ptr < plan.length; ptr++) { + for(var ctr = 0; ctr < plan[ptr][0]; ctr++) { + plan[ptr][1](R); + } + } + + /* Write back result to output buffer. */ + for(i = 0; i < 4; i++) { + if(_iv !== null) { + if(encrypt) { + /* We're encrypting in CBC-mode, feed back encrypted bytes into + IV buffer to carry it forward to next block. */ + _iv.putInt16Le(R[i]); + } else { + R[i] ^= _iv.getInt16Le(); + } + } + + _output.putInt16Le(R[i]); + } + }; + + /* Create cipher object */ + var cipher = null; + cipher = { + /** + * Starts or restarts the encryption or decryption process, whichever + * was previously configured. + * + * To use the cipher in CBC mode, iv may be given either as a string + * of bytes, or as a byte buffer. For ECB mode, give null as iv. + * + * @param iv the initialization vector to use, null for ECB mode. + * @param output the output the buffer to write to, null to create one. + */ + start: function(iv, output) { + if(iv) { + /* CBC mode */ + if(typeof iv === 'string') { + iv = forge.util.createBuffer(iv); + } + } + + _finish = false; + _input = forge.util.createBuffer(); + _output = output || new forge.util.createBuffer(); + _iv = iv; + + cipher.output = _output; + }, + + /** + * Updates the next block. + * + * @param input the buffer to read from. + */ + update: function(input) { + if(!_finish) { + // not finishing, so fill the input buffer with more input + _input.putBuffer(input); + } + + while(_input.length() >= 8) { + runPlan([ + [ 5, mixRound ], + [ 1, mashRound ], + [ 6, mixRound ], + [ 1, mashRound ], + [ 5, mixRound ] + ]); + } + }, + + /** + * Finishes encrypting or decrypting. + * + * @param pad a padding function to use, null for PKCS#7 padding, + * signature(blockSize, buffer, decrypt). + * + * @return true if successful, false on error. + */ + finish: function(pad) { + var rval = true; + + if(encrypt) { + if(pad) { + rval = pad(8, _input, !encrypt); + } else { + // add PKCS#7 padding to block (each pad byte is the + // value of the number of pad bytes) + var padding = (_input.length() === 8) ? 8 : (8 - _input.length()); + _input.fillWithByte(padding, padding); + } + } + + if(rval) { + // do final update + _finish = true; + cipher.update(); + } + + if(!encrypt) { + // check for error: input data not a multiple of block size + rval = (_input.length() === 0); + if(rval) { + if(pad) { + rval = pad(8, _output, !encrypt); + } else { + // ensure padding byte count is valid + var len = _output.length(); + var count = _output.at(len - 1); + + if(count > len) { + rval = false; + } else { + // trim off padding bytes + _output.truncate(count); + } + } + } + } + + return rval; + } + }; + + return cipher; +}; + +/** + * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the + * given symmetric key. The output will be stored in the 'output' member + * of the returned cipher. + * + * The key and iv may be given as a string of bytes or a byte buffer. + * The cipher is initialized to use 128 effective key bits. + * + * @param key the symmetric key to use. + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * + * @return the cipher. + */ +forge.rc2.startEncrypting = function(key, iv, output) { + var cipher = forge.rc2.createEncryptionCipher(key, 128); + cipher.start(iv, output); + return cipher; +}; + +/** + * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the + * given symmetric key. + * + * The key may be given as a string of bytes or a byte buffer. + * + * To start encrypting call start() on the cipher with an iv and optional + * output buffer. + * + * @param key the symmetric key to use. + * + * @return the cipher. + */ +forge.rc2.createEncryptionCipher = function(key, bits) { + return createCipher(key, bits, true); +}; + +/** + * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the + * given symmetric key. The output will be stored in the 'output' member + * of the returned cipher. + * + * The key and iv may be given as a string of bytes or a byte buffer. + * The cipher is initialized to use 128 effective key bits. + * + * @param key the symmetric key to use. + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * + * @return the cipher. + */ +forge.rc2.startDecrypting = function(key, iv, output) { + var cipher = forge.rc2.createDecryptionCipher(key, 128); + cipher.start(iv, output); + return cipher; +}; + +/** + * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the + * given symmetric key. + * + * The key may be given as a string of bytes or a byte buffer. + * + * To start decrypting call start() on the cipher with an iv and optional + * output buffer. + * + * @param key the symmetric key to use. + * + * @return the cipher. + */ +forge.rc2.createDecryptionCipher = function(key, bits) { + return createCipher(key, bits, false); +}; diff --git a/node_modules/node-forge/lib/rsa.js b/node_modules/node-forge/lib/rsa.js new file mode 100644 index 0000000..b207a63 --- /dev/null +++ b/node_modules/node-forge/lib/rsa.js @@ -0,0 +1,1949 @@ +/** + * Javascript implementation of basic RSA algorithms. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + * + * The only algorithm currently supported for PKI is RSA. + * + * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo + * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier + * and a subjectPublicKey of type bit string. + * + * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters + * for the algorithm, if any. In the case of RSA, there aren't any. + * + * SubjectPublicKeyInfo ::= SEQUENCE { + * algorithm AlgorithmIdentifier, + * subjectPublicKey BIT STRING + * } + * + * AlgorithmIdentifer ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters ANY DEFINED BY algorithm OPTIONAL + * } + * + * For an RSA public key, the subjectPublicKey is: + * + * RSAPublicKey ::= SEQUENCE { + * modulus INTEGER, -- n + * publicExponent INTEGER -- e + * } + * + * PrivateKeyInfo ::= SEQUENCE { + * version Version, + * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, + * privateKey PrivateKey, + * attributes [0] IMPLICIT Attributes OPTIONAL + * } + * + * Version ::= INTEGER + * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier + * PrivateKey ::= OCTET STRING + * Attributes ::= SET OF Attribute + * + * An RSA private key as the following structure: + * + * RSAPrivateKey ::= SEQUENCE { + * version Version, + * modulus INTEGER, -- n + * publicExponent INTEGER, -- e + * privateExponent INTEGER, -- d + * prime1 INTEGER, -- p + * prime2 INTEGER, -- q + * exponent1 INTEGER, -- d mod (p-1) + * exponent2 INTEGER, -- d mod (q-1) + * coefficient INTEGER -- (inverse of q) mod p + * } + * + * Version ::= INTEGER + * + * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1 + */ +var forge = require('./forge'); +require('./asn1'); +require('./jsbn'); +require('./oids'); +require('./pkcs1'); +require('./prime'); +require('./random'); +require('./util'); + +if(typeof BigInteger === 'undefined') { + var BigInteger = forge.jsbn.BigInteger; +} + +var _crypto = forge.util.isNodejs ? require('crypto') : null; + +// shortcut for asn.1 API +var asn1 = forge.asn1; + +// shortcut for util API +var util = forge.util; + +/* + * RSA encryption and decryption, see RFC 2313. + */ +forge.pki = forge.pki || {}; +module.exports = forge.pki.rsa = forge.rsa = forge.rsa || {}; +var pki = forge.pki; + +// for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29 +var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; + +// validator for a PrivateKeyInfo structure +var privateKeyValidator = { + // PrivateKeyInfo + name: 'PrivateKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // Version (INTEGER) + name: 'PrivateKeyInfo.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyVersion' + }, { + // privateKeyAlgorithm + name: 'PrivateKeyInfo.privateKeyAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'privateKeyOid' + }] + }, { + // PrivateKey + name: 'PrivateKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'privateKey' + }] +}; + +// validator for an RSA private key +var rsaPrivateKeyValidator = { + // RSAPrivateKey + name: 'RSAPrivateKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // Version (INTEGER) + name: 'RSAPrivateKey.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyVersion' + }, { + // modulus (n) + name: 'RSAPrivateKey.modulus', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyModulus' + }, { + // publicExponent (e) + name: 'RSAPrivateKey.publicExponent', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyPublicExponent' + }, { + // privateExponent (d) + name: 'RSAPrivateKey.privateExponent', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyPrivateExponent' + }, { + // prime1 (p) + name: 'RSAPrivateKey.prime1', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyPrime1' + }, { + // prime2 (q) + name: 'RSAPrivateKey.prime2', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyPrime2' + }, { + // exponent1 (d mod (p-1)) + name: 'RSAPrivateKey.exponent1', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyExponent1' + }, { + // exponent2 (d mod (q-1)) + name: 'RSAPrivateKey.exponent2', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyExponent2' + }, { + // coefficient ((inverse of q) mod p) + name: 'RSAPrivateKey.coefficient', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyCoefficient' + }] +}; + +// validator for an RSA public key +var rsaPublicKeyValidator = { + // RSAPublicKey + name: 'RSAPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // modulus (n) + name: 'RSAPublicKey.modulus', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'publicKeyModulus' + }, { + // publicExponent (e) + name: 'RSAPublicKey.exponent', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'publicKeyExponent' + }] +}; + +// validator for an SubjectPublicKeyInfo structure +// Note: Currently only works with an RSA public key +var publicKeyValidator = forge.pki.rsa.publicKeyValidator = { + name: 'SubjectPublicKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'subjectPublicKeyInfo', + value: [{ + name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'publicKeyOid' + }] + }, { + // subjectPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + value: [{ + // RSAPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: 'rsaPublicKey' + }] + }] +}; + +// validator for a DigestInfo structure +var digestInfoValidator = { + name: 'DigestInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'DigestInfo.DigestAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'DigestInfo.DigestAlgorithm.algorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'algorithmIdentifier' + }, { + // NULL parameters + name: 'DigestInfo.DigestAlgorithm.parameters', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.NULL, + // captured only to check existence for md2 and md5 + capture: 'parameters', + optional: true, + constructed: false + }] + }, { + // digest + name: 'DigestInfo.digest', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'digest' + }] +}; + +/** + * Wrap digest in DigestInfo object. + * + * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447. + * + * DigestInfo ::= SEQUENCE { + * digestAlgorithm DigestAlgorithmIdentifier, + * digest Digest + * } + * + * DigestAlgorithmIdentifier ::= AlgorithmIdentifier + * Digest ::= OCTET STRING + * + * @param md the message digest object with the hash to sign. + * + * @return the encoded message (ready for RSA encryption) + */ +var emsaPkcs1v15encode = function(md) { + // get the oid for the algorithm + var oid; + if(md.algorithm in pki.oids) { + oid = pki.oids[md.algorithm]; + } else { + var error = new Error('Unknown message digest algorithm.'); + error.algorithm = md.algorithm; + throw error; + } + var oidBytes = asn1.oidToDer(oid).getBytes(); + + // create the digest info + var digestInfo = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var digestAlgorithm = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + digestAlgorithm.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes)); + digestAlgorithm.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')); + var digest = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, + false, md.digest().getBytes()); + digestInfo.value.push(digestAlgorithm); + digestInfo.value.push(digest); + + // encode digest info + return asn1.toDer(digestInfo).getBytes(); +}; + +/** + * Performs x^c mod n (RSA encryption or decryption operation). + * + * @param x the number to raise and mod. + * @param key the key to use. + * @param pub true if the key is public, false if private. + * + * @return the result of x^c mod n. + */ +var _modPow = function(x, key, pub) { + if(pub) { + return x.modPow(key.e, key.n); + } + + if(!key.p || !key.q) { + // allow calculation without CRT params (slow) + return x.modPow(key.d, key.n); + } + + // pre-compute dP, dQ, and qInv if necessary + if(!key.dP) { + key.dP = key.d.mod(key.p.subtract(BigInteger.ONE)); + } + if(!key.dQ) { + key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE)); + } + if(!key.qInv) { + key.qInv = key.q.modInverse(key.p); + } + + /* Chinese remainder theorem (CRT) states: + + Suppose n1, n2, ..., nk are positive integers which are pairwise + coprime (n1 and n2 have no common factors other than 1). For any + integers x1, x2, ..., xk there exists an integer x solving the + system of simultaneous congruences (where ~= means modularly + congruent so a ~= b mod n means a mod n = b mod n): + + x ~= x1 mod n1 + x ~= x2 mod n2 + ... + x ~= xk mod nk + + This system of congruences has a single simultaneous solution x + between 0 and n - 1. Furthermore, each xk solution and x itself + is congruent modulo the product n = n1*n2*...*nk. + So x1 mod n = x2 mod n = xk mod n = x mod n. + + The single simultaneous solution x can be solved with the following + equation: + + x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni. + + Where x is less than n, xi = x mod ni. + + For RSA we are only concerned with k = 2. The modulus n = pq, where + p and q are coprime. The RSA decryption algorithm is: + + y = x^d mod n + + Given the above: + + x1 = x^d mod p + r1 = n/p = q + s1 = q^-1 mod p + x2 = x^d mod q + r2 = n/q = p + s2 = p^-1 mod q + + So y = (x1r1s1 + x2r2s2) mod n + = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n + + According to Fermat's Little Theorem, if the modulus P is prime, + for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P. + Since A is not divisible by P it follows that if: + N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore: + + A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort + to calculate). In order to calculate x^d mod p more quickly the + exponent d mod (p - 1) is stored in the RSA private key (the same + is done for x^d mod q). These values are referred to as dP and dQ + respectively. Therefore we now have: + + y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n + + Since we'll be reducing x^dP by modulo p (same for q) we can also + reduce x by p (and q respectively) before hand. Therefore, let + + xp = ((x mod p)^dP mod p), and + xq = ((x mod q)^dQ mod q), yielding: + + y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n + + This can be further reduced to a simple algorithm that only + requires 1 inverse (the q inverse is used) to be used and stored. + The algorithm is called Garner's algorithm. If qInv is the + inverse of q, we simply calculate: + + y = (qInv*(xp - xq) mod p) * q + xq + + However, there are two further complications. First, we need to + ensure that xp > xq to prevent signed BigIntegers from being used + so we add p until this is true (since we will be mod'ing with + p anyway). Then, there is a known timing attack on algorithms + using the CRT. To mitigate this risk, "cryptographic blinding" + should be used. This requires simply generating a random number r + between 0 and n-1 and its inverse and multiplying x by r^e before + calculating y and then multiplying y by r^-1 afterwards. Note that + r must be coprime with n (gcd(r, n) === 1) in order to have an + inverse. + */ + + // cryptographic blinding + var r; + do { + r = new BigInteger( + forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)), + 16); + } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE)); + x = x.multiply(r.modPow(key.e, key.n)).mod(key.n); + + // calculate xp and xq + var xp = x.mod(key.p).modPow(key.dP, key.p); + var xq = x.mod(key.q).modPow(key.dQ, key.q); + + // xp must be larger than xq to avoid signed bit usage + while(xp.compareTo(xq) < 0) { + xp = xp.add(key.p); + } + + // do last step + var y = xp.subtract(xq) + .multiply(key.qInv).mod(key.p) + .multiply(key.q).add(xq); + + // remove effect of random for cryptographic blinding + y = y.multiply(r.modInverse(key.n)).mod(key.n); + + return y; +}; + +/** + * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or + * 'encrypt' on a public key object instead. + * + * Performs RSA encryption. + * + * The parameter bt controls whether to put padding bytes before the + * message passed in. Set bt to either true or false to disable padding + * completely (in order to handle e.g. EMSA-PSS encoding separately before), + * signaling whether the encryption operation is a public key operation + * (i.e. encrypting data) or not, i.e. private key operation (data signing). + * + * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01 + * (for signing) or 0x02 (for encryption). The key operation mode (private + * or public) is derived from this flag in that case). + * + * @param m the message to encrypt as a byte string. + * @param key the RSA key to use. + * @param bt for PKCS#1 v1.5 padding, the block type to use + * (0x01 for private key, 0x02 for public), + * to disable padding: true = public key, false = private key. + * + * @return the encrypted bytes as a string. + */ +pki.rsa.encrypt = function(m, key, bt) { + var pub = bt; + var eb; + + // get the length of the modulus in bytes + var k = Math.ceil(key.n.bitLength() / 8); + + if(bt !== false && bt !== true) { + // legacy, default to PKCS#1 v1.5 padding + pub = (bt === 0x02); + eb = _encodePkcs1_v1_5(m, key, bt); + } else { + eb = forge.util.createBuffer(); + eb.putBytes(m); + } + + // load encryption block as big integer 'x' + // FIXME: hex conversion inefficient, get BigInteger w/byte strings + var x = new BigInteger(eb.toHex(), 16); + + // do RSA encryption + var y = _modPow(x, key, pub); + + // convert y into the encrypted data byte string, if y is shorter in + // bytes than k, then prepend zero bytes to fill up ed + // FIXME: hex conversion inefficient, get BigInteger w/byte strings + var yhex = y.toString(16); + var ed = forge.util.createBuffer(); + var zeros = k - Math.ceil(yhex.length / 2); + while(zeros > 0) { + ed.putByte(0x00); + --zeros; + } + ed.putBytes(forge.util.hexToBytes(yhex)); + return ed.getBytes(); +}; + +/** + * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or + * 'verify' on a public key object instead. + * + * Performs RSA decryption. + * + * The parameter ml controls whether to apply PKCS#1 v1.5 padding + * or not. Set ml = false to disable padding removal completely + * (in order to handle e.g. EMSA-PSS later on) and simply pass back + * the RSA encryption block. + * + * @param ed the encrypted data to decrypt in as a byte string. + * @param key the RSA key to use. + * @param pub true for a public key operation, false for private. + * @param ml the message length, if known, false to disable padding. + * + * @return the decrypted message as a byte string. + */ +pki.rsa.decrypt = function(ed, key, pub, ml) { + // get the length of the modulus in bytes + var k = Math.ceil(key.n.bitLength() / 8); + + // error if the length of the encrypted data ED is not k + if(ed.length !== k) { + var error = new Error('Encrypted message length is invalid.'); + error.length = ed.length; + error.expected = k; + throw error; + } + + // convert encrypted data into a big integer + // FIXME: hex conversion inefficient, get BigInteger w/byte strings + var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16); + + // y must be less than the modulus or it wasn't the result of + // a previous mod operation (encryption) using that modulus + if(y.compareTo(key.n) >= 0) { + throw new Error('Encrypted message is invalid.'); + } + + // do RSA decryption + var x = _modPow(y, key, pub); + + // create the encryption block, if x is shorter in bytes than k, then + // prepend zero bytes to fill up eb + // FIXME: hex conversion inefficient, get BigInteger w/byte strings + var xhex = x.toString(16); + var eb = forge.util.createBuffer(); + var zeros = k - Math.ceil(xhex.length / 2); + while(zeros > 0) { + eb.putByte(0x00); + --zeros; + } + eb.putBytes(forge.util.hexToBytes(xhex)); + + if(ml !== false) { + // legacy, default to PKCS#1 v1.5 padding + return _decodePkcs1_v1_5(eb.getBytes(), key, pub); + } + + // return message + return eb.getBytes(); +}; + +/** + * Creates an RSA key-pair generation state object. It is used to allow + * key-generation to be performed in steps. It also allows for a UI to + * display progress updates. + * + * @param bits the size for the private key in bits, defaults to 2048. + * @param e the public exponent to use, defaults to 65537 (0x10001). + * @param [options] the options to use. + * prng a custom crypto-secure pseudo-random number generator to use, + * that must define "getBytesSync". + * algorithm the algorithm to use (default: 'PRIMEINC'). + * + * @return the state object to use to generate the key-pair. + */ +pki.rsa.createKeyPairGenerationState = function(bits, e, options) { + // TODO: migrate step-based prime generation code to forge.prime + + // set default bits + if(typeof(bits) === 'string') { + bits = parseInt(bits, 10); + } + bits = bits || 2048; + + // create prng with api that matches BigInteger secure random + options = options || {}; + var prng = options.prng || forge.random; + var rng = { + // x is an array to fill with bytes + nextBytes: function(x) { + var b = prng.getBytesSync(x.length); + for(var i = 0; i < x.length; ++i) { + x[i] = b.charCodeAt(i); + } + } + }; + + var algorithm = options.algorithm || 'PRIMEINC'; + + // create PRIMEINC algorithm state + var rval; + if(algorithm === 'PRIMEINC') { + rval = { + algorithm: algorithm, + state: 0, + bits: bits, + rng: rng, + eInt: e || 65537, + e: new BigInteger(null), + p: null, + q: null, + qBits: bits >> 1, + pBits: bits - (bits >> 1), + pqState: 0, + num: null, + keys: null + }; + rval.e.fromInt(rval.eInt); + } else { + throw new Error('Invalid key generation algorithm: ' + algorithm); + } + + return rval; +}; + +/** + * Attempts to runs the key-generation algorithm for at most n seconds + * (approximately) using the given state. When key-generation has completed, + * the keys will be stored in state.keys. + * + * To use this function to update a UI while generating a key or to prevent + * causing browser lockups/warnings, set "n" to a value other than 0. A + * simple pattern for generating a key and showing a progress indicator is: + * + * var state = pki.rsa.createKeyPairGenerationState(2048); + * var step = function() { + * // step key-generation, run algorithm for 100 ms, repeat + * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) { + * setTimeout(step, 1); + * } else { + * // key-generation complete + * // TODO: turn off progress indicator here + * // TODO: use the generated key-pair in "state.keys" + * } + * }; + * // TODO: turn on progress indicator here + * setTimeout(step, 0); + * + * @param state the state to use. + * @param n the maximum number of milliseconds to run the algorithm for, 0 + * to run the algorithm to completion. + * + * @return true if the key-generation completed, false if not. + */ +pki.rsa.stepKeyPairGenerationState = function(state, n) { + // set default algorithm if not set + if(!('algorithm' in state)) { + state.algorithm = 'PRIMEINC'; + } + + // TODO: migrate step-based prime generation code to forge.prime + // TODO: abstract as PRIMEINC algorithm + + // do key generation (based on Tom Wu's rsa.js, see jsbn.js license) + // with some minor optimizations and designed to run in steps + + // local state vars + var THIRTY = new BigInteger(null); + THIRTY.fromInt(30); + var deltaIdx = 0; + var op_or = function(x, y) {return x | y;}; + + // keep stepping until time limit is reached or done + var t1 = +new Date(); + var t2; + var total = 0; + while(state.keys === null && (n <= 0 || total < n)) { + // generate p or q + if(state.state === 0) { + /* Note: All primes are of the form: + + 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i + + When we generate a random number, we always align it at 30k + 1. Each + time the number is determined not to be prime we add to get to the + next 'i', eg: if the number was at 30k + 1 we add 6. */ + var bits = (state.p === null) ? state.pBits : state.qBits; + var bits1 = bits - 1; + + // get a random number + if(state.pqState === 0) { + state.num = new BigInteger(bits, state.rng); + // force MSB set + if(!state.num.testBit(bits1)) { + state.num.bitwiseTo( + BigInteger.ONE.shiftLeft(bits1), op_or, state.num); + } + // align number on 30k+1 boundary + state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0); + deltaIdx = 0; + + ++state.pqState; + } else if(state.pqState === 1) { + // try to make the number a prime + if(state.num.bitLength() > bits) { + // overflow, try again + state.pqState = 0; + // do primality test + } else if(state.num.isProbablePrime( + _getMillerRabinTests(state.num.bitLength()))) { + ++state.pqState; + } else { + // get next potential prime + state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); + } + } else if(state.pqState === 2) { + // ensure number is coprime with e + state.pqState = + (state.num.subtract(BigInteger.ONE).gcd(state.e) + .compareTo(BigInteger.ONE) === 0) ? 3 : 0; + } else if(state.pqState === 3) { + // store p or q + state.pqState = 0; + if(state.p === null) { + state.p = state.num; + } else { + state.q = state.num; + } + + // advance state if both p and q are ready + if(state.p !== null && state.q !== null) { + ++state.state; + } + state.num = null; + } + } else if(state.state === 1) { + // ensure p is larger than q (swap them if not) + if(state.p.compareTo(state.q) < 0) { + state.num = state.p; + state.p = state.q; + state.q = state.num; + } + ++state.state; + } else if(state.state === 2) { + // compute phi: (p - 1)(q - 1) (Euler's totient function) + state.p1 = state.p.subtract(BigInteger.ONE); + state.q1 = state.q.subtract(BigInteger.ONE); + state.phi = state.p1.multiply(state.q1); + ++state.state; + } else if(state.state === 3) { + // ensure e and phi are coprime + if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) { + // phi and e are coprime, advance + ++state.state; + } else { + // phi and e aren't coprime, so generate a new p and q + state.p = null; + state.q = null; + state.state = 0; + } + } else if(state.state === 4) { + // create n, ensure n is has the right number of bits + state.n = state.p.multiply(state.q); + + // ensure n is right number of bits + if(state.n.bitLength() === state.bits) { + // success, advance + ++state.state; + } else { + // failed, get new q + state.q = null; + state.state = 0; + } + } else if(state.state === 5) { + // set keys + var d = state.e.modInverse(state.phi); + state.keys = { + privateKey: pki.rsa.setPrivateKey( + state.n, state.e, d, state.p, state.q, + d.mod(state.p1), d.mod(state.q1), + state.q.modInverse(state.p)), + publicKey: pki.rsa.setPublicKey(state.n, state.e) + }; + } + + // update timing + t2 = +new Date(); + total += t2 - t1; + t1 = t2; + } + + return state.keys !== null; +}; + +/** + * Generates an RSA public-private key pair in a single call. + * + * To generate a key-pair in steps (to allow for progress updates and to + * prevent blocking or warnings in slow browsers) then use the key-pair + * generation state functions. + * + * To generate a key-pair asynchronously (either through web-workers, if + * available, or by breaking up the work on the main thread), pass a + * callback function. + * + * @param [bits] the size for the private key in bits, defaults to 2048. + * @param [e] the public exponent to use, defaults to 65537. + * @param [options] options for key-pair generation, if given then 'bits' + * and 'e' must *not* be given: + * bits the size for the private key in bits, (default: 2048). + * e the public exponent to use, (default: 65537 (0x10001)). + * workerScript the worker script URL. + * workers the number of web workers (if supported) to use, + * (default: 2). + * workLoad the size of the work load, ie: number of possible prime + * numbers for each web worker to check per work assignment, + * (default: 100). + * prng a custom crypto-secure pseudo-random number generator to use, + * that must define "getBytesSync". Disables use of native APIs. + * algorithm the algorithm to use (default: 'PRIMEINC'). + * @param [callback(err, keypair)] called once the operation completes. + * + * @return an object with privateKey and publicKey properties. + */ +pki.rsa.generateKeyPair = function(bits, e, options, callback) { + // (bits), (options), (callback) + if(arguments.length === 1) { + if(typeof bits === 'object') { + options = bits; + bits = undefined; + } else if(typeof bits === 'function') { + callback = bits; + bits = undefined; + } + } else if(arguments.length === 2) { + // (bits, e), (bits, options), (bits, callback), (options, callback) + if(typeof bits === 'number') { + if(typeof e === 'function') { + callback = e; + e = undefined; + } else if(typeof e !== 'number') { + options = e; + e = undefined; + } + } else { + options = bits; + callback = e; + bits = undefined; + e = undefined; + } + } else if(arguments.length === 3) { + // (bits, e, options), (bits, e, callback), (bits, options, callback) + if(typeof e === 'number') { + if(typeof options === 'function') { + callback = options; + options = undefined; + } + } else { + callback = options; + options = e; + e = undefined; + } + } + options = options || {}; + if(bits === undefined) { + bits = options.bits || 2048; + } + if(e === undefined) { + e = options.e || 0x10001; + } + + // use native code if permitted, available, and parameters are acceptable + if(!forge.options.usePureJavaScript && !options.prng && + bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) { + if(callback) { + // try native async + if(_detectNodeCrypto('generateKeyPair')) { + return _crypto.generateKeyPair('rsa', { + modulusLength: bits, + publicExponent: e, + publicKeyEncoding: { + type: 'spki', + format: 'pem' + }, + privateKeyEncoding: { + type: 'pkcs8', + format: 'pem' + } + }, function(err, pub, priv) { + if(err) { + return callback(err); + } + callback(null, { + privateKey: pki.privateKeyFromPem(priv), + publicKey: pki.publicKeyFromPem(pub) + }); + }); + } + if(_detectSubtleCrypto('generateKey') && + _detectSubtleCrypto('exportKey')) { + // use standard native generateKey + return util.globalScope.crypto.subtle.generateKey({ + name: 'RSASSA-PKCS1-v1_5', + modulusLength: bits, + publicExponent: _intToUint8Array(e), + hash: {name: 'SHA-256'} + }, true /* key can be exported*/, ['sign', 'verify']) + .then(function(pair) { + return util.globalScope.crypto.subtle.exportKey( + 'pkcs8', pair.privateKey); + // avoiding catch(function(err) {...}) to support IE <= 8 + }).then(undefined, function(err) { + callback(err); + }).then(function(pkcs8) { + if(pkcs8) { + var privateKey = pki.privateKeyFromAsn1( + asn1.fromDer(forge.util.createBuffer(pkcs8))); + callback(null, { + privateKey: privateKey, + publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e) + }); + } + }); + } + if(_detectSubtleMsCrypto('generateKey') && + _detectSubtleMsCrypto('exportKey')) { + var genOp = util.globalScope.msCrypto.subtle.generateKey({ + name: 'RSASSA-PKCS1-v1_5', + modulusLength: bits, + publicExponent: _intToUint8Array(e), + hash: {name: 'SHA-256'} + }, true /* key can be exported*/, ['sign', 'verify']); + genOp.oncomplete = function(e) { + var pair = e.target.result; + var exportOp = util.globalScope.msCrypto.subtle.exportKey( + 'pkcs8', pair.privateKey); + exportOp.oncomplete = function(e) { + var pkcs8 = e.target.result; + var privateKey = pki.privateKeyFromAsn1( + asn1.fromDer(forge.util.createBuffer(pkcs8))); + callback(null, { + privateKey: privateKey, + publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e) + }); + }; + exportOp.onerror = function(err) { + callback(err); + }; + }; + genOp.onerror = function(err) { + callback(err); + }; + return; + } + } else { + // try native sync + if(_detectNodeCrypto('generateKeyPairSync')) { + var keypair = _crypto.generateKeyPairSync('rsa', { + modulusLength: bits, + publicExponent: e, + publicKeyEncoding: { + type: 'spki', + format: 'pem' + }, + privateKeyEncoding: { + type: 'pkcs8', + format: 'pem' + } + }); + return { + privateKey: pki.privateKeyFromPem(keypair.privateKey), + publicKey: pki.publicKeyFromPem(keypair.publicKey) + }; + } + } + } + + // use JavaScript implementation + var state = pki.rsa.createKeyPairGenerationState(bits, e, options); + if(!callback) { + pki.rsa.stepKeyPairGenerationState(state, 0); + return state.keys; + } + _generateKeyPair(state, options, callback); +}; + +/** + * Sets an RSA public key from BigIntegers modulus and exponent. + * + * @param n the modulus. + * @param e the exponent. + * + * @return the public key. + */ +pki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) { + var key = { + n: n, + e: e + }; + + /** + * Encrypts the given data with this public key. Newer applications + * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for + * legacy applications. + * + * @param data the byte string to encrypt. + * @param scheme the encryption scheme to use: + * 'RSAES-PKCS1-V1_5' (default), + * 'RSA-OAEP', + * 'RAW', 'NONE', or null to perform raw RSA encryption, + * an object with an 'encode' property set to a function + * with the signature 'function(data, key)' that returns + * a binary-encoded string representing the encoded data. + * @param schemeOptions any scheme-specific options. + * + * @return the encrypted byte string. + */ + key.encrypt = function(data, scheme, schemeOptions) { + if(typeof scheme === 'string') { + scheme = scheme.toUpperCase(); + } else if(scheme === undefined) { + scheme = 'RSAES-PKCS1-V1_5'; + } + + if(scheme === 'RSAES-PKCS1-V1_5') { + scheme = { + encode: function(m, key, pub) { + return _encodePkcs1_v1_5(m, key, 0x02).getBytes(); + } + }; + } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') { + scheme = { + encode: function(m, key) { + return forge.pkcs1.encode_rsa_oaep(key, m, schemeOptions); + } + }; + } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) { + scheme = {encode: function(e) {return e;}}; + } else if(typeof scheme === 'string') { + throw new Error('Unsupported encryption scheme: "' + scheme + '".'); + } + + // do scheme-based encoding then rsa encryption + var e = scheme.encode(data, key, true); + return pki.rsa.encrypt(e, key, true); + }; + + /** + * Verifies the given signature against the given digest. + * + * PKCS#1 supports multiple (currently two) signature schemes: + * RSASSA-PKCS1-V1_5 and RSASSA-PSS. + * + * By default this implementation uses the "old scheme", i.e. + * RSASSA-PKCS1-V1_5, in which case once RSA-decrypted, the + * signature is an OCTET STRING that holds a DigestInfo. + * + * DigestInfo ::= SEQUENCE { + * digestAlgorithm DigestAlgorithmIdentifier, + * digest Digest + * } + * DigestAlgorithmIdentifier ::= AlgorithmIdentifier + * Digest ::= OCTET STRING + * + * To perform PSS signature verification, provide an instance + * of Forge PSS object as the scheme parameter. + * + * @param digest the message digest hash to compare against the signature, + * as a binary-encoded string. + * @param signature the signature to verify, as a binary-encoded string. + * @param scheme signature verification scheme to use: + * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5, + * a Forge PSS object for RSASSA-PSS, + * 'NONE' or null for none, DigestInfo will not be expected, but + * PKCS#1 v1.5 padding will still be used. + * @param options optional verify options + * _parseAllDigestBytes testing flag to control parsing of all + * digest bytes. Unsupported and not for general usage. + * (default: true) + * + * @return true if the signature was verified, false if not. + */ + key.verify = function(digest, signature, scheme, options) { + if(typeof scheme === 'string') { + scheme = scheme.toUpperCase(); + } else if(scheme === undefined) { + scheme = 'RSASSA-PKCS1-V1_5'; + } + if(options === undefined) { + options = { + _parseAllDigestBytes: true + }; + } + if(!('_parseAllDigestBytes' in options)) { + options._parseAllDigestBytes = true; + } + + if(scheme === 'RSASSA-PKCS1-V1_5') { + scheme = { + verify: function(digest, d) { + // remove padding + d = _decodePkcs1_v1_5(d, key, true); + // d is ASN.1 BER-encoded DigestInfo + var obj = asn1.fromDer(d, { + parseAllBytes: options._parseAllDigestBytes + }); + + // validate DigestInfo + var capture = {}; + var errors = []; + if(!asn1.validate(obj, digestInfoValidator, capture, errors)) { + var error = new Error( + 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' + + 'DigestInfo value.'); + error.errors = errors; + throw error; + } + // check hash algorithm identifier + // see PKCS1-v1-5DigestAlgorithms in RFC 8017 + // FIXME: add support to validator for strict value choices + var oid = asn1.derToOid(capture.algorithmIdentifier); + if(!(oid === forge.oids.md2 || + oid === forge.oids.md5 || + oid === forge.oids.sha1 || + oid === forge.oids.sha224 || + oid === forge.oids.sha256 || + oid === forge.oids.sha384 || + oid === forge.oids.sha512 || + oid === forge.oids['sha512-224'] || + oid === forge.oids['sha512-256'])) { + var error = new Error( + 'Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.'); + error.oid = oid; + throw error; + } + + // special check for md2 and md5 that NULL parameters exist + if(oid === forge.oids.md2 || oid === forge.oids.md5) { + if(!('parameters' in capture)) { + throw new Error( + 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' + + 'DigestInfo value. ' + + 'Missing algorithm identifier NULL parameters.'); + } + } + + // compare the given digest to the decrypted one + return digest === capture.digest; + } + }; + } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) { + scheme = { + verify: function(digest, d) { + // remove padding + d = _decodePkcs1_v1_5(d, key, true); + return digest === d; + } + }; + } + + // do rsa decryption w/o any decoding, then verify -- which does decoding + var d = pki.rsa.decrypt(signature, key, true, false); + return scheme.verify(digest, d, key.n.bitLength()); + }; + + return key; +}; + +/** + * Sets an RSA private key from BigIntegers modulus, exponent, primes, + * prime exponents, and modular multiplicative inverse. + * + * @param n the modulus. + * @param e the public exponent. + * @param d the private exponent ((inverse of e) mod n). + * @param p the first prime. + * @param q the second prime. + * @param dP exponent1 (d mod (p-1)). + * @param dQ exponent2 (d mod (q-1)). + * @param qInv ((inverse of q) mod p) + * + * @return the private key. + */ +pki.setRsaPrivateKey = pki.rsa.setPrivateKey = function( + n, e, d, p, q, dP, dQ, qInv) { + var key = { + n: n, + e: e, + d: d, + p: p, + q: q, + dP: dP, + dQ: dQ, + qInv: qInv + }; + + /** + * Decrypts the given data with this private key. The decryption scheme + * must match the one used to encrypt the data. + * + * @param data the byte string to decrypt. + * @param scheme the decryption scheme to use: + * 'RSAES-PKCS1-V1_5' (default), + * 'RSA-OAEP', + * 'RAW', 'NONE', or null to perform raw RSA decryption. + * @param schemeOptions any scheme-specific options. + * + * @return the decrypted byte string. + */ + key.decrypt = function(data, scheme, schemeOptions) { + if(typeof scheme === 'string') { + scheme = scheme.toUpperCase(); + } else if(scheme === undefined) { + scheme = 'RSAES-PKCS1-V1_5'; + } + + // do rsa decryption w/o any decoding + var d = pki.rsa.decrypt(data, key, false, false); + + if(scheme === 'RSAES-PKCS1-V1_5') { + scheme = {decode: _decodePkcs1_v1_5}; + } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') { + scheme = { + decode: function(d, key) { + return forge.pkcs1.decode_rsa_oaep(key, d, schemeOptions); + } + }; + } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) { + scheme = {decode: function(d) {return d;}}; + } else { + throw new Error('Unsupported encryption scheme: "' + scheme + '".'); + } + + // decode according to scheme + return scheme.decode(d, key, false); + }; + + /** + * Signs the given digest, producing a signature. + * + * PKCS#1 supports multiple (currently two) signature schemes: + * RSASSA-PKCS1-V1_5 and RSASSA-PSS. + * + * By default this implementation uses the "old scheme", i.e. + * RSASSA-PKCS1-V1_5. In order to generate a PSS signature, provide + * an instance of Forge PSS object as the scheme parameter. + * + * @param md the message digest object with the hash to sign. + * @param scheme the signature scheme to use: + * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5, + * a Forge PSS object for RSASSA-PSS, + * 'NONE' or null for none, DigestInfo will not be used but + * PKCS#1 v1.5 padding will still be used. + * + * @return the signature as a byte string. + */ + key.sign = function(md, scheme) { + /* Note: The internal implementation of RSA operations is being + transitioned away from a PKCS#1 v1.5 hard-coded scheme. Some legacy + code like the use of an encoding block identifier 'bt' will eventually + be removed. */ + + // private key operation + var bt = false; + + if(typeof scheme === 'string') { + scheme = scheme.toUpperCase(); + } + + if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') { + scheme = {encode: emsaPkcs1v15encode}; + bt = 0x01; + } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) { + scheme = {encode: function() {return md;}}; + bt = 0x01; + } + + // encode and then encrypt + var d = scheme.encode(md, key.n.bitLength()); + return pki.rsa.encrypt(d, key, bt); + }; + + return key; +}; + +/** + * Wraps an RSAPrivateKey ASN.1 object in an ASN.1 PrivateKeyInfo object. + * + * @param rsaKey the ASN.1 RSAPrivateKey. + * + * @return the ASN.1 PrivateKeyInfo. + */ +pki.wrapRsaPrivateKey = function(rsaKey) { + // PrivateKeyInfo + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version (0) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(0).getBytes()), + // privateKeyAlgorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.rsaEncryption).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]), + // PrivateKey + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + asn1.toDer(rsaKey).getBytes()) + ]); +}; + +/** + * Converts a private key from an ASN.1 object. + * + * @param obj the ASN.1 representation of a PrivateKeyInfo containing an + * RSAPrivateKey or an RSAPrivateKey. + * + * @return the private key. + */ +pki.privateKeyFromAsn1 = function(obj) { + // get PrivateKeyInfo + var capture = {}; + var errors = []; + if(asn1.validate(obj, privateKeyValidator, capture, errors)) { + obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey)); + } + + // get RSAPrivateKey + capture = {}; + errors = []; + if(!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) { + var error = new Error('Cannot read private key. ' + + 'ASN.1 object does not contain an RSAPrivateKey.'); + error.errors = errors; + throw error; + } + + // Note: Version is currently ignored. + // capture.privateKeyVersion + // FIXME: inefficient, get a BigInteger that uses byte strings + var n, e, d, p, q, dP, dQ, qInv; + n = forge.util.createBuffer(capture.privateKeyModulus).toHex(); + e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex(); + d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex(); + p = forge.util.createBuffer(capture.privateKeyPrime1).toHex(); + q = forge.util.createBuffer(capture.privateKeyPrime2).toHex(); + dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex(); + dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex(); + qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex(); + + // set private key + return pki.setRsaPrivateKey( + new BigInteger(n, 16), + new BigInteger(e, 16), + new BigInteger(d, 16), + new BigInteger(p, 16), + new BigInteger(q, 16), + new BigInteger(dP, 16), + new BigInteger(dQ, 16), + new BigInteger(qInv, 16)); +}; + +/** + * Converts a private key to an ASN.1 RSAPrivateKey. + * + * @param key the private key. + * + * @return the ASN.1 representation of an RSAPrivateKey. + */ +pki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key) { + // RSAPrivateKey + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version (0 = only 2 primes, 1 multiple primes) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(0).getBytes()), + // modulus (n) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.n)), + // publicExponent (e) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.e)), + // privateExponent (d) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.d)), + // privateKeyPrime1 (p) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.p)), + // privateKeyPrime2 (q) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.q)), + // privateKeyExponent1 (dP) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.dP)), + // privateKeyExponent2 (dQ) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.dQ)), + // coefficient (qInv) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.qInv)) + ]); +}; + +/** + * Converts a public key from an ASN.1 SubjectPublicKeyInfo or RSAPublicKey. + * + * @param obj the asn1 representation of a SubjectPublicKeyInfo or RSAPublicKey. + * + * @return the public key. + */ +pki.publicKeyFromAsn1 = function(obj) { + // get SubjectPublicKeyInfo + var capture = {}; + var errors = []; + if(asn1.validate(obj, publicKeyValidator, capture, errors)) { + // get oid + var oid = asn1.derToOid(capture.publicKeyOid); + if(oid !== pki.oids.rsaEncryption) { + var error = new Error('Cannot read public key. Unknown OID.'); + error.oid = oid; + throw error; + } + obj = capture.rsaPublicKey; + } + + // get RSA params + errors = []; + if(!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) { + var error = new Error('Cannot read public key. ' + + 'ASN.1 object does not contain an RSAPublicKey.'); + error.errors = errors; + throw error; + } + + // FIXME: inefficient, get a BigInteger that uses byte strings + var n = forge.util.createBuffer(capture.publicKeyModulus).toHex(); + var e = forge.util.createBuffer(capture.publicKeyExponent).toHex(); + + // set public key + return pki.setRsaPublicKey( + new BigInteger(n, 16), + new BigInteger(e, 16)); +}; + +/** + * Converts a public key to an ASN.1 SubjectPublicKeyInfo. + * + * @param key the public key. + * + * @return the asn1 representation of a SubjectPublicKeyInfo. + */ +pki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key) { + // SubjectPublicKeyInfo + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.rsaEncryption).getBytes()), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]), + // subjectPublicKey + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [ + pki.publicKeyToRSAPublicKey(key) + ]) + ]); +}; + +/** + * Converts a public key to an ASN.1 RSAPublicKey. + * + * @param key the public key. + * + * @return the asn1 representation of a RSAPublicKey. + */ +pki.publicKeyToRSAPublicKey = function(key) { + // RSAPublicKey + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // modulus (n) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.n)), + // publicExponent (e) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.e)) + ]); +}; + +/** + * Encodes a message using PKCS#1 v1.5 padding. + * + * @param m the message to encode. + * @param key the RSA key to use. + * @param bt the block type to use, i.e. either 0x01 (for signing) or 0x02 + * (for encryption). + * + * @return the padded byte buffer. + */ +function _encodePkcs1_v1_5(m, key, bt) { + var eb = forge.util.createBuffer(); + + // get the length of the modulus in bytes + var k = Math.ceil(key.n.bitLength() / 8); + + /* use PKCS#1 v1.5 padding */ + if(m.length > (k - 11)) { + var error = new Error('Message is too long for PKCS#1 v1.5 padding.'); + error.length = m.length; + error.max = k - 11; + throw error; + } + + /* A block type BT, a padding string PS, and the data D shall be + formatted into an octet string EB, the encryption block: + + EB = 00 || BT || PS || 00 || D + + The block type BT shall be a single octet indicating the structure of + the encryption block. For this version of the document it shall have + value 00, 01, or 02. For a private-key operation, the block type + shall be 00 or 01. For a public-key operation, it shall be 02. + + The padding string PS shall consist of k-3-||D|| octets. For block + type 00, the octets shall have value 00; for block type 01, they + shall have value FF; and for block type 02, they shall be + pseudorandomly generated and nonzero. This makes the length of the + encryption block EB equal to k. */ + + // build the encryption block + eb.putByte(0x00); + eb.putByte(bt); + + // create the padding + var padNum = k - 3 - m.length; + var padByte; + // private key op + if(bt === 0x00 || bt === 0x01) { + padByte = (bt === 0x00) ? 0x00 : 0xFF; + for(var i = 0; i < padNum; ++i) { + eb.putByte(padByte); + } + } else { + // public key op + // pad with random non-zero values + while(padNum > 0) { + var numZeros = 0; + var padBytes = forge.random.getBytes(padNum); + for(var i = 0; i < padNum; ++i) { + padByte = padBytes.charCodeAt(i); + if(padByte === 0) { + ++numZeros; + } else { + eb.putByte(padByte); + } + } + padNum = numZeros; + } + } + + // zero followed by message + eb.putByte(0x00); + eb.putBytes(m); + + return eb; +} + +/** + * Decodes a message using PKCS#1 v1.5 padding. + * + * @param em the message to decode. + * @param key the RSA key to use. + * @param pub true if the key is a public key, false if it is private. + * @param ml the message length, if specified. + * + * @return the decoded bytes. + */ +function _decodePkcs1_v1_5(em, key, pub, ml) { + // get the length of the modulus in bytes + var k = Math.ceil(key.n.bitLength() / 8); + + /* It is an error if any of the following conditions occurs: + + 1. The encryption block EB cannot be parsed unambiguously. + 2. The padding string PS consists of fewer than eight octets + or is inconsistent with the block type BT. + 3. The decryption process is a public-key operation and the block + type BT is not 00 or 01, or the decryption process is a + private-key operation and the block type is not 02. + */ + + // parse the encryption block + var eb = forge.util.createBuffer(em); + var first = eb.getByte(); + var bt = eb.getByte(); + if(first !== 0x00 || + (pub && bt !== 0x00 && bt !== 0x01) || + (!pub && bt != 0x02) || + (pub && bt === 0x00 && typeof(ml) === 'undefined')) { + throw new Error('Encryption block is invalid.'); + } + + var padNum = 0; + if(bt === 0x00) { + // check all padding bytes for 0x00 + padNum = k - 3 - ml; + for(var i = 0; i < padNum; ++i) { + if(eb.getByte() !== 0x00) { + throw new Error('Encryption block is invalid.'); + } + } + } else if(bt === 0x01) { + // find the first byte that isn't 0xFF, should be after all padding + padNum = 0; + while(eb.length() > 1) { + if(eb.getByte() !== 0xFF) { + --eb.read; + break; + } + ++padNum; + } + } else if(bt === 0x02) { + // look for 0x00 byte + padNum = 0; + while(eb.length() > 1) { + if(eb.getByte() === 0x00) { + --eb.read; + break; + } + ++padNum; + } + } + + // zero must be 0x00 and padNum must be (k - 3 - message length) + var zero = eb.getByte(); + if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) { + throw new Error('Encryption block is invalid.'); + } + + return eb.getBytes(); +} + +/** + * Runs the key-generation algorithm asynchronously, either in the background + * via Web Workers, or using the main thread and setImmediate. + * + * @param state the key-pair generation state. + * @param [options] options for key-pair generation: + * workerScript the worker script URL. + * workers the number of web workers (if supported) to use, + * (default: 2, -1 to use estimated cores minus one). + * workLoad the size of the work load, ie: number of possible prime + * numbers for each web worker to check per work assignment, + * (default: 100). + * @param callback(err, keypair) called once the operation completes. + */ +function _generateKeyPair(state, options, callback) { + if(typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + + var opts = { + algorithm: { + name: options.algorithm || 'PRIMEINC', + options: { + workers: options.workers || 2, + workLoad: options.workLoad || 100, + workerScript: options.workerScript + } + } + }; + if('prng' in options) { + opts.prng = options.prng; + } + + generate(); + + function generate() { + // find p and then q (done in series to simplify) + getPrime(state.pBits, function(err, num) { + if(err) { + return callback(err); + } + state.p = num; + if(state.q !== null) { + return finish(err, state.q); + } + getPrime(state.qBits, finish); + }); + } + + function getPrime(bits, callback) { + forge.prime.generateProbablePrime(bits, opts, callback); + } + + function finish(err, num) { + if(err) { + return callback(err); + } + + // set q + state.q = num; + + // ensure p is larger than q (swap them if not) + if(state.p.compareTo(state.q) < 0) { + var tmp = state.p; + state.p = state.q; + state.q = tmp; + } + + // ensure p is coprime with e + if(state.p.subtract(BigInteger.ONE).gcd(state.e) + .compareTo(BigInteger.ONE) !== 0) { + state.p = null; + generate(); + return; + } + + // ensure q is coprime with e + if(state.q.subtract(BigInteger.ONE).gcd(state.e) + .compareTo(BigInteger.ONE) !== 0) { + state.q = null; + getPrime(state.qBits, finish); + return; + } + + // compute phi: (p - 1)(q - 1) (Euler's totient function) + state.p1 = state.p.subtract(BigInteger.ONE); + state.q1 = state.q.subtract(BigInteger.ONE); + state.phi = state.p1.multiply(state.q1); + + // ensure e and phi are coprime + if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) { + // phi and e aren't coprime, so generate a new p and q + state.p = state.q = null; + generate(); + return; + } + + // create n, ensure n is has the right number of bits + state.n = state.p.multiply(state.q); + if(state.n.bitLength() !== state.bits) { + // failed, get new q + state.q = null; + getPrime(state.qBits, finish); + return; + } + + // set keys + var d = state.e.modInverse(state.phi); + state.keys = { + privateKey: pki.rsa.setPrivateKey( + state.n, state.e, d, state.p, state.q, + d.mod(state.p1), d.mod(state.q1), + state.q.modInverse(state.p)), + publicKey: pki.rsa.setPublicKey(state.n, state.e) + }; + + callback(null, state.keys); + } +} + +/** + * Converts a positive BigInteger into 2's-complement big-endian bytes. + * + * @param b the big integer to convert. + * + * @return the bytes. + */ +function _bnToBytes(b) { + // prepend 0x00 if first byte >= 0x80 + var hex = b.toString(16); + if(hex[0] >= '8') { + hex = '00' + hex; + } + var bytes = forge.util.hexToBytes(hex); + + // ensure integer is minimally-encoded + if(bytes.length > 1 && + // leading 0x00 for positive integer + ((bytes.charCodeAt(0) === 0 && + (bytes.charCodeAt(1) & 0x80) === 0) || + // leading 0xFF for negative integer + (bytes.charCodeAt(0) === 0xFF && + (bytes.charCodeAt(1) & 0x80) === 0x80))) { + return bytes.substr(1); + } + return bytes; +} + +/** + * Returns the required number of Miller-Rabin tests to generate a + * prime with an error probability of (1/2)^80. + * + * See Handbook of Applied Cryptography Chapter 4, Table 4.4. + * + * @param bits the bit size. + * + * @return the required number of iterations. + */ +function _getMillerRabinTests(bits) { + if(bits <= 100) return 27; + if(bits <= 150) return 18; + if(bits <= 200) return 15; + if(bits <= 250) return 12; + if(bits <= 300) return 9; + if(bits <= 350) return 8; + if(bits <= 400) return 7; + if(bits <= 500) return 6; + if(bits <= 600) return 5; + if(bits <= 800) return 4; + if(bits <= 1250) return 3; + return 2; +} + +/** + * Performs feature detection on the Node crypto interface. + * + * @param fn the feature (function) to detect. + * + * @return true if detected, false if not. + */ +function _detectNodeCrypto(fn) { + return forge.util.isNodejs && typeof _crypto[fn] === 'function'; +} + +/** + * Performs feature detection on the SubtleCrypto interface. + * + * @param fn the feature (function) to detect. + * + * @return true if detected, false if not. + */ +function _detectSubtleCrypto(fn) { + return (typeof util.globalScope !== 'undefined' && + typeof util.globalScope.crypto === 'object' && + typeof util.globalScope.crypto.subtle === 'object' && + typeof util.globalScope.crypto.subtle[fn] === 'function'); +} + +/** + * Performs feature detection on the deprecated Microsoft Internet Explorer + * outdated SubtleCrypto interface. This function should only be used after + * checking for the modern, standard SubtleCrypto interface. + * + * @param fn the feature (function) to detect. + * + * @return true if detected, false if not. + */ +function _detectSubtleMsCrypto(fn) { + return (typeof util.globalScope !== 'undefined' && + typeof util.globalScope.msCrypto === 'object' && + typeof util.globalScope.msCrypto.subtle === 'object' && + typeof util.globalScope.msCrypto.subtle[fn] === 'function'); +} + +function _intToUint8Array(x) { + var bytes = forge.util.hexToBytes(x.toString(16)); + var buffer = new Uint8Array(bytes.length); + for(var i = 0; i < bytes.length; ++i) { + buffer[i] = bytes.charCodeAt(i); + } + return buffer; +} + +function _privateKeyFromJwk(jwk) { + if(jwk.kty !== 'RSA') { + throw new Error( + 'Unsupported key algorithm "' + jwk.kty + '"; algorithm must be "RSA".'); + } + return pki.setRsaPrivateKey( + _base64ToBigInt(jwk.n), + _base64ToBigInt(jwk.e), + _base64ToBigInt(jwk.d), + _base64ToBigInt(jwk.p), + _base64ToBigInt(jwk.q), + _base64ToBigInt(jwk.dp), + _base64ToBigInt(jwk.dq), + _base64ToBigInt(jwk.qi)); +} + +function _publicKeyFromJwk(jwk) { + if(jwk.kty !== 'RSA') { + throw new Error('Key algorithm must be "RSA".'); + } + return pki.setRsaPublicKey( + _base64ToBigInt(jwk.n), + _base64ToBigInt(jwk.e)); +} + +function _base64ToBigInt(b64) { + return new BigInteger(forge.util.bytesToHex(forge.util.decode64(b64)), 16); +} diff --git a/node_modules/node-forge/lib/sha1.js b/node_modules/node-forge/lib/sha1.js new file mode 100644 index 0000000..5f84eb6 --- /dev/null +++ b/node_modules/node-forge/lib/sha1.js @@ -0,0 +1,319 @@ +/** + * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation. + * + * @author Dave Longley + * + * Copyright (c) 2010-2015 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./md'); +require('./util'); + +var sha1 = module.exports = forge.sha1 = forge.sha1 || {}; +forge.md.sha1 = forge.md.algorithms.sha1 = sha1; + +/** + * Creates a SHA-1 message digest object. + * + * @return a message digest object. + */ +sha1.create = function() { + // do initialization as necessary + if(!_initialized) { + _init(); + } + + // SHA-1 state contains five 32-bit integers + var _state = null; + + // input buffer + var _input = forge.util.createBuffer(); + + // used for word storage + var _w = new Array(80); + + // message digest object + var md = { + algorithm: 'sha1', + blockLength: 64, + digestLength: 20, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 8 + }; + + /** + * Starts the digest. + * + * @return this digest object. + */ + md.start = function() { + // up to 56-bit message length for convenience + md.messageLength = 0; + + // full message length (set md.messageLength64 for backwards-compatibility) + md.fullMessageLength = md.messageLength64 = []; + var int32s = md.messageLengthSize / 4; + for(var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _state = { + h0: 0x67452301, + h1: 0xEFCDAB89, + h2: 0x98BADCFE, + h3: 0x10325476, + h4: 0xC3D2E1F0 + }; + return md; + }; + // start digest automatically for first time + md.start(); + + /** + * Updates the digest with the given message input. The given input can + * treated as raw input (no encoding will be applied) or an encoding of + * 'utf8' maybe given to encode the input using UTF-8. + * + * @param msg the message input to update with. + * @param encoding the encoding to use (default: 'raw', other: 'utf8'). + * + * @return this digest object. + */ + md.update = function(msg, encoding) { + if(encoding === 'utf8') { + msg = forge.util.encodeUtf8(msg); + } + + // update message length + var len = msg.length; + md.messageLength += len; + len = [(len / 0x100000000) >>> 0, len >>> 0]; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = ((len[1] / 0x100000000) >>> 0); + } + + // add bytes to input buffer + _input.putBytes(msg); + + // process bytes + _update(_state, _w, _input); + + // compact input buffer every 2K or if empty + if(_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + + return md; + }; + + /** + * Produces the digest. + * + * @return a byte buffer containing the digest value. + */ + md.digest = function() { + /* Note: Here we copy the remaining bytes in the input buffer and + add the appropriate SHA-1 padding. Then we do the final update + on a copy of the state so that if the user wants to get + intermediate digests they can do so. */ + + /* Determine the number of bytes that must be added to the message + to ensure its length is congruent to 448 mod 512. In other words, + the data to be digested must be a multiple of 512 bits (or 128 bytes). + This data includes the message, some padding, and the length of the + message. Since the length of the message will be encoded as 8 bytes (64 + bits), that means that the last segment of the data must have 56 bytes + (448 bits) of message and padding. Therefore, the length of the message + plus the padding must be congruent to 448 mod 512 because + 512 - 128 = 448. + + In order to fill up the message length it must be filled with + padding that begins with 1 bit followed by all 0 bits. Padding + must *always* be present, so if the message length is already + congruent to 448 mod 512, then 512 padding bits must be added. */ + + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + + // compute remaining size to be digested (include message length size) + var remaining = ( + md.fullMessageLength[md.fullMessageLength.length - 1] + + md.messageLengthSize); + + // add padding for overflow blockSize - overflow + // _padding starts with 1 byte with first bit is set (byte value 128), then + // there may be up to (blockSize - 1) other pad bytes + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + + // serialize message length in bits in big-endian order; since length + // is stored in bytes we multiply by 8 and add carry from next int + var next, carry; + var bits = md.fullMessageLength[0] * 8; + for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { + next = md.fullMessageLength[i + 1] * 8; + carry = (next / 0x100000000) >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); + + var s2 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3, + h4: _state.h4 + }; + _update(s2, _w, finalBlock); + var rval = forge.util.createBuffer(); + rval.putInt32(s2.h0); + rval.putInt32(s2.h1); + rval.putInt32(s2.h2); + rval.putInt32(s2.h3); + rval.putInt32(s2.h4); + return rval; + }; + + return md; +}; + +// sha-1 padding bytes not initialized yet +var _padding = null; +var _initialized = false; + +/** + * Initializes the constant tables. + */ +function _init() { + // create padding + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0x00), 64); + + // now initialized + _initialized = true; +} + +/** + * Updates a SHA-1 state with the given byte buffer. + * + * @param s the SHA-1 state to update. + * @param w the array to use to store words. + * @param bytes the byte buffer to update with. + */ +function _update(s, w, bytes) { + // consume 512 bit (64 byte) chunks + var t, a, b, c, d, e, f, i; + var len = bytes.length(); + while(len >= 64) { + // the w array will be populated with sixteen 32-bit big-endian words + // and then extended into 80 32-bit words according to SHA-1 algorithm + // and for 32-79 using Max Locktyukhin's optimization + + // initialize hash value for this chunk + a = s.h0; + b = s.h1; + c = s.h2; + d = s.h3; + e = s.h4; + + // round 1 + for(i = 0; i < 16; ++i) { + t = bytes.getInt32(); + w[i] = t; + f = d ^ (b & (c ^ d)); + t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + for(; i < 20; ++i) { + t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); + t = (t << 1) | (t >>> 31); + w[i] = t; + f = d ^ (b & (c ^ d)); + t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + // round 2 + for(; i < 32; ++i) { + t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); + t = (t << 1) | (t >>> 31); + w[i] = t; + f = b ^ c ^ d; + t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + for(; i < 40; ++i) { + t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); + t = (t << 2) | (t >>> 30); + w[i] = t; + f = b ^ c ^ d; + t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + // round 3 + for(; i < 60; ++i) { + t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); + t = (t << 2) | (t >>> 30); + w[i] = t; + f = (b & c) | (d & (b ^ c)); + t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + // round 4 + for(; i < 80; ++i) { + t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); + t = (t << 2) | (t >>> 30); + w[i] = t; + f = b ^ c ^ d; + t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + + // update hash state + s.h0 = (s.h0 + a) | 0; + s.h1 = (s.h1 + b) | 0; + s.h2 = (s.h2 + c) | 0; + s.h3 = (s.h3 + d) | 0; + s.h4 = (s.h4 + e) | 0; + + len -= 64; + } +} diff --git a/node_modules/node-forge/lib/sha256.js b/node_modules/node-forge/lib/sha256.js new file mode 100644 index 0000000..0659ad7 --- /dev/null +++ b/node_modules/node-forge/lib/sha256.js @@ -0,0 +1,327 @@ +/** + * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation. + * + * See FIPS 180-2 for details. + * + * @author Dave Longley + * + * Copyright (c) 2010-2015 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./md'); +require('./util'); + +var sha256 = module.exports = forge.sha256 = forge.sha256 || {}; +forge.md.sha256 = forge.md.algorithms.sha256 = sha256; + +/** + * Creates a SHA-256 message digest object. + * + * @return a message digest object. + */ +sha256.create = function() { + // do initialization as necessary + if(!_initialized) { + _init(); + } + + // SHA-256 state contains eight 32-bit integers + var _state = null; + + // input buffer + var _input = forge.util.createBuffer(); + + // used for word storage + var _w = new Array(64); + + // message digest object + var md = { + algorithm: 'sha256', + blockLength: 64, + digestLength: 32, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 8 + }; + + /** + * Starts the digest. + * + * @return this digest object. + */ + md.start = function() { + // up to 56-bit message length for convenience + md.messageLength = 0; + + // full message length (set md.messageLength64 for backwards-compatibility) + md.fullMessageLength = md.messageLength64 = []; + var int32s = md.messageLengthSize / 4; + for(var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _state = { + h0: 0x6A09E667, + h1: 0xBB67AE85, + h2: 0x3C6EF372, + h3: 0xA54FF53A, + h4: 0x510E527F, + h5: 0x9B05688C, + h6: 0x1F83D9AB, + h7: 0x5BE0CD19 + }; + return md; + }; + // start digest automatically for first time + md.start(); + + /** + * Updates the digest with the given message input. The given input can + * treated as raw input (no encoding will be applied) or an encoding of + * 'utf8' maybe given to encode the input using UTF-8. + * + * @param msg the message input to update with. + * @param encoding the encoding to use (default: 'raw', other: 'utf8'). + * + * @return this digest object. + */ + md.update = function(msg, encoding) { + if(encoding === 'utf8') { + msg = forge.util.encodeUtf8(msg); + } + + // update message length + var len = msg.length; + md.messageLength += len; + len = [(len / 0x100000000) >>> 0, len >>> 0]; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = ((len[1] / 0x100000000) >>> 0); + } + + // add bytes to input buffer + _input.putBytes(msg); + + // process bytes + _update(_state, _w, _input); + + // compact input buffer every 2K or if empty + if(_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + + return md; + }; + + /** + * Produces the digest. + * + * @return a byte buffer containing the digest value. + */ + md.digest = function() { + /* Note: Here we copy the remaining bytes in the input buffer and + add the appropriate SHA-256 padding. Then we do the final update + on a copy of the state so that if the user wants to get + intermediate digests they can do so. */ + + /* Determine the number of bytes that must be added to the message + to ensure its length is congruent to 448 mod 512. In other words, + the data to be digested must be a multiple of 512 bits (or 128 bytes). + This data includes the message, some padding, and the length of the + message. Since the length of the message will be encoded as 8 bytes (64 + bits), that means that the last segment of the data must have 56 bytes + (448 bits) of message and padding. Therefore, the length of the message + plus the padding must be congruent to 448 mod 512 because + 512 - 128 = 448. + + In order to fill up the message length it must be filled with + padding that begins with 1 bit followed by all 0 bits. Padding + must *always* be present, so if the message length is already + congruent to 448 mod 512, then 512 padding bits must be added. */ + + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + + // compute remaining size to be digested (include message length size) + var remaining = ( + md.fullMessageLength[md.fullMessageLength.length - 1] + + md.messageLengthSize); + + // add padding for overflow blockSize - overflow + // _padding starts with 1 byte with first bit is set (byte value 128), then + // there may be up to (blockSize - 1) other pad bytes + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + + // serialize message length in bits in big-endian order; since length + // is stored in bytes we multiply by 8 and add carry from next int + var next, carry; + var bits = md.fullMessageLength[0] * 8; + for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { + next = md.fullMessageLength[i + 1] * 8; + carry = (next / 0x100000000) >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); + + var s2 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3, + h4: _state.h4, + h5: _state.h5, + h6: _state.h6, + h7: _state.h7 + }; + _update(s2, _w, finalBlock); + var rval = forge.util.createBuffer(); + rval.putInt32(s2.h0); + rval.putInt32(s2.h1); + rval.putInt32(s2.h2); + rval.putInt32(s2.h3); + rval.putInt32(s2.h4); + rval.putInt32(s2.h5); + rval.putInt32(s2.h6); + rval.putInt32(s2.h7); + return rval; + }; + + return md; +}; + +// sha-256 padding bytes not initialized yet +var _padding = null; +var _initialized = false; + +// table of constants +var _k = null; + +/** + * Initializes the constant tables. + */ +function _init() { + // create padding + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0x00), 64); + + // create K table for SHA-256 + _k = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, + 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, + 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]; + + // now initialized + _initialized = true; +} + +/** + * Updates a SHA-256 state with the given byte buffer. + * + * @param s the SHA-256 state to update. + * @param w the array to use to store words. + * @param bytes the byte buffer to update with. + */ +function _update(s, w, bytes) { + // consume 512 bit (64 byte) chunks + var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h; + var len = bytes.length(); + while(len >= 64) { + // the w array will be populated with sixteen 32-bit big-endian words + // and then extended into 64 32-bit words according to SHA-256 + for(i = 0; i < 16; ++i) { + w[i] = bytes.getInt32(); + } + for(; i < 64; ++i) { + // XOR word 2 words ago rot right 17, rot right 19, shft right 10 + t1 = w[i - 2]; + t1 = + ((t1 >>> 17) | (t1 << 15)) ^ + ((t1 >>> 19) | (t1 << 13)) ^ + (t1 >>> 10); + // XOR word 15 words ago rot right 7, rot right 18, shft right 3 + t2 = w[i - 15]; + t2 = + ((t2 >>> 7) | (t2 << 25)) ^ + ((t2 >>> 18) | (t2 << 14)) ^ + (t2 >>> 3); + // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32 + w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0; + } + + // initialize hash value for this chunk + a = s.h0; + b = s.h1; + c = s.h2; + d = s.h3; + e = s.h4; + f = s.h5; + g = s.h6; + h = s.h7; + + // round function + for(i = 0; i < 64; ++i) { + // Sum1(e) + s1 = + ((e >>> 6) | (e << 26)) ^ + ((e >>> 11) | (e << 21)) ^ + ((e >>> 25) | (e << 7)); + // Ch(e, f, g) (optimized the same way as SHA-1) + ch = g ^ (e & (f ^ g)); + // Sum0(a) + s0 = + ((a >>> 2) | (a << 30)) ^ + ((a >>> 13) | (a << 19)) ^ + ((a >>> 22) | (a << 10)); + // Maj(a, b, c) (optimized the same way as SHA-1) + maj = (a & b) | (c & (a ^ b)); + + // main algorithm + t1 = h + s1 + ch + _k[i] + w[i]; + t2 = s0 + maj; + h = g; + g = f; + f = e; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + // can't truncate with `| 0` + e = (d + t1) >>> 0; + d = c; + c = b; + b = a; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + // can't truncate with `| 0` + a = (t1 + t2) >>> 0; + } + + // update hash state + s.h0 = (s.h0 + a) | 0; + s.h1 = (s.h1 + b) | 0; + s.h2 = (s.h2 + c) | 0; + s.h3 = (s.h3 + d) | 0; + s.h4 = (s.h4 + e) | 0; + s.h5 = (s.h5 + f) | 0; + s.h6 = (s.h6 + g) | 0; + s.h7 = (s.h7 + h) | 0; + len -= 64; + } +} diff --git a/node_modules/node-forge/lib/sha512.js b/node_modules/node-forge/lib/sha512.js new file mode 100644 index 0000000..e09b442 --- /dev/null +++ b/node_modules/node-forge/lib/sha512.js @@ -0,0 +1,561 @@ +/** + * Secure Hash Algorithm with a 1024-bit block size implementation. + * + * This includes: SHA-512, SHA-384, SHA-512/224, and SHA-512/256. For + * SHA-256 (block size 512 bits), see sha256.js. + * + * See FIPS 180-4 for details. + * + * @author Dave Longley + * + * Copyright (c) 2014-2015 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./md'); +require('./util'); + +var sha512 = module.exports = forge.sha512 = forge.sha512 || {}; + +// SHA-512 +forge.md.sha512 = forge.md.algorithms.sha512 = sha512; + +// SHA-384 +var sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {}; +sha384.create = function() { + return sha512.create('SHA-384'); +}; +forge.md.sha384 = forge.md.algorithms.sha384 = sha384; + +// SHA-512/256 +forge.sha512.sha256 = forge.sha512.sha256 || { + create: function() { + return sha512.create('SHA-512/256'); + } +}; +forge.md['sha512/256'] = forge.md.algorithms['sha512/256'] = + forge.sha512.sha256; + +// SHA-512/224 +forge.sha512.sha224 = forge.sha512.sha224 || { + create: function() { + return sha512.create('SHA-512/224'); + } +}; +forge.md['sha512/224'] = forge.md.algorithms['sha512/224'] = + forge.sha512.sha224; + +/** + * Creates a SHA-2 message digest object. + * + * @param algorithm the algorithm to use (SHA-512, SHA-384, SHA-512/224, + * SHA-512/256). + * + * @return a message digest object. + */ +sha512.create = function(algorithm) { + // do initialization as necessary + if(!_initialized) { + _init(); + } + + if(typeof algorithm === 'undefined') { + algorithm = 'SHA-512'; + } + + if(!(algorithm in _states)) { + throw new Error('Invalid SHA-512 algorithm: ' + algorithm); + } + + // SHA-512 state contains eight 64-bit integers (each as two 32-bit ints) + var _state = _states[algorithm]; + var _h = null; + + // input buffer + var _input = forge.util.createBuffer(); + + // used for 64-bit word storage + var _w = new Array(80); + for(var wi = 0; wi < 80; ++wi) { + _w[wi] = new Array(2); + } + + // determine digest length by algorithm name (default) + var digestLength = 64; + switch(algorithm) { + case 'SHA-384': + digestLength = 48; + break; + case 'SHA-512/256': + digestLength = 32; + break; + case 'SHA-512/224': + digestLength = 28; + break; + } + + // message digest object + var md = { + // SHA-512 => sha512 + algorithm: algorithm.replace('-', '').toLowerCase(), + blockLength: 128, + digestLength: digestLength, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 16 + }; + + /** + * Starts the digest. + * + * @return this digest object. + */ + md.start = function() { + // up to 56-bit message length for convenience + md.messageLength = 0; + + // full message length (set md.messageLength128 for backwards-compatibility) + md.fullMessageLength = md.messageLength128 = []; + var int32s = md.messageLengthSize / 4; + for(var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _h = new Array(_state.length); + for(var i = 0; i < _state.length; ++i) { + _h[i] = _state[i].slice(0); + } + return md; + }; + // start digest automatically for first time + md.start(); + + /** + * Updates the digest with the given message input. The given input can + * treated as raw input (no encoding will be applied) or an encoding of + * 'utf8' maybe given to encode the input using UTF-8. + * + * @param msg the message input to update with. + * @param encoding the encoding to use (default: 'raw', other: 'utf8'). + * + * @return this digest object. + */ + md.update = function(msg, encoding) { + if(encoding === 'utf8') { + msg = forge.util.encodeUtf8(msg); + } + + // update message length + var len = msg.length; + md.messageLength += len; + len = [(len / 0x100000000) >>> 0, len >>> 0]; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = ((len[1] / 0x100000000) >>> 0); + } + + // add bytes to input buffer + _input.putBytes(msg); + + // process bytes + _update(_h, _w, _input); + + // compact input buffer every 2K or if empty + if(_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + + return md; + }; + + /** + * Produces the digest. + * + * @return a byte buffer containing the digest value. + */ + md.digest = function() { + /* Note: Here we copy the remaining bytes in the input buffer and + add the appropriate SHA-512 padding. Then we do the final update + on a copy of the state so that if the user wants to get + intermediate digests they can do so. */ + + /* Determine the number of bytes that must be added to the message + to ensure its length is congruent to 896 mod 1024. In other words, + the data to be digested must be a multiple of 1024 bits (or 128 bytes). + This data includes the message, some padding, and the length of the + message. Since the length of the message will be encoded as 16 bytes (128 + bits), that means that the last segment of the data must have 112 bytes + (896 bits) of message and padding. Therefore, the length of the message + plus the padding must be congruent to 896 mod 1024 because + 1024 - 128 = 896. + + In order to fill up the message length it must be filled with + padding that begins with 1 bit followed by all 0 bits. Padding + must *always* be present, so if the message length is already + congruent to 896 mod 1024, then 1024 padding bits must be added. */ + + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + + // compute remaining size to be digested (include message length size) + var remaining = ( + md.fullMessageLength[md.fullMessageLength.length - 1] + + md.messageLengthSize); + + // add padding for overflow blockSize - overflow + // _padding starts with 1 byte with first bit is set (byte value 128), then + // there may be up to (blockSize - 1) other pad bytes + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + + // serialize message length in bits in big-endian order; since length + // is stored in bytes we multiply by 8 and add carry from next int + var next, carry; + var bits = md.fullMessageLength[0] * 8; + for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { + next = md.fullMessageLength[i + 1] * 8; + carry = (next / 0x100000000) >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); + + var h = new Array(_h.length); + for(var i = 0; i < _h.length; ++i) { + h[i] = _h[i].slice(0); + } + _update(h, _w, finalBlock); + var rval = forge.util.createBuffer(); + var hlen; + if(algorithm === 'SHA-512') { + hlen = h.length; + } else if(algorithm === 'SHA-384') { + hlen = h.length - 2; + } else { + hlen = h.length - 4; + } + for(var i = 0; i < hlen; ++i) { + rval.putInt32(h[i][0]); + if(i !== hlen - 1 || algorithm !== 'SHA-512/224') { + rval.putInt32(h[i][1]); + } + } + return rval; + }; + + return md; +}; + +// sha-512 padding bytes not initialized yet +var _padding = null; +var _initialized = false; + +// table of constants +var _k = null; + +// initial hash states +var _states = null; + +/** + * Initializes the constant tables. + */ +function _init() { + // create padding + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0x00), 128); + + // create K table for SHA-512 + _k = [ + [0x428a2f98, 0xd728ae22], [0x71374491, 0x23ef65cd], + [0xb5c0fbcf, 0xec4d3b2f], [0xe9b5dba5, 0x8189dbbc], + [0x3956c25b, 0xf348b538], [0x59f111f1, 0xb605d019], + [0x923f82a4, 0xaf194f9b], [0xab1c5ed5, 0xda6d8118], + [0xd807aa98, 0xa3030242], [0x12835b01, 0x45706fbe], + [0x243185be, 0x4ee4b28c], [0x550c7dc3, 0xd5ffb4e2], + [0x72be5d74, 0xf27b896f], [0x80deb1fe, 0x3b1696b1], + [0x9bdc06a7, 0x25c71235], [0xc19bf174, 0xcf692694], + [0xe49b69c1, 0x9ef14ad2], [0xefbe4786, 0x384f25e3], + [0x0fc19dc6, 0x8b8cd5b5], [0x240ca1cc, 0x77ac9c65], + [0x2de92c6f, 0x592b0275], [0x4a7484aa, 0x6ea6e483], + [0x5cb0a9dc, 0xbd41fbd4], [0x76f988da, 0x831153b5], + [0x983e5152, 0xee66dfab], [0xa831c66d, 0x2db43210], + [0xb00327c8, 0x98fb213f], [0xbf597fc7, 0xbeef0ee4], + [0xc6e00bf3, 0x3da88fc2], [0xd5a79147, 0x930aa725], + [0x06ca6351, 0xe003826f], [0x14292967, 0x0a0e6e70], + [0x27b70a85, 0x46d22ffc], [0x2e1b2138, 0x5c26c926], + [0x4d2c6dfc, 0x5ac42aed], [0x53380d13, 0x9d95b3df], + [0x650a7354, 0x8baf63de], [0x766a0abb, 0x3c77b2a8], + [0x81c2c92e, 0x47edaee6], [0x92722c85, 0x1482353b], + [0xa2bfe8a1, 0x4cf10364], [0xa81a664b, 0xbc423001], + [0xc24b8b70, 0xd0f89791], [0xc76c51a3, 0x0654be30], + [0xd192e819, 0xd6ef5218], [0xd6990624, 0x5565a910], + [0xf40e3585, 0x5771202a], [0x106aa070, 0x32bbd1b8], + [0x19a4c116, 0xb8d2d0c8], [0x1e376c08, 0x5141ab53], + [0x2748774c, 0xdf8eeb99], [0x34b0bcb5, 0xe19b48a8], + [0x391c0cb3, 0xc5c95a63], [0x4ed8aa4a, 0xe3418acb], + [0x5b9cca4f, 0x7763e373], [0x682e6ff3, 0xd6b2b8a3], + [0x748f82ee, 0x5defb2fc], [0x78a5636f, 0x43172f60], + [0x84c87814, 0xa1f0ab72], [0x8cc70208, 0x1a6439ec], + [0x90befffa, 0x23631e28], [0xa4506ceb, 0xde82bde9], + [0xbef9a3f7, 0xb2c67915], [0xc67178f2, 0xe372532b], + [0xca273ece, 0xea26619c], [0xd186b8c7, 0x21c0c207], + [0xeada7dd6, 0xcde0eb1e], [0xf57d4f7f, 0xee6ed178], + [0x06f067aa, 0x72176fba], [0x0a637dc5, 0xa2c898a6], + [0x113f9804, 0xbef90dae], [0x1b710b35, 0x131c471b], + [0x28db77f5, 0x23047d84], [0x32caab7b, 0x40c72493], + [0x3c9ebe0a, 0x15c9bebc], [0x431d67c4, 0x9c100d4c], + [0x4cc5d4be, 0xcb3e42b6], [0x597f299c, 0xfc657e2a], + [0x5fcb6fab, 0x3ad6faec], [0x6c44198c, 0x4a475817] + ]; + + // initial hash states + _states = {}; + _states['SHA-512'] = [ + [0x6a09e667, 0xf3bcc908], + [0xbb67ae85, 0x84caa73b], + [0x3c6ef372, 0xfe94f82b], + [0xa54ff53a, 0x5f1d36f1], + [0x510e527f, 0xade682d1], + [0x9b05688c, 0x2b3e6c1f], + [0x1f83d9ab, 0xfb41bd6b], + [0x5be0cd19, 0x137e2179] + ]; + _states['SHA-384'] = [ + [0xcbbb9d5d, 0xc1059ed8], + [0x629a292a, 0x367cd507], + [0x9159015a, 0x3070dd17], + [0x152fecd8, 0xf70e5939], + [0x67332667, 0xffc00b31], + [0x8eb44a87, 0x68581511], + [0xdb0c2e0d, 0x64f98fa7], + [0x47b5481d, 0xbefa4fa4] + ]; + _states['SHA-512/256'] = [ + [0x22312194, 0xFC2BF72C], + [0x9F555FA3, 0xC84C64C2], + [0x2393B86B, 0x6F53B151], + [0x96387719, 0x5940EABD], + [0x96283EE2, 0xA88EFFE3], + [0xBE5E1E25, 0x53863992], + [0x2B0199FC, 0x2C85B8AA], + [0x0EB72DDC, 0x81C52CA2] + ]; + _states['SHA-512/224'] = [ + [0x8C3D37C8, 0x19544DA2], + [0x73E19966, 0x89DCD4D6], + [0x1DFAB7AE, 0x32FF9C82], + [0x679DD514, 0x582F9FCF], + [0x0F6D2B69, 0x7BD44DA8], + [0x77E36F73, 0x04C48942], + [0x3F9D85A8, 0x6A1D36C8], + [0x1112E6AD, 0x91D692A1] + ]; + + // now initialized + _initialized = true; +} + +/** + * Updates a SHA-512 state with the given byte buffer. + * + * @param s the SHA-512 state to update. + * @param w the array to use to store words. + * @param bytes the byte buffer to update with. + */ +function _update(s, w, bytes) { + // consume 512 bit (128 byte) chunks + var t1_hi, t1_lo; + var t2_hi, t2_lo; + var s0_hi, s0_lo; + var s1_hi, s1_lo; + var ch_hi, ch_lo; + var maj_hi, maj_lo; + var a_hi, a_lo; + var b_hi, b_lo; + var c_hi, c_lo; + var d_hi, d_lo; + var e_hi, e_lo; + var f_hi, f_lo; + var g_hi, g_lo; + var h_hi, h_lo; + var i, hi, lo, w2, w7, w15, w16; + var len = bytes.length(); + while(len >= 128) { + // the w array will be populated with sixteen 64-bit big-endian words + // and then extended into 64 64-bit words according to SHA-512 + for(i = 0; i < 16; ++i) { + w[i][0] = bytes.getInt32() >>> 0; + w[i][1] = bytes.getInt32() >>> 0; + } + for(; i < 80; ++i) { + // for word 2 words ago: ROTR 19(x) ^ ROTR 61(x) ^ SHR 6(x) + w2 = w[i - 2]; + hi = w2[0]; + lo = w2[1]; + + // high bits + t1_hi = ( + ((hi >>> 19) | (lo << 13)) ^ // ROTR 19 + ((lo >>> 29) | (hi << 3)) ^ // ROTR 61/(swap + ROTR 29) + (hi >>> 6)) >>> 0; // SHR 6 + // low bits + t1_lo = ( + ((hi << 13) | (lo >>> 19)) ^ // ROTR 19 + ((lo << 3) | (hi >>> 29)) ^ // ROTR 61/(swap + ROTR 29) + ((hi << 26) | (lo >>> 6))) >>> 0; // SHR 6 + + // for word 15 words ago: ROTR 1(x) ^ ROTR 8(x) ^ SHR 7(x) + w15 = w[i - 15]; + hi = w15[0]; + lo = w15[1]; + + // high bits + t2_hi = ( + ((hi >>> 1) | (lo << 31)) ^ // ROTR 1 + ((hi >>> 8) | (lo << 24)) ^ // ROTR 8 + (hi >>> 7)) >>> 0; // SHR 7 + // low bits + t2_lo = ( + ((hi << 31) | (lo >>> 1)) ^ // ROTR 1 + ((hi << 24) | (lo >>> 8)) ^ // ROTR 8 + ((hi << 25) | (lo >>> 7))) >>> 0; // SHR 7 + + // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^64 (carry lo overflow) + w7 = w[i - 7]; + w16 = w[i - 16]; + lo = (t1_lo + w7[1] + t2_lo + w16[1]); + w[i][0] = (t1_hi + w7[0] + t2_hi + w16[0] + + ((lo / 0x100000000) >>> 0)) >>> 0; + w[i][1] = lo >>> 0; + } + + // initialize hash value for this chunk + a_hi = s[0][0]; + a_lo = s[0][1]; + b_hi = s[1][0]; + b_lo = s[1][1]; + c_hi = s[2][0]; + c_lo = s[2][1]; + d_hi = s[3][0]; + d_lo = s[3][1]; + e_hi = s[4][0]; + e_lo = s[4][1]; + f_hi = s[5][0]; + f_lo = s[5][1]; + g_hi = s[6][0]; + g_lo = s[6][1]; + h_hi = s[7][0]; + h_lo = s[7][1]; + + // round function + for(i = 0; i < 80; ++i) { + // Sum1(e) = ROTR 14(e) ^ ROTR 18(e) ^ ROTR 41(e) + s1_hi = ( + ((e_hi >>> 14) | (e_lo << 18)) ^ // ROTR 14 + ((e_hi >>> 18) | (e_lo << 14)) ^ // ROTR 18 + ((e_lo >>> 9) | (e_hi << 23))) >>> 0; // ROTR 41/(swap + ROTR 9) + s1_lo = ( + ((e_hi << 18) | (e_lo >>> 14)) ^ // ROTR 14 + ((e_hi << 14) | (e_lo >>> 18)) ^ // ROTR 18 + ((e_lo << 23) | (e_hi >>> 9))) >>> 0; // ROTR 41/(swap + ROTR 9) + + // Ch(e, f, g) (optimized the same way as SHA-1) + ch_hi = (g_hi ^ (e_hi & (f_hi ^ g_hi))) >>> 0; + ch_lo = (g_lo ^ (e_lo & (f_lo ^ g_lo))) >>> 0; + + // Sum0(a) = ROTR 28(a) ^ ROTR 34(a) ^ ROTR 39(a) + s0_hi = ( + ((a_hi >>> 28) | (a_lo << 4)) ^ // ROTR 28 + ((a_lo >>> 2) | (a_hi << 30)) ^ // ROTR 34/(swap + ROTR 2) + ((a_lo >>> 7) | (a_hi << 25))) >>> 0; // ROTR 39/(swap + ROTR 7) + s0_lo = ( + ((a_hi << 4) | (a_lo >>> 28)) ^ // ROTR 28 + ((a_lo << 30) | (a_hi >>> 2)) ^ // ROTR 34/(swap + ROTR 2) + ((a_lo << 25) | (a_hi >>> 7))) >>> 0; // ROTR 39/(swap + ROTR 7) + + // Maj(a, b, c) (optimized the same way as SHA-1) + maj_hi = ((a_hi & b_hi) | (c_hi & (a_hi ^ b_hi))) >>> 0; + maj_lo = ((a_lo & b_lo) | (c_lo & (a_lo ^ b_lo))) >>> 0; + + // main algorithm + // t1 = (h + s1 + ch + _k[i] + _w[i]) modulo 2^64 (carry lo overflow) + lo = (h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]); + t1_hi = (h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] + + ((lo / 0x100000000) >>> 0)) >>> 0; + t1_lo = lo >>> 0; + + // t2 = s0 + maj modulo 2^64 (carry lo overflow) + lo = s0_lo + maj_lo; + t2_hi = (s0_hi + maj_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + t2_lo = lo >>> 0; + + h_hi = g_hi; + h_lo = g_lo; + + g_hi = f_hi; + g_lo = f_lo; + + f_hi = e_hi; + f_lo = e_lo; + + // e = (d + t1) modulo 2^64 (carry lo overflow) + lo = d_lo + t1_lo; + e_hi = (d_hi + t1_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + e_lo = lo >>> 0; + + d_hi = c_hi; + d_lo = c_lo; + + c_hi = b_hi; + c_lo = b_lo; + + b_hi = a_hi; + b_lo = a_lo; + + // a = (t1 + t2) modulo 2^64 (carry lo overflow) + lo = t1_lo + t2_lo; + a_hi = (t1_hi + t2_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + a_lo = lo >>> 0; + } + + // update hash state (additional modulo 2^64) + lo = s[0][1] + a_lo; + s[0][0] = (s[0][0] + a_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[0][1] = lo >>> 0; + + lo = s[1][1] + b_lo; + s[1][0] = (s[1][0] + b_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[1][1] = lo >>> 0; + + lo = s[2][1] + c_lo; + s[2][0] = (s[2][0] + c_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[2][1] = lo >>> 0; + + lo = s[3][1] + d_lo; + s[3][0] = (s[3][0] + d_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[3][1] = lo >>> 0; + + lo = s[4][1] + e_lo; + s[4][0] = (s[4][0] + e_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[4][1] = lo >>> 0; + + lo = s[5][1] + f_lo; + s[5][0] = (s[5][0] + f_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[5][1] = lo >>> 0; + + lo = s[6][1] + g_lo; + s[6][0] = (s[6][0] + g_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[6][1] = lo >>> 0; + + lo = s[7][1] + h_lo; + s[7][0] = (s[7][0] + h_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[7][1] = lo >>> 0; + + len -= 128; + } +} diff --git a/node_modules/node-forge/lib/socket.js b/node_modules/node-forge/lib/socket.js new file mode 100644 index 0000000..3a1d7ff --- /dev/null +++ b/node_modules/node-forge/lib/socket.js @@ -0,0 +1,287 @@ +/** + * Socket implementation that uses flash SocketPool class as a backend. + * + * @author Dave Longley + * + * Copyright (c) 2010-2013 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./util'); + +// define net namespace +var net = module.exports = forge.net = forge.net || {}; + +// map of flash ID to socket pool +net.socketPools = {}; + +/** + * Creates a flash socket pool. + * + * @param options: + * flashId: the dom ID for the flash object element. + * policyPort: the default policy port for sockets, 0 to use the + * flash default. + * policyUrl: the default policy file URL for sockets (if provided + * used instead of a policy port). + * msie: true if the browser is msie, false if not. + * + * @return the created socket pool. + */ +net.createSocketPool = function(options) { + // set default + options.msie = options.msie || false; + + // initialize the flash interface + var spId = options.flashId; + var api = document.getElementById(spId); + api.init({marshallExceptions: !options.msie}); + + // create socket pool entry + var sp = { + // ID of the socket pool + id: spId, + // flash interface + flashApi: api, + // map of socket ID to sockets + sockets: {}, + // default policy port + policyPort: options.policyPort || 0, + // default policy URL + policyUrl: options.policyUrl || null + }; + net.socketPools[spId] = sp; + + // create event handler, subscribe to flash events + if(options.msie === true) { + sp.handler = function(e) { + if(e.id in sp.sockets) { + // get handler function + var f; + switch(e.type) { + case 'connect': + f = 'connected'; + break; + case 'close': + f = 'closed'; + break; + case 'socketData': + f = 'data'; + break; + default: + f = 'error'; + break; + } + /* IE calls javascript on the thread of the external object + that triggered the event (in this case flash) ... which will + either run concurrently with other javascript or pre-empt any + running javascript in the middle of its execution (BAD!) ... + calling setTimeout() will schedule the javascript to run on + the javascript thread and solve this EVIL problem. */ + setTimeout(function() {sp.sockets[e.id][f](e);}, 0); + } + }; + } else { + sp.handler = function(e) { + if(e.id in sp.sockets) { + // get handler function + var f; + switch(e.type) { + case 'connect': + f = 'connected'; + break; + case 'close': + f = 'closed'; + break; + case 'socketData': + f = 'data'; + break; + default: + f = 'error'; + break; + } + sp.sockets[e.id][f](e); + } + }; + } + var handler = 'forge.net.socketPools[\'' + spId + '\'].handler'; + api.subscribe('connect', handler); + api.subscribe('close', handler); + api.subscribe('socketData', handler); + api.subscribe('ioError', handler); + api.subscribe('securityError', handler); + + /** + * Destroys a socket pool. The socket pool still needs to be cleaned + * up via net.cleanup(). + */ + sp.destroy = function() { + delete net.socketPools[options.flashId]; + for(var id in sp.sockets) { + sp.sockets[id].destroy(); + } + sp.sockets = {}; + api.cleanup(); + }; + + /** + * Creates a new socket. + * + * @param options: + * connected: function(event) called when the socket connects. + * closed: function(event) called when the socket closes. + * data: function(event) called when socket data has arrived, + * it can be read from the socket using receive(). + * error: function(event) called when a socket error occurs. + */ + sp.createSocket = function(options) { + // default to empty options + options = options || {}; + + // create flash socket + var id = api.create(); + + // create javascript socket wrapper + var socket = { + id: id, + // set handlers + connected: options.connected || function(e) {}, + closed: options.closed || function(e) {}, + data: options.data || function(e) {}, + error: options.error || function(e) {} + }; + + /** + * Destroys this socket. + */ + socket.destroy = function() { + api.destroy(id); + delete sp.sockets[id]; + }; + + /** + * Connects this socket. + * + * @param options: + * host: the host to connect to. + * port: the port to connect to. + * policyPort: the policy port to use (if non-default), 0 to + * use the flash default. + * policyUrl: the policy file URL to use (instead of port). + */ + socket.connect = function(options) { + // give precedence to policy URL over policy port + // if no policy URL and passed port isn't 0, use default port, + // otherwise use 0 for the port + var policyUrl = options.policyUrl || null; + var policyPort = 0; + if(policyUrl === null && options.policyPort !== 0) { + policyPort = options.policyPort || sp.policyPort; + } + api.connect(id, options.host, options.port, policyPort, policyUrl); + }; + + /** + * Closes this socket. + */ + socket.close = function() { + api.close(id); + socket.closed({ + id: socket.id, + type: 'close', + bytesAvailable: 0 + }); + }; + + /** + * Determines if the socket is connected or not. + * + * @return true if connected, false if not. + */ + socket.isConnected = function() { + return api.isConnected(id); + }; + + /** + * Writes bytes to this socket. + * + * @param bytes the bytes (as a string) to write. + * + * @return true on success, false on failure. + */ + socket.send = function(bytes) { + return api.send(id, forge.util.encode64(bytes)); + }; + + /** + * Reads bytes from this socket (non-blocking). Fewer than the number + * of bytes requested may be read if enough bytes are not available. + * + * This method should be called from the data handler if there are + * enough bytes available. To see how many bytes are available, check + * the 'bytesAvailable' property on the event in the data handler or + * call the bytesAvailable() function on the socket. If the browser is + * msie, then the bytesAvailable() function should be used to avoid + * race conditions. Otherwise, using the property on the data handler's + * event may be quicker. + * + * @param count the maximum number of bytes to read. + * + * @return the bytes read (as a string) or null on error. + */ + socket.receive = function(count) { + var rval = api.receive(id, count).rval; + return (rval === null) ? null : forge.util.decode64(rval); + }; + + /** + * Gets the number of bytes available for receiving on the socket. + * + * @return the number of bytes available for receiving. + */ + socket.bytesAvailable = function() { + return api.getBytesAvailable(id); + }; + + // store and return socket + sp.sockets[id] = socket; + return socket; + }; + + return sp; +}; + +/** + * Destroys a flash socket pool. + * + * @param options: + * flashId: the dom ID for the flash object element. + */ +net.destroySocketPool = function(options) { + if(options.flashId in net.socketPools) { + var sp = net.socketPools[options.flashId]; + sp.destroy(); + } +}; + +/** + * Creates a new socket. + * + * @param options: + * flashId: the dom ID for the flash object element. + * connected: function(event) called when the socket connects. + * closed: function(event) called when the socket closes. + * data: function(event) called when socket data has arrived, it + * can be read from the socket using receive(). + * error: function(event) called when a socket error occurs. + * + * @return the created socket. + */ +net.createSocket = function(options) { + var socket = null; + if(options.flashId in net.socketPools) { + // get related socket pool + var sp = net.socketPools[options.flashId]; + socket = sp.createSocket(options); + } + return socket; +}; diff --git a/node_modules/node-forge/lib/ssh.js b/node_modules/node-forge/lib/ssh.js new file mode 100644 index 0000000..6480203 --- /dev/null +++ b/node_modules/node-forge/lib/ssh.js @@ -0,0 +1,236 @@ +/** + * Functions to output keys in SSH-friendly formats. + * + * This is part of the Forge project which may be used under the terms of + * either the BSD License or the GNU General Public License (GPL) Version 2. + * + * See: https://github.com/digitalbazaar/forge/blob/cbebca3780658703d925b61b2caffb1d263a6c1d/LICENSE + * + * @author https://github.com/shellac + */ +var forge = require('./forge'); +require('./aes'); +require('./hmac'); +require('./md5'); +require('./sha1'); +require('./util'); + +var ssh = module.exports = forge.ssh = forge.ssh || {}; + +/** + * Encodes (and optionally encrypts) a private RSA key as a Putty PPK file. + * + * @param privateKey the key. + * @param passphrase a passphrase to protect the key (falsy for no encryption). + * @param comment a comment to include in the key file. + * + * @return the PPK file as a string. + */ +ssh.privateKeyToPutty = function(privateKey, passphrase, comment) { + comment = comment || ''; + passphrase = passphrase || ''; + var algorithm = 'ssh-rsa'; + var encryptionAlgorithm = (passphrase === '') ? 'none' : 'aes256-cbc'; + + var ppk = 'PuTTY-User-Key-File-2: ' + algorithm + '\r\n'; + ppk += 'Encryption: ' + encryptionAlgorithm + '\r\n'; + ppk += 'Comment: ' + comment + '\r\n'; + + // public key into buffer for ppk + var pubbuffer = forge.util.createBuffer(); + _addStringToBuffer(pubbuffer, algorithm); + _addBigIntegerToBuffer(pubbuffer, privateKey.e); + _addBigIntegerToBuffer(pubbuffer, privateKey.n); + + // write public key + var pub = forge.util.encode64(pubbuffer.bytes(), 64); + var length = Math.floor(pub.length / 66) + 1; // 66 = 64 + \r\n + ppk += 'Public-Lines: ' + length + '\r\n'; + ppk += pub; + + // private key into a buffer + var privbuffer = forge.util.createBuffer(); + _addBigIntegerToBuffer(privbuffer, privateKey.d); + _addBigIntegerToBuffer(privbuffer, privateKey.p); + _addBigIntegerToBuffer(privbuffer, privateKey.q); + _addBigIntegerToBuffer(privbuffer, privateKey.qInv); + + // optionally encrypt the private key + var priv; + if(!passphrase) { + // use the unencrypted buffer + priv = forge.util.encode64(privbuffer.bytes(), 64); + } else { + // encrypt RSA key using passphrase + var encLen = privbuffer.length() + 16 - 1; + encLen -= encLen % 16; + + // pad private key with sha1-d data -- needs to be a multiple of 16 + var padding = _sha1(privbuffer.bytes()); + + padding.truncate(padding.length() - encLen + privbuffer.length()); + privbuffer.putBuffer(padding); + + var aeskey = forge.util.createBuffer(); + aeskey.putBuffer(_sha1('\x00\x00\x00\x00', passphrase)); + aeskey.putBuffer(_sha1('\x00\x00\x00\x01', passphrase)); + + // encrypt some bytes using CBC mode + // key is 40 bytes, so truncate *by* 8 bytes + var cipher = forge.aes.createEncryptionCipher(aeskey.truncate(8), 'CBC'); + cipher.start(forge.util.createBuffer().fillWithByte(0, 16)); + cipher.update(privbuffer.copy()); + cipher.finish(); + var encrypted = cipher.output; + + // Note: this appears to differ from Putty -- is forge wrong, or putty? + // due to padding we finish as an exact multiple of 16 + encrypted.truncate(16); // all padding + + priv = forge.util.encode64(encrypted.bytes(), 64); + } + + // output private key + length = Math.floor(priv.length / 66) + 1; // 64 + \r\n + ppk += '\r\nPrivate-Lines: ' + length + '\r\n'; + ppk += priv; + + // MAC + var mackey = _sha1('putty-private-key-file-mac-key', passphrase); + + var macbuffer = forge.util.createBuffer(); + _addStringToBuffer(macbuffer, algorithm); + _addStringToBuffer(macbuffer, encryptionAlgorithm); + _addStringToBuffer(macbuffer, comment); + macbuffer.putInt32(pubbuffer.length()); + macbuffer.putBuffer(pubbuffer); + macbuffer.putInt32(privbuffer.length()); + macbuffer.putBuffer(privbuffer); + + var hmac = forge.hmac.create(); + hmac.start('sha1', mackey); + hmac.update(macbuffer.bytes()); + + ppk += '\r\nPrivate-MAC: ' + hmac.digest().toHex() + '\r\n'; + + return ppk; +}; + +/** + * Encodes a public RSA key as an OpenSSH file. + * + * @param key the key. + * @param comment a comment. + * + * @return the public key in OpenSSH format. + */ +ssh.publicKeyToOpenSSH = function(key, comment) { + var type = 'ssh-rsa'; + comment = comment || ''; + + var buffer = forge.util.createBuffer(); + _addStringToBuffer(buffer, type); + _addBigIntegerToBuffer(buffer, key.e); + _addBigIntegerToBuffer(buffer, key.n); + + return type + ' ' + forge.util.encode64(buffer.bytes()) + ' ' + comment; +}; + +/** + * Encodes a private RSA key as an OpenSSH file. + * + * @param key the key. + * @param passphrase a passphrase to protect the key (falsy for no encryption). + * + * @return the public key in OpenSSH format. + */ +ssh.privateKeyToOpenSSH = function(privateKey, passphrase) { + if(!passphrase) { + return forge.pki.privateKeyToPem(privateKey); + } + // OpenSSH private key is just a legacy format, it seems + return forge.pki.encryptRsaPrivateKey(privateKey, passphrase, + {legacy: true, algorithm: 'aes128'}); +}; + +/** + * Gets the SSH fingerprint for the given public key. + * + * @param options the options to use. + * [md] the message digest object to use (defaults to forge.md.md5). + * [encoding] an alternative output encoding, such as 'hex' + * (defaults to none, outputs a byte buffer). + * [delimiter] the delimiter to use between bytes for 'hex' encoded + * output, eg: ':' (defaults to none). + * + * @return the fingerprint as a byte buffer or other encoding based on options. + */ +ssh.getPublicKeyFingerprint = function(key, options) { + options = options || {}; + var md = options.md || forge.md.md5.create(); + + var type = 'ssh-rsa'; + var buffer = forge.util.createBuffer(); + _addStringToBuffer(buffer, type); + _addBigIntegerToBuffer(buffer, key.e); + _addBigIntegerToBuffer(buffer, key.n); + + // hash public key bytes + md.start(); + md.update(buffer.getBytes()); + var digest = md.digest(); + if(options.encoding === 'hex') { + var hex = digest.toHex(); + if(options.delimiter) { + return hex.match(/.{2}/g).join(options.delimiter); + } + return hex; + } else if(options.encoding === 'binary') { + return digest.getBytes(); + } else if(options.encoding) { + throw new Error('Unknown encoding "' + options.encoding + '".'); + } + return digest; +}; + +/** + * Adds len(val) then val to a buffer. + * + * @param buffer the buffer to add to. + * @param val a big integer. + */ +function _addBigIntegerToBuffer(buffer, val) { + var hexVal = val.toString(16); + // ensure 2s complement +ve + if(hexVal[0] >= '8') { + hexVal = '00' + hexVal; + } + var bytes = forge.util.hexToBytes(hexVal); + buffer.putInt32(bytes.length); + buffer.putBytes(bytes); +} + +/** + * Adds len(val) then val to a buffer. + * + * @param buffer the buffer to add to. + * @param val a string. + */ +function _addStringToBuffer(buffer, val) { + buffer.putInt32(val.length); + buffer.putString(val); +} + +/** + * Hashes the arguments into one value using SHA-1. + * + * @return the sha1 hash of the provided arguments. + */ +function _sha1() { + var sha = forge.md.sha1.create(); + var num = arguments.length; + for (var i = 0; i < num; ++i) { + sha.update(arguments[i]); + } + return sha.digest(); +} diff --git a/node_modules/node-forge/lib/tls.js b/node_modules/node-forge/lib/tls.js new file mode 100644 index 0000000..00d4508 --- /dev/null +++ b/node_modules/node-forge/lib/tls.js @@ -0,0 +1,4282 @@ +/** + * A Javascript implementation of Transport Layer Security (TLS). + * + * @author Dave Longley + * + * Copyright (c) 2009-2014 Digital Bazaar, Inc. + * + * The TLS Handshake Protocol involves the following steps: + * + * - Exchange hello messages to agree on algorithms, exchange random values, + * and check for session resumption. + * + * - Exchange the necessary cryptographic parameters to allow the client and + * server to agree on a premaster secret. + * + * - Exchange certificates and cryptographic information to allow the client + * and server to authenticate themselves. + * + * - Generate a master secret from the premaster secret and exchanged random + * values. + * + * - Provide security parameters to the record layer. + * + * - Allow the client and server to verify that their peer has calculated the + * same security parameters and that the handshake occurred without tampering + * by an attacker. + * + * Up to 4 different messages may be sent during a key exchange. The server + * certificate, the server key exchange, the client certificate, and the + * client key exchange. + * + * A typical handshake (from the client's perspective). + * + * 1. Client sends ClientHello. + * 2. Client receives ServerHello. + * 3. Client receives optional Certificate. + * 4. Client receives optional ServerKeyExchange. + * 5. Client receives ServerHelloDone. + * 6. Client sends optional Certificate. + * 7. Client sends ClientKeyExchange. + * 8. Client sends optional CertificateVerify. + * 9. Client sends ChangeCipherSpec. + * 10. Client sends Finished. + * 11. Client receives ChangeCipherSpec. + * 12. Client receives Finished. + * 13. Client sends/receives application data. + * + * To reuse an existing session: + * + * 1. Client sends ClientHello with session ID for reuse. + * 2. Client receives ServerHello with same session ID if reusing. + * 3. Client receives ChangeCipherSpec message if reusing. + * 4. Client receives Finished. + * 5. Client sends ChangeCipherSpec. + * 6. Client sends Finished. + * + * Note: Client ignores HelloRequest if in the middle of a handshake. + * + * Record Layer: + * + * The record layer fragments information blocks into TLSPlaintext records + * carrying data in chunks of 2^14 bytes or less. Client message boundaries are + * not preserved in the record layer (i.e., multiple client messages of the + * same ContentType MAY be coalesced into a single TLSPlaintext record, or a + * single message MAY be fragmented across several records). + * + * struct { + * uint8 major; + * uint8 minor; + * } ProtocolVersion; + * + * struct { + * ContentType type; + * ProtocolVersion version; + * uint16 length; + * opaque fragment[TLSPlaintext.length]; + * } TLSPlaintext; + * + * type: + * The higher-level protocol used to process the enclosed fragment. + * + * version: + * The version of the protocol being employed. TLS Version 1.2 uses version + * {3, 3}. TLS Version 1.0 uses version {3, 1}. Note that a client that + * supports multiple versions of TLS may not know what version will be + * employed before it receives the ServerHello. + * + * length: + * The length (in bytes) of the following TLSPlaintext.fragment. The length + * MUST NOT exceed 2^14 = 16384 bytes. + * + * fragment: + * The application data. This data is transparent and treated as an + * independent block to be dealt with by the higher-level protocol specified + * by the type field. + * + * Implementations MUST NOT send zero-length fragments of Handshake, Alert, or + * ChangeCipherSpec content types. Zero-length fragments of Application data + * MAY be sent as they are potentially useful as a traffic analysis + * countermeasure. + * + * Note: Data of different TLS record layer content types MAY be interleaved. + * Application data is generally of lower precedence for transmission than + * other content types. However, records MUST be delivered to the network in + * the same order as they are protected by the record layer. Recipients MUST + * receive and process interleaved application layer traffic during handshakes + * subsequent to the first one on a connection. + * + * struct { + * ContentType type; // same as TLSPlaintext.type + * ProtocolVersion version;// same as TLSPlaintext.version + * uint16 length; + * opaque fragment[TLSCompressed.length]; + * } TLSCompressed; + * + * length: + * The length (in bytes) of the following TLSCompressed.fragment. + * The length MUST NOT exceed 2^14 + 1024. + * + * fragment: + * The compressed form of TLSPlaintext.fragment. + * + * Note: A CompressionMethod.null operation is an identity operation; no fields + * are altered. In this implementation, since no compression is supported, + * uncompressed records are always the same as compressed records. + * + * Encryption Information: + * + * The encryption and MAC functions translate a TLSCompressed structure into a + * TLSCiphertext. The decryption functions reverse the process. The MAC of the + * record also includes a sequence number so that missing, extra, or repeated + * messages are detectable. + * + * struct { + * ContentType type; + * ProtocolVersion version; + * uint16 length; + * select (SecurityParameters.cipher_type) { + * case stream: GenericStreamCipher; + * case block: GenericBlockCipher; + * case aead: GenericAEADCipher; + * } fragment; + * } TLSCiphertext; + * + * type: + * The type field is identical to TLSCompressed.type. + * + * version: + * The version field is identical to TLSCompressed.version. + * + * length: + * The length (in bytes) of the following TLSCiphertext.fragment. + * The length MUST NOT exceed 2^14 + 2048. + * + * fragment: + * The encrypted form of TLSCompressed.fragment, with the MAC. + * + * Note: Only CBC Block Ciphers are supported by this implementation. + * + * The TLSCompressed.fragment structures are converted to/from block + * TLSCiphertext.fragment structures. + * + * struct { + * opaque IV[SecurityParameters.record_iv_length]; + * block-ciphered struct { + * opaque content[TLSCompressed.length]; + * opaque MAC[SecurityParameters.mac_length]; + * uint8 padding[GenericBlockCipher.padding_length]; + * uint8 padding_length; + * }; + * } GenericBlockCipher; + * + * The MAC is generated as described in Section 6.2.3.1. + * + * IV: + * The Initialization Vector (IV) SHOULD be chosen at random, and MUST be + * unpredictable. Note that in versions of TLS prior to 1.1, there was no + * IV field, and the last ciphertext block of the previous record (the "CBC + * residue") was used as the IV. This was changed to prevent the attacks + * described in [CBCATT]. For block ciphers, the IV length is of length + * SecurityParameters.record_iv_length, which is equal to the + * SecurityParameters.block_size. + * + * padding: + * Padding that is added to force the length of the plaintext to be an + * integral multiple of the block cipher's block length. The padding MAY be + * any length up to 255 bytes, as long as it results in the + * TLSCiphertext.length being an integral multiple of the block length. + * Lengths longer than necessary might be desirable to frustrate attacks on + * a protocol that are based on analysis of the lengths of exchanged + * messages. Each uint8 in the padding data vector MUST be filled with the + * padding length value. The receiver MUST check this padding and MUST use + * the bad_record_mac alert to indicate padding errors. + * + * padding_length: + * The padding length MUST be such that the total size of the + * GenericBlockCipher structure is a multiple of the cipher's block length. + * Legal values range from zero to 255, inclusive. This length specifies the + * length of the padding field exclusive of the padding_length field itself. + * + * The encrypted data length (TLSCiphertext.length) is one more than the sum of + * SecurityParameters.block_length, TLSCompressed.length, + * SecurityParameters.mac_length, and padding_length. + * + * Example: If the block length is 8 bytes, the content length + * (TLSCompressed.length) is 61 bytes, and the MAC length is 20 bytes, then the + * length before padding is 82 bytes (this does not include the IV. Thus, the + * padding length modulo 8 must be equal to 6 in order to make the total length + * an even multiple of 8 bytes (the block length). The padding length can be + * 6, 14, 22, and so on, through 254. If the padding length were the minimum + * necessary, 6, the padding would be 6 bytes, each containing the value 6. + * Thus, the last 8 octets of the GenericBlockCipher before block encryption + * would be xx 06 06 06 06 06 06 06, where xx is the last octet of the MAC. + * + * Note: With block ciphers in CBC mode (Cipher Block Chaining), it is critical + * that the entire plaintext of the record be known before any ciphertext is + * transmitted. Otherwise, it is possible for the attacker to mount the attack + * described in [CBCATT]. + * + * Implementation note: Canvel et al. [CBCTIME] have demonstrated a timing + * attack on CBC padding based on the time required to compute the MAC. In + * order to defend against this attack, implementations MUST ensure that + * record processing time is essentially the same whether or not the padding + * is correct. In general, the best way to do this is to compute the MAC even + * if the padding is incorrect, and only then reject the packet. For instance, + * if the pad appears to be incorrect, the implementation might assume a + * zero-length pad and then compute the MAC. This leaves a small timing + * channel, since MAC performance depends, to some extent, on the size of the + * data fragment, but it is not believed to be large enough to be exploitable, + * due to the large block size of existing MACs and the small size of the + * timing signal. + */ +var forge = require('./forge'); +require('./asn1'); +require('./hmac'); +require('./md5'); +require('./pem'); +require('./pki'); +require('./random'); +require('./sha1'); +require('./util'); + +/** + * Generates pseudo random bytes by mixing the result of two hash functions, + * MD5 and SHA-1. + * + * prf_TLS1(secret, label, seed) = + * P_MD5(S1, label + seed) XOR P_SHA-1(S2, label + seed); + * + * Each P_hash function functions as follows: + * + * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) + + * HMAC_hash(secret, A(2) + seed) + + * HMAC_hash(secret, A(3) + seed) + ... + * A() is defined as: + * A(0) = seed + * A(i) = HMAC_hash(secret, A(i-1)) + * + * The '+' operator denotes concatenation. + * + * As many iterations A(N) as are needed are performed to generate enough + * pseudo random byte output. If an iteration creates more data than is + * necessary, then it is truncated. + * + * Therefore: + * A(1) = HMAC_hash(secret, A(0)) + * = HMAC_hash(secret, seed) + * A(2) = HMAC_hash(secret, A(1)) + * = HMAC_hash(secret, HMAC_hash(secret, seed)) + * + * Therefore: + * P_hash(secret, seed) = + * HMAC_hash(secret, HMAC_hash(secret, A(0)) + seed) + + * HMAC_hash(secret, HMAC_hash(secret, A(1)) + seed) + + * ... + * + * Therefore: + * P_hash(secret, seed) = + * HMAC_hash(secret, HMAC_hash(secret, seed) + seed) + + * HMAC_hash(secret, HMAC_hash(secret, HMAC_hash(secret, seed)) + seed) + + * ... + * + * @param secret the secret to use. + * @param label the label to use. + * @param seed the seed value to use. + * @param length the number of bytes to generate. + * + * @return the pseudo random bytes in a byte buffer. + */ +var prf_TLS1 = function(secret, label, seed, length) { + var rval = forge.util.createBuffer(); + + /* For TLS 1.0, the secret is split in half, into two secrets of equal + length. If the secret has an odd length then the last byte of the first + half will be the same as the first byte of the second. The length of the + two secrets is half of the secret rounded up. */ + var idx = (secret.length >> 1); + var slen = idx + (secret.length & 1); + var s1 = secret.substr(0, slen); + var s2 = secret.substr(idx, slen); + var ai = forge.util.createBuffer(); + var hmac = forge.hmac.create(); + seed = label + seed; + + // determine the number of iterations that must be performed to generate + // enough output bytes, md5 creates 16 byte hashes, sha1 creates 20 + var md5itr = Math.ceil(length / 16); + var sha1itr = Math.ceil(length / 20); + + // do md5 iterations + hmac.start('MD5', s1); + var md5bytes = forge.util.createBuffer(); + ai.putBytes(seed); + for(var i = 0; i < md5itr; ++i) { + // HMAC_hash(secret, A(i-1)) + hmac.start(null, null); + hmac.update(ai.getBytes()); + ai.putBuffer(hmac.digest()); + + // HMAC_hash(secret, A(i) + seed) + hmac.start(null, null); + hmac.update(ai.bytes() + seed); + md5bytes.putBuffer(hmac.digest()); + } + + // do sha1 iterations + hmac.start('SHA1', s2); + var sha1bytes = forge.util.createBuffer(); + ai.clear(); + ai.putBytes(seed); + for(var i = 0; i < sha1itr; ++i) { + // HMAC_hash(secret, A(i-1)) + hmac.start(null, null); + hmac.update(ai.getBytes()); + ai.putBuffer(hmac.digest()); + + // HMAC_hash(secret, A(i) + seed) + hmac.start(null, null); + hmac.update(ai.bytes() + seed); + sha1bytes.putBuffer(hmac.digest()); + } + + // XOR the md5 bytes with the sha1 bytes + rval.putBytes(forge.util.xorBytes( + md5bytes.getBytes(), sha1bytes.getBytes(), length)); + + return rval; +}; + +/** + * Generates pseudo random bytes using a SHA256 algorithm. For TLS 1.2. + * + * @param secret the secret to use. + * @param label the label to use. + * @param seed the seed value to use. + * @param length the number of bytes to generate. + * + * @return the pseudo random bytes in a byte buffer. + */ +var prf_sha256 = function(secret, label, seed, length) { + // FIXME: implement me for TLS 1.2 +}; + +/** + * Gets a MAC for a record using the SHA-1 hash algorithm. + * + * @param key the mac key. + * @param state the sequence number (array of two 32-bit integers). + * @param record the record. + * + * @return the sha-1 hash (20 bytes) for the given record. + */ +var hmac_sha1 = function(key, seqNum, record) { + /* MAC is computed like so: + HMAC_hash( + key, seqNum + + TLSCompressed.type + + TLSCompressed.version + + TLSCompressed.length + + TLSCompressed.fragment) + */ + var hmac = forge.hmac.create(); + hmac.start('SHA1', key); + var b = forge.util.createBuffer(); + b.putInt32(seqNum[0]); + b.putInt32(seqNum[1]); + b.putByte(record.type); + b.putByte(record.version.major); + b.putByte(record.version.minor); + b.putInt16(record.length); + b.putBytes(record.fragment.bytes()); + hmac.update(b.getBytes()); + return hmac.digest().getBytes(); +}; + +/** + * Compresses the TLSPlaintext record into a TLSCompressed record using the + * deflate algorithm. + * + * @param c the TLS connection. + * @param record the TLSPlaintext record to compress. + * @param s the ConnectionState to use. + * + * @return true on success, false on failure. + */ +var deflate = function(c, record, s) { + var rval = false; + + try { + var bytes = c.deflate(record.fragment.getBytes()); + record.fragment = forge.util.createBuffer(bytes); + record.length = bytes.length; + rval = true; + } catch(ex) { + // deflate error, fail out + } + + return rval; +}; + +/** + * Decompresses the TLSCompressed record into a TLSPlaintext record using the + * deflate algorithm. + * + * @param c the TLS connection. + * @param record the TLSCompressed record to decompress. + * @param s the ConnectionState to use. + * + * @return true on success, false on failure. + */ +var inflate = function(c, record, s) { + var rval = false; + + try { + var bytes = c.inflate(record.fragment.getBytes()); + record.fragment = forge.util.createBuffer(bytes); + record.length = bytes.length; + rval = true; + } catch(ex) { + // inflate error, fail out + } + + return rval; +}; + +/** + * Reads a TLS variable-length vector from a byte buffer. + * + * Variable-length vectors are defined by specifying a subrange of legal + * lengths, inclusively, using the notation . When these are + * encoded, the actual length precedes the vector's contents in the byte + * stream. The length will be in the form of a number consuming as many bytes + * as required to hold the vector's specified maximum (ceiling) length. A + * variable-length vector with an actual length field of zero is referred to + * as an empty vector. + * + * @param b the byte buffer. + * @param lenBytes the number of bytes required to store the length. + * + * @return the resulting byte buffer. + */ +var readVector = function(b, lenBytes) { + var len = 0; + switch(lenBytes) { + case 1: + len = b.getByte(); + break; + case 2: + len = b.getInt16(); + break; + case 3: + len = b.getInt24(); + break; + case 4: + len = b.getInt32(); + break; + } + + // read vector bytes into a new buffer + return forge.util.createBuffer(b.getBytes(len)); +}; + +/** + * Writes a TLS variable-length vector to a byte buffer. + * + * @param b the byte buffer. + * @param lenBytes the number of bytes required to store the length. + * @param v the byte buffer vector. + */ +var writeVector = function(b, lenBytes, v) { + // encode length at the start of the vector, where the number of bytes for + // the length is the maximum number of bytes it would take to encode the + // vector's ceiling + b.putInt(v.length(), lenBytes << 3); + b.putBuffer(v); +}; + +/** + * The tls implementation. + */ +var tls = {}; + +/** + * Version: TLS 1.2 = 3.3, TLS 1.1 = 3.2, TLS 1.0 = 3.1. Both TLS 1.1 and + * TLS 1.2 were still too new (ie: openSSL didn't implement them) at the time + * of this implementation so TLS 1.0 was implemented instead. + */ +tls.Versions = { + TLS_1_0: {major: 3, minor: 1}, + TLS_1_1: {major: 3, minor: 2}, + TLS_1_2: {major: 3, minor: 3} +}; +tls.SupportedVersions = [ + tls.Versions.TLS_1_1, + tls.Versions.TLS_1_0 +]; +tls.Version = tls.SupportedVersions[0]; + +/** + * Maximum fragment size. True maximum is 16384, but we fragment before that + * to allow for unusual small increases during compression. + */ +tls.MaxFragment = 16384 - 1024; + +/** + * Whether this entity is considered the "client" or "server". + * enum { server, client } ConnectionEnd; + */ +tls.ConnectionEnd = { + server: 0, + client: 1 +}; + +/** + * Pseudo-random function algorithm used to generate keys from the master + * secret. + * enum { tls_prf_sha256 } PRFAlgorithm; + */ +tls.PRFAlgorithm = { + tls_prf_sha256: 0 +}; + +/** + * Bulk encryption algorithms. + * enum { null, rc4, des3, aes } BulkCipherAlgorithm; + */ +tls.BulkCipherAlgorithm = { + none: null, + rc4: 0, + des3: 1, + aes: 2 +}; + +/** + * Cipher types. + * enum { stream, block, aead } CipherType; + */ +tls.CipherType = { + stream: 0, + block: 1, + aead: 2 +}; + +/** + * MAC (Message Authentication Code) algorithms. + * enum { null, hmac_md5, hmac_sha1, hmac_sha256, + * hmac_sha384, hmac_sha512} MACAlgorithm; + */ +tls.MACAlgorithm = { + none: null, + hmac_md5: 0, + hmac_sha1: 1, + hmac_sha256: 2, + hmac_sha384: 3, + hmac_sha512: 4 +}; + +/** + * Compression algorithms. + * enum { null(0), deflate(1), (255) } CompressionMethod; + */ +tls.CompressionMethod = { + none: 0, + deflate: 1 +}; + +/** + * TLS record content types. + * enum { + * change_cipher_spec(20), alert(21), handshake(22), + * application_data(23), (255) + * } ContentType; + */ +tls.ContentType = { + change_cipher_spec: 20, + alert: 21, + handshake: 22, + application_data: 23, + heartbeat: 24 +}; + +/** + * TLS handshake types. + * enum { + * hello_request(0), client_hello(1), server_hello(2), + * certificate(11), server_key_exchange (12), + * certificate_request(13), server_hello_done(14), + * certificate_verify(15), client_key_exchange(16), + * finished(20), (255) + * } HandshakeType; + */ +tls.HandshakeType = { + hello_request: 0, + client_hello: 1, + server_hello: 2, + certificate: 11, + server_key_exchange: 12, + certificate_request: 13, + server_hello_done: 14, + certificate_verify: 15, + client_key_exchange: 16, + finished: 20 +}; + +/** + * TLS Alert Protocol. + * + * enum { warning(1), fatal(2), (255) } AlertLevel; + * + * enum { + * close_notify(0), + * unexpected_message(10), + * bad_record_mac(20), + * decryption_failed(21), + * record_overflow(22), + * decompression_failure(30), + * handshake_failure(40), + * bad_certificate(42), + * unsupported_certificate(43), + * certificate_revoked(44), + * certificate_expired(45), + * certificate_unknown(46), + * illegal_parameter(47), + * unknown_ca(48), + * access_denied(49), + * decode_error(50), + * decrypt_error(51), + * export_restriction(60), + * protocol_version(70), + * insufficient_security(71), + * internal_error(80), + * user_canceled(90), + * no_renegotiation(100), + * (255) + * } AlertDescription; + * + * struct { + * AlertLevel level; + * AlertDescription description; + * } Alert; + */ +tls.Alert = {}; +tls.Alert.Level = { + warning: 1, + fatal: 2 +}; +tls.Alert.Description = { + close_notify: 0, + unexpected_message: 10, + bad_record_mac: 20, + decryption_failed: 21, + record_overflow: 22, + decompression_failure: 30, + handshake_failure: 40, + bad_certificate: 42, + unsupported_certificate: 43, + certificate_revoked: 44, + certificate_expired: 45, + certificate_unknown: 46, + illegal_parameter: 47, + unknown_ca: 48, + access_denied: 49, + decode_error: 50, + decrypt_error: 51, + export_restriction: 60, + protocol_version: 70, + insufficient_security: 71, + internal_error: 80, + user_canceled: 90, + no_renegotiation: 100 +}; + +/** + * TLS Heartbeat Message types. + * enum { + * heartbeat_request(1), + * heartbeat_response(2), + * (255) + * } HeartbeatMessageType; + */ +tls.HeartbeatMessageType = { + heartbeat_request: 1, + heartbeat_response: 2 +}; + +/** + * Supported cipher suites. + */ +tls.CipherSuites = {}; + +/** + * Gets a supported cipher suite from its 2 byte ID. + * + * @param twoBytes two bytes in a string. + * + * @return the matching supported cipher suite or null. + */ +tls.getCipherSuite = function(twoBytes) { + var rval = null; + for(var key in tls.CipherSuites) { + var cs = tls.CipherSuites[key]; + if(cs.id[0] === twoBytes.charCodeAt(0) && + cs.id[1] === twoBytes.charCodeAt(1)) { + rval = cs; + break; + } + } + return rval; +}; + +/** + * Called when an unexpected record is encountered. + * + * @param c the connection. + * @param record the record. + */ +tls.handleUnexpected = function(c, record) { + // if connection is client and closed, ignore unexpected messages + var ignore = (!c.open && c.entity === tls.ConnectionEnd.client); + if(!ignore) { + c.error(c, { + message: 'Unexpected message. Received TLS record out of order.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unexpected_message + } + }); + } +}; + +/** + * Called when a client receives a HelloRequest record. + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleHelloRequest = function(c, record, length) { + // ignore renegotiation requests from the server during a handshake, but + // if handshaking, send a warning alert that renegotiation is denied + if(!c.handshaking && c.handshakes > 0) { + // send alert warning + tls.queue(c, tls.createAlert(c, { + level: tls.Alert.Level.warning, + description: tls.Alert.Description.no_renegotiation + })); + tls.flush(c); + } + + // continue + c.process(); +}; + +/** + * Parses a hello message from a ClientHello or ServerHello record. + * + * @param record the record to parse. + * + * @return the parsed message. + */ +tls.parseHelloMessage = function(c, record, length) { + var msg = null; + + var client = (c.entity === tls.ConnectionEnd.client); + + // minimum of 38 bytes in message + if(length < 38) { + c.error(c, { + message: client ? + 'Invalid ServerHello message. Message too short.' : + 'Invalid ClientHello message. Message too short.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } else { + // use 'remaining' to calculate # of remaining bytes in the message + var b = record.fragment; + var remaining = b.length(); + msg = { + version: { + major: b.getByte(), + minor: b.getByte() + }, + random: forge.util.createBuffer(b.getBytes(32)), + session_id: readVector(b, 1), + extensions: [] + }; + if(client) { + msg.cipher_suite = b.getBytes(2); + msg.compression_method = b.getByte(); + } else { + msg.cipher_suites = readVector(b, 2); + msg.compression_methods = readVector(b, 1); + } + + // read extensions if there are any bytes left in the message + remaining = length - (remaining - b.length()); + if(remaining > 0) { + // parse extensions + var exts = readVector(b, 2); + while(exts.length() > 0) { + msg.extensions.push({ + type: [exts.getByte(), exts.getByte()], + data: readVector(exts, 2) + }); + } + + // TODO: make extension support modular + if(!client) { + for(var i = 0; i < msg.extensions.length; ++i) { + var ext = msg.extensions[i]; + + // support SNI extension + if(ext.type[0] === 0x00 && ext.type[1] === 0x00) { + // get server name list + var snl = readVector(ext.data, 2); + while(snl.length() > 0) { + // read server name type + var snType = snl.getByte(); + + // only HostName type (0x00) is known, break out if + // another type is detected + if(snType !== 0x00) { + break; + } + + // add host name to server name list + c.session.extensions.server_name.serverNameList.push( + readVector(snl, 2).getBytes()); + } + } + } + } + } + + // version already set, do not allow version change + if(c.session.version) { + if(msg.version.major !== c.session.version.major || + msg.version.minor !== c.session.version.minor) { + return c.error(c, { + message: 'TLS version change is disallowed during renegotiation.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.protocol_version + } + }); + } + } + + // get the chosen (ServerHello) cipher suite + if(client) { + // FIXME: should be checking configured acceptable cipher suites + c.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite); + } else { + // get a supported preferred (ClientHello) cipher suite + // choose the first supported cipher suite + var tmp = forge.util.createBuffer(msg.cipher_suites.bytes()); + while(tmp.length() > 0) { + // FIXME: should be checking configured acceptable suites + // cipher suites take up 2 bytes + c.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2)); + if(c.session.cipherSuite !== null) { + break; + } + } + } + + // cipher suite not supported + if(c.session.cipherSuite === null) { + return c.error(c, { + message: 'No cipher suites in common.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.handshake_failure + }, + cipherSuite: forge.util.bytesToHex(msg.cipher_suite) + }); + } + + // TODO: handle compression methods + if(client) { + c.session.compressionMethod = msg.compression_method; + } else { + // no compression + c.session.compressionMethod = tls.CompressionMethod.none; + } + } + + return msg; +}; + +/** + * Creates security parameters for the given connection based on the given + * hello message. + * + * @param c the TLS connection. + * @param msg the hello message. + */ +tls.createSecurityParameters = function(c, msg) { + /* Note: security params are from TLS 1.2, some values like prf_algorithm + are ignored for TLS 1.0/1.1 and the builtin as specified in the spec is + used. */ + + // TODO: handle other options from server when more supported + + // get client and server randoms + var client = (c.entity === tls.ConnectionEnd.client); + var msgRandom = msg.random.bytes(); + var cRandom = client ? c.session.sp.client_random : msgRandom; + var sRandom = client ? msgRandom : tls.createRandom().getBytes(); + + // create new security parameters + c.session.sp = { + entity: c.entity, + prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256, + bulk_cipher_algorithm: null, + cipher_type: null, + enc_key_length: null, + block_length: null, + fixed_iv_length: null, + record_iv_length: null, + mac_algorithm: null, + mac_length: null, + mac_key_length: null, + compression_algorithm: c.session.compressionMethod, + pre_master_secret: null, + master_secret: null, + client_random: cRandom, + server_random: sRandom + }; +}; + +/** + * Called when a client receives a ServerHello record. + * + * When a ServerHello message will be sent: + * The server will send this message in response to a client hello message + * when it was able to find an acceptable set of algorithms. If it cannot + * find such a match, it will respond with a handshake failure alert. + * + * uint24 length; + * struct { + * ProtocolVersion server_version; + * Random random; + * SessionID session_id; + * CipherSuite cipher_suite; + * CompressionMethod compression_method; + * select(extensions_present) { + * case false: + * struct {}; + * case true: + * Extension extensions<0..2^16-1>; + * }; + * } ServerHello; + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleServerHello = function(c, record, length) { + var msg = tls.parseHelloMessage(c, record, length); + if(c.fail) { + return; + } + + // ensure server version is compatible + if(msg.version.minor <= c.version.minor) { + c.version.minor = msg.version.minor; + } else { + return c.error(c, { + message: 'Incompatible TLS version.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.protocol_version + } + }); + } + + // indicate session version has been set + c.session.version = c.version; + + // get the session ID from the message + var sessionId = msg.session_id.bytes(); + + // if the session ID is not blank and matches the cached one, resume + // the session + if(sessionId.length > 0 && sessionId === c.session.id) { + // resuming session, expect a ChangeCipherSpec next + c.expect = SCC; + c.session.resuming = true; + + // get new server random + c.session.sp.server_random = msg.random.bytes(); + } else { + // not resuming, expect a server Certificate message next + c.expect = SCE; + c.session.resuming = false; + + // create new security parameters + tls.createSecurityParameters(c, msg); + } + + // set new session ID + c.session.id = sessionId; + + // continue + c.process(); +}; + +/** + * Called when a server receives a ClientHello record. + * + * When a ClientHello message will be sent: + * When a client first connects to a server it is required to send the + * client hello as its first message. The client can also send a client + * hello in response to a hello request or on its own initiative in order + * to renegotiate the security parameters in an existing connection. + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleClientHello = function(c, record, length) { + var msg = tls.parseHelloMessage(c, record, length); + if(c.fail) { + return; + } + + // get the session ID from the message + var sessionId = msg.session_id.bytes(); + + // see if the given session ID is in the cache + var session = null; + if(c.sessionCache) { + session = c.sessionCache.getSession(sessionId); + if(session === null) { + // session ID not found + sessionId = ''; + } else if(session.version.major !== msg.version.major || + session.version.minor > msg.version.minor) { + // if session version is incompatible with client version, do not resume + session = null; + sessionId = ''; + } + } + + // no session found to resume, generate a new session ID + if(sessionId.length === 0) { + sessionId = forge.random.getBytes(32); + } + + // update session + c.session.id = sessionId; + c.session.clientHelloVersion = msg.version; + c.session.sp = {}; + if(session) { + // use version and security parameters from resumed session + c.version = c.session.version = session.version; + c.session.sp = session.sp; + } else { + // use highest compatible minor version + var version; + for(var i = 1; i < tls.SupportedVersions.length; ++i) { + version = tls.SupportedVersions[i]; + if(version.minor <= msg.version.minor) { + break; + } + } + c.version = {major: version.major, minor: version.minor}; + c.session.version = c.version; + } + + // if a session is set, resume it + if(session !== null) { + // resuming session, expect a ChangeCipherSpec next + c.expect = CCC; + c.session.resuming = true; + + // get new client random + c.session.sp.client_random = msg.random.bytes(); + } else { + // not resuming, expect a Certificate or ClientKeyExchange + c.expect = (c.verifyClient !== false) ? CCE : CKE; + c.session.resuming = false; + + // create new security parameters + tls.createSecurityParameters(c, msg); + } + + // connection now open + c.open = true; + + // queue server hello + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createServerHello(c) + })); + + if(c.session.resuming) { + // queue change cipher spec message + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.change_cipher_spec, + data: tls.createChangeCipherSpec() + })); + + // create pending state + c.state.pending = tls.createConnectionState(c); + + // change current write state to pending write state + c.state.current.write = c.state.pending.write; + + // queue finished + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createFinished(c) + })); + } else { + // queue server certificate + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificate(c) + })); + + if(!c.fail) { + // queue server key exchange + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createServerKeyExchange(c) + })); + + // request client certificate if set + if(c.verifyClient !== false) { + // queue certificate request + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificateRequest(c) + })); + } + + // queue server hello done + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createServerHelloDone(c) + })); + } + } + + // send records + tls.flush(c); + + // continue + c.process(); +}; + +/** + * Called when a client receives a Certificate record. + * + * When this message will be sent: + * The server must send a certificate whenever the agreed-upon key exchange + * method is not an anonymous one. This message will always immediately + * follow the server hello message. + * + * Meaning of this message: + * The certificate type must be appropriate for the selected cipher suite's + * key exchange algorithm, and is generally an X.509v3 certificate. It must + * contain a key which matches the key exchange method, as follows. Unless + * otherwise specified, the signing algorithm for the certificate must be + * the same as the algorithm for the certificate key. Unless otherwise + * specified, the public key may be of any length. + * + * opaque ASN.1Cert<1..2^24-1>; + * struct { + * ASN.1Cert certificate_list<1..2^24-1>; + * } Certificate; + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleCertificate = function(c, record, length) { + // minimum of 3 bytes in message + if(length < 3) { + return c.error(c, { + message: 'Invalid Certificate message. Message too short.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } + + var b = record.fragment; + var msg = { + certificate_list: readVector(b, 3) + }; + + /* The sender's certificate will be first in the list (chain), each + subsequent one that follows will certify the previous one, but root + certificates (self-signed) that specify the certificate authority may + be omitted under the assumption that clients must already possess it. */ + var cert, asn1; + var certs = []; + try { + while(msg.certificate_list.length() > 0) { + // each entry in msg.certificate_list is a vector with 3 len bytes + cert = readVector(msg.certificate_list, 3); + asn1 = forge.asn1.fromDer(cert); + cert = forge.pki.certificateFromAsn1(asn1, true); + certs.push(cert); + } + } catch(ex) { + return c.error(c, { + message: 'Could not parse certificate list.', + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.bad_certificate + } + }); + } + + // ensure at least 1 certificate was provided if in client-mode + // or if verifyClient was set to true to require a certificate + // (as opposed to 'optional') + var client = (c.entity === tls.ConnectionEnd.client); + if((client || c.verifyClient === true) && certs.length === 0) { + // error, no certificate + c.error(c, { + message: client ? + 'No server certificate provided.' : + 'No client certificate provided.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } else if(certs.length === 0) { + // no certs to verify + // expect a ServerKeyExchange or ClientKeyExchange message next + c.expect = client ? SKE : CKE; + } else { + // save certificate in session + if(client) { + c.session.serverCertificate = certs[0]; + } else { + c.session.clientCertificate = certs[0]; + } + + if(tls.verifyCertificateChain(c, certs)) { + // expect a ServerKeyExchange or ClientKeyExchange message next + c.expect = client ? SKE : CKE; + } + } + + // continue + c.process(); +}; + +/** + * Called when a client receives a ServerKeyExchange record. + * + * When this message will be sent: + * This message will be sent immediately after the server certificate + * message (or the server hello message, if this is an anonymous + * negotiation). + * + * The server key exchange message is sent by the server only when the + * server certificate message (if sent) does not contain enough data to + * allow the client to exchange a premaster secret. + * + * Meaning of this message: + * This message conveys cryptographic information to allow the client to + * communicate the premaster secret: either an RSA public key to encrypt + * the premaster secret with, or a Diffie-Hellman public key with which the + * client can complete a key exchange (with the result being the premaster + * secret.) + * + * enum { + * dhe_dss, dhe_rsa, dh_anon, rsa, dh_dss, dh_rsa + * } KeyExchangeAlgorithm; + * + * struct { + * opaque dh_p<1..2^16-1>; + * opaque dh_g<1..2^16-1>; + * opaque dh_Ys<1..2^16-1>; + * } ServerDHParams; + * + * struct { + * select(KeyExchangeAlgorithm) { + * case dh_anon: + * ServerDHParams params; + * case dhe_dss: + * case dhe_rsa: + * ServerDHParams params; + * digitally-signed struct { + * opaque client_random[32]; + * opaque server_random[32]; + * ServerDHParams params; + * } signed_params; + * case rsa: + * case dh_dss: + * case dh_rsa: + * struct {}; + * }; + * } ServerKeyExchange; + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleServerKeyExchange = function(c, record, length) { + // this implementation only supports RSA, no Diffie-Hellman support + // so any length > 0 is invalid + if(length > 0) { + return c.error(c, { + message: 'Invalid key parameters. Only RSA is supported.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unsupported_certificate + } + }); + } + + // expect an optional CertificateRequest message next + c.expect = SCR; + + // continue + c.process(); +}; + +/** + * Called when a client receives a ClientKeyExchange record. + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleClientKeyExchange = function(c, record, length) { + // this implementation only supports RSA, no Diffie-Hellman support + // so any length < 48 is invalid + if(length < 48) { + return c.error(c, { + message: 'Invalid key parameters. Only RSA is supported.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unsupported_certificate + } + }); + } + + var b = record.fragment; + var msg = { + enc_pre_master_secret: readVector(b, 2).getBytes() + }; + + // do rsa decryption + var privateKey = null; + if(c.getPrivateKey) { + try { + privateKey = c.getPrivateKey(c, c.session.serverCertificate); + privateKey = forge.pki.privateKeyFromPem(privateKey); + } catch(ex) { + c.error(c, { + message: 'Could not get private key.', + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } + } + + if(privateKey === null) { + return c.error(c, { + message: 'No private key set.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } + + try { + // decrypt 48-byte pre-master secret + var sp = c.session.sp; + sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret); + + // ensure client hello version matches first 2 bytes + var version = c.session.clientHelloVersion; + if(version.major !== sp.pre_master_secret.charCodeAt(0) || + version.minor !== sp.pre_master_secret.charCodeAt(1)) { + // error, do not send alert (see BLEI attack below) + throw new Error('TLS version rollback attack detected.'); + } + } catch(ex) { + /* Note: Daniel Bleichenbacher [BLEI] can be used to attack a + TLS server which is using PKCS#1 encoded RSA, so instead of + failing here, we generate 48 random bytes and use that as + the pre-master secret. */ + sp.pre_master_secret = forge.random.getBytes(48); + } + + // expect a CertificateVerify message if a Certificate was received that + // does not have fixed Diffie-Hellman params, otherwise expect + // ChangeCipherSpec + c.expect = CCC; + if(c.session.clientCertificate !== null) { + // only RSA support, so expect CertificateVerify + // TODO: support Diffie-Hellman + c.expect = CCV; + } + + // continue + c.process(); +}; + +/** + * Called when a client receives a CertificateRequest record. + * + * When this message will be sent: + * A non-anonymous server can optionally request a certificate from the + * client, if appropriate for the selected cipher suite. This message, if + * sent, will immediately follow the Server Key Exchange message (if it is + * sent; otherwise, the Server Certificate message). + * + * enum { + * rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4), + * rsa_ephemeral_dh_RESERVED(5), dss_ephemeral_dh_RESERVED(6), + * fortezza_dms_RESERVED(20), (255) + * } ClientCertificateType; + * + * opaque DistinguishedName<1..2^16-1>; + * + * struct { + * ClientCertificateType certificate_types<1..2^8-1>; + * SignatureAndHashAlgorithm supported_signature_algorithms<2^16-1>; + * DistinguishedName certificate_authorities<0..2^16-1>; + * } CertificateRequest; + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleCertificateRequest = function(c, record, length) { + // minimum of 3 bytes in message + if(length < 3) { + return c.error(c, { + message: 'Invalid CertificateRequest. Message too short.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } + + // TODO: TLS 1.2+ has different format including + // SignatureAndHashAlgorithm after cert types + var b = record.fragment; + var msg = { + certificate_types: readVector(b, 1), + certificate_authorities: readVector(b, 2) + }; + + // save certificate request in session + c.session.certificateRequest = msg; + + // expect a ServerHelloDone message next + c.expect = SHD; + + // continue + c.process(); +}; + +/** + * Called when a server receives a CertificateVerify record. + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleCertificateVerify = function(c, record, length) { + if(length < 2) { + return c.error(c, { + message: 'Invalid CertificateVerify. Message too short.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } + + // rewind to get full bytes for message so it can be manually + // digested below (special case for CertificateVerify messages because + // they must be digested *after* handling as opposed to all others) + var b = record.fragment; + b.read -= 4; + var msgBytes = b.bytes(); + b.read += 4; + + var msg = { + signature: readVector(b, 2).getBytes() + }; + + // TODO: add support for DSA + + // generate data to verify + var verify = forge.util.createBuffer(); + verify.putBuffer(c.session.md5.digest()); + verify.putBuffer(c.session.sha1.digest()); + verify = verify.getBytes(); + + try { + var cert = c.session.clientCertificate; + /*b = forge.pki.rsa.decrypt( + msg.signature, cert.publicKey, true, verify.length); + if(b !== verify) {*/ + if(!cert.publicKey.verify(verify, msg.signature, 'NONE')) { + throw new Error('CertificateVerify signature does not match.'); + } + + // digest message now that it has been handled + c.session.md5.update(msgBytes); + c.session.sha1.update(msgBytes); + } catch(ex) { + return c.error(c, { + message: 'Bad signature in CertificateVerify.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.handshake_failure + } + }); + } + + // expect ChangeCipherSpec + c.expect = CCC; + + // continue + c.process(); +}; + +/** + * Called when a client receives a ServerHelloDone record. + * + * When this message will be sent: + * The server hello done message is sent by the server to indicate the end + * of the server hello and associated messages. After sending this message + * the server will wait for a client response. + * + * Meaning of this message: + * This message means that the server is done sending messages to support + * the key exchange, and the client can proceed with its phase of the key + * exchange. + * + * Upon receipt of the server hello done message the client should verify + * that the server provided a valid certificate if required and check that + * the server hello parameters are acceptable. + * + * struct {} ServerHelloDone; + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleServerHelloDone = function(c, record, length) { + // len must be 0 bytes + if(length > 0) { + return c.error(c, { + message: 'Invalid ServerHelloDone message. Invalid length.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.record_overflow + } + }); + } + + if(c.serverCertificate === null) { + // no server certificate was provided + var error = { + message: 'No server certificate provided. Not enough security.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.insufficient_security + } + }; + + // call application callback + var depth = 0; + var ret = c.verify(c, error.alert.description, depth, []); + if(ret !== true) { + // check for custom alert info + if(ret || ret === 0) { + // set custom message and alert description + if(typeof ret === 'object' && !forge.util.isArray(ret)) { + if(ret.message) { + error.message = ret.message; + } + if(ret.alert) { + error.alert.description = ret.alert; + } + } else if(typeof ret === 'number') { + // set custom alert description + error.alert.description = ret; + } + } + + // send error + return c.error(c, error); + } + } + + // create client certificate message if requested + if(c.session.certificateRequest !== null) { + record = tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificate(c) + }); + tls.queue(c, record); + } + + // create client key exchange message + record = tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createClientKeyExchange(c) + }); + tls.queue(c, record); + + // expect no messages until the following callback has been called + c.expect = SER; + + // create callback to handle client signature (for client-certs) + var callback = function(c, signature) { + if(c.session.certificateRequest !== null && + c.session.clientCertificate !== null) { + // create certificate verify message + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificateVerify(c, signature) + })); + } + + // create change cipher spec message + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.change_cipher_spec, + data: tls.createChangeCipherSpec() + })); + + // create pending state + c.state.pending = tls.createConnectionState(c); + + // change current write state to pending write state + c.state.current.write = c.state.pending.write; + + // create finished message + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createFinished(c) + })); + + // expect a server ChangeCipherSpec message next + c.expect = SCC; + + // send records + tls.flush(c); + + // continue + c.process(); + }; + + // if there is no certificate request or no client certificate, do + // callback immediately + if(c.session.certificateRequest === null || + c.session.clientCertificate === null) { + return callback(c, null); + } + + // otherwise get the client signature + tls.getClientSignature(c, callback); +}; + +/** + * Called when a ChangeCipherSpec record is received. + * + * @param c the connection. + * @param record the record. + */ +tls.handleChangeCipherSpec = function(c, record) { + if(record.fragment.getByte() !== 0x01) { + return c.error(c, { + message: 'Invalid ChangeCipherSpec message received.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } + + // create pending state if: + // 1. Resuming session in client mode OR + // 2. NOT resuming session in server mode + var client = (c.entity === tls.ConnectionEnd.client); + if((c.session.resuming && client) || (!c.session.resuming && !client)) { + c.state.pending = tls.createConnectionState(c); + } + + // change current read state to pending read state + c.state.current.read = c.state.pending.read; + + // clear pending state if: + // 1. NOT resuming session in client mode OR + // 2. resuming a session in server mode + if((!c.session.resuming && client) || (c.session.resuming && !client)) { + c.state.pending = null; + } + + // expect a Finished record next + c.expect = client ? SFI : CFI; + + // continue + c.process(); +}; + +/** + * Called when a Finished record is received. + * + * When this message will be sent: + * A finished message is always sent immediately after a change + * cipher spec message to verify that the key exchange and + * authentication processes were successful. It is essential that a + * change cipher spec message be received between the other + * handshake messages and the Finished message. + * + * Meaning of this message: + * The finished message is the first protected with the just- + * negotiated algorithms, keys, and secrets. Recipients of finished + * messages must verify that the contents are correct. Once a side + * has sent its Finished message and received and validated the + * Finished message from its peer, it may begin to send and receive + * application data over the connection. + * + * struct { + * opaque verify_data[verify_data_length]; + * } Finished; + * + * verify_data + * PRF(master_secret, finished_label, Hash(handshake_messages)) + * [0..verify_data_length-1]; + * + * finished_label + * For Finished messages sent by the client, the string + * "client finished". For Finished messages sent by the server, the + * string "server finished". + * + * verify_data_length depends on the cipher suite. If it is not specified + * by the cipher suite, then it is 12. Versions of TLS < 1.2 always used + * 12 bytes. + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleFinished = function(c, record, length) { + // rewind to get full bytes for message so it can be manually + // digested below (special case for Finished messages because they + // must be digested *after* handling as opposed to all others) + var b = record.fragment; + b.read -= 4; + var msgBytes = b.bytes(); + b.read += 4; + + // message contains only verify_data + var vd = record.fragment.getBytes(); + + // ensure verify data is correct + b = forge.util.createBuffer(); + b.putBuffer(c.session.md5.digest()); + b.putBuffer(c.session.sha1.digest()); + + // set label based on entity type + var client = (c.entity === tls.ConnectionEnd.client); + var label = client ? 'server finished' : 'client finished'; + + // TODO: determine prf function and verify length for TLS 1.2 + var sp = c.session.sp; + var vdl = 12; + var prf = prf_TLS1; + b = prf(sp.master_secret, label, b.getBytes(), vdl); + if(b.getBytes() !== vd) { + return c.error(c, { + message: 'Invalid verify_data in Finished message.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.decrypt_error + } + }); + } + + // digest finished message now that it has been handled + c.session.md5.update(msgBytes); + c.session.sha1.update(msgBytes); + + // resuming session as client or NOT resuming session as server + if((c.session.resuming && client) || (!c.session.resuming && !client)) { + // create change cipher spec message + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.change_cipher_spec, + data: tls.createChangeCipherSpec() + })); + + // change current write state to pending write state, clear pending + c.state.current.write = c.state.pending.write; + c.state.pending = null; + + // create finished message + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createFinished(c) + })); + } + + // expect application data next + c.expect = client ? SAD : CAD; + + // handshake complete + c.handshaking = false; + ++c.handshakes; + + // save access to peer certificate + c.peerCertificate = client ? + c.session.serverCertificate : c.session.clientCertificate; + + // send records + tls.flush(c); + + // now connected + c.isConnected = true; + c.connected(c); + + // continue + c.process(); +}; + +/** + * Called when an Alert record is received. + * + * @param c the connection. + * @param record the record. + */ +tls.handleAlert = function(c, record) { + // read alert + var b = record.fragment; + var alert = { + level: b.getByte(), + description: b.getByte() + }; + + // TODO: consider using a table? + // get appropriate message + var msg; + switch(alert.description) { + case tls.Alert.Description.close_notify: + msg = 'Connection closed.'; + break; + case tls.Alert.Description.unexpected_message: + msg = 'Unexpected message.'; + break; + case tls.Alert.Description.bad_record_mac: + msg = 'Bad record MAC.'; + break; + case tls.Alert.Description.decryption_failed: + msg = 'Decryption failed.'; + break; + case tls.Alert.Description.record_overflow: + msg = 'Record overflow.'; + break; + case tls.Alert.Description.decompression_failure: + msg = 'Decompression failed.'; + break; + case tls.Alert.Description.handshake_failure: + msg = 'Handshake failure.'; + break; + case tls.Alert.Description.bad_certificate: + msg = 'Bad certificate.'; + break; + case tls.Alert.Description.unsupported_certificate: + msg = 'Unsupported certificate.'; + break; + case tls.Alert.Description.certificate_revoked: + msg = 'Certificate revoked.'; + break; + case tls.Alert.Description.certificate_expired: + msg = 'Certificate expired.'; + break; + case tls.Alert.Description.certificate_unknown: + msg = 'Certificate unknown.'; + break; + case tls.Alert.Description.illegal_parameter: + msg = 'Illegal parameter.'; + break; + case tls.Alert.Description.unknown_ca: + msg = 'Unknown certificate authority.'; + break; + case tls.Alert.Description.access_denied: + msg = 'Access denied.'; + break; + case tls.Alert.Description.decode_error: + msg = 'Decode error.'; + break; + case tls.Alert.Description.decrypt_error: + msg = 'Decrypt error.'; + break; + case tls.Alert.Description.export_restriction: + msg = 'Export restriction.'; + break; + case tls.Alert.Description.protocol_version: + msg = 'Unsupported protocol version.'; + break; + case tls.Alert.Description.insufficient_security: + msg = 'Insufficient security.'; + break; + case tls.Alert.Description.internal_error: + msg = 'Internal error.'; + break; + case tls.Alert.Description.user_canceled: + msg = 'User canceled.'; + break; + case tls.Alert.Description.no_renegotiation: + msg = 'Renegotiation not supported.'; + break; + default: + msg = 'Unknown error.'; + break; + } + + // close connection on close_notify, not an error + if(alert.description === tls.Alert.Description.close_notify) { + return c.close(); + } + + // call error handler + c.error(c, { + message: msg, + send: false, + // origin is the opposite end + origin: (c.entity === tls.ConnectionEnd.client) ? 'server' : 'client', + alert: alert + }); + + // continue + c.process(); +}; + +/** + * Called when a Handshake record is received. + * + * @param c the connection. + * @param record the record. + */ +tls.handleHandshake = function(c, record) { + // get the handshake type and message length + var b = record.fragment; + var type = b.getByte(); + var length = b.getInt24(); + + // see if the record fragment doesn't yet contain the full message + if(length > b.length()) { + // cache the record, clear its fragment, and reset the buffer read + // pointer before the type and length were read + c.fragmented = record; + record.fragment = forge.util.createBuffer(); + b.read -= 4; + + // continue + return c.process(); + } + + // full message now available, clear cache, reset read pointer to + // before type and length + c.fragmented = null; + b.read -= 4; + + // save the handshake bytes for digestion after handler is found + // (include type and length of handshake msg) + var bytes = b.bytes(length + 4); + + // restore read pointer + b.read += 4; + + // handle expected message + if(type in hsTable[c.entity][c.expect]) { + // initialize server session + if(c.entity === tls.ConnectionEnd.server && !c.open && !c.fail) { + c.handshaking = true; + c.session = { + version: null, + extensions: { + server_name: { + serverNameList: [] + } + }, + cipherSuite: null, + compressionMethod: null, + serverCertificate: null, + clientCertificate: null, + md5: forge.md.md5.create(), + sha1: forge.md.sha1.create() + }; + } + + /* Update handshake messages digest. Finished and CertificateVerify + messages are not digested here. They can't be digested as part of + the verify_data that they contain. These messages are manually + digested in their handlers. HelloRequest messages are simply never + included in the handshake message digest according to spec. */ + if(type !== tls.HandshakeType.hello_request && + type !== tls.HandshakeType.certificate_verify && + type !== tls.HandshakeType.finished) { + c.session.md5.update(bytes); + c.session.sha1.update(bytes); + } + + // handle specific handshake type record + hsTable[c.entity][c.expect][type](c, record, length); + } else { + // unexpected record + tls.handleUnexpected(c, record); + } +}; + +/** + * Called when an ApplicationData record is received. + * + * @param c the connection. + * @param record the record. + */ +tls.handleApplicationData = function(c, record) { + // buffer data, notify that its ready + c.data.putBuffer(record.fragment); + c.dataReady(c); + + // continue + c.process(); +}; + +/** + * Called when a Heartbeat record is received. + * + * @param c the connection. + * @param record the record. + */ +tls.handleHeartbeat = function(c, record) { + // get the heartbeat type and payload + var b = record.fragment; + var type = b.getByte(); + var length = b.getInt16(); + var payload = b.getBytes(length); + + if(type === tls.HeartbeatMessageType.heartbeat_request) { + // discard request during handshake or if length is too large + if(c.handshaking || length > payload.length) { + // continue + return c.process(); + } + // retransmit payload + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.heartbeat, + data: tls.createHeartbeat( + tls.HeartbeatMessageType.heartbeat_response, payload) + })); + tls.flush(c); + } else if(type === tls.HeartbeatMessageType.heartbeat_response) { + // check payload against expected payload, discard heartbeat if no match + if(payload !== c.expectedHeartbeatPayload) { + // continue + return c.process(); + } + + // notify that a valid heartbeat was received + if(c.heartbeatReceived) { + c.heartbeatReceived(c, forge.util.createBuffer(payload)); + } + } + + // continue + c.process(); +}; + +/** + * The transistional state tables for receiving TLS records. It maps the + * current TLS engine state and a received record to a function to handle the + * record and update the state. + * + * For instance, if the current state is SHE, then the TLS engine is expecting + * a ServerHello record. Once a record is received, the handler function is + * looked up using the state SHE and the record's content type. + * + * The resulting function will either be an error handler or a record handler. + * The function will take whatever action is appropriate and update the state + * for the next record. + * + * The states are all based on possible server record types. Note that the + * client will never specifically expect to receive a HelloRequest or an alert + * from the server so there is no state that reflects this. These messages may + * occur at any time. + * + * There are two tables for mapping states because there is a second tier of + * types for handshake messages. Once a record with a content type of handshake + * is received, the handshake record handler will look up the handshake type in + * the secondary map to get its appropriate handler. + * + * Valid message orders are as follows: + * + * =======================FULL HANDSHAKE====================== + * Client Server + * + * ClientHello --------> + * ServerHello + * Certificate* + * ServerKeyExchange* + * CertificateRequest* + * <-------- ServerHelloDone + * Certificate* + * ClientKeyExchange + * CertificateVerify* + * [ChangeCipherSpec] + * Finished --------> + * [ChangeCipherSpec] + * <-------- Finished + * Application Data <-------> Application Data + * + * =====================SESSION RESUMPTION===================== + * Client Server + * + * ClientHello --------> + * ServerHello + * [ChangeCipherSpec] + * <-------- Finished + * [ChangeCipherSpec] + * Finished --------> + * Application Data <-------> Application Data + */ +// client expect states (indicate which records are expected to be received) +var SHE = 0; // rcv server hello +var SCE = 1; // rcv server certificate +var SKE = 2; // rcv server key exchange +var SCR = 3; // rcv certificate request +var SHD = 4; // rcv server hello done +var SCC = 5; // rcv change cipher spec +var SFI = 6; // rcv finished +var SAD = 7; // rcv application data +var SER = 8; // not expecting any messages at this point + +// server expect states +var CHE = 0; // rcv client hello +var CCE = 1; // rcv client certificate +var CKE = 2; // rcv client key exchange +var CCV = 3; // rcv certificate verify +var CCC = 4; // rcv change cipher spec +var CFI = 5; // rcv finished +var CAD = 6; // rcv application data +var CER = 7; // not expecting any messages at this point + +// map client current expect state and content type to function +var __ = tls.handleUnexpected; +var R0 = tls.handleChangeCipherSpec; +var R1 = tls.handleAlert; +var R2 = tls.handleHandshake; +var R3 = tls.handleApplicationData; +var R4 = tls.handleHeartbeat; +var ctTable = []; +ctTable[tls.ConnectionEnd.client] = [ +// CC,AL,HS,AD,HB +/*SHE*/[__,R1,R2,__,R4], +/*SCE*/[__,R1,R2,__,R4], +/*SKE*/[__,R1,R2,__,R4], +/*SCR*/[__,R1,R2,__,R4], +/*SHD*/[__,R1,R2,__,R4], +/*SCC*/[R0,R1,__,__,R4], +/*SFI*/[__,R1,R2,__,R4], +/*SAD*/[__,R1,R2,R3,R4], +/*SER*/[__,R1,R2,__,R4] +]; + +// map server current expect state and content type to function +ctTable[tls.ConnectionEnd.server] = [ +// CC,AL,HS,AD +/*CHE*/[__,R1,R2,__,R4], +/*CCE*/[__,R1,R2,__,R4], +/*CKE*/[__,R1,R2,__,R4], +/*CCV*/[__,R1,R2,__,R4], +/*CCC*/[R0,R1,__,__,R4], +/*CFI*/[__,R1,R2,__,R4], +/*CAD*/[__,R1,R2,R3,R4], +/*CER*/[__,R1,R2,__,R4] +]; + +// map client current expect state and handshake type to function +var H0 = tls.handleHelloRequest; +var H1 = tls.handleServerHello; +var H2 = tls.handleCertificate; +var H3 = tls.handleServerKeyExchange; +var H4 = tls.handleCertificateRequest; +var H5 = tls.handleServerHelloDone; +var H6 = tls.handleFinished; +var hsTable = []; +hsTable[tls.ConnectionEnd.client] = [ +// HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI +/*SHE*/[__,__,H1,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*SCE*/[H0,__,__,__,__,__,__,__,__,__,__,H2,H3,H4,H5,__,__,__,__,__,__], +/*SKE*/[H0,__,__,__,__,__,__,__,__,__,__,__,H3,H4,H5,__,__,__,__,__,__], +/*SCR*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,H4,H5,__,__,__,__,__,__], +/*SHD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,H5,__,__,__,__,__,__], +/*SCC*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*SFI*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6], +/*SAD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*SER*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__] +]; + +// map server current expect state and handshake type to function +// Note: CAD[CH] does not map to FB because renegotiation is prohibited +var H7 = tls.handleClientHello; +var H8 = tls.handleClientKeyExchange; +var H9 = tls.handleCertificateVerify; +hsTable[tls.ConnectionEnd.server] = [ +// 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI +/*CHE*/[__,H7,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*CCE*/[__,__,__,__,__,__,__,__,__,__,__,H2,__,__,__,__,__,__,__,__,__], +/*CKE*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H8,__,__,__,__], +/*CCV*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H9,__,__,__,__,__], +/*CCC*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*CFI*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6], +/*CAD*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*CER*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__] +]; + +/** + * Generates the master_secret and keys using the given security parameters. + * + * The security parameters for a TLS connection state are defined as such: + * + * struct { + * ConnectionEnd entity; + * PRFAlgorithm prf_algorithm; + * BulkCipherAlgorithm bulk_cipher_algorithm; + * CipherType cipher_type; + * uint8 enc_key_length; + * uint8 block_length; + * uint8 fixed_iv_length; + * uint8 record_iv_length; + * MACAlgorithm mac_algorithm; + * uint8 mac_length; + * uint8 mac_key_length; + * CompressionMethod compression_algorithm; + * opaque master_secret[48]; + * opaque client_random[32]; + * opaque server_random[32]; + * } SecurityParameters; + * + * Note that this definition is from TLS 1.2. In TLS 1.0 some of these + * parameters are ignored because, for instance, the PRFAlgorithm is a + * builtin-fixed algorithm combining iterations of MD5 and SHA-1 in TLS 1.0. + * + * The Record Protocol requires an algorithm to generate keys required by the + * current connection state. + * + * The master secret is expanded into a sequence of secure bytes, which is then + * split to a client write MAC key, a server write MAC key, a client write + * encryption key, and a server write encryption key. In TLS 1.0 a client write + * IV and server write IV are also generated. Each of these is generated from + * the byte sequence in that order. Unused values are empty. In TLS 1.2, some + * AEAD ciphers may additionally require a client write IV and a server write + * IV (see Section 6.2.3.3). + * + * When keys, MAC keys, and IVs are generated, the master secret is used as an + * entropy source. + * + * To generate the key material, compute: + * + * master_secret = PRF(pre_master_secret, "master secret", + * ClientHello.random + ServerHello.random) + * + * key_block = PRF(SecurityParameters.master_secret, + * "key expansion", + * SecurityParameters.server_random + + * SecurityParameters.client_random); + * + * until enough output has been generated. Then, the key_block is + * partitioned as follows: + * + * client_write_MAC_key[SecurityParameters.mac_key_length] + * server_write_MAC_key[SecurityParameters.mac_key_length] + * client_write_key[SecurityParameters.enc_key_length] + * server_write_key[SecurityParameters.enc_key_length] + * client_write_IV[SecurityParameters.fixed_iv_length] + * server_write_IV[SecurityParameters.fixed_iv_length] + * + * In TLS 1.2, the client_write_IV and server_write_IV are only generated for + * implicit nonce techniques as described in Section 3.2.1 of [AEAD]. This + * implementation uses TLS 1.0 so IVs are generated. + * + * Implementation note: The currently defined cipher suite which requires the + * most material is AES_256_CBC_SHA256. It requires 2 x 32 byte keys and 2 x 32 + * byte MAC keys, for a total 128 bytes of key material. In TLS 1.0 it also + * requires 2 x 16 byte IVs, so it actually takes 160 bytes of key material. + * + * @param c the connection. + * @param sp the security parameters to use. + * + * @return the security keys. + */ +tls.generateKeys = function(c, sp) { + // TLS_RSA_WITH_AES_128_CBC_SHA (required to be compliant with TLS 1.2) & + // TLS_RSA_WITH_AES_256_CBC_SHA are the only cipher suites implemented + // at present + + // TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA is required to be compliant with + // TLS 1.0 but we don't care right now because AES is better and we have + // an implementation for it + + // TODO: TLS 1.2 implementation + /* + // determine the PRF + var prf; + switch(sp.prf_algorithm) { + case tls.PRFAlgorithm.tls_prf_sha256: + prf = prf_sha256; + break; + default: + // should never happen + throw new Error('Invalid PRF'); + } + */ + + // TLS 1.0/1.1 implementation + var prf = prf_TLS1; + + // concatenate server and client random + var random = sp.client_random + sp.server_random; + + // only create master secret if session is new + if(!c.session.resuming) { + // create master secret, clean up pre-master secret + sp.master_secret = prf( + sp.pre_master_secret, 'master secret', random, 48).bytes(); + sp.pre_master_secret = null; + } + + // generate the amount of key material needed + random = sp.server_random + sp.client_random; + var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length; + + // include IV for TLS/1.0 + var tls10 = (c.version.major === tls.Versions.TLS_1_0.major && + c.version.minor === tls.Versions.TLS_1_0.minor); + if(tls10) { + length += 2 * sp.fixed_iv_length; + } + var km = prf(sp.master_secret, 'key expansion', random, length); + + // split the key material into the MAC and encryption keys + var rval = { + client_write_MAC_key: km.getBytes(sp.mac_key_length), + server_write_MAC_key: km.getBytes(sp.mac_key_length), + client_write_key: km.getBytes(sp.enc_key_length), + server_write_key: km.getBytes(sp.enc_key_length) + }; + + // include TLS 1.0 IVs + if(tls10) { + rval.client_write_IV = km.getBytes(sp.fixed_iv_length); + rval.server_write_IV = km.getBytes(sp.fixed_iv_length); + } + + return rval; +}; + +/** + * Creates a new initialized TLS connection state. A connection state has + * a read mode and a write mode. + * + * compression state: + * The current state of the compression algorithm. + * + * cipher state: + * The current state of the encryption algorithm. This will consist of the + * scheduled key for that connection. For stream ciphers, this will also + * contain whatever state information is necessary to allow the stream to + * continue to encrypt or decrypt data. + * + * MAC key: + * The MAC key for the connection. + * + * sequence number: + * Each connection state contains a sequence number, which is maintained + * separately for read and write states. The sequence number MUST be set to + * zero whenever a connection state is made the active state. Sequence + * numbers are of type uint64 and may not exceed 2^64-1. Sequence numbers do + * not wrap. If a TLS implementation would need to wrap a sequence number, + * it must renegotiate instead. A sequence number is incremented after each + * record: specifically, the first record transmitted under a particular + * connection state MUST use sequence number 0. + * + * @param c the connection. + * + * @return the new initialized TLS connection state. + */ +tls.createConnectionState = function(c) { + var client = (c.entity === tls.ConnectionEnd.client); + + var createMode = function() { + var mode = { + // two 32-bit numbers, first is most significant + sequenceNumber: [0, 0], + macKey: null, + macLength: 0, + macFunction: null, + cipherState: null, + cipherFunction: function(record) {return true;}, + compressionState: null, + compressFunction: function(record) {return true;}, + updateSequenceNumber: function() { + if(mode.sequenceNumber[1] === 0xFFFFFFFF) { + mode.sequenceNumber[1] = 0; + ++mode.sequenceNumber[0]; + } else { + ++mode.sequenceNumber[1]; + } + } + }; + return mode; + }; + var state = { + read: createMode(), + write: createMode() + }; + + // update function in read mode will decrypt then decompress a record + state.read.update = function(c, record) { + if(!state.read.cipherFunction(record, state.read)) { + c.error(c, { + message: 'Could not decrypt record or bad MAC.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + // doesn't matter if decryption failed or MAC was + // invalid, return the same error so as not to reveal + // which one occurred + description: tls.Alert.Description.bad_record_mac + } + }); + } else if(!state.read.compressFunction(c, record, state.read)) { + c.error(c, { + message: 'Could not decompress record.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.decompression_failure + } + }); + } + return !c.fail; + }; + + // update function in write mode will compress then encrypt a record + state.write.update = function(c, record) { + if(!state.write.compressFunction(c, record, state.write)) { + // error, but do not send alert since it would require + // compression as well + c.error(c, { + message: 'Could not compress record.', + send: false, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } else if(!state.write.cipherFunction(record, state.write)) { + // error, but do not send alert since it would require + // encryption as well + c.error(c, { + message: 'Could not encrypt record.', + send: false, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } + return !c.fail; + }; + + // handle security parameters + if(c.session) { + var sp = c.session.sp; + c.session.cipherSuite.initSecurityParameters(sp); + + // generate keys + sp.keys = tls.generateKeys(c, sp); + state.read.macKey = client ? + sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key; + state.write.macKey = client ? + sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key; + + // cipher suite setup + c.session.cipherSuite.initConnectionState(state, c, sp); + + // compression setup + switch(sp.compression_algorithm) { + case tls.CompressionMethod.none: + break; + case tls.CompressionMethod.deflate: + state.read.compressFunction = inflate; + state.write.compressFunction = deflate; + break; + default: + throw new Error('Unsupported compression algorithm.'); + } + } + + return state; +}; + +/** + * Creates a Random structure. + * + * struct { + * uint32 gmt_unix_time; + * opaque random_bytes[28]; + * } Random; + * + * gmt_unix_time: + * The current time and date in standard UNIX 32-bit format (seconds since + * the midnight starting Jan 1, 1970, UTC, ignoring leap seconds) according + * to the sender's internal clock. Clocks are not required to be set + * correctly by the basic TLS protocol; higher-level or application + * protocols may define additional requirements. Note that, for historical + * reasons, the data element is named using GMT, the predecessor of the + * current worldwide time base, UTC. + * random_bytes: + * 28 bytes generated by a secure random number generator. + * + * @return the Random structure as a byte array. + */ +tls.createRandom = function() { + // get UTC milliseconds + var d = new Date(); + var utc = +d + d.getTimezoneOffset() * 60000; + var rval = forge.util.createBuffer(); + rval.putInt32(utc); + rval.putBytes(forge.random.getBytes(28)); + return rval; +}; + +/** + * Creates a TLS record with the given type and data. + * + * @param c the connection. + * @param options: + * type: the record type. + * data: the plain text data in a byte buffer. + * + * @return the created record. + */ +tls.createRecord = function(c, options) { + if(!options.data) { + return null; + } + var record = { + type: options.type, + version: { + major: c.version.major, + minor: c.version.minor + }, + length: options.data.length(), + fragment: options.data + }; + return record; +}; + +/** + * Creates a TLS alert record. + * + * @param c the connection. + * @param alert: + * level: the TLS alert level. + * description: the TLS alert description. + * + * @return the created alert record. + */ +tls.createAlert = function(c, alert) { + var b = forge.util.createBuffer(); + b.putByte(alert.level); + b.putByte(alert.description); + return tls.createRecord(c, { + type: tls.ContentType.alert, + data: b + }); +}; + +/* The structure of a TLS handshake message. + * + * struct { + * HandshakeType msg_type; // handshake type + * uint24 length; // bytes in message + * select(HandshakeType) { + * case hello_request: HelloRequest; + * case client_hello: ClientHello; + * case server_hello: ServerHello; + * case certificate: Certificate; + * case server_key_exchange: ServerKeyExchange; + * case certificate_request: CertificateRequest; + * case server_hello_done: ServerHelloDone; + * case certificate_verify: CertificateVerify; + * case client_key_exchange: ClientKeyExchange; + * case finished: Finished; + * } body; + * } Handshake; + */ + +/** + * Creates a ClientHello message. + * + * opaque SessionID<0..32>; + * enum { null(0), deflate(1), (255) } CompressionMethod; + * uint8 CipherSuite[2]; + * + * struct { + * ProtocolVersion client_version; + * Random random; + * SessionID session_id; + * CipherSuite cipher_suites<2..2^16-2>; + * CompressionMethod compression_methods<1..2^8-1>; + * select(extensions_present) { + * case false: + * struct {}; + * case true: + * Extension extensions<0..2^16-1>; + * }; + * } ClientHello; + * + * The extension format for extended client hellos and server hellos is: + * + * struct { + * ExtensionType extension_type; + * opaque extension_data<0..2^16-1>; + * } Extension; + * + * Here: + * + * - "extension_type" identifies the particular extension type. + * - "extension_data" contains information specific to the particular + * extension type. + * + * The extension types defined in this document are: + * + * enum { + * server_name(0), max_fragment_length(1), + * client_certificate_url(2), trusted_ca_keys(3), + * truncated_hmac(4), status_request(5), (65535) + * } ExtensionType; + * + * @param c the connection. + * + * @return the ClientHello byte buffer. + */ +tls.createClientHello = function(c) { + // save hello version + c.session.clientHelloVersion = { + major: c.version.major, + minor: c.version.minor + }; + + // create supported cipher suites + var cipherSuites = forge.util.createBuffer(); + for(var i = 0; i < c.cipherSuites.length; ++i) { + var cs = c.cipherSuites[i]; + cipherSuites.putByte(cs.id[0]); + cipherSuites.putByte(cs.id[1]); + } + var cSuites = cipherSuites.length(); + + // create supported compression methods, null always supported, but + // also support deflate if connection has inflate and deflate methods + var compressionMethods = forge.util.createBuffer(); + compressionMethods.putByte(tls.CompressionMethod.none); + // FIXME: deflate support disabled until issues with raw deflate data + // without zlib headers are resolved + /* + if(c.inflate !== null && c.deflate !== null) { + compressionMethods.putByte(tls.CompressionMethod.deflate); + } + */ + var cMethods = compressionMethods.length(); + + // create TLS SNI (server name indication) extension if virtual host + // has been specified, see RFC 3546 + var extensions = forge.util.createBuffer(); + if(c.virtualHost) { + // create extension struct + var ext = forge.util.createBuffer(); + ext.putByte(0x00); // type server_name (ExtensionType is 2 bytes) + ext.putByte(0x00); + + /* In order to provide the server name, clients MAY include an + * extension of type "server_name" in the (extended) client hello. + * The "extension_data" field of this extension SHALL contain + * "ServerNameList" where: + * + * struct { + * NameType name_type; + * select(name_type) { + * case host_name: HostName; + * } name; + * } ServerName; + * + * enum { + * host_name(0), (255) + * } NameType; + * + * opaque HostName<1..2^16-1>; + * + * struct { + * ServerName server_name_list<1..2^16-1> + * } ServerNameList; + */ + var serverName = forge.util.createBuffer(); + serverName.putByte(0x00); // type host_name + writeVector(serverName, 2, forge.util.createBuffer(c.virtualHost)); + + // ServerNameList is in extension_data + var snList = forge.util.createBuffer(); + writeVector(snList, 2, serverName); + writeVector(ext, 2, snList); + extensions.putBuffer(ext); + } + var extLength = extensions.length(); + if(extLength > 0) { + // add extension vector length + extLength += 2; + } + + // determine length of the handshake message + // cipher suites and compression methods size will need to be + // updated if more get added to the list + var sessionId = c.session.id; + var length = + sessionId.length + 1 + // session ID vector + 2 + // version (major + minor) + 4 + 28 + // random time and random bytes + 2 + cSuites + // cipher suites vector + 1 + cMethods + // compression methods vector + extLength; // extensions vector + + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.client_hello); + rval.putInt24(length); // handshake length + rval.putByte(c.version.major); // major version + rval.putByte(c.version.minor); // minor version + rval.putBytes(c.session.sp.client_random); // random time + bytes + writeVector(rval, 1, forge.util.createBuffer(sessionId)); + writeVector(rval, 2, cipherSuites); + writeVector(rval, 1, compressionMethods); + if(extLength > 0) { + writeVector(rval, 2, extensions); + } + return rval; +}; + +/** + * Creates a ServerHello message. + * + * @param c the connection. + * + * @return the ServerHello byte buffer. + */ +tls.createServerHello = function(c) { + // determine length of the handshake message + var sessionId = c.session.id; + var length = + sessionId.length + 1 + // session ID vector + 2 + // version (major + minor) + 4 + 28 + // random time and random bytes + 2 + // chosen cipher suite + 1; // chosen compression method + + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.server_hello); + rval.putInt24(length); // handshake length + rval.putByte(c.version.major); // major version + rval.putByte(c.version.minor); // minor version + rval.putBytes(c.session.sp.server_random); // random time + bytes + writeVector(rval, 1, forge.util.createBuffer(sessionId)); + rval.putByte(c.session.cipherSuite.id[0]); + rval.putByte(c.session.cipherSuite.id[1]); + rval.putByte(c.session.compressionMethod); + return rval; +}; + +/** + * Creates a Certificate message. + * + * When this message will be sent: + * This is the first message the client can send after receiving a server + * hello done message and the first message the server can send after + * sending a ServerHello. This client message is only sent if the server + * requests a certificate. If no suitable certificate is available, the + * client should send a certificate message containing no certificates. If + * client authentication is required by the server for the handshake to + * continue, it may respond with a fatal handshake failure alert. + * + * opaque ASN.1Cert<1..2^24-1>; + * + * struct { + * ASN.1Cert certificate_list<0..2^24-1>; + * } Certificate; + * + * @param c the connection. + * + * @return the Certificate byte buffer. + */ +tls.createCertificate = function(c) { + // TODO: check certificate request to ensure types are supported + + // get a certificate (a certificate as a PEM string) + var client = (c.entity === tls.ConnectionEnd.client); + var cert = null; + if(c.getCertificate) { + var hint; + if(client) { + hint = c.session.certificateRequest; + } else { + hint = c.session.extensions.server_name.serverNameList; + } + cert = c.getCertificate(c, hint); + } + + // buffer to hold certificate list + var certList = forge.util.createBuffer(); + if(cert !== null) { + try { + // normalize cert to a chain of certificates + if(!forge.util.isArray(cert)) { + cert = [cert]; + } + var asn1 = null; + for(var i = 0; i < cert.length; ++i) { + var msg = forge.pem.decode(cert[i])[0]; + if(msg.type !== 'CERTIFICATE' && + msg.type !== 'X509 CERTIFICATE' && + msg.type !== 'TRUSTED CERTIFICATE') { + var error = new Error('Could not convert certificate from PEM; PEM ' + + 'header type is not "CERTIFICATE", "X509 CERTIFICATE", or ' + + '"TRUSTED CERTIFICATE".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert certificate from PEM; PEM is encrypted.'); + } + + var der = forge.util.createBuffer(msg.body); + if(asn1 === null) { + asn1 = forge.asn1.fromDer(der.bytes(), false); + } + + // certificate entry is itself a vector with 3 length bytes + var certBuffer = forge.util.createBuffer(); + writeVector(certBuffer, 3, der); + + // add cert vector to cert list vector + certList.putBuffer(certBuffer); + } + + // save certificate + cert = forge.pki.certificateFromAsn1(asn1); + if(client) { + c.session.clientCertificate = cert; + } else { + c.session.serverCertificate = cert; + } + } catch(ex) { + return c.error(c, { + message: 'Could not send certificate list.', + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.bad_certificate + } + }); + } + } + + // determine length of the handshake message + var length = 3 + certList.length(); // cert list vector + + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.certificate); + rval.putInt24(length); + writeVector(rval, 3, certList); + return rval; +}; + +/** + * Creates a ClientKeyExchange message. + * + * When this message will be sent: + * This message is always sent by the client. It will immediately follow the + * client certificate message, if it is sent. Otherwise it will be the first + * message sent by the client after it receives the server hello done + * message. + * + * Meaning of this message: + * With this message, the premaster secret is set, either though direct + * transmission of the RSA-encrypted secret, or by the transmission of + * Diffie-Hellman parameters which will allow each side to agree upon the + * same premaster secret. When the key exchange method is DH_RSA or DH_DSS, + * client certification has been requested, and the client was able to + * respond with a certificate which contained a Diffie-Hellman public key + * whose parameters (group and generator) matched those specified by the + * server in its certificate, this message will not contain any data. + * + * Meaning of this message: + * If RSA is being used for key agreement and authentication, the client + * generates a 48-byte premaster secret, encrypts it using the public key + * from the server's certificate or the temporary RSA key provided in a + * server key exchange message, and sends the result in an encrypted + * premaster secret message. This structure is a variant of the client + * key exchange message, not a message in itself. + * + * struct { + * select(KeyExchangeAlgorithm) { + * case rsa: EncryptedPreMasterSecret; + * case diffie_hellman: ClientDiffieHellmanPublic; + * } exchange_keys; + * } ClientKeyExchange; + * + * struct { + * ProtocolVersion client_version; + * opaque random[46]; + * } PreMasterSecret; + * + * struct { + * public-key-encrypted PreMasterSecret pre_master_secret; + * } EncryptedPreMasterSecret; + * + * A public-key-encrypted element is encoded as a vector <0..2^16-1>. + * + * @param c the connection. + * + * @return the ClientKeyExchange byte buffer. + */ +tls.createClientKeyExchange = function(c) { + // create buffer to encrypt + var b = forge.util.createBuffer(); + + // add highest client-supported protocol to help server avoid version + // rollback attacks + b.putByte(c.session.clientHelloVersion.major); + b.putByte(c.session.clientHelloVersion.minor); + + // generate and add 46 random bytes + b.putBytes(forge.random.getBytes(46)); + + // save pre-master secret + var sp = c.session.sp; + sp.pre_master_secret = b.getBytes(); + + // RSA-encrypt the pre-master secret + var key = c.session.serverCertificate.publicKey; + b = key.encrypt(sp.pre_master_secret); + + /* Note: The encrypted pre-master secret will be stored in a + public-key-encrypted opaque vector that has the length prefixed using + 2 bytes, so include those 2 bytes in the handshake message length. This + is done as a minor optimization instead of calling writeVector(). */ + + // determine length of the handshake message + var length = b.length + 2; + + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.client_key_exchange); + rval.putInt24(length); + // add vector length bytes + rval.putInt16(b.length); + rval.putBytes(b); + return rval; +}; + +/** + * Creates a ServerKeyExchange message. + * + * @param c the connection. + * + * @return the ServerKeyExchange byte buffer. + */ +tls.createServerKeyExchange = function(c) { + // this implementation only supports RSA, no Diffie-Hellman support, + // so this record is empty + + // determine length of the handshake message + var length = 0; + + // build record fragment + var rval = forge.util.createBuffer(); + if(length > 0) { + rval.putByte(tls.HandshakeType.server_key_exchange); + rval.putInt24(length); + } + return rval; +}; + +/** + * Gets the signed data used to verify a client-side certificate. See + * tls.createCertificateVerify() for details. + * + * @param c the connection. + * @param callback the callback to call once the signed data is ready. + */ +tls.getClientSignature = function(c, callback) { + // generate data to RSA encrypt + var b = forge.util.createBuffer(); + b.putBuffer(c.session.md5.digest()); + b.putBuffer(c.session.sha1.digest()); + b = b.getBytes(); + + // create default signing function as necessary + c.getSignature = c.getSignature || function(c, b, callback) { + // do rsa encryption, call callback + var privateKey = null; + if(c.getPrivateKey) { + try { + privateKey = c.getPrivateKey(c, c.session.clientCertificate); + privateKey = forge.pki.privateKeyFromPem(privateKey); + } catch(ex) { + c.error(c, { + message: 'Could not get private key.', + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } + } + if(privateKey === null) { + c.error(c, { + message: 'No private key set.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } else { + b = privateKey.sign(b, null); + } + callback(c, b); + }; + + // get client signature + c.getSignature(c, b, callback); +}; + +/** + * Creates a CertificateVerify message. + * + * Meaning of this message: + * This structure conveys the client's Diffie-Hellman public value + * (Yc) if it was not already included in the client's certificate. + * The encoding used for Yc is determined by the enumerated + * PublicValueEncoding. This structure is a variant of the client + * key exchange message, not a message in itself. + * + * When this message will be sent: + * This message is used to provide explicit verification of a client + * certificate. This message is only sent following a client + * certificate that has signing capability (i.e. all certificates + * except those containing fixed Diffie-Hellman parameters). When + * sent, it will immediately follow the client key exchange message. + * + * struct { + * Signature signature; + * } CertificateVerify; + * + * CertificateVerify.signature.md5_hash + * MD5(handshake_messages); + * + * Certificate.signature.sha_hash + * SHA(handshake_messages); + * + * Here handshake_messages refers to all handshake messages sent or + * received starting at client hello up to but not including this + * message, including the type and length fields of the handshake + * messages. + * + * select(SignatureAlgorithm) { + * case anonymous: struct { }; + * case rsa: + * digitally-signed struct { + * opaque md5_hash[16]; + * opaque sha_hash[20]; + * }; + * case dsa: + * digitally-signed struct { + * opaque sha_hash[20]; + * }; + * } Signature; + * + * In digital signing, one-way hash functions are used as input for a + * signing algorithm. A digitally-signed element is encoded as an opaque + * vector <0..2^16-1>, where the length is specified by the signing + * algorithm and key. + * + * In RSA signing, a 36-byte structure of two hashes (one SHA and one + * MD5) is signed (encrypted with the private key). It is encoded with + * PKCS #1 block type 0 or type 1 as described in [PKCS1]. + * + * In DSS, the 20 bytes of the SHA hash are run directly through the + * Digital Signing Algorithm with no additional hashing. + * + * @param c the connection. + * @param signature the signature to include in the message. + * + * @return the CertificateVerify byte buffer. + */ +tls.createCertificateVerify = function(c, signature) { + /* Note: The signature will be stored in a "digitally-signed" opaque + vector that has the length prefixed using 2 bytes, so include those + 2 bytes in the handshake message length. This is done as a minor + optimization instead of calling writeVector(). */ + + // determine length of the handshake message + var length = signature.length + 2; + + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.certificate_verify); + rval.putInt24(length); + // add vector length bytes + rval.putInt16(signature.length); + rval.putBytes(signature); + return rval; +}; + +/** + * Creates a CertificateRequest message. + * + * @param c the connection. + * + * @return the CertificateRequest byte buffer. + */ +tls.createCertificateRequest = function(c) { + // TODO: support other certificate types + var certTypes = forge.util.createBuffer(); + + // common RSA certificate type + certTypes.putByte(0x01); + + // add distinguished names from CA store + var cAs = forge.util.createBuffer(); + for(var key in c.caStore.certs) { + var cert = c.caStore.certs[key]; + var dn = forge.pki.distinguishedNameToAsn1(cert.subject); + var byteBuffer = forge.asn1.toDer(dn); + cAs.putInt16(byteBuffer.length()); + cAs.putBuffer(byteBuffer); + } + + // TODO: TLS 1.2+ has a different format + + // determine length of the handshake message + var length = + 1 + certTypes.length() + + 2 + cAs.length(); + + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.certificate_request); + rval.putInt24(length); + writeVector(rval, 1, certTypes); + writeVector(rval, 2, cAs); + return rval; +}; + +/** + * Creates a ServerHelloDone message. + * + * @param c the connection. + * + * @return the ServerHelloDone byte buffer. + */ +tls.createServerHelloDone = function(c) { + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.server_hello_done); + rval.putInt24(0); + return rval; +}; + +/** + * Creates a ChangeCipherSpec message. + * + * The change cipher spec protocol exists to signal transitions in + * ciphering strategies. The protocol consists of a single message, + * which is encrypted and compressed under the current (not the pending) + * connection state. The message consists of a single byte of value 1. + * + * struct { + * enum { change_cipher_spec(1), (255) } type; + * } ChangeCipherSpec; + * + * @return the ChangeCipherSpec byte buffer. + */ +tls.createChangeCipherSpec = function() { + var rval = forge.util.createBuffer(); + rval.putByte(0x01); + return rval; +}; + +/** + * Creates a Finished message. + * + * struct { + * opaque verify_data[12]; + * } Finished; + * + * verify_data + * PRF(master_secret, finished_label, MD5(handshake_messages) + + * SHA-1(handshake_messages)) [0..11]; + * + * finished_label + * For Finished messages sent by the client, the string "client + * finished". For Finished messages sent by the server, the + * string "server finished". + * + * handshake_messages + * All of the data from all handshake messages up to but not + * including this message. This is only data visible at the + * handshake layer and does not include record layer headers. + * This is the concatenation of all the Handshake structures as + * defined in 7.4 exchanged thus far. + * + * @param c the connection. + * + * @return the Finished byte buffer. + */ +tls.createFinished = function(c) { + // generate verify_data + var b = forge.util.createBuffer(); + b.putBuffer(c.session.md5.digest()); + b.putBuffer(c.session.sha1.digest()); + + // TODO: determine prf function and verify length for TLS 1.2 + var client = (c.entity === tls.ConnectionEnd.client); + var sp = c.session.sp; + var vdl = 12; + var prf = prf_TLS1; + var label = client ? 'client finished' : 'server finished'; + b = prf(sp.master_secret, label, b.getBytes(), vdl); + + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.finished); + rval.putInt24(b.length()); + rval.putBuffer(b); + return rval; +}; + +/** + * Creates a HeartbeatMessage (See RFC 6520). + * + * struct { + * HeartbeatMessageType type; + * uint16 payload_length; + * opaque payload[HeartbeatMessage.payload_length]; + * opaque padding[padding_length]; + * } HeartbeatMessage; + * + * The total length of a HeartbeatMessage MUST NOT exceed 2^14 or + * max_fragment_length when negotiated as defined in [RFC6066]. + * + * type: The message type, either heartbeat_request or heartbeat_response. + * + * payload_length: The length of the payload. + * + * payload: The payload consists of arbitrary content. + * + * padding: The padding is random content that MUST be ignored by the + * receiver. The length of a HeartbeatMessage is TLSPlaintext.length + * for TLS and DTLSPlaintext.length for DTLS. Furthermore, the + * length of the type field is 1 byte, and the length of the + * payload_length is 2. Therefore, the padding_length is + * TLSPlaintext.length - payload_length - 3 for TLS and + * DTLSPlaintext.length - payload_length - 3 for DTLS. The + * padding_length MUST be at least 16. + * + * The sender of a HeartbeatMessage MUST use a random padding of at + * least 16 bytes. The padding of a received HeartbeatMessage message + * MUST be ignored. + * + * If the payload_length of a received HeartbeatMessage is too large, + * the received HeartbeatMessage MUST be discarded silently. + * + * @param c the connection. + * @param type the tls.HeartbeatMessageType. + * @param payload the heartbeat data to send as the payload. + * @param [payloadLength] the payload length to use, defaults to the + * actual payload length. + * + * @return the HeartbeatRequest byte buffer. + */ +tls.createHeartbeat = function(type, payload, payloadLength) { + if(typeof payloadLength === 'undefined') { + payloadLength = payload.length; + } + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(type); // heartbeat message type + rval.putInt16(payloadLength); // payload length + rval.putBytes(payload); // payload + // padding + var plaintextLength = rval.length(); + var paddingLength = Math.max(16, plaintextLength - payloadLength - 3); + rval.putBytes(forge.random.getBytes(paddingLength)); + return rval; +}; + +/** + * Fragments, compresses, encrypts, and queues a record for delivery. + * + * @param c the connection. + * @param record the record to queue. + */ +tls.queue = function(c, record) { + // error during record creation + if(!record) { + return; + } + + if(record.fragment.length() === 0) { + if(record.type === tls.ContentType.handshake || + record.type === tls.ContentType.alert || + record.type === tls.ContentType.change_cipher_spec) { + // Empty handshake, alert of change cipher spec messages are not allowed per the TLS specification and should not be sent. + return; + } + } + + // if the record is a handshake record, update handshake hashes + if(record.type === tls.ContentType.handshake) { + var bytes = record.fragment.bytes(); + c.session.md5.update(bytes); + c.session.sha1.update(bytes); + bytes = null; + } + + // handle record fragmentation + var records; + if(record.fragment.length() <= tls.MaxFragment) { + records = [record]; + } else { + // fragment data as long as it is too long + records = []; + var data = record.fragment.bytes(); + while(data.length > tls.MaxFragment) { + records.push(tls.createRecord(c, { + type: record.type, + data: forge.util.createBuffer(data.slice(0, tls.MaxFragment)) + })); + data = data.slice(tls.MaxFragment); + } + // add last record + if(data.length > 0) { + records.push(tls.createRecord(c, { + type: record.type, + data: forge.util.createBuffer(data) + })); + } + } + + // compress and encrypt all fragmented records + for(var i = 0; i < records.length && !c.fail; ++i) { + // update the record using current write state + var rec = records[i]; + var s = c.state.current.write; + if(s.update(c, rec)) { + // store record + c.records.push(rec); + } + } +}; + +/** + * Flushes all queued records to the output buffer and calls the + * tlsDataReady() handler on the given connection. + * + * @param c the connection. + * + * @return true on success, false on failure. + */ +tls.flush = function(c) { + for(var i = 0; i < c.records.length; ++i) { + var record = c.records[i]; + + // add record header and fragment + c.tlsData.putByte(record.type); + c.tlsData.putByte(record.version.major); + c.tlsData.putByte(record.version.minor); + c.tlsData.putInt16(record.fragment.length()); + c.tlsData.putBuffer(c.records[i].fragment); + } + c.records = []; + return c.tlsDataReady(c); +}; + +/** + * Maps a pki.certificateError to a tls.Alert.Description. + * + * @param error the error to map. + * + * @return the alert description. + */ +var _certErrorToAlertDesc = function(error) { + switch(error) { + case true: + return true; + case forge.pki.certificateError.bad_certificate: + return tls.Alert.Description.bad_certificate; + case forge.pki.certificateError.unsupported_certificate: + return tls.Alert.Description.unsupported_certificate; + case forge.pki.certificateError.certificate_revoked: + return tls.Alert.Description.certificate_revoked; + case forge.pki.certificateError.certificate_expired: + return tls.Alert.Description.certificate_expired; + case forge.pki.certificateError.certificate_unknown: + return tls.Alert.Description.certificate_unknown; + case forge.pki.certificateError.unknown_ca: + return tls.Alert.Description.unknown_ca; + default: + return tls.Alert.Description.bad_certificate; + } +}; + +/** + * Maps a tls.Alert.Description to a pki.certificateError. + * + * @param desc the alert description. + * + * @return the certificate error. + */ +var _alertDescToCertError = function(desc) { + switch(desc) { + case true: + return true; + case tls.Alert.Description.bad_certificate: + return forge.pki.certificateError.bad_certificate; + case tls.Alert.Description.unsupported_certificate: + return forge.pki.certificateError.unsupported_certificate; + case tls.Alert.Description.certificate_revoked: + return forge.pki.certificateError.certificate_revoked; + case tls.Alert.Description.certificate_expired: + return forge.pki.certificateError.certificate_expired; + case tls.Alert.Description.certificate_unknown: + return forge.pki.certificateError.certificate_unknown; + case tls.Alert.Description.unknown_ca: + return forge.pki.certificateError.unknown_ca; + default: + return forge.pki.certificateError.bad_certificate; + } +}; + +/** + * Verifies a certificate chain against the given connection's + * Certificate Authority store. + * + * @param c the TLS connection. + * @param chain the certificate chain to verify, with the root or highest + * authority at the end. + * + * @return true if successful, false if not. + */ +tls.verifyCertificateChain = function(c, chain) { + try { + // Make a copy of c.verifyOptions so that we can modify options.verify + // without modifying c.verifyOptions. + var options = {}; + for (var key in c.verifyOptions) { + options[key] = c.verifyOptions[key]; + } + + options.verify = function(vfd, depth, chain) { + // convert pki.certificateError to tls alert description + var desc = _certErrorToAlertDesc(vfd); + + // call application callback + var ret = c.verify(c, vfd, depth, chain); + if(ret !== true) { + if(typeof ret === 'object' && !forge.util.isArray(ret)) { + // throw custom error + var error = new Error('The application rejected the certificate.'); + error.send = true; + error.alert = { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.bad_certificate + }; + if(ret.message) { + error.message = ret.message; + } + if(ret.alert) { + error.alert.description = ret.alert; + } + throw error; + } + + // convert tls alert description to pki.certificateError + if(ret !== vfd) { + ret = _alertDescToCertError(ret); + } + } + + return ret; + }; + + // verify chain + forge.pki.verifyCertificateChain(c.caStore, chain, options); + } catch(ex) { + // build tls error if not already customized + var err = ex; + if(typeof err !== 'object' || forge.util.isArray(err)) { + err = { + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: _certErrorToAlertDesc(ex) + } + }; + } + if(!('send' in err)) { + err.send = true; + } + if(!('alert' in err)) { + err.alert = { + level: tls.Alert.Level.fatal, + description: _certErrorToAlertDesc(err.error) + }; + } + + // send error + c.error(c, err); + } + + return !c.fail; +}; + +/** + * Creates a new TLS session cache. + * + * @param cache optional map of session ID to cached session. + * @param capacity the maximum size for the cache (default: 100). + * + * @return the new TLS session cache. + */ +tls.createSessionCache = function(cache, capacity) { + var rval = null; + + // assume input is already a session cache object + if(cache && cache.getSession && cache.setSession && cache.order) { + rval = cache; + } else { + // create cache + rval = {}; + rval.cache = cache || {}; + rval.capacity = Math.max(capacity || 100, 1); + rval.order = []; + + // store order for sessions, delete session overflow + for(var key in cache) { + if(rval.order.length <= capacity) { + rval.order.push(key); + } else { + delete cache[key]; + } + } + + // get a session from a session ID (or get any session) + rval.getSession = function(sessionId) { + var session = null; + var key = null; + + // if session ID provided, use it + if(sessionId) { + key = forge.util.bytesToHex(sessionId); + } else if(rval.order.length > 0) { + // get first session from cache + key = rval.order[0]; + } + + if(key !== null && key in rval.cache) { + // get cached session and remove from cache + session = rval.cache[key]; + delete rval.cache[key]; + for(var i in rval.order) { + if(rval.order[i] === key) { + rval.order.splice(i, 1); + break; + } + } + } + + return session; + }; + + // set a session in the cache + rval.setSession = function(sessionId, session) { + // remove session from cache if at capacity + if(rval.order.length === rval.capacity) { + var key = rval.order.shift(); + delete rval.cache[key]; + } + // add session to cache + var key = forge.util.bytesToHex(sessionId); + rval.order.push(key); + rval.cache[key] = session; + }; + } + + return rval; +}; + +/** + * Creates a new TLS connection. + * + * See public createConnection() docs for more details. + * + * @param options the options for this connection. + * + * @return the new TLS connection. + */ +tls.createConnection = function(options) { + var caStore = null; + if(options.caStore) { + // if CA store is an array, convert it to a CA store object + if(forge.util.isArray(options.caStore)) { + caStore = forge.pki.createCaStore(options.caStore); + } else { + caStore = options.caStore; + } + } else { + // create empty CA store + caStore = forge.pki.createCaStore(); + } + + // setup default cipher suites + var cipherSuites = options.cipherSuites || null; + if(cipherSuites === null) { + cipherSuites = []; + for(var key in tls.CipherSuites) { + cipherSuites.push(tls.CipherSuites[key]); + } + } + + // set default entity + var entity = (options.server || false) ? + tls.ConnectionEnd.server : tls.ConnectionEnd.client; + + // create session cache if requested + var sessionCache = options.sessionCache ? + tls.createSessionCache(options.sessionCache) : null; + + // create TLS connection + var c = { + version: {major: tls.Version.major, minor: tls.Version.minor}, + entity: entity, + sessionId: options.sessionId, + caStore: caStore, + sessionCache: sessionCache, + cipherSuites: cipherSuites, + connected: options.connected, + virtualHost: options.virtualHost || null, + verifyClient: options.verifyClient || false, + verify: options.verify || function(cn, vfd, dpth, cts) {return vfd;}, + verifyOptions: options.verifyOptions || {}, + getCertificate: options.getCertificate || null, + getPrivateKey: options.getPrivateKey || null, + getSignature: options.getSignature || null, + input: forge.util.createBuffer(), + tlsData: forge.util.createBuffer(), + data: forge.util.createBuffer(), + tlsDataReady: options.tlsDataReady, + dataReady: options.dataReady, + heartbeatReceived: options.heartbeatReceived, + closed: options.closed, + error: function(c, ex) { + // set origin if not set + ex.origin = ex.origin || + ((c.entity === tls.ConnectionEnd.client) ? 'client' : 'server'); + + // send TLS alert + if(ex.send) { + tls.queue(c, tls.createAlert(c, ex.alert)); + tls.flush(c); + } + + // error is fatal by default + var fatal = (ex.fatal !== false); + if(fatal) { + // set fail flag + c.fail = true; + } + + // call error handler first + options.error(c, ex); + + if(fatal) { + // fatal error, close connection, do not clear fail + c.close(false); + } + }, + deflate: options.deflate || null, + inflate: options.inflate || null + }; + + /** + * Resets a closed TLS connection for reuse. Called in c.close(). + * + * @param clearFail true to clear the fail flag (default: true). + */ + c.reset = function(clearFail) { + c.version = {major: tls.Version.major, minor: tls.Version.minor}; + c.record = null; + c.session = null; + c.peerCertificate = null; + c.state = { + pending: null, + current: null + }; + c.expect = (c.entity === tls.ConnectionEnd.client) ? SHE : CHE; + c.fragmented = null; + c.records = []; + c.open = false; + c.handshakes = 0; + c.handshaking = false; + c.isConnected = false; + c.fail = !(clearFail || typeof(clearFail) === 'undefined'); + c.input.clear(); + c.tlsData.clear(); + c.data.clear(); + c.state.current = tls.createConnectionState(c); + }; + + // do initial reset of connection + c.reset(); + + /** + * Updates the current TLS engine state based on the given record. + * + * @param c the TLS connection. + * @param record the TLS record to act on. + */ + var _update = function(c, record) { + // get record handler (align type in table by subtracting lowest) + var aligned = record.type - tls.ContentType.change_cipher_spec; + var handlers = ctTable[c.entity][c.expect]; + if(aligned in handlers) { + handlers[aligned](c, record); + } else { + // unexpected record + tls.handleUnexpected(c, record); + } + }; + + /** + * Reads the record header and initializes the next record on the given + * connection. + * + * @param c the TLS connection with the next record. + * + * @return 0 if the input data could be processed, otherwise the + * number of bytes required for data to be processed. + */ + var _readRecordHeader = function(c) { + var rval = 0; + + // get input buffer and its length + var b = c.input; + var len = b.length(); + + // need at least 5 bytes to initialize a record + if(len < 5) { + rval = 5 - len; + } else { + // enough bytes for header + // initialize record + c.record = { + type: b.getByte(), + version: { + major: b.getByte(), + minor: b.getByte() + }, + length: b.getInt16(), + fragment: forge.util.createBuffer(), + ready: false + }; + + // check record version + var compatibleVersion = (c.record.version.major === c.version.major); + if(compatibleVersion && c.session && c.session.version) { + // session version already set, require same minor version + compatibleVersion = (c.record.version.minor === c.version.minor); + } + if(!compatibleVersion) { + c.error(c, { + message: 'Incompatible TLS version.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.protocol_version + } + }); + } + } + + return rval; + }; + + /** + * Reads the next record's contents and appends its message to any + * previously fragmented message. + * + * @param c the TLS connection with the next record. + * + * @return 0 if the input data could be processed, otherwise the + * number of bytes required for data to be processed. + */ + var _readRecord = function(c) { + var rval = 0; + + // ensure there is enough input data to get the entire record + var b = c.input; + var len = b.length(); + if(len < c.record.length) { + // not enough data yet, return how much is required + rval = c.record.length - len; + } else { + // there is enough data to parse the pending record + // fill record fragment and compact input buffer + c.record.fragment.putBytes(b.getBytes(c.record.length)); + b.compact(); + + // update record using current read state + var s = c.state.current.read; + if(s.update(c, c.record)) { + // see if there is a previously fragmented message that the + // new record's message fragment should be appended to + if(c.fragmented !== null) { + // if the record type matches a previously fragmented + // record, append the record fragment to it + if(c.fragmented.type === c.record.type) { + // concatenate record fragments + c.fragmented.fragment.putBuffer(c.record.fragment); + c.record = c.fragmented; + } else { + // error, invalid fragmented record + c.error(c, { + message: 'Invalid fragmented record.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: + tls.Alert.Description.unexpected_message + } + }); + } + } + + // record is now ready + c.record.ready = true; + } + } + + return rval; + }; + + /** + * Performs a handshake using the TLS Handshake Protocol, as a client. + * + * This method should only be called if the connection is in client mode. + * + * @param sessionId the session ID to use, null to start a new one. + */ + c.handshake = function(sessionId) { + // error to call this in non-client mode + if(c.entity !== tls.ConnectionEnd.client) { + // not fatal error + c.error(c, { + message: 'Cannot initiate handshake as a server.', + fatal: false + }); + } else if(c.handshaking) { + // handshake is already in progress, fail but not fatal error + c.error(c, { + message: 'Handshake already in progress.', + fatal: false + }); + } else { + // clear fail flag on reuse + if(c.fail && !c.open && c.handshakes === 0) { + c.fail = false; + } + + // now handshaking + c.handshaking = true; + + // default to blank (new session) + sessionId = sessionId || ''; + + // if a session ID was specified, try to find it in the cache + var session = null; + if(sessionId.length > 0) { + if(c.sessionCache) { + session = c.sessionCache.getSession(sessionId); + } + + // matching session not found in cache, clear session ID + if(session === null) { + sessionId = ''; + } + } + + // no session given, grab a session from the cache, if available + if(sessionId.length === 0 && c.sessionCache) { + session = c.sessionCache.getSession(); + if(session !== null) { + sessionId = session.id; + } + } + + // set up session + c.session = { + id: sessionId, + version: null, + cipherSuite: null, + compressionMethod: null, + serverCertificate: null, + certificateRequest: null, + clientCertificate: null, + sp: {}, + md5: forge.md.md5.create(), + sha1: forge.md.sha1.create() + }; + + // use existing session information + if(session) { + // only update version on connection, session version not yet set + c.version = session.version; + c.session.sp = session.sp; + } + + // generate new client random + c.session.sp.client_random = tls.createRandom().getBytes(); + + // connection now open + c.open = true; + + // send hello + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createClientHello(c) + })); + tls.flush(c); + } + }; + + /** + * Called when TLS protocol data has been received from somewhere and should + * be processed by the TLS engine. + * + * @param data the TLS protocol data, as a string, to process. + * + * @return 0 if the data could be processed, otherwise the number of bytes + * required for data to be processed. + */ + c.process = function(data) { + var rval = 0; + + // buffer input data + if(data) { + c.input.putBytes(data); + } + + // process next record if no failure, process will be called after + // each record is handled (since handling can be asynchronous) + if(!c.fail) { + // reset record if ready and now empty + if(c.record !== null && + c.record.ready && c.record.fragment.isEmpty()) { + c.record = null; + } + + // if there is no pending record, try to read record header + if(c.record === null) { + rval = _readRecordHeader(c); + } + + // read the next record (if record not yet ready) + if(!c.fail && c.record !== null && !c.record.ready) { + rval = _readRecord(c); + } + + // record ready to be handled, update engine state + if(!c.fail && c.record !== null && c.record.ready) { + _update(c, c.record); + } + } + + return rval; + }; + + /** + * Requests that application data be packaged into a TLS record. The + * tlsDataReady handler will be called when the TLS record(s) have been + * prepared. + * + * @param data the application data, as a raw 'binary' encoded string, to + * be sent; to send utf-16/utf-8 string data, use the return value + * of util.encodeUtf8(str). + * + * @return true on success, false on failure. + */ + c.prepare = function(data) { + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.application_data, + data: forge.util.createBuffer(data) + })); + return tls.flush(c); + }; + + /** + * Requests that a heartbeat request be packaged into a TLS record for + * transmission. The tlsDataReady handler will be called when TLS record(s) + * have been prepared. + * + * When a heartbeat response has been received, the heartbeatReceived + * handler will be called with the matching payload. This handler can + * be used to clear a retransmission timer, etc. + * + * @param payload the heartbeat data to send as the payload in the message. + * @param [payloadLength] the payload length to use, defaults to the + * actual payload length. + * + * @return true on success, false on failure. + */ + c.prepareHeartbeatRequest = function(payload, payloadLength) { + if(payload instanceof forge.util.ByteBuffer) { + payload = payload.bytes(); + } + if(typeof payloadLength === 'undefined') { + payloadLength = payload.length; + } + c.expectedHeartbeatPayload = payload; + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.heartbeat, + data: tls.createHeartbeat( + tls.HeartbeatMessageType.heartbeat_request, payload, payloadLength) + })); + return tls.flush(c); + }; + + /** + * Closes the connection (sends a close_notify alert). + * + * @param clearFail true to clear the fail flag (default: true). + */ + c.close = function(clearFail) { + // save session if connection didn't fail + if(!c.fail && c.sessionCache && c.session) { + // only need to preserve session ID, version, and security params + var session = { + id: c.session.id, + version: c.session.version, + sp: c.session.sp + }; + session.sp.keys = null; + c.sessionCache.setSession(session.id, session); + } + + if(c.open) { + // connection no longer open, clear input + c.open = false; + c.input.clear(); + + // if connected or handshaking, send an alert + if(c.isConnected || c.handshaking) { + c.isConnected = c.handshaking = false; + + // send close_notify alert + tls.queue(c, tls.createAlert(c, { + level: tls.Alert.Level.warning, + description: tls.Alert.Description.close_notify + })); + tls.flush(c); + } + + // call handler + c.closed(c); + } + + // reset TLS connection, do not clear fail flag + c.reset(clearFail); + }; + + return c; +}; + +/* TLS API */ +module.exports = forge.tls = forge.tls || {}; + +// expose non-functions +for(var key in tls) { + if(typeof tls[key] !== 'function') { + forge.tls[key] = tls[key]; + } +} + +// expose prf_tls1 for testing +forge.tls.prf_tls1 = prf_TLS1; + +// expose sha1 hmac method +forge.tls.hmac_sha1 = hmac_sha1; + +// expose session cache creation +forge.tls.createSessionCache = tls.createSessionCache; + +/** + * Creates a new TLS connection. This does not make any assumptions about the + * transport layer that TLS is working on top of, ie: it does not assume there + * is a TCP/IP connection or establish one. A TLS connection is totally + * abstracted away from the layer is runs on top of, it merely establishes a + * secure channel between a client" and a "server". + * + * A TLS connection contains 4 connection states: pending read and write, and + * current read and write. + * + * At initialization, the current read and write states will be null. Only once + * the security parameters have been set and the keys have been generated can + * the pending states be converted into current states. Current states will be + * updated for each record processed. + * + * A custom certificate verify callback may be provided to check information + * like the common name on the server's certificate. It will be called for + * every certificate in the chain. It has the following signature: + * + * variable func(c, certs, index, preVerify) + * Where: + * c The TLS connection + * verified Set to true if certificate was verified, otherwise the alert + * tls.Alert.Description for why the certificate failed. + * depth The current index in the chain, where 0 is the server's cert. + * certs The certificate chain, *NOTE* if the server was anonymous then + * the chain will be empty. + * + * The function returns true on success and on failure either the appropriate + * tls.Alert.Description or an object with 'alert' set to the appropriate + * tls.Alert.Description and 'message' set to a custom error message. If true + * is not returned then the connection will abort using, in order of + * availability, first the returned alert description, second the preVerify + * alert description, and lastly the default 'bad_certificate'. + * + * There are three callbacks that can be used to make use of client-side + * certificates where each takes the TLS connection as the first parameter: + * + * getCertificate(conn, hint) + * The second parameter is a hint as to which certificate should be + * returned. If the connection entity is a client, then the hint will be + * the CertificateRequest message from the server that is part of the + * TLS protocol. If the connection entity is a server, then it will be + * the servername list provided via an SNI extension the ClientHello, if + * one was provided (empty array if not). The hint can be examined to + * determine which certificate to use (advanced). Most implementations + * will just return a certificate. The return value must be a + * PEM-formatted certificate or an array of PEM-formatted certificates + * that constitute a certificate chain, with the first in the array/chain + * being the client's certificate. + * getPrivateKey(conn, certificate) + * The second parameter is an forge.pki X.509 certificate object that + * is associated with the requested private key. The return value must + * be a PEM-formatted private key. + * getSignature(conn, bytes, callback) + * This callback can be used instead of getPrivateKey if the private key + * is not directly accessible in javascript or should not be. For + * instance, a secure external web service could provide the signature + * in exchange for appropriate credentials. The second parameter is a + * string of bytes to be signed that are part of the TLS protocol. These + * bytes are used to verify that the private key for the previously + * provided client-side certificate is accessible to the client. The + * callback is a function that takes 2 parameters, the TLS connection + * and the RSA encrypted (signed) bytes as a string. This callback must + * be called once the signature is ready. + * + * @param options the options for this connection: + * server: true if the connection is server-side, false for client. + * sessionId: a session ID to reuse, null for a new connection. + * caStore: an array of certificates to trust. + * sessionCache: a session cache to use. + * cipherSuites: an optional array of cipher suites to use, + * see tls.CipherSuites. + * connected: function(conn) called when the first handshake completes. + * virtualHost: the virtual server name to use in a TLS SNI extension. + * verifyClient: true to require a client certificate in server mode, + * 'optional' to request one, false not to (default: false). + * verify: a handler used to custom verify certificates in the chain. + * verifyOptions: an object with options for the certificate chain validation. + * See documentation of pki.verifyCertificateChain for possible options. + * verifyOptions.verify is ignored. If you wish to specify a verify handler + * use the verify key. + * getCertificate: an optional callback used to get a certificate or + * a chain of certificates (as an array). + * getPrivateKey: an optional callback used to get a private key. + * getSignature: an optional callback used to get a signature. + * tlsDataReady: function(conn) called when TLS protocol data has been + * prepared and is ready to be used (typically sent over a socket + * connection to its destination), read from conn.tlsData buffer. + * dataReady: function(conn) called when application data has + * been parsed from a TLS record and should be consumed by the + * application, read from conn.data buffer. + * closed: function(conn) called when the connection has been closed. + * error: function(conn, error) called when there was an error. + * deflate: function(inBytes) if provided, will deflate TLS records using + * the deflate algorithm if the server supports it. + * inflate: function(inBytes) if provided, will inflate TLS records using + * the deflate algorithm if the server supports it. + * + * @return the new TLS connection. + */ +forge.tls.createConnection = tls.createConnection; diff --git a/node_modules/node-forge/lib/tlssocket.js b/node_modules/node-forge/lib/tlssocket.js new file mode 100644 index 0000000..d09b650 --- /dev/null +++ b/node_modules/node-forge/lib/tlssocket.js @@ -0,0 +1,249 @@ +/** + * Socket wrapping functions for TLS. + * + * @author Dave Longley + * + * Copyright (c) 2009-2012 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./tls'); + +/** + * Wraps a forge.net socket with a TLS layer. + * + * @param options: + * sessionId: a session ID to reuse, null for a new connection if no session + * cache is provided or it is empty. + * caStore: an array of certificates to trust. + * sessionCache: a session cache to use. + * cipherSuites: an optional array of cipher suites to use, see + * tls.CipherSuites. + * socket: the socket to wrap. + * virtualHost: the virtual server name to use in a TLS SNI extension. + * verify: a handler used to custom verify certificates in the chain. + * getCertificate: an optional callback used to get a certificate. + * getPrivateKey: an optional callback used to get a private key. + * getSignature: an optional callback used to get a signature. + * deflate: function(inBytes) if provided, will deflate TLS records using + * the deflate algorithm if the server supports it. + * inflate: function(inBytes) if provided, will inflate TLS records using + * the deflate algorithm if the server supports it. + * + * @return the TLS-wrapped socket. + */ +forge.tls.wrapSocket = function(options) { + // get raw socket + var socket = options.socket; + + // create TLS socket + var tlsSocket = { + id: socket.id, + // set handlers + connected: socket.connected || function(e) {}, + closed: socket.closed || function(e) {}, + data: socket.data || function(e) {}, + error: socket.error || function(e) {} + }; + + // create TLS connection + var c = forge.tls.createConnection({ + server: false, + sessionId: options.sessionId || null, + caStore: options.caStore || [], + sessionCache: options.sessionCache || null, + cipherSuites: options.cipherSuites || null, + virtualHost: options.virtualHost, + verify: options.verify, + getCertificate: options.getCertificate, + getPrivateKey: options.getPrivateKey, + getSignature: options.getSignature, + deflate: options.deflate, + inflate: options.inflate, + connected: function(c) { + // first handshake complete, call handler + if(c.handshakes === 1) { + tlsSocket.connected({ + id: socket.id, + type: 'connect', + bytesAvailable: c.data.length() + }); + } + }, + tlsDataReady: function(c) { + // send TLS data over socket + return socket.send(c.tlsData.getBytes()); + }, + dataReady: function(c) { + // indicate application data is ready + tlsSocket.data({ + id: socket.id, + type: 'socketData', + bytesAvailable: c.data.length() + }); + }, + closed: function(c) { + // close socket + socket.close(); + }, + error: function(c, e) { + // send error, close socket + tlsSocket.error({ + id: socket.id, + type: 'tlsError', + message: e.message, + bytesAvailable: 0, + error: e + }); + socket.close(); + } + }); + + // handle doing handshake after connecting + socket.connected = function(e) { + c.handshake(options.sessionId); + }; + + // handle closing TLS connection + socket.closed = function(e) { + if(c.open && c.handshaking) { + // error + tlsSocket.error({ + id: socket.id, + type: 'ioError', + message: 'Connection closed during handshake.', + bytesAvailable: 0 + }); + } + c.close(); + + // call socket handler + tlsSocket.closed({ + id: socket.id, + type: 'close', + bytesAvailable: 0 + }); + }; + + // handle error on socket + socket.error = function(e) { + // error + tlsSocket.error({ + id: socket.id, + type: e.type, + message: e.message, + bytesAvailable: 0 + }); + c.close(); + }; + + // handle receiving raw TLS data from socket + var _requiredBytes = 0; + socket.data = function(e) { + // drop data if connection not open + if(!c.open) { + socket.receive(e.bytesAvailable); + } else { + // only receive if there are enough bytes available to + // process a record + if(e.bytesAvailable >= _requiredBytes) { + var count = Math.max(e.bytesAvailable, _requiredBytes); + var data = socket.receive(count); + if(data !== null) { + _requiredBytes = c.process(data); + } + } + } + }; + + /** + * Destroys this socket. + */ + tlsSocket.destroy = function() { + socket.destroy(); + }; + + /** + * Sets this socket's TLS session cache. This should be called before + * the socket is connected or after it is closed. + * + * The cache is an object mapping session IDs to internal opaque state. + * An application might need to change the cache used by a particular + * tlsSocket between connections if it accesses multiple TLS hosts. + * + * @param cache the session cache to use. + */ + tlsSocket.setSessionCache = function(cache) { + c.sessionCache = tls.createSessionCache(cache); + }; + + /** + * Connects this socket. + * + * @param options: + * host: the host to connect to. + * port: the port to connect to. + * policyPort: the policy port to use (if non-default), 0 to + * use the flash default. + * policyUrl: the policy file URL to use (instead of port). + */ + tlsSocket.connect = function(options) { + socket.connect(options); + }; + + /** + * Closes this socket. + */ + tlsSocket.close = function() { + c.close(); + }; + + /** + * Determines if the socket is connected or not. + * + * @return true if connected, false if not. + */ + tlsSocket.isConnected = function() { + return c.isConnected && socket.isConnected(); + }; + + /** + * Writes bytes to this socket. + * + * @param bytes the bytes (as a string) to write. + * + * @return true on success, false on failure. + */ + tlsSocket.send = function(bytes) { + return c.prepare(bytes); + }; + + /** + * Reads bytes from this socket (non-blocking). Fewer than the number of + * bytes requested may be read if enough bytes are not available. + * + * This method should be called from the data handler if there are enough + * bytes available. To see how many bytes are available, check the + * 'bytesAvailable' property on the event in the data handler or call the + * bytesAvailable() function on the socket. If the browser is msie, then the + * bytesAvailable() function should be used to avoid race conditions. + * Otherwise, using the property on the data handler's event may be quicker. + * + * @param count the maximum number of bytes to read. + * + * @return the bytes read (as a string) or null on error. + */ + tlsSocket.receive = function(count) { + return c.data.getBytes(count); + }; + + /** + * Gets the number of bytes available for receiving on the socket. + * + * @return the number of bytes available for receiving. + */ + tlsSocket.bytesAvailable = function() { + return c.data.length(); + }; + + return tlsSocket; +}; diff --git a/node_modules/node-forge/lib/util.js b/node_modules/node-forge/lib/util.js new file mode 100644 index 0000000..db2341a --- /dev/null +++ b/node_modules/node-forge/lib/util.js @@ -0,0 +1,2652 @@ +/** + * Utility functions for web applications. + * + * @author Dave Longley + * + * Copyright (c) 2010-2018 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +var baseN = require('./baseN'); + +/* Utilities API */ +var util = module.exports = forge.util = forge.util || {}; + +// define setImmediate and nextTick +(function() { + // use native nextTick (unless we're in webpack) + // webpack (or better node-libs-browser polyfill) sets process.browser. + // this way we can detect webpack properly + if(typeof process !== 'undefined' && process.nextTick && !process.browser) { + util.nextTick = process.nextTick; + if(typeof setImmediate === 'function') { + util.setImmediate = setImmediate; + } else { + // polyfill setImmediate with nextTick, older versions of node + // (those w/o setImmediate) won't totally starve IO + util.setImmediate = util.nextTick; + } + return; + } + + // polyfill nextTick with native setImmediate + if(typeof setImmediate === 'function') { + util.setImmediate = function() { return setImmediate.apply(undefined, arguments); }; + util.nextTick = function(callback) { + return setImmediate(callback); + }; + return; + } + + /* Note: A polyfill upgrade pattern is used here to allow combining + polyfills. For example, MutationObserver is fast, but blocks UI updates, + so it needs to allow UI updates periodically, so it falls back on + postMessage or setTimeout. */ + + // polyfill with setTimeout + util.setImmediate = function(callback) { + setTimeout(callback, 0); + }; + + // upgrade polyfill to use postMessage + if(typeof window !== 'undefined' && + typeof window.postMessage === 'function') { + var msg = 'forge.setImmediate'; + var callbacks = []; + util.setImmediate = function(callback) { + callbacks.push(callback); + // only send message when one hasn't been sent in + // the current turn of the event loop + if(callbacks.length === 1) { + window.postMessage(msg, '*'); + } + }; + function handler(event) { + if(event.source === window && event.data === msg) { + event.stopPropagation(); + var copy = callbacks.slice(); + callbacks.length = 0; + copy.forEach(function(callback) { + callback(); + }); + } + } + window.addEventListener('message', handler, true); + } + + // upgrade polyfill to use MutationObserver + if(typeof MutationObserver !== 'undefined') { + // polyfill with MutationObserver + var now = Date.now(); + var attr = true; + var div = document.createElement('div'); + var callbacks = []; + new MutationObserver(function() { + var copy = callbacks.slice(); + callbacks.length = 0; + copy.forEach(function(callback) { + callback(); + }); + }).observe(div, {attributes: true}); + var oldSetImmediate = util.setImmediate; + util.setImmediate = function(callback) { + if(Date.now() - now > 15) { + now = Date.now(); + oldSetImmediate(callback); + } else { + callbacks.push(callback); + // only trigger observer when it hasn't been triggered in + // the current turn of the event loop + if(callbacks.length === 1) { + div.setAttribute('a', attr = !attr); + } + } + }; + } + + util.nextTick = util.setImmediate; +})(); + +// check if running under Node.js +util.isNodejs = + typeof process !== 'undefined' && process.versions && process.versions.node; + + +// 'self' will also work in Web Workers (instance of WorkerGlobalScope) while +// it will point to `window` in the main thread. +// To remain compatible with older browsers, we fall back to 'window' if 'self' +// is not available. +util.globalScope = (function() { + if(util.isNodejs) { + return global; + } + + return typeof self === 'undefined' ? window : self; +})(); + +// define isArray +util.isArray = Array.isArray || function(x) { + return Object.prototype.toString.call(x) === '[object Array]'; +}; + +// define isArrayBuffer +util.isArrayBuffer = function(x) { + return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer; +}; + +// define isArrayBufferView +util.isArrayBufferView = function(x) { + return x && util.isArrayBuffer(x.buffer) && x.byteLength !== undefined; +}; + +/** + * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for + * algorithms where bit manipulation, JavaScript limitations, and/or algorithm + * design only allow for byte operations of a limited size. + * + * @param n number of bits. + * + * Throw Error if n invalid. + */ +function _checkBitsParam(n) { + if(!(n === 8 || n === 16 || n === 24 || n === 32)) { + throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n); + } +} + +// TODO: set ByteBuffer to best available backing +util.ByteBuffer = ByteStringBuffer; + +/** Buffer w/BinaryString backing */ + +/** + * Constructor for a binary string backed byte buffer. + * + * @param [b] the bytes to wrap (either encoded as string, one byte per + * character, or as an ArrayBuffer or Typed Array). + */ +function ByteStringBuffer(b) { + // TODO: update to match DataBuffer API + + // the data in this buffer + this.data = ''; + // the pointer for reading from this buffer + this.read = 0; + + if(typeof b === 'string') { + this.data = b; + } else if(util.isArrayBuffer(b) || util.isArrayBufferView(b)) { + if(typeof Buffer !== 'undefined' && b instanceof Buffer) { + this.data = b.toString('binary'); + } else { + // convert native buffer to forge buffer + // FIXME: support native buffers internally instead + var arr = new Uint8Array(b); + try { + this.data = String.fromCharCode.apply(null, arr); + } catch(e) { + for(var i = 0; i < arr.length; ++i) { + this.putByte(arr[i]); + } + } + } + } else if(b instanceof ByteStringBuffer || + (typeof b === 'object' && typeof b.data === 'string' && + typeof b.read === 'number')) { + // copy existing buffer + this.data = b.data; + this.read = b.read; + } + + // used for v8 optimization + this._constructedStringLength = 0; +} +util.ByteStringBuffer = ByteStringBuffer; + +/* Note: This is an optimization for V8-based browsers. When V8 concatenates + a string, the strings are only joined logically using a "cons string" or + "constructed/concatenated string". These containers keep references to one + another and can result in very large memory usage. For example, if a 2MB + string is constructed by concatenating 4 bytes together at a time, the + memory usage will be ~44MB; so ~22x increase. The strings are only joined + together when an operation requiring their joining takes place, such as + substr(). This function is called when adding data to this buffer to ensure + these types of strings are periodically joined to reduce the memory + footprint. */ +var _MAX_CONSTRUCTED_STRING_LENGTH = 4096; +util.ByteStringBuffer.prototype._optimizeConstructedString = function(x) { + this._constructedStringLength += x; + if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) { + // this substr() should cause the constructed string to join + this.data.substr(0, 1); + this._constructedStringLength = 0; + } +}; + +/** + * Gets the number of bytes in this buffer. + * + * @return the number of bytes in this buffer. + */ +util.ByteStringBuffer.prototype.length = function() { + return this.data.length - this.read; +}; + +/** + * Gets whether or not this buffer is empty. + * + * @return true if this buffer is empty, false if not. + */ +util.ByteStringBuffer.prototype.isEmpty = function() { + return this.length() <= 0; +}; + +/** + * Puts a byte in this buffer. + * + * @param b the byte to put. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putByte = function(b) { + return this.putBytes(String.fromCharCode(b)); +}; + +/** + * Puts a byte in this buffer N times. + * + * @param b the byte to put. + * @param n the number of bytes of value b to put. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.fillWithByte = function(b, n) { + b = String.fromCharCode(b); + var d = this.data; + while(n > 0) { + if(n & 1) { + d += b; + } + n >>>= 1; + if(n > 0) { + b += b; + } + } + this.data = d; + this._optimizeConstructedString(n); + return this; +}; + +/** + * Puts bytes in this buffer. + * + * @param bytes the bytes (as a binary encoded string) to put. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putBytes = function(bytes) { + this.data += bytes; + this._optimizeConstructedString(bytes.length); + return this; +}; + +/** + * Puts a UTF-16 encoded string into this buffer. + * + * @param str the string to put. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putString = function(str) { + return this.putBytes(util.encodeUtf8(str)); +}; + +/** + * Puts a 16-bit integer in this buffer in big-endian order. + * + * @param i the 16-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt16 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i & 0xFF)); +}; + +/** + * Puts a 24-bit integer in this buffer in big-endian order. + * + * @param i the 24-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt24 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 16 & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i & 0xFF)); +}; + +/** + * Puts a 32-bit integer in this buffer in big-endian order. + * + * @param i the 32-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt32 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 24 & 0xFF) + + String.fromCharCode(i >> 16 & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i & 0xFF)); +}; + +/** + * Puts a 16-bit integer in this buffer in little-endian order. + * + * @param i the 16-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt16Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF)); +}; + +/** + * Puts a 24-bit integer in this buffer in little-endian order. + * + * @param i the 24-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt24Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i >> 16 & 0xFF)); +}; + +/** + * Puts a 32-bit integer in this buffer in little-endian order. + * + * @param i the 32-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt32Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i >> 16 & 0xFF) + + String.fromCharCode(i >> 24 & 0xFF)); +}; + +/** + * Puts an n-bit integer in this buffer in big-endian order. + * + * @param i the n-bit integer. + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt = function(i, n) { + _checkBitsParam(n); + var bytes = ''; + do { + n -= 8; + bytes += String.fromCharCode((i >> n) & 0xFF); + } while(n > 0); + return this.putBytes(bytes); +}; + +/** + * Puts a signed n-bit integer in this buffer in big-endian order. Two's + * complement representation is used. + * + * @param i the n-bit integer. + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putSignedInt = function(i, n) { + // putInt checks n + if(i < 0) { + i += 2 << (n - 1); + } + return this.putInt(i, n); +}; + +/** + * Puts the given buffer into this buffer. + * + * @param buffer the buffer to put into this one. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putBuffer = function(buffer) { + return this.putBytes(buffer.getBytes()); +}; + +/** + * Gets a byte from this buffer and advances the read pointer by 1. + * + * @return the byte. + */ +util.ByteStringBuffer.prototype.getByte = function() { + return this.data.charCodeAt(this.read++); +}; + +/** + * Gets a uint16 from this buffer in big-endian order and advances the read + * pointer by 2. + * + * @return the uint16. + */ +util.ByteStringBuffer.prototype.getInt16 = function() { + var rval = ( + this.data.charCodeAt(this.read) << 8 ^ + this.data.charCodeAt(this.read + 1)); + this.read += 2; + return rval; +}; + +/** + * Gets a uint24 from this buffer in big-endian order and advances the read + * pointer by 3. + * + * @return the uint24. + */ +util.ByteStringBuffer.prototype.getInt24 = function() { + var rval = ( + this.data.charCodeAt(this.read) << 16 ^ + this.data.charCodeAt(this.read + 1) << 8 ^ + this.data.charCodeAt(this.read + 2)); + this.read += 3; + return rval; +}; + +/** + * Gets a uint32 from this buffer in big-endian order and advances the read + * pointer by 4. + * + * @return the word. + */ +util.ByteStringBuffer.prototype.getInt32 = function() { + var rval = ( + this.data.charCodeAt(this.read) << 24 ^ + this.data.charCodeAt(this.read + 1) << 16 ^ + this.data.charCodeAt(this.read + 2) << 8 ^ + this.data.charCodeAt(this.read + 3)); + this.read += 4; + return rval; +}; + +/** + * Gets a uint16 from this buffer in little-endian order and advances the read + * pointer by 2. + * + * @return the uint16. + */ +util.ByteStringBuffer.prototype.getInt16Le = function() { + var rval = ( + this.data.charCodeAt(this.read) ^ + this.data.charCodeAt(this.read + 1) << 8); + this.read += 2; + return rval; +}; + +/** + * Gets a uint24 from this buffer in little-endian order and advances the read + * pointer by 3. + * + * @return the uint24. + */ +util.ByteStringBuffer.prototype.getInt24Le = function() { + var rval = ( + this.data.charCodeAt(this.read) ^ + this.data.charCodeAt(this.read + 1) << 8 ^ + this.data.charCodeAt(this.read + 2) << 16); + this.read += 3; + return rval; +}; + +/** + * Gets a uint32 from this buffer in little-endian order and advances the read + * pointer by 4. + * + * @return the word. + */ +util.ByteStringBuffer.prototype.getInt32Le = function() { + var rval = ( + this.data.charCodeAt(this.read) ^ + this.data.charCodeAt(this.read + 1) << 8 ^ + this.data.charCodeAt(this.read + 2) << 16 ^ + this.data.charCodeAt(this.read + 3) << 24); + this.read += 4; + return rval; +}; + +/** + * Gets an n-bit integer from this buffer in big-endian order and advances the + * read pointer by ceil(n/8). + * + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return the integer. + */ +util.ByteStringBuffer.prototype.getInt = function(n) { + _checkBitsParam(n); + var rval = 0; + do { + // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. + rval = (rval << 8) + this.data.charCodeAt(this.read++); + n -= 8; + } while(n > 0); + return rval; +}; + +/** + * Gets a signed n-bit integer from this buffer in big-endian order, using + * two's complement, and advances the read pointer by n/8. + * + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return the integer. + */ +util.ByteStringBuffer.prototype.getSignedInt = function(n) { + // getInt checks n + var x = this.getInt(n); + var max = 2 << (n - 2); + if(x >= max) { + x -= max << 1; + } + return x; +}; + +/** + * Reads bytes out as a binary encoded string and clears them from the + * buffer. Note that the resulting string is binary encoded (in node.js this + * encoding is referred to as `binary`, it is *not* `utf8`). + * + * @param count the number of bytes to read, undefined or null for all. + * + * @return a binary encoded string of bytes. + */ +util.ByteStringBuffer.prototype.getBytes = function(count) { + var rval; + if(count) { + // read count bytes + count = Math.min(this.length(), count); + rval = this.data.slice(this.read, this.read + count); + this.read += count; + } else if(count === 0) { + rval = ''; + } else { + // read all bytes, optimize to only copy when needed + rval = (this.read === 0) ? this.data : this.data.slice(this.read); + this.clear(); + } + return rval; +}; + +/** + * Gets a binary encoded string of the bytes from this buffer without + * modifying the read pointer. + * + * @param count the number of bytes to get, omit to get all. + * + * @return a string full of binary encoded characters. + */ +util.ByteStringBuffer.prototype.bytes = function(count) { + return (typeof(count) === 'undefined' ? + this.data.slice(this.read) : + this.data.slice(this.read, this.read + count)); +}; + +/** + * Gets a byte at the given index without modifying the read pointer. + * + * @param i the byte index. + * + * @return the byte. + */ +util.ByteStringBuffer.prototype.at = function(i) { + return this.data.charCodeAt(this.read + i); +}; + +/** + * Puts a byte at the given index without modifying the read pointer. + * + * @param i the byte index. + * @param b the byte to put. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.setAt = function(i, b) { + this.data = this.data.substr(0, this.read + i) + + String.fromCharCode(b) + + this.data.substr(this.read + i + 1); + return this; +}; + +/** + * Gets the last byte without modifying the read pointer. + * + * @return the last byte. + */ +util.ByteStringBuffer.prototype.last = function() { + return this.data.charCodeAt(this.data.length - 1); +}; + +/** + * Creates a copy of this buffer. + * + * @return the copy. + */ +util.ByteStringBuffer.prototype.copy = function() { + var c = util.createBuffer(this.data); + c.read = this.read; + return c; +}; + +/** + * Compacts this buffer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.compact = function() { + if(this.read > 0) { + this.data = this.data.slice(this.read); + this.read = 0; + } + return this; +}; + +/** + * Clears this buffer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.clear = function() { + this.data = ''; + this.read = 0; + return this; +}; + +/** + * Shortens this buffer by trimming bytes off of the end of this buffer. + * + * @param count the number of bytes to trim off. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.truncate = function(count) { + var len = Math.max(0, this.length() - count); + this.data = this.data.substr(this.read, len); + this.read = 0; + return this; +}; + +/** + * Converts this buffer to a hexadecimal string. + * + * @return a hexadecimal string. + */ +util.ByteStringBuffer.prototype.toHex = function() { + var rval = ''; + for(var i = this.read; i < this.data.length; ++i) { + var b = this.data.charCodeAt(i); + if(b < 16) { + rval += '0'; + } + rval += b.toString(16); + } + return rval; +}; + +/** + * Converts this buffer to a UTF-16 string (standard JavaScript string). + * + * @return a UTF-16 string. + */ +util.ByteStringBuffer.prototype.toString = function() { + return util.decodeUtf8(this.bytes()); +}; + +/** End Buffer w/BinaryString backing */ + +/** Buffer w/UInt8Array backing */ + +/** + * FIXME: Experimental. Do not use yet. + * + * Constructor for an ArrayBuffer-backed byte buffer. + * + * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a + * TypedArray. + * + * If a string is given, its encoding should be provided as an option, + * otherwise it will default to 'binary'. A 'binary' string is encoded such + * that each character is one byte in length and size. + * + * If an ArrayBuffer, DataView, or TypedArray is given, it will be used + * *directly* without any copying. Note that, if a write to the buffer requires + * more space, the buffer will allocate a new backing ArrayBuffer to + * accommodate. The starting read and write offsets for the buffer may be + * given as options. + * + * @param [b] the initial bytes for this buffer. + * @param options the options to use: + * [readOffset] the starting read offset to use (default: 0). + * [writeOffset] the starting write offset to use (default: the + * length of the first parameter). + * [growSize] the minimum amount, in bytes, to grow the buffer by to + * accommodate writes (default: 1024). + * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the + * first parameter, if it is a string (default: 'binary'). + */ +function DataBuffer(b, options) { + // default options + options = options || {}; + + // pointers for read from/write to buffer + this.read = options.readOffset || 0; + this.growSize = options.growSize || 1024; + + var isArrayBuffer = util.isArrayBuffer(b); + var isArrayBufferView = util.isArrayBufferView(b); + if(isArrayBuffer || isArrayBufferView) { + // use ArrayBuffer directly + if(isArrayBuffer) { + this.data = new DataView(b); + } else { + // TODO: adjust read/write offset based on the type of view + // or specify that this must be done in the options ... that the + // offsets are byte-based + this.data = new DataView(b.buffer, b.byteOffset, b.byteLength); + } + this.write = ('writeOffset' in options ? + options.writeOffset : this.data.byteLength); + return; + } + + // initialize to empty array buffer and add any given bytes using putBytes + this.data = new DataView(new ArrayBuffer(0)); + this.write = 0; + + if(b !== null && b !== undefined) { + this.putBytes(b); + } + + if('writeOffset' in options) { + this.write = options.writeOffset; + } +} +util.DataBuffer = DataBuffer; + +/** + * Gets the number of bytes in this buffer. + * + * @return the number of bytes in this buffer. + */ +util.DataBuffer.prototype.length = function() { + return this.write - this.read; +}; + +/** + * Gets whether or not this buffer is empty. + * + * @return true if this buffer is empty, false if not. + */ +util.DataBuffer.prototype.isEmpty = function() { + return this.length() <= 0; +}; + +/** + * Ensures this buffer has enough empty space to accommodate the given number + * of bytes. An optional parameter may be given that indicates a minimum + * amount to grow the buffer if necessary. If the parameter is not given, + * the buffer will be grown by some previously-specified default amount + * or heuristic. + * + * @param amount the number of bytes to accommodate. + * @param [growSize] the minimum amount, in bytes, to grow the buffer by if + * necessary. + */ +util.DataBuffer.prototype.accommodate = function(amount, growSize) { + if(this.length() >= amount) { + return this; + } + growSize = Math.max(growSize || this.growSize, amount); + + // grow buffer + var src = new Uint8Array( + this.data.buffer, this.data.byteOffset, this.data.byteLength); + var dst = new Uint8Array(this.length() + growSize); + dst.set(src); + this.data = new DataView(dst.buffer); + + return this; +}; + +/** + * Puts a byte in this buffer. + * + * @param b the byte to put. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putByte = function(b) { + this.accommodate(1); + this.data.setUint8(this.write++, b); + return this; +}; + +/** + * Puts a byte in this buffer N times. + * + * @param b the byte to put. + * @param n the number of bytes of value b to put. + * + * @return this buffer. + */ +util.DataBuffer.prototype.fillWithByte = function(b, n) { + this.accommodate(n); + for(var i = 0; i < n; ++i) { + this.data.setUint8(b); + } + return this; +}; + +/** + * Puts bytes in this buffer. The bytes may be given as a string, an + * ArrayBuffer, a DataView, or a TypedArray. + * + * @param bytes the bytes to put. + * @param [encoding] the encoding for the first parameter ('binary', 'utf8', + * 'utf16', 'hex'), if it is a string (default: 'binary'). + * + * @return this buffer. + */ +util.DataBuffer.prototype.putBytes = function(bytes, encoding) { + if(util.isArrayBufferView(bytes)) { + var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); + var len = src.byteLength - src.byteOffset; + this.accommodate(len); + var dst = new Uint8Array(this.data.buffer, this.write); + dst.set(src); + this.write += len; + return this; + } + + if(util.isArrayBuffer(bytes)) { + var src = new Uint8Array(bytes); + this.accommodate(src.byteLength); + var dst = new Uint8Array(this.data.buffer); + dst.set(src, this.write); + this.write += src.byteLength; + return this; + } + + // bytes is a util.DataBuffer or equivalent + if(bytes instanceof util.DataBuffer || + (typeof bytes === 'object' && + typeof bytes.read === 'number' && typeof bytes.write === 'number' && + util.isArrayBufferView(bytes.data))) { + var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length()); + this.accommodate(src.byteLength); + var dst = new Uint8Array(bytes.data.byteLength, this.write); + dst.set(src); + this.write += src.byteLength; + return this; + } + + if(bytes instanceof util.ByteStringBuffer) { + // copy binary string and process as the same as a string parameter below + bytes = bytes.data; + encoding = 'binary'; + } + + // string conversion + encoding = encoding || 'binary'; + if(typeof bytes === 'string') { + var view; + + // decode from string + if(encoding === 'hex') { + this.accommodate(Math.ceil(bytes.length / 2)); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.hex.decode(bytes, view, this.write); + return this; + } + if(encoding === 'base64') { + this.accommodate(Math.ceil(bytes.length / 4) * 3); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.base64.decode(bytes, view, this.write); + return this; + } + + // encode text as UTF-8 bytes + if(encoding === 'utf8') { + // encode as UTF-8 then decode string as raw binary + bytes = util.encodeUtf8(bytes); + encoding = 'binary'; + } + + // decode string as raw binary + if(encoding === 'binary' || encoding === 'raw') { + // one byte per character + this.accommodate(bytes.length); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.raw.decode(view); + return this; + } + + // encode text as UTF-16 bytes + if(encoding === 'utf16') { + // two bytes per character + this.accommodate(bytes.length * 2); + view = new Uint16Array(this.data.buffer, this.write); + this.write += util.text.utf16.encode(view); + return this; + } + + throw new Error('Invalid encoding: ' + encoding); + } + + throw Error('Invalid parameter: ' + bytes); +}; + +/** + * Puts the given buffer into this buffer. + * + * @param buffer the buffer to put into this one. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putBuffer = function(buffer) { + this.putBytes(buffer); + buffer.clear(); + return this; +}; + +/** + * Puts a string into this buffer. + * + * @param str the string to put. + * @param [encoding] the encoding for the string (default: 'utf16'). + * + * @return this buffer. + */ +util.DataBuffer.prototype.putString = function(str) { + return this.putBytes(str, 'utf16'); +}; + +/** + * Puts a 16-bit integer in this buffer in big-endian order. + * + * @param i the 16-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt16 = function(i) { + this.accommodate(2); + this.data.setInt16(this.write, i); + this.write += 2; + return this; +}; + +/** + * Puts a 24-bit integer in this buffer in big-endian order. + * + * @param i the 24-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt24 = function(i) { + this.accommodate(3); + this.data.setInt16(this.write, i >> 8 & 0xFFFF); + this.data.setInt8(this.write, i >> 16 & 0xFF); + this.write += 3; + return this; +}; + +/** + * Puts a 32-bit integer in this buffer in big-endian order. + * + * @param i the 32-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt32 = function(i) { + this.accommodate(4); + this.data.setInt32(this.write, i); + this.write += 4; + return this; +}; + +/** + * Puts a 16-bit integer in this buffer in little-endian order. + * + * @param i the 16-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt16Le = function(i) { + this.accommodate(2); + this.data.setInt16(this.write, i, true); + this.write += 2; + return this; +}; + +/** + * Puts a 24-bit integer in this buffer in little-endian order. + * + * @param i the 24-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt24Le = function(i) { + this.accommodate(3); + this.data.setInt8(this.write, i >> 16 & 0xFF); + this.data.setInt16(this.write, i >> 8 & 0xFFFF, true); + this.write += 3; + return this; +}; + +/** + * Puts a 32-bit integer in this buffer in little-endian order. + * + * @param i the 32-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt32Le = function(i) { + this.accommodate(4); + this.data.setInt32(this.write, i, true); + this.write += 4; + return this; +}; + +/** + * Puts an n-bit integer in this buffer in big-endian order. + * + * @param i the n-bit integer. + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt = function(i, n) { + _checkBitsParam(n); + this.accommodate(n / 8); + do { + n -= 8; + this.data.setInt8(this.write++, (i >> n) & 0xFF); + } while(n > 0); + return this; +}; + +/** + * Puts a signed n-bit integer in this buffer in big-endian order. Two's + * complement representation is used. + * + * @param i the n-bit integer. + * @param n the number of bits in the integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putSignedInt = function(i, n) { + _checkBitsParam(n); + this.accommodate(n / 8); + if(i < 0) { + i += 2 << (n - 1); + } + return this.putInt(i, n); +}; + +/** + * Gets a byte from this buffer and advances the read pointer by 1. + * + * @return the byte. + */ +util.DataBuffer.prototype.getByte = function() { + return this.data.getInt8(this.read++); +}; + +/** + * Gets a uint16 from this buffer in big-endian order and advances the read + * pointer by 2. + * + * @return the uint16. + */ +util.DataBuffer.prototype.getInt16 = function() { + var rval = this.data.getInt16(this.read); + this.read += 2; + return rval; +}; + +/** + * Gets a uint24 from this buffer in big-endian order and advances the read + * pointer by 3. + * + * @return the uint24. + */ +util.DataBuffer.prototype.getInt24 = function() { + var rval = ( + this.data.getInt16(this.read) << 8 ^ + this.data.getInt8(this.read + 2)); + this.read += 3; + return rval; +}; + +/** + * Gets a uint32 from this buffer in big-endian order and advances the read + * pointer by 4. + * + * @return the word. + */ +util.DataBuffer.prototype.getInt32 = function() { + var rval = this.data.getInt32(this.read); + this.read += 4; + return rval; +}; + +/** + * Gets a uint16 from this buffer in little-endian order and advances the read + * pointer by 2. + * + * @return the uint16. + */ +util.DataBuffer.prototype.getInt16Le = function() { + var rval = this.data.getInt16(this.read, true); + this.read += 2; + return rval; +}; + +/** + * Gets a uint24 from this buffer in little-endian order and advances the read + * pointer by 3. + * + * @return the uint24. + */ +util.DataBuffer.prototype.getInt24Le = function() { + var rval = ( + this.data.getInt8(this.read) ^ + this.data.getInt16(this.read + 1, true) << 8); + this.read += 3; + return rval; +}; + +/** + * Gets a uint32 from this buffer in little-endian order and advances the read + * pointer by 4. + * + * @return the word. + */ +util.DataBuffer.prototype.getInt32Le = function() { + var rval = this.data.getInt32(this.read, true); + this.read += 4; + return rval; +}; + +/** + * Gets an n-bit integer from this buffer in big-endian order and advances the + * read pointer by n/8. + * + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return the integer. + */ +util.DataBuffer.prototype.getInt = function(n) { + _checkBitsParam(n); + var rval = 0; + do { + // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. + rval = (rval << 8) + this.data.getInt8(this.read++); + n -= 8; + } while(n > 0); + return rval; +}; + +/** + * Gets a signed n-bit integer from this buffer in big-endian order, using + * two's complement, and advances the read pointer by n/8. + * + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return the integer. + */ +util.DataBuffer.prototype.getSignedInt = function(n) { + // getInt checks n + var x = this.getInt(n); + var max = 2 << (n - 2); + if(x >= max) { + x -= max << 1; + } + return x; +}; + +/** + * Reads bytes out as a binary encoded string and clears them from the + * buffer. + * + * @param count the number of bytes to read, undefined or null for all. + * + * @return a binary encoded string of bytes. + */ +util.DataBuffer.prototype.getBytes = function(count) { + // TODO: deprecate this method, it is poorly named and + // this.toString('binary') replaces it + // add a toTypedArray()/toArrayBuffer() function + var rval; + if(count) { + // read count bytes + count = Math.min(this.length(), count); + rval = this.data.slice(this.read, this.read + count); + this.read += count; + } else if(count === 0) { + rval = ''; + } else { + // read all bytes, optimize to only copy when needed + rval = (this.read === 0) ? this.data : this.data.slice(this.read); + this.clear(); + } + return rval; +}; + +/** + * Gets a binary encoded string of the bytes from this buffer without + * modifying the read pointer. + * + * @param count the number of bytes to get, omit to get all. + * + * @return a string full of binary encoded characters. + */ +util.DataBuffer.prototype.bytes = function(count) { + // TODO: deprecate this method, it is poorly named, add "getString()" + return (typeof(count) === 'undefined' ? + this.data.slice(this.read) : + this.data.slice(this.read, this.read + count)); +}; + +/** + * Gets a byte at the given index without modifying the read pointer. + * + * @param i the byte index. + * + * @return the byte. + */ +util.DataBuffer.prototype.at = function(i) { + return this.data.getUint8(this.read + i); +}; + +/** + * Puts a byte at the given index without modifying the read pointer. + * + * @param i the byte index. + * @param b the byte to put. + * + * @return this buffer. + */ +util.DataBuffer.prototype.setAt = function(i, b) { + this.data.setUint8(i, b); + return this; +}; + +/** + * Gets the last byte without modifying the read pointer. + * + * @return the last byte. + */ +util.DataBuffer.prototype.last = function() { + return this.data.getUint8(this.write - 1); +}; + +/** + * Creates a copy of this buffer. + * + * @return the copy. + */ +util.DataBuffer.prototype.copy = function() { + return new util.DataBuffer(this); +}; + +/** + * Compacts this buffer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.compact = function() { + if(this.read > 0) { + var src = new Uint8Array(this.data.buffer, this.read); + var dst = new Uint8Array(src.byteLength); + dst.set(src); + this.data = new DataView(dst); + this.write -= this.read; + this.read = 0; + } + return this; +}; + +/** + * Clears this buffer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.clear = function() { + this.data = new DataView(new ArrayBuffer(0)); + this.read = this.write = 0; + return this; +}; + +/** + * Shortens this buffer by trimming bytes off of the end of this buffer. + * + * @param count the number of bytes to trim off. + * + * @return this buffer. + */ +util.DataBuffer.prototype.truncate = function(count) { + this.write = Math.max(0, this.length() - count); + this.read = Math.min(this.read, this.write); + return this; +}; + +/** + * Converts this buffer to a hexadecimal string. + * + * @return a hexadecimal string. + */ +util.DataBuffer.prototype.toHex = function() { + var rval = ''; + for(var i = this.read; i < this.data.byteLength; ++i) { + var b = this.data.getUint8(i); + if(b < 16) { + rval += '0'; + } + rval += b.toString(16); + } + return rval; +}; + +/** + * Converts this buffer to a string, using the given encoding. If no + * encoding is given, 'utf8' (UTF-8) is used. + * + * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex', + * 'base64' (default: 'utf8'). + * + * @return a string representation of the bytes in this buffer. + */ +util.DataBuffer.prototype.toString = function(encoding) { + var view = new Uint8Array(this.data, this.read, this.length()); + encoding = encoding || 'utf8'; + + // encode to string + if(encoding === 'binary' || encoding === 'raw') { + return util.binary.raw.encode(view); + } + if(encoding === 'hex') { + return util.binary.hex.encode(view); + } + if(encoding === 'base64') { + return util.binary.base64.encode(view); + } + + // decode to text + if(encoding === 'utf8') { + return util.text.utf8.decode(view); + } + if(encoding === 'utf16') { + return util.text.utf16.decode(view); + } + + throw new Error('Invalid encoding: ' + encoding); +}; + +/** End Buffer w/UInt8Array backing */ + +/** + * Creates a buffer that stores bytes. A value may be given to populate the + * buffer with data. This value can either be string of encoded bytes or a + * regular string of characters. When passing a string of binary encoded + * bytes, the encoding `raw` should be given. This is also the default. When + * passing a string of characters, the encoding `utf8` should be given. + * + * @param [input] a string with encoded bytes to store in the buffer. + * @param [encoding] (default: 'raw', other: 'utf8'). + */ +util.createBuffer = function(input, encoding) { + // TODO: deprecate, use new ByteBuffer() instead + encoding = encoding || 'raw'; + if(input !== undefined && encoding === 'utf8') { + input = util.encodeUtf8(input); + } + return new util.ByteBuffer(input); +}; + +/** + * Fills a string with a particular value. If you want the string to be a byte + * string, pass in String.fromCharCode(theByte). + * + * @param c the character to fill the string with, use String.fromCharCode + * to fill the string with a byte value. + * @param n the number of characters of value c to fill with. + * + * @return the filled string. + */ +util.fillString = function(c, n) { + var s = ''; + while(n > 0) { + if(n & 1) { + s += c; + } + n >>>= 1; + if(n > 0) { + c += c; + } + } + return s; +}; + +/** + * Performs a per byte XOR between two byte strings and returns the result as a + * string of bytes. + * + * @param s1 first string of bytes. + * @param s2 second string of bytes. + * @param n the number of bytes to XOR. + * + * @return the XOR'd result. + */ +util.xorBytes = function(s1, s2, n) { + var s3 = ''; + var b = ''; + var t = ''; + var i = 0; + var c = 0; + for(; n > 0; --n, ++i) { + b = s1.charCodeAt(i) ^ s2.charCodeAt(i); + if(c >= 10) { + s3 += t; + t = ''; + c = 0; + } + t += String.fromCharCode(b); + ++c; + } + s3 += t; + return s3; +}; + +/** + * Converts a hex string into a 'binary' encoded string of bytes. + * + * @param hex the hexadecimal string to convert. + * + * @return the binary-encoded string of bytes. + */ +util.hexToBytes = function(hex) { + // TODO: deprecate: "Deprecated. Use util.binary.hex.decode instead." + var rval = ''; + var i = 0; + if(hex.length & 1 == 1) { + // odd number of characters, convert first character alone + i = 1; + rval += String.fromCharCode(parseInt(hex[0], 16)); + } + // convert 2 characters (1 byte) at a time + for(; i < hex.length; i += 2) { + rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); + } + return rval; +}; + +/** + * Converts a 'binary' encoded string of bytes to hex. + * + * @param bytes the byte string to convert. + * + * @return the string of hexadecimal characters. + */ +util.bytesToHex = function(bytes) { + // TODO: deprecate: "Deprecated. Use util.binary.hex.encode instead." + return util.createBuffer(bytes).toHex(); +}; + +/** + * Converts an 32-bit integer to 4-big-endian byte string. + * + * @param i the integer. + * + * @return the byte string. + */ +util.int32ToBytes = function(i) { + return ( + String.fromCharCode(i >> 24 & 0xFF) + + String.fromCharCode(i >> 16 & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i & 0xFF)); +}; + +// base64 characters, reverse mapping +var _base64 = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; +var _base64Idx = [ +/*43 -43 = 0*/ +/*'+', 1, 2, 3,'/' */ + 62, -1, -1, -1, 63, + +/*'0','1','2','3','4','5','6','7','8','9' */ + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, + +/*15, 16, 17,'=', 19, 20, 21 */ + -1, -1, -1, 64, -1, -1, -1, + +/*65 - 43 = 22*/ +/*'A','B','C','D','E','F','G','H','I','J','K','L','M', */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, + +/*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */ + 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + +/*91 - 43 = 48 */ +/*48, 49, 50, 51, 52, 53 */ + -1, -1, -1, -1, -1, -1, + +/*97 - 43 = 54*/ +/*'a','b','c','d','e','f','g','h','i','j','k','l','m' */ + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, + +/*'n','o','p','q','r','s','t','u','v','w','x','y','z' */ + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 +]; + +// base58 characters (Bitcoin alphabet) +var _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + +/** + * Base64 encodes a 'binary' encoded string of bytes. + * + * @param input the binary encoded string of bytes to base64-encode. + * @param maxline the maximum number of encoded characters per line to use, + * defaults to none. + * + * @return the base64-encoded output. + */ +util.encode64 = function(input, maxline) { + // TODO: deprecate: "Deprecated. Use util.binary.base64.encode instead." + var line = ''; + var output = ''; + var chr1, chr2, chr3; + var i = 0; + while(i < input.length) { + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + // encode 4 character group + line += _base64.charAt(chr1 >> 2); + line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); + if(isNaN(chr2)) { + line += '=='; + } else { + line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); + line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); + } + + if(maxline && line.length > maxline) { + output += line.substr(0, maxline) + '\r\n'; + line = line.substr(maxline); + } + } + output += line; + return output; +}; + +/** + * Base64 decodes a string into a 'binary' encoded string of bytes. + * + * @param input the base64-encoded input. + * + * @return the binary encoded string. + */ +util.decode64 = function(input) { + // TODO: deprecate: "Deprecated. Use util.binary.base64.decode instead." + + // remove all non-base64 characters + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); + + var output = ''; + var enc1, enc2, enc3, enc4; + var i = 0; + + while(i < input.length) { + enc1 = _base64Idx[input.charCodeAt(i++) - 43]; + enc2 = _base64Idx[input.charCodeAt(i++) - 43]; + enc3 = _base64Idx[input.charCodeAt(i++) - 43]; + enc4 = _base64Idx[input.charCodeAt(i++) - 43]; + + output += String.fromCharCode((enc1 << 2) | (enc2 >> 4)); + if(enc3 !== 64) { + // decoded at least 2 bytes + output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2)); + if(enc4 !== 64) { + // decoded 3 bytes + output += String.fromCharCode(((enc3 & 3) << 6) | enc4); + } + } + } + + return output; +}; + +/** + * Encodes the given string of characters (a standard JavaScript + * string) as a binary encoded string where the bytes represent + * a UTF-8 encoded string of characters. Non-ASCII characters will be + * encoded as multiple bytes according to UTF-8. + * + * @param str a standard string of characters to encode. + * + * @return the binary encoded string. + */ +util.encodeUtf8 = function(str) { + return unescape(encodeURIComponent(str)); +}; + +/** + * Decodes a binary encoded string that contains bytes that + * represent a UTF-8 encoded string of characters -- into a + * string of characters (a standard JavaScript string). + * + * @param str the binary encoded string to decode. + * + * @return the resulting standard string of characters. + */ +util.decodeUtf8 = function(str) { + return decodeURIComponent(escape(str)); +}; + +// binary encoding/decoding tools +// FIXME: Experimental. Do not use yet. +util.binary = { + raw: {}, + hex: {}, + base64: {}, + base58: {}, + baseN : { + encode: baseN.encode, + decode: baseN.decode + } +}; + +/** + * Encodes a Uint8Array as a binary-encoded string. This encoding uses + * a value between 0 and 255 for each character. + * + * @param bytes the Uint8Array to encode. + * + * @return the binary-encoded string. + */ +util.binary.raw.encode = function(bytes) { + return String.fromCharCode.apply(null, bytes); +}; + +/** + * Decodes a binary-encoded string to a Uint8Array. This encoding uses + * a value between 0 and 255 for each character. + * + * @param str the binary-encoded string to decode. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util.binary.raw.decode = function(str, output, offset) { + var out = output; + if(!out) { + out = new Uint8Array(str.length); + } + offset = offset || 0; + var j = offset; + for(var i = 0; i < str.length; ++i) { + out[j++] = str.charCodeAt(i); + } + return output ? (j - offset) : out; +}; + +/** + * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or + * ByteBuffer as a string of hexadecimal characters. + * + * @param bytes the bytes to convert. + * + * @return the string of hexadecimal characters. + */ +util.binary.hex.encode = util.bytesToHex; + +/** + * Decodes a hex-encoded string to a Uint8Array. + * + * @param hex the hexadecimal string to convert. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util.binary.hex.decode = function(hex, output, offset) { + var out = output; + if(!out) { + out = new Uint8Array(Math.ceil(hex.length / 2)); + } + offset = offset || 0; + var i = 0, j = offset; + if(hex.length & 1) { + // odd number of characters, convert first character alone + i = 1; + out[j++] = parseInt(hex[0], 16); + } + // convert 2 characters (1 byte) at a time + for(; i < hex.length; i += 2) { + out[j++] = parseInt(hex.substr(i, 2), 16); + } + return output ? (j - offset) : out; +}; + +/** + * Base64-encodes a Uint8Array. + * + * @param input the Uint8Array to encode. + * @param maxline the maximum number of encoded characters per line to use, + * defaults to none. + * + * @return the base64-encoded output string. + */ +util.binary.base64.encode = function(input, maxline) { + var line = ''; + var output = ''; + var chr1, chr2, chr3; + var i = 0; + while(i < input.byteLength) { + chr1 = input[i++]; + chr2 = input[i++]; + chr3 = input[i++]; + + // encode 4 character group + line += _base64.charAt(chr1 >> 2); + line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); + if(isNaN(chr2)) { + line += '=='; + } else { + line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); + line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); + } + + if(maxline && line.length > maxline) { + output += line.substr(0, maxline) + '\r\n'; + line = line.substr(maxline); + } + } + output += line; + return output; +}; + +/** + * Decodes a base64-encoded string to a Uint8Array. + * + * @param input the base64-encoded input string. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util.binary.base64.decode = function(input, output, offset) { + var out = output; + if(!out) { + out = new Uint8Array(Math.ceil(input.length / 4) * 3); + } + + // remove all non-base64 characters + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); + + offset = offset || 0; + var enc1, enc2, enc3, enc4; + var i = 0, j = offset; + + while(i < input.length) { + enc1 = _base64Idx[input.charCodeAt(i++) - 43]; + enc2 = _base64Idx[input.charCodeAt(i++) - 43]; + enc3 = _base64Idx[input.charCodeAt(i++) - 43]; + enc4 = _base64Idx[input.charCodeAt(i++) - 43]; + + out[j++] = (enc1 << 2) | (enc2 >> 4); + if(enc3 !== 64) { + // decoded at least 2 bytes + out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2); + if(enc4 !== 64) { + // decoded 3 bytes + out[j++] = ((enc3 & 3) << 6) | enc4; + } + } + } + + // make sure result is the exact decoded length + return output ? (j - offset) : out.subarray(0, j); +}; + +// add support for base58 encoding/decoding with Bitcoin alphabet +util.binary.base58.encode = function(input, maxline) { + return util.binary.baseN.encode(input, _base58, maxline); +}; +util.binary.base58.decode = function(input, maxline) { + return util.binary.baseN.decode(input, _base58, maxline); +}; + +// text encoding/decoding tools +// FIXME: Experimental. Do not use yet. +util.text = { + utf8: {}, + utf16: {} +}; + +/** + * Encodes the given string as UTF-8 in a Uint8Array. + * + * @param str the string to encode. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util.text.utf8.encode = function(str, output, offset) { + str = util.encodeUtf8(str); + var out = output; + if(!out) { + out = new Uint8Array(str.length); + } + offset = offset || 0; + var j = offset; + for(var i = 0; i < str.length; ++i) { + out[j++] = str.charCodeAt(i); + } + return output ? (j - offset) : out; +}; + +/** + * Decodes the UTF-8 contents from a Uint8Array. + * + * @param bytes the Uint8Array to decode. + * + * @return the resulting string. + */ +util.text.utf8.decode = function(bytes) { + return util.decodeUtf8(String.fromCharCode.apply(null, bytes)); +}; + +/** + * Encodes the given string as UTF-16 in a Uint8Array. + * + * @param str the string to encode. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util.text.utf16.encode = function(str, output, offset) { + var out = output; + if(!out) { + out = new Uint8Array(str.length * 2); + } + var view = new Uint16Array(out.buffer); + offset = offset || 0; + var j = offset; + var k = offset; + for(var i = 0; i < str.length; ++i) { + view[k++] = str.charCodeAt(i); + j += 2; + } + return output ? (j - offset) : out; +}; + +/** + * Decodes the UTF-16 contents from a Uint8Array. + * + * @param bytes the Uint8Array to decode. + * + * @return the resulting string. + */ +util.text.utf16.decode = function(bytes) { + return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer)); +}; + +/** + * Deflates the given data using a flash interface. + * + * @param api the flash interface. + * @param bytes the data. + * @param raw true to return only raw deflate data, false to include zlib + * header and trailer. + * + * @return the deflated data as a string. + */ +util.deflate = function(api, bytes, raw) { + bytes = util.decode64(api.deflate(util.encode64(bytes)).rval); + + // strip zlib header and trailer if necessary + if(raw) { + // zlib header is 2 bytes (CMF,FLG) where FLG indicates that + // there is a 4-byte DICT (alder-32) block before the data if + // its 5th bit is set + var start = 2; + var flg = bytes.charCodeAt(1); + if(flg & 0x20) { + start = 6; + } + // zlib trailer is 4 bytes of adler-32 + bytes = bytes.substring(start, bytes.length - 4); + } + + return bytes; +}; + +/** + * Inflates the given data using a flash interface. + * + * @param api the flash interface. + * @param bytes the data. + * @param raw true if the incoming data has no zlib header or trailer and is + * raw DEFLATE data. + * + * @return the inflated data as a string, null on error. + */ +util.inflate = function(api, bytes, raw) { + // TODO: add zlib header and trailer if necessary/possible + var rval = api.inflate(util.encode64(bytes)).rval; + return (rval === null) ? null : util.decode64(rval); +}; + +/** + * Sets a storage object. + * + * @param api the storage interface. + * @param id the storage ID to use. + * @param obj the storage object, null to remove. + */ +var _setStorageObject = function(api, id, obj) { + if(!api) { + throw new Error('WebStorage not available.'); + } + + var rval; + if(obj === null) { + rval = api.removeItem(id); + } else { + // json-encode and base64-encode object + obj = util.encode64(JSON.stringify(obj)); + rval = api.setItem(id, obj); + } + + // handle potential flash error + if(typeof(rval) !== 'undefined' && rval.rval !== true) { + var error = new Error(rval.error.message); + error.id = rval.error.id; + error.name = rval.error.name; + throw error; + } +}; + +/** + * Gets a storage object. + * + * @param api the storage interface. + * @param id the storage ID to use. + * + * @return the storage object entry or null if none exists. + */ +var _getStorageObject = function(api, id) { + if(!api) { + throw new Error('WebStorage not available.'); + } + + // get the existing entry + var rval = api.getItem(id); + + /* Note: We check api.init because we can't do (api == localStorage) + on IE because of "Class doesn't support Automation" exception. Only + the flash api has an init method so this works too, but we need a + better solution in the future. */ + + // flash returns item wrapped in an object, handle special case + if(api.init) { + if(rval.rval === null) { + if(rval.error) { + var error = new Error(rval.error.message); + error.id = rval.error.id; + error.name = rval.error.name; + throw error; + } + // no error, but also no item + rval = null; + } else { + rval = rval.rval; + } + } + + // handle decoding + if(rval !== null) { + // base64-decode and json-decode data + rval = JSON.parse(util.decode64(rval)); + } + + return rval; +}; + +/** + * Stores an item in local storage. + * + * @param api the storage interface. + * @param id the storage ID to use. + * @param key the key for the item. + * @param data the data for the item (any javascript object/primitive). + */ +var _setItem = function(api, id, key, data) { + // get storage object + var obj = _getStorageObject(api, id); + if(obj === null) { + // create a new storage object + obj = {}; + } + // update key + obj[key] = data; + + // set storage object + _setStorageObject(api, id, obj); +}; + +/** + * Gets an item from local storage. + * + * @param api the storage interface. + * @param id the storage ID to use. + * @param key the key for the item. + * + * @return the item. + */ +var _getItem = function(api, id, key) { + // get storage object + var rval = _getStorageObject(api, id); + if(rval !== null) { + // return data at key + rval = (key in rval) ? rval[key] : null; + } + + return rval; +}; + +/** + * Removes an item from local storage. + * + * @param api the storage interface. + * @param id the storage ID to use. + * @param key the key for the item. + */ +var _removeItem = function(api, id, key) { + // get storage object + var obj = _getStorageObject(api, id); + if(obj !== null && key in obj) { + // remove key + delete obj[key]; + + // see if entry has no keys remaining + var empty = true; + for(var prop in obj) { + empty = false; + break; + } + if(empty) { + // remove entry entirely if no keys are left + obj = null; + } + + // set storage object + _setStorageObject(api, id, obj); + } +}; + +/** + * Clears the local disk storage identified by the given ID. + * + * @param api the storage interface. + * @param id the storage ID to use. + */ +var _clearItems = function(api, id) { + _setStorageObject(api, id, null); +}; + +/** + * Calls a storage function. + * + * @param func the function to call. + * @param args the arguments for the function. + * @param location the location argument. + * + * @return the return value from the function. + */ +var _callStorageFunction = function(func, args, location) { + var rval = null; + + // default storage types + if(typeof(location) === 'undefined') { + location = ['web', 'flash']; + } + + // apply storage types in order of preference + var type; + var done = false; + var exception = null; + for(var idx in location) { + type = location[idx]; + try { + if(type === 'flash' || type === 'both') { + if(args[0] === null) { + throw new Error('Flash local storage not available.'); + } + rval = func.apply(this, args); + done = (type === 'flash'); + } + if(type === 'web' || type === 'both') { + args[0] = localStorage; + rval = func.apply(this, args); + done = true; + } + } catch(ex) { + exception = ex; + } + if(done) { + break; + } + } + + if(!done) { + throw exception; + } + + return rval; +}; + +/** + * Stores an item on local disk. + * + * The available types of local storage include 'flash', 'web', and 'both'. + * + * The type 'flash' refers to flash local storage (SharedObject). In order + * to use flash local storage, the 'api' parameter must be valid. The type + * 'web' refers to WebStorage, if supported by the browser. The type 'both' + * refers to storing using both 'flash' and 'web', not just one or the + * other. + * + * The location array should list the storage types to use in order of + * preference: + * + * ['flash']: flash only storage + * ['web']: web only storage + * ['both']: try to store in both + * ['flash','web']: store in flash first, but if not available, 'web' + * ['web','flash']: store in web first, but if not available, 'flash' + * + * The location array defaults to: ['web', 'flash'] + * + * @param api the flash interface, null to use only WebStorage. + * @param id the storage ID to use. + * @param key the key for the item. + * @param data the data for the item (any javascript object/primitive). + * @param location an array with the preferred types of storage to use. + */ +util.setItem = function(api, id, key, data, location) { + _callStorageFunction(_setItem, arguments, location); +}; + +/** + * Gets an item on local disk. + * + * Set setItem() for details on storage types. + * + * @param api the flash interface, null to use only WebStorage. + * @param id the storage ID to use. + * @param key the key for the item. + * @param location an array with the preferred types of storage to use. + * + * @return the item. + */ +util.getItem = function(api, id, key, location) { + return _callStorageFunction(_getItem, arguments, location); +}; + +/** + * Removes an item on local disk. + * + * Set setItem() for details on storage types. + * + * @param api the flash interface. + * @param id the storage ID to use. + * @param key the key for the item. + * @param location an array with the preferred types of storage to use. + */ +util.removeItem = function(api, id, key, location) { + _callStorageFunction(_removeItem, arguments, location); +}; + +/** + * Clears the local disk storage identified by the given ID. + * + * Set setItem() for details on storage types. + * + * @param api the flash interface if flash is available. + * @param id the storage ID to use. + * @param location an array with the preferred types of storage to use. + */ +util.clearItems = function(api, id, location) { + _callStorageFunction(_clearItems, arguments, location); +}; + +/** + * Check if an object is empty. + * + * Taken from: + * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937 + * + * @param object the object to check. + */ +util.isEmpty = function(obj) { + for(var prop in obj) { + if(obj.hasOwnProperty(prop)) { + return false; + } + } + return true; +}; + +/** + * Format with simple printf-style interpolation. + * + * %%: literal '%' + * %s,%o: convert next argument into a string. + * + * @param format the string to format. + * @param ... arguments to interpolate into the format string. + */ +util.format = function(format) { + var re = /%./g; + // current match + var match; + // current part + var part; + // current arg index + var argi = 0; + // collected parts to recombine later + var parts = []; + // last index found + var last = 0; + // loop while matches remain + while((match = re.exec(format))) { + part = format.substring(last, re.lastIndex - 2); + // don't add empty strings (ie, parts between %s%s) + if(part.length > 0) { + parts.push(part); + } + last = re.lastIndex; + // switch on % code + var code = match[0][1]; + switch(code) { + case 's': + case 'o': + // check if enough arguments were given + if(argi < arguments.length) { + parts.push(arguments[argi++ + 1]); + } else { + parts.push(''); + } + break; + // FIXME: do proper formatting for numbers, etc + //case 'f': + //case 'd': + case '%': + parts.push('%'); + break; + default: + parts.push('<%' + code + '?>'); + } + } + // add trailing part of format string + parts.push(format.substring(last)); + return parts.join(''); +}; + +/** + * Formats a number. + * + * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/ + */ +util.formatNumber = function(number, decimals, dec_point, thousands_sep) { + // http://kevin.vanzonneveld.net + // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + bugfix by: Michael White (http://crestidg.com) + // + bugfix by: Benjamin Lupton + // + bugfix by: Allan Jensen (http://www.winternet.no) + // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) + // * example 1: number_format(1234.5678, 2, '.', ''); + // * returns 1: 1234.57 + + var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals; + var d = dec_point === undefined ? ',' : dec_point; + var t = thousands_sep === undefined ? + '.' : thousands_sep, s = n < 0 ? '-' : ''; + var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + ''; + var j = (i.length > 3) ? i.length % 3 : 0; + return s + (j ? i.substr(0, j) + t : '') + + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + t) + + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ''); +}; + +/** + * Formats a byte size. + * + * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/ + */ +util.formatSize = function(size) { + if(size >= 1073741824) { + size = util.formatNumber(size / 1073741824, 2, '.', '') + ' GiB'; + } else if(size >= 1048576) { + size = util.formatNumber(size / 1048576, 2, '.', '') + ' MiB'; + } else if(size >= 1024) { + size = util.formatNumber(size / 1024, 0) + ' KiB'; + } else { + size = util.formatNumber(size, 0) + ' bytes'; + } + return size; +}; + +/** + * Converts an IPv4 or IPv6 string representation into bytes (in network order). + * + * @param ip the IPv4 or IPv6 address to convert. + * + * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't + * be parsed. + */ +util.bytesFromIP = function(ip) { + if(ip.indexOf('.') !== -1) { + return util.bytesFromIPv4(ip); + } + if(ip.indexOf(':') !== -1) { + return util.bytesFromIPv6(ip); + } + return null; +}; + +/** + * Converts an IPv4 string representation into bytes (in network order). + * + * @param ip the IPv4 address to convert. + * + * @return the 4-byte address or null if the address can't be parsed. + */ +util.bytesFromIPv4 = function(ip) { + ip = ip.split('.'); + if(ip.length !== 4) { + return null; + } + var b = util.createBuffer(); + for(var i = 0; i < ip.length; ++i) { + var num = parseInt(ip[i], 10); + if(isNaN(num)) { + return null; + } + b.putByte(num); + } + return b.getBytes(); +}; + +/** + * Converts an IPv6 string representation into bytes (in network order). + * + * @param ip the IPv6 address to convert. + * + * @return the 16-byte address or null if the address can't be parsed. + */ +util.bytesFromIPv6 = function(ip) { + var blanks = 0; + ip = ip.split(':').filter(function(e) { + if(e.length === 0) ++blanks; + return true; + }); + var zeros = (8 - ip.length + blanks) * 2; + var b = util.createBuffer(); + for(var i = 0; i < 8; ++i) { + if(!ip[i] || ip[i].length === 0) { + b.fillWithByte(0, zeros); + zeros = 0; + continue; + } + var bytes = util.hexToBytes(ip[i]); + if(bytes.length < 2) { + b.putByte(0); + } + b.putBytes(bytes); + } + return b.getBytes(); +}; + +/** + * Converts 4-bytes into an IPv4 string representation or 16-bytes into + * an IPv6 string representation. The bytes must be in network order. + * + * @param bytes the bytes to convert. + * + * @return the IPv4 or IPv6 string representation if 4 or 16 bytes, + * respectively, are given, otherwise null. + */ +util.bytesToIP = function(bytes) { + if(bytes.length === 4) { + return util.bytesToIPv4(bytes); + } + if(bytes.length === 16) { + return util.bytesToIPv6(bytes); + } + return null; +}; + +/** + * Converts 4-bytes into an IPv4 string representation. The bytes must be + * in network order. + * + * @param bytes the bytes to convert. + * + * @return the IPv4 string representation or null for an invalid # of bytes. + */ +util.bytesToIPv4 = function(bytes) { + if(bytes.length !== 4) { + return null; + } + var ip = []; + for(var i = 0; i < bytes.length; ++i) { + ip.push(bytes.charCodeAt(i)); + } + return ip.join('.'); +}; + +/** + * Converts 16-bytes into an IPv16 string representation. The bytes must be + * in network order. + * + * @param bytes the bytes to convert. + * + * @return the IPv16 string representation or null for an invalid # of bytes. + */ +util.bytesToIPv6 = function(bytes) { + if(bytes.length !== 16) { + return null; + } + var ip = []; + var zeroGroups = []; + var zeroMaxGroup = 0; + for(var i = 0; i < bytes.length; i += 2) { + var hex = util.bytesToHex(bytes[i] + bytes[i + 1]); + // canonicalize zero representation + while(hex[0] === '0' && hex !== '0') { + hex = hex.substr(1); + } + if(hex === '0') { + var last = zeroGroups[zeroGroups.length - 1]; + var idx = ip.length; + if(!last || idx !== last.end + 1) { + zeroGroups.push({start: idx, end: idx}); + } else { + last.end = idx; + if((last.end - last.start) > + (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) { + zeroMaxGroup = zeroGroups.length - 1; + } + } + } + ip.push(hex); + } + if(zeroGroups.length > 0) { + var group = zeroGroups[zeroMaxGroup]; + // only shorten group of length > 0 + if(group.end - group.start > 0) { + ip.splice(group.start, group.end - group.start + 1, ''); + if(group.start === 0) { + ip.unshift(''); + } + if(group.end === 7) { + ip.push(''); + } + } + } + return ip.join(':'); +}; + +/** + * Estimates the number of processes that can be run concurrently. If + * creating Web Workers, keep in mind that the main JavaScript process needs + * its own core. + * + * @param options the options to use: + * update true to force an update (not use the cached value). + * @param callback(err, max) called once the operation completes. + */ +util.estimateCores = function(options, callback) { + if(typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + if('cores' in util && !options.update) { + return callback(null, util.cores); + } + if(typeof navigator !== 'undefined' && + 'hardwareConcurrency' in navigator && + navigator.hardwareConcurrency > 0) { + util.cores = navigator.hardwareConcurrency; + return callback(null, util.cores); + } + if(typeof Worker === 'undefined') { + // workers not available + util.cores = 1; + return callback(null, util.cores); + } + if(typeof Blob === 'undefined') { + // can't estimate, default to 2 + util.cores = 2; + return callback(null, util.cores); + } + + // create worker concurrency estimation code as blob + var blobUrl = URL.createObjectURL(new Blob(['(', + function() { + self.addEventListener('message', function(e) { + // run worker for 4 ms + var st = Date.now(); + var et = st + 4; + while(Date.now() < et); + self.postMessage({st: st, et: et}); + }); + }.toString(), + ')()'], {type: 'application/javascript'})); + + // take 5 samples using 16 workers + sample([], 5, 16); + + function sample(max, samples, numWorkers) { + if(samples === 0) { + // get overlap average + var avg = Math.floor(max.reduce(function(avg, x) { + return avg + x; + }, 0) / max.length); + util.cores = Math.max(1, avg); + URL.revokeObjectURL(blobUrl); + return callback(null, util.cores); + } + map(numWorkers, function(err, results) { + max.push(reduce(numWorkers, results)); + sample(max, samples - 1, numWorkers); + }); + } + + function map(numWorkers, callback) { + var workers = []; + var results = []; + for(var i = 0; i < numWorkers; ++i) { + var worker = new Worker(blobUrl); + worker.addEventListener('message', function(e) { + results.push(e.data); + if(results.length === numWorkers) { + for(var i = 0; i < numWorkers; ++i) { + workers[i].terminate(); + } + callback(null, results); + } + }); + workers.push(worker); + } + for(var i = 0; i < numWorkers; ++i) { + workers[i].postMessage(i); + } + } + + function reduce(numWorkers, results) { + // find overlapping time windows + var overlaps = []; + for(var n = 0; n < numWorkers; ++n) { + var r1 = results[n]; + var overlap = overlaps[n] = []; + for(var i = 0; i < numWorkers; ++i) { + if(n === i) { + continue; + } + var r2 = results[i]; + if((r1.st > r2.st && r1.st < r2.et) || + (r2.st > r1.st && r2.st < r1.et)) { + overlap.push(i); + } + } + } + // get maximum overlaps ... don't include overlapping worker itself + // as the main JS process was also being scheduled during the work and + // would have to be subtracted from the estimate anyway + return overlaps.reduce(function(max, overlap) { + return Math.max(max, overlap.length); + }, 0); + } +}; diff --git a/node_modules/node-forge/lib/x509.js b/node_modules/node-forge/lib/x509.js new file mode 100644 index 0000000..99209ff --- /dev/null +++ b/node_modules/node-forge/lib/x509.js @@ -0,0 +1,3242 @@ +/** + * Javascript implementation of X.509 and related components (such as + * Certification Signing Requests) of a Public Key Infrastructure. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + * + * The ASN.1 representation of an X.509v3 certificate is as follows + * (see RFC 2459): + * + * Certificate ::= SEQUENCE { + * tbsCertificate TBSCertificate, + * signatureAlgorithm AlgorithmIdentifier, + * signatureValue BIT STRING + * } + * + * TBSCertificate ::= SEQUENCE { + * version [0] EXPLICIT Version DEFAULT v1, + * serialNumber CertificateSerialNumber, + * signature AlgorithmIdentifier, + * issuer Name, + * validity Validity, + * subject Name, + * subjectPublicKeyInfo SubjectPublicKeyInfo, + * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL, + * -- If present, version shall be v2 or v3 + * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL, + * -- If present, version shall be v2 or v3 + * extensions [3] EXPLICIT Extensions OPTIONAL + * -- If present, version shall be v3 + * } + * + * Version ::= INTEGER { v1(0), v2(1), v3(2) } + * + * CertificateSerialNumber ::= INTEGER + * + * Name ::= CHOICE { + * // only one possible choice for now + * RDNSequence + * } + * + * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName + * + * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue + * + * AttributeTypeAndValue ::= SEQUENCE { + * type AttributeType, + * value AttributeValue + * } + * AttributeType ::= OBJECT IDENTIFIER + * AttributeValue ::= ANY DEFINED BY AttributeType + * + * Validity ::= SEQUENCE { + * notBefore Time, + * notAfter Time + * } + * + * Time ::= CHOICE { + * utcTime UTCTime, + * generalTime GeneralizedTime + * } + * + * UniqueIdentifier ::= BIT STRING + * + * SubjectPublicKeyInfo ::= SEQUENCE { + * algorithm AlgorithmIdentifier, + * subjectPublicKey BIT STRING + * } + * + * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension + * + * Extension ::= SEQUENCE { + * extnID OBJECT IDENTIFIER, + * critical BOOLEAN DEFAULT FALSE, + * extnValue OCTET STRING + * } + * + * The only key algorithm currently supported for PKI is RSA. + * + * RSASSA-PSS signatures are described in RFC 3447 and RFC 4055. + * + * PKCS#10 v1.7 describes certificate signing requests: + * + * CertificationRequestInfo: + * + * CertificationRequestInfo ::= SEQUENCE { + * version INTEGER { v1(0) } (v1,...), + * subject Name, + * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }}, + * attributes [0] Attributes{{ CRIAttributes }} + * } + * + * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }} + * + * CRIAttributes ATTRIBUTE ::= { + * ... -- add any locally defined attributes here -- } + * + * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE { + * type ATTRIBUTE.&id({IOSet}), + * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type}) + * } + * + * CertificationRequest ::= SEQUENCE { + * certificationRequestInfo CertificationRequestInfo, + * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }}, + * signature BIT STRING + * } + */ +var forge = require('./forge'); +require('./aes'); +require('./asn1'); +require('./des'); +require('./md'); +require('./mgf'); +require('./oids'); +require('./pem'); +require('./pss'); +require('./rsa'); +require('./util'); + +// shortcut for asn.1 API +var asn1 = forge.asn1; + +/* Public Key Infrastructure (PKI) implementation. */ +var pki = module.exports = forge.pki = forge.pki || {}; +var oids = pki.oids; + +// short name OID mappings +var _shortNames = {}; +_shortNames['CN'] = oids['commonName']; +_shortNames['commonName'] = 'CN'; +_shortNames['C'] = oids['countryName']; +_shortNames['countryName'] = 'C'; +_shortNames['L'] = oids['localityName']; +_shortNames['localityName'] = 'L'; +_shortNames['ST'] = oids['stateOrProvinceName']; +_shortNames['stateOrProvinceName'] = 'ST'; +_shortNames['O'] = oids['organizationName']; +_shortNames['organizationName'] = 'O'; +_shortNames['OU'] = oids['organizationalUnitName']; +_shortNames['organizationalUnitName'] = 'OU'; +_shortNames['E'] = oids['emailAddress']; +_shortNames['emailAddress'] = 'E'; + +// validator for an SubjectPublicKeyInfo structure +// Note: Currently only works with an RSA public key +var publicKeyValidator = forge.pki.rsa.publicKeyValidator; + +// validator for an X.509v3 certificate +var x509CertificateValidator = { + name: 'Certificate', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'Certificate.TBSCertificate', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'tbsCertificate', + value: [{ + name: 'Certificate.TBSCertificate.version', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + value: [{ + name: 'Certificate.TBSCertificate.version.integer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'certVersion' + }] + }, { + name: 'Certificate.TBSCertificate.serialNumber', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'certSerialNumber' + }, { + name: 'Certificate.TBSCertificate.signature', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'Certificate.TBSCertificate.signature.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'certinfoSignatureOid' + }, { + name: 'Certificate.TBSCertificate.signature.parameters', + tagClass: asn1.Class.UNIVERSAL, + optional: true, + captureAsn1: 'certinfoSignatureParams' + }] + }, { + name: 'Certificate.TBSCertificate.issuer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'certIssuer' + }, { + name: 'Certificate.TBSCertificate.validity', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + // Note: UTC and generalized times may both appear so the capture + // names are based on their detected order, the names used below + // are only for the common case, which validity time really means + // "notBefore" and which means "notAfter" will be determined by order + value: [{ + // notBefore (Time) (UTC time case) + name: 'Certificate.TBSCertificate.validity.notBefore (utc)', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.UTCTIME, + constructed: false, + optional: true, + capture: 'certValidity1UTCTime' + }, { + // notBefore (Time) (generalized time case) + name: 'Certificate.TBSCertificate.validity.notBefore (generalized)', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.GENERALIZEDTIME, + constructed: false, + optional: true, + capture: 'certValidity2GeneralizedTime' + }, { + // notAfter (Time) (only UTC time is supported) + name: 'Certificate.TBSCertificate.validity.notAfter (utc)', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.UTCTIME, + constructed: false, + optional: true, + capture: 'certValidity3UTCTime' + }, { + // notAfter (Time) (only UTC time is supported) + name: 'Certificate.TBSCertificate.validity.notAfter (generalized)', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.GENERALIZEDTIME, + constructed: false, + optional: true, + capture: 'certValidity4GeneralizedTime' + }] + }, { + // Name (subject) (RDNSequence) + name: 'Certificate.TBSCertificate.subject', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'certSubject' + }, + // SubjectPublicKeyInfo + publicKeyValidator, + { + // issuerUniqueID (optional) + name: 'Certificate.TBSCertificate.issuerUniqueID', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + optional: true, + value: [{ + name: 'Certificate.TBSCertificate.issuerUniqueID.id', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + // TODO: support arbitrary bit length ids + captureBitStringValue: 'certIssuerUniqueId' + }] + }, { + // subjectUniqueID (optional) + name: 'Certificate.TBSCertificate.subjectUniqueID', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 2, + constructed: true, + optional: true, + value: [{ + name: 'Certificate.TBSCertificate.subjectUniqueID.id', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + // TODO: support arbitrary bit length ids + captureBitStringValue: 'certSubjectUniqueId' + }] + }, { + // Extensions (optional) + name: 'Certificate.TBSCertificate.extensions', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 3, + constructed: true, + captureAsn1: 'certExtensions', + optional: true + }] + }, { + // AlgorithmIdentifier (signature algorithm) + name: 'Certificate.signatureAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // algorithm + name: 'Certificate.signatureAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'certSignatureOid' + }, { + name: 'Certificate.TBSCertificate.signature.parameters', + tagClass: asn1.Class.UNIVERSAL, + optional: true, + captureAsn1: 'certSignatureParams' + }] + }, { + // SignatureValue + name: 'Certificate.signatureValue', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + captureBitStringValue: 'certSignature' + }] +}; + +var rsassaPssParameterValidator = { + name: 'rsapss', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'rsapss.hashAlgorithm', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + value: [{ + name: 'rsapss.hashAlgorithm.AlgorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.SEQUENCE, + constructed: true, + optional: true, + value: [{ + name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'hashOid' + /* parameter block omitted, for SHA1 NULL anyhow. */ + }] + }] + }, { + name: 'rsapss.maskGenAlgorithm', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + value: [{ + name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.SEQUENCE, + constructed: true, + optional: true, + value: [{ + name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'maskGenOid' + }, { + name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'maskGenHashOid' + /* parameter block omitted, for SHA1 NULL anyhow. */ + }] + }] + }] + }, { + name: 'rsapss.saltLength', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 2, + optional: true, + value: [{ + name: 'rsapss.saltLength.saltLength', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.INTEGER, + constructed: false, + capture: 'saltLength' + }] + }, { + name: 'rsapss.trailerField', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 3, + optional: true, + value: [{ + name: 'rsapss.trailer.trailer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.INTEGER, + constructed: false, + capture: 'trailer' + }] + }] +}; + +// validator for a CertificationRequestInfo structure +var certificationRequestInfoValidator = { + name: 'CertificationRequestInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'certificationRequestInfo', + value: [{ + name: 'CertificationRequestInfo.integer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'certificationRequestInfoVersion' + }, { + // Name (subject) (RDNSequence) + name: 'CertificationRequestInfo.subject', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'certificationRequestInfoSubject' + }, + // SubjectPublicKeyInfo + publicKeyValidator, + { + name: 'CertificationRequestInfo.attributes', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + capture: 'certificationRequestInfoAttributes', + value: [{ + name: 'CertificationRequestInfo.attributes', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'CertificationRequestInfo.attributes.type', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false + }, { + name: 'CertificationRequestInfo.attributes.value', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true + }] + }] + }] +}; + +// validator for a CertificationRequest structure +var certificationRequestValidator = { + name: 'CertificationRequest', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'csr', + value: [ + certificationRequestInfoValidator, { + // AlgorithmIdentifier (signature algorithm) + name: 'CertificationRequest.signatureAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // algorithm + name: 'CertificationRequest.signatureAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'csrSignatureOid' + }, { + name: 'CertificationRequest.signatureAlgorithm.parameters', + tagClass: asn1.Class.UNIVERSAL, + optional: true, + captureAsn1: 'csrSignatureParams' + }] + }, { + // signature + name: 'CertificationRequest.signature', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + captureBitStringValue: 'csrSignature' + } + ] +}; + +/** + * Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName + * sets into an array with objects that have type and value properties. + * + * @param rdn the RDNSequence to convert. + * @param md a message digest to append type and value to if provided. + */ +pki.RDNAttributesAsArray = function(rdn, md) { + var rval = []; + + // each value in 'rdn' in is a SET of RelativeDistinguishedName + var set, attr, obj; + for(var si = 0; si < rdn.value.length; ++si) { + // get the RelativeDistinguishedName set + set = rdn.value[si]; + + // each value in the SET is an AttributeTypeAndValue sequence + // containing first a type (an OID) and second a value (defined by + // the OID) + for(var i = 0; i < set.value.length; ++i) { + obj = {}; + attr = set.value[i]; + obj.type = asn1.derToOid(attr.value[0].value); + obj.value = attr.value[1].value; + obj.valueTagClass = attr.value[1].type; + // if the OID is known, get its name and short name + if(obj.type in oids) { + obj.name = oids[obj.type]; + if(obj.name in _shortNames) { + obj.shortName = _shortNames[obj.name]; + } + } + if(md) { + md.update(obj.type); + md.update(obj.value); + } + rval.push(obj); + } + } + + return rval; +}; + +/** + * Converts ASN.1 CRIAttributes into an array with objects that have type and + * value properties. + * + * @param attributes the CRIAttributes to convert. + */ +pki.CRIAttributesAsArray = function(attributes) { + var rval = []; + + // each value in 'attributes' in is a SEQUENCE with an OID and a SET + for(var si = 0; si < attributes.length; ++si) { + // get the attribute sequence + var seq = attributes[si]; + + // each value in the SEQUENCE containing first a type (an OID) and + // second a set of values (defined by the OID) + var type = asn1.derToOid(seq.value[0].value); + var values = seq.value[1].value; + for(var vi = 0; vi < values.length; ++vi) { + var obj = {}; + obj.type = type; + obj.value = values[vi].value; + obj.valueTagClass = values[vi].type; + // if the OID is known, get its name and short name + if(obj.type in oids) { + obj.name = oids[obj.type]; + if(obj.name in _shortNames) { + obj.shortName = _shortNames[obj.name]; + } + } + // parse extensions + if(obj.type === oids.extensionRequest) { + obj.extensions = []; + for(var ei = 0; ei < obj.value.length; ++ei) { + obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei])); + } + } + rval.push(obj); + } + } + + return rval; +}; + +/** + * Gets an issuer or subject attribute from its name, type, or short name. + * + * @param obj the issuer or subject object. + * @param options a short name string or an object with: + * shortName the short name for the attribute. + * name the name for the attribute. + * type the type for the attribute. + * + * @return the attribute. + */ +function _getAttribute(obj, options) { + if(typeof options === 'string') { + options = {shortName: options}; + } + + var rval = null; + var attr; + for(var i = 0; rval === null && i < obj.attributes.length; ++i) { + attr = obj.attributes[i]; + if(options.type && options.type === attr.type) { + rval = attr; + } else if(options.name && options.name === attr.name) { + rval = attr; + } else if(options.shortName && options.shortName === attr.shortName) { + rval = attr; + } + } + return rval; +} + +/** + * Converts signature parameters from ASN.1 structure. + * + * Currently only RSASSA-PSS supported. The PKCS#1 v1.5 signature scheme had + * no parameters. + * + * RSASSA-PSS-params ::= SEQUENCE { + * hashAlgorithm [0] HashAlgorithm DEFAULT + * sha1Identifier, + * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT + * mgf1SHA1Identifier, + * saltLength [2] INTEGER DEFAULT 20, + * trailerField [3] INTEGER DEFAULT 1 + * } + * + * HashAlgorithm ::= AlgorithmIdentifier + * + * MaskGenAlgorithm ::= AlgorithmIdentifier + * + * AlgorithmIdentifer ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters ANY DEFINED BY algorithm OPTIONAL + * } + * + * @param oid The OID specifying the signature algorithm + * @param obj The ASN.1 structure holding the parameters + * @param fillDefaults Whether to use return default values where omitted + * @return signature parameter object + */ +var _readSignatureParameters = function(oid, obj, fillDefaults) { + var params = {}; + + if(oid !== oids['RSASSA-PSS']) { + return params; + } + + if(fillDefaults) { + params = { + hash: { + algorithmOid: oids['sha1'] + }, + mgf: { + algorithmOid: oids['mgf1'], + hash: { + algorithmOid: oids['sha1'] + } + }, + saltLength: 20 + }; + } + + var capture = {}; + var errors = []; + if(!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) { + var error = new Error('Cannot read RSASSA-PSS parameter block.'); + error.errors = errors; + throw error; + } + + if(capture.hashOid !== undefined) { + params.hash = params.hash || {}; + params.hash.algorithmOid = asn1.derToOid(capture.hashOid); + } + + if(capture.maskGenOid !== undefined) { + params.mgf = params.mgf || {}; + params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid); + params.mgf.hash = params.mgf.hash || {}; + params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid); + } + + if(capture.saltLength !== undefined) { + params.saltLength = capture.saltLength.charCodeAt(0); + } + + return params; +}; + +/** + * Create signature digest for OID. + * + * @param options + * signatureOid: the OID specifying the signature algorithm. + * type: a human readable type for error messages + * @return a created md instance. throws if unknown oid. + */ +var _createSignatureDigest = function(options) { + switch(oids[options.signatureOid]) { + case 'sha1WithRSAEncryption': + // deprecated alias + case 'sha1WithRSASignature': + return forge.md.sha1.create(); + case 'md5WithRSAEncryption': + return forge.md.md5.create(); + case 'sha256WithRSAEncryption': + return forge.md.sha256.create(); + case 'sha384WithRSAEncryption': + return forge.md.sha384.create(); + case 'sha512WithRSAEncryption': + return forge.md.sha512.create(); + case 'RSASSA-PSS': + return forge.md.sha256.create(); + default: + var error = new Error( + 'Could not compute ' + options.type + ' digest. ' + + 'Unknown signature OID.'); + error.signatureOid = options.signatureOid; + throw error; + } +}; + +/** + * Verify signature on certificate or CSR. + * + * @param options: + * certificate the certificate or CSR to verify. + * md the signature digest. + * signature the signature + * @return a created md instance. throws if unknown oid. + */ +var _verifySignature = function(options) { + var cert = options.certificate; + var scheme; + + switch(cert.signatureOid) { + case oids.sha1WithRSAEncryption: + // deprecated alias + case oids.sha1WithRSASignature: + /* use PKCS#1 v1.5 padding scheme */ + break; + case oids['RSASSA-PSS']: + var hash, mgf; + + /* initialize mgf */ + hash = oids[cert.signatureParameters.mgf.hash.algorithmOid]; + if(hash === undefined || forge.md[hash] === undefined) { + var error = new Error('Unsupported MGF hash function.'); + error.oid = cert.signatureParameters.mgf.hash.algorithmOid; + error.name = hash; + throw error; + } + + mgf = oids[cert.signatureParameters.mgf.algorithmOid]; + if(mgf === undefined || forge.mgf[mgf] === undefined) { + var error = new Error('Unsupported MGF function.'); + error.oid = cert.signatureParameters.mgf.algorithmOid; + error.name = mgf; + throw error; + } + + mgf = forge.mgf[mgf].create(forge.md[hash].create()); + + /* initialize hash function */ + hash = oids[cert.signatureParameters.hash.algorithmOid]; + if(hash === undefined || forge.md[hash] === undefined) { + var error = new Error('Unsupported RSASSA-PSS hash function.'); + error.oid = cert.signatureParameters.hash.algorithmOid; + error.name = hash; + throw error; + } + + scheme = forge.pss.create( + forge.md[hash].create(), mgf, cert.signatureParameters.saltLength + ); + break; + } + + // verify signature on cert using public key + return cert.publicKey.verify( + options.md.digest().getBytes(), options.signature, scheme + ); +}; + +/** + * Converts an X.509 certificate from PEM format. + * + * Note: If the certificate is to be verified then compute hash should + * be set to true. This will scan the TBSCertificate part of the ASN.1 + * object while it is converted so it doesn't need to be converted back + * to ASN.1-DER-encoding later. + * + * @param pem the PEM-formatted certificate. + * @param computeHash true to compute the hash for verification. + * @param strict true to be strict when checking ASN.1 value lengths, false to + * allow truncated values (default: true). + * + * @return the certificate. + */ +pki.certificateFromPem = function(pem, computeHash, strict) { + var msg = forge.pem.decode(pem)[0]; + + if(msg.type !== 'CERTIFICATE' && + msg.type !== 'X509 CERTIFICATE' && + msg.type !== 'TRUSTED CERTIFICATE') { + var error = new Error( + 'Could not convert certificate from PEM; PEM header type ' + + 'is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error( + 'Could not convert certificate from PEM; PEM is encrypted.'); + } + + // convert DER to ASN.1 object + var obj = asn1.fromDer(msg.body, strict); + + return pki.certificateFromAsn1(obj, computeHash); +}; + +/** + * Converts an X.509 certificate to PEM format. + * + * @param cert the certificate. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted certificate. + */ +pki.certificateToPem = function(cert, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var msg = { + type: 'CERTIFICATE', + body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; + +/** + * Converts an RSA public key from PEM format. + * + * @param pem the PEM-formatted public key. + * + * @return the public key. + */ +pki.publicKeyFromPem = function(pem) { + var msg = forge.pem.decode(pem)[0]; + + if(msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') { + var error = new Error('Could not convert public key from PEM; PEM header ' + + 'type is not "PUBLIC KEY" or "RSA PUBLIC KEY".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert public key from PEM; PEM is encrypted.'); + } + + // convert DER to ASN.1 object + var obj = asn1.fromDer(msg.body); + + return pki.publicKeyFromAsn1(obj); +}; + +/** + * Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo). + * + * @param key the public key. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted public key. + */ +pki.publicKeyToPem = function(key, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var msg = { + type: 'PUBLIC KEY', + body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; + +/** + * Converts an RSA public key to PEM format (using an RSAPublicKey). + * + * @param key the public key. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted public key. + */ +pki.publicKeyToRSAPublicKeyPem = function(key, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var msg = { + type: 'RSA PUBLIC KEY', + body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; + +/** + * Gets a fingerprint for the given public key. + * + * @param options the options to use. + * [md] the message digest object to use (defaults to forge.md.sha1). + * [type] the type of fingerprint, such as 'RSAPublicKey', + * 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey'). + * [encoding] an alternative output encoding, such as 'hex' + * (defaults to none, outputs a byte buffer). + * [delimiter] the delimiter to use between bytes for 'hex' encoded + * output, eg: ':' (defaults to none). + * + * @return the fingerprint as a byte buffer or other encoding based on options. + */ +pki.getPublicKeyFingerprint = function(key, options) { + options = options || {}; + var md = options.md || forge.md.sha1.create(); + var type = options.type || 'RSAPublicKey'; + + var bytes; + switch(type) { + case 'RSAPublicKey': + bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes(); + break; + case 'SubjectPublicKeyInfo': + bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes(); + break; + default: + throw new Error('Unknown fingerprint type "' + options.type + '".'); + } + + // hash public key bytes + md.start(); + md.update(bytes); + var digest = md.digest(); + if(options.encoding === 'hex') { + var hex = digest.toHex(); + if(options.delimiter) { + return hex.match(/.{2}/g).join(options.delimiter); + } + return hex; + } else if(options.encoding === 'binary') { + return digest.getBytes(); + } else if(options.encoding) { + throw new Error('Unknown encoding "' + options.encoding + '".'); + } + return digest; +}; + +/** + * Converts a PKCS#10 certification request (CSR) from PEM format. + * + * Note: If the certification request is to be verified then compute hash + * should be set to true. This will scan the CertificationRequestInfo part of + * the ASN.1 object while it is converted so it doesn't need to be converted + * back to ASN.1-DER-encoding later. + * + * @param pem the PEM-formatted certificate. + * @param computeHash true to compute the hash for verification. + * @param strict true to be strict when checking ASN.1 value lengths, false to + * allow truncated values (default: true). + * + * @return the certification request (CSR). + */ +pki.certificationRequestFromPem = function(pem, computeHash, strict) { + var msg = forge.pem.decode(pem)[0]; + + if(msg.type !== 'CERTIFICATE REQUEST') { + var error = new Error('Could not convert certification request from PEM; ' + + 'PEM header type is not "CERTIFICATE REQUEST".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert certification request from PEM; ' + + 'PEM is encrypted.'); + } + + // convert DER to ASN.1 object + var obj = asn1.fromDer(msg.body, strict); + + return pki.certificationRequestFromAsn1(obj, computeHash); +}; + +/** + * Converts a PKCS#10 certification request (CSR) to PEM format. + * + * @param csr the certification request. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted certification request. + */ +pki.certificationRequestToPem = function(csr, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var msg = { + type: 'CERTIFICATE REQUEST', + body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; + +/** + * Creates an empty X.509v3 RSA certificate. + * + * @return the certificate. + */ +pki.createCertificate = function() { + var cert = {}; + cert.version = 0x02; + cert.serialNumber = '00'; + cert.signatureOid = null; + cert.signature = null; + cert.siginfo = {}; + cert.siginfo.algorithmOid = null; + cert.validity = {}; + cert.validity.notBefore = new Date(); + cert.validity.notAfter = new Date(); + + cert.issuer = {}; + cert.issuer.getField = function(sn) { + return _getAttribute(cert.issuer, sn); + }; + cert.issuer.addField = function(attr) { + _fillMissingFields([attr]); + cert.issuer.attributes.push(attr); + }; + cert.issuer.attributes = []; + cert.issuer.hash = null; + + cert.subject = {}; + cert.subject.getField = function(sn) { + return _getAttribute(cert.subject, sn); + }; + cert.subject.addField = function(attr) { + _fillMissingFields([attr]); + cert.subject.attributes.push(attr); + }; + cert.subject.attributes = []; + cert.subject.hash = null; + + cert.extensions = []; + cert.publicKey = null; + cert.md = null; + + /** + * Sets the subject of this certificate. + * + * @param attrs the array of subject attributes to use. + * @param uniqueId an optional a unique ID to use. + */ + cert.setSubject = function(attrs, uniqueId) { + // set new attributes, clear hash + _fillMissingFields(attrs); + cert.subject.attributes = attrs; + delete cert.subject.uniqueId; + if(uniqueId) { + // TODO: support arbitrary bit length ids + cert.subject.uniqueId = uniqueId; + } + cert.subject.hash = null; + }; + + /** + * Sets the issuer of this certificate. + * + * @param attrs the array of issuer attributes to use. + * @param uniqueId an optional a unique ID to use. + */ + cert.setIssuer = function(attrs, uniqueId) { + // set new attributes, clear hash + _fillMissingFields(attrs); + cert.issuer.attributes = attrs; + delete cert.issuer.uniqueId; + if(uniqueId) { + // TODO: support arbitrary bit length ids + cert.issuer.uniqueId = uniqueId; + } + cert.issuer.hash = null; + }; + + /** + * Sets the extensions of this certificate. + * + * @param exts the array of extensions to use. + */ + cert.setExtensions = function(exts) { + for(var i = 0; i < exts.length; ++i) { + _fillMissingExtensionFields(exts[i], {cert: cert}); + } + // set new extensions + cert.extensions = exts; + }; + + /** + * Gets an extension by its name or id. + * + * @param options the name to use or an object with: + * name the name to use. + * id the id to use. + * + * @return the extension or null if not found. + */ + cert.getExtension = function(options) { + if(typeof options === 'string') { + options = {name: options}; + } + + var rval = null; + var ext; + for(var i = 0; rval === null && i < cert.extensions.length; ++i) { + ext = cert.extensions[i]; + if(options.id && ext.id === options.id) { + rval = ext; + } else if(options.name && ext.name === options.name) { + rval = ext; + } + } + return rval; + }; + + /** + * Signs this certificate using the given private key. + * + * @param key the private key to sign with. + * @param md the message digest object to use (defaults to forge.md.sha1). + */ + cert.sign = function(key, md) { + // TODO: get signature OID from private key + cert.md = md || forge.md.sha1.create(); + var algorithmOid = oids[cert.md.algorithm + 'WithRSAEncryption']; + if(!algorithmOid) { + var error = new Error('Could not compute certificate digest. ' + + 'Unknown message digest algorithm OID.'); + error.algorithm = cert.md.algorithm; + throw error; + } + cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid; + + // get TBSCertificate, convert to DER + cert.tbsCertificate = pki.getTBSCertificate(cert); + var bytes = asn1.toDer(cert.tbsCertificate); + + // digest and sign + cert.md.update(bytes.getBytes()); + cert.signature = key.sign(cert.md); + }; + + /** + * Attempts verify the signature on the passed certificate using this + * certificate's public key. + * + * @param child the certificate to verify. + * + * @return true if verified, false if not. + */ + cert.verify = function(child) { + var rval = false; + + if(!cert.issued(child)) { + var issuer = child.issuer; + var subject = cert.subject; + var error = new Error( + 'The parent certificate did not issue the given child ' + + 'certificate; the child certificate\'s issuer does not match the ' + + 'parent\'s subject.'); + error.expectedIssuer = subject.attributes; + error.actualIssuer = issuer.attributes; + throw error; + } + + var md = child.md; + if(md === null) { + // create digest for OID signature types + md = _createSignatureDigest({ + signatureOid: child.signatureOid, + type: 'certificate' + }); + + // produce DER formatted TBSCertificate and digest it + var tbsCertificate = child.tbsCertificate || pki.getTBSCertificate(child); + var bytes = asn1.toDer(tbsCertificate); + md.update(bytes.getBytes()); + } + + if(md !== null) { + rval = _verifySignature({ + certificate: cert, md: md, signature: child.signature + }); + } + + return rval; + }; + + /** + * Returns true if this certificate's issuer matches the passed + * certificate's subject. Note that no signature check is performed. + * + * @param parent the certificate to check. + * + * @return true if this certificate's issuer matches the passed certificate's + * subject. + */ + cert.isIssuer = function(parent) { + var rval = false; + + var i = cert.issuer; + var s = parent.subject; + + // compare hashes if present + if(i.hash && s.hash) { + rval = (i.hash === s.hash); + } else if(i.attributes.length === s.attributes.length) { + // all attributes are the same so issuer matches subject + rval = true; + var iattr, sattr; + for(var n = 0; rval && n < i.attributes.length; ++n) { + iattr = i.attributes[n]; + sattr = s.attributes[n]; + if(iattr.type !== sattr.type || iattr.value !== sattr.value) { + // attribute mismatch + rval = false; + } + } + } + + return rval; + }; + + /** + * Returns true if this certificate's subject matches the issuer of the + * given certificate). Note that not signature check is performed. + * + * @param child the certificate to check. + * + * @return true if this certificate's subject matches the passed + * certificate's issuer. + */ + cert.issued = function(child) { + return child.isIssuer(cert); + }; + + /** + * Generates the subjectKeyIdentifier for this certificate as byte buffer. + * + * @return the subjectKeyIdentifier for this certificate as byte buffer. + */ + cert.generateSubjectKeyIdentifier = function() { + /* See: 4.2.1.2 section of the the RFC3280, keyIdentifier is either: + + (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the + value of the BIT STRING subjectPublicKey (excluding the tag, + length, and number of unused bits). + + (2) The keyIdentifier is composed of a four bit type field with + the value 0100 followed by the least significant 60 bits of the + SHA-1 hash of the value of the BIT STRING subjectPublicKey + (excluding the tag, length, and number of unused bit string bits). + */ + + // skipping the tag, length, and number of unused bits is the same + // as just using the RSAPublicKey (for RSA keys, which are the + // only ones supported) + return pki.getPublicKeyFingerprint(cert.publicKey, {type: 'RSAPublicKey'}); + }; + + /** + * Verifies the subjectKeyIdentifier extension value for this certificate + * against its public key. If no extension is found, false will be + * returned. + * + * @return true if verified, false if not. + */ + cert.verifySubjectKeyIdentifier = function() { + var oid = oids['subjectKeyIdentifier']; + for(var i = 0; i < cert.extensions.length; ++i) { + var ext = cert.extensions[i]; + if(ext.id === oid) { + var ski = cert.generateSubjectKeyIdentifier().getBytes(); + return (forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski); + } + } + return false; + }; + + return cert; +}; + +/** + * Converts an X.509v3 RSA certificate from an ASN.1 object. + * + * Note: If the certificate is to be verified then compute hash should + * be set to true. There is currently no implementation for converting + * a certificate back to ASN.1 so the TBSCertificate part of the ASN.1 + * object needs to be scanned before the cert object is created. + * + * @param obj the asn1 representation of an X.509v3 RSA certificate. + * @param computeHash true to compute the hash for verification. + * + * @return the certificate. + */ +pki.certificateFromAsn1 = function(obj, computeHash) { + // validate certificate and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(obj, x509CertificateValidator, capture, errors)) { + var error = new Error('Cannot read X.509 certificate. ' + + 'ASN.1 object is not an X509v3 Certificate.'); + error.errors = errors; + throw error; + } + + // get oid + var oid = asn1.derToOid(capture.publicKeyOid); + if(oid !== pki.oids.rsaEncryption) { + throw new Error('Cannot read public key. OID is not RSA.'); + } + + // create certificate + var cert = pki.createCertificate(); + cert.version = capture.certVersion ? + capture.certVersion.charCodeAt(0) : 0; + var serial = forge.util.createBuffer(capture.certSerialNumber); + cert.serialNumber = serial.toHex(); + cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid); + cert.signatureParameters = _readSignatureParameters( + cert.signatureOid, capture.certSignatureParams, true); + cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid); + cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid, + capture.certinfoSignatureParams, false); + cert.signature = capture.certSignature; + + var validity = []; + if(capture.certValidity1UTCTime !== undefined) { + validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime)); + } + if(capture.certValidity2GeneralizedTime !== undefined) { + validity.push(asn1.generalizedTimeToDate( + capture.certValidity2GeneralizedTime)); + } + if(capture.certValidity3UTCTime !== undefined) { + validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime)); + } + if(capture.certValidity4GeneralizedTime !== undefined) { + validity.push(asn1.generalizedTimeToDate( + capture.certValidity4GeneralizedTime)); + } + if(validity.length > 2) { + throw new Error('Cannot read notBefore/notAfter validity times; more ' + + 'than two times were provided in the certificate.'); + } + if(validity.length < 2) { + throw new Error('Cannot read notBefore/notAfter validity times; they ' + + 'were not provided as either UTCTime or GeneralizedTime.'); + } + cert.validity.notBefore = validity[0]; + cert.validity.notAfter = validity[1]; + + // keep TBSCertificate to preserve signature when exporting + cert.tbsCertificate = capture.tbsCertificate; + + if(computeHash) { + // create digest for OID signature type + cert.md = _createSignatureDigest({ + signatureOid: cert.signatureOid, + type: 'certificate' + }); + + // produce DER formatted TBSCertificate and digest it + var bytes = asn1.toDer(cert.tbsCertificate); + cert.md.update(bytes.getBytes()); + } + + // handle issuer, build issuer message digest + var imd = forge.md.sha1.create(); + var ibytes = asn1.toDer(capture.certIssuer); + imd.update(ibytes.getBytes()); + cert.issuer.getField = function(sn) { + return _getAttribute(cert.issuer, sn); + }; + cert.issuer.addField = function(attr) { + _fillMissingFields([attr]); + cert.issuer.attributes.push(attr); + }; + cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer); + if(capture.certIssuerUniqueId) { + cert.issuer.uniqueId = capture.certIssuerUniqueId; + } + cert.issuer.hash = imd.digest().toHex(); + + // handle subject, build subject message digest + var smd = forge.md.sha1.create(); + var sbytes = asn1.toDer(capture.certSubject); + smd.update(sbytes.getBytes()); + cert.subject.getField = function(sn) { + return _getAttribute(cert.subject, sn); + }; + cert.subject.addField = function(attr) { + _fillMissingFields([attr]); + cert.subject.attributes.push(attr); + }; + cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject); + if(capture.certSubjectUniqueId) { + cert.subject.uniqueId = capture.certSubjectUniqueId; + } + cert.subject.hash = smd.digest().toHex(); + + // handle extensions + if(capture.certExtensions) { + cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions); + } else { + cert.extensions = []; + } + + // convert RSA public key from ASN.1 + cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo); + + return cert; +}; + +/** + * Converts an ASN.1 extensions object (with extension sequences as its + * values) into an array of extension objects with types and values. + * + * Supported extensions: + * + * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 } + * KeyUsage ::= BIT STRING { + * digitalSignature (0), + * nonRepudiation (1), + * keyEncipherment (2), + * dataEncipherment (3), + * keyAgreement (4), + * keyCertSign (5), + * cRLSign (6), + * encipherOnly (7), + * decipherOnly (8) + * } + * + * id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 } + * BasicConstraints ::= SEQUENCE { + * cA BOOLEAN DEFAULT FALSE, + * pathLenConstraint INTEGER (0..MAX) OPTIONAL + * } + * + * subjectAltName EXTENSION ::= { + * SYNTAX GeneralNames + * IDENTIFIED BY id-ce-subjectAltName + * } + * + * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName + * + * GeneralName ::= CHOICE { + * otherName [0] INSTANCE OF OTHER-NAME, + * rfc822Name [1] IA5String, + * dNSName [2] IA5String, + * x400Address [3] ORAddress, + * directoryName [4] Name, + * ediPartyName [5] EDIPartyName, + * uniformResourceIdentifier [6] IA5String, + * IPAddress [7] OCTET STRING, + * registeredID [8] OBJECT IDENTIFIER + * } + * + * OTHER-NAME ::= TYPE-IDENTIFIER + * + * EDIPartyName ::= SEQUENCE { + * nameAssigner [0] DirectoryString {ub-name} OPTIONAL, + * partyName [1] DirectoryString {ub-name} + * } + * + * @param exts the extensions ASN.1 with extension sequences to parse. + * + * @return the array. + */ +pki.certificateExtensionsFromAsn1 = function(exts) { + var rval = []; + for(var i = 0; i < exts.value.length; ++i) { + // get extension sequence + var extseq = exts.value[i]; + for(var ei = 0; ei < extseq.value.length; ++ei) { + rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei])); + } + } + + return rval; +}; + +/** + * Parses a single certificate extension from ASN.1. + * + * @param ext the extension in ASN.1 format. + * + * @return the parsed extension as an object. + */ +pki.certificateExtensionFromAsn1 = function(ext) { + // an extension has: + // [0] extnID OBJECT IDENTIFIER + // [1] critical BOOLEAN DEFAULT FALSE + // [2] extnValue OCTET STRING + var e = {}; + e.id = asn1.derToOid(ext.value[0].value); + e.critical = false; + if(ext.value[1].type === asn1.Type.BOOLEAN) { + e.critical = (ext.value[1].value.charCodeAt(0) !== 0x00); + e.value = ext.value[2].value; + } else { + e.value = ext.value[1].value; + } + // if the oid is known, get its name + if(e.id in oids) { + e.name = oids[e.id]; + + // handle key usage + if(e.name === 'keyUsage') { + // get value as BIT STRING + var ev = asn1.fromDer(e.value); + var b2 = 0x00; + var b3 = 0x00; + if(ev.value.length > 1) { + // skip first byte, just indicates unused bits which + // will be padded with 0s anyway + // get bytes with flag bits + b2 = ev.value.charCodeAt(1); + b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0; + } + // set flags + e.digitalSignature = (b2 & 0x80) === 0x80; + e.nonRepudiation = (b2 & 0x40) === 0x40; + e.keyEncipherment = (b2 & 0x20) === 0x20; + e.dataEncipherment = (b2 & 0x10) === 0x10; + e.keyAgreement = (b2 & 0x08) === 0x08; + e.keyCertSign = (b2 & 0x04) === 0x04; + e.cRLSign = (b2 & 0x02) === 0x02; + e.encipherOnly = (b2 & 0x01) === 0x01; + e.decipherOnly = (b3 & 0x80) === 0x80; + } else if(e.name === 'basicConstraints') { + // handle basic constraints + // get value as SEQUENCE + var ev = asn1.fromDer(e.value); + // get cA BOOLEAN flag (defaults to false) + if(ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) { + e.cA = (ev.value[0].value.charCodeAt(0) !== 0x00); + } else { + e.cA = false; + } + // get path length constraint + var value = null; + if(ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) { + value = ev.value[0].value; + } else if(ev.value.length > 1) { + value = ev.value[1].value; + } + if(value !== null) { + e.pathLenConstraint = asn1.derToInteger(value); + } + } else if(e.name === 'extKeyUsage') { + // handle extKeyUsage + // value is a SEQUENCE of OIDs + var ev = asn1.fromDer(e.value); + for(var vi = 0; vi < ev.value.length; ++vi) { + var oid = asn1.derToOid(ev.value[vi].value); + if(oid in oids) { + e[oids[oid]] = true; + } else { + e[oid] = true; + } + } + } else if(e.name === 'nsCertType') { + // handle nsCertType + // get value as BIT STRING + var ev = asn1.fromDer(e.value); + var b2 = 0x00; + if(ev.value.length > 1) { + // skip first byte, just indicates unused bits which + // will be padded with 0s anyway + // get bytes with flag bits + b2 = ev.value.charCodeAt(1); + } + // set flags + e.client = (b2 & 0x80) === 0x80; + e.server = (b2 & 0x40) === 0x40; + e.email = (b2 & 0x20) === 0x20; + e.objsign = (b2 & 0x10) === 0x10; + e.reserved = (b2 & 0x08) === 0x08; + e.sslCA = (b2 & 0x04) === 0x04; + e.emailCA = (b2 & 0x02) === 0x02; + e.objCA = (b2 & 0x01) === 0x01; + } else if( + e.name === 'subjectAltName' || + e.name === 'issuerAltName') { + // handle subjectAltName/issuerAltName + e.altNames = []; + + // ev is a SYNTAX SEQUENCE + var gn; + var ev = asn1.fromDer(e.value); + for(var n = 0; n < ev.value.length; ++n) { + // get GeneralName + gn = ev.value[n]; + + var altName = { + type: gn.type, + value: gn.value + }; + e.altNames.push(altName); + + // Note: Support for types 1,2,6,7,8 + switch(gn.type) { + // rfc822Name + case 1: + // dNSName + case 2: + // uniformResourceIdentifier (URI) + case 6: + break; + // IPAddress + case 7: + // convert to IPv4/IPv6 string representation + altName.ip = forge.util.bytesToIP(gn.value); + break; + // registeredID + case 8: + altName.oid = asn1.derToOid(gn.value); + break; + default: + // unsupported + } + } + } else if(e.name === 'subjectKeyIdentifier') { + // value is an OCTETSTRING w/the hash of the key-type specific + // public key structure (eg: RSAPublicKey) + var ev = asn1.fromDer(e.value); + e.subjectKeyIdentifier = forge.util.bytesToHex(ev.value); + } + } + return e; +}; + +/** + * Converts a PKCS#10 certification request (CSR) from an ASN.1 object. + * + * Note: If the certification request is to be verified then compute hash + * should be set to true. There is currently no implementation for converting + * a certificate back to ASN.1 so the CertificationRequestInfo part of the + * ASN.1 object needs to be scanned before the csr object is created. + * + * @param obj the asn1 representation of a PKCS#10 certification request (CSR). + * @param computeHash true to compute the hash for verification. + * + * @return the certification request (CSR). + */ +pki.certificationRequestFromAsn1 = function(obj, computeHash) { + // validate certification request and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(obj, certificationRequestValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#10 certificate request. ' + + 'ASN.1 object is not a PKCS#10 CertificationRequest.'); + error.errors = errors; + throw error; + } + + // get oid + var oid = asn1.derToOid(capture.publicKeyOid); + if(oid !== pki.oids.rsaEncryption) { + throw new Error('Cannot read public key. OID is not RSA.'); + } + + // create certification request + var csr = pki.createCertificationRequest(); + csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0; + csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid); + csr.signatureParameters = _readSignatureParameters( + csr.signatureOid, capture.csrSignatureParams, true); + csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid); + csr.siginfo.parameters = _readSignatureParameters( + csr.siginfo.algorithmOid, capture.csrSignatureParams, false); + csr.signature = capture.csrSignature; + + // keep CertificationRequestInfo to preserve signature when exporting + csr.certificationRequestInfo = capture.certificationRequestInfo; + + if(computeHash) { + // create digest for OID signature type + csr.md = _createSignatureDigest({ + signatureOid: csr.signatureOid, + type: 'certification request' + }); + + // produce DER formatted CertificationRequestInfo and digest it + var bytes = asn1.toDer(csr.certificationRequestInfo); + csr.md.update(bytes.getBytes()); + } + + // handle subject, build subject message digest + var smd = forge.md.sha1.create(); + csr.subject.getField = function(sn) { + return _getAttribute(csr.subject, sn); + }; + csr.subject.addField = function(attr) { + _fillMissingFields([attr]); + csr.subject.attributes.push(attr); + }; + csr.subject.attributes = pki.RDNAttributesAsArray( + capture.certificationRequestInfoSubject, smd); + csr.subject.hash = smd.digest().toHex(); + + // convert RSA public key from ASN.1 + csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo); + + // convert attributes from ASN.1 + csr.getAttribute = function(sn) { + return _getAttribute(csr, sn); + }; + csr.addAttribute = function(attr) { + _fillMissingFields([attr]); + csr.attributes.push(attr); + }; + csr.attributes = pki.CRIAttributesAsArray( + capture.certificationRequestInfoAttributes || []); + + return csr; +}; + +/** + * Creates an empty certification request (a CSR or certificate signing + * request). Once created, its public key and attributes can be set and then + * it can be signed. + * + * @return the empty certification request. + */ +pki.createCertificationRequest = function() { + var csr = {}; + csr.version = 0x00; + csr.signatureOid = null; + csr.signature = null; + csr.siginfo = {}; + csr.siginfo.algorithmOid = null; + + csr.subject = {}; + csr.subject.getField = function(sn) { + return _getAttribute(csr.subject, sn); + }; + csr.subject.addField = function(attr) { + _fillMissingFields([attr]); + csr.subject.attributes.push(attr); + }; + csr.subject.attributes = []; + csr.subject.hash = null; + + csr.publicKey = null; + csr.attributes = []; + csr.getAttribute = function(sn) { + return _getAttribute(csr, sn); + }; + csr.addAttribute = function(attr) { + _fillMissingFields([attr]); + csr.attributes.push(attr); + }; + csr.md = null; + + /** + * Sets the subject of this certification request. + * + * @param attrs the array of subject attributes to use. + */ + csr.setSubject = function(attrs) { + // set new attributes + _fillMissingFields(attrs); + csr.subject.attributes = attrs; + csr.subject.hash = null; + }; + + /** + * Sets the attributes of this certification request. + * + * @param attrs the array of attributes to use. + */ + csr.setAttributes = function(attrs) { + // set new attributes + _fillMissingFields(attrs); + csr.attributes = attrs; + }; + + /** + * Signs this certification request using the given private key. + * + * @param key the private key to sign with. + * @param md the message digest object to use (defaults to forge.md.sha1). + */ + csr.sign = function(key, md) { + // TODO: get signature OID from private key + csr.md = md || forge.md.sha1.create(); + var algorithmOid = oids[csr.md.algorithm + 'WithRSAEncryption']; + if(!algorithmOid) { + var error = new Error('Could not compute certification request digest. ' + + 'Unknown message digest algorithm OID.'); + error.algorithm = csr.md.algorithm; + throw error; + } + csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid; + + // get CertificationRequestInfo, convert to DER + csr.certificationRequestInfo = pki.getCertificationRequestInfo(csr); + var bytes = asn1.toDer(csr.certificationRequestInfo); + + // digest and sign + csr.md.update(bytes.getBytes()); + csr.signature = key.sign(csr.md); + }; + + /** + * Attempts verify the signature on the passed certification request using + * its public key. + * + * A CSR that has been exported to a file in PEM format can be verified using + * OpenSSL using this command: + * + * openssl req -in -verify -noout -text + * + * @return true if verified, false if not. + */ + csr.verify = function() { + var rval = false; + + var md = csr.md; + if(md === null) { + md = _createSignatureDigest({ + signatureOid: csr.signatureOid, + type: 'certification request' + }); + + // produce DER formatted CertificationRequestInfo and digest it + var cri = csr.certificationRequestInfo || + pki.getCertificationRequestInfo(csr); + var bytes = asn1.toDer(cri); + md.update(bytes.getBytes()); + } + + if(md !== null) { + rval = _verifySignature({ + certificate: csr, md: md, signature: csr.signature + }); + } + + return rval; + }; + + return csr; +}; + +/** + * Converts an X.509 subject or issuer to an ASN.1 RDNSequence. + * + * @param obj the subject or issuer (distinguished name). + * + * @return the ASN.1 RDNSequence. + */ +function _dnToAsn1(obj) { + // create an empty RDNSequence + var rval = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + + // iterate over attributes + var attr, set; + var attrs = obj.attributes; + for(var i = 0; i < attrs.length; ++i) { + attr = attrs[i]; + var value = attr.value; + + // reuse tag class for attribute value if available + var valueTagClass = asn1.Type.PRINTABLESTRING; + if('valueTagClass' in attr) { + valueTagClass = attr.valueTagClass; + + if(valueTagClass === asn1.Type.UTF8) { + value = forge.util.encodeUtf8(value); + } + // FIXME: handle more encodings + } + + // create a RelativeDistinguishedName set + // each value in the set is an AttributeTypeAndValue first + // containing the type (an OID) and second the value + set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AttributeType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(attr.type).getBytes()), + // AttributeValue + asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value) + ]) + ]); + rval.value.push(set); + } + + return rval; +} + +/** + * Gets all printable attributes (typically of an issuer or subject) in a + * simplified JSON format for display. + * + * @param attrs the attributes. + * + * @return the JSON for display. + */ +function _getAttributesAsJson(attrs) { + var rval = {}; + for(var i = 0; i < attrs.length; ++i) { + var attr = attrs[i]; + if(attr.shortName && ( + attr.valueTagClass === asn1.Type.UTF8 || + attr.valueTagClass === asn1.Type.PRINTABLESTRING || + attr.valueTagClass === asn1.Type.IA5STRING)) { + var value = attr.value; + if(attr.valueTagClass === asn1.Type.UTF8) { + value = forge.util.encodeUtf8(attr.value); + } + if(!(attr.shortName in rval)) { + rval[attr.shortName] = value; + } else if(forge.util.isArray(rval[attr.shortName])) { + rval[attr.shortName].push(value); + } else { + rval[attr.shortName] = [rval[attr.shortName], value]; + } + } + } + return rval; +} + +/** + * Fills in missing fields in attributes. + * + * @param attrs the attributes to fill missing fields in. + */ +function _fillMissingFields(attrs) { + var attr; + for(var i = 0; i < attrs.length; ++i) { + attr = attrs[i]; + + // populate missing name + if(typeof attr.name === 'undefined') { + if(attr.type && attr.type in pki.oids) { + attr.name = pki.oids[attr.type]; + } else if(attr.shortName && attr.shortName in _shortNames) { + attr.name = pki.oids[_shortNames[attr.shortName]]; + } + } + + // populate missing type (OID) + if(typeof attr.type === 'undefined') { + if(attr.name && attr.name in pki.oids) { + attr.type = pki.oids[attr.name]; + } else { + var error = new Error('Attribute type not specified.'); + error.attribute = attr; + throw error; + } + } + + // populate missing shortname + if(typeof attr.shortName === 'undefined') { + if(attr.name && attr.name in _shortNames) { + attr.shortName = _shortNames[attr.name]; + } + } + + // convert extensions to value + if(attr.type === oids.extensionRequest) { + attr.valueConstructed = true; + attr.valueTagClass = asn1.Type.SEQUENCE; + if(!attr.value && attr.extensions) { + attr.value = []; + for(var ei = 0; ei < attr.extensions.length; ++ei) { + attr.value.push(pki.certificateExtensionToAsn1( + _fillMissingExtensionFields(attr.extensions[ei]))); + } + } + } + + if(typeof attr.value === 'undefined') { + var error = new Error('Attribute value not specified.'); + error.attribute = attr; + throw error; + } + } +} + +/** + * Fills in missing fields in certificate extensions. + * + * @param e the extension. + * @param [options] the options to use. + * [cert] the certificate the extensions are for. + * + * @return the extension. + */ +function _fillMissingExtensionFields(e, options) { + options = options || {}; + + // populate missing name + if(typeof e.name === 'undefined') { + if(e.id && e.id in pki.oids) { + e.name = pki.oids[e.id]; + } + } + + // populate missing id + if(typeof e.id === 'undefined') { + if(e.name && e.name in pki.oids) { + e.id = pki.oids[e.name]; + } else { + var error = new Error('Extension ID not specified.'); + error.extension = e; + throw error; + } + } + + if(typeof e.value !== 'undefined') { + return e; + } + + // handle missing value: + + // value is a BIT STRING + if(e.name === 'keyUsage') { + // build flags + var unused = 0; + var b2 = 0x00; + var b3 = 0x00; + if(e.digitalSignature) { + b2 |= 0x80; + unused = 7; + } + if(e.nonRepudiation) { + b2 |= 0x40; + unused = 6; + } + if(e.keyEncipherment) { + b2 |= 0x20; + unused = 5; + } + if(e.dataEncipherment) { + b2 |= 0x10; + unused = 4; + } + if(e.keyAgreement) { + b2 |= 0x08; + unused = 3; + } + if(e.keyCertSign) { + b2 |= 0x04; + unused = 2; + } + if(e.cRLSign) { + b2 |= 0x02; + unused = 1; + } + if(e.encipherOnly) { + b2 |= 0x01; + unused = 0; + } + if(e.decipherOnly) { + b3 |= 0x80; + unused = 7; + } + + // create bit string + var value = String.fromCharCode(unused); + if(b3 !== 0) { + value += String.fromCharCode(b2) + String.fromCharCode(b3); + } else if(b2 !== 0) { + value += String.fromCharCode(b2); + } + e.value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value); + } else if(e.name === 'basicConstraints') { + // basicConstraints is a SEQUENCE + e.value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + // cA BOOLEAN flag defaults to false + if(e.cA) { + e.value.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false, + String.fromCharCode(0xFF))); + } + if('pathLenConstraint' in e) { + e.value.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(e.pathLenConstraint).getBytes())); + } + } else if(e.name === 'extKeyUsage') { + // extKeyUsage is a SEQUENCE of OIDs + e.value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var seq = e.value.value; + for(var key in e) { + if(e[key] !== true) { + continue; + } + // key is name in OID map + if(key in oids) { + seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, + false, asn1.oidToDer(oids[key]).getBytes())); + } else if(key.indexOf('.') !== -1) { + // assume key is an OID + seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, + false, asn1.oidToDer(key).getBytes())); + } + } + } else if(e.name === 'nsCertType') { + // nsCertType is a BIT STRING + // build flags + var unused = 0; + var b2 = 0x00; + + if(e.client) { + b2 |= 0x80; + unused = 7; + } + if(e.server) { + b2 |= 0x40; + unused = 6; + } + if(e.email) { + b2 |= 0x20; + unused = 5; + } + if(e.objsign) { + b2 |= 0x10; + unused = 4; + } + if(e.reserved) { + b2 |= 0x08; + unused = 3; + } + if(e.sslCA) { + b2 |= 0x04; + unused = 2; + } + if(e.emailCA) { + b2 |= 0x02; + unused = 1; + } + if(e.objCA) { + b2 |= 0x01; + unused = 0; + } + + // create bit string + var value = String.fromCharCode(unused); + if(b2 !== 0) { + value += String.fromCharCode(b2); + } + e.value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value); + } else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') { + // SYNTAX SEQUENCE + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + + var altName; + for(var n = 0; n < e.altNames.length; ++n) { + altName = e.altNames[n]; + var value = altName.value; + // handle IP + if(altName.type === 7 && altName.ip) { + value = forge.util.bytesFromIP(altName.ip); + if(value === null) { + var error = new Error( + 'Extension "ip" value is not a valid IPv4 or IPv6 address.'); + error.extension = e; + throw error; + } + } else if(altName.type === 8) { + // handle OID + if(altName.oid) { + value = asn1.oidToDer(asn1.oidToDer(altName.oid)); + } else { + // deprecated ... convert value to OID + value = asn1.oidToDer(value); + } + } + e.value.value.push(asn1.create( + asn1.Class.CONTEXT_SPECIFIC, altName.type, false, + value)); + } + } else if(e.name === 'nsComment' && options.cert) { + // sanity check value is ASCII (req'd) and not too big + if(!(/^[\x00-\x7F]*$/.test(e.comment)) || + (e.comment.length < 1) || (e.comment.length > 128)) { + throw new Error('Invalid "nsComment" content.'); + } + // IA5STRING opaque comment + e.value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.IA5STRING, false, e.comment); + } else if(e.name === 'subjectKeyIdentifier' && options.cert) { + var ski = options.cert.generateSubjectKeyIdentifier(); + e.subjectKeyIdentifier = ski.toHex(); + // OCTETSTRING w/digest + e.value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes()); + } else if(e.name === 'authorityKeyIdentifier' && options.cert) { + // SYNTAX SEQUENCE + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var seq = e.value.value; + + if(e.keyIdentifier) { + var keyIdentifier = (e.keyIdentifier === true ? + options.cert.generateSubjectKeyIdentifier().getBytes() : + e.keyIdentifier); + seq.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier)); + } + + if(e.authorityCertIssuer) { + var authorityCertIssuer = [ + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [ + _dnToAsn1(e.authorityCertIssuer === true ? + options.cert.issuer : e.authorityCertIssuer) + ]) + ]; + seq.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer)); + } + + if(e.serialNumber) { + var serialNumber = forge.util.hexToBytes(e.serialNumber === true ? + options.cert.serialNumber : e.serialNumber); + seq.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber)); + } + } else if(e.name === 'cRLDistributionPoints') { + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var seq = e.value.value; + + // Create sub SEQUENCE of DistributionPointName + var subSeq = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + + // Create fullName CHOICE + var fullNameGeneralNames = asn1.create( + asn1.Class.CONTEXT_SPECIFIC, 0, true, []); + var altName; + for(var n = 0; n < e.altNames.length; ++n) { + altName = e.altNames[n]; + var value = altName.value; + // handle IP + if(altName.type === 7 && altName.ip) { + value = forge.util.bytesFromIP(altName.ip); + if(value === null) { + var error = new Error( + 'Extension "ip" value is not a valid IPv4 or IPv6 address.'); + error.extension = e; + throw error; + } + } else if(altName.type === 8) { + // handle OID + if(altName.oid) { + value = asn1.oidToDer(asn1.oidToDer(altName.oid)); + } else { + // deprecated ... convert value to OID + value = asn1.oidToDer(value); + } + } + fullNameGeneralNames.value.push(asn1.create( + asn1.Class.CONTEXT_SPECIFIC, altName.type, false, + value)); + } + + // Add to the parent SEQUENCE + subSeq.value.push(asn1.create( + asn1.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames])); + seq.push(subSeq); + } + + // ensure value has been defined by now + if(typeof e.value === 'undefined') { + var error = new Error('Extension value not specified.'); + error.extension = e; + throw error; + } + + return e; +} + +/** + * Convert signature parameters object to ASN.1 + * + * @param {String} oid Signature algorithm OID + * @param params The signature parameters object + * @return ASN.1 object representing signature parameters + */ +function _signatureParametersToAsn1(oid, params) { + switch(oid) { + case oids['RSASSA-PSS']: + var parts = []; + + if(params.hash.algorithmOid !== undefined) { + parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(params.hash.algorithmOid).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]) + ])); + } + + if(params.mgf.algorithmOid !== undefined) { + parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(params.mgf.algorithmOid).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]) + ]) + ])); + } + + if(params.saltLength !== undefined) { + parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(params.saltLength).getBytes()) + ])); + } + + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts); + + default: + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ''); + } +} + +/** + * Converts a certification request's attributes to an ASN.1 set of + * CRIAttributes. + * + * @param csr certification request. + * + * @return the ASN.1 set of CRIAttributes. + */ +function _CRIAttributesToAsn1(csr) { + // create an empty context-specific container + var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []); + + // no attributes, return empty container + if(csr.attributes.length === 0) { + return rval; + } + + // each attribute has a sequence with a type and a set of values + var attrs = csr.attributes; + for(var i = 0; i < attrs.length; ++i) { + var attr = attrs[i]; + var value = attr.value; + + // reuse tag class for attribute value if available + var valueTagClass = asn1.Type.UTF8; + if('valueTagClass' in attr) { + valueTagClass = attr.valueTagClass; + } + if(valueTagClass === asn1.Type.UTF8) { + value = forge.util.encodeUtf8(value); + } + var valueConstructed = false; + if('valueConstructed' in attr) { + valueConstructed = attr.valueConstructed; + } + // FIXME: handle more encodings + + // create a RelativeDistinguishedName set + // each value in the set is an AttributeTypeAndValue first + // containing the type (an OID) and second the value + var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AttributeType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(attr.type).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + // AttributeValue + asn1.create( + asn1.Class.UNIVERSAL, valueTagClass, valueConstructed, value) + ]) + ]); + rval.value.push(seq); + } + + return rval; +} + +var jan_1_1950 = new Date('1950-01-01T00:00:00Z'); +var jan_1_2050 = new Date('2050-01-01T00:00:00Z'); + +/** + * Converts a Date object to ASN.1 + * Handles the different format before and after 1st January 2050 + * + * @param date date object. + * + * @return the ASN.1 object representing the date. + */ +function _dateToAsn1(date) { + if(date >= jan_1_1950 && date < jan_1_2050) { + return asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false, + asn1.dateToUtcTime(date)); + } else { + return asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false, + asn1.dateToGeneralizedTime(date)); + } +} + +/** + * Gets the ASN.1 TBSCertificate part of an X.509v3 certificate. + * + * @param cert the certificate. + * + * @return the asn1 TBSCertificate. + */ +pki.getTBSCertificate = function(cert) { + // TBSCertificate + var notBefore = _dateToAsn1(cert.validity.notBefore); + var notAfter = _dateToAsn1(cert.validity.notAfter); + var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // integer + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(cert.version).getBytes()) + ]), + // serialNumber + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + forge.util.hexToBytes(cert.serialNumber)), + // signature + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()), + // parameters + _signatureParametersToAsn1( + cert.siginfo.algorithmOid, cert.siginfo.parameters) + ]), + // issuer + _dnToAsn1(cert.issuer), + // validity + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + notBefore, + notAfter + ]), + // subject + _dnToAsn1(cert.subject), + // SubjectPublicKeyInfo + pki.publicKeyToAsn1(cert.publicKey) + ]); + + if(cert.issuer.uniqueId) { + // issuerUniqueID (optional) + tbs.value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, + // TODO: support arbitrary bit length ids + String.fromCharCode(0x00) + + cert.issuer.uniqueId + ) + ]) + ); + } + if(cert.subject.uniqueId) { + // subjectUniqueID (optional) + tbs.value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, + // TODO: support arbitrary bit length ids + String.fromCharCode(0x00) + + cert.subject.uniqueId + ) + ]) + ); + } + + if(cert.extensions.length > 0) { + // extensions (optional) + tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions)); + } + + return tbs; +}; + +/** + * Gets the ASN.1 CertificationRequestInfo part of a + * PKCS#10 CertificationRequest. + * + * @param csr the certification request. + * + * @return the asn1 CertificationRequestInfo. + */ +pki.getCertificationRequestInfo = function(csr) { + // CertificationRequestInfo + var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(csr.version).getBytes()), + // subject + _dnToAsn1(csr.subject), + // SubjectPublicKeyInfo + pki.publicKeyToAsn1(csr.publicKey), + // attributes + _CRIAttributesToAsn1(csr) + ]); + + return cri; +}; + +/** + * Converts a DistinguishedName (subject or issuer) to an ASN.1 object. + * + * @param dn the DistinguishedName. + * + * @return the asn1 representation of a DistinguishedName. + */ +pki.distinguishedNameToAsn1 = function(dn) { + return _dnToAsn1(dn); +}; + +/** + * Converts an X.509v3 RSA certificate to an ASN.1 object. + * + * @param cert the certificate. + * + * @return the asn1 representation of an X.509v3 RSA certificate. + */ +pki.certificateToAsn1 = function(cert) { + // prefer cached TBSCertificate over generating one + var tbsCertificate = cert.tbsCertificate || pki.getTBSCertificate(cert); + + // Certificate + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // TBSCertificate + tbsCertificate, + // AlgorithmIdentifier (signature algorithm) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(cert.signatureOid).getBytes()), + // parameters + _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters) + ]), + // SignatureValue + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, + String.fromCharCode(0x00) + cert.signature) + ]); +}; + +/** + * Converts X.509v3 certificate extensions to ASN.1. + * + * @param exts the extensions to convert. + * + * @return the extensions in ASN.1 format. + */ +pki.certificateExtensionsToAsn1 = function(exts) { + // create top-level extension container + var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []); + + // create extension sequence (stores a sequence for each extension) + var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + rval.value.push(seq); + + for(var i = 0; i < exts.length; ++i) { + seq.value.push(pki.certificateExtensionToAsn1(exts[i])); + } + + return rval; +}; + +/** + * Converts a single certificate extension to ASN.1. + * + * @param ext the extension to convert. + * + * @return the extension in ASN.1 format. + */ +pki.certificateExtensionToAsn1 = function(ext) { + // create a sequence for each extension + var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + + // extnID (OID) + extseq.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(ext.id).getBytes())); + + // critical defaults to false + if(ext.critical) { + // critical BOOLEAN DEFAULT FALSE + extseq.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false, + String.fromCharCode(0xFF))); + } + + var value = ext.value; + if(typeof ext.value !== 'string') { + // value is asn.1 + value = asn1.toDer(value).getBytes(); + } + + // extnValue (OCTET STRING) + extseq.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value)); + + return extseq; +}; + +/** + * Converts a PKCS#10 certification request to an ASN.1 object. + * + * @param csr the certification request. + * + * @return the asn1 representation of a certification request. + */ +pki.certificationRequestToAsn1 = function(csr) { + // prefer cached CertificationRequestInfo over generating one + var cri = csr.certificationRequestInfo || + pki.getCertificationRequestInfo(csr); + + // Certificate + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // CertificationRequestInfo + cri, + // AlgorithmIdentifier (signature algorithm) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(csr.signatureOid).getBytes()), + // parameters + _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters) + ]), + // signature + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, + String.fromCharCode(0x00) + csr.signature) + ]); +}; + +/** + * Creates a CA store. + * + * @param certs an optional array of certificate objects or PEM-formatted + * certificate strings to add to the CA store. + * + * @return the CA store. + */ +pki.createCaStore = function(certs) { + // create CA store + var caStore = { + // stored certificates + certs: {} + }; + + /** + * Gets the certificate that issued the passed certificate or its + * 'parent'. + * + * @param cert the certificate to get the parent for. + * + * @return the parent certificate or null if none was found. + */ + caStore.getIssuer = function(cert) { + var rval = getBySubject(cert.issuer); + + // see if there are multiple matches + /*if(forge.util.isArray(rval)) { + // TODO: resolve multiple matches by checking + // authorityKey/subjectKey/issuerUniqueID/other identifiers, etc. + // FIXME: or alternatively do authority key mapping + // if possible (X.509v1 certs can't work?) + throw new Error('Resolving multiple issuer matches not implemented yet.'); + }*/ + + return rval; + }; + + /** + * Adds a trusted certificate to the store. + * + * @param cert the certificate to add as a trusted certificate (either a + * pki.certificate object or a PEM-formatted certificate). + */ + caStore.addCertificate = function(cert) { + // convert from pem if necessary + if(typeof cert === 'string') { + cert = forge.pki.certificateFromPem(cert); + } + + ensureSubjectHasHash(cert.subject); + + if(!caStore.hasCertificate(cert)) { // avoid duplicate certificates in store + if(cert.subject.hash in caStore.certs) { + // subject hash already exists, append to array + var tmp = caStore.certs[cert.subject.hash]; + if(!forge.util.isArray(tmp)) { + tmp = [tmp]; + } + tmp.push(cert); + caStore.certs[cert.subject.hash] = tmp; + } else { + caStore.certs[cert.subject.hash] = cert; + } + } + }; + + /** + * Checks to see if the given certificate is in the store. + * + * @param cert the certificate to check (either a pki.certificate or a + * PEM-formatted certificate). + * + * @return true if the certificate is in the store, false if not. + */ + caStore.hasCertificate = function(cert) { + // convert from pem if necessary + if(typeof cert === 'string') { + cert = forge.pki.certificateFromPem(cert); + } + + var match = getBySubject(cert.subject); + if(!match) { + return false; + } + if(!forge.util.isArray(match)) { + match = [match]; + } + // compare DER-encoding of certificates + var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes(); + for(var i = 0; i < match.length; ++i) { + var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes(); + if(der1 === der2) { + return true; + } + } + return false; + }; + + /** + * Lists all of the certificates kept in the store. + * + * @return an array of all of the pki.certificate objects in the store. + */ + caStore.listAllCertificates = function() { + var certList = []; + + for(var hash in caStore.certs) { + if(caStore.certs.hasOwnProperty(hash)) { + var value = caStore.certs[hash]; + if(!forge.util.isArray(value)) { + certList.push(value); + } else { + for(var i = 0; i < value.length; ++i) { + certList.push(value[i]); + } + } + } + } + + return certList; + }; + + /** + * Removes a certificate from the store. + * + * @param cert the certificate to remove (either a pki.certificate or a + * PEM-formatted certificate). + * + * @return the certificate that was removed or null if the certificate + * wasn't in store. + */ + caStore.removeCertificate = function(cert) { + var result; + + // convert from pem if necessary + if(typeof cert === 'string') { + cert = forge.pki.certificateFromPem(cert); + } + ensureSubjectHasHash(cert.subject); + if(!caStore.hasCertificate(cert)) { + return null; + } + + var match = getBySubject(cert.subject); + + if(!forge.util.isArray(match)) { + result = caStore.certs[cert.subject.hash]; + delete caStore.certs[cert.subject.hash]; + return result; + } + + // compare DER-encoding of certificates + var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes(); + for(var i = 0; i < match.length; ++i) { + var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes(); + if(der1 === der2) { + result = match[i]; + match.splice(i, 1); + } + } + if(match.length === 0) { + delete caStore.certs[cert.subject.hash]; + } + + return result; + }; + + function getBySubject(subject) { + ensureSubjectHasHash(subject); + return caStore.certs[subject.hash] || null; + } + + function ensureSubjectHasHash(subject) { + // produce subject hash if it doesn't exist + if(!subject.hash) { + var md = forge.md.sha1.create(); + subject.attributes = pki.RDNAttributesAsArray(_dnToAsn1(subject), md); + subject.hash = md.digest().toHex(); + } + } + + // auto-add passed in certs + if(certs) { + // parse PEM-formatted certificates as necessary + for(var i = 0; i < certs.length; ++i) { + var cert = certs[i]; + caStore.addCertificate(cert); + } + } + + return caStore; +}; + +/** + * Certificate verification errors, based on TLS. + */ +pki.certificateError = { + bad_certificate: 'forge.pki.BadCertificate', + unsupported_certificate: 'forge.pki.UnsupportedCertificate', + certificate_revoked: 'forge.pki.CertificateRevoked', + certificate_expired: 'forge.pki.CertificateExpired', + certificate_unknown: 'forge.pki.CertificateUnknown', + unknown_ca: 'forge.pki.UnknownCertificateAuthority' +}; + +/** + * Verifies a certificate chain against the given Certificate Authority store + * with an optional custom verify callback. + * + * @param caStore a certificate store to verify against. + * @param chain the certificate chain to verify, with the root or highest + * authority at the end (an array of certificates). + * @param options a callback to be called for every certificate in the chain or + * an object with: + * verify a callback to be called for every certificate in the + * chain + * validityCheckDate the date against which the certificate + * validity period should be checked. Pass null to not check + * the validity period. By default, the current date is used. + * + * The verify callback has the following signature: + * + * verified - Set to true if certificate was verified, otherwise the + * pki.certificateError for why the certificate failed. + * depth - The current index in the chain, where 0 is the end point's cert. + * certs - The certificate chain, *NOTE* an empty chain indicates an anonymous + * end point. + * + * The function returns true on success and on failure either the appropriate + * pki.certificateError or an object with 'error' set to the appropriate + * pki.certificateError and 'message' set to a custom error message. + * + * @return true if successful, error thrown if not. + */ +pki.verifyCertificateChain = function(caStore, chain, options) { + /* From: RFC3280 - Internet X.509 Public Key Infrastructure Certificate + Section 6: Certification Path Validation + See inline parentheticals related to this particular implementation. + + The primary goal of path validation is to verify the binding between + a subject distinguished name or a subject alternative name and subject + public key, as represented in the end entity certificate, based on the + public key of the trust anchor. This requires obtaining a sequence of + certificates that support that binding. That sequence should be provided + in the passed 'chain'. The trust anchor should be in the given CA + store. The 'end entity' certificate is the certificate provided by the + end point (typically a server) and is the first in the chain. + + To meet this goal, the path validation process verifies, among other + things, that a prospective certification path (a sequence of n + certificates or a 'chain') satisfies the following conditions: + + (a) for all x in {1, ..., n-1}, the subject of certificate x is + the issuer of certificate x+1; + + (b) certificate 1 is issued by the trust anchor; + + (c) certificate n is the certificate to be validated; and + + (d) for all x in {1, ..., n}, the certificate was valid at the + time in question. + + Note that here 'n' is index 0 in the chain and 1 is the last certificate + in the chain and it must be signed by a certificate in the connection's + CA store. + + The path validation process also determines the set of certificate + policies that are valid for this path, based on the certificate policies + extension, policy mapping extension, policy constraints extension, and + inhibit any-policy extension. + + Note: Policy mapping extension not supported (Not Required). + + Note: If the certificate has an unsupported critical extension, then it + must be rejected. + + Note: A certificate is self-issued if the DNs that appear in the subject + and issuer fields are identical and are not empty. + + The path validation algorithm assumes the following seven inputs are + provided to the path processing logic. What this specific implementation + will use is provided parenthetically: + + (a) a prospective certification path of length n (the 'chain') + (b) the current date/time: ('now'). + (c) user-initial-policy-set: A set of certificate policy identifiers + naming the policies that are acceptable to the certificate user. + The user-initial-policy-set contains the special value any-policy + if the user is not concerned about certificate policy + (Not implemented. Any policy is accepted). + (d) trust anchor information, describing a CA that serves as a trust + anchor for the certification path. The trust anchor information + includes: + + (1) the trusted issuer name, + (2) the trusted public key algorithm, + (3) the trusted public key, and + (4) optionally, the trusted public key parameters associated + with the public key. + + (Trust anchors are provided via certificates in the CA store). + + The trust anchor information may be provided to the path processing + procedure in the form of a self-signed certificate. The trusted anchor + information is trusted because it was delivered to the path processing + procedure by some trustworthy out-of-band procedure. If the trusted + public key algorithm requires parameters, then the parameters are + provided along with the trusted public key (No parameters used in this + implementation). + + (e) initial-policy-mapping-inhibit, which indicates if policy mapping is + allowed in the certification path. + (Not implemented, no policy checking) + + (f) initial-explicit-policy, which indicates if the path must be valid + for at least one of the certificate policies in the user-initial- + policy-set. + (Not implemented, no policy checking) + + (g) initial-any-policy-inhibit, which indicates whether the + anyPolicy OID should be processed if it is included in a + certificate. + (Not implemented, so any policy is valid provided that it is + not marked as critical) */ + + /* Basic Path Processing: + + For each certificate in the 'chain', the following is checked: + + 1. The certificate validity period includes the current time. + 2. The certificate was signed by its parent (where the parent is either + the next in the chain or from the CA store). Allow processing to + continue to the next step if no parent is found but the certificate is + in the CA store. + 3. TODO: The certificate has not been revoked. + 4. The certificate issuer name matches the parent's subject name. + 5. TODO: If the certificate is self-issued and not the final certificate + in the chain, skip this step, otherwise verify that the subject name + is within one of the permitted subtrees of X.500 distinguished names + and that each of the alternative names in the subjectAltName extension + (critical or non-critical) is within one of the permitted subtrees for + that name type. + 6. TODO: If the certificate is self-issued and not the final certificate + in the chain, skip this step, otherwise verify that the subject name + is not within one of the excluded subtrees for X.500 distinguished + names and none of the subjectAltName extension names are excluded for + that name type. + 7. The other steps in the algorithm for basic path processing involve + handling the policy extension which is not presently supported in this + implementation. Instead, if a critical policy extension is found, the + certificate is rejected as not supported. + 8. If the certificate is not the first or if its the only certificate in + the chain (having no parent from the CA store or is self-signed) and it + has a critical key usage extension, verify that the keyCertSign bit is + set. If the key usage extension exists, verify that the basic + constraints extension exists. If the basic constraints extension exists, + verify that the cA flag is set. If pathLenConstraint is set, ensure that + the number of certificates that precede in the chain (come earlier + in the chain as implemented below), excluding the very first in the + chain (typically the end-entity one), isn't greater than the + pathLenConstraint. This constraint limits the number of intermediate + CAs that may appear below a CA before only end-entity certificates + may be issued. */ + + // if a verify callback is passed as the third parameter, package it within + // the options object. This is to support a legacy function signature that + // expected the verify callback as the third parameter. + if(typeof options === 'function') { + options = {verify: options}; + } + options = options || {}; + + // copy cert chain references to another array to protect against changes + // in verify callback + chain = chain.slice(0); + var certs = chain.slice(0); + + var validityCheckDate = options.validityCheckDate; + // if no validityCheckDate is specified, default to the current date. Make + // sure to maintain the value null because it indicates that the validity + // period should not be checked. + if(typeof validityCheckDate === 'undefined') { + validityCheckDate = new Date(); + } + + // verify each cert in the chain using its parent, where the parent + // is either the next in the chain or from the CA store + var first = true; + var error = null; + var depth = 0; + do { + var cert = chain.shift(); + var parent = null; + var selfSigned = false; + + if(validityCheckDate) { + // 1. check valid time + if(validityCheckDate < cert.validity.notBefore || + validityCheckDate > cert.validity.notAfter) { + error = { + message: 'Certificate is not valid yet or has expired.', + error: pki.certificateError.certificate_expired, + notBefore: cert.validity.notBefore, + notAfter: cert.validity.notAfter, + // TODO: we might want to reconsider renaming 'now' to + // 'validityCheckDate' should this API be changed in the future. + now: validityCheckDate + }; + } + } + + // 2. verify with parent from chain or CA store + if(error === null) { + parent = chain[0] || caStore.getIssuer(cert); + if(parent === null) { + // check for self-signed cert + if(cert.isIssuer(cert)) { + selfSigned = true; + parent = cert; + } + } + + if(parent) { + // FIXME: current CA store implementation might have multiple + // certificates where the issuer can't be determined from the + // certificate (happens rarely with, eg: old certificates) so normalize + // by always putting parents into an array + // TODO: there's may be an extreme degenerate case currently uncovered + // where an old intermediate certificate seems to have a matching parent + // but none of the parents actually verify ... but the intermediate + // is in the CA and it should pass this check; needs investigation + var parents = parent; + if(!forge.util.isArray(parents)) { + parents = [parents]; + } + + // try to verify with each possible parent (typically only one) + var verified = false; + while(!verified && parents.length > 0) { + parent = parents.shift(); + try { + verified = parent.verify(cert); + } catch(ex) { + // failure to verify, don't care why, try next one + } + } + + if(!verified) { + error = { + message: 'Certificate signature is invalid.', + error: pki.certificateError.bad_certificate + }; + } + } + + if(error === null && (!parent || selfSigned) && + !caStore.hasCertificate(cert)) { + // no parent issuer and certificate itself is not trusted + error = { + message: 'Certificate is not trusted.', + error: pki.certificateError.unknown_ca + }; + } + } + + // TODO: 3. check revoked + + // 4. check for matching issuer/subject + if(error === null && parent && !cert.isIssuer(parent)) { + // parent is not issuer + error = { + message: 'Certificate issuer is invalid.', + error: pki.certificateError.bad_certificate + }; + } + + // 5. TODO: check names with permitted names tree + + // 6. TODO: check names against excluded names tree + + // 7. check for unsupported critical extensions + if(error === null) { + // supported extensions + var se = { + keyUsage: true, + basicConstraints: true + }; + for(var i = 0; error === null && i < cert.extensions.length; ++i) { + var ext = cert.extensions[i]; + if(ext.critical && !(ext.name in se)) { + error = { + message: + 'Certificate has an unsupported critical extension.', + error: pki.certificateError.unsupported_certificate + }; + } + } + } + + // 8. check for CA if cert is not first or is the only certificate + // remaining in chain with no parent or is self-signed + if(error === null && + (!first || (chain.length === 0 && (!parent || selfSigned)))) { + // first check keyUsage extension and then basic constraints + var bcExt = cert.getExtension('basicConstraints'); + var keyUsageExt = cert.getExtension('keyUsage'); + if(keyUsageExt !== null) { + // keyCertSign must be true and there must be a basic + // constraints extension + if(!keyUsageExt.keyCertSign || bcExt === null) { + // bad certificate + error = { + message: + 'Certificate keyUsage or basicConstraints conflict ' + + 'or indicate that the certificate is not a CA. ' + + 'If the certificate is the only one in the chain or ' + + 'isn\'t the first then the certificate must be a ' + + 'valid CA.', + error: pki.certificateError.bad_certificate + }; + } + } + // basic constraints cA flag must be set + if(error === null && bcExt !== null && !bcExt.cA) { + // bad certificate + error = { + message: + 'Certificate basicConstraints indicates the certificate ' + + 'is not a CA.', + error: pki.certificateError.bad_certificate + }; + } + // if error is not null and keyUsage is available, then we know it + // has keyCertSign and there is a basic constraints extension too, + // which means we can check pathLenConstraint (if it exists) + if(error === null && keyUsageExt !== null && + 'pathLenConstraint' in bcExt) { + // pathLen is the maximum # of intermediate CA certs that can be + // found between the current certificate and the end-entity (depth 0) + // certificate; this number does not include the end-entity (depth 0, + // last in the chain) even if it happens to be a CA certificate itself + var pathLen = depth - 1; + if(pathLen > bcExt.pathLenConstraint) { + // pathLenConstraint violated, bad certificate + error = { + message: + 'Certificate basicConstraints pathLenConstraint violated.', + error: pki.certificateError.bad_certificate + }; + } + } + } + + // call application callback + var vfd = (error === null) ? true : error.error; + var ret = options.verify ? options.verify(vfd, depth, certs) : vfd; + if(ret === true) { + // clear any set error + error = null; + } else { + // if passed basic tests, set default message and alert + if(vfd === true) { + error = { + message: 'The application rejected the certificate.', + error: pki.certificateError.bad_certificate + }; + } + + // check for custom error info + if(ret || ret === 0) { + // set custom message and error + if(typeof ret === 'object' && !forge.util.isArray(ret)) { + if(ret.message) { + error.message = ret.message; + } + if(ret.error) { + error.error = ret.error; + } + } else if(typeof ret === 'string') { + // set custom error + error.error = ret; + } + } + + // throw error + throw error; + } + + // no longer first cert in chain + first = false; + ++depth; + } while(chain.length > 0); + + return true; +}; diff --git a/node_modules/node-forge/lib/xhr.js b/node_modules/node-forge/lib/xhr.js new file mode 100644 index 0000000..1527042 --- /dev/null +++ b/node_modules/node-forge/lib/xhr.js @@ -0,0 +1,738 @@ +/** + * XmlHttpRequest implementation that uses TLS and flash SocketPool. + * + * @author Dave Longley + * + * Copyright (c) 2010-2013 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./socket'); +require('./http'); + +/* XHR API */ +var xhrApi = module.exports = forge.xhr = forge.xhr || {}; + +(function($) { + +// logging category +var cat = 'forge.xhr'; + +/* +XMLHttpRequest interface definition from: +http://www.w3.org/TR/XMLHttpRequest + +interface XMLHttpRequest { + // event handler + attribute EventListener onreadystatechange; + + // state + const unsigned short UNSENT = 0; + const unsigned short OPENED = 1; + const unsigned short HEADERS_RECEIVED = 2; + const unsigned short LOADING = 3; + const unsigned short DONE = 4; + readonly attribute unsigned short readyState; + + // request + void open(in DOMString method, in DOMString url); + void open(in DOMString method, in DOMString url, in boolean async); + void open(in DOMString method, in DOMString url, + in boolean async, in DOMString user); + void open(in DOMString method, in DOMString url, + in boolean async, in DOMString user, in DOMString password); + void setRequestHeader(in DOMString header, in DOMString value); + void send(); + void send(in DOMString data); + void send(in Document data); + void abort(); + + // response + DOMString getAllResponseHeaders(); + DOMString getResponseHeader(in DOMString header); + readonly attribute DOMString responseText; + readonly attribute Document responseXML; + readonly attribute unsigned short status; + readonly attribute DOMString statusText; +}; +*/ + +// readyStates +var UNSENT = 0; +var OPENED = 1; +var HEADERS_RECEIVED = 2; +var LOADING = 3; +var DONE = 4; + +// exceptions +var INVALID_STATE_ERR = 11; +var SYNTAX_ERR = 12; +var SECURITY_ERR = 18; +var NETWORK_ERR = 19; +var ABORT_ERR = 20; + +// private flash socket pool vars +var _sp = null; +var _policyPort = 0; +var _policyUrl = null; + +// default client (used if no special URL provided when creating an XHR) +var _client = null; + +// all clients including the default, key'd by full base url +// (multiple cross-domain http clients are permitted so there may be more +// than one client in this map) +// TODO: provide optional clean up API for non-default clients +var _clients = {}; + +// the default maximum number of concurrents connections per client +var _maxConnections = 10; + +var net = forge.net; +var http = forge.http; + +/** + * Initializes flash XHR support. + * + * @param options: + * url: the default base URL to connect to if xhr URLs are relative, + * ie: https://myserver.com. + * flashId: the dom ID of the flash SocketPool. + * policyPort: the port that provides the server's flash policy, 0 to use + * the flash default. + * policyUrl: the policy file URL to use instead of a policy port. + * msie: true if browser is internet explorer, false if not. + * connections: the maximum number of concurrent connections. + * caCerts: a list of PEM-formatted certificates to trust. + * cipherSuites: an optional array of cipher suites to use, + * see forge.tls.CipherSuites. + * verify: optional TLS certificate verify callback to use (see forge.tls + * for details). + * getCertificate: an optional callback used to get a client-side + * certificate (see forge.tls for details). + * getPrivateKey: an optional callback used to get a client-side private + * key (see forge.tls for details). + * getSignature: an optional callback used to get a client-side signature + * (see forge.tls for details). + * persistCookies: true to use persistent cookies via flash local storage, + * false to only keep cookies in javascript. + * primeTlsSockets: true to immediately connect TLS sockets on their + * creation so that they will cache TLS sessions for reuse. + */ +xhrApi.init = function(options) { + forge.log.debug(cat, 'initializing', options); + + // update default policy port and max connections + _policyPort = options.policyPort || _policyPort; + _policyUrl = options.policyUrl || _policyUrl; + _maxConnections = options.connections || _maxConnections; + + // create the flash socket pool + _sp = net.createSocketPool({ + flashId: options.flashId, + policyPort: _policyPort, + policyUrl: _policyUrl, + msie: options.msie || false + }); + + // create default http client + _client = http.createClient({ + url: options.url || ( + window.location.protocol + '//' + window.location.host), + socketPool: _sp, + policyPort: _policyPort, + policyUrl: _policyUrl, + connections: options.connections || _maxConnections, + caCerts: options.caCerts, + cipherSuites: options.cipherSuites, + persistCookies: options.persistCookies || true, + primeTlsSockets: options.primeTlsSockets || false, + verify: options.verify, + getCertificate: options.getCertificate, + getPrivateKey: options.getPrivateKey, + getSignature: options.getSignature + }); + _clients[_client.url.origin] = _client; + + forge.log.debug(cat, 'ready'); +}; + +/** + * Called to clean up the clients and socket pool. + */ +xhrApi.cleanup = function() { + // destroy all clients + for(var key in _clients) { + _clients[key].destroy(); + } + _clients = {}; + _client = null; + + // destroy socket pool + _sp.destroy(); + _sp = null; +}; + +/** + * Sets a cookie. + * + * @param cookie the cookie with parameters: + * name: the name of the cookie. + * value: the value of the cookie. + * comment: an optional comment string. + * maxAge: the age of the cookie in seconds relative to created time. + * secure: true if the cookie must be sent over a secure protocol. + * httpOnly: true to restrict access to the cookie from javascript + * (inaffective since the cookies are stored in javascript). + * path: the path for the cookie. + * domain: optional domain the cookie belongs to (must start with dot). + * version: optional version of the cookie. + * created: creation time, in UTC seconds, of the cookie. + */ +xhrApi.setCookie = function(cookie) { + // default cookie expiration to never + cookie.maxAge = cookie.maxAge || -1; + + // if the cookie's domain is set, use the appropriate client + if(cookie.domain) { + // add the cookies to the applicable domains + for(var key in _clients) { + var client = _clients[key]; + if(http.withinCookieDomain(client.url, cookie) && + client.secure === cookie.secure) { + client.setCookie(cookie); + } + } + } else { + // use the default domain + // FIXME: should a null domain cookie be added to all clients? should + // this be an option? + _client.setCookie(cookie); + } +}; + +/** + * Gets a cookie. + * + * @param name the name of the cookie. + * @param path an optional path for the cookie (if there are multiple cookies + * with the same name but different paths). + * @param domain an optional domain for the cookie (if not using the default + * domain). + * + * @return the cookie, cookies (if multiple matches), or null if not found. + */ +xhrApi.getCookie = function(name, path, domain) { + var rval = null; + + if(domain) { + // get the cookies from the applicable domains + for(var key in _clients) { + var client = _clients[key]; + if(http.withinCookieDomain(client.url, domain)) { + var cookie = client.getCookie(name, path); + if(cookie !== null) { + if(rval === null) { + rval = cookie; + } else if(!forge.util.isArray(rval)) { + rval = [rval, cookie]; + } else { + rval.push(cookie); + } + } + } + } + } else { + // get cookie from default domain + rval = _client.getCookie(name, path); + } + + return rval; +}; + +/** + * Removes a cookie. + * + * @param name the name of the cookie. + * @param path an optional path for the cookie (if there are multiple cookies + * with the same name but different paths). + * @param domain an optional domain for the cookie (if not using the default + * domain). + * + * @return true if a cookie was removed, false if not. + */ +xhrApi.removeCookie = function(name, path, domain) { + var rval = false; + + if(domain) { + // remove the cookies from the applicable domains + for(var key in _clients) { + var client = _clients[key]; + if(http.withinCookieDomain(client.url, domain)) { + if(client.removeCookie(name, path)) { + rval = true; + } + } + } + } else { + // remove cookie from default domain + rval = _client.removeCookie(name, path); + } + + return rval; +}; + +/** + * Creates a new XmlHttpRequest. By default the base URL, flash policy port, + * etc, will be used. However, an XHR can be created to point at another + * cross-domain URL. + * + * @param options: + * logWarningOnError: If true and an HTTP error status code is received then + * log a warning, otherwise log a verbose message. + * verbose: If true be very verbose in the output including the response + * event and response body, otherwise only include status, timing, and + * data size. + * logError: a multi-var log function for warnings that takes the log + * category as the first var. + * logWarning: a multi-var log function for warnings that takes the log + * category as the first var. + * logDebug: a multi-var log function for warnings that takes the log + * category as the first var. + * logVerbose: a multi-var log function for warnings that takes the log + * category as the first var. + * url: the default base URL to connect to if xhr URLs are relative, + * eg: https://myserver.com, and note that the following options will be + * ignored if the URL is absent or the same as the default base URL. + * policyPort: the port that provides the server's flash policy, 0 to use + * the flash default. + * policyUrl: the policy file URL to use instead of a policy port. + * connections: the maximum number of concurrent connections. + * caCerts: a list of PEM-formatted certificates to trust. + * cipherSuites: an optional array of cipher suites to use, see + * forge.tls.CipherSuites. + * verify: optional TLS certificate verify callback to use (see forge.tls + * for details). + * getCertificate: an optional callback used to get a client-side + * certificate. + * getPrivateKey: an optional callback used to get a client-side private key. + * getSignature: an optional callback used to get a client-side signature. + * persistCookies: true to use persistent cookies via flash local storage, + * false to only keep cookies in javascript. + * primeTlsSockets: true to immediately connect TLS sockets on their + * creation so that they will cache TLS sessions for reuse. + * + * @return the XmlHttpRequest. + */ +xhrApi.create = function(options) { + // set option defaults + options = $.extend({ + logWarningOnError: true, + verbose: false, + logError: function() {}, + logWarning: function() {}, + logDebug: function() {}, + logVerbose: function() {}, + url: null + }, options || {}); + + // private xhr state + var _state = { + // the http client to use + client: null, + // request storage + request: null, + // response storage + response: null, + // asynchronous, true if doing asynchronous communication + asynchronous: true, + // sendFlag, true if send has been called + sendFlag: false, + // errorFlag, true if a network error occurred + errorFlag: false + }; + + // private log functions + var _log = { + error: options.logError || forge.log.error, + warning: options.logWarning || forge.log.warning, + debug: options.logDebug || forge.log.debug, + verbose: options.logVerbose || forge.log.verbose + }; + + // create public xhr interface + var xhr = { + // an EventListener + onreadystatechange: null, + // readonly, the current readyState + readyState: UNSENT, + // a string with the response entity-body + responseText: '', + // a Document for response entity-bodies that are XML + responseXML: null, + // readonly, returns the HTTP status code (i.e. 404) + status: 0, + // readonly, returns the HTTP status message (i.e. 'Not Found') + statusText: '' + }; + + // determine which http client to use + if(options.url === null) { + // use default + _state.client = _client; + } else { + var url; + try { + url = new URL(options.url); + } catch(e) { + var error = new Error('Invalid url.'); + error.details = { + url: options.url + }; + } + + // find client + if(url.origin in _clients) { + // client found + _state.client = _clients[url.origin]; + } else { + // create client + _state.client = http.createClient({ + url: options.url, + socketPool: _sp, + policyPort: options.policyPort || _policyPort, + policyUrl: options.policyUrl || _policyUrl, + connections: options.connections || _maxConnections, + caCerts: options.caCerts, + cipherSuites: options.cipherSuites, + persistCookies: options.persistCookies || true, + primeTlsSockets: options.primeTlsSockets || false, + verify: options.verify, + getCertificate: options.getCertificate, + getPrivateKey: options.getPrivateKey, + getSignature: options.getSignature + }); + _clients[url.origin] = _state.client; + } + } + + /** + * Opens the request. This method will create the HTTP request to send. + * + * @param method the HTTP method (i.e. 'GET'). + * @param url the relative url (the HTTP request path). + * @param async always true, ignored. + * @param user always null, ignored. + * @param password always null, ignored. + */ + xhr.open = function(method, url, async, user, password) { + // 1. validate Document if one is associated + // TODO: not implemented (not used yet) + + // 2. validate method token + // 3. change method to uppercase if it matches a known + // method (here we just require it to be uppercase, and + // we do not allow the standard methods) + // 4. disallow CONNECT, TRACE, or TRACK with a security error + switch(method) { + case 'DELETE': + case 'GET': + case 'HEAD': + case 'OPTIONS': + case 'PATCH': + case 'POST': + case 'PUT': + // valid method + break; + case 'CONNECT': + case 'TRACE': + case 'TRACK': + throw new Error('CONNECT, TRACE and TRACK methods are disallowed'); + default: + throw new Error('Invalid method: ' + method); + } + + // TODO: other validation steps in algorithm are not implemented + + // 19. set send flag to false + // set response body to null + // empty list of request headers + // set request method to given method + // set request URL + // set username, password + // set asynchronous flag + _state.sendFlag = false; + xhr.responseText = ''; + xhr.responseXML = null; + + // custom: reset status and statusText + xhr.status = 0; + xhr.statusText = ''; + + // create the HTTP request + _state.request = http.createRequest({ + method: method, + path: url + }); + + // 20. set state to OPENED + xhr.readyState = OPENED; + + // 21. dispatch onreadystatechange + if(xhr.onreadystatechange) { + xhr.onreadystatechange(); + } + }; + + /** + * Adds an HTTP header field to the request. + * + * @param header the name of the header field. + * @param value the value of the header field. + */ + xhr.setRequestHeader = function(header, value) { + // 1. if state is not OPENED or send flag is true, raise exception + if(xhr.readyState != OPENED || _state.sendFlag) { + throw new Error('XHR not open or sending'); + } + + // TODO: other validation steps in spec aren't implemented + + // set header + _state.request.setField(header, value); + }; + + /** + * Sends the request and any associated data. + * + * @param data a string or Document object to send, null to send no data. + */ + xhr.send = function(data) { + // 1. if state is not OPENED or 2. send flag is true, raise + // an invalid state exception + if(xhr.readyState != OPENED || _state.sendFlag) { + throw new Error('XHR not open or sending'); + } + + // 3. ignore data if method is GET or HEAD + if(data && + _state.request.method !== 'GET' && + _state.request.method !== 'HEAD') { + // handle non-IE case + if(typeof(XMLSerializer) !== 'undefined') { + if(data instanceof Document) { + var xs = new XMLSerializer(); + _state.request.body = xs.serializeToString(data); + } else { + _state.request.body = data; + } + } else { + // poorly implemented IE case + if(typeof(data.xml) !== 'undefined') { + _state.request.body = data.xml; + } else { + _state.request.body = data; + } + } + } + + // 4. release storage mutex (not used) + + // 5. set error flag to false + _state.errorFlag = false; + + // 6. if asynchronous is true (must be in this implementation) + + // 6.1 set send flag to true + _state.sendFlag = true; + + // 6.2 dispatch onreadystatechange + if(xhr.onreadystatechange) { + xhr.onreadystatechange(); + } + + // create send options + var options = {}; + options.request = _state.request; + options.headerReady = function(e) { + // make cookies available for ease of use/iteration + xhr.cookies = _state.client.cookies; + + // TODO: update document.cookie with any cookies where the + // script's domain matches + + // headers received + xhr.readyState = HEADERS_RECEIVED; + xhr.status = e.response.code; + xhr.statusText = e.response.message; + _state.response = e.response; + if(xhr.onreadystatechange) { + xhr.onreadystatechange(); + } + if(!_state.response.aborted) { + // now loading body + xhr.readyState = LOADING; + if(xhr.onreadystatechange) { + xhr.onreadystatechange(); + } + } + }; + options.bodyReady = function(e) { + xhr.readyState = DONE; + var ct = e.response.getField('Content-Type'); + // Note: this null/undefined check is done outside because IE + // dies otherwise on a "'null' is null" error + if(ct) { + if(ct.indexOf('text/xml') === 0 || + ct.indexOf('application/xml') === 0 || + ct.indexOf('+xml') !== -1) { + try { + var doc = new ActiveXObject('MicrosoftXMLDOM'); + doc.async = false; + doc.loadXML(e.response.body); + xhr.responseXML = doc; + } catch(ex) { + var parser = new DOMParser(); + xhr.responseXML = parser.parseFromString(ex.body, 'text/xml'); + } + } + } + + var length = 0; + if(e.response.body !== null) { + xhr.responseText = e.response.body; + length = e.response.body.length; + } + // build logging output + var req = _state.request; + var output = + req.method + ' ' + req.path + ' ' + + xhr.status + ' ' + xhr.statusText + ' ' + + length + 'B ' + + (e.request.connectTime + e.request.time + e.response.time) + + 'ms'; + var lFunc; + if(options.verbose) { + lFunc = (xhr.status >= 400 && options.logWarningOnError) ? + _log.warning : _log.verbose; + lFunc(cat, output, + e, e.response.body ? '\n' + e.response.body : '\nNo content'); + } else { + lFunc = (xhr.status >= 400 && options.logWarningOnError) ? + _log.warning : _log.debug; + lFunc(cat, output); + } + if(xhr.onreadystatechange) { + xhr.onreadystatechange(); + } + }; + options.error = function(e) { + var req = _state.request; + _log.error(cat, req.method + ' ' + req.path, e); + + // 1. set response body to null + xhr.responseText = ''; + xhr.responseXML = null; + + // 2. set error flag to true (and reset status) + _state.errorFlag = true; + xhr.status = 0; + xhr.statusText = ''; + + // 3. set state to done + xhr.readyState = DONE; + + // 4. asyc flag is always true, so dispatch onreadystatechange + if(xhr.onreadystatechange) { + xhr.onreadystatechange(); + } + }; + + // 7. send request + _state.client.send(options); + }; + + /** + * Aborts the request. + */ + xhr.abort = function() { + // 1. abort send + // 2. stop network activity + _state.request.abort(); + + // 3. set response to null + xhr.responseText = ''; + xhr.responseXML = null; + + // 4. set error flag to true (and reset status) + _state.errorFlag = true; + xhr.status = 0; + xhr.statusText = ''; + + // 5. clear user headers + _state.request = null; + _state.response = null; + + // 6. if state is DONE or UNSENT, or if OPENED and send flag is false + if(xhr.readyState === DONE || xhr.readyState === UNSENT || + (xhr.readyState === OPENED && !_state.sendFlag)) { + // 7. set ready state to unsent + xhr.readyState = UNSENT; + } else { + // 6.1 set state to DONE + xhr.readyState = DONE; + + // 6.2 set send flag to false + _state.sendFlag = false; + + // 6.3 dispatch onreadystatechange + if(xhr.onreadystatechange) { + xhr.onreadystatechange(); + } + + // 7. set state to UNSENT + xhr.readyState = UNSENT; + } + }; + + /** + * Gets all response headers as a string. + * + * @return the HTTP-encoded response header fields. + */ + xhr.getAllResponseHeaders = function() { + var rval = ''; + if(_state.response !== null) { + var fields = _state.response.fields; + $.each(fields, function(name, array) { + $.each(array, function(i, value) { + rval += name + ': ' + value + '\r\n'; + }); + }); + } + return rval; + }; + + /** + * Gets a single header field value or, if there are multiple + * fields with the same name, a comma-separated list of header + * values. + * + * @return the header field value(s) or null. + */ + xhr.getResponseHeader = function(header) { + var rval = null; + if(_state.response !== null) { + if(header in _state.response.fields) { + rval = _state.response.fields[header]; + if(forge.util.isArray(rval)) { + rval = rval.join(); + } + } + } + return rval; + }; + + return xhr; +}; + +})(jQuery); diff --git a/node_modules/node-forge/package.json b/node_modules/node-forge/package.json new file mode 100644 index 0000000..4f7ad0a --- /dev/null +++ b/node_modules/node-forge/package.json @@ -0,0 +1,123 @@ +{ + "name": "node-forge", + "version": "1.3.3", + "description": "JavaScript implementations of network transports, cryptography, ciphers, PKI, message digests, and various utilities.", + "homepage": "https://github.com/digitalbazaar/forge", + "author": { + "name": "Digital Bazaar, Inc.", + "email": "support@digitalbazaar.com", + "url": "http://digitalbazaar.com/" + }, + "contributors": [ + "Dave Longley ", + "David I. Lehn ", + "Stefan Siegl ", + "Christoph Dorn " + ], + "devDependencies": { + "browserify": "^16.5.2", + "commander": "^2.20.0", + "cross-env": "^5.2.1", + "eslint": "^7.27.0", + "eslint-config-digitalbazaar": "^2.8.0", + "express": "^4.16.2", + "karma": "^4.4.1", + "karma-browserify": "^7.0.0", + "karma-chrome-launcher": "^3.1.0", + "karma-edge-launcher": "^0.4.2", + "karma-firefox-launcher": "^1.3.0", + "karma-ie-launcher": "^1.0.0", + "karma-mocha": "^1.3.0", + "karma-mocha-reporter": "^2.2.5", + "karma-safari-launcher": "^1.0.0", + "karma-sauce-launcher": "^2.0.2", + "karma-sourcemap-loader": "^0.3.8", + "karma-tap-reporter": "0.0.6", + "karma-webpack": "^4.0.2", + "mocha": "^5.2.0", + "mocha-lcov-reporter": "^1.2.0", + "nodejs-websocket": "^1.7.1", + "nyc": "^15.1.0", + "opts": "^1.2.7", + "webpack": "^4.44.1", + "webpack-cli": "^3.3.12", + "worker-loader": "^2.0.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/digitalbazaar/forge" + }, + "bugs": { + "url": "https://github.com/digitalbazaar/forge/issues", + "email": "support@digitalbazaar.com" + }, + "license": "(BSD-3-Clause OR GPL-2.0)", + "main": "lib/index.js", + "files": [ + "lib/*.js", + "flash/swf/*.swf", + "dist/*.min.js", + "dist/*.min.js.map" + ], + "engines": { + "node": ">= 6.13.0" + }, + "keywords": [ + "aes", + "asn", + "asn.1", + "cbc", + "crypto", + "cryptography", + "csr", + "des", + "gcm", + "hmac", + "http", + "https", + "md5", + "network", + "pkcs", + "pki", + "prng", + "rc2", + "rsa", + "sha1", + "sha256", + "sha384", + "sha512", + "ssh", + "tls", + "x.509", + "x509" + ], + "scripts": { + "prepublish": "npm run build", + "build": "webpack", + "test-build": "webpack --config webpack-tests.config.js", + "test": "npm run test-node", + "test-node": "cross-env NODE_ENV=test mocha -t 30000 -R ${REPORTER:-spec} tests/unit/index.js", + "test-karma": "karma start", + "test-karma-sauce": "karma start karma-sauce.conf", + "test-server": "node tests/server.js", + "test-server-ws": "node tests/websockets/server-ws.js", + "test-server-webid": "node tests/websockets/server-webid.js", + "coverage": "rm -rf coverage && nyc --reporter=lcov --reporter=text-summary npm test", + "coverage-ci": "rm -rf coverage && nyc --reporter=lcovonly npm test", + "coverage-report": "nyc report", + "lint": "eslint *.js lib/*.js tests/*.js tests/**/*.js examples/*.js flash/*.js" + }, + "nyc": { + "exclude": [ + "tests" + ] + }, + "jspm": { + "format": "amd" + }, + "browser": { + "buffer": false, + "crypto": false, + "process": false + } +} diff --git a/node_modules/object-hash/LICENSE b/node_modules/object-hash/LICENSE new file mode 100644 index 0000000..6ea185f --- /dev/null +++ b/node_modules/object-hash/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2014 object-hash contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/object-hash/dist/object_hash.js b/node_modules/object-hash/dist/object_hash.js new file mode 100644 index 0000000..2e584c5 --- /dev/null +++ b/node_modules/object-hash/dist/object_hash.js @@ -0,0 +1 @@ +!function(e){var t;"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):("undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.objectHash=e())}(function(){return function r(o,i,u){function s(n,e){if(!i[n]){if(!o[n]){var t="function"==typeof require&&require;if(!e&&t)return t(n,!0);if(a)return a(n,!0);throw new Error("Cannot find module '"+n+"'")}e=i[n]={exports:{}};o[n][0].call(e.exports,function(e){var t=o[n][1][e];return s(t||e)},e,e.exports,r,o,i,u)}return i[n].exports}for(var a="function"==typeof require&&require,e=0;e>16),s((65280&n)>>8),s(255&n);return 2==r?s(255&(n=f(e.charAt(t))<<2|f(e.charAt(t+1))>>4)):1==r&&(s((n=f(e.charAt(t))<<10|f(e.charAt(t+1))<<4|f(e.charAt(t+2))>>2)>>8&255),s(255&n)),o},e.fromByteArray=function(e){var t,n,r,o,i=e.length%3,u="";function s(e){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(e)}for(t=0,r=e.length-i;t>18&63)+s(o>>12&63)+s(o>>6&63)+s(63&o);switch(i){case 1:u=(u+=s((n=e[e.length-1])>>2))+s(n<<4&63)+"==";break;case 2:u=(u=(u+=s((n=(e[e.length-2]<<8)+e[e.length-1])>>10))+s(n>>4&63))+s(n<<2&63)+"="}return u}}(void 0===f?this.base64js={}:f)}.call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js","/node_modules/gulp-browserify/node_modules/base64-js/lib")},{buffer:3,lYpoI2:11}],3:[function(O,e,H){!function(e,n,f,r,h,p,g,y,w){var a=O("base64-js"),i=O("ieee754");function f(e,t,n){if(!(this instanceof f))return new f(e,t,n);var r,o,i,u,s=typeof e;if("base64"===t&&"string"==s)for(e=(u=e).trim?u.trim():u.replace(/^\s+|\s+$/g,"");e.length%4!=0;)e+="=";if("number"==s)r=j(e);else if("string"==s)r=f.byteLength(e,t);else{if("object"!=s)throw new Error("First argument needs to be a number, array or string.");r=j(e.length)}if(f._useTypedArrays?o=f._augment(new Uint8Array(r)):((o=this).length=r,o._isBuffer=!0),f._useTypedArrays&&"number"==typeof e.byteLength)o._set(e);else if(C(u=e)||f.isBuffer(u)||u&&"object"==typeof u&&"number"==typeof u.length)for(i=0;i>8,n=n%256,r.push(n),r.push(t);return r}(t),e,n,r)}function v(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;o>>0)):(t+1>>0),o}function _(e,t,n,r){if(r||(d("boolean"==typeof n,"missing or invalid endian"),d(null!=t,"missing offset"),d(t+1>>8*(r?i:1-i)}function l(e,t,n,r,o){o||(d(null!=t,"missing value"),d("boolean"==typeof r,"missing or invalid endian"),d(null!=n,"missing offset"),d(n+3>>8*(r?i:3-i)&255}function B(e,t,n,r,o){o||(d(null!=t,"missing value"),d("boolean"==typeof r,"missing or invalid endian"),d(null!=n,"missing offset"),d(n+1this.length&&(r=this.length);var o=(r=e.length-t=this.length))return this[e]},f.prototype.readUInt16LE=function(e,t){return o(this,e,!0,t)},f.prototype.readUInt16BE=function(e,t){return o(this,e,!1,t)},f.prototype.readUInt32LE=function(e,t){return u(this,e,!0,t)},f.prototype.readUInt32BE=function(e,t){return u(this,e,!1,t)},f.prototype.readInt8=function(e,t){if(t||(d(null!=e,"missing offset"),d(e=this.length))return 128&this[e]?-1*(255-this[e]+1):this[e]},f.prototype.readInt16LE=function(e,t){return _(this,e,!0,t)},f.prototype.readInt16BE=function(e,t){return _(this,e,!1,t)},f.prototype.readInt32LE=function(e,t){return E(this,e,!0,t)},f.prototype.readInt32BE=function(e,t){return E(this,e,!1,t)},f.prototype.readFloatLE=function(e,t){return I(this,e,!0,t)},f.prototype.readFloatBE=function(e,t){return I(this,e,!1,t)},f.prototype.readDoubleLE=function(e,t){return A(this,e,!0,t)},f.prototype.readDoubleBE=function(e,t){return A(this,e,!1,t)},f.prototype.writeUInt8=function(e,t,n){n||(d(null!=e,"missing value"),d(null!=t,"missing offset"),d(t=this.length||(this[t]=e)},f.prototype.writeUInt16LE=function(e,t,n){s(this,e,t,!0,n)},f.prototype.writeUInt16BE=function(e,t,n){s(this,e,t,!1,n)},f.prototype.writeUInt32LE=function(e,t,n){l(this,e,t,!0,n)},f.prototype.writeUInt32BE=function(e,t,n){l(this,e,t,!1,n)},f.prototype.writeInt8=function(e,t,n){n||(d(null!=e,"missing value"),d(null!=t,"missing offset"),d(t=this.length||(0<=e?this.writeUInt8(e,t,n):this.writeUInt8(255+e+1,t,n))},f.prototype.writeInt16LE=function(e,t,n){B(this,e,t,!0,n)},f.prototype.writeInt16BE=function(e,t,n){B(this,e,t,!1,n)},f.prototype.writeInt32LE=function(e,t,n){L(this,e,t,!0,n)},f.prototype.writeInt32BE=function(e,t,n){L(this,e,t,!1,n)},f.prototype.writeFloatLE=function(e,t,n){U(this,e,t,!0,n)},f.prototype.writeFloatBE=function(e,t,n){U(this,e,t,!1,n)},f.prototype.writeDoubleLE=function(e,t,n){x(this,e,t,!0,n)},f.prototype.writeDoubleBE=function(e,t,n){x(this,e,t,!1,n)},f.prototype.fill=function(e,t,n){if(t=t||0,n=n||this.length,d("number"==typeof(e="string"==typeof(e=e||0)?e.charCodeAt(0):e)&&!isNaN(e),"value is not a number"),d(t<=n,"end < start"),n!==t&&0!==this.length){d(0<=t&&t"},f.prototype.toArrayBuffer=function(){if("undefined"==typeof Uint8Array)throw new Error("Buffer.toArrayBuffer not supported in this browser");if(f._useTypedArrays)return new f(this).buffer;for(var e=new Uint8Array(this.length),t=0,n=e.length;t=t.length||o>=e.length);o++)t[o+n]=e[o];return o}function N(e){try{return decodeURIComponent(e)}catch(e){return String.fromCharCode(65533)}}function Y(e,t){d("number"==typeof e,"cannot write a non-number as a number"),d(0<=e,"specified a negative value for writing an unsigned value"),d(e<=t,"value is larger than maximum value for type"),d(Math.floor(e)===e,"value has a fractional component")}function F(e,t,n){d("number"==typeof e,"cannot write a non-number as a number"),d(e<=t,"value larger than maximum allowed value"),d(n<=e,"value smaller than minimum allowed value"),d(Math.floor(e)===e,"value has a fractional component")}function D(e,t,n){d("number"==typeof e,"cannot write a non-number as a number"),d(e<=t,"value larger than maximum allowed value"),d(n<=e,"value smaller than minimum allowed value")}function d(e,t){if(!e)throw new Error(t||"Failed assertion")}f._augment=function(e){return e._isBuffer=!0,e._get=e.get,e._set=e.set,e.get=t.get,e.set=t.set,e.write=t.write,e.toString=t.toString,e.toLocaleString=t.toString,e.toJSON=t.toJSON,e.copy=t.copy,e.slice=t.slice,e.readUInt8=t.readUInt8,e.readUInt16LE=t.readUInt16LE,e.readUInt16BE=t.readUInt16BE,e.readUInt32LE=t.readUInt32LE,e.readUInt32BE=t.readUInt32BE,e.readInt8=t.readInt8,e.readInt16LE=t.readInt16LE,e.readInt16BE=t.readInt16BE,e.readInt32LE=t.readInt32LE,e.readInt32BE=t.readInt32BE,e.readFloatLE=t.readFloatLE,e.readFloatBE=t.readFloatBE,e.readDoubleLE=t.readDoubleLE,e.readDoubleBE=t.readDoubleBE,e.writeUInt8=t.writeUInt8,e.writeUInt16LE=t.writeUInt16LE,e.writeUInt16BE=t.writeUInt16BE,e.writeUInt32LE=t.writeUInt32LE,e.writeUInt32BE=t.writeUInt32BE,e.writeInt8=t.writeInt8,e.writeInt16LE=t.writeInt16LE,e.writeInt16BE=t.writeInt16BE,e.writeInt32LE=t.writeInt32LE,e.writeInt32BE=t.writeInt32BE,e.writeFloatLE=t.writeFloatLE,e.writeFloatBE=t.writeFloatBE,e.writeDoubleLE=t.writeDoubleLE,e.writeDoubleBE=t.writeDoubleBE,e.fill=t.fill,e.inspect=t.inspect,e.toArrayBuffer=t.toArrayBuffer,e}}.call(this,O("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},O("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(c,d,e){!function(e,t,a,n,r,o,i,u,s){var a=c("buffer").Buffer,f=4,l=new a(f);l.fill(0);d.exports={hash:function(e,t,n,r){for(var o=t(function(e,t){e.length%f!=0&&(n=e.length+(f-e.length%f),e=a.concat([e,l],n));for(var n,r=[],o=t?e.readInt32BE:e.readInt32LE,i=0;is?t=e(t):t.length>5]|=128<>>9<<4)]=t;for(var n=1732584193,r=-271733879,o=-1732584194,i=271733878,u=0;u>>32-o,n)}function c(e,t,n,r,o,i,u){return s(t&n|~t&r,e,t,o,i,u)}function d(e,t,n,r,o,i,u){return s(t&r|n&~r,e,t,o,i,u)}function h(e,t,n,r,o,i,u){return s(t^n^r,e,t,o,i,u)}function p(e,t,n,r,o,i,u){return s(n^(t|~r),e,t,o,i,u)}function g(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}b.exports=function(e){return t.hash(e,n,16)}}.call(this,w("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},w("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],7:[function(e,l,t){!function(e,t,n,r,o,i,u,s,f){var a;l.exports=a||function(e){for(var t,n=new Array(e),r=0;r>>((3&r)<<3)&255;return n}}.call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(c,d,e){!function(e,t,n,r,o,s,a,f,l){var i=c("./helpers");function u(l,c){l[c>>5]|=128<<24-c%32,l[15+(c+64>>9<<4)]=c;for(var e,t,n,r=Array(80),o=1732584193,i=-271733879,u=-1732584194,s=271733878,d=-1009589776,h=0;h>16)+(t>>16)+(n>>16)<<16|65535&n}function v(e,t){return e<>>32-t}d.exports=function(e){return i.hash(e,u,20,!0)}}.call(this,c("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},c("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],9:[function(c,d,e){!function(e,t,n,r,u,s,a,f,l){function b(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function o(e,l){var c,d=new Array(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),t=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),n=new Array(64);e[l>>5]|=128<<24-l%32,e[15+(l+64>>9<<4)]=l;for(var r,o,h=0;h>>t|e<<32-t},v=function(e,t){return e>>>t};d.exports=function(e){return i.hash(e,o,32,!0)}}.call(this,c("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},c("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],10:[function(e,t,f){!function(e,t,n,r,o,i,u,s,a){f.read=function(e,t,n,r,o){var i,u,l=8*o-r-1,c=(1<>1,s=-7,a=n?o-1:0,f=n?-1:1,o=e[t+a];for(a+=f,i=o&(1<<-s)-1,o>>=-s,s+=l;0>=-s,s+=r;0>1,d=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:c-1,h=n?1:-1,c=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,o=s):(o=Math.floor(Math.log(t)/Math.LN2),t*(n=Math.pow(2,-o))<1&&(o--,n*=2),2<=(t+=1<=o+a?d/n:d*Math.pow(2,1-a))*n&&(o++,n/=2),s<=o+a?(i=0,o=s):1<=o+a?(i=(t*n-1)*Math.pow(2,r),o+=a):(i=t*Math.pow(2,a-1)*Math.pow(2,r),o=0));8<=r;e[l+f]=255&i,f+=h,i/=256,r-=8);for(o=o<", type, " -> ", "_" + type); + + return this['_' + type](value); + }, + _object: function(object) { + var pattern = (/\[object (.*)\]/i); + var objString = Object.prototype.toString.call(object); + var objType = pattern.exec(objString); + if (!objType) { // object type did not match [object ...] + objType = 'unknown:[' + objString + ']'; + } else { + objType = objType[1]; // take only the class name + } + + objType = objType.toLowerCase(); + + var objectNumber = null; + + if ((objectNumber = context.indexOf(object)) >= 0) { + return this.dispatch('[CIRCULAR:' + objectNumber + ']'); + } else { + context.push(object); + } + + if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(object)) { + write('buffer:'); + return write(object); + } + + if(objType !== 'object' && objType !== 'function' && objType !== 'asyncfunction') { + if(this['_' + objType]) { + this['_' + objType](object); + } else if (options.ignoreUnknown) { + return write('[' + objType + ']'); + } else { + throw new Error('Unknown object type "' + objType + '"'); + } + }else{ + var keys = Object.keys(object); + if (options.unorderedObjects) { + keys = keys.sort(); + } + // Make sure to incorporate special properties, so + // Types with different prototypes will produce + // a different hash and objects derived from + // different functions (`new Foo`, `new Bar`) will + // produce different hashes. + // We never do this for native functions since some + // seem to break because of that. + if (options.respectType !== false && !isNativeFunction(object)) { + keys.splice(0, 0, 'prototype', '__proto__', 'constructor'); + } + + if (options.excludeKeys) { + keys = keys.filter(function(key) { return !options.excludeKeys(key); }); + } + + write('object:' + keys.length + ':'); + var self = this; + return keys.forEach(function(key){ + self.dispatch(key); + write(':'); + if(!options.excludeValues) { + self.dispatch(object[key]); + } + write(','); + }); + } + }, + _array: function(arr, unordered){ + unordered = typeof unordered !== 'undefined' ? unordered : + options.unorderedArrays !== false; // default to options.unorderedArrays + + var self = this; + write('array:' + arr.length + ':'); + if (!unordered || arr.length <= 1) { + return arr.forEach(function(entry) { + return self.dispatch(entry); + }); + } + + // the unordered case is a little more complicated: + // since there is no canonical ordering on objects, + // i.e. {a:1} < {a:2} and {a:1} > {a:2} are both false, + // we first serialize each entry using a PassThrough stream + // before sorting. + // also: we can’t use the same context array for all entries + // since the order of hashing should *not* matter. instead, + // we keep track of the additions to a copy of the context array + // and add all of them to the global context array when we’re done + var contextAdditions = []; + var entries = arr.map(function(entry) { + var strm = new PassThrough(); + var localContext = context.slice(); // make copy + var hasher = typeHasher(options, strm, localContext); + hasher.dispatch(entry); + // take only what was added to localContext and append it to contextAdditions + contextAdditions = contextAdditions.concat(localContext.slice(context.length)); + return strm.read().toString(); + }); + context = context.concat(contextAdditions); + entries.sort(); + return this._array(entries, false); + }, + _date: function(date){ + return write('date:' + date.toJSON()); + }, + _symbol: function(sym){ + return write('symbol:' + sym.toString()); + }, + _error: function(err){ + return write('error:' + err.toString()); + }, + _boolean: function(bool){ + return write('bool:' + bool.toString()); + }, + _string: function(string){ + write('string:' + string.length + ':'); + write(string.toString()); + }, + _function: function(fn){ + write('fn:'); + if (isNativeFunction(fn)) { + this.dispatch('[native]'); + } else { + this.dispatch(fn.toString()); + } + + if (options.respectFunctionNames !== false) { + // Make sure we can still distinguish native functions + // by their name, otherwise String and Function will + // have the same hash + this.dispatch("function-name:" + String(fn.name)); + } + + if (options.respectFunctionProperties) { + this._object(fn); + } + }, + _number: function(number){ + return write('number:' + number.toString()); + }, + _xml: function(xml){ + return write('xml:' + xml.toString()); + }, + _null: function() { + return write('Null'); + }, + _undefined: function() { + return write('Undefined'); + }, + _regexp: function(regex){ + return write('regex:' + regex.toString()); + }, + _uint8array: function(arr){ + write('uint8array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint8clampedarray: function(arr){ + write('uint8clampedarray:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int8array: function(arr){ + write('int8array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint16array: function(arr){ + write('uint16array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int16array: function(arr){ + write('int16array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint32array: function(arr){ + write('uint32array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int32array: function(arr){ + write('int32array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _float32array: function(arr){ + write('float32array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _float64array: function(arr){ + write('float64array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _arraybuffer: function(arr){ + write('arraybuffer:'); + return this.dispatch(new Uint8Array(arr)); + }, + _url: function(url) { + return write('url:' + url.toString(), 'utf8'); + }, + _map: function(map) { + write('map:'); + var arr = Array.from(map); + return this._array(arr, options.unorderedSets !== false); + }, + _set: function(set) { + write('set:'); + var arr = Array.from(set); + return this._array(arr, options.unorderedSets !== false); + }, + _file: function(file) { + write('file:'); + return this.dispatch([file.name, file.size, file.type, file.lastModfied]); + }, + _blob: function() { + if (options.ignoreUnknown) { + return write('[blob]'); + } + + throw Error('Hashing Blob objects is currently not supported\n' + + '(see https://github.com/puleos/object-hash/issues/26)\n' + + 'Use "options.replacer" or "options.ignoreUnknown"\n'); + }, + _domwindow: function() { return write('domwindow'); }, + _bigint: function(number){ + return write('bigint:' + number.toString()); + }, + /* Node.js standard native objects */ + _process: function() { return write('process'); }, + _timer: function() { return write('timer'); }, + _pipe: function() { return write('pipe'); }, + _tcp: function() { return write('tcp'); }, + _udp: function() { return write('udp'); }, + _tty: function() { return write('tty'); }, + _statwatcher: function() { return write('statwatcher'); }, + _securecontext: function() { return write('securecontext'); }, + _connection: function() { return write('connection'); }, + _zlib: function() { return write('zlib'); }, + _context: function() { return write('context'); }, + _nodescript: function() { return write('nodescript'); }, + _httpparser: function() { return write('httpparser'); }, + _dataview: function() { return write('dataview'); }, + _signal: function() { return write('signal'); }, + _fsevent: function() { return write('fsevent'); }, + _tlswrap: function() { return write('tlswrap'); }, + }; +} + +// Mini-implementation of stream.PassThrough +// We are far from having need for the full implementation, and we can +// make assumptions like "many writes, then only one final read" +// and we can ignore encoding specifics +function PassThrough() { + return { + buf: '', + + write: function(b) { + this.buf += b; + }, + + end: function(b) { + this.buf += b; + }, + + read: function() { + return this.buf; + } + }; +} diff --git a/node_modules/object-hash/package.json b/node_modules/object-hash/package.json new file mode 100644 index 0000000..a72557f --- /dev/null +++ b/node_modules/object-hash/package.json @@ -0,0 +1,53 @@ +{ + "name": "object-hash", + "version": "3.0.0", + "description": "Generate hashes from javascript objects in node and the browser.", + "homepage": "https://github.com/puleos/object-hash", + "repository": { + "type": "git", + "url": "https://github.com/puleos/object-hash" + }, + "keywords": [ + "object", + "hash", + "sha1", + "md5" + ], + "bugs": { + "url": "https://github.com/puleos/object-hash/issues" + }, + "scripts": { + "test": "node ./node_modules/.bin/mocha test", + "prepublish": "gulp dist" + }, + "author": "Scott Puleo ", + "files": [ + "index.js", + "dist/object_hash.js" + ], + "license": "MIT", + "devDependencies": { + "browserify": "^16.2.3", + "gulp": "^4.0.0", + "gulp-browserify": "^0.5.1", + "gulp-coveralls": "^0.1.4", + "gulp-exec": "^3.0.1", + "gulp-istanbul": "^1.1.3", + "gulp-jshint": "^2.0.0", + "gulp-mocha": "^5.0.0", + "gulp-rename": "^1.2.0", + "gulp-replace": "^1.0.0", + "gulp-uglify": "^3.0.0", + "jshint": "^2.8.0", + "jshint-stylish": "^2.1.0", + "karma": "^4.2.0", + "karma-chrome-launcher": "^2.2.0", + "karma-mocha": "^1.3.0", + "mocha": "^6.2.0" + }, + "engines": { + "node": ">= 6" + }, + "main": "./index.js", + "browser": "./dist/object_hash.js" +} diff --git a/node_modules/object-hash/readme.markdown b/node_modules/object-hash/readme.markdown new file mode 100644 index 0000000..c507cf8 --- /dev/null +++ b/node_modules/object-hash/readme.markdown @@ -0,0 +1,198 @@ +# object-hash + +Generate hashes from objects and values in node and the browser. Uses node.js +crypto module for hashing. Supports SHA1 and many others (depending on the platform) +as well as custom streams (e.g. CRC32). + +[![NPM](https://nodei.co/npm/object-hash.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/object-hash) + +[![Travis CI](https://secure.travis-ci.org/puleos/object-hash.png?branch=master)](https://secure.travis-ci.org/puleos/object-hash?branch=master) +[![Coverage Status](https://coveralls.io/repos/puleos/object-hash/badge.svg?branch=master&service=github)](https://coveralls.io/github/puleos/object-hash?branch=master) + +* Hash values of any type. +* Supports a keys only option for grouping similar objects with different values. + +```js +var hash = require('object-hash'); + +hash({foo: 'bar'}) // => '67b69634f9880a282c14a0f0cb7ba20cf5d677e9' +hash([1, 2, 2.718, 3.14159]) // => '136b9b88375971dff9f1af09d7356e3e04281951' +``` + +## Versioning Disclaimer + +Starting with version `1.1.8` (released April 2017), new versions will consider +the exact returned hash part of the API contract, i.e. changes that will affect +hash values will be considered `semver-major`. Previous versions may violate +that expectation. + +For more information, see [this discussion](https://github.com/puleos/object-hash/issues/30). + +## hash(value, options) + +Generate a hash from any object or type. Defaults to sha1 with hex encoding. + +* `algorithm` hash algo to be used: 'sha1', 'md5', 'passthrough'. default: sha1 + * This supports the algorithms returned by `crypto.getHashes()`. Note that the default of SHA-1 is not considered secure, and a stronger algorithm should be used if a cryptographical hash is desired. + * This also supports the `passthrough` algorith, which will return the information that would otherwise have been hashed. +* `excludeValues` {true|false} hash object keys, values ignored. default: false +* `encoding` hash encoding, supports 'buffer', 'hex', 'binary', 'base64'. default: hex +* `ignoreUnknown` {true|*false} ignore unknown object types. default: false +* `replacer` optional function that replaces values before hashing. default: accept all values +* `respectFunctionProperties` {true|false} Whether properties on functions are considered when hashing. default: true +* `respectFunctionNames` {true|false} consider `name` property of functions for hashing. default: true +* `respectType` {true|false} Whether special type attributes (`.prototype`, `.__proto__`, `.constructor`) + are hashed. default: true +* `unorderedArrays` {true|false} Sort all arrays before hashing. Note that this affects *all* collections, + i.e. including typed arrays, Sets, Maps, etc. default: false +* `unorderedSets` {true|false} Sort `Set` and `Map` instances before hashing, i.e. make + `hash(new Set([1, 2])) == hash(new Set([2, 1]))` return `true`. default: true +* `unorderedObjects` {true|false} Sort objects before hashing, i.e. make `hash({ x: 1, y: 2 }) === hash({ y: 2, x: 1 })`. default: true +* `excludeKeys` optional function for excluding specific key(s) from hashing, if true is returned then exclude from hash. default: include all keys + +## hash.sha1(value) + +Hash using the sha1 algorithm. + +Note that SHA-1 is not considered secure, and a stronger algorithm should be used if a cryptographical hash is desired. + +*Sugar method, equivalent to* `hash(value, {algorithm: 'sha1'})` + +## hash.keys(value) + +Hash object keys using the sha1 algorithm, values ignored. + +*Sugar method, equivalent to* `hash(value, {excludeValues: true})` + +## hash.MD5(value) + +Hash using the md5 algorithm. + +Note that the MD5 algorithm is not considered secure, and a stronger algorithm should be used if a cryptographical hash is desired. + +*Sugar method, equivalent to* `hash(value, {algorithm: 'md5'})` + +## hash.keysMD5(value) + +Hash object keys using the md5 algorithm, values ignored. + +Note that the MD5 algorithm is not considered secure, and a stronger algorithm should be used if a cryptographical hash is desired. + +*Sugar method, equivalent to* `hash(value, {algorithm: 'md5', excludeValues: true})` + +## hash.writeToStream(value, [options,] stream) + +Write the information that would otherwise have been hashed to a stream, e.g.: + +```js +hash.writeToStream({foo: 'bar', a: 42}, {respectType: false}, process.stdout) +// => e.g. 'object:a:number:42foo:string:bar' +``` + +## Installation + +node: + +```js +npm install object-hash +``` + +browser: */dist/object_hash.js* + +```html + + + +``` + +## Example usage + +```js +var hash = require('object-hash'); + +var peter = { name: 'Peter', stapler: false, friends: ['Joanna', 'Michael', 'Samir'] }; +var michael = { name: 'Michael', stapler: false, friends: ['Peter', 'Samir'] }; +var bob = { name: 'Bob', stapler: true, friends: [] }; + +/*** + * sha1 hex encoding (default) + */ +hash(peter); +// 14fa461bf4b98155e82adc86532938553b4d33a9 +hash(michael); +// 4b2b30e27699979ce46714253bc2213010db039c +hash(bob); +// 38d96106bc8ef3d8bd369b99bb6972702c9826d5 + +/*** + * hash object keys, values ignored + */ +hash(peter, { excludeValues: true }); +// 48f370a772c7496f6c9d2e6d92e920c87dd00a5c +hash(michael, { excludeValues: true }); +// 48f370a772c7496f6c9d2e6d92e920c87dd00a5c +hash.keys(bob); +// 48f370a772c7496f6c9d2e6d92e920c87dd00a5c + +/*** + * hash object, ignore specific key(s) + */ +hash(peter, { excludeKeys: function(key) { + if ( key === 'friends') { + return true; + } + return false; + } +}); +// 66b7d7e64871aa9fda1bdc8e88a28df797648d80 + +/*** + * md5 base64 encoding + */ +hash(peter, { algorithm: 'md5', encoding: 'base64' }); +// 6rkWaaDiG3NynWw4svGH7g== +hash(michael, { algorithm: 'md5', encoding: 'base64' }); +// djXaWpuWVJeOF8Sb6SFFNg== +hash(bob, { algorithm: 'md5', encoding: 'base64' }); +// lFzkw/IJ8/12jZI0rQeS3w== +``` + +## Legacy Browser Support + +IE <= 8 and Opera <= 11 support dropped in version 0.3.0. If you require +legacy browser support you must either use an ES5 shim or use version 0.2.5 +of this module. + +## Development + +```sh-session +git clone https://github.com/puleos/object-hash +``` + +## Node Docker Wrapper + +If you want to stand this up in a docker container, you should take at look +at the [![node-object-hash](https://github.com/bean5/node-object-hash)](https://github.com/bean5/node-object-hash) project. + +### gulp tasks + +* `gulp watch` (default) watch files, test and lint on change/add +* `gulp test` unit tests +* `gulp karma` browser unit tests +* `gulp lint` jshint +* `gulp dist` create browser version in /dist + +## License + +MIT + +## Changelog + +### v2.0.0 + +Only Node.js versions `>= 6.0.0` are being tested in CI now. +No other breaking changes were introduced. diff --git a/node_modules/once/LICENSE b/node_modules/once/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/once/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/once/README.md b/node_modules/once/README.md new file mode 100644 index 0000000..1f1ffca --- /dev/null +++ b/node_modules/once/README.md @@ -0,0 +1,79 @@ +# once + +Only call a function once. + +## usage + +```javascript +var once = require('once') + +function load (file, cb) { + cb = once(cb) + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Or add to the Function.prototype in a responsible way: + +```javascript +// only has to be done once +require('once').proto() + +function load (file, cb) { + cb = cb.once() + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Ironically, the prototype feature makes this module twice as +complicated as necessary. + +To check whether you function has been called, use `fn.called`. Once the +function is called for the first time the return value of the original +function is saved in `fn.value` and subsequent calls will continue to +return this value. + +```javascript +var once = require('once') + +function load (cb) { + cb = once(cb) + var stream = createStream() + stream.once('data', cb) + stream.once('end', function () { + if (!cb.called) cb(new Error('not found')) + }) +} +``` + +## `once.strict(func)` + +Throw an error if the function is called twice. + +Some functions are expected to be called only once. Using `once` for them would +potentially hide logical errors. + +In the example below, the `greet` function has to call the callback only once: + +```javascript +function greet (name, cb) { + // return is missing from the if statement + // when no name is passed, the callback is called twice + if (!name) cb('Hello anonymous') + cb('Hello ' + name) +} + +function log (msg) { + console.log(msg) +} + +// this will print 'Hello anonymous' but the logical error will be missed +greet(null, once(msg)) + +// once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time +greet(null, once.strict(msg)) +``` diff --git a/node_modules/once/once.js b/node_modules/once/once.js new file mode 100644 index 0000000..2354067 --- /dev/null +++ b/node_modules/once/once.js @@ -0,0 +1,42 @@ +var wrappy = require('wrappy') +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} diff --git a/node_modules/once/package.json b/node_modules/once/package.json new file mode 100644 index 0000000..16815b2 --- /dev/null +++ b/node_modules/once/package.json @@ -0,0 +1,33 @@ +{ + "name": "once", + "version": "1.4.0", + "description": "Run a function exactly one time", + "main": "once.js", + "directories": { + "test": "test" + }, + "dependencies": { + "wrappy": "1" + }, + "devDependencies": { + "tap": "^7.0.1" + }, + "scripts": { + "test": "tap test/*.js" + }, + "files": [ + "once.js" + ], + "repository": { + "type": "git", + "url": "git://github.com/isaacs/once" + }, + "keywords": [ + "once", + "function", + "one", + "single" + ], + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC" +} diff --git a/node_modules/p-limit/index.d.ts b/node_modules/p-limit/index.d.ts new file mode 100644 index 0000000..f348d7f --- /dev/null +++ b/node_modules/p-limit/index.d.ts @@ -0,0 +1,42 @@ +declare namespace pLimit { + interface Limit { + /** + The number of promises that are currently running. + */ + readonly activeCount: number; + + /** + The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + */ + readonly pendingCount: number; + + /** + Discard pending promises that are waiting to run. + + This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + + Note: This does not cancel promises that are already running. + */ + clearQueue: () => void; + + /** + @param fn - Promise-returning/async function. + @param arguments - Any arguments to pass through to `fn`. Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a lot of functions. + @returns The promise returned by calling `fn(...arguments)`. + */ + ( + fn: (...arguments: Arguments) => PromiseLike | ReturnType, + ...arguments: Arguments + ): Promise; + } +} + +/** +Run multiple promise-returning & async functions with limited concurrency. + +@param concurrency - Concurrency limit. Minimum: `1`. +@returns A `limit` function. +*/ +declare function pLimit(concurrency: number): pLimit.Limit; + +export = pLimit; diff --git a/node_modules/p-limit/index.js b/node_modules/p-limit/index.js new file mode 100644 index 0000000..c2ae52d --- /dev/null +++ b/node_modules/p-limit/index.js @@ -0,0 +1,71 @@ +'use strict'; +const Queue = require('yocto-queue'); + +const pLimit = concurrency => { + if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) { + throw new TypeError('Expected `concurrency` to be a number from 1 and up'); + } + + const queue = new Queue(); + let activeCount = 0; + + const next = () => { + activeCount--; + + if (queue.size > 0) { + queue.dequeue()(); + } + }; + + const run = async (fn, resolve, ...args) => { + activeCount++; + + const result = (async () => fn(...args))(); + + resolve(result); + + try { + await result; + } catch {} + + next(); + }; + + const enqueue = (fn, resolve, ...args) => { + queue.enqueue(run.bind(null, fn, resolve, ...args)); + + (async () => { + // This function needs to wait until the next microtask before comparing + // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously + // when the run function is dequeued and called. The comparison in the if-statement + // needs to happen asynchronously as well to get an up-to-date value for `activeCount`. + await Promise.resolve(); + + if (activeCount < concurrency && queue.size > 0) { + queue.dequeue()(); + } + })(); + }; + + const generator = (fn, ...args) => new Promise(resolve => { + enqueue(fn, resolve, ...args); + }); + + Object.defineProperties(generator, { + activeCount: { + get: () => activeCount + }, + pendingCount: { + get: () => queue.size + }, + clearQueue: { + value: () => { + queue.clear(); + } + } + }); + + return generator; +}; + +module.exports = pLimit; diff --git a/node_modules/p-limit/license b/node_modules/p-limit/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/p-limit/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/p-limit/package.json b/node_modules/p-limit/package.json new file mode 100644 index 0000000..7651473 --- /dev/null +++ b/node_modules/p-limit/package.json @@ -0,0 +1,52 @@ +{ + "name": "p-limit", + "version": "3.1.0", + "description": "Run multiple promise-returning & async functions with limited concurrency", + "license": "MIT", + "repository": "sindresorhus/p-limit", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "promise", + "limit", + "limited", + "concurrency", + "throttle", + "throat", + "rate", + "batch", + "ratelimit", + "task", + "queue", + "async", + "await", + "promises", + "bluebird" + ], + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "devDependencies": { + "ava": "^2.4.0", + "delay": "^4.4.0", + "in-range": "^2.0.0", + "random-int": "^2.0.1", + "time-span": "^4.0.0", + "tsd": "^0.13.1", + "xo": "^0.35.0" + } +} diff --git a/node_modules/p-limit/readme.md b/node_modules/p-limit/readme.md new file mode 100644 index 0000000..b283c1e --- /dev/null +++ b/node_modules/p-limit/readme.md @@ -0,0 +1,101 @@ +# p-limit + +> Run multiple promise-returning & async functions with limited concurrency + +## Install + +``` +$ npm install p-limit +``` + +## Usage + +```js +const pLimit = require('p-limit'); + +const limit = pLimit(1); + +const input = [ + limit(() => fetchSomething('foo')), + limit(() => fetchSomething('bar')), + limit(() => doSomething()) +]; + +(async () => { + // Only one promise is run at once + const result = await Promise.all(input); + console.log(result); +})(); +``` + +## API + +### pLimit(concurrency) + +Returns a `limit` function. + +#### concurrency + +Type: `number`\ +Minimum: `1`\ +Default: `Infinity` + +Concurrency limit. + +### limit(fn, ...args) + +Returns the promise returned by calling `fn(...args)`. + +#### fn + +Type: `Function` + +Promise-returning/async function. + +#### args + +Any arguments to pass through to `fn`. + +Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions. + +### limit.activeCount + +The number of promises that are currently running. + +### limit.pendingCount + +The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + +### limit.clearQueue() + +Discard pending promises that are waiting to run. + +This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + +Note: This does not cancel promises that are already running. + +## FAQ + +### How is this different from the [`p-queue`](https://github.com/sindresorhus/p-queue) package? + +This package is only about limiting the number of concurrent executions, while `p-queue` is a fully featured queue implementation with lots of different options, introspection, and ability to pause the queue. + +## Related + +- [p-queue](https://github.com/sindresorhus/p-queue) - Promise queue with concurrency control +- [p-throttle](https://github.com/sindresorhus/p-throttle) - Throttle promise-returning & async functions +- [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions +- [p-all](https://github.com/sindresorhus/p-all) - Run promise-returning & async functions concurrently with optional limited concurrency +- [More…](https://github.com/sindresorhus/promise-fun) + +--- + +
                          + + Get professional support for this package with a Tidelift subscription + +
                          + + Tidelift helps make open source sustainable for maintainers while giving companies
                          assurances about security, maintenance, and licensing for their dependencies. +
                          +
                          diff --git a/node_modules/proto3-json-serializer/CHANGELOG.md b/node_modules/proto3-json-serializer/CHANGELOG.md new file mode 100644 index 0000000..6c8913f --- /dev/null +++ b/node_modules/proto3-json-serializer/CHANGELOG.md @@ -0,0 +1,152 @@ +# Changelog + +## [2.0.2](https://github.com/googleapis/proto3-json-serializer-nodejs/compare/v2.0.1...v2.0.2) (2024-05-22) + + +### Bug Fixes + +* Properly convert repeated int64 and maps of int64 ([#96](https://github.com/googleapis/proto3-json-serializer-nodejs/issues/96)) ([1ec05fb](https://github.com/googleapis/proto3-json-serializer-nodejs/commit/1ec05fb59edfdff7531b9372dcfe14c0fe36562c)) + +## [2.0.1](https://github.com/googleapis/proto3-json-serializer-nodejs/compare/v2.0.0...v2.0.1) (2024-01-16) + + +### Bug Fixes + +* **deps:** Update dependency google-proto-files to v4 ([#82](https://github.com/googleapis/proto3-json-serializer-nodejs/issues/82)) ([72623e0](https://github.com/googleapis/proto3-json-serializer-nodejs/commit/72623e04e1043353ef952178714ced733001a06d)) +* **deps:** Update protobufjs to 7.2.5 ([a0f5c83](https://github.com/googleapis/proto3-json-serializer-nodejs/commit/a0f5c833cba654949ec5e624fad1849020cf899d)) + +## [2.0.0](https://github.com/googleapis/proto3-json-serializer-nodejs/compare/v1.1.1...v2.0.0) (2023-08-07) + + +### ⚠ BREAKING CHANGES + +* require Node 14 ([#72](https://github.com/googleapis/proto3-json-serializer-nodejs/issues/72)) + +### Miscellaneous Chores + +* Require Node 14 ([#72](https://github.com/googleapis/proto3-json-serializer-nodejs/issues/72)) ([8681834](https://github.com/googleapis/proto3-json-serializer-nodejs/commit/8681834d8bc204c40857e299570e1e5df4bc5618)) + +## [1.1.1](https://github.com/googleapis/proto3-json-serializer-nodejs/compare/v1.1.0...v1.1.1) (2023-04-25) + + +### Bug Fixes + +* Repeated field can be null in JSON ([#66](https://github.com/googleapis/proto3-json-serializer-nodejs/issues/66)) ([f81d3ab](https://github.com/googleapis/proto3-json-serializer-nodejs/commit/f81d3ab202e2a674be73db8a9b74d3eecf3bbed4)) + +## [1.1.0](https://github.com/googleapis/proto3-json-serializer-nodejs/compare/v1.0.3...v1.1.0) (2022-08-26) + + +### Features + +* option to serialize enum values as numbers ([#60](https://github.com/googleapis/proto3-json-serializer-nodejs/issues/60)) ([456b771](https://github.com/googleapis/proto3-json-serializer-nodejs/commit/456b771d5fef06d914c6e201fd9f17251e55d4d9)) + + +### Bug Fixes + +* remove pip install statements ([#1546](https://github.com/googleapis/proto3-json-serializer-nodejs/issues/1546)) ([#58](https://github.com/googleapis/proto3-json-serializer-nodejs/issues/58)) ([741d070](https://github.com/googleapis/proto3-json-serializer-nodejs/commit/741d0704f49332dd5d66206fcdf2111464fb8759)) + +## [1.0.3](https://github.com/googleapis/proto3-json-serializer-nodejs/compare/v1.0.2...v1.0.3) (2022-07-10) + + +### Bug Fixes + +* **deps:** update dependency protobufjs to v7 ([#56](https://github.com/googleapis/proto3-json-serializer-nodejs/issues/56)) ([038fea5](https://github.com/googleapis/proto3-json-serializer-nodejs/commit/038fea537c8809dc272c2352b832b5301c7b79d2)) + +## [1.0.2](https://github.com/googleapis/proto3-json-serializer-nodejs/compare/v1.0.1...v1.0.2) (2022-06-15) + + +### Bug Fixes + +* **deps:** update dependency google-proto-files to v3 ([#53](https://github.com/googleapis/proto3-json-serializer-nodejs/issues/53)) ([40fd527](https://github.com/googleapis/proto3-json-serializer-nodejs/commit/40fd527109838a21887f7a5058406244acabe938)) + +## [1.0.1](https://github.com/googleapis/proto3-json-serializer-nodejs/compare/v1.0.0...v1.0.1) (2022-06-03) + + +### Bug Fixes + +* **deps:** bump protobuf.js to ^6.11.3 ([#46](https://github.com/googleapis/proto3-json-serializer-nodejs/issues/46)) ([af8a14a](https://github.com/googleapis/proto3-json-serializer-nodejs/commit/af8a14a35c04cbef49bff806b7d906287d1d2c0d)) + +## [1.0.0](https://github.com/googleapis/proto3-json-serializer-nodejs/compare/v0.1.9...v1.0.0) (2022-05-12) + + +### ⚠ BREAKING CHANGES + +* make Node 12 minimum language version (#38) + +### Features + +* make Node 12 minimum language version ([#38](https://github.com/googleapis/proto3-json-serializer-nodejs/issues/38)) ([658d29e](https://github.com/googleapis/proto3-json-serializer-nodejs/commit/658d29e531c2d04d4007e5843aa62d9d8ee0dae8)) + +### [0.1.9](https://github.com/googleapis/proto3-json-serializer-nodejs/compare/v0.1.8...v0.1.9) (2022-05-11) + + +### Bug Fixes + +* do not use Node.js assert ([#37](https://github.com/googleapis/proto3-json-serializer-nodejs/issues/37)) ([dccfeca](https://github.com/googleapis/proto3-json-serializer-nodejs/commit/dccfeca6f3bbeec29d88319f375a734ec48aadf7)) + +### [0.1.8](https://github.com/googleapis/proto3-json-serializer-nodejs/compare/v0.1.7...v0.1.8) (2022-01-21) + + +### Bug Fixes + +* timestamp without millisecond ([#30](https://github.com/googleapis/proto3-json-serializer-nodejs/issues/30)) ([a55d0b6](https://github.com/googleapis/proto3-json-serializer-nodejs/commit/a55d0b6f98f6d1c8b7d971d0a583bbd82ea66983)) + +### [0.1.7](https://github.com/googleapis/proto3-json-serializer-nodejs/compare/v0.1.6...v0.1.7) (2022-01-14) + + +### Bug Fixes + +* keep nano second precision when maps between JSON and proto3 ([#28](https://github.com/googleapis/proto3-json-serializer-nodejs/issues/28)) ([eaa01ce](https://github.com/googleapis/proto3-json-serializer-nodejs/commit/eaa01ce92c4eefa816d1d6f8ef6ed11bd2a6364b)) + +### [0.1.6](https://www.github.com/googleapis/proto3-json-serializer-nodejs/compare/v0.1.5...v0.1.6) (2021-11-15) + + +### Bug Fixes + +* **deps:** protobufjs is a dependency for the types ([#23](https://www.github.com/googleapis/proto3-json-serializer-nodejs/issues/23)) ([06470c1](https://www.github.com/googleapis/proto3-json-serializer-nodejs/commit/06470c1df501439ec3f8bc546cd23d798604f3bd)) + +### [0.1.5](https://www.github.com/googleapis/proto3-json-serializer-nodejs/compare/v0.1.4...v0.1.5) (2021-10-26) + + +### Bug Fixes + +* JSON accept special string for NaN, Infinity ([#19](https://www.github.com/googleapis/proto3-json-serializer-nodejs/issues/19)) ([01a345b](https://www.github.com/googleapis/proto3-json-serializer-nodejs/commit/01a345b7b1d62ee65a8673737975980d274fa22a)) + +### [0.1.4](https://www.github.com/googleapis/proto3-json-serializer-nodejs/compare/v0.1.3...v0.1.4) (2021-09-20) + + +### Bug Fixes + +* do not emit empty lists to JSON ([#15](https://www.github.com/googleapis/proto3-json-serializer-nodejs/issues/15)) ([af9dfd6](https://www.github.com/googleapis/proto3-json-serializer-nodejs/commit/af9dfd65efb84cfb31af0faca805f53b0ffa9874)) + +### [0.1.3](https://www.github.com/googleapis/proto3-json-serializer-nodejs/compare/v0.1.2...v0.1.3) (2021-08-18) + + +### Bug Fixes + +* do not fail for unknown enum values ([#11](https://www.github.com/googleapis/proto3-json-serializer-nodejs/issues/11)) ([ff9f0f1](https://www.github.com/googleapis/proto3-json-serializer-nodejs/commit/ff9f0f1881b1aafacd693b4e24eaee9e56aff79c)) + +### [0.1.2](https://www.github.com/googleapis/proto3-json-serializer-nodejs/compare/v0.1.1...v0.1.2) (2021-08-17) + + +### Bug Fixes + +* use imported protobufjs in toproto3json.ts ([#9](https://www.github.com/googleapis/proto3-json-serializer-nodejs/issues/9)) ([f6c86c7](https://www.github.com/googleapis/proto3-json-serializer-nodejs/commit/f6c86c777d567d8430b09dea3282e52af24d890f)) + +### [0.1.1](https://www.github.com/googleapis/proto3-json-serializer-nodejs/compare/v0.1.0...v0.1.1) (2021-08-04) + + +### Bug Fixes + +* accept and return strings for int64 and uint64 ([#7](https://www.github.com/googleapis/proto3-json-serializer-nodejs/issues/7)) ([35689ec](https://www.github.com/googleapis/proto3-json-serializer-nodejs/commit/35689ecee55dbe6e4cf3327c535514d7fcb8332d)) + +## 0.1.0 (2021-08-03) + + +### ⚠ BREAKING CHANGES + +* proto3 JSON serializer and deserializer (#2) + +### Features + +* proto3 JSON serializer and deserializer ([#2](https://www.github.com/googleapis/proto3-json-serializer-nodejs/issues/2)) ([96255a7](https://www.github.com/googleapis/proto3-json-serializer-nodejs/commit/96255a77c7714f33cae547db9160615d7f80a233)) diff --git a/node_modules/proto3-json-serializer/LICENSE b/node_modules/proto3-json-serializer/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/proto3-json-serializer/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/proto3-json-serializer/README.md b/node_modules/proto3-json-serializer/README.md new file mode 100644 index 0000000..21544d0 --- /dev/null +++ b/node_modules/proto3-json-serializer/README.md @@ -0,0 +1,97 @@ +# proto3 JSON serializer for TypeScript / JavaScript + +This library implements proto3 JSON serialization and deserialization for +[protobuf.js](https://www.npmjs.com/package/protobufjs) protobuf objects +according to the [spec](https://developers.google.com/protocol-buffers/docs/proto3#json). + +Note that the spec requires special representation of some `google.protobuf.*` types +(`Value`, `Struct`, `Timestamp`, `Duration`, etc.), so you cannot just use `.toObject()` +since the result won't be understood by protobuf in other languages. Hence this module. + +JavaScript: + +```js +const serializer = require('proto3-json-serializer'); +``` + +TypeScript: + +```ts +import * as serializer from 'proto3-json-serializer'; +``` + +## Serialization: protobuf.js object to proto3 JSON + +```js +const root = protobuf.loadSync('test.proto'); +const Type = root.lookupType('test.Message'); +const message = Type.fromObject({...}); + +const serialized = serializer.toProto3JSON(message); +``` + +Serialization works with any object created by calling `.create()`, `.decode()`, or `.fromObject()` +for a loaded protobuf type. It relies on the `$type` field so it will not work with a static object. + +## Deserialization: proto3 JSON to protobuf.js object + +To deserialize an object from proto3 JSON, we must know its type (as returned by `root.lookupType('...')`). +Pass this type as the first parameter to `.fromProto3JSON`: + +```js +const root = protobuf.loadSync('test.proto'); +const Type = root.lookupType('test.Message'); +const json = {...}; + +const deserialized = serializer.fromProto3JSON(Type, json); +``` + +## Complete example +```js +const assert = require('assert'); +const path = require('path'); +const protobuf = require('protobufjs'); +const serializer = require('proto3-json-serializer'); + +// We'll take sample protos from google-proto-files but the code will work with any protos +const protos = require('google-proto-files'); + +// Load some proto file +const rpcProtos = protos.getProtoPath('rpc'); +const root = protobuf.loadSync([ + path.join(rpcProtos, 'status.proto'), + path.join(rpcProtos, 'error_details.proto'), +]); +const Status = root.lookupType('google.rpc.Status'); + +// If you have a protobuf object that follows proto3 JSON syntax +// https://developers.google.com/protocol-buffers/docs/proto3#json +// (this is an example of google.rpc.Status message in JSON) +const json = { + code: 3, + message: 'Test error message', + details: [ + { + '@type': 'google.rpc.BadRequest', + fieldViolations: [ + { + field: 'field', + description: 'must not be null', + }, + ], + }, + ], +}; + +// You can deserialize it into a protobuf.js object: +const deserialized = serializer.fromProto3JSON(Status, json); +console.log(deserialized); + +// And serialize it back +const serialized = serializer.toProto3JSON(deserialized); +assert.deepStrictEqual(serialized, json); +``` + +## Disclaimer + +This is not an officially supported Google project. diff --git a/node_modules/proto3-json-serializer/build/src/any.d.ts b/node_modules/proto3-json-serializer/build/src/any.d.ts new file mode 100644 index 0000000..db301d9 --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/any.d.ts @@ -0,0 +1,16 @@ +/// +import * as protobuf from 'protobufjs'; +import { ToProto3JSONOptions } from './toproto3json'; +import { JSONObject, JSONValue } from './types'; +export interface Any { + type_url: string; + value: Buffer | Uint8Array; +} +export declare function googleProtobufAnyToProto3JSON(obj: protobuf.Message & Any, options?: ToProto3JSONOptions): JSONObject; +export declare function googleProtobufAnyFromProto3JSON(root: protobuf.Root, json: JSONValue): { + type_url: string; + value: null; +} | { + type_url: string; + value: string; +}; diff --git a/node_modules/proto3-json-serializer/build/src/any.js b/node_modules/proto3-json-serializer/build/src/any.js new file mode 100644 index 0000000..d2ec56e --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/any.js @@ -0,0 +1,95 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.googleProtobufAnyFromProto3JSON = exports.googleProtobufAnyToProto3JSON = void 0; +const fromproto3json_1 = require("./fromproto3json"); +const toproto3json_1 = require("./toproto3json"); +// https://github.com/protocolbuffers/protobuf/blob/ba3836703b4a9e98e474aea2bac8c5b49b6d3b5c/python/google/protobuf/json_format.py#L850 +const specialJSON = new Set([ + 'google.protobuf.Any', + 'google.protobuf.Duration', + 'google.protobuf.FieldMask', + 'google.protobuf.ListValue', + 'google.protobuf.Struct', + 'google.protobuf.Timestamp', + 'google.protobuf.Value', +]); +function googleProtobufAnyToProto3JSON(obj, options) { + // https://developers.google.com/protocol-buffers/docs/proto3#json + // If the Any contains a value that has a special JSON mapping, it will be converted as follows: + // {"@type": xxx, "value": yyy}. + // Otherwise, the value will be converted into a JSON object, and the "@type" field will be inserted + // to indicate the actual data type. + const typeName = obj.type_url.replace(/^.*\//, ''); + let type; + try { + type = obj.$type.root.lookupType(typeName); + } + catch (err) { + throw new Error(`googleProtobufAnyToProto3JSON: cannot find type ${typeName}: ${err}`); + } + const valueMessage = type.decode(obj.value); + const valueProto3JSON = (0, toproto3json_1.toProto3JSON)(valueMessage, options); + if (specialJSON.has(typeName)) { + return { + '@type': obj.type_url, + value: valueProto3JSON, + }; + } + valueProto3JSON['@type'] = obj.type_url; + return valueProto3JSON; +} +exports.googleProtobufAnyToProto3JSON = googleProtobufAnyToProto3JSON; +function googleProtobufAnyFromProto3JSON(root, json) { + // Not all possible JSON values can hold Any, only real objects. + if (json === null || typeof json !== 'object' || Array.isArray(json)) { + throw new Error('googleProtobufAnyFromProto3JSON: must be an object to decode google.protobuf.Any'); + } + const typeUrl = json['@type']; + if (!typeUrl || typeof typeUrl !== 'string') { + throw new Error('googleProtobufAnyFromProto3JSON: JSON serialization of google.protobuf.Any must contain @type field'); + } + const typeName = typeUrl.replace(/^.*\//, ''); + let type; + try { + type = root.lookupType(typeName); + } + catch (err) { + throw new Error(`googleProtobufAnyFromProto3JSON: cannot find type ${typeName}: ${err}`); + } + let value = json; + if (specialJSON.has(typeName)) { + if (!('value' in json)) { + throw new Error(`googleProtobufAnyFromProto3JSON: JSON representation of google.protobuf.Any with type ${typeName} must contain the value field`); + } + value = json.value; + } + const valueMessage = (0, fromproto3json_1.fromProto3JSON)(type, value); + if (valueMessage === null) { + return { + type_url: typeUrl, + value: null, + }; + } + const uint8array = type.encode(valueMessage).finish(); + const buffer = Buffer.from(uint8array, 0, uint8array.byteLength); + const base64 = buffer.toString('base64'); + return { + type_url: typeUrl, + value: base64, + }; +} +exports.googleProtobufAnyFromProto3JSON = googleProtobufAnyFromProto3JSON; +//# sourceMappingURL=any.js.map \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/any.js.map b/node_modules/proto3-json-serializer/build/src/any.js.map new file mode 100644 index 0000000..59cb7d9 --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/any.js.map @@ -0,0 +1 @@ +{"version":3,"file":"any.js","sourceRoot":"","sources":["../../typescript/src/any.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,iDAAiD;AACjD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAMjC,qDAAgD;AAChD,iDAAiE;AAGjE,uIAAuI;AACvI,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC;IAC1B,qBAAqB;IACrB,0BAA0B;IAC1B,2BAA2B;IAC3B,2BAA2B;IAC3B,wBAAwB;IACxB,2BAA2B;IAC3B,uBAAuB;CACxB,CAAC,CAAC;AAOH,SAAgB,6BAA6B,CAC3C,GAA2B,EAC3B,OAA6B;IAE7B,kEAAkE;IAClE,gGAAgG;IAChG,gCAAgC;IAChC,oGAAoG;IACpG,oCAAoC;IAEpC,MAAM,QAAQ,GAAG,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;IACnD,IAAI,IAAmB,CAAC;IACxB,IAAI;QACF,IAAI,GAAG,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;KAC5C;IAAC,OAAO,GAAG,EAAE;QACZ,MAAM,IAAI,KAAK,CACb,mDAAmD,QAAQ,KAAK,GAAG,EAAE,CACtE,CAAC;KACH;IACD,MAAM,YAAY,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CA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;SACH;QACD,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;KACpB;IAED,MAAM,YAAY,GAAG,IAAA,+BAAc,EAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IACjD,IAAI,YAAY,KAAK,IAAI,EAAE;QACzB,OAAO;YACL,QAAQ,EAAE,OAAO;YACjB,KAAK,EAAE,IAAI;SACZ,CAAC;KACH;IAED,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC,MAAM,EAAE,CAAC;IACtD,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC;IACjE,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAEzC,OAAO;QACL,QAAQ,EAAE,OAAO;QACjB,KAAK,EAAE,MAAM;KACd,CAAC;AACJ,CAAC;AAtDD,0EAsDC"} \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/bytes.d.ts b/node_modules/proto3-json-serializer/build/src/bytes.d.ts new file mode 100644 index 0000000..069a490 --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/bytes.d.ts @@ -0,0 +1,3 @@ +/// +export declare function bytesToProto3JSON(obj: Buffer | Uint8Array): string; +export declare function bytesFromProto3JSON(json: string): Buffer; diff --git a/node_modules/proto3-json-serializer/build/src/bytes.js b/node_modules/proto3-json-serializer/build/src/bytes.js new file mode 100644 index 0000000..1f7c535 --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/bytes.js @@ -0,0 +1,30 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bytesFromProto3JSON = exports.bytesToProto3JSON = void 0; +function bytesToProto3JSON(obj) { + if (Buffer.isBuffer(obj)) { + return obj.toString('base64'); + } + else { + return Buffer.from(obj.buffer, 0, obj.byteLength).toString('base64'); + } +} +exports.bytesToProto3JSON = bytesToProto3JSON; +function bytesFromProto3JSON(json) { + return Buffer.from(json, 'base64'); +} +exports.bytesFromProto3JSON = bytesFromProto3JSON; +//# sourceMappingURL=bytes.js.map \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/bytes.js.map b/node_modules/proto3-json-serializer/build/src/bytes.js.map new file mode 100644 index 0000000..f90253b --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/bytes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bytes.js","sourceRoot":"","sources":["../../typescript/src/bytes.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,iDAAiD;AACjD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAEjC,SAAgB,iBAAiB,CAAC,GAAwB;IACxD,IAAI,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;QACxB,OAAO,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;KAC/B;SAAM;QACL,OAAO,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;KACtE;AACH,CAAC;AAND,8CAMC;AAED,SAAgB,mBAAmB,CAAC,IAAY;IAC9C,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;AACrC,CAAC;AAFD,kDAEC"} \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/duration.d.ts b/node_modules/proto3-json-serializer/build/src/duration.d.ts new file mode 100644 index 0000000..ef80d51 --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/duration.d.ts @@ -0,0 +1,10 @@ +import * as protobuf from 'protobufjs'; +import { FromObjectValue } from './types'; +export interface Duration { + seconds: number; + nanos?: number; +} +export declare function googleProtobufDurationToProto3JSON(obj: protobuf.Message & Duration): string; +export declare function googleProtobufDurationFromProto3JSON(json: string): { + [key: string]: FromObjectValue; +}; diff --git a/node_modules/proto3-json-serializer/build/src/duration.js b/node_modules/proto3-json-serializer/build/src/duration.js new file mode 100644 index 0000000..e69080d --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/duration.js @@ -0,0 +1,55 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.googleProtobufDurationFromProto3JSON = exports.googleProtobufDurationToProto3JSON = void 0; +function googleProtobufDurationToProto3JSON(obj) { + // seconds is an instance of Long so it won't be undefined + let durationSeconds = obj.seconds.toString(); + if (typeof obj.nanos === 'number' && obj.nanos > 0) { + // nanosStr should contain 3, 6, or 9 fractional digits. + const nanosStr = obj.nanos + .toString() + .padStart(9, '0') + .replace(/^((?:\d\d\d)+?)(?:0*)$/, '$1'); + durationSeconds += '.' + nanosStr; + } + durationSeconds += 's'; + return durationSeconds; +} +exports.googleProtobufDurationToProto3JSON = googleProtobufDurationToProto3JSON; +function googleProtobufDurationFromProto3JSON(json) { + const match = json.match(/^(\d*)(?:\.(\d*))?s$/); + if (!match) { + throw new Error(`googleProtobufDurationFromProto3JSON: incorrect value ${json} passed as google.protobuf.Duration`); + } + let seconds = 0; + let nanos = 0; + if (typeof match[1] === 'string' && match[1].length > 0) { + seconds = parseInt(match[1]); + } + if (typeof match[2] === 'string' && match[2].length > 0) { + nanos = parseInt(match[2].padEnd(9, '0')); + } + const result = {}; + if (seconds !== 0) { + result.seconds = seconds; + } + if (nanos !== 0) { + result.nanos = nanos; + } + return result; +} +exports.googleProtobufDurationFromProto3JSON = googleProtobufDurationFromProto3JSON; +//# sourceMappingURL=duration.js.map \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/duration.js.map b/node_modules/proto3-json-serializer/build/src/duration.js.map new file mode 100644 index 0000000..23ad684 --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/duration.js.map @@ -0,0 +1 @@ +{"version":3,"file":"duration.js","sourceRoot":"","sources":["../../typescript/src/duration.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,iDAAiD;AACjD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAUjC,SAAgB,kCAAkC,CAChD,GAAgC;IAEhC,0DAA0D;IAC1D,IAAI,eAAe,GAAG,GAAG,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;IAC7C,IAAI,OAAO,GAAG,CAAC,KAAK,KAAK,QAAQ,IAAI,GAAG,CAAC,KAAK,GAAG,CAAC,EAAE;QAClD,wDAAwD;QACxD,MAAM,QAAQ,GAAG,GAAG,CAAC,KAAK;aACvB,QAAQ,EAAE;aACV,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC;aAChB,OAAO,CAAC,wBAAwB,EAAE,IAAI,CAAC,CAAC;QAC3C,eAAe,IAAI,GAAG,GAAG,QAAQ,CAAC;KACnC;IACD,eAAe,IAAI,GAAG,CAAC;IACvB,OAAO,eAAe,CAAC;AACzB,CAAC;AAfD,gFAeC;AAED,SAAgB,oCAAoC,CAAC,IAAY;IAC/D,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,sBAAsB,CAAC,CAAC;IACjD,IAAI,CAAC,KAAK,EAAE;QACV,MAAM,IAAI,KAAK,CACb,yDAAyD,IAAI,qCAAqC,CACnG,CAAC;KACH;IAED,IAAI,OAAO,GAAG,CAAC,CAAC;IAChB,IAAI,KAAK,GAAG,CAAC,CAAC;IAEd,IAAI,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,QAAQ,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;QACvD,OAAO,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;KAC9B;IAED,IAAI,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,QAAQ,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;QACvD,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;KAC3C;IAED,MAAM,MAAM,GAAoB,EAAE,CAAC;IACnC,IAAI,OAAO,KAAK,CAAC,EAAE;QACjB,MAAM,CAAC,OAAO,GAAG,OAAO,CAAC;KAC1B;IACD,IAAI,KAAK,KAAK,CAAC,EAAE;QACf,MAAM,CAAC,KAAK,GAAG,KAAK,CAAC;KACtB;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AA3BD,oFA2BC"} \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/enum.d.ts b/node_modules/proto3-json-serializer/build/src/enum.d.ts new file mode 100644 index 0000000..802627d --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/enum.d.ts @@ -0,0 +1,4 @@ +import * as protobuf from 'protobufjs'; +import { JSONValue } from './types'; +export declare function resolveEnumValueToString(enumType: protobuf.Enum, enumValue: JSONValue): string | number; +export declare function resolveEnumValueToNumber(enumType: protobuf.Enum, enumValue: JSONValue): string | number; diff --git a/node_modules/proto3-json-serializer/build/src/enum.js b/node_modules/proto3-json-serializer/build/src/enum.js new file mode 100644 index 0000000..c0b9d85 --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/enum.js @@ -0,0 +1,52 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveEnumValueToNumber = exports.resolveEnumValueToString = void 0; +function resolveEnumValueToString(enumType, enumValue) { + // for unknown enum values, do not fail and try to do the best we could. + // protobuf.js fromObject() will likely ignore unknown values, but at least + // we won't fail. + if (typeof enumValue === 'number') { + const value = enumType.valuesById[enumValue]; + if (typeof value === 'undefined') { + // unknown value, cannot convert to string, returning number as is + return enumValue; + } + return value; + } + if (typeof enumValue === 'string') { + // for strings, just accept what we got + return enumValue; + } + throw new Error('resolveEnumValueToString: enum value must be a string or a number'); +} +exports.resolveEnumValueToString = resolveEnumValueToString; +function resolveEnumValueToNumber(enumType, enumValue) { + if (typeof enumValue === 'number') { + // return as is + return enumValue; + } + if (typeof enumValue === 'string') { + const num = enumType.values[enumValue]; + if (typeof num === 'undefined') { + // unknown value, cannot convert to number, returning string as is + return enumValue; + } + return num; + } + throw new Error('resolveEnumValueToNumber: enum value must be a string or a number'); +} +exports.resolveEnumValueToNumber = resolveEnumValueToNumber; +//# sourceMappingURL=enum.js.map \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/enum.js.map b/node_modules/proto3-json-serializer/build/src/enum.js.map new file mode 100644 index 0000000..8e7c903 --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/enum.js.map @@ -0,0 +1 @@ +{"version":3,"file":"enum.js","sourceRoot":"","sources":["../../typescript/src/enum.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,iDAAiD;AACjD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAKjC,SAAgB,wBAAwB,CACtC,QAAuB,EACvB,SAAoB;IAEpB,wEAAwE;IACxE,2EAA2E;IAC3E,iBAAiB;IACjB,IAAI,OAAO,SAAS,KAAK,QAAQ,EAAE;QACjC,MAAM,KAAK,GAAG,QAAQ,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC;QAC7C,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;YAChC,kEAAkE;YAClE,OAAO,SAAS,CAAC;SAClB;QACD,OAAO,KAAK,CAAC;KACd;IACD,IAAI,OAAO,SAAS,KAAK,QAAQ,EAAE;QACjC,uCAAuC;QACvC,OAAO,SAAS,CAAC;KAClB;IACD,MAAM,IAAI,KAAK,CACb,mEAAmE,CACpE,CAAC;AACJ,CAAC;AAtBD,4DAsBC;AAED,SAAgB,wBAAwB,CACtC,QAAuB,EACvB,SAAoB;IAEpB,IAAI,OAAO,SAAS,KAAK,QAAQ,EAAE;QACjC,eAAe;QACf,OAAO,SAAS,CAAC;KAClB;IACD,IAAI,OAAO,SAAS,KAAK,QAAQ,EAAE;QACjC,MAAM,GAAG,GAAG,QAAQ,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QACvC,IAAI,OAAO,GAAG,KAAK,WAAW,EAAE;YAC9B,kEAAkE;YAClE,OAAO,SAAS,CAAC;SAClB;QACD,OAAO,GAAG,CAAC;KACZ;IACD,MAAM,IAAI,KAAK,CACb,mEAAmE,CACpE,CAAC;AACJ,CAAC;AAnBD,4DAmBC"} \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/fieldmask.d.ts b/node_modules/proto3-json-serializer/build/src/fieldmask.d.ts new file mode 100644 index 0000000..4b86a24 --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/fieldmask.d.ts @@ -0,0 +1,8 @@ +import * as protobuf from 'protobufjs'; +export interface FieldMask { + paths: string[]; +} +export declare function googleProtobufFieldMaskToProto3JSON(obj: protobuf.Message & FieldMask): string; +export declare function googleProtobufFieldMaskFromProto3JSON(json: string): { + paths: string[]; +}; diff --git a/node_modules/proto3-json-serializer/build/src/fieldmask.js b/node_modules/proto3-json-serializer/build/src/fieldmask.js new file mode 100644 index 0000000..856cf8f --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/fieldmask.js @@ -0,0 +1,27 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.googleProtobufFieldMaskFromProto3JSON = exports.googleProtobufFieldMaskToProto3JSON = void 0; +function googleProtobufFieldMaskToProto3JSON(obj) { + return obj.paths.join(','); +} +exports.googleProtobufFieldMaskToProto3JSON = googleProtobufFieldMaskToProto3JSON; +function googleProtobufFieldMaskFromProto3JSON(json) { + return { + paths: json.split(','), + }; +} +exports.googleProtobufFieldMaskFromProto3JSON = googleProtobufFieldMaskFromProto3JSON; +//# sourceMappingURL=fieldmask.js.map \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/fieldmask.js.map b/node_modules/proto3-json-serializer/build/src/fieldmask.js.map new file mode 100644 index 0000000..2fa53a2 --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/fieldmask.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fieldmask.js","sourceRoot":"","sources":["../../typescript/src/fieldmask.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,iDAAiD;AACjD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAQjC,SAAgB,mCAAmC,CACjD,GAAiC;IAEjC,OAAO,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC;AAJD,kFAIC;AAED,SAAgB,qCAAqC,CAAC,IAAY;IAChE,OAAO;QACL,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC;KACvB,CAAC;AACJ,CAAC;AAJD,sFAIC"} \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/fromproto3json.d.ts b/node_modules/proto3-json-serializer/build/src/fromproto3json.d.ts new file mode 100644 index 0000000..93a9c30 --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/fromproto3json.d.ts @@ -0,0 +1,4 @@ +import * as protobuf from 'protobufjs'; +import { FromObjectValue, JSONValue } from './types'; +export declare function fromProto3JSONToInternalRepresentation(type: protobuf.Type | protobuf.Enum | string, json: JSONValue): FromObjectValue; +export declare function fromProto3JSON(type: protobuf.Type, json: JSONValue): protobuf.Message<{}> | null; diff --git a/node_modules/proto3-json-serializer/build/src/fromproto3json.js b/node_modules/proto3-json-serializer/build/src/fromproto3json.js new file mode 100644 index 0000000..8b761ff --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/fromproto3json.js @@ -0,0 +1,163 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromProto3JSON = exports.fromProto3JSONToInternalRepresentation = void 0; +const any_1 = require("./any"); +const bytes_1 = require("./bytes"); +const enum_1 = require("./enum"); +const value_1 = require("./value"); +const util_1 = require("./util"); +const duration_1 = require("./duration"); +const timestamp_1 = require("./timestamp"); +const wrappers_1 = require("./wrappers"); +const fieldmask_1 = require("./fieldmask"); +function fromProto3JSONToInternalRepresentation(type, json) { + const fullyQualifiedTypeName = typeof type === 'string' ? type : (0, util_1.getFullyQualifiedTypeName)(type); + if (typeof type !== 'string' && 'values' in type) { + // type is an Enum + if (fullyQualifiedTypeName === '.google.protobuf.NullValue') { + return 'NULL_VALUE'; + } + return (0, enum_1.resolveEnumValueToString)(type, json); + } + if (typeof type !== 'string') { + type.resolveAll(); + } + if (typeof type === 'string') { + return json; + } + // Types that require special handling according to + // https://developers.google.com/protocol-buffers/docs/proto3#json + // Types that can have meaningful "null" value + if (fullyQualifiedTypeName === '.google.protobuf.Value') { + return (0, value_1.googleProtobufValueFromProto3JSON)(json); + } + if (util_1.wrapperTypes.has(fullyQualifiedTypeName)) { + if ((json !== null && typeof json === 'object') || Array.isArray(json)) { + throw new Error(`fromProto3JSONToInternalRepresentation: JSON representation for ${fullyQualifiedTypeName} expects a string, a number, or a boolean, but got ${typeof json}`); + } + return (0, wrappers_1.wrapperFromProto3JSON)(fullyQualifiedTypeName, json); + } + if (json === null) { + return null; + } + // Types that cannot be "null" + if (fullyQualifiedTypeName === '.google.protobuf.Any') { + return (0, any_1.googleProtobufAnyFromProto3JSON)(type.root, json); + } + if (fullyQualifiedTypeName === '.google.protobuf.Struct') { + if (typeof json !== 'object') { + throw new Error(`fromProto3JSONToInternalRepresentation: google.protobuf.Struct must be an object but got ${typeof json}`); + } + if (Array.isArray(json)) { + throw new Error('fromProto3JSONToInternalRepresentation: google.protobuf.Struct must be an object but got an array'); + } + return (0, value_1.googleProtobufStructFromProto3JSON)(json); + } + if (fullyQualifiedTypeName === '.google.protobuf.ListValue') { + if (!Array.isArray(json)) { + throw new Error(`fromProto3JSONToInternalRepresentation: google.protobuf.ListValue must be an array but got ${typeof json}`); + } + return (0, value_1.googleProtobufListValueFromProto3JSON)(json); + } + if (fullyQualifiedTypeName === '.google.protobuf.Duration') { + if (typeof json !== 'string') { + throw new Error(`fromProto3JSONToInternalRepresentation: google.protobuf.Duration must be a string but got ${typeof json}`); + } + return (0, duration_1.googleProtobufDurationFromProto3JSON)(json); + } + if (fullyQualifiedTypeName === '.google.protobuf.Timestamp') { + if (typeof json !== 'string') { + throw new Error(`fromProto3JSONToInternalRepresentation: google.protobuf.Timestamp must be a string but got ${typeof json}`); + } + return (0, timestamp_1.googleProtobufTimestampFromProto3JSON)(json); + } + if (fullyQualifiedTypeName === '.google.protobuf.FieldMask') { + if (typeof json !== 'string') { + throw new Error(`fromProto3JSONToInternalRepresentation: google.protobuf.FieldMask must be a string but got ${typeof json}`); + } + return (0, fieldmask_1.googleProtobufFieldMaskFromProto3JSON)(json); + } + const result = {}; + for (const [key, value] of Object.entries(json)) { + const field = type.fields[key]; + if (!field) { + continue; + } + const resolvedType = field.resolvedType; + const fieldType = field.type; + if (field.repeated) { + if (value === null) { + result[key] = []; + } + else { + if (!Array.isArray(value)) { + throw new Error(`fromProto3JSONToInternalRepresentation: expected an array for field ${key}`); + } + result[key] = value.map(element => fromProto3JSONToInternalRepresentation(resolvedType || fieldType, element)); + } + } + else if (field.map) { + const map = {}; + for (const [mapKey, mapValue] of Object.entries(value)) { + map[mapKey] = fromProto3JSONToInternalRepresentation(resolvedType || fieldType, mapValue); + } + result[key] = map; + } + else if (fieldType.match(/^(?:(?:(?:u?int|fixed)(?:32|64))|float|double)$/)) { + if (typeof value !== 'number' && typeof value !== 'string') { + throw new Error(`fromProto3JSONToInternalRepresentation: field ${key} of type ${field.type} cannot contain value ${value}`); + } + result[key] = value; + } + else if (fieldType === 'string') { + if (typeof value !== 'string') { + throw new Error(`fromProto3JSONToInternalRepresentation: field ${key} of type ${field.type} cannot contain value ${value}`); + } + result[key] = value; + } + else if (fieldType === 'bool') { + if (typeof value !== 'boolean') { + throw new Error(`fromProto3JSONToInternalRepresentation: field ${key} of type ${field.type} cannot contain value ${value}`); + } + result[key] = value; + } + else if (fieldType === 'bytes') { + if (typeof value !== 'string') { + throw new Error(`fromProto3JSONToInternalRepresentation: field ${key} of type ${field.type} cannot contain value ${value}`); + } + result[key] = (0, bytes_1.bytesFromProto3JSON)(value); + } + else { + // Message type + (0, util_1.assert)(resolvedType !== null, `Expected to be able to resolve type for field ${field.name}`); + const deserializedValue = fromProto3JSONToInternalRepresentation(resolvedType, value); + result[key] = deserializedValue; + } + } + return result; +} +exports.fromProto3JSONToInternalRepresentation = fromProto3JSONToInternalRepresentation; +function fromProto3JSON(type, json) { + const internalRepr = fromProto3JSONToInternalRepresentation(type, json); + if (internalRepr === null) { + return null; + } + // We only expect a real object here sine all special cases should be already resolved. Everything else is an internal error + (0, util_1.assert)(typeof internalRepr === 'object' && !Array.isArray(internalRepr), `fromProto3JSON: expected an object, not ${json}`); + return type.fromObject(internalRepr); +} +exports.fromProto3JSON = fromProto3JSON; +//# sourceMappingURL=fromproto3json.js.map \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/fromproto3json.js.map b/node_modules/proto3-json-serializer/build/src/fromproto3json.js.map new file mode 100644 index 0000000..6c0fc47 --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/fromproto3json.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fromproto3json.js","sourceRoot":"","sources":["../../typescript/src/fromproto3json.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,iDAAiD;AACjD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA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,GAAG,CAAC,GAAG,iBAAiB,CAAC;SACjC;KACF;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AApLD,wFAoLC;AAED,SAAgB,cAAc,CAAC,IAAmB,EAAE,IAAe;IACjE,MAAM,YAAY,GAAG,sCAAsC,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACxE,IAAI,YAAY,KAAK,IAAI,EAAE;QACzB,OAAO,IAAI,CAAC;KACb;IACD,4HAA4H;IAC5H,IAAA,aAAM,EACJ,OAAO,YAAY,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,EAChE,2CAA2C,IAAI,EAAE,CAClD,CAAC;IACF,OAAO,IAAI,CAAC,UAAU,CAAC,YAAkB,CAAC,CAAC;AAC7C,CAAC;AAXD,wCAWC"} \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/index.d.ts b/node_modules/proto3-json-serializer/build/src/index.d.ts new file mode 100644 index 0000000..0238dff --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/index.d.ts @@ -0,0 +1,3 @@ +export { JSONObject, JSONValue } from './types'; +export { toProto3JSON, ToProto3JSONOptions } from './toproto3json'; +export { fromProto3JSON } from './fromproto3json'; diff --git a/node_modules/proto3-json-serializer/build/src/index.js b/node_modules/proto3-json-serializer/build/src/index.js new file mode 100644 index 0000000..3f2fcaa --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/index.js @@ -0,0 +1,21 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromProto3JSON = exports.toProto3JSON = void 0; +var toproto3json_1 = require("./toproto3json"); +Object.defineProperty(exports, "toProto3JSON", { enumerable: true, get: function () { return toproto3json_1.toProto3JSON; } }); +var fromproto3json_1 = require("./fromproto3json"); +Object.defineProperty(exports, "fromProto3JSON", { enumerable: true, get: function () { return fromproto3json_1.fromProto3JSON; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/index.js.map b/node_modules/proto3-json-serializer/build/src/index.js.map new file mode 100644 index 0000000..e4a5b91 --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../typescript/src/index.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,iDAAiD;AACjD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAGjC,+CAAiE;AAAzD,4GAAA,YAAY,OAAA;AACpB,mDAAgD;AAAxC,gHAAA,cAAc,OAAA"} \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/timestamp.d.ts b/node_modules/proto3-json-serializer/build/src/timestamp.d.ts new file mode 100644 index 0000000..4aeee23 --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/timestamp.d.ts @@ -0,0 +1,10 @@ +import * as protobuf from 'protobufjs'; +import { FromObjectValue } from './types'; +export interface Timestamp { + seconds: number; + nanos?: number; +} +export declare function googleProtobufTimestampToProto3JSON(obj: protobuf.Message & Timestamp): string; +export declare function googleProtobufTimestampFromProto3JSON(json: string): { + [key: string]: FromObjectValue; +}; diff --git a/node_modules/proto3-json-serializer/build/src/timestamp.js b/node_modules/proto3-json-serializer/build/src/timestamp.js new file mode 100644 index 0000000..dbffeda --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/timestamp.js @@ -0,0 +1,57 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.googleProtobufTimestampFromProto3JSON = exports.googleProtobufTimestampToProto3JSON = void 0; +function googleProtobufTimestampToProto3JSON(obj) { + var _a; + // seconds is an instance of Long so it won't be undefined + const durationSeconds = obj.seconds; + const date = new Date(durationSeconds * 1000).toISOString(); + // Pad leading zeros if nano string length is less than 9. + let nanos = (_a = obj.nanos) === null || _a === void 0 ? void 0 : _a.toString().padStart(9, '0'); + // Trim the unsignificant zeros and keep 3, 6, or 9 decimal digits. + while (nanos && nanos.length > 3 && nanos.endsWith('000')) { + nanos = nanos.slice(0, -3); + } + return date.replace(/(?:\.\d{0,9})/, '.' + nanos); +} +exports.googleProtobufTimestampToProto3JSON = googleProtobufTimestampToProto3JSON; +function googleProtobufTimestampFromProto3JSON(json) { + const match = json.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?/); + if (!match) { + throw new Error(`googleProtobufDurationFromProto3JSON: incorrect value ${json} passed as google.protobuf.Duration`); + } + const date = new Date(json); + const millisecondsSinceEpoch = date.getTime(); + const seconds = Math.floor(millisecondsSinceEpoch / 1000); + // The fractional seconds in the JSON timestamps can go up to 9 digits (i.e. up to 1 nanosecond resolution). + // However, Javascript Date object represent any date and time to millisecond precision. + // To keep the precision, we extract the fractional seconds and append 0 until the length is equal to 9. + let nanos = 0; + const secondsFromDate = json.split('.')[1]; + if (secondsFromDate) { + nanos = parseInt(secondsFromDate.slice(0, -1).padEnd(9, '0')); + } + const result = {}; + if (seconds !== 0) { + result.seconds = seconds; + } + if (nanos !== 0) { + result.nanos = nanos; + } + return result; +} +exports.googleProtobufTimestampFromProto3JSON = googleProtobufTimestampFromProto3JSON; +//# sourceMappingURL=timestamp.js.map \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/timestamp.js.map b/node_modules/proto3-json-serializer/build/src/timestamp.js.map new file mode 100644 index 0000000..b0d224b --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/timestamp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"timestamp.js","sourceRoot":"","sources":["../../typescript/src/timestamp.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,iDAAiD;AACjD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAUjC,SAAgB,mCAAmC,CACjD,GAAiC;;IAEjC,0DAA0D;IAC1D,MAAM,eAAe,GAAG,GAAG,CAAC,OAAO,CAAC;IACpC,MAAM,IAAI,GAAG,IAAI,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC;IAC5D,0DAA0D;IAC1D,IAAI,KAAK,GAAG,MAAA,GAAG,CAAC,KAAK,0CAAE,QAAQ,GAAG,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IACnD,mEAAmE;IACnE,OAAO,KAAK,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE;QACzD,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;KAC5B;IACD,OAAO,IAAI,CAAC,OAAO,CAAC,eAAe,EAAE,GAAG,GAAG,KAAK,CAAC,CAAC;AACpD,CAAC;AAbD,kFAaC;AAED,SAAgB,qCAAqC,CAAC,IAAY;IAChE,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,gDAAgD,CAAC,CAAC;IAC3E,IAAI,CAAC,KAAK,EAAE;QACV,MAAM,IAAI,KAAK,CACb,yDAAyD,IAAI,qCAAqC,CACnG,CAAC;KACH;IACD,MAAM,IAAI,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;IAC5B,MAAM,sBAAsB,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;IAC9C,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,sBAAsB,GAAG,IAAI,CAAC,CAAC;IAC1D,4GAA4G;IAC5G,wFAAwF;IACxF,wGAAwG;IACxG,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,MAAM,eAAe,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAC3C,IAAI,eAAe,EAAE;QACnB,KAAK,GAAG,QAAQ,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;KAC/D;IACD,MAAM,MAAM,GAAoB,EAAE,CAAC;IACnC,IAAI,OAAO,KAAK,CAAC,EAAE;QACjB,MAAM,CAAC,OAAO,GAAG,OAAO,CAAC;KAC1B;IACD,IAAI,KAAK,KAAK,CAAC,EAAE;QACf,MAAM,CAAC,KAAK,GAAG,KAAK,CAAC;KACtB;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AA1BD,sFA0BC"} \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/toproto3json.d.ts b/node_modules/proto3-json-serializer/build/src/toproto3json.d.ts new file mode 100644 index 0000000..fe06c38 --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/toproto3json.d.ts @@ -0,0 +1,6 @@ +import * as protobuf from 'protobufjs'; +import { JSONValue } from './types'; +export interface ToProto3JSONOptions { + numericEnums: boolean; +} +export declare function toProto3JSON(obj: protobuf.Message, options?: ToProto3JSONOptions): JSONValue; diff --git a/node_modules/proto3-json-serializer/build/src/toproto3json.js b/node_modules/proto3-json-serializer/build/src/toproto3json.js new file mode 100644 index 0000000..ba61bbe --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/toproto3json.js @@ -0,0 +1,143 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toProto3JSON = void 0; +const any_1 = require("./any"); +const bytes_1 = require("./bytes"); +const util_1 = require("./util"); +const enum_1 = require("./enum"); +const value_1 = require("./value"); +const duration_1 = require("./duration"); +const timestamp_1 = require("./timestamp"); +const wrappers_1 = require("./wrappers"); +const fieldmask_1 = require("./fieldmask"); +// Convert a single value, which might happen to be an instance of Long, to JSONValue +function convertSingleValue(value) { + var _a; + if (typeof value === 'object') { + if (((_a = value === null || value === void 0 ? void 0 : value.constructor) === null || _a === void 0 ? void 0 : _a.name) === 'Long') { + return value.toString(); + } + throw new Error(`toProto3JSON: don't know how to convert value ${value}`); + } + return value; +} +function toProto3JSON(obj, options) { + const objType = obj.$type; + if (!objType) { + throw new Error('Cannot serialize object to proto3 JSON since its .$type is unknown. Use Type.fromObject(obj) before calling toProto3JSON.'); + } + objType.resolveAll(); + const typeName = (0, util_1.getFullyQualifiedTypeName)(objType); + // Types that require special handling according to + // https://developers.google.com/protocol-buffers/docs/proto3#json + if (typeName === '.google.protobuf.Any') { + return (0, any_1.googleProtobufAnyToProto3JSON)(obj, options); + } + if (typeName === '.google.protobuf.Value') { + return (0, value_1.googleProtobufValueToProto3JSON)(obj); + } + if (typeName === '.google.protobuf.Struct') { + return (0, value_1.googleProtobufStructToProto3JSON)(obj); + } + if (typeName === '.google.protobuf.ListValue') { + return (0, value_1.googleProtobufListValueToProto3JSON)(obj); + } + if (typeName === '.google.protobuf.Duration') { + return (0, duration_1.googleProtobufDurationToProto3JSON)(obj); + } + if (typeName === '.google.protobuf.Timestamp') { + return (0, timestamp_1.googleProtobufTimestampToProto3JSON)(obj); + } + if (typeName === '.google.protobuf.FieldMask') { + return (0, fieldmask_1.googleProtobufFieldMaskToProto3JSON)(obj); + } + if (util_1.wrapperTypes.has(typeName)) { + return (0, wrappers_1.wrapperToProto3JSON)(obj); + } + const result = {}; + for (const [key, value] of Object.entries(obj)) { + const field = objType.fields[key]; + const fieldResolvedType = field.resolvedType; + const fieldFullyQualifiedTypeName = fieldResolvedType + ? (0, util_1.getFullyQualifiedTypeName)(fieldResolvedType) + : null; + if (value === null) { + result[key] = null; + continue; + } + if (Array.isArray(value)) { + if (value.length === 0) { + // ignore repeated fields with no values + continue; + } + // if the repeated value has a complex type, convert it to proto3 JSON, otherwise use as is + result[key] = value.map(fieldResolvedType + ? element => { + return toProto3JSON(element, options); + } + : convertSingleValue); + continue; + } + if (field.map) { + const map = {}; + for (const [mapKey, mapValue] of Object.entries(value)) { + // if the map value has a complex type, convert it to proto3 JSON, otherwise use as is + map[mapKey] = fieldResolvedType + ? toProto3JSON(mapValue, options) + : convertSingleValue(mapValue); + } + result[key] = map; + continue; + } + if (fieldFullyQualifiedTypeName === '.google.protobuf.NullValue') { + result[key] = null; + continue; + } + if (fieldResolvedType && 'values' in fieldResolvedType && value !== null) { + if (options === null || options === void 0 ? void 0 : options.numericEnums) { + result[key] = (0, enum_1.resolveEnumValueToNumber)(fieldResolvedType, value); + } + else { + result[key] = (0, enum_1.resolveEnumValueToString)(fieldResolvedType, value); + } + continue; + } + if (fieldResolvedType) { + result[key] = toProto3JSON(value, options); + continue; + } + if (typeof value === 'string' || + typeof value === 'number' || + typeof value === 'boolean' || + value === null) { + if (typeof value === 'number' && !Number.isFinite(value)) { + result[key] = value.toString(); + continue; + } + result[key] = value; + continue; + } + if (Buffer.isBuffer(value) || value instanceof Uint8Array) { + result[key] = (0, bytes_1.bytesToProto3JSON)(value); + continue; + } + result[key] = convertSingleValue(value); + continue; + } + return result; +} +exports.toProto3JSON = toProto3JSON; +//# sourceMappingURL=toproto3json.js.map \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/toproto3json.js.map b/node_modules/proto3-json-serializer/build/src/toproto3json.js.map new file mode 100644 index 0000000..35cf40a --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/toproto3json.js.map @@ -0,0 +1 @@ +{"version":3,"file":"toproto3json.js","sourceRoot":"","sources":["../../typescript/src/toproto3json.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,iDAAiD;AACjD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAIjC,+BAAyD;AACzD,mCAA0C;AAC1C,iCAA+D;AAC/D,iCAA0E;AAC1E,mCAOiB;AACjB,yCAAwE;AACxE,2CAA2E;AAC3E,yCAMoB;AACpB,2CAA2E;AAM3E,qFAAqF;AACrF,SAAS,kBAAkB,CAAC,KAAyB;;IACnD,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC7B,IAAI,CAAA,MAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,WAAW,0CAAE,IAAI,MAAK,MAAM,EAAE;YACvC,OAAQ,KAAkB,CAAC,QAAQ,EAAE,CAAC;SACvC;QACD,MAAM,IAAI,KAAK,CAAC,iDAAiD,KAAK,EAAE,CAAC,CAAC;KAC3E;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAgB,YAAY,CAC1B,GAAqB,EACrB,OAA6B;IAE7B,MAAM,OAAO,GAAG,GAAG,CAAC,KAAK,CAAC;IAC1B,IAAI,CAAC,OAAO,EAAE;QACZ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AAE,YAAY,EAAE;gBACzB,MAAM,CAAC,GAAG,CAAC,GAAG,IAAA,+BAAwB,EAAC,iBAAiB,EAAE,KAAK,CAAC,CAAC;aAClE;iBAAM;gBACL,MAAM,CAAC,GAAG,CAAC,GAAG,IAAA,+BAAwB,EAAC,iBAAiB,EAAE,KAAK,CAAC,CAAC;aAClE;YACD,SAAS;SACV;QACD,IAAI,iBAAiB,EAAE;YACrB,MAAM,CAAC,GAAG,CAAC,GAAG,YAAY,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;YAC3C,SAAS;SACV;QACD,IACE,OAAO,KAAK,KAAK,QAAQ;YACzB,OAAO,KAAK,KAAK,QAAQ;YACzB,OAAO,KAAK,KAAK,SAAS;YAC1B,KAAK,KAAK,IAAI,EACd;YACA,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE;gBACxD,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,QAAQ,EAAE,CAAC;gBAC/B,SAAS;aACV;YACD,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;YACpB,SAAS;SACV;QACD,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,YAAY,UAAU,EAAE;YACzD,MAAM,CAAC,GAAG,CAAC,GAAG,IAAA,yBAAiB,EAAC,KAAK,CAAC,CAAC;YACvC,SAAS;SACV;QACD,MAAM,CAAC,GAAG,CAAC,GAAG,kBAAkB,CAAC,KAAK,CAAC,CAAC;QACxC,SAAS;KACV;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAxID,oCAwIC"} \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/types.d.ts b/node_modules/proto3-json-serializer/build/src/types.d.ts new file mode 100644 index 0000000..4815de3 --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/types.d.ts @@ -0,0 +1,13 @@ +/// +export type JSONValue = string | number | boolean | null | JSONValue[] | { + [key: string]: JSONValue; +}; +export interface JSONObject { + [key: string]: JSONValue; +} +export type FromObjectValue = string | number | boolean | null | FromObjectValue[] | Buffer | Uint8Array | { + [key: string]: FromObjectValue; +}; +export interface LongStub { + toString: () => string; +} diff --git a/node_modules/proto3-json-serializer/build/src/types.js b/node_modules/proto3-json-serializer/build/src/types.js new file mode 100644 index 0000000..bf8c4ae --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/types.js @@ -0,0 +1,16 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/types.js.map b/node_modules/proto3-json-serializer/build/src/types.js.map new file mode 100644 index 0000000..608566c --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../typescript/src/types.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,iDAAiD;AACjD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC"} \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/util.d.ts b/node_modules/proto3-json-serializer/build/src/util.d.ts new file mode 100644 index 0000000..b417a09 --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/util.d.ts @@ -0,0 +1,3 @@ +export declare function getFullyQualifiedTypeName(type: protobuf.Type | protobuf.Namespace | protobuf.Enum): string; +export declare const wrapperTypes: Set; +export declare function assert(assertion: boolean, message: string): void; diff --git a/node_modules/proto3-json-serializer/build/src/util.js b/node_modules/proto3-json-serializer/build/src/util.js new file mode 100644 index 0000000..fadd9e0 --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/util.js @@ -0,0 +1,44 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.assert = exports.wrapperTypes = exports.getFullyQualifiedTypeName = void 0; +function getFullyQualifiedTypeName(type) { + // We assume that the protobuf package tree cannot have cycles. + let fullyQualifiedTypeName = ''; + while (type.parent) { + fullyQualifiedTypeName = `.${type.name}${fullyQualifiedTypeName}`; + type = type.parent; + } + return fullyQualifiedTypeName; +} +exports.getFullyQualifiedTypeName = getFullyQualifiedTypeName; +exports.wrapperTypes = new Set([ + '.google.protobuf.DoubleValue', + '.google.protobuf.FloatValue', + '.google.protobuf.Int64Value', + '.google.protobuf.UInt64Value', + '.google.protobuf.Int32Value', + '.google.protobuf.UInt32Value', + '.google.protobuf.BoolValue', + '.google.protobuf.StringValue', + '.google.protobuf.BytesValue', +]); +function assert(assertion, message) { + if (!assertion) { + throw new Error(message); + } +} +exports.assert = assert; +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/util.js.map b/node_modules/proto3-json-serializer/build/src/util.js.map new file mode 100644 index 0000000..10ab219 --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/util.js.map @@ -0,0 +1 @@ +{"version":3,"file":"util.js","sourceRoot":"","sources":["../../typescript/src/util.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,iDAAiD;AACjD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAEjC,SAAgB,yBAAyB,CACvC,IAAwD;IAExD,+DAA+D;IAC/D,IAAI,sBAAsB,GAAG,EAAE,CAAC;IAChC,OAAO,IAAI,CAAC,MAAM,EAAE;QAClB,sBAAsB,GAAG,IAAI,IAAI,CAAC,IAAI,GAAG,sBAAsB,EAAE,CAAC;QAClE,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC;KACpB;IACD,OAAO,sBAAsB,CAAC;AAChC,CAAC;AAVD,8DAUC;AAEY,QAAA,YAAY,GAAG,IAAI,GAAG,CAAC;IAClC,8BAA8B;IAC9B,6BAA6B;IAC7B,6BAA6B;IAC7B,8BAA8B;IAC9B,6BAA6B;IAC7B,8BAA8B;IAC9B,4BAA4B;IAC5B,8BAA8B;IAC9B,6BAA6B;CAC9B,CAAC,CAAC;AAEH,SAAgB,MAAM,CAAC,SAAkB,EAAE,OAAe;IACxD,IAAI,CAAC,SAAS,EAAE;QACd,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;KAC1B;AACH,CAAC;AAJD,wBAIC"} \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/value.d.ts b/node_modules/proto3-json-serializer/build/src/value.d.ts new file mode 100644 index 0000000..9d12ddf --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/value.d.ts @@ -0,0 +1,23 @@ +import { FromObjectValue, JSONObject, JSONValue } from './types'; +export interface Struct { + fields: { + [key: string]: Value; + }; +} +export interface ListValue { + values: Array; +} +export interface Value { + nullValue?: 0; + numberValue?: number; + stringValue?: string; + boolValue?: boolean; + listValue?: ListValue; + structValue?: Struct; +} +export declare function googleProtobufStructToProto3JSON(obj: protobuf.Message & Struct): JSONObject; +export declare function googleProtobufListValueToProto3JSON(obj: protobuf.Message & ListValue): JSONValue[]; +export declare function googleProtobufValueToProto3JSON(obj: protobuf.Message & Value): JSONValue; +export declare function googleProtobufStructFromProto3JSON(json: JSONObject): FromObjectValue; +export declare function googleProtobufListValueFromProto3JSON(json: JSONValue[]): FromObjectValue; +export declare function googleProtobufValueFromProto3JSON(json: JSONValue): FromObjectValue; diff --git a/node_modules/proto3-json-serializer/build/src/value.js b/node_modules/proto3-json-serializer/build/src/value.js new file mode 100644 index 0000000..6ea423e --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/value.js @@ -0,0 +1,104 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.googleProtobufValueFromProto3JSON = exports.googleProtobufListValueFromProto3JSON = exports.googleProtobufStructFromProto3JSON = exports.googleProtobufValueToProto3JSON = exports.googleProtobufListValueToProto3JSON = exports.googleProtobufStructToProto3JSON = void 0; +const util_1 = require("./util"); +function googleProtobufStructToProto3JSON(obj) { + const result = {}; + const fields = obj.fields; + for (const [key, value] of Object.entries(fields)) { + result[key] = googleProtobufValueToProto3JSON(value); + } + return result; +} +exports.googleProtobufStructToProto3JSON = googleProtobufStructToProto3JSON; +function googleProtobufListValueToProto3JSON(obj) { + (0, util_1.assert)(Array.isArray(obj.values), 'ListValue internal representation must contain array of values'); + return obj.values.map(googleProtobufValueToProto3JSON); +} +exports.googleProtobufListValueToProto3JSON = googleProtobufListValueToProto3JSON; +function googleProtobufValueToProto3JSON(obj) { + if (Object.prototype.hasOwnProperty.call(obj, 'nullValue')) { + return null; + } + if (Object.prototype.hasOwnProperty.call(obj, 'numberValue') && + typeof obj.numberValue === 'number') { + if (!Number.isFinite(obj.numberValue)) { + return obj.numberValue.toString(); + } + return obj.numberValue; + } + if (Object.prototype.hasOwnProperty.call(obj, 'stringValue') && + typeof obj.stringValue === 'string') { + return obj.stringValue; + } + if (Object.prototype.hasOwnProperty.call(obj, 'boolValue') && + typeof obj.boolValue === 'boolean') { + return obj.boolValue; + } + if (Object.prototype.hasOwnProperty.call(obj, 'structValue') && + typeof obj.structValue === 'object') { + return googleProtobufStructToProto3JSON(obj.structValue); + } + if (Object.prototype.hasOwnProperty.call(obj, 'listValue') && + typeof obj === 'object' && + typeof obj.listValue === 'object') { + return googleProtobufListValueToProto3JSON(obj.listValue); + } + // Assuming empty Value to be null + return null; +} +exports.googleProtobufValueToProto3JSON = googleProtobufValueToProto3JSON; +function googleProtobufStructFromProto3JSON(json) { + const fields = {}; + for (const [key, value] of Object.entries(json)) { + fields[key] = googleProtobufValueFromProto3JSON(value); + } + return { fields }; +} +exports.googleProtobufStructFromProto3JSON = googleProtobufStructFromProto3JSON; +function googleProtobufListValueFromProto3JSON(json) { + return { + values: json.map(element => googleProtobufValueFromProto3JSON(element)), + }; +} +exports.googleProtobufListValueFromProto3JSON = googleProtobufListValueFromProto3JSON; +function googleProtobufValueFromProto3JSON(json) { + if (json === null) { + return { nullValue: 'NULL_VALUE' }; + } + if (typeof json === 'number') { + return { numberValue: json }; + } + if (typeof json === 'string') { + return { stringValue: json }; + } + if (typeof json === 'boolean') { + return { boolValue: json }; + } + if (Array.isArray(json)) { + return { + listValue: googleProtobufListValueFromProto3JSON(json), + }; + } + if (typeof json === 'object') { + return { + structValue: googleProtobufStructFromProto3JSON(json), + }; + } + throw new Error(`googleProtobufValueFromProto3JSON: incorrect parameter type: ${typeof json}`); +} +exports.googleProtobufValueFromProto3JSON = googleProtobufValueFromProto3JSON; +//# sourceMappingURL=value.js.map \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/value.js.map b/node_modules/proto3-json-serializer/build/src/value.js.map new file mode 100644 index 0000000..5cd3ecc --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/value.js.map @@ -0,0 +1 @@ +{"version":3,"file":"value.js","sourceRoot":"","sources":["../../typescript/src/value.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,iDAAiD;AACjD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAEjC,iCAA8B;AAsB9B,SAAgB,gCAAgC,CAC9C,GAA8B;IAE9B,MAAM,MAAM,GAAe,EAAE,CAAC;IAC9B,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC;IAC1B,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;QACjD,MAAM,CAAC,GAAG,CAAC,GAAG,+BAA+B,CAC3C,KAAiC,CAClC,CAAC;KACH;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAXD,4EAWC;AAED,SAAgB,mCAAmC,CACjD,GAAiC;IAEjC,IAAA,aAAM,EACJ,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,EACzB,gEAAgE,CACjE,CAAC;IACF,OAAQ,GAAG,CAAC,MAA0C,CAAC,GAAG,CACxD,+BAA+B,CAChC,CAAC;AACJ,CAAC;AAVD,kFAUC;AAED,SAAgB,+BAA+B,CAC7C,GAA6B;IAE7B,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,WAAW,CAAC,EAAE;QAC1D,OAAO,IAAI,CAAC;KACb;IAED,IACE,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,aAAa,CAAC;QACxD,OAAO,GAAG,CAAC,WAAW,KA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AC,KAAK,CAAC,CAAC;KACxD;IACD,OAAO,EAAC,MAAM,EAAC,CAAC;AAClB,CAAC;AARD,gFAQC;AAED,SAAgB,qCAAqC,CACnD,IAAiB;IAEjB,OAAO;QACL,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,iCAAiC,CAAC,OAAO,CAAC,CAAC;KACxE,CAAC;AACJ,CAAC;AAND,sFAMC;AAED,SAAgB,iCAAiC,CAC/C,IAAe;IAEf,IAAI,IAAI,KAAK,IAAI,EAAE;QACjB,OAAO,EAAC,SAAS,EAAE,YAAY,EAAC,CAAC;KAClC;IAED,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QAC5B,OAAO,EAAC,WAAW,EAAE,IAAI,EAAC,CAAC;KAC5B;IAED,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QAC5B,OAAO,EAAC,WAAW,EAAE,IAAI,EAAC,CAAC;KAC5B;IAED,IAAI,OAAO,IAAI,KAAK,SAAS,EAAE;QAC7B,OAAO,EAAC,SAAS,EAAE,IAAI,EAAC,CAAC;KAC1B;IAED,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;QACvB,OAAO;YACL,SAAS,EAAE,qCAAqC,CAAC,IAAI,CAAC;SACvD,CAAC;KACH;IAED,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QAC5B,OAAO;YACL,WAAW,EAAE,kCAAkC,CAAC,IAAI,CAAC;SACtD,CAAC;KACH;IAED,MAAM,IAAI,KAAK,CACb,gEAAgE,OAAO,IAAI,EAAE,CAC9E,CAAC;AACJ,CAAC;AAlCD,8EAkCC"} \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/wrappers.d.ts b/node_modules/proto3-json-serializer/build/src/wrappers.d.ts new file mode 100644 index 0000000..cc5a64a --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/wrappers.d.ts @@ -0,0 +1,21 @@ +/// +export interface NumberValue { + value: number | object; +} +export interface StringValue { + value: string; +} +export interface BoolValue { + value: boolean; +} +export interface BytesValue { + value: Buffer | Uint8Array; +} +export declare function wrapperToProto3JSON(obj: protobuf.Message & (NumberValue | StringValue | BoolValue | BytesValue)): string | number | boolean | null; +export declare function wrapperFromProto3JSON(typeName: string, json: number | string | boolean | null): { + value: null; +} | { + value: Buffer; +} | { + value: string | number | boolean; +}; diff --git a/node_modules/proto3-json-serializer/build/src/wrappers.js b/node_modules/proto3-json-serializer/build/src/wrappers.js new file mode 100644 index 0000000..a04b31c --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/wrappers.js @@ -0,0 +1,56 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wrapperFromProto3JSON = exports.wrapperToProto3JSON = void 0; +const bytes_1 = require("./bytes"); +const util_1 = require("./util"); +function wrapperToProto3JSON(obj) { + if (!Object.prototype.hasOwnProperty.call(obj, 'value')) { + return null; + } + if (Buffer.isBuffer(obj.value) || obj.value instanceof Uint8Array) { + return (0, bytes_1.bytesToProto3JSON)(obj.value); + } + if (typeof obj.value === 'object') { + (0, util_1.assert)(obj.value.constructor.name === 'Long', `wrapperToProto3JSON: expected to see a number, a string, a boolean, or a Long, but got ${obj.value}`); + return obj.value.toString(); + } + // JSON accept special string values "NaN", "Infinity", and "-Infinity". + if (typeof obj.value === 'number' && !Number.isFinite(obj.value)) { + return obj.value.toString(); + } + return obj.value; +} +exports.wrapperToProto3JSON = wrapperToProto3JSON; +function wrapperFromProto3JSON(typeName, json) { + if (json === null) { + return { + value: null, + }; + } + if (typeName === '.google.protobuf.BytesValue') { + if (typeof json !== 'string') { + throw new Error(`numberWrapperFromProto3JSON: expected to get a string for google.protobuf.BytesValue but got ${typeof json}`); + } + return { + value: (0, bytes_1.bytesFromProto3JSON)(json), + }; + } + return { + value: json, + }; +} +exports.wrapperFromProto3JSON = wrapperFromProto3JSON; +//# sourceMappingURL=wrappers.js.map \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/build/src/wrappers.js.map b/node_modules/proto3-json-serializer/build/src/wrappers.js.map new file mode 100644 index 0000000..8e0e734 --- /dev/null +++ b/node_modules/proto3-json-serializer/build/src/wrappers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wrappers.js","sourceRoot":"","sources":["../../typescript/src/wrappers.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,iDAAiD;AACjD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAEjC,mCAA+D;AAE/D,iCAA8B;AAkB9B,SAAgB,mBAAmB,CACjC,GAA4E;IAE5E,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,CAAC,EAAE;QACvD,OAAO,IAAI,CAAC;KACb;IACD,IAAI,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,KAAK,YAAY,UAAU,EAAE;QACjE,OAAO,IAAA,yBAAiB,EAAC,GAAG,CAAC,KAAK,CAAC,CAAC;KACrC;IACD,IAAI,OAAO,GAAG,CAAC,KAAK,KAAK,QAAQ,EAAE;QACjC,IAAA,aAAM,EACJ,GAAG,CAAC,KAAK,CAAC,WAAW,CAAC,IAAI,KAAK,MAAM,EACrC,0FAA0F,GAAG,CAAC,KAAK,EAAE,CACtG,CAAC;QACF,OAAQ,GAAG,CAAC,KAAkB,CAAC,QAAQ,EAAE,CAAC;KAC3C;IACD,wEAAwE;IACxE,IAAI,OAAO,GAAG,CAAC,KAAK,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE;QAChE,OAAO,GAAG,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC;KAC7B;IACD,OAAO,GAAG,CAAC,KAAK,CAAC;AACnB,CAAC;AArBD,kDAqBC;AAED,SAAgB,qBAAqB,CACnC,QAAgB,EAChB,IAAsC;IAEtC,IAAI,IAAI,KAAK,IAAI,EAAE;QACjB,OAAO;YACL,KAAK,EAAE,IAAI;SACZ,CAAC;KACH;IACD,IAAI,QAAQ,KAAK,6BAA6B,EAAE;QAC9C,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;YAC5B,MAAM,IAAI,KAAK,CACb,gGAAgG,OAAO,IAAI,EAAE,CAC9G,CAAC;SACH;QACD,OAAO;YACL,KAAK,EAAE,IAAA,2BAAmB,EAAC,IAAI,CAAC;SACjC,CAAC;KACH;IACD,OAAO;QACL,KAAK,EAAE,IAAI;KACZ,CAAC;AACJ,CAAC;AAtBD,sDAsBC"} \ No newline at end of file diff --git a/node_modules/proto3-json-serializer/package.json b/node_modules/proto3-json-serializer/package.json new file mode 100644 index 0000000..87bd06c --- /dev/null +++ b/node_modules/proto3-json-serializer/package.json @@ -0,0 +1,59 @@ +{ + "name": "proto3-json-serializer", + "version": "2.0.2", + "repository": "googleapis/proto3-json-serializer-nodejs", + "description": "Support for proto3 JSON serialiazation/deserialization for protobuf.js", + "main": "build/src/index.js", + "types": "build/src/index.d.ts", + "files": [ + "build/src" + ], + "license": "Apache-2.0", + "keywords": [ + "protobufjs", + "protobuf.js", + "protobuf", + "proto3", + "json", + "serialization", + "deserialization" + ], + "scripts": { + "test": "c8 node_modules/mocha/bin/mocha build/test/unit", + "system-test": "mocha build/test/system", + "lint": "gts lint", + "clean": "gts clean", + "compile": "tsc", + "fix": "gts fix", + "prepare": "npm run compile", + "pretest": "npm run compile", + "posttest": "npm run lint", + "compile-test-protos": "cd test-fixtures/proto && pbjs -t json test.proto > test.json", + "docs": "jsdoc -c .jsdoc.js", + "docs-test": "linkinator docs", + "predocs-test": "npm run docs", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "prelint": "cd samples && npm link ../ && npm install" + }, + "dependencies": { + "protobufjs": "^7.2.5" + }, + "devDependencies": { + "@types/mocha": "^9.0.0", + "@types/node": "^20.0.0", + "c8": "^9.0.0", + "google-proto-files": "^4.0.0", + "gts": "^5.0.0", + "jsdoc": "^4.0.0", + "jsdoc-fresh": "^3.0.0", + "jsdoc-region-tag": "^3.0.0", + "linkinator": "^5.0.0", + "mocha": "^9.2.2", + "pack-n-play": "^2.0.0", + "protobufjs-cli": "^1.1.2", + "typescript": "^4.6.4" + }, + "engines": { + "node": ">=14.0.0" + } +} diff --git a/node_modules/protobufjs/LICENSE b/node_modules/protobufjs/LICENSE new file mode 100644 index 0000000..57b7e30 --- /dev/null +++ b/node_modules/protobufjs/LICENSE @@ -0,0 +1,39 @@ +This license applies to all parts of protobuf.js except those files +either explicitly including or referencing a different license or +located in a directory containing a different LICENSE file. + +--- + +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--- + +Code generated by the command line utilities is owned by the owner +of the input file used when generating it. This code is not +standalone and requires a support library to be linked with it. This +support library is itself covered by the above license. diff --git a/node_modules/protobufjs/README.md b/node_modules/protobufjs/README.md new file mode 100644 index 0000000..46752a9 --- /dev/null +++ b/node_modules/protobufjs/README.md @@ -0,0 +1,727 @@ +

                          protobuf.js
                          protobuf.js

                          +

                          + + + + + +

                          + +**Protocol Buffers** are a language-neutral, platform-neutral, extensible way of serializing structured data for use in communications protocols, data storage, and more, originally designed at Google ([see](https://protobuf.dev/)). + +**protobuf.js** is a pure JavaScript implementation with [TypeScript](https://www.typescriptlang.org) support for [Node.js](https://nodejs.org) and the browser. It's easy to use, does not sacrifice on performance, has good conformance and works out of the box with [.proto](https://protobuf.dev/programming-guides/proto3/) files! + +Contents +-------- + +* [Installation](#installation)
                          + How to include protobuf.js in your project. + +* [Usage](#usage)
                          + A brief introduction to using the toolset. + + * [Valid Message](#valid-message) + * [Toolset](#toolset)
                          + +* [Examples](#examples)
                          + A few examples to get you started. + + * [Using .proto files](#using-proto-files) + * [Using JSON descriptors](#using-json-descriptors) + * [Using reflection only](#using-reflection-only) + * [Using custom classes](#using-custom-classes) + * [Using services](#using-services) + * [Usage with TypeScript](#usage-with-typescript)
                          + +* [Additional documentation](#additional-documentation)
                          + A list of available documentation resources. + +* [Performance](#performance)
                          + A few internals and a benchmark on performance. + +* [Compatibility](#compatibility)
                          + Notes on compatibility regarding browsers and optional libraries. + +* [Building](#building)
                          + How to build the library and its components yourself. + +Installation +--------------- + +### Node.js + +```sh +npm install protobufjs --save +``` + +```js +// Static code + Reflection + .proto parser +var protobuf = require("protobufjs"); + +// Static code + Reflection +var protobuf = require("protobufjs/light"); + +// Static code only +var protobuf = require("protobufjs/minimal"); +``` + +The optional [command line utility](./cli/) to generate static code and reflection bundles lives in the `protobufjs-cli` package and can be installed separately: + +```sh +npm install protobufjs-cli --save-dev +``` + +### Browsers + +Pick the variant matching your needs and replace the version tag with the exact [release](https://github.com/protobufjs/protobuf.js/tags) your project depends upon. For example, to use the minified full variant: + +```html + +``` + +| Distribution | Location +|--------------|-------------------------------------------------------- +| Full | +| Light | +| Minimal | + +All variants support CommonJS and AMD loaders and export globally as `window.protobuf`. + +Usage +----- + +Because JavaScript is a dynamically typed language, protobuf.js utilizes the concept of a **valid message** in order to provide the best possible [performance](#performance) (and, as a side product, proper typings): + +### Valid message + +> A valid message is an object (1) not missing any required fields and (2) exclusively composed of JS types understood by the wire format writer. + +There are two possible types of valid messages and the encoder is able to work with both of these for convenience: + +* **Message instances** (explicit instances of message classes with default values on their prototype) naturally satisfy the requirements of a valid message and +* **Plain JavaScript objects** that just so happen to be composed in a way satisfying the requirements of a valid message as well. + +In a nutshell, the wire format writer understands the following types: + +| Field type | Expected JS type (create, encode) | Conversion (fromObject) +|------------|-----------------------------------|------------------------ +| s-/u-/int32
                          s-/fixed32 | `number` (32 bit integer) | value | 0 if signed
                          `value >>> 0` if unsigned +| s-/u-/int64
                          s-/fixed64 | `Long`-like (optimal)
                          `number` (53 bit integer) | `Long.fromValue(value)` with long.js
                          `parseInt(value, 10)` otherwise +| float
                          double | `number` | `Number(value)` +| bool | `boolean` | `Boolean(value)` +| string | `string` | `String(value)` +| bytes | `Uint8Array` (optimal)
                          `Buffer` (optimal under node)
                          `Array.` (8 bit integers) | `base64.decode(value)` if a `string`
                          `Object` with non-zero `.length` is assumed to be buffer-like +| enum | `number` (32 bit integer) | Looks up the numeric id if a `string` +| message | Valid message | `Message.fromObject(value)` +| repeated T | `Array` | Copy +| map | `Object` | Copy + +* Explicit `undefined` and `null` are considered as not set if the field is optional. +* Maps are objects where the key is the string representation of the respective value or an 8 characters long hash string for `Long`-likes. + +### Toolset + +With that in mind and again for performance reasons, each message class provides a distinct set of methods with each method doing just one thing. This avoids unnecessary assertions / redundant operations where performance is a concern but also forces a user to perform verification (of plain JavaScript objects that *might* just so happen to be a valid message) explicitly where necessary - for example when dealing with user input. + +**Note** that `Message` below refers to any message class. + +* **Message.verify**(message: `Object`): `null|string`
                          + verifies that a **plain JavaScript object** satisfies the requirements of a valid message and thus can be encoded without issues. Instead of throwing, it returns the error message as a string, if any. + + ```js + var payload = "invalid (not an object)"; + var err = AwesomeMessage.verify(payload); + if (err) + throw Error(err); + ``` + +* **Message.encode**(message: `Message|Object` [, writer: `Writer`]): `Writer`
                          + encodes a **message instance** or valid **plain JavaScript object**. This method does not implicitly verify the message and it's up to the user to make sure that the payload is a valid message. + + ```js + var buffer = AwesomeMessage.encode(message).finish(); + ``` + +* **Message.encodeDelimited**(message: `Message|Object` [, writer: `Writer`]): `Writer`
                          + works like `Message.encode` but additionally prepends the length of the message as a varint. + +* **Message.decode**(reader: `Reader|Uint8Array`): `Message`
                          + decodes a buffer to a **message instance**. If required fields are missing, it throws a `util.ProtocolError` with an `instance` property set to the so far decoded message. If the wire format is invalid, it throws an `Error`. + + ```js + try { + var decodedMessage = AwesomeMessage.decode(buffer); + } catch (e) { + if (e instanceof protobuf.util.ProtocolError) { + // e.instance holds the so far decoded message with missing required fields + } else { + // wire format is invalid + } + } + ``` + +* **Message.decodeDelimited**(reader: `Reader|Uint8Array`): `Message`
                          + works like `Message.decode` but additionally reads the length of the message prepended as a varint. + +* **Message.create**(properties: `Object`): `Message`
                          + creates a new **message instance** from a set of properties that satisfy the requirements of a valid message. Where applicable, it is recommended to prefer `Message.create` over `Message.fromObject` because it doesn't perform possibly redundant conversion. + + ```js + var message = AwesomeMessage.create({ awesomeField: "AwesomeString" }); + ``` + +* **Message.fromObject**(object: `Object`): `Message`
                          + converts any non-valid **plain JavaScript object** to a **message instance** using the conversion steps outlined within the table above. + + ```js + var message = AwesomeMessage.fromObject({ awesomeField: 42 }); + // converts awesomeField to a string + ``` + +* **Message.toObject**(message: `Message` [, options: `ConversionOptions`]): `Object`
                          + converts a **message instance** to an arbitrary **plain JavaScript object** for interoperability with other libraries or storage. The resulting plain JavaScript object *might* still satisfy the requirements of a valid message depending on the actual conversion options specified, but most of the time it does not. + + ```js + var object = AwesomeMessage.toObject(message, { + enums: String, // enums as string names + longs: String, // longs as strings (requires long.js) + bytes: String, // bytes as base64 encoded strings + defaults: true, // includes default values + arrays: true, // populates empty arrays (repeated fields) even if defaults=false + objects: true, // populates empty objects (map fields) even if defaults=false + oneofs: true // includes virtual oneof fields set to the present field's name + }); + ``` + +For reference, the following diagram aims to display relationships between the different methods and the concept of a valid message: + +

                          Toolset Diagram

                          + +> In other words: `verify` indicates that calling `create` or `encode` directly on the plain object will [result in a valid message respectively] succeed. `fromObject`, on the other hand, does conversion from a broader range of plain objects to create valid messages. ([ref](https://github.com/protobufjs/protobuf.js/issues/748#issuecomment-291925749)) + +Examples +-------- + +### Using .proto files + +It is possible to load existing .proto files using the full library, which parses and compiles the definitions to ready to use (reflection-based) message classes: + +```protobuf +// awesome.proto +package awesomepackage; +syntax = "proto3"; + +message AwesomeMessage { + string awesome_field = 1; // becomes awesomeField +} +``` + +```js +protobuf.load("awesome.proto", function(err, root) { + if (err) + throw err; + + // Obtain a message type + var AwesomeMessage = root.lookupType("awesomepackage.AwesomeMessage"); + + // Exemplary payload + var payload = { awesomeField: "AwesomeString" }; + + // Verify the payload if necessary (i.e. when possibly incomplete or invalid) + var errMsg = AwesomeMessage.verify(payload); + if (errMsg) + throw Error(errMsg); + + // Create a new message + var message = AwesomeMessage.create(payload); // or use .fromObject if conversion is necessary + + // Encode a message to an Uint8Array (browser) or Buffer (node) + var buffer = AwesomeMessage.encode(message).finish(); + // ... do something with buffer + + // Decode an Uint8Array (browser) or Buffer (node) to a message + var message = AwesomeMessage.decode(buffer); + // ... do something with message + + // If the application uses length-delimited buffers, there is also encodeDelimited and decodeDelimited. + + // Maybe convert the message back to a plain object + var object = AwesomeMessage.toObject(message, { + longs: String, + enums: String, + bytes: String, + // see ConversionOptions + }); +}); +``` + +Additionally, promise syntax can be used by omitting the callback, if preferred: + +```js +protobuf.load("awesome.proto") + .then(function(root) { + ... + }); +``` + +### Using JSON descriptors + +The library utilizes JSON descriptors that are equivalent to a .proto definition. For example, the following is identical to the .proto definition seen above: + +```json +// awesome.json +{ + "nested": { + "awesomepackage": { + "nested": { + "AwesomeMessage": { + "fields": { + "awesomeField": { + "type": "string", + "id": 1 + } + } + } + } + } + } +} +``` + +JSON descriptors closely resemble the internal reflection structure: + +| Type (T) | Extends | Type-specific properties +|--------------------|--------------------|------------------------- +| *ReflectionObject* | | options +| *Namespace* | *ReflectionObject* | nested +| Root | *Namespace* | **nested** +| Type | *Namespace* | **fields** +| Enum | *ReflectionObject* | **values** +| Field | *ReflectionObject* | rule, **type**, **id** +| MapField | Field | **keyType** +| OneOf | *ReflectionObject* | **oneof** (array of field names) +| Service | *Namespace* | **methods** +| Method | *ReflectionObject* | type, **requestType**, **responseType**, requestStream, responseStream + +* **Bold properties** are required. *Italic types* are abstract. +* `T.fromJSON(name, json)` creates the respective reflection object from a JSON descriptor +* `T#toJSON()` creates a JSON descriptor from the respective reflection object (its name is used as the key within the parent) + +Exclusively using JSON descriptors instead of .proto files enables the use of just the light library (the parser isn't required in this case). + +A JSON descriptor can either be loaded the usual way: + +```js +protobuf.load("awesome.json", function(err, root) { + if (err) throw err; + + // Continue at "Obtain a message type" above +}); +``` + +Or it can be loaded inline: + +```js +var jsonDescriptor = require("./awesome.json"); // exemplary for node + +var root = protobuf.Root.fromJSON(jsonDescriptor); + +// Continue at "Obtain a message type" above +``` + +### Using reflection only + +Both the full and the light library include full reflection support. One could, for example, define the .proto definitions seen in the examples above using just reflection: + +```js +... +var Root = protobuf.Root, + Type = protobuf.Type, + Field = protobuf.Field; + +var AwesomeMessage = new Type("AwesomeMessage").add(new Field("awesomeField", 1, "string")); + +var root = new Root().define("awesomepackage").add(AwesomeMessage); + +// Continue at "Create a new message" above +... +``` + +Detailed information on the reflection structure is available within the [API documentation](#additional-documentation). + +### Using custom classes + +Message classes can also be extended with custom functionality and it is also possible to register a custom constructor with a reflected message type: + +```js +... + +// Define a custom constructor +function AwesomeMessage(properties) { + // custom initialization code + ... +} + +// Register the custom constructor with its reflected type (*) +root.lookupType("awesomepackage.AwesomeMessage").ctor = AwesomeMessage; + +// Define custom functionality +AwesomeMessage.customStaticMethod = function() { ... }; +AwesomeMessage.prototype.customInstanceMethod = function() { ... }; + +// Continue at "Create a new message" above +``` + +(*) Besides referencing its reflected type through `AwesomeMessage.$type` and `AwesomeMesage#$type`, the respective custom class is automatically populated with: + +* `AwesomeMessage.create` +* `AwesomeMessage.encode` and `AwesomeMessage.encodeDelimited` +* `AwesomeMessage.decode` and `AwesomeMessage.decodeDelimited` +* `AwesomeMessage.verify` +* `AwesomeMessage.fromObject`, `AwesomeMessage.toObject` and `AwesomeMessage#toJSON` + +Afterwards, decoded messages of this type are `instanceof AwesomeMessage`. + +Alternatively, it is also possible to reuse and extend the internal constructor if custom initialization code is not required: + +```js +... + +// Reuse the internal constructor +var AwesomeMessage = root.lookupType("awesomepackage.AwesomeMessage").ctor; + +// Define custom functionality +AwesomeMessage.customStaticMethod = function() { ... }; +AwesomeMessage.prototype.customInstanceMethod = function() { ... }; + +// Continue at "Create a new message" above +``` + +### Using services + +The library also supports consuming services but it doesn't make any assumptions about the actual transport channel. Instead, a user must provide a suitable RPC implementation, which is an asynchronous function that takes the reflected service method, the binary request and a node-style callback as its parameters: + +```js +function rpcImpl(method, requestData, callback) { + // perform the request using an HTTP request or a WebSocket for example + var responseData = ...; + // and call the callback with the binary response afterwards: + callback(null, responseData); +} +``` + +Below is a working example with a typescript implementation using grpc npm package. +```ts +const grpc = require('grpc') + +const Client = grpc.makeGenericClientConstructor({}) +const client = new Client( + grpcServerUrl, + grpc.credentials.createInsecure() +) + +const rpcImpl = function(method, requestData, callback) { + client.makeUnaryRequest( + method.name, + arg => arg, + arg => arg, + requestData, + callback + ) +} +``` + +Example: + +```protobuf +// greeter.proto +syntax = "proto3"; + +service Greeter { + rpc SayHello (HelloRequest) returns (HelloReply) {} +} + +message HelloRequest { + string name = 1; +} + +message HelloReply { + string message = 1; +} +``` + +```js +... +var Greeter = root.lookup("Greeter"); +var greeter = Greeter.create(/* see above */ rpcImpl, /* request delimited? */ false, /* response delimited? */ false); + +greeter.sayHello({ name: 'you' }, function(err, response) { + console.log('Greeting:', response.message); +}); +``` + +Services also support promises: + +```js +greeter.sayHello({ name: 'you' }) + .then(function(response) { + console.log('Greeting:', response.message); + }); +``` + +There is also an [example for streaming RPC](https://github.com/protobufjs/protobuf.js/blob/master/examples/streaming-rpc.js). + +Note that the service API is meant for clients. Implementing a server-side endpoint pretty much always requires transport channel (i.e. http, websocket, etc.) specific code with the only common denominator being that it decodes and encodes messages. + +### Usage with TypeScript + +The library ships with its own [type definitions](https://github.com/protobufjs/protobuf.js/blob/master/index.d.ts) and modern editors like [Visual Studio Code](https://code.visualstudio.com/) will automatically detect and use them for code completion. + +The npm package depends on [@types/node](https://www.npmjs.com/package/@types/node) because of `Buffer` and [@types/long](https://www.npmjs.com/package/@types/long) because of `Long`. If you are not building for node and/or not using long.js, it should be safe to exclude them manually. + +#### Using the JS API + +The API shown above works pretty much the same with TypeScript. However, because everything is typed, accessing fields on instances of dynamically generated message classes requires either using bracket-notation (i.e. `message["awesomeField"]`) or explicit casts. Alternatively, it is possible to use a [typings file generated for its static counterpart](#pbts-for-typescript). + +```ts +import { load } from "protobufjs"; // respectively "./node_modules/protobufjs" + +load("awesome.proto", function(err, root) { + if (err) + throw err; + + // example code + const AwesomeMessage = root.lookupType("awesomepackage.AwesomeMessage"); + + let message = AwesomeMessage.create({ awesomeField: "hello" }); + console.log(`message = ${JSON.stringify(message)}`); + + let buffer = AwesomeMessage.encode(message).finish(); + console.log(`buffer = ${Array.prototype.toString.call(buffer)}`); + + let decoded = AwesomeMessage.decode(buffer); + console.log(`decoded = ${JSON.stringify(decoded)}`); +}); +``` + +#### Using generated static code + +If you generated static code to `bundle.js` using the CLI and its type definitions to `bundle.d.ts`, then you can just do: + +```ts +import { AwesomeMessage } from "./bundle.js"; + +// example code +let message = AwesomeMessage.create({ awesomeField: "hello" }); +let buffer = AwesomeMessage.encode(message).finish(); +let decoded = AwesomeMessage.decode(buffer); +``` + +#### Using decorators + +The library also includes an early implementation of [decorators](https://www.typescriptlang.org/docs/handbook/decorators.html). + +**Note** that decorators are an experimental feature in TypeScript and that declaration order is important depending on the JS target. For example, `@Field.d(2, AwesomeArrayMessage)` requires that `AwesomeArrayMessage` has been defined earlier when targeting `ES5`. + +```ts +import { Message, Type, Field, OneOf } from "protobufjs/light"; // respectively "./node_modules/protobufjs/light.js" + +export class AwesomeSubMessage extends Message { + + @Field.d(1, "string") + public awesomeString: string; + +} + +export enum AwesomeEnum { + ONE = 1, + TWO = 2 +} + +@Type.d("SuperAwesomeMessage") +export class AwesomeMessage extends Message { + + @Field.d(1, "string", "optional", "awesome default string") + public awesomeField: string; + + @Field.d(2, AwesomeSubMessage) + public awesomeSubMessage: AwesomeSubMessage; + + @Field.d(3, AwesomeEnum, "optional", AwesomeEnum.ONE) + public awesomeEnum: AwesomeEnum; + + @OneOf.d("awesomeSubMessage", "awesomeEnum") + public which: string; + +} + +// example code +let message = new AwesomeMessage({ awesomeField: "hello" }); +let buffer = AwesomeMessage.encode(message).finish(); +let decoded = AwesomeMessage.decode(buffer); +``` + +Supported decorators are: + +* **Type.d(typeName?: `string`)**   *(optional)*
                          + annotates a class as a protobuf message type. If `typeName` is not specified, the constructor's runtime function name is used for the reflected type. + +* **Field.d<T>(fieldId: `number`, fieldType: `string | Constructor`, fieldRule?: `"optional" | "required" | "repeated"`, defaultValue?: `T`)**
                          + annotates a property as a protobuf field with the specified id and protobuf type. + +* **MapField.d<T extends { [key: string]: any }>(fieldId: `number`, fieldKeyType: `string`, fieldValueType. `string | Constructor<{}>`)**
                          + annotates a property as a protobuf map field with the specified id, protobuf key and value type. + +* **OneOf.d<T extends string>(...fieldNames: `string[]`)**
                          + annotates a property as a protobuf oneof covering the specified fields. + +Other notes: + +* Decorated types reside in `protobuf.roots["decorated"]` using a flat structure, so no duplicate names. +* Enums are copied to a reflected enum with a generic name on decorator evaluation because referenced enum objects have no runtime name the decorator could use. +* Default values must be specified as arguments to the decorator instead of using a property initializer for proper prototype behavior. +* Property names on decorated classes must not be renamed on compile time (i.e. by a minifier) because decorators just receive the original field name as a string. + +**ProTip!** Not as pretty, but you can [use decorators in plain JavaScript](https://github.com/protobufjs/protobuf.js/blob/master/examples/js-decorators.js) as well. + +Additional documentation +------------------------ + +#### Protocol Buffers +* [Google's Developer Guide](https://protobuf.dev/overview/) + +#### protobuf.js +* [API Documentation](https://protobufjs.github.io/protobuf.js) +* [CHANGELOG](https://github.com/protobufjs/protobuf.js/blob/master/CHANGELOG.md) +* [Frequently asked questions](https://github.com/protobufjs/protobuf.js/wiki) on our wiki + +#### Community +* [Questions and answers](http://stackoverflow.com/search?tab=newest&q=protobuf.js) on StackOverflow + +Performance +----------- +The package includes a benchmark that compares protobuf.js performance to native JSON (as far as this is possible) and [Google's JS implementation](https://github.com/google/protobuf/tree/master/js). On an i7-2600K running node 6.9.1 it yields: + +``` +benchmarking encoding performance ... + +protobuf.js (reflect) x 541,707 ops/sec ±1.13% (87 runs sampled) +protobuf.js (static) x 548,134 ops/sec ±1.38% (89 runs sampled) +JSON (string) x 318,076 ops/sec ±0.63% (93 runs sampled) +JSON (buffer) x 179,165 ops/sec ±2.26% (91 runs sampled) +google-protobuf x 74,406 ops/sec ±0.85% (86 runs sampled) + + protobuf.js (static) was fastest + protobuf.js (reflect) was 0.9% ops/sec slower (factor 1.0) + JSON (string) was 41.5% ops/sec slower (factor 1.7) + JSON (buffer) was 67.6% ops/sec slower (factor 3.1) + google-protobuf was 86.4% ops/sec slower (factor 7.3) + +benchmarking decoding performance ... + +protobuf.js (reflect) x 1,383,981 ops/sec ±0.88% (93 runs sampled) +protobuf.js (static) x 1,378,925 ops/sec ±0.81% (93 runs sampled) +JSON (string) x 302,444 ops/sec ±0.81% (93 runs sampled) +JSON (buffer) x 264,882 ops/sec ±0.81% (93 runs sampled) +google-protobuf x 179,180 ops/sec ±0.64% (94 runs sampled) + + protobuf.js (reflect) was fastest + protobuf.js (static) was 0.3% ops/sec slower (factor 1.0) + JSON (string) was 78.1% ops/sec slower (factor 4.6) + JSON (buffer) was 80.8% ops/sec slower (factor 5.2) + google-protobuf was 87.0% ops/sec slower (factor 7.7) + +benchmarking combined performance ... + +protobuf.js (reflect) x 275,900 ops/sec ±0.78% (90 runs sampled) +protobuf.js (static) x 290,096 ops/sec ±0.96% (90 runs sampled) +JSON (string) x 129,381 ops/sec ±0.77% (90 runs sampled) +JSON (buffer) x 91,051 ops/sec ±0.94% (90 runs sampled) +google-protobuf x 42,050 ops/sec ±0.85% (91 runs sampled) + + protobuf.js (static) was fastest + protobuf.js (reflect) was 4.7% ops/sec slower (factor 1.0) + JSON (string) was 55.3% ops/sec slower (factor 2.2) + JSON (buffer) was 68.6% ops/sec slower (factor 3.2) + google-protobuf was 85.5% ops/sec slower (factor 6.9) +``` + +These results are achieved by + +* generating type-specific encoders, decoders, verifiers and converters at runtime +* configuring the reader/writer interface according to the environment +* using node-specific functionality where beneficial and, of course +* avoiding unnecessary operations through splitting up [the toolset](#toolset). + +You can also run [the benchmark](https://github.com/protobufjs/protobuf.js/blob/master/bench/index.js) ... + +``` +$> npm run bench +``` + +and [the profiler](https://github.com/protobufjs/protobuf.js/blob/master/bench/prof.js) yourself (the latter requires a recent version of node): + +``` +$> npm run prof [iterations=10000000] +``` + +Note that as of this writing, the benchmark suite performs significantly slower on node 7.2.0 compared to 6.9.1 because moths. + +Compatibility +------------- + +* Works in all modern and not-so-modern browsers except IE8. +* Because the internals of this package do not rely on `google/protobuf/descriptor.proto`, options are parsed and presented literally. +* If typed arrays are not supported by the environment, plain arrays will be used instead. +* Support for pre-ES5 environments (except IE8) can be achieved by [using a polyfill](https://github.com/protobufjs/protobuf.js/blob/master/lib/polyfill.js). +* Support for [Content Security Policy](https://w3c.github.io/webappsec-csp/)-restricted environments (like Chrome extensions without unsafe-eval) can be achieved by generating and using static code instead. +* If a proper way to work with 64 bit values (uint64, int64 etc.) is required, just install [long.js](https://github.com/dcodeIO/long.js) alongside this library. All 64 bit numbers will then be returned as a `Long` instance instead of a possibly unsafe JavaScript number ([see](https://github.com/dcodeIO/long.js)). +* For descriptor.proto interoperability, see [ext/descriptor](https://github.com/protobufjs/protobuf.js/tree/master/ext/descriptor) + +Building +-------- + +To build the library or its components yourself, clone it from GitHub and install the development dependencies: + +``` +$> git clone https://github.com/protobufjs/protobuf.js.git +$> cd protobuf.js +$> npm install +``` + +Building the respective development and production versions with their respective source maps to `dist/`: + +``` +$> npm run build +``` + +Building the documentation to `docs/`: + +``` +$> npm run docs +``` + +Building the TypeScript definition to `index.d.ts`: + +``` +$> npm run build:types +``` + +### Browserify integration + +By default, protobuf.js integrates into any browserify build-process without requiring any optional modules. Hence: + +* If int64 support is required, explicitly require the `long` module somewhere in your project as it will be excluded otherwise. This assumes that a global `require` function is present that protobuf.js can call to obtain the long module. + + If there is no global `require` function present after bundling, it's also possible to assign the long module programmatically: + + ```js + var Long = ...; + + protobuf.util.Long = Long; + protobuf.configure(); + ``` + +* If you have any special requirements, there is [the bundler](https://github.com/protobufjs/protobuf.js/blob/master/scripts/bundle.js) for reference. + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/protobufjs/dist/light/protobuf.js b/node_modules/protobufjs/dist/light/protobuf.js new file mode 100644 index 0000000..c785d2f --- /dev/null +++ b/node_modules/protobufjs/dist/light/protobuf.js @@ -0,0 +1,7833 @@ +/*! + * protobuf.js v7.5.4 (c) 2016, daniel wirtz + * compiled fri, 15 aug 2025 23:28:54 utc + * licensed under the bsd-3-clause license + * see: https://github.com/dcodeio/protobuf.js for details + */ +(function(undefined){"use strict";(function prelude(modules, cache, entries) { + + // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS + // sources through a conflict-free require shim and is again wrapped within an iife that + // provides a minification-friendly `undefined` var plus a global "use strict" directive + // so that minification can remove the directives of each module. + + function $require(name) { + var $module = cache[name]; + if (!$module) + modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports); + return $module.exports; + } + + var protobuf = $require(entries[0]); + + // Expose globally + protobuf.util.global.protobuf = protobuf; + + // Be nice to AMD + if (typeof define === "function" && define.amd) + define(["long"], function(Long) { + if (Long && Long.isLong) { + protobuf.util.Long = Long; + protobuf.configure(); + } + return protobuf; + }); + + // Be nice to CommonJS + if (typeof module === "object" && module && module.exports) + module.exports = protobuf; + +})/* end of prelude */({1:[function(require,module,exports){ +"use strict"; +module.exports = asPromise; + +/** + * Callback as used by {@link util.asPromise}. + * @typedef asPromiseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {...*} params Additional arguments + * @returns {undefined} + */ + +/** + * Returns a promise from a node-style callback function. + * @memberof util + * @param {asPromiseCallback} fn Function to call + * @param {*} ctx Function context + * @param {...*} params Function arguments + * @returns {Promise<*>} Promisified function + */ +function asPromise(fn, ctx/*, varargs */) { + var params = new Array(arguments.length - 1), + offset = 0, + index = 2, + pending = true; + while (index < arguments.length) + params[offset++] = arguments[index++]; + return new Promise(function executor(resolve, reject) { + params[offset] = function callback(err/*, varargs */) { + if (pending) { + pending = false; + if (err) + reject(err); + else { + var params = new Array(arguments.length - 1), + offset = 0; + while (offset < params.length) + params[offset++] = arguments[offset]; + resolve.apply(null, params); + } + } + }; + try { + fn.apply(ctx || null, params); + } catch (err) { + if (pending) { + pending = false; + reject(err); + } + } + }); +} + +},{}],2:[function(require,module,exports){ +"use strict"; + +/** + * A minimal base64 implementation for number arrays. + * @memberof util + * @namespace + */ +var base64 = exports; + +/** + * Calculates the byte length of a base64 encoded string. + * @param {string} string Base64 encoded string + * @returns {number} Byte length + */ +base64.length = function length(string) { + var p = string.length; + if (!p) + return 0; + var n = 0; + while (--p % 4 > 1 && string.charAt(p) === "=") + ++n; + return Math.ceil(string.length * 3) / 4 - n; +}; + +// Base64 encoding table +var b64 = new Array(64); + +// Base64 decoding table +var s64 = new Array(123); + +// 65..90, 97..122, 48..57, 43, 47 +for (var i = 0; i < 64;) + s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; + +/** + * Encodes a buffer to a base64 encoded string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} Base64 encoded string + */ +base64.encode = function encode(buffer, start, end) { + var parts = null, + chunk = []; + var i = 0, // output index + j = 0, // goto index + t; // temporary + while (start < end) { + var b = buffer[start++]; + switch (j) { + case 0: + chunk[i++] = b64[b >> 2]; + t = (b & 3) << 4; + j = 1; + break; + case 1: + chunk[i++] = b64[t | b >> 4]; + t = (b & 15) << 2; + j = 2; + break; + case 2: + chunk[i++] = b64[t | b >> 6]; + chunk[i++] = b64[b & 63]; + j = 0; + break; + } + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i = 0; + } + } + if (j) { + chunk[i++] = b64[t]; + chunk[i++] = 61; + if (j === 1) + chunk[i++] = 61; + } + if (parts) { + if (i) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i)); +}; + +var invalidEncoding = "invalid encoding"; + +/** + * Decodes a base64 encoded string to a buffer. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Number of bytes written + * @throws {Error} If encoding is invalid + */ +base64.decode = function decode(string, buffer, offset) { + var start = offset; + var j = 0, // goto index + t; // temporary + for (var i = 0; i < string.length;) { + var c = string.charCodeAt(i++); + if (c === 61 && j > 1) + break; + if ((c = s64[c]) === undefined) + throw Error(invalidEncoding); + switch (j) { + case 0: + t = c; + j = 1; + break; + case 1: + buffer[offset++] = t << 2 | (c & 48) >> 4; + t = c; + j = 2; + break; + case 2: + buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; + t = c; + j = 3; + break; + case 3: + buffer[offset++] = (t & 3) << 6 | c; + j = 0; + break; + } + } + if (j === 1) + throw Error(invalidEncoding); + return offset - start; +}; + +/** + * Tests if the specified string appears to be base64 encoded. + * @param {string} string String to test + * @returns {boolean} `true` if probably base64 encoded, otherwise false + */ +base64.test = function test(string) { + return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string); +}; + +},{}],3:[function(require,module,exports){ +"use strict"; +module.exports = codegen; + +/** + * Begins generating a function. + * @memberof util + * @param {string[]} functionParams Function parameter names + * @param {string} [functionName] Function name if not anonymous + * @returns {Codegen} Appender that appends code to the function's body + */ +function codegen(functionParams, functionName) { + + /* istanbul ignore if */ + if (typeof functionParams === "string") { + functionName = functionParams; + functionParams = undefined; + } + + var body = []; + + /** + * Appends code to the function's body or finishes generation. + * @typedef Codegen + * @type {function} + * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any + * @param {...*} [formatParams] Format parameters + * @returns {Codegen|Function} Itself or the generated function if finished + * @throws {Error} If format parameter counts do not match + */ + + function Codegen(formatStringOrScope) { + // note that explicit array handling below makes this ~50% faster + + // finish the function + if (typeof formatStringOrScope !== "string") { + var source = toString(); + if (codegen.verbose) + console.log("codegen: " + source); // eslint-disable-line no-console + source = "return " + source; + if (formatStringOrScope) { + var scopeKeys = Object.keys(formatStringOrScope), + scopeParams = new Array(scopeKeys.length + 1), + scopeValues = new Array(scopeKeys.length), + scopeOffset = 0; + while (scopeOffset < scopeKeys.length) { + scopeParams[scopeOffset] = scopeKeys[scopeOffset]; + scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]]; + } + scopeParams[scopeOffset] = source; + return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func + } + return Function(source)(); // eslint-disable-line no-new-func + } + + // otherwise append to body + var formatParams = new Array(arguments.length - 1), + formatOffset = 0; + while (formatOffset < formatParams.length) + formatParams[formatOffset] = arguments[++formatOffset]; + formatOffset = 0; + formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) { + var value = formatParams[formatOffset++]; + switch ($1) { + case "d": case "f": return String(Number(value)); + case "i": return String(Math.floor(value)); + case "j": return JSON.stringify(value); + case "s": return String(value); + } + return "%"; + }); + if (formatOffset !== formatParams.length) + throw Error("parameter count mismatch"); + body.push(formatStringOrScope); + return Codegen; + } + + function toString(functionNameOverride) { + return "function " + (functionNameOverride || functionName || "") + "(" + (functionParams && functionParams.join(",") || "") + "){\n " + body.join("\n ") + "\n}"; + } + + Codegen.toString = toString; + return Codegen; +} + +/** + * Begins generating a function. + * @memberof util + * @function codegen + * @param {string} [functionName] Function name if not anonymous + * @returns {Codegen} Appender that appends code to the function's body + * @variation 2 + */ + +/** + * When set to `true`, codegen will log generated code to console. Useful for debugging. + * @name util.codegen.verbose + * @type {boolean} + */ +codegen.verbose = false; + +},{}],4:[function(require,module,exports){ +"use strict"; +module.exports = EventEmitter; + +/** + * Constructs a new event emitter instance. + * @classdesc A minimal event emitter. + * @memberof util + * @constructor + */ +function EventEmitter() { + + /** + * Registered listeners. + * @type {Object.} + * @private + */ + this._listeners = {}; +} + +/** + * Registers an event listener. + * @param {string} evt Event name + * @param {function} fn Listener + * @param {*} [ctx] Listener context + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.on = function on(evt, fn, ctx) { + (this._listeners[evt] || (this._listeners[evt] = [])).push({ + fn : fn, + ctx : ctx || this + }); + return this; +}; + +/** + * Removes an event listener or any matching listeners if arguments are omitted. + * @param {string} [evt] Event name. Removes all listeners if omitted. + * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted. + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.off = function off(evt, fn) { + if (evt === undefined) + this._listeners = {}; + else { + if (fn === undefined) + this._listeners[evt] = []; + else { + var listeners = this._listeners[evt]; + for (var i = 0; i < listeners.length;) + if (listeners[i].fn === fn) + listeners.splice(i, 1); + else + ++i; + } + } + return this; +}; + +/** + * Emits an event by calling its listeners with the specified arguments. + * @param {string} evt Event name + * @param {...*} args Arguments + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.emit = function emit(evt) { + var listeners = this._listeners[evt]; + if (listeners) { + var args = [], + i = 1; + for (; i < arguments.length;) + args.push(arguments[i++]); + for (i = 0; i < listeners.length;) + listeners[i].fn.apply(listeners[i++].ctx, args); + } + return this; +}; + +},{}],5:[function(require,module,exports){ +"use strict"; +module.exports = fetch; + +var asPromise = require(1), + inquire = require(7); + +var fs = inquire("fs"); + +/** + * Node-style callback as used by {@link util.fetch}. + * @typedef FetchCallback + * @type {function} + * @param {?Error} error Error, if any, otherwise `null` + * @param {string} [contents] File contents, if there hasn't been an error + * @returns {undefined} + */ + +/** + * Options as used by {@link util.fetch}. + * @typedef FetchOptions + * @type {Object} + * @property {boolean} [binary=false] Whether expecting a binary response + * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest + */ + +/** + * Fetches the contents of a file. + * @memberof util + * @param {string} filename File path or url + * @param {FetchOptions} options Fetch options + * @param {FetchCallback} callback Callback function + * @returns {undefined} + */ +function fetch(filename, options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; + } else if (!options) + options = {}; + + if (!callback) + return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this + + // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found. + if (!options.xhr && fs && fs.readFile) + return fs.readFile(filename, function fetchReadFileCallback(err, contents) { + return err && typeof XMLHttpRequest !== "undefined" + ? fetch.xhr(filename, options, callback) + : err + ? callback(err) + : callback(null, options.binary ? contents : contents.toString("utf8")); + }); + + // use the XHR version otherwise. + return fetch.xhr(filename, options, callback); +} + +/** + * Fetches the contents of a file. + * @name util.fetch + * @function + * @param {string} path File path or url + * @param {FetchCallback} callback Callback function + * @returns {undefined} + * @variation 2 + */ + +/** + * Fetches the contents of a file. + * @name util.fetch + * @function + * @param {string} path File path or url + * @param {FetchOptions} [options] Fetch options + * @returns {Promise} Promise + * @variation 3 + */ + +/**/ +fetch.xhr = function fetch_xhr(filename, options, callback) { + var xhr = new XMLHttpRequest(); + xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() { + + if (xhr.readyState !== 4) + return undefined; + + // local cors security errors return status 0 / empty string, too. afaik this cannot be + // reliably distinguished from an actually empty file for security reasons. feel free + // to send a pull request if you are aware of a solution. + if (xhr.status !== 0 && xhr.status !== 200) + return callback(Error("status " + xhr.status)); + + // if binary data is expected, make sure that some sort of array is returned, even if + // ArrayBuffers are not supported. the binary string fallback, however, is unsafe. + if (options.binary) { + var buffer = xhr.response; + if (!buffer) { + buffer = []; + for (var i = 0; i < xhr.responseText.length; ++i) + buffer.push(xhr.responseText.charCodeAt(i) & 255); + } + return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer); + } + return callback(null, xhr.responseText); + }; + + if (options.binary) { + // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers + if ("overrideMimeType" in xhr) + xhr.overrideMimeType("text/plain; charset=x-user-defined"); + xhr.responseType = "arraybuffer"; + } + + xhr.open("GET", filename); + xhr.send(); +}; + +},{"1":1,"7":7}],6:[function(require,module,exports){ +"use strict"; + +module.exports = factory(factory); + +/** + * Reads / writes floats / doubles from / to buffers. + * @name util.float + * @namespace + */ + +/** + * Writes a 32 bit float to a buffer using little endian byte order. + * @name util.float.writeFloatLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Writes a 32 bit float to a buffer using big endian byte order. + * @name util.float.writeFloatBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Reads a 32 bit float from a buffer using little endian byte order. + * @name util.float.readFloatLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Reads a 32 bit float from a buffer using big endian byte order. + * @name util.float.readFloatBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Writes a 64 bit double to a buffer using little endian byte order. + * @name util.float.writeDoubleLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Writes a 64 bit double to a buffer using big endian byte order. + * @name util.float.writeDoubleBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Reads a 64 bit double from a buffer using little endian byte order. + * @name util.float.readDoubleLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Reads a 64 bit double from a buffer using big endian byte order. + * @name util.float.readDoubleBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +// Factory function for the purpose of node-based testing in modified global environments +function factory(exports) { + + // float: typed array + if (typeof Float32Array !== "undefined") (function() { + + var f32 = new Float32Array([ -0 ]), + f8b = new Uint8Array(f32.buffer), + le = f8b[3] === 128; + + function writeFloat_f32_cpy(val, buf, pos) { + f32[0] = val; + buf[pos ] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + } + + function writeFloat_f32_rev(val, buf, pos) { + f32[0] = val; + buf[pos ] = f8b[3]; + buf[pos + 1] = f8b[2]; + buf[pos + 2] = f8b[1]; + buf[pos + 3] = f8b[0]; + } + + /* istanbul ignore next */ + exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; + /* istanbul ignore next */ + exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; + + function readFloat_f32_cpy(buf, pos) { + f8b[0] = buf[pos ]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + return f32[0]; + } + + function readFloat_f32_rev(buf, pos) { + f8b[3] = buf[pos ]; + f8b[2] = buf[pos + 1]; + f8b[1] = buf[pos + 2]; + f8b[0] = buf[pos + 3]; + return f32[0]; + } + + /* istanbul ignore next */ + exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; + /* istanbul ignore next */ + exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; + + // float: ieee754 + })(); else (function() { + + function writeFloat_ieee754(writeUint, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) + writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos); + else if (isNaN(val)) + writeUint(2143289344, buf, pos); + else if (val > 3.4028234663852886e+38) // +-Infinity + writeUint((sign << 31 | 2139095040) >>> 0, buf, pos); + else if (val < 1.1754943508222875e-38) // denormal + writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos); + else { + var exponent = Math.floor(Math.log(val) / Math.LN2), + mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; + writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); + } + } + + exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); + exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); + + function readFloat_ieee754(readUint, buf, pos) { + var uint = readUint(buf, pos), + sign = (uint >> 31) * 2 + 1, + exponent = uint >>> 23 & 255, + mantissa = uint & 8388607; + return exponent === 255 + ? mantissa + ? NaN + : sign * Infinity + : exponent === 0 // denormal + ? sign * 1.401298464324817e-45 * mantissa + : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); + } + + exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE); + exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE); + + })(); + + // double: typed array + if (typeof Float64Array !== "undefined") (function() { + + var f64 = new Float64Array([-0]), + f8b = new Uint8Array(f64.buffer), + le = f8b[7] === 128; + + function writeDouble_f64_cpy(val, buf, pos) { + f64[0] = val; + buf[pos ] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + buf[pos + 4] = f8b[4]; + buf[pos + 5] = f8b[5]; + buf[pos + 6] = f8b[6]; + buf[pos + 7] = f8b[7]; + } + + function writeDouble_f64_rev(val, buf, pos) { + f64[0] = val; + buf[pos ] = f8b[7]; + buf[pos + 1] = f8b[6]; + buf[pos + 2] = f8b[5]; + buf[pos + 3] = f8b[4]; + buf[pos + 4] = f8b[3]; + buf[pos + 5] = f8b[2]; + buf[pos + 6] = f8b[1]; + buf[pos + 7] = f8b[0]; + } + + /* istanbul ignore next */ + exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; + /* istanbul ignore next */ + exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; + + function readDouble_f64_cpy(buf, pos) { + f8b[0] = buf[pos ]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + f8b[4] = buf[pos + 4]; + f8b[5] = buf[pos + 5]; + f8b[6] = buf[pos + 6]; + f8b[7] = buf[pos + 7]; + return f64[0]; + } + + function readDouble_f64_rev(buf, pos) { + f8b[7] = buf[pos ]; + f8b[6] = buf[pos + 1]; + f8b[5] = buf[pos + 2]; + f8b[4] = buf[pos + 3]; + f8b[3] = buf[pos + 4]; + f8b[2] = buf[pos + 5]; + f8b[1] = buf[pos + 6]; + f8b[0] = buf[pos + 7]; + return f64[0]; + } + + /* istanbul ignore next */ + exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; + /* istanbul ignore next */ + exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; + + // double: ieee754 + })(); else (function() { + + function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) { + writeUint(0, buf, pos + off0); + writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1); + } else if (isNaN(val)) { + writeUint(0, buf, pos + off0); + writeUint(2146959360, buf, pos + off1); + } else if (val > 1.7976931348623157e+308) { // +-Infinity + writeUint(0, buf, pos + off0); + writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1); + } else { + var mantissa; + if (val < 2.2250738585072014e-308) { // denormal + mantissa = val / 5e-324; + writeUint(mantissa >>> 0, buf, pos + off0); + writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); + } else { + var exponent = Math.floor(Math.log(val) / Math.LN2); + if (exponent === 1024) + exponent = 1023; + mantissa = val * Math.pow(2, -exponent); + writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); + writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); + } + } + } + + exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); + exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); + + function readDouble_ieee754(readUint, off0, off1, buf, pos) { + var lo = readUint(buf, pos + off0), + hi = readUint(buf, pos + off1); + var sign = (hi >> 31) * 2 + 1, + exponent = hi >>> 20 & 2047, + mantissa = 4294967296 * (hi & 1048575) + lo; + return exponent === 2047 + ? mantissa + ? NaN + : sign * Infinity + : exponent === 0 // denormal + ? sign * 5e-324 * mantissa + : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); + } + + exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); + exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); + + })(); + + return exports; +} + +// uint helpers + +function writeUintLE(val, buf, pos) { + buf[pos ] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; +} + +function writeUintBE(val, buf, pos) { + buf[pos ] = val >>> 24; + buf[pos + 1] = val >>> 16 & 255; + buf[pos + 2] = val >>> 8 & 255; + buf[pos + 3] = val & 255; +} + +function readUintLE(buf, pos) { + return (buf[pos ] + | buf[pos + 1] << 8 + | buf[pos + 2] << 16 + | buf[pos + 3] << 24) >>> 0; +} + +function readUintBE(buf, pos) { + return (buf[pos ] << 24 + | buf[pos + 1] << 16 + | buf[pos + 2] << 8 + | buf[pos + 3]) >>> 0; +} + +},{}],7:[function(require,module,exports){ +"use strict"; +module.exports = inquire; + +/** + * Requires a module only if available. + * @memberof util + * @param {string} moduleName Module to require + * @returns {?Object} Required module if available and not empty, otherwise `null` + */ +function inquire(moduleName) { + try { + var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval + if (mod && (mod.length || Object.keys(mod).length)) + return mod; + } catch (e) {} // eslint-disable-line no-empty + return null; +} + +},{}],8:[function(require,module,exports){ +"use strict"; + +/** + * A minimal path module to resolve Unix, Windows and URL paths alike. + * @memberof util + * @namespace + */ +var path = exports; + +var isAbsolute = +/** + * Tests if the specified path is absolute. + * @param {string} path Path to test + * @returns {boolean} `true` if path is absolute + */ +path.isAbsolute = function isAbsolute(path) { + return /^(?:\/|\w+:)/.test(path); +}; + +var normalize = +/** + * Normalizes the specified path. + * @param {string} path Path to normalize + * @returns {string} Normalized path + */ +path.normalize = function normalize(path) { + path = path.replace(/\\/g, "/") + .replace(/\/{2,}/g, "/"); + var parts = path.split("/"), + absolute = isAbsolute(path), + prefix = ""; + if (absolute) + prefix = parts.shift() + "/"; + for (var i = 0; i < parts.length;) { + if (parts[i] === "..") { + if (i > 0 && parts[i - 1] !== "..") + parts.splice(--i, 2); + else if (absolute) + parts.splice(i, 1); + else + ++i; + } else if (parts[i] === ".") + parts.splice(i, 1); + else + ++i; + } + return prefix + parts.join("/"); +}; + +/** + * Resolves the specified include path against the specified origin path. + * @param {string} originPath Path to the origin file + * @param {string} includePath Include path relative to origin path + * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized + * @returns {string} Path to the include file + */ +path.resolve = function resolve(originPath, includePath, alreadyNormalized) { + if (!alreadyNormalized) + includePath = normalize(includePath); + if (isAbsolute(includePath)) + return includePath; + if (!alreadyNormalized) + originPath = normalize(originPath); + return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath; +}; + +},{}],9:[function(require,module,exports){ +"use strict"; +module.exports = pool; + +/** + * An allocator as used by {@link util.pool}. + * @typedef PoolAllocator + * @type {function} + * @param {number} size Buffer size + * @returns {Uint8Array} Buffer + */ + +/** + * A slicer as used by {@link util.pool}. + * @typedef PoolSlicer + * @type {function} + * @param {number} start Start offset + * @param {number} end End offset + * @returns {Uint8Array} Buffer slice + * @this {Uint8Array} + */ + +/** + * A general purpose buffer pool. + * @memberof util + * @function + * @param {PoolAllocator} alloc Allocator + * @param {PoolSlicer} slice Slicer + * @param {number} [size=8192] Slab size + * @returns {PoolAllocator} Pooled allocator + */ +function pool(alloc, slice, size) { + var SIZE = size || 8192; + var MAX = SIZE >>> 1; + var slab = null; + var offset = SIZE; + return function pool_alloc(size) { + if (size < 1 || size > MAX) + return alloc(size); + if (offset + size > SIZE) { + slab = alloc(SIZE); + offset = 0; + } + var buf = slice.call(slab, offset, offset += size); + if (offset & 7) // align to 32 bit + offset = (offset | 7) + 1; + return buf; + }; +} + +},{}],10:[function(require,module,exports){ +"use strict"; + +/** + * A minimal UTF8 implementation for number arrays. + * @memberof util + * @namespace + */ +var utf8 = exports; + +/** + * Calculates the UTF8 byte length of a string. + * @param {string} string String + * @returns {number} Byte length + */ +utf8.length = function utf8_length(string) { + var len = 0, + c = 0; + for (var i = 0; i < string.length; ++i) { + c = string.charCodeAt(i); + if (c < 128) + len += 1; + else if (c < 2048) + len += 2; + else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) { + ++i; + len += 4; + } else + len += 3; + } + return len; +}; + +/** + * Reads UTF8 bytes as a string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} String read + */ +utf8.read = function utf8_read(buffer, start, end) { + var len = end - start; + if (len < 1) + return ""; + var parts = null, + chunk = [], + i = 0, // char offset + t; // temporary + while (start < end) { + t = buffer[start++]; + if (t < 128) + chunk[i++] = t; + else if (t > 191 && t < 224) + chunk[i++] = (t & 31) << 6 | buffer[start++] & 63; + else if (t > 239 && t < 365) { + t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000; + chunk[i++] = 0xD800 + (t >> 10); + chunk[i++] = 0xDC00 + (t & 1023); + } else + chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i = 0; + } + } + if (parts) { + if (i) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i)); +}; + +/** + * Writes a string as UTF8 bytes. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Bytes written + */ +utf8.write = function utf8_write(string, buffer, offset) { + var start = offset, + c1, // character 1 + c2; // character 2 + for (var i = 0; i < string.length; ++i) { + c1 = string.charCodeAt(i); + if (c1 < 128) { + buffer[offset++] = c1; + } else if (c1 < 2048) { + buffer[offset++] = c1 >> 6 | 192; + buffer[offset++] = c1 & 63 | 128; + } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) { + c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF); + ++i; + buffer[offset++] = c1 >> 18 | 240; + buffer[offset++] = c1 >> 12 & 63 | 128; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } else { + buffer[offset++] = c1 >> 12 | 224; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } + } + return offset - start; +}; + +},{}],11:[function(require,module,exports){ +"use strict"; +/** + * Runtime message from/to plain object converters. + * @namespace + */ +var converter = exports; + +var Enum = require(14), + util = require(33); + +/** + * Generates a partial value fromObject conveter. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {number} fieldIndex Field index + * @param {string} prop Property reference + * @returns {Codegen} Codegen instance + * @ignore + */ +function genValuePartial_fromObject(gen, field, fieldIndex, prop) { + var defaultAlreadyEmitted = false; + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + if (field.resolvedType) { + if (field.resolvedType instanceof Enum) { gen + ("switch(d%s){", prop); + for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) { + // enum unknown values passthrough + if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen + ("default:") + ("if(typeof(d%s)===\"number\"){m%s=d%s;break}", prop, prop, prop); + if (!field.repeated) gen // fallback to default value only for + // arrays, to avoid leaving holes. + ("break"); // for non-repeated fields, just ignore + defaultAlreadyEmitted = true; + } + gen + ("case%j:", keys[i]) + ("case %i:", values[keys[i]]) + ("m%s=%j", prop, values[keys[i]]) + ("break"); + } gen + ("}"); + } else gen + ("if(typeof d%s!==\"object\")", prop) + ("throw TypeError(%j)", field.fullName + ": object expected") + ("m%s=types[%i].fromObject(d%s)", prop, fieldIndex, prop); + } else { + var isUnsigned = false; + switch (field.type) { + case "double": + case "float": gen + ("m%s=Number(d%s)", prop, prop); // also catches "NaN", "Infinity" + break; + case "uint32": + case "fixed32": gen + ("m%s=d%s>>>0", prop, prop); + break; + case "int32": + case "sint32": + case "sfixed32": gen + ("m%s=d%s|0", prop, prop); + break; + case "uint64": + isUnsigned = true; + // eslint-disable-next-line no-fallthrough + case "int64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(util.Long)") + ("(m%s=util.Long.fromValue(d%s)).unsigned=%j", prop, prop, isUnsigned) + ("else if(typeof d%s===\"string\")", prop) + ("m%s=parseInt(d%s,10)", prop, prop) + ("else if(typeof d%s===\"number\")", prop) + ("m%s=d%s", prop, prop) + ("else if(typeof d%s===\"object\")", prop) + ("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : ""); + break; + case "bytes": gen + ("if(typeof d%s===\"string\")", prop) + ("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop) + ("else if(d%s.length >= 0)", prop) + ("m%s=d%s", prop, prop); + break; + case "string": gen + ("m%s=String(d%s)", prop, prop); + break; + case "bool": gen + ("m%s=Boolean(d%s)", prop, prop); + break; + /* default: gen + ("m%s=d%s", prop, prop); + break; */ + } + } + return gen; + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ +} + +/** + * Generates a plain object to runtime message converter specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +converter.fromObject = function fromObject(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var fields = mtype.fieldsArray; + var gen = util.codegen(["d"], mtype.name + "$fromObject") + ("if(d instanceof this.ctor)") + ("return d"); + if (!fields.length) return gen + ("return new this.ctor"); + gen + ("var m=new this.ctor"); + for (var i = 0; i < fields.length; ++i) { + var field = fields[i].resolve(), + prop = util.safeProp(field.name); + + // Map fields + if (field.map) { gen + ("if(d%s){", prop) + ("if(typeof d%s!==\"object\")", prop) + ("throw TypeError(%j)", field.fullName + ": object expected") + ("m%s={}", prop) + ("for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s", prop, prop, prop, prop, isUnsigned ? "true": "", prop); + break; + case "bytes": gen + ("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", prop, prop, prop, prop, prop); + break; + default: gen + ("d%s=m%s", prop, prop); + break; + } + } + return gen; + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ +} + +/** + * Generates a runtime message to plain object converter specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +converter.toObject = function toObject(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById); + if (!fields.length) + return util.codegen()("return {}"); + var gen = util.codegen(["m", "o"], mtype.name + "$toObject") + ("if(!o)") + ("o={}") + ("var d={}"); + + var repeatedFields = [], + mapFields = [], + normalFields = [], + i = 0; + for (; i < fields.length; ++i) + if (!fields[i].partOf) + ( fields[i].resolve().repeated ? repeatedFields + : fields[i].map ? mapFields + : normalFields).push(fields[i]); + + if (repeatedFields.length) { gen + ("if(o.arrays||o.defaults){"); + for (i = 0; i < repeatedFields.length; ++i) gen + ("d%s=[]", util.safeProp(repeatedFields[i].name)); + gen + ("}"); + } + + if (mapFields.length) { gen + ("if(o.objects||o.defaults){"); + for (i = 0; i < mapFields.length; ++i) gen + ("d%s={}", util.safeProp(mapFields[i].name)); + gen + ("}"); + } + + if (normalFields.length) { gen + ("if(o.defaults){"); + for (i = 0; i < normalFields.length; ++i) { + var field = normalFields[i], + prop = util.safeProp(field.name); + if (field.resolvedType instanceof Enum) gen + ("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault); + else if (field.long) gen + ("if(util.Long){") + ("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned) + ("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n", prop) + ("}else") + ("d%s=o.longs===String?%j:%i", prop, field.typeDefault.toString(), field.typeDefault.toNumber()); + else if (field.bytes) { + var arrayDefault = "[" + Array.prototype.slice.call(field.typeDefault).join(",") + "]"; + gen + ("if(o.bytes===String)d%s=%j", prop, String.fromCharCode.apply(String, field.typeDefault)) + ("else{") + ("d%s=%s", prop, arrayDefault) + ("if(o.bytes!==Array)d%s=util.newBuffer(d%s)", prop, prop) + ("}"); + } else gen + ("d%s=%j", prop, field.typeDefault); // also messages (=null) + } gen + ("}"); + } + var hasKs2 = false; + for (i = 0; i < fields.length; ++i) { + var field = fields[i], + index = mtype._fieldsArray.indexOf(field), + prop = util.safeProp(field.name); + if (field.map) { + if (!hasKs2) { hasKs2 = true; gen + ("var ks2"); + } gen + ("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop) + ("d%s={}", prop) + ("for(var j=0;j>>3){"); + + var i = 0; + for (; i < /* initializes */ mtype.fieldsArray.length; ++i) { + var field = mtype._fieldsArray[i].resolve(), + type = field.resolvedType instanceof Enum ? "int32" : field.type, + ref = "m" + util.safeProp(field.name); gen + ("case %i: {", field.id); + + // Map fields + if (field.map) { gen + ("if(%s===util.emptyObject)", ref) + ("%s={}", ref) + ("var c2 = r.uint32()+r.pos"); + + if (types.defaults[field.keyType] !== undefined) gen + ("k=%j", types.defaults[field.keyType]); + else gen + ("k=null"); + + if (types.defaults[type] !== undefined) gen + ("value=%j", types.defaults[type]); + else gen + ("value=null"); + + gen + ("while(r.pos>>3){") + ("case 1: k=r.%s(); break", field.keyType) + ("case 2:"); + + if (types.basic[type] === undefined) gen + ("value=types[%i].decode(r,r.uint32())", i); // can't be groups + else gen + ("value=r.%s()", type); + + gen + ("break") + ("default:") + ("r.skipType(tag2&7)") + ("break") + ("}") + ("}"); + + if (types.long[field.keyType] !== undefined) gen + ("%s[typeof k===\"object\"?util.longToHash(k):k]=value", ref); + else gen + ("%s[k]=value", ref); + + // Repeated fields + } else if (field.repeated) { gen + + ("if(!(%s&&%s.length))", ref, ref) + ("%s=[]", ref); + + // Packable (always check for forward and backward compatiblity) + if (types.packed[type] !== undefined) gen + ("if((t&7)===2){") + ("var c2=r.uint32()+r.pos") + ("while(r.pos>> 0, (field.id << 3 | 4) >>> 0) + : gen("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0); +} + +/** + * Generates an encoder specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +function encoder(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var gen = util.codegen(["m", "w"], mtype.name + "$encode") + ("if(!w)") + ("w=Writer.create()"); + + var i, ref; + + // "when a message is serialized its known fields should be written sequentially by field number" + var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById); + + for (var i = 0; i < fields.length; ++i) { + var field = fields[i].resolve(), + index = mtype._fieldsArray.indexOf(field), + type = field.resolvedType instanceof Enum ? "int32" : field.type, + wireType = types.basic[type]; + ref = "m" + util.safeProp(field.name); + + // Map fields + if (field.map) { + gen + ("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){", ref, field.name) // !== undefined && !== null + ("for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType); + if (wireType === undefined) gen + ("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", index, ref); // can't be groups + else gen + (".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref); + gen + ("}") + ("}"); + + // Repeated fields + } else if (field.repeated) { gen + ("if(%s!=null&&%s.length){", ref, ref); // !== undefined && !== null + + // Packed repeated + if (field.packed && types.packed[type] !== undefined) { gen + + ("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0) + ("for(var i=0;i<%s.length;++i)", ref) + ("w.%s(%s[i])", type, ref) + ("w.ldelim()"); + + // Non-packed + } else { gen + + ("for(var i=0;i<%s.length;++i)", ref); + if (wireType === undefined) + genTypePartial(gen, field, index, ref + "[i]"); + else gen + ("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref); + + } gen + ("}"); + + // Non-repeated + } else { + if (field.optional) gen + ("if(%s!=null&&Object.hasOwnProperty.call(m,%j))", ref, field.name); // !== undefined && !== null + + if (wireType === undefined) + genTypePartial(gen, field, index, ref); + else gen + ("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref); + + } + } + + return gen + ("return w"); + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ +} + +},{"14":14,"32":32,"33":33}],14:[function(require,module,exports){ +"use strict"; +module.exports = Enum; + +// extends ReflectionObject +var ReflectionObject = require(22); +((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum"; + +var Namespace = require(21), + util = require(33); + +/** + * Constructs a new enum instance. + * @classdesc Reflected enum. + * @extends ReflectionObject + * @constructor + * @param {string} name Unique name within its namespace + * @param {Object.} [values] Enum values as an object, by name + * @param {Object.} [options] Declared options + * @param {string} [comment] The comment for this enum + * @param {Object.} [comments] The value comments for this enum + * @param {Object.>|undefined} [valuesOptions] The value options for this enum + */ +function Enum(name, values, options, comment, comments, valuesOptions) { + ReflectionObject.call(this, name, options); + + if (values && typeof values !== "object") + throw TypeError("values must be an object"); + + /** + * Enum values by id. + * @type {Object.} + */ + this.valuesById = {}; + + /** + * Enum values by name. + * @type {Object.} + */ + this.values = Object.create(this.valuesById); // toJSON, marker + + /** + * Enum comment text. + * @type {string|null} + */ + this.comment = comment; + + /** + * Value comment texts, if any. + * @type {Object.} + */ + this.comments = comments || {}; + + /** + * Values options, if any + * @type {Object>|undefined} + */ + this.valuesOptions = valuesOptions; + + /** + * Resolved values features, if any + * @type {Object>|undefined} + */ + this._valuesFeatures = {}; + + /** + * Reserved ranges, if any. + * @type {Array.} + */ + this.reserved = undefined; // toJSON + + // Note that values inherit valuesById on their prototype which makes them a TypeScript- + // compatible enum. This is used by pbts to write actual enum definitions that work for + // static and reflection code alike instead of emitting generic object definitions. + + if (values) + for (var keys = Object.keys(values), i = 0; i < keys.length; ++i) + if (typeof values[keys[i]] === "number") // use forward entries only + this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i]; +} + +/** + * @override + */ +Enum.prototype._resolveFeatures = function _resolveFeatures(edition) { + edition = this._edition || edition; + ReflectionObject.prototype._resolveFeatures.call(this, edition); + + Object.keys(this.values).forEach(key => { + var parentFeaturesCopy = Object.assign({}, this._features); + this._valuesFeatures[key] = Object.assign(parentFeaturesCopy, this.valuesOptions && this.valuesOptions[key] && this.valuesOptions[key].features); + }); + + return this; +}; + +/** + * Enum descriptor. + * @interface IEnum + * @property {Object.} values Enum values + * @property {Object.} [options] Enum options + */ + +/** + * Constructs an enum from an enum descriptor. + * @param {string} name Enum name + * @param {IEnum} json Enum descriptor + * @returns {Enum} Created enum + * @throws {TypeError} If arguments are invalid + */ +Enum.fromJSON = function fromJSON(name, json) { + var enm = new Enum(name, json.values, json.options, json.comment, json.comments); + enm.reserved = json.reserved; + if (json.edition) + enm._edition = json.edition; + enm._defaultEdition = "proto3"; // For backwards-compatibility. + return enm; +}; + +/** + * Converts this enum to an enum descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IEnum} Enum descriptor + */ +Enum.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "edition" , this._editionToJSON(), + "options" , this.options, + "valuesOptions" , this.valuesOptions, + "values" , this.values, + "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined, + "comment" , keepComments ? this.comment : undefined, + "comments" , keepComments ? this.comments : undefined + ]); +}; + +/** + * Adds a value to this enum. + * @param {string} name Value name + * @param {number} id Value id + * @param {string} [comment] Comment, if any + * @param {Object.|undefined} [options] Options, if any + * @returns {Enum} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a value with this name or id + */ +Enum.prototype.add = function add(name, id, comment, options) { + // utilized by the parser but not by .fromJSON + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + if (!util.isInteger(id)) + throw TypeError("id must be an integer"); + + if (this.values[name] !== undefined) + throw Error("duplicate name '" + name + "' in " + this); + + if (this.isReservedId(id)) + throw Error("id " + id + " is reserved in " + this); + + if (this.isReservedName(name)) + throw Error("name '" + name + "' is reserved in " + this); + + if (this.valuesById[id] !== undefined) { + if (!(this.options && this.options.allow_alias)) + throw Error("duplicate id " + id + " in " + this); + this.values[name] = id; + } else + this.valuesById[this.values[name] = id] = name; + + if (options) { + if (this.valuesOptions === undefined) + this.valuesOptions = {}; + this.valuesOptions[name] = options || null; + } + + this.comments[name] = comment || null; + return this; +}; + +/** + * Removes a value from this enum + * @param {string} name Value name + * @returns {Enum} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `name` is not a name of this enum + */ +Enum.prototype.remove = function remove(name) { + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + var val = this.values[name]; + if (val == null) + throw Error("name '" + name + "' does not exist in " + this); + + delete this.valuesById[val]; + delete this.values[name]; + delete this.comments[name]; + if (this.valuesOptions) + delete this.valuesOptions[name]; + + return this; +}; + +/** + * Tests if the specified id is reserved. + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Enum.prototype.isReservedId = function isReservedId(id) { + return Namespace.isReservedId(this.reserved, id); +}; + +/** + * Tests if the specified name is reserved. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Enum.prototype.isReservedName = function isReservedName(name) { + return Namespace.isReservedName(this.reserved, name); +}; + +},{"21":21,"22":22,"33":33}],15:[function(require,module,exports){ +"use strict"; +module.exports = Field; + +// extends ReflectionObject +var ReflectionObject = require(22); +((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field"; + +var Enum = require(14), + types = require(32), + util = require(33); + +var Type; // cyclic + +var ruleRe = /^required|optional|repeated$/; + +/** + * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class. + * @name Field + * @classdesc Reflected message field. + * @extends FieldBase + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} type Value type + * @param {string|Object.} [rule="optional"] Field rule + * @param {string|Object.} [extend] Extended type if different from parent + * @param {Object.} [options] Declared options + */ + +/** + * Constructs a field from a field descriptor. + * @param {string} name Field name + * @param {IField} json Field descriptor + * @returns {Field} Created field + * @throws {TypeError} If arguments are invalid + */ +Field.fromJSON = function fromJSON(name, json) { + var field = new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment); + if (json.edition) + field._edition = json.edition; + field._defaultEdition = "proto3"; // For backwards-compatibility. + return field; +}; + +/** + * Not an actual constructor. Use {@link Field} instead. + * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions. + * @exports FieldBase + * @extends ReflectionObject + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} type Value type + * @param {string|Object.} [rule="optional"] Field rule + * @param {string|Object.} [extend] Extended type if different from parent + * @param {Object.} [options] Declared options + * @param {string} [comment] Comment associated with this field + */ +function Field(name, id, type, rule, extend, options, comment) { + + if (util.isObject(rule)) { + comment = extend; + options = rule; + rule = extend = undefined; + } else if (util.isObject(extend)) { + comment = options; + options = extend; + extend = undefined; + } + + ReflectionObject.call(this, name, options); + + if (!util.isInteger(id) || id < 0) + throw TypeError("id must be a non-negative integer"); + + if (!util.isString(type)) + throw TypeError("type must be a string"); + + if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase())) + throw TypeError("rule must be a string rule"); + + if (extend !== undefined && !util.isString(extend)) + throw TypeError("extend must be a string"); + + /** + * Field rule, if any. + * @type {string|undefined} + */ + if (rule === "proto3_optional") { + rule = "optional"; + } + this.rule = rule && rule !== "optional" ? rule : undefined; // toJSON + + /** + * Field type. + * @type {string} + */ + this.type = type; // toJSON + + /** + * Unique field id. + * @type {number} + */ + this.id = id; // toJSON, marker + + /** + * Extended type if different from parent. + * @type {string|undefined} + */ + this.extend = extend || undefined; // toJSON + + /** + * Whether this field is repeated. + * @type {boolean} + */ + this.repeated = rule === "repeated"; + + /** + * Whether this field is a map or not. + * @type {boolean} + */ + this.map = false; + + /** + * Message this field belongs to. + * @type {Type|null} + */ + this.message = null; + + /** + * OneOf this field belongs to, if any, + * @type {OneOf|null} + */ + this.partOf = null; + + /** + * The field type's default value. + * @type {*} + */ + this.typeDefault = null; + + /** + * The field's default value on prototypes. + * @type {*} + */ + this.defaultValue = null; + + /** + * Whether this field's value should be treated as a long. + * @type {boolean} + */ + this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false; + + /** + * Whether this field's value is a buffer. + * @type {boolean} + */ + this.bytes = type === "bytes"; + + /** + * Resolved type if not a basic type. + * @type {Type|Enum|null} + */ + this.resolvedType = null; + + /** + * Sister-field within the extended type if a declaring extension field. + * @type {Field|null} + */ + this.extensionField = null; + + /** + * Sister-field within the declaring namespace if an extended field. + * @type {Field|null} + */ + this.declaringField = null; + + /** + * Comment for this field. + * @type {string|null} + */ + this.comment = comment; +} + +/** + * Determines whether this field is required. + * @name Field#required + * @type {boolean} + * @readonly + */ +Object.defineProperty(Field.prototype, "required", { + get: function() { + return this._features.field_presence === "LEGACY_REQUIRED"; + } +}); + +/** + * Determines whether this field is not required. + * @name Field#optional + * @type {boolean} + * @readonly + */ +Object.defineProperty(Field.prototype, "optional", { + get: function() { + return !this.required; + } +}); + +/** + * Determines whether this field uses tag-delimited encoding. In proto2 this + * corresponded to group syntax. + * @name Field#delimited + * @type {boolean} + * @readonly + */ +Object.defineProperty(Field.prototype, "delimited", { + get: function() { + return this.resolvedType instanceof Type && + this._features.message_encoding === "DELIMITED"; + } +}); + +/** + * Determines whether this field is packed. Only relevant when repeated. + * @name Field#packed + * @type {boolean} + * @readonly + */ +Object.defineProperty(Field.prototype, "packed", { + get: function() { + return this._features.repeated_field_encoding === "PACKED"; + } +}); + +/** + * Determines whether this field tracks presence. + * @name Field#hasPresence + * @type {boolean} + * @readonly + */ +Object.defineProperty(Field.prototype, "hasPresence", { + get: function() { + if (this.repeated || this.map) { + return false; + } + return this.partOf || // oneofs + this.declaringField || this.extensionField || // extensions + this._features.field_presence !== "IMPLICIT"; + } +}); + +/** + * @override + */ +Field.prototype.setOption = function setOption(name, value, ifNotSet) { + return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet); +}; + +/** + * Field descriptor. + * @interface IField + * @property {string} [rule="optional"] Field rule + * @property {string} type Field type + * @property {number} id Field id + * @property {Object.} [options] Field options + */ + +/** + * Extension field descriptor. + * @interface IExtensionField + * @extends IField + * @property {string} extend Extended type + */ + +/** + * Converts this field to a field descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IField} Field descriptor + */ +Field.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "edition" , this._editionToJSON(), + "rule" , this.rule !== "optional" && this.rule || undefined, + "type" , this.type, + "id" , this.id, + "extend" , this.extend, + "options" , this.options, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * Resolves this field's type references. + * @returns {Field} `this` + * @throws {Error} If any reference cannot be resolved + */ +Field.prototype.resolve = function resolve() { + + if (this.resolved) + return this; + + if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it + this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type); + if (this.resolvedType instanceof Type) + this.typeDefault = null; + else // instanceof Enum + this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined + } else if (this.options && this.options.proto3_optional) { + // proto3 scalar value marked optional; should default to null + this.typeDefault = null; + } + + // use explicitly set default value if present + if (this.options && this.options["default"] != null) { + this.typeDefault = this.options["default"]; + if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string") + this.typeDefault = this.resolvedType.values[this.typeDefault]; + } + + // remove unnecessary options + if (this.options) { + if (this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum)) + delete this.options.packed; + if (!Object.keys(this.options).length) + this.options = undefined; + } + + // convert to internal data type if necesssary + if (this.long) { + this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u"); + + /* istanbul ignore else */ + if (Object.freeze) + Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it) + + } else if (this.bytes && typeof this.typeDefault === "string") { + var buf; + if (util.base64.test(this.typeDefault)) + util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0); + else + util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0); + this.typeDefault = buf; + } + + // take special care of maps and repeated fields + if (this.map) + this.defaultValue = util.emptyObject; + else if (this.repeated) + this.defaultValue = util.emptyArray; + else + this.defaultValue = this.typeDefault; + + // ensure proper value on prototype + if (this.parent instanceof Type) + this.parent.ctor.prototype[this.name] = this.defaultValue; + + return ReflectionObject.prototype.resolve.call(this); +}; + +/** + * Infers field features from legacy syntax that may have been specified differently. + * in older editions. + * @param {string|undefined} edition The edition this proto is on, or undefined if pre-editions + * @returns {object} The feature values to override + */ +Field.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(edition) { + if (edition !== "proto2" && edition !== "proto3") { + return {}; + } + + var features = {}; + + if (this.rule === "required") { + features.field_presence = "LEGACY_REQUIRED"; + } + if (this.parent && types.defaults[this.type] === undefined) { + // We can't use resolvedType because types may not have been resolved yet. However, + // legacy groups are always in the same scope as the field so we don't have to do a + // full scan of the tree. + var type = this.parent.get(this.type.split(".").pop()); + if (type && type instanceof Type && type.group) { + features.message_encoding = "DELIMITED"; + } + } + if (this.getOption("packed") === true) { + features.repeated_field_encoding = "PACKED"; + } else if (this.getOption("packed") === false) { + features.repeated_field_encoding = "EXPANDED"; + } + return features; +}; + +/** + * @override + */ +Field.prototype._resolveFeatures = function _resolveFeatures(edition) { + return ReflectionObject.prototype._resolveFeatures.call(this, this._edition || edition); +}; + +/** + * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript). + * @typedef FieldDecorator + * @type {function} + * @param {Object} prototype Target prototype + * @param {string} fieldName Field name + * @returns {undefined} + */ + +/** + * Field decorator (TypeScript). + * @name Field.d + * @function + * @param {number} fieldId Field id + * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"string"|"bool"|"bytes"|Object} fieldType Field type + * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule + * @param {T} [defaultValue] Default value + * @returns {FieldDecorator} Decorator function + * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[] + */ +Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) { + + // submessage: decorate the submessage and use its name as the type + if (typeof fieldType === "function") + fieldType = util.decorateType(fieldType).name; + + // enum reference: create a reflected copy of the enum and keep reuseing it + else if (fieldType && typeof fieldType === "object") + fieldType = util.decorateEnum(fieldType).name; + + return function fieldDecorator(prototype, fieldName) { + util.decorateType(prototype.constructor) + .add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue })); + }; +}; + +/** + * Field decorator (TypeScript). + * @name Field.d + * @function + * @param {number} fieldId Field id + * @param {Constructor|string} fieldType Field type + * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule + * @returns {FieldDecorator} Decorator function + * @template T extends Message + * @variation 2 + */ +// like Field.d but without a default value + +// Sets up cyclic dependencies (called in index-light) +Field._configure = function configure(Type_) { + Type = Type_; +}; + +},{"14":14,"22":22,"32":32,"33":33}],16:[function(require,module,exports){ +"use strict"; +var protobuf = module.exports = require(17); + +protobuf.build = "light"; + +/** + * A node-style callback as used by {@link load} and {@link Root#load}. + * @typedef LoadCallback + * @type {function} + * @param {Error|null} error Error, if any, otherwise `null` + * @param {Root} [root] Root, if there hasn't been an error + * @returns {undefined} + */ + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. + * @param {string|string[]} filename One or multiple files to load + * @param {Root} root Root namespace, defaults to create a new one if omitted. + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @see {@link Root#load} + */ +function load(filename, root, callback) { + if (typeof root === "function") { + callback = root; + root = new protobuf.Root(); + } else if (!root) + root = new protobuf.Root(); + return root.load(filename, callback); +} + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. + * @name load + * @function + * @param {string|string[]} filename One or multiple files to load + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @see {@link Root#load} + * @variation 2 + */ +// function load(filename:string, callback:LoadCallback):undefined + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise. + * @name load + * @function + * @param {string|string[]} filename One or multiple files to load + * @param {Root} [root] Root namespace, defaults to create a new one if omitted. + * @returns {Promise} Promise + * @see {@link Root#load} + * @variation 3 + */ +// function load(filename:string, [root:Root]):Promise + +protobuf.load = load; + +/** + * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only). + * @param {string|string[]} filename One or multiple files to load + * @param {Root} [root] Root namespace, defaults to create a new one if omitted. + * @returns {Root} Root namespace + * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid + * @see {@link Root#loadSync} + */ +function loadSync(filename, root) { + if (!root) + root = new protobuf.Root(); + return root.loadSync(filename); +} + +protobuf.loadSync = loadSync; + +// Serialization +protobuf.encoder = require(13); +protobuf.decoder = require(12); +protobuf.verifier = require(36); +protobuf.converter = require(11); + +// Reflection +protobuf.ReflectionObject = require(22); +protobuf.Namespace = require(21); +protobuf.Root = require(26); +protobuf.Enum = require(14); +protobuf.Type = require(31); +protobuf.Field = require(15); +protobuf.OneOf = require(23); +protobuf.MapField = require(18); +protobuf.Service = require(30); +protobuf.Method = require(20); + +// Runtime +protobuf.Message = require(19); +protobuf.wrappers = require(37); + +// Utility +protobuf.types = require(32); +protobuf.util = require(33); + +// Set up possibly cyclic reflection dependencies +protobuf.ReflectionObject._configure(protobuf.Root); +protobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum); +protobuf.Root._configure(protobuf.Type); +protobuf.Field._configure(protobuf.Type); + +},{"11":11,"12":12,"13":13,"14":14,"15":15,"17":17,"18":18,"19":19,"20":20,"21":21,"22":22,"23":23,"26":26,"30":30,"31":31,"32":32,"33":33,"36":36,"37":37}],17:[function(require,module,exports){ +"use strict"; +var protobuf = exports; + +/** + * Build type, one of `"full"`, `"light"` or `"minimal"`. + * @name build + * @type {string} + * @const + */ +protobuf.build = "minimal"; + +// Serialization +protobuf.Writer = require(38); +protobuf.BufferWriter = require(39); +protobuf.Reader = require(24); +protobuf.BufferReader = require(25); + +// Utility +protobuf.util = require(35); +protobuf.rpc = require(28); +protobuf.roots = require(27); +protobuf.configure = configure; + +/* istanbul ignore next */ +/** + * Reconfigures the library according to the environment. + * @returns {undefined} + */ +function configure() { + protobuf.util._configure(); + protobuf.Writer._configure(protobuf.BufferWriter); + protobuf.Reader._configure(protobuf.BufferReader); +} + +// Set up buffer utility according to the environment +configure(); + +},{"24":24,"25":25,"27":27,"28":28,"35":35,"38":38,"39":39}],18:[function(require,module,exports){ +"use strict"; +module.exports = MapField; + +// extends Field +var Field = require(15); +((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField"; + +var types = require(32), + util = require(33); + +/** + * Constructs a new map field instance. + * @classdesc Reflected map field. + * @extends FieldBase + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} keyType Key type + * @param {string} type Value type + * @param {Object.} [options] Declared options + * @param {string} [comment] Comment associated with this field + */ +function MapField(name, id, keyType, type, options, comment) { + Field.call(this, name, id, type, undefined, undefined, options, comment); + + /* istanbul ignore if */ + if (!util.isString(keyType)) + throw TypeError("keyType must be a string"); + + /** + * Key type. + * @type {string} + */ + this.keyType = keyType; // toJSON, marker + + /** + * Resolved key type if not a basic type. + * @type {ReflectionObject|null} + */ + this.resolvedKeyType = null; + + // Overrides Field#map + this.map = true; +} + +/** + * Map field descriptor. + * @interface IMapField + * @extends {IField} + * @property {string} keyType Key type + */ + +/** + * Extension map field descriptor. + * @interface IExtensionMapField + * @extends IMapField + * @property {string} extend Extended type + */ + +/** + * Constructs a map field from a map field descriptor. + * @param {string} name Field name + * @param {IMapField} json Map field descriptor + * @returns {MapField} Created map field + * @throws {TypeError} If arguments are invalid + */ +MapField.fromJSON = function fromJSON(name, json) { + return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment); +}; + +/** + * Converts this map field to a map field descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IMapField} Map field descriptor + */ +MapField.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "keyType" , this.keyType, + "type" , this.type, + "id" , this.id, + "extend" , this.extend, + "options" , this.options, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * @override + */ +MapField.prototype.resolve = function resolve() { + if (this.resolved) + return this; + + // Besides a value type, map fields have a key type that may be "any scalar type except for floating point types and bytes" + if (types.mapKey[this.keyType] === undefined) + throw Error("invalid key type: " + this.keyType); + + return Field.prototype.resolve.call(this); +}; + +/** + * Map field decorator (TypeScript). + * @name MapField.d + * @function + * @param {number} fieldId Field id + * @param {"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"} fieldKeyType Field key type + * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"|"bytes"|Object|Constructor<{}>} fieldValueType Field value type + * @returns {FieldDecorator} Decorator function + * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> } + */ +MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) { + + // submessage value: decorate the submessage and use its name as the type + if (typeof fieldValueType === "function") + fieldValueType = util.decorateType(fieldValueType).name; + + // enum reference value: create a reflected copy of the enum and keep reuseing it + else if (fieldValueType && typeof fieldValueType === "object") + fieldValueType = util.decorateEnum(fieldValueType).name; + + return function mapFieldDecorator(prototype, fieldName) { + util.decorateType(prototype.constructor) + .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType)); + }; +}; + +},{"15":15,"32":32,"33":33}],19:[function(require,module,exports){ +"use strict"; +module.exports = Message; + +var util = require(35); + +/** + * Constructs a new message instance. + * @classdesc Abstract runtime message. + * @constructor + * @param {Properties} [properties] Properties to set + * @template T extends object = object + */ +function Message(properties) { + // not used internally + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + this[keys[i]] = properties[keys[i]]; +} + +/** + * Reference to the reflected type. + * @name Message.$type + * @type {Type} + * @readonly + */ + +/** + * Reference to the reflected type. + * @name Message#$type + * @type {Type} + * @readonly + */ + +/*eslint-disable valid-jsdoc*/ + +/** + * Creates a new message of this type using the specified properties. + * @param {Object.} [properties] Properties to set + * @returns {Message} Message instance + * @template T extends Message + * @this Constructor + */ +Message.create = function create(properties) { + return this.$type.create(properties); +}; + +/** + * Encodes a message of this type. + * @param {T|Object.} message Message to encode + * @param {Writer} [writer] Writer to use + * @returns {Writer} Writer + * @template T extends Message + * @this Constructor + */ +Message.encode = function encode(message, writer) { + return this.$type.encode(message, writer); +}; + +/** + * Encodes a message of this type preceeded by its length as a varint. + * @param {T|Object.} message Message to encode + * @param {Writer} [writer] Writer to use + * @returns {Writer} Writer + * @template T extends Message + * @this Constructor + */ +Message.encodeDelimited = function encodeDelimited(message, writer) { + return this.$type.encodeDelimited(message, writer); +}; + +/** + * Decodes a message of this type. + * @name Message.decode + * @function + * @param {Reader|Uint8Array} reader Reader or buffer to decode + * @returns {T} Decoded message + * @template T extends Message + * @this Constructor + */ +Message.decode = function decode(reader) { + return this.$type.decode(reader); +}; + +/** + * Decodes a message of this type preceeded by its length as a varint. + * @name Message.decodeDelimited + * @function + * @param {Reader|Uint8Array} reader Reader or buffer to decode + * @returns {T} Decoded message + * @template T extends Message + * @this Constructor + */ +Message.decodeDelimited = function decodeDelimited(reader) { + return this.$type.decodeDelimited(reader); +}; + +/** + * Verifies a message of this type. + * @name Message.verify + * @function + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ +Message.verify = function verify(message) { + return this.$type.verify(message); +}; + +/** + * Creates a new message of this type from a plain object. Also converts values to their respective internal types. + * @param {Object.} object Plain object + * @returns {T} Message instance + * @template T extends Message + * @this Constructor + */ +Message.fromObject = function fromObject(object) { + return this.$type.fromObject(object); +}; + +/** + * Creates a plain object from a message of this type. Also converts values to other types if specified. + * @param {T} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + * @template T extends Message + * @this Constructor + */ +Message.toObject = function toObject(message, options) { + return this.$type.toObject(message, options); +}; + +/** + * Converts this message to JSON. + * @returns {Object.} JSON object + */ +Message.prototype.toJSON = function toJSON() { + return this.$type.toObject(this, util.toJSONOptions); +}; + +/*eslint-enable valid-jsdoc*/ +},{"35":35}],20:[function(require,module,exports){ +"use strict"; +module.exports = Method; + +// extends ReflectionObject +var ReflectionObject = require(22); +((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method"; + +var util = require(33); + +/** + * Constructs a new service method instance. + * @classdesc Reflected service method. + * @extends ReflectionObject + * @constructor + * @param {string} name Method name + * @param {string|undefined} type Method type, usually `"rpc"` + * @param {string} requestType Request message type + * @param {string} responseType Response message type + * @param {boolean|Object.} [requestStream] Whether the request is streamed + * @param {boolean|Object.} [responseStream] Whether the response is streamed + * @param {Object.} [options] Declared options + * @param {string} [comment] The comment for this method + * @param {Object.} [parsedOptions] Declared options, properly parsed into an object + */ +function Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) { + + /* istanbul ignore next */ + if (util.isObject(requestStream)) { + options = requestStream; + requestStream = responseStream = undefined; + } else if (util.isObject(responseStream)) { + options = responseStream; + responseStream = undefined; + } + + /* istanbul ignore if */ + if (!(type === undefined || util.isString(type))) + throw TypeError("type must be a string"); + + /* istanbul ignore if */ + if (!util.isString(requestType)) + throw TypeError("requestType must be a string"); + + /* istanbul ignore if */ + if (!util.isString(responseType)) + throw TypeError("responseType must be a string"); + + ReflectionObject.call(this, name, options); + + /** + * Method type. + * @type {string} + */ + this.type = type || "rpc"; // toJSON + + /** + * Request type. + * @type {string} + */ + this.requestType = requestType; // toJSON, marker + + /** + * Whether requests are streamed or not. + * @type {boolean|undefined} + */ + this.requestStream = requestStream ? true : undefined; // toJSON + + /** + * Response type. + * @type {string} + */ + this.responseType = responseType; // toJSON + + /** + * Whether responses are streamed or not. + * @type {boolean|undefined} + */ + this.responseStream = responseStream ? true : undefined; // toJSON + + /** + * Resolved request type. + * @type {Type|null} + */ + this.resolvedRequestType = null; + + /** + * Resolved response type. + * @type {Type|null} + */ + this.resolvedResponseType = null; + + /** + * Comment for this method + * @type {string|null} + */ + this.comment = comment; + + /** + * Options properly parsed into an object + */ + this.parsedOptions = parsedOptions; +} + +/** + * Method descriptor. + * @interface IMethod + * @property {string} [type="rpc"] Method type + * @property {string} requestType Request type + * @property {string} responseType Response type + * @property {boolean} [requestStream=false] Whether requests are streamed + * @property {boolean} [responseStream=false] Whether responses are streamed + * @property {Object.} [options] Method options + * @property {string} comment Method comments + * @property {Object.} [parsedOptions] Method options properly parsed into an object + */ + +/** + * Constructs a method from a method descriptor. + * @param {string} name Method name + * @param {IMethod} json Method descriptor + * @returns {Method} Created method + * @throws {TypeError} If arguments are invalid + */ +Method.fromJSON = function fromJSON(name, json) { + return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions); +}; + +/** + * Converts this method to a method descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IMethod} Method descriptor + */ +Method.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "type" , this.type !== "rpc" && /* istanbul ignore next */ this.type || undefined, + "requestType" , this.requestType, + "requestStream" , this.requestStream, + "responseType" , this.responseType, + "responseStream" , this.responseStream, + "options" , this.options, + "comment" , keepComments ? this.comment : undefined, + "parsedOptions" , this.parsedOptions, + ]); +}; + +/** + * @override + */ +Method.prototype.resolve = function resolve() { + + /* istanbul ignore if */ + if (this.resolved) + return this; + + this.resolvedRequestType = this.parent.lookupType(this.requestType); + this.resolvedResponseType = this.parent.lookupType(this.responseType); + + return ReflectionObject.prototype.resolve.call(this); +}; + +},{"22":22,"33":33}],21:[function(require,module,exports){ +"use strict"; +module.exports = Namespace; + +// extends ReflectionObject +var ReflectionObject = require(22); +((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace"; + +var Field = require(15), + util = require(33), + OneOf = require(23); + +var Type, // cyclic + Service, + Enum; + +/** + * Constructs a new namespace instance. + * @name Namespace + * @classdesc Reflected namespace. + * @extends NamespaceBase + * @constructor + * @param {string} name Namespace name + * @param {Object.} [options] Declared options + */ + +/** + * Constructs a namespace from JSON. + * @memberof Namespace + * @function + * @param {string} name Namespace name + * @param {Object.} json JSON object + * @returns {Namespace} Created namespace + * @throws {TypeError} If arguments are invalid + */ +Namespace.fromJSON = function fromJSON(name, json) { + return new Namespace(name, json.options).addJSON(json.nested); +}; + +/** + * Converts an array of reflection objects to JSON. + * @memberof Namespace + * @param {ReflectionObject[]} array Object array + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {Object.|undefined} JSON object or `undefined` when array is empty + */ +function arrayToJSON(array, toJSONOptions) { + if (!(array && array.length)) + return undefined; + var obj = {}; + for (var i = 0; i < array.length; ++i) + obj[array[i].name] = array[i].toJSON(toJSONOptions); + return obj; +} + +Namespace.arrayToJSON = arrayToJSON; + +/** + * Tests if the specified id is reserved. + * @param {Array.|undefined} reserved Array of reserved ranges and names + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Namespace.isReservedId = function isReservedId(reserved, id) { + if (reserved) + for (var i = 0; i < reserved.length; ++i) + if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] > id) + return true; + return false; +}; + +/** + * Tests if the specified name is reserved. + * @param {Array.|undefined} reserved Array of reserved ranges and names + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Namespace.isReservedName = function isReservedName(reserved, name) { + if (reserved) + for (var i = 0; i < reserved.length; ++i) + if (reserved[i] === name) + return true; + return false; +}; + +/** + * Not an actual constructor. Use {@link Namespace} instead. + * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions. + * @exports NamespaceBase + * @extends ReflectionObject + * @abstract + * @constructor + * @param {string} name Namespace name + * @param {Object.} [options] Declared options + * @see {@link Namespace} + */ +function Namespace(name, options) { + ReflectionObject.call(this, name, options); + + /** + * Nested objects by name. + * @type {Object.|undefined} + */ + this.nested = undefined; // toJSON + + /** + * Cached nested objects as an array. + * @type {ReflectionObject[]|null} + * @private + */ + this._nestedArray = null; + + /** + * Cache lookup calls for any objects contains anywhere under this namespace. + * This drastically speeds up resolve for large cross-linked protos where the same + * types are looked up repeatedly. + * @type {Object.} + * @private + */ + this._lookupCache = {}; + + /** + * Whether or not objects contained in this namespace need feature resolution. + * @type {boolean} + * @protected + */ + this._needsRecursiveFeatureResolution = true; + + /** + * Whether or not objects contained in this namespace need a resolve. + * @type {boolean} + * @protected + */ + this._needsRecursiveResolve = true; +} + +function clearCache(namespace) { + namespace._nestedArray = null; + namespace._lookupCache = {}; + + // Also clear parent caches, since they include nested lookups. + var parent = namespace; + while(parent = parent.parent) { + parent._lookupCache = {}; + } + return namespace; +} + +/** + * Nested objects of this namespace as an array for iteration. + * @name NamespaceBase#nestedArray + * @type {ReflectionObject[]} + * @readonly + */ +Object.defineProperty(Namespace.prototype, "nestedArray", { + get: function() { + return this._nestedArray || (this._nestedArray = util.toArray(this.nested)); + } +}); + +/** + * Namespace descriptor. + * @interface INamespace + * @property {Object.} [options] Namespace options + * @property {Object.} [nested] Nested object descriptors + */ + +/** + * Any extension field descriptor. + * @typedef AnyExtensionField + * @type {IExtensionField|IExtensionMapField} + */ + +/** + * Any nested object descriptor. + * @typedef AnyNestedObject + * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf} + */ + +/** + * Converts this namespace to a namespace descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {INamespace} Namespace descriptor + */ +Namespace.prototype.toJSON = function toJSON(toJSONOptions) { + return util.toObject([ + "options" , this.options, + "nested" , arrayToJSON(this.nestedArray, toJSONOptions) + ]); +}; + +/** + * Adds nested objects to this namespace from nested object descriptors. + * @param {Object.} nestedJson Any nested object descriptors + * @returns {Namespace} `this` + */ +Namespace.prototype.addJSON = function addJSON(nestedJson) { + var ns = this; + /* istanbul ignore else */ + if (nestedJson) { + for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) { + nested = nestedJson[names[i]]; + ns.add( // most to least likely + ( nested.fields !== undefined + ? Type.fromJSON + : nested.values !== undefined + ? Enum.fromJSON + : nested.methods !== undefined + ? Service.fromJSON + : nested.id !== undefined + ? Field.fromJSON + : Namespace.fromJSON )(names[i], nested) + ); + } + } + return this; +}; + +/** + * Gets the nested object of the specified name. + * @param {string} name Nested object name + * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist + */ +Namespace.prototype.get = function get(name) { + return this.nested && this.nested[name] + || null; +}; + +/** + * Gets the values of the nested {@link Enum|enum} of the specified name. + * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`. + * @param {string} name Nested enum name + * @returns {Object.} Enum values + * @throws {Error} If there is no such enum + */ +Namespace.prototype.getEnum = function getEnum(name) { + if (this.nested && this.nested[name] instanceof Enum) + return this.nested[name].values; + throw Error("no such enum: " + name); +}; + +/** + * Adds a nested object to this namespace. + * @param {ReflectionObject} object Nested object to add + * @returns {Namespace} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a nested object with this name + */ +Namespace.prototype.add = function add(object) { + + if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace)) + throw TypeError("object must be a valid nested object"); + + if (!this.nested) + this.nested = {}; + else { + var prev = this.get(object.name); + if (prev) { + if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) { + // replace plain namespace but keep existing nested elements and options + var nested = prev.nestedArray; + for (var i = 0; i < nested.length; ++i) + object.add(nested[i]); + this.remove(prev); + if (!this.nested) + this.nested = {}; + object.setOptions(prev.options, true); + + } else + throw Error("duplicate name '" + object.name + "' in " + this); + } + } + this.nested[object.name] = object; + + if (!(this instanceof Type || this instanceof Service || this instanceof Enum || this instanceof Field)) { + // This is a package or a root namespace. + if (!object._edition) { + // Make sure that some edition is set if it hasn't already been specified. + object._edition = object._defaultEdition; + } + } + + this._needsRecursiveFeatureResolution = true; + this._needsRecursiveResolve = true; + + // Also clear parent caches, since they need to recurse down. + var parent = this; + while(parent = parent.parent) { + parent._needsRecursiveFeatureResolution = true; + parent._needsRecursiveResolve = true; + } + + object.onAdd(this); + return clearCache(this); +}; + +/** + * Removes a nested object from this namespace. + * @param {ReflectionObject} object Nested object to remove + * @returns {Namespace} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `object` is not a member of this namespace + */ +Namespace.prototype.remove = function remove(object) { + + if (!(object instanceof ReflectionObject)) + throw TypeError("object must be a ReflectionObject"); + if (object.parent !== this) + throw Error(object + " is not a member of " + this); + + delete this.nested[object.name]; + if (!Object.keys(this.nested).length) + this.nested = undefined; + + object.onRemove(this); + return clearCache(this); +}; + +/** + * Defines additial namespaces within this one if not yet existing. + * @param {string|string[]} path Path to create + * @param {*} [json] Nested types to create from JSON + * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty + */ +Namespace.prototype.define = function define(path, json) { + + if (util.isString(path)) + path = path.split("."); + else if (!Array.isArray(path)) + throw TypeError("illegal path"); + if (path && path.length && path[0] === "") + throw Error("path must be relative"); + + var ptr = this; + while (path.length > 0) { + var part = path.shift(); + if (ptr.nested && ptr.nested[part]) { + ptr = ptr.nested[part]; + if (!(ptr instanceof Namespace)) + throw Error("path conflicts with non-namespace objects"); + } else + ptr.add(ptr = new Namespace(part)); + } + if (json) + ptr.addJSON(json); + return ptr; +}; + +/** + * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost. + * @returns {Namespace} `this` + */ +Namespace.prototype.resolveAll = function resolveAll() { + if (!this._needsRecursiveResolve) return this; + + this._resolveFeaturesRecursive(this._edition); + + var nested = this.nestedArray, i = 0; + this.resolve(); + while (i < nested.length) + if (nested[i] instanceof Namespace) + nested[i++].resolveAll(); + else + nested[i++].resolve(); + this._needsRecursiveResolve = false; + return this; +}; + +/** + * @override + */ +Namespace.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { + if (!this._needsRecursiveFeatureResolution) return this; + this._needsRecursiveFeatureResolution = false; + + edition = this._edition || edition; + + ReflectionObject.prototype._resolveFeaturesRecursive.call(this, edition); + this.nestedArray.forEach(nested => { + nested._resolveFeaturesRecursive(edition); + }); + return this; +}; + +/** + * Recursively looks up the reflection object matching the specified path in the scope of this namespace. + * @param {string|string[]} path Path to look up + * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc. + * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked + * @returns {ReflectionObject|null} Looked up object or `null` if none could be found + */ +Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) { + /* istanbul ignore next */ + if (typeof filterTypes === "boolean") { + parentAlreadyChecked = filterTypes; + filterTypes = undefined; + } else if (filterTypes && !Array.isArray(filterTypes)) + filterTypes = [ filterTypes ]; + + if (util.isString(path) && path.length) { + if (path === ".") + return this.root; + path = path.split("."); + } else if (!path.length) + return this; + + var flatPath = path.join("."); + + // Start at root if path is absolute + if (path[0] === "") + return this.root.lookup(path.slice(1), filterTypes); + + // Early bailout for objects with matching absolute paths + var found = this.root._fullyQualifiedObjects && this.root._fullyQualifiedObjects["." + flatPath]; + if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { + return found; + } + + // Do a regular lookup at this namespace and below + found = this._lookupImpl(path, flatPath); + if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { + return found; + } + + if (parentAlreadyChecked) + return null; + + // If there hasn't been a match, walk up the tree and look more broadly + var current = this; + while (current.parent) { + found = current.parent._lookupImpl(path, flatPath); + if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { + return found; + } + current = current.parent; + } + return null; +}; + +/** + * Internal helper for lookup that handles searching just at this namespace and below along with caching. + * @param {string[]} path Path to look up + * @param {string} flatPath Flattened version of the path to use as a cache key + * @returns {ReflectionObject|null} Looked up object or `null` if none could be found + * @private + */ +Namespace.prototype._lookupImpl = function lookup(path, flatPath) { + if(Object.prototype.hasOwnProperty.call(this._lookupCache, flatPath)) { + return this._lookupCache[flatPath]; + } + + // Test if the first part matches any nested object, and if so, traverse if path contains more + var found = this.get(path[0]); + var exact = null; + if (found) { + if (path.length === 1) { + exact = found; + } else if (found instanceof Namespace) { + path = path.slice(1); + exact = found._lookupImpl(path, path.join(".")); + } + + // Otherwise try each nested namespace + } else { + for (var i = 0; i < this.nestedArray.length; ++i) + if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i]._lookupImpl(path, flatPath))) + exact = found; + } + + // Set this even when null, so that when we walk up the tree we can quickly bail on repeated checks back down. + this._lookupCache[flatPath] = exact; + return exact; +}; + +/** + * Looks up the reflection object at the specified path, relative to this namespace. + * @name NamespaceBase#lookup + * @function + * @param {string|string[]} path Path to look up + * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked + * @returns {ReflectionObject|null} Looked up object or `null` if none could be found + * @variation 2 + */ +// lookup(path: string, [parentAlreadyChecked: boolean]) + +/** + * Looks up the {@link Type|type} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Type} Looked up type + * @throws {Error} If `path` does not point to a type + */ +Namespace.prototype.lookupType = function lookupType(path) { + var found = this.lookup(path, [ Type ]); + if (!found) + throw Error("no such type: " + path); + return found; +}; + +/** + * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Enum} Looked up enum + * @throws {Error} If `path` does not point to an enum + */ +Namespace.prototype.lookupEnum = function lookupEnum(path) { + var found = this.lookup(path, [ Enum ]); + if (!found) + throw Error("no such Enum '" + path + "' in " + this); + return found; +}; + +/** + * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Type} Looked up type or enum + * @throws {Error} If `path` does not point to a type or enum + */ +Namespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) { + var found = this.lookup(path, [ Type, Enum ]); + if (!found) + throw Error("no such Type or Enum '" + path + "' in " + this); + return found; +}; + +/** + * Looks up the {@link Service|service} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Service} Looked up service + * @throws {Error} If `path` does not point to a service + */ +Namespace.prototype.lookupService = function lookupService(path) { + var found = this.lookup(path, [ Service ]); + if (!found) + throw Error("no such Service '" + path + "' in " + this); + return found; +}; + +// Sets up cyclic dependencies (called in index-light) +Namespace._configure = function(Type_, Service_, Enum_) { + Type = Type_; + Service = Service_; + Enum = Enum_; +}; + +},{"15":15,"22":22,"23":23,"33":33}],22:[function(require,module,exports){ +"use strict"; +module.exports = ReflectionObject; + +ReflectionObject.className = "ReflectionObject"; + +const OneOf = require(23); +var util = require(33); + +var Root; // cyclic + +/* eslint-disable no-warning-comments */ +// TODO: Replace with embedded proto. +var editions2023Defaults = {enum_type: "OPEN", field_presence: "EXPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY"}; +var proto2Defaults = {enum_type: "CLOSED", field_presence: "EXPLICIT", json_format: "LEGACY_BEST_EFFORT", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "EXPANDED", utf8_validation: "NONE"}; +var proto3Defaults = {enum_type: "OPEN", field_presence: "IMPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY"}; + +/** + * Constructs a new reflection object instance. + * @classdesc Base class of all reflection objects. + * @constructor + * @param {string} name Object name + * @param {Object.} [options] Declared options + * @abstract + */ +function ReflectionObject(name, options) { + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + if (options && !util.isObject(options)) + throw TypeError("options must be an object"); + + /** + * Options. + * @type {Object.|undefined} + */ + this.options = options; // toJSON + + /** + * Parsed Options. + * @type {Array.>|undefined} + */ + this.parsedOptions = null; + + /** + * Unique name within its namespace. + * @type {string} + */ + this.name = name; + + /** + * The edition specified for this object. Only relevant for top-level objects. + * @type {string} + * @private + */ + this._edition = null; + + /** + * The default edition to use for this object if none is specified. For legacy reasons, + * this is proto2 except in the JSON parsing case where it was proto3. + * @type {string} + * @private + */ + this._defaultEdition = "proto2"; + + /** + * Resolved Features. + * @type {object} + * @private + */ + this._features = {}; + + /** + * Whether or not features have been resolved. + * @type {boolean} + * @private + */ + this._featuresResolved = false; + + /** + * Parent namespace. + * @type {Namespace|null} + */ + this.parent = null; + + /** + * Whether already resolved or not. + * @type {boolean} + */ + this.resolved = false; + + /** + * Comment text, if any. + * @type {string|null} + */ + this.comment = null; + + /** + * Defining file name. + * @type {string|null} + */ + this.filename = null; +} + +Object.defineProperties(ReflectionObject.prototype, { + + /** + * Reference to the root namespace. + * @name ReflectionObject#root + * @type {Root} + * @readonly + */ + root: { + get: function() { + var ptr = this; + while (ptr.parent !== null) + ptr = ptr.parent; + return ptr; + } + }, + + /** + * Full name including leading dot. + * @name ReflectionObject#fullName + * @type {string} + * @readonly + */ + fullName: { + get: function() { + var path = [ this.name ], + ptr = this.parent; + while (ptr) { + path.unshift(ptr.name); + ptr = ptr.parent; + } + return path.join("."); + } + } +}); + +/** + * Converts this reflection object to its descriptor representation. + * @returns {Object.} Descriptor + * @abstract + */ +ReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() { + throw Error(); // not implemented, shouldn't happen +}; + +/** + * Called when this object is added to a parent. + * @param {ReflectionObject} parent Parent added to + * @returns {undefined} + */ +ReflectionObject.prototype.onAdd = function onAdd(parent) { + if (this.parent && this.parent !== parent) + this.parent.remove(this); + this.parent = parent; + this.resolved = false; + var root = parent.root; + if (root instanceof Root) + root._handleAdd(this); +}; + +/** + * Called when this object is removed from a parent. + * @param {ReflectionObject} parent Parent removed from + * @returns {undefined} + */ +ReflectionObject.prototype.onRemove = function onRemove(parent) { + var root = parent.root; + if (root instanceof Root) + root._handleRemove(this); + this.parent = null; + this.resolved = false; +}; + +/** + * Resolves this objects type references. + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.resolve = function resolve() { + if (this.resolved) + return this; + if (this.root instanceof Root) + this.resolved = true; // only if part of a root + return this; +}; + +/** + * Resolves this objects editions features. + * @param {string} edition The edition we're currently resolving for. + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { + return this._resolveFeatures(this._edition || edition); +}; + +/** + * Resolves child features from parent features + * @param {string} edition The edition we're currently resolving for. + * @returns {undefined} + */ +ReflectionObject.prototype._resolveFeatures = function _resolveFeatures(edition) { + if (this._featuresResolved) { + return; + } + + var defaults = {}; + + /* istanbul ignore if */ + if (!edition) { + throw new Error("Unknown edition for " + this.fullName); + } + + var protoFeatures = Object.assign(this.options ? Object.assign({}, this.options.features) : {}, + this._inferLegacyProtoFeatures(edition)); + + if (this._edition) { + // For a namespace marked with a specific edition, reset defaults. + /* istanbul ignore else */ + if (edition === "proto2") { + defaults = Object.assign({}, proto2Defaults); + } else if (edition === "proto3") { + defaults = Object.assign({}, proto3Defaults); + } else if (edition === "2023") { + defaults = Object.assign({}, editions2023Defaults); + } else { + throw new Error("Unknown edition: " + edition); + } + this._features = Object.assign(defaults, protoFeatures || {}); + this._featuresResolved = true; + return; + } + + // fields in Oneofs aren't actually children of them, so we have to + // special-case it + /* istanbul ignore else */ + if (this.partOf instanceof OneOf) { + var lexicalParentFeaturesCopy = Object.assign({}, this.partOf._features); + this._features = Object.assign(lexicalParentFeaturesCopy, protoFeatures || {}); + } else if (this.declaringField) { + // Skip feature resolution of sister fields. + } else if (this.parent) { + var parentFeaturesCopy = Object.assign({}, this.parent._features); + this._features = Object.assign(parentFeaturesCopy, protoFeatures || {}); + } else { + throw new Error("Unable to find a parent for " + this.fullName); + } + if (this.extensionField) { + // Sister fields should have the same features as their extensions. + this.extensionField._features = this._features; + } + this._featuresResolved = true; +}; + +/** + * Infers features from legacy syntax that may have been specified differently. + * in older editions. + * @param {string|undefined} edition The edition this proto is on, or undefined if pre-editions + * @returns {object} The feature values to override + */ +ReflectionObject.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(/*edition*/) { + return {}; +}; + +/** + * Gets an option value. + * @param {string} name Option name + * @returns {*} Option value or `undefined` if not set + */ +ReflectionObject.prototype.getOption = function getOption(name) { + if (this.options) + return this.options[name]; + return undefined; +}; + +/** + * Sets an option. + * @param {string} name Option name + * @param {*} value Option value + * @param {boolean|undefined} [ifNotSet] Sets the option only if it isn't currently set + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) { + if (!this.options) + this.options = {}; + if (/^features\./.test(name)) { + util.setProperty(this.options, name, value, ifNotSet); + } else if (!ifNotSet || this.options[name] === undefined) { + if (this.getOption(name) !== value) this.resolved = false; + this.options[name] = value; + } + + return this; +}; + +/** + * Sets a parsed option. + * @param {string} name parsed Option name + * @param {*} value Option value + * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\empty, will add a new option with that value + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) { + if (!this.parsedOptions) { + this.parsedOptions = []; + } + var parsedOptions = this.parsedOptions; + if (propName) { + // If setting a sub property of an option then try to merge it + // with an existing option + var opt = parsedOptions.find(function (opt) { + return Object.prototype.hasOwnProperty.call(opt, name); + }); + if (opt) { + // If we found an existing option - just merge the property value + // (If it's a feature, will just write over) + var newValue = opt[name]; + util.setProperty(newValue, propName, value); + } else { + // otherwise, create a new option, set its property and add it to the list + opt = {}; + opt[name] = util.setProperty({}, propName, value); + parsedOptions.push(opt); + } + } else { + // Always create a new option when setting the value of the option itself + var newOpt = {}; + newOpt[name] = value; + parsedOptions.push(newOpt); + } + + return this; +}; + +/** + * Sets multiple options. + * @param {Object.} options Options to set + * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) { + if (options) + for (var keys = Object.keys(options), i = 0; i < keys.length; ++i) + this.setOption(keys[i], options[keys[i]], ifNotSet); + return this; +}; + +/** + * Converts this instance to its string representation. + * @returns {string} Class name[, space, full name] + */ +ReflectionObject.prototype.toString = function toString() { + var className = this.constructor.className, + fullName = this.fullName; + if (fullName.length) + return className + " " + fullName; + return className; +}; + +/** + * Converts the edition this object is pinned to for JSON format. + * @returns {string|undefined} The edition string for JSON representation + */ +ReflectionObject.prototype._editionToJSON = function _editionToJSON() { + if (!this._edition || this._edition === "proto3") { + // Avoid emitting proto3 since we need to default to it for backwards + // compatibility anyway. + return undefined; + } + return this._edition; +}; + +// Sets up cyclic dependencies (called in index-light) +ReflectionObject._configure = function(Root_) { + Root = Root_; +}; + +},{"23":23,"33":33}],23:[function(require,module,exports){ +"use strict"; +module.exports = OneOf; + +// extends ReflectionObject +var ReflectionObject = require(22); +((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf"; + +var Field = require(15), + util = require(33); + +/** + * Constructs a new oneof instance. + * @classdesc Reflected oneof. + * @extends ReflectionObject + * @constructor + * @param {string} name Oneof name + * @param {string[]|Object.} [fieldNames] Field names + * @param {Object.} [options] Declared options + * @param {string} [comment] Comment associated with this field + */ +function OneOf(name, fieldNames, options, comment) { + if (!Array.isArray(fieldNames)) { + options = fieldNames; + fieldNames = undefined; + } + ReflectionObject.call(this, name, options); + + /* istanbul ignore if */ + if (!(fieldNames === undefined || Array.isArray(fieldNames))) + throw TypeError("fieldNames must be an Array"); + + /** + * Field names that belong to this oneof. + * @type {string[]} + */ + this.oneof = fieldNames || []; // toJSON, marker + + /** + * Fields that belong to this oneof as an array for iteration. + * @type {Field[]} + * @readonly + */ + this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent + + /** + * Comment for this field. + * @type {string|null} + */ + this.comment = comment; +} + +/** + * Oneof descriptor. + * @interface IOneOf + * @property {Array.} oneof Oneof field names + * @property {Object.} [options] Oneof options + */ + +/** + * Constructs a oneof from a oneof descriptor. + * @param {string} name Oneof name + * @param {IOneOf} json Oneof descriptor + * @returns {OneOf} Created oneof + * @throws {TypeError} If arguments are invalid + */ +OneOf.fromJSON = function fromJSON(name, json) { + return new OneOf(name, json.oneof, json.options, json.comment); +}; + +/** + * Converts this oneof to a oneof descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IOneOf} Oneof descriptor + */ +OneOf.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "options" , this.options, + "oneof" , this.oneof, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * Adds the fields of the specified oneof to the parent if not already done so. + * @param {OneOf} oneof The oneof + * @returns {undefined} + * @inner + * @ignore + */ +function addFieldsToParent(oneof) { + if (oneof.parent) + for (var i = 0; i < oneof.fieldsArray.length; ++i) + if (!oneof.fieldsArray[i].parent) + oneof.parent.add(oneof.fieldsArray[i]); +} + +/** + * Adds a field to this oneof and removes it from its current parent, if any. + * @param {Field} field Field to add + * @returns {OneOf} `this` + */ +OneOf.prototype.add = function add(field) { + + /* istanbul ignore if */ + if (!(field instanceof Field)) + throw TypeError("field must be a Field"); + + if (field.parent && field.parent !== this.parent) + field.parent.remove(field); + this.oneof.push(field.name); + this.fieldsArray.push(field); + field.partOf = this; // field.parent remains null + addFieldsToParent(this); + return this; +}; + +/** + * Removes a field from this oneof and puts it back to the oneof's parent. + * @param {Field} field Field to remove + * @returns {OneOf} `this` + */ +OneOf.prototype.remove = function remove(field) { + + /* istanbul ignore if */ + if (!(field instanceof Field)) + throw TypeError("field must be a Field"); + + var index = this.fieldsArray.indexOf(field); + + /* istanbul ignore if */ + if (index < 0) + throw Error(field + " is not a member of " + this); + + this.fieldsArray.splice(index, 1); + index = this.oneof.indexOf(field.name); + + /* istanbul ignore else */ + if (index > -1) // theoretical + this.oneof.splice(index, 1); + + field.partOf = null; + return this; +}; + +/** + * @override + */ +OneOf.prototype.onAdd = function onAdd(parent) { + ReflectionObject.prototype.onAdd.call(this, parent); + var self = this; + // Collect present fields + for (var i = 0; i < this.oneof.length; ++i) { + var field = parent.get(this.oneof[i]); + if (field && !field.partOf) { + field.partOf = self; + self.fieldsArray.push(field); + } + } + // Add not yet present fields + addFieldsToParent(this); +}; + +/** + * @override + */ +OneOf.prototype.onRemove = function onRemove(parent) { + for (var i = 0, field; i < this.fieldsArray.length; ++i) + if ((field = this.fieldsArray[i]).parent) + field.parent.remove(field); + ReflectionObject.prototype.onRemove.call(this, parent); +}; + +/** + * Determines whether this field corresponds to a synthetic oneof created for + * a proto3 optional field. No behavioral logic should depend on this, but it + * can be relevant for reflection. + * @name OneOf#isProto3Optional + * @type {boolean} + * @readonly + */ +Object.defineProperty(OneOf.prototype, "isProto3Optional", { + get: function() { + if (this.fieldsArray == null || this.fieldsArray.length !== 1) { + return false; + } + + var field = this.fieldsArray[0]; + return field.options != null && field.options["proto3_optional"] === true; + } +}); + +/** + * Decorator function as returned by {@link OneOf.d} (TypeScript). + * @typedef OneOfDecorator + * @type {function} + * @param {Object} prototype Target prototype + * @param {string} oneofName OneOf name + * @returns {undefined} + */ + +/** + * OneOf decorator (TypeScript). + * @function + * @param {...string} fieldNames Field names + * @returns {OneOfDecorator} Decorator function + * @template T extends string + */ +OneOf.d = function decorateOneOf() { + var fieldNames = new Array(arguments.length), + index = 0; + while (index < arguments.length) + fieldNames[index] = arguments[index++]; + return function oneOfDecorator(prototype, oneofName) { + util.decorateType(prototype.constructor) + .add(new OneOf(oneofName, fieldNames)); + Object.defineProperty(prototype, oneofName, { + get: util.oneOfGetter(fieldNames), + set: util.oneOfSetter(fieldNames) + }); + }; +}; + +},{"15":15,"22":22,"33":33}],24:[function(require,module,exports){ +"use strict"; +module.exports = Reader; + +var util = require(35); + +var BufferReader; // cyclic + +var LongBits = util.LongBits, + utf8 = util.utf8; + +/* istanbul ignore next */ +function indexOutOfRange(reader, writeLength) { + return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); +} + +/** + * Constructs a new reader instance using the specified buffer. + * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`. + * @constructor + * @param {Uint8Array} buffer Buffer to read from + */ +function Reader(buffer) { + + /** + * Read buffer. + * @type {Uint8Array} + */ + this.buf = buffer; + + /** + * Read buffer position. + * @type {number} + */ + this.pos = 0; + + /** + * Read buffer length. + * @type {number} + */ + this.len = buffer.length; +} + +var create_array = typeof Uint8Array !== "undefined" + ? function create_typed_array(buffer) { + if (buffer instanceof Uint8Array || Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + } + /* istanbul ignore next */ + : function create_array(buffer) { + if (Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + }; + +var create = function create() { + return util.Buffer + ? function create_buffer_setup(buffer) { + return (Reader.create = function create_buffer(buffer) { + return util.Buffer.isBuffer(buffer) + ? new BufferReader(buffer) + /* istanbul ignore next */ + : create_array(buffer); + })(buffer); + } + /* istanbul ignore next */ + : create_array; +}; + +/** + * Creates a new reader using the specified buffer. + * @function + * @param {Uint8Array|Buffer} buffer Buffer to read from + * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader} + * @throws {Error} If `buffer` is not a valid buffer + */ +Reader.create = create(); + +Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice; + +/** + * Reads a varint as an unsigned 32 bit value. + * @function + * @returns {number} Value read + */ +Reader.prototype.uint32 = (function read_uint32_setup() { + var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!) + return function read_uint32() { + value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value; + + /* istanbul ignore if */ + if ((this.pos += 5) > this.len) { + this.pos = this.len; + throw indexOutOfRange(this, 10); + } + return value; + }; +})(); + +/** + * Reads a varint as a signed 32 bit value. + * @returns {number} Value read + */ +Reader.prototype.int32 = function read_int32() { + return this.uint32() | 0; +}; + +/** + * Reads a zig-zag encoded varint as a signed 32 bit value. + * @returns {number} Value read + */ +Reader.prototype.sint32 = function read_sint32() { + var value = this.uint32(); + return value >>> 1 ^ -(value & 1) | 0; +}; + +/* eslint-disable no-invalid-this */ + +function readLongVarint() { + // tends to deopt with local vars for octet etc. + var bits = new LongBits(0, 0); + var i = 0; + if (this.len - this.pos > 4) { // fast route (lo) + for (; i < 4; ++i) { + // 1st..4th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + // 5th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; + bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + i = 0; + } else { + for (; i < 3; ++i) { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + // 1st..3th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + // 4th + bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0; + return bits; + } + if (this.len - this.pos > 4) { // fast route (hi) + for (; i < 5; ++i) { + // 6th..10th + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } else { + for (; i < 5; ++i) { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + // 6th..10th + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } + /* istanbul ignore next */ + throw Error("invalid varint encoding"); +} + +/* eslint-enable no-invalid-this */ + +/** + * Reads a varint as a signed 64 bit value. + * @name Reader#int64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a varint as an unsigned 64 bit value. + * @name Reader#uint64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a zig-zag encoded varint as a signed 64 bit value. + * @name Reader#sint64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a varint as a boolean. + * @returns {boolean} Value read + */ +Reader.prototype.bool = function read_bool() { + return this.uint32() !== 0; +}; + +function readFixed32_end(buf, end) { // note that this uses `end`, not `pos` + return (buf[end - 4] + | buf[end - 3] << 8 + | buf[end - 2] << 16 + | buf[end - 1] << 24) >>> 0; +} + +/** + * Reads fixed 32 bits as an unsigned 32 bit integer. + * @returns {number} Value read + */ +Reader.prototype.fixed32 = function read_fixed32() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + return readFixed32_end(this.buf, this.pos += 4); +}; + +/** + * Reads fixed 32 bits as a signed 32 bit integer. + * @returns {number} Value read + */ +Reader.prototype.sfixed32 = function read_sfixed32() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + return readFixed32_end(this.buf, this.pos += 4) | 0; +}; + +/* eslint-disable no-invalid-this */ + +function readFixed64(/* this: Reader */) { + + /* istanbul ignore if */ + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 8); + + return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); +} + +/* eslint-enable no-invalid-this */ + +/** + * Reads fixed 64 bits. + * @name Reader#fixed64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads zig-zag encoded fixed 64 bits. + * @name Reader#sfixed64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a float (32 bit) as a number. + * @function + * @returns {number} Value read + */ +Reader.prototype.float = function read_float() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + var value = util.float.readFloatLE(this.buf, this.pos); + this.pos += 4; + return value; +}; + +/** + * Reads a double (64 bit float) as a number. + * @function + * @returns {number} Value read + */ +Reader.prototype.double = function read_double() { + + /* istanbul ignore if */ + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 4); + + var value = util.float.readDoubleLE(this.buf, this.pos); + this.pos += 8; + return value; +}; + +/** + * Reads a sequence of bytes preceeded by its length as a varint. + * @returns {Uint8Array} Value read + */ +Reader.prototype.bytes = function read_bytes() { + var length = this.uint32(), + start = this.pos, + end = this.pos + length; + + /* istanbul ignore if */ + if (end > this.len) + throw indexOutOfRange(this, length); + + this.pos += length; + if (Array.isArray(this.buf)) // plain array + return this.buf.slice(start, end); + + if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1 + var nativeBuffer = util.Buffer; + return nativeBuffer + ? nativeBuffer.alloc(0) + : new this.buf.constructor(0); + } + return this._slice.call(this.buf, start, end); +}; + +/** + * Reads a string preceeded by its byte length as a varint. + * @returns {string} Value read + */ +Reader.prototype.string = function read_string() { + var bytes = this.bytes(); + return utf8.read(bytes, 0, bytes.length); +}; + +/** + * Skips the specified number of bytes if specified, otherwise skips a varint. + * @param {number} [length] Length if known, otherwise a varint is assumed + * @returns {Reader} `this` + */ +Reader.prototype.skip = function skip(length) { + if (typeof length === "number") { + /* istanbul ignore if */ + if (this.pos + length > this.len) + throw indexOutOfRange(this, length); + this.pos += length; + } else { + do { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + } while (this.buf[this.pos++] & 128); + } + return this; +}; + +/** + * Skips the next element of the specified wire type. + * @param {number} wireType Wire type received + * @returns {Reader} `this` + */ +Reader.prototype.skipType = function(wireType) { + switch (wireType) { + case 0: + this.skip(); + break; + case 1: + this.skip(8); + break; + case 2: + this.skip(this.uint32()); + break; + case 3: + while ((wireType = this.uint32() & 7) !== 4) { + this.skipType(wireType); + } + break; + case 5: + this.skip(4); + break; + + /* istanbul ignore next */ + default: + throw Error("invalid wire type " + wireType + " at offset " + this.pos); + } + return this; +}; + +Reader._configure = function(BufferReader_) { + BufferReader = BufferReader_; + Reader.create = create(); + BufferReader._configure(); + + var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber"; + util.merge(Reader.prototype, { + + int64: function read_int64() { + return readLongVarint.call(this)[fn](false); + }, + + uint64: function read_uint64() { + return readLongVarint.call(this)[fn](true); + }, + + sint64: function read_sint64() { + return readLongVarint.call(this).zzDecode()[fn](false); + }, + + fixed64: function read_fixed64() { + return readFixed64.call(this)[fn](true); + }, + + sfixed64: function read_sfixed64() { + return readFixed64.call(this)[fn](false); + } + + }); +}; + +},{"35":35}],25:[function(require,module,exports){ +"use strict"; +module.exports = BufferReader; + +// extends Reader +var Reader = require(24); +(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; + +var util = require(35); + +/** + * Constructs a new buffer reader instance. + * @classdesc Wire format reader using node buffers. + * @extends Reader + * @constructor + * @param {Buffer} buffer Buffer to read from + */ +function BufferReader(buffer) { + Reader.call(this, buffer); + + /** + * Read buffer. + * @name BufferReader#buf + * @type {Buffer} + */ +} + +BufferReader._configure = function () { + /* istanbul ignore else */ + if (util.Buffer) + BufferReader.prototype._slice = util.Buffer.prototype.slice; +}; + + +/** + * @override + */ +BufferReader.prototype.string = function read_string_buffer() { + var len = this.uint32(); // modifies pos + return this.buf.utf8Slice + ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) + : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len)); +}; + +/** + * Reads a sequence of bytes preceeded by its length as a varint. + * @name BufferReader#bytes + * @function + * @returns {Buffer} Value read + */ + +BufferReader._configure(); + +},{"24":24,"35":35}],26:[function(require,module,exports){ +"use strict"; +module.exports = Root; + +// extends Namespace +var Namespace = require(21); +((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root"; + +var Field = require(15), + Enum = require(14), + OneOf = require(23), + util = require(33); + +var Type, // cyclic + parse, // might be excluded + common; // " + +/** + * Constructs a new root namespace instance. + * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together. + * @extends NamespaceBase + * @constructor + * @param {Object.} [options] Top level options + */ +function Root(options) { + Namespace.call(this, "", options); + + /** + * Deferred extension fields. + * @type {Field[]} + */ + this.deferred = []; + + /** + * Resolved file names of loaded files. + * @type {string[]} + */ + this.files = []; + + /** + * Edition, defaults to proto2 if unspecified. + * @type {string} + * @private + */ + this._edition = "proto2"; + + /** + * Global lookup cache of fully qualified names. + * @type {Object.} + * @private + */ + this._fullyQualifiedObjects = {}; +} + +/** + * Loads a namespace descriptor into a root namespace. + * @param {INamespace} json Namespace descriptor + * @param {Root} [root] Root namespace, defaults to create a new one if omitted + * @returns {Root} Root namespace + */ +Root.fromJSON = function fromJSON(json, root) { + if (!root) + root = new Root(); + if (json.options) + root.setOptions(json.options); + return root.addJSON(json.nested).resolveAll(); +}; + +/** + * Resolves the path of an imported file, relative to the importing origin. + * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories. + * @function + * @param {string} origin The file name of the importing file + * @param {string} target The file name being imported + * @returns {string|null} Resolved path to `target` or `null` to skip the file + */ +Root.prototype.resolvePath = util.path.resolve; + +/** + * Fetch content from file path or url + * This method exists so you can override it with your own logic. + * @function + * @param {string} path File path or url + * @param {FetchCallback} callback Callback function + * @returns {undefined} + */ +Root.prototype.fetch = util.fetch; + +// A symbol-like function to safely signal synchronous loading +/* istanbul ignore next */ +function SYNC() {} // eslint-disable-line no-empty-function + +/** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} options Parse options + * @param {LoadCallback} callback Callback function + * @returns {undefined} + */ +Root.prototype.load = function load(filename, options, callback) { + if (typeof options === "function") { + callback = options; + options = undefined; + } + var self = this; + if (!callback) { + return util.asPromise(load, self, filename, options); + } + + var sync = callback === SYNC; // undocumented + + // Finishes loading by calling the callback (exactly once) + function finish(err, root) { + /* istanbul ignore if */ + if (!callback) { + return; + } + if (sync) { + throw err; + } + if (root) { + root.resolveAll(); + } + var cb = callback; + callback = null; + cb(err, root); + } + + // Bundled definition existence checking + function getBundledFileName(filename) { + var idx = filename.lastIndexOf("google/protobuf/"); + if (idx > -1) { + var altname = filename.substring(idx); + if (altname in common) return altname; + } + return null; + } + + // Processes a single file + function process(filename, source) { + try { + if (util.isString(source) && source.charAt(0) === "{") + source = JSON.parse(source); + if (!util.isString(source)) + self.setOptions(source.options).addJSON(source.nested); + else { + parse.filename = filename; + var parsed = parse(source, self, options), + resolved, + i = 0; + if (parsed.imports) + for (; i < parsed.imports.length; ++i) + if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i])) + fetch(resolved); + if (parsed.weakImports) + for (i = 0; i < parsed.weakImports.length; ++i) + if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i])) + fetch(resolved, true); + } + } catch (err) { + finish(err); + } + if (!sync && !queued) { + finish(null, self); // only once anyway + } + } + + // Fetches a single file + function fetch(filename, weak) { + filename = getBundledFileName(filename) || filename; + + // Skip if already loaded / attempted + if (self.files.indexOf(filename) > -1) { + return; + } + self.files.push(filename); + + // Shortcut bundled definitions + if (filename in common) { + if (sync) { + process(filename, common[filename]); + } else { + ++queued; + setTimeout(function() { + --queued; + process(filename, common[filename]); + }); + } + return; + } + + // Otherwise fetch from disk or network + if (sync) { + var source; + try { + source = util.fs.readFileSync(filename).toString("utf8"); + } catch (err) { + if (!weak) + finish(err); + return; + } + process(filename, source); + } else { + ++queued; + self.fetch(filename, function(err, source) { + --queued; + /* istanbul ignore if */ + if (!callback) { + return; // terminated meanwhile + } + if (err) { + /* istanbul ignore else */ + if (!weak) + finish(err); + else if (!queued) // can't be covered reliably + finish(null, self); + return; + } + process(filename, source); + }); + } + } + var queued = 0; + + // Assembling the root namespace doesn't require working type + // references anymore, so we can load everything in parallel + if (util.isString(filename)) { + filename = [ filename ]; + } + for (var i = 0, resolved; i < filename.length; ++i) + if (resolved = self.resolvePath("", filename[i])) + fetch(resolved); + if (sync) { + self.resolveAll(); + return self; + } + if (!queued) { + finish(null, self); + } + + return self; +}; +// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined + +/** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. + * @function Root#load + * @param {string|string[]} filename Names of one or multiple files to load + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @variation 2 + */ +// function load(filename:string, callback:LoadCallback):undefined + +/** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise. + * @function Root#load + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {Promise} Promise + * @variation 3 + */ +// function load(filename:string, [options:IParseOptions]):Promise + +/** + * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only). + * @function Root#loadSync + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {Root} Root namespace + * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid + */ +Root.prototype.loadSync = function loadSync(filename, options) { + if (!util.isNode) + throw Error("not supported"); + return this.load(filename, options, SYNC); +}; + +/** + * @override + */ +Root.prototype.resolveAll = function resolveAll() { + if (!this._needsRecursiveResolve) return this; + + if (this.deferred.length) + throw Error("unresolvable extensions: " + this.deferred.map(function(field) { + return "'extend " + field.extend + "' in " + field.parent.fullName; + }).join(", ")); + return Namespace.prototype.resolveAll.call(this); +}; + +// only uppercased (and thus conflict-free) children are exposed, see below +var exposeRe = /^[A-Z]/; + +/** + * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type. + * @param {Root} root Root instance + * @param {Field} field Declaring extension field witin the declaring type + * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise + * @inner + * @ignore + */ +function tryHandleExtension(root, field) { + var extendedType = field.parent.lookup(field.extend); + if (extendedType) { + var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options); + //do not allow to extend same field twice to prevent the error + if (extendedType.get(sisterField.name)) { + return true; + } + sisterField.declaringField = field; + field.extensionField = sisterField; + extendedType.add(sisterField); + return true; + } + return false; +} + +/** + * Called when any object is added to this root or its sub-namespaces. + * @param {ReflectionObject} object Object added + * @returns {undefined} + * @private + */ +Root.prototype._handleAdd = function _handleAdd(object) { + if (object instanceof Field) { + + if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField) + if (!tryHandleExtension(this, object)) + this.deferred.push(object); + + } else if (object instanceof Enum) { + + if (exposeRe.test(object.name)) + object.parent[object.name] = object.values; // expose enum values as property of its parent + + } else if (!(object instanceof OneOf)) /* everything else is a namespace */ { + + if (object instanceof Type) // Try to handle any deferred extensions + for (var i = 0; i < this.deferred.length;) + if (tryHandleExtension(this, this.deferred[i])) + this.deferred.splice(i, 1); + else + ++i; + for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace + this._handleAdd(object._nestedArray[j]); + if (exposeRe.test(object.name)) + object.parent[object.name] = object; // expose namespace as property of its parent + } + + if (object instanceof Type || object instanceof Enum || object instanceof Field) { + // Only store types and enums for quick lookup during resolve. + this._fullyQualifiedObjects[object.fullName] = object; + } + + // The above also adds uppercased (and thus conflict-free) nested types, services and enums as + // properties of namespaces just like static code does. This allows using a .d.ts generated for + // a static module with reflection-based solutions where the condition is met. +}; + +/** + * Called when any object is removed from this root or its sub-namespaces. + * @param {ReflectionObject} object Object removed + * @returns {undefined} + * @private + */ +Root.prototype._handleRemove = function _handleRemove(object) { + if (object instanceof Field) { + + if (/* an extension field */ object.extend !== undefined) { + if (/* already handled */ object.extensionField) { // remove its sister field + object.extensionField.parent.remove(object.extensionField); + object.extensionField = null; + } else { // cancel the extension + var index = this.deferred.indexOf(object); + /* istanbul ignore else */ + if (index > -1) + this.deferred.splice(index, 1); + } + } + + } else if (object instanceof Enum) { + + if (exposeRe.test(object.name)) + delete object.parent[object.name]; // unexpose enum values + + } else if (object instanceof Namespace) { + + for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace + this._handleRemove(object._nestedArray[i]); + + if (exposeRe.test(object.name)) + delete object.parent[object.name]; // unexpose namespaces + + } + + delete this._fullyQualifiedObjects[object.fullName]; +}; + +// Sets up cyclic dependencies (called in index-light) +Root._configure = function(Type_, parse_, common_) { + Type = Type_; + parse = parse_; + common = common_; +}; + +},{"14":14,"15":15,"21":21,"23":23,"33":33}],27:[function(require,module,exports){ +"use strict"; +module.exports = {}; + +/** + * Named roots. + * This is where pbjs stores generated structures (the option `-r, --root` specifies a name). + * Can also be used manually to make roots available across modules. + * @name roots + * @type {Object.} + * @example + * // pbjs -r myroot -o compiled.js ... + * + * // in another module: + * require("./compiled.js"); + * + * // in any subsequent module: + * var root = protobuf.roots["myroot"]; + */ + +},{}],28:[function(require,module,exports){ +"use strict"; + +/** + * Streaming RPC helpers. + * @namespace + */ +var rpc = exports; + +/** + * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets. + * @typedef RPCImpl + * @type {function} + * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called + * @param {Uint8Array} requestData Request data + * @param {RPCImplCallback} callback Callback function + * @returns {undefined} + * @example + * function rpcImpl(method, requestData, callback) { + * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code + * throw Error("no such method"); + * asynchronouslyObtainAResponse(requestData, function(err, responseData) { + * callback(err, responseData); + * }); + * } + */ + +/** + * Node-style callback as used by {@link RPCImpl}. + * @typedef RPCImplCallback + * @type {function} + * @param {Error|null} error Error, if any, otherwise `null` + * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error + * @returns {undefined} + */ + +rpc.Service = require(29); + +},{"29":29}],29:[function(require,module,exports){ +"use strict"; +module.exports = Service; + +var util = require(35); + +// Extends EventEmitter +(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; + +/** + * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}. + * + * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`. + * @typedef rpc.ServiceMethodCallback + * @template TRes extends Message + * @type {function} + * @param {Error|null} error Error, if any + * @param {TRes} [response] Response message + * @returns {undefined} + */ + +/** + * A service method part of a {@link rpc.Service} as created by {@link Service.create}. + * @typedef rpc.ServiceMethod + * @template TReq extends Message + * @template TRes extends Message + * @type {function} + * @param {TReq|Properties} request Request message or plain object + * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message + * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined` + */ + +/** + * Constructs a new RPC service instance. + * @classdesc An RPC service as returned by {@link Service#create}. + * @exports rpc.Service + * @extends util.EventEmitter + * @constructor + * @param {RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ +function Service(rpcImpl, requestDelimited, responseDelimited) { + + if (typeof rpcImpl !== "function") + throw TypeError("rpcImpl must be a function"); + + util.EventEmitter.call(this); + + /** + * RPC implementation. Becomes `null` once the service is ended. + * @type {RPCImpl|null} + */ + this.rpcImpl = rpcImpl; + + /** + * Whether requests are length-delimited. + * @type {boolean} + */ + this.requestDelimited = Boolean(requestDelimited); + + /** + * Whether responses are length-delimited. + * @type {boolean} + */ + this.responseDelimited = Boolean(responseDelimited); +} + +/** + * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}. + * @param {Method|rpc.ServiceMethod} method Reflected or static method + * @param {Constructor} requestCtor Request constructor + * @param {Constructor} responseCtor Response constructor + * @param {TReq|Properties} request Request message or plain object + * @param {rpc.ServiceMethodCallback} callback Service callback + * @returns {undefined} + * @template TReq extends Message + * @template TRes extends Message + */ +Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) { + + if (!request) + throw TypeError("request must be specified"); + + var self = this; + if (!callback) + return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request); + + if (!self.rpcImpl) { + setTimeout(function() { callback(Error("already ended")); }, 0); + return undefined; + } + + try { + return self.rpcImpl( + method, + requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(), + function rpcCallback(err, response) { + + if (err) { + self.emit("error", err, method); + return callback(err); + } + + if (response === null) { + self.end(/* endedByRPC */ true); + return undefined; + } + + if (!(response instanceof responseCtor)) { + try { + response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response); + } catch (err) { + self.emit("error", err, method); + return callback(err); + } + } + + self.emit("data", response, method); + return callback(null, response); + } + ); + } catch (err) { + self.emit("error", err, method); + setTimeout(function() { callback(err); }, 0); + return undefined; + } +}; + +/** + * Ends this service and emits the `end` event. + * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation. + * @returns {rpc.Service} `this` + */ +Service.prototype.end = function end(endedByRPC) { + if (this.rpcImpl) { + if (!endedByRPC) // signal end to rpcImpl + this.rpcImpl(null, null, null); + this.rpcImpl = null; + this.emit("end").off(); + } + return this; +}; + +},{"35":35}],30:[function(require,module,exports){ +"use strict"; +module.exports = Service; + +// extends Namespace +var Namespace = require(21); +((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service"; + +var Method = require(20), + util = require(33), + rpc = require(28); + +/** + * Constructs a new service instance. + * @classdesc Reflected service. + * @extends NamespaceBase + * @constructor + * @param {string} name Service name + * @param {Object.} [options] Service options + * @throws {TypeError} If arguments are invalid + */ +function Service(name, options) { + Namespace.call(this, name, options); + + /** + * Service methods. + * @type {Object.} + */ + this.methods = {}; // toJSON, marker + + /** + * Cached methods as an array. + * @type {Method[]|null} + * @private + */ + this._methodsArray = null; +} + +/** + * Service descriptor. + * @interface IService + * @extends INamespace + * @property {Object.} methods Method descriptors + */ + +/** + * Constructs a service from a service descriptor. + * @param {string} name Service name + * @param {IService} json Service descriptor + * @returns {Service} Created service + * @throws {TypeError} If arguments are invalid + */ +Service.fromJSON = function fromJSON(name, json) { + var service = new Service(name, json.options); + /* istanbul ignore else */ + if (json.methods) + for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i) + service.add(Method.fromJSON(names[i], json.methods[names[i]])); + if (json.nested) + service.addJSON(json.nested); + if (json.edition) + service._edition = json.edition; + service.comment = json.comment; + service._defaultEdition = "proto3"; // For backwards-compatibility. + return service; +}; + +/** + * Converts this service to a service descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IService} Service descriptor + */ +Service.prototype.toJSON = function toJSON(toJSONOptions) { + var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "edition" , this._editionToJSON(), + "options" , inherited && inherited.options || undefined, + "methods" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {}, + "nested" , inherited && inherited.nested || undefined, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * Methods of this service as an array for iteration. + * @name Service#methodsArray + * @type {Method[]} + * @readonly + */ +Object.defineProperty(Service.prototype, "methodsArray", { + get: function() { + return this._methodsArray || (this._methodsArray = util.toArray(this.methods)); + } +}); + +function clearCache(service) { + service._methodsArray = null; + return service; +} + +/** + * @override + */ +Service.prototype.get = function get(name) { + return this.methods[name] + || Namespace.prototype.get.call(this, name); +}; + +/** + * @override + */ +Service.prototype.resolveAll = function resolveAll() { + if (!this._needsRecursiveResolve) return this; + + Namespace.prototype.resolve.call(this); + var methods = this.methodsArray; + for (var i = 0; i < methods.length; ++i) + methods[i].resolve(); + return this; +}; + +/** + * @override + */ +Service.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { + if (!this._needsRecursiveFeatureResolution) return this; + + edition = this._edition || edition; + + Namespace.prototype._resolveFeaturesRecursive.call(this, edition); + this.methodsArray.forEach(method => { + method._resolveFeaturesRecursive(edition); + }); + return this; +}; + +/** + * @override + */ +Service.prototype.add = function add(object) { + + /* istanbul ignore if */ + if (this.get(object.name)) + throw Error("duplicate name '" + object.name + "' in " + this); + + if (object instanceof Method) { + this.methods[object.name] = object; + object.parent = this; + return clearCache(this); + } + return Namespace.prototype.add.call(this, object); +}; + +/** + * @override + */ +Service.prototype.remove = function remove(object) { + if (object instanceof Method) { + + /* istanbul ignore if */ + if (this.methods[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.methods[object.name]; + object.parent = null; + return clearCache(this); + } + return Namespace.prototype.remove.call(this, object); +}; + +/** + * Creates a runtime service using the specified rpc implementation. + * @param {RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed. + */ +Service.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) { + var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited); + for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) { + var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, ""); + rpcService[methodName] = util.codegen(["r","c"], util.isReserved(methodName) ? methodName + "_" : methodName)("return this.rpcCall(m,q,s,r,c)")({ + m: method, + q: method.resolvedRequestType.ctor, + s: method.resolvedResponseType.ctor + }); + } + return rpcService; +}; + +},{"20":20,"21":21,"28":28,"33":33}],31:[function(require,module,exports){ +"use strict"; +module.exports = Type; + +// extends Namespace +var Namespace = require(21); +((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type"; + +var Enum = require(14), + OneOf = require(23), + Field = require(15), + MapField = require(18), + Service = require(30), + Message = require(19), + Reader = require(24), + Writer = require(38), + util = require(33), + encoder = require(13), + decoder = require(12), + verifier = require(36), + converter = require(11), + wrappers = require(37); + +/** + * Constructs a new reflected message type instance. + * @classdesc Reflected message type. + * @extends NamespaceBase + * @constructor + * @param {string} name Message name + * @param {Object.} [options] Declared options + */ +function Type(name, options) { + Namespace.call(this, name, options); + + /** + * Message fields. + * @type {Object.} + */ + this.fields = {}; // toJSON, marker + + /** + * Oneofs declared within this namespace, if any. + * @type {Object.} + */ + this.oneofs = undefined; // toJSON + + /** + * Extension ranges, if any. + * @type {number[][]} + */ + this.extensions = undefined; // toJSON + + /** + * Reserved ranges, if any. + * @type {Array.} + */ + this.reserved = undefined; // toJSON + + /*? + * Whether this type is a legacy group. + * @type {boolean|undefined} + */ + this.group = undefined; // toJSON + + /** + * Cached fields by id. + * @type {Object.|null} + * @private + */ + this._fieldsById = null; + + /** + * Cached fields as an array. + * @type {Field[]|null} + * @private + */ + this._fieldsArray = null; + + /** + * Cached oneofs as an array. + * @type {OneOf[]|null} + * @private + */ + this._oneofsArray = null; + + /** + * Cached constructor. + * @type {Constructor<{}>} + * @private + */ + this._ctor = null; +} + +Object.defineProperties(Type.prototype, { + + /** + * Message fields by id. + * @name Type#fieldsById + * @type {Object.} + * @readonly + */ + fieldsById: { + get: function() { + + /* istanbul ignore if */ + if (this._fieldsById) + return this._fieldsById; + + this._fieldsById = {}; + for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) { + var field = this.fields[names[i]], + id = field.id; + + /* istanbul ignore if */ + if (this._fieldsById[id]) + throw Error("duplicate id " + id + " in " + this); + + this._fieldsById[id] = field; + } + return this._fieldsById; + } + }, + + /** + * Fields of this message as an array for iteration. + * @name Type#fieldsArray + * @type {Field[]} + * @readonly + */ + fieldsArray: { + get: function() { + return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields)); + } + }, + + /** + * Oneofs of this message as an array for iteration. + * @name Type#oneofsArray + * @type {OneOf[]} + * @readonly + */ + oneofsArray: { + get: function() { + return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs)); + } + }, + + /** + * The registered constructor, if any registered, otherwise a generic constructor. + * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor. + * @name Type#ctor + * @type {Constructor<{}>} + */ + ctor: { + get: function() { + return this._ctor || (this.ctor = Type.generateConstructor(this)()); + }, + set: function(ctor) { + + // Ensure proper prototype + var prototype = ctor.prototype; + if (!(prototype instanceof Message)) { + (ctor.prototype = new Message()).constructor = ctor; + util.merge(ctor.prototype, prototype); + } + + // Classes and messages reference their reflected type + ctor.$type = ctor.prototype.$type = this; + + // Mix in static methods + util.merge(ctor, Message, true); + + this._ctor = ctor; + + // Messages have non-enumerable default values on their prototype + var i = 0; + for (; i < /* initializes */ this.fieldsArray.length; ++i) + this._fieldsArray[i].resolve(); // ensures a proper value + + // Messages have non-enumerable getters and setters for each virtual oneof field + var ctorProperties = {}; + for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i) + ctorProperties[this._oneofsArray[i].resolve().name] = { + get: util.oneOfGetter(this._oneofsArray[i].oneof), + set: util.oneOfSetter(this._oneofsArray[i].oneof) + }; + if (i) + Object.defineProperties(ctor.prototype, ctorProperties); + } + } +}); + +/** + * Generates a constructor function for the specified type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +Type.generateConstructor = function generateConstructor(mtype) { + /* eslint-disable no-unexpected-multiline */ + var gen = util.codegen(["p"], mtype.name); + // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype + for (var i = 0, field; i < mtype.fieldsArray.length; ++i) + if ((field = mtype._fieldsArray[i]).map) gen + ("this%s={}", util.safeProp(field.name)); + else if (field.repeated) gen + ("this%s=[]", util.safeProp(field.name)); + return gen + ("if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors + * @property {Object.} fields Field descriptors + * @property {number[][]} [extensions] Extension ranges + * @property {Array.} [reserved] Reserved ranges + * @property {boolean} [group=false] Whether a legacy group or not + */ + +/** + * Creates a message type from a message type descriptor. + * @param {string} name Message name + * @param {IType} json Message type descriptor + * @returns {Type} Created message type + */ +Type.fromJSON = function fromJSON(name, json) { + var type = new Type(name, json.options); + type.extensions = json.extensions; + type.reserved = json.reserved; + var names = Object.keys(json.fields), + i = 0; + for (; i < names.length; ++i) + type.add( + ( typeof json.fields[names[i]].keyType !== "undefined" + ? MapField.fromJSON + : Field.fromJSON )(names[i], json.fields[names[i]]) + ); + if (json.oneofs) + for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i) + type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]])); + if (json.nested) + for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) { + var nested = json.nested[names[i]]; + type.add( // most to least likely + ( nested.id !== undefined + ? Field.fromJSON + : nested.fields !== undefined + ? Type.fromJSON + : nested.values !== undefined + ? Enum.fromJSON + : nested.methods !== undefined + ? Service.fromJSON + : Namespace.fromJSON )(names[i], nested) + ); + } + if (json.extensions && json.extensions.length) + type.extensions = json.extensions; + if (json.reserved && json.reserved.length) + type.reserved = json.reserved; + if (json.group) + type.group = true; + if (json.comment) + type.comment = json.comment; + if (json.edition) + type._edition = json.edition; + type._defaultEdition = "proto3"; // For backwards-compatibility. + return type; +}; + +/** + * Converts this message type to a message type descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IType} Message type descriptor + */ +Type.prototype.toJSON = function toJSON(toJSONOptions) { + var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "edition" , this._editionToJSON(), + "options" , inherited && inherited.options || undefined, + "oneofs" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions), + "fields" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {}, + "extensions" , this.extensions && this.extensions.length ? this.extensions : undefined, + "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined, + "group" , this.group || undefined, + "nested" , inherited && inherited.nested || undefined, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * @override + */ +Type.prototype.resolveAll = function resolveAll() { + if (!this._needsRecursiveResolve) return this; + + Namespace.prototype.resolveAll.call(this); + var oneofs = this.oneofsArray; i = 0; + while (i < oneofs.length) + oneofs[i++].resolve(); + var fields = this.fieldsArray, i = 0; + while (i < fields.length) + fields[i++].resolve(); + return this; +}; + +/** + * @override + */ +Type.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { + if (!this._needsRecursiveFeatureResolution) return this; + + edition = this._edition || edition; + + Namespace.prototype._resolveFeaturesRecursive.call(this, edition); + this.oneofsArray.forEach(oneof => { + oneof._resolveFeatures(edition); + }); + this.fieldsArray.forEach(field => { + field._resolveFeatures(edition); + }); + return this; +}; + +/** + * @override + */ +Type.prototype.get = function get(name) { + return this.fields[name] + || this.oneofs && this.oneofs[name] + || this.nested && this.nested[name] + || null; +}; + +/** + * Adds a nested object to this type. + * @param {ReflectionObject} object Nested object to add + * @returns {Type} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id + */ +Type.prototype.add = function add(object) { + + if (this.get(object.name)) + throw Error("duplicate name '" + object.name + "' in " + this); + + if (object instanceof Field && object.extend === undefined) { + // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects. + // The root object takes care of adding distinct sister-fields to the respective extended + // type instead. + + // avoids calling the getter if not absolutely necessary because it's called quite frequently + if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id]) + throw Error("duplicate id " + object.id + " in " + this); + if (this.isReservedId(object.id)) + throw Error("id " + object.id + " is reserved in " + this); + if (this.isReservedName(object.name)) + throw Error("name '" + object.name + "' is reserved in " + this); + + if (object.parent) + object.parent.remove(object); + this.fields[object.name] = object; + object.message = this; + object.onAdd(this); + return clearCache(this); + } + if (object instanceof OneOf) { + if (!this.oneofs) + this.oneofs = {}; + this.oneofs[object.name] = object; + object.onAdd(this); + return clearCache(this); + } + return Namespace.prototype.add.call(this, object); +}; + +/** + * Removes a nested object from this type. + * @param {ReflectionObject} object Nested object to remove + * @returns {Type} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `object` is not a member of this type + */ +Type.prototype.remove = function remove(object) { + if (object instanceof Field && object.extend === undefined) { + // See Type#add for the reason why extension fields are excluded here. + + /* istanbul ignore if */ + if (!this.fields || this.fields[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.fields[object.name]; + object.parent = null; + object.onRemove(this); + return clearCache(this); + } + if (object instanceof OneOf) { + + /* istanbul ignore if */ + if (!this.oneofs || this.oneofs[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.oneofs[object.name]; + object.parent = null; + object.onRemove(this); + return clearCache(this); + } + return Namespace.prototype.remove.call(this, object); +}; + +/** + * Tests if the specified id is reserved. + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Type.prototype.isReservedId = function isReservedId(id) { + return Namespace.isReservedId(this.reserved, id); +}; + +/** + * Tests if the specified name is reserved. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Type.prototype.isReservedName = function isReservedName(name) { + return Namespace.isReservedName(this.reserved, name); +}; + +/** + * Creates a new message of this type using the specified properties. + * @param {Object.} [properties] Properties to set + * @returns {Message<{}>} Message instance + */ +Type.prototype.create = function create(properties) { + return new this.ctor(properties); +}; + +/** + * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}. + * @returns {Type} `this` + */ +Type.prototype.setup = function setup() { + // Sets up everything at once so that the prototype chain does not have to be re-evaluated + // multiple times (V8, soft-deopt prototype-check). + + var fullName = this.fullName, + types = []; + for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i) + types.push(this._fieldsArray[i].resolve().resolvedType); + + // Replace setup methods with type-specific generated functions + this.encode = encoder(this)({ + Writer : Writer, + types : types, + util : util + }); + this.decode = decoder(this)({ + Reader : Reader, + types : types, + util : util + }); + this.verify = verifier(this)({ + types : types, + util : util + }); + this.fromObject = converter.fromObject(this)({ + types : types, + util : util + }); + this.toObject = converter.toObject(this)({ + types : types, + util : util + }); + + // Inject custom wrappers for common types + var wrapper = wrappers[fullName]; + if (wrapper) { + var originalThis = Object.create(this); + // if (wrapper.fromObject) { + originalThis.fromObject = this.fromObject; + this.fromObject = wrapper.fromObject.bind(originalThis); + // } + // if (wrapper.toObject) { + originalThis.toObject = this.toObject; + this.toObject = wrapper.toObject.bind(originalThis); + // } + } + + return this; +}; + +/** + * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages. + * @param {Message<{}>|Object.} message Message instance or plain object + * @param {Writer} [writer] Writer to encode to + * @returns {Writer} writer + */ +Type.prototype.encode = function encode_setup(message, writer) { + return this.setup().encode(message, writer); // overrides this method +}; + +/** + * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages. + * @param {Message<{}>|Object.} message Message instance or plain object + * @param {Writer} [writer] Writer to encode to + * @returns {Writer} writer + */ +Type.prototype.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim(); +}; + +/** + * Decodes a message of this type. + * @param {Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Length of the message, if known beforehand + * @returns {Message<{}>} Decoded message + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {util.ProtocolError<{}>} If required fields are missing + */ +Type.prototype.decode = function decode_setup(reader, length) { + return this.setup().decode(reader, length); // overrides this method +}; + +/** + * Decodes a message of this type preceeded by its byte length as a varint. + * @param {Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {Message<{}>} Decoded message + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {util.ProtocolError} If required fields are missing + */ +Type.prototype.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof Reader)) + reader = Reader.create(reader); + return this.decode(reader, reader.uint32()); +}; + +/** + * Verifies that field values are valid and that required fields are present. + * @param {Object.} message Plain object to verify + * @returns {null|string} `null` if valid, otherwise the reason why it is not + */ +Type.prototype.verify = function verify_setup(message) { + return this.setup().verify(message); // overrides this method +}; + +/** + * Creates a new message of this type from a plain object. Also converts values to their respective internal types. + * @param {Object.} object Plain object to convert + * @returns {Message<{}>} Message instance + */ +Type.prototype.fromObject = function fromObject(object) { + return this.setup().fromObject(object); +}; + +/** + * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}. + * @interface IConversionOptions + * @property {Function} [longs] Long conversion type. + * Valid values are `String` and `Number` (the global types). + * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library. + * @property {Function} [enums] Enum value conversion type. + * Only valid value is `String` (the global type). + * Defaults to copy the present value, which is the numeric id. + * @property {Function} [bytes] Bytes value conversion type. + * Valid values are `Array` and (a base64 encoded) `String` (the global types). + * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser. + * @property {boolean} [defaults=false] Also sets default values on the resulting object + * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false` + * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false` + * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any + * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings + */ + +/** + * Creates a plain object from a message of this type. Also converts values to other types if specified. + * @param {Message<{}>} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ +Type.prototype.toObject = function toObject(message, options) { + return this.setup().toObject(message, options); +}; + +/** + * Decorator function as returned by {@link Type.d} (TypeScript). + * @typedef TypeDecorator + * @type {function} + * @param {Constructor} target Target constructor + * @returns {undefined} + * @template T extends Message + */ + +/** + * Type decorator (TypeScript). + * @param {string} [typeName] Type name, defaults to the constructor's name + * @returns {TypeDecorator} Decorator function + * @template T extends Message + */ +Type.d = function decorateType(typeName) { + return function typeDecorator(target) { + util.decorateType(target, typeName); + }; +}; + +},{"11":11,"12":12,"13":13,"14":14,"15":15,"18":18,"19":19,"21":21,"23":23,"24":24,"30":30,"33":33,"36":36,"37":37,"38":38}],32:[function(require,module,exports){ +"use strict"; + +/** + * Common type constants. + * @namespace + */ +var types = exports; + +var util = require(33); + +var s = [ + "double", // 0 + "float", // 1 + "int32", // 2 + "uint32", // 3 + "sint32", // 4 + "fixed32", // 5 + "sfixed32", // 6 + "int64", // 7 + "uint64", // 8 + "sint64", // 9 + "fixed64", // 10 + "sfixed64", // 11 + "bool", // 12 + "string", // 13 + "bytes" // 14 +]; + +function bake(values, offset) { + var i = 0, o = {}; + offset |= 0; + while (i < values.length) o[s[i + offset]] = values[i++]; + return o; +} + +/** + * Basic type wire types. + * @type {Object.} + * @const + * @property {number} double=1 Fixed64 wire type + * @property {number} float=5 Fixed32 wire type + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + * @property {number} string=2 Ldelim wire type + * @property {number} bytes=2 Ldelim wire type + */ +types.basic = bake([ + /* double */ 1, + /* float */ 5, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0, + /* string */ 2, + /* bytes */ 2 +]); + +/** + * Basic type defaults. + * @type {Object.} + * @const + * @property {number} double=0 Double default + * @property {number} float=0 Float default + * @property {number} int32=0 Int32 default + * @property {number} uint32=0 Uint32 default + * @property {number} sint32=0 Sint32 default + * @property {number} fixed32=0 Fixed32 default + * @property {number} sfixed32=0 Sfixed32 default + * @property {number} int64=0 Int64 default + * @property {number} uint64=0 Uint64 default + * @property {number} sint64=0 Sint32 default + * @property {number} fixed64=0 Fixed64 default + * @property {number} sfixed64=0 Sfixed64 default + * @property {boolean} bool=false Bool default + * @property {string} string="" String default + * @property {Array.} bytes=Array(0) Bytes default + * @property {null} message=null Message default + */ +types.defaults = bake([ + /* double */ 0, + /* float */ 0, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 0, + /* sfixed32 */ 0, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 0, + /* sfixed64 */ 0, + /* bool */ false, + /* string */ "", + /* bytes */ util.emptyArray, + /* message */ null +]); + +/** + * Basic long type wire types. + * @type {Object.} + * @const + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + */ +types.long = bake([ + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1 +], 7); + +/** + * Allowed types for map keys with their associated wire type. + * @type {Object.} + * @const + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + * @property {number} string=2 Ldelim wire type + */ +types.mapKey = bake([ + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0, + /* string */ 2 +], 2); + +/** + * Allowed types for packed repeated fields with their associated wire type. + * @type {Object.} + * @const + * @property {number} double=1 Fixed64 wire type + * @property {number} float=5 Fixed32 wire type + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + */ +types.packed = bake([ + /* double */ 1, + /* float */ 5, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0 +]); + +},{"33":33}],33:[function(require,module,exports){ +"use strict"; + +/** + * Various utility functions. + * @namespace + */ +var util = module.exports = require(35); + +var roots = require(27); + +var Type, // cyclic + Enum; + +util.codegen = require(3); +util.fetch = require(5); +util.path = require(8); + +/** + * Node's fs module if available. + * @type {Object.} + */ +util.fs = util.inquire("fs"); + +/** + * Converts an object's values to an array. + * @param {Object.} object Object to convert + * @returns {Array.<*>} Converted array + */ +util.toArray = function toArray(object) { + if (object) { + var keys = Object.keys(object), + array = new Array(keys.length), + index = 0; + while (index < keys.length) + array[index] = object[keys[index++]]; + return array; + } + return []; +}; + +/** + * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values. + * @param {Array.<*>} array Array to convert + * @returns {Object.} Converted object + */ +util.toObject = function toObject(array) { + var object = {}, + index = 0; + while (index < array.length) { + var key = array[index++], + val = array[index++]; + if (val !== undefined) + object[key] = val; + } + return object; +}; + +var safePropBackslashRe = /\\/g, + safePropQuoteRe = /"/g; + +/** + * Tests whether the specified name is a reserved word in JS. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +util.isReserved = function isReserved(name) { + return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name); +}; + +/** + * Returns a safe property accessor for the specified property name. + * @param {string} prop Property name + * @returns {string} Safe accessor + */ +util.safeProp = function safeProp(prop) { + if (!/^[$\w_]+$/.test(prop) || util.isReserved(prop)) + return "[\"" + prop.replace(safePropBackslashRe, "\\\\").replace(safePropQuoteRe, "\\\"") + "\"]"; + return "." + prop; +}; + +/** + * Converts the first character of a string to upper case. + * @param {string} str String to convert + * @returns {string} Converted string + */ +util.ucFirst = function ucFirst(str) { + return str.charAt(0).toUpperCase() + str.substring(1); +}; + +var camelCaseRe = /_([a-z])/g; + +/** + * Converts a string to camel case. + * @param {string} str String to convert + * @returns {string} Converted string + */ +util.camelCase = function camelCase(str) { + return str.substring(0, 1) + + str.substring(1) + .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); }); +}; + +/** + * Compares reflected fields by id. + * @param {Field} a First field + * @param {Field} b Second field + * @returns {number} Comparison value + */ +util.compareFieldsById = function compareFieldsById(a, b) { + return a.id - b.id; +}; + +/** + * Decorator helper for types (TypeScript). + * @param {Constructor} ctor Constructor function + * @param {string} [typeName] Type name, defaults to the constructor's name + * @returns {Type} Reflected type + * @template T extends Message + * @property {Root} root Decorators root + */ +util.decorateType = function decorateType(ctor, typeName) { + + /* istanbul ignore if */ + if (ctor.$type) { + if (typeName && ctor.$type.name !== typeName) { + util.decorateRoot.remove(ctor.$type); + ctor.$type.name = typeName; + util.decorateRoot.add(ctor.$type); + } + return ctor.$type; + } + + /* istanbul ignore next */ + if (!Type) + Type = require(31); + + var type = new Type(typeName || ctor.name); + util.decorateRoot.add(type); + type.ctor = ctor; // sets up .encode, .decode etc. + Object.defineProperty(ctor, "$type", { value: type, enumerable: false }); + Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false }); + return type; +}; + +var decorateEnumIndex = 0; + +/** + * Decorator helper for enums (TypeScript). + * @param {Object} object Enum object + * @returns {Enum} Reflected enum + */ +util.decorateEnum = function decorateEnum(object) { + + /* istanbul ignore if */ + if (object.$type) + return object.$type; + + /* istanbul ignore next */ + if (!Enum) + Enum = require(14); + + var enm = new Enum("Enum" + decorateEnumIndex++, object); + util.decorateRoot.add(enm); + Object.defineProperty(object, "$type", { value: enm, enumerable: false }); + return enm; +}; + + +/** + * Sets the value of a property by property path. If a value already exists, it is turned to an array + * @param {Object.} dst Destination object + * @param {string} path dot '.' delimited path of the property to set + * @param {Object} value the value to set + * @param {boolean|undefined} [ifNotSet] Sets the option only if it isn't currently set + * @returns {Object.} Destination object + */ +util.setProperty = function setProperty(dst, path, value, ifNotSet) { + function setProp(dst, path, value) { + var part = path.shift(); + if (part === "__proto__" || part === "prototype") { + return dst; + } + if (path.length > 0) { + dst[part] = setProp(dst[part] || {}, path, value); + } else { + var prevValue = dst[part]; + if (prevValue && ifNotSet) + return dst; + if (prevValue) + value = [].concat(prevValue).concat(value); + dst[part] = value; + } + return dst; + } + + if (typeof dst !== "object") + throw TypeError("dst must be an object"); + if (!path) + throw TypeError("path must be specified"); + + path = path.split("."); + return setProp(dst, path, value); +}; + +/** + * Decorator root (TypeScript). + * @name util.decorateRoot + * @type {Root} + * @readonly + */ +Object.defineProperty(util, "decorateRoot", { + get: function() { + return roots["decorated"] || (roots["decorated"] = new (require(26))()); + } +}); + +},{"14":14,"26":26,"27":27,"3":3,"31":31,"35":35,"5":5,"8":8}],34:[function(require,module,exports){ +"use strict"; +module.exports = LongBits; + +var util = require(35); + +/** + * Constructs new long bits. + * @classdesc Helper class for working with the low and high bits of a 64 bit value. + * @memberof util + * @constructor + * @param {number} lo Low 32 bits, unsigned + * @param {number} hi High 32 bits, unsigned + */ +function LongBits(lo, hi) { + + // note that the casts below are theoretically unnecessary as of today, but older statically + // generated converter code might still call the ctor with signed 32bits. kept for compat. + + /** + * Low bits. + * @type {number} + */ + this.lo = lo >>> 0; + + /** + * High bits. + * @type {number} + */ + this.hi = hi >>> 0; +} + +/** + * Zero bits. + * @memberof util.LongBits + * @type {util.LongBits} + */ +var zero = LongBits.zero = new LongBits(0, 0); + +zero.toNumber = function() { return 0; }; +zero.zzEncode = zero.zzDecode = function() { return this; }; +zero.length = function() { return 1; }; + +/** + * Zero hash. + * @memberof util.LongBits + * @type {string} + */ +var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; + +/** + * Constructs new long bits from the specified number. + * @param {number} value Value + * @returns {util.LongBits} Instance + */ +LongBits.fromNumber = function fromNumber(value) { + if (value === 0) + return zero; + var sign = value < 0; + if (sign) + value = -value; + var lo = value >>> 0, + hi = (value - lo) / 4294967296 >>> 0; + if (sign) { + hi = ~hi >>> 0; + lo = ~lo >>> 0; + if (++lo > 4294967295) { + lo = 0; + if (++hi > 4294967295) + hi = 0; + } + } + return new LongBits(lo, hi); +}; + +/** + * Constructs new long bits from a number, long or string. + * @param {Long|number|string} value Value + * @returns {util.LongBits} Instance + */ +LongBits.from = function from(value) { + if (typeof value === "number") + return LongBits.fromNumber(value); + if (util.isString(value)) { + /* istanbul ignore else */ + if (util.Long) + value = util.Long.fromString(value); + else + return LongBits.fromNumber(parseInt(value, 10)); + } + return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; +}; + +/** + * Converts this long bits to a possibly unsafe JavaScript number. + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {number} Possibly unsafe number + */ +LongBits.prototype.toNumber = function toNumber(unsigned) { + if (!unsigned && this.hi >>> 31) { + var lo = ~this.lo + 1 >>> 0, + hi = ~this.hi >>> 0; + if (!lo) + hi = hi + 1 >>> 0; + return -(lo + hi * 4294967296); + } + return this.lo + this.hi * 4294967296; +}; + +/** + * Converts this long bits to a long. + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {Long} Long + */ +LongBits.prototype.toLong = function toLong(unsigned) { + return util.Long + ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) + /* istanbul ignore next */ + : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; +}; + +var charCodeAt = String.prototype.charCodeAt; + +/** + * Constructs new long bits from the specified 8 characters long hash. + * @param {string} hash Hash + * @returns {util.LongBits} Bits + */ +LongBits.fromHash = function fromHash(hash) { + if (hash === zeroHash) + return zero; + return new LongBits( + ( charCodeAt.call(hash, 0) + | charCodeAt.call(hash, 1) << 8 + | charCodeAt.call(hash, 2) << 16 + | charCodeAt.call(hash, 3) << 24) >>> 0 + , + ( charCodeAt.call(hash, 4) + | charCodeAt.call(hash, 5) << 8 + | charCodeAt.call(hash, 6) << 16 + | charCodeAt.call(hash, 7) << 24) >>> 0 + ); +}; + +/** + * Converts this long bits to a 8 characters long hash. + * @returns {string} Hash + */ +LongBits.prototype.toHash = function toHash() { + return String.fromCharCode( + this.lo & 255, + this.lo >>> 8 & 255, + this.lo >>> 16 & 255, + this.lo >>> 24 , + this.hi & 255, + this.hi >>> 8 & 255, + this.hi >>> 16 & 255, + this.hi >>> 24 + ); +}; + +/** + * Zig-zag encodes this long bits. + * @returns {util.LongBits} `this` + */ +LongBits.prototype.zzEncode = function zzEncode() { + var mask = this.hi >> 31; + this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; + this.lo = ( this.lo << 1 ^ mask) >>> 0; + return this; +}; + +/** + * Zig-zag decodes this long bits. + * @returns {util.LongBits} `this` + */ +LongBits.prototype.zzDecode = function zzDecode() { + var mask = -(this.lo & 1); + this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; + this.hi = ( this.hi >>> 1 ^ mask) >>> 0; + return this; +}; + +/** + * Calculates the length of this longbits when encoded as a varint. + * @returns {number} Length + */ +LongBits.prototype.length = function length() { + var part0 = this.lo, + part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, + part2 = this.hi >>> 24; + return part2 === 0 + ? part1 === 0 + ? part0 < 16384 + ? part0 < 128 ? 1 : 2 + : part0 < 2097152 ? 3 : 4 + : part1 < 16384 + ? part1 < 128 ? 5 : 6 + : part1 < 2097152 ? 7 : 8 + : part2 < 128 ? 9 : 10; +}; + +},{"35":35}],35:[function(require,module,exports){ +"use strict"; +var util = exports; + +// used to return a Promise where callback is omitted +util.asPromise = require(1); + +// converts to / from base64 encoded strings +util.base64 = require(2); + +// base class of rpc.Service +util.EventEmitter = require(4); + +// float handling accross browsers +util.float = require(6); + +// requires modules optionally and hides the call from bundlers +util.inquire = require(7); + +// converts to / from utf8 encoded strings +util.utf8 = require(10); + +// provides a node-like buffer pool in the browser +util.pool = require(9); + +// utility to work with the low and high bits of a 64 bit value +util.LongBits = require(34); + +/** + * Whether running within node or not. + * @memberof util + * @type {boolean} + */ +util.isNode = Boolean(typeof global !== "undefined" + && global + && global.process + && global.process.versions + && global.process.versions.node); + +/** + * Global object reference. + * @memberof util + * @type {Object} + */ +util.global = util.isNode && global + || typeof window !== "undefined" && window + || typeof self !== "undefined" && self + || this; // eslint-disable-line no-invalid-this + +/** + * An immuable empty array. + * @memberof util + * @type {Array.<*>} + * @const + */ +util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes + +/** + * An immutable empty object. + * @type {Object} + * @const + */ +util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes + +/** + * Tests if the specified value is an integer. + * @function + * @param {*} value Value to test + * @returns {boolean} `true` if the value is an integer + */ +util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) { + return typeof value === "number" && isFinite(value) && Math.floor(value) === value; +}; + +/** + * Tests if the specified value is a string. + * @param {*} value Value to test + * @returns {boolean} `true` if the value is a string + */ +util.isString = function isString(value) { + return typeof value === "string" || value instanceof String; +}; + +/** + * Tests if the specified value is a non-null object. + * @param {*} value Value to test + * @returns {boolean} `true` if the value is a non-null object + */ +util.isObject = function isObject(value) { + return value && typeof value === "object"; +}; + +/** + * Checks if a property on a message is considered to be present. + * This is an alias of {@link util.isSet}. + * @function + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ +util.isset = + +/** + * Checks if a property on a message is considered to be present. + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ +util.isSet = function isSet(obj, prop) { + var value = obj[prop]; + if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins + return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; + return false; +}; + +/** + * Any compatible Buffer instance. + * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings. + * @interface Buffer + * @extends Uint8Array + */ + +/** + * Node's Buffer class if available. + * @type {Constructor} + */ +util.Buffer = (function() { + try { + var Buffer = util.inquire("buffer").Buffer; + // refuse to use non-node buffers if not explicitly assigned (perf reasons): + return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null; + } catch (e) { + /* istanbul ignore next */ + return null; + } +})(); + +// Internal alias of or polyfull for Buffer.from. +util._Buffer_from = null; + +// Internal alias of or polyfill for Buffer.allocUnsafe. +util._Buffer_allocUnsafe = null; + +/** + * Creates a new buffer of whatever type supported by the environment. + * @param {number|number[]} [sizeOrArray=0] Buffer size or number array + * @returns {Uint8Array|Buffer} Buffer + */ +util.newBuffer = function newBuffer(sizeOrArray) { + /* istanbul ignore next */ + return typeof sizeOrArray === "number" + ? util.Buffer + ? util._Buffer_allocUnsafe(sizeOrArray) + : new util.Array(sizeOrArray) + : util.Buffer + ? util._Buffer_from(sizeOrArray) + : typeof Uint8Array === "undefined" + ? sizeOrArray + : new Uint8Array(sizeOrArray); +}; + +/** + * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`. + * @type {Constructor} + */ +util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array; + +/** + * Any compatible Long instance. + * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js. + * @interface Long + * @property {number} low Low bits + * @property {number} high High bits + * @property {boolean} unsigned Whether unsigned or not + */ + +/** + * Long.js's Long class if available. + * @type {Constructor} + */ +util.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long + || /* istanbul ignore next */ util.global.Long + || util.inquire("long"); + +/** + * Regular expression used to verify 2 bit (`bool`) map keys. + * @type {RegExp} + * @const + */ +util.key2Re = /^true|false|0|1$/; + +/** + * Regular expression used to verify 32 bit (`int32` etc.) map keys. + * @type {RegExp} + * @const + */ +util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; + +/** + * Regular expression used to verify 64 bit (`int64` etc.) map keys. + * @type {RegExp} + * @const + */ +util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; + +/** + * Converts a number or long to an 8 characters long hash string. + * @param {Long|number} value Value to convert + * @returns {string} Hash + */ +util.longToHash = function longToHash(value) { + return value + ? util.LongBits.from(value).toHash() + : util.LongBits.zeroHash; +}; + +/** + * Converts an 8 characters long hash string to a long or number. + * @param {string} hash Hash + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {Long|number} Original value + */ +util.longFromHash = function longFromHash(hash, unsigned) { + var bits = util.LongBits.fromHash(hash); + if (util.Long) + return util.Long.fromBits(bits.lo, bits.hi, unsigned); + return bits.toNumber(Boolean(unsigned)); +}; + +/** + * Merges the properties of the source object into the destination object. + * @memberof util + * @param {Object.} dst Destination object + * @param {Object.} src Source object + * @param {boolean} [ifNotSet=false] Merges only if the key is not already set + * @returns {Object.} Destination object + */ +function merge(dst, src, ifNotSet) { // used by converters + for (var keys = Object.keys(src), i = 0; i < keys.length; ++i) + if (dst[keys[i]] === undefined || !ifNotSet) + dst[keys[i]] = src[keys[i]]; + return dst; +} + +util.merge = merge; + +/** + * Converts the first character of a string to lower case. + * @param {string} str String to convert + * @returns {string} Converted string + */ +util.lcFirst = function lcFirst(str) { + return str.charAt(0).toLowerCase() + str.substring(1); +}; + +/** + * Creates a custom error constructor. + * @memberof util + * @param {string} name Error name + * @returns {Constructor} Custom error constructor + */ +function newError(name) { + + function CustomError(message, properties) { + + if (!(this instanceof CustomError)) + return new CustomError(message, properties); + + // Error.call(this, message); + // ^ just returns a new error instance because the ctor can be called as a function + + Object.defineProperty(this, "message", { get: function() { return message; } }); + + /* istanbul ignore next */ + if (Error.captureStackTrace) // node + Error.captureStackTrace(this, CustomError); + else + Object.defineProperty(this, "stack", { value: new Error().stack || "" }); + + if (properties) + merge(this, properties); + } + + CustomError.prototype = Object.create(Error.prototype, { + constructor: { + value: CustomError, + writable: true, + enumerable: false, + configurable: true, + }, + name: { + get: function get() { return name; }, + set: undefined, + enumerable: false, + // configurable: false would accurately preserve the behavior of + // the original, but I'm guessing that was not intentional. + // For an actual error subclass, this property would + // be configurable. + configurable: true, + }, + toString: { + value: function value() { return this.name + ": " + this.message; }, + writable: true, + enumerable: false, + configurable: true, + }, + }); + + return CustomError; +} + +util.newError = newError; + +/** + * Constructs a new protocol error. + * @classdesc Error subclass indicating a protocol specifc error. + * @memberof util + * @extends Error + * @template T extends Message + * @constructor + * @param {string} message Error message + * @param {Object.} [properties] Additional properties + * @example + * try { + * MyMessage.decode(someBuffer); // throws if required fields are missing + * } catch (e) { + * if (e instanceof ProtocolError && e.instance) + * console.log("decoded so far: " + JSON.stringify(e.instance)); + * } + */ +util.ProtocolError = newError("ProtocolError"); + +/** + * So far decoded message instance. + * @name util.ProtocolError#instance + * @type {Message} + */ + +/** + * A OneOf getter as returned by {@link util.oneOfGetter}. + * @typedef OneOfGetter + * @type {function} + * @returns {string|undefined} Set field name, if any + */ + +/** + * Builds a getter for a oneof's present field name. + * @param {string[]} fieldNames Field names + * @returns {OneOfGetter} Unbound getter + */ +util.oneOfGetter = function getOneOf(fieldNames) { + var fieldMap = {}; + for (var i = 0; i < fieldNames.length; ++i) + fieldMap[fieldNames[i]] = 1; + + /** + * @returns {string|undefined} Set field name, if any + * @this Object + * @ignore + */ + return function() { // eslint-disable-line consistent-return + for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i) + if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null) + return keys[i]; + }; +}; + +/** + * A OneOf setter as returned by {@link util.oneOfSetter}. + * @typedef OneOfSetter + * @type {function} + * @param {string|undefined} value Field name + * @returns {undefined} + */ + +/** + * Builds a setter for a oneof's present field name. + * @param {string[]} fieldNames Field names + * @returns {OneOfSetter} Unbound setter + */ +util.oneOfSetter = function setOneOf(fieldNames) { + + /** + * @param {string} name Field name + * @returns {undefined} + * @this Object + * @ignore + */ + return function(name) { + for (var i = 0; i < fieldNames.length; ++i) + if (fieldNames[i] !== name) + delete this[fieldNames[i]]; + }; +}; + +/** + * Default conversion options used for {@link Message#toJSON} implementations. + * + * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely: + * + * - Longs become strings + * - Enums become string keys + * - Bytes become base64 encoded strings + * - (Sub-)Messages become plain objects + * - Maps become plain objects with all string keys + * - Repeated fields become arrays + * - NaN and Infinity for float and double fields become strings + * + * @type {IConversionOptions} + * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json + */ +util.toJSONOptions = { + longs: String, + enums: String, + bytes: String, + json: true +}; + +// Sets up buffer utility according to the environment (called in index-minimal) +util._configure = function() { + var Buffer = util.Buffer; + /* istanbul ignore if */ + if (!Buffer) { + util._Buffer_from = util._Buffer_allocUnsafe = null; + return; + } + // because node 4.x buffers are incompatible & immutable + // see: https://github.com/dcodeIO/protobuf.js/pull/665 + util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from || + /* istanbul ignore next */ + function Buffer_from(value, encoding) { + return new Buffer(value, encoding); + }; + util._Buffer_allocUnsafe = Buffer.allocUnsafe || + /* istanbul ignore next */ + function Buffer_allocUnsafe(size) { + return new Buffer(size); + }; +}; + +},{"1":1,"10":10,"2":2,"34":34,"4":4,"6":6,"7":7,"9":9}],36:[function(require,module,exports){ +"use strict"; +module.exports = verifier; + +var Enum = require(14), + util = require(33); + +function invalid(field, expected) { + return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:"+field.keyType+"}" : "") + " expected"; +} + +/** + * Generates a partial value verifier. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {number} fieldIndex Field index + * @param {string} ref Variable reference + * @returns {Codegen} Codegen instance + * @ignore + */ +function genVerifyValue(gen, field, fieldIndex, ref) { + /* eslint-disable no-unexpected-multiline */ + if (field.resolvedType) { + if (field.resolvedType instanceof Enum) { gen + ("switch(%s){", ref) + ("default:") + ("return%j", invalid(field, "enum value")); + for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen + ("case %i:", field.resolvedType.values[keys[j]]); + gen + ("break") + ("}"); + } else { + gen + ("{") + ("var e=types[%i].verify(%s);", fieldIndex, ref) + ("if(e)") + ("return%j+e", field.name + ".") + ("}"); + } + } else { + switch (field.type) { + case "int32": + case "uint32": + case "sint32": + case "fixed32": + case "sfixed32": gen + ("if(!util.isInteger(%s))", ref) + ("return%j", invalid(field, "integer")); + break; + case "int64": + case "uint64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))", ref, ref, ref, ref) + ("return%j", invalid(field, "integer|Long")); + break; + case "float": + case "double": gen + ("if(typeof %s!==\"number\")", ref) + ("return%j", invalid(field, "number")); + break; + case "bool": gen + ("if(typeof %s!==\"boolean\")", ref) + ("return%j", invalid(field, "boolean")); + break; + case "string": gen + ("if(!util.isString(%s))", ref) + ("return%j", invalid(field, "string")); + break; + case "bytes": gen + ("if(!(%s&&typeof %s.length===\"number\"||util.isString(%s)))", ref, ref, ref) + ("return%j", invalid(field, "buffer")); + break; + } + } + return gen; + /* eslint-enable no-unexpected-multiline */ +} + +/** + * Generates a partial key verifier. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {string} ref Variable reference + * @returns {Codegen} Codegen instance + * @ignore + */ +function genVerifyKey(gen, field, ref) { + /* eslint-disable no-unexpected-multiline */ + switch (field.keyType) { + case "int32": + case "uint32": + case "sint32": + case "fixed32": + case "sfixed32": gen + ("if(!util.key32Re.test(%s))", ref) + ("return%j", invalid(field, "integer key")); + break; + case "int64": + case "uint64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(!util.key64Re.test(%s))", ref) // see comment above: x is ok, d is not + ("return%j", invalid(field, "integer|Long key")); + break; + case "bool": gen + ("if(!util.key2Re.test(%s))", ref) + ("return%j", invalid(field, "boolean key")); + break; + } + return gen; + /* eslint-enable no-unexpected-multiline */ +} + +/** + * Generates a verifier specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +function verifier(mtype) { + /* eslint-disable no-unexpected-multiline */ + + var gen = util.codegen(["m"], mtype.name + "$verify") + ("if(typeof m!==\"object\"||m===null)") + ("return%j", "object expected"); + var oneofs = mtype.oneofsArray, + seenFirstField = {}; + if (oneofs.length) gen + ("var p={}"); + + for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) { + var field = mtype._fieldsArray[i].resolve(), + ref = "m" + util.safeProp(field.name); + + if (field.optional) gen + ("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name); // !== undefined && !== null + + // map fields + if (field.map) { gen + ("if(!util.isObject(%s))", ref) + ("return%j", invalid(field, "object")) + ("var k=Object.keys(%s)", ref) + ("for(var i=0;i} + * @const + */ +var wrappers = exports; + +var Message = require(19); + +/** + * From object converter part of an {@link IWrapper}. + * @typedef WrapperFromObjectConverter + * @type {function} + * @param {Object.} object Plain object + * @returns {Message<{}>} Message instance + * @this Type + */ + +/** + * To object converter part of an {@link IWrapper}. + * @typedef WrapperToObjectConverter + * @type {function} + * @param {Message<{}>} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + * @this Type + */ + +/** + * Common type wrapper part of {@link wrappers}. + * @interface IWrapper + * @property {WrapperFromObjectConverter} [fromObject] From object converter + * @property {WrapperToObjectConverter} [toObject] To object converter + */ + +// Custom wrapper for Any +wrappers[".google.protobuf.Any"] = { + + fromObject: function(object) { + + // unwrap value type if mapped + if (object && object["@type"]) { + // Only use fully qualified type name after the last '/' + var name = object["@type"].substring(object["@type"].lastIndexOf("/") + 1); + var type = this.lookup(name); + /* istanbul ignore else */ + if (type) { + // type_url does not accept leading "." + var type_url = object["@type"].charAt(0) === "." ? + object["@type"].slice(1) : object["@type"]; + // type_url prefix is optional, but path seperator is required + if (type_url.indexOf("/") === -1) { + type_url = "/" + type_url; + } + return this.create({ + type_url: type_url, + value: type.encode(type.fromObject(object)).finish() + }); + } + } + + return this.fromObject(object); + }, + + toObject: function(message, options) { + + // Default prefix + var googleApi = "type.googleapis.com/"; + var prefix = ""; + var name = ""; + + // decode value if requested and unmapped + if (options && options.json && message.type_url && message.value) { + // Only use fully qualified type name after the last '/' + name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1); + // Separate the prefix used + prefix = message.type_url.substring(0, message.type_url.lastIndexOf("/") + 1); + var type = this.lookup(name); + /* istanbul ignore else */ + if (type) + message = type.decode(message.value); + } + + // wrap value if unmapped + if (!(message instanceof this.ctor) && message instanceof Message) { + var object = message.$type.toObject(message, options); + var messageName = message.$type.fullName[0] === "." ? + message.$type.fullName.slice(1) : message.$type.fullName; + // Default to type.googleapis.com prefix if no prefix is used + if (prefix === "") { + prefix = googleApi; + } + name = prefix + messageName; + object["@type"] = name; + return object; + } + + return this.toObject(message, options); + } +}; + +},{"19":19}],38:[function(require,module,exports){ +"use strict"; +module.exports = Writer; + +var util = require(35); + +var BufferWriter; // cyclic + +var LongBits = util.LongBits, + base64 = util.base64, + utf8 = util.utf8; + +/** + * Constructs a new writer operation instance. + * @classdesc Scheduled writer operation. + * @constructor + * @param {function(*, Uint8Array, number)} fn Function to call + * @param {number} len Value byte length + * @param {*} val Value to write + * @ignore + */ +function Op(fn, len, val) { + + /** + * Function to call. + * @type {function(Uint8Array, number, *)} + */ + this.fn = fn; + + /** + * Value byte length. + * @type {number} + */ + this.len = len; + + /** + * Next operation. + * @type {Writer.Op|undefined} + */ + this.next = undefined; + + /** + * Value to write. + * @type {*} + */ + this.val = val; // type varies +} + +/* istanbul ignore next */ +function noop() {} // eslint-disable-line no-empty-function + +/** + * Constructs a new writer state instance. + * @classdesc Copied writer state. + * @memberof Writer + * @constructor + * @param {Writer} writer Writer to copy state from + * @ignore + */ +function State(writer) { + + /** + * Current head. + * @type {Writer.Op} + */ + this.head = writer.head; + + /** + * Current tail. + * @type {Writer.Op} + */ + this.tail = writer.tail; + + /** + * Current buffer length. + * @type {number} + */ + this.len = writer.len; + + /** + * Next state. + * @type {State|null} + */ + this.next = writer.states; +} + +/** + * Constructs a new writer instance. + * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`. + * @constructor + */ +function Writer() { + + /** + * Current length. + * @type {number} + */ + this.len = 0; + + /** + * Operations head. + * @type {Object} + */ + this.head = new Op(noop, 0, 0); + + /** + * Operations tail + * @type {Object} + */ + this.tail = this.head; + + /** + * Linked forked states. + * @type {Object|null} + */ + this.states = null; + + // When a value is written, the writer calculates its byte length and puts it into a linked + // list of operations to perform when finish() is called. This both allows us to allocate + // buffers of the exact required size and reduces the amount of work we have to do compared + // to first calculating over objects and then encoding over objects. In our case, the encoding + // part is just a linked list walk calling operations with already prepared values. +} + +var create = function create() { + return util.Buffer + ? function create_buffer_setup() { + return (Writer.create = function create_buffer() { + return new BufferWriter(); + })(); + } + /* istanbul ignore next */ + : function create_array() { + return new Writer(); + }; +}; + +/** + * Creates a new writer. + * @function + * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer} + */ +Writer.create = create(); + +/** + * Allocates a buffer of the specified size. + * @param {number} size Buffer size + * @returns {Uint8Array} Buffer + */ +Writer.alloc = function alloc(size) { + return new util.Array(size); +}; + +// Use Uint8Array buffer pool in the browser, just like node does with buffers +/* istanbul ignore else */ +if (util.Array !== Array) + Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray); + +/** + * Pushes a new operation to the queue. + * @param {function(Uint8Array, number, *)} fn Function to call + * @param {number} len Value byte length + * @param {number} val Value to write + * @returns {Writer} `this` + * @private + */ +Writer.prototype._push = function push(fn, len, val) { + this.tail = this.tail.next = new Op(fn, len, val); + this.len += len; + return this; +}; + +function writeByte(val, buf, pos) { + buf[pos] = val & 255; +} + +function writeVarint32(val, buf, pos) { + while (val > 127) { + buf[pos++] = val & 127 | 128; + val >>>= 7; + } + buf[pos] = val; +} + +/** + * Constructs a new varint writer operation instance. + * @classdesc Scheduled varint writer operation. + * @extends Op + * @constructor + * @param {number} len Value byte length + * @param {number} val Value to write + * @ignore + */ +function VarintOp(len, val) { + this.len = len; + this.next = undefined; + this.val = val; +} + +VarintOp.prototype = Object.create(Op.prototype); +VarintOp.prototype.fn = writeVarint32; + +/** + * Writes an unsigned 32 bit value as a varint. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.uint32 = function write_uint32(value) { + // here, the call to this.push has been inlined and a varint specific Op subclass is used. + // uint32 is by far the most frequently used operation and benefits significantly from this. + this.len += (this.tail = this.tail.next = new VarintOp( + (value = value >>> 0) + < 128 ? 1 + : value < 16384 ? 2 + : value < 2097152 ? 3 + : value < 268435456 ? 4 + : 5, + value)).len; + return this; +}; + +/** + * Writes a signed 32 bit value as a varint. + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.int32 = function write_int32(value) { + return value < 0 + ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec + : this.uint32(value); +}; + +/** + * Writes a 32 bit value as a varint, zig-zag encoded. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.sint32 = function write_sint32(value) { + return this.uint32((value << 1 ^ value >> 31) >>> 0); +}; + +function writeVarint64(val, buf, pos) { + while (val.hi) { + buf[pos++] = val.lo & 127 | 128; + val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; + val.hi >>>= 7; + } + while (val.lo > 127) { + buf[pos++] = val.lo & 127 | 128; + val.lo = val.lo >>> 7; + } + buf[pos++] = val.lo; +} + +/** + * Writes an unsigned 64 bit value as a varint. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.uint64 = function write_uint64(value) { + var bits = LongBits.from(value); + return this._push(writeVarint64, bits.length(), bits); +}; + +/** + * Writes a signed 64 bit value as a varint. + * @function + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.int64 = Writer.prototype.uint64; + +/** + * Writes a signed 64 bit value as a varint, zig-zag encoded. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.sint64 = function write_sint64(value) { + var bits = LongBits.from(value).zzEncode(); + return this._push(writeVarint64, bits.length(), bits); +}; + +/** + * Writes a boolish value as a varint. + * @param {boolean} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.bool = function write_bool(value) { + return this._push(writeByte, 1, value ? 1 : 0); +}; + +function writeFixed32(val, buf, pos) { + buf[pos ] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; +} + +/** + * Writes an unsigned 32 bit value as fixed 32 bits. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.fixed32 = function write_fixed32(value) { + return this._push(writeFixed32, 4, value >>> 0); +}; + +/** + * Writes a signed 32 bit value as fixed 32 bits. + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.sfixed32 = Writer.prototype.fixed32; + +/** + * Writes an unsigned 64 bit value as fixed 64 bits. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.fixed64 = function write_fixed64(value) { + var bits = LongBits.from(value); + return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); +}; + +/** + * Writes a signed 64 bit value as fixed 64 bits. + * @function + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.sfixed64 = Writer.prototype.fixed64; + +/** + * Writes a float (32 bit). + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.float = function write_float(value) { + return this._push(util.float.writeFloatLE, 4, value); +}; + +/** + * Writes a double (64 bit float). + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.double = function write_double(value) { + return this._push(util.float.writeDoubleLE, 8, value); +}; + +var writeBytes = util.Array.prototype.set + ? function writeBytes_set(val, buf, pos) { + buf.set(val, pos); // also works for plain array values + } + /* istanbul ignore next */ + : function writeBytes_for(val, buf, pos) { + for (var i = 0; i < val.length; ++i) + buf[pos + i] = val[i]; + }; + +/** + * Writes a sequence of bytes. + * @param {Uint8Array|string} value Buffer or base64 encoded string to write + * @returns {Writer} `this` + */ +Writer.prototype.bytes = function write_bytes(value) { + var len = value.length >>> 0; + if (!len) + return this._push(writeByte, 1, 0); + if (util.isString(value)) { + var buf = Writer.alloc(len = base64.length(value)); + base64.decode(value, buf, 0); + value = buf; + } + return this.uint32(len)._push(writeBytes, len, value); +}; + +/** + * Writes a string. + * @param {string} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.string = function write_string(value) { + var len = utf8.length(value); + return len + ? this.uint32(len)._push(utf8.write, len, value) + : this._push(writeByte, 1, 0); +}; + +/** + * Forks this writer's state by pushing it to a stack. + * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state. + * @returns {Writer} `this` + */ +Writer.prototype.fork = function fork() { + this.states = new State(this); + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + return this; +}; + +/** + * Resets this instance to the last state. + * @returns {Writer} `this` + */ +Writer.prototype.reset = function reset() { + if (this.states) { + this.head = this.states.head; + this.tail = this.states.tail; + this.len = this.states.len; + this.states = this.states.next; + } else { + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + } + return this; +}; + +/** + * Resets to the last state and appends the fork state's current write length as a varint followed by its operations. + * @returns {Writer} `this` + */ +Writer.prototype.ldelim = function ldelim() { + var head = this.head, + tail = this.tail, + len = this.len; + this.reset().uint32(len); + if (len) { + this.tail.next = head.next; // skip noop + this.tail = tail; + this.len += len; + } + return this; +}; + +/** + * Finishes the write operation. + * @returns {Uint8Array} Finished buffer + */ +Writer.prototype.finish = function finish() { + var head = this.head.next, // skip noop + buf = this.constructor.alloc(this.len), + pos = 0; + while (head) { + head.fn(head.val, buf, pos); + pos += head.len; + head = head.next; + } + // this.head = this.tail = null; + return buf; +}; + +Writer._configure = function(BufferWriter_) { + BufferWriter = BufferWriter_; + Writer.create = create(); + BufferWriter._configure(); +}; + +},{"35":35}],39:[function(require,module,exports){ +"use strict"; +module.exports = BufferWriter; + +// extends Writer +var Writer = require(38); +(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; + +var util = require(35); + +/** + * Constructs a new buffer writer instance. + * @classdesc Wire format writer using node buffers. + * @extends Writer + * @constructor + */ +function BufferWriter() { + Writer.call(this); +} + +BufferWriter._configure = function () { + /** + * Allocates a buffer of the specified size. + * @function + * @param {number} size Buffer size + * @returns {Buffer} Buffer + */ + BufferWriter.alloc = util._Buffer_allocUnsafe; + + BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set" + ? function writeBytesBuffer_set(val, buf, pos) { + buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited) + // also works for plain array values + } + /* istanbul ignore next */ + : function writeBytesBuffer_copy(val, buf, pos) { + if (val.copy) // Buffer values + val.copy(buf, pos, 0, val.length); + else for (var i = 0; i < val.length;) // plain array values + buf[pos++] = val[i++]; + }; +}; + + +/** + * @override + */ +BufferWriter.prototype.bytes = function write_bytes_buffer(value) { + if (util.isString(value)) + value = util._Buffer_from(value, "base64"); + var len = value.length >>> 0; + this.uint32(len); + if (len) + this._push(BufferWriter.writeBytesBuffer, len, value); + return this; +}; + +function writeStringBuffer(val, buf, pos) { + if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions) + util.utf8.write(val, buf, pos); + else if (buf.utf8Write) + buf.utf8Write(val, pos); + else + buf.write(val, pos); +} + +/** + * @override + */ +BufferWriter.prototype.string = function write_string_buffer(value) { + var len = util.Buffer.byteLength(value); + this.uint32(len); + if (len) + this._push(writeStringBuffer, len, value); + return this; +}; + + +/** + * Finishes the write operation. + * @name BufferWriter#finish + * @function + * @returns {Buffer} Finished buffer + */ + +BufferWriter._configure(); + +},{"35":35,"38":38}]},{},[16]) + +})(); +//# sourceMappingURL=protobuf.js.map diff --git a/node_modules/protobufjs/dist/light/protobuf.js.map b/node_modules/protobufjs/dist/light/protobuf.js.map new file mode 100644 index 0000000..bbc4fe6 --- /dev/null +++ b/node_modules/protobufjs/dist/light/protobuf.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["lib/prelude.js","../node_modules/@protobufjs/aspromise/index.js","../node_modules/@protobufjs/base64/index.js","../node_modules/@protobufjs/codegen/index.js","../node_modules/@protobufjs/eventemitter/index.js","../node_modules/@protobufjs/fetch/index.js","../node_modules/@protobufjs/float/index.js","../node_modules/@protobufjs/inquire/index.js","../node_modules/@protobufjs/path/index.js","../node_modules/@protobufjs/pool/index.js","../node_modules/@protobufjs/utf8/index.js","../src/converter.js","../src/decoder.js","../src/encoder.js","../src/enum.js","../src/field.js","../src/index-light","../src/index-minimal.js","../src/mapfield.js","../src/message.js","../src/method.js","../src/namespace.js","../src/object.js","../src/oneof.js","../src/reader.js","../src/reader_buffer.js","../src/root.js","../src/roots.js","../src/rpc.js","../src/rpc/service.js","../src/service.js","../src/type.js","../src/types.js","../src/util.js","../src/util/longbits.js","../src/util/minimal.js","../src/verifier.js","../src/wrappers.js","../src/writer.js","../src/writer_buffer.js"],"names":[],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/UA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7SA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrcA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACliBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1XA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtmBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"protobuf.js","sourcesContent":["(function prelude(modules, cache, entries) {\n\n // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS\n // sources through a conflict-free require shim and is again wrapped within an iife that\n // provides a minification-friendly `undefined` var plus a global \"use strict\" directive\n // so that minification can remove the directives of each module.\n\n function $require(name) {\n var $module = cache[name];\n if (!$module)\n modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports);\n return $module.exports;\n }\n\n var protobuf = $require(entries[0]);\n\n // Expose globally\n protobuf.util.global.protobuf = protobuf;\n\n // Be nice to AMD\n if (typeof define === \"function\" && define.amd)\n define([\"long\"], function(Long) {\n if (Long && Long.isLong) {\n protobuf.util.Long = Long;\n protobuf.configure();\n }\n return protobuf;\n });\n\n // Be nice to CommonJS\n if (typeof module === \"object\" && module && module.exports)\n module.exports = protobuf;\n\n})/* end of prelude */","\"use strict\";\r\nmodule.exports = asPromise;\r\n\r\n/**\r\n * Callback as used by {@link util.asPromise}.\r\n * @typedef asPromiseCallback\r\n * @type {function}\r\n * @param {Error|null} error Error, if any\r\n * @param {...*} params Additional arguments\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Returns a promise from a node-style callback function.\r\n * @memberof util\r\n * @param {asPromiseCallback} fn Function to call\r\n * @param {*} ctx Function context\r\n * @param {...*} params Function arguments\r\n * @returns {Promise<*>} Promisified function\r\n */\r\nfunction asPromise(fn, ctx/*, varargs */) {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0,\r\n index = 2,\r\n pending = true;\r\n while (index < arguments.length)\r\n params[offset++] = arguments[index++];\r\n return new Promise(function executor(resolve, reject) {\r\n params[offset] = function callback(err/*, varargs */) {\r\n if (pending) {\r\n pending = false;\r\n if (err)\r\n reject(err);\r\n else {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0;\r\n while (offset < params.length)\r\n params[offset++] = arguments[offset];\r\n resolve.apply(null, params);\r\n }\r\n }\r\n };\r\n try {\r\n fn.apply(ctx || null, params);\r\n } catch (err) {\r\n if (pending) {\r\n pending = false;\r\n reject(err);\r\n }\r\n }\r\n });\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal base64 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar base64 = exports;\r\n\r\n/**\r\n * Calculates the byte length of a base64 encoded string.\r\n * @param {string} string Base64 encoded string\r\n * @returns {number} Byte length\r\n */\r\nbase64.length = function length(string) {\r\n var p = string.length;\r\n if (!p)\r\n return 0;\r\n var n = 0;\r\n while (--p % 4 > 1 && string.charAt(p) === \"=\")\r\n ++n;\r\n return Math.ceil(string.length * 3) / 4 - n;\r\n};\r\n\r\n// Base64 encoding table\r\nvar b64 = new Array(64);\r\n\r\n// Base64 decoding table\r\nvar s64 = new Array(123);\r\n\r\n// 65..90, 97..122, 48..57, 43, 47\r\nfor (var i = 0; i < 64;)\r\n s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;\r\n\r\n/**\r\n * Encodes a buffer to a base64 encoded string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} Base64 encoded string\r\n */\r\nbase64.encode = function encode(buffer, start, end) {\r\n var parts = null,\r\n chunk = [];\r\n var i = 0, // output index\r\n j = 0, // goto index\r\n t; // temporary\r\n while (start < end) {\r\n var b = buffer[start++];\r\n switch (j) {\r\n case 0:\r\n chunk[i++] = b64[b >> 2];\r\n t = (b & 3) << 4;\r\n j = 1;\r\n break;\r\n case 1:\r\n chunk[i++] = b64[t | b >> 4];\r\n t = (b & 15) << 2;\r\n j = 2;\r\n break;\r\n case 2:\r\n chunk[i++] = b64[t | b >> 6];\r\n chunk[i++] = b64[b & 63];\r\n j = 0;\r\n break;\r\n }\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (j) {\r\n chunk[i++] = b64[t];\r\n chunk[i++] = 61;\r\n if (j === 1)\r\n chunk[i++] = 61;\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\nvar invalidEncoding = \"invalid encoding\";\r\n\r\n/**\r\n * Decodes a base64 encoded string to a buffer.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Number of bytes written\r\n * @throws {Error} If encoding is invalid\r\n */\r\nbase64.decode = function decode(string, buffer, offset) {\r\n var start = offset;\r\n var j = 0, // goto index\r\n t; // temporary\r\n for (var i = 0; i < string.length;) {\r\n var c = string.charCodeAt(i++);\r\n if (c === 61 && j > 1)\r\n break;\r\n if ((c = s64[c]) === undefined)\r\n throw Error(invalidEncoding);\r\n switch (j) {\r\n case 0:\r\n t = c;\r\n j = 1;\r\n break;\r\n case 1:\r\n buffer[offset++] = t << 2 | (c & 48) >> 4;\r\n t = c;\r\n j = 2;\r\n break;\r\n case 2:\r\n buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;\r\n t = c;\r\n j = 3;\r\n break;\r\n case 3:\r\n buffer[offset++] = (t & 3) << 6 | c;\r\n j = 0;\r\n break;\r\n }\r\n }\r\n if (j === 1)\r\n throw Error(invalidEncoding);\r\n return offset - start;\r\n};\r\n\r\n/**\r\n * Tests if the specified string appears to be base64 encoded.\r\n * @param {string} string String to test\r\n * @returns {boolean} `true` if probably base64 encoded, otherwise false\r\n */\r\nbase64.test = function test(string) {\r\n return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);\r\n};\r\n","\"use strict\";\r\nmodule.exports = codegen;\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @param {string[]} functionParams Function parameter names\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n */\r\nfunction codegen(functionParams, functionName) {\r\n\r\n /* istanbul ignore if */\r\n if (typeof functionParams === \"string\") {\r\n functionName = functionParams;\r\n functionParams = undefined;\r\n }\r\n\r\n var body = [];\r\n\r\n /**\r\n * Appends code to the function's body or finishes generation.\r\n * @typedef Codegen\r\n * @type {function}\r\n * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any\r\n * @param {...*} [formatParams] Format parameters\r\n * @returns {Codegen|Function} Itself or the generated function if finished\r\n * @throws {Error} If format parameter counts do not match\r\n */\r\n\r\n function Codegen(formatStringOrScope) {\r\n // note that explicit array handling below makes this ~50% faster\r\n\r\n // finish the function\r\n if (typeof formatStringOrScope !== \"string\") {\r\n var source = toString();\r\n if (codegen.verbose)\r\n console.log(\"codegen: \" + source); // eslint-disable-line no-console\r\n source = \"return \" + source;\r\n if (formatStringOrScope) {\r\n var scopeKeys = Object.keys(formatStringOrScope),\r\n scopeParams = new Array(scopeKeys.length + 1),\r\n scopeValues = new Array(scopeKeys.length),\r\n scopeOffset = 0;\r\n while (scopeOffset < scopeKeys.length) {\r\n scopeParams[scopeOffset] = scopeKeys[scopeOffset];\r\n scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]];\r\n }\r\n scopeParams[scopeOffset] = source;\r\n return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func\r\n }\r\n return Function(source)(); // eslint-disable-line no-new-func\r\n }\r\n\r\n // otherwise append to body\r\n var formatParams = new Array(arguments.length - 1),\r\n formatOffset = 0;\r\n while (formatOffset < formatParams.length)\r\n formatParams[formatOffset] = arguments[++formatOffset];\r\n formatOffset = 0;\r\n formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) {\r\n var value = formatParams[formatOffset++];\r\n switch ($1) {\r\n case \"d\": case \"f\": return String(Number(value));\r\n case \"i\": return String(Math.floor(value));\r\n case \"j\": return JSON.stringify(value);\r\n case \"s\": return String(value);\r\n }\r\n return \"%\";\r\n });\r\n if (formatOffset !== formatParams.length)\r\n throw Error(\"parameter count mismatch\");\r\n body.push(formatStringOrScope);\r\n return Codegen;\r\n }\r\n\r\n function toString(functionNameOverride) {\r\n return \"function \" + (functionNameOverride || functionName || \"\") + \"(\" + (functionParams && functionParams.join(\",\") || \"\") + \"){\\n \" + body.join(\"\\n \") + \"\\n}\";\r\n }\r\n\r\n Codegen.toString = toString;\r\n return Codegen;\r\n}\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @function codegen\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * When set to `true`, codegen will log generated code to console. Useful for debugging.\r\n * @name util.codegen.verbose\r\n * @type {boolean}\r\n */\r\ncodegen.verbose = false;\r\n","\"use strict\";\r\nmodule.exports = EventEmitter;\r\n\r\n/**\r\n * Constructs a new event emitter instance.\r\n * @classdesc A minimal event emitter.\r\n * @memberof util\r\n * @constructor\r\n */\r\nfunction EventEmitter() {\r\n\r\n /**\r\n * Registered listeners.\r\n * @type {Object.}\r\n * @private\r\n */\r\n this._listeners = {};\r\n}\r\n\r\n/**\r\n * Registers an event listener.\r\n * @param {string} evt Event name\r\n * @param {function} fn Listener\r\n * @param {*} [ctx] Listener context\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.on = function on(evt, fn, ctx) {\r\n (this._listeners[evt] || (this._listeners[evt] = [])).push({\r\n fn : fn,\r\n ctx : ctx || this\r\n });\r\n return this;\r\n};\r\n\r\n/**\r\n * Removes an event listener or any matching listeners if arguments are omitted.\r\n * @param {string} [evt] Event name. Removes all listeners if omitted.\r\n * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.off = function off(evt, fn) {\r\n if (evt === undefined)\r\n this._listeners = {};\r\n else {\r\n if (fn === undefined)\r\n this._listeners[evt] = [];\r\n else {\r\n var listeners = this._listeners[evt];\r\n for (var i = 0; i < listeners.length;)\r\n if (listeners[i].fn === fn)\r\n listeners.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emits an event by calling its listeners with the specified arguments.\r\n * @param {string} evt Event name\r\n * @param {...*} args Arguments\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.emit = function emit(evt) {\r\n var listeners = this._listeners[evt];\r\n if (listeners) {\r\n var args = [],\r\n i = 1;\r\n for (; i < arguments.length;)\r\n args.push(arguments[i++]);\r\n for (i = 0; i < listeners.length;)\r\n listeners[i].fn.apply(listeners[i++].ctx, args);\r\n }\r\n return this;\r\n};\r\n","\"use strict\";\r\nmodule.exports = fetch;\r\n\r\nvar asPromise = require(1),\r\n inquire = require(7);\r\n\r\nvar fs = inquire(\"fs\");\r\n\r\n/**\r\n * Node-style callback as used by {@link util.fetch}.\r\n * @typedef FetchCallback\r\n * @type {function}\r\n * @param {?Error} error Error, if any, otherwise `null`\r\n * @param {string} [contents] File contents, if there hasn't been an error\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Options as used by {@link util.fetch}.\r\n * @typedef FetchOptions\r\n * @type {Object}\r\n * @property {boolean} [binary=false] Whether expecting a binary response\r\n * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @memberof util\r\n * @param {string} filename File path or url\r\n * @param {FetchOptions} options Fetch options\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n */\r\nfunction fetch(filename, options, callback) {\r\n if (typeof options === \"function\") {\r\n callback = options;\r\n options = {};\r\n } else if (!options)\r\n options = {};\r\n\r\n if (!callback)\r\n return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this\r\n\r\n // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found.\r\n if (!options.xhr && fs && fs.readFile)\r\n return fs.readFile(filename, function fetchReadFileCallback(err, contents) {\r\n return err && typeof XMLHttpRequest !== \"undefined\"\r\n ? fetch.xhr(filename, options, callback)\r\n : err\r\n ? callback(err)\r\n : callback(null, options.binary ? contents : contents.toString(\"utf8\"));\r\n });\r\n\r\n // use the XHR version otherwise.\r\n return fetch.xhr(filename, options, callback);\r\n}\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchOptions} [options] Fetch options\r\n * @returns {Promise} Promise\r\n * @variation 3\r\n */\r\n\r\n/**/\r\nfetch.xhr = function fetch_xhr(filename, options, callback) {\r\n var xhr = new XMLHttpRequest();\r\n xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() {\r\n\r\n if (xhr.readyState !== 4)\r\n return undefined;\r\n\r\n // local cors security errors return status 0 / empty string, too. afaik this cannot be\r\n // reliably distinguished from an actually empty file for security reasons. feel free\r\n // to send a pull request if you are aware of a solution.\r\n if (xhr.status !== 0 && xhr.status !== 200)\r\n return callback(Error(\"status \" + xhr.status));\r\n\r\n // if binary data is expected, make sure that some sort of array is returned, even if\r\n // ArrayBuffers are not supported. the binary string fallback, however, is unsafe.\r\n if (options.binary) {\r\n var buffer = xhr.response;\r\n if (!buffer) {\r\n buffer = [];\r\n for (var i = 0; i < xhr.responseText.length; ++i)\r\n buffer.push(xhr.responseText.charCodeAt(i) & 255);\r\n }\r\n return callback(null, typeof Uint8Array !== \"undefined\" ? new Uint8Array(buffer) : buffer);\r\n }\r\n return callback(null, xhr.responseText);\r\n };\r\n\r\n if (options.binary) {\r\n // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers\r\n if (\"overrideMimeType\" in xhr)\r\n xhr.overrideMimeType(\"text/plain; charset=x-user-defined\");\r\n xhr.responseType = \"arraybuffer\";\r\n }\r\n\r\n xhr.open(\"GET\", filename);\r\n xhr.send();\r\n};\r\n","\"use strict\";\r\n\r\nmodule.exports = factory(factory);\r\n\r\n/**\r\n * Reads / writes floats / doubles from / to buffers.\r\n * @name util.float\r\n * @namespace\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using little endian byte order.\r\n * @name util.float.writeFloatLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using big endian byte order.\r\n * @name util.float.writeFloatBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using little endian byte order.\r\n * @name util.float.readFloatLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using big endian byte order.\r\n * @name util.float.readFloatBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using little endian byte order.\r\n * @name util.float.writeDoubleLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using big endian byte order.\r\n * @name util.float.writeDoubleBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using little endian byte order.\r\n * @name util.float.readDoubleLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using big endian byte order.\r\n * @name util.float.readDoubleBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n// Factory function for the purpose of node-based testing in modified global environments\r\nfunction factory(exports) {\r\n\r\n // float: typed array\r\n if (typeof Float32Array !== \"undefined\") (function() {\r\n\r\n var f32 = new Float32Array([ -0 ]),\r\n f8b = new Uint8Array(f32.buffer),\r\n le = f8b[3] === 128;\r\n\r\n function writeFloat_f32_cpy(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n }\r\n\r\n function writeFloat_f32_rev(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[3];\r\n buf[pos + 1] = f8b[2];\r\n buf[pos + 2] = f8b[1];\r\n buf[pos + 3] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;\r\n\r\n function readFloat_f32_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n function readFloat_f32_rev(buf, pos) {\r\n f8b[3] = buf[pos ];\r\n f8b[2] = buf[pos + 1];\r\n f8b[1] = buf[pos + 2];\r\n f8b[0] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;\r\n\r\n // float: ieee754\r\n })(); else (function() {\r\n\r\n function writeFloat_ieee754(writeUint, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0)\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);\r\n else if (isNaN(val))\r\n writeUint(2143289344, buf, pos);\r\n else if (val > 3.4028234663852886e+38) // +-Infinity\r\n writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);\r\n else if (val < 1.1754943508222875e-38) // denormal\r\n writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);\r\n else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2),\r\n mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;\r\n writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);\r\n }\r\n }\r\n\r\n exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);\r\n exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);\r\n\r\n function readFloat_ieee754(readUint, buf, pos) {\r\n var uint = readUint(buf, pos),\r\n sign = (uint >> 31) * 2 + 1,\r\n exponent = uint >>> 23 & 255,\r\n mantissa = uint & 8388607;\r\n return exponent === 255\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 1.401298464324817e-45 * mantissa\r\n : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);\r\n }\r\n\r\n exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);\r\n exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);\r\n\r\n })();\r\n\r\n // double: typed array\r\n if (typeof Float64Array !== \"undefined\") (function() {\r\n\r\n var f64 = new Float64Array([-0]),\r\n f8b = new Uint8Array(f64.buffer),\r\n le = f8b[7] === 128;\r\n\r\n function writeDouble_f64_cpy(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n buf[pos + 4] = f8b[4];\r\n buf[pos + 5] = f8b[5];\r\n buf[pos + 6] = f8b[6];\r\n buf[pos + 7] = f8b[7];\r\n }\r\n\r\n function writeDouble_f64_rev(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[7];\r\n buf[pos + 1] = f8b[6];\r\n buf[pos + 2] = f8b[5];\r\n buf[pos + 3] = f8b[4];\r\n buf[pos + 4] = f8b[3];\r\n buf[pos + 5] = f8b[2];\r\n buf[pos + 6] = f8b[1];\r\n buf[pos + 7] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;\r\n\r\n function readDouble_f64_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n f8b[4] = buf[pos + 4];\r\n f8b[5] = buf[pos + 5];\r\n f8b[6] = buf[pos + 6];\r\n f8b[7] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n function readDouble_f64_rev(buf, pos) {\r\n f8b[7] = buf[pos ];\r\n f8b[6] = buf[pos + 1];\r\n f8b[5] = buf[pos + 2];\r\n f8b[4] = buf[pos + 3];\r\n f8b[3] = buf[pos + 4];\r\n f8b[2] = buf[pos + 5];\r\n f8b[1] = buf[pos + 6];\r\n f8b[0] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;\r\n\r\n // double: ieee754\r\n })(); else (function() {\r\n\r\n function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);\r\n } else if (isNaN(val)) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(2146959360, buf, pos + off1);\r\n } else if (val > 1.7976931348623157e+308) { // +-Infinity\r\n writeUint(0, buf, pos + off0);\r\n writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);\r\n } else {\r\n var mantissa;\r\n if (val < 2.2250738585072014e-308) { // denormal\r\n mantissa = val / 5e-324;\r\n writeUint(mantissa >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);\r\n } else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2);\r\n if (exponent === 1024)\r\n exponent = 1023;\r\n mantissa = val * Math.pow(2, -exponent);\r\n writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);\r\n }\r\n }\r\n }\r\n\r\n exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);\r\n exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);\r\n\r\n function readDouble_ieee754(readUint, off0, off1, buf, pos) {\r\n var lo = readUint(buf, pos + off0),\r\n hi = readUint(buf, pos + off1);\r\n var sign = (hi >> 31) * 2 + 1,\r\n exponent = hi >>> 20 & 2047,\r\n mantissa = 4294967296 * (hi & 1048575) + lo;\r\n return exponent === 2047\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 5e-324 * mantissa\r\n : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);\r\n }\r\n\r\n exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);\r\n exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);\r\n\r\n })();\r\n\r\n return exports;\r\n}\r\n\r\n// uint helpers\r\n\r\nfunction writeUintLE(val, buf, pos) {\r\n buf[pos ] = val & 255;\r\n buf[pos + 1] = val >>> 8 & 255;\r\n buf[pos + 2] = val >>> 16 & 255;\r\n buf[pos + 3] = val >>> 24;\r\n}\r\n\r\nfunction writeUintBE(val, buf, pos) {\r\n buf[pos ] = val >>> 24;\r\n buf[pos + 1] = val >>> 16 & 255;\r\n buf[pos + 2] = val >>> 8 & 255;\r\n buf[pos + 3] = val & 255;\r\n}\r\n\r\nfunction readUintLE(buf, pos) {\r\n return (buf[pos ]\r\n | buf[pos + 1] << 8\r\n | buf[pos + 2] << 16\r\n | buf[pos + 3] << 24) >>> 0;\r\n}\r\n\r\nfunction readUintBE(buf, pos) {\r\n return (buf[pos ] << 24\r\n | buf[pos + 1] << 16\r\n | buf[pos + 2] << 8\r\n | buf[pos + 3]) >>> 0;\r\n}\r\n","\"use strict\";\r\nmodule.exports = inquire;\r\n\r\n/**\r\n * Requires a module only if available.\r\n * @memberof util\r\n * @param {string} moduleName Module to require\r\n * @returns {?Object} Required module if available and not empty, otherwise `null`\r\n */\r\nfunction inquire(moduleName) {\r\n try {\r\n var mod = eval(\"quire\".replace(/^/,\"re\"))(moduleName); // eslint-disable-line no-eval\r\n if (mod && (mod.length || Object.keys(mod).length))\r\n return mod;\r\n } catch (e) {} // eslint-disable-line no-empty\r\n return null;\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal path module to resolve Unix, Windows and URL paths alike.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar path = exports;\r\n\r\nvar isAbsolute =\r\n/**\r\n * Tests if the specified path is absolute.\r\n * @param {string} path Path to test\r\n * @returns {boolean} `true` if path is absolute\r\n */\r\npath.isAbsolute = function isAbsolute(path) {\r\n return /^(?:\\/|\\w+:)/.test(path);\r\n};\r\n\r\nvar normalize =\r\n/**\r\n * Normalizes the specified path.\r\n * @param {string} path Path to normalize\r\n * @returns {string} Normalized path\r\n */\r\npath.normalize = function normalize(path) {\r\n path = path.replace(/\\\\/g, \"/\")\r\n .replace(/\\/{2,}/g, \"/\");\r\n var parts = path.split(\"/\"),\r\n absolute = isAbsolute(path),\r\n prefix = \"\";\r\n if (absolute)\r\n prefix = parts.shift() + \"/\";\r\n for (var i = 0; i < parts.length;) {\r\n if (parts[i] === \"..\") {\r\n if (i > 0 && parts[i - 1] !== \"..\")\r\n parts.splice(--i, 2);\r\n else if (absolute)\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n } else if (parts[i] === \".\")\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n return prefix + parts.join(\"/\");\r\n};\r\n\r\n/**\r\n * Resolves the specified include path against the specified origin path.\r\n * @param {string} originPath Path to the origin file\r\n * @param {string} includePath Include path relative to origin path\r\n * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized\r\n * @returns {string} Path to the include file\r\n */\r\npath.resolve = function resolve(originPath, includePath, alreadyNormalized) {\r\n if (!alreadyNormalized)\r\n includePath = normalize(includePath);\r\n if (isAbsolute(includePath))\r\n return includePath;\r\n if (!alreadyNormalized)\r\n originPath = normalize(originPath);\r\n return (originPath = originPath.replace(/(?:\\/|^)[^/]+$/, \"\")).length ? normalize(originPath + \"/\" + includePath) : includePath;\r\n};\r\n","\"use strict\";\r\nmodule.exports = pool;\r\n\r\n/**\r\n * An allocator as used by {@link util.pool}.\r\n * @typedef PoolAllocator\r\n * @type {function}\r\n * @param {number} size Buffer size\r\n * @returns {Uint8Array} Buffer\r\n */\r\n\r\n/**\r\n * A slicer as used by {@link util.pool}.\r\n * @typedef PoolSlicer\r\n * @type {function}\r\n * @param {number} start Start offset\r\n * @param {number} end End offset\r\n * @returns {Uint8Array} Buffer slice\r\n * @this {Uint8Array}\r\n */\r\n\r\n/**\r\n * A general purpose buffer pool.\r\n * @memberof util\r\n * @function\r\n * @param {PoolAllocator} alloc Allocator\r\n * @param {PoolSlicer} slice Slicer\r\n * @param {number} [size=8192] Slab size\r\n * @returns {PoolAllocator} Pooled allocator\r\n */\r\nfunction pool(alloc, slice, size) {\r\n var SIZE = size || 8192;\r\n var MAX = SIZE >>> 1;\r\n var slab = null;\r\n var offset = SIZE;\r\n return function pool_alloc(size) {\r\n if (size < 1 || size > MAX)\r\n return alloc(size);\r\n if (offset + size > SIZE) {\r\n slab = alloc(SIZE);\r\n offset = 0;\r\n }\r\n var buf = slice.call(slab, offset, offset += size);\r\n if (offset & 7) // align to 32 bit\r\n offset = (offset | 7) + 1;\r\n return buf;\r\n };\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal UTF8 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar utf8 = exports;\r\n\r\n/**\r\n * Calculates the UTF8 byte length of a string.\r\n * @param {string} string String\r\n * @returns {number} Byte length\r\n */\r\nutf8.length = function utf8_length(string) {\r\n var len = 0,\r\n c = 0;\r\n for (var i = 0; i < string.length; ++i) {\r\n c = string.charCodeAt(i);\r\n if (c < 128)\r\n len += 1;\r\n else if (c < 2048)\r\n len += 2;\r\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\r\n ++i;\r\n len += 4;\r\n } else\r\n len += 3;\r\n }\r\n return len;\r\n};\r\n\r\n/**\r\n * Reads UTF8 bytes as a string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} String read\r\n */\r\nutf8.read = function utf8_read(buffer, start, end) {\r\n var len = end - start;\r\n if (len < 1)\r\n return \"\";\r\n var parts = null,\r\n chunk = [],\r\n i = 0, // char offset\r\n t; // temporary\r\n while (start < end) {\r\n t = buffer[start++];\r\n if (t < 128)\r\n chunk[i++] = t;\r\n else if (t > 191 && t < 224)\r\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\r\n else if (t > 239 && t < 365) {\r\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\r\n chunk[i++] = 0xD800 + (t >> 10);\r\n chunk[i++] = 0xDC00 + (t & 1023);\r\n } else\r\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\n/**\r\n * Writes a string as UTF8 bytes.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Bytes written\r\n */\r\nutf8.write = function utf8_write(string, buffer, offset) {\r\n var start = offset,\r\n c1, // character 1\r\n c2; // character 2\r\n for (var i = 0; i < string.length; ++i) {\r\n c1 = string.charCodeAt(i);\r\n if (c1 < 128) {\r\n buffer[offset++] = c1;\r\n } else if (c1 < 2048) {\r\n buffer[offset++] = c1 >> 6 | 192;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\r\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\r\n ++i;\r\n buffer[offset++] = c1 >> 18 | 240;\r\n buffer[offset++] = c1 >> 12 & 63 | 128;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else {\r\n buffer[offset++] = c1 >> 12 | 224;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n }\r\n }\r\n return offset - start;\r\n};\r\n","\"use strict\";\n/**\n * Runtime message from/to plain object converters.\n * @namespace\n */\nvar converter = exports;\n\nvar Enum = require(14),\n util = require(33);\n\n/**\n * Generates a partial value fromObject conveter.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {number} fieldIndex Field index\n * @param {string} prop Property reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genValuePartial_fromObject(gen, field, fieldIndex, prop) {\n var defaultAlreadyEmitted = false;\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n if (field.resolvedType) {\n if (field.resolvedType instanceof Enum) { gen\n (\"switch(d%s){\", prop);\n for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {\n // enum unknown values passthrough\n if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen\n (\"default:\")\n (\"if(typeof(d%s)===\\\"number\\\"){m%s=d%s;break}\", prop, prop, prop);\n if (!field.repeated) gen // fallback to default value only for\n // arrays, to avoid leaving holes.\n (\"break\"); // for non-repeated fields, just ignore\n defaultAlreadyEmitted = true;\n }\n gen\n (\"case%j:\", keys[i])\n (\"case %i:\", values[keys[i]])\n (\"m%s=%j\", prop, values[keys[i]])\n (\"break\");\n } gen\n (\"}\");\n } else gen\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\n (\"m%s=types[%i].fromObject(d%s)\", prop, fieldIndex, prop);\n } else {\n var isUnsigned = false;\n switch (field.type) {\n case \"double\":\n case \"float\": gen\n (\"m%s=Number(d%s)\", prop, prop); // also catches \"NaN\", \"Infinity\"\n break;\n case \"uint32\":\n case \"fixed32\": gen\n (\"m%s=d%s>>>0\", prop, prop);\n break;\n case \"int32\":\n case \"sint32\":\n case \"sfixed32\": gen\n (\"m%s=d%s|0\", prop, prop);\n break;\n case \"uint64\":\n isUnsigned = true;\n // eslint-disable-next-line no-fallthrough\n case \"int64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(util.Long)\")\n (\"(m%s=util.Long.fromValue(d%s)).unsigned=%j\", prop, prop, isUnsigned)\n (\"else if(typeof d%s===\\\"string\\\")\", prop)\n (\"m%s=parseInt(d%s,10)\", prop, prop)\n (\"else if(typeof d%s===\\\"number\\\")\", prop)\n (\"m%s=d%s\", prop, prop)\n (\"else if(typeof d%s===\\\"object\\\")\", prop)\n (\"m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)\", prop, prop, prop, isUnsigned ? \"true\" : \"\");\n break;\n case \"bytes\": gen\n (\"if(typeof d%s===\\\"string\\\")\", prop)\n (\"util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)\", prop, prop, prop)\n (\"else if(d%s.length >= 0)\", prop)\n (\"m%s=d%s\", prop, prop);\n break;\n case \"string\": gen\n (\"m%s=String(d%s)\", prop, prop);\n break;\n case \"bool\": gen\n (\"m%s=Boolean(d%s)\", prop, prop);\n break;\n /* default: gen\n (\"m%s=d%s\", prop, prop);\n break; */\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n\n/**\n * Generates a plain object to runtime message converter specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nconverter.fromObject = function fromObject(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var fields = mtype.fieldsArray;\n var gen = util.codegen([\"d\"], mtype.name + \"$fromObject\")\n (\"if(d instanceof this.ctor)\")\n (\"return d\");\n if (!fields.length) return gen\n (\"return new this.ctor\");\n gen\n (\"var m=new this.ctor\");\n for (var i = 0; i < fields.length; ++i) {\n var field = fields[i].resolve(),\n prop = util.safeProp(field.name);\n\n // Map fields\n if (field.map) { gen\n (\"if(d%s){\", prop)\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\n (\"m%s={}\", prop)\n (\"for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s\", prop, prop, prop, prop, isUnsigned ? \"true\": \"\", prop);\n break;\n case \"bytes\": gen\n (\"d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s\", prop, prop, prop, prop, prop);\n break;\n default: gen\n (\"d%s=m%s\", prop, prop);\n break;\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n\n/**\n * Generates a runtime message to plain object converter specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nconverter.toObject = function toObject(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById);\n if (!fields.length)\n return util.codegen()(\"return {}\");\n var gen = util.codegen([\"m\", \"o\"], mtype.name + \"$toObject\")\n (\"if(!o)\")\n (\"o={}\")\n (\"var d={}\");\n\n var repeatedFields = [],\n mapFields = [],\n normalFields = [],\n i = 0;\n for (; i < fields.length; ++i)\n if (!fields[i].partOf)\n ( fields[i].resolve().repeated ? repeatedFields\n : fields[i].map ? mapFields\n : normalFields).push(fields[i]);\n\n if (repeatedFields.length) { gen\n (\"if(o.arrays||o.defaults){\");\n for (i = 0; i < repeatedFields.length; ++i) gen\n (\"d%s=[]\", util.safeProp(repeatedFields[i].name));\n gen\n (\"}\");\n }\n\n if (mapFields.length) { gen\n (\"if(o.objects||o.defaults){\");\n for (i = 0; i < mapFields.length; ++i) gen\n (\"d%s={}\", util.safeProp(mapFields[i].name));\n gen\n (\"}\");\n }\n\n if (normalFields.length) { gen\n (\"if(o.defaults){\");\n for (i = 0; i < normalFields.length; ++i) {\n var field = normalFields[i],\n prop = util.safeProp(field.name);\n if (field.resolvedType instanceof Enum) gen\n (\"d%s=o.enums===String?%j:%j\", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault);\n else if (field.long) gen\n (\"if(util.Long){\")\n (\"var n=new util.Long(%i,%i,%j)\", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)\n (\"d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n\", prop)\n (\"}else\")\n (\"d%s=o.longs===String?%j:%i\", prop, field.typeDefault.toString(), field.typeDefault.toNumber());\n else if (field.bytes) {\n var arrayDefault = \"[\" + Array.prototype.slice.call(field.typeDefault).join(\",\") + \"]\";\n gen\n (\"if(o.bytes===String)d%s=%j\", prop, String.fromCharCode.apply(String, field.typeDefault))\n (\"else{\")\n (\"d%s=%s\", prop, arrayDefault)\n (\"if(o.bytes!==Array)d%s=util.newBuffer(d%s)\", prop, prop)\n (\"}\");\n } else gen\n (\"d%s=%j\", prop, field.typeDefault); // also messages (=null)\n } gen\n (\"}\");\n }\n var hasKs2 = false;\n for (i = 0; i < fields.length; ++i) {\n var field = fields[i],\n index = mtype._fieldsArray.indexOf(field),\n prop = util.safeProp(field.name);\n if (field.map) {\n if (!hasKs2) { hasKs2 = true; gen\n (\"var ks2\");\n } gen\n (\"if(m%s&&(ks2=Object.keys(m%s)).length){\", prop, prop)\n (\"d%s={}\", prop)\n (\"for(var j=0;j>>3){\");\n\n var i = 0;\n for (; i < /* initializes */ mtype.fieldsArray.length; ++i) {\n var field = mtype._fieldsArray[i].resolve(),\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\n ref = \"m\" + util.safeProp(field.name); gen\n (\"case %i: {\", field.id);\n\n // Map fields\n if (field.map) { gen\n (\"if(%s===util.emptyObject)\", ref)\n (\"%s={}\", ref)\n (\"var c2 = r.uint32()+r.pos\");\n\n if (types.defaults[field.keyType] !== undefined) gen\n (\"k=%j\", types.defaults[field.keyType]);\n else gen\n (\"k=null\");\n\n if (types.defaults[type] !== undefined) gen\n (\"value=%j\", types.defaults[type]);\n else gen\n (\"value=null\");\n\n gen\n (\"while(r.pos>>3){\")\n (\"case 1: k=r.%s(); break\", field.keyType)\n (\"case 2:\");\n\n if (types.basic[type] === undefined) gen\n (\"value=types[%i].decode(r,r.uint32())\", i); // can't be groups\n else gen\n (\"value=r.%s()\", type);\n\n gen\n (\"break\")\n (\"default:\")\n (\"r.skipType(tag2&7)\")\n (\"break\")\n (\"}\")\n (\"}\");\n\n if (types.long[field.keyType] !== undefined) gen\n (\"%s[typeof k===\\\"object\\\"?util.longToHash(k):k]=value\", ref);\n else gen\n (\"%s[k]=value\", ref);\n\n // Repeated fields\n } else if (field.repeated) { gen\n\n (\"if(!(%s&&%s.length))\", ref, ref)\n (\"%s=[]\", ref);\n\n // Packable (always check for forward and backward compatiblity)\n if (types.packed[type] !== undefined) gen\n (\"if((t&7)===2){\")\n (\"var c2=r.uint32()+r.pos\")\n (\"while(r.pos>> 0, (field.id << 3 | 4) >>> 0)\n : gen(\"types[%i].encode(%s,w.uint32(%i).fork()).ldelim()\", fieldIndex, ref, (field.id << 3 | 2) >>> 0);\n}\n\n/**\n * Generates an encoder specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nfunction encoder(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var gen = util.codegen([\"m\", \"w\"], mtype.name + \"$encode\")\n (\"if(!w)\")\n (\"w=Writer.create()\");\n\n var i, ref;\n\n // \"when a message is serialized its known fields should be written sequentially by field number\"\n var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById);\n\n for (var i = 0; i < fields.length; ++i) {\n var field = fields[i].resolve(),\n index = mtype._fieldsArray.indexOf(field),\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\n wireType = types.basic[type];\n ref = \"m\" + util.safeProp(field.name);\n\n // Map fields\n if (field.map) {\n gen\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j)){\", ref, field.name) // !== undefined && !== null\n (\"for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType);\n if (wireType === undefined) gen\n (\"types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()\", index, ref); // can't be groups\n else gen\n (\".uint32(%i).%s(%s[ks[i]]).ldelim()\", 16 | wireType, type, ref);\n gen\n (\"}\")\n (\"}\");\n\n // Repeated fields\n } else if (field.repeated) { gen\n (\"if(%s!=null&&%s.length){\", ref, ref); // !== undefined && !== null\n\n // Packed repeated\n if (field.packed && types.packed[type] !== undefined) { gen\n\n (\"w.uint32(%i).fork()\", (field.id << 3 | 2) >>> 0)\n (\"for(var i=0;i<%s.length;++i)\", ref)\n (\"w.%s(%s[i])\", type, ref)\n (\"w.ldelim()\");\n\n // Non-packed\n } else { gen\n\n (\"for(var i=0;i<%s.length;++i)\", ref);\n if (wireType === undefined)\n genTypePartial(gen, field, index, ref + \"[i]\");\n else gen\n (\"w.uint32(%i).%s(%s[i])\", (field.id << 3 | wireType) >>> 0, type, ref);\n\n } gen\n (\"}\");\n\n // Non-repeated\n } else {\n if (field.optional) gen\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j))\", ref, field.name); // !== undefined && !== null\n\n if (wireType === undefined)\n genTypePartial(gen, field, index, ref);\n else gen\n (\"w.uint32(%i).%s(%s)\", (field.id << 3 | wireType) >>> 0, type, ref);\n\n }\n }\n\n return gen\n (\"return w\");\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n","\"use strict\";\nmodule.exports = Enum;\n\n// extends ReflectionObject\nvar ReflectionObject = require(22);\n((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = \"Enum\";\n\nvar Namespace = require(21),\n util = require(33);\n\n/**\n * Constructs a new enum instance.\n * @classdesc Reflected enum.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {Object.} [values] Enum values as an object, by name\n * @param {Object.} [options] Declared options\n * @param {string} [comment] The comment for this enum\n * @param {Object.} [comments] The value comments for this enum\n * @param {Object.>|undefined} [valuesOptions] The value options for this enum\n */\nfunction Enum(name, values, options, comment, comments, valuesOptions) {\n ReflectionObject.call(this, name, options);\n\n if (values && typeof values !== \"object\")\n throw TypeError(\"values must be an object\");\n\n /**\n * Enum values by id.\n * @type {Object.}\n */\n this.valuesById = {};\n\n /**\n * Enum values by name.\n * @type {Object.}\n */\n this.values = Object.create(this.valuesById); // toJSON, marker\n\n /**\n * Enum comment text.\n * @type {string|null}\n */\n this.comment = comment;\n\n /**\n * Value comment texts, if any.\n * @type {Object.}\n */\n this.comments = comments || {};\n\n /**\n * Values options, if any\n * @type {Object>|undefined}\n */\n this.valuesOptions = valuesOptions;\n\n /**\n * Resolved values features, if any\n * @type {Object>|undefined}\n */\n this._valuesFeatures = {};\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n // Note that values inherit valuesById on their prototype which makes them a TypeScript-\n // compatible enum. This is used by pbts to write actual enum definitions that work for\n // static and reflection code alike instead of emitting generic object definitions.\n\n if (values)\n for (var keys = Object.keys(values), i = 0; i < keys.length; ++i)\n if (typeof values[keys[i]] === \"number\") // use forward entries only\n this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i];\n}\n\n/**\n * @override\n */\nEnum.prototype._resolveFeatures = function _resolveFeatures(edition) {\n edition = this._edition || edition;\n ReflectionObject.prototype._resolveFeatures.call(this, edition);\n\n Object.keys(this.values).forEach(key => {\n var parentFeaturesCopy = Object.assign({}, this._features);\n this._valuesFeatures[key] = Object.assign(parentFeaturesCopy, this.valuesOptions && this.valuesOptions[key] && this.valuesOptions[key].features);\n });\n\n return this;\n};\n\n/**\n * Enum descriptor.\n * @interface IEnum\n * @property {Object.} values Enum values\n * @property {Object.} [options] Enum options\n */\n\n/**\n * Constructs an enum from an enum descriptor.\n * @param {string} name Enum name\n * @param {IEnum} json Enum descriptor\n * @returns {Enum} Created enum\n * @throws {TypeError} If arguments are invalid\n */\nEnum.fromJSON = function fromJSON(name, json) {\n var enm = new Enum(name, json.values, json.options, json.comment, json.comments);\n enm.reserved = json.reserved;\n if (json.edition)\n enm._edition = json.edition;\n enm._defaultEdition = \"proto3\"; // For backwards-compatibility.\n return enm;\n};\n\n/**\n * Converts this enum to an enum descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IEnum} Enum descriptor\n */\nEnum.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"edition\" , this._editionToJSON(),\n \"options\" , this.options,\n \"valuesOptions\" , this.valuesOptions,\n \"values\" , this.values,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"comment\" , keepComments ? this.comment : undefined,\n \"comments\" , keepComments ? this.comments : undefined\n ]);\n};\n\n/**\n * Adds a value to this enum.\n * @param {string} name Value name\n * @param {number} id Value id\n * @param {string} [comment] Comment, if any\n * @param {Object.|undefined} [options] Options, if any\n * @returns {Enum} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a value with this name or id\n */\nEnum.prototype.add = function add(name, id, comment, options) {\n // utilized by the parser but not by .fromJSON\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n if (!util.isInteger(id))\n throw TypeError(\"id must be an integer\");\n\n if (this.values[name] !== undefined)\n throw Error(\"duplicate name '\" + name + \"' in \" + this);\n\n if (this.isReservedId(id))\n throw Error(\"id \" + id + \" is reserved in \" + this);\n\n if (this.isReservedName(name))\n throw Error(\"name '\" + name + \"' is reserved in \" + this);\n\n if (this.valuesById[id] !== undefined) {\n if (!(this.options && this.options.allow_alias))\n throw Error(\"duplicate id \" + id + \" in \" + this);\n this.values[name] = id;\n } else\n this.valuesById[this.values[name] = id] = name;\n\n if (options) {\n if (this.valuesOptions === undefined)\n this.valuesOptions = {};\n this.valuesOptions[name] = options || null;\n }\n\n this.comments[name] = comment || null;\n return this;\n};\n\n/**\n * Removes a value from this enum\n * @param {string} name Value name\n * @returns {Enum} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `name` is not a name of this enum\n */\nEnum.prototype.remove = function remove(name) {\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n var val = this.values[name];\n if (val == null)\n throw Error(\"name '\" + name + \"' does not exist in \" + this);\n\n delete this.valuesById[val];\n delete this.values[name];\n delete this.comments[name];\n if (this.valuesOptions)\n delete this.valuesOptions[name];\n\n return this;\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nEnum.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nEnum.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n","\"use strict\";\nmodule.exports = Field;\n\n// extends ReflectionObject\nvar ReflectionObject = require(22);\n((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = \"Field\";\n\nvar Enum = require(14),\n types = require(32),\n util = require(33);\n\nvar Type; // cyclic\n\nvar ruleRe = /^required|optional|repeated$/;\n\n/**\n * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class.\n * @name Field\n * @classdesc Reflected message field.\n * @extends FieldBase\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} type Value type\n * @param {string|Object.} [rule=\"optional\"] Field rule\n * @param {string|Object.} [extend] Extended type if different from parent\n * @param {Object.} [options] Declared options\n */\n\n/**\n * Constructs a field from a field descriptor.\n * @param {string} name Field name\n * @param {IField} json Field descriptor\n * @returns {Field} Created field\n * @throws {TypeError} If arguments are invalid\n */\nField.fromJSON = function fromJSON(name, json) {\n var field = new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment);\n if (json.edition)\n field._edition = json.edition;\n field._defaultEdition = \"proto3\"; // For backwards-compatibility.\n return field;\n};\n\n/**\n * Not an actual constructor. Use {@link Field} instead.\n * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions.\n * @exports FieldBase\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} type Value type\n * @param {string|Object.} [rule=\"optional\"] Field rule\n * @param {string|Object.} [extend] Extended type if different from parent\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction Field(name, id, type, rule, extend, options, comment) {\n\n if (util.isObject(rule)) {\n comment = extend;\n options = rule;\n rule = extend = undefined;\n } else if (util.isObject(extend)) {\n comment = options;\n options = extend;\n extend = undefined;\n }\n\n ReflectionObject.call(this, name, options);\n\n if (!util.isInteger(id) || id < 0)\n throw TypeError(\"id must be a non-negative integer\");\n\n if (!util.isString(type))\n throw TypeError(\"type must be a string\");\n\n if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase()))\n throw TypeError(\"rule must be a string rule\");\n\n if (extend !== undefined && !util.isString(extend))\n throw TypeError(\"extend must be a string\");\n\n /**\n * Field rule, if any.\n * @type {string|undefined}\n */\n if (rule === \"proto3_optional\") {\n rule = \"optional\";\n }\n this.rule = rule && rule !== \"optional\" ? rule : undefined; // toJSON\n\n /**\n * Field type.\n * @type {string}\n */\n this.type = type; // toJSON\n\n /**\n * Unique field id.\n * @type {number}\n */\n this.id = id; // toJSON, marker\n\n /**\n * Extended type if different from parent.\n * @type {string|undefined}\n */\n this.extend = extend || undefined; // toJSON\n\n /**\n * Whether this field is repeated.\n * @type {boolean}\n */\n this.repeated = rule === \"repeated\";\n\n /**\n * Whether this field is a map or not.\n * @type {boolean}\n */\n this.map = false;\n\n /**\n * Message this field belongs to.\n * @type {Type|null}\n */\n this.message = null;\n\n /**\n * OneOf this field belongs to, if any,\n * @type {OneOf|null}\n */\n this.partOf = null;\n\n /**\n * The field type's default value.\n * @type {*}\n */\n this.typeDefault = null;\n\n /**\n * The field's default value on prototypes.\n * @type {*}\n */\n this.defaultValue = null;\n\n /**\n * Whether this field's value should be treated as a long.\n * @type {boolean}\n */\n this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false;\n\n /**\n * Whether this field's value is a buffer.\n * @type {boolean}\n */\n this.bytes = type === \"bytes\";\n\n /**\n * Resolved type if not a basic type.\n * @type {Type|Enum|null}\n */\n this.resolvedType = null;\n\n /**\n * Sister-field within the extended type if a declaring extension field.\n * @type {Field|null}\n */\n this.extensionField = null;\n\n /**\n * Sister-field within the declaring namespace if an extended field.\n * @type {Field|null}\n */\n this.declaringField = null;\n\n /**\n * Comment for this field.\n * @type {string|null}\n */\n this.comment = comment;\n}\n\n/**\n * Determines whether this field is required.\n * @name Field#required\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"required\", {\n get: function() {\n return this._features.field_presence === \"LEGACY_REQUIRED\";\n }\n});\n\n/**\n * Determines whether this field is not required.\n * @name Field#optional\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"optional\", {\n get: function() {\n return !this.required;\n }\n});\n\n/**\n * Determines whether this field uses tag-delimited encoding. In proto2 this\n * corresponded to group syntax.\n * @name Field#delimited\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"delimited\", {\n get: function() {\n return this.resolvedType instanceof Type &&\n this._features.message_encoding === \"DELIMITED\";\n }\n});\n\n/**\n * Determines whether this field is packed. Only relevant when repeated.\n * @name Field#packed\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"packed\", {\n get: function() {\n return this._features.repeated_field_encoding === \"PACKED\";\n }\n});\n\n/**\n * Determines whether this field tracks presence.\n * @name Field#hasPresence\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"hasPresence\", {\n get: function() {\n if (this.repeated || this.map) {\n return false;\n }\n return this.partOf || // oneofs\n this.declaringField || this.extensionField || // extensions\n this._features.field_presence !== \"IMPLICIT\";\n }\n});\n\n/**\n * @override\n */\nField.prototype.setOption = function setOption(name, value, ifNotSet) {\n return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet);\n};\n\n/**\n * Field descriptor.\n * @interface IField\n * @property {string} [rule=\"optional\"] Field rule\n * @property {string} type Field type\n * @property {number} id Field id\n * @property {Object.} [options] Field options\n */\n\n/**\n * Extension field descriptor.\n * @interface IExtensionField\n * @extends IField\n * @property {string} extend Extended type\n */\n\n/**\n * Converts this field to a field descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IField} Field descriptor\n */\nField.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"edition\" , this._editionToJSON(),\n \"rule\" , this.rule !== \"optional\" && this.rule || undefined,\n \"type\" , this.type,\n \"id\" , this.id,\n \"extend\" , this.extend,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Resolves this field's type references.\n * @returns {Field} `this`\n * @throws {Error} If any reference cannot be resolved\n */\nField.prototype.resolve = function resolve() {\n\n if (this.resolved)\n return this;\n\n if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it\n this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);\n if (this.resolvedType instanceof Type)\n this.typeDefault = null;\n else // instanceof Enum\n this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined\n } else if (this.options && this.options.proto3_optional) {\n // proto3 scalar value marked optional; should default to null\n this.typeDefault = null;\n }\n\n // use explicitly set default value if present\n if (this.options && this.options[\"default\"] != null) {\n this.typeDefault = this.options[\"default\"];\n if (this.resolvedType instanceof Enum && typeof this.typeDefault === \"string\")\n this.typeDefault = this.resolvedType.values[this.typeDefault];\n }\n\n // remove unnecessary options\n if (this.options) {\n if (this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum))\n delete this.options.packed;\n if (!Object.keys(this.options).length)\n this.options = undefined;\n }\n\n // convert to internal data type if necesssary\n if (this.long) {\n this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === \"u\");\n\n /* istanbul ignore else */\n if (Object.freeze)\n Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it)\n\n } else if (this.bytes && typeof this.typeDefault === \"string\") {\n var buf;\n if (util.base64.test(this.typeDefault))\n util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0);\n else\n util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0);\n this.typeDefault = buf;\n }\n\n // take special care of maps and repeated fields\n if (this.map)\n this.defaultValue = util.emptyObject;\n else if (this.repeated)\n this.defaultValue = util.emptyArray;\n else\n this.defaultValue = this.typeDefault;\n\n // ensure proper value on prototype\n if (this.parent instanceof Type)\n this.parent.ctor.prototype[this.name] = this.defaultValue;\n\n return ReflectionObject.prototype.resolve.call(this);\n};\n\n/**\n * Infers field features from legacy syntax that may have been specified differently.\n * in older editions.\n * @param {string|undefined} edition The edition this proto is on, or undefined if pre-editions\n * @returns {object} The feature values to override\n */\nField.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(edition) {\n if (edition !== \"proto2\" && edition !== \"proto3\") {\n return {};\n }\n\n var features = {};\n\n if (this.rule === \"required\") {\n features.field_presence = \"LEGACY_REQUIRED\";\n }\n if (this.parent && types.defaults[this.type] === undefined) {\n // We can't use resolvedType because types may not have been resolved yet. However,\n // legacy groups are always in the same scope as the field so we don't have to do a\n // full scan of the tree.\n var type = this.parent.get(this.type.split(\".\").pop());\n if (type && type instanceof Type && type.group) {\n features.message_encoding = \"DELIMITED\";\n }\n }\n if (this.getOption(\"packed\") === true) {\n features.repeated_field_encoding = \"PACKED\";\n } else if (this.getOption(\"packed\") === false) {\n features.repeated_field_encoding = \"EXPANDED\";\n }\n return features;\n};\n\n/**\n * @override\n */\nField.prototype._resolveFeatures = function _resolveFeatures(edition) {\n return ReflectionObject.prototype._resolveFeatures.call(this, this._edition || edition);\n};\n\n/**\n * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript).\n * @typedef FieldDecorator\n * @type {function}\n * @param {Object} prototype Target prototype\n * @param {string} fieldName Field name\n * @returns {undefined}\n */\n\n/**\n * Field decorator (TypeScript).\n * @name Field.d\n * @function\n * @param {number} fieldId Field id\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"string\"|\"bool\"|\"bytes\"|Object} fieldType Field type\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\n * @param {T} [defaultValue] Default value\n * @returns {FieldDecorator} Decorator function\n * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[]\n */\nField.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) {\n\n // submessage: decorate the submessage and use its name as the type\n if (typeof fieldType === \"function\")\n fieldType = util.decorateType(fieldType).name;\n\n // enum reference: create a reflected copy of the enum and keep reuseing it\n else if (fieldType && typeof fieldType === \"object\")\n fieldType = util.decorateEnum(fieldType).name;\n\n return function fieldDecorator(prototype, fieldName) {\n util.decorateType(prototype.constructor)\n .add(new Field(fieldName, fieldId, fieldType, fieldRule, { \"default\": defaultValue }));\n };\n};\n\n/**\n * Field decorator (TypeScript).\n * @name Field.d\n * @function\n * @param {number} fieldId Field id\n * @param {Constructor|string} fieldType Field type\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\n * @returns {FieldDecorator} Decorator function\n * @template T extends Message\n * @variation 2\n */\n// like Field.d but without a default value\n\n// Sets up cyclic dependencies (called in index-light)\nField._configure = function configure(Type_) {\n Type = Type_;\n};\n","\"use strict\";\nvar protobuf = module.exports = require(17);\n\nprotobuf.build = \"light\";\n\n/**\n * A node-style callback as used by {@link load} and {@link Root#load}.\n * @typedef LoadCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Root} [root] Root, if there hasn't been an error\n * @returns {undefined}\n */\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} root Root namespace, defaults to create a new one if omitted.\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @see {@link Root#load}\n */\nfunction load(filename, root, callback) {\n if (typeof root === \"function\") {\n callback = root;\n root = new protobuf.Root();\n } else if (!root)\n root = new protobuf.Root();\n return root.load(filename, callback);\n}\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\n * @name load\n * @function\n * @param {string|string[]} filename One or multiple files to load\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @see {@link Root#load}\n * @variation 2\n */\n// function load(filename:string, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise.\n * @name load\n * @function\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\n * @returns {Promise} Promise\n * @see {@link Root#load}\n * @variation 3\n */\n// function load(filename:string, [root:Root]):Promise\n\nprotobuf.load = load;\n\n/**\n * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only).\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\n * @returns {Root} Root namespace\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\n * @see {@link Root#loadSync}\n */\nfunction loadSync(filename, root) {\n if (!root)\n root = new protobuf.Root();\n return root.loadSync(filename);\n}\n\nprotobuf.loadSync = loadSync;\n\n// Serialization\nprotobuf.encoder = require(13);\nprotobuf.decoder = require(12);\nprotobuf.verifier = require(36);\nprotobuf.converter = require(11);\n\n// Reflection\nprotobuf.ReflectionObject = require(22);\nprotobuf.Namespace = require(21);\nprotobuf.Root = require(26);\nprotobuf.Enum = require(14);\nprotobuf.Type = require(31);\nprotobuf.Field = require(15);\nprotobuf.OneOf = require(23);\nprotobuf.MapField = require(18);\nprotobuf.Service = require(30);\nprotobuf.Method = require(20);\n\n// Runtime\nprotobuf.Message = require(19);\nprotobuf.wrappers = require(37);\n\n// Utility\nprotobuf.types = require(32);\nprotobuf.util = require(33);\n\n// Set up possibly cyclic reflection dependencies\nprotobuf.ReflectionObject._configure(protobuf.Root);\nprotobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum);\nprotobuf.Root._configure(protobuf.Type);\nprotobuf.Field._configure(protobuf.Type);\n","\"use strict\";\nvar protobuf = exports;\n\n/**\n * Build type, one of `\"full\"`, `\"light\"` or `\"minimal\"`.\n * @name build\n * @type {string}\n * @const\n */\nprotobuf.build = \"minimal\";\n\n// Serialization\nprotobuf.Writer = require(38);\nprotobuf.BufferWriter = require(39);\nprotobuf.Reader = require(24);\nprotobuf.BufferReader = require(25);\n\n// Utility\nprotobuf.util = require(35);\nprotobuf.rpc = require(28);\nprotobuf.roots = require(27);\nprotobuf.configure = configure;\n\n/* istanbul ignore next */\n/**\n * Reconfigures the library according to the environment.\n * @returns {undefined}\n */\nfunction configure() {\n protobuf.util._configure();\n protobuf.Writer._configure(protobuf.BufferWriter);\n protobuf.Reader._configure(protobuf.BufferReader);\n}\n\n// Set up buffer utility according to the environment\nconfigure();\n","\"use strict\";\nmodule.exports = MapField;\n\n// extends Field\nvar Field = require(15);\n((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = \"MapField\";\n\nvar types = require(32),\n util = require(33);\n\n/**\n * Constructs a new map field instance.\n * @classdesc Reflected map field.\n * @extends FieldBase\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} keyType Key type\n * @param {string} type Value type\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction MapField(name, id, keyType, type, options, comment) {\n Field.call(this, name, id, type, undefined, undefined, options, comment);\n\n /* istanbul ignore if */\n if (!util.isString(keyType))\n throw TypeError(\"keyType must be a string\");\n\n /**\n * Key type.\n * @type {string}\n */\n this.keyType = keyType; // toJSON, marker\n\n /**\n * Resolved key type if not a basic type.\n * @type {ReflectionObject|null}\n */\n this.resolvedKeyType = null;\n\n // Overrides Field#map\n this.map = true;\n}\n\n/**\n * Map field descriptor.\n * @interface IMapField\n * @extends {IField}\n * @property {string} keyType Key type\n */\n\n/**\n * Extension map field descriptor.\n * @interface IExtensionMapField\n * @extends IMapField\n * @property {string} extend Extended type\n */\n\n/**\n * Constructs a map field from a map field descriptor.\n * @param {string} name Field name\n * @param {IMapField} json Map field descriptor\n * @returns {MapField} Created map field\n * @throws {TypeError} If arguments are invalid\n */\nMapField.fromJSON = function fromJSON(name, json) {\n return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment);\n};\n\n/**\n * Converts this map field to a map field descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IMapField} Map field descriptor\n */\nMapField.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"keyType\" , this.keyType,\n \"type\" , this.type,\n \"id\" , this.id,\n \"extend\" , this.extend,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nMapField.prototype.resolve = function resolve() {\n if (this.resolved)\n return this;\n\n // Besides a value type, map fields have a key type that may be \"any scalar type except for floating point types and bytes\"\n if (types.mapKey[this.keyType] === undefined)\n throw Error(\"invalid key type: \" + this.keyType);\n\n return Field.prototype.resolve.call(this);\n};\n\n/**\n * Map field decorator (TypeScript).\n * @name MapField.d\n * @function\n * @param {number} fieldId Field id\n * @param {\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"} fieldKeyType Field key type\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"|\"bytes\"|Object|Constructor<{}>} fieldValueType Field value type\n * @returns {FieldDecorator} Decorator function\n * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> }\n */\nMapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) {\n\n // submessage value: decorate the submessage and use its name as the type\n if (typeof fieldValueType === \"function\")\n fieldValueType = util.decorateType(fieldValueType).name;\n\n // enum reference value: create a reflected copy of the enum and keep reuseing it\n else if (fieldValueType && typeof fieldValueType === \"object\")\n fieldValueType = util.decorateEnum(fieldValueType).name;\n\n return function mapFieldDecorator(prototype, fieldName) {\n util.decorateType(prototype.constructor)\n .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType));\n };\n};\n","\"use strict\";\nmodule.exports = Message;\n\nvar util = require(35);\n\n/**\n * Constructs a new message instance.\n * @classdesc Abstract runtime message.\n * @constructor\n * @param {Properties} [properties] Properties to set\n * @template T extends object = object\n */\nfunction Message(properties) {\n // not used internally\n if (properties)\n for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)\n this[keys[i]] = properties[keys[i]];\n}\n\n/**\n * Reference to the reflected type.\n * @name Message.$type\n * @type {Type}\n * @readonly\n */\n\n/**\n * Reference to the reflected type.\n * @name Message#$type\n * @type {Type}\n * @readonly\n */\n\n/*eslint-disable valid-jsdoc*/\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message} Message instance\n * @template T extends Message\n * @this Constructor\n */\nMessage.create = function create(properties) {\n return this.$type.create(properties);\n};\n\n/**\n * Encodes a message of this type.\n * @param {T|Object.} message Message to encode\n * @param {Writer} [writer] Writer to use\n * @returns {Writer} Writer\n * @template T extends Message\n * @this Constructor\n */\nMessage.encode = function encode(message, writer) {\n return this.$type.encode(message, writer);\n};\n\n/**\n * Encodes a message of this type preceeded by its length as a varint.\n * @param {T|Object.} message Message to encode\n * @param {Writer} [writer] Writer to use\n * @returns {Writer} Writer\n * @template T extends Message\n * @this Constructor\n */\nMessage.encodeDelimited = function encodeDelimited(message, writer) {\n return this.$type.encodeDelimited(message, writer);\n};\n\n/**\n * Decodes a message of this type.\n * @name Message.decode\n * @function\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\n * @returns {T} Decoded message\n * @template T extends Message\n * @this Constructor\n */\nMessage.decode = function decode(reader) {\n return this.$type.decode(reader);\n};\n\n/**\n * Decodes a message of this type preceeded by its length as a varint.\n * @name Message.decodeDelimited\n * @function\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\n * @returns {T} Decoded message\n * @template T extends Message\n * @this Constructor\n */\nMessage.decodeDelimited = function decodeDelimited(reader) {\n return this.$type.decodeDelimited(reader);\n};\n\n/**\n * Verifies a message of this type.\n * @name Message.verify\n * @function\n * @param {Object.} message Plain object to verify\n * @returns {string|null} `null` if valid, otherwise the reason why it is not\n */\nMessage.verify = function verify(message) {\n return this.$type.verify(message);\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object\n * @returns {T} Message instance\n * @template T extends Message\n * @this Constructor\n */\nMessage.fromObject = function fromObject(object) {\n return this.$type.fromObject(object);\n};\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {T} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n * @template T extends Message\n * @this Constructor\n */\nMessage.toObject = function toObject(message, options) {\n return this.$type.toObject(message, options);\n};\n\n/**\n * Converts this message to JSON.\n * @returns {Object.} JSON object\n */\nMessage.prototype.toJSON = function toJSON() {\n return this.$type.toObject(this, util.toJSONOptions);\n};\n\n/*eslint-enable valid-jsdoc*/","\"use strict\";\nmodule.exports = Method;\n\n// extends ReflectionObject\nvar ReflectionObject = require(22);\n((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = \"Method\";\n\nvar util = require(33);\n\n/**\n * Constructs a new service method instance.\n * @classdesc Reflected service method.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Method name\n * @param {string|undefined} type Method type, usually `\"rpc\"`\n * @param {string} requestType Request message type\n * @param {string} responseType Response message type\n * @param {boolean|Object.} [requestStream] Whether the request is streamed\n * @param {boolean|Object.} [responseStream] Whether the response is streamed\n * @param {Object.} [options] Declared options\n * @param {string} [comment] The comment for this method\n * @param {Object.} [parsedOptions] Declared options, properly parsed into an object\n */\nfunction Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) {\n\n /* istanbul ignore next */\n if (util.isObject(requestStream)) {\n options = requestStream;\n requestStream = responseStream = undefined;\n } else if (util.isObject(responseStream)) {\n options = responseStream;\n responseStream = undefined;\n }\n\n /* istanbul ignore if */\n if (!(type === undefined || util.isString(type)))\n throw TypeError(\"type must be a string\");\n\n /* istanbul ignore if */\n if (!util.isString(requestType))\n throw TypeError(\"requestType must be a string\");\n\n /* istanbul ignore if */\n if (!util.isString(responseType))\n throw TypeError(\"responseType must be a string\");\n\n ReflectionObject.call(this, name, options);\n\n /**\n * Method type.\n * @type {string}\n */\n this.type = type || \"rpc\"; // toJSON\n\n /**\n * Request type.\n * @type {string}\n */\n this.requestType = requestType; // toJSON, marker\n\n /**\n * Whether requests are streamed or not.\n * @type {boolean|undefined}\n */\n this.requestStream = requestStream ? true : undefined; // toJSON\n\n /**\n * Response type.\n * @type {string}\n */\n this.responseType = responseType; // toJSON\n\n /**\n * Whether responses are streamed or not.\n * @type {boolean|undefined}\n */\n this.responseStream = responseStream ? true : undefined; // toJSON\n\n /**\n * Resolved request type.\n * @type {Type|null}\n */\n this.resolvedRequestType = null;\n\n /**\n * Resolved response type.\n * @type {Type|null}\n */\n this.resolvedResponseType = null;\n\n /**\n * Comment for this method\n * @type {string|null}\n */\n this.comment = comment;\n\n /**\n * Options properly parsed into an object\n */\n this.parsedOptions = parsedOptions;\n}\n\n/**\n * Method descriptor.\n * @interface IMethod\n * @property {string} [type=\"rpc\"] Method type\n * @property {string} requestType Request type\n * @property {string} responseType Response type\n * @property {boolean} [requestStream=false] Whether requests are streamed\n * @property {boolean} [responseStream=false] Whether responses are streamed\n * @property {Object.} [options] Method options\n * @property {string} comment Method comments\n * @property {Object.} [parsedOptions] Method options properly parsed into an object\n */\n\n/**\n * Constructs a method from a method descriptor.\n * @param {string} name Method name\n * @param {IMethod} json Method descriptor\n * @returns {Method} Created method\n * @throws {TypeError} If arguments are invalid\n */\nMethod.fromJSON = function fromJSON(name, json) {\n return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions);\n};\n\n/**\n * Converts this method to a method descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IMethod} Method descriptor\n */\nMethod.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"type\" , this.type !== \"rpc\" && /* istanbul ignore next */ this.type || undefined,\n \"requestType\" , this.requestType,\n \"requestStream\" , this.requestStream,\n \"responseType\" , this.responseType,\n \"responseStream\" , this.responseStream,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined,\n \"parsedOptions\" , this.parsedOptions,\n ]);\n};\n\n/**\n * @override\n */\nMethod.prototype.resolve = function resolve() {\n\n /* istanbul ignore if */\n if (this.resolved)\n return this;\n\n this.resolvedRequestType = this.parent.lookupType(this.requestType);\n this.resolvedResponseType = this.parent.lookupType(this.responseType);\n\n return ReflectionObject.prototype.resolve.call(this);\n};\n","\"use strict\";\nmodule.exports = Namespace;\n\n// extends ReflectionObject\nvar ReflectionObject = require(22);\n((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = \"Namespace\";\n\nvar Field = require(15),\n util = require(33),\n OneOf = require(23);\n\nvar Type, // cyclic\n Service,\n Enum;\n\n/**\n * Constructs a new namespace instance.\n * @name Namespace\n * @classdesc Reflected namespace.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Namespace name\n * @param {Object.} [options] Declared options\n */\n\n/**\n * Constructs a namespace from JSON.\n * @memberof Namespace\n * @function\n * @param {string} name Namespace name\n * @param {Object.} json JSON object\n * @returns {Namespace} Created namespace\n * @throws {TypeError} If arguments are invalid\n */\nNamespace.fromJSON = function fromJSON(name, json) {\n return new Namespace(name, json.options).addJSON(json.nested);\n};\n\n/**\n * Converts an array of reflection objects to JSON.\n * @memberof Namespace\n * @param {ReflectionObject[]} array Object array\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {Object.|undefined} JSON object or `undefined` when array is empty\n */\nfunction arrayToJSON(array, toJSONOptions) {\n if (!(array && array.length))\n return undefined;\n var obj = {};\n for (var i = 0; i < array.length; ++i)\n obj[array[i].name] = array[i].toJSON(toJSONOptions);\n return obj;\n}\n\nNamespace.arrayToJSON = arrayToJSON;\n\n/**\n * Tests if the specified id is reserved.\n * @param {Array.|undefined} reserved Array of reserved ranges and names\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nNamespace.isReservedId = function isReservedId(reserved, id) {\n if (reserved)\n for (var i = 0; i < reserved.length; ++i)\n if (typeof reserved[i] !== \"string\" && reserved[i][0] <= id && reserved[i][1] > id)\n return true;\n return false;\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {Array.|undefined} reserved Array of reserved ranges and names\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nNamespace.isReservedName = function isReservedName(reserved, name) {\n if (reserved)\n for (var i = 0; i < reserved.length; ++i)\n if (reserved[i] === name)\n return true;\n return false;\n};\n\n/**\n * Not an actual constructor. Use {@link Namespace} instead.\n * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions.\n * @exports NamespaceBase\n * @extends ReflectionObject\n * @abstract\n * @constructor\n * @param {string} name Namespace name\n * @param {Object.} [options] Declared options\n * @see {@link Namespace}\n */\nfunction Namespace(name, options) {\n ReflectionObject.call(this, name, options);\n\n /**\n * Nested objects by name.\n * @type {Object.|undefined}\n */\n this.nested = undefined; // toJSON\n\n /**\n * Cached nested objects as an array.\n * @type {ReflectionObject[]|null}\n * @private\n */\n this._nestedArray = null;\n\n /**\n * Cache lookup calls for any objects contains anywhere under this namespace.\n * This drastically speeds up resolve for large cross-linked protos where the same\n * types are looked up repeatedly.\n * @type {Object.}\n * @private\n */\n this._lookupCache = {};\n\n /**\n * Whether or not objects contained in this namespace need feature resolution.\n * @type {boolean}\n * @protected\n */\n this._needsRecursiveFeatureResolution = true;\n\n /**\n * Whether or not objects contained in this namespace need a resolve.\n * @type {boolean}\n * @protected\n */\n this._needsRecursiveResolve = true;\n}\n\nfunction clearCache(namespace) {\n namespace._nestedArray = null;\n namespace._lookupCache = {};\n\n // Also clear parent caches, since they include nested lookups.\n var parent = namespace;\n while(parent = parent.parent) {\n parent._lookupCache = {};\n }\n return namespace;\n}\n\n/**\n * Nested objects of this namespace as an array for iteration.\n * @name NamespaceBase#nestedArray\n * @type {ReflectionObject[]}\n * @readonly\n */\nObject.defineProperty(Namespace.prototype, \"nestedArray\", {\n get: function() {\n return this._nestedArray || (this._nestedArray = util.toArray(this.nested));\n }\n});\n\n/**\n * Namespace descriptor.\n * @interface INamespace\n * @property {Object.} [options] Namespace options\n * @property {Object.} [nested] Nested object descriptors\n */\n\n/**\n * Any extension field descriptor.\n * @typedef AnyExtensionField\n * @type {IExtensionField|IExtensionMapField}\n */\n\n/**\n * Any nested object descriptor.\n * @typedef AnyNestedObject\n * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf}\n */\n\n/**\n * Converts this namespace to a namespace descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {INamespace} Namespace descriptor\n */\nNamespace.prototype.toJSON = function toJSON(toJSONOptions) {\n return util.toObject([\n \"options\" , this.options,\n \"nested\" , arrayToJSON(this.nestedArray, toJSONOptions)\n ]);\n};\n\n/**\n * Adds nested objects to this namespace from nested object descriptors.\n * @param {Object.} nestedJson Any nested object descriptors\n * @returns {Namespace} `this`\n */\nNamespace.prototype.addJSON = function addJSON(nestedJson) {\n var ns = this;\n /* istanbul ignore else */\n if (nestedJson) {\n for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) {\n nested = nestedJson[names[i]];\n ns.add( // most to least likely\n ( nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : nested.id !== undefined\n ? Field.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n }\n return this;\n};\n\n/**\n * Gets the nested object of the specified name.\n * @param {string} name Nested object name\n * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist\n */\nNamespace.prototype.get = function get(name) {\n return this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Gets the values of the nested {@link Enum|enum} of the specified name.\n * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`.\n * @param {string} name Nested enum name\n * @returns {Object.} Enum values\n * @throws {Error} If there is no such enum\n */\nNamespace.prototype.getEnum = function getEnum(name) {\n if (this.nested && this.nested[name] instanceof Enum)\n return this.nested[name].values;\n throw Error(\"no such enum: \" + name);\n};\n\n/**\n * Adds a nested object to this namespace.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Namespace} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name\n */\nNamespace.prototype.add = function add(object) {\n\n if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace))\n throw TypeError(\"object must be a valid nested object\");\n\n if (!this.nested)\n this.nested = {};\n else {\n var prev = this.get(object.name);\n if (prev) {\n if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) {\n // replace plain namespace but keep existing nested elements and options\n var nested = prev.nestedArray;\n for (var i = 0; i < nested.length; ++i)\n object.add(nested[i]);\n this.remove(prev);\n if (!this.nested)\n this.nested = {};\n object.setOptions(prev.options, true);\n\n } else\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n }\n }\n this.nested[object.name] = object;\n\n if (!(this instanceof Type || this instanceof Service || this instanceof Enum || this instanceof Field)) {\n // This is a package or a root namespace.\n if (!object._edition) {\n // Make sure that some edition is set if it hasn't already been specified.\n object._edition = object._defaultEdition;\n }\n }\n\n this._needsRecursiveFeatureResolution = true;\n this._needsRecursiveResolve = true;\n\n // Also clear parent caches, since they need to recurse down.\n var parent = this;\n while(parent = parent.parent) {\n parent._needsRecursiveFeatureResolution = true;\n parent._needsRecursiveResolve = true;\n }\n\n object.onAdd(this);\n return clearCache(this);\n};\n\n/**\n * Removes a nested object from this namespace.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Namespace} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this namespace\n */\nNamespace.prototype.remove = function remove(object) {\n\n if (!(object instanceof ReflectionObject))\n throw TypeError(\"object must be a ReflectionObject\");\n if (object.parent !== this)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.nested[object.name];\n if (!Object.keys(this.nested).length)\n this.nested = undefined;\n\n object.onRemove(this);\n return clearCache(this);\n};\n\n/**\n * Defines additial namespaces within this one if not yet existing.\n * @param {string|string[]} path Path to create\n * @param {*} [json] Nested types to create from JSON\n * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty\n */\nNamespace.prototype.define = function define(path, json) {\n\n if (util.isString(path))\n path = path.split(\".\");\n else if (!Array.isArray(path))\n throw TypeError(\"illegal path\");\n if (path && path.length && path[0] === \"\")\n throw Error(\"path must be relative\");\n\n var ptr = this;\n while (path.length > 0) {\n var part = path.shift();\n if (ptr.nested && ptr.nested[part]) {\n ptr = ptr.nested[part];\n if (!(ptr instanceof Namespace))\n throw Error(\"path conflicts with non-namespace objects\");\n } else\n ptr.add(ptr = new Namespace(part));\n }\n if (json)\n ptr.addJSON(json);\n return ptr;\n};\n\n/**\n * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost.\n * @returns {Namespace} `this`\n */\nNamespace.prototype.resolveAll = function resolveAll() {\n if (!this._needsRecursiveResolve) return this;\n\n this._resolveFeaturesRecursive(this._edition);\n\n var nested = this.nestedArray, i = 0;\n this.resolve();\n while (i < nested.length)\n if (nested[i] instanceof Namespace)\n nested[i++].resolveAll();\n else\n nested[i++].resolve();\n this._needsRecursiveResolve = false;\n return this;\n};\n\n/**\n * @override\n */\nNamespace.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) {\n if (!this._needsRecursiveFeatureResolution) return this;\n this._needsRecursiveFeatureResolution = false;\n\n edition = this._edition || edition;\n\n ReflectionObject.prototype._resolveFeaturesRecursive.call(this, edition);\n this.nestedArray.forEach(nested => {\n nested._resolveFeaturesRecursive(edition);\n });\n return this;\n};\n\n/**\n * Recursively looks up the reflection object matching the specified path in the scope of this namespace.\n * @param {string|string[]} path Path to look up\n * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc.\n * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n */\nNamespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) {\n /* istanbul ignore next */\n if (typeof filterTypes === \"boolean\") {\n parentAlreadyChecked = filterTypes;\n filterTypes = undefined;\n } else if (filterTypes && !Array.isArray(filterTypes))\n filterTypes = [ filterTypes ];\n\n if (util.isString(path) && path.length) {\n if (path === \".\")\n return this.root;\n path = path.split(\".\");\n } else if (!path.length)\n return this;\n\n var flatPath = path.join(\".\");\n\n // Start at root if path is absolute\n if (path[0] === \"\")\n return this.root.lookup(path.slice(1), filterTypes);\n\n // Early bailout for objects with matching absolute paths\n var found = this.root._fullyQualifiedObjects && this.root._fullyQualifiedObjects[\".\" + flatPath];\n if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {\n return found;\n }\n\n // Do a regular lookup at this namespace and below\n found = this._lookupImpl(path, flatPath);\n if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {\n return found;\n }\n\n if (parentAlreadyChecked)\n return null;\n\n // If there hasn't been a match, walk up the tree and look more broadly\n var current = this;\n while (current.parent) {\n found = current.parent._lookupImpl(path, flatPath);\n if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {\n return found;\n }\n current = current.parent;\n }\n return null;\n};\n\n/**\n * Internal helper for lookup that handles searching just at this namespace and below along with caching.\n * @param {string[]} path Path to look up\n * @param {string} flatPath Flattened version of the path to use as a cache key\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n * @private\n */\nNamespace.prototype._lookupImpl = function lookup(path, flatPath) {\n if(Object.prototype.hasOwnProperty.call(this._lookupCache, flatPath)) {\n return this._lookupCache[flatPath];\n }\n\n // Test if the first part matches any nested object, and if so, traverse if path contains more\n var found = this.get(path[0]);\n var exact = null;\n if (found) {\n if (path.length === 1) {\n exact = found;\n } else if (found instanceof Namespace) {\n path = path.slice(1);\n exact = found._lookupImpl(path, path.join(\".\"));\n }\n\n // Otherwise try each nested namespace\n } else {\n for (var i = 0; i < this.nestedArray.length; ++i)\n if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i]._lookupImpl(path, flatPath)))\n exact = found;\n }\n\n // Set this even when null, so that when we walk up the tree we can quickly bail on repeated checks back down.\n this._lookupCache[flatPath] = exact;\n return exact;\n};\n\n/**\n * Looks up the reflection object at the specified path, relative to this namespace.\n * @name NamespaceBase#lookup\n * @function\n * @param {string|string[]} path Path to look up\n * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n * @variation 2\n */\n// lookup(path: string, [parentAlreadyChecked: boolean])\n\n/**\n * Looks up the {@link Type|type} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Type} Looked up type\n * @throws {Error} If `path` does not point to a type\n */\nNamespace.prototype.lookupType = function lookupType(path) {\n var found = this.lookup(path, [ Type ]);\n if (!found)\n throw Error(\"no such type: \" + path);\n return found;\n};\n\n/**\n * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Enum} Looked up enum\n * @throws {Error} If `path` does not point to an enum\n */\nNamespace.prototype.lookupEnum = function lookupEnum(path) {\n var found = this.lookup(path, [ Enum ]);\n if (!found)\n throw Error(\"no such Enum '\" + path + \"' in \" + this);\n return found;\n};\n\n/**\n * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Type} Looked up type or enum\n * @throws {Error} If `path` does not point to a type or enum\n */\nNamespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) {\n var found = this.lookup(path, [ Type, Enum ]);\n if (!found)\n throw Error(\"no such Type or Enum '\" + path + \"' in \" + this);\n return found;\n};\n\n/**\n * Looks up the {@link Service|service} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Service} Looked up service\n * @throws {Error} If `path` does not point to a service\n */\nNamespace.prototype.lookupService = function lookupService(path) {\n var found = this.lookup(path, [ Service ]);\n if (!found)\n throw Error(\"no such Service '\" + path + \"' in \" + this);\n return found;\n};\n\n// Sets up cyclic dependencies (called in index-light)\nNamespace._configure = function(Type_, Service_, Enum_) {\n Type = Type_;\n Service = Service_;\n Enum = Enum_;\n};\n","\"use strict\";\nmodule.exports = ReflectionObject;\n\nReflectionObject.className = \"ReflectionObject\";\n\nconst OneOf = require(23);\nvar util = require(33);\n\nvar Root; // cyclic\n\n/* eslint-disable no-warning-comments */\n// TODO: Replace with embedded proto.\nvar editions2023Defaults = {enum_type: \"OPEN\", field_presence: \"EXPLICIT\", json_format: \"ALLOW\", message_encoding: \"LENGTH_PREFIXED\", repeated_field_encoding: \"PACKED\", utf8_validation: \"VERIFY\"};\nvar proto2Defaults = {enum_type: \"CLOSED\", field_presence: \"EXPLICIT\", json_format: \"LEGACY_BEST_EFFORT\", message_encoding: \"LENGTH_PREFIXED\", repeated_field_encoding: \"EXPANDED\", utf8_validation: \"NONE\"};\nvar proto3Defaults = {enum_type: \"OPEN\", field_presence: \"IMPLICIT\", json_format: \"ALLOW\", message_encoding: \"LENGTH_PREFIXED\", repeated_field_encoding: \"PACKED\", utf8_validation: \"VERIFY\"};\n\n/**\n * Constructs a new reflection object instance.\n * @classdesc Base class of all reflection objects.\n * @constructor\n * @param {string} name Object name\n * @param {Object.} [options] Declared options\n * @abstract\n */\nfunction ReflectionObject(name, options) {\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n if (options && !util.isObject(options))\n throw TypeError(\"options must be an object\");\n\n /**\n * Options.\n * @type {Object.|undefined}\n */\n this.options = options; // toJSON\n\n /**\n * Parsed Options.\n * @type {Array.>|undefined}\n */\n this.parsedOptions = null;\n\n /**\n * Unique name within its namespace.\n * @type {string}\n */\n this.name = name;\n\n /**\n * The edition specified for this object. Only relevant for top-level objects.\n * @type {string}\n * @private\n */\n this._edition = null;\n\n /**\n * The default edition to use for this object if none is specified. For legacy reasons,\n * this is proto2 except in the JSON parsing case where it was proto3.\n * @type {string}\n * @private\n */\n this._defaultEdition = \"proto2\";\n\n /**\n * Resolved Features.\n * @type {object}\n * @private\n */\n this._features = {};\n\n /**\n * Whether or not features have been resolved.\n * @type {boolean}\n * @private\n */\n this._featuresResolved = false;\n\n /**\n * Parent namespace.\n * @type {Namespace|null}\n */\n this.parent = null;\n\n /**\n * Whether already resolved or not.\n * @type {boolean}\n */\n this.resolved = false;\n\n /**\n * Comment text, if any.\n * @type {string|null}\n */\n this.comment = null;\n\n /**\n * Defining file name.\n * @type {string|null}\n */\n this.filename = null;\n}\n\nObject.defineProperties(ReflectionObject.prototype, {\n\n /**\n * Reference to the root namespace.\n * @name ReflectionObject#root\n * @type {Root}\n * @readonly\n */\n root: {\n get: function() {\n var ptr = this;\n while (ptr.parent !== null)\n ptr = ptr.parent;\n return ptr;\n }\n },\n\n /**\n * Full name including leading dot.\n * @name ReflectionObject#fullName\n * @type {string}\n * @readonly\n */\n fullName: {\n get: function() {\n var path = [ this.name ],\n ptr = this.parent;\n while (ptr) {\n path.unshift(ptr.name);\n ptr = ptr.parent;\n }\n return path.join(\".\");\n }\n }\n});\n\n/**\n * Converts this reflection object to its descriptor representation.\n * @returns {Object.} Descriptor\n * @abstract\n */\nReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() {\n throw Error(); // not implemented, shouldn't happen\n};\n\n/**\n * Called when this object is added to a parent.\n * @param {ReflectionObject} parent Parent added to\n * @returns {undefined}\n */\nReflectionObject.prototype.onAdd = function onAdd(parent) {\n if (this.parent && this.parent !== parent)\n this.parent.remove(this);\n this.parent = parent;\n this.resolved = false;\n var root = parent.root;\n if (root instanceof Root)\n root._handleAdd(this);\n};\n\n/**\n * Called when this object is removed from a parent.\n * @param {ReflectionObject} parent Parent removed from\n * @returns {undefined}\n */\nReflectionObject.prototype.onRemove = function onRemove(parent) {\n var root = parent.root;\n if (root instanceof Root)\n root._handleRemove(this);\n this.parent = null;\n this.resolved = false;\n};\n\n/**\n * Resolves this objects type references.\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.resolve = function resolve() {\n if (this.resolved)\n return this;\n if (this.root instanceof Root)\n this.resolved = true; // only if part of a root\n return this;\n};\n\n/**\n * Resolves this objects editions features.\n * @param {string} edition The edition we're currently resolving for.\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) {\n return this._resolveFeatures(this._edition || edition);\n};\n\n/**\n * Resolves child features from parent features\n * @param {string} edition The edition we're currently resolving for.\n * @returns {undefined}\n */\nReflectionObject.prototype._resolveFeatures = function _resolveFeatures(edition) {\n if (this._featuresResolved) {\n return;\n }\n\n var defaults = {};\n\n /* istanbul ignore if */\n if (!edition) {\n throw new Error(\"Unknown edition for \" + this.fullName);\n }\n\n var protoFeatures = Object.assign(this.options ? Object.assign({}, this.options.features) : {},\n this._inferLegacyProtoFeatures(edition));\n\n if (this._edition) {\n // For a namespace marked with a specific edition, reset defaults.\n /* istanbul ignore else */\n if (edition === \"proto2\") {\n defaults = Object.assign({}, proto2Defaults);\n } else if (edition === \"proto3\") {\n defaults = Object.assign({}, proto3Defaults);\n } else if (edition === \"2023\") {\n defaults = Object.assign({}, editions2023Defaults);\n } else {\n throw new Error(\"Unknown edition: \" + edition);\n }\n this._features = Object.assign(defaults, protoFeatures || {});\n this._featuresResolved = true;\n return;\n }\n\n // fields in Oneofs aren't actually children of them, so we have to\n // special-case it\n /* istanbul ignore else */\n if (this.partOf instanceof OneOf) {\n var lexicalParentFeaturesCopy = Object.assign({}, this.partOf._features);\n this._features = Object.assign(lexicalParentFeaturesCopy, protoFeatures || {});\n } else if (this.declaringField) {\n // Skip feature resolution of sister fields.\n } else if (this.parent) {\n var parentFeaturesCopy = Object.assign({}, this.parent._features);\n this._features = Object.assign(parentFeaturesCopy, protoFeatures || {});\n } else {\n throw new Error(\"Unable to find a parent for \" + this.fullName);\n }\n if (this.extensionField) {\n // Sister fields should have the same features as their extensions.\n this.extensionField._features = this._features;\n }\n this._featuresResolved = true;\n};\n\n/**\n * Infers features from legacy syntax that may have been specified differently.\n * in older editions.\n * @param {string|undefined} edition The edition this proto is on, or undefined if pre-editions\n * @returns {object} The feature values to override\n */\nReflectionObject.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(/*edition*/) {\n return {};\n};\n\n/**\n * Gets an option value.\n * @param {string} name Option name\n * @returns {*} Option value or `undefined` if not set\n */\nReflectionObject.prototype.getOption = function getOption(name) {\n if (this.options)\n return this.options[name];\n return undefined;\n};\n\n/**\n * Sets an option.\n * @param {string} name Option name\n * @param {*} value Option value\n * @param {boolean|undefined} [ifNotSet] Sets the option only if it isn't currently set\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) {\n if (!this.options)\n this.options = {};\n if (/^features\\./.test(name)) {\n util.setProperty(this.options, name, value, ifNotSet);\n } else if (!ifNotSet || this.options[name] === undefined) {\n if (this.getOption(name) !== value) this.resolved = false;\n this.options[name] = value;\n }\n\n return this;\n};\n\n/**\n * Sets a parsed option.\n * @param {string} name parsed Option name\n * @param {*} value Option value\n * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\\empty, will add a new option with that value\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) {\n if (!this.parsedOptions) {\n this.parsedOptions = [];\n }\n var parsedOptions = this.parsedOptions;\n if (propName) {\n // If setting a sub property of an option then try to merge it\n // with an existing option\n var opt = parsedOptions.find(function (opt) {\n return Object.prototype.hasOwnProperty.call(opt, name);\n });\n if (opt) {\n // If we found an existing option - just merge the property value\n // (If it's a feature, will just write over)\n var newValue = opt[name];\n util.setProperty(newValue, propName, value);\n } else {\n // otherwise, create a new option, set its property and add it to the list\n opt = {};\n opt[name] = util.setProperty({}, propName, value);\n parsedOptions.push(opt);\n }\n } else {\n // Always create a new option when setting the value of the option itself\n var newOpt = {};\n newOpt[name] = value;\n parsedOptions.push(newOpt);\n }\n\n return this;\n};\n\n/**\n * Sets multiple options.\n * @param {Object.} options Options to set\n * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) {\n if (options)\n for (var keys = Object.keys(options), i = 0; i < keys.length; ++i)\n this.setOption(keys[i], options[keys[i]], ifNotSet);\n return this;\n};\n\n/**\n * Converts this instance to its string representation.\n * @returns {string} Class name[, space, full name]\n */\nReflectionObject.prototype.toString = function toString() {\n var className = this.constructor.className,\n fullName = this.fullName;\n if (fullName.length)\n return className + \" \" + fullName;\n return className;\n};\n\n/**\n * Converts the edition this object is pinned to for JSON format.\n * @returns {string|undefined} The edition string for JSON representation\n */\nReflectionObject.prototype._editionToJSON = function _editionToJSON() {\n if (!this._edition || this._edition === \"proto3\") {\n // Avoid emitting proto3 since we need to default to it for backwards\n // compatibility anyway.\n return undefined;\n }\n return this._edition;\n};\n\n// Sets up cyclic dependencies (called in index-light)\nReflectionObject._configure = function(Root_) {\n Root = Root_;\n};\n","\"use strict\";\nmodule.exports = OneOf;\n\n// extends ReflectionObject\nvar ReflectionObject = require(22);\n((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = \"OneOf\";\n\nvar Field = require(15),\n util = require(33);\n\n/**\n * Constructs a new oneof instance.\n * @classdesc Reflected oneof.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Oneof name\n * @param {string[]|Object.} [fieldNames] Field names\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction OneOf(name, fieldNames, options, comment) {\n if (!Array.isArray(fieldNames)) {\n options = fieldNames;\n fieldNames = undefined;\n }\n ReflectionObject.call(this, name, options);\n\n /* istanbul ignore if */\n if (!(fieldNames === undefined || Array.isArray(fieldNames)))\n throw TypeError(\"fieldNames must be an Array\");\n\n /**\n * Field names that belong to this oneof.\n * @type {string[]}\n */\n this.oneof = fieldNames || []; // toJSON, marker\n\n /**\n * Fields that belong to this oneof as an array for iteration.\n * @type {Field[]}\n * @readonly\n */\n this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent\n\n /**\n * Comment for this field.\n * @type {string|null}\n */\n this.comment = comment;\n}\n\n/**\n * Oneof descriptor.\n * @interface IOneOf\n * @property {Array.} oneof Oneof field names\n * @property {Object.} [options] Oneof options\n */\n\n/**\n * Constructs a oneof from a oneof descriptor.\n * @param {string} name Oneof name\n * @param {IOneOf} json Oneof descriptor\n * @returns {OneOf} Created oneof\n * @throws {TypeError} If arguments are invalid\n */\nOneOf.fromJSON = function fromJSON(name, json) {\n return new OneOf(name, json.oneof, json.options, json.comment);\n};\n\n/**\n * Converts this oneof to a oneof descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IOneOf} Oneof descriptor\n */\nOneOf.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , this.options,\n \"oneof\" , this.oneof,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Adds the fields of the specified oneof to the parent if not already done so.\n * @param {OneOf} oneof The oneof\n * @returns {undefined}\n * @inner\n * @ignore\n */\nfunction addFieldsToParent(oneof) {\n if (oneof.parent)\n for (var i = 0; i < oneof.fieldsArray.length; ++i)\n if (!oneof.fieldsArray[i].parent)\n oneof.parent.add(oneof.fieldsArray[i]);\n}\n\n/**\n * Adds a field to this oneof and removes it from its current parent, if any.\n * @param {Field} field Field to add\n * @returns {OneOf} `this`\n */\nOneOf.prototype.add = function add(field) {\n\n /* istanbul ignore if */\n if (!(field instanceof Field))\n throw TypeError(\"field must be a Field\");\n\n if (field.parent && field.parent !== this.parent)\n field.parent.remove(field);\n this.oneof.push(field.name);\n this.fieldsArray.push(field);\n field.partOf = this; // field.parent remains null\n addFieldsToParent(this);\n return this;\n};\n\n/**\n * Removes a field from this oneof and puts it back to the oneof's parent.\n * @param {Field} field Field to remove\n * @returns {OneOf} `this`\n */\nOneOf.prototype.remove = function remove(field) {\n\n /* istanbul ignore if */\n if (!(field instanceof Field))\n throw TypeError(\"field must be a Field\");\n\n var index = this.fieldsArray.indexOf(field);\n\n /* istanbul ignore if */\n if (index < 0)\n throw Error(field + \" is not a member of \" + this);\n\n this.fieldsArray.splice(index, 1);\n index = this.oneof.indexOf(field.name);\n\n /* istanbul ignore else */\n if (index > -1) // theoretical\n this.oneof.splice(index, 1);\n\n field.partOf = null;\n return this;\n};\n\n/**\n * @override\n */\nOneOf.prototype.onAdd = function onAdd(parent) {\n ReflectionObject.prototype.onAdd.call(this, parent);\n var self = this;\n // Collect present fields\n for (var i = 0; i < this.oneof.length; ++i) {\n var field = parent.get(this.oneof[i]);\n if (field && !field.partOf) {\n field.partOf = self;\n self.fieldsArray.push(field);\n }\n }\n // Add not yet present fields\n addFieldsToParent(this);\n};\n\n/**\n * @override\n */\nOneOf.prototype.onRemove = function onRemove(parent) {\n for (var i = 0, field; i < this.fieldsArray.length; ++i)\n if ((field = this.fieldsArray[i]).parent)\n field.parent.remove(field);\n ReflectionObject.prototype.onRemove.call(this, parent);\n};\n\n/**\n * Determines whether this field corresponds to a synthetic oneof created for\n * a proto3 optional field. No behavioral logic should depend on this, but it\n * can be relevant for reflection.\n * @name OneOf#isProto3Optional\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(OneOf.prototype, \"isProto3Optional\", {\n get: function() {\n if (this.fieldsArray == null || this.fieldsArray.length !== 1) {\n return false;\n }\n\n var field = this.fieldsArray[0];\n return field.options != null && field.options[\"proto3_optional\"] === true;\n }\n});\n\n/**\n * Decorator function as returned by {@link OneOf.d} (TypeScript).\n * @typedef OneOfDecorator\n * @type {function}\n * @param {Object} prototype Target prototype\n * @param {string} oneofName OneOf name\n * @returns {undefined}\n */\n\n/**\n * OneOf decorator (TypeScript).\n * @function\n * @param {...string} fieldNames Field names\n * @returns {OneOfDecorator} Decorator function\n * @template T extends string\n */\nOneOf.d = function decorateOneOf() {\n var fieldNames = new Array(arguments.length),\n index = 0;\n while (index < arguments.length)\n fieldNames[index] = arguments[index++];\n return function oneOfDecorator(prototype, oneofName) {\n util.decorateType(prototype.constructor)\n .add(new OneOf(oneofName, fieldNames));\n Object.defineProperty(prototype, oneofName, {\n get: util.oneOfGetter(fieldNames),\n set: util.oneOfSetter(fieldNames)\n });\n };\n};\n","\"use strict\";\nmodule.exports = Reader;\n\nvar util = require(35);\n\nvar BufferReader; // cyclic\n\nvar LongBits = util.LongBits,\n utf8 = util.utf8;\n\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(\"index out of range: \" + reader.pos + \" + \" + (writeLength || 1) + \" > \" + reader.len);\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n * @param {Uint8Array} buffer Buffer to read from\n */\nfunction Reader(buffer) {\n\n /**\n * Read buffer.\n * @type {Uint8Array}\n */\n this.buf = buffer;\n\n /**\n * Read buffer position.\n * @type {number}\n */\n this.pos = 0;\n\n /**\n * Read buffer length.\n * @type {number}\n */\n this.len = buffer.length;\n}\n\nvar create_array = typeof Uint8Array !== \"undefined\"\n ? function create_typed_array(buffer) {\n if (buffer instanceof Uint8Array || Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n }\n /* istanbul ignore next */\n : function create_array(buffer) {\n if (Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n };\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup(buffer) {\n return (Reader.create = function create_buffer(buffer) {\n return util.Buffer.isBuffer(buffer)\n ? new BufferReader(buffer)\n /* istanbul ignore next */\n : create_array(buffer);\n })(buffer);\n }\n /* istanbul ignore next */\n : create_array;\n};\n\n/**\n * Creates a new reader using the specified buffer.\n * @function\n * @param {Uint8Array|Buffer} buffer Buffer to read from\n * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}\n * @throws {Error} If `buffer` is not a valid buffer\n */\nReader.create = create();\n\nReader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;\n\n/**\n * Reads a varint as an unsigned 32 bit value.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.uint32 = (function read_uint32_setup() {\n var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)\n return function read_uint32() {\n value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;\n\n /* istanbul ignore if */\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n };\n})();\n\n/**\n * Reads a varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.int32 = function read_int32() {\n return this.uint32() | 0;\n};\n\n/**\n * Reads a zig-zag encoded varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.sint32 = function read_sint32() {\n var value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readLongVarint() {\n // tends to deopt with local vars for octet etc.\n var bits = new LongBits(0, 0);\n var i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n i = 0;\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n } else {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n }\n /* istanbul ignore next */\n throw Error(\"invalid varint encoding\");\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads a varint as a signed 64 bit value.\n * @name Reader#int64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as an unsigned 64 bit value.\n * @name Reader#uint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a zig-zag encoded varint as a signed 64 bit value.\n * @name Reader#sint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as a boolean.\n * @returns {boolean} Value read\n */\nReader.prototype.bool = function read_bool() {\n return this.uint32() !== 0;\n};\n\nfunction readFixed32_end(buf, end) { // note that this uses `end`, not `pos`\n return (buf[end - 4]\n | buf[end - 3] << 8\n | buf[end - 2] << 16\n | buf[end - 1] << 24) >>> 0;\n}\n\n/**\n * Reads fixed 32 bits as an unsigned 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.fixed32 = function read_fixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4);\n};\n\n/**\n * Reads fixed 32 bits as a signed 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.sfixed32 = function read_sfixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readFixed64(/* this: Reader */) {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 8);\n\n return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads fixed 64 bits.\n * @name Reader#fixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads zig-zag encoded fixed 64 bits.\n * @name Reader#sfixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a float (32 bit) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.float = function read_float() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readFloatLE(this.buf, this.pos);\n this.pos += 4;\n return value;\n};\n\n/**\n * Reads a double (64 bit float) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.double = function read_double() {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readDoubleLE(this.buf, this.pos);\n this.pos += 8;\n return value;\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @returns {Uint8Array} Value read\n */\nReader.prototype.bytes = function read_bytes() {\n var length = this.uint32(),\n start = this.pos,\n end = this.pos + length;\n\n /* istanbul ignore if */\n if (end > this.len)\n throw indexOutOfRange(this, length);\n\n this.pos += length;\n if (Array.isArray(this.buf)) // plain array\n return this.buf.slice(start, end);\n\n if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1\n var nativeBuffer = util.Buffer;\n return nativeBuffer\n ? nativeBuffer.alloc(0)\n : new this.buf.constructor(0);\n }\n return this._slice.call(this.buf, start, end);\n};\n\n/**\n * Reads a string preceeded by its byte length as a varint.\n * @returns {string} Value read\n */\nReader.prototype.string = function read_string() {\n var bytes = this.bytes();\n return utf8.read(bytes, 0, bytes.length);\n};\n\n/**\n * Skips the specified number of bytes if specified, otherwise skips a varint.\n * @param {number} [length] Length if known, otherwise a varint is assumed\n * @returns {Reader} `this`\n */\nReader.prototype.skip = function skip(length) {\n if (typeof length === \"number\") {\n /* istanbul ignore if */\n if (this.pos + length > this.len)\n throw indexOutOfRange(this, length);\n this.pos += length;\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n } while (this.buf[this.pos++] & 128);\n }\n return this;\n};\n\n/**\n * Skips the next element of the specified wire type.\n * @param {number} wireType Wire type received\n * @returns {Reader} `this`\n */\nReader.prototype.skipType = function(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n\n /* istanbul ignore next */\n default:\n throw Error(\"invalid wire type \" + wireType + \" at offset \" + this.pos);\n }\n return this;\n};\n\nReader._configure = function(BufferReader_) {\n BufferReader = BufferReader_;\n Reader.create = create();\n BufferReader._configure();\n\n var fn = util.Long ? \"toLong\" : /* istanbul ignore next */ \"toNumber\";\n util.merge(Reader.prototype, {\n\n int64: function read_int64() {\n return readLongVarint.call(this)[fn](false);\n },\n\n uint64: function read_uint64() {\n return readLongVarint.call(this)[fn](true);\n },\n\n sint64: function read_sint64() {\n return readLongVarint.call(this).zzDecode()[fn](false);\n },\n\n fixed64: function read_fixed64() {\n return readFixed64.call(this)[fn](true);\n },\n\n sfixed64: function read_sfixed64() {\n return readFixed64.call(this)[fn](false);\n }\n\n });\n};\n","\"use strict\";\nmodule.exports = BufferReader;\n\n// extends Reader\nvar Reader = require(24);\n(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;\n\nvar util = require(35);\n\n/**\n * Constructs a new buffer reader instance.\n * @classdesc Wire format reader using node buffers.\n * @extends Reader\n * @constructor\n * @param {Buffer} buffer Buffer to read from\n */\nfunction BufferReader(buffer) {\n Reader.call(this, buffer);\n\n /**\n * Read buffer.\n * @name BufferReader#buf\n * @type {Buffer}\n */\n}\n\nBufferReader._configure = function () {\n /* istanbul ignore else */\n if (util.Buffer)\n BufferReader.prototype._slice = util.Buffer.prototype.slice;\n};\n\n\n/**\n * @override\n */\nBufferReader.prototype.string = function read_string_buffer() {\n var len = this.uint32(); // modifies pos\n return this.buf.utf8Slice\n ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))\n : this.buf.toString(\"utf-8\", this.pos, this.pos = Math.min(this.pos + len, this.len));\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @name BufferReader#bytes\n * @function\n * @returns {Buffer} Value read\n */\n\nBufferReader._configure();\n","\"use strict\";\nmodule.exports = Root;\n\n// extends Namespace\nvar Namespace = require(21);\n((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = \"Root\";\n\nvar Field = require(15),\n Enum = require(14),\n OneOf = require(23),\n util = require(33);\n\nvar Type, // cyclic\n parse, // might be excluded\n common; // \"\n\n/**\n * Constructs a new root namespace instance.\n * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together.\n * @extends NamespaceBase\n * @constructor\n * @param {Object.} [options] Top level options\n */\nfunction Root(options) {\n Namespace.call(this, \"\", options);\n\n /**\n * Deferred extension fields.\n * @type {Field[]}\n */\n this.deferred = [];\n\n /**\n * Resolved file names of loaded files.\n * @type {string[]}\n */\n this.files = [];\n\n /**\n * Edition, defaults to proto2 if unspecified.\n * @type {string}\n * @private\n */\n this._edition = \"proto2\";\n\n /**\n * Global lookup cache of fully qualified names.\n * @type {Object.}\n * @private\n */\n this._fullyQualifiedObjects = {};\n}\n\n/**\n * Loads a namespace descriptor into a root namespace.\n * @param {INamespace} json Namespace descriptor\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted\n * @returns {Root} Root namespace\n */\nRoot.fromJSON = function fromJSON(json, root) {\n if (!root)\n root = new Root();\n if (json.options)\n root.setOptions(json.options);\n return root.addJSON(json.nested).resolveAll();\n};\n\n/**\n * Resolves the path of an imported file, relative to the importing origin.\n * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories.\n * @function\n * @param {string} origin The file name of the importing file\n * @param {string} target The file name being imported\n * @returns {string|null} Resolved path to `target` or `null` to skip the file\n */\nRoot.prototype.resolvePath = util.path.resolve;\n\n/**\n * Fetch content from file path or url\n * This method exists so you can override it with your own logic.\n * @function\n * @param {string} path File path or url\n * @param {FetchCallback} callback Callback function\n * @returns {undefined}\n */\nRoot.prototype.fetch = util.fetch;\n\n// A symbol-like function to safely signal synchronous loading\n/* istanbul ignore next */\nfunction SYNC() {} // eslint-disable-line no-empty-function\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} options Parse options\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n */\nRoot.prototype.load = function load(filename, options, callback) {\n if (typeof options === \"function\") {\n callback = options;\n options = undefined;\n }\n var self = this;\n if (!callback) {\n return util.asPromise(load, self, filename, options);\n }\n\n var sync = callback === SYNC; // undocumented\n\n // Finishes loading by calling the callback (exactly once)\n function finish(err, root) {\n /* istanbul ignore if */\n if (!callback) {\n return;\n }\n if (sync) {\n throw err;\n }\n if (root) {\n root.resolveAll();\n }\n var cb = callback;\n callback = null;\n cb(err, root);\n }\n\n // Bundled definition existence checking\n function getBundledFileName(filename) {\n var idx = filename.lastIndexOf(\"google/protobuf/\");\n if (idx > -1) {\n var altname = filename.substring(idx);\n if (altname in common) return altname;\n }\n return null;\n }\n\n // Processes a single file\n function process(filename, source) {\n try {\n if (util.isString(source) && source.charAt(0) === \"{\")\n source = JSON.parse(source);\n if (!util.isString(source))\n self.setOptions(source.options).addJSON(source.nested);\n else {\n parse.filename = filename;\n var parsed = parse(source, self, options),\n resolved,\n i = 0;\n if (parsed.imports)\n for (; i < parsed.imports.length; ++i)\n if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i]))\n fetch(resolved);\n if (parsed.weakImports)\n for (i = 0; i < parsed.weakImports.length; ++i)\n if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i]))\n fetch(resolved, true);\n }\n } catch (err) {\n finish(err);\n }\n if (!sync && !queued) {\n finish(null, self); // only once anyway\n }\n }\n\n // Fetches a single file\n function fetch(filename, weak) {\n filename = getBundledFileName(filename) || filename;\n\n // Skip if already loaded / attempted\n if (self.files.indexOf(filename) > -1) {\n return;\n }\n self.files.push(filename);\n\n // Shortcut bundled definitions\n if (filename in common) {\n if (sync) {\n process(filename, common[filename]);\n } else {\n ++queued;\n setTimeout(function() {\n --queued;\n process(filename, common[filename]);\n });\n }\n return;\n }\n\n // Otherwise fetch from disk or network\n if (sync) {\n var source;\n try {\n source = util.fs.readFileSync(filename).toString(\"utf8\");\n } catch (err) {\n if (!weak)\n finish(err);\n return;\n }\n process(filename, source);\n } else {\n ++queued;\n self.fetch(filename, function(err, source) {\n --queued;\n /* istanbul ignore if */\n if (!callback) {\n return; // terminated meanwhile\n }\n if (err) {\n /* istanbul ignore else */\n if (!weak)\n finish(err);\n else if (!queued) // can't be covered reliably\n finish(null, self);\n return;\n }\n process(filename, source);\n });\n }\n }\n var queued = 0;\n\n // Assembling the root namespace doesn't require working type\n // references anymore, so we can load everything in parallel\n if (util.isString(filename)) {\n filename = [ filename ];\n }\n for (var i = 0, resolved; i < filename.length; ++i)\n if (resolved = self.resolvePath(\"\", filename[i]))\n fetch(resolved);\n if (sync) {\n self.resolveAll();\n return self;\n }\n if (!queued) {\n finish(null, self);\n }\n\n return self;\n};\n// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\n * @function Root#load\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @variation 2\n */\n// function load(filename:string, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise.\n * @function Root#load\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {Promise} Promise\n * @variation 3\n */\n// function load(filename:string, [options:IParseOptions]):Promise\n\n/**\n * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only).\n * @function Root#loadSync\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {Root} Root namespace\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\n */\nRoot.prototype.loadSync = function loadSync(filename, options) {\n if (!util.isNode)\n throw Error(\"not supported\");\n return this.load(filename, options, SYNC);\n};\n\n/**\n * @override\n */\nRoot.prototype.resolveAll = function resolveAll() {\n if (!this._needsRecursiveResolve) return this;\n\n if (this.deferred.length)\n throw Error(\"unresolvable extensions: \" + this.deferred.map(function(field) {\n return \"'extend \" + field.extend + \"' in \" + field.parent.fullName;\n }).join(\", \"));\n return Namespace.prototype.resolveAll.call(this);\n};\n\n// only uppercased (and thus conflict-free) children are exposed, see below\nvar exposeRe = /^[A-Z]/;\n\n/**\n * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type.\n * @param {Root} root Root instance\n * @param {Field} field Declaring extension field witin the declaring type\n * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise\n * @inner\n * @ignore\n */\nfunction tryHandleExtension(root, field) {\n var extendedType = field.parent.lookup(field.extend);\n if (extendedType) {\n var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options);\n //do not allow to extend same field twice to prevent the error\n if (extendedType.get(sisterField.name)) {\n return true;\n }\n sisterField.declaringField = field;\n field.extensionField = sisterField;\n extendedType.add(sisterField);\n return true;\n }\n return false;\n}\n\n/**\n * Called when any object is added to this root or its sub-namespaces.\n * @param {ReflectionObject} object Object added\n * @returns {undefined}\n * @private\n */\nRoot.prototype._handleAdd = function _handleAdd(object) {\n if (object instanceof Field) {\n\n if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField)\n if (!tryHandleExtension(this, object))\n this.deferred.push(object);\n\n } else if (object instanceof Enum) {\n\n if (exposeRe.test(object.name))\n object.parent[object.name] = object.values; // expose enum values as property of its parent\n\n } else if (!(object instanceof OneOf)) /* everything else is a namespace */ {\n\n if (object instanceof Type) // Try to handle any deferred extensions\n for (var i = 0; i < this.deferred.length;)\n if (tryHandleExtension(this, this.deferred[i]))\n this.deferred.splice(i, 1);\n else\n ++i;\n for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace\n this._handleAdd(object._nestedArray[j]);\n if (exposeRe.test(object.name))\n object.parent[object.name] = object; // expose namespace as property of its parent\n }\n\n if (object instanceof Type || object instanceof Enum || object instanceof Field) {\n // Only store types and enums for quick lookup during resolve.\n this._fullyQualifiedObjects[object.fullName] = object;\n }\n\n // The above also adds uppercased (and thus conflict-free) nested types, services and enums as\n // properties of namespaces just like static code does. This allows using a .d.ts generated for\n // a static module with reflection-based solutions where the condition is met.\n};\n\n/**\n * Called when any object is removed from this root or its sub-namespaces.\n * @param {ReflectionObject} object Object removed\n * @returns {undefined}\n * @private\n */\nRoot.prototype._handleRemove = function _handleRemove(object) {\n if (object instanceof Field) {\n\n if (/* an extension field */ object.extend !== undefined) {\n if (/* already handled */ object.extensionField) { // remove its sister field\n object.extensionField.parent.remove(object.extensionField);\n object.extensionField = null;\n } else { // cancel the extension\n var index = this.deferred.indexOf(object);\n /* istanbul ignore else */\n if (index > -1)\n this.deferred.splice(index, 1);\n }\n }\n\n } else if (object instanceof Enum) {\n\n if (exposeRe.test(object.name))\n delete object.parent[object.name]; // unexpose enum values\n\n } else if (object instanceof Namespace) {\n\n for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace\n this._handleRemove(object._nestedArray[i]);\n\n if (exposeRe.test(object.name))\n delete object.parent[object.name]; // unexpose namespaces\n\n }\n\n delete this._fullyQualifiedObjects[object.fullName];\n};\n\n// Sets up cyclic dependencies (called in index-light)\nRoot._configure = function(Type_, parse_, common_) {\n Type = Type_;\n parse = parse_;\n common = common_;\n};\n","\"use strict\";\nmodule.exports = {};\n\n/**\n * Named roots.\n * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).\n * Can also be used manually to make roots available across modules.\n * @name roots\n * @type {Object.}\n * @example\n * // pbjs -r myroot -o compiled.js ...\n *\n * // in another module:\n * require(\"./compiled.js\");\n *\n * // in any subsequent module:\n * var root = protobuf.roots[\"myroot\"];\n */\n","\"use strict\";\n\n/**\n * Streaming RPC helpers.\n * @namespace\n */\nvar rpc = exports;\n\n/**\n * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.\n * @typedef RPCImpl\n * @type {function}\n * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called\n * @param {Uint8Array} requestData Request data\n * @param {RPCImplCallback} callback Callback function\n * @returns {undefined}\n * @example\n * function rpcImpl(method, requestData, callback) {\n * if (protobuf.util.lcFirst(method.name) !== \"myMethod\") // compatible with static code\n * throw Error(\"no such method\");\n * asynchronouslyObtainAResponse(requestData, function(err, responseData) {\n * callback(err, responseData);\n * });\n * }\n */\n\n/**\n * Node-style callback as used by {@link RPCImpl}.\n * @typedef RPCImplCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error\n * @returns {undefined}\n */\n\nrpc.Service = require(29);\n","\"use strict\";\nmodule.exports = Service;\n\nvar util = require(35);\n\n// Extends EventEmitter\n(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;\n\n/**\n * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.\n *\n * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.\n * @typedef rpc.ServiceMethodCallback\n * @template TRes extends Message\n * @type {function}\n * @param {Error|null} error Error, if any\n * @param {TRes} [response] Response message\n * @returns {undefined}\n */\n\n/**\n * A service method part of a {@link rpc.Service} as created by {@link Service.create}.\n * @typedef rpc.ServiceMethod\n * @template TReq extends Message\n * @template TRes extends Message\n * @type {function}\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message\n * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined`\n */\n\n/**\n * Constructs a new RPC service instance.\n * @classdesc An RPC service as returned by {@link Service#create}.\n * @exports rpc.Service\n * @extends util.EventEmitter\n * @constructor\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n */\nfunction Service(rpcImpl, requestDelimited, responseDelimited) {\n\n if (typeof rpcImpl !== \"function\")\n throw TypeError(\"rpcImpl must be a function\");\n\n util.EventEmitter.call(this);\n\n /**\n * RPC implementation. Becomes `null` once the service is ended.\n * @type {RPCImpl|null}\n */\n this.rpcImpl = rpcImpl;\n\n /**\n * Whether requests are length-delimited.\n * @type {boolean}\n */\n this.requestDelimited = Boolean(requestDelimited);\n\n /**\n * Whether responses are length-delimited.\n * @type {boolean}\n */\n this.responseDelimited = Boolean(responseDelimited);\n}\n\n/**\n * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.\n * @param {Method|rpc.ServiceMethod} method Reflected or static method\n * @param {Constructor} requestCtor Request constructor\n * @param {Constructor} responseCtor Response constructor\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} callback Service callback\n * @returns {undefined}\n * @template TReq extends Message\n * @template TRes extends Message\n */\nService.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {\n\n if (!request)\n throw TypeError(\"request must be specified\");\n\n var self = this;\n if (!callback)\n return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);\n\n if (!self.rpcImpl) {\n setTimeout(function() { callback(Error(\"already ended\")); }, 0);\n return undefined;\n }\n\n try {\n return self.rpcImpl(\n method,\n requestCtor[self.requestDelimited ? \"encodeDelimited\" : \"encode\"](request).finish(),\n function rpcCallback(err, response) {\n\n if (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n\n if (response === null) {\n self.end(/* endedByRPC */ true);\n return undefined;\n }\n\n if (!(response instanceof responseCtor)) {\n try {\n response = responseCtor[self.responseDelimited ? \"decodeDelimited\" : \"decode\"](response);\n } catch (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n }\n\n self.emit(\"data\", response, method);\n return callback(null, response);\n }\n );\n } catch (err) {\n self.emit(\"error\", err, method);\n setTimeout(function() { callback(err); }, 0);\n return undefined;\n }\n};\n\n/**\n * Ends this service and emits the `end` event.\n * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.\n * @returns {rpc.Service} `this`\n */\nService.prototype.end = function end(endedByRPC) {\n if (this.rpcImpl) {\n if (!endedByRPC) // signal end to rpcImpl\n this.rpcImpl(null, null, null);\n this.rpcImpl = null;\n this.emit(\"end\").off();\n }\n return this;\n};\n","\"use strict\";\nmodule.exports = Service;\n\n// extends Namespace\nvar Namespace = require(21);\n((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = \"Service\";\n\nvar Method = require(20),\n util = require(33),\n rpc = require(28);\n\n/**\n * Constructs a new service instance.\n * @classdesc Reflected service.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Service name\n * @param {Object.} [options] Service options\n * @throws {TypeError} If arguments are invalid\n */\nfunction Service(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Service methods.\n * @type {Object.}\n */\n this.methods = {}; // toJSON, marker\n\n /**\n * Cached methods as an array.\n * @type {Method[]|null}\n * @private\n */\n this._methodsArray = null;\n}\n\n/**\n * Service descriptor.\n * @interface IService\n * @extends INamespace\n * @property {Object.} methods Method descriptors\n */\n\n/**\n * Constructs a service from a service descriptor.\n * @param {string} name Service name\n * @param {IService} json Service descriptor\n * @returns {Service} Created service\n * @throws {TypeError} If arguments are invalid\n */\nService.fromJSON = function fromJSON(name, json) {\n var service = new Service(name, json.options);\n /* istanbul ignore else */\n if (json.methods)\n for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i)\n service.add(Method.fromJSON(names[i], json.methods[names[i]]));\n if (json.nested)\n service.addJSON(json.nested);\n if (json.edition)\n service._edition = json.edition;\n service.comment = json.comment;\n service._defaultEdition = \"proto3\"; // For backwards-compatibility.\n return service;\n};\n\n/**\n * Converts this service to a service descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IService} Service descriptor\n */\nService.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"edition\" , this._editionToJSON(),\n \"options\" , inherited && inherited.options || undefined,\n \"methods\" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {},\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Methods of this service as an array for iteration.\n * @name Service#methodsArray\n * @type {Method[]}\n * @readonly\n */\nObject.defineProperty(Service.prototype, \"methodsArray\", {\n get: function() {\n return this._methodsArray || (this._methodsArray = util.toArray(this.methods));\n }\n});\n\nfunction clearCache(service) {\n service._methodsArray = null;\n return service;\n}\n\n/**\n * @override\n */\nService.prototype.get = function get(name) {\n return this.methods[name]\n || Namespace.prototype.get.call(this, name);\n};\n\n/**\n * @override\n */\nService.prototype.resolveAll = function resolveAll() {\n if (!this._needsRecursiveResolve) return this;\n\n Namespace.prototype.resolve.call(this);\n var methods = this.methodsArray;\n for (var i = 0; i < methods.length; ++i)\n methods[i].resolve();\n return this;\n};\n\n/**\n * @override\n */\nService.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) {\n if (!this._needsRecursiveFeatureResolution) return this;\n\n edition = this._edition || edition;\n\n Namespace.prototype._resolveFeaturesRecursive.call(this, edition);\n this.methodsArray.forEach(method => {\n method._resolveFeaturesRecursive(edition);\n });\n return this;\n};\n\n/**\n * @override\n */\nService.prototype.add = function add(object) {\n\n /* istanbul ignore if */\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Method) {\n this.methods[object.name] = object;\n object.parent = this;\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * @override\n */\nService.prototype.remove = function remove(object) {\n if (object instanceof Method) {\n\n /* istanbul ignore if */\n if (this.methods[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.methods[object.name];\n object.parent = null;\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Creates a runtime service using the specified rpc implementation.\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed.\n */\nService.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) {\n var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);\n for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) {\n var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\\w_]/g, \"\");\n rpcService[methodName] = util.codegen([\"r\",\"c\"], util.isReserved(methodName) ? methodName + \"_\" : methodName)(\"return this.rpcCall(m,q,s,r,c)\")({\n m: method,\n q: method.resolvedRequestType.ctor,\n s: method.resolvedResponseType.ctor\n });\n }\n return rpcService;\n};\n","\"use strict\";\nmodule.exports = Type;\n\n// extends Namespace\nvar Namespace = require(21);\n((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = \"Type\";\n\nvar Enum = require(14),\n OneOf = require(23),\n Field = require(15),\n MapField = require(18),\n Service = require(30),\n Message = require(19),\n Reader = require(24),\n Writer = require(38),\n util = require(33),\n encoder = require(13),\n decoder = require(12),\n verifier = require(36),\n converter = require(11),\n wrappers = require(37);\n\n/**\n * Constructs a new reflected message type instance.\n * @classdesc Reflected message type.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Message name\n * @param {Object.} [options] Declared options\n */\nfunction Type(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Message fields.\n * @type {Object.}\n */\n this.fields = {}; // toJSON, marker\n\n /**\n * Oneofs declared within this namespace, if any.\n * @type {Object.}\n */\n this.oneofs = undefined; // toJSON\n\n /**\n * Extension ranges, if any.\n * @type {number[][]}\n */\n this.extensions = undefined; // toJSON\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n /*?\n * Whether this type is a legacy group.\n * @type {boolean|undefined}\n */\n this.group = undefined; // toJSON\n\n /**\n * Cached fields by id.\n * @type {Object.|null}\n * @private\n */\n this._fieldsById = null;\n\n /**\n * Cached fields as an array.\n * @type {Field[]|null}\n * @private\n */\n this._fieldsArray = null;\n\n /**\n * Cached oneofs as an array.\n * @type {OneOf[]|null}\n * @private\n */\n this._oneofsArray = null;\n\n /**\n * Cached constructor.\n * @type {Constructor<{}>}\n * @private\n */\n this._ctor = null;\n}\n\nObject.defineProperties(Type.prototype, {\n\n /**\n * Message fields by id.\n * @name Type#fieldsById\n * @type {Object.}\n * @readonly\n */\n fieldsById: {\n get: function() {\n\n /* istanbul ignore if */\n if (this._fieldsById)\n return this._fieldsById;\n\n this._fieldsById = {};\n for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {\n var field = this.fields[names[i]],\n id = field.id;\n\n /* istanbul ignore if */\n if (this._fieldsById[id])\n throw Error(\"duplicate id \" + id + \" in \" + this);\n\n this._fieldsById[id] = field;\n }\n return this._fieldsById;\n }\n },\n\n /**\n * Fields of this message as an array for iteration.\n * @name Type#fieldsArray\n * @type {Field[]}\n * @readonly\n */\n fieldsArray: {\n get: function() {\n return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));\n }\n },\n\n /**\n * Oneofs of this message as an array for iteration.\n * @name Type#oneofsArray\n * @type {OneOf[]}\n * @readonly\n */\n oneofsArray: {\n get: function() {\n return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));\n }\n },\n\n /**\n * The registered constructor, if any registered, otherwise a generic constructor.\n * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.\n * @name Type#ctor\n * @type {Constructor<{}>}\n */\n ctor: {\n get: function() {\n return this._ctor || (this.ctor = Type.generateConstructor(this)());\n },\n set: function(ctor) {\n\n // Ensure proper prototype\n var prototype = ctor.prototype;\n if (!(prototype instanceof Message)) {\n (ctor.prototype = new Message()).constructor = ctor;\n util.merge(ctor.prototype, prototype);\n }\n\n // Classes and messages reference their reflected type\n ctor.$type = ctor.prototype.$type = this;\n\n // Mix in static methods\n util.merge(ctor, Message, true);\n\n this._ctor = ctor;\n\n // Messages have non-enumerable default values on their prototype\n var i = 0;\n for (; i < /* initializes */ this.fieldsArray.length; ++i)\n this._fieldsArray[i].resolve(); // ensures a proper value\n\n // Messages have non-enumerable getters and setters for each virtual oneof field\n var ctorProperties = {};\n for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i)\n ctorProperties[this._oneofsArray[i].resolve().name] = {\n get: util.oneOfGetter(this._oneofsArray[i].oneof),\n set: util.oneOfSetter(this._oneofsArray[i].oneof)\n };\n if (i)\n Object.defineProperties(ctor.prototype, ctorProperties);\n }\n }\n});\n\n/**\n * Generates a constructor function for the specified type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nType.generateConstructor = function generateConstructor(mtype) {\n /* eslint-disable no-unexpected-multiline */\n var gen = util.codegen([\"p\"], mtype.name);\n // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype\n for (var i = 0, field; i < mtype.fieldsArray.length; ++i)\n if ((field = mtype._fieldsArray[i]).map) gen\n (\"this%s={}\", util.safeProp(field.name));\n else if (field.repeated) gen\n (\"this%s=[]\", util.safeProp(field.name));\n return gen\n (\"if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors\n * @property {Object.} fields Field descriptors\n * @property {number[][]} [extensions] Extension ranges\n * @property {Array.} [reserved] Reserved ranges\n * @property {boolean} [group=false] Whether a legacy group or not\n */\n\n/**\n * Creates a message type from a message type descriptor.\n * @param {string} name Message name\n * @param {IType} json Message type descriptor\n * @returns {Type} Created message type\n */\nType.fromJSON = function fromJSON(name, json) {\n var type = new Type(name, json.options);\n type.extensions = json.extensions;\n type.reserved = json.reserved;\n var names = Object.keys(json.fields),\n i = 0;\n for (; i < names.length; ++i)\n type.add(\n ( typeof json.fields[names[i]].keyType !== \"undefined\"\n ? MapField.fromJSON\n : Field.fromJSON )(names[i], json.fields[names[i]])\n );\n if (json.oneofs)\n for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i)\n type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]]));\n if (json.nested)\n for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) {\n var nested = json.nested[names[i]];\n type.add( // most to least likely\n ( nested.id !== undefined\n ? Field.fromJSON\n : nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n if (json.extensions && json.extensions.length)\n type.extensions = json.extensions;\n if (json.reserved && json.reserved.length)\n type.reserved = json.reserved;\n if (json.group)\n type.group = true;\n if (json.comment)\n type.comment = json.comment;\n if (json.edition)\n type._edition = json.edition;\n type._defaultEdition = \"proto3\"; // For backwards-compatibility.\n return type;\n};\n\n/**\n * Converts this message type to a message type descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IType} Message type descriptor\n */\nType.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"edition\" , this._editionToJSON(),\n \"options\" , inherited && inherited.options || undefined,\n \"oneofs\" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),\n \"fields\" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {},\n \"extensions\" , this.extensions && this.extensions.length ? this.extensions : undefined,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"group\" , this.group || undefined,\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nType.prototype.resolveAll = function resolveAll() {\n if (!this._needsRecursiveResolve) return this;\n\n Namespace.prototype.resolveAll.call(this);\n var oneofs = this.oneofsArray; i = 0;\n while (i < oneofs.length)\n oneofs[i++].resolve();\n var fields = this.fieldsArray, i = 0;\n while (i < fields.length)\n fields[i++].resolve();\n return this;\n};\n\n/**\n * @override\n */\nType.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) {\n if (!this._needsRecursiveFeatureResolution) return this;\n\n edition = this._edition || edition;\n\n Namespace.prototype._resolveFeaturesRecursive.call(this, edition);\n this.oneofsArray.forEach(oneof => {\n oneof._resolveFeatures(edition);\n });\n this.fieldsArray.forEach(field => {\n field._resolveFeatures(edition);\n });\n return this;\n};\n\n/**\n * @override\n */\nType.prototype.get = function get(name) {\n return this.fields[name]\n || this.oneofs && this.oneofs[name]\n || this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Adds a nested object to this type.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id\n */\nType.prototype.add = function add(object) {\n\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Field && object.extend === undefined) {\n // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.\n // The root object takes care of adding distinct sister-fields to the respective extended\n // type instead.\n\n // avoids calling the getter if not absolutely necessary because it's called quite frequently\n if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id])\n throw Error(\"duplicate id \" + object.id + \" in \" + this);\n if (this.isReservedId(object.id))\n throw Error(\"id \" + object.id + \" is reserved in \" + this);\n if (this.isReservedName(object.name))\n throw Error(\"name '\" + object.name + \"' is reserved in \" + this);\n\n if (object.parent)\n object.parent.remove(object);\n this.fields[object.name] = object;\n object.message = this;\n object.onAdd(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n if (!this.oneofs)\n this.oneofs = {};\n this.oneofs[object.name] = object;\n object.onAdd(this);\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * Removes a nested object from this type.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this type\n */\nType.prototype.remove = function remove(object) {\n if (object instanceof Field && object.extend === undefined) {\n // See Type#add for the reason why extension fields are excluded here.\n\n /* istanbul ignore if */\n if (!this.fields || this.fields[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.fields[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n\n /* istanbul ignore if */\n if (!this.oneofs || this.oneofs[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.oneofs[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message<{}>} Message instance\n */\nType.prototype.create = function create(properties) {\n return new this.ctor(properties);\n};\n\n/**\n * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.\n * @returns {Type} `this`\n */\nType.prototype.setup = function setup() {\n // Sets up everything at once so that the prototype chain does not have to be re-evaluated\n // multiple times (V8, soft-deopt prototype-check).\n\n var fullName = this.fullName,\n types = [];\n for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i)\n types.push(this._fieldsArray[i].resolve().resolvedType);\n\n // Replace setup methods with type-specific generated functions\n this.encode = encoder(this)({\n Writer : Writer,\n types : types,\n util : util\n });\n this.decode = decoder(this)({\n Reader : Reader,\n types : types,\n util : util\n });\n this.verify = verifier(this)({\n types : types,\n util : util\n });\n this.fromObject = converter.fromObject(this)({\n types : types,\n util : util\n });\n this.toObject = converter.toObject(this)({\n types : types,\n util : util\n });\n\n // Inject custom wrappers for common types\n var wrapper = wrappers[fullName];\n if (wrapper) {\n var originalThis = Object.create(this);\n // if (wrapper.fromObject) {\n originalThis.fromObject = this.fromObject;\n this.fromObject = wrapper.fromObject.bind(originalThis);\n // }\n // if (wrapper.toObject) {\n originalThis.toObject = this.toObject;\n this.toObject = wrapper.toObject.bind(originalThis);\n // }\n }\n\n return this;\n};\n\n/**\n * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encode = function encode_setup(message, writer) {\n return this.setup().encode(message, writer); // overrides this method\n};\n\n/**\n * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encodeDelimited = function encodeDelimited(message, writer) {\n return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();\n};\n\n/**\n * Decodes a message of this type.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @param {number} [length] Length of the message, if known beforehand\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError<{}>} If required fields are missing\n */\nType.prototype.decode = function decode_setup(reader, length) {\n return this.setup().decode(reader, length); // overrides this method\n};\n\n/**\n * Decodes a message of this type preceeded by its byte length as a varint.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError} If required fields are missing\n */\nType.prototype.decodeDelimited = function decodeDelimited(reader) {\n if (!(reader instanceof Reader))\n reader = Reader.create(reader);\n return this.decode(reader, reader.uint32());\n};\n\n/**\n * Verifies that field values are valid and that required fields are present.\n * @param {Object.} message Plain object to verify\n * @returns {null|string} `null` if valid, otherwise the reason why it is not\n */\nType.prototype.verify = function verify_setup(message) {\n return this.setup().verify(message); // overrides this method\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object to convert\n * @returns {Message<{}>} Message instance\n */\nType.prototype.fromObject = function fromObject(object) {\n return this.setup().fromObject(object);\n};\n\n/**\n * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}.\n * @interface IConversionOptions\n * @property {Function} [longs] Long conversion type.\n * Valid values are `String` and `Number` (the global types).\n * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.\n * @property {Function} [enums] Enum value conversion type.\n * Only valid value is `String` (the global type).\n * Defaults to copy the present value, which is the numeric id.\n * @property {Function} [bytes] Bytes value conversion type.\n * Valid values are `Array` and (a base64 encoded) `String` (the global types).\n * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.\n * @property {boolean} [defaults=false] Also sets default values on the resulting object\n * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false`\n * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false`\n * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any\n * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings\n */\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n */\nType.prototype.toObject = function toObject(message, options) {\n return this.setup().toObject(message, options);\n};\n\n/**\n * Decorator function as returned by {@link Type.d} (TypeScript).\n * @typedef TypeDecorator\n * @type {function}\n * @param {Constructor} target Target constructor\n * @returns {undefined}\n * @template T extends Message\n */\n\n/**\n * Type decorator (TypeScript).\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {TypeDecorator} Decorator function\n * @template T extends Message\n */\nType.d = function decorateType(typeName) {\n return function typeDecorator(target) {\n util.decorateType(target, typeName);\n };\n};\n","\"use strict\";\n\n/**\n * Common type constants.\n * @namespace\n */\nvar types = exports;\n\nvar util = require(33);\n\nvar s = [\n \"double\", // 0\n \"float\", // 1\n \"int32\", // 2\n \"uint32\", // 3\n \"sint32\", // 4\n \"fixed32\", // 5\n \"sfixed32\", // 6\n \"int64\", // 7\n \"uint64\", // 8\n \"sint64\", // 9\n \"fixed64\", // 10\n \"sfixed64\", // 11\n \"bool\", // 12\n \"string\", // 13\n \"bytes\" // 14\n];\n\nfunction bake(values, offset) {\n var i = 0, o = {};\n offset |= 0;\n while (i < values.length) o[s[i + offset]] = values[i++];\n return o;\n}\n\n/**\n * Basic type wire types.\n * @type {Object.}\n * @const\n * @property {number} double=1 Fixed64 wire type\n * @property {number} float=5 Fixed32 wire type\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n * @property {number} string=2 Ldelim wire type\n * @property {number} bytes=2 Ldelim wire type\n */\ntypes.basic = bake([\n /* double */ 1,\n /* float */ 5,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0,\n /* string */ 2,\n /* bytes */ 2\n]);\n\n/**\n * Basic type defaults.\n * @type {Object.}\n * @const\n * @property {number} double=0 Double default\n * @property {number} float=0 Float default\n * @property {number} int32=0 Int32 default\n * @property {number} uint32=0 Uint32 default\n * @property {number} sint32=0 Sint32 default\n * @property {number} fixed32=0 Fixed32 default\n * @property {number} sfixed32=0 Sfixed32 default\n * @property {number} int64=0 Int64 default\n * @property {number} uint64=0 Uint64 default\n * @property {number} sint64=0 Sint32 default\n * @property {number} fixed64=0 Fixed64 default\n * @property {number} sfixed64=0 Sfixed64 default\n * @property {boolean} bool=false Bool default\n * @property {string} string=\"\" String default\n * @property {Array.} bytes=Array(0) Bytes default\n * @property {null} message=null Message default\n */\ntypes.defaults = bake([\n /* double */ 0,\n /* float */ 0,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 0,\n /* sfixed32 */ 0,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 0,\n /* sfixed64 */ 0,\n /* bool */ false,\n /* string */ \"\",\n /* bytes */ util.emptyArray,\n /* message */ null\n]);\n\n/**\n * Basic long type wire types.\n * @type {Object.}\n * @const\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n */\ntypes.long = bake([\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1\n], 7);\n\n/**\n * Allowed types for map keys with their associated wire type.\n * @type {Object.}\n * @const\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n * @property {number} string=2 Ldelim wire type\n */\ntypes.mapKey = bake([\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0,\n /* string */ 2\n], 2);\n\n/**\n * Allowed types for packed repeated fields with their associated wire type.\n * @type {Object.}\n * @const\n * @property {number} double=1 Fixed64 wire type\n * @property {number} float=5 Fixed32 wire type\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n */\ntypes.packed = bake([\n /* double */ 1,\n /* float */ 5,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0\n]);\n","\"use strict\";\n\n/**\n * Various utility functions.\n * @namespace\n */\nvar util = module.exports = require(35);\n\nvar roots = require(27);\n\nvar Type, // cyclic\n Enum;\n\nutil.codegen = require(3);\nutil.fetch = require(5);\nutil.path = require(8);\n\n/**\n * Node's fs module if available.\n * @type {Object.}\n */\nutil.fs = util.inquire(\"fs\");\n\n/**\n * Converts an object's values to an array.\n * @param {Object.} object Object to convert\n * @returns {Array.<*>} Converted array\n */\nutil.toArray = function toArray(object) {\n if (object) {\n var keys = Object.keys(object),\n array = new Array(keys.length),\n index = 0;\n while (index < keys.length)\n array[index] = object[keys[index++]];\n return array;\n }\n return [];\n};\n\n/**\n * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values.\n * @param {Array.<*>} array Array to convert\n * @returns {Object.} Converted object\n */\nutil.toObject = function toObject(array) {\n var object = {},\n index = 0;\n while (index < array.length) {\n var key = array[index++],\n val = array[index++];\n if (val !== undefined)\n object[key] = val;\n }\n return object;\n};\n\nvar safePropBackslashRe = /\\\\/g,\n safePropQuoteRe = /\"/g;\n\n/**\n * Tests whether the specified name is a reserved word in JS.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nutil.isReserved = function isReserved(name) {\n return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name);\n};\n\n/**\n * Returns a safe property accessor for the specified property name.\n * @param {string} prop Property name\n * @returns {string} Safe accessor\n */\nutil.safeProp = function safeProp(prop) {\n if (!/^[$\\w_]+$/.test(prop) || util.isReserved(prop))\n return \"[\\\"\" + prop.replace(safePropBackslashRe, \"\\\\\\\\\").replace(safePropQuoteRe, \"\\\\\\\"\") + \"\\\"]\";\n return \".\" + prop;\n};\n\n/**\n * Converts the first character of a string to upper case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.ucFirst = function ucFirst(str) {\n return str.charAt(0).toUpperCase() + str.substring(1);\n};\n\nvar camelCaseRe = /_([a-z])/g;\n\n/**\n * Converts a string to camel case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.camelCase = function camelCase(str) {\n return str.substring(0, 1)\n + str.substring(1)\n .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); });\n};\n\n/**\n * Compares reflected fields by id.\n * @param {Field} a First field\n * @param {Field} b Second field\n * @returns {number} Comparison value\n */\nutil.compareFieldsById = function compareFieldsById(a, b) {\n return a.id - b.id;\n};\n\n/**\n * Decorator helper for types (TypeScript).\n * @param {Constructor} ctor Constructor function\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {Type} Reflected type\n * @template T extends Message\n * @property {Root} root Decorators root\n */\nutil.decorateType = function decorateType(ctor, typeName) {\n\n /* istanbul ignore if */\n if (ctor.$type) {\n if (typeName && ctor.$type.name !== typeName) {\n util.decorateRoot.remove(ctor.$type);\n ctor.$type.name = typeName;\n util.decorateRoot.add(ctor.$type);\n }\n return ctor.$type;\n }\n\n /* istanbul ignore next */\n if (!Type)\n Type = require(31);\n\n var type = new Type(typeName || ctor.name);\n util.decorateRoot.add(type);\n type.ctor = ctor; // sets up .encode, .decode etc.\n Object.defineProperty(ctor, \"$type\", { value: type, enumerable: false });\n Object.defineProperty(ctor.prototype, \"$type\", { value: type, enumerable: false });\n return type;\n};\n\nvar decorateEnumIndex = 0;\n\n/**\n * Decorator helper for enums (TypeScript).\n * @param {Object} object Enum object\n * @returns {Enum} Reflected enum\n */\nutil.decorateEnum = function decorateEnum(object) {\n\n /* istanbul ignore if */\n if (object.$type)\n return object.$type;\n\n /* istanbul ignore next */\n if (!Enum)\n Enum = require(14);\n\n var enm = new Enum(\"Enum\" + decorateEnumIndex++, object);\n util.decorateRoot.add(enm);\n Object.defineProperty(object, \"$type\", { value: enm, enumerable: false });\n return enm;\n};\n\n\n/**\n * Sets the value of a property by property path. If a value already exists, it is turned to an array\n * @param {Object.} dst Destination object\n * @param {string} path dot '.' delimited path of the property to set\n * @param {Object} value the value to set\n * @param {boolean|undefined} [ifNotSet] Sets the option only if it isn't currently set\n * @returns {Object.} Destination object\n */\nutil.setProperty = function setProperty(dst, path, value, ifNotSet) {\n function setProp(dst, path, value) {\n var part = path.shift();\n if (part === \"__proto__\" || part === \"prototype\") {\n return dst;\n }\n if (path.length > 0) {\n dst[part] = setProp(dst[part] || {}, path, value);\n } else {\n var prevValue = dst[part];\n if (prevValue && ifNotSet)\n return dst;\n if (prevValue)\n value = [].concat(prevValue).concat(value);\n dst[part] = value;\n }\n return dst;\n }\n\n if (typeof dst !== \"object\")\n throw TypeError(\"dst must be an object\");\n if (!path)\n throw TypeError(\"path must be specified\");\n\n path = path.split(\".\");\n return setProp(dst, path, value);\n};\n\n/**\n * Decorator root (TypeScript).\n * @name util.decorateRoot\n * @type {Root}\n * @readonly\n */\nObject.defineProperty(util, \"decorateRoot\", {\n get: function() {\n return roots[\"decorated\"] || (roots[\"decorated\"] = new (require(26))());\n }\n});\n","\"use strict\";\nmodule.exports = LongBits;\n\nvar util = require(35);\n\n/**\n * Constructs new long bits.\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @constructor\n * @param {number} lo Low 32 bits, unsigned\n * @param {number} hi High 32 bits, unsigned\n */\nfunction LongBits(lo, hi) {\n\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits.\n * @type {number}\n */\n this.lo = lo >>> 0;\n\n /**\n * High bits.\n * @type {number}\n */\n this.hi = hi >>> 0;\n}\n\n/**\n * Zero bits.\n * @memberof util.LongBits\n * @type {util.LongBits}\n */\nvar zero = LongBits.zero = new LongBits(0, 0);\n\nzero.toNumber = function() { return 0; };\nzero.zzEncode = zero.zzDecode = function() { return this; };\nzero.length = function() { return 1; };\n\n/**\n * Zero hash.\n * @memberof util.LongBits\n * @type {string}\n */\nvar zeroHash = LongBits.zeroHash = \"\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n/**\n * Constructs new long bits from the specified number.\n * @param {number} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.fromNumber = function fromNumber(value) {\n if (value === 0)\n return zero;\n var sign = value < 0;\n if (sign)\n value = -value;\n var lo = value >>> 0,\n hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295)\n hi = 0;\n }\n }\n return new LongBits(lo, hi);\n};\n\n/**\n * Constructs new long bits from a number, long or string.\n * @param {Long|number|string} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.from = function from(value) {\n if (typeof value === \"number\")\n return LongBits.fromNumber(value);\n if (util.isString(value)) {\n /* istanbul ignore else */\n if (util.Long)\n value = util.Long.fromString(value);\n else\n return LongBits.fromNumber(parseInt(value, 10));\n }\n return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n};\n\n/**\n * Converts this long bits to a possibly unsafe JavaScript number.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {number} Possibly unsafe number\n */\nLongBits.prototype.toNumber = function toNumber(unsigned) {\n if (!unsigned && this.hi >>> 31) {\n var lo = ~this.lo + 1 >>> 0,\n hi = ~this.hi >>> 0;\n if (!lo)\n hi = hi + 1 >>> 0;\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n};\n\n/**\n * Converts this long bits to a long.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long} Long\n */\nLongBits.prototype.toLong = function toLong(unsigned) {\n return util.Long\n ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))\n /* istanbul ignore next */\n : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };\n};\n\nvar charCodeAt = String.prototype.charCodeAt;\n\n/**\n * Constructs new long bits from the specified 8 characters long hash.\n * @param {string} hash Hash\n * @returns {util.LongBits} Bits\n */\nLongBits.fromHash = function fromHash(hash) {\n if (hash === zeroHash)\n return zero;\n return new LongBits(\n ( charCodeAt.call(hash, 0)\n | charCodeAt.call(hash, 1) << 8\n | charCodeAt.call(hash, 2) << 16\n | charCodeAt.call(hash, 3) << 24) >>> 0\n ,\n ( charCodeAt.call(hash, 4)\n | charCodeAt.call(hash, 5) << 8\n | charCodeAt.call(hash, 6) << 16\n | charCodeAt.call(hash, 7) << 24) >>> 0\n );\n};\n\n/**\n * Converts this long bits to a 8 characters long hash.\n * @returns {string} Hash\n */\nLongBits.prototype.toHash = function toHash() {\n return String.fromCharCode(\n this.lo & 255,\n this.lo >>> 8 & 255,\n this.lo >>> 16 & 255,\n this.lo >>> 24 ,\n this.hi & 255,\n this.hi >>> 8 & 255,\n this.hi >>> 16 & 255,\n this.hi >>> 24\n );\n};\n\n/**\n * Zig-zag encodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzEncode = function zzEncode() {\n var mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = ( this.lo << 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Zig-zag decodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzDecode = function zzDecode() {\n var mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = ( this.hi >>> 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Calculates the length of this longbits when encoded as a varint.\n * @returns {number} Length\n */\nLongBits.prototype.length = function length() {\n var part0 = this.lo,\n part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,\n part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n};\n","\"use strict\";\nvar util = exports;\n\n// used to return a Promise where callback is omitted\nutil.asPromise = require(1);\n\n// converts to / from base64 encoded strings\nutil.base64 = require(2);\n\n// base class of rpc.Service\nutil.EventEmitter = require(4);\n\n// float handling accross browsers\nutil.float = require(6);\n\n// requires modules optionally and hides the call from bundlers\nutil.inquire = require(7);\n\n// converts to / from utf8 encoded strings\nutil.utf8 = require(10);\n\n// provides a node-like buffer pool in the browser\nutil.pool = require(9);\n\n// utility to work with the low and high bits of a 64 bit value\nutil.LongBits = require(34);\n\n/**\n * Whether running within node or not.\n * @memberof util\n * @type {boolean}\n */\nutil.isNode = Boolean(typeof global !== \"undefined\"\n && global\n && global.process\n && global.process.versions\n && global.process.versions.node);\n\n/**\n * Global object reference.\n * @memberof util\n * @type {Object}\n */\nutil.global = util.isNode && global\n || typeof window !== \"undefined\" && window\n || typeof self !== \"undefined\" && self\n || this; // eslint-disable-line no-invalid-this\n\n/**\n * An immuable empty array.\n * @memberof util\n * @type {Array.<*>}\n * @const\n */\nutil.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes\n\n/**\n * An immutable empty object.\n * @type {Object}\n * @const\n */\nutil.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes\n\n/**\n * Tests if the specified value is an integer.\n * @function\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is an integer\n */\nutil.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {\n return typeof value === \"number\" && isFinite(value) && Math.floor(value) === value;\n};\n\n/**\n * Tests if the specified value is a string.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a string\n */\nutil.isString = function isString(value) {\n return typeof value === \"string\" || value instanceof String;\n};\n\n/**\n * Tests if the specified value is a non-null object.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a non-null object\n */\nutil.isObject = function isObject(value) {\n return value && typeof value === \"object\";\n};\n\n/**\n * Checks if a property on a message is considered to be present.\n * This is an alias of {@link util.isSet}.\n * @function\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isset =\n\n/**\n * Checks if a property on a message is considered to be present.\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isSet = function isSet(obj, prop) {\n var value = obj[prop];\n if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins\n return typeof value !== \"object\" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;\n return false;\n};\n\n/**\n * Any compatible Buffer instance.\n * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.\n * @interface Buffer\n * @extends Uint8Array\n */\n\n/**\n * Node's Buffer class if available.\n * @type {Constructor}\n */\nutil.Buffer = (function() {\n try {\n var Buffer = util.inquire(\"buffer\").Buffer;\n // refuse to use non-node buffers if not explicitly assigned (perf reasons):\n return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;\n } catch (e) {\n /* istanbul ignore next */\n return null;\n }\n})();\n\n// Internal alias of or polyfull for Buffer.from.\nutil._Buffer_from = null;\n\n// Internal alias of or polyfill for Buffer.allocUnsafe.\nutil._Buffer_allocUnsafe = null;\n\n/**\n * Creates a new buffer of whatever type supported by the environment.\n * @param {number|number[]} [sizeOrArray=0] Buffer size or number array\n * @returns {Uint8Array|Buffer} Buffer\n */\nutil.newBuffer = function newBuffer(sizeOrArray) {\n /* istanbul ignore next */\n return typeof sizeOrArray === \"number\"\n ? util.Buffer\n ? util._Buffer_allocUnsafe(sizeOrArray)\n : new util.Array(sizeOrArray)\n : util.Buffer\n ? util._Buffer_from(sizeOrArray)\n : typeof Uint8Array === \"undefined\"\n ? sizeOrArray\n : new Uint8Array(sizeOrArray);\n};\n\n/**\n * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.\n * @type {Constructor}\n */\nutil.Array = typeof Uint8Array !== \"undefined\" ? Uint8Array /* istanbul ignore next */ : Array;\n\n/**\n * Any compatible Long instance.\n * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.\n * @interface Long\n * @property {number} low Low bits\n * @property {number} high High bits\n * @property {boolean} unsigned Whether unsigned or not\n */\n\n/**\n * Long.js's Long class if available.\n * @type {Constructor}\n */\nutil.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long\n || /* istanbul ignore next */ util.global.Long\n || util.inquire(\"long\");\n\n/**\n * Regular expression used to verify 2 bit (`bool`) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key2Re = /^true|false|0|1$/;\n\n/**\n * Regular expression used to verify 32 bit (`int32` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key32Re = /^-?(?:0|[1-9][0-9]*)$/;\n\n/**\n * Regular expression used to verify 64 bit (`int64` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key64Re = /^(?:[\\\\x00-\\\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;\n\n/**\n * Converts a number or long to an 8 characters long hash string.\n * @param {Long|number} value Value to convert\n * @returns {string} Hash\n */\nutil.longToHash = function longToHash(value) {\n return value\n ? util.LongBits.from(value).toHash()\n : util.LongBits.zeroHash;\n};\n\n/**\n * Converts an 8 characters long hash string to a long or number.\n * @param {string} hash Hash\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long|number} Original value\n */\nutil.longFromHash = function longFromHash(hash, unsigned) {\n var bits = util.LongBits.fromHash(hash);\n if (util.Long)\n return util.Long.fromBits(bits.lo, bits.hi, unsigned);\n return bits.toNumber(Boolean(unsigned));\n};\n\n/**\n * Merges the properties of the source object into the destination object.\n * @memberof util\n * @param {Object.} dst Destination object\n * @param {Object.} src Source object\n * @param {boolean} [ifNotSet=false] Merges only if the key is not already set\n * @returns {Object.} Destination object\n */\nfunction merge(dst, src, ifNotSet) { // used by converters\n for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)\n if (dst[keys[i]] === undefined || !ifNotSet)\n dst[keys[i]] = src[keys[i]];\n return dst;\n}\n\nutil.merge = merge;\n\n/**\n * Converts the first character of a string to lower case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.lcFirst = function lcFirst(str) {\n return str.charAt(0).toLowerCase() + str.substring(1);\n};\n\n/**\n * Creates a custom error constructor.\n * @memberof util\n * @param {string} name Error name\n * @returns {Constructor} Custom error constructor\n */\nfunction newError(name) {\n\n function CustomError(message, properties) {\n\n if (!(this instanceof CustomError))\n return new CustomError(message, properties);\n\n // Error.call(this, message);\n // ^ just returns a new error instance because the ctor can be called as a function\n\n Object.defineProperty(this, \"message\", { get: function() { return message; } });\n\n /* istanbul ignore next */\n if (Error.captureStackTrace) // node\n Error.captureStackTrace(this, CustomError);\n else\n Object.defineProperty(this, \"stack\", { value: new Error().stack || \"\" });\n\n if (properties)\n merge(this, properties);\n }\n\n CustomError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: CustomError,\n writable: true,\n enumerable: false,\n configurable: true,\n },\n name: {\n get: function get() { return name; },\n set: undefined,\n enumerable: false,\n // configurable: false would accurately preserve the behavior of\n // the original, but I'm guessing that was not intentional.\n // For an actual error subclass, this property would\n // be configurable.\n configurable: true,\n },\n toString: {\n value: function value() { return this.name + \": \" + this.message; },\n writable: true,\n enumerable: false,\n configurable: true,\n },\n });\n\n return CustomError;\n}\n\nutil.newError = newError;\n\n/**\n * Constructs a new protocol error.\n * @classdesc Error subclass indicating a protocol specifc error.\n * @memberof util\n * @extends Error\n * @template T extends Message\n * @constructor\n * @param {string} message Error message\n * @param {Object.} [properties] Additional properties\n * @example\n * try {\n * MyMessage.decode(someBuffer); // throws if required fields are missing\n * } catch (e) {\n * if (e instanceof ProtocolError && e.instance)\n * console.log(\"decoded so far: \" + JSON.stringify(e.instance));\n * }\n */\nutil.ProtocolError = newError(\"ProtocolError\");\n\n/**\n * So far decoded message instance.\n * @name util.ProtocolError#instance\n * @type {Message}\n */\n\n/**\n * A OneOf getter as returned by {@link util.oneOfGetter}.\n * @typedef OneOfGetter\n * @type {function}\n * @returns {string|undefined} Set field name, if any\n */\n\n/**\n * Builds a getter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfGetter} Unbound getter\n */\nutil.oneOfGetter = function getOneOf(fieldNames) {\n var fieldMap = {};\n for (var i = 0; i < fieldNames.length; ++i)\n fieldMap[fieldNames[i]] = 1;\n\n /**\n * @returns {string|undefined} Set field name, if any\n * @this Object\n * @ignore\n */\n return function() { // eslint-disable-line consistent-return\n for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)\n if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)\n return keys[i];\n };\n};\n\n/**\n * A OneOf setter as returned by {@link util.oneOfSetter}.\n * @typedef OneOfSetter\n * @type {function}\n * @param {string|undefined} value Field name\n * @returns {undefined}\n */\n\n/**\n * Builds a setter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfSetter} Unbound setter\n */\nutil.oneOfSetter = function setOneOf(fieldNames) {\n\n /**\n * @param {string} name Field name\n * @returns {undefined}\n * @this Object\n * @ignore\n */\n return function(name) {\n for (var i = 0; i < fieldNames.length; ++i)\n if (fieldNames[i] !== name)\n delete this[fieldNames[i]];\n };\n};\n\n/**\n * Default conversion options used for {@link Message#toJSON} implementations.\n *\n * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:\n *\n * - Longs become strings\n * - Enums become string keys\n * - Bytes become base64 encoded strings\n * - (Sub-)Messages become plain objects\n * - Maps become plain objects with all string keys\n * - Repeated fields become arrays\n * - NaN and Infinity for float and double fields become strings\n *\n * @type {IConversionOptions}\n * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json\n */\nutil.toJSONOptions = {\n longs: String,\n enums: String,\n bytes: String,\n json: true\n};\n\n// Sets up buffer utility according to the environment (called in index-minimal)\nutil._configure = function() {\n var Buffer = util.Buffer;\n /* istanbul ignore if */\n if (!Buffer) {\n util._Buffer_from = util._Buffer_allocUnsafe = null;\n return;\n }\n // because node 4.x buffers are incompatible & immutable\n // see: https://github.com/dcodeIO/protobuf.js/pull/665\n util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||\n /* istanbul ignore next */\n function Buffer_from(value, encoding) {\n return new Buffer(value, encoding);\n };\n util._Buffer_allocUnsafe = Buffer.allocUnsafe ||\n /* istanbul ignore next */\n function Buffer_allocUnsafe(size) {\n return new Buffer(size);\n };\n};\n","\"use strict\";\nmodule.exports = verifier;\n\nvar Enum = require(14),\n util = require(33);\n\nfunction invalid(field, expected) {\n return field.name + \": \" + expected + (field.repeated && expected !== \"array\" ? \"[]\" : field.map && expected !== \"object\" ? \"{k:\"+field.keyType+\"}\" : \"\") + \" expected\";\n}\n\n/**\n * Generates a partial value verifier.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {number} fieldIndex Field index\n * @param {string} ref Variable reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genVerifyValue(gen, field, fieldIndex, ref) {\n /* eslint-disable no-unexpected-multiline */\n if (field.resolvedType) {\n if (field.resolvedType instanceof Enum) { gen\n (\"switch(%s){\", ref)\n (\"default:\")\n (\"return%j\", invalid(field, \"enum value\"));\n for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen\n (\"case %i:\", field.resolvedType.values[keys[j]]);\n gen\n (\"break\")\n (\"}\");\n } else {\n gen\n (\"{\")\n (\"var e=types[%i].verify(%s);\", fieldIndex, ref)\n (\"if(e)\")\n (\"return%j+e\", field.name + \".\")\n (\"}\");\n }\n } else {\n switch (field.type) {\n case \"int32\":\n case \"uint32\":\n case \"sint32\":\n case \"fixed32\":\n case \"sfixed32\": gen\n (\"if(!util.isInteger(%s))\", ref)\n (\"return%j\", invalid(field, \"integer\"));\n break;\n case \"int64\":\n case \"uint64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))\", ref, ref, ref, ref)\n (\"return%j\", invalid(field, \"integer|Long\"));\n break;\n case \"float\":\n case \"double\": gen\n (\"if(typeof %s!==\\\"number\\\")\", ref)\n (\"return%j\", invalid(field, \"number\"));\n break;\n case \"bool\": gen\n (\"if(typeof %s!==\\\"boolean\\\")\", ref)\n (\"return%j\", invalid(field, \"boolean\"));\n break;\n case \"string\": gen\n (\"if(!util.isString(%s))\", ref)\n (\"return%j\", invalid(field, \"string\"));\n break;\n case \"bytes\": gen\n (\"if(!(%s&&typeof %s.length===\\\"number\\\"||util.isString(%s)))\", ref, ref, ref)\n (\"return%j\", invalid(field, \"buffer\"));\n break;\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline */\n}\n\n/**\n * Generates a partial key verifier.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {string} ref Variable reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genVerifyKey(gen, field, ref) {\n /* eslint-disable no-unexpected-multiline */\n switch (field.keyType) {\n case \"int32\":\n case \"uint32\":\n case \"sint32\":\n case \"fixed32\":\n case \"sfixed32\": gen\n (\"if(!util.key32Re.test(%s))\", ref)\n (\"return%j\", invalid(field, \"integer key\"));\n break;\n case \"int64\":\n case \"uint64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(!util.key64Re.test(%s))\", ref) // see comment above: x is ok, d is not\n (\"return%j\", invalid(field, \"integer|Long key\"));\n break;\n case \"bool\": gen\n (\"if(!util.key2Re.test(%s))\", ref)\n (\"return%j\", invalid(field, \"boolean key\"));\n break;\n }\n return gen;\n /* eslint-enable no-unexpected-multiline */\n}\n\n/**\n * Generates a verifier specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nfunction verifier(mtype) {\n /* eslint-disable no-unexpected-multiline */\n\n var gen = util.codegen([\"m\"], mtype.name + \"$verify\")\n (\"if(typeof m!==\\\"object\\\"||m===null)\")\n (\"return%j\", \"object expected\");\n var oneofs = mtype.oneofsArray,\n seenFirstField = {};\n if (oneofs.length) gen\n (\"var p={}\");\n\n for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {\n var field = mtype._fieldsArray[i].resolve(),\n ref = \"m\" + util.safeProp(field.name);\n\n if (field.optional) gen\n (\"if(%s!=null&&m.hasOwnProperty(%j)){\", ref, field.name); // !== undefined && !== null\n\n // map fields\n if (field.map) { gen\n (\"if(!util.isObject(%s))\", ref)\n (\"return%j\", invalid(field, \"object\"))\n (\"var k=Object.keys(%s)\", ref)\n (\"for(var i=0;i}\n * @const\n */\nvar wrappers = exports;\n\nvar Message = require(19);\n\n/**\n * From object converter part of an {@link IWrapper}.\n * @typedef WrapperFromObjectConverter\n * @type {function}\n * @param {Object.} object Plain object\n * @returns {Message<{}>} Message instance\n * @this Type\n */\n\n/**\n * To object converter part of an {@link IWrapper}.\n * @typedef WrapperToObjectConverter\n * @type {function}\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n * @this Type\n */\n\n/**\n * Common type wrapper part of {@link wrappers}.\n * @interface IWrapper\n * @property {WrapperFromObjectConverter} [fromObject] From object converter\n * @property {WrapperToObjectConverter} [toObject] To object converter\n */\n\n// Custom wrapper for Any\nwrappers[\".google.protobuf.Any\"] = {\n\n fromObject: function(object) {\n\n // unwrap value type if mapped\n if (object && object[\"@type\"]) {\n // Only use fully qualified type name after the last '/'\n var name = object[\"@type\"].substring(object[\"@type\"].lastIndexOf(\"/\") + 1);\n var type = this.lookup(name);\n /* istanbul ignore else */\n if (type) {\n // type_url does not accept leading \".\"\n var type_url = object[\"@type\"].charAt(0) === \".\" ?\n object[\"@type\"].slice(1) : object[\"@type\"];\n // type_url prefix is optional, but path seperator is required\n if (type_url.indexOf(\"/\") === -1) {\n type_url = \"/\" + type_url;\n }\n return this.create({\n type_url: type_url,\n value: type.encode(type.fromObject(object)).finish()\n });\n }\n }\n\n return this.fromObject(object);\n },\n\n toObject: function(message, options) {\n\n // Default prefix\n var googleApi = \"type.googleapis.com/\";\n var prefix = \"\";\n var name = \"\";\n\n // decode value if requested and unmapped\n if (options && options.json && message.type_url && message.value) {\n // Only use fully qualified type name after the last '/'\n name = message.type_url.substring(message.type_url.lastIndexOf(\"/\") + 1);\n // Separate the prefix used\n prefix = message.type_url.substring(0, message.type_url.lastIndexOf(\"/\") + 1);\n var type = this.lookup(name);\n /* istanbul ignore else */\n if (type)\n message = type.decode(message.value);\n }\n\n // wrap value if unmapped\n if (!(message instanceof this.ctor) && message instanceof Message) {\n var object = message.$type.toObject(message, options);\n var messageName = message.$type.fullName[0] === \".\" ?\n message.$type.fullName.slice(1) : message.$type.fullName;\n // Default to type.googleapis.com prefix if no prefix is used\n if (prefix === \"\") {\n prefix = googleApi;\n }\n name = prefix + messageName;\n object[\"@type\"] = name;\n return object;\n }\n\n return this.toObject(message, options);\n }\n};\n","\"use strict\";\nmodule.exports = Writer;\n\nvar util = require(35);\n\nvar BufferWriter; // cyclic\n\nvar LongBits = util.LongBits,\n base64 = util.base64,\n utf8 = util.utf8;\n\n/**\n * Constructs a new writer operation instance.\n * @classdesc Scheduled writer operation.\n * @constructor\n * @param {function(*, Uint8Array, number)} fn Function to call\n * @param {number} len Value byte length\n * @param {*} val Value to write\n * @ignore\n */\nfunction Op(fn, len, val) {\n\n /**\n * Function to call.\n * @type {function(Uint8Array, number, *)}\n */\n this.fn = fn;\n\n /**\n * Value byte length.\n * @type {number}\n */\n this.len = len;\n\n /**\n * Next operation.\n * @type {Writer.Op|undefined}\n */\n this.next = undefined;\n\n /**\n * Value to write.\n * @type {*}\n */\n this.val = val; // type varies\n}\n\n/* istanbul ignore next */\nfunction noop() {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance.\n * @classdesc Copied writer state.\n * @memberof Writer\n * @constructor\n * @param {Writer} writer Writer to copy state from\n * @ignore\n */\nfunction State(writer) {\n\n /**\n * Current head.\n * @type {Writer.Op}\n */\n this.head = writer.head;\n\n /**\n * Current tail.\n * @type {Writer.Op}\n */\n this.tail = writer.tail;\n\n /**\n * Current buffer length.\n * @type {number}\n */\n this.len = writer.len;\n\n /**\n * Next state.\n * @type {State|null}\n */\n this.next = writer.states;\n}\n\n/**\n * Constructs a new writer instance.\n * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n */\nfunction Writer() {\n\n /**\n * Current length.\n * @type {number}\n */\n this.len = 0;\n\n /**\n * Operations head.\n * @type {Object}\n */\n this.head = new Op(noop, 0, 0);\n\n /**\n * Operations tail\n * @type {Object}\n */\n this.tail = this.head;\n\n /**\n * Linked forked states.\n * @type {Object|null}\n */\n this.states = null;\n\n // When a value is written, the writer calculates its byte length and puts it into a linked\n // list of operations to perform when finish() is called. This both allows us to allocate\n // buffers of the exact required size and reduces the amount of work we have to do compared\n // to first calculating over objects and then encoding over objects. In our case, the encoding\n // part is just a linked list walk calling operations with already prepared values.\n}\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup() {\n return (Writer.create = function create_buffer() {\n return new BufferWriter();\n })();\n }\n /* istanbul ignore next */\n : function create_array() {\n return new Writer();\n };\n};\n\n/**\n * Creates a new writer.\n * @function\n * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}\n */\nWriter.create = create();\n\n/**\n * Allocates a buffer of the specified size.\n * @param {number} size Buffer size\n * @returns {Uint8Array} Buffer\n */\nWriter.alloc = function alloc(size) {\n return new util.Array(size);\n};\n\n// Use Uint8Array buffer pool in the browser, just like node does with buffers\n/* istanbul ignore else */\nif (util.Array !== Array)\n Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);\n\n/**\n * Pushes a new operation to the queue.\n * @param {function(Uint8Array, number, *)} fn Function to call\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @returns {Writer} `this`\n * @private\n */\nWriter.prototype._push = function push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n};\n\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\n\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n\n/**\n * Constructs a new varint writer operation instance.\n * @classdesc Scheduled varint writer operation.\n * @extends Op\n * @constructor\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @ignore\n */\nfunction VarintOp(len, val) {\n this.len = len;\n this.next = undefined;\n this.val = val;\n}\n\nVarintOp.prototype = Object.create(Op.prototype);\nVarintOp.prototype.fn = writeVarint32;\n\n/**\n * Writes an unsigned 32 bit value as a varint.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.uint32 = function write_uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0)\n < 128 ? 1\n : value < 16384 ? 2\n : value < 2097152 ? 3\n : value < 268435456 ? 4\n : 5,\n value)).len;\n return this;\n};\n\n/**\n * Writes a signed 32 bit value as a varint.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.int32 = function write_int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n};\n\n/**\n * Writes a 32 bit value as a varint, zig-zag encoded.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sint32 = function write_sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n};\n\nfunction writeVarint64(val, buf, pos) {\n while (val.hi) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\n\n/**\n * Writes an unsigned 64 bit value as a varint.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.uint64 = function write_uint64(value) {\n var bits = LongBits.from(value);\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a signed 64 bit value as a varint.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.int64 = Writer.prototype.uint64;\n\n/**\n * Writes a signed 64 bit value as a varint, zig-zag encoded.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sint64 = function write_sint64(value) {\n var bits = LongBits.from(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a boolish value as a varint.\n * @param {boolean} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bool = function write_bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n};\n\nfunction writeFixed32(val, buf, pos) {\n buf[pos ] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\n\n/**\n * Writes an unsigned 32 bit value as fixed 32 bits.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.fixed32 = function write_fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n};\n\n/**\n * Writes a signed 32 bit value as fixed 32 bits.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sfixed32 = Writer.prototype.fixed32;\n\n/**\n * Writes an unsigned 64 bit value as fixed 64 bits.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.fixed64 = function write_fixed64(value) {\n var bits = LongBits.from(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n};\n\n/**\n * Writes a signed 64 bit value as fixed 64 bits.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sfixed64 = Writer.prototype.fixed64;\n\n/**\n * Writes a float (32 bit).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.float = function write_float(value) {\n return this._push(util.float.writeFloatLE, 4, value);\n};\n\n/**\n * Writes a double (64 bit float).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.double = function write_double(value) {\n return this._push(util.float.writeDoubleLE, 8, value);\n};\n\nvar writeBytes = util.Array.prototype.set\n ? function writeBytes_set(val, buf, pos) {\n buf.set(val, pos); // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytes_for(val, buf, pos) {\n for (var i = 0; i < val.length; ++i)\n buf[pos + i] = val[i];\n };\n\n/**\n * Writes a sequence of bytes.\n * @param {Uint8Array|string} value Buffer or base64 encoded string to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bytes = function write_bytes(value) {\n var len = value.length >>> 0;\n if (!len)\n return this._push(writeByte, 1, 0);\n if (util.isString(value)) {\n var buf = Writer.alloc(len = base64.length(value));\n base64.decode(value, buf, 0);\n value = buf;\n }\n return this.uint32(len)._push(writeBytes, len, value);\n};\n\n/**\n * Writes a string.\n * @param {string} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.string = function write_string(value) {\n var len = utf8.length(value);\n return len\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0);\n};\n\n/**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n * @returns {Writer} `this`\n */\nWriter.prototype.fork = function fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n};\n\n/**\n * Resets this instance to the last state.\n * @returns {Writer} `this`\n */\nWriter.prototype.reset = function reset() {\n if (this.states) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n } else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n};\n\n/**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n * @returns {Writer} `this`\n */\nWriter.prototype.ldelim = function ldelim() {\n var head = this.head,\n tail = this.tail,\n len = this.len;\n this.reset().uint32(len);\n if (len) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n};\n\n/**\n * Finishes the write operation.\n * @returns {Uint8Array} Finished buffer\n */\nWriter.prototype.finish = function finish() {\n var head = this.head.next, // skip noop\n buf = this.constructor.alloc(this.len),\n pos = 0;\n while (head) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n};\n\nWriter._configure = function(BufferWriter_) {\n BufferWriter = BufferWriter_;\n Writer.create = create();\n BufferWriter._configure();\n};\n","\"use strict\";\nmodule.exports = BufferWriter;\n\n// extends Writer\nvar Writer = require(38);\n(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;\n\nvar util = require(35);\n\n/**\n * Constructs a new buffer writer instance.\n * @classdesc Wire format writer using node buffers.\n * @extends Writer\n * @constructor\n */\nfunction BufferWriter() {\n Writer.call(this);\n}\n\nBufferWriter._configure = function () {\n /**\n * Allocates a buffer of the specified size.\n * @function\n * @param {number} size Buffer size\n * @returns {Buffer} Buffer\n */\n BufferWriter.alloc = util._Buffer_allocUnsafe;\n\n BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === \"set\"\n ? function writeBytesBuffer_set(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytesBuffer_copy(val, buf, pos) {\n if (val.copy) // Buffer values\n val.copy(buf, pos, 0, val.length);\n else for (var i = 0; i < val.length;) // plain array values\n buf[pos++] = val[i++];\n };\n};\n\n\n/**\n * @override\n */\nBufferWriter.prototype.bytes = function write_bytes_buffer(value) {\n if (util.isString(value))\n value = util._Buffer_from(value, \"base64\");\n var len = value.length >>> 0;\n this.uint32(len);\n if (len)\n this._push(BufferWriter.writeBytesBuffer, len, value);\n return this;\n};\n\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)\n util.utf8.write(val, buf, pos);\n else if (buf.utf8Write)\n buf.utf8Write(val, pos);\n else\n buf.write(val, pos);\n}\n\n/**\n * @override\n */\nBufferWriter.prototype.string = function write_string_buffer(value) {\n var len = util.Buffer.byteLength(value);\n this.uint32(len);\n if (len)\n this._push(writeStringBuffer, len, value);\n return this;\n};\n\n\n/**\n * Finishes the write operation.\n * @name BufferWriter#finish\n * @function\n * @returns {Buffer} Finished buffer\n */\n\nBufferWriter._configure();\n"],"sourceRoot":"."} \ No newline at end of file diff --git a/node_modules/protobufjs/dist/light/protobuf.min.js b/node_modules/protobufjs/dist/light/protobuf.min.js new file mode 100644 index 0000000..0d9d89b --- /dev/null +++ b/node_modules/protobufjs/dist/light/protobuf.min.js @@ -0,0 +1,8 @@ +/*! + * protobuf.js v7.5.4 (c) 2016, daniel wirtz + * compiled fri, 15 aug 2025 23:28:55 utc + * licensed under the bsd-3-clause license + * see: https://github.com/dcodeio/protobuf.js for details + */ +!function(g){"use strict";!function(r,e,t){var i=function t(i){var n=e[i];return n||r[i][0].call(n=e[i]={exports:{}},t,n,n.exports),n.exports}(t[0]);i.util.global.protobuf=i,"function"==typeof define&&define.amd&&define(["long"],function(t){return t&&t.isLong&&(i.util.Long=t,i.configure()),i}),"object"==typeof module&&module&&module.exports&&(module.exports=i)}({1:[function(t,i,n){i.exports=function(t,i){var n=Array(arguments.length-1),s=0,r=2,o=!0;for(;r>2],r=(3&h)<<4,u=1;break;case 1:s[o++]=f[r|h>>4],r=(15&h)<<2,u=2;break;case 2:s[o++]=f[r|h>>6],s[o++]=f[63&h],u=0}8191>4,r=u,s=2;break;case 2:i[n++]=(15&r)<<4|(60&u)>>2,r=u,s=3;break;case 3:i[n++]=(3&r)<<6|u,s=0}}if(1===s)throw Error(c);return n-e},n.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}},{}],3:[function(t,i,n){function a(i,n){"string"==typeof i&&(n=i,i=g);var h=[];function f(t){if("string"!=typeof t){var i=c();if(a.verbose&&console.log("codegen: "+i),i="return "+i,t){for(var n=Object.keys(t),r=Array(n.length+1),e=Array(n.length),s=0;s>>0:i<11754943508222875e-54?(e<<31|Math.round(i/1401298464324817e-60))>>>0:(e<<31|127+(t=Math.floor(Math.log(i)/Math.LN2))<<23|8388607&Math.round(i*Math.pow(2,-t)*8388608))>>>0,n,r)}function n(t,i,n){t=t(i,n),i=2*(t>>31)+1,n=t>>>23&255,t&=8388607;return 255==n?t?NaN:1/0*i:0==n?1401298464324817e-60*i*t:i*Math.pow(2,n-150)*(8388608+t)}function r(t,i,n){u[0]=t,i[n]=h[0],i[n+1]=h[1],i[n+2]=h[2],i[n+3]=h[3]}function e(t,i,n){u[0]=t,i[n]=h[3],i[n+1]=h[2],i[n+2]=h[1],i[n+3]=h[0]}function s(t,i){return h[0]=t[i],h[1]=t[i+1],h[2]=t[i+2],h[3]=t[i+3],u[0]}function o(t,i){return h[3]=t[i],h[2]=t[i+1],h[1]=t[i+2],h[0]=t[i+3],u[0]}var u,h,f,c,a;function l(t,i,n,r,e,s){var o,u=r<0?1:0;0===(r=u?-r:r)?(t(0,e,s+i),t(0<1/r?0:2147483648,e,s+n)):isNaN(r)?(t(0,e,s+i),t(2146959360,e,s+n)):17976931348623157e292>>0,e,s+n)):r<22250738585072014e-324?(t((o=r/5e-324)>>>0,e,s+i),t((u<<31|o/4294967296)>>>0,e,s+n)):(t(4503599627370496*(o=r*Math.pow(2,-(r=1024===(r=Math.floor(Math.log(r)/Math.LN2))?1023:r)))>>>0,e,s+i),t((u<<31|r+1023<<20|1048576*o&1048575)>>>0,e,s+n))}function d(t,i,n,r,e){i=t(r,e+i),t=t(r,e+n),r=2*(t>>31)+1,e=t>>>20&2047,n=4294967296*(1048575&t)+i;return 2047==e?n?NaN:1/0*r:0==e?5e-324*r*n:r*Math.pow(2,e-1075)*(n+4503599627370496)}function v(t,i,n){f[0]=t,i[n]=c[0],i[n+1]=c[1],i[n+2]=c[2],i[n+3]=c[3],i[n+4]=c[4],i[n+5]=c[5],i[n+6]=c[6],i[n+7]=c[7]}function b(t,i,n){f[0]=t,i[n]=c[7],i[n+1]=c[6],i[n+2]=c[5],i[n+3]=c[4],i[n+4]=c[3],i[n+5]=c[2],i[n+6]=c[1],i[n+7]=c[0]}function p(t,i){return c[0]=t[i],c[1]=t[i+1],c[2]=t[i+2],c[3]=t[i+3],c[4]=t[i+4],c[5]=t[i+5],c[6]=t[i+6],c[7]=t[i+7],f[0]}function y(t,i){return c[7]=t[i],c[6]=t[i+1],c[5]=t[i+2],c[4]=t[i+3],c[3]=t[i+4],c[2]=t[i+5],c[1]=t[i+6],c[0]=t[i+7],f[0]}return"undefined"!=typeof Float32Array?(u=new Float32Array([-0]),h=new Uint8Array(u.buffer),a=128===h[3],t.writeFloatLE=a?r:e,t.writeFloatBE=a?e:r,t.readFloatLE=a?s:o,t.readFloatBE=a?o:s):(t.writeFloatLE=i.bind(null,m),t.writeFloatBE=i.bind(null,w),t.readFloatLE=n.bind(null,g),t.readFloatBE=n.bind(null,j)),"undefined"!=typeof Float64Array?(f=new Float64Array([-0]),c=new Uint8Array(f.buffer),a=128===c[7],t.writeDoubleLE=a?v:b,t.writeDoubleBE=a?b:v,t.readDoubleLE=a?p:y,t.readDoubleBE=a?y:p):(t.writeDoubleLE=l.bind(null,m,0,4),t.writeDoubleBE=l.bind(null,w,4,0),t.readDoubleLE=d.bind(null,g,0,4),t.readDoubleBE=d.bind(null,j,4,0)),t}function m(t,i,n){i[n]=255&t,i[n+1]=t>>>8&255,i[n+2]=t>>>16&255,i[n+3]=t>>>24}function w(t,i,n){i[n]=t>>>24,i[n+1]=t>>>16&255,i[n+2]=t>>>8&255,i[n+3]=255&t}function g(t,i){return(t[i]|t[i+1]<<8|t[i+2]<<16|t[i+3]<<24)>>>0}function j(t,i){return(t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3])>>>0}i.exports=r(r)},{}],7:[function(t,i,n){function r(t){try{var i=eval("require")(t);if(i&&(i.length||Object.keys(i).length))return i}catch(t){}return null}i.exports=r},{}],8:[function(t,i,n){var e=n.isAbsolute=function(t){return/^(?:\/|\w+:)/.test(t)},r=n.normalize=function(t){var i=(t=t.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),n=e(t),t="";n&&(t=i.shift()+"/");for(var r=0;r>>1,s=null,o=r;return function(t){if(t<1||e>10),s[o++]=56320+(1023&r)):s[o++]=(15&r)<<12|(63&t[i++])<<6|63&t[i++],8191>6|192:(55296==(64512&r)&&56320==(64512&(e=t.charCodeAt(o+1)))?(++o,i[n++]=(r=65536+((1023&r)<<10)+(1023&e))>>18|240,i[n++]=r>>12&63|128):i[n++]=r>>12|224,i[n++]=r>>6&63|128),i[n++]=63&r|128);return n-s}},{}],11:[function(t,i,n){var l=t(14),d=t(33);function o(t,i,n,r){var e=!1;if(i.resolvedType)if(i.resolvedType instanceof l){t("switch(d%s){",r);for(var s=i.resolvedType.values,o=Object.keys(s),u=0;u>>0",r,r);break;case"int32":case"sint32":case"sfixed32":t("m%s=d%s|0",r,r);break;case"uint64":h=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",r,r,h)('else if(typeof d%s==="string")',r)("m%s=parseInt(d%s,10)",r,r)('else if(typeof d%s==="number")',r)("m%s=d%s",r,r)('else if(typeof d%s==="object")',r)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",r,r,r,h?"true":"");break;case"bytes":t('if(typeof d%s==="string")',r)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",r,r,r)("else if(d%s.length >= 0)",r)("m%s=d%s",r,r);break;case"string":t("m%s=String(d%s)",r,r);break;case"bool":t("m%s=Boolean(d%s)",r,r)}}return t}function v(t,i,n,r){if(i.resolvedType)i.resolvedType instanceof l?t("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",r,n,r,r,n,r,r):t("d%s=types[%i].toObject(m%s,o)",r,n,r);else{var e=!1;switch(i.type){case"double":case"float":t("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",r,r,r,r);break;case"uint64":e=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t('if(typeof m%s==="number")',r)("d%s=o.longs===String?String(m%s):m%s",r,r,r)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",r,r,r,r,e?"true":"",r);break;case"bytes":t("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",r,r,r,r,r);break;default:t("d%s=m%s",r,r)}}return t}n.fromObject=function(t){var i=t.fieldsArray,n=d.codegen(["d"],t.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!i.length)return n("return new this.ctor");n("var m=new this.ctor");for(var r=0;r>>3){"),n=0;n>>3){")("case 1: k=r.%s(); break",r.keyType)("case 2:"),h.basic[e]===g?i("value=types[%i].decode(r,r.uint32())",n):i("value=r.%s()",e),i("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),h.long[r.keyType]!==g?i('%s[typeof k==="object"?util.longToHash(k):k]=value',s):i("%s[k]=value",s)):r.repeated?(i("if(!(%s&&%s.length))",s,s)("%s=[]",s),h.packed[e]!==g&&i("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos>>0,8|c.mapKey[s.keyType],s.keyType),h===g?n("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",o,i):n(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|h,u,i),n("}")("}")):s.repeated?(n("if(%s!=null&&%s.length){",i,i),s.packed&&c.packed[u]!==g?n("w.uint32(%i).fork()",(s.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",i)("w.%s(%s[i])",u,i)("w.ldelim()"):(n("for(var i=0;i<%s.length;++i)",i),h===g?l(n,s,o,i+"[i]"):n("w.uint32(%i).%s(%s[i])",(s.id<<3|h)>>>0,u,i)),n("}")):(s.optional&&n("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",i,s.name),h===g?l(n,s,o,i):n("w.uint32(%i).%s(%s)",(s.id<<3|h)>>>0,u,i))}return n("return w")};var f=t(14),c=t(32),a=t(33);function l(t,i,n,r){i.delimited?t("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",n,r,(i.id<<3|3)>>>0,(i.id<<3|4)>>>0):t("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",n,r,(i.id<<3|2)>>>0)}},{14:14,32:32,33:33}],14:[function(t,i,n){i.exports=s;var h=t(22),r=(((s.prototype=Object.create(h.prototype)).constructor=s).className="Enum",t(21)),e=t(33);function s(t,i,n,r,e,s){if(h.call(this,t,n),i&&"object"!=typeof i)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=r,this.comments=e||{},this.valuesOptions=s,this.n={},this.reserved=g,i)for(var o=Object.keys(i),u=0;u{var i=Object.assign({},this.o);this.n[t]=Object.assign(i,this.valuesOptions&&this.valuesOptions[t]&&this.valuesOptions[t].features)}),this},s.fromJSON=function(t,i){t=new s(t,i.values,i.options,i.comment,i.comments);return t.reserved=i.reserved,i.edition&&(t.e=i.edition),t.u="proto3",t},s.prototype.toJSON=function(t){t=!!t&&!!t.keepComments;return e.toObject(["edition",this.h(),"options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:g,"comment",t?this.comment:g,"comments",t?this.comments:g])},s.prototype.add=function(t,i,n,r){if(!e.isString(t))throw TypeError("name must be a string");if(!e.isInteger(i))throw TypeError("id must be an integer");if(this.values[t]!==g)throw Error("duplicate name '"+t+"' in "+this);if(this.isReservedId(i))throw Error("id "+i+" is reserved in "+this);if(this.isReservedName(t))throw Error("name '"+t+"' is reserved in "+this);if(this.valuesById[i]!==g){if(!this.options||!this.options.allow_alias)throw Error("duplicate id "+i+" in "+this);this.values[t]=i}else this.valuesById[this.values[t]=i]=t;return r&&(this.valuesOptions===g&&(this.valuesOptions={}),this.valuesOptions[t]=r||null),this.comments[t]=n||null,this},s.prototype.remove=function(t){if(!e.isString(t))throw TypeError("name must be a string");var i=this.values[t];if(null==i)throw Error("name '"+t+"' does not exist in "+this);return delete this.valuesById[i],delete this.values[t],delete this.comments[t],this.valuesOptions&&delete this.valuesOptions[t],this},s.prototype.isReservedId=function(t){return r.isReservedId(this.reserved,t)},s.prototype.isReservedName=function(t){return r.isReservedName(this.reserved,t)}},{21:21,22:22,33:33}],15:[function(t,i,n){i.exports=o;var r,u=t(22),e=(((o.prototype=Object.create(u.prototype)).constructor=o).className="Field",t(14)),h=t(32),f=t(33),c=/^required|optional|repeated$/;function o(t,i,n,r,e,s,o){if(f.isObject(r)?(o=e,s=r,r=e=g):f.isObject(e)&&(o=s,s=e,e=g),u.call(this,t,s),!f.isInteger(i)||i<0)throw TypeError("id must be a non-negative integer");if(!f.isString(n))throw TypeError("type must be a string");if(r!==g&&!c.test(r=r.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(e!==g&&!f.isString(e))throw TypeError("extend must be a string");this.rule=(r="proto3_optional"===r?"optional":r)&&"optional"!==r?r:g,this.type=n,this.id=i,this.extend=e||g,this.repeated="repeated"===r,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!f.Long&&h.long[n]!==g,this.bytes="bytes"===n,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.comment=o}o.fromJSON=function(t,i){t=new o(t,i.id,i.type,i.rule,i.extend,i.options,i.comment);return i.edition&&(t.e=i.edition),t.u="proto3",t},Object.defineProperty(o.prototype,"required",{get:function(){return"LEGACY_REQUIRED"===this.o.field_presence}}),Object.defineProperty(o.prototype,"optional",{get:function(){return!this.required}}),Object.defineProperty(o.prototype,"delimited",{get:function(){return this.resolvedType instanceof r&&"DELIMITED"===this.o.message_encoding}}),Object.defineProperty(o.prototype,"packed",{get:function(){return"PACKED"===this.o.repeated_field_encoding}}),Object.defineProperty(o.prototype,"hasPresence",{get:function(){return!this.repeated&&!this.map&&(this.partOf||this.declaringField||this.extensionField||"IMPLICIT"!==this.o.field_presence)}}),o.prototype.setOption=function(t,i,n){return u.prototype.setOption.call(this,t,i,n)},o.prototype.toJSON=function(t){t=!!t&&!!t.keepComments;return f.toObject(["edition",this.h(),"rule","optional"!==this.rule&&this.rule||g,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:g])},o.prototype.resolve=function(){var t;return this.resolved?this:((this.typeDefault=h.defaults[this.type])===g?(this.resolvedType=(this.declaringField||this).parent.lookupTypeOrEnum(this.type),this.resolvedType instanceof r?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof e&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(this.options.packed===g||!this.resolvedType||this.resolvedType instanceof e||delete this.options.packed,Object.keys(this.options).length||(this.options=g)),this.long?(this.typeDefault=f.Long.fromNumber(this.typeDefault,"u"==(this.type[0]||"")),Object.freeze&&Object.freeze(this.typeDefault)):this.bytes&&"string"==typeof this.typeDefault&&(f.base64.test(this.typeDefault)?f.base64.decode(this.typeDefault,t=f.newBuffer(f.base64.length(this.typeDefault)),0):f.utf8.write(this.typeDefault,t=f.newBuffer(f.utf8.length(this.typeDefault)),0),this.typeDefault=t),this.map?this.defaultValue=f.emptyObject:this.repeated?this.defaultValue=f.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof r&&(this.parent.ctor.prototype[this.name]=this.defaultValue),u.prototype.resolve.call(this))},o.prototype.f=function(t){var i;return"proto2"!==t&&"proto3"!==t?{}:(t={},"required"===this.rule&&(t.field_presence="LEGACY_REQUIRED"),this.parent&&h.defaults[this.type]===g&&(i=this.parent.get(this.type.split(".").pop()))&&i instanceof r&&i.group&&(t.message_encoding="DELIMITED"),!0===this.getOption("packed")?t.repeated_field_encoding="PACKED":!1===this.getOption("packed")&&(t.repeated_field_encoding="EXPANDED"),t)},o.prototype.r=function(t){return u.prototype.r.call(this,this.e||t)},o.d=function(n,r,e,s){return"function"==typeof r?r=f.decorateType(r).name:r&&"object"==typeof r&&(r=f.decorateEnum(r).name),function(t,i){f.decorateType(t.constructor).add(new o(i,n,r,e,{default:s}))}},o.c=function(t){r=t}},{14:14,22:22,32:32,33:33}],16:[function(t,i,n){var r=i.exports=t(17);r.build="light",r.load=function(t,i,n){return(i="function"==typeof i?(n=i,new r.Root):i||new r.Root).load(t,n)},r.loadSync=function(t,i){return(i=i||new r.Root).loadSync(t)},r.encoder=t(13),r.decoder=t(12),r.verifier=t(36),r.converter=t(11),r.ReflectionObject=t(22),r.Namespace=t(21),r.Root=t(26),r.Enum=t(14),r.Type=t(31),r.Field=t(15),r.OneOf=t(23),r.MapField=t(18),r.Service=t(30),r.Method=t(20),r.Message=t(19),r.wrappers=t(37),r.types=t(32),r.util=t(33),r.ReflectionObject.c(r.Root),r.Namespace.c(r.Type,r.Service,r.Enum),r.Root.c(r.Type),r.Field.c(r.Type)},{11:11,12:12,13:13,14:14,15:15,17:17,18:18,19:19,20:20,21:21,22:22,23:23,26:26,30:30,31:31,32:32,33:33,36:36,37:37}],17:[function(t,i,n){var r=n;function e(){r.util.c(),r.Writer.c(r.BufferWriter),r.Reader.c(r.BufferReader)}r.build="minimal",r.Writer=t(38),r.BufferWriter=t(39),r.Reader=t(24),r.BufferReader=t(25),r.util=t(35),r.rpc=t(28),r.roots=t(27),r.configure=e,e()},{24:24,25:25,27:27,28:28,35:35,38:38,39:39}],18:[function(t,i,n){i.exports=s;var o=t(15),r=(((s.prototype=Object.create(o.prototype)).constructor=s).className="MapField",t(32)),u=t(33);function s(t,i,n,r,e,s){if(o.call(this,t,i,r,g,g,e,s),!u.isString(n))throw TypeError("keyType must be a string");this.keyType=n,this.resolvedKeyType=null,this.map=!0}s.fromJSON=function(t,i){return new s(t,i.id,i.keyType,i.type,i.options,i.comment)},s.prototype.toJSON=function(t){t=!!t&&!!t.keepComments;return u.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:g])},s.prototype.resolve=function(){if(this.resolved)return this;if(r.mapKey[this.keyType]===g)throw Error("invalid key type: "+this.keyType);return o.prototype.resolve.call(this)},s.d=function(n,r,e){return"function"==typeof e?e=u.decorateType(e).name:e&&"object"==typeof e&&(e=u.decorateEnum(e).name),function(t,i){u.decorateType(t.constructor).add(new s(i,n,r,e))}}},{15:15,32:32,33:33}],19:[function(t,i,n){i.exports=e;var r=t(35);function e(t){if(t)for(var i=Object.keys(t),n=0;ni)return!0;return!1},a.isReservedName=function(t,i){if(t)for(var n=0;n{t.p(i)})),this},a.prototype.lookup=function(t,i,n){if("boolean"==typeof i?(n=i,i=g):i&&!Array.isArray(i)&&(i=[i]),f.isString(t)&&t.length){if("."===t)return this.root;t=t.split(".")}else if(!t.length)return this;var r=t.join(".");if(""===t[0])return this.root.lookup(t.slice(1),i);var e=this.root.y&&this.root.y["."+r];if(e&&(!i||~i.indexOf(e.constructor)))return e;if((e=this.w(t,r))&&(!i||~i.indexOf(e.constructor)))return e;if(!n)for(var s=this;s.parent;){if((e=s.parent.w(t,r))&&(!i||~i.indexOf(e.constructor)))return e;s=s.parent}return null},a.prototype.w=function(t,i){if(Object.prototype.hasOwnProperty.call(this.l,i))return this.l[i];var n=this.get(t[0]),r=null;if(n)1===t.length?r=n:n instanceof a&&(t=t.slice(1),r=n.w(t,t.join(".")));else for(var e=0;e "+t.len)}function h(t){this.buf=t,this.pos=0,this.len=t.length}function f(){return e.Buffer?function(t){return(h.create=function(t){return e.Buffer.isBuffer(t)?new r(t):a(t)})(t)}:a}var c,a="undefined"!=typeof Uint8Array?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new h(t);throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new h(t);throw Error("illegal buffer")};function l(){var t=new s(0,0),i=0;if(!(4=this.len)throw u(this);if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*i)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(127&this.buf[this.pos++])<<7*i)>>>0,t}for(;i<4;++i)if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*i)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(127&this.buf[this.pos])<<28)>>>0,t.hi=(t.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return t;if(i=0,4>>0,this.buf[this.pos++]<128)return t}else for(;i<5;++i){if(this.pos>=this.len)throw u(this);if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*i+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}function d(t,i){return(t[i-4]|t[i-3]<<8|t[i-2]<<16|t[i-1]<<24)>>>0}function v(){if(this.pos+8>this.len)throw u(this,8);return new s(d(this.buf,this.pos+=4),d(this.buf,this.pos+=4))}h.create=f(),h.prototype.k=e.Array.prototype.subarray||e.Array.prototype.slice,h.prototype.uint32=(c=4294967295,function(){if(c=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(c=(c|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128||(c=(c|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128||(c=(c|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128||(c=(c|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128||!((this.pos+=5)>this.len))))))return c;throw this.pos=this.len,u(this,10)}),h.prototype.int32=function(){return 0|this.uint32()},h.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(1&t)|0},h.prototype.bool=function(){return 0!==this.uint32()},h.prototype.fixed32=function(){if(this.pos+4>this.len)throw u(this,4);return d(this.buf,this.pos+=4)},h.prototype.sfixed32=function(){if(this.pos+4>this.len)throw u(this,4);return 0|d(this.buf,this.pos+=4)},h.prototype.float=function(){if(this.pos+4>this.len)throw u(this,4);var t=e.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t},h.prototype.double=function(){if(this.pos+8>this.len)throw u(this,4);var t=e.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t},h.prototype.bytes=function(){var t=this.uint32(),i=this.pos,n=this.pos+t;if(n>this.len)throw u(this,t);return this.pos+=t,Array.isArray(this.buf)?this.buf.slice(i,n):i===n?(t=e.Buffer)?t.alloc(0):new this.buf.constructor(0):this.k.call(this.buf,i,n)},h.prototype.string=function(){var t=this.bytes();return o.read(t,0,t.length)},h.prototype.skip=function(t){if("number"==typeof t){if(this.pos+t>this.len)throw u(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw u(this)}while(128&this.buf[this.pos++]);return this},h.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this},h.c=function(t){r=t,h.create=f(),r.c();var i=e.Long?"toLong":"toNumber";e.merge(h.prototype,{int64:function(){return l.call(this)[i](!1)},uint64:function(){return l.call(this)[i](!0)},sint64:function(){return l.call(this).zzDecode()[i](!1)},fixed64:function(){return v.call(this)[i](!0)},sfixed64:function(){return v.call(this)[i](!1)}})}},{35:35}],25:[function(t,i,n){i.exports=s;var r=t(24),e=((s.prototype=Object.create(r.prototype)).constructor=s,t(35));function s(t){r.call(this,t)}s.c=function(){e.Buffer&&(s.prototype.k=e.Buffer.prototype.slice)},s.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+t,this.len))},s.c()},{24:24,35:35}],26:[function(t,i,n){i.exports=h;var r,d,v,e=t(21),s=(((h.prototype=Object.create(e.prototype)).constructor=h).className="Root",t(15)),o=t(14),u=t(23),b=t(33);function h(t){e.call(this,"",t),this.deferred=[],this.files=[],this.e="proto2",this.y={}}function p(){}h.fromJSON=function(t,i){return i=i||new h,t.options&&i.setOptions(t.options),i.addJSON(t.nested).resolveAll()},h.prototype.resolvePath=b.path.resolve,h.prototype.fetch=b.fetch,h.prototype.load=function t(i,s,e){"function"==typeof s&&(e=s,s=g);var o=this;if(!e)return b.asPromise(t,o,i,s);var u=e===p;function h(t,i){if(e){if(u)throw t;i&&i.resolveAll();var n=e;e=null,n(t,i)}}function f(t){var i=t.lastIndexOf("google/protobuf/");if(-1{t.p(i)})),this},o.prototype.add=function(t){if(this.get(t.name))throw Error("duplicate name '"+t.name+"' in "+this);return t instanceof s?e((this.methods[t.name]=t).parent=this):r.prototype.add.call(this,t)},o.prototype.remove=function(t){if(t instanceof s){if(this.methods[t.name]!==t)throw Error(t+" is not a member of "+this);return delete this.methods[t.name],t.parent=null,e(this)}return r.prototype.remove.call(this,t)},o.prototype.create=function(t,i,n){for(var r,e=new h.Service(t,i,n),s=0;s{t.r(i)}),this.fieldsArray.forEach(t=>{t.r(i)})),this},w.prototype.get=function(t){return this.fields[t]||this.oneofs&&this.oneofs[t]||this.nested&&this.nested[t]||null},w.prototype.add=function(t){if(this.get(t.name))throw Error("duplicate name '"+t.name+"' in "+this);if(t instanceof f&&t.extend===g){if((this.T||this.fieldsById)[t.id])throw Error("duplicate id "+t.id+" in "+this);if(this.isReservedId(t.id))throw Error("id "+t.id+" is reserved in "+this);if(this.isReservedName(t.name))throw Error("name '"+t.name+"' is reserved in "+this);return t.parent&&t.parent.remove(t),(this.fields[t.name]=t).message=this,t.onAdd(this),r(this)}return t instanceof h?(this.oneofs||(this.oneofs={}),(this.oneofs[t.name]=t).onAdd(this),r(this)):o.prototype.add.call(this,t)},w.prototype.remove=function(t){if(t instanceof f&&t.extend===g){if(this.fields&&this.fields[t.name]===t)return delete this.fields[t.name],t.parent=null,t.onRemove(this),r(this);throw Error(t+" is not a member of "+this)}if(t instanceof h){if(this.oneofs&&this.oneofs[t.name]===t)return delete this.oneofs[t.name],t.parent=null,t.onRemove(this),r(this);throw Error(t+" is not a member of "+this)}return o.prototype.remove.call(this,t)},w.prototype.isReservedId=function(t){return o.isReservedId(this.reserved,t)},w.prototype.isReservedName=function(t){return o.isReservedName(this.reserved,t)},w.prototype.create=function(t){return new this.ctor(t)},w.prototype.setup=function(){for(var t=this.fullName,i=[],n=0;n>>0,this.hi=i>>>0}var s=e.zero=new e(0,0),o=(s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1},e.zeroHash="\0\0\0\0\0\0\0\0",e.fromNumber=function(t){var i,n;return 0===t?s:(n=(t=(i=t<0)?-t:t)>>>0,t=(t-n)/4294967296>>>0,i&&(t=~t>>>0,n=~n>>>0,4294967295<++n&&(n=0,4294967295<++t&&(t=0))),new e(n,t))},e.from=function(t){if("number"==typeof t)return e.fromNumber(t);if(r.isString(t)){if(!r.Long)return e.fromNumber(parseInt(t,10));t=r.Long.fromString(t)}return t.low||t.high?new e(t.low>>>0,t.high>>>0):s},e.prototype.toNumber=function(t){var i;return!t&&this.hi>>>31?(t=1+~this.lo>>>0,i=~this.hi>>>0,-(t+4294967296*(i=t?i:i+1>>>0))):this.lo+4294967296*this.hi},e.prototype.toLong=function(t){return r.Long?new r.Long(0|this.lo,0|this.hi,!!t):{low:0|this.lo,high:0|this.hi,unsigned:!!t}},String.prototype.charCodeAt);e.fromHash=function(t){return"\0\0\0\0\0\0\0\0"===t?s:new e((o.call(t,0)|o.call(t,1)<<8|o.call(t,2)<<16|o.call(t,3)<<24)>>>0,(o.call(t,4)|o.call(t,5)<<8|o.call(t,6)<<16|o.call(t,7)<<24)>>>0)},e.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},e.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this},e.prototype.zzDecode=function(){var t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this},e.prototype.length=function(){var t=this.lo,i=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0==n?0==i?t<16384?t<128?1:2:t<2097152?3:4:i<16384?i<128?5:6:i<2097152?7:8:n<128?9:10}},{35:35}],35:[function(t,i,n){var r=n;function e(t,i,n){for(var r=Object.keys(i),e=0;e>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;127>>7;i[n++]=t.lo}function p(t,i,n){i[n]=255&t,i[n+1]=t>>>8&255,i[n+2]=t>>>16&255,i[n+3]=t>>>24}a.create=l(),a.alloc=function(t){return new e.Array(t)},e.Array!==Array&&(a.alloc=e.pool(a.alloc,e.Array.prototype.subarray)),a.prototype.I=function(t,i,n){return this.tail=this.tail.next=new h(t,i,n),this.len+=i,this},(v.prototype=Object.create(h.prototype)).fn=function(t,i,n){for(;127>>=7;i[n]=t},a.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new v((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this},a.prototype.int32=function(t){return t<0?this.I(b,10,s.fromNumber(t)):this.uint32(t)},a.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},a.prototype.int64=a.prototype.uint64=function(t){t=s.from(t);return this.I(b,t.length(),t)},a.prototype.sint64=function(t){t=s.from(t).zzEncode();return this.I(b,t.length(),t)},a.prototype.bool=function(t){return this.I(d,1,t?1:0)},a.prototype.sfixed32=a.prototype.fixed32=function(t){return this.I(p,4,t>>>0)},a.prototype.sfixed64=a.prototype.fixed64=function(t){t=s.from(t);return this.I(p,4,t.lo).I(p,4,t.hi)},a.prototype.float=function(t){return this.I(e.float.writeFloatLE,4,t)},a.prototype.double=function(t){return this.I(e.float.writeDoubleLE,8,t)};var y=e.Array.prototype.set?function(t,i,n){i.set(t,n)}:function(t,i,n){for(var r=0;r>>0;return n?(e.isString(t)&&(i=a.alloc(n=o.length(t)),o.decode(t,i,0),t=i),this.uint32(n).I(y,n,t)):this.I(d,1,0)},a.prototype.string=function(t){var i=u.length(t);return i?this.uint32(i).I(u.write,i,t):this.I(d,1,0)},a.prototype.fork=function(){return this.states=new c(this),this.head=this.tail=new h(f,0,0),this.len=0,this},a.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new h(f,0,0),this.len=0),this},a.prototype.ldelim=function(){var t=this.head,i=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=t.next,this.tail=i,this.len+=n),this},a.prototype.finish=function(){for(var t=this.head.next,i=this.constructor.alloc(this.len),n=0;t;)t.fn(t.val,i,n),n+=t.len,t=t.next;return i},a.c=function(t){r=t,a.create=l(),r.c()}},{35:35}],39:[function(t,i,n){i.exports=s;var r=t(38),e=((s.prototype=Object.create(r.prototype)).constructor=s,t(35));function s(){r.call(this)}function o(t,i,n){t.length<40?e.utf8.write(t,i,n):i.utf8Write?i.utf8Write(t,n):i.write(t,n)}s.c=function(){s.alloc=e.N,s.writeBytesBuffer=e.Buffer&&e.Buffer.prototype instanceof Uint8Array&&"set"===e.Buffer.prototype.set.name?function(t,i,n){i.set(t,n)}:function(t,i,n){if(t.copy)t.copy(i,n,0,t.length);else for(var r=0;r>>0;return this.uint32(i),i&&this.I(s.writeBytesBuffer,i,t),this},s.prototype.string=function(t){var i=e.Buffer.byteLength(t);return this.uint32(i),i&&this.I(o,i,t),this},s.c()},{35:35,38:38}]},{},[16])}(); +//# sourceMappingURL=protobuf.min.js.map diff --git a/node_modules/protobufjs/dist/light/protobuf.min.js.map b/node_modules/protobufjs/dist/light/protobuf.min.js.map new file mode 100644 index 0000000..4b74cb5 --- /dev/null +++ b/node_modules/protobufjs/dist/light/protobuf.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["lib/prelude.js","../node_modules/@protobufjs/aspromise/index.js","../node_modules/@protobufjs/base64/index.js","../node_modules/@protobufjs/codegen/index.js","../node_modules/@protobufjs/eventemitter/index.js","../node_modules/@protobufjs/fetch/index.js","../node_modules/@protobufjs/float/index.js","../node_modules/@protobufjs/inquire/index.js","../node_modules/@protobufjs/path/index.js","../node_modules/@protobufjs/pool/index.js","../node_modules/@protobufjs/utf8/index.js","../src/converter.js","../src/decoder.js","../src/encoder.js","../src/enum.js","../src/field.js","../src/index-light","../src/index-minimal.js","../src/mapfield.js","../src/message.js","../src/method.js","../src/namespace.js","../src/object.js","../src/oneof.js","../src/reader.js","../src/reader_buffer.js","../src/root.js","../src/roots.js","../src/rpc.js","../src/rpc/service.js","../src/service.js","../src/type.js","../src/types.js","../src/util.js","../src/util/longbits.js","../src/util/minimal.js","../src/verifier.js","../src/wrappers.js","../src/writer.js","../src/writer_buffer.js"],"names":["undefined","modules","cache","entries","protobuf","$require","name","$module","call","exports","util","global","define","amd","Long","isLong","configure","module","1","require","fn","ctx","params","Array","arguments","length","offset","index","pending","Promise","resolve","reject","err","apply","base64","string","p","n","Math","ceil","b64","s64","i","encode","buffer","start","end","t","parts","chunk","j","b","push","String","fromCharCode","slice","join","invalidEncoding","decode","c","charCodeAt","Error","test","codegen","functionParams","functionName","body","Codegen","formatStringOrScope","source","toString","verbose","console","log","scopeKeys","Object","keys","scopeParams","scopeValues","scopeOffset","Function","formatParams","formatOffset","replace","$0","$1","value","Number","floor","JSON","stringify","functionNameOverride","EventEmitter","this","_listeners","prototype","on","evt","off","listeners","splice","emit","args","fetch","asPromise","fs","filename","options","callback","xhr","readFile","contents","XMLHttpRequest","binary","onreadystatechange","readyState","status","response","responseText","Uint8Array","overrideMimeType","responseType","open","send","factory","writeFloat_ieee754","writeUint","val","buf","pos","sign","isNaN","round","exponent","LN2","pow","readFloat_ieee754","readUint","uint","mantissa","NaN","Infinity","writeFloat_f32_cpy","f32","f8b","writeFloat_f32_rev","readFloat_f32_cpy","readFloat_f32_rev","f64","le","writeDouble_ieee754","off0","off1","readDouble_ieee754","lo","hi","writeDouble_f64_cpy","writeDouble_f64_rev","readDouble_f64_cpy","readDouble_f64_rev","Float32Array","writeFloatLE","writeFloatBE","readFloatLE","readFloatBE","bind","writeUintLE","writeUintBE","readUintLE","readUintBE","Float64Array","writeDoubleLE","writeDoubleBE","readDoubleLE","readDoubleBE","inquire","moduleName","mod","eval","e","isAbsolute","path","normalize","split","absolute","prefix","shift","originPath","includePath","alreadyNormalized","alloc","size","SIZE","MAX","slab","utf8","len","read","write","c1","c2","Enum","genValuePartial_fromObject","gen","field","fieldIndex","prop","defaultAlreadyEmitted","resolvedType","values","typeDefault","repeated","fullName","isUnsigned","type","genValuePartial_toObject","converter","fromObject","mtype","fields","fieldsArray","safeProp","map","toObject","sort","compareFieldsById","repeatedFields","mapFields","normalFields","partOf","arrayDefault","valuesById","long","low","high","unsigned","toNumber","bytes","hasKs2","_fieldsArray","indexOf","filter","ref","id","types","defaults","keyType","basic","packed","delimited","rfield","required","wireType","mapKey","genTypePartial","optional","ReflectionObject","Namespace","create","constructor","className","comment","comments","valuesOptions","TypeError","_valuesFeatures","reserved","_resolveFeatures","edition","_edition","forEach","key","parentFeaturesCopy","assign","_features","features","fromJSON","json","enm","_defaultEdition","toJSON","toJSONOptions","keepComments","Boolean","_editionToJSON","add","isString","isInteger","isReservedId","isReservedName","allow_alias","remove","Field","Type","ruleRe","rule","extend","isObject","toLowerCase","message","defaultValue","extensionField","declaringField","defineProperty","get","field_presence","message_encoding","repeated_field_encoding","setOption","ifNotSet","resolved","parent","lookupTypeOrEnum","proto3_optional","fromNumber","freeze","newBuffer","emptyObject","emptyArray","ctor","_inferLegacyProtoFeatures","pop","group","getOption","d","fieldId","fieldType","fieldRule","decorateType","decorateEnum","fieldName","default","_configure","Type_","build","load","root","Root","loadSync","encoder","decoder","verifier","OneOf","MapField","Service","Method","Message","wrappers","Writer","BufferWriter","Reader","BufferReader","rpc","roots","resolvedKeyType","fieldKeyType","fieldValueType","properties","$type","writer","encodeDelimited","reader","decodeDelimited","verify","object","requestType","requestStream","responseStream","parsedOptions","resolvedRequestType","resolvedResponseType","lookupType","arrayToJSON","array","obj","nested","_nestedArray","_lookupCache","_needsRecursiveFeatureResolution","_needsRecursiveResolve","clearCache","namespace","addJSON","toArray","nestedArray","nestedJson","names","methods","getEnum","prev","setOptions","onAdd","onRemove","isArray","ptr","part","resolveAll","_resolveFeaturesRecursive","lookup","filterTypes","parentAlreadyChecked","flatPath","found","_fullyQualifiedObjects","_lookupImpl","current","hasOwnProperty","exact","lookupEnum","lookupService","Service_","Enum_","editions2023Defaults","enum_type","json_format","utf8_validation","proto2Defaults","proto3Defaults","_featuresResolved","defineProperties","unshift","_handleAdd","_handleRemove","protoFeatures","lexicalParentFeaturesCopy","setProperty","setParsedOption","propName","opt","newOpt","find","newValue","Root_","fieldNames","oneof","addFieldsToParent","oneofName","oneOfGetter","set","oneOfSetter","LongBits","indexOutOfRange","writeLength","RangeError","Buffer","isBuffer","create_array","readLongVarint","bits","readFixed32_end","readFixed64","_slice","subarray","uint32","int32","sint32","bool","fixed32","sfixed32","float","double","nativeBuffer","skip","skipType","BufferReader_","merge","int64","uint64","sint64","zzDecode","fixed64","sfixed64","utf8Slice","min","parse","common","deferred","files","SYNC","resolvePath","self","sync","finish","cb","getBundledFileName","idx","lastIndexOf","altname","substring","process","parsed","imports","weakImports","queued","weak","setTimeout","readFileSync","isNode","exposeRe","tryHandleExtension","sisterField","extendedType","parse_","common_","rpcImpl","requestDelimited","responseDelimited","rpcCall","method","requestCtor","responseCtor","request","endedByRPC","_methodsArray","service","inherited","methodsArray","rpcService","methodName","lcFirst","isReserved","m","q","s","oneofs","extensions","_fieldsById","_oneofsArray","_ctor","fieldsById","oneofsArray","generateConstructor","ctorProperties","setup","originalThis","wrapper","fork","ldelim","typeName","target","bake","o","safePropBackslashRe","safePropQuoteRe","camelCaseRe","ucFirst","str","toUpperCase","decorateEnumIndex","camelCase","a","decorateRoot","enumerable","dst","setProp","prevValue","concat","zero","zzEncode","zeroHash","from","parseInt","fromString","toLong","fromHash","hash","toHash","mask","part0","part1","part2","src","newError","CustomError","captureStackTrace","stack","writable","configurable","pool","versions","node","window","isFinite","isset","isSet","utf8Write","_Buffer_from","_Buffer_allocUnsafe","sizeOrArray","dcodeIO","key2Re","key32Re","key64Re","longToHash","longFromHash","fromBits","ProtocolError","fieldMap","longs","enums","encoding","allocUnsafe","seenFirstField","oneofProp","invalid","genVerifyValue","expected","type_url","messageName","Op","next","noop","State","head","tail","states","writeByte","VarintOp","writeVarint64","writeFixed32","_push","writeBytes","reset","BufferWriter_","writeStringBuffer","writeBytesBuffer","copy","byteLength"],"mappings":";;;;;;AAAA,CAAA,SAAAA,GAAA,aAAA,CAAA,SAAAC,EAAAC,EAAAC,GAcA,IAAAC,EAPA,SAAAC,EAAAC,GACA,IAAAC,EAAAL,EAAAI,GAGA,OAFAC,GACAN,EAAAK,GAAA,GAAAE,KAAAD,EAAAL,EAAAI,GAAA,CAAAG,QAAA,EAAA,EAAAJ,EAAAE,EAAAA,EAAAE,OAAA,EACAF,EAAAE,OACA,EAEAN,EAAA,EAAA,EAGAC,EAAAM,KAAAC,OAAAP,SAAAA,EAGA,YAAA,OAAAQ,QAAAA,OAAAC,KACAD,OAAA,CAAA,QAAA,SAAAE,GAKA,OAJAA,GAAAA,EAAAC,SACAX,EAAAM,KAAAI,KAAAA,EACAV,EAAAY,UAAA,GAEAZ,CACA,CAAA,EAGA,UAAA,OAAAa,QAAAA,QAAAA,OAAAR,UACAQ,OAAAR,QAAAL,EAEA,EAAA,CAAAc,EAAA,CAAA,SAAAC,EAAAF,EAAAR,GChCAQ,EAAAR,QAmBA,SAAAW,EAAAC,GACA,IAAAC,EAAAC,MAAAC,UAAAC,OAAA,CAAA,EACAC,EAAA,EACAC,EAAA,EACAC,EAAA,CAAA,EACA,KAAAD,EAAAH,UAAAC,QACAH,EAAAI,CAAA,IAAAF,UAAAG,CAAA,IACA,OAAA,IAAAE,QAAA,SAAAC,EAAAC,GACAT,EAAAI,GAAA,SAAAM,GACA,GAAAJ,EAEA,GADAA,EAAA,CAAA,EACAI,EACAD,EAAAC,CAAA,MACA,CAGA,IAFA,IAAAV,EAAAC,MAAAC,UAAAC,OAAA,CAAA,E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AjB,EAAA","file":"protobuf.min.js","sourcesContent":["(function prelude(modules, cache, entries) {\n\n // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS\n // sources through a conflict-free require shim and is again wrapped within an iife that\n // provides a minification-friendly `undefined` var plus a global \"use strict\" directive\n // so that minification can remove the directives of each module.\n\n function $require(name) {\n var $module = cache[name];\n if (!$module)\n modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports);\n return $module.exports;\n }\n\n var protobuf = $require(entries[0]);\n\n // Expose globally\n protobuf.util.global.protobuf = protobuf;\n\n // Be nice to AMD\n if (typeof define === \"function\" && define.amd)\n define([\"long\"], function(Long) {\n if (Long && Long.isLong) {\n protobuf.util.Long = Long;\n protobuf.configure();\n }\n return protobuf;\n });\n\n // Be nice to CommonJS\n if (typeof module === \"object\" && module && module.exports)\n module.exports = protobuf;\n\n})/* end of prelude */","\"use strict\";\r\nmodule.exports = asPromise;\r\n\r\n/**\r\n * Callback as used by {@link util.asPromise}.\r\n * @typedef asPromiseCallback\r\n * @type {function}\r\n * @param {Error|null} error Error, if any\r\n * @param {...*} params Additional arguments\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Returns a promise from a node-style callback function.\r\n * @memberof util\r\n * @param {asPromiseCallback} fn Function to call\r\n * @param {*} ctx Function context\r\n * @param {...*} params Function arguments\r\n * @returns {Promise<*>} Promisified function\r\n */\r\nfunction asPromise(fn, ctx/*, varargs */) {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0,\r\n index = 2,\r\n pending = true;\r\n while (index < arguments.length)\r\n params[offset++] = arguments[index++];\r\n return new Promise(function executor(resolve, reject) {\r\n params[offset] = function callback(err/*, varargs */) {\r\n if (pending) {\r\n pending = false;\r\n if (err)\r\n reject(err);\r\n else {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0;\r\n while (offset < params.length)\r\n params[offset++] = arguments[offset];\r\n resolve.apply(null, params);\r\n }\r\n }\r\n };\r\n try {\r\n fn.apply(ctx || null, params);\r\n } catch (err) {\r\n if (pending) {\r\n pending = false;\r\n reject(err);\r\n }\r\n }\r\n });\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal base64 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar base64 = exports;\r\n\r\n/**\r\n * Calculates the byte length of a base64 encoded string.\r\n * @param {string} string Base64 encoded string\r\n * @returns {number} Byte length\r\n */\r\nbase64.length = function length(string) {\r\n var p = string.length;\r\n if (!p)\r\n return 0;\r\n var n = 0;\r\n while (--p % 4 > 1 && string.charAt(p) === \"=\")\r\n ++n;\r\n return Math.ceil(string.length * 3) / 4 - n;\r\n};\r\n\r\n// Base64 encoding table\r\nvar b64 = new Array(64);\r\n\r\n// Base64 decoding table\r\nvar s64 = new Array(123);\r\n\r\n// 65..90, 97..122, 48..57, 43, 47\r\nfor (var i = 0; i < 64;)\r\n s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;\r\n\r\n/**\r\n * Encodes a buffer to a base64 encoded string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} Base64 encoded string\r\n */\r\nbase64.encode = function encode(buffer, start, end) {\r\n var parts = null,\r\n chunk = [];\r\n var i = 0, // output index\r\n j = 0, // goto index\r\n t; // temporary\r\n while (start < end) {\r\n var b = buffer[start++];\r\n switch (j) {\r\n case 0:\r\n chunk[i++] = b64[b >> 2];\r\n t = (b & 3) << 4;\r\n j = 1;\r\n break;\r\n case 1:\r\n chunk[i++] = b64[t | b >> 4];\r\n t = (b & 15) << 2;\r\n j = 2;\r\n break;\r\n case 2:\r\n chunk[i++] = b64[t | b >> 6];\r\n chunk[i++] = b64[b & 63];\r\n j = 0;\r\n break;\r\n }\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (j) {\r\n chunk[i++] = b64[t];\r\n chunk[i++] = 61;\r\n if (j === 1)\r\n chunk[i++] = 61;\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\nvar invalidEncoding = \"invalid encoding\";\r\n\r\n/**\r\n * Decodes a base64 encoded string to a buffer.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Number of bytes written\r\n * @throws {Error} If encoding is invalid\r\n */\r\nbase64.decode = function decode(string, buffer, offset) {\r\n var start = offset;\r\n var j = 0, // goto index\r\n t; // temporary\r\n for (var i = 0; i < string.length;) {\r\n var c = string.charCodeAt(i++);\r\n if (c === 61 && j > 1)\r\n break;\r\n if ((c = s64[c]) === undefined)\r\n throw Error(invalidEncoding);\r\n switch (j) {\r\n case 0:\r\n t = c;\r\n j = 1;\r\n break;\r\n case 1:\r\n buffer[offset++] = t << 2 | (c & 48) >> 4;\r\n t = c;\r\n j = 2;\r\n break;\r\n case 2:\r\n buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;\r\n t = c;\r\n j = 3;\r\n break;\r\n case 3:\r\n buffer[offset++] = (t & 3) << 6 | c;\r\n j = 0;\r\n break;\r\n }\r\n }\r\n if (j === 1)\r\n throw Error(invalidEncoding);\r\n return offset - start;\r\n};\r\n\r\n/**\r\n * Tests if the specified string appears to be base64 encoded.\r\n * @param {string} string String to test\r\n * @returns {boolean} `true` if probably base64 encoded, otherwise false\r\n */\r\nbase64.test = function test(string) {\r\n return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);\r\n};\r\n","\"use strict\";\r\nmodule.exports = codegen;\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @param {string[]} functionParams Function parameter names\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n */\r\nfunction codegen(functionParams, functionName) {\r\n\r\n /* istanbul ignore if */\r\n if (typeof functionParams === \"string\") {\r\n functionName = functionParams;\r\n functionParams = undefined;\r\n }\r\n\r\n var body = [];\r\n\r\n /**\r\n * Appends code to the function's body or finishes generation.\r\n * @typedef Codegen\r\n * @type {function}\r\n * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any\r\n * @param {...*} [formatParams] Format parameters\r\n * @returns {Codegen|Function} Itself or the generated function if finished\r\n * @throws {Error} If format parameter counts do not match\r\n */\r\n\r\n function Codegen(formatStringOrScope) {\r\n // note that explicit array handling below makes this ~50% faster\r\n\r\n // finish the function\r\n if (typeof formatStringOrScope !== \"string\") {\r\n var source = toString();\r\n if (codegen.verbose)\r\n console.log(\"codegen: \" + source); // eslint-disable-line no-console\r\n source = \"return \" + source;\r\n if (formatStringOrScope) {\r\n var scopeKeys = Object.keys(formatStringOrScope),\r\n scopeParams = new Array(scopeKeys.length + 1),\r\n scopeValues = new Array(scopeKeys.length),\r\n scopeOffset = 0;\r\n while (scopeOffset < scopeKeys.length) {\r\n scopeParams[scopeOffset] = scopeKeys[scopeOffset];\r\n scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]];\r\n }\r\n scopeParams[scopeOffset] = source;\r\n return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func\r\n }\r\n return Function(source)(); // eslint-disable-line no-new-func\r\n }\r\n\r\n // otherwise append to body\r\n var formatParams = new Array(arguments.length - 1),\r\n formatOffset = 0;\r\n while (formatOffset < formatParams.length)\r\n formatParams[formatOffset] = arguments[++formatOffset];\r\n formatOffset = 0;\r\n formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) {\r\n var value = formatParams[formatOffset++];\r\n switch ($1) {\r\n case \"d\": case \"f\": return String(Number(value));\r\n case \"i\": return String(Math.floor(value));\r\n case \"j\": return JSON.stringify(value);\r\n case \"s\": return String(value);\r\n }\r\n return \"%\";\r\n });\r\n if (formatOffset !== formatParams.length)\r\n throw Error(\"parameter count mismatch\");\r\n body.push(formatStringOrScope);\r\n return Codegen;\r\n }\r\n\r\n function toString(functionNameOverride) {\r\n return \"function \" + (functionNameOverride || functionName || \"\") + \"(\" + (functionParams && functionParams.join(\",\") || \"\") + \"){\\n \" + body.join(\"\\n \") + \"\\n}\";\r\n }\r\n\r\n Codegen.toString = toString;\r\n return Codegen;\r\n}\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @function codegen\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * When set to `true`, codegen will log generated code to console. Useful for debugging.\r\n * @name util.codegen.verbose\r\n * @type {boolean}\r\n */\r\ncodegen.verbose = false;\r\n","\"use strict\";\r\nmodule.exports = EventEmitter;\r\n\r\n/**\r\n * Constructs a new event emitter instance.\r\n * @classdesc A minimal event emitter.\r\n * @memberof util\r\n * @constructor\r\n */\r\nfunction EventEmitter() {\r\n\r\n /**\r\n * Registered listeners.\r\n * @type {Object.}\r\n * @private\r\n */\r\n this._listeners = {};\r\n}\r\n\r\n/**\r\n * Registers an event listener.\r\n * @param {string} evt Event name\r\n * @param {function} fn Listener\r\n * @param {*} [ctx] Listener context\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.on = function on(evt, fn, ctx) {\r\n (this._listeners[evt] || (this._listeners[evt] = [])).push({\r\n fn : fn,\r\n ctx : ctx || this\r\n });\r\n return this;\r\n};\r\n\r\n/**\r\n * Removes an event listener or any matching listeners if arguments are omitted.\r\n * @param {string} [evt] Event name. Removes all listeners if omitted.\r\n * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.off = function off(evt, fn) {\r\n if (evt === undefined)\r\n this._listeners = {};\r\n else {\r\n if (fn === undefined)\r\n this._listeners[evt] = [];\r\n else {\r\n var listeners = this._listeners[evt];\r\n for (var i = 0; i < listeners.length;)\r\n if (listeners[i].fn === fn)\r\n listeners.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emits an event by calling its listeners with the specified arguments.\r\n * @param {string} evt Event name\r\n * @param {...*} args Arguments\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.emit = function emit(evt) {\r\n var listeners = this._listeners[evt];\r\n if (listeners) {\r\n var args = [],\r\n i = 1;\r\n for (; i < arguments.length;)\r\n args.push(arguments[i++]);\r\n for (i = 0; i < listeners.length;)\r\n listeners[i].fn.apply(listeners[i++].ctx, args);\r\n }\r\n return this;\r\n};\r\n","\"use strict\";\r\nmodule.exports = fetch;\r\n\r\nvar asPromise = require(1),\r\n inquire = require(7);\r\n\r\nvar fs = inquire(\"fs\");\r\n\r\n/**\r\n * Node-style callback as used by {@link util.fetch}.\r\n * @typedef FetchCallback\r\n * @type {function}\r\n * @param {?Error} error Error, if any, otherwise `null`\r\n * @param {string} [contents] File contents, if there hasn't been an error\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Options as used by {@link util.fetch}.\r\n * @typedef FetchOptions\r\n * @type {Object}\r\n * @property {boolean} [binary=false] Whether expecting a binary response\r\n * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @memberof util\r\n * @param {string} filename File path or url\r\n * @param {FetchOptions} options Fetch options\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n */\r\nfunction fetch(filename, options, callback) {\r\n if (typeof options === \"function\") {\r\n callback = options;\r\n options = {};\r\n } else if (!options)\r\n options = {};\r\n\r\n if (!callback)\r\n return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this\r\n\r\n // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found.\r\n if (!options.xhr && fs && fs.readFile)\r\n return fs.readFile(filename, function fetchReadFileCallback(err, contents) {\r\n return err && typeof XMLHttpRequest !== \"undefined\"\r\n ? fetch.xhr(filename, options, callback)\r\n : err\r\n ? callback(err)\r\n : callback(null, options.binary ? contents : contents.toString(\"utf8\"));\r\n });\r\n\r\n // use the XHR version otherwise.\r\n return fetch.xhr(filename, options, callback);\r\n}\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchOptions} [options] Fetch options\r\n * @returns {Promise} Promise\r\n * @variation 3\r\n */\r\n\r\n/**/\r\nfetch.xhr = function fetch_xhr(filename, options, callback) {\r\n var xhr = new XMLHttpRequest();\r\n xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() {\r\n\r\n if (xhr.readyState !== 4)\r\n return undefined;\r\n\r\n // local cors security errors return status 0 / empty string, too. afaik this cannot be\r\n // reliably distinguished from an actually empty file for security reasons. feel free\r\n // to send a pull request if you are aware of a solution.\r\n if (xhr.status !== 0 && xhr.status !== 200)\r\n return callback(Error(\"status \" + xhr.status));\r\n\r\n // if binary data is expected, make sure that some sort of array is returned, even if\r\n // ArrayBuffers are not supported. the binary string fallback, however, is unsafe.\r\n if (options.binary) {\r\n var buffer = xhr.response;\r\n if (!buffer) {\r\n buffer = [];\r\n for (var i = 0; i < xhr.responseText.length; ++i)\r\n buffer.push(xhr.responseText.charCodeAt(i) & 255);\r\n }\r\n return callback(null, typeof Uint8Array !== \"undefined\" ? new Uint8Array(buffer) : buffer);\r\n }\r\n return callback(null, xhr.responseText);\r\n };\r\n\r\n if (options.binary) {\r\n // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers\r\n if (\"overrideMimeType\" in xhr)\r\n xhr.overrideMimeType(\"text/plain; charset=x-user-defined\");\r\n xhr.responseType = \"arraybuffer\";\r\n }\r\n\r\n xhr.open(\"GET\", filename);\r\n xhr.send();\r\n};\r\n","\"use strict\";\r\n\r\nmodule.exports = factory(factory);\r\n\r\n/**\r\n * Reads / writes floats / doubles from / to buffers.\r\n * @name util.float\r\n * @namespace\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using little endian byte order.\r\n * @name util.float.writeFloatLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using big endian byte order.\r\n * @name util.float.writeFloatBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using little endian byte order.\r\n * @name util.float.readFloatLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using big endian byte order.\r\n * @name util.float.readFloatBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using little endian byte order.\r\n * @name util.float.writeDoubleLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using big endian byte order.\r\n * @name util.float.writeDoubleBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using little endian byte order.\r\n * @name util.float.readDoubleLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using big endian byte order.\r\n * @name util.float.readDoubleBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n// Factory function for the purpose of node-based testing in modified global environments\r\nfunction factory(exports) {\r\n\r\n // float: typed array\r\n if (typeof Float32Array !== \"undefined\") (function() {\r\n\r\n var f32 = new Float32Array([ -0 ]),\r\n f8b = new Uint8Array(f32.buffer),\r\n le = f8b[3] === 128;\r\n\r\n function writeFloat_f32_cpy(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n }\r\n\r\n function writeFloat_f32_rev(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[3];\r\n buf[pos + 1] = f8b[2];\r\n buf[pos + 2] = f8b[1];\r\n buf[pos + 3] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;\r\n\r\n function readFloat_f32_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n function readFloat_f32_rev(buf, pos) {\r\n f8b[3] = buf[pos ];\r\n f8b[2] = buf[pos + 1];\r\n f8b[1] = buf[pos + 2];\r\n f8b[0] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;\r\n\r\n // float: ieee754\r\n })(); else (function() {\r\n\r\n function writeFloat_ieee754(writeUint, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0)\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);\r\n else if (isNaN(val))\r\n writeUint(2143289344, buf, pos);\r\n else if (val > 3.4028234663852886e+38) // +-Infinity\r\n writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);\r\n else if (val < 1.1754943508222875e-38) // denormal\r\n writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);\r\n else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2),\r\n mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;\r\n writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);\r\n }\r\n }\r\n\r\n exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);\r\n exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);\r\n\r\n function readFloat_ieee754(readUint, buf, pos) {\r\n var uint = readUint(buf, pos),\r\n sign = (uint >> 31) * 2 + 1,\r\n exponent = uint >>> 23 & 255,\r\n mantissa = uint & 8388607;\r\n return exponent === 255\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 1.401298464324817e-45 * mantissa\r\n : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);\r\n }\r\n\r\n exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);\r\n exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);\r\n\r\n })();\r\n\r\n // double: typed array\r\n if (typeof Float64Array !== \"undefined\") (function() {\r\n\r\n var f64 = new Float64Array([-0]),\r\n f8b = new Uint8Array(f64.buffer),\r\n le = f8b[7] === 128;\r\n\r\n function writeDouble_f64_cpy(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n buf[pos + 4] = f8b[4];\r\n buf[pos + 5] = f8b[5];\r\n buf[pos + 6] = f8b[6];\r\n buf[pos + 7] = f8b[7];\r\n }\r\n\r\n function writeDouble_f64_rev(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[7];\r\n buf[pos + 1] = f8b[6];\r\n buf[pos + 2] = f8b[5];\r\n buf[pos + 3] = f8b[4];\r\n buf[pos + 4] = f8b[3];\r\n buf[pos + 5] = f8b[2];\r\n buf[pos + 6] = f8b[1];\r\n buf[pos + 7] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;\r\n\r\n function readDouble_f64_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n f8b[4] = buf[pos + 4];\r\n f8b[5] = buf[pos + 5];\r\n f8b[6] = buf[pos + 6];\r\n f8b[7] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n function readDouble_f64_rev(buf, pos) {\r\n f8b[7] = buf[pos ];\r\n f8b[6] = buf[pos + 1];\r\n f8b[5] = buf[pos + 2];\r\n f8b[4] = buf[pos + 3];\r\n f8b[3] = buf[pos + 4];\r\n f8b[2] = buf[pos + 5];\r\n f8b[1] = buf[pos + 6];\r\n f8b[0] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;\r\n\r\n // double: ieee754\r\n })(); else (function() {\r\n\r\n function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);\r\n } else if (isNaN(val)) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(2146959360, buf, pos + off1);\r\n } else if (val > 1.7976931348623157e+308) { // +-Infinity\r\n writeUint(0, buf, pos + off0);\r\n writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);\r\n } else {\r\n var mantissa;\r\n if (val < 2.2250738585072014e-308) { // denormal\r\n mantissa = val / 5e-324;\r\n writeUint(mantissa >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);\r\n } else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2);\r\n if (exponent === 1024)\r\n exponent = 1023;\r\n mantissa = val * Math.pow(2, -exponent);\r\n writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);\r\n }\r\n }\r\n }\r\n\r\n exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);\r\n exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);\r\n\r\n function readDouble_ieee754(readUint, off0, off1, buf, pos) {\r\n var lo = readUint(buf, pos + off0),\r\n hi = readUint(buf, pos + off1);\r\n var sign = (hi >> 31) * 2 + 1,\r\n exponent = hi >>> 20 & 2047,\r\n mantissa = 4294967296 * (hi & 1048575) + lo;\r\n return exponent === 2047\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 5e-324 * mantissa\r\n : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);\r\n }\r\n\r\n exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);\r\n exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);\r\n\r\n })();\r\n\r\n return exports;\r\n}\r\n\r\n// uint helpers\r\n\r\nfunction writeUintLE(val, buf, pos) {\r\n buf[pos ] = val & 255;\r\n buf[pos + 1] = val >>> 8 & 255;\r\n buf[pos + 2] = val >>> 16 & 255;\r\n buf[pos + 3] = val >>> 24;\r\n}\r\n\r\nfunction writeUintBE(val, buf, pos) {\r\n buf[pos ] = val >>> 24;\r\n buf[pos + 1] = val >>> 16 & 255;\r\n buf[pos + 2] = val >>> 8 & 255;\r\n buf[pos + 3] = val & 255;\r\n}\r\n\r\nfunction readUintLE(buf, pos) {\r\n return (buf[pos ]\r\n | buf[pos + 1] << 8\r\n | buf[pos + 2] << 16\r\n | buf[pos + 3] << 24) >>> 0;\r\n}\r\n\r\nfunction readUintBE(buf, pos) {\r\n return (buf[pos ] << 24\r\n | buf[pos + 1] << 16\r\n | buf[pos + 2] << 8\r\n | buf[pos + 3]) >>> 0;\r\n}\r\n","\"use strict\";\r\nmodule.exports = inquire;\r\n\r\n/**\r\n * Requires a module only if available.\r\n * @memberof util\r\n * @param {string} moduleName Module to require\r\n * @returns {?Object} Required module if available and not empty, otherwise `null`\r\n */\r\nfunction inquire(moduleName) {\r\n try {\r\n var mod = eval(\"quire\".replace(/^/,\"re\"))(moduleName); // eslint-disable-line no-eval\r\n if (mod && (mod.length || Object.keys(mod).length))\r\n return mod;\r\n } catch (e) {} // eslint-disable-line no-empty\r\n return null;\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal path module to resolve Unix, Windows and URL paths alike.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar path = exports;\r\n\r\nvar isAbsolute =\r\n/**\r\n * Tests if the specified path is absolute.\r\n * @param {string} path Path to test\r\n * @returns {boolean} `true` if path is absolute\r\n */\r\npath.isAbsolute = function isAbsolute(path) {\r\n return /^(?:\\/|\\w+:)/.test(path);\r\n};\r\n\r\nvar normalize =\r\n/**\r\n * Normalizes the specified path.\r\n * @param {string} path Path to normalize\r\n * @returns {string} Normalized path\r\n */\r\npath.normalize = function normalize(path) {\r\n path = path.replace(/\\\\/g, \"/\")\r\n .replace(/\\/{2,}/g, \"/\");\r\n var parts = path.split(\"/\"),\r\n absolute = isAbsolute(path),\r\n prefix = \"\";\r\n if (absolute)\r\n prefix = parts.shift() + \"/\";\r\n for (var i = 0; i < parts.length;) {\r\n if (parts[i] === \"..\") {\r\n if (i > 0 && parts[i - 1] !== \"..\")\r\n parts.splice(--i, 2);\r\n else if (absolute)\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n } else if (parts[i] === \".\")\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n return prefix + parts.join(\"/\");\r\n};\r\n\r\n/**\r\n * Resolves the specified include path against the specified origin path.\r\n * @param {string} originPath Path to the origin file\r\n * @param {string} includePath Include path relative to origin path\r\n * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized\r\n * @returns {string} Path to the include file\r\n */\r\npath.resolve = function resolve(originPath, includePath, alreadyNormalized) {\r\n if (!alreadyNormalized)\r\n includePath = normalize(includePath);\r\n if (isAbsolute(includePath))\r\n return includePath;\r\n if (!alreadyNormalized)\r\n originPath = normalize(originPath);\r\n return (originPath = originPath.replace(/(?:\\/|^)[^/]+$/, \"\")).length ? normalize(originPath + \"/\" + includePath) : includePath;\r\n};\r\n","\"use strict\";\r\nmodule.exports = pool;\r\n\r\n/**\r\n * An allocator as used by {@link util.pool}.\r\n * @typedef PoolAllocator\r\n * @type {function}\r\n * @param {number} size Buffer size\r\n * @returns {Uint8Array} Buffer\r\n */\r\n\r\n/**\r\n * A slicer as used by {@link util.pool}.\r\n * @typedef PoolSlicer\r\n * @type {function}\r\n * @param {number} start Start offset\r\n * @param {number} end End offset\r\n * @returns {Uint8Array} Buffer slice\r\n * @this {Uint8Array}\r\n */\r\n\r\n/**\r\n * A general purpose buffer pool.\r\n * @memberof util\r\n * @function\r\n * @param {PoolAllocator} alloc Allocator\r\n * @param {PoolSlicer} slice Slicer\r\n * @param {number} [size=8192] Slab size\r\n * @returns {PoolAllocator} Pooled allocator\r\n */\r\nfunction pool(alloc, slice, size) {\r\n var SIZE = size || 8192;\r\n var MAX = SIZE >>> 1;\r\n var slab = null;\r\n var offset = SIZE;\r\n return function pool_alloc(size) {\r\n if (size < 1 || size > MAX)\r\n return alloc(size);\r\n if (offset + size > SIZE) {\r\n slab = alloc(SIZE);\r\n offset = 0;\r\n }\r\n var buf = slice.call(slab, offset, offset += size);\r\n if (offset & 7) // align to 32 bit\r\n offset = (offset | 7) + 1;\r\n return buf;\r\n };\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal UTF8 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar utf8 = exports;\r\n\r\n/**\r\n * Calculates the UTF8 byte length of a string.\r\n * @param {string} string String\r\n * @returns {number} Byte length\r\n */\r\nutf8.length = function utf8_length(string) {\r\n var len = 0,\r\n c = 0;\r\n for (var i = 0; i < string.length; ++i) {\r\n c = string.charCodeAt(i);\r\n if (c < 128)\r\n len += 1;\r\n else if (c < 2048)\r\n len += 2;\r\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\r\n ++i;\r\n len += 4;\r\n } else\r\n len += 3;\r\n }\r\n return len;\r\n};\r\n\r\n/**\r\n * Reads UTF8 bytes as a string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} String read\r\n */\r\nutf8.read = function utf8_read(buffer, start, end) {\r\n var len = end - start;\r\n if (len < 1)\r\n return \"\";\r\n var parts = null,\r\n chunk = [],\r\n i = 0, // char offset\r\n t; // temporary\r\n while (start < end) {\r\n t = buffer[start++];\r\n if (t < 128)\r\n chunk[i++] = t;\r\n else if (t > 191 && t < 224)\r\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\r\n else if (t > 239 && t < 365) {\r\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\r\n chunk[i++] = 0xD800 + (t >> 10);\r\n chunk[i++] = 0xDC00 + (t & 1023);\r\n } else\r\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\n/**\r\n * Writes a string as UTF8 bytes.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Bytes written\r\n */\r\nutf8.write = function utf8_write(string, buffer, offset) {\r\n var start = offset,\r\n c1, // character 1\r\n c2; // character 2\r\n for (var i = 0; i < string.length; ++i) {\r\n c1 = string.charCodeAt(i);\r\n if (c1 < 128) {\r\n buffer[offset++] = c1;\r\n } else if (c1 < 2048) {\r\n buffer[offset++] = c1 >> 6 | 192;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\r\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\r\n ++i;\r\n buffer[offset++] = c1 >> 18 | 240;\r\n buffer[offset++] = c1 >> 12 & 63 | 128;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else {\r\n buffer[offset++] = c1 >> 12 | 224;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n }\r\n }\r\n return offset - start;\r\n};\r\n","\"use strict\";\n/**\n * Runtime message from/to plain object converters.\n * @namespace\n */\nvar converter = exports;\n\nvar Enum = require(14),\n util = require(33);\n\n/**\n * Generates a partial value fromObject conveter.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {number} fieldIndex Field index\n * @param {string} prop Property reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genValuePartial_fromObject(gen, field, fieldIndex, prop) {\n var defaultAlreadyEmitted = false;\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n if (field.resolvedType) {\n if (field.resolvedType instanceof Enum) { gen\n (\"switch(d%s){\", prop);\n for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {\n // enum unknown values passthrough\n if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen\n (\"default:\")\n (\"if(typeof(d%s)===\\\"number\\\"){m%s=d%s;break}\", prop, prop, prop);\n if (!field.repeated) gen // fallback to default value only for\n // arrays, to avoid leaving holes.\n (\"break\"); // for non-repeated fields, just ignore\n defaultAlreadyEmitted = true;\n }\n gen\n (\"case%j:\", keys[i])\n (\"case %i:\", values[keys[i]])\n (\"m%s=%j\", prop, values[keys[i]])\n (\"break\");\n } gen\n (\"}\");\n } else gen\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\n (\"m%s=types[%i].fromObject(d%s)\", prop, fieldIndex, prop);\n } else {\n var isUnsigned = false;\n switch (field.type) {\n case \"double\":\n case \"float\": gen\n (\"m%s=Number(d%s)\", prop, prop); // also catches \"NaN\", \"Infinity\"\n break;\n case \"uint32\":\n case \"fixed32\": gen\n (\"m%s=d%s>>>0\", prop, prop);\n break;\n case \"int32\":\n case \"sint32\":\n case \"sfixed32\": gen\n (\"m%s=d%s|0\", prop, prop);\n break;\n case \"uint64\":\n isUnsigned = true;\n // eslint-disable-next-line no-fallthrough\n case \"int64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(util.Long)\")\n (\"(m%s=util.Long.fromValue(d%s)).unsigned=%j\", prop, prop, isUnsigned)\n (\"else if(typeof d%s===\\\"string\\\")\", prop)\n (\"m%s=parseInt(d%s,10)\", prop, prop)\n (\"else if(typeof d%s===\\\"number\\\")\", prop)\n (\"m%s=d%s\", prop, prop)\n (\"else if(typeof d%s===\\\"object\\\")\", prop)\n (\"m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)\", prop, prop, prop, isUnsigned ? \"true\" : \"\");\n break;\n case \"bytes\": gen\n (\"if(typeof d%s===\\\"string\\\")\", prop)\n (\"util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)\", prop, prop, prop)\n (\"else if(d%s.length >= 0)\", prop)\n (\"m%s=d%s\", prop, prop);\n break;\n case \"string\": gen\n (\"m%s=String(d%s)\", prop, prop);\n break;\n case \"bool\": gen\n (\"m%s=Boolean(d%s)\", prop, prop);\n break;\n /* default: gen\n (\"m%s=d%s\", prop, prop);\n break; */\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n\n/**\n * Generates a plain object to runtime message converter specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nconverter.fromObject = function fromObject(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var fields = mtype.fieldsArray;\n var gen = util.codegen([\"d\"], mtype.name + \"$fromObject\")\n (\"if(d instanceof this.ctor)\")\n (\"return d\");\n if (!fields.length) return gen\n (\"return new this.ctor\");\n gen\n (\"var m=new this.ctor\");\n for (var i = 0; i < fields.length; ++i) {\n var field = fields[i].resolve(),\n prop = util.safeProp(field.name);\n\n // Map fields\n if (field.map) { gen\n (\"if(d%s){\", prop)\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\n (\"m%s={}\", prop)\n (\"for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s\", prop, prop, prop, prop, isUnsigned ? \"true\": \"\", prop);\n break;\n case \"bytes\": gen\n (\"d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s\", prop, prop, prop, prop, prop);\n break;\n default: gen\n (\"d%s=m%s\", prop, prop);\n break;\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n\n/**\n * Generates a runtime message to plain object converter specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nconverter.toObject = function toObject(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById);\n if (!fields.length)\n return util.codegen()(\"return {}\");\n var gen = util.codegen([\"m\", \"o\"], mtype.name + \"$toObject\")\n (\"if(!o)\")\n (\"o={}\")\n (\"var d={}\");\n\n var repeatedFields = [],\n mapFields = [],\n normalFields = [],\n i = 0;\n for (; i < fields.length; ++i)\n if (!fields[i].partOf)\n ( fields[i].resolve().repeated ? repeatedFields\n : fields[i].map ? mapFields\n : normalFields).push(fields[i]);\n\n if (repeatedFields.length) { gen\n (\"if(o.arrays||o.defaults){\");\n for (i = 0; i < repeatedFields.length; ++i) gen\n (\"d%s=[]\", util.safeProp(repeatedFields[i].name));\n gen\n (\"}\");\n }\n\n if (mapFields.length) { gen\n (\"if(o.objects||o.defaults){\");\n for (i = 0; i < mapFields.length; ++i) gen\n (\"d%s={}\", util.safeProp(mapFields[i].name));\n gen\n (\"}\");\n }\n\n if (normalFields.length) { gen\n (\"if(o.defaults){\");\n for (i = 0; i < normalFields.length; ++i) {\n var field = normalFields[i],\n prop = util.safeProp(field.name);\n if (field.resolvedType instanceof Enum) gen\n (\"d%s=o.enums===String?%j:%j\", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault);\n else if (field.long) gen\n (\"if(util.Long){\")\n (\"var n=new util.Long(%i,%i,%j)\", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)\n (\"d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n\", prop)\n (\"}else\")\n (\"d%s=o.longs===String?%j:%i\", prop, field.typeDefault.toString(), field.typeDefault.toNumber());\n else if (field.bytes) {\n var arrayDefault = \"[\" + Array.prototype.slice.call(field.typeDefault).join(\",\") + \"]\";\n gen\n (\"if(o.bytes===String)d%s=%j\", prop, String.fromCharCode.apply(String, field.typeDefault))\n (\"else{\")\n (\"d%s=%s\", prop, arrayDefault)\n (\"if(o.bytes!==Array)d%s=util.newBuffer(d%s)\", prop, prop)\n (\"}\");\n } else gen\n (\"d%s=%j\", prop, field.typeDefault); // also messages (=null)\n } gen\n (\"}\");\n }\n var hasKs2 = false;\n for (i = 0; i < fields.length; ++i) {\n var field = fields[i],\n index = mtype._fieldsArray.indexOf(field),\n prop = util.safeProp(field.name);\n if (field.map) {\n if (!hasKs2) { hasKs2 = true; gen\n (\"var ks2\");\n } gen\n (\"if(m%s&&(ks2=Object.keys(m%s)).length){\", prop, prop)\n (\"d%s={}\", prop)\n (\"for(var j=0;j>>3){\");\n\n var i = 0;\n for (; i < /* initializes */ mtype.fieldsArray.length; ++i) {\n var field = mtype._fieldsArray[i].resolve(),\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\n ref = \"m\" + util.safeProp(field.name); gen\n (\"case %i: {\", field.id);\n\n // Map fields\n if (field.map) { gen\n (\"if(%s===util.emptyObject)\", ref)\n (\"%s={}\", ref)\n (\"var c2 = r.uint32()+r.pos\");\n\n if (types.defaults[field.keyType] !== undefined) gen\n (\"k=%j\", types.defaults[field.keyType]);\n else gen\n (\"k=null\");\n\n if (types.defaults[type] !== undefined) gen\n (\"value=%j\", types.defaults[type]);\n else gen\n (\"value=null\");\n\n gen\n (\"while(r.pos>>3){\")\n (\"case 1: k=r.%s(); break\", field.keyType)\n (\"case 2:\");\n\n if (types.basic[type] === undefined) gen\n (\"value=types[%i].decode(r,r.uint32())\", i); // can't be groups\n else gen\n (\"value=r.%s()\", type);\n\n gen\n (\"break\")\n (\"default:\")\n (\"r.skipType(tag2&7)\")\n (\"break\")\n (\"}\")\n (\"}\");\n\n if (types.long[field.keyType] !== undefined) gen\n (\"%s[typeof k===\\\"object\\\"?util.longToHash(k):k]=value\", ref);\n else gen\n (\"%s[k]=value\", ref);\n\n // Repeated fields\n } else if (field.repeated) { gen\n\n (\"if(!(%s&&%s.length))\", ref, ref)\n (\"%s=[]\", ref);\n\n // Packable (always check for forward and backward compatiblity)\n if (types.packed[type] !== undefined) gen\n (\"if((t&7)===2){\")\n (\"var c2=r.uint32()+r.pos\")\n (\"while(r.pos>> 0, (field.id << 3 | 4) >>> 0)\n : gen(\"types[%i].encode(%s,w.uint32(%i).fork()).ldelim()\", fieldIndex, ref, (field.id << 3 | 2) >>> 0);\n}\n\n/**\n * Generates an encoder specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nfunction encoder(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var gen = util.codegen([\"m\", \"w\"], mtype.name + \"$encode\")\n (\"if(!w)\")\n (\"w=Writer.create()\");\n\n var i, ref;\n\n // \"when a message is serialized its known fields should be written sequentially by field number\"\n var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById);\n\n for (var i = 0; i < fields.length; ++i) {\n var field = fields[i].resolve(),\n index = mtype._fieldsArray.indexOf(field),\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\n wireType = types.basic[type];\n ref = \"m\" + util.safeProp(field.name);\n\n // Map fields\n if (field.map) {\n gen\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j)){\", ref, field.name) // !== undefined && !== null\n (\"for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType);\n if (wireType === undefined) gen\n (\"types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()\", index, ref); // can't be groups\n else gen\n (\".uint32(%i).%s(%s[ks[i]]).ldelim()\", 16 | wireType, type, ref);\n gen\n (\"}\")\n (\"}\");\n\n // Repeated fields\n } else if (field.repeated) { gen\n (\"if(%s!=null&&%s.length){\", ref, ref); // !== undefined && !== null\n\n // Packed repeated\n if (field.packed && types.packed[type] !== undefined) { gen\n\n (\"w.uint32(%i).fork()\", (field.id << 3 | 2) >>> 0)\n (\"for(var i=0;i<%s.length;++i)\", ref)\n (\"w.%s(%s[i])\", type, ref)\n (\"w.ldelim()\");\n\n // Non-packed\n } else { gen\n\n (\"for(var i=0;i<%s.length;++i)\", ref);\n if (wireType === undefined)\n genTypePartial(gen, field, index, ref + \"[i]\");\n else gen\n (\"w.uint32(%i).%s(%s[i])\", (field.id << 3 | wireType) >>> 0, type, ref);\n\n } gen\n (\"}\");\n\n // Non-repeated\n } else {\n if (field.optional) gen\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j))\", ref, field.name); // !== undefined && !== null\n\n if (wireType === undefined)\n genTypePartial(gen, field, index, ref);\n else gen\n (\"w.uint32(%i).%s(%s)\", (field.id << 3 | wireType) >>> 0, type, ref);\n\n }\n }\n\n return gen\n (\"return w\");\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n","\"use strict\";\nmodule.exports = Enum;\n\n// extends ReflectionObject\nvar ReflectionObject = require(22);\n((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = \"Enum\";\n\nvar Namespace = require(21),\n util = require(33);\n\n/**\n * Constructs a new enum instance.\n * @classdesc Reflected enum.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {Object.} [values] Enum values as an object, by name\n * @param {Object.} [options] Declared options\n * @param {string} [comment] The comment for this enum\n * @param {Object.} [comments] The value comments for this enum\n * @param {Object.>|undefined} [valuesOptions] The value options for this enum\n */\nfunction Enum(name, values, options, comment, comments, valuesOptions) {\n ReflectionObject.call(this, name, options);\n\n if (values && typeof values !== \"object\")\n throw TypeError(\"values must be an object\");\n\n /**\n * Enum values by id.\n * @type {Object.}\n */\n this.valuesById = {};\n\n /**\n * Enum values by name.\n * @type {Object.}\n */\n this.values = Object.create(this.valuesById); // toJSON, marker\n\n /**\n * Enum comment text.\n * @type {string|null}\n */\n this.comment = comment;\n\n /**\n * Value comment texts, if any.\n * @type {Object.}\n */\n this.comments = comments || {};\n\n /**\n * Values options, if any\n * @type {Object>|undefined}\n */\n this.valuesOptions = valuesOptions;\n\n /**\n * Resolved values features, if any\n * @type {Object>|undefined}\n */\n this._valuesFeatures = {};\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n // Note that values inherit valuesById on their prototype which makes them a TypeScript-\n // compatible enum. This is used by pbts to write actual enum definitions that work for\n // static and reflection code alike instead of emitting generic object definitions.\n\n if (values)\n for (var keys = Object.keys(values), i = 0; i < keys.length; ++i)\n if (typeof values[keys[i]] === \"number\") // use forward entries only\n this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i];\n}\n\n/**\n * @override\n */\nEnum.prototype._resolveFeatures = function _resolveFeatures(edition) {\n edition = this._edition || edition;\n ReflectionObject.prototype._resolveFeatures.call(this, edition);\n\n Object.keys(this.values).forEach(key => {\n var parentFeaturesCopy = Object.assign({}, this._features);\n this._valuesFeatures[key] = Object.assign(parentFeaturesCopy, this.valuesOptions && this.valuesOptions[key] && this.valuesOptions[key].features);\n });\n\n return this;\n};\n\n/**\n * Enum descriptor.\n * @interface IEnum\n * @property {Object.} values Enum values\n * @property {Object.} [options] Enum options\n */\n\n/**\n * Constructs an enum from an enum descriptor.\n * @param {string} name Enum name\n * @param {IEnum} json Enum descriptor\n * @returns {Enum} Created enum\n * @throws {TypeError} If arguments are invalid\n */\nEnum.fromJSON = function fromJSON(name, json) {\n var enm = new Enum(name, json.values, json.options, json.comment, json.comments);\n enm.reserved = json.reserved;\n if (json.edition)\n enm._edition = json.edition;\n enm._defaultEdition = \"proto3\"; // For backwards-compatibility.\n return enm;\n};\n\n/**\n * Converts this enum to an enum descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IEnum} Enum descriptor\n */\nEnum.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"edition\" , this._editionToJSON(),\n \"options\" , this.options,\n \"valuesOptions\" , this.valuesOptions,\n \"values\" , this.values,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"comment\" , keepComments ? this.comment : undefined,\n \"comments\" , keepComments ? this.comments : undefined\n ]);\n};\n\n/**\n * Adds a value to this enum.\n * @param {string} name Value name\n * @param {number} id Value id\n * @param {string} [comment] Comment, if any\n * @param {Object.|undefined} [options] Options, if any\n * @returns {Enum} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a value with this name or id\n */\nEnum.prototype.add = function add(name, id, comment, options) {\n // utilized by the parser but not by .fromJSON\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n if (!util.isInteger(id))\n throw TypeError(\"id must be an integer\");\n\n if (this.values[name] !== undefined)\n throw Error(\"duplicate name '\" + name + \"' in \" + this);\n\n if (this.isReservedId(id))\n throw Error(\"id \" + id + \" is reserved in \" + this);\n\n if (this.isReservedName(name))\n throw Error(\"name '\" + name + \"' is reserved in \" + this);\n\n if (this.valuesById[id] !== undefined) {\n if (!(this.options && this.options.allow_alias))\n throw Error(\"duplicate id \" + id + \" in \" + this);\n this.values[name] = id;\n } else\n this.valuesById[this.values[name] = id] = name;\n\n if (options) {\n if (this.valuesOptions === undefined)\n this.valuesOptions = {};\n this.valuesOptions[name] = options || null;\n }\n\n this.comments[name] = comment || null;\n return this;\n};\n\n/**\n * Removes a value from this enum\n * @param {string} name Value name\n * @returns {Enum} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `name` is not a name of this enum\n */\nEnum.prototype.remove = function remove(name) {\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n var val = this.values[name];\n if (val == null)\n throw Error(\"name '\" + name + \"' does not exist in \" + this);\n\n delete this.valuesById[val];\n delete this.values[name];\n delete this.comments[name];\n if (this.valuesOptions)\n delete this.valuesOptions[name];\n\n return this;\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nEnum.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nEnum.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n","\"use strict\";\nmodule.exports = Field;\n\n// extends ReflectionObject\nvar ReflectionObject = require(22);\n((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = \"Field\";\n\nvar Enum = require(14),\n types = require(32),\n util = require(33);\n\nvar Type; // cyclic\n\nvar ruleRe = /^required|optional|repeated$/;\n\n/**\n * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class.\n * @name Field\n * @classdesc Reflected message field.\n * @extends FieldBase\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} type Value type\n * @param {string|Object.} [rule=\"optional\"] Field rule\n * @param {string|Object.} [extend] Extended type if different from parent\n * @param {Object.} [options] Declared options\n */\n\n/**\n * Constructs a field from a field descriptor.\n * @param {string} name Field name\n * @param {IField} json Field descriptor\n * @returns {Field} Created field\n * @throws {TypeError} If arguments are invalid\n */\nField.fromJSON = function fromJSON(name, json) {\n var field = new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment);\n if (json.edition)\n field._edition = json.edition;\n field._defaultEdition = \"proto3\"; // For backwards-compatibility.\n return field;\n};\n\n/**\n * Not an actual constructor. Use {@link Field} instead.\n * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions.\n * @exports FieldBase\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} type Value type\n * @param {string|Object.} [rule=\"optional\"] Field rule\n * @param {string|Object.} [extend] Extended type if different from parent\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction Field(name, id, type, rule, extend, options, comment) {\n\n if (util.isObject(rule)) {\n comment = extend;\n options = rule;\n rule = extend = undefined;\n } else if (util.isObject(extend)) {\n comment = options;\n options = extend;\n extend = undefined;\n }\n\n ReflectionObject.call(this, name, options);\n\n if (!util.isInteger(id) || id < 0)\n throw TypeError(\"id must be a non-negative integer\");\n\n if (!util.isString(type))\n throw TypeError(\"type must be a string\");\n\n if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase()))\n throw TypeError(\"rule must be a string rule\");\n\n if (extend !== undefined && !util.isString(extend))\n throw TypeError(\"extend must be a string\");\n\n /**\n * Field rule, if any.\n * @type {string|undefined}\n */\n if (rule === \"proto3_optional\") {\n rule = \"optional\";\n }\n this.rule = rule && rule !== \"optional\" ? rule : undefined; // toJSON\n\n /**\n * Field type.\n * @type {string}\n */\n this.type = type; // toJSON\n\n /**\n * Unique field id.\n * @type {number}\n */\n this.id = id; // toJSON, marker\n\n /**\n * Extended type if different from parent.\n * @type {string|undefined}\n */\n this.extend = extend || undefined; // toJSON\n\n /**\n * Whether this field is repeated.\n * @type {boolean}\n */\n this.repeated = rule === \"repeated\";\n\n /**\n * Whether this field is a map or not.\n * @type {boolean}\n */\n this.map = false;\n\n /**\n * Message this field belongs to.\n * @type {Type|null}\n */\n this.message = null;\n\n /**\n * OneOf this field belongs to, if any,\n * @type {OneOf|null}\n */\n this.partOf = null;\n\n /**\n * The field type's default value.\n * @type {*}\n */\n this.typeDefault = null;\n\n /**\n * The field's default value on prototypes.\n * @type {*}\n */\n this.defaultValue = null;\n\n /**\n * Whether this field's value should be treated as a long.\n * @type {boolean}\n */\n this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false;\n\n /**\n * Whether this field's value is a buffer.\n * @type {boolean}\n */\n this.bytes = type === \"bytes\";\n\n /**\n * Resolved type if not a basic type.\n * @type {Type|Enum|null}\n */\n this.resolvedType = null;\n\n /**\n * Sister-field within the extended type if a declaring extension field.\n * @type {Field|null}\n */\n this.extensionField = null;\n\n /**\n * Sister-field within the declaring namespace if an extended field.\n * @type {Field|null}\n */\n this.declaringField = null;\n\n /**\n * Comment for this field.\n * @type {string|null}\n */\n this.comment = comment;\n}\n\n/**\n * Determines whether this field is required.\n * @name Field#required\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"required\", {\n get: function() {\n return this._features.field_presence === \"LEGACY_REQUIRED\";\n }\n});\n\n/**\n * Determines whether this field is not required.\n * @name Field#optional\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"optional\", {\n get: function() {\n return !this.required;\n }\n});\n\n/**\n * Determines whether this field uses tag-delimited encoding. In proto2 this\n * corresponded to group syntax.\n * @name Field#delimited\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"delimited\", {\n get: function() {\n return this.resolvedType instanceof Type &&\n this._features.message_encoding === \"DELIMITED\";\n }\n});\n\n/**\n * Determines whether this field is packed. Only relevant when repeated.\n * @name Field#packed\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"packed\", {\n get: function() {\n return this._features.repeated_field_encoding === \"PACKED\";\n }\n});\n\n/**\n * Determines whether this field tracks presence.\n * @name Field#hasPresence\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"hasPresence\", {\n get: function() {\n if (this.repeated || this.map) {\n return false;\n }\n return this.partOf || // oneofs\n this.declaringField || this.extensionField || // extensions\n this._features.field_presence !== \"IMPLICIT\";\n }\n});\n\n/**\n * @override\n */\nField.prototype.setOption = function setOption(name, value, ifNotSet) {\n return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet);\n};\n\n/**\n * Field descriptor.\n * @interface IField\n * @property {string} [rule=\"optional\"] Field rule\n * @property {string} type Field type\n * @property {number} id Field id\n * @property {Object.} [options] Field options\n */\n\n/**\n * Extension field descriptor.\n * @interface IExtensionField\n * @extends IField\n * @property {string} extend Extended type\n */\n\n/**\n * Converts this field to a field descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IField} Field descriptor\n */\nField.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"edition\" , this._editionToJSON(),\n \"rule\" , this.rule !== \"optional\" && this.rule || undefined,\n \"type\" , this.type,\n \"id\" , this.id,\n \"extend\" , this.extend,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Resolves this field's type references.\n * @returns {Field} `this`\n * @throws {Error} If any reference cannot be resolved\n */\nField.prototype.resolve = function resolve() {\n\n if (this.resolved)\n return this;\n\n if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it\n this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);\n if (this.resolvedType instanceof Type)\n this.typeDefault = null;\n else // instanceof Enum\n this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined\n } else if (this.options && this.options.proto3_optional) {\n // proto3 scalar value marked optional; should default to null\n this.typeDefault = null;\n }\n\n // use explicitly set default value if present\n if (this.options && this.options[\"default\"] != null) {\n this.typeDefault = this.options[\"default\"];\n if (this.resolvedType instanceof Enum && typeof this.typeDefault === \"string\")\n this.typeDefault = this.resolvedType.values[this.typeDefault];\n }\n\n // remove unnecessary options\n if (this.options) {\n if (this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum))\n delete this.options.packed;\n if (!Object.keys(this.options).length)\n this.options = undefined;\n }\n\n // convert to internal data type if necesssary\n if (this.long) {\n this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === \"u\");\n\n /* istanbul ignore else */\n if (Object.freeze)\n Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it)\n\n } else if (this.bytes && typeof this.typeDefault === \"string\") {\n var buf;\n if (util.base64.test(this.typeDefault))\n util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0);\n else\n util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0);\n this.typeDefault = buf;\n }\n\n // take special care of maps and repeated fields\n if (this.map)\n this.defaultValue = util.emptyObject;\n else if (this.repeated)\n this.defaultValue = util.emptyArray;\n else\n this.defaultValue = this.typeDefault;\n\n // ensure proper value on prototype\n if (this.parent instanceof Type)\n this.parent.ctor.prototype[this.name] = this.defaultValue;\n\n return ReflectionObject.prototype.resolve.call(this);\n};\n\n/**\n * Infers field features from legacy syntax that may have been specified differently.\n * in older editions.\n * @param {string|undefined} edition The edition this proto is on, or undefined if pre-editions\n * @returns {object} The feature values to override\n */\nField.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(edition) {\n if (edition !== \"proto2\" && edition !== \"proto3\") {\n return {};\n }\n\n var features = {};\n\n if (this.rule === \"required\") {\n features.field_presence = \"LEGACY_REQUIRED\";\n }\n if (this.parent && types.defaults[this.type] === undefined) {\n // We can't use resolvedType because types may not have been resolved yet. However,\n // legacy groups are always in the same scope as the field so we don't have to do a\n // full scan of the tree.\n var type = this.parent.get(this.type.split(\".\").pop());\n if (type && type instanceof Type && type.group) {\n features.message_encoding = \"DELIMITED\";\n }\n }\n if (this.getOption(\"packed\") === true) {\n features.repeated_field_encoding = \"PACKED\";\n } else if (this.getOption(\"packed\") === false) {\n features.repeated_field_encoding = \"EXPANDED\";\n }\n return features;\n};\n\n/**\n * @override\n */\nField.prototype._resolveFeatures = function _resolveFeatures(edition) {\n return ReflectionObject.prototype._resolveFeatures.call(this, this._edition || edition);\n};\n\n/**\n * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript).\n * @typedef FieldDecorator\n * @type {function}\n * @param {Object} prototype Target prototype\n * @param {string} fieldName Field name\n * @returns {undefined}\n */\n\n/**\n * Field decorator (TypeScript).\n * @name Field.d\n * @function\n * @param {number} fieldId Field id\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"string\"|\"bool\"|\"bytes\"|Object} fieldType Field type\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\n * @param {T} [defaultValue] Default value\n * @returns {FieldDecorator} Decorator function\n * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[]\n */\nField.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) {\n\n // submessage: decorate the submessage and use its name as the type\n if (typeof fieldType === \"function\")\n fieldType = util.decorateType(fieldType).name;\n\n // enum reference: create a reflected copy of the enum and keep reuseing it\n else if (fieldType && typeof fieldType === \"object\")\n fieldType = util.decorateEnum(fieldType).name;\n\n return function fieldDecorator(prototype, fieldName) {\n util.decorateType(prototype.constructor)\n .add(new Field(fieldName, fieldId, fieldType, fieldRule, { \"default\": defaultValue }));\n };\n};\n\n/**\n * Field decorator (TypeScript).\n * @name Field.d\n * @function\n * @param {number} fieldId Field id\n * @param {Constructor|string} fieldType Field type\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\n * @returns {FieldDecorator} Decorator function\n * @template T extends Message\n * @variation 2\n */\n// like Field.d but without a default value\n\n// Sets up cyclic dependencies (called in index-light)\nField._configure = function configure(Type_) {\n Type = Type_;\n};\n","\"use strict\";\nvar protobuf = module.exports = require(17);\n\nprotobuf.build = \"light\";\n\n/**\n * A node-style callback as used by {@link load} and {@link Root#load}.\n * @typedef LoadCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Root} [root] Root, if there hasn't been an error\n * @returns {undefined}\n */\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} root Root namespace, defaults to create a new one if omitted.\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @see {@link Root#load}\n */\nfunction load(filename, root, callback) {\n if (typeof root === \"function\") {\n callback = root;\n root = new protobuf.Root();\n } else if (!root)\n root = new protobuf.Root();\n return root.load(filename, callback);\n}\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\n * @name load\n * @function\n * @param {string|string[]} filename One or multiple files to load\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @see {@link Root#load}\n * @variation 2\n */\n// function load(filename:string, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise.\n * @name load\n * @function\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\n * @returns {Promise} Promise\n * @see {@link Root#load}\n * @variation 3\n */\n// function load(filename:string, [root:Root]):Promise\n\nprotobuf.load = load;\n\n/**\n * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only).\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\n * @returns {Root} Root namespace\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\n * @see {@link Root#loadSync}\n */\nfunction loadSync(filename, root) {\n if (!root)\n root = new protobuf.Root();\n return root.loadSync(filename);\n}\n\nprotobuf.loadSync = loadSync;\n\n// Serialization\nprotobuf.encoder = require(13);\nprotobuf.decoder = require(12);\nprotobuf.verifier = require(36);\nprotobuf.converter = require(11);\n\n// Reflection\nprotobuf.ReflectionObject = require(22);\nprotobuf.Namespace = require(21);\nprotobuf.Root = require(26);\nprotobuf.Enum = require(14);\nprotobuf.Type = require(31);\nprotobuf.Field = require(15);\nprotobuf.OneOf = require(23);\nprotobuf.MapField = require(18);\nprotobuf.Service = require(30);\nprotobuf.Method = require(20);\n\n// Runtime\nprotobuf.Message = require(19);\nprotobuf.wrappers = require(37);\n\n// Utility\nprotobuf.types = require(32);\nprotobuf.util = require(33);\n\n// Set up possibly cyclic reflection dependencies\nprotobuf.ReflectionObject._configure(protobuf.Root);\nprotobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum);\nprotobuf.Root._configure(protobuf.Type);\nprotobuf.Field._configure(protobuf.Type);\n","\"use strict\";\nvar protobuf = exports;\n\n/**\n * Build type, one of `\"full\"`, `\"light\"` or `\"minimal\"`.\n * @name build\n * @type {string}\n * @const\n */\nprotobuf.build = \"minimal\";\n\n// Serialization\nprotobuf.Writer = require(38);\nprotobuf.BufferWriter = require(39);\nprotobuf.Reader = require(24);\nprotobuf.BufferReader = require(25);\n\n// Utility\nprotobuf.util = require(35);\nprotobuf.rpc = require(28);\nprotobuf.roots = require(27);\nprotobuf.configure = configure;\n\n/* istanbul ignore next */\n/**\n * Reconfigures the library according to the environment.\n * @returns {undefined}\n */\nfunction configure() {\n protobuf.util._configure();\n protobuf.Writer._configure(protobuf.BufferWriter);\n protobuf.Reader._configure(protobuf.BufferReader);\n}\n\n// Set up buffer utility according to the environment\nconfigure();\n","\"use strict\";\nmodule.exports = MapField;\n\n// extends Field\nvar Field = require(15);\n((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = \"MapField\";\n\nvar types = require(32),\n util = require(33);\n\n/**\n * Constructs a new map field instance.\n * @classdesc Reflected map field.\n * @extends FieldBase\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} keyType Key type\n * @param {string} type Value type\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction MapField(name, id, keyType, type, options, comment) {\n Field.call(this, name, id, type, undefined, undefined, options, comment);\n\n /* istanbul ignore if */\n if (!util.isString(keyType))\n throw TypeError(\"keyType must be a string\");\n\n /**\n * Key type.\n * @type {string}\n */\n this.keyType = keyType; // toJSON, marker\n\n /**\n * Resolved key type if not a basic type.\n * @type {ReflectionObject|null}\n */\n this.resolvedKeyType = null;\n\n // Overrides Field#map\n this.map = true;\n}\n\n/**\n * Map field descriptor.\n * @interface IMapField\n * @extends {IField}\n * @property {string} keyType Key type\n */\n\n/**\n * Extension map field descriptor.\n * @interface IExtensionMapField\n * @extends IMapField\n * @property {string} extend Extended type\n */\n\n/**\n * Constructs a map field from a map field descriptor.\n * @param {string} name Field name\n * @param {IMapField} json Map field descriptor\n * @returns {MapField} Created map field\n * @throws {TypeError} If arguments are invalid\n */\nMapField.fromJSON = function fromJSON(name, json) {\n return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment);\n};\n\n/**\n * Converts this map field to a map field descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IMapField} Map field descriptor\n */\nMapField.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"keyType\" , this.keyType,\n \"type\" , this.type,\n \"id\" , this.id,\n \"extend\" , this.extend,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nMapField.prototype.resolve = function resolve() {\n if (this.resolved)\n return this;\n\n // Besides a value type, map fields have a key type that may be \"any scalar type except for floating point types and bytes\"\n if (types.mapKey[this.keyType] === undefined)\n throw Error(\"invalid key type: \" + this.keyType);\n\n return Field.prototype.resolve.call(this);\n};\n\n/**\n * Map field decorator (TypeScript).\n * @name MapField.d\n * @function\n * @param {number} fieldId Field id\n * @param {\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"} fieldKeyType Field key type\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"|\"bytes\"|Object|Constructor<{}>} fieldValueType Field value type\n * @returns {FieldDecorator} Decorator function\n * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> }\n */\nMapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) {\n\n // submessage value: decorate the submessage and use its name as the type\n if (typeof fieldValueType === \"function\")\n fieldValueType = util.decorateType(fieldValueType).name;\n\n // enum reference value: create a reflected copy of the enum and keep reuseing it\n else if (fieldValueType && typeof fieldValueType === \"object\")\n fieldValueType = util.decorateEnum(fieldValueType).name;\n\n return function mapFieldDecorator(prototype, fieldName) {\n util.decorateType(prototype.constructor)\n .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType));\n };\n};\n","\"use strict\";\nmodule.exports = Message;\n\nvar util = require(35);\n\n/**\n * Constructs a new message instance.\n * @classdesc Abstract runtime message.\n * @constructor\n * @param {Properties} [properties] Properties to set\n * @template T extends object = object\n */\nfunction Message(properties) {\n // not used internally\n if (properties)\n for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)\n this[keys[i]] = properties[keys[i]];\n}\n\n/**\n * Reference to the reflected type.\n * @name Message.$type\n * @type {Type}\n * @readonly\n */\n\n/**\n * Reference to the reflected type.\n * @name Message#$type\n * @type {Type}\n * @readonly\n */\n\n/*eslint-disable valid-jsdoc*/\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message} Message instance\n * @template T extends Message\n * @this Constructor\n */\nMessage.create = function create(properties) {\n return this.$type.create(properties);\n};\n\n/**\n * Encodes a message of this type.\n * @param {T|Object.} message Message to encode\n * @param {Writer} [writer] Writer to use\n * @returns {Writer} Writer\n * @template T extends Message\n * @this Constructor\n */\nMessage.encode = function encode(message, writer) {\n return this.$type.encode(message, writer);\n};\n\n/**\n * Encodes a message of this type preceeded by its length as a varint.\n * @param {T|Object.} message Message to encode\n * @param {Writer} [writer] Writer to use\n * @returns {Writer} Writer\n * @template T extends Message\n * @this Constructor\n */\nMessage.encodeDelimited = function encodeDelimited(message, writer) {\n return this.$type.encodeDelimited(message, writer);\n};\n\n/**\n * Decodes a message of this type.\n * @name Message.decode\n * @function\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\n * @returns {T} Decoded message\n * @template T extends Message\n * @this Constructor\n */\nMessage.decode = function decode(reader) {\n return this.$type.decode(reader);\n};\n\n/**\n * Decodes a message of this type preceeded by its length as a varint.\n * @name Message.decodeDelimited\n * @function\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\n * @returns {T} Decoded message\n * @template T extends Message\n * @this Constructor\n */\nMessage.decodeDelimited = function decodeDelimited(reader) {\n return this.$type.decodeDelimited(reader);\n};\n\n/**\n * Verifies a message of this type.\n * @name Message.verify\n * @function\n * @param {Object.} message Plain object to verify\n * @returns {string|null} `null` if valid, otherwise the reason why it is not\n */\nMessage.verify = function verify(message) {\n return this.$type.verify(message);\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object\n * @returns {T} Message instance\n * @template T extends Message\n * @this Constructor\n */\nMessage.fromObject = function fromObject(object) {\n return this.$type.fromObject(object);\n};\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {T} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n * @template T extends Message\n * @this Constructor\n */\nMessage.toObject = function toObject(message, options) {\n return this.$type.toObject(message, options);\n};\n\n/**\n * Converts this message to JSON.\n * @returns {Object.} JSON object\n */\nMessage.prototype.toJSON = function toJSON() {\n return this.$type.toObject(this, util.toJSONOptions);\n};\n\n/*eslint-enable valid-jsdoc*/","\"use strict\";\nmodule.exports = Method;\n\n// extends ReflectionObject\nvar ReflectionObject = require(22);\n((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = \"Method\";\n\nvar util = require(33);\n\n/**\n * Constructs a new service method instance.\n * @classdesc Reflected service method.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Method name\n * @param {string|undefined} type Method type, usually `\"rpc\"`\n * @param {string} requestType Request message type\n * @param {string} responseType Response message type\n * @param {boolean|Object.} [requestStream] Whether the request is streamed\n * @param {boolean|Object.} [responseStream] Whether the response is streamed\n * @param {Object.} [options] Declared options\n * @param {string} [comment] The comment for this method\n * @param {Object.} [parsedOptions] Declared options, properly parsed into an object\n */\nfunction Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) {\n\n /* istanbul ignore next */\n if (util.isObject(requestStream)) {\n options = requestStream;\n requestStream = responseStream = undefined;\n } else if (util.isObject(responseStream)) {\n options = responseStream;\n responseStream = undefined;\n }\n\n /* istanbul ignore if */\n if (!(type === undefined || util.isString(type)))\n throw TypeError(\"type must be a string\");\n\n /* istanbul ignore if */\n if (!util.isString(requestType))\n throw TypeError(\"requestType must be a string\");\n\n /* istanbul ignore if */\n if (!util.isString(responseType))\n throw TypeError(\"responseType must be a string\");\n\n ReflectionObject.call(this, name, options);\n\n /**\n * Method type.\n * @type {string}\n */\n this.type = type || \"rpc\"; // toJSON\n\n /**\n * Request type.\n * @type {string}\n */\n this.requestType = requestType; // toJSON, marker\n\n /**\n * Whether requests are streamed or not.\n * @type {boolean|undefined}\n */\n this.requestStream = requestStream ? true : undefined; // toJSON\n\n /**\n * Response type.\n * @type {string}\n */\n this.responseType = responseType; // toJSON\n\n /**\n * Whether responses are streamed or not.\n * @type {boolean|undefined}\n */\n this.responseStream = responseStream ? true : undefined; // toJSON\n\n /**\n * Resolved request type.\n * @type {Type|null}\n */\n this.resolvedRequestType = null;\n\n /**\n * Resolved response type.\n * @type {Type|null}\n */\n this.resolvedResponseType = null;\n\n /**\n * Comment for this method\n * @type {string|null}\n */\n this.comment = comment;\n\n /**\n * Options properly parsed into an object\n */\n this.parsedOptions = parsedOptions;\n}\n\n/**\n * Method descriptor.\n * @interface IMethod\n * @property {string} [type=\"rpc\"] Method type\n * @property {string} requestType Request type\n * @property {string} responseType Response type\n * @property {boolean} [requestStream=false] Whether requests are streamed\n * @property {boolean} [responseStream=false] Whether responses are streamed\n * @property {Object.} [options] Method options\n * @property {string} comment Method comments\n * @property {Object.} [parsedOptions] Method options properly parsed into an object\n */\n\n/**\n * Constructs a method from a method descriptor.\n * @param {string} name Method name\n * @param {IMethod} json Method descriptor\n * @returns {Method} Created method\n * @throws {TypeError} If arguments are invalid\n */\nMethod.fromJSON = function fromJSON(name, json) {\n return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions);\n};\n\n/**\n * Converts this method to a method descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IMethod} Method descriptor\n */\nMethod.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"type\" , this.type !== \"rpc\" && /* istanbul ignore next */ this.type || undefined,\n \"requestType\" , this.requestType,\n \"requestStream\" , this.requestStream,\n \"responseType\" , this.responseType,\n \"responseStream\" , this.responseStream,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined,\n \"parsedOptions\" , this.parsedOptions,\n ]);\n};\n\n/**\n * @override\n */\nMethod.prototype.resolve = function resolve() {\n\n /* istanbul ignore if */\n if (this.resolved)\n return this;\n\n this.resolvedRequestType = this.parent.lookupType(this.requestType);\n this.resolvedResponseType = this.parent.lookupType(this.responseType);\n\n return ReflectionObject.prototype.resolve.call(this);\n};\n","\"use strict\";\nmodule.exports = Namespace;\n\n// extends ReflectionObject\nvar ReflectionObject = require(22);\n((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = \"Namespace\";\n\nvar Field = require(15),\n util = require(33),\n OneOf = require(23);\n\nvar Type, // cyclic\n Service,\n Enum;\n\n/**\n * Constructs a new namespace instance.\n * @name Namespace\n * @classdesc Reflected namespace.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Namespace name\n * @param {Object.} [options] Declared options\n */\n\n/**\n * Constructs a namespace from JSON.\n * @memberof Namespace\n * @function\n * @param {string} name Namespace name\n * @param {Object.} json JSON object\n * @returns {Namespace} Created namespace\n * @throws {TypeError} If arguments are invalid\n */\nNamespace.fromJSON = function fromJSON(name, json) {\n return new Namespace(name, json.options).addJSON(json.nested);\n};\n\n/**\n * Converts an array of reflection objects to JSON.\n * @memberof Namespace\n * @param {ReflectionObject[]} array Object array\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {Object.|undefined} JSON object or `undefined` when array is empty\n */\nfunction arrayToJSON(array, toJSONOptions) {\n if (!(array && array.length))\n return undefined;\n var obj = {};\n for (var i = 0; i < array.length; ++i)\n obj[array[i].name] = array[i].toJSON(toJSONOptions);\n return obj;\n}\n\nNamespace.arrayToJSON = arrayToJSON;\n\n/**\n * Tests if the specified id is reserved.\n * @param {Array.|undefined} reserved Array of reserved ranges and names\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nNamespace.isReservedId = function isReservedId(reserved, id) {\n if (reserved)\n for (var i = 0; i < reserved.length; ++i)\n if (typeof reserved[i] !== \"string\" && reserved[i][0] <= id && reserved[i][1] > id)\n return true;\n return false;\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {Array.|undefined} reserved Array of reserved ranges and names\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nNamespace.isReservedName = function isReservedName(reserved, name) {\n if (reserved)\n for (var i = 0; i < reserved.length; ++i)\n if (reserved[i] === name)\n return true;\n return false;\n};\n\n/**\n * Not an actual constructor. Use {@link Namespace} instead.\n * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions.\n * @exports NamespaceBase\n * @extends ReflectionObject\n * @abstract\n * @constructor\n * @param {string} name Namespace name\n * @param {Object.} [options] Declared options\n * @see {@link Namespace}\n */\nfunction Namespace(name, options) {\n ReflectionObject.call(this, name, options);\n\n /**\n * Nested objects by name.\n * @type {Object.|undefined}\n */\n this.nested = undefined; // toJSON\n\n /**\n * Cached nested objects as an array.\n * @type {ReflectionObject[]|null}\n * @private\n */\n this._nestedArray = null;\n\n /**\n * Cache lookup calls for any objects contains anywhere under this namespace.\n * This drastically speeds up resolve for large cross-linked protos where the same\n * types are looked up repeatedly.\n * @type {Object.}\n * @private\n */\n this._lookupCache = {};\n\n /**\n * Whether or not objects contained in this namespace need feature resolution.\n * @type {boolean}\n * @protected\n */\n this._needsRecursiveFeatureResolution = true;\n\n /**\n * Whether or not objects contained in this namespace need a resolve.\n * @type {boolean}\n * @protected\n */\n this._needsRecursiveResolve = true;\n}\n\nfunction clearCache(namespace) {\n namespace._nestedArray = null;\n namespace._lookupCache = {};\n\n // Also clear parent caches, since they include nested lookups.\n var parent = namespace;\n while(parent = parent.parent) {\n parent._lookupCache = {};\n }\n return namespace;\n}\n\n/**\n * Nested objects of this namespace as an array for iteration.\n * @name NamespaceBase#nestedArray\n * @type {ReflectionObject[]}\n * @readonly\n */\nObject.defineProperty(Namespace.prototype, \"nestedArray\", {\n get: function() {\n return this._nestedArray || (this._nestedArray = util.toArray(this.nested));\n }\n});\n\n/**\n * Namespace descriptor.\n * @interface INamespace\n * @property {Object.} [options] Namespace options\n * @property {Object.} [nested] Nested object descriptors\n */\n\n/**\n * Any extension field descriptor.\n * @typedef AnyExtensionField\n * @type {IExtensionField|IExtensionMapField}\n */\n\n/**\n * Any nested object descriptor.\n * @typedef AnyNestedObject\n * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf}\n */\n\n/**\n * Converts this namespace to a namespace descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {INamespace} Namespace descriptor\n */\nNamespace.prototype.toJSON = function toJSON(toJSONOptions) {\n return util.toObject([\n \"options\" , this.options,\n \"nested\" , arrayToJSON(this.nestedArray, toJSONOptions)\n ]);\n};\n\n/**\n * Adds nested objects to this namespace from nested object descriptors.\n * @param {Object.} nestedJson Any nested object descriptors\n * @returns {Namespace} `this`\n */\nNamespace.prototype.addJSON = function addJSON(nestedJson) {\n var ns = this;\n /* istanbul ignore else */\n if (nestedJson) {\n for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) {\n nested = nestedJson[names[i]];\n ns.add( // most to least likely\n ( nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : nested.id !== undefined\n ? Field.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n }\n return this;\n};\n\n/**\n * Gets the nested object of the specified name.\n * @param {string} name Nested object name\n * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist\n */\nNamespace.prototype.get = function get(name) {\n return this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Gets the values of the nested {@link Enum|enum} of the specified name.\n * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`.\n * @param {string} name Nested enum name\n * @returns {Object.} Enum values\n * @throws {Error} If there is no such enum\n */\nNamespace.prototype.getEnum = function getEnum(name) {\n if (this.nested && this.nested[name] instanceof Enum)\n return this.nested[name].values;\n throw Error(\"no such enum: \" + name);\n};\n\n/**\n * Adds a nested object to this namespace.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Namespace} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name\n */\nNamespace.prototype.add = function add(object) {\n\n if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace))\n throw TypeError(\"object must be a valid nested object\");\n\n if (!this.nested)\n this.nested = {};\n else {\n var prev = this.get(object.name);\n if (prev) {\n if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) {\n // replace plain namespace but keep existing nested elements and options\n var nested = prev.nestedArray;\n for (var i = 0; i < nested.length; ++i)\n object.add(nested[i]);\n this.remove(prev);\n if (!this.nested)\n this.nested = {};\n object.setOptions(prev.options, true);\n\n } else\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n }\n }\n this.nested[object.name] = object;\n\n if (!(this instanceof Type || this instanceof Service || this instanceof Enum || this instanceof Field)) {\n // This is a package or a root namespace.\n if (!object._edition) {\n // Make sure that some edition is set if it hasn't already been specified.\n object._edition = object._defaultEdition;\n }\n }\n\n this._needsRecursiveFeatureResolution = true;\n this._needsRecursiveResolve = true;\n\n // Also clear parent caches, since they need to recurse down.\n var parent = this;\n while(parent = parent.parent) {\n parent._needsRecursiveFeatureResolution = true;\n parent._needsRecursiveResolve = true;\n }\n\n object.onAdd(this);\n return clearCache(this);\n};\n\n/**\n * Removes a nested object from this namespace.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Namespace} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this namespace\n */\nNamespace.prototype.remove = function remove(object) {\n\n if (!(object instanceof ReflectionObject))\n throw TypeError(\"object must be a ReflectionObject\");\n if (object.parent !== this)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.nested[object.name];\n if (!Object.keys(this.nested).length)\n this.nested = undefined;\n\n object.onRemove(this);\n return clearCache(this);\n};\n\n/**\n * Defines additial namespaces within this one if not yet existing.\n * @param {string|string[]} path Path to create\n * @param {*} [json] Nested types to create from JSON\n * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty\n */\nNamespace.prototype.define = function define(path, json) {\n\n if (util.isString(path))\n path = path.split(\".\");\n else if (!Array.isArray(path))\n throw TypeError(\"illegal path\");\n if (path && path.length && path[0] === \"\")\n throw Error(\"path must be relative\");\n\n var ptr = this;\n while (path.length > 0) {\n var part = path.shift();\n if (ptr.nested && ptr.nested[part]) {\n ptr = ptr.nested[part];\n if (!(ptr instanceof Namespace))\n throw Error(\"path conflicts with non-namespace objects\");\n } else\n ptr.add(ptr = new Namespace(part));\n }\n if (json)\n ptr.addJSON(json);\n return ptr;\n};\n\n/**\n * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost.\n * @returns {Namespace} `this`\n */\nNamespace.prototype.resolveAll = function resolveAll() {\n if (!this._needsRecursiveResolve) return this;\n\n this._resolveFeaturesRecursive(this._edition);\n\n var nested = this.nestedArray, i = 0;\n this.resolve();\n while (i < nested.length)\n if (nested[i] instanceof Namespace)\n nested[i++].resolveAll();\n else\n nested[i++].resolve();\n this._needsRecursiveResolve = false;\n return this;\n};\n\n/**\n * @override\n */\nNamespace.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) {\n if (!this._needsRecursiveFeatureResolution) return this;\n this._needsRecursiveFeatureResolution = false;\n\n edition = this._edition || edition;\n\n ReflectionObject.prototype._resolveFeaturesRecursive.call(this, edition);\n this.nestedArray.forEach(nested => {\n nested._resolveFeaturesRecursive(edition);\n });\n return this;\n};\n\n/**\n * Recursively looks up the reflection object matching the specified path in the scope of this namespace.\n * @param {string|string[]} path Path to look up\n * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc.\n * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n */\nNamespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) {\n /* istanbul ignore next */\n if (typeof filterTypes === \"boolean\") {\n parentAlreadyChecked = filterTypes;\n filterTypes = undefined;\n } else if (filterTypes && !Array.isArray(filterTypes))\n filterTypes = [ filterTypes ];\n\n if (util.isString(path) && path.length) {\n if (path === \".\")\n return this.root;\n path = path.split(\".\");\n } else if (!path.length)\n return this;\n\n var flatPath = path.join(\".\");\n\n // Start at root if path is absolute\n if (path[0] === \"\")\n return this.root.lookup(path.slice(1), filterTypes);\n\n // Early bailout for objects with matching absolute paths\n var found = this.root._fullyQualifiedObjects && this.root._fullyQualifiedObjects[\".\" + flatPath];\n if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {\n return found;\n }\n\n // Do a regular lookup at this namespace and below\n found = this._lookupImpl(path, flatPath);\n if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {\n return found;\n }\n\n if (parentAlreadyChecked)\n return null;\n\n // If there hasn't been a match, walk up the tree and look more broadly\n var current = this;\n while (current.parent) {\n found = current.parent._lookupImpl(path, flatPath);\n if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {\n return found;\n }\n current = current.parent;\n }\n return null;\n};\n\n/**\n * Internal helper for lookup that handles searching just at this namespace and below along with caching.\n * @param {string[]} path Path to look up\n * @param {string} flatPath Flattened version of the path to use as a cache key\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n * @private\n */\nNamespace.prototype._lookupImpl = function lookup(path, flatPath) {\n if(Object.prototype.hasOwnProperty.call(this._lookupCache, flatPath)) {\n return this._lookupCache[flatPath];\n }\n\n // Test if the first part matches any nested object, and if so, traverse if path contains more\n var found = this.get(path[0]);\n var exact = null;\n if (found) {\n if (path.length === 1) {\n exact = found;\n } else if (found instanceof Namespace) {\n path = path.slice(1);\n exact = found._lookupImpl(path, path.join(\".\"));\n }\n\n // Otherwise try each nested namespace\n } else {\n for (var i = 0; i < this.nestedArray.length; ++i)\n if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i]._lookupImpl(path, flatPath)))\n exact = found;\n }\n\n // Set this even when null, so that when we walk up the tree we can quickly bail on repeated checks back down.\n this._lookupCache[flatPath] = exact;\n return exact;\n};\n\n/**\n * Looks up the reflection object at the specified path, relative to this namespace.\n * @name NamespaceBase#lookup\n * @function\n * @param {string|string[]} path Path to look up\n * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n * @variation 2\n */\n// lookup(path: string, [parentAlreadyChecked: boolean])\n\n/**\n * Looks up the {@link Type|type} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Type} Looked up type\n * @throws {Error} If `path` does not point to a type\n */\nNamespace.prototype.lookupType = function lookupType(path) {\n var found = this.lookup(path, [ Type ]);\n if (!found)\n throw Error(\"no such type: \" + path);\n return found;\n};\n\n/**\n * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Enum} Looked up enum\n * @throws {Error} If `path` does not point to an enum\n */\nNamespace.prototype.lookupEnum = function lookupEnum(path) {\n var found = this.lookup(path, [ Enum ]);\n if (!found)\n throw Error(\"no such Enum '\" + path + \"' in \" + this);\n return found;\n};\n\n/**\n * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Type} Looked up type or enum\n * @throws {Error} If `path` does not point to a type or enum\n */\nNamespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) {\n var found = this.lookup(path, [ Type, Enum ]);\n if (!found)\n throw Error(\"no such Type or Enum '\" + path + \"' in \" + this);\n return found;\n};\n\n/**\n * Looks up the {@link Service|service} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Service} Looked up service\n * @throws {Error} If `path` does not point to a service\n */\nNamespace.prototype.lookupService = function lookupService(path) {\n var found = this.lookup(path, [ Service ]);\n if (!found)\n throw Error(\"no such Service '\" + path + \"' in \" + this);\n return found;\n};\n\n// Sets up cyclic dependencies (called in index-light)\nNamespace._configure = function(Type_, Service_, Enum_) {\n Type = Type_;\n Service = Service_;\n Enum = Enum_;\n};\n","\"use strict\";\nmodule.exports = ReflectionObject;\n\nReflectionObject.className = \"ReflectionObject\";\n\nconst OneOf = require(23);\nvar util = require(33);\n\nvar Root; // cyclic\n\n/* eslint-disable no-warning-comments */\n// TODO: Replace with embedded proto.\nvar editions2023Defaults = {enum_type: \"OPEN\", field_presence: \"EXPLICIT\", json_format: \"ALLOW\", message_encoding: \"LENGTH_PREFIXED\", repeated_field_encoding: \"PACKED\", utf8_validation: \"VERIFY\"};\nvar proto2Defaults = {enum_type: \"CLOSED\", field_presence: \"EXPLICIT\", json_format: \"LEGACY_BEST_EFFORT\", message_encoding: \"LENGTH_PREFIXED\", repeated_field_encoding: \"EXPANDED\", utf8_validation: \"NONE\"};\nvar proto3Defaults = {enum_type: \"OPEN\", field_presence: \"IMPLICIT\", json_format: \"ALLOW\", message_encoding: \"LENGTH_PREFIXED\", repeated_field_encoding: \"PACKED\", utf8_validation: \"VERIFY\"};\n\n/**\n * Constructs a new reflection object instance.\n * @classdesc Base class of all reflection objects.\n * @constructor\n * @param {string} name Object name\n * @param {Object.} [options] Declared options\n * @abstract\n */\nfunction ReflectionObject(name, options) {\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n if (options && !util.isObject(options))\n throw TypeError(\"options must be an object\");\n\n /**\n * Options.\n * @type {Object.|undefined}\n */\n this.options = options; // toJSON\n\n /**\n * Parsed Options.\n * @type {Array.>|undefined}\n */\n this.parsedOptions = null;\n\n /**\n * Unique name within its namespace.\n * @type {string}\n */\n this.name = name;\n\n /**\n * The edition specified for this object. Only relevant for top-level objects.\n * @type {string}\n * @private\n */\n this._edition = null;\n\n /**\n * The default edition to use for this object if none is specified. For legacy reasons,\n * this is proto2 except in the JSON parsing case where it was proto3.\n * @type {string}\n * @private\n */\n this._defaultEdition = \"proto2\";\n\n /**\n * Resolved Features.\n * @type {object}\n * @private\n */\n this._features = {};\n\n /**\n * Whether or not features have been resolved.\n * @type {boolean}\n * @private\n */\n this._featuresResolved = false;\n\n /**\n * Parent namespace.\n * @type {Namespace|null}\n */\n this.parent = null;\n\n /**\n * Whether already resolved or not.\n * @type {boolean}\n */\n this.resolved = false;\n\n /**\n * Comment text, if any.\n * @type {string|null}\n */\n this.comment = null;\n\n /**\n * Defining file name.\n * @type {string|null}\n */\n this.filename = null;\n}\n\nObject.defineProperties(ReflectionObject.prototype, {\n\n /**\n * Reference to the root namespace.\n * @name ReflectionObject#root\n * @type {Root}\n * @readonly\n */\n root: {\n get: function() {\n var ptr = this;\n while (ptr.parent !== null)\n ptr = ptr.parent;\n return ptr;\n }\n },\n\n /**\n * Full name including leading dot.\n * @name ReflectionObject#fullName\n * @type {string}\n * @readonly\n */\n fullName: {\n get: function() {\n var path = [ this.name ],\n ptr = this.parent;\n while (ptr) {\n path.unshift(ptr.name);\n ptr = ptr.parent;\n }\n return path.join(\".\");\n }\n }\n});\n\n/**\n * Converts this reflection object to its descriptor representation.\n * @returns {Object.} Descriptor\n * @abstract\n */\nReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() {\n throw Error(); // not implemented, shouldn't happen\n};\n\n/**\n * Called when this object is added to a parent.\n * @param {ReflectionObject} parent Parent added to\n * @returns {undefined}\n */\nReflectionObject.prototype.onAdd = function onAdd(parent) {\n if (this.parent && this.parent !== parent)\n this.parent.remove(this);\n this.parent = parent;\n this.resolved = false;\n var root = parent.root;\n if (root instanceof Root)\n root._handleAdd(this);\n};\n\n/**\n * Called when this object is removed from a parent.\n * @param {ReflectionObject} parent Parent removed from\n * @returns {undefined}\n */\nReflectionObject.prototype.onRemove = function onRemove(parent) {\n var root = parent.root;\n if (root instanceof Root)\n root._handleRemove(this);\n this.parent = null;\n this.resolved = false;\n};\n\n/**\n * Resolves this objects type references.\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.resolve = function resolve() {\n if (this.resolved)\n return this;\n if (this.root instanceof Root)\n this.resolved = true; // only if part of a root\n return this;\n};\n\n/**\n * Resolves this objects editions features.\n * @param {string} edition The edition we're currently resolving for.\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) {\n return this._resolveFeatures(this._edition || edition);\n};\n\n/**\n * Resolves child features from parent features\n * @param {string} edition The edition we're currently resolving for.\n * @returns {undefined}\n */\nReflectionObject.prototype._resolveFeatures = function _resolveFeatures(edition) {\n if (this._featuresResolved) {\n return;\n }\n\n var defaults = {};\n\n /* istanbul ignore if */\n if (!edition) {\n throw new Error(\"Unknown edition for \" + this.fullName);\n }\n\n var protoFeatures = Object.assign(this.options ? Object.assign({}, this.options.features) : {},\n this._inferLegacyProtoFeatures(edition));\n\n if (this._edition) {\n // For a namespace marked with a specific edition, reset defaults.\n /* istanbul ignore else */\n if (edition === \"proto2\") {\n defaults = Object.assign({}, proto2Defaults);\n } else if (edition === \"proto3\") {\n defaults = Object.assign({}, proto3Defaults);\n } else if (edition === \"2023\") {\n defaults = Object.assign({}, editions2023Defaults);\n } else {\n throw new Error(\"Unknown edition: \" + edition);\n }\n this._features = Object.assign(defaults, protoFeatures || {});\n this._featuresResolved = true;\n return;\n }\n\n // fields in Oneofs aren't actually children of them, so we have to\n // special-case it\n /* istanbul ignore else */\n if (this.partOf instanceof OneOf) {\n var lexicalParentFeaturesCopy = Object.assign({}, this.partOf._features);\n this._features = Object.assign(lexicalParentFeaturesCopy, protoFeatures || {});\n } else if (this.declaringField) {\n // Skip feature resolution of sister fields.\n } else if (this.parent) {\n var parentFeaturesCopy = Object.assign({}, this.parent._features);\n this._features = Object.assign(parentFeaturesCopy, protoFeatures || {});\n } else {\n throw new Error(\"Unable to find a parent for \" + this.fullName);\n }\n if (this.extensionField) {\n // Sister fields should have the same features as their extensions.\n this.extensionField._features = this._features;\n }\n this._featuresResolved = true;\n};\n\n/**\n * Infers features from legacy syntax that may have been specified differently.\n * in older editions.\n * @param {string|undefined} edition The edition this proto is on, or undefined if pre-editions\n * @returns {object} The feature values to override\n */\nReflectionObject.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(/*edition*/) {\n return {};\n};\n\n/**\n * Gets an option value.\n * @param {string} name Option name\n * @returns {*} Option value or `undefined` if not set\n */\nReflectionObject.prototype.getOption = function getOption(name) {\n if (this.options)\n return this.options[name];\n return undefined;\n};\n\n/**\n * Sets an option.\n * @param {string} name Option name\n * @param {*} value Option value\n * @param {boolean|undefined} [ifNotSet] Sets the option only if it isn't currently set\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) {\n if (!this.options)\n this.options = {};\n if (/^features\\./.test(name)) {\n util.setProperty(this.options, name, value, ifNotSet);\n } else if (!ifNotSet || this.options[name] === undefined) {\n if (this.getOption(name) !== value) this.resolved = false;\n this.options[name] = value;\n }\n\n return this;\n};\n\n/**\n * Sets a parsed option.\n * @param {string} name parsed Option name\n * @param {*} value Option value\n * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\\empty, will add a new option with that value\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) {\n if (!this.parsedOptions) {\n this.parsedOptions = [];\n }\n var parsedOptions = this.parsedOptions;\n if (propName) {\n // If setting a sub property of an option then try to merge it\n // with an existing option\n var opt = parsedOptions.find(function (opt) {\n return Object.prototype.hasOwnProperty.call(opt, name);\n });\n if (opt) {\n // If we found an existing option - just merge the property value\n // (If it's a feature, will just write over)\n var newValue = opt[name];\n util.setProperty(newValue, propName, value);\n } else {\n // otherwise, create a new option, set its property and add it to the list\n opt = {};\n opt[name] = util.setProperty({}, propName, value);\n parsedOptions.push(opt);\n }\n } else {\n // Always create a new option when setting the value of the option itself\n var newOpt = {};\n newOpt[name] = value;\n parsedOptions.push(newOpt);\n }\n\n return this;\n};\n\n/**\n * Sets multiple options.\n * @param {Object.} options Options to set\n * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) {\n if (options)\n for (var keys = Object.keys(options), i = 0; i < keys.length; ++i)\n this.setOption(keys[i], options[keys[i]], ifNotSet);\n return this;\n};\n\n/**\n * Converts this instance to its string representation.\n * @returns {string} Class name[, space, full name]\n */\nReflectionObject.prototype.toString = function toString() {\n var className = this.constructor.className,\n fullName = this.fullName;\n if (fullName.length)\n return className + \" \" + fullName;\n return className;\n};\n\n/**\n * Converts the edition this object is pinned to for JSON format.\n * @returns {string|undefined} The edition string for JSON representation\n */\nReflectionObject.prototype._editionToJSON = function _editionToJSON() {\n if (!this._edition || this._edition === \"proto3\") {\n // Avoid emitting proto3 since we need to default to it for backwards\n // compatibility anyway.\n return undefined;\n }\n return this._edition;\n};\n\n// Sets up cyclic dependencies (called in index-light)\nReflectionObject._configure = function(Root_) {\n Root = Root_;\n};\n","\"use strict\";\nmodule.exports = OneOf;\n\n// extends ReflectionObject\nvar ReflectionObject = require(22);\n((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = \"OneOf\";\n\nvar Field = require(15),\n util = require(33);\n\n/**\n * Constructs a new oneof instance.\n * @classdesc Reflected oneof.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Oneof name\n * @param {string[]|Object.} [fieldNames] Field names\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction OneOf(name, fieldNames, options, comment) {\n if (!Array.isArray(fieldNames)) {\n options = fieldNames;\n fieldNames = undefined;\n }\n ReflectionObject.call(this, name, options);\n\n /* istanbul ignore if */\n if (!(fieldNames === undefined || Array.isArray(fieldNames)))\n throw TypeError(\"fieldNames must be an Array\");\n\n /**\n * Field names that belong to this oneof.\n * @type {string[]}\n */\n this.oneof = fieldNames || []; // toJSON, marker\n\n /**\n * Fields that belong to this oneof as an array for iteration.\n * @type {Field[]}\n * @readonly\n */\n this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent\n\n /**\n * Comment for this field.\n * @type {string|null}\n */\n this.comment = comment;\n}\n\n/**\n * Oneof descriptor.\n * @interface IOneOf\n * @property {Array.} oneof Oneof field names\n * @property {Object.} [options] Oneof options\n */\n\n/**\n * Constructs a oneof from a oneof descriptor.\n * @param {string} name Oneof name\n * @param {IOneOf} json Oneof descriptor\n * @returns {OneOf} Created oneof\n * @throws {TypeError} If arguments are invalid\n */\nOneOf.fromJSON = function fromJSON(name, json) {\n return new OneOf(name, json.oneof, json.options, json.comment);\n};\n\n/**\n * Converts this oneof to a oneof descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IOneOf} Oneof descriptor\n */\nOneOf.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , this.options,\n \"oneof\" , this.oneof,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Adds the fields of the specified oneof to the parent if not already done so.\n * @param {OneOf} oneof The oneof\n * @returns {undefined}\n * @inner\n * @ignore\n */\nfunction addFieldsToParent(oneof) {\n if (oneof.parent)\n for (var i = 0; i < oneof.fieldsArray.length; ++i)\n if (!oneof.fieldsArray[i].parent)\n oneof.parent.add(oneof.fieldsArray[i]);\n}\n\n/**\n * Adds a field to this oneof and removes it from its current parent, if any.\n * @param {Field} field Field to add\n * @returns {OneOf} `this`\n */\nOneOf.prototype.add = function add(field) {\n\n /* istanbul ignore if */\n if (!(field instanceof Field))\n throw TypeError(\"field must be a Field\");\n\n if (field.parent && field.parent !== this.parent)\n field.parent.remove(field);\n this.oneof.push(field.name);\n this.fieldsArray.push(field);\n field.partOf = this; // field.parent remains null\n addFieldsToParent(this);\n return this;\n};\n\n/**\n * Removes a field from this oneof and puts it back to the oneof's parent.\n * @param {Field} field Field to remove\n * @returns {OneOf} `this`\n */\nOneOf.prototype.remove = function remove(field) {\n\n /* istanbul ignore if */\n if (!(field instanceof Field))\n throw TypeError(\"field must be a Field\");\n\n var index = this.fieldsArray.indexOf(field);\n\n /* istanbul ignore if */\n if (index < 0)\n throw Error(field + \" is not a member of \" + this);\n\n this.fieldsArray.splice(index, 1);\n index = this.oneof.indexOf(field.name);\n\n /* istanbul ignore else */\n if (index > -1) // theoretical\n this.oneof.splice(index, 1);\n\n field.partOf = null;\n return this;\n};\n\n/**\n * @override\n */\nOneOf.prototype.onAdd = function onAdd(parent) {\n ReflectionObject.prototype.onAdd.call(this, parent);\n var self = this;\n // Collect present fields\n for (var i = 0; i < this.oneof.length; ++i) {\n var field = parent.get(this.oneof[i]);\n if (field && !field.partOf) {\n field.partOf = self;\n self.fieldsArray.push(field);\n }\n }\n // Add not yet present fields\n addFieldsToParent(this);\n};\n\n/**\n * @override\n */\nOneOf.prototype.onRemove = function onRemove(parent) {\n for (var i = 0, field; i < this.fieldsArray.length; ++i)\n if ((field = this.fieldsArray[i]).parent)\n field.parent.remove(field);\n ReflectionObject.prototype.onRemove.call(this, parent);\n};\n\n/**\n * Determines whether this field corresponds to a synthetic oneof created for\n * a proto3 optional field. No behavioral logic should depend on this, but it\n * can be relevant for reflection.\n * @name OneOf#isProto3Optional\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(OneOf.prototype, \"isProto3Optional\", {\n get: function() {\n if (this.fieldsArray == null || this.fieldsArray.length !== 1) {\n return false;\n }\n\n var field = this.fieldsArray[0];\n return field.options != null && field.options[\"proto3_optional\"] === true;\n }\n});\n\n/**\n * Decorator function as returned by {@link OneOf.d} (TypeScript).\n * @typedef OneOfDecorator\n * @type {function}\n * @param {Object} prototype Target prototype\n * @param {string} oneofName OneOf name\n * @returns {undefined}\n */\n\n/**\n * OneOf decorator (TypeScript).\n * @function\n * @param {...string} fieldNames Field names\n * @returns {OneOfDecorator} Decorator function\n * @template T extends string\n */\nOneOf.d = function decorateOneOf() {\n var fieldNames = new Array(arguments.length),\n index = 0;\n while (index < arguments.length)\n fieldNames[index] = arguments[index++];\n return function oneOfDecorator(prototype, oneofName) {\n util.decorateType(prototype.constructor)\n .add(new OneOf(oneofName, fieldNames));\n Object.defineProperty(prototype, oneofName, {\n get: util.oneOfGetter(fieldNames),\n set: util.oneOfSetter(fieldNames)\n });\n };\n};\n","\"use strict\";\nmodule.exports = Reader;\n\nvar util = require(35);\n\nvar BufferReader; // cyclic\n\nvar LongBits = util.LongBits,\n utf8 = util.utf8;\n\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(\"index out of range: \" + reader.pos + \" + \" + (writeLength || 1) + \" > \" + reader.len);\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n * @param {Uint8Array} buffer Buffer to read from\n */\nfunction Reader(buffer) {\n\n /**\n * Read buffer.\n * @type {Uint8Array}\n */\n this.buf = buffer;\n\n /**\n * Read buffer position.\n * @type {number}\n */\n this.pos = 0;\n\n /**\n * Read buffer length.\n * @type {number}\n */\n this.len = buffer.length;\n}\n\nvar create_array = typeof Uint8Array !== \"undefined\"\n ? function create_typed_array(buffer) {\n if (buffer instanceof Uint8Array || Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n }\n /* istanbul ignore next */\n : function create_array(buffer) {\n if (Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n };\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup(buffer) {\n return (Reader.create = function create_buffer(buffer) {\n return util.Buffer.isBuffer(buffer)\n ? new BufferReader(buffer)\n /* istanbul ignore next */\n : create_array(buffer);\n })(buffer);\n }\n /* istanbul ignore next */\n : create_array;\n};\n\n/**\n * Creates a new reader using the specified buffer.\n * @function\n * @param {Uint8Array|Buffer} buffer Buffer to read from\n * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}\n * @throws {Error} If `buffer` is not a valid buffer\n */\nReader.create = create();\n\nReader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;\n\n/**\n * Reads a varint as an unsigned 32 bit value.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.uint32 = (function read_uint32_setup() {\n var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)\n return function read_uint32() {\n value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;\n\n /* istanbul ignore if */\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n };\n})();\n\n/**\n * Reads a varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.int32 = function read_int32() {\n return this.uint32() | 0;\n};\n\n/**\n * Reads a zig-zag encoded varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.sint32 = function read_sint32() {\n var value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readLongVarint() {\n // tends to deopt with local vars for octet etc.\n var bits = new LongBits(0, 0);\n var i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n i = 0;\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n } else {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n }\n /* istanbul ignore next */\n throw Error(\"invalid varint encoding\");\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads a varint as a signed 64 bit value.\n * @name Reader#int64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as an unsigned 64 bit value.\n * @name Reader#uint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a zig-zag encoded varint as a signed 64 bit value.\n * @name Reader#sint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as a boolean.\n * @returns {boolean} Value read\n */\nReader.prototype.bool = function read_bool() {\n return this.uint32() !== 0;\n};\n\nfunction readFixed32_end(buf, end) { // note that this uses `end`, not `pos`\n return (buf[end - 4]\n | buf[end - 3] << 8\n | buf[end - 2] << 16\n | buf[end - 1] << 24) >>> 0;\n}\n\n/**\n * Reads fixed 32 bits as an unsigned 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.fixed32 = function read_fixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4);\n};\n\n/**\n * Reads fixed 32 bits as a signed 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.sfixed32 = function read_sfixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readFixed64(/* this: Reader */) {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 8);\n\n return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads fixed 64 bits.\n * @name Reader#fixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads zig-zag encoded fixed 64 bits.\n * @name Reader#sfixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a float (32 bit) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.float = function read_float() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readFloatLE(this.buf, this.pos);\n this.pos += 4;\n return value;\n};\n\n/**\n * Reads a double (64 bit float) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.double = function read_double() {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readDoubleLE(this.buf, this.pos);\n this.pos += 8;\n return value;\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @returns {Uint8Array} Value read\n */\nReader.prototype.bytes = function read_bytes() {\n var length = this.uint32(),\n start = this.pos,\n end = this.pos + length;\n\n /* istanbul ignore if */\n if (end > this.len)\n throw indexOutOfRange(this, length);\n\n this.pos += length;\n if (Array.isArray(this.buf)) // plain array\n return this.buf.slice(start, end);\n\n if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1\n var nativeBuffer = util.Buffer;\n return nativeBuffer\n ? nativeBuffer.alloc(0)\n : new this.buf.constructor(0);\n }\n return this._slice.call(this.buf, start, end);\n};\n\n/**\n * Reads a string preceeded by its byte length as a varint.\n * @returns {string} Value read\n */\nReader.prototype.string = function read_string() {\n var bytes = this.bytes();\n return utf8.read(bytes, 0, bytes.length);\n};\n\n/**\n * Skips the specified number of bytes if specified, otherwise skips a varint.\n * @param {number} [length] Length if known, otherwise a varint is assumed\n * @returns {Reader} `this`\n */\nReader.prototype.skip = function skip(length) {\n if (typeof length === \"number\") {\n /* istanbul ignore if */\n if (this.pos + length > this.len)\n throw indexOutOfRange(this, length);\n this.pos += length;\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n } while (this.buf[this.pos++] & 128);\n }\n return this;\n};\n\n/**\n * Skips the next element of the specified wire type.\n * @param {number} wireType Wire type received\n * @returns {Reader} `this`\n */\nReader.prototype.skipType = function(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n\n /* istanbul ignore next */\n default:\n throw Error(\"invalid wire type \" + wireType + \" at offset \" + this.pos);\n }\n return this;\n};\n\nReader._configure = function(BufferReader_) {\n BufferReader = BufferReader_;\n Reader.create = create();\n BufferReader._configure();\n\n var fn = util.Long ? \"toLong\" : /* istanbul ignore next */ \"toNumber\";\n util.merge(Reader.prototype, {\n\n int64: function read_int64() {\n return readLongVarint.call(this)[fn](false);\n },\n\n uint64: function read_uint64() {\n return readLongVarint.call(this)[fn](true);\n },\n\n sint64: function read_sint64() {\n return readLongVarint.call(this).zzDecode()[fn](false);\n },\n\n fixed64: function read_fixed64() {\n return readFixed64.call(this)[fn](true);\n },\n\n sfixed64: function read_sfixed64() {\n return readFixed64.call(this)[fn](false);\n }\n\n });\n};\n","\"use strict\";\nmodule.exports = BufferReader;\n\n// extends Reader\nvar Reader = require(24);\n(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;\n\nvar util = require(35);\n\n/**\n * Constructs a new buffer reader instance.\n * @classdesc Wire format reader using node buffers.\n * @extends Reader\n * @constructor\n * @param {Buffer} buffer Buffer to read from\n */\nfunction BufferReader(buffer) {\n Reader.call(this, buffer);\n\n /**\n * Read buffer.\n * @name BufferReader#buf\n * @type {Buffer}\n */\n}\n\nBufferReader._configure = function () {\n /* istanbul ignore else */\n if (util.Buffer)\n BufferReader.prototype._slice = util.Buffer.prototype.slice;\n};\n\n\n/**\n * @override\n */\nBufferReader.prototype.string = function read_string_buffer() {\n var len = this.uint32(); // modifies pos\n return this.buf.utf8Slice\n ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))\n : this.buf.toString(\"utf-8\", this.pos, this.pos = Math.min(this.pos + len, this.len));\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @name BufferReader#bytes\n * @function\n * @returns {Buffer} Value read\n */\n\nBufferReader._configure();\n","\"use strict\";\nmodule.exports = Root;\n\n// extends Namespace\nvar Namespace = require(21);\n((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = \"Root\";\n\nvar Field = require(15),\n Enum = require(14),\n OneOf = require(23),\n util = require(33);\n\nvar Type, // cyclic\n parse, // might be excluded\n common; // \"\n\n/**\n * Constructs a new root namespace instance.\n * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together.\n * @extends NamespaceBase\n * @constructor\n * @param {Object.} [options] Top level options\n */\nfunction Root(options) {\n Namespace.call(this, \"\", options);\n\n /**\n * Deferred extension fields.\n * @type {Field[]}\n */\n this.deferred = [];\n\n /**\n * Resolved file names of loaded files.\n * @type {string[]}\n */\n this.files = [];\n\n /**\n * Edition, defaults to proto2 if unspecified.\n * @type {string}\n * @private\n */\n this._edition = \"proto2\";\n\n /**\n * Global lookup cache of fully qualified names.\n * @type {Object.}\n * @private\n */\n this._fullyQualifiedObjects = {};\n}\n\n/**\n * Loads a namespace descriptor into a root namespace.\n * @param {INamespace} json Namespace descriptor\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted\n * @returns {Root} Root namespace\n */\nRoot.fromJSON = function fromJSON(json, root) {\n if (!root)\n root = new Root();\n if (json.options)\n root.setOptions(json.options);\n return root.addJSON(json.nested).resolveAll();\n};\n\n/**\n * Resolves the path of an imported file, relative to the importing origin.\n * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories.\n * @function\n * @param {string} origin The file name of the importing file\n * @param {string} target The file name being imported\n * @returns {string|null} Resolved path to `target` or `null` to skip the file\n */\nRoot.prototype.resolvePath = util.path.resolve;\n\n/**\n * Fetch content from file path or url\n * This method exists so you can override it with your own logic.\n * @function\n * @param {string} path File path or url\n * @param {FetchCallback} callback Callback function\n * @returns {undefined}\n */\nRoot.prototype.fetch = util.fetch;\n\n// A symbol-like function to safely signal synchronous loading\n/* istanbul ignore next */\nfunction SYNC() {} // eslint-disable-line no-empty-function\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} options Parse options\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n */\nRoot.prototype.load = function load(filename, options, callback) {\n if (typeof options === \"function\") {\n callback = options;\n options = undefined;\n }\n var self = this;\n if (!callback) {\n return util.asPromise(load, self, filename, options);\n }\n\n var sync = callback === SYNC; // undocumented\n\n // Finishes loading by calling the callback (exactly once)\n function finish(err, root) {\n /* istanbul ignore if */\n if (!callback) {\n return;\n }\n if (sync) {\n throw err;\n }\n if (root) {\n root.resolveAll();\n }\n var cb = callback;\n callback = null;\n cb(err, root);\n }\n\n // Bundled definition existence checking\n function getBundledFileName(filename) {\n var idx = filename.lastIndexOf(\"google/protobuf/\");\n if (idx > -1) {\n var altname = filename.substring(idx);\n if (altname in common) return altname;\n }\n return null;\n }\n\n // Processes a single file\n function process(filename, source) {\n try {\n if (util.isString(source) && source.charAt(0) === \"{\")\n source = JSON.parse(source);\n if (!util.isString(source))\n self.setOptions(source.options).addJSON(source.nested);\n else {\n parse.filename = filename;\n var parsed = parse(source, self, options),\n resolved,\n i = 0;\n if (parsed.imports)\n for (; i < parsed.imports.length; ++i)\n if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i]))\n fetch(resolved);\n if (parsed.weakImports)\n for (i = 0; i < parsed.weakImports.length; ++i)\n if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i]))\n fetch(resolved, true);\n }\n } catch (err) {\n finish(err);\n }\n if (!sync && !queued) {\n finish(null, self); // only once anyway\n }\n }\n\n // Fetches a single file\n function fetch(filename, weak) {\n filename = getBundledFileName(filename) || filename;\n\n // Skip if already loaded / attempted\n if (self.files.indexOf(filename) > -1) {\n return;\n }\n self.files.push(filename);\n\n // Shortcut bundled definitions\n if (filename in common) {\n if (sync) {\n process(filename, common[filename]);\n } else {\n ++queued;\n setTimeout(function() {\n --queued;\n process(filename, common[filename]);\n });\n }\n return;\n }\n\n // Otherwise fetch from disk or network\n if (sync) {\n var source;\n try {\n source = util.fs.readFileSync(filename).toString(\"utf8\");\n } catch (err) {\n if (!weak)\n finish(err);\n return;\n }\n process(filename, source);\n } else {\n ++queued;\n self.fetch(filename, function(err, source) {\n --queued;\n /* istanbul ignore if */\n if (!callback) {\n return; // terminated meanwhile\n }\n if (err) {\n /* istanbul ignore else */\n if (!weak)\n finish(err);\n else if (!queued) // can't be covered reliably\n finish(null, self);\n return;\n }\n process(filename, source);\n });\n }\n }\n var queued = 0;\n\n // Assembling the root namespace doesn't require working type\n // references anymore, so we can load everything in parallel\n if (util.isString(filename)) {\n filename = [ filename ];\n }\n for (var i = 0, resolved; i < filename.length; ++i)\n if (resolved = self.resolvePath(\"\", filename[i]))\n fetch(resolved);\n if (sync) {\n self.resolveAll();\n return self;\n }\n if (!queued) {\n finish(null, self);\n }\n\n return self;\n};\n// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\n * @function Root#load\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @variation 2\n */\n// function load(filename:string, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise.\n * @function Root#load\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {Promise} Promise\n * @variation 3\n */\n// function load(filename:string, [options:IParseOptions]):Promise\n\n/**\n * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only).\n * @function Root#loadSync\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {Root} Root namespace\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\n */\nRoot.prototype.loadSync = function loadSync(filename, options) {\n if (!util.isNode)\n throw Error(\"not supported\");\n return this.load(filename, options, SYNC);\n};\n\n/**\n * @override\n */\nRoot.prototype.resolveAll = function resolveAll() {\n if (!this._needsRecursiveResolve) return this;\n\n if (this.deferred.length)\n throw Error(\"unresolvable extensions: \" + this.deferred.map(function(field) {\n return \"'extend \" + field.extend + \"' in \" + field.parent.fullName;\n }).join(\", \"));\n return Namespace.prototype.resolveAll.call(this);\n};\n\n// only uppercased (and thus conflict-free) children are exposed, see below\nvar exposeRe = /^[A-Z]/;\n\n/**\n * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type.\n * @param {Root} root Root instance\n * @param {Field} field Declaring extension field witin the declaring type\n * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise\n * @inner\n * @ignore\n */\nfunction tryHandleExtension(root, field) {\n var extendedType = field.parent.lookup(field.extend);\n if (extendedType) {\n var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options);\n //do not allow to extend same field twice to prevent the error\n if (extendedType.get(sisterField.name)) {\n return true;\n }\n sisterField.declaringField = field;\n field.extensionField = sisterField;\n extendedType.add(sisterField);\n return true;\n }\n return false;\n}\n\n/**\n * Called when any object is added to this root or its sub-namespaces.\n * @param {ReflectionObject} object Object added\n * @returns {undefined}\n * @private\n */\nRoot.prototype._handleAdd = function _handleAdd(object) {\n if (object instanceof Field) {\n\n if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField)\n if (!tryHandleExtension(this, object))\n this.deferred.push(object);\n\n } else if (object instanceof Enum) {\n\n if (exposeRe.test(object.name))\n object.parent[object.name] = object.values; // expose enum values as property of its parent\n\n } else if (!(object instanceof OneOf)) /* everything else is a namespace */ {\n\n if (object instanceof Type) // Try to handle any deferred extensions\n for (var i = 0; i < this.deferred.length;)\n if (tryHandleExtension(this, this.deferred[i]))\n this.deferred.splice(i, 1);\n else\n ++i;\n for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace\n this._handleAdd(object._nestedArray[j]);\n if (exposeRe.test(object.name))\n object.parent[object.name] = object; // expose namespace as property of its parent\n }\n\n if (object instanceof Type || object instanceof Enum || object instanceof Field) {\n // Only store types and enums for quick lookup during resolve.\n this._fullyQualifiedObjects[object.fullName] = object;\n }\n\n // The above also adds uppercased (and thus conflict-free) nested types, services and enums as\n // properties of namespaces just like static code does. This allows using a .d.ts generated for\n // a static module with reflection-based solutions where the condition is met.\n};\n\n/**\n * Called when any object is removed from this root or its sub-namespaces.\n * @param {ReflectionObject} object Object removed\n * @returns {undefined}\n * @private\n */\nRoot.prototype._handleRemove = function _handleRemove(object) {\n if (object instanceof Field) {\n\n if (/* an extension field */ object.extend !== undefined) {\n if (/* already handled */ object.extensionField) { // remove its sister field\n object.extensionField.parent.remove(object.extensionField);\n object.extensionField = null;\n } else { // cancel the extension\n var index = this.deferred.indexOf(object);\n /* istanbul ignore else */\n if (index > -1)\n this.deferred.splice(index, 1);\n }\n }\n\n } else if (object instanceof Enum) {\n\n if (exposeRe.test(object.name))\n delete object.parent[object.name]; // unexpose enum values\n\n } else if (object instanceof Namespace) {\n\n for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace\n this._handleRemove(object._nestedArray[i]);\n\n if (exposeRe.test(object.name))\n delete object.parent[object.name]; // unexpose namespaces\n\n }\n\n delete this._fullyQualifiedObjects[object.fullName];\n};\n\n// Sets up cyclic dependencies (called in index-light)\nRoot._configure = function(Type_, parse_, common_) {\n Type = Type_;\n parse = parse_;\n common = common_;\n};\n","\"use strict\";\nmodule.exports = {};\n\n/**\n * Named roots.\n * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).\n * Can also be used manually to make roots available across modules.\n * @name roots\n * @type {Object.}\n * @example\n * // pbjs -r myroot -o compiled.js ...\n *\n * // in another module:\n * require(\"./compiled.js\");\n *\n * // in any subsequent module:\n * var root = protobuf.roots[\"myroot\"];\n */\n","\"use strict\";\n\n/**\n * Streaming RPC helpers.\n * @namespace\n */\nvar rpc = exports;\n\n/**\n * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.\n * @typedef RPCImpl\n * @type {function}\n * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called\n * @param {Uint8Array} requestData Request data\n * @param {RPCImplCallback} callback Callback function\n * @returns {undefined}\n * @example\n * function rpcImpl(method, requestData, callback) {\n * if (protobuf.util.lcFirst(method.name) !== \"myMethod\") // compatible with static code\n * throw Error(\"no such method\");\n * asynchronouslyObtainAResponse(requestData, function(err, responseData) {\n * callback(err, responseData);\n * });\n * }\n */\n\n/**\n * Node-style callback as used by {@link RPCImpl}.\n * @typedef RPCImplCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error\n * @returns {undefined}\n */\n\nrpc.Service = require(29);\n","\"use strict\";\nmodule.exports = Service;\n\nvar util = require(35);\n\n// Extends EventEmitter\n(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;\n\n/**\n * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.\n *\n * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.\n * @typedef rpc.ServiceMethodCallback\n * @template TRes extends Message\n * @type {function}\n * @param {Error|null} error Error, if any\n * @param {TRes} [response] Response message\n * @returns {undefined}\n */\n\n/**\n * A service method part of a {@link rpc.Service} as created by {@link Service.create}.\n * @typedef rpc.ServiceMethod\n * @template TReq extends Message\n * @template TRes extends Message\n * @type {function}\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message\n * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined`\n */\n\n/**\n * Constructs a new RPC service instance.\n * @classdesc An RPC service as returned by {@link Service#create}.\n * @exports rpc.Service\n * @extends util.EventEmitter\n * @constructor\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n */\nfunction Service(rpcImpl, requestDelimited, responseDelimited) {\n\n if (typeof rpcImpl !== \"function\")\n throw TypeError(\"rpcImpl must be a function\");\n\n util.EventEmitter.call(this);\n\n /**\n * RPC implementation. Becomes `null` once the service is ended.\n * @type {RPCImpl|null}\n */\n this.rpcImpl = rpcImpl;\n\n /**\n * Whether requests are length-delimited.\n * @type {boolean}\n */\n this.requestDelimited = Boolean(requestDelimited);\n\n /**\n * Whether responses are length-delimited.\n * @type {boolean}\n */\n this.responseDelimited = Boolean(responseDelimited);\n}\n\n/**\n * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.\n * @param {Method|rpc.ServiceMethod} method Reflected or static method\n * @param {Constructor} requestCtor Request constructor\n * @param {Constructor} responseCtor Response constructor\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} callback Service callback\n * @returns {undefined}\n * @template TReq extends Message\n * @template TRes extends Message\n */\nService.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {\n\n if (!request)\n throw TypeError(\"request must be specified\");\n\n var self = this;\n if (!callback)\n return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);\n\n if (!self.rpcImpl) {\n setTimeout(function() { callback(Error(\"already ended\")); }, 0);\n return undefined;\n }\n\n try {\n return self.rpcImpl(\n method,\n requestCtor[self.requestDelimited ? \"encodeDelimited\" : \"encode\"](request).finish(),\n function rpcCallback(err, response) {\n\n if (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n\n if (response === null) {\n self.end(/* endedByRPC */ true);\n return undefined;\n }\n\n if (!(response instanceof responseCtor)) {\n try {\n response = responseCtor[self.responseDelimited ? \"decodeDelimited\" : \"decode\"](response);\n } catch (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n }\n\n self.emit(\"data\", response, method);\n return callback(null, response);\n }\n );\n } catch (err) {\n self.emit(\"error\", err, method);\n setTimeout(function() { callback(err); }, 0);\n return undefined;\n }\n};\n\n/**\n * Ends this service and emits the `end` event.\n * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.\n * @returns {rpc.Service} `this`\n */\nService.prototype.end = function end(endedByRPC) {\n if (this.rpcImpl) {\n if (!endedByRPC) // signal end to rpcImpl\n this.rpcImpl(null, null, null);\n this.rpcImpl = null;\n this.emit(\"end\").off();\n }\n return this;\n};\n","\"use strict\";\nmodule.exports = Service;\n\n// extends Namespace\nvar Namespace = require(21);\n((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = \"Service\";\n\nvar Method = require(20),\n util = require(33),\n rpc = require(28);\n\n/**\n * Constructs a new service instance.\n * @classdesc Reflected service.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Service name\n * @param {Object.} [options] Service options\n * @throws {TypeError} If arguments are invalid\n */\nfunction Service(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Service methods.\n * @type {Object.}\n */\n this.methods = {}; // toJSON, marker\n\n /**\n * Cached methods as an array.\n * @type {Method[]|null}\n * @private\n */\n this._methodsArray = null;\n}\n\n/**\n * Service descriptor.\n * @interface IService\n * @extends INamespace\n * @property {Object.} methods Method descriptors\n */\n\n/**\n * Constructs a service from a service descriptor.\n * @param {string} name Service name\n * @param {IService} json Service descriptor\n * @returns {Service} Created service\n * @throws {TypeError} If arguments are invalid\n */\nService.fromJSON = function fromJSON(name, json) {\n var service = new Service(name, json.options);\n /* istanbul ignore else */\n if (json.methods)\n for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i)\n service.add(Method.fromJSON(names[i], json.methods[names[i]]));\n if (json.nested)\n service.addJSON(json.nested);\n if (json.edition)\n service._edition = json.edition;\n service.comment = json.comment;\n service._defaultEdition = \"proto3\"; // For backwards-compatibility.\n return service;\n};\n\n/**\n * Converts this service to a service descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IService} Service descriptor\n */\nService.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"edition\" , this._editionToJSON(),\n \"options\" , inherited && inherited.options || undefined,\n \"methods\" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {},\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Methods of this service as an array for iteration.\n * @name Service#methodsArray\n * @type {Method[]}\n * @readonly\n */\nObject.defineProperty(Service.prototype, \"methodsArray\", {\n get: function() {\n return this._methodsArray || (this._methodsArray = util.toArray(this.methods));\n }\n});\n\nfunction clearCache(service) {\n service._methodsArray = null;\n return service;\n}\n\n/**\n * @override\n */\nService.prototype.get = function get(name) {\n return this.methods[name]\n || Namespace.prototype.get.call(this, name);\n};\n\n/**\n * @override\n */\nService.prototype.resolveAll = function resolveAll() {\n if (!this._needsRecursiveResolve) return this;\n\n Namespace.prototype.resolve.call(this);\n var methods = this.methodsArray;\n for (var i = 0; i < methods.length; ++i)\n methods[i].resolve();\n return this;\n};\n\n/**\n * @override\n */\nService.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) {\n if (!this._needsRecursiveFeatureResolution) return this;\n\n edition = this._edition || edition;\n\n Namespace.prototype._resolveFeaturesRecursive.call(this, edition);\n this.methodsArray.forEach(method => {\n method._resolveFeaturesRecursive(edition);\n });\n return this;\n};\n\n/**\n * @override\n */\nService.prototype.add = function add(object) {\n\n /* istanbul ignore if */\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Method) {\n this.methods[object.name] = object;\n object.parent = this;\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * @override\n */\nService.prototype.remove = function remove(object) {\n if (object instanceof Method) {\n\n /* istanbul ignore if */\n if (this.methods[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.methods[object.name];\n object.parent = null;\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Creates a runtime service using the specified rpc implementation.\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed.\n */\nService.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) {\n var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);\n for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) {\n var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\\w_]/g, \"\");\n rpcService[methodName] = util.codegen([\"r\",\"c\"], util.isReserved(methodName) ? methodName + \"_\" : methodName)(\"return this.rpcCall(m,q,s,r,c)\")({\n m: method,\n q: method.resolvedRequestType.ctor,\n s: method.resolvedResponseType.ctor\n });\n }\n return rpcService;\n};\n","\"use strict\";\nmodule.exports = Type;\n\n// extends Namespace\nvar Namespace = require(21);\n((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = \"Type\";\n\nvar Enum = require(14),\n OneOf = require(23),\n Field = require(15),\n MapField = require(18),\n Service = require(30),\n Message = require(19),\n Reader = require(24),\n Writer = require(38),\n util = require(33),\n encoder = require(13),\n decoder = require(12),\n verifier = require(36),\n converter = require(11),\n wrappers = require(37);\n\n/**\n * Constructs a new reflected message type instance.\n * @classdesc Reflected message type.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Message name\n * @param {Object.} [options] Declared options\n */\nfunction Type(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Message fields.\n * @type {Object.}\n */\n this.fields = {}; // toJSON, marker\n\n /**\n * Oneofs declared within this namespace, if any.\n * @type {Object.}\n */\n this.oneofs = undefined; // toJSON\n\n /**\n * Extension ranges, if any.\n * @type {number[][]}\n */\n this.extensions = undefined; // toJSON\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n /*?\n * Whether this type is a legacy group.\n * @type {boolean|undefined}\n */\n this.group = undefined; // toJSON\n\n /**\n * Cached fields by id.\n * @type {Object.|null}\n * @private\n */\n this._fieldsById = null;\n\n /**\n * Cached fields as an array.\n * @type {Field[]|null}\n * @private\n */\n this._fieldsArray = null;\n\n /**\n * Cached oneofs as an array.\n * @type {OneOf[]|null}\n * @private\n */\n this._oneofsArray = null;\n\n /**\n * Cached constructor.\n * @type {Constructor<{}>}\n * @private\n */\n this._ctor = null;\n}\n\nObject.defineProperties(Type.prototype, {\n\n /**\n * Message fields by id.\n * @name Type#fieldsById\n * @type {Object.}\n * @readonly\n */\n fieldsById: {\n get: function() {\n\n /* istanbul ignore if */\n if (this._fieldsById)\n return this._fieldsById;\n\n this._fieldsById = {};\n for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {\n var field = this.fields[names[i]],\n id = field.id;\n\n /* istanbul ignore if */\n if (this._fieldsById[id])\n throw Error(\"duplicate id \" + id + \" in \" + this);\n\n this._fieldsById[id] = field;\n }\n return this._fieldsById;\n }\n },\n\n /**\n * Fields of this message as an array for iteration.\n * @name Type#fieldsArray\n * @type {Field[]}\n * @readonly\n */\n fieldsArray: {\n get: function() {\n return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));\n }\n },\n\n /**\n * Oneofs of this message as an array for iteration.\n * @name Type#oneofsArray\n * @type {OneOf[]}\n * @readonly\n */\n oneofsArray: {\n get: function() {\n return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));\n }\n },\n\n /**\n * The registered constructor, if any registered, otherwise a generic constructor.\n * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.\n * @name Type#ctor\n * @type {Constructor<{}>}\n */\n ctor: {\n get: function() {\n return this._ctor || (this.ctor = Type.generateConstructor(this)());\n },\n set: function(ctor) {\n\n // Ensure proper prototype\n var prototype = ctor.prototype;\n if (!(prototype instanceof Message)) {\n (ctor.prototype = new Message()).constructor = ctor;\n util.merge(ctor.prototype, prototype);\n }\n\n // Classes and messages reference their reflected type\n ctor.$type = ctor.prototype.$type = this;\n\n // Mix in static methods\n util.merge(ctor, Message, true);\n\n this._ctor = ctor;\n\n // Messages have non-enumerable default values on their prototype\n var i = 0;\n for (; i < /* initializes */ this.fieldsArray.length; ++i)\n this._fieldsArray[i].resolve(); // ensures a proper value\n\n // Messages have non-enumerable getters and setters for each virtual oneof field\n var ctorProperties = {};\n for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i)\n ctorProperties[this._oneofsArray[i].resolve().name] = {\n get: util.oneOfGetter(this._oneofsArray[i].oneof),\n set: util.oneOfSetter(this._oneofsArray[i].oneof)\n };\n if (i)\n Object.defineProperties(ctor.prototype, ctorProperties);\n }\n }\n});\n\n/**\n * Generates a constructor function for the specified type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nType.generateConstructor = function generateConstructor(mtype) {\n /* eslint-disable no-unexpected-multiline */\n var gen = util.codegen([\"p\"], mtype.name);\n // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype\n for (var i = 0, field; i < mtype.fieldsArray.length; ++i)\n if ((field = mtype._fieldsArray[i]).map) gen\n (\"this%s={}\", util.safeProp(field.name));\n else if (field.repeated) gen\n (\"this%s=[]\", util.safeProp(field.name));\n return gen\n (\"if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors\n * @property {Object.} fields Field descriptors\n * @property {number[][]} [extensions] Extension ranges\n * @property {Array.} [reserved] Reserved ranges\n * @property {boolean} [group=false] Whether a legacy group or not\n */\n\n/**\n * Creates a message type from a message type descriptor.\n * @param {string} name Message name\n * @param {IType} json Message type descriptor\n * @returns {Type} Created message type\n */\nType.fromJSON = function fromJSON(name, json) {\n var type = new Type(name, json.options);\n type.extensions = json.extensions;\n type.reserved = json.reserved;\n var names = Object.keys(json.fields),\n i = 0;\n for (; i < names.length; ++i)\n type.add(\n ( typeof json.fields[names[i]].keyType !== \"undefined\"\n ? MapField.fromJSON\n : Field.fromJSON )(names[i], json.fields[names[i]])\n );\n if (json.oneofs)\n for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i)\n type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]]));\n if (json.nested)\n for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) {\n var nested = json.nested[names[i]];\n type.add( // most to least likely\n ( nested.id !== undefined\n ? Field.fromJSON\n : nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n if (json.extensions && json.extensions.length)\n type.extensions = json.extensions;\n if (json.reserved && json.reserved.length)\n type.reserved = json.reserved;\n if (json.group)\n type.group = true;\n if (json.comment)\n type.comment = json.comment;\n if (json.edition)\n type._edition = json.edition;\n type._defaultEdition = \"proto3\"; // For backwards-compatibility.\n return type;\n};\n\n/**\n * Converts this message type to a message type descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IType} Message type descriptor\n */\nType.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"edition\" , this._editionToJSON(),\n \"options\" , inherited && inherited.options || undefined,\n \"oneofs\" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),\n \"fields\" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {},\n \"extensions\" , this.extensions && this.extensions.length ? this.extensions : undefined,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"group\" , this.group || undefined,\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nType.prototype.resolveAll = function resolveAll() {\n if (!this._needsRecursiveResolve) return this;\n\n Namespace.prototype.resolveAll.call(this);\n var oneofs = this.oneofsArray; i = 0;\n while (i < oneofs.length)\n oneofs[i++].resolve();\n var fields = this.fieldsArray, i = 0;\n while (i < fields.length)\n fields[i++].resolve();\n return this;\n};\n\n/**\n * @override\n */\nType.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) {\n if (!this._needsRecursiveFeatureResolution) return this;\n\n edition = this._edition || edition;\n\n Namespace.prototype._resolveFeaturesRecursive.call(this, edition);\n this.oneofsArray.forEach(oneof => {\n oneof._resolveFeatures(edition);\n });\n this.fieldsArray.forEach(field => {\n field._resolveFeatures(edition);\n });\n return this;\n};\n\n/**\n * @override\n */\nType.prototype.get = function get(name) {\n return this.fields[name]\n || this.oneofs && this.oneofs[name]\n || this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Adds a nested object to this type.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id\n */\nType.prototype.add = function add(object) {\n\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Field && object.extend === undefined) {\n // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.\n // The root object takes care of adding distinct sister-fields to the respective extended\n // type instead.\n\n // avoids calling the getter if not absolutely necessary because it's called quite frequently\n if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id])\n throw Error(\"duplicate id \" + object.id + \" in \" + this);\n if (this.isReservedId(object.id))\n throw Error(\"id \" + object.id + \" is reserved in \" + this);\n if (this.isReservedName(object.name))\n throw Error(\"name '\" + object.name + \"' is reserved in \" + this);\n\n if (object.parent)\n object.parent.remove(object);\n this.fields[object.name] = object;\n object.message = this;\n object.onAdd(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n if (!this.oneofs)\n this.oneofs = {};\n this.oneofs[object.name] = object;\n object.onAdd(this);\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * Removes a nested object from this type.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this type\n */\nType.prototype.remove = function remove(object) {\n if (object instanceof Field && object.extend === undefined) {\n // See Type#add for the reason why extension fields are excluded here.\n\n /* istanbul ignore if */\n if (!this.fields || this.fields[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.fields[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n\n /* istanbul ignore if */\n if (!this.oneofs || this.oneofs[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.oneofs[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message<{}>} Message instance\n */\nType.prototype.create = function create(properties) {\n return new this.ctor(properties);\n};\n\n/**\n * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.\n * @returns {Type} `this`\n */\nType.prototype.setup = function setup() {\n // Sets up everything at once so that the prototype chain does not have to be re-evaluated\n // multiple times (V8, soft-deopt prototype-check).\n\n var fullName = this.fullName,\n types = [];\n for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i)\n types.push(this._fieldsArray[i].resolve().resolvedType);\n\n // Replace setup methods with type-specific generated functions\n this.encode = encoder(this)({\n Writer : Writer,\n types : types,\n util : util\n });\n this.decode = decoder(this)({\n Reader : Reader,\n types : types,\n util : util\n });\n this.verify = verifier(this)({\n types : types,\n util : util\n });\n this.fromObject = converter.fromObject(this)({\n types : types,\n util : util\n });\n this.toObject = converter.toObject(this)({\n types : types,\n util : util\n });\n\n // Inject custom wrappers for common types\n var wrapper = wrappers[fullName];\n if (wrapper) {\n var originalThis = Object.create(this);\n // if (wrapper.fromObject) {\n originalThis.fromObject = this.fromObject;\n this.fromObject = wrapper.fromObject.bind(originalThis);\n // }\n // if (wrapper.toObject) {\n originalThis.toObject = this.toObject;\n this.toObject = wrapper.toObject.bind(originalThis);\n // }\n }\n\n return this;\n};\n\n/**\n * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encode = function encode_setup(message, writer) {\n return this.setup().encode(message, writer); // overrides this method\n};\n\n/**\n * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encodeDelimited = function encodeDelimited(message, writer) {\n return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();\n};\n\n/**\n * Decodes a message of this type.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @param {number} [length] Length of the message, if known beforehand\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError<{}>} If required fields are missing\n */\nType.prototype.decode = function decode_setup(reader, length) {\n return this.setup().decode(reader, length); // overrides this method\n};\n\n/**\n * Decodes a message of this type preceeded by its byte length as a varint.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError} If required fields are missing\n */\nType.prototype.decodeDelimited = function decodeDelimited(reader) {\n if (!(reader instanceof Reader))\n reader = Reader.create(reader);\n return this.decode(reader, reader.uint32());\n};\n\n/**\n * Verifies that field values are valid and that required fields are present.\n * @param {Object.} message Plain object to verify\n * @returns {null|string} `null` if valid, otherwise the reason why it is not\n */\nType.prototype.verify = function verify_setup(message) {\n return this.setup().verify(message); // overrides this method\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object to convert\n * @returns {Message<{}>} Message instance\n */\nType.prototype.fromObject = function fromObject(object) {\n return this.setup().fromObject(object);\n};\n\n/**\n * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}.\n * @interface IConversionOptions\n * @property {Function} [longs] Long conversion type.\n * Valid values are `String` and `Number` (the global types).\n * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.\n * @property {Function} [enums] Enum value conversion type.\n * Only valid value is `String` (the global type).\n * Defaults to copy the present value, which is the numeric id.\n * @property {Function} [bytes] Bytes value conversion type.\n * Valid values are `Array` and (a base64 encoded) `String` (the global types).\n * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.\n * @property {boolean} [defaults=false] Also sets default values on the resulting object\n * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false`\n * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false`\n * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any\n * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings\n */\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n */\nType.prototype.toObject = function toObject(message, options) {\n return this.setup().toObject(message, options);\n};\n\n/**\n * Decorator function as returned by {@link Type.d} (TypeScript).\n * @typedef TypeDecorator\n * @type {function}\n * @param {Constructor} target Target constructor\n * @returns {undefined}\n * @template T extends Message\n */\n\n/**\n * Type decorator (TypeScript).\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {TypeDecorator} Decorator function\n * @template T extends Message\n */\nType.d = function decorateType(typeName) {\n return function typeDecorator(target) {\n util.decorateType(target, typeName);\n };\n};\n","\"use strict\";\n\n/**\n * Common type constants.\n * @namespace\n */\nvar types = exports;\n\nvar util = require(33);\n\nvar s = [\n \"double\", // 0\n \"float\", // 1\n \"int32\", // 2\n \"uint32\", // 3\n \"sint32\", // 4\n \"fixed32\", // 5\n \"sfixed32\", // 6\n \"int64\", // 7\n \"uint64\", // 8\n \"sint64\", // 9\n \"fixed64\", // 10\n \"sfixed64\", // 11\n \"bool\", // 12\n \"string\", // 13\n \"bytes\" // 14\n];\n\nfunction bake(values, offset) {\n var i = 0, o = {};\n offset |= 0;\n while (i < values.length) o[s[i + offset]] = values[i++];\n return o;\n}\n\n/**\n * Basic type wire types.\n * @type {Object.}\n * @const\n * @property {number} double=1 Fixed64 wire type\n * @property {number} float=5 Fixed32 wire type\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n * @property {number} string=2 Ldelim wire type\n * @property {number} bytes=2 Ldelim wire type\n */\ntypes.basic = bake([\n /* double */ 1,\n /* float */ 5,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0,\n /* string */ 2,\n /* bytes */ 2\n]);\n\n/**\n * Basic type defaults.\n * @type {Object.}\n * @const\n * @property {number} double=0 Double default\n * @property {number} float=0 Float default\n * @property {number} int32=0 Int32 default\n * @property {number} uint32=0 Uint32 default\n * @property {number} sint32=0 Sint32 default\n * @property {number} fixed32=0 Fixed32 default\n * @property {number} sfixed32=0 Sfixed32 default\n * @property {number} int64=0 Int64 default\n * @property {number} uint64=0 Uint64 default\n * @property {number} sint64=0 Sint32 default\n * @property {number} fixed64=0 Fixed64 default\n * @property {number} sfixed64=0 Sfixed64 default\n * @property {boolean} bool=false Bool default\n * @property {string} string=\"\" String default\n * @property {Array.} bytes=Array(0) Bytes default\n * @property {null} message=null Message default\n */\ntypes.defaults = bake([\n /* double */ 0,\n /* float */ 0,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 0,\n /* sfixed32 */ 0,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 0,\n /* sfixed64 */ 0,\n /* bool */ false,\n /* string */ \"\",\n /* bytes */ util.emptyArray,\n /* message */ null\n]);\n\n/**\n * Basic long type wire types.\n * @type {Object.}\n * @const\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n */\ntypes.long = bake([\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1\n], 7);\n\n/**\n * Allowed types for map keys with their associated wire type.\n * @type {Object.}\n * @const\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n * @property {number} string=2 Ldelim wire type\n */\ntypes.mapKey = bake([\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0,\n /* string */ 2\n], 2);\n\n/**\n * Allowed types for packed repeated fields with their associated wire type.\n * @type {Object.}\n * @const\n * @property {number} double=1 Fixed64 wire type\n * @property {number} float=5 Fixed32 wire type\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n */\ntypes.packed = bake([\n /* double */ 1,\n /* float */ 5,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0\n]);\n","\"use strict\";\n\n/**\n * Various utility functions.\n * @namespace\n */\nvar util = module.exports = require(35);\n\nvar roots = require(27);\n\nvar Type, // cyclic\n Enum;\n\nutil.codegen = require(3);\nutil.fetch = require(5);\nutil.path = require(8);\n\n/**\n * Node's fs module if available.\n * @type {Object.}\n */\nutil.fs = util.inquire(\"fs\");\n\n/**\n * Converts an object's values to an array.\n * @param {Object.} object Object to convert\n * @returns {Array.<*>} Converted array\n */\nutil.toArray = function toArray(object) {\n if (object) {\n var keys = Object.keys(object),\n array = new Array(keys.length),\n index = 0;\n while (index < keys.length)\n array[index] = object[keys[index++]];\n return array;\n }\n return [];\n};\n\n/**\n * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values.\n * @param {Array.<*>} array Array to convert\n * @returns {Object.} Converted object\n */\nutil.toObject = function toObject(array) {\n var object = {},\n index = 0;\n while (index < array.length) {\n var key = array[index++],\n val = array[index++];\n if (val !== undefined)\n object[key] = val;\n }\n return object;\n};\n\nvar safePropBackslashRe = /\\\\/g,\n safePropQuoteRe = /\"/g;\n\n/**\n * Tests whether the specified name is a reserved word in JS.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nutil.isReserved = function isReserved(name) {\n return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name);\n};\n\n/**\n * Returns a safe property accessor for the specified property name.\n * @param {string} prop Property name\n * @returns {string} Safe accessor\n */\nutil.safeProp = function safeProp(prop) {\n if (!/^[$\\w_]+$/.test(prop) || util.isReserved(prop))\n return \"[\\\"\" + prop.replace(safePropBackslashRe, \"\\\\\\\\\").replace(safePropQuoteRe, \"\\\\\\\"\") + \"\\\"]\";\n return \".\" + prop;\n};\n\n/**\n * Converts the first character of a string to upper case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.ucFirst = function ucFirst(str) {\n return str.charAt(0).toUpperCase() + str.substring(1);\n};\n\nvar camelCaseRe = /_([a-z])/g;\n\n/**\n * Converts a string to camel case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.camelCase = function camelCase(str) {\n return str.substring(0, 1)\n + str.substring(1)\n .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); });\n};\n\n/**\n * Compares reflected fields by id.\n * @param {Field} a First field\n * @param {Field} b Second field\n * @returns {number} Comparison value\n */\nutil.compareFieldsById = function compareFieldsById(a, b) {\n return a.id - b.id;\n};\n\n/**\n * Decorator helper for types (TypeScript).\n * @param {Constructor} ctor Constructor function\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {Type} Reflected type\n * @template T extends Message\n * @property {Root} root Decorators root\n */\nutil.decorateType = function decorateType(ctor, typeName) {\n\n /* istanbul ignore if */\n if (ctor.$type) {\n if (typeName && ctor.$type.name !== typeName) {\n util.decorateRoot.remove(ctor.$type);\n ctor.$type.name = typeName;\n util.decorateRoot.add(ctor.$type);\n }\n return ctor.$type;\n }\n\n /* istanbul ignore next */\n if (!Type)\n Type = require(31);\n\n var type = new Type(typeName || ctor.name);\n util.decorateRoot.add(type);\n type.ctor = ctor; // sets up .encode, .decode etc.\n Object.defineProperty(ctor, \"$type\", { value: type, enumerable: false });\n Object.defineProperty(ctor.prototype, \"$type\", { value: type, enumerable: false });\n return type;\n};\n\nvar decorateEnumIndex = 0;\n\n/**\n * Decorator helper for enums (TypeScript).\n * @param {Object} object Enum object\n * @returns {Enum} Reflected enum\n */\nutil.decorateEnum = function decorateEnum(object) {\n\n /* istanbul ignore if */\n if (object.$type)\n return object.$type;\n\n /* istanbul ignore next */\n if (!Enum)\n Enum = require(14);\n\n var enm = new Enum(\"Enum\" + decorateEnumIndex++, object);\n util.decorateRoot.add(enm);\n Object.defineProperty(object, \"$type\", { value: enm, enumerable: false });\n return enm;\n};\n\n\n/**\n * Sets the value of a property by property path. If a value already exists, it is turned to an array\n * @param {Object.} dst Destination object\n * @param {string} path dot '.' delimited path of the property to set\n * @param {Object} value the value to set\n * @param {boolean|undefined} [ifNotSet] Sets the option only if it isn't currently set\n * @returns {Object.} Destination object\n */\nutil.setProperty = function setProperty(dst, path, value, ifNotSet) {\n function setProp(dst, path, value) {\n var part = path.shift();\n if (part === \"__proto__\" || part === \"prototype\") {\n return dst;\n }\n if (path.length > 0) {\n dst[part] = setProp(dst[part] || {}, path, value);\n } else {\n var prevValue = dst[part];\n if (prevValue && ifNotSet)\n return dst;\n if (prevValue)\n value = [].concat(prevValue).concat(value);\n dst[part] = value;\n }\n return dst;\n }\n\n if (typeof dst !== \"object\")\n throw TypeError(\"dst must be an object\");\n if (!path)\n throw TypeError(\"path must be specified\");\n\n path = path.split(\".\");\n return setProp(dst, path, value);\n};\n\n/**\n * Decorator root (TypeScript).\n * @name util.decorateRoot\n * @type {Root}\n * @readonly\n */\nObject.defineProperty(util, \"decorateRoot\", {\n get: function() {\n return roots[\"decorated\"] || (roots[\"decorated\"] = new (require(26))());\n }\n});\n","\"use strict\";\nmodule.exports = LongBits;\n\nvar util = require(35);\n\n/**\n * Constructs new long bits.\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @constructor\n * @param {number} lo Low 32 bits, unsigned\n * @param {number} hi High 32 bits, unsigned\n */\nfunction LongBits(lo, hi) {\n\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits.\n * @type {number}\n */\n this.lo = lo >>> 0;\n\n /**\n * High bits.\n * @type {number}\n */\n this.hi = hi >>> 0;\n}\n\n/**\n * Zero bits.\n * @memberof util.LongBits\n * @type {util.LongBits}\n */\nvar zero = LongBits.zero = new LongBits(0, 0);\n\nzero.toNumber = function() { return 0; };\nzero.zzEncode = zero.zzDecode = function() { return this; };\nzero.length = function() { return 1; };\n\n/**\n * Zero hash.\n * @memberof util.LongBits\n * @type {string}\n */\nvar zeroHash = LongBits.zeroHash = \"\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n/**\n * Constructs new long bits from the specified number.\n * @param {number} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.fromNumber = function fromNumber(value) {\n if (value === 0)\n return zero;\n var sign = value < 0;\n if (sign)\n value = -value;\n var lo = value >>> 0,\n hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295)\n hi = 0;\n }\n }\n return new LongBits(lo, hi);\n};\n\n/**\n * Constructs new long bits from a number, long or string.\n * @param {Long|number|string} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.from = function from(value) {\n if (typeof value === \"number\")\n return LongBits.fromNumber(value);\n if (util.isString(value)) {\n /* istanbul ignore else */\n if (util.Long)\n value = util.Long.fromString(value);\n else\n return LongBits.fromNumber(parseInt(value, 10));\n }\n return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n};\n\n/**\n * Converts this long bits to a possibly unsafe JavaScript number.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {number} Possibly unsafe number\n */\nLongBits.prototype.toNumber = function toNumber(unsigned) {\n if (!unsigned && this.hi >>> 31) {\n var lo = ~this.lo + 1 >>> 0,\n hi = ~this.hi >>> 0;\n if (!lo)\n hi = hi + 1 >>> 0;\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n};\n\n/**\n * Converts this long bits to a long.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long} Long\n */\nLongBits.prototype.toLong = function toLong(unsigned) {\n return util.Long\n ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))\n /* istanbul ignore next */\n : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };\n};\n\nvar charCodeAt = String.prototype.charCodeAt;\n\n/**\n * Constructs new long bits from the specified 8 characters long hash.\n * @param {string} hash Hash\n * @returns {util.LongBits} Bits\n */\nLongBits.fromHash = function fromHash(hash) {\n if (hash === zeroHash)\n return zero;\n return new LongBits(\n ( charCodeAt.call(hash, 0)\n | charCodeAt.call(hash, 1) << 8\n | charCodeAt.call(hash, 2) << 16\n | charCodeAt.call(hash, 3) << 24) >>> 0\n ,\n ( charCodeAt.call(hash, 4)\n | charCodeAt.call(hash, 5) << 8\n | charCodeAt.call(hash, 6) << 16\n | charCodeAt.call(hash, 7) << 24) >>> 0\n );\n};\n\n/**\n * Converts this long bits to a 8 characters long hash.\n * @returns {string} Hash\n */\nLongBits.prototype.toHash = function toHash() {\n return String.fromCharCode(\n this.lo & 255,\n this.lo >>> 8 & 255,\n this.lo >>> 16 & 255,\n this.lo >>> 24 ,\n this.hi & 255,\n this.hi >>> 8 & 255,\n this.hi >>> 16 & 255,\n this.hi >>> 24\n );\n};\n\n/**\n * Zig-zag encodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzEncode = function zzEncode() {\n var mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = ( this.lo << 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Zig-zag decodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzDecode = function zzDecode() {\n var mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = ( this.hi >>> 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Calculates the length of this longbits when encoded as a varint.\n * @returns {number} Length\n */\nLongBits.prototype.length = function length() {\n var part0 = this.lo,\n part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,\n part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n};\n","\"use strict\";\nvar util = exports;\n\n// used to return a Promise where callback is omitted\nutil.asPromise = require(1);\n\n// converts to / from base64 encoded strings\nutil.base64 = require(2);\n\n// base class of rpc.Service\nutil.EventEmitter = require(4);\n\n// float handling accross browsers\nutil.float = require(6);\n\n// requires modules optionally and hides the call from bundlers\nutil.inquire = require(7);\n\n// converts to / from utf8 encoded strings\nutil.utf8 = require(10);\n\n// provides a node-like buffer pool in the browser\nutil.pool = require(9);\n\n// utility to work with the low and high bits of a 64 bit value\nutil.LongBits = require(34);\n\n/**\n * Whether running within node or not.\n * @memberof util\n * @type {boolean}\n */\nutil.isNode = Boolean(typeof global !== \"undefined\"\n && global\n && global.process\n && global.process.versions\n && global.process.versions.node);\n\n/**\n * Global object reference.\n * @memberof util\n * @type {Object}\n */\nutil.global = util.isNode && global\n || typeof window !== \"undefined\" && window\n || typeof self !== \"undefined\" && self\n || this; // eslint-disable-line no-invalid-this\n\n/**\n * An immuable empty array.\n * @memberof util\n * @type {Array.<*>}\n * @const\n */\nutil.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes\n\n/**\n * An immutable empty object.\n * @type {Object}\n * @const\n */\nutil.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes\n\n/**\n * Tests if the specified value is an integer.\n * @function\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is an integer\n */\nutil.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {\n return typeof value === \"number\" && isFinite(value) && Math.floor(value) === value;\n};\n\n/**\n * Tests if the specified value is a string.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a string\n */\nutil.isString = function isString(value) {\n return typeof value === \"string\" || value instanceof String;\n};\n\n/**\n * Tests if the specified value is a non-null object.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a non-null object\n */\nutil.isObject = function isObject(value) {\n return value && typeof value === \"object\";\n};\n\n/**\n * Checks if a property on a message is considered to be present.\n * This is an alias of {@link util.isSet}.\n * @function\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isset =\n\n/**\n * Checks if a property on a message is considered to be present.\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isSet = function isSet(obj, prop) {\n var value = obj[prop];\n if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins\n return typeof value !== \"object\" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;\n return false;\n};\n\n/**\n * Any compatible Buffer instance.\n * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.\n * @interface Buffer\n * @extends Uint8Array\n */\n\n/**\n * Node's Buffer class if available.\n * @type {Constructor}\n */\nutil.Buffer = (function() {\n try {\n var Buffer = util.inquire(\"buffer\").Buffer;\n // refuse to use non-node buffers if not explicitly assigned (perf reasons):\n return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;\n } catch (e) {\n /* istanbul ignore next */\n return null;\n }\n})();\n\n// Internal alias of or polyfull for Buffer.from.\nutil._Buffer_from = null;\n\n// Internal alias of or polyfill for Buffer.allocUnsafe.\nutil._Buffer_allocUnsafe = null;\n\n/**\n * Creates a new buffer of whatever type supported by the environment.\n * @param {number|number[]} [sizeOrArray=0] Buffer size or number array\n * @returns {Uint8Array|Buffer} Buffer\n */\nutil.newBuffer = function newBuffer(sizeOrArray) {\n /* istanbul ignore next */\n return typeof sizeOrArray === \"number\"\n ? util.Buffer\n ? util._Buffer_allocUnsafe(sizeOrArray)\n : new util.Array(sizeOrArray)\n : util.Buffer\n ? util._Buffer_from(sizeOrArray)\n : typeof Uint8Array === \"undefined\"\n ? sizeOrArray\n : new Uint8Array(sizeOrArray);\n};\n\n/**\n * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.\n * @type {Constructor}\n */\nutil.Array = typeof Uint8Array !== \"undefined\" ? Uint8Array /* istanbul ignore next */ : Array;\n\n/**\n * Any compatible Long instance.\n * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.\n * @interface Long\n * @property {number} low Low bits\n * @property {number} high High bits\n * @property {boolean} unsigned Whether unsigned or not\n */\n\n/**\n * Long.js's Long class if available.\n * @type {Constructor}\n */\nutil.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long\n || /* istanbul ignore next */ util.global.Long\n || util.inquire(\"long\");\n\n/**\n * Regular expression used to verify 2 bit (`bool`) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key2Re = /^true|false|0|1$/;\n\n/**\n * Regular expression used to verify 32 bit (`int32` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key32Re = /^-?(?:0|[1-9][0-9]*)$/;\n\n/**\n * Regular expression used to verify 64 bit (`int64` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key64Re = /^(?:[\\\\x00-\\\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;\n\n/**\n * Converts a number or long to an 8 characters long hash string.\n * @param {Long|number} value Value to convert\n * @returns {string} Hash\n */\nutil.longToHash = function longToHash(value) {\n return value\n ? util.LongBits.from(value).toHash()\n : util.LongBits.zeroHash;\n};\n\n/**\n * Converts an 8 characters long hash string to a long or number.\n * @param {string} hash Hash\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long|number} Original value\n */\nutil.longFromHash = function longFromHash(hash, unsigned) {\n var bits = util.LongBits.fromHash(hash);\n if (util.Long)\n return util.Long.fromBits(bits.lo, bits.hi, unsigned);\n return bits.toNumber(Boolean(unsigned));\n};\n\n/**\n * Merges the properties of the source object into the destination object.\n * @memberof util\n * @param {Object.} dst Destination object\n * @param {Object.} src Source object\n * @param {boolean} [ifNotSet=false] Merges only if the key is not already set\n * @returns {Object.} Destination object\n */\nfunction merge(dst, src, ifNotSet) { // used by converters\n for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)\n if (dst[keys[i]] === undefined || !ifNotSet)\n dst[keys[i]] = src[keys[i]];\n return dst;\n}\n\nutil.merge = merge;\n\n/**\n * Converts the first character of a string to lower case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.lcFirst = function lcFirst(str) {\n return str.charAt(0).toLowerCase() + str.substring(1);\n};\n\n/**\n * Creates a custom error constructor.\n * @memberof util\n * @param {string} name Error name\n * @returns {Constructor} Custom error constructor\n */\nfunction newError(name) {\n\n function CustomError(message, properties) {\n\n if (!(this instanceof CustomError))\n return new CustomError(message, properties);\n\n // Error.call(this, message);\n // ^ just returns a new error instance because the ctor can be called as a function\n\n Object.defineProperty(this, \"message\", { get: function() { return message; } });\n\n /* istanbul ignore next */\n if (Error.captureStackTrace) // node\n Error.captureStackTrace(this, CustomError);\n else\n Object.defineProperty(this, \"stack\", { value: new Error().stack || \"\" });\n\n if (properties)\n merge(this, properties);\n }\n\n CustomError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: CustomError,\n writable: true,\n enumerable: false,\n configurable: true,\n },\n name: {\n get: function get() { return name; },\n set: undefined,\n enumerable: false,\n // configurable: false would accurately preserve the behavior of\n // the original, but I'm guessing that was not intentional.\n // For an actual error subclass, this property would\n // be configurable.\n configurable: true,\n },\n toString: {\n value: function value() { return this.name + \": \" + this.message; },\n writable: true,\n enumerable: false,\n configurable: true,\n },\n });\n\n return CustomError;\n}\n\nutil.newError = newError;\n\n/**\n * Constructs a new protocol error.\n * @classdesc Error subclass indicating a protocol specifc error.\n * @memberof util\n * @extends Error\n * @template T extends Message\n * @constructor\n * @param {string} message Error message\n * @param {Object.} [properties] Additional properties\n * @example\n * try {\n * MyMessage.decode(someBuffer); // throws if required fields are missing\n * } catch (e) {\n * if (e instanceof ProtocolError && e.instance)\n * console.log(\"decoded so far: \" + JSON.stringify(e.instance));\n * }\n */\nutil.ProtocolError = newError(\"ProtocolError\");\n\n/**\n * So far decoded message instance.\n * @name util.ProtocolError#instance\n * @type {Message}\n */\n\n/**\n * A OneOf getter as returned by {@link util.oneOfGetter}.\n * @typedef OneOfGetter\n * @type {function}\n * @returns {string|undefined} Set field name, if any\n */\n\n/**\n * Builds a getter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfGetter} Unbound getter\n */\nutil.oneOfGetter = function getOneOf(fieldNames) {\n var fieldMap = {};\n for (var i = 0; i < fieldNames.length; ++i)\n fieldMap[fieldNames[i]] = 1;\n\n /**\n * @returns {string|undefined} Set field name, if any\n * @this Object\n * @ignore\n */\n return function() { // eslint-disable-line consistent-return\n for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)\n if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)\n return keys[i];\n };\n};\n\n/**\n * A OneOf setter as returned by {@link util.oneOfSetter}.\n * @typedef OneOfSetter\n * @type {function}\n * @param {string|undefined} value Field name\n * @returns {undefined}\n */\n\n/**\n * Builds a setter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfSetter} Unbound setter\n */\nutil.oneOfSetter = function setOneOf(fieldNames) {\n\n /**\n * @param {string} name Field name\n * @returns {undefined}\n * @this Object\n * @ignore\n */\n return function(name) {\n for (var i = 0; i < fieldNames.length; ++i)\n if (fieldNames[i] !== name)\n delete this[fieldNames[i]];\n };\n};\n\n/**\n * Default conversion options used for {@link Message#toJSON} implementations.\n *\n * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:\n *\n * - Longs become strings\n * - Enums become string keys\n * - Bytes become base64 encoded strings\n * - (Sub-)Messages become plain objects\n * - Maps become plain objects with all string keys\n * - Repeated fields become arrays\n * - NaN and Infinity for float and double fields become strings\n *\n * @type {IConversionOptions}\n * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json\n */\nutil.toJSONOptions = {\n longs: String,\n enums: String,\n bytes: String,\n json: true\n};\n\n// Sets up buffer utility according to the environment (called in index-minimal)\nutil._configure = function() {\n var Buffer = util.Buffer;\n /* istanbul ignore if */\n if (!Buffer) {\n util._Buffer_from = util._Buffer_allocUnsafe = null;\n return;\n }\n // because node 4.x buffers are incompatible & immutable\n // see: https://github.com/dcodeIO/protobuf.js/pull/665\n util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||\n /* istanbul ignore next */\n function Buffer_from(value, encoding) {\n return new Buffer(value, encoding);\n };\n util._Buffer_allocUnsafe = Buffer.allocUnsafe ||\n /* istanbul ignore next */\n function Buffer_allocUnsafe(size) {\n return new Buffer(size);\n };\n};\n","\"use strict\";\nmodule.exports = verifier;\n\nvar Enum = require(14),\n util = require(33);\n\nfunction invalid(field, expected) {\n return field.name + \": \" + expected + (field.repeated && expected !== \"array\" ? \"[]\" : field.map && expected !== \"object\" ? \"{k:\"+field.keyType+\"}\" : \"\") + \" expected\";\n}\n\n/**\n * Generates a partial value verifier.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {number} fieldIndex Field index\n * @param {string} ref Variable reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genVerifyValue(gen, field, fieldIndex, ref) {\n /* eslint-disable no-unexpected-multiline */\n if (field.resolvedType) {\n if (field.resolvedType instanceof Enum) { gen\n (\"switch(%s){\", ref)\n (\"default:\")\n (\"return%j\", invalid(field, \"enum value\"));\n for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen\n (\"case %i:\", field.resolvedType.values[keys[j]]);\n gen\n (\"break\")\n (\"}\");\n } else {\n gen\n (\"{\")\n (\"var e=types[%i].verify(%s);\", fieldIndex, ref)\n (\"if(e)\")\n (\"return%j+e\", field.name + \".\")\n (\"}\");\n }\n } else {\n switch (field.type) {\n case \"int32\":\n case \"uint32\":\n case \"sint32\":\n case \"fixed32\":\n case \"sfixed32\": gen\n (\"if(!util.isInteger(%s))\", ref)\n (\"return%j\", invalid(field, \"integer\"));\n break;\n case \"int64\":\n case \"uint64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))\", ref, ref, ref, ref)\n (\"return%j\", invalid(field, \"integer|Long\"));\n break;\n case \"float\":\n case \"double\": gen\n (\"if(typeof %s!==\\\"number\\\")\", ref)\n (\"return%j\", invalid(field, \"number\"));\n break;\n case \"bool\": gen\n (\"if(typeof %s!==\\\"boolean\\\")\", ref)\n (\"return%j\", invalid(field, \"boolean\"));\n break;\n case \"string\": gen\n (\"if(!util.isString(%s))\", ref)\n (\"return%j\", invalid(field, \"string\"));\n break;\n case \"bytes\": gen\n (\"if(!(%s&&typeof %s.length===\\\"number\\\"||util.isString(%s)))\", ref, ref, ref)\n (\"return%j\", invalid(field, \"buffer\"));\n break;\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline */\n}\n\n/**\n * Generates a partial key verifier.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {string} ref Variable reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genVerifyKey(gen, field, ref) {\n /* eslint-disable no-unexpected-multiline */\n switch (field.keyType) {\n case \"int32\":\n case \"uint32\":\n case \"sint32\":\n case \"fixed32\":\n case \"sfixed32\": gen\n (\"if(!util.key32Re.test(%s))\", ref)\n (\"return%j\", invalid(field, \"integer key\"));\n break;\n case \"int64\":\n case \"uint64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(!util.key64Re.test(%s))\", ref) // see comment above: x is ok, d is not\n (\"return%j\", invalid(field, \"integer|Long key\"));\n break;\n case \"bool\": gen\n (\"if(!util.key2Re.test(%s))\", ref)\n (\"return%j\", invalid(field, \"boolean key\"));\n break;\n }\n return gen;\n /* eslint-enable no-unexpected-multiline */\n}\n\n/**\n * Generates a verifier specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nfunction verifier(mtype) {\n /* eslint-disable no-unexpected-multiline */\n\n var gen = util.codegen([\"m\"], mtype.name + \"$verify\")\n (\"if(typeof m!==\\\"object\\\"||m===null)\")\n (\"return%j\", \"object expected\");\n var oneofs = mtype.oneofsArray,\n seenFirstField = {};\n if (oneofs.length) gen\n (\"var p={}\");\n\n for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {\n var field = mtype._fieldsArray[i].resolve(),\n ref = \"m\" + util.safeProp(field.name);\n\n if (field.optional) gen\n (\"if(%s!=null&&m.hasOwnProperty(%j)){\", ref, field.name); // !== undefined && !== null\n\n // map fields\n if (field.map) { gen\n (\"if(!util.isObject(%s))\", ref)\n (\"return%j\", invalid(field, \"object\"))\n (\"var k=Object.keys(%s)\", ref)\n (\"for(var i=0;i}\n * @const\n */\nvar wrappers = exports;\n\nvar Message = require(19);\n\n/**\n * From object converter part of an {@link IWrapper}.\n * @typedef WrapperFromObjectConverter\n * @type {function}\n * @param {Object.} object Plain object\n * @returns {Message<{}>} Message instance\n * @this Type\n */\n\n/**\n * To object converter part of an {@link IWrapper}.\n * @typedef WrapperToObjectConverter\n * @type {function}\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n * @this Type\n */\n\n/**\n * Common type wrapper part of {@link wrappers}.\n * @interface IWrapper\n * @property {WrapperFromObjectConverter} [fromObject] From object converter\n * @property {WrapperToObjectConverter} [toObject] To object converter\n */\n\n// Custom wrapper for Any\nwrappers[\".google.protobuf.Any\"] = {\n\n fromObject: function(object) {\n\n // unwrap value type if mapped\n if (object && object[\"@type\"]) {\n // Only use fully qualified type name after the last '/'\n var name = object[\"@type\"].substring(object[\"@type\"].lastIndexOf(\"/\") + 1);\n var type = this.lookup(name);\n /* istanbul ignore else */\n if (type) {\n // type_url does not accept leading \".\"\n var type_url = object[\"@type\"].charAt(0) === \".\" ?\n object[\"@type\"].slice(1) : object[\"@type\"];\n // type_url prefix is optional, but path seperator is required\n if (type_url.indexOf(\"/\") === -1) {\n type_url = \"/\" + type_url;\n }\n return this.create({\n type_url: type_url,\n value: type.encode(type.fromObject(object)).finish()\n });\n }\n }\n\n return this.fromObject(object);\n },\n\n toObject: function(message, options) {\n\n // Default prefix\n var googleApi = \"type.googleapis.com/\";\n var prefix = \"\";\n var name = \"\";\n\n // decode value if requested and unmapped\n if (options && options.json && message.type_url && message.value) {\n // Only use fully qualified type name after the last '/'\n name = message.type_url.substring(message.type_url.lastIndexOf(\"/\") + 1);\n // Separate the prefix used\n prefix = message.type_url.substring(0, message.type_url.lastIndexOf(\"/\") + 1);\n var type = this.lookup(name);\n /* istanbul ignore else */\n if (type)\n message = type.decode(message.value);\n }\n\n // wrap value if unmapped\n if (!(message instanceof this.ctor) && message instanceof Message) {\n var object = message.$type.toObject(message, options);\n var messageName = message.$type.fullName[0] === \".\" ?\n message.$type.fullName.slice(1) : message.$type.fullName;\n // Default to type.googleapis.com prefix if no prefix is used\n if (prefix === \"\") {\n prefix = googleApi;\n }\n name = prefix + messageName;\n object[\"@type\"] = name;\n return object;\n }\n\n return this.toObject(message, options);\n }\n};\n","\"use strict\";\nmodule.exports = Writer;\n\nvar util = require(35);\n\nvar BufferWriter; // cyclic\n\nvar LongBits = util.LongBits,\n base64 = util.base64,\n utf8 = util.utf8;\n\n/**\n * Constructs a new writer operation instance.\n * @classdesc Scheduled writer operation.\n * @constructor\n * @param {function(*, Uint8Array, number)} fn Function to call\n * @param {number} len Value byte length\n * @param {*} val Value to write\n * @ignore\n */\nfunction Op(fn, len, val) {\n\n /**\n * Function to call.\n * @type {function(Uint8Array, number, *)}\n */\n this.fn = fn;\n\n /**\n * Value byte length.\n * @type {number}\n */\n this.len = len;\n\n /**\n * Next operation.\n * @type {Writer.Op|undefined}\n */\n this.next = undefined;\n\n /**\n * Value to write.\n * @type {*}\n */\n this.val = val; // type varies\n}\n\n/* istanbul ignore next */\nfunction noop() {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance.\n * @classdesc Copied writer state.\n * @memberof Writer\n * @constructor\n * @param {Writer} writer Writer to copy state from\n * @ignore\n */\nfunction State(writer) {\n\n /**\n * Current head.\n * @type {Writer.Op}\n */\n this.head = writer.head;\n\n /**\n * Current tail.\n * @type {Writer.Op}\n */\n this.tail = writer.tail;\n\n /**\n * Current buffer length.\n * @type {number}\n */\n this.len = writer.len;\n\n /**\n * Next state.\n * @type {State|null}\n */\n this.next = writer.states;\n}\n\n/**\n * Constructs a new writer instance.\n * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n */\nfunction Writer() {\n\n /**\n * Current length.\n * @type {number}\n */\n this.len = 0;\n\n /**\n * Operations head.\n * @type {Object}\n */\n this.head = new Op(noop, 0, 0);\n\n /**\n * Operations tail\n * @type {Object}\n */\n this.tail = this.head;\n\n /**\n * Linked forked states.\n * @type {Object|null}\n */\n this.states = null;\n\n // When a value is written, the writer calculates its byte length and puts it into a linked\n // list of operations to perform when finish() is called. This both allows us to allocate\n // buffers of the exact required size and reduces the amount of work we have to do compared\n // to first calculating over objects and then encoding over objects. In our case, the encoding\n // part is just a linked list walk calling operations with already prepared values.\n}\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup() {\n return (Writer.create = function create_buffer() {\n return new BufferWriter();\n })();\n }\n /* istanbul ignore next */\n : function create_array() {\n return new Writer();\n };\n};\n\n/**\n * Creates a new writer.\n * @function\n * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}\n */\nWriter.create = create();\n\n/**\n * Allocates a buffer of the specified size.\n * @param {number} size Buffer size\n * @returns {Uint8Array} Buffer\n */\nWriter.alloc = function alloc(size) {\n return new util.Array(size);\n};\n\n// Use Uint8Array buffer pool in the browser, just like node does with buffers\n/* istanbul ignore else */\nif (util.Array !== Array)\n Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);\n\n/**\n * Pushes a new operation to the queue.\n * @param {function(Uint8Array, number, *)} fn Function to call\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @returns {Writer} `this`\n * @private\n */\nWriter.prototype._push = function push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n};\n\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\n\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n\n/**\n * Constructs a new varint writer operation instance.\n * @classdesc Scheduled varint writer operation.\n * @extends Op\n * @constructor\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @ignore\n */\nfunction VarintOp(len, val) {\n this.len = len;\n this.next = undefined;\n this.val = val;\n}\n\nVarintOp.prototype = Object.create(Op.prototype);\nVarintOp.prototype.fn = writeVarint32;\n\n/**\n * Writes an unsigned 32 bit value as a varint.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.uint32 = function write_uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0)\n < 128 ? 1\n : value < 16384 ? 2\n : value < 2097152 ? 3\n : value < 268435456 ? 4\n : 5,\n value)).len;\n return this;\n};\n\n/**\n * Writes a signed 32 bit value as a varint.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.int32 = function write_int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n};\n\n/**\n * Writes a 32 bit value as a varint, zig-zag encoded.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sint32 = function write_sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n};\n\nfunction writeVarint64(val, buf, pos) {\n while (val.hi) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\n\n/**\n * Writes an unsigned 64 bit value as a varint.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.uint64 = function write_uint64(value) {\n var bits = LongBits.from(value);\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a signed 64 bit value as a varint.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.int64 = Writer.prototype.uint64;\n\n/**\n * Writes a signed 64 bit value as a varint, zig-zag encoded.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sint64 = function write_sint64(value) {\n var bits = LongBits.from(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a boolish value as a varint.\n * @param {boolean} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bool = function write_bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n};\n\nfunction writeFixed32(val, buf, pos) {\n buf[pos ] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\n\n/**\n * Writes an unsigned 32 bit value as fixed 32 bits.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.fixed32 = function write_fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n};\n\n/**\n * Writes a signed 32 bit value as fixed 32 bits.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sfixed32 = Writer.prototype.fixed32;\n\n/**\n * Writes an unsigned 64 bit value as fixed 64 bits.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.fixed64 = function write_fixed64(value) {\n var bits = LongBits.from(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n};\n\n/**\n * Writes a signed 64 bit value as fixed 64 bits.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sfixed64 = Writer.prototype.fixed64;\n\n/**\n * Writes a float (32 bit).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.float = function write_float(value) {\n return this._push(util.float.writeFloatLE, 4, value);\n};\n\n/**\n * Writes a double (64 bit float).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.double = function write_double(value) {\n return this._push(util.float.writeDoubleLE, 8, value);\n};\n\nvar writeBytes = util.Array.prototype.set\n ? function writeBytes_set(val, buf, pos) {\n buf.set(val, pos); // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytes_for(val, buf, pos) {\n for (var i = 0; i < val.length; ++i)\n buf[pos + i] = val[i];\n };\n\n/**\n * Writes a sequence of bytes.\n * @param {Uint8Array|string} value Buffer or base64 encoded string to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bytes = function write_bytes(value) {\n var len = value.length >>> 0;\n if (!len)\n return this._push(writeByte, 1, 0);\n if (util.isString(value)) {\n var buf = Writer.alloc(len = base64.length(value));\n base64.decode(value, buf, 0);\n value = buf;\n }\n return this.uint32(len)._push(writeBytes, len, value);\n};\n\n/**\n * Writes a string.\n * @param {string} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.string = function write_string(value) {\n var len = utf8.length(value);\n return len\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0);\n};\n\n/**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n * @returns {Writer} `this`\n */\nWriter.prototype.fork = function fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n};\n\n/**\n * Resets this instance to the last state.\n * @returns {Writer} `this`\n */\nWriter.prototype.reset = function reset() {\n if (this.states) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n } else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n};\n\n/**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n * @returns {Writer} `this`\n */\nWriter.prototype.ldelim = function ldelim() {\n var head = this.head,\n tail = this.tail,\n len = this.len;\n this.reset().uint32(len);\n if (len) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n};\n\n/**\n * Finishes the write operation.\n * @returns {Uint8Array} Finished buffer\n */\nWriter.prototype.finish = function finish() {\n var head = this.head.next, // skip noop\n buf = this.constructor.alloc(this.len),\n pos = 0;\n while (head) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n};\n\nWriter._configure = function(BufferWriter_) {\n BufferWriter = BufferWriter_;\n Writer.create = create();\n BufferWriter._configure();\n};\n","\"use strict\";\nmodule.exports = BufferWriter;\n\n// extends Writer\nvar Writer = require(38);\n(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;\n\nvar util = require(35);\n\n/**\n * Constructs a new buffer writer instance.\n * @classdesc Wire format writer using node buffers.\n * @extends Writer\n * @constructor\n */\nfunction BufferWriter() {\n Writer.call(this);\n}\n\nBufferWriter._configure = function () {\n /**\n * Allocates a buffer of the specified size.\n * @function\n * @param {number} size Buffer size\n * @returns {Buffer} Buffer\n */\n BufferWriter.alloc = util._Buffer_allocUnsafe;\n\n BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === \"set\"\n ? function writeBytesBuffer_set(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytesBuffer_copy(val, buf, pos) {\n if (val.copy) // Buffer values\n val.copy(buf, pos, 0, val.length);\n else for (var i = 0; i < val.length;) // plain array values\n buf[pos++] = val[i++];\n };\n};\n\n\n/**\n * @override\n */\nBufferWriter.prototype.bytes = function write_bytes_buffer(value) {\n if (util.isString(value))\n value = util._Buffer_from(value, \"base64\");\n var len = value.length >>> 0;\n this.uint32(len);\n if (len)\n this._push(BufferWriter.writeBytesBuffer, len, value);\n return this;\n};\n\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)\n util.utf8.write(val, buf, pos);\n else if (buf.utf8Write)\n buf.utf8Write(val, pos);\n else\n buf.write(val, pos);\n}\n\n/**\n * @override\n */\nBufferWriter.prototype.string = function write_string_buffer(value) {\n var len = util.Buffer.byteLength(value);\n this.uint32(len);\n if (len)\n this._push(writeStringBuffer, len, value);\n return this;\n};\n\n\n/**\n * Finishes the write operation.\n * @name BufferWriter#finish\n * @function\n * @returns {Buffer} Finished buffer\n */\n\nBufferWriter._configure();\n"],"sourceRoot":"."} \ No newline at end of file diff --git a/node_modules/protobufjs/dist/minimal/protobuf.js b/node_modules/protobufjs/dist/minimal/protobuf.js new file mode 100644 index 0000000..02f5cf8 --- /dev/null +++ b/node_modules/protobufjs/dist/minimal/protobuf.js @@ -0,0 +1,2736 @@ +/*! + * protobuf.js v7.5.4 (c) 2016, daniel wirtz + * compiled fri, 15 aug 2025 23:28:54 utc + * licensed under the bsd-3-clause license + * see: https://github.com/dcodeio/protobuf.js for details + */ +(function(undefined){"use strict";(function prelude(modules, cache, entries) { + + // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS + // sources through a conflict-free require shim and is again wrapped within an iife that + // provides a minification-friendly `undefined` var plus a global "use strict" directive + // so that minification can remove the directives of each module. + + function $require(name) { + var $module = cache[name]; + if (!$module) + modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports); + return $module.exports; + } + + var protobuf = $require(entries[0]); + + // Expose globally + protobuf.util.global.protobuf = protobuf; + + // Be nice to AMD + if (typeof define === "function" && define.amd) + define(["long"], function(Long) { + if (Long && Long.isLong) { + protobuf.util.Long = Long; + protobuf.configure(); + } + return protobuf; + }); + + // Be nice to CommonJS + if (typeof module === "object" && module && module.exports) + module.exports = protobuf; + +})/* end of prelude */({1:[function(require,module,exports){ +"use strict"; +module.exports = asPromise; + +/** + * Callback as used by {@link util.asPromise}. + * @typedef asPromiseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {...*} params Additional arguments + * @returns {undefined} + */ + +/** + * Returns a promise from a node-style callback function. + * @memberof util + * @param {asPromiseCallback} fn Function to call + * @param {*} ctx Function context + * @param {...*} params Function arguments + * @returns {Promise<*>} Promisified function + */ +function asPromise(fn, ctx/*, varargs */) { + var params = new Array(arguments.length - 1), + offset = 0, + index = 2, + pending = true; + while (index < arguments.length) + params[offset++] = arguments[index++]; + return new Promise(function executor(resolve, reject) { + params[offset] = function callback(err/*, varargs */) { + if (pending) { + pending = false; + if (err) + reject(err); + else { + var params = new Array(arguments.length - 1), + offset = 0; + while (offset < params.length) + params[offset++] = arguments[offset]; + resolve.apply(null, params); + } + } + }; + try { + fn.apply(ctx || null, params); + } catch (err) { + if (pending) { + pending = false; + reject(err); + } + } + }); +} + +},{}],2:[function(require,module,exports){ +"use strict"; + +/** + * A minimal base64 implementation for number arrays. + * @memberof util + * @namespace + */ +var base64 = exports; + +/** + * Calculates the byte length of a base64 encoded string. + * @param {string} string Base64 encoded string + * @returns {number} Byte length + */ +base64.length = function length(string) { + var p = string.length; + if (!p) + return 0; + var n = 0; + while (--p % 4 > 1 && string.charAt(p) === "=") + ++n; + return Math.ceil(string.length * 3) / 4 - n; +}; + +// Base64 encoding table +var b64 = new Array(64); + +// Base64 decoding table +var s64 = new Array(123); + +// 65..90, 97..122, 48..57, 43, 47 +for (var i = 0; i < 64;) + s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; + +/** + * Encodes a buffer to a base64 encoded string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} Base64 encoded string + */ +base64.encode = function encode(buffer, start, end) { + var parts = null, + chunk = []; + var i = 0, // output index + j = 0, // goto index + t; // temporary + while (start < end) { + var b = buffer[start++]; + switch (j) { + case 0: + chunk[i++] = b64[b >> 2]; + t = (b & 3) << 4; + j = 1; + break; + case 1: + chunk[i++] = b64[t | b >> 4]; + t = (b & 15) << 2; + j = 2; + break; + case 2: + chunk[i++] = b64[t | b >> 6]; + chunk[i++] = b64[b & 63]; + j = 0; + break; + } + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i = 0; + } + } + if (j) { + chunk[i++] = b64[t]; + chunk[i++] = 61; + if (j === 1) + chunk[i++] = 61; + } + if (parts) { + if (i) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i)); +}; + +var invalidEncoding = "invalid encoding"; + +/** + * Decodes a base64 encoded string to a buffer. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Number of bytes written + * @throws {Error} If encoding is invalid + */ +base64.decode = function decode(string, buffer, offset) { + var start = offset; + var j = 0, // goto index + t; // temporary + for (var i = 0; i < string.length;) { + var c = string.charCodeAt(i++); + if (c === 61 && j > 1) + break; + if ((c = s64[c]) === undefined) + throw Error(invalidEncoding); + switch (j) { + case 0: + t = c; + j = 1; + break; + case 1: + buffer[offset++] = t << 2 | (c & 48) >> 4; + t = c; + j = 2; + break; + case 2: + buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; + t = c; + j = 3; + break; + case 3: + buffer[offset++] = (t & 3) << 6 | c; + j = 0; + break; + } + } + if (j === 1) + throw Error(invalidEncoding); + return offset - start; +}; + +/** + * Tests if the specified string appears to be base64 encoded. + * @param {string} string String to test + * @returns {boolean} `true` if probably base64 encoded, otherwise false + */ +base64.test = function test(string) { + return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string); +}; + +},{}],3:[function(require,module,exports){ +"use strict"; +module.exports = EventEmitter; + +/** + * Constructs a new event emitter instance. + * @classdesc A minimal event emitter. + * @memberof util + * @constructor + */ +function EventEmitter() { + + /** + * Registered listeners. + * @type {Object.} + * @private + */ + this._listeners = {}; +} + +/** + * Registers an event listener. + * @param {string} evt Event name + * @param {function} fn Listener + * @param {*} [ctx] Listener context + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.on = function on(evt, fn, ctx) { + (this._listeners[evt] || (this._listeners[evt] = [])).push({ + fn : fn, + ctx : ctx || this + }); + return this; +}; + +/** + * Removes an event listener or any matching listeners if arguments are omitted. + * @param {string} [evt] Event name. Removes all listeners if omitted. + * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted. + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.off = function off(evt, fn) { + if (evt === undefined) + this._listeners = {}; + else { + if (fn === undefined) + this._listeners[evt] = []; + else { + var listeners = this._listeners[evt]; + for (var i = 0; i < listeners.length;) + if (listeners[i].fn === fn) + listeners.splice(i, 1); + else + ++i; + } + } + return this; +}; + +/** + * Emits an event by calling its listeners with the specified arguments. + * @param {string} evt Event name + * @param {...*} args Arguments + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.emit = function emit(evt) { + var listeners = this._listeners[evt]; + if (listeners) { + var args = [], + i = 1; + for (; i < arguments.length;) + args.push(arguments[i++]); + for (i = 0; i < listeners.length;) + listeners[i].fn.apply(listeners[i++].ctx, args); + } + return this; +}; + +},{}],4:[function(require,module,exports){ +"use strict"; + +module.exports = factory(factory); + +/** + * Reads / writes floats / doubles from / to buffers. + * @name util.float + * @namespace + */ + +/** + * Writes a 32 bit float to a buffer using little endian byte order. + * @name util.float.writeFloatLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Writes a 32 bit float to a buffer using big endian byte order. + * @name util.float.writeFloatBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Reads a 32 bit float from a buffer using little endian byte order. + * @name util.float.readFloatLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Reads a 32 bit float from a buffer using big endian byte order. + * @name util.float.readFloatBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Writes a 64 bit double to a buffer using little endian byte order. + * @name util.float.writeDoubleLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Writes a 64 bit double to a buffer using big endian byte order. + * @name util.float.writeDoubleBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Reads a 64 bit double from a buffer using little endian byte order. + * @name util.float.readDoubleLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Reads a 64 bit double from a buffer using big endian byte order. + * @name util.float.readDoubleBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +// Factory function for the purpose of node-based testing in modified global environments +function factory(exports) { + + // float: typed array + if (typeof Float32Array !== "undefined") (function() { + + var f32 = new Float32Array([ -0 ]), + f8b = new Uint8Array(f32.buffer), + le = f8b[3] === 128; + + function writeFloat_f32_cpy(val, buf, pos) { + f32[0] = val; + buf[pos ] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + } + + function writeFloat_f32_rev(val, buf, pos) { + f32[0] = val; + buf[pos ] = f8b[3]; + buf[pos + 1] = f8b[2]; + buf[pos + 2] = f8b[1]; + buf[pos + 3] = f8b[0]; + } + + /* istanbul ignore next */ + exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; + /* istanbul ignore next */ + exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; + + function readFloat_f32_cpy(buf, pos) { + f8b[0] = buf[pos ]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + return f32[0]; + } + + function readFloat_f32_rev(buf, pos) { + f8b[3] = buf[pos ]; + f8b[2] = buf[pos + 1]; + f8b[1] = buf[pos + 2]; + f8b[0] = buf[pos + 3]; + return f32[0]; + } + + /* istanbul ignore next */ + exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; + /* istanbul ignore next */ + exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; + + // float: ieee754 + })(); else (function() { + + function writeFloat_ieee754(writeUint, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) + writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos); + else if (isNaN(val)) + writeUint(2143289344, buf, pos); + else if (val > 3.4028234663852886e+38) // +-Infinity + writeUint((sign << 31 | 2139095040) >>> 0, buf, pos); + else if (val < 1.1754943508222875e-38) // denormal + writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos); + else { + var exponent = Math.floor(Math.log(val) / Math.LN2), + mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; + writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); + } + } + + exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); + exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); + + function readFloat_ieee754(readUint, buf, pos) { + var uint = readUint(buf, pos), + sign = (uint >> 31) * 2 + 1, + exponent = uint >>> 23 & 255, + mantissa = uint & 8388607; + return exponent === 255 + ? mantissa + ? NaN + : sign * Infinity + : exponent === 0 // denormal + ? sign * 1.401298464324817e-45 * mantissa + : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); + } + + exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE); + exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE); + + })(); + + // double: typed array + if (typeof Float64Array !== "undefined") (function() { + + var f64 = new Float64Array([-0]), + f8b = new Uint8Array(f64.buffer), + le = f8b[7] === 128; + + function writeDouble_f64_cpy(val, buf, pos) { + f64[0] = val; + buf[pos ] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + buf[pos + 4] = f8b[4]; + buf[pos + 5] = f8b[5]; + buf[pos + 6] = f8b[6]; + buf[pos + 7] = f8b[7]; + } + + function writeDouble_f64_rev(val, buf, pos) { + f64[0] = val; + buf[pos ] = f8b[7]; + buf[pos + 1] = f8b[6]; + buf[pos + 2] = f8b[5]; + buf[pos + 3] = f8b[4]; + buf[pos + 4] = f8b[3]; + buf[pos + 5] = f8b[2]; + buf[pos + 6] = f8b[1]; + buf[pos + 7] = f8b[0]; + } + + /* istanbul ignore next */ + exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; + /* istanbul ignore next */ + exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; + + function readDouble_f64_cpy(buf, pos) { + f8b[0] = buf[pos ]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + f8b[4] = buf[pos + 4]; + f8b[5] = buf[pos + 5]; + f8b[6] = buf[pos + 6]; + f8b[7] = buf[pos + 7]; + return f64[0]; + } + + function readDouble_f64_rev(buf, pos) { + f8b[7] = buf[pos ]; + f8b[6] = buf[pos + 1]; + f8b[5] = buf[pos + 2]; + f8b[4] = buf[pos + 3]; + f8b[3] = buf[pos + 4]; + f8b[2] = buf[pos + 5]; + f8b[1] = buf[pos + 6]; + f8b[0] = buf[pos + 7]; + return f64[0]; + } + + /* istanbul ignore next */ + exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; + /* istanbul ignore next */ + exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; + + // double: ieee754 + })(); else (function() { + + function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) { + writeUint(0, buf, pos + off0); + writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1); + } else if (isNaN(val)) { + writeUint(0, buf, pos + off0); + writeUint(2146959360, buf, pos + off1); + } else if (val > 1.7976931348623157e+308) { // +-Infinity + writeUint(0, buf, pos + off0); + writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1); + } else { + var mantissa; + if (val < 2.2250738585072014e-308) { // denormal + mantissa = val / 5e-324; + writeUint(mantissa >>> 0, buf, pos + off0); + writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); + } else { + var exponent = Math.floor(Math.log(val) / Math.LN2); + if (exponent === 1024) + exponent = 1023; + mantissa = val * Math.pow(2, -exponent); + writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); + writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); + } + } + } + + exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); + exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); + + function readDouble_ieee754(readUint, off0, off1, buf, pos) { + var lo = readUint(buf, pos + off0), + hi = readUint(buf, pos + off1); + var sign = (hi >> 31) * 2 + 1, + exponent = hi >>> 20 & 2047, + mantissa = 4294967296 * (hi & 1048575) + lo; + return exponent === 2047 + ? mantissa + ? NaN + : sign * Infinity + : exponent === 0 // denormal + ? sign * 5e-324 * mantissa + : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); + } + + exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); + exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); + + })(); + + return exports; +} + +// uint helpers + +function writeUintLE(val, buf, pos) { + buf[pos ] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; +} + +function writeUintBE(val, buf, pos) { + buf[pos ] = val >>> 24; + buf[pos + 1] = val >>> 16 & 255; + buf[pos + 2] = val >>> 8 & 255; + buf[pos + 3] = val & 255; +} + +function readUintLE(buf, pos) { + return (buf[pos ] + | buf[pos + 1] << 8 + | buf[pos + 2] << 16 + | buf[pos + 3] << 24) >>> 0; +} + +function readUintBE(buf, pos) { + return (buf[pos ] << 24 + | buf[pos + 1] << 16 + | buf[pos + 2] << 8 + | buf[pos + 3]) >>> 0; +} + +},{}],5:[function(require,module,exports){ +"use strict"; +module.exports = inquire; + +/** + * Requires a module only if available. + * @memberof util + * @param {string} moduleName Module to require + * @returns {?Object} Required module if available and not empty, otherwise `null` + */ +function inquire(moduleName) { + try { + var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval + if (mod && (mod.length || Object.keys(mod).length)) + return mod; + } catch (e) {} // eslint-disable-line no-empty + return null; +} + +},{}],6:[function(require,module,exports){ +"use strict"; +module.exports = pool; + +/** + * An allocator as used by {@link util.pool}. + * @typedef PoolAllocator + * @type {function} + * @param {number} size Buffer size + * @returns {Uint8Array} Buffer + */ + +/** + * A slicer as used by {@link util.pool}. + * @typedef PoolSlicer + * @type {function} + * @param {number} start Start offset + * @param {number} end End offset + * @returns {Uint8Array} Buffer slice + * @this {Uint8Array} + */ + +/** + * A general purpose buffer pool. + * @memberof util + * @function + * @param {PoolAllocator} alloc Allocator + * @param {PoolSlicer} slice Slicer + * @param {number} [size=8192] Slab size + * @returns {PoolAllocator} Pooled allocator + */ +function pool(alloc, slice, size) { + var SIZE = size || 8192; + var MAX = SIZE >>> 1; + var slab = null; + var offset = SIZE; + return function pool_alloc(size) { + if (size < 1 || size > MAX) + return alloc(size); + if (offset + size > SIZE) { + slab = alloc(SIZE); + offset = 0; + } + var buf = slice.call(slab, offset, offset += size); + if (offset & 7) // align to 32 bit + offset = (offset | 7) + 1; + return buf; + }; +} + +},{}],7:[function(require,module,exports){ +"use strict"; + +/** + * A minimal UTF8 implementation for number arrays. + * @memberof util + * @namespace + */ +var utf8 = exports; + +/** + * Calculates the UTF8 byte length of a string. + * @param {string} string String + * @returns {number} Byte length + */ +utf8.length = function utf8_length(string) { + var len = 0, + c = 0; + for (var i = 0; i < string.length; ++i) { + c = string.charCodeAt(i); + if (c < 128) + len += 1; + else if (c < 2048) + len += 2; + else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) { + ++i; + len += 4; + } else + len += 3; + } + return len; +}; + +/** + * Reads UTF8 bytes as a string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} String read + */ +utf8.read = function utf8_read(buffer, start, end) { + var len = end - start; + if (len < 1) + return ""; + var parts = null, + chunk = [], + i = 0, // char offset + t; // temporary + while (start < end) { + t = buffer[start++]; + if (t < 128) + chunk[i++] = t; + else if (t > 191 && t < 224) + chunk[i++] = (t & 31) << 6 | buffer[start++] & 63; + else if (t > 239 && t < 365) { + t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000; + chunk[i++] = 0xD800 + (t >> 10); + chunk[i++] = 0xDC00 + (t & 1023); + } else + chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i = 0; + } + } + if (parts) { + if (i) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i)); +}; + +/** + * Writes a string as UTF8 bytes. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Bytes written + */ +utf8.write = function utf8_write(string, buffer, offset) { + var start = offset, + c1, // character 1 + c2; // character 2 + for (var i = 0; i < string.length; ++i) { + c1 = string.charCodeAt(i); + if (c1 < 128) { + buffer[offset++] = c1; + } else if (c1 < 2048) { + buffer[offset++] = c1 >> 6 | 192; + buffer[offset++] = c1 & 63 | 128; + } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) { + c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF); + ++i; + buffer[offset++] = c1 >> 18 | 240; + buffer[offset++] = c1 >> 12 & 63 | 128; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } else { + buffer[offset++] = c1 >> 12 | 224; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } + } + return offset - start; +}; + +},{}],8:[function(require,module,exports){ +"use strict"; +var protobuf = exports; + +/** + * Build type, one of `"full"`, `"light"` or `"minimal"`. + * @name build + * @type {string} + * @const + */ +protobuf.build = "minimal"; + +// Serialization +protobuf.Writer = require(16); +protobuf.BufferWriter = require(17); +protobuf.Reader = require(9); +protobuf.BufferReader = require(10); + +// Utility +protobuf.util = require(15); +protobuf.rpc = require(12); +protobuf.roots = require(11); +protobuf.configure = configure; + +/* istanbul ignore next */ +/** + * Reconfigures the library according to the environment. + * @returns {undefined} + */ +function configure() { + protobuf.util._configure(); + protobuf.Writer._configure(protobuf.BufferWriter); + protobuf.Reader._configure(protobuf.BufferReader); +} + +// Set up buffer utility according to the environment +configure(); + +},{"10":10,"11":11,"12":12,"15":15,"16":16,"17":17,"9":9}],9:[function(require,module,exports){ +"use strict"; +module.exports = Reader; + +var util = require(15); + +var BufferReader; // cyclic + +var LongBits = util.LongBits, + utf8 = util.utf8; + +/* istanbul ignore next */ +function indexOutOfRange(reader, writeLength) { + return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); +} + +/** + * Constructs a new reader instance using the specified buffer. + * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`. + * @constructor + * @param {Uint8Array} buffer Buffer to read from + */ +function Reader(buffer) { + + /** + * Read buffer. + * @type {Uint8Array} + */ + this.buf = buffer; + + /** + * Read buffer position. + * @type {number} + */ + this.pos = 0; + + /** + * Read buffer length. + * @type {number} + */ + this.len = buffer.length; +} + +var create_array = typeof Uint8Array !== "undefined" + ? function create_typed_array(buffer) { + if (buffer instanceof Uint8Array || Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + } + /* istanbul ignore next */ + : function create_array(buffer) { + if (Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + }; + +var create = function create() { + return util.Buffer + ? function create_buffer_setup(buffer) { + return (Reader.create = function create_buffer(buffer) { + return util.Buffer.isBuffer(buffer) + ? new BufferReader(buffer) + /* istanbul ignore next */ + : create_array(buffer); + })(buffer); + } + /* istanbul ignore next */ + : create_array; +}; + +/** + * Creates a new reader using the specified buffer. + * @function + * @param {Uint8Array|Buffer} buffer Buffer to read from + * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader} + * @throws {Error} If `buffer` is not a valid buffer + */ +Reader.create = create(); + +Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice; + +/** + * Reads a varint as an unsigned 32 bit value. + * @function + * @returns {number} Value read + */ +Reader.prototype.uint32 = (function read_uint32_setup() { + var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!) + return function read_uint32() { + value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value; + + /* istanbul ignore if */ + if ((this.pos += 5) > this.len) { + this.pos = this.len; + throw indexOutOfRange(this, 10); + } + return value; + }; +})(); + +/** + * Reads a varint as a signed 32 bit value. + * @returns {number} Value read + */ +Reader.prototype.int32 = function read_int32() { + return this.uint32() | 0; +}; + +/** + * Reads a zig-zag encoded varint as a signed 32 bit value. + * @returns {number} Value read + */ +Reader.prototype.sint32 = function read_sint32() { + var value = this.uint32(); + return value >>> 1 ^ -(value & 1) | 0; +}; + +/* eslint-disable no-invalid-this */ + +function readLongVarint() { + // tends to deopt with local vars for octet etc. + var bits = new LongBits(0, 0); + var i = 0; + if (this.len - this.pos > 4) { // fast route (lo) + for (; i < 4; ++i) { + // 1st..4th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + // 5th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; + bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + i = 0; + } else { + for (; i < 3; ++i) { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + // 1st..3th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + // 4th + bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0; + return bits; + } + if (this.len - this.pos > 4) { // fast route (hi) + for (; i < 5; ++i) { + // 6th..10th + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } else { + for (; i < 5; ++i) { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + // 6th..10th + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } + /* istanbul ignore next */ + throw Error("invalid varint encoding"); +} + +/* eslint-enable no-invalid-this */ + +/** + * Reads a varint as a signed 64 bit value. + * @name Reader#int64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a varint as an unsigned 64 bit value. + * @name Reader#uint64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a zig-zag encoded varint as a signed 64 bit value. + * @name Reader#sint64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a varint as a boolean. + * @returns {boolean} Value read + */ +Reader.prototype.bool = function read_bool() { + return this.uint32() !== 0; +}; + +function readFixed32_end(buf, end) { // note that this uses `end`, not `pos` + return (buf[end - 4] + | buf[end - 3] << 8 + | buf[end - 2] << 16 + | buf[end - 1] << 24) >>> 0; +} + +/** + * Reads fixed 32 bits as an unsigned 32 bit integer. + * @returns {number} Value read + */ +Reader.prototype.fixed32 = function read_fixed32() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + return readFixed32_end(this.buf, this.pos += 4); +}; + +/** + * Reads fixed 32 bits as a signed 32 bit integer. + * @returns {number} Value read + */ +Reader.prototype.sfixed32 = function read_sfixed32() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + return readFixed32_end(this.buf, this.pos += 4) | 0; +}; + +/* eslint-disable no-invalid-this */ + +function readFixed64(/* this: Reader */) { + + /* istanbul ignore if */ + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 8); + + return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); +} + +/* eslint-enable no-invalid-this */ + +/** + * Reads fixed 64 bits. + * @name Reader#fixed64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads zig-zag encoded fixed 64 bits. + * @name Reader#sfixed64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a float (32 bit) as a number. + * @function + * @returns {number} Value read + */ +Reader.prototype.float = function read_float() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + var value = util.float.readFloatLE(this.buf, this.pos); + this.pos += 4; + return value; +}; + +/** + * Reads a double (64 bit float) as a number. + * @function + * @returns {number} Value read + */ +Reader.prototype.double = function read_double() { + + /* istanbul ignore if */ + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 4); + + var value = util.float.readDoubleLE(this.buf, this.pos); + this.pos += 8; + return value; +}; + +/** + * Reads a sequence of bytes preceeded by its length as a varint. + * @returns {Uint8Array} Value read + */ +Reader.prototype.bytes = function read_bytes() { + var length = this.uint32(), + start = this.pos, + end = this.pos + length; + + /* istanbul ignore if */ + if (end > this.len) + throw indexOutOfRange(this, length); + + this.pos += length; + if (Array.isArray(this.buf)) // plain array + return this.buf.slice(start, end); + + if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1 + var nativeBuffer = util.Buffer; + return nativeBuffer + ? nativeBuffer.alloc(0) + : new this.buf.constructor(0); + } + return this._slice.call(this.buf, start, end); +}; + +/** + * Reads a string preceeded by its byte length as a varint. + * @returns {string} Value read + */ +Reader.prototype.string = function read_string() { + var bytes = this.bytes(); + return utf8.read(bytes, 0, bytes.length); +}; + +/** + * Skips the specified number of bytes if specified, otherwise skips a varint. + * @param {number} [length] Length if known, otherwise a varint is assumed + * @returns {Reader} `this` + */ +Reader.prototype.skip = function skip(length) { + if (typeof length === "number") { + /* istanbul ignore if */ + if (this.pos + length > this.len) + throw indexOutOfRange(this, length); + this.pos += length; + } else { + do { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + } while (this.buf[this.pos++] & 128); + } + return this; +}; + +/** + * Skips the next element of the specified wire type. + * @param {number} wireType Wire type received + * @returns {Reader} `this` + */ +Reader.prototype.skipType = function(wireType) { + switch (wireType) { + case 0: + this.skip(); + break; + case 1: + this.skip(8); + break; + case 2: + this.skip(this.uint32()); + break; + case 3: + while ((wireType = this.uint32() & 7) !== 4) { + this.skipType(wireType); + } + break; + case 5: + this.skip(4); + break; + + /* istanbul ignore next */ + default: + throw Error("invalid wire type " + wireType + " at offset " + this.pos); + } + return this; +}; + +Reader._configure = function(BufferReader_) { + BufferReader = BufferReader_; + Reader.create = create(); + BufferReader._configure(); + + var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber"; + util.merge(Reader.prototype, { + + int64: function read_int64() { + return readLongVarint.call(this)[fn](false); + }, + + uint64: function read_uint64() { + return readLongVarint.call(this)[fn](true); + }, + + sint64: function read_sint64() { + return readLongVarint.call(this).zzDecode()[fn](false); + }, + + fixed64: function read_fixed64() { + return readFixed64.call(this)[fn](true); + }, + + sfixed64: function read_sfixed64() { + return readFixed64.call(this)[fn](false); + } + + }); +}; + +},{"15":15}],10:[function(require,module,exports){ +"use strict"; +module.exports = BufferReader; + +// extends Reader +var Reader = require(9); +(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; + +var util = require(15); + +/** + * Constructs a new buffer reader instance. + * @classdesc Wire format reader using node buffers. + * @extends Reader + * @constructor + * @param {Buffer} buffer Buffer to read from + */ +function BufferReader(buffer) { + Reader.call(this, buffer); + + /** + * Read buffer. + * @name BufferReader#buf + * @type {Buffer} + */ +} + +BufferReader._configure = function () { + /* istanbul ignore else */ + if (util.Buffer) + BufferReader.prototype._slice = util.Buffer.prototype.slice; +}; + + +/** + * @override + */ +BufferReader.prototype.string = function read_string_buffer() { + var len = this.uint32(); // modifies pos + return this.buf.utf8Slice + ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) + : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len)); +}; + +/** + * Reads a sequence of bytes preceeded by its length as a varint. + * @name BufferReader#bytes + * @function + * @returns {Buffer} Value read + */ + +BufferReader._configure(); + +},{"15":15,"9":9}],11:[function(require,module,exports){ +"use strict"; +module.exports = {}; + +/** + * Named roots. + * This is where pbjs stores generated structures (the option `-r, --root` specifies a name). + * Can also be used manually to make roots available across modules. + * @name roots + * @type {Object.} + * @example + * // pbjs -r myroot -o compiled.js ... + * + * // in another module: + * require("./compiled.js"); + * + * // in any subsequent module: + * var root = protobuf.roots["myroot"]; + */ + +},{}],12:[function(require,module,exports){ +"use strict"; + +/** + * Streaming RPC helpers. + * @namespace + */ +var rpc = exports; + +/** + * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets. + * @typedef RPCImpl + * @type {function} + * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called + * @param {Uint8Array} requestData Request data + * @param {RPCImplCallback} callback Callback function + * @returns {undefined} + * @example + * function rpcImpl(method, requestData, callback) { + * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code + * throw Error("no such method"); + * asynchronouslyObtainAResponse(requestData, function(err, responseData) { + * callback(err, responseData); + * }); + * } + */ + +/** + * Node-style callback as used by {@link RPCImpl}. + * @typedef RPCImplCallback + * @type {function} + * @param {Error|null} error Error, if any, otherwise `null` + * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error + * @returns {undefined} + */ + +rpc.Service = require(13); + +},{"13":13}],13:[function(require,module,exports){ +"use strict"; +module.exports = Service; + +var util = require(15); + +// Extends EventEmitter +(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; + +/** + * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}. + * + * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`. + * @typedef rpc.ServiceMethodCallback + * @template TRes extends Message + * @type {function} + * @param {Error|null} error Error, if any + * @param {TRes} [response] Response message + * @returns {undefined} + */ + +/** + * A service method part of a {@link rpc.Service} as created by {@link Service.create}. + * @typedef rpc.ServiceMethod + * @template TReq extends Message + * @template TRes extends Message + * @type {function} + * @param {TReq|Properties} request Request message or plain object + * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message + * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined` + */ + +/** + * Constructs a new RPC service instance. + * @classdesc An RPC service as returned by {@link Service#create}. + * @exports rpc.Service + * @extends util.EventEmitter + * @constructor + * @param {RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ +function Service(rpcImpl, requestDelimited, responseDelimited) { + + if (typeof rpcImpl !== "function") + throw TypeError("rpcImpl must be a function"); + + util.EventEmitter.call(this); + + /** + * RPC implementation. Becomes `null` once the service is ended. + * @type {RPCImpl|null} + */ + this.rpcImpl = rpcImpl; + + /** + * Whether requests are length-delimited. + * @type {boolean} + */ + this.requestDelimited = Boolean(requestDelimited); + + /** + * Whether responses are length-delimited. + * @type {boolean} + */ + this.responseDelimited = Boolean(responseDelimited); +} + +/** + * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}. + * @param {Method|rpc.ServiceMethod} method Reflected or static method + * @param {Constructor} requestCtor Request constructor + * @param {Constructor} responseCtor Response constructor + * @param {TReq|Properties} request Request message or plain object + * @param {rpc.ServiceMethodCallback} callback Service callback + * @returns {undefined} + * @template TReq extends Message + * @template TRes extends Message + */ +Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) { + + if (!request) + throw TypeError("request must be specified"); + + var self = this; + if (!callback) + return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request); + + if (!self.rpcImpl) { + setTimeout(function() { callback(Error("already ended")); }, 0); + return undefined; + } + + try { + return self.rpcImpl( + method, + requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(), + function rpcCallback(err, response) { + + if (err) { + self.emit("error", err, method); + return callback(err); + } + + if (response === null) { + self.end(/* endedByRPC */ true); + return undefined; + } + + if (!(response instanceof responseCtor)) { + try { + response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response); + } catch (err) { + self.emit("error", err, method); + return callback(err); + } + } + + self.emit("data", response, method); + return callback(null, response); + } + ); + } catch (err) { + self.emit("error", err, method); + setTimeout(function() { callback(err); }, 0); + return undefined; + } +}; + +/** + * Ends this service and emits the `end` event. + * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation. + * @returns {rpc.Service} `this` + */ +Service.prototype.end = function end(endedByRPC) { + if (this.rpcImpl) { + if (!endedByRPC) // signal end to rpcImpl + this.rpcImpl(null, null, null); + this.rpcImpl = null; + this.emit("end").off(); + } + return this; +}; + +},{"15":15}],14:[function(require,module,exports){ +"use strict"; +module.exports = LongBits; + +var util = require(15); + +/** + * Constructs new long bits. + * @classdesc Helper class for working with the low and high bits of a 64 bit value. + * @memberof util + * @constructor + * @param {number} lo Low 32 bits, unsigned + * @param {number} hi High 32 bits, unsigned + */ +function LongBits(lo, hi) { + + // note that the casts below are theoretically unnecessary as of today, but older statically + // generated converter code might still call the ctor with signed 32bits. kept for compat. + + /** + * Low bits. + * @type {number} + */ + this.lo = lo >>> 0; + + /** + * High bits. + * @type {number} + */ + this.hi = hi >>> 0; +} + +/** + * Zero bits. + * @memberof util.LongBits + * @type {util.LongBits} + */ +var zero = LongBits.zero = new LongBits(0, 0); + +zero.toNumber = function() { return 0; }; +zero.zzEncode = zero.zzDecode = function() { return this; }; +zero.length = function() { return 1; }; + +/** + * Zero hash. + * @memberof util.LongBits + * @type {string} + */ +var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; + +/** + * Constructs new long bits from the specified number. + * @param {number} value Value + * @returns {util.LongBits} Instance + */ +LongBits.fromNumber = function fromNumber(value) { + if (value === 0) + return zero; + var sign = value < 0; + if (sign) + value = -value; + var lo = value >>> 0, + hi = (value - lo) / 4294967296 >>> 0; + if (sign) { + hi = ~hi >>> 0; + lo = ~lo >>> 0; + if (++lo > 4294967295) { + lo = 0; + if (++hi > 4294967295) + hi = 0; + } + } + return new LongBits(lo, hi); +}; + +/** + * Constructs new long bits from a number, long or string. + * @param {Long|number|string} value Value + * @returns {util.LongBits} Instance + */ +LongBits.from = function from(value) { + if (typeof value === "number") + return LongBits.fromNumber(value); + if (util.isString(value)) { + /* istanbul ignore else */ + if (util.Long) + value = util.Long.fromString(value); + else + return LongBits.fromNumber(parseInt(value, 10)); + } + return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; +}; + +/** + * Converts this long bits to a possibly unsafe JavaScript number. + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {number} Possibly unsafe number + */ +LongBits.prototype.toNumber = function toNumber(unsigned) { + if (!unsigned && this.hi >>> 31) { + var lo = ~this.lo + 1 >>> 0, + hi = ~this.hi >>> 0; + if (!lo) + hi = hi + 1 >>> 0; + return -(lo + hi * 4294967296); + } + return this.lo + this.hi * 4294967296; +}; + +/** + * Converts this long bits to a long. + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {Long} Long + */ +LongBits.prototype.toLong = function toLong(unsigned) { + return util.Long + ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) + /* istanbul ignore next */ + : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; +}; + +var charCodeAt = String.prototype.charCodeAt; + +/** + * Constructs new long bits from the specified 8 characters long hash. + * @param {string} hash Hash + * @returns {util.LongBits} Bits + */ +LongBits.fromHash = function fromHash(hash) { + if (hash === zeroHash) + return zero; + return new LongBits( + ( charCodeAt.call(hash, 0) + | charCodeAt.call(hash, 1) << 8 + | charCodeAt.call(hash, 2) << 16 + | charCodeAt.call(hash, 3) << 24) >>> 0 + , + ( charCodeAt.call(hash, 4) + | charCodeAt.call(hash, 5) << 8 + | charCodeAt.call(hash, 6) << 16 + | charCodeAt.call(hash, 7) << 24) >>> 0 + ); +}; + +/** + * Converts this long bits to a 8 characters long hash. + * @returns {string} Hash + */ +LongBits.prototype.toHash = function toHash() { + return String.fromCharCode( + this.lo & 255, + this.lo >>> 8 & 255, + this.lo >>> 16 & 255, + this.lo >>> 24 , + this.hi & 255, + this.hi >>> 8 & 255, + this.hi >>> 16 & 255, + this.hi >>> 24 + ); +}; + +/** + * Zig-zag encodes this long bits. + * @returns {util.LongBits} `this` + */ +LongBits.prototype.zzEncode = function zzEncode() { + var mask = this.hi >> 31; + this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; + this.lo = ( this.lo << 1 ^ mask) >>> 0; + return this; +}; + +/** + * Zig-zag decodes this long bits. + * @returns {util.LongBits} `this` + */ +LongBits.prototype.zzDecode = function zzDecode() { + var mask = -(this.lo & 1); + this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; + this.hi = ( this.hi >>> 1 ^ mask) >>> 0; + return this; +}; + +/** + * Calculates the length of this longbits when encoded as a varint. + * @returns {number} Length + */ +LongBits.prototype.length = function length() { + var part0 = this.lo, + part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, + part2 = this.hi >>> 24; + return part2 === 0 + ? part1 === 0 + ? part0 < 16384 + ? part0 < 128 ? 1 : 2 + : part0 < 2097152 ? 3 : 4 + : part1 < 16384 + ? part1 < 128 ? 5 : 6 + : part1 < 2097152 ? 7 : 8 + : part2 < 128 ? 9 : 10; +}; + +},{"15":15}],15:[function(require,module,exports){ +"use strict"; +var util = exports; + +// used to return a Promise where callback is omitted +util.asPromise = require(1); + +// converts to / from base64 encoded strings +util.base64 = require(2); + +// base class of rpc.Service +util.EventEmitter = require(3); + +// float handling accross browsers +util.float = require(4); + +// requires modules optionally and hides the call from bundlers +util.inquire = require(5); + +// converts to / from utf8 encoded strings +util.utf8 = require(7); + +// provides a node-like buffer pool in the browser +util.pool = require(6); + +// utility to work with the low and high bits of a 64 bit value +util.LongBits = require(14); + +/** + * Whether running within node or not. + * @memberof util + * @type {boolean} + */ +util.isNode = Boolean(typeof global !== "undefined" + && global + && global.process + && global.process.versions + && global.process.versions.node); + +/** + * Global object reference. + * @memberof util + * @type {Object} + */ +util.global = util.isNode && global + || typeof window !== "undefined" && window + || typeof self !== "undefined" && self + || this; // eslint-disable-line no-invalid-this + +/** + * An immuable empty array. + * @memberof util + * @type {Array.<*>} + * @const + */ +util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes + +/** + * An immutable empty object. + * @type {Object} + * @const + */ +util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes + +/** + * Tests if the specified value is an integer. + * @function + * @param {*} value Value to test + * @returns {boolean} `true` if the value is an integer + */ +util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) { + return typeof value === "number" && isFinite(value) && Math.floor(value) === value; +}; + +/** + * Tests if the specified value is a string. + * @param {*} value Value to test + * @returns {boolean} `true` if the value is a string + */ +util.isString = function isString(value) { + return typeof value === "string" || value instanceof String; +}; + +/** + * Tests if the specified value is a non-null object. + * @param {*} value Value to test + * @returns {boolean} `true` if the value is a non-null object + */ +util.isObject = function isObject(value) { + return value && typeof value === "object"; +}; + +/** + * Checks if a property on a message is considered to be present. + * This is an alias of {@link util.isSet}. + * @function + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ +util.isset = + +/** + * Checks if a property on a message is considered to be present. + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ +util.isSet = function isSet(obj, prop) { + var value = obj[prop]; + if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins + return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; + return false; +}; + +/** + * Any compatible Buffer instance. + * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings. + * @interface Buffer + * @extends Uint8Array + */ + +/** + * Node's Buffer class if available. + * @type {Constructor} + */ +util.Buffer = (function() { + try { + var Buffer = util.inquire("buffer").Buffer; + // refuse to use non-node buffers if not explicitly assigned (perf reasons): + return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null; + } catch (e) { + /* istanbul ignore next */ + return null; + } +})(); + +// Internal alias of or polyfull for Buffer.from. +util._Buffer_from = null; + +// Internal alias of or polyfill for Buffer.allocUnsafe. +util._Buffer_allocUnsafe = null; + +/** + * Creates a new buffer of whatever type supported by the environment. + * @param {number|number[]} [sizeOrArray=0] Buffer size or number array + * @returns {Uint8Array|Buffer} Buffer + */ +util.newBuffer = function newBuffer(sizeOrArray) { + /* istanbul ignore next */ + return typeof sizeOrArray === "number" + ? util.Buffer + ? util._Buffer_allocUnsafe(sizeOrArray) + : new util.Array(sizeOrArray) + : util.Buffer + ? util._Buffer_from(sizeOrArray) + : typeof Uint8Array === "undefined" + ? sizeOrArray + : new Uint8Array(sizeOrArray); +}; + +/** + * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`. + * @type {Constructor} + */ +util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array; + +/** + * Any compatible Long instance. + * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js. + * @interface Long + * @property {number} low Low bits + * @property {number} high High bits + * @property {boolean} unsigned Whether unsigned or not + */ + +/** + * Long.js's Long class if available. + * @type {Constructor} + */ +util.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long + || /* istanbul ignore next */ util.global.Long + || util.inquire("long"); + +/** + * Regular expression used to verify 2 bit (`bool`) map keys. + * @type {RegExp} + * @const + */ +util.key2Re = /^true|false|0|1$/; + +/** + * Regular expression used to verify 32 bit (`int32` etc.) map keys. + * @type {RegExp} + * @const + */ +util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; + +/** + * Regular expression used to verify 64 bit (`int64` etc.) map keys. + * @type {RegExp} + * @const + */ +util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; + +/** + * Converts a number or long to an 8 characters long hash string. + * @param {Long|number} value Value to convert + * @returns {string} Hash + */ +util.longToHash = function longToHash(value) { + return value + ? util.LongBits.from(value).toHash() + : util.LongBits.zeroHash; +}; + +/** + * Converts an 8 characters long hash string to a long or number. + * @param {string} hash Hash + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {Long|number} Original value + */ +util.longFromHash = function longFromHash(hash, unsigned) { + var bits = util.LongBits.fromHash(hash); + if (util.Long) + return util.Long.fromBits(bits.lo, bits.hi, unsigned); + return bits.toNumber(Boolean(unsigned)); +}; + +/** + * Merges the properties of the source object into the destination object. + * @memberof util + * @param {Object.} dst Destination object + * @param {Object.} src Source object + * @param {boolean} [ifNotSet=false] Merges only if the key is not already set + * @returns {Object.} Destination object + */ +function merge(dst, src, ifNotSet) { // used by converters + for (var keys = Object.keys(src), i = 0; i < keys.length; ++i) + if (dst[keys[i]] === undefined || !ifNotSet) + dst[keys[i]] = src[keys[i]]; + return dst; +} + +util.merge = merge; + +/** + * Converts the first character of a string to lower case. + * @param {string} str String to convert + * @returns {string} Converted string + */ +util.lcFirst = function lcFirst(str) { + return str.charAt(0).toLowerCase() + str.substring(1); +}; + +/** + * Creates a custom error constructor. + * @memberof util + * @param {string} name Error name + * @returns {Constructor} Custom error constructor + */ +function newError(name) { + + function CustomError(message, properties) { + + if (!(this instanceof CustomError)) + return new CustomError(message, properties); + + // Error.call(this, message); + // ^ just returns a new error instance because the ctor can be called as a function + + Object.defineProperty(this, "message", { get: function() { return message; } }); + + /* istanbul ignore next */ + if (Error.captureStackTrace) // node + Error.captureStackTrace(this, CustomError); + else + Object.defineProperty(this, "stack", { value: new Error().stack || "" }); + + if (properties) + merge(this, properties); + } + + CustomError.prototype = Object.create(Error.prototype, { + constructor: { + value: CustomError, + writable: true, + enumerable: false, + configurable: true, + }, + name: { + get: function get() { return name; }, + set: undefined, + enumerable: false, + // configurable: false would accurately preserve the behavior of + // the original, but I'm guessing that was not intentional. + // For an actual error subclass, this property would + // be configurable. + configurable: true, + }, + toString: { + value: function value() { return this.name + ": " + this.message; }, + writable: true, + enumerable: false, + configurable: true, + }, + }); + + return CustomError; +} + +util.newError = newError; + +/** + * Constructs a new protocol error. + * @classdesc Error subclass indicating a protocol specifc error. + * @memberof util + * @extends Error + * @template T extends Message + * @constructor + * @param {string} message Error message + * @param {Object.} [properties] Additional properties + * @example + * try { + * MyMessage.decode(someBuffer); // throws if required fields are missing + * } catch (e) { + * if (e instanceof ProtocolError && e.instance) + * console.log("decoded so far: " + JSON.stringify(e.instance)); + * } + */ +util.ProtocolError = newError("ProtocolError"); + +/** + * So far decoded message instance. + * @name util.ProtocolError#instance + * @type {Message} + */ + +/** + * A OneOf getter as returned by {@link util.oneOfGetter}. + * @typedef OneOfGetter + * @type {function} + * @returns {string|undefined} Set field name, if any + */ + +/** + * Builds a getter for a oneof's present field name. + * @param {string[]} fieldNames Field names + * @returns {OneOfGetter} Unbound getter + */ +util.oneOfGetter = function getOneOf(fieldNames) { + var fieldMap = {}; + for (var i = 0; i < fieldNames.length; ++i) + fieldMap[fieldNames[i]] = 1; + + /** + * @returns {string|undefined} Set field name, if any + * @this Object + * @ignore + */ + return function() { // eslint-disable-line consistent-return + for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i) + if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null) + return keys[i]; + }; +}; + +/** + * A OneOf setter as returned by {@link util.oneOfSetter}. + * @typedef OneOfSetter + * @type {function} + * @param {string|undefined} value Field name + * @returns {undefined} + */ + +/** + * Builds a setter for a oneof's present field name. + * @param {string[]} fieldNames Field names + * @returns {OneOfSetter} Unbound setter + */ +util.oneOfSetter = function setOneOf(fieldNames) { + + /** + * @param {string} name Field name + * @returns {undefined} + * @this Object + * @ignore + */ + return function(name) { + for (var i = 0; i < fieldNames.length; ++i) + if (fieldNames[i] !== name) + delete this[fieldNames[i]]; + }; +}; + +/** + * Default conversion options used for {@link Message#toJSON} implementations. + * + * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely: + * + * - Longs become strings + * - Enums become string keys + * - Bytes become base64 encoded strings + * - (Sub-)Messages become plain objects + * - Maps become plain objects with all string keys + * - Repeated fields become arrays + * - NaN and Infinity for float and double fields become strings + * + * @type {IConversionOptions} + * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json + */ +util.toJSONOptions = { + longs: String, + enums: String, + bytes: String, + json: true +}; + +// Sets up buffer utility according to the environment (called in index-minimal) +util._configure = function() { + var Buffer = util.Buffer; + /* istanbul ignore if */ + if (!Buffer) { + util._Buffer_from = util._Buffer_allocUnsafe = null; + return; + } + // because node 4.x buffers are incompatible & immutable + // see: https://github.com/dcodeIO/protobuf.js/pull/665 + util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from || + /* istanbul ignore next */ + function Buffer_from(value, encoding) { + return new Buffer(value, encoding); + }; + util._Buffer_allocUnsafe = Buffer.allocUnsafe || + /* istanbul ignore next */ + function Buffer_allocUnsafe(size) { + return new Buffer(size); + }; +}; + +},{"1":1,"14":14,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7}],16:[function(require,module,exports){ +"use strict"; +module.exports = Writer; + +var util = require(15); + +var BufferWriter; // cyclic + +var LongBits = util.LongBits, + base64 = util.base64, + utf8 = util.utf8; + +/** + * Constructs a new writer operation instance. + * @classdesc Scheduled writer operation. + * @constructor + * @param {function(*, Uint8Array, number)} fn Function to call + * @param {number} len Value byte length + * @param {*} val Value to write + * @ignore + */ +function Op(fn, len, val) { + + /** + * Function to call. + * @type {function(Uint8Array, number, *)} + */ + this.fn = fn; + + /** + * Value byte length. + * @type {number} + */ + this.len = len; + + /** + * Next operation. + * @type {Writer.Op|undefined} + */ + this.next = undefined; + + /** + * Value to write. + * @type {*} + */ + this.val = val; // type varies +} + +/* istanbul ignore next */ +function noop() {} // eslint-disable-line no-empty-function + +/** + * Constructs a new writer state instance. + * @classdesc Copied writer state. + * @memberof Writer + * @constructor + * @param {Writer} writer Writer to copy state from + * @ignore + */ +function State(writer) { + + /** + * Current head. + * @type {Writer.Op} + */ + this.head = writer.head; + + /** + * Current tail. + * @type {Writer.Op} + */ + this.tail = writer.tail; + + /** + * Current buffer length. + * @type {number} + */ + this.len = writer.len; + + /** + * Next state. + * @type {State|null} + */ + this.next = writer.states; +} + +/** + * Constructs a new writer instance. + * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`. + * @constructor + */ +function Writer() { + + /** + * Current length. + * @type {number} + */ + this.len = 0; + + /** + * Operations head. + * @type {Object} + */ + this.head = new Op(noop, 0, 0); + + /** + * Operations tail + * @type {Object} + */ + this.tail = this.head; + + /** + * Linked forked states. + * @type {Object|null} + */ + this.states = null; + + // When a value is written, the writer calculates its byte length and puts it into a linked + // list of operations to perform when finish() is called. This both allows us to allocate + // buffers of the exact required size and reduces the amount of work we have to do compared + // to first calculating over objects and then encoding over objects. In our case, the encoding + // part is just a linked list walk calling operations with already prepared values. +} + +var create = function create() { + return util.Buffer + ? function create_buffer_setup() { + return (Writer.create = function create_buffer() { + return new BufferWriter(); + })(); + } + /* istanbul ignore next */ + : function create_array() { + return new Writer(); + }; +}; + +/** + * Creates a new writer. + * @function + * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer} + */ +Writer.create = create(); + +/** + * Allocates a buffer of the specified size. + * @param {number} size Buffer size + * @returns {Uint8Array} Buffer + */ +Writer.alloc = function alloc(size) { + return new util.Array(size); +}; + +// Use Uint8Array buffer pool in the browser, just like node does with buffers +/* istanbul ignore else */ +if (util.Array !== Array) + Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray); + +/** + * Pushes a new operation to the queue. + * @param {function(Uint8Array, number, *)} fn Function to call + * @param {number} len Value byte length + * @param {number} val Value to write + * @returns {Writer} `this` + * @private + */ +Writer.prototype._push = function push(fn, len, val) { + this.tail = this.tail.next = new Op(fn, len, val); + this.len += len; + return this; +}; + +function writeByte(val, buf, pos) { + buf[pos] = val & 255; +} + +function writeVarint32(val, buf, pos) { + while (val > 127) { + buf[pos++] = val & 127 | 128; + val >>>= 7; + } + buf[pos] = val; +} + +/** + * Constructs a new varint writer operation instance. + * @classdesc Scheduled varint writer operation. + * @extends Op + * @constructor + * @param {number} len Value byte length + * @param {number} val Value to write + * @ignore + */ +function VarintOp(len, val) { + this.len = len; + this.next = undefined; + this.val = val; +} + +VarintOp.prototype = Object.create(Op.prototype); +VarintOp.prototype.fn = writeVarint32; + +/** + * Writes an unsigned 32 bit value as a varint. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.uint32 = function write_uint32(value) { + // here, the call to this.push has been inlined and a varint specific Op subclass is used. + // uint32 is by far the most frequently used operation and benefits significantly from this. + this.len += (this.tail = this.tail.next = new VarintOp( + (value = value >>> 0) + < 128 ? 1 + : value < 16384 ? 2 + : value < 2097152 ? 3 + : value < 268435456 ? 4 + : 5, + value)).len; + return this; +}; + +/** + * Writes a signed 32 bit value as a varint. + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.int32 = function write_int32(value) { + return value < 0 + ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec + : this.uint32(value); +}; + +/** + * Writes a 32 bit value as a varint, zig-zag encoded. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.sint32 = function write_sint32(value) { + return this.uint32((value << 1 ^ value >> 31) >>> 0); +}; + +function writeVarint64(val, buf, pos) { + while (val.hi) { + buf[pos++] = val.lo & 127 | 128; + val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; + val.hi >>>= 7; + } + while (val.lo > 127) { + buf[pos++] = val.lo & 127 | 128; + val.lo = val.lo >>> 7; + } + buf[pos++] = val.lo; +} + +/** + * Writes an unsigned 64 bit value as a varint. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.uint64 = function write_uint64(value) { + var bits = LongBits.from(value); + return this._push(writeVarint64, bits.length(), bits); +}; + +/** + * Writes a signed 64 bit value as a varint. + * @function + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.int64 = Writer.prototype.uint64; + +/** + * Writes a signed 64 bit value as a varint, zig-zag encoded. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.sint64 = function write_sint64(value) { + var bits = LongBits.from(value).zzEncode(); + return this._push(writeVarint64, bits.length(), bits); +}; + +/** + * Writes a boolish value as a varint. + * @param {boolean} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.bool = function write_bool(value) { + return this._push(writeByte, 1, value ? 1 : 0); +}; + +function writeFixed32(val, buf, pos) { + buf[pos ] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; +} + +/** + * Writes an unsigned 32 bit value as fixed 32 bits. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.fixed32 = function write_fixed32(value) { + return this._push(writeFixed32, 4, value >>> 0); +}; + +/** + * Writes a signed 32 bit value as fixed 32 bits. + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.sfixed32 = Writer.prototype.fixed32; + +/** + * Writes an unsigned 64 bit value as fixed 64 bits. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.fixed64 = function write_fixed64(value) { + var bits = LongBits.from(value); + return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); +}; + +/** + * Writes a signed 64 bit value as fixed 64 bits. + * @function + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.sfixed64 = Writer.prototype.fixed64; + +/** + * Writes a float (32 bit). + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.float = function write_float(value) { + return this._push(util.float.writeFloatLE, 4, value); +}; + +/** + * Writes a double (64 bit float). + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.double = function write_double(value) { + return this._push(util.float.writeDoubleLE, 8, value); +}; + +var writeBytes = util.Array.prototype.set + ? function writeBytes_set(val, buf, pos) { + buf.set(val, pos); // also works for plain array values + } + /* istanbul ignore next */ + : function writeBytes_for(val, buf, pos) { + for (var i = 0; i < val.length; ++i) + buf[pos + i] = val[i]; + }; + +/** + * Writes a sequence of bytes. + * @param {Uint8Array|string} value Buffer or base64 encoded string to write + * @returns {Writer} `this` + */ +Writer.prototype.bytes = function write_bytes(value) { + var len = value.length >>> 0; + if (!len) + return this._push(writeByte, 1, 0); + if (util.isString(value)) { + var buf = Writer.alloc(len = base64.length(value)); + base64.decode(value, buf, 0); + value = buf; + } + return this.uint32(len)._push(writeBytes, len, value); +}; + +/** + * Writes a string. + * @param {string} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.string = function write_string(value) { + var len = utf8.length(value); + return len + ? this.uint32(len)._push(utf8.write, len, value) + : this._push(writeByte, 1, 0); +}; + +/** + * Forks this writer's state by pushing it to a stack. + * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state. + * @returns {Writer} `this` + */ +Writer.prototype.fork = function fork() { + this.states = new State(this); + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + return this; +}; + +/** + * Resets this instance to the last state. + * @returns {Writer} `this` + */ +Writer.prototype.reset = function reset() { + if (this.states) { + this.head = this.states.head; + this.tail = this.states.tail; + this.len = this.states.len; + this.states = this.states.next; + } else { + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + } + return this; +}; + +/** + * Resets to the last state and appends the fork state's current write length as a varint followed by its operations. + * @returns {Writer} `this` + */ +Writer.prototype.ldelim = function ldelim() { + var head = this.head, + tail = this.tail, + len = this.len; + this.reset().uint32(len); + if (len) { + this.tail.next = head.next; // skip noop + this.tail = tail; + this.len += len; + } + return this; +}; + +/** + * Finishes the write operation. + * @returns {Uint8Array} Finished buffer + */ +Writer.prototype.finish = function finish() { + var head = this.head.next, // skip noop + buf = this.constructor.alloc(this.len), + pos = 0; + while (head) { + head.fn(head.val, buf, pos); + pos += head.len; + head = head.next; + } + // this.head = this.tail = null; + return buf; +}; + +Writer._configure = function(BufferWriter_) { + BufferWriter = BufferWriter_; + Writer.create = create(); + BufferWriter._configure(); +}; + +},{"15":15}],17:[function(require,module,exports){ +"use strict"; +module.exports = BufferWriter; + +// extends Writer +var Writer = require(16); +(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; + +var util = require(15); + +/** + * Constructs a new buffer writer instance. + * @classdesc Wire format writer using node buffers. + * @extends Writer + * @constructor + */ +function BufferWriter() { + Writer.call(this); +} + +BufferWriter._configure = function () { + /** + * Allocates a buffer of the specified size. + * @function + * @param {number} size Buffer size + * @returns {Buffer} Buffer + */ + BufferWriter.alloc = util._Buffer_allocUnsafe; + + BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set" + ? function writeBytesBuffer_set(val, buf, pos) { + buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited) + // also works for plain array values + } + /* istanbul ignore next */ + : function writeBytesBuffer_copy(val, buf, pos) { + if (val.copy) // Buffer values + val.copy(buf, pos, 0, val.length); + else for (var i = 0; i < val.length;) // plain array values + buf[pos++] = val[i++]; + }; +}; + + +/** + * @override + */ +BufferWriter.prototype.bytes = function write_bytes_buffer(value) { + if (util.isString(value)) + value = util._Buffer_from(value, "base64"); + var len = value.length >>> 0; + this.uint32(len); + if (len) + this._push(BufferWriter.writeBytesBuffer, len, value); + return this; +}; + +function writeStringBuffer(val, buf, pos) { + if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions) + util.utf8.write(val, buf, pos); + else if (buf.utf8Write) + buf.utf8Write(val, pos); + else + buf.write(val, pos); +} + +/** + * @override + */ +BufferWriter.prototype.string = function write_string_buffer(value) { + var len = util.Buffer.byteLength(value); + this.uint32(len); + if (len) + this._push(writeStringBuffer, len, value); + return this; +}; + + +/** + * Finishes the write operation. + * @name BufferWriter#finish + * @function + * @returns {Buffer} Finished buffer + */ + +BufferWriter._configure(); + +},{"15":15,"16":16}]},{},[8]) + +})(); +//# sourceMappingURL=protobuf.js.map diff --git a/node_modules/protobufjs/dist/minimal/protobuf.js.map b/node_modules/protobufjs/dist/minimal/protobuf.js.map new file mode 100644 index 0000000..e9dfbe7 --- /dev/null +++ b/node_modules/protobufjs/dist/minimal/protobuf.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["lib/prelude.js","../node_modules/@protobufjs/aspromise/index.js","../node_modules/@protobufjs/base64/index.js","../node_modules/@protobufjs/eventemitter/index.js","../node_modules/@protobufjs/float/index.js","../node_modules/@protobufjs/inquire/index.js","../node_modules/@protobufjs/pool/index.js","../node_modules/@protobufjs/utf8/index.js","../src/index-minimal","../src/reader.js","../src/reader_buffer.js","../src/roots.js","../src/rpc.js","../src/rpc/service.js","../src/util/longbits.js","../src/util/minimal.js","../src/writer.js","../src/writer_buffer.js"],"names":[],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/UA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"protobuf.js","sourcesContent":["(function prelude(modules, cache, entries) {\n\n // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS\n // sources through a conflict-free require shim and is again wrapped within an iife that\n // provides a minification-friendly `undefined` var plus a global \"use strict\" directive\n // so that minification can remove the directives of each module.\n\n function $require(name) {\n var $module = cache[name];\n if (!$module)\n modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports);\n return $module.exports;\n }\n\n var protobuf = $require(entries[0]);\n\n // Expose globally\n protobuf.util.global.protobuf = protobuf;\n\n // Be nice to AMD\n if (typeof define === \"function\" && define.amd)\n define([\"long\"], function(Long) {\n if (Long && Long.isLong) {\n protobuf.util.Long = Long;\n protobuf.configure();\n }\n return protobuf;\n });\n\n // Be nice to CommonJS\n if (typeof module === \"object\" && module && module.exports)\n module.exports = protobuf;\n\n})/* end of prelude */","\"use strict\";\r\nmodule.exports = asPromise;\r\n\r\n/**\r\n * Callback as used by {@link util.asPromise}.\r\n * @typedef asPromiseCallback\r\n * @type {function}\r\n * @param {Error|null} error Error, if any\r\n * @param {...*} params Additional arguments\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Returns a promise from a node-style callback function.\r\n * @memberof util\r\n * @param {asPromiseCallback} fn Function to call\r\n * @param {*} ctx Function context\r\n * @param {...*} params Function arguments\r\n * @returns {Promise<*>} Promisified function\r\n */\r\nfunction asPromise(fn, ctx/*, varargs */) {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0,\r\n index = 2,\r\n pending = true;\r\n while (index < arguments.length)\r\n params[offset++] = arguments[index++];\r\n return new Promise(function executor(resolve, reject) {\r\n params[offset] = function callback(err/*, varargs */) {\r\n if (pending) {\r\n pending = false;\r\n if (err)\r\n reject(err);\r\n else {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0;\r\n while (offset < params.length)\r\n params[offset++] = arguments[offset];\r\n resolve.apply(null, params);\r\n }\r\n }\r\n };\r\n try {\r\n fn.apply(ctx || null, params);\r\n } catch (err) {\r\n if (pending) {\r\n pending = false;\r\n reject(err);\r\n }\r\n }\r\n });\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal base64 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar base64 = exports;\r\n\r\n/**\r\n * Calculates the byte length of a base64 encoded string.\r\n * @param {string} string Base64 encoded string\r\n * @returns {number} Byte length\r\n */\r\nbase64.length = function length(string) {\r\n var p = string.length;\r\n if (!p)\r\n return 0;\r\n var n = 0;\r\n while (--p % 4 > 1 && string.charAt(p) === \"=\")\r\n ++n;\r\n return Math.ceil(string.length * 3) / 4 - n;\r\n};\r\n\r\n// Base64 encoding table\r\nvar b64 = new Array(64);\r\n\r\n// Base64 decoding table\r\nvar s64 = new Array(123);\r\n\r\n// 65..90, 97..122, 48..57, 43, 47\r\nfor (var i = 0; i < 64;)\r\n s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;\r\n\r\n/**\r\n * Encodes a buffer to a base64 encoded string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} Base64 encoded string\r\n */\r\nbase64.encode = function encode(buffer, start, end) {\r\n var parts = null,\r\n chunk = [];\r\n var i = 0, // output index\r\n j = 0, // goto index\r\n t; // temporary\r\n while (start < end) {\r\n var b = buffer[start++];\r\n switch (j) {\r\n case 0:\r\n chunk[i++] = b64[b >> 2];\r\n t = (b & 3) << 4;\r\n j = 1;\r\n break;\r\n case 1:\r\n chunk[i++] = b64[t | b >> 4];\r\n t = (b & 15) << 2;\r\n j = 2;\r\n break;\r\n case 2:\r\n chunk[i++] = b64[t | b >> 6];\r\n chunk[i++] = b64[b & 63];\r\n j = 0;\r\n break;\r\n }\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (j) {\r\n chunk[i++] = b64[t];\r\n chunk[i++] = 61;\r\n if (j === 1)\r\n chunk[i++] = 61;\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\nvar invalidEncoding = \"invalid encoding\";\r\n\r\n/**\r\n * Decodes a base64 encoded string to a buffer.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Number of bytes written\r\n * @throws {Error} If encoding is invalid\r\n */\r\nbase64.decode = function decode(string, buffer, offset) {\r\n var start = offset;\r\n var j = 0, // goto index\r\n t; // temporary\r\n for (var i = 0; i < string.length;) {\r\n var c = string.charCodeAt(i++);\r\n if (c === 61 && j > 1)\r\n break;\r\n if ((c = s64[c]) === undefined)\r\n throw Error(invalidEncoding);\r\n switch (j) {\r\n case 0:\r\n t = c;\r\n j = 1;\r\n break;\r\n case 1:\r\n buffer[offset++] = t << 2 | (c & 48) >> 4;\r\n t = c;\r\n j = 2;\r\n break;\r\n case 2:\r\n buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;\r\n t = c;\r\n j = 3;\r\n break;\r\n case 3:\r\n buffer[offset++] = (t & 3) << 6 | c;\r\n j = 0;\r\n break;\r\n }\r\n }\r\n if (j === 1)\r\n throw Error(invalidEncoding);\r\n return offset - start;\r\n};\r\n\r\n/**\r\n * Tests if the specified string appears to be base64 encoded.\r\n * @param {string} string String to test\r\n * @returns {boolean} `true` if probably base64 encoded, otherwise false\r\n */\r\nbase64.test = function test(string) {\r\n return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);\r\n};\r\n","\"use strict\";\r\nmodule.exports = EventEmitter;\r\n\r\n/**\r\n * Constructs a new event emitter instance.\r\n * @classdesc A minimal event emitter.\r\n * @memberof util\r\n * @constructor\r\n */\r\nfunction EventEmitter() {\r\n\r\n /**\r\n * Registered listeners.\r\n * @type {Object.}\r\n * @private\r\n */\r\n this._listeners = {};\r\n}\r\n\r\n/**\r\n * Registers an event listener.\r\n * @param {string} evt Event name\r\n * @param {function} fn Listener\r\n * @param {*} [ctx] Listener context\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.on = function on(evt, fn, ctx) {\r\n (this._listeners[evt] || (this._listeners[evt] = [])).push({\r\n fn : fn,\r\n ctx : ctx || this\r\n });\r\n return this;\r\n};\r\n\r\n/**\r\n * Removes an event listener or any matching listeners if arguments are omitted.\r\n * @param {string} [evt] Event name. Removes all listeners if omitted.\r\n * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.off = function off(evt, fn) {\r\n if (evt === undefined)\r\n this._listeners = {};\r\n else {\r\n if (fn === undefined)\r\n this._listeners[evt] = [];\r\n else {\r\n var listeners = this._listeners[evt];\r\n for (var i = 0; i < listeners.length;)\r\n if (listeners[i].fn === fn)\r\n listeners.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emits an event by calling its listeners with the specified arguments.\r\n * @param {string} evt Event name\r\n * @param {...*} args Arguments\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.emit = function emit(evt) {\r\n var listeners = this._listeners[evt];\r\n if (listeners) {\r\n var args = [],\r\n i = 1;\r\n for (; i < arguments.length;)\r\n args.push(arguments[i++]);\r\n for (i = 0; i < listeners.length;)\r\n listeners[i].fn.apply(listeners[i++].ctx, args);\r\n }\r\n return this;\r\n};\r\n","\"use strict\";\r\n\r\nmodule.exports = factory(factory);\r\n\r\n/**\r\n * Reads / writes floats / doubles from / to buffers.\r\n * @name util.float\r\n * @namespace\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using little endian byte order.\r\n * @name util.float.writeFloatLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using big endian byte order.\r\n * @name util.float.writeFloatBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using little endian byte order.\r\n * @name util.float.readFloatLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using big endian byte order.\r\n * @name util.float.readFloatBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using little endian byte order.\r\n * @name util.float.writeDoubleLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using big endian byte order.\r\n * @name util.float.writeDoubleBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using little endian byte order.\r\n * @name util.float.readDoubleLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using big endian byte order.\r\n * @name util.float.readDoubleBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n// Factory function for the purpose of node-based testing in modified global environments\r\nfunction factory(exports) {\r\n\r\n // float: typed array\r\n if (typeof Float32Array !== \"undefined\") (function() {\r\n\r\n var f32 = new Float32Array([ -0 ]),\r\n f8b = new Uint8Array(f32.buffer),\r\n le = f8b[3] === 128;\r\n\r\n function writeFloat_f32_cpy(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n }\r\n\r\n function writeFloat_f32_rev(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[3];\r\n buf[pos + 1] = f8b[2];\r\n buf[pos + 2] = f8b[1];\r\n buf[pos + 3] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;\r\n\r\n function readFloat_f32_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n function readFloat_f32_rev(buf, pos) {\r\n f8b[3] = buf[pos ];\r\n f8b[2] = buf[pos + 1];\r\n f8b[1] = buf[pos + 2];\r\n f8b[0] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;\r\n\r\n // float: ieee754\r\n })(); else (function() {\r\n\r\n function writeFloat_ieee754(writeUint, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0)\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);\r\n else if (isNaN(val))\r\n writeUint(2143289344, buf, pos);\r\n else if (val > 3.4028234663852886e+38) // +-Infinity\r\n writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);\r\n else if (val < 1.1754943508222875e-38) // denormal\r\n writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);\r\n else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2),\r\n mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;\r\n writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);\r\n }\r\n }\r\n\r\n exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);\r\n exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);\r\n\r\n function readFloat_ieee754(readUint, buf, pos) {\r\n var uint = readUint(buf, pos),\r\n sign = (uint >> 31) * 2 + 1,\r\n exponent = uint >>> 23 & 255,\r\n mantissa = uint & 8388607;\r\n return exponent === 255\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 1.401298464324817e-45 * mantissa\r\n : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);\r\n }\r\n\r\n exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);\r\n exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);\r\n\r\n })();\r\n\r\n // double: typed array\r\n if (typeof Float64Array !== \"undefined\") (function() {\r\n\r\n var f64 = new Float64Array([-0]),\r\n f8b = new Uint8Array(f64.buffer),\r\n le = f8b[7] === 128;\r\n\r\n function writeDouble_f64_cpy(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n buf[pos + 4] = f8b[4];\r\n buf[pos + 5] = f8b[5];\r\n buf[pos + 6] = f8b[6];\r\n buf[pos + 7] = f8b[7];\r\n }\r\n\r\n function writeDouble_f64_rev(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[7];\r\n buf[pos + 1] = f8b[6];\r\n buf[pos + 2] = f8b[5];\r\n buf[pos + 3] = f8b[4];\r\n buf[pos + 4] = f8b[3];\r\n buf[pos + 5] = f8b[2];\r\n buf[pos + 6] = f8b[1];\r\n buf[pos + 7] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;\r\n\r\n function readDouble_f64_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n f8b[4] = buf[pos + 4];\r\n f8b[5] = buf[pos + 5];\r\n f8b[6] = buf[pos + 6];\r\n f8b[7] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n function readDouble_f64_rev(buf, pos) {\r\n f8b[7] = buf[pos ];\r\n f8b[6] = buf[pos + 1];\r\n f8b[5] = buf[pos + 2];\r\n f8b[4] = buf[pos + 3];\r\n f8b[3] = buf[pos + 4];\r\n f8b[2] = buf[pos + 5];\r\n f8b[1] = buf[pos + 6];\r\n f8b[0] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;\r\n\r\n // double: ieee754\r\n })(); else (function() {\r\n\r\n function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);\r\n } else if (isNaN(val)) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(2146959360, buf, pos + off1);\r\n } else if (val > 1.7976931348623157e+308) { // +-Infinity\r\n writeUint(0, buf, pos + off0);\r\n writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);\r\n } else {\r\n var mantissa;\r\n if (val < 2.2250738585072014e-308) { // denormal\r\n mantissa = val / 5e-324;\r\n writeUint(mantissa >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);\r\n } else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2);\r\n if (exponent === 1024)\r\n exponent = 1023;\r\n mantissa = val * Math.pow(2, -exponent);\r\n writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);\r\n }\r\n }\r\n }\r\n\r\n exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);\r\n exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);\r\n\r\n function readDouble_ieee754(readUint, off0, off1, buf, pos) {\r\n var lo = readUint(buf, pos + off0),\r\n hi = readUint(buf, pos + off1);\r\n var sign = (hi >> 31) * 2 + 1,\r\n exponent = hi >>> 20 & 2047,\r\n mantissa = 4294967296 * (hi & 1048575) + lo;\r\n return exponent === 2047\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 5e-324 * mantissa\r\n : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);\r\n }\r\n\r\n exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);\r\n exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);\r\n\r\n })();\r\n\r\n return exports;\r\n}\r\n\r\n// uint helpers\r\n\r\nfunction writeUintLE(val, buf, pos) {\r\n buf[pos ] = val & 255;\r\n buf[pos + 1] = val >>> 8 & 255;\r\n buf[pos + 2] = val >>> 16 & 255;\r\n buf[pos + 3] = val >>> 24;\r\n}\r\n\r\nfunction writeUintBE(val, buf, pos) {\r\n buf[pos ] = val >>> 24;\r\n buf[pos + 1] = val >>> 16 & 255;\r\n buf[pos + 2] = val >>> 8 & 255;\r\n buf[pos + 3] = val & 255;\r\n}\r\n\r\nfunction readUintLE(buf, pos) {\r\n return (buf[pos ]\r\n | buf[pos + 1] << 8\r\n | buf[pos + 2] << 16\r\n | buf[pos + 3] << 24) >>> 0;\r\n}\r\n\r\nfunction readUintBE(buf, pos) {\r\n return (buf[pos ] << 24\r\n | buf[pos + 1] << 16\r\n | buf[pos + 2] << 8\r\n | buf[pos + 3]) >>> 0;\r\n}\r\n","\"use strict\";\r\nmodule.exports = inquire;\r\n\r\n/**\r\n * Requires a module only if available.\r\n * @memberof util\r\n * @param {string} moduleName Module to require\r\n * @returns {?Object} Required module if available and not empty, otherwise `null`\r\n */\r\nfunction inquire(moduleName) {\r\n try {\r\n var mod = eval(\"quire\".replace(/^/,\"re\"))(moduleName); // eslint-disable-line no-eval\r\n if (mod && (mod.length || Object.keys(mod).length))\r\n return mod;\r\n } catch (e) {} // eslint-disable-line no-empty\r\n return null;\r\n}\r\n","\"use strict\";\r\nmodule.exports = pool;\r\n\r\n/**\r\n * An allocator as used by {@link util.pool}.\r\n * @typedef PoolAllocator\r\n * @type {function}\r\n * @param {number} size Buffer size\r\n * @returns {Uint8Array} Buffer\r\n */\r\n\r\n/**\r\n * A slicer as used by {@link util.pool}.\r\n * @typedef PoolSlicer\r\n * @type {function}\r\n * @param {number} start Start offset\r\n * @param {number} end End offset\r\n * @returns {Uint8Array} Buffer slice\r\n * @this {Uint8Array}\r\n */\r\n\r\n/**\r\n * A general purpose buffer pool.\r\n * @memberof util\r\n * @function\r\n * @param {PoolAllocator} alloc Allocator\r\n * @param {PoolSlicer} slice Slicer\r\n * @param {number} [size=8192] Slab size\r\n * @returns {PoolAllocator} Pooled allocator\r\n */\r\nfunction pool(alloc, slice, size) {\r\n var SIZE = size || 8192;\r\n var MAX = SIZE >>> 1;\r\n var slab = null;\r\n var offset = SIZE;\r\n return function pool_alloc(size) {\r\n if (size < 1 || size > MAX)\r\n return alloc(size);\r\n if (offset + size > SIZE) {\r\n slab = alloc(SIZE);\r\n offset = 0;\r\n }\r\n var buf = slice.call(slab, offset, offset += size);\r\n if (offset & 7) // align to 32 bit\r\n offset = (offset | 7) + 1;\r\n return buf;\r\n };\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal UTF8 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar utf8 = exports;\r\n\r\n/**\r\n * Calculates the UTF8 byte length of a string.\r\n * @param {string} string String\r\n * @returns {number} Byte length\r\n */\r\nutf8.length = function utf8_length(string) {\r\n var len = 0,\r\n c = 0;\r\n for (var i = 0; i < string.length; ++i) {\r\n c = string.charCodeAt(i);\r\n if (c < 128)\r\n len += 1;\r\n else if (c < 2048)\r\n len += 2;\r\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\r\n ++i;\r\n len += 4;\r\n } else\r\n len += 3;\r\n }\r\n return len;\r\n};\r\n\r\n/**\r\n * Reads UTF8 bytes as a string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} String read\r\n */\r\nutf8.read = function utf8_read(buffer, start, end) {\r\n var len = end - start;\r\n if (len < 1)\r\n return \"\";\r\n var parts = null,\r\n chunk = [],\r\n i = 0, // char offset\r\n t; // temporary\r\n while (start < end) {\r\n t = buffer[start++];\r\n if (t < 128)\r\n chunk[i++] = t;\r\n else if (t > 191 && t < 224)\r\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\r\n else if (t > 239 && t < 365) {\r\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\r\n chunk[i++] = 0xD800 + (t >> 10);\r\n chunk[i++] = 0xDC00 + (t & 1023);\r\n } else\r\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\n/**\r\n * Writes a string as UTF8 bytes.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Bytes written\r\n */\r\nutf8.write = function utf8_write(string, buffer, offset) {\r\n var start = offset,\r\n c1, // character 1\r\n c2; // character 2\r\n for (var i = 0; i < string.length; ++i) {\r\n c1 = string.charCodeAt(i);\r\n if (c1 < 128) {\r\n buffer[offset++] = c1;\r\n } else if (c1 < 2048) {\r\n buffer[offset++] = c1 >> 6 | 192;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\r\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\r\n ++i;\r\n buffer[offset++] = c1 >> 18 | 240;\r\n buffer[offset++] = c1 >> 12 & 63 | 128;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else {\r\n buffer[offset++] = c1 >> 12 | 224;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n }\r\n }\r\n return offset - start;\r\n};\r\n","\"use strict\";\nvar protobuf = exports;\n\n/**\n * Build type, one of `\"full\"`, `\"light\"` or `\"minimal\"`.\n * @name build\n * @type {string}\n * @const\n */\nprotobuf.build = \"minimal\";\n\n// Serialization\nprotobuf.Writer = require(16);\nprotobuf.BufferWriter = require(17);\nprotobuf.Reader = require(9);\nprotobuf.BufferReader = require(10);\n\n// Utility\nprotobuf.util = require(15);\nprotobuf.rpc = require(12);\nprotobuf.roots = require(11);\nprotobuf.configure = configure;\n\n/* istanbul ignore next */\n/**\n * Reconfigures the library according to the environment.\n * @returns {undefined}\n */\nfunction configure() {\n protobuf.util._configure();\n protobuf.Writer._configure(protobuf.BufferWriter);\n protobuf.Reader._configure(protobuf.BufferReader);\n}\n\n// Set up buffer utility according to the environment\nconfigure();\n","\"use strict\";\nmodule.exports = Reader;\n\nvar util = require(15);\n\nvar BufferReader; // cyclic\n\nvar LongBits = util.LongBits,\n utf8 = util.utf8;\n\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(\"index out of range: \" + reader.pos + \" + \" + (writeLength || 1) + \" > \" + reader.len);\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n * @param {Uint8Array} buffer Buffer to read from\n */\nfunction Reader(buffer) {\n\n /**\n * Read buffer.\n * @type {Uint8Array}\n */\n this.buf = buffer;\n\n /**\n * Read buffer position.\n * @type {number}\n */\n this.pos = 0;\n\n /**\n * Read buffer length.\n * @type {number}\n */\n this.len = buffer.length;\n}\n\nvar create_array = typeof Uint8Array !== \"undefined\"\n ? function create_typed_array(buffer) {\n if (buffer instanceof Uint8Array || Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n }\n /* istanbul ignore next */\n : function create_array(buffer) {\n if (Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n };\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup(buffer) {\n return (Reader.create = function create_buffer(buffer) {\n return util.Buffer.isBuffer(buffer)\n ? new BufferReader(buffer)\n /* istanbul ignore next */\n : create_array(buffer);\n })(buffer);\n }\n /* istanbul ignore next */\n : create_array;\n};\n\n/**\n * Creates a new reader using the specified buffer.\n * @function\n * @param {Uint8Array|Buffer} buffer Buffer to read from\n * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}\n * @throws {Error} If `buffer` is not a valid buffer\n */\nReader.create = create();\n\nReader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;\n\n/**\n * Reads a varint as an unsigned 32 bit value.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.uint32 = (function read_uint32_setup() {\n var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)\n return function read_uint32() {\n value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;\n\n /* istanbul ignore if */\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n };\n})();\n\n/**\n * Reads a varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.int32 = function read_int32() {\n return this.uint32() | 0;\n};\n\n/**\n * Reads a zig-zag encoded varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.sint32 = function read_sint32() {\n var value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readLongVarint() {\n // tends to deopt with local vars for octet etc.\n var bits = new LongBits(0, 0);\n var i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n i = 0;\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n } else {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n }\n /* istanbul ignore next */\n throw Error(\"invalid varint encoding\");\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads a varint as a signed 64 bit value.\n * @name Reader#int64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as an unsigned 64 bit value.\n * @name Reader#uint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a zig-zag encoded varint as a signed 64 bit value.\n * @name Reader#sint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as a boolean.\n * @returns {boolean} Value read\n */\nReader.prototype.bool = function read_bool() {\n return this.uint32() !== 0;\n};\n\nfunction readFixed32_end(buf, end) { // note that this uses `end`, not `pos`\n return (buf[end - 4]\n | buf[end - 3] << 8\n | buf[end - 2] << 16\n | buf[end - 1] << 24) >>> 0;\n}\n\n/**\n * Reads fixed 32 bits as an unsigned 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.fixed32 = function read_fixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4);\n};\n\n/**\n * Reads fixed 32 bits as a signed 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.sfixed32 = function read_sfixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readFixed64(/* this: Reader */) {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 8);\n\n return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads fixed 64 bits.\n * @name Reader#fixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads zig-zag encoded fixed 64 bits.\n * @name Reader#sfixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a float (32 bit) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.float = function read_float() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readFloatLE(this.buf, this.pos);\n this.pos += 4;\n return value;\n};\n\n/**\n * Reads a double (64 bit float) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.double = function read_double() {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readDoubleLE(this.buf, this.pos);\n this.pos += 8;\n return value;\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @returns {Uint8Array} Value read\n */\nReader.prototype.bytes = function read_bytes() {\n var length = this.uint32(),\n start = this.pos,\n end = this.pos + length;\n\n /* istanbul ignore if */\n if (end > this.len)\n throw indexOutOfRange(this, length);\n\n this.pos += length;\n if (Array.isArray(this.buf)) // plain array\n return this.buf.slice(start, end);\n\n if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1\n var nativeBuffer = util.Buffer;\n return nativeBuffer\n ? nativeBuffer.alloc(0)\n : new this.buf.constructor(0);\n }\n return this._slice.call(this.buf, start, end);\n};\n\n/**\n * Reads a string preceeded by its byte length as a varint.\n * @returns {string} Value read\n */\nReader.prototype.string = function read_string() {\n var bytes = this.bytes();\n return utf8.read(bytes, 0, bytes.length);\n};\n\n/**\n * Skips the specified number of bytes if specified, otherwise skips a varint.\n * @param {number} [length] Length if known, otherwise a varint is assumed\n * @returns {Reader} `this`\n */\nReader.prototype.skip = function skip(length) {\n if (typeof length === \"number\") {\n /* istanbul ignore if */\n if (this.pos + length > this.len)\n throw indexOutOfRange(this, length);\n this.pos += length;\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n } while (this.buf[this.pos++] & 128);\n }\n return this;\n};\n\n/**\n * Skips the next element of the specified wire type.\n * @param {number} wireType Wire type received\n * @returns {Reader} `this`\n */\nReader.prototype.skipType = function(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n\n /* istanbul ignore next */\n default:\n throw Error(\"invalid wire type \" + wireType + \" at offset \" + this.pos);\n }\n return this;\n};\n\nReader._configure = function(BufferReader_) {\n BufferReader = BufferReader_;\n Reader.create = create();\n BufferReader._configure();\n\n var fn = util.Long ? \"toLong\" : /* istanbul ignore next */ \"toNumber\";\n util.merge(Reader.prototype, {\n\n int64: function read_int64() {\n return readLongVarint.call(this)[fn](false);\n },\n\n uint64: function read_uint64() {\n return readLongVarint.call(this)[fn](true);\n },\n\n sint64: function read_sint64() {\n return readLongVarint.call(this).zzDecode()[fn](false);\n },\n\n fixed64: function read_fixed64() {\n return readFixed64.call(this)[fn](true);\n },\n\n sfixed64: function read_sfixed64() {\n return readFixed64.call(this)[fn](false);\n }\n\n });\n};\n","\"use strict\";\nmodule.exports = BufferReader;\n\n// extends Reader\nvar Reader = require(9);\n(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;\n\nvar util = require(15);\n\n/**\n * Constructs a new buffer reader instance.\n * @classdesc Wire format reader using node buffers.\n * @extends Reader\n * @constructor\n * @param {Buffer} buffer Buffer to read from\n */\nfunction BufferReader(buffer) {\n Reader.call(this, buffer);\n\n /**\n * Read buffer.\n * @name BufferReader#buf\n * @type {Buffer}\n */\n}\n\nBufferReader._configure = function () {\n /* istanbul ignore else */\n if (util.Buffer)\n BufferReader.prototype._slice = util.Buffer.prototype.slice;\n};\n\n\n/**\n * @override\n */\nBufferReader.prototype.string = function read_string_buffer() {\n var len = this.uint32(); // modifies pos\n return this.buf.utf8Slice\n ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))\n : this.buf.toString(\"utf-8\", this.pos, this.pos = Math.min(this.pos + len, this.len));\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @name BufferReader#bytes\n * @function\n * @returns {Buffer} Value read\n */\n\nBufferReader._configure();\n","\"use strict\";\nmodule.exports = {};\n\n/**\n * Named roots.\n * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).\n * Can also be used manually to make roots available across modules.\n * @name roots\n * @type {Object.}\n * @example\n * // pbjs -r myroot -o compiled.js ...\n *\n * // in another module:\n * require(\"./compiled.js\");\n *\n * // in any subsequent module:\n * var root = protobuf.roots[\"myroot\"];\n */\n","\"use strict\";\n\n/**\n * Streaming RPC helpers.\n * @namespace\n */\nvar rpc = exports;\n\n/**\n * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.\n * @typedef RPCImpl\n * @type {function}\n * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called\n * @param {Uint8Array} requestData Request data\n * @param {RPCImplCallback} callback Callback function\n * @returns {undefined}\n * @example\n * function rpcImpl(method, requestData, callback) {\n * if (protobuf.util.lcFirst(method.name) !== \"myMethod\") // compatible with static code\n * throw Error(\"no such method\");\n * asynchronouslyObtainAResponse(requestData, function(err, responseData) {\n * callback(err, responseData);\n * });\n * }\n */\n\n/**\n * Node-style callback as used by {@link RPCImpl}.\n * @typedef RPCImplCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error\n * @returns {undefined}\n */\n\nrpc.Service = require(13);\n","\"use strict\";\nmodule.exports = Service;\n\nvar util = require(15);\n\n// Extends EventEmitter\n(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;\n\n/**\n * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.\n *\n * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.\n * @typedef rpc.ServiceMethodCallback\n * @template TRes extends Message\n * @type {function}\n * @param {Error|null} error Error, if any\n * @param {TRes} [response] Response message\n * @returns {undefined}\n */\n\n/**\n * A service method part of a {@link rpc.Service} as created by {@link Service.create}.\n * @typedef rpc.ServiceMethod\n * @template TReq extends Message\n * @template TRes extends Message\n * @type {function}\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message\n * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined`\n */\n\n/**\n * Constructs a new RPC service instance.\n * @classdesc An RPC service as returned by {@link Service#create}.\n * @exports rpc.Service\n * @extends util.EventEmitter\n * @constructor\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n */\nfunction Service(rpcImpl, requestDelimited, responseDelimited) {\n\n if (typeof rpcImpl !== \"function\")\n throw TypeError(\"rpcImpl must be a function\");\n\n util.EventEmitter.call(this);\n\n /**\n * RPC implementation. Becomes `null` once the service is ended.\n * @type {RPCImpl|null}\n */\n this.rpcImpl = rpcImpl;\n\n /**\n * Whether requests are length-delimited.\n * @type {boolean}\n */\n this.requestDelimited = Boolean(requestDelimited);\n\n /**\n * Whether responses are length-delimited.\n * @type {boolean}\n */\n this.responseDelimited = Boolean(responseDelimited);\n}\n\n/**\n * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.\n * @param {Method|rpc.ServiceMethod} method Reflected or static method\n * @param {Constructor} requestCtor Request constructor\n * @param {Constructor} responseCtor Response constructor\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} callback Service callback\n * @returns {undefined}\n * @template TReq extends Message\n * @template TRes extends Message\n */\nService.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {\n\n if (!request)\n throw TypeError(\"request must be specified\");\n\n var self = this;\n if (!callback)\n return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);\n\n if (!self.rpcImpl) {\n setTimeout(function() { callback(Error(\"already ended\")); }, 0);\n return undefined;\n }\n\n try {\n return self.rpcImpl(\n method,\n requestCtor[self.requestDelimited ? \"encodeDelimited\" : \"encode\"](request).finish(),\n function rpcCallback(err, response) {\n\n if (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n\n if (response === null) {\n self.end(/* endedByRPC */ true);\n return undefined;\n }\n\n if (!(response instanceof responseCtor)) {\n try {\n response = responseCtor[self.responseDelimited ? \"decodeDelimited\" : \"decode\"](response);\n } catch (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n }\n\n self.emit(\"data\", response, method);\n return callback(null, response);\n }\n );\n } catch (err) {\n self.emit(\"error\", err, method);\n setTimeout(function() { callback(err); }, 0);\n return undefined;\n }\n};\n\n/**\n * Ends this service and emits the `end` event.\n * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.\n * @returns {rpc.Service} `this`\n */\nService.prototype.end = function end(endedByRPC) {\n if (this.rpcImpl) {\n if (!endedByRPC) // signal end to rpcImpl\n this.rpcImpl(null, null, null);\n this.rpcImpl = null;\n this.emit(\"end\").off();\n }\n return this;\n};\n","\"use strict\";\nmodule.exports = LongBits;\n\nvar util = require(15);\n\n/**\n * Constructs new long bits.\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @constructor\n * @param {number} lo Low 32 bits, unsigned\n * @param {number} hi High 32 bits, unsigned\n */\nfunction LongBits(lo, hi) {\n\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits.\n * @type {number}\n */\n this.lo = lo >>> 0;\n\n /**\n * High bits.\n * @type {number}\n */\n this.hi = hi >>> 0;\n}\n\n/**\n * Zero bits.\n * @memberof util.LongBits\n * @type {util.LongBits}\n */\nvar zero = LongBits.zero = new LongBits(0, 0);\n\nzero.toNumber = function() { return 0; };\nzero.zzEncode = zero.zzDecode = function() { return this; };\nzero.length = function() { return 1; };\n\n/**\n * Zero hash.\n * @memberof util.LongBits\n * @type {string}\n */\nvar zeroHash = LongBits.zeroHash = \"\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n/**\n * Constructs new long bits from the specified number.\n * @param {number} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.fromNumber = function fromNumber(value) {\n if (value === 0)\n return zero;\n var sign = value < 0;\n if (sign)\n value = -value;\n var lo = value >>> 0,\n hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295)\n hi = 0;\n }\n }\n return new LongBits(lo, hi);\n};\n\n/**\n * Constructs new long bits from a number, long or string.\n * @param {Long|number|string} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.from = function from(value) {\n if (typeof value === \"number\")\n return LongBits.fromNumber(value);\n if (util.isString(value)) {\n /* istanbul ignore else */\n if (util.Long)\n value = util.Long.fromString(value);\n else\n return LongBits.fromNumber(parseInt(value, 10));\n }\n return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n};\n\n/**\n * Converts this long bits to a possibly unsafe JavaScript number.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {number} Possibly unsafe number\n */\nLongBits.prototype.toNumber = function toNumber(unsigned) {\n if (!unsigned && this.hi >>> 31) {\n var lo = ~this.lo + 1 >>> 0,\n hi = ~this.hi >>> 0;\n if (!lo)\n hi = hi + 1 >>> 0;\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n};\n\n/**\n * Converts this long bits to a long.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long} Long\n */\nLongBits.prototype.toLong = function toLong(unsigned) {\n return util.Long\n ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))\n /* istanbul ignore next */\n : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };\n};\n\nvar charCodeAt = String.prototype.charCodeAt;\n\n/**\n * Constructs new long bits from the specified 8 characters long hash.\n * @param {string} hash Hash\n * @returns {util.LongBits} Bits\n */\nLongBits.fromHash = function fromHash(hash) {\n if (hash === zeroHash)\n return zero;\n return new LongBits(\n ( charCodeAt.call(hash, 0)\n | charCodeAt.call(hash, 1) << 8\n | charCodeAt.call(hash, 2) << 16\n | charCodeAt.call(hash, 3) << 24) >>> 0\n ,\n ( charCodeAt.call(hash, 4)\n | charCodeAt.call(hash, 5) << 8\n | charCodeAt.call(hash, 6) << 16\n | charCodeAt.call(hash, 7) << 24) >>> 0\n );\n};\n\n/**\n * Converts this long bits to a 8 characters long hash.\n * @returns {string} Hash\n */\nLongBits.prototype.toHash = function toHash() {\n return String.fromCharCode(\n this.lo & 255,\n this.lo >>> 8 & 255,\n this.lo >>> 16 & 255,\n this.lo >>> 24 ,\n this.hi & 255,\n this.hi >>> 8 & 255,\n this.hi >>> 16 & 255,\n this.hi >>> 24\n );\n};\n\n/**\n * Zig-zag encodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzEncode = function zzEncode() {\n var mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = ( this.lo << 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Zig-zag decodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzDecode = function zzDecode() {\n var mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = ( this.hi >>> 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Calculates the length of this longbits when encoded as a varint.\n * @returns {number} Length\n */\nLongBits.prototype.length = function length() {\n var part0 = this.lo,\n part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,\n part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n};\n","\"use strict\";\nvar util = exports;\n\n// used to return a Promise where callback is omitted\nutil.asPromise = require(1);\n\n// converts to / from base64 encoded strings\nutil.base64 = require(2);\n\n// base class of rpc.Service\nutil.EventEmitter = require(3);\n\n// float handling accross browsers\nutil.float = require(4);\n\n// requires modules optionally and hides the call from bundlers\nutil.inquire = require(5);\n\n// converts to / from utf8 encoded strings\nutil.utf8 = require(7);\n\n// provides a node-like buffer pool in the browser\nutil.pool = require(6);\n\n// utility to work with the low and high bits of a 64 bit value\nutil.LongBits = require(14);\n\n/**\n * Whether running within node or not.\n * @memberof util\n * @type {boolean}\n */\nutil.isNode = Boolean(typeof global !== \"undefined\"\n && global\n && global.process\n && global.process.versions\n && global.process.versions.node);\n\n/**\n * Global object reference.\n * @memberof util\n * @type {Object}\n */\nutil.global = util.isNode && global\n || typeof window !== \"undefined\" && window\n || typeof self !== \"undefined\" && self\n || this; // eslint-disable-line no-invalid-this\n\n/**\n * An immuable empty array.\n * @memberof util\n * @type {Array.<*>}\n * @const\n */\nutil.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes\n\n/**\n * An immutable empty object.\n * @type {Object}\n * @const\n */\nutil.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes\n\n/**\n * Tests if the specified value is an integer.\n * @function\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is an integer\n */\nutil.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {\n return typeof value === \"number\" && isFinite(value) && Math.floor(value) === value;\n};\n\n/**\n * Tests if the specified value is a string.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a string\n */\nutil.isString = function isString(value) {\n return typeof value === \"string\" || value instanceof String;\n};\n\n/**\n * Tests if the specified value is a non-null object.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a non-null object\n */\nutil.isObject = function isObject(value) {\n return value && typeof value === \"object\";\n};\n\n/**\n * Checks if a property on a message is considered to be present.\n * This is an alias of {@link util.isSet}.\n * @function\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isset =\n\n/**\n * Checks if a property on a message is considered to be present.\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isSet = function isSet(obj, prop) {\n var value = obj[prop];\n if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins\n return typeof value !== \"object\" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;\n return false;\n};\n\n/**\n * Any compatible Buffer instance.\n * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.\n * @interface Buffer\n * @extends Uint8Array\n */\n\n/**\n * Node's Buffer class if available.\n * @type {Constructor}\n */\nutil.Buffer = (function() {\n try {\n var Buffer = util.inquire(\"buffer\").Buffer;\n // refuse to use non-node buffers if not explicitly assigned (perf reasons):\n return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;\n } catch (e) {\n /* istanbul ignore next */\n return null;\n }\n})();\n\n// Internal alias of or polyfull for Buffer.from.\nutil._Buffer_from = null;\n\n// Internal alias of or polyfill for Buffer.allocUnsafe.\nutil._Buffer_allocUnsafe = null;\n\n/**\n * Creates a new buffer of whatever type supported by the environment.\n * @param {number|number[]} [sizeOrArray=0] Buffer size or number array\n * @returns {Uint8Array|Buffer} Buffer\n */\nutil.newBuffer = function newBuffer(sizeOrArray) {\n /* istanbul ignore next */\n return typeof sizeOrArray === \"number\"\n ? util.Buffer\n ? util._Buffer_allocUnsafe(sizeOrArray)\n : new util.Array(sizeOrArray)\n : util.Buffer\n ? util._Buffer_from(sizeOrArray)\n : typeof Uint8Array === \"undefined\"\n ? sizeOrArray\n : new Uint8Array(sizeOrArray);\n};\n\n/**\n * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.\n * @type {Constructor}\n */\nutil.Array = typeof Uint8Array !== \"undefined\" ? Uint8Array /* istanbul ignore next */ : Array;\n\n/**\n * Any compatible Long instance.\n * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.\n * @interface Long\n * @property {number} low Low bits\n * @property {number} high High bits\n * @property {boolean} unsigned Whether unsigned or not\n */\n\n/**\n * Long.js's Long class if available.\n * @type {Constructor}\n */\nutil.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long\n || /* istanbul ignore next */ util.global.Long\n || util.inquire(\"long\");\n\n/**\n * Regular expression used to verify 2 bit (`bool`) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key2Re = /^true|false|0|1$/;\n\n/**\n * Regular expression used to verify 32 bit (`int32` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key32Re = /^-?(?:0|[1-9][0-9]*)$/;\n\n/**\n * Regular expression used to verify 64 bit (`int64` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key64Re = /^(?:[\\\\x00-\\\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;\n\n/**\n * Converts a number or long to an 8 characters long hash string.\n * @param {Long|number} value Value to convert\n * @returns {string} Hash\n */\nutil.longToHash = function longToHash(value) {\n return value\n ? util.LongBits.from(value).toHash()\n : util.LongBits.zeroHash;\n};\n\n/**\n * Converts an 8 characters long hash string to a long or number.\n * @param {string} hash Hash\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long|number} Original value\n */\nutil.longFromHash = function longFromHash(hash, unsigned) {\n var bits = util.LongBits.fromHash(hash);\n if (util.Long)\n return util.Long.fromBits(bits.lo, bits.hi, unsigned);\n return bits.toNumber(Boolean(unsigned));\n};\n\n/**\n * Merges the properties of the source object into the destination object.\n * @memberof util\n * @param {Object.} dst Destination object\n * @param {Object.} src Source object\n * @param {boolean} [ifNotSet=false] Merges only if the key is not already set\n * @returns {Object.} Destination object\n */\nfunction merge(dst, src, ifNotSet) { // used by converters\n for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)\n if (dst[keys[i]] === undefined || !ifNotSet)\n dst[keys[i]] = src[keys[i]];\n return dst;\n}\n\nutil.merge = merge;\n\n/**\n * Converts the first character of a string to lower case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.lcFirst = function lcFirst(str) {\n return str.charAt(0).toLowerCase() + str.substring(1);\n};\n\n/**\n * Creates a custom error constructor.\n * @memberof util\n * @param {string} name Error name\n * @returns {Constructor} Custom error constructor\n */\nfunction newError(name) {\n\n function CustomError(message, properties) {\n\n if (!(this instanceof CustomError))\n return new CustomError(message, properties);\n\n // Error.call(this, message);\n // ^ just returns a new error instance because the ctor can be called as a function\n\n Object.defineProperty(this, \"message\", { get: function() { return message; } });\n\n /* istanbul ignore next */\n if (Error.captureStackTrace) // node\n Error.captureStackTrace(this, CustomError);\n else\n Object.defineProperty(this, \"stack\", { value: new Error().stack || \"\" });\n\n if (properties)\n merge(this, properties);\n }\n\n CustomError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: CustomError,\n writable: true,\n enumerable: false,\n configurable: true,\n },\n name: {\n get: function get() { return name; },\n set: undefined,\n enumerable: false,\n // configurable: false would accurately preserve the behavior of\n // the original, but I'm guessing that was not intentional.\n // For an actual error subclass, this property would\n // be configurable.\n configurable: true,\n },\n toString: {\n value: function value() { return this.name + \": \" + this.message; },\n writable: true,\n enumerable: false,\n configurable: true,\n },\n });\n\n return CustomError;\n}\n\nutil.newError = newError;\n\n/**\n * Constructs a new protocol error.\n * @classdesc Error subclass indicating a protocol specifc error.\n * @memberof util\n * @extends Error\n * @template T extends Message\n * @constructor\n * @param {string} message Error message\n * @param {Object.} [properties] Additional properties\n * @example\n * try {\n * MyMessage.decode(someBuffer); // throws if required fields are missing\n * } catch (e) {\n * if (e instanceof ProtocolError && e.instance)\n * console.log(\"decoded so far: \" + JSON.stringify(e.instance));\n * }\n */\nutil.ProtocolError = newError(\"ProtocolError\");\n\n/**\n * So far decoded message instance.\n * @name util.ProtocolError#instance\n * @type {Message}\n */\n\n/**\n * A OneOf getter as returned by {@link util.oneOfGetter}.\n * @typedef OneOfGetter\n * @type {function}\n * @returns {string|undefined} Set field name, if any\n */\n\n/**\n * Builds a getter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfGetter} Unbound getter\n */\nutil.oneOfGetter = function getOneOf(fieldNames) {\n var fieldMap = {};\n for (var i = 0; i < fieldNames.length; ++i)\n fieldMap[fieldNames[i]] = 1;\n\n /**\n * @returns {string|undefined} Set field name, if any\n * @this Object\n * @ignore\n */\n return function() { // eslint-disable-line consistent-return\n for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)\n if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)\n return keys[i];\n };\n};\n\n/**\n * A OneOf setter as returned by {@link util.oneOfSetter}.\n * @typedef OneOfSetter\n * @type {function}\n * @param {string|undefined} value Field name\n * @returns {undefined}\n */\n\n/**\n * Builds a setter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfSetter} Unbound setter\n */\nutil.oneOfSetter = function setOneOf(fieldNames) {\n\n /**\n * @param {string} name Field name\n * @returns {undefined}\n * @this Object\n * @ignore\n */\n return function(name) {\n for (var i = 0; i < fieldNames.length; ++i)\n if (fieldNames[i] !== name)\n delete this[fieldNames[i]];\n };\n};\n\n/**\n * Default conversion options used for {@link Message#toJSON} implementations.\n *\n * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:\n *\n * - Longs become strings\n * - Enums become string keys\n * - Bytes become base64 encoded strings\n * - (Sub-)Messages become plain objects\n * - Maps become plain objects with all string keys\n * - Repeated fields become arrays\n * - NaN and Infinity for float and double fields become strings\n *\n * @type {IConversionOptions}\n * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json\n */\nutil.toJSONOptions = {\n longs: String,\n enums: String,\n bytes: String,\n json: true\n};\n\n// Sets up buffer utility according to the environment (called in index-minimal)\nutil._configure = function() {\n var Buffer = util.Buffer;\n /* istanbul ignore if */\n if (!Buffer) {\n util._Buffer_from = util._Buffer_allocUnsafe = null;\n return;\n }\n // because node 4.x buffers are incompatible & immutable\n // see: https://github.com/dcodeIO/protobuf.js/pull/665\n util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||\n /* istanbul ignore next */\n function Buffer_from(value, encoding) {\n return new Buffer(value, encoding);\n };\n util._Buffer_allocUnsafe = Buffer.allocUnsafe ||\n /* istanbul ignore next */\n function Buffer_allocUnsafe(size) {\n return new Buffer(size);\n };\n};\n","\"use strict\";\nmodule.exports = Writer;\n\nvar util = require(15);\n\nvar BufferWriter; // cyclic\n\nvar LongBits = util.LongBits,\n base64 = util.base64,\n utf8 = util.utf8;\n\n/**\n * Constructs a new writer operation instance.\n * @classdesc Scheduled writer operation.\n * @constructor\n * @param {function(*, Uint8Array, number)} fn Function to call\n * @param {number} len Value byte length\n * @param {*} val Value to write\n * @ignore\n */\nfunction Op(fn, len, val) {\n\n /**\n * Function to call.\n * @type {function(Uint8Array, number, *)}\n */\n this.fn = fn;\n\n /**\n * Value byte length.\n * @type {number}\n */\n this.len = len;\n\n /**\n * Next operation.\n * @type {Writer.Op|undefined}\n */\n this.next = undefined;\n\n /**\n * Value to write.\n * @type {*}\n */\n this.val = val; // type varies\n}\n\n/* istanbul ignore next */\nfunction noop() {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance.\n * @classdesc Copied writer state.\n * @memberof Writer\n * @constructor\n * @param {Writer} writer Writer to copy state from\n * @ignore\n */\nfunction State(writer) {\n\n /**\n * Current head.\n * @type {Writer.Op}\n */\n this.head = writer.head;\n\n /**\n * Current tail.\n * @type {Writer.Op}\n */\n this.tail = writer.tail;\n\n /**\n * Current buffer length.\n * @type {number}\n */\n this.len = writer.len;\n\n /**\n * Next state.\n * @type {State|null}\n */\n this.next = writer.states;\n}\n\n/**\n * Constructs a new writer instance.\n * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n */\nfunction Writer() {\n\n /**\n * Current length.\n * @type {number}\n */\n this.len = 0;\n\n /**\n * Operations head.\n * @type {Object}\n */\n this.head = new Op(noop, 0, 0);\n\n /**\n * Operations tail\n * @type {Object}\n */\n this.tail = this.head;\n\n /**\n * Linked forked states.\n * @type {Object|null}\n */\n this.states = null;\n\n // When a value is written, the writer calculates its byte length and puts it into a linked\n // list of operations to perform when finish() is called. This both allows us to allocate\n // buffers of the exact required size and reduces the amount of work we have to do compared\n // to first calculating over objects and then encoding over objects. In our case, the encoding\n // part is just a linked list walk calling operations with already prepared values.\n}\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup() {\n return (Writer.create = function create_buffer() {\n return new BufferWriter();\n })();\n }\n /* istanbul ignore next */\n : function create_array() {\n return new Writer();\n };\n};\n\n/**\n * Creates a new writer.\n * @function\n * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}\n */\nWriter.create = create();\n\n/**\n * Allocates a buffer of the specified size.\n * @param {number} size Buffer size\n * @returns {Uint8Array} Buffer\n */\nWriter.alloc = function alloc(size) {\n return new util.Array(size);\n};\n\n// Use Uint8Array buffer pool in the browser, just like node does with buffers\n/* istanbul ignore else */\nif (util.Array !== Array)\n Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);\n\n/**\n * Pushes a new operation to the queue.\n * @param {function(Uint8Array, number, *)} fn Function to call\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @returns {Writer} `this`\n * @private\n */\nWriter.prototype._push = function push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n};\n\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\n\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n\n/**\n * Constructs a new varint writer operation instance.\n * @classdesc Scheduled varint writer operation.\n * @extends Op\n * @constructor\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @ignore\n */\nfunction VarintOp(len, val) {\n this.len = len;\n this.next = undefined;\n this.val = val;\n}\n\nVarintOp.prototype = Object.create(Op.prototype);\nVarintOp.prototype.fn = writeVarint32;\n\n/**\n * Writes an unsigned 32 bit value as a varint.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.uint32 = function write_uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0)\n < 128 ? 1\n : value < 16384 ? 2\n : value < 2097152 ? 3\n : value < 268435456 ? 4\n : 5,\n value)).len;\n return this;\n};\n\n/**\n * Writes a signed 32 bit value as a varint.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.int32 = function write_int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n};\n\n/**\n * Writes a 32 bit value as a varint, zig-zag encoded.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sint32 = function write_sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n};\n\nfunction writeVarint64(val, buf, pos) {\n while (val.hi) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\n\n/**\n * Writes an unsigned 64 bit value as a varint.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.uint64 = function write_uint64(value) {\n var bits = LongBits.from(value);\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a signed 64 bit value as a varint.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.int64 = Writer.prototype.uint64;\n\n/**\n * Writes a signed 64 bit value as a varint, zig-zag encoded.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sint64 = function write_sint64(value) {\n var bits = LongBits.from(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a boolish value as a varint.\n * @param {boolean} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bool = function write_bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n};\n\nfunction writeFixed32(val, buf, pos) {\n buf[pos ] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\n\n/**\n * Writes an unsigned 32 bit value as fixed 32 bits.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.fixed32 = function write_fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n};\n\n/**\n * Writes a signed 32 bit value as fixed 32 bits.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sfixed32 = Writer.prototype.fixed32;\n\n/**\n * Writes an unsigned 64 bit value as fixed 64 bits.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.fixed64 = function write_fixed64(value) {\n var bits = LongBits.from(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n};\n\n/**\n * Writes a signed 64 bit value as fixed 64 bits.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sfixed64 = Writer.prototype.fixed64;\n\n/**\n * Writes a float (32 bit).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.float = function write_float(value) {\n return this._push(util.float.writeFloatLE, 4, value);\n};\n\n/**\n * Writes a double (64 bit float).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.double = function write_double(value) {\n return this._push(util.float.writeDoubleLE, 8, value);\n};\n\nvar writeBytes = util.Array.prototype.set\n ? function writeBytes_set(val, buf, pos) {\n buf.set(val, pos); // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytes_for(val, buf, pos) {\n for (var i = 0; i < val.length; ++i)\n buf[pos + i] = val[i];\n };\n\n/**\n * Writes a sequence of bytes.\n * @param {Uint8Array|string} value Buffer or base64 encoded string to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bytes = function write_bytes(value) {\n var len = value.length >>> 0;\n if (!len)\n return this._push(writeByte, 1, 0);\n if (util.isString(value)) {\n var buf = Writer.alloc(len = base64.length(value));\n base64.decode(value, buf, 0);\n value = buf;\n }\n return this.uint32(len)._push(writeBytes, len, value);\n};\n\n/**\n * Writes a string.\n * @param {string} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.string = function write_string(value) {\n var len = utf8.length(value);\n return len\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0);\n};\n\n/**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n * @returns {Writer} `this`\n */\nWriter.prototype.fork = function fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n};\n\n/**\n * Resets this instance to the last state.\n * @returns {Writer} `this`\n */\nWriter.prototype.reset = function reset() {\n if (this.states) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n } else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n};\n\n/**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n * @returns {Writer} `this`\n */\nWriter.prototype.ldelim = function ldelim() {\n var head = this.head,\n tail = this.tail,\n len = this.len;\n this.reset().uint32(len);\n if (len) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n};\n\n/**\n * Finishes the write operation.\n * @returns {Uint8Array} Finished buffer\n */\nWriter.prototype.finish = function finish() {\n var head = this.head.next, // skip noop\n buf = this.constructor.alloc(this.len),\n pos = 0;\n while (head) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n};\n\nWriter._configure = function(BufferWriter_) {\n BufferWriter = BufferWriter_;\n Writer.create = create();\n BufferWriter._configure();\n};\n","\"use strict\";\nmodule.exports = BufferWriter;\n\n// extends Writer\nvar Writer = require(16);\n(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;\n\nvar util = require(15);\n\n/**\n * Constructs a new buffer writer instance.\n * @classdesc Wire format writer using node buffers.\n * @extends Writer\n * @constructor\n */\nfunction BufferWriter() {\n Writer.call(this);\n}\n\nBufferWriter._configure = function () {\n /**\n * Allocates a buffer of the specified size.\n * @function\n * @param {number} size Buffer size\n * @returns {Buffer} Buffer\n */\n BufferWriter.alloc = util._Buffer_allocUnsafe;\n\n BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === \"set\"\n ? function writeBytesBuffer_set(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytesBuffer_copy(val, buf, pos) {\n if (val.copy) // Buffer values\n val.copy(buf, pos, 0, val.length);\n else for (var i = 0; i < val.length;) // plain array values\n buf[pos++] = val[i++];\n };\n};\n\n\n/**\n * @override\n */\nBufferWriter.prototype.bytes = function write_bytes_buffer(value) {\n if (util.isString(value))\n value = util._Buffer_from(value, \"base64\");\n var len = value.length >>> 0;\n this.uint32(len);\n if (len)\n this._push(BufferWriter.writeBytesBuffer, len, value);\n return this;\n};\n\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)\n util.utf8.write(val, buf, pos);\n else if (buf.utf8Write)\n buf.utf8Write(val, pos);\n else\n buf.write(val, pos);\n}\n\n/**\n * @override\n */\nBufferWriter.prototype.string = function write_string_buffer(value) {\n var len = util.Buffer.byteLength(value);\n this.uint32(len);\n if (len)\n this._push(writeStringBuffer, len, value);\n return this;\n};\n\n\n/**\n * Finishes the write operation.\n * @name BufferWriter#finish\n * @function\n * @returns {Buffer} Finished buffer\n */\n\nBufferWriter._configure();\n"],"sourceRoot":"."} \ No newline at end of file diff --git a/node_modules/protobufjs/dist/minimal/protobuf.min.js b/node_modules/protobufjs/dist/minimal/protobuf.min.js new file mode 100644 index 0000000..2c603b7 --- /dev/null +++ b/node_modules/protobufjs/dist/minimal/protobuf.min.js @@ -0,0 +1,8 @@ +/*! + * protobuf.js v7.5.4 (c) 2016, daniel wirtz + * compiled fri, 15 aug 2025 23:28:55 utc + * licensed under the bsd-3-clause license + * see: https://github.com/dcodeio/protobuf.js for details + */ +!function(d){"use strict";!function(r,u,t){var n=function t(n){var i=u[n];return i||r[n][0].call(i=u[n]={exports:{}},t,i,i.exports),i.exports}(t[0]);n.util.global.protobuf=n,"function"==typeof define&&define.amd&&define(["long"],function(t){return t&&t.isLong&&(n.util.Long=t,n.configure()),n}),"object"==typeof module&&module&&module.exports&&(module.exports=n)}({1:[function(t,n,i){n.exports=function(t,n){var i=Array(arguments.length-1),e=0,r=2,s=!0;for(;r>2],r=(3&o)<<4,h=1;break;case 1:e[s++]=f[r|o>>4],r=(15&o)<<2,h=2;break;case 2:e[s++]=f[r|o>>6],e[s++]=f[63&o],h=0}8191>4,r=h,e=2;break;case 2:n[i++]=(15&r)<<4|(60&h)>>2,r=h,e=3;break;case 3:n[i++]=(3&r)<<6|h,e=0}}if(1===e)throw Error(c);return i-u},i.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}},{}],3:[function(t,n,i){function r(){this.t={}}(n.exports=r).prototype.on=function(t,n,i){return(this.t[t]||(this.t[t]=[])).push({fn:n,ctx:i||this}),this},r.prototype.off=function(t,n){if(t===d)this.t={};else if(n===d)this.t[t]=[];else for(var i=this.t[t],r=0;r>>0:n<11754943508222875e-54?(u<<31|Math.round(n/1401298464324817e-60))>>>0:(u<<31|127+(t=Math.floor(Math.log(n)/Math.LN2))<<23|8388607&Math.round(n*Math.pow(2,-t)*8388608))>>>0,i,r)}function i(t,n,i){t=t(n,i),n=2*(t>>31)+1,i=t>>>23&255,t&=8388607;return 255==i?t?NaN:1/0*n:0==i?1401298464324817e-60*n*t:n*Math.pow(2,i-150)*(8388608+t)}function r(t,n,i){h[0]=t,n[i]=o[0],n[i+1]=o[1],n[i+2]=o[2],n[i+3]=o[3]}function u(t,n,i){h[0]=t,n[i]=o[3],n[i+1]=o[2],n[i+2]=o[1],n[i+3]=o[0]}function e(t,n){return o[0]=t[n],o[1]=t[n+1],o[2]=t[n+2],o[3]=t[n+3],h[0]}function s(t,n){return o[3]=t[n],o[2]=t[n+1],o[1]=t[n+2],o[0]=t[n+3],h[0]}var h,o,f,c,a;function l(t,n,i,r,u,e){var s,h=r<0?1:0;0===(r=h?-r:r)?(t(0,u,e+n),t(0<1/r?0:2147483648,u,e+i)):isNaN(r)?(t(0,u,e+n),t(2146959360,u,e+i)):17976931348623157e292>>0,u,e+i)):r<22250738585072014e-324?(t((s=r/5e-324)>>>0,u,e+n),t((h<<31|s/4294967296)>>>0,u,e+i)):(t(4503599627370496*(s=r*Math.pow(2,-(r=1024===(r=Math.floor(Math.log(r)/Math.LN2))?1023:r)))>>>0,u,e+n),t((h<<31|r+1023<<20|1048576*s&1048575)>>>0,u,e+i))}function v(t,n,i,r,u){n=t(r,u+n),t=t(r,u+i),r=2*(t>>31)+1,u=t>>>20&2047,i=4294967296*(1048575&t)+n;return 2047==u?i?NaN:1/0*r:0==u?5e-324*r*i:r*Math.pow(2,u-1075)*(i+4503599627370496)}function w(t,n,i){f[0]=t,n[i]=c[0],n[i+1]=c[1],n[i+2]=c[2],n[i+3]=c[3],n[i+4]=c[4],n[i+5]=c[5],n[i+6]=c[6],n[i+7]=c[7]}function b(t,n,i){f[0]=t,n[i]=c[7],n[i+1]=c[6],n[i+2]=c[5],n[i+3]=c[4],n[i+4]=c[3],n[i+5]=c[2],n[i+6]=c[1],n[i+7]=c[0]}function y(t,n){return c[0]=t[n],c[1]=t[n+1],c[2]=t[n+2],c[3]=t[n+3],c[4]=t[n+4],c[5]=t[n+5],c[6]=t[n+6],c[7]=t[n+7],f[0]}function g(t,n){return c[7]=t[n],c[6]=t[n+1],c[5]=t[n+2],c[4]=t[n+3],c[3]=t[n+4],c[2]=t[n+5],c[1]=t[n+6],c[0]=t[n+7],f[0]}return"undefined"!=typeof Float32Array?(h=new Float32Array([-0]),o=new Uint8Array(h.buffer),a=128===o[3],t.writeFloatLE=a?r:u,t.writeFloatBE=a?u:r,t.readFloatLE=a?e:s,t.readFloatBE=a?s:e):(t.writeFloatLE=n.bind(null,d),t.writeFloatBE=n.bind(null,A),t.readFloatLE=i.bind(null,p),t.readFloatBE=i.bind(null,m)),"undefined"!=typeof Float64Array?(f=new Float64Array([-0]),c=new Uint8Array(f.buffer),a=128===c[7],t.writeDoubleLE=a?w:b,t.writeDoubleBE=a?b:w,t.readDoubleLE=a?y:g,t.readDoubleBE=a?g:y):(t.writeDoubleLE=l.bind(null,d,0,4),t.writeDoubleBE=l.bind(null,A,4,0),t.readDoubleLE=v.bind(null,p,0,4),t.readDoubleBE=v.bind(null,m,4,0)),t}function d(t,n,i){n[i]=255&t,n[i+1]=t>>>8&255,n[i+2]=t>>>16&255,n[i+3]=t>>>24}function A(t,n,i){n[i]=t>>>24,n[i+1]=t>>>16&255,n[i+2]=t>>>8&255,n[i+3]=255&t}function p(t,n){return(t[n]|t[n+1]<<8|t[n+2]<<16|t[n+3]<<24)>>>0}function m(t,n){return(t[n]<<24|t[n+1]<<16|t[n+2]<<8|t[n+3])>>>0}n.exports=r(r)},{}],5:[function(t,n,i){function r(t){try{var n=eval("require")(t);if(n&&(n.length||Object.keys(n).length))return n}catch(t){}return null}n.exports=r},{}],6:[function(t,n,i){n.exports=function(n,i,t){var r=t||8192,u=r>>>1,e=null,s=r;return function(t){if(t<1||u>10),e[s++]=56320+(1023&r)):e[s++]=(15&r)<<12|(63&t[n++])<<6|63&t[n++],8191>6|192:(55296==(64512&r)&&56320==(64512&(u=t.charCodeAt(s+1)))?(++s,n[i++]=(r=65536+((1023&r)<<10)+(1023&u))>>18|240,n[i++]=r>>12&63|128):n[i++]=r>>12|224,n[i++]=r>>6&63|128),n[i++]=63&r|128);return i-e}},{}],8:[function(t,n,i){var r=i;function u(){r.util.n(),r.Writer.n(r.BufferWriter),r.Reader.n(r.BufferReader)}r.build="minimal",r.Writer=t(16),r.BufferWriter=t(17),r.Reader=t(9),r.BufferReader=t(10),r.util=t(15),r.rpc=t(12),r.roots=t(11),r.configure=u,u()},{10:10,11:11,12:12,15:15,16:16,17:17,9:9}],9:[function(t,n,i){n.exports=o;var r,u=t(15),e=u.LongBits,s=u.utf8;function h(t,n){return RangeError("index out of range: "+t.pos+" + "+(n||1)+" > "+t.len)}function o(t){this.buf=t,this.pos=0,this.len=t.length}function f(){return u.Buffer?function(t){return(o.create=function(t){return u.Buffer.isBuffer(t)?new r(t):a(t)})(t)}:a}var c,a="undefined"!=typeof Uint8Array?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new o(t);throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new o(t);throw Error("illegal buffer")};function l(){var t=new e(0,0),n=0;if(!(4=this.len)throw h(this);if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*n)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(127&this.buf[this.pos++])<<7*n)>>>0,t}for(;n<4;++n)if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*n)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(127&this.buf[this.pos])<<28)>>>0,t.hi=(t.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return t;if(n=0,4>>0,this.buf[this.pos++]<128)return t}else for(;n<5;++n){if(this.pos>=this.len)throw h(this);if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*n+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}function v(t,n){return(t[n-4]|t[n-3]<<8|t[n-2]<<16|t[n-1]<<24)>>>0}function w(){if(this.pos+8>this.len)throw h(this,8);return new e(v(this.buf,this.pos+=4),v(this.buf,this.pos+=4))}o.create=f(),o.prototype.i=u.Array.prototype.subarray||u.Array.prototype.slice,o.prototype.uint32=(c=4294967295,function(){if(c=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(c=(c|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128||(c=(c|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128||(c=(c|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128||(c=(c|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128||!((this.pos+=5)>this.len))))))return c;throw this.pos=this.len,h(this,10)}),o.prototype.int32=function(){return 0|this.uint32()},o.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(1&t)|0},o.prototype.bool=function(){return 0!==this.uint32()},o.prototype.fixed32=function(){if(this.pos+4>this.len)throw h(this,4);return v(this.buf,this.pos+=4)},o.prototype.sfixed32=function(){if(this.pos+4>this.len)throw h(this,4);return 0|v(this.buf,this.pos+=4)},o.prototype.float=function(){if(this.pos+4>this.len)throw h(this,4);var t=u.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t},o.prototype.double=function(){if(this.pos+8>this.len)throw h(this,4);var t=u.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t},o.prototype.bytes=function(){var t=this.uint32(),n=this.pos,i=this.pos+t;if(i>this.len)throw h(this,t);return this.pos+=t,Array.isArray(this.buf)?this.buf.slice(n,i):n===i?(t=u.Buffer)?t.alloc(0):new this.buf.constructor(0):this.i.call(this.buf,n,i)},o.prototype.string=function(){var t=this.bytes();return s.read(t,0,t.length)},o.prototype.skip=function(t){if("number"==typeof t){if(this.pos+t>this.len)throw h(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw h(this)}while(128&this.buf[this.pos++]);return this},o.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this},o.n=function(t){r=t,o.create=f(),r.n();var n=u.Long?"toLong":"toNumber";u.merge(o.prototype,{int64:function(){return l.call(this)[n](!1)},uint64:function(){return l.call(this)[n](!0)},sint64:function(){return l.call(this).zzDecode()[n](!1)},fixed64:function(){return w.call(this)[n](!0)},sfixed64:function(){return w.call(this)[n](!1)}})}},{15:15}],10:[function(t,n,i){n.exports=e;var r=t(9),u=((e.prototype=Object.create(r.prototype)).constructor=e,t(15));function e(t){r.call(this,t)}e.n=function(){u.Buffer&&(e.prototype.i=u.Buffer.prototype.slice)},e.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+t,this.len))},e.n()},{15:15,9:9}],11:[function(t,n,i){n.exports={}},{}],12:[function(t,n,i){i.Service=t(13)},{13:13}],13:[function(t,n,i){n.exports=r;var h=t(15);function r(t,n,i){if("function"!=typeof t)throw TypeError("rpcImpl must be a function");h.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=!!n,this.responseDelimited=!!i}((r.prototype=Object.create(h.EventEmitter.prototype)).constructor=r).prototype.rpcCall=function t(i,n,r,u,e){if(!u)throw TypeError("request must be specified");var s=this;if(!e)return h.asPromise(t,s,i,n,r,u);if(!s.rpcImpl)return setTimeout(function(){e(Error("already ended"))},0),d;try{return s.rpcImpl(i,n[s.requestDelimited?"encodeDelimited":"encode"](u).finish(),function(t,n){if(t)return s.emit("error",t,i),e(t);if(null===n)return s.end(!0),d;if(!(n instanceof r))try{n=r[s.responseDelimited?"decodeDelimited":"decode"](n)}catch(t){return s.emit("error",t,i),e(t)}return s.emit("data",n,i),e(null,n)})}catch(t){return s.emit("error",t,i),setTimeout(function(){e(t)},0),d}},r.prototype.end=function(t){return this.rpcImpl&&(t||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},{15:15}],14:[function(t,n,i){n.exports=u;var r=t(15);function u(t,n){this.lo=t>>>0,this.hi=n>>>0}var e=u.zero=new u(0,0),s=(e.toNumber=function(){return 0},e.zzEncode=e.zzDecode=function(){return this},e.length=function(){return 1},u.zeroHash="\0\0\0\0\0\0\0\0",u.fromNumber=function(t){var n,i;return 0===t?e:(i=(t=(n=t<0)?-t:t)>>>0,t=(t-i)/4294967296>>>0,n&&(t=~t>>>0,i=~i>>>0,4294967295<++i&&(i=0,4294967295<++t&&(t=0))),new u(i,t))},u.from=function(t){if("number"==typeof t)return u.fromNumber(t);if(r.isString(t)){if(!r.Long)return u.fromNumber(parseInt(t,10));t=r.Long.fromString(t)}return t.low||t.high?new u(t.low>>>0,t.high>>>0):e},u.prototype.toNumber=function(t){var n;return!t&&this.hi>>>31?(t=1+~this.lo>>>0,n=~this.hi>>>0,-(t+4294967296*(n=t?n:n+1>>>0))):this.lo+4294967296*this.hi},u.prototype.toLong=function(t){return r.Long?new r.Long(0|this.lo,0|this.hi,!!t):{low:0|this.lo,high:0|this.hi,unsigned:!!t}},String.prototype.charCodeAt);u.fromHash=function(t){return"\0\0\0\0\0\0\0\0"===t?e:new u((s.call(t,0)|s.call(t,1)<<8|s.call(t,2)<<16|s.call(t,3)<<24)>>>0,(s.call(t,4)|s.call(t,5)<<8|s.call(t,6)<<16|s.call(t,7)<<24)>>>0)},u.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},u.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this},u.prototype.zzDecode=function(){var t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this},u.prototype.length=function(){var t=this.lo,n=(this.lo>>>28|this.hi<<4)>>>0,i=this.hi>>>24;return 0==i?0==n?t<16384?t<128?1:2:t<2097152?3:4:n<16384?n<128?5:6:n<2097152?7:8:i<128?9:10}},{15:15}],15:[function(t,n,i){var r=i;function u(t,n,i){for(var r=Object.keys(n),u=0;u>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;127>>7;n[i++]=t.lo}function y(t,n,i){n[i]=255&t,n[i+1]=t>>>8&255,n[i+2]=t>>>16&255,n[i+3]=t>>>24}a.create=l(),a.alloc=function(t){return new u.Array(t)},u.Array!==Array&&(a.alloc=u.pool(a.alloc,u.Array.prototype.subarray)),a.prototype.e=function(t,n,i){return this.tail=this.tail.next=new o(t,n,i),this.len+=n,this},(w.prototype=Object.create(o.prototype)).fn=function(t,n,i){for(;127>>=7;n[i]=t},a.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new w((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this},a.prototype.int32=function(t){return t<0?this.e(b,10,e.fromNumber(t)):this.uint32(t)},a.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},a.prototype.int64=a.prototype.uint64=function(t){t=e.from(t);return this.e(b,t.length(),t)},a.prototype.sint64=function(t){t=e.from(t).zzEncode();return this.e(b,t.length(),t)},a.prototype.bool=function(t){return this.e(v,1,t?1:0)},a.prototype.sfixed32=a.prototype.fixed32=function(t){return this.e(y,4,t>>>0)},a.prototype.sfixed64=a.prototype.fixed64=function(t){t=e.from(t);return this.e(y,4,t.lo).e(y,4,t.hi)},a.prototype.float=function(t){return this.e(u.float.writeFloatLE,4,t)},a.prototype.double=function(t){return this.e(u.float.writeDoubleLE,8,t)};var g=u.Array.prototype.set?function(t,n,i){n.set(t,i)}:function(t,n,i){for(var r=0;r>>0;return i?(u.isString(t)&&(n=a.alloc(i=s.length(t)),s.decode(t,n,0),t=n),this.uint32(i).e(g,i,t)):this.e(v,1,0)},a.prototype.string=function(t){var n=h.length(t);return n?this.uint32(n).e(h.write,n,t):this.e(v,1,0)},a.prototype.fork=function(){return this.states=new c(this),this.head=this.tail=new o(f,0,0),this.len=0,this},a.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new o(f,0,0),this.len=0),this},a.prototype.ldelim=function(){var t=this.head,n=this.tail,i=this.len;return this.reset().uint32(i),i&&(this.tail.next=t.next,this.tail=n,this.len+=i),this},a.prototype.finish=function(){for(var t=this.head.next,n=this.constructor.alloc(this.len),i=0;t;)t.fn(t.val,n,i),i+=t.len,t=t.next;return n},a.n=function(t){r=t,a.create=l(),r.n()}},{15:15}],17:[function(t,n,i){n.exports=e;var r=t(16),u=((e.prototype=Object.create(r.prototype)).constructor=e,t(15));function e(){r.call(this)}function s(t,n,i){t.length<40?u.utf8.write(t,n,i):n.utf8Write?n.utf8Write(t,i):n.write(t,i)}e.n=function(){e.alloc=u.u,e.writeBytesBuffer=u.Buffer&&u.Buffer.prototype instanceof Uint8Array&&"set"===u.Buffer.prototype.set.name?function(t,n,i){n.set(t,i)}:function(t,n,i){if(t.copy)t.copy(n,i,0,t.length);else for(var r=0;r>>0;return this.uint32(n),n&&this.e(e.writeBytesBuffer,n,t),this},e.prototype.string=function(t){var n=u.Buffer.byteLength(t);return this.uint32(n),n&&this.e(s,n,t),this},e.n()},{15:15,16:16}]},{},[8])}(); +//# sourceMappingURL=protobuf.min.js.map diff --git a/node_modules/protobufjs/dist/minimal/protobuf.min.js.map b/node_modules/protobufjs/dist/minimal/protobuf.min.js.map new file mode 100644 index 0000000..9647827 --- /dev/null +++ b/node_modules/protobufjs/dist/minimal/protobuf.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["lib/prelude.js","../node_modules/@protobufjs/aspromise/index.js","../node_modules/@protobufjs/base64/index.js","../node_modules/@protobufjs/eventemitter/index.js","../node_modules/@protobufjs/float/index.js","../node_modules/@protobufjs/inquire/index.js","../node_modules/@protobufjs/pool/index.js","../node_modules/@protobufjs/utf8/index.js","../src/index-minimal","../src/reader.js","../src/reader_buffer.js","../src/roots.js","../src/rpc.js","../src/rpc/service.js","../src/util/longbits.js","../src/util/minimal.js","../src/writer.js","../src/writer_buffer.js"],"names":["undefined","modules","cache","entries","protobuf","$require","name","$module","call","exports","util","global","define","amd","Long","isLong","configure","module","1","require","fn","ctx","params","Array","arguments","length","offset","index","pending","Promise","resolve","reject","err","apply","base64","string","p","n","Math","ceil","b64","s64","i","encode","buffer","start","end","t","parts","chunk","j","b","push","String","fromCharCode","slice","join","invalidEncoding","decode","c","charCodeAt","Error","test","EventEmitter","this","_listeners","prototype","on","evt","off","listeners","splice","emit","args","factory","writeFloat_ieee754","writeUint","val","buf","pos","sign","isNaN","round","exponent","floor","log","LN2","pow","readFloat_ieee754","readUint","uint","mantissa","NaN","Infinity","writeFloat_f32_cpy","f32","f8b","writeFloat_f32_rev","readFloat_f32_cpy","readFloat_f32_rev","f64","le","writeDouble_ieee754","off0","off1","readDouble_ieee754","lo","hi","writeDouble_f64_cpy","writeDouble_f64_rev","readDouble_f64_cpy","readDouble_f64_rev","Float32Array","Uint8Array","writeFloatLE","writeFloatBE","readFloatLE","readFloatBE","bind","writeUintLE","writeUintBE","readUintLE","readUintBE","Float64Array","writeDoubleLE","writeDoubleBE","readDoubleLE","readDoubleBE","inquire","moduleName","mod","eval","Object","keys","e","alloc","size","SIZE","MAX","slab","utf8","len","read","write","c1","c2","_configure","Writer","BufferWriter","Reader","BufferReader","build","rpc","roots","LongBits","indexOutOfRange","reader","writeLength","RangeError","create","Buffer","isBuffer","create_array","value","isArray","readLongVarint","bits","readFixed32_end","readFixed64","_slice","subarray","uint32","int32","sint32","bool","fixed32","sfixed32","float","double","bytes","nativeBuffer","constructor","skip","skipType","wireType","BufferReader_","merge","int64","uint64","sint64","zzDecode","fixed64","sfixed64","utf8Slice","min","toString","Service","rpcImpl","requestDelimited","responseDelimited","TypeError","Boolean","rpcCall","method","requestCtor","responseCtor","request","callback","self","asPromise","setTimeout","finish","response","endedByRPC","zero","toNumber","zzEncode","zeroHash","fromNumber","from","isString","parseInt","fromString","low","high","unsigned","toLong","fromHash","hash","toHash","mask","part0","part1","part2","dst","src","ifNotSet","newError","CustomError","message","properties","defineProperty","get","captureStackTrace","stack","writable","enumerable","configurable","set","pool","isNode","process","versions","node","window","emptyArray","freeze","emptyObject","isInteger","Number","isFinite","isObject","isset","isSet","obj","prop","hasOwnProperty","utf8Write","_Buffer_from","_Buffer_allocUnsafe","newBuffer","sizeOrArray","dcodeIO","key2Re","key32Re","key64Re","longToHash","longFromHash","fromBits","lcFirst","str","toLowerCase","substring","ProtocolError","oneOfGetter","fieldNames","fieldMap","oneOfSetter","toJSONOptions","longs","enums","json","encoding","allocUnsafe","Op","next","noop","State","writer","head","tail","states","writeByte","VarintOp","writeVarint64","writeFixed32","_push","writeBytes","fork","reset","ldelim","BufferWriter_","writeStringBuffer","writeBytesBuffer","copy","byteLength"],"mappings":";;;;;;AAAA,CAAA,SAAAA,GAAA,aAAA,CAAA,SAAAC,EAAAC,EAAAC,GAcA,IAAAC,EAPA,SAAAC,EAAAC,GACA,IAAAC,EAAAL,EAAAI,GAGA,OAFAC,GACAN,EAAAK,GAAA,GAAAE,KAAAD,EAAAL,EAAAI,GAAA,CAAAG,QAAA,EAAA,EAAAJ,EAAAE,EAAAA,EAAAE,OAAA,EACAF,EAAAE,OACA,EAEAN,EAAA,EAAA,EAGA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AAA,SAAAhB,GAGA,IAAAtB,GADAsB,EADAzJ,EAAAkN,SAAAzD,CAAA,EACAzJ,EAAAkQ,EAAAzG,EAAA,QAAA,EACAA,GAAA1I,SAAA,EAIA,OAHAuC,KAAA2G,OAAA9B,CAAA,EACAA,GACA7E,KAAAkP,EAAA9J,EAAAqK,iBAAA5K,EAAAsB,CAAA,EACAnG,IACA,EAcAoF,EAAAlF,UAAA/B,OAAA,SAAAgI,GACA,IAAAtB,EAAAnI,EAAAsJ,OAAA2J,WAAAxJ,CAAA,EAIA,OAHAnG,KAAA2G,OAAA9B,CAAA,EACAA,GACA7E,KAAAkP,EAAAM,EAAA3K,EAAAsB,CAAA,EACAnG,IACA,EAUAoF,EAAAF,EAAA","file":"protobuf.min.js","sourcesContent":["(function prelude(modules, cache, entries) {\n\n // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS\n // sources through a conflict-free require shim and is again wrapped within an iife that\n // provides a minification-friendly `undefined` var plus a global \"use strict\" directive\n // so that minification can remove the directives of each module.\n\n function $require(name) {\n var $module = cache[name];\n if (!$module)\n modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports);\n return $module.exports;\n }\n\n var protobuf = $require(entries[0]);\n\n // Expose globally\n protobuf.util.global.protobuf = protobuf;\n\n // Be nice to AMD\n if (typeof define === \"function\" && define.amd)\n define([\"long\"], function(Long) {\n if (Long && Long.isLong) {\n protobuf.util.Long = Long;\n protobuf.configure();\n }\n return protobuf;\n });\n\n // Be nice to CommonJS\n if (typeof module === \"object\" && module && module.exports)\n module.exports = protobuf;\n\n})/* end of prelude */","\"use strict\";\r\nmodule.exports = asPromise;\r\n\r\n/**\r\n * Callback as used by {@link util.asPromise}.\r\n * @typedef asPromiseCallback\r\n * @type {function}\r\n * @param {Error|null} error Error, if any\r\n * @param {...*} params Additional arguments\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Returns a promise from a node-style callback function.\r\n * @memberof util\r\n * @param {asPromiseCallback} fn Function to call\r\n * @param {*} ctx Function context\r\n * @param {...*} params Function arguments\r\n * @returns {Promise<*>} Promisified function\r\n */\r\nfunction asPromise(fn, ctx/*, varargs */) {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0,\r\n index = 2,\r\n pending = true;\r\n while (index < arguments.length)\r\n params[offset++] = arguments[index++];\r\n return new Promise(function executor(resolve, reject) {\r\n params[offset] = function callback(err/*, varargs */) {\r\n if (pending) {\r\n pending = false;\r\n if (err)\r\n reject(err);\r\n else {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0;\r\n while (offset < params.length)\r\n params[offset++] = arguments[offset];\r\n resolve.apply(null, params);\r\n }\r\n }\r\n };\r\n try {\r\n fn.apply(ctx || null, params);\r\n } catch (err) {\r\n if (pending) {\r\n pending = false;\r\n reject(err);\r\n }\r\n }\r\n });\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal base64 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar base64 = exports;\r\n\r\n/**\r\n * Calculates the byte length of a base64 encoded string.\r\n * @param {string} string Base64 encoded string\r\n * @returns {number} Byte length\r\n */\r\nbase64.length = function length(string) {\r\n var p = string.length;\r\n if (!p)\r\n return 0;\r\n var n = 0;\r\n while (--p % 4 > 1 && string.charAt(p) === \"=\")\r\n ++n;\r\n return Math.ceil(string.length * 3) / 4 - n;\r\n};\r\n\r\n// Base64 encoding table\r\nvar b64 = new Array(64);\r\n\r\n// Base64 decoding table\r\nvar s64 = new Array(123);\r\n\r\n// 65..90, 97..122, 48..57, 43, 47\r\nfor (var i = 0; i < 64;)\r\n s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;\r\n\r\n/**\r\n * Encodes a buffer to a base64 encoded string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} Base64 encoded string\r\n */\r\nbase64.encode = function encode(buffer, start, end) {\r\n var parts = null,\r\n chunk = [];\r\n var i = 0, // output index\r\n j = 0, // goto index\r\n t; // temporary\r\n while (start < end) {\r\n var b = buffer[start++];\r\n switch (j) {\r\n case 0:\r\n chunk[i++] = b64[b >> 2];\r\n t = (b & 3) << 4;\r\n j = 1;\r\n break;\r\n case 1:\r\n chunk[i++] = b64[t | b >> 4];\r\n t = (b & 15) << 2;\r\n j = 2;\r\n break;\r\n case 2:\r\n chunk[i++] = b64[t | b >> 6];\r\n chunk[i++] = b64[b & 63];\r\n j = 0;\r\n break;\r\n }\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (j) {\r\n chunk[i++] = b64[t];\r\n chunk[i++] = 61;\r\n if (j === 1)\r\n chunk[i++] = 61;\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\nvar invalidEncoding = \"invalid encoding\";\r\n\r\n/**\r\n * Decodes a base64 encoded string to a buffer.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Number of bytes written\r\n * @throws {Error} If encoding is invalid\r\n */\r\nbase64.decode = function decode(string, buffer, offset) {\r\n var start = offset;\r\n var j = 0, // goto index\r\n t; // temporary\r\n for (var i = 0; i < string.length;) {\r\n var c = string.charCodeAt(i++);\r\n if (c === 61 && j > 1)\r\n break;\r\n if ((c = s64[c]) === undefined)\r\n throw Error(invalidEncoding);\r\n switch (j) {\r\n case 0:\r\n t = c;\r\n j = 1;\r\n break;\r\n case 1:\r\n buffer[offset++] = t << 2 | (c & 48) >> 4;\r\n t = c;\r\n j = 2;\r\n break;\r\n case 2:\r\n buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;\r\n t = c;\r\n j = 3;\r\n break;\r\n case 3:\r\n buffer[offset++] = (t & 3) << 6 | c;\r\n j = 0;\r\n break;\r\n }\r\n }\r\n if (j === 1)\r\n throw Error(invalidEncoding);\r\n return offset - start;\r\n};\r\n\r\n/**\r\n * Tests if the specified string appears to be base64 encoded.\r\n * @param {string} string String to test\r\n * @returns {boolean} `true` if probably base64 encoded, otherwise false\r\n */\r\nbase64.test = function test(string) {\r\n return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);\r\n};\r\n","\"use strict\";\r\nmodule.exports = EventEmitter;\r\n\r\n/**\r\n * Constructs a new event emitter instance.\r\n * @classdesc A minimal event emitter.\r\n * @memberof util\r\n * @constructor\r\n */\r\nfunction EventEmitter() {\r\n\r\n /**\r\n * Registered listeners.\r\n * @type {Object.}\r\n * @private\r\n */\r\n this._listeners = {};\r\n}\r\n\r\n/**\r\n * Registers an event listener.\r\n * @param {string} evt Event name\r\n * @param {function} fn Listener\r\n * @param {*} [ctx] Listener context\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.on = function on(evt, fn, ctx) {\r\n (this._listeners[evt] || (this._listeners[evt] = [])).push({\r\n fn : fn,\r\n ctx : ctx || this\r\n });\r\n return this;\r\n};\r\n\r\n/**\r\n * Removes an event listener or any matching listeners if arguments are omitted.\r\n * @param {string} [evt] Event name. Removes all listeners if omitted.\r\n * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.off = function off(evt, fn) {\r\n if (evt === undefined)\r\n this._listeners = {};\r\n else {\r\n if (fn === undefined)\r\n this._listeners[evt] = [];\r\n else {\r\n var listeners = this._listeners[evt];\r\n for (var i = 0; i < listeners.length;)\r\n if (listeners[i].fn === fn)\r\n listeners.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emits an event by calling its listeners with the specified arguments.\r\n * @param {string} evt Event name\r\n * @param {...*} args Arguments\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.emit = function emit(evt) {\r\n var listeners = this._listeners[evt];\r\n if (listeners) {\r\n var args = [],\r\n i = 1;\r\n for (; i < arguments.length;)\r\n args.push(arguments[i++]);\r\n for (i = 0; i < listeners.length;)\r\n listeners[i].fn.apply(listeners[i++].ctx, args);\r\n }\r\n return this;\r\n};\r\n","\"use strict\";\r\n\r\nmodule.exports = factory(factory);\r\n\r\n/**\r\n * Reads / writes floats / doubles from / to buffers.\r\n * @name util.float\r\n * @namespace\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using little endian byte order.\r\n * @name util.float.writeFloatLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using big endian byte order.\r\n * @name util.float.writeFloatBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using little endian byte order.\r\n * @name util.float.readFloatLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using big endian byte order.\r\n * @name util.float.readFloatBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using little endian byte order.\r\n * @name util.float.writeDoubleLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using big endian byte order.\r\n * @name util.float.writeDoubleBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using little endian byte order.\r\n * @name util.float.readDoubleLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using big endian byte order.\r\n * @name util.float.readDoubleBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n// Factory function for the purpose of node-based testing in modified global environments\r\nfunction factory(exports) {\r\n\r\n // float: typed array\r\n if (typeof Float32Array !== \"undefined\") (function() {\r\n\r\n var f32 = new Float32Array([ -0 ]),\r\n f8b = new Uint8Array(f32.buffer),\r\n le = f8b[3] === 128;\r\n\r\n function writeFloat_f32_cpy(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n }\r\n\r\n function writeFloat_f32_rev(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[3];\r\n buf[pos + 1] = f8b[2];\r\n buf[pos + 2] = f8b[1];\r\n buf[pos + 3] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;\r\n\r\n function readFloat_f32_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n function readFloat_f32_rev(buf, pos) {\r\n f8b[3] = buf[pos ];\r\n f8b[2] = buf[pos + 1];\r\n f8b[1] = buf[pos + 2];\r\n f8b[0] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;\r\n\r\n // float: ieee754\r\n })(); else (function() {\r\n\r\n function writeFloat_ieee754(writeUint, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0)\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);\r\n else if (isNaN(val))\r\n writeUint(2143289344, buf, pos);\r\n else if (val > 3.4028234663852886e+38) // +-Infinity\r\n writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);\r\n else if (val < 1.1754943508222875e-38) // denormal\r\n writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);\r\n else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2),\r\n mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;\r\n writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);\r\n }\r\n }\r\n\r\n exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);\r\n exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);\r\n\r\n function readFloat_ieee754(readUint, buf, pos) {\r\n var uint = readUint(buf, pos),\r\n sign = (uint >> 31) * 2 + 1,\r\n exponent = uint >>> 23 & 255,\r\n mantissa = uint & 8388607;\r\n return exponent === 255\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 1.401298464324817e-45 * mantissa\r\n : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);\r\n }\r\n\r\n exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);\r\n exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);\r\n\r\n })();\r\n\r\n // double: typed array\r\n if (typeof Float64Array !== \"undefined\") (function() {\r\n\r\n var f64 = new Float64Array([-0]),\r\n f8b = new Uint8Array(f64.buffer),\r\n le = f8b[7] === 128;\r\n\r\n function writeDouble_f64_cpy(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n buf[pos + 4] = f8b[4];\r\n buf[pos + 5] = f8b[5];\r\n buf[pos + 6] = f8b[6];\r\n buf[pos + 7] = f8b[7];\r\n }\r\n\r\n function writeDouble_f64_rev(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[7];\r\n buf[pos + 1] = f8b[6];\r\n buf[pos + 2] = f8b[5];\r\n buf[pos + 3] = f8b[4];\r\n buf[pos + 4] = f8b[3];\r\n buf[pos + 5] = f8b[2];\r\n buf[pos + 6] = f8b[1];\r\n buf[pos + 7] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;\r\n\r\n function readDouble_f64_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n f8b[4] = buf[pos + 4];\r\n f8b[5] = buf[pos + 5];\r\n f8b[6] = buf[pos + 6];\r\n f8b[7] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n function readDouble_f64_rev(buf, pos) {\r\n f8b[7] = buf[pos ];\r\n f8b[6] = buf[pos + 1];\r\n f8b[5] = buf[pos + 2];\r\n f8b[4] = buf[pos + 3];\r\n f8b[3] = buf[pos + 4];\r\n f8b[2] = buf[pos + 5];\r\n f8b[1] = buf[pos + 6];\r\n f8b[0] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;\r\n\r\n // double: ieee754\r\n })(); else (function() {\r\n\r\n function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);\r\n } else if (isNaN(val)) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(2146959360, buf, pos + off1);\r\n } else if (val > 1.7976931348623157e+308) { // +-Infinity\r\n writeUint(0, buf, pos + off0);\r\n writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);\r\n } else {\r\n var mantissa;\r\n if (val < 2.2250738585072014e-308) { // denormal\r\n mantissa = val / 5e-324;\r\n writeUint(mantissa >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);\r\n } else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2);\r\n if (exponent === 1024)\r\n exponent = 1023;\r\n mantissa = val * Math.pow(2, -exponent);\r\n writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);\r\n }\r\n }\r\n }\r\n\r\n exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);\r\n exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);\r\n\r\n function readDouble_ieee754(readUint, off0, off1, buf, pos) {\r\n var lo = readUint(buf, pos + off0),\r\n hi = readUint(buf, pos + off1);\r\n var sign = (hi >> 31) * 2 + 1,\r\n exponent = hi >>> 20 & 2047,\r\n mantissa = 4294967296 * (hi & 1048575) + lo;\r\n return exponent === 2047\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 5e-324 * mantissa\r\n : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);\r\n }\r\n\r\n exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);\r\n exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);\r\n\r\n })();\r\n\r\n return exports;\r\n}\r\n\r\n// uint helpers\r\n\r\nfunction writeUintLE(val, buf, pos) {\r\n buf[pos ] = val & 255;\r\n buf[pos + 1] = val >>> 8 & 255;\r\n buf[pos + 2] = val >>> 16 & 255;\r\n buf[pos + 3] = val >>> 24;\r\n}\r\n\r\nfunction writeUintBE(val, buf, pos) {\r\n buf[pos ] = val >>> 24;\r\n buf[pos + 1] = val >>> 16 & 255;\r\n buf[pos + 2] = val >>> 8 & 255;\r\n buf[pos + 3] = val & 255;\r\n}\r\n\r\nfunction readUintLE(buf, pos) {\r\n return (buf[pos ]\r\n | buf[pos + 1] << 8\r\n | buf[pos + 2] << 16\r\n | buf[pos + 3] << 24) >>> 0;\r\n}\r\n\r\nfunction readUintBE(buf, pos) {\r\n return (buf[pos ] << 24\r\n | buf[pos + 1] << 16\r\n | buf[pos + 2] << 8\r\n | buf[pos + 3]) >>> 0;\r\n}\r\n","\"use strict\";\r\nmodule.exports = inquire;\r\n\r\n/**\r\n * Requires a module only if available.\r\n * @memberof util\r\n * @param {string} moduleName Module to require\r\n * @returns {?Object} Required module if available and not empty, otherwise `null`\r\n */\r\nfunction inquire(moduleName) {\r\n try {\r\n var mod = eval(\"quire\".replace(/^/,\"re\"))(moduleName); // eslint-disable-line no-eval\r\n if (mod && (mod.length || Object.keys(mod).length))\r\n return mod;\r\n } catch (e) {} // eslint-disable-line no-empty\r\n return null;\r\n}\r\n","\"use strict\";\r\nmodule.exports = pool;\r\n\r\n/**\r\n * An allocator as used by {@link util.pool}.\r\n * @typedef PoolAllocator\r\n * @type {function}\r\n * @param {number} size Buffer size\r\n * @returns {Uint8Array} Buffer\r\n */\r\n\r\n/**\r\n * A slicer as used by {@link util.pool}.\r\n * @typedef PoolSlicer\r\n * @type {function}\r\n * @param {number} start Start offset\r\n * @param {number} end End offset\r\n * @returns {Uint8Array} Buffer slice\r\n * @this {Uint8Array}\r\n */\r\n\r\n/**\r\n * A general purpose buffer pool.\r\n * @memberof util\r\n * @function\r\n * @param {PoolAllocator} alloc Allocator\r\n * @param {PoolSlicer} slice Slicer\r\n * @param {number} [size=8192] Slab size\r\n * @returns {PoolAllocator} Pooled allocator\r\n */\r\nfunction pool(alloc, slice, size) {\r\n var SIZE = size || 8192;\r\n var MAX = SIZE >>> 1;\r\n var slab = null;\r\n var offset = SIZE;\r\n return function pool_alloc(size) {\r\n if (size < 1 || size > MAX)\r\n return alloc(size);\r\n if (offset + size > SIZE) {\r\n slab = alloc(SIZE);\r\n offset = 0;\r\n }\r\n var buf = slice.call(slab, offset, offset += size);\r\n if (offset & 7) // align to 32 bit\r\n offset = (offset | 7) + 1;\r\n return buf;\r\n };\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal UTF8 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar utf8 = exports;\r\n\r\n/**\r\n * Calculates the UTF8 byte length of a string.\r\n * @param {string} string String\r\n * @returns {number} Byte length\r\n */\r\nutf8.length = function utf8_length(string) {\r\n var len = 0,\r\n c = 0;\r\n for (var i = 0; i < string.length; ++i) {\r\n c = string.charCodeAt(i);\r\n if (c < 128)\r\n len += 1;\r\n else if (c < 2048)\r\n len += 2;\r\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\r\n ++i;\r\n len += 4;\r\n } else\r\n len += 3;\r\n }\r\n return len;\r\n};\r\n\r\n/**\r\n * Reads UTF8 bytes as a string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} String read\r\n */\r\nutf8.read = function utf8_read(buffer, start, end) {\r\n var len = end - start;\r\n if (len < 1)\r\n return \"\";\r\n var parts = null,\r\n chunk = [],\r\n i = 0, // char offset\r\n t; // temporary\r\n while (start < end) {\r\n t = buffer[start++];\r\n if (t < 128)\r\n chunk[i++] = t;\r\n else if (t > 191 && t < 224)\r\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\r\n else if (t > 239 && t < 365) {\r\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\r\n chunk[i++] = 0xD800 + (t >> 10);\r\n chunk[i++] = 0xDC00 + (t & 1023);\r\n } else\r\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\n/**\r\n * Writes a string as UTF8 bytes.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Bytes written\r\n */\r\nutf8.write = function utf8_write(string, buffer, offset) {\r\n var start = offset,\r\n c1, // character 1\r\n c2; // character 2\r\n for (var i = 0; i < string.length; ++i) {\r\n c1 = string.charCodeAt(i);\r\n if (c1 < 128) {\r\n buffer[offset++] = c1;\r\n } else if (c1 < 2048) {\r\n buffer[offset++] = c1 >> 6 | 192;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\r\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\r\n ++i;\r\n buffer[offset++] = c1 >> 18 | 240;\r\n buffer[offset++] = c1 >> 12 & 63 | 128;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else {\r\n buffer[offset++] = c1 >> 12 | 224;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n }\r\n }\r\n return offset - start;\r\n};\r\n","\"use strict\";\nvar protobuf = exports;\n\n/**\n * Build type, one of `\"full\"`, `\"light\"` or `\"minimal\"`.\n * @name build\n * @type {string}\n * @const\n */\nprotobuf.build = \"minimal\";\n\n// Serialization\nprotobuf.Writer = require(16);\nprotobuf.BufferWriter = require(17);\nprotobuf.Reader = require(9);\nprotobuf.BufferReader = require(10);\n\n// Utility\nprotobuf.util = require(15);\nprotobuf.rpc = require(12);\nprotobuf.roots = require(11);\nprotobuf.configure = configure;\n\n/* istanbul ignore next */\n/**\n * Reconfigures the library according to the environment.\n * @returns {undefined}\n */\nfunction configure() {\n protobuf.util._configure();\n protobuf.Writer._configure(protobuf.BufferWriter);\n protobuf.Reader._configure(protobuf.BufferReader);\n}\n\n// Set up buffer utility according to the environment\nconfigure();\n","\"use strict\";\nmodule.exports = Reader;\n\nvar util = require(15);\n\nvar BufferReader; // cyclic\n\nvar LongBits = util.LongBits,\n utf8 = util.utf8;\n\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(\"index out of range: \" + reader.pos + \" + \" + (writeLength || 1) + \" > \" + reader.len);\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n * @param {Uint8Array} buffer Buffer to read from\n */\nfunction Reader(buffer) {\n\n /**\n * Read buffer.\n * @type {Uint8Array}\n */\n this.buf = buffer;\n\n /**\n * Read buffer position.\n * @type {number}\n */\n this.pos = 0;\n\n /**\n * Read buffer length.\n * @type {number}\n */\n this.len = buffer.length;\n}\n\nvar create_array = typeof Uint8Array !== \"undefined\"\n ? function create_typed_array(buffer) {\n if (buffer instanceof Uint8Array || Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n }\n /* istanbul ignore next */\n : function create_array(buffer) {\n if (Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n };\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup(buffer) {\n return (Reader.create = function create_buffer(buffer) {\n return util.Buffer.isBuffer(buffer)\n ? new BufferReader(buffer)\n /* istanbul ignore next */\n : create_array(buffer);\n })(buffer);\n }\n /* istanbul ignore next */\n : create_array;\n};\n\n/**\n * Creates a new reader using the specified buffer.\n * @function\n * @param {Uint8Array|Buffer} buffer Buffer to read from\n * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}\n * @throws {Error} If `buffer` is not a valid buffer\n */\nReader.create = create();\n\nReader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;\n\n/**\n * Reads a varint as an unsigned 32 bit value.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.uint32 = (function read_uint32_setup() {\n var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)\n return function read_uint32() {\n value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;\n\n /* istanbul ignore if */\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n };\n})();\n\n/**\n * Reads a varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.int32 = function read_int32() {\n return this.uint32() | 0;\n};\n\n/**\n * Reads a zig-zag encoded varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.sint32 = function read_sint32() {\n var value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readLongVarint() {\n // tends to deopt with local vars for octet etc.\n var bits = new LongBits(0, 0);\n var i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n i = 0;\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n } else {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n }\n /* istanbul ignore next */\n throw Error(\"invalid varint encoding\");\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads a varint as a signed 64 bit value.\n * @name Reader#int64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as an unsigned 64 bit value.\n * @name Reader#uint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a zig-zag encoded varint as a signed 64 bit value.\n * @name Reader#sint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as a boolean.\n * @returns {boolean} Value read\n */\nReader.prototype.bool = function read_bool() {\n return this.uint32() !== 0;\n};\n\nfunction readFixed32_end(buf, end) { // note that this uses `end`, not `pos`\n return (buf[end - 4]\n | buf[end - 3] << 8\n | buf[end - 2] << 16\n | buf[end - 1] << 24) >>> 0;\n}\n\n/**\n * Reads fixed 32 bits as an unsigned 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.fixed32 = function read_fixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4);\n};\n\n/**\n * Reads fixed 32 bits as a signed 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.sfixed32 = function read_sfixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readFixed64(/* this: Reader */) {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 8);\n\n return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads fixed 64 bits.\n * @name Reader#fixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads zig-zag encoded fixed 64 bits.\n * @name Reader#sfixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a float (32 bit) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.float = function read_float() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readFloatLE(this.buf, this.pos);\n this.pos += 4;\n return value;\n};\n\n/**\n * Reads a double (64 bit float) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.double = function read_double() {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readDoubleLE(this.buf, this.pos);\n this.pos += 8;\n return value;\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @returns {Uint8Array} Value read\n */\nReader.prototype.bytes = function read_bytes() {\n var length = this.uint32(),\n start = this.pos,\n end = this.pos + length;\n\n /* istanbul ignore if */\n if (end > this.len)\n throw indexOutOfRange(this, length);\n\n this.pos += length;\n if (Array.isArray(this.buf)) // plain array\n return this.buf.slice(start, end);\n\n if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1\n var nativeBuffer = util.Buffer;\n return nativeBuffer\n ? nativeBuffer.alloc(0)\n : new this.buf.constructor(0);\n }\n return this._slice.call(this.buf, start, end);\n};\n\n/**\n * Reads a string preceeded by its byte length as a varint.\n * @returns {string} Value read\n */\nReader.prototype.string = function read_string() {\n var bytes = this.bytes();\n return utf8.read(bytes, 0, bytes.length);\n};\n\n/**\n * Skips the specified number of bytes if specified, otherwise skips a varint.\n * @param {number} [length] Length if known, otherwise a varint is assumed\n * @returns {Reader} `this`\n */\nReader.prototype.skip = function skip(length) {\n if (typeof length === \"number\") {\n /* istanbul ignore if */\n if (this.pos + length > this.len)\n throw indexOutOfRange(this, length);\n this.pos += length;\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n } while (this.buf[this.pos++] & 128);\n }\n return this;\n};\n\n/**\n * Skips the next element of the specified wire type.\n * @param {number} wireType Wire type received\n * @returns {Reader} `this`\n */\nReader.prototype.skipType = function(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n\n /* istanbul ignore next */\n default:\n throw Error(\"invalid wire type \" + wireType + \" at offset \" + this.pos);\n }\n return this;\n};\n\nReader._configure = function(BufferReader_) {\n BufferReader = BufferReader_;\n Reader.create = create();\n BufferReader._configure();\n\n var fn = util.Long ? \"toLong\" : /* istanbul ignore next */ \"toNumber\";\n util.merge(Reader.prototype, {\n\n int64: function read_int64() {\n return readLongVarint.call(this)[fn](false);\n },\n\n uint64: function read_uint64() {\n return readLongVarint.call(this)[fn](true);\n },\n\n sint64: function read_sint64() {\n return readLongVarint.call(this).zzDecode()[fn](false);\n },\n\n fixed64: function read_fixed64() {\n return readFixed64.call(this)[fn](true);\n },\n\n sfixed64: function read_sfixed64() {\n return readFixed64.call(this)[fn](false);\n }\n\n });\n};\n","\"use strict\";\nmodule.exports = BufferReader;\n\n// extends Reader\nvar Reader = require(9);\n(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;\n\nvar util = require(15);\n\n/**\n * Constructs a new buffer reader instance.\n * @classdesc Wire format reader using node buffers.\n * @extends Reader\n * @constructor\n * @param {Buffer} buffer Buffer to read from\n */\nfunction BufferReader(buffer) {\n Reader.call(this, buffer);\n\n /**\n * Read buffer.\n * @name BufferReader#buf\n * @type {Buffer}\n */\n}\n\nBufferReader._configure = function () {\n /* istanbul ignore else */\n if (util.Buffer)\n BufferReader.prototype._slice = util.Buffer.prototype.slice;\n};\n\n\n/**\n * @override\n */\nBufferReader.prototype.string = function read_string_buffer() {\n var len = this.uint32(); // modifies pos\n return this.buf.utf8Slice\n ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))\n : this.buf.toString(\"utf-8\", this.pos, this.pos = Math.min(this.pos + len, this.len));\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @name BufferReader#bytes\n * @function\n * @returns {Buffer} Value read\n */\n\nBufferReader._configure();\n","\"use strict\";\nmodule.exports = {};\n\n/**\n * Named roots.\n * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).\n * Can also be used manually to make roots available across modules.\n * @name roots\n * @type {Object.}\n * @example\n * // pbjs -r myroot -o compiled.js ...\n *\n * // in another module:\n * require(\"./compiled.js\");\n *\n * // in any subsequent module:\n * var root = protobuf.roots[\"myroot\"];\n */\n","\"use strict\";\n\n/**\n * Streaming RPC helpers.\n * @namespace\n */\nvar rpc = exports;\n\n/**\n * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.\n * @typedef RPCImpl\n * @type {function}\n * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called\n * @param {Uint8Array} requestData Request data\n * @param {RPCImplCallback} callback Callback function\n * @returns {undefined}\n * @example\n * function rpcImpl(method, requestData, callback) {\n * if (protobuf.util.lcFirst(method.name) !== \"myMethod\") // compatible with static code\n * throw Error(\"no such method\");\n * asynchronouslyObtainAResponse(requestData, function(err, responseData) {\n * callback(err, responseData);\n * });\n * }\n */\n\n/**\n * Node-style callback as used by {@link RPCImpl}.\n * @typedef RPCImplCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error\n * @returns {undefined}\n */\n\nrpc.Service = require(13);\n","\"use strict\";\nmodule.exports = Service;\n\nvar util = require(15);\n\n// Extends EventEmitter\n(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;\n\n/**\n * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.\n *\n * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.\n * @typedef rpc.ServiceMethodCallback\n * @template TRes extends Message\n * @type {function}\n * @param {Error|null} error Error, if any\n * @param {TRes} [response] Response message\n * @returns {undefined}\n */\n\n/**\n * A service method part of a {@link rpc.Service} as created by {@link Service.create}.\n * @typedef rpc.ServiceMethod\n * @template TReq extends Message\n * @template TRes extends Message\n * @type {function}\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message\n * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined`\n */\n\n/**\n * Constructs a new RPC service instance.\n * @classdesc An RPC service as returned by {@link Service#create}.\n * @exports rpc.Service\n * @extends util.EventEmitter\n * @constructor\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n */\nfunction Service(rpcImpl, requestDelimited, responseDelimited) {\n\n if (typeof rpcImpl !== \"function\")\n throw TypeError(\"rpcImpl must be a function\");\n\n util.EventEmitter.call(this);\n\n /**\n * RPC implementation. Becomes `null` once the service is ended.\n * @type {RPCImpl|null}\n */\n this.rpcImpl = rpcImpl;\n\n /**\n * Whether requests are length-delimited.\n * @type {boolean}\n */\n this.requestDelimited = Boolean(requestDelimited);\n\n /**\n * Whether responses are length-delimited.\n * @type {boolean}\n */\n this.responseDelimited = Boolean(responseDelimited);\n}\n\n/**\n * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.\n * @param {Method|rpc.ServiceMethod} method Reflected or static method\n * @param {Constructor} requestCtor Request constructor\n * @param {Constructor} responseCtor Response constructor\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} callback Service callback\n * @returns {undefined}\n * @template TReq extends Message\n * @template TRes extends Message\n */\nService.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {\n\n if (!request)\n throw TypeError(\"request must be specified\");\n\n var self = this;\n if (!callback)\n return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);\n\n if (!self.rpcImpl) {\n setTimeout(function() { callback(Error(\"already ended\")); }, 0);\n return undefined;\n }\n\n try {\n return self.rpcImpl(\n method,\n requestCtor[self.requestDelimited ? \"encodeDelimited\" : \"encode\"](request).finish(),\n function rpcCallback(err, response) {\n\n if (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n\n if (response === null) {\n self.end(/* endedByRPC */ true);\n return undefined;\n }\n\n if (!(response instanceof responseCtor)) {\n try {\n response = responseCtor[self.responseDelimited ? \"decodeDelimited\" : \"decode\"](response);\n } catch (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n }\n\n self.emit(\"data\", response, method);\n return callback(null, response);\n }\n );\n } catch (err) {\n self.emit(\"error\", err, method);\n setTimeout(function() { callback(err); }, 0);\n return undefined;\n }\n};\n\n/**\n * Ends this service and emits the `end` event.\n * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.\n * @returns {rpc.Service} `this`\n */\nService.prototype.end = function end(endedByRPC) {\n if (this.rpcImpl) {\n if (!endedByRPC) // signal end to rpcImpl\n this.rpcImpl(null, null, null);\n this.rpcImpl = null;\n this.emit(\"end\").off();\n }\n return this;\n};\n","\"use strict\";\nmodule.exports = LongBits;\n\nvar util = require(15);\n\n/**\n * Constructs new long bits.\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @constructor\n * @param {number} lo Low 32 bits, unsigned\n * @param {number} hi High 32 bits, unsigned\n */\nfunction LongBits(lo, hi) {\n\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits.\n * @type {number}\n */\n this.lo = lo >>> 0;\n\n /**\n * High bits.\n * @type {number}\n */\n this.hi = hi >>> 0;\n}\n\n/**\n * Zero bits.\n * @memberof util.LongBits\n * @type {util.LongBits}\n */\nvar zero = LongBits.zero = new LongBits(0, 0);\n\nzero.toNumber = function() { return 0; };\nzero.zzEncode = zero.zzDecode = function() { return this; };\nzero.length = function() { return 1; };\n\n/**\n * Zero hash.\n * @memberof util.LongBits\n * @type {string}\n */\nvar zeroHash = LongBits.zeroHash = \"\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n/**\n * Constructs new long bits from the specified number.\n * @param {number} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.fromNumber = function fromNumber(value) {\n if (value === 0)\n return zero;\n var sign = value < 0;\n if (sign)\n value = -value;\n var lo = value >>> 0,\n hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295)\n hi = 0;\n }\n }\n return new LongBits(lo, hi);\n};\n\n/**\n * Constructs new long bits from a number, long or string.\n * @param {Long|number|string} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.from = function from(value) {\n if (typeof value === \"number\")\n return LongBits.fromNumber(value);\n if (util.isString(value)) {\n /* istanbul ignore else */\n if (util.Long)\n value = util.Long.fromString(value);\n else\n return LongBits.fromNumber(parseInt(value, 10));\n }\n return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n};\n\n/**\n * Converts this long bits to a possibly unsafe JavaScript number.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {number} Possibly unsafe number\n */\nLongBits.prototype.toNumber = function toNumber(unsigned) {\n if (!unsigned && this.hi >>> 31) {\n var lo = ~this.lo + 1 >>> 0,\n hi = ~this.hi >>> 0;\n if (!lo)\n hi = hi + 1 >>> 0;\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n};\n\n/**\n * Converts this long bits to a long.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long} Long\n */\nLongBits.prototype.toLong = function toLong(unsigned) {\n return util.Long\n ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))\n /* istanbul ignore next */\n : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };\n};\n\nvar charCodeAt = String.prototype.charCodeAt;\n\n/**\n * Constructs new long bits from the specified 8 characters long hash.\n * @param {string} hash Hash\n * @returns {util.LongBits} Bits\n */\nLongBits.fromHash = function fromHash(hash) {\n if (hash === zeroHash)\n return zero;\n return new LongBits(\n ( charCodeAt.call(hash, 0)\n | charCodeAt.call(hash, 1) << 8\n | charCodeAt.call(hash, 2) << 16\n | charCodeAt.call(hash, 3) << 24) >>> 0\n ,\n ( charCodeAt.call(hash, 4)\n | charCodeAt.call(hash, 5) << 8\n | charCodeAt.call(hash, 6) << 16\n | charCodeAt.call(hash, 7) << 24) >>> 0\n );\n};\n\n/**\n * Converts this long bits to a 8 characters long hash.\n * @returns {string} Hash\n */\nLongBits.prototype.toHash = function toHash() {\n return String.fromCharCode(\n this.lo & 255,\n this.lo >>> 8 & 255,\n this.lo >>> 16 & 255,\n this.lo >>> 24 ,\n this.hi & 255,\n this.hi >>> 8 & 255,\n this.hi >>> 16 & 255,\n this.hi >>> 24\n );\n};\n\n/**\n * Zig-zag encodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzEncode = function zzEncode() {\n var mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = ( this.lo << 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Zig-zag decodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzDecode = function zzDecode() {\n var mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = ( this.hi >>> 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Calculates the length of this longbits when encoded as a varint.\n * @returns {number} Length\n */\nLongBits.prototype.length = function length() {\n var part0 = this.lo,\n part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,\n part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n};\n","\"use strict\";\nvar util = exports;\n\n// used to return a Promise where callback is omitted\nutil.asPromise = require(1);\n\n// converts to / from base64 encoded strings\nutil.base64 = require(2);\n\n// base class of rpc.Service\nutil.EventEmitter = require(3);\n\n// float handling accross browsers\nutil.float = require(4);\n\n// requires modules optionally and hides the call from bundlers\nutil.inquire = require(5);\n\n// converts to / from utf8 encoded strings\nutil.utf8 = require(7);\n\n// provides a node-like buffer pool in the browser\nutil.pool = require(6);\n\n// utility to work with the low and high bits of a 64 bit value\nutil.LongBits = require(14);\n\n/**\n * Whether running within node or not.\n * @memberof util\n * @type {boolean}\n */\nutil.isNode = Boolean(typeof global !== \"undefined\"\n && global\n && global.process\n && global.process.versions\n && global.process.versions.node);\n\n/**\n * Global object reference.\n * @memberof util\n * @type {Object}\n */\nutil.global = util.isNode && global\n || typeof window !== \"undefined\" && window\n || typeof self !== \"undefined\" && self\n || this; // eslint-disable-line no-invalid-this\n\n/**\n * An immuable empty array.\n * @memberof util\n * @type {Array.<*>}\n * @const\n */\nutil.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes\n\n/**\n * An immutable empty object.\n * @type {Object}\n * @const\n */\nutil.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes\n\n/**\n * Tests if the specified value is an integer.\n * @function\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is an integer\n */\nutil.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {\n return typeof value === \"number\" && isFinite(value) && Math.floor(value) === value;\n};\n\n/**\n * Tests if the specified value is a string.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a string\n */\nutil.isString = function isString(value) {\n return typeof value === \"string\" || value instanceof String;\n};\n\n/**\n * Tests if the specified value is a non-null object.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a non-null object\n */\nutil.isObject = function isObject(value) {\n return value && typeof value === \"object\";\n};\n\n/**\n * Checks if a property on a message is considered to be present.\n * This is an alias of {@link util.isSet}.\n * @function\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isset =\n\n/**\n * Checks if a property on a message is considered to be present.\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isSet = function isSet(obj, prop) {\n var value = obj[prop];\n if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins\n return typeof value !== \"object\" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;\n return false;\n};\n\n/**\n * Any compatible Buffer instance.\n * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.\n * @interface Buffer\n * @extends Uint8Array\n */\n\n/**\n * Node's Buffer class if available.\n * @type {Constructor}\n */\nutil.Buffer = (function() {\n try {\n var Buffer = util.inquire(\"buffer\").Buffer;\n // refuse to use non-node buffers if not explicitly assigned (perf reasons):\n return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;\n } catch (e) {\n /* istanbul ignore next */\n return null;\n }\n})();\n\n// Internal alias of or polyfull for Buffer.from.\nutil._Buffer_from = null;\n\n// Internal alias of or polyfill for Buffer.allocUnsafe.\nutil._Buffer_allocUnsafe = null;\n\n/**\n * Creates a new buffer of whatever type supported by the environment.\n * @param {number|number[]} [sizeOrArray=0] Buffer size or number array\n * @returns {Uint8Array|Buffer} Buffer\n */\nutil.newBuffer = function newBuffer(sizeOrArray) {\n /* istanbul ignore next */\n return typeof sizeOrArray === \"number\"\n ? util.Buffer\n ? util._Buffer_allocUnsafe(sizeOrArray)\n : new util.Array(sizeOrArray)\n : util.Buffer\n ? util._Buffer_from(sizeOrArray)\n : typeof Uint8Array === \"undefined\"\n ? sizeOrArray\n : new Uint8Array(sizeOrArray);\n};\n\n/**\n * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.\n * @type {Constructor}\n */\nutil.Array = typeof Uint8Array !== \"undefined\" ? Uint8Array /* istanbul ignore next */ : Array;\n\n/**\n * Any compatible Long instance.\n * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.\n * @interface Long\n * @property {number} low Low bits\n * @property {number} high High bits\n * @property {boolean} unsigned Whether unsigned or not\n */\n\n/**\n * Long.js's Long class if available.\n * @type {Constructor}\n */\nutil.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long\n || /* istanbul ignore next */ util.global.Long\n || util.inquire(\"long\");\n\n/**\n * Regular expression used to verify 2 bit (`bool`) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key2Re = /^true|false|0|1$/;\n\n/**\n * Regular expression used to verify 32 bit (`int32` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key32Re = /^-?(?:0|[1-9][0-9]*)$/;\n\n/**\n * Regular expression used to verify 64 bit (`int64` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key64Re = /^(?:[\\\\x00-\\\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;\n\n/**\n * Converts a number or long to an 8 characters long hash string.\n * @param {Long|number} value Value to convert\n * @returns {string} Hash\n */\nutil.longToHash = function longToHash(value) {\n return value\n ? util.LongBits.from(value).toHash()\n : util.LongBits.zeroHash;\n};\n\n/**\n * Converts an 8 characters long hash string to a long or number.\n * @param {string} hash Hash\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long|number} Original value\n */\nutil.longFromHash = function longFromHash(hash, unsigned) {\n var bits = util.LongBits.fromHash(hash);\n if (util.Long)\n return util.Long.fromBits(bits.lo, bits.hi, unsigned);\n return bits.toNumber(Boolean(unsigned));\n};\n\n/**\n * Merges the properties of the source object into the destination object.\n * @memberof util\n * @param {Object.} dst Destination object\n * @param {Object.} src Source object\n * @param {boolean} [ifNotSet=false] Merges only if the key is not already set\n * @returns {Object.} Destination object\n */\nfunction merge(dst, src, ifNotSet) { // used by converters\n for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)\n if (dst[keys[i]] === undefined || !ifNotSet)\n dst[keys[i]] = src[keys[i]];\n return dst;\n}\n\nutil.merge = merge;\n\n/**\n * Converts the first character of a string to lower case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.lcFirst = function lcFirst(str) {\n return str.charAt(0).toLowerCase() + str.substring(1);\n};\n\n/**\n * Creates a custom error constructor.\n * @memberof util\n * @param {string} name Error name\n * @returns {Constructor} Custom error constructor\n */\nfunction newError(name) {\n\n function CustomError(message, properties) {\n\n if (!(this instanceof CustomError))\n return new CustomError(message, properties);\n\n // Error.call(this, message);\n // ^ just returns a new error instance because the ctor can be called as a function\n\n Object.defineProperty(this, \"message\", { get: function() { return message; } });\n\n /* istanbul ignore next */\n if (Error.captureStackTrace) // node\n Error.captureStackTrace(this, CustomError);\n else\n Object.defineProperty(this, \"stack\", { value: new Error().stack || \"\" });\n\n if (properties)\n merge(this, properties);\n }\n\n CustomError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: CustomError,\n writable: true,\n enumerable: false,\n configurable: true,\n },\n name: {\n get: function get() { return name; },\n set: undefined,\n enumerable: false,\n // configurable: false would accurately preserve the behavior of\n // the original, but I'm guessing that was not intentional.\n // For an actual error subclass, this property would\n // be configurable.\n configurable: true,\n },\n toString: {\n value: function value() { return this.name + \": \" + this.message; },\n writable: true,\n enumerable: false,\n configurable: true,\n },\n });\n\n return CustomError;\n}\n\nutil.newError = newError;\n\n/**\n * Constructs a new protocol error.\n * @classdesc Error subclass indicating a protocol specifc error.\n * @memberof util\n * @extends Error\n * @template T extends Message\n * @constructor\n * @param {string} message Error message\n * @param {Object.} [properties] Additional properties\n * @example\n * try {\n * MyMessage.decode(someBuffer); // throws if required fields are missing\n * } catch (e) {\n * if (e instanceof ProtocolError && e.instance)\n * console.log(\"decoded so far: \" + JSON.stringify(e.instance));\n * }\n */\nutil.ProtocolError = newError(\"ProtocolError\");\n\n/**\n * So far decoded message instance.\n * @name util.ProtocolError#instance\n * @type {Message}\n */\n\n/**\n * A OneOf getter as returned by {@link util.oneOfGetter}.\n * @typedef OneOfGetter\n * @type {function}\n * @returns {string|undefined} Set field name, if any\n */\n\n/**\n * Builds a getter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfGetter} Unbound getter\n */\nutil.oneOfGetter = function getOneOf(fieldNames) {\n var fieldMap = {};\n for (var i = 0; i < fieldNames.length; ++i)\n fieldMap[fieldNames[i]] = 1;\n\n /**\n * @returns {string|undefined} Set field name, if any\n * @this Object\n * @ignore\n */\n return function() { // eslint-disable-line consistent-return\n for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)\n if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)\n return keys[i];\n };\n};\n\n/**\n * A OneOf setter as returned by {@link util.oneOfSetter}.\n * @typedef OneOfSetter\n * @type {function}\n * @param {string|undefined} value Field name\n * @returns {undefined}\n */\n\n/**\n * Builds a setter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfSetter} Unbound setter\n */\nutil.oneOfSetter = function setOneOf(fieldNames) {\n\n /**\n * @param {string} name Field name\n * @returns {undefined}\n * @this Object\n * @ignore\n */\n return function(name) {\n for (var i = 0; i < fieldNames.length; ++i)\n if (fieldNames[i] !== name)\n delete this[fieldNames[i]];\n };\n};\n\n/**\n * Default conversion options used for {@link Message#toJSON} implementations.\n *\n * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:\n *\n * - Longs become strings\n * - Enums become string keys\n * - Bytes become base64 encoded strings\n * - (Sub-)Messages become plain objects\n * - Maps become plain objects with all string keys\n * - Repeated fields become arrays\n * - NaN and Infinity for float and double fields become strings\n *\n * @type {IConversionOptions}\n * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json\n */\nutil.toJSONOptions = {\n longs: String,\n enums: String,\n bytes: String,\n json: true\n};\n\n// Sets up buffer utility according to the environment (called in index-minimal)\nutil._configure = function() {\n var Buffer = util.Buffer;\n /* istanbul ignore if */\n if (!Buffer) {\n util._Buffer_from = util._Buffer_allocUnsafe = null;\n return;\n }\n // because node 4.x buffers are incompatible & immutable\n // see: https://github.com/dcodeIO/protobuf.js/pull/665\n util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||\n /* istanbul ignore next */\n function Buffer_from(value, encoding) {\n return new Buffer(value, encoding);\n };\n util._Buffer_allocUnsafe = Buffer.allocUnsafe ||\n /* istanbul ignore next */\n function Buffer_allocUnsafe(size) {\n return new Buffer(size);\n };\n};\n","\"use strict\";\nmodule.exports = Writer;\n\nvar util = require(15);\n\nvar BufferWriter; // cyclic\n\nvar LongBits = util.LongBits,\n base64 = util.base64,\n utf8 = util.utf8;\n\n/**\n * Constructs a new writer operation instance.\n * @classdesc Scheduled writer operation.\n * @constructor\n * @param {function(*, Uint8Array, number)} fn Function to call\n * @param {number} len Value byte length\n * @param {*} val Value to write\n * @ignore\n */\nfunction Op(fn, len, val) {\n\n /**\n * Function to call.\n * @type {function(Uint8Array, number, *)}\n */\n this.fn = fn;\n\n /**\n * Value byte length.\n * @type {number}\n */\n this.len = len;\n\n /**\n * Next operation.\n * @type {Writer.Op|undefined}\n */\n this.next = undefined;\n\n /**\n * Value to write.\n * @type {*}\n */\n this.val = val; // type varies\n}\n\n/* istanbul ignore next */\nfunction noop() {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance.\n * @classdesc Copied writer state.\n * @memberof Writer\n * @constructor\n * @param {Writer} writer Writer to copy state from\n * @ignore\n */\nfunction State(writer) {\n\n /**\n * Current head.\n * @type {Writer.Op}\n */\n this.head = writer.head;\n\n /**\n * Current tail.\n * @type {Writer.Op}\n */\n this.tail = writer.tail;\n\n /**\n * Current buffer length.\n * @type {number}\n */\n this.len = writer.len;\n\n /**\n * Next state.\n * @type {State|null}\n */\n this.next = writer.states;\n}\n\n/**\n * Constructs a new writer instance.\n * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n */\nfunction Writer() {\n\n /**\n * Current length.\n * @type {number}\n */\n this.len = 0;\n\n /**\n * Operations head.\n * @type {Object}\n */\n this.head = new Op(noop, 0, 0);\n\n /**\n * Operations tail\n * @type {Object}\n */\n this.tail = this.head;\n\n /**\n * Linked forked states.\n * @type {Object|null}\n */\n this.states = null;\n\n // When a value is written, the writer calculates its byte length and puts it into a linked\n // list of operations to perform when finish() is called. This both allows us to allocate\n // buffers of the exact required size and reduces the amount of work we have to do compared\n // to first calculating over objects and then encoding over objects. In our case, the encoding\n // part is just a linked list walk calling operations with already prepared values.\n}\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup() {\n return (Writer.create = function create_buffer() {\n return new BufferWriter();\n })();\n }\n /* istanbul ignore next */\n : function create_array() {\n return new Writer();\n };\n};\n\n/**\n * Creates a new writer.\n * @function\n * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}\n */\nWriter.create = create();\n\n/**\n * Allocates a buffer of the specified size.\n * @param {number} size Buffer size\n * @returns {Uint8Array} Buffer\n */\nWriter.alloc = function alloc(size) {\n return new util.Array(size);\n};\n\n// Use Uint8Array buffer pool in the browser, just like node does with buffers\n/* istanbul ignore else */\nif (util.Array !== Array)\n Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);\n\n/**\n * Pushes a new operation to the queue.\n * @param {function(Uint8Array, number, *)} fn Function to call\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @returns {Writer} `this`\n * @private\n */\nWriter.prototype._push = function push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n};\n\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\n\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n\n/**\n * Constructs a new varint writer operation instance.\n * @classdesc Scheduled varint writer operation.\n * @extends Op\n * @constructor\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @ignore\n */\nfunction VarintOp(len, val) {\n this.len = len;\n this.next = undefined;\n this.val = val;\n}\n\nVarintOp.prototype = Object.create(Op.prototype);\nVarintOp.prototype.fn = writeVarint32;\n\n/**\n * Writes an unsigned 32 bit value as a varint.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.uint32 = function write_uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0)\n < 128 ? 1\n : value < 16384 ? 2\n : value < 2097152 ? 3\n : value < 268435456 ? 4\n : 5,\n value)).len;\n return this;\n};\n\n/**\n * Writes a signed 32 bit value as a varint.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.int32 = function write_int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n};\n\n/**\n * Writes a 32 bit value as a varint, zig-zag encoded.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sint32 = function write_sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n};\n\nfunction writeVarint64(val, buf, pos) {\n while (val.hi) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\n\n/**\n * Writes an unsigned 64 bit value as a varint.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.uint64 = function write_uint64(value) {\n var bits = LongBits.from(value);\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a signed 64 bit value as a varint.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.int64 = Writer.prototype.uint64;\n\n/**\n * Writes a signed 64 bit value as a varint, zig-zag encoded.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sint64 = function write_sint64(value) {\n var bits = LongBits.from(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a boolish value as a varint.\n * @param {boolean} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bool = function write_bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n};\n\nfunction writeFixed32(val, buf, pos) {\n buf[pos ] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\n\n/**\n * Writes an unsigned 32 bit value as fixed 32 bits.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.fixed32 = function write_fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n};\n\n/**\n * Writes a signed 32 bit value as fixed 32 bits.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sfixed32 = Writer.prototype.fixed32;\n\n/**\n * Writes an unsigned 64 bit value as fixed 64 bits.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.fixed64 = function write_fixed64(value) {\n var bits = LongBits.from(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n};\n\n/**\n * Writes a signed 64 bit value as fixed 64 bits.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sfixed64 = Writer.prototype.fixed64;\n\n/**\n * Writes a float (32 bit).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.float = function write_float(value) {\n return this._push(util.float.writeFloatLE, 4, value);\n};\n\n/**\n * Writes a double (64 bit float).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.double = function write_double(value) {\n return this._push(util.float.writeDoubleLE, 8, value);\n};\n\nvar writeBytes = util.Array.prototype.set\n ? function writeBytes_set(val, buf, pos) {\n buf.set(val, pos); // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytes_for(val, buf, pos) {\n for (var i = 0; i < val.length; ++i)\n buf[pos + i] = val[i];\n };\n\n/**\n * Writes a sequence of bytes.\n * @param {Uint8Array|string} value Buffer or base64 encoded string to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bytes = function write_bytes(value) {\n var len = value.length >>> 0;\n if (!len)\n return this._push(writeByte, 1, 0);\n if (util.isString(value)) {\n var buf = Writer.alloc(len = base64.length(value));\n base64.decode(value, buf, 0);\n value = buf;\n }\n return this.uint32(len)._push(writeBytes, len, value);\n};\n\n/**\n * Writes a string.\n * @param {string} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.string = function write_string(value) {\n var len = utf8.length(value);\n return len\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0);\n};\n\n/**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n * @returns {Writer} `this`\n */\nWriter.prototype.fork = function fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n};\n\n/**\n * Resets this instance to the last state.\n * @returns {Writer} `this`\n */\nWriter.prototype.reset = function reset() {\n if (this.states) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n } else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n};\n\n/**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n * @returns {Writer} `this`\n */\nWriter.prototype.ldelim = function ldelim() {\n var head = this.head,\n tail = this.tail,\n len = this.len;\n this.reset().uint32(len);\n if (len) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n};\n\n/**\n * Finishes the write operation.\n * @returns {Uint8Array} Finished buffer\n */\nWriter.prototype.finish = function finish() {\n var head = this.head.next, // skip noop\n buf = this.constructor.alloc(this.len),\n pos = 0;\n while (head) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n};\n\nWriter._configure = function(BufferWriter_) {\n BufferWriter = BufferWriter_;\n Writer.create = create();\n BufferWriter._configure();\n};\n","\"use strict\";\nmodule.exports = BufferWriter;\n\n// extends Writer\nvar Writer = require(16);\n(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;\n\nvar util = require(15);\n\n/**\n * Constructs a new buffer writer instance.\n * @classdesc Wire format writer using node buffers.\n * @extends Writer\n * @constructor\n */\nfunction BufferWriter() {\n Writer.call(this);\n}\n\nBufferWriter._configure = function () {\n /**\n * Allocates a buffer of the specified size.\n * @function\n * @param {number} size Buffer size\n * @returns {Buffer} Buffer\n */\n BufferWriter.alloc = util._Buffer_allocUnsafe;\n\n BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === \"set\"\n ? function writeBytesBuffer_set(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytesBuffer_copy(val, buf, pos) {\n if (val.copy) // Buffer values\n val.copy(buf, pos, 0, val.length);\n else for (var i = 0; i < val.length;) // plain array values\n buf[pos++] = val[i++];\n };\n};\n\n\n/**\n * @override\n */\nBufferWriter.prototype.bytes = function write_bytes_buffer(value) {\n if (util.isString(value))\n value = util._Buffer_from(value, \"base64\");\n var len = value.length >>> 0;\n this.uint32(len);\n if (len)\n this._push(BufferWriter.writeBytesBuffer, len, value);\n return this;\n};\n\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)\n util.utf8.write(val, buf, pos);\n else if (buf.utf8Write)\n buf.utf8Write(val, pos);\n else\n buf.write(val, pos);\n}\n\n/**\n * @override\n */\nBufferWriter.prototype.string = function write_string_buffer(value) {\n var len = util.Buffer.byteLength(value);\n this.uint32(len);\n if (len)\n this._push(writeStringBuffer, len, value);\n return this;\n};\n\n\n/**\n * Finishes the write operation.\n * @name BufferWriter#finish\n * @function\n * @returns {Buffer} Finished buffer\n */\n\nBufferWriter._configure();\n"],"sourceRoot":"."} \ No newline at end of file diff --git a/node_modules/protobufjs/dist/protobuf.js b/node_modules/protobufjs/dist/protobuf.js new file mode 100644 index 0000000..4a0ef99 --- /dev/null +++ b/node_modules/protobufjs/dist/protobuf.js @@ -0,0 +1,9637 @@ +/*! + * protobuf.js v7.5.4 (c) 2016, daniel wirtz + * compiled fri, 15 aug 2025 23:28:54 utc + * licensed under the bsd-3-clause license + * see: https://github.com/dcodeio/protobuf.js for details + */ +(function(undefined){"use strict";(function prelude(modules, cache, entries) { + + // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS + // sources through a conflict-free require shim and is again wrapped within an iife that + // provides a minification-friendly `undefined` var plus a global "use strict" directive + // so that minification can remove the directives of each module. + + function $require(name) { + var $module = cache[name]; + if (!$module) + modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports); + return $module.exports; + } + + var protobuf = $require(entries[0]); + + // Expose globally + protobuf.util.global.protobuf = protobuf; + + // Be nice to AMD + if (typeof define === "function" && define.amd) + define(["long"], function(Long) { + if (Long && Long.isLong) { + protobuf.util.Long = Long; + protobuf.configure(); + } + return protobuf; + }); + + // Be nice to CommonJS + if (typeof module === "object" && module && module.exports) + module.exports = protobuf; + +})/* end of prelude */({1:[function(require,module,exports){ +"use strict"; +module.exports = asPromise; + +/** + * Callback as used by {@link util.asPromise}. + * @typedef asPromiseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {...*} params Additional arguments + * @returns {undefined} + */ + +/** + * Returns a promise from a node-style callback function. + * @memberof util + * @param {asPromiseCallback} fn Function to call + * @param {*} ctx Function context + * @param {...*} params Function arguments + * @returns {Promise<*>} Promisified function + */ +function asPromise(fn, ctx/*, varargs */) { + var params = new Array(arguments.length - 1), + offset = 0, + index = 2, + pending = true; + while (index < arguments.length) + params[offset++] = arguments[index++]; + return new Promise(function executor(resolve, reject) { + params[offset] = function callback(err/*, varargs */) { + if (pending) { + pending = false; + if (err) + reject(err); + else { + var params = new Array(arguments.length - 1), + offset = 0; + while (offset < params.length) + params[offset++] = arguments[offset]; + resolve.apply(null, params); + } + } + }; + try { + fn.apply(ctx || null, params); + } catch (err) { + if (pending) { + pending = false; + reject(err); + } + } + }); +} + +},{}],2:[function(require,module,exports){ +"use strict"; + +/** + * A minimal base64 implementation for number arrays. + * @memberof util + * @namespace + */ +var base64 = exports; + +/** + * Calculates the byte length of a base64 encoded string. + * @param {string} string Base64 encoded string + * @returns {number} Byte length + */ +base64.length = function length(string) { + var p = string.length; + if (!p) + return 0; + var n = 0; + while (--p % 4 > 1 && string.charAt(p) === "=") + ++n; + return Math.ceil(string.length * 3) / 4 - n; +}; + +// Base64 encoding table +var b64 = new Array(64); + +// Base64 decoding table +var s64 = new Array(123); + +// 65..90, 97..122, 48..57, 43, 47 +for (var i = 0; i < 64;) + s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; + +/** + * Encodes a buffer to a base64 encoded string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} Base64 encoded string + */ +base64.encode = function encode(buffer, start, end) { + var parts = null, + chunk = []; + var i = 0, // output index + j = 0, // goto index + t; // temporary + while (start < end) { + var b = buffer[start++]; + switch (j) { + case 0: + chunk[i++] = b64[b >> 2]; + t = (b & 3) << 4; + j = 1; + break; + case 1: + chunk[i++] = b64[t | b >> 4]; + t = (b & 15) << 2; + j = 2; + break; + case 2: + chunk[i++] = b64[t | b >> 6]; + chunk[i++] = b64[b & 63]; + j = 0; + break; + } + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i = 0; + } + } + if (j) { + chunk[i++] = b64[t]; + chunk[i++] = 61; + if (j === 1) + chunk[i++] = 61; + } + if (parts) { + if (i) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i)); +}; + +var invalidEncoding = "invalid encoding"; + +/** + * Decodes a base64 encoded string to a buffer. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Number of bytes written + * @throws {Error} If encoding is invalid + */ +base64.decode = function decode(string, buffer, offset) { + var start = offset; + var j = 0, // goto index + t; // temporary + for (var i = 0; i < string.length;) { + var c = string.charCodeAt(i++); + if (c === 61 && j > 1) + break; + if ((c = s64[c]) === undefined) + throw Error(invalidEncoding); + switch (j) { + case 0: + t = c; + j = 1; + break; + case 1: + buffer[offset++] = t << 2 | (c & 48) >> 4; + t = c; + j = 2; + break; + case 2: + buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; + t = c; + j = 3; + break; + case 3: + buffer[offset++] = (t & 3) << 6 | c; + j = 0; + break; + } + } + if (j === 1) + throw Error(invalidEncoding); + return offset - start; +}; + +/** + * Tests if the specified string appears to be base64 encoded. + * @param {string} string String to test + * @returns {boolean} `true` if probably base64 encoded, otherwise false + */ +base64.test = function test(string) { + return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string); +}; + +},{}],3:[function(require,module,exports){ +"use strict"; +module.exports = codegen; + +/** + * Begins generating a function. + * @memberof util + * @param {string[]} functionParams Function parameter names + * @param {string} [functionName] Function name if not anonymous + * @returns {Codegen} Appender that appends code to the function's body + */ +function codegen(functionParams, functionName) { + + /* istanbul ignore if */ + if (typeof functionParams === "string") { + functionName = functionParams; + functionParams = undefined; + } + + var body = []; + + /** + * Appends code to the function's body or finishes generation. + * @typedef Codegen + * @type {function} + * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any + * @param {...*} [formatParams] Format parameters + * @returns {Codegen|Function} Itself or the generated function if finished + * @throws {Error} If format parameter counts do not match + */ + + function Codegen(formatStringOrScope) { + // note that explicit array handling below makes this ~50% faster + + // finish the function + if (typeof formatStringOrScope !== "string") { + var source = toString(); + if (codegen.verbose) + console.log("codegen: " + source); // eslint-disable-line no-console + source = "return " + source; + if (formatStringOrScope) { + var scopeKeys = Object.keys(formatStringOrScope), + scopeParams = new Array(scopeKeys.length + 1), + scopeValues = new Array(scopeKeys.length), + scopeOffset = 0; + while (scopeOffset < scopeKeys.length) { + scopeParams[scopeOffset] = scopeKeys[scopeOffset]; + scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]]; + } + scopeParams[scopeOffset] = source; + return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func + } + return Function(source)(); // eslint-disable-line no-new-func + } + + // otherwise append to body + var formatParams = new Array(arguments.length - 1), + formatOffset = 0; + while (formatOffset < formatParams.length) + formatParams[formatOffset] = arguments[++formatOffset]; + formatOffset = 0; + formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) { + var value = formatParams[formatOffset++]; + switch ($1) { + case "d": case "f": return String(Number(value)); + case "i": return String(Math.floor(value)); + case "j": return JSON.stringify(value); + case "s": return String(value); + } + return "%"; + }); + if (formatOffset !== formatParams.length) + throw Error("parameter count mismatch"); + body.push(formatStringOrScope); + return Codegen; + } + + function toString(functionNameOverride) { + return "function " + (functionNameOverride || functionName || "") + "(" + (functionParams && functionParams.join(",") || "") + "){\n " + body.join("\n ") + "\n}"; + } + + Codegen.toString = toString; + return Codegen; +} + +/** + * Begins generating a function. + * @memberof util + * @function codegen + * @param {string} [functionName] Function name if not anonymous + * @returns {Codegen} Appender that appends code to the function's body + * @variation 2 + */ + +/** + * When set to `true`, codegen will log generated code to console. Useful for debugging. + * @name util.codegen.verbose + * @type {boolean} + */ +codegen.verbose = false; + +},{}],4:[function(require,module,exports){ +"use strict"; +module.exports = EventEmitter; + +/** + * Constructs a new event emitter instance. + * @classdesc A minimal event emitter. + * @memberof util + * @constructor + */ +function EventEmitter() { + + /** + * Registered listeners. + * @type {Object.} + * @private + */ + this._listeners = {}; +} + +/** + * Registers an event listener. + * @param {string} evt Event name + * @param {function} fn Listener + * @param {*} [ctx] Listener context + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.on = function on(evt, fn, ctx) { + (this._listeners[evt] || (this._listeners[evt] = [])).push({ + fn : fn, + ctx : ctx || this + }); + return this; +}; + +/** + * Removes an event listener or any matching listeners if arguments are omitted. + * @param {string} [evt] Event name. Removes all listeners if omitted. + * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted. + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.off = function off(evt, fn) { + if (evt === undefined) + this._listeners = {}; + else { + if (fn === undefined) + this._listeners[evt] = []; + else { + var listeners = this._listeners[evt]; + for (var i = 0; i < listeners.length;) + if (listeners[i].fn === fn) + listeners.splice(i, 1); + else + ++i; + } + } + return this; +}; + +/** + * Emits an event by calling its listeners with the specified arguments. + * @param {string} evt Event name + * @param {...*} args Arguments + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.emit = function emit(evt) { + var listeners = this._listeners[evt]; + if (listeners) { + var args = [], + i = 1; + for (; i < arguments.length;) + args.push(arguments[i++]); + for (i = 0; i < listeners.length;) + listeners[i].fn.apply(listeners[i++].ctx, args); + } + return this; +}; + +},{}],5:[function(require,module,exports){ +"use strict"; +module.exports = fetch; + +var asPromise = require(1), + inquire = require(7); + +var fs = inquire("fs"); + +/** + * Node-style callback as used by {@link util.fetch}. + * @typedef FetchCallback + * @type {function} + * @param {?Error} error Error, if any, otherwise `null` + * @param {string} [contents] File contents, if there hasn't been an error + * @returns {undefined} + */ + +/** + * Options as used by {@link util.fetch}. + * @typedef FetchOptions + * @type {Object} + * @property {boolean} [binary=false] Whether expecting a binary response + * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest + */ + +/** + * Fetches the contents of a file. + * @memberof util + * @param {string} filename File path or url + * @param {FetchOptions} options Fetch options + * @param {FetchCallback} callback Callback function + * @returns {undefined} + */ +function fetch(filename, options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; + } else if (!options) + options = {}; + + if (!callback) + return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this + + // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found. + if (!options.xhr && fs && fs.readFile) + return fs.readFile(filename, function fetchReadFileCallback(err, contents) { + return err && typeof XMLHttpRequest !== "undefined" + ? fetch.xhr(filename, options, callback) + : err + ? callback(err) + : callback(null, options.binary ? contents : contents.toString("utf8")); + }); + + // use the XHR version otherwise. + return fetch.xhr(filename, options, callback); +} + +/** + * Fetches the contents of a file. + * @name util.fetch + * @function + * @param {string} path File path or url + * @param {FetchCallback} callback Callback function + * @returns {undefined} + * @variation 2 + */ + +/** + * Fetches the contents of a file. + * @name util.fetch + * @function + * @param {string} path File path or url + * @param {FetchOptions} [options] Fetch options + * @returns {Promise} Promise + * @variation 3 + */ + +/**/ +fetch.xhr = function fetch_xhr(filename, options, callback) { + var xhr = new XMLHttpRequest(); + xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() { + + if (xhr.readyState !== 4) + return undefined; + + // local cors security errors return status 0 / empty string, too. afaik this cannot be + // reliably distinguished from an actually empty file for security reasons. feel free + // to send a pull request if you are aware of a solution. + if (xhr.status !== 0 && xhr.status !== 200) + return callback(Error("status " + xhr.status)); + + // if binary data is expected, make sure that some sort of array is returned, even if + // ArrayBuffers are not supported. the binary string fallback, however, is unsafe. + if (options.binary) { + var buffer = xhr.response; + if (!buffer) { + buffer = []; + for (var i = 0; i < xhr.responseText.length; ++i) + buffer.push(xhr.responseText.charCodeAt(i) & 255); + } + return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer); + } + return callback(null, xhr.responseText); + }; + + if (options.binary) { + // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers + if ("overrideMimeType" in xhr) + xhr.overrideMimeType("text/plain; charset=x-user-defined"); + xhr.responseType = "arraybuffer"; + } + + xhr.open("GET", filename); + xhr.send(); +}; + +},{"1":1,"7":7}],6:[function(require,module,exports){ +"use strict"; + +module.exports = factory(factory); + +/** + * Reads / writes floats / doubles from / to buffers. + * @name util.float + * @namespace + */ + +/** + * Writes a 32 bit float to a buffer using little endian byte order. + * @name util.float.writeFloatLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Writes a 32 bit float to a buffer using big endian byte order. + * @name util.float.writeFloatBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Reads a 32 bit float from a buffer using little endian byte order. + * @name util.float.readFloatLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Reads a 32 bit float from a buffer using big endian byte order. + * @name util.float.readFloatBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Writes a 64 bit double to a buffer using little endian byte order. + * @name util.float.writeDoubleLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Writes a 64 bit double to a buffer using big endian byte order. + * @name util.float.writeDoubleBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Reads a 64 bit double from a buffer using little endian byte order. + * @name util.float.readDoubleLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Reads a 64 bit double from a buffer using big endian byte order. + * @name util.float.readDoubleBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +// Factory function for the purpose of node-based testing in modified global environments +function factory(exports) { + + // float: typed array + if (typeof Float32Array !== "undefined") (function() { + + var f32 = new Float32Array([ -0 ]), + f8b = new Uint8Array(f32.buffer), + le = f8b[3] === 128; + + function writeFloat_f32_cpy(val, buf, pos) { + f32[0] = val; + buf[pos ] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + } + + function writeFloat_f32_rev(val, buf, pos) { + f32[0] = val; + buf[pos ] = f8b[3]; + buf[pos + 1] = f8b[2]; + buf[pos + 2] = f8b[1]; + buf[pos + 3] = f8b[0]; + } + + /* istanbul ignore next */ + exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; + /* istanbul ignore next */ + exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; + + function readFloat_f32_cpy(buf, pos) { + f8b[0] = buf[pos ]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + return f32[0]; + } + + function readFloat_f32_rev(buf, pos) { + f8b[3] = buf[pos ]; + f8b[2] = buf[pos + 1]; + f8b[1] = buf[pos + 2]; + f8b[0] = buf[pos + 3]; + return f32[0]; + } + + /* istanbul ignore next */ + exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; + /* istanbul ignore next */ + exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; + + // float: ieee754 + })(); else (function() { + + function writeFloat_ieee754(writeUint, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) + writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos); + else if (isNaN(val)) + writeUint(2143289344, buf, pos); + else if (val > 3.4028234663852886e+38) // +-Infinity + writeUint((sign << 31 | 2139095040) >>> 0, buf, pos); + else if (val < 1.1754943508222875e-38) // denormal + writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos); + else { + var exponent = Math.floor(Math.log(val) / Math.LN2), + mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; + writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); + } + } + + exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); + exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); + + function readFloat_ieee754(readUint, buf, pos) { + var uint = readUint(buf, pos), + sign = (uint >> 31) * 2 + 1, + exponent = uint >>> 23 & 255, + mantissa = uint & 8388607; + return exponent === 255 + ? mantissa + ? NaN + : sign * Infinity + : exponent === 0 // denormal + ? sign * 1.401298464324817e-45 * mantissa + : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); + } + + exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE); + exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE); + + })(); + + // double: typed array + if (typeof Float64Array !== "undefined") (function() { + + var f64 = new Float64Array([-0]), + f8b = new Uint8Array(f64.buffer), + le = f8b[7] === 128; + + function writeDouble_f64_cpy(val, buf, pos) { + f64[0] = val; + buf[pos ] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + buf[pos + 4] = f8b[4]; + buf[pos + 5] = f8b[5]; + buf[pos + 6] = f8b[6]; + buf[pos + 7] = f8b[7]; + } + + function writeDouble_f64_rev(val, buf, pos) { + f64[0] = val; + buf[pos ] = f8b[7]; + buf[pos + 1] = f8b[6]; + buf[pos + 2] = f8b[5]; + buf[pos + 3] = f8b[4]; + buf[pos + 4] = f8b[3]; + buf[pos + 5] = f8b[2]; + buf[pos + 6] = f8b[1]; + buf[pos + 7] = f8b[0]; + } + + /* istanbul ignore next */ + exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; + /* istanbul ignore next */ + exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; + + function readDouble_f64_cpy(buf, pos) { + f8b[0] = buf[pos ]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + f8b[4] = buf[pos + 4]; + f8b[5] = buf[pos + 5]; + f8b[6] = buf[pos + 6]; + f8b[7] = buf[pos + 7]; + return f64[0]; + } + + function readDouble_f64_rev(buf, pos) { + f8b[7] = buf[pos ]; + f8b[6] = buf[pos + 1]; + f8b[5] = buf[pos + 2]; + f8b[4] = buf[pos + 3]; + f8b[3] = buf[pos + 4]; + f8b[2] = buf[pos + 5]; + f8b[1] = buf[pos + 6]; + f8b[0] = buf[pos + 7]; + return f64[0]; + } + + /* istanbul ignore next */ + exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; + /* istanbul ignore next */ + exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; + + // double: ieee754 + })(); else (function() { + + function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) { + writeUint(0, buf, pos + off0); + writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1); + } else if (isNaN(val)) { + writeUint(0, buf, pos + off0); + writeUint(2146959360, buf, pos + off1); + } else if (val > 1.7976931348623157e+308) { // +-Infinity + writeUint(0, buf, pos + off0); + writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1); + } else { + var mantissa; + if (val < 2.2250738585072014e-308) { // denormal + mantissa = val / 5e-324; + writeUint(mantissa >>> 0, buf, pos + off0); + writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); + } else { + var exponent = Math.floor(Math.log(val) / Math.LN2); + if (exponent === 1024) + exponent = 1023; + mantissa = val * Math.pow(2, -exponent); + writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); + writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); + } + } + } + + exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); + exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); + + function readDouble_ieee754(readUint, off0, off1, buf, pos) { + var lo = readUint(buf, pos + off0), + hi = readUint(buf, pos + off1); + var sign = (hi >> 31) * 2 + 1, + exponent = hi >>> 20 & 2047, + mantissa = 4294967296 * (hi & 1048575) + lo; + return exponent === 2047 + ? mantissa + ? NaN + : sign * Infinity + : exponent === 0 // denormal + ? sign * 5e-324 * mantissa + : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); + } + + exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); + exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); + + })(); + + return exports; +} + +// uint helpers + +function writeUintLE(val, buf, pos) { + buf[pos ] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; +} + +function writeUintBE(val, buf, pos) { + buf[pos ] = val >>> 24; + buf[pos + 1] = val >>> 16 & 255; + buf[pos + 2] = val >>> 8 & 255; + buf[pos + 3] = val & 255; +} + +function readUintLE(buf, pos) { + return (buf[pos ] + | buf[pos + 1] << 8 + | buf[pos + 2] << 16 + | buf[pos + 3] << 24) >>> 0; +} + +function readUintBE(buf, pos) { + return (buf[pos ] << 24 + | buf[pos + 1] << 16 + | buf[pos + 2] << 8 + | buf[pos + 3]) >>> 0; +} + +},{}],7:[function(require,module,exports){ +"use strict"; +module.exports = inquire; + +/** + * Requires a module only if available. + * @memberof util + * @param {string} moduleName Module to require + * @returns {?Object} Required module if available and not empty, otherwise `null` + */ +function inquire(moduleName) { + try { + var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval + if (mod && (mod.length || Object.keys(mod).length)) + return mod; + } catch (e) {} // eslint-disable-line no-empty + return null; +} + +},{}],8:[function(require,module,exports){ +"use strict"; + +/** + * A minimal path module to resolve Unix, Windows and URL paths alike. + * @memberof util + * @namespace + */ +var path = exports; + +var isAbsolute = +/** + * Tests if the specified path is absolute. + * @param {string} path Path to test + * @returns {boolean} `true` if path is absolute + */ +path.isAbsolute = function isAbsolute(path) { + return /^(?:\/|\w+:)/.test(path); +}; + +var normalize = +/** + * Normalizes the specified path. + * @param {string} path Path to normalize + * @returns {string} Normalized path + */ +path.normalize = function normalize(path) { + path = path.replace(/\\/g, "/") + .replace(/\/{2,}/g, "/"); + var parts = path.split("/"), + absolute = isAbsolute(path), + prefix = ""; + if (absolute) + prefix = parts.shift() + "/"; + for (var i = 0; i < parts.length;) { + if (parts[i] === "..") { + if (i > 0 && parts[i - 1] !== "..") + parts.splice(--i, 2); + else if (absolute) + parts.splice(i, 1); + else + ++i; + } else if (parts[i] === ".") + parts.splice(i, 1); + else + ++i; + } + return prefix + parts.join("/"); +}; + +/** + * Resolves the specified include path against the specified origin path. + * @param {string} originPath Path to the origin file + * @param {string} includePath Include path relative to origin path + * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized + * @returns {string} Path to the include file + */ +path.resolve = function resolve(originPath, includePath, alreadyNormalized) { + if (!alreadyNormalized) + includePath = normalize(includePath); + if (isAbsolute(includePath)) + return includePath; + if (!alreadyNormalized) + originPath = normalize(originPath); + return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath; +}; + +},{}],9:[function(require,module,exports){ +"use strict"; +module.exports = pool; + +/** + * An allocator as used by {@link util.pool}. + * @typedef PoolAllocator + * @type {function} + * @param {number} size Buffer size + * @returns {Uint8Array} Buffer + */ + +/** + * A slicer as used by {@link util.pool}. + * @typedef PoolSlicer + * @type {function} + * @param {number} start Start offset + * @param {number} end End offset + * @returns {Uint8Array} Buffer slice + * @this {Uint8Array} + */ + +/** + * A general purpose buffer pool. + * @memberof util + * @function + * @param {PoolAllocator} alloc Allocator + * @param {PoolSlicer} slice Slicer + * @param {number} [size=8192] Slab size + * @returns {PoolAllocator} Pooled allocator + */ +function pool(alloc, slice, size) { + var SIZE = size || 8192; + var MAX = SIZE >>> 1; + var slab = null; + var offset = SIZE; + return function pool_alloc(size) { + if (size < 1 || size > MAX) + return alloc(size); + if (offset + size > SIZE) { + slab = alloc(SIZE); + offset = 0; + } + var buf = slice.call(slab, offset, offset += size); + if (offset & 7) // align to 32 bit + offset = (offset | 7) + 1; + return buf; + }; +} + +},{}],10:[function(require,module,exports){ +"use strict"; + +/** + * A minimal UTF8 implementation for number arrays. + * @memberof util + * @namespace + */ +var utf8 = exports; + +/** + * Calculates the UTF8 byte length of a string. + * @param {string} string String + * @returns {number} Byte length + */ +utf8.length = function utf8_length(string) { + var len = 0, + c = 0; + for (var i = 0; i < string.length; ++i) { + c = string.charCodeAt(i); + if (c < 128) + len += 1; + else if (c < 2048) + len += 2; + else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) { + ++i; + len += 4; + } else + len += 3; + } + return len; +}; + +/** + * Reads UTF8 bytes as a string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} String read + */ +utf8.read = function utf8_read(buffer, start, end) { + var len = end - start; + if (len < 1) + return ""; + var parts = null, + chunk = [], + i = 0, // char offset + t; // temporary + while (start < end) { + t = buffer[start++]; + if (t < 128) + chunk[i++] = t; + else if (t > 191 && t < 224) + chunk[i++] = (t & 31) << 6 | buffer[start++] & 63; + else if (t > 239 && t < 365) { + t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000; + chunk[i++] = 0xD800 + (t >> 10); + chunk[i++] = 0xDC00 + (t & 1023); + } else + chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i = 0; + } + } + if (parts) { + if (i) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i)); +}; + +/** + * Writes a string as UTF8 bytes. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Bytes written + */ +utf8.write = function utf8_write(string, buffer, offset) { + var start = offset, + c1, // character 1 + c2; // character 2 + for (var i = 0; i < string.length; ++i) { + c1 = string.charCodeAt(i); + if (c1 < 128) { + buffer[offset++] = c1; + } else if (c1 < 2048) { + buffer[offset++] = c1 >> 6 | 192; + buffer[offset++] = c1 & 63 | 128; + } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) { + c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF); + ++i; + buffer[offset++] = c1 >> 18 | 240; + buffer[offset++] = c1 >> 12 & 63 | 128; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } else { + buffer[offset++] = c1 >> 12 | 224; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } + } + return offset - start; +}; + +},{}],11:[function(require,module,exports){ +"use strict"; +module.exports = common; + +var commonRe = /\/|\./; + +/** + * Provides common type definitions. + * Can also be used to provide additional google types or your own custom types. + * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name + * @param {Object.} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition + * @returns {undefined} + * @property {INamespace} google/protobuf/any.proto Any + * @property {INamespace} google/protobuf/duration.proto Duration + * @property {INamespace} google/protobuf/empty.proto Empty + * @property {INamespace} google/protobuf/field_mask.proto FieldMask + * @property {INamespace} google/protobuf/struct.proto Struct, Value, NullValue and ListValue + * @property {INamespace} google/protobuf/timestamp.proto Timestamp + * @property {INamespace} google/protobuf/wrappers.proto Wrappers + * @example + * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension) + * protobuf.common("descriptor", descriptorJson); + * + * // manually provides a custom definition (uses my.foo namespace) + * protobuf.common("my/foo/bar.proto", myFooBarJson); + */ +function common(name, json) { + if (!commonRe.test(name)) { + name = "google/protobuf/" + name + ".proto"; + json = { nested: { google: { nested: { protobuf: { nested: json } } } } }; + } + common[name] = json; +} + +// Not provided because of limited use (feel free to discuss or to provide yourself): +// +// google/protobuf/descriptor.proto +// google/protobuf/source_context.proto +// google/protobuf/type.proto +// +// Stripped and pre-parsed versions of these non-bundled files are instead available as part of +// the repository or package within the google/protobuf directory. + +common("any", { + + /** + * Properties of a google.protobuf.Any message. + * @interface IAny + * @type {Object} + * @property {string} [typeUrl] + * @property {Uint8Array} [bytes] + * @memberof common + */ + Any: { + fields: { + type_url: { + type: "string", + id: 1 + }, + value: { + type: "bytes", + id: 2 + } + } + } +}); + +var timeType; + +common("duration", { + + /** + * Properties of a google.protobuf.Duration message. + * @interface IDuration + * @type {Object} + * @property {number|Long} [seconds] + * @property {number} [nanos] + * @memberof common + */ + Duration: timeType = { + fields: { + seconds: { + type: "int64", + id: 1 + }, + nanos: { + type: "int32", + id: 2 + } + } + } +}); + +common("timestamp", { + + /** + * Properties of a google.protobuf.Timestamp message. + * @interface ITimestamp + * @type {Object} + * @property {number|Long} [seconds] + * @property {number} [nanos] + * @memberof common + */ + Timestamp: timeType +}); + +common("empty", { + + /** + * Properties of a google.protobuf.Empty message. + * @interface IEmpty + * @memberof common + */ + Empty: { + fields: {} + } +}); + +common("struct", { + + /** + * Properties of a google.protobuf.Struct message. + * @interface IStruct + * @type {Object} + * @property {Object.} [fields] + * @memberof common + */ + Struct: { + fields: { + fields: { + keyType: "string", + type: "Value", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.Value message. + * @interface IValue + * @type {Object} + * @property {string} [kind] + * @property {0} [nullValue] + * @property {number} [numberValue] + * @property {string} [stringValue] + * @property {boolean} [boolValue] + * @property {IStruct} [structValue] + * @property {IListValue} [listValue] + * @memberof common + */ + Value: { + oneofs: { + kind: { + oneof: [ + "nullValue", + "numberValue", + "stringValue", + "boolValue", + "structValue", + "listValue" + ] + } + }, + fields: { + nullValue: { + type: "NullValue", + id: 1 + }, + numberValue: { + type: "double", + id: 2 + }, + stringValue: { + type: "string", + id: 3 + }, + boolValue: { + type: "bool", + id: 4 + }, + structValue: { + type: "Struct", + id: 5 + }, + listValue: { + type: "ListValue", + id: 6 + } + } + }, + + NullValue: { + values: { + NULL_VALUE: 0 + } + }, + + /** + * Properties of a google.protobuf.ListValue message. + * @interface IListValue + * @type {Object} + * @property {Array.} [values] + * @memberof common + */ + ListValue: { + fields: { + values: { + rule: "repeated", + type: "Value", + id: 1 + } + } + } +}); + +common("wrappers", { + + /** + * Properties of a google.protobuf.DoubleValue message. + * @interface IDoubleValue + * @type {Object} + * @property {number} [value] + * @memberof common + */ + DoubleValue: { + fields: { + value: { + type: "double", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.FloatValue message. + * @interface IFloatValue + * @type {Object} + * @property {number} [value] + * @memberof common + */ + FloatValue: { + fields: { + value: { + type: "float", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.Int64Value message. + * @interface IInt64Value + * @type {Object} + * @property {number|Long} [value] + * @memberof common + */ + Int64Value: { + fields: { + value: { + type: "int64", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.UInt64Value message. + * @interface IUInt64Value + * @type {Object} + * @property {number|Long} [value] + * @memberof common + */ + UInt64Value: { + fields: { + value: { + type: "uint64", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.Int32Value message. + * @interface IInt32Value + * @type {Object} + * @property {number} [value] + * @memberof common + */ + Int32Value: { + fields: { + value: { + type: "int32", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.UInt32Value message. + * @interface IUInt32Value + * @type {Object} + * @property {number} [value] + * @memberof common + */ + UInt32Value: { + fields: { + value: { + type: "uint32", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.BoolValue message. + * @interface IBoolValue + * @type {Object} + * @property {boolean} [value] + * @memberof common + */ + BoolValue: { + fields: { + value: { + type: "bool", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.StringValue message. + * @interface IStringValue + * @type {Object} + * @property {string} [value] + * @memberof common + */ + StringValue: { + fields: { + value: { + type: "string", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.BytesValue message. + * @interface IBytesValue + * @type {Object} + * @property {Uint8Array} [value] + * @memberof common + */ + BytesValue: { + fields: { + value: { + type: "bytes", + id: 1 + } + } + } +}); + +common("field_mask", { + + /** + * Properties of a google.protobuf.FieldMask message. + * @interface IDoubleValue + * @type {Object} + * @property {number} [value] + * @memberof common + */ + FieldMask: { + fields: { + paths: { + rule: "repeated", + type: "string", + id: 1 + } + } + } +}); + +/** + * Gets the root definition of the specified common proto file. + * + * Bundled definitions are: + * - google/protobuf/any.proto + * - google/protobuf/duration.proto + * - google/protobuf/empty.proto + * - google/protobuf/field_mask.proto + * - google/protobuf/struct.proto + * - google/protobuf/timestamp.proto + * - google/protobuf/wrappers.proto + * + * @param {string} file Proto file name + * @returns {INamespace|null} Root definition or `null` if not defined + */ +common.get = function get(file) { + return common[file] || null; +}; + +},{}],12:[function(require,module,exports){ +"use strict"; +/** + * Runtime message from/to plain object converters. + * @namespace + */ +var converter = exports; + +var Enum = require(15), + util = require(37); + +/** + * Generates a partial value fromObject conveter. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {number} fieldIndex Field index + * @param {string} prop Property reference + * @returns {Codegen} Codegen instance + * @ignore + */ +function genValuePartial_fromObject(gen, field, fieldIndex, prop) { + var defaultAlreadyEmitted = false; + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + if (field.resolvedType) { + if (field.resolvedType instanceof Enum) { gen + ("switch(d%s){", prop); + for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) { + // enum unknown values passthrough + if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen + ("default:") + ("if(typeof(d%s)===\"number\"){m%s=d%s;break}", prop, prop, prop); + if (!field.repeated) gen // fallback to default value only for + // arrays, to avoid leaving holes. + ("break"); // for non-repeated fields, just ignore + defaultAlreadyEmitted = true; + } + gen + ("case%j:", keys[i]) + ("case %i:", values[keys[i]]) + ("m%s=%j", prop, values[keys[i]]) + ("break"); + } gen + ("}"); + } else gen + ("if(typeof d%s!==\"object\")", prop) + ("throw TypeError(%j)", field.fullName + ": object expected") + ("m%s=types[%i].fromObject(d%s)", prop, fieldIndex, prop); + } else { + var isUnsigned = false; + switch (field.type) { + case "double": + case "float": gen + ("m%s=Number(d%s)", prop, prop); // also catches "NaN", "Infinity" + break; + case "uint32": + case "fixed32": gen + ("m%s=d%s>>>0", prop, prop); + break; + case "int32": + case "sint32": + case "sfixed32": gen + ("m%s=d%s|0", prop, prop); + break; + case "uint64": + isUnsigned = true; + // eslint-disable-next-line no-fallthrough + case "int64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(util.Long)") + ("(m%s=util.Long.fromValue(d%s)).unsigned=%j", prop, prop, isUnsigned) + ("else if(typeof d%s===\"string\")", prop) + ("m%s=parseInt(d%s,10)", prop, prop) + ("else if(typeof d%s===\"number\")", prop) + ("m%s=d%s", prop, prop) + ("else if(typeof d%s===\"object\")", prop) + ("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : ""); + break; + case "bytes": gen + ("if(typeof d%s===\"string\")", prop) + ("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop) + ("else if(d%s.length >= 0)", prop) + ("m%s=d%s", prop, prop); + break; + case "string": gen + ("m%s=String(d%s)", prop, prop); + break; + case "bool": gen + ("m%s=Boolean(d%s)", prop, prop); + break; + /* default: gen + ("m%s=d%s", prop, prop); + break; */ + } + } + return gen; + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ +} + +/** + * Generates a plain object to runtime message converter specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +converter.fromObject = function fromObject(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var fields = mtype.fieldsArray; + var gen = util.codegen(["d"], mtype.name + "$fromObject") + ("if(d instanceof this.ctor)") + ("return d"); + if (!fields.length) return gen + ("return new this.ctor"); + gen + ("var m=new this.ctor"); + for (var i = 0; i < fields.length; ++i) { + var field = fields[i].resolve(), + prop = util.safeProp(field.name); + + // Map fields + if (field.map) { gen + ("if(d%s){", prop) + ("if(typeof d%s!==\"object\")", prop) + ("throw TypeError(%j)", field.fullName + ": object expected") + ("m%s={}", prop) + ("for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s", prop, prop, prop, prop, isUnsigned ? "true": "", prop); + break; + case "bytes": gen + ("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", prop, prop, prop, prop, prop); + break; + default: gen + ("d%s=m%s", prop, prop); + break; + } + } + return gen; + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ +} + +/** + * Generates a runtime message to plain object converter specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +converter.toObject = function toObject(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById); + if (!fields.length) + return util.codegen()("return {}"); + var gen = util.codegen(["m", "o"], mtype.name + "$toObject") + ("if(!o)") + ("o={}") + ("var d={}"); + + var repeatedFields = [], + mapFields = [], + normalFields = [], + i = 0; + for (; i < fields.length; ++i) + if (!fields[i].partOf) + ( fields[i].resolve().repeated ? repeatedFields + : fields[i].map ? mapFields + : normalFields).push(fields[i]); + + if (repeatedFields.length) { gen + ("if(o.arrays||o.defaults){"); + for (i = 0; i < repeatedFields.length; ++i) gen + ("d%s=[]", util.safeProp(repeatedFields[i].name)); + gen + ("}"); + } + + if (mapFields.length) { gen + ("if(o.objects||o.defaults){"); + for (i = 0; i < mapFields.length; ++i) gen + ("d%s={}", util.safeProp(mapFields[i].name)); + gen + ("}"); + } + + if (normalFields.length) { gen + ("if(o.defaults){"); + for (i = 0; i < normalFields.length; ++i) { + var field = normalFields[i], + prop = util.safeProp(field.name); + if (field.resolvedType instanceof Enum) gen + ("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault); + else if (field.long) gen + ("if(util.Long){") + ("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned) + ("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n", prop) + ("}else") + ("d%s=o.longs===String?%j:%i", prop, field.typeDefault.toString(), field.typeDefault.toNumber()); + else if (field.bytes) { + var arrayDefault = "[" + Array.prototype.slice.call(field.typeDefault).join(",") + "]"; + gen + ("if(o.bytes===String)d%s=%j", prop, String.fromCharCode.apply(String, field.typeDefault)) + ("else{") + ("d%s=%s", prop, arrayDefault) + ("if(o.bytes!==Array)d%s=util.newBuffer(d%s)", prop, prop) + ("}"); + } else gen + ("d%s=%j", prop, field.typeDefault); // also messages (=null) + } gen + ("}"); + } + var hasKs2 = false; + for (i = 0; i < fields.length; ++i) { + var field = fields[i], + index = mtype._fieldsArray.indexOf(field), + prop = util.safeProp(field.name); + if (field.map) { + if (!hasKs2) { hasKs2 = true; gen + ("var ks2"); + } gen + ("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop) + ("d%s={}", prop) + ("for(var j=0;j>>3){"); + + var i = 0; + for (; i < /* initializes */ mtype.fieldsArray.length; ++i) { + var field = mtype._fieldsArray[i].resolve(), + type = field.resolvedType instanceof Enum ? "int32" : field.type, + ref = "m" + util.safeProp(field.name); gen + ("case %i: {", field.id); + + // Map fields + if (field.map) { gen + ("if(%s===util.emptyObject)", ref) + ("%s={}", ref) + ("var c2 = r.uint32()+r.pos"); + + if (types.defaults[field.keyType] !== undefined) gen + ("k=%j", types.defaults[field.keyType]); + else gen + ("k=null"); + + if (types.defaults[type] !== undefined) gen + ("value=%j", types.defaults[type]); + else gen + ("value=null"); + + gen + ("while(r.pos>>3){") + ("case 1: k=r.%s(); break", field.keyType) + ("case 2:"); + + if (types.basic[type] === undefined) gen + ("value=types[%i].decode(r,r.uint32())", i); // can't be groups + else gen + ("value=r.%s()", type); + + gen + ("break") + ("default:") + ("r.skipType(tag2&7)") + ("break") + ("}") + ("}"); + + if (types.long[field.keyType] !== undefined) gen + ("%s[typeof k===\"object\"?util.longToHash(k):k]=value", ref); + else gen + ("%s[k]=value", ref); + + // Repeated fields + } else if (field.repeated) { gen + + ("if(!(%s&&%s.length))", ref, ref) + ("%s=[]", ref); + + // Packable (always check for forward and backward compatiblity) + if (types.packed[type] !== undefined) gen + ("if((t&7)===2){") + ("var c2=r.uint32()+r.pos") + ("while(r.pos>> 0, (field.id << 3 | 4) >>> 0) + : gen("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0); +} + +/** + * Generates an encoder specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +function encoder(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var gen = util.codegen(["m", "w"], mtype.name + "$encode") + ("if(!w)") + ("w=Writer.create()"); + + var i, ref; + + // "when a message is serialized its known fields should be written sequentially by field number" + var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById); + + for (var i = 0; i < fields.length; ++i) { + var field = fields[i].resolve(), + index = mtype._fieldsArray.indexOf(field), + type = field.resolvedType instanceof Enum ? "int32" : field.type, + wireType = types.basic[type]; + ref = "m" + util.safeProp(field.name); + + // Map fields + if (field.map) { + gen + ("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){", ref, field.name) // !== undefined && !== null + ("for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType); + if (wireType === undefined) gen + ("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", index, ref); // can't be groups + else gen + (".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref); + gen + ("}") + ("}"); + + // Repeated fields + } else if (field.repeated) { gen + ("if(%s!=null&&%s.length){", ref, ref); // !== undefined && !== null + + // Packed repeated + if (field.packed && types.packed[type] !== undefined) { gen + + ("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0) + ("for(var i=0;i<%s.length;++i)", ref) + ("w.%s(%s[i])", type, ref) + ("w.ldelim()"); + + // Non-packed + } else { gen + + ("for(var i=0;i<%s.length;++i)", ref); + if (wireType === undefined) + genTypePartial(gen, field, index, ref + "[i]"); + else gen + ("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref); + + } gen + ("}"); + + // Non-repeated + } else { + if (field.optional) gen + ("if(%s!=null&&Object.hasOwnProperty.call(m,%j))", ref, field.name); // !== undefined && !== null + + if (wireType === undefined) + genTypePartial(gen, field, index, ref); + else gen + ("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref); + + } + } + + return gen + ("return w"); + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ +} + +},{"15":15,"36":36,"37":37}],15:[function(require,module,exports){ +"use strict"; +module.exports = Enum; + +// extends ReflectionObject +var ReflectionObject = require(24); +((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum"; + +var Namespace = require(23), + util = require(37); + +/** + * Constructs a new enum instance. + * @classdesc Reflected enum. + * @extends ReflectionObject + * @constructor + * @param {string} name Unique name within its namespace + * @param {Object.} [values] Enum values as an object, by name + * @param {Object.} [options] Declared options + * @param {string} [comment] The comment for this enum + * @param {Object.} [comments] The value comments for this enum + * @param {Object.>|undefined} [valuesOptions] The value options for this enum + */ +function Enum(name, values, options, comment, comments, valuesOptions) { + ReflectionObject.call(this, name, options); + + if (values && typeof values !== "object") + throw TypeError("values must be an object"); + + /** + * Enum values by id. + * @type {Object.} + */ + this.valuesById = {}; + + /** + * Enum values by name. + * @type {Object.} + */ + this.values = Object.create(this.valuesById); // toJSON, marker + + /** + * Enum comment text. + * @type {string|null} + */ + this.comment = comment; + + /** + * Value comment texts, if any. + * @type {Object.} + */ + this.comments = comments || {}; + + /** + * Values options, if any + * @type {Object>|undefined} + */ + this.valuesOptions = valuesOptions; + + /** + * Resolved values features, if any + * @type {Object>|undefined} + */ + this._valuesFeatures = {}; + + /** + * Reserved ranges, if any. + * @type {Array.} + */ + this.reserved = undefined; // toJSON + + // Note that values inherit valuesById on their prototype which makes them a TypeScript- + // compatible enum. This is used by pbts to write actual enum definitions that work for + // static and reflection code alike instead of emitting generic object definitions. + + if (values) + for (var keys = Object.keys(values), i = 0; i < keys.length; ++i) + if (typeof values[keys[i]] === "number") // use forward entries only + this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i]; +} + +/** + * @override + */ +Enum.prototype._resolveFeatures = function _resolveFeatures(edition) { + edition = this._edition || edition; + ReflectionObject.prototype._resolveFeatures.call(this, edition); + + Object.keys(this.values).forEach(key => { + var parentFeaturesCopy = Object.assign({}, this._features); + this._valuesFeatures[key] = Object.assign(parentFeaturesCopy, this.valuesOptions && this.valuesOptions[key] && this.valuesOptions[key].features); + }); + + return this; +}; + +/** + * Enum descriptor. + * @interface IEnum + * @property {Object.} values Enum values + * @property {Object.} [options] Enum options + */ + +/** + * Constructs an enum from an enum descriptor. + * @param {string} name Enum name + * @param {IEnum} json Enum descriptor + * @returns {Enum} Created enum + * @throws {TypeError} If arguments are invalid + */ +Enum.fromJSON = function fromJSON(name, json) { + var enm = new Enum(name, json.values, json.options, json.comment, json.comments); + enm.reserved = json.reserved; + if (json.edition) + enm._edition = json.edition; + enm._defaultEdition = "proto3"; // For backwards-compatibility. + return enm; +}; + +/** + * Converts this enum to an enum descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IEnum} Enum descriptor + */ +Enum.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "edition" , this._editionToJSON(), + "options" , this.options, + "valuesOptions" , this.valuesOptions, + "values" , this.values, + "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined, + "comment" , keepComments ? this.comment : undefined, + "comments" , keepComments ? this.comments : undefined + ]); +}; + +/** + * Adds a value to this enum. + * @param {string} name Value name + * @param {number} id Value id + * @param {string} [comment] Comment, if any + * @param {Object.|undefined} [options] Options, if any + * @returns {Enum} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a value with this name or id + */ +Enum.prototype.add = function add(name, id, comment, options) { + // utilized by the parser but not by .fromJSON + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + if (!util.isInteger(id)) + throw TypeError("id must be an integer"); + + if (this.values[name] !== undefined) + throw Error("duplicate name '" + name + "' in " + this); + + if (this.isReservedId(id)) + throw Error("id " + id + " is reserved in " + this); + + if (this.isReservedName(name)) + throw Error("name '" + name + "' is reserved in " + this); + + if (this.valuesById[id] !== undefined) { + if (!(this.options && this.options.allow_alias)) + throw Error("duplicate id " + id + " in " + this); + this.values[name] = id; + } else + this.valuesById[this.values[name] = id] = name; + + if (options) { + if (this.valuesOptions === undefined) + this.valuesOptions = {}; + this.valuesOptions[name] = options || null; + } + + this.comments[name] = comment || null; + return this; +}; + +/** + * Removes a value from this enum + * @param {string} name Value name + * @returns {Enum} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `name` is not a name of this enum + */ +Enum.prototype.remove = function remove(name) { + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + var val = this.values[name]; + if (val == null) + throw Error("name '" + name + "' does not exist in " + this); + + delete this.valuesById[val]; + delete this.values[name]; + delete this.comments[name]; + if (this.valuesOptions) + delete this.valuesOptions[name]; + + return this; +}; + +/** + * Tests if the specified id is reserved. + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Enum.prototype.isReservedId = function isReservedId(id) { + return Namespace.isReservedId(this.reserved, id); +}; + +/** + * Tests if the specified name is reserved. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Enum.prototype.isReservedName = function isReservedName(name) { + return Namespace.isReservedName(this.reserved, name); +}; + +},{"23":23,"24":24,"37":37}],16:[function(require,module,exports){ +"use strict"; +module.exports = Field; + +// extends ReflectionObject +var ReflectionObject = require(24); +((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field"; + +var Enum = require(15), + types = require(36), + util = require(37); + +var Type; // cyclic + +var ruleRe = /^required|optional|repeated$/; + +/** + * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class. + * @name Field + * @classdesc Reflected message field. + * @extends FieldBase + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} type Value type + * @param {string|Object.} [rule="optional"] Field rule + * @param {string|Object.} [extend] Extended type if different from parent + * @param {Object.} [options] Declared options + */ + +/** + * Constructs a field from a field descriptor. + * @param {string} name Field name + * @param {IField} json Field descriptor + * @returns {Field} Created field + * @throws {TypeError} If arguments are invalid + */ +Field.fromJSON = function fromJSON(name, json) { + var field = new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment); + if (json.edition) + field._edition = json.edition; + field._defaultEdition = "proto3"; // For backwards-compatibility. + return field; +}; + +/** + * Not an actual constructor. Use {@link Field} instead. + * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions. + * @exports FieldBase + * @extends ReflectionObject + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} type Value type + * @param {string|Object.} [rule="optional"] Field rule + * @param {string|Object.} [extend] Extended type if different from parent + * @param {Object.} [options] Declared options + * @param {string} [comment] Comment associated with this field + */ +function Field(name, id, type, rule, extend, options, comment) { + + if (util.isObject(rule)) { + comment = extend; + options = rule; + rule = extend = undefined; + } else if (util.isObject(extend)) { + comment = options; + options = extend; + extend = undefined; + } + + ReflectionObject.call(this, name, options); + + if (!util.isInteger(id) || id < 0) + throw TypeError("id must be a non-negative integer"); + + if (!util.isString(type)) + throw TypeError("type must be a string"); + + if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase())) + throw TypeError("rule must be a string rule"); + + if (extend !== undefined && !util.isString(extend)) + throw TypeError("extend must be a string"); + + /** + * Field rule, if any. + * @type {string|undefined} + */ + if (rule === "proto3_optional") { + rule = "optional"; + } + this.rule = rule && rule !== "optional" ? rule : undefined; // toJSON + + /** + * Field type. + * @type {string} + */ + this.type = type; // toJSON + + /** + * Unique field id. + * @type {number} + */ + this.id = id; // toJSON, marker + + /** + * Extended type if different from parent. + * @type {string|undefined} + */ + this.extend = extend || undefined; // toJSON + + /** + * Whether this field is repeated. + * @type {boolean} + */ + this.repeated = rule === "repeated"; + + /** + * Whether this field is a map or not. + * @type {boolean} + */ + this.map = false; + + /** + * Message this field belongs to. + * @type {Type|null} + */ + this.message = null; + + /** + * OneOf this field belongs to, if any, + * @type {OneOf|null} + */ + this.partOf = null; + + /** + * The field type's default value. + * @type {*} + */ + this.typeDefault = null; + + /** + * The field's default value on prototypes. + * @type {*} + */ + this.defaultValue = null; + + /** + * Whether this field's value should be treated as a long. + * @type {boolean} + */ + this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false; + + /** + * Whether this field's value is a buffer. + * @type {boolean} + */ + this.bytes = type === "bytes"; + + /** + * Resolved type if not a basic type. + * @type {Type|Enum|null} + */ + this.resolvedType = null; + + /** + * Sister-field within the extended type if a declaring extension field. + * @type {Field|null} + */ + this.extensionField = null; + + /** + * Sister-field within the declaring namespace if an extended field. + * @type {Field|null} + */ + this.declaringField = null; + + /** + * Comment for this field. + * @type {string|null} + */ + this.comment = comment; +} + +/** + * Determines whether this field is required. + * @name Field#required + * @type {boolean} + * @readonly + */ +Object.defineProperty(Field.prototype, "required", { + get: function() { + return this._features.field_presence === "LEGACY_REQUIRED"; + } +}); + +/** + * Determines whether this field is not required. + * @name Field#optional + * @type {boolean} + * @readonly + */ +Object.defineProperty(Field.prototype, "optional", { + get: function() { + return !this.required; + } +}); + +/** + * Determines whether this field uses tag-delimited encoding. In proto2 this + * corresponded to group syntax. + * @name Field#delimited + * @type {boolean} + * @readonly + */ +Object.defineProperty(Field.prototype, "delimited", { + get: function() { + return this.resolvedType instanceof Type && + this._features.message_encoding === "DELIMITED"; + } +}); + +/** + * Determines whether this field is packed. Only relevant when repeated. + * @name Field#packed + * @type {boolean} + * @readonly + */ +Object.defineProperty(Field.prototype, "packed", { + get: function() { + return this._features.repeated_field_encoding === "PACKED"; + } +}); + +/** + * Determines whether this field tracks presence. + * @name Field#hasPresence + * @type {boolean} + * @readonly + */ +Object.defineProperty(Field.prototype, "hasPresence", { + get: function() { + if (this.repeated || this.map) { + return false; + } + return this.partOf || // oneofs + this.declaringField || this.extensionField || // extensions + this._features.field_presence !== "IMPLICIT"; + } +}); + +/** + * @override + */ +Field.prototype.setOption = function setOption(name, value, ifNotSet) { + return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet); +}; + +/** + * Field descriptor. + * @interface IField + * @property {string} [rule="optional"] Field rule + * @property {string} type Field type + * @property {number} id Field id + * @property {Object.} [options] Field options + */ + +/** + * Extension field descriptor. + * @interface IExtensionField + * @extends IField + * @property {string} extend Extended type + */ + +/** + * Converts this field to a field descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IField} Field descriptor + */ +Field.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "edition" , this._editionToJSON(), + "rule" , this.rule !== "optional" && this.rule || undefined, + "type" , this.type, + "id" , this.id, + "extend" , this.extend, + "options" , this.options, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * Resolves this field's type references. + * @returns {Field} `this` + * @throws {Error} If any reference cannot be resolved + */ +Field.prototype.resolve = function resolve() { + + if (this.resolved) + return this; + + if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it + this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type); + if (this.resolvedType instanceof Type) + this.typeDefault = null; + else // instanceof Enum + this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined + } else if (this.options && this.options.proto3_optional) { + // proto3 scalar value marked optional; should default to null + this.typeDefault = null; + } + + // use explicitly set default value if present + if (this.options && this.options["default"] != null) { + this.typeDefault = this.options["default"]; + if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string") + this.typeDefault = this.resolvedType.values[this.typeDefault]; + } + + // remove unnecessary options + if (this.options) { + if (this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum)) + delete this.options.packed; + if (!Object.keys(this.options).length) + this.options = undefined; + } + + // convert to internal data type if necesssary + if (this.long) { + this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u"); + + /* istanbul ignore else */ + if (Object.freeze) + Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it) + + } else if (this.bytes && typeof this.typeDefault === "string") { + var buf; + if (util.base64.test(this.typeDefault)) + util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0); + else + util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0); + this.typeDefault = buf; + } + + // take special care of maps and repeated fields + if (this.map) + this.defaultValue = util.emptyObject; + else if (this.repeated) + this.defaultValue = util.emptyArray; + else + this.defaultValue = this.typeDefault; + + // ensure proper value on prototype + if (this.parent instanceof Type) + this.parent.ctor.prototype[this.name] = this.defaultValue; + + return ReflectionObject.prototype.resolve.call(this); +}; + +/** + * Infers field features from legacy syntax that may have been specified differently. + * in older editions. + * @param {string|undefined} edition The edition this proto is on, or undefined if pre-editions + * @returns {object} The feature values to override + */ +Field.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(edition) { + if (edition !== "proto2" && edition !== "proto3") { + return {}; + } + + var features = {}; + + if (this.rule === "required") { + features.field_presence = "LEGACY_REQUIRED"; + } + if (this.parent && types.defaults[this.type] === undefined) { + // We can't use resolvedType because types may not have been resolved yet. However, + // legacy groups are always in the same scope as the field so we don't have to do a + // full scan of the tree. + var type = this.parent.get(this.type.split(".").pop()); + if (type && type instanceof Type && type.group) { + features.message_encoding = "DELIMITED"; + } + } + if (this.getOption("packed") === true) { + features.repeated_field_encoding = "PACKED"; + } else if (this.getOption("packed") === false) { + features.repeated_field_encoding = "EXPANDED"; + } + return features; +}; + +/** + * @override + */ +Field.prototype._resolveFeatures = function _resolveFeatures(edition) { + return ReflectionObject.prototype._resolveFeatures.call(this, this._edition || edition); +}; + +/** + * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript). + * @typedef FieldDecorator + * @type {function} + * @param {Object} prototype Target prototype + * @param {string} fieldName Field name + * @returns {undefined} + */ + +/** + * Field decorator (TypeScript). + * @name Field.d + * @function + * @param {number} fieldId Field id + * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"string"|"bool"|"bytes"|Object} fieldType Field type + * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule + * @param {T} [defaultValue] Default value + * @returns {FieldDecorator} Decorator function + * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[] + */ +Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) { + + // submessage: decorate the submessage and use its name as the type + if (typeof fieldType === "function") + fieldType = util.decorateType(fieldType).name; + + // enum reference: create a reflected copy of the enum and keep reuseing it + else if (fieldType && typeof fieldType === "object") + fieldType = util.decorateEnum(fieldType).name; + + return function fieldDecorator(prototype, fieldName) { + util.decorateType(prototype.constructor) + .add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue })); + }; +}; + +/** + * Field decorator (TypeScript). + * @name Field.d + * @function + * @param {number} fieldId Field id + * @param {Constructor|string} fieldType Field type + * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule + * @returns {FieldDecorator} Decorator function + * @template T extends Message + * @variation 2 + */ +// like Field.d but without a default value + +// Sets up cyclic dependencies (called in index-light) +Field._configure = function configure(Type_) { + Type = Type_; +}; + +},{"15":15,"24":24,"36":36,"37":37}],17:[function(require,module,exports){ +"use strict"; +var protobuf = module.exports = require(18); + +protobuf.build = "light"; + +/** + * A node-style callback as used by {@link load} and {@link Root#load}. + * @typedef LoadCallback + * @type {function} + * @param {Error|null} error Error, if any, otherwise `null` + * @param {Root} [root] Root, if there hasn't been an error + * @returns {undefined} + */ + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. + * @param {string|string[]} filename One or multiple files to load + * @param {Root} root Root namespace, defaults to create a new one if omitted. + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @see {@link Root#load} + */ +function load(filename, root, callback) { + if (typeof root === "function") { + callback = root; + root = new protobuf.Root(); + } else if (!root) + root = new protobuf.Root(); + return root.load(filename, callback); +} + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. + * @name load + * @function + * @param {string|string[]} filename One or multiple files to load + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @see {@link Root#load} + * @variation 2 + */ +// function load(filename:string, callback:LoadCallback):undefined + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise. + * @name load + * @function + * @param {string|string[]} filename One or multiple files to load + * @param {Root} [root] Root namespace, defaults to create a new one if omitted. + * @returns {Promise} Promise + * @see {@link Root#load} + * @variation 3 + */ +// function load(filename:string, [root:Root]):Promise + +protobuf.load = load; + +/** + * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only). + * @param {string|string[]} filename One or multiple files to load + * @param {Root} [root] Root namespace, defaults to create a new one if omitted. + * @returns {Root} Root namespace + * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid + * @see {@link Root#loadSync} + */ +function loadSync(filename, root) { + if (!root) + root = new protobuf.Root(); + return root.loadSync(filename); +} + +protobuf.loadSync = loadSync; + +// Serialization +protobuf.encoder = require(14); +protobuf.decoder = require(13); +protobuf.verifier = require(40); +protobuf.converter = require(12); + +// Reflection +protobuf.ReflectionObject = require(24); +protobuf.Namespace = require(23); +protobuf.Root = require(29); +protobuf.Enum = require(15); +protobuf.Type = require(35); +protobuf.Field = require(16); +protobuf.OneOf = require(25); +protobuf.MapField = require(20); +protobuf.Service = require(33); +protobuf.Method = require(22); + +// Runtime +protobuf.Message = require(21); +protobuf.wrappers = require(41); + +// Utility +protobuf.types = require(36); +protobuf.util = require(37); + +// Set up possibly cyclic reflection dependencies +protobuf.ReflectionObject._configure(protobuf.Root); +protobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum); +protobuf.Root._configure(protobuf.Type); +protobuf.Field._configure(protobuf.Type); + +},{"12":12,"13":13,"14":14,"15":15,"16":16,"18":18,"20":20,"21":21,"22":22,"23":23,"24":24,"25":25,"29":29,"33":33,"35":35,"36":36,"37":37,"40":40,"41":41}],18:[function(require,module,exports){ +"use strict"; +var protobuf = exports; + +/** + * Build type, one of `"full"`, `"light"` or `"minimal"`. + * @name build + * @type {string} + * @const + */ +protobuf.build = "minimal"; + +// Serialization +protobuf.Writer = require(42); +protobuf.BufferWriter = require(43); +protobuf.Reader = require(27); +protobuf.BufferReader = require(28); + +// Utility +protobuf.util = require(39); +protobuf.rpc = require(31); +protobuf.roots = require(30); +protobuf.configure = configure; + +/* istanbul ignore next */ +/** + * Reconfigures the library according to the environment. + * @returns {undefined} + */ +function configure() { + protobuf.util._configure(); + protobuf.Writer._configure(protobuf.BufferWriter); + protobuf.Reader._configure(protobuf.BufferReader); +} + +// Set up buffer utility according to the environment +configure(); + +},{"27":27,"28":28,"30":30,"31":31,"39":39,"42":42,"43":43}],19:[function(require,module,exports){ +"use strict"; +var protobuf = module.exports = require(17); + +protobuf.build = "full"; + +// Parser +protobuf.tokenize = require(34); +protobuf.parse = require(26); +protobuf.common = require(11); + +// Configure parser +protobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common); + +},{"11":11,"17":17,"26":26,"34":34}],20:[function(require,module,exports){ +"use strict"; +module.exports = MapField; + +// extends Field +var Field = require(16); +((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField"; + +var types = require(36), + util = require(37); + +/** + * Constructs a new map field instance. + * @classdesc Reflected map field. + * @extends FieldBase + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} keyType Key type + * @param {string} type Value type + * @param {Object.} [options] Declared options + * @param {string} [comment] Comment associated with this field + */ +function MapField(name, id, keyType, type, options, comment) { + Field.call(this, name, id, type, undefined, undefined, options, comment); + + /* istanbul ignore if */ + if (!util.isString(keyType)) + throw TypeError("keyType must be a string"); + + /** + * Key type. + * @type {string} + */ + this.keyType = keyType; // toJSON, marker + + /** + * Resolved key type if not a basic type. + * @type {ReflectionObject|null} + */ + this.resolvedKeyType = null; + + // Overrides Field#map + this.map = true; +} + +/** + * Map field descriptor. + * @interface IMapField + * @extends {IField} + * @property {string} keyType Key type + */ + +/** + * Extension map field descriptor. + * @interface IExtensionMapField + * @extends IMapField + * @property {string} extend Extended type + */ + +/** + * Constructs a map field from a map field descriptor. + * @param {string} name Field name + * @param {IMapField} json Map field descriptor + * @returns {MapField} Created map field + * @throws {TypeError} If arguments are invalid + */ +MapField.fromJSON = function fromJSON(name, json) { + return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment); +}; + +/** + * Converts this map field to a map field descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IMapField} Map field descriptor + */ +MapField.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "keyType" , this.keyType, + "type" , this.type, + "id" , this.id, + "extend" , this.extend, + "options" , this.options, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * @override + */ +MapField.prototype.resolve = function resolve() { + if (this.resolved) + return this; + + // Besides a value type, map fields have a key type that may be "any scalar type except for floating point types and bytes" + if (types.mapKey[this.keyType] === undefined) + throw Error("invalid key type: " + this.keyType); + + return Field.prototype.resolve.call(this); +}; + +/** + * Map field decorator (TypeScript). + * @name MapField.d + * @function + * @param {number} fieldId Field id + * @param {"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"} fieldKeyType Field key type + * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"|"bytes"|Object|Constructor<{}>} fieldValueType Field value type + * @returns {FieldDecorator} Decorator function + * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> } + */ +MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) { + + // submessage value: decorate the submessage and use its name as the type + if (typeof fieldValueType === "function") + fieldValueType = util.decorateType(fieldValueType).name; + + // enum reference value: create a reflected copy of the enum and keep reuseing it + else if (fieldValueType && typeof fieldValueType === "object") + fieldValueType = util.decorateEnum(fieldValueType).name; + + return function mapFieldDecorator(prototype, fieldName) { + util.decorateType(prototype.constructor) + .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType)); + }; +}; + +},{"16":16,"36":36,"37":37}],21:[function(require,module,exports){ +"use strict"; +module.exports = Message; + +var util = require(39); + +/** + * Constructs a new message instance. + * @classdesc Abstract runtime message. + * @constructor + * @param {Properties} [properties] Properties to set + * @template T extends object = object + */ +function Message(properties) { + // not used internally + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + this[keys[i]] = properties[keys[i]]; +} + +/** + * Reference to the reflected type. + * @name Message.$type + * @type {Type} + * @readonly + */ + +/** + * Reference to the reflected type. + * @name Message#$type + * @type {Type} + * @readonly + */ + +/*eslint-disable valid-jsdoc*/ + +/** + * Creates a new message of this type using the specified properties. + * @param {Object.} [properties] Properties to set + * @returns {Message} Message instance + * @template T extends Message + * @this Constructor + */ +Message.create = function create(properties) { + return this.$type.create(properties); +}; + +/** + * Encodes a message of this type. + * @param {T|Object.} message Message to encode + * @param {Writer} [writer] Writer to use + * @returns {Writer} Writer + * @template T extends Message + * @this Constructor + */ +Message.encode = function encode(message, writer) { + return this.$type.encode(message, writer); +}; + +/** + * Encodes a message of this type preceeded by its length as a varint. + * @param {T|Object.} message Message to encode + * @param {Writer} [writer] Writer to use + * @returns {Writer} Writer + * @template T extends Message + * @this Constructor + */ +Message.encodeDelimited = function encodeDelimited(message, writer) { + return this.$type.encodeDelimited(message, writer); +}; + +/** + * Decodes a message of this type. + * @name Message.decode + * @function + * @param {Reader|Uint8Array} reader Reader or buffer to decode + * @returns {T} Decoded message + * @template T extends Message + * @this Constructor + */ +Message.decode = function decode(reader) { + return this.$type.decode(reader); +}; + +/** + * Decodes a message of this type preceeded by its length as a varint. + * @name Message.decodeDelimited + * @function + * @param {Reader|Uint8Array} reader Reader or buffer to decode + * @returns {T} Decoded message + * @template T extends Message + * @this Constructor + */ +Message.decodeDelimited = function decodeDelimited(reader) { + return this.$type.decodeDelimited(reader); +}; + +/** + * Verifies a message of this type. + * @name Message.verify + * @function + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ +Message.verify = function verify(message) { + return this.$type.verify(message); +}; + +/** + * Creates a new message of this type from a plain object. Also converts values to their respective internal types. + * @param {Object.} object Plain object + * @returns {T} Message instance + * @template T extends Message + * @this Constructor + */ +Message.fromObject = function fromObject(object) { + return this.$type.fromObject(object); +}; + +/** + * Creates a plain object from a message of this type. Also converts values to other types if specified. + * @param {T} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + * @template T extends Message + * @this Constructor + */ +Message.toObject = function toObject(message, options) { + return this.$type.toObject(message, options); +}; + +/** + * Converts this message to JSON. + * @returns {Object.} JSON object + */ +Message.prototype.toJSON = function toJSON() { + return this.$type.toObject(this, util.toJSONOptions); +}; + +/*eslint-enable valid-jsdoc*/ +},{"39":39}],22:[function(require,module,exports){ +"use strict"; +module.exports = Method; + +// extends ReflectionObject +var ReflectionObject = require(24); +((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method"; + +var util = require(37); + +/** + * Constructs a new service method instance. + * @classdesc Reflected service method. + * @extends ReflectionObject + * @constructor + * @param {string} name Method name + * @param {string|undefined} type Method type, usually `"rpc"` + * @param {string} requestType Request message type + * @param {string} responseType Response message type + * @param {boolean|Object.} [requestStream] Whether the request is streamed + * @param {boolean|Object.} [responseStream] Whether the response is streamed + * @param {Object.} [options] Declared options + * @param {string} [comment] The comment for this method + * @param {Object.} [parsedOptions] Declared options, properly parsed into an object + */ +function Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) { + + /* istanbul ignore next */ + if (util.isObject(requestStream)) { + options = requestStream; + requestStream = responseStream = undefined; + } else if (util.isObject(responseStream)) { + options = responseStream; + responseStream = undefined; + } + + /* istanbul ignore if */ + if (!(type === undefined || util.isString(type))) + throw TypeError("type must be a string"); + + /* istanbul ignore if */ + if (!util.isString(requestType)) + throw TypeError("requestType must be a string"); + + /* istanbul ignore if */ + if (!util.isString(responseType)) + throw TypeError("responseType must be a string"); + + ReflectionObject.call(this, name, options); + + /** + * Method type. + * @type {string} + */ + this.type = type || "rpc"; // toJSON + + /** + * Request type. + * @type {string} + */ + this.requestType = requestType; // toJSON, marker + + /** + * Whether requests are streamed or not. + * @type {boolean|undefined} + */ + this.requestStream = requestStream ? true : undefined; // toJSON + + /** + * Response type. + * @type {string} + */ + this.responseType = responseType; // toJSON + + /** + * Whether responses are streamed or not. + * @type {boolean|undefined} + */ + this.responseStream = responseStream ? true : undefined; // toJSON + + /** + * Resolved request type. + * @type {Type|null} + */ + this.resolvedRequestType = null; + + /** + * Resolved response type. + * @type {Type|null} + */ + this.resolvedResponseType = null; + + /** + * Comment for this method + * @type {string|null} + */ + this.comment = comment; + + /** + * Options properly parsed into an object + */ + this.parsedOptions = parsedOptions; +} + +/** + * Method descriptor. + * @interface IMethod + * @property {string} [type="rpc"] Method type + * @property {string} requestType Request type + * @property {string} responseType Response type + * @property {boolean} [requestStream=false] Whether requests are streamed + * @property {boolean} [responseStream=false] Whether responses are streamed + * @property {Object.} [options] Method options + * @property {string} comment Method comments + * @property {Object.} [parsedOptions] Method options properly parsed into an object + */ + +/** + * Constructs a method from a method descriptor. + * @param {string} name Method name + * @param {IMethod} json Method descriptor + * @returns {Method} Created method + * @throws {TypeError} If arguments are invalid + */ +Method.fromJSON = function fromJSON(name, json) { + return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions); +}; + +/** + * Converts this method to a method descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IMethod} Method descriptor + */ +Method.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "type" , this.type !== "rpc" && /* istanbul ignore next */ this.type || undefined, + "requestType" , this.requestType, + "requestStream" , this.requestStream, + "responseType" , this.responseType, + "responseStream" , this.responseStream, + "options" , this.options, + "comment" , keepComments ? this.comment : undefined, + "parsedOptions" , this.parsedOptions, + ]); +}; + +/** + * @override + */ +Method.prototype.resolve = function resolve() { + + /* istanbul ignore if */ + if (this.resolved) + return this; + + this.resolvedRequestType = this.parent.lookupType(this.requestType); + this.resolvedResponseType = this.parent.lookupType(this.responseType); + + return ReflectionObject.prototype.resolve.call(this); +}; + +},{"24":24,"37":37}],23:[function(require,module,exports){ +"use strict"; +module.exports = Namespace; + +// extends ReflectionObject +var ReflectionObject = require(24); +((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace"; + +var Field = require(16), + util = require(37), + OneOf = require(25); + +var Type, // cyclic + Service, + Enum; + +/** + * Constructs a new namespace instance. + * @name Namespace + * @classdesc Reflected namespace. + * @extends NamespaceBase + * @constructor + * @param {string} name Namespace name + * @param {Object.} [options] Declared options + */ + +/** + * Constructs a namespace from JSON. + * @memberof Namespace + * @function + * @param {string} name Namespace name + * @param {Object.} json JSON object + * @returns {Namespace} Created namespace + * @throws {TypeError} If arguments are invalid + */ +Namespace.fromJSON = function fromJSON(name, json) { + return new Namespace(name, json.options).addJSON(json.nested); +}; + +/** + * Converts an array of reflection objects to JSON. + * @memberof Namespace + * @param {ReflectionObject[]} array Object array + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {Object.|undefined} JSON object or `undefined` when array is empty + */ +function arrayToJSON(array, toJSONOptions) { + if (!(array && array.length)) + return undefined; + var obj = {}; + for (var i = 0; i < array.length; ++i) + obj[array[i].name] = array[i].toJSON(toJSONOptions); + return obj; +} + +Namespace.arrayToJSON = arrayToJSON; + +/** + * Tests if the specified id is reserved. + * @param {Array.|undefined} reserved Array of reserved ranges and names + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Namespace.isReservedId = function isReservedId(reserved, id) { + if (reserved) + for (var i = 0; i < reserved.length; ++i) + if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] > id) + return true; + return false; +}; + +/** + * Tests if the specified name is reserved. + * @param {Array.|undefined} reserved Array of reserved ranges and names + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Namespace.isReservedName = function isReservedName(reserved, name) { + if (reserved) + for (var i = 0; i < reserved.length; ++i) + if (reserved[i] === name) + return true; + return false; +}; + +/** + * Not an actual constructor. Use {@link Namespace} instead. + * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions. + * @exports NamespaceBase + * @extends ReflectionObject + * @abstract + * @constructor + * @param {string} name Namespace name + * @param {Object.} [options] Declared options + * @see {@link Namespace} + */ +function Namespace(name, options) { + ReflectionObject.call(this, name, options); + + /** + * Nested objects by name. + * @type {Object.|undefined} + */ + this.nested = undefined; // toJSON + + /** + * Cached nested objects as an array. + * @type {ReflectionObject[]|null} + * @private + */ + this._nestedArray = null; + + /** + * Cache lookup calls for any objects contains anywhere under this namespace. + * This drastically speeds up resolve for large cross-linked protos where the same + * types are looked up repeatedly. + * @type {Object.} + * @private + */ + this._lookupCache = {}; + + /** + * Whether or not objects contained in this namespace need feature resolution. + * @type {boolean} + * @protected + */ + this._needsRecursiveFeatureResolution = true; + + /** + * Whether or not objects contained in this namespace need a resolve. + * @type {boolean} + * @protected + */ + this._needsRecursiveResolve = true; +} + +function clearCache(namespace) { + namespace._nestedArray = null; + namespace._lookupCache = {}; + + // Also clear parent caches, since they include nested lookups. + var parent = namespace; + while(parent = parent.parent) { + parent._lookupCache = {}; + } + return namespace; +} + +/** + * Nested objects of this namespace as an array for iteration. + * @name NamespaceBase#nestedArray + * @type {ReflectionObject[]} + * @readonly + */ +Object.defineProperty(Namespace.prototype, "nestedArray", { + get: function() { + return this._nestedArray || (this._nestedArray = util.toArray(this.nested)); + } +}); + +/** + * Namespace descriptor. + * @interface INamespace + * @property {Object.} [options] Namespace options + * @property {Object.} [nested] Nested object descriptors + */ + +/** + * Any extension field descriptor. + * @typedef AnyExtensionField + * @type {IExtensionField|IExtensionMapField} + */ + +/** + * Any nested object descriptor. + * @typedef AnyNestedObject + * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf} + */ + +/** + * Converts this namespace to a namespace descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {INamespace} Namespace descriptor + */ +Namespace.prototype.toJSON = function toJSON(toJSONOptions) { + return util.toObject([ + "options" , this.options, + "nested" , arrayToJSON(this.nestedArray, toJSONOptions) + ]); +}; + +/** + * Adds nested objects to this namespace from nested object descriptors. + * @param {Object.} nestedJson Any nested object descriptors + * @returns {Namespace} `this` + */ +Namespace.prototype.addJSON = function addJSON(nestedJson) { + var ns = this; + /* istanbul ignore else */ + if (nestedJson) { + for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) { + nested = nestedJson[names[i]]; + ns.add( // most to least likely + ( nested.fields !== undefined + ? Type.fromJSON + : nested.values !== undefined + ? Enum.fromJSON + : nested.methods !== undefined + ? Service.fromJSON + : nested.id !== undefined + ? Field.fromJSON + : Namespace.fromJSON )(names[i], nested) + ); + } + } + return this; +}; + +/** + * Gets the nested object of the specified name. + * @param {string} name Nested object name + * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist + */ +Namespace.prototype.get = function get(name) { + return this.nested && this.nested[name] + || null; +}; + +/** + * Gets the values of the nested {@link Enum|enum} of the specified name. + * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`. + * @param {string} name Nested enum name + * @returns {Object.} Enum values + * @throws {Error} If there is no such enum + */ +Namespace.prototype.getEnum = function getEnum(name) { + if (this.nested && this.nested[name] instanceof Enum) + return this.nested[name].values; + throw Error("no such enum: " + name); +}; + +/** + * Adds a nested object to this namespace. + * @param {ReflectionObject} object Nested object to add + * @returns {Namespace} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a nested object with this name + */ +Namespace.prototype.add = function add(object) { + + if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace)) + throw TypeError("object must be a valid nested object"); + + if (!this.nested) + this.nested = {}; + else { + var prev = this.get(object.name); + if (prev) { + if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) { + // replace plain namespace but keep existing nested elements and options + var nested = prev.nestedArray; + for (var i = 0; i < nested.length; ++i) + object.add(nested[i]); + this.remove(prev); + if (!this.nested) + this.nested = {}; + object.setOptions(prev.options, true); + + } else + throw Error("duplicate name '" + object.name + "' in " + this); + } + } + this.nested[object.name] = object; + + if (!(this instanceof Type || this instanceof Service || this instanceof Enum || this instanceof Field)) { + // This is a package or a root namespace. + if (!object._edition) { + // Make sure that some edition is set if it hasn't already been specified. + object._edition = object._defaultEdition; + } + } + + this._needsRecursiveFeatureResolution = true; + this._needsRecursiveResolve = true; + + // Also clear parent caches, since they need to recurse down. + var parent = this; + while(parent = parent.parent) { + parent._needsRecursiveFeatureResolution = true; + parent._needsRecursiveResolve = true; + } + + object.onAdd(this); + return clearCache(this); +}; + +/** + * Removes a nested object from this namespace. + * @param {ReflectionObject} object Nested object to remove + * @returns {Namespace} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `object` is not a member of this namespace + */ +Namespace.prototype.remove = function remove(object) { + + if (!(object instanceof ReflectionObject)) + throw TypeError("object must be a ReflectionObject"); + if (object.parent !== this) + throw Error(object + " is not a member of " + this); + + delete this.nested[object.name]; + if (!Object.keys(this.nested).length) + this.nested = undefined; + + object.onRemove(this); + return clearCache(this); +}; + +/** + * Defines additial namespaces within this one if not yet existing. + * @param {string|string[]} path Path to create + * @param {*} [json] Nested types to create from JSON + * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty + */ +Namespace.prototype.define = function define(path, json) { + + if (util.isString(path)) + path = path.split("."); + else if (!Array.isArray(path)) + throw TypeError("illegal path"); + if (path && path.length && path[0] === "") + throw Error("path must be relative"); + + var ptr = this; + while (path.length > 0) { + var part = path.shift(); + if (ptr.nested && ptr.nested[part]) { + ptr = ptr.nested[part]; + if (!(ptr instanceof Namespace)) + throw Error("path conflicts with non-namespace objects"); + } else + ptr.add(ptr = new Namespace(part)); + } + if (json) + ptr.addJSON(json); + return ptr; +}; + +/** + * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost. + * @returns {Namespace} `this` + */ +Namespace.prototype.resolveAll = function resolveAll() { + if (!this._needsRecursiveResolve) return this; + + this._resolveFeaturesRecursive(this._edition); + + var nested = this.nestedArray, i = 0; + this.resolve(); + while (i < nested.length) + if (nested[i] instanceof Namespace) + nested[i++].resolveAll(); + else + nested[i++].resolve(); + this._needsRecursiveResolve = false; + return this; +}; + +/** + * @override + */ +Namespace.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { + if (!this._needsRecursiveFeatureResolution) return this; + this._needsRecursiveFeatureResolution = false; + + edition = this._edition || edition; + + ReflectionObject.prototype._resolveFeaturesRecursive.call(this, edition); + this.nestedArray.forEach(nested => { + nested._resolveFeaturesRecursive(edition); + }); + return this; +}; + +/** + * Recursively looks up the reflection object matching the specified path in the scope of this namespace. + * @param {string|string[]} path Path to look up + * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc. + * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked + * @returns {ReflectionObject|null} Looked up object or `null` if none could be found + */ +Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) { + /* istanbul ignore next */ + if (typeof filterTypes === "boolean") { + parentAlreadyChecked = filterTypes; + filterTypes = undefined; + } else if (filterTypes && !Array.isArray(filterTypes)) + filterTypes = [ filterTypes ]; + + if (util.isString(path) && path.length) { + if (path === ".") + return this.root; + path = path.split("."); + } else if (!path.length) + return this; + + var flatPath = path.join("."); + + // Start at root if path is absolute + if (path[0] === "") + return this.root.lookup(path.slice(1), filterTypes); + + // Early bailout for objects with matching absolute paths + var found = this.root._fullyQualifiedObjects && this.root._fullyQualifiedObjects["." + flatPath]; + if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { + return found; + } + + // Do a regular lookup at this namespace and below + found = this._lookupImpl(path, flatPath); + if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { + return found; + } + + if (parentAlreadyChecked) + return null; + + // If there hasn't been a match, walk up the tree and look more broadly + var current = this; + while (current.parent) { + found = current.parent._lookupImpl(path, flatPath); + if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { + return found; + } + current = current.parent; + } + return null; +}; + +/** + * Internal helper for lookup that handles searching just at this namespace and below along with caching. + * @param {string[]} path Path to look up + * @param {string} flatPath Flattened version of the path to use as a cache key + * @returns {ReflectionObject|null} Looked up object or `null` if none could be found + * @private + */ +Namespace.prototype._lookupImpl = function lookup(path, flatPath) { + if(Object.prototype.hasOwnProperty.call(this._lookupCache, flatPath)) { + return this._lookupCache[flatPath]; + } + + // Test if the first part matches any nested object, and if so, traverse if path contains more + var found = this.get(path[0]); + var exact = null; + if (found) { + if (path.length === 1) { + exact = found; + } else if (found instanceof Namespace) { + path = path.slice(1); + exact = found._lookupImpl(path, path.join(".")); + } + + // Otherwise try each nested namespace + } else { + for (var i = 0; i < this.nestedArray.length; ++i) + if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i]._lookupImpl(path, flatPath))) + exact = found; + } + + // Set this even when null, so that when we walk up the tree we can quickly bail on repeated checks back down. + this._lookupCache[flatPath] = exact; + return exact; +}; + +/** + * Looks up the reflection object at the specified path, relative to this namespace. + * @name NamespaceBase#lookup + * @function + * @param {string|string[]} path Path to look up + * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked + * @returns {ReflectionObject|null} Looked up object or `null` if none could be found + * @variation 2 + */ +// lookup(path: string, [parentAlreadyChecked: boolean]) + +/** + * Looks up the {@link Type|type} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Type} Looked up type + * @throws {Error} If `path` does not point to a type + */ +Namespace.prototype.lookupType = function lookupType(path) { + var found = this.lookup(path, [ Type ]); + if (!found) + throw Error("no such type: " + path); + return found; +}; + +/** + * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Enum} Looked up enum + * @throws {Error} If `path` does not point to an enum + */ +Namespace.prototype.lookupEnum = function lookupEnum(path) { + var found = this.lookup(path, [ Enum ]); + if (!found) + throw Error("no such Enum '" + path + "' in " + this); + return found; +}; + +/** + * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Type} Looked up type or enum + * @throws {Error} If `path` does not point to a type or enum + */ +Namespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) { + var found = this.lookup(path, [ Type, Enum ]); + if (!found) + throw Error("no such Type or Enum '" + path + "' in " + this); + return found; +}; + +/** + * Looks up the {@link Service|service} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Service} Looked up service + * @throws {Error} If `path` does not point to a service + */ +Namespace.prototype.lookupService = function lookupService(path) { + var found = this.lookup(path, [ Service ]); + if (!found) + throw Error("no such Service '" + path + "' in " + this); + return found; +}; + +// Sets up cyclic dependencies (called in index-light) +Namespace._configure = function(Type_, Service_, Enum_) { + Type = Type_; + Service = Service_; + Enum = Enum_; +}; + +},{"16":16,"24":24,"25":25,"37":37}],24:[function(require,module,exports){ +"use strict"; +module.exports = ReflectionObject; + +ReflectionObject.className = "ReflectionObject"; + +const OneOf = require(25); +var util = require(37); + +var Root; // cyclic + +/* eslint-disable no-warning-comments */ +// TODO: Replace with embedded proto. +var editions2023Defaults = {enum_type: "OPEN", field_presence: "EXPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY"}; +var proto2Defaults = {enum_type: "CLOSED", field_presence: "EXPLICIT", json_format: "LEGACY_BEST_EFFORT", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "EXPANDED", utf8_validation: "NONE"}; +var proto3Defaults = {enum_type: "OPEN", field_presence: "IMPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY"}; + +/** + * Constructs a new reflection object instance. + * @classdesc Base class of all reflection objects. + * @constructor + * @param {string} name Object name + * @param {Object.} [options] Declared options + * @abstract + */ +function ReflectionObject(name, options) { + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + if (options && !util.isObject(options)) + throw TypeError("options must be an object"); + + /** + * Options. + * @type {Object.|undefined} + */ + this.options = options; // toJSON + + /** + * Parsed Options. + * @type {Array.>|undefined} + */ + this.parsedOptions = null; + + /** + * Unique name within its namespace. + * @type {string} + */ + this.name = name; + + /** + * The edition specified for this object. Only relevant for top-level objects. + * @type {string} + * @private + */ + this._edition = null; + + /** + * The default edition to use for this object if none is specified. For legacy reasons, + * this is proto2 except in the JSON parsing case where it was proto3. + * @type {string} + * @private + */ + this._defaultEdition = "proto2"; + + /** + * Resolved Features. + * @type {object} + * @private + */ + this._features = {}; + + /** + * Whether or not features have been resolved. + * @type {boolean} + * @private + */ + this._featuresResolved = false; + + /** + * Parent namespace. + * @type {Namespace|null} + */ + this.parent = null; + + /** + * Whether already resolved or not. + * @type {boolean} + */ + this.resolved = false; + + /** + * Comment text, if any. + * @type {string|null} + */ + this.comment = null; + + /** + * Defining file name. + * @type {string|null} + */ + this.filename = null; +} + +Object.defineProperties(ReflectionObject.prototype, { + + /** + * Reference to the root namespace. + * @name ReflectionObject#root + * @type {Root} + * @readonly + */ + root: { + get: function() { + var ptr = this; + while (ptr.parent !== null) + ptr = ptr.parent; + return ptr; + } + }, + + /** + * Full name including leading dot. + * @name ReflectionObject#fullName + * @type {string} + * @readonly + */ + fullName: { + get: function() { + var path = [ this.name ], + ptr = this.parent; + while (ptr) { + path.unshift(ptr.name); + ptr = ptr.parent; + } + return path.join("."); + } + } +}); + +/** + * Converts this reflection object to its descriptor representation. + * @returns {Object.} Descriptor + * @abstract + */ +ReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() { + throw Error(); // not implemented, shouldn't happen +}; + +/** + * Called when this object is added to a parent. + * @param {ReflectionObject} parent Parent added to + * @returns {undefined} + */ +ReflectionObject.prototype.onAdd = function onAdd(parent) { + if (this.parent && this.parent !== parent) + this.parent.remove(this); + this.parent = parent; + this.resolved = false; + var root = parent.root; + if (root instanceof Root) + root._handleAdd(this); +}; + +/** + * Called when this object is removed from a parent. + * @param {ReflectionObject} parent Parent removed from + * @returns {undefined} + */ +ReflectionObject.prototype.onRemove = function onRemove(parent) { + var root = parent.root; + if (root instanceof Root) + root._handleRemove(this); + this.parent = null; + this.resolved = false; +}; + +/** + * Resolves this objects type references. + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.resolve = function resolve() { + if (this.resolved) + return this; + if (this.root instanceof Root) + this.resolved = true; // only if part of a root + return this; +}; + +/** + * Resolves this objects editions features. + * @param {string} edition The edition we're currently resolving for. + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { + return this._resolveFeatures(this._edition || edition); +}; + +/** + * Resolves child features from parent features + * @param {string} edition The edition we're currently resolving for. + * @returns {undefined} + */ +ReflectionObject.prototype._resolveFeatures = function _resolveFeatures(edition) { + if (this._featuresResolved) { + return; + } + + var defaults = {}; + + /* istanbul ignore if */ + if (!edition) { + throw new Error("Unknown edition for " + this.fullName); + } + + var protoFeatures = Object.assign(this.options ? Object.assign({}, this.options.features) : {}, + this._inferLegacyProtoFeatures(edition)); + + if (this._edition) { + // For a namespace marked with a specific edition, reset defaults. + /* istanbul ignore else */ + if (edition === "proto2") { + defaults = Object.assign({}, proto2Defaults); + } else if (edition === "proto3") { + defaults = Object.assign({}, proto3Defaults); + } else if (edition === "2023") { + defaults = Object.assign({}, editions2023Defaults); + } else { + throw new Error("Unknown edition: " + edition); + } + this._features = Object.assign(defaults, protoFeatures || {}); + this._featuresResolved = true; + return; + } + + // fields in Oneofs aren't actually children of them, so we have to + // special-case it + /* istanbul ignore else */ + if (this.partOf instanceof OneOf) { + var lexicalParentFeaturesCopy = Object.assign({}, this.partOf._features); + this._features = Object.assign(lexicalParentFeaturesCopy, protoFeatures || {}); + } else if (this.declaringField) { + // Skip feature resolution of sister fields. + } else if (this.parent) { + var parentFeaturesCopy = Object.assign({}, this.parent._features); + this._features = Object.assign(parentFeaturesCopy, protoFeatures || {}); + } else { + throw new Error("Unable to find a parent for " + this.fullName); + } + if (this.extensionField) { + // Sister fields should have the same features as their extensions. + this.extensionField._features = this._features; + } + this._featuresResolved = true; +}; + +/** + * Infers features from legacy syntax that may have been specified differently. + * in older editions. + * @param {string|undefined} edition The edition this proto is on, or undefined if pre-editions + * @returns {object} The feature values to override + */ +ReflectionObject.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(/*edition*/) { + return {}; +}; + +/** + * Gets an option value. + * @param {string} name Option name + * @returns {*} Option value or `undefined` if not set + */ +ReflectionObject.prototype.getOption = function getOption(name) { + if (this.options) + return this.options[name]; + return undefined; +}; + +/** + * Sets an option. + * @param {string} name Option name + * @param {*} value Option value + * @param {boolean|undefined} [ifNotSet] Sets the option only if it isn't currently set + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) { + if (!this.options) + this.options = {}; + if (/^features\./.test(name)) { + util.setProperty(this.options, name, value, ifNotSet); + } else if (!ifNotSet || this.options[name] === undefined) { + if (this.getOption(name) !== value) this.resolved = false; + this.options[name] = value; + } + + return this; +}; + +/** + * Sets a parsed option. + * @param {string} name parsed Option name + * @param {*} value Option value + * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\empty, will add a new option with that value + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) { + if (!this.parsedOptions) { + this.parsedOptions = []; + } + var parsedOptions = this.parsedOptions; + if (propName) { + // If setting a sub property of an option then try to merge it + // with an existing option + var opt = parsedOptions.find(function (opt) { + return Object.prototype.hasOwnProperty.call(opt, name); + }); + if (opt) { + // If we found an existing option - just merge the property value + // (If it's a feature, will just write over) + var newValue = opt[name]; + util.setProperty(newValue, propName, value); + } else { + // otherwise, create a new option, set its property and add it to the list + opt = {}; + opt[name] = util.setProperty({}, propName, value); + parsedOptions.push(opt); + } + } else { + // Always create a new option when setting the value of the option itself + var newOpt = {}; + newOpt[name] = value; + parsedOptions.push(newOpt); + } + + return this; +}; + +/** + * Sets multiple options. + * @param {Object.} options Options to set + * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) { + if (options) + for (var keys = Object.keys(options), i = 0; i < keys.length; ++i) + this.setOption(keys[i], options[keys[i]], ifNotSet); + return this; +}; + +/** + * Converts this instance to its string representation. + * @returns {string} Class name[, space, full name] + */ +ReflectionObject.prototype.toString = function toString() { + var className = this.constructor.className, + fullName = this.fullName; + if (fullName.length) + return className + " " + fullName; + return className; +}; + +/** + * Converts the edition this object is pinned to for JSON format. + * @returns {string|undefined} The edition string for JSON representation + */ +ReflectionObject.prototype._editionToJSON = function _editionToJSON() { + if (!this._edition || this._edition === "proto3") { + // Avoid emitting proto3 since we need to default to it for backwards + // compatibility anyway. + return undefined; + } + return this._edition; +}; + +// Sets up cyclic dependencies (called in index-light) +ReflectionObject._configure = function(Root_) { + Root = Root_; +}; + +},{"25":25,"37":37}],25:[function(require,module,exports){ +"use strict"; +module.exports = OneOf; + +// extends ReflectionObject +var ReflectionObject = require(24); +((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf"; + +var Field = require(16), + util = require(37); + +/** + * Constructs a new oneof instance. + * @classdesc Reflected oneof. + * @extends ReflectionObject + * @constructor + * @param {string} name Oneof name + * @param {string[]|Object.} [fieldNames] Field names + * @param {Object.} [options] Declared options + * @param {string} [comment] Comment associated with this field + */ +function OneOf(name, fieldNames, options, comment) { + if (!Array.isArray(fieldNames)) { + options = fieldNames; + fieldNames = undefined; + } + ReflectionObject.call(this, name, options); + + /* istanbul ignore if */ + if (!(fieldNames === undefined || Array.isArray(fieldNames))) + throw TypeError("fieldNames must be an Array"); + + /** + * Field names that belong to this oneof. + * @type {string[]} + */ + this.oneof = fieldNames || []; // toJSON, marker + + /** + * Fields that belong to this oneof as an array for iteration. + * @type {Field[]} + * @readonly + */ + this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent + + /** + * Comment for this field. + * @type {string|null} + */ + this.comment = comment; +} + +/** + * Oneof descriptor. + * @interface IOneOf + * @property {Array.} oneof Oneof field names + * @property {Object.} [options] Oneof options + */ + +/** + * Constructs a oneof from a oneof descriptor. + * @param {string} name Oneof name + * @param {IOneOf} json Oneof descriptor + * @returns {OneOf} Created oneof + * @throws {TypeError} If arguments are invalid + */ +OneOf.fromJSON = function fromJSON(name, json) { + return new OneOf(name, json.oneof, json.options, json.comment); +}; + +/** + * Converts this oneof to a oneof descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IOneOf} Oneof descriptor + */ +OneOf.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "options" , this.options, + "oneof" , this.oneof, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * Adds the fields of the specified oneof to the parent if not already done so. + * @param {OneOf} oneof The oneof + * @returns {undefined} + * @inner + * @ignore + */ +function addFieldsToParent(oneof) { + if (oneof.parent) + for (var i = 0; i < oneof.fieldsArray.length; ++i) + if (!oneof.fieldsArray[i].parent) + oneof.parent.add(oneof.fieldsArray[i]); +} + +/** + * Adds a field to this oneof and removes it from its current parent, if any. + * @param {Field} field Field to add + * @returns {OneOf} `this` + */ +OneOf.prototype.add = function add(field) { + + /* istanbul ignore if */ + if (!(field instanceof Field)) + throw TypeError("field must be a Field"); + + if (field.parent && field.parent !== this.parent) + field.parent.remove(field); + this.oneof.push(field.name); + this.fieldsArray.push(field); + field.partOf = this; // field.parent remains null + addFieldsToParent(this); + return this; +}; + +/** + * Removes a field from this oneof and puts it back to the oneof's parent. + * @param {Field} field Field to remove + * @returns {OneOf} `this` + */ +OneOf.prototype.remove = function remove(field) { + + /* istanbul ignore if */ + if (!(field instanceof Field)) + throw TypeError("field must be a Field"); + + var index = this.fieldsArray.indexOf(field); + + /* istanbul ignore if */ + if (index < 0) + throw Error(field + " is not a member of " + this); + + this.fieldsArray.splice(index, 1); + index = this.oneof.indexOf(field.name); + + /* istanbul ignore else */ + if (index > -1) // theoretical + this.oneof.splice(index, 1); + + field.partOf = null; + return this; +}; + +/** + * @override + */ +OneOf.prototype.onAdd = function onAdd(parent) { + ReflectionObject.prototype.onAdd.call(this, parent); + var self = this; + // Collect present fields + for (var i = 0; i < this.oneof.length; ++i) { + var field = parent.get(this.oneof[i]); + if (field && !field.partOf) { + field.partOf = self; + self.fieldsArray.push(field); + } + } + // Add not yet present fields + addFieldsToParent(this); +}; + +/** + * @override + */ +OneOf.prototype.onRemove = function onRemove(parent) { + for (var i = 0, field; i < this.fieldsArray.length; ++i) + if ((field = this.fieldsArray[i]).parent) + field.parent.remove(field); + ReflectionObject.prototype.onRemove.call(this, parent); +}; + +/** + * Determines whether this field corresponds to a synthetic oneof created for + * a proto3 optional field. No behavioral logic should depend on this, but it + * can be relevant for reflection. + * @name OneOf#isProto3Optional + * @type {boolean} + * @readonly + */ +Object.defineProperty(OneOf.prototype, "isProto3Optional", { + get: function() { + if (this.fieldsArray == null || this.fieldsArray.length !== 1) { + return false; + } + + var field = this.fieldsArray[0]; + return field.options != null && field.options["proto3_optional"] === true; + } +}); + +/** + * Decorator function as returned by {@link OneOf.d} (TypeScript). + * @typedef OneOfDecorator + * @type {function} + * @param {Object} prototype Target prototype + * @param {string} oneofName OneOf name + * @returns {undefined} + */ + +/** + * OneOf decorator (TypeScript). + * @function + * @param {...string} fieldNames Field names + * @returns {OneOfDecorator} Decorator function + * @template T extends string + */ +OneOf.d = function decorateOneOf() { + var fieldNames = new Array(arguments.length), + index = 0; + while (index < arguments.length) + fieldNames[index] = arguments[index++]; + return function oneOfDecorator(prototype, oneofName) { + util.decorateType(prototype.constructor) + .add(new OneOf(oneofName, fieldNames)); + Object.defineProperty(prototype, oneofName, { + get: util.oneOfGetter(fieldNames), + set: util.oneOfSetter(fieldNames) + }); + }; +}; + +},{"16":16,"24":24,"37":37}],26:[function(require,module,exports){ +"use strict"; +module.exports = parse; + +parse.filename = null; +parse.defaults = { keepCase: false }; + +var tokenize = require(34), + Root = require(29), + Type = require(35), + Field = require(16), + MapField = require(20), + OneOf = require(25), + Enum = require(15), + Service = require(33), + Method = require(22), + ReflectionObject = require(24), + types = require(36), + util = require(37); + +var base10Re = /^[1-9][0-9]*$/, + base10NegRe = /^-?[1-9][0-9]*$/, + base16Re = /^0[x][0-9a-fA-F]+$/, + base16NegRe = /^-?0[x][0-9a-fA-F]+$/, + base8Re = /^0[0-7]+$/, + base8NegRe = /^-?0[0-7]+$/, + numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/, + nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/, + typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/; + +/** + * Result object returned from {@link parse}. + * @interface IParserResult + * @property {string|undefined} package Package name, if declared + * @property {string[]|undefined} imports Imports, if any + * @property {string[]|undefined} weakImports Weak imports, if any + * @property {Root} root Populated root instance + */ + +/** + * Options modifying the behavior of {@link parse}. + * @interface IParseOptions + * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case + * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments. + * @property {boolean} [preferTrailingComment=false] Use trailing comment when both leading comment and trailing comment exist. + */ + +/** + * Options modifying the behavior of JSON serialization. + * @interface IToJSONOptions + * @property {boolean} [keepComments=false] Serializes comments. + */ + +/** + * Parses the given .proto source and returns an object with the parsed contents. + * @param {string} source Source contents + * @param {Root} root Root to populate + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {IParserResult} Parser result + * @property {string} filename=null Currently processing file name for error reporting, if known + * @property {IParseOptions} defaults Default {@link IParseOptions} + */ +function parse(source, root, options) { + /* eslint-disable callback-return */ + if (!(root instanceof Root)) { + options = root; + root = new Root(); + } + if (!options) + options = parse.defaults; + + var preferTrailingComment = options.preferTrailingComment || false; + var tn = tokenize(source, options.alternateCommentMode || false), + next = tn.next, + push = tn.push, + peek = tn.peek, + skip = tn.skip, + cmnt = tn.cmnt; + + var head = true, + pkg, + imports, + weakImports, + edition = "proto2"; + + var ptr = root; + + var topLevelObjects = []; + var topLevelOptions = {}; + + var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase; + + function resolveFileFeatures() { + topLevelObjects.forEach(obj => { + obj._edition = edition; + Object.keys(topLevelOptions).forEach(opt => { + if (obj.getOption(opt) !== undefined) return; + obj.setOption(opt, topLevelOptions[opt], true); + }); + }); + } + + /* istanbul ignore next */ + function illegal(token, name, insideTryCatch) { + var filename = parse.filename; + if (!insideTryCatch) + parse.filename = null; + return Error("illegal " + (name || "token") + " '" + token + "' (" + (filename ? filename + ", " : "") + "line " + tn.line + ")"); + } + + function readString() { + var values = [], + token; + do { + /* istanbul ignore if */ + if ((token = next()) !== "\"" && token !== "'") + throw illegal(token); + + values.push(next()); + skip(token); + token = peek(); + } while (token === "\"" || token === "'"); + return values.join(""); + } + + function readValue(acceptTypeRef) { + var token = next(); + switch (token) { + case "'": + case "\"": + push(token); + return readString(); + case "true": case "TRUE": + return true; + case "false": case "FALSE": + return false; + } + try { + return parseNumber(token, /* insideTryCatch */ true); + } catch (e) { + /* istanbul ignore else */ + if (acceptTypeRef && typeRefRe.test(token)) + return token; + + /* istanbul ignore next */ + throw illegal(token, "value"); + } + } + + function readRanges(target, acceptStrings) { + var token, start; + do { + if (acceptStrings && ((token = peek()) === "\"" || token === "'")) { + var str = readString(); + target.push(str); + if (edition >= 2023) { + throw illegal(str, "id"); + } + } else { + try { + target.push([ start = parseId(next()), skip("to", true) ? parseId(next()) : start ]); + } catch (err) { + if (acceptStrings && typeRefRe.test(token) && edition >= 2023) { + target.push(token); + } else { + throw err; + } + } + } + } while (skip(",", true)); + var dummy = {options: undefined}; + dummy.setOption = function(name, value) { + if (this.options === undefined) this.options = {}; + this.options[name] = value; + }; + ifBlock( + dummy, + function parseRange_block(token) { + /* istanbul ignore else */ + if (token === "option") { + parseOption(dummy, token); // skip + skip(";"); + } else + throw illegal(token); + }, + function parseRange_line() { + parseInlineOptions(dummy); // skip + }); + } + + function parseNumber(token, insideTryCatch) { + var sign = 1; + if (token.charAt(0) === "-") { + sign = -1; + token = token.substring(1); + } + switch (token) { + case "inf": case "INF": case "Inf": + return sign * Infinity; + case "nan": case "NAN": case "Nan": case "NaN": + return NaN; + case "0": + return 0; + } + if (base10Re.test(token)) + return sign * parseInt(token, 10); + if (base16Re.test(token)) + return sign * parseInt(token, 16); + if (base8Re.test(token)) + return sign * parseInt(token, 8); + + /* istanbul ignore else */ + if (numberRe.test(token)) + return sign * parseFloat(token); + + /* istanbul ignore next */ + throw illegal(token, "number", insideTryCatch); + } + + function parseId(token, acceptNegative) { + switch (token) { + case "max": case "MAX": case "Max": + return 536870911; + case "0": + return 0; + } + + /* istanbul ignore if */ + if (!acceptNegative && token.charAt(0) === "-") + throw illegal(token, "id"); + + if (base10NegRe.test(token)) + return parseInt(token, 10); + if (base16NegRe.test(token)) + return parseInt(token, 16); + + /* istanbul ignore else */ + if (base8NegRe.test(token)) + return parseInt(token, 8); + + /* istanbul ignore next */ + throw illegal(token, "id"); + } + + function parsePackage() { + /* istanbul ignore if */ + if (pkg !== undefined) + throw illegal("package"); + + pkg = next(); + + /* istanbul ignore if */ + if (!typeRefRe.test(pkg)) + throw illegal(pkg, "name"); + + ptr = ptr.define(pkg); + + skip(";"); + } + + function parseImport() { + var token = peek(); + var whichImports; + switch (token) { + case "weak": + whichImports = weakImports || (weakImports = []); + next(); + break; + case "public": + next(); + // eslint-disable-next-line no-fallthrough + default: + whichImports = imports || (imports = []); + break; + } + token = readString(); + skip(";"); + whichImports.push(token); + } + + function parseSyntax() { + skip("="); + edition = readString(); + + /* istanbul ignore if */ + if (edition < 2023) + throw illegal(edition, "syntax"); + + skip(";"); + } + + function parseEdition() { + skip("="); + edition = readString(); + const supportedEditions = ["2023"]; + + /* istanbul ignore if */ + if (!supportedEditions.includes(edition)) + throw illegal(edition, "edition"); + + skip(";"); + } + + + function parseCommon(parent, token) { + switch (token) { + + case "option": + parseOption(parent, token); + skip(";"); + return true; + + case "message": + parseType(parent, token); + return true; + + case "enum": + parseEnum(parent, token); + return true; + + case "service": + parseService(parent, token); + return true; + + case "extend": + parseExtension(parent, token); + return true; + } + return false; + } + + function ifBlock(obj, fnIf, fnElse) { + var trailingLine = tn.line; + if (obj) { + if(typeof obj.comment !== "string") { + obj.comment = cmnt(); // try block-type comment + } + obj.filename = parse.filename; + } + if (skip("{", true)) { + var token; + while ((token = next()) !== "}") + fnIf(token); + skip(";", true); + } else { + if (fnElse) + fnElse(); + skip(";"); + if (obj && (typeof obj.comment !== "string" || preferTrailingComment)) + obj.comment = cmnt(trailingLine) || obj.comment; // try line-type comment + } + } + + function parseType(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "type name"); + + var type = new Type(token); + ifBlock(type, function parseType_block(token) { + if (parseCommon(type, token)) + return; + + switch (token) { + + case "map": + parseMapField(type, token); + break; + + case "required": + if (edition !== "proto2") + throw illegal(token); + /* eslint-disable no-fallthrough */ + case "repeated": + parseField(type, token); + break; + + case "optional": + /* istanbul ignore if */ + if (edition === "proto3") { + parseField(type, "proto3_optional"); + } else if (edition !== "proto2") { + throw illegal(token); + } else { + parseField(type, "optional"); + } + break; + + case "oneof": + parseOneOf(type, token); + break; + + case "extensions": + readRanges(type.extensions || (type.extensions = [])); + break; + + case "reserved": + readRanges(type.reserved || (type.reserved = []), true); + break; + + default: + /* istanbul ignore if */ + if (edition === "proto2" || !typeRefRe.test(token)) { + throw illegal(token); + } + + push(token); + parseField(type, "optional"); + break; + } + }); + parent.add(type); + if (parent === ptr) { + topLevelObjects.push(type); + } + } + + function parseField(parent, rule, extend) { + var type = next(); + if (type === "group") { + parseGroup(parent, rule); + return; + } + // Type names can consume multiple tokens, in multiple variants: + // package.subpackage field tokens: "package.subpackage" [TYPE NAME ENDS HERE] "field" + // package . subpackage field tokens: "package" "." "subpackage" [TYPE NAME ENDS HERE] "field" + // package. subpackage field tokens: "package." "subpackage" [TYPE NAME ENDS HERE] "field" + // package .subpackage field tokens: "package" ".subpackage" [TYPE NAME ENDS HERE] "field" + // Keep reading tokens until we get a type name with no period at the end, + // and the next token does not start with a period. + while (type.endsWith(".") || peek().startsWith(".")) { + type += next(); + } + + /* istanbul ignore if */ + if (!typeRefRe.test(type)) + throw illegal(type, "type"); + + var name = next(); + + /* istanbul ignore if */ + + if (!nameRe.test(name)) + throw illegal(name, "name"); + + name = applyCase(name); + skip("="); + + var field = new Field(name, parseId(next()), type, rule, extend); + + ifBlock(field, function parseField_block(token) { + + /* istanbul ignore else */ + if (token === "option") { + parseOption(field, token); + skip(";"); + } else + throw illegal(token); + + }, function parseField_line() { + parseInlineOptions(field); + }); + + if (rule === "proto3_optional") { + // for proto3 optional fields, we create a single-member Oneof to mimic "optional" behavior + var oneof = new OneOf("_" + name); + field.setOption("proto3_optional", true); + oneof.add(field); + parent.add(oneof); + } else { + parent.add(field); + } + if (parent === ptr) { + topLevelObjects.push(field); + } + } + + function parseGroup(parent, rule) { + if (edition >= 2023) { + throw illegal("group"); + } + var name = next(); + + /* istanbul ignore if */ + if (!nameRe.test(name)) + throw illegal(name, "name"); + + var fieldName = util.lcFirst(name); + if (name === fieldName) + name = util.ucFirst(name); + skip("="); + var id = parseId(next()); + var type = new Type(name); + type.group = true; + var field = new Field(fieldName, id, name, rule); + field.filename = parse.filename; + ifBlock(type, function parseGroup_block(token) { + switch (token) { + + case "option": + parseOption(type, token); + skip(";"); + break; + case "required": + case "repeated": + parseField(type, token); + break; + + case "optional": + /* istanbul ignore if */ + if (edition === "proto3") { + parseField(type, "proto3_optional"); + } else { + parseField(type, "optional"); + } + break; + + case "message": + parseType(type, token); + break; + + case "enum": + parseEnum(type, token); + break; + + case "reserved": + readRanges(type.reserved || (type.reserved = []), true); + break; + + /* istanbul ignore next */ + default: + throw illegal(token); // there are no groups with proto3 semantics + } + }); + parent.add(type) + .add(field); + } + + function parseMapField(parent) { + skip("<"); + var keyType = next(); + + /* istanbul ignore if */ + if (types.mapKey[keyType] === undefined) + throw illegal(keyType, "type"); + + skip(","); + var valueType = next(); + + /* istanbul ignore if */ + if (!typeRefRe.test(valueType)) + throw illegal(valueType, "type"); + + skip(">"); + var name = next(); + + /* istanbul ignore if */ + if (!nameRe.test(name)) + throw illegal(name, "name"); + + skip("="); + var field = new MapField(applyCase(name), parseId(next()), keyType, valueType); + ifBlock(field, function parseMapField_block(token) { + + /* istanbul ignore else */ + if (token === "option") { + parseOption(field, token); + skip(";"); + } else + throw illegal(token); + + }, function parseMapField_line() { + parseInlineOptions(field); + }); + parent.add(field); + } + + function parseOneOf(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "name"); + + var oneof = new OneOf(applyCase(token)); + ifBlock(oneof, function parseOneOf_block(token) { + if (token === "option") { + parseOption(oneof, token); + skip(";"); + } else { + push(token); + parseField(oneof, "optional"); + } + }); + parent.add(oneof); + } + + function parseEnum(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "name"); + + var enm = new Enum(token); + ifBlock(enm, function parseEnum_block(token) { + switch(token) { + case "option": + parseOption(enm, token); + skip(";"); + break; + + case "reserved": + readRanges(enm.reserved || (enm.reserved = []), true); + if(enm.reserved === undefined) enm.reserved = []; + break; + + default: + parseEnumValue(enm, token); + } + }); + parent.add(enm); + if (parent === ptr) { + topLevelObjects.push(enm); + } + } + + function parseEnumValue(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token)) + throw illegal(token, "name"); + + skip("="); + var value = parseId(next(), true), + dummy = { + options: undefined + }; + dummy.getOption = function(name) { + return this.options[name]; + }; + dummy.setOption = function(name, value) { + ReflectionObject.prototype.setOption.call(dummy, name, value); + }; + dummy.setParsedOption = function() { + return undefined; + }; + ifBlock(dummy, function parseEnumValue_block(token) { + + /* istanbul ignore else */ + if (token === "option") { + parseOption(dummy, token); // skip + skip(";"); + } else + throw illegal(token); + + }, function parseEnumValue_line() { + parseInlineOptions(dummy); // skip + }); + parent.add(token, value, dummy.comment, dummy.parsedOptions || dummy.options); + } + + function parseOption(parent, token) { + var option; + var propName; + var isOption = true; + if (token === "option") { + token = next(); + } + + while (token !== "=") { + if (token === "(") { + var parensValue = next(); + skip(")"); + token = "(" + parensValue + ")"; + } + if (isOption) { + isOption = false; + if (token.includes(".") && !token.includes("(")) { + var tokens = token.split("."); + option = tokens[0] + "."; + token = tokens[1]; + continue; + } + option = token; + } else { + propName = propName ? propName += token : token; + } + token = next(); + } + var name = propName ? option.concat(propName) : option; + var optionValue = parseOptionValue(parent, name); + propName = propName && propName[0] === "." ? propName.slice(1) : propName; + option = option && option[option.length - 1] === "." ? option.slice(0, -1) : option; + setParsedOption(parent, option, optionValue, propName); + } + + function parseOptionValue(parent, name) { + // { a: "foo" b { c: "bar" } } + if (skip("{", true)) { + var objectResult = {}; + + while (!skip("}", true)) { + /* istanbul ignore if */ + if (!nameRe.test(token = next())) { + throw illegal(token, "name"); + } + if (token === null) { + throw illegal(token, "end of input"); + } + + var value; + var propName = token; + + skip(":", true); + + if (peek() === "{") { + // option (my_option) = { + // repeated_value: [ "foo", "bar" ] + // }; + value = parseOptionValue(parent, name + "." + token); + } else if (peek() === "[") { + value = []; + var lastValue; + if (skip("[", true)) { + do { + lastValue = readValue(true); + value.push(lastValue); + } while (skip(",", true)); + skip("]"); + if (typeof lastValue !== "undefined") { + setOption(parent, name + "." + token, lastValue); + } + } + } else { + value = readValue(true); + setOption(parent, name + "." + token, value); + } + + var prevValue = objectResult[propName]; + + if (prevValue) + value = [].concat(prevValue).concat(value); + + objectResult[propName] = value; + + // Semicolons and commas can be optional + skip(",", true); + skip(";", true); + } + + return objectResult; + } + + var simpleValue = readValue(true); + setOption(parent, name, simpleValue); + return simpleValue; + // Does not enforce a delimiter to be universal + } + + function setOption(parent, name, value) { + if (ptr === parent && /^features\./.test(name)) { + topLevelOptions[name] = value; + return; + } + if (parent.setOption) + parent.setOption(name, value); + } + + function setParsedOption(parent, name, value, propName) { + if (parent.setParsedOption) + parent.setParsedOption(name, value, propName); + } + + function parseInlineOptions(parent) { + if (skip("[", true)) { + do { + parseOption(parent, "option"); + } while (skip(",", true)); + skip("]"); + } + return parent; + } + + function parseService(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "service name"); + + var service = new Service(token); + ifBlock(service, function parseService_block(token) { + if (parseCommon(service, token)) { + return; + } + + /* istanbul ignore else */ + if (token === "rpc") + parseMethod(service, token); + else + throw illegal(token); + }); + parent.add(service); + if (parent === ptr) { + topLevelObjects.push(service); + } + } + + function parseMethod(parent, token) { + // Get the comment of the preceding line now (if one exists) in case the + // method is defined across multiple lines. + var commentText = cmnt(); + + var type = token; + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "name"); + + var name = token, + requestType, requestStream, + responseType, responseStream; + + skip("("); + if (skip("stream", true)) + requestStream = true; + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) + throw illegal(token); + + requestType = token; + skip(")"); skip("returns"); skip("("); + if (skip("stream", true)) + responseStream = true; + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) + throw illegal(token); + + responseType = token; + skip(")"); + + var method = new Method(name, type, requestType, responseType, requestStream, responseStream); + method.comment = commentText; + ifBlock(method, function parseMethod_block(token) { + + /* istanbul ignore else */ + if (token === "option") { + parseOption(method, token); + skip(";"); + } else + throw illegal(token); + + }); + parent.add(method); + } + + function parseExtension(parent, token) { + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) + throw illegal(token, "reference"); + + var reference = token; + ifBlock(null, function parseExtension_block(token) { + switch (token) { + + case "required": + case "repeated": + parseField(parent, token, reference); + break; + + case "optional": + /* istanbul ignore if */ + if (edition === "proto3") { + parseField(parent, "proto3_optional", reference); + } else { + parseField(parent, "optional", reference); + } + break; + + default: + /* istanbul ignore if */ + if (edition === "proto2" || !typeRefRe.test(token)) + throw illegal(token); + push(token); + parseField(parent, "optional", reference); + break; + } + }); + } + + var token; + while ((token = next()) !== null) { + switch (token) { + + case "package": + + /* istanbul ignore if */ + if (!head) + throw illegal(token); + + parsePackage(); + break; + + case "import": + + /* istanbul ignore if */ + if (!head) + throw illegal(token); + + parseImport(); + break; + + case "syntax": + + /* istanbul ignore if */ + if (!head) + throw illegal(token); + + parseSyntax(); + break; + + case "edition": + /* istanbul ignore if */ + if (!head) + throw illegal(token); + parseEdition(); + break; + + case "option": + parseOption(ptr, token); + skip(";", true); + break; + + default: + + /* istanbul ignore else */ + if (parseCommon(ptr, token)) { + head = false; + continue; + } + + /* istanbul ignore next */ + throw illegal(token); + } + } + + resolveFileFeatures(); + + parse.filename = null; + return { + "package" : pkg, + "imports" : imports, + weakImports : weakImports, + root : root + }; +} + +/** + * Parses the given .proto source and returns an object with the parsed contents. + * @name parse + * @function + * @param {string} source Source contents + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {IParserResult} Parser result + * @property {string} filename=null Currently processing file name for error reporting, if known + * @property {IParseOptions} defaults Default {@link IParseOptions} + * @variation 2 + */ + +},{"15":15,"16":16,"20":20,"22":22,"24":24,"25":25,"29":29,"33":33,"34":34,"35":35,"36":36,"37":37}],27:[function(require,module,exports){ +"use strict"; +module.exports = Reader; + +var util = require(39); + +var BufferReader; // cyclic + +var LongBits = util.LongBits, + utf8 = util.utf8; + +/* istanbul ignore next */ +function indexOutOfRange(reader, writeLength) { + return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); +} + +/** + * Constructs a new reader instance using the specified buffer. + * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`. + * @constructor + * @param {Uint8Array} buffer Buffer to read from + */ +function Reader(buffer) { + + /** + * Read buffer. + * @type {Uint8Array} + */ + this.buf = buffer; + + /** + * Read buffer position. + * @type {number} + */ + this.pos = 0; + + /** + * Read buffer length. + * @type {number} + */ + this.len = buffer.length; +} + +var create_array = typeof Uint8Array !== "undefined" + ? function create_typed_array(buffer) { + if (buffer instanceof Uint8Array || Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + } + /* istanbul ignore next */ + : function create_array(buffer) { + if (Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + }; + +var create = function create() { + return util.Buffer + ? function create_buffer_setup(buffer) { + return (Reader.create = function create_buffer(buffer) { + return util.Buffer.isBuffer(buffer) + ? new BufferReader(buffer) + /* istanbul ignore next */ + : create_array(buffer); + })(buffer); + } + /* istanbul ignore next */ + : create_array; +}; + +/** + * Creates a new reader using the specified buffer. + * @function + * @param {Uint8Array|Buffer} buffer Buffer to read from + * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader} + * @throws {Error} If `buffer` is not a valid buffer + */ +Reader.create = create(); + +Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice; + +/** + * Reads a varint as an unsigned 32 bit value. + * @function + * @returns {number} Value read + */ +Reader.prototype.uint32 = (function read_uint32_setup() { + var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!) + return function read_uint32() { + value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value; + + /* istanbul ignore if */ + if ((this.pos += 5) > this.len) { + this.pos = this.len; + throw indexOutOfRange(this, 10); + } + return value; + }; +})(); + +/** + * Reads a varint as a signed 32 bit value. + * @returns {number} Value read + */ +Reader.prototype.int32 = function read_int32() { + return this.uint32() | 0; +}; + +/** + * Reads a zig-zag encoded varint as a signed 32 bit value. + * @returns {number} Value read + */ +Reader.prototype.sint32 = function read_sint32() { + var value = this.uint32(); + return value >>> 1 ^ -(value & 1) | 0; +}; + +/* eslint-disable no-invalid-this */ + +function readLongVarint() { + // tends to deopt with local vars for octet etc. + var bits = new LongBits(0, 0); + var i = 0; + if (this.len - this.pos > 4) { // fast route (lo) + for (; i < 4; ++i) { + // 1st..4th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + // 5th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; + bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + i = 0; + } else { + for (; i < 3; ++i) { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + // 1st..3th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + // 4th + bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0; + return bits; + } + if (this.len - this.pos > 4) { // fast route (hi) + for (; i < 5; ++i) { + // 6th..10th + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } else { + for (; i < 5; ++i) { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + // 6th..10th + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } + /* istanbul ignore next */ + throw Error("invalid varint encoding"); +} + +/* eslint-enable no-invalid-this */ + +/** + * Reads a varint as a signed 64 bit value. + * @name Reader#int64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a varint as an unsigned 64 bit value. + * @name Reader#uint64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a zig-zag encoded varint as a signed 64 bit value. + * @name Reader#sint64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a varint as a boolean. + * @returns {boolean} Value read + */ +Reader.prototype.bool = function read_bool() { + return this.uint32() !== 0; +}; + +function readFixed32_end(buf, end) { // note that this uses `end`, not `pos` + return (buf[end - 4] + | buf[end - 3] << 8 + | buf[end - 2] << 16 + | buf[end - 1] << 24) >>> 0; +} + +/** + * Reads fixed 32 bits as an unsigned 32 bit integer. + * @returns {number} Value read + */ +Reader.prototype.fixed32 = function read_fixed32() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + return readFixed32_end(this.buf, this.pos += 4); +}; + +/** + * Reads fixed 32 bits as a signed 32 bit integer. + * @returns {number} Value read + */ +Reader.prototype.sfixed32 = function read_sfixed32() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + return readFixed32_end(this.buf, this.pos += 4) | 0; +}; + +/* eslint-disable no-invalid-this */ + +function readFixed64(/* this: Reader */) { + + /* istanbul ignore if */ + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 8); + + return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); +} + +/* eslint-enable no-invalid-this */ + +/** + * Reads fixed 64 bits. + * @name Reader#fixed64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads zig-zag encoded fixed 64 bits. + * @name Reader#sfixed64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a float (32 bit) as a number. + * @function + * @returns {number} Value read + */ +Reader.prototype.float = function read_float() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + var value = util.float.readFloatLE(this.buf, this.pos); + this.pos += 4; + return value; +}; + +/** + * Reads a double (64 bit float) as a number. + * @function + * @returns {number} Value read + */ +Reader.prototype.double = function read_double() { + + /* istanbul ignore if */ + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 4); + + var value = util.float.readDoubleLE(this.buf, this.pos); + this.pos += 8; + return value; +}; + +/** + * Reads a sequence of bytes preceeded by its length as a varint. + * @returns {Uint8Array} Value read + */ +Reader.prototype.bytes = function read_bytes() { + var length = this.uint32(), + start = this.pos, + end = this.pos + length; + + /* istanbul ignore if */ + if (end > this.len) + throw indexOutOfRange(this, length); + + this.pos += length; + if (Array.isArray(this.buf)) // plain array + return this.buf.slice(start, end); + + if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1 + var nativeBuffer = util.Buffer; + return nativeBuffer + ? nativeBuffer.alloc(0) + : new this.buf.constructor(0); + } + return this._slice.call(this.buf, start, end); +}; + +/** + * Reads a string preceeded by its byte length as a varint. + * @returns {string} Value read + */ +Reader.prototype.string = function read_string() { + var bytes = this.bytes(); + return utf8.read(bytes, 0, bytes.length); +}; + +/** + * Skips the specified number of bytes if specified, otherwise skips a varint. + * @param {number} [length] Length if known, otherwise a varint is assumed + * @returns {Reader} `this` + */ +Reader.prototype.skip = function skip(length) { + if (typeof length === "number") { + /* istanbul ignore if */ + if (this.pos + length > this.len) + throw indexOutOfRange(this, length); + this.pos += length; + } else { + do { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + } while (this.buf[this.pos++] & 128); + } + return this; +}; + +/** + * Skips the next element of the specified wire type. + * @param {number} wireType Wire type received + * @returns {Reader} `this` + */ +Reader.prototype.skipType = function(wireType) { + switch (wireType) { + case 0: + this.skip(); + break; + case 1: + this.skip(8); + break; + case 2: + this.skip(this.uint32()); + break; + case 3: + while ((wireType = this.uint32() & 7) !== 4) { + this.skipType(wireType); + } + break; + case 5: + this.skip(4); + break; + + /* istanbul ignore next */ + default: + throw Error("invalid wire type " + wireType + " at offset " + this.pos); + } + return this; +}; + +Reader._configure = function(BufferReader_) { + BufferReader = BufferReader_; + Reader.create = create(); + BufferReader._configure(); + + var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber"; + util.merge(Reader.prototype, { + + int64: function read_int64() { + return readLongVarint.call(this)[fn](false); + }, + + uint64: function read_uint64() { + return readLongVarint.call(this)[fn](true); + }, + + sint64: function read_sint64() { + return readLongVarint.call(this).zzDecode()[fn](false); + }, + + fixed64: function read_fixed64() { + return readFixed64.call(this)[fn](true); + }, + + sfixed64: function read_sfixed64() { + return readFixed64.call(this)[fn](false); + } + + }); +}; + +},{"39":39}],28:[function(require,module,exports){ +"use strict"; +module.exports = BufferReader; + +// extends Reader +var Reader = require(27); +(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; + +var util = require(39); + +/** + * Constructs a new buffer reader instance. + * @classdesc Wire format reader using node buffers. + * @extends Reader + * @constructor + * @param {Buffer} buffer Buffer to read from + */ +function BufferReader(buffer) { + Reader.call(this, buffer); + + /** + * Read buffer. + * @name BufferReader#buf + * @type {Buffer} + */ +} + +BufferReader._configure = function () { + /* istanbul ignore else */ + if (util.Buffer) + BufferReader.prototype._slice = util.Buffer.prototype.slice; +}; + + +/** + * @override + */ +BufferReader.prototype.string = function read_string_buffer() { + var len = this.uint32(); // modifies pos + return this.buf.utf8Slice + ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) + : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len)); +}; + +/** + * Reads a sequence of bytes preceeded by its length as a varint. + * @name BufferReader#bytes + * @function + * @returns {Buffer} Value read + */ + +BufferReader._configure(); + +},{"27":27,"39":39}],29:[function(require,module,exports){ +"use strict"; +module.exports = Root; + +// extends Namespace +var Namespace = require(23); +((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root"; + +var Field = require(16), + Enum = require(15), + OneOf = require(25), + util = require(37); + +var Type, // cyclic + parse, // might be excluded + common; // " + +/** + * Constructs a new root namespace instance. + * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together. + * @extends NamespaceBase + * @constructor + * @param {Object.} [options] Top level options + */ +function Root(options) { + Namespace.call(this, "", options); + + /** + * Deferred extension fields. + * @type {Field[]} + */ + this.deferred = []; + + /** + * Resolved file names of loaded files. + * @type {string[]} + */ + this.files = []; + + /** + * Edition, defaults to proto2 if unspecified. + * @type {string} + * @private + */ + this._edition = "proto2"; + + /** + * Global lookup cache of fully qualified names. + * @type {Object.} + * @private + */ + this._fullyQualifiedObjects = {}; +} + +/** + * Loads a namespace descriptor into a root namespace. + * @param {INamespace} json Namespace descriptor + * @param {Root} [root] Root namespace, defaults to create a new one if omitted + * @returns {Root} Root namespace + */ +Root.fromJSON = function fromJSON(json, root) { + if (!root) + root = new Root(); + if (json.options) + root.setOptions(json.options); + return root.addJSON(json.nested).resolveAll(); +}; + +/** + * Resolves the path of an imported file, relative to the importing origin. + * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories. + * @function + * @param {string} origin The file name of the importing file + * @param {string} target The file name being imported + * @returns {string|null} Resolved path to `target` or `null` to skip the file + */ +Root.prototype.resolvePath = util.path.resolve; + +/** + * Fetch content from file path or url + * This method exists so you can override it with your own logic. + * @function + * @param {string} path File path or url + * @param {FetchCallback} callback Callback function + * @returns {undefined} + */ +Root.prototype.fetch = util.fetch; + +// A symbol-like function to safely signal synchronous loading +/* istanbul ignore next */ +function SYNC() {} // eslint-disable-line no-empty-function + +/** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} options Parse options + * @param {LoadCallback} callback Callback function + * @returns {undefined} + */ +Root.prototype.load = function load(filename, options, callback) { + if (typeof options === "function") { + callback = options; + options = undefined; + } + var self = this; + if (!callback) { + return util.asPromise(load, self, filename, options); + } + + var sync = callback === SYNC; // undocumented + + // Finishes loading by calling the callback (exactly once) + function finish(err, root) { + /* istanbul ignore if */ + if (!callback) { + return; + } + if (sync) { + throw err; + } + if (root) { + root.resolveAll(); + } + var cb = callback; + callback = null; + cb(err, root); + } + + // Bundled definition existence checking + function getBundledFileName(filename) { + var idx = filename.lastIndexOf("google/protobuf/"); + if (idx > -1) { + var altname = filename.substring(idx); + if (altname in common) return altname; + } + return null; + } + + // Processes a single file + function process(filename, source) { + try { + if (util.isString(source) && source.charAt(0) === "{") + source = JSON.parse(source); + if (!util.isString(source)) + self.setOptions(source.options).addJSON(source.nested); + else { + parse.filename = filename; + var parsed = parse(source, self, options), + resolved, + i = 0; + if (parsed.imports) + for (; i < parsed.imports.length; ++i) + if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i])) + fetch(resolved); + if (parsed.weakImports) + for (i = 0; i < parsed.weakImports.length; ++i) + if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i])) + fetch(resolved, true); + } + } catch (err) { + finish(err); + } + if (!sync && !queued) { + finish(null, self); // only once anyway + } + } + + // Fetches a single file + function fetch(filename, weak) { + filename = getBundledFileName(filename) || filename; + + // Skip if already loaded / attempted + if (self.files.indexOf(filename) > -1) { + return; + } + self.files.push(filename); + + // Shortcut bundled definitions + if (filename in common) { + if (sync) { + process(filename, common[filename]); + } else { + ++queued; + setTimeout(function() { + --queued; + process(filename, common[filename]); + }); + } + return; + } + + // Otherwise fetch from disk or network + if (sync) { + var source; + try { + source = util.fs.readFileSync(filename).toString("utf8"); + } catch (err) { + if (!weak) + finish(err); + return; + } + process(filename, source); + } else { + ++queued; + self.fetch(filename, function(err, source) { + --queued; + /* istanbul ignore if */ + if (!callback) { + return; // terminated meanwhile + } + if (err) { + /* istanbul ignore else */ + if (!weak) + finish(err); + else if (!queued) // can't be covered reliably + finish(null, self); + return; + } + process(filename, source); + }); + } + } + var queued = 0; + + // Assembling the root namespace doesn't require working type + // references anymore, so we can load everything in parallel + if (util.isString(filename)) { + filename = [ filename ]; + } + for (var i = 0, resolved; i < filename.length; ++i) + if (resolved = self.resolvePath("", filename[i])) + fetch(resolved); + if (sync) { + self.resolveAll(); + return self; + } + if (!queued) { + finish(null, self); + } + + return self; +}; +// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined + +/** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. + * @function Root#load + * @param {string|string[]} filename Names of one or multiple files to load + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @variation 2 + */ +// function load(filename:string, callback:LoadCallback):undefined + +/** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise. + * @function Root#load + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {Promise} Promise + * @variation 3 + */ +// function load(filename:string, [options:IParseOptions]):Promise + +/** + * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only). + * @function Root#loadSync + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {Root} Root namespace + * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid + */ +Root.prototype.loadSync = function loadSync(filename, options) { + if (!util.isNode) + throw Error("not supported"); + return this.load(filename, options, SYNC); +}; + +/** + * @override + */ +Root.prototype.resolveAll = function resolveAll() { + if (!this._needsRecursiveResolve) return this; + + if (this.deferred.length) + throw Error("unresolvable extensions: " + this.deferred.map(function(field) { + return "'extend " + field.extend + "' in " + field.parent.fullName; + }).join(", ")); + return Namespace.prototype.resolveAll.call(this); +}; + +// only uppercased (and thus conflict-free) children are exposed, see below +var exposeRe = /^[A-Z]/; + +/** + * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type. + * @param {Root} root Root instance + * @param {Field} field Declaring extension field witin the declaring type + * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise + * @inner + * @ignore + */ +function tryHandleExtension(root, field) { + var extendedType = field.parent.lookup(field.extend); + if (extendedType) { + var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options); + //do not allow to extend same field twice to prevent the error + if (extendedType.get(sisterField.name)) { + return true; + } + sisterField.declaringField = field; + field.extensionField = sisterField; + extendedType.add(sisterField); + return true; + } + return false; +} + +/** + * Called when any object is added to this root or its sub-namespaces. + * @param {ReflectionObject} object Object added + * @returns {undefined} + * @private + */ +Root.prototype._handleAdd = function _handleAdd(object) { + if (object instanceof Field) { + + if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField) + if (!tryHandleExtension(this, object)) + this.deferred.push(object); + + } else if (object instanceof Enum) { + + if (exposeRe.test(object.name)) + object.parent[object.name] = object.values; // expose enum values as property of its parent + + } else if (!(object instanceof OneOf)) /* everything else is a namespace */ { + + if (object instanceof Type) // Try to handle any deferred extensions + for (var i = 0; i < this.deferred.length;) + if (tryHandleExtension(this, this.deferred[i])) + this.deferred.splice(i, 1); + else + ++i; + for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace + this._handleAdd(object._nestedArray[j]); + if (exposeRe.test(object.name)) + object.parent[object.name] = object; // expose namespace as property of its parent + } + + if (object instanceof Type || object instanceof Enum || object instanceof Field) { + // Only store types and enums for quick lookup during resolve. + this._fullyQualifiedObjects[object.fullName] = object; + } + + // The above also adds uppercased (and thus conflict-free) nested types, services and enums as + // properties of namespaces just like static code does. This allows using a .d.ts generated for + // a static module with reflection-based solutions where the condition is met. +}; + +/** + * Called when any object is removed from this root or its sub-namespaces. + * @param {ReflectionObject} object Object removed + * @returns {undefined} + * @private + */ +Root.prototype._handleRemove = function _handleRemove(object) { + if (object instanceof Field) { + + if (/* an extension field */ object.extend !== undefined) { + if (/* already handled */ object.extensionField) { // remove its sister field + object.extensionField.parent.remove(object.extensionField); + object.extensionField = null; + } else { // cancel the extension + var index = this.deferred.indexOf(object); + /* istanbul ignore else */ + if (index > -1) + this.deferred.splice(index, 1); + } + } + + } else if (object instanceof Enum) { + + if (exposeRe.test(object.name)) + delete object.parent[object.name]; // unexpose enum values + + } else if (object instanceof Namespace) { + + for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace + this._handleRemove(object._nestedArray[i]); + + if (exposeRe.test(object.name)) + delete object.parent[object.name]; // unexpose namespaces + + } + + delete this._fullyQualifiedObjects[object.fullName]; +}; + +// Sets up cyclic dependencies (called in index-light) +Root._configure = function(Type_, parse_, common_) { + Type = Type_; + parse = parse_; + common = common_; +}; + +},{"15":15,"16":16,"23":23,"25":25,"37":37}],30:[function(require,module,exports){ +"use strict"; +module.exports = {}; + +/** + * Named roots. + * This is where pbjs stores generated structures (the option `-r, --root` specifies a name). + * Can also be used manually to make roots available across modules. + * @name roots + * @type {Object.} + * @example + * // pbjs -r myroot -o compiled.js ... + * + * // in another module: + * require("./compiled.js"); + * + * // in any subsequent module: + * var root = protobuf.roots["myroot"]; + */ + +},{}],31:[function(require,module,exports){ +"use strict"; + +/** + * Streaming RPC helpers. + * @namespace + */ +var rpc = exports; + +/** + * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets. + * @typedef RPCImpl + * @type {function} + * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called + * @param {Uint8Array} requestData Request data + * @param {RPCImplCallback} callback Callback function + * @returns {undefined} + * @example + * function rpcImpl(method, requestData, callback) { + * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code + * throw Error("no such method"); + * asynchronouslyObtainAResponse(requestData, function(err, responseData) { + * callback(err, responseData); + * }); + * } + */ + +/** + * Node-style callback as used by {@link RPCImpl}. + * @typedef RPCImplCallback + * @type {function} + * @param {Error|null} error Error, if any, otherwise `null` + * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error + * @returns {undefined} + */ + +rpc.Service = require(32); + +},{"32":32}],32:[function(require,module,exports){ +"use strict"; +module.exports = Service; + +var util = require(39); + +// Extends EventEmitter +(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; + +/** + * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}. + * + * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`. + * @typedef rpc.ServiceMethodCallback + * @template TRes extends Message + * @type {function} + * @param {Error|null} error Error, if any + * @param {TRes} [response] Response message + * @returns {undefined} + */ + +/** + * A service method part of a {@link rpc.Service} as created by {@link Service.create}. + * @typedef rpc.ServiceMethod + * @template TReq extends Message + * @template TRes extends Message + * @type {function} + * @param {TReq|Properties} request Request message or plain object + * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message + * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined` + */ + +/** + * Constructs a new RPC service instance. + * @classdesc An RPC service as returned by {@link Service#create}. + * @exports rpc.Service + * @extends util.EventEmitter + * @constructor + * @param {RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ +function Service(rpcImpl, requestDelimited, responseDelimited) { + + if (typeof rpcImpl !== "function") + throw TypeError("rpcImpl must be a function"); + + util.EventEmitter.call(this); + + /** + * RPC implementation. Becomes `null` once the service is ended. + * @type {RPCImpl|null} + */ + this.rpcImpl = rpcImpl; + + /** + * Whether requests are length-delimited. + * @type {boolean} + */ + this.requestDelimited = Boolean(requestDelimited); + + /** + * Whether responses are length-delimited. + * @type {boolean} + */ + this.responseDelimited = Boolean(responseDelimited); +} + +/** + * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}. + * @param {Method|rpc.ServiceMethod} method Reflected or static method + * @param {Constructor} requestCtor Request constructor + * @param {Constructor} responseCtor Response constructor + * @param {TReq|Properties} request Request message or plain object + * @param {rpc.ServiceMethodCallback} callback Service callback + * @returns {undefined} + * @template TReq extends Message + * @template TRes extends Message + */ +Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) { + + if (!request) + throw TypeError("request must be specified"); + + var self = this; + if (!callback) + return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request); + + if (!self.rpcImpl) { + setTimeout(function() { callback(Error("already ended")); }, 0); + return undefined; + } + + try { + return self.rpcImpl( + method, + requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(), + function rpcCallback(err, response) { + + if (err) { + self.emit("error", err, method); + return callback(err); + } + + if (response === null) { + self.end(/* endedByRPC */ true); + return undefined; + } + + if (!(response instanceof responseCtor)) { + try { + response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response); + } catch (err) { + self.emit("error", err, method); + return callback(err); + } + } + + self.emit("data", response, method); + return callback(null, response); + } + ); + } catch (err) { + self.emit("error", err, method); + setTimeout(function() { callback(err); }, 0); + return undefined; + } +}; + +/** + * Ends this service and emits the `end` event. + * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation. + * @returns {rpc.Service} `this` + */ +Service.prototype.end = function end(endedByRPC) { + if (this.rpcImpl) { + if (!endedByRPC) // signal end to rpcImpl + this.rpcImpl(null, null, null); + this.rpcImpl = null; + this.emit("end").off(); + } + return this; +}; + +},{"39":39}],33:[function(require,module,exports){ +"use strict"; +module.exports = Service; + +// extends Namespace +var Namespace = require(23); +((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service"; + +var Method = require(22), + util = require(37), + rpc = require(31); + +/** + * Constructs a new service instance. + * @classdesc Reflected service. + * @extends NamespaceBase + * @constructor + * @param {string} name Service name + * @param {Object.} [options] Service options + * @throws {TypeError} If arguments are invalid + */ +function Service(name, options) { + Namespace.call(this, name, options); + + /** + * Service methods. + * @type {Object.} + */ + this.methods = {}; // toJSON, marker + + /** + * Cached methods as an array. + * @type {Method[]|null} + * @private + */ + this._methodsArray = null; +} + +/** + * Service descriptor. + * @interface IService + * @extends INamespace + * @property {Object.} methods Method descriptors + */ + +/** + * Constructs a service from a service descriptor. + * @param {string} name Service name + * @param {IService} json Service descriptor + * @returns {Service} Created service + * @throws {TypeError} If arguments are invalid + */ +Service.fromJSON = function fromJSON(name, json) { + var service = new Service(name, json.options); + /* istanbul ignore else */ + if (json.methods) + for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i) + service.add(Method.fromJSON(names[i], json.methods[names[i]])); + if (json.nested) + service.addJSON(json.nested); + if (json.edition) + service._edition = json.edition; + service.comment = json.comment; + service._defaultEdition = "proto3"; // For backwards-compatibility. + return service; +}; + +/** + * Converts this service to a service descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IService} Service descriptor + */ +Service.prototype.toJSON = function toJSON(toJSONOptions) { + var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "edition" , this._editionToJSON(), + "options" , inherited && inherited.options || undefined, + "methods" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {}, + "nested" , inherited && inherited.nested || undefined, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * Methods of this service as an array for iteration. + * @name Service#methodsArray + * @type {Method[]} + * @readonly + */ +Object.defineProperty(Service.prototype, "methodsArray", { + get: function() { + return this._methodsArray || (this._methodsArray = util.toArray(this.methods)); + } +}); + +function clearCache(service) { + service._methodsArray = null; + return service; +} + +/** + * @override + */ +Service.prototype.get = function get(name) { + return this.methods[name] + || Namespace.prototype.get.call(this, name); +}; + +/** + * @override + */ +Service.prototype.resolveAll = function resolveAll() { + if (!this._needsRecursiveResolve) return this; + + Namespace.prototype.resolve.call(this); + var methods = this.methodsArray; + for (var i = 0; i < methods.length; ++i) + methods[i].resolve(); + return this; +}; + +/** + * @override + */ +Service.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { + if (!this._needsRecursiveFeatureResolution) return this; + + edition = this._edition || edition; + + Namespace.prototype._resolveFeaturesRecursive.call(this, edition); + this.methodsArray.forEach(method => { + method._resolveFeaturesRecursive(edition); + }); + return this; +}; + +/** + * @override + */ +Service.prototype.add = function add(object) { + + /* istanbul ignore if */ + if (this.get(object.name)) + throw Error("duplicate name '" + object.name + "' in " + this); + + if (object instanceof Method) { + this.methods[object.name] = object; + object.parent = this; + return clearCache(this); + } + return Namespace.prototype.add.call(this, object); +}; + +/** + * @override + */ +Service.prototype.remove = function remove(object) { + if (object instanceof Method) { + + /* istanbul ignore if */ + if (this.methods[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.methods[object.name]; + object.parent = null; + return clearCache(this); + } + return Namespace.prototype.remove.call(this, object); +}; + +/** + * Creates a runtime service using the specified rpc implementation. + * @param {RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed. + */ +Service.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) { + var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited); + for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) { + var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, ""); + rpcService[methodName] = util.codegen(["r","c"], util.isReserved(methodName) ? methodName + "_" : methodName)("return this.rpcCall(m,q,s,r,c)")({ + m: method, + q: method.resolvedRequestType.ctor, + s: method.resolvedResponseType.ctor + }); + } + return rpcService; +}; + +},{"22":22,"23":23,"31":31,"37":37}],34:[function(require,module,exports){ +"use strict"; +module.exports = tokenize; + +var delimRe = /[\s{}=;:[\],'"()<>]/g, + stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g, + stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g; + +var setCommentRe = /^ *[*/]+ */, + setCommentAltRe = /^\s*\*?\/*/, + setCommentSplitRe = /\n/g, + whitespaceRe = /\s/, + unescapeRe = /\\(.?)/g; + +var unescapeMap = { + "0": "\0", + "r": "\r", + "n": "\n", + "t": "\t" +}; + +/** + * Unescapes a string. + * @param {string} str String to unescape + * @returns {string} Unescaped string + * @property {Object.} map Special characters map + * @memberof tokenize + */ +function unescape(str) { + return str.replace(unescapeRe, function($0, $1) { + switch ($1) { + case "\\": + case "": + return $1; + default: + return unescapeMap[$1] || ""; + } + }); +} + +tokenize.unescape = unescape; + +/** + * Gets the next token and advances. + * @typedef TokenizerHandleNext + * @type {function} + * @returns {string|null} Next token or `null` on eof + */ + +/** + * Peeks for the next token. + * @typedef TokenizerHandlePeek + * @type {function} + * @returns {string|null} Next token or `null` on eof + */ + +/** + * Pushes a token back to the stack. + * @typedef TokenizerHandlePush + * @type {function} + * @param {string} token Token + * @returns {undefined} + */ + +/** + * Skips the next token. + * @typedef TokenizerHandleSkip + * @type {function} + * @param {string} expected Expected token + * @param {boolean} [optional=false] If optional + * @returns {boolean} Whether the token matched + * @throws {Error} If the token didn't match and is not optional + */ + +/** + * Gets the comment on the previous line or, alternatively, the line comment on the specified line. + * @typedef TokenizerHandleCmnt + * @type {function} + * @param {number} [line] Line number + * @returns {string|null} Comment text or `null` if none + */ + +/** + * Handle object returned from {@link tokenize}. + * @interface ITokenizerHandle + * @property {TokenizerHandleNext} next Gets the next token and advances (`null` on eof) + * @property {TokenizerHandlePeek} peek Peeks for the next token (`null` on eof) + * @property {TokenizerHandlePush} push Pushes a token back to the stack + * @property {TokenizerHandleSkip} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws + * @property {TokenizerHandleCmnt} cmnt Gets the comment on the previous line or the line comment on the specified line, if any + * @property {number} line Current line number + */ + +/** + * Tokenizes the given .proto source and returns an object with useful utility functions. + * @param {string} source Source contents + * @param {boolean} alternateCommentMode Whether we should activate alternate comment parsing mode. + * @returns {ITokenizerHandle} Tokenizer handle + */ +function tokenize(source, alternateCommentMode) { + /* eslint-disable callback-return */ + source = source.toString(); + + var offset = 0, + length = source.length, + line = 1, + lastCommentLine = 0, + comments = {}; + + var stack = []; + + var stringDelim = null; + + /* istanbul ignore next */ + /** + * Creates an error for illegal syntax. + * @param {string} subject Subject + * @returns {Error} Error created + * @inner + */ + function illegal(subject) { + return Error("illegal " + subject + " (line " + line + ")"); + } + + /** + * Reads a string till its end. + * @returns {string} String read + * @inner + */ + function readString() { + var re = stringDelim === "'" ? stringSingleRe : stringDoubleRe; + re.lastIndex = offset - 1; + var match = re.exec(source); + if (!match) + throw illegal("string"); + offset = re.lastIndex; + push(stringDelim); + stringDelim = null; + return unescape(match[1]); + } + + /** + * Gets the character at `pos` within the source. + * @param {number} pos Position + * @returns {string} Character + * @inner + */ + function charAt(pos) { + return source.charAt(pos); + } + + /** + * Sets the current comment text. + * @param {number} start Start offset + * @param {number} end End offset + * @param {boolean} isLeading set if a leading comment + * @returns {undefined} + * @inner + */ + function setComment(start, end, isLeading) { + var comment = { + type: source.charAt(start++), + lineEmpty: false, + leading: isLeading, + }; + var lookback; + if (alternateCommentMode) { + lookback = 2; // alternate comment parsing: "//" or "/*" + } else { + lookback = 3; // "///" or "/**" + } + var commentOffset = start - lookback, + c; + do { + if (--commentOffset < 0 || + (c = source.charAt(commentOffset)) === "\n") { + comment.lineEmpty = true; + break; + } + } while (c === " " || c === "\t"); + var lines = source + .substring(start, end) + .split(setCommentSplitRe); + for (var i = 0; i < lines.length; ++i) + lines[i] = lines[i] + .replace(alternateCommentMode ? setCommentAltRe : setCommentRe, "") + .trim(); + comment.text = lines + .join("\n") + .trim(); + + comments[line] = comment; + lastCommentLine = line; + } + + function isDoubleSlashCommentLine(startOffset) { + var endOffset = findEndOfLine(startOffset); + + // see if remaining line matches comment pattern + var lineText = source.substring(startOffset, endOffset); + var isComment = /^\s*\/\//.test(lineText); + return isComment; + } + + function findEndOfLine(cursor) { + // find end of cursor's line + var endOffset = cursor; + while (endOffset < length && charAt(endOffset) !== "\n") { + endOffset++; + } + return endOffset; + } + + /** + * Obtains the next token. + * @returns {string|null} Next token or `null` on eof + * @inner + */ + function next() { + if (stack.length > 0) + return stack.shift(); + if (stringDelim) + return readString(); + var repeat, + prev, + curr, + start, + isDoc, + isLeadingComment = offset === 0; + do { + if (offset === length) + return null; + repeat = false; + while (whitespaceRe.test(curr = charAt(offset))) { + if (curr === "\n") { + isLeadingComment = true; + ++line; + } + if (++offset === length) + return null; + } + + if (charAt(offset) === "/") { + if (++offset === length) { + throw illegal("comment"); + } + if (charAt(offset) === "/") { // Line + if (!alternateCommentMode) { + // check for triple-slash comment + isDoc = charAt(start = offset + 1) === "/"; + + while (charAt(++offset) !== "\n") { + if (offset === length) { + return null; + } + } + ++offset; + if (isDoc) { + setComment(start, offset - 1, isLeadingComment); + // Trailing comment cannot not be multi-line, + // so leading comment state should be reset to handle potential next comments + isLeadingComment = true; + } + ++line; + repeat = true; + } else { + // check for double-slash comments, consolidating consecutive lines + start = offset; + isDoc = false; + if (isDoubleSlashCommentLine(offset - 1)) { + isDoc = true; + do { + offset = findEndOfLine(offset); + if (offset === length) { + break; + } + offset++; + if (!isLeadingComment) { + // Trailing comment cannot not be multi-line + break; + } + } while (isDoubleSlashCommentLine(offset)); + } else { + offset = Math.min(length, findEndOfLine(offset) + 1); + } + if (isDoc) { + setComment(start, offset, isLeadingComment); + isLeadingComment = true; + } + line++; + repeat = true; + } + } else if ((curr = charAt(offset)) === "*") { /* Block */ + // check for /** (regular comment mode) or /* (alternate comment mode) + start = offset + 1; + isDoc = alternateCommentMode || charAt(start) === "*"; + do { + if (curr === "\n") { + ++line; + } + if (++offset === length) { + throw illegal("comment"); + } + prev = curr; + curr = charAt(offset); + } while (prev !== "*" || curr !== "/"); + ++offset; + if (isDoc) { + setComment(start, offset - 2, isLeadingComment); + isLeadingComment = true; + } + repeat = true; + } else { + return "/"; + } + } + } while (repeat); + + // offset !== length if we got here + + var end = offset; + delimRe.lastIndex = 0; + var delim = delimRe.test(charAt(end++)); + if (!delim) + while (end < length && !delimRe.test(charAt(end))) + ++end; + var token = source.substring(offset, offset = end); + if (token === "\"" || token === "'") + stringDelim = token; + return token; + } + + /** + * Pushes a token back to the stack. + * @param {string} token Token + * @returns {undefined} + * @inner + */ + function push(token) { + stack.push(token); + } + + /** + * Peeks for the next token. + * @returns {string|null} Token or `null` on eof + * @inner + */ + function peek() { + if (!stack.length) { + var token = next(); + if (token === null) + return null; + push(token); + } + return stack[0]; + } + + /** + * Skips a token. + * @param {string} expected Expected token + * @param {boolean} [optional=false] Whether the token is optional + * @returns {boolean} `true` when skipped, `false` if not + * @throws {Error} When a required token is not present + * @inner + */ + function skip(expected, optional) { + var actual = peek(), + equals = actual === expected; + if (equals) { + next(); + return true; + } + if (!optional) + throw illegal("token '" + actual + "', '" + expected + "' expected"); + return false; + } + + /** + * Gets a comment. + * @param {number} [trailingLine] Line number if looking for a trailing comment + * @returns {string|null} Comment text + * @inner + */ + function cmnt(trailingLine) { + var ret = null; + var comment; + if (trailingLine === undefined) { + comment = comments[line - 1]; + delete comments[line - 1]; + if (comment && (alternateCommentMode || comment.type === "*" || comment.lineEmpty)) { + ret = comment.leading ? comment.text : null; + } + } else { + /* istanbul ignore else */ + if (lastCommentLine < trailingLine) { + peek(); + } + comment = comments[trailingLine]; + delete comments[trailingLine]; + if (comment && !comment.lineEmpty && (alternateCommentMode || comment.type === "/")) { + ret = comment.leading ? null : comment.text; + } + } + return ret; + } + + return Object.defineProperty({ + next: next, + peek: peek, + push: push, + skip: skip, + cmnt: cmnt + }, "line", { + get: function() { return line; } + }); + /* eslint-enable callback-return */ +} + +},{}],35:[function(require,module,exports){ +"use strict"; +module.exports = Type; + +// extends Namespace +var Namespace = require(23); +((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type"; + +var Enum = require(15), + OneOf = require(25), + Field = require(16), + MapField = require(20), + Service = require(33), + Message = require(21), + Reader = require(27), + Writer = require(42), + util = require(37), + encoder = require(14), + decoder = require(13), + verifier = require(40), + converter = require(12), + wrappers = require(41); + +/** + * Constructs a new reflected message type instance. + * @classdesc Reflected message type. + * @extends NamespaceBase + * @constructor + * @param {string} name Message name + * @param {Object.} [options] Declared options + */ +function Type(name, options) { + Namespace.call(this, name, options); + + /** + * Message fields. + * @type {Object.} + */ + this.fields = {}; // toJSON, marker + + /** + * Oneofs declared within this namespace, if any. + * @type {Object.} + */ + this.oneofs = undefined; // toJSON + + /** + * Extension ranges, if any. + * @type {number[][]} + */ + this.extensions = undefined; // toJSON + + /** + * Reserved ranges, if any. + * @type {Array.} + */ + this.reserved = undefined; // toJSON + + /*? + * Whether this type is a legacy group. + * @type {boolean|undefined} + */ + this.group = undefined; // toJSON + + /** + * Cached fields by id. + * @type {Object.|null} + * @private + */ + this._fieldsById = null; + + /** + * Cached fields as an array. + * @type {Field[]|null} + * @private + */ + this._fieldsArray = null; + + /** + * Cached oneofs as an array. + * @type {OneOf[]|null} + * @private + */ + this._oneofsArray = null; + + /** + * Cached constructor. + * @type {Constructor<{}>} + * @private + */ + this._ctor = null; +} + +Object.defineProperties(Type.prototype, { + + /** + * Message fields by id. + * @name Type#fieldsById + * @type {Object.} + * @readonly + */ + fieldsById: { + get: function() { + + /* istanbul ignore if */ + if (this._fieldsById) + return this._fieldsById; + + this._fieldsById = {}; + for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) { + var field = this.fields[names[i]], + id = field.id; + + /* istanbul ignore if */ + if (this._fieldsById[id]) + throw Error("duplicate id " + id + " in " + this); + + this._fieldsById[id] = field; + } + return this._fieldsById; + } + }, + + /** + * Fields of this message as an array for iteration. + * @name Type#fieldsArray + * @type {Field[]} + * @readonly + */ + fieldsArray: { + get: function() { + return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields)); + } + }, + + /** + * Oneofs of this message as an array for iteration. + * @name Type#oneofsArray + * @type {OneOf[]} + * @readonly + */ + oneofsArray: { + get: function() { + return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs)); + } + }, + + /** + * The registered constructor, if any registered, otherwise a generic constructor. + * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor. + * @name Type#ctor + * @type {Constructor<{}>} + */ + ctor: { + get: function() { + return this._ctor || (this.ctor = Type.generateConstructor(this)()); + }, + set: function(ctor) { + + // Ensure proper prototype + var prototype = ctor.prototype; + if (!(prototype instanceof Message)) { + (ctor.prototype = new Message()).constructor = ctor; + util.merge(ctor.prototype, prototype); + } + + // Classes and messages reference their reflected type + ctor.$type = ctor.prototype.$type = this; + + // Mix in static methods + util.merge(ctor, Message, true); + + this._ctor = ctor; + + // Messages have non-enumerable default values on their prototype + var i = 0; + for (; i < /* initializes */ this.fieldsArray.length; ++i) + this._fieldsArray[i].resolve(); // ensures a proper value + + // Messages have non-enumerable getters and setters for each virtual oneof field + var ctorProperties = {}; + for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i) + ctorProperties[this._oneofsArray[i].resolve().name] = { + get: util.oneOfGetter(this._oneofsArray[i].oneof), + set: util.oneOfSetter(this._oneofsArray[i].oneof) + }; + if (i) + Object.defineProperties(ctor.prototype, ctorProperties); + } + } +}); + +/** + * Generates a constructor function for the specified type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +Type.generateConstructor = function generateConstructor(mtype) { + /* eslint-disable no-unexpected-multiline */ + var gen = util.codegen(["p"], mtype.name); + // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype + for (var i = 0, field; i < mtype.fieldsArray.length; ++i) + if ((field = mtype._fieldsArray[i]).map) gen + ("this%s={}", util.safeProp(field.name)); + else if (field.repeated) gen + ("this%s=[]", util.safeProp(field.name)); + return gen + ("if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors + * @property {Object.} fields Field descriptors + * @property {number[][]} [extensions] Extension ranges + * @property {Array.} [reserved] Reserved ranges + * @property {boolean} [group=false] Whether a legacy group or not + */ + +/** + * Creates a message type from a message type descriptor. + * @param {string} name Message name + * @param {IType} json Message type descriptor + * @returns {Type} Created message type + */ +Type.fromJSON = function fromJSON(name, json) { + var type = new Type(name, json.options); + type.extensions = json.extensions; + type.reserved = json.reserved; + var names = Object.keys(json.fields), + i = 0; + for (; i < names.length; ++i) + type.add( + ( typeof json.fields[names[i]].keyType !== "undefined" + ? MapField.fromJSON + : Field.fromJSON )(names[i], json.fields[names[i]]) + ); + if (json.oneofs) + for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i) + type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]])); + if (json.nested) + for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) { + var nested = json.nested[names[i]]; + type.add( // most to least likely + ( nested.id !== undefined + ? Field.fromJSON + : nested.fields !== undefined + ? Type.fromJSON + : nested.values !== undefined + ? Enum.fromJSON + : nested.methods !== undefined + ? Service.fromJSON + : Namespace.fromJSON )(names[i], nested) + ); + } + if (json.extensions && json.extensions.length) + type.extensions = json.extensions; + if (json.reserved && json.reserved.length) + type.reserved = json.reserved; + if (json.group) + type.group = true; + if (json.comment) + type.comment = json.comment; + if (json.edition) + type._edition = json.edition; + type._defaultEdition = "proto3"; // For backwards-compatibility. + return type; +}; + +/** + * Converts this message type to a message type descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IType} Message type descriptor + */ +Type.prototype.toJSON = function toJSON(toJSONOptions) { + var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "edition" , this._editionToJSON(), + "options" , inherited && inherited.options || undefined, + "oneofs" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions), + "fields" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {}, + "extensions" , this.extensions && this.extensions.length ? this.extensions : undefined, + "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined, + "group" , this.group || undefined, + "nested" , inherited && inherited.nested || undefined, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * @override + */ +Type.prototype.resolveAll = function resolveAll() { + if (!this._needsRecursiveResolve) return this; + + Namespace.prototype.resolveAll.call(this); + var oneofs = this.oneofsArray; i = 0; + while (i < oneofs.length) + oneofs[i++].resolve(); + var fields = this.fieldsArray, i = 0; + while (i < fields.length) + fields[i++].resolve(); + return this; +}; + +/** + * @override + */ +Type.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { + if (!this._needsRecursiveFeatureResolution) return this; + + edition = this._edition || edition; + + Namespace.prototype._resolveFeaturesRecursive.call(this, edition); + this.oneofsArray.forEach(oneof => { + oneof._resolveFeatures(edition); + }); + this.fieldsArray.forEach(field => { + field._resolveFeatures(edition); + }); + return this; +}; + +/** + * @override + */ +Type.prototype.get = function get(name) { + return this.fields[name] + || this.oneofs && this.oneofs[name] + || this.nested && this.nested[name] + || null; +}; + +/** + * Adds a nested object to this type. + * @param {ReflectionObject} object Nested object to add + * @returns {Type} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id + */ +Type.prototype.add = function add(object) { + + if (this.get(object.name)) + throw Error("duplicate name '" + object.name + "' in " + this); + + if (object instanceof Field && object.extend === undefined) { + // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects. + // The root object takes care of adding distinct sister-fields to the respective extended + // type instead. + + // avoids calling the getter if not absolutely necessary because it's called quite frequently + if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id]) + throw Error("duplicate id " + object.id + " in " + this); + if (this.isReservedId(object.id)) + throw Error("id " + object.id + " is reserved in " + this); + if (this.isReservedName(object.name)) + throw Error("name '" + object.name + "' is reserved in " + this); + + if (object.parent) + object.parent.remove(object); + this.fields[object.name] = object; + object.message = this; + object.onAdd(this); + return clearCache(this); + } + if (object instanceof OneOf) { + if (!this.oneofs) + this.oneofs = {}; + this.oneofs[object.name] = object; + object.onAdd(this); + return clearCache(this); + } + return Namespace.prototype.add.call(this, object); +}; + +/** + * Removes a nested object from this type. + * @param {ReflectionObject} object Nested object to remove + * @returns {Type} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `object` is not a member of this type + */ +Type.prototype.remove = function remove(object) { + if (object instanceof Field && object.extend === undefined) { + // See Type#add for the reason why extension fields are excluded here. + + /* istanbul ignore if */ + if (!this.fields || this.fields[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.fields[object.name]; + object.parent = null; + object.onRemove(this); + return clearCache(this); + } + if (object instanceof OneOf) { + + /* istanbul ignore if */ + if (!this.oneofs || this.oneofs[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.oneofs[object.name]; + object.parent = null; + object.onRemove(this); + return clearCache(this); + } + return Namespace.prototype.remove.call(this, object); +}; + +/** + * Tests if the specified id is reserved. + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Type.prototype.isReservedId = function isReservedId(id) { + return Namespace.isReservedId(this.reserved, id); +}; + +/** + * Tests if the specified name is reserved. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Type.prototype.isReservedName = function isReservedName(name) { + return Namespace.isReservedName(this.reserved, name); +}; + +/** + * Creates a new message of this type using the specified properties. + * @param {Object.} [properties] Properties to set + * @returns {Message<{}>} Message instance + */ +Type.prototype.create = function create(properties) { + return new this.ctor(properties); +}; + +/** + * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}. + * @returns {Type} `this` + */ +Type.prototype.setup = function setup() { + // Sets up everything at once so that the prototype chain does not have to be re-evaluated + // multiple times (V8, soft-deopt prototype-check). + + var fullName = this.fullName, + types = []; + for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i) + types.push(this._fieldsArray[i].resolve().resolvedType); + + // Replace setup methods with type-specific generated functions + this.encode = encoder(this)({ + Writer : Writer, + types : types, + util : util + }); + this.decode = decoder(this)({ + Reader : Reader, + types : types, + util : util + }); + this.verify = verifier(this)({ + types : types, + util : util + }); + this.fromObject = converter.fromObject(this)({ + types : types, + util : util + }); + this.toObject = converter.toObject(this)({ + types : types, + util : util + }); + + // Inject custom wrappers for common types + var wrapper = wrappers[fullName]; + if (wrapper) { + var originalThis = Object.create(this); + // if (wrapper.fromObject) { + originalThis.fromObject = this.fromObject; + this.fromObject = wrapper.fromObject.bind(originalThis); + // } + // if (wrapper.toObject) { + originalThis.toObject = this.toObject; + this.toObject = wrapper.toObject.bind(originalThis); + // } + } + + return this; +}; + +/** + * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages. + * @param {Message<{}>|Object.} message Message instance or plain object + * @param {Writer} [writer] Writer to encode to + * @returns {Writer} writer + */ +Type.prototype.encode = function encode_setup(message, writer) { + return this.setup().encode(message, writer); // overrides this method +}; + +/** + * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages. + * @param {Message<{}>|Object.} message Message instance or plain object + * @param {Writer} [writer] Writer to encode to + * @returns {Writer} writer + */ +Type.prototype.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim(); +}; + +/** + * Decodes a message of this type. + * @param {Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Length of the message, if known beforehand + * @returns {Message<{}>} Decoded message + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {util.ProtocolError<{}>} If required fields are missing + */ +Type.prototype.decode = function decode_setup(reader, length) { + return this.setup().decode(reader, length); // overrides this method +}; + +/** + * Decodes a message of this type preceeded by its byte length as a varint. + * @param {Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {Message<{}>} Decoded message + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {util.ProtocolError} If required fields are missing + */ +Type.prototype.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof Reader)) + reader = Reader.create(reader); + return this.decode(reader, reader.uint32()); +}; + +/** + * Verifies that field values are valid and that required fields are present. + * @param {Object.} message Plain object to verify + * @returns {null|string} `null` if valid, otherwise the reason why it is not + */ +Type.prototype.verify = function verify_setup(message) { + return this.setup().verify(message); // overrides this method +}; + +/** + * Creates a new message of this type from a plain object. Also converts values to their respective internal types. + * @param {Object.} object Plain object to convert + * @returns {Message<{}>} Message instance + */ +Type.prototype.fromObject = function fromObject(object) { + return this.setup().fromObject(object); +}; + +/** + * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}. + * @interface IConversionOptions + * @property {Function} [longs] Long conversion type. + * Valid values are `String` and `Number` (the global types). + * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library. + * @property {Function} [enums] Enum value conversion type. + * Only valid value is `String` (the global type). + * Defaults to copy the present value, which is the numeric id. + * @property {Function} [bytes] Bytes value conversion type. + * Valid values are `Array` and (a base64 encoded) `String` (the global types). + * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser. + * @property {boolean} [defaults=false] Also sets default values on the resulting object + * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false` + * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false` + * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any + * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings + */ + +/** + * Creates a plain object from a message of this type. Also converts values to other types if specified. + * @param {Message<{}>} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ +Type.prototype.toObject = function toObject(message, options) { + return this.setup().toObject(message, options); +}; + +/** + * Decorator function as returned by {@link Type.d} (TypeScript). + * @typedef TypeDecorator + * @type {function} + * @param {Constructor} target Target constructor + * @returns {undefined} + * @template T extends Message + */ + +/** + * Type decorator (TypeScript). + * @param {string} [typeName] Type name, defaults to the constructor's name + * @returns {TypeDecorator} Decorator function + * @template T extends Message + */ +Type.d = function decorateType(typeName) { + return function typeDecorator(target) { + util.decorateType(target, typeName); + }; +}; + +},{"12":12,"13":13,"14":14,"15":15,"16":16,"20":20,"21":21,"23":23,"25":25,"27":27,"33":33,"37":37,"40":40,"41":41,"42":42}],36:[function(require,module,exports){ +"use strict"; + +/** + * Common type constants. + * @namespace + */ +var types = exports; + +var util = require(37); + +var s = [ + "double", // 0 + "float", // 1 + "int32", // 2 + "uint32", // 3 + "sint32", // 4 + "fixed32", // 5 + "sfixed32", // 6 + "int64", // 7 + "uint64", // 8 + "sint64", // 9 + "fixed64", // 10 + "sfixed64", // 11 + "bool", // 12 + "string", // 13 + "bytes" // 14 +]; + +function bake(values, offset) { + var i = 0, o = {}; + offset |= 0; + while (i < values.length) o[s[i + offset]] = values[i++]; + return o; +} + +/** + * Basic type wire types. + * @type {Object.} + * @const + * @property {number} double=1 Fixed64 wire type + * @property {number} float=5 Fixed32 wire type + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + * @property {number} string=2 Ldelim wire type + * @property {number} bytes=2 Ldelim wire type + */ +types.basic = bake([ + /* double */ 1, + /* float */ 5, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0, + /* string */ 2, + /* bytes */ 2 +]); + +/** + * Basic type defaults. + * @type {Object.} + * @const + * @property {number} double=0 Double default + * @property {number} float=0 Float default + * @property {number} int32=0 Int32 default + * @property {number} uint32=0 Uint32 default + * @property {number} sint32=0 Sint32 default + * @property {number} fixed32=0 Fixed32 default + * @property {number} sfixed32=0 Sfixed32 default + * @property {number} int64=0 Int64 default + * @property {number} uint64=0 Uint64 default + * @property {number} sint64=0 Sint32 default + * @property {number} fixed64=0 Fixed64 default + * @property {number} sfixed64=0 Sfixed64 default + * @property {boolean} bool=false Bool default + * @property {string} string="" String default + * @property {Array.} bytes=Array(0) Bytes default + * @property {null} message=null Message default + */ +types.defaults = bake([ + /* double */ 0, + /* float */ 0, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 0, + /* sfixed32 */ 0, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 0, + /* sfixed64 */ 0, + /* bool */ false, + /* string */ "", + /* bytes */ util.emptyArray, + /* message */ null +]); + +/** + * Basic long type wire types. + * @type {Object.} + * @const + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + */ +types.long = bake([ + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1 +], 7); + +/** + * Allowed types for map keys with their associated wire type. + * @type {Object.} + * @const + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + * @property {number} string=2 Ldelim wire type + */ +types.mapKey = bake([ + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0, + /* string */ 2 +], 2); + +/** + * Allowed types for packed repeated fields with their associated wire type. + * @type {Object.} + * @const + * @property {number} double=1 Fixed64 wire type + * @property {number} float=5 Fixed32 wire type + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + */ +types.packed = bake([ + /* double */ 1, + /* float */ 5, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0 +]); + +},{"37":37}],37:[function(require,module,exports){ +"use strict"; + +/** + * Various utility functions. + * @namespace + */ +var util = module.exports = require(39); + +var roots = require(30); + +var Type, // cyclic + Enum; + +util.codegen = require(3); +util.fetch = require(5); +util.path = require(8); + +/** + * Node's fs module if available. + * @type {Object.} + */ +util.fs = util.inquire("fs"); + +/** + * Converts an object's values to an array. + * @param {Object.} object Object to convert + * @returns {Array.<*>} Converted array + */ +util.toArray = function toArray(object) { + if (object) { + var keys = Object.keys(object), + array = new Array(keys.length), + index = 0; + while (index < keys.length) + array[index] = object[keys[index++]]; + return array; + } + return []; +}; + +/** + * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values. + * @param {Array.<*>} array Array to convert + * @returns {Object.} Converted object + */ +util.toObject = function toObject(array) { + var object = {}, + index = 0; + while (index < array.length) { + var key = array[index++], + val = array[index++]; + if (val !== undefined) + object[key] = val; + } + return object; +}; + +var safePropBackslashRe = /\\/g, + safePropQuoteRe = /"/g; + +/** + * Tests whether the specified name is a reserved word in JS. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +util.isReserved = function isReserved(name) { + return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name); +}; + +/** + * Returns a safe property accessor for the specified property name. + * @param {string} prop Property name + * @returns {string} Safe accessor + */ +util.safeProp = function safeProp(prop) { + if (!/^[$\w_]+$/.test(prop) || util.isReserved(prop)) + return "[\"" + prop.replace(safePropBackslashRe, "\\\\").replace(safePropQuoteRe, "\\\"") + "\"]"; + return "." + prop; +}; + +/** + * Converts the first character of a string to upper case. + * @param {string} str String to convert + * @returns {string} Converted string + */ +util.ucFirst = function ucFirst(str) { + return str.charAt(0).toUpperCase() + str.substring(1); +}; + +var camelCaseRe = /_([a-z])/g; + +/** + * Converts a string to camel case. + * @param {string} str String to convert + * @returns {string} Converted string + */ +util.camelCase = function camelCase(str) { + return str.substring(0, 1) + + str.substring(1) + .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); }); +}; + +/** + * Compares reflected fields by id. + * @param {Field} a First field + * @param {Field} b Second field + * @returns {number} Comparison value + */ +util.compareFieldsById = function compareFieldsById(a, b) { + return a.id - b.id; +}; + +/** + * Decorator helper for types (TypeScript). + * @param {Constructor} ctor Constructor function + * @param {string} [typeName] Type name, defaults to the constructor's name + * @returns {Type} Reflected type + * @template T extends Message + * @property {Root} root Decorators root + */ +util.decorateType = function decorateType(ctor, typeName) { + + /* istanbul ignore if */ + if (ctor.$type) { + if (typeName && ctor.$type.name !== typeName) { + util.decorateRoot.remove(ctor.$type); + ctor.$type.name = typeName; + util.decorateRoot.add(ctor.$type); + } + return ctor.$type; + } + + /* istanbul ignore next */ + if (!Type) + Type = require(35); + + var type = new Type(typeName || ctor.name); + util.decorateRoot.add(type); + type.ctor = ctor; // sets up .encode, .decode etc. + Object.defineProperty(ctor, "$type", { value: type, enumerable: false }); + Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false }); + return type; +}; + +var decorateEnumIndex = 0; + +/** + * Decorator helper for enums (TypeScript). + * @param {Object} object Enum object + * @returns {Enum} Reflected enum + */ +util.decorateEnum = function decorateEnum(object) { + + /* istanbul ignore if */ + if (object.$type) + return object.$type; + + /* istanbul ignore next */ + if (!Enum) + Enum = require(15); + + var enm = new Enum("Enum" + decorateEnumIndex++, object); + util.decorateRoot.add(enm); + Object.defineProperty(object, "$type", { value: enm, enumerable: false }); + return enm; +}; + + +/** + * Sets the value of a property by property path. If a value already exists, it is turned to an array + * @param {Object.} dst Destination object + * @param {string} path dot '.' delimited path of the property to set + * @param {Object} value the value to set + * @param {boolean|undefined} [ifNotSet] Sets the option only if it isn't currently set + * @returns {Object.} Destination object + */ +util.setProperty = function setProperty(dst, path, value, ifNotSet) { + function setProp(dst, path, value) { + var part = path.shift(); + if (part === "__proto__" || part === "prototype") { + return dst; + } + if (path.length > 0) { + dst[part] = setProp(dst[part] || {}, path, value); + } else { + var prevValue = dst[part]; + if (prevValue && ifNotSet) + return dst; + if (prevValue) + value = [].concat(prevValue).concat(value); + dst[part] = value; + } + return dst; + } + + if (typeof dst !== "object") + throw TypeError("dst must be an object"); + if (!path) + throw TypeError("path must be specified"); + + path = path.split("."); + return setProp(dst, path, value); +}; + +/** + * Decorator root (TypeScript). + * @name util.decorateRoot + * @type {Root} + * @readonly + */ +Object.defineProperty(util, "decorateRoot", { + get: function() { + return roots["decorated"] || (roots["decorated"] = new (require(29))()); + } +}); + +},{"15":15,"29":29,"3":3,"30":30,"35":35,"39":39,"5":5,"8":8}],38:[function(require,module,exports){ +"use strict"; +module.exports = LongBits; + +var util = require(39); + +/** + * Constructs new long bits. + * @classdesc Helper class for working with the low and high bits of a 64 bit value. + * @memberof util + * @constructor + * @param {number} lo Low 32 bits, unsigned + * @param {number} hi High 32 bits, unsigned + */ +function LongBits(lo, hi) { + + // note that the casts below are theoretically unnecessary as of today, but older statically + // generated converter code might still call the ctor with signed 32bits. kept for compat. + + /** + * Low bits. + * @type {number} + */ + this.lo = lo >>> 0; + + /** + * High bits. + * @type {number} + */ + this.hi = hi >>> 0; +} + +/** + * Zero bits. + * @memberof util.LongBits + * @type {util.LongBits} + */ +var zero = LongBits.zero = new LongBits(0, 0); + +zero.toNumber = function() { return 0; }; +zero.zzEncode = zero.zzDecode = function() { return this; }; +zero.length = function() { return 1; }; + +/** + * Zero hash. + * @memberof util.LongBits + * @type {string} + */ +var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; + +/** + * Constructs new long bits from the specified number. + * @param {number} value Value + * @returns {util.LongBits} Instance + */ +LongBits.fromNumber = function fromNumber(value) { + if (value === 0) + return zero; + var sign = value < 0; + if (sign) + value = -value; + var lo = value >>> 0, + hi = (value - lo) / 4294967296 >>> 0; + if (sign) { + hi = ~hi >>> 0; + lo = ~lo >>> 0; + if (++lo > 4294967295) { + lo = 0; + if (++hi > 4294967295) + hi = 0; + } + } + return new LongBits(lo, hi); +}; + +/** + * Constructs new long bits from a number, long or string. + * @param {Long|number|string} value Value + * @returns {util.LongBits} Instance + */ +LongBits.from = function from(value) { + if (typeof value === "number") + return LongBits.fromNumber(value); + if (util.isString(value)) { + /* istanbul ignore else */ + if (util.Long) + value = util.Long.fromString(value); + else + return LongBits.fromNumber(parseInt(value, 10)); + } + return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; +}; + +/** + * Converts this long bits to a possibly unsafe JavaScript number. + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {number} Possibly unsafe number + */ +LongBits.prototype.toNumber = function toNumber(unsigned) { + if (!unsigned && this.hi >>> 31) { + var lo = ~this.lo + 1 >>> 0, + hi = ~this.hi >>> 0; + if (!lo) + hi = hi + 1 >>> 0; + return -(lo + hi * 4294967296); + } + return this.lo + this.hi * 4294967296; +}; + +/** + * Converts this long bits to a long. + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {Long} Long + */ +LongBits.prototype.toLong = function toLong(unsigned) { + return util.Long + ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) + /* istanbul ignore next */ + : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; +}; + +var charCodeAt = String.prototype.charCodeAt; + +/** + * Constructs new long bits from the specified 8 characters long hash. + * @param {string} hash Hash + * @returns {util.LongBits} Bits + */ +LongBits.fromHash = function fromHash(hash) { + if (hash === zeroHash) + return zero; + return new LongBits( + ( charCodeAt.call(hash, 0) + | charCodeAt.call(hash, 1) << 8 + | charCodeAt.call(hash, 2) << 16 + | charCodeAt.call(hash, 3) << 24) >>> 0 + , + ( charCodeAt.call(hash, 4) + | charCodeAt.call(hash, 5) << 8 + | charCodeAt.call(hash, 6) << 16 + | charCodeAt.call(hash, 7) << 24) >>> 0 + ); +}; + +/** + * Converts this long bits to a 8 characters long hash. + * @returns {string} Hash + */ +LongBits.prototype.toHash = function toHash() { + return String.fromCharCode( + this.lo & 255, + this.lo >>> 8 & 255, + this.lo >>> 16 & 255, + this.lo >>> 24 , + this.hi & 255, + this.hi >>> 8 & 255, + this.hi >>> 16 & 255, + this.hi >>> 24 + ); +}; + +/** + * Zig-zag encodes this long bits. + * @returns {util.LongBits} `this` + */ +LongBits.prototype.zzEncode = function zzEncode() { + var mask = this.hi >> 31; + this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; + this.lo = ( this.lo << 1 ^ mask) >>> 0; + return this; +}; + +/** + * Zig-zag decodes this long bits. + * @returns {util.LongBits} `this` + */ +LongBits.prototype.zzDecode = function zzDecode() { + var mask = -(this.lo & 1); + this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; + this.hi = ( this.hi >>> 1 ^ mask) >>> 0; + return this; +}; + +/** + * Calculates the length of this longbits when encoded as a varint. + * @returns {number} Length + */ +LongBits.prototype.length = function length() { + var part0 = this.lo, + part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, + part2 = this.hi >>> 24; + return part2 === 0 + ? part1 === 0 + ? part0 < 16384 + ? part0 < 128 ? 1 : 2 + : part0 < 2097152 ? 3 : 4 + : part1 < 16384 + ? part1 < 128 ? 5 : 6 + : part1 < 2097152 ? 7 : 8 + : part2 < 128 ? 9 : 10; +}; + +},{"39":39}],39:[function(require,module,exports){ +"use strict"; +var util = exports; + +// used to return a Promise where callback is omitted +util.asPromise = require(1); + +// converts to / from base64 encoded strings +util.base64 = require(2); + +// base class of rpc.Service +util.EventEmitter = require(4); + +// float handling accross browsers +util.float = require(6); + +// requires modules optionally and hides the call from bundlers +util.inquire = require(7); + +// converts to / from utf8 encoded strings +util.utf8 = require(10); + +// provides a node-like buffer pool in the browser +util.pool = require(9); + +// utility to work with the low and high bits of a 64 bit value +util.LongBits = require(38); + +/** + * Whether running within node or not. + * @memberof util + * @type {boolean} + */ +util.isNode = Boolean(typeof global !== "undefined" + && global + && global.process + && global.process.versions + && global.process.versions.node); + +/** + * Global object reference. + * @memberof util + * @type {Object} + */ +util.global = util.isNode && global + || typeof window !== "undefined" && window + || typeof self !== "undefined" && self + || this; // eslint-disable-line no-invalid-this + +/** + * An immuable empty array. + * @memberof util + * @type {Array.<*>} + * @const + */ +util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes + +/** + * An immutable empty object. + * @type {Object} + * @const + */ +util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes + +/** + * Tests if the specified value is an integer. + * @function + * @param {*} value Value to test + * @returns {boolean} `true` if the value is an integer + */ +util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) { + return typeof value === "number" && isFinite(value) && Math.floor(value) === value; +}; + +/** + * Tests if the specified value is a string. + * @param {*} value Value to test + * @returns {boolean} `true` if the value is a string + */ +util.isString = function isString(value) { + return typeof value === "string" || value instanceof String; +}; + +/** + * Tests if the specified value is a non-null object. + * @param {*} value Value to test + * @returns {boolean} `true` if the value is a non-null object + */ +util.isObject = function isObject(value) { + return value && typeof value === "object"; +}; + +/** + * Checks if a property on a message is considered to be present. + * This is an alias of {@link util.isSet}. + * @function + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ +util.isset = + +/** + * Checks if a property on a message is considered to be present. + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ +util.isSet = function isSet(obj, prop) { + var value = obj[prop]; + if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins + return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; + return false; +}; + +/** + * Any compatible Buffer instance. + * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings. + * @interface Buffer + * @extends Uint8Array + */ + +/** + * Node's Buffer class if available. + * @type {Constructor} + */ +util.Buffer = (function() { + try { + var Buffer = util.inquire("buffer").Buffer; + // refuse to use non-node buffers if not explicitly assigned (perf reasons): + return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null; + } catch (e) { + /* istanbul ignore next */ + return null; + } +})(); + +// Internal alias of or polyfull for Buffer.from. +util._Buffer_from = null; + +// Internal alias of or polyfill for Buffer.allocUnsafe. +util._Buffer_allocUnsafe = null; + +/** + * Creates a new buffer of whatever type supported by the environment. + * @param {number|number[]} [sizeOrArray=0] Buffer size or number array + * @returns {Uint8Array|Buffer} Buffer + */ +util.newBuffer = function newBuffer(sizeOrArray) { + /* istanbul ignore next */ + return typeof sizeOrArray === "number" + ? util.Buffer + ? util._Buffer_allocUnsafe(sizeOrArray) + : new util.Array(sizeOrArray) + : util.Buffer + ? util._Buffer_from(sizeOrArray) + : typeof Uint8Array === "undefined" + ? sizeOrArray + : new Uint8Array(sizeOrArray); +}; + +/** + * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`. + * @type {Constructor} + */ +util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array; + +/** + * Any compatible Long instance. + * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js. + * @interface Long + * @property {number} low Low bits + * @property {number} high High bits + * @property {boolean} unsigned Whether unsigned or not + */ + +/** + * Long.js's Long class if available. + * @type {Constructor} + */ +util.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long + || /* istanbul ignore next */ util.global.Long + || util.inquire("long"); + +/** + * Regular expression used to verify 2 bit (`bool`) map keys. + * @type {RegExp} + * @const + */ +util.key2Re = /^true|false|0|1$/; + +/** + * Regular expression used to verify 32 bit (`int32` etc.) map keys. + * @type {RegExp} + * @const + */ +util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; + +/** + * Regular expression used to verify 64 bit (`int64` etc.) map keys. + * @type {RegExp} + * @const + */ +util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; + +/** + * Converts a number or long to an 8 characters long hash string. + * @param {Long|number} value Value to convert + * @returns {string} Hash + */ +util.longToHash = function longToHash(value) { + return value + ? util.LongBits.from(value).toHash() + : util.LongBits.zeroHash; +}; + +/** + * Converts an 8 characters long hash string to a long or number. + * @param {string} hash Hash + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {Long|number} Original value + */ +util.longFromHash = function longFromHash(hash, unsigned) { + var bits = util.LongBits.fromHash(hash); + if (util.Long) + return util.Long.fromBits(bits.lo, bits.hi, unsigned); + return bits.toNumber(Boolean(unsigned)); +}; + +/** + * Merges the properties of the source object into the destination object. + * @memberof util + * @param {Object.} dst Destination object + * @param {Object.} src Source object + * @param {boolean} [ifNotSet=false] Merges only if the key is not already set + * @returns {Object.} Destination object + */ +function merge(dst, src, ifNotSet) { // used by converters + for (var keys = Object.keys(src), i = 0; i < keys.length; ++i) + if (dst[keys[i]] === undefined || !ifNotSet) + dst[keys[i]] = src[keys[i]]; + return dst; +} + +util.merge = merge; + +/** + * Converts the first character of a string to lower case. + * @param {string} str String to convert + * @returns {string} Converted string + */ +util.lcFirst = function lcFirst(str) { + return str.charAt(0).toLowerCase() + str.substring(1); +}; + +/** + * Creates a custom error constructor. + * @memberof util + * @param {string} name Error name + * @returns {Constructor} Custom error constructor + */ +function newError(name) { + + function CustomError(message, properties) { + + if (!(this instanceof CustomError)) + return new CustomError(message, properties); + + // Error.call(this, message); + // ^ just returns a new error instance because the ctor can be called as a function + + Object.defineProperty(this, "message", { get: function() { return message; } }); + + /* istanbul ignore next */ + if (Error.captureStackTrace) // node + Error.captureStackTrace(this, CustomError); + else + Object.defineProperty(this, "stack", { value: new Error().stack || "" }); + + if (properties) + merge(this, properties); + } + + CustomError.prototype = Object.create(Error.prototype, { + constructor: { + value: CustomError, + writable: true, + enumerable: false, + configurable: true, + }, + name: { + get: function get() { return name; }, + set: undefined, + enumerable: false, + // configurable: false would accurately preserve the behavior of + // the original, but I'm guessing that was not intentional. + // For an actual error subclass, this property would + // be configurable. + configurable: true, + }, + toString: { + value: function value() { return this.name + ": " + this.message; }, + writable: true, + enumerable: false, + configurable: true, + }, + }); + + return CustomError; +} + +util.newError = newError; + +/** + * Constructs a new protocol error. + * @classdesc Error subclass indicating a protocol specifc error. + * @memberof util + * @extends Error + * @template T extends Message + * @constructor + * @param {string} message Error message + * @param {Object.} [properties] Additional properties + * @example + * try { + * MyMessage.decode(someBuffer); // throws if required fields are missing + * } catch (e) { + * if (e instanceof ProtocolError && e.instance) + * console.log("decoded so far: " + JSON.stringify(e.instance)); + * } + */ +util.ProtocolError = newError("ProtocolError"); + +/** + * So far decoded message instance. + * @name util.ProtocolError#instance + * @type {Message} + */ + +/** + * A OneOf getter as returned by {@link util.oneOfGetter}. + * @typedef OneOfGetter + * @type {function} + * @returns {string|undefined} Set field name, if any + */ + +/** + * Builds a getter for a oneof's present field name. + * @param {string[]} fieldNames Field names + * @returns {OneOfGetter} Unbound getter + */ +util.oneOfGetter = function getOneOf(fieldNames) { + var fieldMap = {}; + for (var i = 0; i < fieldNames.length; ++i) + fieldMap[fieldNames[i]] = 1; + + /** + * @returns {string|undefined} Set field name, if any + * @this Object + * @ignore + */ + return function() { // eslint-disable-line consistent-return + for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i) + if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null) + return keys[i]; + }; +}; + +/** + * A OneOf setter as returned by {@link util.oneOfSetter}. + * @typedef OneOfSetter + * @type {function} + * @param {string|undefined} value Field name + * @returns {undefined} + */ + +/** + * Builds a setter for a oneof's present field name. + * @param {string[]} fieldNames Field names + * @returns {OneOfSetter} Unbound setter + */ +util.oneOfSetter = function setOneOf(fieldNames) { + + /** + * @param {string} name Field name + * @returns {undefined} + * @this Object + * @ignore + */ + return function(name) { + for (var i = 0; i < fieldNames.length; ++i) + if (fieldNames[i] !== name) + delete this[fieldNames[i]]; + }; +}; + +/** + * Default conversion options used for {@link Message#toJSON} implementations. + * + * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely: + * + * - Longs become strings + * - Enums become string keys + * - Bytes become base64 encoded strings + * - (Sub-)Messages become plain objects + * - Maps become plain objects with all string keys + * - Repeated fields become arrays + * - NaN and Infinity for float and double fields become strings + * + * @type {IConversionOptions} + * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json + */ +util.toJSONOptions = { + longs: String, + enums: String, + bytes: String, + json: true +}; + +// Sets up buffer utility according to the environment (called in index-minimal) +util._configure = function() { + var Buffer = util.Buffer; + /* istanbul ignore if */ + if (!Buffer) { + util._Buffer_from = util._Buffer_allocUnsafe = null; + return; + } + // because node 4.x buffers are incompatible & immutable + // see: https://github.com/dcodeIO/protobuf.js/pull/665 + util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from || + /* istanbul ignore next */ + function Buffer_from(value, encoding) { + return new Buffer(value, encoding); + }; + util._Buffer_allocUnsafe = Buffer.allocUnsafe || + /* istanbul ignore next */ + function Buffer_allocUnsafe(size) { + return new Buffer(size); + }; +}; + +},{"1":1,"10":10,"2":2,"38":38,"4":4,"6":6,"7":7,"9":9}],40:[function(require,module,exports){ +"use strict"; +module.exports = verifier; + +var Enum = require(15), + util = require(37); + +function invalid(field, expected) { + return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:"+field.keyType+"}" : "") + " expected"; +} + +/** + * Generates a partial value verifier. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {number} fieldIndex Field index + * @param {string} ref Variable reference + * @returns {Codegen} Codegen instance + * @ignore + */ +function genVerifyValue(gen, field, fieldIndex, ref) { + /* eslint-disable no-unexpected-multiline */ + if (field.resolvedType) { + if (field.resolvedType instanceof Enum) { gen + ("switch(%s){", ref) + ("default:") + ("return%j", invalid(field, "enum value")); + for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen + ("case %i:", field.resolvedType.values[keys[j]]); + gen + ("break") + ("}"); + } else { + gen + ("{") + ("var e=types[%i].verify(%s);", fieldIndex, ref) + ("if(e)") + ("return%j+e", field.name + ".") + ("}"); + } + } else { + switch (field.type) { + case "int32": + case "uint32": + case "sint32": + case "fixed32": + case "sfixed32": gen + ("if(!util.isInteger(%s))", ref) + ("return%j", invalid(field, "integer")); + break; + case "int64": + case "uint64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))", ref, ref, ref, ref) + ("return%j", invalid(field, "integer|Long")); + break; + case "float": + case "double": gen + ("if(typeof %s!==\"number\")", ref) + ("return%j", invalid(field, "number")); + break; + case "bool": gen + ("if(typeof %s!==\"boolean\")", ref) + ("return%j", invalid(field, "boolean")); + break; + case "string": gen + ("if(!util.isString(%s))", ref) + ("return%j", invalid(field, "string")); + break; + case "bytes": gen + ("if(!(%s&&typeof %s.length===\"number\"||util.isString(%s)))", ref, ref, ref) + ("return%j", invalid(field, "buffer")); + break; + } + } + return gen; + /* eslint-enable no-unexpected-multiline */ +} + +/** + * Generates a partial key verifier. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {string} ref Variable reference + * @returns {Codegen} Codegen instance + * @ignore + */ +function genVerifyKey(gen, field, ref) { + /* eslint-disable no-unexpected-multiline */ + switch (field.keyType) { + case "int32": + case "uint32": + case "sint32": + case "fixed32": + case "sfixed32": gen + ("if(!util.key32Re.test(%s))", ref) + ("return%j", invalid(field, "integer key")); + break; + case "int64": + case "uint64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(!util.key64Re.test(%s))", ref) // see comment above: x is ok, d is not + ("return%j", invalid(field, "integer|Long key")); + break; + case "bool": gen + ("if(!util.key2Re.test(%s))", ref) + ("return%j", invalid(field, "boolean key")); + break; + } + return gen; + /* eslint-enable no-unexpected-multiline */ +} + +/** + * Generates a verifier specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +function verifier(mtype) { + /* eslint-disable no-unexpected-multiline */ + + var gen = util.codegen(["m"], mtype.name + "$verify") + ("if(typeof m!==\"object\"||m===null)") + ("return%j", "object expected"); + var oneofs = mtype.oneofsArray, + seenFirstField = {}; + if (oneofs.length) gen + ("var p={}"); + + for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) { + var field = mtype._fieldsArray[i].resolve(), + ref = "m" + util.safeProp(field.name); + + if (field.optional) gen + ("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name); // !== undefined && !== null + + // map fields + if (field.map) { gen + ("if(!util.isObject(%s))", ref) + ("return%j", invalid(field, "object")) + ("var k=Object.keys(%s)", ref) + ("for(var i=0;i} + * @const + */ +var wrappers = exports; + +var Message = require(21); + +/** + * From object converter part of an {@link IWrapper}. + * @typedef WrapperFromObjectConverter + * @type {function} + * @param {Object.} object Plain object + * @returns {Message<{}>} Message instance + * @this Type + */ + +/** + * To object converter part of an {@link IWrapper}. + * @typedef WrapperToObjectConverter + * @type {function} + * @param {Message<{}>} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + * @this Type + */ + +/** + * Common type wrapper part of {@link wrappers}. + * @interface IWrapper + * @property {WrapperFromObjectConverter} [fromObject] From object converter + * @property {WrapperToObjectConverter} [toObject] To object converter + */ + +// Custom wrapper for Any +wrappers[".google.protobuf.Any"] = { + + fromObject: function(object) { + + // unwrap value type if mapped + if (object && object["@type"]) { + // Only use fully qualified type name after the last '/' + var name = object["@type"].substring(object["@type"].lastIndexOf("/") + 1); + var type = this.lookup(name); + /* istanbul ignore else */ + if (type) { + // type_url does not accept leading "." + var type_url = object["@type"].charAt(0) === "." ? + object["@type"].slice(1) : object["@type"]; + // type_url prefix is optional, but path seperator is required + if (type_url.indexOf("/") === -1) { + type_url = "/" + type_url; + } + return this.create({ + type_url: type_url, + value: type.encode(type.fromObject(object)).finish() + }); + } + } + + return this.fromObject(object); + }, + + toObject: function(message, options) { + + // Default prefix + var googleApi = "type.googleapis.com/"; + var prefix = ""; + var name = ""; + + // decode value if requested and unmapped + if (options && options.json && message.type_url && message.value) { + // Only use fully qualified type name after the last '/' + name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1); + // Separate the prefix used + prefix = message.type_url.substring(0, message.type_url.lastIndexOf("/") + 1); + var type = this.lookup(name); + /* istanbul ignore else */ + if (type) + message = type.decode(message.value); + } + + // wrap value if unmapped + if (!(message instanceof this.ctor) && message instanceof Message) { + var object = message.$type.toObject(message, options); + var messageName = message.$type.fullName[0] === "." ? + message.$type.fullName.slice(1) : message.$type.fullName; + // Default to type.googleapis.com prefix if no prefix is used + if (prefix === "") { + prefix = googleApi; + } + name = prefix + messageName; + object["@type"] = name; + return object; + } + + return this.toObject(message, options); + } +}; + +},{"21":21}],42:[function(require,module,exports){ +"use strict"; +module.exports = Writer; + +var util = require(39); + +var BufferWriter; // cyclic + +var LongBits = util.LongBits, + base64 = util.base64, + utf8 = util.utf8; + +/** + * Constructs a new writer operation instance. + * @classdesc Scheduled writer operation. + * @constructor + * @param {function(*, Uint8Array, number)} fn Function to call + * @param {number} len Value byte length + * @param {*} val Value to write + * @ignore + */ +function Op(fn, len, val) { + + /** + * Function to call. + * @type {function(Uint8Array, number, *)} + */ + this.fn = fn; + + /** + * Value byte length. + * @type {number} + */ + this.len = len; + + /** + * Next operation. + * @type {Writer.Op|undefined} + */ + this.next = undefined; + + /** + * Value to write. + * @type {*} + */ + this.val = val; // type varies +} + +/* istanbul ignore next */ +function noop() {} // eslint-disable-line no-empty-function + +/** + * Constructs a new writer state instance. + * @classdesc Copied writer state. + * @memberof Writer + * @constructor + * @param {Writer} writer Writer to copy state from + * @ignore + */ +function State(writer) { + + /** + * Current head. + * @type {Writer.Op} + */ + this.head = writer.head; + + /** + * Current tail. + * @type {Writer.Op} + */ + this.tail = writer.tail; + + /** + * Current buffer length. + * @type {number} + */ + this.len = writer.len; + + /** + * Next state. + * @type {State|null} + */ + this.next = writer.states; +} + +/** + * Constructs a new writer instance. + * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`. + * @constructor + */ +function Writer() { + + /** + * Current length. + * @type {number} + */ + this.len = 0; + + /** + * Operations head. + * @type {Object} + */ + this.head = new Op(noop, 0, 0); + + /** + * Operations tail + * @type {Object} + */ + this.tail = this.head; + + /** + * Linked forked states. + * @type {Object|null} + */ + this.states = null; + + // When a value is written, the writer calculates its byte length and puts it into a linked + // list of operations to perform when finish() is called. This both allows us to allocate + // buffers of the exact required size and reduces the amount of work we have to do compared + // to first calculating over objects and then encoding over objects. In our case, the encoding + // part is just a linked list walk calling operations with already prepared values. +} + +var create = function create() { + return util.Buffer + ? function create_buffer_setup() { + return (Writer.create = function create_buffer() { + return new BufferWriter(); + })(); + } + /* istanbul ignore next */ + : function create_array() { + return new Writer(); + }; +}; + +/** + * Creates a new writer. + * @function + * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer} + */ +Writer.create = create(); + +/** + * Allocates a buffer of the specified size. + * @param {number} size Buffer size + * @returns {Uint8Array} Buffer + */ +Writer.alloc = function alloc(size) { + return new util.Array(size); +}; + +// Use Uint8Array buffer pool in the browser, just like node does with buffers +/* istanbul ignore else */ +if (util.Array !== Array) + Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray); + +/** + * Pushes a new operation to the queue. + * @param {function(Uint8Array, number, *)} fn Function to call + * @param {number} len Value byte length + * @param {number} val Value to write + * @returns {Writer} `this` + * @private + */ +Writer.prototype._push = function push(fn, len, val) { + this.tail = this.tail.next = new Op(fn, len, val); + this.len += len; + return this; +}; + +function writeByte(val, buf, pos) { + buf[pos] = val & 255; +} + +function writeVarint32(val, buf, pos) { + while (val > 127) { + buf[pos++] = val & 127 | 128; + val >>>= 7; + } + buf[pos] = val; +} + +/** + * Constructs a new varint writer operation instance. + * @classdesc Scheduled varint writer operation. + * @extends Op + * @constructor + * @param {number} len Value byte length + * @param {number} val Value to write + * @ignore + */ +function VarintOp(len, val) { + this.len = len; + this.next = undefined; + this.val = val; +} + +VarintOp.prototype = Object.create(Op.prototype); +VarintOp.prototype.fn = writeVarint32; + +/** + * Writes an unsigned 32 bit value as a varint. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.uint32 = function write_uint32(value) { + // here, the call to this.push has been inlined and a varint specific Op subclass is used. + // uint32 is by far the most frequently used operation and benefits significantly from this. + this.len += (this.tail = this.tail.next = new VarintOp( + (value = value >>> 0) + < 128 ? 1 + : value < 16384 ? 2 + : value < 2097152 ? 3 + : value < 268435456 ? 4 + : 5, + value)).len; + return this; +}; + +/** + * Writes a signed 32 bit value as a varint. + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.int32 = function write_int32(value) { + return value < 0 + ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec + : this.uint32(value); +}; + +/** + * Writes a 32 bit value as a varint, zig-zag encoded. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.sint32 = function write_sint32(value) { + return this.uint32((value << 1 ^ value >> 31) >>> 0); +}; + +function writeVarint64(val, buf, pos) { + while (val.hi) { + buf[pos++] = val.lo & 127 | 128; + val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; + val.hi >>>= 7; + } + while (val.lo > 127) { + buf[pos++] = val.lo & 127 | 128; + val.lo = val.lo >>> 7; + } + buf[pos++] = val.lo; +} + +/** + * Writes an unsigned 64 bit value as a varint. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.uint64 = function write_uint64(value) { + var bits = LongBits.from(value); + return this._push(writeVarint64, bits.length(), bits); +}; + +/** + * Writes a signed 64 bit value as a varint. + * @function + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.int64 = Writer.prototype.uint64; + +/** + * Writes a signed 64 bit value as a varint, zig-zag encoded. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.sint64 = function write_sint64(value) { + var bits = LongBits.from(value).zzEncode(); + return this._push(writeVarint64, bits.length(), bits); +}; + +/** + * Writes a boolish value as a varint. + * @param {boolean} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.bool = function write_bool(value) { + return this._push(writeByte, 1, value ? 1 : 0); +}; + +function writeFixed32(val, buf, pos) { + buf[pos ] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; +} + +/** + * Writes an unsigned 32 bit value as fixed 32 bits. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.fixed32 = function write_fixed32(value) { + return this._push(writeFixed32, 4, value >>> 0); +}; + +/** + * Writes a signed 32 bit value as fixed 32 bits. + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.sfixed32 = Writer.prototype.fixed32; + +/** + * Writes an unsigned 64 bit value as fixed 64 bits. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.fixed64 = function write_fixed64(value) { + var bits = LongBits.from(value); + return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); +}; + +/** + * Writes a signed 64 bit value as fixed 64 bits. + * @function + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.sfixed64 = Writer.prototype.fixed64; + +/** + * Writes a float (32 bit). + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.float = function write_float(value) { + return this._push(util.float.writeFloatLE, 4, value); +}; + +/** + * Writes a double (64 bit float). + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.double = function write_double(value) { + return this._push(util.float.writeDoubleLE, 8, value); +}; + +var writeBytes = util.Array.prototype.set + ? function writeBytes_set(val, buf, pos) { + buf.set(val, pos); // also works for plain array values + } + /* istanbul ignore next */ + : function writeBytes_for(val, buf, pos) { + for (var i = 0; i < val.length; ++i) + buf[pos + i] = val[i]; + }; + +/** + * Writes a sequence of bytes. + * @param {Uint8Array|string} value Buffer or base64 encoded string to write + * @returns {Writer} `this` + */ +Writer.prototype.bytes = function write_bytes(value) { + var len = value.length >>> 0; + if (!len) + return this._push(writeByte, 1, 0); + if (util.isString(value)) { + var buf = Writer.alloc(len = base64.length(value)); + base64.decode(value, buf, 0); + value = buf; + } + return this.uint32(len)._push(writeBytes, len, value); +}; + +/** + * Writes a string. + * @param {string} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.string = function write_string(value) { + var len = utf8.length(value); + return len + ? this.uint32(len)._push(utf8.write, len, value) + : this._push(writeByte, 1, 0); +}; + +/** + * Forks this writer's state by pushing it to a stack. + * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state. + * @returns {Writer} `this` + */ +Writer.prototype.fork = function fork() { + this.states = new State(this); + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + return this; +}; + +/** + * Resets this instance to the last state. + * @returns {Writer} `this` + */ +Writer.prototype.reset = function reset() { + if (this.states) { + this.head = this.states.head; + this.tail = this.states.tail; + this.len = this.states.len; + this.states = this.states.next; + } else { + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + } + return this; +}; + +/** + * Resets to the last state and appends the fork state's current write length as a varint followed by its operations. + * @returns {Writer} `this` + */ +Writer.prototype.ldelim = function ldelim() { + var head = this.head, + tail = this.tail, + len = this.len; + this.reset().uint32(len); + if (len) { + this.tail.next = head.next; // skip noop + this.tail = tail; + this.len += len; + } + return this; +}; + +/** + * Finishes the write operation. + * @returns {Uint8Array} Finished buffer + */ +Writer.prototype.finish = function finish() { + var head = this.head.next, // skip noop + buf = this.constructor.alloc(this.len), + pos = 0; + while (head) { + head.fn(head.val, buf, pos); + pos += head.len; + head = head.next; + } + // this.head = this.tail = null; + return buf; +}; + +Writer._configure = function(BufferWriter_) { + BufferWriter = BufferWriter_; + Writer.create = create(); + BufferWriter._configure(); +}; + +},{"39":39}],43:[function(require,module,exports){ +"use strict"; +module.exports = BufferWriter; + +// extends Writer +var Writer = require(42); +(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; + +var util = require(39); + +/** + * Constructs a new buffer writer instance. + * @classdesc Wire format writer using node buffers. + * @extends Writer + * @constructor + */ +function BufferWriter() { + Writer.call(this); +} + +BufferWriter._configure = function () { + /** + * Allocates a buffer of the specified size. + * @function + * @param {number} size Buffer size + * @returns {Buffer} Buffer + */ + BufferWriter.alloc = util._Buffer_allocUnsafe; + + BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set" + ? function writeBytesBuffer_set(val, buf, pos) { + buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited) + // also works for plain array values + } + /* istanbul ignore next */ + : function writeBytesBuffer_copy(val, buf, pos) { + if (val.copy) // Buffer values + val.copy(buf, pos, 0, val.length); + else for (var i = 0; i < val.length;) // plain array values + buf[pos++] = val[i++]; + }; +}; + + +/** + * @override + */ +BufferWriter.prototype.bytes = function write_bytes_buffer(value) { + if (util.isString(value)) + value = util._Buffer_from(value, "base64"); + var len = value.length >>> 0; + this.uint32(len); + if (len) + this._push(BufferWriter.writeBytesBuffer, len, value); + return this; +}; + +function writeStringBuffer(val, buf, pos) { + if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions) + util.utf8.write(val, buf, pos); + else if (buf.utf8Write) + buf.utf8Write(val, pos); + else + buf.write(val, pos); +} + +/** + * @override + */ +BufferWriter.prototype.string = function write_string_buffer(value) { + var len = util.Buffer.byteLength(value); + this.uint32(len); + if (len) + this._push(writeStringBuffer, len, value); + return this; +}; + + +/** + * Finishes the write operation. + * @name BufferWriter#finish + * @function + * @returns {Buffer} Finished buffer + */ + +BufferWriter._configure(); + +},{"39":39,"42":42}]},{},[19]) + +})(); +//# sourceMappingURL=protobuf.js.map diff --git a/node_modules/protobufjs/dist/protobuf.js.map b/node_modules/protobufjs/dist/protobuf.js.map new file mode 100644 index 0000000..ce1ec16 --- /dev/null +++ b/node_modules/protobufjs/dist/protobuf.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["lib/prelude.js","../node_modules/@protobufjs/aspromise/index.js","../node_modules/@protobufjs/base64/index.js","../node_modules/@protobufjs/codegen/index.js","../node_modules/@protobufjs/eventemitter/index.js","../node_modules/@protobufjs/fetch/index.js","../node_modules/@protobufjs/float/index.js","../node_modules/@protobufjs/inquire/index.js","../node_modules/@protobufjs/path/index.js","../node_modules/@protobufjs/pool/index.js","../node_modules/@protobufjs/utf8/index.js","../src/common.js","../src/converter.js","../src/decoder.js","../src/encoder.js","../src/enum.js","../src/field.js","../src/index-light.js","../src/index-minimal.js","../src/index","../src/mapfield.js","../src/message.js","../src/method.js","../src/namespace.js","../src/object.js","../src/oneof.js","../src/parse.js","../src/reader.js","../src/reader_buffer.js","../src/root.js","../src/roots.js","../src/rpc.js","../src/rpc/service.js","../src/service.js","../src/tokenize.js","../src/type.js","../src/types.js","../src/util.js","../src/util/longbits.js","../src/util/minimal.js","../src/verifier.js","../src/wrappers.js","../src/writer.js","../src/writer_buffer.js"],"names":[],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/UA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/YA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7SA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrcA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACliBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1XA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACz8BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtmBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"protobuf.js","sourcesContent":["(function prelude(modules, cache, entries) {\n\n // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS\n // sources through a conflict-free require shim and is again wrapped within an iife that\n // provides a minification-friendly `undefined` var plus a global \"use strict\" directive\n // so that minification can remove the directives of each module.\n\n function $require(name) {\n var $module = cache[name];\n if (!$module)\n modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports);\n return $module.exports;\n }\n\n var protobuf = $require(entries[0]);\n\n // Expose globally\n protobuf.util.global.protobuf = protobuf;\n\n // Be nice to AMD\n if (typeof define === \"function\" && define.amd)\n define([\"long\"], function(Long) {\n if (Long && Long.isLong) {\n protobuf.util.Long = Long;\n protobuf.configure();\n }\n return protobuf;\n });\n\n // Be nice to CommonJS\n if (typeof module === \"object\" && module && module.exports)\n module.exports = protobuf;\n\n})/* end of prelude */","\"use strict\";\r\nmodule.exports = asPromise;\r\n\r\n/**\r\n * Callback as used by {@link util.asPromise}.\r\n * @typedef asPromiseCallback\r\n * @type {function}\r\n * @param {Error|null} error Error, if any\r\n * @param {...*} params Additional arguments\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Returns a promise from a node-style callback function.\r\n * @memberof util\r\n * @param {asPromiseCallback} fn Function to call\r\n * @param {*} ctx Function context\r\n * @param {...*} params Function arguments\r\n * @returns {Promise<*>} Promisified function\r\n */\r\nfunction asPromise(fn, ctx/*, varargs */) {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0,\r\n index = 2,\r\n pending = true;\r\n while (index < arguments.length)\r\n params[offset++] = arguments[index++];\r\n return new Promise(function executor(resolve, reject) {\r\n params[offset] = function callback(err/*, varargs */) {\r\n if (pending) {\r\n pending = false;\r\n if (err)\r\n reject(err);\r\n else {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0;\r\n while (offset < params.length)\r\n params[offset++] = arguments[offset];\r\n resolve.apply(null, params);\r\n }\r\n }\r\n };\r\n try {\r\n fn.apply(ctx || null, params);\r\n } catch (err) {\r\n if (pending) {\r\n pending = false;\r\n reject(err);\r\n }\r\n }\r\n });\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal base64 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar base64 = exports;\r\n\r\n/**\r\n * Calculates the byte length of a base64 encoded string.\r\n * @param {string} string Base64 encoded string\r\n * @returns {number} Byte length\r\n */\r\nbase64.length = function length(string) {\r\n var p = string.length;\r\n if (!p)\r\n return 0;\r\n var n = 0;\r\n while (--p % 4 > 1 && string.charAt(p) === \"=\")\r\n ++n;\r\n return Math.ceil(string.length * 3) / 4 - n;\r\n};\r\n\r\n// Base64 encoding table\r\nvar b64 = new Array(64);\r\n\r\n// Base64 decoding table\r\nvar s64 = new Array(123);\r\n\r\n// 65..90, 97..122, 48..57, 43, 47\r\nfor (var i = 0; i < 64;)\r\n s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;\r\n\r\n/**\r\n * Encodes a buffer to a base64 encoded string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} Base64 encoded string\r\n */\r\nbase64.encode = function encode(buffer, start, end) {\r\n var parts = null,\r\n chunk = [];\r\n var i = 0, // output index\r\n j = 0, // goto index\r\n t; // temporary\r\n while (start < end) {\r\n var b = buffer[start++];\r\n switch (j) {\r\n case 0:\r\n chunk[i++] = b64[b >> 2];\r\n t = (b & 3) << 4;\r\n j = 1;\r\n break;\r\n case 1:\r\n chunk[i++] = b64[t | b >> 4];\r\n t = (b & 15) << 2;\r\n j = 2;\r\n break;\r\n case 2:\r\n chunk[i++] = b64[t | b >> 6];\r\n chunk[i++] = b64[b & 63];\r\n j = 0;\r\n break;\r\n }\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (j) {\r\n chunk[i++] = b64[t];\r\n chunk[i++] = 61;\r\n if (j === 1)\r\n chunk[i++] = 61;\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\nvar invalidEncoding = \"invalid encoding\";\r\n\r\n/**\r\n * Decodes a base64 encoded string to a buffer.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Number of bytes written\r\n * @throws {Error} If encoding is invalid\r\n */\r\nbase64.decode = function decode(string, buffer, offset) {\r\n var start = offset;\r\n var j = 0, // goto index\r\n t; // temporary\r\n for (var i = 0; i < string.length;) {\r\n var c = string.charCodeAt(i++);\r\n if (c === 61 && j > 1)\r\n break;\r\n if ((c = s64[c]) === undefined)\r\n throw Error(invalidEncoding);\r\n switch (j) {\r\n case 0:\r\n t = c;\r\n j = 1;\r\n break;\r\n case 1:\r\n buffer[offset++] = t << 2 | (c & 48) >> 4;\r\n t = c;\r\n j = 2;\r\n break;\r\n case 2:\r\n buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;\r\n t = c;\r\n j = 3;\r\n break;\r\n case 3:\r\n buffer[offset++] = (t & 3) << 6 | c;\r\n j = 0;\r\n break;\r\n }\r\n }\r\n if (j === 1)\r\n throw Error(invalidEncoding);\r\n return offset - start;\r\n};\r\n\r\n/**\r\n * Tests if the specified string appears to be base64 encoded.\r\n * @param {string} string String to test\r\n * @returns {boolean} `true` if probably base64 encoded, otherwise false\r\n */\r\nbase64.test = function test(string) {\r\n return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);\r\n};\r\n","\"use strict\";\r\nmodule.exports = codegen;\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @param {string[]} functionParams Function parameter names\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n */\r\nfunction codegen(functionParams, functionName) {\r\n\r\n /* istanbul ignore if */\r\n if (typeof functionParams === \"string\") {\r\n functionName = functionParams;\r\n functionParams = undefined;\r\n }\r\n\r\n var body = [];\r\n\r\n /**\r\n * Appends code to the function's body or finishes generation.\r\n * @typedef Codegen\r\n * @type {function}\r\n * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any\r\n * @param {...*} [formatParams] Format parameters\r\n * @returns {Codegen|Function} Itself or the generated function if finished\r\n * @throws {Error} If format parameter counts do not match\r\n */\r\n\r\n function Codegen(formatStringOrScope) {\r\n // note that explicit array handling below makes this ~50% faster\r\n\r\n // finish the function\r\n if (typeof formatStringOrScope !== \"string\") {\r\n var source = toString();\r\n if (codegen.verbose)\r\n console.log(\"codegen: \" + source); // eslint-disable-line no-console\r\n source = \"return \" + source;\r\n if (formatStringOrScope) {\r\n var scopeKeys = Object.keys(formatStringOrScope),\r\n scopeParams = new Array(scopeKeys.length + 1),\r\n scopeValues = new Array(scopeKeys.length),\r\n scopeOffset = 0;\r\n while (scopeOffset < scopeKeys.length) {\r\n scopeParams[scopeOffset] = scopeKeys[scopeOffset];\r\n scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]];\r\n }\r\n scopeParams[scopeOffset] = source;\r\n return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func\r\n }\r\n return Function(source)(); // eslint-disable-line no-new-func\r\n }\r\n\r\n // otherwise append to body\r\n var formatParams = new Array(arguments.length - 1),\r\n formatOffset = 0;\r\n while (formatOffset < formatParams.length)\r\n formatParams[formatOffset] = arguments[++formatOffset];\r\n formatOffset = 0;\r\n formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) {\r\n var value = formatParams[formatOffset++];\r\n switch ($1) {\r\n case \"d\": case \"f\": return String(Number(value));\r\n case \"i\": return String(Math.floor(value));\r\n case \"j\": return JSON.stringify(value);\r\n case \"s\": return String(value);\r\n }\r\n return \"%\";\r\n });\r\n if (formatOffset !== formatParams.length)\r\n throw Error(\"parameter count mismatch\");\r\n body.push(formatStringOrScope);\r\n return Codegen;\r\n }\r\n\r\n function toString(functionNameOverride) {\r\n return \"function \" + (functionNameOverride || functionName || \"\") + \"(\" + (functionParams && functionParams.join(\",\") || \"\") + \"){\\n \" + body.join(\"\\n \") + \"\\n}\";\r\n }\r\n\r\n Codegen.toString = toString;\r\n return Codegen;\r\n}\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @function codegen\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * When set to `true`, codegen will log generated code to console. Useful for debugging.\r\n * @name util.codegen.verbose\r\n * @type {boolean}\r\n */\r\ncodegen.verbose = false;\r\n","\"use strict\";\r\nmodule.exports = EventEmitter;\r\n\r\n/**\r\n * Constructs a new event emitter instance.\r\n * @classdesc A minimal event emitter.\r\n * @memberof util\r\n * @constructor\r\n */\r\nfunction EventEmitter() {\r\n\r\n /**\r\n * Registered listeners.\r\n * @type {Object.}\r\n * @private\r\n */\r\n this._listeners = {};\r\n}\r\n\r\n/**\r\n * Registers an event listener.\r\n * @param {string} evt Event name\r\n * @param {function} fn Listener\r\n * @param {*} [ctx] Listener context\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.on = function on(evt, fn, ctx) {\r\n (this._listeners[evt] || (this._listeners[evt] = [])).push({\r\n fn : fn,\r\n ctx : ctx || this\r\n });\r\n return this;\r\n};\r\n\r\n/**\r\n * Removes an event listener or any matching listeners if arguments are omitted.\r\n * @param {string} [evt] Event name. Removes all listeners if omitted.\r\n * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.off = function off(evt, fn) {\r\n if (evt === undefined)\r\n this._listeners = {};\r\n else {\r\n if (fn === undefined)\r\n this._listeners[evt] = [];\r\n else {\r\n var listeners = this._listeners[evt];\r\n for (var i = 0; i < listeners.length;)\r\n if (listeners[i].fn === fn)\r\n listeners.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emits an event by calling its listeners with the specified arguments.\r\n * @param {string} evt Event name\r\n * @param {...*} args Arguments\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.emit = function emit(evt) {\r\n var listeners = this._listeners[evt];\r\n if (listeners) {\r\n var args = [],\r\n i = 1;\r\n for (; i < arguments.length;)\r\n args.push(arguments[i++]);\r\n for (i = 0; i < listeners.length;)\r\n listeners[i].fn.apply(listeners[i++].ctx, args);\r\n }\r\n return this;\r\n};\r\n","\"use strict\";\r\nmodule.exports = fetch;\r\n\r\nvar asPromise = require(1),\r\n inquire = require(7);\r\n\r\nvar fs = inquire(\"fs\");\r\n\r\n/**\r\n * Node-style callback as used by {@link util.fetch}.\r\n * @typedef FetchCallback\r\n * @type {function}\r\n * @param {?Error} error Error, if any, otherwise `null`\r\n * @param {string} [contents] File contents, if there hasn't been an error\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Options as used by {@link util.fetch}.\r\n * @typedef FetchOptions\r\n * @type {Object}\r\n * @property {boolean} [binary=false] Whether expecting a binary response\r\n * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @memberof util\r\n * @param {string} filename File path or url\r\n * @param {FetchOptions} options Fetch options\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n */\r\nfunction fetch(filename, options, callback) {\r\n if (typeof options === \"function\") {\r\n callback = options;\r\n options = {};\r\n } else if (!options)\r\n options = {};\r\n\r\n if (!callback)\r\n return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this\r\n\r\n // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found.\r\n if (!options.xhr && fs && fs.readFile)\r\n return fs.readFile(filename, function fetchReadFileCallback(err, contents) {\r\n return err && typeof XMLHttpRequest !== \"undefined\"\r\n ? fetch.xhr(filename, options, callback)\r\n : err\r\n ? callback(err)\r\n : callback(null, options.binary ? contents : contents.toString(\"utf8\"));\r\n });\r\n\r\n // use the XHR version otherwise.\r\n return fetch.xhr(filename, options, callback);\r\n}\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchOptions} [options] Fetch options\r\n * @returns {Promise} Promise\r\n * @variation 3\r\n */\r\n\r\n/**/\r\nfetch.xhr = function fetch_xhr(filename, options, callback) {\r\n var xhr = new XMLHttpRequest();\r\n xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() {\r\n\r\n if (xhr.readyState !== 4)\r\n return undefined;\r\n\r\n // local cors security errors return status 0 / empty string, too. afaik this cannot be\r\n // reliably distinguished from an actually empty file for security reasons. feel free\r\n // to send a pull request if you are aware of a solution.\r\n if (xhr.status !== 0 && xhr.status !== 200)\r\n return callback(Error(\"status \" + xhr.status));\r\n\r\n // if binary data is expected, make sure that some sort of array is returned, even if\r\n // ArrayBuffers are not supported. the binary string fallback, however, is unsafe.\r\n if (options.binary) {\r\n var buffer = xhr.response;\r\n if (!buffer) {\r\n buffer = [];\r\n for (var i = 0; i < xhr.responseText.length; ++i)\r\n buffer.push(xhr.responseText.charCodeAt(i) & 255);\r\n }\r\n return callback(null, typeof Uint8Array !== \"undefined\" ? new Uint8Array(buffer) : buffer);\r\n }\r\n return callback(null, xhr.responseText);\r\n };\r\n\r\n if (options.binary) {\r\n // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers\r\n if (\"overrideMimeType\" in xhr)\r\n xhr.overrideMimeType(\"text/plain; charset=x-user-defined\");\r\n xhr.responseType = \"arraybuffer\";\r\n }\r\n\r\n xhr.open(\"GET\", filename);\r\n xhr.send();\r\n};\r\n","\"use strict\";\r\n\r\nmodule.exports = factory(factory);\r\n\r\n/**\r\n * Reads / writes floats / doubles from / to buffers.\r\n * @name util.float\r\n * @namespace\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using little endian byte order.\r\n * @name util.float.writeFloatLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using big endian byte order.\r\n * @name util.float.writeFloatBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using little endian byte order.\r\n * @name util.float.readFloatLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using big endian byte order.\r\n * @name util.float.readFloatBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using little endian byte order.\r\n * @name util.float.writeDoubleLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using big endian byte order.\r\n * @name util.float.writeDoubleBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using little endian byte order.\r\n * @name util.float.readDoubleLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using big endian byte order.\r\n * @name util.float.readDoubleBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n// Factory function for the purpose of node-based testing in modified global environments\r\nfunction factory(exports) {\r\n\r\n // float: typed array\r\n if (typeof Float32Array !== \"undefined\") (function() {\r\n\r\n var f32 = new Float32Array([ -0 ]),\r\n f8b = new Uint8Array(f32.buffer),\r\n le = f8b[3] === 128;\r\n\r\n function writeFloat_f32_cpy(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n }\r\n\r\n function writeFloat_f32_rev(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[3];\r\n buf[pos + 1] = f8b[2];\r\n buf[pos + 2] = f8b[1];\r\n buf[pos + 3] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;\r\n\r\n function readFloat_f32_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n function readFloat_f32_rev(buf, pos) {\r\n f8b[3] = buf[pos ];\r\n f8b[2] = buf[pos + 1];\r\n f8b[1] = buf[pos + 2];\r\n f8b[0] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;\r\n\r\n // float: ieee754\r\n })(); else (function() {\r\n\r\n function writeFloat_ieee754(writeUint, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0)\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);\r\n else if (isNaN(val))\r\n writeUint(2143289344, buf, pos);\r\n else if (val > 3.4028234663852886e+38) // +-Infinity\r\n writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);\r\n else if (val < 1.1754943508222875e-38) // denormal\r\n writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);\r\n else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2),\r\n mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;\r\n writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);\r\n }\r\n }\r\n\r\n exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);\r\n exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);\r\n\r\n function readFloat_ieee754(readUint, buf, pos) {\r\n var uint = readUint(buf, pos),\r\n sign = (uint >> 31) * 2 + 1,\r\n exponent = uint >>> 23 & 255,\r\n mantissa = uint & 8388607;\r\n return exponent === 255\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 1.401298464324817e-45 * mantissa\r\n : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);\r\n }\r\n\r\n exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);\r\n exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);\r\n\r\n })();\r\n\r\n // double: typed array\r\n if (typeof Float64Array !== \"undefined\") (function() {\r\n\r\n var f64 = new Float64Array([-0]),\r\n f8b = new Uint8Array(f64.buffer),\r\n le = f8b[7] === 128;\r\n\r\n function writeDouble_f64_cpy(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n buf[pos + 4] = f8b[4];\r\n buf[pos + 5] = f8b[5];\r\n buf[pos + 6] = f8b[6];\r\n buf[pos + 7] = f8b[7];\r\n }\r\n\r\n function writeDouble_f64_rev(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[7];\r\n buf[pos + 1] = f8b[6];\r\n buf[pos + 2] = f8b[5];\r\n buf[pos + 3] = f8b[4];\r\n buf[pos + 4] = f8b[3];\r\n buf[pos + 5] = f8b[2];\r\n buf[pos + 6] = f8b[1];\r\n buf[pos + 7] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;\r\n\r\n function readDouble_f64_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n f8b[4] = buf[pos + 4];\r\n f8b[5] = buf[pos + 5];\r\n f8b[6] = buf[pos + 6];\r\n f8b[7] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n function readDouble_f64_rev(buf, pos) {\r\n f8b[7] = buf[pos ];\r\n f8b[6] = buf[pos + 1];\r\n f8b[5] = buf[pos + 2];\r\n f8b[4] = buf[pos + 3];\r\n f8b[3] = buf[pos + 4];\r\n f8b[2] = buf[pos + 5];\r\n f8b[1] = buf[pos + 6];\r\n f8b[0] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;\r\n\r\n // double: ieee754\r\n })(); else (function() {\r\n\r\n function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);\r\n } else if (isNaN(val)) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(2146959360, buf, pos + off1);\r\n } else if (val > 1.7976931348623157e+308) { // +-Infinity\r\n writeUint(0, buf, pos + off0);\r\n writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);\r\n } else {\r\n var mantissa;\r\n if (val < 2.2250738585072014e-308) { // denormal\r\n mantissa = val / 5e-324;\r\n writeUint(mantissa >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);\r\n } else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2);\r\n if (exponent === 1024)\r\n exponent = 1023;\r\n mantissa = val * Math.pow(2, -exponent);\r\n writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);\r\n }\r\n }\r\n }\r\n\r\n exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);\r\n exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);\r\n\r\n function readDouble_ieee754(readUint, off0, off1, buf, pos) {\r\n var lo = readUint(buf, pos + off0),\r\n hi = readUint(buf, pos + off1);\r\n var sign = (hi >> 31) * 2 + 1,\r\n exponent = hi >>> 20 & 2047,\r\n mantissa = 4294967296 * (hi & 1048575) + lo;\r\n return exponent === 2047\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 5e-324 * mantissa\r\n : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);\r\n }\r\n\r\n exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);\r\n exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);\r\n\r\n })();\r\n\r\n return exports;\r\n}\r\n\r\n// uint helpers\r\n\r\nfunction writeUintLE(val, buf, pos) {\r\n buf[pos ] = val & 255;\r\n buf[pos + 1] = val >>> 8 & 255;\r\n buf[pos + 2] = val >>> 16 & 255;\r\n buf[pos + 3] = val >>> 24;\r\n}\r\n\r\nfunction writeUintBE(val, buf, pos) {\r\n buf[pos ] = val >>> 24;\r\n buf[pos + 1] = val >>> 16 & 255;\r\n buf[pos + 2] = val >>> 8 & 255;\r\n buf[pos + 3] = val & 255;\r\n}\r\n\r\nfunction readUintLE(buf, pos) {\r\n return (buf[pos ]\r\n | buf[pos + 1] << 8\r\n | buf[pos + 2] << 16\r\n | buf[pos + 3] << 24) >>> 0;\r\n}\r\n\r\nfunction readUintBE(buf, pos) {\r\n return (buf[pos ] << 24\r\n | buf[pos + 1] << 16\r\n | buf[pos + 2] << 8\r\n | buf[pos + 3]) >>> 0;\r\n}\r\n","\"use strict\";\r\nmodule.exports = inquire;\r\n\r\n/**\r\n * Requires a module only if available.\r\n * @memberof util\r\n * @param {string} moduleName Module to require\r\n * @returns {?Object} Required module if available and not empty, otherwise `null`\r\n */\r\nfunction inquire(moduleName) {\r\n try {\r\n var mod = eval(\"quire\".replace(/^/,\"re\"))(moduleName); // eslint-disable-line no-eval\r\n if (mod && (mod.length || Object.keys(mod).length))\r\n return mod;\r\n } catch (e) {} // eslint-disable-line no-empty\r\n return null;\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal path module to resolve Unix, Windows and URL paths alike.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar path = exports;\r\n\r\nvar isAbsolute =\r\n/**\r\n * Tests if the specified path is absolute.\r\n * @param {string} path Path to test\r\n * @returns {boolean} `true` if path is absolute\r\n */\r\npath.isAbsolute = function isAbsolute(path) {\r\n return /^(?:\\/|\\w+:)/.test(path);\r\n};\r\n\r\nvar normalize =\r\n/**\r\n * Normalizes the specified path.\r\n * @param {string} path Path to normalize\r\n * @returns {string} Normalized path\r\n */\r\npath.normalize = function normalize(path) {\r\n path = path.replace(/\\\\/g, \"/\")\r\n .replace(/\\/{2,}/g, \"/\");\r\n var parts = path.split(\"/\"),\r\n absolute = isAbsolute(path),\r\n prefix = \"\";\r\n if (absolute)\r\n prefix = parts.shift() + \"/\";\r\n for (var i = 0; i < parts.length;) {\r\n if (parts[i] === \"..\") {\r\n if (i > 0 && parts[i - 1] !== \"..\")\r\n parts.splice(--i, 2);\r\n else if (absolute)\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n } else if (parts[i] === \".\")\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n return prefix + parts.join(\"/\");\r\n};\r\n\r\n/**\r\n * Resolves the specified include path against the specified origin path.\r\n * @param {string} originPath Path to the origin file\r\n * @param {string} includePath Include path relative to origin path\r\n * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized\r\n * @returns {string} Path to the include file\r\n */\r\npath.resolve = function resolve(originPath, includePath, alreadyNormalized) {\r\n if (!alreadyNormalized)\r\n includePath = normalize(includePath);\r\n if (isAbsolute(includePath))\r\n return includePath;\r\n if (!alreadyNormalized)\r\n originPath = normalize(originPath);\r\n return (originPath = originPath.replace(/(?:\\/|^)[^/]+$/, \"\")).length ? normalize(originPath + \"/\" + includePath) : includePath;\r\n};\r\n","\"use strict\";\r\nmodule.exports = pool;\r\n\r\n/**\r\n * An allocator as used by {@link util.pool}.\r\n * @typedef PoolAllocator\r\n * @type {function}\r\n * @param {number} size Buffer size\r\n * @returns {Uint8Array} Buffer\r\n */\r\n\r\n/**\r\n * A slicer as used by {@link util.pool}.\r\n * @typedef PoolSlicer\r\n * @type {function}\r\n * @param {number} start Start offset\r\n * @param {number} end End offset\r\n * @returns {Uint8Array} Buffer slice\r\n * @this {Uint8Array}\r\n */\r\n\r\n/**\r\n * A general purpose buffer pool.\r\n * @memberof util\r\n * @function\r\n * @param {PoolAllocator} alloc Allocator\r\n * @param {PoolSlicer} slice Slicer\r\n * @param {number} [size=8192] Slab size\r\n * @returns {PoolAllocator} Pooled allocator\r\n */\r\nfunction pool(alloc, slice, size) {\r\n var SIZE = size || 8192;\r\n var MAX = SIZE >>> 1;\r\n var slab = null;\r\n var offset = SIZE;\r\n return function pool_alloc(size) {\r\n if (size < 1 || size > MAX)\r\n return alloc(size);\r\n if (offset + size > SIZE) {\r\n slab = alloc(SIZE);\r\n offset = 0;\r\n }\r\n var buf = slice.call(slab, offset, offset += size);\r\n if (offset & 7) // align to 32 bit\r\n offset = (offset | 7) + 1;\r\n return buf;\r\n };\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal UTF8 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar utf8 = exports;\r\n\r\n/**\r\n * Calculates the UTF8 byte length of a string.\r\n * @param {string} string String\r\n * @returns {number} Byte length\r\n */\r\nutf8.length = function utf8_length(string) {\r\n var len = 0,\r\n c = 0;\r\n for (var i = 0; i < string.length; ++i) {\r\n c = string.charCodeAt(i);\r\n if (c < 128)\r\n len += 1;\r\n else if (c < 2048)\r\n len += 2;\r\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\r\n ++i;\r\n len += 4;\r\n } else\r\n len += 3;\r\n }\r\n return len;\r\n};\r\n\r\n/**\r\n * Reads UTF8 bytes as a string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} String read\r\n */\r\nutf8.read = function utf8_read(buffer, start, end) {\r\n var len = end - start;\r\n if (len < 1)\r\n return \"\";\r\n var parts = null,\r\n chunk = [],\r\n i = 0, // char offset\r\n t; // temporary\r\n while (start < end) {\r\n t = buffer[start++];\r\n if (t < 128)\r\n chunk[i++] = t;\r\n else if (t > 191 && t < 224)\r\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\r\n else if (t > 239 && t < 365) {\r\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\r\n chunk[i++] = 0xD800 + (t >> 10);\r\n chunk[i++] = 0xDC00 + (t & 1023);\r\n } else\r\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\n/**\r\n * Writes a string as UTF8 bytes.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Bytes written\r\n */\r\nutf8.write = function utf8_write(string, buffer, offset) {\r\n var start = offset,\r\n c1, // character 1\r\n c2; // character 2\r\n for (var i = 0; i < string.length; ++i) {\r\n c1 = string.charCodeAt(i);\r\n if (c1 < 128) {\r\n buffer[offset++] = c1;\r\n } else if (c1 < 2048) {\r\n buffer[offset++] = c1 >> 6 | 192;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\r\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\r\n ++i;\r\n buffer[offset++] = c1 >> 18 | 240;\r\n buffer[offset++] = c1 >> 12 & 63 | 128;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else {\r\n buffer[offset++] = c1 >> 12 | 224;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n }\r\n }\r\n return offset - start;\r\n};\r\n","\"use strict\";\nmodule.exports = common;\n\nvar commonRe = /\\/|\\./;\n\n/**\n * Provides common type definitions.\n * Can also be used to provide additional google types or your own custom types.\n * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name\n * @param {Object.} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition\n * @returns {undefined}\n * @property {INamespace} google/protobuf/any.proto Any\n * @property {INamespace} google/protobuf/duration.proto Duration\n * @property {INamespace} google/protobuf/empty.proto Empty\n * @property {INamespace} google/protobuf/field_mask.proto FieldMask\n * @property {INamespace} google/protobuf/struct.proto Struct, Value, NullValue and ListValue\n * @property {INamespace} google/protobuf/timestamp.proto Timestamp\n * @property {INamespace} google/protobuf/wrappers.proto Wrappers\n * @example\n * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension)\n * protobuf.common(\"descriptor\", descriptorJson);\n *\n * // manually provides a custom definition (uses my.foo namespace)\n * protobuf.common(\"my/foo/bar.proto\", myFooBarJson);\n */\nfunction common(name, json) {\n if (!commonRe.test(name)) {\n name = \"google/protobuf/\" + name + \".proto\";\n json = { nested: { google: { nested: { protobuf: { nested: json } } } } };\n }\n common[name] = json;\n}\n\n// Not provided because of limited use (feel free to discuss or to provide yourself):\n//\n// google/protobuf/descriptor.proto\n// google/protobuf/source_context.proto\n// google/protobuf/type.proto\n//\n// Stripped and pre-parsed versions of these non-bundled files are instead available as part of\n// the repository or package within the google/protobuf directory.\n\ncommon(\"any\", {\n\n /**\n * Properties of a google.protobuf.Any message.\n * @interface IAny\n * @type {Object}\n * @property {string} [typeUrl]\n * @property {Uint8Array} [bytes]\n * @memberof common\n */\n Any: {\n fields: {\n type_url: {\n type: \"string\",\n id: 1\n },\n value: {\n type: \"bytes\",\n id: 2\n }\n }\n }\n});\n\nvar timeType;\n\ncommon(\"duration\", {\n\n /**\n * Properties of a google.protobuf.Duration message.\n * @interface IDuration\n * @type {Object}\n * @property {number|Long} [seconds]\n * @property {number} [nanos]\n * @memberof common\n */\n Duration: timeType = {\n fields: {\n seconds: {\n type: \"int64\",\n id: 1\n },\n nanos: {\n type: \"int32\",\n id: 2\n }\n }\n }\n});\n\ncommon(\"timestamp\", {\n\n /**\n * Properties of a google.protobuf.Timestamp message.\n * @interface ITimestamp\n * @type {Object}\n * @property {number|Long} [seconds]\n * @property {number} [nanos]\n * @memberof common\n */\n Timestamp: timeType\n});\n\ncommon(\"empty\", {\n\n /**\n * Properties of a google.protobuf.Empty message.\n * @interface IEmpty\n * @memberof common\n */\n Empty: {\n fields: {}\n }\n});\n\ncommon(\"struct\", {\n\n /**\n * Properties of a google.protobuf.Struct message.\n * @interface IStruct\n * @type {Object}\n * @property {Object.} [fields]\n * @memberof common\n */\n Struct: {\n fields: {\n fields: {\n keyType: \"string\",\n type: \"Value\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.Value message.\n * @interface IValue\n * @type {Object}\n * @property {string} [kind]\n * @property {0} [nullValue]\n * @property {number} [numberValue]\n * @property {string} [stringValue]\n * @property {boolean} [boolValue]\n * @property {IStruct} [structValue]\n * @property {IListValue} [listValue]\n * @memberof common\n */\n Value: {\n oneofs: {\n kind: {\n oneof: [\n \"nullValue\",\n \"numberValue\",\n \"stringValue\",\n \"boolValue\",\n \"structValue\",\n \"listValue\"\n ]\n }\n },\n fields: {\n nullValue: {\n type: \"NullValue\",\n id: 1\n },\n numberValue: {\n type: \"double\",\n id: 2\n },\n stringValue: {\n type: \"string\",\n id: 3\n },\n boolValue: {\n type: \"bool\",\n id: 4\n },\n structValue: {\n type: \"Struct\",\n id: 5\n },\n listValue: {\n type: \"ListValue\",\n id: 6\n }\n }\n },\n\n NullValue: {\n values: {\n NULL_VALUE: 0\n }\n },\n\n /**\n * Properties of a google.protobuf.ListValue message.\n * @interface IListValue\n * @type {Object}\n * @property {Array.} [values]\n * @memberof common\n */\n ListValue: {\n fields: {\n values: {\n rule: \"repeated\",\n type: \"Value\",\n id: 1\n }\n }\n }\n});\n\ncommon(\"wrappers\", {\n\n /**\n * Properties of a google.protobuf.DoubleValue message.\n * @interface IDoubleValue\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n DoubleValue: {\n fields: {\n value: {\n type: \"double\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.FloatValue message.\n * @interface IFloatValue\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n FloatValue: {\n fields: {\n value: {\n type: \"float\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.Int64Value message.\n * @interface IInt64Value\n * @type {Object}\n * @property {number|Long} [value]\n * @memberof common\n */\n Int64Value: {\n fields: {\n value: {\n type: \"int64\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.UInt64Value message.\n * @interface IUInt64Value\n * @type {Object}\n * @property {number|Long} [value]\n * @memberof common\n */\n UInt64Value: {\n fields: {\n value: {\n type: \"uint64\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.Int32Value message.\n * @interface IInt32Value\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n Int32Value: {\n fields: {\n value: {\n type: \"int32\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.UInt32Value message.\n * @interface IUInt32Value\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n UInt32Value: {\n fields: {\n value: {\n type: \"uint32\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.BoolValue message.\n * @interface IBoolValue\n * @type {Object}\n * @property {boolean} [value]\n * @memberof common\n */\n BoolValue: {\n fields: {\n value: {\n type: \"bool\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.StringValue message.\n * @interface IStringValue\n * @type {Object}\n * @property {string} [value]\n * @memberof common\n */\n StringValue: {\n fields: {\n value: {\n type: \"string\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.BytesValue message.\n * @interface IBytesValue\n * @type {Object}\n * @property {Uint8Array} [value]\n * @memberof common\n */\n BytesValue: {\n fields: {\n value: {\n type: \"bytes\",\n id: 1\n }\n }\n }\n});\n\ncommon(\"field_mask\", {\n\n /**\n * Properties of a google.protobuf.FieldMask message.\n * @interface IDoubleValue\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n FieldMask: {\n fields: {\n paths: {\n rule: \"repeated\",\n type: \"string\",\n id: 1\n }\n }\n }\n});\n\n/**\n * Gets the root definition of the specified common proto file.\n *\n * Bundled definitions are:\n * - google/protobuf/any.proto\n * - google/protobuf/duration.proto\n * - google/protobuf/empty.proto\n * - google/protobuf/field_mask.proto\n * - google/protobuf/struct.proto\n * - google/protobuf/timestamp.proto\n * - google/protobuf/wrappers.proto\n *\n * @param {string} file Proto file name\n * @returns {INamespace|null} Root definition or `null` if not defined\n */\ncommon.get = function get(file) {\n return common[file] || null;\n};\n","\"use strict\";\n/**\n * Runtime message from/to plain object converters.\n * @namespace\n */\nvar converter = exports;\n\nvar Enum = require(15),\n util = require(37);\n\n/**\n * Generates a partial value fromObject conveter.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {number} fieldIndex Field index\n * @param {string} prop Property reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genValuePartial_fromObject(gen, field, fieldIndex, prop) {\n var defaultAlreadyEmitted = false;\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n if (field.resolvedType) {\n if (field.resolvedType instanceof Enum) { gen\n (\"switch(d%s){\", prop);\n for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {\n // enum unknown values passthrough\n if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen\n (\"default:\")\n (\"if(typeof(d%s)===\\\"number\\\"){m%s=d%s;break}\", prop, prop, prop);\n if (!field.repeated) gen // fallback to default value only for\n // arrays, to avoid leaving holes.\n (\"break\"); // for non-repeated fields, just ignore\n defaultAlreadyEmitted = true;\n }\n gen\n (\"case%j:\", keys[i])\n (\"case %i:\", values[keys[i]])\n (\"m%s=%j\", prop, values[keys[i]])\n (\"break\");\n } gen\n (\"}\");\n } else gen\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\n (\"m%s=types[%i].fromObject(d%s)\", prop, fieldIndex, prop);\n } else {\n var isUnsigned = false;\n switch (field.type) {\n case \"double\":\n case \"float\": gen\n (\"m%s=Number(d%s)\", prop, prop); // also catches \"NaN\", \"Infinity\"\n break;\n case \"uint32\":\n case \"fixed32\": gen\n (\"m%s=d%s>>>0\", prop, prop);\n break;\n case \"int32\":\n case \"sint32\":\n case \"sfixed32\": gen\n (\"m%s=d%s|0\", prop, prop);\n break;\n case \"uint64\":\n isUnsigned = true;\n // eslint-disable-next-line no-fallthrough\n case \"int64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(util.Long)\")\n (\"(m%s=util.Long.fromValue(d%s)).unsigned=%j\", prop, prop, isUnsigned)\n (\"else if(typeof d%s===\\\"string\\\")\", prop)\n (\"m%s=parseInt(d%s,10)\", prop, prop)\n (\"else if(typeof d%s===\\\"number\\\")\", prop)\n (\"m%s=d%s\", prop, prop)\n (\"else if(typeof d%s===\\\"object\\\")\", prop)\n (\"m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)\", prop, prop, prop, isUnsigned ? \"true\" : \"\");\n break;\n case \"bytes\": gen\n (\"if(typeof d%s===\\\"string\\\")\", prop)\n (\"util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)\", prop, prop, prop)\n (\"else if(d%s.length >= 0)\", prop)\n (\"m%s=d%s\", prop, prop);\n break;\n case \"string\": gen\n (\"m%s=String(d%s)\", prop, prop);\n break;\n case \"bool\": gen\n (\"m%s=Boolean(d%s)\", prop, prop);\n break;\n /* default: gen\n (\"m%s=d%s\", prop, prop);\n break; */\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n\n/**\n * Generates a plain object to runtime message converter specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nconverter.fromObject = function fromObject(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var fields = mtype.fieldsArray;\n var gen = util.codegen([\"d\"], mtype.name + \"$fromObject\")\n (\"if(d instanceof this.ctor)\")\n (\"return d\");\n if (!fields.length) return gen\n (\"return new this.ctor\");\n gen\n (\"var m=new this.ctor\");\n for (var i = 0; i < fields.length; ++i) {\n var field = fields[i].resolve(),\n prop = util.safeProp(field.name);\n\n // Map fields\n if (field.map) { gen\n (\"if(d%s){\", prop)\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\n (\"m%s={}\", prop)\n (\"for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s\", prop, prop, prop, prop, isUnsigned ? \"true\": \"\", prop);\n break;\n case \"bytes\": gen\n (\"d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s\", prop, prop, prop, prop, prop);\n break;\n default: gen\n (\"d%s=m%s\", prop, prop);\n break;\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n\n/**\n * Generates a runtime message to plain object converter specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nconverter.toObject = function toObject(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById);\n if (!fields.length)\n return util.codegen()(\"return {}\");\n var gen = util.codegen([\"m\", \"o\"], mtype.name + \"$toObject\")\n (\"if(!o)\")\n (\"o={}\")\n (\"var d={}\");\n\n var repeatedFields = [],\n mapFields = [],\n normalFields = [],\n i = 0;\n for (; i < fields.length; ++i)\n if (!fields[i].partOf)\n ( fields[i].resolve().repeated ? repeatedFields\n : fields[i].map ? mapFields\n : normalFields).push(fields[i]);\n\n if (repeatedFields.length) { gen\n (\"if(o.arrays||o.defaults){\");\n for (i = 0; i < repeatedFields.length; ++i) gen\n (\"d%s=[]\", util.safeProp(repeatedFields[i].name));\n gen\n (\"}\");\n }\n\n if (mapFields.length) { gen\n (\"if(o.objects||o.defaults){\");\n for (i = 0; i < mapFields.length; ++i) gen\n (\"d%s={}\", util.safeProp(mapFields[i].name));\n gen\n (\"}\");\n }\n\n if (normalFields.length) { gen\n (\"if(o.defaults){\");\n for (i = 0; i < normalFields.length; ++i) {\n var field = normalFields[i],\n prop = util.safeProp(field.name);\n if (field.resolvedType instanceof Enum) gen\n (\"d%s=o.enums===String?%j:%j\", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault);\n else if (field.long) gen\n (\"if(util.Long){\")\n (\"var n=new util.Long(%i,%i,%j)\", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)\n (\"d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n\", prop)\n (\"}else\")\n (\"d%s=o.longs===String?%j:%i\", prop, field.typeDefault.toString(), field.typeDefault.toNumber());\n else if (field.bytes) {\n var arrayDefault = \"[\" + Array.prototype.slice.call(field.typeDefault).join(\",\") + \"]\";\n gen\n (\"if(o.bytes===String)d%s=%j\", prop, String.fromCharCode.apply(String, field.typeDefault))\n (\"else{\")\n (\"d%s=%s\", prop, arrayDefault)\n (\"if(o.bytes!==Array)d%s=util.newBuffer(d%s)\", prop, prop)\n (\"}\");\n } else gen\n (\"d%s=%j\", prop, field.typeDefault); // also messages (=null)\n } gen\n (\"}\");\n }\n var hasKs2 = false;\n for (i = 0; i < fields.length; ++i) {\n var field = fields[i],\n index = mtype._fieldsArray.indexOf(field),\n prop = util.safeProp(field.name);\n if (field.map) {\n if (!hasKs2) { hasKs2 = true; gen\n (\"var ks2\");\n } gen\n (\"if(m%s&&(ks2=Object.keys(m%s)).length){\", prop, prop)\n (\"d%s={}\", prop)\n (\"for(var j=0;j>>3){\");\n\n var i = 0;\n for (; i < /* initializes */ mtype.fieldsArray.length; ++i) {\n var field = mtype._fieldsArray[i].resolve(),\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\n ref = \"m\" + util.safeProp(field.name); gen\n (\"case %i: {\", field.id);\n\n // Map fields\n if (field.map) { gen\n (\"if(%s===util.emptyObject)\", ref)\n (\"%s={}\", ref)\n (\"var c2 = r.uint32()+r.pos\");\n\n if (types.defaults[field.keyType] !== undefined) gen\n (\"k=%j\", types.defaults[field.keyType]);\n else gen\n (\"k=null\");\n\n if (types.defaults[type] !== undefined) gen\n (\"value=%j\", types.defaults[type]);\n else gen\n (\"value=null\");\n\n gen\n (\"while(r.pos>>3){\")\n (\"case 1: k=r.%s(); break\", field.keyType)\n (\"case 2:\");\n\n if (types.basic[type] === undefined) gen\n (\"value=types[%i].decode(r,r.uint32())\", i); // can't be groups\n else gen\n (\"value=r.%s()\", type);\n\n gen\n (\"break\")\n (\"default:\")\n (\"r.skipType(tag2&7)\")\n (\"break\")\n (\"}\")\n (\"}\");\n\n if (types.long[field.keyType] !== undefined) gen\n (\"%s[typeof k===\\\"object\\\"?util.longToHash(k):k]=value\", ref);\n else gen\n (\"%s[k]=value\", ref);\n\n // Repeated fields\n } else if (field.repeated) { gen\n\n (\"if(!(%s&&%s.length))\", ref, ref)\n (\"%s=[]\", ref);\n\n // Packable (always check for forward and backward compatiblity)\n if (types.packed[type] !== undefined) gen\n (\"if((t&7)===2){\")\n (\"var c2=r.uint32()+r.pos\")\n (\"while(r.pos>> 0, (field.id << 3 | 4) >>> 0)\n : gen(\"types[%i].encode(%s,w.uint32(%i).fork()).ldelim()\", fieldIndex, ref, (field.id << 3 | 2) >>> 0);\n}\n\n/**\n * Generates an encoder specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nfunction encoder(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var gen = util.codegen([\"m\", \"w\"], mtype.name + \"$encode\")\n (\"if(!w)\")\n (\"w=Writer.create()\");\n\n var i, ref;\n\n // \"when a message is serialized its known fields should be written sequentially by field number\"\n var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById);\n\n for (var i = 0; i < fields.length; ++i) {\n var field = fields[i].resolve(),\n index = mtype._fieldsArray.indexOf(field),\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\n wireType = types.basic[type];\n ref = \"m\" + util.safeProp(field.name);\n\n // Map fields\n if (field.map) {\n gen\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j)){\", ref, field.name) // !== undefined && !== null\n (\"for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType);\n if (wireType === undefined) gen\n (\"types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()\", index, ref); // can't be groups\n else gen\n (\".uint32(%i).%s(%s[ks[i]]).ldelim()\", 16 | wireType, type, ref);\n gen\n (\"}\")\n (\"}\");\n\n // Repeated fields\n } else if (field.repeated) { gen\n (\"if(%s!=null&&%s.length){\", ref, ref); // !== undefined && !== null\n\n // Packed repeated\n if (field.packed && types.packed[type] !== undefined) { gen\n\n (\"w.uint32(%i).fork()\", (field.id << 3 | 2) >>> 0)\n (\"for(var i=0;i<%s.length;++i)\", ref)\n (\"w.%s(%s[i])\", type, ref)\n (\"w.ldelim()\");\n\n // Non-packed\n } else { gen\n\n (\"for(var i=0;i<%s.length;++i)\", ref);\n if (wireType === undefined)\n genTypePartial(gen, field, index, ref + \"[i]\");\n else gen\n (\"w.uint32(%i).%s(%s[i])\", (field.id << 3 | wireType) >>> 0, type, ref);\n\n } gen\n (\"}\");\n\n // Non-repeated\n } else {\n if (field.optional) gen\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j))\", ref, field.name); // !== undefined && !== null\n\n if (wireType === undefined)\n genTypePartial(gen, field, index, ref);\n else gen\n (\"w.uint32(%i).%s(%s)\", (field.id << 3 | wireType) >>> 0, type, ref);\n\n }\n }\n\n return gen\n (\"return w\");\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n","\"use strict\";\nmodule.exports = Enum;\n\n// extends ReflectionObject\nvar ReflectionObject = require(24);\n((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = \"Enum\";\n\nvar Namespace = require(23),\n util = require(37);\n\n/**\n * Constructs a new enum instance.\n * @classdesc Reflected enum.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {Object.} [values] Enum values as an object, by name\n * @param {Object.} [options] Declared options\n * @param {string} [comment] The comment for this enum\n * @param {Object.} [comments] The value comments for this enum\n * @param {Object.>|undefined} [valuesOptions] The value options for this enum\n */\nfunction Enum(name, values, options, comment, comments, valuesOptions) {\n ReflectionObject.call(this, name, options);\n\n if (values && typeof values !== \"object\")\n throw TypeError(\"values must be an object\");\n\n /**\n * Enum values by id.\n * @type {Object.}\n */\n this.valuesById = {};\n\n /**\n * Enum values by name.\n * @type {Object.}\n */\n this.values = Object.create(this.valuesById); // toJSON, marker\n\n /**\n * Enum comment text.\n * @type {string|null}\n */\n this.comment = comment;\n\n /**\n * Value comment texts, if any.\n * @type {Object.}\n */\n this.comments = comments || {};\n\n /**\n * Values options, if any\n * @type {Object>|undefined}\n */\n this.valuesOptions = valuesOptions;\n\n /**\n * Resolved values features, if any\n * @type {Object>|undefined}\n */\n this._valuesFeatures = {};\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n // Note that values inherit valuesById on their prototype which makes them a TypeScript-\n // compatible enum. This is used by pbts to write actual enum definitions that work for\n // static and reflection code alike instead of emitting generic object definitions.\n\n if (values)\n for (var keys = Object.keys(values), i = 0; i < keys.length; ++i)\n if (typeof values[keys[i]] === \"number\") // use forward entries only\n this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i];\n}\n\n/**\n * @override\n */\nEnum.prototype._resolveFeatures = function _resolveFeatures(edition) {\n edition = this._edition || edition;\n ReflectionObject.prototype._resolveFeatures.call(this, edition);\n\n Object.keys(this.values).forEach(key => {\n var parentFeaturesCopy = Object.assign({}, this._features);\n this._valuesFeatures[key] = Object.assign(parentFeaturesCopy, this.valuesOptions && this.valuesOptions[key] && this.valuesOptions[key].features);\n });\n\n return this;\n};\n\n/**\n * Enum descriptor.\n * @interface IEnum\n * @property {Object.} values Enum values\n * @property {Object.} [options] Enum options\n */\n\n/**\n * Constructs an enum from an enum descriptor.\n * @param {string} name Enum name\n * @param {IEnum} json Enum descriptor\n * @returns {Enum} Created enum\n * @throws {TypeError} If arguments are invalid\n */\nEnum.fromJSON = function fromJSON(name, json) {\n var enm = new Enum(name, json.values, json.options, json.comment, json.comments);\n enm.reserved = json.reserved;\n if (json.edition)\n enm._edition = json.edition;\n enm._defaultEdition = \"proto3\"; // For backwards-compatibility.\n return enm;\n};\n\n/**\n * Converts this enum to an enum descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IEnum} Enum descriptor\n */\nEnum.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"edition\" , this._editionToJSON(),\n \"options\" , this.options,\n \"valuesOptions\" , this.valuesOptions,\n \"values\" , this.values,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"comment\" , keepComments ? this.comment : undefined,\n \"comments\" , keepComments ? this.comments : undefined\n ]);\n};\n\n/**\n * Adds a value to this enum.\n * @param {string} name Value name\n * @param {number} id Value id\n * @param {string} [comment] Comment, if any\n * @param {Object.|undefined} [options] Options, if any\n * @returns {Enum} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a value with this name or id\n */\nEnum.prototype.add = function add(name, id, comment, options) {\n // utilized by the parser but not by .fromJSON\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n if (!util.isInteger(id))\n throw TypeError(\"id must be an integer\");\n\n if (this.values[name] !== undefined)\n throw Error(\"duplicate name '\" + name + \"' in \" + this);\n\n if (this.isReservedId(id))\n throw Error(\"id \" + id + \" is reserved in \" + this);\n\n if (this.isReservedName(name))\n throw Error(\"name '\" + name + \"' is reserved in \" + this);\n\n if (this.valuesById[id] !== undefined) {\n if (!(this.options && this.options.allow_alias))\n throw Error(\"duplicate id \" + id + \" in \" + this);\n this.values[name] = id;\n } else\n this.valuesById[this.values[name] = id] = name;\n\n if (options) {\n if (this.valuesOptions === undefined)\n this.valuesOptions = {};\n this.valuesOptions[name] = options || null;\n }\n\n this.comments[name] = comment || null;\n return this;\n};\n\n/**\n * Removes a value from this enum\n * @param {string} name Value name\n * @returns {Enum} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `name` is not a name of this enum\n */\nEnum.prototype.remove = function remove(name) {\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n var val = this.values[name];\n if (val == null)\n throw Error(\"name '\" + name + \"' does not exist in \" + this);\n\n delete this.valuesById[val];\n delete this.values[name];\n delete this.comments[name];\n if (this.valuesOptions)\n delete this.valuesOptions[name];\n\n return this;\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nEnum.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nEnum.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n","\"use strict\";\nmodule.exports = Field;\n\n// extends ReflectionObject\nvar ReflectionObject = require(24);\n((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = \"Field\";\n\nvar Enum = require(15),\n types = require(36),\n util = require(37);\n\nvar Type; // cyclic\n\nvar ruleRe = /^required|optional|repeated$/;\n\n/**\n * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class.\n * @name Field\n * @classdesc Reflected message field.\n * @extends FieldBase\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} type Value type\n * @param {string|Object.} [rule=\"optional\"] Field rule\n * @param {string|Object.} [extend] Extended type if different from parent\n * @param {Object.} [options] Declared options\n */\n\n/**\n * Constructs a field from a field descriptor.\n * @param {string} name Field name\n * @param {IField} json Field descriptor\n * @returns {Field} Created field\n * @throws {TypeError} If arguments are invalid\n */\nField.fromJSON = function fromJSON(name, json) {\n var field = new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment);\n if (json.edition)\n field._edition = json.edition;\n field._defaultEdition = \"proto3\"; // For backwards-compatibility.\n return field;\n};\n\n/**\n * Not an actual constructor. Use {@link Field} instead.\n * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions.\n * @exports FieldBase\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} type Value type\n * @param {string|Object.} [rule=\"optional\"] Field rule\n * @param {string|Object.} [extend] Extended type if different from parent\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction Field(name, id, type, rule, extend, options, comment) {\n\n if (util.isObject(rule)) {\n comment = extend;\n options = rule;\n rule = extend = undefined;\n } else if (util.isObject(extend)) {\n comment = options;\n options = extend;\n extend = undefined;\n }\n\n ReflectionObject.call(this, name, options);\n\n if (!util.isInteger(id) || id < 0)\n throw TypeError(\"id must be a non-negative integer\");\n\n if (!util.isString(type))\n throw TypeError(\"type must be a string\");\n\n if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase()))\n throw TypeError(\"rule must be a string rule\");\n\n if (extend !== undefined && !util.isString(extend))\n throw TypeError(\"extend must be a string\");\n\n /**\n * Field rule, if any.\n * @type {string|undefined}\n */\n if (rule === \"proto3_optional\") {\n rule = \"optional\";\n }\n this.rule = rule && rule !== \"optional\" ? rule : undefined; // toJSON\n\n /**\n * Field type.\n * @type {string}\n */\n this.type = type; // toJSON\n\n /**\n * Unique field id.\n * @type {number}\n */\n this.id = id; // toJSON, marker\n\n /**\n * Extended type if different from parent.\n * @type {string|undefined}\n */\n this.extend = extend || undefined; // toJSON\n\n /**\n * Whether this field is repeated.\n * @type {boolean}\n */\n this.repeated = rule === \"repeated\";\n\n /**\n * Whether this field is a map or not.\n * @type {boolean}\n */\n this.map = false;\n\n /**\n * Message this field belongs to.\n * @type {Type|null}\n */\n this.message = null;\n\n /**\n * OneOf this field belongs to, if any,\n * @type {OneOf|null}\n */\n this.partOf = null;\n\n /**\n * The field type's default value.\n * @type {*}\n */\n this.typeDefault = null;\n\n /**\n * The field's default value on prototypes.\n * @type {*}\n */\n this.defaultValue = null;\n\n /**\n * Whether this field's value should be treated as a long.\n * @type {boolean}\n */\n this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false;\n\n /**\n * Whether this field's value is a buffer.\n * @type {boolean}\n */\n this.bytes = type === \"bytes\";\n\n /**\n * Resolved type if not a basic type.\n * @type {Type|Enum|null}\n */\n this.resolvedType = null;\n\n /**\n * Sister-field within the extended type if a declaring extension field.\n * @type {Field|null}\n */\n this.extensionField = null;\n\n /**\n * Sister-field within the declaring namespace if an extended field.\n * @type {Field|null}\n */\n this.declaringField = null;\n\n /**\n * Comment for this field.\n * @type {string|null}\n */\n this.comment = comment;\n}\n\n/**\n * Determines whether this field is required.\n * @name Field#required\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"required\", {\n get: function() {\n return this._features.field_presence === \"LEGACY_REQUIRED\";\n }\n});\n\n/**\n * Determines whether this field is not required.\n * @name Field#optional\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"optional\", {\n get: function() {\n return !this.required;\n }\n});\n\n/**\n * Determines whether this field uses tag-delimited encoding. In proto2 this\n * corresponded to group syntax.\n * @name Field#delimited\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"delimited\", {\n get: function() {\n return this.resolvedType instanceof Type &&\n this._features.message_encoding === \"DELIMITED\";\n }\n});\n\n/**\n * Determines whether this field is packed. Only relevant when repeated.\n * @name Field#packed\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"packed\", {\n get: function() {\n return this._features.repeated_field_encoding === \"PACKED\";\n }\n});\n\n/**\n * Determines whether this field tracks presence.\n * @name Field#hasPresence\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"hasPresence\", {\n get: function() {\n if (this.repeated || this.map) {\n return false;\n }\n return this.partOf || // oneofs\n this.declaringField || this.extensionField || // extensions\n this._features.field_presence !== \"IMPLICIT\";\n }\n});\n\n/**\n * @override\n */\nField.prototype.setOption = function setOption(name, value, ifNotSet) {\n return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet);\n};\n\n/**\n * Field descriptor.\n * @interface IField\n * @property {string} [rule=\"optional\"] Field rule\n * @property {string} type Field type\n * @property {number} id Field id\n * @property {Object.} [options] Field options\n */\n\n/**\n * Extension field descriptor.\n * @interface IExtensionField\n * @extends IField\n * @property {string} extend Extended type\n */\n\n/**\n * Converts this field to a field descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IField} Field descriptor\n */\nField.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"edition\" , this._editionToJSON(),\n \"rule\" , this.rule !== \"optional\" && this.rule || undefined,\n \"type\" , this.type,\n \"id\" , this.id,\n \"extend\" , this.extend,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Resolves this field's type references.\n * @returns {Field} `this`\n * @throws {Error} If any reference cannot be resolved\n */\nField.prototype.resolve = function resolve() {\n\n if (this.resolved)\n return this;\n\n if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it\n this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);\n if (this.resolvedType instanceof Type)\n this.typeDefault = null;\n else // instanceof Enum\n this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined\n } else if (this.options && this.options.proto3_optional) {\n // proto3 scalar value marked optional; should default to null\n this.typeDefault = null;\n }\n\n // use explicitly set default value if present\n if (this.options && this.options[\"default\"] != null) {\n this.typeDefault = this.options[\"default\"];\n if (this.resolvedType instanceof Enum && typeof this.typeDefault === \"string\")\n this.typeDefault = this.resolvedType.values[this.typeDefault];\n }\n\n // remove unnecessary options\n if (this.options) {\n if (this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum))\n delete this.options.packed;\n if (!Object.keys(this.options).length)\n this.options = undefined;\n }\n\n // convert to internal data type if necesssary\n if (this.long) {\n this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === \"u\");\n\n /* istanbul ignore else */\n if (Object.freeze)\n Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it)\n\n } else if (this.bytes && typeof this.typeDefault === \"string\") {\n var buf;\n if (util.base64.test(this.typeDefault))\n util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0);\n else\n util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0);\n this.typeDefault = buf;\n }\n\n // take special care of maps and repeated fields\n if (this.map)\n this.defaultValue = util.emptyObject;\n else if (this.repeated)\n this.defaultValue = util.emptyArray;\n else\n this.defaultValue = this.typeDefault;\n\n // ensure proper value on prototype\n if (this.parent instanceof Type)\n this.parent.ctor.prototype[this.name] = this.defaultValue;\n\n return ReflectionObject.prototype.resolve.call(this);\n};\n\n/**\n * Infers field features from legacy syntax that may have been specified differently.\n * in older editions.\n * @param {string|undefined} edition The edition this proto is on, or undefined if pre-editions\n * @returns {object} The feature values to override\n */\nField.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(edition) {\n if (edition !== \"proto2\" && edition !== \"proto3\") {\n return {};\n }\n\n var features = {};\n\n if (this.rule === \"required\") {\n features.field_presence = \"LEGACY_REQUIRED\";\n }\n if (this.parent && types.defaults[this.type] === undefined) {\n // We can't use resolvedType because types may not have been resolved yet. However,\n // legacy groups are always in the same scope as the field so we don't have to do a\n // full scan of the tree.\n var type = this.parent.get(this.type.split(\".\").pop());\n if (type && type instanceof Type && type.group) {\n features.message_encoding = \"DELIMITED\";\n }\n }\n if (this.getOption(\"packed\") === true) {\n features.repeated_field_encoding = \"PACKED\";\n } else if (this.getOption(\"packed\") === false) {\n features.repeated_field_encoding = \"EXPANDED\";\n }\n return features;\n};\n\n/**\n * @override\n */\nField.prototype._resolveFeatures = function _resolveFeatures(edition) {\n return ReflectionObject.prototype._resolveFeatures.call(this, this._edition || edition);\n};\n\n/**\n * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript).\n * @typedef FieldDecorator\n * @type {function}\n * @param {Object} prototype Target prototype\n * @param {string} fieldName Field name\n * @returns {undefined}\n */\n\n/**\n * Field decorator (TypeScript).\n * @name Field.d\n * @function\n * @param {number} fieldId Field id\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"string\"|\"bool\"|\"bytes\"|Object} fieldType Field type\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\n * @param {T} [defaultValue] Default value\n * @returns {FieldDecorator} Decorator function\n * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[]\n */\nField.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) {\n\n // submessage: decorate the submessage and use its name as the type\n if (typeof fieldType === \"function\")\n fieldType = util.decorateType(fieldType).name;\n\n // enum reference: create a reflected copy of the enum and keep reuseing it\n else if (fieldType && typeof fieldType === \"object\")\n fieldType = util.decorateEnum(fieldType).name;\n\n return function fieldDecorator(prototype, fieldName) {\n util.decorateType(prototype.constructor)\n .add(new Field(fieldName, fieldId, fieldType, fieldRule, { \"default\": defaultValue }));\n };\n};\n\n/**\n * Field decorator (TypeScript).\n * @name Field.d\n * @function\n * @param {number} fieldId Field id\n * @param {Constructor|string} fieldType Field type\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\n * @returns {FieldDecorator} Decorator function\n * @template T extends Message\n * @variation 2\n */\n// like Field.d but without a default value\n\n// Sets up cyclic dependencies (called in index-light)\nField._configure = function configure(Type_) {\n Type = Type_;\n};\n","\"use strict\";\nvar protobuf = module.exports = require(18);\n\nprotobuf.build = \"light\";\n\n/**\n * A node-style callback as used by {@link load} and {@link Root#load}.\n * @typedef LoadCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Root} [root] Root, if there hasn't been an error\n * @returns {undefined}\n */\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} root Root namespace, defaults to create a new one if omitted.\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @see {@link Root#load}\n */\nfunction load(filename, root, callback) {\n if (typeof root === \"function\") {\n callback = root;\n root = new protobuf.Root();\n } else if (!root)\n root = new protobuf.Root();\n return root.load(filename, callback);\n}\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\n * @name load\n * @function\n * @param {string|string[]} filename One or multiple files to load\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @see {@link Root#load}\n * @variation 2\n */\n// function load(filename:string, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise.\n * @name load\n * @function\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\n * @returns {Promise} Promise\n * @see {@link Root#load}\n * @variation 3\n */\n// function load(filename:string, [root:Root]):Promise\n\nprotobuf.load = load;\n\n/**\n * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only).\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\n * @returns {Root} Root namespace\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\n * @see {@link Root#loadSync}\n */\nfunction loadSync(filename, root) {\n if (!root)\n root = new protobuf.Root();\n return root.loadSync(filename);\n}\n\nprotobuf.loadSync = loadSync;\n\n// Serialization\nprotobuf.encoder = require(14);\nprotobuf.decoder = require(13);\nprotobuf.verifier = require(40);\nprotobuf.converter = require(12);\n\n// Reflection\nprotobuf.ReflectionObject = require(24);\nprotobuf.Namespace = require(23);\nprotobuf.Root = require(29);\nprotobuf.Enum = require(15);\nprotobuf.Type = require(35);\nprotobuf.Field = require(16);\nprotobuf.OneOf = require(25);\nprotobuf.MapField = require(20);\nprotobuf.Service = require(33);\nprotobuf.Method = require(22);\n\n// Runtime\nprotobuf.Message = require(21);\nprotobuf.wrappers = require(41);\n\n// Utility\nprotobuf.types = require(36);\nprotobuf.util = require(37);\n\n// Set up possibly cyclic reflection dependencies\nprotobuf.ReflectionObject._configure(protobuf.Root);\nprotobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum);\nprotobuf.Root._configure(protobuf.Type);\nprotobuf.Field._configure(protobuf.Type);\n","\"use strict\";\nvar protobuf = exports;\n\n/**\n * Build type, one of `\"full\"`, `\"light\"` or `\"minimal\"`.\n * @name build\n * @type {string}\n * @const\n */\nprotobuf.build = \"minimal\";\n\n// Serialization\nprotobuf.Writer = require(42);\nprotobuf.BufferWriter = require(43);\nprotobuf.Reader = require(27);\nprotobuf.BufferReader = require(28);\n\n// Utility\nprotobuf.util = require(39);\nprotobuf.rpc = require(31);\nprotobuf.roots = require(30);\nprotobuf.configure = configure;\n\n/* istanbul ignore next */\n/**\n * Reconfigures the library according to the environment.\n * @returns {undefined}\n */\nfunction configure() {\n protobuf.util._configure();\n protobuf.Writer._configure(protobuf.BufferWriter);\n protobuf.Reader._configure(protobuf.BufferReader);\n}\n\n// Set up buffer utility according to the environment\nconfigure();\n","\"use strict\";\nvar protobuf = module.exports = require(17);\n\nprotobuf.build = \"full\";\n\n// Parser\nprotobuf.tokenize = require(34);\nprotobuf.parse = require(26);\nprotobuf.common = require(11);\n\n// Configure parser\nprotobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common);\n","\"use strict\";\nmodule.exports = MapField;\n\n// extends Field\nvar Field = require(16);\n((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = \"MapField\";\n\nvar types = require(36),\n util = require(37);\n\n/**\n * Constructs a new map field instance.\n * @classdesc Reflected map field.\n * @extends FieldBase\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} keyType Key type\n * @param {string} type Value type\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction MapField(name, id, keyType, type, options, comment) {\n Field.call(this, name, id, type, undefined, undefined, options, comment);\n\n /* istanbul ignore if */\n if (!util.isString(keyType))\n throw TypeError(\"keyType must be a string\");\n\n /**\n * Key type.\n * @type {string}\n */\n this.keyType = keyType; // toJSON, marker\n\n /**\n * Resolved key type if not a basic type.\n * @type {ReflectionObject|null}\n */\n this.resolvedKeyType = null;\n\n // Overrides Field#map\n this.map = true;\n}\n\n/**\n * Map field descriptor.\n * @interface IMapField\n * @extends {IField}\n * @property {string} keyType Key type\n */\n\n/**\n * Extension map field descriptor.\n * @interface IExtensionMapField\n * @extends IMapField\n * @property {string} extend Extended type\n */\n\n/**\n * Constructs a map field from a map field descriptor.\n * @param {string} name Field name\n * @param {IMapField} json Map field descriptor\n * @returns {MapField} Created map field\n * @throws {TypeError} If arguments are invalid\n */\nMapField.fromJSON = function fromJSON(name, json) {\n return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment);\n};\n\n/**\n * Converts this map field to a map field descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IMapField} Map field descriptor\n */\nMapField.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"keyType\" , this.keyType,\n \"type\" , this.type,\n \"id\" , this.id,\n \"extend\" , this.extend,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nMapField.prototype.resolve = function resolve() {\n if (this.resolved)\n return this;\n\n // Besides a value type, map fields have a key type that may be \"any scalar type except for floating point types and bytes\"\n if (types.mapKey[this.keyType] === undefined)\n throw Error(\"invalid key type: \" + this.keyType);\n\n return Field.prototype.resolve.call(this);\n};\n\n/**\n * Map field decorator (TypeScript).\n * @name MapField.d\n * @function\n * @param {number} fieldId Field id\n * @param {\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"} fieldKeyType Field key type\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"|\"bytes\"|Object|Constructor<{}>} fieldValueType Field value type\n * @returns {FieldDecorator} Decorator function\n * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> }\n */\nMapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) {\n\n // submessage value: decorate the submessage and use its name as the type\n if (typeof fieldValueType === \"function\")\n fieldValueType = util.decorateType(fieldValueType).name;\n\n // enum reference value: create a reflected copy of the enum and keep reuseing it\n else if (fieldValueType && typeof fieldValueType === \"object\")\n fieldValueType = util.decorateEnum(fieldValueType).name;\n\n return function mapFieldDecorator(prototype, fieldName) {\n util.decorateType(prototype.constructor)\n .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType));\n };\n};\n","\"use strict\";\nmodule.exports = Message;\n\nvar util = require(39);\n\n/**\n * Constructs a new message instance.\n * @classdesc Abstract runtime message.\n * @constructor\n * @param {Properties} [properties] Properties to set\n * @template T extends object = object\n */\nfunction Message(properties) {\n // not used internally\n if (properties)\n for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)\n this[keys[i]] = properties[keys[i]];\n}\n\n/**\n * Reference to the reflected type.\n * @name Message.$type\n * @type {Type}\n * @readonly\n */\n\n/**\n * Reference to the reflected type.\n * @name Message#$type\n * @type {Type}\n * @readonly\n */\n\n/*eslint-disable valid-jsdoc*/\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message} Message instance\n * @template T extends Message\n * @this Constructor\n */\nMessage.create = function create(properties) {\n return this.$type.create(properties);\n};\n\n/**\n * Encodes a message of this type.\n * @param {T|Object.} message Message to encode\n * @param {Writer} [writer] Writer to use\n * @returns {Writer} Writer\n * @template T extends Message\n * @this Constructor\n */\nMessage.encode = function encode(message, writer) {\n return this.$type.encode(message, writer);\n};\n\n/**\n * Encodes a message of this type preceeded by its length as a varint.\n * @param {T|Object.} message Message to encode\n * @param {Writer} [writer] Writer to use\n * @returns {Writer} Writer\n * @template T extends Message\n * @this Constructor\n */\nMessage.encodeDelimited = function encodeDelimited(message, writer) {\n return this.$type.encodeDelimited(message, writer);\n};\n\n/**\n * Decodes a message of this type.\n * @name Message.decode\n * @function\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\n * @returns {T} Decoded message\n * @template T extends Message\n * @this Constructor\n */\nMessage.decode = function decode(reader) {\n return this.$type.decode(reader);\n};\n\n/**\n * Decodes a message of this type preceeded by its length as a varint.\n * @name Message.decodeDelimited\n * @function\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\n * @returns {T} Decoded message\n * @template T extends Message\n * @this Constructor\n */\nMessage.decodeDelimited = function decodeDelimited(reader) {\n return this.$type.decodeDelimited(reader);\n};\n\n/**\n * Verifies a message of this type.\n * @name Message.verify\n * @function\n * @param {Object.} message Plain object to verify\n * @returns {string|null} `null` if valid, otherwise the reason why it is not\n */\nMessage.verify = function verify(message) {\n return this.$type.verify(message);\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object\n * @returns {T} Message instance\n * @template T extends Message\n * @this Constructor\n */\nMessage.fromObject = function fromObject(object) {\n return this.$type.fromObject(object);\n};\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {T} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n * @template T extends Message\n * @this Constructor\n */\nMessage.toObject = function toObject(message, options) {\n return this.$type.toObject(message, options);\n};\n\n/**\n * Converts this message to JSON.\n * @returns {Object.} JSON object\n */\nMessage.prototype.toJSON = function toJSON() {\n return this.$type.toObject(this, util.toJSONOptions);\n};\n\n/*eslint-enable valid-jsdoc*/","\"use strict\";\nmodule.exports = Method;\n\n// extends ReflectionObject\nvar ReflectionObject = require(24);\n((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = \"Method\";\n\nvar util = require(37);\n\n/**\n * Constructs a new service method instance.\n * @classdesc Reflected service method.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Method name\n * @param {string|undefined} type Method type, usually `\"rpc\"`\n * @param {string} requestType Request message type\n * @param {string} responseType Response message type\n * @param {boolean|Object.} [requestStream] Whether the request is streamed\n * @param {boolean|Object.} [responseStream] Whether the response is streamed\n * @param {Object.} [options] Declared options\n * @param {string} [comment] The comment for this method\n * @param {Object.} [parsedOptions] Declared options, properly parsed into an object\n */\nfunction Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) {\n\n /* istanbul ignore next */\n if (util.isObject(requestStream)) {\n options = requestStream;\n requestStream = responseStream = undefined;\n } else if (util.isObject(responseStream)) {\n options = responseStream;\n responseStream = undefined;\n }\n\n /* istanbul ignore if */\n if (!(type === undefined || util.isString(type)))\n throw TypeError(\"type must be a string\");\n\n /* istanbul ignore if */\n if (!util.isString(requestType))\n throw TypeError(\"requestType must be a string\");\n\n /* istanbul ignore if */\n if (!util.isString(responseType))\n throw TypeError(\"responseType must be a string\");\n\n ReflectionObject.call(this, name, options);\n\n /**\n * Method type.\n * @type {string}\n */\n this.type = type || \"rpc\"; // toJSON\n\n /**\n * Request type.\n * @type {string}\n */\n this.requestType = requestType; // toJSON, marker\n\n /**\n * Whether requests are streamed or not.\n * @type {boolean|undefined}\n */\n this.requestStream = requestStream ? true : undefined; // toJSON\n\n /**\n * Response type.\n * @type {string}\n */\n this.responseType = responseType; // toJSON\n\n /**\n * Whether responses are streamed or not.\n * @type {boolean|undefined}\n */\n this.responseStream = responseStream ? true : undefined; // toJSON\n\n /**\n * Resolved request type.\n * @type {Type|null}\n */\n this.resolvedRequestType = null;\n\n /**\n * Resolved response type.\n * @type {Type|null}\n */\n this.resolvedResponseType = null;\n\n /**\n * Comment for this method\n * @type {string|null}\n */\n this.comment = comment;\n\n /**\n * Options properly parsed into an object\n */\n this.parsedOptions = parsedOptions;\n}\n\n/**\n * Method descriptor.\n * @interface IMethod\n * @property {string} [type=\"rpc\"] Method type\n * @property {string} requestType Request type\n * @property {string} responseType Response type\n * @property {boolean} [requestStream=false] Whether requests are streamed\n * @property {boolean} [responseStream=false] Whether responses are streamed\n * @property {Object.} [options] Method options\n * @property {string} comment Method comments\n * @property {Object.} [parsedOptions] Method options properly parsed into an object\n */\n\n/**\n * Constructs a method from a method descriptor.\n * @param {string} name Method name\n * @param {IMethod} json Method descriptor\n * @returns {Method} Created method\n * @throws {TypeError} If arguments are invalid\n */\nMethod.fromJSON = function fromJSON(name, json) {\n return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions);\n};\n\n/**\n * Converts this method to a method descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IMethod} Method descriptor\n */\nMethod.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"type\" , this.type !== \"rpc\" && /* istanbul ignore next */ this.type || undefined,\n \"requestType\" , this.requestType,\n \"requestStream\" , this.requestStream,\n \"responseType\" , this.responseType,\n \"responseStream\" , this.responseStream,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined,\n \"parsedOptions\" , this.parsedOptions,\n ]);\n};\n\n/**\n * @override\n */\nMethod.prototype.resolve = function resolve() {\n\n /* istanbul ignore if */\n if (this.resolved)\n return this;\n\n this.resolvedRequestType = this.parent.lookupType(this.requestType);\n this.resolvedResponseType = this.parent.lookupType(this.responseType);\n\n return ReflectionObject.prototype.resolve.call(this);\n};\n","\"use strict\";\nmodule.exports = Namespace;\n\n// extends ReflectionObject\nvar ReflectionObject = require(24);\n((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = \"Namespace\";\n\nvar Field = require(16),\n util = require(37),\n OneOf = require(25);\n\nvar Type, // cyclic\n Service,\n Enum;\n\n/**\n * Constructs a new namespace instance.\n * @name Namespace\n * @classdesc Reflected namespace.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Namespace name\n * @param {Object.} [options] Declared options\n */\n\n/**\n * Constructs a namespace from JSON.\n * @memberof Namespace\n * @function\n * @param {string} name Namespace name\n * @param {Object.} json JSON object\n * @returns {Namespace} Created namespace\n * @throws {TypeError} If arguments are invalid\n */\nNamespace.fromJSON = function fromJSON(name, json) {\n return new Namespace(name, json.options).addJSON(json.nested);\n};\n\n/**\n * Converts an array of reflection objects to JSON.\n * @memberof Namespace\n * @param {ReflectionObject[]} array Object array\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {Object.|undefined} JSON object or `undefined` when array is empty\n */\nfunction arrayToJSON(array, toJSONOptions) {\n if (!(array && array.length))\n return undefined;\n var obj = {};\n for (var i = 0; i < array.length; ++i)\n obj[array[i].name] = array[i].toJSON(toJSONOptions);\n return obj;\n}\n\nNamespace.arrayToJSON = arrayToJSON;\n\n/**\n * Tests if the specified id is reserved.\n * @param {Array.|undefined} reserved Array of reserved ranges and names\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nNamespace.isReservedId = function isReservedId(reserved, id) {\n if (reserved)\n for (var i = 0; i < reserved.length; ++i)\n if (typeof reserved[i] !== \"string\" && reserved[i][0] <= id && reserved[i][1] > id)\n return true;\n return false;\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {Array.|undefined} reserved Array of reserved ranges and names\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nNamespace.isReservedName = function isReservedName(reserved, name) {\n if (reserved)\n for (var i = 0; i < reserved.length; ++i)\n if (reserved[i] === name)\n return true;\n return false;\n};\n\n/**\n * Not an actual constructor. Use {@link Namespace} instead.\n * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions.\n * @exports NamespaceBase\n * @extends ReflectionObject\n * @abstract\n * @constructor\n * @param {string} name Namespace name\n * @param {Object.} [options] Declared options\n * @see {@link Namespace}\n */\nfunction Namespace(name, options) {\n ReflectionObject.call(this, name, options);\n\n /**\n * Nested objects by name.\n * @type {Object.|undefined}\n */\n this.nested = undefined; // toJSON\n\n /**\n * Cached nested objects as an array.\n * @type {ReflectionObject[]|null}\n * @private\n */\n this._nestedArray = null;\n\n /**\n * Cache lookup calls for any objects contains anywhere under this namespace.\n * This drastically speeds up resolve for large cross-linked protos where the same\n * types are looked up repeatedly.\n * @type {Object.}\n * @private\n */\n this._lookupCache = {};\n\n /**\n * Whether or not objects contained in this namespace need feature resolution.\n * @type {boolean}\n * @protected\n */\n this._needsRecursiveFeatureResolution = true;\n\n /**\n * Whether or not objects contained in this namespace need a resolve.\n * @type {boolean}\n * @protected\n */\n this._needsRecursiveResolve = true;\n}\n\nfunction clearCache(namespace) {\n namespace._nestedArray = null;\n namespace._lookupCache = {};\n\n // Also clear parent caches, since they include nested lookups.\n var parent = namespace;\n while(parent = parent.parent) {\n parent._lookupCache = {};\n }\n return namespace;\n}\n\n/**\n * Nested objects of this namespace as an array for iteration.\n * @name NamespaceBase#nestedArray\n * @type {ReflectionObject[]}\n * @readonly\n */\nObject.defineProperty(Namespace.prototype, \"nestedArray\", {\n get: function() {\n return this._nestedArray || (this._nestedArray = util.toArray(this.nested));\n }\n});\n\n/**\n * Namespace descriptor.\n * @interface INamespace\n * @property {Object.} [options] Namespace options\n * @property {Object.} [nested] Nested object descriptors\n */\n\n/**\n * Any extension field descriptor.\n * @typedef AnyExtensionField\n * @type {IExtensionField|IExtensionMapField}\n */\n\n/**\n * Any nested object descriptor.\n * @typedef AnyNestedObject\n * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf}\n */\n\n/**\n * Converts this namespace to a namespace descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {INamespace} Namespace descriptor\n */\nNamespace.prototype.toJSON = function toJSON(toJSONOptions) {\n return util.toObject([\n \"options\" , this.options,\n \"nested\" , arrayToJSON(this.nestedArray, toJSONOptions)\n ]);\n};\n\n/**\n * Adds nested objects to this namespace from nested object descriptors.\n * @param {Object.} nestedJson Any nested object descriptors\n * @returns {Namespace} `this`\n */\nNamespace.prototype.addJSON = function addJSON(nestedJson) {\n var ns = this;\n /* istanbul ignore else */\n if (nestedJson) {\n for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) {\n nested = nestedJson[names[i]];\n ns.add( // most to least likely\n ( nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : nested.id !== undefined\n ? Field.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n }\n return this;\n};\n\n/**\n * Gets the nested object of the specified name.\n * @param {string} name Nested object name\n * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist\n */\nNamespace.prototype.get = function get(name) {\n return this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Gets the values of the nested {@link Enum|enum} of the specified name.\n * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`.\n * @param {string} name Nested enum name\n * @returns {Object.} Enum values\n * @throws {Error} If there is no such enum\n */\nNamespace.prototype.getEnum = function getEnum(name) {\n if (this.nested && this.nested[name] instanceof Enum)\n return this.nested[name].values;\n throw Error(\"no such enum: \" + name);\n};\n\n/**\n * Adds a nested object to this namespace.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Namespace} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name\n */\nNamespace.prototype.add = function add(object) {\n\n if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace))\n throw TypeError(\"object must be a valid nested object\");\n\n if (!this.nested)\n this.nested = {};\n else {\n var prev = this.get(object.name);\n if (prev) {\n if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) {\n // replace plain namespace but keep existing nested elements and options\n var nested = prev.nestedArray;\n for (var i = 0; i < nested.length; ++i)\n object.add(nested[i]);\n this.remove(prev);\n if (!this.nested)\n this.nested = {};\n object.setOptions(prev.options, true);\n\n } else\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n }\n }\n this.nested[object.name] = object;\n\n if (!(this instanceof Type || this instanceof Service || this instanceof Enum || this instanceof Field)) {\n // This is a package or a root namespace.\n if (!object._edition) {\n // Make sure that some edition is set if it hasn't already been specified.\n object._edition = object._defaultEdition;\n }\n }\n\n this._needsRecursiveFeatureResolution = true;\n this._needsRecursiveResolve = true;\n\n // Also clear parent caches, since they need to recurse down.\n var parent = this;\n while(parent = parent.parent) {\n parent._needsRecursiveFeatureResolution = true;\n parent._needsRecursiveResolve = true;\n }\n\n object.onAdd(this);\n return clearCache(this);\n};\n\n/**\n * Removes a nested object from this namespace.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Namespace} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this namespace\n */\nNamespace.prototype.remove = function remove(object) {\n\n if (!(object instanceof ReflectionObject))\n throw TypeError(\"object must be a ReflectionObject\");\n if (object.parent !== this)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.nested[object.name];\n if (!Object.keys(this.nested).length)\n this.nested = undefined;\n\n object.onRemove(this);\n return clearCache(this);\n};\n\n/**\n * Defines additial namespaces within this one if not yet existing.\n * @param {string|string[]} path Path to create\n * @param {*} [json] Nested types to create from JSON\n * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty\n */\nNamespace.prototype.define = function define(path, json) {\n\n if (util.isString(path))\n path = path.split(\".\");\n else if (!Array.isArray(path))\n throw TypeError(\"illegal path\");\n if (path && path.length && path[0] === \"\")\n throw Error(\"path must be relative\");\n\n var ptr = this;\n while (path.length > 0) {\n var part = path.shift();\n if (ptr.nested && ptr.nested[part]) {\n ptr = ptr.nested[part];\n if (!(ptr instanceof Namespace))\n throw Error(\"path conflicts with non-namespace objects\");\n } else\n ptr.add(ptr = new Namespace(part));\n }\n if (json)\n ptr.addJSON(json);\n return ptr;\n};\n\n/**\n * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost.\n * @returns {Namespace} `this`\n */\nNamespace.prototype.resolveAll = function resolveAll() {\n if (!this._needsRecursiveResolve) return this;\n\n this._resolveFeaturesRecursive(this._edition);\n\n var nested = this.nestedArray, i = 0;\n this.resolve();\n while (i < nested.length)\n if (nested[i] instanceof Namespace)\n nested[i++].resolveAll();\n else\n nested[i++].resolve();\n this._needsRecursiveResolve = false;\n return this;\n};\n\n/**\n * @override\n */\nNamespace.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) {\n if (!this._needsRecursiveFeatureResolution) return this;\n this._needsRecursiveFeatureResolution = false;\n\n edition = this._edition || edition;\n\n ReflectionObject.prototype._resolveFeaturesRecursive.call(this, edition);\n this.nestedArray.forEach(nested => {\n nested._resolveFeaturesRecursive(edition);\n });\n return this;\n};\n\n/**\n * Recursively looks up the reflection object matching the specified path in the scope of this namespace.\n * @param {string|string[]} path Path to look up\n * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc.\n * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n */\nNamespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) {\n /* istanbul ignore next */\n if (typeof filterTypes === \"boolean\") {\n parentAlreadyChecked = filterTypes;\n filterTypes = undefined;\n } else if (filterTypes && !Array.isArray(filterTypes))\n filterTypes = [ filterTypes ];\n\n if (util.isString(path) && path.length) {\n if (path === \".\")\n return this.root;\n path = path.split(\".\");\n } else if (!path.length)\n return this;\n\n var flatPath = path.join(\".\");\n\n // Start at root if path is absolute\n if (path[0] === \"\")\n return this.root.lookup(path.slice(1), filterTypes);\n\n // Early bailout for objects with matching absolute paths\n var found = this.root._fullyQualifiedObjects && this.root._fullyQualifiedObjects[\".\" + flatPath];\n if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {\n return found;\n }\n\n // Do a regular lookup at this namespace and below\n found = this._lookupImpl(path, flatPath);\n if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {\n return found;\n }\n\n if (parentAlreadyChecked)\n return null;\n\n // If there hasn't been a match, walk up the tree and look more broadly\n var current = this;\n while (current.parent) {\n found = current.parent._lookupImpl(path, flatPath);\n if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {\n return found;\n }\n current = current.parent;\n }\n return null;\n};\n\n/**\n * Internal helper for lookup that handles searching just at this namespace and below along with caching.\n * @param {string[]} path Path to look up\n * @param {string} flatPath Flattened version of the path to use as a cache key\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n * @private\n */\nNamespace.prototype._lookupImpl = function lookup(path, flatPath) {\n if(Object.prototype.hasOwnProperty.call(this._lookupCache, flatPath)) {\n return this._lookupCache[flatPath];\n }\n\n // Test if the first part matches any nested object, and if so, traverse if path contains more\n var found = this.get(path[0]);\n var exact = null;\n if (found) {\n if (path.length === 1) {\n exact = found;\n } else if (found instanceof Namespace) {\n path = path.slice(1);\n exact = found._lookupImpl(path, path.join(\".\"));\n }\n\n // Otherwise try each nested namespace\n } else {\n for (var i = 0; i < this.nestedArray.length; ++i)\n if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i]._lookupImpl(path, flatPath)))\n exact = found;\n }\n\n // Set this even when null, so that when we walk up the tree we can quickly bail on repeated checks back down.\n this._lookupCache[flatPath] = exact;\n return exact;\n};\n\n/**\n * Looks up the reflection object at the specified path, relative to this namespace.\n * @name NamespaceBase#lookup\n * @function\n * @param {string|string[]} path Path to look up\n * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n * @variation 2\n */\n// lookup(path: string, [parentAlreadyChecked: boolean])\n\n/**\n * Looks up the {@link Type|type} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Type} Looked up type\n * @throws {Error} If `path` does not point to a type\n */\nNamespace.prototype.lookupType = function lookupType(path) {\n var found = this.lookup(path, [ Type ]);\n if (!found)\n throw Error(\"no such type: \" + path);\n return found;\n};\n\n/**\n * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Enum} Looked up enum\n * @throws {Error} If `path` does not point to an enum\n */\nNamespace.prototype.lookupEnum = function lookupEnum(path) {\n var found = this.lookup(path, [ Enum ]);\n if (!found)\n throw Error(\"no such Enum '\" + path + \"' in \" + this);\n return found;\n};\n\n/**\n * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Type} Looked up type or enum\n * @throws {Error} If `path` does not point to a type or enum\n */\nNamespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) {\n var found = this.lookup(path, [ Type, Enum ]);\n if (!found)\n throw Error(\"no such Type or Enum '\" + path + \"' in \" + this);\n return found;\n};\n\n/**\n * Looks up the {@link Service|service} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Service} Looked up service\n * @throws {Error} If `path` does not point to a service\n */\nNamespace.prototype.lookupService = function lookupService(path) {\n var found = this.lookup(path, [ Service ]);\n if (!found)\n throw Error(\"no such Service '\" + path + \"' in \" + this);\n return found;\n};\n\n// Sets up cyclic dependencies (called in index-light)\nNamespace._configure = function(Type_, Service_, Enum_) {\n Type = Type_;\n Service = Service_;\n Enum = Enum_;\n};\n","\"use strict\";\nmodule.exports = ReflectionObject;\n\nReflectionObject.className = \"ReflectionObject\";\n\nconst OneOf = require(25);\nvar util = require(37);\n\nvar Root; // cyclic\n\n/* eslint-disable no-warning-comments */\n// TODO: Replace with embedded proto.\nvar editions2023Defaults = {enum_type: \"OPEN\", field_presence: \"EXPLICIT\", json_format: \"ALLOW\", message_encoding: \"LENGTH_PREFIXED\", repeated_field_encoding: \"PACKED\", utf8_validation: \"VERIFY\"};\nvar proto2Defaults = {enum_type: \"CLOSED\", field_presence: \"EXPLICIT\", json_format: \"LEGACY_BEST_EFFORT\", message_encoding: \"LENGTH_PREFIXED\", repeated_field_encoding: \"EXPANDED\", utf8_validation: \"NONE\"};\nvar proto3Defaults = {enum_type: \"OPEN\", field_presence: \"IMPLICIT\", json_format: \"ALLOW\", message_encoding: \"LENGTH_PREFIXED\", repeated_field_encoding: \"PACKED\", utf8_validation: \"VERIFY\"};\n\n/**\n * Constructs a new reflection object instance.\n * @classdesc Base class of all reflection objects.\n * @constructor\n * @param {string} name Object name\n * @param {Object.} [options] Declared options\n * @abstract\n */\nfunction ReflectionObject(name, options) {\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n if (options && !util.isObject(options))\n throw TypeError(\"options must be an object\");\n\n /**\n * Options.\n * @type {Object.|undefined}\n */\n this.options = options; // toJSON\n\n /**\n * Parsed Options.\n * @type {Array.>|undefined}\n */\n this.parsedOptions = null;\n\n /**\n * Unique name within its namespace.\n * @type {string}\n */\n this.name = name;\n\n /**\n * The edition specified for this object. Only relevant for top-level objects.\n * @type {string}\n * @private\n */\n this._edition = null;\n\n /**\n * The default edition to use for this object if none is specified. For legacy reasons,\n * this is proto2 except in the JSON parsing case where it was proto3.\n * @type {string}\n * @private\n */\n this._defaultEdition = \"proto2\";\n\n /**\n * Resolved Features.\n * @type {object}\n * @private\n */\n this._features = {};\n\n /**\n * Whether or not features have been resolved.\n * @type {boolean}\n * @private\n */\n this._featuresResolved = false;\n\n /**\n * Parent namespace.\n * @type {Namespace|null}\n */\n this.parent = null;\n\n /**\n * Whether already resolved or not.\n * @type {boolean}\n */\n this.resolved = false;\n\n /**\n * Comment text, if any.\n * @type {string|null}\n */\n this.comment = null;\n\n /**\n * Defining file name.\n * @type {string|null}\n */\n this.filename = null;\n}\n\nObject.defineProperties(ReflectionObject.prototype, {\n\n /**\n * Reference to the root namespace.\n * @name ReflectionObject#root\n * @type {Root}\n * @readonly\n */\n root: {\n get: function() {\n var ptr = this;\n while (ptr.parent !== null)\n ptr = ptr.parent;\n return ptr;\n }\n },\n\n /**\n * Full name including leading dot.\n * @name ReflectionObject#fullName\n * @type {string}\n * @readonly\n */\n fullName: {\n get: function() {\n var path = [ this.name ],\n ptr = this.parent;\n while (ptr) {\n path.unshift(ptr.name);\n ptr = ptr.parent;\n }\n return path.join(\".\");\n }\n }\n});\n\n/**\n * Converts this reflection object to its descriptor representation.\n * @returns {Object.} Descriptor\n * @abstract\n */\nReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() {\n throw Error(); // not implemented, shouldn't happen\n};\n\n/**\n * Called when this object is added to a parent.\n * @param {ReflectionObject} parent Parent added to\n * @returns {undefined}\n */\nReflectionObject.prototype.onAdd = function onAdd(parent) {\n if (this.parent && this.parent !== parent)\n this.parent.remove(this);\n this.parent = parent;\n this.resolved = false;\n var root = parent.root;\n if (root instanceof Root)\n root._handleAdd(this);\n};\n\n/**\n * Called when this object is removed from a parent.\n * @param {ReflectionObject} parent Parent removed from\n * @returns {undefined}\n */\nReflectionObject.prototype.onRemove = function onRemove(parent) {\n var root = parent.root;\n if (root instanceof Root)\n root._handleRemove(this);\n this.parent = null;\n this.resolved = false;\n};\n\n/**\n * Resolves this objects type references.\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.resolve = function resolve() {\n if (this.resolved)\n return this;\n if (this.root instanceof Root)\n this.resolved = true; // only if part of a root\n return this;\n};\n\n/**\n * Resolves this objects editions features.\n * @param {string} edition The edition we're currently resolving for.\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) {\n return this._resolveFeatures(this._edition || edition);\n};\n\n/**\n * Resolves child features from parent features\n * @param {string} edition The edition we're currently resolving for.\n * @returns {undefined}\n */\nReflectionObject.prototype._resolveFeatures = function _resolveFeatures(edition) {\n if (this._featuresResolved) {\n return;\n }\n\n var defaults = {};\n\n /* istanbul ignore if */\n if (!edition) {\n throw new Error(\"Unknown edition for \" + this.fullName);\n }\n\n var protoFeatures = Object.assign(this.options ? Object.assign({}, this.options.features) : {},\n this._inferLegacyProtoFeatures(edition));\n\n if (this._edition) {\n // For a namespace marked with a specific edition, reset defaults.\n /* istanbul ignore else */\n if (edition === \"proto2\") {\n defaults = Object.assign({}, proto2Defaults);\n } else if (edition === \"proto3\") {\n defaults = Object.assign({}, proto3Defaults);\n } else if (edition === \"2023\") {\n defaults = Object.assign({}, editions2023Defaults);\n } else {\n throw new Error(\"Unknown edition: \" + edition);\n }\n this._features = Object.assign(defaults, protoFeatures || {});\n this._featuresResolved = true;\n return;\n }\n\n // fields in Oneofs aren't actually children of them, so we have to\n // special-case it\n /* istanbul ignore else */\n if (this.partOf instanceof OneOf) {\n var lexicalParentFeaturesCopy = Object.assign({}, this.partOf._features);\n this._features = Object.assign(lexicalParentFeaturesCopy, protoFeatures || {});\n } else if (this.declaringField) {\n // Skip feature resolution of sister fields.\n } else if (this.parent) {\n var parentFeaturesCopy = Object.assign({}, this.parent._features);\n this._features = Object.assign(parentFeaturesCopy, protoFeatures || {});\n } else {\n throw new Error(\"Unable to find a parent for \" + this.fullName);\n }\n if (this.extensionField) {\n // Sister fields should have the same features as their extensions.\n this.extensionField._features = this._features;\n }\n this._featuresResolved = true;\n};\n\n/**\n * Infers features from legacy syntax that may have been specified differently.\n * in older editions.\n * @param {string|undefined} edition The edition this proto is on, or undefined if pre-editions\n * @returns {object} The feature values to override\n */\nReflectionObject.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(/*edition*/) {\n return {};\n};\n\n/**\n * Gets an option value.\n * @param {string} name Option name\n * @returns {*} Option value or `undefined` if not set\n */\nReflectionObject.prototype.getOption = function getOption(name) {\n if (this.options)\n return this.options[name];\n return undefined;\n};\n\n/**\n * Sets an option.\n * @param {string} name Option name\n * @param {*} value Option value\n * @param {boolean|undefined} [ifNotSet] Sets the option only if it isn't currently set\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) {\n if (!this.options)\n this.options = {};\n if (/^features\\./.test(name)) {\n util.setProperty(this.options, name, value, ifNotSet);\n } else if (!ifNotSet || this.options[name] === undefined) {\n if (this.getOption(name) !== value) this.resolved = false;\n this.options[name] = value;\n }\n\n return this;\n};\n\n/**\n * Sets a parsed option.\n * @param {string} name parsed Option name\n * @param {*} value Option value\n * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\\empty, will add a new option with that value\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) {\n if (!this.parsedOptions) {\n this.parsedOptions = [];\n }\n var parsedOptions = this.parsedOptions;\n if (propName) {\n // If setting a sub property of an option then try to merge it\n // with an existing option\n var opt = parsedOptions.find(function (opt) {\n return Object.prototype.hasOwnProperty.call(opt, name);\n });\n if (opt) {\n // If we found an existing option - just merge the property value\n // (If it's a feature, will just write over)\n var newValue = opt[name];\n util.setProperty(newValue, propName, value);\n } else {\n // otherwise, create a new option, set its property and add it to the list\n opt = {};\n opt[name] = util.setProperty({}, propName, value);\n parsedOptions.push(opt);\n }\n } else {\n // Always create a new option when setting the value of the option itself\n var newOpt = {};\n newOpt[name] = value;\n parsedOptions.push(newOpt);\n }\n\n return this;\n};\n\n/**\n * Sets multiple options.\n * @param {Object.} options Options to set\n * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) {\n if (options)\n for (var keys = Object.keys(options), i = 0; i < keys.length; ++i)\n this.setOption(keys[i], options[keys[i]], ifNotSet);\n return this;\n};\n\n/**\n * Converts this instance to its string representation.\n * @returns {string} Class name[, space, full name]\n */\nReflectionObject.prototype.toString = function toString() {\n var className = this.constructor.className,\n fullName = this.fullName;\n if (fullName.length)\n return className + \" \" + fullName;\n return className;\n};\n\n/**\n * Converts the edition this object is pinned to for JSON format.\n * @returns {string|undefined} The edition string for JSON representation\n */\nReflectionObject.prototype._editionToJSON = function _editionToJSON() {\n if (!this._edition || this._edition === \"proto3\") {\n // Avoid emitting proto3 since we need to default to it for backwards\n // compatibility anyway.\n return undefined;\n }\n return this._edition;\n};\n\n// Sets up cyclic dependencies (called in index-light)\nReflectionObject._configure = function(Root_) {\n Root = Root_;\n};\n","\"use strict\";\nmodule.exports = OneOf;\n\n// extends ReflectionObject\nvar ReflectionObject = require(24);\n((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = \"OneOf\";\n\nvar Field = require(16),\n util = require(37);\n\n/**\n * Constructs a new oneof instance.\n * @classdesc Reflected oneof.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Oneof name\n * @param {string[]|Object.} [fieldNames] Field names\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction OneOf(name, fieldNames, options, comment) {\n if (!Array.isArray(fieldNames)) {\n options = fieldNames;\n fieldNames = undefined;\n }\n ReflectionObject.call(this, name, options);\n\n /* istanbul ignore if */\n if (!(fieldNames === undefined || Array.isArray(fieldNames)))\n throw TypeError(\"fieldNames must be an Array\");\n\n /**\n * Field names that belong to this oneof.\n * @type {string[]}\n */\n this.oneof = fieldNames || []; // toJSON, marker\n\n /**\n * Fields that belong to this oneof as an array for iteration.\n * @type {Field[]}\n * @readonly\n */\n this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent\n\n /**\n * Comment for this field.\n * @type {string|null}\n */\n this.comment = comment;\n}\n\n/**\n * Oneof descriptor.\n * @interface IOneOf\n * @property {Array.} oneof Oneof field names\n * @property {Object.} [options] Oneof options\n */\n\n/**\n * Constructs a oneof from a oneof descriptor.\n * @param {string} name Oneof name\n * @param {IOneOf} json Oneof descriptor\n * @returns {OneOf} Created oneof\n * @throws {TypeError} If arguments are invalid\n */\nOneOf.fromJSON = function fromJSON(name, json) {\n return new OneOf(name, json.oneof, json.options, json.comment);\n};\n\n/**\n * Converts this oneof to a oneof descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IOneOf} Oneof descriptor\n */\nOneOf.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , this.options,\n \"oneof\" , this.oneof,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Adds the fields of the specified oneof to the parent if not already done so.\n * @param {OneOf} oneof The oneof\n * @returns {undefined}\n * @inner\n * @ignore\n */\nfunction addFieldsToParent(oneof) {\n if (oneof.parent)\n for (var i = 0; i < oneof.fieldsArray.length; ++i)\n if (!oneof.fieldsArray[i].parent)\n oneof.parent.add(oneof.fieldsArray[i]);\n}\n\n/**\n * Adds a field to this oneof and removes it from its current parent, if any.\n * @param {Field} field Field to add\n * @returns {OneOf} `this`\n */\nOneOf.prototype.add = function add(field) {\n\n /* istanbul ignore if */\n if (!(field instanceof Field))\n throw TypeError(\"field must be a Field\");\n\n if (field.parent && field.parent !== this.parent)\n field.parent.remove(field);\n this.oneof.push(field.name);\n this.fieldsArray.push(field);\n field.partOf = this; // field.parent remains null\n addFieldsToParent(this);\n return this;\n};\n\n/**\n * Removes a field from this oneof and puts it back to the oneof's parent.\n * @param {Field} field Field to remove\n * @returns {OneOf} `this`\n */\nOneOf.prototype.remove = function remove(field) {\n\n /* istanbul ignore if */\n if (!(field instanceof Field))\n throw TypeError(\"field must be a Field\");\n\n var index = this.fieldsArray.indexOf(field);\n\n /* istanbul ignore if */\n if (index < 0)\n throw Error(field + \" is not a member of \" + this);\n\n this.fieldsArray.splice(index, 1);\n index = this.oneof.indexOf(field.name);\n\n /* istanbul ignore else */\n if (index > -1) // theoretical\n this.oneof.splice(index, 1);\n\n field.partOf = null;\n return this;\n};\n\n/**\n * @override\n */\nOneOf.prototype.onAdd = function onAdd(parent) {\n ReflectionObject.prototype.onAdd.call(this, parent);\n var self = this;\n // Collect present fields\n for (var i = 0; i < this.oneof.length; ++i) {\n var field = parent.get(this.oneof[i]);\n if (field && !field.partOf) {\n field.partOf = self;\n self.fieldsArray.push(field);\n }\n }\n // Add not yet present fields\n addFieldsToParent(this);\n};\n\n/**\n * @override\n */\nOneOf.prototype.onRemove = function onRemove(parent) {\n for (var i = 0, field; i < this.fieldsArray.length; ++i)\n if ((field = this.fieldsArray[i]).parent)\n field.parent.remove(field);\n ReflectionObject.prototype.onRemove.call(this, parent);\n};\n\n/**\n * Determines whether this field corresponds to a synthetic oneof created for\n * a proto3 optional field. No behavioral logic should depend on this, but it\n * can be relevant for reflection.\n * @name OneOf#isProto3Optional\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(OneOf.prototype, \"isProto3Optional\", {\n get: function() {\n if (this.fieldsArray == null || this.fieldsArray.length !== 1) {\n return false;\n }\n\n var field = this.fieldsArray[0];\n return field.options != null && field.options[\"proto3_optional\"] === true;\n }\n});\n\n/**\n * Decorator function as returned by {@link OneOf.d} (TypeScript).\n * @typedef OneOfDecorator\n * @type {function}\n * @param {Object} prototype Target prototype\n * @param {string} oneofName OneOf name\n * @returns {undefined}\n */\n\n/**\n * OneOf decorator (TypeScript).\n * @function\n * @param {...string} fieldNames Field names\n * @returns {OneOfDecorator} Decorator function\n * @template T extends string\n */\nOneOf.d = function decorateOneOf() {\n var fieldNames = new Array(arguments.length),\n index = 0;\n while (index < arguments.length)\n fieldNames[index] = arguments[index++];\n return function oneOfDecorator(prototype, oneofName) {\n util.decorateType(prototype.constructor)\n .add(new OneOf(oneofName, fieldNames));\n Object.defineProperty(prototype, oneofName, {\n get: util.oneOfGetter(fieldNames),\n set: util.oneOfSetter(fieldNames)\n });\n };\n};\n","\"use strict\";\nmodule.exports = parse;\n\nparse.filename = null;\nparse.defaults = { keepCase: false };\n\nvar tokenize = require(34),\n Root = require(29),\n Type = require(35),\n Field = require(16),\n MapField = require(20),\n OneOf = require(25),\n Enum = require(15),\n Service = require(33),\n Method = require(22),\n ReflectionObject = require(24),\n types = require(36),\n util = require(37);\n\nvar base10Re = /^[1-9][0-9]*$/,\n base10NegRe = /^-?[1-9][0-9]*$/,\n base16Re = /^0[x][0-9a-fA-F]+$/,\n base16NegRe = /^-?0[x][0-9a-fA-F]+$/,\n base8Re = /^0[0-7]+$/,\n base8NegRe = /^-?0[0-7]+$/,\n numberRe = /^(?![eE])[0-9]*(?:\\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,\n nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/,\n typeRefRe = /^(?:\\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;\n\n/**\n * Result object returned from {@link parse}.\n * @interface IParserResult\n * @property {string|undefined} package Package name, if declared\n * @property {string[]|undefined} imports Imports, if any\n * @property {string[]|undefined} weakImports Weak imports, if any\n * @property {Root} root Populated root instance\n */\n\n/**\n * Options modifying the behavior of {@link parse}.\n * @interface IParseOptions\n * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case\n * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments.\n * @property {boolean} [preferTrailingComment=false] Use trailing comment when both leading comment and trailing comment exist.\n */\n\n/**\n * Options modifying the behavior of JSON serialization.\n * @interface IToJSONOptions\n * @property {boolean} [keepComments=false] Serializes comments.\n */\n\n/**\n * Parses the given .proto source and returns an object with the parsed contents.\n * @param {string} source Source contents\n * @param {Root} root Root to populate\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {IParserResult} Parser result\n * @property {string} filename=null Currently processing file name for error reporting, if known\n * @property {IParseOptions} defaults Default {@link IParseOptions}\n */\nfunction parse(source, root, options) {\n /* eslint-disable callback-return */\n if (!(root instanceof Root)) {\n options = root;\n root = new Root();\n }\n if (!options)\n options = parse.defaults;\n\n var preferTrailingComment = options.preferTrailingComment || false;\n var tn = tokenize(source, options.alternateCommentMode || false),\n next = tn.next,\n push = tn.push,\n peek = tn.peek,\n skip = tn.skip,\n cmnt = tn.cmnt;\n\n var head = true,\n pkg,\n imports,\n weakImports,\n edition = \"proto2\";\n\n var ptr = root;\n\n var topLevelObjects = [];\n var topLevelOptions = {};\n\n var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase;\n\n function resolveFileFeatures() {\n topLevelObjects.forEach(obj => {\n obj._edition = edition;\n Object.keys(topLevelOptions).forEach(opt => {\n if (obj.getOption(opt) !== undefined) return;\n obj.setOption(opt, topLevelOptions[opt], true);\n });\n });\n }\n\n /* istanbul ignore next */\n function illegal(token, name, insideTryCatch) {\n var filename = parse.filename;\n if (!insideTryCatch)\n parse.filename = null;\n return Error(\"illegal \" + (name || \"token\") + \" '\" + token + \"' (\" + (filename ? filename + \", \" : \"\") + \"line \" + tn.line + \")\");\n }\n\n function readString() {\n var values = [],\n token;\n do {\n /* istanbul ignore if */\n if ((token = next()) !== \"\\\"\" && token !== \"'\")\n throw illegal(token);\n\n values.push(next());\n skip(token);\n token = peek();\n } while (token === \"\\\"\" || token === \"'\");\n return values.join(\"\");\n }\n\n function readValue(acceptTypeRef) {\n var token = next();\n switch (token) {\n case \"'\":\n case \"\\\"\":\n push(token);\n return readString();\n case \"true\": case \"TRUE\":\n return true;\n case \"false\": case \"FALSE\":\n return false;\n }\n try {\n return parseNumber(token, /* insideTryCatch */ true);\n } catch (e) {\n /* istanbul ignore else */\n if (acceptTypeRef && typeRefRe.test(token))\n return token;\n\n /* istanbul ignore next */\n throw illegal(token, \"value\");\n }\n }\n\n function readRanges(target, acceptStrings) {\n var token, start;\n do {\n if (acceptStrings && ((token = peek()) === \"\\\"\" || token === \"'\")) {\n var str = readString();\n target.push(str);\n if (edition >= 2023) {\n throw illegal(str, \"id\");\n }\n } else {\n try {\n target.push([ start = parseId(next()), skip(\"to\", true) ? parseId(next()) : start ]);\n } catch (err) {\n if (acceptStrings && typeRefRe.test(token) && edition >= 2023) {\n target.push(token);\n } else {\n throw err;\n }\n }\n }\n } while (skip(\",\", true));\n var dummy = {options: undefined};\n dummy.setOption = function(name, value) {\n if (this.options === undefined) this.options = {};\n this.options[name] = value;\n };\n ifBlock(\n dummy,\n function parseRange_block(token) {\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(dummy, token); // skip\n skip(\";\");\n } else\n throw illegal(token);\n },\n function parseRange_line() {\n parseInlineOptions(dummy); // skip\n });\n }\n\n function parseNumber(token, insideTryCatch) {\n var sign = 1;\n if (token.charAt(0) === \"-\") {\n sign = -1;\n token = token.substring(1);\n }\n switch (token) {\n case \"inf\": case \"INF\": case \"Inf\":\n return sign * Infinity;\n case \"nan\": case \"NAN\": case \"Nan\": case \"NaN\":\n return NaN;\n case \"0\":\n return 0;\n }\n if (base10Re.test(token))\n return sign * parseInt(token, 10);\n if (base16Re.test(token))\n return sign * parseInt(token, 16);\n if (base8Re.test(token))\n return sign * parseInt(token, 8);\n\n /* istanbul ignore else */\n if (numberRe.test(token))\n return sign * parseFloat(token);\n\n /* istanbul ignore next */\n throw illegal(token, \"number\", insideTryCatch);\n }\n\n function parseId(token, acceptNegative) {\n switch (token) {\n case \"max\": case \"MAX\": case \"Max\":\n return 536870911;\n case \"0\":\n return 0;\n }\n\n /* istanbul ignore if */\n if (!acceptNegative && token.charAt(0) === \"-\")\n throw illegal(token, \"id\");\n\n if (base10NegRe.test(token))\n return parseInt(token, 10);\n if (base16NegRe.test(token))\n return parseInt(token, 16);\n\n /* istanbul ignore else */\n if (base8NegRe.test(token))\n return parseInt(token, 8);\n\n /* istanbul ignore next */\n throw illegal(token, \"id\");\n }\n\n function parsePackage() {\n /* istanbul ignore if */\n if (pkg !== undefined)\n throw illegal(\"package\");\n\n pkg = next();\n\n /* istanbul ignore if */\n if (!typeRefRe.test(pkg))\n throw illegal(pkg, \"name\");\n\n ptr = ptr.define(pkg);\n\n skip(\";\");\n }\n\n function parseImport() {\n var token = peek();\n var whichImports;\n switch (token) {\n case \"weak\":\n whichImports = weakImports || (weakImports = []);\n next();\n break;\n case \"public\":\n next();\n // eslint-disable-next-line no-fallthrough\n default:\n whichImports = imports || (imports = []);\n break;\n }\n token = readString();\n skip(\";\");\n whichImports.push(token);\n }\n\n function parseSyntax() {\n skip(\"=\");\n edition = readString();\n\n /* istanbul ignore if */\n if (edition < 2023)\n throw illegal(edition, \"syntax\");\n\n skip(\";\");\n }\n\n function parseEdition() {\n skip(\"=\");\n edition = readString();\n const supportedEditions = [\"2023\"];\n\n /* istanbul ignore if */\n if (!supportedEditions.includes(edition))\n throw illegal(edition, \"edition\");\n\n skip(\";\");\n }\n\n\n function parseCommon(parent, token) {\n switch (token) {\n\n case \"option\":\n parseOption(parent, token);\n skip(\";\");\n return true;\n\n case \"message\":\n parseType(parent, token);\n return true;\n\n case \"enum\":\n parseEnum(parent, token);\n return true;\n\n case \"service\":\n parseService(parent, token);\n return true;\n\n case \"extend\":\n parseExtension(parent, token);\n return true;\n }\n return false;\n }\n\n function ifBlock(obj, fnIf, fnElse) {\n var trailingLine = tn.line;\n if (obj) {\n if(typeof obj.comment !== \"string\") {\n obj.comment = cmnt(); // try block-type comment\n }\n obj.filename = parse.filename;\n }\n if (skip(\"{\", true)) {\n var token;\n while ((token = next()) !== \"}\")\n fnIf(token);\n skip(\";\", true);\n } else {\n if (fnElse)\n fnElse();\n skip(\";\");\n if (obj && (typeof obj.comment !== \"string\" || preferTrailingComment))\n obj.comment = cmnt(trailingLine) || obj.comment; // try line-type comment\n }\n }\n\n function parseType(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"type name\");\n\n var type = new Type(token);\n ifBlock(type, function parseType_block(token) {\n if (parseCommon(type, token))\n return;\n\n switch (token) {\n\n case \"map\":\n parseMapField(type, token);\n break;\n\n case \"required\":\n if (edition !== \"proto2\")\n throw illegal(token);\n /* eslint-disable no-fallthrough */\n case \"repeated\":\n parseField(type, token);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (edition === \"proto3\") {\n parseField(type, \"proto3_optional\");\n } else if (edition !== \"proto2\") {\n throw illegal(token);\n } else {\n parseField(type, \"optional\");\n }\n break;\n\n case \"oneof\":\n parseOneOf(type, token);\n break;\n\n case \"extensions\":\n readRanges(type.extensions || (type.extensions = []));\n break;\n\n case \"reserved\":\n readRanges(type.reserved || (type.reserved = []), true);\n break;\n\n default:\n /* istanbul ignore if */\n if (edition === \"proto2\" || !typeRefRe.test(token)) {\n throw illegal(token);\n }\n\n push(token);\n parseField(type, \"optional\");\n break;\n }\n });\n parent.add(type);\n if (parent === ptr) {\n topLevelObjects.push(type);\n }\n }\n\n function parseField(parent, rule, extend) {\n var type = next();\n if (type === \"group\") {\n parseGroup(parent, rule);\n return;\n }\n // Type names can consume multiple tokens, in multiple variants:\n // package.subpackage field tokens: \"package.subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package . subpackage field tokens: \"package\" \".\" \"subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package. subpackage field tokens: \"package.\" \"subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package .subpackage field tokens: \"package\" \".subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // Keep reading tokens until we get a type name with no period at the end,\n // and the next token does not start with a period.\n while (type.endsWith(\".\") || peek().startsWith(\".\")) {\n type += next();\n }\n\n /* istanbul ignore if */\n if (!typeRefRe.test(type))\n throw illegal(type, \"type\");\n\n var name = next();\n\n /* istanbul ignore if */\n\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n name = applyCase(name);\n skip(\"=\");\n\n var field = new Field(name, parseId(next()), type, rule, extend);\n\n ifBlock(field, function parseField_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(field, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseField_line() {\n parseInlineOptions(field);\n });\n\n if (rule === \"proto3_optional\") {\n // for proto3 optional fields, we create a single-member Oneof to mimic \"optional\" behavior\n var oneof = new OneOf(\"_\" + name);\n field.setOption(\"proto3_optional\", true);\n oneof.add(field);\n parent.add(oneof);\n } else {\n parent.add(field);\n }\n if (parent === ptr) {\n topLevelObjects.push(field);\n }\n }\n\n function parseGroup(parent, rule) {\n if (edition >= 2023) {\n throw illegal(\"group\");\n }\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n var fieldName = util.lcFirst(name);\n if (name === fieldName)\n name = util.ucFirst(name);\n skip(\"=\");\n var id = parseId(next());\n var type = new Type(name);\n type.group = true;\n var field = new Field(fieldName, id, name, rule);\n field.filename = parse.filename;\n ifBlock(type, function parseGroup_block(token) {\n switch (token) {\n\n case \"option\":\n parseOption(type, token);\n skip(\";\");\n break;\n case \"required\":\n case \"repeated\":\n parseField(type, token);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (edition === \"proto3\") {\n parseField(type, \"proto3_optional\");\n } else {\n parseField(type, \"optional\");\n }\n break;\n\n case \"message\":\n parseType(type, token);\n break;\n\n case \"enum\":\n parseEnum(type, token);\n break;\n\n case \"reserved\":\n readRanges(type.reserved || (type.reserved = []), true);\n break;\n\n /* istanbul ignore next */\n default:\n throw illegal(token); // there are no groups with proto3 semantics\n }\n });\n parent.add(type)\n .add(field);\n }\n\n function parseMapField(parent) {\n skip(\"<\");\n var keyType = next();\n\n /* istanbul ignore if */\n if (types.mapKey[keyType] === undefined)\n throw illegal(keyType, \"type\");\n\n skip(\",\");\n var valueType = next();\n\n /* istanbul ignore if */\n if (!typeRefRe.test(valueType))\n throw illegal(valueType, \"type\");\n\n skip(\">\");\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n skip(\"=\");\n var field = new MapField(applyCase(name), parseId(next()), keyType, valueType);\n ifBlock(field, function parseMapField_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(field, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseMapField_line() {\n parseInlineOptions(field);\n });\n parent.add(field);\n }\n\n function parseOneOf(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var oneof = new OneOf(applyCase(token));\n ifBlock(oneof, function parseOneOf_block(token) {\n if (token === \"option\") {\n parseOption(oneof, token);\n skip(\";\");\n } else {\n push(token);\n parseField(oneof, \"optional\");\n }\n });\n parent.add(oneof);\n }\n\n function parseEnum(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var enm = new Enum(token);\n ifBlock(enm, function parseEnum_block(token) {\n switch(token) {\n case \"option\":\n parseOption(enm, token);\n skip(\";\");\n break;\n\n case \"reserved\":\n readRanges(enm.reserved || (enm.reserved = []), true);\n if(enm.reserved === undefined) enm.reserved = [];\n break;\n\n default:\n parseEnumValue(enm, token);\n }\n });\n parent.add(enm);\n if (parent === ptr) {\n topLevelObjects.push(enm);\n }\n }\n\n function parseEnumValue(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token))\n throw illegal(token, \"name\");\n\n skip(\"=\");\n var value = parseId(next(), true),\n dummy = {\n options: undefined\n };\n dummy.getOption = function(name) {\n return this.options[name];\n };\n dummy.setOption = function(name, value) {\n ReflectionObject.prototype.setOption.call(dummy, name, value);\n };\n dummy.setParsedOption = function() {\n return undefined;\n };\n ifBlock(dummy, function parseEnumValue_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(dummy, token); // skip\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseEnumValue_line() {\n parseInlineOptions(dummy); // skip\n });\n parent.add(token, value, dummy.comment, dummy.parsedOptions || dummy.options);\n }\n\n function parseOption(parent, token) {\n var option;\n var propName;\n var isOption = true;\n if (token === \"option\") {\n token = next();\n }\n\n while (token !== \"=\") {\n if (token === \"(\") {\n var parensValue = next();\n skip(\")\");\n token = \"(\" + parensValue + \")\";\n }\n if (isOption) {\n isOption = false;\n if (token.includes(\".\") && !token.includes(\"(\")) {\n var tokens = token.split(\".\");\n option = tokens[0] + \".\";\n token = tokens[1];\n continue;\n }\n option = token;\n } else {\n propName = propName ? propName += token : token;\n }\n token = next();\n }\n var name = propName ? option.concat(propName) : option;\n var optionValue = parseOptionValue(parent, name);\n propName = propName && propName[0] === \".\" ? propName.slice(1) : propName;\n option = option && option[option.length - 1] === \".\" ? option.slice(0, -1) : option;\n setParsedOption(parent, option, optionValue, propName);\n }\n\n function parseOptionValue(parent, name) {\n // { a: \"foo\" b { c: \"bar\" } }\n if (skip(\"{\", true)) {\n var objectResult = {};\n\n while (!skip(\"}\", true)) {\n /* istanbul ignore if */\n if (!nameRe.test(token = next())) {\n throw illegal(token, \"name\");\n }\n if (token === null) {\n throw illegal(token, \"end of input\");\n }\n\n var value;\n var propName = token;\n\n skip(\":\", true);\n\n if (peek() === \"{\") {\n // option (my_option) = {\n // repeated_value: [ \"foo\", \"bar\" ]\n // };\n value = parseOptionValue(parent, name + \".\" + token);\n } else if (peek() === \"[\") {\n value = [];\n var lastValue;\n if (skip(\"[\", true)) {\n do {\n lastValue = readValue(true);\n value.push(lastValue);\n } while (skip(\",\", true));\n skip(\"]\");\n if (typeof lastValue !== \"undefined\") {\n setOption(parent, name + \".\" + token, lastValue);\n }\n }\n } else {\n value = readValue(true);\n setOption(parent, name + \".\" + token, value);\n }\n\n var prevValue = objectResult[propName];\n\n if (prevValue)\n value = [].concat(prevValue).concat(value);\n\n objectResult[propName] = value;\n\n // Semicolons and commas can be optional\n skip(\",\", true);\n skip(\";\", true);\n }\n\n return objectResult;\n }\n\n var simpleValue = readValue(true);\n setOption(parent, name, simpleValue);\n return simpleValue;\n // Does not enforce a delimiter to be universal\n }\n\n function setOption(parent, name, value) {\n if (ptr === parent && /^features\\./.test(name)) {\n topLevelOptions[name] = value;\n return;\n }\n if (parent.setOption)\n parent.setOption(name, value);\n }\n\n function setParsedOption(parent, name, value, propName) {\n if (parent.setParsedOption)\n parent.setParsedOption(name, value, propName);\n }\n\n function parseInlineOptions(parent) {\n if (skip(\"[\", true)) {\n do {\n parseOption(parent, \"option\");\n } while (skip(\",\", true));\n skip(\"]\");\n }\n return parent;\n }\n\n function parseService(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"service name\");\n\n var service = new Service(token);\n ifBlock(service, function parseService_block(token) {\n if (parseCommon(service, token)) {\n return;\n }\n\n /* istanbul ignore else */\n if (token === \"rpc\")\n parseMethod(service, token);\n else\n throw illegal(token);\n });\n parent.add(service);\n if (parent === ptr) {\n topLevelObjects.push(service);\n }\n }\n\n function parseMethod(parent, token) {\n // Get the comment of the preceding line now (if one exists) in case the\n // method is defined across multiple lines.\n var commentText = cmnt();\n\n var type = token;\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var name = token,\n requestType, requestStream,\n responseType, responseStream;\n\n skip(\"(\");\n if (skip(\"stream\", true))\n requestStream = true;\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token);\n\n requestType = token;\n skip(\")\"); skip(\"returns\"); skip(\"(\");\n if (skip(\"stream\", true))\n responseStream = true;\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token);\n\n responseType = token;\n skip(\")\");\n\n var method = new Method(name, type, requestType, responseType, requestStream, responseStream);\n method.comment = commentText;\n ifBlock(method, function parseMethod_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(method, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n });\n parent.add(method);\n }\n\n function parseExtension(parent, token) {\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token, \"reference\");\n\n var reference = token;\n ifBlock(null, function parseExtension_block(token) {\n switch (token) {\n\n case \"required\":\n case \"repeated\":\n parseField(parent, token, reference);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (edition === \"proto3\") {\n parseField(parent, \"proto3_optional\", reference);\n } else {\n parseField(parent, \"optional\", reference);\n }\n break;\n\n default:\n /* istanbul ignore if */\n if (edition === \"proto2\" || !typeRefRe.test(token))\n throw illegal(token);\n push(token);\n parseField(parent, \"optional\", reference);\n break;\n }\n });\n }\n\n var token;\n while ((token = next()) !== null) {\n switch (token) {\n\n case \"package\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parsePackage();\n break;\n\n case \"import\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parseImport();\n break;\n\n case \"syntax\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parseSyntax();\n break;\n\n case \"edition\":\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n parseEdition();\n break;\n\n case \"option\":\n parseOption(ptr, token);\n skip(\";\", true);\n break;\n\n default:\n\n /* istanbul ignore else */\n if (parseCommon(ptr, token)) {\n head = false;\n continue;\n }\n\n /* istanbul ignore next */\n throw illegal(token);\n }\n }\n\n resolveFileFeatures();\n\n parse.filename = null;\n return {\n \"package\" : pkg,\n \"imports\" : imports,\n weakImports : weakImports,\n root : root\n };\n}\n\n/**\n * Parses the given .proto source and returns an object with the parsed contents.\n * @name parse\n * @function\n * @param {string} source Source contents\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {IParserResult} Parser result\n * @property {string} filename=null Currently processing file name for error reporting, if known\n * @property {IParseOptions} defaults Default {@link IParseOptions}\n * @variation 2\n */\n","\"use strict\";\nmodule.exports = Reader;\n\nvar util = require(39);\n\nvar BufferReader; // cyclic\n\nvar LongBits = util.LongBits,\n utf8 = util.utf8;\n\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(\"index out of range: \" + reader.pos + \" + \" + (writeLength || 1) + \" > \" + reader.len);\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n * @param {Uint8Array} buffer Buffer to read from\n */\nfunction Reader(buffer) {\n\n /**\n * Read buffer.\n * @type {Uint8Array}\n */\n this.buf = buffer;\n\n /**\n * Read buffer position.\n * @type {number}\n */\n this.pos = 0;\n\n /**\n * Read buffer length.\n * @type {number}\n */\n this.len = buffer.length;\n}\n\nvar create_array = typeof Uint8Array !== \"undefined\"\n ? function create_typed_array(buffer) {\n if (buffer instanceof Uint8Array || Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n }\n /* istanbul ignore next */\n : function create_array(buffer) {\n if (Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n };\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup(buffer) {\n return (Reader.create = function create_buffer(buffer) {\n return util.Buffer.isBuffer(buffer)\n ? new BufferReader(buffer)\n /* istanbul ignore next */\n : create_array(buffer);\n })(buffer);\n }\n /* istanbul ignore next */\n : create_array;\n};\n\n/**\n * Creates a new reader using the specified buffer.\n * @function\n * @param {Uint8Array|Buffer} buffer Buffer to read from\n * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}\n * @throws {Error} If `buffer` is not a valid buffer\n */\nReader.create = create();\n\nReader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;\n\n/**\n * Reads a varint as an unsigned 32 bit value.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.uint32 = (function read_uint32_setup() {\n var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)\n return function read_uint32() {\n value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;\n\n /* istanbul ignore if */\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n };\n})();\n\n/**\n * Reads a varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.int32 = function read_int32() {\n return this.uint32() | 0;\n};\n\n/**\n * Reads a zig-zag encoded varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.sint32 = function read_sint32() {\n var value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readLongVarint() {\n // tends to deopt with local vars for octet etc.\n var bits = new LongBits(0, 0);\n var i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n i = 0;\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n } else {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n }\n /* istanbul ignore next */\n throw Error(\"invalid varint encoding\");\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads a varint as a signed 64 bit value.\n * @name Reader#int64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as an unsigned 64 bit value.\n * @name Reader#uint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a zig-zag encoded varint as a signed 64 bit value.\n * @name Reader#sint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as a boolean.\n * @returns {boolean} Value read\n */\nReader.prototype.bool = function read_bool() {\n return this.uint32() !== 0;\n};\n\nfunction readFixed32_end(buf, end) { // note that this uses `end`, not `pos`\n return (buf[end - 4]\n | buf[end - 3] << 8\n | buf[end - 2] << 16\n | buf[end - 1] << 24) >>> 0;\n}\n\n/**\n * Reads fixed 32 bits as an unsigned 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.fixed32 = function read_fixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4);\n};\n\n/**\n * Reads fixed 32 bits as a signed 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.sfixed32 = function read_sfixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readFixed64(/* this: Reader */) {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 8);\n\n return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads fixed 64 bits.\n * @name Reader#fixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads zig-zag encoded fixed 64 bits.\n * @name Reader#sfixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a float (32 bit) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.float = function read_float() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readFloatLE(this.buf, this.pos);\n this.pos += 4;\n return value;\n};\n\n/**\n * Reads a double (64 bit float) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.double = function read_double() {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readDoubleLE(this.buf, this.pos);\n this.pos += 8;\n return value;\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @returns {Uint8Array} Value read\n */\nReader.prototype.bytes = function read_bytes() {\n var length = this.uint32(),\n start = this.pos,\n end = this.pos + length;\n\n /* istanbul ignore if */\n if (end > this.len)\n throw indexOutOfRange(this, length);\n\n this.pos += length;\n if (Array.isArray(this.buf)) // plain array\n return this.buf.slice(start, end);\n\n if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1\n var nativeBuffer = util.Buffer;\n return nativeBuffer\n ? nativeBuffer.alloc(0)\n : new this.buf.constructor(0);\n }\n return this._slice.call(this.buf, start, end);\n};\n\n/**\n * Reads a string preceeded by its byte length as a varint.\n * @returns {string} Value read\n */\nReader.prototype.string = function read_string() {\n var bytes = this.bytes();\n return utf8.read(bytes, 0, bytes.length);\n};\n\n/**\n * Skips the specified number of bytes if specified, otherwise skips a varint.\n * @param {number} [length] Length if known, otherwise a varint is assumed\n * @returns {Reader} `this`\n */\nReader.prototype.skip = function skip(length) {\n if (typeof length === \"number\") {\n /* istanbul ignore if */\n if (this.pos + length > this.len)\n throw indexOutOfRange(this, length);\n this.pos += length;\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n } while (this.buf[this.pos++] & 128);\n }\n return this;\n};\n\n/**\n * Skips the next element of the specified wire type.\n * @param {number} wireType Wire type received\n * @returns {Reader} `this`\n */\nReader.prototype.skipType = function(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n\n /* istanbul ignore next */\n default:\n throw Error(\"invalid wire type \" + wireType + \" at offset \" + this.pos);\n }\n return this;\n};\n\nReader._configure = function(BufferReader_) {\n BufferReader = BufferReader_;\n Reader.create = create();\n BufferReader._configure();\n\n var fn = util.Long ? \"toLong\" : /* istanbul ignore next */ \"toNumber\";\n util.merge(Reader.prototype, {\n\n int64: function read_int64() {\n return readLongVarint.call(this)[fn](false);\n },\n\n uint64: function read_uint64() {\n return readLongVarint.call(this)[fn](true);\n },\n\n sint64: function read_sint64() {\n return readLongVarint.call(this).zzDecode()[fn](false);\n },\n\n fixed64: function read_fixed64() {\n return readFixed64.call(this)[fn](true);\n },\n\n sfixed64: function read_sfixed64() {\n return readFixed64.call(this)[fn](false);\n }\n\n });\n};\n","\"use strict\";\nmodule.exports = BufferReader;\n\n// extends Reader\nvar Reader = require(27);\n(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;\n\nvar util = require(39);\n\n/**\n * Constructs a new buffer reader instance.\n * @classdesc Wire format reader using node buffers.\n * @extends Reader\n * @constructor\n * @param {Buffer} buffer Buffer to read from\n */\nfunction BufferReader(buffer) {\n Reader.call(this, buffer);\n\n /**\n * Read buffer.\n * @name BufferReader#buf\n * @type {Buffer}\n */\n}\n\nBufferReader._configure = function () {\n /* istanbul ignore else */\n if (util.Buffer)\n BufferReader.prototype._slice = util.Buffer.prototype.slice;\n};\n\n\n/**\n * @override\n */\nBufferReader.prototype.string = function read_string_buffer() {\n var len = this.uint32(); // modifies pos\n return this.buf.utf8Slice\n ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))\n : this.buf.toString(\"utf-8\", this.pos, this.pos = Math.min(this.pos + len, this.len));\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @name BufferReader#bytes\n * @function\n * @returns {Buffer} Value read\n */\n\nBufferReader._configure();\n","\"use strict\";\nmodule.exports = Root;\n\n// extends Namespace\nvar Namespace = require(23);\n((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = \"Root\";\n\nvar Field = require(16),\n Enum = require(15),\n OneOf = require(25),\n util = require(37);\n\nvar Type, // cyclic\n parse, // might be excluded\n common; // \"\n\n/**\n * Constructs a new root namespace instance.\n * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together.\n * @extends NamespaceBase\n * @constructor\n * @param {Object.} [options] Top level options\n */\nfunction Root(options) {\n Namespace.call(this, \"\", options);\n\n /**\n * Deferred extension fields.\n * @type {Field[]}\n */\n this.deferred = [];\n\n /**\n * Resolved file names of loaded files.\n * @type {string[]}\n */\n this.files = [];\n\n /**\n * Edition, defaults to proto2 if unspecified.\n * @type {string}\n * @private\n */\n this._edition = \"proto2\";\n\n /**\n * Global lookup cache of fully qualified names.\n * @type {Object.}\n * @private\n */\n this._fullyQualifiedObjects = {};\n}\n\n/**\n * Loads a namespace descriptor into a root namespace.\n * @param {INamespace} json Namespace descriptor\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted\n * @returns {Root} Root namespace\n */\nRoot.fromJSON = function fromJSON(json, root) {\n if (!root)\n root = new Root();\n if (json.options)\n root.setOptions(json.options);\n return root.addJSON(json.nested).resolveAll();\n};\n\n/**\n * Resolves the path of an imported file, relative to the importing origin.\n * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories.\n * @function\n * @param {string} origin The file name of the importing file\n * @param {string} target The file name being imported\n * @returns {string|null} Resolved path to `target` or `null` to skip the file\n */\nRoot.prototype.resolvePath = util.path.resolve;\n\n/**\n * Fetch content from file path or url\n * This method exists so you can override it with your own logic.\n * @function\n * @param {string} path File path or url\n * @param {FetchCallback} callback Callback function\n * @returns {undefined}\n */\nRoot.prototype.fetch = util.fetch;\n\n// A symbol-like function to safely signal synchronous loading\n/* istanbul ignore next */\nfunction SYNC() {} // eslint-disable-line no-empty-function\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} options Parse options\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n */\nRoot.prototype.load = function load(filename, options, callback) {\n if (typeof options === \"function\") {\n callback = options;\n options = undefined;\n }\n var self = this;\n if (!callback) {\n return util.asPromise(load, self, filename, options);\n }\n\n var sync = callback === SYNC; // undocumented\n\n // Finishes loading by calling the callback (exactly once)\n function finish(err, root) {\n /* istanbul ignore if */\n if (!callback) {\n return;\n }\n if (sync) {\n throw err;\n }\n if (root) {\n root.resolveAll();\n }\n var cb = callback;\n callback = null;\n cb(err, root);\n }\n\n // Bundled definition existence checking\n function getBundledFileName(filename) {\n var idx = filename.lastIndexOf(\"google/protobuf/\");\n if (idx > -1) {\n var altname = filename.substring(idx);\n if (altname in common) return altname;\n }\n return null;\n }\n\n // Processes a single file\n function process(filename, source) {\n try {\n if (util.isString(source) && source.charAt(0) === \"{\")\n source = JSON.parse(source);\n if (!util.isString(source))\n self.setOptions(source.options).addJSON(source.nested);\n else {\n parse.filename = filename;\n var parsed = parse(source, self, options),\n resolved,\n i = 0;\n if (parsed.imports)\n for (; i < parsed.imports.length; ++i)\n if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i]))\n fetch(resolved);\n if (parsed.weakImports)\n for (i = 0; i < parsed.weakImports.length; ++i)\n if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i]))\n fetch(resolved, true);\n }\n } catch (err) {\n finish(err);\n }\n if (!sync && !queued) {\n finish(null, self); // only once anyway\n }\n }\n\n // Fetches a single file\n function fetch(filename, weak) {\n filename = getBundledFileName(filename) || filename;\n\n // Skip if already loaded / attempted\n if (self.files.indexOf(filename) > -1) {\n return;\n }\n self.files.push(filename);\n\n // Shortcut bundled definitions\n if (filename in common) {\n if (sync) {\n process(filename, common[filename]);\n } else {\n ++queued;\n setTimeout(function() {\n --queued;\n process(filename, common[filename]);\n });\n }\n return;\n }\n\n // Otherwise fetch from disk or network\n if (sync) {\n var source;\n try {\n source = util.fs.readFileSync(filename).toString(\"utf8\");\n } catch (err) {\n if (!weak)\n finish(err);\n return;\n }\n process(filename, source);\n } else {\n ++queued;\n self.fetch(filename, function(err, source) {\n --queued;\n /* istanbul ignore if */\n if (!callback) {\n return; // terminated meanwhile\n }\n if (err) {\n /* istanbul ignore else */\n if (!weak)\n finish(err);\n else if (!queued) // can't be covered reliably\n finish(null, self);\n return;\n }\n process(filename, source);\n });\n }\n }\n var queued = 0;\n\n // Assembling the root namespace doesn't require working type\n // references anymore, so we can load everything in parallel\n if (util.isString(filename)) {\n filename = [ filename ];\n }\n for (var i = 0, resolved; i < filename.length; ++i)\n if (resolved = self.resolvePath(\"\", filename[i]))\n fetch(resolved);\n if (sync) {\n self.resolveAll();\n return self;\n }\n if (!queued) {\n finish(null, self);\n }\n\n return self;\n};\n// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\n * @function Root#load\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @variation 2\n */\n// function load(filename:string, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise.\n * @function Root#load\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {Promise} Promise\n * @variation 3\n */\n// function load(filename:string, [options:IParseOptions]):Promise\n\n/**\n * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only).\n * @function Root#loadSync\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {Root} Root namespace\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\n */\nRoot.prototype.loadSync = function loadSync(filename, options) {\n if (!util.isNode)\n throw Error(\"not supported\");\n return this.load(filename, options, SYNC);\n};\n\n/**\n * @override\n */\nRoot.prototype.resolveAll = function resolveAll() {\n if (!this._needsRecursiveResolve) return this;\n\n if (this.deferred.length)\n throw Error(\"unresolvable extensions: \" + this.deferred.map(function(field) {\n return \"'extend \" + field.extend + \"' in \" + field.parent.fullName;\n }).join(\", \"));\n return Namespace.prototype.resolveAll.call(this);\n};\n\n// only uppercased (and thus conflict-free) children are exposed, see below\nvar exposeRe = /^[A-Z]/;\n\n/**\n * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type.\n * @param {Root} root Root instance\n * @param {Field} field Declaring extension field witin the declaring type\n * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise\n * @inner\n * @ignore\n */\nfunction tryHandleExtension(root, field) {\n var extendedType = field.parent.lookup(field.extend);\n if (extendedType) {\n var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options);\n //do not allow to extend same field twice to prevent the error\n if (extendedType.get(sisterField.name)) {\n return true;\n }\n sisterField.declaringField = field;\n field.extensionField = sisterField;\n extendedType.add(sisterField);\n return true;\n }\n return false;\n}\n\n/**\n * Called when any object is added to this root or its sub-namespaces.\n * @param {ReflectionObject} object Object added\n * @returns {undefined}\n * @private\n */\nRoot.prototype._handleAdd = function _handleAdd(object) {\n if (object instanceof Field) {\n\n if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField)\n if (!tryHandleExtension(this, object))\n this.deferred.push(object);\n\n } else if (object instanceof Enum) {\n\n if (exposeRe.test(object.name))\n object.parent[object.name] = object.values; // expose enum values as property of its parent\n\n } else if (!(object instanceof OneOf)) /* everything else is a namespace */ {\n\n if (object instanceof Type) // Try to handle any deferred extensions\n for (var i = 0; i < this.deferred.length;)\n if (tryHandleExtension(this, this.deferred[i]))\n this.deferred.splice(i, 1);\n else\n ++i;\n for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace\n this._handleAdd(object._nestedArray[j]);\n if (exposeRe.test(object.name))\n object.parent[object.name] = object; // expose namespace as property of its parent\n }\n\n if (object instanceof Type || object instanceof Enum || object instanceof Field) {\n // Only store types and enums for quick lookup during resolve.\n this._fullyQualifiedObjects[object.fullName] = object;\n }\n\n // The above also adds uppercased (and thus conflict-free) nested types, services and enums as\n // properties of namespaces just like static code does. This allows using a .d.ts generated for\n // a static module with reflection-based solutions where the condition is met.\n};\n\n/**\n * Called when any object is removed from this root or its sub-namespaces.\n * @param {ReflectionObject} object Object removed\n * @returns {undefined}\n * @private\n */\nRoot.prototype._handleRemove = function _handleRemove(object) {\n if (object instanceof Field) {\n\n if (/* an extension field */ object.extend !== undefined) {\n if (/* already handled */ object.extensionField) { // remove its sister field\n object.extensionField.parent.remove(object.extensionField);\n object.extensionField = null;\n } else { // cancel the extension\n var index = this.deferred.indexOf(object);\n /* istanbul ignore else */\n if (index > -1)\n this.deferred.splice(index, 1);\n }\n }\n\n } else if (object instanceof Enum) {\n\n if (exposeRe.test(object.name))\n delete object.parent[object.name]; // unexpose enum values\n\n } else if (object instanceof Namespace) {\n\n for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace\n this._handleRemove(object._nestedArray[i]);\n\n if (exposeRe.test(object.name))\n delete object.parent[object.name]; // unexpose namespaces\n\n }\n\n delete this._fullyQualifiedObjects[object.fullName];\n};\n\n// Sets up cyclic dependencies (called in index-light)\nRoot._configure = function(Type_, parse_, common_) {\n Type = Type_;\n parse = parse_;\n common = common_;\n};\n","\"use strict\";\nmodule.exports = {};\n\n/**\n * Named roots.\n * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).\n * Can also be used manually to make roots available across modules.\n * @name roots\n * @type {Object.}\n * @example\n * // pbjs -r myroot -o compiled.js ...\n *\n * // in another module:\n * require(\"./compiled.js\");\n *\n * // in any subsequent module:\n * var root = protobuf.roots[\"myroot\"];\n */\n","\"use strict\";\n\n/**\n * Streaming RPC helpers.\n * @namespace\n */\nvar rpc = exports;\n\n/**\n * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.\n * @typedef RPCImpl\n * @type {function}\n * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called\n * @param {Uint8Array} requestData Request data\n * @param {RPCImplCallback} callback Callback function\n * @returns {undefined}\n * @example\n * function rpcImpl(method, requestData, callback) {\n * if (protobuf.util.lcFirst(method.name) !== \"myMethod\") // compatible with static code\n * throw Error(\"no such method\");\n * asynchronouslyObtainAResponse(requestData, function(err, responseData) {\n * callback(err, responseData);\n * });\n * }\n */\n\n/**\n * Node-style callback as used by {@link RPCImpl}.\n * @typedef RPCImplCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error\n * @returns {undefined}\n */\n\nrpc.Service = require(32);\n","\"use strict\";\nmodule.exports = Service;\n\nvar util = require(39);\n\n// Extends EventEmitter\n(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;\n\n/**\n * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.\n *\n * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.\n * @typedef rpc.ServiceMethodCallback\n * @template TRes extends Message\n * @type {function}\n * @param {Error|null} error Error, if any\n * @param {TRes} [response] Response message\n * @returns {undefined}\n */\n\n/**\n * A service method part of a {@link rpc.Service} as created by {@link Service.create}.\n * @typedef rpc.ServiceMethod\n * @template TReq extends Message\n * @template TRes extends Message\n * @type {function}\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message\n * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined`\n */\n\n/**\n * Constructs a new RPC service instance.\n * @classdesc An RPC service as returned by {@link Service#create}.\n * @exports rpc.Service\n * @extends util.EventEmitter\n * @constructor\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n */\nfunction Service(rpcImpl, requestDelimited, responseDelimited) {\n\n if (typeof rpcImpl !== \"function\")\n throw TypeError(\"rpcImpl must be a function\");\n\n util.EventEmitter.call(this);\n\n /**\n * RPC implementation. Becomes `null` once the service is ended.\n * @type {RPCImpl|null}\n */\n this.rpcImpl = rpcImpl;\n\n /**\n * Whether requests are length-delimited.\n * @type {boolean}\n */\n this.requestDelimited = Boolean(requestDelimited);\n\n /**\n * Whether responses are length-delimited.\n * @type {boolean}\n */\n this.responseDelimited = Boolean(responseDelimited);\n}\n\n/**\n * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.\n * @param {Method|rpc.ServiceMethod} method Reflected or static method\n * @param {Constructor} requestCtor Request constructor\n * @param {Constructor} responseCtor Response constructor\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} callback Service callback\n * @returns {undefined}\n * @template TReq extends Message\n * @template TRes extends Message\n */\nService.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {\n\n if (!request)\n throw TypeError(\"request must be specified\");\n\n var self = this;\n if (!callback)\n return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);\n\n if (!self.rpcImpl) {\n setTimeout(function() { callback(Error(\"already ended\")); }, 0);\n return undefined;\n }\n\n try {\n return self.rpcImpl(\n method,\n requestCtor[self.requestDelimited ? \"encodeDelimited\" : \"encode\"](request).finish(),\n function rpcCallback(err, response) {\n\n if (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n\n if (response === null) {\n self.end(/* endedByRPC */ true);\n return undefined;\n }\n\n if (!(response instanceof responseCtor)) {\n try {\n response = responseCtor[self.responseDelimited ? \"decodeDelimited\" : \"decode\"](response);\n } catch (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n }\n\n self.emit(\"data\", response, method);\n return callback(null, response);\n }\n );\n } catch (err) {\n self.emit(\"error\", err, method);\n setTimeout(function() { callback(err); }, 0);\n return undefined;\n }\n};\n\n/**\n * Ends this service and emits the `end` event.\n * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.\n * @returns {rpc.Service} `this`\n */\nService.prototype.end = function end(endedByRPC) {\n if (this.rpcImpl) {\n if (!endedByRPC) // signal end to rpcImpl\n this.rpcImpl(null, null, null);\n this.rpcImpl = null;\n this.emit(\"end\").off();\n }\n return this;\n};\n","\"use strict\";\nmodule.exports = Service;\n\n// extends Namespace\nvar Namespace = require(23);\n((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = \"Service\";\n\nvar Method = require(22),\n util = require(37),\n rpc = require(31);\n\n/**\n * Constructs a new service instance.\n * @classdesc Reflected service.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Service name\n * @param {Object.} [options] Service options\n * @throws {TypeError} If arguments are invalid\n */\nfunction Service(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Service methods.\n * @type {Object.}\n */\n this.methods = {}; // toJSON, marker\n\n /**\n * Cached methods as an array.\n * @type {Method[]|null}\n * @private\n */\n this._methodsArray = null;\n}\n\n/**\n * Service descriptor.\n * @interface IService\n * @extends INamespace\n * @property {Object.} methods Method descriptors\n */\n\n/**\n * Constructs a service from a service descriptor.\n * @param {string} name Service name\n * @param {IService} json Service descriptor\n * @returns {Service} Created service\n * @throws {TypeError} If arguments are invalid\n */\nService.fromJSON = function fromJSON(name, json) {\n var service = new Service(name, json.options);\n /* istanbul ignore else */\n if (json.methods)\n for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i)\n service.add(Method.fromJSON(names[i], json.methods[names[i]]));\n if (json.nested)\n service.addJSON(json.nested);\n if (json.edition)\n service._edition = json.edition;\n service.comment = json.comment;\n service._defaultEdition = \"proto3\"; // For backwards-compatibility.\n return service;\n};\n\n/**\n * Converts this service to a service descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IService} Service descriptor\n */\nService.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"edition\" , this._editionToJSON(),\n \"options\" , inherited && inherited.options || undefined,\n \"methods\" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {},\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Methods of this service as an array for iteration.\n * @name Service#methodsArray\n * @type {Method[]}\n * @readonly\n */\nObject.defineProperty(Service.prototype, \"methodsArray\", {\n get: function() {\n return this._methodsArray || (this._methodsArray = util.toArray(this.methods));\n }\n});\n\nfunction clearCache(service) {\n service._methodsArray = null;\n return service;\n}\n\n/**\n * @override\n */\nService.prototype.get = function get(name) {\n return this.methods[name]\n || Namespace.prototype.get.call(this, name);\n};\n\n/**\n * @override\n */\nService.prototype.resolveAll = function resolveAll() {\n if (!this._needsRecursiveResolve) return this;\n\n Namespace.prototype.resolve.call(this);\n var methods = this.methodsArray;\n for (var i = 0; i < methods.length; ++i)\n methods[i].resolve();\n return this;\n};\n\n/**\n * @override\n */\nService.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) {\n if (!this._needsRecursiveFeatureResolution) return this;\n\n edition = this._edition || edition;\n\n Namespace.prototype._resolveFeaturesRecursive.call(this, edition);\n this.methodsArray.forEach(method => {\n method._resolveFeaturesRecursive(edition);\n });\n return this;\n};\n\n/**\n * @override\n */\nService.prototype.add = function add(object) {\n\n /* istanbul ignore if */\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Method) {\n this.methods[object.name] = object;\n object.parent = this;\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * @override\n */\nService.prototype.remove = function remove(object) {\n if (object instanceof Method) {\n\n /* istanbul ignore if */\n if (this.methods[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.methods[object.name];\n object.parent = null;\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Creates a runtime service using the specified rpc implementation.\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed.\n */\nService.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) {\n var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);\n for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) {\n var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\\w_]/g, \"\");\n rpcService[methodName] = util.codegen([\"r\",\"c\"], util.isReserved(methodName) ? methodName + \"_\" : methodName)(\"return this.rpcCall(m,q,s,r,c)\")({\n m: method,\n q: method.resolvedRequestType.ctor,\n s: method.resolvedResponseType.ctor\n });\n }\n return rpcService;\n};\n","\"use strict\";\nmodule.exports = tokenize;\n\nvar delimRe = /[\\s{}=;:[\\],'\"()<>]/g,\n stringDoubleRe = /(?:\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\")/g,\n stringSingleRe = /(?:'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)')/g;\n\nvar setCommentRe = /^ *[*/]+ */,\n setCommentAltRe = /^\\s*\\*?\\/*/,\n setCommentSplitRe = /\\n/g,\n whitespaceRe = /\\s/,\n unescapeRe = /\\\\(.?)/g;\n\nvar unescapeMap = {\n \"0\": \"\\0\",\n \"r\": \"\\r\",\n \"n\": \"\\n\",\n \"t\": \"\\t\"\n};\n\n/**\n * Unescapes a string.\n * @param {string} str String to unescape\n * @returns {string} Unescaped string\n * @property {Object.} map Special characters map\n * @memberof tokenize\n */\nfunction unescape(str) {\n return str.replace(unescapeRe, function($0, $1) {\n switch ($1) {\n case \"\\\\\":\n case \"\":\n return $1;\n default:\n return unescapeMap[$1] || \"\";\n }\n });\n}\n\ntokenize.unescape = unescape;\n\n/**\n * Gets the next token and advances.\n * @typedef TokenizerHandleNext\n * @type {function}\n * @returns {string|null} Next token or `null` on eof\n */\n\n/**\n * Peeks for the next token.\n * @typedef TokenizerHandlePeek\n * @type {function}\n * @returns {string|null} Next token or `null` on eof\n */\n\n/**\n * Pushes a token back to the stack.\n * @typedef TokenizerHandlePush\n * @type {function}\n * @param {string} token Token\n * @returns {undefined}\n */\n\n/**\n * Skips the next token.\n * @typedef TokenizerHandleSkip\n * @type {function}\n * @param {string} expected Expected token\n * @param {boolean} [optional=false] If optional\n * @returns {boolean} Whether the token matched\n * @throws {Error} If the token didn't match and is not optional\n */\n\n/**\n * Gets the comment on the previous line or, alternatively, the line comment on the specified line.\n * @typedef TokenizerHandleCmnt\n * @type {function}\n * @param {number} [line] Line number\n * @returns {string|null} Comment text or `null` if none\n */\n\n/**\n * Handle object returned from {@link tokenize}.\n * @interface ITokenizerHandle\n * @property {TokenizerHandleNext} next Gets the next token and advances (`null` on eof)\n * @property {TokenizerHandlePeek} peek Peeks for the next token (`null` on eof)\n * @property {TokenizerHandlePush} push Pushes a token back to the stack\n * @property {TokenizerHandleSkip} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws\n * @property {TokenizerHandleCmnt} cmnt Gets the comment on the previous line or the line comment on the specified line, if any\n * @property {number} line Current line number\n */\n\n/**\n * Tokenizes the given .proto source and returns an object with useful utility functions.\n * @param {string} source Source contents\n * @param {boolean} alternateCommentMode Whether we should activate alternate comment parsing mode.\n * @returns {ITokenizerHandle} Tokenizer handle\n */\nfunction tokenize(source, alternateCommentMode) {\n /* eslint-disable callback-return */\n source = source.toString();\n\n var offset = 0,\n length = source.length,\n line = 1,\n lastCommentLine = 0,\n comments = {};\n\n var stack = [];\n\n var stringDelim = null;\n\n /* istanbul ignore next */\n /**\n * Creates an error for illegal syntax.\n * @param {string} subject Subject\n * @returns {Error} Error created\n * @inner\n */\n function illegal(subject) {\n return Error(\"illegal \" + subject + \" (line \" + line + \")\");\n }\n\n /**\n * Reads a string till its end.\n * @returns {string} String read\n * @inner\n */\n function readString() {\n var re = stringDelim === \"'\" ? stringSingleRe : stringDoubleRe;\n re.lastIndex = offset - 1;\n var match = re.exec(source);\n if (!match)\n throw illegal(\"string\");\n offset = re.lastIndex;\n push(stringDelim);\n stringDelim = null;\n return unescape(match[1]);\n }\n\n /**\n * Gets the character at `pos` within the source.\n * @param {number} pos Position\n * @returns {string} Character\n * @inner\n */\n function charAt(pos) {\n return source.charAt(pos);\n }\n\n /**\n * Sets the current comment text.\n * @param {number} start Start offset\n * @param {number} end End offset\n * @param {boolean} isLeading set if a leading comment\n * @returns {undefined}\n * @inner\n */\n function setComment(start, end, isLeading) {\n var comment = {\n type: source.charAt(start++),\n lineEmpty: false,\n leading: isLeading,\n };\n var lookback;\n if (alternateCommentMode) {\n lookback = 2; // alternate comment parsing: \"//\" or \"/*\"\n } else {\n lookback = 3; // \"///\" or \"/**\"\n }\n var commentOffset = start - lookback,\n c;\n do {\n if (--commentOffset < 0 ||\n (c = source.charAt(commentOffset)) === \"\\n\") {\n comment.lineEmpty = true;\n break;\n }\n } while (c === \" \" || c === \"\\t\");\n var lines = source\n .substring(start, end)\n .split(setCommentSplitRe);\n for (var i = 0; i < lines.length; ++i)\n lines[i] = lines[i]\n .replace(alternateCommentMode ? setCommentAltRe : setCommentRe, \"\")\n .trim();\n comment.text = lines\n .join(\"\\n\")\n .trim();\n\n comments[line] = comment;\n lastCommentLine = line;\n }\n\n function isDoubleSlashCommentLine(startOffset) {\n var endOffset = findEndOfLine(startOffset);\n\n // see if remaining line matches comment pattern\n var lineText = source.substring(startOffset, endOffset);\n var isComment = /^\\s*\\/\\//.test(lineText);\n return isComment;\n }\n\n function findEndOfLine(cursor) {\n // find end of cursor's line\n var endOffset = cursor;\n while (endOffset < length && charAt(endOffset) !== \"\\n\") {\n endOffset++;\n }\n return endOffset;\n }\n\n /**\n * Obtains the next token.\n * @returns {string|null} Next token or `null` on eof\n * @inner\n */\n function next() {\n if (stack.length > 0)\n return stack.shift();\n if (stringDelim)\n return readString();\n var repeat,\n prev,\n curr,\n start,\n isDoc,\n isLeadingComment = offset === 0;\n do {\n if (offset === length)\n return null;\n repeat = false;\n while (whitespaceRe.test(curr = charAt(offset))) {\n if (curr === \"\\n\") {\n isLeadingComment = true;\n ++line;\n }\n if (++offset === length)\n return null;\n }\n\n if (charAt(offset) === \"/\") {\n if (++offset === length) {\n throw illegal(\"comment\");\n }\n if (charAt(offset) === \"/\") { // Line\n if (!alternateCommentMode) {\n // check for triple-slash comment\n isDoc = charAt(start = offset + 1) === \"/\";\n\n while (charAt(++offset) !== \"\\n\") {\n if (offset === length) {\n return null;\n }\n }\n ++offset;\n if (isDoc) {\n setComment(start, offset - 1, isLeadingComment);\n // Trailing comment cannot not be multi-line,\n // so leading comment state should be reset to handle potential next comments\n isLeadingComment = true;\n }\n ++line;\n repeat = true;\n } else {\n // check for double-slash comments, consolidating consecutive lines\n start = offset;\n isDoc = false;\n if (isDoubleSlashCommentLine(offset - 1)) {\n isDoc = true;\n do {\n offset = findEndOfLine(offset);\n if (offset === length) {\n break;\n }\n offset++;\n if (!isLeadingComment) {\n // Trailing comment cannot not be multi-line\n break;\n }\n } while (isDoubleSlashCommentLine(offset));\n } else {\n offset = Math.min(length, findEndOfLine(offset) + 1);\n }\n if (isDoc) {\n setComment(start, offset, isLeadingComment);\n isLeadingComment = true;\n }\n line++;\n repeat = true;\n }\n } else if ((curr = charAt(offset)) === \"*\") { /* Block */\n // check for /** (regular comment mode) or /* (alternate comment mode)\n start = offset + 1;\n isDoc = alternateCommentMode || charAt(start) === \"*\";\n do {\n if (curr === \"\\n\") {\n ++line;\n }\n if (++offset === length) {\n throw illegal(\"comment\");\n }\n prev = curr;\n curr = charAt(offset);\n } while (prev !== \"*\" || curr !== \"/\");\n ++offset;\n if (isDoc) {\n setComment(start, offset - 2, isLeadingComment);\n isLeadingComment = true;\n }\n repeat = true;\n } else {\n return \"/\";\n }\n }\n } while (repeat);\n\n // offset !== length if we got here\n\n var end = offset;\n delimRe.lastIndex = 0;\n var delim = delimRe.test(charAt(end++));\n if (!delim)\n while (end < length && !delimRe.test(charAt(end)))\n ++end;\n var token = source.substring(offset, offset = end);\n if (token === \"\\\"\" || token === \"'\")\n stringDelim = token;\n return token;\n }\n\n /**\n * Pushes a token back to the stack.\n * @param {string} token Token\n * @returns {undefined}\n * @inner\n */\n function push(token) {\n stack.push(token);\n }\n\n /**\n * Peeks for the next token.\n * @returns {string|null} Token or `null` on eof\n * @inner\n */\n function peek() {\n if (!stack.length) {\n var token = next();\n if (token === null)\n return null;\n push(token);\n }\n return stack[0];\n }\n\n /**\n * Skips a token.\n * @param {string} expected Expected token\n * @param {boolean} [optional=false] Whether the token is optional\n * @returns {boolean} `true` when skipped, `false` if not\n * @throws {Error} When a required token is not present\n * @inner\n */\n function skip(expected, optional) {\n var actual = peek(),\n equals = actual === expected;\n if (equals) {\n next();\n return true;\n }\n if (!optional)\n throw illegal(\"token '\" + actual + \"', '\" + expected + \"' expected\");\n return false;\n }\n\n /**\n * Gets a comment.\n * @param {number} [trailingLine] Line number if looking for a trailing comment\n * @returns {string|null} Comment text\n * @inner\n */\n function cmnt(trailingLine) {\n var ret = null;\n var comment;\n if (trailingLine === undefined) {\n comment = comments[line - 1];\n delete comments[line - 1];\n if (comment && (alternateCommentMode || comment.type === \"*\" || comment.lineEmpty)) {\n ret = comment.leading ? comment.text : null;\n }\n } else {\n /* istanbul ignore else */\n if (lastCommentLine < trailingLine) {\n peek();\n }\n comment = comments[trailingLine];\n delete comments[trailingLine];\n if (comment && !comment.lineEmpty && (alternateCommentMode || comment.type === \"/\")) {\n ret = comment.leading ? null : comment.text;\n }\n }\n return ret;\n }\n\n return Object.defineProperty({\n next: next,\n peek: peek,\n push: push,\n skip: skip,\n cmnt: cmnt\n }, \"line\", {\n get: function() { return line; }\n });\n /* eslint-enable callback-return */\n}\n","\"use strict\";\nmodule.exports = Type;\n\n// extends Namespace\nvar Namespace = require(23);\n((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = \"Type\";\n\nvar Enum = require(15),\n OneOf = require(25),\n Field = require(16),\n MapField = require(20),\n Service = require(33),\n Message = require(21),\n Reader = require(27),\n Writer = require(42),\n util = require(37),\n encoder = require(14),\n decoder = require(13),\n verifier = require(40),\n converter = require(12),\n wrappers = require(41);\n\n/**\n * Constructs a new reflected message type instance.\n * @classdesc Reflected message type.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Message name\n * @param {Object.} [options] Declared options\n */\nfunction Type(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Message fields.\n * @type {Object.}\n */\n this.fields = {}; // toJSON, marker\n\n /**\n * Oneofs declared within this namespace, if any.\n * @type {Object.}\n */\n this.oneofs = undefined; // toJSON\n\n /**\n * Extension ranges, if any.\n * @type {number[][]}\n */\n this.extensions = undefined; // toJSON\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n /*?\n * Whether this type is a legacy group.\n * @type {boolean|undefined}\n */\n this.group = undefined; // toJSON\n\n /**\n * Cached fields by id.\n * @type {Object.|null}\n * @private\n */\n this._fieldsById = null;\n\n /**\n * Cached fields as an array.\n * @type {Field[]|null}\n * @private\n */\n this._fieldsArray = null;\n\n /**\n * Cached oneofs as an array.\n * @type {OneOf[]|null}\n * @private\n */\n this._oneofsArray = null;\n\n /**\n * Cached constructor.\n * @type {Constructor<{}>}\n * @private\n */\n this._ctor = null;\n}\n\nObject.defineProperties(Type.prototype, {\n\n /**\n * Message fields by id.\n * @name Type#fieldsById\n * @type {Object.}\n * @readonly\n */\n fieldsById: {\n get: function() {\n\n /* istanbul ignore if */\n if (this._fieldsById)\n return this._fieldsById;\n\n this._fieldsById = {};\n for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {\n var field = this.fields[names[i]],\n id = field.id;\n\n /* istanbul ignore if */\n if (this._fieldsById[id])\n throw Error(\"duplicate id \" + id + \" in \" + this);\n\n this._fieldsById[id] = field;\n }\n return this._fieldsById;\n }\n },\n\n /**\n * Fields of this message as an array for iteration.\n * @name Type#fieldsArray\n * @type {Field[]}\n * @readonly\n */\n fieldsArray: {\n get: function() {\n return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));\n }\n },\n\n /**\n * Oneofs of this message as an array for iteration.\n * @name Type#oneofsArray\n * @type {OneOf[]}\n * @readonly\n */\n oneofsArray: {\n get: function() {\n return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));\n }\n },\n\n /**\n * The registered constructor, if any registered, otherwise a generic constructor.\n * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.\n * @name Type#ctor\n * @type {Constructor<{}>}\n */\n ctor: {\n get: function() {\n return this._ctor || (this.ctor = Type.generateConstructor(this)());\n },\n set: function(ctor) {\n\n // Ensure proper prototype\n var prototype = ctor.prototype;\n if (!(prototype instanceof Message)) {\n (ctor.prototype = new Message()).constructor = ctor;\n util.merge(ctor.prototype, prototype);\n }\n\n // Classes and messages reference their reflected type\n ctor.$type = ctor.prototype.$type = this;\n\n // Mix in static methods\n util.merge(ctor, Message, true);\n\n this._ctor = ctor;\n\n // Messages have non-enumerable default values on their prototype\n var i = 0;\n for (; i < /* initializes */ this.fieldsArray.length; ++i)\n this._fieldsArray[i].resolve(); // ensures a proper value\n\n // Messages have non-enumerable getters and setters for each virtual oneof field\n var ctorProperties = {};\n for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i)\n ctorProperties[this._oneofsArray[i].resolve().name] = {\n get: util.oneOfGetter(this._oneofsArray[i].oneof),\n set: util.oneOfSetter(this._oneofsArray[i].oneof)\n };\n if (i)\n Object.defineProperties(ctor.prototype, ctorProperties);\n }\n }\n});\n\n/**\n * Generates a constructor function for the specified type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nType.generateConstructor = function generateConstructor(mtype) {\n /* eslint-disable no-unexpected-multiline */\n var gen = util.codegen([\"p\"], mtype.name);\n // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype\n for (var i = 0, field; i < mtype.fieldsArray.length; ++i)\n if ((field = mtype._fieldsArray[i]).map) gen\n (\"this%s={}\", util.safeProp(field.name));\n else if (field.repeated) gen\n (\"this%s=[]\", util.safeProp(field.name));\n return gen\n (\"if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors\n * @property {Object.} fields Field descriptors\n * @property {number[][]} [extensions] Extension ranges\n * @property {Array.} [reserved] Reserved ranges\n * @property {boolean} [group=false] Whether a legacy group or not\n */\n\n/**\n * Creates a message type from a message type descriptor.\n * @param {string} name Message name\n * @param {IType} json Message type descriptor\n * @returns {Type} Created message type\n */\nType.fromJSON = function fromJSON(name, json) {\n var type = new Type(name, json.options);\n type.extensions = json.extensions;\n type.reserved = json.reserved;\n var names = Object.keys(json.fields),\n i = 0;\n for (; i < names.length; ++i)\n type.add(\n ( typeof json.fields[names[i]].keyType !== \"undefined\"\n ? MapField.fromJSON\n : Field.fromJSON )(names[i], json.fields[names[i]])\n );\n if (json.oneofs)\n for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i)\n type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]]));\n if (json.nested)\n for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) {\n var nested = json.nested[names[i]];\n type.add( // most to least likely\n ( nested.id !== undefined\n ? Field.fromJSON\n : nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n if (json.extensions && json.extensions.length)\n type.extensions = json.extensions;\n if (json.reserved && json.reserved.length)\n type.reserved = json.reserved;\n if (json.group)\n type.group = true;\n if (json.comment)\n type.comment = json.comment;\n if (json.edition)\n type._edition = json.edition;\n type._defaultEdition = \"proto3\"; // For backwards-compatibility.\n return type;\n};\n\n/**\n * Converts this message type to a message type descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IType} Message type descriptor\n */\nType.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"edition\" , this._editionToJSON(),\n \"options\" , inherited && inherited.options || undefined,\n \"oneofs\" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),\n \"fields\" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {},\n \"extensions\" , this.extensions && this.extensions.length ? this.extensions : undefined,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"group\" , this.group || undefined,\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nType.prototype.resolveAll = function resolveAll() {\n if (!this._needsRecursiveResolve) return this;\n\n Namespace.prototype.resolveAll.call(this);\n var oneofs = this.oneofsArray; i = 0;\n while (i < oneofs.length)\n oneofs[i++].resolve();\n var fields = this.fieldsArray, i = 0;\n while (i < fields.length)\n fields[i++].resolve();\n return this;\n};\n\n/**\n * @override\n */\nType.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) {\n if (!this._needsRecursiveFeatureResolution) return this;\n\n edition = this._edition || edition;\n\n Namespace.prototype._resolveFeaturesRecursive.call(this, edition);\n this.oneofsArray.forEach(oneof => {\n oneof._resolveFeatures(edition);\n });\n this.fieldsArray.forEach(field => {\n field._resolveFeatures(edition);\n });\n return this;\n};\n\n/**\n * @override\n */\nType.prototype.get = function get(name) {\n return this.fields[name]\n || this.oneofs && this.oneofs[name]\n || this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Adds a nested object to this type.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id\n */\nType.prototype.add = function add(object) {\n\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Field && object.extend === undefined) {\n // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.\n // The root object takes care of adding distinct sister-fields to the respective extended\n // type instead.\n\n // avoids calling the getter if not absolutely necessary because it's called quite frequently\n if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id])\n throw Error(\"duplicate id \" + object.id + \" in \" + this);\n if (this.isReservedId(object.id))\n throw Error(\"id \" + object.id + \" is reserved in \" + this);\n if (this.isReservedName(object.name))\n throw Error(\"name '\" + object.name + \"' is reserved in \" + this);\n\n if (object.parent)\n object.parent.remove(object);\n this.fields[object.name] = object;\n object.message = this;\n object.onAdd(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n if (!this.oneofs)\n this.oneofs = {};\n this.oneofs[object.name] = object;\n object.onAdd(this);\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * Removes a nested object from this type.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this type\n */\nType.prototype.remove = function remove(object) {\n if (object instanceof Field && object.extend === undefined) {\n // See Type#add for the reason why extension fields are excluded here.\n\n /* istanbul ignore if */\n if (!this.fields || this.fields[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.fields[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n\n /* istanbul ignore if */\n if (!this.oneofs || this.oneofs[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.oneofs[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message<{}>} Message instance\n */\nType.prototype.create = function create(properties) {\n return new this.ctor(properties);\n};\n\n/**\n * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.\n * @returns {Type} `this`\n */\nType.prototype.setup = function setup() {\n // Sets up everything at once so that the prototype chain does not have to be re-evaluated\n // multiple times (V8, soft-deopt prototype-check).\n\n var fullName = this.fullName,\n types = [];\n for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i)\n types.push(this._fieldsArray[i].resolve().resolvedType);\n\n // Replace setup methods with type-specific generated functions\n this.encode = encoder(this)({\n Writer : Writer,\n types : types,\n util : util\n });\n this.decode = decoder(this)({\n Reader : Reader,\n types : types,\n util : util\n });\n this.verify = verifier(this)({\n types : types,\n util : util\n });\n this.fromObject = converter.fromObject(this)({\n types : types,\n util : util\n });\n this.toObject = converter.toObject(this)({\n types : types,\n util : util\n });\n\n // Inject custom wrappers for common types\n var wrapper = wrappers[fullName];\n if (wrapper) {\n var originalThis = Object.create(this);\n // if (wrapper.fromObject) {\n originalThis.fromObject = this.fromObject;\n this.fromObject = wrapper.fromObject.bind(originalThis);\n // }\n // if (wrapper.toObject) {\n originalThis.toObject = this.toObject;\n this.toObject = wrapper.toObject.bind(originalThis);\n // }\n }\n\n return this;\n};\n\n/**\n * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encode = function encode_setup(message, writer) {\n return this.setup().encode(message, writer); // overrides this method\n};\n\n/**\n * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encodeDelimited = function encodeDelimited(message, writer) {\n return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();\n};\n\n/**\n * Decodes a message of this type.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @param {number} [length] Length of the message, if known beforehand\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError<{}>} If required fields are missing\n */\nType.prototype.decode = function decode_setup(reader, length) {\n return this.setup().decode(reader, length); // overrides this method\n};\n\n/**\n * Decodes a message of this type preceeded by its byte length as a varint.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError} If required fields are missing\n */\nType.prototype.decodeDelimited = function decodeDelimited(reader) {\n if (!(reader instanceof Reader))\n reader = Reader.create(reader);\n return this.decode(reader, reader.uint32());\n};\n\n/**\n * Verifies that field values are valid and that required fields are present.\n * @param {Object.} message Plain object to verify\n * @returns {null|string} `null` if valid, otherwise the reason why it is not\n */\nType.prototype.verify = function verify_setup(message) {\n return this.setup().verify(message); // overrides this method\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object to convert\n * @returns {Message<{}>} Message instance\n */\nType.prototype.fromObject = function fromObject(object) {\n return this.setup().fromObject(object);\n};\n\n/**\n * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}.\n * @interface IConversionOptions\n * @property {Function} [longs] Long conversion type.\n * Valid values are `String` and `Number` (the global types).\n * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.\n * @property {Function} [enums] Enum value conversion type.\n * Only valid value is `String` (the global type).\n * Defaults to copy the present value, which is the numeric id.\n * @property {Function} [bytes] Bytes value conversion type.\n * Valid values are `Array` and (a base64 encoded) `String` (the global types).\n * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.\n * @property {boolean} [defaults=false] Also sets default values on the resulting object\n * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false`\n * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false`\n * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any\n * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings\n */\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n */\nType.prototype.toObject = function toObject(message, options) {\n return this.setup().toObject(message, options);\n};\n\n/**\n * Decorator function as returned by {@link Type.d} (TypeScript).\n * @typedef TypeDecorator\n * @type {function}\n * @param {Constructor} target Target constructor\n * @returns {undefined}\n * @template T extends Message\n */\n\n/**\n * Type decorator (TypeScript).\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {TypeDecorator} Decorator function\n * @template T extends Message\n */\nType.d = function decorateType(typeName) {\n return function typeDecorator(target) {\n util.decorateType(target, typeName);\n };\n};\n","\"use strict\";\n\n/**\n * Common type constants.\n * @namespace\n */\nvar types = exports;\n\nvar util = require(37);\n\nvar s = [\n \"double\", // 0\n \"float\", // 1\n \"int32\", // 2\n \"uint32\", // 3\n \"sint32\", // 4\n \"fixed32\", // 5\n \"sfixed32\", // 6\n \"int64\", // 7\n \"uint64\", // 8\n \"sint64\", // 9\n \"fixed64\", // 10\n \"sfixed64\", // 11\n \"bool\", // 12\n \"string\", // 13\n \"bytes\" // 14\n];\n\nfunction bake(values, offset) {\n var i = 0, o = {};\n offset |= 0;\n while (i < values.length) o[s[i + offset]] = values[i++];\n return o;\n}\n\n/**\n * Basic type wire types.\n * @type {Object.}\n * @const\n * @property {number} double=1 Fixed64 wire type\n * @property {number} float=5 Fixed32 wire type\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n * @property {number} string=2 Ldelim wire type\n * @property {number} bytes=2 Ldelim wire type\n */\ntypes.basic = bake([\n /* double */ 1,\n /* float */ 5,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0,\n /* string */ 2,\n /* bytes */ 2\n]);\n\n/**\n * Basic type defaults.\n * @type {Object.}\n * @const\n * @property {number} double=0 Double default\n * @property {number} float=0 Float default\n * @property {number} int32=0 Int32 default\n * @property {number} uint32=0 Uint32 default\n * @property {number} sint32=0 Sint32 default\n * @property {number} fixed32=0 Fixed32 default\n * @property {number} sfixed32=0 Sfixed32 default\n * @property {number} int64=0 Int64 default\n * @property {number} uint64=0 Uint64 default\n * @property {number} sint64=0 Sint32 default\n * @property {number} fixed64=0 Fixed64 default\n * @property {number} sfixed64=0 Sfixed64 default\n * @property {boolean} bool=false Bool default\n * @property {string} string=\"\" String default\n * @property {Array.} bytes=Array(0) Bytes default\n * @property {null} message=null Message default\n */\ntypes.defaults = bake([\n /* double */ 0,\n /* float */ 0,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 0,\n /* sfixed32 */ 0,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 0,\n /* sfixed64 */ 0,\n /* bool */ false,\n /* string */ \"\",\n /* bytes */ util.emptyArray,\n /* message */ null\n]);\n\n/**\n * Basic long type wire types.\n * @type {Object.}\n * @const\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n */\ntypes.long = bake([\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1\n], 7);\n\n/**\n * Allowed types for map keys with their associated wire type.\n * @type {Object.}\n * @const\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n * @property {number} string=2 Ldelim wire type\n */\ntypes.mapKey = bake([\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0,\n /* string */ 2\n], 2);\n\n/**\n * Allowed types for packed repeated fields with their associated wire type.\n * @type {Object.}\n * @const\n * @property {number} double=1 Fixed64 wire type\n * @property {number} float=5 Fixed32 wire type\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n */\ntypes.packed = bake([\n /* double */ 1,\n /* float */ 5,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0\n]);\n","\"use strict\";\n\n/**\n * Various utility functions.\n * @namespace\n */\nvar util = module.exports = require(39);\n\nvar roots = require(30);\n\nvar Type, // cyclic\n Enum;\n\nutil.codegen = require(3);\nutil.fetch = require(5);\nutil.path = require(8);\n\n/**\n * Node's fs module if available.\n * @type {Object.}\n */\nutil.fs = util.inquire(\"fs\");\n\n/**\n * Converts an object's values to an array.\n * @param {Object.} object Object to convert\n * @returns {Array.<*>} Converted array\n */\nutil.toArray = function toArray(object) {\n if (object) {\n var keys = Object.keys(object),\n array = new Array(keys.length),\n index = 0;\n while (index < keys.length)\n array[index] = object[keys[index++]];\n return array;\n }\n return [];\n};\n\n/**\n * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values.\n * @param {Array.<*>} array Array to convert\n * @returns {Object.} Converted object\n */\nutil.toObject = function toObject(array) {\n var object = {},\n index = 0;\n while (index < array.length) {\n var key = array[index++],\n val = array[index++];\n if (val !== undefined)\n object[key] = val;\n }\n return object;\n};\n\nvar safePropBackslashRe = /\\\\/g,\n safePropQuoteRe = /\"/g;\n\n/**\n * Tests whether the specified name is a reserved word in JS.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nutil.isReserved = function isReserved(name) {\n return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name);\n};\n\n/**\n * Returns a safe property accessor for the specified property name.\n * @param {string} prop Property name\n * @returns {string} Safe accessor\n */\nutil.safeProp = function safeProp(prop) {\n if (!/^[$\\w_]+$/.test(prop) || util.isReserved(prop))\n return \"[\\\"\" + prop.replace(safePropBackslashRe, \"\\\\\\\\\").replace(safePropQuoteRe, \"\\\\\\\"\") + \"\\\"]\";\n return \".\" + prop;\n};\n\n/**\n * Converts the first character of a string to upper case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.ucFirst = function ucFirst(str) {\n return str.charAt(0).toUpperCase() + str.substring(1);\n};\n\nvar camelCaseRe = /_([a-z])/g;\n\n/**\n * Converts a string to camel case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.camelCase = function camelCase(str) {\n return str.substring(0, 1)\n + str.substring(1)\n .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); });\n};\n\n/**\n * Compares reflected fields by id.\n * @param {Field} a First field\n * @param {Field} b Second field\n * @returns {number} Comparison value\n */\nutil.compareFieldsById = function compareFieldsById(a, b) {\n return a.id - b.id;\n};\n\n/**\n * Decorator helper for types (TypeScript).\n * @param {Constructor} ctor Constructor function\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {Type} Reflected type\n * @template T extends Message\n * @property {Root} root Decorators root\n */\nutil.decorateType = function decorateType(ctor, typeName) {\n\n /* istanbul ignore if */\n if (ctor.$type) {\n if (typeName && ctor.$type.name !== typeName) {\n util.decorateRoot.remove(ctor.$type);\n ctor.$type.name = typeName;\n util.decorateRoot.add(ctor.$type);\n }\n return ctor.$type;\n }\n\n /* istanbul ignore next */\n if (!Type)\n Type = require(35);\n\n var type = new Type(typeName || ctor.name);\n util.decorateRoot.add(type);\n type.ctor = ctor; // sets up .encode, .decode etc.\n Object.defineProperty(ctor, \"$type\", { value: type, enumerable: false });\n Object.defineProperty(ctor.prototype, \"$type\", { value: type, enumerable: false });\n return type;\n};\n\nvar decorateEnumIndex = 0;\n\n/**\n * Decorator helper for enums (TypeScript).\n * @param {Object} object Enum object\n * @returns {Enum} Reflected enum\n */\nutil.decorateEnum = function decorateEnum(object) {\n\n /* istanbul ignore if */\n if (object.$type)\n return object.$type;\n\n /* istanbul ignore next */\n if (!Enum)\n Enum = require(15);\n\n var enm = new Enum(\"Enum\" + decorateEnumIndex++, object);\n util.decorateRoot.add(enm);\n Object.defineProperty(object, \"$type\", { value: enm, enumerable: false });\n return enm;\n};\n\n\n/**\n * Sets the value of a property by property path. If a value already exists, it is turned to an array\n * @param {Object.} dst Destination object\n * @param {string} path dot '.' delimited path of the property to set\n * @param {Object} value the value to set\n * @param {boolean|undefined} [ifNotSet] Sets the option only if it isn't currently set\n * @returns {Object.} Destination object\n */\nutil.setProperty = function setProperty(dst, path, value, ifNotSet) {\n function setProp(dst, path, value) {\n var part = path.shift();\n if (part === \"__proto__\" || part === \"prototype\") {\n return dst;\n }\n if (path.length > 0) {\n dst[part] = setProp(dst[part] || {}, path, value);\n } else {\n var prevValue = dst[part];\n if (prevValue && ifNotSet)\n return dst;\n if (prevValue)\n value = [].concat(prevValue).concat(value);\n dst[part] = value;\n }\n return dst;\n }\n\n if (typeof dst !== \"object\")\n throw TypeError(\"dst must be an object\");\n if (!path)\n throw TypeError(\"path must be specified\");\n\n path = path.split(\".\");\n return setProp(dst, path, value);\n};\n\n/**\n * Decorator root (TypeScript).\n * @name util.decorateRoot\n * @type {Root}\n * @readonly\n */\nObject.defineProperty(util, \"decorateRoot\", {\n get: function() {\n return roots[\"decorated\"] || (roots[\"decorated\"] = new (require(29))());\n }\n});\n","\"use strict\";\nmodule.exports = LongBits;\n\nvar util = require(39);\n\n/**\n * Constructs new long bits.\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @constructor\n * @param {number} lo Low 32 bits, unsigned\n * @param {number} hi High 32 bits, unsigned\n */\nfunction LongBits(lo, hi) {\n\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits.\n * @type {number}\n */\n this.lo = lo >>> 0;\n\n /**\n * High bits.\n * @type {number}\n */\n this.hi = hi >>> 0;\n}\n\n/**\n * Zero bits.\n * @memberof util.LongBits\n * @type {util.LongBits}\n */\nvar zero = LongBits.zero = new LongBits(0, 0);\n\nzero.toNumber = function() { return 0; };\nzero.zzEncode = zero.zzDecode = function() { return this; };\nzero.length = function() { return 1; };\n\n/**\n * Zero hash.\n * @memberof util.LongBits\n * @type {string}\n */\nvar zeroHash = LongBits.zeroHash = \"\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n/**\n * Constructs new long bits from the specified number.\n * @param {number} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.fromNumber = function fromNumber(value) {\n if (value === 0)\n return zero;\n var sign = value < 0;\n if (sign)\n value = -value;\n var lo = value >>> 0,\n hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295)\n hi = 0;\n }\n }\n return new LongBits(lo, hi);\n};\n\n/**\n * Constructs new long bits from a number, long or string.\n * @param {Long|number|string} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.from = function from(value) {\n if (typeof value === \"number\")\n return LongBits.fromNumber(value);\n if (util.isString(value)) {\n /* istanbul ignore else */\n if (util.Long)\n value = util.Long.fromString(value);\n else\n return LongBits.fromNumber(parseInt(value, 10));\n }\n return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n};\n\n/**\n * Converts this long bits to a possibly unsafe JavaScript number.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {number} Possibly unsafe number\n */\nLongBits.prototype.toNumber = function toNumber(unsigned) {\n if (!unsigned && this.hi >>> 31) {\n var lo = ~this.lo + 1 >>> 0,\n hi = ~this.hi >>> 0;\n if (!lo)\n hi = hi + 1 >>> 0;\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n};\n\n/**\n * Converts this long bits to a long.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long} Long\n */\nLongBits.prototype.toLong = function toLong(unsigned) {\n return util.Long\n ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))\n /* istanbul ignore next */\n : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };\n};\n\nvar charCodeAt = String.prototype.charCodeAt;\n\n/**\n * Constructs new long bits from the specified 8 characters long hash.\n * @param {string} hash Hash\n * @returns {util.LongBits} Bits\n */\nLongBits.fromHash = function fromHash(hash) {\n if (hash === zeroHash)\n return zero;\n return new LongBits(\n ( charCodeAt.call(hash, 0)\n | charCodeAt.call(hash, 1) << 8\n | charCodeAt.call(hash, 2) << 16\n | charCodeAt.call(hash, 3) << 24) >>> 0\n ,\n ( charCodeAt.call(hash, 4)\n | charCodeAt.call(hash, 5) << 8\n | charCodeAt.call(hash, 6) << 16\n | charCodeAt.call(hash, 7) << 24) >>> 0\n );\n};\n\n/**\n * Converts this long bits to a 8 characters long hash.\n * @returns {string} Hash\n */\nLongBits.prototype.toHash = function toHash() {\n return String.fromCharCode(\n this.lo & 255,\n this.lo >>> 8 & 255,\n this.lo >>> 16 & 255,\n this.lo >>> 24 ,\n this.hi & 255,\n this.hi >>> 8 & 255,\n this.hi >>> 16 & 255,\n this.hi >>> 24\n );\n};\n\n/**\n * Zig-zag encodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzEncode = function zzEncode() {\n var mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = ( this.lo << 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Zig-zag decodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzDecode = function zzDecode() {\n var mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = ( this.hi >>> 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Calculates the length of this longbits when encoded as a varint.\n * @returns {number} Length\n */\nLongBits.prototype.length = function length() {\n var part0 = this.lo,\n part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,\n part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n};\n","\"use strict\";\nvar util = exports;\n\n// used to return a Promise where callback is omitted\nutil.asPromise = require(1);\n\n// converts to / from base64 encoded strings\nutil.base64 = require(2);\n\n// base class of rpc.Service\nutil.EventEmitter = require(4);\n\n// float handling accross browsers\nutil.float = require(6);\n\n// requires modules optionally and hides the call from bundlers\nutil.inquire = require(7);\n\n// converts to / from utf8 encoded strings\nutil.utf8 = require(10);\n\n// provides a node-like buffer pool in the browser\nutil.pool = require(9);\n\n// utility to work with the low and high bits of a 64 bit value\nutil.LongBits = require(38);\n\n/**\n * Whether running within node or not.\n * @memberof util\n * @type {boolean}\n */\nutil.isNode = Boolean(typeof global !== \"undefined\"\n && global\n && global.process\n && global.process.versions\n && global.process.versions.node);\n\n/**\n * Global object reference.\n * @memberof util\n * @type {Object}\n */\nutil.global = util.isNode && global\n || typeof window !== \"undefined\" && window\n || typeof self !== \"undefined\" && self\n || this; // eslint-disable-line no-invalid-this\n\n/**\n * An immuable empty array.\n * @memberof util\n * @type {Array.<*>}\n * @const\n */\nutil.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes\n\n/**\n * An immutable empty object.\n * @type {Object}\n * @const\n */\nutil.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes\n\n/**\n * Tests if the specified value is an integer.\n * @function\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is an integer\n */\nutil.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {\n return typeof value === \"number\" && isFinite(value) && Math.floor(value) === value;\n};\n\n/**\n * Tests if the specified value is a string.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a string\n */\nutil.isString = function isString(value) {\n return typeof value === \"string\" || value instanceof String;\n};\n\n/**\n * Tests if the specified value is a non-null object.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a non-null object\n */\nutil.isObject = function isObject(value) {\n return value && typeof value === \"object\";\n};\n\n/**\n * Checks if a property on a message is considered to be present.\n * This is an alias of {@link util.isSet}.\n * @function\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isset =\n\n/**\n * Checks if a property on a message is considered to be present.\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isSet = function isSet(obj, prop) {\n var value = obj[prop];\n if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins\n return typeof value !== \"object\" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;\n return false;\n};\n\n/**\n * Any compatible Buffer instance.\n * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.\n * @interface Buffer\n * @extends Uint8Array\n */\n\n/**\n * Node's Buffer class if available.\n * @type {Constructor}\n */\nutil.Buffer = (function() {\n try {\n var Buffer = util.inquire(\"buffer\").Buffer;\n // refuse to use non-node buffers if not explicitly assigned (perf reasons):\n return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;\n } catch (e) {\n /* istanbul ignore next */\n return null;\n }\n})();\n\n// Internal alias of or polyfull for Buffer.from.\nutil._Buffer_from = null;\n\n// Internal alias of or polyfill for Buffer.allocUnsafe.\nutil._Buffer_allocUnsafe = null;\n\n/**\n * Creates a new buffer of whatever type supported by the environment.\n * @param {number|number[]} [sizeOrArray=0] Buffer size or number array\n * @returns {Uint8Array|Buffer} Buffer\n */\nutil.newBuffer = function newBuffer(sizeOrArray) {\n /* istanbul ignore next */\n return typeof sizeOrArray === \"number\"\n ? util.Buffer\n ? util._Buffer_allocUnsafe(sizeOrArray)\n : new util.Array(sizeOrArray)\n : util.Buffer\n ? util._Buffer_from(sizeOrArray)\n : typeof Uint8Array === \"undefined\"\n ? sizeOrArray\n : new Uint8Array(sizeOrArray);\n};\n\n/**\n * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.\n * @type {Constructor}\n */\nutil.Array = typeof Uint8Array !== \"undefined\" ? Uint8Array /* istanbul ignore next */ : Array;\n\n/**\n * Any compatible Long instance.\n * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.\n * @interface Long\n * @property {number} low Low bits\n * @property {number} high High bits\n * @property {boolean} unsigned Whether unsigned or not\n */\n\n/**\n * Long.js's Long class if available.\n * @type {Constructor}\n */\nutil.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long\n || /* istanbul ignore next */ util.global.Long\n || util.inquire(\"long\");\n\n/**\n * Regular expression used to verify 2 bit (`bool`) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key2Re = /^true|false|0|1$/;\n\n/**\n * Regular expression used to verify 32 bit (`int32` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key32Re = /^-?(?:0|[1-9][0-9]*)$/;\n\n/**\n * Regular expression used to verify 64 bit (`int64` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key64Re = /^(?:[\\\\x00-\\\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;\n\n/**\n * Converts a number or long to an 8 characters long hash string.\n * @param {Long|number} value Value to convert\n * @returns {string} Hash\n */\nutil.longToHash = function longToHash(value) {\n return value\n ? util.LongBits.from(value).toHash()\n : util.LongBits.zeroHash;\n};\n\n/**\n * Converts an 8 characters long hash string to a long or number.\n * @param {string} hash Hash\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long|number} Original value\n */\nutil.longFromHash = function longFromHash(hash, unsigned) {\n var bits = util.LongBits.fromHash(hash);\n if (util.Long)\n return util.Long.fromBits(bits.lo, bits.hi, unsigned);\n return bits.toNumber(Boolean(unsigned));\n};\n\n/**\n * Merges the properties of the source object into the destination object.\n * @memberof util\n * @param {Object.} dst Destination object\n * @param {Object.} src Source object\n * @param {boolean} [ifNotSet=false] Merges only if the key is not already set\n * @returns {Object.} Destination object\n */\nfunction merge(dst, src, ifNotSet) { // used by converters\n for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)\n if (dst[keys[i]] === undefined || !ifNotSet)\n dst[keys[i]] = src[keys[i]];\n return dst;\n}\n\nutil.merge = merge;\n\n/**\n * Converts the first character of a string to lower case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.lcFirst = function lcFirst(str) {\n return str.charAt(0).toLowerCase() + str.substring(1);\n};\n\n/**\n * Creates a custom error constructor.\n * @memberof util\n * @param {string} name Error name\n * @returns {Constructor} Custom error constructor\n */\nfunction newError(name) {\n\n function CustomError(message, properties) {\n\n if (!(this instanceof CustomError))\n return new CustomError(message, properties);\n\n // Error.call(this, message);\n // ^ just returns a new error instance because the ctor can be called as a function\n\n Object.defineProperty(this, \"message\", { get: function() { return message; } });\n\n /* istanbul ignore next */\n if (Error.captureStackTrace) // node\n Error.captureStackTrace(this, CustomError);\n else\n Object.defineProperty(this, \"stack\", { value: new Error().stack || \"\" });\n\n if (properties)\n merge(this, properties);\n }\n\n CustomError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: CustomError,\n writable: true,\n enumerable: false,\n configurable: true,\n },\n name: {\n get: function get() { return name; },\n set: undefined,\n enumerable: false,\n // configurable: false would accurately preserve the behavior of\n // the original, but I'm guessing that was not intentional.\n // For an actual error subclass, this property would\n // be configurable.\n configurable: true,\n },\n toString: {\n value: function value() { return this.name + \": \" + this.message; },\n writable: true,\n enumerable: false,\n configurable: true,\n },\n });\n\n return CustomError;\n}\n\nutil.newError = newError;\n\n/**\n * Constructs a new protocol error.\n * @classdesc Error subclass indicating a protocol specifc error.\n * @memberof util\n * @extends Error\n * @template T extends Message\n * @constructor\n * @param {string} message Error message\n * @param {Object.} [properties] Additional properties\n * @example\n * try {\n * MyMessage.decode(someBuffer); // throws if required fields are missing\n * } catch (e) {\n * if (e instanceof ProtocolError && e.instance)\n * console.log(\"decoded so far: \" + JSON.stringify(e.instance));\n * }\n */\nutil.ProtocolError = newError(\"ProtocolError\");\n\n/**\n * So far decoded message instance.\n * @name util.ProtocolError#instance\n * @type {Message}\n */\n\n/**\n * A OneOf getter as returned by {@link util.oneOfGetter}.\n * @typedef OneOfGetter\n * @type {function}\n * @returns {string|undefined} Set field name, if any\n */\n\n/**\n * Builds a getter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfGetter} Unbound getter\n */\nutil.oneOfGetter = function getOneOf(fieldNames) {\n var fieldMap = {};\n for (var i = 0; i < fieldNames.length; ++i)\n fieldMap[fieldNames[i]] = 1;\n\n /**\n * @returns {string|undefined} Set field name, if any\n * @this Object\n * @ignore\n */\n return function() { // eslint-disable-line consistent-return\n for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)\n if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)\n return keys[i];\n };\n};\n\n/**\n * A OneOf setter as returned by {@link util.oneOfSetter}.\n * @typedef OneOfSetter\n * @type {function}\n * @param {string|undefined} value Field name\n * @returns {undefined}\n */\n\n/**\n * Builds a setter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfSetter} Unbound setter\n */\nutil.oneOfSetter = function setOneOf(fieldNames) {\n\n /**\n * @param {string} name Field name\n * @returns {undefined}\n * @this Object\n * @ignore\n */\n return function(name) {\n for (var i = 0; i < fieldNames.length; ++i)\n if (fieldNames[i] !== name)\n delete this[fieldNames[i]];\n };\n};\n\n/**\n * Default conversion options used for {@link Message#toJSON} implementations.\n *\n * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:\n *\n * - Longs become strings\n * - Enums become string keys\n * - Bytes become base64 encoded strings\n * - (Sub-)Messages become plain objects\n * - Maps become plain objects with all string keys\n * - Repeated fields become arrays\n * - NaN and Infinity for float and double fields become strings\n *\n * @type {IConversionOptions}\n * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json\n */\nutil.toJSONOptions = {\n longs: String,\n enums: String,\n bytes: String,\n json: true\n};\n\n// Sets up buffer utility according to the environment (called in index-minimal)\nutil._configure = function() {\n var Buffer = util.Buffer;\n /* istanbul ignore if */\n if (!Buffer) {\n util._Buffer_from = util._Buffer_allocUnsafe = null;\n return;\n }\n // because node 4.x buffers are incompatible & immutable\n // see: https://github.com/dcodeIO/protobuf.js/pull/665\n util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||\n /* istanbul ignore next */\n function Buffer_from(value, encoding) {\n return new Buffer(value, encoding);\n };\n util._Buffer_allocUnsafe = Buffer.allocUnsafe ||\n /* istanbul ignore next */\n function Buffer_allocUnsafe(size) {\n return new Buffer(size);\n };\n};\n","\"use strict\";\nmodule.exports = verifier;\n\nvar Enum = require(15),\n util = require(37);\n\nfunction invalid(field, expected) {\n return field.name + \": \" + expected + (field.repeated && expected !== \"array\" ? \"[]\" : field.map && expected !== \"object\" ? \"{k:\"+field.keyType+\"}\" : \"\") + \" expected\";\n}\n\n/**\n * Generates a partial value verifier.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {number} fieldIndex Field index\n * @param {string} ref Variable reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genVerifyValue(gen, field, fieldIndex, ref) {\n /* eslint-disable no-unexpected-multiline */\n if (field.resolvedType) {\n if (field.resolvedType instanceof Enum) { gen\n (\"switch(%s){\", ref)\n (\"default:\")\n (\"return%j\", invalid(field, \"enum value\"));\n for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen\n (\"case %i:\", field.resolvedType.values[keys[j]]);\n gen\n (\"break\")\n (\"}\");\n } else {\n gen\n (\"{\")\n (\"var e=types[%i].verify(%s);\", fieldIndex, ref)\n (\"if(e)\")\n (\"return%j+e\", field.name + \".\")\n (\"}\");\n }\n } else {\n switch (field.type) {\n case \"int32\":\n case \"uint32\":\n case \"sint32\":\n case \"fixed32\":\n case \"sfixed32\": gen\n (\"if(!util.isInteger(%s))\", ref)\n (\"return%j\", invalid(field, \"integer\"));\n break;\n case \"int64\":\n case \"uint64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))\", ref, ref, ref, ref)\n (\"return%j\", invalid(field, \"integer|Long\"));\n break;\n case \"float\":\n case \"double\": gen\n (\"if(typeof %s!==\\\"number\\\")\", ref)\n (\"return%j\", invalid(field, \"number\"));\n break;\n case \"bool\": gen\n (\"if(typeof %s!==\\\"boolean\\\")\", ref)\n (\"return%j\", invalid(field, \"boolean\"));\n break;\n case \"string\": gen\n (\"if(!util.isString(%s))\", ref)\n (\"return%j\", invalid(field, \"string\"));\n break;\n case \"bytes\": gen\n (\"if(!(%s&&typeof %s.length===\\\"number\\\"||util.isString(%s)))\", ref, ref, ref)\n (\"return%j\", invalid(field, \"buffer\"));\n break;\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline */\n}\n\n/**\n * Generates a partial key verifier.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {string} ref Variable reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genVerifyKey(gen, field, ref) {\n /* eslint-disable no-unexpected-multiline */\n switch (field.keyType) {\n case \"int32\":\n case \"uint32\":\n case \"sint32\":\n case \"fixed32\":\n case \"sfixed32\": gen\n (\"if(!util.key32Re.test(%s))\", ref)\n (\"return%j\", invalid(field, \"integer key\"));\n break;\n case \"int64\":\n case \"uint64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(!util.key64Re.test(%s))\", ref) // see comment above: x is ok, d is not\n (\"return%j\", invalid(field, \"integer|Long key\"));\n break;\n case \"bool\": gen\n (\"if(!util.key2Re.test(%s))\", ref)\n (\"return%j\", invalid(field, \"boolean key\"));\n break;\n }\n return gen;\n /* eslint-enable no-unexpected-multiline */\n}\n\n/**\n * Generates a verifier specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nfunction verifier(mtype) {\n /* eslint-disable no-unexpected-multiline */\n\n var gen = util.codegen([\"m\"], mtype.name + \"$verify\")\n (\"if(typeof m!==\\\"object\\\"||m===null)\")\n (\"return%j\", \"object expected\");\n var oneofs = mtype.oneofsArray,\n seenFirstField = {};\n if (oneofs.length) gen\n (\"var p={}\");\n\n for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {\n var field = mtype._fieldsArray[i].resolve(),\n ref = \"m\" + util.safeProp(field.name);\n\n if (field.optional) gen\n (\"if(%s!=null&&m.hasOwnProperty(%j)){\", ref, field.name); // !== undefined && !== null\n\n // map fields\n if (field.map) { gen\n (\"if(!util.isObject(%s))\", ref)\n (\"return%j\", invalid(field, \"object\"))\n (\"var k=Object.keys(%s)\", ref)\n (\"for(var i=0;i}\n * @const\n */\nvar wrappers = exports;\n\nvar Message = require(21);\n\n/**\n * From object converter part of an {@link IWrapper}.\n * @typedef WrapperFromObjectConverter\n * @type {function}\n * @param {Object.} object Plain object\n * @returns {Message<{}>} Message instance\n * @this Type\n */\n\n/**\n * To object converter part of an {@link IWrapper}.\n * @typedef WrapperToObjectConverter\n * @type {function}\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n * @this Type\n */\n\n/**\n * Common type wrapper part of {@link wrappers}.\n * @interface IWrapper\n * @property {WrapperFromObjectConverter} [fromObject] From object converter\n * @property {WrapperToObjectConverter} [toObject] To object converter\n */\n\n// Custom wrapper for Any\nwrappers[\".google.protobuf.Any\"] = {\n\n fromObject: function(object) {\n\n // unwrap value type if mapped\n if (object && object[\"@type\"]) {\n // Only use fully qualified type name after the last '/'\n var name = object[\"@type\"].substring(object[\"@type\"].lastIndexOf(\"/\") + 1);\n var type = this.lookup(name);\n /* istanbul ignore else */\n if (type) {\n // type_url does not accept leading \".\"\n var type_url = object[\"@type\"].charAt(0) === \".\" ?\n object[\"@type\"].slice(1) : object[\"@type\"];\n // type_url prefix is optional, but path seperator is required\n if (type_url.indexOf(\"/\") === -1) {\n type_url = \"/\" + type_url;\n }\n return this.create({\n type_url: type_url,\n value: type.encode(type.fromObject(object)).finish()\n });\n }\n }\n\n return this.fromObject(object);\n },\n\n toObject: function(message, options) {\n\n // Default prefix\n var googleApi = \"type.googleapis.com/\";\n var prefix = \"\";\n var name = \"\";\n\n // decode value if requested and unmapped\n if (options && options.json && message.type_url && message.value) {\n // Only use fully qualified type name after the last '/'\n name = message.type_url.substring(message.type_url.lastIndexOf(\"/\") + 1);\n // Separate the prefix used\n prefix = message.type_url.substring(0, message.type_url.lastIndexOf(\"/\") + 1);\n var type = this.lookup(name);\n /* istanbul ignore else */\n if (type)\n message = type.decode(message.value);\n }\n\n // wrap value if unmapped\n if (!(message instanceof this.ctor) && message instanceof Message) {\n var object = message.$type.toObject(message, options);\n var messageName = message.$type.fullName[0] === \".\" ?\n message.$type.fullName.slice(1) : message.$type.fullName;\n // Default to type.googleapis.com prefix if no prefix is used\n if (prefix === \"\") {\n prefix = googleApi;\n }\n name = prefix + messageName;\n object[\"@type\"] = name;\n return object;\n }\n\n return this.toObject(message, options);\n }\n};\n","\"use strict\";\nmodule.exports = Writer;\n\nvar util = require(39);\n\nvar BufferWriter; // cyclic\n\nvar LongBits = util.LongBits,\n base64 = util.base64,\n utf8 = util.utf8;\n\n/**\n * Constructs a new writer operation instance.\n * @classdesc Scheduled writer operation.\n * @constructor\n * @param {function(*, Uint8Array, number)} fn Function to call\n * @param {number} len Value byte length\n * @param {*} val Value to write\n * @ignore\n */\nfunction Op(fn, len, val) {\n\n /**\n * Function to call.\n * @type {function(Uint8Array, number, *)}\n */\n this.fn = fn;\n\n /**\n * Value byte length.\n * @type {number}\n */\n this.len = len;\n\n /**\n * Next operation.\n * @type {Writer.Op|undefined}\n */\n this.next = undefined;\n\n /**\n * Value to write.\n * @type {*}\n */\n this.val = val; // type varies\n}\n\n/* istanbul ignore next */\nfunction noop() {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance.\n * @classdesc Copied writer state.\n * @memberof Writer\n * @constructor\n * @param {Writer} writer Writer to copy state from\n * @ignore\n */\nfunction State(writer) {\n\n /**\n * Current head.\n * @type {Writer.Op}\n */\n this.head = writer.head;\n\n /**\n * Current tail.\n * @type {Writer.Op}\n */\n this.tail = writer.tail;\n\n /**\n * Current buffer length.\n * @type {number}\n */\n this.len = writer.len;\n\n /**\n * Next state.\n * @type {State|null}\n */\n this.next = writer.states;\n}\n\n/**\n * Constructs a new writer instance.\n * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n */\nfunction Writer() {\n\n /**\n * Current length.\n * @type {number}\n */\n this.len = 0;\n\n /**\n * Operations head.\n * @type {Object}\n */\n this.head = new Op(noop, 0, 0);\n\n /**\n * Operations tail\n * @type {Object}\n */\n this.tail = this.head;\n\n /**\n * Linked forked states.\n * @type {Object|null}\n */\n this.states = null;\n\n // When a value is written, the writer calculates its byte length and puts it into a linked\n // list of operations to perform when finish() is called. This both allows us to allocate\n // buffers of the exact required size and reduces the amount of work we have to do compared\n // to first calculating over objects and then encoding over objects. In our case, the encoding\n // part is just a linked list walk calling operations with already prepared values.\n}\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup() {\n return (Writer.create = function create_buffer() {\n return new BufferWriter();\n })();\n }\n /* istanbul ignore next */\n : function create_array() {\n return new Writer();\n };\n};\n\n/**\n * Creates a new writer.\n * @function\n * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}\n */\nWriter.create = create();\n\n/**\n * Allocates a buffer of the specified size.\n * @param {number} size Buffer size\n * @returns {Uint8Array} Buffer\n */\nWriter.alloc = function alloc(size) {\n return new util.Array(size);\n};\n\n// Use Uint8Array buffer pool in the browser, just like node does with buffers\n/* istanbul ignore else */\nif (util.Array !== Array)\n Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);\n\n/**\n * Pushes a new operation to the queue.\n * @param {function(Uint8Array, number, *)} fn Function to call\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @returns {Writer} `this`\n * @private\n */\nWriter.prototype._push = function push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n};\n\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\n\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n\n/**\n * Constructs a new varint writer operation instance.\n * @classdesc Scheduled varint writer operation.\n * @extends Op\n * @constructor\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @ignore\n */\nfunction VarintOp(len, val) {\n this.len = len;\n this.next = undefined;\n this.val = val;\n}\n\nVarintOp.prototype = Object.create(Op.prototype);\nVarintOp.prototype.fn = writeVarint32;\n\n/**\n * Writes an unsigned 32 bit value as a varint.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.uint32 = function write_uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0)\n < 128 ? 1\n : value < 16384 ? 2\n : value < 2097152 ? 3\n : value < 268435456 ? 4\n : 5,\n value)).len;\n return this;\n};\n\n/**\n * Writes a signed 32 bit value as a varint.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.int32 = function write_int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n};\n\n/**\n * Writes a 32 bit value as a varint, zig-zag encoded.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sint32 = function write_sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n};\n\nfunction writeVarint64(val, buf, pos) {\n while (val.hi) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\n\n/**\n * Writes an unsigned 64 bit value as a varint.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.uint64 = function write_uint64(value) {\n var bits = LongBits.from(value);\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a signed 64 bit value as a varint.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.int64 = Writer.prototype.uint64;\n\n/**\n * Writes a signed 64 bit value as a varint, zig-zag encoded.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sint64 = function write_sint64(value) {\n var bits = LongBits.from(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a boolish value as a varint.\n * @param {boolean} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bool = function write_bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n};\n\nfunction writeFixed32(val, buf, pos) {\n buf[pos ] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\n\n/**\n * Writes an unsigned 32 bit value as fixed 32 bits.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.fixed32 = function write_fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n};\n\n/**\n * Writes a signed 32 bit value as fixed 32 bits.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sfixed32 = Writer.prototype.fixed32;\n\n/**\n * Writes an unsigned 64 bit value as fixed 64 bits.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.fixed64 = function write_fixed64(value) {\n var bits = LongBits.from(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n};\n\n/**\n * Writes a signed 64 bit value as fixed 64 bits.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sfixed64 = Writer.prototype.fixed64;\n\n/**\n * Writes a float (32 bit).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.float = function write_float(value) {\n return this._push(util.float.writeFloatLE, 4, value);\n};\n\n/**\n * Writes a double (64 bit float).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.double = function write_double(value) {\n return this._push(util.float.writeDoubleLE, 8, value);\n};\n\nvar writeBytes = util.Array.prototype.set\n ? function writeBytes_set(val, buf, pos) {\n buf.set(val, pos); // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytes_for(val, buf, pos) {\n for (var i = 0; i < val.length; ++i)\n buf[pos + i] = val[i];\n };\n\n/**\n * Writes a sequence of bytes.\n * @param {Uint8Array|string} value Buffer or base64 encoded string to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bytes = function write_bytes(value) {\n var len = value.length >>> 0;\n if (!len)\n return this._push(writeByte, 1, 0);\n if (util.isString(value)) {\n var buf = Writer.alloc(len = base64.length(value));\n base64.decode(value, buf, 0);\n value = buf;\n }\n return this.uint32(len)._push(writeBytes, len, value);\n};\n\n/**\n * Writes a string.\n * @param {string} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.string = function write_string(value) {\n var len = utf8.length(value);\n return len\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0);\n};\n\n/**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n * @returns {Writer} `this`\n */\nWriter.prototype.fork = function fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n};\n\n/**\n * Resets this instance to the last state.\n * @returns {Writer} `this`\n */\nWriter.prototype.reset = function reset() {\n if (this.states) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n } else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n};\n\n/**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n * @returns {Writer} `this`\n */\nWriter.prototype.ldelim = function ldelim() {\n var head = this.head,\n tail = this.tail,\n len = this.len;\n this.reset().uint32(len);\n if (len) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n};\n\n/**\n * Finishes the write operation.\n * @returns {Uint8Array} Finished buffer\n */\nWriter.prototype.finish = function finish() {\n var head = this.head.next, // skip noop\n buf = this.constructor.alloc(this.len),\n pos = 0;\n while (head) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n};\n\nWriter._configure = function(BufferWriter_) {\n BufferWriter = BufferWriter_;\n Writer.create = create();\n BufferWriter._configure();\n};\n","\"use strict\";\nmodule.exports = BufferWriter;\n\n// extends Writer\nvar Writer = require(42);\n(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;\n\nvar util = require(39);\n\n/**\n * Constructs a new buffer writer instance.\n * @classdesc Wire format writer using node buffers.\n * @extends Writer\n * @constructor\n */\nfunction BufferWriter() {\n Writer.call(this);\n}\n\nBufferWriter._configure = function () {\n /**\n * Allocates a buffer of the specified size.\n * @function\n * @param {number} size Buffer size\n * @returns {Buffer} Buffer\n */\n BufferWriter.alloc = util._Buffer_allocUnsafe;\n\n BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === \"set\"\n ? function writeBytesBuffer_set(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytesBuffer_copy(val, buf, pos) {\n if (val.copy) // Buffer values\n val.copy(buf, pos, 0, val.length);\n else for (var i = 0; i < val.length;) // plain array values\n buf[pos++] = val[i++];\n };\n};\n\n\n/**\n * @override\n */\nBufferWriter.prototype.bytes = function write_bytes_buffer(value) {\n if (util.isString(value))\n value = util._Buffer_from(value, \"base64\");\n var len = value.length >>> 0;\n this.uint32(len);\n if (len)\n this._push(BufferWriter.writeBytesBuffer, len, value);\n return this;\n};\n\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)\n util.utf8.write(val, buf, pos);\n else if (buf.utf8Write)\n buf.utf8Write(val, pos);\n else\n buf.write(val, pos);\n}\n\n/**\n * @override\n */\nBufferWriter.prototype.string = function write_string_buffer(value) {\n var len = util.Buffer.byteLength(value);\n this.uint32(len);\n if (len)\n this._push(writeStringBuffer, len, value);\n return this;\n};\n\n\n/**\n * Finishes the write operation.\n * @name BufferWriter#finish\n * @function\n * @returns {Buffer} Finished buffer\n */\n\nBufferWriter._configure();\n"],"sourceRoot":"."} \ No newline at end of file diff --git a/node_modules/protobufjs/dist/protobuf.min.js b/node_modules/protobufjs/dist/protobuf.min.js new file mode 100644 index 0000000..0fc1d0a --- /dev/null +++ b/node_modules/protobufjs/dist/protobuf.min.js @@ -0,0 +1,8 @@ +/*! + * protobuf.js v7.5.4 (c) 2016, daniel wirtz + * compiled fri, 15 aug 2025 23:28:55 utc + * licensed under the bsd-3-clause license + * see: https://github.com/dcodeio/protobuf.js for details + */ +!function(rt){"use strict";!function(r,e,t){var i=function t(i){var n=e[i];return n||r[i][0].call(n=e[i]={exports:{}},t,n,n.exports),n.exports}(t[0]);i.util.global.protobuf=i,"function"==typeof define&&define.amd&&define(["long"],function(t){return t&&t.isLong&&(i.util.Long=t,i.configure()),i}),"object"==typeof module&&module&&module.exports&&(module.exports=i)}({1:[function(t,i,n){i.exports=function(t,i){var n=Array(arguments.length-1),s=0,r=2,o=!0;for(;r>2],r=(3&f)<<4,u=1;break;case 1:s[o++]=h[r|f>>4],r=(15&f)<<2,u=2;break;case 2:s[o++]=h[r|f>>6],s[o++]=h[63&f],u=0}8191>4,r=u,s=2;break;case 2:i[n++]=(15&r)<<4|(60&u)>>2,r=u,s=3;break;case 3:i[n++]=(3&r)<<6|u,s=0}}if(1===s)throw Error(a);return n-e},n.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}},{}],3:[function(t,i,n){function c(i,n){"string"==typeof i&&(n=i,i=rt);var f=[];function h(t){if("string"!=typeof t){var i=a();if(c.verbose&&console.log("codegen: "+i),i="return "+i,t){for(var n=Object.keys(t),r=Array(n.length+1),e=Array(n.length),s=0;s>>0:i<11754943508222875e-54?(e<<31|Math.round(i/1401298464324817e-60))>>>0:(e<<31|127+(t=Math.floor(Math.log(i)/Math.LN2))<<23|8388607&Math.round(i*Math.pow(2,-t)*8388608))>>>0,n,r)}function n(t,i,n){t=t(i,n),i=2*(t>>31)+1,n=t>>>23&255,t&=8388607;return 255==n?t?NaN:1/0*i:0==n?1401298464324817e-60*i*t:i*Math.pow(2,n-150)*(8388608+t)}function r(t,i,n){u[0]=t,i[n]=f[0],i[n+1]=f[1],i[n+2]=f[2],i[n+3]=f[3]}function e(t,i,n){u[0]=t,i[n]=f[3],i[n+1]=f[2],i[n+2]=f[1],i[n+3]=f[0]}function s(t,i){return f[0]=t[i],f[1]=t[i+1],f[2]=t[i+2],f[3]=t[i+3],u[0]}function o(t,i){return f[3]=t[i],f[2]=t[i+1],f[1]=t[i+2],f[0]=t[i+3],u[0]}var u,f,h,a,c;function l(t,i,n,r,e,s){var o,u=r<0?1:0;0===(r=u?-r:r)?(t(0,e,s+i),t(0<1/r?0:2147483648,e,s+n)):isNaN(r)?(t(0,e,s+i),t(2146959360,e,s+n)):17976931348623157e292>>0,e,s+n)):r<22250738585072014e-324?(t((o=r/5e-324)>>>0,e,s+i),t((u<<31|o/4294967296)>>>0,e,s+n)):(t(4503599627370496*(o=r*Math.pow(2,-(r=1024===(r=Math.floor(Math.log(r)/Math.LN2))?1023:r)))>>>0,e,s+i),t((u<<31|r+1023<<20|1048576*o&1048575)>>>0,e,s+n))}function d(t,i,n,r,e){i=t(r,e+i),t=t(r,e+n),r=2*(t>>31)+1,e=t>>>20&2047,n=4294967296*(1048575&t)+i;return 2047==e?n?NaN:1/0*r:0==e?5e-324*r*n:r*Math.pow(2,e-1075)*(n+4503599627370496)}function p(t,i,n){h[0]=t,i[n]=a[0],i[n+1]=a[1],i[n+2]=a[2],i[n+3]=a[3],i[n+4]=a[4],i[n+5]=a[5],i[n+6]=a[6],i[n+7]=a[7]}function v(t,i,n){h[0]=t,i[n]=a[7],i[n+1]=a[6],i[n+2]=a[5],i[n+3]=a[4],i[n+4]=a[3],i[n+5]=a[2],i[n+6]=a[1],i[n+7]=a[0]}function b(t,i){return a[0]=t[i],a[1]=t[i+1],a[2]=t[i+2],a[3]=t[i+3],a[4]=t[i+4],a[5]=t[i+5],a[6]=t[i+6],a[7]=t[i+7],h[0]}function w(t,i){return a[7]=t[i],a[6]=t[i+1],a[5]=t[i+2],a[4]=t[i+3],a[3]=t[i+4],a[2]=t[i+5],a[1]=t[i+6],a[0]=t[i+7],h[0]}return"undefined"!=typeof Float32Array?(u=new Float32Array([-0]),f=new Uint8Array(u.buffer),c=128===f[3],t.writeFloatLE=c?r:e,t.writeFloatBE=c?e:r,t.readFloatLE=c?s:o,t.readFloatBE=c?o:s):(t.writeFloatLE=i.bind(null,y),t.writeFloatBE=i.bind(null,m),t.readFloatLE=n.bind(null,g),t.readFloatBE=n.bind(null,j)),"undefined"!=typeof Float64Array?(h=new Float64Array([-0]),a=new Uint8Array(h.buffer),c=128===a[7],t.writeDoubleLE=c?p:v,t.writeDoubleBE=c?v:p,t.readDoubleLE=c?b:w,t.readDoubleBE=c?w:b):(t.writeDoubleLE=l.bind(null,y,0,4),t.writeDoubleBE=l.bind(null,m,4,0),t.readDoubleLE=d.bind(null,g,0,4),t.readDoubleBE=d.bind(null,j,4,0)),t}function y(t,i,n){i[n]=255&t,i[n+1]=t>>>8&255,i[n+2]=t>>>16&255,i[n+3]=t>>>24}function m(t,i,n){i[n]=t>>>24,i[n+1]=t>>>16&255,i[n+2]=t>>>8&255,i[n+3]=255&t}function g(t,i){return(t[i]|t[i+1]<<8|t[i+2]<<16|t[i+3]<<24)>>>0}function j(t,i){return(t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3])>>>0}i.exports=r(r)},{}],7:[function(t,i,n){function r(t){try{var i=eval("require")(t);if(i&&(i.length||Object.keys(i).length))return i}catch(t){}return null}i.exports=r},{}],8:[function(t,i,n){var e=n.isAbsolute=function(t){return/^(?:\/|\w+:)/.test(t)},r=n.normalize=function(t){var i=(t=t.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),n=e(t),t="";n&&(t=i.shift()+"/");for(var r=0;r>>1,s=null,o=r;return function(t){if(t<1||e>10),s[o++]=56320+(1023&r)):s[o++]=(15&r)<<12|(63&t[i++])<<6|63&t[i++],8191>6|192:(55296==(64512&r)&&56320==(64512&(e=t.charCodeAt(o+1)))?(++o,i[n++]=(r=65536+((1023&r)<<10)+(1023&e))>>18|240,i[n++]=r>>12&63|128):i[n++]=r>>12|224,i[n++]=r>>6&63|128),i[n++]=63&r|128);return n-s}},{}],11:[function(t,i,n){i.exports=e;var r=/\/|\./;function e(t,i){r.test(t)||(t="google/protobuf/"+t+".proto",i={nested:{google:{nested:{protobuf:{nested:i}}}}}),e[t]=i}e("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),e("duration",{Duration:i={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),e("timestamp",{Timestamp:i}),e("empty",{Empty:{fields:{}}}),e("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),e("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),e("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),e.get=function(t){return e[t]||null}},{}],12:[function(t,i,n){var l=t(15),d=t(37);function o(t,i,n,r){var e=!1;if(i.resolvedType)if(i.resolvedType instanceof l){t("switch(d%s){",r);for(var s=i.resolvedType.values,o=Object.keys(s),u=0;u>>0",r,r);break;case"int32":case"sint32":case"sfixed32":t("m%s=d%s|0",r,r);break;case"uint64":f=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",r,r,f)('else if(typeof d%s==="string")',r)("m%s=parseInt(d%s,10)",r,r)('else if(typeof d%s==="number")',r)("m%s=d%s",r,r)('else if(typeof d%s==="object")',r)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",r,r,r,f?"true":"");break;case"bytes":t('if(typeof d%s==="string")',r)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",r,r,r)("else if(d%s.length >= 0)",r)("m%s=d%s",r,r);break;case"string":t("m%s=String(d%s)",r,r);break;case"bool":t("m%s=Boolean(d%s)",r,r)}}return t}function p(t,i,n,r){if(i.resolvedType)i.resolvedType instanceof l?t("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",r,n,r,r,n,r,r):t("d%s=types[%i].toObject(m%s,o)",r,n,r);else{var e=!1;switch(i.type){case"double":case"float":t("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",r,r,r,r);break;case"uint64":e=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t('if(typeof m%s==="number")',r)("d%s=o.longs===String?String(m%s):m%s",r,r,r)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",r,r,r,r,e?"true":"",r);break;case"bytes":t("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",r,r,r,r,r);break;default:t("d%s=m%s",r,r)}}return t}n.fromObject=function(t){var i=t.fieldsArray,n=d.codegen(["d"],t.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!i.length)return n("return new this.ctor");n("var m=new this.ctor");for(var r=0;r>>3){"),n=0;n>>3){")("case 1: k=r.%s(); break",r.keyType)("case 2:"),f.basic[e]===rt?i("value=types[%i].decode(r,r.uint32())",n):i("value=r.%s()",e),i("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),f.long[r.keyType]!==rt?i('%s[typeof k==="object"?util.longToHash(k):k]=value',s):i("%s[k]=value",s)):r.repeated?(i("if(!(%s&&%s.length))",s,s)("%s=[]",s),f.packed[e]!==rt&&i("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos>>0,8|a.mapKey[s.keyType],s.keyType),f===rt?n("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",o,i):n(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|f,u,i),n("}")("}")):s.repeated?(n("if(%s!=null&&%s.length){",i,i),s.packed&&a.packed[u]!==rt?n("w.uint32(%i).fork()",(s.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",i)("w.%s(%s[i])",u,i)("w.ldelim()"):(n("for(var i=0;i<%s.length;++i)",i),f===rt?l(n,s,o,i+"[i]"):n("w.uint32(%i).%s(%s[i])",(s.id<<3|f)>>>0,u,i)),n("}")):(s.optional&&n("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",i,s.name),f===rt?l(n,s,o,i):n("w.uint32(%i).%s(%s)",(s.id<<3|f)>>>0,u,i))}return n("return w")};var h=t(15),a=t(36),c=t(37);function l(t,i,n,r){i.delimited?t("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",n,r,(i.id<<3|3)>>>0,(i.id<<3|4)>>>0):t("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",n,r,(i.id<<3|2)>>>0)}},{15:15,36:36,37:37}],15:[function(t,i,n){i.exports=s;var f=t(24),r=(((s.prototype=Object.create(f.prototype)).constructor=s).className="Enum",t(23)),e=t(37);function s(t,i,n,r,e,s){if(f.call(this,t,n),i&&"object"!=typeof i)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=r,this.comments=e||{},this.valuesOptions=s,this.o={},this.reserved=rt,i)for(var o=Object.keys(i),u=0;u{var i=Object.assign({},this.h);this.o[t]=Object.assign(i,this.valuesOptions&&this.valuesOptions[t]&&this.valuesOptions[t].features)}),this},s.fromJSON=function(t,i){t=new s(t,i.values,i.options,i.comment,i.comments);return t.reserved=i.reserved,i.edition&&(t.f=i.edition),t.a="proto3",t},s.prototype.toJSON=function(t){t=!!t&&!!t.keepComments;return e.toObject(["edition",this.c(),"options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:rt,"comment",t?this.comment:rt,"comments",t?this.comments:rt])},s.prototype.add=function(t,i,n,r){if(!e.isString(t))throw TypeError("name must be a string");if(!e.isInteger(i))throw TypeError("id must be an integer");if(this.values[t]!==rt)throw Error("duplicate name '"+t+"' in "+this);if(this.isReservedId(i))throw Error("id "+i+" is reserved in "+this);if(this.isReservedName(t))throw Error("name '"+t+"' is reserved in "+this);if(this.valuesById[i]!==rt){if(!this.options||!this.options.allow_alias)throw Error("duplicate id "+i+" in "+this);this.values[t]=i}else this.valuesById[this.values[t]=i]=t;return r&&(this.valuesOptions===rt&&(this.valuesOptions={}),this.valuesOptions[t]=r||null),this.comments[t]=n||null,this},s.prototype.remove=function(t){if(!e.isString(t))throw TypeError("name must be a string");var i=this.values[t];if(null==i)throw Error("name '"+t+"' does not exist in "+this);return delete this.valuesById[i],delete this.values[t],delete this.comments[t],this.valuesOptions&&delete this.valuesOptions[t],this},s.prototype.isReservedId=function(t){return r.isReservedId(this.reserved,t)},s.prototype.isReservedName=function(t){return r.isReservedName(this.reserved,t)}},{23:23,24:24,37:37}],16:[function(t,i,n){i.exports=o;var r,u=t(24),e=(((o.prototype=Object.create(u.prototype)).constructor=o).className="Field",t(15)),f=t(36),h=t(37),a=/^required|optional|repeated$/;function o(t,i,n,r,e,s,o){if(h.isObject(r)?(o=e,s=r,r=e=rt):h.isObject(e)&&(o=s,s=e,e=rt),u.call(this,t,s),!h.isInteger(i)||i<0)throw TypeError("id must be a non-negative integer");if(!h.isString(n))throw TypeError("type must be a string");if(r!==rt&&!a.test(r=r.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(e!==rt&&!h.isString(e))throw TypeError("extend must be a string");this.rule=(r="proto3_optional"===r?"optional":r)&&"optional"!==r?r:rt,this.type=n,this.id=i,this.extend=e||rt,this.repeated="repeated"===r,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!h.Long&&f.long[n]!==rt,this.bytes="bytes"===n,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.comment=o}o.fromJSON=function(t,i){t=new o(t,i.id,i.type,i.rule,i.extend,i.options,i.comment);return i.edition&&(t.f=i.edition),t.a="proto3",t},Object.defineProperty(o.prototype,"required",{get:function(){return"LEGACY_REQUIRED"===this.h.field_presence}}),Object.defineProperty(o.prototype,"optional",{get:function(){return!this.required}}),Object.defineProperty(o.prototype,"delimited",{get:function(){return this.resolvedType instanceof r&&"DELIMITED"===this.h.message_encoding}}),Object.defineProperty(o.prototype,"packed",{get:function(){return"PACKED"===this.h.repeated_field_encoding}}),Object.defineProperty(o.prototype,"hasPresence",{get:function(){return!this.repeated&&!this.map&&(this.partOf||this.declaringField||this.extensionField||"IMPLICIT"!==this.h.field_presence)}}),o.prototype.setOption=function(t,i,n){return u.prototype.setOption.call(this,t,i,n)},o.prototype.toJSON=function(t){t=!!t&&!!t.keepComments;return h.toObject(["edition",this.c(),"rule","optional"!==this.rule&&this.rule||rt,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:rt])},o.prototype.resolve=function(){var t;return this.resolved?this:((this.typeDefault=f.defaults[this.type])===rt?(this.resolvedType=(this.declaringField||this).parent.lookupTypeOrEnum(this.type),this.resolvedType instanceof r?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof e&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(this.options.packed===rt||!this.resolvedType||this.resolvedType instanceof e||delete this.options.packed,Object.keys(this.options).length||(this.options=rt)),this.long?(this.typeDefault=h.Long.fromNumber(this.typeDefault,"u"==(this.type[0]||"")),Object.freeze&&Object.freeze(this.typeDefault)):this.bytes&&"string"==typeof this.typeDefault&&(h.base64.test(this.typeDefault)?h.base64.decode(this.typeDefault,t=h.newBuffer(h.base64.length(this.typeDefault)),0):h.utf8.write(this.typeDefault,t=h.newBuffer(h.utf8.length(this.typeDefault)),0),this.typeDefault=t),this.map?this.defaultValue=h.emptyObject:this.repeated?this.defaultValue=h.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof r&&(this.parent.ctor.prototype[this.name]=this.defaultValue),u.prototype.resolve.call(this))},o.prototype.l=function(t){var i;return"proto2"!==t&&"proto3"!==t?{}:(t={},"required"===this.rule&&(t.field_presence="LEGACY_REQUIRED"),this.parent&&f.defaults[this.type]===rt&&(i=this.parent.get(this.type.split(".").pop()))&&i instanceof r&&i.group&&(t.message_encoding="DELIMITED"),!0===this.getOption("packed")?t.repeated_field_encoding="PACKED":!1===this.getOption("packed")&&(t.repeated_field_encoding="EXPANDED"),t)},o.prototype.u=function(t){return u.prototype.u.call(this,this.f||t)},o.d=function(n,r,e,s){return"function"==typeof r?r=h.decorateType(r).name:r&&"object"==typeof r&&(r=h.decorateEnum(r).name),function(t,i){h.decorateType(t.constructor).add(new o(i,n,r,e,{default:s}))}},o.p=function(t){r=t}},{15:15,24:24,36:36,37:37}],17:[function(t,i,n){var r=i.exports=t(18);r.build="light",r.load=function(t,i,n){return(i="function"==typeof i?(n=i,new r.Root):i||new r.Root).load(t,n)},r.loadSync=function(t,i){return(i=i||new r.Root).loadSync(t)},r.encoder=t(14),r.decoder=t(13),r.verifier=t(40),r.converter=t(12),r.ReflectionObject=t(24),r.Namespace=t(23),r.Root=t(29),r.Enum=t(15),r.Type=t(35),r.Field=t(16),r.OneOf=t(25),r.MapField=t(20),r.Service=t(33),r.Method=t(22),r.Message=t(21),r.wrappers=t(41),r.types=t(36),r.util=t(37),r.ReflectionObject.p(r.Root),r.Namespace.p(r.Type,r.Service,r.Enum),r.Root.p(r.Type),r.Field.p(r.Type)},{12:12,13:13,14:14,15:15,16:16,18:18,20:20,21:21,22:22,23:23,24:24,25:25,29:29,33:33,35:35,36:36,37:37,40:40,41:41}],18:[function(t,i,n){var r=n;function e(){r.util.p(),r.Writer.p(r.BufferWriter),r.Reader.p(r.BufferReader)}r.build="minimal",r.Writer=t(42),r.BufferWriter=t(43),r.Reader=t(27),r.BufferReader=t(28),r.util=t(39),r.rpc=t(31),r.roots=t(30),r.configure=e,e()},{27:27,28:28,30:30,31:31,39:39,42:42,43:43}],19:[function(t,i,n){i=i.exports=t(17);i.build="full",i.tokenize=t(34),i.parse=t(26),i.common=t(11),i.Root.p(i.Type,i.parse,i.common)},{11:11,17:17,26:26,34:34}],20:[function(t,i,n){i.exports=s;var o=t(16),r=(((s.prototype=Object.create(o.prototype)).constructor=s).className="MapField",t(36)),u=t(37);function s(t,i,n,r,e,s){if(o.call(this,t,i,r,rt,rt,e,s),!u.isString(n))throw TypeError("keyType must be a string");this.keyType=n,this.resolvedKeyType=null,this.map=!0}s.fromJSON=function(t,i){return new s(t,i.id,i.keyType,i.type,i.options,i.comment)},s.prototype.toJSON=function(t){t=!!t&&!!t.keepComments;return u.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:rt])},s.prototype.resolve=function(){if(this.resolved)return this;if(r.mapKey[this.keyType]===rt)throw Error("invalid key type: "+this.keyType);return o.prototype.resolve.call(this)},s.d=function(n,r,e){return"function"==typeof e?e=u.decorateType(e).name:e&&"object"==typeof e&&(e=u.decorateEnum(e).name),function(t,i){u.decorateType(t.constructor).add(new s(i,n,r,e))}}},{16:16,36:36,37:37}],21:[function(t,i,n){i.exports=e;var r=t(39);function e(t){if(t)for(var i=Object.keys(t),n=0;ni)return!0;return!1},c.isReservedName=function(t,i){if(t)for(var n=0;n{t.g(i)})),this},c.prototype.lookup=function(t,i,n){if("boolean"==typeof i?(n=i,i=rt):i&&!Array.isArray(i)&&(i=[i]),h.isString(t)&&t.length){if("."===t)return this.root;t=t.split(".")}else if(!t.length)return this;var r=t.join(".");if(""===t[0])return this.root.lookup(t.slice(1),i);var e=this.root.j&&this.root.j["."+r];if(e&&(!i||~i.indexOf(e.constructor)))return e;if((e=this.k(t,r))&&(!i||~i.indexOf(e.constructor)))return e;if(!n)for(var s=this;s.parent;){if((e=s.parent.k(t,r))&&(!i||~i.indexOf(e.constructor)))return e;s=s.parent}return null},c.prototype.k=function(t,i){if(Object.prototype.hasOwnProperty.call(this.b,i))return this.b[i];var n=this.get(t[0]),r=null;if(n)1===t.length?r=n:n instanceof c&&(t=t.slice(1),r=n.k(t,t.join(".")));else for(var e=0;e");var e=c();if(!tt.test(e))throw k(e,"name");p("=");var s=new U(j(e),T(c()),n,r);x(s,function(t){if("option"!==t)throw k(t);L(s,t),p(";")},function(){M(s)}),i.add(s);break;case"required":if("proto2"!==w)throw k(t);case"repeated":I(u,t);break;case"optional":if("proto3"===w)I(u,"proto3_optional");else{if("proto2"!==w)throw k(t);I(u,"optional")}break;case"oneof":e=u,n=t;if(!tt.test(n=c()))throw k(n,"name");var o=new D(j(n));x(o,function(t){"option"===t?(L(o,t),p(";")):(l(t),I(o,"optional"))}),e.add(o);break;case"extensions":A(u.extensions||(u.extensions=[]));break;case"reserved":A(u.reserved||(u.reserved=[]),!0);break;default:if("proto2"===w||!it.test(t))throw k(t);l(t),I(u,"optional")}}),t.add(u),t===y&&m.push(u)}function I(t,i,n){var r=c();if("group"===r){var e=t,s=i;if(2023<=w)throw k("group");var o,u,f=c();if(tt.test(f))return u=B.lcFirst(f),f===u&&(f=B.ucFirst(f)),p("="),h=T(c()),(o=new P(f)).group=!0,(u=new R(u,h,f,s)).filename=nt.filename,x(o,function(t){switch(t){case"option":L(o,t),p(";");break;case"required":case"repeated":I(o,t);break;case"optional":I(o,"proto3"===w?"proto3_optional":"optional");break;case"message":S(o);break;case"enum":N(o);break;case"reserved":A(o.reserved||(o.reserved=[]),!0);break;default:throw k(t)}}),void e.add(o).add(u);throw k(f,"name")}for(;r.endsWith(".")||d().startsWith(".");)r+=c();if(!it.test(r))throw k(r,"type");var h=c();if(!tt.test(h))throw k(h,"name");h=j(h),p("=");var a=new R(h,T(c()),r,i,n);x(a,function(t){if("option"!==t)throw k(t);L(a,t),p(";")},function(){M(a)}),"proto3_optional"===i?(s=new D("_"+h),a.setOption("proto3_optional",!0),s.add(a),t.add(s)):t.add(a),t===y&&m.push(a)}function N(t,i){if(!tt.test(i=c()))throw k(i,"name");var s=new q(i);x(s,function(t){switch(t){case"option":L(s,t),p(";");break;case"reserved":A(s.reserved||(s.reserved=[]),!0),s.reserved===rt&&(s.reserved=[]);break;default:var i=s,n=t;if(!tt.test(n))throw k(n,"name");p("=");var r=T(c(),!0),e={options:rt,getOption:function(t){return this.options[t]},setOption:function(t,i){X.prototype.setOption.call(e,t,i)},setParsedOption:function(){return rt}};return x(e,function(t){if("option"!==t)throw k(t);L(e,t),p(";")},function(){M(e)}),void i.add(n,r,e.comment,e.parsedOptions||e.options)}}),t.add(s),t===y&&m.push(s)}function L(t,i){var n=!0;for("option"===i&&(i=c());"="!==i;){if("("===i&&(r=c(),p(")"),i="("+r+")"),n){if(n=!1,i.includes(".")&&!i.includes("(")){var r=i.split("."),e=r[0]+".";i=r[1];continue}e=i}else f=f?f+i:i;i=c()}var s,o,u=f?e.concat(f):e,u=function t(i,n){if(p("{",!0)){for(var r={};!p("}",!0);){if(!tt.test(h=c()))throw k(h,"name");if(null===h)throw k(h,"end of input");var e,s,o=h;if(p(":",!0),"{"===d())e=t(i,n+"."+h);else if("["===d()){if(e=[],p("[",!0)){for(;s=O(!0),e.push(s),p(",",!0););p("]"),void 0!==s&&V(i,n+"."+h,s)}}else e=O(!0),V(i,n+"."+h,e);var u=r[o];u&&(e=[].concat(u).concat(e)),r[o]=e,p(",",!0),p(";",!0)}return r}var f=O(!0);V(i,n,f);return f}(t,u),f=f&&"."===f[0]?f.slice(1):f;e=e&&"."===e[e.length-1]?e.slice(0,-1):e,s=e,u=u,o=f,(t=t).setParsedOption&&t.setParsedOption(s,u,o)}function V(t,i,n){y===t&&/^features\./.test(i)?g[i]=n:t.setOption&&t.setOption(i,n)}function M(t){if(p("[",!0)){for(;L(t,"option"),p(",",!0););p("]")}}for(;null!==(h=c());)switch(h){case"package":if(!b)throw k(h);if(r!==rt)throw k("package");if(r=c(),!it.test(r))throw k(r,"name");y=y.define(r),p(";");break;case"import":if(!b)throw k(h);switch(u=o=void 0,d()){case"weak":u=s=s||[],c();break;case"public":c();default:u=e=e||[]}o=E(),p(";"),u.push(o);break;case"syntax":if(!b)throw k(h);if(p("="),(w=E())<2023)throw k(w,"syntax");p(";");break;case"edition":if(!b)throw k(h);if(p("="),w=E(),!["2023"].includes(w))throw k(w,"edition");p(";");break;case"option":L(y,h),p(";",!0);break;default:if(_(y,h)){b=!1;continue}throw k(h)}return m.forEach(i=>{i.f=w,Object.keys(g).forEach(t=>{i.getOption(t)===rt&&i.setOption(t,g[t],!0)})}),nt.filename=null,{package:r,imports:e,weakImports:s,root:i}}},{15:15,16:16,20:20,22:22,24:24,25:25,29:29,33:33,34:34,35:35,36:36,37:37}],27:[function(t,i,n){i.exports=f;var r,e=t(39),s=e.LongBits,o=e.utf8;function u(t,i){return RangeError("index out of range: "+t.pos+" + "+(i||1)+" > "+t.len)}function f(t){this.buf=t,this.pos=0,this.len=t.length}function h(){return e.Buffer?function(t){return(f.create=function(t){return e.Buffer.isBuffer(t)?new r(t):c(t)})(t)}:c}var a,c="undefined"!=typeof Uint8Array?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new f(t);throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new f(t);throw Error("illegal buffer")};function l(){var t=new s(0,0),i=0;if(!(4=this.len)throw u(this);if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*i)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(127&this.buf[this.pos++])<<7*i)>>>0,t}for(;i<4;++i)if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*i)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(127&this.buf[this.pos])<<28)>>>0,t.hi=(t.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return t;if(i=0,4>>0,this.buf[this.pos++]<128)return t}else for(;i<5;++i){if(this.pos>=this.len)throw u(this);if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*i+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}function d(t,i){return(t[i-4]|t[i-3]<<8|t[i-2]<<16|t[i-1]<<24)>>>0}function p(){if(this.pos+8>this.len)throw u(this,8);return new s(d(this.buf,this.pos+=4),d(this.buf,this.pos+=4))}f.create=h(),f.prototype._=e.Array.prototype.subarray||e.Array.prototype.slice,f.prototype.uint32=(a=4294967295,function(){if(a=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(a=(a|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128||(a=(a|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128||(a=(a|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128||(a=(a|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128||!((this.pos+=5)>this.len))))))return a;throw this.pos=this.len,u(this,10)}),f.prototype.int32=function(){return 0|this.uint32()},f.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(1&t)|0},f.prototype.bool=function(){return 0!==this.uint32()},f.prototype.fixed32=function(){if(this.pos+4>this.len)throw u(this,4);return d(this.buf,this.pos+=4)},f.prototype.sfixed32=function(){if(this.pos+4>this.len)throw u(this,4);return 0|d(this.buf,this.pos+=4)},f.prototype.float=function(){if(this.pos+4>this.len)throw u(this,4);var t=e.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t},f.prototype.double=function(){if(this.pos+8>this.len)throw u(this,4);var t=e.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t},f.prototype.bytes=function(){var t=this.uint32(),i=this.pos,n=this.pos+t;if(n>this.len)throw u(this,t);return this.pos+=t,Array.isArray(this.buf)?this.buf.slice(i,n):i===n?(t=e.Buffer)?t.alloc(0):new this.buf.constructor(0):this._.call(this.buf,i,n)},f.prototype.string=function(){var t=this.bytes();return o.read(t,0,t.length)},f.prototype.skip=function(t){if("number"==typeof t){if(this.pos+t>this.len)throw u(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw u(this)}while(128&this.buf[this.pos++]);return this},f.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this},f.p=function(t){r=t,f.create=h(),r.p();var i=e.Long?"toLong":"toNumber";e.merge(f.prototype,{int64:function(){return l.call(this)[i](!1)},uint64:function(){return l.call(this)[i](!0)},sint64:function(){return l.call(this).zzDecode()[i](!1)},fixed64:function(){return p.call(this)[i](!0)},sfixed64:function(){return p.call(this)[i](!1)}})}},{39:39}],28:[function(t,i,n){i.exports=s;var r=t(27),e=((s.prototype=Object.create(r.prototype)).constructor=s,t(39));function s(t){r.call(this,t)}s.p=function(){e.Buffer&&(s.prototype._=e.Buffer.prototype.slice)},s.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+t,this.len))},s.p()},{27:27,39:39}],29:[function(t,i,n){i.exports=f;var r,d,p,e=t(23),s=(((f.prototype=Object.create(e.prototype)).constructor=f).className="Root",t(16)),o=t(15),u=t(25),v=t(37);function f(t){e.call(this,"",t),this.deferred=[],this.files=[],this.f="proto2",this.j={}}function b(){}f.fromJSON=function(t,i){return i=i||new f,t.options&&i.setOptions(t.options),i.addJSON(t.nested).resolveAll()},f.prototype.resolvePath=v.path.resolve,f.prototype.fetch=v.fetch,f.prototype.load=function t(i,s,e){"function"==typeof s&&(e=s,s=rt);var o=this;if(!e)return v.asPromise(t,o,i,s);var u=e===b;function f(t,i){if(e){if(u)throw t;i&&i.resolveAll();var n=e;e=null,n(t,i)}}function h(t){var i=t.lastIndexOf("google/protobuf/");if(-1{t.g(i)})),this},o.prototype.add=function(t){if(this.get(t.name))throw Error("duplicate name '"+t.name+"' in "+this);return t instanceof s?e((this.methods[t.name]=t).parent=this):r.prototype.add.call(this,t)},o.prototype.remove=function(t){if(t instanceof s){if(this.methods[t.name]!==t)throw Error(t+" is not a member of "+this);return delete this.methods[t.name],t.parent=null,e(this)}return r.prototype.remove.call(this,t)},o.prototype.create=function(t,i,n){for(var r,e=new f.Service(t,i,n),s=0;s]/g,O=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,A=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,T=/^ *[*/]+ */,_=/^\s*\*?\/*/,x=/\n/g,S=/\s/,r=/\\(.?)/g,e={0:"\0",r:"\r",n:"\n",t:"\t"};function I(t){return t.replace(r,function(t,i){switch(i){case"\\":case"":return i;default:return e[i]||""}})}function s(h,a){h=h.toString();var c=0,l=h.length,d=1,f=0,p={},v=[],b=null;function w(t){return Error("illegal "+t+" (line "+d+")")}function y(t){return h[0|t]||""}function m(t,i,n){var r,e={type:h[0|t++]||"",lineEmpty:!1,leading:n},n=a?2:3,s=t-n;do{if(--s<0||"\n"==(r=h[0|s]||"")){e.lineEmpty=!0;break}}while(" "===r||"\t"===r);for(var o=h.substring(t,i).split(x),u=0;u{t.u(i)}),this.fieldsArray.forEach(t=>{t.u(i)})),this},m.prototype.get=function(t){return this.fields[t]||this.oneofs&&this.oneofs[t]||this.nested&&this.nested[t]||null},m.prototype.add=function(t){if(this.get(t.name))throw Error("duplicate name '"+t.name+"' in "+this);if(t instanceof h&&t.extend===rt){if((this.S||this.fieldsById)[t.id])throw Error("duplicate id "+t.id+" in "+this);if(this.isReservedId(t.id))throw Error("id "+t.id+" is reserved in "+this);if(this.isReservedName(t.name))throw Error("name '"+t.name+"' is reserved in "+this);return t.parent&&t.parent.remove(t),(this.fields[t.name]=t).message=this,t.onAdd(this),r(this)}return t instanceof f?(this.oneofs||(this.oneofs={}),(this.oneofs[t.name]=t).onAdd(this),r(this)):o.prototype.add.call(this,t)},m.prototype.remove=function(t){if(t instanceof h&&t.extend===rt){if(this.fields&&this.fields[t.name]===t)return delete this.fields[t.name],t.parent=null,t.onRemove(this),r(this);throw Error(t+" is not a member of "+this)}if(t instanceof f){if(this.oneofs&&this.oneofs[t.name]===t)return delete this.oneofs[t.name],t.parent=null,t.onRemove(this),r(this);throw Error(t+" is not a member of "+this)}return o.prototype.remove.call(this,t)},m.prototype.isReservedId=function(t){return o.isReservedId(this.reserved,t)},m.prototype.isReservedName=function(t){return o.isReservedName(this.reserved,t)},m.prototype.create=function(t){return new this.ctor(t)},m.prototype.setup=function(){for(var t=this.fullName,i=[],n=0;n>>0,this.hi=i>>>0}var s=e.zero=new e(0,0),o=(s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1},e.zeroHash="\0\0\0\0\0\0\0\0",e.fromNumber=function(t){var i,n;return 0===t?s:(n=(t=(i=t<0)?-t:t)>>>0,t=(t-n)/4294967296>>>0,i&&(t=~t>>>0,n=~n>>>0,4294967295<++n&&(n=0,4294967295<++t&&(t=0))),new e(n,t))},e.from=function(t){if("number"==typeof t)return e.fromNumber(t);if(r.isString(t)){if(!r.Long)return e.fromNumber(parseInt(t,10));t=r.Long.fromString(t)}return t.low||t.high?new e(t.low>>>0,t.high>>>0):s},e.prototype.toNumber=function(t){var i;return!t&&this.hi>>>31?(t=1+~this.lo>>>0,i=~this.hi>>>0,-(t+4294967296*(i=t?i:i+1>>>0))):this.lo+4294967296*this.hi},e.prototype.toLong=function(t){return r.Long?new r.Long(0|this.lo,0|this.hi,!!t):{low:0|this.lo,high:0|this.hi,unsigned:!!t}},String.prototype.charCodeAt);e.fromHash=function(t){return"\0\0\0\0\0\0\0\0"===t?s:new e((o.call(t,0)|o.call(t,1)<<8|o.call(t,2)<<16|o.call(t,3)<<24)>>>0,(o.call(t,4)|o.call(t,5)<<8|o.call(t,6)<<16|o.call(t,7)<<24)>>>0)},e.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},e.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this},e.prototype.zzDecode=function(){var t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this},e.prototype.length=function(){var t=this.lo,i=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0==n?0==i?t<16384?t<128?1:2:t<2097152?3:4:i<16384?i<128?5:6:i<2097152?7:8:n<128?9:10}},{39:39}],39:[function(t,i,n){var r=n;function e(t,i,n){for(var r=Object.keys(i),e=0;e>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;127>>7;i[n++]=t.lo}function b(t,i,n){i[n]=255&t,i[n+1]=t>>>8&255,i[n+2]=t>>>16&255,i[n+3]=t>>>24}c.create=l(),c.alloc=function(t){return new e.Array(t)},e.Array!==Array&&(c.alloc=e.pool(c.alloc,e.Array.prototype.subarray)),c.prototype.M=function(t,i,n){return this.tail=this.tail.next=new f(t,i,n),this.len+=i,this},(p.prototype=Object.create(f.prototype)).fn=function(t,i,n){for(;127>>=7;i[n]=t},c.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new p((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this},c.prototype.int32=function(t){return t<0?this.M(v,10,s.fromNumber(t)):this.uint32(t)},c.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},c.prototype.int64=c.prototype.uint64=function(t){t=s.from(t);return this.M(v,t.length(),t)},c.prototype.sint64=function(t){t=s.from(t).zzEncode();return this.M(v,t.length(),t)},c.prototype.bool=function(t){return this.M(d,1,t?1:0)},c.prototype.sfixed32=c.prototype.fixed32=function(t){return this.M(b,4,t>>>0)},c.prototype.sfixed64=c.prototype.fixed64=function(t){t=s.from(t);return this.M(b,4,t.lo).M(b,4,t.hi)},c.prototype.float=function(t){return this.M(e.float.writeFloatLE,4,t)},c.prototype.double=function(t){return this.M(e.float.writeDoubleLE,8,t)};var w=e.Array.prototype.set?function(t,i,n){i.set(t,n)}:function(t,i,n){for(var r=0;r>>0;return n?(e.isString(t)&&(i=c.alloc(n=o.length(t)),o.decode(t,i,0),t=i),this.uint32(n).M(w,n,t)):this.M(d,1,0)},c.prototype.string=function(t){var i=u.length(t);return i?this.uint32(i).M(u.write,i,t):this.M(d,1,0)},c.prototype.fork=function(){return this.states=new a(this),this.head=this.tail=new f(h,0,0),this.len=0,this},c.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new f(h,0,0),this.len=0),this},c.prototype.ldelim=function(){var t=this.head,i=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=t.next,this.tail=i,this.len+=n),this},c.prototype.finish=function(){for(var t=this.head.next,i=this.constructor.alloc(this.len),n=0;t;)t.fn(t.val,i,n),n+=t.len,t=t.next;return i},c.p=function(t){r=t,c.create=l(),r.p()}},{39:39}],43:[function(t,i,n){i.exports=s;var r=t(42),e=((s.prototype=Object.create(r.prototype)).constructor=s,t(39));function s(){r.call(this)}function o(t,i,n){t.length<40?e.utf8.write(t,i,n):i.utf8Write?i.utf8Write(t,n):i.write(t,n)}s.p=function(){s.alloc=e.V,s.writeBytesBuffer=e.Buffer&&e.Buffer.prototype instanceof Uint8Array&&"set"===e.Buffer.prototype.set.name?function(t,i,n){i.set(t,n)}:function(t,i,n){if(t.copy)t.copy(i,n,0,t.length);else for(var r=0;r>>0;return this.uint32(i),i&&this.M(s.writeBytesBuffer,i,t),this},s.prototype.string=function(t){var i=e.Buffer.byteLength(t);return this.uint32(i),i&&this.M(o,i,t),this},s.p()},{39:39,42:42}]},{},[19])}(); +//# sourceMappingURL=protobuf.min.js.map diff --git a/node_modules/protobufjs/dist/protobuf.min.js.map b/node_modules/protobufjs/dist/protobuf.min.js.map new file mode 100644 index 0000000..5917576 --- /dev/null +++ b/node_modules/protobufjs/dist/protobuf.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["lib/prelude.js","../node_modules/@protobufjs/aspromise/index.js","../node_modules/@protobufjs/base64/index.js","../node_modules/@protobufjs/codegen/index.js","../node_modules/@protobufjs/eventemitter/index.js","../node_modules/@protobufjs/fetch/index.js","../node_modules/@protobufjs/float/index.js","../node_modules/@protobufjs/inquire/index.js","../node_modules/@protobufjs/path/index.js","../node_modules/@protobufjs/pool/index.js","../node_modules/@protobufjs/utf8/index.js","../src/common.js","../src/converter.js","../src/decoder.js","../src/encoder.js","../src/enum.js","../src/field.js","../src/index-light.js","../src/index-minimal.js","../src/index","../src/mapfield.js","../src/message.js","../src/method.js","../src/namespace.js","../src/object.js","../src/oneof.js","../src/parse.js","../src/reader.js","../src/reader_buffer.js","../src/root.js","../src/roots.js","../src/rpc.js","../src/rpc/service.js","../src/service.js","../src/tokenize.js","../src/type.js","../src/types.js","../src/util.js","../src/util/longbits.js","../src/util/minimal.js","../src/verifier.js","../src/wrappers.js","../src/writer.js","../src/writer_buffer.js"],"names":["undefined","modules","cache","entries","protobuf","$require","name","$module","call","exports","util","global","define","amd","Long","isLong","configure","module","1","require","fn","ctx","params","Array","arguments","length","offset","index","pending","Promise","resolve","reject","err","apply","base64","string","p","n","Math","ceil","b64","s64","i","encode","buffer","start","end","t","parts","chunk","j","b","push","String","fromCharCode","slice","join","invalidEncoding","decode","c","charCodeAt","Error","test","codegen","functionParams","functionName","body","Codegen","formatStringOrScope","source","toString","verbose","console","log","scopeKeys","Object","keys","scopeParams","scopeValues","scopeOffset","Function","formatParams","formatOffset","replace","$0","$1","value","Number","floor","JSON","stringify","functionNameOverride","EventEmitter","this","_listeners","prototype","on","evt","off","listeners","splice","emit","args","fetch","asPromise","fs","filename","options","callback","xhr","readFile","contents","XMLHttpRequest","binary","onreadystatechange","readyState","status","response","responseText","Uint8Array","overrideMimeType","responseType","open","send","factory","writeFloat_ieee754","writeUint","val","buf","pos","sign","isNaN","round","exponent","LN2","pow","readFloat_ieee754","readUint","uint","mantissa","NaN","Infinity","writeFloat_f32_cpy","f32","f8b","writeFloat_f32_rev","readFloat_f32_cpy","readFloat_f32_rev","f64","le","writeDouble_ieee754","off0","off1","readDouble_ieee754","lo","hi","writeDouble_f64_cpy","writeDouble_f64_rev","readDouble_f64_cpy","readDouble_f64_rev","Float32Array","writeFloatLE","writeFloatBE","readFloatLE","readFloatBE","bind","writeUintLE","writeUintBE","readUintLE","readUintBE","Float64Array","writeDoubleLE","writeDoubleBE","readDoubleLE","readDoubleBE","inquire","moduleName","mod","eval","e","isAbsolute","path","normalize","split","absolute","prefix","shift","originPath","includePath","alreadyNormalized","alloc","size","SIZE","MAX","slab","utf8","len","read","write","c1","c2","common","commonRe","json","nested","google","Any","fields","type_url","type","id","Duration","timeType","seconds","nanos","Timestamp","Empty","Struct","keyType","Value","oneofs","kind","oneof","nullValue","numberValue","stringValue","boolValue","structValue","listValue","NullValue","values","NULL_VALUE","ListValue","rule","DoubleValue","FloatValue","Int64Value","UInt64Value","Int32Value","UInt32Value","BoolValue","StringValue","BytesValue","FieldMask","paths","get","file","Enum","genValuePartial_fromObject","gen","field","fieldIndex","prop","defaultAlreadyEmitted","resolvedType","typeDefault","repeated","fullName","isUnsigned","genValuePartial_toObject","converter","fromObject","mtype","fieldsArray","safeProp","map","toObject","sort","compareFieldsById","repeatedFields","mapFields","normalFields","partOf","arrayDefault","valuesById","long","low","high","unsigned","toNumber","bytes","hasKs2","_fieldsArray","indexOf","filter","ref","types","defaults","basic","packed","delimited","rfield","required","wireType","mapKey","genTypePartial","optional","ReflectionObject","Namespace","create","constructor","className","comment","comments","valuesOptions","TypeError","_valuesFeatures","reserved","_resolveFeatures","edition","_edition","forEach","key","parentFeaturesCopy","assign","_features","features","fromJSON","enm","_defaultEdition","toJSON","toJSONOptions","keepComments","Boolean","_editionToJSON","add","isString","isInteger","isReservedId","isReservedName","allow_alias","remove","Field","Type","ruleRe","extend","isObject","toLowerCase","message","defaultValue","extensionField","declaringField","defineProperty","field_presence","message_encoding","repeated_field_encoding","setOption","ifNotSet","resolved","parent","lookupTypeOrEnum","proto3_optional","fromNumber","freeze","newBuffer","emptyObject","emptyArray","ctor","_inferLegacyProtoFeatures","pop","group","getOption","d","fieldId","fieldType","fieldRule","decorateType","decorateEnum","fieldName","default","_configure","Type_","build","load","root","Root","loadSync","encoder","decoder","verifier","OneOf","MapField","Service","Method","Message","wrappers","Writer","BufferWriter","Reader","BufferReader","rpc","roots","tokenize","parse","resolvedKeyType","fieldKeyType","fieldValueType","properties","$type","writer","encodeDelimited","reader","decodeDelimited","verify","object","requestType","requestStream","responseStream","parsedOptions","resolvedRequestType","resolvedResponseType","lookupType","arrayToJSON","array","obj","_nestedArray","_lookupCache","_needsRecursiveFeatureResolution","_needsRecursiveResolve","clearCache","namespace","addJSON","toArray","nestedArray","nestedJson","names","methods","getEnum","prev","setOptions","onAdd","onRemove","isArray","ptr","part","resolveAll","_resolveFeaturesRecursive","lookup","filterTypes","parentAlreadyChecked","flatPath","found","_fullyQualifiedObjects","_lookupImpl","current","hasOwnProperty","exact","lookupEnum","lookupService","Service_","Enum_","editions2023Defaults","enum_type","json_format","utf8_validation","proto2Defaults","proto3Defaults","_featuresResolved","defineProperties","unshift","_handleAdd","_handleRemove","protoFeatures","lexicalParentFeaturesCopy","setProperty","setParsedOption","propName","opt","newOpt","find","newValue","Root_","fieldNames","addFieldsToParent","oneofName","oneOfGetter","set","oneOfSetter","keepCase","base10Re","base10NegRe","base16Re","base16NegRe","base8Re","base8NegRe","numberRe","nameRe","typeRefRe","pkg","imports","weakImports","token","whichImports","preferTrailingComment","tn","alternateCommentMode","next","peek","skip","cmnt","head","topLevelObjects","topLevelOptions","applyCase","camelCase","illegal","insideTryCatch","line","readString","readValue","acceptTypeRef","parseNumber","substring","parseInt","parseFloat","readRanges","target","acceptStrings","parseId","str","dummy","ifBlock","parseOption","parseInlineOptions","acceptNegative","parseCommon","parseType","parseEnum","parseService","service","parseMethod","commentText","method","parseExtension","reference","parseField","fnIf","fnElse","trailingLine","parseMapField","valueType","extensions","parseGroup","lcFirst","ucFirst","endsWith","startsWith","parseEnumValue","isOption","parensValue","includes","tokens","option","concat","optionValue","parseOptionValue","objectResult","lastValue","prevValue","simpleValue","package","LongBits","indexOutOfRange","writeLength","RangeError","Buffer","isBuffer","create_array","readLongVarint","bits","readFixed32_end","readFixed64","_slice","subarray","uint32","int32","sint32","bool","fixed32","sfixed32","float","double","nativeBuffer","skipType","BufferReader_","merge","int64","uint64","sint64","zzDecode","fixed64","sfixed64","utf8Slice","min","deferred","files","SYNC","resolvePath","self","sync","finish","cb","getBundledFileName","idx","lastIndexOf","altname","process","parsed","queued","weak","setTimeout","readFileSync","isNode","exposeRe","tryHandleExtension","sisterField","extendedType","parse_","common_","rpcImpl","requestDelimited","responseDelimited","rpcCall","requestCtor","responseCtor","request","endedByRPC","_methodsArray","inherited","methodsArray","rpcService","methodName","isReserved","m","q","s","delimRe","stringDoubleRe","stringSingleRe","setCommentRe","setCommentAltRe","setCommentSplitRe","whitespaceRe","unescapeRe","unescapeMap","0","r","unescape","lastCommentLine","stack","stringDelim","subject","charAt","setComment","isLeading","lineEmpty","leading","lookback","commentOffset","lines","trim","text","isDoubleSlashCommentLine","startOffset","endOffset","findEndOfLine","lineText","cursor","re","match","lastIndex","exec","repeat","curr","isDoc","isLeadingComment","expected","actual","ret","_fieldsById","_oneofsArray","_ctor","fieldsById","oneofsArray","generateConstructor","ctorProperties","setup","originalThis","wrapper","fork","ldelim","typeName","bake","o","safePropBackslashRe","safePropQuoteRe","camelCaseRe","toUpperCase","decorateEnumIndex","a","decorateRoot","enumerable","dst","setProp","zero","zzEncode","zeroHash","from","fromString","toLong","fromHash","hash","toHash","mask","part0","part1","part2","src","newError","CustomError","captureStackTrace","writable","configurable","pool","versions","node","window","isFinite","isset","isSet","utf8Write","_Buffer_from","_Buffer_allocUnsafe","sizeOrArray","dcodeIO","key2Re","key32Re","key64Re","longToHash","longFromHash","fromBits","ProtocolError","fieldMap","longs","enums","encoding","allocUnsafe","seenFirstField","oneofProp","invalid","genVerifyValue","messageName","Op","noop","State","tail","states","writeByte","VarintOp","writeVarint64","writeFixed32","_push","writeBytes","reset","BufferWriter_","writeStringBuffer","writeBytesBuffer","copy","byteLength"],"mappings":";;;;;;AAAA,CAAA,SAAAA,IAAA,aAAA,CAAA,SAAAC,EAAAC,EAAAC,GAcA,IAAAC,EAPA,SAAAC,EAAAC,GACA,IAAAC,EAAAL,EAAAI,GAGA,OAFAC,GACAN,EAAAK,GAAA,GAAAE,KAAAD,EAAAL,EAAAI,GAAA,CAAAG,QAAA,EAAA,EAAAJ,EAAAE,EAAAA,EAAAE,OAAA,EACAF,EAAAE,OACA,EAEAN,EAAA,EAAA,EAGAC,EAAAM,KAAAC,OAAAP,SAAAA,EAGA,YAAA,OAAAQ,QAAAA,OAAAC,KACAD,OAAA,CAAA,QAAA,SAAAE,GAKA,OAJAA,GAAAA,EAAAC,SACAX,EAAAM,KAAAI,KAAAA,EACAV,EAAAY,UAAA,GAE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.min.js","sourcesContent":["(function prelude(modules, cache, entries) {\n\n // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS\n // sources through a conflict-free require shim and is again wrapped within an iife that\n // provides a minification-friendly `undefined` var plus a global \"use strict\" directive\n // so that minification can remove the directives of each module.\n\n function $require(name) {\n var $module = cache[name];\n if (!$module)\n modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports);\n return $module.exports;\n }\n\n var protobuf = $require(entries[0]);\n\n // Expose globally\n protobuf.util.global.protobuf = protobuf;\n\n // Be nice to AMD\n if (typeof define === \"function\" && define.amd)\n define([\"long\"], function(Long) {\n if (Long && Long.isLong) {\n protobuf.util.Long = Long;\n protobuf.configure();\n }\n return protobuf;\n });\n\n // Be nice to CommonJS\n if (typeof module === \"object\" && module && module.exports)\n module.exports = protobuf;\n\n})/* end of prelude */","\"use strict\";\r\nmodule.exports = asPromise;\r\n\r\n/**\r\n * Callback as used by {@link util.asPromise}.\r\n * @typedef asPromiseCallback\r\n * @type {function}\r\n * @param {Error|null} error Error, if any\r\n * @param {...*} params Additional arguments\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Returns a promise from a node-style callback function.\r\n * @memberof util\r\n * @param {asPromiseCallback} fn Function to call\r\n * @param {*} ctx Function context\r\n * @param {...*} params Function arguments\r\n * @returns {Promise<*>} Promisified function\r\n */\r\nfunction asPromise(fn, ctx/*, varargs */) {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0,\r\n index = 2,\r\n pending = true;\r\n while (index < arguments.length)\r\n params[offset++] = arguments[index++];\r\n return new Promise(function executor(resolve, reject) {\r\n params[offset] = function callback(err/*, varargs */) {\r\n if (pending) {\r\n pending = false;\r\n if (err)\r\n reject(err);\r\n else {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0;\r\n while (offset < params.length)\r\n params[offset++] = arguments[offset];\r\n resolve.apply(null, params);\r\n }\r\n }\r\n };\r\n try {\r\n fn.apply(ctx || null, params);\r\n } catch (err) {\r\n if (pending) {\r\n pending = false;\r\n reject(err);\r\n }\r\n }\r\n });\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal base64 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar base64 = exports;\r\n\r\n/**\r\n * Calculates the byte length of a base64 encoded string.\r\n * @param {string} string Base64 encoded string\r\n * @returns {number} Byte length\r\n */\r\nbase64.length = function length(string) {\r\n var p = string.length;\r\n if (!p)\r\n return 0;\r\n var n = 0;\r\n while (--p % 4 > 1 && string.charAt(p) === \"=\")\r\n ++n;\r\n return Math.ceil(string.length * 3) / 4 - n;\r\n};\r\n\r\n// Base64 encoding table\r\nvar b64 = new Array(64);\r\n\r\n// Base64 decoding table\r\nvar s64 = new Array(123);\r\n\r\n// 65..90, 97..122, 48..57, 43, 47\r\nfor (var i = 0; i < 64;)\r\n s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;\r\n\r\n/**\r\n * Encodes a buffer to a base64 encoded string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} Base64 encoded string\r\n */\r\nbase64.encode = function encode(buffer, start, end) {\r\n var parts = null,\r\n chunk = [];\r\n var i = 0, // output index\r\n j = 0, // goto index\r\n t; // temporary\r\n while (start < end) {\r\n var b = buffer[start++];\r\n switch (j) {\r\n case 0:\r\n chunk[i++] = b64[b >> 2];\r\n t = (b & 3) << 4;\r\n j = 1;\r\n break;\r\n case 1:\r\n chunk[i++] = b64[t | b >> 4];\r\n t = (b & 15) << 2;\r\n j = 2;\r\n break;\r\n case 2:\r\n chunk[i++] = b64[t | b >> 6];\r\n chunk[i++] = b64[b & 63];\r\n j = 0;\r\n break;\r\n }\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (j) {\r\n chunk[i++] = b64[t];\r\n chunk[i++] = 61;\r\n if (j === 1)\r\n chunk[i++] = 61;\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\nvar invalidEncoding = \"invalid encoding\";\r\n\r\n/**\r\n * Decodes a base64 encoded string to a buffer.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Number of bytes written\r\n * @throws {Error} If encoding is invalid\r\n */\r\nbase64.decode = function decode(string, buffer, offset) {\r\n var start = offset;\r\n var j = 0, // goto index\r\n t; // temporary\r\n for (var i = 0; i < string.length;) {\r\n var c = string.charCodeAt(i++);\r\n if (c === 61 && j > 1)\r\n break;\r\n if ((c = s64[c]) === undefined)\r\n throw Error(invalidEncoding);\r\n switch (j) {\r\n case 0:\r\n t = c;\r\n j = 1;\r\n break;\r\n case 1:\r\n buffer[offset++] = t << 2 | (c & 48) >> 4;\r\n t = c;\r\n j = 2;\r\n break;\r\n case 2:\r\n buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;\r\n t = c;\r\n j = 3;\r\n break;\r\n case 3:\r\n buffer[offset++] = (t & 3) << 6 | c;\r\n j = 0;\r\n break;\r\n }\r\n }\r\n if (j === 1)\r\n throw Error(invalidEncoding);\r\n return offset - start;\r\n};\r\n\r\n/**\r\n * Tests if the specified string appears to be base64 encoded.\r\n * @param {string} string String to test\r\n * @returns {boolean} `true` if probably base64 encoded, otherwise false\r\n */\r\nbase64.test = function test(string) {\r\n return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);\r\n};\r\n","\"use strict\";\r\nmodule.exports = codegen;\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @param {string[]} functionParams Function parameter names\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n */\r\nfunction codegen(functionParams, functionName) {\r\n\r\n /* istanbul ignore if */\r\n if (typeof functionParams === \"string\") {\r\n functionName = functionParams;\r\n functionParams = undefined;\r\n }\r\n\r\n var body = [];\r\n\r\n /**\r\n * Appends code to the function's body or finishes generation.\r\n * @typedef Codegen\r\n * @type {function}\r\n * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any\r\n * @param {...*} [formatParams] Format parameters\r\n * @returns {Codegen|Function} Itself or the generated function if finished\r\n * @throws {Error} If format parameter counts do not match\r\n */\r\n\r\n function Codegen(formatStringOrScope) {\r\n // note that explicit array handling below makes this ~50% faster\r\n\r\n // finish the function\r\n if (typeof formatStringOrScope !== \"string\") {\r\n var source = toString();\r\n if (codegen.verbose)\r\n console.log(\"codegen: \" + source); // eslint-disable-line no-console\r\n source = \"return \" + source;\r\n if (formatStringOrScope) {\r\n var scopeKeys = Object.keys(formatStringOrScope),\r\n scopeParams = new Array(scopeKeys.length + 1),\r\n scopeValues = new Array(scopeKeys.length),\r\n scopeOffset = 0;\r\n while (scopeOffset < scopeKeys.length) {\r\n scopeParams[scopeOffset] = scopeKeys[scopeOffset];\r\n scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]];\r\n }\r\n scopeParams[scopeOffset] = source;\r\n return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func\r\n }\r\n return Function(source)(); // eslint-disable-line no-new-func\r\n }\r\n\r\n // otherwise append to body\r\n var formatParams = new Array(arguments.length - 1),\r\n formatOffset = 0;\r\n while (formatOffset < formatParams.length)\r\n formatParams[formatOffset] = arguments[++formatOffset];\r\n formatOffset = 0;\r\n formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) {\r\n var value = formatParams[formatOffset++];\r\n switch ($1) {\r\n case \"d\": case \"f\": return String(Number(value));\r\n case \"i\": return String(Math.floor(value));\r\n case \"j\": return JSON.stringify(value);\r\n case \"s\": return String(value);\r\n }\r\n return \"%\";\r\n });\r\n if (formatOffset !== formatParams.length)\r\n throw Error(\"parameter count mismatch\");\r\n body.push(formatStringOrScope);\r\n return Codegen;\r\n }\r\n\r\n function toString(functionNameOverride) {\r\n return \"function \" + (functionNameOverride || functionName || \"\") + \"(\" + (functionParams && functionParams.join(\",\") || \"\") + \"){\\n \" + body.join(\"\\n \") + \"\\n}\";\r\n }\r\n\r\n Codegen.toString = toString;\r\n return Codegen;\r\n}\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @function codegen\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * When set to `true`, codegen will log generated code to console. Useful for debugging.\r\n * @name util.codegen.verbose\r\n * @type {boolean}\r\n */\r\ncodegen.verbose = false;\r\n","\"use strict\";\r\nmodule.exports = EventEmitter;\r\n\r\n/**\r\n * Constructs a new event emitter instance.\r\n * @classdesc A minimal event emitter.\r\n * @memberof util\r\n * @constructor\r\n */\r\nfunction EventEmitter() {\r\n\r\n /**\r\n * Registered listeners.\r\n * @type {Object.}\r\n * @private\r\n */\r\n this._listeners = {};\r\n}\r\n\r\n/**\r\n * Registers an event listener.\r\n * @param {string} evt Event name\r\n * @param {function} fn Listener\r\n * @param {*} [ctx] Listener context\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.on = function on(evt, fn, ctx) {\r\n (this._listeners[evt] || (this._listeners[evt] = [])).push({\r\n fn : fn,\r\n ctx : ctx || this\r\n });\r\n return this;\r\n};\r\n\r\n/**\r\n * Removes an event listener or any matching listeners if arguments are omitted.\r\n * @param {string} [evt] Event name. Removes all listeners if omitted.\r\n * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.off = function off(evt, fn) {\r\n if (evt === undefined)\r\n this._listeners = {};\r\n else {\r\n if (fn === undefined)\r\n this._listeners[evt] = [];\r\n else {\r\n var listeners = this._listeners[evt];\r\n for (var i = 0; i < listeners.length;)\r\n if (listeners[i].fn === fn)\r\n listeners.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emits an event by calling its listeners with the specified arguments.\r\n * @param {string} evt Event name\r\n * @param {...*} args Arguments\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.emit = function emit(evt) {\r\n var listeners = this._listeners[evt];\r\n if (listeners) {\r\n var args = [],\r\n i = 1;\r\n for (; i < arguments.length;)\r\n args.push(arguments[i++]);\r\n for (i = 0; i < listeners.length;)\r\n listeners[i].fn.apply(listeners[i++].ctx, args);\r\n }\r\n return this;\r\n};\r\n","\"use strict\";\r\nmodule.exports = fetch;\r\n\r\nvar asPromise = require(1),\r\n inquire = require(7);\r\n\r\nvar fs = inquire(\"fs\");\r\n\r\n/**\r\n * Node-style callback as used by {@link util.fetch}.\r\n * @typedef FetchCallback\r\n * @type {function}\r\n * @param {?Error} error Error, if any, otherwise `null`\r\n * @param {string} [contents] File contents, if there hasn't been an error\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Options as used by {@link util.fetch}.\r\n * @typedef FetchOptions\r\n * @type {Object}\r\n * @property {boolean} [binary=false] Whether expecting a binary response\r\n * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @memberof util\r\n * @param {string} filename File path or url\r\n * @param {FetchOptions} options Fetch options\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n */\r\nfunction fetch(filename, options, callback) {\r\n if (typeof options === \"function\") {\r\n callback = options;\r\n options = {};\r\n } else if (!options)\r\n options = {};\r\n\r\n if (!callback)\r\n return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this\r\n\r\n // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found.\r\n if (!options.xhr && fs && fs.readFile)\r\n return fs.readFile(filename, function fetchReadFileCallback(err, contents) {\r\n return err && typeof XMLHttpRequest !== \"undefined\"\r\n ? fetch.xhr(filename, options, callback)\r\n : err\r\n ? callback(err)\r\n : callback(null, options.binary ? contents : contents.toString(\"utf8\"));\r\n });\r\n\r\n // use the XHR version otherwise.\r\n return fetch.xhr(filename, options, callback);\r\n}\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchOptions} [options] Fetch options\r\n * @returns {Promise} Promise\r\n * @variation 3\r\n */\r\n\r\n/**/\r\nfetch.xhr = function fetch_xhr(filename, options, callback) {\r\n var xhr = new XMLHttpRequest();\r\n xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() {\r\n\r\n if (xhr.readyState !== 4)\r\n return undefined;\r\n\r\n // local cors security errors return status 0 / empty string, too. afaik this cannot be\r\n // reliably distinguished from an actually empty file for security reasons. feel free\r\n // to send a pull request if you are aware of a solution.\r\n if (xhr.status !== 0 && xhr.status !== 200)\r\n return callback(Error(\"status \" + xhr.status));\r\n\r\n // if binary data is expected, make sure that some sort of array is returned, even if\r\n // ArrayBuffers are not supported. the binary string fallback, however, is unsafe.\r\n if (options.binary) {\r\n var buffer = xhr.response;\r\n if (!buffer) {\r\n buffer = [];\r\n for (var i = 0; i < xhr.responseText.length; ++i)\r\n buffer.push(xhr.responseText.charCodeAt(i) & 255);\r\n }\r\n return callback(null, typeof Uint8Array !== \"undefined\" ? new Uint8Array(buffer) : buffer);\r\n }\r\n return callback(null, xhr.responseText);\r\n };\r\n\r\n if (options.binary) {\r\n // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers\r\n if (\"overrideMimeType\" in xhr)\r\n xhr.overrideMimeType(\"text/plain; charset=x-user-defined\");\r\n xhr.responseType = \"arraybuffer\";\r\n }\r\n\r\n xhr.open(\"GET\", filename);\r\n xhr.send();\r\n};\r\n","\"use strict\";\r\n\r\nmodule.exports = factory(factory);\r\n\r\n/**\r\n * Reads / writes floats / doubles from / to buffers.\r\n * @name util.float\r\n * @namespace\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using little endian byte order.\r\n * @name util.float.writeFloatLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using big endian byte order.\r\n * @name util.float.writeFloatBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using little endian byte order.\r\n * @name util.float.readFloatLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using big endian byte order.\r\n * @name util.float.readFloatBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using little endian byte order.\r\n * @name util.float.writeDoubleLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using big endian byte order.\r\n * @name util.float.writeDoubleBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using little endian byte order.\r\n * @name util.float.readDoubleLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using big endian byte order.\r\n * @name util.float.readDoubleBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n// Factory function for the purpose of node-based testing in modified global environments\r\nfunction factory(exports) {\r\n\r\n // float: typed array\r\n if (typeof Float32Array !== \"undefined\") (function() {\r\n\r\n var f32 = new Float32Array([ -0 ]),\r\n f8b = new Uint8Array(f32.buffer),\r\n le = f8b[3] === 128;\r\n\r\n function writeFloat_f32_cpy(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n }\r\n\r\n function writeFloat_f32_rev(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[3];\r\n buf[pos + 1] = f8b[2];\r\n buf[pos + 2] = f8b[1];\r\n buf[pos + 3] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;\r\n\r\n function readFloat_f32_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n function readFloat_f32_rev(buf, pos) {\r\n f8b[3] = buf[pos ];\r\n f8b[2] = buf[pos + 1];\r\n f8b[1] = buf[pos + 2];\r\n f8b[0] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;\r\n\r\n // float: ieee754\r\n })(); else (function() {\r\n\r\n function writeFloat_ieee754(writeUint, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0)\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);\r\n else if (isNaN(val))\r\n writeUint(2143289344, buf, pos);\r\n else if (val > 3.4028234663852886e+38) // +-Infinity\r\n writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);\r\n else if (val < 1.1754943508222875e-38) // denormal\r\n writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);\r\n else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2),\r\n mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;\r\n writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);\r\n }\r\n }\r\n\r\n exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);\r\n exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);\r\n\r\n function readFloat_ieee754(readUint, buf, pos) {\r\n var uint = readUint(buf, pos),\r\n sign = (uint >> 31) * 2 + 1,\r\n exponent = uint >>> 23 & 255,\r\n mantissa = uint & 8388607;\r\n return exponent === 255\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 1.401298464324817e-45 * mantissa\r\n : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);\r\n }\r\n\r\n exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);\r\n exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);\r\n\r\n })();\r\n\r\n // double: typed array\r\n if (typeof Float64Array !== \"undefined\") (function() {\r\n\r\n var f64 = new Float64Array([-0]),\r\n f8b = new Uint8Array(f64.buffer),\r\n le = f8b[7] === 128;\r\n\r\n function writeDouble_f64_cpy(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n buf[pos + 4] = f8b[4];\r\n buf[pos + 5] = f8b[5];\r\n buf[pos + 6] = f8b[6];\r\n buf[pos + 7] = f8b[7];\r\n }\r\n\r\n function writeDouble_f64_rev(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[7];\r\n buf[pos + 1] = f8b[6];\r\n buf[pos + 2] = f8b[5];\r\n buf[pos + 3] = f8b[4];\r\n buf[pos + 4] = f8b[3];\r\n buf[pos + 5] = f8b[2];\r\n buf[pos + 6] = f8b[1];\r\n buf[pos + 7] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;\r\n\r\n function readDouble_f64_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n f8b[4] = buf[pos + 4];\r\n f8b[5] = buf[pos + 5];\r\n f8b[6] = buf[pos + 6];\r\n f8b[7] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n function readDouble_f64_rev(buf, pos) {\r\n f8b[7] = buf[pos ];\r\n f8b[6] = buf[pos + 1];\r\n f8b[5] = buf[pos + 2];\r\n f8b[4] = buf[pos + 3];\r\n f8b[3] = buf[pos + 4];\r\n f8b[2] = buf[pos + 5];\r\n f8b[1] = buf[pos + 6];\r\n f8b[0] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;\r\n\r\n // double: ieee754\r\n })(); else (function() {\r\n\r\n function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);\r\n } else if (isNaN(val)) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(2146959360, buf, pos + off1);\r\n } else if (val > 1.7976931348623157e+308) { // +-Infinity\r\n writeUint(0, buf, pos + off0);\r\n writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);\r\n } else {\r\n var mantissa;\r\n if (val < 2.2250738585072014e-308) { // denormal\r\n mantissa = val / 5e-324;\r\n writeUint(mantissa >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);\r\n } else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2);\r\n if (exponent === 1024)\r\n exponent = 1023;\r\n mantissa = val * Math.pow(2, -exponent);\r\n writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);\r\n }\r\n }\r\n }\r\n\r\n exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);\r\n exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);\r\n\r\n function readDouble_ieee754(readUint, off0, off1, buf, pos) {\r\n var lo = readUint(buf, pos + off0),\r\n hi = readUint(buf, pos + off1);\r\n var sign = (hi >> 31) * 2 + 1,\r\n exponent = hi >>> 20 & 2047,\r\n mantissa = 4294967296 * (hi & 1048575) + lo;\r\n return exponent === 2047\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 5e-324 * mantissa\r\n : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);\r\n }\r\n\r\n exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);\r\n exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);\r\n\r\n })();\r\n\r\n return exports;\r\n}\r\n\r\n// uint helpers\r\n\r\nfunction writeUintLE(val, buf, pos) {\r\n buf[pos ] = val & 255;\r\n buf[pos + 1] = val >>> 8 & 255;\r\n buf[pos + 2] = val >>> 16 & 255;\r\n buf[pos + 3] = val >>> 24;\r\n}\r\n\r\nfunction writeUintBE(val, buf, pos) {\r\n buf[pos ] = val >>> 24;\r\n buf[pos + 1] = val >>> 16 & 255;\r\n buf[pos + 2] = val >>> 8 & 255;\r\n buf[pos + 3] = val & 255;\r\n}\r\n\r\nfunction readUintLE(buf, pos) {\r\n return (buf[pos ]\r\n | buf[pos + 1] << 8\r\n | buf[pos + 2] << 16\r\n | buf[pos + 3] << 24) >>> 0;\r\n}\r\n\r\nfunction readUintBE(buf, pos) {\r\n return (buf[pos ] << 24\r\n | buf[pos + 1] << 16\r\n | buf[pos + 2] << 8\r\n | buf[pos + 3]) >>> 0;\r\n}\r\n","\"use strict\";\r\nmodule.exports = inquire;\r\n\r\n/**\r\n * Requires a module only if available.\r\n * @memberof util\r\n * @param {string} moduleName Module to require\r\n * @returns {?Object} Required module if available and not empty, otherwise `null`\r\n */\r\nfunction inquire(moduleName) {\r\n try {\r\n var mod = eval(\"quire\".replace(/^/,\"re\"))(moduleName); // eslint-disable-line no-eval\r\n if (mod && (mod.length || Object.keys(mod).length))\r\n return mod;\r\n } catch (e) {} // eslint-disable-line no-empty\r\n return null;\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal path module to resolve Unix, Windows and URL paths alike.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar path = exports;\r\n\r\nvar isAbsolute =\r\n/**\r\n * Tests if the specified path is absolute.\r\n * @param {string} path Path to test\r\n * @returns {boolean} `true` if path is absolute\r\n */\r\npath.isAbsolute = function isAbsolute(path) {\r\n return /^(?:\\/|\\w+:)/.test(path);\r\n};\r\n\r\nvar normalize =\r\n/**\r\n * Normalizes the specified path.\r\n * @param {string} path Path to normalize\r\n * @returns {string} Normalized path\r\n */\r\npath.normalize = function normalize(path) {\r\n path = path.replace(/\\\\/g, \"/\")\r\n .replace(/\\/{2,}/g, \"/\");\r\n var parts = path.split(\"/\"),\r\n absolute = isAbsolute(path),\r\n prefix = \"\";\r\n if (absolute)\r\n prefix = parts.shift() + \"/\";\r\n for (var i = 0; i < parts.length;) {\r\n if (parts[i] === \"..\") {\r\n if (i > 0 && parts[i - 1] !== \"..\")\r\n parts.splice(--i, 2);\r\n else if (absolute)\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n } else if (parts[i] === \".\")\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n return prefix + parts.join(\"/\");\r\n};\r\n\r\n/**\r\n * Resolves the specified include path against the specified origin path.\r\n * @param {string} originPath Path to the origin file\r\n * @param {string} includePath Include path relative to origin path\r\n * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized\r\n * @returns {string} Path to the include file\r\n */\r\npath.resolve = function resolve(originPath, includePath, alreadyNormalized) {\r\n if (!alreadyNormalized)\r\n includePath = normalize(includePath);\r\n if (isAbsolute(includePath))\r\n return includePath;\r\n if (!alreadyNormalized)\r\n originPath = normalize(originPath);\r\n return (originPath = originPath.replace(/(?:\\/|^)[^/]+$/, \"\")).length ? normalize(originPath + \"/\" + includePath) : includePath;\r\n};\r\n","\"use strict\";\r\nmodule.exports = pool;\r\n\r\n/**\r\n * An allocator as used by {@link util.pool}.\r\n * @typedef PoolAllocator\r\n * @type {function}\r\n * @param {number} size Buffer size\r\n * @returns {Uint8Array} Buffer\r\n */\r\n\r\n/**\r\n * A slicer as used by {@link util.pool}.\r\n * @typedef PoolSlicer\r\n * @type {function}\r\n * @param {number} start Start offset\r\n * @param {number} end End offset\r\n * @returns {Uint8Array} Buffer slice\r\n * @this {Uint8Array}\r\n */\r\n\r\n/**\r\n * A general purpose buffer pool.\r\n * @memberof util\r\n * @function\r\n * @param {PoolAllocator} alloc Allocator\r\n * @param {PoolSlicer} slice Slicer\r\n * @param {number} [size=8192] Slab size\r\n * @returns {PoolAllocator} Pooled allocator\r\n */\r\nfunction pool(alloc, slice, size) {\r\n var SIZE = size || 8192;\r\n var MAX = SIZE >>> 1;\r\n var slab = null;\r\n var offset = SIZE;\r\n return function pool_alloc(size) {\r\n if (size < 1 || size > MAX)\r\n return alloc(size);\r\n if (offset + size > SIZE) {\r\n slab = alloc(SIZE);\r\n offset = 0;\r\n }\r\n var buf = slice.call(slab, offset, offset += size);\r\n if (offset & 7) // align to 32 bit\r\n offset = (offset | 7) + 1;\r\n return buf;\r\n };\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal UTF8 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar utf8 = exports;\r\n\r\n/**\r\n * Calculates the UTF8 byte length of a string.\r\n * @param {string} string String\r\n * @returns {number} Byte length\r\n */\r\nutf8.length = function utf8_length(string) {\r\n var len = 0,\r\n c = 0;\r\n for (var i = 0; i < string.length; ++i) {\r\n c = string.charCodeAt(i);\r\n if (c < 128)\r\n len += 1;\r\n else if (c < 2048)\r\n len += 2;\r\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\r\n ++i;\r\n len += 4;\r\n } else\r\n len += 3;\r\n }\r\n return len;\r\n};\r\n\r\n/**\r\n * Reads UTF8 bytes as a string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} String read\r\n */\r\nutf8.read = function utf8_read(buffer, start, end) {\r\n var len = end - start;\r\n if (len < 1)\r\n return \"\";\r\n var parts = null,\r\n chunk = [],\r\n i = 0, // char offset\r\n t; // temporary\r\n while (start < end) {\r\n t = buffer[start++];\r\n if (t < 128)\r\n chunk[i++] = t;\r\n else if (t > 191 && t < 224)\r\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\r\n else if (t > 239 && t < 365) {\r\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\r\n chunk[i++] = 0xD800 + (t >> 10);\r\n chunk[i++] = 0xDC00 + (t & 1023);\r\n } else\r\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\n/**\r\n * Writes a string as UTF8 bytes.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Bytes written\r\n */\r\nutf8.write = function utf8_write(string, buffer, offset) {\r\n var start = offset,\r\n c1, // character 1\r\n c2; // character 2\r\n for (var i = 0; i < string.length; ++i) {\r\n c1 = string.charCodeAt(i);\r\n if (c1 < 128) {\r\n buffer[offset++] = c1;\r\n } else if (c1 < 2048) {\r\n buffer[offset++] = c1 >> 6 | 192;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\r\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\r\n ++i;\r\n buffer[offset++] = c1 >> 18 | 240;\r\n buffer[offset++] = c1 >> 12 & 63 | 128;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else {\r\n buffer[offset++] = c1 >> 12 | 224;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n }\r\n }\r\n return offset - start;\r\n};\r\n","\"use strict\";\nmodule.exports = common;\n\nvar commonRe = /\\/|\\./;\n\n/**\n * Provides common type definitions.\n * Can also be used to provide additional google types or your own custom types.\n * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name\n * @param {Object.} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition\n * @returns {undefined}\n * @property {INamespace} google/protobuf/any.proto Any\n * @property {INamespace} google/protobuf/duration.proto Duration\n * @property {INamespace} google/protobuf/empty.proto Empty\n * @property {INamespace} google/protobuf/field_mask.proto FieldMask\n * @property {INamespace} google/protobuf/struct.proto Struct, Value, NullValue and ListValue\n * @property {INamespace} google/protobuf/timestamp.proto Timestamp\n * @property {INamespace} google/protobuf/wrappers.proto Wrappers\n * @example\n * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension)\n * protobuf.common(\"descriptor\", descriptorJson);\n *\n * // manually provides a custom definition (uses my.foo namespace)\n * protobuf.common(\"my/foo/bar.proto\", myFooBarJson);\n */\nfunction common(name, json) {\n if (!commonRe.test(name)) {\n name = \"google/protobuf/\" + name + \".proto\";\n json = { nested: { google: { nested: { protobuf: { nested: json } } } } };\n }\n common[name] = json;\n}\n\n// Not provided because of limited use (feel free to discuss or to provide yourself):\n//\n// google/protobuf/descriptor.proto\n// google/protobuf/source_context.proto\n// google/protobuf/type.proto\n//\n// Stripped and pre-parsed versions of these non-bundled files are instead available as part of\n// the repository or package within the google/protobuf directory.\n\ncommon(\"any\", {\n\n /**\n * Properties of a google.protobuf.Any message.\n * @interface IAny\n * @type {Object}\n * @property {string} [typeUrl]\n * @property {Uint8Array} [bytes]\n * @memberof common\n */\n Any: {\n fields: {\n type_url: {\n type: \"string\",\n id: 1\n },\n value: {\n type: \"bytes\",\n id: 2\n }\n }\n }\n});\n\nvar timeType;\n\ncommon(\"duration\", {\n\n /**\n * Properties of a google.protobuf.Duration message.\n * @interface IDuration\n * @type {Object}\n * @property {number|Long} [seconds]\n * @property {number} [nanos]\n * @memberof common\n */\n Duration: timeType = {\n fields: {\n seconds: {\n type: \"int64\",\n id: 1\n },\n nanos: {\n type: \"int32\",\n id: 2\n }\n }\n }\n});\n\ncommon(\"timestamp\", {\n\n /**\n * Properties of a google.protobuf.Timestamp message.\n * @interface ITimestamp\n * @type {Object}\n * @property {number|Long} [seconds]\n * @property {number} [nanos]\n * @memberof common\n */\n Timestamp: timeType\n});\n\ncommon(\"empty\", {\n\n /**\n * Properties of a google.protobuf.Empty message.\n * @interface IEmpty\n * @memberof common\n */\n Empty: {\n fields: {}\n }\n});\n\ncommon(\"struct\", {\n\n /**\n * Properties of a google.protobuf.Struct message.\n * @interface IStruct\n * @type {Object}\n * @property {Object.} [fields]\n * @memberof common\n */\n Struct: {\n fields: {\n fields: {\n keyType: \"string\",\n type: \"Value\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.Value message.\n * @interface IValue\n * @type {Object}\n * @property {string} [kind]\n * @property {0} [nullValue]\n * @property {number} [numberValue]\n * @property {string} [stringValue]\n * @property {boolean} [boolValue]\n * @property {IStruct} [structValue]\n * @property {IListValue} [listValue]\n * @memberof common\n */\n Value: {\n oneofs: {\n kind: {\n oneof: [\n \"nullValue\",\n \"numberValue\",\n \"stringValue\",\n \"boolValue\",\n \"structValue\",\n \"listValue\"\n ]\n }\n },\n fields: {\n nullValue: {\n type: \"NullValue\",\n id: 1\n },\n numberValue: {\n type: \"double\",\n id: 2\n },\n stringValue: {\n type: \"string\",\n id: 3\n },\n boolValue: {\n type: \"bool\",\n id: 4\n },\n structValue: {\n type: \"Struct\",\n id: 5\n },\n listValue: {\n type: \"ListValue\",\n id: 6\n }\n }\n },\n\n NullValue: {\n values: {\n NULL_VALUE: 0\n }\n },\n\n /**\n * Properties of a google.protobuf.ListValue message.\n * @interface IListValue\n * @type {Object}\n * @property {Array.} [values]\n * @memberof common\n */\n ListValue: {\n fields: {\n values: {\n rule: \"repeated\",\n type: \"Value\",\n id: 1\n }\n }\n }\n});\n\ncommon(\"wrappers\", {\n\n /**\n * Properties of a google.protobuf.DoubleValue message.\n * @interface IDoubleValue\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n DoubleValue: {\n fields: {\n value: {\n type: \"double\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.FloatValue message.\n * @interface IFloatValue\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n FloatValue: {\n fields: {\n value: {\n type: \"float\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.Int64Value message.\n * @interface IInt64Value\n * @type {Object}\n * @property {number|Long} [value]\n * @memberof common\n */\n Int64Value: {\n fields: {\n value: {\n type: \"int64\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.UInt64Value message.\n * @interface IUInt64Value\n * @type {Object}\n * @property {number|Long} [value]\n * @memberof common\n */\n UInt64Value: {\n fields: {\n value: {\n type: \"uint64\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.Int32Value message.\n * @interface IInt32Value\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n Int32Value: {\n fields: {\n value: {\n type: \"int32\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.UInt32Value message.\n * @interface IUInt32Value\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n UInt32Value: {\n fields: {\n value: {\n type: \"uint32\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.BoolValue message.\n * @interface IBoolValue\n * @type {Object}\n * @property {boolean} [value]\n * @memberof common\n */\n BoolValue: {\n fields: {\n value: {\n type: \"bool\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.StringValue message.\n * @interface IStringValue\n * @type {Object}\n * @property {string} [value]\n * @memberof common\n */\n StringValue: {\n fields: {\n value: {\n type: \"string\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.BytesValue message.\n * @interface IBytesValue\n * @type {Object}\n * @property {Uint8Array} [value]\n * @memberof common\n */\n BytesValue: {\n fields: {\n value: {\n type: \"bytes\",\n id: 1\n }\n }\n }\n});\n\ncommon(\"field_mask\", {\n\n /**\n * Properties of a google.protobuf.FieldMask message.\n * @interface IDoubleValue\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n FieldMask: {\n fields: {\n paths: {\n rule: \"repeated\",\n type: \"string\",\n id: 1\n }\n }\n }\n});\n\n/**\n * Gets the root definition of the specified common proto file.\n *\n * Bundled definitions are:\n * - google/protobuf/any.proto\n * - google/protobuf/duration.proto\n * - google/protobuf/empty.proto\n * - google/protobuf/field_mask.proto\n * - google/protobuf/struct.proto\n * - google/protobuf/timestamp.proto\n * - google/protobuf/wrappers.proto\n *\n * @param {string} file Proto file name\n * @returns {INamespace|null} Root definition or `null` if not defined\n */\ncommon.get = function get(file) {\n return common[file] || null;\n};\n","\"use strict\";\n/**\n * Runtime message from/to plain object converters.\n * @namespace\n */\nvar converter = exports;\n\nvar Enum = require(15),\n util = require(37);\n\n/**\n * Generates a partial value fromObject conveter.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {number} fieldIndex Field index\n * @param {string} prop Property reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genValuePartial_fromObject(gen, field, fieldIndex, prop) {\n var defaultAlreadyEmitted = false;\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n if (field.resolvedType) {\n if (field.resolvedType instanceof Enum) { gen\n (\"switch(d%s){\", prop);\n for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {\n // enum unknown values passthrough\n if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen\n (\"default:\")\n (\"if(typeof(d%s)===\\\"number\\\"){m%s=d%s;break}\", prop, prop, prop);\n if (!field.repeated) gen // fallback to default value only for\n // arrays, to avoid leaving holes.\n (\"break\"); // for non-repeated fields, just ignore\n defaultAlreadyEmitted = true;\n }\n gen\n (\"case%j:\", keys[i])\n (\"case %i:\", values[keys[i]])\n (\"m%s=%j\", prop, values[keys[i]])\n (\"break\");\n } gen\n (\"}\");\n } else gen\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\n (\"m%s=types[%i].fromObject(d%s)\", prop, fieldIndex, prop);\n } else {\n var isUnsigned = false;\n switch (field.type) {\n case \"double\":\n case \"float\": gen\n (\"m%s=Number(d%s)\", prop, prop); // also catches \"NaN\", \"Infinity\"\n break;\n case \"uint32\":\n case \"fixed32\": gen\n (\"m%s=d%s>>>0\", prop, prop);\n break;\n case \"int32\":\n case \"sint32\":\n case \"sfixed32\": gen\n (\"m%s=d%s|0\", prop, prop);\n break;\n case \"uint64\":\n isUnsigned = true;\n // eslint-disable-next-line no-fallthrough\n case \"int64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(util.Long)\")\n (\"(m%s=util.Long.fromValue(d%s)).unsigned=%j\", prop, prop, isUnsigned)\n (\"else if(typeof d%s===\\\"string\\\")\", prop)\n (\"m%s=parseInt(d%s,10)\", prop, prop)\n (\"else if(typeof d%s===\\\"number\\\")\", prop)\n (\"m%s=d%s\", prop, prop)\n (\"else if(typeof d%s===\\\"object\\\")\", prop)\n (\"m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)\", prop, prop, prop, isUnsigned ? \"true\" : \"\");\n break;\n case \"bytes\": gen\n (\"if(typeof d%s===\\\"string\\\")\", prop)\n (\"util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)\", prop, prop, prop)\n (\"else if(d%s.length >= 0)\", prop)\n (\"m%s=d%s\", prop, prop);\n break;\n case \"string\": gen\n (\"m%s=String(d%s)\", prop, prop);\n break;\n case \"bool\": gen\n (\"m%s=Boolean(d%s)\", prop, prop);\n break;\n /* default: gen\n (\"m%s=d%s\", prop, prop);\n break; */\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n\n/**\n * Generates a plain object to runtime message converter specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nconverter.fromObject = function fromObject(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var fields = mtype.fieldsArray;\n var gen = util.codegen([\"d\"], mtype.name + \"$fromObject\")\n (\"if(d instanceof this.ctor)\")\n (\"return d\");\n if (!fields.length) return gen\n (\"return new this.ctor\");\n gen\n (\"var m=new this.ctor\");\n for (var i = 0; i < fields.length; ++i) {\n var field = fields[i].resolve(),\n prop = util.safeProp(field.name);\n\n // Map fields\n if (field.map) { gen\n (\"if(d%s){\", prop)\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\n (\"m%s={}\", prop)\n (\"for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s\", prop, prop, prop, prop, isUnsigned ? \"true\": \"\", prop);\n break;\n case \"bytes\": gen\n (\"d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s\", prop, prop, prop, prop, prop);\n break;\n default: gen\n (\"d%s=m%s\", prop, prop);\n break;\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n\n/**\n * Generates a runtime message to plain object converter specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nconverter.toObject = function toObject(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById);\n if (!fields.length)\n return util.codegen()(\"return {}\");\n var gen = util.codegen([\"m\", \"o\"], mtype.name + \"$toObject\")\n (\"if(!o)\")\n (\"o={}\")\n (\"var d={}\");\n\n var repeatedFields = [],\n mapFields = [],\n normalFields = [],\n i = 0;\n for (; i < fields.length; ++i)\n if (!fields[i].partOf)\n ( fields[i].resolve().repeated ? repeatedFields\n : fields[i].map ? mapFields\n : normalFields).push(fields[i]);\n\n if (repeatedFields.length) { gen\n (\"if(o.arrays||o.defaults){\");\n for (i = 0; i < repeatedFields.length; ++i) gen\n (\"d%s=[]\", util.safeProp(repeatedFields[i].name));\n gen\n (\"}\");\n }\n\n if (mapFields.length) { gen\n (\"if(o.objects||o.defaults){\");\n for (i = 0; i < mapFields.length; ++i) gen\n (\"d%s={}\", util.safeProp(mapFields[i].name));\n gen\n (\"}\");\n }\n\n if (normalFields.length) { gen\n (\"if(o.defaults){\");\n for (i = 0; i < normalFields.length; ++i) {\n var field = normalFields[i],\n prop = util.safeProp(field.name);\n if (field.resolvedType instanceof Enum) gen\n (\"d%s=o.enums===String?%j:%j\", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault);\n else if (field.long) gen\n (\"if(util.Long){\")\n (\"var n=new util.Long(%i,%i,%j)\", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)\n (\"d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n\", prop)\n (\"}else\")\n (\"d%s=o.longs===String?%j:%i\", prop, field.typeDefault.toString(), field.typeDefault.toNumber());\n else if (field.bytes) {\n var arrayDefault = \"[\" + Array.prototype.slice.call(field.typeDefault).join(\",\") + \"]\";\n gen\n (\"if(o.bytes===String)d%s=%j\", prop, String.fromCharCode.apply(String, field.typeDefault))\n (\"else{\")\n (\"d%s=%s\", prop, arrayDefault)\n (\"if(o.bytes!==Array)d%s=util.newBuffer(d%s)\", prop, prop)\n (\"}\");\n } else gen\n (\"d%s=%j\", prop, field.typeDefault); // also messages (=null)\n } gen\n (\"}\");\n }\n var hasKs2 = false;\n for (i = 0; i < fields.length; ++i) {\n var field = fields[i],\n index = mtype._fieldsArray.indexOf(field),\n prop = util.safeProp(field.name);\n if (field.map) {\n if (!hasKs2) { hasKs2 = true; gen\n (\"var ks2\");\n } gen\n (\"if(m%s&&(ks2=Object.keys(m%s)).length){\", prop, prop)\n (\"d%s={}\", prop)\n (\"for(var j=0;j>>3){\");\n\n var i = 0;\n for (; i < /* initializes */ mtype.fieldsArray.length; ++i) {\n var field = mtype._fieldsArray[i].resolve(),\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\n ref = \"m\" + util.safeProp(field.name); gen\n (\"case %i: {\", field.id);\n\n // Map fields\n if (field.map) { gen\n (\"if(%s===util.emptyObject)\", ref)\n (\"%s={}\", ref)\n (\"var c2 = r.uint32()+r.pos\");\n\n if (types.defaults[field.keyType] !== undefined) gen\n (\"k=%j\", types.defaults[field.keyType]);\n else gen\n (\"k=null\");\n\n if (types.defaults[type] !== undefined) gen\n (\"value=%j\", types.defaults[type]);\n else gen\n (\"value=null\");\n\n gen\n (\"while(r.pos>>3){\")\n (\"case 1: k=r.%s(); break\", field.keyType)\n (\"case 2:\");\n\n if (types.basic[type] === undefined) gen\n (\"value=types[%i].decode(r,r.uint32())\", i); // can't be groups\n else gen\n (\"value=r.%s()\", type);\n\n gen\n (\"break\")\n (\"default:\")\n (\"r.skipType(tag2&7)\")\n (\"break\")\n (\"}\")\n (\"}\");\n\n if (types.long[field.keyType] !== undefined) gen\n (\"%s[typeof k===\\\"object\\\"?util.longToHash(k):k]=value\", ref);\n else gen\n (\"%s[k]=value\", ref);\n\n // Repeated fields\n } else if (field.repeated) { gen\n\n (\"if(!(%s&&%s.length))\", ref, ref)\n (\"%s=[]\", ref);\n\n // Packable (always check for forward and backward compatiblity)\n if (types.packed[type] !== undefined) gen\n (\"if((t&7)===2){\")\n (\"var c2=r.uint32()+r.pos\")\n (\"while(r.pos>> 0, (field.id << 3 | 4) >>> 0)\n : gen(\"types[%i].encode(%s,w.uint32(%i).fork()).ldelim()\", fieldIndex, ref, (field.id << 3 | 2) >>> 0);\n}\n\n/**\n * Generates an encoder specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nfunction encoder(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var gen = util.codegen([\"m\", \"w\"], mtype.name + \"$encode\")\n (\"if(!w)\")\n (\"w=Writer.create()\");\n\n var i, ref;\n\n // \"when a message is serialized its known fields should be written sequentially by field number\"\n var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById);\n\n for (var i = 0; i < fields.length; ++i) {\n var field = fields[i].resolve(),\n index = mtype._fieldsArray.indexOf(field),\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\n wireType = types.basic[type];\n ref = \"m\" + util.safeProp(field.name);\n\n // Map fields\n if (field.map) {\n gen\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j)){\", ref, field.name) // !== undefined && !== null\n (\"for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType);\n if (wireType === undefined) gen\n (\"types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()\", index, ref); // can't be groups\n else gen\n (\".uint32(%i).%s(%s[ks[i]]).ldelim()\", 16 | wireType, type, ref);\n gen\n (\"}\")\n (\"}\");\n\n // Repeated fields\n } else if (field.repeated) { gen\n (\"if(%s!=null&&%s.length){\", ref, ref); // !== undefined && !== null\n\n // Packed repeated\n if (field.packed && types.packed[type] !== undefined) { gen\n\n (\"w.uint32(%i).fork()\", (field.id << 3 | 2) >>> 0)\n (\"for(var i=0;i<%s.length;++i)\", ref)\n (\"w.%s(%s[i])\", type, ref)\n (\"w.ldelim()\");\n\n // Non-packed\n } else { gen\n\n (\"for(var i=0;i<%s.length;++i)\", ref);\n if (wireType === undefined)\n genTypePartial(gen, field, index, ref + \"[i]\");\n else gen\n (\"w.uint32(%i).%s(%s[i])\", (field.id << 3 | wireType) >>> 0, type, ref);\n\n } gen\n (\"}\");\n\n // Non-repeated\n } else {\n if (field.optional) gen\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j))\", ref, field.name); // !== undefined && !== null\n\n if (wireType === undefined)\n genTypePartial(gen, field, index, ref);\n else gen\n (\"w.uint32(%i).%s(%s)\", (field.id << 3 | wireType) >>> 0, type, ref);\n\n }\n }\n\n return gen\n (\"return w\");\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n","\"use strict\";\nmodule.exports = Enum;\n\n// extends ReflectionObject\nvar ReflectionObject = require(24);\n((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = \"Enum\";\n\nvar Namespace = require(23),\n util = require(37);\n\n/**\n * Constructs a new enum instance.\n * @classdesc Reflected enum.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {Object.} [values] Enum values as an object, by name\n * @param {Object.} [options] Declared options\n * @param {string} [comment] The comment for this enum\n * @param {Object.} [comments] The value comments for this enum\n * @param {Object.>|undefined} [valuesOptions] The value options for this enum\n */\nfunction Enum(name, values, options, comment, comments, valuesOptions) {\n ReflectionObject.call(this, name, options);\n\n if (values && typeof values !== \"object\")\n throw TypeError(\"values must be an object\");\n\n /**\n * Enum values by id.\n * @type {Object.}\n */\n this.valuesById = {};\n\n /**\n * Enum values by name.\n * @type {Object.}\n */\n this.values = Object.create(this.valuesById); // toJSON, marker\n\n /**\n * Enum comment text.\n * @type {string|null}\n */\n this.comment = comment;\n\n /**\n * Value comment texts, if any.\n * @type {Object.}\n */\n this.comments = comments || {};\n\n /**\n * Values options, if any\n * @type {Object>|undefined}\n */\n this.valuesOptions = valuesOptions;\n\n /**\n * Resolved values features, if any\n * @type {Object>|undefined}\n */\n this._valuesFeatures = {};\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n // Note that values inherit valuesById on their prototype which makes them a TypeScript-\n // compatible enum. This is used by pbts to write actual enum definitions that work for\n // static and reflection code alike instead of emitting generic object definitions.\n\n if (values)\n for (var keys = Object.keys(values), i = 0; i < keys.length; ++i)\n if (typeof values[keys[i]] === \"number\") // use forward entries only\n this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i];\n}\n\n/**\n * @override\n */\nEnum.prototype._resolveFeatures = function _resolveFeatures(edition) {\n edition = this._edition || edition;\n ReflectionObject.prototype._resolveFeatures.call(this, edition);\n\n Object.keys(this.values).forEach(key => {\n var parentFeaturesCopy = Object.assign({}, this._features);\n this._valuesFeatures[key] = Object.assign(parentFeaturesCopy, this.valuesOptions && this.valuesOptions[key] && this.valuesOptions[key].features);\n });\n\n return this;\n};\n\n/**\n * Enum descriptor.\n * @interface IEnum\n * @property {Object.} values Enum values\n * @property {Object.} [options] Enum options\n */\n\n/**\n * Constructs an enum from an enum descriptor.\n * @param {string} name Enum name\n * @param {IEnum} json Enum descriptor\n * @returns {Enum} Created enum\n * @throws {TypeError} If arguments are invalid\n */\nEnum.fromJSON = function fromJSON(name, json) {\n var enm = new Enum(name, json.values, json.options, json.comment, json.comments);\n enm.reserved = json.reserved;\n if (json.edition)\n enm._edition = json.edition;\n enm._defaultEdition = \"proto3\"; // For backwards-compatibility.\n return enm;\n};\n\n/**\n * Converts this enum to an enum descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IEnum} Enum descriptor\n */\nEnum.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"edition\" , this._editionToJSON(),\n \"options\" , this.options,\n \"valuesOptions\" , this.valuesOptions,\n \"values\" , this.values,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"comment\" , keepComments ? this.comment : undefined,\n \"comments\" , keepComments ? this.comments : undefined\n ]);\n};\n\n/**\n * Adds a value to this enum.\n * @param {string} name Value name\n * @param {number} id Value id\n * @param {string} [comment] Comment, if any\n * @param {Object.|undefined} [options] Options, if any\n * @returns {Enum} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a value with this name or id\n */\nEnum.prototype.add = function add(name, id, comment, options) {\n // utilized by the parser but not by .fromJSON\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n if (!util.isInteger(id))\n throw TypeError(\"id must be an integer\");\n\n if (this.values[name] !== undefined)\n throw Error(\"duplicate name '\" + name + \"' in \" + this);\n\n if (this.isReservedId(id))\n throw Error(\"id \" + id + \" is reserved in \" + this);\n\n if (this.isReservedName(name))\n throw Error(\"name '\" + name + \"' is reserved in \" + this);\n\n if (this.valuesById[id] !== undefined) {\n if (!(this.options && this.options.allow_alias))\n throw Error(\"duplicate id \" + id + \" in \" + this);\n this.values[name] = id;\n } else\n this.valuesById[this.values[name] = id] = name;\n\n if (options) {\n if (this.valuesOptions === undefined)\n this.valuesOptions = {};\n this.valuesOptions[name] = options || null;\n }\n\n this.comments[name] = comment || null;\n return this;\n};\n\n/**\n * Removes a value from this enum\n * @param {string} name Value name\n * @returns {Enum} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `name` is not a name of this enum\n */\nEnum.prototype.remove = function remove(name) {\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n var val = this.values[name];\n if (val == null)\n throw Error(\"name '\" + name + \"' does not exist in \" + this);\n\n delete this.valuesById[val];\n delete this.values[name];\n delete this.comments[name];\n if (this.valuesOptions)\n delete this.valuesOptions[name];\n\n return this;\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nEnum.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nEnum.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n","\"use strict\";\nmodule.exports = Field;\n\n// extends ReflectionObject\nvar ReflectionObject = require(24);\n((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = \"Field\";\n\nvar Enum = require(15),\n types = require(36),\n util = require(37);\n\nvar Type; // cyclic\n\nvar ruleRe = /^required|optional|repeated$/;\n\n/**\n * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class.\n * @name Field\n * @classdesc Reflected message field.\n * @extends FieldBase\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} type Value type\n * @param {string|Object.} [rule=\"optional\"] Field rule\n * @param {string|Object.} [extend] Extended type if different from parent\n * @param {Object.} [options] Declared options\n */\n\n/**\n * Constructs a field from a field descriptor.\n * @param {string} name Field name\n * @param {IField} json Field descriptor\n * @returns {Field} Created field\n * @throws {TypeError} If arguments are invalid\n */\nField.fromJSON = function fromJSON(name, json) {\n var field = new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment);\n if (json.edition)\n field._edition = json.edition;\n field._defaultEdition = \"proto3\"; // For backwards-compatibility.\n return field;\n};\n\n/**\n * Not an actual constructor. Use {@link Field} instead.\n * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions.\n * @exports FieldBase\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} type Value type\n * @param {string|Object.} [rule=\"optional\"] Field rule\n * @param {string|Object.} [extend] Extended type if different from parent\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction Field(name, id, type, rule, extend, options, comment) {\n\n if (util.isObject(rule)) {\n comment = extend;\n options = rule;\n rule = extend = undefined;\n } else if (util.isObject(extend)) {\n comment = options;\n options = extend;\n extend = undefined;\n }\n\n ReflectionObject.call(this, name, options);\n\n if (!util.isInteger(id) || id < 0)\n throw TypeError(\"id must be a non-negative integer\");\n\n if (!util.isString(type))\n throw TypeError(\"type must be a string\");\n\n if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase()))\n throw TypeError(\"rule must be a string rule\");\n\n if (extend !== undefined && !util.isString(extend))\n throw TypeError(\"extend must be a string\");\n\n /**\n * Field rule, if any.\n * @type {string|undefined}\n */\n if (rule === \"proto3_optional\") {\n rule = \"optional\";\n }\n this.rule = rule && rule !== \"optional\" ? rule : undefined; // toJSON\n\n /**\n * Field type.\n * @type {string}\n */\n this.type = type; // toJSON\n\n /**\n * Unique field id.\n * @type {number}\n */\n this.id = id; // toJSON, marker\n\n /**\n * Extended type if different from parent.\n * @type {string|undefined}\n */\n this.extend = extend || undefined; // toJSON\n\n /**\n * Whether this field is repeated.\n * @type {boolean}\n */\n this.repeated = rule === \"repeated\";\n\n /**\n * Whether this field is a map or not.\n * @type {boolean}\n */\n this.map = false;\n\n /**\n * Message this field belongs to.\n * @type {Type|null}\n */\n this.message = null;\n\n /**\n * OneOf this field belongs to, if any,\n * @type {OneOf|null}\n */\n this.partOf = null;\n\n /**\n * The field type's default value.\n * @type {*}\n */\n this.typeDefault = null;\n\n /**\n * The field's default value on prototypes.\n * @type {*}\n */\n this.defaultValue = null;\n\n /**\n * Whether this field's value should be treated as a long.\n * @type {boolean}\n */\n this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false;\n\n /**\n * Whether this field's value is a buffer.\n * @type {boolean}\n */\n this.bytes = type === \"bytes\";\n\n /**\n * Resolved type if not a basic type.\n * @type {Type|Enum|null}\n */\n this.resolvedType = null;\n\n /**\n * Sister-field within the extended type if a declaring extension field.\n * @type {Field|null}\n */\n this.extensionField = null;\n\n /**\n * Sister-field within the declaring namespace if an extended field.\n * @type {Field|null}\n */\n this.declaringField = null;\n\n /**\n * Comment for this field.\n * @type {string|null}\n */\n this.comment = comment;\n}\n\n/**\n * Determines whether this field is required.\n * @name Field#required\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"required\", {\n get: function() {\n return this._features.field_presence === \"LEGACY_REQUIRED\";\n }\n});\n\n/**\n * Determines whether this field is not required.\n * @name Field#optional\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"optional\", {\n get: function() {\n return !this.required;\n }\n});\n\n/**\n * Determines whether this field uses tag-delimited encoding. In proto2 this\n * corresponded to group syntax.\n * @name Field#delimited\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"delimited\", {\n get: function() {\n return this.resolvedType instanceof Type &&\n this._features.message_encoding === \"DELIMITED\";\n }\n});\n\n/**\n * Determines whether this field is packed. Only relevant when repeated.\n * @name Field#packed\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"packed\", {\n get: function() {\n return this._features.repeated_field_encoding === \"PACKED\";\n }\n});\n\n/**\n * Determines whether this field tracks presence.\n * @name Field#hasPresence\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"hasPresence\", {\n get: function() {\n if (this.repeated || this.map) {\n return false;\n }\n return this.partOf || // oneofs\n this.declaringField || this.extensionField || // extensions\n this._features.field_presence !== \"IMPLICIT\";\n }\n});\n\n/**\n * @override\n */\nField.prototype.setOption = function setOption(name, value, ifNotSet) {\n return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet);\n};\n\n/**\n * Field descriptor.\n * @interface IField\n * @property {string} [rule=\"optional\"] Field rule\n * @property {string} type Field type\n * @property {number} id Field id\n * @property {Object.} [options] Field options\n */\n\n/**\n * Extension field descriptor.\n * @interface IExtensionField\n * @extends IField\n * @property {string} extend Extended type\n */\n\n/**\n * Converts this field to a field descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IField} Field descriptor\n */\nField.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"edition\" , this._editionToJSON(),\n \"rule\" , this.rule !== \"optional\" && this.rule || undefined,\n \"type\" , this.type,\n \"id\" , this.id,\n \"extend\" , this.extend,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Resolves this field's type references.\n * @returns {Field} `this`\n * @throws {Error} If any reference cannot be resolved\n */\nField.prototype.resolve = function resolve() {\n\n if (this.resolved)\n return this;\n\n if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it\n this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);\n if (this.resolvedType instanceof Type)\n this.typeDefault = null;\n else // instanceof Enum\n this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined\n } else if (this.options && this.options.proto3_optional) {\n // proto3 scalar value marked optional; should default to null\n this.typeDefault = null;\n }\n\n // use explicitly set default value if present\n if (this.options && this.options[\"default\"] != null) {\n this.typeDefault = this.options[\"default\"];\n if (this.resolvedType instanceof Enum && typeof this.typeDefault === \"string\")\n this.typeDefault = this.resolvedType.values[this.typeDefault];\n }\n\n // remove unnecessary options\n if (this.options) {\n if (this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum))\n delete this.options.packed;\n if (!Object.keys(this.options).length)\n this.options = undefined;\n }\n\n // convert to internal data type if necesssary\n if (this.long) {\n this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === \"u\");\n\n /* istanbul ignore else */\n if (Object.freeze)\n Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it)\n\n } else if (this.bytes && typeof this.typeDefault === \"string\") {\n var buf;\n if (util.base64.test(this.typeDefault))\n util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0);\n else\n util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0);\n this.typeDefault = buf;\n }\n\n // take special care of maps and repeated fields\n if (this.map)\n this.defaultValue = util.emptyObject;\n else if (this.repeated)\n this.defaultValue = util.emptyArray;\n else\n this.defaultValue = this.typeDefault;\n\n // ensure proper value on prototype\n if (this.parent instanceof Type)\n this.parent.ctor.prototype[this.name] = this.defaultValue;\n\n return ReflectionObject.prototype.resolve.call(this);\n};\n\n/**\n * Infers field features from legacy syntax that may have been specified differently.\n * in older editions.\n * @param {string|undefined} edition The edition this proto is on, or undefined if pre-editions\n * @returns {object} The feature values to override\n */\nField.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(edition) {\n if (edition !== \"proto2\" && edition !== \"proto3\") {\n return {};\n }\n\n var features = {};\n\n if (this.rule === \"required\") {\n features.field_presence = \"LEGACY_REQUIRED\";\n }\n if (this.parent && types.defaults[this.type] === undefined) {\n // We can't use resolvedType because types may not have been resolved yet. However,\n // legacy groups are always in the same scope as the field so we don't have to do a\n // full scan of the tree.\n var type = this.parent.get(this.type.split(\".\").pop());\n if (type && type instanceof Type && type.group) {\n features.message_encoding = \"DELIMITED\";\n }\n }\n if (this.getOption(\"packed\") === true) {\n features.repeated_field_encoding = \"PACKED\";\n } else if (this.getOption(\"packed\") === false) {\n features.repeated_field_encoding = \"EXPANDED\";\n }\n return features;\n};\n\n/**\n * @override\n */\nField.prototype._resolveFeatures = function _resolveFeatures(edition) {\n return ReflectionObject.prototype._resolveFeatures.call(this, this._edition || edition);\n};\n\n/**\n * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript).\n * @typedef FieldDecorator\n * @type {function}\n * @param {Object} prototype Target prototype\n * @param {string} fieldName Field name\n * @returns {undefined}\n */\n\n/**\n * Field decorator (TypeScript).\n * @name Field.d\n * @function\n * @param {number} fieldId Field id\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"string\"|\"bool\"|\"bytes\"|Object} fieldType Field type\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\n * @param {T} [defaultValue] Default value\n * @returns {FieldDecorator} Decorator function\n * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[]\n */\nField.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) {\n\n // submessage: decorate the submessage and use its name as the type\n if (typeof fieldType === \"function\")\n fieldType = util.decorateType(fieldType).name;\n\n // enum reference: create a reflected copy of the enum and keep reuseing it\n else if (fieldType && typeof fieldType === \"object\")\n fieldType = util.decorateEnum(fieldType).name;\n\n return function fieldDecorator(prototype, fieldName) {\n util.decorateType(prototype.constructor)\n .add(new Field(fieldName, fieldId, fieldType, fieldRule, { \"default\": defaultValue }));\n };\n};\n\n/**\n * Field decorator (TypeScript).\n * @name Field.d\n * @function\n * @param {number} fieldId Field id\n * @param {Constructor|string} fieldType Field type\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\n * @returns {FieldDecorator} Decorator function\n * @template T extends Message\n * @variation 2\n */\n// like Field.d but without a default value\n\n// Sets up cyclic dependencies (called in index-light)\nField._configure = function configure(Type_) {\n Type = Type_;\n};\n","\"use strict\";\nvar protobuf = module.exports = require(18);\n\nprotobuf.build = \"light\";\n\n/**\n * A node-style callback as used by {@link load} and {@link Root#load}.\n * @typedef LoadCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Root} [root] Root, if there hasn't been an error\n * @returns {undefined}\n */\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} root Root namespace, defaults to create a new one if omitted.\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @see {@link Root#load}\n */\nfunction load(filename, root, callback) {\n if (typeof root === \"function\") {\n callback = root;\n root = new protobuf.Root();\n } else if (!root)\n root = new protobuf.Root();\n return root.load(filename, callback);\n}\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\n * @name load\n * @function\n * @param {string|string[]} filename One or multiple files to load\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @see {@link Root#load}\n * @variation 2\n */\n// function load(filename:string, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise.\n * @name load\n * @function\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\n * @returns {Promise} Promise\n * @see {@link Root#load}\n * @variation 3\n */\n// function load(filename:string, [root:Root]):Promise\n\nprotobuf.load = load;\n\n/**\n * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only).\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\n * @returns {Root} Root namespace\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\n * @see {@link Root#loadSync}\n */\nfunction loadSync(filename, root) {\n if (!root)\n root = new protobuf.Root();\n return root.loadSync(filename);\n}\n\nprotobuf.loadSync = loadSync;\n\n// Serialization\nprotobuf.encoder = require(14);\nprotobuf.decoder = require(13);\nprotobuf.verifier = require(40);\nprotobuf.converter = require(12);\n\n// Reflection\nprotobuf.ReflectionObject = require(24);\nprotobuf.Namespace = require(23);\nprotobuf.Root = require(29);\nprotobuf.Enum = require(15);\nprotobuf.Type = require(35);\nprotobuf.Field = require(16);\nprotobuf.OneOf = require(25);\nprotobuf.MapField = require(20);\nprotobuf.Service = require(33);\nprotobuf.Method = require(22);\n\n// Runtime\nprotobuf.Message = require(21);\nprotobuf.wrappers = require(41);\n\n// Utility\nprotobuf.types = require(36);\nprotobuf.util = require(37);\n\n// Set up possibly cyclic reflection dependencies\nprotobuf.ReflectionObject._configure(protobuf.Root);\nprotobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum);\nprotobuf.Root._configure(protobuf.Type);\nprotobuf.Field._configure(protobuf.Type);\n","\"use strict\";\nvar protobuf = exports;\n\n/**\n * Build type, one of `\"full\"`, `\"light\"` or `\"minimal\"`.\n * @name build\n * @type {string}\n * @const\n */\nprotobuf.build = \"minimal\";\n\n// Serialization\nprotobuf.Writer = require(42);\nprotobuf.BufferWriter = require(43);\nprotobuf.Reader = require(27);\nprotobuf.BufferReader = require(28);\n\n// Utility\nprotobuf.util = require(39);\nprotobuf.rpc = require(31);\nprotobuf.roots = require(30);\nprotobuf.configure = configure;\n\n/* istanbul ignore next */\n/**\n * Reconfigures the library according to the environment.\n * @returns {undefined}\n */\nfunction configure() {\n protobuf.util._configure();\n protobuf.Writer._configure(protobuf.BufferWriter);\n protobuf.Reader._configure(protobuf.BufferReader);\n}\n\n// Set up buffer utility according to the environment\nconfigure();\n","\"use strict\";\nvar protobuf = module.exports = require(17);\n\nprotobuf.build = \"full\";\n\n// Parser\nprotobuf.tokenize = require(34);\nprotobuf.parse = require(26);\nprotobuf.common = require(11);\n\n// Configure parser\nprotobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common);\n","\"use strict\";\nmodule.exports = MapField;\n\n// extends Field\nvar Field = require(16);\n((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = \"MapField\";\n\nvar types = require(36),\n util = require(37);\n\n/**\n * Constructs a new map field instance.\n * @classdesc Reflected map field.\n * @extends FieldBase\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} keyType Key type\n * @param {string} type Value type\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction MapField(name, id, keyType, type, options, comment) {\n Field.call(this, name, id, type, undefined, undefined, options, comment);\n\n /* istanbul ignore if */\n if (!util.isString(keyType))\n throw TypeError(\"keyType must be a string\");\n\n /**\n * Key type.\n * @type {string}\n */\n this.keyType = keyType; // toJSON, marker\n\n /**\n * Resolved key type if not a basic type.\n * @type {ReflectionObject|null}\n */\n this.resolvedKeyType = null;\n\n // Overrides Field#map\n this.map = true;\n}\n\n/**\n * Map field descriptor.\n * @interface IMapField\n * @extends {IField}\n * @property {string} keyType Key type\n */\n\n/**\n * Extension map field descriptor.\n * @interface IExtensionMapField\n * @extends IMapField\n * @property {string} extend Extended type\n */\n\n/**\n * Constructs a map field from a map field descriptor.\n * @param {string} name Field name\n * @param {IMapField} json Map field descriptor\n * @returns {MapField} Created map field\n * @throws {TypeError} If arguments are invalid\n */\nMapField.fromJSON = function fromJSON(name, json) {\n return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment);\n};\n\n/**\n * Converts this map field to a map field descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IMapField} Map field descriptor\n */\nMapField.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"keyType\" , this.keyType,\n \"type\" , this.type,\n \"id\" , this.id,\n \"extend\" , this.extend,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nMapField.prototype.resolve = function resolve() {\n if (this.resolved)\n return this;\n\n // Besides a value type, map fields have a key type that may be \"any scalar type except for floating point types and bytes\"\n if (types.mapKey[this.keyType] === undefined)\n throw Error(\"invalid key type: \" + this.keyType);\n\n return Field.prototype.resolve.call(this);\n};\n\n/**\n * Map field decorator (TypeScript).\n * @name MapField.d\n * @function\n * @param {number} fieldId Field id\n * @param {\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"} fieldKeyType Field key type\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"|\"bytes\"|Object|Constructor<{}>} fieldValueType Field value type\n * @returns {FieldDecorator} Decorator function\n * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> }\n */\nMapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) {\n\n // submessage value: decorate the submessage and use its name as the type\n if (typeof fieldValueType === \"function\")\n fieldValueType = util.decorateType(fieldValueType).name;\n\n // enum reference value: create a reflected copy of the enum and keep reuseing it\n else if (fieldValueType && typeof fieldValueType === \"object\")\n fieldValueType = util.decorateEnum(fieldValueType).name;\n\n return function mapFieldDecorator(prototype, fieldName) {\n util.decorateType(prototype.constructor)\n .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType));\n };\n};\n","\"use strict\";\nmodule.exports = Message;\n\nvar util = require(39);\n\n/**\n * Constructs a new message instance.\n * @classdesc Abstract runtime message.\n * @constructor\n * @param {Properties} [properties] Properties to set\n * @template T extends object = object\n */\nfunction Message(properties) {\n // not used internally\n if (properties)\n for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)\n this[keys[i]] = properties[keys[i]];\n}\n\n/**\n * Reference to the reflected type.\n * @name Message.$type\n * @type {Type}\n * @readonly\n */\n\n/**\n * Reference to the reflected type.\n * @name Message#$type\n * @type {Type}\n * @readonly\n */\n\n/*eslint-disable valid-jsdoc*/\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message} Message instance\n * @template T extends Message\n * @this Constructor\n */\nMessage.create = function create(properties) {\n return this.$type.create(properties);\n};\n\n/**\n * Encodes a message of this type.\n * @param {T|Object.} message Message to encode\n * @param {Writer} [writer] Writer to use\n * @returns {Writer} Writer\n * @template T extends Message\n * @this Constructor\n */\nMessage.encode = function encode(message, writer) {\n return this.$type.encode(message, writer);\n};\n\n/**\n * Encodes a message of this type preceeded by its length as a varint.\n * @param {T|Object.} message Message to encode\n * @param {Writer} [writer] Writer to use\n * @returns {Writer} Writer\n * @template T extends Message\n * @this Constructor\n */\nMessage.encodeDelimited = function encodeDelimited(message, writer) {\n return this.$type.encodeDelimited(message, writer);\n};\n\n/**\n * Decodes a message of this type.\n * @name Message.decode\n * @function\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\n * @returns {T} Decoded message\n * @template T extends Message\n * @this Constructor\n */\nMessage.decode = function decode(reader) {\n return this.$type.decode(reader);\n};\n\n/**\n * Decodes a message of this type preceeded by its length as a varint.\n * @name Message.decodeDelimited\n * @function\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\n * @returns {T} Decoded message\n * @template T extends Message\n * @this Constructor\n */\nMessage.decodeDelimited = function decodeDelimited(reader) {\n return this.$type.decodeDelimited(reader);\n};\n\n/**\n * Verifies a message of this type.\n * @name Message.verify\n * @function\n * @param {Object.} message Plain object to verify\n * @returns {string|null} `null` if valid, otherwise the reason why it is not\n */\nMessage.verify = function verify(message) {\n return this.$type.verify(message);\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object\n * @returns {T} Message instance\n * @template T extends Message\n * @this Constructor\n */\nMessage.fromObject = function fromObject(object) {\n return this.$type.fromObject(object);\n};\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {T} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n * @template T extends Message\n * @this Constructor\n */\nMessage.toObject = function toObject(message, options) {\n return this.$type.toObject(message, options);\n};\n\n/**\n * Converts this message to JSON.\n * @returns {Object.} JSON object\n */\nMessage.prototype.toJSON = function toJSON() {\n return this.$type.toObject(this, util.toJSONOptions);\n};\n\n/*eslint-enable valid-jsdoc*/","\"use strict\";\nmodule.exports = Method;\n\n// extends ReflectionObject\nvar ReflectionObject = require(24);\n((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = \"Method\";\n\nvar util = require(37);\n\n/**\n * Constructs a new service method instance.\n * @classdesc Reflected service method.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Method name\n * @param {string|undefined} type Method type, usually `\"rpc\"`\n * @param {string} requestType Request message type\n * @param {string} responseType Response message type\n * @param {boolean|Object.} [requestStream] Whether the request is streamed\n * @param {boolean|Object.} [responseStream] Whether the response is streamed\n * @param {Object.} [options] Declared options\n * @param {string} [comment] The comment for this method\n * @param {Object.} [parsedOptions] Declared options, properly parsed into an object\n */\nfunction Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) {\n\n /* istanbul ignore next */\n if (util.isObject(requestStream)) {\n options = requestStream;\n requestStream = responseStream = undefined;\n } else if (util.isObject(responseStream)) {\n options = responseStream;\n responseStream = undefined;\n }\n\n /* istanbul ignore if */\n if (!(type === undefined || util.isString(type)))\n throw TypeError(\"type must be a string\");\n\n /* istanbul ignore if */\n if (!util.isString(requestType))\n throw TypeError(\"requestType must be a string\");\n\n /* istanbul ignore if */\n if (!util.isString(responseType))\n throw TypeError(\"responseType must be a string\");\n\n ReflectionObject.call(this, name, options);\n\n /**\n * Method type.\n * @type {string}\n */\n this.type = type || \"rpc\"; // toJSON\n\n /**\n * Request type.\n * @type {string}\n */\n this.requestType = requestType; // toJSON, marker\n\n /**\n * Whether requests are streamed or not.\n * @type {boolean|undefined}\n */\n this.requestStream = requestStream ? true : undefined; // toJSON\n\n /**\n * Response type.\n * @type {string}\n */\n this.responseType = responseType; // toJSON\n\n /**\n * Whether responses are streamed or not.\n * @type {boolean|undefined}\n */\n this.responseStream = responseStream ? true : undefined; // toJSON\n\n /**\n * Resolved request type.\n * @type {Type|null}\n */\n this.resolvedRequestType = null;\n\n /**\n * Resolved response type.\n * @type {Type|null}\n */\n this.resolvedResponseType = null;\n\n /**\n * Comment for this method\n * @type {string|null}\n */\n this.comment = comment;\n\n /**\n * Options properly parsed into an object\n */\n this.parsedOptions = parsedOptions;\n}\n\n/**\n * Method descriptor.\n * @interface IMethod\n * @property {string} [type=\"rpc\"] Method type\n * @property {string} requestType Request type\n * @property {string} responseType Response type\n * @property {boolean} [requestStream=false] Whether requests are streamed\n * @property {boolean} [responseStream=false] Whether responses are streamed\n * @property {Object.} [options] Method options\n * @property {string} comment Method comments\n * @property {Object.} [parsedOptions] Method options properly parsed into an object\n */\n\n/**\n * Constructs a method from a method descriptor.\n * @param {string} name Method name\n * @param {IMethod} json Method descriptor\n * @returns {Method} Created method\n * @throws {TypeError} If arguments are invalid\n */\nMethod.fromJSON = function fromJSON(name, json) {\n return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions);\n};\n\n/**\n * Converts this method to a method descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IMethod} Method descriptor\n */\nMethod.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"type\" , this.type !== \"rpc\" && /* istanbul ignore next */ this.type || undefined,\n \"requestType\" , this.requestType,\n \"requestStream\" , this.requestStream,\n \"responseType\" , this.responseType,\n \"responseStream\" , this.responseStream,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined,\n \"parsedOptions\" , this.parsedOptions,\n ]);\n};\n\n/**\n * @override\n */\nMethod.prototype.resolve = function resolve() {\n\n /* istanbul ignore if */\n if (this.resolved)\n return this;\n\n this.resolvedRequestType = this.parent.lookupType(this.requestType);\n this.resolvedResponseType = this.parent.lookupType(this.responseType);\n\n return ReflectionObject.prototype.resolve.call(this);\n};\n","\"use strict\";\nmodule.exports = Namespace;\n\n// extends ReflectionObject\nvar ReflectionObject = require(24);\n((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = \"Namespace\";\n\nvar Field = require(16),\n util = require(37),\n OneOf = require(25);\n\nvar Type, // cyclic\n Service,\n Enum;\n\n/**\n * Constructs a new namespace instance.\n * @name Namespace\n * @classdesc Reflected namespace.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Namespace name\n * @param {Object.} [options] Declared options\n */\n\n/**\n * Constructs a namespace from JSON.\n * @memberof Namespace\n * @function\n * @param {string} name Namespace name\n * @param {Object.} json JSON object\n * @returns {Namespace} Created namespace\n * @throws {TypeError} If arguments are invalid\n */\nNamespace.fromJSON = function fromJSON(name, json) {\n return new Namespace(name, json.options).addJSON(json.nested);\n};\n\n/**\n * Converts an array of reflection objects to JSON.\n * @memberof Namespace\n * @param {ReflectionObject[]} array Object array\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {Object.|undefined} JSON object or `undefined` when array is empty\n */\nfunction arrayToJSON(array, toJSONOptions) {\n if (!(array && array.length))\n return undefined;\n var obj = {};\n for (var i = 0; i < array.length; ++i)\n obj[array[i].name] = array[i].toJSON(toJSONOptions);\n return obj;\n}\n\nNamespace.arrayToJSON = arrayToJSON;\n\n/**\n * Tests if the specified id is reserved.\n * @param {Array.|undefined} reserved Array of reserved ranges and names\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nNamespace.isReservedId = function isReservedId(reserved, id) {\n if (reserved)\n for (var i = 0; i < reserved.length; ++i)\n if (typeof reserved[i] !== \"string\" && reserved[i][0] <= id && reserved[i][1] > id)\n return true;\n return false;\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {Array.|undefined} reserved Array of reserved ranges and names\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nNamespace.isReservedName = function isReservedName(reserved, name) {\n if (reserved)\n for (var i = 0; i < reserved.length; ++i)\n if (reserved[i] === name)\n return true;\n return false;\n};\n\n/**\n * Not an actual constructor. Use {@link Namespace} instead.\n * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions.\n * @exports NamespaceBase\n * @extends ReflectionObject\n * @abstract\n * @constructor\n * @param {string} name Namespace name\n * @param {Object.} [options] Declared options\n * @see {@link Namespace}\n */\nfunction Namespace(name, options) {\n ReflectionObject.call(this, name, options);\n\n /**\n * Nested objects by name.\n * @type {Object.|undefined}\n */\n this.nested = undefined; // toJSON\n\n /**\n * Cached nested objects as an array.\n * @type {ReflectionObject[]|null}\n * @private\n */\n this._nestedArray = null;\n\n /**\n * Cache lookup calls for any objects contains anywhere under this namespace.\n * This drastically speeds up resolve for large cross-linked protos where the same\n * types are looked up repeatedly.\n * @type {Object.}\n * @private\n */\n this._lookupCache = {};\n\n /**\n * Whether or not objects contained in this namespace need feature resolution.\n * @type {boolean}\n * @protected\n */\n this._needsRecursiveFeatureResolution = true;\n\n /**\n * Whether or not objects contained in this namespace need a resolve.\n * @type {boolean}\n * @protected\n */\n this._needsRecursiveResolve = true;\n}\n\nfunction clearCache(namespace) {\n namespace._nestedArray = null;\n namespace._lookupCache = {};\n\n // Also clear parent caches, since they include nested lookups.\n var parent = namespace;\n while(parent = parent.parent) {\n parent._lookupCache = {};\n }\n return namespace;\n}\n\n/**\n * Nested objects of this namespace as an array for iteration.\n * @name NamespaceBase#nestedArray\n * @type {ReflectionObject[]}\n * @readonly\n */\nObject.defineProperty(Namespace.prototype, \"nestedArray\", {\n get: function() {\n return this._nestedArray || (this._nestedArray = util.toArray(this.nested));\n }\n});\n\n/**\n * Namespace descriptor.\n * @interface INamespace\n * @property {Object.} [options] Namespace options\n * @property {Object.} [nested] Nested object descriptors\n */\n\n/**\n * Any extension field descriptor.\n * @typedef AnyExtensionField\n * @type {IExtensionField|IExtensionMapField}\n */\n\n/**\n * Any nested object descriptor.\n * @typedef AnyNestedObject\n * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf}\n */\n\n/**\n * Converts this namespace to a namespace descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {INamespace} Namespace descriptor\n */\nNamespace.prototype.toJSON = function toJSON(toJSONOptions) {\n return util.toObject([\n \"options\" , this.options,\n \"nested\" , arrayToJSON(this.nestedArray, toJSONOptions)\n ]);\n};\n\n/**\n * Adds nested objects to this namespace from nested object descriptors.\n * @param {Object.} nestedJson Any nested object descriptors\n * @returns {Namespace} `this`\n */\nNamespace.prototype.addJSON = function addJSON(nestedJson) {\n var ns = this;\n /* istanbul ignore else */\n if (nestedJson) {\n for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) {\n nested = nestedJson[names[i]];\n ns.add( // most to least likely\n ( nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : nested.id !== undefined\n ? Field.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n }\n return this;\n};\n\n/**\n * Gets the nested object of the specified name.\n * @param {string} name Nested object name\n * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist\n */\nNamespace.prototype.get = function get(name) {\n return this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Gets the values of the nested {@link Enum|enum} of the specified name.\n * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`.\n * @param {string} name Nested enum name\n * @returns {Object.} Enum values\n * @throws {Error} If there is no such enum\n */\nNamespace.prototype.getEnum = function getEnum(name) {\n if (this.nested && this.nested[name] instanceof Enum)\n return this.nested[name].values;\n throw Error(\"no such enum: \" + name);\n};\n\n/**\n * Adds a nested object to this namespace.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Namespace} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name\n */\nNamespace.prototype.add = function add(object) {\n\n if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace))\n throw TypeError(\"object must be a valid nested object\");\n\n if (!this.nested)\n this.nested = {};\n else {\n var prev = this.get(object.name);\n if (prev) {\n if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) {\n // replace plain namespace but keep existing nested elements and options\n var nested = prev.nestedArray;\n for (var i = 0; i < nested.length; ++i)\n object.add(nested[i]);\n this.remove(prev);\n if (!this.nested)\n this.nested = {};\n object.setOptions(prev.options, true);\n\n } else\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n }\n }\n this.nested[object.name] = object;\n\n if (!(this instanceof Type || this instanceof Service || this instanceof Enum || this instanceof Field)) {\n // This is a package or a root namespace.\n if (!object._edition) {\n // Make sure that some edition is set if it hasn't already been specified.\n object._edition = object._defaultEdition;\n }\n }\n\n this._needsRecursiveFeatureResolution = true;\n this._needsRecursiveResolve = true;\n\n // Also clear parent caches, since they need to recurse down.\n var parent = this;\n while(parent = parent.parent) {\n parent._needsRecursiveFeatureResolution = true;\n parent._needsRecursiveResolve = true;\n }\n\n object.onAdd(this);\n return clearCache(this);\n};\n\n/**\n * Removes a nested object from this namespace.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Namespace} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this namespace\n */\nNamespace.prototype.remove = function remove(object) {\n\n if (!(object instanceof ReflectionObject))\n throw TypeError(\"object must be a ReflectionObject\");\n if (object.parent !== this)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.nested[object.name];\n if (!Object.keys(this.nested).length)\n this.nested = undefined;\n\n object.onRemove(this);\n return clearCache(this);\n};\n\n/**\n * Defines additial namespaces within this one if not yet existing.\n * @param {string|string[]} path Path to create\n * @param {*} [json] Nested types to create from JSON\n * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty\n */\nNamespace.prototype.define = function define(path, json) {\n\n if (util.isString(path))\n path = path.split(\".\");\n else if (!Array.isArray(path))\n throw TypeError(\"illegal path\");\n if (path && path.length && path[0] === \"\")\n throw Error(\"path must be relative\");\n\n var ptr = this;\n while (path.length > 0) {\n var part = path.shift();\n if (ptr.nested && ptr.nested[part]) {\n ptr = ptr.nested[part];\n if (!(ptr instanceof Namespace))\n throw Error(\"path conflicts with non-namespace objects\");\n } else\n ptr.add(ptr = new Namespace(part));\n }\n if (json)\n ptr.addJSON(json);\n return ptr;\n};\n\n/**\n * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost.\n * @returns {Namespace} `this`\n */\nNamespace.prototype.resolveAll = function resolveAll() {\n if (!this._needsRecursiveResolve) return this;\n\n this._resolveFeaturesRecursive(this._edition);\n\n var nested = this.nestedArray, i = 0;\n this.resolve();\n while (i < nested.length)\n if (nested[i] instanceof Namespace)\n nested[i++].resolveAll();\n else\n nested[i++].resolve();\n this._needsRecursiveResolve = false;\n return this;\n};\n\n/**\n * @override\n */\nNamespace.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) {\n if (!this._needsRecursiveFeatureResolution) return this;\n this._needsRecursiveFeatureResolution = false;\n\n edition = this._edition || edition;\n\n ReflectionObject.prototype._resolveFeaturesRecursive.call(this, edition);\n this.nestedArray.forEach(nested => {\n nested._resolveFeaturesRecursive(edition);\n });\n return this;\n};\n\n/**\n * Recursively looks up the reflection object matching the specified path in the scope of this namespace.\n * @param {string|string[]} path Path to look up\n * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc.\n * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n */\nNamespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) {\n /* istanbul ignore next */\n if (typeof filterTypes === \"boolean\") {\n parentAlreadyChecked = filterTypes;\n filterTypes = undefined;\n } else if (filterTypes && !Array.isArray(filterTypes))\n filterTypes = [ filterTypes ];\n\n if (util.isString(path) && path.length) {\n if (path === \".\")\n return this.root;\n path = path.split(\".\");\n } else if (!path.length)\n return this;\n\n var flatPath = path.join(\".\");\n\n // Start at root if path is absolute\n if (path[0] === \"\")\n return this.root.lookup(path.slice(1), filterTypes);\n\n // Early bailout for objects with matching absolute paths\n var found = this.root._fullyQualifiedObjects && this.root._fullyQualifiedObjects[\".\" + flatPath];\n if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {\n return found;\n }\n\n // Do a regular lookup at this namespace and below\n found = this._lookupImpl(path, flatPath);\n if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {\n return found;\n }\n\n if (parentAlreadyChecked)\n return null;\n\n // If there hasn't been a match, walk up the tree and look more broadly\n var current = this;\n while (current.parent) {\n found = current.parent._lookupImpl(path, flatPath);\n if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {\n return found;\n }\n current = current.parent;\n }\n return null;\n};\n\n/**\n * Internal helper for lookup that handles searching just at this namespace and below along with caching.\n * @param {string[]} path Path to look up\n * @param {string} flatPath Flattened version of the path to use as a cache key\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n * @private\n */\nNamespace.prototype._lookupImpl = function lookup(path, flatPath) {\n if(Object.prototype.hasOwnProperty.call(this._lookupCache, flatPath)) {\n return this._lookupCache[flatPath];\n }\n\n // Test if the first part matches any nested object, and if so, traverse if path contains more\n var found = this.get(path[0]);\n var exact = null;\n if (found) {\n if (path.length === 1) {\n exact = found;\n } else if (found instanceof Namespace) {\n path = path.slice(1);\n exact = found._lookupImpl(path, path.join(\".\"));\n }\n\n // Otherwise try each nested namespace\n } else {\n for (var i = 0; i < this.nestedArray.length; ++i)\n if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i]._lookupImpl(path, flatPath)))\n exact = found;\n }\n\n // Set this even when null, so that when we walk up the tree we can quickly bail on repeated checks back down.\n this._lookupCache[flatPath] = exact;\n return exact;\n};\n\n/**\n * Looks up the reflection object at the specified path, relative to this namespace.\n * @name NamespaceBase#lookup\n * @function\n * @param {string|string[]} path Path to look up\n * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n * @variation 2\n */\n// lookup(path: string, [parentAlreadyChecked: boolean])\n\n/**\n * Looks up the {@link Type|type} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Type} Looked up type\n * @throws {Error} If `path` does not point to a type\n */\nNamespace.prototype.lookupType = function lookupType(path) {\n var found = this.lookup(path, [ Type ]);\n if (!found)\n throw Error(\"no such type: \" + path);\n return found;\n};\n\n/**\n * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Enum} Looked up enum\n * @throws {Error} If `path` does not point to an enum\n */\nNamespace.prototype.lookupEnum = function lookupEnum(path) {\n var found = this.lookup(path, [ Enum ]);\n if (!found)\n throw Error(\"no such Enum '\" + path + \"' in \" + this);\n return found;\n};\n\n/**\n * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Type} Looked up type or enum\n * @throws {Error} If `path` does not point to a type or enum\n */\nNamespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) {\n var found = this.lookup(path, [ Type, Enum ]);\n if (!found)\n throw Error(\"no such Type or Enum '\" + path + \"' in \" + this);\n return found;\n};\n\n/**\n * Looks up the {@link Service|service} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Service} Looked up service\n * @throws {Error} If `path` does not point to a service\n */\nNamespace.prototype.lookupService = function lookupService(path) {\n var found = this.lookup(path, [ Service ]);\n if (!found)\n throw Error(\"no such Service '\" + path + \"' in \" + this);\n return found;\n};\n\n// Sets up cyclic dependencies (called in index-light)\nNamespace._configure = function(Type_, Service_, Enum_) {\n Type = Type_;\n Service = Service_;\n Enum = Enum_;\n};\n","\"use strict\";\nmodule.exports = ReflectionObject;\n\nReflectionObject.className = \"ReflectionObject\";\n\nconst OneOf = require(25);\nvar util = require(37);\n\nvar Root; // cyclic\n\n/* eslint-disable no-warning-comments */\n// TODO: Replace with embedded proto.\nvar editions2023Defaults = {enum_type: \"OPEN\", field_presence: \"EXPLICIT\", json_format: \"ALLOW\", message_encoding: \"LENGTH_PREFIXED\", repeated_field_encoding: \"PACKED\", utf8_validation: \"VERIFY\"};\nvar proto2Defaults = {enum_type: \"CLOSED\", field_presence: \"EXPLICIT\", json_format: \"LEGACY_BEST_EFFORT\", message_encoding: \"LENGTH_PREFIXED\", repeated_field_encoding: \"EXPANDED\", utf8_validation: \"NONE\"};\nvar proto3Defaults = {enum_type: \"OPEN\", field_presence: \"IMPLICIT\", json_format: \"ALLOW\", message_encoding: \"LENGTH_PREFIXED\", repeated_field_encoding: \"PACKED\", utf8_validation: \"VERIFY\"};\n\n/**\n * Constructs a new reflection object instance.\n * @classdesc Base class of all reflection objects.\n * @constructor\n * @param {string} name Object name\n * @param {Object.} [options] Declared options\n * @abstract\n */\nfunction ReflectionObject(name, options) {\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n if (options && !util.isObject(options))\n throw TypeError(\"options must be an object\");\n\n /**\n * Options.\n * @type {Object.|undefined}\n */\n this.options = options; // toJSON\n\n /**\n * Parsed Options.\n * @type {Array.>|undefined}\n */\n this.parsedOptions = null;\n\n /**\n * Unique name within its namespace.\n * @type {string}\n */\n this.name = name;\n\n /**\n * The edition specified for this object. Only relevant for top-level objects.\n * @type {string}\n * @private\n */\n this._edition = null;\n\n /**\n * The default edition to use for this object if none is specified. For legacy reasons,\n * this is proto2 except in the JSON parsing case where it was proto3.\n * @type {string}\n * @private\n */\n this._defaultEdition = \"proto2\";\n\n /**\n * Resolved Features.\n * @type {object}\n * @private\n */\n this._features = {};\n\n /**\n * Whether or not features have been resolved.\n * @type {boolean}\n * @private\n */\n this._featuresResolved = false;\n\n /**\n * Parent namespace.\n * @type {Namespace|null}\n */\n this.parent = null;\n\n /**\n * Whether already resolved or not.\n * @type {boolean}\n */\n this.resolved = false;\n\n /**\n * Comment text, if any.\n * @type {string|null}\n */\n this.comment = null;\n\n /**\n * Defining file name.\n * @type {string|null}\n */\n this.filename = null;\n}\n\nObject.defineProperties(ReflectionObject.prototype, {\n\n /**\n * Reference to the root namespace.\n * @name ReflectionObject#root\n * @type {Root}\n * @readonly\n */\n root: {\n get: function() {\n var ptr = this;\n while (ptr.parent !== null)\n ptr = ptr.parent;\n return ptr;\n }\n },\n\n /**\n * Full name including leading dot.\n * @name ReflectionObject#fullName\n * @type {string}\n * @readonly\n */\n fullName: {\n get: function() {\n var path = [ this.name ],\n ptr = this.parent;\n while (ptr) {\n path.unshift(ptr.name);\n ptr = ptr.parent;\n }\n return path.join(\".\");\n }\n }\n});\n\n/**\n * Converts this reflection object to its descriptor representation.\n * @returns {Object.} Descriptor\n * @abstract\n */\nReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() {\n throw Error(); // not implemented, shouldn't happen\n};\n\n/**\n * Called when this object is added to a parent.\n * @param {ReflectionObject} parent Parent added to\n * @returns {undefined}\n */\nReflectionObject.prototype.onAdd = function onAdd(parent) {\n if (this.parent && this.parent !== parent)\n this.parent.remove(this);\n this.parent = parent;\n this.resolved = false;\n var root = parent.root;\n if (root instanceof Root)\n root._handleAdd(this);\n};\n\n/**\n * Called when this object is removed from a parent.\n * @param {ReflectionObject} parent Parent removed from\n * @returns {undefined}\n */\nReflectionObject.prototype.onRemove = function onRemove(parent) {\n var root = parent.root;\n if (root instanceof Root)\n root._handleRemove(this);\n this.parent = null;\n this.resolved = false;\n};\n\n/**\n * Resolves this objects type references.\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.resolve = function resolve() {\n if (this.resolved)\n return this;\n if (this.root instanceof Root)\n this.resolved = true; // only if part of a root\n return this;\n};\n\n/**\n * Resolves this objects editions features.\n * @param {string} edition The edition we're currently resolving for.\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) {\n return this._resolveFeatures(this._edition || edition);\n};\n\n/**\n * Resolves child features from parent features\n * @param {string} edition The edition we're currently resolving for.\n * @returns {undefined}\n */\nReflectionObject.prototype._resolveFeatures = function _resolveFeatures(edition) {\n if (this._featuresResolved) {\n return;\n }\n\n var defaults = {};\n\n /* istanbul ignore if */\n if (!edition) {\n throw new Error(\"Unknown edition for \" + this.fullName);\n }\n\n var protoFeatures = Object.assign(this.options ? Object.assign({}, this.options.features) : {},\n this._inferLegacyProtoFeatures(edition));\n\n if (this._edition) {\n // For a namespace marked with a specific edition, reset defaults.\n /* istanbul ignore else */\n if (edition === \"proto2\") {\n defaults = Object.assign({}, proto2Defaults);\n } else if (edition === \"proto3\") {\n defaults = Object.assign({}, proto3Defaults);\n } else if (edition === \"2023\") {\n defaults = Object.assign({}, editions2023Defaults);\n } else {\n throw new Error(\"Unknown edition: \" + edition);\n }\n this._features = Object.assign(defaults, protoFeatures || {});\n this._featuresResolved = true;\n return;\n }\n\n // fields in Oneofs aren't actually children of them, so we have to\n // special-case it\n /* istanbul ignore else */\n if (this.partOf instanceof OneOf) {\n var lexicalParentFeaturesCopy = Object.assign({}, this.partOf._features);\n this._features = Object.assign(lexicalParentFeaturesCopy, protoFeatures || {});\n } else if (this.declaringField) {\n // Skip feature resolution of sister fields.\n } else if (this.parent) {\n var parentFeaturesCopy = Object.assign({}, this.parent._features);\n this._features = Object.assign(parentFeaturesCopy, protoFeatures || {});\n } else {\n throw new Error(\"Unable to find a parent for \" + this.fullName);\n }\n if (this.extensionField) {\n // Sister fields should have the same features as their extensions.\n this.extensionField._features = this._features;\n }\n this._featuresResolved = true;\n};\n\n/**\n * Infers features from legacy syntax that may have been specified differently.\n * in older editions.\n * @param {string|undefined} edition The edition this proto is on, or undefined if pre-editions\n * @returns {object} The feature values to override\n */\nReflectionObject.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(/*edition*/) {\n return {};\n};\n\n/**\n * Gets an option value.\n * @param {string} name Option name\n * @returns {*} Option value or `undefined` if not set\n */\nReflectionObject.prototype.getOption = function getOption(name) {\n if (this.options)\n return this.options[name];\n return undefined;\n};\n\n/**\n * Sets an option.\n * @param {string} name Option name\n * @param {*} value Option value\n * @param {boolean|undefined} [ifNotSet] Sets the option only if it isn't currently set\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) {\n if (!this.options)\n this.options = {};\n if (/^features\\./.test(name)) {\n util.setProperty(this.options, name, value, ifNotSet);\n } else if (!ifNotSet || this.options[name] === undefined) {\n if (this.getOption(name) !== value) this.resolved = false;\n this.options[name] = value;\n }\n\n return this;\n};\n\n/**\n * Sets a parsed option.\n * @param {string} name parsed Option name\n * @param {*} value Option value\n * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\\empty, will add a new option with that value\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) {\n if (!this.parsedOptions) {\n this.parsedOptions = [];\n }\n var parsedOptions = this.parsedOptions;\n if (propName) {\n // If setting a sub property of an option then try to merge it\n // with an existing option\n var opt = parsedOptions.find(function (opt) {\n return Object.prototype.hasOwnProperty.call(opt, name);\n });\n if (opt) {\n // If we found an existing option - just merge the property value\n // (If it's a feature, will just write over)\n var newValue = opt[name];\n util.setProperty(newValue, propName, value);\n } else {\n // otherwise, create a new option, set its property and add it to the list\n opt = {};\n opt[name] = util.setProperty({}, propName, value);\n parsedOptions.push(opt);\n }\n } else {\n // Always create a new option when setting the value of the option itself\n var newOpt = {};\n newOpt[name] = value;\n parsedOptions.push(newOpt);\n }\n\n return this;\n};\n\n/**\n * Sets multiple options.\n * @param {Object.} options Options to set\n * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) {\n if (options)\n for (var keys = Object.keys(options), i = 0; i < keys.length; ++i)\n this.setOption(keys[i], options[keys[i]], ifNotSet);\n return this;\n};\n\n/**\n * Converts this instance to its string representation.\n * @returns {string} Class name[, space, full name]\n */\nReflectionObject.prototype.toString = function toString() {\n var className = this.constructor.className,\n fullName = this.fullName;\n if (fullName.length)\n return className + \" \" + fullName;\n return className;\n};\n\n/**\n * Converts the edition this object is pinned to for JSON format.\n * @returns {string|undefined} The edition string for JSON representation\n */\nReflectionObject.prototype._editionToJSON = function _editionToJSON() {\n if (!this._edition || this._edition === \"proto3\") {\n // Avoid emitting proto3 since we need to default to it for backwards\n // compatibility anyway.\n return undefined;\n }\n return this._edition;\n};\n\n// Sets up cyclic dependencies (called in index-light)\nReflectionObject._configure = function(Root_) {\n Root = Root_;\n};\n","\"use strict\";\nmodule.exports = OneOf;\n\n// extends ReflectionObject\nvar ReflectionObject = require(24);\n((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = \"OneOf\";\n\nvar Field = require(16),\n util = require(37);\n\n/**\n * Constructs a new oneof instance.\n * @classdesc Reflected oneof.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Oneof name\n * @param {string[]|Object.} [fieldNames] Field names\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction OneOf(name, fieldNames, options, comment) {\n if (!Array.isArray(fieldNames)) {\n options = fieldNames;\n fieldNames = undefined;\n }\n ReflectionObject.call(this, name, options);\n\n /* istanbul ignore if */\n if (!(fieldNames === undefined || Array.isArray(fieldNames)))\n throw TypeError(\"fieldNames must be an Array\");\n\n /**\n * Field names that belong to this oneof.\n * @type {string[]}\n */\n this.oneof = fieldNames || []; // toJSON, marker\n\n /**\n * Fields that belong to this oneof as an array for iteration.\n * @type {Field[]}\n * @readonly\n */\n this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent\n\n /**\n * Comment for this field.\n * @type {string|null}\n */\n this.comment = comment;\n}\n\n/**\n * Oneof descriptor.\n * @interface IOneOf\n * @property {Array.} oneof Oneof field names\n * @property {Object.} [options] Oneof options\n */\n\n/**\n * Constructs a oneof from a oneof descriptor.\n * @param {string} name Oneof name\n * @param {IOneOf} json Oneof descriptor\n * @returns {OneOf} Created oneof\n * @throws {TypeError} If arguments are invalid\n */\nOneOf.fromJSON = function fromJSON(name, json) {\n return new OneOf(name, json.oneof, json.options, json.comment);\n};\n\n/**\n * Converts this oneof to a oneof descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IOneOf} Oneof descriptor\n */\nOneOf.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , this.options,\n \"oneof\" , this.oneof,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Adds the fields of the specified oneof to the parent if not already done so.\n * @param {OneOf} oneof The oneof\n * @returns {undefined}\n * @inner\n * @ignore\n */\nfunction addFieldsToParent(oneof) {\n if (oneof.parent)\n for (var i = 0; i < oneof.fieldsArray.length; ++i)\n if (!oneof.fieldsArray[i].parent)\n oneof.parent.add(oneof.fieldsArray[i]);\n}\n\n/**\n * Adds a field to this oneof and removes it from its current parent, if any.\n * @param {Field} field Field to add\n * @returns {OneOf} `this`\n */\nOneOf.prototype.add = function add(field) {\n\n /* istanbul ignore if */\n if (!(field instanceof Field))\n throw TypeError(\"field must be a Field\");\n\n if (field.parent && field.parent !== this.parent)\n field.parent.remove(field);\n this.oneof.push(field.name);\n this.fieldsArray.push(field);\n field.partOf = this; // field.parent remains null\n addFieldsToParent(this);\n return this;\n};\n\n/**\n * Removes a field from this oneof and puts it back to the oneof's parent.\n * @param {Field} field Field to remove\n * @returns {OneOf} `this`\n */\nOneOf.prototype.remove = function remove(field) {\n\n /* istanbul ignore if */\n if (!(field instanceof Field))\n throw TypeError(\"field must be a Field\");\n\n var index = this.fieldsArray.indexOf(field);\n\n /* istanbul ignore if */\n if (index < 0)\n throw Error(field + \" is not a member of \" + this);\n\n this.fieldsArray.splice(index, 1);\n index = this.oneof.indexOf(field.name);\n\n /* istanbul ignore else */\n if (index > -1) // theoretical\n this.oneof.splice(index, 1);\n\n field.partOf = null;\n return this;\n};\n\n/**\n * @override\n */\nOneOf.prototype.onAdd = function onAdd(parent) {\n ReflectionObject.prototype.onAdd.call(this, parent);\n var self = this;\n // Collect present fields\n for (var i = 0; i < this.oneof.length; ++i) {\n var field = parent.get(this.oneof[i]);\n if (field && !field.partOf) {\n field.partOf = self;\n self.fieldsArray.push(field);\n }\n }\n // Add not yet present fields\n addFieldsToParent(this);\n};\n\n/**\n * @override\n */\nOneOf.prototype.onRemove = function onRemove(parent) {\n for (var i = 0, field; i < this.fieldsArray.length; ++i)\n if ((field = this.fieldsArray[i]).parent)\n field.parent.remove(field);\n ReflectionObject.prototype.onRemove.call(this, parent);\n};\n\n/**\n * Determines whether this field corresponds to a synthetic oneof created for\n * a proto3 optional field. No behavioral logic should depend on this, but it\n * can be relevant for reflection.\n * @name OneOf#isProto3Optional\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(OneOf.prototype, \"isProto3Optional\", {\n get: function() {\n if (this.fieldsArray == null || this.fieldsArray.length !== 1) {\n return false;\n }\n\n var field = this.fieldsArray[0];\n return field.options != null && field.options[\"proto3_optional\"] === true;\n }\n});\n\n/**\n * Decorator function as returned by {@link OneOf.d} (TypeScript).\n * @typedef OneOfDecorator\n * @type {function}\n * @param {Object} prototype Target prototype\n * @param {string} oneofName OneOf name\n * @returns {undefined}\n */\n\n/**\n * OneOf decorator (TypeScript).\n * @function\n * @param {...string} fieldNames Field names\n * @returns {OneOfDecorator} Decorator function\n * @template T extends string\n */\nOneOf.d = function decorateOneOf() {\n var fieldNames = new Array(arguments.length),\n index = 0;\n while (index < arguments.length)\n fieldNames[index] = arguments[index++];\n return function oneOfDecorator(prototype, oneofName) {\n util.decorateType(prototype.constructor)\n .add(new OneOf(oneofName, fieldNames));\n Object.defineProperty(prototype, oneofName, {\n get: util.oneOfGetter(fieldNames),\n set: util.oneOfSetter(fieldNames)\n });\n };\n};\n","\"use strict\";\nmodule.exports = parse;\n\nparse.filename = null;\nparse.defaults = { keepCase: false };\n\nvar tokenize = require(34),\n Root = require(29),\n Type = require(35),\n Field = require(16),\n MapField = require(20),\n OneOf = require(25),\n Enum = require(15),\n Service = require(33),\n Method = require(22),\n ReflectionObject = require(24),\n types = require(36),\n util = require(37);\n\nvar base10Re = /^[1-9][0-9]*$/,\n base10NegRe = /^-?[1-9][0-9]*$/,\n base16Re = /^0[x][0-9a-fA-F]+$/,\n base16NegRe = /^-?0[x][0-9a-fA-F]+$/,\n base8Re = /^0[0-7]+$/,\n base8NegRe = /^-?0[0-7]+$/,\n numberRe = /^(?![eE])[0-9]*(?:\\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,\n nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/,\n typeRefRe = /^(?:\\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;\n\n/**\n * Result object returned from {@link parse}.\n * @interface IParserResult\n * @property {string|undefined} package Package name, if declared\n * @property {string[]|undefined} imports Imports, if any\n * @property {string[]|undefined} weakImports Weak imports, if any\n * @property {Root} root Populated root instance\n */\n\n/**\n * Options modifying the behavior of {@link parse}.\n * @interface IParseOptions\n * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case\n * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments.\n * @property {boolean} [preferTrailingComment=false] Use trailing comment when both leading comment and trailing comment exist.\n */\n\n/**\n * Options modifying the behavior of JSON serialization.\n * @interface IToJSONOptions\n * @property {boolean} [keepComments=false] Serializes comments.\n */\n\n/**\n * Parses the given .proto source and returns an object with the parsed contents.\n * @param {string} source Source contents\n * @param {Root} root Root to populate\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {IParserResult} Parser result\n * @property {string} filename=null Currently processing file name for error reporting, if known\n * @property {IParseOptions} defaults Default {@link IParseOptions}\n */\nfunction parse(source, root, options) {\n /* eslint-disable callback-return */\n if (!(root instanceof Root)) {\n options = root;\n root = new Root();\n }\n if (!options)\n options = parse.defaults;\n\n var preferTrailingComment = options.preferTrailingComment || false;\n var tn = tokenize(source, options.alternateCommentMode || false),\n next = tn.next,\n push = tn.push,\n peek = tn.peek,\n skip = tn.skip,\n cmnt = tn.cmnt;\n\n var head = true,\n pkg,\n imports,\n weakImports,\n edition = \"proto2\";\n\n var ptr = root;\n\n var topLevelObjects = [];\n var topLevelOptions = {};\n\n var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase;\n\n function resolveFileFeatures() {\n topLevelObjects.forEach(obj => {\n obj._edition = edition;\n Object.keys(topLevelOptions).forEach(opt => {\n if (obj.getOption(opt) !== undefined) return;\n obj.setOption(opt, topLevelOptions[opt], true);\n });\n });\n }\n\n /* istanbul ignore next */\n function illegal(token, name, insideTryCatch) {\n var filename = parse.filename;\n if (!insideTryCatch)\n parse.filename = null;\n return Error(\"illegal \" + (name || \"token\") + \" '\" + token + \"' (\" + (filename ? filename + \", \" : \"\") + \"line \" + tn.line + \")\");\n }\n\n function readString() {\n var values = [],\n token;\n do {\n /* istanbul ignore if */\n if ((token = next()) !== \"\\\"\" && token !== \"'\")\n throw illegal(token);\n\n values.push(next());\n skip(token);\n token = peek();\n } while (token === \"\\\"\" || token === \"'\");\n return values.join(\"\");\n }\n\n function readValue(acceptTypeRef) {\n var token = next();\n switch (token) {\n case \"'\":\n case \"\\\"\":\n push(token);\n return readString();\n case \"true\": case \"TRUE\":\n return true;\n case \"false\": case \"FALSE\":\n return false;\n }\n try {\n return parseNumber(token, /* insideTryCatch */ true);\n } catch (e) {\n /* istanbul ignore else */\n if (acceptTypeRef && typeRefRe.test(token))\n return token;\n\n /* istanbul ignore next */\n throw illegal(token, \"value\");\n }\n }\n\n function readRanges(target, acceptStrings) {\n var token, start;\n do {\n if (acceptStrings && ((token = peek()) === \"\\\"\" || token === \"'\")) {\n var str = readString();\n target.push(str);\n if (edition >= 2023) {\n throw illegal(str, \"id\");\n }\n } else {\n try {\n target.push([ start = parseId(next()), skip(\"to\", true) ? parseId(next()) : start ]);\n } catch (err) {\n if (acceptStrings && typeRefRe.test(token) && edition >= 2023) {\n target.push(token);\n } else {\n throw err;\n }\n }\n }\n } while (skip(\",\", true));\n var dummy = {options: undefined};\n dummy.setOption = function(name, value) {\n if (this.options === undefined) this.options = {};\n this.options[name] = value;\n };\n ifBlock(\n dummy,\n function parseRange_block(token) {\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(dummy, token); // skip\n skip(\";\");\n } else\n throw illegal(token);\n },\n function parseRange_line() {\n parseInlineOptions(dummy); // skip\n });\n }\n\n function parseNumber(token, insideTryCatch) {\n var sign = 1;\n if (token.charAt(0) === \"-\") {\n sign = -1;\n token = token.substring(1);\n }\n switch (token) {\n case \"inf\": case \"INF\": case \"Inf\":\n return sign * Infinity;\n case \"nan\": case \"NAN\": case \"Nan\": case \"NaN\":\n return NaN;\n case \"0\":\n return 0;\n }\n if (base10Re.test(token))\n return sign * parseInt(token, 10);\n if (base16Re.test(token))\n return sign * parseInt(token, 16);\n if (base8Re.test(token))\n return sign * parseInt(token, 8);\n\n /* istanbul ignore else */\n if (numberRe.test(token))\n return sign * parseFloat(token);\n\n /* istanbul ignore next */\n throw illegal(token, \"number\", insideTryCatch);\n }\n\n function parseId(token, acceptNegative) {\n switch (token) {\n case \"max\": case \"MAX\": case \"Max\":\n return 536870911;\n case \"0\":\n return 0;\n }\n\n /* istanbul ignore if */\n if (!acceptNegative && token.charAt(0) === \"-\")\n throw illegal(token, \"id\");\n\n if (base10NegRe.test(token))\n return parseInt(token, 10);\n if (base16NegRe.test(token))\n return parseInt(token, 16);\n\n /* istanbul ignore else */\n if (base8NegRe.test(token))\n return parseInt(token, 8);\n\n /* istanbul ignore next */\n throw illegal(token, \"id\");\n }\n\n function parsePackage() {\n /* istanbul ignore if */\n if (pkg !== undefined)\n throw illegal(\"package\");\n\n pkg = next();\n\n /* istanbul ignore if */\n if (!typeRefRe.test(pkg))\n throw illegal(pkg, \"name\");\n\n ptr = ptr.define(pkg);\n\n skip(\";\");\n }\n\n function parseImport() {\n var token = peek();\n var whichImports;\n switch (token) {\n case \"weak\":\n whichImports = weakImports || (weakImports = []);\n next();\n break;\n case \"public\":\n next();\n // eslint-disable-next-line no-fallthrough\n default:\n whichImports = imports || (imports = []);\n break;\n }\n token = readString();\n skip(\";\");\n whichImports.push(token);\n }\n\n function parseSyntax() {\n skip(\"=\");\n edition = readString();\n\n /* istanbul ignore if */\n if (edition < 2023)\n throw illegal(edition, \"syntax\");\n\n skip(\";\");\n }\n\n function parseEdition() {\n skip(\"=\");\n edition = readString();\n const supportedEditions = [\"2023\"];\n\n /* istanbul ignore if */\n if (!supportedEditions.includes(edition))\n throw illegal(edition, \"edition\");\n\n skip(\";\");\n }\n\n\n function parseCommon(parent, token) {\n switch (token) {\n\n case \"option\":\n parseOption(parent, token);\n skip(\";\");\n return true;\n\n case \"message\":\n parseType(parent, token);\n return true;\n\n case \"enum\":\n parseEnum(parent, token);\n return true;\n\n case \"service\":\n parseService(parent, token);\n return true;\n\n case \"extend\":\n parseExtension(parent, token);\n return true;\n }\n return false;\n }\n\n function ifBlock(obj, fnIf, fnElse) {\n var trailingLine = tn.line;\n if (obj) {\n if(typeof obj.comment !== \"string\") {\n obj.comment = cmnt(); // try block-type comment\n }\n obj.filename = parse.filename;\n }\n if (skip(\"{\", true)) {\n var token;\n while ((token = next()) !== \"}\")\n fnIf(token);\n skip(\";\", true);\n } else {\n if (fnElse)\n fnElse();\n skip(\";\");\n if (obj && (typeof obj.comment !== \"string\" || preferTrailingComment))\n obj.comment = cmnt(trailingLine) || obj.comment; // try line-type comment\n }\n }\n\n function parseType(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"type name\");\n\n var type = new Type(token);\n ifBlock(type, function parseType_block(token) {\n if (parseCommon(type, token))\n return;\n\n switch (token) {\n\n case \"map\":\n parseMapField(type, token);\n break;\n\n case \"required\":\n if (edition !== \"proto2\")\n throw illegal(token);\n /* eslint-disable no-fallthrough */\n case \"repeated\":\n parseField(type, token);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (edition === \"proto3\") {\n parseField(type, \"proto3_optional\");\n } else if (edition !== \"proto2\") {\n throw illegal(token);\n } else {\n parseField(type, \"optional\");\n }\n break;\n\n case \"oneof\":\n parseOneOf(type, token);\n break;\n\n case \"extensions\":\n readRanges(type.extensions || (type.extensions = []));\n break;\n\n case \"reserved\":\n readRanges(type.reserved || (type.reserved = []), true);\n break;\n\n default:\n /* istanbul ignore if */\n if (edition === \"proto2\" || !typeRefRe.test(token)) {\n throw illegal(token);\n }\n\n push(token);\n parseField(type, \"optional\");\n break;\n }\n });\n parent.add(type);\n if (parent === ptr) {\n topLevelObjects.push(type);\n }\n }\n\n function parseField(parent, rule, extend) {\n var type = next();\n if (type === \"group\") {\n parseGroup(parent, rule);\n return;\n }\n // Type names can consume multiple tokens, in multiple variants:\n // package.subpackage field tokens: \"package.subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package . subpackage field tokens: \"package\" \".\" \"subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package. subpackage field tokens: \"package.\" \"subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package .subpackage field tokens: \"package\" \".subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // Keep reading tokens until we get a type name with no period at the end,\n // and the next token does not start with a period.\n while (type.endsWith(\".\") || peek().startsWith(\".\")) {\n type += next();\n }\n\n /* istanbul ignore if */\n if (!typeRefRe.test(type))\n throw illegal(type, \"type\");\n\n var name = next();\n\n /* istanbul ignore if */\n\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n name = applyCase(name);\n skip(\"=\");\n\n var field = new Field(name, parseId(next()), type, rule, extend);\n\n ifBlock(field, function parseField_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(field, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseField_line() {\n parseInlineOptions(field);\n });\n\n if (rule === \"proto3_optional\") {\n // for proto3 optional fields, we create a single-member Oneof to mimic \"optional\" behavior\n var oneof = new OneOf(\"_\" + name);\n field.setOption(\"proto3_optional\", true);\n oneof.add(field);\n parent.add(oneof);\n } else {\n parent.add(field);\n }\n if (parent === ptr) {\n topLevelObjects.push(field);\n }\n }\n\n function parseGroup(parent, rule) {\n if (edition >= 2023) {\n throw illegal(\"group\");\n }\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n var fieldName = util.lcFirst(name);\n if (name === fieldName)\n name = util.ucFirst(name);\n skip(\"=\");\n var id = parseId(next());\n var type = new Type(name);\n type.group = true;\n var field = new Field(fieldName, id, name, rule);\n field.filename = parse.filename;\n ifBlock(type, function parseGroup_block(token) {\n switch (token) {\n\n case \"option\":\n parseOption(type, token);\n skip(\";\");\n break;\n case \"required\":\n case \"repeated\":\n parseField(type, token);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (edition === \"proto3\") {\n parseField(type, \"proto3_optional\");\n } else {\n parseField(type, \"optional\");\n }\n break;\n\n case \"message\":\n parseType(type, token);\n break;\n\n case \"enum\":\n parseEnum(type, token);\n break;\n\n case \"reserved\":\n readRanges(type.reserved || (type.reserved = []), true);\n break;\n\n /* istanbul ignore next */\n default:\n throw illegal(token); // there are no groups with proto3 semantics\n }\n });\n parent.add(type)\n .add(field);\n }\n\n function parseMapField(parent) {\n skip(\"<\");\n var keyType = next();\n\n /* istanbul ignore if */\n if (types.mapKey[keyType] === undefined)\n throw illegal(keyType, \"type\");\n\n skip(\",\");\n var valueType = next();\n\n /* istanbul ignore if */\n if (!typeRefRe.test(valueType))\n throw illegal(valueType, \"type\");\n\n skip(\">\");\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n skip(\"=\");\n var field = new MapField(applyCase(name), parseId(next()), keyType, valueType);\n ifBlock(field, function parseMapField_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(field, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseMapField_line() {\n parseInlineOptions(field);\n });\n parent.add(field);\n }\n\n function parseOneOf(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var oneof = new OneOf(applyCase(token));\n ifBlock(oneof, function parseOneOf_block(token) {\n if (token === \"option\") {\n parseOption(oneof, token);\n skip(\";\");\n } else {\n push(token);\n parseField(oneof, \"optional\");\n }\n });\n parent.add(oneof);\n }\n\n function parseEnum(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var enm = new Enum(token);\n ifBlock(enm, function parseEnum_block(token) {\n switch(token) {\n case \"option\":\n parseOption(enm, token);\n skip(\";\");\n break;\n\n case \"reserved\":\n readRanges(enm.reserved || (enm.reserved = []), true);\n if(enm.reserved === undefined) enm.reserved = [];\n break;\n\n default:\n parseEnumValue(enm, token);\n }\n });\n parent.add(enm);\n if (parent === ptr) {\n topLevelObjects.push(enm);\n }\n }\n\n function parseEnumValue(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token))\n throw illegal(token, \"name\");\n\n skip(\"=\");\n var value = parseId(next(), true),\n dummy = {\n options: undefined\n };\n dummy.getOption = function(name) {\n return this.options[name];\n };\n dummy.setOption = function(name, value) {\n ReflectionObject.prototype.setOption.call(dummy, name, value);\n };\n dummy.setParsedOption = function() {\n return undefined;\n };\n ifBlock(dummy, function parseEnumValue_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(dummy, token); // skip\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseEnumValue_line() {\n parseInlineOptions(dummy); // skip\n });\n parent.add(token, value, dummy.comment, dummy.parsedOptions || dummy.options);\n }\n\n function parseOption(parent, token) {\n var option;\n var propName;\n var isOption = true;\n if (token === \"option\") {\n token = next();\n }\n\n while (token !== \"=\") {\n if (token === \"(\") {\n var parensValue = next();\n skip(\")\");\n token = \"(\" + parensValue + \")\";\n }\n if (isOption) {\n isOption = false;\n if (token.includes(\".\") && !token.includes(\"(\")) {\n var tokens = token.split(\".\");\n option = tokens[0] + \".\";\n token = tokens[1];\n continue;\n }\n option = token;\n } else {\n propName = propName ? propName += token : token;\n }\n token = next();\n }\n var name = propName ? option.concat(propName) : option;\n var optionValue = parseOptionValue(parent, name);\n propName = propName && propName[0] === \".\" ? propName.slice(1) : propName;\n option = option && option[option.length - 1] === \".\" ? option.slice(0, -1) : option;\n setParsedOption(parent, option, optionValue, propName);\n }\n\n function parseOptionValue(parent, name) {\n // { a: \"foo\" b { c: \"bar\" } }\n if (skip(\"{\", true)) {\n var objectResult = {};\n\n while (!skip(\"}\", true)) {\n /* istanbul ignore if */\n if (!nameRe.test(token = next())) {\n throw illegal(token, \"name\");\n }\n if (token === null) {\n throw illegal(token, \"end of input\");\n }\n\n var value;\n var propName = token;\n\n skip(\":\", true);\n\n if (peek() === \"{\") {\n // option (my_option) = {\n // repeated_value: [ \"foo\", \"bar\" ]\n // };\n value = parseOptionValue(parent, name + \".\" + token);\n } else if (peek() === \"[\") {\n value = [];\n var lastValue;\n if (skip(\"[\", true)) {\n do {\n lastValue = readValue(true);\n value.push(lastValue);\n } while (skip(\",\", true));\n skip(\"]\");\n if (typeof lastValue !== \"undefined\") {\n setOption(parent, name + \".\" + token, lastValue);\n }\n }\n } else {\n value = readValue(true);\n setOption(parent, name + \".\" + token, value);\n }\n\n var prevValue = objectResult[propName];\n\n if (prevValue)\n value = [].concat(prevValue).concat(value);\n\n objectResult[propName] = value;\n\n // Semicolons and commas can be optional\n skip(\",\", true);\n skip(\";\", true);\n }\n\n return objectResult;\n }\n\n var simpleValue = readValue(true);\n setOption(parent, name, simpleValue);\n return simpleValue;\n // Does not enforce a delimiter to be universal\n }\n\n function setOption(parent, name, value) {\n if (ptr === parent && /^features\\./.test(name)) {\n topLevelOptions[name] = value;\n return;\n }\n if (parent.setOption)\n parent.setOption(name, value);\n }\n\n function setParsedOption(parent, name, value, propName) {\n if (parent.setParsedOption)\n parent.setParsedOption(name, value, propName);\n }\n\n function parseInlineOptions(parent) {\n if (skip(\"[\", true)) {\n do {\n parseOption(parent, \"option\");\n } while (skip(\",\", true));\n skip(\"]\");\n }\n return parent;\n }\n\n function parseService(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"service name\");\n\n var service = new Service(token);\n ifBlock(service, function parseService_block(token) {\n if (parseCommon(service, token)) {\n return;\n }\n\n /* istanbul ignore else */\n if (token === \"rpc\")\n parseMethod(service, token);\n else\n throw illegal(token);\n });\n parent.add(service);\n if (parent === ptr) {\n topLevelObjects.push(service);\n }\n }\n\n function parseMethod(parent, token) {\n // Get the comment of the preceding line now (if one exists) in case the\n // method is defined across multiple lines.\n var commentText = cmnt();\n\n var type = token;\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var name = token,\n requestType, requestStream,\n responseType, responseStream;\n\n skip(\"(\");\n if (skip(\"stream\", true))\n requestStream = true;\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token);\n\n requestType = token;\n skip(\")\"); skip(\"returns\"); skip(\"(\");\n if (skip(\"stream\", true))\n responseStream = true;\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token);\n\n responseType = token;\n skip(\")\");\n\n var method = new Method(name, type, requestType, responseType, requestStream, responseStream);\n method.comment = commentText;\n ifBlock(method, function parseMethod_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(method, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n });\n parent.add(method);\n }\n\n function parseExtension(parent, token) {\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token, \"reference\");\n\n var reference = token;\n ifBlock(null, function parseExtension_block(token) {\n switch (token) {\n\n case \"required\":\n case \"repeated\":\n parseField(parent, token, reference);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (edition === \"proto3\") {\n parseField(parent, \"proto3_optional\", reference);\n } else {\n parseField(parent, \"optional\", reference);\n }\n break;\n\n default:\n /* istanbul ignore if */\n if (edition === \"proto2\" || !typeRefRe.test(token))\n throw illegal(token);\n push(token);\n parseField(parent, \"optional\", reference);\n break;\n }\n });\n }\n\n var token;\n while ((token = next()) !== null) {\n switch (token) {\n\n case \"package\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parsePackage();\n break;\n\n case \"import\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parseImport();\n break;\n\n case \"syntax\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parseSyntax();\n break;\n\n case \"edition\":\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n parseEdition();\n break;\n\n case \"option\":\n parseOption(ptr, token);\n skip(\";\", true);\n break;\n\n default:\n\n /* istanbul ignore else */\n if (parseCommon(ptr, token)) {\n head = false;\n continue;\n }\n\n /* istanbul ignore next */\n throw illegal(token);\n }\n }\n\n resolveFileFeatures();\n\n parse.filename = null;\n return {\n \"package\" : pkg,\n \"imports\" : imports,\n weakImports : weakImports,\n root : root\n };\n}\n\n/**\n * Parses the given .proto source and returns an object with the parsed contents.\n * @name parse\n * @function\n * @param {string} source Source contents\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {IParserResult} Parser result\n * @property {string} filename=null Currently processing file name for error reporting, if known\n * @property {IParseOptions} defaults Default {@link IParseOptions}\n * @variation 2\n */\n","\"use strict\";\nmodule.exports = Reader;\n\nvar util = require(39);\n\nvar BufferReader; // cyclic\n\nvar LongBits = util.LongBits,\n utf8 = util.utf8;\n\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(\"index out of range: \" + reader.pos + \" + \" + (writeLength || 1) + \" > \" + reader.len);\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n * @param {Uint8Array} buffer Buffer to read from\n */\nfunction Reader(buffer) {\n\n /**\n * Read buffer.\n * @type {Uint8Array}\n */\n this.buf = buffer;\n\n /**\n * Read buffer position.\n * @type {number}\n */\n this.pos = 0;\n\n /**\n * Read buffer length.\n * @type {number}\n */\n this.len = buffer.length;\n}\n\nvar create_array = typeof Uint8Array !== \"undefined\"\n ? function create_typed_array(buffer) {\n if (buffer instanceof Uint8Array || Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n }\n /* istanbul ignore next */\n : function create_array(buffer) {\n if (Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n };\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup(buffer) {\n return (Reader.create = function create_buffer(buffer) {\n return util.Buffer.isBuffer(buffer)\n ? new BufferReader(buffer)\n /* istanbul ignore next */\n : create_array(buffer);\n })(buffer);\n }\n /* istanbul ignore next */\n : create_array;\n};\n\n/**\n * Creates a new reader using the specified buffer.\n * @function\n * @param {Uint8Array|Buffer} buffer Buffer to read from\n * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}\n * @throws {Error} If `buffer` is not a valid buffer\n */\nReader.create = create();\n\nReader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;\n\n/**\n * Reads a varint as an unsigned 32 bit value.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.uint32 = (function read_uint32_setup() {\n var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)\n return function read_uint32() {\n value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;\n\n /* istanbul ignore if */\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n };\n})();\n\n/**\n * Reads a varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.int32 = function read_int32() {\n return this.uint32() | 0;\n};\n\n/**\n * Reads a zig-zag encoded varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.sint32 = function read_sint32() {\n var value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readLongVarint() {\n // tends to deopt with local vars for octet etc.\n var bits = new LongBits(0, 0);\n var i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n i = 0;\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n } else {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n }\n /* istanbul ignore next */\n throw Error(\"invalid varint encoding\");\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads a varint as a signed 64 bit value.\n * @name Reader#int64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as an unsigned 64 bit value.\n * @name Reader#uint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a zig-zag encoded varint as a signed 64 bit value.\n * @name Reader#sint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as a boolean.\n * @returns {boolean} Value read\n */\nReader.prototype.bool = function read_bool() {\n return this.uint32() !== 0;\n};\n\nfunction readFixed32_end(buf, end) { // note that this uses `end`, not `pos`\n return (buf[end - 4]\n | buf[end - 3] << 8\n | buf[end - 2] << 16\n | buf[end - 1] << 24) >>> 0;\n}\n\n/**\n * Reads fixed 32 bits as an unsigned 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.fixed32 = function read_fixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4);\n};\n\n/**\n * Reads fixed 32 bits as a signed 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.sfixed32 = function read_sfixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readFixed64(/* this: Reader */) {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 8);\n\n return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads fixed 64 bits.\n * @name Reader#fixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads zig-zag encoded fixed 64 bits.\n * @name Reader#sfixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a float (32 bit) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.float = function read_float() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readFloatLE(this.buf, this.pos);\n this.pos += 4;\n return value;\n};\n\n/**\n * Reads a double (64 bit float) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.double = function read_double() {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readDoubleLE(this.buf, this.pos);\n this.pos += 8;\n return value;\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @returns {Uint8Array} Value read\n */\nReader.prototype.bytes = function read_bytes() {\n var length = this.uint32(),\n start = this.pos,\n end = this.pos + length;\n\n /* istanbul ignore if */\n if (end > this.len)\n throw indexOutOfRange(this, length);\n\n this.pos += length;\n if (Array.isArray(this.buf)) // plain array\n return this.buf.slice(start, end);\n\n if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1\n var nativeBuffer = util.Buffer;\n return nativeBuffer\n ? nativeBuffer.alloc(0)\n : new this.buf.constructor(0);\n }\n return this._slice.call(this.buf, start, end);\n};\n\n/**\n * Reads a string preceeded by its byte length as a varint.\n * @returns {string} Value read\n */\nReader.prototype.string = function read_string() {\n var bytes = this.bytes();\n return utf8.read(bytes, 0, bytes.length);\n};\n\n/**\n * Skips the specified number of bytes if specified, otherwise skips a varint.\n * @param {number} [length] Length if known, otherwise a varint is assumed\n * @returns {Reader} `this`\n */\nReader.prototype.skip = function skip(length) {\n if (typeof length === \"number\") {\n /* istanbul ignore if */\n if (this.pos + length > this.len)\n throw indexOutOfRange(this, length);\n this.pos += length;\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n } while (this.buf[this.pos++] & 128);\n }\n return this;\n};\n\n/**\n * Skips the next element of the specified wire type.\n * @param {number} wireType Wire type received\n * @returns {Reader} `this`\n */\nReader.prototype.skipType = function(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n\n /* istanbul ignore next */\n default:\n throw Error(\"invalid wire type \" + wireType + \" at offset \" + this.pos);\n }\n return this;\n};\n\nReader._configure = function(BufferReader_) {\n BufferReader = BufferReader_;\n Reader.create = create();\n BufferReader._configure();\n\n var fn = util.Long ? \"toLong\" : /* istanbul ignore next */ \"toNumber\";\n util.merge(Reader.prototype, {\n\n int64: function read_int64() {\n return readLongVarint.call(this)[fn](false);\n },\n\n uint64: function read_uint64() {\n return readLongVarint.call(this)[fn](true);\n },\n\n sint64: function read_sint64() {\n return readLongVarint.call(this).zzDecode()[fn](false);\n },\n\n fixed64: function read_fixed64() {\n return readFixed64.call(this)[fn](true);\n },\n\n sfixed64: function read_sfixed64() {\n return readFixed64.call(this)[fn](false);\n }\n\n });\n};\n","\"use strict\";\nmodule.exports = BufferReader;\n\n// extends Reader\nvar Reader = require(27);\n(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;\n\nvar util = require(39);\n\n/**\n * Constructs a new buffer reader instance.\n * @classdesc Wire format reader using node buffers.\n * @extends Reader\n * @constructor\n * @param {Buffer} buffer Buffer to read from\n */\nfunction BufferReader(buffer) {\n Reader.call(this, buffer);\n\n /**\n * Read buffer.\n * @name BufferReader#buf\n * @type {Buffer}\n */\n}\n\nBufferReader._configure = function () {\n /* istanbul ignore else */\n if (util.Buffer)\n BufferReader.prototype._slice = util.Buffer.prototype.slice;\n};\n\n\n/**\n * @override\n */\nBufferReader.prototype.string = function read_string_buffer() {\n var len = this.uint32(); // modifies pos\n return this.buf.utf8Slice\n ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))\n : this.buf.toString(\"utf-8\", this.pos, this.pos = Math.min(this.pos + len, this.len));\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @name BufferReader#bytes\n * @function\n * @returns {Buffer} Value read\n */\n\nBufferReader._configure();\n","\"use strict\";\nmodule.exports = Root;\n\n// extends Namespace\nvar Namespace = require(23);\n((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = \"Root\";\n\nvar Field = require(16),\n Enum = require(15),\n OneOf = require(25),\n util = require(37);\n\nvar Type, // cyclic\n parse, // might be excluded\n common; // \"\n\n/**\n * Constructs a new root namespace instance.\n * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together.\n * @extends NamespaceBase\n * @constructor\n * @param {Object.} [options] Top level options\n */\nfunction Root(options) {\n Namespace.call(this, \"\", options);\n\n /**\n * Deferred extension fields.\n * @type {Field[]}\n */\n this.deferred = [];\n\n /**\n * Resolved file names of loaded files.\n * @type {string[]}\n */\n this.files = [];\n\n /**\n * Edition, defaults to proto2 if unspecified.\n * @type {string}\n * @private\n */\n this._edition = \"proto2\";\n\n /**\n * Global lookup cache of fully qualified names.\n * @type {Object.}\n * @private\n */\n this._fullyQualifiedObjects = {};\n}\n\n/**\n * Loads a namespace descriptor into a root namespace.\n * @param {INamespace} json Namespace descriptor\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted\n * @returns {Root} Root namespace\n */\nRoot.fromJSON = function fromJSON(json, root) {\n if (!root)\n root = new Root();\n if (json.options)\n root.setOptions(json.options);\n return root.addJSON(json.nested).resolveAll();\n};\n\n/**\n * Resolves the path of an imported file, relative to the importing origin.\n * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories.\n * @function\n * @param {string} origin The file name of the importing file\n * @param {string} target The file name being imported\n * @returns {string|null} Resolved path to `target` or `null` to skip the file\n */\nRoot.prototype.resolvePath = util.path.resolve;\n\n/**\n * Fetch content from file path or url\n * This method exists so you can override it with your own logic.\n * @function\n * @param {string} path File path or url\n * @param {FetchCallback} callback Callback function\n * @returns {undefined}\n */\nRoot.prototype.fetch = util.fetch;\n\n// A symbol-like function to safely signal synchronous loading\n/* istanbul ignore next */\nfunction SYNC() {} // eslint-disable-line no-empty-function\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} options Parse options\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n */\nRoot.prototype.load = function load(filename, options, callback) {\n if (typeof options === \"function\") {\n callback = options;\n options = undefined;\n }\n var self = this;\n if (!callback) {\n return util.asPromise(load, self, filename, options);\n }\n\n var sync = callback === SYNC; // undocumented\n\n // Finishes loading by calling the callback (exactly once)\n function finish(err, root) {\n /* istanbul ignore if */\n if (!callback) {\n return;\n }\n if (sync) {\n throw err;\n }\n if (root) {\n root.resolveAll();\n }\n var cb = callback;\n callback = null;\n cb(err, root);\n }\n\n // Bundled definition existence checking\n function getBundledFileName(filename) {\n var idx = filename.lastIndexOf(\"google/protobuf/\");\n if (idx > -1) {\n var altname = filename.substring(idx);\n if (altname in common) return altname;\n }\n return null;\n }\n\n // Processes a single file\n function process(filename, source) {\n try {\n if (util.isString(source) && source.charAt(0) === \"{\")\n source = JSON.parse(source);\n if (!util.isString(source))\n self.setOptions(source.options).addJSON(source.nested);\n else {\n parse.filename = filename;\n var parsed = parse(source, self, options),\n resolved,\n i = 0;\n if (parsed.imports)\n for (; i < parsed.imports.length; ++i)\n if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i]))\n fetch(resolved);\n if (parsed.weakImports)\n for (i = 0; i < parsed.weakImports.length; ++i)\n if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i]))\n fetch(resolved, true);\n }\n } catch (err) {\n finish(err);\n }\n if (!sync && !queued) {\n finish(null, self); // only once anyway\n }\n }\n\n // Fetches a single file\n function fetch(filename, weak) {\n filename = getBundledFileName(filename) || filename;\n\n // Skip if already loaded / attempted\n if (self.files.indexOf(filename) > -1) {\n return;\n }\n self.files.push(filename);\n\n // Shortcut bundled definitions\n if (filename in common) {\n if (sync) {\n process(filename, common[filename]);\n } else {\n ++queued;\n setTimeout(function() {\n --queued;\n process(filename, common[filename]);\n });\n }\n return;\n }\n\n // Otherwise fetch from disk or network\n if (sync) {\n var source;\n try {\n source = util.fs.readFileSync(filename).toString(\"utf8\");\n } catch (err) {\n if (!weak)\n finish(err);\n return;\n }\n process(filename, source);\n } else {\n ++queued;\n self.fetch(filename, function(err, source) {\n --queued;\n /* istanbul ignore if */\n if (!callback) {\n return; // terminated meanwhile\n }\n if (err) {\n /* istanbul ignore else */\n if (!weak)\n finish(err);\n else if (!queued) // can't be covered reliably\n finish(null, self);\n return;\n }\n process(filename, source);\n });\n }\n }\n var queued = 0;\n\n // Assembling the root namespace doesn't require working type\n // references anymore, so we can load everything in parallel\n if (util.isString(filename)) {\n filename = [ filename ];\n }\n for (var i = 0, resolved; i < filename.length; ++i)\n if (resolved = self.resolvePath(\"\", filename[i]))\n fetch(resolved);\n if (sync) {\n self.resolveAll();\n return self;\n }\n if (!queued) {\n finish(null, self);\n }\n\n return self;\n};\n// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\n * @function Root#load\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @variation 2\n */\n// function load(filename:string, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise.\n * @function Root#load\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {Promise} Promise\n * @variation 3\n */\n// function load(filename:string, [options:IParseOptions]):Promise\n\n/**\n * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only).\n * @function Root#loadSync\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {Root} Root namespace\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\n */\nRoot.prototype.loadSync = function loadSync(filename, options) {\n if (!util.isNode)\n throw Error(\"not supported\");\n return this.load(filename, options, SYNC);\n};\n\n/**\n * @override\n */\nRoot.prototype.resolveAll = function resolveAll() {\n if (!this._needsRecursiveResolve) return this;\n\n if (this.deferred.length)\n throw Error(\"unresolvable extensions: \" + this.deferred.map(function(field) {\n return \"'extend \" + field.extend + \"' in \" + field.parent.fullName;\n }).join(\", \"));\n return Namespace.prototype.resolveAll.call(this);\n};\n\n// only uppercased (and thus conflict-free) children are exposed, see below\nvar exposeRe = /^[A-Z]/;\n\n/**\n * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type.\n * @param {Root} root Root instance\n * @param {Field} field Declaring extension field witin the declaring type\n * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise\n * @inner\n * @ignore\n */\nfunction tryHandleExtension(root, field) {\n var extendedType = field.parent.lookup(field.extend);\n if (extendedType) {\n var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options);\n //do not allow to extend same field twice to prevent the error\n if (extendedType.get(sisterField.name)) {\n return true;\n }\n sisterField.declaringField = field;\n field.extensionField = sisterField;\n extendedType.add(sisterField);\n return true;\n }\n return false;\n}\n\n/**\n * Called when any object is added to this root or its sub-namespaces.\n * @param {ReflectionObject} object Object added\n * @returns {undefined}\n * @private\n */\nRoot.prototype._handleAdd = function _handleAdd(object) {\n if (object instanceof Field) {\n\n if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField)\n if (!tryHandleExtension(this, object))\n this.deferred.push(object);\n\n } else if (object instanceof Enum) {\n\n if (exposeRe.test(object.name))\n object.parent[object.name] = object.values; // expose enum values as property of its parent\n\n } else if (!(object instanceof OneOf)) /* everything else is a namespace */ {\n\n if (object instanceof Type) // Try to handle any deferred extensions\n for (var i = 0; i < this.deferred.length;)\n if (tryHandleExtension(this, this.deferred[i]))\n this.deferred.splice(i, 1);\n else\n ++i;\n for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace\n this._handleAdd(object._nestedArray[j]);\n if (exposeRe.test(object.name))\n object.parent[object.name] = object; // expose namespace as property of its parent\n }\n\n if (object instanceof Type || object instanceof Enum || object instanceof Field) {\n // Only store types and enums for quick lookup during resolve.\n this._fullyQualifiedObjects[object.fullName] = object;\n }\n\n // The above also adds uppercased (and thus conflict-free) nested types, services and enums as\n // properties of namespaces just like static code does. This allows using a .d.ts generated for\n // a static module with reflection-based solutions where the condition is met.\n};\n\n/**\n * Called when any object is removed from this root or its sub-namespaces.\n * @param {ReflectionObject} object Object removed\n * @returns {undefined}\n * @private\n */\nRoot.prototype._handleRemove = function _handleRemove(object) {\n if (object instanceof Field) {\n\n if (/* an extension field */ object.extend !== undefined) {\n if (/* already handled */ object.extensionField) { // remove its sister field\n object.extensionField.parent.remove(object.extensionField);\n object.extensionField = null;\n } else { // cancel the extension\n var index = this.deferred.indexOf(object);\n /* istanbul ignore else */\n if (index > -1)\n this.deferred.splice(index, 1);\n }\n }\n\n } else if (object instanceof Enum) {\n\n if (exposeRe.test(object.name))\n delete object.parent[object.name]; // unexpose enum values\n\n } else if (object instanceof Namespace) {\n\n for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace\n this._handleRemove(object._nestedArray[i]);\n\n if (exposeRe.test(object.name))\n delete object.parent[object.name]; // unexpose namespaces\n\n }\n\n delete this._fullyQualifiedObjects[object.fullName];\n};\n\n// Sets up cyclic dependencies (called in index-light)\nRoot._configure = function(Type_, parse_, common_) {\n Type = Type_;\n parse = parse_;\n common = common_;\n};\n","\"use strict\";\nmodule.exports = {};\n\n/**\n * Named roots.\n * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).\n * Can also be used manually to make roots available across modules.\n * @name roots\n * @type {Object.}\n * @example\n * // pbjs -r myroot -o compiled.js ...\n *\n * // in another module:\n * require(\"./compiled.js\");\n *\n * // in any subsequent module:\n * var root = protobuf.roots[\"myroot\"];\n */\n","\"use strict\";\n\n/**\n * Streaming RPC helpers.\n * @namespace\n */\nvar rpc = exports;\n\n/**\n * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.\n * @typedef RPCImpl\n * @type {function}\n * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called\n * @param {Uint8Array} requestData Request data\n * @param {RPCImplCallback} callback Callback function\n * @returns {undefined}\n * @example\n * function rpcImpl(method, requestData, callback) {\n * if (protobuf.util.lcFirst(method.name) !== \"myMethod\") // compatible with static code\n * throw Error(\"no such method\");\n * asynchronouslyObtainAResponse(requestData, function(err, responseData) {\n * callback(err, responseData);\n * });\n * }\n */\n\n/**\n * Node-style callback as used by {@link RPCImpl}.\n * @typedef RPCImplCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error\n * @returns {undefined}\n */\n\nrpc.Service = require(32);\n","\"use strict\";\nmodule.exports = Service;\n\nvar util = require(39);\n\n// Extends EventEmitter\n(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;\n\n/**\n * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.\n *\n * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.\n * @typedef rpc.ServiceMethodCallback\n * @template TRes extends Message\n * @type {function}\n * @param {Error|null} error Error, if any\n * @param {TRes} [response] Response message\n * @returns {undefined}\n */\n\n/**\n * A service method part of a {@link rpc.Service} as created by {@link Service.create}.\n * @typedef rpc.ServiceMethod\n * @template TReq extends Message\n * @template TRes extends Message\n * @type {function}\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message\n * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined`\n */\n\n/**\n * Constructs a new RPC service instance.\n * @classdesc An RPC service as returned by {@link Service#create}.\n * @exports rpc.Service\n * @extends util.EventEmitter\n * @constructor\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n */\nfunction Service(rpcImpl, requestDelimited, responseDelimited) {\n\n if (typeof rpcImpl !== \"function\")\n throw TypeError(\"rpcImpl must be a function\");\n\n util.EventEmitter.call(this);\n\n /**\n * RPC implementation. Becomes `null` once the service is ended.\n * @type {RPCImpl|null}\n */\n this.rpcImpl = rpcImpl;\n\n /**\n * Whether requests are length-delimited.\n * @type {boolean}\n */\n this.requestDelimited = Boolean(requestDelimited);\n\n /**\n * Whether responses are length-delimited.\n * @type {boolean}\n */\n this.responseDelimited = Boolean(responseDelimited);\n}\n\n/**\n * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.\n * @param {Method|rpc.ServiceMethod} method Reflected or static method\n * @param {Constructor} requestCtor Request constructor\n * @param {Constructor} responseCtor Response constructor\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} callback Service callback\n * @returns {undefined}\n * @template TReq extends Message\n * @template TRes extends Message\n */\nService.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {\n\n if (!request)\n throw TypeError(\"request must be specified\");\n\n var self = this;\n if (!callback)\n return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);\n\n if (!self.rpcImpl) {\n setTimeout(function() { callback(Error(\"already ended\")); }, 0);\n return undefined;\n }\n\n try {\n return self.rpcImpl(\n method,\n requestCtor[self.requestDelimited ? \"encodeDelimited\" : \"encode\"](request).finish(),\n function rpcCallback(err, response) {\n\n if (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n\n if (response === null) {\n self.end(/* endedByRPC */ true);\n return undefined;\n }\n\n if (!(response instanceof responseCtor)) {\n try {\n response = responseCtor[self.responseDelimited ? \"decodeDelimited\" : \"decode\"](response);\n } catch (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n }\n\n self.emit(\"data\", response, method);\n return callback(null, response);\n }\n );\n } catch (err) {\n self.emit(\"error\", err, method);\n setTimeout(function() { callback(err); }, 0);\n return undefined;\n }\n};\n\n/**\n * Ends this service and emits the `end` event.\n * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.\n * @returns {rpc.Service} `this`\n */\nService.prototype.end = function end(endedByRPC) {\n if (this.rpcImpl) {\n if (!endedByRPC) // signal end to rpcImpl\n this.rpcImpl(null, null, null);\n this.rpcImpl = null;\n this.emit(\"end\").off();\n }\n return this;\n};\n","\"use strict\";\nmodule.exports = Service;\n\n// extends Namespace\nvar Namespace = require(23);\n((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = \"Service\";\n\nvar Method = require(22),\n util = require(37),\n rpc = require(31);\n\n/**\n * Constructs a new service instance.\n * @classdesc Reflected service.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Service name\n * @param {Object.} [options] Service options\n * @throws {TypeError} If arguments are invalid\n */\nfunction Service(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Service methods.\n * @type {Object.}\n */\n this.methods = {}; // toJSON, marker\n\n /**\n * Cached methods as an array.\n * @type {Method[]|null}\n * @private\n */\n this._methodsArray = null;\n}\n\n/**\n * Service descriptor.\n * @interface IService\n * @extends INamespace\n * @property {Object.} methods Method descriptors\n */\n\n/**\n * Constructs a service from a service descriptor.\n * @param {string} name Service name\n * @param {IService} json Service descriptor\n * @returns {Service} Created service\n * @throws {TypeError} If arguments are invalid\n */\nService.fromJSON = function fromJSON(name, json) {\n var service = new Service(name, json.options);\n /* istanbul ignore else */\n if (json.methods)\n for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i)\n service.add(Method.fromJSON(names[i], json.methods[names[i]]));\n if (json.nested)\n service.addJSON(json.nested);\n if (json.edition)\n service._edition = json.edition;\n service.comment = json.comment;\n service._defaultEdition = \"proto3\"; // For backwards-compatibility.\n return service;\n};\n\n/**\n * Converts this service to a service descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IService} Service descriptor\n */\nService.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"edition\" , this._editionToJSON(),\n \"options\" , inherited && inherited.options || undefined,\n \"methods\" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {},\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Methods of this service as an array for iteration.\n * @name Service#methodsArray\n * @type {Method[]}\n * @readonly\n */\nObject.defineProperty(Service.prototype, \"methodsArray\", {\n get: function() {\n return this._methodsArray || (this._methodsArray = util.toArray(this.methods));\n }\n});\n\nfunction clearCache(service) {\n service._methodsArray = null;\n return service;\n}\n\n/**\n * @override\n */\nService.prototype.get = function get(name) {\n return this.methods[name]\n || Namespace.prototype.get.call(this, name);\n};\n\n/**\n * @override\n */\nService.prototype.resolveAll = function resolveAll() {\n if (!this._needsRecursiveResolve) return this;\n\n Namespace.prototype.resolve.call(this);\n var methods = this.methodsArray;\n for (var i = 0; i < methods.length; ++i)\n methods[i].resolve();\n return this;\n};\n\n/**\n * @override\n */\nService.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) {\n if (!this._needsRecursiveFeatureResolution) return this;\n\n edition = this._edition || edition;\n\n Namespace.prototype._resolveFeaturesRecursive.call(this, edition);\n this.methodsArray.forEach(method => {\n method._resolveFeaturesRecursive(edition);\n });\n return this;\n};\n\n/**\n * @override\n */\nService.prototype.add = function add(object) {\n\n /* istanbul ignore if */\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Method) {\n this.methods[object.name] = object;\n object.parent = this;\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * @override\n */\nService.prototype.remove = function remove(object) {\n if (object instanceof Method) {\n\n /* istanbul ignore if */\n if (this.methods[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.methods[object.name];\n object.parent = null;\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Creates a runtime service using the specified rpc implementation.\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed.\n */\nService.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) {\n var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);\n for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) {\n var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\\w_]/g, \"\");\n rpcService[methodName] = util.codegen([\"r\",\"c\"], util.isReserved(methodName) ? methodName + \"_\" : methodName)(\"return this.rpcCall(m,q,s,r,c)\")({\n m: method,\n q: method.resolvedRequestType.ctor,\n s: method.resolvedResponseType.ctor\n });\n }\n return rpcService;\n};\n","\"use strict\";\nmodule.exports = tokenize;\n\nvar delimRe = /[\\s{}=;:[\\],'\"()<>]/g,\n stringDoubleRe = /(?:\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\")/g,\n stringSingleRe = /(?:'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)')/g;\n\nvar setCommentRe = /^ *[*/]+ */,\n setCommentAltRe = /^\\s*\\*?\\/*/,\n setCommentSplitRe = /\\n/g,\n whitespaceRe = /\\s/,\n unescapeRe = /\\\\(.?)/g;\n\nvar unescapeMap = {\n \"0\": \"\\0\",\n \"r\": \"\\r\",\n \"n\": \"\\n\",\n \"t\": \"\\t\"\n};\n\n/**\n * Unescapes a string.\n * @param {string} str String to unescape\n * @returns {string} Unescaped string\n * @property {Object.} map Special characters map\n * @memberof tokenize\n */\nfunction unescape(str) {\n return str.replace(unescapeRe, function($0, $1) {\n switch ($1) {\n case \"\\\\\":\n case \"\":\n return $1;\n default:\n return unescapeMap[$1] || \"\";\n }\n });\n}\n\ntokenize.unescape = unescape;\n\n/**\n * Gets the next token and advances.\n * @typedef TokenizerHandleNext\n * @type {function}\n * @returns {string|null} Next token or `null` on eof\n */\n\n/**\n * Peeks for the next token.\n * @typedef TokenizerHandlePeek\n * @type {function}\n * @returns {string|null} Next token or `null` on eof\n */\n\n/**\n * Pushes a token back to the stack.\n * @typedef TokenizerHandlePush\n * @type {function}\n * @param {string} token Token\n * @returns {undefined}\n */\n\n/**\n * Skips the next token.\n * @typedef TokenizerHandleSkip\n * @type {function}\n * @param {string} expected Expected token\n * @param {boolean} [optional=false] If optional\n * @returns {boolean} Whether the token matched\n * @throws {Error} If the token didn't match and is not optional\n */\n\n/**\n * Gets the comment on the previous line or, alternatively, the line comment on the specified line.\n * @typedef TokenizerHandleCmnt\n * @type {function}\n * @param {number} [line] Line number\n * @returns {string|null} Comment text or `null` if none\n */\n\n/**\n * Handle object returned from {@link tokenize}.\n * @interface ITokenizerHandle\n * @property {TokenizerHandleNext} next Gets the next token and advances (`null` on eof)\n * @property {TokenizerHandlePeek} peek Peeks for the next token (`null` on eof)\n * @property {TokenizerHandlePush} push Pushes a token back to the stack\n * @property {TokenizerHandleSkip} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws\n * @property {TokenizerHandleCmnt} cmnt Gets the comment on the previous line or the line comment on the specified line, if any\n * @property {number} line Current line number\n */\n\n/**\n * Tokenizes the given .proto source and returns an object with useful utility functions.\n * @param {string} source Source contents\n * @param {boolean} alternateCommentMode Whether we should activate alternate comment parsing mode.\n * @returns {ITokenizerHandle} Tokenizer handle\n */\nfunction tokenize(source, alternateCommentMode) {\n /* eslint-disable callback-return */\n source = source.toString();\n\n var offset = 0,\n length = source.length,\n line = 1,\n lastCommentLine = 0,\n comments = {};\n\n var stack = [];\n\n var stringDelim = null;\n\n /* istanbul ignore next */\n /**\n * Creates an error for illegal syntax.\n * @param {string} subject Subject\n * @returns {Error} Error created\n * @inner\n */\n function illegal(subject) {\n return Error(\"illegal \" + subject + \" (line \" + line + \")\");\n }\n\n /**\n * Reads a string till its end.\n * @returns {string} String read\n * @inner\n */\n function readString() {\n var re = stringDelim === \"'\" ? stringSingleRe : stringDoubleRe;\n re.lastIndex = offset - 1;\n var match = re.exec(source);\n if (!match)\n throw illegal(\"string\");\n offset = re.lastIndex;\n push(stringDelim);\n stringDelim = null;\n return unescape(match[1]);\n }\n\n /**\n * Gets the character at `pos` within the source.\n * @param {number} pos Position\n * @returns {string} Character\n * @inner\n */\n function charAt(pos) {\n return source.charAt(pos);\n }\n\n /**\n * Sets the current comment text.\n * @param {number} start Start offset\n * @param {number} end End offset\n * @param {boolean} isLeading set if a leading comment\n * @returns {undefined}\n * @inner\n */\n function setComment(start, end, isLeading) {\n var comment = {\n type: source.charAt(start++),\n lineEmpty: false,\n leading: isLeading,\n };\n var lookback;\n if (alternateCommentMode) {\n lookback = 2; // alternate comment parsing: \"//\" or \"/*\"\n } else {\n lookback = 3; // \"///\" or \"/**\"\n }\n var commentOffset = start - lookback,\n c;\n do {\n if (--commentOffset < 0 ||\n (c = source.charAt(commentOffset)) === \"\\n\") {\n comment.lineEmpty = true;\n break;\n }\n } while (c === \" \" || c === \"\\t\");\n var lines = source\n .substring(start, end)\n .split(setCommentSplitRe);\n for (var i = 0; i < lines.length; ++i)\n lines[i] = lines[i]\n .replace(alternateCommentMode ? setCommentAltRe : setCommentRe, \"\")\n .trim();\n comment.text = lines\n .join(\"\\n\")\n .trim();\n\n comments[line] = comment;\n lastCommentLine = line;\n }\n\n function isDoubleSlashCommentLine(startOffset) {\n var endOffset = findEndOfLine(startOffset);\n\n // see if remaining line matches comment pattern\n var lineText = source.substring(startOffset, endOffset);\n var isComment = /^\\s*\\/\\//.test(lineText);\n return isComment;\n }\n\n function findEndOfLine(cursor) {\n // find end of cursor's line\n var endOffset = cursor;\n while (endOffset < length && charAt(endOffset) !== \"\\n\") {\n endOffset++;\n }\n return endOffset;\n }\n\n /**\n * Obtains the next token.\n * @returns {string|null} Next token or `null` on eof\n * @inner\n */\n function next() {\n if (stack.length > 0)\n return stack.shift();\n if (stringDelim)\n return readString();\n var repeat,\n prev,\n curr,\n start,\n isDoc,\n isLeadingComment = offset === 0;\n do {\n if (offset === length)\n return null;\n repeat = false;\n while (whitespaceRe.test(curr = charAt(offset))) {\n if (curr === \"\\n\") {\n isLeadingComment = true;\n ++line;\n }\n if (++offset === length)\n return null;\n }\n\n if (charAt(offset) === \"/\") {\n if (++offset === length) {\n throw illegal(\"comment\");\n }\n if (charAt(offset) === \"/\") { // Line\n if (!alternateCommentMode) {\n // check for triple-slash comment\n isDoc = charAt(start = offset + 1) === \"/\";\n\n while (charAt(++offset) !== \"\\n\") {\n if (offset === length) {\n return null;\n }\n }\n ++offset;\n if (isDoc) {\n setComment(start, offset - 1, isLeadingComment);\n // Trailing comment cannot not be multi-line,\n // so leading comment state should be reset to handle potential next comments\n isLeadingComment = true;\n }\n ++line;\n repeat = true;\n } else {\n // check for double-slash comments, consolidating consecutive lines\n start = offset;\n isDoc = false;\n if (isDoubleSlashCommentLine(offset - 1)) {\n isDoc = true;\n do {\n offset = findEndOfLine(offset);\n if (offset === length) {\n break;\n }\n offset++;\n if (!isLeadingComment) {\n // Trailing comment cannot not be multi-line\n break;\n }\n } while (isDoubleSlashCommentLine(offset));\n } else {\n offset = Math.min(length, findEndOfLine(offset) + 1);\n }\n if (isDoc) {\n setComment(start, offset, isLeadingComment);\n isLeadingComment = true;\n }\n line++;\n repeat = true;\n }\n } else if ((curr = charAt(offset)) === \"*\") { /* Block */\n // check for /** (regular comment mode) or /* (alternate comment mode)\n start = offset + 1;\n isDoc = alternateCommentMode || charAt(start) === \"*\";\n do {\n if (curr === \"\\n\") {\n ++line;\n }\n if (++offset === length) {\n throw illegal(\"comment\");\n }\n prev = curr;\n curr = charAt(offset);\n } while (prev !== \"*\" || curr !== \"/\");\n ++offset;\n if (isDoc) {\n setComment(start, offset - 2, isLeadingComment);\n isLeadingComment = true;\n }\n repeat = true;\n } else {\n return \"/\";\n }\n }\n } while (repeat);\n\n // offset !== length if we got here\n\n var end = offset;\n delimRe.lastIndex = 0;\n var delim = delimRe.test(charAt(end++));\n if (!delim)\n while (end < length && !delimRe.test(charAt(end)))\n ++end;\n var token = source.substring(offset, offset = end);\n if (token === \"\\\"\" || token === \"'\")\n stringDelim = token;\n return token;\n }\n\n /**\n * Pushes a token back to the stack.\n * @param {string} token Token\n * @returns {undefined}\n * @inner\n */\n function push(token) {\n stack.push(token);\n }\n\n /**\n * Peeks for the next token.\n * @returns {string|null} Token or `null` on eof\n * @inner\n */\n function peek() {\n if (!stack.length) {\n var token = next();\n if (token === null)\n return null;\n push(token);\n }\n return stack[0];\n }\n\n /**\n * Skips a token.\n * @param {string} expected Expected token\n * @param {boolean} [optional=false] Whether the token is optional\n * @returns {boolean} `true` when skipped, `false` if not\n * @throws {Error} When a required token is not present\n * @inner\n */\n function skip(expected, optional) {\n var actual = peek(),\n equals = actual === expected;\n if (equals) {\n next();\n return true;\n }\n if (!optional)\n throw illegal(\"token '\" + actual + \"', '\" + expected + \"' expected\");\n return false;\n }\n\n /**\n * Gets a comment.\n * @param {number} [trailingLine] Line number if looking for a trailing comment\n * @returns {string|null} Comment text\n * @inner\n */\n function cmnt(trailingLine) {\n var ret = null;\n var comment;\n if (trailingLine === undefined) {\n comment = comments[line - 1];\n delete comments[line - 1];\n if (comment && (alternateCommentMode || comment.type === \"*\" || comment.lineEmpty)) {\n ret = comment.leading ? comment.text : null;\n }\n } else {\n /* istanbul ignore else */\n if (lastCommentLine < trailingLine) {\n peek();\n }\n comment = comments[trailingLine];\n delete comments[trailingLine];\n if (comment && !comment.lineEmpty && (alternateCommentMode || comment.type === \"/\")) {\n ret = comment.leading ? null : comment.text;\n }\n }\n return ret;\n }\n\n return Object.defineProperty({\n next: next,\n peek: peek,\n push: push,\n skip: skip,\n cmnt: cmnt\n }, \"line\", {\n get: function() { return line; }\n });\n /* eslint-enable callback-return */\n}\n","\"use strict\";\nmodule.exports = Type;\n\n// extends Namespace\nvar Namespace = require(23);\n((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = \"Type\";\n\nvar Enum = require(15),\n OneOf = require(25),\n Field = require(16),\n MapField = require(20),\n Service = require(33),\n Message = require(21),\n Reader = require(27),\n Writer = require(42),\n util = require(37),\n encoder = require(14),\n decoder = require(13),\n verifier = require(40),\n converter = require(12),\n wrappers = require(41);\n\n/**\n * Constructs a new reflected message type instance.\n * @classdesc Reflected message type.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Message name\n * @param {Object.} [options] Declared options\n */\nfunction Type(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Message fields.\n * @type {Object.}\n */\n this.fields = {}; // toJSON, marker\n\n /**\n * Oneofs declared within this namespace, if any.\n * @type {Object.}\n */\n this.oneofs = undefined; // toJSON\n\n /**\n * Extension ranges, if any.\n * @type {number[][]}\n */\n this.extensions = undefined; // toJSON\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n /*?\n * Whether this type is a legacy group.\n * @type {boolean|undefined}\n */\n this.group = undefined; // toJSON\n\n /**\n * Cached fields by id.\n * @type {Object.|null}\n * @private\n */\n this._fieldsById = null;\n\n /**\n * Cached fields as an array.\n * @type {Field[]|null}\n * @private\n */\n this._fieldsArray = null;\n\n /**\n * Cached oneofs as an array.\n * @type {OneOf[]|null}\n * @private\n */\n this._oneofsArray = null;\n\n /**\n * Cached constructor.\n * @type {Constructor<{}>}\n * @private\n */\n this._ctor = null;\n}\n\nObject.defineProperties(Type.prototype, {\n\n /**\n * Message fields by id.\n * @name Type#fieldsById\n * @type {Object.}\n * @readonly\n */\n fieldsById: {\n get: function() {\n\n /* istanbul ignore if */\n if (this._fieldsById)\n return this._fieldsById;\n\n this._fieldsById = {};\n for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {\n var field = this.fields[names[i]],\n id = field.id;\n\n /* istanbul ignore if */\n if (this._fieldsById[id])\n throw Error(\"duplicate id \" + id + \" in \" + this);\n\n this._fieldsById[id] = field;\n }\n return this._fieldsById;\n }\n },\n\n /**\n * Fields of this message as an array for iteration.\n * @name Type#fieldsArray\n * @type {Field[]}\n * @readonly\n */\n fieldsArray: {\n get: function() {\n return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));\n }\n },\n\n /**\n * Oneofs of this message as an array for iteration.\n * @name Type#oneofsArray\n * @type {OneOf[]}\n * @readonly\n */\n oneofsArray: {\n get: function() {\n return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));\n }\n },\n\n /**\n * The registered constructor, if any registered, otherwise a generic constructor.\n * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.\n * @name Type#ctor\n * @type {Constructor<{}>}\n */\n ctor: {\n get: function() {\n return this._ctor || (this.ctor = Type.generateConstructor(this)());\n },\n set: function(ctor) {\n\n // Ensure proper prototype\n var prototype = ctor.prototype;\n if (!(prototype instanceof Message)) {\n (ctor.prototype = new Message()).constructor = ctor;\n util.merge(ctor.prototype, prototype);\n }\n\n // Classes and messages reference their reflected type\n ctor.$type = ctor.prototype.$type = this;\n\n // Mix in static methods\n util.merge(ctor, Message, true);\n\n this._ctor = ctor;\n\n // Messages have non-enumerable default values on their prototype\n var i = 0;\n for (; i < /* initializes */ this.fieldsArray.length; ++i)\n this._fieldsArray[i].resolve(); // ensures a proper value\n\n // Messages have non-enumerable getters and setters for each virtual oneof field\n var ctorProperties = {};\n for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i)\n ctorProperties[this._oneofsArray[i].resolve().name] = {\n get: util.oneOfGetter(this._oneofsArray[i].oneof),\n set: util.oneOfSetter(this._oneofsArray[i].oneof)\n };\n if (i)\n Object.defineProperties(ctor.prototype, ctorProperties);\n }\n }\n});\n\n/**\n * Generates a constructor function for the specified type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nType.generateConstructor = function generateConstructor(mtype) {\n /* eslint-disable no-unexpected-multiline */\n var gen = util.codegen([\"p\"], mtype.name);\n // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype\n for (var i = 0, field; i < mtype.fieldsArray.length; ++i)\n if ((field = mtype._fieldsArray[i]).map) gen\n (\"this%s={}\", util.safeProp(field.name));\n else if (field.repeated) gen\n (\"this%s=[]\", util.safeProp(field.name));\n return gen\n (\"if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors\n * @property {Object.} fields Field descriptors\n * @property {number[][]} [extensions] Extension ranges\n * @property {Array.} [reserved] Reserved ranges\n * @property {boolean} [group=false] Whether a legacy group or not\n */\n\n/**\n * Creates a message type from a message type descriptor.\n * @param {string} name Message name\n * @param {IType} json Message type descriptor\n * @returns {Type} Created message type\n */\nType.fromJSON = function fromJSON(name, json) {\n var type = new Type(name, json.options);\n type.extensions = json.extensions;\n type.reserved = json.reserved;\n var names = Object.keys(json.fields),\n i = 0;\n for (; i < names.length; ++i)\n type.add(\n ( typeof json.fields[names[i]].keyType !== \"undefined\"\n ? MapField.fromJSON\n : Field.fromJSON )(names[i], json.fields[names[i]])\n );\n if (json.oneofs)\n for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i)\n type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]]));\n if (json.nested)\n for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) {\n var nested = json.nested[names[i]];\n type.add( // most to least likely\n ( nested.id !== undefined\n ? Field.fromJSON\n : nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n if (json.extensions && json.extensions.length)\n type.extensions = json.extensions;\n if (json.reserved && json.reserved.length)\n type.reserved = json.reserved;\n if (json.group)\n type.group = true;\n if (json.comment)\n type.comment = json.comment;\n if (json.edition)\n type._edition = json.edition;\n type._defaultEdition = \"proto3\"; // For backwards-compatibility.\n return type;\n};\n\n/**\n * Converts this message type to a message type descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IType} Message type descriptor\n */\nType.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"edition\" , this._editionToJSON(),\n \"options\" , inherited && inherited.options || undefined,\n \"oneofs\" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),\n \"fields\" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {},\n \"extensions\" , this.extensions && this.extensions.length ? this.extensions : undefined,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"group\" , this.group || undefined,\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nType.prototype.resolveAll = function resolveAll() {\n if (!this._needsRecursiveResolve) return this;\n\n Namespace.prototype.resolveAll.call(this);\n var oneofs = this.oneofsArray; i = 0;\n while (i < oneofs.length)\n oneofs[i++].resolve();\n var fields = this.fieldsArray, i = 0;\n while (i < fields.length)\n fields[i++].resolve();\n return this;\n};\n\n/**\n * @override\n */\nType.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) {\n if (!this._needsRecursiveFeatureResolution) return this;\n\n edition = this._edition || edition;\n\n Namespace.prototype._resolveFeaturesRecursive.call(this, edition);\n this.oneofsArray.forEach(oneof => {\n oneof._resolveFeatures(edition);\n });\n this.fieldsArray.forEach(field => {\n field._resolveFeatures(edition);\n });\n return this;\n};\n\n/**\n * @override\n */\nType.prototype.get = function get(name) {\n return this.fields[name]\n || this.oneofs && this.oneofs[name]\n || this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Adds a nested object to this type.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id\n */\nType.prototype.add = function add(object) {\n\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Field && object.extend === undefined) {\n // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.\n // The root object takes care of adding distinct sister-fields to the respective extended\n // type instead.\n\n // avoids calling the getter if not absolutely necessary because it's called quite frequently\n if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id])\n throw Error(\"duplicate id \" + object.id + \" in \" + this);\n if (this.isReservedId(object.id))\n throw Error(\"id \" + object.id + \" is reserved in \" + this);\n if (this.isReservedName(object.name))\n throw Error(\"name '\" + object.name + \"' is reserved in \" + this);\n\n if (object.parent)\n object.parent.remove(object);\n this.fields[object.name] = object;\n object.message = this;\n object.onAdd(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n if (!this.oneofs)\n this.oneofs = {};\n this.oneofs[object.name] = object;\n object.onAdd(this);\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * Removes a nested object from this type.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this type\n */\nType.prototype.remove = function remove(object) {\n if (object instanceof Field && object.extend === undefined) {\n // See Type#add for the reason why extension fields are excluded here.\n\n /* istanbul ignore if */\n if (!this.fields || this.fields[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.fields[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n\n /* istanbul ignore if */\n if (!this.oneofs || this.oneofs[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.oneofs[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message<{}>} Message instance\n */\nType.prototype.create = function create(properties) {\n return new this.ctor(properties);\n};\n\n/**\n * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.\n * @returns {Type} `this`\n */\nType.prototype.setup = function setup() {\n // Sets up everything at once so that the prototype chain does not have to be re-evaluated\n // multiple times (V8, soft-deopt prototype-check).\n\n var fullName = this.fullName,\n types = [];\n for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i)\n types.push(this._fieldsArray[i].resolve().resolvedType);\n\n // Replace setup methods with type-specific generated functions\n this.encode = encoder(this)({\n Writer : Writer,\n types : types,\n util : util\n });\n this.decode = decoder(this)({\n Reader : Reader,\n types : types,\n util : util\n });\n this.verify = verifier(this)({\n types : types,\n util : util\n });\n this.fromObject = converter.fromObject(this)({\n types : types,\n util : util\n });\n this.toObject = converter.toObject(this)({\n types : types,\n util : util\n });\n\n // Inject custom wrappers for common types\n var wrapper = wrappers[fullName];\n if (wrapper) {\n var originalThis = Object.create(this);\n // if (wrapper.fromObject) {\n originalThis.fromObject = this.fromObject;\n this.fromObject = wrapper.fromObject.bind(originalThis);\n // }\n // if (wrapper.toObject) {\n originalThis.toObject = this.toObject;\n this.toObject = wrapper.toObject.bind(originalThis);\n // }\n }\n\n return this;\n};\n\n/**\n * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encode = function encode_setup(message, writer) {\n return this.setup().encode(message, writer); // overrides this method\n};\n\n/**\n * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encodeDelimited = function encodeDelimited(message, writer) {\n return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();\n};\n\n/**\n * Decodes a message of this type.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @param {number} [length] Length of the message, if known beforehand\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError<{}>} If required fields are missing\n */\nType.prototype.decode = function decode_setup(reader, length) {\n return this.setup().decode(reader, length); // overrides this method\n};\n\n/**\n * Decodes a message of this type preceeded by its byte length as a varint.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError} If required fields are missing\n */\nType.prototype.decodeDelimited = function decodeDelimited(reader) {\n if (!(reader instanceof Reader))\n reader = Reader.create(reader);\n return this.decode(reader, reader.uint32());\n};\n\n/**\n * Verifies that field values are valid and that required fields are present.\n * @param {Object.} message Plain object to verify\n * @returns {null|string} `null` if valid, otherwise the reason why it is not\n */\nType.prototype.verify = function verify_setup(message) {\n return this.setup().verify(message); // overrides this method\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object to convert\n * @returns {Message<{}>} Message instance\n */\nType.prototype.fromObject = function fromObject(object) {\n return this.setup().fromObject(object);\n};\n\n/**\n * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}.\n * @interface IConversionOptions\n * @property {Function} [longs] Long conversion type.\n * Valid values are `String` and `Number` (the global types).\n * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.\n * @property {Function} [enums] Enum value conversion type.\n * Only valid value is `String` (the global type).\n * Defaults to copy the present value, which is the numeric id.\n * @property {Function} [bytes] Bytes value conversion type.\n * Valid values are `Array` and (a base64 encoded) `String` (the global types).\n * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.\n * @property {boolean} [defaults=false] Also sets default values on the resulting object\n * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false`\n * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false`\n * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any\n * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings\n */\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n */\nType.prototype.toObject = function toObject(message, options) {\n return this.setup().toObject(message, options);\n};\n\n/**\n * Decorator function as returned by {@link Type.d} (TypeScript).\n * @typedef TypeDecorator\n * @type {function}\n * @param {Constructor} target Target constructor\n * @returns {undefined}\n * @template T extends Message\n */\n\n/**\n * Type decorator (TypeScript).\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {TypeDecorator} Decorator function\n * @template T extends Message\n */\nType.d = function decorateType(typeName) {\n return function typeDecorator(target) {\n util.decorateType(target, typeName);\n };\n};\n","\"use strict\";\n\n/**\n * Common type constants.\n * @namespace\n */\nvar types = exports;\n\nvar util = require(37);\n\nvar s = [\n \"double\", // 0\n \"float\", // 1\n \"int32\", // 2\n \"uint32\", // 3\n \"sint32\", // 4\n \"fixed32\", // 5\n \"sfixed32\", // 6\n \"int64\", // 7\n \"uint64\", // 8\n \"sint64\", // 9\n \"fixed64\", // 10\n \"sfixed64\", // 11\n \"bool\", // 12\n \"string\", // 13\n \"bytes\" // 14\n];\n\nfunction bake(values, offset) {\n var i = 0, o = {};\n offset |= 0;\n while (i < values.length) o[s[i + offset]] = values[i++];\n return o;\n}\n\n/**\n * Basic type wire types.\n * @type {Object.}\n * @const\n * @property {number} double=1 Fixed64 wire type\n * @property {number} float=5 Fixed32 wire type\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n * @property {number} string=2 Ldelim wire type\n * @property {number} bytes=2 Ldelim wire type\n */\ntypes.basic = bake([\n /* double */ 1,\n /* float */ 5,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0,\n /* string */ 2,\n /* bytes */ 2\n]);\n\n/**\n * Basic type defaults.\n * @type {Object.}\n * @const\n * @property {number} double=0 Double default\n * @property {number} float=0 Float default\n * @property {number} int32=0 Int32 default\n * @property {number} uint32=0 Uint32 default\n * @property {number} sint32=0 Sint32 default\n * @property {number} fixed32=0 Fixed32 default\n * @property {number} sfixed32=0 Sfixed32 default\n * @property {number} int64=0 Int64 default\n * @property {number} uint64=0 Uint64 default\n * @property {number} sint64=0 Sint32 default\n * @property {number} fixed64=0 Fixed64 default\n * @property {number} sfixed64=0 Sfixed64 default\n * @property {boolean} bool=false Bool default\n * @property {string} string=\"\" String default\n * @property {Array.} bytes=Array(0) Bytes default\n * @property {null} message=null Message default\n */\ntypes.defaults = bake([\n /* double */ 0,\n /* float */ 0,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 0,\n /* sfixed32 */ 0,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 0,\n /* sfixed64 */ 0,\n /* bool */ false,\n /* string */ \"\",\n /* bytes */ util.emptyArray,\n /* message */ null\n]);\n\n/**\n * Basic long type wire types.\n * @type {Object.}\n * @const\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n */\ntypes.long = bake([\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1\n], 7);\n\n/**\n * Allowed types for map keys with their associated wire type.\n * @type {Object.}\n * @const\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n * @property {number} string=2 Ldelim wire type\n */\ntypes.mapKey = bake([\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0,\n /* string */ 2\n], 2);\n\n/**\n * Allowed types for packed repeated fields with their associated wire type.\n * @type {Object.}\n * @const\n * @property {number} double=1 Fixed64 wire type\n * @property {number} float=5 Fixed32 wire type\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n */\ntypes.packed = bake([\n /* double */ 1,\n /* float */ 5,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0\n]);\n","\"use strict\";\n\n/**\n * Various utility functions.\n * @namespace\n */\nvar util = module.exports = require(39);\n\nvar roots = require(30);\n\nvar Type, // cyclic\n Enum;\n\nutil.codegen = require(3);\nutil.fetch = require(5);\nutil.path = require(8);\n\n/**\n * Node's fs module if available.\n * @type {Object.}\n */\nutil.fs = util.inquire(\"fs\");\n\n/**\n * Converts an object's values to an array.\n * @param {Object.} object Object to convert\n * @returns {Array.<*>} Converted array\n */\nutil.toArray = function toArray(object) {\n if (object) {\n var keys = Object.keys(object),\n array = new Array(keys.length),\n index = 0;\n while (index < keys.length)\n array[index] = object[keys[index++]];\n return array;\n }\n return [];\n};\n\n/**\n * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values.\n * @param {Array.<*>} array Array to convert\n * @returns {Object.} Converted object\n */\nutil.toObject = function toObject(array) {\n var object = {},\n index = 0;\n while (index < array.length) {\n var key = array[index++],\n val = array[index++];\n if (val !== undefined)\n object[key] = val;\n }\n return object;\n};\n\nvar safePropBackslashRe = /\\\\/g,\n safePropQuoteRe = /\"/g;\n\n/**\n * Tests whether the specified name is a reserved word in JS.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nutil.isReserved = function isReserved(name) {\n return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name);\n};\n\n/**\n * Returns a safe property accessor for the specified property name.\n * @param {string} prop Property name\n * @returns {string} Safe accessor\n */\nutil.safeProp = function safeProp(prop) {\n if (!/^[$\\w_]+$/.test(prop) || util.isReserved(prop))\n return \"[\\\"\" + prop.replace(safePropBackslashRe, \"\\\\\\\\\").replace(safePropQuoteRe, \"\\\\\\\"\") + \"\\\"]\";\n return \".\" + prop;\n};\n\n/**\n * Converts the first character of a string to upper case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.ucFirst = function ucFirst(str) {\n return str.charAt(0).toUpperCase() + str.substring(1);\n};\n\nvar camelCaseRe = /_([a-z])/g;\n\n/**\n * Converts a string to camel case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.camelCase = function camelCase(str) {\n return str.substring(0, 1)\n + str.substring(1)\n .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); });\n};\n\n/**\n * Compares reflected fields by id.\n * @param {Field} a First field\n * @param {Field} b Second field\n * @returns {number} Comparison value\n */\nutil.compareFieldsById = function compareFieldsById(a, b) {\n return a.id - b.id;\n};\n\n/**\n * Decorator helper for types (TypeScript).\n * @param {Constructor} ctor Constructor function\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {Type} Reflected type\n * @template T extends Message\n * @property {Root} root Decorators root\n */\nutil.decorateType = function decorateType(ctor, typeName) {\n\n /* istanbul ignore if */\n if (ctor.$type) {\n if (typeName && ctor.$type.name !== typeName) {\n util.decorateRoot.remove(ctor.$type);\n ctor.$type.name = typeName;\n util.decorateRoot.add(ctor.$type);\n }\n return ctor.$type;\n }\n\n /* istanbul ignore next */\n if (!Type)\n Type = require(35);\n\n var type = new Type(typeName || ctor.name);\n util.decorateRoot.add(type);\n type.ctor = ctor; // sets up .encode, .decode etc.\n Object.defineProperty(ctor, \"$type\", { value: type, enumerable: false });\n Object.defineProperty(ctor.prototype, \"$type\", { value: type, enumerable: false });\n return type;\n};\n\nvar decorateEnumIndex = 0;\n\n/**\n * Decorator helper for enums (TypeScript).\n * @param {Object} object Enum object\n * @returns {Enum} Reflected enum\n */\nutil.decorateEnum = function decorateEnum(object) {\n\n /* istanbul ignore if */\n if (object.$type)\n return object.$type;\n\n /* istanbul ignore next */\n if (!Enum)\n Enum = require(15);\n\n var enm = new Enum(\"Enum\" + decorateEnumIndex++, object);\n util.decorateRoot.add(enm);\n Object.defineProperty(object, \"$type\", { value: enm, enumerable: false });\n return enm;\n};\n\n\n/**\n * Sets the value of a property by property path. If a value already exists, it is turned to an array\n * @param {Object.} dst Destination object\n * @param {string} path dot '.' delimited path of the property to set\n * @param {Object} value the value to set\n * @param {boolean|undefined} [ifNotSet] Sets the option only if it isn't currently set\n * @returns {Object.} Destination object\n */\nutil.setProperty = function setProperty(dst, path, value, ifNotSet) {\n function setProp(dst, path, value) {\n var part = path.shift();\n if (part === \"__proto__\" || part === \"prototype\") {\n return dst;\n }\n if (path.length > 0) {\n dst[part] = setProp(dst[part] || {}, path, value);\n } else {\n var prevValue = dst[part];\n if (prevValue && ifNotSet)\n return dst;\n if (prevValue)\n value = [].concat(prevValue).concat(value);\n dst[part] = value;\n }\n return dst;\n }\n\n if (typeof dst !== \"object\")\n throw TypeError(\"dst must be an object\");\n if (!path)\n throw TypeError(\"path must be specified\");\n\n path = path.split(\".\");\n return setProp(dst, path, value);\n};\n\n/**\n * Decorator root (TypeScript).\n * @name util.decorateRoot\n * @type {Root}\n * @readonly\n */\nObject.defineProperty(util, \"decorateRoot\", {\n get: function() {\n return roots[\"decorated\"] || (roots[\"decorated\"] = new (require(29))());\n }\n});\n","\"use strict\";\nmodule.exports = LongBits;\n\nvar util = require(39);\n\n/**\n * Constructs new long bits.\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @constructor\n * @param {number} lo Low 32 bits, unsigned\n * @param {number} hi High 32 bits, unsigned\n */\nfunction LongBits(lo, hi) {\n\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits.\n * @type {number}\n */\n this.lo = lo >>> 0;\n\n /**\n * High bits.\n * @type {number}\n */\n this.hi = hi >>> 0;\n}\n\n/**\n * Zero bits.\n * @memberof util.LongBits\n * @type {util.LongBits}\n */\nvar zero = LongBits.zero = new LongBits(0, 0);\n\nzero.toNumber = function() { return 0; };\nzero.zzEncode = zero.zzDecode = function() { return this; };\nzero.length = function() { return 1; };\n\n/**\n * Zero hash.\n * @memberof util.LongBits\n * @type {string}\n */\nvar zeroHash = LongBits.zeroHash = \"\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n/**\n * Constructs new long bits from the specified number.\n * @param {number} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.fromNumber = function fromNumber(value) {\n if (value === 0)\n return zero;\n var sign = value < 0;\n if (sign)\n value = -value;\n var lo = value >>> 0,\n hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295)\n hi = 0;\n }\n }\n return new LongBits(lo, hi);\n};\n\n/**\n * Constructs new long bits from a number, long or string.\n * @param {Long|number|string} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.from = function from(value) {\n if (typeof value === \"number\")\n return LongBits.fromNumber(value);\n if (util.isString(value)) {\n /* istanbul ignore else */\n if (util.Long)\n value = util.Long.fromString(value);\n else\n return LongBits.fromNumber(parseInt(value, 10));\n }\n return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n};\n\n/**\n * Converts this long bits to a possibly unsafe JavaScript number.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {number} Possibly unsafe number\n */\nLongBits.prototype.toNumber = function toNumber(unsigned) {\n if (!unsigned && this.hi >>> 31) {\n var lo = ~this.lo + 1 >>> 0,\n hi = ~this.hi >>> 0;\n if (!lo)\n hi = hi + 1 >>> 0;\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n};\n\n/**\n * Converts this long bits to a long.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long} Long\n */\nLongBits.prototype.toLong = function toLong(unsigned) {\n return util.Long\n ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))\n /* istanbul ignore next */\n : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };\n};\n\nvar charCodeAt = String.prototype.charCodeAt;\n\n/**\n * Constructs new long bits from the specified 8 characters long hash.\n * @param {string} hash Hash\n * @returns {util.LongBits} Bits\n */\nLongBits.fromHash = function fromHash(hash) {\n if (hash === zeroHash)\n return zero;\n return new LongBits(\n ( charCodeAt.call(hash, 0)\n | charCodeAt.call(hash, 1) << 8\n | charCodeAt.call(hash, 2) << 16\n | charCodeAt.call(hash, 3) << 24) >>> 0\n ,\n ( charCodeAt.call(hash, 4)\n | charCodeAt.call(hash, 5) << 8\n | charCodeAt.call(hash, 6) << 16\n | charCodeAt.call(hash, 7) << 24) >>> 0\n );\n};\n\n/**\n * Converts this long bits to a 8 characters long hash.\n * @returns {string} Hash\n */\nLongBits.prototype.toHash = function toHash() {\n return String.fromCharCode(\n this.lo & 255,\n this.lo >>> 8 & 255,\n this.lo >>> 16 & 255,\n this.lo >>> 24 ,\n this.hi & 255,\n this.hi >>> 8 & 255,\n this.hi >>> 16 & 255,\n this.hi >>> 24\n );\n};\n\n/**\n * Zig-zag encodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzEncode = function zzEncode() {\n var mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = ( this.lo << 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Zig-zag decodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzDecode = function zzDecode() {\n var mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = ( this.hi >>> 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Calculates the length of this longbits when encoded as a varint.\n * @returns {number} Length\n */\nLongBits.prototype.length = function length() {\n var part0 = this.lo,\n part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,\n part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n};\n","\"use strict\";\nvar util = exports;\n\n// used to return a Promise where callback is omitted\nutil.asPromise = require(1);\n\n// converts to / from base64 encoded strings\nutil.base64 = require(2);\n\n// base class of rpc.Service\nutil.EventEmitter = require(4);\n\n// float handling accross browsers\nutil.float = require(6);\n\n// requires modules optionally and hides the call from bundlers\nutil.inquire = require(7);\n\n// converts to / from utf8 encoded strings\nutil.utf8 = require(10);\n\n// provides a node-like buffer pool in the browser\nutil.pool = require(9);\n\n// utility to work with the low and high bits of a 64 bit value\nutil.LongBits = require(38);\n\n/**\n * Whether running within node or not.\n * @memberof util\n * @type {boolean}\n */\nutil.isNode = Boolean(typeof global !== \"undefined\"\n && global\n && global.process\n && global.process.versions\n && global.process.versions.node);\n\n/**\n * Global object reference.\n * @memberof util\n * @type {Object}\n */\nutil.global = util.isNode && global\n || typeof window !== \"undefined\" && window\n || typeof self !== \"undefined\" && self\n || this; // eslint-disable-line no-invalid-this\n\n/**\n * An immuable empty array.\n * @memberof util\n * @type {Array.<*>}\n * @const\n */\nutil.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes\n\n/**\n * An immutable empty object.\n * @type {Object}\n * @const\n */\nutil.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes\n\n/**\n * Tests if the specified value is an integer.\n * @function\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is an integer\n */\nutil.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {\n return typeof value === \"number\" && isFinite(value) && Math.floor(value) === value;\n};\n\n/**\n * Tests if the specified value is a string.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a string\n */\nutil.isString = function isString(value) {\n return typeof value === \"string\" || value instanceof String;\n};\n\n/**\n * Tests if the specified value is a non-null object.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a non-null object\n */\nutil.isObject = function isObject(value) {\n return value && typeof value === \"object\";\n};\n\n/**\n * Checks if a property on a message is considered to be present.\n * This is an alias of {@link util.isSet}.\n * @function\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isset =\n\n/**\n * Checks if a property on a message is considered to be present.\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isSet = function isSet(obj, prop) {\n var value = obj[prop];\n if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins\n return typeof value !== \"object\" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;\n return false;\n};\n\n/**\n * Any compatible Buffer instance.\n * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.\n * @interface Buffer\n * @extends Uint8Array\n */\n\n/**\n * Node's Buffer class if available.\n * @type {Constructor}\n */\nutil.Buffer = (function() {\n try {\n var Buffer = util.inquire(\"buffer\").Buffer;\n // refuse to use non-node buffers if not explicitly assigned (perf reasons):\n return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;\n } catch (e) {\n /* istanbul ignore next */\n return null;\n }\n})();\n\n// Internal alias of or polyfull for Buffer.from.\nutil._Buffer_from = null;\n\n// Internal alias of or polyfill for Buffer.allocUnsafe.\nutil._Buffer_allocUnsafe = null;\n\n/**\n * Creates a new buffer of whatever type supported by the environment.\n * @param {number|number[]} [sizeOrArray=0] Buffer size or number array\n * @returns {Uint8Array|Buffer} Buffer\n */\nutil.newBuffer = function newBuffer(sizeOrArray) {\n /* istanbul ignore next */\n return typeof sizeOrArray === \"number\"\n ? util.Buffer\n ? util._Buffer_allocUnsafe(sizeOrArray)\n : new util.Array(sizeOrArray)\n : util.Buffer\n ? util._Buffer_from(sizeOrArray)\n : typeof Uint8Array === \"undefined\"\n ? sizeOrArray\n : new Uint8Array(sizeOrArray);\n};\n\n/**\n * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.\n * @type {Constructor}\n */\nutil.Array = typeof Uint8Array !== \"undefined\" ? Uint8Array /* istanbul ignore next */ : Array;\n\n/**\n * Any compatible Long instance.\n * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.\n * @interface Long\n * @property {number} low Low bits\n * @property {number} high High bits\n * @property {boolean} unsigned Whether unsigned or not\n */\n\n/**\n * Long.js's Long class if available.\n * @type {Constructor}\n */\nutil.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long\n || /* istanbul ignore next */ util.global.Long\n || util.inquire(\"long\");\n\n/**\n * Regular expression used to verify 2 bit (`bool`) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key2Re = /^true|false|0|1$/;\n\n/**\n * Regular expression used to verify 32 bit (`int32` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key32Re = /^-?(?:0|[1-9][0-9]*)$/;\n\n/**\n * Regular expression used to verify 64 bit (`int64` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key64Re = /^(?:[\\\\x00-\\\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;\n\n/**\n * Converts a number or long to an 8 characters long hash string.\n * @param {Long|number} value Value to convert\n * @returns {string} Hash\n */\nutil.longToHash = function longToHash(value) {\n return value\n ? util.LongBits.from(value).toHash()\n : util.LongBits.zeroHash;\n};\n\n/**\n * Converts an 8 characters long hash string to a long or number.\n * @param {string} hash Hash\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long|number} Original value\n */\nutil.longFromHash = function longFromHash(hash, unsigned) {\n var bits = util.LongBits.fromHash(hash);\n if (util.Long)\n return util.Long.fromBits(bits.lo, bits.hi, unsigned);\n return bits.toNumber(Boolean(unsigned));\n};\n\n/**\n * Merges the properties of the source object into the destination object.\n * @memberof util\n * @param {Object.} dst Destination object\n * @param {Object.} src Source object\n * @param {boolean} [ifNotSet=false] Merges only if the key is not already set\n * @returns {Object.} Destination object\n */\nfunction merge(dst, src, ifNotSet) { // used by converters\n for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)\n if (dst[keys[i]] === undefined || !ifNotSet)\n dst[keys[i]] = src[keys[i]];\n return dst;\n}\n\nutil.merge = merge;\n\n/**\n * Converts the first character of a string to lower case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.lcFirst = function lcFirst(str) {\n return str.charAt(0).toLowerCase() + str.substring(1);\n};\n\n/**\n * Creates a custom error constructor.\n * @memberof util\n * @param {string} name Error name\n * @returns {Constructor} Custom error constructor\n */\nfunction newError(name) {\n\n function CustomError(message, properties) {\n\n if (!(this instanceof CustomError))\n return new CustomError(message, properties);\n\n // Error.call(this, message);\n // ^ just returns a new error instance because the ctor can be called as a function\n\n Object.defineProperty(this, \"message\", { get: function() { return message; } });\n\n /* istanbul ignore next */\n if (Error.captureStackTrace) // node\n Error.captureStackTrace(this, CustomError);\n else\n Object.defineProperty(this, \"stack\", { value: new Error().stack || \"\" });\n\n if (properties)\n merge(this, properties);\n }\n\n CustomError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: CustomError,\n writable: true,\n enumerable: false,\n configurable: true,\n },\n name: {\n get: function get() { return name; },\n set: undefined,\n enumerable: false,\n // configurable: false would accurately preserve the behavior of\n // the original, but I'm guessing that was not intentional.\n // For an actual error subclass, this property would\n // be configurable.\n configurable: true,\n },\n toString: {\n value: function value() { return this.name + \": \" + this.message; },\n writable: true,\n enumerable: false,\n configurable: true,\n },\n });\n\n return CustomError;\n}\n\nutil.newError = newError;\n\n/**\n * Constructs a new protocol error.\n * @classdesc Error subclass indicating a protocol specifc error.\n * @memberof util\n * @extends Error\n * @template T extends Message\n * @constructor\n * @param {string} message Error message\n * @param {Object.} [properties] Additional properties\n * @example\n * try {\n * MyMessage.decode(someBuffer); // throws if required fields are missing\n * } catch (e) {\n * if (e instanceof ProtocolError && e.instance)\n * console.log(\"decoded so far: \" + JSON.stringify(e.instance));\n * }\n */\nutil.ProtocolError = newError(\"ProtocolError\");\n\n/**\n * So far decoded message instance.\n * @name util.ProtocolError#instance\n * @type {Message}\n */\n\n/**\n * A OneOf getter as returned by {@link util.oneOfGetter}.\n * @typedef OneOfGetter\n * @type {function}\n * @returns {string|undefined} Set field name, if any\n */\n\n/**\n * Builds a getter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfGetter} Unbound getter\n */\nutil.oneOfGetter = function getOneOf(fieldNames) {\n var fieldMap = {};\n for (var i = 0; i < fieldNames.length; ++i)\n fieldMap[fieldNames[i]] = 1;\n\n /**\n * @returns {string|undefined} Set field name, if any\n * @this Object\n * @ignore\n */\n return function() { // eslint-disable-line consistent-return\n for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)\n if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)\n return keys[i];\n };\n};\n\n/**\n * A OneOf setter as returned by {@link util.oneOfSetter}.\n * @typedef OneOfSetter\n * @type {function}\n * @param {string|undefined} value Field name\n * @returns {undefined}\n */\n\n/**\n * Builds a setter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfSetter} Unbound setter\n */\nutil.oneOfSetter = function setOneOf(fieldNames) {\n\n /**\n * @param {string} name Field name\n * @returns {undefined}\n * @this Object\n * @ignore\n */\n return function(name) {\n for (var i = 0; i < fieldNames.length; ++i)\n if (fieldNames[i] !== name)\n delete this[fieldNames[i]];\n };\n};\n\n/**\n * Default conversion options used for {@link Message#toJSON} implementations.\n *\n * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:\n *\n * - Longs become strings\n * - Enums become string keys\n * - Bytes become base64 encoded strings\n * - (Sub-)Messages become plain objects\n * - Maps become plain objects with all string keys\n * - Repeated fields become arrays\n * - NaN and Infinity for float and double fields become strings\n *\n * @type {IConversionOptions}\n * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json\n */\nutil.toJSONOptions = {\n longs: String,\n enums: String,\n bytes: String,\n json: true\n};\n\n// Sets up buffer utility according to the environment (called in index-minimal)\nutil._configure = function() {\n var Buffer = util.Buffer;\n /* istanbul ignore if */\n if (!Buffer) {\n util._Buffer_from = util._Buffer_allocUnsafe = null;\n return;\n }\n // because node 4.x buffers are incompatible & immutable\n // see: https://github.com/dcodeIO/protobuf.js/pull/665\n util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||\n /* istanbul ignore next */\n function Buffer_from(value, encoding) {\n return new Buffer(value, encoding);\n };\n util._Buffer_allocUnsafe = Buffer.allocUnsafe ||\n /* istanbul ignore next */\n function Buffer_allocUnsafe(size) {\n return new Buffer(size);\n };\n};\n","\"use strict\";\nmodule.exports = verifier;\n\nvar Enum = require(15),\n util = require(37);\n\nfunction invalid(field, expected) {\n return field.name + \": \" + expected + (field.repeated && expected !== \"array\" ? \"[]\" : field.map && expected !== \"object\" ? \"{k:\"+field.keyType+\"}\" : \"\") + \" expected\";\n}\n\n/**\n * Generates a partial value verifier.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {number} fieldIndex Field index\n * @param {string} ref Variable reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genVerifyValue(gen, field, fieldIndex, ref) {\n /* eslint-disable no-unexpected-multiline */\n if (field.resolvedType) {\n if (field.resolvedType instanceof Enum) { gen\n (\"switch(%s){\", ref)\n (\"default:\")\n (\"return%j\", invalid(field, \"enum value\"));\n for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen\n (\"case %i:\", field.resolvedType.values[keys[j]]);\n gen\n (\"break\")\n (\"}\");\n } else {\n gen\n (\"{\")\n (\"var e=types[%i].verify(%s);\", fieldIndex, ref)\n (\"if(e)\")\n (\"return%j+e\", field.name + \".\")\n (\"}\");\n }\n } else {\n switch (field.type) {\n case \"int32\":\n case \"uint32\":\n case \"sint32\":\n case \"fixed32\":\n case \"sfixed32\": gen\n (\"if(!util.isInteger(%s))\", ref)\n (\"return%j\", invalid(field, \"integer\"));\n break;\n case \"int64\":\n case \"uint64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))\", ref, ref, ref, ref)\n (\"return%j\", invalid(field, \"integer|Long\"));\n break;\n case \"float\":\n case \"double\": gen\n (\"if(typeof %s!==\\\"number\\\")\", ref)\n (\"return%j\", invalid(field, \"number\"));\n break;\n case \"bool\": gen\n (\"if(typeof %s!==\\\"boolean\\\")\", ref)\n (\"return%j\", invalid(field, \"boolean\"));\n break;\n case \"string\": gen\n (\"if(!util.isString(%s))\", ref)\n (\"return%j\", invalid(field, \"string\"));\n break;\n case \"bytes\": gen\n (\"if(!(%s&&typeof %s.length===\\\"number\\\"||util.isString(%s)))\", ref, ref, ref)\n (\"return%j\", invalid(field, \"buffer\"));\n break;\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline */\n}\n\n/**\n * Generates a partial key verifier.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {string} ref Variable reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genVerifyKey(gen, field, ref) {\n /* eslint-disable no-unexpected-multiline */\n switch (field.keyType) {\n case \"int32\":\n case \"uint32\":\n case \"sint32\":\n case \"fixed32\":\n case \"sfixed32\": gen\n (\"if(!util.key32Re.test(%s))\", ref)\n (\"return%j\", invalid(field, \"integer key\"));\n break;\n case \"int64\":\n case \"uint64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(!util.key64Re.test(%s))\", ref) // see comment above: x is ok, d is not\n (\"return%j\", invalid(field, \"integer|Long key\"));\n break;\n case \"bool\": gen\n (\"if(!util.key2Re.test(%s))\", ref)\n (\"return%j\", invalid(field, \"boolean key\"));\n break;\n }\n return gen;\n /* eslint-enable no-unexpected-multiline */\n}\n\n/**\n * Generates a verifier specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nfunction verifier(mtype) {\n /* eslint-disable no-unexpected-multiline */\n\n var gen = util.codegen([\"m\"], mtype.name + \"$verify\")\n (\"if(typeof m!==\\\"object\\\"||m===null)\")\n (\"return%j\", \"object expected\");\n var oneofs = mtype.oneofsArray,\n seenFirstField = {};\n if (oneofs.length) gen\n (\"var p={}\");\n\n for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {\n var field = mtype._fieldsArray[i].resolve(),\n ref = \"m\" + util.safeProp(field.name);\n\n if (field.optional) gen\n (\"if(%s!=null&&m.hasOwnProperty(%j)){\", ref, field.name); // !== undefined && !== null\n\n // map fields\n if (field.map) { gen\n (\"if(!util.isObject(%s))\", ref)\n (\"return%j\", invalid(field, \"object\"))\n (\"var k=Object.keys(%s)\", ref)\n (\"for(var i=0;i}\n * @const\n */\nvar wrappers = exports;\n\nvar Message = require(21);\n\n/**\n * From object converter part of an {@link IWrapper}.\n * @typedef WrapperFromObjectConverter\n * @type {function}\n * @param {Object.} object Plain object\n * @returns {Message<{}>} Message instance\n * @this Type\n */\n\n/**\n * To object converter part of an {@link IWrapper}.\n * @typedef WrapperToObjectConverter\n * @type {function}\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n * @this Type\n */\n\n/**\n * Common type wrapper part of {@link wrappers}.\n * @interface IWrapper\n * @property {WrapperFromObjectConverter} [fromObject] From object converter\n * @property {WrapperToObjectConverter} [toObject] To object converter\n */\n\n// Custom wrapper for Any\nwrappers[\".google.protobuf.Any\"] = {\n\n fromObject: function(object) {\n\n // unwrap value type if mapped\n if (object && object[\"@type\"]) {\n // Only use fully qualified type name after the last '/'\n var name = object[\"@type\"].substring(object[\"@type\"].lastIndexOf(\"/\") + 1);\n var type = this.lookup(name);\n /* istanbul ignore else */\n if (type) {\n // type_url does not accept leading \".\"\n var type_url = object[\"@type\"].charAt(0) === \".\" ?\n object[\"@type\"].slice(1) : object[\"@type\"];\n // type_url prefix is optional, but path seperator is required\n if (type_url.indexOf(\"/\") === -1) {\n type_url = \"/\" + type_url;\n }\n return this.create({\n type_url: type_url,\n value: type.encode(type.fromObject(object)).finish()\n });\n }\n }\n\n return this.fromObject(object);\n },\n\n toObject: function(message, options) {\n\n // Default prefix\n var googleApi = \"type.googleapis.com/\";\n var prefix = \"\";\n var name = \"\";\n\n // decode value if requested and unmapped\n if (options && options.json && message.type_url && message.value) {\n // Only use fully qualified type name after the last '/'\n name = message.type_url.substring(message.type_url.lastIndexOf(\"/\") + 1);\n // Separate the prefix used\n prefix = message.type_url.substring(0, message.type_url.lastIndexOf(\"/\") + 1);\n var type = this.lookup(name);\n /* istanbul ignore else */\n if (type)\n message = type.decode(message.value);\n }\n\n // wrap value if unmapped\n if (!(message instanceof this.ctor) && message instanceof Message) {\n var object = message.$type.toObject(message, options);\n var messageName = message.$type.fullName[0] === \".\" ?\n message.$type.fullName.slice(1) : message.$type.fullName;\n // Default to type.googleapis.com prefix if no prefix is used\n if (prefix === \"\") {\n prefix = googleApi;\n }\n name = prefix + messageName;\n object[\"@type\"] = name;\n return object;\n }\n\n return this.toObject(message, options);\n }\n};\n","\"use strict\";\nmodule.exports = Writer;\n\nvar util = require(39);\n\nvar BufferWriter; // cyclic\n\nvar LongBits = util.LongBits,\n base64 = util.base64,\n utf8 = util.utf8;\n\n/**\n * Constructs a new writer operation instance.\n * @classdesc Scheduled writer operation.\n * @constructor\n * @param {function(*, Uint8Array, number)} fn Function to call\n * @param {number} len Value byte length\n * @param {*} val Value to write\n * @ignore\n */\nfunction Op(fn, len, val) {\n\n /**\n * Function to call.\n * @type {function(Uint8Array, number, *)}\n */\n this.fn = fn;\n\n /**\n * Value byte length.\n * @type {number}\n */\n this.len = len;\n\n /**\n * Next operation.\n * @type {Writer.Op|undefined}\n */\n this.next = undefined;\n\n /**\n * Value to write.\n * @type {*}\n */\n this.val = val; // type varies\n}\n\n/* istanbul ignore next */\nfunction noop() {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance.\n * @classdesc Copied writer state.\n * @memberof Writer\n * @constructor\n * @param {Writer} writer Writer to copy state from\n * @ignore\n */\nfunction State(writer) {\n\n /**\n * Current head.\n * @type {Writer.Op}\n */\n this.head = writer.head;\n\n /**\n * Current tail.\n * @type {Writer.Op}\n */\n this.tail = writer.tail;\n\n /**\n * Current buffer length.\n * @type {number}\n */\n this.len = writer.len;\n\n /**\n * Next state.\n * @type {State|null}\n */\n this.next = writer.states;\n}\n\n/**\n * Constructs a new writer instance.\n * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n */\nfunction Writer() {\n\n /**\n * Current length.\n * @type {number}\n */\n this.len = 0;\n\n /**\n * Operations head.\n * @type {Object}\n */\n this.head = new Op(noop, 0, 0);\n\n /**\n * Operations tail\n * @type {Object}\n */\n this.tail = this.head;\n\n /**\n * Linked forked states.\n * @type {Object|null}\n */\n this.states = null;\n\n // When a value is written, the writer calculates its byte length and puts it into a linked\n // list of operations to perform when finish() is called. This both allows us to allocate\n // buffers of the exact required size and reduces the amount of work we have to do compared\n // to first calculating over objects and then encoding over objects. In our case, the encoding\n // part is just a linked list walk calling operations with already prepared values.\n}\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup() {\n return (Writer.create = function create_buffer() {\n return new BufferWriter();\n })();\n }\n /* istanbul ignore next */\n : function create_array() {\n return new Writer();\n };\n};\n\n/**\n * Creates a new writer.\n * @function\n * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}\n */\nWriter.create = create();\n\n/**\n * Allocates a buffer of the specified size.\n * @param {number} size Buffer size\n * @returns {Uint8Array} Buffer\n */\nWriter.alloc = function alloc(size) {\n return new util.Array(size);\n};\n\n// Use Uint8Array buffer pool in the browser, just like node does with buffers\n/* istanbul ignore else */\nif (util.Array !== Array)\n Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);\n\n/**\n * Pushes a new operation to the queue.\n * @param {function(Uint8Array, number, *)} fn Function to call\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @returns {Writer} `this`\n * @private\n */\nWriter.prototype._push = function push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n};\n\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\n\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n\n/**\n * Constructs a new varint writer operation instance.\n * @classdesc Scheduled varint writer operation.\n * @extends Op\n * @constructor\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @ignore\n */\nfunction VarintOp(len, val) {\n this.len = len;\n this.next = undefined;\n this.val = val;\n}\n\nVarintOp.prototype = Object.create(Op.prototype);\nVarintOp.prototype.fn = writeVarint32;\n\n/**\n * Writes an unsigned 32 bit value as a varint.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.uint32 = function write_uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0)\n < 128 ? 1\n : value < 16384 ? 2\n : value < 2097152 ? 3\n : value < 268435456 ? 4\n : 5,\n value)).len;\n return this;\n};\n\n/**\n * Writes a signed 32 bit value as a varint.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.int32 = function write_int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n};\n\n/**\n * Writes a 32 bit value as a varint, zig-zag encoded.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sint32 = function write_sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n};\n\nfunction writeVarint64(val, buf, pos) {\n while (val.hi) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\n\n/**\n * Writes an unsigned 64 bit value as a varint.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.uint64 = function write_uint64(value) {\n var bits = LongBits.from(value);\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a signed 64 bit value as a varint.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.int64 = Writer.prototype.uint64;\n\n/**\n * Writes a signed 64 bit value as a varint, zig-zag encoded.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sint64 = function write_sint64(value) {\n var bits = LongBits.from(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a boolish value as a varint.\n * @param {boolean} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bool = function write_bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n};\n\nfunction writeFixed32(val, buf, pos) {\n buf[pos ] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\n\n/**\n * Writes an unsigned 32 bit value as fixed 32 bits.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.fixed32 = function write_fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n};\n\n/**\n * Writes a signed 32 bit value as fixed 32 bits.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sfixed32 = Writer.prototype.fixed32;\n\n/**\n * Writes an unsigned 64 bit value as fixed 64 bits.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.fixed64 = function write_fixed64(value) {\n var bits = LongBits.from(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n};\n\n/**\n * Writes a signed 64 bit value as fixed 64 bits.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sfixed64 = Writer.prototype.fixed64;\n\n/**\n * Writes a float (32 bit).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.float = function write_float(value) {\n return this._push(util.float.writeFloatLE, 4, value);\n};\n\n/**\n * Writes a double (64 bit float).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.double = function write_double(value) {\n return this._push(util.float.writeDoubleLE, 8, value);\n};\n\nvar writeBytes = util.Array.prototype.set\n ? function writeBytes_set(val, buf, pos) {\n buf.set(val, pos); // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytes_for(val, buf, pos) {\n for (var i = 0; i < val.length; ++i)\n buf[pos + i] = val[i];\n };\n\n/**\n * Writes a sequence of bytes.\n * @param {Uint8Array|string} value Buffer or base64 encoded string to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bytes = function write_bytes(value) {\n var len = value.length >>> 0;\n if (!len)\n return this._push(writeByte, 1, 0);\n if (util.isString(value)) {\n var buf = Writer.alloc(len = base64.length(value));\n base64.decode(value, buf, 0);\n value = buf;\n }\n return this.uint32(len)._push(writeBytes, len, value);\n};\n\n/**\n * Writes a string.\n * @param {string} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.string = function write_string(value) {\n var len = utf8.length(value);\n return len\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0);\n};\n\n/**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n * @returns {Writer} `this`\n */\nWriter.prototype.fork = function fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n};\n\n/**\n * Resets this instance to the last state.\n * @returns {Writer} `this`\n */\nWriter.prototype.reset = function reset() {\n if (this.states) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n } else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n};\n\n/**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n * @returns {Writer} `this`\n */\nWriter.prototype.ldelim = function ldelim() {\n var head = this.head,\n tail = this.tail,\n len = this.len;\n this.reset().uint32(len);\n if (len) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n};\n\n/**\n * Finishes the write operation.\n * @returns {Uint8Array} Finished buffer\n */\nWriter.prototype.finish = function finish() {\n var head = this.head.next, // skip noop\n buf = this.constructor.alloc(this.len),\n pos = 0;\n while (head) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n};\n\nWriter._configure = function(BufferWriter_) {\n BufferWriter = BufferWriter_;\n Writer.create = create();\n BufferWriter._configure();\n};\n","\"use strict\";\nmodule.exports = BufferWriter;\n\n// extends Writer\nvar Writer = require(42);\n(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;\n\nvar util = require(39);\n\n/**\n * Constructs a new buffer writer instance.\n * @classdesc Wire format writer using node buffers.\n * @extends Writer\n * @constructor\n */\nfunction BufferWriter() {\n Writer.call(this);\n}\n\nBufferWriter._configure = function () {\n /**\n * Allocates a buffer of the specified size.\n * @function\n * @param {number} size Buffer size\n * @returns {Buffer} Buffer\n */\n BufferWriter.alloc = util._Buffer_allocUnsafe;\n\n BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === \"set\"\n ? function writeBytesBuffer_set(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytesBuffer_copy(val, buf, pos) {\n if (val.copy) // Buffer values\n val.copy(buf, pos, 0, val.length);\n else for (var i = 0; i < val.length;) // plain array values\n buf[pos++] = val[i++];\n };\n};\n\n\n/**\n * @override\n */\nBufferWriter.prototype.bytes = function write_bytes_buffer(value) {\n if (util.isString(value))\n value = util._Buffer_from(value, \"base64\");\n var len = value.length >>> 0;\n this.uint32(len);\n if (len)\n this._push(BufferWriter.writeBytesBuffer, len, value);\n return this;\n};\n\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)\n util.utf8.write(val, buf, pos);\n else if (buf.utf8Write)\n buf.utf8Write(val, pos);\n else\n buf.write(val, pos);\n}\n\n/**\n * @override\n */\nBufferWriter.prototype.string = function write_string_buffer(value) {\n var len = util.Buffer.byteLength(value);\n this.uint32(len);\n if (len)\n this._push(writeStringBuffer, len, value);\n return this;\n};\n\n\n/**\n * Finishes the write operation.\n * @name BufferWriter#finish\n * @function\n * @returns {Buffer} Finished buffer\n */\n\nBufferWriter._configure();\n"],"sourceRoot":"."} \ No newline at end of file diff --git a/node_modules/protobufjs/ext/debug/README.md b/node_modules/protobufjs/ext/debug/README.md new file mode 100644 index 0000000..a48517e --- /dev/null +++ b/node_modules/protobufjs/ext/debug/README.md @@ -0,0 +1,4 @@ +protobufjs/ext/debug +========================= + +Experimental debugging extension. diff --git a/node_modules/protobufjs/ext/debug/index.js b/node_modules/protobufjs/ext/debug/index.js new file mode 100644 index 0000000..2b79766 --- /dev/null +++ b/node_modules/protobufjs/ext/debug/index.js @@ -0,0 +1,71 @@ +"use strict"; +var protobuf = require("../.."); + +/** + * Debugging utility functions. Only present in debug builds. + * @namespace + */ +var debug = protobuf.debug = module.exports = {}; + +var codegen = protobuf.util.codegen; + +var debugFnRe = /function ([^(]+)\(([^)]*)\) {/g; + +// Counts number of calls to any generated function +function codegen_debug() { + codegen_debug.supported = codegen.supported; + codegen_debug.verbose = codegen.verbose; + var gen = codegen.apply(null, Array.prototype.slice.call(arguments)); + gen.str = (function(str) { return function str_debug() { + return str.apply(null, Array.prototype.slice.call(arguments)).replace(debugFnRe, "function $1($2) {\n\t$1.calls=($1.calls|0)+1"); + };})(gen.str); + return gen; +} + +/** + * Returns a list of unused types within the specified root. + * @param {NamespaceBase} ns Namespace to search + * @returns {Type[]} Unused types + */ +debug.unusedTypes = function unusedTypes(ns) { + + /* istanbul ignore if */ + if (!(ns instanceof protobuf.Namespace)) + throw TypeError("ns must be a Namespace"); + + /* istanbul ignore if */ + if (!ns.nested) + return []; + + var unused = []; + for (var names = Object.keys(ns.nested), i = 0; i < names.length; ++i) { + var nested = ns.nested[names[i]]; + if (nested instanceof protobuf.Type) { + var calls = (nested.encode.calls|0) + + (nested.decode.calls|0) + + (nested.verify.calls|0) + + (nested.toObject.calls|0) + + (nested.fromObject.calls|0); + if (!calls) + unused.push(nested); + } else if (nested instanceof protobuf.Namespace) + Array.prototype.push.apply(unused, unusedTypes(nested)); + } + return unused; +}; + +/** + * Enables debugging extensions. + * @returns {undefined} + */ +debug.enable = function enable() { + protobuf.util.codegen = codegen_debug; +}; + +/** + * Disables debugging extensions. + * @returns {undefined} + */ +debug.disable = function disable() { + protobuf.util.codegen = codegen; +}; diff --git a/node_modules/protobufjs/ext/descriptor/README.md b/node_modules/protobufjs/ext/descriptor/README.md new file mode 100644 index 0000000..3bc4c6c --- /dev/null +++ b/node_modules/protobufjs/ext/descriptor/README.md @@ -0,0 +1,72 @@ +protobufjs/ext/descriptor +========================= + +Experimental extension for interoperability with [descriptor.proto](https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto) types. + +Usage +----- + +```js +var protobuf = require("protobufjs"), // requires the full library + descriptor = require("protobufjs/ext/descriptor"); + +var root = ...; + +// convert any existing root instance to the corresponding descriptor type +var descriptorMsg = root.toDescriptor("proto2"); +// ^ returns a FileDescriptorSet message, see table below + +// encode to a descriptor buffer +var buffer = descriptor.FileDescriptorSet.encode(descriptorMsg).finish(); + +// decode from a descriptor buffer +var decodedDescriptor = descriptor.FileDescriptorSet.decode(buffer); + +// convert any existing descriptor to a root instance +root = protobuf.Root.fromDescriptor(decodedDescriptor); +// ^ expects a FileDescriptorSet message or buffer, see table below + +// and start all over again +``` + +API +--- + +The extension adds `.fromDescriptor(descriptor[, syntax])` and `#toDescriptor([syntax])` methods to reflection objects and exports the `.google.protobuf` namespace of the internally used `Root` instance containing the following types present in descriptor.proto: + +| Descriptor type | protobuf.js type | Remarks +|-------------------------------|------------------|--------- +| **FileDescriptorSet** | Root | +| FileDescriptorProto | | dependencies are not supported +| FileOptions | | +| FileOptionsOptimizeMode | | +| SourceCodeInfo | | not supported +| SourceCodeInfoLocation | | +| GeneratedCodeInfo | | not supported +| GeneratedCodeInfoAnnotation | | +| **DescriptorProto** | Type | +| MessageOptions | | +| DescriptorProtoExtensionRange | | +| DescriptorProtoReservedRange | | +| **FieldDescriptorProto** | Field | +| FieldDescriptorProtoLabel | | +| FieldDescriptorProtoType | | +| FieldOptions | | +| FieldOptionsCType | | +| FieldOptionsJSType | | +| **OneofDescriptorProto** | OneOf | +| OneofOptions | | +| **EnumDescriptorProto** | Enum | +| EnumOptions | | +| EnumValueDescriptorProto | | +| EnumValueOptions | | not supported +| **ServiceDescriptorProto** | Service | +| ServiceOptions | | +| **MethodDescriptorProto** | Method | +| MethodOptions | | +| UninterpretedOption | | not supported +| UninterpretedOptionNamePart | | + +Note that not all features of descriptor.proto translate perfectly to a protobuf.js root instance. A root instance has only limited knowlege of packages or individual files for example, which is then compensated by guessing and generating fictional file names. + +When using TypeScript, the respective interface types can be used to reference specific message instances (i.e. `protobuf.Message`). diff --git a/node_modules/protobufjs/ext/descriptor/index.d.ts b/node_modules/protobufjs/ext/descriptor/index.d.ts new file mode 100644 index 0000000..1df2efc --- /dev/null +++ b/node_modules/protobufjs/ext/descriptor/index.d.ts @@ -0,0 +1,191 @@ +import * as $protobuf from "../.."; +export const FileDescriptorSet: $protobuf.Type; + +export const FileDescriptorProto: $protobuf.Type; + +export const DescriptorProto: $protobuf.Type & { + ExtensionRange: $protobuf.Type, + ReservedRange: $protobuf.Type +}; + +export const FieldDescriptorProto: $protobuf.Type & { + Label: $protobuf.Enum, + Type: $protobuf.Enum +}; + +export const OneofDescriptorProto: $protobuf.Type; + +export const EnumDescriptorProto: $protobuf.Type; + +export const ServiceDescriptorProto: $protobuf.Type; + +export const EnumValueDescriptorProto: $protobuf.Type; + +export const MethodDescriptorProto: $protobuf.Type; + +export const FileOptions: $protobuf.Type & { + OptimizeMode: $protobuf.Enum +}; + +export const MessageOptions: $protobuf.Type; + +export const FieldOptions: $protobuf.Type & { + CType: $protobuf.Enum, + JSType: $protobuf.Enum +}; + +export const OneofOptions: $protobuf.Type; + +export const EnumOptions: $protobuf.Type; + +export const EnumValueOptions: $protobuf.Type; + +export const ServiceOptions: $protobuf.Type; + +export const MethodOptions: $protobuf.Type; + +export const UninterpretedOption: $protobuf.Type & { + NamePart: $protobuf.Type +}; + +export const SourceCodeInfo: $protobuf.Type & { + Location: $protobuf.Type +}; + +export const GeneratedCodeInfo: $protobuf.Type & { + Annotation: $protobuf.Type +}; + +export interface IFileDescriptorSet { + file: IFileDescriptorProto[]; +} + +export interface IFileDescriptorProto { + name?: string; + package?: string; + dependency?: any; + publicDependency?: any; + weakDependency?: any; + messageType?: IDescriptorProto[]; + enumType?: IEnumDescriptorProto[]; + service?: IServiceDescriptorProto[]; + extension?: IFieldDescriptorProto[]; + options?: IFileOptions; + sourceCodeInfo?: any; + syntax?: string; +} + +export interface IFileOptions { + javaPackage?: string; + javaOuterClassname?: string; + javaMultipleFiles?: boolean; + javaGenerateEqualsAndHash?: boolean; + javaStringCheckUtf8?: boolean; + optimizeFor?: IFileOptionsOptimizeMode; + goPackage?: string; + ccGenericServices?: boolean; + javaGenericServices?: boolean; + pyGenericServices?: boolean; + deprecated?: boolean; + ccEnableArenas?: boolean; + objcClassPrefix?: string; + csharpNamespace?: string; +} + +type IFileOptionsOptimizeMode = number; + +export interface IDescriptorProto { + name?: string; + field?: IFieldDescriptorProto[]; + extension?: IFieldDescriptorProto[]; + nestedType?: IDescriptorProto[]; + enumType?: IEnumDescriptorProto[]; + extensionRange?: IDescriptorProtoExtensionRange[]; + oneofDecl?: IOneofDescriptorProto[]; + options?: IMessageOptions; + reservedRange?: IDescriptorProtoReservedRange[]; + reservedName?: string[]; +} + +export interface IMessageOptions { + mapEntry?: boolean; +} + +export interface IDescriptorProtoExtensionRange { + start?: number; + end?: number; +} + +export interface IDescriptorProtoReservedRange { + start?: number; + end?: number; +} + +export interface IFieldDescriptorProto { + name?: string; + number?: number; + label?: IFieldDescriptorProtoLabel; + type?: IFieldDescriptorProtoType; + typeName?: string; + extendee?: string; + defaultValue?: string; + oneofIndex?: number; + jsonName?: any; + options?: IFieldOptions; +} + +type IFieldDescriptorProtoLabel = number; + +type IFieldDescriptorProtoType = number; + +export interface IFieldOptions { + packed?: boolean; + jstype?: IFieldOptionsJSType; +} + +type IFieldOptionsJSType = number; + +export interface IEnumDescriptorProto { + name?: string; + value?: IEnumValueDescriptorProto[]; + options?: IEnumOptions; +} + +export interface IEnumValueDescriptorProto { + name?: string; + number?: number; + options?: any; +} + +export interface IEnumOptions { + allowAlias?: boolean; + deprecated?: boolean; +} + +export interface IOneofDescriptorProto { + name?: string; + options?: any; +} + +export interface IServiceDescriptorProto { + name?: string; + method?: IMethodDescriptorProto[]; + options?: IServiceOptions; +} + +export interface IServiceOptions { + deprecated?: boolean; +} + +export interface IMethodDescriptorProto { + name?: string; + inputType?: string; + outputType?: string; + options?: IMethodOptions; + clientStreaming?: boolean; + serverStreaming?: boolean; +} + +export interface IMethodOptions { + deprecated?: boolean; +} diff --git a/node_modules/protobufjs/ext/descriptor/index.js b/node_modules/protobufjs/ext/descriptor/index.js new file mode 100644 index 0000000..77ba8d2 --- /dev/null +++ b/node_modules/protobufjs/ext/descriptor/index.js @@ -0,0 +1,1162 @@ +"use strict"; +var $protobuf = require("../.."); +module.exports = exports = $protobuf.descriptor = $protobuf.Root.fromJSON(require("../../google/protobuf/descriptor.json")).lookup(".google.protobuf"); + +var Namespace = $protobuf.Namespace, + Root = $protobuf.Root, + Enum = $protobuf.Enum, + Type = $protobuf.Type, + Field = $protobuf.Field, + MapField = $protobuf.MapField, + OneOf = $protobuf.OneOf, + Service = $protobuf.Service, + Method = $protobuf.Method; + +// --- Root --- + +/** + * Properties of a FileDescriptorSet message. + * @interface IFileDescriptorSet + * @property {IFileDescriptorProto[]} file Files + */ + +/** + * Properties of a FileDescriptorProto message. + * @interface IFileDescriptorProto + * @property {string} [name] File name + * @property {string} [package] Package + * @property {*} [dependency] Not supported + * @property {*} [publicDependency] Not supported + * @property {*} [weakDependency] Not supported + * @property {IDescriptorProto[]} [messageType] Nested message types + * @property {IEnumDescriptorProto[]} [enumType] Nested enums + * @property {IServiceDescriptorProto[]} [service] Nested services + * @property {IFieldDescriptorProto[]} [extension] Nested extension fields + * @property {IFileOptions} [options] Options + * @property {*} [sourceCodeInfo] Not supported + * @property {string} [syntax="proto2"] Syntax + * @property {IEdition} [edition] Edition + */ + +/** + * Values of the Edition enum. + * @typedef IEdition + * @type {number} + * @property {number} EDITION_UNKNOWN=0 + * @property {number} EDITION_LEGACY=900 + * @property {number} EDITION_PROTO2=998 + * @property {number} EDITION_PROTO3=999 + * @property {number} EDITION_2023=1000 + * @property {number} EDITION_2024=1001 + * @property {number} EDITION_1_TEST_ONLY=1 + * @property {number} EDITION_2_TEST_ONLY=2 + * @property {number} EDITION_99997_TEST_ONLY=99997 + * @property {number} EDITION_99998_TEST_ONLY=99998 + * @property {number} EDITION_99998_TEST_ONLY=99999 + * @property {number} EDITION_MAX=2147483647 + */ + +/** + * Properties of a FileOptions message. + * @interface IFileOptions + * @property {string} [javaPackage] + * @property {string} [javaOuterClassname] + * @property {boolean} [javaMultipleFiles] + * @property {boolean} [javaGenerateEqualsAndHash] + * @property {boolean} [javaStringCheckUtf8] + * @property {IFileOptionsOptimizeMode} [optimizeFor=1] + * @property {string} [goPackage] + * @property {boolean} [ccGenericServices] + * @property {boolean} [javaGenericServices] + * @property {boolean} [pyGenericServices] + * @property {boolean} [deprecated] + * @property {boolean} [ccEnableArenas] + * @property {string} [objcClassPrefix] + * @property {string} [csharpNamespace] + */ + +/** + * Values of he FileOptions.OptimizeMode enum. + * @typedef IFileOptionsOptimizeMode + * @type {number} + * @property {number} SPEED=1 + * @property {number} CODE_SIZE=2 + * @property {number} LITE_RUNTIME=3 + */ + +/** + * Creates a root from a descriptor set. + * @param {IFileDescriptorSet|Reader|Uint8Array} descriptor Descriptor + * @returns {Root} Root instance + */ +Root.fromDescriptor = function fromDescriptor(descriptor) { + + // Decode the descriptor message if specified as a buffer: + if (typeof descriptor.length === "number") + descriptor = exports.FileDescriptorSet.decode(descriptor); + + var root = new Root(); + + if (descriptor.file) { + var fileDescriptor, + filePackage; + for (var j = 0, i; j < descriptor.file.length; ++j) { + filePackage = root; + if ((fileDescriptor = descriptor.file[j])["package"] && fileDescriptor["package"].length) + filePackage = root.define(fileDescriptor["package"]); + var edition = editionFromDescriptor(fileDescriptor); + if (fileDescriptor.name && fileDescriptor.name.length) + root.files.push(filePackage.filename = fileDescriptor.name); + if (fileDescriptor.messageType) + for (i = 0; i < fileDescriptor.messageType.length; ++i) + filePackage.add(Type.fromDescriptor(fileDescriptor.messageType[i], edition)); + if (fileDescriptor.enumType) + for (i = 0; i < fileDescriptor.enumType.length; ++i) + filePackage.add(Enum.fromDescriptor(fileDescriptor.enumType[i], edition)); + if (fileDescriptor.extension) + for (i = 0; i < fileDescriptor.extension.length; ++i) + filePackage.add(Field.fromDescriptor(fileDescriptor.extension[i], edition)); + if (fileDescriptor.service) + for (i = 0; i < fileDescriptor.service.length; ++i) + filePackage.add(Service.fromDescriptor(fileDescriptor.service[i], edition)); + var opts = fromDescriptorOptions(fileDescriptor.options, exports.FileOptions); + if (opts) { + var ks = Object.keys(opts); + for (i = 0; i < ks.length; ++i) + filePackage.setOption(ks[i], opts[ks[i]]); + } + } + } + + return root.resolveAll(); +}; + +/** + * Converts a root to a descriptor set. + * @returns {Message} Descriptor + * @param {string} [edition="proto2"] The syntax or edition to use + */ +Root.prototype.toDescriptor = function toDescriptor(edition) { + var set = exports.FileDescriptorSet.create(); + Root_toDescriptorRecursive(this, set.file, edition); + return set; +}; + +// Traverses a namespace and assembles the descriptor set +function Root_toDescriptorRecursive(ns, files, edition) { + + // Create a new file + var file = exports.FileDescriptorProto.create({ name: ns.filename || (ns.fullName.substring(1).replace(/\./g, "_") || "root") + ".proto" }); + editionToDescriptor(edition, file); + if (!(ns instanceof Root)) + file["package"] = ns.fullName.substring(1); + + // Add nested types + for (var i = 0, nested; i < ns.nestedArray.length; ++i) + if ((nested = ns._nestedArray[i]) instanceof Type) + file.messageType.push(nested.toDescriptor(edition)); + else if (nested instanceof Enum) + file.enumType.push(nested.toDescriptor()); + else if (nested instanceof Field) + file.extension.push(nested.toDescriptor(edition)); + else if (nested instanceof Service) + file.service.push(nested.toDescriptor()); + else if (nested instanceof /* plain */ Namespace) + Root_toDescriptorRecursive(nested, files, edition); // requires new file + + // Keep package-level options + file.options = toDescriptorOptions(ns.options, exports.FileOptions); + + // And keep the file only if there is at least one nested object + if (file.messageType.length + file.enumType.length + file.extension.length + file.service.length) + files.push(file); +} + +// --- Type --- + +/** + * Properties of a DescriptorProto message. + * @interface IDescriptorProto + * @property {string} [name] Message type name + * @property {IFieldDescriptorProto[]} [field] Fields + * @property {IFieldDescriptorProto[]} [extension] Extension fields + * @property {IDescriptorProto[]} [nestedType] Nested message types + * @property {IEnumDescriptorProto[]} [enumType] Nested enums + * @property {IDescriptorProtoExtensionRange[]} [extensionRange] Extension ranges + * @property {IOneofDescriptorProto[]} [oneofDecl] Oneofs + * @property {IMessageOptions} [options] Not supported + * @property {IDescriptorProtoReservedRange[]} [reservedRange] Reserved ranges + * @property {string[]} [reservedName] Reserved names + */ + +/** + * Properties of a MessageOptions message. + * @interface IMessageOptions + * @property {boolean} [mapEntry=false] Whether this message is a map entry + */ + +/** + * Properties of an ExtensionRange message. + * @interface IDescriptorProtoExtensionRange + * @property {number} [start] Start field id + * @property {number} [end] End field id + */ + +/** + * Properties of a ReservedRange message. + * @interface IDescriptorProtoReservedRange + * @property {number} [start] Start field id + * @property {number} [end] End field id + */ + +var unnamedMessageIndex = 0; + +/** + * Creates a type from a descriptor. + * + * Warning: this is not safe to use with editions protos, since it discards relevant file context. + * + * @param {IDescriptorProto|Reader|Uint8Array} descriptor Descriptor + * @param {string} [edition="proto2"] The syntax or edition to use + * @param {boolean} [nested=false] Whether or not this is a nested object + * @returns {Type} Type instance + */ +Type.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { + // Decode the descriptor message if specified as a buffer: + if (typeof descriptor.length === "number") + descriptor = exports.DescriptorProto.decode(descriptor); + + // Create the message type + var type = new Type(descriptor.name.length ? descriptor.name : "Type" + unnamedMessageIndex++, fromDescriptorOptions(descriptor.options, exports.MessageOptions)), + i; + + if (!nested) + type._edition = edition; + + /* Oneofs */ if (descriptor.oneofDecl) + for (i = 0; i < descriptor.oneofDecl.length; ++i) + type.add(OneOf.fromDescriptor(descriptor.oneofDecl[i])); + /* Fields */ if (descriptor.field) + for (i = 0; i < descriptor.field.length; ++i) { + var field = Field.fromDescriptor(descriptor.field[i], edition, true); + type.add(field); + if (descriptor.field[i].hasOwnProperty("oneofIndex")) // eslint-disable-line no-prototype-builtins + type.oneofsArray[descriptor.field[i].oneofIndex].add(field); + } + /* Extension fields */ if (descriptor.extension) + for (i = 0; i < descriptor.extension.length; ++i) + type.add(Field.fromDescriptor(descriptor.extension[i], edition, true)); + /* Nested types */ if (descriptor.nestedType) + for (i = 0; i < descriptor.nestedType.length; ++i) { + type.add(Type.fromDescriptor(descriptor.nestedType[i], edition, true)); + if (descriptor.nestedType[i].options && descriptor.nestedType[i].options.mapEntry) + type.setOption("map_entry", true); + } + /* Nested enums */ if (descriptor.enumType) + for (i = 0; i < descriptor.enumType.length; ++i) + type.add(Enum.fromDescriptor(descriptor.enumType[i], edition, true)); + /* Extension ranges */ if (descriptor.extensionRange && descriptor.extensionRange.length) { + type.extensions = []; + for (i = 0; i < descriptor.extensionRange.length; ++i) + type.extensions.push([ descriptor.extensionRange[i].start, descriptor.extensionRange[i].end ]); + } + /* Reserved... */ if (descriptor.reservedRange && descriptor.reservedRange.length || descriptor.reservedName && descriptor.reservedName.length) { + type.reserved = []; + /* Ranges */ if (descriptor.reservedRange) + for (i = 0; i < descriptor.reservedRange.length; ++i) + type.reserved.push([ descriptor.reservedRange[i].start, descriptor.reservedRange[i].end ]); + /* Names */ if (descriptor.reservedName) + for (i = 0; i < descriptor.reservedName.length; ++i) + type.reserved.push(descriptor.reservedName[i]); + } + + return type; +}; + +/** + * Converts a type to a descriptor. + * @returns {Message} Descriptor + * @param {string} [edition="proto2"] The syntax or edition to use + */ +Type.prototype.toDescriptor = function toDescriptor(edition) { + var descriptor = exports.DescriptorProto.create({ name: this.name }), + i; + + /* Fields */ for (i = 0; i < this.fieldsArray.length; ++i) { + var fieldDescriptor; + descriptor.field.push(fieldDescriptor = this._fieldsArray[i].toDescriptor(edition)); + if (this._fieldsArray[i] instanceof MapField) { // map fields are repeated FieldNameEntry + var keyType = toDescriptorType(this._fieldsArray[i].keyType, this._fieldsArray[i].resolvedKeyType, false), + valueType = toDescriptorType(this._fieldsArray[i].type, this._fieldsArray[i].resolvedType, false), + valueTypeName = valueType === /* type */ 11 || valueType === /* enum */ 14 + ? this._fieldsArray[i].resolvedType && shortname(this.parent, this._fieldsArray[i].resolvedType) || this._fieldsArray[i].type + : undefined; + descriptor.nestedType.push(exports.DescriptorProto.create({ + name: fieldDescriptor.typeName, + field: [ + exports.FieldDescriptorProto.create({ name: "key", number: 1, label: 1, type: keyType }), // can't reference a type or enum + exports.FieldDescriptorProto.create({ name: "value", number: 2, label: 1, type: valueType, typeName: valueTypeName }) + ], + options: exports.MessageOptions.create({ mapEntry: true }) + })); + } + } + /* Oneofs */ for (i = 0; i < this.oneofsArray.length; ++i) + descriptor.oneofDecl.push(this._oneofsArray[i].toDescriptor()); + /* Nested... */ for (i = 0; i < this.nestedArray.length; ++i) { + /* Extension fields */ if (this._nestedArray[i] instanceof Field) + descriptor.field.push(this._nestedArray[i].toDescriptor(edition)); + /* Types */ else if (this._nestedArray[i] instanceof Type) + descriptor.nestedType.push(this._nestedArray[i].toDescriptor(edition)); + /* Enums */ else if (this._nestedArray[i] instanceof Enum) + descriptor.enumType.push(this._nestedArray[i].toDescriptor()); + // plain nested namespaces become packages instead in Root#toDescriptor + } + /* Extension ranges */ if (this.extensions) + for (i = 0; i < this.extensions.length; ++i) + descriptor.extensionRange.push(exports.DescriptorProto.ExtensionRange.create({ start: this.extensions[i][0], end: this.extensions[i][1] })); + /* Reserved... */ if (this.reserved) + for (i = 0; i < this.reserved.length; ++i) + /* Names */ if (typeof this.reserved[i] === "string") + descriptor.reservedName.push(this.reserved[i]); + /* Ranges */ else + descriptor.reservedRange.push(exports.DescriptorProto.ReservedRange.create({ start: this.reserved[i][0], end: this.reserved[i][1] })); + + descriptor.options = toDescriptorOptions(this.options, exports.MessageOptions); + + return descriptor; +}; + +// --- Field --- + +/** + * Properties of a FieldDescriptorProto message. + * @interface IFieldDescriptorProto + * @property {string} [name] Field name + * @property {number} [number] Field id + * @property {IFieldDescriptorProtoLabel} [label] Field rule + * @property {IFieldDescriptorProtoType} [type] Field basic type + * @property {string} [typeName] Field type name + * @property {string} [extendee] Extended type name + * @property {string} [defaultValue] Literal default value + * @property {number} [oneofIndex] Oneof index if part of a oneof + * @property {*} [jsonName] Not supported + * @property {IFieldOptions} [options] Field options + */ + +/** + * Values of the FieldDescriptorProto.Label enum. + * @typedef IFieldDescriptorProtoLabel + * @type {number} + * @property {number} LABEL_OPTIONAL=1 + * @property {number} LABEL_REQUIRED=2 + * @property {number} LABEL_REPEATED=3 + */ + +/** + * Values of the FieldDescriptorProto.Type enum. + * @typedef IFieldDescriptorProtoType + * @type {number} + * @property {number} TYPE_DOUBLE=1 + * @property {number} TYPE_FLOAT=2 + * @property {number} TYPE_INT64=3 + * @property {number} TYPE_UINT64=4 + * @property {number} TYPE_INT32=5 + * @property {number} TYPE_FIXED64=6 + * @property {number} TYPE_FIXED32=7 + * @property {number} TYPE_BOOL=8 + * @property {number} TYPE_STRING=9 + * @property {number} TYPE_GROUP=10 + * @property {number} TYPE_MESSAGE=11 + * @property {number} TYPE_BYTES=12 + * @property {number} TYPE_UINT32=13 + * @property {number} TYPE_ENUM=14 + * @property {number} TYPE_SFIXED32=15 + * @property {number} TYPE_SFIXED64=16 + * @property {number} TYPE_SINT32=17 + * @property {number} TYPE_SINT64=18 + */ + +/** + * Properties of a FieldOptions message. + * @interface IFieldOptions + * @property {boolean} [packed] Whether packed or not (defaults to `false` for proto2 and `true` for proto3) + * @property {IFieldOptionsJSType} [jstype] JavaScript value type (not used by protobuf.js) + */ + +/** + * Values of the FieldOptions.JSType enum. + * @typedef IFieldOptionsJSType + * @type {number} + * @property {number} JS_NORMAL=0 + * @property {number} JS_STRING=1 + * @property {number} JS_NUMBER=2 + */ + +// copied here from parse.js +var numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/; + +/** + * Creates a field from a descriptor. + * + * Warning: this is not safe to use with editions protos, since it discards relevant file context. + * + * @param {IFieldDescriptorProto|Reader|Uint8Array} descriptor Descriptor + * @param {string} [edition="proto2"] The syntax or edition to use + * @param {boolean} [nested=false] Whether or not this is a top-level object + * @returns {Field} Field instance + */ +Field.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { + + // Decode the descriptor message if specified as a buffer: + if (typeof descriptor.length === "number") + descriptor = exports.DescriptorProto.decode(descriptor); + + if (typeof descriptor.number !== "number") + throw Error("missing field id"); + + // Rewire field type + var fieldType; + if (descriptor.typeName && descriptor.typeName.length) + fieldType = descriptor.typeName; + else + fieldType = fromDescriptorType(descriptor.type); + + // Rewire field rule + var fieldRule; + switch (descriptor.label) { + // 0 is reserved for errors + case 1: fieldRule = undefined; break; + case 2: fieldRule = "required"; break; + case 3: fieldRule = "repeated"; break; + default: throw Error("illegal label: " + descriptor.label); + } + + var extendee = descriptor.extendee; + if (descriptor.extendee !== undefined) { + extendee = extendee.length ? extendee : undefined; + } + var field = new Field( + descriptor.name.length ? descriptor.name : "field" + descriptor.number, + descriptor.number, + fieldType, + fieldRule, + extendee + ); + + if (!nested) + field._edition = edition; + + field.options = fromDescriptorOptions(descriptor.options, exports.FieldOptions); + if (descriptor.proto3_optional) + field.options.proto3_optional = true; + + if (descriptor.defaultValue && descriptor.defaultValue.length) { + var defaultValue = descriptor.defaultValue; + switch (defaultValue) { + case "true": case "TRUE": + defaultValue = true; + break; + case "false": case "FALSE": + defaultValue = false; + break; + default: + var match = numberRe.exec(defaultValue); + if (match) + defaultValue = parseInt(defaultValue); // eslint-disable-line radix + break; + } + field.setOption("default", defaultValue); + } + + if (packableDescriptorType(descriptor.type)) { + if (edition === "proto3") { // defaults to packed=true (internal preset is packed=true) + if (descriptor.options && !descriptor.options.packed) + field.setOption("packed", false); + } else if ((!edition || edition === "proto2") && descriptor.options && descriptor.options.packed) // defaults to packed=false + field.setOption("packed", true); + } + + return field; +}; + +/** + * Converts a field to a descriptor. + * @returns {Message} Descriptor + * @param {string} [edition="proto2"] The syntax or edition to use + */ +Field.prototype.toDescriptor = function toDescriptor(edition) { + var descriptor = exports.FieldDescriptorProto.create({ name: this.name, number: this.id }); + + if (this.map) { + + descriptor.type = 11; // message + descriptor.typeName = $protobuf.util.ucFirst(this.name); // fieldName -> FieldNameEntry (built in Type#toDescriptor) + descriptor.label = 3; // repeated + + } else { + + // Rewire field type + switch (descriptor.type = toDescriptorType(this.type, this.resolve().resolvedType, this.delimited)) { + case 10: // group + case 11: // type + case 14: // enum + descriptor.typeName = this.resolvedType ? shortname(this.parent, this.resolvedType) : this.type; + break; + } + + // Rewire field rule + if (this.rule === "repeated") { + descriptor.label = 3; + } else if (this.required && edition === "proto2") { + descriptor.label = 2; + } else { + descriptor.label = 1; + } + } + + // Handle extension field + descriptor.extendee = this.extensionField ? this.extensionField.parent.fullName : this.extend; + + // Handle part of oneof + if (this.partOf) + if ((descriptor.oneofIndex = this.parent.oneofsArray.indexOf(this.partOf)) < 0) + throw Error("missing oneof"); + + if (this.options) { + descriptor.options = toDescriptorOptions(this.options, exports.FieldOptions); + if (this.options["default"] != null) + descriptor.defaultValue = String(this.options["default"]); + if (this.options.proto3_optional) + descriptor.proto3_optional = true; + } + + if (edition === "proto3") { // defaults to packed=true + if (!this.packed) + (descriptor.options || (descriptor.options = exports.FieldOptions.create())).packed = false; + } else if ((!edition || edition === "proto2") && this.packed) // defaults to packed=false + (descriptor.options || (descriptor.options = exports.FieldOptions.create())).packed = true; + + return descriptor; +}; + +// --- Enum --- + +/** + * Properties of an EnumDescriptorProto message. + * @interface IEnumDescriptorProto + * @property {string} [name] Enum name + * @property {IEnumValueDescriptorProto[]} [value] Enum values + * @property {IEnumOptions} [options] Enum options + */ + +/** + * Properties of an EnumValueDescriptorProto message. + * @interface IEnumValueDescriptorProto + * @property {string} [name] Name + * @property {number} [number] Value + * @property {*} [options] Not supported + */ + +/** + * Properties of an EnumOptions message. + * @interface IEnumOptions + * @property {boolean} [allowAlias] Whether aliases are allowed + * @property {boolean} [deprecated] + */ + +var unnamedEnumIndex = 0; + +/** + * Creates an enum from a descriptor. + * + * Warning: this is not safe to use with editions protos, since it discards relevant file context. + * + * @param {IEnumDescriptorProto|Reader|Uint8Array} descriptor Descriptor + * @param {string} [edition="proto2"] The syntax or edition to use + * @param {boolean} [nested=false] Whether or not this is a top-level object + * @returns {Enum} Enum instance + */ +Enum.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { + + // Decode the descriptor message if specified as a buffer: + if (typeof descriptor.length === "number") + descriptor = exports.EnumDescriptorProto.decode(descriptor); + + // Construct values object + var values = {}; + if (descriptor.value) + for (var i = 0; i < descriptor.value.length; ++i) { + var name = descriptor.value[i].name, + value = descriptor.value[i].number || 0; + values[name && name.length ? name : "NAME" + value] = value; + } + + var enm = new Enum( + descriptor.name && descriptor.name.length ? descriptor.name : "Enum" + unnamedEnumIndex++, + values, + fromDescriptorOptions(descriptor.options, exports.EnumOptions) + ); + + if (!nested) + enm._edition = edition; + + return enm; +}; + +/** + * Converts an enum to a descriptor. + * @returns {Message} Descriptor + */ +Enum.prototype.toDescriptor = function toDescriptor() { + + // Values + var values = []; + for (var i = 0, ks = Object.keys(this.values); i < ks.length; ++i) + values.push(exports.EnumValueDescriptorProto.create({ name: ks[i], number: this.values[ks[i]] })); + + return exports.EnumDescriptorProto.create({ + name: this.name, + value: values, + options: toDescriptorOptions(this.options, exports.EnumOptions) + }); +}; + +// --- OneOf --- + +/** + * Properties of a OneofDescriptorProto message. + * @interface IOneofDescriptorProto + * @property {string} [name] Oneof name + * @property {*} [options] Not supported + */ + +var unnamedOneofIndex = 0; + +/** + * Creates a oneof from a descriptor. + * + * Warning: this is not safe to use with editions protos, since it discards relevant file context. + * + * @param {IOneofDescriptorProto|Reader|Uint8Array} descriptor Descriptor + * @returns {OneOf} OneOf instance + */ +OneOf.fromDescriptor = function fromDescriptor(descriptor) { + + // Decode the descriptor message if specified as a buffer: + if (typeof descriptor.length === "number") + descriptor = exports.OneofDescriptorProto.decode(descriptor); + + return new OneOf( + // unnamedOneOfIndex is global, not per type, because we have no ref to a type here + descriptor.name && descriptor.name.length ? descriptor.name : "oneof" + unnamedOneofIndex++ + // fromDescriptorOptions(descriptor.options, exports.OneofOptions) - only uninterpreted_option + ); +}; + +/** + * Converts a oneof to a descriptor. + * @returns {Message} Descriptor + */ +OneOf.prototype.toDescriptor = function toDescriptor() { + return exports.OneofDescriptorProto.create({ + name: this.name + // options: toDescriptorOptions(this.options, exports.OneofOptions) - only uninterpreted_option + }); +}; + +// --- Service --- + +/** + * Properties of a ServiceDescriptorProto message. + * @interface IServiceDescriptorProto + * @property {string} [name] Service name + * @property {IMethodDescriptorProto[]} [method] Methods + * @property {IServiceOptions} [options] Options + */ + +/** + * Properties of a ServiceOptions message. + * @interface IServiceOptions + * @property {boolean} [deprecated] + */ + +var unnamedServiceIndex = 0; + +/** + * Creates a service from a descriptor. + * + * Warning: this is not safe to use with editions protos, since it discards relevant file context. + * + * @param {IServiceDescriptorProto|Reader|Uint8Array} descriptor Descriptor + * @param {string} [edition="proto2"] The syntax or edition to use + * @param {boolean} [nested=false] Whether or not this is a top-level object + * @returns {Service} Service instance + */ +Service.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { + + // Decode the descriptor message if specified as a buffer: + if (typeof descriptor.length === "number") + descriptor = exports.ServiceDescriptorProto.decode(descriptor); + + var service = new Service(descriptor.name && descriptor.name.length ? descriptor.name : "Service" + unnamedServiceIndex++, fromDescriptorOptions(descriptor.options, exports.ServiceOptions)); + if (!nested) + service._edition = edition; + if (descriptor.method) + for (var i = 0; i < descriptor.method.length; ++i) + service.add(Method.fromDescriptor(descriptor.method[i])); + + return service; +}; + +/** + * Converts a service to a descriptor. + * @returns {Message} Descriptor + */ +Service.prototype.toDescriptor = function toDescriptor() { + + // Methods + var methods = []; + for (var i = 0; i < this.methodsArray.length; ++i) + methods.push(this._methodsArray[i].toDescriptor()); + + return exports.ServiceDescriptorProto.create({ + name: this.name, + method: methods, + options: toDescriptorOptions(this.options, exports.ServiceOptions) + }); +}; + +// --- Method --- + +/** + * Properties of a MethodDescriptorProto message. + * @interface IMethodDescriptorProto + * @property {string} [name] Method name + * @property {string} [inputType] Request type name + * @property {string} [outputType] Response type name + * @property {IMethodOptions} [options] Not supported + * @property {boolean} [clientStreaming=false] Whether requests are streamed + * @property {boolean} [serverStreaming=false] Whether responses are streamed + */ + +/** + * Properties of a MethodOptions message. + * + * Warning: this is not safe to use with editions protos, since it discards relevant file context. + * + * @interface IMethodOptions + * @property {boolean} [deprecated] + */ + +var unnamedMethodIndex = 0; + +/** + * Creates a method from a descriptor. + * @param {IMethodDescriptorProto|Reader|Uint8Array} descriptor Descriptor + * @returns {Method} Reflected method instance + */ +Method.fromDescriptor = function fromDescriptor(descriptor) { + + // Decode the descriptor message if specified as a buffer: + if (typeof descriptor.length === "number") + descriptor = exports.MethodDescriptorProto.decode(descriptor); + + return new Method( + // unnamedMethodIndex is global, not per service, because we have no ref to a service here + descriptor.name && descriptor.name.length ? descriptor.name : "Method" + unnamedMethodIndex++, + "rpc", + descriptor.inputType, + descriptor.outputType, + Boolean(descriptor.clientStreaming), + Boolean(descriptor.serverStreaming), + fromDescriptorOptions(descriptor.options, exports.MethodOptions) + ); +}; + +/** + * Converts a method to a descriptor. + * @returns {Message} Descriptor + */ +Method.prototype.toDescriptor = function toDescriptor() { + return exports.MethodDescriptorProto.create({ + name: this.name, + inputType: this.resolvedRequestType ? this.resolvedRequestType.fullName : this.requestType, + outputType: this.resolvedResponseType ? this.resolvedResponseType.fullName : this.responseType, + clientStreaming: this.requestStream, + serverStreaming: this.responseStream, + options: toDescriptorOptions(this.options, exports.MethodOptions) + }); +}; + +// --- utility --- + +// Converts a descriptor type to a protobuf.js basic type +function fromDescriptorType(type) { + switch (type) { + // 0 is reserved for errors + case 1: return "double"; + case 2: return "float"; + case 3: return "int64"; + case 4: return "uint64"; + case 5: return "int32"; + case 6: return "fixed64"; + case 7: return "fixed32"; + case 8: return "bool"; + case 9: return "string"; + case 12: return "bytes"; + case 13: return "uint32"; + case 15: return "sfixed32"; + case 16: return "sfixed64"; + case 17: return "sint32"; + case 18: return "sint64"; + } + throw Error("illegal type: " + type); +} + +// Tests if a descriptor type is packable +function packableDescriptorType(type) { + switch (type) { + case 1: // double + case 2: // float + case 3: // int64 + case 4: // uint64 + case 5: // int32 + case 6: // fixed64 + case 7: // fixed32 + case 8: // bool + case 13: // uint32 + case 14: // enum (!) + case 15: // sfixed32 + case 16: // sfixed64 + case 17: // sint32 + case 18: // sint64 + return true; + } + return false; +} + +// Converts a protobuf.js basic type to a descriptor type +function toDescriptorType(type, resolvedType, delimited) { + switch (type) { + // 0 is reserved for errors + case "double": return 1; + case "float": return 2; + case "int64": return 3; + case "uint64": return 4; + case "int32": return 5; + case "fixed64": return 6; + case "fixed32": return 7; + case "bool": return 8; + case "string": return 9; + case "bytes": return 12; + case "uint32": return 13; + case "sfixed32": return 15; + case "sfixed64": return 16; + case "sint32": return 17; + case "sint64": return 18; + } + if (resolvedType instanceof Enum) + return 14; + if (resolvedType instanceof Type) + return delimited ? 10 : 11; + throw Error("illegal type: " + type); +} + +function fromDescriptorOptionsRecursive(obj, type) { + var val = {}; + for (var i = 0, field, key; i < type.fieldsArray.length; ++i) { + if ((key = (field = type._fieldsArray[i]).name) === "uninterpretedOption") continue; + if (!Object.prototype.hasOwnProperty.call(obj, key)) continue; + + var newKey = underScore(key); + if (field.resolvedType instanceof Type) { + val[newKey] = fromDescriptorOptionsRecursive(obj[key], field.resolvedType); + } else if(field.resolvedType instanceof Enum) { + val[newKey] = field.resolvedType.valuesById[obj[key]]; + } else { + val[newKey] = obj[key]; + } + } + return val; +} + +// Converts descriptor options to an options object +function fromDescriptorOptions(options, type) { + if (!options) + return undefined; + return fromDescriptorOptionsRecursive(type.toObject(options), type); +} + +function toDescriptorOptionsRecursive(obj, type) { + var val = {}; + var keys = Object.keys(obj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var newKey = $protobuf.util.camelCase(key); + if (!Object.prototype.hasOwnProperty.call(type.fields, newKey)) continue; + var field = type.fields[newKey]; + if (field.resolvedType instanceof Type) { + val[newKey] = toDescriptorOptionsRecursive(obj[key], field.resolvedType); + } else { + val[newKey] = obj[key]; + } + if (field.repeated && !Array.isArray(val[newKey])) { + val[newKey] = [val[newKey]]; + } + } + return val; +} + +// Converts an options object to descriptor options +function toDescriptorOptions(options, type) { + if (!options) + return undefined; + return type.fromObject(toDescriptorOptionsRecursive(options, type)); +} + +// Calculates the shortest relative path from `from` to `to`. +function shortname(from, to) { + var fromPath = from.fullName.split("."), + toPath = to.fullName.split("."), + i = 0, + j = 0, + k = toPath.length - 1; + if (!(from instanceof Root) && to instanceof Namespace) + while (i < fromPath.length && j < k && fromPath[i] === toPath[j]) { + var other = to.lookup(fromPath[i++], true); + if (other !== null && other !== to) + break; + ++j; + } + else + for (; i < fromPath.length && j < k && fromPath[i] === toPath[j]; ++i, ++j); + return toPath.slice(j).join("."); +} + +// copied here from cli/targets/proto.js +function underScore(str) { + return str.substring(0,1) + + str.substring(1) + .replace(/([A-Z])(?=[a-z]|$)/g, function($0, $1) { return "_" + $1.toLowerCase(); }); +} + +function editionFromDescriptor(fileDescriptor) { + if (fileDescriptor.syntax === "editions") { + switch(fileDescriptor.edition) { + case exports.Edition.EDITION_2023: + return "2023"; + default: + throw new Error("Unsupported edition " + fileDescriptor.edition); + } + } + if (fileDescriptor.syntax === "proto3") { + return "proto3"; + } + return "proto2"; +} + +function editionToDescriptor(edition, fileDescriptor) { + if (!edition) return; + if (edition === "proto2" || edition === "proto3") { + fileDescriptor.syntax = edition; + } else { + fileDescriptor.syntax = "editions"; + switch(edition) { + case "2023": + fileDescriptor.edition = exports.Edition.EDITION_2023; + break; + default: + throw new Error("Unsupported edition " + edition); + } + } +} + +// --- exports --- + +/** + * Reflected file descriptor set. + * @name FileDescriptorSet + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected file descriptor proto. + * @name FileDescriptorProto + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected descriptor proto. + * @name DescriptorProto + * @type {Type} + * @property {Type} ExtensionRange + * @property {Type} ReservedRange + * @const + * @tstype $protobuf.Type & { + * ExtensionRange: $protobuf.Type, + * ReservedRange: $protobuf.Type + * } + */ + +/** + * Reflected field descriptor proto. + * @name FieldDescriptorProto + * @type {Type} + * @property {Enum} Label + * @property {Enum} Type + * @const + * @tstype $protobuf.Type & { + * Label: $protobuf.Enum, + * Type: $protobuf.Enum + * } + */ + +/** + * Reflected oneof descriptor proto. + * @name OneofDescriptorProto + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected enum descriptor proto. + * @name EnumDescriptorProto + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected service descriptor proto. + * @name ServiceDescriptorProto + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected enum value descriptor proto. + * @name EnumValueDescriptorProto + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected method descriptor proto. + * @name MethodDescriptorProto + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected file options. + * @name FileOptions + * @type {Type} + * @property {Enum} OptimizeMode + * @const + * @tstype $protobuf.Type & { + * OptimizeMode: $protobuf.Enum + * } + */ + +/** + * Reflected message options. + * @name MessageOptions + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected field options. + * @name FieldOptions + * @type {Type} + * @property {Enum} CType + * @property {Enum} JSType + * @const + * @tstype $protobuf.Type & { + * CType: $protobuf.Enum, + * JSType: $protobuf.Enum + * } + */ + +/** + * Reflected oneof options. + * @name OneofOptions + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected enum options. + * @name EnumOptions + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected enum value options. + * @name EnumValueOptions + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected service options. + * @name ServiceOptions + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected method options. + * @name MethodOptions + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected uninterpretet option. + * @name UninterpretedOption + * @type {Type} + * @property {Type} NamePart + * @const + * @tstype $protobuf.Type & { + * NamePart: $protobuf.Type + * } + */ + +/** + * Reflected source code info. + * @name SourceCodeInfo + * @type {Type} + * @property {Type} Location + * @const + * @tstype $protobuf.Type & { + * Location: $protobuf.Type + * } + */ + +/** + * Reflected generated code info. + * @name GeneratedCodeInfo + * @type {Type} + * @property {Type} Annotation + * @const + * @tstype $protobuf.Type & { + * Annotation: $protobuf.Type + * } + */ diff --git a/node_modules/protobufjs/ext/descriptor/test.js b/node_modules/protobufjs/ext/descriptor/test.js new file mode 100644 index 0000000..ceb80f8 --- /dev/null +++ b/node_modules/protobufjs/ext/descriptor/test.js @@ -0,0 +1,54 @@ +/*eslint-disable no-console*/ +"use strict"; +var protobuf = require("../../"), + descriptor = require("."); + +/* var proto = { + nested: { + Message: { + fields: { + foo: { + type: "string", + id: 1 + } + }, + nested: { + SubMessage: { + fields: {} + } + } + }, + Enum: { + values: { + ONE: 1, + TWO: 2 + } + } + } +}; */ + +// var root = protobuf.Root.fromJSON(proto).resolveAll(); +var root = protobuf.loadSync("tests/data/google/protobuf/descriptor.proto").resolveAll(); + +// console.log("Original proto", JSON.stringify(root, null, 2)); + +var msg = root.toDescriptor(); + +// console.log("\nDescriptor", JSON.stringify(msg.toObject(), null, 2)); + +var buf = descriptor.FileDescriptorSet.encode(msg).finish(); +var root2 = protobuf.Root.fromDescriptor(buf, "proto2").resolveAll(); + +// console.log("\nDecoded proto", JSON.stringify(root2, null, 2)); + +var diff = require("deep-diff").diff(root.toJSON(), root2.toJSON()); +if (diff) { + diff.forEach(function(diff) { + console.log(diff.kind + " @ " + diff.path.join(".")); + console.log("lhs:", typeof diff.lhs, diff.lhs); + console.log("rhs:", typeof diff.rhs, diff.rhs); + console.log(); + }); + process.exitCode = 1; +} else + console.log("no differences"); diff --git a/node_modules/protobufjs/google/LICENSE b/node_modules/protobufjs/google/LICENSE new file mode 100644 index 0000000..868bd40 --- /dev/null +++ b/node_modules/protobufjs/google/LICENSE @@ -0,0 +1,27 @@ +Copyright 2014, Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/protobufjs/google/README.md b/node_modules/protobufjs/google/README.md new file mode 100644 index 0000000..09e3f23 --- /dev/null +++ b/node_modules/protobufjs/google/README.md @@ -0,0 +1 @@ +This folder contains stripped and pre-parsed definitions of common Google types. These files are not used by protobuf.js directly but are here so you can use or include them where required. diff --git a/node_modules/protobufjs/google/api/annotations.json b/node_modules/protobufjs/google/api/annotations.json new file mode 100644 index 0000000..3f13a73 --- /dev/null +++ b/node_modules/protobufjs/google/api/annotations.json @@ -0,0 +1,83 @@ +{ + "nested": { + "google": { + "nested": { + "api": { + "nested": { + "http": { + "type": "HttpRule", + "id": 72295728, + "extend": "google.protobuf.MethodOptions" + }, + "HttpRule": { + "oneofs": { + "pattern": { + "oneof": [ + "get", + "put", + "post", + "delete", + "patch", + "custom" + ] + } + }, + "fields": { + "get": { + "type": "string", + "id": 2 + }, + "put": { + "type": "string", + "id": 3 + }, + "post": { + "type": "string", + "id": 4 + }, + "delete": { + "type": "string", + "id": 5 + }, + "patch": { + "type": "string", + "id": 6 + }, + "custom": { + "type": "CustomHttpPattern", + "id": 8 + }, + "selector": { + "type": "string", + "id": 1 + }, + "body": { + "type": "string", + "id": 7 + }, + "additionalBindings": { + "rule": "repeated", + "type": "HttpRule", + "id": 11 + } + } + } + } + }, + "protobuf": { + "nested": { + "MethodOptions": { + "fields": {}, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + } + } + } + } + } + } +} \ No newline at end of file diff --git a/node_modules/protobufjs/google/api/annotations.proto b/node_modules/protobufjs/google/api/annotations.proto new file mode 100644 index 0000000..63a8eef --- /dev/null +++ b/node_modules/protobufjs/google/api/annotations.proto @@ -0,0 +1,11 @@ +syntax = "proto3"; + +package google.api; + +import "google/api/http.proto"; +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.MethodOptions { + + HttpRule http = 72295728; +} \ No newline at end of file diff --git a/node_modules/protobufjs/google/api/http.json b/node_modules/protobufjs/google/api/http.json new file mode 100644 index 0000000..e3a0f4f --- /dev/null +++ b/node_modules/protobufjs/google/api/http.json @@ -0,0 +1,86 @@ +{ + "nested": { + "google": { + "nested": { + "api": { + "nested": { + "Http": { + "fields": { + "rules": { + "rule": "repeated", + "type": "HttpRule", + "id": 1 + } + } + }, + "HttpRule": { + "oneofs": { + "pattern": { + "oneof": [ + "get", + "put", + "post", + "delete", + "patch", + "custom" + ] + } + }, + "fields": { + "get": { + "type": "string", + "id": 2 + }, + "put": { + "type": "string", + "id": 3 + }, + "post": { + "type": "string", + "id": 4 + }, + "delete": { + "type": "string", + "id": 5 + }, + "patch": { + "type": "string", + "id": 6 + }, + "custom": { + "type": "CustomHttpPattern", + "id": 8 + }, + "selector": { + "type": "string", + "id": 1 + }, + "body": { + "type": "string", + "id": 7 + }, + "additionalBindings": { + "rule": "repeated", + "type": "HttpRule", + "id": 11 + } + } + }, + "CustomHttpPattern": { + "fields": { + "kind": { + "type": "string", + "id": 1 + }, + "path": { + "type": "string", + "id": 2 + } + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/node_modules/protobufjs/google/api/http.proto b/node_modules/protobufjs/google/api/http.proto new file mode 100644 index 0000000..e9a7e9d --- /dev/null +++ b/node_modules/protobufjs/google/api/http.proto @@ -0,0 +1,31 @@ +syntax = "proto3"; + +package google.api; + +message Http { + + repeated HttpRule rules = 1; +} + +message HttpRule { + + oneof pattern { + + string get = 2; + string put = 3; + string post = 4; + string delete = 5; + string patch = 6; + CustomHttpPattern custom = 8; + } + + string selector = 1; + string body = 7; + repeated HttpRule additional_bindings = 11; +} + +message CustomHttpPattern { + + string kind = 1; + string path = 2; +} \ No newline at end of file diff --git a/node_modules/protobufjs/google/protobuf/api.json b/node_modules/protobufjs/google/protobuf/api.json new file mode 100644 index 0000000..5460612 --- /dev/null +++ b/node_modules/protobufjs/google/protobuf/api.json @@ -0,0 +1,118 @@ +{ + "nested": { + "google": { + "nested": { + "protobuf": { + "nested": { + "Api": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "methods": { + "rule": "repeated", + "type": "Method", + "id": 2 + }, + "options": { + "rule": "repeated", + "type": "Option", + "id": 3 + }, + "version": { + "type": "string", + "id": 4 + }, + "sourceContext": { + "type": "SourceContext", + "id": 5 + }, + "mixins": { + "rule": "repeated", + "type": "Mixin", + "id": 6 + }, + "syntax": { + "type": "Syntax", + "id": 7 + } + } + }, + "Method": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "requestTypeUrl": { + "type": "string", + "id": 2 + }, + "requestStreaming": { + "type": "bool", + "id": 3 + }, + "responseTypeUrl": { + "type": "string", + "id": 4 + }, + "responseStreaming": { + "type": "bool", + "id": 5 + }, + "options": { + "rule": "repeated", + "type": "Option", + "id": 6 + }, + "syntax": { + "type": "Syntax", + "id": 7 + } + } + }, + "Mixin": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "root": { + "type": "string", + "id": 2 + } + } + }, + "SourceContext": { + "fields": { + "fileName": { + "type": "string", + "id": 1 + } + } + }, + "Option": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "value": { + "type": "Any", + "id": 2 + } + } + }, + "Syntax": { + "values": { + "SYNTAX_PROTO2": 0, + "SYNTAX_PROTO3": 1 + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/node_modules/protobufjs/google/protobuf/api.proto b/node_modules/protobufjs/google/protobuf/api.proto new file mode 100644 index 0000000..cf6ae3f --- /dev/null +++ b/node_modules/protobufjs/google/protobuf/api.proto @@ -0,0 +1,34 @@ +syntax = "proto3"; + +package google.protobuf; + +import "google/protobuf/source_context.proto"; +import "google/protobuf/type.proto"; + +message Api { + + string name = 1; + repeated Method methods = 2; + repeated Option options = 3; + string version = 4; + SourceContext source_context = 5; + repeated Mixin mixins = 6; + Syntax syntax = 7; +} + +message Method { + + string name = 1; + string request_type_url = 2; + bool request_streaming = 3; + string response_type_url = 4; + bool response_streaming = 5; + repeated Option options = 6; + Syntax syntax = 7; +} + +message Mixin { + + string name = 1; + string root = 2; +} \ No newline at end of file diff --git a/node_modules/protobufjs/google/protobuf/descriptor.json b/node_modules/protobufjs/google/protobuf/descriptor.json new file mode 100644 index 0000000..300227b --- /dev/null +++ b/node_modules/protobufjs/google/protobuf/descriptor.json @@ -0,0 +1,1382 @@ +{ + "nested": { + "google": { + "nested": { + "protobuf": { + "options": { + "go_package": "google.golang.org/protobuf/types/descriptorpb", + "java_package": "com.google.protobuf", + "java_outer_classname": "DescriptorProtos", + "csharp_namespace": "Google.Protobuf.Reflection", + "objc_class_prefix": "GPB", + "cc_enable_arenas": true, + "optimize_for": "SPEED" + }, + "nested": { + "FileDescriptorSet": { + "edition": "proto2", + "fields": { + "file": { + "rule": "repeated", + "type": "FileDescriptorProto", + "id": 1 + } + }, + "extensions": [ + [ + 536000000, + 536000000 + ] + ] + }, + "Edition": { + "edition": "proto2", + "values": { + "EDITION_UNKNOWN": 0, + "EDITION_LEGACY": 900, + "EDITION_PROTO2": 998, + "EDITION_PROTO3": 999, + "EDITION_2023": 1000, + "EDITION_2024": 1001, + "EDITION_1_TEST_ONLY": 1, + "EDITION_2_TEST_ONLY": 2, + "EDITION_99997_TEST_ONLY": 99997, + "EDITION_99998_TEST_ONLY": 99998, + "EDITION_99999_TEST_ONLY": 99999, + "EDITION_MAX": 2147483647 + } + }, + "FileDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "package": { + "type": "string", + "id": 2 + }, + "dependency": { + "rule": "repeated", + "type": "string", + "id": 3 + }, + "publicDependency": { + "rule": "repeated", + "type": "int32", + "id": 10 + }, + "weakDependency": { + "rule": "repeated", + "type": "int32", + "id": 11 + }, + "optionDependency": { + "rule": "repeated", + "type": "string", + "id": 15 + }, + "messageType": { + "rule": "repeated", + "type": "DescriptorProto", + "id": 4 + }, + "enumType": { + "rule": "repeated", + "type": "EnumDescriptorProto", + "id": 5 + }, + "service": { + "rule": "repeated", + "type": "ServiceDescriptorProto", + "id": 6 + }, + "extension": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 7 + }, + "options": { + "type": "FileOptions", + "id": 8 + }, + "sourceCodeInfo": { + "type": "SourceCodeInfo", + "id": 9 + }, + "syntax": { + "type": "string", + "id": 12 + }, + "edition": { + "type": "Edition", + "id": 14 + } + } + }, + "DescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "field": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 2 + }, + "extension": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 6 + }, + "nestedType": { + "rule": "repeated", + "type": "DescriptorProto", + "id": 3 + }, + "enumType": { + "rule": "repeated", + "type": "EnumDescriptorProto", + "id": 4 + }, + "extensionRange": { + "rule": "repeated", + "type": "ExtensionRange", + "id": 5 + }, + "oneofDecl": { + "rule": "repeated", + "type": "OneofDescriptorProto", + "id": 8 + }, + "options": { + "type": "MessageOptions", + "id": 7 + }, + "reservedRange": { + "rule": "repeated", + "type": "ReservedRange", + "id": 9 + }, + "reservedName": { + "rule": "repeated", + "type": "string", + "id": 10 + }, + "visibility": { + "type": "SymbolVisibility", + "id": 11 + } + }, + "nested": { + "ExtensionRange": { + "fields": { + "start": { + "type": "int32", + "id": 1 + }, + "end": { + "type": "int32", + "id": 2 + }, + "options": { + "type": "ExtensionRangeOptions", + "id": 3 + } + } + }, + "ReservedRange": { + "fields": { + "start": { + "type": "int32", + "id": 1 + }, + "end": { + "type": "int32", + "id": 2 + } + } + } + } + }, + "ExtensionRangeOptions": { + "edition": "proto2", + "fields": { + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + }, + "declaration": { + "rule": "repeated", + "type": "Declaration", + "id": 2, + "options": { + "retention": "RETENTION_SOURCE" + } + }, + "features": { + "type": "FeatureSet", + "id": 50 + }, + "verification": { + "type": "VerificationState", + "id": 3, + "options": { + "default": "UNVERIFIED", + "retention": "RETENTION_SOURCE" + } + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "nested": { + "Declaration": { + "fields": { + "number": { + "type": "int32", + "id": 1 + }, + "fullName": { + "type": "string", + "id": 2 + }, + "type": { + "type": "string", + "id": 3 + }, + "reserved": { + "type": "bool", + "id": 5 + }, + "repeated": { + "type": "bool", + "id": 6 + } + }, + "reserved": [ + [ + 4, + 4 + ] + ] + }, + "VerificationState": { + "values": { + "DECLARATION": 0, + "UNVERIFIED": 1 + } + } + } + }, + "FieldDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "number": { + "type": "int32", + "id": 3 + }, + "label": { + "type": "Label", + "id": 4 + }, + "type": { + "type": "Type", + "id": 5 + }, + "typeName": { + "type": "string", + "id": 6 + }, + "extendee": { + "type": "string", + "id": 2 + }, + "defaultValue": { + "type": "string", + "id": 7 + }, + "oneofIndex": { + "type": "int32", + "id": 9 + }, + "jsonName": { + "type": "string", + "id": 10 + }, + "options": { + "type": "FieldOptions", + "id": 8 + }, + "proto3Optional": { + "type": "bool", + "id": 17 + } + }, + "nested": { + "Type": { + "values": { + "TYPE_DOUBLE": 1, + "TYPE_FLOAT": 2, + "TYPE_INT64": 3, + "TYPE_UINT64": 4, + "TYPE_INT32": 5, + "TYPE_FIXED64": 6, + "TYPE_FIXED32": 7, + "TYPE_BOOL": 8, + "TYPE_STRING": 9, + "TYPE_GROUP": 10, + "TYPE_MESSAGE": 11, + "TYPE_BYTES": 12, + "TYPE_UINT32": 13, + "TYPE_ENUM": 14, + "TYPE_SFIXED32": 15, + "TYPE_SFIXED64": 16, + "TYPE_SINT32": 17, + "TYPE_SINT64": 18 + } + }, + "Label": { + "values": { + "LABEL_OPTIONAL": 1, + "LABEL_REPEATED": 3, + "LABEL_REQUIRED": 2 + } + } + } + }, + "OneofDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "options": { + "type": "OneofOptions", + "id": 2 + } + } + }, + "EnumDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "value": { + "rule": "repeated", + "type": "EnumValueDescriptorProto", + "id": 2 + }, + "options": { + "type": "EnumOptions", + "id": 3 + }, + "reservedRange": { + "rule": "repeated", + "type": "EnumReservedRange", + "id": 4 + }, + "reservedName": { + "rule": "repeated", + "type": "string", + "id": 5 + }, + "visibility": { + "type": "SymbolVisibility", + "id": 6 + } + }, + "nested": { + "EnumReservedRange": { + "fields": { + "start": { + "type": "int32", + "id": 1 + }, + "end": { + "type": "int32", + "id": 2 + } + } + } + } + }, + "EnumValueDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "number": { + "type": "int32", + "id": 2 + }, + "options": { + "type": "EnumValueOptions", + "id": 3 + } + } + }, + "ServiceDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "method": { + "rule": "repeated", + "type": "MethodDescriptorProto", + "id": 2 + }, + "options": { + "type": "ServiceOptions", + "id": 3 + } + } + }, + "MethodDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "inputType": { + "type": "string", + "id": 2 + }, + "outputType": { + "type": "string", + "id": 3 + }, + "options": { + "type": "MethodOptions", + "id": 4 + }, + "clientStreaming": { + "type": "bool", + "id": 5 + }, + "serverStreaming": { + "type": "bool", + "id": 6 + } + } + }, + "FileOptions": { + "edition": "proto2", + "fields": { + "javaPackage": { + "type": "string", + "id": 1 + }, + "javaOuterClassname": { + "type": "string", + "id": 8 + }, + "javaMultipleFiles": { + "type": "bool", + "id": 10 + }, + "javaGenerateEqualsAndHash": { + "type": "bool", + "id": 20, + "options": { + "deprecated": true + } + }, + "javaStringCheckUtf8": { + "type": "bool", + "id": 27 + }, + "optimizeFor": { + "type": "OptimizeMode", + "id": 9, + "options": { + "default": "SPEED" + } + }, + "goPackage": { + "type": "string", + "id": 11 + }, + "ccGenericServices": { + "type": "bool", + "id": 16 + }, + "javaGenericServices": { + "type": "bool", + "id": 17 + }, + "pyGenericServices": { + "type": "bool", + "id": 18 + }, + "deprecated": { + "type": "bool", + "id": 23 + }, + "ccEnableArenas": { + "type": "bool", + "id": 31, + "options": { + "default": true + } + }, + "objcClassPrefix": { + "type": "string", + "id": 36 + }, + "csharpNamespace": { + "type": "string", + "id": 37 + }, + "swiftPrefix": { + "type": "string", + "id": 39 + }, + "phpClassPrefix": { + "type": "string", + "id": 40 + }, + "phpNamespace": { + "type": "string", + "id": 41 + }, + "phpMetadataNamespace": { + "type": "string", + "id": 44 + }, + "rubyPackage": { + "type": "string", + "id": 45 + }, + "features": { + "type": "FeatureSet", + "id": 50 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 42, + 42 + ], + [ + 38, + 38 + ], + "php_generic_services" + ], + "nested": { + "OptimizeMode": { + "values": { + "SPEED": 1, + "CODE_SIZE": 2, + "LITE_RUNTIME": 3 + } + } + } + }, + "MessageOptions": { + "edition": "proto2", + "fields": { + "messageSetWireFormat": { + "type": "bool", + "id": 1 + }, + "noStandardDescriptorAccessor": { + "type": "bool", + "id": 2 + }, + "deprecated": { + "type": "bool", + "id": 3 + }, + "mapEntry": { + "type": "bool", + "id": 7 + }, + "deprecatedLegacyJsonFieldConflicts": { + "type": "bool", + "id": 11, + "options": { + "deprecated": true + } + }, + "features": { + "type": "FeatureSet", + "id": 12 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 4, + 4 + ], + [ + 5, + 5 + ], + [ + 6, + 6 + ], + [ + 8, + 8 + ], + [ + 9, + 9 + ] + ] + }, + "FieldOptions": { + "edition": "proto2", + "fields": { + "ctype": { + "type": "CType", + "id": 1, + "options": { + "default": "STRING" + } + }, + "packed": { + "type": "bool", + "id": 2 + }, + "jstype": { + "type": "JSType", + "id": 6, + "options": { + "default": "JS_NORMAL" + } + }, + "lazy": { + "type": "bool", + "id": 5 + }, + "unverifiedLazy": { + "type": "bool", + "id": 15 + }, + "deprecated": { + "type": "bool", + "id": 3 + }, + "weak": { + "type": "bool", + "id": 10, + "options": { + "deprecated": true + } + }, + "debugRedact": { + "type": "bool", + "id": 16 + }, + "retention": { + "type": "OptionRetention", + "id": 17 + }, + "targets": { + "rule": "repeated", + "type": "OptionTargetType", + "id": 19 + }, + "editionDefaults": { + "rule": "repeated", + "type": "EditionDefault", + "id": 20 + }, + "features": { + "type": "FeatureSet", + "id": 21 + }, + "featureSupport": { + "type": "FeatureSupport", + "id": 22 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 4, + 4 + ], + [ + 18, + 18 + ] + ], + "nested": { + "CType": { + "values": { + "STRING": 0, + "CORD": 1, + "STRING_PIECE": 2 + } + }, + "JSType": { + "values": { + "JS_NORMAL": 0, + "JS_STRING": 1, + "JS_NUMBER": 2 + } + }, + "OptionRetention": { + "values": { + "RETENTION_UNKNOWN": 0, + "RETENTION_RUNTIME": 1, + "RETENTION_SOURCE": 2 + } + }, + "OptionTargetType": { + "values": { + "TARGET_TYPE_UNKNOWN": 0, + "TARGET_TYPE_FILE": 1, + "TARGET_TYPE_EXTENSION_RANGE": 2, + "TARGET_TYPE_MESSAGE": 3, + "TARGET_TYPE_FIELD": 4, + "TARGET_TYPE_ONEOF": 5, + "TARGET_TYPE_ENUM": 6, + "TARGET_TYPE_ENUM_ENTRY": 7, + "TARGET_TYPE_SERVICE": 8, + "TARGET_TYPE_METHOD": 9 + } + }, + "EditionDefault": { + "fields": { + "edition": { + "type": "Edition", + "id": 3 + }, + "value": { + "type": "string", + "id": 2 + } + } + }, + "FeatureSupport": { + "fields": { + "editionIntroduced": { + "type": "Edition", + "id": 1 + }, + "editionDeprecated": { + "type": "Edition", + "id": 2 + }, + "deprecationWarning": { + "type": "string", + "id": 3 + }, + "editionRemoved": { + "type": "Edition", + "id": 4 + } + } + } + } + }, + "OneofOptions": { + "edition": "proto2", + "fields": { + "features": { + "type": "FeatureSet", + "id": 1 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "EnumOptions": { + "edition": "proto2", + "fields": { + "allowAlias": { + "type": "bool", + "id": 2 + }, + "deprecated": { + "type": "bool", + "id": 3 + }, + "deprecatedLegacyJsonFieldConflicts": { + "type": "bool", + "id": 6, + "options": { + "deprecated": true + } + }, + "features": { + "type": "FeatureSet", + "id": 7 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 5, + 5 + ] + ] + }, + "EnumValueOptions": { + "edition": "proto2", + "fields": { + "deprecated": { + "type": "bool", + "id": 1 + }, + "features": { + "type": "FeatureSet", + "id": 2 + }, + "debugRedact": { + "type": "bool", + "id": 3 + }, + "featureSupport": { + "type": "FieldOptions.FeatureSupport", + "id": 4 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "ServiceOptions": { + "edition": "proto2", + "fields": { + "features": { + "type": "FeatureSet", + "id": 34 + }, + "deprecated": { + "type": "bool", + "id": 33 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "MethodOptions": { + "edition": "proto2", + "fields": { + "deprecated": { + "type": "bool", + "id": 33 + }, + "idempotencyLevel": { + "type": "IdempotencyLevel", + "id": 34, + "options": { + "default": "IDEMPOTENCY_UNKNOWN" + } + }, + "features": { + "type": "FeatureSet", + "id": 35 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "nested": { + "IdempotencyLevel": { + "values": { + "IDEMPOTENCY_UNKNOWN": 0, + "NO_SIDE_EFFECTS": 1, + "IDEMPOTENT": 2 + } + } + } + }, + "UninterpretedOption": { + "edition": "proto2", + "fields": { + "name": { + "rule": "repeated", + "type": "NamePart", + "id": 2 + }, + "identifierValue": { + "type": "string", + "id": 3 + }, + "positiveIntValue": { + "type": "uint64", + "id": 4 + }, + "negativeIntValue": { + "type": "int64", + "id": 5 + }, + "doubleValue": { + "type": "double", + "id": 6 + }, + "stringValue": { + "type": "bytes", + "id": 7 + }, + "aggregateValue": { + "type": "string", + "id": 8 + } + }, + "nested": { + "NamePart": { + "fields": { + "namePart": { + "rule": "required", + "type": "string", + "id": 1 + }, + "isExtension": { + "rule": "required", + "type": "bool", + "id": 2 + } + } + } + } + }, + "FeatureSet": { + "edition": "proto2", + "fields": { + "fieldPresence": { + "type": "FieldPresence", + "id": 1, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_2023", + "edition_defaults.value": "EXPLICIT" + } + }, + "enumType": { + "type": "EnumType", + "id": 2, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "OPEN" + } + }, + "repeatedFieldEncoding": { + "type": "RepeatedFieldEncoding", + "id": 3, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "PACKED" + } + }, + "utf8Validation": { + "type": "Utf8Validation", + "id": 4, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "VERIFY" + } + }, + "messageEncoding": { + "type": "MessageEncoding", + "id": 5, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_LEGACY", + "edition_defaults.value": "LENGTH_PREFIXED" + } + }, + "jsonFormat": { + "type": "JsonFormat", + "id": 6, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "ALLOW" + } + }, + "enforceNamingStyle": { + "type": "EnforceNamingStyle", + "id": 7, + "options": { + "retention": "RETENTION_SOURCE", + "targets": "TARGET_TYPE_METHOD", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "STYLE2024" + } + }, + "defaultSymbolVisibility": { + "type": "VisibilityFeature.DefaultSymbolVisibility", + "id": 8, + "options": { + "retention": "RETENTION_SOURCE", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "EXPORT_TOP_LEVEL" + } + } + }, + "extensions": [ + [ + 1000, + 9994 + ], + [ + 9995, + 9999 + ], + [ + 10000, + 10000 + ] + ], + "reserved": [ + [ + 999, + 999 + ] + ], + "nested": { + "FieldPresence": { + "values": { + "FIELD_PRESENCE_UNKNOWN": 0, + "EXPLICIT": 1, + "IMPLICIT": 2, + "LEGACY_REQUIRED": 3 + } + }, + "EnumType": { + "values": { + "ENUM_TYPE_UNKNOWN": 0, + "OPEN": 1, + "CLOSED": 2 + } + }, + "RepeatedFieldEncoding": { + "values": { + "REPEATED_FIELD_ENCODING_UNKNOWN": 0, + "PACKED": 1, + "EXPANDED": 2 + } + }, + "Utf8Validation": { + "values": { + "UTF8_VALIDATION_UNKNOWN": 0, + "VERIFY": 2, + "NONE": 3 + } + }, + "MessageEncoding": { + "values": { + "MESSAGE_ENCODING_UNKNOWN": 0, + "LENGTH_PREFIXED": 1, + "DELIMITED": 2 + } + }, + "JsonFormat": { + "values": { + "JSON_FORMAT_UNKNOWN": 0, + "ALLOW": 1, + "LEGACY_BEST_EFFORT": 2 + } + }, + "EnforceNamingStyle": { + "values": { + "ENFORCE_NAMING_STYLE_UNKNOWN": 0, + "STYLE2024": 1, + "STYLE_LEGACY": 2 + } + }, + "VisibilityFeature": { + "fields": {}, + "reserved": [ + [ + 1, + 536870911 + ] + ], + "nested": { + "DefaultSymbolVisibility": { + "values": { + "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN": 0, + "EXPORT_ALL": 1, + "EXPORT_TOP_LEVEL": 2, + "LOCAL_ALL": 3, + "STRICT": 4 + } + } + } + } + } + }, + "FeatureSetDefaults": { + "edition": "proto2", + "fields": { + "defaults": { + "rule": "repeated", + "type": "FeatureSetEditionDefault", + "id": 1 + }, + "minimumEdition": { + "type": "Edition", + "id": 4 + }, + "maximumEdition": { + "type": "Edition", + "id": 5 + } + }, + "nested": { + "FeatureSetEditionDefault": { + "fields": { + "edition": { + "type": "Edition", + "id": 3 + }, + "overridableFeatures": { + "type": "FeatureSet", + "id": 4 + }, + "fixedFeatures": { + "type": "FeatureSet", + "id": 5 + } + }, + "reserved": [ + [ + 1, + 1 + ], + [ + 2, + 2 + ], + "features" + ] + } + } + }, + "SourceCodeInfo": { + "edition": "proto2", + "fields": { + "location": { + "rule": "repeated", + "type": "Location", + "id": 1 + } + }, + "extensions": [ + [ + 536000000, + 536000000 + ] + ], + "nested": { + "Location": { + "fields": { + "path": { + "rule": "repeated", + "type": "int32", + "id": 1, + "options": { + "packed": true + } + }, + "span": { + "rule": "repeated", + "type": "int32", + "id": 2, + "options": { + "packed": true + } + }, + "leadingComments": { + "type": "string", + "id": 3 + }, + "trailingComments": { + "type": "string", + "id": 4 + }, + "leadingDetachedComments": { + "rule": "repeated", + "type": "string", + "id": 6 + } + } + } + } + }, + "GeneratedCodeInfo": { + "edition": "proto2", + "fields": { + "annotation": { + "rule": "repeated", + "type": "Annotation", + "id": 1 + } + }, + "nested": { + "Annotation": { + "fields": { + "path": { + "rule": "repeated", + "type": "int32", + "id": 1, + "options": { + "packed": true + } + }, + "sourceFile": { + "type": "string", + "id": 2 + }, + "begin": { + "type": "int32", + "id": 3 + }, + "end": { + "type": "int32", + "id": 4 + }, + "semantic": { + "type": "Semantic", + "id": 5 + } + }, + "nested": { + "Semantic": { + "values": { + "NONE": 0, + "SET": 1, + "ALIAS": 2 + } + } + } + } + } + }, + "SymbolVisibility": { + "edition": "proto2", + "values": { + "VISIBILITY_UNSET": 0, + "VISIBILITY_LOCAL": 1, + "VISIBILITY_EXPORT": 2 + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/node_modules/protobufjs/google/protobuf/descriptor.proto b/node_modules/protobufjs/google/protobuf/descriptor.proto new file mode 100644 index 0000000..1b130fd --- /dev/null +++ b/node_modules/protobufjs/google/protobuf/descriptor.proto @@ -0,0 +1,535 @@ +syntax = "proto2"; + +package google.protobuf; + +option go_package = "google.golang.org/protobuf/types/descriptorpb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "DescriptorProtos"; +option csharp_namespace = "Google.Protobuf.Reflection"; +option objc_class_prefix = "GPB"; +option cc_enable_arenas = true; +option optimize_for = "SPEED"; + +message FileDescriptorSet { + + repeated FileDescriptorProto file = 1; + + extensions 536000000; +} + +enum Edition { + + EDITION_UNKNOWN = 0; + EDITION_LEGACY = 900; + EDITION_PROTO2 = 998; + EDITION_PROTO3 = 999; + EDITION_2023 = 1000; + EDITION_2024 = 1001; + EDITION_1_TEST_ONLY = 1; + EDITION_2_TEST_ONLY = 2; + EDITION_99997_TEST_ONLY = 99997; + EDITION_99998_TEST_ONLY = 99998; + EDITION_99999_TEST_ONLY = 99999; + EDITION_MAX = 2147483647; +} + +message FileDescriptorProto { + + optional string name = 1; + optional string package = 2; + repeated string dependency = 3; + repeated int32 public_dependency = 10; + repeated int32 weak_dependency = 11; + repeated string option_dependency = 15; + repeated DescriptorProto message_type = 4; + repeated EnumDescriptorProto enum_type = 5; + repeated ServiceDescriptorProto service = 6; + repeated FieldDescriptorProto extension = 7; + optional FileOptions options = 8; + optional SourceCodeInfo source_code_info = 9; + optional string syntax = 12; + optional Edition edition = 14; +} + +message DescriptorProto { + + optional string name = 1; + repeated FieldDescriptorProto field = 2; + repeated FieldDescriptorProto extension = 6; + repeated DescriptorProto nested_type = 3; + repeated EnumDescriptorProto enum_type = 4; + repeated ExtensionRange extension_range = 5; + repeated OneofDescriptorProto oneof_decl = 8; + optional MessageOptions options = 7; + repeated ReservedRange reserved_range = 9; + repeated string reserved_name = 10; + optional SymbolVisibility visibility = 11; + + message ExtensionRange { + + optional int32 start = 1; + optional int32 end = 2; + optional ExtensionRangeOptions options = 3; + } + + message ReservedRange { + + optional int32 start = 1; + optional int32 end = 2; + } +} + +message ExtensionRangeOptions { + + repeated UninterpretedOption uninterpreted_option = 999; + repeated Declaration declaration = 2 [retention="RETENTION_SOURCE"]; + optional FeatureSet features = 50; + optional VerificationState verification = 3 [default=UNVERIFIED, retention="RETENTION_SOURCE"]; + + message Declaration { + + optional int32 number = 1; + optional string full_name = 2; + optional string type = 3; + optional bool reserved = 5; + optional bool repeated = 6; + + reserved 4; + } + + enum VerificationState { + + DECLARATION = 0; + UNVERIFIED = 1; + } + + extensions 1000 to max; +} + +message FieldDescriptorProto { + + optional string name = 1; + optional int32 number = 3; + optional Label label = 4; + optional Type type = 5; + optional string type_name = 6; + optional string extendee = 2; + optional string default_value = 7; + optional int32 oneof_index = 9; + optional string json_name = 10; + optional FieldOptions options = 8; + optional bool proto3_optional = 17; + + enum Type { + + TYPE_DOUBLE = 1; + TYPE_FLOAT = 2; + TYPE_INT64 = 3; + TYPE_UINT64 = 4; + TYPE_INT32 = 5; + TYPE_FIXED64 = 6; + TYPE_FIXED32 = 7; + TYPE_BOOL = 8; + TYPE_STRING = 9; + TYPE_GROUP = 10; + TYPE_MESSAGE = 11; + TYPE_BYTES = 12; + TYPE_UINT32 = 13; + TYPE_ENUM = 14; + TYPE_SFIXED32 = 15; + TYPE_SFIXED64 = 16; + TYPE_SINT32 = 17; + TYPE_SINT64 = 18; + } + + enum Label { + + LABEL_OPTIONAL = 1; + LABEL_REPEATED = 3; + LABEL_REQUIRED = 2; + } +} + +message OneofDescriptorProto { + + optional string name = 1; + optional OneofOptions options = 2; +} + +message EnumDescriptorProto { + + optional string name = 1; + repeated EnumValueDescriptorProto value = 2; + optional EnumOptions options = 3; + repeated EnumReservedRange reserved_range = 4; + repeated string reserved_name = 5; + optional SymbolVisibility visibility = 6; + + message EnumReservedRange { + + optional int32 start = 1; + optional int32 end = 2; + } +} + +message EnumValueDescriptorProto { + + optional string name = 1; + optional int32 number = 2; + optional EnumValueOptions options = 3; +} + +message ServiceDescriptorProto { + + optional string name = 1; + repeated MethodDescriptorProto method = 2; + optional ServiceOptions options = 3; +} + +message MethodDescriptorProto { + + optional string name = 1; + optional string input_type = 2; + optional string output_type = 3; + optional MethodOptions options = 4; + optional bool client_streaming = 5; + optional bool server_streaming = 6; +} + +message FileOptions { + + optional string java_package = 1; + optional string java_outer_classname = 8; + optional bool java_multiple_files = 10; + optional bool java_generate_equals_and_hash = 20 [deprecated=true]; + optional bool java_string_check_utf8 = 27; + optional OptimizeMode optimize_for = 9 [default=SPEED]; + optional string go_package = 11; + optional bool cc_generic_services = 16; + optional bool java_generic_services = 17; + optional bool py_generic_services = 18; + optional bool deprecated = 23; + optional bool cc_enable_arenas = 31 [default=true]; + optional string objc_class_prefix = 36; + optional string csharp_namespace = 37; + optional string swift_prefix = 39; + optional string php_class_prefix = 40; + optional string php_namespace = 41; + optional string php_metadata_namespace = 44; + optional string ruby_package = 45; + optional FeatureSet features = 50; + repeated UninterpretedOption uninterpreted_option = 999; + + enum OptimizeMode { + + SPEED = 1; + CODE_SIZE = 2; + LITE_RUNTIME = 3; + } + + extensions 1000 to max; + + reserved 42, 38; + reserved "php_generic_services"; +} + +message MessageOptions { + + optional bool message_set_wire_format = 1; + optional bool no_standard_descriptor_accessor = 2; + optional bool deprecated = 3; + optional bool map_entry = 7; + optional bool deprecated_legacy_json_field_conflicts = 11 [deprecated=true]; + optional FeatureSet features = 12; + repeated UninterpretedOption uninterpreted_option = 999; + + extensions 1000 to max; + + reserved 4, 5, 6, 8, 9; +} + +message FieldOptions { + + optional CType ctype = 1 [default=STRING]; + optional bool packed = 2; + optional JSType jstype = 6 [default=JS_NORMAL]; + optional bool lazy = 5; + optional bool unverified_lazy = 15; + optional bool deprecated = 3; + optional bool weak = 10 [deprecated=true]; + optional bool debug_redact = 16; + optional OptionRetention retention = 17; + repeated OptionTargetType targets = 19; + repeated EditionDefault edition_defaults = 20; + optional FeatureSet features = 21; + optional FeatureSupport feature_support = 22; + repeated UninterpretedOption uninterpreted_option = 999; + + enum CType { + + STRING = 0; + CORD = 1; + STRING_PIECE = 2; + } + + enum JSType { + + JS_NORMAL = 0; + JS_STRING = 1; + JS_NUMBER = 2; + } + + enum OptionRetention { + + RETENTION_UNKNOWN = 0; + RETENTION_RUNTIME = 1; + RETENTION_SOURCE = 2; + } + + enum OptionTargetType { + + TARGET_TYPE_UNKNOWN = 0; + TARGET_TYPE_FILE = 1; + TARGET_TYPE_EXTENSION_RANGE = 2; + TARGET_TYPE_MESSAGE = 3; + TARGET_TYPE_FIELD = 4; + TARGET_TYPE_ONEOF = 5; + TARGET_TYPE_ENUM = 6; + TARGET_TYPE_ENUM_ENTRY = 7; + TARGET_TYPE_SERVICE = 8; + TARGET_TYPE_METHOD = 9; + } + + message EditionDefault { + + optional Edition edition = 3; + optional string value = 2; + } + + message FeatureSupport { + + optional Edition edition_introduced = 1; + optional Edition edition_deprecated = 2; + optional string deprecation_warning = 3; + optional Edition edition_removed = 4; + } + + extensions 1000 to max; + + reserved 4, 18; +} + +message OneofOptions { + + optional FeatureSet features = 1; + repeated UninterpretedOption uninterpreted_option = 999; + + extensions 1000 to max; +} + +message EnumOptions { + + optional bool allow_alias = 2; + optional bool deprecated = 3; + optional bool deprecated_legacy_json_field_conflicts = 6 [deprecated=true]; + optional FeatureSet features = 7; + repeated UninterpretedOption uninterpreted_option = 999; + + extensions 1000 to max; + + reserved 5; +} + +message EnumValueOptions { + + optional bool deprecated = 1; + optional FeatureSet features = 2; + optional bool debug_redact = 3; + optional FieldOptions.FeatureSupport feature_support = 4; + repeated UninterpretedOption uninterpreted_option = 999; + + extensions 1000 to max; +} + +message ServiceOptions { + + optional FeatureSet features = 34; + optional bool deprecated = 33; + repeated UninterpretedOption uninterpreted_option = 999; + + extensions 1000 to max; +} + +message MethodOptions { + + optional bool deprecated = 33; + optional IdempotencyLevel idempotency_level = 34 [default=IDEMPOTENCY_UNKNOWN]; + optional FeatureSet features = 35; + repeated UninterpretedOption uninterpreted_option = 999; + + enum IdempotencyLevel { + + IDEMPOTENCY_UNKNOWN = 0; + NO_SIDE_EFFECTS = 1; + IDEMPOTENT = 2; + } + + extensions 1000 to max; +} + +message UninterpretedOption { + + repeated NamePart name = 2; + optional string identifier_value = 3; + optional uint64 positive_int_value = 4; + optional int64 negative_int_value = 5; + optional double double_value = 6; + optional bytes string_value = 7; + optional string aggregate_value = 8; + + message NamePart { + + required string name_part = 1; + required bool is_extension = 2; + } +} + +message FeatureSet { + + optional FieldPresence field_presence = 1 [retention="RETENTION_RUNTIME", targets="TARGET_TYPE_FILE", feature_support.edition_introduced="EDITION_2023", edition_defaults.edition="EDITION_2023", edition_defaults.value="EXPLICIT"]; + optional EnumType enum_type = 2 [retention="RETENTION_RUNTIME", targets="TARGET_TYPE_FILE", feature_support.edition_introduced="EDITION_2023", edition_defaults.edition="EDITION_PROTO3", edition_defaults.value="OPEN"]; + optional RepeatedFieldEncoding repeated_field_encoding = 3 [retention="RETENTION_RUNTIME", targets="TARGET_TYPE_FILE", feature_support.edition_introduced="EDITION_2023", edition_defaults.edition="EDITION_PROTO3", edition_defaults.value="PACKED"]; + optional Utf8Validation utf8_validation = 4 [retention="RETENTION_RUNTIME", targets="TARGET_TYPE_FILE", feature_support.edition_introduced="EDITION_2023", edition_defaults.edition="EDITION_PROTO3", edition_defaults.value="VERIFY"]; + optional MessageEncoding message_encoding = 5 [retention="RETENTION_RUNTIME", targets="TARGET_TYPE_FILE", feature_support.edition_introduced="EDITION_2023", edition_defaults.edition="EDITION_LEGACY", edition_defaults.value="LENGTH_PREFIXED"]; + optional JsonFormat json_format = 6 [retention="RETENTION_RUNTIME", targets="TARGET_TYPE_FILE", feature_support.edition_introduced="EDITION_2023", edition_defaults.edition="EDITION_PROTO3", edition_defaults.value="ALLOW"]; + optional EnforceNamingStyle enforce_naming_style = 7 [retention="RETENTION_SOURCE", targets="TARGET_TYPE_METHOD", feature_support.edition_introduced="EDITION_2024", edition_defaults.edition="EDITION_2024", edition_defaults.value="STYLE2024"]; + optional VisibilityFeature.DefaultSymbolVisibility default_symbol_visibility = 8 [retention="RETENTION_SOURCE", targets="TARGET_TYPE_FILE", feature_support.edition_introduced="EDITION_2024", edition_defaults.edition="EDITION_2024", edition_defaults.value="EXPORT_TOP_LEVEL"]; + + enum FieldPresence { + + FIELD_PRESENCE_UNKNOWN = 0; + EXPLICIT = 1; + IMPLICIT = 2; + LEGACY_REQUIRED = 3; + } + + enum EnumType { + + ENUM_TYPE_UNKNOWN = 0; + OPEN = 1; + CLOSED = 2; + } + + enum RepeatedFieldEncoding { + + REPEATED_FIELD_ENCODING_UNKNOWN = 0; + PACKED = 1; + EXPANDED = 2; + } + + enum Utf8Validation { + + UTF8_VALIDATION_UNKNOWN = 0; + VERIFY = 2; + NONE = 3; + } + + enum MessageEncoding { + + MESSAGE_ENCODING_UNKNOWN = 0; + LENGTH_PREFIXED = 1; + DELIMITED = 2; + } + + enum JsonFormat { + + JSON_FORMAT_UNKNOWN = 0; + ALLOW = 1; + LEGACY_BEST_EFFORT = 2; + } + + enum EnforceNamingStyle { + + ENFORCE_NAMING_STYLE_UNKNOWN = 0; + STYLE2024 = 1; + STYLE_LEGACY = 2; + } + + message VisibilityFeature { + + enum DefaultSymbolVisibility { + + DEFAULT_SYMBOL_VISIBILITY_UNKNOWN = 0; + EXPORT_ALL = 1; + EXPORT_TOP_LEVEL = 2; + LOCAL_ALL = 3; + STRICT = 4; + } + + reserved 1 to max; + } + + extensions 1000 to 9994, 9995 to 9999, 10000; + + reserved 999; +} + +message FeatureSetDefaults { + + repeated FeatureSetEditionDefault defaults = 1; + optional Edition minimum_edition = 4; + optional Edition maximum_edition = 5; + + message FeatureSetEditionDefault { + + optional Edition edition = 3; + optional FeatureSet overridable_features = 4; + optional FeatureSet fixed_features = 5; + + reserved 1, 2, "features"; + } +} + +message SourceCodeInfo { + + repeated Location location = 1; + + message Location { + + repeated int32 path = 1 [packed=true]; + repeated int32 span = 2 [packed=true]; + optional string leading_comments = 3; + optional string trailing_comments = 4; + repeated string leading_detached_comments = 6; + } + + extensions 536000000; +} + +message GeneratedCodeInfo { + + repeated Annotation annotation = 1; + + message Annotation { + + repeated int32 path = 1 [packed=true]; + optional string source_file = 2; + optional int32 begin = 3; + optional int32 end = 4; + optional Semantic semantic = 5; + + enum Semantic { + + NONE = 0; + SET = 1; + ALIAS = 2; + } + } +} + +enum SymbolVisibility { + + VISIBILITY_UNSET = 0; + VISIBILITY_LOCAL = 1; + VISIBILITY_EXPORT = 2; +} \ No newline at end of file diff --git a/node_modules/protobufjs/google/protobuf/source_context.json b/node_modules/protobufjs/google/protobuf/source_context.json new file mode 100644 index 0000000..51adb63 --- /dev/null +++ b/node_modules/protobufjs/google/protobuf/source_context.json @@ -0,0 +1,20 @@ +{ + "nested": { + "google": { + "nested": { + "protobuf": { + "nested": { + "SourceContext": { + "fields": { + "fileName": { + "type": "string", + "id": 1 + } + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/node_modules/protobufjs/google/protobuf/source_context.proto b/node_modules/protobufjs/google/protobuf/source_context.proto new file mode 100644 index 0000000..584d36c --- /dev/null +++ b/node_modules/protobufjs/google/protobuf/source_context.proto @@ -0,0 +1,7 @@ +syntax = "proto3"; + +package google.protobuf; + +message SourceContext { + string file_name = 1; +} diff --git a/node_modules/protobufjs/google/protobuf/type.json b/node_modules/protobufjs/google/protobuf/type.json new file mode 100644 index 0000000..fffa70d --- /dev/null +++ b/node_modules/protobufjs/google/protobuf/type.json @@ -0,0 +1,202 @@ +{ + "nested": { + "google": { + "nested": { + "protobuf": { + "nested": { + "Type": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "fields": { + "rule": "repeated", + "type": "Field", + "id": 2 + }, + "oneofs": { + "rule": "repeated", + "type": "string", + "id": 3 + }, + "options": { + "rule": "repeated", + "type": "Option", + "id": 4 + }, + "sourceContext": { + "type": "SourceContext", + "id": 5 + }, + "syntax": { + "type": "Syntax", + "id": 6 + } + } + }, + "Field": { + "fields": { + "kind": { + "type": "Kind", + "id": 1 + }, + "cardinality": { + "type": "Cardinality", + "id": 2 + }, + "number": { + "type": "int32", + "id": 3 + }, + "name": { + "type": "string", + "id": 4 + }, + "typeUrl": { + "type": "string", + "id": 6 + }, + "oneofIndex": { + "type": "int32", + "id": 7 + }, + "packed": { + "type": "bool", + "id": 8 + }, + "options": { + "rule": "repeated", + "type": "Option", + "id": 9 + }, + "jsonName": { + "type": "string", + "id": 10 + }, + "defaultValue": { + "type": "string", + "id": 11 + } + }, + "nested": { + "Kind": { + "values": { + "TYPE_UNKNOWN": 0, + "TYPE_DOUBLE": 1, + "TYPE_FLOAT": 2, + "TYPE_INT64": 3, + "TYPE_UINT64": 4, + "TYPE_INT32": 5, + "TYPE_FIXED64": 6, + "TYPE_FIXED32": 7, + "TYPE_BOOL": 8, + "TYPE_STRING": 9, + "TYPE_GROUP": 10, + "TYPE_MESSAGE": 11, + "TYPE_BYTES": 12, + "TYPE_UINT32": 13, + "TYPE_ENUM": 14, + "TYPE_SFIXED32": 15, + "TYPE_SFIXED64": 16, + "TYPE_SINT32": 17, + "TYPE_SINT64": 18 + } + }, + "Cardinality": { + "values": { + "CARDINALITY_UNKNOWN": 0, + "CARDINALITY_OPTIONAL": 1, + "CARDINALITY_REQUIRED": 2, + "CARDINALITY_REPEATED": 3 + } + } + } + }, + "Enum": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "enumvalue": { + "rule": "repeated", + "type": "EnumValue", + "id": 2 + }, + "options": { + "rule": "repeated", + "type": "Option", + "id": 3 + }, + "sourceContext": { + "type": "SourceContext", + "id": 4 + }, + "syntax": { + "type": "Syntax", + "id": 5 + } + } + }, + "EnumValue": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "number": { + "type": "int32", + "id": 2 + }, + "options": { + "rule": "repeated", + "type": "Option", + "id": 3 + } + } + }, + "Option": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "value": { + "type": "Any", + "id": 2 + } + } + }, + "Syntax": { + "values": { + "SYNTAX_PROTO2": 0, + "SYNTAX_PROTO3": 1 + } + }, + "Any": { + "fields": { + "type_url": { + "type": "string", + "id": 1 + }, + "value": { + "type": "bytes", + "id": 2 + } + } + }, + "SourceContext": { + "fields": { + "fileName": { + "type": "string", + "id": 1 + } + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/node_modules/protobufjs/google/protobuf/type.proto b/node_modules/protobufjs/google/protobuf/type.proto new file mode 100644 index 0000000..8ee445b --- /dev/null +++ b/node_modules/protobufjs/google/protobuf/type.proto @@ -0,0 +1,89 @@ +syntax = "proto3"; + +package google.protobuf; + +import "google/protobuf/any.proto"; +import "google/protobuf/source_context.proto"; + +message Type { + + string name = 1; + repeated Field fields = 2; + repeated string oneofs = 3; + repeated Option options = 4; + SourceContext source_context = 5; + Syntax syntax = 6; +} + +message Field { + + Kind kind = 1; + Cardinality cardinality = 2; + int32 number = 3; + string name = 4; + string type_url = 6; + int32 oneof_index = 7; + bool packed = 8; + repeated Option options = 9; + string json_name = 10; + string default_value = 11; + + enum Kind { + + TYPE_UNKNOWN = 0; + TYPE_DOUBLE = 1; + TYPE_FLOAT = 2; + TYPE_INT64 = 3; + TYPE_UINT64 = 4; + TYPE_INT32 = 5; + TYPE_FIXED64 = 6; + TYPE_FIXED32 = 7; + TYPE_BOOL = 8; + TYPE_STRING = 9; + TYPE_GROUP = 10; + TYPE_MESSAGE = 11; + TYPE_BYTES = 12; + TYPE_UINT32 = 13; + TYPE_ENUM = 14; + TYPE_SFIXED32 = 15; + TYPE_SFIXED64 = 16; + TYPE_SINT32 = 17; + TYPE_SINT64 = 18; + } + + enum Cardinality { + + CARDINALITY_UNKNOWN = 0; + CARDINALITY_OPTIONAL = 1; + CARDINALITY_REQUIRED = 2; + CARDINALITY_REPEATED = 3; + } +} + +message Enum { + + string name = 1; + repeated EnumValue enumvalue = 2; + repeated Option options = 3; + SourceContext source_context = 4; + Syntax syntax = 5; +} + +message EnumValue { + + string name = 1; + int32 number = 2; + repeated Option options = 3; +} + +message Option { + + string name = 1; + Any value = 2; +} + +enum Syntax { + + SYNTAX_PROTO2 = 0; + SYNTAX_PROTO3 = 1; +} diff --git a/node_modules/protobufjs/index.d.ts b/node_modules/protobufjs/index.d.ts new file mode 100644 index 0000000..9161111 --- /dev/null +++ b/node_modules/protobufjs/index.d.ts @@ -0,0 +1,2799 @@ +// DO NOT EDIT! This is a generated file. Edit the JSDoc in src/*.js instead and run 'npm run build:types'. + +export as namespace protobuf; + +/** + * Provides common type definitions. + * Can also be used to provide additional google types or your own custom types. + * @param name Short name as in `google/protobuf/[name].proto` or full file name + * @param json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition + */ +export function common(name: string, json: { [k: string]: any }): void; + +export namespace common { + + /** Properties of a google.protobuf.Any message. */ + interface IAny { + typeUrl?: string; + bytes?: Uint8Array; + } + + /** Properties of a google.protobuf.Duration message. */ + interface IDuration { + seconds?: (number|Long); + nanos?: number; + } + + /** Properties of a google.protobuf.Timestamp message. */ + interface ITimestamp { + seconds?: (number|Long); + nanos?: number; + } + + /** Properties of a google.protobuf.Empty message. */ + interface IEmpty { + } + + /** Properties of a google.protobuf.Struct message. */ + interface IStruct { + fields?: { [k: string]: IValue }; + } + + /** Properties of a google.protobuf.Value message. */ + interface IValue { + kind?: string; + nullValue?: 0; + numberValue?: number; + stringValue?: string; + boolValue?: boolean; + structValue?: IStruct; + listValue?: IListValue; + } + + /** Properties of a google.protobuf.ListValue message. */ + interface IListValue { + values?: IValue[]; + } + + /** Properties of a google.protobuf.DoubleValue message. */ + interface IDoubleValue { + value?: number; + } + + /** Properties of a google.protobuf.FloatValue message. */ + interface IFloatValue { + value?: number; + } + + /** Properties of a google.protobuf.Int64Value message. */ + interface IInt64Value { + value?: (number|Long); + } + + /** Properties of a google.protobuf.UInt64Value message. */ + interface IUInt64Value { + value?: (number|Long); + } + + /** Properties of a google.protobuf.Int32Value message. */ + interface IInt32Value { + value?: number; + } + + /** Properties of a google.protobuf.UInt32Value message. */ + interface IUInt32Value { + value?: number; + } + + /** Properties of a google.protobuf.BoolValue message. */ + interface IBoolValue { + value?: boolean; + } + + /** Properties of a google.protobuf.StringValue message. */ + interface IStringValue { + value?: string; + } + + /** Properties of a google.protobuf.BytesValue message. */ + interface IBytesValue { + value?: Uint8Array; + } + + /** + * Gets the root definition of the specified common proto file. + * + * Bundled definitions are: + * - google/protobuf/any.proto + * - google/protobuf/duration.proto + * - google/protobuf/empty.proto + * - google/protobuf/field_mask.proto + * - google/protobuf/struct.proto + * - google/protobuf/timestamp.proto + * - google/protobuf/wrappers.proto + * + * @param file Proto file name + * @returns Root definition or `null` if not defined + */ + function get(file: string): (INamespace|null); +} + +/** Runtime message from/to plain object converters. */ +export namespace converter { + + /** + * Generates a plain object to runtime message converter specific to the specified message type. + * @param mtype Message type + * @returns Codegen instance + */ + function fromObject(mtype: Type): Codegen; + + /** + * Generates a runtime message to plain object converter specific to the specified message type. + * @param mtype Message type + * @returns Codegen instance + */ + function toObject(mtype: Type): Codegen; +} + +/** + * Generates a decoder specific to the specified message type. + * @param mtype Message type + * @returns Codegen instance + */ +export function decoder(mtype: Type): Codegen; + +/** + * Generates an encoder specific to the specified message type. + * @param mtype Message type + * @returns Codegen instance + */ +export function encoder(mtype: Type): Codegen; + +/** Reflected enum. */ +export class Enum extends ReflectionObject { + + /** + * Constructs a new enum instance. + * @param name Unique name within its namespace + * @param [values] Enum values as an object, by name + * @param [options] Declared options + * @param [comment] The comment for this enum + * @param [comments] The value comments for this enum + * @param [valuesOptions] The value options for this enum + */ + constructor(name: string, values?: { [k: string]: number }, options?: { [k: string]: any }, comment?: string, comments?: { [k: string]: string }, valuesOptions?: ({ [k: string]: { [k: string]: any } }|undefined)); + + /** Enum values by id. */ + public valuesById: { [k: number]: string }; + + /** Enum values by name. */ + public values: { [k: string]: number }; + + /** Enum comment text. */ + public comment: (string|null); + + /** Value comment texts, if any. */ + public comments: { [k: string]: string }; + + /** Values options, if any */ + public valuesOptions?: { [k: string]: { [k: string]: any } }; + + /** Resolved values features, if any */ + public _valuesFeatures?: { [k: string]: { [k: string]: any } }; + + /** Reserved ranges, if any. */ + public reserved: (number[]|string)[]; + + /** + * Constructs an enum from an enum descriptor. + * @param name Enum name + * @param json Enum descriptor + * @returns Created enum + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: IEnum): Enum; + + /** + * Converts this enum to an enum descriptor. + * @param [toJSONOptions] JSON conversion options + * @returns Enum descriptor + */ + public toJSON(toJSONOptions?: IToJSONOptions): IEnum; + + /** + * Adds a value to this enum. + * @param name Value name + * @param id Value id + * @param [comment] Comment, if any + * @param {Object.|undefined} [options] Options, if any + * @returns `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a value with this name or id + */ + public add(name: string, id: number, comment?: string, options?: ({ [k: string]: any }|undefined)): Enum; + + /** + * Removes a value from this enum + * @param name Value name + * @returns `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `name` is not a name of this enum + */ + public remove(name: string): Enum; + + /** + * Tests if the specified id is reserved. + * @param id Id to test + * @returns `true` if reserved, otherwise `false` + */ + public isReservedId(id: number): boolean; + + /** + * Tests if the specified name is reserved. + * @param name Name to test + * @returns `true` if reserved, otherwise `false` + */ + public isReservedName(name: string): boolean; +} + +/** Enum descriptor. */ +export interface IEnum { + + /** Enum values */ + values: { [k: string]: number }; + + /** Enum options */ + options?: { [k: string]: any }; +} + +/** Reflected message field. */ +export class Field extends FieldBase { + + /** + * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class. + * @param name Unique name within its namespace + * @param id Unique id within its namespace + * @param type Value type + * @param [rule="optional"] Field rule + * @param [extend] Extended type if different from parent + * @param [options] Declared options + */ + constructor(name: string, id: number, type: string, rule?: (string|{ [k: string]: any }), extend?: (string|{ [k: string]: any }), options?: { [k: string]: any }); + + /** + * Constructs a field from a field descriptor. + * @param name Field name + * @param json Field descriptor + * @returns Created field + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: IField): Field; + + /** Determines whether this field is required. */ + public readonly required: boolean; + + /** Determines whether this field is not required. */ + public readonly optional: boolean; + + /** + * Determines whether this field uses tag-delimited encoding. In proto2 this + * corresponded to group syntax. + */ + public readonly delimited: boolean; + + /** Determines whether this field is packed. Only relevant when repeated. */ + public readonly packed: boolean; + + /** Determines whether this field tracks presence. */ + public readonly hasPresence: boolean; + + /** + * Field decorator (TypeScript). + * @param fieldId Field id + * @param fieldType Field type + * @param [fieldRule="optional"] Field rule + * @param [defaultValue] Default value + * @returns Decorator function + */ + public static d(fieldId: number, fieldType: ("double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"string"|"bool"|"bytes"|object), fieldRule?: ("optional"|"required"|"repeated"), defaultValue?: T): FieldDecorator; + + /** + * Field decorator (TypeScript). + * @param fieldId Field id + * @param fieldType Field type + * @param [fieldRule="optional"] Field rule + * @returns Decorator function + */ + public static d>(fieldId: number, fieldType: (Constructor|string), fieldRule?: ("optional"|"required"|"repeated")): FieldDecorator; +} + +/** Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions. */ +export class FieldBase extends ReflectionObject { + + /** + * Not an actual constructor. Use {@link Field} instead. + * @param name Unique name within its namespace + * @param id Unique id within its namespace + * @param type Value type + * @param [rule="optional"] Field rule + * @param [extend] Extended type if different from parent + * @param [options] Declared options + * @param [comment] Comment associated with this field + */ + constructor(name: string, id: number, type: string, rule?: (string|{ [k: string]: any }), extend?: (string|{ [k: string]: any }), options?: { [k: string]: any }, comment?: string); + + /** Field type. */ + public type: string; + + /** Unique field id. */ + public id: number; + + /** Extended type if different from parent. */ + public extend?: string; + + /** Whether this field is repeated. */ + public repeated: boolean; + + /** Whether this field is a map or not. */ + public map: boolean; + + /** Message this field belongs to. */ + public message: (Type|null); + + /** OneOf this field belongs to, if any, */ + public partOf: (OneOf|null); + + /** The field type's default value. */ + public typeDefault: any; + + /** The field's default value on prototypes. */ + public defaultValue: any; + + /** Whether this field's value should be treated as a long. */ + public long: boolean; + + /** Whether this field's value is a buffer. */ + public bytes: boolean; + + /** Resolved type if not a basic type. */ + public resolvedType: (Type|Enum|null); + + /** Sister-field within the extended type if a declaring extension field. */ + public extensionField: (Field|null); + + /** Sister-field within the declaring namespace if an extended field. */ + public declaringField: (Field|null); + + /** Comment for this field. */ + public comment: (string|null); + + /** + * Converts this field to a field descriptor. + * @param [toJSONOptions] JSON conversion options + * @returns Field descriptor + */ + public toJSON(toJSONOptions?: IToJSONOptions): IField; + + /** + * Resolves this field's type references. + * @returns `this` + * @throws {Error} If any reference cannot be resolved + */ + public resolve(): Field; + + /** + * Infers field features from legacy syntax that may have been specified differently. + * in older editions. + * @param edition The edition this proto is on, or undefined if pre-editions + * @returns The feature values to override + */ + public _inferLegacyProtoFeatures(edition: (string|undefined)): object; +} + +/** Field descriptor. */ +export interface IField { + + /** Field rule */ + rule?: string; + + /** Field type */ + type: string; + + /** Field id */ + id: number; + + /** Field options */ + options?: { [k: string]: any }; +} + +/** Extension field descriptor. */ +export interface IExtensionField extends IField { + + /** Extended type */ + extend: string; +} + +/** + * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript). + * @param prototype Target prototype + * @param fieldName Field name + */ +type FieldDecorator = (prototype: object, fieldName: string) => void; + +/** + * A node-style callback as used by {@link load} and {@link Root#load}. + * @param error Error, if any, otherwise `null` + * @param [root] Root, if there hasn't been an error + */ +type LoadCallback = (error: (Error|null), root?: Root) => void; + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. + * @param filename One or multiple files to load + * @param root Root namespace, defaults to create a new one if omitted. + * @param callback Callback function + * @see {@link Root#load} + */ +export function load(filename: (string|string[]), root: Root, callback: LoadCallback): void; + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. + * @param filename One or multiple files to load + * @param callback Callback function + * @see {@link Root#load} + */ +export function load(filename: (string|string[]), callback: LoadCallback): void; + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise. + * @param filename One or multiple files to load + * @param [root] Root namespace, defaults to create a new one if omitted. + * @returns Promise + * @see {@link Root#load} + */ +export function load(filename: (string|string[]), root?: Root): Promise; + +/** + * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only). + * @param filename One or multiple files to load + * @param [root] Root namespace, defaults to create a new one if omitted. + * @returns Root namespace + * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid + * @see {@link Root#loadSync} + */ +export function loadSync(filename: (string|string[]), root?: Root): Root; + +/** Build type, one of `"full"`, `"light"` or `"minimal"`. */ +export const build: string; + +/** Reconfigures the library according to the environment. */ +export function configure(): void; + +/** Reflected map field. */ +export class MapField extends FieldBase { + + /** + * Constructs a new map field instance. + * @param name Unique name within its namespace + * @param id Unique id within its namespace + * @param keyType Key type + * @param type Value type + * @param [options] Declared options + * @param [comment] Comment associated with this field + */ + constructor(name: string, id: number, keyType: string, type: string, options?: { [k: string]: any }, comment?: string); + + /** Key type. */ + public keyType: string; + + /** Resolved key type if not a basic type. */ + public resolvedKeyType: (ReflectionObject|null); + + /** + * Constructs a map field from a map field descriptor. + * @param name Field name + * @param json Map field descriptor + * @returns Created map field + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: IMapField): MapField; + + /** + * Converts this map field to a map field descriptor. + * @param [toJSONOptions] JSON conversion options + * @returns Map field descriptor + */ + public toJSON(toJSONOptions?: IToJSONOptions): IMapField; + + /** + * Map field decorator (TypeScript). + * @param fieldId Field id + * @param fieldKeyType Field key type + * @param fieldValueType Field value type + * @returns Decorator function + */ + public static d }>(fieldId: number, fieldKeyType: ("int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"), fieldValueType: ("double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"|"bytes"|object|Constructor<{}>)): FieldDecorator; +} + +/** Map field descriptor. */ +export interface IMapField extends IField { + + /** Key type */ + keyType: string; +} + +/** Extension map field descriptor. */ +export interface IExtensionMapField extends IMapField { + + /** Extended type */ + extend: string; +} + +/** Abstract runtime message. */ +export class Message { + + /** + * Constructs a new message instance. + * @param [properties] Properties to set + */ + constructor(properties?: Properties); + + /** Reference to the reflected type. */ + public static readonly $type: Type; + + /** Reference to the reflected type. */ + public readonly $type: Type; + + /** + * Creates a new message of this type using the specified properties. + * @param [properties] Properties to set + * @returns Message instance + */ + public static create>(this: Constructor, properties?: { [k: string]: any }): Message; + + /** + * Encodes a message of this type. + * @param message Message to encode + * @param [writer] Writer to use + * @returns Writer + */ + public static encode>(this: Constructor, message: (T|{ [k: string]: any }), writer?: Writer): Writer; + + /** + * Encodes a message of this type preceeded by its length as a varint. + * @param message Message to encode + * @param [writer] Writer to use + * @returns Writer + */ + public static encodeDelimited>(this: Constructor, message: (T|{ [k: string]: any }), writer?: Writer): Writer; + + /** + * Decodes a message of this type. + * @param reader Reader or buffer to decode + * @returns Decoded message + */ + public static decode>(this: Constructor, reader: (Reader|Uint8Array)): T; + + /** + * Decodes a message of this type preceeded by its length as a varint. + * @param reader Reader or buffer to decode + * @returns Decoded message + */ + public static decodeDelimited>(this: Constructor, reader: (Reader|Uint8Array)): T; + + /** + * Verifies a message of this type. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a new message of this type from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Message instance + */ + public static fromObject>(this: Constructor, object: { [k: string]: any }): T; + + /** + * Creates a plain object from a message of this type. Also converts values to other types if specified. + * @param message Message instance + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject>(this: Constructor, message: T, options?: IConversionOptions): { [k: string]: any }; + + /** + * Converts this message to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; +} + +/** Reflected service method. */ +export class Method extends ReflectionObject { + + /** + * Constructs a new service method instance. + * @param name Method name + * @param type Method type, usually `"rpc"` + * @param requestType Request message type + * @param responseType Response message type + * @param [requestStream] Whether the request is streamed + * @param [responseStream] Whether the response is streamed + * @param [options] Declared options + * @param [comment] The comment for this method + * @param [parsedOptions] Declared options, properly parsed into an object + */ + constructor(name: string, type: (string|undefined), requestType: string, responseType: string, requestStream?: (boolean|{ [k: string]: any }), responseStream?: (boolean|{ [k: string]: any }), options?: { [k: string]: any }, comment?: string, parsedOptions?: { [k: string]: any }); + + /** Method type. */ + public type: string; + + /** Request type. */ + public requestType: string; + + /** Whether requests are streamed or not. */ + public requestStream?: boolean; + + /** Response type. */ + public responseType: string; + + /** Whether responses are streamed or not. */ + public responseStream?: boolean; + + /** Resolved request type. */ + public resolvedRequestType: (Type|null); + + /** Resolved response type. */ + public resolvedResponseType: (Type|null); + + /** Comment for this method */ + public comment: (string|null); + + /** Options properly parsed into an object */ + public parsedOptions: any; + + /** + * Constructs a method from a method descriptor. + * @param name Method name + * @param json Method descriptor + * @returns Created method + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: IMethod): Method; + + /** + * Converts this method to a method descriptor. + * @param [toJSONOptions] JSON conversion options + * @returns Method descriptor + */ + public toJSON(toJSONOptions?: IToJSONOptions): IMethod; +} + +/** Method descriptor. */ +export interface IMethod { + + /** Method type */ + type?: string; + + /** Request type */ + requestType: string; + + /** Response type */ + responseType: string; + + /** Whether requests are streamed */ + requestStream?: boolean; + + /** Whether responses are streamed */ + responseStream?: boolean; + + /** Method options */ + options?: { [k: string]: any }; + + /** Method comments */ + comment: string; + + /** Method options properly parsed into an object */ + parsedOptions?: { [k: string]: any }; +} + +/** Reflected namespace. */ +export class Namespace extends NamespaceBase { + + /** + * Constructs a new namespace instance. + * @param name Namespace name + * @param [options] Declared options + */ + constructor(name: string, options?: { [k: string]: any }); + + /** + * Constructs a namespace from JSON. + * @param name Namespace name + * @param json JSON object + * @returns Created namespace + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: { [k: string]: any }): Namespace; + + /** + * Converts an array of reflection objects to JSON. + * @param array Object array + * @param [toJSONOptions] JSON conversion options + * @returns JSON object or `undefined` when array is empty + */ + public static arrayToJSON(array: ReflectionObject[], toJSONOptions?: IToJSONOptions): ({ [k: string]: any }|undefined); + + /** + * Tests if the specified id is reserved. + * @param reserved Array of reserved ranges and names + * @param id Id to test + * @returns `true` if reserved, otherwise `false` + */ + public static isReservedId(reserved: ((number[]|string)[]|undefined), id: number): boolean; + + /** + * Tests if the specified name is reserved. + * @param reserved Array of reserved ranges and names + * @param name Name to test + * @returns `true` if reserved, otherwise `false` + */ + public static isReservedName(reserved: ((number[]|string)[]|undefined), name: string): boolean; +} + +/** Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions. */ +export abstract class NamespaceBase extends ReflectionObject { + + /** Nested objects by name. */ + public nested?: { [k: string]: ReflectionObject }; + + /** Whether or not objects contained in this namespace need feature resolution. */ + protected _needsRecursiveFeatureResolution: boolean; + + /** Whether or not objects contained in this namespace need a resolve. */ + protected _needsRecursiveResolve: boolean; + + /** Nested objects of this namespace as an array for iteration. */ + public readonly nestedArray: ReflectionObject[]; + + /** + * Converts this namespace to a namespace descriptor. + * @param [toJSONOptions] JSON conversion options + * @returns Namespace descriptor + */ + public toJSON(toJSONOptions?: IToJSONOptions): INamespace; + + /** + * Adds nested objects to this namespace from nested object descriptors. + * @param nestedJson Any nested object descriptors + * @returns `this` + */ + public addJSON(nestedJson: { [k: string]: AnyNestedObject }): Namespace; + + /** + * Gets the nested object of the specified name. + * @param name Nested object name + * @returns The reflection object or `null` if it doesn't exist + */ + public get(name: string): (ReflectionObject|null); + + /** + * Gets the values of the nested {@link Enum|enum} of the specified name. + * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`. + * @param name Nested enum name + * @returns Enum values + * @throws {Error} If there is no such enum + */ + public getEnum(name: string): { [k: string]: number }; + + /** + * Adds a nested object to this namespace. + * @param object Nested object to add + * @returns `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a nested object with this name + */ + public add(object: ReflectionObject): Namespace; + + /** + * Removes a nested object from this namespace. + * @param object Nested object to remove + * @returns `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `object` is not a member of this namespace + */ + public remove(object: ReflectionObject): Namespace; + + /** + * Defines additial namespaces within this one if not yet existing. + * @param path Path to create + * @param [json] Nested types to create from JSON + * @returns Pointer to the last namespace created or `this` if path is empty + */ + public define(path: (string|string[]), json?: any): Namespace; + + /** + * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost. + * @returns `this` + */ + public resolveAll(): Namespace; + + /** + * Recursively looks up the reflection object matching the specified path in the scope of this namespace. + * @param path Path to look up + * @param filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc. + * @param [parentAlreadyChecked=false] If known, whether the parent has already been checked + * @returns Looked up object or `null` if none could be found + */ + public lookup(path: (string|string[]), filterTypes: (any|any[]), parentAlreadyChecked?: boolean): (ReflectionObject|null); + + /** + * Looks up the reflection object at the specified path, relative to this namespace. + * @param path Path to look up + * @param [parentAlreadyChecked=false] Whether the parent has already been checked + * @returns Looked up object or `null` if none could be found + */ + public lookup(path: (string|string[]), parentAlreadyChecked?: boolean): (ReflectionObject|null); + + /** + * Looks up the {@link Type|type} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param path Path to look up + * @returns Looked up type + * @throws {Error} If `path` does not point to a type + */ + public lookupType(path: (string|string[])): Type; + + /** + * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param path Path to look up + * @returns Looked up enum + * @throws {Error} If `path` does not point to an enum + */ + public lookupEnum(path: (string|string[])): Enum; + + /** + * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param path Path to look up + * @returns Looked up type or enum + * @throws {Error} If `path` does not point to a type or enum + */ + public lookupTypeOrEnum(path: (string|string[])): Type; + + /** + * Looks up the {@link Service|service} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param path Path to look up + * @returns Looked up service + * @throws {Error} If `path` does not point to a service + */ + public lookupService(path: (string|string[])): Service; +} + +/** Namespace descriptor. */ +export interface INamespace { + + /** Namespace options */ + options?: { [k: string]: any }; + + /** Nested object descriptors */ + nested?: { [k: string]: AnyNestedObject }; +} + +/** Any extension field descriptor. */ +type AnyExtensionField = (IExtensionField|IExtensionMapField); + +/** Any nested object descriptor. */ +type AnyNestedObject = (IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf); + +/** Base class of all reflection objects. */ +export abstract class ReflectionObject { + + /** Options. */ + public options?: { [k: string]: any }; + + /** Parsed Options. */ + public parsedOptions?: { [k: string]: any[] }; + + /** Unique name within its namespace. */ + public name: string; + + /** Parent namespace. */ + public parent: (Namespace|null); + + /** Whether already resolved or not. */ + public resolved: boolean; + + /** Comment text, if any. */ + public comment: (string|null); + + /** Defining file name. */ + public filename: (string|null); + + /** Reference to the root namespace. */ + public readonly root: Root; + + /** Full name including leading dot. */ + public readonly fullName: string; + + /** + * Converts this reflection object to its descriptor representation. + * @returns Descriptor + */ + public toJSON(): { [k: string]: any }; + + /** + * Called when this object is added to a parent. + * @param parent Parent added to + */ + public onAdd(parent: ReflectionObject): void; + + /** + * Called when this object is removed from a parent. + * @param parent Parent removed from + */ + public onRemove(parent: ReflectionObject): void; + + /** + * Resolves this objects type references. + * @returns `this` + */ + public resolve(): ReflectionObject; + + /** + * Resolves this objects editions features. + * @param edition The edition we're currently resolving for. + * @returns `this` + */ + public _resolveFeaturesRecursive(edition: string): ReflectionObject; + + /** + * Resolves child features from parent features + * @param edition The edition we're currently resolving for. + */ + public _resolveFeatures(edition: string): void; + + /** + * Infers features from legacy syntax that may have been specified differently. + * in older editions. + * @param edition The edition this proto is on, or undefined if pre-editions + * @returns The feature values to override + */ + public _inferLegacyProtoFeatures(edition: (string|undefined)): object; + + /** + * Gets an option value. + * @param name Option name + * @returns Option value or `undefined` if not set + */ + public getOption(name: string): any; + + /** + * Sets an option. + * @param name Option name + * @param value Option value + * @param [ifNotSet] Sets the option only if it isn't currently set + * @returns `this` + */ + public setOption(name: string, value: any, ifNotSet?: (boolean|undefined)): ReflectionObject; + + /** + * Sets a parsed option. + * @param name parsed Option name + * @param value Option value + * @param propName dot '.' delimited full path of property within the option to set. if undefined\empty, will add a new option with that value + * @returns `this` + */ + public setParsedOption(name: string, value: any, propName: string): ReflectionObject; + + /** + * Sets multiple options. + * @param options Options to set + * @param [ifNotSet] Sets an option only if it isn't currently set + * @returns `this` + */ + public setOptions(options: { [k: string]: any }, ifNotSet?: boolean): ReflectionObject; + + /** + * Converts this instance to its string representation. + * @returns Class name[, space, full name] + */ + public toString(): string; + + /** + * Converts the edition this object is pinned to for JSON format. + * @returns The edition string for JSON representation + */ + public _editionToJSON(): (string|undefined); +} + +/** Reflected oneof. */ +export class OneOf extends ReflectionObject { + + /** + * Constructs a new oneof instance. + * @param name Oneof name + * @param [fieldNames] Field names + * @param [options] Declared options + * @param [comment] Comment associated with this field + */ + constructor(name: string, fieldNames?: (string[]|{ [k: string]: any }), options?: { [k: string]: any }, comment?: string); + + /** Field names that belong to this oneof. */ + public oneof: string[]; + + /** Fields that belong to this oneof as an array for iteration. */ + public readonly fieldsArray: Field[]; + + /** Comment for this field. */ + public comment: (string|null); + + /** + * Constructs a oneof from a oneof descriptor. + * @param name Oneof name + * @param json Oneof descriptor + * @returns Created oneof + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: IOneOf): OneOf; + + /** + * Converts this oneof to a oneof descriptor. + * @param [toJSONOptions] JSON conversion options + * @returns Oneof descriptor + */ + public toJSON(toJSONOptions?: IToJSONOptions): IOneOf; + + /** + * Adds a field to this oneof and removes it from its current parent, if any. + * @param field Field to add + * @returns `this` + */ + public add(field: Field): OneOf; + + /** + * Removes a field from this oneof and puts it back to the oneof's parent. + * @param field Field to remove + * @returns `this` + */ + public remove(field: Field): OneOf; + + /** + * Determines whether this field corresponds to a synthetic oneof created for + * a proto3 optional field. No behavioral logic should depend on this, but it + * can be relevant for reflection. + */ + public readonly isProto3Optional: boolean; + + /** + * OneOf decorator (TypeScript). + * @param fieldNames Field names + * @returns Decorator function + */ + public static d(...fieldNames: string[]): OneOfDecorator; +} + +/** Oneof descriptor. */ +export interface IOneOf { + + /** Oneof field names */ + oneof: string[]; + + /** Oneof options */ + options?: { [k: string]: any }; +} + +/** + * Decorator function as returned by {@link OneOf.d} (TypeScript). + * @param prototype Target prototype + * @param oneofName OneOf name + */ +type OneOfDecorator = (prototype: object, oneofName: string) => void; + +/** + * Parses the given .proto source and returns an object with the parsed contents. + * @param source Source contents + * @param [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns Parser result + */ +export function parse(source: string, options?: IParseOptions): IParserResult; + +/** Result object returned from {@link parse}. */ +export interface IParserResult { + + /** Package name, if declared */ + package: (string|undefined); + + /** Imports, if any */ + imports: (string[]|undefined); + + /** Weak imports, if any */ + weakImports: (string[]|undefined); + + /** Populated root instance */ + root: Root; +} + +/** Options modifying the behavior of {@link parse}. */ +export interface IParseOptions { + + /** Keeps field casing instead of converting to camel case */ + keepCase?: boolean; + + /** Recognize double-slash comments in addition to doc-block comments. */ + alternateCommentMode?: boolean; + + /** Use trailing comment when both leading comment and trailing comment exist. */ + preferTrailingComment?: boolean; +} + +/** Options modifying the behavior of JSON serialization. */ +export interface IToJSONOptions { + + /** Serializes comments. */ + keepComments?: boolean; +} + +/** + * Parses the given .proto source and returns an object with the parsed contents. + * @param source Source contents + * @param root Root to populate + * @param [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns Parser result + */ +export function parse(source: string, root: Root, options?: IParseOptions): IParserResult; + +/** Wire format reader using `Uint8Array` if available, otherwise `Array`. */ +export class Reader { + + /** + * Constructs a new reader instance using the specified buffer. + * @param buffer Buffer to read from + */ + constructor(buffer: Uint8Array); + + /** Read buffer. */ + public buf: Uint8Array; + + /** Read buffer position. */ + public pos: number; + + /** Read buffer length. */ + public len: number; + + /** + * Creates a new reader using the specified buffer. + * @param buffer Buffer to read from + * @returns A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader} + * @throws {Error} If `buffer` is not a valid buffer + */ + public static create(buffer: (Uint8Array|Buffer)): (Reader|BufferReader); + + /** + * Reads a varint as an unsigned 32 bit value. + * @returns Value read + */ + public uint32(): number; + + /** + * Reads a varint as a signed 32 bit value. + * @returns Value read + */ + public int32(): number; + + /** + * Reads a zig-zag encoded varint as a signed 32 bit value. + * @returns Value read + */ + public sint32(): number; + + /** + * Reads a varint as a signed 64 bit value. + * @returns Value read + */ + public int64(): Long; + + /** + * Reads a varint as an unsigned 64 bit value. + * @returns Value read + */ + public uint64(): Long; + + /** + * Reads a zig-zag encoded varint as a signed 64 bit value. + * @returns Value read + */ + public sint64(): Long; + + /** + * Reads a varint as a boolean. + * @returns Value read + */ + public bool(): boolean; + + /** + * Reads fixed 32 bits as an unsigned 32 bit integer. + * @returns Value read + */ + public fixed32(): number; + + /** + * Reads fixed 32 bits as a signed 32 bit integer. + * @returns Value read + */ + public sfixed32(): number; + + /** + * Reads fixed 64 bits. + * @returns Value read + */ + public fixed64(): Long; + + /** + * Reads zig-zag encoded fixed 64 bits. + * @returns Value read + */ + public sfixed64(): Long; + + /** + * Reads a float (32 bit) as a number. + * @returns Value read + */ + public float(): number; + + /** + * Reads a double (64 bit float) as a number. + * @returns Value read + */ + public double(): number; + + /** + * Reads a sequence of bytes preceeded by its length as a varint. + * @returns Value read + */ + public bytes(): Uint8Array; + + /** + * Reads a string preceeded by its byte length as a varint. + * @returns Value read + */ + public string(): string; + + /** + * Skips the specified number of bytes if specified, otherwise skips a varint. + * @param [length] Length if known, otherwise a varint is assumed + * @returns `this` + */ + public skip(length?: number): Reader; + + /** + * Skips the next element of the specified wire type. + * @param wireType Wire type received + * @returns `this` + */ + public skipType(wireType: number): Reader; +} + +/** Wire format reader using node buffers. */ +export class BufferReader extends Reader { + + /** + * Constructs a new buffer reader instance. + * @param buffer Buffer to read from + */ + constructor(buffer: Buffer); + + /** + * Reads a sequence of bytes preceeded by its length as a varint. + * @returns Value read + */ + public bytes(): Buffer; +} + +/** Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together. */ +export class Root extends NamespaceBase { + + /** + * Constructs a new root namespace instance. + * @param [options] Top level options + */ + constructor(options?: { [k: string]: any }); + + /** Deferred extension fields. */ + public deferred: Field[]; + + /** Resolved file names of loaded files. */ + public files: string[]; + + /** + * Loads a namespace descriptor into a root namespace. + * @param json Namespace descriptor + * @param [root] Root namespace, defaults to create a new one if omitted + * @returns Root namespace + */ + public static fromJSON(json: INamespace, root?: Root): Root; + + /** + * Resolves the path of an imported file, relative to the importing origin. + * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories. + * @param origin The file name of the importing file + * @param target The file name being imported + * @returns Resolved path to `target` or `null` to skip the file + */ + public resolvePath(origin: string, target: string): (string|null); + + /** + * Fetch content from file path or url + * This method exists so you can override it with your own logic. + * @param path File path or url + * @param callback Callback function + */ + public fetch(path: string, callback: FetchCallback): void; + + /** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. + * @param filename Names of one or multiple files to load + * @param options Parse options + * @param callback Callback function + */ + public load(filename: (string|string[]), options: IParseOptions, callback: LoadCallback): void; + + /** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. + * @param filename Names of one or multiple files to load + * @param callback Callback function + */ + public load(filename: (string|string[]), callback: LoadCallback): void; + + /** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise. + * @param filename Names of one or multiple files to load + * @param [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns Promise + */ + public load(filename: (string|string[]), options?: IParseOptions): Promise; + + /** + * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only). + * @param filename Names of one or multiple files to load + * @param [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns Root namespace + * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid + */ + public loadSync(filename: (string|string[]), options?: IParseOptions): Root; +} + +/** + * Named roots. + * This is where pbjs stores generated structures (the option `-r, --root` specifies a name). + * Can also be used manually to make roots available across modules. + */ +export let roots: { [k: string]: Root }; + +/** Streaming RPC helpers. */ +export namespace rpc { + + /** + * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}. + * + * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`. + * @param error Error, if any + * @param [response] Response message + */ + type ServiceMethodCallback> = (error: (Error|null), response?: TRes) => void; + + /** + * A service method part of a {@link rpc.Service} as created by {@link Service.create}. + * @param request Request message or plain object + * @param [callback] Node-style callback called with the error, if any, and the response message + * @returns Promise if `callback` has been omitted, otherwise `undefined` + */ + type ServiceMethod, TRes extends Message> = (request: (TReq|Properties), callback?: rpc.ServiceMethodCallback) => Promise>; + + /** An RPC service as returned by {@link Service#create}. */ + class Service extends util.EventEmitter { + + /** + * Constructs a new RPC service instance. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** RPC implementation. Becomes `null` once the service is ended. */ + public rpcImpl: (RPCImpl|null); + + /** Whether requests are length-delimited. */ + public requestDelimited: boolean; + + /** Whether responses are length-delimited. */ + public responseDelimited: boolean; + + /** + * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}. + * @param method Reflected or static method + * @param requestCtor Request constructor + * @param responseCtor Response constructor + * @param request Request message or plain object + * @param callback Service callback + */ + public rpcCall, TRes extends Message>(method: (Method|rpc.ServiceMethod), requestCtor: Constructor, responseCtor: Constructor, request: (TReq|Properties), callback: rpc.ServiceMethodCallback): void; + + /** + * Ends this service and emits the `end` event. + * @param [endedByRPC=false] Whether the service has been ended by the RPC implementation. + * @returns `this` + */ + public end(endedByRPC?: boolean): rpc.Service; + } +} + +/** + * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets. + * @param method Reflected or static method being called + * @param requestData Request data + * @param callback Callback function + */ +type RPCImpl = (method: (Method|rpc.ServiceMethod, Message<{}>>), requestData: Uint8Array, callback: RPCImplCallback) => void; + +/** + * Node-style callback as used by {@link RPCImpl}. + * @param error Error, if any, otherwise `null` + * @param [response] Response data or `null` to signal end of stream, if there hasn't been an error + */ +type RPCImplCallback = (error: (Error|null), response?: (Uint8Array|null)) => void; + +/** Reflected service. */ +export class Service extends NamespaceBase { + + /** + * Constructs a new service instance. + * @param name Service name + * @param [options] Service options + * @throws {TypeError} If arguments are invalid + */ + constructor(name: string, options?: { [k: string]: any }); + + /** Service methods. */ + public methods: { [k: string]: Method }; + + /** + * Constructs a service from a service descriptor. + * @param name Service name + * @param json Service descriptor + * @returns Created service + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: IService): Service; + + /** + * Converts this service to a service descriptor. + * @param [toJSONOptions] JSON conversion options + * @returns Service descriptor + */ + public toJSON(toJSONOptions?: IToJSONOptions): IService; + + /** Methods of this service as an array for iteration. */ + public readonly methodsArray: Method[]; + + /** + * Creates a runtime service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public create(rpcImpl: RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): rpc.Service; +} + +/** Service descriptor. */ +export interface IService extends INamespace { + + /** Method descriptors */ + methods: { [k: string]: IMethod }; +} + +/** + * Gets the next token and advances. + * @returns Next token or `null` on eof + */ +type TokenizerHandleNext = () => (string|null); + +/** + * Peeks for the next token. + * @returns Next token or `null` on eof + */ +type TokenizerHandlePeek = () => (string|null); + +/** + * Pushes a token back to the stack. + * @param token Token + */ +type TokenizerHandlePush = (token: string) => void; + +/** + * Skips the next token. + * @param expected Expected token + * @param [optional=false] If optional + * @returns Whether the token matched + * @throws {Error} If the token didn't match and is not optional + */ +type TokenizerHandleSkip = (expected: string, optional?: boolean) => boolean; + +/** + * Gets the comment on the previous line or, alternatively, the line comment on the specified line. + * @param [line] Line number + * @returns Comment text or `null` if none + */ +type TokenizerHandleCmnt = (line?: number) => (string|null); + +/** Handle object returned from {@link tokenize}. */ +export interface ITokenizerHandle { + + /** Gets the next token and advances (`null` on eof) */ + next: TokenizerHandleNext; + + /** Peeks for the next token (`null` on eof) */ + peek: TokenizerHandlePeek; + + /** Pushes a token back to the stack */ + push: TokenizerHandlePush; + + /** Skips a token, returns its presence and advances or, if non-optional and not present, throws */ + skip: TokenizerHandleSkip; + + /** Gets the comment on the previous line or the line comment on the specified line, if any */ + cmnt: TokenizerHandleCmnt; + + /** Current line number */ + line: number; +} + +/** + * Tokenizes the given .proto source and returns an object with useful utility functions. + * @param source Source contents + * @param alternateCommentMode Whether we should activate alternate comment parsing mode. + * @returns Tokenizer handle + */ +export function tokenize(source: string, alternateCommentMode: boolean): ITokenizerHandle; + +export namespace tokenize { + + /** + * Unescapes a string. + * @param str String to unescape + * @returns Unescaped string + */ + function unescape(str: string): string; +} + +/** Reflected message type. */ +export class Type extends NamespaceBase { + + /** + * Constructs a new reflected message type instance. + * @param name Message name + * @param [options] Declared options + */ + constructor(name: string, options?: { [k: string]: any }); + + /** Message fields. */ + public fields: { [k: string]: Field }; + + /** Oneofs declared within this namespace, if any. */ + public oneofs: { [k: string]: OneOf }; + + /** Extension ranges, if any. */ + public extensions: number[][]; + + /** Reserved ranges, if any. */ + public reserved: (number[]|string)[]; + + /** Message fields by id. */ + public readonly fieldsById: { [k: number]: Field }; + + /** Fields of this message as an array for iteration. */ + public readonly fieldsArray: Field[]; + + /** Oneofs of this message as an array for iteration. */ + public readonly oneofsArray: OneOf[]; + + /** + * The registered constructor, if any registered, otherwise a generic constructor. + * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor. + */ + public ctor: Constructor<{}>; + + /** + * Generates a constructor function for the specified type. + * @param mtype Message type + * @returns Codegen instance + */ + public static generateConstructor(mtype: Type): Codegen; + + /** + * Creates a message type from a message type descriptor. + * @param name Message name + * @param json Message type descriptor + * @returns Created message type + */ + public static fromJSON(name: string, json: IType): Type; + + /** + * Converts this message type to a message type descriptor. + * @param [toJSONOptions] JSON conversion options + * @returns Message type descriptor + */ + public toJSON(toJSONOptions?: IToJSONOptions): IType; + + /** + * Adds a nested object to this type. + * @param object Nested object to add + * @returns `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id + */ + public add(object: ReflectionObject): Type; + + /** + * Removes a nested object from this type. + * @param object Nested object to remove + * @returns `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `object` is not a member of this type + */ + public remove(object: ReflectionObject): Type; + + /** + * Tests if the specified id is reserved. + * @param id Id to test + * @returns `true` if reserved, otherwise `false` + */ + public isReservedId(id: number): boolean; + + /** + * Tests if the specified name is reserved. + * @param name Name to test + * @returns `true` if reserved, otherwise `false` + */ + public isReservedName(name: string): boolean; + + /** + * Creates a new message of this type using the specified properties. + * @param [properties] Properties to set + * @returns Message instance + */ + public create(properties?: { [k: string]: any }): Message<{}>; + + /** + * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}. + * @returns `this` + */ + public setup(): Type; + + /** + * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages. + * @param message Message instance or plain object + * @param [writer] Writer to encode to + * @returns writer + */ + public encode(message: (Message<{}>|{ [k: string]: any }), writer?: Writer): Writer; + + /** + * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages. + * @param message Message instance or plain object + * @param [writer] Writer to encode to + * @returns writer + */ + public encodeDelimited(message: (Message<{}>|{ [k: string]: any }), writer?: Writer): Writer; + + /** + * Decodes a message of this type. + * @param reader Reader or buffer to decode from + * @param [length] Length of the message, if known beforehand + * @returns Decoded message + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {util.ProtocolError<{}>} If required fields are missing + */ + public decode(reader: (Reader|Uint8Array), length?: number): Message<{}>; + + /** + * Decodes a message of this type preceeded by its byte length as a varint. + * @param reader Reader or buffer to decode from + * @returns Decoded message + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {util.ProtocolError} If required fields are missing + */ + public decodeDelimited(reader: (Reader|Uint8Array)): Message<{}>; + + /** + * Verifies that field values are valid and that required fields are present. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public verify(message: { [k: string]: any }): (null|string); + + /** + * Creates a new message of this type from a plain object. Also converts values to their respective internal types. + * @param object Plain object to convert + * @returns Message instance + */ + public fromObject(object: { [k: string]: any }): Message<{}>; + + /** + * Creates a plain object from a message of this type. Also converts values to other types if specified. + * @param message Message instance + * @param [options] Conversion options + * @returns Plain object + */ + public toObject(message: Message<{}>, options?: IConversionOptions): { [k: string]: any }; + + /** + * Type decorator (TypeScript). + * @param [typeName] Type name, defaults to the constructor's name + * @returns Decorator function + */ + public static d>(typeName?: string): TypeDecorator; +} + +/** Message type descriptor. */ +export interface IType extends INamespace { + + /** Oneof descriptors */ + oneofs?: { [k: string]: IOneOf }; + + /** Field descriptors */ + fields: { [k: string]: IField }; + + /** Extension ranges */ + extensions?: number[][]; + + /** Reserved ranges */ + reserved?: (number[]|string)[]; + + /** Whether a legacy group or not */ + group?: boolean; +} + +/** Conversion options as used by {@link Type#toObject} and {@link Message.toObject}. */ +export interface IConversionOptions { + + /** + * Long conversion type. + * Valid values are `String` and `Number` (the global types). + * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library. + */ + longs?: Function; + + /** + * Enum value conversion type. + * Only valid value is `String` (the global type). + * Defaults to copy the present value, which is the numeric id. + */ + enums?: Function; + + /** + * Bytes value conversion type. + * Valid values are `Array` and (a base64 encoded) `String` (the global types). + * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser. + */ + bytes?: Function; + + /** Also sets default values on the resulting object */ + defaults?: boolean; + + /** Sets empty arrays for missing repeated fields even if `defaults=false` */ + arrays?: boolean; + + /** Sets empty objects for missing map fields even if `defaults=false` */ + objects?: boolean; + + /** Includes virtual oneof properties set to the present field's name, if any */ + oneofs?: boolean; + + /** Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings */ + json?: boolean; +} + +/** + * Decorator function as returned by {@link Type.d} (TypeScript). + * @param target Target constructor + */ +type TypeDecorator> = (target: Constructor) => void; + +/** Common type constants. */ +export namespace types { + + /** Basic type wire types. */ + const basic: { + "double": number, + "float": number, + "int32": number, + "uint32": number, + "sint32": number, + "fixed32": number, + "sfixed32": number, + "int64": number, + "uint64": number, + "sint64": number, + "fixed64": number, + "sfixed64": number, + "bool": number, + "string": number, + "bytes": number + }; + + /** Basic type defaults. */ + const defaults: { + "double": number, + "float": number, + "int32": number, + "uint32": number, + "sint32": number, + "fixed32": number, + "sfixed32": number, + "int64": number, + "uint64": number, + "sint64": number, + "fixed64": number, + "sfixed64": number, + "bool": boolean, + "string": string, + "bytes": number[], + "message": null + }; + + /** Basic long type wire types. */ + const long: { + "int64": number, + "uint64": number, + "sint64": number, + "fixed64": number, + "sfixed64": number + }; + + /** Allowed types for map keys with their associated wire type. */ + const mapKey: { + "int32": number, + "uint32": number, + "sint32": number, + "fixed32": number, + "sfixed32": number, + "int64": number, + "uint64": number, + "sint64": number, + "fixed64": number, + "sfixed64": number, + "bool": number, + "string": number + }; + + /** Allowed types for packed repeated fields with their associated wire type. */ + const packed: { + "double": number, + "float": number, + "int32": number, + "uint32": number, + "sint32": number, + "fixed32": number, + "sfixed32": number, + "int64": number, + "uint64": number, + "sint64": number, + "fixed64": number, + "sfixed64": number, + "bool": number + }; +} + +/** Constructor type. */ +export interface Constructor extends Function { + new(...params: any[]): T; prototype: T; +} + +/** Properties type. */ +type Properties = { [P in keyof T]?: T[P] }; + +/** + * Any compatible Buffer instance. + * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings. + */ +export interface Buffer extends Uint8Array { +} + +/** + * Any compatible Long instance. + * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js. + */ +export interface Long { + + /** Low bits */ + low: number; + + /** High bits */ + high: number; + + /** Whether unsigned or not */ + unsigned: boolean; +} + +/** + * A OneOf getter as returned by {@link util.oneOfGetter}. + * @returns Set field name, if any + */ +type OneOfGetter = () => (string|undefined); + +/** + * A OneOf setter as returned by {@link util.oneOfSetter}. + * @param value Field name + */ +type OneOfSetter = (value: (string|undefined)) => void; + +/** Various utility functions. */ +export namespace util { + + /** Helper class for working with the low and high bits of a 64 bit value. */ + class LongBits { + + /** + * Constructs new long bits. + * @param lo Low 32 bits, unsigned + * @param hi High 32 bits, unsigned + */ + constructor(lo: number, hi: number); + + /** Low bits. */ + public lo: number; + + /** High bits. */ + public hi: number; + + /** Zero bits. */ + public static zero: util.LongBits; + + /** Zero hash. */ + public static zeroHash: string; + + /** + * Constructs new long bits from the specified number. + * @param value Value + * @returns Instance + */ + public static fromNumber(value: number): util.LongBits; + + /** + * Constructs new long bits from a number, long or string. + * @param value Value + * @returns Instance + */ + public static from(value: (Long|number|string)): util.LongBits; + + /** + * Converts this long bits to a possibly unsafe JavaScript number. + * @param [unsigned=false] Whether unsigned or not + * @returns Possibly unsafe number + */ + public toNumber(unsigned?: boolean): number; + + /** + * Converts this long bits to a long. + * @param [unsigned=false] Whether unsigned or not + * @returns Long + */ + public toLong(unsigned?: boolean): Long; + + /** + * Constructs new long bits from the specified 8 characters long hash. + * @param hash Hash + * @returns Bits + */ + public static fromHash(hash: string): util.LongBits; + + /** + * Converts this long bits to a 8 characters long hash. + * @returns Hash + */ + public toHash(): string; + + /** + * Zig-zag encodes this long bits. + * @returns `this` + */ + public zzEncode(): util.LongBits; + + /** + * Zig-zag decodes this long bits. + * @returns `this` + */ + public zzDecode(): util.LongBits; + + /** + * Calculates the length of this longbits when encoded as a varint. + * @returns Length + */ + public length(): number; + } + + /** Whether running within node or not. */ + let isNode: boolean; + + /** Global object reference. */ + let global: object; + + /** An immuable empty array. */ + const emptyArray: any[]; + + /** An immutable empty object. */ + const emptyObject: object; + + /** + * Tests if the specified value is an integer. + * @param value Value to test + * @returns `true` if the value is an integer + */ + function isInteger(value: any): boolean; + + /** + * Tests if the specified value is a string. + * @param value Value to test + * @returns `true` if the value is a string + */ + function isString(value: any): boolean; + + /** + * Tests if the specified value is a non-null object. + * @param value Value to test + * @returns `true` if the value is a non-null object + */ + function isObject(value: any): boolean; + + /** + * Checks if a property on a message is considered to be present. + * This is an alias of {@link util.isSet}. + * @param obj Plain object or message instance + * @param prop Property name + * @returns `true` if considered to be present, otherwise `false` + */ + function isset(obj: object, prop: string): boolean; + + /** + * Checks if a property on a message is considered to be present. + * @param obj Plain object or message instance + * @param prop Property name + * @returns `true` if considered to be present, otherwise `false` + */ + function isSet(obj: object, prop: string): boolean; + + /** Node's Buffer class if available. */ + let Buffer: Constructor; + + /** + * Creates a new buffer of whatever type supported by the environment. + * @param [sizeOrArray=0] Buffer size or number array + * @returns Buffer + */ + function newBuffer(sizeOrArray?: (number|number[])): (Uint8Array|Buffer); + + /** Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`. */ + let Array: Constructor; + + /** Long.js's Long class if available. */ + let Long: Constructor; + + /** Regular expression used to verify 2 bit (`bool`) map keys. */ + const key2Re: RegExp; + + /** Regular expression used to verify 32 bit (`int32` etc.) map keys. */ + const key32Re: RegExp; + + /** Regular expression used to verify 64 bit (`int64` etc.) map keys. */ + const key64Re: RegExp; + + /** + * Converts a number or long to an 8 characters long hash string. + * @param value Value to convert + * @returns Hash + */ + function longToHash(value: (Long|number)): string; + + /** + * Converts an 8 characters long hash string to a long or number. + * @param hash Hash + * @param [unsigned=false] Whether unsigned or not + * @returns Original value + */ + function longFromHash(hash: string, unsigned?: boolean): (Long|number); + + /** + * Merges the properties of the source object into the destination object. + * @param dst Destination object + * @param src Source object + * @param [ifNotSet=false] Merges only if the key is not already set + * @returns Destination object + */ + function merge(dst: { [k: string]: any }, src: { [k: string]: any }, ifNotSet?: boolean): { [k: string]: any }; + + /** + * Converts the first character of a string to lower case. + * @param str String to convert + * @returns Converted string + */ + function lcFirst(str: string): string; + + /** + * Creates a custom error constructor. + * @param name Error name + * @returns Custom error constructor + */ + function newError(name: string): Constructor; + + /** Error subclass indicating a protocol specifc error. */ + class ProtocolError> extends Error { + + /** + * Constructs a new protocol error. + * @param message Error message + * @param [properties] Additional properties + */ + constructor(message: string, properties?: { [k: string]: any }); + + /** So far decoded message instance. */ + public instance: Message; + } + + /** + * Builds a getter for a oneof's present field name. + * @param fieldNames Field names + * @returns Unbound getter + */ + function oneOfGetter(fieldNames: string[]): OneOfGetter; + + /** + * Builds a setter for a oneof's present field name. + * @param fieldNames Field names + * @returns Unbound setter + */ + function oneOfSetter(fieldNames: string[]): OneOfSetter; + + /** + * Default conversion options used for {@link Message#toJSON} implementations. + * + * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely: + * + * - Longs become strings + * - Enums become string keys + * - Bytes become base64 encoded strings + * - (Sub-)Messages become plain objects + * - Maps become plain objects with all string keys + * - Repeated fields become arrays + * - NaN and Infinity for float and double fields become strings + * + * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json + */ + let toJSONOptions: IConversionOptions; + + /** Node's fs module if available. */ + let fs: { [k: string]: any }; + + /** + * Converts an object's values to an array. + * @param object Object to convert + * @returns Converted array + */ + function toArray(object: { [k: string]: any }): any[]; + + /** + * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values. + * @param array Array to convert + * @returns Converted object + */ + function toObject(array: any[]): { [k: string]: any }; + + /** + * Tests whether the specified name is a reserved word in JS. + * @param name Name to test + * @returns `true` if reserved, otherwise `false` + */ + function isReserved(name: string): boolean; + + /** + * Returns a safe property accessor for the specified property name. + * @param prop Property name + * @returns Safe accessor + */ + function safeProp(prop: string): string; + + /** + * Converts the first character of a string to upper case. + * @param str String to convert + * @returns Converted string + */ + function ucFirst(str: string): string; + + /** + * Converts a string to camel case. + * @param str String to convert + * @returns Converted string + */ + function camelCase(str: string): string; + + /** + * Compares reflected fields by id. + * @param a First field + * @param b Second field + * @returns Comparison value + */ + function compareFieldsById(a: Field, b: Field): number; + + /** + * Decorator helper for types (TypeScript). + * @param ctor Constructor function + * @param [typeName] Type name, defaults to the constructor's name + * @returns Reflected type + */ + function decorateType>(ctor: Constructor, typeName?: string): Type; + + /** + * Decorator helper for enums (TypeScript). + * @param object Enum object + * @returns Reflected enum + */ + function decorateEnum(object: object): Enum; + + /** + * Sets the value of a property by property path. If a value already exists, it is turned to an array + * @param dst Destination object + * @param path dot '.' delimited path of the property to set + * @param value the value to set + * @param [ifNotSet] Sets the option only if it isn't currently set + * @returns Destination object + */ + function setProperty(dst: { [k: string]: any }, path: string, value: object, ifNotSet?: (boolean|undefined)): { [k: string]: any }; + + /** Decorator root (TypeScript). */ + let decorateRoot: Root; + + /** + * Returns a promise from a node-style callback function. + * @param fn Function to call + * @param ctx Function context + * @param params Function arguments + * @returns Promisified function + */ + function asPromise(fn: asPromiseCallback, ctx: any, ...params: any[]): Promise; + + /** A minimal base64 implementation for number arrays. */ + namespace base64 { + + /** + * Calculates the byte length of a base64 encoded string. + * @param string Base64 encoded string + * @returns Byte length + */ + function length(string: string): number; + + /** + * Encodes a buffer to a base64 encoded string. + * @param buffer Source buffer + * @param start Source start + * @param end Source end + * @returns Base64 encoded string + */ + function encode(buffer: Uint8Array, start: number, end: number): string; + + /** + * Decodes a base64 encoded string to a buffer. + * @param string Source string + * @param buffer Destination buffer + * @param offset Destination offset + * @returns Number of bytes written + * @throws {Error} If encoding is invalid + */ + function decode(string: string, buffer: Uint8Array, offset: number): number; + + /** + * Tests if the specified string appears to be base64 encoded. + * @param string String to test + * @returns `true` if probably base64 encoded, otherwise false + */ + function test(string: string): boolean; + } + + /** + * Begins generating a function. + * @param functionParams Function parameter names + * @param [functionName] Function name if not anonymous + * @returns Appender that appends code to the function's body + */ + function codegen(functionParams: string[], functionName?: string): Codegen; + + namespace codegen { + + /** When set to `true`, codegen will log generated code to console. Useful for debugging. */ + let verbose: boolean; + } + + /** + * Begins generating a function. + * @param [functionName] Function name if not anonymous + * @returns Appender that appends code to the function's body + */ + function codegen(functionName?: string): Codegen; + + /** A minimal event emitter. */ + class EventEmitter { + + /** Constructs a new event emitter instance. */ + constructor(); + + /** + * Registers an event listener. + * @param evt Event name + * @param fn Listener + * @param [ctx] Listener context + * @returns `this` + */ + public on(evt: string, fn: EventEmitterListener, ctx?: any): this; + + /** + * Removes an event listener or any matching listeners if arguments are omitted. + * @param [evt] Event name. Removes all listeners if omitted. + * @param [fn] Listener to remove. Removes all listeners of `evt` if omitted. + * @returns `this` + */ + public off(evt?: string, fn?: EventEmitterListener): this; + + /** + * Emits an event by calling its listeners with the specified arguments. + * @param evt Event name + * @param args Arguments + * @returns `this` + */ + public emit(evt: string, ...args: any[]): this; + } + + /** Reads / writes floats / doubles from / to buffers. */ + namespace float { + + /** + * Writes a 32 bit float to a buffer using little endian byte order. + * @param val Value to write + * @param buf Target buffer + * @param pos Target buffer offset + */ + function writeFloatLE(val: number, buf: Uint8Array, pos: number): void; + + /** + * Writes a 32 bit float to a buffer using big endian byte order. + * @param val Value to write + * @param buf Target buffer + * @param pos Target buffer offset + */ + function writeFloatBE(val: number, buf: Uint8Array, pos: number): void; + + /** + * Reads a 32 bit float from a buffer using little endian byte order. + * @param buf Source buffer + * @param pos Source buffer offset + * @returns Value read + */ + function readFloatLE(buf: Uint8Array, pos: number): number; + + /** + * Reads a 32 bit float from a buffer using big endian byte order. + * @param buf Source buffer + * @param pos Source buffer offset + * @returns Value read + */ + function readFloatBE(buf: Uint8Array, pos: number): number; + + /** + * Writes a 64 bit double to a buffer using little endian byte order. + * @param val Value to write + * @param buf Target buffer + * @param pos Target buffer offset + */ + function writeDoubleLE(val: number, buf: Uint8Array, pos: number): void; + + /** + * Writes a 64 bit double to a buffer using big endian byte order. + * @param val Value to write + * @param buf Target buffer + * @param pos Target buffer offset + */ + function writeDoubleBE(val: number, buf: Uint8Array, pos: number): void; + + /** + * Reads a 64 bit double from a buffer using little endian byte order. + * @param buf Source buffer + * @param pos Source buffer offset + * @returns Value read + */ + function readDoubleLE(buf: Uint8Array, pos: number): number; + + /** + * Reads a 64 bit double from a buffer using big endian byte order. + * @param buf Source buffer + * @param pos Source buffer offset + * @returns Value read + */ + function readDoubleBE(buf: Uint8Array, pos: number): number; + } + + /** + * Fetches the contents of a file. + * @param filename File path or url + * @param options Fetch options + * @param callback Callback function + */ + function fetch(filename: string, options: IFetchOptions, callback: FetchCallback): void; + + /** + * Fetches the contents of a file. + * @param path File path or url + * @param callback Callback function + */ + function fetch(path: string, callback: FetchCallback): void; + + /** + * Fetches the contents of a file. + * @param path File path or url + * @param [options] Fetch options + * @returns Promise + */ + function fetch(path: string, options?: IFetchOptions): Promise<(string|Uint8Array)>; + + /** + * Requires a module only if available. + * @param moduleName Module to require + * @returns Required module if available and not empty, otherwise `null` + */ + function inquire(moduleName: string): object; + + /** A minimal path module to resolve Unix, Windows and URL paths alike. */ + namespace path { + + /** + * Tests if the specified path is absolute. + * @param path Path to test + * @returns `true` if path is absolute + */ + function isAbsolute(path: string): boolean; + + /** + * Normalizes the specified path. + * @param path Path to normalize + * @returns Normalized path + */ + function normalize(path: string): string; + + /** + * Resolves the specified include path against the specified origin path. + * @param originPath Path to the origin file + * @param includePath Include path relative to origin path + * @param [alreadyNormalized=false] `true` if both paths are already known to be normalized + * @returns Path to the include file + */ + function resolve(originPath: string, includePath: string, alreadyNormalized?: boolean): string; + } + + /** + * A general purpose buffer pool. + * @param alloc Allocator + * @param slice Slicer + * @param [size=8192] Slab size + * @returns Pooled allocator + */ + function pool(alloc: PoolAllocator, slice: PoolSlicer, size?: number): PoolAllocator; + + /** A minimal UTF8 implementation for number arrays. */ + namespace utf8 { + + /** + * Calculates the UTF8 byte length of a string. + * @param string String + * @returns Byte length + */ + function length(string: string): number; + + /** + * Reads UTF8 bytes as a string. + * @param buffer Source buffer + * @param start Source start + * @param end Source end + * @returns String read + */ + function read(buffer: Uint8Array, start: number, end: number): string; + + /** + * Writes a string as UTF8 bytes. + * @param string Source string + * @param buffer Destination buffer + * @param offset Destination offset + * @returns Bytes written + */ + function write(string: string, buffer: Uint8Array, offset: number): number; + } +} + +/** + * Generates a verifier specific to the specified message type. + * @param mtype Message type + * @returns Codegen instance + */ +export function verifier(mtype: Type): Codegen; + +/** Wrappers for common types. */ +export const wrappers: { [k: string]: IWrapper }; + +/** + * From object converter part of an {@link IWrapper}. + * @param object Plain object + * @returns Message instance + */ +type WrapperFromObjectConverter = (this: Type, object: { [k: string]: any }) => Message<{}>; + +/** + * To object converter part of an {@link IWrapper}. + * @param message Message instance + * @param [options] Conversion options + * @returns Plain object + */ +type WrapperToObjectConverter = (this: Type, message: Message<{}>, options?: IConversionOptions) => { [k: string]: any }; + +/** Common type wrapper part of {@link wrappers}. */ +export interface IWrapper { + + /** From object converter */ + fromObject?: WrapperFromObjectConverter; + + /** To object converter */ + toObject?: WrapperToObjectConverter; +} + +/** Wire format writer using `Uint8Array` if available, otherwise `Array`. */ +export class Writer { + + /** Constructs a new writer instance. */ + constructor(); + + /** Current length. */ + public len: number; + + /** Operations head. */ + public head: object; + + /** Operations tail */ + public tail: object; + + /** Linked forked states. */ + public states: (object|null); + + /** + * Creates a new writer. + * @returns A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer} + */ + public static create(): (BufferWriter|Writer); + + /** + * Allocates a buffer of the specified size. + * @param size Buffer size + * @returns Buffer + */ + public static alloc(size: number): Uint8Array; + + /** + * Writes an unsigned 32 bit value as a varint. + * @param value Value to write + * @returns `this` + */ + public uint32(value: number): Writer; + + /** + * Writes a signed 32 bit value as a varint. + * @param value Value to write + * @returns `this` + */ + public int32(value: number): Writer; + + /** + * Writes a 32 bit value as a varint, zig-zag encoded. + * @param value Value to write + * @returns `this` + */ + public sint32(value: number): Writer; + + /** + * Writes an unsigned 64 bit value as a varint. + * @param value Value to write + * @returns `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ + public uint64(value: (Long|number|string)): Writer; + + /** + * Writes a signed 64 bit value as a varint. + * @param value Value to write + * @returns `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ + public int64(value: (Long|number|string)): Writer; + + /** + * Writes a signed 64 bit value as a varint, zig-zag encoded. + * @param value Value to write + * @returns `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ + public sint64(value: (Long|number|string)): Writer; + + /** + * Writes a boolish value as a varint. + * @param value Value to write + * @returns `this` + */ + public bool(value: boolean): Writer; + + /** + * Writes an unsigned 32 bit value as fixed 32 bits. + * @param value Value to write + * @returns `this` + */ + public fixed32(value: number): Writer; + + /** + * Writes a signed 32 bit value as fixed 32 bits. + * @param value Value to write + * @returns `this` + */ + public sfixed32(value: number): Writer; + + /** + * Writes an unsigned 64 bit value as fixed 64 bits. + * @param value Value to write + * @returns `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ + public fixed64(value: (Long|number|string)): Writer; + + /** + * Writes a signed 64 bit value as fixed 64 bits. + * @param value Value to write + * @returns `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ + public sfixed64(value: (Long|number|string)): Writer; + + /** + * Writes a float (32 bit). + * @param value Value to write + * @returns `this` + */ + public float(value: number): Writer; + + /** + * Writes a double (64 bit float). + * @param value Value to write + * @returns `this` + */ + public double(value: number): Writer; + + /** + * Writes a sequence of bytes. + * @param value Buffer or base64 encoded string to write + * @returns `this` + */ + public bytes(value: (Uint8Array|string)): Writer; + + /** + * Writes a string. + * @param value Value to write + * @returns `this` + */ + public string(value: string): Writer; + + /** + * Forks this writer's state by pushing it to a stack. + * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state. + * @returns `this` + */ + public fork(): Writer; + + /** + * Resets this instance to the last state. + * @returns `this` + */ + public reset(): Writer; + + /** + * Resets to the last state and appends the fork state's current write length as a varint followed by its operations. + * @returns `this` + */ + public ldelim(): Writer; + + /** + * Finishes the write operation. + * @returns Finished buffer + */ + public finish(): Uint8Array; +} + +/** Wire format writer using node buffers. */ +export class BufferWriter extends Writer { + + /** Constructs a new buffer writer instance. */ + constructor(); + + /** + * Allocates a buffer of the specified size. + * @param size Buffer size + * @returns Buffer + */ + public static alloc(size: number): Buffer; + + /** + * Finishes the write operation. + * @returns Finished buffer + */ + public finish(): Buffer; +} + +/** + * Callback as used by {@link util.asPromise}. + * @param error Error, if any + * @param params Additional arguments + */ +type asPromiseCallback = (error: (Error|null), ...params: any[]) => void; + +/** + * Appends code to the function's body or finishes generation. + * @param [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any + * @param [formatParams] Format parameters + * @returns Itself or the generated function if finished + * @throws {Error} If format parameter counts do not match + */ +type Codegen = (formatStringOrScope?: (string|{ [k: string]: any }), ...formatParams: any[]) => (Codegen|Function); + +/** + * Event listener as used by {@link util.EventEmitter}. + * @param args Arguments + */ +type EventEmitterListener = (...args: any[]) => void; + +/** + * Node-style callback as used by {@link util.fetch}. + * @param error Error, if any, otherwise `null` + * @param [contents] File contents, if there hasn't been an error + */ +type FetchCallback = (error: Error, contents?: string) => void; + +/** Options as used by {@link util.fetch}. */ +export interface IFetchOptions { + + /** Whether expecting a binary response */ + binary?: boolean; + + /** If `true`, forces the use of XMLHttpRequest */ + xhr?: boolean; +} + +/** + * An allocator as used by {@link util.pool}. + * @param size Buffer size + * @returns Buffer + */ +type PoolAllocator = (size: number) => Uint8Array; + +/** + * A slicer as used by {@link util.pool}. + * @param start Start offset + * @param end End offset + * @returns Buffer slice + */ +type PoolSlicer = (this: Uint8Array, start: number, end: number) => Uint8Array; diff --git a/node_modules/protobufjs/index.js b/node_modules/protobufjs/index.js new file mode 100644 index 0000000..042042a --- /dev/null +++ b/node_modules/protobufjs/index.js @@ -0,0 +1,4 @@ +// full library entry point. + +"use strict"; +module.exports = require("./src/index"); diff --git a/node_modules/protobufjs/light.d.ts b/node_modules/protobufjs/light.d.ts new file mode 100644 index 0000000..d83e7f9 --- /dev/null +++ b/node_modules/protobufjs/light.d.ts @@ -0,0 +1,2 @@ +export as namespace protobuf; +export * from "./index"; diff --git a/node_modules/protobufjs/light.js b/node_modules/protobufjs/light.js new file mode 100644 index 0000000..1209e64 --- /dev/null +++ b/node_modules/protobufjs/light.js @@ -0,0 +1,4 @@ +// light library entry point. + +"use strict"; +module.exports = require("./src/index-light"); \ No newline at end of file diff --git a/node_modules/protobufjs/minimal.d.ts b/node_modules/protobufjs/minimal.d.ts new file mode 100644 index 0000000..d83e7f9 --- /dev/null +++ b/node_modules/protobufjs/minimal.d.ts @@ -0,0 +1,2 @@ +export as namespace protobuf; +export * from "./index"; diff --git a/node_modules/protobufjs/minimal.js b/node_modules/protobufjs/minimal.js new file mode 100644 index 0000000..1f35ec9 --- /dev/null +++ b/node_modules/protobufjs/minimal.js @@ -0,0 +1,4 @@ +// minimal library entry point. + +"use strict"; +module.exports = require("./src/index-minimal"); diff --git a/node_modules/protobufjs/package.json b/node_modules/protobufjs/package.json new file mode 100644 index 0000000..0a34b97 --- /dev/null +++ b/node_modules/protobufjs/package.json @@ -0,0 +1,114 @@ +{ + "name": "protobufjs", + "version": "7.5.4", + "versionScheme": "~", + "description": "Protocol Buffers for JavaScript (& TypeScript).", + "author": "Daniel Wirtz ", + "license": "BSD-3-Clause", + "repository": "protobufjs/protobuf.js", + "bugs": "https://github.com/protobufjs/protobuf.js/issues", + "homepage": "https://protobufjs.github.io/protobuf.js/", + "engines": { + "node": ">=12.0.0" + }, + "eslintConfig": { + "env": { + "es6": true + }, + "parserOptions": { + "ecmaVersion": 6 + } + }, + "keywords": [ + "protobuf", + "protocol-buffers", + "serialization", + "typescript" + ], + "main": "index.js", + "types": "index.d.ts", + "scripts": { + "bench": "node bench", + "build": "npm run build:bundle && npm run build:types", + "build:bundle": "gulp --gulpfile scripts/gulpfile.js", + "build:types": "node cli/bin/pbts --main --global protobuf --out index.d.ts src/ lib/aspromise/index.js lib/base64/index.js lib/codegen/index.js lib/eventemitter/index.js lib/float/index.js lib/fetch/index.js lib/inquire/index.js lib/path/index.js lib/pool/index.js lib/utf8/index.js", + "changelog": "node scripts/changelog -w", + "coverage": "npm run coverage:test && npm run coverage:report", + "coverage:test": "nyc --silent tape -r ./lib/tape-adapter tests/*.js tests/node/*.js", + "coverage:report": "nyc report --reporter=lcov --reporter=text", + "docs": "jsdoc -c config/jsdoc.json -R README.md --verbose --pedantic", + "lint": "npm run lint:sources && npm run lint:types", + "lint:sources": "eslint \"**/*.js\" -c config/eslint.json", + "lint:types": "tslint \"**/*.d.ts\" -e \"**/node_modules/**\" -t stylish -c config/tslint.json", + "pages": "node scripts/pages", + "prepublish": "cd cli && npm install && cd .. && npm run build", + "prepublishOnly": "cd cli && npm install && cd .. && npm run build", + "postinstall": "node scripts/postinstall", + "prof": "node bench/prof", + "test": "npm run test:sources && npm run test:types", + "test:sources": "tape -r ./lib/tape-adapter tests/*.js tests/node/*.js", + "test:types": "tsc tests/comp_typescript.ts --lib es2015 --esModuleInterop --strictNullChecks --experimentalDecorators --emitDecoratorMetadata && tsc tests/data/test.js.ts --lib es2015 --esModuleInterop --noEmit --strictNullChecks && tsc tests/data/*.ts --lib es2015 --esModuleInterop --noEmit --strictNullChecks", + "make": "npm run lint:sources && npm run build && npm run lint:types && node ./scripts/gentests.js && npm test" + }, + "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" + }, + "devDependencies": { + "benchmark": "^2.1.4", + "browserify": "^17.0.0", + "browserify-wrap": "^1.0.2", + "bundle-collapser": "^1.3.0", + "chalk": "^4.0.0", + "escodegen": "^1.13.0", + "eslint": "^8.15.0", + "espree": "^9.0.0", + "estraverse": "^5.1.0", + "gh-pages": "^4.0.0", + "git-raw-commits": "^2.0.3", + "git-semver-tags": "^4.0.0", + "google-protobuf": "^3.11.3", + "gulp": "^4.0.2", + "gulp-header": "^2.0.9", + "gulp-if": "^3.0.0", + "gulp-sourcemaps": "^3.0.0", + "gulp-uglify": "^3.0.2", + "jaguarjs-jsdoc": "github:dcodeIO/jaguarjs-jsdoc", + "jsdoc": "^4.0.0", + "minimist": "^1.2.0", + "nyc": "^15.0.0", + "reflect-metadata": "^0.1.13", + "tape": "^5.0.0", + "tslint": "^6.0.0", + "typescript": "^3.7.5", + "uglify-js": "^3.7.7", + "vinyl-buffer": "^1.0.1", + "vinyl-fs": "^3.0.3", + "vinyl-source-stream": "^2.0.0" + }, + "files": [ + "index.js", + "index.d.ts", + "light.d.ts", + "light.js", + "minimal.d.ts", + "minimal.js", + "package-lock.json", + "tsconfig.json", + "scripts/postinstall.js", + "dist/**", + "ext/**", + "google/**", + "src/**" + ] +} diff --git a/node_modules/protobufjs/scripts/postinstall.js b/node_modules/protobufjs/scripts/postinstall.js new file mode 100644 index 0000000..bf4ff45 --- /dev/null +++ b/node_modules/protobufjs/scripts/postinstall.js @@ -0,0 +1,32 @@ +"use strict"; + +var path = require("path"), + fs = require("fs"), + pkg = require(path.join(__dirname, "..", "package.json")); + +// check version scheme used by dependents +if (!pkg.versionScheme) + return; + +var warn = process.stderr.isTTY + ? "\x1b[30m\x1b[43mWARN\x1b[0m \x1b[35m" + path.basename(process.argv[1], ".js") + "\x1b[0m" + : "WARN " + path.basename(process.argv[1], ".js"); + +var basePkg; +try { + basePkg = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "..", "package.json"))); +} catch (e) { + return; +} + +[ + "dependencies", + "devDependencies", + "optionalDependencies", + "peerDependencies" +] +.forEach(function(check) { + var version = basePkg && basePkg[check] && basePkg[check][pkg.name]; + if (typeof version === "string" && version.charAt(0) !== pkg.versionScheme) + process.stderr.write(pkg.name + " " + warn + " " + pkg.name + "@" + version + " is configured as a dependency of " + basePkg.name + ". use " + pkg.name + "@" + pkg.versionScheme + version.substring(1) + " instead for API compatibility.\n"); +}); diff --git a/node_modules/protobufjs/src/common.js b/node_modules/protobufjs/src/common.js new file mode 100644 index 0000000..489ee1c --- /dev/null +++ b/node_modules/protobufjs/src/common.js @@ -0,0 +1,399 @@ +"use strict"; +module.exports = common; + +var commonRe = /\/|\./; + +/** + * Provides common type definitions. + * Can also be used to provide additional google types or your own custom types. + * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name + * @param {Object.} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition + * @returns {undefined} + * @property {INamespace} google/protobuf/any.proto Any + * @property {INamespace} google/protobuf/duration.proto Duration + * @property {INamespace} google/protobuf/empty.proto Empty + * @property {INamespace} google/protobuf/field_mask.proto FieldMask + * @property {INamespace} google/protobuf/struct.proto Struct, Value, NullValue and ListValue + * @property {INamespace} google/protobuf/timestamp.proto Timestamp + * @property {INamespace} google/protobuf/wrappers.proto Wrappers + * @example + * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension) + * protobuf.common("descriptor", descriptorJson); + * + * // manually provides a custom definition (uses my.foo namespace) + * protobuf.common("my/foo/bar.proto", myFooBarJson); + */ +function common(name, json) { + if (!commonRe.test(name)) { + name = "google/protobuf/" + name + ".proto"; + json = { nested: { google: { nested: { protobuf: { nested: json } } } } }; + } + common[name] = json; +} + +// Not provided because of limited use (feel free to discuss or to provide yourself): +// +// google/protobuf/descriptor.proto +// google/protobuf/source_context.proto +// google/protobuf/type.proto +// +// Stripped and pre-parsed versions of these non-bundled files are instead available as part of +// the repository or package within the google/protobuf directory. + +common("any", { + + /** + * Properties of a google.protobuf.Any message. + * @interface IAny + * @type {Object} + * @property {string} [typeUrl] + * @property {Uint8Array} [bytes] + * @memberof common + */ + Any: { + fields: { + type_url: { + type: "string", + id: 1 + }, + value: { + type: "bytes", + id: 2 + } + } + } +}); + +var timeType; + +common("duration", { + + /** + * Properties of a google.protobuf.Duration message. + * @interface IDuration + * @type {Object} + * @property {number|Long} [seconds] + * @property {number} [nanos] + * @memberof common + */ + Duration: timeType = { + fields: { + seconds: { + type: "int64", + id: 1 + }, + nanos: { + type: "int32", + id: 2 + } + } + } +}); + +common("timestamp", { + + /** + * Properties of a google.protobuf.Timestamp message. + * @interface ITimestamp + * @type {Object} + * @property {number|Long} [seconds] + * @property {number} [nanos] + * @memberof common + */ + Timestamp: timeType +}); + +common("empty", { + + /** + * Properties of a google.protobuf.Empty message. + * @interface IEmpty + * @memberof common + */ + Empty: { + fields: {} + } +}); + +common("struct", { + + /** + * Properties of a google.protobuf.Struct message. + * @interface IStruct + * @type {Object} + * @property {Object.} [fields] + * @memberof common + */ + Struct: { + fields: { + fields: { + keyType: "string", + type: "Value", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.Value message. + * @interface IValue + * @type {Object} + * @property {string} [kind] + * @property {0} [nullValue] + * @property {number} [numberValue] + * @property {string} [stringValue] + * @property {boolean} [boolValue] + * @property {IStruct} [structValue] + * @property {IListValue} [listValue] + * @memberof common + */ + Value: { + oneofs: { + kind: { + oneof: [ + "nullValue", + "numberValue", + "stringValue", + "boolValue", + "structValue", + "listValue" + ] + } + }, + fields: { + nullValue: { + type: "NullValue", + id: 1 + }, + numberValue: { + type: "double", + id: 2 + }, + stringValue: { + type: "string", + id: 3 + }, + boolValue: { + type: "bool", + id: 4 + }, + structValue: { + type: "Struct", + id: 5 + }, + listValue: { + type: "ListValue", + id: 6 + } + } + }, + + NullValue: { + values: { + NULL_VALUE: 0 + } + }, + + /** + * Properties of a google.protobuf.ListValue message. + * @interface IListValue + * @type {Object} + * @property {Array.} [values] + * @memberof common + */ + ListValue: { + fields: { + values: { + rule: "repeated", + type: "Value", + id: 1 + } + } + } +}); + +common("wrappers", { + + /** + * Properties of a google.protobuf.DoubleValue message. + * @interface IDoubleValue + * @type {Object} + * @property {number} [value] + * @memberof common + */ + DoubleValue: { + fields: { + value: { + type: "double", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.FloatValue message. + * @interface IFloatValue + * @type {Object} + * @property {number} [value] + * @memberof common + */ + FloatValue: { + fields: { + value: { + type: "float", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.Int64Value message. + * @interface IInt64Value + * @type {Object} + * @property {number|Long} [value] + * @memberof common + */ + Int64Value: { + fields: { + value: { + type: "int64", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.UInt64Value message. + * @interface IUInt64Value + * @type {Object} + * @property {number|Long} [value] + * @memberof common + */ + UInt64Value: { + fields: { + value: { + type: "uint64", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.Int32Value message. + * @interface IInt32Value + * @type {Object} + * @property {number} [value] + * @memberof common + */ + Int32Value: { + fields: { + value: { + type: "int32", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.UInt32Value message. + * @interface IUInt32Value + * @type {Object} + * @property {number} [value] + * @memberof common + */ + UInt32Value: { + fields: { + value: { + type: "uint32", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.BoolValue message. + * @interface IBoolValue + * @type {Object} + * @property {boolean} [value] + * @memberof common + */ + BoolValue: { + fields: { + value: { + type: "bool", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.StringValue message. + * @interface IStringValue + * @type {Object} + * @property {string} [value] + * @memberof common + */ + StringValue: { + fields: { + value: { + type: "string", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.BytesValue message. + * @interface IBytesValue + * @type {Object} + * @property {Uint8Array} [value] + * @memberof common + */ + BytesValue: { + fields: { + value: { + type: "bytes", + id: 1 + } + } + } +}); + +common("field_mask", { + + /** + * Properties of a google.protobuf.FieldMask message. + * @interface IDoubleValue + * @type {Object} + * @property {number} [value] + * @memberof common + */ + FieldMask: { + fields: { + paths: { + rule: "repeated", + type: "string", + id: 1 + } + } + } +}); + +/** + * Gets the root definition of the specified common proto file. + * + * Bundled definitions are: + * - google/protobuf/any.proto + * - google/protobuf/duration.proto + * - google/protobuf/empty.proto + * - google/protobuf/field_mask.proto + * - google/protobuf/struct.proto + * - google/protobuf/timestamp.proto + * - google/protobuf/wrappers.proto + * + * @param {string} file Proto file name + * @returns {INamespace|null} Root definition or `null` if not defined + */ +common.get = function get(file) { + return common[file] || null; +}; diff --git a/node_modules/protobufjs/src/converter.js b/node_modules/protobufjs/src/converter.js new file mode 100644 index 0000000..086e003 --- /dev/null +++ b/node_modules/protobufjs/src/converter.js @@ -0,0 +1,301 @@ +"use strict"; +/** + * Runtime message from/to plain object converters. + * @namespace + */ +var converter = exports; + +var Enum = require("./enum"), + util = require("./util"); + +/** + * Generates a partial value fromObject conveter. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {number} fieldIndex Field index + * @param {string} prop Property reference + * @returns {Codegen} Codegen instance + * @ignore + */ +function genValuePartial_fromObject(gen, field, fieldIndex, prop) { + var defaultAlreadyEmitted = false; + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + if (field.resolvedType) { + if (field.resolvedType instanceof Enum) { gen + ("switch(d%s){", prop); + for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) { + // enum unknown values passthrough + if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen + ("default:") + ("if(typeof(d%s)===\"number\"){m%s=d%s;break}", prop, prop, prop); + if (!field.repeated) gen // fallback to default value only for + // arrays, to avoid leaving holes. + ("break"); // for non-repeated fields, just ignore + defaultAlreadyEmitted = true; + } + gen + ("case%j:", keys[i]) + ("case %i:", values[keys[i]]) + ("m%s=%j", prop, values[keys[i]]) + ("break"); + } gen + ("}"); + } else gen + ("if(typeof d%s!==\"object\")", prop) + ("throw TypeError(%j)", field.fullName + ": object expected") + ("m%s=types[%i].fromObject(d%s)", prop, fieldIndex, prop); + } else { + var isUnsigned = false; + switch (field.type) { + case "double": + case "float": gen + ("m%s=Number(d%s)", prop, prop); // also catches "NaN", "Infinity" + break; + case "uint32": + case "fixed32": gen + ("m%s=d%s>>>0", prop, prop); + break; + case "int32": + case "sint32": + case "sfixed32": gen + ("m%s=d%s|0", prop, prop); + break; + case "uint64": + isUnsigned = true; + // eslint-disable-next-line no-fallthrough + case "int64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(util.Long)") + ("(m%s=util.Long.fromValue(d%s)).unsigned=%j", prop, prop, isUnsigned) + ("else if(typeof d%s===\"string\")", prop) + ("m%s=parseInt(d%s,10)", prop, prop) + ("else if(typeof d%s===\"number\")", prop) + ("m%s=d%s", prop, prop) + ("else if(typeof d%s===\"object\")", prop) + ("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : ""); + break; + case "bytes": gen + ("if(typeof d%s===\"string\")", prop) + ("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop) + ("else if(d%s.length >= 0)", prop) + ("m%s=d%s", prop, prop); + break; + case "string": gen + ("m%s=String(d%s)", prop, prop); + break; + case "bool": gen + ("m%s=Boolean(d%s)", prop, prop); + break; + /* default: gen + ("m%s=d%s", prop, prop); + break; */ + } + } + return gen; + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ +} + +/** + * Generates a plain object to runtime message converter specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +converter.fromObject = function fromObject(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var fields = mtype.fieldsArray; + var gen = util.codegen(["d"], mtype.name + "$fromObject") + ("if(d instanceof this.ctor)") + ("return d"); + if (!fields.length) return gen + ("return new this.ctor"); + gen + ("var m=new this.ctor"); + for (var i = 0; i < fields.length; ++i) { + var field = fields[i].resolve(), + prop = util.safeProp(field.name); + + // Map fields + if (field.map) { gen + ("if(d%s){", prop) + ("if(typeof d%s!==\"object\")", prop) + ("throw TypeError(%j)", field.fullName + ": object expected") + ("m%s={}", prop) + ("for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s", prop, prop, prop, prop, isUnsigned ? "true": "", prop); + break; + case "bytes": gen + ("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", prop, prop, prop, prop, prop); + break; + default: gen + ("d%s=m%s", prop, prop); + break; + } + } + return gen; + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ +} + +/** + * Generates a runtime message to plain object converter specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +converter.toObject = function toObject(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById); + if (!fields.length) + return util.codegen()("return {}"); + var gen = util.codegen(["m", "o"], mtype.name + "$toObject") + ("if(!o)") + ("o={}") + ("var d={}"); + + var repeatedFields = [], + mapFields = [], + normalFields = [], + i = 0; + for (; i < fields.length; ++i) + if (!fields[i].partOf) + ( fields[i].resolve().repeated ? repeatedFields + : fields[i].map ? mapFields + : normalFields).push(fields[i]); + + if (repeatedFields.length) { gen + ("if(o.arrays||o.defaults){"); + for (i = 0; i < repeatedFields.length; ++i) gen + ("d%s=[]", util.safeProp(repeatedFields[i].name)); + gen + ("}"); + } + + if (mapFields.length) { gen + ("if(o.objects||o.defaults){"); + for (i = 0; i < mapFields.length; ++i) gen + ("d%s={}", util.safeProp(mapFields[i].name)); + gen + ("}"); + } + + if (normalFields.length) { gen + ("if(o.defaults){"); + for (i = 0; i < normalFields.length; ++i) { + var field = normalFields[i], + prop = util.safeProp(field.name); + if (field.resolvedType instanceof Enum) gen + ("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault); + else if (field.long) gen + ("if(util.Long){") + ("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned) + ("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n", prop) + ("}else") + ("d%s=o.longs===String?%j:%i", prop, field.typeDefault.toString(), field.typeDefault.toNumber()); + else if (field.bytes) { + var arrayDefault = "[" + Array.prototype.slice.call(field.typeDefault).join(",") + "]"; + gen + ("if(o.bytes===String)d%s=%j", prop, String.fromCharCode.apply(String, field.typeDefault)) + ("else{") + ("d%s=%s", prop, arrayDefault) + ("if(o.bytes!==Array)d%s=util.newBuffer(d%s)", prop, prop) + ("}"); + } else gen + ("d%s=%j", prop, field.typeDefault); // also messages (=null) + } gen + ("}"); + } + var hasKs2 = false; + for (i = 0; i < fields.length; ++i) { + var field = fields[i], + index = mtype._fieldsArray.indexOf(field), + prop = util.safeProp(field.name); + if (field.map) { + if (!hasKs2) { hasKs2 = true; gen + ("var ks2"); + } gen + ("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop) + ("d%s={}", prop) + ("for(var j=0;j>>3){"); + + var i = 0; + for (; i < /* initializes */ mtype.fieldsArray.length; ++i) { + var field = mtype._fieldsArray[i].resolve(), + type = field.resolvedType instanceof Enum ? "int32" : field.type, + ref = "m" + util.safeProp(field.name); gen + ("case %i: {", field.id); + + // Map fields + if (field.map) { gen + ("if(%s===util.emptyObject)", ref) + ("%s={}", ref) + ("var c2 = r.uint32()+r.pos"); + + if (types.defaults[field.keyType] !== undefined) gen + ("k=%j", types.defaults[field.keyType]); + else gen + ("k=null"); + + if (types.defaults[type] !== undefined) gen + ("value=%j", types.defaults[type]); + else gen + ("value=null"); + + gen + ("while(r.pos>>3){") + ("case 1: k=r.%s(); break", field.keyType) + ("case 2:"); + + if (types.basic[type] === undefined) gen + ("value=types[%i].decode(r,r.uint32())", i); // can't be groups + else gen + ("value=r.%s()", type); + + gen + ("break") + ("default:") + ("r.skipType(tag2&7)") + ("break") + ("}") + ("}"); + + if (types.long[field.keyType] !== undefined) gen + ("%s[typeof k===\"object\"?util.longToHash(k):k]=value", ref); + else gen + ("%s[k]=value", ref); + + // Repeated fields + } else if (field.repeated) { gen + + ("if(!(%s&&%s.length))", ref, ref) + ("%s=[]", ref); + + // Packable (always check for forward and backward compatiblity) + if (types.packed[type] !== undefined) gen + ("if((t&7)===2){") + ("var c2=r.uint32()+r.pos") + ("while(r.pos>> 0, (field.id << 3 | 4) >>> 0) + : gen("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0); +} + +/** + * Generates an encoder specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +function encoder(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var gen = util.codegen(["m", "w"], mtype.name + "$encode") + ("if(!w)") + ("w=Writer.create()"); + + var i, ref; + + // "when a message is serialized its known fields should be written sequentially by field number" + var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById); + + for (var i = 0; i < fields.length; ++i) { + var field = fields[i].resolve(), + index = mtype._fieldsArray.indexOf(field), + type = field.resolvedType instanceof Enum ? "int32" : field.type, + wireType = types.basic[type]; + ref = "m" + util.safeProp(field.name); + + // Map fields + if (field.map) { + gen + ("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){", ref, field.name) // !== undefined && !== null + ("for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType); + if (wireType === undefined) gen + ("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", index, ref); // can't be groups + else gen + (".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref); + gen + ("}") + ("}"); + + // Repeated fields + } else if (field.repeated) { gen + ("if(%s!=null&&%s.length){", ref, ref); // !== undefined && !== null + + // Packed repeated + if (field.packed && types.packed[type] !== undefined) { gen + + ("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0) + ("for(var i=0;i<%s.length;++i)", ref) + ("w.%s(%s[i])", type, ref) + ("w.ldelim()"); + + // Non-packed + } else { gen + + ("for(var i=0;i<%s.length;++i)", ref); + if (wireType === undefined) + genTypePartial(gen, field, index, ref + "[i]"); + else gen + ("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref); + + } gen + ("}"); + + // Non-repeated + } else { + if (field.optional) gen + ("if(%s!=null&&Object.hasOwnProperty.call(m,%j))", ref, field.name); // !== undefined && !== null + + if (wireType === undefined) + genTypePartial(gen, field, index, ref); + else gen + ("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref); + + } + } + + return gen + ("return w"); + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ +} diff --git a/node_modules/protobufjs/src/enum.js b/node_modules/protobufjs/src/enum.js new file mode 100644 index 0000000..8eea761 --- /dev/null +++ b/node_modules/protobufjs/src/enum.js @@ -0,0 +1,223 @@ +"use strict"; +module.exports = Enum; + +// extends ReflectionObject +var ReflectionObject = require("./object"); +((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum"; + +var Namespace = require("./namespace"), + util = require("./util"); + +/** + * Constructs a new enum instance. + * @classdesc Reflected enum. + * @extends ReflectionObject + * @constructor + * @param {string} name Unique name within its namespace + * @param {Object.} [values] Enum values as an object, by name + * @param {Object.} [options] Declared options + * @param {string} [comment] The comment for this enum + * @param {Object.} [comments] The value comments for this enum + * @param {Object.>|undefined} [valuesOptions] The value options for this enum + */ +function Enum(name, values, options, comment, comments, valuesOptions) { + ReflectionObject.call(this, name, options); + + if (values && typeof values !== "object") + throw TypeError("values must be an object"); + + /** + * Enum values by id. + * @type {Object.} + */ + this.valuesById = {}; + + /** + * Enum values by name. + * @type {Object.} + */ + this.values = Object.create(this.valuesById); // toJSON, marker + + /** + * Enum comment text. + * @type {string|null} + */ + this.comment = comment; + + /** + * Value comment texts, if any. + * @type {Object.} + */ + this.comments = comments || {}; + + /** + * Values options, if any + * @type {Object>|undefined} + */ + this.valuesOptions = valuesOptions; + + /** + * Resolved values features, if any + * @type {Object>|undefined} + */ + this._valuesFeatures = {}; + + /** + * Reserved ranges, if any. + * @type {Array.} + */ + this.reserved = undefined; // toJSON + + // Note that values inherit valuesById on their prototype which makes them a TypeScript- + // compatible enum. This is used by pbts to write actual enum definitions that work for + // static and reflection code alike instead of emitting generic object definitions. + + if (values) + for (var keys = Object.keys(values), i = 0; i < keys.length; ++i) + if (typeof values[keys[i]] === "number") // use forward entries only + this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i]; +} + +/** + * @override + */ +Enum.prototype._resolveFeatures = function _resolveFeatures(edition) { + edition = this._edition || edition; + ReflectionObject.prototype._resolveFeatures.call(this, edition); + + Object.keys(this.values).forEach(key => { + var parentFeaturesCopy = Object.assign({}, this._features); + this._valuesFeatures[key] = Object.assign(parentFeaturesCopy, this.valuesOptions && this.valuesOptions[key] && this.valuesOptions[key].features); + }); + + return this; +}; + +/** + * Enum descriptor. + * @interface IEnum + * @property {Object.} values Enum values + * @property {Object.} [options] Enum options + */ + +/** + * Constructs an enum from an enum descriptor. + * @param {string} name Enum name + * @param {IEnum} json Enum descriptor + * @returns {Enum} Created enum + * @throws {TypeError} If arguments are invalid + */ +Enum.fromJSON = function fromJSON(name, json) { + var enm = new Enum(name, json.values, json.options, json.comment, json.comments); + enm.reserved = json.reserved; + if (json.edition) + enm._edition = json.edition; + enm._defaultEdition = "proto3"; // For backwards-compatibility. + return enm; +}; + +/** + * Converts this enum to an enum descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IEnum} Enum descriptor + */ +Enum.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "edition" , this._editionToJSON(), + "options" , this.options, + "valuesOptions" , this.valuesOptions, + "values" , this.values, + "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined, + "comment" , keepComments ? this.comment : undefined, + "comments" , keepComments ? this.comments : undefined + ]); +}; + +/** + * Adds a value to this enum. + * @param {string} name Value name + * @param {number} id Value id + * @param {string} [comment] Comment, if any + * @param {Object.|undefined} [options] Options, if any + * @returns {Enum} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a value with this name or id + */ +Enum.prototype.add = function add(name, id, comment, options) { + // utilized by the parser but not by .fromJSON + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + if (!util.isInteger(id)) + throw TypeError("id must be an integer"); + + if (this.values[name] !== undefined) + throw Error("duplicate name '" + name + "' in " + this); + + if (this.isReservedId(id)) + throw Error("id " + id + " is reserved in " + this); + + if (this.isReservedName(name)) + throw Error("name '" + name + "' is reserved in " + this); + + if (this.valuesById[id] !== undefined) { + if (!(this.options && this.options.allow_alias)) + throw Error("duplicate id " + id + " in " + this); + this.values[name] = id; + } else + this.valuesById[this.values[name] = id] = name; + + if (options) { + if (this.valuesOptions === undefined) + this.valuesOptions = {}; + this.valuesOptions[name] = options || null; + } + + this.comments[name] = comment || null; + return this; +}; + +/** + * Removes a value from this enum + * @param {string} name Value name + * @returns {Enum} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `name` is not a name of this enum + */ +Enum.prototype.remove = function remove(name) { + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + var val = this.values[name]; + if (val == null) + throw Error("name '" + name + "' does not exist in " + this); + + delete this.valuesById[val]; + delete this.values[name]; + delete this.comments[name]; + if (this.valuesOptions) + delete this.valuesOptions[name]; + + return this; +}; + +/** + * Tests if the specified id is reserved. + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Enum.prototype.isReservedId = function isReservedId(id) { + return Namespace.isReservedId(this.reserved, id); +}; + +/** + * Tests if the specified name is reserved. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Enum.prototype.isReservedName = function isReservedName(name) { + return Namespace.isReservedName(this.reserved, name); +}; diff --git a/node_modules/protobufjs/src/field.js b/node_modules/protobufjs/src/field.js new file mode 100644 index 0000000..72d8f63 --- /dev/null +++ b/node_modules/protobufjs/src/field.js @@ -0,0 +1,453 @@ +"use strict"; +module.exports = Field; + +// extends ReflectionObject +var ReflectionObject = require("./object"); +((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field"; + +var Enum = require("./enum"), + types = require("./types"), + util = require("./util"); + +var Type; // cyclic + +var ruleRe = /^required|optional|repeated$/; + +/** + * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class. + * @name Field + * @classdesc Reflected message field. + * @extends FieldBase + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} type Value type + * @param {string|Object.} [rule="optional"] Field rule + * @param {string|Object.} [extend] Extended type if different from parent + * @param {Object.} [options] Declared options + */ + +/** + * Constructs a field from a field descriptor. + * @param {string} name Field name + * @param {IField} json Field descriptor + * @returns {Field} Created field + * @throws {TypeError} If arguments are invalid + */ +Field.fromJSON = function fromJSON(name, json) { + var field = new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment); + if (json.edition) + field._edition = json.edition; + field._defaultEdition = "proto3"; // For backwards-compatibility. + return field; +}; + +/** + * Not an actual constructor. Use {@link Field} instead. + * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions. + * @exports FieldBase + * @extends ReflectionObject + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} type Value type + * @param {string|Object.} [rule="optional"] Field rule + * @param {string|Object.} [extend] Extended type if different from parent + * @param {Object.} [options] Declared options + * @param {string} [comment] Comment associated with this field + */ +function Field(name, id, type, rule, extend, options, comment) { + + if (util.isObject(rule)) { + comment = extend; + options = rule; + rule = extend = undefined; + } else if (util.isObject(extend)) { + comment = options; + options = extend; + extend = undefined; + } + + ReflectionObject.call(this, name, options); + + if (!util.isInteger(id) || id < 0) + throw TypeError("id must be a non-negative integer"); + + if (!util.isString(type)) + throw TypeError("type must be a string"); + + if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase())) + throw TypeError("rule must be a string rule"); + + if (extend !== undefined && !util.isString(extend)) + throw TypeError("extend must be a string"); + + /** + * Field rule, if any. + * @type {string|undefined} + */ + if (rule === "proto3_optional") { + rule = "optional"; + } + this.rule = rule && rule !== "optional" ? rule : undefined; // toJSON + + /** + * Field type. + * @type {string} + */ + this.type = type; // toJSON + + /** + * Unique field id. + * @type {number} + */ + this.id = id; // toJSON, marker + + /** + * Extended type if different from parent. + * @type {string|undefined} + */ + this.extend = extend || undefined; // toJSON + + /** + * Whether this field is repeated. + * @type {boolean} + */ + this.repeated = rule === "repeated"; + + /** + * Whether this field is a map or not. + * @type {boolean} + */ + this.map = false; + + /** + * Message this field belongs to. + * @type {Type|null} + */ + this.message = null; + + /** + * OneOf this field belongs to, if any, + * @type {OneOf|null} + */ + this.partOf = null; + + /** + * The field type's default value. + * @type {*} + */ + this.typeDefault = null; + + /** + * The field's default value on prototypes. + * @type {*} + */ + this.defaultValue = null; + + /** + * Whether this field's value should be treated as a long. + * @type {boolean} + */ + this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false; + + /** + * Whether this field's value is a buffer. + * @type {boolean} + */ + this.bytes = type === "bytes"; + + /** + * Resolved type if not a basic type. + * @type {Type|Enum|null} + */ + this.resolvedType = null; + + /** + * Sister-field within the extended type if a declaring extension field. + * @type {Field|null} + */ + this.extensionField = null; + + /** + * Sister-field within the declaring namespace if an extended field. + * @type {Field|null} + */ + this.declaringField = null; + + /** + * Comment for this field. + * @type {string|null} + */ + this.comment = comment; +} + +/** + * Determines whether this field is required. + * @name Field#required + * @type {boolean} + * @readonly + */ +Object.defineProperty(Field.prototype, "required", { + get: function() { + return this._features.field_presence === "LEGACY_REQUIRED"; + } +}); + +/** + * Determines whether this field is not required. + * @name Field#optional + * @type {boolean} + * @readonly + */ +Object.defineProperty(Field.prototype, "optional", { + get: function() { + return !this.required; + } +}); + +/** + * Determines whether this field uses tag-delimited encoding. In proto2 this + * corresponded to group syntax. + * @name Field#delimited + * @type {boolean} + * @readonly + */ +Object.defineProperty(Field.prototype, "delimited", { + get: function() { + return this.resolvedType instanceof Type && + this._features.message_encoding === "DELIMITED"; + } +}); + +/** + * Determines whether this field is packed. Only relevant when repeated. + * @name Field#packed + * @type {boolean} + * @readonly + */ +Object.defineProperty(Field.prototype, "packed", { + get: function() { + return this._features.repeated_field_encoding === "PACKED"; + } +}); + +/** + * Determines whether this field tracks presence. + * @name Field#hasPresence + * @type {boolean} + * @readonly + */ +Object.defineProperty(Field.prototype, "hasPresence", { + get: function() { + if (this.repeated || this.map) { + return false; + } + return this.partOf || // oneofs + this.declaringField || this.extensionField || // extensions + this._features.field_presence !== "IMPLICIT"; + } +}); + +/** + * @override + */ +Field.prototype.setOption = function setOption(name, value, ifNotSet) { + return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet); +}; + +/** + * Field descriptor. + * @interface IField + * @property {string} [rule="optional"] Field rule + * @property {string} type Field type + * @property {number} id Field id + * @property {Object.} [options] Field options + */ + +/** + * Extension field descriptor. + * @interface IExtensionField + * @extends IField + * @property {string} extend Extended type + */ + +/** + * Converts this field to a field descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IField} Field descriptor + */ +Field.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "edition" , this._editionToJSON(), + "rule" , this.rule !== "optional" && this.rule || undefined, + "type" , this.type, + "id" , this.id, + "extend" , this.extend, + "options" , this.options, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * Resolves this field's type references. + * @returns {Field} `this` + * @throws {Error} If any reference cannot be resolved + */ +Field.prototype.resolve = function resolve() { + + if (this.resolved) + return this; + + if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it + this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type); + if (this.resolvedType instanceof Type) + this.typeDefault = null; + else // instanceof Enum + this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined + } else if (this.options && this.options.proto3_optional) { + // proto3 scalar value marked optional; should default to null + this.typeDefault = null; + } + + // use explicitly set default value if present + if (this.options && this.options["default"] != null) { + this.typeDefault = this.options["default"]; + if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string") + this.typeDefault = this.resolvedType.values[this.typeDefault]; + } + + // remove unnecessary options + if (this.options) { + if (this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum)) + delete this.options.packed; + if (!Object.keys(this.options).length) + this.options = undefined; + } + + // convert to internal data type if necesssary + if (this.long) { + this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u"); + + /* istanbul ignore else */ + if (Object.freeze) + Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it) + + } else if (this.bytes && typeof this.typeDefault === "string") { + var buf; + if (util.base64.test(this.typeDefault)) + util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0); + else + util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0); + this.typeDefault = buf; + } + + // take special care of maps and repeated fields + if (this.map) + this.defaultValue = util.emptyObject; + else if (this.repeated) + this.defaultValue = util.emptyArray; + else + this.defaultValue = this.typeDefault; + + // ensure proper value on prototype + if (this.parent instanceof Type) + this.parent.ctor.prototype[this.name] = this.defaultValue; + + return ReflectionObject.prototype.resolve.call(this); +}; + +/** + * Infers field features from legacy syntax that may have been specified differently. + * in older editions. + * @param {string|undefined} edition The edition this proto is on, or undefined if pre-editions + * @returns {object} The feature values to override + */ +Field.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(edition) { + if (edition !== "proto2" && edition !== "proto3") { + return {}; + } + + var features = {}; + + if (this.rule === "required") { + features.field_presence = "LEGACY_REQUIRED"; + } + if (this.parent && types.defaults[this.type] === undefined) { + // We can't use resolvedType because types may not have been resolved yet. However, + // legacy groups are always in the same scope as the field so we don't have to do a + // full scan of the tree. + var type = this.parent.get(this.type.split(".").pop()); + if (type && type instanceof Type && type.group) { + features.message_encoding = "DELIMITED"; + } + } + if (this.getOption("packed") === true) { + features.repeated_field_encoding = "PACKED"; + } else if (this.getOption("packed") === false) { + features.repeated_field_encoding = "EXPANDED"; + } + return features; +}; + +/** + * @override + */ +Field.prototype._resolveFeatures = function _resolveFeatures(edition) { + return ReflectionObject.prototype._resolveFeatures.call(this, this._edition || edition); +}; + +/** + * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript). + * @typedef FieldDecorator + * @type {function} + * @param {Object} prototype Target prototype + * @param {string} fieldName Field name + * @returns {undefined} + */ + +/** + * Field decorator (TypeScript). + * @name Field.d + * @function + * @param {number} fieldId Field id + * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"string"|"bool"|"bytes"|Object} fieldType Field type + * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule + * @param {T} [defaultValue] Default value + * @returns {FieldDecorator} Decorator function + * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[] + */ +Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) { + + // submessage: decorate the submessage and use its name as the type + if (typeof fieldType === "function") + fieldType = util.decorateType(fieldType).name; + + // enum reference: create a reflected copy of the enum and keep reuseing it + else if (fieldType && typeof fieldType === "object") + fieldType = util.decorateEnum(fieldType).name; + + return function fieldDecorator(prototype, fieldName) { + util.decorateType(prototype.constructor) + .add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue })); + }; +}; + +/** + * Field decorator (TypeScript). + * @name Field.d + * @function + * @param {number} fieldId Field id + * @param {Constructor|string} fieldType Field type + * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule + * @returns {FieldDecorator} Decorator function + * @template T extends Message + * @variation 2 + */ +// like Field.d but without a default value + +// Sets up cyclic dependencies (called in index-light) +Field._configure = function configure(Type_) { + Type = Type_; +}; diff --git a/node_modules/protobufjs/src/index-light.js b/node_modules/protobufjs/src/index-light.js new file mode 100644 index 0000000..32c6a05 --- /dev/null +++ b/node_modules/protobufjs/src/index-light.js @@ -0,0 +1,104 @@ +"use strict"; +var protobuf = module.exports = require("./index-minimal"); + +protobuf.build = "light"; + +/** + * A node-style callback as used by {@link load} and {@link Root#load}. + * @typedef LoadCallback + * @type {function} + * @param {Error|null} error Error, if any, otherwise `null` + * @param {Root} [root] Root, if there hasn't been an error + * @returns {undefined} + */ + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. + * @param {string|string[]} filename One or multiple files to load + * @param {Root} root Root namespace, defaults to create a new one if omitted. + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @see {@link Root#load} + */ +function load(filename, root, callback) { + if (typeof root === "function") { + callback = root; + root = new protobuf.Root(); + } else if (!root) + root = new protobuf.Root(); + return root.load(filename, callback); +} + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. + * @name load + * @function + * @param {string|string[]} filename One or multiple files to load + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @see {@link Root#load} + * @variation 2 + */ +// function load(filename:string, callback:LoadCallback):undefined + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise. + * @name load + * @function + * @param {string|string[]} filename One or multiple files to load + * @param {Root} [root] Root namespace, defaults to create a new one if omitted. + * @returns {Promise} Promise + * @see {@link Root#load} + * @variation 3 + */ +// function load(filename:string, [root:Root]):Promise + +protobuf.load = load; + +/** + * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only). + * @param {string|string[]} filename One or multiple files to load + * @param {Root} [root] Root namespace, defaults to create a new one if omitted. + * @returns {Root} Root namespace + * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid + * @see {@link Root#loadSync} + */ +function loadSync(filename, root) { + if (!root) + root = new protobuf.Root(); + return root.loadSync(filename); +} + +protobuf.loadSync = loadSync; + +// Serialization +protobuf.encoder = require("./encoder"); +protobuf.decoder = require("./decoder"); +protobuf.verifier = require("./verifier"); +protobuf.converter = require("./converter"); + +// Reflection +protobuf.ReflectionObject = require("./object"); +protobuf.Namespace = require("./namespace"); +protobuf.Root = require("./root"); +protobuf.Enum = require("./enum"); +protobuf.Type = require("./type"); +protobuf.Field = require("./field"); +protobuf.OneOf = require("./oneof"); +protobuf.MapField = require("./mapfield"); +protobuf.Service = require("./service"); +protobuf.Method = require("./method"); + +// Runtime +protobuf.Message = require("./message"); +protobuf.wrappers = require("./wrappers"); + +// Utility +protobuf.types = require("./types"); +protobuf.util = require("./util"); + +// Set up possibly cyclic reflection dependencies +protobuf.ReflectionObject._configure(protobuf.Root); +protobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum); +protobuf.Root._configure(protobuf.Type); +protobuf.Field._configure(protobuf.Type); diff --git a/node_modules/protobufjs/src/index-minimal.js b/node_modules/protobufjs/src/index-minimal.js new file mode 100644 index 0000000..1f4aaea --- /dev/null +++ b/node_modules/protobufjs/src/index-minimal.js @@ -0,0 +1,36 @@ +"use strict"; +var protobuf = exports; + +/** + * Build type, one of `"full"`, `"light"` or `"minimal"`. + * @name build + * @type {string} + * @const + */ +protobuf.build = "minimal"; + +// Serialization +protobuf.Writer = require("./writer"); +protobuf.BufferWriter = require("./writer_buffer"); +protobuf.Reader = require("./reader"); +protobuf.BufferReader = require("./reader_buffer"); + +// Utility +protobuf.util = require("./util/minimal"); +protobuf.rpc = require("./rpc"); +protobuf.roots = require("./roots"); +protobuf.configure = configure; + +/* istanbul ignore next */ +/** + * Reconfigures the library according to the environment. + * @returns {undefined} + */ +function configure() { + protobuf.util._configure(); + protobuf.Writer._configure(protobuf.BufferWriter); + protobuf.Reader._configure(protobuf.BufferReader); +} + +// Set up buffer utility according to the environment +configure(); diff --git a/node_modules/protobufjs/src/index.js b/node_modules/protobufjs/src/index.js new file mode 100644 index 0000000..56bd3d5 --- /dev/null +++ b/node_modules/protobufjs/src/index.js @@ -0,0 +1,12 @@ +"use strict"; +var protobuf = module.exports = require("./index-light"); + +protobuf.build = "full"; + +// Parser +protobuf.tokenize = require("./tokenize"); +protobuf.parse = require("./parse"); +protobuf.common = require("./common"); + +// Configure parser +protobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common); diff --git a/node_modules/protobufjs/src/mapfield.js b/node_modules/protobufjs/src/mapfield.js new file mode 100644 index 0000000..67c7097 --- /dev/null +++ b/node_modules/protobufjs/src/mapfield.js @@ -0,0 +1,126 @@ +"use strict"; +module.exports = MapField; + +// extends Field +var Field = require("./field"); +((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField"; + +var types = require("./types"), + util = require("./util"); + +/** + * Constructs a new map field instance. + * @classdesc Reflected map field. + * @extends FieldBase + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} keyType Key type + * @param {string} type Value type + * @param {Object.} [options] Declared options + * @param {string} [comment] Comment associated with this field + */ +function MapField(name, id, keyType, type, options, comment) { + Field.call(this, name, id, type, undefined, undefined, options, comment); + + /* istanbul ignore if */ + if (!util.isString(keyType)) + throw TypeError("keyType must be a string"); + + /** + * Key type. + * @type {string} + */ + this.keyType = keyType; // toJSON, marker + + /** + * Resolved key type if not a basic type. + * @type {ReflectionObject|null} + */ + this.resolvedKeyType = null; + + // Overrides Field#map + this.map = true; +} + +/** + * Map field descriptor. + * @interface IMapField + * @extends {IField} + * @property {string} keyType Key type + */ + +/** + * Extension map field descriptor. + * @interface IExtensionMapField + * @extends IMapField + * @property {string} extend Extended type + */ + +/** + * Constructs a map field from a map field descriptor. + * @param {string} name Field name + * @param {IMapField} json Map field descriptor + * @returns {MapField} Created map field + * @throws {TypeError} If arguments are invalid + */ +MapField.fromJSON = function fromJSON(name, json) { + return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment); +}; + +/** + * Converts this map field to a map field descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IMapField} Map field descriptor + */ +MapField.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "keyType" , this.keyType, + "type" , this.type, + "id" , this.id, + "extend" , this.extend, + "options" , this.options, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * @override + */ +MapField.prototype.resolve = function resolve() { + if (this.resolved) + return this; + + // Besides a value type, map fields have a key type that may be "any scalar type except for floating point types and bytes" + if (types.mapKey[this.keyType] === undefined) + throw Error("invalid key type: " + this.keyType); + + return Field.prototype.resolve.call(this); +}; + +/** + * Map field decorator (TypeScript). + * @name MapField.d + * @function + * @param {number} fieldId Field id + * @param {"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"} fieldKeyType Field key type + * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"|"bytes"|Object|Constructor<{}>} fieldValueType Field value type + * @returns {FieldDecorator} Decorator function + * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> } + */ +MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) { + + // submessage value: decorate the submessage and use its name as the type + if (typeof fieldValueType === "function") + fieldValueType = util.decorateType(fieldValueType).name; + + // enum reference value: create a reflected copy of the enum and keep reuseing it + else if (fieldValueType && typeof fieldValueType === "object") + fieldValueType = util.decorateEnum(fieldValueType).name; + + return function mapFieldDecorator(prototype, fieldName) { + util.decorateType(prototype.constructor) + .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType)); + }; +}; diff --git a/node_modules/protobufjs/src/message.js b/node_modules/protobufjs/src/message.js new file mode 100644 index 0000000..3f94bf6 --- /dev/null +++ b/node_modules/protobufjs/src/message.js @@ -0,0 +1,139 @@ +"use strict"; +module.exports = Message; + +var util = require("./util/minimal"); + +/** + * Constructs a new message instance. + * @classdesc Abstract runtime message. + * @constructor + * @param {Properties} [properties] Properties to set + * @template T extends object = object + */ +function Message(properties) { + // not used internally + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + this[keys[i]] = properties[keys[i]]; +} + +/** + * Reference to the reflected type. + * @name Message.$type + * @type {Type} + * @readonly + */ + +/** + * Reference to the reflected type. + * @name Message#$type + * @type {Type} + * @readonly + */ + +/*eslint-disable valid-jsdoc*/ + +/** + * Creates a new message of this type using the specified properties. + * @param {Object.} [properties] Properties to set + * @returns {Message} Message instance + * @template T extends Message + * @this Constructor + */ +Message.create = function create(properties) { + return this.$type.create(properties); +}; + +/** + * Encodes a message of this type. + * @param {T|Object.} message Message to encode + * @param {Writer} [writer] Writer to use + * @returns {Writer} Writer + * @template T extends Message + * @this Constructor + */ +Message.encode = function encode(message, writer) { + return this.$type.encode(message, writer); +}; + +/** + * Encodes a message of this type preceeded by its length as a varint. + * @param {T|Object.} message Message to encode + * @param {Writer} [writer] Writer to use + * @returns {Writer} Writer + * @template T extends Message + * @this Constructor + */ +Message.encodeDelimited = function encodeDelimited(message, writer) { + return this.$type.encodeDelimited(message, writer); +}; + +/** + * Decodes a message of this type. + * @name Message.decode + * @function + * @param {Reader|Uint8Array} reader Reader or buffer to decode + * @returns {T} Decoded message + * @template T extends Message + * @this Constructor + */ +Message.decode = function decode(reader) { + return this.$type.decode(reader); +}; + +/** + * Decodes a message of this type preceeded by its length as a varint. + * @name Message.decodeDelimited + * @function + * @param {Reader|Uint8Array} reader Reader or buffer to decode + * @returns {T} Decoded message + * @template T extends Message + * @this Constructor + */ +Message.decodeDelimited = function decodeDelimited(reader) { + return this.$type.decodeDelimited(reader); +}; + +/** + * Verifies a message of this type. + * @name Message.verify + * @function + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ +Message.verify = function verify(message) { + return this.$type.verify(message); +}; + +/** + * Creates a new message of this type from a plain object. Also converts values to their respective internal types. + * @param {Object.} object Plain object + * @returns {T} Message instance + * @template T extends Message + * @this Constructor + */ +Message.fromObject = function fromObject(object) { + return this.$type.fromObject(object); +}; + +/** + * Creates a plain object from a message of this type. Also converts values to other types if specified. + * @param {T} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + * @template T extends Message + * @this Constructor + */ +Message.toObject = function toObject(message, options) { + return this.$type.toObject(message, options); +}; + +/** + * Converts this message to JSON. + * @returns {Object.} JSON object + */ +Message.prototype.toJSON = function toJSON() { + return this.$type.toObject(this, util.toJSONOptions); +}; + +/*eslint-enable valid-jsdoc*/ \ No newline at end of file diff --git a/node_modules/protobufjs/src/method.js b/node_modules/protobufjs/src/method.js new file mode 100644 index 0000000..18a6ab2 --- /dev/null +++ b/node_modules/protobufjs/src/method.js @@ -0,0 +1,160 @@ +"use strict"; +module.exports = Method; + +// extends ReflectionObject +var ReflectionObject = require("./object"); +((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method"; + +var util = require("./util"); + +/** + * Constructs a new service method instance. + * @classdesc Reflected service method. + * @extends ReflectionObject + * @constructor + * @param {string} name Method name + * @param {string|undefined} type Method type, usually `"rpc"` + * @param {string} requestType Request message type + * @param {string} responseType Response message type + * @param {boolean|Object.} [requestStream] Whether the request is streamed + * @param {boolean|Object.} [responseStream] Whether the response is streamed + * @param {Object.} [options] Declared options + * @param {string} [comment] The comment for this method + * @param {Object.} [parsedOptions] Declared options, properly parsed into an object + */ +function Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) { + + /* istanbul ignore next */ + if (util.isObject(requestStream)) { + options = requestStream; + requestStream = responseStream = undefined; + } else if (util.isObject(responseStream)) { + options = responseStream; + responseStream = undefined; + } + + /* istanbul ignore if */ + if (!(type === undefined || util.isString(type))) + throw TypeError("type must be a string"); + + /* istanbul ignore if */ + if (!util.isString(requestType)) + throw TypeError("requestType must be a string"); + + /* istanbul ignore if */ + if (!util.isString(responseType)) + throw TypeError("responseType must be a string"); + + ReflectionObject.call(this, name, options); + + /** + * Method type. + * @type {string} + */ + this.type = type || "rpc"; // toJSON + + /** + * Request type. + * @type {string} + */ + this.requestType = requestType; // toJSON, marker + + /** + * Whether requests are streamed or not. + * @type {boolean|undefined} + */ + this.requestStream = requestStream ? true : undefined; // toJSON + + /** + * Response type. + * @type {string} + */ + this.responseType = responseType; // toJSON + + /** + * Whether responses are streamed or not. + * @type {boolean|undefined} + */ + this.responseStream = responseStream ? true : undefined; // toJSON + + /** + * Resolved request type. + * @type {Type|null} + */ + this.resolvedRequestType = null; + + /** + * Resolved response type. + * @type {Type|null} + */ + this.resolvedResponseType = null; + + /** + * Comment for this method + * @type {string|null} + */ + this.comment = comment; + + /** + * Options properly parsed into an object + */ + this.parsedOptions = parsedOptions; +} + +/** + * Method descriptor. + * @interface IMethod + * @property {string} [type="rpc"] Method type + * @property {string} requestType Request type + * @property {string} responseType Response type + * @property {boolean} [requestStream=false] Whether requests are streamed + * @property {boolean} [responseStream=false] Whether responses are streamed + * @property {Object.} [options] Method options + * @property {string} comment Method comments + * @property {Object.} [parsedOptions] Method options properly parsed into an object + */ + +/** + * Constructs a method from a method descriptor. + * @param {string} name Method name + * @param {IMethod} json Method descriptor + * @returns {Method} Created method + * @throws {TypeError} If arguments are invalid + */ +Method.fromJSON = function fromJSON(name, json) { + return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions); +}; + +/** + * Converts this method to a method descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IMethod} Method descriptor + */ +Method.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "type" , this.type !== "rpc" && /* istanbul ignore next */ this.type || undefined, + "requestType" , this.requestType, + "requestStream" , this.requestStream, + "responseType" , this.responseType, + "responseStream" , this.responseStream, + "options" , this.options, + "comment" , keepComments ? this.comment : undefined, + "parsedOptions" , this.parsedOptions, + ]); +}; + +/** + * @override + */ +Method.prototype.resolve = function resolve() { + + /* istanbul ignore if */ + if (this.resolved) + return this; + + this.resolvedRequestType = this.parent.lookupType(this.requestType); + this.resolvedResponseType = this.parent.lookupType(this.responseType); + + return ReflectionObject.prototype.resolve.call(this); +}; diff --git a/node_modules/protobufjs/src/namespace.js b/node_modules/protobufjs/src/namespace.js new file mode 100644 index 0000000..3169280 --- /dev/null +++ b/node_modules/protobufjs/src/namespace.js @@ -0,0 +1,546 @@ +"use strict"; +module.exports = Namespace; + +// extends ReflectionObject +var ReflectionObject = require("./object"); +((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace"; + +var Field = require("./field"), + util = require("./util"), + OneOf = require("./oneof"); + +var Type, // cyclic + Service, + Enum; + +/** + * Constructs a new namespace instance. + * @name Namespace + * @classdesc Reflected namespace. + * @extends NamespaceBase + * @constructor + * @param {string} name Namespace name + * @param {Object.} [options] Declared options + */ + +/** + * Constructs a namespace from JSON. + * @memberof Namespace + * @function + * @param {string} name Namespace name + * @param {Object.} json JSON object + * @returns {Namespace} Created namespace + * @throws {TypeError} If arguments are invalid + */ +Namespace.fromJSON = function fromJSON(name, json) { + return new Namespace(name, json.options).addJSON(json.nested); +}; + +/** + * Converts an array of reflection objects to JSON. + * @memberof Namespace + * @param {ReflectionObject[]} array Object array + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {Object.|undefined} JSON object or `undefined` when array is empty + */ +function arrayToJSON(array, toJSONOptions) { + if (!(array && array.length)) + return undefined; + var obj = {}; + for (var i = 0; i < array.length; ++i) + obj[array[i].name] = array[i].toJSON(toJSONOptions); + return obj; +} + +Namespace.arrayToJSON = arrayToJSON; + +/** + * Tests if the specified id is reserved. + * @param {Array.|undefined} reserved Array of reserved ranges and names + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Namespace.isReservedId = function isReservedId(reserved, id) { + if (reserved) + for (var i = 0; i < reserved.length; ++i) + if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] > id) + return true; + return false; +}; + +/** + * Tests if the specified name is reserved. + * @param {Array.|undefined} reserved Array of reserved ranges and names + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Namespace.isReservedName = function isReservedName(reserved, name) { + if (reserved) + for (var i = 0; i < reserved.length; ++i) + if (reserved[i] === name) + return true; + return false; +}; + +/** + * Not an actual constructor. Use {@link Namespace} instead. + * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions. + * @exports NamespaceBase + * @extends ReflectionObject + * @abstract + * @constructor + * @param {string} name Namespace name + * @param {Object.} [options] Declared options + * @see {@link Namespace} + */ +function Namespace(name, options) { + ReflectionObject.call(this, name, options); + + /** + * Nested objects by name. + * @type {Object.|undefined} + */ + this.nested = undefined; // toJSON + + /** + * Cached nested objects as an array. + * @type {ReflectionObject[]|null} + * @private + */ + this._nestedArray = null; + + /** + * Cache lookup calls for any objects contains anywhere under this namespace. + * This drastically speeds up resolve for large cross-linked protos where the same + * types are looked up repeatedly. + * @type {Object.} + * @private + */ + this._lookupCache = {}; + + /** + * Whether or not objects contained in this namespace need feature resolution. + * @type {boolean} + * @protected + */ + this._needsRecursiveFeatureResolution = true; + + /** + * Whether or not objects contained in this namespace need a resolve. + * @type {boolean} + * @protected + */ + this._needsRecursiveResolve = true; +} + +function clearCache(namespace) { + namespace._nestedArray = null; + namespace._lookupCache = {}; + + // Also clear parent caches, since they include nested lookups. + var parent = namespace; + while(parent = parent.parent) { + parent._lookupCache = {}; + } + return namespace; +} + +/** + * Nested objects of this namespace as an array for iteration. + * @name NamespaceBase#nestedArray + * @type {ReflectionObject[]} + * @readonly + */ +Object.defineProperty(Namespace.prototype, "nestedArray", { + get: function() { + return this._nestedArray || (this._nestedArray = util.toArray(this.nested)); + } +}); + +/** + * Namespace descriptor. + * @interface INamespace + * @property {Object.} [options] Namespace options + * @property {Object.} [nested] Nested object descriptors + */ + +/** + * Any extension field descriptor. + * @typedef AnyExtensionField + * @type {IExtensionField|IExtensionMapField} + */ + +/** + * Any nested object descriptor. + * @typedef AnyNestedObject + * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf} + */ + +/** + * Converts this namespace to a namespace descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {INamespace} Namespace descriptor + */ +Namespace.prototype.toJSON = function toJSON(toJSONOptions) { + return util.toObject([ + "options" , this.options, + "nested" , arrayToJSON(this.nestedArray, toJSONOptions) + ]); +}; + +/** + * Adds nested objects to this namespace from nested object descriptors. + * @param {Object.} nestedJson Any nested object descriptors + * @returns {Namespace} `this` + */ +Namespace.prototype.addJSON = function addJSON(nestedJson) { + var ns = this; + /* istanbul ignore else */ + if (nestedJson) { + for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) { + nested = nestedJson[names[i]]; + ns.add( // most to least likely + ( nested.fields !== undefined + ? Type.fromJSON + : nested.values !== undefined + ? Enum.fromJSON + : nested.methods !== undefined + ? Service.fromJSON + : nested.id !== undefined + ? Field.fromJSON + : Namespace.fromJSON )(names[i], nested) + ); + } + } + return this; +}; + +/** + * Gets the nested object of the specified name. + * @param {string} name Nested object name + * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist + */ +Namespace.prototype.get = function get(name) { + return this.nested && this.nested[name] + || null; +}; + +/** + * Gets the values of the nested {@link Enum|enum} of the specified name. + * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`. + * @param {string} name Nested enum name + * @returns {Object.} Enum values + * @throws {Error} If there is no such enum + */ +Namespace.prototype.getEnum = function getEnum(name) { + if (this.nested && this.nested[name] instanceof Enum) + return this.nested[name].values; + throw Error("no such enum: " + name); +}; + +/** + * Adds a nested object to this namespace. + * @param {ReflectionObject} object Nested object to add + * @returns {Namespace} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a nested object with this name + */ +Namespace.prototype.add = function add(object) { + + if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace)) + throw TypeError("object must be a valid nested object"); + + if (!this.nested) + this.nested = {}; + else { + var prev = this.get(object.name); + if (prev) { + if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) { + // replace plain namespace but keep existing nested elements and options + var nested = prev.nestedArray; + for (var i = 0; i < nested.length; ++i) + object.add(nested[i]); + this.remove(prev); + if (!this.nested) + this.nested = {}; + object.setOptions(prev.options, true); + + } else + throw Error("duplicate name '" + object.name + "' in " + this); + } + } + this.nested[object.name] = object; + + if (!(this instanceof Type || this instanceof Service || this instanceof Enum || this instanceof Field)) { + // This is a package or a root namespace. + if (!object._edition) { + // Make sure that some edition is set if it hasn't already been specified. + object._edition = object._defaultEdition; + } + } + + this._needsRecursiveFeatureResolution = true; + this._needsRecursiveResolve = true; + + // Also clear parent caches, since they need to recurse down. + var parent = this; + while(parent = parent.parent) { + parent._needsRecursiveFeatureResolution = true; + parent._needsRecursiveResolve = true; + } + + object.onAdd(this); + return clearCache(this); +}; + +/** + * Removes a nested object from this namespace. + * @param {ReflectionObject} object Nested object to remove + * @returns {Namespace} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `object` is not a member of this namespace + */ +Namespace.prototype.remove = function remove(object) { + + if (!(object instanceof ReflectionObject)) + throw TypeError("object must be a ReflectionObject"); + if (object.parent !== this) + throw Error(object + " is not a member of " + this); + + delete this.nested[object.name]; + if (!Object.keys(this.nested).length) + this.nested = undefined; + + object.onRemove(this); + return clearCache(this); +}; + +/** + * Defines additial namespaces within this one if not yet existing. + * @param {string|string[]} path Path to create + * @param {*} [json] Nested types to create from JSON + * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty + */ +Namespace.prototype.define = function define(path, json) { + + if (util.isString(path)) + path = path.split("."); + else if (!Array.isArray(path)) + throw TypeError("illegal path"); + if (path && path.length && path[0] === "") + throw Error("path must be relative"); + + var ptr = this; + while (path.length > 0) { + var part = path.shift(); + if (ptr.nested && ptr.nested[part]) { + ptr = ptr.nested[part]; + if (!(ptr instanceof Namespace)) + throw Error("path conflicts with non-namespace objects"); + } else + ptr.add(ptr = new Namespace(part)); + } + if (json) + ptr.addJSON(json); + return ptr; +}; + +/** + * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost. + * @returns {Namespace} `this` + */ +Namespace.prototype.resolveAll = function resolveAll() { + if (!this._needsRecursiveResolve) return this; + + this._resolveFeaturesRecursive(this._edition); + + var nested = this.nestedArray, i = 0; + this.resolve(); + while (i < nested.length) + if (nested[i] instanceof Namespace) + nested[i++].resolveAll(); + else + nested[i++].resolve(); + this._needsRecursiveResolve = false; + return this; +}; + +/** + * @override + */ +Namespace.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { + if (!this._needsRecursiveFeatureResolution) return this; + this._needsRecursiveFeatureResolution = false; + + edition = this._edition || edition; + + ReflectionObject.prototype._resolveFeaturesRecursive.call(this, edition); + this.nestedArray.forEach(nested => { + nested._resolveFeaturesRecursive(edition); + }); + return this; +}; + +/** + * Recursively looks up the reflection object matching the specified path in the scope of this namespace. + * @param {string|string[]} path Path to look up + * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc. + * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked + * @returns {ReflectionObject|null} Looked up object or `null` if none could be found + */ +Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) { + /* istanbul ignore next */ + if (typeof filterTypes === "boolean") { + parentAlreadyChecked = filterTypes; + filterTypes = undefined; + } else if (filterTypes && !Array.isArray(filterTypes)) + filterTypes = [ filterTypes ]; + + if (util.isString(path) && path.length) { + if (path === ".") + return this.root; + path = path.split("."); + } else if (!path.length) + return this; + + var flatPath = path.join("."); + + // Start at root if path is absolute + if (path[0] === "") + return this.root.lookup(path.slice(1), filterTypes); + + // Early bailout for objects with matching absolute paths + var found = this.root._fullyQualifiedObjects && this.root._fullyQualifiedObjects["." + flatPath]; + if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { + return found; + } + + // Do a regular lookup at this namespace and below + found = this._lookupImpl(path, flatPath); + if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { + return found; + } + + if (parentAlreadyChecked) + return null; + + // If there hasn't been a match, walk up the tree and look more broadly + var current = this; + while (current.parent) { + found = current.parent._lookupImpl(path, flatPath); + if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { + return found; + } + current = current.parent; + } + return null; +}; + +/** + * Internal helper for lookup that handles searching just at this namespace and below along with caching. + * @param {string[]} path Path to look up + * @param {string} flatPath Flattened version of the path to use as a cache key + * @returns {ReflectionObject|null} Looked up object or `null` if none could be found + * @private + */ +Namespace.prototype._lookupImpl = function lookup(path, flatPath) { + if(Object.prototype.hasOwnProperty.call(this._lookupCache, flatPath)) { + return this._lookupCache[flatPath]; + } + + // Test if the first part matches any nested object, and if so, traverse if path contains more + var found = this.get(path[0]); + var exact = null; + if (found) { + if (path.length === 1) { + exact = found; + } else if (found instanceof Namespace) { + path = path.slice(1); + exact = found._lookupImpl(path, path.join(".")); + } + + // Otherwise try each nested namespace + } else { + for (var i = 0; i < this.nestedArray.length; ++i) + if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i]._lookupImpl(path, flatPath))) + exact = found; + } + + // Set this even when null, so that when we walk up the tree we can quickly bail on repeated checks back down. + this._lookupCache[flatPath] = exact; + return exact; +}; + +/** + * Looks up the reflection object at the specified path, relative to this namespace. + * @name NamespaceBase#lookup + * @function + * @param {string|string[]} path Path to look up + * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked + * @returns {ReflectionObject|null} Looked up object or `null` if none could be found + * @variation 2 + */ +// lookup(path: string, [parentAlreadyChecked: boolean]) + +/** + * Looks up the {@link Type|type} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Type} Looked up type + * @throws {Error} If `path` does not point to a type + */ +Namespace.prototype.lookupType = function lookupType(path) { + var found = this.lookup(path, [ Type ]); + if (!found) + throw Error("no such type: " + path); + return found; +}; + +/** + * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Enum} Looked up enum + * @throws {Error} If `path` does not point to an enum + */ +Namespace.prototype.lookupEnum = function lookupEnum(path) { + var found = this.lookup(path, [ Enum ]); + if (!found) + throw Error("no such Enum '" + path + "' in " + this); + return found; +}; + +/** + * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Type} Looked up type or enum + * @throws {Error} If `path` does not point to a type or enum + */ +Namespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) { + var found = this.lookup(path, [ Type, Enum ]); + if (!found) + throw Error("no such Type or Enum '" + path + "' in " + this); + return found; +}; + +/** + * Looks up the {@link Service|service} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Service} Looked up service + * @throws {Error} If `path` does not point to a service + */ +Namespace.prototype.lookupService = function lookupService(path) { + var found = this.lookup(path, [ Service ]); + if (!found) + throw Error("no such Service '" + path + "' in " + this); + return found; +}; + +// Sets up cyclic dependencies (called in index-light) +Namespace._configure = function(Type_, Service_, Enum_) { + Type = Type_; + Service = Service_; + Enum = Enum_; +}; diff --git a/node_modules/protobufjs/src/object.js b/node_modules/protobufjs/src/object.js new file mode 100644 index 0000000..8eb2310 --- /dev/null +++ b/node_modules/protobufjs/src/object.js @@ -0,0 +1,378 @@ +"use strict"; +module.exports = ReflectionObject; + +ReflectionObject.className = "ReflectionObject"; + +const OneOf = require("./oneof"); +var util = require("./util"); + +var Root; // cyclic + +/* eslint-disable no-warning-comments */ +// TODO: Replace with embedded proto. +var editions2023Defaults = {enum_type: "OPEN", field_presence: "EXPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY"}; +var proto2Defaults = {enum_type: "CLOSED", field_presence: "EXPLICIT", json_format: "LEGACY_BEST_EFFORT", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "EXPANDED", utf8_validation: "NONE"}; +var proto3Defaults = {enum_type: "OPEN", field_presence: "IMPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY"}; + +/** + * Constructs a new reflection object instance. + * @classdesc Base class of all reflection objects. + * @constructor + * @param {string} name Object name + * @param {Object.} [options] Declared options + * @abstract + */ +function ReflectionObject(name, options) { + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + if (options && !util.isObject(options)) + throw TypeError("options must be an object"); + + /** + * Options. + * @type {Object.|undefined} + */ + this.options = options; // toJSON + + /** + * Parsed Options. + * @type {Array.>|undefined} + */ + this.parsedOptions = null; + + /** + * Unique name within its namespace. + * @type {string} + */ + this.name = name; + + /** + * The edition specified for this object. Only relevant for top-level objects. + * @type {string} + * @private + */ + this._edition = null; + + /** + * The default edition to use for this object if none is specified. For legacy reasons, + * this is proto2 except in the JSON parsing case where it was proto3. + * @type {string} + * @private + */ + this._defaultEdition = "proto2"; + + /** + * Resolved Features. + * @type {object} + * @private + */ + this._features = {}; + + /** + * Whether or not features have been resolved. + * @type {boolean} + * @private + */ + this._featuresResolved = false; + + /** + * Parent namespace. + * @type {Namespace|null} + */ + this.parent = null; + + /** + * Whether already resolved or not. + * @type {boolean} + */ + this.resolved = false; + + /** + * Comment text, if any. + * @type {string|null} + */ + this.comment = null; + + /** + * Defining file name. + * @type {string|null} + */ + this.filename = null; +} + +Object.defineProperties(ReflectionObject.prototype, { + + /** + * Reference to the root namespace. + * @name ReflectionObject#root + * @type {Root} + * @readonly + */ + root: { + get: function() { + var ptr = this; + while (ptr.parent !== null) + ptr = ptr.parent; + return ptr; + } + }, + + /** + * Full name including leading dot. + * @name ReflectionObject#fullName + * @type {string} + * @readonly + */ + fullName: { + get: function() { + var path = [ this.name ], + ptr = this.parent; + while (ptr) { + path.unshift(ptr.name); + ptr = ptr.parent; + } + return path.join("."); + } + } +}); + +/** + * Converts this reflection object to its descriptor representation. + * @returns {Object.} Descriptor + * @abstract + */ +ReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() { + throw Error(); // not implemented, shouldn't happen +}; + +/** + * Called when this object is added to a parent. + * @param {ReflectionObject} parent Parent added to + * @returns {undefined} + */ +ReflectionObject.prototype.onAdd = function onAdd(parent) { + if (this.parent && this.parent !== parent) + this.parent.remove(this); + this.parent = parent; + this.resolved = false; + var root = parent.root; + if (root instanceof Root) + root._handleAdd(this); +}; + +/** + * Called when this object is removed from a parent. + * @param {ReflectionObject} parent Parent removed from + * @returns {undefined} + */ +ReflectionObject.prototype.onRemove = function onRemove(parent) { + var root = parent.root; + if (root instanceof Root) + root._handleRemove(this); + this.parent = null; + this.resolved = false; +}; + +/** + * Resolves this objects type references. + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.resolve = function resolve() { + if (this.resolved) + return this; + if (this.root instanceof Root) + this.resolved = true; // only if part of a root + return this; +}; + +/** + * Resolves this objects editions features. + * @param {string} edition The edition we're currently resolving for. + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { + return this._resolveFeatures(this._edition || edition); +}; + +/** + * Resolves child features from parent features + * @param {string} edition The edition we're currently resolving for. + * @returns {undefined} + */ +ReflectionObject.prototype._resolveFeatures = function _resolveFeatures(edition) { + if (this._featuresResolved) { + return; + } + + var defaults = {}; + + /* istanbul ignore if */ + if (!edition) { + throw new Error("Unknown edition for " + this.fullName); + } + + var protoFeatures = Object.assign(this.options ? Object.assign({}, this.options.features) : {}, + this._inferLegacyProtoFeatures(edition)); + + if (this._edition) { + // For a namespace marked with a specific edition, reset defaults. + /* istanbul ignore else */ + if (edition === "proto2") { + defaults = Object.assign({}, proto2Defaults); + } else if (edition === "proto3") { + defaults = Object.assign({}, proto3Defaults); + } else if (edition === "2023") { + defaults = Object.assign({}, editions2023Defaults); + } else { + throw new Error("Unknown edition: " + edition); + } + this._features = Object.assign(defaults, protoFeatures || {}); + this._featuresResolved = true; + return; + } + + // fields in Oneofs aren't actually children of them, so we have to + // special-case it + /* istanbul ignore else */ + if (this.partOf instanceof OneOf) { + var lexicalParentFeaturesCopy = Object.assign({}, this.partOf._features); + this._features = Object.assign(lexicalParentFeaturesCopy, protoFeatures || {}); + } else if (this.declaringField) { + // Skip feature resolution of sister fields. + } else if (this.parent) { + var parentFeaturesCopy = Object.assign({}, this.parent._features); + this._features = Object.assign(parentFeaturesCopy, protoFeatures || {}); + } else { + throw new Error("Unable to find a parent for " + this.fullName); + } + if (this.extensionField) { + // Sister fields should have the same features as their extensions. + this.extensionField._features = this._features; + } + this._featuresResolved = true; +}; + +/** + * Infers features from legacy syntax that may have been specified differently. + * in older editions. + * @param {string|undefined} edition The edition this proto is on, or undefined if pre-editions + * @returns {object} The feature values to override + */ +ReflectionObject.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(/*edition*/) { + return {}; +}; + +/** + * Gets an option value. + * @param {string} name Option name + * @returns {*} Option value or `undefined` if not set + */ +ReflectionObject.prototype.getOption = function getOption(name) { + if (this.options) + return this.options[name]; + return undefined; +}; + +/** + * Sets an option. + * @param {string} name Option name + * @param {*} value Option value + * @param {boolean|undefined} [ifNotSet] Sets the option only if it isn't currently set + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) { + if (!this.options) + this.options = {}; + if (/^features\./.test(name)) { + util.setProperty(this.options, name, value, ifNotSet); + } else if (!ifNotSet || this.options[name] === undefined) { + if (this.getOption(name) !== value) this.resolved = false; + this.options[name] = value; + } + + return this; +}; + +/** + * Sets a parsed option. + * @param {string} name parsed Option name + * @param {*} value Option value + * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\empty, will add a new option with that value + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) { + if (!this.parsedOptions) { + this.parsedOptions = []; + } + var parsedOptions = this.parsedOptions; + if (propName) { + // If setting a sub property of an option then try to merge it + // with an existing option + var opt = parsedOptions.find(function (opt) { + return Object.prototype.hasOwnProperty.call(opt, name); + }); + if (opt) { + // If we found an existing option - just merge the property value + // (If it's a feature, will just write over) + var newValue = opt[name]; + util.setProperty(newValue, propName, value); + } else { + // otherwise, create a new option, set its property and add it to the list + opt = {}; + opt[name] = util.setProperty({}, propName, value); + parsedOptions.push(opt); + } + } else { + // Always create a new option when setting the value of the option itself + var newOpt = {}; + newOpt[name] = value; + parsedOptions.push(newOpt); + } + + return this; +}; + +/** + * Sets multiple options. + * @param {Object.} options Options to set + * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) { + if (options) + for (var keys = Object.keys(options), i = 0; i < keys.length; ++i) + this.setOption(keys[i], options[keys[i]], ifNotSet); + return this; +}; + +/** + * Converts this instance to its string representation. + * @returns {string} Class name[, space, full name] + */ +ReflectionObject.prototype.toString = function toString() { + var className = this.constructor.className, + fullName = this.fullName; + if (fullName.length) + return className + " " + fullName; + return className; +}; + +/** + * Converts the edition this object is pinned to for JSON format. + * @returns {string|undefined} The edition string for JSON representation + */ +ReflectionObject.prototype._editionToJSON = function _editionToJSON() { + if (!this._edition || this._edition === "proto3") { + // Avoid emitting proto3 since we need to default to it for backwards + // compatibility anyway. + return undefined; + } + return this._edition; +}; + +// Sets up cyclic dependencies (called in index-light) +ReflectionObject._configure = function(Root_) { + Root = Root_; +}; diff --git a/node_modules/protobufjs/src/oneof.js b/node_modules/protobufjs/src/oneof.js new file mode 100644 index 0000000..6da2fe1 --- /dev/null +++ b/node_modules/protobufjs/src/oneof.js @@ -0,0 +1,222 @@ +"use strict"; +module.exports = OneOf; + +// extends ReflectionObject +var ReflectionObject = require("./object"); +((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf"; + +var Field = require("./field"), + util = require("./util"); + +/** + * Constructs a new oneof instance. + * @classdesc Reflected oneof. + * @extends ReflectionObject + * @constructor + * @param {string} name Oneof name + * @param {string[]|Object.} [fieldNames] Field names + * @param {Object.} [options] Declared options + * @param {string} [comment] Comment associated with this field + */ +function OneOf(name, fieldNames, options, comment) { + if (!Array.isArray(fieldNames)) { + options = fieldNames; + fieldNames = undefined; + } + ReflectionObject.call(this, name, options); + + /* istanbul ignore if */ + if (!(fieldNames === undefined || Array.isArray(fieldNames))) + throw TypeError("fieldNames must be an Array"); + + /** + * Field names that belong to this oneof. + * @type {string[]} + */ + this.oneof = fieldNames || []; // toJSON, marker + + /** + * Fields that belong to this oneof as an array for iteration. + * @type {Field[]} + * @readonly + */ + this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent + + /** + * Comment for this field. + * @type {string|null} + */ + this.comment = comment; +} + +/** + * Oneof descriptor. + * @interface IOneOf + * @property {Array.} oneof Oneof field names + * @property {Object.} [options] Oneof options + */ + +/** + * Constructs a oneof from a oneof descriptor. + * @param {string} name Oneof name + * @param {IOneOf} json Oneof descriptor + * @returns {OneOf} Created oneof + * @throws {TypeError} If arguments are invalid + */ +OneOf.fromJSON = function fromJSON(name, json) { + return new OneOf(name, json.oneof, json.options, json.comment); +}; + +/** + * Converts this oneof to a oneof descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IOneOf} Oneof descriptor + */ +OneOf.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "options" , this.options, + "oneof" , this.oneof, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * Adds the fields of the specified oneof to the parent if not already done so. + * @param {OneOf} oneof The oneof + * @returns {undefined} + * @inner + * @ignore + */ +function addFieldsToParent(oneof) { + if (oneof.parent) + for (var i = 0; i < oneof.fieldsArray.length; ++i) + if (!oneof.fieldsArray[i].parent) + oneof.parent.add(oneof.fieldsArray[i]); +} + +/** + * Adds a field to this oneof and removes it from its current parent, if any. + * @param {Field} field Field to add + * @returns {OneOf} `this` + */ +OneOf.prototype.add = function add(field) { + + /* istanbul ignore if */ + if (!(field instanceof Field)) + throw TypeError("field must be a Field"); + + if (field.parent && field.parent !== this.parent) + field.parent.remove(field); + this.oneof.push(field.name); + this.fieldsArray.push(field); + field.partOf = this; // field.parent remains null + addFieldsToParent(this); + return this; +}; + +/** + * Removes a field from this oneof and puts it back to the oneof's parent. + * @param {Field} field Field to remove + * @returns {OneOf} `this` + */ +OneOf.prototype.remove = function remove(field) { + + /* istanbul ignore if */ + if (!(field instanceof Field)) + throw TypeError("field must be a Field"); + + var index = this.fieldsArray.indexOf(field); + + /* istanbul ignore if */ + if (index < 0) + throw Error(field + " is not a member of " + this); + + this.fieldsArray.splice(index, 1); + index = this.oneof.indexOf(field.name); + + /* istanbul ignore else */ + if (index > -1) // theoretical + this.oneof.splice(index, 1); + + field.partOf = null; + return this; +}; + +/** + * @override + */ +OneOf.prototype.onAdd = function onAdd(parent) { + ReflectionObject.prototype.onAdd.call(this, parent); + var self = this; + // Collect present fields + for (var i = 0; i < this.oneof.length; ++i) { + var field = parent.get(this.oneof[i]); + if (field && !field.partOf) { + field.partOf = self; + self.fieldsArray.push(field); + } + } + // Add not yet present fields + addFieldsToParent(this); +}; + +/** + * @override + */ +OneOf.prototype.onRemove = function onRemove(parent) { + for (var i = 0, field; i < this.fieldsArray.length; ++i) + if ((field = this.fieldsArray[i]).parent) + field.parent.remove(field); + ReflectionObject.prototype.onRemove.call(this, parent); +}; + +/** + * Determines whether this field corresponds to a synthetic oneof created for + * a proto3 optional field. No behavioral logic should depend on this, but it + * can be relevant for reflection. + * @name OneOf#isProto3Optional + * @type {boolean} + * @readonly + */ +Object.defineProperty(OneOf.prototype, "isProto3Optional", { + get: function() { + if (this.fieldsArray == null || this.fieldsArray.length !== 1) { + return false; + } + + var field = this.fieldsArray[0]; + return field.options != null && field.options["proto3_optional"] === true; + } +}); + +/** + * Decorator function as returned by {@link OneOf.d} (TypeScript). + * @typedef OneOfDecorator + * @type {function} + * @param {Object} prototype Target prototype + * @param {string} oneofName OneOf name + * @returns {undefined} + */ + +/** + * OneOf decorator (TypeScript). + * @function + * @param {...string} fieldNames Field names + * @returns {OneOfDecorator} Decorator function + * @template T extends string + */ +OneOf.d = function decorateOneOf() { + var fieldNames = new Array(arguments.length), + index = 0; + while (index < arguments.length) + fieldNames[index] = arguments[index++]; + return function oneOfDecorator(prototype, oneofName) { + util.decorateType(prototype.constructor) + .add(new OneOf(oneofName, fieldNames)); + Object.defineProperty(prototype, oneofName, { + get: util.oneOfGetter(fieldNames), + set: util.oneOfSetter(fieldNames) + }); + }; +}; diff --git a/node_modules/protobufjs/src/parse.js b/node_modules/protobufjs/src/parse.js new file mode 100644 index 0000000..9c3cc27 --- /dev/null +++ b/node_modules/protobufjs/src/parse.js @@ -0,0 +1,969 @@ +"use strict"; +module.exports = parse; + +parse.filename = null; +parse.defaults = { keepCase: false }; + +var tokenize = require("./tokenize"), + Root = require("./root"), + Type = require("./type"), + Field = require("./field"), + MapField = require("./mapfield"), + OneOf = require("./oneof"), + Enum = require("./enum"), + Service = require("./service"), + Method = require("./method"), + ReflectionObject = require("./object"), + types = require("./types"), + util = require("./util"); + +var base10Re = /^[1-9][0-9]*$/, + base10NegRe = /^-?[1-9][0-9]*$/, + base16Re = /^0[x][0-9a-fA-F]+$/, + base16NegRe = /^-?0[x][0-9a-fA-F]+$/, + base8Re = /^0[0-7]+$/, + base8NegRe = /^-?0[0-7]+$/, + numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/, + nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/, + typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/; + +/** + * Result object returned from {@link parse}. + * @interface IParserResult + * @property {string|undefined} package Package name, if declared + * @property {string[]|undefined} imports Imports, if any + * @property {string[]|undefined} weakImports Weak imports, if any + * @property {Root} root Populated root instance + */ + +/** + * Options modifying the behavior of {@link parse}. + * @interface IParseOptions + * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case + * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments. + * @property {boolean} [preferTrailingComment=false] Use trailing comment when both leading comment and trailing comment exist. + */ + +/** + * Options modifying the behavior of JSON serialization. + * @interface IToJSONOptions + * @property {boolean} [keepComments=false] Serializes comments. + */ + +/** + * Parses the given .proto source and returns an object with the parsed contents. + * @param {string} source Source contents + * @param {Root} root Root to populate + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {IParserResult} Parser result + * @property {string} filename=null Currently processing file name for error reporting, if known + * @property {IParseOptions} defaults Default {@link IParseOptions} + */ +function parse(source, root, options) { + /* eslint-disable callback-return */ + if (!(root instanceof Root)) { + options = root; + root = new Root(); + } + if (!options) + options = parse.defaults; + + var preferTrailingComment = options.preferTrailingComment || false; + var tn = tokenize(source, options.alternateCommentMode || false), + next = tn.next, + push = tn.push, + peek = tn.peek, + skip = tn.skip, + cmnt = tn.cmnt; + + var head = true, + pkg, + imports, + weakImports, + edition = "proto2"; + + var ptr = root; + + var topLevelObjects = []; + var topLevelOptions = {}; + + var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase; + + function resolveFileFeatures() { + topLevelObjects.forEach(obj => { + obj._edition = edition; + Object.keys(topLevelOptions).forEach(opt => { + if (obj.getOption(opt) !== undefined) return; + obj.setOption(opt, topLevelOptions[opt], true); + }); + }); + } + + /* istanbul ignore next */ + function illegal(token, name, insideTryCatch) { + var filename = parse.filename; + if (!insideTryCatch) + parse.filename = null; + return Error("illegal " + (name || "token") + " '" + token + "' (" + (filename ? filename + ", " : "") + "line " + tn.line + ")"); + } + + function readString() { + var values = [], + token; + do { + /* istanbul ignore if */ + if ((token = next()) !== "\"" && token !== "'") + throw illegal(token); + + values.push(next()); + skip(token); + token = peek(); + } while (token === "\"" || token === "'"); + return values.join(""); + } + + function readValue(acceptTypeRef) { + var token = next(); + switch (token) { + case "'": + case "\"": + push(token); + return readString(); + case "true": case "TRUE": + return true; + case "false": case "FALSE": + return false; + } + try { + return parseNumber(token, /* insideTryCatch */ true); + } catch (e) { + /* istanbul ignore else */ + if (acceptTypeRef && typeRefRe.test(token)) + return token; + + /* istanbul ignore next */ + throw illegal(token, "value"); + } + } + + function readRanges(target, acceptStrings) { + var token, start; + do { + if (acceptStrings && ((token = peek()) === "\"" || token === "'")) { + var str = readString(); + target.push(str); + if (edition >= 2023) { + throw illegal(str, "id"); + } + } else { + try { + target.push([ start = parseId(next()), skip("to", true) ? parseId(next()) : start ]); + } catch (err) { + if (acceptStrings && typeRefRe.test(token) && edition >= 2023) { + target.push(token); + } else { + throw err; + } + } + } + } while (skip(",", true)); + var dummy = {options: undefined}; + dummy.setOption = function(name, value) { + if (this.options === undefined) this.options = {}; + this.options[name] = value; + }; + ifBlock( + dummy, + function parseRange_block(token) { + /* istanbul ignore else */ + if (token === "option") { + parseOption(dummy, token); // skip + skip(";"); + } else + throw illegal(token); + }, + function parseRange_line() { + parseInlineOptions(dummy); // skip + }); + } + + function parseNumber(token, insideTryCatch) { + var sign = 1; + if (token.charAt(0) === "-") { + sign = -1; + token = token.substring(1); + } + switch (token) { + case "inf": case "INF": case "Inf": + return sign * Infinity; + case "nan": case "NAN": case "Nan": case "NaN": + return NaN; + case "0": + return 0; + } + if (base10Re.test(token)) + return sign * parseInt(token, 10); + if (base16Re.test(token)) + return sign * parseInt(token, 16); + if (base8Re.test(token)) + return sign * parseInt(token, 8); + + /* istanbul ignore else */ + if (numberRe.test(token)) + return sign * parseFloat(token); + + /* istanbul ignore next */ + throw illegal(token, "number", insideTryCatch); + } + + function parseId(token, acceptNegative) { + switch (token) { + case "max": case "MAX": case "Max": + return 536870911; + case "0": + return 0; + } + + /* istanbul ignore if */ + if (!acceptNegative && token.charAt(0) === "-") + throw illegal(token, "id"); + + if (base10NegRe.test(token)) + return parseInt(token, 10); + if (base16NegRe.test(token)) + return parseInt(token, 16); + + /* istanbul ignore else */ + if (base8NegRe.test(token)) + return parseInt(token, 8); + + /* istanbul ignore next */ + throw illegal(token, "id"); + } + + function parsePackage() { + /* istanbul ignore if */ + if (pkg !== undefined) + throw illegal("package"); + + pkg = next(); + + /* istanbul ignore if */ + if (!typeRefRe.test(pkg)) + throw illegal(pkg, "name"); + + ptr = ptr.define(pkg); + + skip(";"); + } + + function parseImport() { + var token = peek(); + var whichImports; + switch (token) { + case "weak": + whichImports = weakImports || (weakImports = []); + next(); + break; + case "public": + next(); + // eslint-disable-next-line no-fallthrough + default: + whichImports = imports || (imports = []); + break; + } + token = readString(); + skip(";"); + whichImports.push(token); + } + + function parseSyntax() { + skip("="); + edition = readString(); + + /* istanbul ignore if */ + if (edition < 2023) + throw illegal(edition, "syntax"); + + skip(";"); + } + + function parseEdition() { + skip("="); + edition = readString(); + const supportedEditions = ["2023"]; + + /* istanbul ignore if */ + if (!supportedEditions.includes(edition)) + throw illegal(edition, "edition"); + + skip(";"); + } + + + function parseCommon(parent, token) { + switch (token) { + + case "option": + parseOption(parent, token); + skip(";"); + return true; + + case "message": + parseType(parent, token); + return true; + + case "enum": + parseEnum(parent, token); + return true; + + case "service": + parseService(parent, token); + return true; + + case "extend": + parseExtension(parent, token); + return true; + } + return false; + } + + function ifBlock(obj, fnIf, fnElse) { + var trailingLine = tn.line; + if (obj) { + if(typeof obj.comment !== "string") { + obj.comment = cmnt(); // try block-type comment + } + obj.filename = parse.filename; + } + if (skip("{", true)) { + var token; + while ((token = next()) !== "}") + fnIf(token); + skip(";", true); + } else { + if (fnElse) + fnElse(); + skip(";"); + if (obj && (typeof obj.comment !== "string" || preferTrailingComment)) + obj.comment = cmnt(trailingLine) || obj.comment; // try line-type comment + } + } + + function parseType(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "type name"); + + var type = new Type(token); + ifBlock(type, function parseType_block(token) { + if (parseCommon(type, token)) + return; + + switch (token) { + + case "map": + parseMapField(type, token); + break; + + case "required": + if (edition !== "proto2") + throw illegal(token); + /* eslint-disable no-fallthrough */ + case "repeated": + parseField(type, token); + break; + + case "optional": + /* istanbul ignore if */ + if (edition === "proto3") { + parseField(type, "proto3_optional"); + } else if (edition !== "proto2") { + throw illegal(token); + } else { + parseField(type, "optional"); + } + break; + + case "oneof": + parseOneOf(type, token); + break; + + case "extensions": + readRanges(type.extensions || (type.extensions = [])); + break; + + case "reserved": + readRanges(type.reserved || (type.reserved = []), true); + break; + + default: + /* istanbul ignore if */ + if (edition === "proto2" || !typeRefRe.test(token)) { + throw illegal(token); + } + + push(token); + parseField(type, "optional"); + break; + } + }); + parent.add(type); + if (parent === ptr) { + topLevelObjects.push(type); + } + } + + function parseField(parent, rule, extend) { + var type = next(); + if (type === "group") { + parseGroup(parent, rule); + return; + } + // Type names can consume multiple tokens, in multiple variants: + // package.subpackage field tokens: "package.subpackage" [TYPE NAME ENDS HERE] "field" + // package . subpackage field tokens: "package" "." "subpackage" [TYPE NAME ENDS HERE] "field" + // package. subpackage field tokens: "package." "subpackage" [TYPE NAME ENDS HERE] "field" + // package .subpackage field tokens: "package" ".subpackage" [TYPE NAME ENDS HERE] "field" + // Keep reading tokens until we get a type name with no period at the end, + // and the next token does not start with a period. + while (type.endsWith(".") || peek().startsWith(".")) { + type += next(); + } + + /* istanbul ignore if */ + if (!typeRefRe.test(type)) + throw illegal(type, "type"); + + var name = next(); + + /* istanbul ignore if */ + + if (!nameRe.test(name)) + throw illegal(name, "name"); + + name = applyCase(name); + skip("="); + + var field = new Field(name, parseId(next()), type, rule, extend); + + ifBlock(field, function parseField_block(token) { + + /* istanbul ignore else */ + if (token === "option") { + parseOption(field, token); + skip(";"); + } else + throw illegal(token); + + }, function parseField_line() { + parseInlineOptions(field); + }); + + if (rule === "proto3_optional") { + // for proto3 optional fields, we create a single-member Oneof to mimic "optional" behavior + var oneof = new OneOf("_" + name); + field.setOption("proto3_optional", true); + oneof.add(field); + parent.add(oneof); + } else { + parent.add(field); + } + if (parent === ptr) { + topLevelObjects.push(field); + } + } + + function parseGroup(parent, rule) { + if (edition >= 2023) { + throw illegal("group"); + } + var name = next(); + + /* istanbul ignore if */ + if (!nameRe.test(name)) + throw illegal(name, "name"); + + var fieldName = util.lcFirst(name); + if (name === fieldName) + name = util.ucFirst(name); + skip("="); + var id = parseId(next()); + var type = new Type(name); + type.group = true; + var field = new Field(fieldName, id, name, rule); + field.filename = parse.filename; + ifBlock(type, function parseGroup_block(token) { + switch (token) { + + case "option": + parseOption(type, token); + skip(";"); + break; + case "required": + case "repeated": + parseField(type, token); + break; + + case "optional": + /* istanbul ignore if */ + if (edition === "proto3") { + parseField(type, "proto3_optional"); + } else { + parseField(type, "optional"); + } + break; + + case "message": + parseType(type, token); + break; + + case "enum": + parseEnum(type, token); + break; + + case "reserved": + readRanges(type.reserved || (type.reserved = []), true); + break; + + /* istanbul ignore next */ + default: + throw illegal(token); // there are no groups with proto3 semantics + } + }); + parent.add(type) + .add(field); + } + + function parseMapField(parent) { + skip("<"); + var keyType = next(); + + /* istanbul ignore if */ + if (types.mapKey[keyType] === undefined) + throw illegal(keyType, "type"); + + skip(","); + var valueType = next(); + + /* istanbul ignore if */ + if (!typeRefRe.test(valueType)) + throw illegal(valueType, "type"); + + skip(">"); + var name = next(); + + /* istanbul ignore if */ + if (!nameRe.test(name)) + throw illegal(name, "name"); + + skip("="); + var field = new MapField(applyCase(name), parseId(next()), keyType, valueType); + ifBlock(field, function parseMapField_block(token) { + + /* istanbul ignore else */ + if (token === "option") { + parseOption(field, token); + skip(";"); + } else + throw illegal(token); + + }, function parseMapField_line() { + parseInlineOptions(field); + }); + parent.add(field); + } + + function parseOneOf(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "name"); + + var oneof = new OneOf(applyCase(token)); + ifBlock(oneof, function parseOneOf_block(token) { + if (token === "option") { + parseOption(oneof, token); + skip(";"); + } else { + push(token); + parseField(oneof, "optional"); + } + }); + parent.add(oneof); + } + + function parseEnum(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "name"); + + var enm = new Enum(token); + ifBlock(enm, function parseEnum_block(token) { + switch(token) { + case "option": + parseOption(enm, token); + skip(";"); + break; + + case "reserved": + readRanges(enm.reserved || (enm.reserved = []), true); + if(enm.reserved === undefined) enm.reserved = []; + break; + + default: + parseEnumValue(enm, token); + } + }); + parent.add(enm); + if (parent === ptr) { + topLevelObjects.push(enm); + } + } + + function parseEnumValue(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token)) + throw illegal(token, "name"); + + skip("="); + var value = parseId(next(), true), + dummy = { + options: undefined + }; + dummy.getOption = function(name) { + return this.options[name]; + }; + dummy.setOption = function(name, value) { + ReflectionObject.prototype.setOption.call(dummy, name, value); + }; + dummy.setParsedOption = function() { + return undefined; + }; + ifBlock(dummy, function parseEnumValue_block(token) { + + /* istanbul ignore else */ + if (token === "option") { + parseOption(dummy, token); // skip + skip(";"); + } else + throw illegal(token); + + }, function parseEnumValue_line() { + parseInlineOptions(dummy); // skip + }); + parent.add(token, value, dummy.comment, dummy.parsedOptions || dummy.options); + } + + function parseOption(parent, token) { + var option; + var propName; + var isOption = true; + if (token === "option") { + token = next(); + } + + while (token !== "=") { + if (token === "(") { + var parensValue = next(); + skip(")"); + token = "(" + parensValue + ")"; + } + if (isOption) { + isOption = false; + if (token.includes(".") && !token.includes("(")) { + var tokens = token.split("."); + option = tokens[0] + "."; + token = tokens[1]; + continue; + } + option = token; + } else { + propName = propName ? propName += token : token; + } + token = next(); + } + var name = propName ? option.concat(propName) : option; + var optionValue = parseOptionValue(parent, name); + propName = propName && propName[0] === "." ? propName.slice(1) : propName; + option = option && option[option.length - 1] === "." ? option.slice(0, -1) : option; + setParsedOption(parent, option, optionValue, propName); + } + + function parseOptionValue(parent, name) { + // { a: "foo" b { c: "bar" } } + if (skip("{", true)) { + var objectResult = {}; + + while (!skip("}", true)) { + /* istanbul ignore if */ + if (!nameRe.test(token = next())) { + throw illegal(token, "name"); + } + if (token === null) { + throw illegal(token, "end of input"); + } + + var value; + var propName = token; + + skip(":", true); + + if (peek() === "{") { + // option (my_option) = { + // repeated_value: [ "foo", "bar" ] + // }; + value = parseOptionValue(parent, name + "." + token); + } else if (peek() === "[") { + value = []; + var lastValue; + if (skip("[", true)) { + do { + lastValue = readValue(true); + value.push(lastValue); + } while (skip(",", true)); + skip("]"); + if (typeof lastValue !== "undefined") { + setOption(parent, name + "." + token, lastValue); + } + } + } else { + value = readValue(true); + setOption(parent, name + "." + token, value); + } + + var prevValue = objectResult[propName]; + + if (prevValue) + value = [].concat(prevValue).concat(value); + + objectResult[propName] = value; + + // Semicolons and commas can be optional + skip(",", true); + skip(";", true); + } + + return objectResult; + } + + var simpleValue = readValue(true); + setOption(parent, name, simpleValue); + return simpleValue; + // Does not enforce a delimiter to be universal + } + + function setOption(parent, name, value) { + if (ptr === parent && /^features\./.test(name)) { + topLevelOptions[name] = value; + return; + } + if (parent.setOption) + parent.setOption(name, value); + } + + function setParsedOption(parent, name, value, propName) { + if (parent.setParsedOption) + parent.setParsedOption(name, value, propName); + } + + function parseInlineOptions(parent) { + if (skip("[", true)) { + do { + parseOption(parent, "option"); + } while (skip(",", true)); + skip("]"); + } + return parent; + } + + function parseService(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "service name"); + + var service = new Service(token); + ifBlock(service, function parseService_block(token) { + if (parseCommon(service, token)) { + return; + } + + /* istanbul ignore else */ + if (token === "rpc") + parseMethod(service, token); + else + throw illegal(token); + }); + parent.add(service); + if (parent === ptr) { + topLevelObjects.push(service); + } + } + + function parseMethod(parent, token) { + // Get the comment of the preceding line now (if one exists) in case the + // method is defined across multiple lines. + var commentText = cmnt(); + + var type = token; + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "name"); + + var name = token, + requestType, requestStream, + responseType, responseStream; + + skip("("); + if (skip("stream", true)) + requestStream = true; + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) + throw illegal(token); + + requestType = token; + skip(")"); skip("returns"); skip("("); + if (skip("stream", true)) + responseStream = true; + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) + throw illegal(token); + + responseType = token; + skip(")"); + + var method = new Method(name, type, requestType, responseType, requestStream, responseStream); + method.comment = commentText; + ifBlock(method, function parseMethod_block(token) { + + /* istanbul ignore else */ + if (token === "option") { + parseOption(method, token); + skip(";"); + } else + throw illegal(token); + + }); + parent.add(method); + } + + function parseExtension(parent, token) { + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) + throw illegal(token, "reference"); + + var reference = token; + ifBlock(null, function parseExtension_block(token) { + switch (token) { + + case "required": + case "repeated": + parseField(parent, token, reference); + break; + + case "optional": + /* istanbul ignore if */ + if (edition === "proto3") { + parseField(parent, "proto3_optional", reference); + } else { + parseField(parent, "optional", reference); + } + break; + + default: + /* istanbul ignore if */ + if (edition === "proto2" || !typeRefRe.test(token)) + throw illegal(token); + push(token); + parseField(parent, "optional", reference); + break; + } + }); + } + + var token; + while ((token = next()) !== null) { + switch (token) { + + case "package": + + /* istanbul ignore if */ + if (!head) + throw illegal(token); + + parsePackage(); + break; + + case "import": + + /* istanbul ignore if */ + if (!head) + throw illegal(token); + + parseImport(); + break; + + case "syntax": + + /* istanbul ignore if */ + if (!head) + throw illegal(token); + + parseSyntax(); + break; + + case "edition": + /* istanbul ignore if */ + if (!head) + throw illegal(token); + parseEdition(); + break; + + case "option": + parseOption(ptr, token); + skip(";", true); + break; + + default: + + /* istanbul ignore else */ + if (parseCommon(ptr, token)) { + head = false; + continue; + } + + /* istanbul ignore next */ + throw illegal(token); + } + } + + resolveFileFeatures(); + + parse.filename = null; + return { + "package" : pkg, + "imports" : imports, + weakImports : weakImports, + root : root + }; +} + +/** + * Parses the given .proto source and returns an object with the parsed contents. + * @name parse + * @function + * @param {string} source Source contents + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {IParserResult} Parser result + * @property {string} filename=null Currently processing file name for error reporting, if known + * @property {IParseOptions} defaults Default {@link IParseOptions} + * @variation 2 + */ diff --git a/node_modules/protobufjs/src/reader.js b/node_modules/protobufjs/src/reader.js new file mode 100644 index 0000000..b4fbf29 --- /dev/null +++ b/node_modules/protobufjs/src/reader.js @@ -0,0 +1,416 @@ +"use strict"; +module.exports = Reader; + +var util = require("./util/minimal"); + +var BufferReader; // cyclic + +var LongBits = util.LongBits, + utf8 = util.utf8; + +/* istanbul ignore next */ +function indexOutOfRange(reader, writeLength) { + return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); +} + +/** + * Constructs a new reader instance using the specified buffer. + * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`. + * @constructor + * @param {Uint8Array} buffer Buffer to read from + */ +function Reader(buffer) { + + /** + * Read buffer. + * @type {Uint8Array} + */ + this.buf = buffer; + + /** + * Read buffer position. + * @type {number} + */ + this.pos = 0; + + /** + * Read buffer length. + * @type {number} + */ + this.len = buffer.length; +} + +var create_array = typeof Uint8Array !== "undefined" + ? function create_typed_array(buffer) { + if (buffer instanceof Uint8Array || Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + } + /* istanbul ignore next */ + : function create_array(buffer) { + if (Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + }; + +var create = function create() { + return util.Buffer + ? function create_buffer_setup(buffer) { + return (Reader.create = function create_buffer(buffer) { + return util.Buffer.isBuffer(buffer) + ? new BufferReader(buffer) + /* istanbul ignore next */ + : create_array(buffer); + })(buffer); + } + /* istanbul ignore next */ + : create_array; +}; + +/** + * Creates a new reader using the specified buffer. + * @function + * @param {Uint8Array|Buffer} buffer Buffer to read from + * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader} + * @throws {Error} If `buffer` is not a valid buffer + */ +Reader.create = create(); + +Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice; + +/** + * Reads a varint as an unsigned 32 bit value. + * @function + * @returns {number} Value read + */ +Reader.prototype.uint32 = (function read_uint32_setup() { + var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!) + return function read_uint32() { + value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value; + + /* istanbul ignore if */ + if ((this.pos += 5) > this.len) { + this.pos = this.len; + throw indexOutOfRange(this, 10); + } + return value; + }; +})(); + +/** + * Reads a varint as a signed 32 bit value. + * @returns {number} Value read + */ +Reader.prototype.int32 = function read_int32() { + return this.uint32() | 0; +}; + +/** + * Reads a zig-zag encoded varint as a signed 32 bit value. + * @returns {number} Value read + */ +Reader.prototype.sint32 = function read_sint32() { + var value = this.uint32(); + return value >>> 1 ^ -(value & 1) | 0; +}; + +/* eslint-disable no-invalid-this */ + +function readLongVarint() { + // tends to deopt with local vars for octet etc. + var bits = new LongBits(0, 0); + var i = 0; + if (this.len - this.pos > 4) { // fast route (lo) + for (; i < 4; ++i) { + // 1st..4th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + // 5th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; + bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + i = 0; + } else { + for (; i < 3; ++i) { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + // 1st..3th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + // 4th + bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0; + return bits; + } + if (this.len - this.pos > 4) { // fast route (hi) + for (; i < 5; ++i) { + // 6th..10th + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } else { + for (; i < 5; ++i) { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + // 6th..10th + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } + /* istanbul ignore next */ + throw Error("invalid varint encoding"); +} + +/* eslint-enable no-invalid-this */ + +/** + * Reads a varint as a signed 64 bit value. + * @name Reader#int64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a varint as an unsigned 64 bit value. + * @name Reader#uint64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a zig-zag encoded varint as a signed 64 bit value. + * @name Reader#sint64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a varint as a boolean. + * @returns {boolean} Value read + */ +Reader.prototype.bool = function read_bool() { + return this.uint32() !== 0; +}; + +function readFixed32_end(buf, end) { // note that this uses `end`, not `pos` + return (buf[end - 4] + | buf[end - 3] << 8 + | buf[end - 2] << 16 + | buf[end - 1] << 24) >>> 0; +} + +/** + * Reads fixed 32 bits as an unsigned 32 bit integer. + * @returns {number} Value read + */ +Reader.prototype.fixed32 = function read_fixed32() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + return readFixed32_end(this.buf, this.pos += 4); +}; + +/** + * Reads fixed 32 bits as a signed 32 bit integer. + * @returns {number} Value read + */ +Reader.prototype.sfixed32 = function read_sfixed32() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + return readFixed32_end(this.buf, this.pos += 4) | 0; +}; + +/* eslint-disable no-invalid-this */ + +function readFixed64(/* this: Reader */) { + + /* istanbul ignore if */ + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 8); + + return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); +} + +/* eslint-enable no-invalid-this */ + +/** + * Reads fixed 64 bits. + * @name Reader#fixed64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads zig-zag encoded fixed 64 bits. + * @name Reader#sfixed64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a float (32 bit) as a number. + * @function + * @returns {number} Value read + */ +Reader.prototype.float = function read_float() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + var value = util.float.readFloatLE(this.buf, this.pos); + this.pos += 4; + return value; +}; + +/** + * Reads a double (64 bit float) as a number. + * @function + * @returns {number} Value read + */ +Reader.prototype.double = function read_double() { + + /* istanbul ignore if */ + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 4); + + var value = util.float.readDoubleLE(this.buf, this.pos); + this.pos += 8; + return value; +}; + +/** + * Reads a sequence of bytes preceeded by its length as a varint. + * @returns {Uint8Array} Value read + */ +Reader.prototype.bytes = function read_bytes() { + var length = this.uint32(), + start = this.pos, + end = this.pos + length; + + /* istanbul ignore if */ + if (end > this.len) + throw indexOutOfRange(this, length); + + this.pos += length; + if (Array.isArray(this.buf)) // plain array + return this.buf.slice(start, end); + + if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1 + var nativeBuffer = util.Buffer; + return nativeBuffer + ? nativeBuffer.alloc(0) + : new this.buf.constructor(0); + } + return this._slice.call(this.buf, start, end); +}; + +/** + * Reads a string preceeded by its byte length as a varint. + * @returns {string} Value read + */ +Reader.prototype.string = function read_string() { + var bytes = this.bytes(); + return utf8.read(bytes, 0, bytes.length); +}; + +/** + * Skips the specified number of bytes if specified, otherwise skips a varint. + * @param {number} [length] Length if known, otherwise a varint is assumed + * @returns {Reader} `this` + */ +Reader.prototype.skip = function skip(length) { + if (typeof length === "number") { + /* istanbul ignore if */ + if (this.pos + length > this.len) + throw indexOutOfRange(this, length); + this.pos += length; + } else { + do { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + } while (this.buf[this.pos++] & 128); + } + return this; +}; + +/** + * Skips the next element of the specified wire type. + * @param {number} wireType Wire type received + * @returns {Reader} `this` + */ +Reader.prototype.skipType = function(wireType) { + switch (wireType) { + case 0: + this.skip(); + break; + case 1: + this.skip(8); + break; + case 2: + this.skip(this.uint32()); + break; + case 3: + while ((wireType = this.uint32() & 7) !== 4) { + this.skipType(wireType); + } + break; + case 5: + this.skip(4); + break; + + /* istanbul ignore next */ + default: + throw Error("invalid wire type " + wireType + " at offset " + this.pos); + } + return this; +}; + +Reader._configure = function(BufferReader_) { + BufferReader = BufferReader_; + Reader.create = create(); + BufferReader._configure(); + + var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber"; + util.merge(Reader.prototype, { + + int64: function read_int64() { + return readLongVarint.call(this)[fn](false); + }, + + uint64: function read_uint64() { + return readLongVarint.call(this)[fn](true); + }, + + sint64: function read_sint64() { + return readLongVarint.call(this).zzDecode()[fn](false); + }, + + fixed64: function read_fixed64() { + return readFixed64.call(this)[fn](true); + }, + + sfixed64: function read_sfixed64() { + return readFixed64.call(this)[fn](false); + } + + }); +}; diff --git a/node_modules/protobufjs/src/reader_buffer.js b/node_modules/protobufjs/src/reader_buffer.js new file mode 100644 index 0000000..e547424 --- /dev/null +++ b/node_modules/protobufjs/src/reader_buffer.js @@ -0,0 +1,51 @@ +"use strict"; +module.exports = BufferReader; + +// extends Reader +var Reader = require("./reader"); +(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; + +var util = require("./util/minimal"); + +/** + * Constructs a new buffer reader instance. + * @classdesc Wire format reader using node buffers. + * @extends Reader + * @constructor + * @param {Buffer} buffer Buffer to read from + */ +function BufferReader(buffer) { + Reader.call(this, buffer); + + /** + * Read buffer. + * @name BufferReader#buf + * @type {Buffer} + */ +} + +BufferReader._configure = function () { + /* istanbul ignore else */ + if (util.Buffer) + BufferReader.prototype._slice = util.Buffer.prototype.slice; +}; + + +/** + * @override + */ +BufferReader.prototype.string = function read_string_buffer() { + var len = this.uint32(); // modifies pos + return this.buf.utf8Slice + ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) + : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len)); +}; + +/** + * Reads a sequence of bytes preceeded by its length as a varint. + * @name BufferReader#bytes + * @function + * @returns {Buffer} Value read + */ + +BufferReader._configure(); diff --git a/node_modules/protobufjs/src/root.js b/node_modules/protobufjs/src/root.js new file mode 100644 index 0000000..7e2ca6a --- /dev/null +++ b/node_modules/protobufjs/src/root.js @@ -0,0 +1,404 @@ +"use strict"; +module.exports = Root; + +// extends Namespace +var Namespace = require("./namespace"); +((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root"; + +var Field = require("./field"), + Enum = require("./enum"), + OneOf = require("./oneof"), + util = require("./util"); + +var Type, // cyclic + parse, // might be excluded + common; // " + +/** + * Constructs a new root namespace instance. + * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together. + * @extends NamespaceBase + * @constructor + * @param {Object.} [options] Top level options + */ +function Root(options) { + Namespace.call(this, "", options); + + /** + * Deferred extension fields. + * @type {Field[]} + */ + this.deferred = []; + + /** + * Resolved file names of loaded files. + * @type {string[]} + */ + this.files = []; + + /** + * Edition, defaults to proto2 if unspecified. + * @type {string} + * @private + */ + this._edition = "proto2"; + + /** + * Global lookup cache of fully qualified names. + * @type {Object.} + * @private + */ + this._fullyQualifiedObjects = {}; +} + +/** + * Loads a namespace descriptor into a root namespace. + * @param {INamespace} json Namespace descriptor + * @param {Root} [root] Root namespace, defaults to create a new one if omitted + * @returns {Root} Root namespace + */ +Root.fromJSON = function fromJSON(json, root) { + if (!root) + root = new Root(); + if (json.options) + root.setOptions(json.options); + return root.addJSON(json.nested).resolveAll(); +}; + +/** + * Resolves the path of an imported file, relative to the importing origin. + * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories. + * @function + * @param {string} origin The file name of the importing file + * @param {string} target The file name being imported + * @returns {string|null} Resolved path to `target` or `null` to skip the file + */ +Root.prototype.resolvePath = util.path.resolve; + +/** + * Fetch content from file path or url + * This method exists so you can override it with your own logic. + * @function + * @param {string} path File path or url + * @param {FetchCallback} callback Callback function + * @returns {undefined} + */ +Root.prototype.fetch = util.fetch; + +// A symbol-like function to safely signal synchronous loading +/* istanbul ignore next */ +function SYNC() {} // eslint-disable-line no-empty-function + +/** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} options Parse options + * @param {LoadCallback} callback Callback function + * @returns {undefined} + */ +Root.prototype.load = function load(filename, options, callback) { + if (typeof options === "function") { + callback = options; + options = undefined; + } + var self = this; + if (!callback) { + return util.asPromise(load, self, filename, options); + } + + var sync = callback === SYNC; // undocumented + + // Finishes loading by calling the callback (exactly once) + function finish(err, root) { + /* istanbul ignore if */ + if (!callback) { + return; + } + if (sync) { + throw err; + } + if (root) { + root.resolveAll(); + } + var cb = callback; + callback = null; + cb(err, root); + } + + // Bundled definition existence checking + function getBundledFileName(filename) { + var idx = filename.lastIndexOf("google/protobuf/"); + if (idx > -1) { + var altname = filename.substring(idx); + if (altname in common) return altname; + } + return null; + } + + // Processes a single file + function process(filename, source) { + try { + if (util.isString(source) && source.charAt(0) === "{") + source = JSON.parse(source); + if (!util.isString(source)) + self.setOptions(source.options).addJSON(source.nested); + else { + parse.filename = filename; + var parsed = parse(source, self, options), + resolved, + i = 0; + if (parsed.imports) + for (; i < parsed.imports.length; ++i) + if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i])) + fetch(resolved); + if (parsed.weakImports) + for (i = 0; i < parsed.weakImports.length; ++i) + if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i])) + fetch(resolved, true); + } + } catch (err) { + finish(err); + } + if (!sync && !queued) { + finish(null, self); // only once anyway + } + } + + // Fetches a single file + function fetch(filename, weak) { + filename = getBundledFileName(filename) || filename; + + // Skip if already loaded / attempted + if (self.files.indexOf(filename) > -1) { + return; + } + self.files.push(filename); + + // Shortcut bundled definitions + if (filename in common) { + if (sync) { + process(filename, common[filename]); + } else { + ++queued; + setTimeout(function() { + --queued; + process(filename, common[filename]); + }); + } + return; + } + + // Otherwise fetch from disk or network + if (sync) { + var source; + try { + source = util.fs.readFileSync(filename).toString("utf8"); + } catch (err) { + if (!weak) + finish(err); + return; + } + process(filename, source); + } else { + ++queued; + self.fetch(filename, function(err, source) { + --queued; + /* istanbul ignore if */ + if (!callback) { + return; // terminated meanwhile + } + if (err) { + /* istanbul ignore else */ + if (!weak) + finish(err); + else if (!queued) // can't be covered reliably + finish(null, self); + return; + } + process(filename, source); + }); + } + } + var queued = 0; + + // Assembling the root namespace doesn't require working type + // references anymore, so we can load everything in parallel + if (util.isString(filename)) { + filename = [ filename ]; + } + for (var i = 0, resolved; i < filename.length; ++i) + if (resolved = self.resolvePath("", filename[i])) + fetch(resolved); + if (sync) { + self.resolveAll(); + return self; + } + if (!queued) { + finish(null, self); + } + + return self; +}; +// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined + +/** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. + * @function Root#load + * @param {string|string[]} filename Names of one or multiple files to load + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @variation 2 + */ +// function load(filename:string, callback:LoadCallback):undefined + +/** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise. + * @function Root#load + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {Promise} Promise + * @variation 3 + */ +// function load(filename:string, [options:IParseOptions]):Promise + +/** + * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only). + * @function Root#loadSync + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {Root} Root namespace + * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid + */ +Root.prototype.loadSync = function loadSync(filename, options) { + if (!util.isNode) + throw Error("not supported"); + return this.load(filename, options, SYNC); +}; + +/** + * @override + */ +Root.prototype.resolveAll = function resolveAll() { + if (!this._needsRecursiveResolve) return this; + + if (this.deferred.length) + throw Error("unresolvable extensions: " + this.deferred.map(function(field) { + return "'extend " + field.extend + "' in " + field.parent.fullName; + }).join(", ")); + return Namespace.prototype.resolveAll.call(this); +}; + +// only uppercased (and thus conflict-free) children are exposed, see below +var exposeRe = /^[A-Z]/; + +/** + * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type. + * @param {Root} root Root instance + * @param {Field} field Declaring extension field witin the declaring type + * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise + * @inner + * @ignore + */ +function tryHandleExtension(root, field) { + var extendedType = field.parent.lookup(field.extend); + if (extendedType) { + var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options); + //do not allow to extend same field twice to prevent the error + if (extendedType.get(sisterField.name)) { + return true; + } + sisterField.declaringField = field; + field.extensionField = sisterField; + extendedType.add(sisterField); + return true; + } + return false; +} + +/** + * Called when any object is added to this root or its sub-namespaces. + * @param {ReflectionObject} object Object added + * @returns {undefined} + * @private + */ +Root.prototype._handleAdd = function _handleAdd(object) { + if (object instanceof Field) { + + if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField) + if (!tryHandleExtension(this, object)) + this.deferred.push(object); + + } else if (object instanceof Enum) { + + if (exposeRe.test(object.name)) + object.parent[object.name] = object.values; // expose enum values as property of its parent + + } else if (!(object instanceof OneOf)) /* everything else is a namespace */ { + + if (object instanceof Type) // Try to handle any deferred extensions + for (var i = 0; i < this.deferred.length;) + if (tryHandleExtension(this, this.deferred[i])) + this.deferred.splice(i, 1); + else + ++i; + for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace + this._handleAdd(object._nestedArray[j]); + if (exposeRe.test(object.name)) + object.parent[object.name] = object; // expose namespace as property of its parent + } + + if (object instanceof Type || object instanceof Enum || object instanceof Field) { + // Only store types and enums for quick lookup during resolve. + this._fullyQualifiedObjects[object.fullName] = object; + } + + // The above also adds uppercased (and thus conflict-free) nested types, services and enums as + // properties of namespaces just like static code does. This allows using a .d.ts generated for + // a static module with reflection-based solutions where the condition is met. +}; + +/** + * Called when any object is removed from this root or its sub-namespaces. + * @param {ReflectionObject} object Object removed + * @returns {undefined} + * @private + */ +Root.prototype._handleRemove = function _handleRemove(object) { + if (object instanceof Field) { + + if (/* an extension field */ object.extend !== undefined) { + if (/* already handled */ object.extensionField) { // remove its sister field + object.extensionField.parent.remove(object.extensionField); + object.extensionField = null; + } else { // cancel the extension + var index = this.deferred.indexOf(object); + /* istanbul ignore else */ + if (index > -1) + this.deferred.splice(index, 1); + } + } + + } else if (object instanceof Enum) { + + if (exposeRe.test(object.name)) + delete object.parent[object.name]; // unexpose enum values + + } else if (object instanceof Namespace) { + + for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace + this._handleRemove(object._nestedArray[i]); + + if (exposeRe.test(object.name)) + delete object.parent[object.name]; // unexpose namespaces + + } + + delete this._fullyQualifiedObjects[object.fullName]; +}; + +// Sets up cyclic dependencies (called in index-light) +Root._configure = function(Type_, parse_, common_) { + Type = Type_; + parse = parse_; + common = common_; +}; diff --git a/node_modules/protobufjs/src/roots.js b/node_modules/protobufjs/src/roots.js new file mode 100644 index 0000000..1d93086 --- /dev/null +++ b/node_modules/protobufjs/src/roots.js @@ -0,0 +1,18 @@ +"use strict"; +module.exports = {}; + +/** + * Named roots. + * This is where pbjs stores generated structures (the option `-r, --root` specifies a name). + * Can also be used manually to make roots available across modules. + * @name roots + * @type {Object.} + * @example + * // pbjs -r myroot -o compiled.js ... + * + * // in another module: + * require("./compiled.js"); + * + * // in any subsequent module: + * var root = protobuf.roots["myroot"]; + */ diff --git a/node_modules/protobufjs/src/rpc.js b/node_modules/protobufjs/src/rpc.js new file mode 100644 index 0000000..894e5c7 --- /dev/null +++ b/node_modules/protobufjs/src/rpc.js @@ -0,0 +1,36 @@ +"use strict"; + +/** + * Streaming RPC helpers. + * @namespace + */ +var rpc = exports; + +/** + * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets. + * @typedef RPCImpl + * @type {function} + * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called + * @param {Uint8Array} requestData Request data + * @param {RPCImplCallback} callback Callback function + * @returns {undefined} + * @example + * function rpcImpl(method, requestData, callback) { + * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code + * throw Error("no such method"); + * asynchronouslyObtainAResponse(requestData, function(err, responseData) { + * callback(err, responseData); + * }); + * } + */ + +/** + * Node-style callback as used by {@link RPCImpl}. + * @typedef RPCImplCallback + * @type {function} + * @param {Error|null} error Error, if any, otherwise `null` + * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error + * @returns {undefined} + */ + +rpc.Service = require("./rpc/service"); diff --git a/node_modules/protobufjs/src/rpc/service.js b/node_modules/protobufjs/src/rpc/service.js new file mode 100644 index 0000000..757f382 --- /dev/null +++ b/node_modules/protobufjs/src/rpc/service.js @@ -0,0 +1,142 @@ +"use strict"; +module.exports = Service; + +var util = require("../util/minimal"); + +// Extends EventEmitter +(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; + +/** + * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}. + * + * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`. + * @typedef rpc.ServiceMethodCallback + * @template TRes extends Message + * @type {function} + * @param {Error|null} error Error, if any + * @param {TRes} [response] Response message + * @returns {undefined} + */ + +/** + * A service method part of a {@link rpc.Service} as created by {@link Service.create}. + * @typedef rpc.ServiceMethod + * @template TReq extends Message + * @template TRes extends Message + * @type {function} + * @param {TReq|Properties} request Request message or plain object + * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message + * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined` + */ + +/** + * Constructs a new RPC service instance. + * @classdesc An RPC service as returned by {@link Service#create}. + * @exports rpc.Service + * @extends util.EventEmitter + * @constructor + * @param {RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ +function Service(rpcImpl, requestDelimited, responseDelimited) { + + if (typeof rpcImpl !== "function") + throw TypeError("rpcImpl must be a function"); + + util.EventEmitter.call(this); + + /** + * RPC implementation. Becomes `null` once the service is ended. + * @type {RPCImpl|null} + */ + this.rpcImpl = rpcImpl; + + /** + * Whether requests are length-delimited. + * @type {boolean} + */ + this.requestDelimited = Boolean(requestDelimited); + + /** + * Whether responses are length-delimited. + * @type {boolean} + */ + this.responseDelimited = Boolean(responseDelimited); +} + +/** + * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}. + * @param {Method|rpc.ServiceMethod} method Reflected or static method + * @param {Constructor} requestCtor Request constructor + * @param {Constructor} responseCtor Response constructor + * @param {TReq|Properties} request Request message or plain object + * @param {rpc.ServiceMethodCallback} callback Service callback + * @returns {undefined} + * @template TReq extends Message + * @template TRes extends Message + */ +Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) { + + if (!request) + throw TypeError("request must be specified"); + + var self = this; + if (!callback) + return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request); + + if (!self.rpcImpl) { + setTimeout(function() { callback(Error("already ended")); }, 0); + return undefined; + } + + try { + return self.rpcImpl( + method, + requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(), + function rpcCallback(err, response) { + + if (err) { + self.emit("error", err, method); + return callback(err); + } + + if (response === null) { + self.end(/* endedByRPC */ true); + return undefined; + } + + if (!(response instanceof responseCtor)) { + try { + response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response); + } catch (err) { + self.emit("error", err, method); + return callback(err); + } + } + + self.emit("data", response, method); + return callback(null, response); + } + ); + } catch (err) { + self.emit("error", err, method); + setTimeout(function() { callback(err); }, 0); + return undefined; + } +}; + +/** + * Ends this service and emits the `end` event. + * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation. + * @returns {rpc.Service} `this` + */ +Service.prototype.end = function end(endedByRPC) { + if (this.rpcImpl) { + if (!endedByRPC) // signal end to rpcImpl + this.rpcImpl(null, null, null); + this.rpcImpl = null; + this.emit("end").off(); + } + return this; +}; diff --git a/node_modules/protobufjs/src/service.js b/node_modules/protobufjs/src/service.js new file mode 100644 index 0000000..5046743 --- /dev/null +++ b/node_modules/protobufjs/src/service.js @@ -0,0 +1,189 @@ +"use strict"; +module.exports = Service; + +// extends Namespace +var Namespace = require("./namespace"); +((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service"; + +var Method = require("./method"), + util = require("./util"), + rpc = require("./rpc"); + +/** + * Constructs a new service instance. + * @classdesc Reflected service. + * @extends NamespaceBase + * @constructor + * @param {string} name Service name + * @param {Object.} [options] Service options + * @throws {TypeError} If arguments are invalid + */ +function Service(name, options) { + Namespace.call(this, name, options); + + /** + * Service methods. + * @type {Object.} + */ + this.methods = {}; // toJSON, marker + + /** + * Cached methods as an array. + * @type {Method[]|null} + * @private + */ + this._methodsArray = null; +} + +/** + * Service descriptor. + * @interface IService + * @extends INamespace + * @property {Object.} methods Method descriptors + */ + +/** + * Constructs a service from a service descriptor. + * @param {string} name Service name + * @param {IService} json Service descriptor + * @returns {Service} Created service + * @throws {TypeError} If arguments are invalid + */ +Service.fromJSON = function fromJSON(name, json) { + var service = new Service(name, json.options); + /* istanbul ignore else */ + if (json.methods) + for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i) + service.add(Method.fromJSON(names[i], json.methods[names[i]])); + if (json.nested) + service.addJSON(json.nested); + if (json.edition) + service._edition = json.edition; + service.comment = json.comment; + service._defaultEdition = "proto3"; // For backwards-compatibility. + return service; +}; + +/** + * Converts this service to a service descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IService} Service descriptor + */ +Service.prototype.toJSON = function toJSON(toJSONOptions) { + var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "edition" , this._editionToJSON(), + "options" , inherited && inherited.options || undefined, + "methods" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {}, + "nested" , inherited && inherited.nested || undefined, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * Methods of this service as an array for iteration. + * @name Service#methodsArray + * @type {Method[]} + * @readonly + */ +Object.defineProperty(Service.prototype, "methodsArray", { + get: function() { + return this._methodsArray || (this._methodsArray = util.toArray(this.methods)); + } +}); + +function clearCache(service) { + service._methodsArray = null; + return service; +} + +/** + * @override + */ +Service.prototype.get = function get(name) { + return this.methods[name] + || Namespace.prototype.get.call(this, name); +}; + +/** + * @override + */ +Service.prototype.resolveAll = function resolveAll() { + if (!this._needsRecursiveResolve) return this; + + Namespace.prototype.resolve.call(this); + var methods = this.methodsArray; + for (var i = 0; i < methods.length; ++i) + methods[i].resolve(); + return this; +}; + +/** + * @override + */ +Service.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { + if (!this._needsRecursiveFeatureResolution) return this; + + edition = this._edition || edition; + + Namespace.prototype._resolveFeaturesRecursive.call(this, edition); + this.methodsArray.forEach(method => { + method._resolveFeaturesRecursive(edition); + }); + return this; +}; + +/** + * @override + */ +Service.prototype.add = function add(object) { + + /* istanbul ignore if */ + if (this.get(object.name)) + throw Error("duplicate name '" + object.name + "' in " + this); + + if (object instanceof Method) { + this.methods[object.name] = object; + object.parent = this; + return clearCache(this); + } + return Namespace.prototype.add.call(this, object); +}; + +/** + * @override + */ +Service.prototype.remove = function remove(object) { + if (object instanceof Method) { + + /* istanbul ignore if */ + if (this.methods[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.methods[object.name]; + object.parent = null; + return clearCache(this); + } + return Namespace.prototype.remove.call(this, object); +}; + +/** + * Creates a runtime service using the specified rpc implementation. + * @param {RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed. + */ +Service.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) { + var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited); + for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) { + var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, ""); + rpcService[methodName] = util.codegen(["r","c"], util.isReserved(methodName) ? methodName + "_" : methodName)("return this.rpcCall(m,q,s,r,c)")({ + m: method, + q: method.resolvedRequestType.ctor, + s: method.resolvedResponseType.ctor + }); + } + return rpcService; +}; diff --git a/node_modules/protobufjs/src/tokenize.js b/node_modules/protobufjs/src/tokenize.js new file mode 100644 index 0000000..f107bea --- /dev/null +++ b/node_modules/protobufjs/src/tokenize.js @@ -0,0 +1,416 @@ +"use strict"; +module.exports = tokenize; + +var delimRe = /[\s{}=;:[\],'"()<>]/g, + stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g, + stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g; + +var setCommentRe = /^ *[*/]+ */, + setCommentAltRe = /^\s*\*?\/*/, + setCommentSplitRe = /\n/g, + whitespaceRe = /\s/, + unescapeRe = /\\(.?)/g; + +var unescapeMap = { + "0": "\0", + "r": "\r", + "n": "\n", + "t": "\t" +}; + +/** + * Unescapes a string. + * @param {string} str String to unescape + * @returns {string} Unescaped string + * @property {Object.} map Special characters map + * @memberof tokenize + */ +function unescape(str) { + return str.replace(unescapeRe, function($0, $1) { + switch ($1) { + case "\\": + case "": + return $1; + default: + return unescapeMap[$1] || ""; + } + }); +} + +tokenize.unescape = unescape; + +/** + * Gets the next token and advances. + * @typedef TokenizerHandleNext + * @type {function} + * @returns {string|null} Next token or `null` on eof + */ + +/** + * Peeks for the next token. + * @typedef TokenizerHandlePeek + * @type {function} + * @returns {string|null} Next token or `null` on eof + */ + +/** + * Pushes a token back to the stack. + * @typedef TokenizerHandlePush + * @type {function} + * @param {string} token Token + * @returns {undefined} + */ + +/** + * Skips the next token. + * @typedef TokenizerHandleSkip + * @type {function} + * @param {string} expected Expected token + * @param {boolean} [optional=false] If optional + * @returns {boolean} Whether the token matched + * @throws {Error} If the token didn't match and is not optional + */ + +/** + * Gets the comment on the previous line or, alternatively, the line comment on the specified line. + * @typedef TokenizerHandleCmnt + * @type {function} + * @param {number} [line] Line number + * @returns {string|null} Comment text or `null` if none + */ + +/** + * Handle object returned from {@link tokenize}. + * @interface ITokenizerHandle + * @property {TokenizerHandleNext} next Gets the next token and advances (`null` on eof) + * @property {TokenizerHandlePeek} peek Peeks for the next token (`null` on eof) + * @property {TokenizerHandlePush} push Pushes a token back to the stack + * @property {TokenizerHandleSkip} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws + * @property {TokenizerHandleCmnt} cmnt Gets the comment on the previous line or the line comment on the specified line, if any + * @property {number} line Current line number + */ + +/** + * Tokenizes the given .proto source and returns an object with useful utility functions. + * @param {string} source Source contents + * @param {boolean} alternateCommentMode Whether we should activate alternate comment parsing mode. + * @returns {ITokenizerHandle} Tokenizer handle + */ +function tokenize(source, alternateCommentMode) { + /* eslint-disable callback-return */ + source = source.toString(); + + var offset = 0, + length = source.length, + line = 1, + lastCommentLine = 0, + comments = {}; + + var stack = []; + + var stringDelim = null; + + /* istanbul ignore next */ + /** + * Creates an error for illegal syntax. + * @param {string} subject Subject + * @returns {Error} Error created + * @inner + */ + function illegal(subject) { + return Error("illegal " + subject + " (line " + line + ")"); + } + + /** + * Reads a string till its end. + * @returns {string} String read + * @inner + */ + function readString() { + var re = stringDelim === "'" ? stringSingleRe : stringDoubleRe; + re.lastIndex = offset - 1; + var match = re.exec(source); + if (!match) + throw illegal("string"); + offset = re.lastIndex; + push(stringDelim); + stringDelim = null; + return unescape(match[1]); + } + + /** + * Gets the character at `pos` within the source. + * @param {number} pos Position + * @returns {string} Character + * @inner + */ + function charAt(pos) { + return source.charAt(pos); + } + + /** + * Sets the current comment text. + * @param {number} start Start offset + * @param {number} end End offset + * @param {boolean} isLeading set if a leading comment + * @returns {undefined} + * @inner + */ + function setComment(start, end, isLeading) { + var comment = { + type: source.charAt(start++), + lineEmpty: false, + leading: isLeading, + }; + var lookback; + if (alternateCommentMode) { + lookback = 2; // alternate comment parsing: "//" or "/*" + } else { + lookback = 3; // "///" or "/**" + } + var commentOffset = start - lookback, + c; + do { + if (--commentOffset < 0 || + (c = source.charAt(commentOffset)) === "\n") { + comment.lineEmpty = true; + break; + } + } while (c === " " || c === "\t"); + var lines = source + .substring(start, end) + .split(setCommentSplitRe); + for (var i = 0; i < lines.length; ++i) + lines[i] = lines[i] + .replace(alternateCommentMode ? setCommentAltRe : setCommentRe, "") + .trim(); + comment.text = lines + .join("\n") + .trim(); + + comments[line] = comment; + lastCommentLine = line; + } + + function isDoubleSlashCommentLine(startOffset) { + var endOffset = findEndOfLine(startOffset); + + // see if remaining line matches comment pattern + var lineText = source.substring(startOffset, endOffset); + var isComment = /^\s*\/\//.test(lineText); + return isComment; + } + + function findEndOfLine(cursor) { + // find end of cursor's line + var endOffset = cursor; + while (endOffset < length && charAt(endOffset) !== "\n") { + endOffset++; + } + return endOffset; + } + + /** + * Obtains the next token. + * @returns {string|null} Next token or `null` on eof + * @inner + */ + function next() { + if (stack.length > 0) + return stack.shift(); + if (stringDelim) + return readString(); + var repeat, + prev, + curr, + start, + isDoc, + isLeadingComment = offset === 0; + do { + if (offset === length) + return null; + repeat = false; + while (whitespaceRe.test(curr = charAt(offset))) { + if (curr === "\n") { + isLeadingComment = true; + ++line; + } + if (++offset === length) + return null; + } + + if (charAt(offset) === "/") { + if (++offset === length) { + throw illegal("comment"); + } + if (charAt(offset) === "/") { // Line + if (!alternateCommentMode) { + // check for triple-slash comment + isDoc = charAt(start = offset + 1) === "/"; + + while (charAt(++offset) !== "\n") { + if (offset === length) { + return null; + } + } + ++offset; + if (isDoc) { + setComment(start, offset - 1, isLeadingComment); + // Trailing comment cannot not be multi-line, + // so leading comment state should be reset to handle potential next comments + isLeadingComment = true; + } + ++line; + repeat = true; + } else { + // check for double-slash comments, consolidating consecutive lines + start = offset; + isDoc = false; + if (isDoubleSlashCommentLine(offset - 1)) { + isDoc = true; + do { + offset = findEndOfLine(offset); + if (offset === length) { + break; + } + offset++; + if (!isLeadingComment) { + // Trailing comment cannot not be multi-line + break; + } + } while (isDoubleSlashCommentLine(offset)); + } else { + offset = Math.min(length, findEndOfLine(offset) + 1); + } + if (isDoc) { + setComment(start, offset, isLeadingComment); + isLeadingComment = true; + } + line++; + repeat = true; + } + } else if ((curr = charAt(offset)) === "*") { /* Block */ + // check for /** (regular comment mode) or /* (alternate comment mode) + start = offset + 1; + isDoc = alternateCommentMode || charAt(start) === "*"; + do { + if (curr === "\n") { + ++line; + } + if (++offset === length) { + throw illegal("comment"); + } + prev = curr; + curr = charAt(offset); + } while (prev !== "*" || curr !== "/"); + ++offset; + if (isDoc) { + setComment(start, offset - 2, isLeadingComment); + isLeadingComment = true; + } + repeat = true; + } else { + return "/"; + } + } + } while (repeat); + + // offset !== length if we got here + + var end = offset; + delimRe.lastIndex = 0; + var delim = delimRe.test(charAt(end++)); + if (!delim) + while (end < length && !delimRe.test(charAt(end))) + ++end; + var token = source.substring(offset, offset = end); + if (token === "\"" || token === "'") + stringDelim = token; + return token; + } + + /** + * Pushes a token back to the stack. + * @param {string} token Token + * @returns {undefined} + * @inner + */ + function push(token) { + stack.push(token); + } + + /** + * Peeks for the next token. + * @returns {string|null} Token or `null` on eof + * @inner + */ + function peek() { + if (!stack.length) { + var token = next(); + if (token === null) + return null; + push(token); + } + return stack[0]; + } + + /** + * Skips a token. + * @param {string} expected Expected token + * @param {boolean} [optional=false] Whether the token is optional + * @returns {boolean} `true` when skipped, `false` if not + * @throws {Error} When a required token is not present + * @inner + */ + function skip(expected, optional) { + var actual = peek(), + equals = actual === expected; + if (equals) { + next(); + return true; + } + if (!optional) + throw illegal("token '" + actual + "', '" + expected + "' expected"); + return false; + } + + /** + * Gets a comment. + * @param {number} [trailingLine] Line number if looking for a trailing comment + * @returns {string|null} Comment text + * @inner + */ + function cmnt(trailingLine) { + var ret = null; + var comment; + if (trailingLine === undefined) { + comment = comments[line - 1]; + delete comments[line - 1]; + if (comment && (alternateCommentMode || comment.type === "*" || comment.lineEmpty)) { + ret = comment.leading ? comment.text : null; + } + } else { + /* istanbul ignore else */ + if (lastCommentLine < trailingLine) { + peek(); + } + comment = comments[trailingLine]; + delete comments[trailingLine]; + if (comment && !comment.lineEmpty && (alternateCommentMode || comment.type === "/")) { + ret = comment.leading ? null : comment.text; + } + } + return ret; + } + + return Object.defineProperty({ + next: next, + peek: peek, + push: push, + skip: skip, + cmnt: cmnt + }, "line", { + get: function() { return line; } + }); + /* eslint-enable callback-return */ +} diff --git a/node_modules/protobufjs/src/type.js b/node_modules/protobufjs/src/type.js new file mode 100644 index 0000000..978baf9 --- /dev/null +++ b/node_modules/protobufjs/src/type.js @@ -0,0 +1,614 @@ +"use strict"; +module.exports = Type; + +// extends Namespace +var Namespace = require("./namespace"); +((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type"; + +var Enum = require("./enum"), + OneOf = require("./oneof"), + Field = require("./field"), + MapField = require("./mapfield"), + Service = require("./service"), + Message = require("./message"), + Reader = require("./reader"), + Writer = require("./writer"), + util = require("./util"), + encoder = require("./encoder"), + decoder = require("./decoder"), + verifier = require("./verifier"), + converter = require("./converter"), + wrappers = require("./wrappers"); + +/** + * Constructs a new reflected message type instance. + * @classdesc Reflected message type. + * @extends NamespaceBase + * @constructor + * @param {string} name Message name + * @param {Object.} [options] Declared options + */ +function Type(name, options) { + Namespace.call(this, name, options); + + /** + * Message fields. + * @type {Object.} + */ + this.fields = {}; // toJSON, marker + + /** + * Oneofs declared within this namespace, if any. + * @type {Object.} + */ + this.oneofs = undefined; // toJSON + + /** + * Extension ranges, if any. + * @type {number[][]} + */ + this.extensions = undefined; // toJSON + + /** + * Reserved ranges, if any. + * @type {Array.} + */ + this.reserved = undefined; // toJSON + + /*? + * Whether this type is a legacy group. + * @type {boolean|undefined} + */ + this.group = undefined; // toJSON + + /** + * Cached fields by id. + * @type {Object.|null} + * @private + */ + this._fieldsById = null; + + /** + * Cached fields as an array. + * @type {Field[]|null} + * @private + */ + this._fieldsArray = null; + + /** + * Cached oneofs as an array. + * @type {OneOf[]|null} + * @private + */ + this._oneofsArray = null; + + /** + * Cached constructor. + * @type {Constructor<{}>} + * @private + */ + this._ctor = null; +} + +Object.defineProperties(Type.prototype, { + + /** + * Message fields by id. + * @name Type#fieldsById + * @type {Object.} + * @readonly + */ + fieldsById: { + get: function() { + + /* istanbul ignore if */ + if (this._fieldsById) + return this._fieldsById; + + this._fieldsById = {}; + for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) { + var field = this.fields[names[i]], + id = field.id; + + /* istanbul ignore if */ + if (this._fieldsById[id]) + throw Error("duplicate id " + id + " in " + this); + + this._fieldsById[id] = field; + } + return this._fieldsById; + } + }, + + /** + * Fields of this message as an array for iteration. + * @name Type#fieldsArray + * @type {Field[]} + * @readonly + */ + fieldsArray: { + get: function() { + return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields)); + } + }, + + /** + * Oneofs of this message as an array for iteration. + * @name Type#oneofsArray + * @type {OneOf[]} + * @readonly + */ + oneofsArray: { + get: function() { + return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs)); + } + }, + + /** + * The registered constructor, if any registered, otherwise a generic constructor. + * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor. + * @name Type#ctor + * @type {Constructor<{}>} + */ + ctor: { + get: function() { + return this._ctor || (this.ctor = Type.generateConstructor(this)()); + }, + set: function(ctor) { + + // Ensure proper prototype + var prototype = ctor.prototype; + if (!(prototype instanceof Message)) { + (ctor.prototype = new Message()).constructor = ctor; + util.merge(ctor.prototype, prototype); + } + + // Classes and messages reference their reflected type + ctor.$type = ctor.prototype.$type = this; + + // Mix in static methods + util.merge(ctor, Message, true); + + this._ctor = ctor; + + // Messages have non-enumerable default values on their prototype + var i = 0; + for (; i < /* initializes */ this.fieldsArray.length; ++i) + this._fieldsArray[i].resolve(); // ensures a proper value + + // Messages have non-enumerable getters and setters for each virtual oneof field + var ctorProperties = {}; + for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i) + ctorProperties[this._oneofsArray[i].resolve().name] = { + get: util.oneOfGetter(this._oneofsArray[i].oneof), + set: util.oneOfSetter(this._oneofsArray[i].oneof) + }; + if (i) + Object.defineProperties(ctor.prototype, ctorProperties); + } + } +}); + +/** + * Generates a constructor function for the specified type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +Type.generateConstructor = function generateConstructor(mtype) { + /* eslint-disable no-unexpected-multiline */ + var gen = util.codegen(["p"], mtype.name); + // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype + for (var i = 0, field; i < mtype.fieldsArray.length; ++i) + if ((field = mtype._fieldsArray[i]).map) gen + ("this%s={}", util.safeProp(field.name)); + else if (field.repeated) gen + ("this%s=[]", util.safeProp(field.name)); + return gen + ("if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors + * @property {Object.} fields Field descriptors + * @property {number[][]} [extensions] Extension ranges + * @property {Array.} [reserved] Reserved ranges + * @property {boolean} [group=false] Whether a legacy group or not + */ + +/** + * Creates a message type from a message type descriptor. + * @param {string} name Message name + * @param {IType} json Message type descriptor + * @returns {Type} Created message type + */ +Type.fromJSON = function fromJSON(name, json) { + var type = new Type(name, json.options); + type.extensions = json.extensions; + type.reserved = json.reserved; + var names = Object.keys(json.fields), + i = 0; + for (; i < names.length; ++i) + type.add( + ( typeof json.fields[names[i]].keyType !== "undefined" + ? MapField.fromJSON + : Field.fromJSON )(names[i], json.fields[names[i]]) + ); + if (json.oneofs) + for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i) + type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]])); + if (json.nested) + for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) { + var nested = json.nested[names[i]]; + type.add( // most to least likely + ( nested.id !== undefined + ? Field.fromJSON + : nested.fields !== undefined + ? Type.fromJSON + : nested.values !== undefined + ? Enum.fromJSON + : nested.methods !== undefined + ? Service.fromJSON + : Namespace.fromJSON )(names[i], nested) + ); + } + if (json.extensions && json.extensions.length) + type.extensions = json.extensions; + if (json.reserved && json.reserved.length) + type.reserved = json.reserved; + if (json.group) + type.group = true; + if (json.comment) + type.comment = json.comment; + if (json.edition) + type._edition = json.edition; + type._defaultEdition = "proto3"; // For backwards-compatibility. + return type; +}; + +/** + * Converts this message type to a message type descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IType} Message type descriptor + */ +Type.prototype.toJSON = function toJSON(toJSONOptions) { + var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "edition" , this._editionToJSON(), + "options" , inherited && inherited.options || undefined, + "oneofs" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions), + "fields" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {}, + "extensions" , this.extensions && this.extensions.length ? this.extensions : undefined, + "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined, + "group" , this.group || undefined, + "nested" , inherited && inherited.nested || undefined, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * @override + */ +Type.prototype.resolveAll = function resolveAll() { + if (!this._needsRecursiveResolve) return this; + + Namespace.prototype.resolveAll.call(this); + var oneofs = this.oneofsArray; i = 0; + while (i < oneofs.length) + oneofs[i++].resolve(); + var fields = this.fieldsArray, i = 0; + while (i < fields.length) + fields[i++].resolve(); + return this; +}; + +/** + * @override + */ +Type.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { + if (!this._needsRecursiveFeatureResolution) return this; + + edition = this._edition || edition; + + Namespace.prototype._resolveFeaturesRecursive.call(this, edition); + this.oneofsArray.forEach(oneof => { + oneof._resolveFeatures(edition); + }); + this.fieldsArray.forEach(field => { + field._resolveFeatures(edition); + }); + return this; +}; + +/** + * @override + */ +Type.prototype.get = function get(name) { + return this.fields[name] + || this.oneofs && this.oneofs[name] + || this.nested && this.nested[name] + || null; +}; + +/** + * Adds a nested object to this type. + * @param {ReflectionObject} object Nested object to add + * @returns {Type} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id + */ +Type.prototype.add = function add(object) { + + if (this.get(object.name)) + throw Error("duplicate name '" + object.name + "' in " + this); + + if (object instanceof Field && object.extend === undefined) { + // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects. + // The root object takes care of adding distinct sister-fields to the respective extended + // type instead. + + // avoids calling the getter if not absolutely necessary because it's called quite frequently + if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id]) + throw Error("duplicate id " + object.id + " in " + this); + if (this.isReservedId(object.id)) + throw Error("id " + object.id + " is reserved in " + this); + if (this.isReservedName(object.name)) + throw Error("name '" + object.name + "' is reserved in " + this); + + if (object.parent) + object.parent.remove(object); + this.fields[object.name] = object; + object.message = this; + object.onAdd(this); + return clearCache(this); + } + if (object instanceof OneOf) { + if (!this.oneofs) + this.oneofs = {}; + this.oneofs[object.name] = object; + object.onAdd(this); + return clearCache(this); + } + return Namespace.prototype.add.call(this, object); +}; + +/** + * Removes a nested object from this type. + * @param {ReflectionObject} object Nested object to remove + * @returns {Type} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `object` is not a member of this type + */ +Type.prototype.remove = function remove(object) { + if (object instanceof Field && object.extend === undefined) { + // See Type#add for the reason why extension fields are excluded here. + + /* istanbul ignore if */ + if (!this.fields || this.fields[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.fields[object.name]; + object.parent = null; + object.onRemove(this); + return clearCache(this); + } + if (object instanceof OneOf) { + + /* istanbul ignore if */ + if (!this.oneofs || this.oneofs[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.oneofs[object.name]; + object.parent = null; + object.onRemove(this); + return clearCache(this); + } + return Namespace.prototype.remove.call(this, object); +}; + +/** + * Tests if the specified id is reserved. + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Type.prototype.isReservedId = function isReservedId(id) { + return Namespace.isReservedId(this.reserved, id); +}; + +/** + * Tests if the specified name is reserved. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Type.prototype.isReservedName = function isReservedName(name) { + return Namespace.isReservedName(this.reserved, name); +}; + +/** + * Creates a new message of this type using the specified properties. + * @param {Object.} [properties] Properties to set + * @returns {Message<{}>} Message instance + */ +Type.prototype.create = function create(properties) { + return new this.ctor(properties); +}; + +/** + * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}. + * @returns {Type} `this` + */ +Type.prototype.setup = function setup() { + // Sets up everything at once so that the prototype chain does not have to be re-evaluated + // multiple times (V8, soft-deopt prototype-check). + + var fullName = this.fullName, + types = []; + for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i) + types.push(this._fieldsArray[i].resolve().resolvedType); + + // Replace setup methods with type-specific generated functions + this.encode = encoder(this)({ + Writer : Writer, + types : types, + util : util + }); + this.decode = decoder(this)({ + Reader : Reader, + types : types, + util : util + }); + this.verify = verifier(this)({ + types : types, + util : util + }); + this.fromObject = converter.fromObject(this)({ + types : types, + util : util + }); + this.toObject = converter.toObject(this)({ + types : types, + util : util + }); + + // Inject custom wrappers for common types + var wrapper = wrappers[fullName]; + if (wrapper) { + var originalThis = Object.create(this); + // if (wrapper.fromObject) { + originalThis.fromObject = this.fromObject; + this.fromObject = wrapper.fromObject.bind(originalThis); + // } + // if (wrapper.toObject) { + originalThis.toObject = this.toObject; + this.toObject = wrapper.toObject.bind(originalThis); + // } + } + + return this; +}; + +/** + * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages. + * @param {Message<{}>|Object.} message Message instance or plain object + * @param {Writer} [writer] Writer to encode to + * @returns {Writer} writer + */ +Type.prototype.encode = function encode_setup(message, writer) { + return this.setup().encode(message, writer); // overrides this method +}; + +/** + * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages. + * @param {Message<{}>|Object.} message Message instance or plain object + * @param {Writer} [writer] Writer to encode to + * @returns {Writer} writer + */ +Type.prototype.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim(); +}; + +/** + * Decodes a message of this type. + * @param {Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Length of the message, if known beforehand + * @returns {Message<{}>} Decoded message + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {util.ProtocolError<{}>} If required fields are missing + */ +Type.prototype.decode = function decode_setup(reader, length) { + return this.setup().decode(reader, length); // overrides this method +}; + +/** + * Decodes a message of this type preceeded by its byte length as a varint. + * @param {Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {Message<{}>} Decoded message + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {util.ProtocolError} If required fields are missing + */ +Type.prototype.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof Reader)) + reader = Reader.create(reader); + return this.decode(reader, reader.uint32()); +}; + +/** + * Verifies that field values are valid and that required fields are present. + * @param {Object.} message Plain object to verify + * @returns {null|string} `null` if valid, otherwise the reason why it is not + */ +Type.prototype.verify = function verify_setup(message) { + return this.setup().verify(message); // overrides this method +}; + +/** + * Creates a new message of this type from a plain object. Also converts values to their respective internal types. + * @param {Object.} object Plain object to convert + * @returns {Message<{}>} Message instance + */ +Type.prototype.fromObject = function fromObject(object) { + return this.setup().fromObject(object); +}; + +/** + * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}. + * @interface IConversionOptions + * @property {Function} [longs] Long conversion type. + * Valid values are `String` and `Number` (the global types). + * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library. + * @property {Function} [enums] Enum value conversion type. + * Only valid value is `String` (the global type). + * Defaults to copy the present value, which is the numeric id. + * @property {Function} [bytes] Bytes value conversion type. + * Valid values are `Array` and (a base64 encoded) `String` (the global types). + * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser. + * @property {boolean} [defaults=false] Also sets default values on the resulting object + * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false` + * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false` + * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any + * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings + */ + +/** + * Creates a plain object from a message of this type. Also converts values to other types if specified. + * @param {Message<{}>} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ +Type.prototype.toObject = function toObject(message, options) { + return this.setup().toObject(message, options); +}; + +/** + * Decorator function as returned by {@link Type.d} (TypeScript). + * @typedef TypeDecorator + * @type {function} + * @param {Constructor} target Target constructor + * @returns {undefined} + * @template T extends Message + */ + +/** + * Type decorator (TypeScript). + * @param {string} [typeName] Type name, defaults to the constructor's name + * @returns {TypeDecorator} Decorator function + * @template T extends Message + */ +Type.d = function decorateType(typeName) { + return function typeDecorator(target) { + util.decorateType(target, typeName); + }; +}; diff --git a/node_modules/protobufjs/src/types.js b/node_modules/protobufjs/src/types.js new file mode 100644 index 0000000..5fda19a --- /dev/null +++ b/node_modules/protobufjs/src/types.js @@ -0,0 +1,196 @@ +"use strict"; + +/** + * Common type constants. + * @namespace + */ +var types = exports; + +var util = require("./util"); + +var s = [ + "double", // 0 + "float", // 1 + "int32", // 2 + "uint32", // 3 + "sint32", // 4 + "fixed32", // 5 + "sfixed32", // 6 + "int64", // 7 + "uint64", // 8 + "sint64", // 9 + "fixed64", // 10 + "sfixed64", // 11 + "bool", // 12 + "string", // 13 + "bytes" // 14 +]; + +function bake(values, offset) { + var i = 0, o = {}; + offset |= 0; + while (i < values.length) o[s[i + offset]] = values[i++]; + return o; +} + +/** + * Basic type wire types. + * @type {Object.} + * @const + * @property {number} double=1 Fixed64 wire type + * @property {number} float=5 Fixed32 wire type + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + * @property {number} string=2 Ldelim wire type + * @property {number} bytes=2 Ldelim wire type + */ +types.basic = bake([ + /* double */ 1, + /* float */ 5, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0, + /* string */ 2, + /* bytes */ 2 +]); + +/** + * Basic type defaults. + * @type {Object.} + * @const + * @property {number} double=0 Double default + * @property {number} float=0 Float default + * @property {number} int32=0 Int32 default + * @property {number} uint32=0 Uint32 default + * @property {number} sint32=0 Sint32 default + * @property {number} fixed32=0 Fixed32 default + * @property {number} sfixed32=0 Sfixed32 default + * @property {number} int64=0 Int64 default + * @property {number} uint64=0 Uint64 default + * @property {number} sint64=0 Sint32 default + * @property {number} fixed64=0 Fixed64 default + * @property {number} sfixed64=0 Sfixed64 default + * @property {boolean} bool=false Bool default + * @property {string} string="" String default + * @property {Array.} bytes=Array(0) Bytes default + * @property {null} message=null Message default + */ +types.defaults = bake([ + /* double */ 0, + /* float */ 0, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 0, + /* sfixed32 */ 0, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 0, + /* sfixed64 */ 0, + /* bool */ false, + /* string */ "", + /* bytes */ util.emptyArray, + /* message */ null +]); + +/** + * Basic long type wire types. + * @type {Object.} + * @const + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + */ +types.long = bake([ + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1 +], 7); + +/** + * Allowed types for map keys with their associated wire type. + * @type {Object.} + * @const + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + * @property {number} string=2 Ldelim wire type + */ +types.mapKey = bake([ + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0, + /* string */ 2 +], 2); + +/** + * Allowed types for packed repeated fields with their associated wire type. + * @type {Object.} + * @const + * @property {number} double=1 Fixed64 wire type + * @property {number} float=5 Fixed32 wire type + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + */ +types.packed = bake([ + /* double */ 1, + /* float */ 5, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0 +]); diff --git a/node_modules/protobufjs/src/typescript.jsdoc b/node_modules/protobufjs/src/typescript.jsdoc new file mode 100644 index 0000000..9a67101 --- /dev/null +++ b/node_modules/protobufjs/src/typescript.jsdoc @@ -0,0 +1,15 @@ +/** + * Constructor type. + * @interface Constructor + * @extends Function + * @template T + * @tstype new(...params: any[]): T; prototype: T; + */ + +/** + * Properties type. + * @typedef Properties + * @template T + * @type {Object.} + * @tstype { [P in keyof T]?: T[P] } + */ diff --git a/node_modules/protobufjs/src/util.js b/node_modules/protobufjs/src/util.js new file mode 100644 index 0000000..a77feae --- /dev/null +++ b/node_modules/protobufjs/src/util.js @@ -0,0 +1,215 @@ +"use strict"; + +/** + * Various utility functions. + * @namespace + */ +var util = module.exports = require("./util/minimal"); + +var roots = require("./roots"); + +var Type, // cyclic + Enum; + +util.codegen = require("@protobufjs/codegen"); +util.fetch = require("@protobufjs/fetch"); +util.path = require("@protobufjs/path"); + +/** + * Node's fs module if available. + * @type {Object.} + */ +util.fs = util.inquire("fs"); + +/** + * Converts an object's values to an array. + * @param {Object.} object Object to convert + * @returns {Array.<*>} Converted array + */ +util.toArray = function toArray(object) { + if (object) { + var keys = Object.keys(object), + array = new Array(keys.length), + index = 0; + while (index < keys.length) + array[index] = object[keys[index++]]; + return array; + } + return []; +}; + +/** + * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values. + * @param {Array.<*>} array Array to convert + * @returns {Object.} Converted object + */ +util.toObject = function toObject(array) { + var object = {}, + index = 0; + while (index < array.length) { + var key = array[index++], + val = array[index++]; + if (val !== undefined) + object[key] = val; + } + return object; +}; + +var safePropBackslashRe = /\\/g, + safePropQuoteRe = /"/g; + +/** + * Tests whether the specified name is a reserved word in JS. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +util.isReserved = function isReserved(name) { + return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name); +}; + +/** + * Returns a safe property accessor for the specified property name. + * @param {string} prop Property name + * @returns {string} Safe accessor + */ +util.safeProp = function safeProp(prop) { + if (!/^[$\w_]+$/.test(prop) || util.isReserved(prop)) + return "[\"" + prop.replace(safePropBackslashRe, "\\\\").replace(safePropQuoteRe, "\\\"") + "\"]"; + return "." + prop; +}; + +/** + * Converts the first character of a string to upper case. + * @param {string} str String to convert + * @returns {string} Converted string + */ +util.ucFirst = function ucFirst(str) { + return str.charAt(0).toUpperCase() + str.substring(1); +}; + +var camelCaseRe = /_([a-z])/g; + +/** + * Converts a string to camel case. + * @param {string} str String to convert + * @returns {string} Converted string + */ +util.camelCase = function camelCase(str) { + return str.substring(0, 1) + + str.substring(1) + .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); }); +}; + +/** + * Compares reflected fields by id. + * @param {Field} a First field + * @param {Field} b Second field + * @returns {number} Comparison value + */ +util.compareFieldsById = function compareFieldsById(a, b) { + return a.id - b.id; +}; + +/** + * Decorator helper for types (TypeScript). + * @param {Constructor} ctor Constructor function + * @param {string} [typeName] Type name, defaults to the constructor's name + * @returns {Type} Reflected type + * @template T extends Message + * @property {Root} root Decorators root + */ +util.decorateType = function decorateType(ctor, typeName) { + + /* istanbul ignore if */ + if (ctor.$type) { + if (typeName && ctor.$type.name !== typeName) { + util.decorateRoot.remove(ctor.$type); + ctor.$type.name = typeName; + util.decorateRoot.add(ctor.$type); + } + return ctor.$type; + } + + /* istanbul ignore next */ + if (!Type) + Type = require("./type"); + + var type = new Type(typeName || ctor.name); + util.decorateRoot.add(type); + type.ctor = ctor; // sets up .encode, .decode etc. + Object.defineProperty(ctor, "$type", { value: type, enumerable: false }); + Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false }); + return type; +}; + +var decorateEnumIndex = 0; + +/** + * Decorator helper for enums (TypeScript). + * @param {Object} object Enum object + * @returns {Enum} Reflected enum + */ +util.decorateEnum = function decorateEnum(object) { + + /* istanbul ignore if */ + if (object.$type) + return object.$type; + + /* istanbul ignore next */ + if (!Enum) + Enum = require("./enum"); + + var enm = new Enum("Enum" + decorateEnumIndex++, object); + util.decorateRoot.add(enm); + Object.defineProperty(object, "$type", { value: enm, enumerable: false }); + return enm; +}; + + +/** + * Sets the value of a property by property path. If a value already exists, it is turned to an array + * @param {Object.} dst Destination object + * @param {string} path dot '.' delimited path of the property to set + * @param {Object} value the value to set + * @param {boolean|undefined} [ifNotSet] Sets the option only if it isn't currently set + * @returns {Object.} Destination object + */ +util.setProperty = function setProperty(dst, path, value, ifNotSet) { + function setProp(dst, path, value) { + var part = path.shift(); + if (part === "__proto__" || part === "prototype") { + return dst; + } + if (path.length > 0) { + dst[part] = setProp(dst[part] || {}, path, value); + } else { + var prevValue = dst[part]; + if (prevValue && ifNotSet) + return dst; + if (prevValue) + value = [].concat(prevValue).concat(value); + dst[part] = value; + } + return dst; + } + + if (typeof dst !== "object") + throw TypeError("dst must be an object"); + if (!path) + throw TypeError("path must be specified"); + + path = path.split("."); + return setProp(dst, path, value); +}; + +/** + * Decorator root (TypeScript). + * @name util.decorateRoot + * @type {Root} + * @readonly + */ +Object.defineProperty(util, "decorateRoot", { + get: function() { + return roots["decorated"] || (roots["decorated"] = new (require("./root"))()); + } +}); diff --git a/node_modules/protobufjs/src/util/longbits.js b/node_modules/protobufjs/src/util/longbits.js new file mode 100644 index 0000000..11bfb1c --- /dev/null +++ b/node_modules/protobufjs/src/util/longbits.js @@ -0,0 +1,200 @@ +"use strict"; +module.exports = LongBits; + +var util = require("../util/minimal"); + +/** + * Constructs new long bits. + * @classdesc Helper class for working with the low and high bits of a 64 bit value. + * @memberof util + * @constructor + * @param {number} lo Low 32 bits, unsigned + * @param {number} hi High 32 bits, unsigned + */ +function LongBits(lo, hi) { + + // note that the casts below are theoretically unnecessary as of today, but older statically + // generated converter code might still call the ctor with signed 32bits. kept for compat. + + /** + * Low bits. + * @type {number} + */ + this.lo = lo >>> 0; + + /** + * High bits. + * @type {number} + */ + this.hi = hi >>> 0; +} + +/** + * Zero bits. + * @memberof util.LongBits + * @type {util.LongBits} + */ +var zero = LongBits.zero = new LongBits(0, 0); + +zero.toNumber = function() { return 0; }; +zero.zzEncode = zero.zzDecode = function() { return this; }; +zero.length = function() { return 1; }; + +/** + * Zero hash. + * @memberof util.LongBits + * @type {string} + */ +var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; + +/** + * Constructs new long bits from the specified number. + * @param {number} value Value + * @returns {util.LongBits} Instance + */ +LongBits.fromNumber = function fromNumber(value) { + if (value === 0) + return zero; + var sign = value < 0; + if (sign) + value = -value; + var lo = value >>> 0, + hi = (value - lo) / 4294967296 >>> 0; + if (sign) { + hi = ~hi >>> 0; + lo = ~lo >>> 0; + if (++lo > 4294967295) { + lo = 0; + if (++hi > 4294967295) + hi = 0; + } + } + return new LongBits(lo, hi); +}; + +/** + * Constructs new long bits from a number, long or string. + * @param {Long|number|string} value Value + * @returns {util.LongBits} Instance + */ +LongBits.from = function from(value) { + if (typeof value === "number") + return LongBits.fromNumber(value); + if (util.isString(value)) { + /* istanbul ignore else */ + if (util.Long) + value = util.Long.fromString(value); + else + return LongBits.fromNumber(parseInt(value, 10)); + } + return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; +}; + +/** + * Converts this long bits to a possibly unsafe JavaScript number. + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {number} Possibly unsafe number + */ +LongBits.prototype.toNumber = function toNumber(unsigned) { + if (!unsigned && this.hi >>> 31) { + var lo = ~this.lo + 1 >>> 0, + hi = ~this.hi >>> 0; + if (!lo) + hi = hi + 1 >>> 0; + return -(lo + hi * 4294967296); + } + return this.lo + this.hi * 4294967296; +}; + +/** + * Converts this long bits to a long. + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {Long} Long + */ +LongBits.prototype.toLong = function toLong(unsigned) { + return util.Long + ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) + /* istanbul ignore next */ + : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; +}; + +var charCodeAt = String.prototype.charCodeAt; + +/** + * Constructs new long bits from the specified 8 characters long hash. + * @param {string} hash Hash + * @returns {util.LongBits} Bits + */ +LongBits.fromHash = function fromHash(hash) { + if (hash === zeroHash) + return zero; + return new LongBits( + ( charCodeAt.call(hash, 0) + | charCodeAt.call(hash, 1) << 8 + | charCodeAt.call(hash, 2) << 16 + | charCodeAt.call(hash, 3) << 24) >>> 0 + , + ( charCodeAt.call(hash, 4) + | charCodeAt.call(hash, 5) << 8 + | charCodeAt.call(hash, 6) << 16 + | charCodeAt.call(hash, 7) << 24) >>> 0 + ); +}; + +/** + * Converts this long bits to a 8 characters long hash. + * @returns {string} Hash + */ +LongBits.prototype.toHash = function toHash() { + return String.fromCharCode( + this.lo & 255, + this.lo >>> 8 & 255, + this.lo >>> 16 & 255, + this.lo >>> 24 , + this.hi & 255, + this.hi >>> 8 & 255, + this.hi >>> 16 & 255, + this.hi >>> 24 + ); +}; + +/** + * Zig-zag encodes this long bits. + * @returns {util.LongBits} `this` + */ +LongBits.prototype.zzEncode = function zzEncode() { + var mask = this.hi >> 31; + this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; + this.lo = ( this.lo << 1 ^ mask) >>> 0; + return this; +}; + +/** + * Zig-zag decodes this long bits. + * @returns {util.LongBits} `this` + */ +LongBits.prototype.zzDecode = function zzDecode() { + var mask = -(this.lo & 1); + this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; + this.hi = ( this.hi >>> 1 ^ mask) >>> 0; + return this; +}; + +/** + * Calculates the length of this longbits when encoded as a varint. + * @returns {number} Length + */ +LongBits.prototype.length = function length() { + var part0 = this.lo, + part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, + part2 = this.hi >>> 24; + return part2 === 0 + ? part1 === 0 + ? part0 < 16384 + ? part0 < 128 ? 1 : 2 + : part0 < 2097152 ? 3 : 4 + : part1 < 16384 + ? part1 < 128 ? 5 : 6 + : part1 < 2097152 ? 7 : 8 + : part2 < 128 ? 9 : 10; +}; diff --git a/node_modules/protobufjs/src/util/minimal.js b/node_modules/protobufjs/src/util/minimal.js new file mode 100644 index 0000000..62d6833 --- /dev/null +++ b/node_modules/protobufjs/src/util/minimal.js @@ -0,0 +1,438 @@ +"use strict"; +var util = exports; + +// used to return a Promise where callback is omitted +util.asPromise = require("@protobufjs/aspromise"); + +// converts to / from base64 encoded strings +util.base64 = require("@protobufjs/base64"); + +// base class of rpc.Service +util.EventEmitter = require("@protobufjs/eventemitter"); + +// float handling accross browsers +util.float = require("@protobufjs/float"); + +// requires modules optionally and hides the call from bundlers +util.inquire = require("@protobufjs/inquire"); + +// converts to / from utf8 encoded strings +util.utf8 = require("@protobufjs/utf8"); + +// provides a node-like buffer pool in the browser +util.pool = require("@protobufjs/pool"); + +// utility to work with the low and high bits of a 64 bit value +util.LongBits = require("./longbits"); + +/** + * Whether running within node or not. + * @memberof util + * @type {boolean} + */ +util.isNode = Boolean(typeof global !== "undefined" + && global + && global.process + && global.process.versions + && global.process.versions.node); + +/** + * Global object reference. + * @memberof util + * @type {Object} + */ +util.global = util.isNode && global + || typeof window !== "undefined" && window + || typeof self !== "undefined" && self + || this; // eslint-disable-line no-invalid-this + +/** + * An immuable empty array. + * @memberof util + * @type {Array.<*>} + * @const + */ +util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes + +/** + * An immutable empty object. + * @type {Object} + * @const + */ +util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes + +/** + * Tests if the specified value is an integer. + * @function + * @param {*} value Value to test + * @returns {boolean} `true` if the value is an integer + */ +util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) { + return typeof value === "number" && isFinite(value) && Math.floor(value) === value; +}; + +/** + * Tests if the specified value is a string. + * @param {*} value Value to test + * @returns {boolean} `true` if the value is a string + */ +util.isString = function isString(value) { + return typeof value === "string" || value instanceof String; +}; + +/** + * Tests if the specified value is a non-null object. + * @param {*} value Value to test + * @returns {boolean} `true` if the value is a non-null object + */ +util.isObject = function isObject(value) { + return value && typeof value === "object"; +}; + +/** + * Checks if a property on a message is considered to be present. + * This is an alias of {@link util.isSet}. + * @function + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ +util.isset = + +/** + * Checks if a property on a message is considered to be present. + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ +util.isSet = function isSet(obj, prop) { + var value = obj[prop]; + if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins + return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; + return false; +}; + +/** + * Any compatible Buffer instance. + * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings. + * @interface Buffer + * @extends Uint8Array + */ + +/** + * Node's Buffer class if available. + * @type {Constructor} + */ +util.Buffer = (function() { + try { + var Buffer = util.inquire("buffer").Buffer; + // refuse to use non-node buffers if not explicitly assigned (perf reasons): + return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null; + } catch (e) { + /* istanbul ignore next */ + return null; + } +})(); + +// Internal alias of or polyfull for Buffer.from. +util._Buffer_from = null; + +// Internal alias of or polyfill for Buffer.allocUnsafe. +util._Buffer_allocUnsafe = null; + +/** + * Creates a new buffer of whatever type supported by the environment. + * @param {number|number[]} [sizeOrArray=0] Buffer size or number array + * @returns {Uint8Array|Buffer} Buffer + */ +util.newBuffer = function newBuffer(sizeOrArray) { + /* istanbul ignore next */ + return typeof sizeOrArray === "number" + ? util.Buffer + ? util._Buffer_allocUnsafe(sizeOrArray) + : new util.Array(sizeOrArray) + : util.Buffer + ? util._Buffer_from(sizeOrArray) + : typeof Uint8Array === "undefined" + ? sizeOrArray + : new Uint8Array(sizeOrArray); +}; + +/** + * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`. + * @type {Constructor} + */ +util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array; + +/** + * Any compatible Long instance. + * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js. + * @interface Long + * @property {number} low Low bits + * @property {number} high High bits + * @property {boolean} unsigned Whether unsigned or not + */ + +/** + * Long.js's Long class if available. + * @type {Constructor} + */ +util.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long + || /* istanbul ignore next */ util.global.Long + || util.inquire("long"); + +/** + * Regular expression used to verify 2 bit (`bool`) map keys. + * @type {RegExp} + * @const + */ +util.key2Re = /^true|false|0|1$/; + +/** + * Regular expression used to verify 32 bit (`int32` etc.) map keys. + * @type {RegExp} + * @const + */ +util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; + +/** + * Regular expression used to verify 64 bit (`int64` etc.) map keys. + * @type {RegExp} + * @const + */ +util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; + +/** + * Converts a number or long to an 8 characters long hash string. + * @param {Long|number} value Value to convert + * @returns {string} Hash + */ +util.longToHash = function longToHash(value) { + return value + ? util.LongBits.from(value).toHash() + : util.LongBits.zeroHash; +}; + +/** + * Converts an 8 characters long hash string to a long or number. + * @param {string} hash Hash + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {Long|number} Original value + */ +util.longFromHash = function longFromHash(hash, unsigned) { + var bits = util.LongBits.fromHash(hash); + if (util.Long) + return util.Long.fromBits(bits.lo, bits.hi, unsigned); + return bits.toNumber(Boolean(unsigned)); +}; + +/** + * Merges the properties of the source object into the destination object. + * @memberof util + * @param {Object.} dst Destination object + * @param {Object.} src Source object + * @param {boolean} [ifNotSet=false] Merges only if the key is not already set + * @returns {Object.} Destination object + */ +function merge(dst, src, ifNotSet) { // used by converters + for (var keys = Object.keys(src), i = 0; i < keys.length; ++i) + if (dst[keys[i]] === undefined || !ifNotSet) + dst[keys[i]] = src[keys[i]]; + return dst; +} + +util.merge = merge; + +/** + * Converts the first character of a string to lower case. + * @param {string} str String to convert + * @returns {string} Converted string + */ +util.lcFirst = function lcFirst(str) { + return str.charAt(0).toLowerCase() + str.substring(1); +}; + +/** + * Creates a custom error constructor. + * @memberof util + * @param {string} name Error name + * @returns {Constructor} Custom error constructor + */ +function newError(name) { + + function CustomError(message, properties) { + + if (!(this instanceof CustomError)) + return new CustomError(message, properties); + + // Error.call(this, message); + // ^ just returns a new error instance because the ctor can be called as a function + + Object.defineProperty(this, "message", { get: function() { return message; } }); + + /* istanbul ignore next */ + if (Error.captureStackTrace) // node + Error.captureStackTrace(this, CustomError); + else + Object.defineProperty(this, "stack", { value: new Error().stack || "" }); + + if (properties) + merge(this, properties); + } + + CustomError.prototype = Object.create(Error.prototype, { + constructor: { + value: CustomError, + writable: true, + enumerable: false, + configurable: true, + }, + name: { + get: function get() { return name; }, + set: undefined, + enumerable: false, + // configurable: false would accurately preserve the behavior of + // the original, but I'm guessing that was not intentional. + // For an actual error subclass, this property would + // be configurable. + configurable: true, + }, + toString: { + value: function value() { return this.name + ": " + this.message; }, + writable: true, + enumerable: false, + configurable: true, + }, + }); + + return CustomError; +} + +util.newError = newError; + +/** + * Constructs a new protocol error. + * @classdesc Error subclass indicating a protocol specifc error. + * @memberof util + * @extends Error + * @template T extends Message + * @constructor + * @param {string} message Error message + * @param {Object.} [properties] Additional properties + * @example + * try { + * MyMessage.decode(someBuffer); // throws if required fields are missing + * } catch (e) { + * if (e instanceof ProtocolError && e.instance) + * console.log("decoded so far: " + JSON.stringify(e.instance)); + * } + */ +util.ProtocolError = newError("ProtocolError"); + +/** + * So far decoded message instance. + * @name util.ProtocolError#instance + * @type {Message} + */ + +/** + * A OneOf getter as returned by {@link util.oneOfGetter}. + * @typedef OneOfGetter + * @type {function} + * @returns {string|undefined} Set field name, if any + */ + +/** + * Builds a getter for a oneof's present field name. + * @param {string[]} fieldNames Field names + * @returns {OneOfGetter} Unbound getter + */ +util.oneOfGetter = function getOneOf(fieldNames) { + var fieldMap = {}; + for (var i = 0; i < fieldNames.length; ++i) + fieldMap[fieldNames[i]] = 1; + + /** + * @returns {string|undefined} Set field name, if any + * @this Object + * @ignore + */ + return function() { // eslint-disable-line consistent-return + for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i) + if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null) + return keys[i]; + }; +}; + +/** + * A OneOf setter as returned by {@link util.oneOfSetter}. + * @typedef OneOfSetter + * @type {function} + * @param {string|undefined} value Field name + * @returns {undefined} + */ + +/** + * Builds a setter for a oneof's present field name. + * @param {string[]} fieldNames Field names + * @returns {OneOfSetter} Unbound setter + */ +util.oneOfSetter = function setOneOf(fieldNames) { + + /** + * @param {string} name Field name + * @returns {undefined} + * @this Object + * @ignore + */ + return function(name) { + for (var i = 0; i < fieldNames.length; ++i) + if (fieldNames[i] !== name) + delete this[fieldNames[i]]; + }; +}; + +/** + * Default conversion options used for {@link Message#toJSON} implementations. + * + * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely: + * + * - Longs become strings + * - Enums become string keys + * - Bytes become base64 encoded strings + * - (Sub-)Messages become plain objects + * - Maps become plain objects with all string keys + * - Repeated fields become arrays + * - NaN and Infinity for float and double fields become strings + * + * @type {IConversionOptions} + * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json + */ +util.toJSONOptions = { + longs: String, + enums: String, + bytes: String, + json: true +}; + +// Sets up buffer utility according to the environment (called in index-minimal) +util._configure = function() { + var Buffer = util.Buffer; + /* istanbul ignore if */ + if (!Buffer) { + util._Buffer_from = util._Buffer_allocUnsafe = null; + return; + } + // because node 4.x buffers are incompatible & immutable + // see: https://github.com/dcodeIO/protobuf.js/pull/665 + util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from || + /* istanbul ignore next */ + function Buffer_from(value, encoding) { + return new Buffer(value, encoding); + }; + util._Buffer_allocUnsafe = Buffer.allocUnsafe || + /* istanbul ignore next */ + function Buffer_allocUnsafe(size) { + return new Buffer(size); + }; +}; diff --git a/node_modules/protobufjs/src/verifier.js b/node_modules/protobufjs/src/verifier.js new file mode 100644 index 0000000..d58e27a --- /dev/null +++ b/node_modules/protobufjs/src/verifier.js @@ -0,0 +1,177 @@ +"use strict"; +module.exports = verifier; + +var Enum = require("./enum"), + util = require("./util"); + +function invalid(field, expected) { + return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:"+field.keyType+"}" : "") + " expected"; +} + +/** + * Generates a partial value verifier. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {number} fieldIndex Field index + * @param {string} ref Variable reference + * @returns {Codegen} Codegen instance + * @ignore + */ +function genVerifyValue(gen, field, fieldIndex, ref) { + /* eslint-disable no-unexpected-multiline */ + if (field.resolvedType) { + if (field.resolvedType instanceof Enum) { gen + ("switch(%s){", ref) + ("default:") + ("return%j", invalid(field, "enum value")); + for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen + ("case %i:", field.resolvedType.values[keys[j]]); + gen + ("break") + ("}"); + } else { + gen + ("{") + ("var e=types[%i].verify(%s);", fieldIndex, ref) + ("if(e)") + ("return%j+e", field.name + ".") + ("}"); + } + } else { + switch (field.type) { + case "int32": + case "uint32": + case "sint32": + case "fixed32": + case "sfixed32": gen + ("if(!util.isInteger(%s))", ref) + ("return%j", invalid(field, "integer")); + break; + case "int64": + case "uint64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))", ref, ref, ref, ref) + ("return%j", invalid(field, "integer|Long")); + break; + case "float": + case "double": gen + ("if(typeof %s!==\"number\")", ref) + ("return%j", invalid(field, "number")); + break; + case "bool": gen + ("if(typeof %s!==\"boolean\")", ref) + ("return%j", invalid(field, "boolean")); + break; + case "string": gen + ("if(!util.isString(%s))", ref) + ("return%j", invalid(field, "string")); + break; + case "bytes": gen + ("if(!(%s&&typeof %s.length===\"number\"||util.isString(%s)))", ref, ref, ref) + ("return%j", invalid(field, "buffer")); + break; + } + } + return gen; + /* eslint-enable no-unexpected-multiline */ +} + +/** + * Generates a partial key verifier. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {string} ref Variable reference + * @returns {Codegen} Codegen instance + * @ignore + */ +function genVerifyKey(gen, field, ref) { + /* eslint-disable no-unexpected-multiline */ + switch (field.keyType) { + case "int32": + case "uint32": + case "sint32": + case "fixed32": + case "sfixed32": gen + ("if(!util.key32Re.test(%s))", ref) + ("return%j", invalid(field, "integer key")); + break; + case "int64": + case "uint64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(!util.key64Re.test(%s))", ref) // see comment above: x is ok, d is not + ("return%j", invalid(field, "integer|Long key")); + break; + case "bool": gen + ("if(!util.key2Re.test(%s))", ref) + ("return%j", invalid(field, "boolean key")); + break; + } + return gen; + /* eslint-enable no-unexpected-multiline */ +} + +/** + * Generates a verifier specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +function verifier(mtype) { + /* eslint-disable no-unexpected-multiline */ + + var gen = util.codegen(["m"], mtype.name + "$verify") + ("if(typeof m!==\"object\"||m===null)") + ("return%j", "object expected"); + var oneofs = mtype.oneofsArray, + seenFirstField = {}; + if (oneofs.length) gen + ("var p={}"); + + for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) { + var field = mtype._fieldsArray[i].resolve(), + ref = "m" + util.safeProp(field.name); + + if (field.optional) gen + ("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name); // !== undefined && !== null + + // map fields + if (field.map) { gen + ("if(!util.isObject(%s))", ref) + ("return%j", invalid(field, "object")) + ("var k=Object.keys(%s)", ref) + ("for(var i=0;i} + * @const + */ +var wrappers = exports; + +var Message = require("./message"); + +/** + * From object converter part of an {@link IWrapper}. + * @typedef WrapperFromObjectConverter + * @type {function} + * @param {Object.} object Plain object + * @returns {Message<{}>} Message instance + * @this Type + */ + +/** + * To object converter part of an {@link IWrapper}. + * @typedef WrapperToObjectConverter + * @type {function} + * @param {Message<{}>} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + * @this Type + */ + +/** + * Common type wrapper part of {@link wrappers}. + * @interface IWrapper + * @property {WrapperFromObjectConverter} [fromObject] From object converter + * @property {WrapperToObjectConverter} [toObject] To object converter + */ + +// Custom wrapper for Any +wrappers[".google.protobuf.Any"] = { + + fromObject: function(object) { + + // unwrap value type if mapped + if (object && object["@type"]) { + // Only use fully qualified type name after the last '/' + var name = object["@type"].substring(object["@type"].lastIndexOf("/") + 1); + var type = this.lookup(name); + /* istanbul ignore else */ + if (type) { + // type_url does not accept leading "." + var type_url = object["@type"].charAt(0) === "." ? + object["@type"].slice(1) : object["@type"]; + // type_url prefix is optional, but path seperator is required + if (type_url.indexOf("/") === -1) { + type_url = "/" + type_url; + } + return this.create({ + type_url: type_url, + value: type.encode(type.fromObject(object)).finish() + }); + } + } + + return this.fromObject(object); + }, + + toObject: function(message, options) { + + // Default prefix + var googleApi = "type.googleapis.com/"; + var prefix = ""; + var name = ""; + + // decode value if requested and unmapped + if (options && options.json && message.type_url && message.value) { + // Only use fully qualified type name after the last '/' + name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1); + // Separate the prefix used + prefix = message.type_url.substring(0, message.type_url.lastIndexOf("/") + 1); + var type = this.lookup(name); + /* istanbul ignore else */ + if (type) + message = type.decode(message.value); + } + + // wrap value if unmapped + if (!(message instanceof this.ctor) && message instanceof Message) { + var object = message.$type.toObject(message, options); + var messageName = message.$type.fullName[0] === "." ? + message.$type.fullName.slice(1) : message.$type.fullName; + // Default to type.googleapis.com prefix if no prefix is used + if (prefix === "") { + prefix = googleApi; + } + name = prefix + messageName; + object["@type"] = name; + return object; + } + + return this.toObject(message, options); + } +}; diff --git a/node_modules/protobufjs/src/writer.js b/node_modules/protobufjs/src/writer.js new file mode 100644 index 0000000..cc84a00 --- /dev/null +++ b/node_modules/protobufjs/src/writer.js @@ -0,0 +1,465 @@ +"use strict"; +module.exports = Writer; + +var util = require("./util/minimal"); + +var BufferWriter; // cyclic + +var LongBits = util.LongBits, + base64 = util.base64, + utf8 = util.utf8; + +/** + * Constructs a new writer operation instance. + * @classdesc Scheduled writer operation. + * @constructor + * @param {function(*, Uint8Array, number)} fn Function to call + * @param {number} len Value byte length + * @param {*} val Value to write + * @ignore + */ +function Op(fn, len, val) { + + /** + * Function to call. + * @type {function(Uint8Array, number, *)} + */ + this.fn = fn; + + /** + * Value byte length. + * @type {number} + */ + this.len = len; + + /** + * Next operation. + * @type {Writer.Op|undefined} + */ + this.next = undefined; + + /** + * Value to write. + * @type {*} + */ + this.val = val; // type varies +} + +/* istanbul ignore next */ +function noop() {} // eslint-disable-line no-empty-function + +/** + * Constructs a new writer state instance. + * @classdesc Copied writer state. + * @memberof Writer + * @constructor + * @param {Writer} writer Writer to copy state from + * @ignore + */ +function State(writer) { + + /** + * Current head. + * @type {Writer.Op} + */ + this.head = writer.head; + + /** + * Current tail. + * @type {Writer.Op} + */ + this.tail = writer.tail; + + /** + * Current buffer length. + * @type {number} + */ + this.len = writer.len; + + /** + * Next state. + * @type {State|null} + */ + this.next = writer.states; +} + +/** + * Constructs a new writer instance. + * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`. + * @constructor + */ +function Writer() { + + /** + * Current length. + * @type {number} + */ + this.len = 0; + + /** + * Operations head. + * @type {Object} + */ + this.head = new Op(noop, 0, 0); + + /** + * Operations tail + * @type {Object} + */ + this.tail = this.head; + + /** + * Linked forked states. + * @type {Object|null} + */ + this.states = null; + + // When a value is written, the writer calculates its byte length and puts it into a linked + // list of operations to perform when finish() is called. This both allows us to allocate + // buffers of the exact required size and reduces the amount of work we have to do compared + // to first calculating over objects and then encoding over objects. In our case, the encoding + // part is just a linked list walk calling operations with already prepared values. +} + +var create = function create() { + return util.Buffer + ? function create_buffer_setup() { + return (Writer.create = function create_buffer() { + return new BufferWriter(); + })(); + } + /* istanbul ignore next */ + : function create_array() { + return new Writer(); + }; +}; + +/** + * Creates a new writer. + * @function + * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer} + */ +Writer.create = create(); + +/** + * Allocates a buffer of the specified size. + * @param {number} size Buffer size + * @returns {Uint8Array} Buffer + */ +Writer.alloc = function alloc(size) { + return new util.Array(size); +}; + +// Use Uint8Array buffer pool in the browser, just like node does with buffers +/* istanbul ignore else */ +if (util.Array !== Array) + Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray); + +/** + * Pushes a new operation to the queue. + * @param {function(Uint8Array, number, *)} fn Function to call + * @param {number} len Value byte length + * @param {number} val Value to write + * @returns {Writer} `this` + * @private + */ +Writer.prototype._push = function push(fn, len, val) { + this.tail = this.tail.next = new Op(fn, len, val); + this.len += len; + return this; +}; + +function writeByte(val, buf, pos) { + buf[pos] = val & 255; +} + +function writeVarint32(val, buf, pos) { + while (val > 127) { + buf[pos++] = val & 127 | 128; + val >>>= 7; + } + buf[pos] = val; +} + +/** + * Constructs a new varint writer operation instance. + * @classdesc Scheduled varint writer operation. + * @extends Op + * @constructor + * @param {number} len Value byte length + * @param {number} val Value to write + * @ignore + */ +function VarintOp(len, val) { + this.len = len; + this.next = undefined; + this.val = val; +} + +VarintOp.prototype = Object.create(Op.prototype); +VarintOp.prototype.fn = writeVarint32; + +/** + * Writes an unsigned 32 bit value as a varint. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.uint32 = function write_uint32(value) { + // here, the call to this.push has been inlined and a varint specific Op subclass is used. + // uint32 is by far the most frequently used operation and benefits significantly from this. + this.len += (this.tail = this.tail.next = new VarintOp( + (value = value >>> 0) + < 128 ? 1 + : value < 16384 ? 2 + : value < 2097152 ? 3 + : value < 268435456 ? 4 + : 5, + value)).len; + return this; +}; + +/** + * Writes a signed 32 bit value as a varint. + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.int32 = function write_int32(value) { + return value < 0 + ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec + : this.uint32(value); +}; + +/** + * Writes a 32 bit value as a varint, zig-zag encoded. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.sint32 = function write_sint32(value) { + return this.uint32((value << 1 ^ value >> 31) >>> 0); +}; + +function writeVarint64(val, buf, pos) { + while (val.hi) { + buf[pos++] = val.lo & 127 | 128; + val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; + val.hi >>>= 7; + } + while (val.lo > 127) { + buf[pos++] = val.lo & 127 | 128; + val.lo = val.lo >>> 7; + } + buf[pos++] = val.lo; +} + +/** + * Writes an unsigned 64 bit value as a varint. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.uint64 = function write_uint64(value) { + var bits = LongBits.from(value); + return this._push(writeVarint64, bits.length(), bits); +}; + +/** + * Writes a signed 64 bit value as a varint. + * @function + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.int64 = Writer.prototype.uint64; + +/** + * Writes a signed 64 bit value as a varint, zig-zag encoded. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.sint64 = function write_sint64(value) { + var bits = LongBits.from(value).zzEncode(); + return this._push(writeVarint64, bits.length(), bits); +}; + +/** + * Writes a boolish value as a varint. + * @param {boolean} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.bool = function write_bool(value) { + return this._push(writeByte, 1, value ? 1 : 0); +}; + +function writeFixed32(val, buf, pos) { + buf[pos ] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; +} + +/** + * Writes an unsigned 32 bit value as fixed 32 bits. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.fixed32 = function write_fixed32(value) { + return this._push(writeFixed32, 4, value >>> 0); +}; + +/** + * Writes a signed 32 bit value as fixed 32 bits. + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.sfixed32 = Writer.prototype.fixed32; + +/** + * Writes an unsigned 64 bit value as fixed 64 bits. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.fixed64 = function write_fixed64(value) { + var bits = LongBits.from(value); + return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); +}; + +/** + * Writes a signed 64 bit value as fixed 64 bits. + * @function + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.sfixed64 = Writer.prototype.fixed64; + +/** + * Writes a float (32 bit). + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.float = function write_float(value) { + return this._push(util.float.writeFloatLE, 4, value); +}; + +/** + * Writes a double (64 bit float). + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.double = function write_double(value) { + return this._push(util.float.writeDoubleLE, 8, value); +}; + +var writeBytes = util.Array.prototype.set + ? function writeBytes_set(val, buf, pos) { + buf.set(val, pos); // also works for plain array values + } + /* istanbul ignore next */ + : function writeBytes_for(val, buf, pos) { + for (var i = 0; i < val.length; ++i) + buf[pos + i] = val[i]; + }; + +/** + * Writes a sequence of bytes. + * @param {Uint8Array|string} value Buffer or base64 encoded string to write + * @returns {Writer} `this` + */ +Writer.prototype.bytes = function write_bytes(value) { + var len = value.length >>> 0; + if (!len) + return this._push(writeByte, 1, 0); + if (util.isString(value)) { + var buf = Writer.alloc(len = base64.length(value)); + base64.decode(value, buf, 0); + value = buf; + } + return this.uint32(len)._push(writeBytes, len, value); +}; + +/** + * Writes a string. + * @param {string} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.string = function write_string(value) { + var len = utf8.length(value); + return len + ? this.uint32(len)._push(utf8.write, len, value) + : this._push(writeByte, 1, 0); +}; + +/** + * Forks this writer's state by pushing it to a stack. + * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state. + * @returns {Writer} `this` + */ +Writer.prototype.fork = function fork() { + this.states = new State(this); + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + return this; +}; + +/** + * Resets this instance to the last state. + * @returns {Writer} `this` + */ +Writer.prototype.reset = function reset() { + if (this.states) { + this.head = this.states.head; + this.tail = this.states.tail; + this.len = this.states.len; + this.states = this.states.next; + } else { + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + } + return this; +}; + +/** + * Resets to the last state and appends the fork state's current write length as a varint followed by its operations. + * @returns {Writer} `this` + */ +Writer.prototype.ldelim = function ldelim() { + var head = this.head, + tail = this.tail, + len = this.len; + this.reset().uint32(len); + if (len) { + this.tail.next = head.next; // skip noop + this.tail = tail; + this.len += len; + } + return this; +}; + +/** + * Finishes the write operation. + * @returns {Uint8Array} Finished buffer + */ +Writer.prototype.finish = function finish() { + var head = this.head.next, // skip noop + buf = this.constructor.alloc(this.len), + pos = 0; + while (head) { + head.fn(head.val, buf, pos); + pos += head.len; + head = head.next; + } + // this.head = this.tail = null; + return buf; +}; + +Writer._configure = function(BufferWriter_) { + BufferWriter = BufferWriter_; + Writer.create = create(); + BufferWriter._configure(); +}; diff --git a/node_modules/protobufjs/src/writer_buffer.js b/node_modules/protobufjs/src/writer_buffer.js new file mode 100644 index 0000000..09a4a91 --- /dev/null +++ b/node_modules/protobufjs/src/writer_buffer.js @@ -0,0 +1,85 @@ +"use strict"; +module.exports = BufferWriter; + +// extends Writer +var Writer = require("./writer"); +(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; + +var util = require("./util/minimal"); + +/** + * Constructs a new buffer writer instance. + * @classdesc Wire format writer using node buffers. + * @extends Writer + * @constructor + */ +function BufferWriter() { + Writer.call(this); +} + +BufferWriter._configure = function () { + /** + * Allocates a buffer of the specified size. + * @function + * @param {number} size Buffer size + * @returns {Buffer} Buffer + */ + BufferWriter.alloc = util._Buffer_allocUnsafe; + + BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set" + ? function writeBytesBuffer_set(val, buf, pos) { + buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited) + // also works for plain array values + } + /* istanbul ignore next */ + : function writeBytesBuffer_copy(val, buf, pos) { + if (val.copy) // Buffer values + val.copy(buf, pos, 0, val.length); + else for (var i = 0; i < val.length;) // plain array values + buf[pos++] = val[i++]; + }; +}; + + +/** + * @override + */ +BufferWriter.prototype.bytes = function write_bytes_buffer(value) { + if (util.isString(value)) + value = util._Buffer_from(value, "base64"); + var len = value.length >>> 0; + this.uint32(len); + if (len) + this._push(BufferWriter.writeBytesBuffer, len, value); + return this; +}; + +function writeStringBuffer(val, buf, pos) { + if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions) + util.utf8.write(val, buf, pos); + else if (buf.utf8Write) + buf.utf8Write(val, pos); + else + buf.write(val, pos); +} + +/** + * @override + */ +BufferWriter.prototype.string = function write_string_buffer(value) { + var len = util.Buffer.byteLength(value); + this.uint32(len); + if (len) + this._push(writeStringBuffer, len, value); + return this; +}; + + +/** + * Finishes the write operation. + * @name BufferWriter#finish + * @function + * @returns {Buffer} Finished buffer + */ + +BufferWriter._configure(); diff --git a/node_modules/protobufjs/tsconfig.json b/node_modules/protobufjs/tsconfig.json new file mode 100644 index 0000000..a0b3639 --- /dev/null +++ b/node_modules/protobufjs/tsconfig.json @@ -0,0 +1,8 @@ +{ + "compilerOptions": { + "target": "ES5", + "experimentalDecorators": true, + "emitDecoratorMetadata": true, + "esModuleInterop": true, + } +} \ No newline at end of file diff --git a/node_modules/readable-stream/CONTRIBUTING.md b/node_modules/readable-stream/CONTRIBUTING.md new file mode 100644 index 0000000..f478d58 --- /dev/null +++ b/node_modules/readable-stream/CONTRIBUTING.md @@ -0,0 +1,38 @@ +# Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +* (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +* (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +* (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. + +## Moderation Policy + +The [Node.js Moderation Policy] applies to this WG. + +## Code of Conduct + +The [Node.js Code of Conduct][] applies to this WG. + +[Node.js Code of Conduct]: +https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md +[Node.js Moderation Policy]: +https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md diff --git a/node_modules/readable-stream/GOVERNANCE.md b/node_modules/readable-stream/GOVERNANCE.md new file mode 100644 index 0000000..16ffb93 --- /dev/null +++ b/node_modules/readable-stream/GOVERNANCE.md @@ -0,0 +1,136 @@ +### Streams Working Group + +The Node.js Streams is jointly governed by a Working Group +(WG) +that is responsible for high-level guidance of the project. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Conduct guidelines +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project +[README.md](./README.md#current-project-team-members). + +### Collaborators + +The readable-stream GitHub repository is +maintained by the WG and additional Collaborators who are added by the +WG on an ongoing basis. + +Individuals making significant and valuable contributions are made +Collaborators and given commit-access to the project. These +individuals are identified by the WG and their addition as +Collaborators is discussed during the WG meeting. + +_Note:_ If you make a significant contribution and are not considered +for commit-access log an issue or contact a WG member directly and it +will be brought up in the next WG meeting. + +Modifications of the contents of the readable-stream repository are +made on +a collaborative basis. Anybody with a GitHub account may propose a +modification via pull request and it will be considered by the project +Collaborators. All pull requests must be reviewed and accepted by a +Collaborator with sufficient expertise who is able to take full +responsibility for the change. In the case of pull requests proposed +by an existing Collaborator, an additional Collaborator is required +for sign-off. Consensus should be sought if additional Collaborators +participate and there is disagreement around a particular +modification. See _Consensus Seeking Process_ below for further detail +on the consensus model used for governance. + +Collaborators may opt to elevate significant or controversial +modifications, or modifications that have not found consensus to the +WG for discussion by assigning the ***WG-agenda*** tag to a pull +request or issue. The WG should serve as the final arbiter where +required. + +For the current list of Collaborators, see the project +[README.md](./README.md#members). + +### WG Membership + +WG seats are not time-limited. There is no fixed size of the WG. +However, the expected target is between 6 and 12, to ensure adequate +coverage of important areas of expertise, balanced with the ability to +make decisions efficiently. + +There is no specific set of requirements or qualifications for WG +membership beyond these rules. + +The WG may add additional members to the WG by unanimous consensus. + +A WG member may be removed from the WG by voluntary resignation, or by +unanimous consensus of all other WG members. + +Changes to WG membership should be posted in the agenda, and may be +suggested as any other agenda item (see "WG Meetings" below). + +If an addition or removal is proposed during a meeting, and the full +WG is not in attendance to participate, then the addition or removal +is added to the agenda for the subsequent meeting. This is to ensure +that all members are given the opportunity to participate in all +membership decisions. If a WG member is unable to attend a meeting +where a planned membership decision is being made, then their consent +is assumed. + +No more than 1/3 of the WG members may be affiliated with the same +employer. If removal or resignation of a WG member, or a change of +employment by a WG member, creates a situation where more than 1/3 of +the WG membership shares an employer, then the situation must be +immediately remedied by the resignation or removal of one or more WG +members affiliated with the over-represented employer(s). + +### WG Meetings + +The WG meets occasionally on a Google Hangout On Air. A designated moderator +approved by the WG runs the meeting. Each meeting should be +published to YouTube. + +Items are added to the WG agenda that are considered contentious or +are modifications of governance, contribution policy, WG membership, +or release process. + +The intention of the agenda is not to approve or review all patches; +that should happen continuously on GitHub and be handled by the larger +group of Collaborators. + +Any community member or contributor can ask that something be added to +the next meeting's agenda by logging a GitHub Issue. Any Collaborator, +WG member or the moderator can add the item to the agenda by adding +the ***WG-agenda*** tag to the issue. + +Prior to each WG meeting the moderator will share the Agenda with +members of the WG. WG members can add any items they like to the +agenda at the beginning of each meeting. The moderator and the WG +cannot veto or remove items. + +The WG may invite persons or representatives from certain projects to +participate in a non-voting capacity. + +The moderator is responsible for summarizing the discussion of each +agenda item and sends it as a pull request after the meeting. + +### Consensus Seeking Process + +The WG follows a +[Consensus +Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) +decision-making model. + +When an agenda item has appeared to reach a consensus the moderator +will ask "Does anyone object?" as a final call for dissent from the +consensus. + +If an agenda item cannot reach a consensus a WG member can call for +either a closing vote or a vote to table the issue to the next +meeting. The call for a vote must be seconded by a majority of the WG +or else the discussion will continue. Simple majority wins. + +Note that changes to WG membership require a majority consensus. See +"WG Membership" above. diff --git a/node_modules/readable-stream/LICENSE b/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000..2873b3b --- /dev/null +++ b/node_modules/readable-stream/LICENSE @@ -0,0 +1,47 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" diff --git a/node_modules/readable-stream/README.md b/node_modules/readable-stream/README.md new file mode 100644 index 0000000..19117c1 --- /dev/null +++ b/node_modules/readable-stream/README.md @@ -0,0 +1,106 @@ +# readable-stream + +***Node.js core streams for userland*** [![Build Status](https://travis-ci.com/nodejs/readable-stream.svg?branch=master)](https://travis-ci.com/nodejs/readable-stream) + + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) + + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/readabe-stream.svg)](https://saucelabs.com/u/readabe-stream) + +```bash +npm install --save readable-stream +``` + +This package is a mirror of the streams implementations in Node.js. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.18.1/docs/api/stream.html). + +If you want to guarantee a stable streams base, regardless of what version of +Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). + +As of version 2.0.0 **readable-stream** uses semantic versioning. + +## Version 3.x.x + +v3.x.x of `readable-stream` is a cut from Node 10. This version supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows: + +1. Error codes: https://github.com/nodejs/node/pull/13310, + https://github.com/nodejs/node/pull/13291, + https://github.com/nodejs/node/pull/16589, + https://github.com/nodejs/node/pull/15042, + https://github.com/nodejs/node/pull/15665, + https://github.com/nodejs/readable-stream/pull/344 +2. 'readable' have precedence over flowing + https://github.com/nodejs/node/pull/18994 +3. make virtual methods errors consistent + https://github.com/nodejs/node/pull/18813 +4. updated streams error handling + https://github.com/nodejs/node/pull/18438 +5. writable.end should return this. + https://github.com/nodejs/node/pull/18780 +6. readable continues to read when push('') + https://github.com/nodejs/node/pull/18211 +7. add custom inspect to BufferList + https://github.com/nodejs/node/pull/17907 +8. always defer 'readable' with nextTick + https://github.com/nodejs/node/pull/17979 + +## Version 2.x.x +v2.x.x of `readable-stream` is a cut of the stream module from Node 8 (there have been no semver-major changes from Node 4 to 8). This version supports all Node.js versions from 0.8, as well as evergreen browsers and IE 10 & 11. + +### Big Thanks + +Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce] + +# Usage + +You can swap your `require('stream')` with `require('readable-stream')` +without any changes, if you are just using one of the main classes and +functions. + +```js +const { + Readable, + Writable, + Transform, + Duplex, + pipeline, + finished +} = require('readable-stream') +```` + +Note that `require('stream')` will return `Stream`, while +`require('readable-stream')` will return `Readable`. We discourage using +whatever is exported directly, but rather use one of the properties as +shown in the example above. + +# Streams Working Group + +`readable-stream` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + + +## Team Members + +* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com> + - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 +* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com> +* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <matteo.collina@gmail.com> + - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E +* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <shestak.irina@gmail.com> +* **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) <yoshuawuyts@gmail.com> + +[sauce]: https://saucelabs.com diff --git a/node_modules/readable-stream/errors-browser.js b/node_modules/readable-stream/errors-browser.js new file mode 100644 index 0000000..fb8e73e --- /dev/null +++ b/node_modules/readable-stream/errors-browser.js @@ -0,0 +1,127 @@ +'use strict'; + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +var codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); + + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } + + return NodeError; + }(Base); + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; +} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + + +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith + + +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + + +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + + return str.substring(this_len - search.length, this_len) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + + +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; + + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + var msg; + + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } + + msg += ". Received type ".concat(typeof actual); + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg; +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); +module.exports.codes = codes; diff --git a/node_modules/readable-stream/errors.js b/node_modules/readable-stream/errors.js new file mode 100644 index 0000000..8471526 --- /dev/null +++ b/node_modules/readable-stream/errors.js @@ -0,0 +1,116 @@ +'use strict'; + +const codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error + } + + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } + + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; +} + +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } + + msg += `. Received type ${typeof actual}`; + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + +module.exports.codes = codes; diff --git a/node_modules/readable-stream/experimentalWarning.js b/node_modules/readable-stream/experimentalWarning.js new file mode 100644 index 0000000..78e8414 --- /dev/null +++ b/node_modules/readable-stream/experimentalWarning.js @@ -0,0 +1,17 @@ +'use strict' + +var experimentalWarnings = new Set(); + +function emitExperimentalWarning(feature) { + if (experimentalWarnings.has(feature)) return; + var msg = feature + ' is an experimental feature. This feature could ' + + 'change at any time'; + experimentalWarnings.add(feature); + process.emitWarning(msg, 'ExperimentalWarning'); +} + +function noop() {} + +module.exports.emitExperimentalWarning = process.emitWarning + ? emitExperimentalWarning + : noop; diff --git a/node_modules/readable-stream/lib/_stream_duplex.js b/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 0000000..19abfa6 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,126 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +}; +/**/ + +module.exports = Duplex; +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); +require('inherits')(Duplex, Readable); +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } +} +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); + +// the no-half-open enforcer +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(onEndNT, this); +} +function onEndNT(self) { + self.end(); +} +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_passthrough.js b/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 0000000..24a6bdd --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,37 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; +var Transform = require('./_stream_transform'); +require('inherits')(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_readable.js b/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 0000000..df1f608 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,1027 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +module.exports = Readable; + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = require('events').EventEmitter; +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +var Buffer = require('buffer').Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ +var debugUtil = require('util'); +var debug; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ + +var BufferList = require('./internal/streams/buffer_list'); +var destroyImpl = require('./internal/streams/destroy'); +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + +// Lazy loaded to improve the startup performance. +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; +require('inherits')(Readable, Stream); +var errorOrDestroy = destroyImpl.errorOrDestroy; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'end' (and potentially 'finish') + this.autoDestroy = !!options.autoDestroy; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + if (!(this instanceof Readable)) return new Readable(options); + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); + + // legacy + this.readable = true; + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + Stream.call(this); +} +Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } + + // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + return !state.ended && (state.length < state.highWaterMark || state.length === 0); +} +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + return er; +} +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; + // If setEncoding(null), decoder.encoding equals utf8 + this._readableState.encoding = this._readableState.decoder.encoding; + + // Iterate over current buffer to convert already stored Buffers: + var p = this._readableState.buffer.head; + var content = ''; + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + this._readableState.buffer.clear(); + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; +}; + +// Don't raise the hwm > 1GB +var MAX_HWM = 0x40000000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + if (ret !== null) this.emit('data', ret); + return ret; +}; +function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } +} +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } + + // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } +} +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + return dest; +}; +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; + + // Try start flowing on next tick if stream isn't explicitly paused + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; + + // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } +} +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + state.flowing = !state.readableListening; + resume(this, state); + } + state.paused = false; + return this; +}; +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } +} +function resume_(stream, state) { + debug('resume', state.reading); + if (!state.reading) { + stream.read(0); + } + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + this._readableState.paused = true; + return this; +}; +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null); +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + return this; +}; +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); + } + return createReadableStreamAsyncIterator(this); + }; +} +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } +}); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } +}); + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; +} +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } +} +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); + + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } +} +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = require('./internal/streams/from'); + } + return from(Readable, iterable, opts); + }; +} +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_transform.js b/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 0000000..1ccb715 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,190 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; +var _require$codes = require('../errors').codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; +var Duplex = require('./_stream_duplex'); +require('inherits')(Transform, Duplex); +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + ts.writechunk = null; + ts.writecb = null; + if (data != null) + // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} +function prefinish() { + var _this = this; + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) + // single equals check for both `null` and `undefined` + stream.push(data); + + // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); +} \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_writable.js b/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 0000000..292415e --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,641 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +var Buffer = require('buffer').Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +var destroyImpl = require('./internal/streams/destroy'); +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; +var errorOrDestroy = destroyImpl.errorOrDestroy; +require('inherits')(Writable, Stream); +function nop() {} +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'finish' (and potentially 'end') + this.autoDestroy = !!options.autoDestroy; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); + + // legacy. + this.writable = true; + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); +}; +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); + // TODO: defer error events consistently everywhere, not just the cb + errorOrDestroy(stream, er); + process.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var er; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); + } + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + return true; +} +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; +}; +Writable.prototype.cork = function () { + this._writableState.corked++; +}; +Writable.prototype.uncork = function () { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + return ret; +} +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } +} +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + if (entry === null) state.lastBufferedRequest = null; + } + state.bufferedRequest = entry; + state.bufferProcessing = false; +} +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; +Writable.prototype._writev = null; +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending) endWritable(this, state, cb); + return this; +}; +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + errorOrDestroy(stream, err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + return need; +} +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + + // reuse the free corkReq. + state.corkedRequestsFree.next = corkReq; +} +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/async_iterator.js b/node_modules/readable-stream/lib/internal/streams/async_iterator.js new file mode 100644 index 0000000..742c5a4 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/async_iterator.js @@ -0,0 +1,180 @@ +'use strict'; + +var _Object$setPrototypeO; +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var finished = require('./end-of-stream'); +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data = iter[kStream].read(); + // we defer if data is null + // we can be expecting either 'end' or + // 'error' + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } +} +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); + }; +} +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + if (error !== null) { + return Promise.reject(error); + } + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } + + // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + var lastPromise = this[kLastPromise]; + var promise; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + promise = new Promise(this[kHandlePromise]); + } + this[kLastPromise] = promise; + return promise; + } +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; + // reject if we are waiting for data in the Promise + // returned by next() and store the error + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + iterator[kError] = err; + return; + } + var resolve = iterator[kLastResolve]; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; +}; +module.exports = createReadableStreamAsyncIterator; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/buffer_list.js b/node_modules/readable-stream/lib/internal/streams/buffer_list.js new file mode 100644 index 0000000..69bda49 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/buffer_list.js @@ -0,0 +1,183 @@ +'use strict'; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var _require = require('buffer'), + Buffer = _require.Buffer; +var _require2 = require('util'), + inspect = _require2.inspect; +var custom = inspect && inspect.custom || 'inspect'; +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} +module.exports = /*#__PURE__*/function () { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) ret += s + p.data; + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + } + + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread(_objectSpread({}, options), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; +}(); \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/destroy.js b/node_modules/readable-stream/lib/internal/streams/destroy.js new file mode 100644 index 0000000..31a17c4 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/destroy.js @@ -0,0 +1,96 @@ +'use strict'; + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + return this; +} +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} +function emitErrorNT(self, err) { + self.emit('error', err); +} +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/end-of-stream.js b/node_modules/readable-stream/lib/internal/streams/end-of-stream.js new file mode 100644 index 0000000..59c671b --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/end-of-stream.js @@ -0,0 +1,86 @@ +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict'; + +var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + callback.apply(this, args); + }; +} +function noop() {} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + var writableEnded = stream._writableState && stream._writableState.finished; + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + var readableEnded = stream._readableState && stream._readableState.endEmitted; + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + var onerror = function onerror(err) { + callback.call(stream, err); + }; + var onclose = function onclose() { + var err; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} +module.exports = eos; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/from-browser.js b/node_modules/readable-stream/lib/internal/streams/from-browser.js new file mode 100644 index 0000000..a4ce56f --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/from-browser.js @@ -0,0 +1,3 @@ +module.exports = function () { + throw new Error('Readable.from is not available in the browser') +}; diff --git a/node_modules/readable-stream/lib/internal/streams/from.js b/node_modules/readable-stream/lib/internal/streams/from.js new file mode 100644 index 0000000..0a34ee9 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/from.js @@ -0,0 +1,52 @@ +'use strict'; + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE; +function from(Readable, iterable, opts) { + var iterator; + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); + // Reading boolean to protect against _read + // being called before last iteration completion. + var reading = false; + readable._read = function () { + if (!reading) { + reading = true; + next(); + } + }; + function next() { + return _next2.apply(this, arguments); + } + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _yield$iterator$next = yield iterator.next(), + value = _yield$iterator$next.value, + done = _yield$iterator$next.done; + if (done) { + readable.push(null); + } else if (readable.push(yield value)) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + return readable; +} +module.exports = from; diff --git a/node_modules/readable-stream/lib/internal/streams/pipeline.js b/node_modules/readable-stream/lib/internal/streams/pipeline.js new file mode 100644 index 0000000..e6f3924 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/pipeline.js @@ -0,0 +1,86 @@ +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict'; + +var eos; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} +var _require$codes = require('../../../errors').codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = require('./end-of-stream'); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; + + // request.destroy just do .end - .abort is what we want + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} +function call(fn) { + fn(); +} +function pipe(from, to) { + return from.pipe(to); +} +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); +} +module.exports = pipeline; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/state.js b/node_modules/readable-stream/lib/internal/streams/state.js new file mode 100644 index 0000000..3fbf892 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/state.js @@ -0,0 +1,22 @@ +'use strict'; + +var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } + + // Default value + return state.objectMode ? 16 : 16 * 1024; +} +module.exports = { + getHighWaterMark: getHighWaterMark +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/stream-browser.js b/node_modules/readable-stream/lib/internal/streams/stream-browser.js new file mode 100644 index 0000000..9332a3f --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/stream-browser.js @@ -0,0 +1 @@ +module.exports = require('events').EventEmitter; diff --git a/node_modules/readable-stream/lib/internal/streams/stream.js b/node_modules/readable-stream/lib/internal/streams/stream.js new file mode 100644 index 0000000..ce2ad5b --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/stream.js @@ -0,0 +1 @@ +module.exports = require('stream'); diff --git a/node_modules/readable-stream/package.json b/node_modules/readable-stream/package.json new file mode 100644 index 0000000..ade59e7 --- /dev/null +++ b/node_modules/readable-stream/package.json @@ -0,0 +1,68 @@ +{ + "name": "readable-stream", + "version": "3.6.2", + "description": "Streams3, a user-land copy of the stream library from Node.js", + "main": "readable.js", + "engines": { + "node": ">= 6" + }, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "devDependencies": { + "@babel/cli": "^7.2.0", + "@babel/core": "^7.2.0", + "@babel/polyfill": "^7.0.0", + "@babel/preset-env": "^7.2.0", + "airtap": "0.0.9", + "assert": "^1.4.0", + "bl": "^2.0.0", + "deep-strict-equal": "^0.2.0", + "events.once": "^2.0.2", + "glob": "^7.1.2", + "gunzip-maybe": "^1.4.1", + "hyperquest": "^2.1.3", + "lolex": "^2.6.0", + "nyc": "^11.0.0", + "pump": "^3.0.0", + "rimraf": "^2.6.2", + "tap": "^12.0.0", + "tape": "^4.9.0", + "tar-fs": "^1.16.2", + "util-promisify": "^2.1.0" + }, + "scripts": { + "test": "tap -J --no-esm test/parallel/*.js test/ours/*.js", + "ci": "TAP=1 tap --no-esm test/parallel/*.js test/ours/*.js | tee test.tap", + "test-browsers": "airtap --sauce-connect --loopback airtap.local -- test/browser.js", + "test-browser-local": "airtap --open --local -- test/browser.js", + "cover": "nyc npm test", + "report": "nyc report --reporter=lcov", + "update-browser-errors": "babel -o errors-browser.js errors.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/readable-stream" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false, + "worker_threads": false, + "./errors": "./errors-browser.js", + "./readable.js": "./readable-browser.js", + "./lib/internal/streams/from.js": "./lib/internal/streams/from-browser.js", + "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js" + }, + "nyc": { + "include": [ + "lib/**.js" + ] + }, + "license": "MIT" +} diff --git a/node_modules/readable-stream/readable-browser.js b/node_modules/readable-stream/readable-browser.js new file mode 100644 index 0000000..adbf60d --- /dev/null +++ b/node_modules/readable-stream/readable-browser.js @@ -0,0 +1,9 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); +exports.finished = require('./lib/internal/streams/end-of-stream.js'); +exports.pipeline = require('./lib/internal/streams/pipeline.js'); diff --git a/node_modules/readable-stream/readable.js b/node_modules/readable-stream/readable.js new file mode 100644 index 0000000..9e0ca12 --- /dev/null +++ b/node_modules/readable-stream/readable.js @@ -0,0 +1,16 @@ +var Stream = require('stream'); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; +} else { + exports = module.exports = require('./lib/_stream_readable.js'); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = require('./lib/_stream_writable.js'); + exports.Duplex = require('./lib/_stream_duplex.js'); + exports.Transform = require('./lib/_stream_transform.js'); + exports.PassThrough = require('./lib/_stream_passthrough.js'); + exports.finished = require('./lib/internal/streams/end-of-stream.js'); + exports.pipeline = require('./lib/internal/streams/pipeline.js'); +} diff --git a/node_modules/require-directory/.jshintrc b/node_modules/require-directory/.jshintrc new file mode 100644 index 0000000..e14e4dc --- /dev/null +++ b/node_modules/require-directory/.jshintrc @@ -0,0 +1,67 @@ +{ + "maxerr" : 50, + "bitwise" : true, + "camelcase" : true, + "curly" : true, + "eqeqeq" : true, + "forin" : true, + "immed" : true, + "indent" : 2, + "latedef" : true, + "newcap" : true, + "noarg" : true, + "noempty" : true, + "nonew" : true, + "plusplus" : true, + "quotmark" : true, + "undef" : true, + "unused" : true, + "strict" : true, + "trailing" : true, + "maxparams" : false, + "maxdepth" : false, + "maxstatements" : false, + "maxcomplexity" : false, + "maxlen" : false, + "asi" : false, + "boss" : false, + "debug" : false, + "eqnull" : true, + "es5" : false, + "esnext" : false, + "moz" : false, + "evil" : false, + "expr" : true, + "funcscope" : true, + "globalstrict" : true, + "iterator" : true, + "lastsemic" : false, + "laxbreak" : false, + "laxcomma" : false, + "loopfunc" : false, + "multistr" : false, + "proto" : false, + "scripturl" : false, + "smarttabs" : false, + "shadow" : false, + "sub" : false, + "supernew" : false, + "validthis" : false, + "browser" : true, + "couch" : false, + "devel" : true, + "dojo" : false, + "jquery" : false, + "mootools" : false, + "node" : true, + "nonstandard" : false, + "prototypejs" : false, + "rhino" : false, + "worker" : false, + "wsh" : false, + "yui" : false, + "nomen" : true, + "onevar" : true, + "passfail" : false, + "white" : true +} diff --git a/node_modules/require-directory/.npmignore b/node_modules/require-directory/.npmignore new file mode 100644 index 0000000..47cf365 --- /dev/null +++ b/node_modules/require-directory/.npmignore @@ -0,0 +1 @@ +test/** diff --git a/node_modules/require-directory/.travis.yml b/node_modules/require-directory/.travis.yml new file mode 100644 index 0000000..20fd86b --- /dev/null +++ b/node_modules/require-directory/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - 0.10 diff --git a/node_modules/require-directory/LICENSE b/node_modules/require-directory/LICENSE new file mode 100644 index 0000000..a70f253 --- /dev/null +++ b/node_modules/require-directory/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2011 Troy Goode + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/require-directory/README.markdown b/node_modules/require-directory/README.markdown new file mode 100644 index 0000000..926a063 --- /dev/null +++ b/node_modules/require-directory/README.markdown @@ -0,0 +1,184 @@ +# require-directory + +Recursively iterates over specified directory, `require()`'ing each file, and returning a nested hash structure containing those modules. + +**[Follow me (@troygoode) on Twitter!](https://twitter.com/intent/user?screen_name=troygoode)** + +[![NPM](https://nodei.co/npm/require-directory.png?downloads=true&stars=true)](https://nodei.co/npm/require-directory/) + +[![build status](https://secure.travis-ci.org/troygoode/node-require-directory.png)](http://travis-ci.org/troygoode/node-require-directory) + +## How To Use + +### Installation (via [npm](https://npmjs.org/package/require-directory)) + +```bash +$ npm install require-directory +``` + +### Usage + +A common pattern in node.js is to include an index file which creates a hash of the files in its current directory. Given a directory structure like so: + +* app.js +* routes/ + * index.js + * home.js + * auth/ + * login.js + * logout.js + * register.js + +`routes/index.js` uses `require-directory` to build the hash (rather than doing so manually) like so: + +```javascript +var requireDirectory = require('require-directory'); +module.exports = requireDirectory(module); +``` + +`app.js` references `routes/index.js` like any other module, but it now has a hash/tree of the exports from the `./routes/` directory: + +```javascript +var routes = require('./routes'); + +// snip + +app.get('/', routes.home); +app.get('/register', routes.auth.register); +app.get('/login', routes.auth.login); +app.get('/logout', routes.auth.logout); +``` + +The `routes` variable above is the equivalent of this: + +```javascript +var routes = { + home: require('routes/home.js'), + auth: { + login: require('routes/auth/login.js'), + logout: require('routes/auth/logout.js'), + register: require('routes/auth/register.js') + } +}; +``` + +*Note that `routes.index` will be `undefined` as you would hope.* + +### Specifying Another Directory + +You can specify which directory you want to build a tree of (if it isn't the current directory for whatever reason) by passing it as the second parameter. Not specifying the path (`requireDirectory(module)`) is the equivelant of `requireDirectory(module, __dirname)`: + +```javascript +var requireDirectory = require('require-directory'); +module.exports = requireDirectory(module, './some/subdirectory'); +``` + +For example, in the [example in the Usage section](#usage) we could have avoided creating `routes/index.js` and instead changed the first lines of `app.js` to: + +```javascript +var requireDirectory = require('require-directory'); +var routes = requireDirectory(module, './routes'); +``` + +## Options + +You can pass an options hash to `require-directory` as the 2nd parameter (or 3rd if you're passing the path to another directory as the 2nd parameter already). Here are the available options: + +### Whitelisting + +Whitelisting (either via RegExp or function) allows you to specify that only certain files be loaded. + +```javascript +var requireDirectory = require('require-directory'), + whitelist = /onlyinclude.js$/, + hash = requireDirectory(module, {include: whitelist}); +``` + +```javascript +var requireDirectory = require('require-directory'), + check = function(path){ + if(/onlyinclude.js$/.test(path)){ + return true; // don't include + }else{ + return false; // go ahead and include + } + }, + hash = requireDirectory(module, {include: check}); +``` + +### Blacklisting + +Blacklisting (either via RegExp or function) allows you to specify that all but certain files should be loaded. + +```javascript +var requireDirectory = require('require-directory'), + blacklist = /dontinclude\.js$/, + hash = requireDirectory(module, {exclude: blacklist}); +``` + +```javascript +var requireDirectory = require('require-directory'), + check = function(path){ + if(/dontinclude\.js$/.test(path)){ + return false; // don't include + }else{ + return true; // go ahead and include + } + }, + hash = requireDirectory(module, {exclude: check}); +``` + +### Visiting Objects As They're Loaded + +`require-directory` takes a function as the `visit` option that will be called for each module that is added to module.exports. + +```javascript +var requireDirectory = require('require-directory'), + visitor = function(obj) { + console.log(obj); // will be called for every module that is loaded + }, + hash = requireDirectory(module, {visit: visitor}); +``` + +The visitor can also transform the objects by returning a value: + +```javascript +var requireDirectory = require('require-directory'), + visitor = function(obj) { + return obj(new Date()); + }, + hash = requireDirectory(module, {visit: visitor}); +``` + +### Renaming Keys + +```javascript +var requireDirectory = require('require-directory'), + renamer = function(name) { + return name.toUpperCase(); + }, + hash = requireDirectory(module, {rename: renamer}); +``` + +### No Recursion + +```javascript +var requireDirectory = require('require-directory'), + hash = requireDirectory(module, {recurse: false}); +``` + +## Run Unit Tests + +```bash +$ npm run lint +$ npm test +``` + +## License + +[MIT License](http://www.opensource.org/licenses/mit-license.php) + +## Author + +[Troy Goode](https://github.com/TroyGoode) ([troygoode@gmail.com](mailto:troygoode@gmail.com)) + diff --git a/node_modules/require-directory/index.js b/node_modules/require-directory/index.js new file mode 100644 index 0000000..cd37da7 --- /dev/null +++ b/node_modules/require-directory/index.js @@ -0,0 +1,86 @@ +'use strict'; + +var fs = require('fs'), + join = require('path').join, + resolve = require('path').resolve, + dirname = require('path').dirname, + defaultOptions = { + extensions: ['js', 'json', 'coffee'], + recurse: true, + rename: function (name) { + return name; + }, + visit: function (obj) { + return obj; + } + }; + +function checkFileInclusion(path, filename, options) { + return ( + // verify file has valid extension + (new RegExp('\\.(' + options.extensions.join('|') + ')$', 'i').test(filename)) && + + // if options.include is a RegExp, evaluate it and make sure the path passes + !(options.include && options.include instanceof RegExp && !options.include.test(path)) && + + // if options.include is a function, evaluate it and make sure the path passes + !(options.include && typeof options.include === 'function' && !options.include(path, filename)) && + + // if options.exclude is a RegExp, evaluate it and make sure the path doesn't pass + !(options.exclude && options.exclude instanceof RegExp && options.exclude.test(path)) && + + // if options.exclude is a function, evaluate it and make sure the path doesn't pass + !(options.exclude && typeof options.exclude === 'function' && options.exclude(path, filename)) + ); +} + +function requireDirectory(m, path, options) { + var retval = {}; + + // path is optional + if (path && !options && typeof path !== 'string') { + options = path; + path = null; + } + + // default options + options = options || {}; + for (var prop in defaultOptions) { + if (typeof options[prop] === 'undefined') { + options[prop] = defaultOptions[prop]; + } + } + + // if no path was passed in, assume the equivelant of __dirname from caller + // otherwise, resolve path relative to the equivalent of __dirname + path = !path ? dirname(m.filename) : resolve(dirname(m.filename), path); + + // get the path of each file in specified directory, append to current tree node, recurse + fs.readdirSync(path).forEach(function (filename) { + var joined = join(path, filename), + files, + key, + obj; + + if (fs.statSync(joined).isDirectory() && options.recurse) { + // this node is a directory; recurse + files = requireDirectory(m, joined, options); + // exclude empty directories + if (Object.keys(files).length) { + retval[options.rename(filename, joined, filename)] = files; + } + } else { + if (joined !== m.filename && checkFileInclusion(joined, filename, options)) { + // hash node key shouldn't include file extension + key = filename.substring(0, filename.lastIndexOf('.')); + obj = m.require(joined); + retval[options.rename(key, joined, filename)] = options.visit(obj, joined, filename) || obj; + } + } + }); + + return retval; +} + +module.exports = requireDirectory; +module.exports.defaults = defaultOptions; diff --git a/node_modules/require-directory/package.json b/node_modules/require-directory/package.json new file mode 100644 index 0000000..25ece4b --- /dev/null +++ b/node_modules/require-directory/package.json @@ -0,0 +1,40 @@ +{ + "author": "Troy Goode (http://github.com/troygoode/)", + "name": "require-directory", + "version": "2.1.1", + "description": "Recursively iterates over specified directory, require()'ing each file, and returning a nested hash structure containing those modules.", + "keywords": [ + "require", + "directory", + "library", + "recursive" + ], + "homepage": "https://github.com/troygoode/node-require-directory/", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/troygoode/node-require-directory.git" + }, + "contributors": [ + { + "name": "Troy Goode", + "email": "troygoode@gmail.com", + "web": "http://github.com/troygoode/" + } + ], + "license": "MIT", + "bugs": { + "url": "http://github.com/troygoode/node-require-directory/issues/" + }, + "engines": { + "node": ">=0.10.0" + }, + "devDependencies": { + "jshint": "^2.6.0", + "mocha": "^2.1.0" + }, + "scripts": { + "test": "mocha", + "lint": "jshint index.js test/test.js" + } +} diff --git a/node_modules/retry-request/CHANGELOG.md b/node_modules/retry-request/CHANGELOG.md new file mode 100644 index 0000000..894f765 --- /dev/null +++ b/node_modules/retry-request/CHANGELOG.md @@ -0,0 +1,91 @@ +# Changelog + +## [7.0.2](https://github.com/googleapis/retry-request/compare/v7.0.1...v7.0.2) (2024-01-19) + + +### Bug Fixes + +* Get rid of debug runtime dependency ([#118](https://github.com/googleapis/retry-request/issues/118)) ([85e1bd0](https://github.com/googleapis/retry-request/commit/85e1bd0a46630876757344405a6c8620d9de6451)) + +## [7.0.1](https://github.com/googleapis/retry-request/compare/v7.0.0...v7.0.1) (2023-10-12) + + +### Bug Fixes + +* Types ([#109](https://github.com/googleapis/retry-request/issues/109)) ([35c0260](https://github.com/googleapis/retry-request/commit/35c02608138a4b66cf488e4e1e90cbff05d42c2f)) + +## [7.0.0](https://github.com/googleapis/retry-request/compare/v6.0.0...v7.0.0) (2023-10-11) + + +### ⚠ BREAKING CHANGES + +* Remove `request` fallback, Update Docs, Update Types ([#107](https://github.com/googleapis/retry-request/issues/107)) + +### Features + +* Remove `request` fallback, Update Docs, Update Types ([#107](https://github.com/googleapis/retry-request/issues/107)) ([ba8abb2](https://github.com/googleapis/retry-request/commit/ba8abb242ff21921a81e3178081806e95a902a68)) + +## [6.0.0](https://github.com/googleapis/retry-request/compare/v5.0.2...v6.0.0) (2023-07-20) + + +### ⚠ BREAKING CHANGES + +* Move to node 14 as the minimum version ([#97](https://github.com/googleapis/retry-request/issues/97)) +* move minimum version to node 14 ([#96](https://github.com/googleapis/retry-request/issues/96)) + +### Features + +* Move to node 14 as the minimum version ([#97](https://github.com/googleapis/retry-request/issues/97)) ([f42d074](https://github.com/googleapis/retry-request/commit/f42d0743de048fdf46c7f480f3dec59c2caefa5a)) + + +### Miscellaneous Chores + +* Move minimum version to node 14 ([#96](https://github.com/googleapis/retry-request/issues/96)) ([2167a91](https://github.com/googleapis/retry-request/commit/2167a91c36e95522ad7e7293b4744ddd81c6166e)) + +## [5.0.2](https://github.com/googleapis/retry-request/compare/v5.0.1...v5.0.2) (2022-09-14) + + +### Bug Fixes + +* Delete second LICENSE ([#82](https://github.com/googleapis/retry-request/issues/82)) ([9dfaf18](https://github.com/googleapis/retry-request/commit/9dfaf1819b18b6d660924951b9cf1c509b6e9870)) +* Remove pip install statements ([#1546](https://github.com/googleapis/retry-request/issues/1546)) ([#79](https://github.com/googleapis/retry-request/issues/79)) ([cb4e15d](https://github.com/googleapis/retry-request/commit/cb4e15d6e8ae9d72855ed1071957afe9d301b12e)) + +## [5.0.1](https://github.com/googleapis/retry-request/compare/v5.0.0...v5.0.1) (2022-06-09) + + +### Bug Fixes + +* respect totalTimeout and do not retry if nextRetryDelay is <= 0 ([#38](https://github.com/googleapis/retry-request/issues/38)) ([9501a42](https://github.com/googleapis/retry-request/commit/9501a42d06a620282dcd2ff9990fd0b5033a990b)) + +## [5.0.0](https://github.com/googleapis/retry-request/compare/v4.2.2...v5.0.0) (2022-05-06) + + +### ⚠ BREAKING CHANGES + +* drop node 10 (#68) + +### Build System + +* drop node 10 ([#68](https://github.com/googleapis/retry-request/issues/68)) ([00ec90c](https://github.com/googleapis/retry-request/commit/00ec90c4d3cb29245ca746e0e133fcddc22d2251)) + +### [4.2.1](https://github.com/googleapis/retry-request/compare/v4.2.0...v4.2.1) (2022-04-12) + + +### Bug Fixes + +* add new retry options to types ([#36](https://github.com/googleapis/retry-request/issues/36)) ([3f10798](https://github.com/googleapis/retry-request/commit/3f10798f47c03b50f1ba352b04d09ea3d0458b9c)) +* use extend instead of object.assign ([#37](https://github.com/googleapis/retry-request/issues/37)) ([8c8dcdd](https://github.com/googleapis/retry-request/commit/8c8dcdd7d6262ce305c93fa4a8a7b2630e984824)) + +## [4.2.0](https://github.com/googleapis/retry-request/compare/v4.1.0...v4.2.0) (2022-04-06) + + +### Features + +* support enhanced retry settings ([#35](https://github.com/googleapis/retry-request/issues/35)) ([0184676](https://github.com/googleapis/retry-request/commit/0184676dee36596fb939fb4559af11d0a14f64bd)) + + +### Bug Fixes + +* add new retry options to types ([#36](https://github.com/googleapis/retry-request/issues/36)) ([3f10798](https://github.com/googleapis/retry-request/commit/3f10798f47c03b50f1ba352b04d09ea3d0458b9c)) +* correctly calculate retry attempt ([#33](https://github.com/googleapis/retry-request/issues/33)) ([4c852e2](https://github.com/googleapis/retry-request/commit/4c852e2ba22a7f75edfb3c905bd37a7e9913e67d)) +* use extend instead of object.assign ([#37](https://github.com/googleapis/retry-request/issues/37)) ([8c8dcdd](https://github.com/googleapis/retry-request/commit/8c8dcdd7d6262ce305c93fa4a8a7b2630e984824)) diff --git a/node_modules/retry-request/index.d.ts b/node_modules/retry-request/index.d.ts new file mode 100644 index 0000000..3627f45 --- /dev/null +++ b/node_modules/retry-request/index.d.ts @@ -0,0 +1,42 @@ +declare module 'retry-request' { + import * as request from 'request'; + import * as teenyRequest from 'teeny-request'; + + type teenyRequestFunction = typeof teenyRequest extends Function + ? typeof teenyRequest + : never; + + namespace retryRequest { + /** + * Set the defaults for `retryRequest`. + */ + const defaults: retryRequest.Options; + /** + * Determines the next retry based on the provided configuration. + */ + function getNextRetryDelay(config: Options): number; + interface Options { + objectMode?: boolean; + request: typeof request | teenyRequestFunction; + retries?: number; + noResponseRetries?: number; + currentRetryAttempt?: number; + maxRetryDelay?: number; + retryDelayMultiplier?: number; + totalTimeout?: number; + shouldRetryFn?: (response: request.RequestResponse) => boolean; + } + } + + function retryRequest( + requestOpts: request.Options, + opts: retryRequest.Options, + callback?: request.RequestCallback + ): {abort: () => void}; + function retryRequest( + requestOpts: request.Options, + callback?: request.RequestCallback + ): {abort: () => void}; + + export = retryRequest; +} diff --git a/node_modules/retry-request/index.js b/node_modules/retry-request/index.js new file mode 100644 index 0000000..2fae107 --- /dev/null +++ b/node_modules/retry-request/index.js @@ -0,0 +1,293 @@ +'use strict'; + +const {PassThrough} = require('stream'); +const extend = require('extend'); + +let debug = () => {}; +if ( + typeof process !== 'undefined' && + 'env' in process && + typeof process.env === 'object' && + process.env.DEBUG === 'retry-request' +) { + debug = message => { + console.log('retry-request:', message); + }; +} + +const DEFAULTS = { + objectMode: false, + retries: 2, + + /* + The maximum time to delay in seconds. If retryDelayMultiplier results in a + delay greater than maxRetryDelay, retries should delay by maxRetryDelay + seconds instead. + */ + maxRetryDelay: 64, + + /* + The multiplier by which to increase the delay time between the completion of + failed requests, and the initiation of the subsequent retrying request. + */ + retryDelayMultiplier: 2, + + /* + The length of time to keep retrying in seconds. The last sleep period will + be shortened as necessary, so that the last retry runs at deadline (and not + considerably beyond it). The total time starting from when the initial + request is sent, after which an error will be returned, regardless of the + retrying attempts made meanwhile. + */ + totalTimeout: 600, + + noResponseRetries: 2, + currentRetryAttempt: 0, + shouldRetryFn: function (response) { + const retryRanges = [ + // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes + // 1xx - Retry (Informational, request still processing) + // 2xx - Do not retry (Success) + // 3xx - Do not retry (Redirect) + // 4xx - Do not retry (Client errors) + // 429 - Retry ("Too Many Requests") + // 5xx - Retry (Server errors) + [100, 199], + [429, 429], + [500, 599], + ]; + + const statusCode = response.statusCode; + debug(`Response status: ${statusCode}`); + + let range; + while ((range = retryRanges.shift())) { + if (statusCode >= range[0] && statusCode <= range[1]) { + // Not a successful status or redirect. + return true; + } + } + }, +}; + +function retryRequest(requestOpts, opts, callback) { + if (typeof requestOpts === 'string') { + requestOpts = {url: requestOpts}; + } + + const streamMode = typeof arguments[arguments.length - 1] !== 'function'; + + if (typeof opts === 'function') { + callback = opts; + } + + const manualCurrentRetryAttemptWasSet = + opts && typeof opts.currentRetryAttempt === 'number'; + opts = extend({}, DEFAULTS, opts); + + if (typeof opts.request === 'undefined') { + throw new Error('A request library must be provided to retry-request.'); + } + + let currentRetryAttempt = opts.currentRetryAttempt; + + let numNoResponseAttempts = 0; + let streamResponseHandled = false; + + let retryStream; + let requestStream; + let delayStream; + + let activeRequest; + const retryRequest = { + abort: function () { + if (activeRequest && activeRequest.abort) { + activeRequest.abort(); + } + }, + }; + + if (streamMode) { + retryStream = new PassThrough({objectMode: opts.objectMode}); + retryStream.abort = resetStreams; + } + + const timeOfFirstRequest = Date.now(); + if (currentRetryAttempt > 0) { + retryAfterDelay(currentRetryAttempt); + } else { + makeRequest(); + } + + if (streamMode) { + return retryStream; + } else { + return retryRequest; + } + + function resetStreams() { + delayStream = null; + + if (requestStream) { + requestStream.abort && requestStream.abort(); + requestStream.cancel && requestStream.cancel(); + + if (requestStream.destroy) { + requestStream.destroy(); + } else if (requestStream.end) { + requestStream.end(); + } + } + } + + function makeRequest() { + let finishHandled = false; + currentRetryAttempt++; + debug(`Current retry attempt: ${currentRetryAttempt}`); + + function handleFinish(args = []) { + if (!finishHandled) { + finishHandled = true; + retryStream.emit('complete', ...args); + } + } + + if (streamMode) { + streamResponseHandled = false; + + delayStream = new PassThrough({objectMode: opts.objectMode}); + requestStream = opts.request(requestOpts); + + setImmediate(() => { + retryStream.emit('request'); + }); + + requestStream + // gRPC via google-cloud-node can emit an `error` as well as a `response` + // Whichever it emits, we run with-- we can't run with both. That's what + // is up with the `streamResponseHandled` tracking. + .on('error', err => { + if (streamResponseHandled) { + return; + } + + streamResponseHandled = true; + onResponse(err); + }) + .on('response', (resp, body) => { + if (streamResponseHandled) { + return; + } + + streamResponseHandled = true; + onResponse(null, resp, body); + }) + .on('complete', (...params) => handleFinish(params)) + .on('finish', (...params) => handleFinish(params)); + + requestStream.pipe(delayStream); + } else { + activeRequest = opts.request(requestOpts, onResponse); + } + } + + function retryAfterDelay(currentRetryAttempt) { + if (streamMode) { + resetStreams(); + } + + const nextRetryDelay = getNextRetryDelay({ + maxRetryDelay: opts.maxRetryDelay, + retryDelayMultiplier: opts.retryDelayMultiplier, + retryNumber: currentRetryAttempt, + timeOfFirstRequest, + totalTimeout: opts.totalTimeout, + }); + debug(`Next retry delay: ${nextRetryDelay}`); + + if (nextRetryDelay <= 0) { + numNoResponseAttempts = opts.noResponseRetries + 1; + return; + } + + setTimeout(makeRequest, nextRetryDelay); + } + + function onResponse(err, response, body) { + // An error such as DNS resolution. + if (err) { + numNoResponseAttempts++; + + if (numNoResponseAttempts <= opts.noResponseRetries) { + retryAfterDelay(numNoResponseAttempts); + } else { + if (streamMode) { + retryStream.emit('error', err); + retryStream.end(); + } else { + callback(err, response, body); + } + } + + return; + } + + // Send the response to see if we should try again. + // NOTE: "currentRetryAttempt" isn't accurate by default, as it counts + // the very first request sent as the first "retry". It is only accurate + // when a user provides their own "currentRetryAttempt" option at + // instantiation. + const adjustedCurrentRetryAttempt = manualCurrentRetryAttemptWasSet + ? currentRetryAttempt + : currentRetryAttempt - 1; + if ( + adjustedCurrentRetryAttempt < opts.retries && + opts.shouldRetryFn(response) + ) { + retryAfterDelay(currentRetryAttempt); + return; + } + + // No more attempts need to be made, just continue on. + if (streamMode) { + retryStream.emit('response', response); + delayStream.pipe(retryStream); + requestStream.on('error', err => { + retryStream.destroy(err); + }); + } else { + callback(err, response, body); + } + } +} + +module.exports = retryRequest; + +function getNextRetryDelay(config) { + const { + maxRetryDelay, + retryDelayMultiplier, + retryNumber, + timeOfFirstRequest, + totalTimeout, + } = config; + + const maxRetryDelayMs = maxRetryDelay * 1000; + const totalTimeoutMs = totalTimeout * 1000; + + const jitter = Math.floor(Math.random() * 1000); + const calculatedNextRetryDelay = + Math.pow(retryDelayMultiplier, retryNumber) * 1000 + jitter; + + const maxAllowableDelayMs = + totalTimeoutMs - (Date.now() - timeOfFirstRequest); + + return Math.min( + calculatedNextRetryDelay, + maxAllowableDelayMs, + maxRetryDelayMs + ); +} + +module.exports.defaults = DEFAULTS; +module.exports.getNextRetryDelay = getNextRetryDelay; diff --git a/node_modules/retry-request/license b/node_modules/retry-request/license new file mode 100644 index 0000000..df6eeb5 --- /dev/null +++ b/node_modules/retry-request/license @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2015 Stephen Sawchuk + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/retry-request/package.json b/node_modules/retry-request/package.json new file mode 100644 index 0000000..7389612 --- /dev/null +++ b/node_modules/retry-request/package.json @@ -0,0 +1,48 @@ +{ + "name": "retry-request", + "version": "7.0.2", + "description": "Retry a request.", + "main": "index.js", + "repository": "stephenplusplus/retry-request", + "scripts": { + "docs": "jsdoc -c .jsdoc.js", + "predocs-test": "npm run docs", + "docs-test": "linkinator docs", + "fix": "gts fix", + "lint": "gts check", + "test": "mocha --timeout 30000", + "system-test": "" + }, + "files": [ + "index.js", + "index.d.ts", + "license" + ], + "types": "index.d.ts", + "keywords": [ + "request", + "retry", + "stream" + ], + "author": "Stephen Sawchuk ", + "license": "MIT", + "engines": { + "node": ">=14" + }, + "dependencies": { + "@types/request": "^2.48.8", + "extend": "^3.0.2", + "teeny-request": "^9.0.0" + }, + "devDependencies": { + "async": "^3.0.1", + "gts": "^5.0.0", + "jsdoc": "^4.0.0", + "jsdoc-fresh": "^3.0.0", + "jsdoc-region-tag": "^3.0.0", + "linkinator": "^4.0.0", + "lodash.range": "^3.2.0", + "mocha": "^10.2.0", + "typescript": "^5.1.6" + } +} diff --git a/node_modules/retry-request/readme.md b/node_modules/retry-request/readme.md new file mode 100644 index 0000000..0c3e0f0 --- /dev/null +++ b/node_modules/retry-request/readme.md @@ -0,0 +1,199 @@ +|![retry-request](logo.png) +|:-: +|Retry a [request][request] with built-in [exponential backoff](https://developers.google.com/analytics/devguides/reporting/core/v3/coreErrors#backoff). + +```sh +$ npm install --save teeny-request +$ npm install --save retry-request +``` + +```js +var request = require('retry-request', { + request: require('teeny-request'), +}); +``` + +It should work the same as `request` and `teeny-request` in both callback mode and stream mode. + +Note: This module only works when used as a readable stream, i.e. POST requests aren't supported ([#3](https://github.com/stephenplusplus/retry-request/issues/3)). + +## Do I need to install `request`? + +Yes! You must independently install `teeny-request` OR `request` (_deprecated_) and provide it to this library: + +```js +var request = require('retry-request', { + request: require('teeny-request'), +}); +``` + +#### Callback + +`urlThatReturns503` will be requested 3 total times before giving up and executing the callback. + +```js +request(urlThatReturns503, function (err, resp, body) {}); +``` + +#### Stream + +`urlThatReturns503` will be requested 3 total times before giving up and emitting the `response` and `complete` event as usual. + +```js +request(urlThatReturns503) + .on('error', function () {}) + .on('response', function () {}) + .on('complete', function () {}); +``` + +## Can I monitor what retry-request is doing internally? + +Yes! To enable the debug mode, set the environment variable `DEBUG` to _retry-request_. + +(Thanks for the implementation, @yihaozhadan!) + +## request(requestOptions, [opts], [cb]) + +### requestOptions + +Passed directly to `request` or `teeny-request`. See the list of options supported: + +- https://github.com/request/request/#requestoptions-callback +- https://github.com/googleapis/teeny-request#teenyrequestoptions-callback + +### opts _(optional)_ + +#### `opts.noResponseRetries` + +Type: `Number` + +Default: `2` + +The number of times to retry after a response fails to come through, such as a DNS resolution error or a socket hangup. + +```js +var opts = { + noResponseRetries: 0, +}; + +request(url, opts, function (err, resp, body) { + // url was requested 1 time before giving up and + // executing this callback. +}); +``` + +#### `opts.objectMode` + +Type: `Boolean` + +Default: `false` + +Set to `true` if your custom `opts.request` function returns a stream in object mode. + +#### `opts.retries` + +Type: `Number` + +Default: `2` + +```js +var opts = { + retries: 4, +}; + +request(urlThatReturns503, opts, function (err, resp, body) { + // urlThatReturns503 was requested a total of 5 times + // before giving up and executing this callback. +}); +``` + +#### `opts.currentRetryAttempt` + +Type: `Number` + +Default: `0` + +```js +var opts = { + currentRetryAttempt: 1, +}; + +request(urlThatReturns503, opts, function (err, resp, body) { + // urlThatReturns503 was requested as if it already failed once. +}); +``` + +#### `opts.shouldRetryFn` + +Type: `Function` + +Default: Returns `true` if [http.incomingMessage](https://nodejs.org/api/http.html#http_http_incomingmessage).statusCode is < 200 or >= 400. + +```js +var opts = { + shouldRetryFn: function (incomingHttpMessage) { + return incomingHttpMessage.statusMessage !== 'OK'; + }, +}; + +request(urlThatReturnsNonOKStatusMessage, opts, function (err, resp, body) { + // urlThatReturnsNonOKStatusMessage was requested a + // total of 3 times, each time using `opts.shouldRetryFn` + // to decide if it should continue before giving up and + // executing this callback. +}); +``` + +#### `opts.request` + +Type: `Function` + +If we not provided we will throw an error advising you to provide it. + +_NOTE: If you override the request function, and it returns a stream in object mode, be sure to set `opts.objectMode` to `true`._ + +```js +var originalRequest = require('teeny-request').defaults({ + pool: { + maxSockets: Infinity, + }, +}); + +var opts = { + request: originalRequest, +}; + +request(urlThatReturns503, opts, function (err, resp, body) { + // Your provided `originalRequest` instance was used. +}); +``` + +#### `opts.maxRetryDelay` + +Type: `Number` + +Default: `64` + +The maximum time to delay in seconds. If retryDelayMultiplier results in a delay greater than maxRetryDelay, retries should delay by maxRetryDelay seconds instead. + +#### `opts.retryDelayMultiplier` + +Type: `Number` + +Default: `2` + +The multiplier by which to increase the delay time between the completion of failed requests, and the initiation of the subsequent retrying request. + +#### `opts.totalTimeout` + +Type: `Number` + +Default: `600` + +The length of time to keep retrying in seconds. The last sleep period will be shortened as necessary, so that the last retry runs at deadline (and not considerably beyond it). The total time starting from when the initial request is sent, after which an error will be returned, regardless of the retrying attempts made meanwhile. + +### cb _(optional)_ + +Passed directly to `request`. See the callback section: https://github.com/request/request/#requestoptions-callback. + +[request]: https://github.com/request/request diff --git a/node_modules/retry/License b/node_modules/retry/License new file mode 100644 index 0000000..0b58de3 --- /dev/null +++ b/node_modules/retry/License @@ -0,0 +1,21 @@ +Copyright (c) 2011: +Tim Koschützki (tim@debuggable.com) +Felix Geisendörfer (felix@debuggable.com) + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. diff --git a/node_modules/retry/README.md b/node_modules/retry/README.md new file mode 100644 index 0000000..6d54153 --- /dev/null +++ b/node_modules/retry/README.md @@ -0,0 +1,227 @@ + +[![Build Status](https://secure.travis-ci.org/tim-kos/node-retry.svg?branch=master)](http://travis-ci.org/tim-kos/node-retry "Check this project's build status on TravisCI") +[![codecov](https://codecov.io/gh/tim-kos/node-retry/branch/master/graph/badge.svg)](https://codecov.io/gh/tim-kos/node-retry) + + +# retry + +Abstraction for exponential and custom retry strategies for failed operations. + +## Installation + + npm install retry + +## Current Status + +This module has been tested and is ready to be used. + +## Tutorial + +The example below will retry a potentially failing `dns.resolve` operation +`10` times using an exponential backoff strategy. With the default settings, this +means the last attempt is made after `17 minutes and 3 seconds`. + +``` javascript +var dns = require('dns'); +var retry = require('retry'); + +function faultTolerantResolve(address, cb) { + var operation = retry.operation(); + + operation.attempt(function(currentAttempt) { + dns.resolve(address, function(err, addresses) { + if (operation.retry(err)) { + return; + } + + cb(err ? operation.mainError() : null, addresses); + }); + }); +} + +faultTolerantResolve('nodejs.org', function(err, addresses) { + console.log(err, addresses); +}); +``` + +Of course you can also configure the factors that go into the exponential +backoff. See the API documentation below for all available settings. +currentAttempt is an int representing the number of attempts so far. + +``` javascript +var operation = retry.operation({ + retries: 5, + factor: 3, + minTimeout: 1 * 1000, + maxTimeout: 60 * 1000, + randomize: true, +}); +``` + +## API + +### retry.operation([options]) + +Creates a new `RetryOperation` object. `options` is the same as `retry.timeouts()`'s `options`, with three additions: + +* `forever`: Whether to retry forever, defaults to `false`. +* `unref`: Whether to [unref](https://nodejs.org/api/timers.html#timers_unref) the setTimeout's, defaults to `false`. +* `maxRetryTime`: The maximum time (in milliseconds) that the retried operation is allowed to run. Default is `Infinity`. + +### retry.timeouts([options]) + +Returns an array of timeouts. All time `options` and return values are in +milliseconds. If `options` is an array, a copy of that array is returned. + +`options` is a JS object that can contain any of the following keys: + +* `retries`: The maximum amount of times to retry the operation. Default is `10`. Seting this to `1` means `do it once, then retry it once`. +* `factor`: The exponential factor to use. Default is `2`. +* `minTimeout`: The number of milliseconds before starting the first retry. Default is `1000`. +* `maxTimeout`: The maximum number of milliseconds between two retries. Default is `Infinity`. +* `randomize`: Randomizes the timeouts by multiplying with a factor between `1` to `2`. Default is `false`. + +The formula used to calculate the individual timeouts is: + +``` +Math.min(random * minTimeout * Math.pow(factor, attempt), maxTimeout) +``` + +Have a look at [this article][article] for a better explanation of approach. + +If you want to tune your `factor` / `times` settings to attempt the last retry +after a certain amount of time, you can use wolfram alpha. For example in order +to tune for `10` attempts in `5 minutes`, you can use this equation: + +![screenshot](https://github.com/tim-kos/node-retry/raw/master/equation.gif) + +Explaining the various values from left to right: + +* `k = 0 ... 9`: The `retries` value (10) +* `1000`: The `minTimeout` value in ms (1000) +* `x^k`: No need to change this, `x` will be your resulting factor +* `5 * 60 * 1000`: The desired total amount of time for retrying in ms (5 minutes) + +To make this a little easier for you, use wolfram alpha to do the calculations: + + + +[article]: http://dthain.blogspot.com/2009/02/exponential-backoff-in-distributed.html + +### retry.createTimeout(attempt, opts) + +Returns a new `timeout` (integer in milliseconds) based on the given parameters. + +`attempt` is an integer representing for which retry the timeout should be calculated. If your retry operation was executed 4 times you had one attempt and 3 retries. If you then want to calculate a new timeout, you should set `attempt` to 4 (attempts are zero-indexed). + +`opts` can include `factor`, `minTimeout`, `randomize` (boolean) and `maxTimeout`. They are documented above. + +`retry.createTimeout()` is used internally by `retry.timeouts()` and is public for you to be able to create your own timeouts for reinserting an item, see [issue #13](https://github.com/tim-kos/node-retry/issues/13). + +### retry.wrap(obj, [options], [methodNames]) + +Wrap all functions of the `obj` with retry. Optionally you can pass operation options and +an array of method names which need to be wrapped. + +``` +retry.wrap(obj) + +retry.wrap(obj, ['method1', 'method2']) + +retry.wrap(obj, {retries: 3}) + +retry.wrap(obj, {retries: 3}, ['method1', 'method2']) +``` +The `options` object can take any options that the usual call to `retry.operation` can take. + +### new RetryOperation(timeouts, [options]) + +Creates a new `RetryOperation` where `timeouts` is an array where each value is +a timeout given in milliseconds. + +Available options: +* `forever`: Whether to retry forever, defaults to `false`. +* `unref`: Wether to [unref](https://nodejs.org/api/timers.html#timers_unref) the setTimeout's, defaults to `false`. + +If `forever` is true, the following changes happen: +* `RetryOperation.errors()` will only output an array of one item: the last error. +* `RetryOperation` will repeatedly use the `timeouts` array. Once all of its timeouts have been used up, it restarts with the first timeout, then uses the second and so on. + +#### retryOperation.errors() + +Returns an array of all errors that have been passed to `retryOperation.retry()` so far. The +returning array has the errors ordered chronologically based on when they were passed to +`retryOperation.retry()`, which means the first passed error is at index zero and the last is +at the last index. + +#### retryOperation.mainError() + +A reference to the error object that occured most frequently. Errors are +compared using the `error.message` property. + +If multiple error messages occured the same amount of time, the last error +object with that message is returned. + +If no errors occured so far, the value is `null`. + +#### retryOperation.attempt(fn, timeoutOps) + +Defines the function `fn` that is to be retried and executes it for the first +time right away. The `fn` function can receive an optional `currentAttempt` callback that represents the number of attempts to execute `fn` so far. + +Optionally defines `timeoutOps` which is an object having a property `timeout` in miliseconds and a property `cb` callback function. +Whenever your retry operation takes longer than `timeout` to execute, the timeout callback function `cb` is called. + + +#### retryOperation.try(fn) + +This is an alias for `retryOperation.attempt(fn)`. This is deprecated. Please use `retryOperation.attempt(fn)` instead. + +#### retryOperation.start(fn) + +This is an alias for `retryOperation.attempt(fn)`. This is deprecated. Please use `retryOperation.attempt(fn)` instead. + +#### retryOperation.retry(error) + +Returns `false` when no `error` value is given, or the maximum amount of retries +has been reached. + +Otherwise it returns `true`, and retries the operation after the timeout for +the current attempt number. + +#### retryOperation.stop() + +Allows you to stop the operation being retried. Useful for aborting the operation on a fatal error etc. + +#### retryOperation.reset() + +Resets the internal state of the operation object, so that you can call `attempt()` again as if this was a new operation object. + +#### retryOperation.attempts() + +Returns an int representing the number of attempts it took to call `fn` before it was successful. + +## License + +retry is licensed under the MIT license. + + +# Changelog + +0.10.0 Adding `stop` functionality, thanks to @maxnachlinger. + +0.9.0 Adding `unref` functionality, thanks to @satazor. + +0.8.0 Implementing retry.wrap. + +0.7.0 Some bug fixes and made retry.createTimeout() public. Fixed issues [#10](https://github.com/tim-kos/node-retry/issues/10), [#12](https://github.com/tim-kos/node-retry/issues/12), and [#13](https://github.com/tim-kos/node-retry/issues/13). + +0.6.0 Introduced optional timeOps parameter for the attempt() function which is an object having a property timeout in milliseconds and a property cb callback function. Whenever your retry operation takes longer than timeout to execute, the timeout callback function cb is called. + +0.5.0 Some minor refactoring. + +0.4.0 Changed retryOperation.try() to retryOperation.attempt(). Deprecated the aliases start() and try() for it. + +0.3.0 Added retryOperation.start() which is an alias for retryOperation.try(). + +0.2.0 Added attempts() function and parameter to retryOperation.try() representing the number of attempts it took to call fn(). diff --git a/node_modules/retry/example/dns.js b/node_modules/retry/example/dns.js new file mode 100644 index 0000000..446729b --- /dev/null +++ b/node_modules/retry/example/dns.js @@ -0,0 +1,31 @@ +var dns = require('dns'); +var retry = require('../lib/retry'); + +function faultTolerantResolve(address, cb) { + var opts = { + retries: 2, + factor: 2, + minTimeout: 1 * 1000, + maxTimeout: 2 * 1000, + randomize: true + }; + var operation = retry.operation(opts); + + operation.attempt(function(currentAttempt) { + dns.resolve(address, function(err, addresses) { + if (operation.retry(err)) { + return; + } + + cb(operation.mainError(), operation.errors(), addresses); + }); + }); +} + +faultTolerantResolve('nodejs.org', function(err, errors, addresses) { + console.warn('err:'); + console.log(err); + + console.warn('addresses:'); + console.log(addresses); +}); \ No newline at end of file diff --git a/node_modules/retry/example/stop.js b/node_modules/retry/example/stop.js new file mode 100644 index 0000000..e1ceafe --- /dev/null +++ b/node_modules/retry/example/stop.js @@ -0,0 +1,40 @@ +var retry = require('../lib/retry'); + +function attemptAsyncOperation(someInput, cb) { + var opts = { + retries: 2, + factor: 2, + minTimeout: 1 * 1000, + maxTimeout: 2 * 1000, + randomize: true + }; + var operation = retry.operation(opts); + + operation.attempt(function(currentAttempt) { + failingAsyncOperation(someInput, function(err, result) { + + if (err && err.message === 'A fatal error') { + operation.stop(); + return cb(err); + } + + if (operation.retry(err)) { + return; + } + + cb(operation.mainError(), operation.errors(), result); + }); + }); +} + +attemptAsyncOperation('test input', function(err, errors, result) { + console.warn('err:'); + console.log(err); + + console.warn('result:'); + console.log(result); +}); + +function failingAsyncOperation(input, cb) { + return setImmediate(cb.bind(null, new Error('A fatal error'))); +} diff --git a/node_modules/retry/index.js b/node_modules/retry/index.js new file mode 100644 index 0000000..ee62f3a --- /dev/null +++ b/node_modules/retry/index.js @@ -0,0 +1 @@ +module.exports = require('./lib/retry'); \ No newline at end of file diff --git a/node_modules/retry/lib/retry.js b/node_modules/retry/lib/retry.js new file mode 100644 index 0000000..5e85e79 --- /dev/null +++ b/node_modules/retry/lib/retry.js @@ -0,0 +1,100 @@ +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 * 1000, + maxTimeout: Infinity, + randomize: false + }; + for (var key in options) { + opts[key] = options[key]; + } + + if (opts.minTimeout > opts.maxTimeout) { + throw new Error('minTimeout is greater than maxTimeout'); + } + + var timeouts = []; + for (var i = 0; i < opts.retries; i++) { + timeouts.push(this.createTimeout(i, opts)); + } + + if (options && options.forever && !timeouts.length) { + timeouts.push(this.createTimeout(i, opts)); + } + + // sort the array numerically ascending + timeouts.sort(function(a,b) { + return a - b; + }); + + return timeouts; +}; + +exports.createTimeout = function(attempt, opts) { + var random = (opts.randomize) + ? (Math.random() + 1) + : 1; + + var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); + timeout = Math.min(timeout, opts.maxTimeout); + + return timeout; +}; + +exports.wrap = function(obj, options, methods) { + if (options instanceof Array) { + methods = options; + options = null; + } + + if (!methods) { + methods = []; + for (var key in obj) { + if (typeof obj[key] === 'function') { + methods.push(key); + } + } + } + + for (var i = 0; i < methods.length; i++) { + var method = methods[i]; + var original = obj[method]; + + obj[method] = function retryWrapper(original) { + var op = exports.operation(options); + var args = Array.prototype.slice.call(arguments, 1); + var callback = args.pop(); + + args.push(function(err) { + if (op.retry(err)) { + return; + } + if (err) { + arguments[0] = op.mainError(); + } + callback.apply(this, arguments); + }); + + op.attempt(function() { + original.apply(obj, args); + }); + }.bind(obj, original); + obj[method].options = options; + } +}; diff --git a/node_modules/retry/lib/retry_operation.js b/node_modules/retry/lib/retry_operation.js new file mode 100644 index 0000000..105ce72 --- /dev/null +++ b/node_modules/retry/lib/retry_operation.js @@ -0,0 +1,162 @@ +function RetryOperation(timeouts, options) { + // Compatibility for the old (timeouts, retryForever) signature + if (typeof options === 'boolean') { + options = { forever: options }; + } + + this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); + this._timeouts = timeouts; + this._options = options || {}; + this._maxRetryTime = options && options.maxRetryTime || Infinity; + this._fn = null; + this._errors = []; + this._attempts = 1; + this._operationTimeout = null; + this._operationTimeoutCb = null; + this._timeout = null; + this._operationStart = null; + this._timer = null; + + if (this._options.forever) { + this._cachedTimeouts = this._timeouts.slice(0); + } +} +module.exports = RetryOperation; + +RetryOperation.prototype.reset = function() { + this._attempts = 1; + this._timeouts = this._originalTimeouts.slice(0); +} + +RetryOperation.prototype.stop = function() { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (this._timer) { + clearTimeout(this._timer); + } + + this._timeouts = []; + this._cachedTimeouts = null; +}; + +RetryOperation.prototype.retry = function(err) { + if (this._timeout) { + clearTimeout(this._timeout); + } + + if (!err) { + return false; + } + var currentTime = new Date().getTime(); + if (err && currentTime - this._operationStart >= this._maxRetryTime) { + this._errors.push(err); + this._errors.unshift(new Error('RetryOperation timeout occurred')); + return false; + } + + this._errors.push(err); + + var timeout = this._timeouts.shift(); + if (timeout === undefined) { + if (this._cachedTimeouts) { + // retry forever, only keep last error + this._errors.splice(0, this._errors.length - 1); + timeout = this._cachedTimeouts.slice(-1); + } else { + return false; + } + } + + var self = this; + this._timer = setTimeout(function() { + self._attempts++; + + if (self._operationTimeoutCb) { + self._timeout = setTimeout(function() { + self._operationTimeoutCb(self._attempts); + }, self._operationTimeout); + + if (self._options.unref) { + self._timeout.unref(); + } + } + + self._fn(self._attempts); + }, timeout); + + if (this._options.unref) { + this._timer.unref(); + } + + return true; +}; + +RetryOperation.prototype.attempt = function(fn, timeoutOps) { + this._fn = fn; + + if (timeoutOps) { + if (timeoutOps.timeout) { + this._operationTimeout = timeoutOps.timeout; + } + if (timeoutOps.cb) { + this._operationTimeoutCb = timeoutOps.cb; + } + } + + var self = this; + if (this._operationTimeoutCb) { + this._timeout = setTimeout(function() { + self._operationTimeoutCb(); + }, self._operationTimeout); + } + + this._operationStart = new Date().getTime(); + + this._fn(this._attempts); +}; + +RetryOperation.prototype.try = function(fn) { + console.log('Using RetryOperation.try() is deprecated'); + this.attempt(fn); +}; + +RetryOperation.prototype.start = function(fn) { + console.log('Using RetryOperation.start() is deprecated'); + this.attempt(fn); +}; + +RetryOperation.prototype.start = RetryOperation.prototype.try; + +RetryOperation.prototype.errors = function() { + return this._errors; +}; + +RetryOperation.prototype.attempts = function() { + return this._attempts; +}; + +RetryOperation.prototype.mainError = function() { + if (this._errors.length === 0) { + return null; + } + + var counts = {}; + var mainError = null; + var mainErrorCount = 0; + + for (var i = 0; i < this._errors.length; i++) { + var error = this._errors[i]; + var message = error.message; + var count = (counts[message] || 0) + 1; + + counts[message] = count; + + if (count >= mainErrorCount) { + mainError = error; + mainErrorCount = count; + } + } + + return mainError; +}; diff --git a/node_modules/retry/package.json b/node_modules/retry/package.json new file mode 100644 index 0000000..48f35e8 --- /dev/null +++ b/node_modules/retry/package.json @@ -0,0 +1,36 @@ +{ + "author": "Tim Koschützki (http://debuggable.com/)", + "name": "retry", + "description": "Abstraction for exponential and custom retry strategies for failed operations.", + "license": "MIT", + "version": "0.13.1", + "homepage": "https://github.com/tim-kos/node-retry", + "repository": { + "type": "git", + "url": "git://github.com/tim-kos/node-retry.git" + }, + "files": [ + "lib", + "example" + ], + "directories": { + "lib": "./lib" + }, + "main": "index.js", + "engines": { + "node": ">= 4" + }, + "dependencies": {}, + "devDependencies": { + "fake": "0.2.0", + "istanbul": "^0.4.5", + "tape": "^4.8.0" + }, + "scripts": { + "test": "./node_modules/.bin/istanbul cover ./node_modules/tape/bin/tape ./test/integration/*.js", + "release:major": "env SEMANTIC=major npm run release", + "release:minor": "env SEMANTIC=minor npm run release", + "release:patch": "env SEMANTIC=patch npm run release", + "release": "npm version ${SEMANTIC:-patch} -m \"Release %s\" && git push && git push --tags && npm publish" + } +} diff --git a/node_modules/safe-buffer/LICENSE b/node_modules/safe-buffer/LICENSE new file mode 100644 index 0000000..0c068ce --- /dev/null +++ b/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/safe-buffer/README.md b/node_modules/safe-buffer/README.md new file mode 100644 index 0000000..e9a81af --- /dev/null +++ b/node_modules/safe-buffer/README.md @@ -0,0 +1,584 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/node_modules/safe-buffer/index.d.ts b/node_modules/safe-buffer/index.d.ts new file mode 100644 index 0000000..e9fed80 --- /dev/null +++ b/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/node_modules/safe-buffer/index.js b/node_modules/safe-buffer/index.js new file mode 100644 index 0000000..f8d3ec9 --- /dev/null +++ b/node_modules/safe-buffer/index.js @@ -0,0 +1,65 @@ +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/node_modules/safe-buffer/package.json b/node_modules/safe-buffer/package.json new file mode 100644 index 0000000..f2869e2 --- /dev/null +++ b/node_modules/safe-buffer/package.json @@ -0,0 +1,51 @@ +{ + "name": "safe-buffer", + "description": "Safer Node.js Buffer API", + "version": "5.2.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "devDependencies": { + "standard": "*", + "tape": "^5.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/semver/LICENSE b/node_modules/semver/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/semver/README.md b/node_modules/semver/README.md new file mode 100644 index 0000000..e952215 --- /dev/null +++ b/node_modules/semver/README.md @@ -0,0 +1,664 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Install + +```bash +npm install semver +```` + +## Usage + +As a node module: + +```js +const semver = require('semver') + +semver.valid('1.2.3') // '1.2.3' +semver.valid('a.b.c') // null +semver.clean(' =v1.2.3 ') // '1.2.3' +semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true +semver.gt('1.2.3', '9.8.7') // false +semver.lt('1.2.3', '9.8.7') // true +semver.minVersion('>=1.0.0') // '1.0.0' +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' +``` + +You can also just load the module for the function that you care about if +you'd like to minimize your footprint. + +```js +// load the whole API at once in a single object +const semver = require('semver') + +// or just load the bits you need +// all of them listed here, just pick and choose what you want + +// classes +const SemVer = require('semver/classes/semver') +const Comparator = require('semver/classes/comparator') +const Range = require('semver/classes/range') + +// functions for working with versions +const semverParse = require('semver/functions/parse') +const semverValid = require('semver/functions/valid') +const semverClean = require('semver/functions/clean') +const semverInc = require('semver/functions/inc') +const semverDiff = require('semver/functions/diff') +const semverMajor = require('semver/functions/major') +const semverMinor = require('semver/functions/minor') +const semverPatch = require('semver/functions/patch') +const semverPrerelease = require('semver/functions/prerelease') +const semverCompare = require('semver/functions/compare') +const semverRcompare = require('semver/functions/rcompare') +const semverCompareLoose = require('semver/functions/compare-loose') +const semverCompareBuild = require('semver/functions/compare-build') +const semverSort = require('semver/functions/sort') +const semverRsort = require('semver/functions/rsort') + +// low-level comparators between versions +const semverGt = require('semver/functions/gt') +const semverLt = require('semver/functions/lt') +const semverEq = require('semver/functions/eq') +const semverNeq = require('semver/functions/neq') +const semverGte = require('semver/functions/gte') +const semverLte = require('semver/functions/lte') +const semverCmp = require('semver/functions/cmp') +const semverCoerce = require('semver/functions/coerce') + +// working with ranges +const semverSatisfies = require('semver/functions/satisfies') +const semverMaxSatisfying = require('semver/ranges/max-satisfying') +const semverMinSatisfying = require('semver/ranges/min-satisfying') +const semverToComparators = require('semver/ranges/to-comparators') +const semverMinVersion = require('semver/ranges/min-version') +const semverValidRange = require('semver/ranges/valid') +const semverOutside = require('semver/ranges/outside') +const semverGtr = require('semver/ranges/gtr') +const semverLtr = require('semver/ranges/ltr') +const semverIntersects = require('semver/ranges/intersects') +const semverSimplifyRange = require('semver/ranges/simplify') +const semverRangeSubset = require('semver/ranges/subset') +``` + +As a command-line utility: + +``` +$ semver -h + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, prerelease, or release. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-n <0|1> + This is the base to be used for the prerelease identifier. + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them. +``` + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. +Support for stripping a leading "v" is kept for compatibility with `v1.0.0` of the SemVer +specification but should not be used anymore. + +## Ranges + +A `version range` is a set of `comparators` that specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. The comparator `>1` is equivalent to `>=2.0.0` and +would match the versions `2.0.0` and `3.1.0`, but not the versions +`1.0.1` or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. +Version `3.4.5` *would* satisfy the range because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose of this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range-matching +semantics. + +Second, a user who has opted into using a prerelease version has +indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +Note that this behavior can be suppressed (treating all prerelease +versions as if they were normal versions, for range-matching) +by setting the `includePrerelease` flag on the options +object to any +[functions](https://github.com/npm/node-semver#functions) that do +range matching. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta') +// '1.2.4-beta.0' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```bash +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +To get out of the prerelease phase, use the `release` option: + +```bash +$ semver 1.2.4-beta.1 -i release +1.2.4 +``` + +#### Prerelease Identifier Base + +The method `.inc` takes an optional parameter 'identifierBase' string +that will let you let your prerelease number as zero-based or one-based. +Set to `false` to omit the prerelease number altogether. +If you do not specify this parameter, it will default to zero-based. + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta', '1') +// '1.2.4-beta.1' +``` + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta', false) +// '1.2.4-beta' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta -n 1 +1.2.4-beta.1 +``` + +```bash +$ semver 1.2.3 -i prerelease --preid beta -n false +1.2.4-beta +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0-0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any non-prerelease version satisfies, unless + `includePrerelease` is specified, in which case any version at all + satisfies) +* `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0-0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero element in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0-0` +* `^0.2.3` := `>=0.2.3 <0.3.0-0` +* `^0.0.3` := `>=0.0.3 <0.0.4-0` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0-0` +* `^0.0.x` := `>=0.0.0 <0.1.0-0` +* `^0.0` := `>=0.0.0 <0.1.0-0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0-0` +* `^0.x` := `>=0.0.0 <1.0.0-0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `options` object argument. All +options in this object are `false` by default. The options supported +are: + +- `loose`: Be more forgiving about not-quite-valid semver strings. + (Any resulting output will always be 100% strict compliant, of + course.) For backwards compatibility reasons, if the `options` + argument is a boolean value instead of an object, it is interpreted + to be the `loose` param. +- `includePrerelease`: Set to suppress the [default + behavior](https://github.com/npm/node-semver#prerelease-tags) of + excluding prerelease tagged versions from ranges unless they are + explicitly opted into. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, releaseType, options, identifier, identifierBase)`: + Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, `prerelease`, or `release`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, `prerelease` will work the + same as `prepatch`. It increments the patch version and then makes a + prerelease. If the input version is already a prerelease it simply + increments it. + * `release` will remove any prerelease part of the version. + * `identifier` can be used to prefix `premajor`, `preminor`, + `prepatch`, or `prerelease` version increments. `identifierBase` + is the base to be used for the `prerelease` identifier. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. +* `intersects(r1, r2, loose)`: Return true if the two supplied ranges + or comparators intersect. +* `parse(v)`: Attempt to parse a string as a semantic version, returning either + a `SemVer` object or `null`. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of `compare`. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions + are equal. Sorts in ascending order if passed to `Array.sort()`. +* `compareLoose(v1, v2)`: Short for `compare(v1, v2, { loose: true })`. +* `diff(v1, v2)`: Returns the difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + +### Sorting + +* `sort(versions)`: Returns a sorted array of versions based on the `compareBuild` + function. +* `rsort(versions)`: The reverse of `sort`. Returns an array of versions based on + the `compareBuild` function in descending order. + +### Comparators + +* `intersects(comparator)`: Return true if the comparators intersect + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid. +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `minVersion(range)`: Return the lowest version that can match + the given range. +* `gtr(version, range)`: Return `true` if the version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if the version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) +* `intersects(range)`: Return true if any of the range comparators intersect. +* `simplifyRange(versions, range)`: Return a "simplified" range that + matches the same items in the `versions` list as the range specified. Note + that it does *not* guarantee that it would match the same versions in all + cases, only for the set of versions provided. This is useful when + generating ranges by joining together multiple versions with `||` + programmatically, to provide the user with something a bit more + ergonomic. If the provided range is shorter in string-length than the + generated range, then that is returned. +* `subset(subRange, superRange)`: Return `true` if the `subRange` range is + entirely contained by the `superRange` range. + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version, options)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver string to +semver. It looks for the first digit in a string and consumes all +remaining characters which satisfy at least a partial semver (e.g., `1`, +`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer +versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All +surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes +`3.4.0`). Only text which lacks digits will fail coercion (`version one` +is not valid). The maximum length for any semver component considered for +coercion is 16 characters; longer components will be ignored +(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any +semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value +components are invalid (`9999999999999999.4.7.4` is likely invalid). + +If the `options.rtl` flag is set, then `coerce` will return the right-most +coercible tuple that does not share an ending index with a longer coercible +tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not +`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of +any other overlapping SemVer tuple. + +If the `options.includePrerelease` flag is set, then the `coerce` result will contain +prerelease and build parts of a version. For example, `1.2.3.4-rc.1+rev.2` +will preserve prerelease `rc.1` and build `rev.2` in the result. + +### Clean + +* `clean(version)`: Clean a string to be a valid semver if possible + +This will return a cleaned and trimmed semver version. If the provided +version is not valid a null will be returned. This does not work for +ranges. + +ex. +* `s.clean(' = v 2.1.5foo')`: `null` +* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean(' = v 2.1.5-foo')`: `null` +* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean('=v2.1.5')`: `'2.1.5'` +* `s.clean(' =v2.1.5')`: `'2.1.5'` +* `s.clean(' 2.1.5 ')`: `'2.1.5'` +* `s.clean('~1.0.0')`: `null` + +## Constants + +As a convenience, helper constants are exported to provide information about what `node-semver` supports: + +### `RELEASE_TYPES` + +- major +- premajor +- minor +- preminor +- patch +- prepatch +- prerelease + +``` +const semver = require('semver'); + +if (semver.RELEASE_TYPES.includes(arbitraryUserInput)) { + console.log('This is a valid release type!'); +} else { + console.warn('This is NOT a valid release type!'); +} +``` + +### `SEMVER_SPEC_VERSION` + +2.0.0 + +``` +const semver = require('semver'); + +console.log('We are currently using the semver specification version:', semver.SEMVER_SPEC_VERSION); +``` + +## Exported Modules + + + +You may pull in just the part of this semver utility that you need if you +are sensitive to packing and tree-shaking concerns. The main +`require('semver')` export uses getter functions to lazily load the parts +of the API that are used. + +The following modules are available: + +* `require('semver')` +* `require('semver/classes')` +* `require('semver/classes/comparator')` +* `require('semver/classes/range')` +* `require('semver/classes/semver')` +* `require('semver/functions/clean')` +* `require('semver/functions/cmp')` +* `require('semver/functions/coerce')` +* `require('semver/functions/compare')` +* `require('semver/functions/compare-build')` +* `require('semver/functions/compare-loose')` +* `require('semver/functions/diff')` +* `require('semver/functions/eq')` +* `require('semver/functions/gt')` +* `require('semver/functions/gte')` +* `require('semver/functions/inc')` +* `require('semver/functions/lt')` +* `require('semver/functions/lte')` +* `require('semver/functions/major')` +* `require('semver/functions/minor')` +* `require('semver/functions/neq')` +* `require('semver/functions/parse')` +* `require('semver/functions/patch')` +* `require('semver/functions/prerelease')` +* `require('semver/functions/rcompare')` +* `require('semver/functions/rsort')` +* `require('semver/functions/satisfies')` +* `require('semver/functions/sort')` +* `require('semver/functions/valid')` +* `require('semver/ranges/gtr')` +* `require('semver/ranges/intersects')` +* `require('semver/ranges/ltr')` +* `require('semver/ranges/max-satisfying')` +* `require('semver/ranges/min-satisfying')` +* `require('semver/ranges/min-version')` +* `require('semver/ranges/outside')` +* `require('semver/ranges/simplify')` +* `require('semver/ranges/subset')` +* `require('semver/ranges/to-comparators')` +* `require('semver/ranges/valid')` + diff --git a/node_modules/semver/bin/semver.js b/node_modules/semver/bin/semver.js new file mode 100644 index 0000000..dbb1bf5 --- /dev/null +++ b/node_modules/semver/bin/semver.js @@ -0,0 +1,191 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +'use strict' + +const argv = process.argv.slice(2) + +let versions = [] + +const range = [] + +let inc = null + +const version = require('../package.json').version + +let loose = false + +let includePrerelease = false + +let coerce = false + +let rtl = false + +let identifier + +let identifierBase + +const semver = require('../') +const parseOptions = require('../internal/parse-options') + +let reverse = false + +let options = {} + +const main = () => { + if (!argv.length) { + return help() + } + while (argv.length) { + let a = argv.shift() + const indexOfEqualSign = a.indexOf('=') + if (indexOfEqualSign !== -1) { + const value = a.slice(indexOfEqualSign + 1) + a = a.slice(0, indexOfEqualSign) + argv.unshift(value) + } + switch (a) { + case '-rv': case '-rev': case '--rev': case '--reverse': + reverse = true + break + case '-l': case '--loose': + loose = true + break + case '-p': case '--include-prerelease': + includePrerelease = true + break + case '-v': case '--version': + versions.push(argv.shift()) + break + case '-i': case '--inc': case '--increment': + switch (argv[0]) { + case 'major': case 'minor': case 'patch': case 'prerelease': + case 'premajor': case 'preminor': case 'prepatch': + case 'release': + inc = argv.shift() + break + default: + inc = 'patch' + break + } + break + case '--preid': + identifier = argv.shift() + break + case '-r': case '--range': + range.push(argv.shift()) + break + case '-n': + identifierBase = argv.shift() + if (identifierBase === 'false') { + identifierBase = false + } + break + case '-c': case '--coerce': + coerce = true + break + case '--rtl': + rtl = true + break + case '--ltr': + rtl = false + break + case '-h': case '--help': case '-?': + return help() + default: + versions.push(a) + break + } + } + + options = parseOptions({ loose, includePrerelease, rtl }) + + versions = versions.map((v) => { + return coerce ? (semver.coerce(v, options) || { version: v }).version : v + }).filter((v) => { + return semver.valid(v) + }) + if (!versions.length) { + return fail() + } + if (inc && (versions.length !== 1 || range.length)) { + return failInc() + } + + for (let i = 0, l = range.length; i < l; i++) { + versions = versions.filter((v) => { + return semver.satisfies(v, range[i], options) + }) + if (!versions.length) { + return fail() + } + } + versions + .sort((a, b) => semver[reverse ? 'rcompare' : 'compare'](a, b, options)) + .map(v => semver.clean(v, options)) + .map(v => inc ? semver.inc(v, inc, options, identifier, identifierBase) : v) + .forEach(v => console.log(v)) +} + +const failInc = () => { + console.error('--inc can only be used on a single version with no range') + fail() +} + +const fail = () => process.exit(1) + +const help = () => console.log( +`SemVer ${version} + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, prerelease, or release. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +-n + Base number to be used for the prerelease identifier. + Can be either 0 or 1, or false to omit the number altogether. + Defaults to 0. + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them.`) + +main() diff --git a/node_modules/semver/classes/comparator.js b/node_modules/semver/classes/comparator.js new file mode 100644 index 0000000..647c1f0 --- /dev/null +++ b/node_modules/semver/classes/comparator.js @@ -0,0 +1,143 @@ +'use strict' + +const ANY = Symbol('SemVer ANY') +// hoisted class for cyclic dependency +class Comparator { + static get ANY () { + return ANY + } + + constructor (comp, options) { + options = parseOptions(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 r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + const m = comp.match(r) + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } + + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[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 = parseOptions(options) + + // Special cases where nothing can possibly be lower + 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 + } + + // Same direction increasing (> or >=) + if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { + return true + } + // Same direction decreasing (< or <=) + if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { + return true + } + // same SemVer and both sides are inclusive (<= or >=) + if ( + (this.semver.version === comp.semver.version) && + this.operator.includes('=') && comp.operator.includes('=')) { + return true + } + // opposite directions less than + if (cmp(this.semver, '<', comp.semver, options) && + this.operator.startsWith('>') && comp.operator.startsWith('<')) { + return true + } + // opposite directions greater than + if (cmp(this.semver, '>', comp.semver, options) && + this.operator.startsWith('<') && comp.operator.startsWith('>')) { + return true + } + return false + } +} + +module.exports = Comparator + +const parseOptions = require('../internal/parse-options') +const { safeRe: re, t } = require('../internal/re') +const cmp = require('../functions/cmp') +const debug = require('../internal/debug') +const SemVer = require('./semver') +const Range = require('./range') diff --git a/node_modules/semver/classes/index.js b/node_modules/semver/classes/index.js new file mode 100644 index 0000000..91c24ec --- /dev/null +++ b/node_modules/semver/classes/index.js @@ -0,0 +1,7 @@ +'use strict' + +module.exports = { + SemVer: require('./semver.js'), + Range: require('./range.js'), + Comparator: require('./comparator.js'), +} diff --git a/node_modules/semver/classes/range.js b/node_modules/semver/classes/range.js new file mode 100644 index 0000000..94629ce --- /dev/null +++ b/node_modules/semver/classes/range.js @@ -0,0 +1,557 @@ +'use strict' + +const SPACE_CHARACTERS = /\s+/g + +// hoisted class for cyclic dependency +class Range { + constructor (range, options) { + options = parseOptions(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) { + // just put it in the set and return + this.raw = range.value + this.set = [[range]] + this.formatted = undefined + return this + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First reduce all whitespace as much as possible so we do not have to rely + // on potentially slow regexes like \s*. This is then stored and used for + // future error messages as well. + this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') + + // First, split on || + this.set = this.raw + .split('||') + // map the range to a 2d array of comparators + .map(r => this.parseRange(r.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length) + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${this.raw}`) + } + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0] + this.set = this.set.filter(c => !isNullSet(c[0])) + if (this.set.length === 0) { + this.set = [first] + } else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c] + break + } + } + } + } + + this.formatted = undefined + } + + get range () { + if (this.formatted === undefined) { + this.formatted = '' + for (let i = 0; i < this.set.length; i++) { + if (i > 0) { + this.formatted += '||' + } + const comps = this.set[i] + for (let k = 0; k < comps.length; k++) { + if (k > 0) { + this.formatted += ' ' + } + this.formatted += comps[k].toString().trim() + } + } + } + return this.formatted + } + + format () { + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = + (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | + (this.options.loose && FLAG_LOOSE) + const memoKey = memoOpts + ':' + range + const cached = cache.get(memoKey) + if (cached) { + return cached + } + + const loose = this.options.loose + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) + debug('hyphen replace', range) + + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + debug('tilde trim', range) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) + debug('caret trim', range) + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + let rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + + if (loose) { + // in loose mode, throw out any that are not valid comparators + rangeList = rangeList.filter(comp => { + debug('loose invalid filter', comp, this.options) + return !!comp.match(re[t.COMPARATORLOOSE]) + }) + } + debug('range list', rangeList) + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + const rangeMap = 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()] + cache.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 i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } +} + +module.exports = Range + +const LRU = require('../internal/lrucache') +const cache = new LRU() + +const parseOptions = require('../internal/parse-options') +const Comparator = require('./comparator') +const debug = require('../internal/debug') +const SemVer = require('./semver') +const { + safeRe: re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace, +} = require('../internal/re') +const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants') + +const isNullSet = c => c.value === '<0.0.0-0' +const isAny = c => c.value === '' + +// take a set of comparators and determine whether there +// exists a version which can satisfy it +const 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 +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +const parseComparator = (comp, options) => { + comp = comp.replace(re[t.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 +} + +const isX = id => !id || id.toLowerCase() === 'x' || id === '*' + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 +// ~0.0.1 --> >=0.0.1 <0.1.0-0 +const replaceTildes = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceTilde(c, options)) + .join(' ') +} + +const replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, (_, M, m, p, pr) => { + debug('tilde', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0` + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` + } else if (pr) { + debug('replaceTilde pr', pr) + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0` + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 +// ^1.2.3 --> >=1.2.3 <2.0.0-0 +// ^1.2.0 --> >=1.2.0 <2.0.0-0 +// ^0.0.1 --> >=0.0.1 <0.0.2-0 +// ^0.1.0 --> >=0.1.0 <0.2.0-0 +const replaceCarets = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceCaret(c, options)) + .join(' ') +} + +const replaceCaret = (comp, options) => { + debug('caret', comp, options) + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + const z = options.includePrerelease ? '-0' : '' + return comp.replace(r, (_, M, m, p, pr) => { + debug('caret', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0` + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0` + } + } + + debug('caret return', ret) + return ret + }) +} + +const replaceXRanges = (comp, options) => { + debug('replaceXRanges', comp, options) + return comp + .split(/\s+/) + .map((c) => replaceXRange(c, options)) + .join(' ') +} + +const replaceXRange = (comp, options) => { + comp = comp.trim() + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + const xM = isX(M) + const xm = xM || isX(m) + const xp = xm || isX(p) + const anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + if (gtlt === '<') { + pr = '-0' + } + + ret = `${gtlt + M}.${m}.${p}${pr}` + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0` + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +const replaceStars = (comp, options) => { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp + .trim() + .replace(re[t.STAR], '') +} + +const replaceGTE0 = (comp, options) => { + debug('replaceGTE0', comp, options) + return comp + .trim() + .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') +} + +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 +// TODO build? +const 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() +} + +const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === Comparator.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} diff --git a/node_modules/semver/classes/semver.js b/node_modules/semver/classes/semver.js new file mode 100644 index 0000000..92254be --- /dev/null +++ b/node_modules/semver/classes/semver.js @@ -0,0 +1,333 @@ +'use strict' + +const debug = require('../internal/debug') +const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants') +const { safeRe: re, t } = require('../internal/re') + +const parseOptions = require('../internal/parse-options') +const { compareIdentifiers } = require('../internal/identifiers') +class SemVer { + constructor (version, options) { + options = parseOptions(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 isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease + + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[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') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[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 = m[5] ? m[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) + } + + // NOT having a prerelease is > having one + 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 i = 0 + do { + const a = this.prerelease[i] + const b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + let i = 0 + do { + const a = this.build[i] + const b = other.build[i] + debug('build compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // 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') + } + // Avoid an invalid semver results + if (identifier) { + const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.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': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + 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 is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + 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 is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + 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 i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + if (identifier === this.prerelease.join('.') && identifierBase === false) { + throw new Error('invalid increment argument: identifier already exists') + } + this.prerelease.push(base) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + 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 diff --git a/node_modules/semver/functions/clean.js b/node_modules/semver/functions/clean.js new file mode 100644 index 0000000..79703d6 --- /dev/null +++ b/node_modules/semver/functions/clean.js @@ -0,0 +1,8 @@ +'use strict' + +const parse = require('./parse') +const clean = (version, options) => { + const s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} +module.exports = clean diff --git a/node_modules/semver/functions/cmp.js b/node_modules/semver/functions/cmp.js new file mode 100644 index 0000000..77487dc --- /dev/null +++ b/node_modules/semver/functions/cmp.js @@ -0,0 +1,54 @@ +'use strict' + +const eq = require('./eq') +const neq = require('./neq') +const gt = require('./gt') +const gte = require('./gte') +const lt = require('./lt') +const lte = require('./lte') + +const cmp = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a === b + + case '!==': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } +} +module.exports = cmp diff --git a/node_modules/semver/functions/coerce.js b/node_modules/semver/functions/coerce.js new file mode 100644 index 0000000..cfe0275 --- /dev/null +++ b/node_modules/semver/functions/coerce.js @@ -0,0 +1,62 @@ +'use strict' + +const SemVer = require('../classes/semver') +const parse = require('./parse') +const { safeRe: re, t } = require('../internal/re') + +const 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 ? re[t.COERCEFULL] : re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.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 + } + // leave it in a clean state + 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 parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) +} +module.exports = coerce diff --git a/node_modules/semver/functions/compare-build.js b/node_modules/semver/functions/compare-build.js new file mode 100644 index 0000000..99157cf --- /dev/null +++ b/node_modules/semver/functions/compare-build.js @@ -0,0 +1,9 @@ +'use strict' + +const SemVer = require('../classes/semver') +const compareBuild = (a, b, loose) => { + const versionA = new SemVer(a, loose) + const versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) +} +module.exports = compareBuild diff --git a/node_modules/semver/functions/compare-loose.js b/node_modules/semver/functions/compare-loose.js new file mode 100644 index 0000000..7531634 --- /dev/null +++ b/node_modules/semver/functions/compare-loose.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const compareLoose = (a, b) => compare(a, b, true) +module.exports = compareLoose diff --git a/node_modules/semver/functions/compare.js b/node_modules/semver/functions/compare.js new file mode 100644 index 0000000..63d8090 --- /dev/null +++ b/node_modules/semver/functions/compare.js @@ -0,0 +1,7 @@ +'use strict' + +const SemVer = require('../classes/semver') +const compare = (a, b, loose) => + new SemVer(a, loose).compare(new SemVer(b, loose)) + +module.exports = compare diff --git a/node_modules/semver/functions/diff.js b/node_modules/semver/functions/diff.js new file mode 100644 index 0000000..04e064e --- /dev/null +++ b/node_modules/semver/functions/diff.js @@ -0,0 +1,60 @@ +'use strict' + +const parse = require('./parse.js') + +const diff = (version1, version2) => { + const v1 = parse(version1, null, true) + const v2 = parse(version2, null, true) + const comparison = v1.compare(v2) + + if (comparison === 0) { + return null + } + + const v1Higher = comparison > 0 + const highVersion = v1Higher ? v1 : v2 + const lowVersion = v1Higher ? v2 : v1 + const highHasPre = !!highVersion.prerelease.length + const lowHasPre = !!lowVersion.prerelease.length + + if (lowHasPre && !highHasPre) { + // Going from prerelease -> no prerelease requires some special casing + + // If the low version has only a major, then it will always be a major + // Some examples: + // 1.0.0-1 -> 1.0.0 + // 1.0.0-1 -> 1.1.1 + // 1.0.0-1 -> 2.0.0 + if (!lowVersion.patch && !lowVersion.minor) { + return 'major' + } + + // If the main part has no difference + if (lowVersion.compareMain(highVersion) === 0) { + if (lowVersion.minor && !lowVersion.patch) { + return 'minor' + } + return 'patch' + } + } + + // add the `pre` prefix if we are going to a prerelease version + const prefix = highHasPre ? 'pre' : '' + + if (v1.major !== v2.major) { + return prefix + 'major' + } + + if (v1.minor !== v2.minor) { + return prefix + 'minor' + } + + if (v1.patch !== v2.patch) { + return prefix + 'patch' + } + + // high and low are preleases + return 'prerelease' +} + +module.exports = diff diff --git a/node_modules/semver/functions/eq.js b/node_modules/semver/functions/eq.js new file mode 100644 index 0000000..5f0eead --- /dev/null +++ b/node_modules/semver/functions/eq.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const eq = (a, b, loose) => compare(a, b, loose) === 0 +module.exports = eq diff --git a/node_modules/semver/functions/gt.js b/node_modules/semver/functions/gt.js new file mode 100644 index 0000000..84a57dd --- /dev/null +++ b/node_modules/semver/functions/gt.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const gt = (a, b, loose) => compare(a, b, loose) > 0 +module.exports = gt diff --git a/node_modules/semver/functions/gte.js b/node_modules/semver/functions/gte.js new file mode 100644 index 0000000..7c52bdf --- /dev/null +++ b/node_modules/semver/functions/gte.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const gte = (a, b, loose) => compare(a, b, loose) >= 0 +module.exports = gte diff --git a/node_modules/semver/functions/inc.js b/node_modules/semver/functions/inc.js new file mode 100644 index 0000000..ff999e9 --- /dev/null +++ b/node_modules/semver/functions/inc.js @@ -0,0 +1,21 @@ +'use strict' + +const SemVer = require('../classes/semver') + +const inc = (version, release, options, identifier, identifierBase) => { + if (typeof (options) === 'string') { + identifierBase = identifier + identifier = options + options = undefined + } + + try { + return new SemVer( + version instanceof SemVer ? version.version : version, + options + ).inc(release, identifier, identifierBase).version + } catch (er) { + return null + } +} +module.exports = inc diff --git a/node_modules/semver/functions/lt.js b/node_modules/semver/functions/lt.js new file mode 100644 index 0000000..2fb32a0 --- /dev/null +++ b/node_modules/semver/functions/lt.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const lt = (a, b, loose) => compare(a, b, loose) < 0 +module.exports = lt diff --git a/node_modules/semver/functions/lte.js b/node_modules/semver/functions/lte.js new file mode 100644 index 0000000..da9ee8f --- /dev/null +++ b/node_modules/semver/functions/lte.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const lte = (a, b, loose) => compare(a, b, loose) <= 0 +module.exports = lte diff --git a/node_modules/semver/functions/major.js b/node_modules/semver/functions/major.js new file mode 100644 index 0000000..e6d08dc --- /dev/null +++ b/node_modules/semver/functions/major.js @@ -0,0 +1,5 @@ +'use strict' + +const SemVer = require('../classes/semver') +const major = (a, loose) => new SemVer(a, loose).major +module.exports = major diff --git a/node_modules/semver/functions/minor.js b/node_modules/semver/functions/minor.js new file mode 100644 index 0000000..9e70ffd --- /dev/null +++ b/node_modules/semver/functions/minor.js @@ -0,0 +1,5 @@ +'use strict' + +const SemVer = require('../classes/semver') +const minor = (a, loose) => new SemVer(a, loose).minor +module.exports = minor diff --git a/node_modules/semver/functions/neq.js b/node_modules/semver/functions/neq.js new file mode 100644 index 0000000..84326b7 --- /dev/null +++ b/node_modules/semver/functions/neq.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const neq = (a, b, loose) => compare(a, b, loose) !== 0 +module.exports = neq diff --git a/node_modules/semver/functions/parse.js b/node_modules/semver/functions/parse.js new file mode 100644 index 0000000..d544d33 --- /dev/null +++ b/node_modules/semver/functions/parse.js @@ -0,0 +1,18 @@ +'use strict' + +const SemVer = require('../classes/semver') +const parse = (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 = parse diff --git a/node_modules/semver/functions/patch.js b/node_modules/semver/functions/patch.js new file mode 100644 index 0000000..7675162 --- /dev/null +++ b/node_modules/semver/functions/patch.js @@ -0,0 +1,5 @@ +'use strict' + +const SemVer = require('../classes/semver') +const patch = (a, loose) => new SemVer(a, loose).patch +module.exports = patch diff --git a/node_modules/semver/functions/prerelease.js b/node_modules/semver/functions/prerelease.js new file mode 100644 index 0000000..b8fe1db --- /dev/null +++ b/node_modules/semver/functions/prerelease.js @@ -0,0 +1,8 @@ +'use strict' + +const parse = require('./parse') +const prerelease = (version, options) => { + const parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} +module.exports = prerelease diff --git a/node_modules/semver/functions/rcompare.js b/node_modules/semver/functions/rcompare.js new file mode 100644 index 0000000..8e1c222 --- /dev/null +++ b/node_modules/semver/functions/rcompare.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const rcompare = (a, b, loose) => compare(b, a, loose) +module.exports = rcompare diff --git a/node_modules/semver/functions/rsort.js b/node_modules/semver/functions/rsort.js new file mode 100644 index 0000000..5d3d200 --- /dev/null +++ b/node_modules/semver/functions/rsort.js @@ -0,0 +1,5 @@ +'use strict' + +const compareBuild = require('./compare-build') +const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) +module.exports = rsort diff --git a/node_modules/semver/functions/satisfies.js b/node_modules/semver/functions/satisfies.js new file mode 100644 index 0000000..a0264a2 --- /dev/null +++ b/node_modules/semver/functions/satisfies.js @@ -0,0 +1,12 @@ +'use strict' + +const Range = require('../classes/range') +const satisfies = (version, range, options) => { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} +module.exports = satisfies diff --git a/node_modules/semver/functions/sort.js b/node_modules/semver/functions/sort.js new file mode 100644 index 0000000..edb24b1 --- /dev/null +++ b/node_modules/semver/functions/sort.js @@ -0,0 +1,5 @@ +'use strict' + +const compareBuild = require('./compare-build') +const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) +module.exports = sort diff --git a/node_modules/semver/functions/valid.js b/node_modules/semver/functions/valid.js new file mode 100644 index 0000000..0db67ed --- /dev/null +++ b/node_modules/semver/functions/valid.js @@ -0,0 +1,8 @@ +'use strict' + +const parse = require('./parse') +const valid = (version, options) => { + const v = parse(version, options) + return v ? v.version : null +} +module.exports = valid diff --git a/node_modules/semver/index.js b/node_modules/semver/index.js new file mode 100644 index 0000000..285662a --- /dev/null +++ b/node_modules/semver/index.js @@ -0,0 +1,91 @@ +'use strict' + +// just pre-load all the stuff that index.js lazily exports +const internalRe = require('./internal/re') +const constants = require('./internal/constants') +const SemVer = require('./classes/semver') +const identifiers = require('./internal/identifiers') +const parse = require('./functions/parse') +const valid = require('./functions/valid') +const clean = require('./functions/clean') +const inc = require('./functions/inc') +const diff = require('./functions/diff') +const major = require('./functions/major') +const minor = require('./functions/minor') +const patch = require('./functions/patch') +const prerelease = require('./functions/prerelease') +const compare = require('./functions/compare') +const rcompare = require('./functions/rcompare') +const compareLoose = require('./functions/compare-loose') +const compareBuild = require('./functions/compare-build') +const sort = require('./functions/sort') +const rsort = require('./functions/rsort') +const gt = require('./functions/gt') +const lt = require('./functions/lt') +const eq = require('./functions/eq') +const neq = require('./functions/neq') +const gte = require('./functions/gte') +const lte = require('./functions/lte') +const cmp = require('./functions/cmp') +const coerce = require('./functions/coerce') +const Comparator = require('./classes/comparator') +const Range = require('./classes/range') +const satisfies = require('./functions/satisfies') +const toComparators = require('./ranges/to-comparators') +const maxSatisfying = require('./ranges/max-satisfying') +const minSatisfying = require('./ranges/min-satisfying') +const minVersion = require('./ranges/min-version') +const validRange = require('./ranges/valid') +const outside = require('./ranges/outside') +const gtr = require('./ranges/gtr') +const ltr = require('./ranges/ltr') +const intersects = require('./ranges/intersects') +const simplifyRange = require('./ranges/simplify') +const subset = require('./ranges/subset') +module.exports = { + parse, + 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, +} diff --git a/node_modules/semver/internal/constants.js b/node_modules/semver/internal/constants.js new file mode 100644 index 0000000..6d1db91 --- /dev/null +++ b/node_modules/semver/internal/constants.js @@ -0,0 +1,37 @@ +'use strict' + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +const SEMVER_SPEC_VERSION = '2.0.0' + +const MAX_LENGTH = 256 +const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || +/* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +const MAX_SAFE_COMPONENT_LENGTH = 16 + +// Max safe length for a build identifier. The max length minus 6 characters for +// the shortest version with a build 0.0.0+BUILD. +const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 + +const 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: 0b001, + FLAG_LOOSE: 0b010, +} diff --git a/node_modules/semver/internal/debug.js b/node_modules/semver/internal/debug.js new file mode 100644 index 0000000..20d1e9d --- /dev/null +++ b/node_modules/semver/internal/debug.js @@ -0,0 +1,11 @@ +'use strict' + +const 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 diff --git a/node_modules/semver/internal/identifiers.js b/node_modules/semver/internal/identifiers.js new file mode 100644 index 0000000..d053472 --- /dev/null +++ b/node_modules/semver/internal/identifiers.js @@ -0,0 +1,29 @@ +'use strict' + +const numeric = /^[0-9]+$/ +const compareIdentifiers = (a, b) => { + if (typeof a === 'number' && typeof b === 'number') { + return a === b ? 0 : a < b ? -1 : 1 + } + + const anum = numeric.test(a) + const bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) + +module.exports = { + compareIdentifiers, + rcompareIdentifiers, +} diff --git a/node_modules/semver/internal/lrucache.js b/node_modules/semver/internal/lrucache.js new file mode 100644 index 0000000..b8bf526 --- /dev/null +++ b/node_modules/semver/internal/lrucache.js @@ -0,0 +1,42 @@ +'use strict' + +class LRUCache { + constructor () { + this.max = 1000 + this.map = new Map() + } + + get (key) { + const value = this.map.get(key) + if (value === undefined) { + return undefined + } else { + // Remove the key from the map and add it to the end + 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 !== undefined) { + // If cache is full, delete the least recently used item + 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 diff --git a/node_modules/semver/internal/parse-options.js b/node_modules/semver/internal/parse-options.js new file mode 100644 index 0000000..5295454 --- /dev/null +++ b/node_modules/semver/internal/parse-options.js @@ -0,0 +1,17 @@ +'use strict' + +// parse out just the options we care about +const looseOption = Object.freeze({ loose: true }) +const emptyOpts = Object.freeze({ }) +const parseOptions = options => { + if (!options) { + return emptyOpts + } + + if (typeof options !== 'object') { + return looseOption + } + + return options +} +module.exports = parseOptions diff --git a/node_modules/semver/internal/re.js b/node_modules/semver/internal/re.js new file mode 100644 index 0000000..4758c58 --- /dev/null +++ b/node_modules/semver/internal/re.js @@ -0,0 +1,223 @@ +'use strict' + +const { + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_LENGTH, +} = require('./constants') +const debug = require('./debug') +exports = module.exports = {} + +// The actual regexps go on exports.re +const re = exports.re = [] +const safeRe = exports.safeRe = [] +const src = exports.src = [] +const safeSrc = exports.safeSrc = [] +const t = exports.t = {} +let R = 0 + +const LETTERDASHNUMBER = '[a-zA-Z0-9-]' + +// Replace some greedy regex tokens to prevent regex dos issues. These regex are +// used internally via the safeRe object since all inputs in this library get +// normalized first to trim and collapse all extra whitespace. The original +// regexes are exported for userland consumption and lower level usage. A +// future breaking change could export the safer regex only with a note that +// all input should have extra whitespace removed. +const safeRegexReplacements = [ + ['\\s', 1], + ['\\d', MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], +] + +const makeSafeRegex = (value) => { + for (const [token, max] of safeRegexReplacements) { + value = value + .split(`${token}*`).join(`${token}{0,${max}}`) + .split(`${token}+`).join(`${token}{1,${max}}`) + } + return value +} + +const createToken = (name, value, isGlobal) => { + const safe = makeSafeRegex(value) + const index = R++ + debug(name, index, value) + t[name] = index + src[index] = value + safeSrc[index] = safe + re[index] = new RegExp(value, isGlobal ? 'g' : undefined) + safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) +} + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') +createToken('NUMERICIDENTIFIERLOOSE', '\\d+') + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) + +// ## Main Version +// Three dot-separated numeric identifiers. + +createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`) + +createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. +// Non-numberic identifiers include numberic identifiers but can be longer. +// Therefore non-numberic identifiers must go first. + +createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER] +}|${src[t.NUMERICIDENTIFIER]})`) + +createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER] +}|${src[t.NUMERICIDENTIFIERLOOSE]})`) + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) + +createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`) + +createToken('FULL', `^${src[t.FULLPLAIN]}$`) + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`) + +createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) + +createToken('GTLT', '((?:<|>)?=?)') + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) +createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) + +createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) +createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +createToken('COERCEPLAIN', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) +createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) +createToken('COERCEFULL', src[t.COERCEPLAIN] + + `(?:${src[t.PRERELEASE]})?` + + `(?:${src[t.BUILD]})?` + + `(?:$|[^\\d])`) +createToken('COERCERTL', src[t.COERCE], true) +createToken('COERCERTLFULL', src[t.COERCEFULL], true) + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +createToken('LONETILDE', '(?:~>?)') + +createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) +exports.tildeTrimReplace = '$1~' + +createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) +createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +createToken('LONECARET', '(?:\\^)') + +createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) +exports.caretTrimReplace = '$1^' + +createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) +createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) +createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) +exports.comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`) + +createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`) + +// Star ranges basically just allow anything at all. +createToken('STAR', '(<|>)?=?\\s*\\*') +// >=0.0.0 is like a star +createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') +createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') diff --git a/node_modules/semver/package.json b/node_modules/semver/package.json new file mode 100644 index 0000000..2b8cada --- /dev/null +++ b/node_modules/semver/package.json @@ -0,0 +1,78 @@ +{ + "name": "semver", + "version": "7.7.3", + "description": "The semantic version parser used by npm.", + "main": "index.js", + "scripts": { + "test": "tap", + "snap": "tap", + "lint": "npm run eslint", + "postlint": "template-oss-check", + "lintfix": "npm run eslint -- --fix", + "posttest": "npm run lint", + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" + }, + "devDependencies": { + "@npmcli/eslint-config": "^5.0.0", + "@npmcli/template-oss": "4.25.1", + "benchmark": "^2.1.4", + "tap": "^16.0.0" + }, + "license": "ISC", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/node-semver.git" + }, + "bin": { + "semver": "bin/semver.js" + }, + "files": [ + "bin/", + "lib/", + "classes/", + "functions/", + "internal/", + "ranges/", + "index.js", + "preload.js", + "range.bnf" + ], + "tap": { + "timeout": 30, + "coverage-map": "map.js", + "nyc-arg": [ + "--exclude", + "tap-snapshots/**" + ] + }, + "engines": { + "node": ">=10" + }, + "author": "GitHub Inc.", + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "version": "4.25.1", + "engines": ">=10", + "distPaths": [ + "classes/", + "functions/", + "internal/", + "ranges/", + "index.js", + "preload.js", + "range.bnf" + ], + "allowPaths": [ + "/classes/", + "/functions/", + "/internal/", + "/ranges/", + "/index.js", + "/preload.js", + "/range.bnf", + "/benchmarks" + ], + "publish": "true" + } +} diff --git a/node_modules/semver/preload.js b/node_modules/semver/preload.js new file mode 100644 index 0000000..e6c47b9 --- /dev/null +++ b/node_modules/semver/preload.js @@ -0,0 +1,4 @@ +'use strict' + +// XXX remove in v8 or beyond +module.exports = require('./index.js') diff --git a/node_modules/semver/range.bnf b/node_modules/semver/range.bnf new file mode 100644 index 0000000..d4c6ae0 --- /dev/null +++ b/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | [1-9] ( [0-9] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/node_modules/semver/ranges/gtr.js b/node_modules/semver/ranges/gtr.js new file mode 100644 index 0000000..0e7601f --- /dev/null +++ b/node_modules/semver/ranges/gtr.js @@ -0,0 +1,6 @@ +'use strict' + +// Determine if version is greater than all the versions possible in the range. +const outside = require('./outside') +const gtr = (version, range, options) => outside(version, range, '>', options) +module.exports = gtr diff --git a/node_modules/semver/ranges/intersects.js b/node_modules/semver/ranges/intersects.js new file mode 100644 index 0000000..917be7e --- /dev/null +++ b/node_modules/semver/ranges/intersects.js @@ -0,0 +1,9 @@ +'use strict' + +const Range = require('../classes/range') +const intersects = (r1, r2, options) => { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2, options) +} +module.exports = intersects diff --git a/node_modules/semver/ranges/ltr.js b/node_modules/semver/ranges/ltr.js new file mode 100644 index 0000000..aa5e568 --- /dev/null +++ b/node_modules/semver/ranges/ltr.js @@ -0,0 +1,6 @@ +'use strict' + +const outside = require('./outside') +// Determine if version is less than all the versions possible in the range +const ltr = (version, range, options) => outside(version, range, '<', options) +module.exports = ltr diff --git a/node_modules/semver/ranges/max-satisfying.js b/node_modules/semver/ranges/max-satisfying.js new file mode 100644 index 0000000..01fe5ae --- /dev/null +++ b/node_modules/semver/ranges/max-satisfying.js @@ -0,0 +1,27 @@ +'use strict' + +const SemVer = require('../classes/semver') +const Range = require('../classes/range') + +const 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((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} +module.exports = maxSatisfying diff --git a/node_modules/semver/ranges/min-satisfying.js b/node_modules/semver/ranges/min-satisfying.js new file mode 100644 index 0000000..af89c8e --- /dev/null +++ b/node_modules/semver/ranges/min-satisfying.js @@ -0,0 +1,26 @@ +'use strict' + +const SemVer = require('../classes/semver') +const Range = require('../classes/range') +const 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((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} +module.exports = minSatisfying diff --git a/node_modules/semver/ranges/min-version.js b/node_modules/semver/ranges/min-version.js new file mode 100644 index 0000000..09a65aa --- /dev/null +++ b/node_modules/semver/ranges/min-version.js @@ -0,0 +1,63 @@ +'use strict' + +const SemVer = require('../classes/semver') +const Range = require('../classes/range') +const gt = require('../functions/gt') + +const 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 i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let setMin = null + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + 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 '<=': + /* Ignore maximum versions */ + 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 diff --git a/node_modules/semver/ranges/outside.js b/node_modules/semver/ranges/outside.js new file mode 100644 index 0000000..ca74421 --- /dev/null +++ b/node_modules/semver/ranges/outside.js @@ -0,0 +1,82 @@ +'use strict' + +const SemVer = require('../classes/semver') +const Comparator = require('../classes/comparator') +const { ANY } = Comparator +const Range = require('../classes/range') +const satisfies = require('../functions/satisfies') +const gt = require('../functions/gt') +const lt = require('../functions/lt') +const lte = require('../functions/lte') +const gte = require('../functions/gte') + +const 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 it satisfies the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + 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 the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + 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 diff --git a/node_modules/semver/ranges/simplify.js b/node_modules/semver/ranges/simplify.js new file mode 100644 index 0000000..262732e --- /dev/null +++ b/node_modules/semver/ranges/simplify.js @@ -0,0 +1,49 @@ +'use strict' + +// given a set of versions and a range, create a "simplified" range +// that includes the same versions that the original range does +// If the original range is shorter than the simplified one, return that. +const satisfies = require('../functions/satisfies.js') +const compare = require('../functions/compare.js') +module.exports = (versions, range, options) => { + const set = [] + let first = null + let prev = null + const v = versions.sort((a, b) => compare(a, b, options)) + for (const version of v) { + const included = satisfies(version, range, options) + if (included) { + prev = version + if (!first) { + first = version + } + } else { + if (prev) { + set.push([first, prev]) + } + prev = null + first = null + } + } + if (first) { + set.push([first, null]) + } + + const ranges = [] + for (const [min, max] of set) { + if (min === max) { + ranges.push(min) + } else if (!max && min === v[0]) { + ranges.push('*') + } else if (!max) { + ranges.push(`>=${min}`) + } else if (min === v[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 +} diff --git a/node_modules/semver/ranges/subset.js b/node_modules/semver/ranges/subset.js new file mode 100644 index 0000000..2c49aef --- /dev/null +++ b/node_modules/semver/ranges/subset.js @@ -0,0 +1,249 @@ +'use strict' + +const Range = require('../classes/range.js') +const Comparator = require('../classes/comparator.js') +const { ANY } = Comparator +const satisfies = require('../functions/satisfies.js') +const compare = require('../functions/compare.js') + +// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: +// - Every simple range `r1, r2, ...` is a null set, OR +// - Every simple range `r1, r2, ...` which is not a null set is a subset of +// some `R1, R2, ...` +// +// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: +// - If c is only the ANY comparator +// - If C is only the ANY comparator, return true +// - Else if in prerelease mode, return false +// - else replace c with `[>=0.0.0]` +// - If C is only the ANY comparator +// - if in prerelease mode, return true +// - else replace C with `[>=0.0.0]` +// - Let EQ be the set of = comparators in c +// - If EQ is more than one, return true (null set) +// - Let GT be the highest > or >= comparator in c +// - Let LT be the lowest < or <= comparator in c +// - If GT and LT, and GT.semver > LT.semver, return true (null set) +// - If any C is a = range, and GT or LT are set, return false +// - If EQ +// - If GT, and EQ does not satisfy GT, return true (null set) +// - If LT, and EQ does not satisfy LT, return true (null set) +// - If EQ satisfies every C, return true +// - Else return false +// - If GT +// - If GT.semver is lower than any > or >= comp in C, return false +// - If GT is >=, and GT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the GT.semver tuple, return false +// - If LT +// - If LT.semver is greater than any < or <= comp in C, return false +// - If LT is <=, and LT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the LT.semver tuple, return false +// - Else return true + +const 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 + } + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) { + return false + } + } + return true +} + +const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] +const minimumVersion = [new Comparator('>=0.0.0')] + +const 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 = new Set() + let gt, lt + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') { + gt = higherGT(gt, c, options) + } else if (c.operator === '<' || c.operator === '<=') { + lt = lowerLT(lt, c, options) + } else { + eqSet.add(c.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 + } + } + + // will iterate one or zero times + 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 c of dom) { + if (!satisfies(eq, String(c), options)) { + return false + } + } + + return true + } + + let higher, lower + let hasDomLT, hasDomGT + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options) + if (higher === c && higher !== gt) { + return false + } + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { + return false + } + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options) + if (lower === c && lower !== lt) { + return false + } + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { + return false + } + } + if (!c.operator && (lt || gt) && gtltComp !== 0) { + return false + } + } + + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) { + return false + } + + if (lt && hasDomGT && !gt && gtltComp !== 0) { + return false + } + + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) { + return false + } + + return true +} + +// >=1.2.3 is lower than >1.2.3 +const higherGT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a +} + +// <=1.2.3 is higher than <1.2.3 +const lowerLT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a +} + +module.exports = subset diff --git a/node_modules/semver/ranges/to-comparators.js b/node_modules/semver/ranges/to-comparators.js new file mode 100644 index 0000000..5be2519 --- /dev/null +++ b/node_modules/semver/ranges/to-comparators.js @@ -0,0 +1,10 @@ +'use strict' + +const Range = require('../classes/range') + +// Mostly just for testing and legacy API reasons +const toComparators = (range, options) => + new Range(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) + +module.exports = toComparators diff --git a/node_modules/semver/ranges/valid.js b/node_modules/semver/ranges/valid.js new file mode 100644 index 0000000..cc6b0e9 --- /dev/null +++ b/node_modules/semver/ranges/valid.js @@ -0,0 +1,13 @@ +'use strict' + +const Range = require('../classes/range') +const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} +module.exports = validRange diff --git a/node_modules/stream-events/index.d.ts b/node_modules/stream-events/index.d.ts new file mode 100644 index 0000000..56ed748 --- /dev/null +++ b/node_modules/stream-events/index.d.ts @@ -0,0 +1,5 @@ +import { Stream } from "stream"; +declare function StreamEvents(stream: StreamType) + : StreamType; +declare namespace StreamEvents { } +export = StreamEvents diff --git a/node_modules/stream-events/index.js b/node_modules/stream-events/index.js new file mode 100644 index 0000000..28d50a6 --- /dev/null +++ b/node_modules/stream-events/index.js @@ -0,0 +1,30 @@ +'use strict'; + +var stubs = require('stubs') + +/* + * StreamEvents can be used 2 ways: + * + * 1: + * function MyStream() { + * require('stream-events').call(this) + * } + * + * 2: + * require('stream-events')(myStream) + */ +function StreamEvents(stream) { + stream = stream || this + + var cfg = { + callthrough: true, + calls: 1 + } + + stubs(stream, '_read', cfg, stream.emit.bind(stream, 'reading')) + stubs(stream, '_write', cfg, stream.emit.bind(stream, 'writing')) + + return stream +} + +module.exports = StreamEvents diff --git a/node_modules/stream-events/package.json b/node_modules/stream-events/package.json new file mode 100644 index 0000000..bd6c778 --- /dev/null +++ b/node_modules/stream-events/package.json @@ -0,0 +1,38 @@ +{ + "name": "stream-events", + "version": "1.0.5", + "description": "Get an event when you're being sent data or asked for it.", + "main": "index.js", + "types": "index.d.ts", + "files": [ + "index.js", + "index.d.ts" + ], + "scripts": { + "test": "node ./test" + }, + "repository": { + "type": "git", + "url": "https://github.com/stephenplusplus/stream-events" + }, + "keywords": [ + "stream", + "events", + "read", + "write", + "duplexify", + "lazy-stream" + ], + "author": "Stephen Sawchuk", + "license": "MIT", + "bugs": { + "url": "https://github.com/stephenplusplus/stream-events/issues" + }, + "homepage": "https://github.com/stephenplusplus/stream-events", + "devDependencies": { + "duplexify": "^3.2.0" + }, + "dependencies": { + "stubs": "^3.0.0" + } +} diff --git a/node_modules/stream-events/readme.md b/node_modules/stream-events/readme.md new file mode 100644 index 0000000..695a7ce --- /dev/null +++ b/node_modules/stream-events/readme.md @@ -0,0 +1,64 @@ +# stream-events + +> Get an event when you're being sent data or asked for it. + +## About + +This is just a simple thing that tells you when `_read` and `_write` have been called, saving you the trouble of writing this yourself. You receive two events `reading` and `writing`-- no magic is performed. + +This works well with [duplexify](https://github.com/mafintosh/duplexify) or lazy streams, so you can wait until you know you're being used as a stream to do something asynchronous, such as fetching an API token. + + +## Use +```sh +$ npm install --save stream-events +``` +```js +var stream = require('stream') +var streamEvents = require('stream-events') +var util = require('util') + +function MyStream() { + stream.Duplex.call(this) + streamEvents.call(this) +} +util.inherits(MyStream, stream.Duplex) + +MyStream.prototype._read = function(chunk) { + console.log('_read called as usual') + this.push(new Buffer(chunk)) + this.push(null) +} + +MyStream.prototype._write = function() { + console.log('_write called as usual') +} + +var stream = new MyStream + +stream.on('reading', function() { + console.log('stream is being asked for data') +}) + +stream.on('writing', function() { + console.log('stream is being sent data') +}) + +stream.pipe(stream) +``` + +### Using with Duplexify +```js +var duplexify = require('duplexify') +var streamEvents = require('stream-events') +var fs = require('fs') + +var dup = streamEvents(duplexify()) + +dup.on('writing', function() { + // do something async + dup.setWritable(/*writable stream*/) +}) + +fs.createReadStream('file').pipe(dup) +``` \ No newline at end of file diff --git a/node_modules/stream-shift/.github/workflows/test.yml b/node_modules/stream-shift/.github/workflows/test.yml new file mode 100644 index 0000000..9b94272 --- /dev/null +++ b/node_modules/stream-shift/.github/workflows/test.yml @@ -0,0 +1,23 @@ +name: Build Status +on: + push: + branches: + - master + pull_request: + branches: + - master +jobs: + build: + strategy: + matrix: + node-version: [lts/*] + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v3 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v3 + with: + node-version: ${{ matrix.node-version }} + - run: npm install + - run: npm test diff --git a/node_modules/stream-shift/LICENSE b/node_modules/stream-shift/LICENSE new file mode 100644 index 0000000..bae9da7 --- /dev/null +++ b/node_modules/stream-shift/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Mathias Buus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/stream-shift/README.md b/node_modules/stream-shift/README.md new file mode 100644 index 0000000..d9cc2d9 --- /dev/null +++ b/node_modules/stream-shift/README.md @@ -0,0 +1,25 @@ +# stream-shift + +Returns the next buffer/object in a stream's readable queue + +``` +npm install stream-shift +``` + +[![build status](http://img.shields.io/travis/mafintosh/stream-shift.svg?style=flat)](http://travis-ci.org/mafintosh/stream-shift) + +## Usage + +``` js +var shift = require('stream-shift') + +console.log(shift(someStream)) // first item in its buffer +``` + +## Credit + +Thanks [@dignifiedquire](https://github.com/dignifiedquire) for making this work on node 6 + +## License + +MIT diff --git a/node_modules/stream-shift/index.js b/node_modules/stream-shift/index.js new file mode 100644 index 0000000..566df88 --- /dev/null +++ b/node_modules/stream-shift/index.js @@ -0,0 +1,21 @@ +module.exports = shift + +function shift (stream) { + var rs = stream._readableState + if (!rs) return null + return (rs.objectMode || typeof stream._duplexState === 'number') ? stream.read() : stream.read(getStateLength(rs)) +} + +function getStateLength (state) { + if (state.buffer.length) { + var idx = state.bufferIndex || 0 + // Since node 6.3.0 state.buffer is a BufferList not an array + if (state.buffer.head) { + return state.buffer.head.data.length + } else if (state.buffer.length - idx > 0 && state.buffer[idx]) { + return state.buffer[idx].length + } + } + + return state.length +} diff --git a/node_modules/stream-shift/package.json b/node_modules/stream-shift/package.json new file mode 100644 index 0000000..8fe3301 --- /dev/null +++ b/node_modules/stream-shift/package.json @@ -0,0 +1,25 @@ +{ + "name": "stream-shift", + "version": "1.0.3", + "description": "Returns the next buffer/object in a stream's readable queue", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "standard": "^7.1.2", + "tape": "^4.6.0", + "through2": "^2.0.1" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/mafintosh/stream-shift.git" + }, + "author": "Mathias Buus (@mafintosh)", + "license": "MIT", + "bugs": { + "url": "https://github.com/mafintosh/stream-shift/issues" + }, + "homepage": "https://github.com/mafintosh/stream-shift" +} diff --git a/node_modules/stream-shift/test.js b/node_modules/stream-shift/test.js new file mode 100644 index 0000000..bf4ed66 --- /dev/null +++ b/node_modules/stream-shift/test.js @@ -0,0 +1,48 @@ +var tape = require('tape') +var through = require('through2') +var stream = require('stream') +var shift = require('./') + +tape('shifts next', function (t) { + var passthrough = through() + + passthrough.write('hello') + passthrough.write('world') + + t.same(shift(passthrough), Buffer.from('hello')) + t.same(shift(passthrough), Buffer.from('world')) + t.end() +}) + +tape('shifts next with core', function (t) { + var passthrough = stream.PassThrough() + + passthrough.write('hello') + passthrough.write('world') + + t.same(shift(passthrough), Buffer.from('hello')) + t.same(shift(passthrough), Buffer.from('world')) + t.end() +}) + +tape('shifts next with object mode', function (t) { + var passthrough = through({objectMode: true}) + + passthrough.write({hello: 1}) + passthrough.write({world: 1}) + + t.same(shift(passthrough), {hello: 1}) + t.same(shift(passthrough), {world: 1}) + t.end() +}) + +tape('shifts next with object mode with core', function (t) { + var passthrough = stream.PassThrough({objectMode: true}) + + passthrough.write({hello: 1}) + passthrough.write({world: 1}) + + t.same(shift(passthrough), {hello: 1}) + t.same(shift(passthrough), {world: 1}) + t.end() +}) diff --git a/node_modules/string-width/index.d.ts b/node_modules/string-width/index.d.ts new file mode 100644 index 0000000..12b5309 --- /dev/null +++ b/node_modules/string-width/index.d.ts @@ -0,0 +1,29 @@ +declare const stringWidth: { + /** + Get the visual width of a string - the number of columns required to display it. + + Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. + + @example + ``` + import stringWidth = require('string-width'); + + stringWidth('a'); + //=> 1 + + stringWidth('古'); + //=> 2 + + stringWidth('\u001B[1m古\u001B[22m'); + //=> 2 + ``` + */ + (string: string): number; + + // TODO: remove this in the next major version, refactor the whole definition to: + // declare function stringWidth(string: string): number; + // export = stringWidth; + default: typeof stringWidth; +} + +export = stringWidth; diff --git a/node_modules/string-width/index.js b/node_modules/string-width/index.js new file mode 100644 index 0000000..f4d261a --- /dev/null +++ b/node_modules/string-width/index.js @@ -0,0 +1,47 @@ +'use strict'; +const stripAnsi = require('strip-ansi'); +const isFullwidthCodePoint = require('is-fullwidth-code-point'); +const emojiRegex = require('emoji-regex'); + +const stringWidth = string => { + if (typeof string !== 'string' || string.length === 0) { + return 0; + } + + string = stripAnsi(string); + + if (string.length === 0) { + return 0; + } + + string = string.replace(emojiRegex(), ' '); + + let width = 0; + + for (let i = 0; i < string.length; i++) { + const code = string.codePointAt(i); + + // Ignore control characters + if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { + continue; + } + + // Ignore combining characters + if (code >= 0x300 && code <= 0x36F) { + continue; + } + + // Surrogates + if (code > 0xFFFF) { + i++; + } + + width += isFullwidthCodePoint(code) ? 2 : 1; + } + + return width; +}; + +module.exports = stringWidth; +// TODO: remove this in the next major version +module.exports.default = stringWidth; diff --git a/node_modules/string-width/license b/node_modules/string-width/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/string-width/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/string-width/package.json b/node_modules/string-width/package.json new file mode 100644 index 0000000..28ba7b4 --- /dev/null +++ b/node_modules/string-width/package.json @@ -0,0 +1,56 @@ +{ + "name": "string-width", + "version": "4.2.3", + "description": "Get the visual width of a string - the number of columns required to display it", + "license": "MIT", + "repository": "sindresorhus/string-width", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "string", + "character", + "unicode", + "width", + "visual", + "column", + "columns", + "fullwidth", + "full-width", + "full", + "ansi", + "escape", + "codes", + "cli", + "command-line", + "terminal", + "console", + "cjk", + "chinese", + "japanese", + "korean", + "fixed-width" + ], + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.1", + "xo": "^0.24.0" + } +} diff --git a/node_modules/string-width/readme.md b/node_modules/string-width/readme.md new file mode 100644 index 0000000..bdd3141 --- /dev/null +++ b/node_modules/string-width/readme.md @@ -0,0 +1,50 @@ +# string-width + +> Get the visual width of a string - the number of columns required to display it + +Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. + +Useful to be able to measure the actual width of command-line output. + + +## Install + +``` +$ npm install string-width +``` + + +## Usage + +```js +const stringWidth = require('string-width'); + +stringWidth('a'); +//=> 1 + +stringWidth('古'); +//=> 2 + +stringWidth('\u001B[1m古\u001B[22m'); +//=> 2 +``` + + +## Related + +- [string-width-cli](https://github.com/sindresorhus/string-width-cli) - CLI for this module +- [string-length](https://github.com/sindresorhus/string-length) - Get the real length of a string +- [widest-line](https://github.com/sindresorhus/widest-line) - Get the visual width of the widest line in a string + + +--- + +
                          + + Get professional support for this package with a Tidelift subscription + +
                          + + Tidelift helps make open source sustainable for maintainers while giving companies
                          assurances about security, maintenance, and licensing for their dependencies. +
                          +
                          diff --git a/node_modules/string_decoder/LICENSE b/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000..778edb2 --- /dev/null +++ b/node_modules/string_decoder/LICENSE @@ -0,0 +1,48 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + diff --git a/node_modules/string_decoder/README.md b/node_modules/string_decoder/README.md new file mode 100644 index 0000000..5fd5831 --- /dev/null +++ b/node_modules/string_decoder/README.md @@ -0,0 +1,47 @@ +# string_decoder + +***Node-core v8.9.4 string_decoder for userland*** + + +[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) +[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) + + +```bash +npm install --save string_decoder +``` + +***Node-core string_decoder for userland*** + +This package is a mirror of the string_decoder implementation in Node-core. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). + +As of version 1.0.0 **string_decoder** uses semantic versioning. + +## Previous versions + +Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. + +## Update + +The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. + +## Streams Working Group + +`string_decoder` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + +See [readable-stream](https://github.com/nodejs/readable-stream) for +more details. diff --git a/node_modules/string_decoder/lib/string_decoder.js b/node_modules/string_decoder/lib/string_decoder.js new file mode 100644 index 0000000..2e89e63 --- /dev/null +++ b/node_modules/string_decoder/lib/string_decoder.js @@ -0,0 +1,296 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +/**/ + +var Buffer = require('safe-buffer').Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} \ No newline at end of file diff --git a/node_modules/string_decoder/package.json b/node_modules/string_decoder/package.json new file mode 100644 index 0000000..b2bb141 --- /dev/null +++ b/node_modules/string_decoder/package.json @@ -0,0 +1,34 @@ +{ + "name": "string_decoder", + "version": "1.3.0", + "description": "The string_decoder module from Node core", + "main": "lib/string_decoder.js", + "files": [ + "lib" + ], + "dependencies": { + "safe-buffer": "~5.2.0" + }, + "devDependencies": { + "babel-polyfill": "^6.23.0", + "core-util-is": "^1.0.2", + "inherits": "^2.0.3", + "tap": "~0.4.8" + }, + "scripts": { + "test": "tap test/parallel/*.js && node test/verify-dependencies", + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/string_decoder.git" + }, + "homepage": "https://github.com/nodejs/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT" +} diff --git a/node_modules/strip-ansi/index.d.ts b/node_modules/strip-ansi/index.d.ts new file mode 100644 index 0000000..907fccc --- /dev/null +++ b/node_modules/strip-ansi/index.d.ts @@ -0,0 +1,17 @@ +/** +Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string. + +@example +``` +import stripAnsi = require('strip-ansi'); + +stripAnsi('\u001B[4mUnicorn\u001B[0m'); +//=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' +``` +*/ +declare function stripAnsi(string: string): string; + +export = stripAnsi; diff --git a/node_modules/strip-ansi/index.js b/node_modules/strip-ansi/index.js new file mode 100644 index 0000000..9a593df --- /dev/null +++ b/node_modules/strip-ansi/index.js @@ -0,0 +1,4 @@ +'use strict'; +const ansiRegex = require('ansi-regex'); + +module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; diff --git a/node_modules/strip-ansi/license b/node_modules/strip-ansi/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/strip-ansi/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/strip-ansi/package.json b/node_modules/strip-ansi/package.json new file mode 100644 index 0000000..1a41108 --- /dev/null +++ b/node_modules/strip-ansi/package.json @@ -0,0 +1,54 @@ +{ + "name": "strip-ansi", + "version": "6.0.1", + "description": "Strip ANSI escape codes from a string", + "license": "MIT", + "repository": "chalk/strip-ansi", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "strip", + "trim", + "remove", + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "devDependencies": { + "ava": "^2.4.0", + "tsd": "^0.10.0", + "xo": "^0.25.3" + } +} diff --git a/node_modules/strip-ansi/readme.md b/node_modules/strip-ansi/readme.md new file mode 100644 index 0000000..7c4b56d --- /dev/null +++ b/node_modules/strip-ansi/readme.md @@ -0,0 +1,46 @@ +# strip-ansi [![Build Status](https://travis-ci.org/chalk/strip-ansi.svg?branch=master)](https://travis-ci.org/chalk/strip-ansi) + +> Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string + + +## Install + +``` +$ npm install strip-ansi +``` + + +## Usage + +```js +const stripAnsi = require('strip-ansi'); + +stripAnsi('\u001B[4mUnicorn\u001B[0m'); +//=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' +``` + + +## strip-ansi for enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of strip-ansi and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-strip-ansi?utm_source=npm-strip-ansi&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + + +## Related + +- [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module +- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Streaming version of this module +- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes +- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + diff --git a/node_modules/strnum/.vscode/launch.json b/node_modules/strnum/.vscode/launch.json new file mode 100644 index 0000000..b87b349 --- /dev/null +++ b/node_modules/strnum/.vscode/launch.json @@ -0,0 +1,25 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "type": "node", + "request": "launch", + "name": "Jasmine Tests", + "program": "${workspaceFolder}/node_modules/jasmine/bin/jasmine.js", + "args": [ + "${workspaceFolder}/spec/attr_spec.js" + ], + "internalConsoleOptions": "openOnSessionStart" + },{ + "type": "node", + "request": "launch", + "name": "Jasmine Tests current test file", + "program": "${workspaceFolder}/node_modules/jasmine/bin/jasmine.js", + "args": [ + "${file}" + ], + "internalConsoleOptions": "openOnSessionStart" + } + ] + +} \ No newline at end of file diff --git a/node_modules/strnum/CHANGELOG.md b/node_modules/strnum/CHANGELOG.md new file mode 100644 index 0000000..582e460 --- /dev/null +++ b/node_modules/strnum/CHANGELOG.md @@ -0,0 +1,22 @@ + +**1.1.2 / 2025-02-27** +- fix skiplike for 0 + +**1.1.1 / 2025-02-21** +- All recent fixes of version 2 + +**2.0.4 / 2025-02-20** +- remove console log + +**2.0.3 / 2025-02-20** +- fix for string which are falsly identified as e-notation + +**2.0.1 / 2025-02-20** +- fix: handle only zeros +- fix: return original string when NaN + +**2.0.0 / 2025-02-20** +- Migrating to ESM modules. No functional change + +**1.1.0 / 2025-02-20** +- fix (#9): support missing floating point and e notations \ No newline at end of file diff --git a/node_modules/strnum/LICENSE b/node_modules/strnum/LICENSE new file mode 100644 index 0000000..6450554 --- /dev/null +++ b/node_modules/strnum/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Natural Intelligence + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/strnum/README.md b/node_modules/strnum/README.md new file mode 100644 index 0000000..419e8ef --- /dev/null +++ b/node_modules/strnum/README.md @@ -0,0 +1,97 @@ +# strnum +Parse string into Number based on configuration + +## Users + + + + + +Many React Native projects and plugins + +## Usage + +```bash +npm install strnum +``` +```js +const toNumber = require("strnum"); + +toNumber(undefined) // undefined +toNumber(null)) //null +toNumber("")) // "" +toNumber("string"); //"string") +toNumber("12,12"); //"12,12") +toNumber("12 12"); //"12 12") +toNumber("12-12"); //"12-12") +toNumber("12.12.12"); //"12.12.12") +toNumber("0x2f"); //47) +toNumber("-0x2f"); //-47) +toNumber("0x2f", { hex : true}); //47) +toNumber("-0x2f", { hex : true}); //-47) +toNumber("0x2f", { hex : false}); //"0x2f") +toNumber("-0x2f", { hex : false}); //"-0x2f") +toNumber("06"); //6) +toNumber("06", { leadingZeros : true}); //6) +toNumber("06", { leadingZeros : false}); //"06") + +toNumber("006"); //6) +toNumber("006", { leadingZeros : true}); //6) +toNumber("006", { leadingZeros : false}); //"006") +toNumber("0.0"); //0) +toNumber("00.00"); //0) +toNumber("0.06"); //0.06) +toNumber("00.6"); //0.6) +toNumber(".006"); //0.006) +toNumber("6.0"); //6) +toNumber("06.0"); //6) + +toNumber("0.0", { leadingZeros : false}); //0) +toNumber("00.00", { leadingZeros : false}); //"00.00") +toNumber("0.06", { leadingZeros : false}); //0.06) +toNumber("00.6", { leadingZeros : false}); //"00.6") +toNumber(".006", { leadingZeros : false}); //0.006) +toNumber("6.0" , { leadingZeros : false}); //6) +toNumber("06.0" , { leadingZeros : false}); //"06.0") +toNumber("-06"); //-6) +toNumber("-06", { leadingZeros : true}); //-6) +toNumber("-06", { leadingZeros : false}); //"-06") + +toNumber("-0.0"); //-0) +toNumber("-00.00"); //-0) +toNumber("-0.06"); //-0.06) +toNumber("-00.6"); //-0.6) +toNumber("-.006"); //-0.006) +toNumber("-6.0"); //-6) +toNumber("-06.0"); //-6) + +toNumber("-0.0" , { leadingZeros : false}); //-0) +toNumber("-00.00", { leadingZeros : false}); //"-00.00") +toNumber("-0.06", { leadingZeros : false}); //-0.06) +toNumber("-00.6", { leadingZeros : false}); //"-00.6") +toNumber("-.006", {leadingZeros : false}); //-0.006) +toNumber("-6.0" , { leadingZeros : false}); //-6) +toNumber("-06.0" , { leadingZeros : false}); //"-06.0") +toNumber("420926189200190257681175017717") ; //4.209261892001902e+29) +toNumber("000000000000000000000000017717" , { leadingZeros : false}); //"000000000000000000000000017717") +toNumber("000000000000000000000000017717" , { leadingZeros : true}); //17717) +toNumber("01.0e2" , { leadingZeros : false}); //"01.0e2") +toNumber("-01.0e2" , { leadingZeros : false}); //"-01.0e2") +toNumber("01.0e2") ; //100) +toNumber("-01.0e2") ; //-100) +toNumber("1.0e2") ; //100) + +toNumber("-1.0e2") ; //-100) +toNumber("1.0e-2"); //0.01) + +toNumber("+1212121212"); // 1212121212 +toNumber("+1212121212", { skipLike: /\+[0-9]{10}/} )); //"+1212121212" +``` + +Supported Options +```js +hex: true, //when hexadecimal string should be parsed +leadingZeros: true, //when number with leading zeros like 08 should be parsed. 0.0 is not impacted +eNotation: true, //when number with eNotation or number parsed in eNotation should be considered +skipLike: /regex/ //when string should not be parsed when it matches the specified regular expression +``` diff --git a/node_modules/strnum/package.json b/node_modules/strnum/package.json new file mode 100644 index 0000000..90a1b96 --- /dev/null +++ b/node_modules/strnum/package.json @@ -0,0 +1,30 @@ +{ + "name": "strnum", + "version": "1.1.2", + "description": "Parse String to Number based on configuration", + "main": "strnum.js", + "scripts": { + "test": "jasmine strnum.test.js" + }, + "keywords": [ + "string", + "number", + "parse", + "convert" + ], + "repository": { + "type": "git", + "url": "https://github.com/NaturalIntelligence/strnum" + }, + "author": "Amit Gupta (https://amitkumargupta.work/)", + "license": "MIT", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "devDependencies": { + "jasmine": "^5.6.0" + } +} diff --git a/node_modules/strnum/strnum.js b/node_modules/strnum/strnum.js new file mode 100644 index 0000000..c3bd08e --- /dev/null +++ b/node_modules/strnum/strnum.js @@ -0,0 +1,111 @@ +const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/; +const numRegex = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/; +// const octRegex = /^0x[a-z0-9]+/; +// const binRegex = /0x[a-z0-9]+/; + + +const consider = { + hex : true, + // oct: false, + leadingZeros: true, + decimalPoint: "\.", + eNotation: true, + //skipLike: /regex/ +}; + +function toNumber(str, options = {}){ + options = Object.assign({}, consider, options ); + if(!str || typeof str !== "string" ) return str; + + let trimmedStr = str.trim(); + + if(options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str; + else if(str==="0") return 0; + else if (options.hex && hexRegex.test(trimmedStr)) { + return parse_int(trimmedStr, 16); + // }else if (options.oct && octRegex.test(str)) { + // return Number.parseInt(val, 8); + }else if (trimmedStr.search(/[eE]/)!== -1) { //eNotation + const notation = trimmedStr.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/); + // +00.123 => [ , '+', '00', '.123', .. + if(notation){ + // console.log(notation) + if(options.leadingZeros){ //accept with leading zeros + trimmedStr = (notation[1] || "") + notation[3]; + }else{ + if(notation[2] === "0" && notation[3][0]=== "."){ //valid number + }else{ + return str; + } + } + return options.eNotation ? Number(trimmedStr) : str; + }else{ + return str; + } + // }else if (options.parseBin && binRegex.test(str)) { + // return Number.parseInt(val, 2); + }else{ + //separate negative sign, leading zeros, and rest number + const match = numRegex.exec(trimmedStr); + // +00.123 => [ , '+', '00', '.123', .. + if(match){ + const sign = match[1]; + const leadingZeros = match[2]; + let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros + //trim ending zeros for floating number + + if(!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str; //-0123 + else if(!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str; //0123 + else if(options.leadingZeros && leadingZeros===str) return 0; //00 + + else{//no leading zeros or leading zeros are allowed + const num = Number(trimmedStr); + const numStr = "" + num; + + if(numStr.search(/[eE]/) !== -1){ //given number is long and parsed to eNotation + if(options.eNotation) return num; + else return str; + }else if(trimmedStr.indexOf(".") !== -1){ //floating number + if(numStr === "0" && (numTrimmedByZeros === "") ) return num; //0.0 + else if(numStr === numTrimmedByZeros) return num; //0.456. 0.79000 + else if( sign && numStr === "-"+numTrimmedByZeros) return num; + else return str; + } + + if(leadingZeros){ + return (numTrimmedByZeros === numStr) || (sign+numTrimmedByZeros === numStr) ? num : str + }else { + return (trimmedStr === numStr) || (trimmedStr === sign+numStr) ? num : str + } + } + }else{ //non-numeric string + return str; + } + } +} + +/** + * + * @param {string} numStr without leading zeros + * @returns + */ +function trimZeros(numStr){ + if(numStr && numStr.indexOf(".") !== -1){//float + numStr = numStr.replace(/0+$/, ""); //remove ending zeros + if(numStr === ".") numStr = "0"; + else if(numStr[0] === ".") numStr = "0"+numStr; + else if(numStr[numStr.length-1] === ".") numStr = numStr.substr(0,numStr.length-1); + return numStr; + } + return numStr; +} + +function parse_int(numStr, base){ + //polyfill + if(parseInt) return parseInt(numStr, base); + else if(Number.parseInt) return Number.parseInt(numStr, base); + else if(window && window.parseInt) return window.parseInt(numStr, base); + else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported") +} + +module.exports = toNumber; \ No newline at end of file diff --git a/node_modules/strnum/strnum.test.js b/node_modules/strnum/strnum.test.js new file mode 100644 index 0000000..c476614 --- /dev/null +++ b/node_modules/strnum/strnum.test.js @@ -0,0 +1,165 @@ +const toNumber = require("./strnum.js"); + +describe("Should convert all the valid numeric strings to number", () => { + it("should return undefined, null, empty string, or non-numeric as it is", () => { + expect(toNumber(undefined)).not.toBeDefined(); + expect(toNumber(null)).toEqual(null); + expect(toNumber("")).toEqual(""); + expect(toNumber("string")).toEqual("string"); + expect(toNumber("e89794659669cb7bb967db73a7ea6889c3891727")).toEqual("e89794659669cb7bb967db73a7ea6889c3891727"); + + }); + it("should not parse number with spaces or comma", () => { + expect(toNumber("12,12")).toEqual("12,12"); + expect(toNumber("12 12")).toEqual("12 12"); + expect(toNumber("12-12")).toEqual("12-12"); + expect(toNumber("12.12.12")).toEqual("12.12.12"); + }) + it("should consider + sign", () => { + expect(toNumber("+12")).toEqual(12); + expect(toNumber("+ 12")).toEqual("+ 12"); + expect(toNumber("12+12")).toEqual("12+12"); + expect(toNumber("1212+")).toEqual("1212+"); + }) + it("should parse hexadecimal values", () => { + expect(toNumber("0x2f")).toEqual(47); + expect(toNumber("-0x2f")).toEqual(-47); + expect(toNumber("0x2f", { hex : true})).toEqual(47); + expect(toNumber("-0x2f", { hex : true})).toEqual(-47); + expect(toNumber("0x2f", { hex : false})).toEqual("0x2f"); + expect(toNumber("-0x2f", { hex : false})).toEqual("-0x2f"); + }) + it("should not parse strings with 0x embedded", () => { + expect(toNumber("0xzz")).toEqual("0xzz"); + expect(toNumber("iweraf0x123qwerqwer")).toEqual("iweraf0x123qwerqwer"); + expect(toNumber("1230x55")).toEqual("1230x55"); + expect(toNumber("JVBERi0xLjMNCiXi48")).toEqual("JVBERi0xLjMNCiXi48"); + }) + it("leading zeros", () => { + expect(toNumber("0")).toEqual(0); + expect(toNumber("00")).toEqual(0); + expect(toNumber("00.0")).toEqual(0); + + expect(toNumber("0",{ leadingZeros : false})).toEqual(0); + expect(toNumber("00",{ leadingZeros : false})).toEqual("00"); + expect(toNumber("00.0",{ leadingZeros : false})).toEqual("00.0"); + + expect(toNumber("06")).toEqual(6); + expect(toNumber("06", { leadingZeros : true})).toEqual(6); + expect(toNumber("06", { leadingZeros : false})).toEqual("06"); + + expect(toNumber("006")).toEqual(6); + expect(toNumber("006", { leadingZeros : true})).toEqual(6); + expect(toNumber("006", { leadingZeros : false})).toEqual("006"); + + expect(toNumber("000000000000000000000000017717" , { leadingZeros : false})).toEqual("000000000000000000000000017717"); + expect(toNumber("000000000000000000000000017717" , { leadingZeros : true})).toEqual(17717); + expect(toNumber("020211201030005811824") ).toEqual("020211201030005811824"); + expect(toNumber("0420926189200190257681175017717") ).toEqual(4.209261892001902e+29); + }) + it("invalid floating number", () => { + expect(toNumber("20.21.030") ).toEqual("20.21.030"); + expect(toNumber("0.21.030") ).toEqual("0.21.030"); + expect(toNumber("0.21.") ).toEqual("0.21."); + }); + it("floating point and leading zeros", () => { + expect(toNumber("0.")).toEqual(0); + expect(toNumber("+0.")).toEqual(0); + expect(toNumber("-0.")).toEqual(-0); + expect(toNumber("1.") ).toEqual(1); + expect(toNumber("00.00")).toEqual(0); + expect(toNumber("0.06")).toEqual(0.06); + expect(toNumber("00.6")).toEqual(0.6); + expect(toNumber(".006")).toEqual(0.006); + expect(toNumber("6.0")).toEqual(6); + expect(toNumber("06.0")).toEqual(6); + + expect(toNumber("0.0", { leadingZeros : false})).toEqual(0); + expect(toNumber("00.00", { leadingZeros : false})).toEqual("00.00"); + expect(toNumber("0.06", { leadingZeros : false})).toEqual(0.06); + expect(toNumber("00.6", { leadingZeros : false})).toEqual("00.6"); + expect(toNumber(".006", { leadingZeros : false})).toEqual(0.006); + expect(toNumber("6.0" , { leadingZeros : false})).toEqual(6); + expect(toNumber("06.0" , { leadingZeros : false})).toEqual("06.0"); + }) + it("negative number leading zeros", () => { + expect(toNumber("+06")).toEqual(6); + expect(toNumber("-06")).toEqual(-6); + expect(toNumber("-06", { leadingZeros : true})).toEqual(-6); + expect(toNumber("-06", { leadingZeros : false})).toEqual("-06"); + + expect(toNumber("-0.0")).toEqual(-0); + expect(toNumber("-00.00")).toEqual(-0); + expect(toNumber("-0.06")).toEqual(-0.06); + expect(toNumber("-00.6")).toEqual(-0.6); + expect(toNumber("-.006")).toEqual(-0.006); + expect(toNumber("-6.0")).toEqual(-6); + expect(toNumber("-06.0")).toEqual(-6); + + expect(toNumber("-0.0" , { leadingZeros : false})).toEqual(-0); + expect(toNumber("-00.00", { leadingZeros : false})).toEqual("-00.00"); + expect(toNumber("-0.06", { leadingZeros : false})).toEqual(-0.06); + expect(toNumber("-00.6", { leadingZeros : false})).toEqual("-00.6"); + expect(toNumber("-.006", {leadingZeros : false})).toEqual(-0.006); + expect(toNumber("-6.0" , { leadingZeros : false})).toEqual(-6); + expect(toNumber("-06.0" , { leadingZeros : false})).toEqual("-06.0"); + }) + it("long number", () => { + expect(toNumber("020211201030005811824") ).toEqual("020211201030005811824"); + expect(toNumber("20211201030005811824") ).toEqual("20211201030005811824"); + expect(toNumber("20.211201030005811824") ).toEqual("20.211201030005811824"); + expect(toNumber("0.211201030005811824") ).toEqual("0.211201030005811824"); + }); + it("scientific notation", () => { + expect(toNumber("01.0e2" , { leadingZeros : false})).toEqual("01.0e2"); + expect(toNumber("-01.0e2" , { leadingZeros : false})).toEqual("-01.0e2"); + expect(toNumber("01.0e2") ).toEqual(100); + expect(toNumber("-01.0e2") ).toEqual(-100); + expect(toNumber("1.0e2") ).toEqual(100); + + expect(toNumber("-1.0e2") ).toEqual(-100); + expect(toNumber("1.0e-2")).toEqual(0.01); + + expect(toNumber("420926189200190257681175017717") ).toEqual(4.209261892001902e+29); + expect(toNumber("420926189200190257681175017717" , { eNotation: false} )).toEqual("420926189200190257681175017717"); + + expect(toNumber("1e-2")).toEqual(0.01); + expect(toNumber("1e+2")).toEqual(100); + expect(toNumber("1.e+2")).toEqual(100); + }); + + it("scientific notation with upper E", () => { + expect(toNumber("01.0E2" , { leadingZeros : false})).toEqual("01.0E2"); + expect(toNumber("-01.0E2" , { leadingZeros : false})).toEqual("-01.0E2"); + expect(toNumber("01.0E2") ).toEqual(100); + expect(toNumber("-01.0E2") ).toEqual(-100); + expect(toNumber("1.0E2") ).toEqual(100); + + expect(toNumber("-1.0E2") ).toEqual(-100); + expect(toNumber("1.0E-2")).toEqual(0.01); + }); + + it("should skip matching pattern", () => { + expect(toNumber("0", { skipLike: /.*/ })).toEqual("0"); + expect(toNumber("+12", { skipLike: /\+[0-9]{10}/} )).toEqual(12); + expect(toNumber("12+12", { skipLike: /\+[0-9]{10}/} )).toEqual("12+12"); + expect(toNumber("12+1212121212", { skipLike: /\+[0-9]{10}/} )).toEqual("12+1212121212"); + expect(toNumber("+1212121212") ).toEqual(1212121212); + expect(toNumber("+1212121212", { skipLike: /\+[0-9]{10}/} )).toEqual("+1212121212"); + }) + it("should not change string if not number", () => { + expect(toNumber("+12 12")).toEqual("+12 12"); + expect(toNumber(" +12 12 ")).toEqual(" +12 12 "); + }) + it("should ignore sorrounded spaces ", () => { + expect(toNumber(" +1212 ")).toEqual(1212); + }) + + it("negative numbers", () => { + expect(toNumber("+1212")).toEqual(1212); + expect(toNumber("+12.12")).toEqual(12.12); + expect(toNumber("-12.12")).toEqual(-12.12); + expect(toNumber("-012.12")).toEqual(-12.12); + expect(toNumber("-012.12")).toEqual(-12.12); + }) +}); diff --git a/node_modules/stubs/index.js b/node_modules/stubs/index.js new file mode 100644 index 0000000..252f34f --- /dev/null +++ b/node_modules/stubs/index.js @@ -0,0 +1,35 @@ +'use strict' + +module.exports = function stubs(obj, method, cfg, stub) { + if (!obj || !method || !obj[method]) + throw new Error('You must provide an object and a key for an existing method') + + if (!stub) { + stub = cfg + cfg = {} + } + + stub = stub || function() {} + + cfg.callthrough = cfg.callthrough || false + cfg.calls = cfg.calls || 0 + + var norevert = cfg.calls === 0 + + var cached = obj[method].bind(obj) + + obj[method] = function() { + var args = [].slice.call(arguments) + var returnVal + + if (cfg.callthrough) + returnVal = cached.apply(obj, args) + + returnVal = stub.apply(obj, args) || returnVal + + if (!norevert && --cfg.calls === 0) + obj[method] = cached + + return returnVal + } +} diff --git a/node_modules/stubs/package.json b/node_modules/stubs/package.json new file mode 100644 index 0000000..7ced3ab --- /dev/null +++ b/node_modules/stubs/package.json @@ -0,0 +1,25 @@ +{ + "name": "stubs", + "version": "3.0.0", + "description": "Easy method stubber.", + "main": "index.js", + "scripts": { + "test": "node ./test" + }, + "repository": { + "type": "git", + "url": "https://github.com/stephenplusplus/stubs" + }, + "keywords": [ + "stubs" + ], + "author": "Stephen Sawchuk", + "license": "MIT", + "bugs": { + "url": "https://github.com/stephenplusplus/stubs/issues" + }, + "homepage": "https://github.com/stephenplusplus/stubs", + "devDependencies": { + "tess": "^1.0.0" + } +} diff --git a/node_modules/stubs/readme.md b/node_modules/stubs/readme.md new file mode 100644 index 0000000..ed07628 --- /dev/null +++ b/node_modules/stubs/readme.md @@ -0,0 +1,73 @@ +# stubs + +> It's a simple stubber. + +## About + +For when you don't want to write the same thing over and over to cache a method and call an override, then revert it, and blah blah. + + +## Use +```sh +$ npm install --save-dev stubs +``` +```js +var mylib = require('./lib/index.js') +var stubs = require('stubs') + +// make it a noop +stubs(mylib, 'create') + +// stub it out +stubs(mylib, 'create', function() { + // calls this instead +}) + +// stub it out, but call the original first +stubs(mylib, 'create', { callthrough: true }, function() { + // call original method, then call this +}) + +// use the stub for a while, then revert +stubs(mylib, 'create', { calls: 3 }, function() { + // call this 3 times, then use the original method +}) +``` + + +## API + +### stubs(object, method[[, opts], stub]) + +#### object +- Type: Object + +#### method +- Type: String + +Name of the method to stub. + +#### opts +- (optional) +- Type: Object + +##### opts.callthrough +- (optional) +- Type: Boolean +- Default: `false` + +Call the original method as well as the stub (if a stub is provided). + +##### opts.calls +- (optional) +- Type: Number +- Default: `0` (never revert) + +Number of calls to allow the stub to receive until reverting to the original. + +#### stub +- (optional) +- Type: Function +- Default: `function() {}` + +This method is called in place of the original method. If `opts.callthrough` is `true`, this method is called *after* the original method is called as well. \ No newline at end of file diff --git a/node_modules/stubs/test.js b/node_modules/stubs/test.js new file mode 100644 index 0000000..cae408e --- /dev/null +++ b/node_modules/stubs/test.js @@ -0,0 +1,172 @@ +'use strict' + +var assert = require('assert') +var stubs = require('./') +var tess = require('tess') + +tess('init', function(it) { + it('is a function', function() { + assert.equal(typeof stubs, 'function') + }) + + it('throws without obj || method', function() { + assert.throws(function() { + stubs() + }, /must provide/) + + assert.throws(function() { + stubs({}) + }, /must provide/) + }) +}) + +tess('stubs', function(it) { + it('stubs a method with a noop', function() { + var originalCalled = false + + var obj = {} + obj.method = function() { + originalCalled = true + } + + stubs(obj, 'method') + + obj.method() + + assert(!originalCalled) + }) + + it('accepts an override', function() { + var originalCalled = false + + var obj = {} + obj.method = function() { + originalCalled = true + } + + var replacementCalled = false + stubs(obj, 'method', function() { + replacementCalled = true + }) + + obj.method() + assert(!originalCalled) + assert(replacementCalled) + }) + + it('returns value of overridden method call', function() { + var overriddenUniqueVal = {} + + var obj = {} + obj.method = function() {} + + stubs(obj, 'method', { callthrough: true }, function() { + return overriddenUniqueVal + }) + + assert.strictEqual(obj.method(), overriddenUniqueVal) + }) + + it('calls through to original method', function() { + var originalCalled = false + + var obj = {} + obj.method = function() { + originalCalled = true + } + + var replacementCalled = false + stubs(obj, 'method', { callthrough: true }, function() { + replacementCalled = true + }) + + obj.method() + assert(originalCalled) + assert(replacementCalled) + }) + + it('returns value of original method call', function() { + var uniqueVal = Date.now() + + var obj = {} + obj.method = function() { + return uniqueVal + } + + stubs(obj, 'method', { callthrough: true }, function() {}) + + assert.equal(obj.method(), uniqueVal) + }) + + it('returns calls override and returns original value', function() { + var uniqueVal = {} + var overrideWasCalled = false + + var obj = {} + obj.method = function() { + return uniqueVal + } + + stubs(obj, 'method', { callthrough: true }, function() { + // does not return anything + overrideWasCalled = true + }) + + assert.strictEqual(obj.method(), uniqueVal) + assert.strictEqual(overrideWasCalled, true) + }) + + it('returns value of overridden method call', function() { + var uniqueVal = {} + var overriddenUniqueVal = {} + + var obj = {} + obj.method = function() { + return uniqueVal + } + + stubs(obj, 'method', { callthrough: true }, function() { + return overriddenUniqueVal + }) + + assert.strictEqual(obj.method(), overriddenUniqueVal) + }) + + it('stops calling stub after n calls', function() { + var timesToCall = 5 + var timesCalled = 0 + + var obj = {} + obj.method = function() { + assert.equal(timesCalled, timesToCall) + } + + stubs(obj, 'method', { calls: timesToCall }, function() { + timesCalled++ + }) + + obj.method() // 1 (stub) + obj.method() // 2 (stub) + obj.method() // 3 (stub) + obj.method() // 4 (stub) + obj.method() // 5 (stub) + obj.method() // 6 (original) + }) + + it('calls stub in original context of obj', function() { + var secret = 'brownies' + + function Class() { + this.method = function() {} + this.secret = secret + } + + var cl = new Class() + + stubs(cl, 'method', function() { + assert.equal(this.secret, secret) + }) + + cl.method() + }) +}) diff --git a/node_modules/teeny-request/CHANGELOG.md b/node_modules/teeny-request/CHANGELOG.md new file mode 100644 index 0000000..dcf3642 --- /dev/null +++ b/node_modules/teeny-request/CHANGELOG.md @@ -0,0 +1,253 @@ +# Changelog + +## [9.0.0](https://github.com/googleapis/teeny-request/compare/v8.0.3...v9.0.0) (2023-07-20) + + +### ⚠ BREAKING CHANGES + +* move minimum version to node 14 ([#312](https://github.com/googleapis/teeny-request/issues/312)) + +### Miscellaneous Chores + +* Move minimum version to node 14 ([#312](https://github.com/googleapis/teeny-request/issues/312)) ([e30cf76](https://github.com/googleapis/teeny-request/commit/e30cf765fb7997e36cf7cc8144dfe8480d12c58b)) + +## [8.0.3](https://github.com/googleapis/teeny-request/compare/v8.0.2...v8.0.3) (2023-02-17) + + +### Bug Fixes + +* Use pipeline in place of pipe to better handle cleanup / errors ([#299](https://github.com/googleapis/teeny-request/issues/299)) ([31d9002](https://github.com/googleapis/teeny-request/commit/31d900227d2ea7cb205fd4dc8db0aed5abd0dfa9)) + +## [8.0.2](https://github.com/googleapis/teeny-request/compare/v8.0.1...v8.0.2) (2022-09-09) + + +### Bug Fixes + +* **deps:** Update dependency uuid to v9 ([#292](https://github.com/googleapis/teeny-request/issues/292)) ([f9fa756](https://github.com/googleapis/teeny-request/commit/f9fa75647913e2be10a48635168b11520d70982f)) + +## [8.0.1](https://github.com/googleapis/teeny-request/compare/v8.0.0...v8.0.1) (2022-08-23) + + +### Bug Fixes + +* remove pip install statements ([#1546](https://github.com/googleapis/teeny-request/issues/1546)) ([#290](https://github.com/googleapis/teeny-request/issues/290)) ([94e7a86](https://github.com/googleapis/teeny-request/commit/94e7a86f13ab380399049e110c648cd381fb1e00)) + +## [8.0.0](https://github.com/googleapis/teeny-request/compare/v7.2.0...v8.0.0) (2022-05-09) + + +### ⚠ BREAKING CHANGES + +* drop node 10, update typescript to 4.6.3 (#279) + +### Build System + +* drop node 10, update typescript to 4.6.3 ([#279](https://github.com/googleapis/teeny-request/issues/279)) ([6f12739](https://github.com/googleapis/teeny-request/commit/6f1273993ae667078abae41a8029833749a25e6a)) + +## [7.2.0](https://github.com/googleapis/teeny-request/compare/v7.1.3...v7.2.0) (2022-03-31) + + +### Features + +* Add support for `NO_PROXY` ([#272](https://github.com/googleapis/teeny-request/issues/272)) ([b02b6e5](https://github.com/googleapis/teeny-request/commit/b02b6e515575814bbef7360586d07030b445705d)) + +### [7.1.3](https://www.github.com/googleapis/teeny-request/compare/v7.1.2...v7.1.3) (2021-09-24) + + +### Bug Fixes + +* **deps:** update dependency http-proxy-agent to v5 ([#253](https://www.github.com/googleapis/teeny-request/issues/253)) ([c84dff4](https://www.github.com/googleapis/teeny-request/commit/c84dff45e4a0e71fc5205838dae51f57f3139c06)) + +### [7.1.2](https://www.github.com/googleapis/teeny-request/compare/v7.1.1...v7.1.2) (2021-09-10) + + +### Bug Fixes + +* **build:** set default branch to main ([#247](https://www.github.com/googleapis/teeny-request/issues/247)) ([db3126d](https://www.github.com/googleapis/teeny-request/commit/db3126df77bc7e6cebb7d092001bbd3a444207d6)) + +### [7.1.1](https://www.github.com/googleapis/teeny-request/compare/v7.1.0...v7.1.1) (2021-06-30) + + +### Bug Fixes + +* throw error if missing uri or url ([#239](https://www.github.com/googleapis/teeny-request/issues/239)) ([4d770e3](https://www.github.com/googleapis/teeny-request/commit/4d770e3b89254c4cec30c422cdcdad257500c9cc)) + +## [7.1.0](https://www.github.com/googleapis/teeny-request/compare/v7.0.1...v7.1.0) (2021-05-19) + + +### Features + +* add `gcf-owl-bot[bot]` to `ignoreAuthors` ([#224](https://www.github.com/googleapis/teeny-request/issues/224)) ([3e7424f](https://www.github.com/googleapis/teeny-request/commit/3e7424fb63f0c0dca3606d6e1fc2f294f9d86ba5)) + + +### Bug Fixes + +* Buffer is allow as body without encoding to string ([#223](https://www.github.com/googleapis/teeny-request/issues/223)) ([d9bcdc3](https://www.github.com/googleapis/teeny-request/commit/d9bcdc36a60074fd78718ea8f7c4745d640e3b4f)) + +### [7.0.1](https://www.github.com/googleapis/teeny-request/compare/v7.0.0...v7.0.1) (2020-09-29) + + +### Bug Fixes + +* **deps:** update node-fetch to 2.6.1 ([#200](https://www.github.com/googleapis/teeny-request/issues/200)) ([8958a78](https://www.github.com/googleapis/teeny-request/commit/8958a78b117e5610f3ccf121ba1d650dbe9739f8)) + +## [7.0.0](https://www.github.com/googleapis/teeny-request/compare/v6.0.3...v7.0.0) (2020-06-01) + + +### ⚠ BREAKING CHANGES + +* dropping support for Node.js 8.x + +### Features + +* pass agent options when using agent pool config ([#149](https://www.github.com/googleapis/teeny-request/issues/149)) ([38ece79](https://www.github.com/googleapis/teeny-request/commit/38ece79151b667ec1a72ec50b1c7a58258924794)) +* warn on too many concurrent requests ([#165](https://www.github.com/googleapis/teeny-request/issues/165)) ([88ff2d0](https://www.github.com/googleapis/teeny-request/commit/88ff2d0d8e0fc25a4219ef5625b8de353ed4aa29)) + + +### Bug Fixes + +* apache license URL ([#468](https://www.github.com/googleapis/teeny-request/issues/468)) ([#156](https://www.github.com/googleapis/teeny-request/issues/156)) ([01ac7bd](https://www.github.com/googleapis/teeny-request/commit/01ac7bd01e870796fd15355e079649633d5d5983)) +* update template files for Node.js libraries ([#152](https://www.github.com/googleapis/teeny-request/issues/152)) ([89833c3](https://www.github.com/googleapis/teeny-request/commit/89833c3c3e8afea04c85a60811f122c5a6d37e48)) +* **deps:** update dependency uuid to v8 ([#164](https://www.github.com/googleapis/teeny-request/issues/164)) ([2ab8155](https://www.github.com/googleapis/teeny-request/commit/2ab81550aeb8ca914516ff4ac20ebbb7b3d73fa5)) + + +### Build System + +* drop support for node.js 8.x ([#159](https://www.github.com/googleapis/teeny-request/issues/159)) ([d87aa73](https://www.github.com/googleapis/teeny-request/commit/d87aa73d3fafbdc013b03b7629a41decda6da98a)) + +### [6.0.3](https://www.github.com/googleapis/teeny-request/compare/v6.0.2...v6.0.3) (2020-03-06) + + +### Bug Fixes + +* **deps:** update dependency uuid to v7 ([#134](https://www.github.com/googleapis/teeny-request/issues/134)) ([97817bf](https://www.github.com/googleapis/teeny-request/commit/97817bfb12396f620b2e280dcdc8965c4815abb5)) + +### [6.0.2](https://www.github.com/googleapis/teeny-request/compare/v6.0.1...v6.0.2) (2020-02-10) + + +### Bug Fixes + +* **deps:** update dependency https-proxy-agent to v5 ([#128](https://www.github.com/googleapis/teeny-request/issues/128)) ([5dcef3f](https://www.github.com/googleapis/teeny-request/commit/5dcef3f5883b24a1092def38004074d04e37e241)) + +### [6.0.1](https://www.github.com/googleapis/teeny-request/compare/v6.0.0...v6.0.1) (2020-01-24) + + +### Bug Fixes + +* **deps:** update dependency http-proxy-agent to v4 ([#121](https://www.github.com/googleapis/teeny-request/issues/121)) ([7caabcf](https://www.github.com/googleapis/teeny-request/commit/7caabcf154d8cf0848e443ce2cd4fbfae913ca41)) + +## [6.0.0](https://www.github.com/googleapis/teeny-request/compare/v5.3.3...v6.0.0) (2020-01-11) + + +### ⚠ BREAKING CHANGES + +* remove console log and throw instead (#107) + +### Bug Fixes + +* remove console log and throw instead ([#107](https://www.github.com/googleapis/teeny-request/issues/107)) ([965beaa](https://www.github.com/googleapis/teeny-request/commit/965beaae17f0273992c9856ebf79b6f1befc59fe)) + +### [5.3.3](https://www.github.com/googleapis/teeny-request/compare/v5.3.2...v5.3.3) (2019-12-15) + + +### Bug Fixes + +* **deps:** update dependency http-proxy-agent to v3 ([#104](https://www.github.com/googleapis/teeny-request/issues/104)) ([35a47d8](https://www.github.com/googleapis/teeny-request/commit/35a47d83adf92b16eab3fce52deae0e3c1353aa6)) +* **deps:** update dependency https-proxy-agent to v4 ([#105](https://www.github.com/googleapis/teeny-request/issues/105)) ([26b67af](https://www.github.com/googleapis/teeny-request/commit/26b67afcb084ce1b99a62ecc55050d6f8f8aaee4)) +* **docs:** add jsdoc-region-tag plugin ([#98](https://www.github.com/googleapis/teeny-request/issues/98)) ([8f3c35a](https://www.github.com/googleapis/teeny-request/commit/8f3c35aee711a1262ffa7c058eb1b9f18204b80e)) + +### [5.3.2](https://www.github.com/googleapis/teeny-request/compare/v5.3.1...v5.3.2) (2019-12-05) + + +### Bug Fixes + +* **deps:** pin TypeScript below 3.7.0 ([#102](https://www.github.com/googleapis/teeny-request/issues/102)) ([c0b81e6](https://www.github.com/googleapis/teeny-request/commit/c0b81e6e7c1bb7e4a3e823c2e41692bc8ede0218)) + +### [5.3.1](https://www.github.com/googleapis/teeny-request/compare/v5.3.0...v5.3.1) (2019-10-29) + + +### Bug Fixes + +* correctly set compress/gzip option when false ([#95](https://www.github.com/googleapis/teeny-request/issues/95)) ([72ef307](https://www.github.com/googleapis/teeny-request/commit/72ef307364de542af3ef8581572b1897fca2bcf4)) + +## [5.3.0](https://www.github.com/googleapis/teeny-request/compare/v5.2.1...v5.3.0) (2019-10-09) + + +### Bug Fixes + +* **deps:** update dependency https-proxy-agent to v3 ([#89](https://www.github.com/googleapis/teeny-request/issues/89)) ([dfd52cc](https://www.github.com/googleapis/teeny-request/commit/dfd52cc)) + + +### Features + +* agent pooling ([#86](https://www.github.com/googleapis/teeny-request/issues/86)) ([b182f51](https://www.github.com/googleapis/teeny-request/commit/b182f51)) + +### [5.2.1](https://www.github.com/googleapis/teeny-request/compare/v5.2.0...v5.2.1) (2019-08-14) + + +### Bug Fixes + +* **types:** make types less strict for method ([#76](https://www.github.com/googleapis/teeny-request/issues/76)) ([9f07e98](https://www.github.com/googleapis/teeny-request/commit/9f07e98)) + +## [5.2.0](https://www.github.com/googleapis/teeny-request/compare/v5.1.3...v5.2.0) (2019-08-13) + + +### Bug Fixes + +* if scheme is http:// use an HTTP agent ([#75](https://www.github.com/googleapis/teeny-request/issues/75)) ([abdf846](https://www.github.com/googleapis/teeny-request/commit/abdf846)) +* remove unused logging ([#71](https://www.github.com/googleapis/teeny-request/issues/71)) ([4cb4967](https://www.github.com/googleapis/teeny-request/commit/4cb4967)) +* undefined headers breaks compatibility with auth ([#66](https://www.github.com/googleapis/teeny-request/issues/66)) ([12901a0](https://www.github.com/googleapis/teeny-request/commit/12901a0)) + + +### Features + +* support lazy-reading from response stream ([#74](https://www.github.com/googleapis/teeny-request/issues/74)) ([f6db420](https://www.github.com/googleapis/teeny-request/commit/f6db420)) +* support reading from the request stream ([#67](https://www.github.com/googleapis/teeny-request/issues/67)) ([ae23054](https://www.github.com/googleapis/teeny-request/commit/ae23054)) + + +### Reverts + +* do not pipe fetch response into user stream ([#72](https://www.github.com/googleapis/teeny-request/issues/72)) ([6ec812e](https://www.github.com/googleapis/teeny-request/commit/6ec812e)) + +### [5.1.3](https://www.github.com/googleapis/teeny-request/compare/v5.1.2...v5.1.3) (2019-08-06) + + +### Bug Fixes + +* duplex stream does not implement methods like _read ([#64](https://www.github.com/googleapis/teeny-request/issues/64)) ([22ee26c](https://www.github.com/googleapis/teeny-request/commit/22ee26c)) + +### [5.1.2](https://www.github.com/googleapis/teeny-request/compare/v5.1.1...v5.1.2) (2019-08-06) + + +### Bug Fixes + +* **types:** expand method and header types ([#61](https://www.github.com/googleapis/teeny-request/issues/61)) ([c04d2f1](https://www.github.com/googleapis/teeny-request/commit/c04d2f1)) + +### [5.1.1](https://www.github.com/googleapis/teeny-request/compare/v5.1.0...v5.1.1) (2019-07-23) + + +### Bug Fixes + +* support lowercase proxy env vars ([#56](https://www.github.com/googleapis/teeny-request/issues/56)) ([0b3e433](https://www.github.com/googleapis/teeny-request/commit/0b3e433)) + +## [5.1.0](https://www.github.com/googleapis/teeny-request/compare/v5.0.0...v5.1.0) (2019-07-19) + + +### Features + +* support forever option ([#54](https://www.github.com/googleapis/teeny-request/issues/54)) ([746d70e](https://www.github.com/googleapis/teeny-request/commit/746d70e)) + +## [5.0.0](https://www.github.com/googleapis/teeny-request/compare/v4.0.0...v5.0.0) (2019-07-15) + + +### ⚠ BREAKING CHANGES + +* this is our first release since moving into googleapis org; in the theme of "better safe than sorry" we're releasing as 5.0.0. + +### Bug Fixes + +* export types independent of @types/request ([#44](https://www.github.com/googleapis/teeny-request/issues/44)) ([fbe2b77](https://www.github.com/googleapis/teeny-request/commit/fbe2b77)) + + +### Reverts + +* revert 4.0.0 release in favor of 5.0.0 release ([#52](https://www.github.com/googleapis/teeny-request/issues/52)) ([f24499e](https://www.github.com/googleapis/teeny-request/commit/f24499e)) diff --git a/node_modules/teeny-request/LICENSE b/node_modules/teeny-request/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/teeny-request/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/teeny-request/README.md b/node_modules/teeny-request/README.md new file mode 100644 index 0000000..14e2f94 --- /dev/null +++ b/node_modules/teeny-request/README.md @@ -0,0 +1,95 @@ +[![Build Status](https://travis-ci.org/googleapis/teeny-request.svg?branch=master)](https://travis-ci.org/googleapis/teeny-request) + +# teeny-request + +Like `request`, but much smaller - and with less options. Uses `node-fetch` under the hood. +Pop it in where you would use `request`. Improves load and parse time of modules. + +```js +const request = require('teeny-request').teenyRequest; + +request({uri: 'http://ip.jsontest.com/'}, function (error, response, body) { + console.log('error:', error); // Print the error if one occurred + console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received + console.log('body:', body); // Print the JSON. +}); +``` + +For TypeScript, you can use `@types/request`. + +```ts +import {teenyRequest as request} from 'teeny-request'; +import * as r from 'request'; // Only for type declarations + +request({uri: 'http://ip.jsontest.com/'}, (error: any, response: r.Response, body: any) => { + console.log('error:', error); // Print the error if one occurred + console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received + console.log('body:', body); // Print the JSON. +}); +``` + + + +## teenyRequest(options, callback) + +Options are limited to the following + +* uri +* method, default GET +* headers +* json +* qs +* useQuerystring +* timeout in ms +* gzip +* proxy + +```ts +request({uri:'http://service.com/upload', method:'POST', json: {key:'value'}}, function(err,httpResponse,body){ /* ... */ }) +``` + +The callback argument gets 3 arguments: + + * An error when applicable (usually from http.ClientRequest object) + * A response object with statusCode, a statusMessage, and a body + * The third is the response body (JSON object) + +## defaults(options) + +Set default options for every `teenyRequest` call. + +```ts +let defaultRequest = teenyRequest.defaults({timeout: 60000}); + defaultRequest({uri: 'http://ip.jsontest.com/'}, function (error, response, body) { + assert.ifError(error); + assert.strictEqual(response.statusCode, 200); + console.log(body.ip); + assert.notEqual(body.ip, null); + + done(); + }); +``` + +## Proxy environment variables +If environment variables `HTTP_PROXY`, `HTTPS_PROXY`, or `NO_PROXY` are set, they are respected. + +## Building with Webpack 4+ +Since 4.0.0, Webpack uses `javascript/esm` for `.mjs` files which handles ESM more strictly compared to `javascript/auto`. If you get the error `Can't import the named export 'PassThrough' from non EcmaScript module`, please add the following to your Webpack config: + +```js +{ + test: /\.mjs$/, + type: 'javascript/auto', +}, +``` + +## Motivation +`request` has a ton of options and features and is accordingly large. Requiring a module incurs load and parse time. For +`request`, that is around 600ms. + +![Load time of request measured with require-so-slow](https://user-images.githubusercontent.com/101553/44694187-20357700-aa3a-11e8-9116-b8ae794cbc27.png) + +`teeny-request` doesn't have any of the bells and whistles that `request` has, but is so much faster to load. If startup time is an issue and you don't need much beyond a basic GET and POST, you can use `teeny-request`. + +## Thanks +Special thanks to [billyjacobson](https://github.com/billyjacobson) for suggesting the name. Please report all bugs to them. Just kidding. Please open issues. diff --git a/node_modules/teeny-request/build/src/TeenyStatistics.d.ts b/node_modules/teeny-request/build/src/TeenyStatistics.d.ts new file mode 100644 index 0000000..669cf6e --- /dev/null +++ b/node_modules/teeny-request/build/src/TeenyStatistics.d.ts @@ -0,0 +1,127 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface TeenyStatisticsOptions { + /** + * A positive number representing when to issue a warning about the number + * of concurrent requests using teeny-request. + * Set to 0 to disable this warning. + * Corresponds to the TEENY_REQUEST_WARN_CONCURRENT_REQUESTS environment + * variable. + */ + concurrentRequests?: number; +} +type TeenyStatisticsConfig = Required; +/** + * TeenyStatisticsCounters is distinct from TeenyStatisticsOptions: + * Used when dumping current counters and other internal metrics. + */ +export interface TeenyStatisticsCounters { + concurrentRequests: number; +} +/** + * @class TeenyStatisticsWarning + * @extends Error + * @description While an error, is used for emitting warnings when + * meeting certain configured thresholds. + * @see process.emitWarning + */ +export declare class TeenyStatisticsWarning extends Error { + static readonly CONCURRENT_REQUESTS = "ConcurrentRequestsExceededWarning"; + threshold: number; + type: string; + value: number; + /** + * @param {string} message + */ + constructor(message: string); +} +/** + * @class TeenyStatistics + * @description Maintain various statistics internal to teeny-request. Tracking + * is not automatic and must be instrumented within teeny-request. + */ +export declare class TeenyStatistics { + /** + * @description A default threshold representing when to warn about excessive + * in-flight/concurrent requests. + * @type {number} + * @static + * @readonly + * @default 5000 + */ + static readonly DEFAULT_WARN_CONCURRENT_REQUESTS = 5000; + /** + * @type {TeenyStatisticsConfig} + * @private + */ + private _options; + /** + * @type {number} + * @private + * @default 0 + */ + private _concurrentRequests; + /** + * @type {boolean} + * @private + * @default false + */ + private _didConcurrentRequestWarn; + /** + * @param {TeenyStatisticsOptions} [opts] + */ + constructor(opts?: TeenyStatisticsOptions); + /** + * Returns a copy of the current options. + * @return {TeenyStatisticsOptions} + */ + getOptions(): TeenyStatisticsOptions; + /** + * Change configured statistics options. This will not preserve unspecified + * options that were previously specified, i.e. this is a reset of options. + * @param {TeenyStatisticsOptions} [opts] + * @returns {TeenyStatisticsConfig} The previous options. + * @see _prepareOptions + */ + setOptions(opts?: TeenyStatisticsOptions): TeenyStatisticsConfig; + /** + * @readonly + * @return {TeenyStatisticsCounters} + */ + get counters(): TeenyStatisticsCounters; + /** + * @description Should call this right before making a request. + */ + requestStarting(): void; + /** + * @description When using `requestStarting`, call this after the request + * has finished. + */ + requestFinished(): void; + /** + * Configuration Precedence: + * 1. Dependency inversion via defined option. + * 2. Global numeric environment variable. + * 3. Built-in default. + * This will not preserve unspecified options previously specified. + * @param {TeenyStatisticsOptions} [opts] + * @returns {TeenyStatisticsOptions} + * @private + */ + private static _prepareOptions; +} +export {}; diff --git a/node_modules/teeny-request/build/src/TeenyStatistics.js b/node_modules/teeny-request/build/src/TeenyStatistics.js new file mode 100644 index 0000000..67d0b31 --- /dev/null +++ b/node_modules/teeny-request/build/src/TeenyStatistics.js @@ -0,0 +1,156 @@ +"use strict"; +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TeenyStatistics = exports.TeenyStatisticsWarning = void 0; +/** + * @class TeenyStatisticsWarning + * @extends Error + * @description While an error, is used for emitting warnings when + * meeting certain configured thresholds. + * @see process.emitWarning + */ +class TeenyStatisticsWarning extends Error { + /** + * @param {string} message + */ + constructor(message) { + super(message); + this.threshold = 0; + this.type = ''; + this.value = 0; + this.name = this.constructor.name; + Error.captureStackTrace(this, this.constructor); + } +} +exports.TeenyStatisticsWarning = TeenyStatisticsWarning; +TeenyStatisticsWarning.CONCURRENT_REQUESTS = 'ConcurrentRequestsExceededWarning'; +/** + * @class TeenyStatistics + * @description Maintain various statistics internal to teeny-request. Tracking + * is not automatic and must be instrumented within teeny-request. + */ +class TeenyStatistics { + /** + * @param {TeenyStatisticsOptions} [opts] + */ + constructor(opts) { + /** + * @type {number} + * @private + * @default 0 + */ + this._concurrentRequests = 0; + /** + * @type {boolean} + * @private + * @default false + */ + this._didConcurrentRequestWarn = false; + this._options = TeenyStatistics._prepareOptions(opts); + } + /** + * Returns a copy of the current options. + * @return {TeenyStatisticsOptions} + */ + getOptions() { + return Object.assign({}, this._options); + } + /** + * Change configured statistics options. This will not preserve unspecified + * options that were previously specified, i.e. this is a reset of options. + * @param {TeenyStatisticsOptions} [opts] + * @returns {TeenyStatisticsConfig} The previous options. + * @see _prepareOptions + */ + setOptions(opts) { + const oldOpts = this._options; + this._options = TeenyStatistics._prepareOptions(opts); + return oldOpts; + } + /** + * @readonly + * @return {TeenyStatisticsCounters} + */ + get counters() { + return { + concurrentRequests: this._concurrentRequests, + }; + } + /** + * @description Should call this right before making a request. + */ + requestStarting() { + this._concurrentRequests++; + if (this._options.concurrentRequests > 0 && + this._concurrentRequests >= this._options.concurrentRequests && + !this._didConcurrentRequestWarn) { + this._didConcurrentRequestWarn = true; + const warning = new TeenyStatisticsWarning('Possible excessive concurrent requests detected. ' + + this._concurrentRequests + + ' requests in-flight, which exceeds the configured threshold of ' + + this._options.concurrentRequests + + '. Use the TEENY_REQUEST_WARN_CONCURRENT_REQUESTS environment ' + + 'variable or the concurrentRequests option of teeny-request to ' + + 'increase or disable (0) this warning.'); + warning.type = TeenyStatisticsWarning.CONCURRENT_REQUESTS; + warning.value = this._concurrentRequests; + warning.threshold = this._options.concurrentRequests; + process.emitWarning(warning); + } + } + /** + * @description When using `requestStarting`, call this after the request + * has finished. + */ + requestFinished() { + // TODO negative? + this._concurrentRequests--; + } + /** + * Configuration Precedence: + * 1. Dependency inversion via defined option. + * 2. Global numeric environment variable. + * 3. Built-in default. + * This will not preserve unspecified options previously specified. + * @param {TeenyStatisticsOptions} [opts] + * @returns {TeenyStatisticsOptions} + * @private + */ + static _prepareOptions({ concurrentRequests: diConcurrentRequests, } = {}) { + let concurrentRequests = this.DEFAULT_WARN_CONCURRENT_REQUESTS; + const envConcurrentRequests = Number(process.env.TEENY_REQUEST_WARN_CONCURRENT_REQUESTS); + if (diConcurrentRequests !== undefined) { + concurrentRequests = diConcurrentRequests; + } + else if (!Number.isNaN(envConcurrentRequests)) { + concurrentRequests = envConcurrentRequests; + } + return { concurrentRequests }; + } +} +exports.TeenyStatistics = TeenyStatistics; +/** + * @description A default threshold representing when to warn about excessive + * in-flight/concurrent requests. + * @type {number} + * @static + * @readonly + * @default 5000 + */ +TeenyStatistics.DEFAULT_WARN_CONCURRENT_REQUESTS = 5000; +//# sourceMappingURL=TeenyStatistics.js.map \ No newline at end of file diff --git a/node_modules/teeny-request/build/src/TeenyStatistics.js.map b/node_modules/teeny-request/build/src/TeenyStatistics.js.map new file mode 100644 index 0000000..e16f12f --- /dev/null +++ b/node_modules/teeny-request/build/src/TeenyStatistics.js.map @@ -0,0 +1 @@ +{"version":3,"file":"TeenyStatistics.js","sourceRoot":"","sources":["../../src/TeenyStatistics.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAuBH;;;;;;GAMG;AACH,MAAa,sBAAuB,SAAQ,KAAK;IAO/C;;OAEG;IACH,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QARV,cAAS,GAAG,CAAC,CAAC;QACd,SAAI,GAAG,EAAE,CAAC;QACV,UAAK,GAAG,CAAC,CAAC;QAOf,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;QAClC,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IAClD,CAAC;;AAdH,wDAeC;AAdiB,0CAAmB,GAAG,mCAAmC,AAAtC,CAAuC;AAgB5E;;;;GAIG;AACH,MAAa,eAAe;IA+B1B;;OAEG;IACH,YAAY,IAA6B;QAjBzC;;;;WAIG;QACK,wBAAmB,GAAG,CAAC,CAAC;QAEhC;;;;WAIG;QACK,8BAAyB,GAAG,KAAK,CAAC;QAMxC,IAAI,CAAC,QAAQ,GAAG,eAAe,CAAC,eAAe,CA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BAAmB,EAAE,CAAC;IAC7B,CAAC;IAED;;;;;;;;;OASG;IACK,MAAM,CAAC,eAAe,CAAC,EAC7B,kBAAkB,EAAE,oBAAoB,MACd,EAAE;QAC5B,IAAI,kBAAkB,GAAG,IAAI,CAAC,gCAAgC,CAAC;QAE/D,MAAM,qBAAqB,GAAG,MAAM,CAClC,OAAO,CAAC,GAAG,CAAC,sCAAsC,CACnD,CAAC;QACF,IAAI,oBAAoB,KAAK,SAAS,EAAE;YACtC,kBAAkB,GAAG,oBAAoB,CAAC;SAC3C;aAAM,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,qBAAqB,CAAC,EAAE;YAC/C,kBAAkB,GAAG,qBAAqB,CAAC;SAC5C;QAED,OAAO,EAAC,kBAAkB,EAAC,CAAC;IAC9B,CAAC;;AAnIH,0CAoIC;AAnIC;;;;;;;GAOG;AACa,gDAAgC,GAAG,IAAI,AAAP,CAAQ"} \ No newline at end of file diff --git a/node_modules/teeny-request/build/src/agents.d.ts b/node_modules/teeny-request/build/src/agents.d.ts new file mode 100644 index 0000000..afa86ba --- /dev/null +++ b/node_modules/teeny-request/build/src/agents.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/// +/// +import { Agent as HTTPAgent } from 'http'; +import { Agent as HTTPSAgent } from 'https'; +import { Options } from './'; +export declare const pool: Map; +export type HttpAnyAgent = HTTPAgent | HTTPSAgent; +/** + * Returns a custom request Agent if one is found, otherwise returns undefined + * which will result in the global http(s) Agent being used. + * @private + * @param {string} uri The request uri + * @param {Options} reqOpts The request options + * @returns {HttpAnyAgent|undefined} + */ +export declare function getAgent(uri: string, reqOpts: Options): HttpAnyAgent | undefined; diff --git a/node_modules/teeny-request/build/src/agents.js b/node_modules/teeny-request/build/src/agents.js new file mode 100644 index 0000000..07c0e44 --- /dev/null +++ b/node_modules/teeny-request/build/src/agents.js @@ -0,0 +1,89 @@ +"use strict"; +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getAgent = exports.pool = void 0; +const http_1 = require("http"); +const https_1 = require("https"); +// eslint-disable-next-line node/no-deprecated-api +const url_1 = require("url"); +exports.pool = new Map(); +/** + * Determines if a proxy should be considered based on the environment. + * + * @param uri The request uri + * @returns {boolean} + */ +function shouldUseProxyForURI(uri) { + const noProxyEnv = process.env.NO_PROXY || process.env.no_proxy; + if (!noProxyEnv) { + return true; + } + const givenURI = new URL(uri); + for (const noProxyRaw of noProxyEnv.split(',')) { + const noProxy = noProxyRaw.trim(); + if (noProxy === givenURI.origin || noProxy === givenURI.hostname) { + return false; + } + else if (noProxy.startsWith('*.') || noProxy.startsWith('.')) { + const noProxyWildcard = noProxy.replace(/^\*\./, '.'); + if (givenURI.hostname.endsWith(noProxyWildcard)) { + return false; + } + } + } + return true; +} +/** + * Returns a custom request Agent if one is found, otherwise returns undefined + * which will result in the global http(s) Agent being used. + * @private + * @param {string} uri The request uri + * @param {Options} reqOpts The request options + * @returns {HttpAnyAgent|undefined} + */ +function getAgent(uri, reqOpts) { + const isHttp = uri.startsWith('http://'); + const proxy = reqOpts.proxy || + process.env.HTTP_PROXY || + process.env.http_proxy || + process.env.HTTPS_PROXY || + process.env.https_proxy; + const poolOptions = Object.assign({}, reqOpts.pool); + const manuallyProvidedProxy = !!reqOpts.proxy; + const shouldUseProxy = manuallyProvidedProxy || shouldUseProxyForURI(uri); + if (proxy && shouldUseProxy) { + // tslint:disable-next-line variable-name + const Agent = isHttp + ? require('http-proxy-agent') + : require('https-proxy-agent'); + const proxyOpts = { ...(0, url_1.parse)(proxy), ...poolOptions }; + return new Agent(proxyOpts); + } + let key = isHttp ? 'http' : 'https'; + if (reqOpts.forever) { + key += ':forever'; + if (!exports.pool.has(key)) { + // tslint:disable-next-line variable-name + const Agent = isHttp ? http_1.Agent : https_1.Agent; + exports.pool.set(key, new Agent({ ...poolOptions, keepAlive: true })); + } + } + return exports.pool.get(key); +} +exports.getAgent = getAgent; +//# sourceMappingURL=agents.js.map \ No newline at end of file diff --git a/node_modules/teeny-request/build/src/agents.js.map b/node_modules/teeny-request/build/src/agents.js.map new file mode 100644 index 0000000..a3e1403 --- /dev/null +++ b/node_modules/teeny-request/build/src/agents.js.map @@ -0,0 +1 @@ +{"version":3,"file":"agents.js","sourceRoot":"","sources":["../../src/agents.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,+BAAwC;AACxC,iCAA0C;AAC1C,kDAAkD;AAClD,6BAA0B;AAGb,QAAA,IAAI,GAAG,IAAI,GAAG,EAAqB,CAAC;AAIjD;;;;;GAKG;AACH,SAAS,oBAAoB,CAAC,GAAW;IACvC,MAAM,UAAU,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;IAChE,IAAI,CAAC,UAAU,EAAE;QACf,OAAO,IAAI,CAAC;KACb;IAED,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;IAE9B,KAAK,MAAM,UAAU,IAAI,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE;QAC9C,MAAM,OAAO,GAAG,UAAU,CAAC,IAAI,EAAE,CAAC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EAAE,GAAG,WAAW,EAAC,CAAC;QACpD,OAAO,IAAI,KAAK,CAAC,SAAS,CAAC,CAAC;KAC7B;IAED,IAAI,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC;IAEpC,IAAI,OAAO,CAAC,OAAO,EAAE;QACnB,GAAG,IAAI,UAAU,CAAC;QAElB,IAAI,CAAC,YAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;YAClB,yCAAyC;YACzC,MAAM,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,YAAS,CAAC,CAAC,CAAC,aAAU,CAAC;YAC9C,YAAI,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,KAAK,CAAC,EAAC,GAAG,WAAW,EAAE,SAAS,EAAE,IAAI,EAAC,CAAC,CAAC,CAAC;SAC7D;KACF;IAED,OAAO,YAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACvB,CAAC;AAxCD,4BAwCC"} \ No newline at end of file diff --git a/node_modules/teeny-request/build/src/index.d.ts b/node_modules/teeny-request/build/src/index.d.ts new file mode 100644 index 0000000..f5585b9 --- /dev/null +++ b/node_modules/teeny-request/build/src/index.d.ts @@ -0,0 +1,76 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/// +/// +/// +import { Agent, AgentOptions as HttpsAgentOptions } from 'https'; +import { AgentOptions as HttpAgentOptions } from 'http'; +import { PassThrough, Readable } from 'stream'; +import { TeenyStatistics } from './TeenyStatistics'; +export interface CoreOptions { + method?: string; + timeout?: number; + gzip?: boolean; + json?: any; + headers?: Headers; + body?: string | {}; + useQuerystring?: boolean; + qs?: any; + proxy?: string; + multipart?: RequestPart[]; + forever?: boolean; + pool?: HttpsAgentOptions | HttpAgentOptions; +} +export interface OptionsWithUri extends CoreOptions { + uri: string; +} +export interface OptionsWithUrl extends CoreOptions { + url: string; +} +export type Options = OptionsWithUri | OptionsWithUrl; +export interface Request extends PassThrough { + agent: Agent | false; + headers: Headers; + href?: string; +} +export interface Response { + statusCode: number; + headers: Headers; + body: T; + request: Request; + statusMessage?: string; +} +export interface RequestPart { + body: string | Readable; +} +export interface RequestCallback { + (err: Error | null, response: Response, body?: T): void; +} +export declare class RequestError extends Error { + code?: number; +} +interface Headers { + [index: string]: any; +} +declare function teenyRequest(reqOpts: Options): Request; +declare function teenyRequest(reqOpts: Options, callback: RequestCallback): void; +declare namespace teenyRequest { + var defaults: (defaults: CoreOptions) => (reqOpts: Options, callback?: RequestCallback | undefined) => void | Request; + var stats: TeenyStatistics; + var resetStats: () => void; +} +export { teenyRequest }; diff --git a/node_modules/teeny-request/build/src/index.js b/node_modules/teeny-request/build/src/index.js new file mode 100644 index 0000000..af5d15e --- /dev/null +++ b/node_modules/teeny-request/build/src/index.js @@ -0,0 +1,253 @@ +"use strict"; +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.teenyRequest = exports.RequestError = void 0; +const node_fetch_1 = require("node-fetch"); +const stream_1 = require("stream"); +const uuid = require("uuid"); +const agents_1 = require("./agents"); +const TeenyStatistics_1 = require("./TeenyStatistics"); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const streamEvents = require('stream-events'); +class RequestError extends Error { +} +exports.RequestError = RequestError; +/** + * Convert options from Request to Fetch format + * @private + * @param reqOpts Request options + */ +function requestToFetchOptions(reqOpts) { + const options = { + method: reqOpts.method || 'GET', + ...(reqOpts.timeout && { timeout: reqOpts.timeout }), + ...(typeof reqOpts.gzip === 'boolean' && { compress: reqOpts.gzip }), + }; + if (typeof reqOpts.json === 'object') { + // Add Content-type: application/json header + reqOpts.headers = reqOpts.headers || {}; + reqOpts.headers['Content-Type'] = 'application/json'; + // Set body to JSON representation of value + options.body = JSON.stringify(reqOpts.json); + } + else { + if (Buffer.isBuffer(reqOpts.body)) { + options.body = reqOpts.body; + } + else if (typeof reqOpts.body !== 'string') { + options.body = JSON.stringify(reqOpts.body); + } + else { + options.body = reqOpts.body; + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + options.headers = reqOpts.headers; + let uri = (reqOpts.uri || + reqOpts.url); + if (!uri) { + throw new Error('Missing uri or url in reqOpts.'); + } + if (reqOpts.useQuerystring === true || typeof reqOpts.qs === 'object') { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const qs = require('querystring'); + const params = qs.stringify(reqOpts.qs); + uri = uri + '?' + params; + } + options.agent = (0, agents_1.getAgent)(uri, reqOpts); + return { uri, options }; +} +/** + * Convert a response from `fetch` to `request` format. + * @private + * @param opts The `request` options used to create the request. + * @param res The Fetch response + * @returns A `request` response object + */ +function fetchToRequestResponse(opts, res) { + const request = {}; + request.agent = opts.agent || false; + request.headers = (opts.headers || {}); + request.href = res.url; + // headers need to be converted from a map to an obj + const resHeaders = {}; + res.headers.forEach((value, key) => (resHeaders[key] = value)); + const response = Object.assign(res.body, { + statusCode: res.status, + statusMessage: res.statusText, + request, + body: res.body, + headers: resHeaders, + toJSON: () => ({ headers: resHeaders }), + }); + return response; +} +/** + * Create POST body from two parts as multipart/related content-type + * @private + * @param boundary + * @param multipart + */ +function createMultipartStream(boundary, multipart) { + const finale = `--${boundary}--`; + const stream = new stream_1.PassThrough(); + for (const part of multipart) { + const preamble = `--${boundary}\r\nContent-Type: ${part['Content-Type']}\r\n\r\n`; + stream.write(preamble); + if (typeof part.body === 'string') { + stream.write(part.body); + stream.write('\r\n'); + } + else { + part.body.pipe(stream, { end: false }); + part.body.on('end', () => { + stream.write('\r\n'); + stream.write(finale); + stream.end(); + }); + } + } + return stream; +} +function teenyRequest(reqOpts, callback) { + const { uri, options } = requestToFetchOptions(reqOpts); + const multipart = reqOpts.multipart; + if (reqOpts.multipart && multipart.length === 2) { + if (!callback) { + // TODO: add support for multipart uploads through streaming + throw new Error('Multipart without callback is not implemented.'); + } + const boundary = uuid.v4(); + options.headers['Content-Type'] = `multipart/related; boundary=${boundary}`; + options.body = createMultipartStream(boundary, multipart); + // Multipart upload + teenyRequest.stats.requestStarting(); + (0, node_fetch_1.default)(uri, options).then(res => { + teenyRequest.stats.requestFinished(); + const header = res.headers.get('content-type'); + const response = fetchToRequestResponse(options, res); + const body = response.body; + if (header === 'application/json' || + header === 'application/json; charset=utf-8') { + res.json().then(json => { + response.body = json; + callback(null, response, json); + }, (err) => { + callback(err, response, body); + }); + return; + } + res.text().then(text => { + response.body = text; + callback(null, response, text); + }, err => { + callback(err, response, body); + }); + }, err => { + teenyRequest.stats.requestFinished(); + callback(err, null, null); + }); + return; + } + if (callback === undefined) { + // Stream mode + const requestStream = streamEvents(new stream_1.PassThrough()); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let responseStream; + requestStream.once('reading', () => { + if (responseStream) { + (0, stream_1.pipeline)(responseStream, requestStream, () => { }); + } + else { + requestStream.once('response', () => { + (0, stream_1.pipeline)(responseStream, requestStream, () => { }); + }); + } + }); + options.compress = false; + teenyRequest.stats.requestStarting(); + (0, node_fetch_1.default)(uri, options).then(res => { + teenyRequest.stats.requestFinished(); + responseStream = res.body; + responseStream.on('error', (err) => { + requestStream.emit('error', err); + }); + const response = fetchToRequestResponse(options, res); + requestStream.emit('response', response); + }, err => { + teenyRequest.stats.requestFinished(); + requestStream.emit('error', err); + }); + // fetch doesn't supply the raw HTTP stream, instead it + // returns a PassThrough piped from the HTTP response + // stream. + return requestStream; + } + // GET or POST with callback + teenyRequest.stats.requestStarting(); + (0, node_fetch_1.default)(uri, options).then(res => { + teenyRequest.stats.requestFinished(); + const header = res.headers.get('content-type'); + const response = fetchToRequestResponse(options, res); + const body = response.body; + if (header === 'application/json' || + header === 'application/json; charset=utf-8') { + if (response.statusCode === 204) { + // Probably a DELETE + callback(null, response, body); + return; + } + res.json().then(json => { + response.body = json; + callback(null, response, json); + }, err => { + callback(err, response, body); + }); + return; + } + res.text().then(text => { + const response = fetchToRequestResponse(options, res); + response.body = text; + callback(null, response, text); + }, err => { + callback(err, response, body); + }); + }, err => { + teenyRequest.stats.requestFinished(); + callback(err, null, null); + }); + return; +} +exports.teenyRequest = teenyRequest; +teenyRequest.defaults = (defaults) => { + return (reqOpts, callback) => { + const opts = { ...defaults, ...reqOpts }; + if (callback === undefined) { + return teenyRequest(opts); + } + teenyRequest(opts, callback); + }; +}; +/** + * Single instance of an interface for keeping track of things. + */ +teenyRequest.stats = new TeenyStatistics_1.TeenyStatistics(); +teenyRequest.resetStats = () => { + teenyRequest.stats = new TeenyStatistics_1.TeenyStatistics(teenyRequest.stats.getOptions()); +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/teeny-request/build/src/index.js.map b/node_modules/teeny-request/build/src/index.js.map new file mode 100644 index 0000000..1513c49 --- /dev/null +++ b/node_modules/teeny-request/build/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAIH,2CAAuC;AACvC,mCAAuD;AACvD,6BAA6B;AAC7B,qCAAkC;AAClC,uDAAkD;AAClD,8DAA8D;AAC9D,MAAM,YAAY,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;AAqD9C,MAAa,YAAa,SAAQ,KAAK;CAEtC;AAFD,oCAEC;AA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a/node_modules/teeny-request/node_modules/.bin/uuid b/node_modules/teeny-request/node_modules/.bin/uuid new file mode 100644 index 0000000..0c2d469 --- /dev/null +++ b/node_modules/teeny-request/node_modules/.bin/uuid @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../uuid/dist/bin/uuid" "$@" +else + exec node "$basedir/../uuid/dist/bin/uuid" "$@" +fi diff --git a/node_modules/teeny-request/node_modules/.bin/uuid.cmd b/node_modules/teeny-request/node_modules/.bin/uuid.cmd new file mode 100644 index 0000000..0f2376e --- /dev/null +++ b/node_modules/teeny-request/node_modules/.bin/uuid.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\uuid\dist\bin\uuid" %* diff --git a/node_modules/teeny-request/node_modules/.bin/uuid.ps1 b/node_modules/teeny-request/node_modules/.bin/uuid.ps1 new file mode 100644 index 0000000..7804628 --- /dev/null +++ b/node_modules/teeny-request/node_modules/.bin/uuid.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } else { + & "$basedir/node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } else { + & "node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/teeny-request/node_modules/agent-base/README.md b/node_modules/teeny-request/node_modules/agent-base/README.md new file mode 100644 index 0000000..256f1f3 --- /dev/null +++ b/node_modules/teeny-request/node_modules/agent-base/README.md @@ -0,0 +1,145 @@ +agent-base +========== +### Turn a function into an [`http.Agent`][http.Agent] instance +[![Build Status](https://github.com/TooTallNate/node-agent-base/workflows/Node%20CI/badge.svg)](https://github.com/TooTallNate/node-agent-base/actions?workflow=Node+CI) + +This module provides an `http.Agent` generator. That is, you pass it an async +callback function, and it returns a new `http.Agent` instance that will invoke the +given callback function when sending outbound HTTP requests. + +#### Some subclasses: + +Here's some more interesting uses of `agent-base`. +Send a pull request to list yours! + + * [`http-proxy-agent`][http-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTP endpoints + * [`https-proxy-agent`][https-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTPS endpoints + * [`pac-proxy-agent`][pac-proxy-agent]: A PAC file proxy `http.Agent` implementation for HTTP and HTTPS + * [`socks-proxy-agent`][socks-proxy-agent]: A SOCKS proxy `http.Agent` implementation for HTTP and HTTPS + + +Installation +------------ + +Install with `npm`: + +``` bash +$ npm install agent-base +``` + + +Example +------- + +Here's a minimal example that creates a new `net.Socket` connection to the server +for every HTTP request (i.e. the equivalent of `agent: false` option): + +```js +var net = require('net'); +var tls = require('tls'); +var url = require('url'); +var http = require('http'); +var agent = require('agent-base'); + +var endpoint = 'http://nodejs.org/api/'; +var parsed = url.parse(endpoint); + +// This is the important part! +parsed.agent = agent(function (req, opts) { + var socket; + // `secureEndpoint` is true when using the https module + if (opts.secureEndpoint) { + socket = tls.connect(opts); + } else { + socket = net.connect(opts); + } + return socket; +}); + +// Everything else works just like normal... +http.get(parsed, function (res) { + console.log('"response" event!', res.headers); + res.pipe(process.stdout); +}); +``` + +Returning a Promise or using an `async` function is also supported: + +```js +agent(async function (req, opts) { + await sleep(1000); + // etc… +}); +``` + +Return another `http.Agent` instance to "pass through" the responsibility +for that HTTP request to that agent: + +```js +agent(function (req, opts) { + return opts.secureEndpoint ? https.globalAgent : http.globalAgent; +}); +``` + + +API +--- + +## Agent(Function callback[, Object options]) → [http.Agent][] + +Creates a base `http.Agent` that will execute the callback function `callback` +for every HTTP request that it is used as the `agent` for. The callback function +is responsible for creating a `stream.Duplex` instance of some kind that will be +used as the underlying socket in the HTTP request. + +The `options` object accepts the following properties: + + * `timeout` - Number - Timeout for the `callback()` function in milliseconds. Defaults to Infinity (optional). + +The callback function should have the following signature: + +### callback(http.ClientRequest req, Object options, Function cb) → undefined + +The ClientRequest `req` can be accessed to read request headers and +and the path, etc. The `options` object contains the options passed +to the `http.request()`/`https.request()` function call, and is formatted +to be directly passed to `net.connect()`/`tls.connect()`, or however +else you want a Socket to be created. Pass the created socket to +the callback function `cb` once created, and the HTTP request will +continue to proceed. + +If the `https` module is used to invoke the HTTP request, then the +`secureEndpoint` property on `options` _will be set to `true`_. + + +License +------- + +(The MIT License) + +Copyright (c) 2013 Nathan Rajlich <nathan@tootallnate.net> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +[http-proxy-agent]: https://github.com/TooTallNate/node-http-proxy-agent +[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent +[pac-proxy-agent]: https://github.com/TooTallNate/node-pac-proxy-agent +[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent +[http.Agent]: https://nodejs.org/api/http.html#http_class_http_agent diff --git a/node_modules/teeny-request/node_modules/agent-base/dist/src/index.d.ts b/node_modules/teeny-request/node_modules/agent-base/dist/src/index.d.ts new file mode 100644 index 0000000..bc4ab74 --- /dev/null +++ b/node_modules/teeny-request/node_modules/agent-base/dist/src/index.d.ts @@ -0,0 +1,78 @@ +/// +import net from 'net'; +import http from 'http'; +import https from 'https'; +import { Duplex } from 'stream'; +import { EventEmitter } from 'events'; +declare function createAgent(opts?: createAgent.AgentOptions): createAgent.Agent; +declare function createAgent(callback: createAgent.AgentCallback, opts?: createAgent.AgentOptions): createAgent.Agent; +declare namespace createAgent { + interface ClientRequest extends http.ClientRequest { + _last?: boolean; + _hadError?: boolean; + method: string; + } + interface AgentRequestOptions { + host?: string; + path?: string; + port: number; + } + interface HttpRequestOptions extends AgentRequestOptions, Omit { + secureEndpoint: false; + } + interface HttpsRequestOptions extends AgentRequestOptions, Omit { + secureEndpoint: true; + } + type RequestOptions = HttpRequestOptions | HttpsRequestOptions; + type AgentLike = Pick | http.Agent; + type AgentCallbackReturn = Duplex | AgentLike; + type AgentCallbackCallback = (err?: Error | null, socket?: createAgent.AgentCallbackReturn) => void; + type AgentCallbackPromise = (req: createAgent.ClientRequest, opts: createAgent.RequestOptions) => createAgent.AgentCallbackReturn | Promise; + type AgentCallback = typeof Agent.prototype.callback; + type AgentOptions = { + timeout?: number; + }; + /** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + * + * @param {Function} callback + * @api public + */ + class Agent extends EventEmitter { + timeout: number | null; + maxFreeSockets: number; + maxTotalSockets: number; + maxSockets: number; + sockets: { + [key: string]: net.Socket[]; + }; + freeSockets: { + [key: string]: net.Socket[]; + }; + requests: { + [key: string]: http.IncomingMessage[]; + }; + options: https.AgentOptions; + private promisifiedCallback?; + private explicitDefaultPort?; + private explicitProtocol?; + constructor(callback?: createAgent.AgentCallback | createAgent.AgentOptions, _opts?: createAgent.AgentOptions); + get defaultPort(): number; + set defaultPort(v: number); + get protocol(): string; + set protocol(v: string); + callback(req: createAgent.ClientRequest, opts: createAgent.RequestOptions, fn: createAgent.AgentCallbackCallback): void; + callback(req: createAgent.ClientRequest, opts: createAgent.RequestOptions): createAgent.AgentCallbackReturn | Promise; + /** + * Called by node-core's "_http_client.js" module when creating + * a new HTTP request with this Agent instance. + * + * @api public + */ + addRequest(req: ClientRequest, _opts: RequestOptions): void; + freeSocket(socket: net.Socket, opts: AgentOptions): void; + destroy(): void; + } +} +export = createAgent; diff --git a/node_modules/teeny-request/node_modules/agent-base/dist/src/index.js b/node_modules/teeny-request/node_modules/agent-base/dist/src/index.js new file mode 100644 index 0000000..bfd9e22 --- /dev/null +++ b/node_modules/teeny-request/node_modules/agent-base/dist/src/index.js @@ -0,0 +1,203 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const events_1 = require("events"); +const debug_1 = __importDefault(require("debug")); +const promisify_1 = __importDefault(require("./promisify")); +const debug = debug_1.default('agent-base'); +function isAgent(v) { + return Boolean(v) && typeof v.addRequest === 'function'; +} +function isSecureEndpoint() { + const { stack } = new Error(); + if (typeof stack !== 'string') + return false; + return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); +} +function createAgent(callback, opts) { + return new createAgent.Agent(callback, opts); +} +(function (createAgent) { + /** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + * + * @param {Function} callback + * @api public + */ + class Agent extends events_1.EventEmitter { + constructor(callback, _opts) { + super(); + let opts = _opts; + if (typeof callback === 'function') { + this.callback = callback; + } + else if (callback) { + opts = callback; + } + // Timeout for the socket to be returned from the callback + this.timeout = null; + if (opts && typeof opts.timeout === 'number') { + this.timeout = opts.timeout; + } + // These aren't actually used by `agent-base`, but are required + // for the TypeScript definition files in `@types/node` :/ + this.maxFreeSockets = 1; + this.maxSockets = 1; + this.maxTotalSockets = Infinity; + this.sockets = {}; + this.freeSockets = {}; + this.requests = {}; + this.options = {}; + } + get defaultPort() { + if (typeof this.explicitDefaultPort === 'number') { + return this.explicitDefaultPort; + } + return isSecureEndpoint() ? 443 : 80; + } + set defaultPort(v) { + this.explicitDefaultPort = v; + } + get protocol() { + if (typeof this.explicitProtocol === 'string') { + return this.explicitProtocol; + } + return isSecureEndpoint() ? 'https:' : 'http:'; + } + set protocol(v) { + this.explicitProtocol = v; + } + callback(req, opts, fn) { + throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); + } + /** + * Called by node-core's "_http_client.js" module when creating + * a new HTTP request with this Agent instance. + * + * @api public + */ + addRequest(req, _opts) { + const opts = Object.assign({}, _opts); + if (typeof opts.secureEndpoint !== 'boolean') { + opts.secureEndpoint = isSecureEndpoint(); + } + if (opts.host == null) { + opts.host = 'localhost'; + } + if (opts.port == null) { + opts.port = opts.secureEndpoint ? 443 : 80; + } + if (opts.protocol == null) { + opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; + } + if (opts.host && opts.path) { + // If both a `host` and `path` are specified then it's most + // likely the result of a `url.parse()` call... we need to + // remove the `path` portion so that `net.connect()` doesn't + // attempt to open that as a unix socket file. + delete opts.path; + } + delete opts.agent; + delete opts.hostname; + delete opts._defaultAgent; + delete opts.defaultPort; + delete opts.createConnection; + // Hint to use "Connection: close" + // XXX: non-documented `http` module API :( + req._last = true; + req.shouldKeepAlive = false; + let timedOut = false; + let timeoutId = null; + const timeoutMs = opts.timeout || this.timeout; + const onerror = (err) => { + if (req._hadError) + return; + req.emit('error', err); + // For Safety. Some additional errors might fire later on + // and we need to make sure we don't double-fire the error event. + req._hadError = true; + }; + const ontimeout = () => { + timeoutId = null; + timedOut = true; + const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); + err.code = 'ETIMEOUT'; + onerror(err); + }; + const callbackError = (err) => { + if (timedOut) + return; + if (timeoutId !== null) { + clearTimeout(timeoutId); + timeoutId = null; + } + onerror(err); + }; + const onsocket = (socket) => { + if (timedOut) + return; + if (timeoutId != null) { + clearTimeout(timeoutId); + timeoutId = null; + } + if (isAgent(socket)) { + // `socket` is actually an `http.Agent` instance, so + // relinquish responsibility for this `req` to the Agent + // from here on + debug('Callback returned another Agent instance %o', socket.constructor.name); + socket.addRequest(req, opts); + return; + } + if (socket) { + socket.once('free', () => { + this.freeSocket(socket, opts); + }); + req.onSocket(socket); + return; + } + const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); + onerror(err); + }; + if (typeof this.callback !== 'function') { + onerror(new Error('`callback` is not defined')); + return; + } + if (!this.promisifiedCallback) { + if (this.callback.length >= 3) { + debug('Converting legacy callback function to promise'); + this.promisifiedCallback = promisify_1.default(this.callback); + } + else { + this.promisifiedCallback = this.callback; + } + } + if (typeof timeoutMs === 'number' && timeoutMs > 0) { + timeoutId = setTimeout(ontimeout, timeoutMs); + } + if ('port' in opts && typeof opts.port !== 'number') { + opts.port = Number(opts.port); + } + try { + debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`); + Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); + } + catch (err) { + Promise.reject(err).catch(callbackError); + } + } + freeSocket(socket, opts) { + debug('Freeing socket %o %o', socket.constructor.name, opts); + socket.destroy(); + } + destroy() { + debug('Destroying agent %o', this.constructor.name); + } + } + createAgent.Agent = Agent; + // So that `instanceof` works correctly + createAgent.prototype = createAgent.Agent.prototype; +})(createAgent || (createAgent = {})); +module.exports = createAgent; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/agent-base/dist/src/index.js.map b/node_modules/teeny-request/node_modules/agent-base/dist/src/index.js.map new file mode 100644 index 0000000..bd118ab --- /dev/null +++ b/node_modules/teeny-request/node_modules/agent-base/dist/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;AAIA,mCAAsC;AACtC,kDAAgC;AAChC,4DAAoC;AAEpC,MAAM,KAAK,GAAG,eAAW,CAAC,YAAY,CAAC,CAAC;AAExC,SAAS,OAAO,CAAC,CAAM;IACtB,OAAO,OAAO,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,CAAC,UAAU,KAAK,UAAU,CAAC;AACzD,CAAC;AAED,SAAS,gBAAgB;IACxB,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,KAAK,EAAE,CAAC;IAC9B,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC5C,OAAO,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,IAAK,CAAC,CAAC,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACxG,CAAC;AAOD,SAAS,WAAW,CACnB,QAA+D,EAC/D,IAA+B;IAE/B,OAAO,IAAI,WAAW,CAAC,KAAK,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;AAC9C,CAAC;AAED,WAAU,WAAW;IAmDpB;;;;;;OAMG;IACH,MAAa,KAAM,SAAQ,qBAAY;QAmBtC,YACC,QAA+D,EAC/D,KAAgC;YAEhC,KAA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AAI,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ,EAAE;gBACpD,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;aAC9B;YAED,IAAI;gBACH,KAAK,CACJ,qCAAqC,EACrC,IAAI,CAAC,QAAQ,EACb,GAAG,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,IAAI,EAAE,CAC3B,CAAC;gBACF,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,mBAAmB,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CACxD,QAAQ,EACR,aAAa,CACb,CAAC;aACF;YAAC,OAAO,GAAG,EAAE;gBACb,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;aACzC;QACF,CAAC;QAED,UAAU,CAAC,MAAkB,EAAE,IAAkB;YAChD,KAAK,CAAC,sBAAsB,EAAE,MAAM,CAAC,WAAW,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YAC7D,MAAM,CAAC,OAAO,EAAE,CAAC;QAClB,CAAC;QAED,OAAO;YACN,KAAK,CAAC,qBAAqB,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QACrD,CAAC;KACD;IAxPY,iBAAK,QAwPjB,CAAA;IAED,uCAAuC;IACvC,WAAW,CAAC,SAAS,GAAG,WAAW,CAAC,KAAK,CAAC,SAAS,CAAC;AACrD,CAAC,EAtTS,WAAW,KAAX,WAAW,QAsTpB;AAED,iBAAS,WAAW,CAAC"} \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/agent-base/dist/src/promisify.d.ts b/node_modules/teeny-request/node_modules/agent-base/dist/src/promisify.d.ts new file mode 100644 index 0000000..0268869 --- /dev/null +++ b/node_modules/teeny-request/node_modules/agent-base/dist/src/promisify.d.ts @@ -0,0 +1,4 @@ +import { ClientRequest, RequestOptions, AgentCallbackCallback, AgentCallbackPromise } from './index'; +declare type LegacyCallback = (req: ClientRequest, opts: RequestOptions, fn: AgentCallbackCallback) => void; +export default function promisify(fn: LegacyCallback): AgentCallbackPromise; +export {}; diff --git a/node_modules/teeny-request/node_modules/agent-base/dist/src/promisify.js b/node_modules/teeny-request/node_modules/agent-base/dist/src/promisify.js new file mode 100644 index 0000000..b2f6132 --- /dev/null +++ b/node_modules/teeny-request/node_modules/agent-base/dist/src/promisify.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +function promisify(fn) { + return function (req, opts) { + return new Promise((resolve, reject) => { + fn.call(this, req, opts, (err, rtn) => { + if (err) { + reject(err); + } + else { + resolve(rtn); + } + }); + }); + }; +} +exports.default = promisify; +//# sourceMappingURL=promisify.js.map \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/agent-base/dist/src/promisify.js.map b/node_modules/teeny-request/node_modules/agent-base/dist/src/promisify.js.map new file mode 100644 index 0000000..4bff9bf --- /dev/null +++ b/node_modules/teeny-request/node_modules/agent-base/dist/src/promisify.js.map @@ -0,0 +1 @@ +{"version":3,"file":"promisify.js","sourceRoot":"","sources":["../../src/promisify.ts"],"names":[],"mappings":";;AAeA,SAAwB,SAAS,CAAC,EAAkB;IACnD,OAAO,UAAsB,GAAkB,EAAE,IAAoB;QACpE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACtC,EAAE,CAAC,IAAI,CACN,IAAI,EACJ,GAAG,EACH,IAAI,EACJ,CAAC,GAA6B,EAAE,GAAyB,EAAE,EAAE;gBAC5D,IAAI,GAAG,EAAE;oBACR,MAAM,CAAC,GAAG,CAAC,CAAC;iBACZ;qBAAM;oBACN,OAAO,CAAC,GAAG,CAAC,CAAC;iBACb;YACF,CAAC,CACD,CAAC;QACH,CAAC,CAAC,CAAC;IACJ,CAAC,CAAC;AACH,CAAC;AAjBD,4BAiBC"} \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/agent-base/package.json b/node_modules/teeny-request/node_modules/agent-base/package.json new file mode 100644 index 0000000..fadce3a --- /dev/null +++ b/node_modules/teeny-request/node_modules/agent-base/package.json @@ -0,0 +1,64 @@ +{ + "name": "agent-base", + "version": "6.0.2", + "description": "Turn a function into an `http.Agent` instance", + "main": "dist/src/index", + "typings": "dist/src/index", + "files": [ + "dist/src", + "src" + ], + "scripts": { + "prebuild": "rimraf dist", + "build": "tsc", + "postbuild": "cpy --parents src test '!**/*.ts' dist", + "test": "mocha --reporter spec dist/test/*.js", + "test-lint": "eslint src --ext .js,.ts", + "prepublishOnly": "npm run build" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/node-agent-base.git" + }, + "keywords": [ + "http", + "agent", + "base", + "barebones", + "https" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/node-agent-base/issues" + }, + "dependencies": { + "debug": "4" + }, + "devDependencies": { + "@types/debug": "4", + "@types/mocha": "^5.2.7", + "@types/node": "^14.0.20", + "@types/semver": "^7.1.0", + "@types/ws": "^6.0.3", + "@typescript-eslint/eslint-plugin": "1.6.0", + "@typescript-eslint/parser": "1.1.0", + "async-listen": "^1.2.0", + "cpy-cli": "^2.0.0", + "eslint": "5.16.0", + "eslint-config-airbnb": "17.1.0", + "eslint-config-prettier": "4.1.0", + "eslint-import-resolver-typescript": "1.1.1", + "eslint-plugin-import": "2.16.0", + "eslint-plugin-jsx-a11y": "6.2.1", + "eslint-plugin-react": "7.12.4", + "mocha": "^6.2.0", + "rimraf": "^3.0.0", + "semver": "^7.1.2", + "typescript": "^3.5.3", + "ws": "^3.0.0" + }, + "engines": { + "node": ">= 6.0.0" + } +} diff --git a/node_modules/teeny-request/node_modules/agent-base/src/index.ts b/node_modules/teeny-request/node_modules/agent-base/src/index.ts new file mode 100644 index 0000000..a47ccd4 --- /dev/null +++ b/node_modules/teeny-request/node_modules/agent-base/src/index.ts @@ -0,0 +1,345 @@ +import net from 'net'; +import http from 'http'; +import https from 'https'; +import { Duplex } from 'stream'; +import { EventEmitter } from 'events'; +import createDebug from 'debug'; +import promisify from './promisify'; + +const debug = createDebug('agent-base'); + +function isAgent(v: any): v is createAgent.AgentLike { + return Boolean(v) && typeof v.addRequest === 'function'; +} + +function isSecureEndpoint(): boolean { + const { stack } = new Error(); + if (typeof stack !== 'string') return false; + return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); +} + +function createAgent(opts?: createAgent.AgentOptions): createAgent.Agent; +function createAgent( + callback: createAgent.AgentCallback, + opts?: createAgent.AgentOptions +): createAgent.Agent; +function createAgent( + callback?: createAgent.AgentCallback | createAgent.AgentOptions, + opts?: createAgent.AgentOptions +) { + return new createAgent.Agent(callback, opts); +} + +namespace createAgent { + export interface ClientRequest extends http.ClientRequest { + _last?: boolean; + _hadError?: boolean; + method: string; + } + + export interface AgentRequestOptions { + host?: string; + path?: string; + // `port` on `http.RequestOptions` can be a string or undefined, + // but `net.TcpNetConnectOpts` expects only a number + port: number; + } + + export interface HttpRequestOptions + extends AgentRequestOptions, + Omit { + secureEndpoint: false; + } + + export interface HttpsRequestOptions + extends AgentRequestOptions, + Omit { + secureEndpoint: true; + } + + export type RequestOptions = HttpRequestOptions | HttpsRequestOptions; + + export type AgentLike = Pick | http.Agent; + + export type AgentCallbackReturn = Duplex | AgentLike; + + export type AgentCallbackCallback = ( + err?: Error | null, + socket?: createAgent.AgentCallbackReturn + ) => void; + + export type AgentCallbackPromise = ( + req: createAgent.ClientRequest, + opts: createAgent.RequestOptions + ) => + | createAgent.AgentCallbackReturn + | Promise; + + export type AgentCallback = typeof Agent.prototype.callback; + + export type AgentOptions = { + timeout?: number; + }; + + /** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + * + * @param {Function} callback + * @api public + */ + export class Agent extends EventEmitter { + public timeout: number | null; + public maxFreeSockets: number; + public maxTotalSockets: number; + public maxSockets: number; + public sockets: { + [key: string]: net.Socket[]; + }; + public freeSockets: { + [key: string]: net.Socket[]; + }; + public requests: { + [key: string]: http.IncomingMessage[]; + }; + public options: https.AgentOptions; + private promisifiedCallback?: createAgent.AgentCallbackPromise; + private explicitDefaultPort?: number; + private explicitProtocol?: string; + + constructor( + callback?: createAgent.AgentCallback | createAgent.AgentOptions, + _opts?: createAgent.AgentOptions + ) { + super(); + + let opts = _opts; + if (typeof callback === 'function') { + this.callback = callback; + } else if (callback) { + opts = callback; + } + + // Timeout for the socket to be returned from the callback + this.timeout = null; + if (opts && typeof opts.timeout === 'number') { + this.timeout = opts.timeout; + } + + // These aren't actually used by `agent-base`, but are required + // for the TypeScript definition files in `@types/node` :/ + this.maxFreeSockets = 1; + this.maxSockets = 1; + this.maxTotalSockets = Infinity; + this.sockets = {}; + this.freeSockets = {}; + this.requests = {}; + this.options = {}; + } + + get defaultPort(): number { + if (typeof this.explicitDefaultPort === 'number') { + return this.explicitDefaultPort; + } + return isSecureEndpoint() ? 443 : 80; + } + + set defaultPort(v: number) { + this.explicitDefaultPort = v; + } + + get protocol(): string { + if (typeof this.explicitProtocol === 'string') { + return this.explicitProtocol; + } + return isSecureEndpoint() ? 'https:' : 'http:'; + } + + set protocol(v: string) { + this.explicitProtocol = v; + } + + callback( + req: createAgent.ClientRequest, + opts: createAgent.RequestOptions, + fn: createAgent.AgentCallbackCallback + ): void; + callback( + req: createAgent.ClientRequest, + opts: createAgent.RequestOptions + ): + | createAgent.AgentCallbackReturn + | Promise; + callback( + req: createAgent.ClientRequest, + opts: createAgent.AgentOptions, + fn?: createAgent.AgentCallbackCallback + ): + | createAgent.AgentCallbackReturn + | Promise + | void { + throw new Error( + '"agent-base" has no default implementation, you must subclass and override `callback()`' + ); + } + + /** + * Called by node-core's "_http_client.js" module when creating + * a new HTTP request with this Agent instance. + * + * @api public + */ + addRequest(req: ClientRequest, _opts: RequestOptions): void { + const opts: RequestOptions = { ..._opts }; + + if (typeof opts.secureEndpoint !== 'boolean') { + opts.secureEndpoint = isSecureEndpoint(); + } + + if (opts.host == null) { + opts.host = 'localhost'; + } + + if (opts.port == null) { + opts.port = opts.secureEndpoint ? 443 : 80; + } + + if (opts.protocol == null) { + opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; + } + + if (opts.host && opts.path) { + // If both a `host` and `path` are specified then it's most + // likely the result of a `url.parse()` call... we need to + // remove the `path` portion so that `net.connect()` doesn't + // attempt to open that as a unix socket file. + delete opts.path; + } + + delete opts.agent; + delete opts.hostname; + delete opts._defaultAgent; + delete opts.defaultPort; + delete opts.createConnection; + + // Hint to use "Connection: close" + // XXX: non-documented `http` module API :( + req._last = true; + req.shouldKeepAlive = false; + + let timedOut = false; + let timeoutId: ReturnType | null = null; + const timeoutMs = opts.timeout || this.timeout; + + const onerror = (err: NodeJS.ErrnoException) => { + if (req._hadError) return; + req.emit('error', err); + // For Safety. Some additional errors might fire later on + // and we need to make sure we don't double-fire the error event. + req._hadError = true; + }; + + const ontimeout = () => { + timeoutId = null; + timedOut = true; + const err: NodeJS.ErrnoException = new Error( + `A "socket" was not created for HTTP request before ${timeoutMs}ms` + ); + err.code = 'ETIMEOUT'; + onerror(err); + }; + + const callbackError = (err: NodeJS.ErrnoException) => { + if (timedOut) return; + if (timeoutId !== null) { + clearTimeout(timeoutId); + timeoutId = null; + } + onerror(err); + }; + + const onsocket = (socket: AgentCallbackReturn) => { + if (timedOut) return; + if (timeoutId != null) { + clearTimeout(timeoutId); + timeoutId = null; + } + + if (isAgent(socket)) { + // `socket` is actually an `http.Agent` instance, so + // relinquish responsibility for this `req` to the Agent + // from here on + debug( + 'Callback returned another Agent instance %o', + socket.constructor.name + ); + (socket as createAgent.Agent).addRequest(req, opts); + return; + } + + if (socket) { + socket.once('free', () => { + this.freeSocket(socket as net.Socket, opts); + }); + req.onSocket(socket as net.Socket); + return; + } + + const err = new Error( + `no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\`` + ); + onerror(err); + }; + + if (typeof this.callback !== 'function') { + onerror(new Error('`callback` is not defined')); + return; + } + + if (!this.promisifiedCallback) { + if (this.callback.length >= 3) { + debug('Converting legacy callback function to promise'); + this.promisifiedCallback = promisify(this.callback); + } else { + this.promisifiedCallback = this.callback; + } + } + + if (typeof timeoutMs === 'number' && timeoutMs > 0) { + timeoutId = setTimeout(ontimeout, timeoutMs); + } + + if ('port' in opts && typeof opts.port !== 'number') { + opts.port = Number(opts.port); + } + + try { + debug( + 'Resolving socket for %o request: %o', + opts.protocol, + `${req.method} ${req.path}` + ); + Promise.resolve(this.promisifiedCallback(req, opts)).then( + onsocket, + callbackError + ); + } catch (err) { + Promise.reject(err).catch(callbackError); + } + } + + freeSocket(socket: net.Socket, opts: AgentOptions) { + debug('Freeing socket %o %o', socket.constructor.name, opts); + socket.destroy(); + } + + destroy() { + debug('Destroying agent %o', this.constructor.name); + } + } + + // So that `instanceof` works correctly + createAgent.prototype = createAgent.Agent.prototype; +} + +export = createAgent; diff --git a/node_modules/teeny-request/node_modules/agent-base/src/promisify.ts b/node_modules/teeny-request/node_modules/agent-base/src/promisify.ts new file mode 100644 index 0000000..60cc662 --- /dev/null +++ b/node_modules/teeny-request/node_modules/agent-base/src/promisify.ts @@ -0,0 +1,33 @@ +import { + Agent, + ClientRequest, + RequestOptions, + AgentCallbackCallback, + AgentCallbackPromise, + AgentCallbackReturn +} from './index'; + +type LegacyCallback = ( + req: ClientRequest, + opts: RequestOptions, + fn: AgentCallbackCallback +) => void; + +export default function promisify(fn: LegacyCallback): AgentCallbackPromise { + return function(this: Agent, req: ClientRequest, opts: RequestOptions) { + return new Promise((resolve, reject) => { + fn.call( + this, + req, + opts, + (err: Error | null | undefined, rtn?: AgentCallbackReturn) => { + if (err) { + reject(err); + } else { + resolve(rtn); + } + } + ); + }); + }; +} diff --git a/node_modules/teeny-request/node_modules/https-proxy-agent/README.md b/node_modules/teeny-request/node_modules/https-proxy-agent/README.md new file mode 100644 index 0000000..328656a --- /dev/null +++ b/node_modules/teeny-request/node_modules/https-proxy-agent/README.md @@ -0,0 +1,137 @@ +https-proxy-agent +================ +### An HTTP(s) proxy `http.Agent` implementation for HTTPS +[![Build Status](https://github.com/TooTallNate/node-https-proxy-agent/workflows/Node%20CI/badge.svg)](https://github.com/TooTallNate/node-https-proxy-agent/actions?workflow=Node+CI) + +This module provides an `http.Agent` implementation that connects to a specified +HTTP or HTTPS proxy server, and can be used with the built-in `https` module. + +Specifically, this `Agent` implementation connects to an intermediary "proxy" +server and issues the [CONNECT HTTP method][CONNECT], which tells the proxy to +open a direct TCP connection to the destination server. + +Since this agent implements the CONNECT HTTP method, it also works with other +protocols that use this method when connecting over proxies (i.e. WebSockets). +See the "Examples" section below for more. + + +Installation +------------ + +Install with `npm`: + +``` bash +$ npm install https-proxy-agent +``` + + +Examples +-------- + +#### `https` module example + +``` js +var url = require('url'); +var https = require('https'); +var HttpsProxyAgent = require('https-proxy-agent'); + +// HTTP/HTTPS proxy to connect to +var proxy = process.env.http_proxy || 'http://168.63.76.32:3128'; +console.log('using proxy server %j', proxy); + +// HTTPS endpoint for the proxy to connect to +var endpoint = process.argv[2] || 'https://graph.facebook.com/tootallnate'; +console.log('attempting to GET %j', endpoint); +var options = url.parse(endpoint); + +// create an instance of the `HttpsProxyAgent` class with the proxy server information +var agent = new HttpsProxyAgent(proxy); +options.agent = agent; + +https.get(options, function (res) { + console.log('"response" event!', res.headers); + res.pipe(process.stdout); +}); +``` + +#### `ws` WebSocket connection example + +``` js +var url = require('url'); +var WebSocket = require('ws'); +var HttpsProxyAgent = require('https-proxy-agent'); + +// HTTP/HTTPS proxy to connect to +var proxy = process.env.http_proxy || 'http://168.63.76.32:3128'; +console.log('using proxy server %j', proxy); + +// WebSocket endpoint for the proxy to connect to +var endpoint = process.argv[2] || 'ws://echo.websocket.org'; +var parsed = url.parse(endpoint); +console.log('attempting to connect to WebSocket %j', endpoint); + +// create an instance of the `HttpsProxyAgent` class with the proxy server information +var options = url.parse(proxy); + +var agent = new HttpsProxyAgent(options); + +// finally, initiate the WebSocket connection +var socket = new WebSocket(endpoint, { agent: agent }); + +socket.on('open', function () { + console.log('"open" event!'); + socket.send('hello world'); +}); + +socket.on('message', function (data, flags) { + console.log('"message" event! %j %j', data, flags); + socket.close(); +}); +``` + +API +--- + +### new HttpsProxyAgent(Object options) + +The `HttpsProxyAgent` class implements an `http.Agent` subclass that connects +to the specified "HTTP(s) proxy server" in order to proxy HTTPS and/or WebSocket +requests. This is achieved by using the [HTTP `CONNECT` method][CONNECT]. + +The `options` argument may either be a string URI of the proxy server to use, or an +"options" object with more specific properties: + + * `host` - String - Proxy host to connect to (may use `hostname` as well). Required. + * `port` - Number - Proxy port to connect to. Required. + * `protocol` - String - If `https:`, then use TLS to connect to the proxy. + * `headers` - Object - Additional HTTP headers to be sent on the HTTP CONNECT method. + * Any other options given are passed to the `net.connect()`/`tls.connect()` functions. + + +License +------- + +(The MIT License) + +Copyright (c) 2013 Nathan Rajlich <nathan@tootallnate.net> + +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. + +[CONNECT]: http://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_Tunneling diff --git a/node_modules/teeny-request/node_modules/https-proxy-agent/dist/agent.d.ts b/node_modules/teeny-request/node_modules/https-proxy-agent/dist/agent.d.ts new file mode 100644 index 0000000..4f1c636 --- /dev/null +++ b/node_modules/teeny-request/node_modules/https-proxy-agent/dist/agent.d.ts @@ -0,0 +1,30 @@ +/// +import net from 'net'; +import { Agent, ClientRequest, RequestOptions } from 'agent-base'; +import { HttpsProxyAgentOptions } from '.'; +/** + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. + * + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. + * + * @api public + */ +export default class HttpsProxyAgent extends Agent { + private secureProxy; + private proxy; + constructor(_opts: string | HttpsProxyAgentOptions); + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + * + * @api protected + */ + callback(req: ClientRequest, opts: RequestOptions): Promise; +} diff --git a/node_modules/teeny-request/node_modules/https-proxy-agent/dist/agent.js b/node_modules/teeny-request/node_modules/https-proxy-agent/dist/agent.js new file mode 100644 index 0000000..75d1136 --- /dev/null +++ b/node_modules/teeny-request/node_modules/https-proxy-agent/dist/agent.js @@ -0,0 +1,177 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const net_1 = __importDefault(require("net")); +const tls_1 = __importDefault(require("tls")); +const url_1 = __importDefault(require("url")); +const assert_1 = __importDefault(require("assert")); +const debug_1 = __importDefault(require("debug")); +const agent_base_1 = require("agent-base"); +const parse_proxy_response_1 = __importDefault(require("./parse-proxy-response")); +const debug = debug_1.default('https-proxy-agent:agent'); +/** + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. + * + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. + * + * @api public + */ +class HttpsProxyAgent extends agent_base_1.Agent { + constructor(_opts) { + let opts; + if (typeof _opts === 'string') { + opts = url_1.default.parse(_opts); + } + else { + opts = _opts; + } + if (!opts) { + throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); + } + debug('creating new HttpsProxyAgent instance: %o', opts); + super(opts); + const proxy = Object.assign({}, opts); + // If `true`, then connect to the proxy server over TLS. + // Defaults to `false`. + this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); + // Prefer `hostname` over `host`, and set the `port` if needed. + proxy.host = proxy.hostname || proxy.host; + if (typeof proxy.port === 'string') { + proxy.port = parseInt(proxy.port, 10); + } + if (!proxy.port && proxy.host) { + proxy.port = this.secureProxy ? 443 : 80; + } + // ALPN is supported by Node.js >= v5. + // attempt to negotiate http/1.1 for proxy servers that support http/2 + if (this.secureProxy && !('ALPNProtocols' in proxy)) { + proxy.ALPNProtocols = ['http 1.1']; + } + if (proxy.host && proxy.path) { + // If both a `host` and `path` are specified then it's most likely + // the result of a `url.parse()` call... we need to remove the + // `path` portion so that `net.connect()` doesn't attempt to open + // that as a Unix socket file. + delete proxy.path; + delete proxy.pathname; + } + this.proxy = proxy; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + * + * @api protected + */ + callback(req, opts) { + return __awaiter(this, void 0, void 0, function* () { + const { proxy, secureProxy } = this; + // Create a socket connection to the proxy server. + let socket; + if (secureProxy) { + debug('Creating `tls.Socket`: %o', proxy); + socket = tls_1.default.connect(proxy); + } + else { + debug('Creating `net.Socket`: %o', proxy); + socket = net_1.default.connect(proxy); + } + const headers = Object.assign({}, proxy.headers); + const hostname = `${opts.host}:${opts.port}`; + let payload = `CONNECT ${hostname} HTTP/1.1\r\n`; + // Inject the `Proxy-Authorization` header if necessary. + if (proxy.auth) { + headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`; + } + // The `Host` header should only include the port + // number when it is not the default port. + let { host, port, secureEndpoint } = opts; + if (!isDefaultPort(port, secureEndpoint)) { + host += `:${port}`; + } + headers.Host = host; + headers.Connection = 'close'; + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r\n`; + } + const proxyResponsePromise = parse_proxy_response_1.default(socket); + socket.write(`${payload}\r\n`); + const { statusCode, buffered } = yield proxyResponsePromise; + if (statusCode === 200) { + req.once('socket', resume); + if (opts.secureEndpoint) { + // The proxy is connecting to a TLS server, so upgrade + // this socket connection to a TLS connection. + debug('Upgrading socket connection to TLS'); + const servername = opts.servername || opts.host; + return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, + servername })); + } + return socket; + } + // Some other status code that's not 200... need to re-play the HTTP + // header "data" events onto the socket once the HTTP machinery is + // attached so that the node core `http` can parse and handle the + // error status code. + // Close the original socket, and a new "fake" socket is returned + // instead, so that the proxy doesn't get the HTTP request + // written to it (which may contain `Authorization` headers or other + // sensitive data). + // + // See: https://hackerone.com/reports/541502 + socket.destroy(); + const fakeSocket = new net_1.default.Socket({ writable: false }); + fakeSocket.readable = true; + // Need to wait for the "socket" event to re-play the "data" events. + req.once('socket', (s) => { + debug('replaying proxy buffer for failed request'); + assert_1.default(s.listenerCount('data') > 0); + // Replay the "buffered" Buffer onto the fake `socket`, since at + // this point the HTTP module machinery has been hooked up for + // the user. + s.push(buffered); + s.push(null); + }); + return fakeSocket; + }); + } +} +exports.default = HttpsProxyAgent; +function resume(socket) { + socket.resume(); +} +function isDefaultPort(port, secure) { + return Boolean((!secure && port === 80) || (secure && port === 443)); +} +function isHTTPS(protocol) { + return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; +} +function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; +} +//# sourceMappingURL=agent.js.map \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/https-proxy-agent/dist/agent.js.map b/node_modules/teeny-request/node_modules/https-proxy-agent/dist/agent.js.map new file mode 100644 index 0000000..0af6c17 --- /dev/null +++ b/node_modules/teeny-request/node_modules/https-proxy-agent/dist/agent.js.map @@ -0,0 +1 @@ +{"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,8CAAsB;AACtB,8CAAsB;AACtB,8CAAsB;AACtB,oDAA4B;AAC5B,kDAAgC;AAEhC,2CAAkE;AAElE,kFAAwD;AAExD,MAAM,KAAK,GAAG,eAAW,CAAC,yBAAyB,CAAC,CAAC;AAErD;;;;;;;;;;;;;GAaG;AACH,MAAqB,eAAgB,SAAQ,kBAAK;IAIjD,YAAY,KAAsC;QACjD,IAAI,IAA4B,CAAC;QACjC,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;YAC9B,IAAI,GAAG,aAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;SACxB;aAAM;YACN,IAAI,GAAG,KAAK,CAAC;SACb;QACD,IAAI,CAAC,IAAI,EAAE;YACV,MAAM,IAAI,KAAK,CACd,8DAA8D,CAC9D,CAAC;SACF;QACD,KAAK,CAAC,2CAA2C,EAAE,IAAI,CAAC,CAAC;QACzD,KAAK,CAAC,IAAI,CAAC,CAAC;QAEZ,MAAM,KAAK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D,MAAM,CAAC,MAAM,EAAE,CAAC;AACjB,CAAC;AAED,SAAS,aAAa,CAAC,IAAY,EAAE,MAAe;IACnD,OAAO,OAAO,CAAC,CAAC,CAAC,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC,IAAI,CAAC,MAAM,IAAI,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC;AACtE,CAAC;AAED,SAAS,OAAO,CAAC,QAAwB;IACxC,OAAO,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;AAC3E,CAAC;AAED,SAAS,IAAI,CACZ,GAAM,EACN,GAAG,IAAO;IAIV,MAAM,GAAG,GAAG,EAEX,CAAC;IACF,IAAI,GAAqB,CAAC;IAC1B,KAAK,GAAG,IAAI,GAAG,EAAE;QAChB,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;YACxB,GAAG,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;SACpB;KACD;IACD,OAAO,GAAG,CAAC;AACZ,CAAC"} \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/https-proxy-agent/dist/index.d.ts b/node_modules/teeny-request/node_modules/https-proxy-agent/dist/index.d.ts new file mode 100644 index 0000000..0d60062 --- /dev/null +++ b/node_modules/teeny-request/node_modules/https-proxy-agent/dist/index.d.ts @@ -0,0 +1,23 @@ +/// +import net from 'net'; +import tls from 'tls'; +import { Url } from 'url'; +import { AgentOptions } from 'agent-base'; +import { OutgoingHttpHeaders } from 'http'; +import _HttpsProxyAgent from './agent'; +declare function createHttpsProxyAgent(opts: string | createHttpsProxyAgent.HttpsProxyAgentOptions): _HttpsProxyAgent; +declare namespace createHttpsProxyAgent { + interface BaseHttpsProxyAgentOptions { + headers?: OutgoingHttpHeaders; + secureProxy?: boolean; + host?: string | null; + path?: string | null; + port?: string | number | null; + } + export interface HttpsProxyAgentOptions extends AgentOptions, BaseHttpsProxyAgentOptions, Partial> { + } + export type HttpsProxyAgent = _HttpsProxyAgent; + export const HttpsProxyAgent: typeof _HttpsProxyAgent; + export {}; +} +export = createHttpsProxyAgent; diff --git a/node_modules/teeny-request/node_modules/https-proxy-agent/dist/index.js b/node_modules/teeny-request/node_modules/https-proxy-agent/dist/index.js new file mode 100644 index 0000000..b03e763 --- /dev/null +++ b/node_modules/teeny-request/node_modules/https-proxy-agent/dist/index.js @@ -0,0 +1,14 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const agent_1 = __importDefault(require("./agent")); +function createHttpsProxyAgent(opts) { + return new agent_1.default(opts); +} +(function (createHttpsProxyAgent) { + createHttpsProxyAgent.HttpsProxyAgent = agent_1.default; + createHttpsProxyAgent.prototype = agent_1.default.prototype; +})(createHttpsProxyAgent || (createHttpsProxyAgent = {})); +module.exports = createHttpsProxyAgent; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/https-proxy-agent/dist/index.js.map b/node_modules/teeny-request/node_modules/https-proxy-agent/dist/index.js.map new file mode 100644 index 0000000..f3ce559 --- /dev/null +++ b/node_modules/teeny-request/node_modules/https-proxy-agent/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;AAKA,oDAAuC;AAEvC,SAAS,qBAAqB,CAC7B,IAA2D;IAE3D,OAAO,IAAI,eAAgB,CAAC,IAAI,CAAC,CAAC;AACnC,CAAC;AAED,WAAU,qBAAqB;IAoBjB,qCAAe,GAAG,eAAgB,CAAC;IAEhD,qBAAqB,CAAC,SAAS,GAAG,eAAgB,CAAC,SAAS,CAAC;AAC9D,CAAC,EAvBS,qBAAqB,KAArB,qBAAqB,QAuB9B;AAED,iBAAS,qBAAqB,CAAC"} \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts b/node_modules/teeny-request/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts new file mode 100644 index 0000000..7565674 --- /dev/null +++ b/node_modules/teeny-request/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts @@ -0,0 +1,7 @@ +/// +import { Readable } from 'stream'; +export interface ProxyResponse { + statusCode: number; + buffered: Buffer; +} +export default function parseProxyResponse(socket: Readable): Promise; diff --git a/node_modules/teeny-request/node_modules/https-proxy-agent/dist/parse-proxy-response.js b/node_modules/teeny-request/node_modules/https-proxy-agent/dist/parse-proxy-response.js new file mode 100644 index 0000000..aa5ce3c --- /dev/null +++ b/node_modules/teeny-request/node_modules/https-proxy-agent/dist/parse-proxy-response.js @@ -0,0 +1,66 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const debug_1 = __importDefault(require("debug")); +const debug = debug_1.default('https-proxy-agent:parse-proxy-response'); +function parseProxyResponse(socket) { + return new Promise((resolve, reject) => { + // we need to buffer any HTTP traffic that happens with the proxy before we get + // the CONNECT response, so that if the response is anything other than an "200" + // response code, then we can re-play the "data" events on the socket once the + // HTTP parser is hooked up... + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once('readable', read); + } + function cleanup() { + socket.removeListener('end', onend); + socket.removeListener('error', onerror); + socket.removeListener('close', onclose); + socket.removeListener('readable', read); + } + function onclose(err) { + debug('onclose had error %o', err); + } + function onend() { + debug('onend'); + } + function onerror(err) { + cleanup(); + debug('onerror %o', err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf('\r\n\r\n'); + if (endOfHeaders === -1) { + // keep buffering + debug('have not received end of HTTP headers yet...'); + read(); + return; + } + const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n')); + const statusCode = +firstLine.split(' ')[1]; + debug('got proxy server response: %o', firstLine); + resolve({ + statusCode, + buffered + }); + } + socket.on('error', onerror); + socket.on('close', onclose); + socket.on('end', onend); + read(); + }); +} +exports.default = parseProxyResponse; +//# sourceMappingURL=parse-proxy-response.js.map \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/https-proxy-agent/dist/parse-proxy-response.js.map b/node_modules/teeny-request/node_modules/https-proxy-agent/dist/parse-proxy-response.js.map new file mode 100644 index 0000000..bacdb84 --- /dev/null +++ b/node_modules/teeny-request/node_modules/https-proxy-agent/dist/parse-proxy-response.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parse-proxy-response.js","sourceRoot":"","sources":["../src/parse-proxy-response.ts"],"names":[],"mappings":";;;;;AAAA,kDAAgC;AAGhC,MAAM,KAAK,GAAG,eAAW,CAAC,wCAAwC,CAAC,CAAC;AAOpE,SAAwB,kBAAkB,CACzC,MAAgB;IAEhB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACtC,+EAA+E;QAC/E,gFAAgF;QAChF,8EAA8E;QAC9E,8BAA8B;QAC9B,IAAI,aAAa,GAAG,CAAC,CAAC;QACtB,MAAM,OAAO,GAAa,EAAE,CAAC;QAE7B,SAAS,IAAI;YACZ,MAAM,CAAC,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC;YACxB,IAAI,CAAC;gBAAE,MAAM,CAAC,CAAC,CAAC,CAAC;;gBACZ,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;QACpC,CAAC;QAED,SAAS,OAAO;YACf,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;YACpC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACxC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACxC,MAAM,CAAC,cAAc,CAAC,UAAU,EAAE,IAAI,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KAAK,CAAC,CAAC;QAExB,IAAI,EAAE,CAAC;IACR,CAAC,CAAC,CAAC;AACJ,CAAC;AAvED,qCAuEC"} \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/https-proxy-agent/package.json b/node_modules/teeny-request/node_modules/https-proxy-agent/package.json new file mode 100644 index 0000000..fb2aba1 --- /dev/null +++ b/node_modules/teeny-request/node_modules/https-proxy-agent/package.json @@ -0,0 +1,56 @@ +{ + "name": "https-proxy-agent", + "version": "5.0.1", + "description": "An HTTP(s) proxy `http.Agent` implementation for HTTPS", + "main": "dist/index", + "types": "dist/index", + "files": [ + "dist" + ], + "scripts": { + "prebuild": "rimraf dist", + "build": "tsc", + "test": "mocha --reporter spec", + "test-lint": "eslint src --ext .js,.ts", + "prepublishOnly": "npm run build" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/node-https-proxy-agent.git" + }, + "keywords": [ + "https", + "proxy", + "endpoint", + "agent" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/node-https-proxy-agent/issues" + }, + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "devDependencies": { + "@types/debug": "4", + "@types/node": "^12.12.11", + "@typescript-eslint/eslint-plugin": "1.6.0", + "@typescript-eslint/parser": "1.1.0", + "eslint": "5.16.0", + "eslint-config-airbnb": "17.1.0", + "eslint-config-prettier": "4.1.0", + "eslint-import-resolver-typescript": "1.1.1", + "eslint-plugin-import": "2.16.0", + "eslint-plugin-jsx-a11y": "6.2.1", + "eslint-plugin-react": "7.12.4", + "mocha": "^6.2.2", + "proxy": "1", + "rimraf": "^3.0.0", + "typescript": "^3.5.3" + }, + "engines": { + "node": ">= 6" + } +} diff --git a/node_modules/teeny-request/node_modules/uuid/CHANGELOG.md b/node_modules/teeny-request/node_modules/uuid/CHANGELOG.md new file mode 100644 index 0000000..0412ad8 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/CHANGELOG.md @@ -0,0 +1,274 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## [9.0.1](https://github.com/uuidjs/uuid/compare/v9.0.0...v9.0.1) (2023-09-12) + +### build + +- Fix CI to work with Node.js 20.x + +## [9.0.0](https://github.com/uuidjs/uuid/compare/v8.3.2...v9.0.0) (2022-09-05) + +### ⚠ BREAKING CHANGES + +- Drop Node.js 10.x support. This library always aims at supporting one EOLed LTS release which by this time now is 12.x which has reached EOL 30 Apr 2022. + +- Remove the minified UMD build from the package. + + Minified code is hard to audit and since this is a widely used library it seems more appropriate nowadays to optimize for auditability than to ship a legacy module format that, at best, serves educational purposes nowadays. + + For production browser use cases, users should be using a bundler. For educational purposes, today's online sandboxes like replit.com offer convenient ways to load npm modules, so the use case for UMD through repos like UNPKG or jsDelivr has largely vanished. + +- Drop IE 11 and Safari 10 support. Drop support for browsers that don't correctly implement const/let and default arguments, and no longer transpile the browser build to ES2015. + + This also removes the fallback on msCrypto instead of the crypto API. + + Browser tests are run in the first supported version of each supported browser and in the latest (as of this commit) version available on Browserstack. + +### Features + +- optimize uuid.v1 by 1.3x uuid.v4 by 4.3x (430%) ([#597](https://github.com/uuidjs/uuid/issues/597)) ([3a033f6](https://github.com/uuidjs/uuid/commit/3a033f6bab6bb3780ece6d645b902548043280bc)) +- remove UMD build ([#645](https://github.com/uuidjs/uuid/issues/645)) ([e948a0f](https://github.com/uuidjs/uuid/commit/e948a0f22bf22f4619b27bd913885e478e20fe6f)), closes [#620](https://github.com/uuidjs/uuid/issues/620) +- use native crypto.randomUUID when available ([#600](https://github.com/uuidjs/uuid/issues/600)) ([c9e076c](https://github.com/uuidjs/uuid/commit/c9e076c852edad7e9a06baaa1d148cf4eda6c6c4)) + +### Bug Fixes + +- add Jest/jsdom compatibility ([#642](https://github.com/uuidjs/uuid/issues/642)) ([16f9c46](https://github.com/uuidjs/uuid/commit/16f9c469edf46f0786164cdf4dc980743984a6fd)) +- change default export to named function ([#545](https://github.com/uuidjs/uuid/issues/545)) ([c57bc5a](https://github.com/uuidjs/uuid/commit/c57bc5a9a0653273aa639cda9177ce52efabe42a)) +- handle error when parameter is not set in v3 and v5 ([#622](https://github.com/uuidjs/uuid/issues/622)) ([fcd7388](https://github.com/uuidjs/uuid/commit/fcd73881692d9fabb63872576ba28e30ff852091)) +- run npm audit fix ([#644](https://github.com/uuidjs/uuid/issues/644)) ([04686f5](https://github.com/uuidjs/uuid/commit/04686f54c5fed2cfffc1b619f4970c4bb8532353)) +- upgrading from uuid3 broken link ([#568](https://github.com/uuidjs/uuid/issues/568)) ([1c849da](https://github.com/uuidjs/uuid/commit/1c849da6e164259e72e18636726345b13a7eddd6)) + +### build + +- drop Node.js 8.x from babel transpile target ([#603](https://github.com/uuidjs/uuid/issues/603)) ([aa11485](https://github.com/uuidjs/uuid/commit/aa114858260402107ec8a1e1a825dea0a259bcb5)) +- drop support for legacy browsers (IE11, Safari 10) ([#604](https://github.com/uuidjs/uuid/issues/604)) ([0f433e5](https://github.com/uuidjs/uuid/commit/0f433e5ec444edacd53016de67db021102f36148)) + +- drop node 10.x to upgrade dev dependencies ([#653](https://github.com/uuidjs/uuid/issues/653)) ([28a5712](https://github.com/uuidjs/uuid/commit/28a571283f8abda6b9d85e689f95b7d3ee9e282e)), closes [#643](https://github.com/uuidjs/uuid/issues/643) + +### [8.3.2](https://github.com/uuidjs/uuid/compare/v8.3.1...v8.3.2) (2020-12-08) + +### Bug Fixes + +- lazy load getRandomValues ([#537](https://github.com/uuidjs/uuid/issues/537)) ([16c8f6d](https://github.com/uuidjs/uuid/commit/16c8f6df2f6b09b4d6235602d6a591188320a82e)), closes [#536](https://github.com/uuidjs/uuid/issues/536) + +### [8.3.1](https://github.com/uuidjs/uuid/compare/v8.3.0...v8.3.1) (2020-10-04) + +### Bug Fixes + +- support expo>=39.0.0 ([#515](https://github.com/uuidjs/uuid/issues/515)) ([c65a0f3](https://github.com/uuidjs/uuid/commit/c65a0f3fa73b901959d638d1e3591dfacdbed867)), closes [#375](https://github.com/uuidjs/uuid/issues/375) + +## [8.3.0](https://github.com/uuidjs/uuid/compare/v8.2.0...v8.3.0) (2020-07-27) + +### Features + +- add parse/stringify/validate/version/NIL APIs ([#479](https://github.com/uuidjs/uuid/issues/479)) ([0e6c10b](https://github.com/uuidjs/uuid/commit/0e6c10ba1bf9517796ff23c052fc0468eedfd5f4)), closes [#475](https://github.com/uuidjs/uuid/issues/475) [#478](https://github.com/uuidjs/uuid/issues/478) [#480](https://github.com/uuidjs/uuid/issues/480) [#481](https://github.com/uuidjs/uuid/issues/481) [#180](https://github.com/uuidjs/uuid/issues/180) + +## [8.2.0](https://github.com/uuidjs/uuid/compare/v8.1.0...v8.2.0) (2020-06-23) + +### Features + +- improve performance of v1 string representation ([#453](https://github.com/uuidjs/uuid/issues/453)) ([0ee0b67](https://github.com/uuidjs/uuid/commit/0ee0b67c37846529c66089880414d29f3ae132d5)) +- remove deprecated v4 string parameter ([#454](https://github.com/uuidjs/uuid/issues/454)) ([88ce3ca](https://github.com/uuidjs/uuid/commit/88ce3ca0ba046f60856de62c7ce03f7ba98ba46c)), closes [#437](https://github.com/uuidjs/uuid/issues/437) +- support jspm ([#473](https://github.com/uuidjs/uuid/issues/473)) ([e9f2587](https://github.com/uuidjs/uuid/commit/e9f2587a92575cac31bc1d4ae944e17c09756659)) + +### Bug Fixes + +- prepare package exports for webpack 5 ([#468](https://github.com/uuidjs/uuid/issues/468)) ([8d6e6a5](https://github.com/uuidjs/uuid/commit/8d6e6a5f8965ca9575eb4d92e99a43435f4a58a8)) + +## [8.1.0](https://github.com/uuidjs/uuid/compare/v8.0.0...v8.1.0) (2020-05-20) + +### Features + +- improve v4 performance by reusing random number array ([#435](https://github.com/uuidjs/uuid/issues/435)) ([bf4af0d](https://github.com/uuidjs/uuid/commit/bf4af0d711b4d2ed03d1f74fd12ad0baa87dc79d)) +- optimize V8 performance of bytesToUuid ([#434](https://github.com/uuidjs/uuid/issues/434)) ([e156415](https://github.com/uuidjs/uuid/commit/e156415448ec1af2351fa0b6660cfb22581971f2)) + +### Bug Fixes + +- export package.json required by react-native and bundlers ([#449](https://github.com/uuidjs/uuid/issues/449)) ([be1c8fe](https://github.com/uuidjs/uuid/commit/be1c8fe9a3206c358e0059b52fafd7213aa48a52)), closes [ai/nanoevents#44](https://github.com/ai/nanoevents/issues/44#issuecomment-602010343) [#444](https://github.com/uuidjs/uuid/issues/444) + +## [8.0.0](https://github.com/uuidjs/uuid/compare/v7.0.3...v8.0.0) (2020-04-29) + +### ⚠ BREAKING CHANGES + +- For native ECMAScript Module (ESM) usage in Node.js only named exports are exposed, there is no more default export. + + ```diff + -import uuid from 'uuid'; + -console.log(uuid.v4()); // -> 'cd6c3b08-0adc-4f4b-a6ef-36087a1c9869' + +import { v4 as uuidv4 } from 'uuid'; + +uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' + ``` + +- Deep requiring specific algorithms of this library like `require('uuid/v4')`, which has been deprecated in `uuid@7`, is no longer supported. + + Instead use the named exports that this module exports. + + For ECMAScript Modules (ESM): + + ```diff + -import uuidv4 from 'uuid/v4'; + +import { v4 as uuidv4 } from 'uuid'; + uuidv4(); + ``` + + For CommonJS: + + ```diff + -const uuidv4 = require('uuid/v4'); + +const { v4: uuidv4 } = require('uuid'); + uuidv4(); + ``` + +### Features + +- native Node.js ES Modules (wrapper approach) ([#423](https://github.com/uuidjs/uuid/issues/423)) ([2d9f590](https://github.com/uuidjs/uuid/commit/2d9f590ad9701d692625c07ed62f0a0f91227991)), closes [#245](https://github.com/uuidjs/uuid/issues/245) [#419](https://github.com/uuidjs/uuid/issues/419) [#342](https://github.com/uuidjs/uuid/issues/342) +- remove deep requires ([#426](https://github.com/uuidjs/uuid/issues/426)) ([daf72b8](https://github.com/uuidjs/uuid/commit/daf72b84ceb20272a81bb5fbddb05dd95922cbba)) + +### Bug Fixes + +- add CommonJS syntax example to README quickstart section ([#417](https://github.com/uuidjs/uuid/issues/417)) ([e0ec840](https://github.com/uuidjs/uuid/commit/e0ec8402c7ad44b7ef0453036c612f5db513fda0)) + +### [7.0.3](https://github.com/uuidjs/uuid/compare/v7.0.2...v7.0.3) (2020-03-31) + +### Bug Fixes + +- make deep require deprecation warning work in browsers ([#409](https://github.com/uuidjs/uuid/issues/409)) ([4b71107](https://github.com/uuidjs/uuid/commit/4b71107d8c0d2ef56861ede6403fc9dc35a1e6bf)), closes [#408](https://github.com/uuidjs/uuid/issues/408) + +### [7.0.2](https://github.com/uuidjs/uuid/compare/v7.0.1...v7.0.2) (2020-03-04) + +### Bug Fixes + +- make access to msCrypto consistent ([#393](https://github.com/uuidjs/uuid/issues/393)) ([8bf2a20](https://github.com/uuidjs/uuid/commit/8bf2a20f3565df743da7215eebdbada9d2df118c)) +- simplify link in deprecation warning ([#391](https://github.com/uuidjs/uuid/issues/391)) ([bb2c8e4](https://github.com/uuidjs/uuid/commit/bb2c8e4e9f4c5f9c1eaaf3ea59710c633cd90cb7)) +- update links to match content in readme ([#386](https://github.com/uuidjs/uuid/issues/386)) ([44f2f86](https://github.com/uuidjs/uuid/commit/44f2f86e9d2bbf14ee5f0f00f72a3db1292666d4)) + +### [7.0.1](https://github.com/uuidjs/uuid/compare/v7.0.0...v7.0.1) (2020-02-25) + +### Bug Fixes + +- clean up esm builds for node and browser ([#383](https://github.com/uuidjs/uuid/issues/383)) ([59e6a49](https://github.com/uuidjs/uuid/commit/59e6a49e7ce7b3e8fb0f3ee52b9daae72af467dc)) +- provide browser versions independent from module system ([#380](https://github.com/uuidjs/uuid/issues/380)) ([4344a22](https://github.com/uuidjs/uuid/commit/4344a22e7aed33be8627eeaaf05360f256a21753)), closes [#378](https://github.com/uuidjs/uuid/issues/378) + +## [7.0.0](https://github.com/uuidjs/uuid/compare/v3.4.0...v7.0.0) (2020-02-24) + +### ⚠ BREAKING CHANGES + +- The default export, which used to be the v4() method but which was already discouraged in v3.x of this library, has been removed. +- Explicitly note that deep imports of the different uuid version functions are deprecated and no longer encouraged and that ECMAScript module named imports should be used instead. Emit a deprecation warning for people who deep-require the different algorithm variants. +- Remove builtin support for insecure random number generators in the browser. Users who want that will have to supply their own random number generator function. +- Remove support for generating v3 and v5 UUIDs in Node.js<4.x +- Convert code base to ECMAScript Modules (ESM) and release CommonJS build for node and ESM build for browser bundlers. + +### Features + +- add UMD build to npm package ([#357](https://github.com/uuidjs/uuid/issues/357)) ([4e75adf](https://github.com/uuidjs/uuid/commit/4e75adf435196f28e3fbbe0185d654b5ded7ca2c)), closes [#345](https://github.com/uuidjs/uuid/issues/345) +- add various es module and CommonJS examples ([b238510](https://github.com/uuidjs/uuid/commit/b238510bf352463521f74bab175a3af9b7a42555)) +- ensure that docs are up-to-date in CI ([ee5e77d](https://github.com/uuidjs/uuid/commit/ee5e77db547474f5a8f23d6c857a6d399209986b)) +- hybrid CommonJS & ECMAScript modules build ([a3f078f](https://github.com/uuidjs/uuid/commit/a3f078faa0baff69ab41aed08e041f8f9c8993d0)) +- remove insecure fallback random number generator ([3a5842b](https://github.com/uuidjs/uuid/commit/3a5842b141a6e5de0ae338f391661e6b84b167c9)), closes [#173](https://github.com/uuidjs/uuid/issues/173) +- remove support for pre Node.js v4 Buffer API ([#356](https://github.com/uuidjs/uuid/issues/356)) ([b59b5c5](https://github.com/uuidjs/uuid/commit/b59b5c5ecad271c5453f1a156f011671f6d35627)) +- rename repository to github:uuidjs/uuid ([#351](https://github.com/uuidjs/uuid/issues/351)) ([c37a518](https://github.com/uuidjs/uuid/commit/c37a518e367ac4b6d0aa62dba1bc6ce9e85020f7)), closes [#338](https://github.com/uuidjs/uuid/issues/338) + +### Bug Fixes + +- add deep-require proxies for local testing and adjust tests ([#365](https://github.com/uuidjs/uuid/issues/365)) ([7fedc79](https://github.com/uuidjs/uuid/commit/7fedc79ac8fda4bfd1c566c7f05ef4ac13b2db48)) +- add note about removal of default export ([#372](https://github.com/uuidjs/uuid/issues/372)) ([12749b7](https://github.com/uuidjs/uuid/commit/12749b700eb49db8a9759fd306d8be05dbfbd58c)), closes [#370](https://github.com/uuidjs/uuid/issues/370) +- deprecated deep requiring of the different algorithm versions ([#361](https://github.com/uuidjs/uuid/issues/361)) ([c0bdf15](https://github.com/uuidjs/uuid/commit/c0bdf15e417639b1aeb0b247b2fb11f7a0a26b23)) + +## [3.4.0](https://github.com/uuidjs/uuid/compare/v3.3.3...v3.4.0) (2020-01-16) + +### Features + +- rename repository to github:uuidjs/uuid ([#351](https://github.com/uuidjs/uuid/issues/351)) ([e2d7314](https://github.com/uuidjs/uuid/commit/e2d7314)), closes [#338](https://github.com/uuidjs/uuid/issues/338) + +## [3.3.3](https://github.com/uuidjs/uuid/compare/v3.3.2...v3.3.3) (2019-08-19) + +### Bug Fixes + +- no longer run ci tests on node v4 +- upgrade dependencies + +## [3.3.2](https://github.com/uuidjs/uuid/compare/v3.3.1...v3.3.2) (2018-06-28) + +### Bug Fixes + +- typo ([305d877](https://github.com/uuidjs/uuid/commit/305d877)) + +## [3.3.1](https://github.com/uuidjs/uuid/compare/v3.3.0...v3.3.1) (2018-06-28) + +### Bug Fixes + +- fix [#284](https://github.com/uuidjs/uuid/issues/284) by setting function name in try-catch ([f2a60f2](https://github.com/uuidjs/uuid/commit/f2a60f2)) + +# [3.3.0](https://github.com/uuidjs/uuid/compare/v3.2.1...v3.3.0) (2018-06-22) + +### Bug Fixes + +- assignment to readonly property to allow running in strict mode ([#270](https://github.com/uuidjs/uuid/issues/270)) ([d062fdc](https://github.com/uuidjs/uuid/commit/d062fdc)) +- fix [#229](https://github.com/uuidjs/uuid/issues/229) ([c9684d4](https://github.com/uuidjs/uuid/commit/c9684d4)) +- Get correct version of IE11 crypto ([#274](https://github.com/uuidjs/uuid/issues/274)) ([153d331](https://github.com/uuidjs/uuid/commit/153d331)) +- mem issue when generating uuid ([#267](https://github.com/uuidjs/uuid/issues/267)) ([c47702c](https://github.com/uuidjs/uuid/commit/c47702c)) + +### Features + +- enforce Conventional Commit style commit messages ([#282](https://github.com/uuidjs/uuid/issues/282)) ([cc9a182](https://github.com/uuidjs/uuid/commit/cc9a182)) + +## [3.2.1](https://github.com/uuidjs/uuid/compare/v3.2.0...v3.2.1) (2018-01-16) + +### Bug Fixes + +- use msCrypto if available. Fixes [#241](https://github.com/uuidjs/uuid/issues/241) ([#247](https://github.com/uuidjs/uuid/issues/247)) ([1fef18b](https://github.com/uuidjs/uuid/commit/1fef18b)) + +# [3.2.0](https://github.com/uuidjs/uuid/compare/v3.1.0...v3.2.0) (2018-01-16) + +### Bug Fixes + +- remove mistakenly added typescript dependency, rollback version (standard-version will auto-increment) ([09fa824](https://github.com/uuidjs/uuid/commit/09fa824)) +- use msCrypto if available. Fixes [#241](https://github.com/uuidjs/uuid/issues/241) ([#247](https://github.com/uuidjs/uuid/issues/247)) ([1fef18b](https://github.com/uuidjs/uuid/commit/1fef18b)) + +### Features + +- Add v3 Support ([#217](https://github.com/uuidjs/uuid/issues/217)) ([d94f726](https://github.com/uuidjs/uuid/commit/d94f726)) + +# [3.1.0](https://github.com/uuidjs/uuid/compare/v3.1.0...v3.0.1) (2017-06-17) + +### Bug Fixes + +- (fix) Add .npmignore file to exclude test/ and other non-essential files from packing. (#183) +- Fix typo (#178) +- Simple typo fix (#165) + +### Features + +- v5 support in CLI (#197) +- V5 support (#188) + +# 3.0.1 (2016-11-28) + +- split uuid versions into separate files + +# 3.0.0 (2016-11-17) + +- remove .parse and .unparse + +# 2.0.0 + +- Removed uuid.BufferClass + +# 1.4.0 + +- Improved module context detection +- Removed public RNG functions + +# 1.3.2 + +- Improve tests and handling of v1() options (Issue #24) +- Expose RNG option to allow for perf testing with different generators + +# 1.3.0 + +- Support for version 1 ids, thanks to [@ctavan](https://github.com/ctavan)! +- Support for node.js crypto API +- De-emphasizing performance in favor of a) cryptographic quality PRNGs where available and b) more manageable code diff --git a/node_modules/teeny-request/node_modules/uuid/CONTRIBUTING.md b/node_modules/teeny-request/node_modules/uuid/CONTRIBUTING.md new file mode 100644 index 0000000..4a4503d --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/CONTRIBUTING.md @@ -0,0 +1,18 @@ +# Contributing + +Please feel free to file GitHub Issues or propose Pull Requests. We're always happy to discuss improvements to this library! + +## Testing + +```shell +npm test +``` + +## Releasing + +Releases are supposed to be done from master, version bumping is automated through [`standard-version`](https://github.com/conventional-changelog/standard-version): + +```shell +npm run release -- --dry-run # verify output manually +npm run release # follow the instructions from the output of this command +``` diff --git a/node_modules/teeny-request/node_modules/uuid/LICENSE.md b/node_modules/teeny-request/node_modules/uuid/LICENSE.md new file mode 100644 index 0000000..3934168 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/LICENSE.md @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2010-2020 Robert Kieffer and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/teeny-request/node_modules/uuid/README.md b/node_modules/teeny-request/node_modules/uuid/README.md new file mode 100644 index 0000000..4f51e09 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/README.md @@ -0,0 +1,466 @@ + + + +# uuid [![CI](https://github.com/uuidjs/uuid/workflows/CI/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ACI) [![Browser](https://github.com/uuidjs/uuid/workflows/Browser/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ABrowser) + +For the creation of [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) UUIDs + +- **Complete** - Support for RFC4122 version 1, 3, 4, and 5 UUIDs +- **Cross-platform** - Support for ... + - CommonJS, [ECMAScript Modules](#ecmascript-modules) and [CDN builds](#cdn-builds) + - NodeJS 12+ ([LTS releases](https://github.com/nodejs/Release)) + - Chrome, Safari, Firefox, Edge browsers + - Webpack and rollup.js module bundlers + - [React Native / Expo](#react-native--expo) +- **Secure** - Cryptographically-strong random values +- **Small** - Zero-dependency, small footprint, plays nice with "tree shaking" packagers +- **CLI** - Includes the [`uuid` command line](#command-line) utility + +> **Note** Upgrading from `uuid@3`? Your code is probably okay, but check out [Upgrading From `uuid@3`](#upgrading-from-uuid3) for details. + +> **Note** Only interested in creating a version 4 UUID? You might be able to use [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID), eliminating the need to install this library. + +## Quickstart + +To create a random UUID... + +**1. Install** + +```shell +npm install uuid +``` + +**2. Create a UUID** (ES6 module syntax) + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' +``` + +... or using CommonJS syntax: + +```javascript +const { v4: uuidv4 } = require('uuid'); +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +For timestamp UUIDs, namespace UUIDs, and other options read on ... + +## API Summary + +| | | | +| --- | --- | --- | +| [`uuid.NIL`](#uuidnil) | The nil UUID string (all zeros) | New in `uuid@8.3` | +| [`uuid.parse()`](#uuidparsestr) | Convert UUID string to array of bytes | New in `uuid@8.3` | +| [`uuid.stringify()`](#uuidstringifyarr-offset) | Convert array of bytes to UUID string | New in `uuid@8.3` | +| [`uuid.v1()`](#uuidv1options-buffer-offset) | Create a version 1 (timestamp) UUID | | +| [`uuid.v3()`](#uuidv3name-namespace-buffer-offset) | Create a version 3 (namespace w/ MD5) UUID | | +| [`uuid.v4()`](#uuidv4options-buffer-offset) | Create a version 4 (random) UUID | | +| [`uuid.v5()`](#uuidv5name-namespace-buffer-offset) | Create a version 5 (namespace w/ SHA-1) UUID | | +| [`uuid.validate()`](#uuidvalidatestr) | Test a string to see if it is a valid UUID | New in `uuid@8.3` | +| [`uuid.version()`](#uuidversionstr) | Detect RFC version of a UUID | New in `uuid@8.3` | + +## API + +### uuid.NIL + +The nil UUID string (all zeros). + +Example: + +```javascript +import { NIL as NIL_UUID } from 'uuid'; + +NIL_UUID; // ⇨ '00000000-0000-0000-0000-000000000000' +``` + +### uuid.parse(str) + +Convert UUID string to array of bytes + +| | | +| --------- | ---------------------------------------- | +| `str` | A valid UUID `String` | +| _returns_ | `Uint8Array[16]` | +| _throws_ | `TypeError` if `str` is not a valid UUID | + +Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left ↠ right order of hex-pairs in UUID strings. As shown in the example below. + +Example: + +```javascript +import { parse as uuidParse } from 'uuid'; + +// Parse a UUID +const bytes = uuidParse('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); + +// Convert to hex strings to show byte order (for documentation purposes) +[...bytes].map((v) => v.toString(16).padStart(2, '0')); // ⇨ + // [ + // '6e', 'c0', 'bd', '7f', + // '11', 'c0', '43', 'da', + // '97', '5e', '2a', '8a', + // 'd9', 'eb', 'ae', '0b' + // ] +``` + +### uuid.stringify(arr[, offset]) + +Convert array of bytes to UUID string + +| | | +| -------------- | ---------------------------------------------------------------------------- | +| `arr` | `Array`-like collection of 16 values (starting from `offset`) between 0-255. | +| [`offset` = 0] | `Number` Starting index in the Array | +| _returns_ | `String` | +| _throws_ | `TypeError` if a valid UUID string cannot be generated | + +Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left ↠ right order of hex-pairs in UUID strings. As shown in the example below. + +Example: + +```javascript +import { stringify as uuidStringify } from 'uuid'; + +const uuidBytes = [ + 0x6e, 0xc0, 0xbd, 0x7f, 0x11, 0xc0, 0x43, 0xda, 0x97, 0x5e, 0x2a, 0x8a, 0xd9, 0xeb, 0xae, 0x0b, +]; + +uuidStringify(uuidBytes); // ⇨ '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b' +``` + +### uuid.v1([options[, buffer[, offset]]]) + +Create an RFC version 1 (timestamp) UUID + +| | | +| --- | --- | +| [`options`] | `Object` with one or more of the following properties: | +| [`options.node` ] | RFC "node" field as an `Array[6]` of byte values (per 4.1.6) | +| [`options.clockseq`] | RFC "clock sequence" as a `Number` between 0 - 0x3fff | +| [`options.msecs`] | RFC "timestamp" field (`Number` of milliseconds, unix epoch) | +| [`options.nsecs`] | RFC "timestamp" field (`Number` of nanoseconds to add to `msecs`, should be 0-10,000) | +| [`options.random`] | `Array` of 16 random bytes (0-255) | +| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | +| _throws_ | `Error` if more than 10M UUIDs/sec are requested | + +Note: The default [node id](https://tools.ietf.org/html/rfc4122#section-4.1.6) (the last 12 digits in the UUID) is generated once, randomly, on process startup, and then remains unchanged for the duration of the process. + +Note: `options.random` and `options.rng` are only meaningful on the very first call to `v1()`, where they may be passed to initialize the internal `node` and `clockseq` fields. + +Example: + +```javascript +import { v1 as uuidv1 } from 'uuid'; + +uuidv1(); // ⇨ '2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d' +``` + +Example using `options`: + +```javascript +import { v1 as uuidv1 } from 'uuid'; + +const v1options = { + node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab], + clockseq: 0x1234, + msecs: new Date('2011-11-01').getTime(), + nsecs: 5678, +}; +uuidv1(v1options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab' +``` + +### uuid.v3(name, namespace[, buffer[, offset]]) + +Create an RFC version 3 (namespace w/ MD5) UUID + +API is identical to `v5()`, but uses "v3" instead. + +⚠️ Note: Per the RFC, "_If backward compatibility is not an issue, SHA-1 [Version 5] is preferred_." + +### uuid.v4([options[, buffer[, offset]]]) + +Create an RFC version 4 (random) UUID + +| | | +| --- | --- | +| [`options`] | `Object` with one or more of the following properties: | +| [`options.random`] | `Array` of 16 random bytes (0-255) | +| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | + +Example: + +```javascript +import { v4 as uuidv4 } from 'uuid'; + +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +Example using predefined `random` values: + +```javascript +import { v4 as uuidv4 } from 'uuid'; + +const v4options = { + random: [ + 0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea, 0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36, + ], +}; +uuidv4(v4options); // ⇨ '109156be-c4fb-41ea-b1b4-efe1671c5836' +``` + +### uuid.v5(name, namespace[, buffer[, offset]]) + +Create an RFC version 5 (namespace w/ SHA-1) UUID + +| | | +| --- | --- | +| `name` | `String \| Array` | +| `namespace` | `String \| Array[16]` Namespace UUID | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | + +Note: The RFC `DNS` and `URL` namespaces are available as `v5.DNS` and `v5.URL`. + +Example with custom namespace: + +```javascript +import { v5 as uuidv5 } from 'uuid'; + +// Define a custom namespace. Readers, create your own using something like +// https://www.uuidgenerator.net/ +const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; + +uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681' +``` + +Example with RFC `URL` namespace: + +```javascript +import { v5 as uuidv5 } from 'uuid'; + +uuidv5('https://www.w3.org/', uuidv5.URL); // ⇨ 'c106a26a-21bb-5538-8bf2-57095d1976c1' +``` + +### uuid.validate(str) + +Test a string to see if it is a valid UUID + +| | | +| --------- | --------------------------------------------------- | +| `str` | `String` to validate | +| _returns_ | `true` if string is a valid UUID, `false` otherwise | + +Example: + +```javascript +import { validate as uuidValidate } from 'uuid'; + +uuidValidate('not a UUID'); // ⇨ false +uuidValidate('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ true +``` + +Using `validate` and `version` together it is possible to do per-version validation, e.g. validate for only v4 UUIds. + +```javascript +import { version as uuidVersion } from 'uuid'; +import { validate as uuidValidate } from 'uuid'; + +function uuidValidateV4(uuid) { + return uuidValidate(uuid) && uuidVersion(uuid) === 4; +} + +const v1Uuid = 'd9428888-122b-11e1-b85c-61cd3cbb3210'; +const v4Uuid = '109156be-c4fb-41ea-b1b4-efe1671c5836'; + +uuidValidateV4(v4Uuid); // ⇨ true +uuidValidateV4(v1Uuid); // ⇨ false +``` + +### uuid.version(str) + +Detect RFC version of a UUID + +| | | +| --------- | ---------------------------------------- | +| `str` | A valid UUID `String` | +| _returns_ | `Number` The RFC version of the UUID | +| _throws_ | `TypeError` if `str` is not a valid UUID | + +Example: + +```javascript +import { version as uuidVersion } from 'uuid'; + +uuidVersion('45637ec4-c85f-11ea-87d0-0242ac130003'); // ⇨ 1 +uuidVersion('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ 4 +``` + +## Command Line + +UUIDs can be generated from the command line using `uuid`. + +```shell +$ npx uuid +ddeb27fb-d9a0-4624-be4d-4615062daed4 +``` + +The default is to generate version 4 UUIDS, however the other versions are supported. Type `uuid --help` for details: + +```shell +$ npx uuid --help + +Usage: + uuid + uuid v1 + uuid v3 + uuid v4 + uuid v5 + uuid --help + +Note: may be "URL" or "DNS" to use the corresponding UUIDs +defined by RFC4122 +``` + +## ECMAScript Modules + +This library comes with [ECMAScript Modules](https://www.ecma-international.org/ecma-262/6.0/#sec-modules) (ESM) support for Node.js versions that support it ([example](./examples/node-esmodules/)) as well as bundlers like [rollup.js](https://rollupjs.org/guide/en/#tree-shaking) ([example](./examples/browser-rollup/)) and [webpack](https://webpack.js.org/guides/tree-shaking/) ([example](./examples/browser-webpack/)) (targeting both, Node.js and browser environments). + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +To run the examples you must first create a dist build of this library in the module root: + +```shell +npm run build +``` + +## CDN Builds + +### ECMAScript Modules + +To load this module directly into modern browsers that [support loading ECMAScript Modules](https://caniuse.com/#feat=es6-module) you can make use of [jspm](https://jspm.org/): + +```html + +``` + +### UMD + +As of `uuid@9` [UMD (Universal Module Definition)](https://github.com/umdjs/umd) builds are no longer shipped with this library. + +If you need a UMD build of this library, use a bundler like Webpack or Rollup. Alternatively, refer to the documentation of [`uuid@8.3.2`](https://github.com/uuidjs/uuid/blob/v8.3.2/README.md#umd) which was the last version that shipped UMD builds. + +## Known issues + +### Duplicate UUIDs (Googlebot) + +This module may generate duplicate UUIDs when run in clients with _deterministic_ random number generators, such as [Googlebot crawlers](https://developers.google.com/search/docs/advanced/crawling/overview-google-crawlers). This can cause problems for apps that expect client-generated UUIDs to always be unique. Developers should be prepared for this and have a strategy for dealing with possible collisions, such as: + +- Check for duplicate UUIDs, fail gracefully +- Disable write operations for Googlebot clients + +### "getRandomValues() not supported" + +This error occurs in environments where the standard [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) API is not supported. This issue can be resolved by adding an appropriate polyfill: + +### React Native / Expo + +1. Install [`react-native-get-random-values`](https://github.com/LinusU/react-native-get-random-values#readme) +1. Import it _before_ `uuid`. Since `uuid` might also appear as a transitive dependency of some other imports it's safest to just import `react-native-get-random-values` as the very first thing in your entry point: + +```javascript +import 'react-native-get-random-values'; +import { v4 as uuidv4 } from 'uuid'; +``` + +Note: If you are using Expo, you must be using at least `react-native-get-random-values@1.5.0` and `expo@39.0.0`. + +### Web Workers / Service Workers (Edge <= 18) + +[In Edge <= 18, Web Crypto is not supported in Web Workers or Service Workers](https://caniuse.com/#feat=cryptography) and we are not aware of a polyfill (let us know if you find one, please). + +### IE 11 (Internet Explorer) + +Support for IE11 and other legacy browsers has been dropped as of `uuid@9`. If you need to support legacy browsers, you can always transpile the uuid module source yourself (e.g. using [Babel](https://babeljs.io/)). + +## Upgrading From `uuid@7` + +### Only Named Exports Supported When Using with Node.js ESM + +`uuid@7` did not come with native ECMAScript Module (ESM) support for Node.js. Importing it in Node.js ESM consequently imported the CommonJS source with a default export. This library now comes with true Node.js ESM support and only provides named exports. + +Instead of doing: + +```javascript +import uuid from 'uuid'; +uuid.v4(); +``` + +you will now have to use the named exports: + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); +``` + +### Deep Requires No Longer Supported + +Deep requires like `require('uuid/v4')` [which have been deprecated in `uuid@7`](#deep-requires-now-deprecated) are no longer supported. + +## Upgrading From `uuid@3` + +"_Wait... what happened to `uuid@4` thru `uuid@6`?!?_" + +In order to avoid confusion with RFC [version 4](#uuidv4options-buffer-offset) and [version 5](#uuidv5name-namespace-buffer-offset) UUIDs, and a possible [version 6](http://gh.peabody.io/uuidv6/), releases 4 thru 6 of this module have been skipped. + +### Deep Requires Now Deprecated + +`uuid@3` encouraged the use of deep requires to minimize the bundle size of browser builds: + +```javascript +const uuidv4 = require('uuid/v4'); // <== NOW DEPRECATED! +uuidv4(); +``` + +As of `uuid@7` this library now provides ECMAScript modules builds, which allow packagers like Webpack and Rollup to do "tree-shaking" to remove dead code. Instead, use the `import` syntax: + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); +``` + +... or for CommonJS: + +```javascript +const { v4: uuidv4 } = require('uuid'); +uuidv4(); +``` + +### Default Export Removed + +`uuid@3` was exporting the Version 4 UUID method as a default export: + +```javascript +const uuid = require('uuid'); // <== REMOVED! +``` + +This usage pattern was already discouraged in `uuid@3` and has been removed in `uuid@7`. + +--- + +Markdown generated from [README_js.md](README_js.md) by diff --git a/node_modules/teeny-request/node_modules/uuid/dist/bin/uuid b/node_modules/teeny-request/node_modules/uuid/dist/bin/uuid new file mode 100644 index 0000000..f38d2ee --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/bin/uuid @@ -0,0 +1,2 @@ +#!/usr/bin/env node +require('../uuid-bin'); diff --git a/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/index.js b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/index.js new file mode 100644 index 0000000..5586dd3 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/index.js @@ -0,0 +1,79 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "NIL", { + enumerable: true, + get: function get() { + return _nil.default; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function get() { + return _parse.default; + } +}); +Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function get() { + return _stringify.default; + } +}); +Object.defineProperty(exports, "v1", { + enumerable: true, + get: function get() { + return _v.default; + } +}); +Object.defineProperty(exports, "v3", { + enumerable: true, + get: function get() { + return _v2.default; + } +}); +Object.defineProperty(exports, "v4", { + enumerable: true, + get: function get() { + return _v3.default; + } +}); +Object.defineProperty(exports, "v5", { + enumerable: true, + get: function get() { + return _v4.default; + } +}); +Object.defineProperty(exports, "validate", { + enumerable: true, + get: function get() { + return _validate.default; + } +}); +Object.defineProperty(exports, "version", { + enumerable: true, + get: function get() { + return _version.default; + } +}); + +var _v = _interopRequireDefault(require("./v1.js")); + +var _v2 = _interopRequireDefault(require("./v3.js")); + +var _v3 = _interopRequireDefault(require("./v4.js")); + +var _v4 = _interopRequireDefault(require("./v5.js")); + +var _nil = _interopRequireDefault(require("./nil.js")); + +var _version = _interopRequireDefault(require("./version.js")); + +var _validate = _interopRequireDefault(require("./validate.js")); + +var _stringify = _interopRequireDefault(require("./stringify.js")); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/md5.js b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/md5.js new file mode 100644 index 0000000..7a4582a --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/md5.js @@ -0,0 +1,223 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Uint8Array(msg.length); + + for (let i = 0; i < msg.length; ++i) { + bytes[i] = msg.charCodeAt(i); + } + } + + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); +} +/* + * Convert an array of little-endian words to an array of bytes + */ + + +function md5ToHexEncodedArray(input) { + const output = []; + const length32 = input.length * 32; + const hexTab = '0123456789abcdef'; + + for (let i = 0; i < length32; i += 8) { + const x = input[i >> 5] >>> i % 32 & 0xff; + const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); + } + + return output; +} +/** + * Calculate output length with padding and bit length + */ + + +function getOutputLength(inputLength8) { + return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; +} +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + + +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[getOutputLength(len) - 1] = len; + let a = 1732584193; + let b = -271733879; + let c = -1732584194; + let d = 271733878; + + for (let i = 0; i < x.length; i += 16) { + const olda = a; + const oldb = b; + const oldc = c; + const oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; +} +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + + +function bytesToWords(input) { + if (input.length === 0) { + return []; + } + + const length8 = input.length * 8; + const output = new Uint32Array(getOutputLength(length8)); + + for (let i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } + + return output; +} +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + + +function safeAdd(x, y) { + const lsw = (x & 0xffff) + (y & 0xffff); + const msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; +} +/* + * Bitwise rotate a 32-bit number to the left. + */ + + +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; +} +/* + * These functions implement the four basic operations the algorithm uses. + */ + + +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} + +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); +} + +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); +} + +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} + +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} + +var _default = md5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/native.js b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/native.js new file mode 100644 index 0000000..c2eea59 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/native.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); +var _default = { + randomUUID +}; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/nil.js b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/nil.js new file mode 100644 index 0000000..7ade577 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/nil.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = '00000000-0000-0000-0000-000000000000'; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/parse.js b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/parse.js new file mode 100644 index 0000000..4c69fc3 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/parse.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +var _default = parse; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/regex.js b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/regex.js new file mode 100644 index 0000000..1ef91d6 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/regex.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/rng.js b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/rng.js new file mode 100644 index 0000000..d067cdb --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/rng.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rng; +// Unique ID creation requires a high quality random # generator. In the browser we therefore +// require the crypto API and do not support built-in fallback to lower quality random number +// generators (like Math.random()). +let getRandomValues; +const rnds8 = new Uint8Array(16); + +function rng() { + // lazy load so that environments that need to polyfill have a chance to do so + if (!getRandomValues) { + // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. + 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); +} \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/sha1.js b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/sha1.js new file mode 100644 index 0000000..24cbced --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/sha1.js @@ -0,0 +1,104 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + + case 1: + return x ^ y ^ z; + + case 2: + return x & y ^ x & z ^ y & z; + + case 3: + return x ^ y ^ z; + } +} + +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} + +function sha1(bytes) { + const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = []; + + for (let i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + // Convert Array-like to Array + bytes = Array.prototype.slice.call(bytes); + } + + bytes.push(0x80); + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + + for (let i = 0; i < N; ++i) { + const arr = new Uint32Array(16); + + for (let j = 0; j < 16; ++j) { + arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + } + + M[i] = arr; + } + + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; + + for (let i = 0; i < N; ++i) { + const W = new Uint32Array(80); + + for (let t = 0; t < 16; ++t) { + W[t] = M[i][t]; + } + + for (let t = 16; t < 80; ++t) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } + + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; +} + +var _default = sha1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/stringify.js b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/stringify.js new file mode 100644 index 0000000..390bf89 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/stringify.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +exports.unsafeStringify = unsafeStringify; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} + +function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; +} + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!(0, _validate.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +var _default = stringify; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/v1.js b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/v1.js new file mode 100644 index 0000000..125bc58 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/v1.js @@ -0,0 +1,107 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = require("./stringify.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || _rng.default)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || (0, _stringify.unsafeStringify)(b); +} + +var _default = v1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/v3.js b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/v3.js new file mode 100644 index 0000000..6b47ff5 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/v3.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _md = _interopRequireDefault(require("./md5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/v35.js b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/v35.js new file mode 100644 index 0000000..7c522d9 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/v35.js @@ -0,0 +1,80 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.URL = exports.DNS = void 0; +exports.default = v35; + +var _stringify = require("./stringify.js"); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.DNS = DNS; +const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = URL; + +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 = (0, _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)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return (0, _stringify.unsafeStringify)(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/v4.js b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/v4.js new file mode 100644 index 0000000..959d698 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/v4.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _native = _interopRequireDefault(require("./native.js")); + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = require("./stringify.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function v4(options, buf, offset) { + if (_native.default.randomUUID && !buf && !options) { + return _native.default.randomUUID(); + } + + options = options || {}; + + const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return (0, _stringify.unsafeStringify)(rnds); +} + +var _default = v4; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/v5.js b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/v5.js new file mode 100644 index 0000000..99d615e --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/v5.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _sha = _interopRequireDefault(require("./sha1.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/validate.js b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/validate.js new file mode 100644 index 0000000..fd05215 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/validate.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _regex = _interopRequireDefault(require("./regex.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function validate(uuid) { + return typeof uuid === 'string' && _regex.default.test(uuid); +} + +var _default = validate; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/version.js b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/version.js new file mode 100644 index 0000000..f63af01 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/commonjs-browser/version.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function version(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.slice(14, 15), 16); +} + +var _default = version; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/index.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/index.js new file mode 100644 index 0000000..1db6f6d --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/index.js @@ -0,0 +1,9 @@ +export { default as v1 } from './v1.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as NIL } from './nil.js'; +export { default as version } from './version.js'; +export { default as validate } from './validate.js'; +export { default as stringify } from './stringify.js'; +export { default as parse } from './parse.js'; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/md5.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/md5.js new file mode 100644 index 0000000..f12212e --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/md5.js @@ -0,0 +1,215 @@ +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Uint8Array(msg.length); + + for (let i = 0; i < msg.length; ++i) { + bytes[i] = msg.charCodeAt(i); + } + } + + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); +} +/* + * Convert an array of little-endian words to an array of bytes + */ + + +function md5ToHexEncodedArray(input) { + const output = []; + const length32 = input.length * 32; + const hexTab = '0123456789abcdef'; + + for (let i = 0; i < length32; i += 8) { + const x = input[i >> 5] >>> i % 32 & 0xff; + const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); + } + + return output; +} +/** + * Calculate output length with padding and bit length + */ + + +function getOutputLength(inputLength8) { + return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; +} +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + + +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[getOutputLength(len) - 1] = len; + let a = 1732584193; + let b = -271733879; + let c = -1732584194; + let d = 271733878; + + for (let i = 0; i < x.length; i += 16) { + const olda = a; + const oldb = b; + const oldc = c; + const oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; +} +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + + +function bytesToWords(input) { + if (input.length === 0) { + return []; + } + + const length8 = input.length * 8; + const output = new Uint32Array(getOutputLength(length8)); + + for (let i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } + + return output; +} +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + + +function safeAdd(x, y) { + const lsw = (x & 0xffff) + (y & 0xffff); + const msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; +} +/* + * Bitwise rotate a 32-bit number to the left. + */ + + +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; +} +/* + * These functions implement the four basic operations the algorithm uses. + */ + + +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} + +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); +} + +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); +} + +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} + +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} + +export default md5; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/native.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/native.js new file mode 100644 index 0000000..b22292c --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/native.js @@ -0,0 +1,4 @@ +const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); +export default { + randomUUID +}; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/nil.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/nil.js new file mode 100644 index 0000000..b36324c --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/nil.js @@ -0,0 +1 @@ +export default '00000000-0000-0000-0000-000000000000'; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/parse.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/parse.js new file mode 100644 index 0000000..6421c5d --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/parse.js @@ -0,0 +1,35 @@ +import validate from './validate.js'; + +function parse(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +export default parse; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/regex.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/regex.js new file mode 100644 index 0000000..3da8673 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/regex.js @@ -0,0 +1 @@ +export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/rng.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/rng.js new file mode 100644 index 0000000..6e65234 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/rng.js @@ -0,0 +1,18 @@ +// Unique ID creation requires a high quality random # generator. In the browser we therefore +// require the crypto API and do not support built-in fallback to lower quality random number +// generators (like Math.random()). +let getRandomValues; +const rnds8 = new Uint8Array(16); +export default function rng() { + // lazy load so that environments that need to polyfill have a chance to do so + if (!getRandomValues) { + // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. + 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); +} \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/sha1.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/sha1.js new file mode 100644 index 0000000..d3c2565 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/sha1.js @@ -0,0 +1,96 @@ +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + + case 1: + return x ^ y ^ z; + + case 2: + return x & y ^ x & z ^ y & z; + + case 3: + return x ^ y ^ z; + } +} + +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} + +function sha1(bytes) { + const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = []; + + for (let i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + // Convert Array-like to Array + bytes = Array.prototype.slice.call(bytes); + } + + bytes.push(0x80); + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + + for (let i = 0; i < N; ++i) { + const arr = new Uint32Array(16); + + for (let j = 0; j < 16; ++j) { + arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + } + + M[i] = arr; + } + + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; + + for (let i = 0; i < N; ++i) { + const W = new Uint32Array(80); + + for (let t = 0; t < 16; ++t) { + W[t] = M[i][t]; + } + + for (let t = 16; t < 80; ++t) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } + + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; +} + +export default sha1; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/stringify.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/stringify.js new file mode 100644 index 0000000..a6e4c88 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/stringify.js @@ -0,0 +1,33 @@ +import validate from './validate.js'; +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ + +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} + +export function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; +} + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!validate(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +export default stringify; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/v1.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/v1.js new file mode 100644 index 0000000..382e5d7 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/v1.js @@ -0,0 +1,95 @@ +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; // **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || rng)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || unsafeStringify(b); +} + +export default v1; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/v3.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/v3.js new file mode 100644 index 0000000..09063b8 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/v3.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import md5 from './md5.js'; +const v3 = v35('v3', 0x30, md5); +export default v3; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/v35.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/v35.js new file mode 100644 index 0000000..3355e1f --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/v35.js @@ -0,0 +1,66 @@ +import { unsafeStringify } from './stringify.js'; +import parse from './parse.js'; + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +export const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +export const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +export default 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(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)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return unsafeStringify(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/v4.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/v4.js new file mode 100644 index 0000000..95ea879 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/v4.js @@ -0,0 +1,29 @@ +import native from './native.js'; +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; + +function v4(options, buf, offset) { + if (native.randomUUID && !buf && !options) { + return native.randomUUID(); + } + + options = options || {}; + const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return unsafeStringify(rnds); +} + +export default v4; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/v5.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/v5.js new file mode 100644 index 0000000..e87fe31 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/v5.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import sha1 from './sha1.js'; +const v5 = v35('v5', 0x50, sha1); +export default v5; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/validate.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/validate.js new file mode 100644 index 0000000..f1cdc7a --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/validate.js @@ -0,0 +1,7 @@ +import REGEX from './regex.js'; + +function validate(uuid) { + return typeof uuid === 'string' && REGEX.test(uuid); +} + +export default validate; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/version.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/version.js new file mode 100644 index 0000000..9363076 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-browser/version.js @@ -0,0 +1,11 @@ +import validate from './validate.js'; + +function version(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.slice(14, 15), 16); +} + +export default version; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-node/index.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/index.js new file mode 100644 index 0000000..1db6f6d --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/index.js @@ -0,0 +1,9 @@ +export { default as v1 } from './v1.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as NIL } from './nil.js'; +export { default as version } from './version.js'; +export { default as validate } from './validate.js'; +export { default as stringify } from './stringify.js'; +export { default as parse } from './parse.js'; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-node/md5.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/md5.js new file mode 100644 index 0000000..4d68b04 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/md5.js @@ -0,0 +1,13 @@ +import crypto from 'crypto'; + +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return crypto.createHash('md5').update(bytes).digest(); +} + +export default md5; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-node/native.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/native.js new file mode 100644 index 0000000..f0d1992 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/native.js @@ -0,0 +1,4 @@ +import crypto from 'crypto'; +export default { + randomUUID: crypto.randomUUID +}; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-node/nil.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/nil.js new file mode 100644 index 0000000..b36324c --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/nil.js @@ -0,0 +1 @@ +export default '00000000-0000-0000-0000-000000000000'; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-node/parse.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/parse.js new file mode 100644 index 0000000..6421c5d --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/parse.js @@ -0,0 +1,35 @@ +import validate from './validate.js'; + +function parse(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +export default parse; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-node/regex.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/regex.js new file mode 100644 index 0000000..3da8673 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/regex.js @@ -0,0 +1 @@ +export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-node/rng.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/rng.js new file mode 100644 index 0000000..8006244 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/rng.js @@ -0,0 +1,12 @@ +import crypto from 'crypto'; +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate + +let poolPtr = rnds8Pool.length; +export default function rng() { + if (poolPtr > rnds8Pool.length - 16) { + crypto.randomFillSync(rnds8Pool); + poolPtr = 0; + } + + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-node/sha1.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/sha1.js new file mode 100644 index 0000000..e23850b --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/sha1.js @@ -0,0 +1,13 @@ +import crypto from 'crypto'; + +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return crypto.createHash('sha1').update(bytes).digest(); +} + +export default sha1; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-node/stringify.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/stringify.js new file mode 100644 index 0000000..a6e4c88 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/stringify.js @@ -0,0 +1,33 @@ +import validate from './validate.js'; +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ + +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} + +export function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; +} + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!validate(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +export default stringify; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-node/v1.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/v1.js new file mode 100644 index 0000000..382e5d7 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/v1.js @@ -0,0 +1,95 @@ +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; // **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || rng)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || unsafeStringify(b); +} + +export default v1; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-node/v3.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/v3.js new file mode 100644 index 0000000..09063b8 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/v3.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import md5 from './md5.js'; +const v3 = v35('v3', 0x30, md5); +export default v3; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-node/v35.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/v35.js new file mode 100644 index 0000000..3355e1f --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/v35.js @@ -0,0 +1,66 @@ +import { unsafeStringify } from './stringify.js'; +import parse from './parse.js'; + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +export const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +export const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +export default 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(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)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return unsafeStringify(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-node/v4.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/v4.js new file mode 100644 index 0000000..95ea879 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/v4.js @@ -0,0 +1,29 @@ +import native from './native.js'; +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; + +function v4(options, buf, offset) { + if (native.randomUUID && !buf && !options) { + return native.randomUUID(); + } + + options = options || {}; + const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return unsafeStringify(rnds); +} + +export default v4; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-node/v5.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/v5.js new file mode 100644 index 0000000..e87fe31 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/v5.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import sha1 from './sha1.js'; +const v5 = v35('v5', 0x50, sha1); +export default v5; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-node/validate.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/validate.js new file mode 100644 index 0000000..f1cdc7a --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/validate.js @@ -0,0 +1,7 @@ +import REGEX from './regex.js'; + +function validate(uuid) { + return typeof uuid === 'string' && REGEX.test(uuid); +} + +export default validate; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/esm-node/version.js b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/version.js new file mode 100644 index 0000000..9363076 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/esm-node/version.js @@ -0,0 +1,11 @@ +import validate from './validate.js'; + +function version(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.slice(14, 15), 16); +} + +export default version; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/index.js b/node_modules/teeny-request/node_modules/uuid/dist/index.js new file mode 100644 index 0000000..88d676a --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/index.js @@ -0,0 +1,79 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "NIL", { + enumerable: true, + get: function () { + return _nil.default; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function () { + return _parse.default; + } +}); +Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function () { + return _stringify.default; + } +}); +Object.defineProperty(exports, "v1", { + enumerable: true, + get: function () { + return _v.default; + } +}); +Object.defineProperty(exports, "v3", { + enumerable: true, + get: function () { + return _v2.default; + } +}); +Object.defineProperty(exports, "v4", { + enumerable: true, + get: function () { + return _v3.default; + } +}); +Object.defineProperty(exports, "v5", { + enumerable: true, + get: function () { + return _v4.default; + } +}); +Object.defineProperty(exports, "validate", { + enumerable: true, + get: function () { + return _validate.default; + } +}); +Object.defineProperty(exports, "version", { + enumerable: true, + get: function () { + return _version.default; + } +}); + +var _v = _interopRequireDefault(require("./v1.js")); + +var _v2 = _interopRequireDefault(require("./v3.js")); + +var _v3 = _interopRequireDefault(require("./v4.js")); + +var _v4 = _interopRequireDefault(require("./v5.js")); + +var _nil = _interopRequireDefault(require("./nil.js")); + +var _version = _interopRequireDefault(require("./version.js")); + +var _validate = _interopRequireDefault(require("./validate.js")); + +var _stringify = _interopRequireDefault(require("./stringify.js")); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/md5-browser.js b/node_modules/teeny-request/node_modules/uuid/dist/md5-browser.js new file mode 100644 index 0000000..7a4582a --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/md5-browser.js @@ -0,0 +1,223 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Uint8Array(msg.length); + + for (let i = 0; i < msg.length; ++i) { + bytes[i] = msg.charCodeAt(i); + } + } + + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); +} +/* + * Convert an array of little-endian words to an array of bytes + */ + + +function md5ToHexEncodedArray(input) { + const output = []; + const length32 = input.length * 32; + const hexTab = '0123456789abcdef'; + + for (let i = 0; i < length32; i += 8) { + const x = input[i >> 5] >>> i % 32 & 0xff; + const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); + } + + return output; +} +/** + * Calculate output length with padding and bit length + */ + + +function getOutputLength(inputLength8) { + return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; +} +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + + +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[getOutputLength(len) - 1] = len; + let a = 1732584193; + let b = -271733879; + let c = -1732584194; + let d = 271733878; + + for (let i = 0; i < x.length; i += 16) { + const olda = a; + const oldb = b; + const oldc = c; + const oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; +} +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + + +function bytesToWords(input) { + if (input.length === 0) { + return []; + } + + const length8 = input.length * 8; + const output = new Uint32Array(getOutputLength(length8)); + + for (let i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } + + return output; +} +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + + +function safeAdd(x, y) { + const lsw = (x & 0xffff) + (y & 0xffff); + const msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; +} +/* + * Bitwise rotate a 32-bit number to the left. + */ + + +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; +} +/* + * These functions implement the four basic operations the algorithm uses. + */ + + +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} + +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); +} + +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); +} + +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} + +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} + +var _default = md5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/md5.js b/node_modules/teeny-request/node_modules/uuid/dist/md5.js new file mode 100644 index 0000000..824d481 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/md5.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return _crypto.default.createHash('md5').update(bytes).digest(); +} + +var _default = md5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/native-browser.js b/node_modules/teeny-request/node_modules/uuid/dist/native-browser.js new file mode 100644 index 0000000..c2eea59 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/native-browser.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); +var _default = { + randomUUID +}; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/native.js b/node_modules/teeny-request/node_modules/uuid/dist/native.js new file mode 100644 index 0000000..de80469 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/native.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var _default = { + randomUUID: _crypto.default.randomUUID +}; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/nil.js b/node_modules/teeny-request/node_modules/uuid/dist/nil.js new file mode 100644 index 0000000..7ade577 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/nil.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = '00000000-0000-0000-0000-000000000000'; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/parse.js b/node_modules/teeny-request/node_modules/uuid/dist/parse.js new file mode 100644 index 0000000..4c69fc3 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/parse.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +var _default = parse; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/regex.js b/node_modules/teeny-request/node_modules/uuid/dist/regex.js new file mode 100644 index 0000000..1ef91d6 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/regex.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/rng-browser.js b/node_modules/teeny-request/node_modules/uuid/dist/rng-browser.js new file mode 100644 index 0000000..d067cdb --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/rng-browser.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rng; +// Unique ID creation requires a high quality random # generator. In the browser we therefore +// require the crypto API and do not support built-in fallback to lower quality random number +// generators (like Math.random()). +let getRandomValues; +const rnds8 = new Uint8Array(16); + +function rng() { + // lazy load so that environments that need to polyfill have a chance to do so + if (!getRandomValues) { + // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. + 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); +} \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/rng.js b/node_modules/teeny-request/node_modules/uuid/dist/rng.js new file mode 100644 index 0000000..3507f93 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/rng.js @@ -0,0 +1,24 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rng; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate + +let poolPtr = rnds8Pool.length; + +function rng() { + if (poolPtr > rnds8Pool.length - 16) { + _crypto.default.randomFillSync(rnds8Pool); + + poolPtr = 0; + } + + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/sha1-browser.js b/node_modules/teeny-request/node_modules/uuid/dist/sha1-browser.js new file mode 100644 index 0000000..24cbced --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/sha1-browser.js @@ -0,0 +1,104 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + + case 1: + return x ^ y ^ z; + + case 2: + return x & y ^ x & z ^ y & z; + + case 3: + return x ^ y ^ z; + } +} + +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} + +function sha1(bytes) { + const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = []; + + for (let i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + // Convert Array-like to Array + bytes = Array.prototype.slice.call(bytes); + } + + bytes.push(0x80); + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + + for (let i = 0; i < N; ++i) { + const arr = new Uint32Array(16); + + for (let j = 0; j < 16; ++j) { + arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + } + + M[i] = arr; + } + + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; + + for (let i = 0; i < N; ++i) { + const W = new Uint32Array(80); + + for (let t = 0; t < 16; ++t) { + W[t] = M[i][t]; + } + + for (let t = 16; t < 80; ++t) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } + + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; +} + +var _default = sha1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/sha1.js b/node_modules/teeny-request/node_modules/uuid/dist/sha1.js new file mode 100644 index 0000000..03bdd63 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/sha1.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return _crypto.default.createHash('sha1').update(bytes).digest(); +} + +var _default = sha1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/stringify.js b/node_modules/teeny-request/node_modules/uuid/dist/stringify.js new file mode 100644 index 0000000..390bf89 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/stringify.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +exports.unsafeStringify = unsafeStringify; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} + +function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; +} + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!(0, _validate.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +var _default = stringify; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/uuid-bin.js b/node_modules/teeny-request/node_modules/uuid/dist/uuid-bin.js new file mode 100644 index 0000000..50a7a9f --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/uuid-bin.js @@ -0,0 +1,85 @@ +"use strict"; + +var _assert = _interopRequireDefault(require("assert")); + +var _v = _interopRequireDefault(require("./v1.js")); + +var _v2 = _interopRequireDefault(require("./v3.js")); + +var _v3 = _interopRequireDefault(require("./v4.js")); + +var _v4 = _interopRequireDefault(require("./v5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function usage() { + console.log('Usage:'); + console.log(' uuid'); + console.log(' uuid v1'); + console.log(' uuid v3 '); + console.log(' uuid v4'); + console.log(' uuid v5 '); + console.log(' uuid --help'); + console.log('\nNote: may be "URL" or "DNS" to use the corresponding UUIDs defined by RFC4122'); +} + +const args = process.argv.slice(2); + +if (args.indexOf('--help') >= 0) { + usage(); + process.exit(0); +} + +const version = args.shift() || 'v4'; + +switch (version) { + case 'v1': + console.log((0, _v.default)()); + break; + + case 'v3': + { + const name = args.shift(); + let namespace = args.shift(); + (0, _assert.default)(name != null, 'v3 name not specified'); + (0, _assert.default)(namespace != null, 'v3 namespace not specified'); + + if (namespace === 'URL') { + namespace = _v2.default.URL; + } + + if (namespace === 'DNS') { + namespace = _v2.default.DNS; + } + + console.log((0, _v2.default)(name, namespace)); + break; + } + + case 'v4': + console.log((0, _v3.default)()); + break; + + case 'v5': + { + const name = args.shift(); + let namespace = args.shift(); + (0, _assert.default)(name != null, 'v5 name not specified'); + (0, _assert.default)(namespace != null, 'v5 namespace not specified'); + + if (namespace === 'URL') { + namespace = _v4.default.URL; + } + + if (namespace === 'DNS') { + namespace = _v4.default.DNS; + } + + console.log((0, _v4.default)(name, namespace)); + break; + } + + default: + usage(); + process.exit(1); +} \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/v1.js b/node_modules/teeny-request/node_modules/uuid/dist/v1.js new file mode 100644 index 0000000..125bc58 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/v1.js @@ -0,0 +1,107 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = require("./stringify.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || _rng.default)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || (0, _stringify.unsafeStringify)(b); +} + +var _default = v1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/v3.js b/node_modules/teeny-request/node_modules/uuid/dist/v3.js new file mode 100644 index 0000000..6b47ff5 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/v3.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _md = _interopRequireDefault(require("./md5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/v35.js b/node_modules/teeny-request/node_modules/uuid/dist/v35.js new file mode 100644 index 0000000..7c522d9 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/v35.js @@ -0,0 +1,80 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.URL = exports.DNS = void 0; +exports.default = v35; + +var _stringify = require("./stringify.js"); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.DNS = DNS; +const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = URL; + +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 = (0, _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)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return (0, _stringify.unsafeStringify)(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/v4.js b/node_modules/teeny-request/node_modules/uuid/dist/v4.js new file mode 100644 index 0000000..959d698 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/v4.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _native = _interopRequireDefault(require("./native.js")); + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = require("./stringify.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function v4(options, buf, offset) { + if (_native.default.randomUUID && !buf && !options) { + return _native.default.randomUUID(); + } + + options = options || {}; + + const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return (0, _stringify.unsafeStringify)(rnds); +} + +var _default = v4; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/v5.js b/node_modules/teeny-request/node_modules/uuid/dist/v5.js new file mode 100644 index 0000000..99d615e --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/v5.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _sha = _interopRequireDefault(require("./sha1.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/validate.js b/node_modules/teeny-request/node_modules/uuid/dist/validate.js new file mode 100644 index 0000000..fd05215 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/validate.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _regex = _interopRequireDefault(require("./regex.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function validate(uuid) { + return typeof uuid === 'string' && _regex.default.test(uuid); +} + +var _default = validate; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/dist/version.js b/node_modules/teeny-request/node_modules/uuid/dist/version.js new file mode 100644 index 0000000..f63af01 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/dist/version.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function version(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.slice(14, 15), 16); +} + +var _default = version; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/teeny-request/node_modules/uuid/package.json b/node_modules/teeny-request/node_modules/uuid/package.json new file mode 100644 index 0000000..6cc3361 --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/package.json @@ -0,0 +1,135 @@ +{ + "name": "uuid", + "version": "9.0.1", + "description": "RFC4122 (v1, v4, and v5) UUIDs", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "commitlint": { + "extends": [ + "@commitlint/config-conventional" + ] + }, + "keywords": [ + "uuid", + "guid", + "rfc4122" + ], + "license": "MIT", + "bin": { + "uuid": "./dist/bin/uuid" + }, + "sideEffects": false, + "main": "./dist/index.js", + "exports": { + ".": { + "node": { + "module": "./dist/esm-node/index.js", + "require": "./dist/index.js", + "import": "./wrapper.mjs" + }, + "browser": { + "import": "./dist/esm-browser/index.js", + "require": "./dist/commonjs-browser/index.js" + }, + "default": "./dist/esm-browser/index.js" + }, + "./package.json": "./package.json" + }, + "module": "./dist/esm-node/index.js", + "browser": { + "./dist/md5.js": "./dist/md5-browser.js", + "./dist/native.js": "./dist/native-browser.js", + "./dist/rng.js": "./dist/rng-browser.js", + "./dist/sha1.js": "./dist/sha1-browser.js", + "./dist/esm-node/index.js": "./dist/esm-browser/index.js" + }, + "files": [ + "CHANGELOG.md", + "CONTRIBUTING.md", + "LICENSE.md", + "README.md", + "dist", + "wrapper.mjs" + ], + "devDependencies": { + "@babel/cli": "7.18.10", + "@babel/core": "7.18.10", + "@babel/eslint-parser": "7.18.9", + "@babel/preset-env": "7.18.10", + "@commitlint/cli": "17.0.3", + "@commitlint/config-conventional": "17.0.3", + "bundlewatch": "0.3.3", + "eslint": "8.21.0", + "eslint-config-prettier": "8.5.0", + "eslint-config-standard": "17.0.0", + "eslint-plugin-import": "2.26.0", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-prettier": "4.2.1", + "eslint-plugin-promise": "6.0.0", + "husky": "8.0.1", + "jest": "28.1.3", + "lint-staged": "13.0.3", + "npm-run-all": "4.1.5", + "optional-dev-dependency": "2.0.1", + "prettier": "2.7.1", + "random-seed": "0.3.0", + "runmd": "1.3.9", + "standard-version": "9.5.0" + }, + "optionalDevDependencies": { + "@wdio/browserstack-service": "7.16.10", + "@wdio/cli": "7.16.10", + "@wdio/jasmine-framework": "7.16.6", + "@wdio/local-runner": "7.16.10", + "@wdio/spec-reporter": "7.16.9", + "@wdio/static-server-service": "7.16.6" + }, + "scripts": { + "examples:browser:webpack:build": "cd examples/browser-webpack && npm install && npm run build", + "examples:browser:rollup:build": "cd examples/browser-rollup && npm install && npm run build", + "examples:node:commonjs:test": "cd examples/node-commonjs && npm install && npm test", + "examples:node:esmodules:test": "cd examples/node-esmodules && npm install && npm test", + "examples:node:jest:test": "cd examples/node-jest && npm install && npm test", + "prepare": "cd $( git rev-parse --show-toplevel ) && husky install", + "lint": "npm run eslint:check && npm run prettier:check", + "eslint:check": "eslint src/ test/ examples/ *.js", + "eslint:fix": "eslint --fix src/ test/ examples/ *.js", + "pretest": "[ -n $CI ] || npm run build", + "test": "BABEL_ENV=commonjsNode node --throw-deprecation node_modules/.bin/jest test/unit/", + "pretest:browser": "optional-dev-dependency && npm run build && npm-run-all --parallel examples:browser:**", + "test:browser": "wdio run ./wdio.conf.js", + "pretest:node": "npm run build", + "test:node": "npm-run-all --parallel examples:node:**", + "test:pack": "./scripts/testpack.sh", + "pretest:benchmark": "npm run build", + "test:benchmark": "cd examples/benchmark && npm install && npm test", + "prettier:check": "prettier --check '**/*.{js,jsx,json,md}'", + "prettier:fix": "prettier --write '**/*.{js,jsx,json,md}'", + "bundlewatch": "npm run pretest:browser && bundlewatch --config bundlewatch.config.json", + "md": "runmd --watch --output=README.md README_js.md", + "docs": "( node --version | grep -q 'v18' ) && ( npm run build && npx runmd --output=README.md README_js.md )", + "docs:diff": "npm run docs && git diff --quiet README.md", + "build": "./scripts/build.sh", + "prepack": "npm run build", + "release": "standard-version --no-verify" + }, + "repository": { + "type": "git", + "url": "https://github.com/uuidjs/uuid.git" + }, + "lint-staged": { + "*.{js,jsx,json,md}": [ + "prettier --write" + ], + "*.{js,jsx}": [ + "eslint --fix" + ] + }, + "standard-version": { + "scripts": { + "postchangelog": "prettier --write CHANGELOG.md" + } + } +} diff --git a/node_modules/teeny-request/node_modules/uuid/wrapper.mjs b/node_modules/teeny-request/node_modules/uuid/wrapper.mjs new file mode 100644 index 0000000..c31e9ce --- /dev/null +++ b/node_modules/teeny-request/node_modules/uuid/wrapper.mjs @@ -0,0 +1,10 @@ +import uuid from './dist/index.js'; +export const v1 = uuid.v1; +export const v3 = uuid.v3; +export const v4 = uuid.v4; +export const v5 = uuid.v5; +export const NIL = uuid.NIL; +export const version = uuid.version; +export const validate = uuid.validate; +export const stringify = uuid.stringify; +export const parse = uuid.parse; diff --git a/node_modules/teeny-request/package.json b/node_modules/teeny-request/package.json new file mode 100644 index 0000000..d24f9dd --- /dev/null +++ b/node_modules/teeny-request/package.json @@ -0,0 +1,68 @@ +{ + "name": "teeny-request", + "version": "9.0.0", + "description": "Like request, but smaller.", + "main": "./build/src/index.js", + "types": "./build/src/index.d.ts", + "engines": { + "node": ">=14" + }, + "scripts": { + "test": "c8 mocha build/test", + "compile": "tsc -p .", + "pretest": "npm run compile", + "lint": "gts check", + "clean": "gts clean", + "fix": "gts fix", + "prepare": "npm run compile", + "docs": "compodoc src/", + "predocs-test": "npm run docs", + "docs-test": "linkinator docs", + "samples-test": "echo no sample tests!", + "system-test": "echo no system tests!", + "precompile": "gts clean" + }, + "files": [ + "build/src" + ], + "repository": "googleapis/teeny-request", + "keywords": [ + "request", + "node-fetch", + "fetch" + ], + "author": "fhinkel", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/googleapis/teeny-request/issues" + }, + "homepage": "https://github.com/googleapis/teeny-request#readme", + "dependencies": { + "http-proxy-agent": "^5.0.0", + "https-proxy-agent": "^5.0.0", + "node-fetch": "^2.6.9", + "stream-events": "^1.0.5", + "uuid": "^9.0.0" + }, + "devDependencies": { + "@babel/plugin-proposal-private-methods": "^7.18.6", + "@compodoc/compodoc": "^1.1.9", + "@types/mocha": "^10.0.0", + "@types/node-fetch": "^2.5.7", + "@types/sinon": "^10.0.0", + "@types/uuid": "^9.0.0", + "c8": "^8.0.0", + "codecov": "^3.1.0", + "gts": "^3.1.1", + "linkinator": "^4.0.0", + "mocha": "^10.0.0", + "nock": "^13.0.0", + "sinon": "^15.0.0", + "typescript": "^5.1.6" + }, + "nyc": { + "exclude": [ + "build/test" + ] + } +} diff --git a/node_modules/tr46/.npmignore b/node_modules/tr46/.npmignore new file mode 100644 index 0000000..96e9161 --- /dev/null +++ b/node_modules/tr46/.npmignore @@ -0,0 +1,4 @@ +scripts/ +test/ + +!lib/mapping_table.json diff --git a/node_modules/tr46/index.js b/node_modules/tr46/index.js new file mode 100644 index 0000000..9ce12ca --- /dev/null +++ b/node_modules/tr46/index.js @@ -0,0 +1,193 @@ +"use strict"; + +var punycode = require("punycode"); +var mappingTable = require("./lib/mappingTable.json"); + +var PROCESSING_OPTIONS = { + TRANSITIONAL: 0, + NONTRANSITIONAL: 1 +}; + +function normalize(str) { // fix bug in v8 + return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000'); +} + +function findStatus(val) { + var start = 0; + var end = mappingTable.length - 1; + + while (start <= end) { + var mid = Math.floor((start + end) / 2); + + var target = mappingTable[mid]; + if (target[0][0] <= val && target[0][1] >= val) { + return target; + } else if (target[0][0] > val) { + end = mid - 1; + } else { + start = mid + 1; + } + } + + return null; +} + +var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + +function countSymbols(string) { + return string + // replace every surrogate pair with a BMP symbol + .replace(regexAstralSymbols, '_') + // then get the length + .length; +} + +function mapChars(domain_name, useSTD3, processing_option) { + var hasError = false; + var processed = ""; + + var len = countSymbols(domain_name); + for (var i = 0; i < len; ++i) { + var codePoint = domain_name.codePointAt(i); + var status = findStatus(codePoint); + + switch (status[1]) { + case "disallowed": + hasError = true; + processed += String.fromCodePoint(codePoint); + break; + case "ignored": + break; + case "mapped": + processed += String.fromCodePoint.apply(String, status[2]); + break; + case "deviation": + if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) { + processed += String.fromCodePoint.apply(String, status[2]); + } else { + processed += String.fromCodePoint(codePoint); + } + break; + case "valid": + processed += String.fromCodePoint(codePoint); + break; + case "disallowed_STD3_mapped": + if (useSTD3) { + hasError = true; + processed += String.fromCodePoint(codePoint); + } else { + processed += String.fromCodePoint.apply(String, status[2]); + } + break; + case "disallowed_STD3_valid": + if (useSTD3) { + hasError = true; + } + + processed += String.fromCodePoint(codePoint); + break; + } + } + + return { + string: processed, + error: hasError + }; +} + +var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/; + +function validateLabel(label, processing_option) { + if (label.substr(0, 4) === "xn--") { + label = punycode.toUnicode(label); + processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL; + } + + var error = false; + + if (normalize(label) !== label || + (label[3] === "-" && label[4] === "-") || + label[0] === "-" || label[label.length - 1] === "-" || + label.indexOf(".") !== -1 || + label.search(combiningMarksRegex) === 0) { + error = true; + } + + var len = countSymbols(label); + for (var i = 0; i < len; ++i) { + var status = findStatus(label.codePointAt(i)); + if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") || + (processing === PROCESSING_OPTIONS.NONTRANSITIONAL && + status[1] !== "valid" && status[1] !== "deviation")) { + error = true; + break; + } + } + + return { + label: label, + error: error + }; +} + +function processing(domain_name, useSTD3, processing_option) { + var result = mapChars(domain_name, useSTD3, processing_option); + result.string = normalize(result.string); + + var labels = result.string.split("."); + for (var i = 0; i < labels.length; ++i) { + try { + var validation = validateLabel(labels[i]); + labels[i] = validation.label; + result.error = result.error || validation.error; + } catch(e) { + result.error = true; + } + } + + return { + string: labels.join("."), + error: result.error + }; +} + +module.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) { + var result = processing(domain_name, useSTD3, processing_option); + var labels = result.string.split("."); + labels = labels.map(function(l) { + try { + return punycode.toASCII(l); + } catch(e) { + result.error = true; + return l; + } + }); + + if (verifyDnsLength) { + var total = labels.slice(0, labels.length - 1).join(".").length; + if (total.length > 253 || total.length === 0) { + result.error = true; + } + + for (var i=0; i < labels.length; ++i) { + if (labels.length > 63 || labels.length === 0) { + result.error = true; + break; + } + } + } + + if (result.error) return null; + return labels.join("."); +}; + +module.exports.toUnicode = function(domain_name, useSTD3) { + var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL); + + return { + domain: result.string, + error: result.error + }; +}; + +module.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS; diff --git a/node_modules/tr46/lib/.gitkeep b/node_modules/tr46/lib/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/tr46/lib/mappingTable.json b/node_modules/tr46/lib/mappingTable.json new file mode 100644 index 0000000..89cf19a --- /dev/null +++ b/node_modules/tr46/lib/mappingTable.json @@ -0,0 +1 @@ +[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"],[[47,47],"disallowed_STD3_valid"],[[48,57],"valid"],[[58,64],"disallowed_STD3_valid"],[[65,65],"mapped",[97]],[[66,66],"mapped",[98]],[[67,67],"mapped",[99]],[[68,68],"mapped",[100]],[[69,69],"mapped",[101]],[[70,70],"mapped",[102]],[[71,71],"mapped",[103]],[[72,72],"mapped",[104]],[[73,73],"mapped",[105]],[[74,74],"mapped",[106]],[[75,75],"mapped",[107]],[[76,76],"mapped",[108]],[[77,77],"mapped",[109]],[[78,78],"mapped",[110]],[[79,79],"mapped",[111]],[[80,80],"mapped",[112]],[[81,81],"mapped",[113]],[[82,82],"mapped",[114]],[[83,83],"mapped",[115]],[[84,84],"mapped",[116]],[[85,85],"mapped",[117]],[[86,86],"mapped",[118]],[[87,87],"mapped",[119]],[[88,88],"mapped",[120]],[[89,89],"mapped",[121]],[[90,90],"mapped",[122]],[[91,96],"disallowed_STD3_valid"],[[97,122],"valid"],[[123,127],"disallowed_STD3_valid"],[[128,159],"disallowed"],[[160,160],"disallowed_STD3_mapped",[32]],[[161,167],"valid",[],"NV8"],[[168,168],"disallowed_STD3_mapped",[32,776]],[[169,169],"valid",[],"NV8"],[[170,170],"mapped",[97]],[[171,172],"valid",[],"NV8"],[[173,173],"ignored"],[[174,174],"valid",[],"NV8"],[[175,175],"disallowed_STD3_mapped",[32,772]],[[176,177],"valid",[],"NV8"],[[178,178],"mapped",[50]],[[179,179],"mapped",[51]],[[180,180],"disallowed_STD3_mapped",[32,769]],[[181,181],"mapped",[956]],[[182,182],"valid",[],"NV8"],[[183,183],"valid"],[[184,184],"disallowed_STD3_mapped",[32,807]],[[185,185],"mapped",[49]],[[186,186],"mapped",[111]],[[187,187],"valid",[],"NV8"],[[188,188],"mapped",[49,8260,52]],[[189,189],"mapped",[49,8260,50]],[[190,190],"mapped",[51,8260,52]],[[191,191],"valid",[],"NV8"],[[192,192],"mapped",[224]],[[193,193],"mapped",[225]],[[194,194],"mapped",[226]],[[195,195],"mapped",[227]],[[196,196],"mapped",[228]],[[197,197],"mapped",[229]],[[198,198],"mapped",[230]],[[199,199],"mapped",[231]],[[200,200],"mapped",[232]],[[201,201],"mapped",[233]],[[202,202],"mapped",[234]],[[203,203],"mapped",[235]],[[204,204],"mapped",[236]],[[205,205],"mapped",[237]],[[206,206],"mapped",[238]],[[207,207],"mapped",[239]],[[208,208],"mapped",[240]],[[209,209],"mapped",[241]],[[210,210],"mapped",[242]],[[211,211],"mapped",[243]],[[212,212],"mapped",[244]],[[213,213],"mapped",[245]],[[214,214],"mapped",[246]],[[215,215],"valid",[],"NV8"],[[216,216],"mapped",[248]],[[217,217],"mapped",[249]],[[218,218],"mapped",[250]],[[219,219],"mapped",[251]],[[220,220],"mapped",[252]],[[221,221],"mapped",[253]],[[222,222],"mapped",[254]],[[223,223],"deviation",[115,115]],[[224,246],"valid"],[[247,247],"valid",[],"NV8"],[[248,255],"valid"],[[256,256],"mapped",[257]],[[257,257],"valid"],[[258,258],"mapped",[259]],[[259,259],"valid"],[[260,260],"mapped",[261]],[[261,261],"valid"],[[262,262],"mapped",[263]],[[263,263],"valid"],[[264,264],"mapped",[265]],[[265,265],"valid"],[[266,266],"mapped",[267]],[[267,267],"valid"],[[268,268],"mapped",[269]],[[269,269],"valid"],[[270,270],"mapped",[271]],[[271,271],"valid"],[[272,272],"mapped",[273]],[[273,273],"valid"],[[274,274],"mapped",[275]],[[275,275],"valid"],[[276,276],"mapped",[277]],[[277,277],"valid"],[[278,278],"mapped",[279]],[[279,279],"valid"],[[280,280],"mapped",[281]],[[281,281],"valid"],[[282,282],"mapped",[283]],[[283,283],"valid"],[[284,284],"mapped",[285]],[[285,285],"valid"],[[286,286],"mapped",[287]],[[287,287],"valid"],[[288,288],"mapped",[289]],[[289,289],"valid"],[[290,290],"mapped",[291]],[[291,291],"valid"],[[292,292],"mapped",[293]],[[293,293],"valid"],[[294,294],"mapped",[295]],[[295,295],"valid"],[[296,296],"mapped",[297]],[[297,297],"valid"],[[298,298],"mapped",[299]],[[299,299],"valid"],[[300,300],"mapped",[301]],[[301,301],"valid"],[[302,302],"mapped",[303]],[[303,303],"valid"],[[304,304],"mapped",[105,775]],[[305,305],"valid"],[[306,307],"mapped",[105,106]],[[308,308],"mapped",[309]],[[309,309],"valid"],[[310,310],"mapped",[311]],[[311,312],"valid"],[[313,313],"mapped",[314]],[[314,314],"valid"],[[315,315],"mapped",[316]],[[316,316],"valid"],[[317,317],"mapped",[318]],[[318,318],"valid"],[[319,320],"mapped",[108,183]],[[321,321],"mapped",[322]],[[322,322],"valid"],[[323,323],"mapped",[324]],[[324,324],"valid"],[[325,325],"mapped",[326]],[[326,326],"valid"],[[327,327],"mapped",[328]],[[328,328],"valid"],[[329,329],"mapped",[700,110]],[[330,330],"mapped",[331]],[[331,331],"valid"],[[332,332],"mapped",[333]],[[333,333],"valid"],[[334,334],"mapped",[335]],[[335,335],"valid"],[[336,336],"mapped",[337]],[[337,337],"valid"],[[338,338],"mapped",[339]],[[339,339],"valid"],[[340,340],"mapped",[341]],[[341,341],"valid"],[[342,342],"mapped",[343]],[[343,343],"valid"],[[344,344],"mapped",[345]],[[345,345],"valid"],[[346,346],"mapped",[347]],[[347,347],"valid"],[[348,348],"mapped",[349]],[[349,349],"valid"],[[350,350],"mapped",[351]],[[351,351],"valid"],[[352,352],"mapped",[353]],[[353,353],"valid"],[[354,354],"mapped",[355]],[[355,355],"valid"],[[356,356],"mapped",[357]],[[357,357],"valid"],[[358,358],"mapped",[359]],[[359,359],"valid"],[[360,360],"mapped",[361]],[[361,361],"valid"],[[362,362],"mapped",[363]],[[363,363],"valid"],[[364,364],"mapped",[365]],[[365,365],"valid"],[[366,366],"mapped",[367]],[[367,367],"valid"],[[368,368],"mapped",[369]],[[369,369],"valid"],[[370,370],"mapped",[371]],[[371,371],"valid"],[[372,372],"mapped",[373]],[[373,373],"valid"],[[374,374],"mapped",[375]],[[375,375],"valid"],[[376,376],"mapped",[255]],[[377,377],"mapped",[378]],[[378,378],"valid"],[[379,379],"mapped",[380]],[[380,380],"valid"],[[381,381],"mapped",[382]],[[382,382],"valid"],[[383,383],"mapped",[115]],[[384,384],"valid"],[[385,385],"mapped",[595]],[[386,386],"mapped",[387]],[[387,387],"valid"],[[388,388],"mapped",[389]],[[389,389],"valid"],[[390,390],"mapped",[596]],[[391,391],"mapped",[392]],[[392,392],"valid"],[[393,393],"mapped",[598]],[[394,394],"mapped",[599]],[[395,395],"mapped",[396]],[[396,397],"valid"],[[398,398],"mapped",[477]],[[399,399],"mapped",[601]],[[400,400],"mapped",[603]],[[401,401],"mapped",[402]],[[402,402],"valid"],[[403,403],"mapped",[608]],[[404,404],"mapped",[611]],[[405,405],"valid"],[[406,406],"mapped",[617]],[[407,407],"mapped",[616]],[[408,408],"mapped",[409]],[[409,411],"valid"],[[412,412],"mapped",[623]],[[413,413],"mapped",[626]],[[414,414],"valid"],[[415,415],"mapped",[629]],[[416,416],"mapped",[417]],[[417,417],"valid"],[[418,418],"mapped",[419]],[[419,419],"valid"],[[420,420],"mapped",[421]],[[421,421],"valid"],[[422,422],"mapped",[640]],[[423,423],"mapped",[424]],[[424,424],"valid"],[[425,425],"mapped",[643]],[[426,427],"valid"],[[428,428],"mapped",[429]],[[429,429],"valid"],[[430,430],"mapped",[648]],[[431,431],"mapped",[432]],[[432,432],"valid"],[[433,433],"mapped",[650]],[[434,434],"mapped",[651]],[[435,435],"mapped",[436]],[[436,436],"valid"],[[437,437],"mapped",[438]],[[438,438],"valid"],[[439,439],"mapped",[658]],[[440,440],"mapped",[441]],[[441,443],"valid"],[[444,444],"mapped",[445]],[[445,451],"valid"],[[452,454],"mapped",[100,382]],[[455,457],"mapped",[108,106]],[[458,460],"mapped",[110,106]],[[461,461],"mapped",[462]],[[462,462],"valid"],[[463,463],"mapped",[464]],[[464,464],"valid"],[[465,465],"mapped",[466]],[[466,466],"valid"],[[467,467],"mapped",[468]],[[468,468],"valid"],[[469,469],"mapped",[470]],[[470,470],"valid"],[[471,471],"mapped",[472]],[[472,472],"valid"],[[473,473],"mapped",[474]],[[474,474],"valid"],[[475,475],"mapped",[476]],[[476,477],"valid"],[[478,478],"mapped",[479]],[[479,479],"valid"],[[480,480],"mapped",[481]],[[481,481],"valid"],[[482,482],"mapped",[483]],[[483,483],"valid"],[[484,484],"mapped",[485]],[[485,485],"valid"],[[486,486],"mapped",[487]],[[487,487],"valid"],[[488,488],"mapped",[489]],[[489,489],"valid"],[[490,490],"mapped",[491]],[[491,491],"valid"],[[492,492],"mapped",[493]],[[493,493],"valid"],[[494,494],"mapped",[495]],[[495,496],"valid"],[[497,499],"mapped",[100,122]],[[500,500],"mapped",[501]],[[501,501],"valid"],[[502,502],"mapped",[405]],[[503,503],"mapped",[447]],[[504,504],"mapped",[505]],[[505,505],"valid"],[[506,506],"mapped",[507]],[[507,507],"valid"],[[508,508],"mapped",[509]],[[509,509],"valid"],[[510,510],"mapped",[511]],[[511,511],"valid"],[[512,512],"mapped",[513]],[[513,513],"valid"],[[514,514],"mapped",[515]],[[515,515],"valid"],[[516,516],"mapped",[517]],[[517,517],"valid"],[[518,518],"mapped",[519]],[[519,519],"valid"],[[520,520],"mapped",[521]],[[521,521],"valid"],[[522,522],"mapped",[523]],[[523,523],"valid"],[[524,524],"mapped",[525]],[[525,525],"valid"],[[526,526],"mapped",[527]],[[527,527],"valid"],[[528,528],"mapped",[529]],[[529,529],"valid"],[[530,530],"mapped",[531]],[[531,531],"valid"],[[532,532],"mapped",[533]],[[533,533],"valid"],[[534,534],"mapped",[535]],[[535,535],"valid"],[[536,536],"mapped",[537]],[[537,537],"valid"],[[538,538],"mapped",[539]],[[539,539],"valid"],[[540,540],"mapped",[541]],[[541,541],"valid"],[[542,542],"mapped",[543]],[[543,543],"valid"],[[544,544],"mapped",[414]],[[545,545],"valid"],[[546,546],"mapped",[547]],[[547,547],"valid"],[[548,548],"mapped",[549]],[[549,549],"valid"],[[550,550],"mapped",[551]],[[551,551],"valid"],[[552,552],"mapped",[553]],[[553,553],"valid"],[[554,554],"mapped",[555]],[[555,555],"valid"],[[556,556],"mapped",[557]],[[557,557],"valid"],[[558,558],"mapped",[559]],[[559,559],"valid"],[[560,560],"mapped",[561]],[[561,561],"valid"],[[562,562],"mapped",[563]],[[563,563],"valid"],[[564,566],"valid"],[[567,569],"valid"],[[570,570],"mapped",[11365]],[[571,571],"mapped",[572]],[[572,572],"valid"],[[573,573],"mapped",[410]],[[574,574],"mapped",[11366]],[[575,576],"valid"],[[577,577],"mapped",[578]],[[578,578],"valid"],[[579,579],"mapped",[384]],[[580,580],"mapped",[649]],[[581,581],"mapped",[652]],[[582,582],"mapped",[583]],[[583,583],"valid"],[[584,584],"mapped",[585]],[[585,585],"valid"],[[586,586],"mapped",[587]],[[587,587],"valid"],[[588,588],"mapped",[589]],[[589,589],"valid"],[[590,590],"mapped",[591]],[[591,591],"valid"],[[592,680],"valid"],[[681,685],"valid"],[[686,687],"valid"],[[688,688],"mapped",[104]],[[689,689],"mapped",[614]],[[690,690],"mapped",[106]],[[691,691],"mapped",[114]],[[692,692],"mapped",[633]],[[693,693],"mapped",[635]],[[694,694],"mapped",[641]],[[695,695],"mapped",[119]],[[696,696],"mapped",[121]],[[697,705],"valid"],[[706,709],"valid",[],"NV8"],[[710,721],"valid"],[[722,727],"valid",[],"NV8"],[[728,728],"disallowed_STD3_mapped",[32,774]],[[729,729],"disallowed_STD3_mapped",[32,775]],[[730,730],"disallowed_STD3_mapped",[32,778]],[[731,731],"disallowed_STD3_mapped",[32,808]],[[732,732],"disallowed_STD3_mapped",[32,771]],[[733,733],"disallowed_STD3_mapped",[32,779]],[[734,734],"valid",[],"NV8"],[[735,735],"valid",[],"NV8"],[[736,736],"mapped",[611]],[[737,737],"mapped",[108]],[[738,738],"mapped",[115]],[[739,739],"mapped",[120]],[[740,740],"mapped",[661]],[[741,745],"valid",[],"NV8"],[[746,747],"valid",[],"NV8"],[[748,748],"valid"],[[749,749],"valid",[],"NV8"],[[750,750],"valid"],[[751,767],"valid",[],"NV8"],[[768,831],"valid"],[[832,832],"mapped",[768]],[[833,833],"mapped",[769]],[[834,834],"valid"],[[835,835],"mapped",[787]],[[836,836],"mapped",[776,769]],[[837,837],"mapped",[953]],[[838,846],"valid"],[[847,847],"ignored"],[[848,855],"valid"],[[856,860],"valid"],[[861,863],"valid"],[[864,865],"valid"],[[866,866],"valid"],[[867,879],"valid"],[[880,880],"mapped",[881]],[[881,881],"valid"],[[882,882],"mapped",[883]],[[883,883],"valid"],[[884,884],"mapped",[697]],[[885,885],"valid"],[[886,886],"mapped",[887]],[[887,887],"valid"],[[888,889],"disallowed"],[[890,890],"disallowed_STD3_mapped",[32,953]],[[891,893],"valid"],[[894,894],"disallowed_STD3_mapped",[59]],[[895,895],"mapped",[1011]],[[896,899],"disallowed"],[[900,900],"disallowed_STD3_mapped",[32,769]],[[901,901],"disallowed_STD3_mapped",[32,776,769]],[[902,902],"mapped",[940]],[[903,903],"mapped",[183]],[[904,904],"mapped",[941]],[[905,905],"mapped",[942]],[[906,906],"mapped",[943]],[[907,907],"disallowed"],[[908,908],"mapped",[972]],[[909,909],"disallowed"],[[910,910],"mapped",[973]],[[911,911],"mapped",[974]],[[912,912],"valid"],[[913,913],"mapped",[945]],[[914,914],"mapped",[946]],[[915,915],"mapped",[947]],[[916,916],"mapped",[948]],[[917,917],"mapped",[949]],[[918,918],"mapped",[950]],[[919,919],"mapped",[951]],[[920,920],"mapped",[952]],[[921,921],"mapped",[953]],[[922,922],"mapped",[954]],[[923,923],"mapped",[955]],[[924,924],"mapped",[956]],[[925,925],"mapped",[957]],[[926,926],"mapped",[958]],[[927,927],"mapped",[959]],[[928,928],"mapped",[960]],[[929,929],"mapped",[961]],[[930,930],"disallowed"],[[931,931],"mapped",[963]],[[932,932],"mapped",[964]],[[933,933],"mapped",[965]],[[934,934],"mapped",[966]],[[935,935],"mapped",[967]],[[936,936],"mapped",[968]],[[937,937],"mapped",[969]],[[938,938],"mapped",[970]],[[939,939],"mapped",[971]],[[940,961],"valid"],[[962,962],"deviation",[963]],[[963,974],"valid"],[[975,975],"mapped",[983]],[[976,976],"mapped",[946]],[[977,977],"mapped",[952]],[[978,978],"mapped",[965]],[[979,979],"mapped",[973]],[[980,980],"mapped",[971]],[[981,981],"mapped",[966]],[[982,982],"mapped",[960]],[[983,983],"valid"],[[984,984],"mapped",[985]],[[985,985],"valid"],[[986,986],"mapped",[987]],[[987,987],"valid"],[[988,988],"mapped",[989]],[[989,989],"valid"],[[990,990],"mapped",[991]],[[991,991],"valid"],[[992,992],"mapped",[993]],[[993,993],"valid"],[[994,994],"mapped",[995]],[[995,995],"valid"],[[996,996],"mapped",[997]],[[997,997],"valid"],[[998,998],"mapped",[999]],[[999,999],"valid"],[[1000,1000],"mapped",[1001]],[[1001,1001],"valid"],[[1002,1002],"mapped",[1003]],[[1003,1003],"valid"],[[1004,1004],"mapped",[1005]],[[1005,1005],"valid"],[[1006,1006],"mapped",[1007]],[[1007,1007],"valid"],[[1008,1008],"mapped",[954]],[[1009,1009],"mapped",[961]],[[1010,1010],"mapped",[963]],[[1011,1011],"valid"],[[1012,1012],"mapped",[952]],[[1013,1013],"mapped",[949]],[[1014,1014],"valid",[],"NV8"],[[1015,1015],"mapped",[1016]],[[1016,1016],"valid"],[[1017,1017],"mapped",[963]],[[1018,1018],"mapped",[1019]],[[1019,1019],"valid"],[[1020,1020],"valid"],[[1021,1021],"mapped",[891]],[[1022,1022],"mapped",[892]],[[1023,1023],"mapped",[893]],[[1024,1024],"mapped",[1104]],[[1025,1025],"mapped",[1105]],[[1026,1026],"mapped",[1106]],[[1027,1027],"mapped",[1107]],[[1028,1028],"mapped",[1108]],[[1029,1029],"mapped",[1109]],[[1030,1030],"mapped",[1110]],[[1031,1031],"mapped",[1111]],[[1032,1032],"mapped",[1112]],[[1033,1033],"mapped",[1113]],[[1034,1034],"mapped",[1114]],[[1035,1035],"mapped",[1115]],[[1036,1036],"mapped",[1116]],[[1037,1037],"mapped",[1117]],[[1038,1038],"mapped",[1118]],[[1039,1039],"mapped",[1119]],[[1040,1040],"mapped",[1072]],[[1041,1041],"mapped",[1073]],[[1042,1042],"mapped",[1074]],[[1043,1043],"mapped",[1075]],[[1044,1044],"mapped",[1076]],[[1045,1045],"mapped",[1077]],[[1046,1046],"mapped",[1078]],[[1047,1047],"mapped",[1079]],[[1048,1048],"mapped",[1080]],[[1049,1049],"mapped",[1081]],[[1050,1050],"mapped",[1082]],[[1051,1051],"mapped",[1083]],[[1052,1052],"mapped",[1084]],[[1053,1053],"mapped",[1085]],[[1054,1054],"mapped",[1086]],[[1055,1055],"mapped",[1087]],[[1056,1056],"mapped",[1088]],[[1057,1057],"mapped",[1089]],[[1058,1058],"mapped",[1090]],[[1059,1059],"mapped",[1091]],[[1060,1060],"mapped",[1092]],[[1061,1061],"mapped",[1093]],[[1062,1062],"mapped",[1094]],[[1063,1063],"mapped",[1095]],[[1064,1064],"mapped",[1096]],[[1065,1065],"mapped",[1097]],[[1066,1066],"mapped",[1098]],[[1067,1067],"mapped",[1099]],[[1068,1068],"mapped",[1100]],[[1069,1069],"mapped",[1101]],[[1070,1070],"mapped",[1102]],[[1071,1071],"mapped",[1103]],[[1072,1103],"valid"],[[1104,1104],"valid"],[[1105,1116],"valid"],[[1117,1117],"valid"],[[1118,1119],"valid"],[[1120,1120],"mapped",[1121]],[[1121,1121],"valid"],[[1122,1122],"mapped",[1123]],[[1123,1123],"valid"],[[1124,1124],"mapped",[1125]],[[1125,1125],"valid"],[[1126,1126],"mapped",[1127]],[[1127,1127],"valid"],[[1128,1128],"mapped",[1129]],[[1129,1129],"valid"],[[1130,1130],"mapped",[1131]],[[1131,1131],"valid"],[[1132,1132],"mapped",[1133]],[[1133,1133],"valid"],[[1134,1134],"mapped",[1135]],[[1135,1135],"valid"],[[1136,1136],"mapped",[1137]],[[1137,1137],"valid"],[[1138,1138],"mapped",[1139]],[[1139,1139],"valid"],[[1140,1140],"mapped",[1141]],[[1141,1141],"valid"],[[1142,1142],"mapped",[1143]],[[1143,1143],"valid"],[[1144,1144],"mapped",[1145]],[[1145,1145],"valid"],[[1146,1146],"mapped",[1147]],[[1147,1147],"valid"],[[1148,1148],"mapped",[1149]],[[1149,1149],"valid"],[[1150,1150],"mapped",[1151]],[[1151,1151],"valid"],[[1152,1152],"mapped",[1153]],[[1153,1153],"valid"],[[1154,1154],"valid",[],"NV8"],[[1155,1158],"valid"],[[1159,1159],"valid"],[[1160,1161],"valid",[],"NV8"],[[1162,1162],"mapped",[1163]],[[1163,1163],"valid"],[[1164,1164],"mapped",[1165]],[[1165,1165],"valid"],[[1166,1166],"mapped",[1167]],[[1167,1167],"valid"],[[1168,1168],"mapped",[1169]],[[1169,1169],"valid"],[[1170,1170],"mapped",[1171]],[[1171,1171],"valid"],[[1172,1172],"mapped",[1173]],[[1173,1173],"valid"],[[1174,1174],"mapped",[1175]],[[1175,1175],"valid"],[[1176,1176],"mapped",[1177]],[[1177,1177],"valid"],[[1178,1178],"mapped",[1179]],[[1179,1179],"valid"],[[1180,1180],"mapped",[1181]],[[1181,1181],"valid"],[[1182,1182],"mapped",[1183]],[[1183,1183],"valid"],[[1184,1184],"mapped",[1185]],[[1185,1185],"valid"],[[1186,1186],"mapped",[1187]],[[1187,1187],"valid"],[[1188,1188],"mapped",[1189]],[[1189,1189],"valid"],[[1190,1190],"mapped",[1191]],[[1191,1191],"valid"],[[1192,1192],"mapped",[1193]],[[1193,1193],"valid"],[[1194,1194],"mapped",[1195]],[[1195,1195],"valid"],[[1196,1196],"mapped",[1197]],[[1197,1197],"valid"],[[1198,1198],"mapped",[1199]],[[1199,1199],"valid"],[[1200,1200],"mapped",[1201]],[[1201,1201],"valid"],[[1202,1202],"mapped",[1203]],[[1203,1203],"valid"],[[1204,1204],"mapped",[1205]],[[1205,1205],"valid"],[[1206,1206],"mapped",[1207]],[[1207,1207],"valid"],[[1208,1208],"mapped",[1209]],[[1209,1209],"valid"],[[1210,1210],"mapped",[1211]],[[1211,1211],"valid"],[[1212,1212],"mapped",[1213]],[[1213,1213],"valid"],[[1214,1214],"mapped",[1215]],[[1215,1215],"valid"],[[1216,1216],"disallowed"],[[1217,1217],"mapped",[1218]],[[1218,1218],"valid"],[[1219,1219],"mapped",[1220]],[[1220,1220],"valid"],[[1221,1221],"mapped",[1222]],[[1222,1222],"valid"],[[1223,1223],"mapped",[1224]],[[1224,1224],"valid"],[[1225,1225],"mapped",[1226]],[[1226,1226],"valid"],[[1227,1227],"mapped",[1228]],[[1228,1228],"valid"],[[1229,1229],"mapped",[1230]],[[1230,1230],"valid"],[[1231,1231],"valid"],[[1232,1232],"mapped",[1233]],[[1233,1233],"valid"],[[1234,1234],"mapped",[1235]],[[1235,1235],"valid"],[[1236,1236],"mapped",[1237]],[[1237,1237],"valid"],[[1238,1238],"mapped",[1239]],[[1239,1239],"valid"],[[1240,1240],"mapped",[1241]],[[1241,1241],"valid"],[[1242,1242],"mapped",[1243]],[[1243,1243],"valid"],[[1244,1244],"mapped",[1245]],[[1245,1245],"valid"],[[1246,1246],"mapped",[1247]],[[1247,1247],"valid"],[[1248,1248],"mapped",[1249]],[[1249,1249],"valid"],[[1250,1250],"mapped",[1251]],[[1251,1251],"valid"],[[1252,1252],"mapped",[1253]],[[1253,1253],"valid"],[[1254,1254],"mapped",[1255]],[[1255,1255],"valid"],[[1256,1256],"mapped",[1257]],[[1257,1257],"valid"],[[1258,1258],"mapped",[1259]],[[1259,1259],"valid"],[[1260,1260],"mapped",[1261]],[[1261,1261],"valid"],[[1262,1262],"mapped",[1263]],[[1263,1263],"valid"],[[1264,1264],"mapped",[1265]],[[1265,1265],"valid"],[[1266,1266],"mapped",[1267]],[[1267,1267],"valid"],[[1268,1268],"mapped",[1269]],[[1269,1269],"valid"],[[1270,1270],"mapped",[1271]],[[1271,1271],"valid"],[[1272,1272],"mapped",[1273]],[[1273,1273],"valid"],[[1274,1274],"mapped",[1275]],[[1275,1275],"valid"],[[1276,1276],"mapped",[1277]],[[1277,1277],"valid"],[[1278,1278],"mapped",[1279]],[[1279,1279],"valid"],[[1280,1280],"mapped",[1281]],[[1281,1281],"valid"],[[1282,1282],"mapped",[1283]],[[1283,1283],"valid"],[[1284,1284],"mapped",[1285]],[[1285,1285],"valid"],[[1286,1286],"mapped",[1287]],[[1287,1287],"valid"],[[1288,1288],"mapped",[1289]],[[1289,1289],"valid"],[[1290,1290],"mapped",[1291]],[[1291,1291],"valid"],[[1292,1292],"mapped",[1293]],[[1293,1293],"valid"],[[1294,1294],"mapped",[1295]],[[1295,1295],"valid"],[[1296,1296],"mapped",[1297]],[[1297,1297],"valid"],[[1298,1298],"mapped",[1299]],[[1299,1299],"valid"],[[1300,1300],"mapped",[1301]],[[1301,1301],"valid"],[[1302,1302],"mapped",[1303]],[[1303,1303],"valid"],[[1304,1304],"mapped",[1305]],[[1305,1305],"valid"],[[1306,1306],"mapped",[1307]],[[1307,1307],"valid"],[[1308,1308],"mapped",[1309]],[[1309,1309],"valid"],[[1310,1310],"mapped",[1311]],[[1311,1311],"valid"],[[1312,1312],"mapped",[1313]],[[1313,1313],"valid"],[[1314,1314],"mapped",[1315]],[[1315,1315],"valid"],[[1316,1316],"mapped",[1317]],[[1317,1317],"valid"],[[1318,1318],"mapped",[1319]],[[1319,1319],"valid"],[[1320,1320],"mapped",[1321]],[[1321,1321],"valid"],[[1322,1322],"mapped",[1323]],[[1323,1323],"valid"],[[1324,1324],"mapped",[1325]],[[1325,1325],"valid"],[[1326,1326],"mapped",[1327]],[[1327,1327],"valid"],[[1328,1328],"disallowed"],[[1329,1329],"mapped",[1377]],[[1330,1330],"mapped",[1378]],[[1331,1331],"mapped",[1379]],[[1332,1332],"mapped",[1380]],[[1333,1333],"mapped",[1381]],[[1334,1334],"mapped",[1382]],[[1335,1335],"mapped",[1383]],[[1336,1336],"mapped",[1384]],[[1337,1337],"mapped",[1385]],[[1338,1338],"mapped",[1386]],[[1339,1339],"mapped",[1387]],[[1340,1340],"mapped",[1388]],[[1341,1341],"mapped",[1389]],[[1342,1342],"mapped",[1390]],[[1343,1343],"mapped",[1391]],[[1344,1344],"mapped",[1392]],[[1345,1345],"mapped",[1393]],[[1346,1346],"mapped",[1394]],[[1347,1347],"mapped",[1395]],[[1348,1348],"mapped",[1396]],[[1349,1349],"mapped",[1397]],[[1350,1350],"mapped",[1398]],[[1351,1351],"mapped",[1399]],[[1352,1352],"mapped",[1400]],[[1353,1353],"mapped",[1401]],[[1354,1354],"mapped",[1402]],[[1355,1355],"mapped",[1403]],[[1356,1356],"mapped",[1404]],[[1357,1357],"mapped",[1405]],[[1358,1358],"mapped",[1406]],[[1359,1359],"mapped",[1407]],[[1360,1360],"mapped",[1408]],[[1361,1361],"mapped",[1409]],[[1362,1362],"mapped",[1410]],[[1363,1363],"mapped",[1411]],[[1364,1364],"mapped",[1412]],[[1365,1365],"mapped",[1413]],[[1366,1366],"mapped",[1414]],[[1367,1368],"disallowed"],[[1369,1369],"valid"],[[1370,1375],"valid",[],"NV8"],[[1376,1376],"disallowed"],[[1377,1414],"valid"],[[1415,1415],"mapped",[1381,1410]],[[1416,1416],"disallowed"],[[1417,1417],"valid",[],"NV8"],[[1418,1418],"valid",[],"NV8"],[[1419,1420],"disallowed"],[[1421,1422],"valid",[],"NV8"],[[1423,1423],"valid",[],"NV8"],[[1424,1424],"disallowed"],[[1425,1441],"valid"],[[1442,1442],"valid"],[[1443,1455],"valid"],[[1456,1465],"valid"],[[1466,1466],"valid"],[[1467,1469],"valid"],[[1470,1470],"valid",[],"NV8"],[[1471,1471],"valid"],[[1472,1472],"valid",[],"NV8"],[[1473,1474],"valid"],[[1475,1475],"valid",[],"NV8"],[[1476,1476],"valid"],[[1477,1477],"valid"],[[1478,1478],"valid",[],"NV8"],[[1479,1479],"valid"],[[1480,1487],"disallowed"],[[1488,1514],"valid"],[[1515,1519],"disallowed"],[[1520,1524],"valid"],[[1525,1535],"disallowed"],[[1536,1539],"disallowed"],[[1540,1540],"disallowed"],[[1541,1541],"disallowed"],[[1542,1546],"valid",[],"NV8"],[[1547,1547],"valid",[],"NV8"],[[1548,1548],"valid",[],"NV8"],[[1549,1551],"valid",[],"NV8"],[[1552,1557],"valid"],[[1558,1562],"valid"],[[1563,1563],"valid",[],"NV8"],[[1564,1564],"disallowed"],[[1565,1565],"disallowed"],[[1566,1566],"valid",[],"NV8"],[[1567,1567],"valid",[],"NV8"],[[1568,1568],"valid"],[[1569,1594],"valid"],[[1595,1599],"valid"],[[1600,1600],"valid",[],"NV8"],[[1601,1618],"valid"],[[1619,1621],"valid"],[[1622,1624],"valid"],[[1625,1630],"valid"],[[1631,1631],"valid"],[[1632,1641],"valid"],[[1642,1645],"valid",[],"NV8"],[[1646,1647],"valid"],[[1648,1652],"valid"],[[1653,1653],"mapped",[1575,1652]],[[1654,1654],"mapped",[1608,1652]],[[1655,1655],"mapped",[1735,1652]],[[1656,1656],"mapped",[1610,1652]],[[1657,1719],"valid"],[[1720,1721],"valid"],[[1722,1726],"valid"],[[1727,1727],"valid"],[[1728,1742],"valid"],[[1743,1743],"valid"],[[1744,1747],"valid"],[[1748,1748],"valid",[],"NV8"],[[1749,1756],"valid"],[[1757,1757],"disallowed"],[[1758,1758],"valid",[],"NV8"],[[1759,1768],"valid"],[[1769,1769],"valid",[],"NV8"],[[1770,1773],"valid"],[[1774,1775],"valid"],[[1776,1785],"valid"],[[1786,1790],"valid"],[[1791,1791],"valid"],[[1792,1805],"valid",[],"NV8"],[[1806,1806],"disallowed"],[[1807,1807],"disallowed"],[[1808,1836],"valid"],[[1837,1839],"valid"],[[1840,1866],"valid"],[[1867,1868],"disallowed"],[[1869,1871],"valid"],[[1872,1901],"valid"],[[1902,1919],"valid"],[[1920,1968],"valid"],[[1969,1969],"valid"],[[1970,1983],"disallowed"],[[1984,2037],"valid"],[[2038,2042],"valid",[],"NV8"],[[2043,2047],"disallowed"],[[2048,2093],"valid"],[[2094,2095],"disallowed"],[[2096,2110],"valid",[],"NV8"],[[2111,2111],"disallowed"],[[2112,2139],"valid"],[[2140,2141],"disallowed"],[[2142,2142],"valid",[],"NV8"],[[2143,2207],"disallowed"],[[2208,2208],"valid"],[[2209,2209],"valid"],[[2210,2220],"valid"],[[2221,2226],"valid"],[[2227,2228],"valid"],[[2229,2274],"disallowed"],[[2275,2275],"valid"],[[2276,2302],"valid"],[[2303,2303],"valid"],[[2304,2304],"valid"],[[2305,2307],"valid"],[[2308,2308],"valid"],[[2309,2361],"valid"],[[2362,2363],"valid"],[[2364,2381],"valid"],[[2382,2382],"valid"],[[2383,2383],"valid"],[[2384,2388],"valid"],[[2389,2389],"valid"],[[2390,2391],"valid"],[[2392,2392],"mapped",[2325,2364]],[[2393,2393],"mapped",[2326,2364]],[[2394,2394],"mapped",[2327,2364]],[[2395,2395],"mapped",[2332,2364]],[[2396,2396],"mapped",[2337,2364]],[[2397,2397],"mapped",[2338,2364]],[[2398,2398],"mapped",[2347,2364]],[[2399,2399],"mapped",[2351,2364]],[[2400,2403],"valid"],[[2404,2405],"valid",[],"NV8"],[[2406,2415],"valid"],[[2416,2416],"valid",[],"NV8"],[[2417,2418],"valid"],[[2419,2423],"valid"],[[2424,2424],"valid"],[[2425,2426],"valid"],[[2427,2428],"valid"],[[2429,2429],"valid"],[[2430,2431],"valid"],[[2432,2432],"valid"],[[2433,2435],"valid"],[[2436,2436],"disallowed"],[[2437,2444],"valid"],[[2445,2446],"disallowed"],[[2447,2448],"valid"],[[2449,2450],"disallowed"],[[2451,2472],"valid"],[[2473,2473],"disallowed"],[[2474,2480],"valid"],[[2481,2481],"disallowed"],[[2482,2482],"valid"],[[2483,2485],"disallowed"],[[2486,2489],"valid"],[[2490,2491],"disallowed"],[[2492,2492],"valid"],[[2493,2493],"valid"],[[2494,2500],"valid"],[[2501,2502],"disallowed"],[[2503,2504],"valid"],[[2505,2506],"disallowed"],[[2507,2509],"valid"],[[2510,2510],"valid"],[[2511,2518],"disallowed"],[[2519,2519],"valid"],[[2520,2523],"disallowed"],[[2524,2524],"mapped",[2465,2492]],[[2525,2525],"mapped",[2466,2492]],[[2526,2526],"disallowed"],[[2527,2527],"mapped",[2479,2492]],[[2528,2531],"valid"],[[2532,2533],"disallowed"],[[2534,2545],"valid"],[[2546,2554],"valid",[],"NV8"],[[2555,2555],"valid",[],"NV8"],[[2556,2560],"disallowed"],[[2561,2561],"valid"],[[2562,2562],"valid"],[[2563,2563],"valid"],[[2564,2564],"disallowed"],[[2565,2570],"valid"],[[2571,2574],"disallowed"],[[2575,2576],"valid"],[[2577,2578],"disallowed"],[[2579,2600],"valid"],[[2601,2601],"disallowed"],[[2602,2608],"valid"],[[2609,2609],"disallowed"],[[2610,2610],"valid"],[[2611,2611],"mapped",[2610,2620]],[[2612,2612],"disallowed"],[[2613,2613],"valid"],[[2614,2614],"mapped",[2616,2620]],[[2615,2615],"disallowed"],[[2616,2617],"valid"],[[2618,2619],"disallowed"],[[2620,2620],"valid"],[[2621,2621],"disallowed"],[[2622,2626],"valid"],[[2627,2630],"disallowed"],[[2631,2632],"valid"],[[2633,2634],"disallowed"],[[2635,2637],"valid"],[[2638,2640],"disallowed"],[[2641,2641],"valid"],[[2642,2648],"disallowed"],[[2649,2649],"mapped",[2582,2620]],[[2650,2650],"mapped",[2583,2620]],[[2651,2651],"mapped",[2588,2620]],[[2652,2652],"valid"],[[2653,2653],"disallowed"],[[2654,2654],"mapped",[2603,2620]],[[2655,2661],"disallowed"],[[2662,2676],"valid"],[[2677,2677],"valid"],[[2678,2688],"disallowed"],[[2689,2691],"valid"],[[2692,2692],"disallowed"],[[2693,2699],"valid"],[[2700,2700],"valid"],[[2701,2701],"valid"],[[2702,2702],"disallowed"],[[2703,2705],"valid"],[[2706,2706],"disallowed"],[[2707,2728],"valid"],[[2729,2729],"disallowed"],[[2730,2736],"valid"],[[2737,2737],"disallowed"],[[2738,2739],"valid"],[[2740,2740],"disallowed"],[[2741,2745],"valid"],[[2746,2747],"disallowed"],[[2748,2757],"valid"],[[2758,2758],"disallowed"],[[2759,2761],"valid"],[[2762,2762],"disallowed"],[[2763,2765],"valid"],[[2766,2767],"disallowed"],[[2768,2768],"valid"],[[2769,2783],"disallowed"],[[2784,2784],"valid"],[[2785,2787],"valid"],[[2788,2789],"disallowed"],[[2790,2799],"valid"],[[2800,2800],"valid",[],"NV8"],[[2801,2801],"valid",[],"NV8"],[[2802,2808],"disallowed"],[[2809,2809],"valid"],[[2810,2816],"disallowed"],[[2817,2819],"valid"],[[2820,2820],"disallowed"],[[2821,2828],"valid"],[[2829,2830],"disallowed"],[[2831,2832],"valid"],[[2833,2834],"disallowed"],[[2835,2856],"valid"],[[2857,2857],"disallowed"],[[2858,2864],"valid"],[[2865,2865],"disallowed"],[[2866,2867],"valid"],[[2868,2868],"disallowed"],[[2869,2869],"valid"],[[2870,2873],"valid"],[[2874,2875],"disallowed"],[[2876,2883],"valid"],[[2884,2884],"valid"],[[2885,2886],"disallowed"],[[2887,2888],"valid"],[[2889,2890],"disallowed"],[[2891,2893],"valid"],[[2894,2901],"disallowed"],[[2902,2903],"valid"],[[2904,2907],"disallowed"],[[2908,2908],"mapped",[2849,2876]],[[2909,2909],"mapped",[2850,2876]],[[2910,2910],"disallowed"],[[2911,2913],"valid"],[[2914,2915],"valid"],[[2916,2917],"disallowed"],[[2918,2927],"valid"],[[2928,2928],"valid",[],"NV8"],[[2929,2929],"valid"],[[2930,2935],"valid",[],"NV8"],[[2936,2945],"disallowed"],[[2946,2947],"valid"],[[2948,2948],"disallowed"],[[2949,2954],"valid"],[[2955,2957],"disallowed"],[[2958,2960],"valid"],[[2961,2961],"disallowed"],[[2962,2965],"valid"],[[2966,2968],"disallowed"],[[2969,2970],"valid"],[[2971,2971],"disallowed"],[[2972,2972],"valid"],[[2973,2973],"disallowed"],[[2974,2975],"valid"],[[2976,2978],"disallowed"],[[2979,2980],"valid"],[[2981,2983],"disallowed"],[[2984,2986],"valid"],[[2987,2989],"disallowed"],[[2990,2997],"valid"],[[2998,2998],"valid"],[[2999,3001],"valid"],[[3002,3005],"disallowed"],[[3006,3010],"valid"],[[3011,3013],"disallowed"],[[3014,3016],"valid"],[[3017,3017],"disallowed"],[[3018,3021],"valid"],[[3022,3023],"disallowed"],[[3024,3024],"valid"],[[3025,3030],"disallowed"],[[3031,3031],"valid"],[[3032,3045],"disallowed"],[[3046,3046],"valid"],[[3047,3055],"valid"],[[3056,3058],"valid",[],"NV8"],[[3059,3066],"valid",[],"NV8"],[[3067,3071],"disallowed"],[[3072,3072],"valid"],[[3073,3075],"valid"],[[3076,3076],"disallowed"],[[3077,3084],"valid"],[[3085,3085],"disallowed"],[[3086,3088],"valid"],[[3089,3089],"disallowed"],[[3090,3112],"valid"],[[3113,3113],"disallowed"],[[3114,3123],"valid"],[[3124,3124],"valid"],[[3125,3129],"valid"],[[3130,3132],"disallowed"],[[3133,3133],"valid"],[[3134,3140],"valid"],[[3141,3141],"disallowed"],[[3142,3144],"valid"],[[3145,3145],"disallowed"],[[3146,3149],"valid"],[[3150,3156],"disallowed"],[[3157,3158],"valid"],[[3159,3159],"disallowed"],[[3160,3161],"valid"],[[3162,3162],"valid"],[[3163,3167],"disallowed"],[[3168,3169],"valid"],[[3170,3171],"valid"],[[3172,3173],"disallowed"],[[3174,3183],"valid"],[[3184,3191],"disallowed"],[[3192,3199],"valid",[],"NV8"],[[3200,3200],"disallowed"],[[3201,3201],"valid"],[[3202,3203],"valid"],[[3204,3204],"disallowed"],[[3205,3212],"valid"],[[3213,3213],"disallowed"],[[3214,3216],"valid"],[[3217,3217],"disallowed"],[[3218,3240],"valid"],[[3241,3241],"disallowed"],[[3242,3251],"valid"],[[3252,3252],"disallowed"],[[3253,3257],"valid"],[[3258,3259],"disallowed"],[[3260,3261],"valid"],[[3262,3268],"valid"],[[3269,3269],"disallowed"],[[3270,3272],"valid"],[[3273,3273],"disallowed"],[[3274,3277],"valid"],[[3278,3284],"disallowed"],[[3285,3286],"valid"],[[3287,3293],"disallowed"],[[3294,3294],"valid"],[[3295,3295],"disallowed"],[[3296,3297],"valid"],[[3298,3299],"valid"],[[3300,3301],"disallowed"],[[3302,3311],"valid"],[[3312,3312],"disallowed"],[[3313,3314],"valid"],[[3315,3328],"disallowed"],[[3329,3329],"valid"],[[3330,3331],"valid"],[[3332,3332],"disallowed"],[[3333,3340],"valid"],[[3341,3341],"disallowed"],[[3342,3344],"valid"],[[3345,3345],"disallowed"],[[3346,3368],"valid"],[[3369,3369],"valid"],[[3370,3385],"valid"],[[3386,3386],"valid"],[[3387,3388],"disallowed"],[[3389,3389],"valid"],[[3390,3395],"valid"],[[3396,3396],"valid"],[[3397,3397],"disallowed"],[[3398,3400],"valid"],[[3401,3401],"disallowed"],[[3402,3405],"valid"],[[3406,3406],"valid"],[[3407,3414],"disallowed"],[[3415,3415],"valid"],[[3416,3422],"disallowed"],[[3423,3423],"valid"],[[3424,3425],"valid"],[[3426,3427],"valid"],[[3428,3429],"disallowed"],[[3430,3439],"valid"],[[3440,3445],"valid",[],"NV8"],[[3446,3448],"disallowed"],[[3449,3449],"valid",[],"NV8"],[[3450,3455],"valid"],[[3456,3457],"disallowed"],[[3458,3459],"valid"],[[3460,3460],"disallowed"],[[3461,3478],"valid"],[[3479,3481],"disallowed"],[[3482,3505],"valid"],[[3506,3506],"disallowed"],[[3507,3515],"valid"],[[3516,3516],"disallowed"],[[3517,3517],"valid"],[[3518,3519],"disallowed"],[[3520,3526],"valid"],[[3527,3529],"disallowed"],[[3530,3530],"valid"],[[3531,3534],"disallowed"],[[3535,3540],"valid"],[[3541,3541],"disallowed"],[[3542,3542],"valid"],[[3543,3543],"disallowed"],[[3544,3551],"valid"],[[3552,3557],"disallowed"],[[3558,3567],"valid"],[[3568,3569],"disallowed"],[[3570,3571],"valid"],[[3572,3572],"valid",[],"NV8"],[[3573,3584],"disallowed"],[[3585,3634],"valid"],[[3635,3635],"mapped",[3661,3634]],[[3636,3642],"valid"],[[3643,3646],"disallowed"],[[3647,3647],"valid",[],"NV8"],[[3648,3662],"valid"],[[3663,3663],"valid",[],"NV8"],[[3664,3673],"valid"],[[3674,3675],"valid",[],"NV8"],[[3676,3712],"disallowed"],[[3713,3714],"valid"],[[3715,3715],"disallowed"],[[3716,3716],"valid"],[[3717,3718],"disallowed"],[[3719,3720],"valid"],[[3721,3721],"disallowed"],[[3722,3722],"valid"],[[3723,3724],"disallowed"],[[3725,3725],"valid"],[[3726,3731],"disallowed"],[[3732,3735],"valid"],[[3736,3736],"disallowed"],[[3737,3743],"valid"],[[3744,3744],"disallowed"],[[3745,3747],"valid"],[[3748,3748],"disallowed"],[[3749,3749],"valid"],[[3750,3750],"disallowed"],[[3751,3751],"valid"],[[3752,3753],"disallowed"],[[3754,3755],"valid"],[[3756,3756],"disallowed"],[[3757,3762],"valid"],[[3763,3763],"mapped",[3789,3762]],[[3764,3769],"valid"],[[3770,3770],"disallowed"],[[3771,3773],"valid"],[[3774,3775],"disallowed"],[[3776,3780],"valid"],[[3781,3781],"disallowed"],[[3782,3782],"valid"],[[3783,3783],"disallowed"],[[3784,3789],"valid"],[[3790,3791],"disallowed"],[[3792,3801],"valid"],[[3802,3803],"disallowed"],[[3804,3804],"mapped",[3755,3737]],[[3805,3805],"mapped",[3755,3745]],[[3806,3807],"valid"],[[3808,3839],"disallowed"],[[3840,3840],"valid"],[[3841,3850],"valid",[],"NV8"],[[3851,3851],"valid"],[[3852,3852],"mapped",[3851]],[[3853,3863],"valid",[],"NV8"],[[3864,3865],"valid"],[[3866,3871],"valid",[],"NV8"],[[3872,3881],"valid"],[[3882,3892],"valid",[],"NV8"],[[3893,3893],"valid"],[[3894,3894],"valid",[],"NV8"],[[3895,3895],"valid"],[[3896,3896],"valid",[],"NV8"],[[3897,3897],"valid"],[[3898,3901],"valid",[],"NV8"],[[3902,3906],"valid"],[[3907,3907],"mapped",[3906,4023]],[[3908,3911],"valid"],[[3912,3912],"disallowed"],[[3913,3916],"valid"],[[3917,3917],"mapped",[3916,4023]],[[3918,3921],"valid"],[[3922,3922],"mapped",[3921,4023]],[[3923,3926],"valid"],[[3927,3927],"mapped",[3926,4023]],[[3928,3931],"valid"],[[3932,3932],"mapped",[3931,4023]],[[3933,3944],"valid"],[[3945,3945],"mapped",[3904,4021]],[[3946,3946],"valid"],[[3947,3948],"valid"],[[3949,3952],"disallowed"],[[3953,3954],"valid"],[[3955,3955],"mapped",[3953,3954]],[[3956,3956],"valid"],[[3957,3957],"mapped",[3953,3956]],[[3958,3958],"mapped",[4018,3968]],[[3959,3959],"mapped",[4018,3953,3968]],[[3960,3960],"mapped",[4019,3968]],[[3961,3961],"mapped",[4019,3953,3968]],[[3962,3968],"valid"],[[3969,3969],"mapped",[3953,3968]],[[3970,3972],"valid"],[[3973,3973],"valid",[],"NV8"],[[3974,3979],"valid"],[[3980,3983],"valid"],[[3984,3986],"valid"],[[3987,3987],"mapped",[3986,4023]],[[3988,3989],"valid"],[[3990,3990],"valid"],[[3991,3991],"valid"],[[3992,3992],"disallowed"],[[3993,3996],"valid"],[[3997,3997],"mapped",[3996,4023]],[[3998,4001],"valid"],[[4002,4002],"mapped",[4001,4023]],[[4003,4006],"valid"],[[4007,4007],"mapped",[4006,4023]],[[4008,4011],"valid"],[[4012,4012],"mapped",[4011,4023]],[[4013,4013],"valid"],[[4014,4016],"valid"],[[4017,4023],"valid"],[[4024,4024],"valid"],[[4025,4025],"mapped",[3984,4021]],[[4026,4028],"valid"],[[4029,4029],"disallowed"],[[4030,4037],"valid",[],"NV8"],[[4038,4038],"valid"],[[4039,4044],"valid",[],"NV8"],[[4045,4045],"disallowed"],[[4046,4046],"valid",[],"NV8"],[[4047,4047],"valid",[],"NV8"],[[4048,4049],"valid",[],"NV8"],[[4050,4052],"valid",[],"NV8"],[[4053,4056],"valid",[],"NV8"],[[4057,4058],"valid",[],"NV8"],[[4059,4095],"disallowed"],[[4096,4129],"valid"],[[4130,4130],"valid"],[[4131,4135],"valid"],[[4136,4136],"valid"],[[4137,4138],"valid"],[[4139,4139],"valid"],[[4140,4146],"valid"],[[4147,4149],"valid"],[[4150,4153],"valid"],[[4154,4159],"valid"],[[4160,4169],"valid"],[[4170,4175],"valid",[],"NV8"],[[4176,4185],"valid"],[[4186,4249],"valid"],[[4250,4253],"valid"],[[4254,4255],"valid",[],"NV8"],[[4256,4293],"disallowed"],[[4294,4294],"disallowed"],[[4295,4295],"mapped",[11559]],[[4296,4300],"disallowed"],[[4301,4301],"mapped",[11565]],[[4302,4303],"disallowed"],[[4304,4342],"valid"],[[4343,4344],"valid"],[[4345,4346],"valid"],[[4347,4347],"valid",[],"NV8"],[[4348,4348],"mapped",[4316]],[[4349,4351],"valid"],[[4352,4441],"valid",[],"NV8"],[[4442,4446],"valid",[],"NV8"],[[4447,4448],"disallowed"],[[4449,4514],"valid",[],"NV8"],[[4515,4519],"valid",[],"NV8"],[[4520,4601],"valid",[],"NV8"],[[4602,4607],"valid",[],"NV8"],[[4608,4614],"valid"],[[4615,4615],"valid"],[[4616,4678],"valid"],[[4679,4679],"valid"],[[4680,4680],"valid"],[[4681,4681],"disallowed"],[[4682,4685],"valid"],[[4686,4687],"disallowed"],[[4688,4694],"valid"],[[4695,4695],"disallowed"],[[4696,4696],"valid"],[[4697,4697],"disallowed"],[[4698,4701],"valid"],[[4702,4703],"disallowed"],[[4704,4742],"valid"],[[4743,4743],"valid"],[[4744,4744],"valid"],[[4745,4745],"disallowed"],[[4746,4749],"valid"],[[4750,4751],"disallowed"],[[4752,4782],"valid"],[[4783,4783],"valid"],[[4784,4784],"valid"],[[4785,4785],"disallowed"],[[4786,4789],"valid"],[[4790,4791],"disallowed"],[[4792,4798],"valid"],[[4799,4799],"disallowed"],[[4800,4800],"valid"],[[4801,4801],"disallowed"],[[4802,4805],"valid"],[[4806,4807],"disallowed"],[[4808,4814],"valid"],[[4815,4815],"valid"],[[4816,4822],"valid"],[[4823,4823],"disallowed"],[[4824,4846],"valid"],[[4847,4847],"valid"],[[4848,4878],"valid"],[[4879,4879],"valid"],[[4880,4880],"valid"],[[4881,4881],"disallowed"],[[4882,4885],"valid"],[[4886,4887],"disallowed"],[[4888,4894],"valid"],[[4895,4895],"valid"],[[4896,4934],"valid"],[[4935,4935],"valid"],[[4936,4954],"valid"],[[4955,4956],"disallowed"],[[4957,4958],"valid"],[[4959,4959],"valid"],[[4960,4960],"valid",[],"NV8"],[[4961,4988],"valid",[],"NV8"],[[4989,4991],"disallowed"],[[4992,5007],"valid"],[[5008,5017],"valid",[],"NV8"],[[5018,5023],"disallowed"],[[5024,5108],"valid"],[[5109,5109],"valid"],[[5110,5111],"disallowed"],[[5112,5112],"mapped",[5104]],[[5113,5113],"mapped",[5105]],[[5114,5114],"mapped",[5106]],[[5115,5115],"mapped",[5107]],[[5116,5116],"mapped",[5108]],[[5117,5117],"mapped",[5109]],[[5118,5119],"disallowed"],[[5120,5120],"valid",[],"NV8"],[[5121,5740],"valid"],[[5741,5742],"valid",[],"NV8"],[[5743,5750],"valid"],[[5751,5759],"valid"],[[5760,5760],"disallowed"],[[5761,5786],"valid"],[[5787,5788],"valid",[],"NV8"],[[5789,5791],"disallowed"],[[5792,5866],"valid"],[[5867,5872],"valid",[],"NV8"],[[5873,5880],"valid"],[[5881,5887],"disallowed"],[[5888,5900],"valid"],[[5901,5901],"disallowed"],[[5902,5908],"valid"],[[5909,5919],"disallowed"],[[5920,5940],"valid"],[[5941,5942],"valid",[],"NV8"],[[5943,5951],"disallowed"],[[5952,5971],"valid"],[[5972,5983],"disallowed"],[[5984,5996],"valid"],[[5997,5997],"disallowed"],[[5998,6000],"valid"],[[6001,6001],"disallowed"],[[6002,6003],"valid"],[[6004,6015],"disallowed"],[[6016,6067],"valid"],[[6068,6069],"disallowed"],[[6070,6099],"valid"],[[6100,6102],"valid",[],"NV8"],[[6103,6103],"valid"],[[6104,6107],"valid",[],"NV8"],[[6108,6108],"valid"],[[6109,6109],"valid"],[[6110,6111],"disallowed"],[[6112,6121],"valid"],[[6122,6127],"disallowed"],[[6128,6137],"valid",[],"NV8"],[[6138,6143],"disallowed"],[[6144,6149],"valid",[],"NV8"],[[6150,6150],"disallowed"],[[6151,6154],"valid",[],"NV8"],[[6155,6157],"ignored"],[[6158,6158],"disallowed"],[[6159,6159],"disallowed"],[[6160,6169],"valid"],[[6170,6175],"disallowed"],[[6176,6263],"valid"],[[6264,6271],"disallowed"],[[6272,6313],"valid"],[[6314,6314],"valid"],[[6315,6319],"disallowed"],[[6320,6389],"valid"],[[6390,6399],"disallowed"],[[6400,6428],"valid"],[[6429,6430],"valid"],[[6431,6431],"disallowed"],[[6432,6443],"valid"],[[6444,6447],"disallowed"],[[6448,6459],"valid"],[[6460,6463],"disallowed"],[[6464,6464],"valid",[],"NV8"],[[6465,6467],"disallowed"],[[6468,6469],"valid",[],"NV8"],[[6470,6509],"valid"],[[6510,6511],"disallowed"],[[6512,6516],"valid"],[[6517,6527],"disallowed"],[[6528,6569],"valid"],[[6570,6571],"valid"],[[6572,6575],"disallowed"],[[6576,6601],"valid"],[[6602,6607],"disallowed"],[[6608,6617],"valid"],[[6618,6618],"valid",[],"XV8"],[[6619,6621],"disallowed"],[[6622,6623],"valid",[],"NV8"],[[6624,6655],"valid",[],"NV8"],[[6656,6683],"valid"],[[6684,6685],"disallowed"],[[6686,6687],"valid",[],"NV8"],[[6688,6750],"valid"],[[6751,6751],"disallowed"],[[6752,6780],"valid"],[[6781,6782],"disallowed"],[[6783,6793],"valid"],[[6794,6799],"disallowed"],[[6800,6809],"valid"],[[6810,6815],"disallowed"],[[6816,6822],"valid",[],"NV8"],[[6823,6823],"valid"],[[6824,6829],"valid",[],"NV8"],[[6830,6831],"disallowed"],[[6832,6845],"valid"],[[6846,6846],"valid",[],"NV8"],[[6847,6911],"disallowed"],[[6912,6987],"valid"],[[6988,6991],"disallowed"],[[6992,7001],"valid"],[[7002,7018],"valid",[],"NV8"],[[7019,7027],"valid"],[[7028,7036],"valid",[],"NV8"],[[7037,7039],"disallowed"],[[7040,7082],"valid"],[[7083,7085],"valid"],[[7086,7097],"valid"],[[7098,7103],"valid"],[[7104,7155],"valid"],[[7156,7163],"disallowed"],[[7164,7167],"valid",[],"NV8"],[[7168,7223],"valid"],[[7224,7226],"disallowed"],[[7227,7231],"valid",[],"NV8"],[[7232,7241],"valid"],[[7242,7244],"disallowed"],[[7245,7293],"valid"],[[7294,7295],"valid",[],"NV8"],[[7296,7359],"disallowed"],[[7360,7367],"valid",[],"NV8"],[[7368,7375],"disallowed"],[[7376,7378],"valid"],[[7379,7379],"valid",[],"NV8"],[[7380,7410],"valid"],[[7411,7414],"valid"],[[7415,7415],"disallowed"],[[7416,7417],"valid"],[[7418,7423],"disallowed"],[[7424,7467],"valid"],[[7468,7468],"mapped",[97]],[[7469,7469],"mapped",[230]],[[7470,7470],"mapped",[98]],[[7471,7471],"valid"],[[7472,7472],"mapped",[100]],[[7473,7473],"mapped",[101]],[[7474,7474],"mapped",[477]],[[7475,7475],"mapped",[103]],[[7476,7476],"mapped",[104]],[[7477,7477],"mapped",[105]],[[7478,7478],"mapped",[106]],[[7479,7479],"mapped",[107]],[[7480,7480],"mapped",[108]],[[7481,7481],"mapped",[109]],[[7482,7482],"mapped",[110]],[[7483,7483],"valid"],[[7484,7484],"mapped",[111]],[[7485,7485],"mapped",[547]],[[7486,7486],"mapped",[112]],[[7487,7487],"mapped",[114]],[[7488,7488],"mapped",[116]],[[7489,7489],"mapped",[117]],[[7490,7490],"mapped",[119]],[[7491,7491],"mapped",[97]],[[7492,7492],"mapped",[592]],[[7493,7493],"mapped",[593]],[[7494,7494],"mapped",[7426]],[[7495,7495],"mapped",[98]],[[7496,7496],"mapped",[100]],[[7497,7497],"mapped",[101]],[[7498,7498],"mapped",[601]],[[7499,7499],"mapped",[603]],[[7500,7500],"mapped",[604]],[[7501,7501],"mapped",[103]],[[7502,7502],"valid"],[[7503,7503],"mapped",[107]],[[7504,7504],"mapped",[109]],[[7505,7505],"mapped",[331]],[[7506,7506],"mapped",[111]],[[7507,7507],"mapped",[596]],[[7508,7508],"mapped",[7446]],[[7509,7509],"mapped",[7447]],[[7510,7510],"mapped",[112]],[[7511,7511],"mapped",[116]],[[7512,7512],"mapped",[117]],[[7513,7513],"mapped",[7453]],[[7514,7514],"mapped",[623]],[[7515,7515],"mapped",[118]],[[7516,7516],"mapped",[7461]],[[7517,7517],"mapped",[946]],[[7518,7518],"mapped",[947]],[[7519,7519],"mapped",[948]],[[7520,7520],"mapped",[966]],[[7521,7521],"mapped",[967]],[[7522,7522],"mapped",[105]],[[7523,7523],"mapped",[114]],[[7524,7524],"mapped",[117]],[[7525,7525],"mapped",[118]],[[7526,7526],"mapped",[946]],[[7527,7527],"mapped",[947]],[[7528,7528],"mapped",[961]],[[7529,7529],"mapped",[966]],[[7530,7530],"mapped",[967]],[[7531,7531],"valid"],[[7532,7543],"valid"],[[7544,7544],"mapped",[1085]],[[7545,7578],"valid"],[[7579,7579],"mapped",[594]],[[7580,7580],"mapped",[99]],[[7581,7581],"mapped",[597]],[[7582,7582],"mapped",[240]],[[7583,7583],"mapped",[604]],[[7584,7584],"mapped",[102]],[[7585,7585],"mapped",[607]],[[7586,7586],"mapped",[609]],[[7587,7587],"mapped",[613]],[[7588,7588],"mapped",[616]],[[7589,7589],"mapped",[617]],[[7590,7590],"mapped",[618]],[[7591,7591],"mapped",[7547]],[[7592,7592],"mapped",[669]],[[7593,7593],"mapped",[621]],[[7594,7594],"mapped",[7557]],[[7595,7595],"mapped",[671]],[[7596,7596],"mapped",[625]],[[7597,7597],"mapped",[624]],[[7598,7598],"mapped",[626]],[[7599,7599],"mapped",[627]],[[7600,7600],"mapped",[628]],[[7601,7601],"mapped",[629]],[[7602,7602],"mapped",[632]],[[7603,7603],"mapped",[642]],[[7604,7604],"mapped",[643]],[[7605,7605],"mapped",[427]],[[7606,7606],"mapped",[649]],[[7607,7607],"mapped",[650]],[[7608,7608],"mapped",[7452]],[[7609,7609],"mapped",[651]],[[7610,7610],"mapped",[652]],[[7611,7611],"mapped",[122]],[[7612,7612],"mapped",[656]],[[7613,7613],"mapped",[657]],[[7614,7614],"mapped",[658]],[[7615,7615],"mapped",[952]],[[7616,7619],"valid"],[[7620,7626],"valid"],[[7627,7654],"valid"],[[7655,7669],"valid"],[[7670,7675],"disallowed"],[[7676,7676],"valid"],[[7677,7677],"valid"],[[7678,7679],"valid"],[[7680,7680],"mapped",[7681]],[[7681,7681],"valid"],[[7682,7682],"mapped",[7683]],[[7683,7683],"valid"],[[7684,7684],"mapped",[7685]],[[7685,7685],"valid"],[[7686,7686],"mapped",[7687]],[[7687,7687],"valid"],[[7688,7688],"mapped",[7689]],[[7689,7689],"valid"],[[7690,7690],"mapped",[7691]],[[7691,7691],"valid"],[[7692,7692],"mapped",[7693]],[[7693,7693],"valid"],[[7694,7694],"mapped",[7695]],[[7695,7695],"valid"],[[7696,7696],"mapped",[7697]],[[7697,7697],"valid"],[[7698,7698],"mapped",[7699]],[[7699,7699],"valid"],[[7700,7700],"mapped",[7701]],[[7701,7701],"valid"],[[7702,7702],"mapped",[7703]],[[7703,7703],"valid"],[[7704,7704],"mapped",[7705]],[[7705,7705],"valid"],[[7706,7706],"mapped",[7707]],[[7707,7707],"valid"],[[7708,7708],"mapped",[7709]],[[7709,7709],"valid"],[[7710,7710],"mapped",[7711]],[[7711,7711],"valid"],[[7712,7712],"mapped",[7713]],[[7713,7713],"valid"],[[7714,7714],"mapped",[7715]],[[7715,7715],"valid"],[[7716,7716],"mapped",[7717]],[[7717,7717],"valid"],[[7718,7718],"mapped",[7719]],[[7719,7719],"valid"],[[7720,7720],"mapped",[7721]],[[7721,7721],"valid"],[[7722,7722],"mapped",[7723]],[[7723,7723],"valid"],[[7724,7724],"mapped",[7725]],[[7725,7725],"valid"],[[7726,7726],"mapped",[7727]],[[7727,7727],"valid"],[[7728,7728],"mapped",[7729]],[[7729,7729],"valid"],[[7730,7730],"mapped",[7731]],[[7731,7731],"valid"],[[7732,7732],"mapped",[7733]],[[7733,7733],"valid"],[[7734,7734],"mapped",[7735]],[[7735,7735],"valid"],[[7736,7736],"mapped",[7737]],[[7737,7737],"valid"],[[7738,7738],"mapped",[7739]],[[7739,7739],"valid"],[[7740,7740],"mapped",[7741]],[[7741,7741],"valid"],[[7742,7742],"mapped",[7743]],[[7743,7743],"valid"],[[7744,7744],"mapped",[7745]],[[7745,7745],"valid"],[[7746,7746],"mapped",[7747]],[[7747,7747],"valid"],[[7748,7748],"mapped",[7749]],[[7749,7749],"valid"],[[7750,7750],"mapped",[7751]],[[7751,7751],"valid"],[[7752,7752],"mapped",[7753]],[[7753,7753],"valid"],[[7754,7754],"mapped",[7755]],[[7755,7755],"valid"],[[7756,7756],"mapped",[7757]],[[7757,7757],"valid"],[[7758,7758],"mapped",[7759]],[[7759,7759],"valid"],[[7760,7760],"mapped",[7761]],[[7761,7761],"valid"],[[7762,7762],"mapped",[7763]],[[7763,7763],"valid"],[[7764,7764],"mapped",[7765]],[[7765,7765],"valid"],[[7766,7766],"mapped",[7767]],[[7767,7767],"valid"],[[7768,7768],"mapped",[7769]],[[7769,7769],"valid"],[[7770,7770],"mapped",[7771]],[[7771,7771],"valid"],[[7772,7772],"mapped",[7773]],[[7773,7773],"valid"],[[7774,7774],"mapped",[7775]],[[7775,7775],"valid"],[[7776,7776],"mapped",[7777]],[[7777,7777],"valid"],[[7778,7778],"mapped",[7779]],[[7779,7779],"valid"],[[7780,7780],"mapped",[7781]],[[7781,7781],"valid"],[[7782,7782],"mapped",[7783]],[[7783,7783],"valid"],[[7784,7784],"mapped",[7785]],[[7785,7785],"valid"],[[7786,7786],"mapped",[7787]],[[7787,7787],"valid"],[[7788,7788],"mapped",[7789]],[[7789,7789],"valid"],[[7790,7790],"mapped",[7791]],[[7791,7791],"valid"],[[7792,7792],"mapped",[7793]],[[7793,7793],"valid"],[[7794,7794],"mapped",[7795]],[[7795,7795],"valid"],[[7796,7796],"mapped",[7797]],[[7797,7797],"valid"],[[7798,7798],"mapped",[7799]],[[7799,7799],"valid"],[[7800,7800],"mapped",[7801]],[[7801,7801],"valid"],[[7802,7802],"mapped",[7803]],[[7803,7803],"valid"],[[7804,7804],"mapped",[7805]],[[7805,7805],"valid"],[[7806,7806],"mapped",[7807]],[[7807,7807],"valid"],[[7808,7808],"mapped",[7809]],[[7809,7809],"valid"],[[7810,7810],"mapped",[7811]],[[7811,7811],"valid"],[[7812,7812],"mapped",[7813]],[[7813,7813],"valid"],[[7814,7814],"mapped",[7815]],[[7815,7815],"valid"],[[7816,7816],"mapped",[7817]],[[7817,7817],"valid"],[[7818,7818],"mapped",[7819]],[[7819,7819],"valid"],[[7820,7820],"mapped",[7821]],[[7821,7821],"valid"],[[7822,7822],"mapped",[7823]],[[7823,7823],"valid"],[[7824,7824],"mapped",[7825]],[[7825,7825],"valid"],[[7826,7826],"mapped",[7827]],[[7827,7827],"valid"],[[7828,7828],"mapped",[7829]],[[7829,7833],"valid"],[[7834,7834],"mapped",[97,702]],[[7835,7835],"mapped",[7777]],[[7836,7837],"valid"],[[7838,7838],"mapped",[115,115]],[[7839,7839],"valid"],[[7840,7840],"mapped",[7841]],[[7841,7841],"valid"],[[7842,7842],"mapped",[7843]],[[7843,7843],"valid"],[[7844,7844],"mapped",[7845]],[[7845,7845],"valid"],[[7846,7846],"mapped",[7847]],[[7847,7847],"valid"],[[7848,7848],"mapped",[7849]],[[7849,7849],"valid"],[[7850,7850],"mapped",[7851]],[[7851,7851],"valid"],[[7852,7852],"mapped",[7853]],[[7853,7853],"valid"],[[7854,7854],"mapped",[7855]],[[7855,7855],"valid"],[[7856,7856],"mapped",[7857]],[[7857,7857],"valid"],[[7858,7858],"mapped",[7859]],[[7859,7859],"valid"],[[7860,7860],"mapped",[7861]],[[7861,7861],"valid"],[[7862,7862],"mapped",[7863]],[[7863,7863],"valid"],[[7864,7864],"mapped",[7865]],[[7865,7865],"valid"],[[7866,7866],"mapped",[7867]],[[7867,7867],"valid"],[[7868,7868],"mapped",[7869]],[[7869,7869],"valid"],[[7870,7870],"mapped",[7871]],[[7871,7871],"valid"],[[7872,7872],"mapped",[7873]],[[7873,7873],"valid"],[[7874,7874],"mapped",[7875]],[[7875,7875],"valid"],[[7876,7876],"mapped",[7877]],[[7877,7877],"valid"],[[7878,7878],"mapped",[7879]],[[7879,7879],"valid"],[[7880,7880],"mapped",[7881]],[[7881,7881],"valid"],[[7882,7882],"mapped",[7883]],[[7883,7883],"valid"],[[7884,7884],"mapped",[7885]],[[7885,7885],"valid"],[[7886,7886],"mapped",[7887]],[[7887,7887],"valid"],[[7888,7888],"mapped",[7889]],[[7889,7889],"valid"],[[7890,7890],"mapped",[7891]],[[7891,7891],"valid"],[[7892,7892],"mapped",[7893]],[[7893,7893],"valid"],[[7894,7894],"mapped",[7895]],[[7895,7895],"valid"],[[7896,7896],"mapped",[7897]],[[7897,7897],"valid"],[[7898,7898],"mapped",[7899]],[[7899,7899],"valid"],[[7900,7900],"mapped",[7901]],[[7901,7901],"valid"],[[7902,7902],"mapped",[7903]],[[7903,7903],"valid"],[[7904,7904],"mapped",[7905]],[[7905,7905],"valid"],[[7906,7906],"mapped",[7907]],[[7907,7907],"valid"],[[7908,7908],"mapped",[7909]],[[7909,7909],"valid"],[[7910,7910],"mapped",[7911]],[[7911,7911],"valid"],[[7912,7912],"mapped",[7913]],[[7913,7913],"valid"],[[7914,7914],"mapped",[7915]],[[7915,7915],"valid"],[[7916,7916],"mapped",[7917]],[[7917,7917],"valid"],[[7918,7918],"mapped",[7919]],[[7919,7919],"valid"],[[7920,7920],"mapped",[7921]],[[7921,7921],"valid"],[[7922,7922],"mapped",[7923]],[[7923,7923],"valid"],[[7924,7924],"mapped",[7925]],[[7925,7925],"valid"],[[7926,7926],"mapped",[7927]],[[7927,7927],"valid"],[[7928,7928],"mapped",[7929]],[[7929,7929],"valid"],[[7930,7930],"mapped",[7931]],[[7931,7931],"valid"],[[7932,7932],"mapped",[7933]],[[7933,7933],"valid"],[[7934,7934],"mapped",[7935]],[[7935,7935],"valid"],[[7936,7943],"valid"],[[7944,7944],"mapped",[7936]],[[7945,7945],"mapped",[7937]],[[7946,7946],"mapped",[7938]],[[7947,7947],"mapped",[7939]],[[7948,7948],"mapped",[7940]],[[7949,7949],"mapped",[7941]],[[7950,7950],"mapped",[7942]],[[7951,7951],"mapped",[7943]],[[7952,7957],"valid"],[[7958,7959],"disallowed"],[[7960,7960],"mapped",[7952]],[[7961,7961],"mapped",[7953]],[[7962,7962],"mapped",[7954]],[[7963,7963],"mapped",[7955]],[[7964,7964],"mapped",[7956]],[[7965,7965],"mapped",[7957]],[[7966,7967],"disallowed"],[[7968,7975],"valid"],[[7976,7976],"mapped",[7968]],[[7977,7977],"mapped",[7969]],[[7978,7978],"mapped",[7970]],[[7979,7979],"mapped",[7971]],[[7980,7980],"mapped",[7972]],[[7981,7981],"mapped",[7973]],[[7982,7982],"mapped",[7974]],[[7983,7983],"mapped",[7975]],[[7984,7991],"valid"],[[7992,7992],"mapped",[7984]],[[7993,7993],"mapped",[7985]],[[7994,7994],"mapped",[7986]],[[7995,7995],"mapped",[7987]],[[7996,7996],"mapped",[7988]],[[7997,7997],"mapped",[7989]],[[7998,7998],"mapped",[7990]],[[7999,7999],"mapped",[7991]],[[8000,8005],"valid"],[[8006,8007],"disallowed"],[[8008,8008],"mapped",[8000]],[[8009,8009],"mapped",[8001]],[[8010,8010],"mapped",[8002]],[[8011,8011],"mapped",[8003]],[[8012,8012],"mapped",[8004]],[[8013,8013],"mapped",[8005]],[[8014,8015],"disallowed"],[[8016,8023],"valid"],[[8024,8024],"disallowed"],[[8025,8025],"mapped",[8017]],[[8026,8026],"disallowed"],[[8027,8027],"mapped",[8019]],[[8028,8028],"disallowed"],[[8029,8029],"mapped",[8021]],[[8030,8030],"disallowed"],[[8031,8031],"mapped",[8023]],[[8032,8039],"valid"],[[8040,8040],"mapped",[8032]],[[8041,8041],"mapped",[8033]],[[8042,8042],"mapped",[8034]],[[8043,8043],"mapped",[8035]],[[8044,8044],"mapped",[8036]],[[8045,8045],"mapped",[8037]],[[8046,8046],"mapped",[8038]],[[8047,8047],"mapped",[8039]],[[8048,8048],"valid"],[[8049,8049],"mapped",[940]],[[8050,8050],"valid"],[[8051,8051],"mapped",[941]],[[8052,8052],"valid"],[[8053,8053],"mapped",[942]],[[8054,8054],"valid"],[[8055,8055],"mapped",[943]],[[8056,8056],"valid"],[[8057,8057],"mapped",[972]],[[8058,8058],"valid"],[[8059,8059],"mapped",[973]],[[8060,8060],"valid"],[[8061,8061],"mapped",[974]],[[8062,8063],"disallowed"],[[8064,8064],"mapped",[7936,953]],[[8065,8065],"mapped",[7937,953]],[[8066,8066],"mapped",[7938,953]],[[8067,8067],"mapped",[7939,953]],[[8068,8068],"mapped",[7940,953]],[[8069,8069],"mapped",[7941,953]],[[8070,8070],"mapped",[7942,953]],[[8071,8071],"mapped",[7943,953]],[[8072,8072],"mapped",[7936,953]],[[8073,8073],"mapped",[7937,953]],[[8074,8074],"mapped",[7938,953]],[[8075,8075],"mapped",[7939,953]],[[8076,8076],"mapped",[7940,953]],[[8077,8077],"mapped",[7941,953]],[[8078,8078],"mapped",[7942,953]],[[8079,8079],"mapped",[7943,953]],[[8080,8080],"mapped",[7968,953]],[[8081,8081],"mapped",[7969,953]],[[8082,8082],"mapped",[7970,953]],[[8083,8083],"mapped",[7971,953]],[[8084,8084],"mapped",[7972,953]],[[8085,8085],"mapped",[7973,953]],[[8086,8086],"mapped",[7974,953]],[[8087,8087],"mapped",[7975,953]],[[8088,8088],"mapped",[7968,953]],[[8089,8089],"mapped",[7969,953]],[[8090,8090],"mapped",[7970,953]],[[8091,8091],"mapped",[7971,953]],[[8092,8092],"mapped",[7972,953]],[[8093,8093],"mapped",[7973,953]],[[8094,8094],"mapped",[7974,953]],[[8095,8095],"mapped",[7975,953]],[[8096,8096],"mapped",[8032,953]],[[8097,8097],"mapped",[8033,953]],[[8098,8098],"mapped",[8034,953]],[[8099,8099],"mapped",[8035,953]],[[8100,8100],"mapped",[8036,953]],[[8101,8101],"mapped",[8037,953]],[[8102,8102],"mapped",[8038,953]],[[8103,8103],"mapped",[8039,953]],[[8104,8104],"mapped",[8032,953]],[[8105,8105],"mapped",[8033,953]],[[8106,8106],"mapped",[8034,953]],[[8107,8107],"mapped",[8035,953]],[[8108,8108],"mapped",[8036,953]],[[8109,8109],"mapped",[8037,953]],[[8110,8110],"mapped",[8038,953]],[[8111,8111],"mapped",[8039,953]],[[8112,8113],"valid"],[[8114,8114],"mapped",[8048,953]],[[8115,8115],"mapped",[945,953]],[[8116,8116],"mapped",[940,953]],[[8117,8117],"disallowed"],[[8118,8118],"valid"],[[8119,8119],"mapped",[8118,953]],[[8120,8120],"mapped",[8112]],[[8121,8121],"mapped",[8113]],[[8122,8122],"mapped",[8048]],[[8123,8123],"mapped",[940]],[[8124,8124],"mapped",[945,953]],[[8125,8125],"disallowed_STD3_mapped",[32,787]],[[8126,8126],"mapped",[953]],[[8127,8127],"disallowed_STD3_mapped",[32,787]],[[8128,8128],"disallowed_STD3_mapped",[32,834]],[[8129,8129],"disallowed_STD3_mapped",[32,776,834]],[[8130,8130],"mapped",[8052,953]],[[8131,8131],"mapped",[951,953]],[[8132,8132],"mapped",[942,953]],[[8133,8133],"disallowed"],[[8134,8134],"valid"],[[8135,8135],"mapped",[8134,953]],[[8136,8136],"mapped",[8050]],[[8137,8137],"mapped",[941]],[[8138,8138],"mapped",[8052]],[[8139,8139],"mapped",[942]],[[8140,8140],"mapped",[951,953]],[[8141,8141],"disallowed_STD3_mapped",[32,787,768]],[[8142,8142],"disallowed_STD3_mapped",[32,787,769]],[[8143,8143],"disallowed_STD3_mapped",[32,787,834]],[[8144,8146],"valid"],[[8147,8147],"mapped",[912]],[[8148,8149],"disallowed"],[[8150,8151],"valid"],[[8152,8152],"mapped",[8144]],[[8153,8153],"mapped",[8145]],[[8154,8154],"mapped",[8054]],[[8155,8155],"mapped",[943]],[[8156,8156],"disallowed"],[[8157,8157],"disallowed_STD3_mapped",[32,788,768]],[[8158,8158],"disallowed_STD3_mapped",[32,788,769]],[[8159,8159],"disallowed_STD3_mapped",[32,788,834]],[[8160,8162],"valid"],[[8163,8163],"mapped",[944]],[[8164,8167],"valid"],[[8168,8168],"mapped",[8160]],[[8169,8169],"mapped",[8161]],[[8170,8170],"mapped",[8058]],[[8171,8171],"mapped",[973]],[[8172,8172],"mapped",[8165]],[[8173,8173],"disallowed_STD3_mapped",[32,776,768]],[[8174,8174],"disallowed_STD3_mapped",[32,776,769]],[[8175,8175],"disallowed_STD3_mapped",[96]],[[8176,8177],"disallowed"],[[8178,8178],"mapped",[8060,953]],[[8179,8179],"mapped",[969,953]],[[8180,8180],"mapped",[974,953]],[[8181,8181],"disallowed"],[[8182,8182],"valid"],[[8183,8183],"mapped",[8182,953]],[[8184,8184],"mapped",[8056]],[[8185,8185],"mapped",[972]],[[8186,8186],"mapped",[8060]],[[8187,8187],"mapped",[974]],[[8188,8188],"mapped",[969,953]],[[8189,8189],"disallowed_STD3_mapped",[32,769]],[[8190,8190],"disallowed_STD3_mapped",[32,788]],[[8191,8191],"disallowed"],[[8192,8202],"disallowed_STD3_mapped",[32]],[[8203,8203],"ignored"],[[8204,8205],"deviation",[]],[[8206,8207],"disallowed"],[[8208,8208],"valid",[],"NV8"],[[8209,8209],"mapped",[8208]],[[8210,8214],"valid",[],"NV8"],[[8215,8215],"disallowed_STD3_mapped",[32,819]],[[8216,8227],"valid",[],"NV8"],[[8228,8230],"disallowed"],[[8231,8231],"valid",[],"NV8"],[[8232,8238],"disallowed"],[[8239,8239],"disallowed_STD3_mapped",[32]],[[8240,8242],"valid",[],"NV8"],[[8243,8243],"mapped",[8242,8242]],[[8244,8244],"mapped",[8242,8242,8242]],[[8245,8245],"valid",[],"NV8"],[[8246,8246],"mapped",[8245,8245]],[[8247,8247],"mapped",[8245,8245,8245]],[[8248,8251],"valid",[],"NV8"],[[8252,8252],"disallowed_STD3_mapped",[33,33]],[[8253,8253],"valid",[],"NV8"],[[8254,8254],"disallowed_STD3_mapped",[32,773]],[[8255,8262],"valid",[],"NV8"],[[8263,8263],"disallowed_STD3_mapped",[63,63]],[[8264,8264],"disallowed_STD3_mapped",[63,33]],[[8265,8265],"disallowed_STD3_mapped",[33,63]],[[8266,8269],"valid",[],"NV8"],[[8270,8274],"valid",[],"NV8"],[[8275,8276],"valid",[],"NV8"],[[8277,8278],"valid",[],"NV8"],[[8279,8279],"mapped",[8242,8242,8242,8242]],[[8280,8286],"valid",[],"NV8"],[[8287,8287],"disallowed_STD3_mapped",[32]],[[8288,8288],"ignored"],[[8289,8291],"disallowed"],[[8292,8292],"ignored"],[[8293,8293],"disallowed"],[[8294,8297],"disallowed"],[[8298,8303],"disallowed"],[[8304,8304],"mapped",[48]],[[8305,8305],"mapped",[105]],[[8306,8307],"disallowed"],[[8308,8308],"mapped",[52]],[[8309,8309],"mapped",[53]],[[8310,8310],"mapped",[54]],[[8311,8311],"mapped",[55]],[[8312,8312],"mapped",[56]],[[8313,8313],"mapped",[57]],[[8314,8314],"disallowed_STD3_mapped",[43]],[[8315,8315],"mapped",[8722]],[[8316,8316],"disallowed_STD3_mapped",[61]],[[8317,8317],"disallowed_STD3_mapped",[40]],[[8318,8318],"disallowed_STD3_mapped",[41]],[[8319,8319],"mapped",[110]],[[8320,8320],"mapped",[48]],[[8321,8321],"mapped",[49]],[[8322,8322],"mapped",[50]],[[8323,8323],"mapped",[51]],[[8324,8324],"mapped",[52]],[[8325,8325],"mapped",[53]],[[8326,8326],"mapped",[54]],[[8327,8327],"mapped",[55]],[[8328,8328],"mapped",[56]],[[8329,8329],"mapped",[57]],[[8330,8330],"disallowed_STD3_mapped",[43]],[[8331,8331],"mapped",[8722]],[[8332,8332],"disallowed_STD3_mapped",[61]],[[8333,8333],"disallowed_STD3_mapped",[40]],[[8334,8334],"disallowed_STD3_mapped",[41]],[[8335,8335],"disallowed"],[[8336,8336],"mapped",[97]],[[8337,8337],"mapped",[101]],[[8338,8338],"mapped",[111]],[[8339,8339],"mapped",[120]],[[8340,8340],"mapped",[601]],[[8341,8341],"mapped",[104]],[[8342,8342],"mapped",[107]],[[8343,8343],"mapped",[108]],[[8344,8344],"mapped",[109]],[[8345,8345],"mapped",[110]],[[8346,8346],"mapped",[112]],[[8347,8347],"mapped",[115]],[[8348,8348],"mapped",[116]],[[8349,8351],"disallowed"],[[8352,8359],"valid",[],"NV8"],[[8360,8360],"mapped",[114,115]],[[8361,8362],"valid",[],"NV8"],[[8363,8363],"valid",[],"NV8"],[[8364,8364],"valid",[],"NV8"],[[8365,8367],"valid",[],"NV8"],[[8368,8369],"valid",[],"NV8"],[[8370,8373],"valid",[],"NV8"],[[8374,8376],"valid",[],"NV8"],[[8377,8377],"valid",[],"NV8"],[[8378,8378],"valid",[],"NV8"],[[8379,8381],"valid",[],"NV8"],[[8382,8382],"valid",[],"NV8"],[[8383,8399],"disallowed"],[[8400,8417],"valid",[],"NV8"],[[8418,8419],"valid",[],"NV8"],[[8420,8426],"valid",[],"NV8"],[[8427,8427],"valid",[],"NV8"],[[8428,8431],"valid",[],"NV8"],[[8432,8432],"valid",[],"NV8"],[[8433,8447],"disallowed"],[[8448,8448],"disallowed_STD3_mapped",[97,47,99]],[[8449,8449],"disallowed_STD3_mapped",[97,47,115]],[[8450,8450],"mapped",[99]],[[8451,8451],"mapped",[176,99]],[[8452,8452],"valid",[],"NV8"],[[8453,8453],"disallowed_STD3_mapped",[99,47,111]],[[8454,8454],"disallowed_STD3_mapped",[99,47,117]],[[8455,8455],"mapped",[603]],[[8456,8456],"valid",[],"NV8"],[[8457,8457],"mapped",[176,102]],[[8458,8458],"mapped",[103]],[[8459,8462],"mapped",[104]],[[8463,8463],"mapped",[295]],[[8464,8465],"mapped",[105]],[[8466,8467],"mapped",[108]],[[8468,8468],"valid",[],"NV8"],[[8469,8469],"mapped",[110]],[[8470,8470],"mapped",[110,111]],[[8471,8472],"valid",[],"NV8"],[[8473,8473],"mapped",[112]],[[8474,8474],"mapped",[113]],[[8475,8477],"mapped",[114]],[[8478,8479],"valid",[],"NV8"],[[8480,8480],"mapped",[115,109]],[[8481,8481],"mapped",[116,101,108]],[[8482,8482],"mapped",[116,109]],[[8483,8483],"valid",[],"NV8"],[[8484,8484],"mapped",[122]],[[8485,8485],"valid",[],"NV8"],[[8486,8486],"mapped",[969]],[[8487,8487],"valid",[],"NV8"],[[8488,8488],"mapped",[122]],[[8489,8489],"valid",[],"NV8"],[[8490,8490],"mapped",[107]],[[8491,8491],"mapped",[229]],[[8492,8492],"mapped",[98]],[[8493,8493],"mapped",[99]],[[8494,8494],"valid",[],"NV8"],[[8495,8496],"mapped",[101]],[[8497,8497],"mapped",[102]],[[8498,8498],"disallowed"],[[8499,8499],"mapped",[109]],[[8500,8500],"mapped",[111]],[[8501,8501],"mapped",[1488]],[[8502,8502],"mapped",[1489]],[[8503,8503],"mapped",[1490]],[[8504,8504],"mapped",[1491]],[[8505,8505],"mapped",[105]],[[8506,8506],"valid",[],"NV8"],[[8507,8507],"mapped",[102,97,120]],[[8508,8508],"mapped",[960]],[[8509,8510],"mapped",[947]],[[8511,8511],"mapped",[960]],[[8512,8512],"mapped",[8721]],[[8513,8516],"valid",[],"NV8"],[[8517,8518],"mapped",[100]],[[8519,8519],"mapped",[101]],[[8520,8520],"mapped",[105]],[[8521,8521],"mapped",[106]],[[8522,8523],"valid",[],"NV8"],[[8524,8524],"valid",[],"NV8"],[[8525,8525],"valid",[],"NV8"],[[8526,8526],"valid"],[[8527,8527],"valid",[],"NV8"],[[8528,8528],"mapped",[49,8260,55]],[[8529,8529],"mapped",[49,8260,57]],[[8530,8530],"mapped",[49,8260,49,48]],[[8531,8531],"mapped",[49,8260,51]],[[8532,8532],"mapped",[50,8260,51]],[[8533,8533],"mapped",[49,8260,53]],[[8534,8534],"mapped",[50,8260,53]],[[8535,8535],"mapped",[51,8260,53]],[[8536,8536],"mapped",[52,8260,53]],[[8537,8537],"mapped",[49,8260,54]],[[8538,8538],"mapped",[53,8260,54]],[[8539,8539],"mapped",[49,8260,56]],[[8540,8540],"mapped",[51,8260,56]],[[8541,8541],"mapped",[53,8260,56]],[[8542,8542],"mapped",[55,8260,56]],[[8543,8543],"mapped",[49,8260]],[[8544,8544],"mapped",[105]],[[8545,8545],"mapped",[105,105]],[[8546,8546],"mapped",[105,105,105]],[[8547,8547],"mapped",[105,118]],[[8548,8548],"mapped",[118]],[[8549,8549],"mapped",[118,105]],[[8550,8550],"mapped",[118,105,105]],[[8551,8551],"mapped",[118,105,105,105]],[[8552,8552],"mapped",[105,120]],[[8553,8553],"mapped",[120]],[[8554,8554],"mapped",[120,105]],[[8555,8555],"mapped",[120,105,105]],[[8556,8556],"mapped",[108]],[[8557,8557],"mapped",[99]],[[8558,8558],"mapped",[100]],[[8559,8559],"mapped",[109]],[[8560,8560],"mapped",[105]],[[8561,8561],"mapped",[105,105]],[[8562,8562],"mapped",[105,105,105]],[[8563,8563],"mapped",[105,118]],[[8564,8564],"mapped",[118]],[[8565,8565],"mapped",[118,105]],[[8566,8566],"mapped",[118,105,105]],[[8567,8567],"mapped",[118,105,105,105]],[[8568,8568],"mapped",[105,120]],[[8569,8569],"mapped",[120]],[[8570,8570],"mapped",[120,105]],[[8571,8571],"mapped",[120,105,105]],[[8572,8572],"mapped",[108]],[[8573,8573],"mapped",[99]],[[8574,8574],"mapped",[100]],[[8575,8575],"mapped",[109]],[[8576,8578],"valid",[],"NV8"],[[8579,8579],"disallowed"],[[8580,8580],"valid"],[[8581,8584],"valid",[],"NV8"],[[8585,8585],"mapped",[48,8260,51]],[[8586,8587],"valid",[],"NV8"],[[8588,8591],"disallowed"],[[8592,8682],"valid",[],"NV8"],[[8683,8691],"valid",[],"NV8"],[[8692,8703],"valid",[],"NV8"],[[8704,8747],"valid",[],"NV8"],[[8748,8748],"mapped",[8747,8747]],[[8749,8749],"mapped",[8747,8747,8747]],[[8750,8750],"valid",[],"NV8"],[[8751,8751],"mapped",[8750,8750]],[[8752,8752],"mapped",[8750,8750,8750]],[[8753,8799],"valid",[],"NV8"],[[8800,8800],"disallowed_STD3_valid"],[[8801,8813],"valid",[],"NV8"],[[8814,8815],"disallowed_STD3_valid"],[[8816,8945],"valid",[],"NV8"],[[8946,8959],"valid",[],"NV8"],[[8960,8960],"valid",[],"NV8"],[[8961,8961],"valid",[],"NV8"],[[8962,9000],"valid",[],"NV8"],[[9001,9001],"mapped",[12296]],[[9002,9002],"mapped",[12297]],[[9003,9082],"valid",[],"NV8"],[[9083,9083],"valid",[],"NV8"],[[9084,9084],"valid",[],"NV8"],[[9085,9114],"valid",[],"NV8"],[[9115,9166],"valid",[],"NV8"],[[9167,9168],"valid",[],"NV8"],[[9169,9179],"valid",[],"NV8"],[[9180,9191],"valid",[],"NV8"],[[9192,9192],"valid",[],"NV8"],[[9193,9203],"valid",[],"NV8"],[[9204,9210],"valid",[],"NV8"],[[9211,9215],"disallowed"],[[9216,9252],"valid",[],"NV8"],[[9253,9254],"valid",[],"NV8"],[[9255,9279],"disallowed"],[[9280,9290],"valid",[],"NV8"],[[9291,9311],"disallowed"],[[9312,9312],"mapped",[49]],[[9313,9313],"mapped",[50]],[[9314,9314],"mapped",[51]],[[9315,9315],"mapped",[52]],[[9316,9316],"mapped",[53]],[[9317,9317],"mapped",[54]],[[9318,9318],"mapped",[55]],[[9319,9319],"mapped",[56]],[[9320,9320],"mapped",[57]],[[9321,9321],"mapped",[49,48]],[[9322,9322],"mapped",[49,49]],[[9323,9323],"mapped",[49,50]],[[9324,9324],"mapped",[49,51]],[[9325,9325],"mapped",[49,52]],[[9326,9326],"mapped",[49,53]],[[9327,9327],"mapped",[49,54]],[[9328,9328],"mapped",[49,55]],[[9329,9329],"mapped",[49,56]],[[9330,9330],"mapped",[49,57]],[[9331,9331],"mapped",[50,48]],[[9332,9332],"disallowed_STD3_mapped",[40,49,41]],[[9333,9333],"disallowed_STD3_mapped",[40,50,41]],[[9334,9334],"disallowed_STD3_mapped",[40,51,41]],[[9335,9335],"disallowed_STD3_mapped",[40,52,41]],[[9336,9336],"disallowed_STD3_mapped",[40,53,41]],[[9337,9337],"disallowed_STD3_mapped",[40,54,41]],[[9338,9338],"disallowed_STD3_mapped",[40,55,41]],[[9339,9339],"disallowed_STD3_mapped",[40,56,41]],[[9340,9340],"disallowed_STD3_mapped",[40,57,41]],[[9341,9341],"disallowed_STD3_mapped",[40,49,48,41]],[[9342,9342],"disallowed_STD3_mapped",[40,49,49,41]],[[9343,9343],"disallowed_STD3_mapped",[40,49,50,41]],[[9344,9344],"disallowed_STD3_mapped",[40,49,51,41]],[[9345,9345],"disallowed_STD3_mapped",[40,49,52,41]],[[9346,9346],"disallowed_STD3_mapped",[40,49,53,41]],[[9347,9347],"disallowed_STD3_mapped",[40,49,54,41]],[[9348,9348],"disallowed_STD3_mapped",[40,49,55,41]],[[9349,9349],"disallowed_STD3_mapped",[40,49,56,41]],[[9350,9350],"disallowed_STD3_mapped",[40,49,57,41]],[[9351,9351],"disallowed_STD3_mapped",[40,50,48,41]],[[9352,9371],"disallowed"],[[9372,9372],"disallowed_STD3_mapped",[40,97,41]],[[9373,9373],"disallowed_STD3_mapped",[40,98,41]],[[9374,9374],"disallowed_STD3_mapped",[40,99,41]],[[9375,9375],"disallowed_STD3_mapped",[40,100,41]],[[9376,9376],"disallowed_STD3_mapped",[40,101,41]],[[9377,9377],"disallowed_STD3_mapped",[40,102,41]],[[9378,9378],"disallowed_STD3_mapped",[40,103,41]],[[9379,9379],"disallowed_STD3_mapped",[40,104,41]],[[9380,9380],"disallowed_STD3_mapped",[40,105,41]],[[9381,9381],"disallowed_STD3_mapped",[40,106,41]],[[9382,9382],"disallowed_STD3_mapped",[40,107,41]],[[9383,9383],"disallowed_STD3_mapped",[40,108,41]],[[9384,9384],"disallowed_STD3_mapped",[40,109,41]],[[9385,9385],"disallowed_STD3_mapped",[40,110,41]],[[9386,9386],"disallowed_STD3_mapped",[40,111,41]],[[9387,9387],"disallowed_STD3_mapped",[40,112,41]],[[9388,9388],"disallowed_STD3_mapped",[40,113,41]],[[9389,9389],"disallowed_STD3_mapped",[40,114,41]],[[9390,9390],"disallowed_STD3_mapped",[40,115,41]],[[9391,9391],"disallowed_STD3_mapped",[40,116,41]],[[9392,9392],"disallowed_STD3_mapped",[40,117,41]],[[9393,9393],"disallowed_STD3_mapped",[40,118,41]],[[9394,9394],"disallowed_STD3_mapped",[40,119,41]],[[9395,9395],"disallowed_STD3_mapped",[40,120,41]],[[9396,9396],"disallowed_STD3_mapped",[40,121,41]],[[9397,9397],"disallowed_STD3_mapped",[40,122,41]],[[9398,9398],"mapped",[97]],[[9399,9399],"mapped",[98]],[[9400,9400],"mapped",[99]],[[9401,9401],"mapped",[100]],[[9402,9402],"mapped",[101]],[[9403,9403],"mapped",[102]],[[9404,9404],"mapped",[103]],[[9405,9405],"mapped",[104]],[[9406,9406],"mapped",[105]],[[9407,9407],"mapped",[106]],[[9408,9408],"mapped",[107]],[[9409,9409],"mapped",[108]],[[9410,9410],"mapped",[109]],[[9411,9411],"mapped",[110]],[[9412,9412],"mapped",[111]],[[9413,9413],"mapped",[112]],[[9414,9414],"mapped",[113]],[[9415,9415],"mapped",[114]],[[9416,9416],"mapped",[115]],[[9417,9417],"mapped",[116]],[[9418,9418],"mapped",[117]],[[9419,9419],"mapped",[118]],[[9420,9420],"mapped",[119]],[[9421,9421],"mapped",[120]],[[9422,9422],"mapped",[121]],[[9423,9423],"mapped",[122]],[[9424,9424],"mapped",[97]],[[9425,9425],"mapped",[98]],[[9426,9426],"mapped",[99]],[[9427,9427],"mapped",[100]],[[9428,9428],"mapped",[101]],[[9429,9429],"mapped",[102]],[[9430,9430],"mapped",[103]],[[9431,9431],"mapped",[104]],[[9432,9432],"mapped",[105]],[[9433,9433],"mapped",[106]],[[9434,9434],"mapped",[107]],[[9435,9435],"mapped",[108]],[[9436,9436],"mapped",[109]],[[9437,9437],"mapped",[110]],[[9438,9438],"mapped",[111]],[[9439,9439],"mapped",[112]],[[9440,9440],"mapped",[113]],[[9441,9441],"mapped",[114]],[[9442,9442],"mapped",[115]],[[9443,9443],"mapped",[116]],[[9444,9444],"mapped",[117]],[[9445,9445],"mapped",[118]],[[9446,9446],"mapped",[119]],[[9447,9447],"mapped",[120]],[[9448,9448],"mapped",[121]],[[9449,9449],"mapped",[122]],[[9450,9450],"mapped",[48]],[[9451,9470],"valid",[],"NV8"],[[9471,9471],"valid",[],"NV8"],[[9472,9621],"valid",[],"NV8"],[[9622,9631],"valid",[],"NV8"],[[9632,9711],"valid",[],"NV8"],[[9712,9719],"valid",[],"NV8"],[[9720,9727],"valid",[],"NV8"],[[9728,9747],"valid",[],"NV8"],[[9748,9749],"valid",[],"NV8"],[[9750,9751],"valid",[],"NV8"],[[9752,9752],"valid",[],"NV8"],[[9753,9753],"valid",[],"NV8"],[[9754,9839],"valid",[],"NV8"],[[9840,9841],"valid",[],"NV8"],[[9842,9853],"valid",[],"NV8"],[[9854,9855],"valid",[],"NV8"],[[9856,9865],"valid",[],"NV8"],[[9866,9873],"valid",[],"NV8"],[[9874,9884],"valid",[],"NV8"],[[9885,9885],"valid",[],"NV8"],[[9886,9887],"valid",[],"NV8"],[[9888,9889],"valid",[],"NV8"],[[9890,9905],"valid",[],"NV8"],[[9906,9906],"valid",[],"NV8"],[[9907,9916],"valid",[],"NV8"],[[9917,9919],"valid",[],"NV8"],[[9920,9923],"valid",[],"NV8"],[[9924,9933],"valid",[],"NV8"],[[9934,9934],"valid",[],"NV8"],[[9935,9953],"valid",[],"NV8"],[[9954,9954],"valid",[],"NV8"],[[9955,9955],"valid",[],"NV8"],[[9956,9959],"valid",[],"NV8"],[[9960,9983],"valid",[],"NV8"],[[9984,9984],"valid",[],"NV8"],[[9985,9988],"valid",[],"NV8"],[[9989,9989],"valid",[],"NV8"],[[9990,9993],"valid",[],"NV8"],[[9994,9995],"valid",[],"NV8"],[[9996,10023],"valid",[],"NV8"],[[10024,10024],"valid",[],"NV8"],[[10025,10059],"valid",[],"NV8"],[[10060,10060],"valid",[],"NV8"],[[10061,10061],"valid",[],"NV8"],[[10062,10062],"valid",[],"NV8"],[[10063,10066],"valid",[],"NV8"],[[10067,10069],"valid",[],"NV8"],[[10070,10070],"valid",[],"NV8"],[[10071,10071],"valid",[],"NV8"],[[10072,10078],"valid",[],"NV8"],[[10079,10080],"valid",[],"NV8"],[[10081,10087],"valid",[],"NV8"],[[10088,10101],"valid",[],"NV8"],[[10102,10132],"valid",[],"NV8"],[[10133,10135],"valid",[],"NV8"],[[10136,10159],"valid",[],"NV8"],[[10160,10160],"valid",[],"NV8"],[[10161,10174],"valid",[],"NV8"],[[10175,10175],"valid",[],"NV8"],[[10176,10182],"valid",[],"NV8"],[[10183,10186],"valid",[],"NV8"],[[10187,10187],"valid",[],"NV8"],[[10188,10188],"valid",[],"NV8"],[[10189,10189],"valid",[],"NV8"],[[10190,10191],"valid",[],"NV8"],[[10192,10219],"valid",[],"NV8"],[[10220,10223],"valid",[],"NV8"],[[10224,10239],"valid",[],"NV8"],[[10240,10495],"valid",[],"NV8"],[[10496,10763],"valid",[],"NV8"],[[10764,10764],"mapped",[8747,8747,8747,8747]],[[10765,10867],"valid",[],"NV8"],[[10868,10868],"disallowed_STD3_mapped",[58,58,61]],[[10869,10869],"disallowed_STD3_mapped",[61,61]],[[10870,10870],"disallowed_STD3_mapped",[61,61,61]],[[10871,10971],"valid",[],"NV8"],[[10972,10972],"mapped",[10973,824]],[[10973,11007],"valid",[],"NV8"],[[11008,11021],"valid",[],"NV8"],[[11022,11027],"valid",[],"NV8"],[[11028,11034],"valid",[],"NV8"],[[11035,11039],"valid",[],"NV8"],[[11040,11043],"valid",[],"NV8"],[[11044,11084],"valid",[],"NV8"],[[11085,11087],"valid",[],"NV8"],[[11088,11092],"valid",[],"NV8"],[[11093,11097],"valid",[],"NV8"],[[11098,11123],"valid",[],"NV8"],[[11124,11125],"disallowed"],[[11126,11157],"valid",[],"NV8"],[[11158,11159],"disallowed"],[[11160,11193],"valid",[],"NV8"],[[11194,11196],"disallowed"],[[11197,11208],"valid",[],"NV8"],[[11209,11209],"disallowed"],[[11210,11217],"valid",[],"NV8"],[[11218,11243],"disallowed"],[[11244,11247],"valid",[],"NV8"],[[11248,11263],"disallowed"],[[11264,11264],"mapped",[11312]],[[11265,11265],"mapped",[11313]],[[11266,11266],"mapped",[11314]],[[11267,11267],"mapped",[11315]],[[11268,11268],"mapped",[11316]],[[11269,11269],"mapped",[11317]],[[11270,11270],"mapped",[11318]],[[11271,11271],"mapped",[11319]],[[11272,11272],"mapped",[11320]],[[11273,11273],"mapped",[11321]],[[11274,11274],"mapped",[11322]],[[11275,11275],"mapped",[11323]],[[11276,11276],"mapped",[11324]],[[11277,11277],"mapped",[11325]],[[11278,11278],"mapped",[11326]],[[11279,11279],"mapped",[11327]],[[11280,11280],"mapped",[11328]],[[11281,11281],"mapped",[11329]],[[11282,11282],"mapped",[11330]],[[11283,11283],"mapped",[11331]],[[11284,11284],"mapped",[11332]],[[11285,11285],"mapped",[11333]],[[11286,11286],"mapped",[11334]],[[11287,11287],"mapped",[11335]],[[11288,11288],"mapped",[11336]],[[11289,11289],"mapped",[11337]],[[11290,11290],"mapped",[11338]],[[11291,11291],"mapped",[11339]],[[11292,11292],"mapped",[11340]],[[11293,11293],"mapped",[11341]],[[11294,11294],"mapped",[11342]],[[11295,11295],"mapped",[11343]],[[11296,11296],"mapped",[11344]],[[11297,11297],"mapped",[11345]],[[11298,11298],"mapped",[11346]],[[11299,11299],"mapped",[11347]],[[11300,11300],"mapped",[11348]],[[11301,11301],"mapped",[11349]],[[11302,11302],"mapped",[11350]],[[11303,11303],"mapped",[11351]],[[11304,11304],"mapped",[11352]],[[11305,11305],"mapped",[11353]],[[11306,11306],"mapped",[11354]],[[11307,11307],"mapped",[11355]],[[11308,11308],"mapped",[11356]],[[11309,11309],"mapped",[11357]],[[11310,11310],"mapped",[11358]],[[11311,11311],"disallowed"],[[11312,11358],"valid"],[[11359,11359],"disallowed"],[[11360,11360],"mapped",[11361]],[[11361,11361],"valid"],[[11362,11362],"mapped",[619]],[[11363,11363],"mapped",[7549]],[[11364,11364],"mapped",[637]],[[11365,11366],"valid"],[[11367,11367],"mapped",[11368]],[[11368,11368],"valid"],[[11369,11369],"mapped",[11370]],[[11370,11370],"valid"],[[11371,11371],"mapped",[11372]],[[11372,11372],"valid"],[[11373,11373],"mapped",[593]],[[11374,11374],"mapped",[625]],[[11375,11375],"mapped",[592]],[[11376,11376],"mapped",[594]],[[11377,11377],"valid"],[[11378,11378],"mapped",[11379]],[[11379,11379],"valid"],[[11380,11380],"valid"],[[11381,11381],"mapped",[11382]],[[11382,11383],"valid"],[[11384,11387],"valid"],[[11388,11388],"mapped",[106]],[[11389,11389],"mapped",[118]],[[11390,11390],"mapped",[575]],[[11391,11391],"mapped",[576]],[[11392,11392],"mapped",[11393]],[[11393,11393],"valid"],[[11394,11394],"mapped",[11395]],[[11395,11395],"valid"],[[11396,11396],"mapped",[11397]],[[11397,11397],"valid"],[[11398,11398],"mapped",[11399]],[[11399,11399],"valid"],[[11400,11400],"mapped",[11401]],[[11401,11401],"valid"],[[11402,11402],"mapped",[11403]],[[11403,11403],"valid"],[[11404,11404],"mapped",[11405]],[[11405,11405],"valid"],[[11406,11406],"mapped",[11407]],[[11407,11407],"valid"],[[11408,11408],"mapped",[11409]],[[11409,11409],"valid"],[[11410,11410],"mapped",[11411]],[[11411,11411],"valid"],[[11412,11412],"mapped",[11413]],[[11413,11413],"valid"],[[11414,11414],"mapped",[11415]],[[11415,11415],"valid"],[[11416,11416],"mapped",[11417]],[[11417,11417],"valid"],[[11418,11418],"mapped",[11419]],[[11419,11419],"valid"],[[11420,11420],"mapped",[11421]],[[11421,11421],"valid"],[[11422,11422],"mapped",[11423]],[[11423,11423],"valid"],[[11424,11424],"mapped",[11425]],[[11425,11425],"valid"],[[11426,11426],"mapped",[11427]],[[11427,11427],"valid"],[[11428,11428],"mapped",[11429]],[[11429,11429],"valid"],[[11430,11430],"mapped",[11431]],[[11431,11431],"valid"],[[11432,11432],"mapped",[11433]],[[11433,11433],"valid"],[[11434,11434],"mapped",[11435]],[[11435,11435],"valid"],[[11436,11436],"mapped",[11437]],[[11437,11437],"valid"],[[11438,11438],"mapped",[11439]],[[11439,11439],"valid"],[[11440,11440],"mapped",[11441]],[[11441,11441],"valid"],[[11442,11442],"mapped",[11443]],[[11443,11443],"valid"],[[11444,11444],"mapped",[11445]],[[11445,11445],"valid"],[[11446,11446],"mapped",[11447]],[[11447,11447],"valid"],[[11448,11448],"mapped",[11449]],[[11449,11449],"valid"],[[11450,11450],"mapped",[11451]],[[11451,11451],"valid"],[[11452,11452],"mapped",[11453]],[[11453,11453],"valid"],[[11454,11454],"mapped",[11455]],[[11455,11455],"valid"],[[11456,11456],"mapped",[11457]],[[11457,11457],"valid"],[[11458,11458],"mapped",[11459]],[[11459,11459],"valid"],[[11460,11460],"mapped",[11461]],[[11461,11461],"valid"],[[11462,11462],"mapped",[11463]],[[11463,11463],"valid"],[[11464,11464],"mapped",[11465]],[[11465,11465],"valid"],[[11466,11466],"mapped",[11467]],[[11467,11467],"valid"],[[11468,11468],"mapped",[11469]],[[11469,11469],"valid"],[[11470,11470],"mapped",[11471]],[[11471,11471],"valid"],[[11472,11472],"mapped",[11473]],[[11473,11473],"valid"],[[11474,11474],"mapped",[11475]],[[11475,11475],"valid"],[[11476,11476],"mapped",[11477]],[[11477,11477],"valid"],[[11478,11478],"mapped",[11479]],[[11479,11479],"valid"],[[11480,11480],"mapped",[11481]],[[11481,11481],"valid"],[[11482,11482],"mapped",[11483]],[[11483,11483],"valid"],[[11484,11484],"mapped",[11485]],[[11485,11485],"valid"],[[11486,11486],"mapped",[11487]],[[11487,11487],"valid"],[[11488,11488],"mapped",[11489]],[[11489,11489],"valid"],[[11490,11490],"mapped",[11491]],[[11491,11492],"valid"],[[11493,11498],"valid",[],"NV8"],[[11499,11499],"mapped",[11500]],[[11500,11500],"valid"],[[11501,11501],"mapped",[11502]],[[11502,11505],"valid"],[[11506,11506],"mapped",[11507]],[[11507,11507],"valid"],[[11508,11512],"disallowed"],[[11513,11519],"valid",[],"NV8"],[[11520,11557],"valid"],[[11558,11558],"disallowed"],[[11559,11559],"valid"],[[11560,11564],"disallowed"],[[11565,11565],"valid"],[[11566,11567],"disallowed"],[[11568,11621],"valid"],[[11622,11623],"valid"],[[11624,11630],"disallowed"],[[11631,11631],"mapped",[11617]],[[11632,11632],"valid",[],"NV8"],[[11633,11646],"disallowed"],[[11647,11647],"valid"],[[11648,11670],"valid"],[[11671,11679],"disallowed"],[[11680,11686],"valid"],[[11687,11687],"disallowed"],[[11688,11694],"valid"],[[11695,11695],"disallowed"],[[11696,11702],"valid"],[[11703,11703],"disallowed"],[[11704,11710],"valid"],[[11711,11711],"disallowed"],[[11712,11718],"valid"],[[11719,11719],"disallowed"],[[11720,11726],"valid"],[[11727,11727],"disallowed"],[[11728,11734],"valid"],[[11735,11735],"disallowed"],[[11736,11742],"valid"],[[11743,11743],"disallowed"],[[11744,11775],"valid"],[[11776,11799],"valid",[],"NV8"],[[11800,11803],"valid",[],"NV8"],[[11804,11805],"valid",[],"NV8"],[[11806,11822],"valid",[],"NV8"],[[11823,11823],"valid"],[[11824,11824],"valid",[],"NV8"],[[11825,11825],"valid",[],"NV8"],[[11826,11835],"valid",[],"NV8"],[[11836,11842],"valid",[],"NV8"],[[11843,11903],"disallowed"],[[11904,11929],"valid",[],"NV8"],[[11930,11930],"disallowed"],[[11931,11934],"valid",[],"NV8"],[[11935,11935],"mapped",[27597]],[[11936,12018],"valid",[],"NV8"],[[12019,12019],"mapped",[40863]],[[12020,12031],"disallowed"],[[12032,12032],"mapped",[19968]],[[12033,12033],"mapped",[20008]],[[12034,12034],"mapped",[20022]],[[12035,12035],"mapped",[20031]],[[12036,12036],"mapped",[20057]],[[12037,12037],"mapped",[20101]],[[12038,12038],"mapped",[20108]],[[12039,12039],"mapped",[20128]],[[12040,12040],"mapped",[20154]],[[12041,12041],"mapped",[20799]],[[12042,12042],"mapped",[20837]],[[12043,12043],"mapped",[20843]],[[12044,12044],"mapped",[20866]],[[12045,12045],"mapped",[20886]],[[12046,12046],"mapped",[20907]],[[12047,12047],"mapped",[20960]],[[12048,12048],"mapped",[20981]],[[12049,12049],"mapped",[20992]],[[12050,12050],"mapped",[21147]],[[12051,12051],"mapped",[21241]],[[12052,12052],"mapped",[21269]],[[12053,12053],"mapped",[21274]],[[12054,12054],"mapped",[21304]],[[12055,12055],"mapped",[21313]],[[12056,12056],"mapped",[21340]],[[12057,12057],"mapped",[21353]],[[12058,12058],"mapped",[21378]],[[12059,12059],"mapped",[21430]],[[12060,12060],"mapped",[21448]],[[12061,12061],"mapped",[21475]],[[12062,12062],"mapped",[22231]],[[12063,12063],"mapped",[22303]],[[12064,12064],"mapped",[22763]],[[12065,12065],"mapped",[22786]],[[12066,12066],"mapped",[22794]],[[12067,12067],"mapped",[22805]],[[12068,12068],"mapped",[22823]],[[12069,12069],"mapped",[22899]],[[12070,12070],"mapped",[23376]],[[12071,12071],"mapped",[23424]],[[12072,12072],"mapped",[23544]],[[12073,12073],"mapped",[23567]],[[12074,12074],"mapped",[23586]],[[12075,12075],"mapped",[23608]],[[12076,12076],"mapped",[23662]],[[12077,12077],"mapped",[23665]],[[12078,12078],"mapped",[24027]],[[12079,12079],"mapped",[24037]],[[12080,12080],"mapped",[24049]],[[12081,12081],"mapped",[24062]],[[12082,12082],"mapped",[24178]],[[12083,12083],"mapped",[24186]],[[12084,12084],"mapped",[24191]],[[12085,12085],"mapped",[24308]],[[12086,12086],"mapped",[24318]],[[12087,12087],"mapped",[24331]],[[12088,12088],"mapped",[24339]],[[12089,12089],"mapped",[24400]],[[12090,12090],"mapped",[24417]],[[12091,12091],"mapped",[24435]],[[12092,12092],"mapped",[24515]],[[12093,12093],"mapped",[25096]],[[12094,12094],"mapped",[25142]],[[12095,12095],"mapped",[25163]],[[12096,12096],"mapped",[25903]],[[12097,12097],"mapped",[25908]],[[12098,12098],"mapped",[25991]],[[12099,12099],"mapped",[26007]],[[12100,12100],"mapped",[26020]],[[12101,12101],"mapped",[26041]],[[12102,12102],"mapped",[26080]],[[12103,12103],"mapped",[26085]],[[12104,12104],"mapped",[26352]],[[12105,12105],"mapped",[26376]],[[12106,12106],"mapped",[26408]],[[12107,12107],"mapped",[27424]],[[12108,12108],"mapped",[27490]],[[12109,12109],"mapped",[27513]],[[12110,12110],"mapped",[27571]],[[12111,12111],"mapped",[27595]],[[12112,12112],"mapped",[27604]],[[12113,12113],"mapped",[27611]],[[12114,12114],"mapped",[27663]],[[12115,12115],"mapped",[27668]],[[12116,12116],"mapped",[27700]],[[12117,12117],"mapped",[28779]],[[12118,12118],"mapped",[29226]],[[12119,12119],"mapped",[29238]],[[12120,12120],"mapped",[29243]],[[12121,12121],"mapped",[29247]],[[12122,12122],"mapped",[29255]],[[12123,12123],"mapped",[29273]],[[12124,12124],"mapped",[29275]],[[12125,12125],"mapped",[29356]],[[12126,12126],"mapped",[29572]],[[12127,12127],"mapped",[29577]],[[12128,12128],"mapped",[29916]],[[12129,12129],"mapped",[29926]],[[12130,12130],"mapped",[29976]],[[12131,12131],"mapped",[29983]],[[12132,12132],"mapped",[29992]],[[12133,12133],"mapped",[30000]],[[12134,12134],"mapped",[30091]],[[12135,12135],"mapped",[30098]],[[12136,12136],"mapped",[30326]],[[12137,12137],"mapped",[30333]],[[12138,12138],"mapped",[30382]],[[12139,12139],"mapped",[30399]],[[12140,12140],"mapped",[30446]],[[12141,12141],"mapped",[30683]],[[12142,12142],"mapped",[30690]],[[12143,12143],"mapped",[30707]],[[12144,12144],"mapped",[31034]],[[12145,12145],"mapped",[31160]],[[12146,12146],"mapped",[31166]],[[12147,12147],"mapped",[31348]],[[12148,12148],"mapped",[31435]],[[12149,12149],"mapped",[31481]],[[12150,12150],"mapped",[31859]],[[12151,12151],"mapped",[31992]],[[12152,12152],"mapped",[32566]],[[12153,12153],"mapped",[32593]],[[12154,12154],"mapped",[32650]],[[12155,12155],"mapped",[32701]],[[12156,12156],"mapped",[32769]],[[12157,12157],"mapped",[32780]],[[12158,12158],"mapped",[32786]],[[12159,12159],"mapped",[32819]],[[12160,12160],"mapped",[32895]],[[12161,12161],"mapped",[32905]],[[12162,12162],"mapped",[33251]],[[12163,12163],"mapped",[33258]],[[12164,12164],"mapped",[33267]],[[12165,12165],"mapped",[33276]],[[12166,12166],"mapped",[33292]],[[12167,12167],"mapped",[33307]],[[12168,12168],"mapped",[33311]],[[12169,12169],"mapped",[33390]],[[12170,12170],"mapped",[33394]],[[12171,12171],"mapped",[33400]],[[12172,12172],"mapped",[34381]],[[12173,12173],"mapped",[34411]],[[12174,12174],"mapped",[34880]],[[12175,12175],"mapped",[34892]],[[12176,12176],"mapped",[34915]],[[12177,12177],"mapped",[35198]],[[12178,12178],"mapped",[35211]],[[12179,12179],"mapped",[35282]],[[12180,12180],"mapped",[35328]],[[12181,12181],"mapped",[35895]],[[12182,12182],"mapped",[35910]],[[12183,12183],"mapped",[35925]],[[12184,12184],"mapped",[35960]],[[12185,12185],"mapped",[35997]],[[12186,12186],"mapped",[36196]],[[12187,12187],"mapped",[36208]],[[12188,12188],"mapped",[36275]],[[12189,12189],"mapped",[36523]],[[12190,12190],"mapped",[36554]],[[12191,12191],"mapped",[36763]],[[12192,12192],"mapped",[36784]],[[12193,12193],"mapped",[36789]],[[12194,12194],"mapped",[37009]],[[12195,12195],"mapped",[37193]],[[12196,12196],"mapped",[37318]],[[12197,12197],"mapped",[37324]],[[12198,12198],"mapped",[37329]],[[12199,12199],"mapped",[38263]],[[12200,12200],"mapped",[38272]],[[12201,12201],"mapped",[38428]],[[12202,12202],"mapped",[38582]],[[12203,12203],"mapped",[38585]],[[12204,12204],"mapped",[38632]],[[12205,12205],"mapped",[38737]],[[12206,12206],"mapped",[38750]],[[12207,12207],"mapped",[38754]],[[12208,12208],"mapped",[38761]],[[12209,12209],"mapped",[38859]],[[12210,12210],"mapped",[38893]],[[12211,12211],"mapped",[38899]],[[12212,12212],"mapped",[38913]],[[12213,12213],"mapped",[39080]],[[12214,12214],"mapped",[39131]],[[12215,12215],"mapped",[39135]],[[12216,12216],"mapped",[39318]],[[12217,12217],"mapped",[39321]],[[12218,12218],"mapped",[39340]],[[12219,12219],"mapped",[39592]],[[12220,12220],"mapped",[39640]],[[12221,12221],"mapped",[39647]],[[12222,12222],"mapped",[39717]],[[12223,12223],"mapped",[39727]],[[12224,12224],"mapped",[39730]],[[12225,12225],"mapped",[39740]],[[12226,12226],"mapped",[39770]],[[12227,12227],"mapped",[40165]],[[12228,12228],"mapped",[40565]],[[12229,12229],"mapped",[40575]],[[12230,12230],"mapped",[40613]],[[12231,12231],"mapped",[40635]],[[12232,12232],"mapped",[40643]],[[12233,12233],"mapped",[40653]],[[12234,12234],"mapped",[40657]],[[12235,12235],"mapped",[40697]],[[12236,12236],"mapped",[40701]],[[12237,12237],"mapped",[40718]],[[12238,12238],"mapped",[40723]],[[12239,12239],"mapped",[40736]],[[12240,12240],"mapped",[40763]],[[12241,12241],"mapped",[40778]],[[12242,12242],"mapped",[40786]],[[12243,12243],"mapped",[40845]],[[12244,12244],"mapped",[40860]],[[12245,12245],"mapped",[40864]],[[12246,12271],"disallowed"],[[12272,12283],"disallowed"],[[12284,12287],"disallowed"],[[12288,12288],"disallowed_STD3_mapped",[32]],[[12289,12289],"valid",[],"NV8"],[[12290,12290],"mapped",[46]],[[12291,12292],"valid",[],"NV8"],[[12293,12295],"valid"],[[12296,12329],"valid",[],"NV8"],[[12330,12333],"valid"],[[12334,12341],"valid",[],"NV8"],[[12342,12342],"mapped",[12306]],[[12343,12343],"valid",[],"NV8"],[[12344,12344],"mapped",[21313]],[[12345,12345],"mapped",[21316]],[[12346,12346],"mapped",[21317]],[[12347,12347],"valid",[],"NV8"],[[12348,12348],"valid"],[[12349,12349],"valid",[],"NV8"],[[12350,12350],"valid",[],"NV8"],[[12351,12351],"valid",[],"NV8"],[[12352,12352],"disallowed"],[[12353,12436],"valid"],[[12437,12438],"valid"],[[12439,12440],"disallowed"],[[12441,12442],"valid"],[[12443,12443],"disallowed_STD3_mapped",[32,12441]],[[12444,12444],"disallowed_STD3_mapped",[32,12442]],[[12445,12446],"valid"],[[12447,12447],"mapped",[12424,12426]],[[12448,12448],"valid",[],"NV8"],[[12449,12542],"valid"],[[12543,12543],"mapped",[12467,12488]],[[12544,12548],"disallowed"],[[12549,12588],"valid"],[[12589,12589],"valid"],[[12590,12592],"disallowed"],[[12593,12593],"mapped",[4352]],[[12594,12594],"mapped",[4353]],[[12595,12595],"mapped",[4522]],[[12596,12596],"mapped",[4354]],[[12597,12597],"mapped",[4524]],[[12598,12598],"mapped",[4525]],[[12599,12599],"mapped",[4355]],[[12600,12600],"mapped",[4356]],[[12601,12601],"mapped",[4357]],[[12602,12602],"mapped",[4528]],[[12603,12603],"mapped",[4529]],[[12604,12604],"mapped",[4530]],[[12605,12605],"mapped",[4531]],[[12606,12606],"mapped",[4532]],[[12607,12607],"mapped",[4533]],[[12608,12608],"mapped",[4378]],[[12609,12609],"mapped",[4358]],[[12610,12610],"mapped",[4359]],[[12611,12611],"mapped",[4360]],[[12612,12612],"mapped",[4385]],[[12613,12613],"mapped",[4361]],[[12614,12614],"mapped",[4362]],[[12615,12615],"mapped",[4363]],[[12616,12616],"mapped",[4364]],[[12617,12617],"mapped",[4365]],[[12618,12618],"mapped",[4366]],[[12619,12619],"mapped",[4367]],[[12620,12620],"mapped",[4368]],[[12621,12621],"mapped",[4369]],[[12622,12622],"mapped",[4370]],[[12623,12623],"mapped",[4449]],[[12624,12624],"mapped",[4450]],[[12625,12625],"mapped",[4451]],[[12626,12626],"mapped",[4452]],[[12627,12627],"mapped",[4453]],[[12628,12628],"mapped",[4454]],[[12629,12629],"mapped",[4455]],[[12630,12630],"mapped",[4456]],[[12631,12631],"mapped",[4457]],[[12632,12632],"mapped",[4458]],[[12633,12633],"mapped",[4459]],[[12634,12634],"mapped",[4460]],[[12635,12635],"mapped",[4461]],[[12636,12636],"mapped",[4462]],[[12637,12637],"mapped",[4463]],[[12638,12638],"mapped",[4464]],[[12639,12639],"mapped",[4465]],[[12640,12640],"mapped",[4466]],[[12641,12641],"mapped",[4467]],[[12642,12642],"mapped",[4468]],[[12643,12643],"mapped",[4469]],[[12644,12644],"disallowed"],[[12645,12645],"mapped",[4372]],[[12646,12646],"mapped",[4373]],[[12647,12647],"mapped",[4551]],[[12648,12648],"mapped",[4552]],[[12649,12649],"mapped",[4556]],[[12650,12650],"mapped",[4558]],[[12651,12651],"mapped",[4563]],[[12652,12652],"mapped",[4567]],[[12653,12653],"mapped",[4569]],[[12654,12654],"mapped",[4380]],[[12655,12655],"mapped",[4573]],[[12656,12656],"mapped",[4575]],[[12657,12657],"mapped",[4381]],[[12658,12658],"mapped",[4382]],[[12659,12659],"mapped",[4384]],[[12660,12660],"mapped",[4386]],[[12661,12661],"mapped",[4387]],[[12662,12662],"mapped",[4391]],[[12663,12663],"mapped",[4393]],[[12664,12664],"mapped",[4395]],[[12665,12665],"mapped",[4396]],[[12666,12666],"mapped",[4397]],[[12667,12667],"mapped",[4398]],[[12668,12668],"mapped",[4399]],[[12669,12669],"mapped",[4402]],[[12670,12670],"mapped",[4406]],[[12671,12671],"mapped",[4416]],[[12672,12672],"mapped",[4423]],[[12673,12673],"mapped",[4428]],[[12674,12674],"mapped",[4593]],[[12675,12675],"mapped",[4594]],[[12676,12676],"mapped",[4439]],[[12677,12677],"mapped",[4440]],[[12678,12678],"mapped",[4441]],[[12679,12679],"mapped",[4484]],[[12680,12680],"mapped",[4485]],[[12681,12681],"mapped",[4488]],[[12682,12682],"mapped",[4497]],[[12683,12683],"mapped",[4498]],[[12684,12684],"mapped",[4500]],[[12685,12685],"mapped",[4510]],[[12686,12686],"mapped",[4513]],[[12687,12687],"disallowed"],[[12688,12689],"valid",[],"NV8"],[[12690,12690],"mapped",[19968]],[[12691,12691],"mapped",[20108]],[[12692,12692],"mapped",[19977]],[[12693,12693],"mapped",[22235]],[[12694,12694],"mapped",[19978]],[[12695,12695],"mapped",[20013]],[[12696,12696],"mapped",[19979]],[[12697,12697],"mapped",[30002]],[[12698,12698],"mapped",[20057]],[[12699,12699],"mapped",[19993]],[[12700,12700],"mapped",[19969]],[[12701,12701],"mapped",[22825]],[[12702,12702],"mapped",[22320]],[[12703,12703],"mapped",[20154]],[[12704,12727],"valid"],[[12728,12730],"valid"],[[12731,12735],"disallowed"],[[12736,12751],"valid",[],"NV8"],[[12752,12771],"valid",[],"NV8"],[[12772,12783],"disallowed"],[[12784,12799],"valid"],[[12800,12800],"disallowed_STD3_mapped",[40,4352,41]],[[12801,12801],"disallowed_STD3_mapped",[40,4354,41]],[[12802,12802],"disallowed_STD3_mapped",[40,4355,41]],[[12803,12803],"disallowed_STD3_mapped",[40,4357,41]],[[12804,12804],"disallowed_STD3_mapped",[40,4358,41]],[[12805,12805],"disallowed_STD3_mapped",[40,4359,41]],[[12806,12806],"disallowed_STD3_mapped",[40,4361,41]],[[12807,12807],"disallowed_STD3_mapped",[40,4363,41]],[[12808,12808],"disallowed_STD3_mapped",[40,4364,41]],[[12809,12809],"disallowed_STD3_mapped",[40,4366,41]],[[12810,12810],"disallowed_STD3_mapped",[40,4367,41]],[[12811,12811],"disallowed_STD3_mapped",[40,4368,41]],[[12812,12812],"disallowed_STD3_mapped",[40,4369,41]],[[12813,12813],"disallowed_STD3_mapped",[40,4370,41]],[[12814,12814],"disallowed_STD3_mapped",[40,44032,41]],[[12815,12815],"disallowed_STD3_mapped",[40,45208,41]],[[12816,12816],"disallowed_STD3_mapped",[40,45796,41]],[[12817,12817],"disallowed_STD3_mapped",[40,46972,41]],[[12818,12818],"disallowed_STD3_mapped",[40,47560,41]],[[12819,12819],"disallowed_STD3_mapped",[40,48148,41]],[[12820,12820],"disallowed_STD3_mapped",[40,49324,41]],[[12821,12821],"disallowed_STD3_mapped",[40,50500,41]],[[12822,12822],"disallowed_STD3_mapped",[40,51088,41]],[[12823,12823],"disallowed_STD3_mapped",[40,52264,41]],[[12824,12824],"disallowed_STD3_mapped",[40,52852,41]],[[12825,12825],"disallowed_STD3_mapped",[40,53440,41]],[[12826,12826],"disallowed_STD3_mapped",[40,54028,41]],[[12827,12827],"disallowed_STD3_mapped",[40,54616,41]],[[12828,12828],"disallowed_STD3_mapped",[40,51452,41]],[[12829,12829],"disallowed_STD3_mapped",[40,50724,51204,41]],[[12830,12830],"disallowed_STD3_mapped",[40,50724,54980,41]],[[12831,12831],"disallowed"],[[12832,12832],"disallowed_STD3_mapped",[40,19968,41]],[[12833,12833],"disallowed_STD3_mapped",[40,20108,41]],[[12834,12834],"disallowed_STD3_mapped",[40,19977,41]],[[12835,12835],"disallowed_STD3_mapped",[40,22235,41]],[[12836,12836],"disallowed_STD3_mapped",[40,20116,41]],[[12837,12837],"disallowed_STD3_mapped",[40,20845,41]],[[12838,12838],"disallowed_STD3_mapped",[40,19971,41]],[[12839,12839],"disallowed_STD3_mapped",[40,20843,41]],[[12840,12840],"disallowed_STD3_mapped",[40,20061,41]],[[12841,12841],"disallowed_STD3_mapped",[40,21313,41]],[[12842,12842],"disallowed_STD3_mapped",[40,26376,41]],[[12843,12843],"disallowed_STD3_mapped",[40,28779,41]],[[12844,12844],"disallowed_STD3_mapped",[40,27700,41]],[[12845,12845],"disallowed_STD3_mapped",[40,26408,41]],[[12846,12846],"disallowed_STD3_mapped",[40,37329,41]],[[12847,12847],"disallowed_STD3_mapped",[40,22303,41]],[[12848,12848],"disallowed_STD3_mapped",[40,26085,41]],[[12849,12849],"disallowed_STD3_mapped",[40,26666,41]],[[12850,12850],"disallowed_STD3_mapped",[40,26377,41]],[[12851,12851],"disallowed_STD3_mapped",[40,31038,41]],[[12852,12852],"disallowed_STD3_mapped",[40,21517,41]],[[12853,12853],"disallowed_STD3_mapped",[40,29305,41]],[[12854,12854],"disallowed_STD3_mapped",[40,36001,41]],[[12855,12855],"disallowed_STD3_mapped",[40,31069,41]],[[12856,12856],"disallowed_STD3_mapped",[40,21172,41]],[[12857,12857],"disallowed_STD3_mapped",[40,20195,41]],[[12858,12858],"disallowed_STD3_mapped",[40,21628,41]],[[12859,12859],"disallowed_STD3_mapped",[40,23398,41]],[[12860,12860],"disallowed_STD3_mapped",[40,30435,41]],[[12861,12861],"disallowed_STD3_mapped",[40,20225,41]],[[12862,12862],"disallowed_STD3_mapped",[40,36039,41]],[[12863,12863],"disallowed_STD3_mapped",[40,21332,41]],[[12864,12864],"disallowed_STD3_mapped",[40,31085,41]],[[12865,12865],"disallowed_STD3_mapped",[40,20241,41]],[[12866,12866],"disallowed_STD3_mapped",[40,33258,41]],[[12867,12867],"disallowed_STD3_mapped",[40,33267,41]],[[12868,12868],"mapped",[21839]],[[12869,12869],"mapped",[24188]],[[12870,12870],"mapped",[25991]],[[12871,12871],"mapped",[31631]],[[12872,12879],"valid",[],"NV8"],[[12880,12880],"mapped",[112,116,101]],[[12881,12881],"mapped",[50,49]],[[12882,12882],"mapped",[50,50]],[[12883,12883],"mapped",[50,51]],[[12884,12884],"mapped",[50,52]],[[12885,12885],"mapped",[50,53]],[[12886,12886],"mapped",[50,54]],[[12887,12887],"mapped",[50,55]],[[12888,12888],"mapped",[50,56]],[[12889,12889],"mapped",[50,57]],[[12890,12890],"mapped",[51,48]],[[12891,12891],"mapped",[51,49]],[[12892,12892],"mapped",[51,50]],[[12893,12893],"mapped",[51,51]],[[12894,12894],"mapped",[51,52]],[[12895,12895],"mapped",[51,53]],[[12896,12896],"mapped",[4352]],[[12897,12897],"mapped",[4354]],[[12898,12898],"mapped",[4355]],[[12899,12899],"mapped",[4357]],[[12900,12900],"mapped",[4358]],[[12901,12901],"mapped",[4359]],[[12902,12902],"mapped",[4361]],[[12903,12903],"mapped",[4363]],[[12904,12904],"mapped",[4364]],[[12905,12905],"mapped",[4366]],[[12906,12906],"mapped",[4367]],[[12907,12907],"mapped",[4368]],[[12908,12908],"mapped",[4369]],[[12909,12909],"mapped",[4370]],[[12910,12910],"mapped",[44032]],[[12911,12911],"mapped",[45208]],[[12912,12912],"mapped",[45796]],[[12913,12913],"mapped",[46972]],[[12914,12914],"mapped",[47560]],[[12915,12915],"mapped",[48148]],[[12916,12916],"mapped",[49324]],[[12917,12917],"mapped",[50500]],[[12918,12918],"mapped",[51088]],[[12919,12919],"mapped",[52264]],[[12920,12920],"mapped",[52852]],[[12921,12921],"mapped",[53440]],[[12922,12922],"mapped",[54028]],[[12923,12923],"mapped",[54616]],[[12924,12924],"mapped",[52280,44256]],[[12925,12925],"mapped",[51452,51032]],[[12926,12926],"mapped",[50864]],[[12927,12927],"valid",[],"NV8"],[[12928,12928],"mapped",[19968]],[[12929,12929],"mapped",[20108]],[[12930,12930],"mapped",[19977]],[[12931,12931],"mapped",[22235]],[[12932,12932],"mapped",[20116]],[[12933,12933],"mapped",[20845]],[[12934,12934],"mapped",[19971]],[[12935,12935],"mapped",[20843]],[[12936,12936],"mapped",[20061]],[[12937,12937],"mapped",[21313]],[[12938,12938],"mapped",[26376]],[[12939,12939],"mapped",[28779]],[[12940,12940],"mapped",[27700]],[[12941,12941],"mapped",[26408]],[[12942,12942],"mapped",[37329]],[[12943,12943],"mapped",[22303]],[[12944,12944],"mapped",[26085]],[[12945,12945],"mapped",[26666]],[[12946,12946],"mapped",[26377]],[[12947,12947],"mapped",[31038]],[[12948,12948],"mapped",[21517]],[[12949,12949],"mapped",[29305]],[[12950,12950],"mapped",[36001]],[[12951,12951],"mapped",[31069]],[[12952,12952],"mapped",[21172]],[[12953,12953],"mapped",[31192]],[[12954,12954],"mapped",[30007]],[[12955,12955],"mapped",[22899]],[[12956,12956],"mapped",[36969]],[[12957,12957],"mapped",[20778]],[[12958,12958],"mapped",[21360]],[[12959,12959],"mapped",[27880]],[[12960,12960],"mapped",[38917]],[[12961,12961],"mapped",[20241]],[[12962,12962],"mapped",[20889]],[[12963,12963],"mapped",[27491]],[[12964,12964],"mapped",[19978]],[[12965,12965],"mapped",[20013]],[[12966,12966],"mapped",[19979]],[[12967,12967],"mapped",[24038]],[[12968,12968],"mapped",[21491]],[[12969,12969],"mapped",[21307]],[[12970,12970],"mapped",[23447]],[[12971,12971],"mapped",[23398]],[[12972,12972],"mapped",[30435]],[[12973,12973],"mapped",[20225]],[[12974,12974],"mapped",[36039]],[[12975,12975],"mapped",[21332]],[[12976,12976],"mapped",[22812]],[[12977,12977],"mapped",[51,54]],[[12978,12978],"mapped",[51,55]],[[12979,12979],"mapped",[51,56]],[[12980,12980],"mapped",[51,57]],[[12981,12981],"mapped",[52,48]],[[12982,12982],"mapped",[52,49]],[[12983,12983],"mapped",[52,50]],[[12984,12984],"mapped",[52,51]],[[12985,12985],"mapped",[52,52]],[[12986,12986],"mapped",[52,53]],[[12987,12987],"mapped",[52,54]],[[12988,12988],"mapped",[52,55]],[[12989,12989],"mapped",[52,56]],[[12990,12990],"mapped",[52,57]],[[12991,12991],"mapped",[53,48]],[[12992,12992],"mapped",[49,26376]],[[12993,12993],"mapped",[50,26376]],[[12994,12994],"mapped",[51,26376]],[[12995,12995],"mapped",[52,26376]],[[12996,12996],"mapped",[53,26376]],[[12997,12997],"mapped",[54,26376]],[[12998,12998],"mapped",[55,26376]],[[12999,12999],"mapped",[56,26376]],[[13000,13000],"mapped",[57,26376]],[[13001,13001],"mapped",[49,48,26376]],[[13002,13002],"mapped",[49,49,26376]],[[13003,13003],"mapped",[49,50,26376]],[[13004,13004],"mapped",[104,103]],[[13005,13005],"mapped",[101,114,103]],[[13006,13006],"mapped",[101,118]],[[13007,13007],"mapped",[108,116,100]],[[13008,13008],"mapped",[12450]],[[13009,13009],"mapped",[12452]],[[13010,13010],"mapped",[12454]],[[13011,13011],"mapped",[12456]],[[13012,13012],"mapped",[12458]],[[13013,13013],"mapped",[12459]],[[13014,13014],"mapped",[12461]],[[13015,13015],"mapped",[12463]],[[13016,13016],"mapped",[12465]],[[13017,13017],"mapped",[12467]],[[13018,13018],"mapped",[12469]],[[13019,13019],"mapped",[12471]],[[13020,13020],"mapped",[12473]],[[13021,13021],"mapped",[12475]],[[13022,13022],"mapped",[12477]],[[13023,13023],"mapped",[12479]],[[13024,13024],"mapped",[12481]],[[13025,13025],"mapped",[12484]],[[13026,13026],"mapped",[12486]],[[13027,13027],"mapped",[12488]],[[13028,13028],"mapped",[12490]],[[13029,13029],"mapped",[12491]],[[13030,13030],"mapped",[12492]],[[13031,13031],"mapped",[12493]],[[13032,13032],"mapped",[12494]],[[13033,13033],"mapped",[12495]],[[13034,13034],"mapped",[12498]],[[13035,13035],"mapped",[12501]],[[13036,13036],"mapped",[12504]],[[13037,13037],"mapped",[12507]],[[13038,13038],"mapped",[12510]],[[13039,13039],"mapped",[12511]],[[13040,13040],"mapped",[12512]],[[13041,13041],"mapped",[12513]],[[13042,13042],"mapped",[12514]],[[13043,13043],"mapped",[12516]],[[13044,13044],"mapped",[12518]],[[13045,13045],"mapped",[12520]],[[13046,13046],"mapped",[12521]],[[13047,13047],"mapped",[12522]],[[13048,13048],"mapped",[12523]],[[13049,13049],"mapped",[12524]],[[13050,13050],"mapped",[12525]],[[13051,13051],"mapped",[12527]],[[13052,13052],"mapped",[12528]],[[13053,13053],"mapped",[12529]],[[13054,13054],"mapped",[12530]],[[13055,13055],"disallowed"],[[13056,13056],"mapped",[12450,12497,12540,12488]],[[13057,13057],"mapped",[12450,12523,12501,12449]],[[13058,13058],"mapped",[12450,12531,12506,12450]],[[13059,13059],"mapped",[12450,12540,12523]],[[13060,13060],"mapped",[12452,12491,12531,12464]],[[13061,13061],"mapped",[12452,12531,12481]],[[13062,13062],"mapped",[12454,12457,12531]],[[13063,13063],"mapped",[12456,12473,12463,12540,12489]],[[13064,13064],"mapped",[12456,12540,12459,12540]],[[13065,13065],"mapped",[12458,12531,12473]],[[13066,13066],"mapped",[12458,12540,12512]],[[13067,13067],"mapped",[12459,12452,12522]],[[13068,13068],"mapped",[12459,12521,12483,12488]],[[13069,13069],"mapped",[12459,12525,12522,12540]],[[13070,13070],"mapped",[12460,12525,12531]],[[13071,13071],"mapped",[12460,12531,12510]],[[13072,13072],"mapped",[12462,12460]],[[13073,13073],"mapped",[12462,12491,12540]],[[13074,13074],"mapped",[12461,12517,12522,12540]],[[13075,13075],"mapped",[12462,12523,12480,12540]],[[13076,13076],"mapped",[12461,12525]],[[13077,13077],"mapped",[12461,12525,12464,12521,12512]],[[13078,13078],"mapped",[12461,12525,12513,12540,12488,12523]],[[13079,13079],"mapped",[12461,12525,12527,12483,12488]],[[13080,13080],"mapped",[12464,12521,12512]],[[13081,13081],"mapped",[12464,12521,12512,12488,12531]],[[13082,13082],"mapped",[12463,12523,12476,12452,12525]],[[13083,13083],"mapped",[12463,12525,12540,12493]],[[13084,13084],"mapped",[12465,12540,12473]],[[13085,13085],"mapped",[12467,12523,12490]],[[13086,13086],"mapped",[12467,12540,12509]],[[13087,13087],"mapped",[12469,12452,12463,12523]],[[13088,13088],"mapped",[12469,12531,12481,12540,12512]],[[13089,13089],"mapped",[12471,12522,12531,12464]],[[13090,13090],"mapped",[12475,12531,12481]],[[13091,13091],"mapped",[12475,12531,12488]],[[13092,13092],"mapped",[12480,12540,12473]],[[13093,13093],"mapped",[12487,12471]],[[13094,13094],"mapped",[12489,12523]],[[13095,13095],"mapped",[12488,12531]],[[13096,13096],"mapped",[12490,12494]],[[13097,13097],"mapped",[12494,12483,12488]],[[13098,13098],"mapped",[12495,12452,12484]],[[13099,13099],"mapped",[12497,12540,12475,12531,12488]],[[13100,13100],"mapped",[12497,12540,12484]],[[13101,13101],"mapped",[12496,12540,12524,12523]],[[13102,13102],"mapped",[12500,12450,12473,12488,12523]],[[13103,13103],"mapped",[12500,12463,12523]],[[13104,13104],"mapped",[12500,12467]],[[13105,13105],"mapped",[12499,12523]],[[13106,13106],"mapped",[12501,12449,12521,12483,12489]],[[13107,13107],"mapped",[12501,12451,12540,12488]],[[13108,13108],"mapped",[12502,12483,12471,12455,12523]],[[13109,13109],"mapped",[12501,12521,12531]],[[13110,13110],"mapped",[12504,12463,12479,12540,12523]],[[13111,13111],"mapped",[12506,12477]],[[13112,13112],"mapped",[12506,12491,12498]],[[13113,13113],"mapped",[12504,12523,12484]],[[13114,13114],"mapped",[12506,12531,12473]],[[13115,13115],"mapped",[12506,12540,12472]],[[13116,13116],"mapped",[12505,12540,12479]],[[13117,13117],"mapped",[12509,12452,12531,12488]],[[13118,13118],"mapped",[12508,12523,12488]],[[13119,13119],"mapped",[12507,12531]],[[13120,13120],"mapped",[12509,12531,12489]],[[13121,13121],"mapped",[12507,12540,12523]],[[13122,13122],"mapped",[12507,12540,12531]],[[13123,13123],"mapped",[12510,12452,12463,12525]],[[13124,13124],"mapped",[12510,12452,12523]],[[13125,13125],"mapped",[12510,12483,12495]],[[13126,13126],"mapped",[12510,12523,12463]],[[13127,13127],"mapped",[12510,12531,12471,12519,12531]],[[13128,13128],"mapped",[12511,12463,12525,12531]],[[13129,13129],"mapped",[12511,12522]],[[13130,13130],"mapped",[12511,12522,12496,12540,12523]],[[13131,13131],"mapped",[12513,12460]],[[13132,13132],"mapped",[12513,12460,12488,12531]],[[13133,13133],"mapped",[12513,12540,12488,12523]],[[13134,13134],"mapped",[12516,12540,12489]],[[13135,13135],"mapped",[12516,12540,12523]],[[13136,13136],"mapped",[12518,12450,12531]],[[13137,13137],"mapped",[12522,12483,12488,12523]],[[13138,13138],"mapped",[12522,12521]],[[13139,13139],"mapped",[12523,12500,12540]],[[13140,13140],"mapped",[12523,12540,12502,12523]],[[13141,13141],"mapped",[12524,12512]],[[13142,13142],"mapped",[12524,12531,12488,12466,12531]],[[13143,13143],"mapped",[12527,12483,12488]],[[13144,13144],"mapped",[48,28857]],[[13145,13145],"mapped",[49,28857]],[[13146,13146],"mapped",[50,28857]],[[13147,13147],"mapped",[51,28857]],[[13148,13148],"mapped",[52,28857]],[[13149,13149],"mapped",[53,28857]],[[13150,13150],"mapped",[54,28857]],[[13151,13151],"mapped",[55,28857]],[[13152,13152],"mapped",[56,28857]],[[13153,13153],"mapped",[57,28857]],[[13154,13154],"mapped",[49,48,28857]],[[13155,13155],"mapped",[49,49,28857]],[[13156,13156],"mapped",[49,50,28857]],[[13157,13157],"mapped",[49,51,28857]],[[13158,13158],"mapped",[49,52,28857]],[[13159,13159],"mapped",[49,53,28857]],[[13160,13160],"mapped",[49,54,28857]],[[13161,13161],"mapped",[49,55,28857]],[[13162,13162],"mapped",[49,56,28857]],[[13163,13163],"mapped",[49,57,28857]],[[13164,13164],"mapped",[50,48,28857]],[[13165,13165],"mapped",[50,49,28857]],[[13166,13166],"mapped",[50,50,28857]],[[13167,13167],"mapped",[50,51,28857]],[[13168,13168],"mapped",[50,52,28857]],[[13169,13169],"mapped",[104,112,97]],[[13170,13170],"mapped",[100,97]],[[13171,13171],"mapped",[97,117]],[[13172,13172],"mapped",[98,97,114]],[[13173,13173],"mapped",[111,118]],[[13174,13174],"mapped",[112,99]],[[13175,13175],"mapped",[100,109]],[[13176,13176],"mapped",[100,109,50]],[[13177,13177],"mapped",[100,109,51]],[[13178,13178],"mapped",[105,117]],[[13179,13179],"mapped",[24179,25104]],[[13180,13180],"mapped",[26157,21644]],[[13181,13181],"mapped",[22823,27491]],[[13182,13182],"mapped",[26126,27835]],[[13183,13183],"mapped",[26666,24335,20250,31038]],[[13184,13184],"mapped",[112,97]],[[13185,13185],"mapped",[110,97]],[[13186,13186],"mapped",[956,97]],[[13187,13187],"mapped",[109,97]],[[13188,13188],"mapped",[107,97]],[[13189,13189],"mapped",[107,98]],[[13190,13190],"mapped",[109,98]],[[13191,13191],"mapped",[103,98]],[[13192,13192],"mapped",[99,97,108]],[[13193,13193],"mapped",[107,99,97,108]],[[13194,13194],"mapped",[112,102]],[[13195,13195],"mapped",[110,102]],[[13196,13196],"mapped",[956,102]],[[13197,13197],"mapped",[956,103]],[[13198,13198],"mapped",[109,103]],[[13199,13199],"mapped",[107,103]],[[13200,13200],"mapped",[104,122]],[[13201,13201],"mapped",[107,104,122]],[[13202,13202],"mapped",[109,104,122]],[[13203,13203],"mapped",[103,104,122]],[[13204,13204],"mapped",[116,104,122]],[[13205,13205],"mapped",[956,108]],[[13206,13206],"mapped",[109,108]],[[13207,13207],"mapped",[100,108]],[[13208,13208],"mapped",[107,108]],[[13209,13209],"mapped",[102,109]],[[13210,13210],"mapped",[110,109]],[[13211,13211],"mapped",[956,109]],[[13212,13212],"mapped",[109,109]],[[13213,13213],"mapped",[99,109]],[[13214,13214],"mapped",[107,109]],[[13215,13215],"mapped",[109,109,50]],[[13216,13216],"mapped",[99,109,50]],[[13217,13217],"mapped",[109,50]],[[13218,13218],"mapped",[107,109,50]],[[13219,13219],"mapped",[109,109,51]],[[13220,13220],"mapped",[99,109,51]],[[13221,13221],"mapped",[109,51]],[[13222,13222],"mapped",[107,109,51]],[[13223,13223],"mapped",[109,8725,115]],[[13224,13224],"mapped",[109,8725,115,50]],[[13225,13225],"mapped",[112,97]],[[13226,13226],"mapped",[107,112,97]],[[13227,13227],"mapped",[109,112,97]],[[13228,13228],"mapped",[103,112,97]],[[13229,13229],"mapped",[114,97,100]],[[13230,13230],"mapped",[114,97,100,8725,115]],[[13231,13231],"mapped",[114,97,100,8725,115,50]],[[13232,13232],"mapped",[112,115]],[[13233,13233],"mapped",[110,115]],[[13234,13234],"mapped",[956,115]],[[13235,13235],"mapped",[109,115]],[[13236,13236],"mapped",[112,118]],[[13237,13237],"mapped",[110,118]],[[13238,13238],"mapped",[956,118]],[[13239,13239],"mapped",[109,118]],[[13240,13240],"mapped",[107,118]],[[13241,13241],"mapped",[109,118]],[[13242,13242],"mapped",[112,119]],[[13243,13243],"mapped",[110,119]],[[13244,13244],"mapped",[956,119]],[[13245,13245],"mapped",[109,119]],[[13246,13246],"mapped",[107,119]],[[13247,13247],"mapped",[109,119]],[[13248,13248],"mapped",[107,969]],[[13249,13249],"mapped",[109,969]],[[13250,13250],"disallowed"],[[13251,13251],"mapped",[98,113]],[[13252,13252],"mapped",[99,99]],[[13253,13253],"mapped",[99,100]],[[13254,13254],"mapped",[99,8725,107,103]],[[13255,13255],"disallowed"],[[13256,13256],"mapped",[100,98]],[[13257,13257],"mapped",[103,121]],[[13258,13258],"mapped",[104,97]],[[13259,13259],"mapped",[104,112]],[[13260,13260],"mapped",[105,110]],[[13261,13261],"mapped",[107,107]],[[13262,13262],"mapped",[107,109]],[[13263,13263],"mapped",[107,116]],[[13264,13264],"mapped",[108,109]],[[13265,13265],"mapped",[108,110]],[[13266,13266],"mapped",[108,111,103]],[[13267,13267],"mapped",[108,120]],[[13268,13268],"mapped",[109,98]],[[13269,13269],"mapped",[109,105,108]],[[13270,13270],"mapped",[109,111,108]],[[13271,13271],"mapped",[112,104]],[[13272,13272],"disallowed"],[[13273,13273],"mapped",[112,112,109]],[[13274,13274],"mapped",[112,114]],[[13275,13275],"mapped",[115,114]],[[13276,13276],"mapped",[115,118]],[[13277,13277],"mapped",[119,98]],[[13278,13278],"mapped",[118,8725,109]],[[13279,13279],"mapped",[97,8725,109]],[[13280,13280],"mapped",[49,26085]],[[13281,13281],"mapped",[50,26085]],[[13282,13282],"mapped",[51,26085]],[[13283,13283],"mapped",[52,26085]],[[13284,13284],"mapped",[53,26085]],[[13285,13285],"mapped",[54,26085]],[[13286,13286],"mapped",[55,26085]],[[13287,13287],"mapped",[56,26085]],[[13288,13288],"mapped",[57,26085]],[[13289,13289],"mapped",[49,48,26085]],[[13290,13290],"mapped",[49,49,26085]],[[13291,13291],"mapped",[49,50,26085]],[[13292,13292],"mapped",[49,51,26085]],[[13293,13293],"mapped",[49,52,26085]],[[13294,13294],"mapped",[49,53,26085]],[[13295,13295],"mapped",[49,54,26085]],[[13296,13296],"mapped",[49,55,26085]],[[13297,13297],"mapped",[49,56,26085]],[[13298,13298],"mapped",[49,57,26085]],[[13299,13299],"mapped",[50,48,26085]],[[13300,13300],"mapped",[50,49,26085]],[[13301,13301],"mapped",[50,50,26085]],[[13302,13302],"mapped",[50,51,26085]],[[13303,13303],"mapped",[50,52,26085]],[[13304,13304],"mapped",[50,53,26085]],[[13305,13305],"mapped",[50,54,26085]],[[13306,13306],"mapped",[50,55,26085]],[[13307,13307],"mapped",[50,56,26085]],[[13308,13308],"mapped",[50,57,26085]],[[13309,13309],"mapped",[51,48,26085]],[[13310,13310],"mapped",[51,49,26085]],[[13311,13311],"mapped",[103,97,108]],[[13312,19893],"valid"],[[19894,19903],"disallowed"],[[19904,19967],"valid",[],"NV8"],[[19968,40869],"valid"],[[40870,40891],"valid"],[[40892,40899],"valid"],[[40900,40907],"valid"],[[40908,40908],"valid"],[[40909,40917],"valid"],[[40918,40959],"disallowed"],[[40960,42124],"valid"],[[42125,42127],"disallowed"],[[42128,42145],"valid",[],"NV8"],[[42146,42147],"valid",[],"NV8"],[[42148,42163],"valid",[],"NV8"],[[42164,42164],"valid",[],"NV8"],[[42165,42176],"valid",[],"NV8"],[[42177,42177],"valid",[],"NV8"],[[42178,42180],"valid",[],"NV8"],[[42181,42181],"valid",[],"NV8"],[[42182,42182],"valid",[],"NV8"],[[42183,42191],"disallowed"],[[42192,42237],"valid"],[[42238,42239],"valid",[],"NV8"],[[42240,42508],"valid"],[[42509,42511],"valid",[],"NV8"],[[42512,42539],"valid"],[[42540,42559],"disallowed"],[[42560,42560],"mapped",[42561]],[[42561,42561],"valid"],[[42562,42562],"mapped",[42563]],[[42563,42563],"valid"],[[42564,42564],"mapped",[42565]],[[42565,42565],"valid"],[[42566,42566],"mapped",[42567]],[[42567,42567],"valid"],[[42568,42568],"mapped",[42569]],[[42569,42569],"valid"],[[42570,42570],"mapped",[42571]],[[42571,42571],"valid"],[[42572,42572],"mapped",[42573]],[[42573,42573],"valid"],[[42574,42574],"mapped",[42575]],[[42575,42575],"valid"],[[42576,42576],"mapped",[42577]],[[42577,42577],"valid"],[[42578,42578],"mapped",[42579]],[[42579,42579],"valid"],[[42580,42580],"mapped",[42581]],[[42581,42581],"valid"],[[42582,42582],"mapped",[42583]],[[42583,42583],"valid"],[[42584,42584],"mapped",[42585]],[[42585,42585],"valid"],[[42586,42586],"mapped",[42587]],[[42587,42587],"valid"],[[42588,42588],"mapped",[42589]],[[42589,42589],"valid"],[[42590,42590],"mapped",[42591]],[[42591,42591],"valid"],[[42592,42592],"mapped",[42593]],[[42593,42593],"valid"],[[42594,42594],"mapped",[42595]],[[42595,42595],"valid"],[[42596,42596],"mapped",[42597]],[[42597,42597],"valid"],[[42598,42598],"mapped",[42599]],[[42599,42599],"valid"],[[42600,42600],"mapped",[42601]],[[42601,42601],"valid"],[[42602,42602],"mapped",[42603]],[[42603,42603],"valid"],[[42604,42604],"mapped",[42605]],[[42605,42607],"valid"],[[42608,42611],"valid",[],"NV8"],[[42612,42619],"valid"],[[42620,42621],"valid"],[[42622,42622],"valid",[],"NV8"],[[42623,42623],"valid"],[[42624,42624],"mapped",[42625]],[[42625,42625],"valid"],[[42626,42626],"mapped",[42627]],[[42627,42627],"valid"],[[42628,42628],"mapped",[42629]],[[42629,42629],"valid"],[[42630,42630],"mapped",[42631]],[[42631,42631],"valid"],[[42632,42632],"mapped",[42633]],[[42633,42633],"valid"],[[42634,42634],"mapped",[42635]],[[42635,42635],"valid"],[[42636,42636],"mapped",[42637]],[[42637,42637],"valid"],[[42638,42638],"mapped",[42639]],[[42639,42639],"valid"],[[42640,42640],"mapped",[42641]],[[42641,42641],"valid"],[[42642,42642],"mapped",[42643]],[[42643,42643],"valid"],[[42644,42644],"mapped",[42645]],[[42645,42645],"valid"],[[42646,42646],"mapped",[42647]],[[42647,42647],"valid"],[[42648,42648],"mapped",[42649]],[[42649,42649],"valid"],[[42650,42650],"mapped",[42651]],[[42651,42651],"valid"],[[42652,42652],"mapped",[1098]],[[42653,42653],"mapped",[1100]],[[42654,42654],"valid"],[[42655,42655],"valid"],[[42656,42725],"valid"],[[42726,42735],"valid",[],"NV8"],[[42736,42737],"valid"],[[42738,42743],"valid",[],"NV8"],[[42744,42751],"disallowed"],[[42752,42774],"valid",[],"NV8"],[[42775,42778],"valid"],[[42779,42783],"valid"],[[42784,42785],"valid",[],"NV8"],[[42786,42786],"mapped",[42787]],[[42787,42787],"valid"],[[42788,42788],"mapped",[42789]],[[42789,42789],"valid"],[[42790,42790],"mapped",[42791]],[[42791,42791],"valid"],[[42792,42792],"mapped",[42793]],[[42793,42793],"valid"],[[42794,42794],"mapped",[42795]],[[42795,42795],"valid"],[[42796,42796],"mapped",[42797]],[[42797,42797],"valid"],[[42798,42798],"mapped",[42799]],[[42799,42801],"valid"],[[42802,42802],"mapped",[42803]],[[42803,42803],"valid"],[[42804,42804],"mapped",[42805]],[[42805,42805],"valid"],[[42806,42806],"mapped",[42807]],[[42807,42807],"valid"],[[42808,42808],"mapped",[42809]],[[42809,42809],"valid"],[[42810,42810],"mapped",[42811]],[[42811,42811],"valid"],[[42812,42812],"mapped",[42813]],[[42813,42813],"valid"],[[42814,42814],"mapped",[42815]],[[42815,42815],"valid"],[[42816,42816],"mapped",[42817]],[[42817,42817],"valid"],[[42818,42818],"mapped",[42819]],[[42819,42819],"valid"],[[42820,42820],"mapped",[42821]],[[42821,42821],"valid"],[[42822,42822],"mapped",[42823]],[[42823,42823],"valid"],[[42824,42824],"mapped",[42825]],[[42825,42825],"valid"],[[42826,42826],"mapped",[42827]],[[42827,42827],"valid"],[[42828,42828],"mapped",[42829]],[[42829,42829],"valid"],[[42830,42830],"mapped",[42831]],[[42831,42831],"valid"],[[42832,42832],"mapped",[42833]],[[42833,42833],"valid"],[[42834,42834],"mapped",[42835]],[[42835,42835],"valid"],[[42836,42836],"mapped",[42837]],[[42837,42837],"valid"],[[42838,42838],"mapped",[42839]],[[42839,42839],"valid"],[[42840,42840],"mapped",[42841]],[[42841,42841],"valid"],[[42842,42842],"mapped",[42843]],[[42843,42843],"valid"],[[42844,42844],"mapped",[42845]],[[42845,42845],"valid"],[[42846,42846],"mapped",[42847]],[[42847,42847],"valid"],[[42848,42848],"mapped",[42849]],[[42849,42849],"valid"],[[42850,42850],"mapped",[42851]],[[42851,42851],"valid"],[[42852,42852],"mapped",[42853]],[[42853,42853],"valid"],[[42854,42854],"mapped",[42855]],[[42855,42855],"valid"],[[42856,42856],"mapped",[42857]],[[42857,42857],"valid"],[[42858,42858],"mapped",[42859]],[[42859,42859],"valid"],[[42860,42860],"mapped",[42861]],[[42861,42861],"valid"],[[42862,42862],"mapped",[42863]],[[42863,42863],"valid"],[[42864,42864],"mapped",[42863]],[[42865,42872],"valid"],[[42873,42873],"mapped",[42874]],[[42874,42874],"valid"],[[42875,42875],"mapped",[42876]],[[42876,42876],"valid"],[[42877,42877],"mapped",[7545]],[[42878,42878],"mapped",[42879]],[[42879,42879],"valid"],[[42880,42880],"mapped",[42881]],[[42881,42881],"valid"],[[42882,42882],"mapped",[42883]],[[42883,42883],"valid"],[[42884,42884],"mapped",[42885]],[[42885,42885],"valid"],[[42886,42886],"mapped",[42887]],[[42887,42888],"valid"],[[42889,42890],"valid",[],"NV8"],[[42891,42891],"mapped",[42892]],[[42892,42892],"valid"],[[42893,42893],"mapped",[613]],[[42894,42894],"valid"],[[42895,42895],"valid"],[[42896,42896],"mapped",[42897]],[[42897,42897],"valid"],[[42898,42898],"mapped",[42899]],[[42899,42899],"valid"],[[42900,42901],"valid"],[[42902,42902],"mapped",[42903]],[[42903,42903],"valid"],[[42904,42904],"mapped",[42905]],[[42905,42905],"valid"],[[42906,42906],"mapped",[42907]],[[42907,42907],"valid"],[[42908,42908],"mapped",[42909]],[[42909,42909],"valid"],[[42910,42910],"mapped",[42911]],[[42911,42911],"valid"],[[42912,42912],"mapped",[42913]],[[42913,42913],"valid"],[[42914,42914],"mapped",[42915]],[[42915,42915],"valid"],[[42916,42916],"mapped",[42917]],[[42917,42917],"valid"],[[42918,42918],"mapped",[42919]],[[42919,42919],"valid"],[[42920,42920],"mapped",[42921]],[[42921,42921],"valid"],[[42922,42922],"mapped",[614]],[[42923,42923],"mapped",[604]],[[42924,42924],"mapped",[609]],[[42925,42925],"mapped",[620]],[[42926,42927],"disallowed"],[[42928,42928],"mapped",[670]],[[42929,42929],"mapped",[647]],[[42930,42930],"mapped",[669]],[[42931,42931],"mapped",[43859]],[[42932,42932],"mapped",[42933]],[[42933,42933],"valid"],[[42934,42934],"mapped",[42935]],[[42935,42935],"valid"],[[42936,42998],"disallowed"],[[42999,42999],"valid"],[[43000,43000],"mapped",[295]],[[43001,43001],"mapped",[339]],[[43002,43002],"valid"],[[43003,43007],"valid"],[[43008,43047],"valid"],[[43048,43051],"valid",[],"NV8"],[[43052,43055],"disallowed"],[[43056,43065],"valid",[],"NV8"],[[43066,43071],"disallowed"],[[43072,43123],"valid"],[[43124,43127],"valid",[],"NV8"],[[43128,43135],"disallowed"],[[43136,43204],"valid"],[[43205,43213],"disallowed"],[[43214,43215],"valid",[],"NV8"],[[43216,43225],"valid"],[[43226,43231],"disallowed"],[[43232,43255],"valid"],[[43256,43258],"valid",[],"NV8"],[[43259,43259],"valid"],[[43260,43260],"valid",[],"NV8"],[[43261,43261],"valid"],[[43262,43263],"disallowed"],[[43264,43309],"valid"],[[43310,43311],"valid",[],"NV8"],[[43312,43347],"valid"],[[43348,43358],"disallowed"],[[43359,43359],"valid",[],"NV8"],[[43360,43388],"valid",[],"NV8"],[[43389,43391],"disallowed"],[[43392,43456],"valid"],[[43457,43469],"valid",[],"NV8"],[[43470,43470],"disallowed"],[[43471,43481],"valid"],[[43482,43485],"disallowed"],[[43486,43487],"valid",[],"NV8"],[[43488,43518],"valid"],[[43519,43519],"disallowed"],[[43520,43574],"valid"],[[43575,43583],"disallowed"],[[43584,43597],"valid"],[[43598,43599],"disallowed"],[[43600,43609],"valid"],[[43610,43611],"disallowed"],[[43612,43615],"valid",[],"NV8"],[[43616,43638],"valid"],[[43639,43641],"valid",[],"NV8"],[[43642,43643],"valid"],[[43644,43647],"valid"],[[43648,43714],"valid"],[[43715,43738],"disallowed"],[[43739,43741],"valid"],[[43742,43743],"valid",[],"NV8"],[[43744,43759],"valid"],[[43760,43761],"valid",[],"NV8"],[[43762,43766],"valid"],[[43767,43776],"disallowed"],[[43777,43782],"valid"],[[43783,43784],"disallowed"],[[43785,43790],"valid"],[[43791,43792],"disallowed"],[[43793,43798],"valid"],[[43799,43807],"disallowed"],[[43808,43814],"valid"],[[43815,43815],"disallowed"],[[43816,43822],"valid"],[[43823,43823],"disallowed"],[[43824,43866],"valid"],[[43867,43867],"valid",[],"NV8"],[[43868,43868],"mapped",[42791]],[[43869,43869],"mapped",[43831]],[[43870,43870],"mapped",[619]],[[43871,43871],"mapped",[43858]],[[43872,43875],"valid"],[[43876,43877],"valid"],[[43878,43887],"disallowed"],[[43888,43888],"mapped",[5024]],[[43889,43889],"mapped",[5025]],[[43890,43890],"mapped",[5026]],[[43891,43891],"mapped",[5027]],[[43892,43892],"mapped",[5028]],[[43893,43893],"mapped",[5029]],[[43894,43894],"mapped",[5030]],[[43895,43895],"mapped",[5031]],[[43896,43896],"mapped",[5032]],[[43897,43897],"mapped",[5033]],[[43898,43898],"mapped",[5034]],[[43899,43899],"mapped",[5035]],[[43900,43900],"mapped",[5036]],[[43901,43901],"mapped",[5037]],[[43902,43902],"mapped",[5038]],[[43903,43903],"mapped",[5039]],[[43904,43904],"mapped",[5040]],[[43905,43905],"mapped",[5041]],[[43906,43906],"mapped",[5042]],[[43907,43907],"mapped",[5043]],[[43908,43908],"mapped",[5044]],[[43909,43909],"mapped",[5045]],[[43910,43910],"mapped",[5046]],[[43911,43911],"mapped",[5047]],[[43912,43912],"mapped",[5048]],[[43913,43913],"mapped",[5049]],[[43914,43914],"mapped",[5050]],[[43915,43915],"mapped",[5051]],[[43916,43916],"mapped",[5052]],[[43917,43917],"mapped",[5053]],[[43918,43918],"mapped",[5054]],[[43919,43919],"mapped",[5055]],[[43920,43920],"mapped",[5056]],[[43921,43921],"mapped",[5057]],[[43922,43922],"mapped",[5058]],[[43923,43923],"mapped",[5059]],[[43924,43924],"mapped",[5060]],[[43925,43925],"mapped",[5061]],[[43926,43926],"mapped",[5062]],[[43927,43927],"mapped",[5063]],[[43928,43928],"mapped",[5064]],[[43929,43929],"mapped",[5065]],[[43930,43930],"mapped",[5066]],[[43931,43931],"mapped",[5067]],[[43932,43932],"mapped",[5068]],[[43933,43933],"mapped",[5069]],[[43934,43934],"mapped",[5070]],[[43935,43935],"mapped",[5071]],[[43936,43936],"mapped",[5072]],[[43937,43937],"mapped",[5073]],[[43938,43938],"mapped",[5074]],[[43939,43939],"mapped",[5075]],[[43940,43940],"mapped",[5076]],[[43941,43941],"mapped",[5077]],[[43942,43942],"mapped",[5078]],[[43943,43943],"mapped",[5079]],[[43944,43944],"mapped",[5080]],[[43945,43945],"mapped",[5081]],[[43946,43946],"mapped",[5082]],[[43947,43947],"mapped",[5083]],[[43948,43948],"mapped",[5084]],[[43949,43949],"mapped",[5085]],[[43950,43950],"mapped",[5086]],[[43951,43951],"mapped",[5087]],[[43952,43952],"mapped",[5088]],[[43953,43953],"mapped",[5089]],[[43954,43954],"mapped",[5090]],[[43955,43955],"mapped",[5091]],[[43956,43956],"mapped",[5092]],[[43957,43957],"mapped",[5093]],[[43958,43958],"mapped",[5094]],[[43959,43959],"mapped",[5095]],[[43960,43960],"mapped",[5096]],[[43961,43961],"mapped",[5097]],[[43962,43962],"mapped",[5098]],[[43963,43963],"mapped",[5099]],[[43964,43964],"mapped",[5100]],[[43965,43965],"mapped",[5101]],[[43966,43966],"mapped",[5102]],[[43967,43967],"mapped",[5103]],[[43968,44010],"valid"],[[44011,44011],"valid",[],"NV8"],[[44012,44013],"valid"],[[44014,44015],"disallowed"],[[44016,44025],"valid"],[[44026,44031],"disallowed"],[[44032,55203],"valid"],[[55204,55215],"disallowed"],[[55216,55238],"valid",[],"NV8"],[[55239,55242],"disallowed"],[[55243,55291],"valid",[],"NV8"],[[55292,55295],"disallowed"],[[55296,57343],"disallowed"],[[57344,63743],"disallowed"],[[63744,63744],"mapped",[35912]],[[63745,63745],"mapped",[26356]],[[63746,63746],"mapped",[36554]],[[63747,63747],"mapped",[36040]],[[63748,63748],"mapped",[28369]],[[63749,63749],"mapped",[20018]],[[63750,63750],"mapped",[21477]],[[63751,63752],"mapped",[40860]],[[63753,63753],"mapped",[22865]],[[63754,63754],"mapped",[37329]],[[63755,63755],"mapped",[21895]],[[63756,63756],"mapped",[22856]],[[63757,63757],"mapped",[25078]],[[63758,63758],"mapped",[30313]],[[63759,63759],"mapped",[32645]],[[63760,63760],"mapped",[34367]],[[63761,63761],"mapped",[34746]],[[63762,63762],"mapped",[35064]],[[63763,63763],"mapped",[37007]],[[63764,63764],"mapped",[27138]],[[63765,63765],"mapped",[27931]],[[63766,63766],"mapped",[28889]],[[63767,63767],"mapped",[29662]],[[63768,63768],"mapped",[33853]],[[63769,63769],"mapped",[37226]],[[63770,63770],"mapped",[39409]],[[63771,63771],"mapped",[20098]],[[63772,63772],"mapped",[21365]],[[63773,63773],"mapped",[27396]],[[63774,63774],"mapped",[29211]],[[63775,63775],"mapped",[34349]],[[63776,63776],"mapped",[40478]],[[63777,63777],"mapped",[23888]],[[63778,63778],"mapped",[28651]],[[63779,63779],"mapped",[34253]],[[63780,63780],"mapped",[35172]],[[63781,63781],"mapped",[25289]],[[63782,63782],"mapped",[33240]],[[63783,63783],"mapped",[34847]],[[63784,63784],"mapped",[24266]],[[63785,63785],"mapped",[26391]],[[63786,63786],"mapped",[28010]],[[63787,63787],"mapped",[29436]],[[63788,63788],"mapped",[37070]],[[63789,63789],"mapped",[20358]],[[63790,63790],"mapped",[20919]],[[63791,63791],"mapped",[21214]],[[63792,63792],"mapped",[25796]],[[63793,63793],"mapped",[27347]],[[63794,63794],"mapped",[29200]],[[63795,63795],"mapped",[30439]],[[63796,63796],"mapped",[32769]],[[63797,63797],"mapped",[34310]],[[63798,63798],"mapped",[34396]],[[63799,63799],"mapped",[36335]],[[63800,63800],"mapped",[38706]],[[63801,63801],"mapped",[39791]],[[63802,63802],"mapped",[40442]],[[63803,63803],"mapped",[30860]],[[63804,63804],"mapped",[31103]],[[63805,63805],"mapped",[32160]],[[63806,63806],"mapped",[33737]],[[63807,63807],"mapped",[37636]],[[63808,63808],"mapped",[40575]],[[63809,63809],"mapped",[35542]],[[63810,63810],"mapped",[22751]],[[63811,63811],"mapped",[24324]],[[63812,63812],"mapped",[31840]],[[63813,63813],"mapped",[32894]],[[63814,63814],"mapped",[29282]],[[63815,63815],"mapped",[30922]],[[63816,63816],"mapped",[36034]],[[63817,63817],"mapped",[38647]],[[63818,63818],"mapped",[22744]],[[63819,63819],"mapped",[23650]],[[63820,63820],"mapped",[27155]],[[63821,63821],"mapped",[28122]],[[63822,63822],"mapped",[28431]],[[63823,63823],"mapped",[32047]],[[63824,63824],"mapped",[32311]],[[63825,63825],"mapped",[38475]],[[63826,63826],"mapped",[21202]],[[63827,63827],"mapped",[32907]],[[63828,63828],"mapped",[20956]],[[63829,63829],"mapped",[20940]],[[63830,63830],"mapped",[31260]],[[63831,63831],"mapped",[32190]],[[63832,63832],"mapped",[33777]],[[63833,63833],"mapped",[38517]],[[63834,63834],"mapped",[35712]],[[63835,63835],"mapped",[25295]],[[63836,63836],"mapped",[27138]],[[63837,63837],"mapped",[35582]],[[63838,63838],"mapped",[20025]],[[63839,63839],"mapped",[23527]],[[63840,63840],"mapped",[24594]],[[63841,63841],"mapped",[29575]],[[63842,63842],"mapped",[30064]],[[63843,63843],"mapped",[21271]],[[63844,63844],"mapped",[30971]],[[63845,63845],"mapped",[20415]],[[63846,63846],"mapped",[24489]],[[63847,63847],"mapped",[19981]],[[63848,63848],"mapped",[27852]],[[63849,63849],"mapped",[25976]],[[63850,63850],"mapped",[32034]],[[63851,63851],"mapped",[21443]],[[63852,63852],"mapped",[22622]],[[63853,63853],"mapped",[30465]],[[63854,63854],"mapped",[33865]],[[63855,63855],"mapped",[35498]],[[63856,63856],"mapped",[27578]],[[63857,63857],"mapped",[36784]],[[63858,63858],"mapped",[27784]],[[63859,63859],"mapped",[25342]],[[63860,63860],"mapped",[33509]],[[63861,63861],"mapped",[25504]],[[63862,63862],"mapped",[30053]],[[63863,63863],"mapped",[20142]],[[63864,63864],"mapped",[20841]],[[63865,63865],"mapped",[20937]],[[63866,63866],"mapped",[26753]],[[63867,63867],"mapped",[31975]],[[63868,63868],"mapped",[33391]],[[63869,63869],"mapped",[35538]],[[63870,63870],"mapped",[37327]],[[63871,63871],"mapped",[21237]],[[63872,63872],"mapped",[21570]],[[63873,63873],"mapped",[22899]],[[63874,63874],"mapped",[24300]],[[63875,63875],"mapped",[26053]],[[63876,63876],"mapped",[28670]],[[63877,63877],"mapped",[31018]],[[63878,63878],"mapped",[38317]],[[63879,63879],"mapped",[39530]],[[63880,63880],"mapped",[40599]],[[63881,63881],"mapped",[40654]],[[63882,63882],"mapped",[21147]],[[63883,63883],"mapped",[26310]],[[63884,63884],"mapped",[27511]],[[63885,63885],"mapped",[36706]],[[63886,63886],"mapped",[24180]],[[63887,63887],"mapped",[24976]],[[63888,63888],"mapped",[25088]],[[63889,63889],"mapped",[25754]],[[63890,63890],"mapped",[28451]],[[63891,63891],"mapped",[29001]],[[63892,63892],"mapped",[29833]],[[63893,63893],"mapped",[31178]],[[63894,63894],"mapped",[32244]],[[63895,63895],"mapped",[32879]],[[63896,63896],"mapped",[36646]],[[63897,63897],"mapped",[34030]],[[63898,63898],"mapped",[36899]],[[63899,63899],"mapped",[37706]],[[63900,63900],"mapped",[21015]],[[63901,63901],"mapped",[21155]],[[63902,63902],"mapped",[21693]],[[63903,63903],"mapped",[28872]],[[63904,63904],"mapped",[35010]],[[63905,63905],"mapped",[35498]],[[63906,63906],"mapped",[24265]],[[63907,63907],"mapped",[24565]],[[63908,63908],"mapped",[25467]],[[63909,63909],"mapped",[27566]],[[63910,63910],"mapped",[31806]],[[63911,63911],"mapped",[29557]],[[63912,63912],"mapped",[20196]],[[63913,63913],"mapped",[22265]],[[63914,63914],"mapped",[23527]],[[63915,63915],"mapped",[23994]],[[63916,63916],"mapped",[24604]],[[63917,63917],"mapped",[29618]],[[63918,63918],"mapped",[29801]],[[63919,63919],"mapped",[32666]],[[63920,63920],"mapped",[32838]],[[63921,63921],"mapped",[37428]],[[63922,63922],"mapped",[38646]],[[63923,63923],"mapped",[38728]],[[63924,63924],"mapped",[38936]],[[63925,63925],"mapped",[20363]],[[63926,63926],"mapped",[31150]],[[63927,63927],"mapped",[37300]],[[63928,63928],"mapped",[38584]],[[63929,63929],"mapped",[24801]],[[63930,63930],"mapped",[20102]],[[63931,63931],"mapped",[20698]],[[63932,63932],"mapped",[23534]],[[63933,63933],"mapped",[23615]],[[63934,63934],"mapped",[26009]],[[63935,63935],"mapped",[27138]],[[63936,63936],"mapped",[29134]],[[63937,63937],"mapped",[30274]],[[63938,63938],"mapped",[34044]],[[63939,63939],"mapped",[36988]],[[63940,63940],"mapped",[40845]],[[63941,63941],"mapped",[26248]],[[63942,63942],"mapped",[38446]],[[63943,63943],"mapped",[21129]],[[63944,63944],"mapped",[26491]],[[63945,63945],"mapped",[26611]],[[63946,63946],"mapped",[27969]],[[63947,63947],"mapped",[28316]],[[63948,63948],"mapped",[29705]],[[63949,63949],"mapped",[30041]],[[63950,63950],"mapped",[30827]],[[63951,63951],"mapped",[32016]],[[63952,63952],"mapped",[39006]],[[63953,63953],"mapped",[20845]],[[63954,63954],"mapped",[25134]],[[63955,63955],"mapped",[38520]],[[63956,63956],"mapped",[20523]],[[63957,63957],"mapped",[23833]],[[63958,63958],"mapped",[28138]],[[63959,63959],"mapped",[36650]],[[63960,63960],"mapped",[24459]],[[63961,63961],"mapped",[24900]],[[63962,63962],"mapped",[26647]],[[63963,63963],"mapped",[29575]],[[63964,63964],"mapped",[38534]],[[63965,63965],"mapped",[21033]],[[63966,63966],"mapped",[21519]],[[63967,63967],"mapped",[23653]],[[63968,63968],"mapped",[26131]],[[63969,63969],"mapped",[26446]],[[63970,63970],"mapped",[26792]],[[63971,63971],"mapped",[27877]],[[63972,63972],"mapped",[29702]],[[63973,63973],"mapped",[30178]],[[63974,63974],"mapped",[32633]],[[63975,63975],"mapped",[35023]],[[63976,63976],"mapped",[35041]],[[63977,63977],"mapped",[37324]],[[63978,63978],"mapped",[38626]],[[63979,63979],"mapped",[21311]],[[63980,63980],"mapped",[28346]],[[63981,63981],"mapped",[21533]],[[63982,63982],"mapped",[29136]],[[63983,63983],"mapped",[29848]],[[63984,63984],"mapped",[34298]],[[63985,63985],"mapped",[38563]],[[63986,63986],"mapped",[40023]],[[63987,63987],"mapped",[40607]],[[63988,63988],"mapped",[26519]],[[63989,63989],"mapped",[28107]],[[63990,63990],"mapped",[33256]],[[63991,63991],"mapped",[31435]],[[63992,63992],"mapped",[31520]],[[63993,63993],"mapped",[31890]],[[63994,63994],"mapped",[29376]],[[63995,63995],"mapped",[28825]],[[63996,63996],"mapped",[35672]],[[63997,63997],"mapped",[20160]],[[63998,63998],"mapped",[33590]],[[63999,63999],"mapped",[21050]],[[64000,64000],"mapped",[20999]],[[64001,64001],"mapped",[24230]],[[64002,64002],"mapped",[25299]],[[64003,64003],"mapped",[31958]],[[64004,64004],"mapped",[23429]],[[64005,64005],"mapped",[27934]],[[64006,64006],"mapped",[26292]],[[64007,64007],"mapped",[36667]],[[64008,64008],"mapped",[34892]],[[64009,64009],"mapped",[38477]],[[64010,64010],"mapped",[35211]],[[64011,64011],"mapped",[24275]],[[64012,64012],"mapped",[20800]],[[64013,64013],"mapped",[21952]],[[64014,64015],"valid"],[[64016,64016],"mapped",[22618]],[[64017,64017],"valid"],[[64018,64018],"mapped",[26228]],[[64019,64020],"valid"],[[64021,64021],"mapped",[20958]],[[64022,64022],"mapped",[29482]],[[64023,64023],"mapped",[30410]],[[64024,64024],"mapped",[31036]],[[64025,64025],"mapped",[31070]],[[64026,64026],"mapped",[31077]],[[64027,64027],"mapped",[31119]],[[64028,64028],"mapped",[38742]],[[64029,64029],"mapped",[31934]],[[64030,64030],"mapped",[32701]],[[64031,64031],"valid"],[[64032,64032],"mapped",[34322]],[[64033,64033],"valid"],[[64034,64034],"mapped",[35576]],[[64035,64036],"valid"],[[64037,64037],"mapped",[36920]],[[64038,64038],"mapped",[37117]],[[64039,64041],"valid"],[[64042,64042],"mapped",[39151]],[[64043,64043],"mapped",[39164]],[[64044,64044],"mapped",[39208]],[[64045,64045],"mapped",[40372]],[[64046,64046],"mapped",[37086]],[[64047,64047],"mapped",[38583]],[[64048,64048],"mapped",[20398]],[[64049,64049],"mapped",[20711]],[[64050,64050],"mapped",[20813]],[[64051,64051],"mapped",[21193]],[[64052,64052],"mapped",[21220]],[[64053,64053],"mapped",[21329]],[[64054,64054],"mapped",[21917]],[[64055,64055],"mapped",[22022]],[[64056,64056],"mapped",[22120]],[[64057,64057],"mapped",[22592]],[[64058,64058],"mapped",[22696]],[[64059,64059],"mapped",[23652]],[[64060,64060],"mapped",[23662]],[[64061,64061],"mapped",[24724]],[[64062,64062],"mapped",[24936]],[[64063,64063],"mapped",[24974]],[[64064,64064],"mapped",[25074]],[[64065,64065],"mapped",[25935]],[[64066,64066],"mapped",[26082]],[[64067,64067],"mapped",[26257]],[[64068,64068],"mapped",[26757]],[[64069,64069],"mapped",[28023]],[[64070,64070],"mapped",[28186]],[[64071,64071],"mapped",[28450]],[[64072,64072],"mapped",[29038]],[[64073,64073],"mapped",[29227]],[[64074,64074],"mapped",[29730]],[[64075,64075],"mapped",[30865]],[[64076,64076],"mapped",[31038]],[[64077,64077],"mapped",[31049]],[[64078,64078],"mapped",[31048]],[[64079,64079],"mapped",[31056]],[[64080,64080],"mapped",[31062]],[[64081,64081],"mapped",[31069]],[[64082,64082],"mapped",[31117]],[[64083,64083],"mapped",[31118]],[[64084,64084],"mapped",[31296]],[[64085,64085],"mapped",[31361]],[[64086,64086],"mapped",[31680]],[[64087,64087],"mapped",[32244]],[[64088,64088],"mapped",[32265]],[[64089,64089],"mapped",[32321]],[[64090,64090],"mapped",[32626]],[[64091,64091],"mapped",[32773]],[[64092,64092],"mapped",[33261]],[[64093,64094],"mapped",[33401]],[[64095,64095],"mapped",[33879]],[[64096,64096],"mapped",[35088]],[[64097,64097],"mapped",[35222]],[[64098,64098],"mapped",[35585]],[[64099,64099],"mapped",[35641]],[[64100,64100],"mapped",[36051]],[[64101,64101],"mapped",[36104]],[[64102,64102],"mapped",[36790]],[[64103,64103],"mapped",[36920]],[[64104,64104],"mapped",[38627]],[[64105,64105],"mapped",[38911]],[[64106,64106],"mapped",[38971]],[[64107,64107],"mapped",[24693]],[[64108,64108],"mapped",[148206]],[[64109,64109],"mapped",[33304]],[[64110,64111],"disallowed"],[[64112,64112],"mapped",[20006]],[[64113,64113],"mapped",[20917]],[[64114,64114],"mapped",[20840]],[[64115,64115],"mapped",[20352]],[[64116,64116],"mapped",[20805]],[[64117,64117],"mapped",[20864]],[[64118,64118],"mapped",[21191]],[[64119,64119],"mapped",[21242]],[[64120,64120],"mapped",[21917]],[[64121,64121],"mapped",[21845]],[[64122,64122],"mapped",[21913]],[[64123,64123],"mapped",[21986]],[[64124,64124],"mapped",[22618]],[[64125,64125],"mapped",[22707]],[[64126,64126],"mapped",[22852]],[[64127,64127],"mapped",[22868]],[[64128,64128],"mapped",[23138]],[[64129,64129],"mapped",[23336]],[[64130,64130],"mapped",[24274]],[[64131,64131],"mapped",[24281]],[[64132,64132],"mapped",[24425]],[[64133,64133],"mapped",[24493]],[[64134,64134],"mapped",[24792]],[[64135,64135],"mapped",[24910]],[[64136,64136],"mapped",[24840]],[[64137,64137],"mapped",[24974]],[[64138,64138],"mapped",[24928]],[[64139,64139],"mapped",[25074]],[[64140,64140],"mapped",[25140]],[[64141,64141],"mapped",[25540]],[[64142,64142],"mapped",[25628]],[[64143,64143],"mapped",[25682]],[[64144,64144],"mapped",[25942]],[[64145,64145],"mapped",[26228]],[[64146,64146],"mapped",[26391]],[[64147,64147],"mapped",[26395]],[[64148,64148],"mapped",[26454]],[[64149,64149],"mapped",[27513]],[[64150,64150],"mapped",[27578]],[[64151,64151],"mapped",[27969]],[[64152,64152],"mapped",[28379]],[[64153,64153],"mapped",[28363]],[[64154,64154],"mapped",[28450]],[[64155,64155],"mapped",[28702]],[[64156,64156],"mapped",[29038]],[[64157,64157],"mapped",[30631]],[[64158,64158],"mapped",[29237]],[[64159,64159],"mapped",[29359]],[[64160,64160],"mapped",[29482]],[[64161,64161],"mapped",[29809]],[[64162,64162],"mapped",[29958]],[[64163,64163],"mapped",[30011]],[[64164,64164],"mapped",[30237]],[[64165,64165],"mapped",[30239]],[[64166,64166],"mapped",[30410]],[[64167,64167],"mapped",[30427]],[[64168,64168],"mapped",[30452]],[[64169,64169],"mapped",[30538]],[[64170,64170],"mapped",[30528]],[[64171,64171],"mapped",[30924]],[[64172,64172],"mapped",[31409]],[[64173,64173],"mapped",[31680]],[[64174,64174],"mapped",[31867]],[[64175,64175],"mapped",[32091]],[[64176,64176],"mapped",[32244]],[[64177,64177],"mapped",[32574]],[[64178,64178],"mapped",[32773]],[[64179,64179],"mapped",[33618]],[[64180,64180],"mapped",[33775]],[[64181,64181],"mapped",[34681]],[[64182,64182],"mapped",[35137]],[[64183,64183],"mapped",[35206]],[[64184,64184],"mapped",[35222]],[[64185,64185],"mapped",[35519]],[[64186,64186],"mapped",[35576]],[[64187,64187],"mapped",[35531]],[[64188,64188],"mapped",[35585]],[[64189,64189],"mapped",[35582]],[[64190,64190],"mapped",[35565]],[[64191,64191],"mapped",[35641]],[[64192,64192],"mapped",[35722]],[[64193,64193],"mapped",[36104]],[[64194,64194],"mapped",[36664]],[[64195,64195],"mapped",[36978]],[[64196,64196],"mapped",[37273]],[[64197,64197],"mapped",[37494]],[[64198,64198],"mapped",[38524]],[[64199,64199],"mapped",[38627]],[[64200,64200],"mapped",[38742]],[[64201,64201],"mapped",[38875]],[[64202,64202],"mapped",[38911]],[[64203,64203],"mapped",[38923]],[[64204,64204],"mapped",[38971]],[[64205,64205],"mapped",[39698]],[[64206,64206],"mapped",[40860]],[[64207,64207],"mapped",[141386]],[[64208,64208],"mapped",[141380]],[[64209,64209],"mapped",[144341]],[[64210,64210],"mapped",[15261]],[[64211,64211],"mapped",[16408]],[[64212,64212],"mapped",[16441]],[[64213,64213],"mapped",[152137]],[[64214,64214],"mapped",[154832]],[[64215,64215],"mapped",[163539]],[[64216,64216],"mapped",[40771]],[[64217,64217],"mapped",[40846]],[[64218,64255],"disallowed"],[[64256,64256],"mapped",[102,102]],[[64257,64257],"mapped",[102,105]],[[64258,64258],"mapped",[102,108]],[[64259,64259],"mapped",[102,102,105]],[[64260,64260],"mapped",[102,102,108]],[[64261,64262],"mapped",[115,116]],[[64263,64274],"disallowed"],[[64275,64275],"mapped",[1396,1398]],[[64276,64276],"mapped",[1396,1381]],[[64277,64277],"mapped",[1396,1387]],[[64278,64278],"mapped",[1406,1398]],[[64279,64279],"mapped",[1396,1389]],[[64280,64284],"disallowed"],[[64285,64285],"mapped",[1497,1460]],[[64286,64286],"valid"],[[64287,64287],"mapped",[1522,1463]],[[64288,64288],"mapped",[1506]],[[64289,64289],"mapped",[1488]],[[64290,64290],"mapped",[1491]],[[64291,64291],"mapped",[1492]],[[64292,64292],"mapped",[1499]],[[64293,64293],"mapped",[1500]],[[64294,64294],"mapped",[1501]],[[64295,64295],"mapped",[1512]],[[64296,64296],"mapped",[1514]],[[64297,64297],"disallowed_STD3_mapped",[43]],[[64298,64298],"mapped",[1513,1473]],[[64299,64299],"mapped",[1513,1474]],[[64300,64300],"mapped",[1513,1468,1473]],[[64301,64301],"mapped",[1513,1468,1474]],[[64302,64302],"mapped",[1488,1463]],[[64303,64303],"mapped",[1488,1464]],[[64304,64304],"mapped",[1488,1468]],[[64305,64305],"mapped",[1489,1468]],[[64306,64306],"mapped",[1490,1468]],[[64307,64307],"mapped",[1491,1468]],[[64308,64308],"mapped",[1492,1468]],[[64309,64309],"mapped",[1493,1468]],[[64310,64310],"mapped",[1494,1468]],[[64311,64311],"disallowed"],[[64312,64312],"mapped",[1496,1468]],[[64313,64313],"mapped",[1497,1468]],[[64314,64314],"mapped",[1498,1468]],[[64315,64315],"mapped",[1499,1468]],[[64316,64316],"mapped",[1500,1468]],[[64317,64317],"disallowed"],[[64318,64318],"mapped",[1502,1468]],[[64319,64319],"disallowed"],[[64320,64320],"mapped",[1504,1468]],[[64321,64321],"mapped",[1505,1468]],[[64322,64322],"disallowed"],[[64323,64323],"mapped",[1507,1468]],[[64324,64324],"mapped",[1508,1468]],[[64325,64325],"disallowed"],[[64326,64326],"mapped",[1510,1468]],[[64327,64327],"mapped",[1511,1468]],[[64328,64328],"mapped",[1512,1468]],[[64329,64329],"mapped",[1513,1468]],[[64330,64330],"mapped",[1514,1468]],[[64331,64331],"mapped",[1493,1465]],[[64332,64332],"mapped",[1489,1471]],[[64333,64333],"mapped",[1499,1471]],[[64334,64334],"mapped",[1508,1471]],[[64335,64335],"mapped",[1488,1500]],[[64336,64337],"mapped",[1649]],[[64338,64341],"mapped",[1659]],[[64342,64345],"mapped",[1662]],[[64346,64349],"mapped",[1664]],[[64350,64353],"mapped",[1658]],[[64354,64357],"mapped",[1663]],[[64358,64361],"mapped",[1657]],[[64362,64365],"mapped",[1700]],[[64366,64369],"mapped",[1702]],[[64370,64373],"mapped",[1668]],[[64374,64377],"mapped",[1667]],[[64378,64381],"mapped",[1670]],[[64382,64385],"mapped",[1671]],[[64386,64387],"mapped",[1677]],[[64388,64389],"mapped",[1676]],[[64390,64391],"mapped",[1678]],[[64392,64393],"mapped",[1672]],[[64394,64395],"mapped",[1688]],[[64396,64397],"mapped",[1681]],[[64398,64401],"mapped",[1705]],[[64402,64405],"mapped",[1711]],[[64406,64409],"mapped",[1715]],[[64410,64413],"mapped",[1713]],[[64414,64415],"mapped",[1722]],[[64416,64419],"mapped",[1723]],[[64420,64421],"mapped",[1728]],[[64422,64425],"mapped",[1729]],[[64426,64429],"mapped",[1726]],[[64430,64431],"mapped",[1746]],[[64432,64433],"mapped",[1747]],[[64434,64449],"valid",[],"NV8"],[[64450,64466],"disallowed"],[[64467,64470],"mapped",[1709]],[[64471,64472],"mapped",[1735]],[[64473,64474],"mapped",[1734]],[[64475,64476],"mapped",[1736]],[[64477,64477],"mapped",[1735,1652]],[[64478,64479],"mapped",[1739]],[[64480,64481],"mapped",[1733]],[[64482,64483],"mapped",[1737]],[[64484,64487],"mapped",[1744]],[[64488,64489],"mapped",[1609]],[[64490,64491],"mapped",[1574,1575]],[[64492,64493],"mapped",[1574,1749]],[[64494,64495],"mapped",[1574,1608]],[[64496,64497],"mapped",[1574,1735]],[[64498,64499],"mapped",[1574,1734]],[[64500,64501],"mapped",[1574,1736]],[[64502,64504],"mapped",[1574,1744]],[[64505,64507],"mapped",[1574,1609]],[[64508,64511],"mapped",[1740]],[[64512,64512],"mapped",[1574,1580]],[[64513,64513],"mapped",[1574,1581]],[[64514,64514],"mapped",[1574,1605]],[[64515,64515],"mapped",[1574,1609]],[[64516,64516],"mapped",[1574,1610]],[[64517,64517],"mapped",[1576,1580]],[[64518,64518],"mapped",[1576,1581]],[[64519,64519],"mapped",[1576,1582]],[[64520,64520],"mapped",[1576,1605]],[[64521,64521],"mapped",[1576,1609]],[[64522,64522],"mapped",[1576,1610]],[[64523,64523],"mapped",[1578,1580]],[[64524,64524],"mapped",[1578,1581]],[[64525,64525],"mapped",[1578,1582]],[[64526,64526],"mapped",[1578,1605]],[[64527,64527],"mapped",[1578,1609]],[[64528,64528],"mapped",[1578,1610]],[[64529,64529],"mapped",[1579,1580]],[[64530,64530],"mapped",[1579,1605]],[[64531,64531],"mapped",[1579,1609]],[[64532,64532],"mapped",[1579,1610]],[[64533,64533],"mapped",[1580,1581]],[[64534,64534],"mapped",[1580,1605]],[[64535,64535],"mapped",[1581,1580]],[[64536,64536],"mapped",[1581,1605]],[[64537,64537],"mapped",[1582,1580]],[[64538,64538],"mapped",[1582,1581]],[[64539,64539],"mapped",[1582,1605]],[[64540,64540],"mapped",[1587,1580]],[[64541,64541],"mapped",[1587,1581]],[[64542,64542],"mapped",[1587,1582]],[[64543,64543],"mapped",[1587,1605]],[[64544,64544],"mapped",[1589,1581]],[[64545,64545],"mapped",[1589,1605]],[[64546,64546],"mapped",[1590,1580]],[[64547,64547],"mapped",[1590,1581]],[[64548,64548],"mapped",[1590,1582]],[[64549,64549],"mapped",[1590,1605]],[[64550,64550],"mapped",[1591,1581]],[[64551,64551],"mapped",[1591,1605]],[[64552,64552],"mapped",[1592,1605]],[[64553,64553],"mapped",[1593,1580]],[[64554,64554],"mapped",[1593,1605]],[[64555,64555],"mapped",[1594,1580]],[[64556,64556],"mapped",[1594,1605]],[[64557,64557],"mapped",[1601,1580]],[[64558,64558],"mapped",[1601,1581]],[[64559,64559],"mapped",[1601,1582]],[[64560,64560],"mapped",[1601,1605]],[[64561,64561],"mapped",[1601,1609]],[[64562,64562],"mapped",[1601,1610]],[[64563,64563],"mapped",[1602,1581]],[[64564,64564],"mapped",[1602,1605]],[[64565,64565],"mapped",[1602,1609]],[[64566,64566],"mapped",[1602,1610]],[[64567,64567],"mapped",[1603,1575]],[[64568,64568],"mapped",[1603,1580]],[[64569,64569],"mapped",[1603,1581]],[[64570,64570],"mapped",[1603,1582]],[[64571,64571],"mapped",[1603,1604]],[[64572,64572],"mapped",[1603,1605]],[[64573,64573],"mapped",[1603,1609]],[[64574,64574],"mapped",[1603,1610]],[[64575,64575],"mapped",[1604,1580]],[[64576,64576],"mapped",[1604,1581]],[[64577,64577],"mapped",[1604,1582]],[[64578,64578],"mapped",[1604,1605]],[[64579,64579],"mapped",[1604,1609]],[[64580,64580],"mapped",[1604,1610]],[[64581,64581],"mapped",[1605,1580]],[[64582,64582],"mapped",[1605,1581]],[[64583,64583],"mapped",[1605,1582]],[[64584,64584],"mapped",[1605,1605]],[[64585,64585],"mapped",[1605,1609]],[[64586,64586],"mapped",[1605,1610]],[[64587,64587],"mapped",[1606,1580]],[[64588,64588],"mapped",[1606,1581]],[[64589,64589],"mapped",[1606,1582]],[[64590,64590],"mapped",[1606,1605]],[[64591,64591],"mapped",[1606,1609]],[[64592,64592],"mapped",[1606,1610]],[[64593,64593],"mapped",[1607,1580]],[[64594,64594],"mapped",[1607,1605]],[[64595,64595],"mapped",[1607,1609]],[[64596,64596],"mapped",[1607,1610]],[[64597,64597],"mapped",[1610,1580]],[[64598,64598],"mapped",[1610,1581]],[[64599,64599],"mapped",[1610,1582]],[[64600,64600],"mapped",[1610,1605]],[[64601,64601],"mapped",[1610,1609]],[[64602,64602],"mapped",[1610,1610]],[[64603,64603],"mapped",[1584,1648]],[[64604,64604],"mapped",[1585,1648]],[[64605,64605],"mapped",[1609,1648]],[[64606,64606],"disallowed_STD3_mapped",[32,1612,1617]],[[64607,64607],"disallowed_STD3_mapped",[32,1613,1617]],[[64608,64608],"disallowed_STD3_mapped",[32,1614,1617]],[[64609,64609],"disallowed_STD3_mapped",[32,1615,1617]],[[64610,64610],"disallowed_STD3_mapped",[32,1616,1617]],[[64611,64611],"disallowed_STD3_mapped",[32,1617,1648]],[[64612,64612],"mapped",[1574,1585]],[[64613,64613],"mapped",[1574,1586]],[[64614,64614],"mapped",[1574,1605]],[[64615,64615],"mapped",[1574,1606]],[[64616,64616],"mapped",[1574,1609]],[[64617,64617],"mapped",[1574,1610]],[[64618,64618],"mapped",[1576,1585]],[[64619,64619],"mapped",[1576,1586]],[[64620,64620],"mapped",[1576,1605]],[[64621,64621],"mapped",[1576,1606]],[[64622,64622],"mapped",[1576,1609]],[[64623,64623],"mapped",[1576,1610]],[[64624,64624],"mapped",[1578,1585]],[[64625,64625],"mapped",[1578,1586]],[[64626,64626],"mapped",[1578,1605]],[[64627,64627],"mapped",[1578,1606]],[[64628,64628],"mapped",[1578,1609]],[[64629,64629],"mapped",[1578,1610]],[[64630,64630],"mapped",[1579,1585]],[[64631,64631],"mapped",[1579,1586]],[[64632,64632],"mapped",[1579,1605]],[[64633,64633],"mapped",[1579,1606]],[[64634,64634],"mapped",[1579,1609]],[[64635,64635],"mapped",[1579,1610]],[[64636,64636],"mapped",[1601,1609]],[[64637,64637],"mapped",[1601,1610]],[[64638,64638],"mapped",[1602,1609]],[[64639,64639],"mapped",[1602,1610]],[[64640,64640],"mapped",[1603,1575]],[[64641,64641],"mapped",[1603,1604]],[[64642,64642],"mapped",[1603,1605]],[[64643,64643],"mapped",[1603,1609]],[[64644,64644],"mapped",[1603,1610]],[[64645,64645],"mapped",[1604,1605]],[[64646,64646],"mapped",[1604,1609]],[[64647,64647],"mapped",[1604,1610]],[[64648,64648],"mapped",[1605,1575]],[[64649,64649],"mapped",[1605,1605]],[[64650,64650],"mapped",[1606,1585]],[[64651,64651],"mapped",[1606,1586]],[[64652,64652],"mapped",[1606,1605]],[[64653,64653],"mapped",[1606,1606]],[[64654,64654],"mapped",[1606,1609]],[[64655,64655],"mapped",[1606,1610]],[[64656,64656],"mapped",[1609,1648]],[[64657,64657],"mapped",[1610,1585]],[[64658,64658],"mapped",[1610,1586]],[[64659,64659],"mapped",[1610,1605]],[[64660,64660],"mapped",[1610,1606]],[[64661,64661],"mapped",[1610,1609]],[[64662,64662],"mapped",[1610,1610]],[[64663,64663],"mapped",[1574,1580]],[[64664,64664],"mapped",[1574,1581]],[[64665,64665],"mapped",[1574,1582]],[[64666,64666],"mapped",[1574,1605]],[[64667,64667],"mapped",[1574,1607]],[[64668,64668],"mapped",[1576,1580]],[[64669,64669],"mapped",[1576,1581]],[[64670,64670],"mapped",[1576,1582]],[[64671,64671],"mapped",[1576,1605]],[[64672,64672],"mapped",[1576,1607]],[[64673,64673],"mapped",[1578,1580]],[[64674,64674],"mapped",[1578,1581]],[[64675,64675],"mapped",[1578,1582]],[[64676,64676],"mapped",[1578,1605]],[[64677,64677],"mapped",[1578,1607]],[[64678,64678],"mapped",[1579,1605]],[[64679,64679],"mapped",[1580,1581]],[[64680,64680],"mapped",[1580,1605]],[[64681,64681],"mapped",[1581,1580]],[[64682,64682],"mapped",[1581,1605]],[[64683,64683],"mapped",[1582,1580]],[[64684,64684],"mapped",[1582,1605]],[[64685,64685],"mapped",[1587,1580]],[[64686,64686],"mapped",[1587,1581]],[[64687,64687],"mapped",[1587,1582]],[[64688,64688],"mapped",[1587,1605]],[[64689,64689],"mapped",[1589,1581]],[[64690,64690],"mapped",[1589,1582]],[[64691,64691],"mapped",[1589,1605]],[[64692,64692],"mapped",[1590,1580]],[[64693,64693],"mapped",[1590,1581]],[[64694,64694],"mapped",[1590,1582]],[[64695,64695],"mapped",[1590,1605]],[[64696,64696],"mapped",[1591,1581]],[[64697,64697],"mapped",[1592,1605]],[[64698,64698],"mapped",[1593,1580]],[[64699,64699],"mapped",[1593,1605]],[[64700,64700],"mapped",[1594,1580]],[[64701,64701],"mapped",[1594,1605]],[[64702,64702],"mapped",[1601,1580]],[[64703,64703],"mapped",[1601,1581]],[[64704,64704],"mapped",[1601,1582]],[[64705,64705],"mapped",[1601,1605]],[[64706,64706],"mapped",[1602,1581]],[[64707,64707],"mapped",[1602,1605]],[[64708,64708],"mapped",[1603,1580]],[[64709,64709],"mapped",[1603,1581]],[[64710,64710],"mapped",[1603,1582]],[[64711,64711],"mapped",[1603,1604]],[[64712,64712],"mapped",[1603,1605]],[[64713,64713],"mapped",[1604,1580]],[[64714,64714],"mapped",[1604,1581]],[[64715,64715],"mapped",[1604,1582]],[[64716,64716],"mapped",[1604,1605]],[[64717,64717],"mapped",[1604,1607]],[[64718,64718],"mapped",[1605,1580]],[[64719,64719],"mapped",[1605,1581]],[[64720,64720],"mapped",[1605,1582]],[[64721,64721],"mapped",[1605,1605]],[[64722,64722],"mapped",[1606,1580]],[[64723,64723],"mapped",[1606,1581]],[[64724,64724],"mapped",[1606,1582]],[[64725,64725],"mapped",[1606,1605]],[[64726,64726],"mapped",[1606,1607]],[[64727,64727],"mapped",[1607,1580]],[[64728,64728],"mapped",[1607,1605]],[[64729,64729],"mapped",[1607,1648]],[[64730,64730],"mapped",[1610,1580]],[[64731,64731],"mapped",[1610,1581]],[[64732,64732],"mapped",[1610,1582]],[[64733,64733],"mapped",[1610,1605]],[[64734,64734],"mapped",[1610,1607]],[[64735,64735],"mapped",[1574,1605]],[[64736,64736],"mapped",[1574,1607]],[[64737,64737],"mapped",[1576,1605]],[[64738,64738],"mapped",[1576,1607]],[[64739,64739],"mapped",[1578,1605]],[[64740,64740],"mapped",[1578,1607]],[[64741,64741],"mapped",[1579,1605]],[[64742,64742],"mapped",[1579,1607]],[[64743,64743],"mapped",[1587,1605]],[[64744,64744],"mapped",[1587,1607]],[[64745,64745],"mapped",[1588,1605]],[[64746,64746],"mapped",[1588,1607]],[[64747,64747],"mapped",[1603,1604]],[[64748,64748],"mapped",[1603,1605]],[[64749,64749],"mapped",[1604,1605]],[[64750,64750],"mapped",[1606,1605]],[[64751,64751],"mapped",[1606,1607]],[[64752,64752],"mapped",[1610,1605]],[[64753,64753],"mapped",[1610,1607]],[[64754,64754],"mapped",[1600,1614,1617]],[[64755,64755],"mapped",[1600,1615,1617]],[[64756,64756],"mapped",[1600,1616,1617]],[[64757,64757],"mapped",[1591,1609]],[[64758,64758],"mapped",[1591,1610]],[[64759,64759],"mapped",[1593,1609]],[[64760,64760],"mapped",[1593,1610]],[[64761,64761],"mapped",[1594,1609]],[[64762,64762],"mapped",[1594,1610]],[[64763,64763],"mapped",[1587,1609]],[[64764,64764],"mapped",[1587,1610]],[[64765,64765],"mapped",[1588,1609]],[[64766,64766],"mapped",[1588,1610]],[[64767,64767],"mapped",[1581,1609]],[[64768,64768],"mapped",[1581,1610]],[[64769,64769],"mapped",[1580,1609]],[[64770,64770],"mapped",[1580,1610]],[[64771,64771],"mapped",[1582,1609]],[[64772,64772],"mapped",[1582,1610]],[[64773,64773],"mapped",[1589,1609]],[[64774,64774],"mapped",[1589,1610]],[[64775,64775],"mapped",[1590,1609]],[[64776,64776],"mapped",[1590,1610]],[[64777,64777],"mapped",[1588,1580]],[[64778,64778],"mapped",[1588,1581]],[[64779,64779],"mapped",[1588,1582]],[[64780,64780],"mapped",[1588,1605]],[[64781,64781],"mapped",[1588,1585]],[[64782,64782],"mapped",[1587,1585]],[[64783,64783],"mapped",[1589,1585]],[[64784,64784],"mapped",[1590,1585]],[[64785,64785],"mapped",[1591,1609]],[[64786,64786],"mapped",[1591,1610]],[[64787,64787],"mapped",[1593,1609]],[[64788,64788],"mapped",[1593,1610]],[[64789,64789],"mapped",[1594,1609]],[[64790,64790],"mapped",[1594,1610]],[[64791,64791],"mapped",[1587,1609]],[[64792,64792],"mapped",[1587,1610]],[[64793,64793],"mapped",[1588,1609]],[[64794,64794],"mapped",[1588,1610]],[[64795,64795],"mapped",[1581,1609]],[[64796,64796],"mapped",[1581,1610]],[[64797,64797],"mapped",[1580,1609]],[[64798,64798],"mapped",[1580,1610]],[[64799,64799],"mapped",[1582,1609]],[[64800,64800],"mapped",[1582,1610]],[[64801,64801],"mapped",[1589,1609]],[[64802,64802],"mapped",[1589,1610]],[[64803,64803],"mapped",[1590,1609]],[[64804,64804],"mapped",[1590,1610]],[[64805,64805],"mapped",[1588,1580]],[[64806,64806],"mapped",[1588,1581]],[[64807,64807],"mapped",[1588,1582]],[[64808,64808],"mapped",[1588,1605]],[[64809,64809],"mapped",[1588,1585]],[[64810,64810],"mapped",[1587,1585]],[[64811,64811],"mapped",[1589,1585]],[[64812,64812],"mapped",[1590,1585]],[[64813,64813],"mapped",[1588,1580]],[[64814,64814],"mapped",[1588,1581]],[[64815,64815],"mapped",[1588,1582]],[[64816,64816],"mapped",[1588,1605]],[[64817,64817],"mapped",[1587,1607]],[[64818,64818],"mapped",[1588,1607]],[[64819,64819],"mapped",[1591,1605]],[[64820,64820],"mapped",[1587,1580]],[[64821,64821],"mapped",[1587,1581]],[[64822,64822],"mapped",[1587,1582]],[[64823,64823],"mapped",[1588,1580]],[[64824,64824],"mapped",[1588,1581]],[[64825,64825],"mapped",[1588,1582]],[[64826,64826],"mapped",[1591,1605]],[[64827,64827],"mapped",[1592,1605]],[[64828,64829],"mapped",[1575,1611]],[[64830,64831],"valid",[],"NV8"],[[64832,64847],"disallowed"],[[64848,64848],"mapped",[1578,1580,1605]],[[64849,64850],"mapped",[1578,1581,1580]],[[64851,64851],"mapped",[1578,1581,1605]],[[64852,64852],"mapped",[1578,1582,1605]],[[64853,64853],"mapped",[1578,1605,1580]],[[64854,64854],"mapped",[1578,1605,1581]],[[64855,64855],"mapped",[1578,1605,1582]],[[64856,64857],"mapped",[1580,1605,1581]],[[64858,64858],"mapped",[1581,1605,1610]],[[64859,64859],"mapped",[1581,1605,1609]],[[64860,64860],"mapped",[1587,1581,1580]],[[64861,64861],"mapped",[1587,1580,1581]],[[64862,64862],"mapped",[1587,1580,1609]],[[64863,64864],"mapped",[1587,1605,1581]],[[64865,64865],"mapped",[1587,1605,1580]],[[64866,64867],"mapped",[1587,1605,1605]],[[64868,64869],"mapped",[1589,1581,1581]],[[64870,64870],"mapped",[1589,1605,1605]],[[64871,64872],"mapped",[1588,1581,1605]],[[64873,64873],"mapped",[1588,1580,1610]],[[64874,64875],"mapped",[1588,1605,1582]],[[64876,64877],"mapped",[1588,1605,1605]],[[64878,64878],"mapped",[1590,1581,1609]],[[64879,64880],"mapped",[1590,1582,1605]],[[64881,64882],"mapped",[1591,1605,1581]],[[64883,64883],"mapped",[1591,1605,1605]],[[64884,64884],"mapped",[1591,1605,1610]],[[64885,64885],"mapped",[1593,1580,1605]],[[64886,64887],"mapped",[1593,1605,1605]],[[64888,64888],"mapped",[1593,1605,1609]],[[64889,64889],"mapped",[1594,1605,1605]],[[64890,64890],"mapped",[1594,1605,1610]],[[64891,64891],"mapped",[1594,1605,1609]],[[64892,64893],"mapped",[1601,1582,1605]],[[64894,64894],"mapped",[1602,1605,1581]],[[64895,64895],"mapped",[1602,1605,1605]],[[64896,64896],"mapped",[1604,1581,1605]],[[64897,64897],"mapped",[1604,1581,1610]],[[64898,64898],"mapped",[1604,1581,1609]],[[64899,64900],"mapped",[1604,1580,1580]],[[64901,64902],"mapped",[1604,1582,1605]],[[64903,64904],"mapped",[1604,1605,1581]],[[64905,64905],"mapped",[1605,1581,1580]],[[64906,64906],"mapped",[1605,1581,1605]],[[64907,64907],"mapped",[1605,1581,1610]],[[64908,64908],"mapped",[1605,1580,1581]],[[64909,64909],"mapped",[1605,1580,1605]],[[64910,64910],"mapped",[1605,1582,1580]],[[64911,64911],"mapped",[1605,1582,1605]],[[64912,64913],"disallowed"],[[64914,64914],"mapped",[1605,1580,1582]],[[64915,64915],"mapped",[1607,1605,1580]],[[64916,64916],"mapped",[1607,1605,1605]],[[64917,64917],"mapped",[1606,1581,1605]],[[64918,64918],"mapped",[1606,1581,1609]],[[64919,64920],"mapped",[1606,1580,1605]],[[64921,64921],"mapped",[1606,1580,1609]],[[64922,64922],"mapped",[1606,1605,1610]],[[64923,64923],"mapped",[1606,1605,1609]],[[64924,64925],"mapped",[1610,1605,1605]],[[64926,64926],"mapped",[1576,1582,1610]],[[64927,64927],"mapped",[1578,1580,1610]],[[64928,64928],"mapped",[1578,1580,1609]],[[64929,64929],"mapped",[1578,1582,1610]],[[64930,64930],"mapped",[1578,1582,1609]],[[64931,64931],"mapped",[1578,1605,1610]],[[64932,64932],"mapped",[1578,1605,1609]],[[64933,64933],"mapped",[1580,1605,1610]],[[64934,64934],"mapped",[1580,1581,1609]],[[64935,64935],"mapped",[1580,1605,1609]],[[64936,64936],"mapped",[1587,1582,1609]],[[64937,64937],"mapped",[1589,1581,1610]],[[64938,64938],"mapped",[1588,1581,1610]],[[64939,64939],"mapped",[1590,1581,1610]],[[64940,64940],"mapped",[1604,1580,1610]],[[64941,64941],"mapped",[1604,1605,1610]],[[64942,64942],"mapped",[1610,1581,1610]],[[64943,64943],"mapped",[1610,1580,1610]],[[64944,64944],"mapped",[1610,1605,1610]],[[64945,64945],"mapped",[1605,1605,1610]],[[64946,64946],"mapped",[1602,1605,1610]],[[64947,64947],"mapped",[1606,1581,1610]],[[64948,64948],"mapped",[1602,1605,1581]],[[64949,64949],"mapped",[1604,1581,1605]],[[64950,64950],"mapped",[1593,1605,1610]],[[64951,64951],"mapped",[1603,1605,1610]],[[64952,64952],"mapped",[1606,1580,1581]],[[64953,64953],"mapped",[1605,1582,1610]],[[64954,64954],"mapped",[1604,1580,1605]],[[64955,64955],"mapped",[1603,1605,1605]],[[64956,64956],"mapped",[1604,1580,1605]],[[64957,64957],"mapped",[1606,1580,1581]],[[64958,64958],"mapped",[1580,1581,1610]],[[64959,64959],"mapped",[1581,1580,1610]],[[64960,64960],"mapped",[1605,1580,1610]],[[64961,64961],"mapped",[1601,1605,1610]],[[64962,64962],"mapped",[1576,1581,1610]],[[64963,64963],"mapped",[1603,1605,1605]],[[64964,64964],"mapped",[1593,1580,1605]],[[64965,64965],"mapped",[1589,1605,1605]],[[64966,64966],"mapped",[1587,1582,1610]],[[64967,64967],"mapped",[1606,1580,1610]],[[64968,64975],"disallowed"],[[64976,65007],"disallowed"],[[65008,65008],"mapped",[1589,1604,1746]],[[65009,65009],"mapped",[1602,1604,1746]],[[65010,65010],"mapped",[1575,1604,1604,1607]],[[65011,65011],"mapped",[1575,1603,1576,1585]],[[65012,65012],"mapped",[1605,1581,1605,1583]],[[65013,65013],"mapped",[1589,1604,1593,1605]],[[65014,65014],"mapped",[1585,1587,1608,1604]],[[65015,65015],"mapped",[1593,1604,1610,1607]],[[65016,65016],"mapped",[1608,1587,1604,1605]],[[65017,65017],"mapped",[1589,1604,1609]],[[65018,65018],"disallowed_STD3_mapped",[1589,1604,1609,32,1575,1604,1604,1607,32,1593,1604,1610,1607,32,1608,1587,1604,1605]],[[65019,65019],"disallowed_STD3_mapped",[1580,1604,32,1580,1604,1575,1604,1607]],[[65020,65020],"mapped",[1585,1740,1575,1604]],[[65021,65021],"valid",[],"NV8"],[[65022,65023],"disallowed"],[[65024,65039],"ignored"],[[65040,65040],"disallowed_STD3_mapped",[44]],[[65041,65041],"mapped",[12289]],[[65042,65042],"disallowed"],[[65043,65043],"disallowed_STD3_mapped",[58]],[[65044,65044],"disallowed_STD3_mapped",[59]],[[65045,65045],"disallowed_STD3_mapped",[33]],[[65046,65046],"disallowed_STD3_mapped",[63]],[[65047,65047],"mapped",[12310]],[[65048,65048],"mapped",[12311]],[[65049,65049],"disallowed"],[[65050,65055],"disallowed"],[[65056,65059],"valid"],[[65060,65062],"valid"],[[65063,65069],"valid"],[[65070,65071],"valid"],[[65072,65072],"disallowed"],[[65073,65073],"mapped",[8212]],[[65074,65074],"mapped",[8211]],[[65075,65076],"disallowed_STD3_mapped",[95]],[[65077,65077],"disallowed_STD3_mapped",[40]],[[65078,65078],"disallowed_STD3_mapped",[41]],[[65079,65079],"disallowed_STD3_mapped",[123]],[[65080,65080],"disallowed_STD3_mapped",[125]],[[65081,65081],"mapped",[12308]],[[65082,65082],"mapped",[12309]],[[65083,65083],"mapped",[12304]],[[65084,65084],"mapped",[12305]],[[65085,65085],"mapped",[12298]],[[65086,65086],"mapped",[12299]],[[65087,65087],"mapped",[12296]],[[65088,65088],"mapped",[12297]],[[65089,65089],"mapped",[12300]],[[65090,65090],"mapped",[12301]],[[65091,65091],"mapped",[12302]],[[65092,65092],"mapped",[12303]],[[65093,65094],"valid",[],"NV8"],[[65095,65095],"disallowed_STD3_mapped",[91]],[[65096,65096],"disallowed_STD3_mapped",[93]],[[65097,65100],"disallowed_STD3_mapped",[32,773]],[[65101,65103],"disallowed_STD3_mapped",[95]],[[65104,65104],"disallowed_STD3_mapped",[44]],[[65105,65105],"mapped",[12289]],[[65106,65106],"disallowed"],[[65107,65107],"disallowed"],[[65108,65108],"disallowed_STD3_mapped",[59]],[[65109,65109],"disallowed_STD3_mapped",[58]],[[65110,65110],"disallowed_STD3_mapped",[63]],[[65111,65111],"disallowed_STD3_mapped",[33]],[[65112,65112],"mapped",[8212]],[[65113,65113],"disallowed_STD3_mapped",[40]],[[65114,65114],"disallowed_STD3_mapped",[41]],[[65115,65115],"disallowed_STD3_mapped",[123]],[[65116,65116],"disallowed_STD3_mapped",[125]],[[65117,65117],"mapped",[12308]],[[65118,65118],"mapped",[12309]],[[65119,65119],"disallowed_STD3_mapped",[35]],[[65120,65120],"disallowed_STD3_mapped",[38]],[[65121,65121],"disallowed_STD3_mapped",[42]],[[65122,65122],"disallowed_STD3_mapped",[43]],[[65123,65123],"mapped",[45]],[[65124,65124],"disallowed_STD3_mapped",[60]],[[65125,65125],"disallowed_STD3_mapped",[62]],[[65126,65126],"disallowed_STD3_mapped",[61]],[[65127,65127],"disallowed"],[[65128,65128],"disallowed_STD3_mapped",[92]],[[65129,65129],"disallowed_STD3_mapped",[36]],[[65130,65130],"disallowed_STD3_mapped",[37]],[[65131,65131],"disallowed_STD3_mapped",[64]],[[65132,65135],"disallowed"],[[65136,65136],"disallowed_STD3_mapped",[32,1611]],[[65137,65137],"mapped",[1600,1611]],[[65138,65138],"disallowed_STD3_mapped",[32,1612]],[[65139,65139],"valid"],[[65140,65140],"disallowed_STD3_mapped",[32,1613]],[[65141,65141],"disallowed"],[[65142,65142],"disallowed_STD3_mapped",[32,1614]],[[65143,65143],"mapped",[1600,1614]],[[65144,65144],"disallowed_STD3_mapped",[32,1615]],[[65145,65145],"mapped",[1600,1615]],[[65146,65146],"disallowed_STD3_mapped",[32,1616]],[[65147,65147],"mapped",[1600,1616]],[[65148,65148],"disallowed_STD3_mapped",[32,1617]],[[65149,65149],"mapped",[1600,1617]],[[65150,65150],"disallowed_STD3_mapped",[32,1618]],[[65151,65151],"mapped",[1600,1618]],[[65152,65152],"mapped",[1569]],[[65153,65154],"mapped",[1570]],[[65155,65156],"mapped",[1571]],[[65157,65158],"mapped",[1572]],[[65159,65160],"mapped",[1573]],[[65161,65164],"mapped",[1574]],[[65165,65166],"mapped",[1575]],[[65167,65170],"mapped",[1576]],[[65171,65172],"mapped",[1577]],[[65173,65176],"mapped",[1578]],[[65177,65180],"mapped",[1579]],[[65181,65184],"mapped",[1580]],[[65185,65188],"mapped",[1581]],[[65189,65192],"mapped",[1582]],[[65193,65194],"mapped",[1583]],[[65195,65196],"mapped",[1584]],[[65197,65198],"mapped",[1585]],[[65199,65200],"mapped",[1586]],[[65201,65204],"mapped",[1587]],[[65205,65208],"mapped",[1588]],[[65209,65212],"mapped",[1589]],[[65213,65216],"mapped",[1590]],[[65217,65220],"mapped",[1591]],[[65221,65224],"mapped",[1592]],[[65225,65228],"mapped",[1593]],[[65229,65232],"mapped",[1594]],[[65233,65236],"mapped",[1601]],[[65237,65240],"mapped",[1602]],[[65241,65244],"mapped",[1603]],[[65245,65248],"mapped",[1604]],[[65249,65252],"mapped",[1605]],[[65253,65256],"mapped",[1606]],[[65257,65260],"mapped",[1607]],[[65261,65262],"mapped",[1608]],[[65263,65264],"mapped",[1609]],[[65265,65268],"mapped",[1610]],[[65269,65270],"mapped",[1604,1570]],[[65271,65272],"mapped",[1604,1571]],[[65273,65274],"mapped",[1604,1573]],[[65275,65276],"mapped",[1604,1575]],[[65277,65278],"disallowed"],[[65279,65279],"ignored"],[[65280,65280],"disallowed"],[[65281,65281],"disallowed_STD3_mapped",[33]],[[65282,65282],"disallowed_STD3_mapped",[34]],[[65283,65283],"disallowed_STD3_mapped",[35]],[[65284,65284],"disallowed_STD3_mapped",[36]],[[65285,65285],"disallowed_STD3_mapped",[37]],[[65286,65286],"disallowed_STD3_mapped",[38]],[[65287,65287],"disallowed_STD3_mapped",[39]],[[65288,65288],"disallowed_STD3_mapped",[40]],[[65289,65289],"disallowed_STD3_mapped",[41]],[[65290,65290],"disallowed_STD3_mapped",[42]],[[65291,65291],"disallowed_STD3_mapped",[43]],[[65292,65292],"disallowed_STD3_mapped",[44]],[[65293,65293],"mapped",[45]],[[65294,65294],"mapped",[46]],[[65295,65295],"disallowed_STD3_mapped",[47]],[[65296,65296],"mapped",[48]],[[65297,65297],"mapped",[49]],[[65298,65298],"mapped",[50]],[[65299,65299],"mapped",[51]],[[65300,65300],"mapped",[52]],[[65301,65301],"mapped",[53]],[[65302,65302],"mapped",[54]],[[65303,65303],"mapped",[55]],[[65304,65304],"mapped",[56]],[[65305,65305],"mapped",[57]],[[65306,65306],"disallowed_STD3_mapped",[58]],[[65307,65307],"disallowed_STD3_mapped",[59]],[[65308,65308],"disallowed_STD3_mapped",[60]],[[65309,65309],"disallowed_STD3_mapped",[61]],[[65310,65310],"disallowed_STD3_mapped",[62]],[[65311,65311],"disallowed_STD3_mapped",[63]],[[65312,65312],"disallowed_STD3_mapped",[64]],[[65313,65313],"mapped",[97]],[[65314,65314],"mapped",[98]],[[65315,65315],"mapped",[99]],[[65316,65316],"mapped",[100]],[[65317,65317],"mapped",[101]],[[65318,65318],"mapped",[102]],[[65319,65319],"mapped",[103]],[[65320,65320],"mapped",[104]],[[65321,65321],"mapped",[105]],[[65322,65322],"mapped",[106]],[[65323,65323],"mapped",[107]],[[65324,65324],"mapped",[108]],[[65325,65325],"mapped",[109]],[[65326,65326],"mapped",[110]],[[65327,65327],"mapped",[111]],[[65328,65328],"mapped",[112]],[[65329,65329],"mapped",[113]],[[65330,65330],"mapped",[114]],[[65331,65331],"mapped",[115]],[[65332,65332],"mapped",[116]],[[65333,65333],"mapped",[117]],[[65334,65334],"mapped",[118]],[[65335,65335],"mapped",[119]],[[65336,65336],"mapped",[120]],[[65337,65337],"mapped",[121]],[[65338,65338],"mapped",[122]],[[65339,65339],"disallowed_STD3_mapped",[91]],[[65340,65340],"disallowed_STD3_mapped",[92]],[[65341,65341],"disallowed_STD3_mapped",[93]],[[65342,65342],"disallowed_STD3_mapped",[94]],[[65343,65343],"disallowed_STD3_mapped",[95]],[[65344,65344],"disallowed_STD3_mapped",[96]],[[65345,65345],"mapped",[97]],[[65346,65346],"mapped",[98]],[[65347,65347],"mapped",[99]],[[65348,65348],"mapped",[100]],[[65349,65349],"mapped",[101]],[[65350,65350],"mapped",[102]],[[65351,65351],"mapped",[103]],[[65352,65352],"mapped",[104]],[[65353,65353],"mapped",[105]],[[65354,65354],"mapped",[106]],[[65355,65355],"mapped",[107]],[[65356,65356],"mapped",[108]],[[65357,65357],"mapped",[109]],[[65358,65358],"mapped",[110]],[[65359,65359],"mapped",[111]],[[65360,65360],"mapped",[112]],[[65361,65361],"mapped",[113]],[[65362,65362],"mapped",[114]],[[65363,65363],"mapped",[115]],[[65364,65364],"mapped",[116]],[[65365,65365],"mapped",[117]],[[65366,65366],"mapped",[118]],[[65367,65367],"mapped",[119]],[[65368,65368],"mapped",[120]],[[65369,65369],"mapped",[121]],[[65370,65370],"mapped",[122]],[[65371,65371],"disallowed_STD3_mapped",[123]],[[65372,65372],"disallowed_STD3_mapped",[124]],[[65373,65373],"disallowed_STD3_mapped",[125]],[[65374,65374],"disallowed_STD3_mapped",[126]],[[65375,65375],"mapped",[10629]],[[65376,65376],"mapped",[10630]],[[65377,65377],"mapped",[46]],[[65378,65378],"mapped",[12300]],[[65379,65379],"mapped",[12301]],[[65380,65380],"mapped",[12289]],[[65381,65381],"mapped",[12539]],[[65382,65382],"mapped",[12530]],[[65383,65383],"mapped",[12449]],[[65384,65384],"mapped",[12451]],[[65385,65385],"mapped",[12453]],[[65386,65386],"mapped",[12455]],[[65387,65387],"mapped",[12457]],[[65388,65388],"mapped",[12515]],[[65389,65389],"mapped",[12517]],[[65390,65390],"mapped",[12519]],[[65391,65391],"mapped",[12483]],[[65392,65392],"mapped",[12540]],[[65393,65393],"mapped",[12450]],[[65394,65394],"mapped",[12452]],[[65395,65395],"mapped",[12454]],[[65396,65396],"mapped",[12456]],[[65397,65397],"mapped",[12458]],[[65398,65398],"mapped",[12459]],[[65399,65399],"mapped",[12461]],[[65400,65400],"mapped",[12463]],[[65401,65401],"mapped",[12465]],[[65402,65402],"mapped",[12467]],[[65403,65403],"mapped",[12469]],[[65404,65404],"mapped",[12471]],[[65405,65405],"mapped",[12473]],[[65406,65406],"mapped",[12475]],[[65407,65407],"mapped",[12477]],[[65408,65408],"mapped",[12479]],[[65409,65409],"mapped",[12481]],[[65410,65410],"mapped",[12484]],[[65411,65411],"mapped",[12486]],[[65412,65412],"mapped",[12488]],[[65413,65413],"mapped",[12490]],[[65414,65414],"mapped",[12491]],[[65415,65415],"mapped",[12492]],[[65416,65416],"mapped",[12493]],[[65417,65417],"mapped",[12494]],[[65418,65418],"mapped",[12495]],[[65419,65419],"mapped",[12498]],[[65420,65420],"mapped",[12501]],[[65421,65421],"mapped",[12504]],[[65422,65422],"mapped",[12507]],[[65423,65423],"mapped",[12510]],[[65424,65424],"mapped",[12511]],[[65425,65425],"mapped",[12512]],[[65426,65426],"mapped",[12513]],[[65427,65427],"mapped",[12514]],[[65428,65428],"mapped",[12516]],[[65429,65429],"mapped",[12518]],[[65430,65430],"mapped",[12520]],[[65431,65431],"mapped",[12521]],[[65432,65432],"mapped",[12522]],[[65433,65433],"mapped",[12523]],[[65434,65434],"mapped",[12524]],[[65435,65435],"mapped",[12525]],[[65436,65436],"mapped",[12527]],[[65437,65437],"mapped",[12531]],[[65438,65438],"mapped",[12441]],[[65439,65439],"mapped",[12442]],[[65440,65440],"disallowed"],[[65441,65441],"mapped",[4352]],[[65442,65442],"mapped",[4353]],[[65443,65443],"mapped",[4522]],[[65444,65444],"mapped",[4354]],[[65445,65445],"mapped",[4524]],[[65446,65446],"mapped",[4525]],[[65447,65447],"mapped",[4355]],[[65448,65448],"mapped",[4356]],[[65449,65449],"mapped",[4357]],[[65450,65450],"mapped",[4528]],[[65451,65451],"mapped",[4529]],[[65452,65452],"mapped",[4530]],[[65453,65453],"mapped",[4531]],[[65454,65454],"mapped",[4532]],[[65455,65455],"mapped",[4533]],[[65456,65456],"mapped",[4378]],[[65457,65457],"mapped",[4358]],[[65458,65458],"mapped",[4359]],[[65459,65459],"mapped",[4360]],[[65460,65460],"mapped",[4385]],[[65461,65461],"mapped",[4361]],[[65462,65462],"mapped",[4362]],[[65463,65463],"mapped",[4363]],[[65464,65464],"mapped",[4364]],[[65465,65465],"mapped",[4365]],[[65466,65466],"mapped",[4366]],[[65467,65467],"mapped",[4367]],[[65468,65468],"mapped",[4368]],[[65469,65469],"mapped",[4369]],[[65470,65470],"mapped",[4370]],[[65471,65473],"disallowed"],[[65474,65474],"mapped",[4449]],[[65475,65475],"mapped",[4450]],[[65476,65476],"mapped",[4451]],[[65477,65477],"mapped",[4452]],[[65478,65478],"mapped",[4453]],[[65479,65479],"mapped",[4454]],[[65480,65481],"disallowed"],[[65482,65482],"mapped",[4455]],[[65483,65483],"mapped",[4456]],[[65484,65484],"mapped",[4457]],[[65485,65485],"mapped",[4458]],[[65486,65486],"mapped",[4459]],[[65487,65487],"mapped",[4460]],[[65488,65489],"disallowed"],[[65490,65490],"mapped",[4461]],[[65491,65491],"mapped",[4462]],[[65492,65492],"mapped",[4463]],[[65493,65493],"mapped",[4464]],[[65494,65494],"mapped",[4465]],[[65495,65495],"mapped",[4466]],[[65496,65497],"disallowed"],[[65498,65498],"mapped",[4467]],[[65499,65499],"mapped",[4468]],[[65500,65500],"mapped",[4469]],[[65501,65503],"disallowed"],[[65504,65504],"mapped",[162]],[[65505,65505],"mapped",[163]],[[65506,65506],"mapped",[172]],[[65507,65507],"disallowed_STD3_mapped",[32,772]],[[65508,65508],"mapped",[166]],[[65509,65509],"mapped",[165]],[[65510,65510],"mapped",[8361]],[[65511,65511],"disallowed"],[[65512,65512],"mapped",[9474]],[[65513,65513],"mapped",[8592]],[[65514,65514],"mapped",[8593]],[[65515,65515],"mapped",[8594]],[[65516,65516],"mapped",[8595]],[[65517,65517],"mapped",[9632]],[[65518,65518],"mapped",[9675]],[[65519,65528],"disallowed"],[[65529,65531],"disallowed"],[[65532,65532],"disallowed"],[[65533,65533],"disallowed"],[[65534,65535],"disallowed"],[[65536,65547],"valid"],[[65548,65548],"disallowed"],[[65549,65574],"valid"],[[65575,65575],"disallowed"],[[65576,65594],"valid"],[[65595,65595],"disallowed"],[[65596,65597],"valid"],[[65598,65598],"disallowed"],[[65599,65613],"valid"],[[65614,65615],"disallowed"],[[65616,65629],"valid"],[[65630,65663],"disallowed"],[[65664,65786],"valid"],[[65787,65791],"disallowed"],[[65792,65794],"valid",[],"NV8"],[[65795,65798],"disallowed"],[[65799,65843],"valid",[],"NV8"],[[65844,65846],"disallowed"],[[65847,65855],"valid",[],"NV8"],[[65856,65930],"valid",[],"NV8"],[[65931,65932],"valid",[],"NV8"],[[65933,65935],"disallowed"],[[65936,65947],"valid",[],"NV8"],[[65948,65951],"disallowed"],[[65952,65952],"valid",[],"NV8"],[[65953,65999],"disallowed"],[[66000,66044],"valid",[],"NV8"],[[66045,66045],"valid"],[[66046,66175],"disallowed"],[[66176,66204],"valid"],[[66205,66207],"disallowed"],[[66208,66256],"valid"],[[66257,66271],"disallowed"],[[66272,66272],"valid"],[[66273,66299],"valid",[],"NV8"],[[66300,66303],"disallowed"],[[66304,66334],"valid"],[[66335,66335],"valid"],[[66336,66339],"valid",[],"NV8"],[[66340,66351],"disallowed"],[[66352,66368],"valid"],[[66369,66369],"valid",[],"NV8"],[[66370,66377],"valid"],[[66378,66378],"valid",[],"NV8"],[[66379,66383],"disallowed"],[[66384,66426],"valid"],[[66427,66431],"disallowed"],[[66432,66461],"valid"],[[66462,66462],"disallowed"],[[66463,66463],"valid",[],"NV8"],[[66464,66499],"valid"],[[66500,66503],"disallowed"],[[66504,66511],"valid"],[[66512,66517],"valid",[],"NV8"],[[66518,66559],"disallowed"],[[66560,66560],"mapped",[66600]],[[66561,66561],"mapped",[66601]],[[66562,66562],"mapped",[66602]],[[66563,66563],"mapped",[66603]],[[66564,66564],"mapped",[66604]],[[66565,66565],"mapped",[66605]],[[66566,66566],"mapped",[66606]],[[66567,66567],"mapped",[66607]],[[66568,66568],"mapped",[66608]],[[66569,66569],"mapped",[66609]],[[66570,66570],"mapped",[66610]],[[66571,66571],"mapped",[66611]],[[66572,66572],"mapped",[66612]],[[66573,66573],"mapped",[66613]],[[66574,66574],"mapped",[66614]],[[66575,66575],"mapped",[66615]],[[66576,66576],"mapped",[66616]],[[66577,66577],"mapped",[66617]],[[66578,66578],"mapped",[66618]],[[66579,66579],"mapped",[66619]],[[66580,66580],"mapped",[66620]],[[66581,66581],"mapped",[66621]],[[66582,66582],"mapped",[66622]],[[66583,66583],"mapped",[66623]],[[66584,66584],"mapped",[66624]],[[66585,66585],"mapped",[66625]],[[66586,66586],"mapped",[66626]],[[66587,66587],"mapped",[66627]],[[66588,66588],"mapped",[66628]],[[66589,66589],"mapped",[66629]],[[66590,66590],"mapped",[66630]],[[66591,66591],"mapped",[66631]],[[66592,66592],"mapped",[66632]],[[66593,66593],"mapped",[66633]],[[66594,66594],"mapped",[66634]],[[66595,66595],"mapped",[66635]],[[66596,66596],"mapped",[66636]],[[66597,66597],"mapped",[66637]],[[66598,66598],"mapped",[66638]],[[66599,66599],"mapped",[66639]],[[66600,66637],"valid"],[[66638,66717],"valid"],[[66718,66719],"disallowed"],[[66720,66729],"valid"],[[66730,66815],"disallowed"],[[66816,66855],"valid"],[[66856,66863],"disallowed"],[[66864,66915],"valid"],[[66916,66926],"disallowed"],[[66927,66927],"valid",[],"NV8"],[[66928,67071],"disallowed"],[[67072,67382],"valid"],[[67383,67391],"disallowed"],[[67392,67413],"valid"],[[67414,67423],"disallowed"],[[67424,67431],"valid"],[[67432,67583],"disallowed"],[[67584,67589],"valid"],[[67590,67591],"disallowed"],[[67592,67592],"valid"],[[67593,67593],"disallowed"],[[67594,67637],"valid"],[[67638,67638],"disallowed"],[[67639,67640],"valid"],[[67641,67643],"disallowed"],[[67644,67644],"valid"],[[67645,67646],"disallowed"],[[67647,67647],"valid"],[[67648,67669],"valid"],[[67670,67670],"disallowed"],[[67671,67679],"valid",[],"NV8"],[[67680,67702],"valid"],[[67703,67711],"valid",[],"NV8"],[[67712,67742],"valid"],[[67743,67750],"disallowed"],[[67751,67759],"valid",[],"NV8"],[[67760,67807],"disallowed"],[[67808,67826],"valid"],[[67827,67827],"disallowed"],[[67828,67829],"valid"],[[67830,67834],"disallowed"],[[67835,67839],"valid",[],"NV8"],[[67840,67861],"valid"],[[67862,67865],"valid",[],"NV8"],[[67866,67867],"valid",[],"NV8"],[[67868,67870],"disallowed"],[[67871,67871],"valid",[],"NV8"],[[67872,67897],"valid"],[[67898,67902],"disallowed"],[[67903,67903],"valid",[],"NV8"],[[67904,67967],"disallowed"],[[67968,68023],"valid"],[[68024,68027],"disallowed"],[[68028,68029],"valid",[],"NV8"],[[68030,68031],"valid"],[[68032,68047],"valid",[],"NV8"],[[68048,68049],"disallowed"],[[68050,68095],"valid",[],"NV8"],[[68096,68099],"valid"],[[68100,68100],"disallowed"],[[68101,68102],"valid"],[[68103,68107],"disallowed"],[[68108,68115],"valid"],[[68116,68116],"disallowed"],[[68117,68119],"valid"],[[68120,68120],"disallowed"],[[68121,68147],"valid"],[[68148,68151],"disallowed"],[[68152,68154],"valid"],[[68155,68158],"disallowed"],[[68159,68159],"valid"],[[68160,68167],"valid",[],"NV8"],[[68168,68175],"disallowed"],[[68176,68184],"valid",[],"NV8"],[[68185,68191],"disallowed"],[[68192,68220],"valid"],[[68221,68223],"valid",[],"NV8"],[[68224,68252],"valid"],[[68253,68255],"valid",[],"NV8"],[[68256,68287],"disallowed"],[[68288,68295],"valid"],[[68296,68296],"valid",[],"NV8"],[[68297,68326],"valid"],[[68327,68330],"disallowed"],[[68331,68342],"valid",[],"NV8"],[[68343,68351],"disallowed"],[[68352,68405],"valid"],[[68406,68408],"disallowed"],[[68409,68415],"valid",[],"NV8"],[[68416,68437],"valid"],[[68438,68439],"disallowed"],[[68440,68447],"valid",[],"NV8"],[[68448,68466],"valid"],[[68467,68471],"disallowed"],[[68472,68479],"valid",[],"NV8"],[[68480,68497],"valid"],[[68498,68504],"disallowed"],[[68505,68508],"valid",[],"NV8"],[[68509,68520],"disallowed"],[[68521,68527],"valid",[],"NV8"],[[68528,68607],"disallowed"],[[68608,68680],"valid"],[[68681,68735],"disallowed"],[[68736,68736],"mapped",[68800]],[[68737,68737],"mapped",[68801]],[[68738,68738],"mapped",[68802]],[[68739,68739],"mapped",[68803]],[[68740,68740],"mapped",[68804]],[[68741,68741],"mapped",[68805]],[[68742,68742],"mapped",[68806]],[[68743,68743],"mapped",[68807]],[[68744,68744],"mapped",[68808]],[[68745,68745],"mapped",[68809]],[[68746,68746],"mapped",[68810]],[[68747,68747],"mapped",[68811]],[[68748,68748],"mapped",[68812]],[[68749,68749],"mapped",[68813]],[[68750,68750],"mapped",[68814]],[[68751,68751],"mapped",[68815]],[[68752,68752],"mapped",[68816]],[[68753,68753],"mapped",[68817]],[[68754,68754],"mapped",[68818]],[[68755,68755],"mapped",[68819]],[[68756,68756],"mapped",[68820]],[[68757,68757],"mapped",[68821]],[[68758,68758],"mapped",[68822]],[[68759,68759],"mapped",[68823]],[[68760,68760],"mapped",[68824]],[[68761,68761],"mapped",[68825]],[[68762,68762],"mapped",[68826]],[[68763,68763],"mapped",[68827]],[[68764,68764],"mapped",[68828]],[[68765,68765],"mapped",[68829]],[[68766,68766],"mapped",[68830]],[[68767,68767],"mapped",[68831]],[[68768,68768],"mapped",[68832]],[[68769,68769],"mapped",[68833]],[[68770,68770],"mapped",[68834]],[[68771,68771],"mapped",[68835]],[[68772,68772],"mapped",[68836]],[[68773,68773],"mapped",[68837]],[[68774,68774],"mapped",[68838]],[[68775,68775],"mapped",[68839]],[[68776,68776],"mapped",[68840]],[[68777,68777],"mapped",[68841]],[[68778,68778],"mapped",[68842]],[[68779,68779],"mapped",[68843]],[[68780,68780],"mapped",[68844]],[[68781,68781],"mapped",[68845]],[[68782,68782],"mapped",[68846]],[[68783,68783],"mapped",[68847]],[[68784,68784],"mapped",[68848]],[[68785,68785],"mapped",[68849]],[[68786,68786],"mapped",[68850]],[[68787,68799],"disallowed"],[[68800,68850],"valid"],[[68851,68857],"disallowed"],[[68858,68863],"valid",[],"NV8"],[[68864,69215],"disallowed"],[[69216,69246],"valid",[],"NV8"],[[69247,69631],"disallowed"],[[69632,69702],"valid"],[[69703,69709],"valid",[],"NV8"],[[69710,69713],"disallowed"],[[69714,69733],"valid",[],"NV8"],[[69734,69743],"valid"],[[69744,69758],"disallowed"],[[69759,69759],"valid"],[[69760,69818],"valid"],[[69819,69820],"valid",[],"NV8"],[[69821,69821],"disallowed"],[[69822,69825],"valid",[],"NV8"],[[69826,69839],"disallowed"],[[69840,69864],"valid"],[[69865,69871],"disallowed"],[[69872,69881],"valid"],[[69882,69887],"disallowed"],[[69888,69940],"valid"],[[69941,69941],"disallowed"],[[69942,69951],"valid"],[[69952,69955],"valid",[],"NV8"],[[69956,69967],"disallowed"],[[69968,70003],"valid"],[[70004,70005],"valid",[],"NV8"],[[70006,70006],"valid"],[[70007,70015],"disallowed"],[[70016,70084],"valid"],[[70085,70088],"valid",[],"NV8"],[[70089,70089],"valid",[],"NV8"],[[70090,70092],"valid"],[[70093,70093],"valid",[],"NV8"],[[70094,70095],"disallowed"],[[70096,70105],"valid"],[[70106,70106],"valid"],[[70107,70107],"valid",[],"NV8"],[[70108,70108],"valid"],[[70109,70111],"valid",[],"NV8"],[[70112,70112],"disallowed"],[[70113,70132],"valid",[],"NV8"],[[70133,70143],"disallowed"],[[70144,70161],"valid"],[[70162,70162],"disallowed"],[[70163,70199],"valid"],[[70200,70205],"valid",[],"NV8"],[[70206,70271],"disallowed"],[[70272,70278],"valid"],[[70279,70279],"disallowed"],[[70280,70280],"valid"],[[70281,70281],"disallowed"],[[70282,70285],"valid"],[[70286,70286],"disallowed"],[[70287,70301],"valid"],[[70302,70302],"disallowed"],[[70303,70312],"valid"],[[70313,70313],"valid",[],"NV8"],[[70314,70319],"disallowed"],[[70320,70378],"valid"],[[70379,70383],"disallowed"],[[70384,70393],"valid"],[[70394,70399],"disallowed"],[[70400,70400],"valid"],[[70401,70403],"valid"],[[70404,70404],"disallowed"],[[70405,70412],"valid"],[[70413,70414],"disallowed"],[[70415,70416],"valid"],[[70417,70418],"disallowed"],[[70419,70440],"valid"],[[70441,70441],"disallowed"],[[70442,70448],"valid"],[[70449,70449],"disallowed"],[[70450,70451],"valid"],[[70452,70452],"disallowed"],[[70453,70457],"valid"],[[70458,70459],"disallowed"],[[70460,70468],"valid"],[[70469,70470],"disallowed"],[[70471,70472],"valid"],[[70473,70474],"disallowed"],[[70475,70477],"valid"],[[70478,70479],"disallowed"],[[70480,70480],"valid"],[[70481,70486],"disallowed"],[[70487,70487],"valid"],[[70488,70492],"disallowed"],[[70493,70499],"valid"],[[70500,70501],"disallowed"],[[70502,70508],"valid"],[[70509,70511],"disallowed"],[[70512,70516],"valid"],[[70517,70783],"disallowed"],[[70784,70853],"valid"],[[70854,70854],"valid",[],"NV8"],[[70855,70855],"valid"],[[70856,70863],"disallowed"],[[70864,70873],"valid"],[[70874,71039],"disallowed"],[[71040,71093],"valid"],[[71094,71095],"disallowed"],[[71096,71104],"valid"],[[71105,71113],"valid",[],"NV8"],[[71114,71127],"valid",[],"NV8"],[[71128,71133],"valid"],[[71134,71167],"disallowed"],[[71168,71232],"valid"],[[71233,71235],"valid",[],"NV8"],[[71236,71236],"valid"],[[71237,71247],"disallowed"],[[71248,71257],"valid"],[[71258,71295],"disallowed"],[[71296,71351],"valid"],[[71352,71359],"disallowed"],[[71360,71369],"valid"],[[71370,71423],"disallowed"],[[71424,71449],"valid"],[[71450,71452],"disallowed"],[[71453,71467],"valid"],[[71468,71471],"disallowed"],[[71472,71481],"valid"],[[71482,71487],"valid",[],"NV8"],[[71488,71839],"disallowed"],[[71840,71840],"mapped",[71872]],[[71841,71841],"mapped",[71873]],[[71842,71842],"mapped",[71874]],[[71843,71843],"mapped",[71875]],[[71844,71844],"mapped",[71876]],[[71845,71845],"mapped",[71877]],[[71846,71846],"mapped",[71878]],[[71847,71847],"mapped",[71879]],[[71848,71848],"mapped",[71880]],[[71849,71849],"mapped",[71881]],[[71850,71850],"mapped",[71882]],[[71851,71851],"mapped",[71883]],[[71852,71852],"mapped",[71884]],[[71853,71853],"mapped",[71885]],[[71854,71854],"mapped",[71886]],[[71855,71855],"mapped",[71887]],[[71856,71856],"mapped",[71888]],[[71857,71857],"mapped",[71889]],[[71858,71858],"mapped",[71890]],[[71859,71859],"mapped",[71891]],[[71860,71860],"mapped",[71892]],[[71861,71861],"mapped",[71893]],[[71862,71862],"mapped",[71894]],[[71863,71863],"mapped",[71895]],[[71864,71864],"mapped",[71896]],[[71865,71865],"mapped",[71897]],[[71866,71866],"mapped",[71898]],[[71867,71867],"mapped",[71899]],[[71868,71868],"mapped",[71900]],[[71869,71869],"mapped",[71901]],[[71870,71870],"mapped",[71902]],[[71871,71871],"mapped",[71903]],[[71872,71913],"valid"],[[71914,71922],"valid",[],"NV8"],[[71923,71934],"disallowed"],[[71935,71935],"valid"],[[71936,72383],"disallowed"],[[72384,72440],"valid"],[[72441,73727],"disallowed"],[[73728,74606],"valid"],[[74607,74648],"valid"],[[74649,74649],"valid"],[[74650,74751],"disallowed"],[[74752,74850],"valid",[],"NV8"],[[74851,74862],"valid",[],"NV8"],[[74863,74863],"disallowed"],[[74864,74867],"valid",[],"NV8"],[[74868,74868],"valid",[],"NV8"],[[74869,74879],"disallowed"],[[74880,75075],"valid"],[[75076,77823],"disallowed"],[[77824,78894],"valid"],[[78895,82943],"disallowed"],[[82944,83526],"valid"],[[83527,92159],"disallowed"],[[92160,92728],"valid"],[[92729,92735],"disallowed"],[[92736,92766],"valid"],[[92767,92767],"disallowed"],[[92768,92777],"valid"],[[92778,92781],"disallowed"],[[92782,92783],"valid",[],"NV8"],[[92784,92879],"disallowed"],[[92880,92909],"valid"],[[92910,92911],"disallowed"],[[92912,92916],"valid"],[[92917,92917],"valid",[],"NV8"],[[92918,92927],"disallowed"],[[92928,92982],"valid"],[[92983,92991],"valid",[],"NV8"],[[92992,92995],"valid"],[[92996,92997],"valid",[],"NV8"],[[92998,93007],"disallowed"],[[93008,93017],"valid"],[[93018,93018],"disallowed"],[[93019,93025],"valid",[],"NV8"],[[93026,93026],"disallowed"],[[93027,93047],"valid"],[[93048,93052],"disallowed"],[[93053,93071],"valid"],[[93072,93951],"disallowed"],[[93952,94020],"valid"],[[94021,94031],"disallowed"],[[94032,94078],"valid"],[[94079,94094],"disallowed"],[[94095,94111],"valid"],[[94112,110591],"disallowed"],[[110592,110593],"valid"],[[110594,113663],"disallowed"],[[113664,113770],"valid"],[[113771,113775],"disallowed"],[[113776,113788],"valid"],[[113789,113791],"disallowed"],[[113792,113800],"valid"],[[113801,113807],"disallowed"],[[113808,113817],"valid"],[[113818,113819],"disallowed"],[[113820,113820],"valid",[],"NV8"],[[113821,113822],"valid"],[[113823,113823],"valid",[],"NV8"],[[113824,113827],"ignored"],[[113828,118783],"disallowed"],[[118784,119029],"valid",[],"NV8"],[[119030,119039],"disallowed"],[[119040,119078],"valid",[],"NV8"],[[119079,119080],"disallowed"],[[119081,119081],"valid",[],"NV8"],[[119082,119133],"valid",[],"NV8"],[[119134,119134],"mapped",[119127,119141]],[[119135,119135],"mapped",[119128,119141]],[[119136,119136],"mapped",[119128,119141,119150]],[[119137,119137],"mapped",[119128,119141,119151]],[[119138,119138],"mapped",[119128,119141,119152]],[[119139,119139],"mapped",[119128,119141,119153]],[[119140,119140],"mapped",[119128,119141,119154]],[[119141,119154],"valid",[],"NV8"],[[119155,119162],"disallowed"],[[119163,119226],"valid",[],"NV8"],[[119227,119227],"mapped",[119225,119141]],[[119228,119228],"mapped",[119226,119141]],[[119229,119229],"mapped",[119225,119141,119150]],[[119230,119230],"mapped",[119226,119141,119150]],[[119231,119231],"mapped",[119225,119141,119151]],[[119232,119232],"mapped",[119226,119141,119151]],[[119233,119261],"valid",[],"NV8"],[[119262,119272],"valid",[],"NV8"],[[119273,119295],"disallowed"],[[119296,119365],"valid",[],"NV8"],[[119366,119551],"disallowed"],[[119552,119638],"valid",[],"NV8"],[[119639,119647],"disallowed"],[[119648,119665],"valid",[],"NV8"],[[119666,119807],"disallowed"],[[119808,119808],"mapped",[97]],[[119809,119809],"mapped",[98]],[[119810,119810],"mapped",[99]],[[119811,119811],"mapped",[100]],[[119812,119812],"mapped",[101]],[[119813,119813],"mapped",[102]],[[119814,119814],"mapped",[103]],[[119815,119815],"mapped",[104]],[[119816,119816],"mapped",[105]],[[119817,119817],"mapped",[106]],[[119818,119818],"mapped",[107]],[[119819,119819],"mapped",[108]],[[119820,119820],"mapped",[109]],[[119821,119821],"mapped",[110]],[[119822,119822],"mapped",[111]],[[119823,119823],"mapped",[112]],[[119824,119824],"mapped",[113]],[[119825,119825],"mapped",[114]],[[119826,119826],"mapped",[115]],[[119827,119827],"mapped",[116]],[[119828,119828],"mapped",[117]],[[119829,119829],"mapped",[118]],[[119830,119830],"mapped",[119]],[[119831,119831],"mapped",[120]],[[119832,119832],"mapped",[121]],[[119833,119833],"mapped",[122]],[[119834,119834],"mapped",[97]],[[119835,119835],"mapped",[98]],[[119836,119836],"mapped",[99]],[[119837,119837],"mapped",[100]],[[119838,119838],"mapped",[101]],[[119839,119839],"mapped",[102]],[[119840,119840],"mapped",[103]],[[119841,119841],"mapped",[104]],[[119842,119842],"mapped",[105]],[[119843,119843],"mapped",[106]],[[119844,119844],"mapped",[107]],[[119845,119845],"mapped",[108]],[[119846,119846],"mapped",[109]],[[119847,119847],"mapped",[110]],[[119848,119848],"mapped",[111]],[[119849,119849],"mapped",[112]],[[119850,119850],"mapped",[113]],[[119851,119851],"mapped",[114]],[[119852,119852],"mapped",[115]],[[119853,119853],"mapped",[116]],[[119854,119854],"mapped",[117]],[[119855,119855],"mapped",[118]],[[119856,119856],"mapped",[119]],[[119857,119857],"mapped",[120]],[[119858,119858],"mapped",[121]],[[119859,119859],"mapped",[122]],[[119860,119860],"mapped",[97]],[[119861,119861],"mapped",[98]],[[119862,119862],"mapped",[99]],[[119863,119863],"mapped",[100]],[[119864,119864],"mapped",[101]],[[119865,119865],"mapped",[102]],[[119866,119866],"mapped",[103]],[[119867,119867],"mapped",[104]],[[119868,119868],"mapped",[105]],[[119869,119869],"mapped",[106]],[[119870,119870],"mapped",[107]],[[119871,119871],"mapped",[108]],[[119872,119872],"mapped",[109]],[[119873,119873],"mapped",[110]],[[119874,119874],"mapped",[111]],[[119875,119875],"mapped",[112]],[[119876,119876],"mapped",[113]],[[119877,119877],"mapped",[114]],[[119878,119878],"mapped",[115]],[[119879,119879],"mapped",[116]],[[119880,119880],"mapped",[117]],[[119881,119881],"mapped",[118]],[[119882,119882],"mapped",[119]],[[119883,119883],"mapped",[120]],[[119884,119884],"mapped",[121]],[[119885,119885],"mapped",[122]],[[119886,119886],"mapped",[97]],[[119887,119887],"mapped",[98]],[[119888,119888],"mapped",[99]],[[119889,119889],"mapped",[100]],[[119890,119890],"mapped",[101]],[[119891,119891],"mapped",[102]],[[119892,119892],"mapped",[103]],[[119893,119893],"disallowed"],[[119894,119894],"mapped",[105]],[[119895,119895],"mapped",[106]],[[119896,119896],"mapped",[107]],[[119897,119897],"mapped",[108]],[[119898,119898],"mapped",[109]],[[119899,119899],"mapped",[110]],[[119900,119900],"mapped",[111]],[[119901,119901],"mapped",[112]],[[119902,119902],"mapped",[113]],[[119903,119903],"mapped",[114]],[[119904,119904],"mapped",[115]],[[119905,119905],"mapped",[116]],[[119906,119906],"mapped",[117]],[[119907,119907],"mapped",[118]],[[119908,119908],"mapped",[119]],[[119909,119909],"mapped",[120]],[[119910,119910],"mapped",[121]],[[119911,119911],"mapped",[122]],[[119912,119912],"mapped",[97]],[[119913,119913],"mapped",[98]],[[119914,119914],"mapped",[99]],[[119915,119915],"mapped",[100]],[[119916,119916],"mapped",[101]],[[119917,119917],"mapped",[102]],[[119918,119918],"mapped",[103]],[[119919,119919],"mapped",[104]],[[119920,119920],"mapped",[105]],[[119921,119921],"mapped",[106]],[[119922,119922],"mapped",[107]],[[119923,119923],"mapped",[108]],[[119924,119924],"mapped",[109]],[[119925,119925],"mapped",[110]],[[119926,119926],"mapped",[111]],[[119927,119927],"mapped",[112]],[[119928,119928],"mapped",[113]],[[119929,119929],"mapped",[114]],[[119930,119930],"mapped",[115]],[[119931,119931],"mapped",[116]],[[119932,119932],"mapped",[117]],[[119933,119933],"mapped",[118]],[[119934,119934],"mapped",[119]],[[119935,119935],"mapped",[120]],[[119936,119936],"mapped",[121]],[[119937,119937],"mapped",[122]],[[119938,119938],"mapped",[97]],[[119939,119939],"mapped",[98]],[[119940,119940],"mapped",[99]],[[119941,119941],"mapped",[100]],[[119942,119942],"mapped",[101]],[[119943,119943],"mapped",[102]],[[119944,119944],"mapped",[103]],[[119945,119945],"mapped",[104]],[[119946,119946],"mapped",[105]],[[119947,119947],"mapped",[106]],[[119948,119948],"mapped",[107]],[[119949,119949],"mapped",[108]],[[119950,119950],"mapped",[109]],[[119951,119951],"mapped",[110]],[[119952,119952],"mapped",[111]],[[119953,119953],"mapped",[112]],[[119954,119954],"mapped",[113]],[[119955,119955],"mapped",[114]],[[119956,119956],"mapped",[115]],[[119957,119957],"mapped",[116]],[[119958,119958],"mapped",[117]],[[119959,119959],"mapped",[118]],[[119960,119960],"mapped",[119]],[[119961,119961],"mapped",[120]],[[119962,119962],"mapped",[121]],[[119963,119963],"mapped",[122]],[[119964,119964],"mapped",[97]],[[119965,119965],"disallowed"],[[119966,119966],"mapped",[99]],[[119967,119967],"mapped",[100]],[[119968,119969],"disallowed"],[[119970,119970],"mapped",[103]],[[119971,119972],"disallowed"],[[119973,119973],"mapped",[106]],[[119974,119974],"mapped",[107]],[[119975,119976],"disallowed"],[[119977,119977],"mapped",[110]],[[119978,119978],"mapped",[111]],[[119979,119979],"mapped",[112]],[[119980,119980],"mapped",[113]],[[119981,119981],"disallowed"],[[119982,119982],"mapped",[115]],[[119983,119983],"mapped",[116]],[[119984,119984],"mapped",[117]],[[119985,119985],"mapped",[118]],[[119986,119986],"mapped",[119]],[[119987,119987],"mapped",[120]],[[119988,119988],"mapped",[121]],[[119989,119989],"mapped",[122]],[[119990,119990],"mapped",[97]],[[119991,119991],"mapped",[98]],[[119992,119992],"mapped",[99]],[[119993,119993],"mapped",[100]],[[119994,119994],"disallowed"],[[119995,119995],"mapped",[102]],[[119996,119996],"disallowed"],[[119997,119997],"mapped",[104]],[[119998,119998],"mapped",[105]],[[119999,119999],"mapped",[106]],[[120000,120000],"mapped",[107]],[[120001,120001],"mapped",[108]],[[120002,120002],"mapped",[109]],[[120003,120003],"mapped",[110]],[[120004,120004],"disallowed"],[[120005,120005],"mapped",[112]],[[120006,120006],"mapped",[113]],[[120007,120007],"mapped",[114]],[[120008,120008],"mapped",[115]],[[120009,120009],"mapped",[116]],[[120010,120010],"mapped",[117]],[[120011,120011],"mapped",[118]],[[120012,120012],"mapped",[119]],[[120013,120013],"mapped",[120]],[[120014,120014],"mapped",[121]],[[120015,120015],"mapped",[122]],[[120016,120016],"mapped",[97]],[[120017,120017],"mapped",[98]],[[120018,120018],"mapped",[99]],[[120019,120019],"mapped",[100]],[[120020,120020],"mapped",[101]],[[120021,120021],"mapped",[102]],[[120022,120022],"mapped",[103]],[[120023,120023],"mapped",[104]],[[120024,120024],"mapped",[105]],[[120025,120025],"mapped",[106]],[[120026,120026],"mapped",[107]],[[120027,120027],"mapped",[108]],[[120028,120028],"mapped",[109]],[[120029,120029],"mapped",[110]],[[120030,120030],"mapped",[111]],[[120031,120031],"mapped",[112]],[[120032,120032],"mapped",[113]],[[120033,120033],"mapped",[114]],[[120034,120034],"mapped",[115]],[[120035,120035],"mapped",[116]],[[120036,120036],"mapped",[117]],[[120037,120037],"mapped",[118]],[[120038,120038],"mapped",[119]],[[120039,120039],"mapped",[120]],[[120040,120040],"mapped",[121]],[[120041,120041],"mapped",[122]],[[120042,120042],"mapped",[97]],[[120043,120043],"mapped",[98]],[[120044,120044],"mapped",[99]],[[120045,120045],"mapped",[100]],[[120046,120046],"mapped",[101]],[[120047,120047],"mapped",[102]],[[120048,120048],"mapped",[103]],[[120049,120049],"mapped",[104]],[[120050,120050],"mapped",[105]],[[120051,120051],"mapped",[106]],[[120052,120052],"mapped",[107]],[[120053,120053],"mapped",[108]],[[120054,120054],"mapped",[109]],[[120055,120055],"mapped",[110]],[[120056,120056],"mapped",[111]],[[120057,120057],"mapped",[112]],[[120058,120058],"mapped",[113]],[[120059,120059],"mapped",[114]],[[120060,120060],"mapped",[115]],[[120061,120061],"mapped",[116]],[[120062,120062],"mapped",[117]],[[120063,120063],"mapped",[118]],[[120064,120064],"mapped",[119]],[[120065,120065],"mapped",[120]],[[120066,120066],"mapped",[121]],[[120067,120067],"mapped",[122]],[[120068,120068],"mapped",[97]],[[120069,120069],"mapped",[98]],[[120070,120070],"disallowed"],[[120071,120071],"mapped",[100]],[[120072,120072],"mapped",[101]],[[120073,120073],"mapped",[102]],[[120074,120074],"mapped",[103]],[[120075,120076],"disallowed"],[[120077,120077],"mapped",[106]],[[120078,120078],"mapped",[107]],[[120079,120079],"mapped",[108]],[[120080,120080],"mapped",[109]],[[120081,120081],"mapped",[110]],[[120082,120082],"mapped",[111]],[[120083,120083],"mapped",[112]],[[120084,120084],"mapped",[113]],[[120085,120085],"disallowed"],[[120086,120086],"mapped",[115]],[[120087,120087],"mapped",[116]],[[120088,120088],"mapped",[117]],[[120089,120089],"mapped",[118]],[[120090,120090],"mapped",[119]],[[120091,120091],"mapped",[120]],[[120092,120092],"mapped",[121]],[[120093,120093],"disallowed"],[[120094,120094],"mapped",[97]],[[120095,120095],"mapped",[98]],[[120096,120096],"mapped",[99]],[[120097,120097],"mapped",[100]],[[120098,120098],"mapped",[101]],[[120099,120099],"mapped",[102]],[[120100,120100],"mapped",[103]],[[120101,120101],"mapped",[104]],[[120102,120102],"mapped",[105]],[[120103,120103],"mapped",[106]],[[120104,120104],"mapped",[107]],[[120105,120105],"mapped",[108]],[[120106,120106],"mapped",[109]],[[120107,120107],"mapped",[110]],[[120108,120108],"mapped",[111]],[[120109,120109],"mapped",[112]],[[120110,120110],"mapped",[113]],[[120111,120111],"mapped",[114]],[[120112,120112],"mapped",[115]],[[120113,120113],"mapped",[116]],[[120114,120114],"mapped",[117]],[[120115,120115],"mapped",[118]],[[120116,120116],"mapped",[119]],[[120117,120117],"mapped",[120]],[[120118,120118],"mapped",[121]],[[120119,120119],"mapped",[122]],[[120120,120120],"mapped",[97]],[[120121,120121],"mapped",[98]],[[120122,120122],"disallowed"],[[120123,120123],"mapped",[100]],[[120124,120124],"mapped",[101]],[[120125,120125],"mapped",[102]],[[120126,120126],"mapped",[103]],[[120127,120127],"disallowed"],[[120128,120128],"mapped",[105]],[[120129,120129],"mapped",[106]],[[120130,120130],"mapped",[107]],[[120131,120131],"mapped",[108]],[[120132,120132],"mapped",[109]],[[120133,120133],"disallowed"],[[120134,120134],"mapped",[111]],[[120135,120137],"disallowed"],[[120138,120138],"mapped",[115]],[[120139,120139],"mapped",[116]],[[120140,120140],"mapped",[117]],[[120141,120141],"mapped",[118]],[[120142,120142],"mapped",[119]],[[120143,120143],"mapped",[120]],[[120144,120144],"mapped",[121]],[[120145,120145],"disallowed"],[[120146,120146],"mapped",[97]],[[120147,120147],"mapped",[98]],[[120148,120148],"mapped",[99]],[[120149,120149],"mapped",[100]],[[120150,120150],"mapped",[101]],[[120151,120151],"mapped",[102]],[[120152,120152],"mapped",[103]],[[120153,120153],"mapped",[104]],[[120154,120154],"mapped",[105]],[[120155,120155],"mapped",[106]],[[120156,120156],"mapped",[107]],[[120157,120157],"mapped",[108]],[[120158,120158],"mapped",[109]],[[120159,120159],"mapped",[110]],[[120160,120160],"mapped",[111]],[[120161,120161],"mapped",[112]],[[120162,120162],"mapped",[113]],[[120163,120163],"mapped",[114]],[[120164,120164],"mapped",[115]],[[120165,120165],"mapped",[116]],[[120166,120166],"mapped",[117]],[[120167,120167],"mapped",[118]],[[120168,120168],"mapped",[119]],[[120169,120169],"mapped",[120]],[[120170,120170],"mapped",[121]],[[120171,120171],"mapped",[122]],[[120172,120172],"mapped",[97]],[[120173,120173],"mapped",[98]],[[120174,120174],"mapped",[99]],[[120175,120175],"mapped",[100]],[[120176,120176],"mapped",[101]],[[120177,120177],"mapped",[102]],[[120178,120178],"mapped",[103]],[[120179,120179],"mapped",[104]],[[120180,120180],"mapped",[105]],[[120181,120181],"mapped",[106]],[[120182,120182],"mapped",[107]],[[120183,120183],"mapped",[108]],[[120184,120184],"mapped",[109]],[[120185,120185],"mapped",[110]],[[120186,120186],"mapped",[111]],[[120187,120187],"mapped",[112]],[[120188,120188],"mapped",[113]],[[120189,120189],"mapped",[114]],[[120190,120190],"mapped",[115]],[[120191,120191],"mapped",[116]],[[120192,120192],"mapped",[117]],[[120193,120193],"mapped",[118]],[[120194,120194],"mapped",[119]],[[120195,120195],"mapped",[120]],[[120196,120196],"mapped",[121]],[[120197,120197],"mapped",[122]],[[120198,120198],"mapped",[97]],[[120199,120199],"mapped",[98]],[[120200,120200],"mapped",[99]],[[120201,120201],"mapped",[100]],[[120202,120202],"mapped",[101]],[[120203,120203],"mapped",[102]],[[120204,120204],"mapped",[103]],[[120205,120205],"mapped",[104]],[[120206,120206],"mapped",[105]],[[120207,120207],"mapped",[106]],[[120208,120208],"mapped",[107]],[[120209,120209],"mapped",[108]],[[120210,120210],"mapped",[109]],[[120211,120211],"mapped",[110]],[[120212,120212],"mapped",[111]],[[120213,120213],"mapped",[112]],[[120214,120214],"mapped",[113]],[[120215,120215],"mapped",[114]],[[120216,120216],"mapped",[115]],[[120217,120217],"mapped",[116]],[[120218,120218],"mapped",[117]],[[120219,120219],"mapped",[118]],[[120220,120220],"mapped",[119]],[[120221,120221],"mapped",[120]],[[120222,120222],"mapped",[121]],[[120223,120223],"mapped",[122]],[[120224,120224],"mapped",[97]],[[120225,120225],"mapped",[98]],[[120226,120226],"mapped",[99]],[[120227,120227],"mapped",[100]],[[120228,120228],"mapped",[101]],[[120229,120229],"mapped",[102]],[[120230,120230],"mapped",[103]],[[120231,120231],"mapped",[104]],[[120232,120232],"mapped",[105]],[[120233,120233],"mapped",[106]],[[120234,120234],"mapped",[107]],[[120235,120235],"mapped",[108]],[[120236,120236],"mapped",[109]],[[120237,120237],"mapped",[110]],[[120238,120238],"mapped",[111]],[[120239,120239],"mapped",[112]],[[120240,120240],"mapped",[113]],[[120241,120241],"mapped",[114]],[[120242,120242],"mapped",[115]],[[120243,120243],"mapped",[116]],[[120244,120244],"mapped",[117]],[[120245,120245],"mapped",[118]],[[120246,120246],"mapped",[119]],[[120247,120247],"mapped",[120]],[[120248,120248],"mapped",[121]],[[120249,120249],"mapped",[122]],[[120250,120250],"mapped",[97]],[[120251,120251],"mapped",[98]],[[120252,120252],"mapped",[99]],[[120253,120253],"mapped",[100]],[[120254,120254],"mapped",[101]],[[120255,120255],"mapped",[102]],[[120256,120256],"mapped",[103]],[[120257,120257],"mapped",[104]],[[120258,120258],"mapped",[105]],[[120259,120259],"mapped",[106]],[[120260,120260],"mapped",[107]],[[120261,120261],"mapped",[108]],[[120262,120262],"mapped",[109]],[[120263,120263],"mapped",[110]],[[120264,120264],"mapped",[111]],[[120265,120265],"mapped",[112]],[[120266,120266],"mapped",[113]],[[120267,120267],"mapped",[114]],[[120268,120268],"mapped",[115]],[[120269,120269],"mapped",[116]],[[120270,120270],"mapped",[117]],[[120271,120271],"mapped",[118]],[[120272,120272],"mapped",[119]],[[120273,120273],"mapped",[120]],[[120274,120274],"mapped",[121]],[[120275,120275],"mapped",[122]],[[120276,120276],"mapped",[97]],[[120277,120277],"mapped",[98]],[[120278,120278],"mapped",[99]],[[120279,120279],"mapped",[100]],[[120280,120280],"mapped",[101]],[[120281,120281],"mapped",[102]],[[120282,120282],"mapped",[103]],[[120283,120283],"mapped",[104]],[[120284,120284],"mapped",[105]],[[120285,120285],"mapped",[106]],[[120286,120286],"mapped",[107]],[[120287,120287],"mapped",[108]],[[120288,120288],"mapped",[109]],[[120289,120289],"mapped",[110]],[[120290,120290],"mapped",[111]],[[120291,120291],"mapped",[112]],[[120292,120292],"mapped",[113]],[[120293,120293],"mapped",[114]],[[120294,120294],"mapped",[115]],[[120295,120295],"mapped",[116]],[[120296,120296],"mapped",[117]],[[120297,120297],"mapped",[118]],[[120298,120298],"mapped",[119]],[[120299,120299],"mapped",[120]],[[120300,120300],"mapped",[121]],[[120301,120301],"mapped",[122]],[[120302,120302],"mapped",[97]],[[120303,120303],"mapped",[98]],[[120304,120304],"mapped",[99]],[[120305,120305],"mapped",[100]],[[120306,120306],"mapped",[101]],[[120307,120307],"mapped",[102]],[[120308,120308],"mapped",[103]],[[120309,120309],"mapped",[104]],[[120310,120310],"mapped",[105]],[[120311,120311],"mapped",[106]],[[120312,120312],"mapped",[107]],[[120313,120313],"mapped",[108]],[[120314,120314],"mapped",[109]],[[120315,120315],"mapped",[110]],[[120316,120316],"mapped",[111]],[[120317,120317],"mapped",[112]],[[120318,120318],"mapped",[113]],[[120319,120319],"mapped",[114]],[[120320,120320],"mapped",[115]],[[120321,120321],"mapped",[116]],[[120322,120322],"mapped",[117]],[[120323,120323],"mapped",[118]],[[120324,120324],"mapped",[119]],[[120325,120325],"mapped",[120]],[[120326,120326],"mapped",[121]],[[120327,120327],"mapped",[122]],[[120328,120328],"mapped",[97]],[[120329,120329],"mapped",[98]],[[120330,120330],"mapped",[99]],[[120331,120331],"mapped",[100]],[[120332,120332],"mapped",[101]],[[120333,120333],"mapped",[102]],[[120334,120334],"mapped",[103]],[[120335,120335],"mapped",[104]],[[120336,120336],"mapped",[105]],[[120337,120337],"mapped",[106]],[[120338,120338],"mapped",[107]],[[120339,120339],"mapped",[108]],[[120340,120340],"mapped",[109]],[[120341,120341],"mapped",[110]],[[120342,120342],"mapped",[111]],[[120343,120343],"mapped",[112]],[[120344,120344],"mapped",[113]],[[120345,120345],"mapped",[114]],[[120346,120346],"mapped",[115]],[[120347,120347],"mapped",[116]],[[120348,120348],"mapped",[117]],[[120349,120349],"mapped",[118]],[[120350,120350],"mapped",[119]],[[120351,120351],"mapped",[120]],[[120352,120352],"mapped",[121]],[[120353,120353],"mapped",[122]],[[120354,120354],"mapped",[97]],[[120355,120355],"mapped",[98]],[[120356,120356],"mapped",[99]],[[120357,120357],"mapped",[100]],[[120358,120358],"mapped",[101]],[[120359,120359],"mapped",[102]],[[120360,120360],"mapped",[103]],[[120361,120361],"mapped",[104]],[[120362,120362],"mapped",[105]],[[120363,120363],"mapped",[106]],[[120364,120364],"mapped",[107]],[[120365,120365],"mapped",[108]],[[120366,120366],"mapped",[109]],[[120367,120367],"mapped",[110]],[[120368,120368],"mapped",[111]],[[120369,120369],"mapped",[112]],[[120370,120370],"mapped",[113]],[[120371,120371],"mapped",[114]],[[120372,120372],"mapped",[115]],[[120373,120373],"mapped",[116]],[[120374,120374],"mapped",[117]],[[120375,120375],"mapped",[118]],[[120376,120376],"mapped",[119]],[[120377,120377],"mapped",[120]],[[120378,120378],"mapped",[121]],[[120379,120379],"mapped",[122]],[[120380,120380],"mapped",[97]],[[120381,120381],"mapped",[98]],[[120382,120382],"mapped",[99]],[[120383,120383],"mapped",[100]],[[120384,120384],"mapped",[101]],[[120385,120385],"mapped",[102]],[[120386,120386],"mapped",[103]],[[120387,120387],"mapped",[104]],[[120388,120388],"mapped",[105]],[[120389,120389],"mapped",[106]],[[120390,120390],"mapped",[107]],[[120391,120391],"mapped",[108]],[[120392,120392],"mapped",[109]],[[120393,120393],"mapped",[110]],[[120394,120394],"mapped",[111]],[[120395,120395],"mapped",[112]],[[120396,120396],"mapped",[113]],[[120397,120397],"mapped",[114]],[[120398,120398],"mapped",[115]],[[120399,120399],"mapped",[116]],[[120400,120400],"mapped",[117]],[[120401,120401],"mapped",[118]],[[120402,120402],"mapped",[119]],[[120403,120403],"mapped",[120]],[[120404,120404],"mapped",[121]],[[120405,120405],"mapped",[122]],[[120406,120406],"mapped",[97]],[[120407,120407],"mapped",[98]],[[120408,120408],"mapped",[99]],[[120409,120409],"mapped",[100]],[[120410,120410],"mapped",[101]],[[120411,120411],"mapped",[102]],[[120412,120412],"mapped",[103]],[[120413,120413],"mapped",[104]],[[120414,120414],"mapped",[105]],[[120415,120415],"mapped",[106]],[[120416,120416],"mapped",[107]],[[120417,120417],"mapped",[108]],[[120418,120418],"mapped",[109]],[[120419,120419],"mapped",[110]],[[120420,120420],"mapped",[111]],[[120421,120421],"mapped",[112]],[[120422,120422],"mapped",[113]],[[120423,120423],"mapped",[114]],[[120424,120424],"mapped",[115]],[[120425,120425],"mapped",[116]],[[120426,120426],"mapped",[117]],[[120427,120427],"mapped",[118]],[[120428,120428],"mapped",[119]],[[120429,120429],"mapped",[120]],[[120430,120430],"mapped",[121]],[[120431,120431],"mapped",[122]],[[120432,120432],"mapped",[97]],[[120433,120433],"mapped",[98]],[[120434,120434],"mapped",[99]],[[120435,120435],"mapped",[100]],[[120436,120436],"mapped",[101]],[[120437,120437],"mapped",[102]],[[120438,120438],"mapped",[103]],[[120439,120439],"mapped",[104]],[[120440,120440],"mapped",[105]],[[120441,120441],"mapped",[106]],[[120442,120442],"mapped",[107]],[[120443,120443],"mapped",[108]],[[120444,120444],"mapped",[109]],[[120445,120445],"mapped",[110]],[[120446,120446],"mapped",[111]],[[120447,120447],"mapped",[112]],[[120448,120448],"mapped",[113]],[[120449,120449],"mapped",[114]],[[120450,120450],"mapped",[115]],[[120451,120451],"mapped",[116]],[[120452,120452],"mapped",[117]],[[120453,120453],"mapped",[118]],[[120454,120454],"mapped",[119]],[[120455,120455],"mapped",[120]],[[120456,120456],"mapped",[121]],[[120457,120457],"mapped",[122]],[[120458,120458],"mapped",[97]],[[120459,120459],"mapped",[98]],[[120460,120460],"mapped",[99]],[[120461,120461],"mapped",[100]],[[120462,120462],"mapped",[101]],[[120463,120463],"mapped",[102]],[[120464,120464],"mapped",[103]],[[120465,120465],"mapped",[104]],[[120466,120466],"mapped",[105]],[[120467,120467],"mapped",[106]],[[120468,120468],"mapped",[107]],[[120469,120469],"mapped",[108]],[[120470,120470],"mapped",[109]],[[120471,120471],"mapped",[110]],[[120472,120472],"mapped",[111]],[[120473,120473],"mapped",[112]],[[120474,120474],"mapped",[113]],[[120475,120475],"mapped",[114]],[[120476,120476],"mapped",[115]],[[120477,120477],"mapped",[116]],[[120478,120478],"mapped",[117]],[[120479,120479],"mapped",[118]],[[120480,120480],"mapped",[119]],[[120481,120481],"mapped",[120]],[[120482,120482],"mapped",[121]],[[120483,120483],"mapped",[122]],[[120484,120484],"mapped",[305]],[[120485,120485],"mapped",[567]],[[120486,120487],"disallowed"],[[120488,120488],"mapped",[945]],[[120489,120489],"mapped",[946]],[[120490,120490],"mapped",[947]],[[120491,120491],"mapped",[948]],[[120492,120492],"mapped",[949]],[[120493,120493],"mapped",[950]],[[120494,120494],"mapped",[951]],[[120495,120495],"mapped",[952]],[[120496,120496],"mapped",[953]],[[120497,120497],"mapped",[954]],[[120498,120498],"mapped",[955]],[[120499,120499],"mapped",[956]],[[120500,120500],"mapped",[957]],[[120501,120501],"mapped",[958]],[[120502,120502],"mapped",[959]],[[120503,120503],"mapped",[960]],[[120504,120504],"mapped",[961]],[[120505,120505],"mapped",[952]],[[120506,120506],"mapped",[963]],[[120507,120507],"mapped",[964]],[[120508,120508],"mapped",[965]],[[120509,120509],"mapped",[966]],[[120510,120510],"mapped",[967]],[[120511,120511],"mapped",[968]],[[120512,120512],"mapped",[969]],[[120513,120513],"mapped",[8711]],[[120514,120514],"mapped",[945]],[[120515,120515],"mapped",[946]],[[120516,120516],"mapped",[947]],[[120517,120517],"mapped",[948]],[[120518,120518],"mapped",[949]],[[120519,120519],"mapped",[950]],[[120520,120520],"mapped",[951]],[[120521,120521],"mapped",[952]],[[120522,120522],"mapped",[953]],[[120523,120523],"mapped",[954]],[[120524,120524],"mapped",[955]],[[120525,120525],"mapped",[956]],[[120526,120526],"mapped",[957]],[[120527,120527],"mapped",[958]],[[120528,120528],"mapped",[959]],[[120529,120529],"mapped",[960]],[[120530,120530],"mapped",[961]],[[120531,120532],"mapped",[963]],[[120533,120533],"mapped",[964]],[[120534,120534],"mapped",[965]],[[120535,120535],"mapped",[966]],[[120536,120536],"mapped",[967]],[[120537,120537],"mapped",[968]],[[120538,120538],"mapped",[969]],[[120539,120539],"mapped",[8706]],[[120540,120540],"mapped",[949]],[[120541,120541],"mapped",[952]],[[120542,120542],"mapped",[954]],[[120543,120543],"mapped",[966]],[[120544,120544],"mapped",[961]],[[120545,120545],"mapped",[960]],[[120546,120546],"mapped",[945]],[[120547,120547],"mapped",[946]],[[120548,120548],"mapped",[947]],[[120549,120549],"mapped",[948]],[[120550,120550],"mapped",[949]],[[120551,120551],"mapped",[950]],[[120552,120552],"mapped",[951]],[[120553,120553],"mapped",[952]],[[120554,120554],"mapped",[953]],[[120555,120555],"mapped",[954]],[[120556,120556],"mapped",[955]],[[120557,120557],"mapped",[956]],[[120558,120558],"mapped",[957]],[[120559,120559],"mapped",[958]],[[120560,120560],"mapped",[959]],[[120561,120561],"mapped",[960]],[[120562,120562],"mapped",[961]],[[120563,120563],"mapped",[952]],[[120564,120564],"mapped",[963]],[[120565,120565],"mapped",[964]],[[120566,120566],"mapped",[965]],[[120567,120567],"mapped",[966]],[[120568,120568],"mapped",[967]],[[120569,120569],"mapped",[968]],[[120570,120570],"mapped",[969]],[[120571,120571],"mapped",[8711]],[[120572,120572],"mapped",[945]],[[120573,120573],"mapped",[946]],[[120574,120574],"mapped",[947]],[[120575,120575],"mapped",[948]],[[120576,120576],"mapped",[949]],[[120577,120577],"mapped",[950]],[[120578,120578],"mapped",[951]],[[120579,120579],"mapped",[952]],[[120580,120580],"mapped",[953]],[[120581,120581],"mapped",[954]],[[120582,120582],"mapped",[955]],[[120583,120583],"mapped",[956]],[[120584,120584],"mapped",[957]],[[120585,120585],"mapped",[958]],[[120586,120586],"mapped",[959]],[[120587,120587],"mapped",[960]],[[120588,120588],"mapped",[961]],[[120589,120590],"mapped",[963]],[[120591,120591],"mapped",[964]],[[120592,120592],"mapped",[965]],[[120593,120593],"mapped",[966]],[[120594,120594],"mapped",[967]],[[120595,120595],"mapped",[968]],[[120596,120596],"mapped",[969]],[[120597,120597],"mapped",[8706]],[[120598,120598],"mapped",[949]],[[120599,120599],"mapped",[952]],[[120600,120600],"mapped",[954]],[[120601,120601],"mapped",[966]],[[120602,120602],"mapped",[961]],[[120603,120603],"mapped",[960]],[[120604,120604],"mapped",[945]],[[120605,120605],"mapped",[946]],[[120606,120606],"mapped",[947]],[[120607,120607],"mapped",[948]],[[120608,120608],"mapped",[949]],[[120609,120609],"mapped",[950]],[[120610,120610],"mapped",[951]],[[120611,120611],"mapped",[952]],[[120612,120612],"mapped",[953]],[[120613,120613],"mapped",[954]],[[120614,120614],"mapped",[955]],[[120615,120615],"mapped",[956]],[[120616,120616],"mapped",[957]],[[120617,120617],"mapped",[958]],[[120618,120618],"mapped",[959]],[[120619,120619],"mapped",[960]],[[120620,120620],"mapped",[961]],[[120621,120621],"mapped",[952]],[[120622,120622],"mapped",[963]],[[120623,120623],"mapped",[964]],[[120624,120624],"mapped",[965]],[[120625,120625],"mapped",[966]],[[120626,120626],"mapped",[967]],[[120627,120627],"mapped",[968]],[[120628,120628],"mapped",[969]],[[120629,120629],"mapped",[8711]],[[120630,120630],"mapped",[945]],[[120631,120631],"mapped",[946]],[[120632,120632],"mapped",[947]],[[120633,120633],"mapped",[948]],[[120634,120634],"mapped",[949]],[[120635,120635],"mapped",[950]],[[120636,120636],"mapped",[951]],[[120637,120637],"mapped",[952]],[[120638,120638],"mapped",[953]],[[120639,120639],"mapped",[954]],[[120640,120640],"mapped",[955]],[[120641,120641],"mapped",[956]],[[120642,120642],"mapped",[957]],[[120643,120643],"mapped",[958]],[[120644,120644],"mapped",[959]],[[120645,120645],"mapped",[960]],[[120646,120646],"mapped",[961]],[[120647,120648],"mapped",[963]],[[120649,120649],"mapped",[964]],[[120650,120650],"mapped",[965]],[[120651,120651],"mapped",[966]],[[120652,120652],"mapped",[967]],[[120653,120653],"mapped",[968]],[[120654,120654],"mapped",[969]],[[120655,120655],"mapped",[8706]],[[120656,120656],"mapped",[949]],[[120657,120657],"mapped",[952]],[[120658,120658],"mapped",[954]],[[120659,120659],"mapped",[966]],[[120660,120660],"mapped",[961]],[[120661,120661],"mapped",[960]],[[120662,120662],"mapped",[945]],[[120663,120663],"mapped",[946]],[[120664,120664],"mapped",[947]],[[120665,120665],"mapped",[948]],[[120666,120666],"mapped",[949]],[[120667,120667],"mapped",[950]],[[120668,120668],"mapped",[951]],[[120669,120669],"mapped",[952]],[[120670,120670],"mapped",[953]],[[120671,120671],"mapped",[954]],[[120672,120672],"mapped",[955]],[[120673,120673],"mapped",[956]],[[120674,120674],"mapped",[957]],[[120675,120675],"mapped",[958]],[[120676,120676],"mapped",[959]],[[120677,120677],"mapped",[960]],[[120678,120678],"mapped",[961]],[[120679,120679],"mapped",[952]],[[120680,120680],"mapped",[963]],[[120681,120681],"mapped",[964]],[[120682,120682],"mapped",[965]],[[120683,120683],"mapped",[966]],[[120684,120684],"mapped",[967]],[[120685,120685],"mapped",[968]],[[120686,120686],"mapped",[969]],[[120687,120687],"mapped",[8711]],[[120688,120688],"mapped",[945]],[[120689,120689],"mapped",[946]],[[120690,120690],"mapped",[947]],[[120691,120691],"mapped",[948]],[[120692,120692],"mapped",[949]],[[120693,120693],"mapped",[950]],[[120694,120694],"mapped",[951]],[[120695,120695],"mapped",[952]],[[120696,120696],"mapped",[953]],[[120697,120697],"mapped",[954]],[[120698,120698],"mapped",[955]],[[120699,120699],"mapped",[956]],[[120700,120700],"mapped",[957]],[[120701,120701],"mapped",[958]],[[120702,120702],"mapped",[959]],[[120703,120703],"mapped",[960]],[[120704,120704],"mapped",[961]],[[120705,120706],"mapped",[963]],[[120707,120707],"mapped",[964]],[[120708,120708],"mapped",[965]],[[120709,120709],"mapped",[966]],[[120710,120710],"mapped",[967]],[[120711,120711],"mapped",[968]],[[120712,120712],"mapped",[969]],[[120713,120713],"mapped",[8706]],[[120714,120714],"mapped",[949]],[[120715,120715],"mapped",[952]],[[120716,120716],"mapped",[954]],[[120717,120717],"mapped",[966]],[[120718,120718],"mapped",[961]],[[120719,120719],"mapped",[960]],[[120720,120720],"mapped",[945]],[[120721,120721],"mapped",[946]],[[120722,120722],"mapped",[947]],[[120723,120723],"mapped",[948]],[[120724,120724],"mapped",[949]],[[120725,120725],"mapped",[950]],[[120726,120726],"mapped",[951]],[[120727,120727],"mapped",[952]],[[120728,120728],"mapped",[953]],[[120729,120729],"mapped",[954]],[[120730,120730],"mapped",[955]],[[120731,120731],"mapped",[956]],[[120732,120732],"mapped",[957]],[[120733,120733],"mapped",[958]],[[120734,120734],"mapped",[959]],[[120735,120735],"mapped",[960]],[[120736,120736],"mapped",[961]],[[120737,120737],"mapped",[952]],[[120738,120738],"mapped",[963]],[[120739,120739],"mapped",[964]],[[120740,120740],"mapped",[965]],[[120741,120741],"mapped",[966]],[[120742,120742],"mapped",[967]],[[120743,120743],"mapped",[968]],[[120744,120744],"mapped",[969]],[[120745,120745],"mapped",[8711]],[[120746,120746],"mapped",[945]],[[120747,120747],"mapped",[946]],[[120748,120748],"mapped",[947]],[[120749,120749],"mapped",[948]],[[120750,120750],"mapped",[949]],[[120751,120751],"mapped",[950]],[[120752,120752],"mapped",[951]],[[120753,120753],"mapped",[952]],[[120754,120754],"mapped",[953]],[[120755,120755],"mapped",[954]],[[120756,120756],"mapped",[955]],[[120757,120757],"mapped",[956]],[[120758,120758],"mapped",[957]],[[120759,120759],"mapped",[958]],[[120760,120760],"mapped",[959]],[[120761,120761],"mapped",[960]],[[120762,120762],"mapped",[961]],[[120763,120764],"mapped",[963]],[[120765,120765],"mapped",[964]],[[120766,120766],"mapped",[965]],[[120767,120767],"mapped",[966]],[[120768,120768],"mapped",[967]],[[120769,120769],"mapped",[968]],[[120770,120770],"mapped",[969]],[[120771,120771],"mapped",[8706]],[[120772,120772],"mapped",[949]],[[120773,120773],"mapped",[952]],[[120774,120774],"mapped",[954]],[[120775,120775],"mapped",[966]],[[120776,120776],"mapped",[961]],[[120777,120777],"mapped",[960]],[[120778,120779],"mapped",[989]],[[120780,120781],"disallowed"],[[120782,120782],"mapped",[48]],[[120783,120783],"mapped",[49]],[[120784,120784],"mapped",[50]],[[120785,120785],"mapped",[51]],[[120786,120786],"mapped",[52]],[[120787,120787],"mapped",[53]],[[120788,120788],"mapped",[54]],[[120789,120789],"mapped",[55]],[[120790,120790],"mapped",[56]],[[120791,120791],"mapped",[57]],[[120792,120792],"mapped",[48]],[[120793,120793],"mapped",[49]],[[120794,120794],"mapped",[50]],[[120795,120795],"mapped",[51]],[[120796,120796],"mapped",[52]],[[120797,120797],"mapped",[53]],[[120798,120798],"mapped",[54]],[[120799,120799],"mapped",[55]],[[120800,120800],"mapped",[56]],[[120801,120801],"mapped",[57]],[[120802,120802],"mapped",[48]],[[120803,120803],"mapped",[49]],[[120804,120804],"mapped",[50]],[[120805,120805],"mapped",[51]],[[120806,120806],"mapped",[52]],[[120807,120807],"mapped",[53]],[[120808,120808],"mapped",[54]],[[120809,120809],"mapped",[55]],[[120810,120810],"mapped",[56]],[[120811,120811],"mapped",[57]],[[120812,120812],"mapped",[48]],[[120813,120813],"mapped",[49]],[[120814,120814],"mapped",[50]],[[120815,120815],"mapped",[51]],[[120816,120816],"mapped",[52]],[[120817,120817],"mapped",[53]],[[120818,120818],"mapped",[54]],[[120819,120819],"mapped",[55]],[[120820,120820],"mapped",[56]],[[120821,120821],"mapped",[57]],[[120822,120822],"mapped",[48]],[[120823,120823],"mapped",[49]],[[120824,120824],"mapped",[50]],[[120825,120825],"mapped",[51]],[[120826,120826],"mapped",[52]],[[120827,120827],"mapped",[53]],[[120828,120828],"mapped",[54]],[[120829,120829],"mapped",[55]],[[120830,120830],"mapped",[56]],[[120831,120831],"mapped",[57]],[[120832,121343],"valid",[],"NV8"],[[121344,121398],"valid"],[[121399,121402],"valid",[],"NV8"],[[121403,121452],"valid"],[[121453,121460],"valid",[],"NV8"],[[121461,121461],"valid"],[[121462,121475],"valid",[],"NV8"],[[121476,121476],"valid"],[[121477,121483],"valid",[],"NV8"],[[121484,121498],"disallowed"],[[121499,121503],"valid"],[[121504,121504],"disallowed"],[[121505,121519],"valid"],[[121520,124927],"disallowed"],[[124928,125124],"valid"],[[125125,125126],"disallowed"],[[125127,125135],"valid",[],"NV8"],[[125136,125142],"valid"],[[125143,126463],"disallowed"],[[126464,126464],"mapped",[1575]],[[126465,126465],"mapped",[1576]],[[126466,126466],"mapped",[1580]],[[126467,126467],"mapped",[1583]],[[126468,126468],"disallowed"],[[126469,126469],"mapped",[1608]],[[126470,126470],"mapped",[1586]],[[126471,126471],"mapped",[1581]],[[126472,126472],"mapped",[1591]],[[126473,126473],"mapped",[1610]],[[126474,126474],"mapped",[1603]],[[126475,126475],"mapped",[1604]],[[126476,126476],"mapped",[1605]],[[126477,126477],"mapped",[1606]],[[126478,126478],"mapped",[1587]],[[126479,126479],"mapped",[1593]],[[126480,126480],"mapped",[1601]],[[126481,126481],"mapped",[1589]],[[126482,126482],"mapped",[1602]],[[126483,126483],"mapped",[1585]],[[126484,126484],"mapped",[1588]],[[126485,126485],"mapped",[1578]],[[126486,126486],"mapped",[1579]],[[126487,126487],"mapped",[1582]],[[126488,126488],"mapped",[1584]],[[126489,126489],"mapped",[1590]],[[126490,126490],"mapped",[1592]],[[126491,126491],"mapped",[1594]],[[126492,126492],"mapped",[1646]],[[126493,126493],"mapped",[1722]],[[126494,126494],"mapped",[1697]],[[126495,126495],"mapped",[1647]],[[126496,126496],"disallowed"],[[126497,126497],"mapped",[1576]],[[126498,126498],"mapped",[1580]],[[126499,126499],"disallowed"],[[126500,126500],"mapped",[1607]],[[126501,126502],"disallowed"],[[126503,126503],"mapped",[1581]],[[126504,126504],"disallowed"],[[126505,126505],"mapped",[1610]],[[126506,126506],"mapped",[1603]],[[126507,126507],"mapped",[1604]],[[126508,126508],"mapped",[1605]],[[126509,126509],"mapped",[1606]],[[126510,126510],"mapped",[1587]],[[126511,126511],"mapped",[1593]],[[126512,126512],"mapped",[1601]],[[126513,126513],"mapped",[1589]],[[126514,126514],"mapped",[1602]],[[126515,126515],"disallowed"],[[126516,126516],"mapped",[1588]],[[126517,126517],"mapped",[1578]],[[126518,126518],"mapped",[1579]],[[126519,126519],"mapped",[1582]],[[126520,126520],"disallowed"],[[126521,126521],"mapped",[1590]],[[126522,126522],"disallowed"],[[126523,126523],"mapped",[1594]],[[126524,126529],"disallowed"],[[126530,126530],"mapped",[1580]],[[126531,126534],"disallowed"],[[126535,126535],"mapped",[1581]],[[126536,126536],"disallowed"],[[126537,126537],"mapped",[1610]],[[126538,126538],"disallowed"],[[126539,126539],"mapped",[1604]],[[126540,126540],"disallowed"],[[126541,126541],"mapped",[1606]],[[126542,126542],"mapped",[1587]],[[126543,126543],"mapped",[1593]],[[126544,126544],"disallowed"],[[126545,126545],"mapped",[1589]],[[126546,126546],"mapped",[1602]],[[126547,126547],"disallowed"],[[126548,126548],"mapped",[1588]],[[126549,126550],"disallowed"],[[126551,126551],"mapped",[1582]],[[126552,126552],"disallowed"],[[126553,126553],"mapped",[1590]],[[126554,126554],"disallowed"],[[126555,126555],"mapped",[1594]],[[126556,126556],"disallowed"],[[126557,126557],"mapped",[1722]],[[126558,126558],"disallowed"],[[126559,126559],"mapped",[1647]],[[126560,126560],"disallowed"],[[126561,126561],"mapped",[1576]],[[126562,126562],"mapped",[1580]],[[126563,126563],"disallowed"],[[126564,126564],"mapped",[1607]],[[126565,126566],"disallowed"],[[126567,126567],"mapped",[1581]],[[126568,126568],"mapped",[1591]],[[126569,126569],"mapped",[1610]],[[126570,126570],"mapped",[1603]],[[126571,126571],"disallowed"],[[126572,126572],"mapped",[1605]],[[126573,126573],"mapped",[1606]],[[126574,126574],"mapped",[1587]],[[126575,126575],"mapped",[1593]],[[126576,126576],"mapped",[1601]],[[126577,126577],"mapped",[1589]],[[126578,126578],"mapped",[1602]],[[126579,126579],"disallowed"],[[126580,126580],"mapped",[1588]],[[126581,126581],"mapped",[1578]],[[126582,126582],"mapped",[1579]],[[126583,126583],"mapped",[1582]],[[126584,126584],"disallowed"],[[126585,126585],"mapped",[1590]],[[126586,126586],"mapped",[1592]],[[126587,126587],"mapped",[1594]],[[126588,126588],"mapped",[1646]],[[126589,126589],"disallowed"],[[126590,126590],"mapped",[1697]],[[126591,126591],"disallowed"],[[126592,126592],"mapped",[1575]],[[126593,126593],"mapped",[1576]],[[126594,126594],"mapped",[1580]],[[126595,126595],"mapped",[1583]],[[126596,126596],"mapped",[1607]],[[126597,126597],"mapped",[1608]],[[126598,126598],"mapped",[1586]],[[126599,126599],"mapped",[1581]],[[126600,126600],"mapped",[1591]],[[126601,126601],"mapped",[1610]],[[126602,126602],"disallowed"],[[126603,126603],"mapped",[1604]],[[126604,126604],"mapped",[1605]],[[126605,126605],"mapped",[1606]],[[126606,126606],"mapped",[1587]],[[126607,126607],"mapped",[1593]],[[126608,126608],"mapped",[1601]],[[126609,126609],"mapped",[1589]],[[126610,126610],"mapped",[1602]],[[126611,126611],"mapped",[1585]],[[126612,126612],"mapped",[1588]],[[126613,126613],"mapped",[1578]],[[126614,126614],"mapped",[1579]],[[126615,126615],"mapped",[1582]],[[126616,126616],"mapped",[1584]],[[126617,126617],"mapped",[1590]],[[126618,126618],"mapped",[1592]],[[126619,126619],"mapped",[1594]],[[126620,126624],"disallowed"],[[126625,126625],"mapped",[1576]],[[126626,126626],"mapped",[1580]],[[126627,126627],"mapped",[1583]],[[126628,126628],"disallowed"],[[126629,126629],"mapped",[1608]],[[126630,126630],"mapped",[1586]],[[126631,126631],"mapped",[1581]],[[126632,126632],"mapped",[1591]],[[126633,126633],"mapped",[1610]],[[126634,126634],"disallowed"],[[126635,126635],"mapped",[1604]],[[126636,126636],"mapped",[1605]],[[126637,126637],"mapped",[1606]],[[126638,126638],"mapped",[1587]],[[126639,126639],"mapped",[1593]],[[126640,126640],"mapped",[1601]],[[126641,126641],"mapped",[1589]],[[126642,126642],"mapped",[1602]],[[126643,126643],"mapped",[1585]],[[126644,126644],"mapped",[1588]],[[126645,126645],"mapped",[1578]],[[126646,126646],"mapped",[1579]],[[126647,126647],"mapped",[1582]],[[126648,126648],"mapped",[1584]],[[126649,126649],"mapped",[1590]],[[126650,126650],"mapped",[1592]],[[126651,126651],"mapped",[1594]],[[126652,126703],"disallowed"],[[126704,126705],"valid",[],"NV8"],[[126706,126975],"disallowed"],[[126976,127019],"valid",[],"NV8"],[[127020,127023],"disallowed"],[[127024,127123],"valid",[],"NV8"],[[127124,127135],"disallowed"],[[127136,127150],"valid",[],"NV8"],[[127151,127152],"disallowed"],[[127153,127166],"valid",[],"NV8"],[[127167,127167],"valid",[],"NV8"],[[127168,127168],"disallowed"],[[127169,127183],"valid",[],"NV8"],[[127184,127184],"disallowed"],[[127185,127199],"valid",[],"NV8"],[[127200,127221],"valid",[],"NV8"],[[127222,127231],"disallowed"],[[127232,127232],"disallowed"],[[127233,127233],"disallowed_STD3_mapped",[48,44]],[[127234,127234],"disallowed_STD3_mapped",[49,44]],[[127235,127235],"disallowed_STD3_mapped",[50,44]],[[127236,127236],"disallowed_STD3_mapped",[51,44]],[[127237,127237],"disallowed_STD3_mapped",[52,44]],[[127238,127238],"disallowed_STD3_mapped",[53,44]],[[127239,127239],"disallowed_STD3_mapped",[54,44]],[[127240,127240],"disallowed_STD3_mapped",[55,44]],[[127241,127241],"disallowed_STD3_mapped",[56,44]],[[127242,127242],"disallowed_STD3_mapped",[57,44]],[[127243,127244],"valid",[],"NV8"],[[127245,127247],"disallowed"],[[127248,127248],"disallowed_STD3_mapped",[40,97,41]],[[127249,127249],"disallowed_STD3_mapped",[40,98,41]],[[127250,127250],"disallowed_STD3_mapped",[40,99,41]],[[127251,127251],"disallowed_STD3_mapped",[40,100,41]],[[127252,127252],"disallowed_STD3_mapped",[40,101,41]],[[127253,127253],"disallowed_STD3_mapped",[40,102,41]],[[127254,127254],"disallowed_STD3_mapped",[40,103,41]],[[127255,127255],"disallowed_STD3_mapped",[40,104,41]],[[127256,127256],"disallowed_STD3_mapped",[40,105,41]],[[127257,127257],"disallowed_STD3_mapped",[40,106,41]],[[127258,127258],"disallowed_STD3_mapped",[40,107,41]],[[127259,127259],"disallowed_STD3_mapped",[40,108,41]],[[127260,127260],"disallowed_STD3_mapped",[40,109,41]],[[127261,127261],"disallowed_STD3_mapped",[40,110,41]],[[127262,127262],"disallowed_STD3_mapped",[40,111,41]],[[127263,127263],"disallowed_STD3_mapped",[40,112,41]],[[127264,127264],"disallowed_STD3_mapped",[40,113,41]],[[127265,127265],"disallowed_STD3_mapped",[40,114,41]],[[127266,127266],"disallowed_STD3_mapped",[40,115,41]],[[127267,127267],"disallowed_STD3_mapped",[40,116,41]],[[127268,127268],"disallowed_STD3_mapped",[40,117,41]],[[127269,127269],"disallowed_STD3_mapped",[40,118,41]],[[127270,127270],"disallowed_STD3_mapped",[40,119,41]],[[127271,127271],"disallowed_STD3_mapped",[40,120,41]],[[127272,127272],"disallowed_STD3_mapped",[40,121,41]],[[127273,127273],"disallowed_STD3_mapped",[40,122,41]],[[127274,127274],"mapped",[12308,115,12309]],[[127275,127275],"mapped",[99]],[[127276,127276],"mapped",[114]],[[127277,127277],"mapped",[99,100]],[[127278,127278],"mapped",[119,122]],[[127279,127279],"disallowed"],[[127280,127280],"mapped",[97]],[[127281,127281],"mapped",[98]],[[127282,127282],"mapped",[99]],[[127283,127283],"mapped",[100]],[[127284,127284],"mapped",[101]],[[127285,127285],"mapped",[102]],[[127286,127286],"mapped",[103]],[[127287,127287],"mapped",[104]],[[127288,127288],"mapped",[105]],[[127289,127289],"mapped",[106]],[[127290,127290],"mapped",[107]],[[127291,127291],"mapped",[108]],[[127292,127292],"mapped",[109]],[[127293,127293],"mapped",[110]],[[127294,127294],"mapped",[111]],[[127295,127295],"mapped",[112]],[[127296,127296],"mapped",[113]],[[127297,127297],"mapped",[114]],[[127298,127298],"mapped",[115]],[[127299,127299],"mapped",[116]],[[127300,127300],"mapped",[117]],[[127301,127301],"mapped",[118]],[[127302,127302],"mapped",[119]],[[127303,127303],"mapped",[120]],[[127304,127304],"mapped",[121]],[[127305,127305],"mapped",[122]],[[127306,127306],"mapped",[104,118]],[[127307,127307],"mapped",[109,118]],[[127308,127308],"mapped",[115,100]],[[127309,127309],"mapped",[115,115]],[[127310,127310],"mapped",[112,112,118]],[[127311,127311],"mapped",[119,99]],[[127312,127318],"valid",[],"NV8"],[[127319,127319],"valid",[],"NV8"],[[127320,127326],"valid",[],"NV8"],[[127327,127327],"valid",[],"NV8"],[[127328,127337],"valid",[],"NV8"],[[127338,127338],"mapped",[109,99]],[[127339,127339],"mapped",[109,100]],[[127340,127343],"disallowed"],[[127344,127352],"valid",[],"NV8"],[[127353,127353],"valid",[],"NV8"],[[127354,127354],"valid",[],"NV8"],[[127355,127356],"valid",[],"NV8"],[[127357,127358],"valid",[],"NV8"],[[127359,127359],"valid",[],"NV8"],[[127360,127369],"valid",[],"NV8"],[[127370,127373],"valid",[],"NV8"],[[127374,127375],"valid",[],"NV8"],[[127376,127376],"mapped",[100,106]],[[127377,127386],"valid",[],"NV8"],[[127387,127461],"disallowed"],[[127462,127487],"valid",[],"NV8"],[[127488,127488],"mapped",[12411,12363]],[[127489,127489],"mapped",[12467,12467]],[[127490,127490],"mapped",[12469]],[[127491,127503],"disallowed"],[[127504,127504],"mapped",[25163]],[[127505,127505],"mapped",[23383]],[[127506,127506],"mapped",[21452]],[[127507,127507],"mapped",[12487]],[[127508,127508],"mapped",[20108]],[[127509,127509],"mapped",[22810]],[[127510,127510],"mapped",[35299]],[[127511,127511],"mapped",[22825]],[[127512,127512],"mapped",[20132]],[[127513,127513],"mapped",[26144]],[[127514,127514],"mapped",[28961]],[[127515,127515],"mapped",[26009]],[[127516,127516],"mapped",[21069]],[[127517,127517],"mapped",[24460]],[[127518,127518],"mapped",[20877]],[[127519,127519],"mapped",[26032]],[[127520,127520],"mapped",[21021]],[[127521,127521],"mapped",[32066]],[[127522,127522],"mapped",[29983]],[[127523,127523],"mapped",[36009]],[[127524,127524],"mapped",[22768]],[[127525,127525],"mapped",[21561]],[[127526,127526],"mapped",[28436]],[[127527,127527],"mapped",[25237]],[[127528,127528],"mapped",[25429]],[[127529,127529],"mapped",[19968]],[[127530,127530],"mapped",[19977]],[[127531,127531],"mapped",[36938]],[[127532,127532],"mapped",[24038]],[[127533,127533],"mapped",[20013]],[[127534,127534],"mapped",[21491]],[[127535,127535],"mapped",[25351]],[[127536,127536],"mapped",[36208]],[[127537,127537],"mapped",[25171]],[[127538,127538],"mapped",[31105]],[[127539,127539],"mapped",[31354]],[[127540,127540],"mapped",[21512]],[[127541,127541],"mapped",[28288]],[[127542,127542],"mapped",[26377]],[[127543,127543],"mapped",[26376]],[[127544,127544],"mapped",[30003]],[[127545,127545],"mapped",[21106]],[[127546,127546],"mapped",[21942]],[[127547,127551],"disallowed"],[[127552,127552],"mapped",[12308,26412,12309]],[[127553,127553],"mapped",[12308,19977,12309]],[[127554,127554],"mapped",[12308,20108,12309]],[[127555,127555],"mapped",[12308,23433,12309]],[[127556,127556],"mapped",[12308,28857,12309]],[[127557,127557],"mapped",[12308,25171,12309]],[[127558,127558],"mapped",[12308,30423,12309]],[[127559,127559],"mapped",[12308,21213,12309]],[[127560,127560],"mapped",[12308,25943,12309]],[[127561,127567],"disallowed"],[[127568,127568],"mapped",[24471]],[[127569,127569],"mapped",[21487]],[[127570,127743],"disallowed"],[[127744,127776],"valid",[],"NV8"],[[127777,127788],"valid",[],"NV8"],[[127789,127791],"valid",[],"NV8"],[[127792,127797],"valid",[],"NV8"],[[127798,127798],"valid",[],"NV8"],[[127799,127868],"valid",[],"NV8"],[[127869,127869],"valid",[],"NV8"],[[127870,127871],"valid",[],"NV8"],[[127872,127891],"valid",[],"NV8"],[[127892,127903],"valid",[],"NV8"],[[127904,127940],"valid",[],"NV8"],[[127941,127941],"valid",[],"NV8"],[[127942,127946],"valid",[],"NV8"],[[127947,127950],"valid",[],"NV8"],[[127951,127955],"valid",[],"NV8"],[[127956,127967],"valid",[],"NV8"],[[127968,127984],"valid",[],"NV8"],[[127985,127991],"valid",[],"NV8"],[[127992,127999],"valid",[],"NV8"],[[128000,128062],"valid",[],"NV8"],[[128063,128063],"valid",[],"NV8"],[[128064,128064],"valid",[],"NV8"],[[128065,128065],"valid",[],"NV8"],[[128066,128247],"valid",[],"NV8"],[[128248,128248],"valid",[],"NV8"],[[128249,128252],"valid",[],"NV8"],[[128253,128254],"valid",[],"NV8"],[[128255,128255],"valid",[],"NV8"],[[128256,128317],"valid",[],"NV8"],[[128318,128319],"valid",[],"NV8"],[[128320,128323],"valid",[],"NV8"],[[128324,128330],"valid",[],"NV8"],[[128331,128335],"valid",[],"NV8"],[[128336,128359],"valid",[],"NV8"],[[128360,128377],"valid",[],"NV8"],[[128378,128378],"disallowed"],[[128379,128419],"valid",[],"NV8"],[[128420,128420],"disallowed"],[[128421,128506],"valid",[],"NV8"],[[128507,128511],"valid",[],"NV8"],[[128512,128512],"valid",[],"NV8"],[[128513,128528],"valid",[],"NV8"],[[128529,128529],"valid",[],"NV8"],[[128530,128532],"valid",[],"NV8"],[[128533,128533],"valid",[],"NV8"],[[128534,128534],"valid",[],"NV8"],[[128535,128535],"valid",[],"NV8"],[[128536,128536],"valid",[],"NV8"],[[128537,128537],"valid",[],"NV8"],[[128538,128538],"valid",[],"NV8"],[[128539,128539],"valid",[],"NV8"],[[128540,128542],"valid",[],"NV8"],[[128543,128543],"valid",[],"NV8"],[[128544,128549],"valid",[],"NV8"],[[128550,128551],"valid",[],"NV8"],[[128552,128555],"valid",[],"NV8"],[[128556,128556],"valid",[],"NV8"],[[128557,128557],"valid",[],"NV8"],[[128558,128559],"valid",[],"NV8"],[[128560,128563],"valid",[],"NV8"],[[128564,128564],"valid",[],"NV8"],[[128565,128576],"valid",[],"NV8"],[[128577,128578],"valid",[],"NV8"],[[128579,128580],"valid",[],"NV8"],[[128581,128591],"valid",[],"NV8"],[[128592,128639],"valid",[],"NV8"],[[128640,128709],"valid",[],"NV8"],[[128710,128719],"valid",[],"NV8"],[[128720,128720],"valid",[],"NV8"],[[128721,128735],"disallowed"],[[128736,128748],"valid",[],"NV8"],[[128749,128751],"disallowed"],[[128752,128755],"valid",[],"NV8"],[[128756,128767],"disallowed"],[[128768,128883],"valid",[],"NV8"],[[128884,128895],"disallowed"],[[128896,128980],"valid",[],"NV8"],[[128981,129023],"disallowed"],[[129024,129035],"valid",[],"NV8"],[[129036,129039],"disallowed"],[[129040,129095],"valid",[],"NV8"],[[129096,129103],"disallowed"],[[129104,129113],"valid",[],"NV8"],[[129114,129119],"disallowed"],[[129120,129159],"valid",[],"NV8"],[[129160,129167],"disallowed"],[[129168,129197],"valid",[],"NV8"],[[129198,129295],"disallowed"],[[129296,129304],"valid",[],"NV8"],[[129305,129407],"disallowed"],[[129408,129412],"valid",[],"NV8"],[[129413,129471],"disallowed"],[[129472,129472],"valid",[],"NV8"],[[129473,131069],"disallowed"],[[131070,131071],"disallowed"],[[131072,173782],"valid"],[[173783,173823],"disallowed"],[[173824,177972],"valid"],[[177973,177983],"disallowed"],[[177984,178205],"valid"],[[178206,178207],"disallowed"],[[178208,183969],"valid"],[[183970,194559],"disallowed"],[[194560,194560],"mapped",[20029]],[[194561,194561],"mapped",[20024]],[[194562,194562],"mapped",[20033]],[[194563,194563],"mapped",[131362]],[[194564,194564],"mapped",[20320]],[[194565,194565],"mapped",[20398]],[[194566,194566],"mapped",[20411]],[[194567,194567],"mapped",[20482]],[[194568,194568],"mapped",[20602]],[[194569,194569],"mapped",[20633]],[[194570,194570],"mapped",[20711]],[[194571,194571],"mapped",[20687]],[[194572,194572],"mapped",[13470]],[[194573,194573],"mapped",[132666]],[[194574,194574],"mapped",[20813]],[[194575,194575],"mapped",[20820]],[[194576,194576],"mapped",[20836]],[[194577,194577],"mapped",[20855]],[[194578,194578],"mapped",[132380]],[[194579,194579],"mapped",[13497]],[[194580,194580],"mapped",[20839]],[[194581,194581],"mapped",[20877]],[[194582,194582],"mapped",[132427]],[[194583,194583],"mapped",[20887]],[[194584,194584],"mapped",[20900]],[[194585,194585],"mapped",[20172]],[[194586,194586],"mapped",[20908]],[[194587,194587],"mapped",[20917]],[[194588,194588],"mapped",[168415]],[[194589,194589],"mapped",[20981]],[[194590,194590],"mapped",[20995]],[[194591,194591],"mapped",[13535]],[[194592,194592],"mapped",[21051]],[[194593,194593],"mapped",[21062]],[[194594,194594],"mapped",[21106]],[[194595,194595],"mapped",[21111]],[[194596,194596],"mapped",[13589]],[[194597,194597],"mapped",[21191]],[[194598,194598],"mapped",[21193]],[[194599,194599],"mapped",[21220]],[[194600,194600],"mapped",[21242]],[[194601,194601],"mapped",[21253]],[[194602,194602],"mapped",[21254]],[[194603,194603],"mapped",[21271]],[[194604,194604],"mapped",[21321]],[[194605,194605],"mapped",[21329]],[[194606,194606],"mapped",[21338]],[[194607,194607],"mapped",[21363]],[[194608,194608],"mapped",[21373]],[[194609,194611],"mapped",[21375]],[[194612,194612],"mapped",[133676]],[[194613,194613],"mapped",[28784]],[[194614,194614],"mapped",[21450]],[[194615,194615],"mapped",[21471]],[[194616,194616],"mapped",[133987]],[[194617,194617],"mapped",[21483]],[[194618,194618],"mapped",[21489]],[[194619,194619],"mapped",[21510]],[[194620,194620],"mapped",[21662]],[[194621,194621],"mapped",[21560]],[[194622,194622],"mapped",[21576]],[[194623,194623],"mapped",[21608]],[[194624,194624],"mapped",[21666]],[[194625,194625],"mapped",[21750]],[[194626,194626],"mapped",[21776]],[[194627,194627],"mapped",[21843]],[[194628,194628],"mapped",[21859]],[[194629,194630],"mapped",[21892]],[[194631,194631],"mapped",[21913]],[[194632,194632],"mapped",[21931]],[[194633,194633],"mapped",[21939]],[[194634,194634],"mapped",[21954]],[[194635,194635],"mapped",[22294]],[[194636,194636],"mapped",[22022]],[[194637,194637],"mapped",[22295]],[[194638,194638],"mapped",[22097]],[[194639,194639],"mapped",[22132]],[[194640,194640],"mapped",[20999]],[[194641,194641],"mapped",[22766]],[[194642,194642],"mapped",[22478]],[[194643,194643],"mapped",[22516]],[[194644,194644],"mapped",[22541]],[[194645,194645],"mapped",[22411]],[[194646,194646],"mapped",[22578]],[[194647,194647],"mapped",[22577]],[[194648,194648],"mapped",[22700]],[[194649,194649],"mapped",[136420]],[[194650,194650],"mapped",[22770]],[[194651,194651],"mapped",[22775]],[[194652,194652],"mapped",[22790]],[[194653,194653],"mapped",[22810]],[[194654,194654],"mapped",[22818]],[[194655,194655],"mapped",[22882]],[[194656,194656],"mapped",[136872]],[[194657,194657],"mapped",[136938]],[[194658,194658],"mapped",[23020]],[[194659,194659],"mapped",[23067]],[[194660,194660],"mapped",[23079]],[[194661,194661],"mapped",[23000]],[[194662,194662],"mapped",[23142]],[[194663,194663],"mapped",[14062]],[[194664,194664],"disallowed"],[[194665,194665],"mapped",[23304]],[[194666,194667],"mapped",[23358]],[[194668,194668],"mapped",[137672]],[[194669,194669],"mapped",[23491]],[[194670,194670],"mapped",[23512]],[[194671,194671],"mapped",[23527]],[[194672,194672],"mapped",[23539]],[[194673,194673],"mapped",[138008]],[[194674,194674],"mapped",[23551]],[[194675,194675],"mapped",[23558]],[[194676,194676],"disallowed"],[[194677,194677],"mapped",[23586]],[[194678,194678],"mapped",[14209]],[[194679,194679],"mapped",[23648]],[[194680,194680],"mapped",[23662]],[[194681,194681],"mapped",[23744]],[[194682,194682],"mapped",[23693]],[[194683,194683],"mapped",[138724]],[[194684,194684],"mapped",[23875]],[[194685,194685],"mapped",[138726]],[[194686,194686],"mapped",[23918]],[[194687,194687],"mapped",[23915]],[[194688,194688],"mapped",[23932]],[[194689,194689],"mapped",[24033]],[[194690,194690],"mapped",[24034]],[[194691,194691],"mapped",[14383]],[[194692,194692],"mapped",[24061]],[[194693,194693],"mapped",[24104]],[[194694,194694],"mapped",[24125]],[[194695,194695],"mapped",[24169]],[[194696,194696],"mapped",[14434]],[[194697,194697],"mapped",[139651]],[[194698,194698],"mapped",[14460]],[[194699,194699],"mapped",[24240]],[[194700,194700],"mapped",[24243]],[[194701,194701],"mapped",[24246]],[[194702,194702],"mapped",[24266]],[[194703,194703],"mapped",[172946]],[[194704,194704],"mapped",[24318]],[[194705,194706],"mapped",[140081]],[[194707,194707],"mapped",[33281]],[[194708,194709],"mapped",[24354]],[[194710,194710],"mapped",[14535]],[[194711,194711],"mapped",[144056]],[[194712,194712],"mapped",[156122]],[[194713,194713],"mapped",[24418]],[[194714,194714],"mapped",[24427]],[[194715,194715],"mapped",[14563]],[[194716,194716],"mapped",[24474]],[[194717,194717],"mapped",[24525]],[[194718,194718],"mapped",[24535]],[[194719,194719],"mapped",[24569]],[[194720,194720],"mapped",[24705]],[[194721,194721],"mapped",[14650]],[[194722,194722],"mapped",[14620]],[[194723,194723],"mapped",[24724]],[[194724,194724],"mapped",[141012]],[[194725,194725],"mapped",[24775]],[[194726,194726],"mapped",[24904]],[[194727,194727],"mapped",[24908]],[[194728,194728],"mapped",[24910]],[[194729,194729],"mapped",[24908]],[[194730,194730],"mapped",[24954]],[[194731,194731],"mapped",[24974]],[[194732,194732],"mapped",[25010]],[[194733,194733],"mapped",[24996]],[[194734,194734],"mapped",[25007]],[[194735,194735],"mapped",[25054]],[[194736,194736],"mapped",[25074]],[[194737,194737],"mapped",[25078]],[[194738,194738],"mapped",[25104]],[[194739,194739],"mapped",[25115]],[[194740,194740],"mapped",[25181]],[[194741,194741],"mapped",[25265]],[[194742,194742],"mapped",[25300]],[[194743,194743],"mapped",[25424]],[[194744,194744],"mapped",[142092]],[[194745,194745],"mapped",[25405]],[[194746,194746],"mapped",[25340]],[[194747,194747],"mapped",[25448]],[[194748,194748],"mapped",[25475]],[[194749,194749],"mapped",[25572]],[[194750,194750],"mapped",[142321]],[[194751,194751],"mapped",[25634]],[[194752,194752],"mapped",[25541]],[[194753,194753],"mapped",[25513]],[[194754,194754],"mapped",[14894]],[[194755,194755],"mapped",[25705]],[[194756,194756],"mapped",[25726]],[[194757,194757],"mapped",[25757]],[[194758,194758],"mapped",[25719]],[[194759,194759],"mapped",[14956]],[[194760,194760],"mapped",[25935]],[[194761,194761],"mapped",[25964]],[[194762,194762],"mapped",[143370]],[[194763,194763],"mapped",[26083]],[[194764,194764],"mapped",[26360]],[[194765,194765],"mapped",[26185]],[[194766,194766],"mapped",[15129]],[[194767,194767],"mapped",[26257]],[[194768,194768],"mapped",[15112]],[[194769,194769],"mapped",[15076]],[[194770,194770],"mapped",[20882]],[[194771,194771],"mapped",[20885]],[[194772,194772],"mapped",[26368]],[[194773,194773],"mapped",[26268]],[[194774,194774],"mapped",[32941]],[[194775,194775],"mapped",[17369]],[[194776,194776],"mapped",[26391]],[[194777,194777],"mapped",[26395]],[[194778,194778],"mapped",[26401]],[[194779,194779],"mapped",[26462]],[[194780,194780],"mapped",[26451]],[[194781,194781],"mapped",[144323]],[[194782,194782],"mapped",[15177]],[[194783,194783],"mapped",[26618]],[[194784,194784],"mapped",[26501]],[[194785,194785],"mapped",[26706]],[[194786,194786],"mapped",[26757]],[[194787,194787],"mapped",[144493]],[[194788,194788],"mapped",[26766]],[[194789,194789],"mapped",[26655]],[[194790,194790],"mapped",[26900]],[[194791,194791],"mapped",[15261]],[[194792,194792],"mapped",[26946]],[[194793,194793],"mapped",[27043]],[[194794,194794],"mapped",[27114]],[[194795,194795],"mapped",[27304]],[[194796,194796],"mapped",[145059]],[[194797,194797],"mapped",[27355]],[[194798,194798],"mapped",[15384]],[[194799,194799],"mapped",[27425]],[[194800,194800],"mapped",[145575]],[[194801,194801],"mapped",[27476]],[[194802,194802],"mapped",[15438]],[[194803,194803],"mapped",[27506]],[[194804,194804],"mapped",[27551]],[[194805,194805],"mapped",[27578]],[[194806,194806],"mapped",[27579]],[[194807,194807],"mapped",[146061]],[[194808,194808],"mapped",[138507]],[[194809,194809],"mapped",[146170]],[[194810,194810],"mapped",[27726]],[[194811,194811],"mapped",[146620]],[[194812,194812],"mapped",[27839]],[[194813,194813],"mapped",[27853]],[[194814,194814],"mapped",[27751]],[[194815,194815],"mapped",[27926]],[[194816,194816],"mapped",[27966]],[[194817,194817],"mapped",[28023]],[[194818,194818],"mapped",[27969]],[[194819,194819],"mapped",[28009]],[[194820,194820],"mapped",[28024]],[[194821,194821],"mapped",[28037]],[[194822,194822],"mapped",[146718]],[[194823,194823],"mapped",[27956]],[[194824,194824],"mapped",[28207]],[[194825,194825],"mapped",[28270]],[[194826,194826],"mapped",[15667]],[[194827,194827],"mapped",[28363]],[[194828,194828],"mapped",[28359]],[[194829,194829],"mapped",[147153]],[[194830,194830],"mapped",[28153]],[[194831,194831],"mapped",[28526]],[[194832,194832],"mapped",[147294]],[[194833,194833],"mapped",[147342]],[[194834,194834],"mapped",[28614]],[[194835,194835],"mapped",[28729]],[[194836,194836],"mapped",[28702]],[[194837,194837],"mapped",[28699]],[[194838,194838],"mapped",[15766]],[[194839,194839],"mapped",[28746]],[[194840,194840],"mapped",[28797]],[[194841,194841],"mapped",[28791]],[[194842,194842],"mapped",[28845]],[[194843,194843],"mapped",[132389]],[[194844,194844],"mapped",[28997]],[[194845,194845],"mapped",[148067]],[[194846,194846],"mapped",[29084]],[[194847,194847],"disallowed"],[[194848,194848],"mapped",[29224]],[[194849,194849],"mapped",[29237]],[[194850,194850],"mapped",[29264]],[[194851,194851],"mapped",[149000]],[[194852,194852],"mapped",[29312]],[[194853,194853],"mapped",[29333]],[[194854,194854],"mapped",[149301]],[[194855,194855],"mapped",[149524]],[[194856,194856],"mapped",[29562]],[[194857,194857],"mapped",[29579]],[[194858,194858],"mapped",[16044]],[[194859,194859],"mapped",[29605]],[[194860,194861],"mapped",[16056]],[[194862,194862],"mapped",[29767]],[[194863,194863],"mapped",[29788]],[[194864,194864],"mapped",[29809]],[[194865,194865],"mapped",[29829]],[[194866,194866],"mapped",[29898]],[[194867,194867],"mapped",[16155]],[[194868,194868],"mapped",[29988]],[[194869,194869],"mapped",[150582]],[[194870,194870],"mapped",[30014]],[[194871,194871],"mapped",[150674]],[[194872,194872],"mapped",[30064]],[[194873,194873],"mapped",[139679]],[[194874,194874],"mapped",[30224]],[[194875,194875],"mapped",[151457]],[[194876,194876],"mapped",[151480]],[[194877,194877],"mapped",[151620]],[[194878,194878],"mapped",[16380]],[[194879,194879],"mapped",[16392]],[[194880,194880],"mapped",[30452]],[[194881,194881],"mapped",[151795]],[[194882,194882],"mapped",[151794]],[[194883,194883],"mapped",[151833]],[[194884,194884],"mapped",[151859]],[[194885,194885],"mapped",[30494]],[[194886,194887],"mapped",[30495]],[[194888,194888],"mapped",[30538]],[[194889,194889],"mapped",[16441]],[[194890,194890],"mapped",[30603]],[[194891,194891],"mapped",[16454]],[[194892,194892],"mapped",[16534]],[[194893,194893],"mapped",[152605]],[[194894,194894],"mapped",[30798]],[[194895,194895],"mapped",[30860]],[[194896,194896],"mapped",[30924]],[[194897,194897],"mapped",[16611]],[[194898,194898],"mapped",[153126]],[[194899,194899],"mapped",[31062]],[[194900,194900],"mapped",[153242]],[[194901,194901],"mapped",[153285]],[[194902,194902],"mapped",[31119]],[[194903,194903],"mapped",[31211]],[[194904,194904],"mapped",[16687]],[[194905,194905],"mapped",[31296]],[[194906,194906],"mapped",[31306]],[[194907,194907],"mapped",[31311]],[[194908,194908],"mapped",[153980]],[[194909,194910],"mapped",[154279]],[[194911,194911],"disallowed"],[[194912,194912],"mapped",[16898]],[[194913,194913],"mapped",[154539]],[[194914,194914],"mapped",[31686]],[[194915,194915],"mapped",[31689]],[[194916,194916],"mapped",[16935]],[[194917,194917],"mapped",[154752]],[[194918,194918],"mapped",[31954]],[[194919,194919],"mapped",[17056]],[[194920,194920],"mapped",[31976]],[[194921,194921],"mapped",[31971]],[[194922,194922],"mapped",[32000]],[[194923,194923],"mapped",[155526]],[[194924,194924],"mapped",[32099]],[[194925,194925],"mapped",[17153]],[[194926,194926],"mapped",[32199]],[[194927,194927],"mapped",[32258]],[[194928,194928],"mapped",[32325]],[[194929,194929],"mapped",[17204]],[[194930,194930],"mapped",[156200]],[[194931,194931],"mapped",[156231]],[[194932,194932],"mapped",[17241]],[[194933,194933],"mapped",[156377]],[[194934,194934],"mapped",[32634]],[[194935,194935],"mapped",[156478]],[[194936,194936],"mapped",[32661]],[[194937,194937],"mapped",[32762]],[[194938,194938],"mapped",[32773]],[[194939,194939],"mapped",[156890]],[[194940,194940],"mapped",[156963]],[[194941,194941],"mapped",[32864]],[[194942,194942],"mapped",[157096]],[[194943,194943],"mapped",[32880]],[[194944,194944],"mapped",[144223]],[[194945,194945],"mapped",[17365]],[[194946,194946],"mapped",[32946]],[[194947,194947],"mapped",[33027]],[[194948,194948],"mapped",[17419]],[[194949,194949],"mapped",[33086]],[[194950,194950],"mapped",[23221]],[[194951,194951],"mapped",[157607]],[[194952,194952],"mapped",[157621]],[[194953,194953],"mapped",[144275]],[[194954,194954],"mapped",[144284]],[[194955,194955],"mapped",[33281]],[[194956,194956],"mapped",[33284]],[[194957,194957],"mapped",[36766]],[[194958,194958],"mapped",[17515]],[[194959,194959],"mapped",[33425]],[[194960,194960],"mapped",[33419]],[[194961,194961],"mapped",[33437]],[[194962,194962],"mapped",[21171]],[[194963,194963],"mapped",[33457]],[[194964,194964],"mapped",[33459]],[[194965,194965],"mapped",[33469]],[[194966,194966],"mapped",[33510]],[[194967,194967],"mapped",[158524]],[[194968,194968],"mapped",[33509]],[[194969,194969],"mapped",[33565]],[[194970,194970],"mapped",[33635]],[[194971,194971],"mapped",[33709]],[[194972,194972],"mapped",[33571]],[[194973,194973],"mapped",[33725]],[[194974,194974],"mapped",[33767]],[[194975,194975],"mapped",[33879]],[[194976,194976],"mapped",[33619]],[[194977,194977],"mapped",[33738]],[[194978,194978],"mapped",[33740]],[[194979,194979],"mapped",[33756]],[[194980,194980],"mapped",[158774]],[[194981,194981],"mapped",[159083]],[[194982,194982],"mapped",[158933]],[[194983,194983],"mapped",[17707]],[[194984,194984],"mapped",[34033]],[[194985,194985],"mapped",[34035]],[[194986,194986],"mapped",[34070]],[[194987,194987],"mapped",[160714]],[[194988,194988],"mapped",[34148]],[[194989,194989],"mapped",[159532]],[[194990,194990],"mapped",[17757]],[[194991,194991],"mapped",[17761]],[[194992,194992],"mapped",[159665]],[[194993,194993],"mapped",[159954]],[[194994,194994],"mapped",[17771]],[[194995,194995],"mapped",[34384]],[[194996,194996],"mapped",[34396]],[[194997,194997],"mapped",[34407]],[[194998,194998],"mapped",[34409]],[[194999,194999],"mapped",[34473]],[[195000,195000],"mapped",[34440]],[[195001,195001],"mapped",[34574]],[[195002,195002],"mapped",[34530]],[[195003,195003],"mapped",[34681]],[[195004,195004],"mapped",[34600]],[[195005,195005],"mapped",[34667]],[[195006,195006],"mapped",[34694]],[[195007,195007],"disallowed"],[[195008,195008],"mapped",[34785]],[[195009,195009],"mapped",[34817]],[[195010,195010],"mapped",[17913]],[[195011,195011],"mapped",[34912]],[[195012,195012],"mapped",[34915]],[[195013,195013],"mapped",[161383]],[[195014,195014],"mapped",[35031]],[[195015,195015],"mapped",[35038]],[[195016,195016],"mapped",[17973]],[[195017,195017],"mapped",[35066]],[[195018,195018],"mapped",[13499]],[[195019,195019],"mapped",[161966]],[[195020,195020],"mapped",[162150]],[[195021,195021],"mapped",[18110]],[[195022,195022],"mapped",[18119]],[[195023,195023],"mapped",[35488]],[[195024,195024],"mapped",[35565]],[[195025,195025],"mapped",[35722]],[[195026,195026],"mapped",[35925]],[[195027,195027],"mapped",[162984]],[[195028,195028],"mapped",[36011]],[[195029,195029],"mapped",[36033]],[[195030,195030],"mapped",[36123]],[[195031,195031],"mapped",[36215]],[[195032,195032],"mapped",[163631]],[[195033,195033],"mapped",[133124]],[[195034,195034],"mapped",[36299]],[[195035,195035],"mapped",[36284]],[[195036,195036],"mapped",[36336]],[[195037,195037],"mapped",[133342]],[[195038,195038],"mapped",[36564]],[[195039,195039],"mapped",[36664]],[[195040,195040],"mapped",[165330]],[[195041,195041],"mapped",[165357]],[[195042,195042],"mapped",[37012]],[[195043,195043],"mapped",[37105]],[[195044,195044],"mapped",[37137]],[[195045,195045],"mapped",[165678]],[[195046,195046],"mapped",[37147]],[[195047,195047],"mapped",[37432]],[[195048,195048],"mapped",[37591]],[[195049,195049],"mapped",[37592]],[[195050,195050],"mapped",[37500]],[[195051,195051],"mapped",[37881]],[[195052,195052],"mapped",[37909]],[[195053,195053],"mapped",[166906]],[[195054,195054],"mapped",[38283]],[[195055,195055],"mapped",[18837]],[[195056,195056],"mapped",[38327]],[[195057,195057],"mapped",[167287]],[[195058,195058],"mapped",[18918]],[[195059,195059],"mapped",[38595]],[[195060,195060],"mapped",[23986]],[[195061,195061],"mapped",[38691]],[[195062,195062],"mapped",[168261]],[[195063,195063],"mapped",[168474]],[[195064,195064],"mapped",[19054]],[[195065,195065],"mapped",[19062]],[[195066,195066],"mapped",[38880]],[[195067,195067],"mapped",[168970]],[[195068,195068],"mapped",[19122]],[[195069,195069],"mapped",[169110]],[[195070,195071],"mapped",[38923]],[[195072,195072],"mapped",[38953]],[[195073,195073],"mapped",[169398]],[[195074,195074],"mapped",[39138]],[[195075,195075],"mapped",[19251]],[[195076,195076],"mapped",[39209]],[[195077,195077],"mapped",[39335]],[[195078,195078],"mapped",[39362]],[[195079,195079],"mapped",[39422]],[[195080,195080],"mapped",[19406]],[[195081,195081],"mapped",[170800]],[[195082,195082],"mapped",[39698]],[[195083,195083],"mapped",[40000]],[[195084,195084],"mapped",[40189]],[[195085,195085],"mapped",[19662]],[[195086,195086],"mapped",[19693]],[[195087,195087],"mapped",[40295]],[[195088,195088],"mapped",[172238]],[[195089,195089],"mapped",[19704]],[[195090,195090],"mapped",[172293]],[[195091,195091],"mapped",[172558]],[[195092,195092],"mapped",[172689]],[[195093,195093],"mapped",[40635]],[[195094,195094],"mapped",[19798]],[[195095,195095],"mapped",[40697]],[[195096,195096],"mapped",[40702]],[[195097,195097],"mapped",[40709]],[[195098,195098],"mapped",[40719]],[[195099,195099],"mapped",[40726]],[[195100,195100],"mapped",[40763]],[[195101,195101],"mapped",[173568]],[[195102,196605],"disallowed"],[[196606,196607],"disallowed"],[[196608,262141],"disallowed"],[[262142,262143],"disallowed"],[[262144,327677],"disallowed"],[[327678,327679],"disallowed"],[[327680,393213],"disallowed"],[[393214,393215],"disallowed"],[[393216,458749],"disallowed"],[[458750,458751],"disallowed"],[[458752,524285],"disallowed"],[[524286,524287],"disallowed"],[[524288,589821],"disallowed"],[[589822,589823],"disallowed"],[[589824,655357],"disallowed"],[[655358,655359],"disallowed"],[[655360,720893],"disallowed"],[[720894,720895],"disallowed"],[[720896,786429],"disallowed"],[[786430,786431],"disallowed"],[[786432,851965],"disallowed"],[[851966,851967],"disallowed"],[[851968,917501],"disallowed"],[[917502,917503],"disallowed"],[[917504,917504],"disallowed"],[[917505,917505],"disallowed"],[[917506,917535],"disallowed"],[[917536,917631],"disallowed"],[[917632,917759],"disallowed"],[[917760,917999],"ignored"],[[918000,983037],"disallowed"],[[983038,983039],"disallowed"],[[983040,1048573],"disallowed"],[[1048574,1048575],"disallowed"],[[1048576,1114109],"disallowed"],[[1114110,1114111],"disallowed"]] \ No newline at end of file diff --git a/node_modules/tr46/package.json b/node_modules/tr46/package.json new file mode 100644 index 0000000..b6826da --- /dev/null +++ b/node_modules/tr46/package.json @@ -0,0 +1,31 @@ +{ + "name": "tr46", + "version": "0.0.3", + "description": "An implementation of the Unicode TR46 spec", + "main": "index.js", + "scripts": { + "test": "mocha", + "pretest": "node scripts/getLatestUnicodeTests.js", + "prepublish": "node scripts/generateMappingTable.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Sebmaster/tr46.js.git" + }, + "keywords": [ + "unicode", + "tr46", + "url", + "whatwg" + ], + "author": "Sebastian Mayr ", + "license": "MIT", + "bugs": { + "url": "https://github.com/Sebmaster/tr46.js/issues" + }, + "homepage": "https://github.com/Sebmaster/tr46.js#readme", + "devDependencies": { + "mocha": "^2.2.5", + "request": "^2.57.0" + } +} diff --git a/node_modules/tslib/CopyrightNotice.txt b/node_modules/tslib/CopyrightNotice.txt new file mode 100644 index 0000000..5d7d2d9 --- /dev/null +++ b/node_modules/tslib/CopyrightNotice.txt @@ -0,0 +1,15 @@ +/****************************************************************************** +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. +***************************************************************************** */ + diff --git a/node_modules/tslib/LICENSE.txt b/node_modules/tslib/LICENSE.txt new file mode 100644 index 0000000..fa7d1bd --- /dev/null +++ b/node_modules/tslib/LICENSE.txt @@ -0,0 +1,12 @@ +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. \ No newline at end of file diff --git a/node_modules/tslib/README.md b/node_modules/tslib/README.md new file mode 100644 index 0000000..14b9a83 --- /dev/null +++ b/node_modules/tslib/README.md @@ -0,0 +1,164 @@ +# tslib + +This is a runtime library for [TypeScript](https://www.typescriptlang.org/) that contains all of the TypeScript helper functions. + +This library is primarily used by the `--importHelpers` flag in TypeScript. +When using `--importHelpers`, a module that uses helper functions like `__extends` and `__assign` in the following emitted file: + +```ts +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +exports.x = {}; +exports.y = __assign({}, exports.x); + +``` + +will instead be emitted as something like the following: + +```ts +var tslib_1 = require("tslib"); +exports.x = {}; +exports.y = tslib_1.__assign({}, exports.x); +``` + +Because this can avoid duplicate declarations of things like `__extends`, `__assign`, etc., this means delivering users smaller files on average, as well as less runtime overhead. +For optimized bundles with TypeScript, you should absolutely consider using `tslib` and `--importHelpers`. + +# Installing + +For the latest stable version, run: + +## npm + +```sh +# TypeScript 3.9.2 or later +npm install tslib + +# TypeScript 3.8.4 or earlier +npm install tslib@^1 + +# TypeScript 2.3.2 or earlier +npm install tslib@1.6.1 +``` + +## yarn + +```sh +# TypeScript 3.9.2 or later +yarn add tslib + +# TypeScript 3.8.4 or earlier +yarn add tslib@^1 + +# TypeScript 2.3.2 or earlier +yarn add tslib@1.6.1 +``` + +## bower + +```sh +# TypeScript 3.9.2 or later +bower install tslib + +# TypeScript 3.8.4 or earlier +bower install tslib@^1 + +# TypeScript 2.3.2 or earlier +bower install tslib@1.6.1 +``` + +## JSPM + +```sh +# TypeScript 3.9.2 or later +jspm install tslib + +# TypeScript 3.8.4 or earlier +jspm install tslib@^1 + +# TypeScript 2.3.2 or earlier +jspm install tslib@1.6.1 +``` + +# Usage + +Set the `importHelpers` compiler option on the command line: + +``` +tsc --importHelpers file.ts +``` + +or in your tsconfig.json: + +```json +{ + "compilerOptions": { + "importHelpers": true + } +} +``` + +#### For bower and JSPM users + +You will need to add a `paths` mapping for `tslib`, e.g. For Bower users: + +```json +{ + "compilerOptions": { + "module": "amd", + "importHelpers": true, + "baseUrl": "./", + "paths": { + "tslib" : ["bower_components/tslib/tslib.d.ts"] + } + } +} +``` + +For JSPM users: + +```json +{ + "compilerOptions": { + "module": "system", + "importHelpers": true, + "baseUrl": "./", + "paths": { + "tslib" : ["jspm_packages/npm/tslib@2.x.y/tslib.d.ts"] + } + } +} +``` + +## Deployment + +- Choose your new version number +- Set it in `package.json` and `bower.json` +- Create a tag: `git tag [version]` +- Push the tag: `git push --tags` +- Create a [release in GitHub](https://github.com/microsoft/tslib/releases) +- Run the [publish to npm](https://github.com/microsoft/tslib/actions?query=workflow%3A%22Publish+to+NPM%22) workflow + +Done. + +# Contribute + +There are many ways to [contribute](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md) to TypeScript. + +* [Submit bugs](https://github.com/Microsoft/TypeScript/issues) and help us verify fixes as they are checked in. +* Review the [source code changes](https://github.com/Microsoft/TypeScript/pulls). +* Engage with other TypeScript users and developers on [StackOverflow](http://stackoverflow.com/questions/tagged/typescript). +* Join the [#typescript](http://twitter.com/#!/search/realtime/%23typescript) discussion on Twitter. +* [Contribute bug fixes](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md). + +# Documentation + +* [Quick tutorial](http://www.typescriptlang.org/Tutorial) +* [Programming handbook](http://www.typescriptlang.org/Handbook) +* [Homepage](http://www.typescriptlang.org/) diff --git a/node_modules/tslib/SECURITY.md b/node_modules/tslib/SECURITY.md new file mode 100644 index 0000000..869fdfe --- /dev/null +++ b/node_modules/tslib/SECURITY.md @@ -0,0 +1,41 @@ + + +## Security + +Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). + +If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below. + +## Reporting Security Issues + +**Please do not report security vulnerabilities through public GitHub issues.** + +Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report). + +If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey). + +You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc). + +Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: + + * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) + * Full paths of source file(s) related to the manifestation of the issue + * The location of the affected source code (tag/branch/commit or direct URL) + * Any special configuration required to reproduce the issue + * Step-by-step instructions to reproduce the issue + * Proof-of-concept or exploit code (if possible) + * Impact of the issue, including how an attacker might exploit the issue + +This information will help us triage your report more quickly. + +If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs. + +## Preferred Languages + +We prefer all communications to be in English. + +## Policy + +Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd). + + diff --git a/node_modules/tslib/modules/index.d.ts b/node_modules/tslib/modules/index.d.ts new file mode 100644 index 0000000..3244fab --- /dev/null +++ b/node_modules/tslib/modules/index.d.ts @@ -0,0 +1,38 @@ +// Note: named reexports are used instead of `export *` because +// TypeScript itself doesn't resolve the `export *` when checking +// if a particular helper exists. +export { + __extends, + __assign, + __rest, + __decorate, + __param, + __esDecorate, + __runInitializers, + __propKey, + __setFunctionName, + __metadata, + __awaiter, + __generator, + __exportStar, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __createBinding, + __addDisposableResource, + __disposeResources, + __rewriteRelativeImportExtension, +} from '../tslib.js'; +export * as default from '../tslib.js'; diff --git a/node_modules/tslib/modules/index.js b/node_modules/tslib/modules/index.js new file mode 100644 index 0000000..f4f9a06 --- /dev/null +++ b/node_modules/tslib/modules/index.js @@ -0,0 +1,70 @@ +import tslib from '../tslib.js'; +const { + __extends, + __assign, + __rest, + __decorate, + __param, + __esDecorate, + __runInitializers, + __propKey, + __setFunctionName, + __metadata, + __awaiter, + __generator, + __exportStar, + __createBinding, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources, + __rewriteRelativeImportExtension, +} = tslib; +export { + __extends, + __assign, + __rest, + __decorate, + __param, + __esDecorate, + __runInitializers, + __propKey, + __setFunctionName, + __metadata, + __awaiter, + __generator, + __exportStar, + __createBinding, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources, + __rewriteRelativeImportExtension, +}; +export default tslib; diff --git a/node_modules/tslib/modules/package.json b/node_modules/tslib/modules/package.json new file mode 100644 index 0000000..96ae6e5 --- /dev/null +++ b/node_modules/tslib/modules/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} \ No newline at end of file diff --git a/node_modules/tslib/package.json b/node_modules/tslib/package.json new file mode 100644 index 0000000..57d0578 --- /dev/null +++ b/node_modules/tslib/package.json @@ -0,0 +1,47 @@ +{ + "name": "tslib", + "author": "Microsoft Corp.", + "homepage": "https://www.typescriptlang.org/", + "version": "2.8.1", + "license": "0BSD", + "description": "Runtime library for TypeScript helper functions", + "keywords": [ + "TypeScript", + "Microsoft", + "compiler", + "language", + "javascript", + "tslib", + "runtime" + ], + "bugs": { + "url": "https://github.com/Microsoft/TypeScript/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/Microsoft/tslib.git" + }, + "main": "tslib.js", + "module": "tslib.es6.js", + "jsnext:main": "tslib.es6.js", + "typings": "tslib.d.ts", + "sideEffects": false, + "exports": { + ".": { + "module": { + "types": "./modules/index.d.ts", + "default": "./tslib.es6.mjs" + }, + "import": { + "node": "./modules/index.js", + "default": { + "types": "./modules/index.d.ts", + "default": "./tslib.es6.mjs" + } + }, + "default": "./tslib.js" + }, + "./*": "./*", + "./": "./" + } +} diff --git a/node_modules/tslib/tslib.d.ts b/node_modules/tslib/tslib.d.ts new file mode 100644 index 0000000..9c27e05 --- /dev/null +++ b/node_modules/tslib/tslib.d.ts @@ -0,0 +1,460 @@ +/****************************************************************************** +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. +***************************************************************************** */ + +/** + * Used to shim class extends. + * + * @param d The derived class. + * @param b The base class. + */ +export declare function __extends(d: Function, b: Function): void; + +/** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * + * @param t The target object to copy to. + * @param sources One or more source objects from which to copy properties + */ +export declare function __assign(t: any, ...sources: any[]): any; + +/** + * Performs a rest spread on an object. + * + * @param t The source value. + * @param propertyNames The property names excluded from the rest spread. + */ +export declare function __rest(t: any, propertyNames: (string | symbol)[]): any; + +/** + * Applies decorators to a target object + * + * @param decorators The set of decorators to apply. + * @param target The target object. + * @param key If specified, the own property to apply the decorators to. + * @param desc The property descriptor, defaults to fetching the descriptor from the target object. + * @experimental + */ +export declare function __decorate(decorators: Function[], target: any, key?: string | symbol, desc?: any): any; + +/** + * Creates an observing function decorator from a parameter decorator. + * + * @param paramIndex The parameter index to apply the decorator to. + * @param decorator The parameter decorator to apply. Note that the return value is ignored. + * @experimental + */ +export declare function __param(paramIndex: number, decorator: Function): Function; + +/** + * Applies decorators to a class or class member, following the native ECMAScript decorator specification. + * @param ctor For non-field class members, the class constructor. Otherwise, `null`. + * @param descriptorIn The `PropertyDescriptor` to use when unable to look up the property from `ctor`. + * @param decorators The decorators to apply + * @param contextIn The `DecoratorContext` to clone for each decorator application. + * @param initializers An array of field initializer mutation functions into which new initializers are written. + * @param extraInitializers An array of extra initializer functions into which new initializers are written. + */ +export declare function __esDecorate(ctor: Function | null, descriptorIn: object | null, decorators: Function[], contextIn: object, initializers: Function[] | null, extraInitializers: Function[]): void; + +/** + * Runs field initializers or extra initializers generated by `__esDecorate`. + * @param thisArg The `this` argument to use. + * @param initializers The array of initializers to evaluate. + * @param value The initial value to pass to the initializers. + */ +export declare function __runInitializers(thisArg: unknown, initializers: Function[], value?: any): any; + +/** + * Converts a computed property name into a `string` or `symbol` value. + */ +export declare function __propKey(x: any): string | symbol; + +/** + * Assigns the name of a function derived from the left-hand side of an assignment. + * @param f The function to rename. + * @param name The new name for the function. + * @param prefix A prefix (such as `"get"` or `"set"`) to insert before the name. + */ +export declare function __setFunctionName(f: Function, name: string | symbol, prefix?: string): Function; + +/** + * Creates a decorator that sets metadata. + * + * @param metadataKey The metadata key + * @param metadataValue The metadata value + * @experimental + */ +export declare function __metadata(metadataKey: any, metadataValue: any): Function; + +/** + * Converts a generator function into a pseudo-async function, by treating each `yield` as an `await`. + * + * @param thisArg The reference to use as the `this` value in the generator function + * @param _arguments The optional arguments array + * @param P The optional promise constructor argument, defaults to the `Promise` property of the global object. + * @param generator The generator function + */ +export declare function __awaiter(thisArg: any, _arguments: any, P: Function, generator: Function): any; + +/** + * Creates an Iterator object using the body as the implementation. + * + * @param thisArg The reference to use as the `this` value in the function + * @param body The generator state-machine based implementation. + * + * @see [./docs/generator.md] + */ +export declare function __generator(thisArg: any, body: Function): any; + +/** + * Creates bindings for all enumerable properties of `m` on `exports` + * + * @param m The source object + * @param o The `exports` object. + */ +export declare function __exportStar(m: any, o: any): void; + +/** + * Creates a value iterator from an `Iterable` or `ArrayLike` object. + * + * @param o The object. + * @throws {TypeError} If `o` is neither `Iterable`, nor an `ArrayLike`. + */ +export declare function __values(o: any): any; + +/** + * Reads values from an `Iterable` or `ArrayLike` object and returns the resulting array. + * + * @param o The object to read from. + * @param n The maximum number of arguments to read, defaults to `Infinity`. + */ +export declare function __read(o: any, n?: number): any[]; + +/** + * Creates an array from iterable spread. + * + * @param args The Iterable objects to spread. + * @deprecated since TypeScript 4.2 - Use `__spreadArray` + */ +export declare function __spread(...args: any[][]): any[]; + +/** + * Creates an array from array spread. + * + * @param args The ArrayLikes to spread into the resulting array. + * @deprecated since TypeScript 4.2 - Use `__spreadArray` + */ +export declare function __spreadArrays(...args: any[][]): any[]; + +/** + * Spreads the `from` array into the `to` array. + * + * @param pack Replace empty elements with `undefined`. + */ +export declare function __spreadArray(to: any[], from: any[], pack?: boolean): any[]; + +/** + * Creates an object that signals to `__asyncGenerator` that it shouldn't be yielded, + * and instead should be awaited and the resulting value passed back to the generator. + * + * @param v The value to await. + */ +export declare function __await(v: any): any; + +/** + * Converts a generator function into an async generator function, by using `yield __await` + * in place of normal `await`. + * + * @param thisArg The reference to use as the `this` value in the generator function + * @param _arguments The optional arguments array + * @param generator The generator function + */ +export declare function __asyncGenerator(thisArg: any, _arguments: any, generator: Function): any; + +/** + * Used to wrap a potentially async iterator in such a way so that it wraps the result + * of calling iterator methods of `o` in `__await` instances, and then yields the awaited values. + * + * @param o The potentially async iterator. + * @returns A synchronous iterator yielding `__await` instances on every odd invocation + * and returning the awaited `IteratorResult` passed to `next` every even invocation. + */ +export declare function __asyncDelegator(o: any): any; + +/** + * Creates a value async iterator from an `AsyncIterable`, `Iterable` or `ArrayLike` object. + * + * @param o The object. + * @throws {TypeError} If `o` is neither `AsyncIterable`, `Iterable`, nor an `ArrayLike`. + */ +export declare function __asyncValues(o: any): any; + +/** + * Creates a `TemplateStringsArray` frozen object from the `cooked` and `raw` arrays. + * + * @param cooked The cooked possibly-sparse array. + * @param raw The raw string content. + */ +export declare function __makeTemplateObject(cooked: string[], raw: string[]): TemplateStringsArray; + +/** + * Used to shim default and named imports in ECMAScript Modules transpiled to CommonJS. + * + * ```js + * import Default, { Named, Other } from "mod"; + * // or + * import { default as Default, Named, Other } from "mod"; + * ``` + * + * @param mod The CommonJS module exports object. + */ +export declare function __importStar(mod: T): T; + +/** + * Used to shim default imports in ECMAScript Modules transpiled to CommonJS. + * + * ```js + * import Default from "mod"; + * ``` + * + * @param mod The CommonJS module exports object. + */ +export declare function __importDefault(mod: T): T | { default: T }; + +/** + * Emulates reading a private instance field. + * + * @param receiver The instance from which to read the private field. + * @param state A WeakMap containing the private field value for an instance. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * + * @throws {TypeError} If `state` doesn't have an entry for `receiver`. + */ +export declare function __classPrivateFieldGet( + receiver: T, + state: { has(o: T): boolean, get(o: T): V | undefined }, + kind?: "f" +): V; + +/** + * Emulates reading a private static field. + * + * @param receiver The object from which to read the private static field. + * @param state The class constructor containing the definition of the static field. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The descriptor that holds the static field value. + * + * @throws {TypeError} If `receiver` is not `state`. + */ +export declare function __classPrivateFieldGet unknown, V>( + receiver: T, + state: T, + kind: "f", + f: { value: V } +): V; + +/** + * Emulates evaluating a private instance "get" accessor. + * + * @param receiver The instance on which to evaluate the private "get" accessor. + * @param state A WeakSet used to verify an instance supports the private "get" accessor. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The "get" accessor function to evaluate. + * + * @throws {TypeError} If `state` doesn't have an entry for `receiver`. + */ +export declare function __classPrivateFieldGet( + receiver: T, + state: { has(o: T): boolean }, + kind: "a", + f: () => V +): V; + +/** + * Emulates evaluating a private static "get" accessor. + * + * @param receiver The object on which to evaluate the private static "get" accessor. + * @param state The class constructor containing the definition of the static "get" accessor. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The "get" accessor function to evaluate. + * + * @throws {TypeError} If `receiver` is not `state`. + */ +export declare function __classPrivateFieldGet unknown, V>( + receiver: T, + state: T, + kind: "a", + f: () => V +): V; + +/** + * Emulates reading a private instance method. + * + * @param receiver The instance from which to read a private method. + * @param state A WeakSet used to verify an instance supports the private method. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The function to return as the private instance method. + * + * @throws {TypeError} If `state` doesn't have an entry for `receiver`. + */ +export declare function __classPrivateFieldGet unknown>( + receiver: T, + state: { has(o: T): boolean }, + kind: "m", + f: V +): V; + +/** + * Emulates reading a private static method. + * + * @param receiver The object from which to read the private static method. + * @param state The class constructor containing the definition of the static method. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The function to return as the private static method. + * + * @throws {TypeError} If `receiver` is not `state`. + */ +export declare function __classPrivateFieldGet unknown, V extends (...args: any[]) => unknown>( + receiver: T, + state: T, + kind: "m", + f: V +): V; + +/** + * Emulates writing to a private instance field. + * + * @param receiver The instance on which to set a private field value. + * @param state A WeakMap used to store the private field value for an instance. + * @param value The value to store in the private field. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * + * @throws {TypeError} If `state` doesn't have an entry for `receiver`. + */ +export declare function __classPrivateFieldSet( + receiver: T, + state: { has(o: T): boolean, set(o: T, value: V): unknown }, + value: V, + kind?: "f" +): V; + +/** + * Emulates writing to a private static field. + * + * @param receiver The object on which to set the private static field. + * @param state The class constructor containing the definition of the private static field. + * @param value The value to store in the private field. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The descriptor that holds the static field value. + * + * @throws {TypeError} If `receiver` is not `state`. + */ +export declare function __classPrivateFieldSet unknown, V>( + receiver: T, + state: T, + value: V, + kind: "f", + f: { value: V } +): V; + +/** + * Emulates writing to a private instance "set" accessor. + * + * @param receiver The instance on which to evaluate the private instance "set" accessor. + * @param state A WeakSet used to verify an instance supports the private "set" accessor. + * @param value The value to store in the private accessor. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The "set" accessor function to evaluate. + * + * @throws {TypeError} If `state` doesn't have an entry for `receiver`. + */ +export declare function __classPrivateFieldSet( + receiver: T, + state: { has(o: T): boolean }, + value: V, + kind: "a", + f: (v: V) => void +): V; + +/** + * Emulates writing to a private static "set" accessor. + * + * @param receiver The object on which to evaluate the private static "set" accessor. + * @param state The class constructor containing the definition of the static "set" accessor. + * @param value The value to store in the private field. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The "set" accessor function to evaluate. + * + * @throws {TypeError} If `receiver` is not `state`. + */ +export declare function __classPrivateFieldSet unknown, V>( + receiver: T, + state: T, + value: V, + kind: "a", + f: (v: V) => void +): V; + +/** + * Checks for the existence of a private field/method/accessor. + * + * @param state The class constructor containing the static member, or the WeakMap or WeakSet associated with a private instance member. + * @param receiver The object for which to test the presence of the private member. + */ +export declare function __classPrivateFieldIn( + state: (new (...args: any[]) => unknown) | { has(o: any): boolean }, + receiver: unknown, +): boolean; + +/** + * Creates a re-export binding on `object` with key `objectKey` that references `target[key]`. + * + * @param object The local `exports` object. + * @param target The object to re-export from. + * @param key The property key of `target` to re-export. + * @param objectKey The property key to re-export as. Defaults to `key`. + */ +export declare function __createBinding(object: object, target: object, key: PropertyKey, objectKey?: PropertyKey): void; + +/** + * Adds a disposable resource to a resource-tracking environment object. + * @param env A resource-tracking environment object. + * @param value Either a Disposable or AsyncDisposable object, `null`, or `undefined`. + * @param async When `true`, `AsyncDisposable` resources can be added. When `false`, `AsyncDisposable` resources cannot be added. + * @returns The {@link value} argument. + * + * @throws {TypeError} If {@link value} is not an object, or if either `Symbol.dispose` or `Symbol.asyncDispose` are not + * defined, or if {@link value} does not have an appropriate `Symbol.dispose` or `Symbol.asyncDispose` method. + */ +export declare function __addDisposableResource(env: { stack: { value?: unknown, dispose?: Function, async: boolean }[]; error: unknown; hasError: boolean; }, value: T, async: boolean): T; + +/** + * Disposes all resources in a resource-tracking environment object. + * @param env A resource-tracking environment object. + * @returns A {@link Promise} if any resources in the environment were marked as `async` when added; otherwise, `void`. + * + * @throws {SuppressedError} if an error thrown during disposal would have suppressed a prior error from disposal or the + * error recorded in the resource-tracking environment object. + * @seealso {@link __addDisposableResource} + */ +export declare function __disposeResources(env: { stack: { value?: unknown, dispose?: Function, async: boolean }[]; error: unknown; hasError: boolean; }): any; + +/** + * Transforms a relative import specifier ending in a non-declaration TypeScript file extension to its JavaScript file extension counterpart. + * @param path The import specifier. + * @param preserveJsx Causes '*.tsx' to transform to '*.jsx' instead of '*.js'. Should be true when `--jsx` is set to `preserve`. + */ +export declare function __rewriteRelativeImportExtension(path: string, preserveJsx?: boolean): string; \ No newline at end of file diff --git a/node_modules/tslib/tslib.es6.html b/node_modules/tslib/tslib.es6.html new file mode 100644 index 0000000..b122e41 --- /dev/null +++ b/node_modules/tslib/tslib.es6.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/node_modules/tslib/tslib.es6.js b/node_modules/tslib/tslib.es6.js new file mode 100644 index 0000000..67ba5c5 --- /dev/null +++ b/node_modules/tslib/tslib.es6.js @@ -0,0 +1,402 @@ +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +export function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +export var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + } + return __assign.apply(this, arguments); +} + +export function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} + +export function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} + +export function __param(paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } +} + +export function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + 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 _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(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 (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; + +export function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; + +export function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +}; + +export function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; + +export function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} + +export function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +export function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +export var __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +}); + +export function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} + +export function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +export function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +} + +/** @deprecated */ +export function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} + +/** @deprecated */ +export function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} + +export function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} + +export function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +export function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +export function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +export function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +export function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; + +var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}; + +var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); +}; + +export function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; +} + +export function __importDefault(mod) { + return (mod && mod.__esModule) ? mod : { default: mod }; +} + +export function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +export function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +} + +export 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); +} + +export 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 (e) { return Promise.reject(e); } }; + env.stack.push({ value: value, dispose: dispose, async: async }); + } + else if (async) { + env.stack.push({ async: true }); + } + return value; + +} + +var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +export function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + else s |= 1; + } + catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); +} + +export function __rewriteRelativeImportExtension(path, preserveJsx) { + if (typeof path === "string" && /^\.\.?\//.test(path)) { + return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) { + return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js"); + }); + } + return path; +} + +export default { + __extends: __extends, + __assign: __assign, + __rest: __rest, + __decorate: __decorate, + __param: __param, + __esDecorate: __esDecorate, + __runInitializers: __runInitializers, + __propKey: __propKey, + __setFunctionName: __setFunctionName, + __metadata: __metadata, + __awaiter: __awaiter, + __generator: __generator, + __createBinding: __createBinding, + __exportStar: __exportStar, + __values: __values, + __read: __read, + __spread: __spread, + __spreadArrays: __spreadArrays, + __spreadArray: __spreadArray, + __await: __await, + __asyncGenerator: __asyncGenerator, + __asyncDelegator: __asyncDelegator, + __asyncValues: __asyncValues, + __makeTemplateObject: __makeTemplateObject, + __importStar: __importStar, + __importDefault: __importDefault, + __classPrivateFieldGet: __classPrivateFieldGet, + __classPrivateFieldSet: __classPrivateFieldSet, + __classPrivateFieldIn: __classPrivateFieldIn, + __addDisposableResource: __addDisposableResource, + __disposeResources: __disposeResources, + __rewriteRelativeImportExtension: __rewriteRelativeImportExtension, +}; diff --git a/node_modules/tslib/tslib.es6.mjs b/node_modules/tslib/tslib.es6.mjs new file mode 100644 index 0000000..c17990a --- /dev/null +++ b/node_modules/tslib/tslib.es6.mjs @@ -0,0 +1,401 @@ +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +export function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +export var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + } + return __assign.apply(this, arguments); +} + +export function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} + +export function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} + +export function __param(paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } +} + +export function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + 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 _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(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 (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; + +export function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; + +export function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +}; + +export function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; + +export function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} + +export function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +export function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +export var __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +}); + +export function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} + +export function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +export function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +} + +/** @deprecated */ +export function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} + +/** @deprecated */ +export function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} + +export function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} + +export function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +export function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +export function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +export function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +export function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; + +var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}; + +var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); +}; + +export function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; +} + +export function __importDefault(mod) { + return (mod && mod.__esModule) ? mod : { default: mod }; +} + +export function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +export function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +} + +export 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); +} + +export 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 (e) { return Promise.reject(e); } }; + env.stack.push({ value: value, dispose: dispose, async: async }); + } + else if (async) { + env.stack.push({ async: true }); + } + return value; +} + +var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +export function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + else s |= 1; + } + catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); +} + +export function __rewriteRelativeImportExtension(path, preserveJsx) { + if (typeof path === "string" && /^\.\.?\//.test(path)) { + return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) { + return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js"); + }); + } + return path; +} + +export 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, +}; diff --git a/node_modules/tslib/tslib.html b/node_modules/tslib/tslib.html new file mode 100644 index 0000000..44c9ba5 --- /dev/null +++ b/node_modules/tslib/tslib.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/node_modules/tslib/tslib.js b/node_modules/tslib/tslib.js new file mode 100644 index 0000000..b6509f7 --- /dev/null +++ b/node_modules/tslib/tslib.js @@ -0,0 +1,484 @@ +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global global, define, Symbol, Reflect, Promise, SuppressedError, Iterator */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __esDecorate; +var __runInitializers; +var __propKey; +var __setFunctionName; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __spreadArray; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __classPrivateFieldIn; +var __createBinding; +var __addDisposableResource; +var __disposeResources; +var __rewriteRelativeImportExtension; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if (typeof module === "object" && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + + __extends = function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + 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 _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(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 (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; + }; + + __runInitializers = function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; + }; + + __propKey = function (x) { + return typeof x === "symbol" ? x : "".concat(x); + }; + + __setFunctionName = function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __exportStar = function(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); + }; + + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + /** @deprecated */ + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + /** @deprecated */ + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __spreadArray = function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; + }; + + __classPrivateFieldIn = function (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); + }; + + __addDisposableResource = function (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 (e) { return Promise.reject(e); } }; + env.stack.push({ value: value, dispose: dispose, async: async }); + } + else if (async) { + env.stack.push({ async: true }); + } + return value; + }; + + var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + __disposeResources = function (env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + else s |= 1; + } + catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); + }; + + __rewriteRelativeImportExtension = function (path, preserveJsx) { + if (typeof path === "string" && /^\.\.?\//.test(path)) { + return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) { + return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js"); + }); + } + return path; + }; + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__esDecorate", __esDecorate); + exporter("__runInitializers", __runInitializers); + exporter("__propKey", __propKey); + exporter("__setFunctionName", __setFunctionName); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__spreadArray", __spreadArray); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); + exporter("__classPrivateFieldIn", __classPrivateFieldIn); + exporter("__addDisposableResource", __addDisposableResource); + exporter("__disposeResources", __disposeResources); + exporter("__rewriteRelativeImportExtension", __rewriteRelativeImportExtension); +}); + +0 && (module.exports = { + __extends: __extends, + __assign: __assign, + __rest: __rest, + __decorate: __decorate, + __param: __param, + __esDecorate: __esDecorate, + __runInitializers: __runInitializers, + __propKey: __propKey, + __setFunctionName: __setFunctionName, + __metadata: __metadata, + __awaiter: __awaiter, + __generator: __generator, + __exportStar: __exportStar, + __createBinding: __createBinding, + __values: __values, + __read: __read, + __spread: __spread, + __spreadArrays: __spreadArrays, + __spreadArray: __spreadArray, + __await: __await, + __asyncGenerator: __asyncGenerator, + __asyncDelegator: __asyncDelegator, + __asyncValues: __asyncValues, + __makeTemplateObject: __makeTemplateObject, + __importStar: __importStar, + __importDefault: __importDefault, + __classPrivateFieldGet: __classPrivateFieldGet, + __classPrivateFieldSet: __classPrivateFieldSet, + __classPrivateFieldIn: __classPrivateFieldIn, + __addDisposableResource: __addDisposableResource, + __disposeResources: __disposeResources, + __rewriteRelativeImportExtension: __rewriteRelativeImportExtension, +}); diff --git a/node_modules/undici-types/LICENSE b/node_modules/undici-types/LICENSE new file mode 100644 index 0000000..e7323bb --- /dev/null +++ b/node_modules/undici-types/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Matteo Collina and Undici contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/undici-types/README.md b/node_modules/undici-types/README.md new file mode 100644 index 0000000..20a721c --- /dev/null +++ b/node_modules/undici-types/README.md @@ -0,0 +1,6 @@ +# undici-types + +This package is a dual-publish of the [undici](https://www.npmjs.com/package/undici) library types. The `undici` package **still contains types**. This package is for users who _only_ need undici types (such as for `@types/node`). It is published alongside every release of `undici`, so you can always use the same version. + +- [GitHub nodejs/undici](https://github.com/nodejs/undici) +- [Undici Documentation](https://undici.nodejs.org/#/) diff --git a/node_modules/undici-types/agent.d.ts b/node_modules/undici-types/agent.d.ts new file mode 100644 index 0000000..58081ce --- /dev/null +++ b/node_modules/undici-types/agent.d.ts @@ -0,0 +1,31 @@ +import { URL } from 'url' +import Pool from './pool' +import Dispatcher from "./dispatcher"; + +export default Agent + +declare class Agent extends Dispatcher{ + constructor(opts?: Agent.Options) + /** `true` after `dispatcher.close()` has been called. */ + closed: boolean; + /** `true` after `dispatcher.destroyed()` has been called or `dispatcher.close()` has been called and the dispatcher shutdown has completed. */ + destroyed: boolean; + /** Dispatches a request. */ + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; +} + +declare namespace Agent { + export interface Options extends Pool.Options { + /** Default: `(origin, opts) => new Pool(origin, opts)`. */ + factory?(origin: string | URL, opts: Object): Dispatcher; + /** Integer. Default: `0` */ + maxRedirections?: number; + + interceptors?: { Agent?: readonly Dispatcher.DispatchInterceptor[] } & Pool.Options["interceptors"] + } + + export interface DispatchOptions extends Dispatcher.DispatchOptions { + /** Integer. */ + maxRedirections?: number; + } +} diff --git a/node_modules/undici-types/api.d.ts b/node_modules/undici-types/api.d.ts new file mode 100644 index 0000000..400341d --- /dev/null +++ b/node_modules/undici-types/api.d.ts @@ -0,0 +1,43 @@ +import { URL, UrlObject } from 'url' +import { Duplex } from 'stream' +import Dispatcher from './dispatcher' + +export { + request, + stream, + pipeline, + connect, + upgrade, +} + +/** Performs an HTTP request. */ +declare function request( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit & Partial>, +): Promise; + +/** A faster version of `request`. */ +declare function stream( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, + factory: Dispatcher.StreamFactory +): Promise; + +/** For easy use with `stream.pipeline`. */ +declare function pipeline( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, + handler: Dispatcher.PipelineHandler +): Duplex; + +/** Starts two-way communications with the requested resource. */ +declare function connect( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit +): Promise; + +/** Upgrade to a different protocol. */ +declare function upgrade( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit +): Promise; diff --git a/node_modules/undici-types/balanced-pool.d.ts b/node_modules/undici-types/balanced-pool.d.ts new file mode 100644 index 0000000..7f930f4 --- /dev/null +++ b/node_modules/undici-types/balanced-pool.d.ts @@ -0,0 +1,29 @@ +import Pool from './pool' +import Dispatcher from './dispatcher' +import { URL } from 'url' + +export default BalancedPool + +type BalancedPoolConnectOptions = Omit; + +declare class BalancedPool extends Dispatcher { + constructor(url: string | string[] | URL | URL[], options?: Pool.Options); + + addUpstream(upstream: string | URL): BalancedPool; + removeUpstream(upstream: string | URL): BalancedPool; + upstreams: Array; + + /** `true` after `pool.close()` has been called. */ + closed: boolean; + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean; + + // Override dispatcher APIs. + override connect( + options: BalancedPoolConnectOptions + ): Promise; + override connect( + options: BalancedPoolConnectOptions, + callback: (err: Error | null, data: Dispatcher.ConnectData) => void + ): void; +} diff --git a/node_modules/undici-types/cache.d.ts b/node_modules/undici-types/cache.d.ts new file mode 100644 index 0000000..4c33335 --- /dev/null +++ b/node_modules/undici-types/cache.d.ts @@ -0,0 +1,36 @@ +import type { RequestInfo, Response, Request } from './fetch' + +export interface CacheStorage { + match (request: RequestInfo, options?: MultiCacheQueryOptions): Promise, + has (cacheName: string): Promise, + open (cacheName: string): Promise, + delete (cacheName: string): Promise, + keys (): Promise +} + +declare const CacheStorage: { + prototype: CacheStorage + new(): CacheStorage +} + +export interface Cache { + match (request: RequestInfo, options?: CacheQueryOptions): Promise, + matchAll (request?: RequestInfo, options?: CacheQueryOptions): Promise, + add (request: RequestInfo): Promise, + addAll (requests: RequestInfo[]): Promise, + put (request: RequestInfo, response: Response): Promise, + delete (request: RequestInfo, options?: CacheQueryOptions): Promise, + keys (request?: RequestInfo, options?: CacheQueryOptions): Promise +} + +export interface CacheQueryOptions { + ignoreSearch?: boolean, + ignoreMethod?: boolean, + ignoreVary?: boolean +} + +export interface MultiCacheQueryOptions extends CacheQueryOptions { + cacheName?: string +} + +export declare const caches: CacheStorage diff --git a/node_modules/undici-types/client.d.ts b/node_modules/undici-types/client.d.ts new file mode 100644 index 0000000..d0a5379 --- /dev/null +++ b/node_modules/undici-types/client.d.ts @@ -0,0 +1,108 @@ +import { URL } from 'url' +import { TlsOptions } from 'tls' +import Dispatcher from './dispatcher' +import buildConnector from "./connector"; + +type ClientConnectOptions = Omit; + +/** + * A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default. + */ +export class Client extends Dispatcher { + constructor(url: string | URL, options?: Client.Options); + /** Property to get and set the pipelining factor. */ + pipelining: number; + /** `true` after `client.close()` has been called. */ + closed: boolean; + /** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */ + destroyed: boolean; + + // Override dispatcher APIs. + override connect( + options: ClientConnectOptions + ): Promise; + override connect( + options: ClientConnectOptions, + callback: (err: Error | null, data: Dispatcher.ConnectData) => void + ): void; +} + +export declare namespace Client { + export interface OptionsInterceptors { + Client: readonly Dispatcher.DispatchInterceptor[]; + } + export interface Options { + /** TODO */ + interceptors?: OptionsInterceptors; + /** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */ + maxHeaderSize?: number; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */ + headersTimeout?: number; + /** @deprecated unsupported socketTimeout, use headersTimeout & bodyTimeout instead */ + socketTimeout?: never; + /** @deprecated unsupported requestTimeout, use headersTimeout & bodyTimeout instead */ + requestTimeout?: never; + /** TODO */ + connectTimeout?: number; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */ + bodyTimeout?: number; + /** @deprecated unsupported idleTimeout, use keepAliveTimeout instead */ + idleTimeout?: never; + /** @deprecated unsupported keepAlive, use pipelining=0 instead */ + keepAlive?: never; + /** the timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */ + keepAliveTimeout?: number; + /** @deprecated unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead */ + maxKeepAliveTimeout?: never; + /** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */ + keepAliveMaxTimeout?: number; + /** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */ + keepAliveTimeoutThreshold?: number; + /** TODO */ + socketPath?: string; + /** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */ + pipelining?: number; + /** @deprecated use the connect option instead */ + tls?: never; + /** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */ + strictContentLength?: boolean; + /** TODO */ + maxCachedSessions?: number; + /** TODO */ + maxRedirections?: number; + /** TODO */ + connect?: buildConnector.BuildOptions | buildConnector.connector; + /** TODO */ + maxRequestsPerClient?: number; + /** TODO */ + localAddress?: string; + /** Max response body size in bytes, -1 is disabled */ + maxResponseSize?: number; + /** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */ + autoSelectFamily?: boolean; + /** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */ + autoSelectFamilyAttemptTimeout?: number; + /** + * @description Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation. + * @default false + */ + allowH2?: boolean; + /** + * @description Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame. + * @default 100 + */ + maxConcurrentStreams?: number + } + export interface SocketInfo { + localAddress?: string + localPort?: number + remoteAddress?: string + remotePort?: number + remoteFamily?: string + timeout?: number + bytesWritten?: number + bytesRead?: number + } +} + +export default Client; diff --git a/node_modules/undici-types/connector.d.ts b/node_modules/undici-types/connector.d.ts new file mode 100644 index 0000000..bd92433 --- /dev/null +++ b/node_modules/undici-types/connector.d.ts @@ -0,0 +1,34 @@ +import { TLSSocket, ConnectionOptions } from 'tls' +import { IpcNetConnectOpts, Socket, TcpNetConnectOpts } from 'net' + +export default buildConnector +declare function buildConnector (options?: buildConnector.BuildOptions): buildConnector.connector + +declare namespace buildConnector { + export type BuildOptions = (ConnectionOptions | TcpNetConnectOpts | IpcNetConnectOpts) & { + allowH2?: boolean; + maxCachedSessions?: number | null; + socketPath?: string | null; + timeout?: number | null; + port?: number; + keepAlive?: boolean | null; + keepAliveInitialDelay?: number | null; + } + + export interface Options { + hostname: string + host?: string + protocol: string + port: string + servername?: string + localAddress?: string | null + httpSocket?: Socket + } + + export type Callback = (...args: CallbackArgs) => void + type CallbackArgs = [null, Socket | TLSSocket] | [Error, null] + + export interface connector { + (options: buildConnector.Options, callback: buildConnector.Callback): void + } +} diff --git a/node_modules/undici-types/content-type.d.ts b/node_modules/undici-types/content-type.d.ts new file mode 100644 index 0000000..f2a87f1 --- /dev/null +++ b/node_modules/undici-types/content-type.d.ts @@ -0,0 +1,21 @@ +/// + +interface MIMEType { + type: string + subtype: string + parameters: Map + essence: string +} + +/** + * Parse a string to a {@link MIMEType} object. Returns `failure` if the string + * couldn't be parsed. + * @see https://mimesniff.spec.whatwg.org/#parse-a-mime-type + */ +export function parseMIMEType (input: string): 'failure' | MIMEType + +/** + * Convert a MIMEType object to a string. + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +export function serializeAMimeType (mimeType: MIMEType): string diff --git a/node_modules/undici-types/cookies.d.ts b/node_modules/undici-types/cookies.d.ts new file mode 100644 index 0000000..aa38cae --- /dev/null +++ b/node_modules/undici-types/cookies.d.ts @@ -0,0 +1,28 @@ +/// + +import type { Headers } from './fetch' + +export interface Cookie { + name: string + value: string + expires?: Date | number + maxAge?: number + domain?: string + path?: string + secure?: boolean + httpOnly?: boolean + sameSite?: 'Strict' | 'Lax' | 'None' + unparsed?: string[] +} + +export function deleteCookie ( + headers: Headers, + name: string, + attributes?: { name?: string, domain?: string } +): void + +export function getCookies (headers: Headers): Record + +export function getSetCookies (headers: Headers): Cookie[] + +export function setCookie (headers: Headers, cookie: Cookie): void diff --git a/node_modules/undici-types/diagnostics-channel.d.ts b/node_modules/undici-types/diagnostics-channel.d.ts new file mode 100644 index 0000000..a037d1e --- /dev/null +++ b/node_modules/undici-types/diagnostics-channel.d.ts @@ -0,0 +1,66 @@ +import { Socket } from "net"; +import { URL } from "url"; +import Connector from "./connector"; +import Dispatcher from "./dispatcher"; + +declare namespace DiagnosticsChannel { + interface Request { + origin?: string | URL; + completed: boolean; + method?: Dispatcher.HttpMethod; + path: string; + headers: any; + } + interface Response { + statusCode: number; + statusText: string; + headers: Array; + } + type Error = unknown; + interface ConnectParams { + host: URL["host"]; + hostname: URL["hostname"]; + protocol: URL["protocol"]; + port: URL["port"]; + servername: string | null; + } + type Connector = Connector.connector; + export interface RequestCreateMessage { + request: Request; + } + export interface RequestBodySentMessage { + request: Request; + } + export interface RequestHeadersMessage { + request: Request; + response: Response; + } + export interface RequestTrailersMessage { + request: Request; + trailers: Array; + } + export interface RequestErrorMessage { + request: Request; + error: Error; + } + export interface ClientSendHeadersMessage { + request: Request; + headers: string; + socket: Socket; + } + export interface ClientBeforeConnectMessage { + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectedMessage { + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectErrorMessage { + error: Error; + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } +} diff --git a/node_modules/undici-types/dispatcher.d.ts b/node_modules/undici-types/dispatcher.d.ts new file mode 100644 index 0000000..1b4c9c7 --- /dev/null +++ b/node_modules/undici-types/dispatcher.d.ts @@ -0,0 +1,256 @@ +import { URL } from 'url' +import { Duplex, Readable, Writable } from 'stream' +import { EventEmitter } from 'events' +import { Blob } from 'buffer' +import { IncomingHttpHeaders } from './header' +import BodyReadable from './readable' +import { FormData } from './formdata' +import Errors from './errors' + +type AbortSignal = unknown; + +export default Dispatcher + +/** Dispatcher is the core API used to dispatch requests. */ +declare class Dispatcher extends EventEmitter { + /** Dispatches a request. This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. It is primarily intended for library developers who implement higher level APIs on top of this. */ + dispatch(options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + /** Starts two-way communications with the requested resource. */ + connect(options: Dispatcher.ConnectOptions): Promise; + connect(options: Dispatcher.ConnectOptions, callback: (err: Error | null, data: Dispatcher.ConnectData) => void): void; + /** Compose a chain of dispatchers */ + compose(dispatchers: Dispatcher.DispatcherComposeInterceptor[]): Dispatcher.ComposedDispatcher; + compose(...dispatchers: Dispatcher.DispatcherComposeInterceptor[]): Dispatcher.ComposedDispatcher; + /** Performs an HTTP request. */ + request(options: Dispatcher.RequestOptions): Promise; + request(options: Dispatcher.RequestOptions, callback: (err: Error | null, data: Dispatcher.ResponseData) => void): void; + /** For easy use with `stream.pipeline`. */ + pipeline(options: Dispatcher.PipelineOptions, handler: Dispatcher.PipelineHandler): Duplex; + /** A faster version of `Dispatcher.request`. */ + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory): Promise; + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory, callback: (err: Error | null, data: Dispatcher.StreamData) => void): void; + /** Upgrade to a different protocol. */ + upgrade(options: Dispatcher.UpgradeOptions): Promise; + upgrade(options: Dispatcher.UpgradeOptions, callback: (err: Error | null, data: Dispatcher.UpgradeData) => void): void; + /** Closes the client and gracefully waits for enqueued requests to complete before invoking the callback (or returning a promise if no callback is provided). */ + close(): Promise; + close(callback: () => void): void; + /** Destroy the client abruptly with the given err. All the pending and running requests will be asynchronously aborted and error. Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. */ + destroy(): Promise; + destroy(err: Error | null): Promise; + destroy(callback: () => void): void; + destroy(err: Error | null, callback: () => void): void; + + on(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + on(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + on(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + on(eventName: 'drain', callback: (origin: URL) => void): this; + + + once(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + once(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + once(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + once(eventName: 'drain', callback: (origin: URL) => void): this; + + + off(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + off(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + off(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + off(eventName: 'drain', callback: (origin: URL) => void): this; + + + addListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + addListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + addListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + addListener(eventName: 'drain', callback: (origin: URL) => void): this; + + removeListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + removeListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + removeListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + removeListener(eventName: 'drain', callback: (origin: URL) => void): this; + + prependListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + prependListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependListener(eventName: 'drain', callback: (origin: URL) => void): this; + + prependOnceListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + prependOnceListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependOnceListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependOnceListener(eventName: 'drain', callback: (origin: URL) => void): this; + + listeners(eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + listeners(eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + listeners(eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + listeners(eventName: 'drain'): ((origin: URL) => void)[]; + + rawListeners(eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + rawListeners(eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + rawListeners(eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + rawListeners(eventName: 'drain'): ((origin: URL) => void)[]; + + emit(eventName: 'connect', origin: URL, targets: readonly Dispatcher[]): boolean; + emit(eventName: 'disconnect', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean; + emit(eventName: 'connectionError', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean; + emit(eventName: 'drain', origin: URL): boolean; +} + +declare namespace Dispatcher { + export interface ComposedDispatcher extends Dispatcher {} + export type DispatcherComposeInterceptor = (dispatch: Dispatcher['dispatch']) => Dispatcher['dispatch']; + export interface DispatchOptions { + origin?: string | URL; + path: string; + method: HttpMethod; + /** Default: `null` */ + body?: string | Buffer | Uint8Array | Readable | null | FormData; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | Iterable<[string, string | string[] | undefined]> | null; + /** Query string params to be embedded in the request URL. Default: `null` */ + query?: Record; + /** Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline have completed. Default: `true` if `method` is `HEAD` or `GET`. */ + idempotent?: boolean; + /** Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. */ + blocking?: boolean; + /** Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. Default: `method === 'CONNECT' || null`. */ + upgrade?: boolean | string | null; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers. Defaults to 300 seconds. */ + headersTimeout?: number | null; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use 0 to disable it entirely. Defaults to 300 seconds. */ + bodyTimeout?: number | null; + /** Whether the request should stablish a keep-alive or not. Default `false` */ + reset?: boolean; + /** Whether Undici should throw an error upon receiving a 4xx or 5xx response from the server. Defaults to false */ + throwOnError?: boolean; + /** For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server*/ + expectContinue?: boolean; + } + export interface ConnectOptions { + origin: string | URL; + path: string; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** This argument parameter is passed through to `ConnectData` */ + opaque?: unknown; + /** Default: 0 */ + maxRedirections?: number; + /** Default: false */ + redirectionLimitReached?: boolean; + /** Default: `null` */ + responseHeader?: 'raw' | null; + } + export interface RequestOptions extends DispatchOptions { + /** Default: `null` */ + opaque?: unknown; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: 0 */ + maxRedirections?: number; + /** Default: false */ + redirectionLimitReached?: boolean; + /** Default: `null` */ + onInfo?: (info: { statusCode: number, headers: Record }) => void; + /** Default: `null` */ + responseHeader?: 'raw' | null; + /** Default: `64 KiB` */ + highWaterMark?: number; + } + export interface PipelineOptions extends RequestOptions { + /** `true` if the `handler` will return an object stream. Default: `false` */ + objectMode?: boolean; + } + export interface UpgradeOptions { + path: string; + /** Default: `'GET'` */ + method?: string; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** A string of comma separated protocols, in descending preference order. Default: `'Websocket'` */ + protocol?: string; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: 0 */ + maxRedirections?: number; + /** Default: false */ + redirectionLimitReached?: boolean; + /** Default: `null` */ + responseHeader?: 'raw' | null; + } + export interface ConnectData { + statusCode: number; + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: unknown; + } + export interface ResponseData { + statusCode: number; + headers: IncomingHttpHeaders; + body: BodyReadable & BodyMixin; + trailers: Record; + opaque: unknown; + context: object; + } + export interface PipelineHandlerData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: unknown; + body: BodyReadable; + context: object; + } + export interface StreamData { + opaque: unknown; + trailers: Record; + } + export interface UpgradeData { + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: unknown; + } + export interface StreamFactoryData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: unknown; + context: object; + } + export type StreamFactory = (data: StreamFactoryData) => Writable; + export interface DispatchHandlers { + /** Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. */ + onConnect?(abort: (err?: Error) => void): void; + /** Invoked when an error has occurred. */ + onError?(err: Error): void; + /** Invoked when request is upgraded either due to a `Upgrade` header or `CONNECT` method. */ + onUpgrade?(statusCode: number, headers: Buffer[] | string[] | null, socket: Duplex): void; + /** Invoked when response is received, before headers have been read. **/ + onResponseStarted?(): void; + /** Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. */ + onHeaders?(statusCode: number, headers: Buffer[], resume: () => void, statusText: string): boolean; + /** Invoked when response payload data is received. */ + onData?(chunk: Buffer): boolean; + /** Invoked when response payload and trailers have been received and the request has completed. */ + onComplete?(trailers: string[] | null): void; + /** Invoked when a body chunk is sent to the server. May be invoked multiple times for chunked requests */ + onBodySent?(chunkSize: number, totalBytesSent: number): void; + } + export type PipelineHandler = (data: PipelineHandlerData) => Readable; + export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'; + + /** + * @link https://fetch.spec.whatwg.org/#body-mixin + */ + interface BodyMixin { + readonly body?: never; + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + bytes(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; + } + + export interface DispatchInterceptor { + (dispatch: Dispatcher['dispatch']): Dispatcher['dispatch'] + } +} diff --git a/node_modules/undici-types/env-http-proxy-agent.d.ts b/node_modules/undici-types/env-http-proxy-agent.d.ts new file mode 100644 index 0000000..d6509dc --- /dev/null +++ b/node_modules/undici-types/env-http-proxy-agent.d.ts @@ -0,0 +1,21 @@ +import Agent from './agent' +import Dispatcher from './dispatcher' + +export default EnvHttpProxyAgent + +declare class EnvHttpProxyAgent extends Dispatcher { + constructor(opts?: EnvHttpProxyAgent.Options) + + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; +} + +declare namespace EnvHttpProxyAgent { + export interface Options extends Agent.Options { + /** Overrides the value of the HTTP_PROXY environment variable */ + httpProxy?: string; + /** Overrides the value of the HTTPS_PROXY environment variable */ + httpsProxy?: string; + /** Overrides the value of the NO_PROXY environment variable */ + noProxy?: string; + } +} diff --git a/node_modules/undici-types/errors.d.ts b/node_modules/undici-types/errors.d.ts new file mode 100644 index 0000000..f6fb73b --- /dev/null +++ b/node_modules/undici-types/errors.d.ts @@ -0,0 +1,149 @@ +import { IncomingHttpHeaders } from "./header"; +import Client from './client' + +export default Errors + +declare namespace Errors { + export class UndiciError extends Error { + name: string; + code: string; + } + + /** Connect timeout error. */ + export class ConnectTimeoutError extends UndiciError { + name: 'ConnectTimeoutError'; + code: 'UND_ERR_CONNECT_TIMEOUT'; + } + + /** A header exceeds the `headersTimeout` option. */ + export class HeadersTimeoutError extends UndiciError { + name: 'HeadersTimeoutError'; + code: 'UND_ERR_HEADERS_TIMEOUT'; + } + + /** Headers overflow error. */ + export class HeadersOverflowError extends UndiciError { + name: 'HeadersOverflowError' + code: 'UND_ERR_HEADERS_OVERFLOW' + } + + /** A body exceeds the `bodyTimeout` option. */ + export class BodyTimeoutError extends UndiciError { + name: 'BodyTimeoutError'; + code: 'UND_ERR_BODY_TIMEOUT'; + } + + export class ResponseStatusCodeError extends UndiciError { + constructor ( + message?: string, + statusCode?: number, + headers?: IncomingHttpHeaders | string[] | null, + body?: null | Record | string + ); + name: 'ResponseStatusCodeError'; + code: 'UND_ERR_RESPONSE_STATUS_CODE'; + body: null | Record | string + status: number + statusCode: number + headers: IncomingHttpHeaders | string[] | null; + } + + /** Passed an invalid argument. */ + export class InvalidArgumentError extends UndiciError { + name: 'InvalidArgumentError'; + code: 'UND_ERR_INVALID_ARG'; + } + + /** Returned an invalid value. */ + export class InvalidReturnValueError extends UndiciError { + name: 'InvalidReturnValueError'; + code: 'UND_ERR_INVALID_RETURN_VALUE'; + } + + /** The request has been aborted by the user. */ + export class RequestAbortedError extends UndiciError { + name: 'AbortError'; + code: 'UND_ERR_ABORTED'; + } + + /** Expected error with reason. */ + export class InformationalError extends UndiciError { + name: 'InformationalError'; + code: 'UND_ERR_INFO'; + } + + /** Request body length does not match content-length header. */ + export class RequestContentLengthMismatchError extends UndiciError { + name: 'RequestContentLengthMismatchError'; + code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'; + } + + /** Response body length does not match content-length header. */ + export class ResponseContentLengthMismatchError extends UndiciError { + name: 'ResponseContentLengthMismatchError'; + code: 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'; + } + + /** Trying to use a destroyed client. */ + export class ClientDestroyedError extends UndiciError { + name: 'ClientDestroyedError'; + code: 'UND_ERR_DESTROYED'; + } + + /** Trying to use a closed client. */ + export class ClientClosedError extends UndiciError { + name: 'ClientClosedError'; + code: 'UND_ERR_CLOSED'; + } + + /** There is an error with the socket. */ + export class SocketError extends UndiciError { + name: 'SocketError'; + code: 'UND_ERR_SOCKET'; + socket: Client.SocketInfo | null + } + + /** Encountered unsupported functionality. */ + export class NotSupportedError extends UndiciError { + name: 'NotSupportedError'; + code: 'UND_ERR_NOT_SUPPORTED'; + } + + /** No upstream has been added to the BalancedPool. */ + export class BalancedPoolMissingUpstreamError extends UndiciError { + name: 'MissingUpstreamError'; + code: 'UND_ERR_BPL_MISSING_UPSTREAM'; + } + + export class HTTPParserError extends UndiciError { + name: 'HTTPParserError'; + code: string; + } + + /** The response exceed the length allowed. */ + export class ResponseExceededMaxSizeError extends UndiciError { + name: 'ResponseExceededMaxSizeError'; + code: 'UND_ERR_RES_EXCEEDED_MAX_SIZE'; + } + + export class RequestRetryError extends UndiciError { + constructor ( + message: string, + statusCode: number, + headers?: IncomingHttpHeaders | string[] | null, + body?: null | Record | string + ); + name: 'RequestRetryError'; + code: 'UND_ERR_REQ_RETRY'; + statusCode: number; + data: { + count: number; + }; + headers: Record; + } + + export class SecureProxyConnectionError extends UndiciError { + name: 'SecureProxyConnectionError'; + code: 'UND_ERR_PRX_TLS'; + } +} diff --git a/node_modules/undici-types/eventsource.d.ts b/node_modules/undici-types/eventsource.d.ts new file mode 100644 index 0000000..deccd73 --- /dev/null +++ b/node_modules/undici-types/eventsource.d.ts @@ -0,0 +1,61 @@ +import { MessageEvent, ErrorEvent } from './websocket' +import Dispatcher from './dispatcher' + +import { + EventListenerOptions, + AddEventListenerOptions, + EventListenerOrEventListenerObject +} from './patch' + +interface EventSourceEventMap { + error: ErrorEvent + message: MessageEvent + open: Event +} + +interface EventSource extends EventTarget { + close(): void + readonly CLOSED: 2 + readonly CONNECTING: 0 + readonly OPEN: 1 + onerror: (this: EventSource, ev: ErrorEvent) => any + onmessage: (this: EventSource, ev: MessageEvent) => any + onopen: (this: EventSource, ev: Event) => any + readonly readyState: 0 | 1 | 2 + readonly url: string + readonly withCredentials: boolean + + addEventListener( + type: K, + listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, + options?: boolean | AddEventListenerOptions + ): void + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void + removeEventListener( + type: K, + listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, + options?: boolean | EventListenerOptions + ): void + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions + ): void +} + +export declare const EventSource: { + prototype: EventSource + new (url: string | URL, init?: EventSourceInit): EventSource + readonly CLOSED: 2 + readonly CONNECTING: 0 + readonly OPEN: 1 +} + +interface EventSourceInit { + withCredentials?: boolean, + dispatcher?: Dispatcher +} diff --git a/node_modules/undici-types/fetch.d.ts b/node_modules/undici-types/fetch.d.ts new file mode 100644 index 0000000..7e94375 --- /dev/null +++ b/node_modules/undici-types/fetch.d.ts @@ -0,0 +1,209 @@ +// based on https://github.com/Ethan-Arrowood/undici-fetch/blob/249269714db874351589d2d364a0645d5160ae71/index.d.ts (MIT license) +// and https://github.com/node-fetch/node-fetch/blob/914ce6be5ec67a8bab63d68510aabf07cb818b6d/index.d.ts (MIT license) +/// + +import { Blob } from 'buffer' +import { URL, URLSearchParams } from 'url' +import { ReadableStream } from 'stream/web' +import { FormData } from './formdata' + +import Dispatcher from './dispatcher' + +export type RequestInfo = string | URL | Request + +export declare function fetch ( + input: RequestInfo, + init?: RequestInit +): Promise + +export type BodyInit = + | ArrayBuffer + | AsyncIterable + | Blob + | FormData + | Iterable + | NodeJS.ArrayBufferView + | URLSearchParams + | null + | string + +export class BodyMixin { + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + /** + * @deprecated This method is not recommended for parsing multipart/form-data bodies in server environments. + * It is recommended to use a library such as [@fastify/busboy](https://www.npmjs.com/package/@fastify/busboy) as follows: + * + * @example + * ```js + * import { Busboy } from '@fastify/busboy' + * import { Readable } from 'node:stream' + * + * const response = await fetch('...') + * const busboy = new Busboy({ headers: { 'content-type': response.headers.get('content-type') } }) + * + * // handle events emitted from `busboy` + * + * Readable.fromWeb(response.body).pipe(busboy) + * ``` + */ + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise +} + +export interface SpecIterator { + next(...args: [] | [TNext]): IteratorResult; +} + +export interface SpecIterableIterator extends SpecIterator { + [Symbol.iterator](): SpecIterableIterator; +} + +export interface SpecIterable { + [Symbol.iterator](): SpecIterator; +} + +export type HeadersInit = string[][] | Record> | Headers + +export declare class Headers implements SpecIterable<[string, string]> { + constructor (init?: HeadersInit) + readonly append: (name: string, value: string) => void + readonly delete: (name: string) => void + readonly get: (name: string) => string | null + readonly has: (name: string) => boolean + readonly set: (name: string, value: string) => void + readonly getSetCookie: () => string[] + readonly forEach: ( + callbackfn: (value: string, key: string, iterable: Headers) => void, + thisArg?: unknown + ) => void + + readonly keys: () => SpecIterableIterator + readonly values: () => SpecIterableIterator + readonly entries: () => SpecIterableIterator<[string, string]> + readonly [Symbol.iterator]: () => SpecIterableIterator<[string, string]> +} + +export type RequestCache = + | 'default' + | 'force-cache' + | 'no-cache' + | 'no-store' + | 'only-if-cached' + | 'reload' + +export type RequestCredentials = 'omit' | 'include' | 'same-origin' + +type RequestDestination = + | '' + | 'audio' + | 'audioworklet' + | 'document' + | 'embed' + | 'font' + | 'image' + | 'manifest' + | 'object' + | 'paintworklet' + | 'report' + | 'script' + | 'sharedworker' + | 'style' + | 'track' + | 'video' + | 'worker' + | 'xslt' + +export interface RequestInit { + method?: string + keepalive?: boolean + headers?: HeadersInit + body?: BodyInit | null + redirect?: RequestRedirect + integrity?: string + signal?: AbortSignal | null + credentials?: RequestCredentials + mode?: RequestMode + referrer?: string + referrerPolicy?: ReferrerPolicy + window?: null + dispatcher?: Dispatcher + duplex?: RequestDuplex +} + +export type ReferrerPolicy = + | '' + | 'no-referrer' + | 'no-referrer-when-downgrade' + | 'origin' + | 'origin-when-cross-origin' + | 'same-origin' + | 'strict-origin' + | 'strict-origin-when-cross-origin' + | 'unsafe-url'; + +export type RequestMode = 'cors' | 'navigate' | 'no-cors' | 'same-origin' + +export type RequestRedirect = 'error' | 'follow' | 'manual' + +export type RequestDuplex = 'half' + +export declare class Request extends BodyMixin { + constructor (input: RequestInfo, init?: RequestInit) + + readonly cache: RequestCache + readonly credentials: RequestCredentials + readonly destination: RequestDestination + readonly headers: Headers + readonly integrity: string + readonly method: string + readonly mode: RequestMode + readonly redirect: RequestRedirect + readonly referrer: string + readonly referrerPolicy: ReferrerPolicy + readonly url: string + + readonly keepalive: boolean + readonly signal: AbortSignal + readonly duplex: RequestDuplex + + readonly clone: () => Request +} + +export interface ResponseInit { + readonly status?: number + readonly statusText?: string + readonly headers?: HeadersInit +} + +export type ResponseType = + | 'basic' + | 'cors' + | 'default' + | 'error' + | 'opaque' + | 'opaqueredirect' + +export type ResponseRedirectStatus = 301 | 302 | 303 | 307 | 308 + +export declare class Response extends BodyMixin { + constructor (body?: BodyInit, init?: ResponseInit) + + readonly headers: Headers + readonly ok: boolean + readonly status: number + readonly statusText: string + readonly type: ResponseType + readonly url: string + readonly redirected: boolean + + readonly clone: () => Response + + static error (): Response + static json(data: any, init?: ResponseInit): Response + static redirect (url: string | URL, status: ResponseRedirectStatus): Response +} diff --git a/node_modules/undici-types/file.d.ts b/node_modules/undici-types/file.d.ts new file mode 100644 index 0000000..c695b7a --- /dev/null +++ b/node_modules/undici-types/file.d.ts @@ -0,0 +1,39 @@ +// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/File.ts (MIT) +/// + +import { Blob } from 'buffer' + +export interface BlobPropertyBag { + type?: string + endings?: 'native' | 'transparent' +} + +export interface FilePropertyBag extends BlobPropertyBag { + /** + * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. + */ + lastModified?: number +} + +export declare class File extends Blob { + /** + * Creates a new File instance. + * + * @param fileBits An `Array` strings, or [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). + * @param fileName The name of the file. + * @param options An options object containing optional attributes for the file. + */ + constructor(fileBits: ReadonlyArray, fileName: string, options?: FilePropertyBag) + + /** + * Name of the file referenced by the File object. + */ + readonly name: string + + /** + * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. + */ + readonly lastModified: number + + readonly [Symbol.toStringTag]: string +} diff --git a/node_modules/undici-types/filereader.d.ts b/node_modules/undici-types/filereader.d.ts new file mode 100644 index 0000000..d1c0f9e --- /dev/null +++ b/node_modules/undici-types/filereader.d.ts @@ -0,0 +1,54 @@ +/// + +import { Blob } from 'buffer' +import { DOMException, EventInit } from './patch' + +export declare class FileReader { + __proto__: EventTarget & FileReader + + constructor () + + readAsArrayBuffer (blob: Blob): void + readAsBinaryString (blob: Blob): void + readAsText (blob: Blob, encoding?: string): void + readAsDataURL (blob: Blob): void + + abort (): void + + static readonly EMPTY = 0 + static readonly LOADING = 1 + static readonly DONE = 2 + + readonly EMPTY = 0 + readonly LOADING = 1 + readonly DONE = 2 + + readonly readyState: number + + readonly result: string | ArrayBuffer | null + + readonly error: DOMException | null + + onloadstart: null | ((this: FileReader, event: ProgressEvent) => void) + onprogress: null | ((this: FileReader, event: ProgressEvent) => void) + onload: null | ((this: FileReader, event: ProgressEvent) => void) + onabort: null | ((this: FileReader, event: ProgressEvent) => void) + onerror: null | ((this: FileReader, event: ProgressEvent) => void) + onloadend: null | ((this: FileReader, event: ProgressEvent) => void) +} + +export interface ProgressEventInit extends EventInit { + lengthComputable?: boolean + loaded?: number + total?: number +} + +export declare class ProgressEvent { + __proto__: Event & ProgressEvent + + constructor (type: string, eventInitDict?: ProgressEventInit) + + readonly lengthComputable: boolean + readonly loaded: number + readonly total: number +} diff --git a/node_modules/undici-types/formdata.d.ts b/node_modules/undici-types/formdata.d.ts new file mode 100644 index 0000000..e676b11 --- /dev/null +++ b/node_modules/undici-types/formdata.d.ts @@ -0,0 +1,108 @@ +// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/FormData.ts (MIT) +/// + +import { File } from './file' +import { SpecIterableIterator } from './fetch' + +/** + * A `string` or `File` that represents a single value from a set of `FormData` key-value pairs. + */ +declare type FormDataEntryValue = string | File + +/** + * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using fetch(). + */ +export declare class FormData { + /** + * Appends a new value onto an existing key inside a FormData object, + * or adds the key if it does not already exist. + * + * The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + */ + append(name: string, value: unknown, fileName?: string): void + + /** + * Set a new value for an existing key inside FormData, + * or add the new field if it does not already exist. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + * + */ + set(name: string, value: unknown, fileName?: string): void + + /** + * Returns the first value associated with a given key from within a `FormData` object. + * If you expect multiple values and want all of them, use the `getAll()` method instead. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns A `FormDataEntryValue` containing the value. If the key doesn't exist, the method returns null. + */ + get(name: string): FormDataEntryValue | null + + /** + * Returns all the values associated with a given key from within a `FormData` object. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list. + */ + getAll(name: string): FormDataEntryValue[] + + /** + * Returns a boolean stating whether a `FormData` object contains a certain key. + * + * @param name A string representing the name of the key you want to test for. + * + * @return A boolean value. + */ + has(name: string): boolean + + /** + * Deletes a key and its value(s) from a `FormData` object. + * + * @param name The name of the key you want to delete. + */ + delete(name: string): void + + /** + * Executes given callback function for each field of the FormData instance + */ + forEach: ( + callbackfn: (value: FormDataEntryValue, key: string, iterable: FormData) => void, + thisArg?: unknown + ) => void + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object. + * Each key is a `string`. + */ + keys: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object. + * Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + values: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs. + * The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + entries: () => SpecIterableIterator<[string, FormDataEntryValue]> + + /** + * An alias for FormData#entries() + */ + [Symbol.iterator]: () => SpecIterableIterator<[string, FormDataEntryValue]> + + readonly [Symbol.toStringTag]: string +} diff --git a/node_modules/undici-types/global-dispatcher.d.ts b/node_modules/undici-types/global-dispatcher.d.ts new file mode 100644 index 0000000..728f95c --- /dev/null +++ b/node_modules/undici-types/global-dispatcher.d.ts @@ -0,0 +1,9 @@ +import Dispatcher from "./dispatcher"; + +export { + getGlobalDispatcher, + setGlobalDispatcher +} + +declare function setGlobalDispatcher(dispatcher: DispatcherImplementation): void; +declare function getGlobalDispatcher(): Dispatcher; diff --git a/node_modules/undici-types/global-origin.d.ts b/node_modules/undici-types/global-origin.d.ts new file mode 100644 index 0000000..322542d --- /dev/null +++ b/node_modules/undici-types/global-origin.d.ts @@ -0,0 +1,7 @@ +export { + setGlobalOrigin, + getGlobalOrigin +} + +declare function setGlobalOrigin(origin: string | URL | undefined): void; +declare function getGlobalOrigin(): URL | undefined; \ No newline at end of file diff --git a/node_modules/undici-types/handlers.d.ts b/node_modules/undici-types/handlers.d.ts new file mode 100644 index 0000000..afcda9a --- /dev/null +++ b/node_modules/undici-types/handlers.d.ts @@ -0,0 +1,15 @@ +import Dispatcher from "./dispatcher"; + +export declare class RedirectHandler implements Dispatcher.DispatchHandlers { + constructor( + dispatch: Dispatcher, + maxRedirections: number, + opts: Dispatcher.DispatchOptions, + handler: Dispatcher.DispatchHandlers, + redirectionLimitReached: boolean + ); +} + +export declare class DecoratorHandler implements Dispatcher.DispatchHandlers { + constructor(handler: Dispatcher.DispatchHandlers); +} diff --git a/node_modules/undici-types/header.d.ts b/node_modules/undici-types/header.d.ts new file mode 100644 index 0000000..bfdb329 --- /dev/null +++ b/node_modules/undici-types/header.d.ts @@ -0,0 +1,4 @@ +/** + * The header type declaration of `undici`. + */ +export type IncomingHttpHeaders = Record; diff --git a/node_modules/undici-types/index.d.ts b/node_modules/undici-types/index.d.ts new file mode 100644 index 0000000..f6be35c --- /dev/null +++ b/node_modules/undici-types/index.d.ts @@ -0,0 +1,71 @@ +import Dispatcher from'./dispatcher' +import { setGlobalDispatcher, getGlobalDispatcher } from './global-dispatcher' +import { setGlobalOrigin, getGlobalOrigin } from './global-origin' +import Pool from'./pool' +import { RedirectHandler, DecoratorHandler } from './handlers' + +import BalancedPool from './balanced-pool' +import Client from'./client' +import buildConnector from'./connector' +import errors from'./errors' +import Agent from'./agent' +import MockClient from'./mock-client' +import MockPool from'./mock-pool' +import MockAgent from'./mock-agent' +import mockErrors from'./mock-errors' +import ProxyAgent from'./proxy-agent' +import EnvHttpProxyAgent from './env-http-proxy-agent' +import RetryHandler from'./retry-handler' +import RetryAgent from'./retry-agent' +import { request, pipeline, stream, connect, upgrade } from './api' +import interceptors from './interceptors' + +export * from './util' +export * from './cookies' +export * from './eventsource' +export * from './fetch' +export * from './file' +export * from './filereader' +export * from './formdata' +export * from './diagnostics-channel' +export * from './websocket' +export * from './content-type' +export * from './cache' +export { Interceptable } from './mock-interceptor' + +export { Dispatcher, BalancedPool, Pool, Client, buildConnector, errors, Agent, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, interceptors, MockClient, MockPool, MockAgent, mockErrors, ProxyAgent, EnvHttpProxyAgent, RedirectHandler, DecoratorHandler, RetryHandler, RetryAgent } +export default Undici + +declare namespace Undici { + var Dispatcher: typeof import('./dispatcher').default + var Pool: typeof import('./pool').default; + var RedirectHandler: typeof import ('./handlers').RedirectHandler + var DecoratorHandler: typeof import ('./handlers').DecoratorHandler + var RetryHandler: typeof import ('./retry-handler').default + var createRedirectInterceptor: typeof import ('./interceptors').default.createRedirectInterceptor + var BalancedPool: typeof import('./balanced-pool').default; + var Client: typeof import('./client').default; + var buildConnector: typeof import('./connector').default; + var errors: typeof import('./errors').default; + var Agent: typeof import('./agent').default; + var setGlobalDispatcher: typeof import('./global-dispatcher').setGlobalDispatcher; + var getGlobalDispatcher: typeof import('./global-dispatcher').getGlobalDispatcher; + var request: typeof import('./api').request; + var stream: typeof import('./api').stream; + var pipeline: typeof import('./api').pipeline; + var connect: typeof import('./api').connect; + var upgrade: typeof import('./api').upgrade; + var MockClient: typeof import('./mock-client').default; + var MockPool: typeof import('./mock-pool').default; + var MockAgent: typeof import('./mock-agent').default; + var mockErrors: typeof import('./mock-errors').default; + var fetch: typeof import('./fetch').fetch; + var Headers: typeof import('./fetch').Headers; + var Response: typeof import('./fetch').Response; + var Request: typeof import('./fetch').Request; + var FormData: typeof import('./formdata').FormData; + var File: typeof import('./file').File; + var FileReader: typeof import('./filereader').FileReader; + var caches: typeof import('./cache').caches; + var interceptors: typeof import('./interceptors').default; +} diff --git a/node_modules/undici-types/interceptors.d.ts b/node_modules/undici-types/interceptors.d.ts new file mode 100644 index 0000000..24166b6 --- /dev/null +++ b/node_modules/undici-types/interceptors.d.ts @@ -0,0 +1,17 @@ +import Dispatcher from "./dispatcher"; +import RetryHandler from "./retry-handler"; + +export default Interceptors; + +declare namespace Interceptors { + export type DumpInterceptorOpts = { maxSize?: number } + export type RetryInterceptorOpts = RetryHandler.RetryOptions + export type RedirectInterceptorOpts = { maxRedirections?: number } + export type ResponseErrorInterceptorOpts = { throwOnError: boolean } + + export function createRedirectInterceptor(opts: RedirectInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function dump(opts?: DumpInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function retry(opts?: RetryInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function redirect(opts?: RedirectInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function responseError(opts?: ResponseErrorInterceptorOpts): Dispatcher.DispatcherComposeInterceptor +} diff --git a/node_modules/undici-types/mock-agent.d.ts b/node_modules/undici-types/mock-agent.d.ts new file mode 100644 index 0000000..98cd645 --- /dev/null +++ b/node_modules/undici-types/mock-agent.d.ts @@ -0,0 +1,50 @@ +import Agent from './agent' +import Dispatcher from './dispatcher' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import MockDispatch = MockInterceptor.MockDispatch; + +export default MockAgent + +interface PendingInterceptor extends MockDispatch { + origin: string; +} + +/** A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. */ +declare class MockAgent extends Dispatcher { + constructor(options?: MockAgent.Options) + /** Creates and retrieves mock Dispatcher instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. */ + get(origin: string): TInterceptable; + get(origin: RegExp): TInterceptable; + get(origin: ((origin: string) => boolean)): TInterceptable; + /** Dispatches a mocked request. */ + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock agent and waits for registered mock pools and clients to also close before resolving. */ + close(): Promise; + /** Disables mocking in MockAgent. */ + deactivate(): void; + /** Enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. */ + activate(): void; + /** Define host matchers so only matching requests that aren't intercepted by the mock dispatchers will be attempted. */ + enableNetConnect(): void; + enableNetConnect(host: string): void; + enableNetConnect(host: RegExp): void; + enableNetConnect(host: ((host: string) => boolean)): void; + /** Causes all requests to throw when requests are not matched in a MockAgent intercept. */ + disableNetConnect(): void; + pendingInterceptors(): PendingInterceptor[]; + assertNoPendingInterceptors(options?: { + pendingInterceptorsFormatter?: PendingInterceptorsFormatter; + }): void; +} + +interface PendingInterceptorsFormatter { + format(pendingInterceptors: readonly PendingInterceptor[]): string; +} + +declare namespace MockAgent { + /** MockAgent options. */ + export interface Options extends Agent.Options { + /** A custom agent to be encapsulated by the MockAgent. */ + agent?: Agent; + } +} diff --git a/node_modules/undici-types/mock-client.d.ts b/node_modules/undici-types/mock-client.d.ts new file mode 100644 index 0000000..51d008c --- /dev/null +++ b/node_modules/undici-types/mock-client.d.ts @@ -0,0 +1,25 @@ +import Client from './client' +import Dispatcher from './dispatcher' +import MockAgent from './mock-agent' +import { MockInterceptor, Interceptable } from './mock-interceptor' + +export default MockClient + +/** MockClient extends the Client API and allows one to mock requests. */ +declare class MockClient extends Client implements Interceptable { + constructor(origin: string, options: MockClient.Options); + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept(options: MockInterceptor.Options): MockInterceptor; + /** Dispatches a mocked request. */ + dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock client and gracefully waits for enqueued requests to complete. */ + close(): Promise; +} + +declare namespace MockClient { + /** MockClient options. */ + export interface Options extends Client.Options { + /** The agent to associate this MockClient with. */ + agent: MockAgent; + } +} diff --git a/node_modules/undici-types/mock-errors.d.ts b/node_modules/undici-types/mock-errors.d.ts new file mode 100644 index 0000000..3d9e727 --- /dev/null +++ b/node_modules/undici-types/mock-errors.d.ts @@ -0,0 +1,12 @@ +import Errors from './errors' + +export default MockErrors + +declare namespace MockErrors { + /** The request does not match any registered mock dispatches. */ + export class MockNotMatchedError extends Errors.UndiciError { + constructor(message?: string); + name: 'MockNotMatchedError'; + code: 'UND_MOCK_ERR_MOCK_NOT_MATCHED'; + } +} diff --git a/node_modules/undici-types/mock-interceptor.d.ts b/node_modules/undici-types/mock-interceptor.d.ts new file mode 100644 index 0000000..33f3f14 --- /dev/null +++ b/node_modules/undici-types/mock-interceptor.d.ts @@ -0,0 +1,93 @@ +import { IncomingHttpHeaders } from './header' +import Dispatcher from './dispatcher'; +import { BodyInit, Headers } from './fetch' + +export { + Interceptable, + MockInterceptor, + MockScope +} + +/** The scope associated with a mock dispatch. */ +declare class MockScope { + constructor(mockDispatch: MockInterceptor.MockDispatch); + /** Delay a reply by a set amount of time in ms. */ + delay(waitInMs: number): MockScope; + /** Persist the defined mock data for the associated reply. It will return the defined mock data indefinitely. */ + persist(): MockScope; + /** Define a reply for a set amount of matching requests. */ + times(repeatTimes: number): MockScope; +} + +/** The interceptor for a Mock. */ +declare class MockInterceptor { + constructor(options: MockInterceptor.Options, mockDispatches: MockInterceptor.MockDispatch[]); + /** Mock an undici request with the defined reply. */ + reply(replyOptionsCallback: MockInterceptor.MockReplyOptionsCallback): MockScope; + reply( + statusCode: number, + data?: TData | Buffer | string | MockInterceptor.MockResponseDataHandler, + responseOptions?: MockInterceptor.MockResponseOptions + ): MockScope; + /** Mock an undici request by throwing the defined reply error. */ + replyWithError(error: TError): MockScope; + /** Set default reply headers on the interceptor for subsequent mocked replies. */ + defaultReplyHeaders(headers: IncomingHttpHeaders): MockInterceptor; + /** Set default reply trailers on the interceptor for subsequent mocked replies. */ + defaultReplyTrailers(trailers: Record): MockInterceptor; + /** Set automatically calculated content-length header on subsequent mocked replies. */ + replyContentLength(): MockInterceptor; +} + +declare namespace MockInterceptor { + /** MockInterceptor options. */ + export interface Options { + /** Path to intercept on. */ + path: string | RegExp | ((path: string) => boolean); + /** Method to intercept on. Defaults to GET. */ + method?: string | RegExp | ((method: string) => boolean); + /** Body to intercept on. */ + body?: string | RegExp | ((body: string) => boolean); + /** Headers to intercept on. */ + headers?: Record boolean)> | ((headers: Record) => boolean); + /** Query params to intercept on */ + query?: Record; + } + export interface MockDispatch extends Options { + times: number | null; + persist: boolean; + consumed: boolean; + data: MockDispatchData; + } + export interface MockDispatchData extends MockResponseOptions { + error: TError | null; + statusCode?: number; + data?: TData | string; + } + export interface MockResponseOptions { + headers?: IncomingHttpHeaders; + trailers?: Record; + } + + export interface MockResponseCallbackOptions { + path: string; + method: string; + headers?: Headers | Record; + origin?: string; + body?: BodyInit | Dispatcher.DispatchOptions['body'] | null; + maxRedirections?: number; + } + + export type MockResponseDataHandler = ( + opts: MockResponseCallbackOptions + ) => TData | Buffer | string; + + export type MockReplyOptionsCallback = ( + opts: MockResponseCallbackOptions + ) => { statusCode: number, data?: TData | Buffer | string, responseOptions?: MockResponseOptions } +} + +interface Interceptable extends Dispatcher { + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept(options: MockInterceptor.Options): MockInterceptor; +} diff --git a/node_modules/undici-types/mock-pool.d.ts b/node_modules/undici-types/mock-pool.d.ts new file mode 100644 index 0000000..39e709a --- /dev/null +++ b/node_modules/undici-types/mock-pool.d.ts @@ -0,0 +1,25 @@ +import Pool from './pool' +import MockAgent from './mock-agent' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import Dispatcher from './dispatcher' + +export default MockPool + +/** MockPool extends the Pool API and allows one to mock requests. */ +declare class MockPool extends Pool implements Interceptable { + constructor(origin: string, options: MockPool.Options); + /** Intercepts any matching requests that use the same origin as this mock pool. */ + intercept(options: MockInterceptor.Options): MockInterceptor; + /** Dispatches a mocked request. */ + dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock pool and gracefully waits for enqueued requests to complete. */ + close(): Promise; +} + +declare namespace MockPool { + /** MockPool options. */ + export interface Options extends Pool.Options { + /** The agent to associate this MockPool with. */ + agent: MockAgent; + } +} diff --git a/node_modules/undici-types/package.json b/node_modules/undici-types/package.json new file mode 100644 index 0000000..d2f33bc --- /dev/null +++ b/node_modules/undici-types/package.json @@ -0,0 +1,55 @@ +{ + "name": "undici-types", + "version": "6.21.0", + "description": "A stand-alone types package for Undici", + "homepage": "https://undici.nodejs.org", + "bugs": { + "url": "https://github.com/nodejs/undici/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/nodejs/undici.git" + }, + "license": "MIT", + "types": "index.d.ts", + "files": [ + "*.d.ts" + ], + "contributors": [ + { + "name": "Daniele Belardi", + "url": "https://github.com/dnlup", + "author": true + }, + { + "name": "Ethan Arrowood", + "url": "https://github.com/ethan-arrowood", + "author": true + }, + { + "name": "Matteo Collina", + "url": "https://github.com/mcollina", + "author": true + }, + { + "name": "Matthew Aitken", + "url": "https://github.com/KhafraDev", + "author": true + }, + { + "name": "Robert Nagy", + "url": "https://github.com/ronag", + "author": true + }, + { + "name": "Szymon Marczak", + "url": "https://github.com/szmarczak", + "author": true + }, + { + "name": "Tomas Della Vedova", + "url": "https://github.com/delvedor", + "author": true + } + ] +} \ No newline at end of file diff --git a/node_modules/undici-types/patch.d.ts b/node_modules/undici-types/patch.d.ts new file mode 100644 index 0000000..4ac3845 --- /dev/null +++ b/node_modules/undici-types/patch.d.ts @@ -0,0 +1,33 @@ +/// + +// See https://github.com/nodejs/undici/issues/1740 + +export type DOMException = typeof globalThis extends { DOMException: infer T } + ? T + : any + +export interface EventInit { + bubbles?: boolean + cancelable?: boolean + composed?: boolean +} + +export interface EventListenerOptions { + capture?: boolean +} + +export interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean + passive?: boolean + signal?: AbortSignal +} + +export type EventListenerOrEventListenerObject = EventListener | EventListenerObject + +export interface EventListenerObject { + handleEvent (object: Event): void +} + +export interface EventListener { + (evt: Event): void +} diff --git a/node_modules/undici-types/pool-stats.d.ts b/node_modules/undici-types/pool-stats.d.ts new file mode 100644 index 0000000..8b6d2bf --- /dev/null +++ b/node_modules/undici-types/pool-stats.d.ts @@ -0,0 +1,19 @@ +import Pool from "./pool" + +export default PoolStats + +declare class PoolStats { + constructor(pool: Pool); + /** Number of open socket connections in this pool. */ + connected: number; + /** Number of open socket connections in this pool that do not have an active request. */ + free: number; + /** Number of pending requests across all clients in this pool. */ + pending: number; + /** Number of queued requests across all clients in this pool. */ + queued: number; + /** Number of currently active requests across all clients in this pool. */ + running: number; + /** Number of active, pending, or queued requests across all clients in this pool. */ + size: number; +} diff --git a/node_modules/undici-types/pool.d.ts b/node_modules/undici-types/pool.d.ts new file mode 100644 index 0000000..bad5ba0 --- /dev/null +++ b/node_modules/undici-types/pool.d.ts @@ -0,0 +1,39 @@ +import Client from './client' +import TPoolStats from './pool-stats' +import { URL } from 'url' +import Dispatcher from "./dispatcher"; + +export default Pool + +type PoolConnectOptions = Omit; + +declare class Pool extends Dispatcher { + constructor(url: string | URL, options?: Pool.Options) + /** `true` after `pool.close()` has been called. */ + closed: boolean; + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean; + /** Aggregate stats for a Pool. */ + readonly stats: TPoolStats; + + // Override dispatcher APIs. + override connect( + options: PoolConnectOptions + ): Promise; + override connect( + options: PoolConnectOptions, + callback: (err: Error | null, data: Dispatcher.ConnectData) => void + ): void; +} + +declare namespace Pool { + export type PoolStats = TPoolStats; + export interface Options extends Client.Options { + /** Default: `(origin, opts) => new Client(origin, opts)`. */ + factory?(origin: URL, opts: object): Dispatcher; + /** The max number of clients to create. `null` if no limit. Default `null`. */ + connections?: number | null; + + interceptors?: { Pool?: readonly Dispatcher.DispatchInterceptor[] } & Client.Options["interceptors"] + } +} diff --git a/node_modules/undici-types/proxy-agent.d.ts b/node_modules/undici-types/proxy-agent.d.ts new file mode 100644 index 0000000..32e3acb --- /dev/null +++ b/node_modules/undici-types/proxy-agent.d.ts @@ -0,0 +1,28 @@ +import Agent from './agent' +import buildConnector from './connector'; +import Dispatcher from './dispatcher' +import { IncomingHttpHeaders } from './header' + +export default ProxyAgent + +declare class ProxyAgent extends Dispatcher { + constructor(options: ProxyAgent.Options | string) + + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + close(): Promise; +} + +declare namespace ProxyAgent { + export interface Options extends Agent.Options { + uri: string; + /** + * @deprecated use opts.token + */ + auth?: string; + token?: string; + headers?: IncomingHttpHeaders; + requestTls?: buildConnector.BuildOptions; + proxyTls?: buildConnector.BuildOptions; + clientFactory?(origin: URL, opts: object): Dispatcher; + } +} diff --git a/node_modules/undici-types/readable.d.ts b/node_modules/undici-types/readable.d.ts new file mode 100644 index 0000000..c4f052a --- /dev/null +++ b/node_modules/undici-types/readable.d.ts @@ -0,0 +1,65 @@ +import { Readable } from "stream"; +import { Blob } from 'buffer' + +export default BodyReadable + +declare class BodyReadable extends Readable { + constructor( + resume?: (this: Readable, size: number) => void | null, + abort?: () => void | null, + contentType?: string + ) + + /** Consumes and returns the body as a string + * https://fetch.spec.whatwg.org/#dom-body-text + */ + text(): Promise + + /** Consumes and returns the body as a JavaScript Object + * https://fetch.spec.whatwg.org/#dom-body-json + */ + json(): Promise + + /** Consumes and returns the body as a Blob + * https://fetch.spec.whatwg.org/#dom-body-blob + */ + blob(): Promise + + /** Consumes and returns the body as an Uint8Array + * https://fetch.spec.whatwg.org/#dom-body-bytes + */ + bytes(): Promise + + /** Consumes and returns the body as an ArrayBuffer + * https://fetch.spec.whatwg.org/#dom-body-arraybuffer + */ + arrayBuffer(): Promise + + /** Not implemented + * + * https://fetch.spec.whatwg.org/#dom-body-formdata + */ + formData(): Promise + + /** Returns true if the body is not null and the body has been consumed + * + * Otherwise, returns false + * + * https://fetch.spec.whatwg.org/#dom-body-bodyused + */ + readonly bodyUsed: boolean + + /** + * If body is null, it should return null as the body + * + * If body is not null, should return the body as a ReadableStream + * + * https://fetch.spec.whatwg.org/#dom-body-body + */ + readonly body: never | undefined + + /** Dumps the response body by reading `limit` number of bytes. + * @param opts.limit Number of bytes to read (optional) - Default: 262144 + */ + dump(opts?: { limit: number }): Promise +} diff --git a/node_modules/undici-types/retry-agent.d.ts b/node_modules/undici-types/retry-agent.d.ts new file mode 100644 index 0000000..963cea9 --- /dev/null +++ b/node_modules/undici-types/retry-agent.d.ts @@ -0,0 +1,8 @@ +import Dispatcher from './dispatcher' +import RetryHandler from './retry-handler' + +export default RetryAgent + +declare class RetryAgent extends Dispatcher { + constructor(dispatcher: Dispatcher, options?: RetryHandler.RetryOptions) +} diff --git a/node_modules/undici-types/retry-handler.d.ts b/node_modules/undici-types/retry-handler.d.ts new file mode 100644 index 0000000..e44b207 --- /dev/null +++ b/node_modules/undici-types/retry-handler.d.ts @@ -0,0 +1,116 @@ +import Dispatcher from "./dispatcher"; + +export default RetryHandler; + +declare class RetryHandler implements Dispatcher.DispatchHandlers { + constructor( + options: Dispatcher.DispatchOptions & { + retryOptions?: RetryHandler.RetryOptions; + }, + retryHandlers: RetryHandler.RetryHandlers + ); +} + +declare namespace RetryHandler { + export type RetryState = { counter: number; }; + + export type RetryContext = { + state: RetryState; + opts: Dispatcher.DispatchOptions & { + retryOptions?: RetryHandler.RetryOptions; + }; + } + + export type OnRetryCallback = (result?: Error | null) => void; + + export type RetryCallback = ( + err: Error, + context: { + state: RetryState; + opts: Dispatcher.DispatchOptions & { + retryOptions?: RetryHandler.RetryOptions; + }; + }, + callback: OnRetryCallback + ) => number | null; + + export interface RetryOptions { + /** + * Callback to be invoked on every retry iteration. + * It receives the error, current state of the retry object and the options object + * passed when instantiating the retry handler. + * + * @type {RetryCallback} + * @memberof RetryOptions + */ + retry?: RetryCallback; + /** + * Maximum number of retries to allow. + * + * @type {number} + * @memberof RetryOptions + * @default 5 + */ + maxRetries?: number; + /** + * Max number of milliseconds allow between retries + * + * @type {number} + * @memberof RetryOptions + * @default 30000 + */ + maxTimeout?: number; + /** + * Initial number of milliseconds to wait before retrying for the first time. + * + * @type {number} + * @memberof RetryOptions + * @default 500 + */ + minTimeout?: number; + /** + * Factior to multiply the timeout factor between retries. + * + * @type {number} + * @memberof RetryOptions + * @default 2 + */ + timeoutFactor?: number; + /** + * It enables to automatically infer timeout between retries based on the `Retry-After` header. + * + * @type {boolean} + * @memberof RetryOptions + * @default true + */ + retryAfter?: boolean; + /** + * HTTP methods to retry. + * + * @type {Dispatcher.HttpMethod[]} + * @memberof RetryOptions + * @default ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], + */ + methods?: Dispatcher.HttpMethod[]; + /** + * Error codes to be retried. e.g. `ECONNRESET`, `ENOTFOUND`, `ETIMEDOUT`, `ECONNREFUSED`, etc. + * + * @type {string[]} + * @default ['ECONNRESET','ECONNREFUSED','ENOTFOUND','ENETDOWN','ENETUNREACH','EHOSTDOWN','EHOSTUNREACH','EPIPE'] + */ + errorCodes?: string[]; + /** + * HTTP status codes to be retried. + * + * @type {number[]} + * @memberof RetryOptions + * @default [500, 502, 503, 504, 429], + */ + statusCodes?: number[]; + } + + export interface RetryHandlers { + dispatch: Dispatcher["dispatch"]; + handler: Dispatcher.DispatchHandlers; + } +} diff --git a/node_modules/undici-types/util.d.ts b/node_modules/undici-types/util.d.ts new file mode 100644 index 0000000..77cf147 --- /dev/null +++ b/node_modules/undici-types/util.d.ts @@ -0,0 +1,18 @@ +export namespace util { + /** + * Retrieves a header name and returns its lowercase value. + * @param value Header name + */ + export function headerNameToString(value: string | Buffer): string; + + /** + * Receives a header object and returns the parsed value. + * @param headers Header object + * @param obj Object to specify a proxy object. Used to assign parsed values. + * @returns If `obj` is specified, it is equivalent to `obj`. + */ + export function parseHeaders( + headers: (Buffer | string | (Buffer | string)[])[], + obj?: Record + ): Record; +} diff --git a/node_modules/undici-types/webidl.d.ts b/node_modules/undici-types/webidl.d.ts new file mode 100644 index 0000000..fd83b68 --- /dev/null +++ b/node_modules/undici-types/webidl.d.ts @@ -0,0 +1,228 @@ +// These types are not exported, and are only used internally + +/** + * Take in an unknown value and return one that is of type T + */ +type Converter = (object: unknown) => T + +type SequenceConverter = (object: unknown, iterable?: IterableIterator) => T[] + +type RecordConverter = (object: unknown) => Record + +interface ConvertToIntOpts { + clamp?: boolean + enforceRange?: boolean +} + +interface WebidlErrors { + exception (opts: { header: string, message: string }): TypeError + /** + * @description Throw an error when conversion from one type to another has failed + */ + conversionFailed (opts: { + prefix: string + argument: string + types: string[] + }): TypeError + /** + * @description Throw an error when an invalid argument is provided + */ + invalidArgument (opts: { + prefix: string + value: string + type: string + }): TypeError +} + +interface WebidlUtil { + /** + * @see https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values + */ + Type (object: unknown): + | 'Undefined' + | 'Boolean' + | 'String' + | 'Symbol' + | 'Number' + | 'BigInt' + | 'Null' + | 'Object' + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + */ + ConvertToInt ( + V: unknown, + bitLength: number, + signedness: 'signed' | 'unsigned', + opts?: ConvertToIntOpts + ): number + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + */ + IntegerPart (N: number): number + + /** + * Stringifies {@param V} + */ + Stringify (V: any): string + + /** + * Mark a value as uncloneable for Node.js. + * This is only effective in some newer Node.js versions. + */ + markAsUncloneable (V: any): void +} + +interface WebidlConverters { + /** + * @see https://webidl.spec.whatwg.org/#es-DOMString + */ + DOMString (V: unknown, prefix: string, argument: string, opts?: { + legacyNullToEmptyString: boolean + }): string + + /** + * @see https://webidl.spec.whatwg.org/#es-ByteString + */ + ByteString (V: unknown, prefix: string, argument: string): string + + /** + * @see https://webidl.spec.whatwg.org/#es-USVString + */ + USVString (V: unknown): string + + /** + * @see https://webidl.spec.whatwg.org/#es-boolean + */ + boolean (V: unknown): boolean + + /** + * @see https://webidl.spec.whatwg.org/#es-any + */ + any (V: Value): Value + + /** + * @see https://webidl.spec.whatwg.org/#es-long-long + */ + ['long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long-long + */ + ['unsigned long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long + */ + ['unsigned long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-short + */ + ['unsigned short'] (V: unknown, opts?: ConvertToIntOpts): number + + /** + * @see https://webidl.spec.whatwg.org/#idl-ArrayBuffer + */ + ArrayBuffer (V: unknown): ArrayBufferLike + ArrayBuffer (V: unknown, opts: { allowShared: false }): ArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + TypedArray ( + V: unknown, + TypedArray: NodeJS.TypedArray | ArrayBufferLike + ): NodeJS.TypedArray | ArrayBufferLike + TypedArray ( + V: unknown, + TypedArray: NodeJS.TypedArray | ArrayBufferLike, + opts?: { allowShared: false } + ): NodeJS.TypedArray | ArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + DataView (V: unknown, opts?: { allowShared: boolean }): DataView + + /** + * @see https://webidl.spec.whatwg.org/#BufferSource + */ + BufferSource ( + V: unknown, + opts?: { allowShared: boolean } + ): NodeJS.TypedArray | ArrayBufferLike | DataView + + ['sequence']: SequenceConverter + + ['sequence>']: SequenceConverter + + ['record']: RecordConverter + + [Key: string]: (...args: any[]) => unknown +} + +export interface Webidl { + errors: WebidlErrors + util: WebidlUtil + converters: WebidlConverters + + /** + * @description Performs a brand-check on {@param V} to ensure it is a + * {@param cls} object. + */ + brandCheck (V: unknown, cls: Interface, opts?: { strict?: boolean }): asserts V is Interface + + /** + * @see https://webidl.spec.whatwg.org/#es-sequence + * @description Convert a value, V, to a WebIDL sequence type. + */ + sequenceConverter (C: Converter): SequenceConverter + + illegalConstructor (): never + + /** + * @see https://webidl.spec.whatwg.org/#es-to-record + * @description Convert a value, V, to a WebIDL record type. + */ + recordConverter ( + keyConverter: Converter, + valueConverter: Converter + ): RecordConverter + + /** + * Similar to {@link Webidl.brandCheck} but allows skipping the check if third party + * interfaces are allowed. + */ + interfaceConverter (cls: Interface): ( + V: unknown, + opts?: { strict: boolean } + ) => asserts V is typeof cls + + // TODO(@KhafraDev): a type could likely be implemented that can infer the return type + // from the converters given? + /** + * Converts a value, V, to a WebIDL dictionary types. Allows limiting which keys are + * allowed, values allowed, optional and required keys. Auto converts the value to + * a type given a converter. + */ + dictionaryConverter (converters: { + key: string, + defaultValue?: () => unknown, + required?: boolean, + converter: (...args: unknown[]) => unknown, + allowedValues?: unknown[] + }[]): (V: unknown) => Record + + /** + * @see https://webidl.spec.whatwg.org/#idl-nullable-type + * @description allows a type, V, to be null + */ + nullableConverter ( + converter: Converter + ): (V: unknown) => ReturnType | null + + argumentLengthCheck (args: { length: number }, min: number, context: string): void +} diff --git a/node_modules/undici-types/websocket.d.ts b/node_modules/undici-types/websocket.d.ts new file mode 100644 index 0000000..dfdd815 --- /dev/null +++ b/node_modules/undici-types/websocket.d.ts @@ -0,0 +1,150 @@ +/// + +import type { Blob } from 'buffer' +import type { MessagePort } from 'worker_threads' +import { + EventInit, + EventListenerOptions, + AddEventListenerOptions, + EventListenerOrEventListenerObject +} from './patch' +import Dispatcher from './dispatcher' +import { HeadersInit } from './fetch' + +export type BinaryType = 'blob' | 'arraybuffer' + +interface WebSocketEventMap { + close: CloseEvent + error: ErrorEvent + message: MessageEvent + open: Event +} + +interface WebSocket extends EventTarget { + binaryType: BinaryType + + readonly bufferedAmount: number + readonly extensions: string + + onclose: ((this: WebSocket, ev: WebSocketEventMap['close']) => any) | null + onerror: ((this: WebSocket, ev: WebSocketEventMap['error']) => any) | null + onmessage: ((this: WebSocket, ev: WebSocketEventMap['message']) => any) | null + onopen: ((this: WebSocket, ev: WebSocketEventMap['open']) => any) | null + + readonly protocol: string + readonly readyState: number + readonly url: string + + close(code?: number, reason?: string): void + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void + + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number + + addEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | AddEventListenerOptions + ): void + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void + removeEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | EventListenerOptions + ): void + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions + ): void +} + +export declare const WebSocket: { + prototype: WebSocket + new (url: string | URL, protocols?: string | string[] | WebSocketInit): WebSocket + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number +} + +interface CloseEventInit extends EventInit { + code?: number + reason?: string + wasClean?: boolean +} + +interface CloseEvent extends Event { + readonly code: number + readonly reason: string + readonly wasClean: boolean +} + +export declare const CloseEvent: { + prototype: CloseEvent + new (type: string, eventInitDict?: CloseEventInit): CloseEvent +} + +interface MessageEventInit extends EventInit { + data?: T + lastEventId?: string + origin?: string + ports?: (typeof MessagePort)[] + source?: typeof MessagePort | null +} + +interface MessageEvent extends Event { + readonly data: T + readonly lastEventId: string + readonly origin: string + readonly ports: ReadonlyArray + readonly source: typeof MessagePort | null + initMessageEvent( + type: string, + bubbles?: boolean, + cancelable?: boolean, + data?: any, + origin?: string, + lastEventId?: string, + source?: typeof MessagePort | null, + ports?: (typeof MessagePort)[] + ): void; +} + +export declare const MessageEvent: { + prototype: MessageEvent + new(type: string, eventInitDict?: MessageEventInit): MessageEvent +} + +interface ErrorEventInit extends EventInit { + message?: string + filename?: string + lineno?: number + colno?: number + error?: any +} + +interface ErrorEvent extends Event { + readonly message: string + readonly filename: string + readonly lineno: number + readonly colno: number + readonly error: any +} + +export declare const ErrorEvent: { + prototype: ErrorEvent + new (type: string, eventInitDict?: ErrorEventInit): ErrorEvent +} + +interface WebSocketInit { + protocols?: string | string[], + dispatcher?: Dispatcher, + headers?: HeadersInit +} diff --git a/node_modules/util-deprecate/History.md b/node_modules/util-deprecate/History.md new file mode 100644 index 0000000..acc8675 --- /dev/null +++ b/node_modules/util-deprecate/History.md @@ -0,0 +1,16 @@ + +1.0.2 / 2015-10-07 +================== + + * use try/catch when checking `localStorage` (#3, @kumavis) + +1.0.1 / 2014-11-25 +================== + + * browser: use `console.warn()` for deprecation calls + * browser: more jsdocs + +1.0.0 / 2014-04-30 +================== + + * initial commit diff --git a/node_modules/util-deprecate/LICENSE b/node_modules/util-deprecate/LICENSE new file mode 100644 index 0000000..6a60e8c --- /dev/null +++ b/node_modules/util-deprecate/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/util-deprecate/README.md b/node_modules/util-deprecate/README.md new file mode 100644 index 0000000..75622fa --- /dev/null +++ b/node_modules/util-deprecate/README.md @@ -0,0 +1,53 @@ +util-deprecate +============== +### The Node.js `util.deprecate()` function with browser support + +In Node.js, this module simply re-exports the `util.deprecate()` function. + +In the web browser (i.e. via browserify), a browser-specific implementation +of the `util.deprecate()` function is used. + + +## API + +A `deprecate()` function is the only thing exposed by this module. + +``` javascript +// setup: +exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead'); + + +// users see: +foo(); +// foo() is deprecated, use bar() instead +foo(); +foo(); +``` + + +## License + +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/util-deprecate/browser.js b/node_modules/util-deprecate/browser.js new file mode 100644 index 0000000..549ae2f --- /dev/null +++ b/node_modules/util-deprecate/browser.js @@ -0,0 +1,67 @@ + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} diff --git a/node_modules/util-deprecate/node.js b/node_modules/util-deprecate/node.js new file mode 100644 index 0000000..5e6fcff --- /dev/null +++ b/node_modules/util-deprecate/node.js @@ -0,0 +1,6 @@ + +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + +module.exports = require('util').deprecate; diff --git a/node_modules/util-deprecate/package.json b/node_modules/util-deprecate/package.json new file mode 100644 index 0000000..2e79f89 --- /dev/null +++ b/node_modules/util-deprecate/package.json @@ -0,0 +1,27 @@ +{ + "name": "util-deprecate", + "version": "1.0.2", + "description": "The Node.js `util.deprecate()` function with browser support", + "main": "node.js", + "browser": "browser.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/util-deprecate.git" + }, + "keywords": [ + "util", + "deprecate", + "browserify", + "browser", + "node" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/util-deprecate/issues" + }, + "homepage": "https://github.com/TooTallNate/util-deprecate" +} diff --git a/node_modules/uuid/LICENSE.md b/node_modules/uuid/LICENSE.md new file mode 100644 index 0000000..3934168 --- /dev/null +++ b/node_modules/uuid/LICENSE.md @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2010-2020 Robert Kieffer and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/uuid/README.md b/node_modules/uuid/README.md new file mode 100644 index 0000000..83ae737 --- /dev/null +++ b/node_modules/uuid/README.md @@ -0,0 +1,510 @@ + + +# uuid [![CI](https://github.com/uuidjs/uuid/workflows/CI/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ACI) [![Browser](https://github.com/uuidjs/uuid/workflows/Browser/badge.svg)](https://github.com/uuidjs/uuid/actions/workflows/browser.yml) + +For the creation of [RFC9562](https://www.rfc-editor.org/rfc/rfc9562.html) (formerly [RFC4122](https://www.rfc-editor.org/rfc/rfc4122.html)) UUIDs + +- **Complete** - Support for all RFC9562 UUID versions +- **Cross-platform** - Support for... + - ESM & Common JS + - [Typescript](#support) + - [Chrome, Safari, Firefox, and Edge](#support) + - [NodeJS](#support) + - [React Native / Expo](#react-native--expo) +- **Secure** - Uses modern `crypto` API for random values +- **Compact** - Zero-dependency, [tree-shakable](https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking) +- **CLI** - [`uuid` command line](#command-line) utility + + +> [!NOTE] +> `uuid@11` is now available: See the [CHANGELOG](./CHANGELOG.md) for details. TL;DR: +> * TypeScript support is now included (remove `@types/uuid` from your dependencies) +> * Subtle changes to how the `options` arg is interpreted for `v1()`, `v6()`, and `v7()`. [See details](#options-handling-for-timestamp-uuids) +> * Binary UUIDs are now `Uint8Array`s. (May impact callers of `parse()`, `stringify()`, or that pass an `option#buf` argument to `v1()`-`v7()`.) + +## Quickstart + +**1. Install** + +```shell +npm install uuid +``` + +**2. Create a UUID** + +ESM-syntax (must use named exports): + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' +``` + +... CommonJS: + +```javascript +const { v4: uuidv4 } = require('uuid'); +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +For timestamp UUIDs, namespace UUIDs, and other options read on ... + +## API Summary + +| | | | +| --- | --- | --- | +| [`uuid.NIL`](#uuidnil) | The nil UUID string (all zeros) | New in `uuid@8.3` | +| [`uuid.MAX`](#uuidmax) | The max UUID string (all ones) | New in `uuid@9.1` | +| [`uuid.parse()`](#uuidparsestr) | Convert UUID string to array of bytes | New in `uuid@8.3` | +| [`uuid.stringify()`](#uuidstringifyarr-offset) | Convert array of bytes to UUID string | New in `uuid@8.3` | +| [`uuid.v1()`](#uuidv1options-buffer-offset) | Create a version 1 (timestamp) UUID | | +| [`uuid.v1ToV6()`](#uuidv1tov6uuid) | Create a version 6 UUID from a version 1 UUID | New in `uuid@10` | +| [`uuid.v3()`](#uuidv3name-namespace-buffer-offset) | Create a version 3 (namespace w/ MD5) UUID | | +| [`uuid.v4()`](#uuidv4options-buffer-offset) | Create a version 4 (random) UUID | | +| [`uuid.v5()`](#uuidv5name-namespace-buffer-offset) | Create a version 5 (namespace w/ SHA-1) UUID | | +| [`uuid.v6()`](#uuidv6options-buffer-offset) | Create a version 6 (timestamp, reordered) UUID | New in `uuid@10` | +| [`uuid.v6ToV1()`](#uuidv6tov1uuid) | Create a version 1 UUID from a version 6 UUID | New in `uuid@10` | +| [`uuid.v7()`](#uuidv7options-buffer-offset) | Create a version 7 (Unix Epoch time-based) UUID | New in `uuid@10` | +| ~~[`uuid.v8()`](#uuidv8)~~ | "Intentionally left blank" | | +| [`uuid.validate()`](#uuidvalidatestr) | Test a string to see if it is a valid UUID | New in `uuid@8.3` | +| [`uuid.version()`](#uuidversionstr) | Detect RFC version of a UUID | New in `uuid@8.3` | + +## API + +### uuid.NIL + +The nil UUID string (all zeros). + +Example: + +```javascript +import { NIL as NIL_UUID } from 'uuid'; + +NIL_UUID; // ⇨ '00000000-0000-0000-0000-000000000000' +``` + +### uuid.MAX + +The max UUID string (all ones). + +Example: + +```javascript +import { MAX as MAX_UUID } from 'uuid'; + +MAX_UUID; // ⇨ 'ffffffff-ffff-ffff-ffff-ffffffffffff' +``` + +### uuid.parse(str) + +Convert UUID string to array of bytes + +| | | +| --------- | ---------------------------------------- | +| `str` | A valid UUID `String` | +| _returns_ | `Uint8Array[16]` | +| _throws_ | `TypeError` if `str` is not a valid UUID | + + +> [!NOTE] +> Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left ↠ right order of hex-pairs in UUID strings. As shown in the example below. + +Example: + +```javascript +import { parse as uuidParse } from 'uuid'; + +// Parse a UUID +uuidParse('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ +// Uint8Array(16) [ +// 110, 192, 189, 127, 17, +// 192, 67, 218, 151, 94, +// 42, 138, 217, 235, 174, +// 11 +// ] +``` + +### uuid.stringify(arr[, offset]) + +Convert array of bytes to UUID string + +| | | +| -------------- | ---------------------------------------------------------------------------- | +| `arr` | `Array`-like collection of 16 values (starting from `offset`) between 0-255. | +| [`offset` = 0] | `Number` Starting index in the Array | +| _returns_ | `String` | +| _throws_ | `TypeError` if a valid UUID string cannot be generated | + + +> [!NOTE] +> Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left ↠ right order of hex-pairs in UUID strings. As shown in the example below. + +Example: + +```javascript +import { stringify as uuidStringify } from 'uuid'; + +const uuidBytes = Uint8Array.of( + 0x6e, + 0xc0, + 0xbd, + 0x7f, + 0x11, + 0xc0, + 0x43, + 0xda, + 0x97, + 0x5e, + 0x2a, + 0x8a, + 0xd9, + 0xeb, + 0xae, + 0x0b +); + +uuidStringify(uuidBytes); // ⇨ '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b' +``` + +### uuid.v1([options[, buffer[, offset]]]) + +Create an RFC version 1 (timestamp) UUID + +| | | +| --- | --- | +| [`options`] | `Object` with one or more of the following properties: | +| [`options.node = (random)` ] | RFC "node" field as an `Array[6]` of byte values (per 4.1.6) | +| [`options.clockseq = (random)`] | RFC "clock sequence" as a `Number` between 0 - 0x3fff | +| [`options.msecs = (current time)`] | RFC "timestamp" field (`Number` of milliseconds, unix epoch) | +| [`options.nsecs = 0`] | RFC "timestamp" field (`Number` of nanoseconds to add to `msecs`, should be 0-10,000) | +| [`options.random = (random)`] | `Array` of 16 random bytes (0-255) used to generate other fields, above | +| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | +| [`buffer`] | `Uint8Array` or `Uint8Array` subtype (e.g. Node.js `Buffer`). If provided, binary UUID is written into the array, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | +| _throws_ | `Error` if more than 10M UUIDs/sec are requested | + + +> [!NOTE] +> The default [node id](https://datatracker.ietf.org/doc/html/rfc9562#section-5.1) (the last 12 digits in the UUID) is generated once, randomly, on process startup, and then remains unchanged for the duration of the process. + + +> [!NOTE] +> `options.random` and `options.rng` are only meaningful on the very first call to `v1()`, where they may be passed to initialize the internal `node` and `clockseq` fields. + +Example: + +```javascript +import { v1 as uuidv1 } from 'uuid'; + +uuidv1(); // ⇨ '2c5ea4c0-4067-11e9-9bdd-2b0d7b3dcb6d' +``` + +Example using `options`: + +```javascript +import { v1 as uuidv1 } from 'uuid'; + +const options = { + node: Uint8Array.of(0x01, 0x23, 0x45, 0x67, 0x89, 0xab), + clockseq: 0x1234, + msecs: new Date('2011-11-01').getTime(), + nsecs: 5678, +}; +uuidv1(options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab' +``` + +### uuid.v1ToV6(uuid) + +Convert a UUID from version 1 to version 6 + +```javascript +import { v1ToV6 } from 'uuid'; + +v1ToV6('92f62d9e-22c4-11ef-97e9-325096b39f47'); // ⇨ '1ef22c49-2f62-6d9e-97e9-325096b39f47' +``` + +### uuid.v3(name, namespace[, buffer[, offset]]) + +Create an RFC version 3 (namespace w/ MD5) UUID + +API is identical to `v5()`, but uses "v3" instead. + + +> [!IMPORTANT] +> Per the RFC, "_If backward compatibility is not an issue, SHA-1 [Version 5] is preferred_." + +### uuid.v4([options[, buffer[, offset]]]) + +Create an RFC version 4 (random) UUID + +| | | +| --- | --- | +| [`options`] | `Object` with one or more of the following properties: | +| [`options.random`] | `Array` of 16 random bytes (0-255) | +| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | +| [`buffer`] | `Uint8Array` or `Uint8Array` subtype (e.g. Node.js `Buffer`). If provided, binary UUID is written into the array, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | + +Example: + +```javascript +import { v4 as uuidv4 } from 'uuid'; + +uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' +``` + +Example using predefined `random` values: + +```javascript +import { v4 as uuidv4 } from 'uuid'; + +const v4options = { + random: Uint8Array.of( + 0x10, + 0x91, + 0x56, + 0xbe, + 0xc4, + 0xfb, + 0xc1, + 0xea, + 0x71, + 0xb4, + 0xef, + 0xe1, + 0x67, + 0x1c, + 0x58, + 0x36 + ), +}; +uuidv4(v4options); // ⇨ '109156be-c4fb-41ea-b1b4-efe1671c5836' +``` + +### uuid.v5(name, namespace[, buffer[, offset]]) + +Create an RFC version 5 (namespace w/ SHA-1) UUID + +| | | +| --- | --- | +| `name` | `String \| Array` | +| `namespace` | `String \| Array[16]` Namespace UUID | +| [`buffer`] | `Uint8Array` or `Uint8Array` subtype (e.g. Node.js `Buffer`). If provided, binary UUID is written into the array, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | + + +> [!NOTE] +> The RFC `DNS` and `URL` namespaces are available as `v5.DNS` and `v5.URL`. + +Example with custom namespace: + +```javascript +import { v5 as uuidv5 } from 'uuid'; + +// Define a custom namespace. Readers, create your own using something like +// https://www.uuidgenerator.net/ +const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; + +uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681' +``` + +Example with RFC `URL` namespace: + +```javascript +import { v5 as uuidv5 } from 'uuid'; + +uuidv5('https://www.w3.org/', uuidv5.URL); // ⇨ 'c106a26a-21bb-5538-8bf2-57095d1976c1' +``` + +### uuid.v6([options[, buffer[, offset]]]) + +Create an RFC version 6 (timestamp, reordered) UUID + +This method takes the same arguments as uuid.v1(). + +```javascript +import { v6 as uuidv6 } from 'uuid'; + +uuidv6(); // ⇨ '1e940672-c5ea-64c0-9b5d-ab8dfbbd4bed' +``` + +Example using `options`: + +```javascript +import { v6 as uuidv6 } from 'uuid'; + +const options = { + node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab], + clockseq: 0x1234, + msecs: new Date('2011-11-01').getTime(), + nsecs: 5678, +}; +uuidv6(options); // ⇨ '1e1041c7-10b9-662e-9234-0123456789ab' +``` + +### uuid.v6ToV1(uuid) + +Convert a UUID from version 6 to version 1 + +```javascript +import { v6ToV1 } from 'uuid'; + +v6ToV1('1ef22c49-2f62-6d9e-97e9-325096b39f47'); // ⇨ '92f62d9e-22c4-11ef-97e9-325096b39f47' +``` + +### uuid.v7([options[, buffer[, offset]]]) + +Create an RFC version 7 (random) UUID + +| | | +| --- | --- | +| [`options`] | `Object` with one or more of the following properties: | +| [`options.msecs = (current time)`] | RFC "timestamp" field (`Number` of milliseconds, unix epoch) | +| [`options.random = (random)`] | `Array` of 16 random bytes (0-255) used to generate other fields, above | +| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | +| [`options.seq = (random)`] | 32-bit sequence `Number` between 0 - 0xffffffff. This may be provided to help ensure uniqueness for UUIDs generated within the same millisecond time interval. Default = random value. | +| [`buffer`] | `Uint8Array` or `Uint8Array` subtype (e.g. Node.js `Buffer`). If provided, binary UUID is written into the array, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | + +Example: + +```javascript +import { v7 as uuidv7 } from 'uuid'; + +uuidv7(); // ⇨ '01695553-c90c-705a-b56d-778dfbbd4bed' +``` + +### ~~uuid.v8()~~ + +**_"Intentionally left blank"_** + + +> [!NOTE] +> Version 8 (experimental) UUIDs are "[for experimental or vendor-specific use cases](https://www.rfc-editor.org/rfc/rfc9562.html#name-uuid-version-8)". The RFC does not define a creation algorithm for them, which is why this package does not offer a `v8()` method. The `validate()` and `version()` methods do work with such UUIDs, however. + +### uuid.validate(str) + +Test a string to see if it is a valid UUID + +| | | +| --------- | --------------------------------------------------- | +| `str` | `String` to validate | +| _returns_ | `true` if string is a valid UUID, `false` otherwise | + +Example: + +```javascript +import { validate as uuidValidate } from 'uuid'; + +uuidValidate('not a UUID'); // ⇨ false +uuidValidate('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ true +``` + +Using `validate` and `version` together it is possible to do per-version validation, e.g. validate for only v4 UUIds. + +```javascript +import { version as uuidVersion } from 'uuid'; +import { validate as uuidValidate } from 'uuid'; + +function uuidValidateV4(uuid) { + return uuidValidate(uuid) && uuidVersion(uuid) === 4; +} + +const v1Uuid = 'd9428888-122b-11e1-b85c-61cd3cbb3210'; +const v4Uuid = '109156be-c4fb-41ea-b1b4-efe1671c5836'; + +uuidValidateV4(v4Uuid); // ⇨ true +uuidValidateV4(v1Uuid); // ⇨ false +``` + +### uuid.version(str) + +Detect RFC version of a UUID + +| | | +| --------- | ---------------------------------------- | +| `str` | A valid UUID `String` | +| _returns_ | `Number` The RFC version of the UUID | +| _throws_ | `TypeError` if `str` is not a valid UUID | + +Example: + +```javascript +import { version as uuidVersion } from 'uuid'; + +uuidVersion('45637ec4-c85f-11ea-87d0-0242ac130003'); // ⇨ 1 +uuidVersion('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ 4 +``` + + +> [!NOTE] +> This method returns `0` for the `NIL` UUID, and `15` for the `MAX` UUID. + +## Command Line + +UUIDs can be generated from the command line using `uuid`. + +```shell +$ npx uuid +ddeb27fb-d9a0-4624-be4d-4615062daed4 +``` + +The default is to generate version 4 UUIDS, however the other versions are supported. Type `uuid --help` for details: + +```shell +$ npx uuid --help + +Usage: + uuid + uuid v1 + uuid v3 + uuid v4 + uuid v5 + uuid v7 + uuid --help + +Note: may be "URL" or "DNS" to use the corresponding UUIDs +defined by RFC9562 +``` + +## `options` Handling for Timestamp UUIDs + +Prior to `uuid@11`, it was possible for `options` state to interfere with the internal state used to ensure uniqueness of timestamp-based UUIDs (the `v1()`, `v6()`, and `v7()` methods). Starting with `uuid@11`, this issue has been addressed by using the presence of the `options` argument as a flag to select between two possible behaviors: + +- Without `options`: Internal state is utilized to improve UUID uniqueness. +- With `options`: Internal state is **NOT** used and, instead, appropriate defaults are applied as needed. + +## Support + +**Browsers**: `uuid` [builds are tested](/uuidjs/uuid/blob/main/wdio.conf.js) against the latest version of desktop Chrome, Safari, Firefox, and Edge. Mobile versions of these same browsers are expected to work but aren't currently tested. + +**Node**: `uuid` [builds are tested](https://github.com/uuidjs/uuid/blob/main/.github/workflows/ci.yml#L26-L27) against node ([LTS releases](https://github.com/nodejs/Release)), plus one prior. E.g. `node@18` is in maintainence mode, and `node@22` is the current LTS release. So `uuid` supports `node@16`-`node@22`. + +**Typescript**: TS versions released within the past two years are supported. [source](https://github.com/microsoft/TypeScript/issues/49088#issuecomment-2468723715) + +## Known issues + + + +### "getRandomValues() not supported" + +This error occurs in environments where the standard [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) API is not supported. This issue can be resolved by adding an appropriate polyfill: + +#### React Native / Expo + +1. Install [`react-native-get-random-values`](https://github.com/LinusU/react-native-get-random-values#readme) +1. Import it _before_ `uuid`. Since `uuid` might also appear as a transitive dependency of some other imports it's safest to just import `react-native-get-random-values` as the very first thing in your entry point: + +```javascript +import 'react-native-get-random-values'; +import { v4 as uuidv4 } from 'uuid'; +``` + +--- + +Markdown generated from [README_js.md](README_js.md) by diff --git a/node_modules/uuid/dist/cjs-browser/index.d.ts b/node_modules/uuid/dist/cjs-browser/index.d.ts new file mode 100644 index 0000000..d7d4edc --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/index.d.ts @@ -0,0 +1,15 @@ +export type * from './types.js'; +export { default as MAX } from './max.js'; +export { default as NIL } from './nil.js'; +export { default as parse } from './parse.js'; +export { default as stringify } from './stringify.js'; +export { default as v1 } from './v1.js'; +export { default as v1ToV6 } from './v1ToV6.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as v6 } from './v6.js'; +export { default as v6ToV1 } from './v6ToV1.js'; +export { default as v7 } from './v7.js'; +export { default as validate } from './validate.js'; +export { default as version } from './version.js'; diff --git a/node_modules/uuid/dist/cjs-browser/index.js b/node_modules/uuid/dist/cjs-browser/index.js new file mode 100644 index 0000000..6148ea4 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/index.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.version = exports.validate = exports.v7 = exports.v6ToV1 = exports.v6 = exports.v5 = exports.v4 = exports.v3 = exports.v1ToV6 = exports.v1 = exports.stringify = exports.parse = exports.NIL = exports.MAX = void 0; +var max_js_1 = require("./max.js"); +Object.defineProperty(exports, "MAX", { enumerable: true, get: function () { return max_js_1.default; } }); +var nil_js_1 = require("./nil.js"); +Object.defineProperty(exports, "NIL", { enumerable: true, get: function () { return nil_js_1.default; } }); +var parse_js_1 = require("./parse.js"); +Object.defineProperty(exports, "parse", { enumerable: true, get: function () { return parse_js_1.default; } }); +var stringify_js_1 = require("./stringify.js"); +Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return stringify_js_1.default; } }); +var v1_js_1 = require("./v1.js"); +Object.defineProperty(exports, "v1", { enumerable: true, get: function () { return v1_js_1.default; } }); +var v1ToV6_js_1 = require("./v1ToV6.js"); +Object.defineProperty(exports, "v1ToV6", { enumerable: true, get: function () { return v1ToV6_js_1.default; } }); +var v3_js_1 = require("./v3.js"); +Object.defineProperty(exports, "v3", { enumerable: true, get: function () { return v3_js_1.default; } }); +var v4_js_1 = require("./v4.js"); +Object.defineProperty(exports, "v4", { enumerable: true, get: function () { return v4_js_1.default; } }); +var v5_js_1 = require("./v5.js"); +Object.defineProperty(exports, "v5", { enumerable: true, get: function () { return v5_js_1.default; } }); +var v6_js_1 = require("./v6.js"); +Object.defineProperty(exports, "v6", { enumerable: true, get: function () { return v6_js_1.default; } }); +var v6ToV1_js_1 = require("./v6ToV1.js"); +Object.defineProperty(exports, "v6ToV1", { enumerable: true, get: function () { return v6ToV1_js_1.default; } }); +var v7_js_1 = require("./v7.js"); +Object.defineProperty(exports, "v7", { enumerable: true, get: function () { return v7_js_1.default; } }); +var validate_js_1 = require("./validate.js"); +Object.defineProperty(exports, "validate", { enumerable: true, get: function () { return validate_js_1.default; } }); +var version_js_1 = require("./version.js"); +Object.defineProperty(exports, "version", { enumerable: true, get: function () { return version_js_1.default; } }); diff --git a/node_modules/uuid/dist/cjs-browser/max.d.ts b/node_modules/uuid/dist/cjs-browser/max.d.ts new file mode 100644 index 0000000..7a1e972 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/max.d.ts @@ -0,0 +1,2 @@ +declare const _default: "ffffffff-ffff-ffff-ffff-ffffffffffff"; +export default _default; diff --git a/node_modules/uuid/dist/cjs-browser/max.js b/node_modules/uuid/dist/cjs-browser/max.js new file mode 100644 index 0000000..7ba71ef --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/max.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = 'ffffffff-ffff-ffff-ffff-ffffffffffff'; diff --git a/node_modules/uuid/dist/cjs-browser/md5.d.ts b/node_modules/uuid/dist/cjs-browser/md5.d.ts new file mode 100644 index 0000000..5a55f51 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/md5.d.ts @@ -0,0 +1,2 @@ +declare function md5(bytes: Uint8Array): Uint8Array; +export default md5; diff --git a/node_modules/uuid/dist/cjs-browser/md5.js b/node_modules/uuid/dist/cjs-browser/md5.js new file mode 100644 index 0000000..004b3d6 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/md5.js @@ -0,0 +1,137 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +function md5(bytes) { + const words = uint8ToUint32(bytes); + const md5Bytes = wordsToMd5(words, bytes.length * 8); + return uint32ToUint8(md5Bytes); +} +function uint32ToUint8(input) { + const bytes = new Uint8Array(input.length * 4); + for (let i = 0; i < input.length * 4; i++) { + bytes[i] = (input[i >> 2] >>> ((i % 4) * 8)) & 0xff; + } + return bytes; +} +function getOutputLength(inputLength8) { + return (((inputLength8 + 64) >>> 9) << 4) + 14 + 1; +} +function wordsToMd5(x, len) { + const xpad = new Uint32Array(getOutputLength(len)).fill(0); + xpad.set(x); + xpad[len >> 5] |= 0x80 << len % 32; + xpad[xpad.length - 1] = len; + x = xpad; + let a = 1732584193; + let b = -271733879; + let c = -1732584194; + let d = 271733878; + for (let i = 0; i < x.length; i += 16) { + const olda = a; + const oldb = b; + const oldc = c; + const oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + return Uint32Array.of(a, b, c, d); +} +function uint8ToUint32(input) { + if (input.length === 0) { + return new Uint32Array(); + } + const output = new Uint32Array(getOutputLength(input.length * 8)).fill(0); + for (let i = 0; i < input.length; i++) { + output[i >> 2] |= (input[i] & 0xff) << ((i % 4) * 8); + } + return output; +} +function safeAdd(x, y) { + const lsw = (x & 0xffff) + (y & 0xffff); + const msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xffff); +} +function bitRotateLeft(num, cnt) { + return (num << cnt) | (num >>> (32 - cnt)); +} +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} +function md5ff(a, b, c, d, x, s, t) { + return md5cmn((b & c) | (~b & d), a, b, x, s, t); +} +function md5gg(a, b, c, d, x, s, t) { + return md5cmn((b & d) | (c & ~d), a, b, x, s, t); +} +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} +exports.default = md5; diff --git a/node_modules/uuid/dist/cjs-browser/native.d.ts b/node_modules/uuid/dist/cjs-browser/native.d.ts new file mode 100644 index 0000000..9418fd3 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/native.d.ts @@ -0,0 +1,4 @@ +declare const _default: { + randomUUID: false | (() => `${string}-${string}-${string}-${string}-${string}`); +}; +export default _default; diff --git a/node_modules/uuid/dist/cjs-browser/native.js b/node_modules/uuid/dist/cjs-browser/native.js new file mode 100644 index 0000000..7e31a2a --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/native.js @@ -0,0 +1,4 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); +exports.default = { randomUUID }; diff --git a/node_modules/uuid/dist/cjs-browser/nil.d.ts b/node_modules/uuid/dist/cjs-browser/nil.d.ts new file mode 100644 index 0000000..b03bb98 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/nil.d.ts @@ -0,0 +1,2 @@ +declare const _default: "00000000-0000-0000-0000-000000000000"; +export default _default; diff --git a/node_modules/uuid/dist/cjs-browser/nil.js b/node_modules/uuid/dist/cjs-browser/nil.js new file mode 100644 index 0000000..5828aa4 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/nil.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = '00000000-0000-0000-0000-000000000000'; diff --git a/node_modules/uuid/dist/cjs-browser/package.json b/node_modules/uuid/dist/cjs-browser/package.json new file mode 100644 index 0000000..729ac4d --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/package.json @@ -0,0 +1 @@ +{"type":"commonjs"} diff --git a/node_modules/uuid/dist/cjs-browser/parse.d.ts b/node_modules/uuid/dist/cjs-browser/parse.d.ts new file mode 100644 index 0000000..a316fb1 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/parse.d.ts @@ -0,0 +1,2 @@ +declare function parse(uuid: string): Uint8Array; +export default parse; diff --git a/node_modules/uuid/dist/cjs-browser/parse.js b/node_modules/uuid/dist/cjs-browser/parse.js new file mode 100644 index 0000000..d2fa8ca --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/parse.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const validate_js_1 = require("./validate.js"); +function parse(uuid) { + if (!(0, validate_js_1.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + let v; + return Uint8Array.of((v = parseInt(uuid.slice(0, 8), 16)) >>> 24, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff, (v = parseInt(uuid.slice(9, 13), 16)) >>> 8, v & 0xff, (v = parseInt(uuid.slice(14, 18), 16)) >>> 8, v & 0xff, (v = parseInt(uuid.slice(19, 23), 16)) >>> 8, v & 0xff, ((v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000) & 0xff, (v / 0x100000000) & 0xff, (v >>> 24) & 0xff, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff); +} +exports.default = parse; diff --git a/node_modules/uuid/dist/cjs-browser/regex.d.ts b/node_modules/uuid/dist/cjs-browser/regex.d.ts new file mode 100644 index 0000000..d39fa3f --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/regex.d.ts @@ -0,0 +1,2 @@ +declare const _default: RegExp; +export default _default; diff --git a/node_modules/uuid/dist/cjs-browser/regex.js b/node_modules/uuid/dist/cjs-browser/regex.js new file mode 100644 index 0000000..e3dde2a --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/regex.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.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; diff --git a/node_modules/uuid/dist/cjs-browser/rng.d.ts b/node_modules/uuid/dist/cjs-browser/rng.d.ts new file mode 100644 index 0000000..73e60cf --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/rng.d.ts @@ -0,0 +1 @@ +export default function rng(): Uint8Array; diff --git a/node_modules/uuid/dist/cjs-browser/rng.js b/node_modules/uuid/dist/cjs-browser/rng.js new file mode 100644 index 0000000..155bcd7 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/rng.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +let getRandomValues; +const rnds8 = new Uint8Array(16); +function rng() { + if (!getRandomValues) { + if (typeof crypto === 'undefined' || !crypto.getRandomValues) { + throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); + } + getRandomValues = crypto.getRandomValues.bind(crypto); + } + return getRandomValues(rnds8); +} +exports.default = rng; diff --git a/node_modules/uuid/dist/cjs-browser/sha1.d.ts b/node_modules/uuid/dist/cjs-browser/sha1.d.ts new file mode 100644 index 0000000..a6552e5 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/sha1.d.ts @@ -0,0 +1,2 @@ +declare function sha1(bytes: Uint8Array): Uint8Array; +export default sha1; diff --git a/node_modules/uuid/dist/cjs-browser/sha1.js b/node_modules/uuid/dist/cjs-browser/sha1.js new file mode 100644 index 0000000..031c42c --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/sha1.js @@ -0,0 +1,72 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +function f(s, x, y, z) { + switch (s) { + case 0: + return (x & y) ^ (~x & z); + case 1: + return x ^ y ^ z; + case 2: + return (x & y) ^ (x & z) ^ (y & z); + case 3: + return x ^ y ^ z; + } +} +function ROTL(x, n) { + return (x << n) | (x >>> (32 - n)); +} +function sha1(bytes) { + const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + const newBytes = new Uint8Array(bytes.length + 1); + newBytes.set(bytes); + newBytes[bytes.length] = 0x80; + bytes = newBytes; + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + for (let i = 0; i < N; ++i) { + const arr = new Uint32Array(16); + for (let j = 0; j < 16; ++j) { + arr[j] = + (bytes[i * 64 + j * 4] << 24) | + (bytes[i * 64 + j * 4 + 1] << 16) | + (bytes[i * 64 + j * 4 + 2] << 8) | + bytes[i * 64 + j * 4 + 3]; + } + M[i] = arr; + } + M[N - 1][14] = ((bytes.length - 1) * 8) / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = ((bytes.length - 1) * 8) & 0xffffffff; + for (let i = 0; i < N; ++i) { + const W = new Uint32Array(80); + for (let t = 0; t < 16; ++t) { + W[t] = M[i][t]; + } + for (let t = 16; t < 80; ++t) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = (ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t]) >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + H[0] = (H[0] + a) >>> 0; + H[1] = (H[1] + b) >>> 0; + H[2] = (H[2] + c) >>> 0; + H[3] = (H[3] + d) >>> 0; + H[4] = (H[4] + e) >>> 0; + } + return Uint8Array.of(H[0] >> 24, H[0] >> 16, H[0] >> 8, H[0], H[1] >> 24, H[1] >> 16, H[1] >> 8, H[1], H[2] >> 24, H[2] >> 16, H[2] >> 8, H[2], H[3] >> 24, H[3] >> 16, H[3] >> 8, H[3], H[4] >> 24, H[4] >> 16, H[4] >> 8, H[4]); +} +exports.default = sha1; diff --git a/node_modules/uuid/dist/cjs-browser/stringify.d.ts b/node_modules/uuid/dist/cjs-browser/stringify.d.ts new file mode 100644 index 0000000..16cb008 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/stringify.d.ts @@ -0,0 +1,3 @@ +export declare function unsafeStringify(arr: Uint8Array, offset?: number): string; +declare function stringify(arr: Uint8Array, offset?: number): string; +export default stringify; diff --git a/node_modules/uuid/dist/cjs-browser/stringify.js b/node_modules/uuid/dist/cjs-browser/stringify.js new file mode 100644 index 0000000..2ba27bb --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/stringify.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.unsafeStringify = void 0; +const validate_js_1 = require("./validate.js"); +const byteToHex = []; +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} +function unsafeStringify(arr, offset = 0) { + return (byteToHex[arr[offset + 0]] + + byteToHex[arr[offset + 1]] + + byteToHex[arr[offset + 2]] + + byteToHex[arr[offset + 3]] + + '-' + + byteToHex[arr[offset + 4]] + + byteToHex[arr[offset + 5]] + + '-' + + byteToHex[arr[offset + 6]] + + byteToHex[arr[offset + 7]] + + '-' + + byteToHex[arr[offset + 8]] + + byteToHex[arr[offset + 9]] + + '-' + + byteToHex[arr[offset + 10]] + + byteToHex[arr[offset + 11]] + + byteToHex[arr[offset + 12]] + + byteToHex[arr[offset + 13]] + + byteToHex[arr[offset + 14]] + + byteToHex[arr[offset + 15]]).toLowerCase(); +} +exports.unsafeStringify = unsafeStringify; +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); + if (!(0, validate_js_1.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + return uuid; +} +exports.default = stringify; diff --git a/node_modules/uuid/dist/cjs-browser/types.d.ts b/node_modules/uuid/dist/cjs-browser/types.d.ts new file mode 100644 index 0000000..ecaed97 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/types.d.ts @@ -0,0 +1,21 @@ +export type UUIDTypes = string | TBuf; +export type Version1Options = { + node?: Uint8Array; + clockseq?: number; + random?: Uint8Array; + rng?: () => Uint8Array; + msecs?: number; + nsecs?: number; + _v6?: boolean; +}; +export type Version4Options = { + random?: Uint8Array; + rng?: () => Uint8Array; +}; +export type Version6Options = Version1Options; +export type Version7Options = { + random?: Uint8Array; + msecs?: number; + seq?: number; + rng?: () => Uint8Array; +}; diff --git a/node_modules/uuid/dist/cjs-browser/types.js b/node_modules/uuid/dist/cjs-browser/types.js new file mode 100644 index 0000000..c8ad2e5 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/types.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/uuid/dist/cjs-browser/uuid-bin.d.ts b/node_modules/uuid/dist/cjs-browser/uuid-bin.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/uuid-bin.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/uuid/dist/cjs-browser/uuid-bin.js b/node_modules/uuid/dist/cjs-browser/uuid-bin.js new file mode 100644 index 0000000..d613137 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/uuid-bin.js @@ -0,0 +1,72 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const assert = require("assert"); +const v1_js_1 = require("./v1.js"); +const v3_js_1 = require("./v3.js"); +const v4_js_1 = require("./v4.js"); +const v5_js_1 = require("./v5.js"); +const v6_js_1 = require("./v6.js"); +const v7_js_1 = require("./v7.js"); +function usage() { + console.log('Usage:'); + console.log(' uuid'); + console.log(' uuid v1'); + console.log(' uuid v3 '); + console.log(' uuid v4'); + console.log(' uuid v5 '); + console.log(' uuid v6'); + console.log(' uuid v7'); + console.log(' uuid --help'); + console.log('\nNote: may be "URL" or "DNS" to use the corresponding UUIDs defined by RFC9562'); +} +const args = process.argv.slice(2); +if (args.indexOf('--help') >= 0) { + usage(); + process.exit(0); +} +const version = args.shift() || 'v4'; +switch (version) { + case 'v1': + console.log((0, v1_js_1.default)()); + break; + case 'v3': { + const name = args.shift(); + let namespace = args.shift(); + assert.ok(name != null, 'v3 name not specified'); + assert.ok(namespace != null, 'v3 namespace not specified'); + if (namespace === 'URL') { + namespace = v3_js_1.default.URL; + } + if (namespace === 'DNS') { + namespace = v3_js_1.default.DNS; + } + console.log((0, v3_js_1.default)(name, namespace)); + break; + } + case 'v4': + console.log((0, v4_js_1.default)()); + break; + case 'v5': { + const name = args.shift(); + let namespace = args.shift(); + assert.ok(name != null, 'v5 name not specified'); + assert.ok(namespace != null, 'v5 namespace not specified'); + if (namespace === 'URL') { + namespace = v5_js_1.default.URL; + } + if (namespace === 'DNS') { + namespace = v5_js_1.default.DNS; + } + console.log((0, v5_js_1.default)(name, namespace)); + break; + } + case 'v6': + console.log((0, v6_js_1.default)()); + break; + case 'v7': + console.log((0, v7_js_1.default)()); + break; + default: + usage(); + process.exit(1); +} diff --git a/node_modules/uuid/dist/cjs-browser/v1.d.ts b/node_modules/uuid/dist/cjs-browser/v1.d.ts new file mode 100644 index 0000000..d8ecee0 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/v1.d.ts @@ -0,0 +1,11 @@ +import { Version1Options } from './types.js'; +type V1State = { + node?: Uint8Array; + clockseq?: number; + msecs?: number; + nsecs?: number; +}; +declare function v1(options?: Version1Options, buf?: undefined, offset?: number): string; +declare function v1(options: Version1Options | undefined, buf: Buf, offset?: number): Buf; +export declare function updateV1State(state: V1State, now: number, rnds: Uint8Array): V1State; +export default v1; diff --git a/node_modules/uuid/dist/cjs-browser/v1.js b/node_modules/uuid/dist/cjs-browser/v1.js new file mode 100644 index 0000000..155b80d --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/v1.js @@ -0,0 +1,87 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.updateV1State = void 0; +const rng_js_1 = require("./rng.js"); +const stringify_js_1 = require("./stringify.js"); +const _state = {}; +function v1(options, buf, offset) { + let bytes; + const isV6 = options?._v6 ?? false; + if (options) { + const optionsKeys = Object.keys(options); + if (optionsKeys.length === 1 && optionsKeys[0] === '_v6') { + options = undefined; + } + } + if (options) { + bytes = v1Bytes(options.random ?? options.rng?.() ?? (0, rng_js_1.default)(), options.msecs, options.nsecs, options.clockseq, options.node, buf, offset); + } + else { + const now = Date.now(); + const rnds = (0, rng_js_1.default)(); + updateV1State(_state, now, rnds); + bytes = v1Bytes(rnds, _state.msecs, _state.nsecs, isV6 ? undefined : _state.clockseq, isV6 ? undefined : _state.node, buf, offset); + } + return buf ?? (0, stringify_js_1.unsafeStringify)(bytes); +} +function updateV1State(state, now, rnds) { + state.msecs ??= -Infinity; + state.nsecs ??= 0; + if (now === state.msecs) { + state.nsecs++; + if (state.nsecs >= 10000) { + state.node = undefined; + state.nsecs = 0; + } + } + else if (now > state.msecs) { + state.nsecs = 0; + } + else if (now < state.msecs) { + state.node = undefined; + } + if (!state.node) { + state.node = rnds.slice(10, 16); + state.node[0] |= 0x01; + state.clockseq = ((rnds[8] << 8) | rnds[9]) & 0x3fff; + } + state.msecs = now; + return state; +} +exports.updateV1State = updateV1State; +function v1Bytes(rnds, msecs, nsecs, clockseq, node, buf, offset = 0) { + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + if (!buf) { + buf = new Uint8Array(16); + offset = 0; + } + else { + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + } + msecs ??= Date.now(); + nsecs ??= 0; + clockseq ??= ((rnds[8] << 8) | rnds[9]) & 0x3fff; + node ??= rnds.slice(10, 16); + msecs += 12219292800000; + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + buf[offset++] = (tl >>> 24) & 0xff; + buf[offset++] = (tl >>> 16) & 0xff; + buf[offset++] = (tl >>> 8) & 0xff; + buf[offset++] = tl & 0xff; + const tmh = ((msecs / 0x100000000) * 10000) & 0xfffffff; + buf[offset++] = (tmh >>> 8) & 0xff; + buf[offset++] = tmh & 0xff; + buf[offset++] = ((tmh >>> 24) & 0xf) | 0x10; + buf[offset++] = (tmh >>> 16) & 0xff; + buf[offset++] = (clockseq >>> 8) | 0x80; + buf[offset++] = clockseq & 0xff; + for (let n = 0; n < 6; ++n) { + buf[offset++] = node[n]; + } + return buf; +} +exports.default = v1; diff --git a/node_modules/uuid/dist/cjs-browser/v1ToV6.d.ts b/node_modules/uuid/dist/cjs-browser/v1ToV6.d.ts new file mode 100644 index 0000000..38eaaf0 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/v1ToV6.d.ts @@ -0,0 +1,2 @@ +export default function v1ToV6(uuid: string): string; +export default function v1ToV6(uuid: Uint8Array): Uint8Array; diff --git a/node_modules/uuid/dist/cjs-browser/v1ToV6.js b/node_modules/uuid/dist/cjs-browser/v1ToV6.js new file mode 100644 index 0000000..daba2c3 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/v1ToV6.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const parse_js_1 = require("./parse.js"); +const stringify_js_1 = require("./stringify.js"); +function v1ToV6(uuid) { + const v1Bytes = typeof uuid === 'string' ? (0, parse_js_1.default)(uuid) : uuid; + const v6Bytes = _v1ToV6(v1Bytes); + return typeof uuid === 'string' ? (0, stringify_js_1.unsafeStringify)(v6Bytes) : v6Bytes; +} +exports.default = v1ToV6; +function _v1ToV6(v1Bytes) { + return Uint8Array.of(((v1Bytes[6] & 0x0f) << 4) | ((v1Bytes[7] >> 4) & 0x0f), ((v1Bytes[7] & 0x0f) << 4) | ((v1Bytes[4] & 0xf0) >> 4), ((v1Bytes[4] & 0x0f) << 4) | ((v1Bytes[5] & 0xf0) >> 4), ((v1Bytes[5] & 0x0f) << 4) | ((v1Bytes[0] & 0xf0) >> 4), ((v1Bytes[0] & 0x0f) << 4) | ((v1Bytes[1] & 0xf0) >> 4), ((v1Bytes[1] & 0x0f) << 4) | ((v1Bytes[2] & 0xf0) >> 4), 0x60 | (v1Bytes[2] & 0x0f), v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]); +} diff --git a/node_modules/uuid/dist/cjs-browser/v3.d.ts b/node_modules/uuid/dist/cjs-browser/v3.d.ts new file mode 100644 index 0000000..5d1c434 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/v3.d.ts @@ -0,0 +1,9 @@ +import { UUIDTypes } from './types.js'; +export { DNS, URL } from './v35.js'; +declare function v3(value: string | Uint8Array, namespace: UUIDTypes, buf?: undefined, offset?: number): string; +declare function v3(value: string | Uint8Array, namespace: UUIDTypes, buf: TBuf, offset?: number): TBuf; +declare namespace v3 { + var DNS: string; + var URL: string; +} +export default v3; diff --git a/node_modules/uuid/dist/cjs-browser/v3.js b/node_modules/uuid/dist/cjs-browser/v3.js new file mode 100644 index 0000000..d318d2a --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/v3.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.URL = exports.DNS = void 0; +const md5_js_1 = require("./md5.js"); +const v35_js_1 = require("./v35.js"); +var v35_js_2 = require("./v35.js"); +Object.defineProperty(exports, "DNS", { enumerable: true, get: function () { return v35_js_2.DNS; } }); +Object.defineProperty(exports, "URL", { enumerable: true, get: function () { return v35_js_2.URL; } }); +function v3(value, namespace, buf, offset) { + return (0, v35_js_1.default)(0x30, md5_js_1.default, value, namespace, buf, offset); +} +v3.DNS = v35_js_1.DNS; +v3.URL = v35_js_1.URL; +exports.default = v3; diff --git a/node_modules/uuid/dist/cjs-browser/v35.d.ts b/node_modules/uuid/dist/cjs-browser/v35.d.ts new file mode 100644 index 0000000..4e6e9d5 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/v35.d.ts @@ -0,0 +1,7 @@ +import { UUIDTypes } from './types.js'; +export declare function stringToBytes(str: string): Uint8Array; +export declare const DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; +export declare const URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; +type HashFunction = (bytes: Uint8Array) => Uint8Array; +export default function v35(version: 0x30 | 0x50, hash: HashFunction, value: string | Uint8Array, namespace: UUIDTypes, buf?: TBuf, offset?: number): UUIDTypes; +export {}; diff --git a/node_modules/uuid/dist/cjs-browser/v35.js b/node_modules/uuid/dist/cjs-browser/v35.js new file mode 100644 index 0000000..a3712f2 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/v35.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.URL = exports.DNS = exports.stringToBytes = void 0; +const parse_js_1 = require("./parse.js"); +const stringify_js_1 = require("./stringify.js"); +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); + const bytes = new Uint8Array(str.length); + for (let i = 0; i < str.length; ++i) { + bytes[i] = str.charCodeAt(i); + } + return bytes; +} +exports.stringToBytes = stringToBytes; +exports.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +function v35(version, hash, value, namespace, buf, offset) { + const valueBytes = typeof value === 'string' ? stringToBytes(value) : value; + const namespaceBytes = typeof namespace === 'string' ? (0, parse_js_1.default)(namespace) : namespace; + if (typeof namespace === 'string') { + namespace = (0, parse_js_1.default)(namespace); + } + if (namespace?.length !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } + let bytes = new Uint8Array(16 + valueBytes.length); + bytes.set(namespaceBytes); + bytes.set(valueBytes, namespaceBytes.length); + bytes = hash(bytes); + bytes[6] = (bytes[6] & 0x0f) | version; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + if (buf) { + offset = offset || 0; + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + return buf; + } + return (0, stringify_js_1.unsafeStringify)(bytes); +} +exports.default = v35; diff --git a/node_modules/uuid/dist/cjs-browser/v4.d.ts b/node_modules/uuid/dist/cjs-browser/v4.d.ts new file mode 100644 index 0000000..8205333 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/v4.d.ts @@ -0,0 +1,4 @@ +import { Version4Options } from './types.js'; +declare function v4(options?: Version4Options, buf?: undefined, offset?: number): string; +declare function v4(options: Version4Options | undefined, buf: TBuf, offset?: number): TBuf; +export default v4; diff --git a/node_modules/uuid/dist/cjs-browser/v4.js b/node_modules/uuid/dist/cjs-browser/v4.js new file mode 100644 index 0000000..69c975e --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/v4.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const native_js_1 = require("./native.js"); +const rng_js_1 = require("./rng.js"); +const stringify_js_1 = require("./stringify.js"); +function v4(options, buf, offset) { + if (native_js_1.default.randomUUID && !buf && !options) { + return native_js_1.default.randomUUID(); + } + options = options || {}; + const rnds = options.random ?? options.rng?.() ?? (0, rng_js_1.default)(); + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; + if (buf) { + offset = offset || 0; + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + return buf; + } + return (0, stringify_js_1.unsafeStringify)(rnds); +} +exports.default = v4; diff --git a/node_modules/uuid/dist/cjs-browser/v5.d.ts b/node_modules/uuid/dist/cjs-browser/v5.d.ts new file mode 100644 index 0000000..0e2ff2f --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/v5.d.ts @@ -0,0 +1,9 @@ +import { UUIDTypes } from './types.js'; +export { DNS, URL } from './v35.js'; +declare function v5(value: string | Uint8Array, namespace: UUIDTypes, buf?: undefined, offset?: number): string; +declare function v5(value: string | Uint8Array, namespace: UUIDTypes, buf: TBuf, offset?: number): TBuf; +declare namespace v5 { + var DNS: string; + var URL: string; +} +export default v5; diff --git a/node_modules/uuid/dist/cjs-browser/v5.js b/node_modules/uuid/dist/cjs-browser/v5.js new file mode 100644 index 0000000..c4239c2 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/v5.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.URL = exports.DNS = void 0; +const sha1_js_1 = require("./sha1.js"); +const v35_js_1 = require("./v35.js"); +var v35_js_2 = require("./v35.js"); +Object.defineProperty(exports, "DNS", { enumerable: true, get: function () { return v35_js_2.DNS; } }); +Object.defineProperty(exports, "URL", { enumerable: true, get: function () { return v35_js_2.URL; } }); +function v5(value, namespace, buf, offset) { + return (0, v35_js_1.default)(0x50, sha1_js_1.default, value, namespace, buf, offset); +} +v5.DNS = v35_js_1.DNS; +v5.URL = v35_js_1.URL; +exports.default = v5; diff --git a/node_modules/uuid/dist/cjs-browser/v6.d.ts b/node_modules/uuid/dist/cjs-browser/v6.d.ts new file mode 100644 index 0000000..cabf4a0 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/v6.d.ts @@ -0,0 +1,4 @@ +import { Version6Options } from './types.js'; +declare function v6(options?: Version6Options, buf?: undefined, offset?: number): string; +declare function v6(options: Version6Options | undefined, buf: TBuf, offset?: number): TBuf; +export default v6; diff --git a/node_modules/uuid/dist/cjs-browser/v6.js b/node_modules/uuid/dist/cjs-browser/v6.js new file mode 100644 index 0000000..b02748d --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/v6.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const stringify_js_1 = require("./stringify.js"); +const v1_js_1 = require("./v1.js"); +const v1ToV6_js_1 = require("./v1ToV6.js"); +function v6(options, buf, offset) { + options ??= {}; + offset ??= 0; + let bytes = (0, v1_js_1.default)({ ...options, _v6: true }, new Uint8Array(16)); + bytes = (0, v1ToV6_js_1.default)(bytes); + if (buf) { + for (let i = 0; i < 16; i++) { + buf[offset + i] = bytes[i]; + } + return buf; + } + return (0, stringify_js_1.unsafeStringify)(bytes); +} +exports.default = v6; diff --git a/node_modules/uuid/dist/cjs-browser/v6ToV1.d.ts b/node_modules/uuid/dist/cjs-browser/v6ToV1.d.ts new file mode 100644 index 0000000..3b3ffc2 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/v6ToV1.d.ts @@ -0,0 +1,2 @@ +export default function v6ToV1(uuid: string): string; +export default function v6ToV1(uuid: Uint8Array): Uint8Array; diff --git a/node_modules/uuid/dist/cjs-browser/v6ToV1.js b/node_modules/uuid/dist/cjs-browser/v6ToV1.js new file mode 100644 index 0000000..9dcb661 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/v6ToV1.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const parse_js_1 = require("./parse.js"); +const stringify_js_1 = require("./stringify.js"); +function v6ToV1(uuid) { + const v6Bytes = typeof uuid === 'string' ? (0, parse_js_1.default)(uuid) : uuid; + const v1Bytes = _v6ToV1(v6Bytes); + return typeof uuid === 'string' ? (0, stringify_js_1.unsafeStringify)(v1Bytes) : v1Bytes; +} +exports.default = v6ToV1; +function _v6ToV1(v6Bytes) { + return Uint8Array.of(((v6Bytes[3] & 0x0f) << 4) | ((v6Bytes[4] >> 4) & 0x0f), ((v6Bytes[4] & 0x0f) << 4) | ((v6Bytes[5] & 0xf0) >> 4), ((v6Bytes[5] & 0x0f) << 4) | (v6Bytes[6] & 0x0f), v6Bytes[7], ((v6Bytes[1] & 0x0f) << 4) | ((v6Bytes[2] & 0xf0) >> 4), ((v6Bytes[2] & 0x0f) << 4) | ((v6Bytes[3] & 0xf0) >> 4), 0x10 | ((v6Bytes[0] & 0xf0) >> 4), ((v6Bytes[0] & 0x0f) << 4) | ((v6Bytes[1] & 0xf0) >> 4), v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]); +} diff --git a/node_modules/uuid/dist/cjs-browser/v7.d.ts b/node_modules/uuid/dist/cjs-browser/v7.d.ts new file mode 100644 index 0000000..f49b03d --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/v7.d.ts @@ -0,0 +1,9 @@ +import { Version7Options } from './types.js'; +type V7State = { + msecs?: number; + seq?: number; +}; +declare function v7(options?: Version7Options, buf?: undefined, offset?: number): string; +declare function v7(options: Version7Options | undefined, buf: TBuf, offset?: number): TBuf; +export declare function updateV7State(state: V7State, now: number, rnds: Uint8Array): V7State; +export default v7; diff --git a/node_modules/uuid/dist/cjs-browser/v7.js b/node_modules/uuid/dist/cjs-browser/v7.js new file mode 100644 index 0000000..697fe34 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/v7.js @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.updateV7State = void 0; +const rng_js_1 = require("./rng.js"); +const stringify_js_1 = require("./stringify.js"); +const _state = {}; +function v7(options, buf, offset) { + let bytes; + if (options) { + bytes = v7Bytes(options.random ?? options.rng?.() ?? (0, rng_js_1.default)(), options.msecs, options.seq, buf, offset); + } + else { + const now = Date.now(); + const rnds = (0, rng_js_1.default)(); + updateV7State(_state, now, rnds); + bytes = v7Bytes(rnds, _state.msecs, _state.seq, buf, offset); + } + return buf ?? (0, stringify_js_1.unsafeStringify)(bytes); +} +function updateV7State(state, now, rnds) { + state.msecs ??= -Infinity; + state.seq ??= 0; + if (now > state.msecs) { + state.seq = (rnds[6] << 23) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9]; + state.msecs = now; + } + else { + state.seq = (state.seq + 1) | 0; + if (state.seq === 0) { + state.msecs++; + } + } + return state; +} +exports.updateV7State = updateV7State; +function v7Bytes(rnds, msecs, seq, buf, offset = 0) { + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + if (!buf) { + buf = new Uint8Array(16); + offset = 0; + } + else { + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + } + msecs ??= Date.now(); + seq ??= ((rnds[6] * 0x7f) << 24) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9]; + buf[offset++] = (msecs / 0x10000000000) & 0xff; + buf[offset++] = (msecs / 0x100000000) & 0xff; + buf[offset++] = (msecs / 0x1000000) & 0xff; + buf[offset++] = (msecs / 0x10000) & 0xff; + buf[offset++] = (msecs / 0x100) & 0xff; + buf[offset++] = msecs & 0xff; + buf[offset++] = 0x70 | ((seq >>> 28) & 0x0f); + buf[offset++] = (seq >>> 20) & 0xff; + buf[offset++] = 0x80 | ((seq >>> 14) & 0x3f); + buf[offset++] = (seq >>> 6) & 0xff; + buf[offset++] = ((seq << 2) & 0xff) | (rnds[10] & 0x03); + buf[offset++] = rnds[11]; + buf[offset++] = rnds[12]; + buf[offset++] = rnds[13]; + buf[offset++] = rnds[14]; + buf[offset++] = rnds[15]; + return buf; +} +exports.default = v7; diff --git a/node_modules/uuid/dist/cjs-browser/validate.d.ts b/node_modules/uuid/dist/cjs-browser/validate.d.ts new file mode 100644 index 0000000..57da03d --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/validate.d.ts @@ -0,0 +1,2 @@ +declare function validate(uuid: unknown): boolean; +export default validate; diff --git a/node_modules/uuid/dist/cjs-browser/validate.js b/node_modules/uuid/dist/cjs-browser/validate.js new file mode 100644 index 0000000..89733b0 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/validate.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const regex_js_1 = require("./regex.js"); +function validate(uuid) { + return typeof uuid === 'string' && regex_js_1.default.test(uuid); +} +exports.default = validate; diff --git a/node_modules/uuid/dist/cjs-browser/version.d.ts b/node_modules/uuid/dist/cjs-browser/version.d.ts new file mode 100644 index 0000000..f1948dc --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/version.d.ts @@ -0,0 +1,2 @@ +declare function version(uuid: string): number; +export default version; diff --git a/node_modules/uuid/dist/cjs-browser/version.js b/node_modules/uuid/dist/cjs-browser/version.js new file mode 100644 index 0000000..05ecd00 --- /dev/null +++ b/node_modules/uuid/dist/cjs-browser/version.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const validate_js_1 = require("./validate.js"); +function version(uuid) { + if (!(0, validate_js_1.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + return parseInt(uuid.slice(14, 15), 16); +} +exports.default = version; diff --git a/node_modules/uuid/dist/cjs/index.d.ts b/node_modules/uuid/dist/cjs/index.d.ts new file mode 100644 index 0000000..d7d4edc --- /dev/null +++ b/node_modules/uuid/dist/cjs/index.d.ts @@ -0,0 +1,15 @@ +export type * from './types.js'; +export { default as MAX } from './max.js'; +export { default as NIL } from './nil.js'; +export { default as parse } from './parse.js'; +export { default as stringify } from './stringify.js'; +export { default as v1 } from './v1.js'; +export { default as v1ToV6 } from './v1ToV6.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as v6 } from './v6.js'; +export { default as v6ToV1 } from './v6ToV1.js'; +export { default as v7 } from './v7.js'; +export { default as validate } from './validate.js'; +export { default as version } from './version.js'; diff --git a/node_modules/uuid/dist/cjs/index.js b/node_modules/uuid/dist/cjs/index.js new file mode 100644 index 0000000..6148ea4 --- /dev/null +++ b/node_modules/uuid/dist/cjs/index.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.version = exports.validate = exports.v7 = exports.v6ToV1 = exports.v6 = exports.v5 = exports.v4 = exports.v3 = exports.v1ToV6 = exports.v1 = exports.stringify = exports.parse = exports.NIL = exports.MAX = void 0; +var max_js_1 = require("./max.js"); +Object.defineProperty(exports, "MAX", { enumerable: true, get: function () { return max_js_1.default; } }); +var nil_js_1 = require("./nil.js"); +Object.defineProperty(exports, "NIL", { enumerable: true, get: function () { return nil_js_1.default; } }); +var parse_js_1 = require("./parse.js"); +Object.defineProperty(exports, "parse", { enumerable: true, get: function () { return parse_js_1.default; } }); +var stringify_js_1 = require("./stringify.js"); +Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return stringify_js_1.default; } }); +var v1_js_1 = require("./v1.js"); +Object.defineProperty(exports, "v1", { enumerable: true, get: function () { return v1_js_1.default; } }); +var v1ToV6_js_1 = require("./v1ToV6.js"); +Object.defineProperty(exports, "v1ToV6", { enumerable: true, get: function () { return v1ToV6_js_1.default; } }); +var v3_js_1 = require("./v3.js"); +Object.defineProperty(exports, "v3", { enumerable: true, get: function () { return v3_js_1.default; } }); +var v4_js_1 = require("./v4.js"); +Object.defineProperty(exports, "v4", { enumerable: true, get: function () { return v4_js_1.default; } }); +var v5_js_1 = require("./v5.js"); +Object.defineProperty(exports, "v5", { enumerable: true, get: function () { return v5_js_1.default; } }); +var v6_js_1 = require("./v6.js"); +Object.defineProperty(exports, "v6", { enumerable: true, get: function () { return v6_js_1.default; } }); +var v6ToV1_js_1 = require("./v6ToV1.js"); +Object.defineProperty(exports, "v6ToV1", { enumerable: true, get: function () { return v6ToV1_js_1.default; } }); +var v7_js_1 = require("./v7.js"); +Object.defineProperty(exports, "v7", { enumerable: true, get: function () { return v7_js_1.default; } }); +var validate_js_1 = require("./validate.js"); +Object.defineProperty(exports, "validate", { enumerable: true, get: function () { return validate_js_1.default; } }); +var version_js_1 = require("./version.js"); +Object.defineProperty(exports, "version", { enumerable: true, get: function () { return version_js_1.default; } }); diff --git a/node_modules/uuid/dist/cjs/max.d.ts b/node_modules/uuid/dist/cjs/max.d.ts new file mode 100644 index 0000000..7a1e972 --- /dev/null +++ b/node_modules/uuid/dist/cjs/max.d.ts @@ -0,0 +1,2 @@ +declare const _default: "ffffffff-ffff-ffff-ffff-ffffffffffff"; +export default _default; diff --git a/node_modules/uuid/dist/cjs/max.js b/node_modules/uuid/dist/cjs/max.js new file mode 100644 index 0000000..7ba71ef --- /dev/null +++ b/node_modules/uuid/dist/cjs/max.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = 'ffffffff-ffff-ffff-ffff-ffffffffffff'; diff --git a/node_modules/uuid/dist/cjs/md5.d.ts b/node_modules/uuid/dist/cjs/md5.d.ts new file mode 100644 index 0000000..f8f6ecf --- /dev/null +++ b/node_modules/uuid/dist/cjs/md5.d.ts @@ -0,0 +1,4 @@ +/// +/// +declare function md5(bytes: Uint8Array): Buffer; +export default md5; diff --git a/node_modules/uuid/dist/cjs/md5.js b/node_modules/uuid/dist/cjs/md5.js new file mode 100644 index 0000000..7665013 --- /dev/null +++ b/node_modules/uuid/dist/cjs/md5.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const crypto_1 = require("crypto"); +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } + else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + return (0, crypto_1.createHash)('md5').update(bytes).digest(); +} +exports.default = md5; diff --git a/node_modules/uuid/dist/cjs/native.d.ts b/node_modules/uuid/dist/cjs/native.d.ts new file mode 100644 index 0000000..2b6c756 --- /dev/null +++ b/node_modules/uuid/dist/cjs/native.d.ts @@ -0,0 +1,6 @@ +/// +import { randomUUID } from 'crypto'; +declare const _default: { + randomUUID: typeof randomUUID; +}; +export default _default; diff --git a/node_modules/uuid/dist/cjs/native.js b/node_modules/uuid/dist/cjs/native.js new file mode 100644 index 0000000..1013e98 --- /dev/null +++ b/node_modules/uuid/dist/cjs/native.js @@ -0,0 +1,4 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const crypto_1 = require("crypto"); +exports.default = { randomUUID: crypto_1.randomUUID }; diff --git a/node_modules/uuid/dist/cjs/nil.d.ts b/node_modules/uuid/dist/cjs/nil.d.ts new file mode 100644 index 0000000..b03bb98 --- /dev/null +++ b/node_modules/uuid/dist/cjs/nil.d.ts @@ -0,0 +1,2 @@ +declare const _default: "00000000-0000-0000-0000-000000000000"; +export default _default; diff --git a/node_modules/uuid/dist/cjs/nil.js b/node_modules/uuid/dist/cjs/nil.js new file mode 100644 index 0000000..5828aa4 --- /dev/null +++ b/node_modules/uuid/dist/cjs/nil.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = '00000000-0000-0000-0000-000000000000'; diff --git a/node_modules/uuid/dist/cjs/package.json b/node_modules/uuid/dist/cjs/package.json new file mode 100644 index 0000000..729ac4d --- /dev/null +++ b/node_modules/uuid/dist/cjs/package.json @@ -0,0 +1 @@ +{"type":"commonjs"} diff --git a/node_modules/uuid/dist/cjs/parse.d.ts b/node_modules/uuid/dist/cjs/parse.d.ts new file mode 100644 index 0000000..a316fb1 --- /dev/null +++ b/node_modules/uuid/dist/cjs/parse.d.ts @@ -0,0 +1,2 @@ +declare function parse(uuid: string): Uint8Array; +export default parse; diff --git a/node_modules/uuid/dist/cjs/parse.js b/node_modules/uuid/dist/cjs/parse.js new file mode 100644 index 0000000..d2fa8ca --- /dev/null +++ b/node_modules/uuid/dist/cjs/parse.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const validate_js_1 = require("./validate.js"); +function parse(uuid) { + if (!(0, validate_js_1.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + let v; + return Uint8Array.of((v = parseInt(uuid.slice(0, 8), 16)) >>> 24, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff, (v = parseInt(uuid.slice(9, 13), 16)) >>> 8, v & 0xff, (v = parseInt(uuid.slice(14, 18), 16)) >>> 8, v & 0xff, (v = parseInt(uuid.slice(19, 23), 16)) >>> 8, v & 0xff, ((v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000) & 0xff, (v / 0x100000000) & 0xff, (v >>> 24) & 0xff, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff); +} +exports.default = parse; diff --git a/node_modules/uuid/dist/cjs/regex.d.ts b/node_modules/uuid/dist/cjs/regex.d.ts new file mode 100644 index 0000000..d39fa3f --- /dev/null +++ b/node_modules/uuid/dist/cjs/regex.d.ts @@ -0,0 +1,2 @@ +declare const _default: RegExp; +export default _default; diff --git a/node_modules/uuid/dist/cjs/regex.js b/node_modules/uuid/dist/cjs/regex.js new file mode 100644 index 0000000..e3dde2a --- /dev/null +++ b/node_modules/uuid/dist/cjs/regex.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.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; diff --git a/node_modules/uuid/dist/cjs/rng.d.ts b/node_modules/uuid/dist/cjs/rng.d.ts new file mode 100644 index 0000000..73e60cf --- /dev/null +++ b/node_modules/uuid/dist/cjs/rng.d.ts @@ -0,0 +1 @@ +export default function rng(): Uint8Array; diff --git a/node_modules/uuid/dist/cjs/rng.js b/node_modules/uuid/dist/cjs/rng.js new file mode 100644 index 0000000..8f5458e --- /dev/null +++ b/node_modules/uuid/dist/cjs/rng.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const crypto_1 = require("crypto"); +const rnds8Pool = new Uint8Array(256); +let poolPtr = rnds8Pool.length; +function rng() { + if (poolPtr > rnds8Pool.length - 16) { + (0, crypto_1.randomFillSync)(rnds8Pool); + poolPtr = 0; + } + return rnds8Pool.slice(poolPtr, (poolPtr += 16)); +} +exports.default = rng; diff --git a/node_modules/uuid/dist/cjs/sha1.d.ts b/node_modules/uuid/dist/cjs/sha1.d.ts new file mode 100644 index 0000000..dfdc2ea --- /dev/null +++ b/node_modules/uuid/dist/cjs/sha1.d.ts @@ -0,0 +1,4 @@ +/// +/// +declare function sha1(bytes: Uint8Array): Buffer; +export default sha1; diff --git a/node_modules/uuid/dist/cjs/sha1.js b/node_modules/uuid/dist/cjs/sha1.js new file mode 100644 index 0000000..dccedf5 --- /dev/null +++ b/node_modules/uuid/dist/cjs/sha1.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const crypto_1 = require("crypto"); +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } + else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + return (0, crypto_1.createHash)('sha1').update(bytes).digest(); +} +exports.default = sha1; diff --git a/node_modules/uuid/dist/cjs/stringify.d.ts b/node_modules/uuid/dist/cjs/stringify.d.ts new file mode 100644 index 0000000..16cb008 --- /dev/null +++ b/node_modules/uuid/dist/cjs/stringify.d.ts @@ -0,0 +1,3 @@ +export declare function unsafeStringify(arr: Uint8Array, offset?: number): string; +declare function stringify(arr: Uint8Array, offset?: number): string; +export default stringify; diff --git a/node_modules/uuid/dist/cjs/stringify.js b/node_modules/uuid/dist/cjs/stringify.js new file mode 100644 index 0000000..2ba27bb --- /dev/null +++ b/node_modules/uuid/dist/cjs/stringify.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.unsafeStringify = void 0; +const validate_js_1 = require("./validate.js"); +const byteToHex = []; +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} +function unsafeStringify(arr, offset = 0) { + return (byteToHex[arr[offset + 0]] + + byteToHex[arr[offset + 1]] + + byteToHex[arr[offset + 2]] + + byteToHex[arr[offset + 3]] + + '-' + + byteToHex[arr[offset + 4]] + + byteToHex[arr[offset + 5]] + + '-' + + byteToHex[arr[offset + 6]] + + byteToHex[arr[offset + 7]] + + '-' + + byteToHex[arr[offset + 8]] + + byteToHex[arr[offset + 9]] + + '-' + + byteToHex[arr[offset + 10]] + + byteToHex[arr[offset + 11]] + + byteToHex[arr[offset + 12]] + + byteToHex[arr[offset + 13]] + + byteToHex[arr[offset + 14]] + + byteToHex[arr[offset + 15]]).toLowerCase(); +} +exports.unsafeStringify = unsafeStringify; +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); + if (!(0, validate_js_1.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + return uuid; +} +exports.default = stringify; diff --git a/node_modules/uuid/dist/cjs/types.d.ts b/node_modules/uuid/dist/cjs/types.d.ts new file mode 100644 index 0000000..ecaed97 --- /dev/null +++ b/node_modules/uuid/dist/cjs/types.d.ts @@ -0,0 +1,21 @@ +export type UUIDTypes = string | TBuf; +export type Version1Options = { + node?: Uint8Array; + clockseq?: number; + random?: Uint8Array; + rng?: () => Uint8Array; + msecs?: number; + nsecs?: number; + _v6?: boolean; +}; +export type Version4Options = { + random?: Uint8Array; + rng?: () => Uint8Array; +}; +export type Version6Options = Version1Options; +export type Version7Options = { + random?: Uint8Array; + msecs?: number; + seq?: number; + rng?: () => Uint8Array; +}; diff --git a/node_modules/uuid/dist/cjs/types.js b/node_modules/uuid/dist/cjs/types.js new file mode 100644 index 0000000..c8ad2e5 --- /dev/null +++ b/node_modules/uuid/dist/cjs/types.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/uuid/dist/cjs/uuid-bin.d.ts b/node_modules/uuid/dist/cjs/uuid-bin.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/uuid/dist/cjs/uuid-bin.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/uuid/dist/cjs/uuid-bin.js b/node_modules/uuid/dist/cjs/uuid-bin.js new file mode 100644 index 0000000..d613137 --- /dev/null +++ b/node_modules/uuid/dist/cjs/uuid-bin.js @@ -0,0 +1,72 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const assert = require("assert"); +const v1_js_1 = require("./v1.js"); +const v3_js_1 = require("./v3.js"); +const v4_js_1 = require("./v4.js"); +const v5_js_1 = require("./v5.js"); +const v6_js_1 = require("./v6.js"); +const v7_js_1 = require("./v7.js"); +function usage() { + console.log('Usage:'); + console.log(' uuid'); + console.log(' uuid v1'); + console.log(' uuid v3 '); + console.log(' uuid v4'); + console.log(' uuid v5 '); + console.log(' uuid v6'); + console.log(' uuid v7'); + console.log(' uuid --help'); + console.log('\nNote: may be "URL" or "DNS" to use the corresponding UUIDs defined by RFC9562'); +} +const args = process.argv.slice(2); +if (args.indexOf('--help') >= 0) { + usage(); + process.exit(0); +} +const version = args.shift() || 'v4'; +switch (version) { + case 'v1': + console.log((0, v1_js_1.default)()); + break; + case 'v3': { + const name = args.shift(); + let namespace = args.shift(); + assert.ok(name != null, 'v3 name not specified'); + assert.ok(namespace != null, 'v3 namespace not specified'); + if (namespace === 'URL') { + namespace = v3_js_1.default.URL; + } + if (namespace === 'DNS') { + namespace = v3_js_1.default.DNS; + } + console.log((0, v3_js_1.default)(name, namespace)); + break; + } + case 'v4': + console.log((0, v4_js_1.default)()); + break; + case 'v5': { + const name = args.shift(); + let namespace = args.shift(); + assert.ok(name != null, 'v5 name not specified'); + assert.ok(namespace != null, 'v5 namespace not specified'); + if (namespace === 'URL') { + namespace = v5_js_1.default.URL; + } + if (namespace === 'DNS') { + namespace = v5_js_1.default.DNS; + } + console.log((0, v5_js_1.default)(name, namespace)); + break; + } + case 'v6': + console.log((0, v6_js_1.default)()); + break; + case 'v7': + console.log((0, v7_js_1.default)()); + break; + default: + usage(); + process.exit(1); +} diff --git a/node_modules/uuid/dist/cjs/v1.d.ts b/node_modules/uuid/dist/cjs/v1.d.ts new file mode 100644 index 0000000..d8ecee0 --- /dev/null +++ b/node_modules/uuid/dist/cjs/v1.d.ts @@ -0,0 +1,11 @@ +import { Version1Options } from './types.js'; +type V1State = { + node?: Uint8Array; + clockseq?: number; + msecs?: number; + nsecs?: number; +}; +declare function v1(options?: Version1Options, buf?: undefined, offset?: number): string; +declare function v1(options: Version1Options | undefined, buf: Buf, offset?: number): Buf; +export declare function updateV1State(state: V1State, now: number, rnds: Uint8Array): V1State; +export default v1; diff --git a/node_modules/uuid/dist/cjs/v1.js b/node_modules/uuid/dist/cjs/v1.js new file mode 100644 index 0000000..155b80d --- /dev/null +++ b/node_modules/uuid/dist/cjs/v1.js @@ -0,0 +1,87 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.updateV1State = void 0; +const rng_js_1 = require("./rng.js"); +const stringify_js_1 = require("./stringify.js"); +const _state = {}; +function v1(options, buf, offset) { + let bytes; + const isV6 = options?._v6 ?? false; + if (options) { + const optionsKeys = Object.keys(options); + if (optionsKeys.length === 1 && optionsKeys[0] === '_v6') { + options = undefined; + } + } + if (options) { + bytes = v1Bytes(options.random ?? options.rng?.() ?? (0, rng_js_1.default)(), options.msecs, options.nsecs, options.clockseq, options.node, buf, offset); + } + else { + const now = Date.now(); + const rnds = (0, rng_js_1.default)(); + updateV1State(_state, now, rnds); + bytes = v1Bytes(rnds, _state.msecs, _state.nsecs, isV6 ? undefined : _state.clockseq, isV6 ? undefined : _state.node, buf, offset); + } + return buf ?? (0, stringify_js_1.unsafeStringify)(bytes); +} +function updateV1State(state, now, rnds) { + state.msecs ??= -Infinity; + state.nsecs ??= 0; + if (now === state.msecs) { + state.nsecs++; + if (state.nsecs >= 10000) { + state.node = undefined; + state.nsecs = 0; + } + } + else if (now > state.msecs) { + state.nsecs = 0; + } + else if (now < state.msecs) { + state.node = undefined; + } + if (!state.node) { + state.node = rnds.slice(10, 16); + state.node[0] |= 0x01; + state.clockseq = ((rnds[8] << 8) | rnds[9]) & 0x3fff; + } + state.msecs = now; + return state; +} +exports.updateV1State = updateV1State; +function v1Bytes(rnds, msecs, nsecs, clockseq, node, buf, offset = 0) { + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + if (!buf) { + buf = new Uint8Array(16); + offset = 0; + } + else { + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + } + msecs ??= Date.now(); + nsecs ??= 0; + clockseq ??= ((rnds[8] << 8) | rnds[9]) & 0x3fff; + node ??= rnds.slice(10, 16); + msecs += 12219292800000; + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + buf[offset++] = (tl >>> 24) & 0xff; + buf[offset++] = (tl >>> 16) & 0xff; + buf[offset++] = (tl >>> 8) & 0xff; + buf[offset++] = tl & 0xff; + const tmh = ((msecs / 0x100000000) * 10000) & 0xfffffff; + buf[offset++] = (tmh >>> 8) & 0xff; + buf[offset++] = tmh & 0xff; + buf[offset++] = ((tmh >>> 24) & 0xf) | 0x10; + buf[offset++] = (tmh >>> 16) & 0xff; + buf[offset++] = (clockseq >>> 8) | 0x80; + buf[offset++] = clockseq & 0xff; + for (let n = 0; n < 6; ++n) { + buf[offset++] = node[n]; + } + return buf; +} +exports.default = v1; diff --git a/node_modules/uuid/dist/cjs/v1ToV6.d.ts b/node_modules/uuid/dist/cjs/v1ToV6.d.ts new file mode 100644 index 0000000..38eaaf0 --- /dev/null +++ b/node_modules/uuid/dist/cjs/v1ToV6.d.ts @@ -0,0 +1,2 @@ +export default function v1ToV6(uuid: string): string; +export default function v1ToV6(uuid: Uint8Array): Uint8Array; diff --git a/node_modules/uuid/dist/cjs/v1ToV6.js b/node_modules/uuid/dist/cjs/v1ToV6.js new file mode 100644 index 0000000..daba2c3 --- /dev/null +++ b/node_modules/uuid/dist/cjs/v1ToV6.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const parse_js_1 = require("./parse.js"); +const stringify_js_1 = require("./stringify.js"); +function v1ToV6(uuid) { + const v1Bytes = typeof uuid === 'string' ? (0, parse_js_1.default)(uuid) : uuid; + const v6Bytes = _v1ToV6(v1Bytes); + return typeof uuid === 'string' ? (0, stringify_js_1.unsafeStringify)(v6Bytes) : v6Bytes; +} +exports.default = v1ToV6; +function _v1ToV6(v1Bytes) { + return Uint8Array.of(((v1Bytes[6] & 0x0f) << 4) | ((v1Bytes[7] >> 4) & 0x0f), ((v1Bytes[7] & 0x0f) << 4) | ((v1Bytes[4] & 0xf0) >> 4), ((v1Bytes[4] & 0x0f) << 4) | ((v1Bytes[5] & 0xf0) >> 4), ((v1Bytes[5] & 0x0f) << 4) | ((v1Bytes[0] & 0xf0) >> 4), ((v1Bytes[0] & 0x0f) << 4) | ((v1Bytes[1] & 0xf0) >> 4), ((v1Bytes[1] & 0x0f) << 4) | ((v1Bytes[2] & 0xf0) >> 4), 0x60 | (v1Bytes[2] & 0x0f), v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]); +} diff --git a/node_modules/uuid/dist/cjs/v3.d.ts b/node_modules/uuid/dist/cjs/v3.d.ts new file mode 100644 index 0000000..5d1c434 --- /dev/null +++ b/node_modules/uuid/dist/cjs/v3.d.ts @@ -0,0 +1,9 @@ +import { UUIDTypes } from './types.js'; +export { DNS, URL } from './v35.js'; +declare function v3(value: string | Uint8Array, namespace: UUIDTypes, buf?: undefined, offset?: number): string; +declare function v3(value: string | Uint8Array, namespace: UUIDTypes, buf: TBuf, offset?: number): TBuf; +declare namespace v3 { + var DNS: string; + var URL: string; +} +export default v3; diff --git a/node_modules/uuid/dist/cjs/v3.js b/node_modules/uuid/dist/cjs/v3.js new file mode 100644 index 0000000..d318d2a --- /dev/null +++ b/node_modules/uuid/dist/cjs/v3.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.URL = exports.DNS = void 0; +const md5_js_1 = require("./md5.js"); +const v35_js_1 = require("./v35.js"); +var v35_js_2 = require("./v35.js"); +Object.defineProperty(exports, "DNS", { enumerable: true, get: function () { return v35_js_2.DNS; } }); +Object.defineProperty(exports, "URL", { enumerable: true, get: function () { return v35_js_2.URL; } }); +function v3(value, namespace, buf, offset) { + return (0, v35_js_1.default)(0x30, md5_js_1.default, value, namespace, buf, offset); +} +v3.DNS = v35_js_1.DNS; +v3.URL = v35_js_1.URL; +exports.default = v3; diff --git a/node_modules/uuid/dist/cjs/v35.d.ts b/node_modules/uuid/dist/cjs/v35.d.ts new file mode 100644 index 0000000..4e6e9d5 --- /dev/null +++ b/node_modules/uuid/dist/cjs/v35.d.ts @@ -0,0 +1,7 @@ +import { UUIDTypes } from './types.js'; +export declare function stringToBytes(str: string): Uint8Array; +export declare const DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; +export declare const URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; +type HashFunction = (bytes: Uint8Array) => Uint8Array; +export default function v35(version: 0x30 | 0x50, hash: HashFunction, value: string | Uint8Array, namespace: UUIDTypes, buf?: TBuf, offset?: number): UUIDTypes; +export {}; diff --git a/node_modules/uuid/dist/cjs/v35.js b/node_modules/uuid/dist/cjs/v35.js new file mode 100644 index 0000000..a3712f2 --- /dev/null +++ b/node_modules/uuid/dist/cjs/v35.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.URL = exports.DNS = exports.stringToBytes = void 0; +const parse_js_1 = require("./parse.js"); +const stringify_js_1 = require("./stringify.js"); +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); + const bytes = new Uint8Array(str.length); + for (let i = 0; i < str.length; ++i) { + bytes[i] = str.charCodeAt(i); + } + return bytes; +} +exports.stringToBytes = stringToBytes; +exports.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +function v35(version, hash, value, namespace, buf, offset) { + const valueBytes = typeof value === 'string' ? stringToBytes(value) : value; + const namespaceBytes = typeof namespace === 'string' ? (0, parse_js_1.default)(namespace) : namespace; + if (typeof namespace === 'string') { + namespace = (0, parse_js_1.default)(namespace); + } + if (namespace?.length !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } + let bytes = new Uint8Array(16 + valueBytes.length); + bytes.set(namespaceBytes); + bytes.set(valueBytes, namespaceBytes.length); + bytes = hash(bytes); + bytes[6] = (bytes[6] & 0x0f) | version; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + if (buf) { + offset = offset || 0; + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + return buf; + } + return (0, stringify_js_1.unsafeStringify)(bytes); +} +exports.default = v35; diff --git a/node_modules/uuid/dist/cjs/v4.d.ts b/node_modules/uuid/dist/cjs/v4.d.ts new file mode 100644 index 0000000..8205333 --- /dev/null +++ b/node_modules/uuid/dist/cjs/v4.d.ts @@ -0,0 +1,4 @@ +import { Version4Options } from './types.js'; +declare function v4(options?: Version4Options, buf?: undefined, offset?: number): string; +declare function v4(options: Version4Options | undefined, buf: TBuf, offset?: number): TBuf; +export default v4; diff --git a/node_modules/uuid/dist/cjs/v4.js b/node_modules/uuid/dist/cjs/v4.js new file mode 100644 index 0000000..69c975e --- /dev/null +++ b/node_modules/uuid/dist/cjs/v4.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const native_js_1 = require("./native.js"); +const rng_js_1 = require("./rng.js"); +const stringify_js_1 = require("./stringify.js"); +function v4(options, buf, offset) { + if (native_js_1.default.randomUUID && !buf && !options) { + return native_js_1.default.randomUUID(); + } + options = options || {}; + const rnds = options.random ?? options.rng?.() ?? (0, rng_js_1.default)(); + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; + if (buf) { + offset = offset || 0; + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + return buf; + } + return (0, stringify_js_1.unsafeStringify)(rnds); +} +exports.default = v4; diff --git a/node_modules/uuid/dist/cjs/v5.d.ts b/node_modules/uuid/dist/cjs/v5.d.ts new file mode 100644 index 0000000..0e2ff2f --- /dev/null +++ b/node_modules/uuid/dist/cjs/v5.d.ts @@ -0,0 +1,9 @@ +import { UUIDTypes } from './types.js'; +export { DNS, URL } from './v35.js'; +declare function v5(value: string | Uint8Array, namespace: UUIDTypes, buf?: undefined, offset?: number): string; +declare function v5(value: string | Uint8Array, namespace: UUIDTypes, buf: TBuf, offset?: number): TBuf; +declare namespace v5 { + var DNS: string; + var URL: string; +} +export default v5; diff --git a/node_modules/uuid/dist/cjs/v5.js b/node_modules/uuid/dist/cjs/v5.js new file mode 100644 index 0000000..c4239c2 --- /dev/null +++ b/node_modules/uuid/dist/cjs/v5.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.URL = exports.DNS = void 0; +const sha1_js_1 = require("./sha1.js"); +const v35_js_1 = require("./v35.js"); +var v35_js_2 = require("./v35.js"); +Object.defineProperty(exports, "DNS", { enumerable: true, get: function () { return v35_js_2.DNS; } }); +Object.defineProperty(exports, "URL", { enumerable: true, get: function () { return v35_js_2.URL; } }); +function v5(value, namespace, buf, offset) { + return (0, v35_js_1.default)(0x50, sha1_js_1.default, value, namespace, buf, offset); +} +v5.DNS = v35_js_1.DNS; +v5.URL = v35_js_1.URL; +exports.default = v5; diff --git a/node_modules/uuid/dist/cjs/v6.d.ts b/node_modules/uuid/dist/cjs/v6.d.ts new file mode 100644 index 0000000..cabf4a0 --- /dev/null +++ b/node_modules/uuid/dist/cjs/v6.d.ts @@ -0,0 +1,4 @@ +import { Version6Options } from './types.js'; +declare function v6(options?: Version6Options, buf?: undefined, offset?: number): string; +declare function v6(options: Version6Options | undefined, buf: TBuf, offset?: number): TBuf; +export default v6; diff --git a/node_modules/uuid/dist/cjs/v6.js b/node_modules/uuid/dist/cjs/v6.js new file mode 100644 index 0000000..b02748d --- /dev/null +++ b/node_modules/uuid/dist/cjs/v6.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const stringify_js_1 = require("./stringify.js"); +const v1_js_1 = require("./v1.js"); +const v1ToV6_js_1 = require("./v1ToV6.js"); +function v6(options, buf, offset) { + options ??= {}; + offset ??= 0; + let bytes = (0, v1_js_1.default)({ ...options, _v6: true }, new Uint8Array(16)); + bytes = (0, v1ToV6_js_1.default)(bytes); + if (buf) { + for (let i = 0; i < 16; i++) { + buf[offset + i] = bytes[i]; + } + return buf; + } + return (0, stringify_js_1.unsafeStringify)(bytes); +} +exports.default = v6; diff --git a/node_modules/uuid/dist/cjs/v6ToV1.d.ts b/node_modules/uuid/dist/cjs/v6ToV1.d.ts new file mode 100644 index 0000000..3b3ffc2 --- /dev/null +++ b/node_modules/uuid/dist/cjs/v6ToV1.d.ts @@ -0,0 +1,2 @@ +export default function v6ToV1(uuid: string): string; +export default function v6ToV1(uuid: Uint8Array): Uint8Array; diff --git a/node_modules/uuid/dist/cjs/v6ToV1.js b/node_modules/uuid/dist/cjs/v6ToV1.js new file mode 100644 index 0000000..9dcb661 --- /dev/null +++ b/node_modules/uuid/dist/cjs/v6ToV1.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const parse_js_1 = require("./parse.js"); +const stringify_js_1 = require("./stringify.js"); +function v6ToV1(uuid) { + const v6Bytes = typeof uuid === 'string' ? (0, parse_js_1.default)(uuid) : uuid; + const v1Bytes = _v6ToV1(v6Bytes); + return typeof uuid === 'string' ? (0, stringify_js_1.unsafeStringify)(v1Bytes) : v1Bytes; +} +exports.default = v6ToV1; +function _v6ToV1(v6Bytes) { + return Uint8Array.of(((v6Bytes[3] & 0x0f) << 4) | ((v6Bytes[4] >> 4) & 0x0f), ((v6Bytes[4] & 0x0f) << 4) | ((v6Bytes[5] & 0xf0) >> 4), ((v6Bytes[5] & 0x0f) << 4) | (v6Bytes[6] & 0x0f), v6Bytes[7], ((v6Bytes[1] & 0x0f) << 4) | ((v6Bytes[2] & 0xf0) >> 4), ((v6Bytes[2] & 0x0f) << 4) | ((v6Bytes[3] & 0xf0) >> 4), 0x10 | ((v6Bytes[0] & 0xf0) >> 4), ((v6Bytes[0] & 0x0f) << 4) | ((v6Bytes[1] & 0xf0) >> 4), v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]); +} diff --git a/node_modules/uuid/dist/cjs/v7.d.ts b/node_modules/uuid/dist/cjs/v7.d.ts new file mode 100644 index 0000000..f49b03d --- /dev/null +++ b/node_modules/uuid/dist/cjs/v7.d.ts @@ -0,0 +1,9 @@ +import { Version7Options } from './types.js'; +type V7State = { + msecs?: number; + seq?: number; +}; +declare function v7(options?: Version7Options, buf?: undefined, offset?: number): string; +declare function v7(options: Version7Options | undefined, buf: TBuf, offset?: number): TBuf; +export declare function updateV7State(state: V7State, now: number, rnds: Uint8Array): V7State; +export default v7; diff --git a/node_modules/uuid/dist/cjs/v7.js b/node_modules/uuid/dist/cjs/v7.js new file mode 100644 index 0000000..697fe34 --- /dev/null +++ b/node_modules/uuid/dist/cjs/v7.js @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.updateV7State = void 0; +const rng_js_1 = require("./rng.js"); +const stringify_js_1 = require("./stringify.js"); +const _state = {}; +function v7(options, buf, offset) { + let bytes; + if (options) { + bytes = v7Bytes(options.random ?? options.rng?.() ?? (0, rng_js_1.default)(), options.msecs, options.seq, buf, offset); + } + else { + const now = Date.now(); + const rnds = (0, rng_js_1.default)(); + updateV7State(_state, now, rnds); + bytes = v7Bytes(rnds, _state.msecs, _state.seq, buf, offset); + } + return buf ?? (0, stringify_js_1.unsafeStringify)(bytes); +} +function updateV7State(state, now, rnds) { + state.msecs ??= -Infinity; + state.seq ??= 0; + if (now > state.msecs) { + state.seq = (rnds[6] << 23) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9]; + state.msecs = now; + } + else { + state.seq = (state.seq + 1) | 0; + if (state.seq === 0) { + state.msecs++; + } + } + return state; +} +exports.updateV7State = updateV7State; +function v7Bytes(rnds, msecs, seq, buf, offset = 0) { + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + if (!buf) { + buf = new Uint8Array(16); + offset = 0; + } + else { + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + } + msecs ??= Date.now(); + seq ??= ((rnds[6] * 0x7f) << 24) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9]; + buf[offset++] = (msecs / 0x10000000000) & 0xff; + buf[offset++] = (msecs / 0x100000000) & 0xff; + buf[offset++] = (msecs / 0x1000000) & 0xff; + buf[offset++] = (msecs / 0x10000) & 0xff; + buf[offset++] = (msecs / 0x100) & 0xff; + buf[offset++] = msecs & 0xff; + buf[offset++] = 0x70 | ((seq >>> 28) & 0x0f); + buf[offset++] = (seq >>> 20) & 0xff; + buf[offset++] = 0x80 | ((seq >>> 14) & 0x3f); + buf[offset++] = (seq >>> 6) & 0xff; + buf[offset++] = ((seq << 2) & 0xff) | (rnds[10] & 0x03); + buf[offset++] = rnds[11]; + buf[offset++] = rnds[12]; + buf[offset++] = rnds[13]; + buf[offset++] = rnds[14]; + buf[offset++] = rnds[15]; + return buf; +} +exports.default = v7; diff --git a/node_modules/uuid/dist/cjs/validate.d.ts b/node_modules/uuid/dist/cjs/validate.d.ts new file mode 100644 index 0000000..57da03d --- /dev/null +++ b/node_modules/uuid/dist/cjs/validate.d.ts @@ -0,0 +1,2 @@ +declare function validate(uuid: unknown): boolean; +export default validate; diff --git a/node_modules/uuid/dist/cjs/validate.js b/node_modules/uuid/dist/cjs/validate.js new file mode 100644 index 0000000..89733b0 --- /dev/null +++ b/node_modules/uuid/dist/cjs/validate.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const regex_js_1 = require("./regex.js"); +function validate(uuid) { + return typeof uuid === 'string' && regex_js_1.default.test(uuid); +} +exports.default = validate; diff --git a/node_modules/uuid/dist/cjs/version.d.ts b/node_modules/uuid/dist/cjs/version.d.ts new file mode 100644 index 0000000..f1948dc --- /dev/null +++ b/node_modules/uuid/dist/cjs/version.d.ts @@ -0,0 +1,2 @@ +declare function version(uuid: string): number; +export default version; diff --git a/node_modules/uuid/dist/cjs/version.js b/node_modules/uuid/dist/cjs/version.js new file mode 100644 index 0000000..05ecd00 --- /dev/null +++ b/node_modules/uuid/dist/cjs/version.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const validate_js_1 = require("./validate.js"); +function version(uuid) { + if (!(0, validate_js_1.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + return parseInt(uuid.slice(14, 15), 16); +} +exports.default = version; diff --git a/node_modules/uuid/dist/esm-browser/index.d.ts b/node_modules/uuid/dist/esm-browser/index.d.ts new file mode 100644 index 0000000..d7d4edc --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/index.d.ts @@ -0,0 +1,15 @@ +export type * from './types.js'; +export { default as MAX } from './max.js'; +export { default as NIL } from './nil.js'; +export { default as parse } from './parse.js'; +export { default as stringify } from './stringify.js'; +export { default as v1 } from './v1.js'; +export { default as v1ToV6 } from './v1ToV6.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as v6 } from './v6.js'; +export { default as v6ToV1 } from './v6ToV1.js'; +export { default as v7 } from './v7.js'; +export { default as validate } from './validate.js'; +export { default as version } from './version.js'; diff --git a/node_modules/uuid/dist/esm-browser/index.js b/node_modules/uuid/dist/esm-browser/index.js new file mode 100644 index 0000000..3193e9a --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/index.js @@ -0,0 +1,14 @@ +export { default as MAX } from './max.js'; +export { default as NIL } from './nil.js'; +export { default as parse } from './parse.js'; +export { default as stringify } from './stringify.js'; +export { default as v1 } from './v1.js'; +export { default as v1ToV6 } from './v1ToV6.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as v6 } from './v6.js'; +export { default as v6ToV1 } from './v6ToV1.js'; +export { default as v7 } from './v7.js'; +export { default as validate } from './validate.js'; +export { default as version } from './version.js'; diff --git a/node_modules/uuid/dist/esm-browser/max.d.ts b/node_modules/uuid/dist/esm-browser/max.d.ts new file mode 100644 index 0000000..7a1e972 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/max.d.ts @@ -0,0 +1,2 @@ +declare const _default: "ffffffff-ffff-ffff-ffff-ffffffffffff"; +export default _default; diff --git a/node_modules/uuid/dist/esm-browser/max.js b/node_modules/uuid/dist/esm-browser/max.js new file mode 100644 index 0000000..58951f6 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/max.js @@ -0,0 +1 @@ +export default 'ffffffff-ffff-ffff-ffff-ffffffffffff'; diff --git a/node_modules/uuid/dist/esm-browser/md5.d.ts b/node_modules/uuid/dist/esm-browser/md5.d.ts new file mode 100644 index 0000000..5a55f51 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/md5.d.ts @@ -0,0 +1,2 @@ +declare function md5(bytes: Uint8Array): Uint8Array; +export default md5; diff --git a/node_modules/uuid/dist/esm-browser/md5.js b/node_modules/uuid/dist/esm-browser/md5.js new file mode 100644 index 0000000..918be8c --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/md5.js @@ -0,0 +1,135 @@ +function md5(bytes) { + const words = uint8ToUint32(bytes); + const md5Bytes = wordsToMd5(words, bytes.length * 8); + return uint32ToUint8(md5Bytes); +} +function uint32ToUint8(input) { + const bytes = new Uint8Array(input.length * 4); + for (let i = 0; i < input.length * 4; i++) { + bytes[i] = (input[i >> 2] >>> ((i % 4) * 8)) & 0xff; + } + return bytes; +} +function getOutputLength(inputLength8) { + return (((inputLength8 + 64) >>> 9) << 4) + 14 + 1; +} +function wordsToMd5(x, len) { + const xpad = new Uint32Array(getOutputLength(len)).fill(0); + xpad.set(x); + xpad[len >> 5] |= 0x80 << len % 32; + xpad[xpad.length - 1] = len; + x = xpad; + let a = 1732584193; + let b = -271733879; + let c = -1732584194; + let d = 271733878; + for (let i = 0; i < x.length; i += 16) { + const olda = a; + const oldb = b; + const oldc = c; + const oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + return Uint32Array.of(a, b, c, d); +} +function uint8ToUint32(input) { + if (input.length === 0) { + return new Uint32Array(); + } + const output = new Uint32Array(getOutputLength(input.length * 8)).fill(0); + for (let i = 0; i < input.length; i++) { + output[i >> 2] |= (input[i] & 0xff) << ((i % 4) * 8); + } + return output; +} +function safeAdd(x, y) { + const lsw = (x & 0xffff) + (y & 0xffff); + const msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xffff); +} +function bitRotateLeft(num, cnt) { + return (num << cnt) | (num >>> (32 - cnt)); +} +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} +function md5ff(a, b, c, d, x, s, t) { + return md5cmn((b & c) | (~b & d), a, b, x, s, t); +} +function md5gg(a, b, c, d, x, s, t) { + return md5cmn((b & d) | (c & ~d), a, b, x, s, t); +} +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} +export default md5; diff --git a/node_modules/uuid/dist/esm-browser/native.d.ts b/node_modules/uuid/dist/esm-browser/native.d.ts new file mode 100644 index 0000000..9418fd3 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/native.d.ts @@ -0,0 +1,4 @@ +declare const _default: { + randomUUID: false | (() => `${string}-${string}-${string}-${string}-${string}`); +}; +export default _default; diff --git a/node_modules/uuid/dist/esm-browser/native.js b/node_modules/uuid/dist/esm-browser/native.js new file mode 100644 index 0000000..76f44f9 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/native.js @@ -0,0 +1,2 @@ +const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); +export default { randomUUID }; diff --git a/node_modules/uuid/dist/esm-browser/nil.d.ts b/node_modules/uuid/dist/esm-browser/nil.d.ts new file mode 100644 index 0000000..b03bb98 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/nil.d.ts @@ -0,0 +1,2 @@ +declare const _default: "00000000-0000-0000-0000-000000000000"; +export default _default; diff --git a/node_modules/uuid/dist/esm-browser/nil.js b/node_modules/uuid/dist/esm-browser/nil.js new file mode 100644 index 0000000..de6f830 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/nil.js @@ -0,0 +1 @@ +export default '00000000-0000-0000-0000-000000000000'; diff --git a/node_modules/uuid/dist/esm-browser/parse.d.ts b/node_modules/uuid/dist/esm-browser/parse.d.ts new file mode 100644 index 0000000..a316fb1 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/parse.d.ts @@ -0,0 +1,2 @@ +declare function parse(uuid: string): Uint8Array; +export default parse; diff --git a/node_modules/uuid/dist/esm-browser/parse.js b/node_modules/uuid/dist/esm-browser/parse.js new file mode 100644 index 0000000..64ac401 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/parse.js @@ -0,0 +1,9 @@ +import validate from './validate.js'; +function parse(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + let v; + return Uint8Array.of((v = parseInt(uuid.slice(0, 8), 16)) >>> 24, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff, (v = parseInt(uuid.slice(9, 13), 16)) >>> 8, v & 0xff, (v = parseInt(uuid.slice(14, 18), 16)) >>> 8, v & 0xff, (v = parseInt(uuid.slice(19, 23), 16)) >>> 8, v & 0xff, ((v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000) & 0xff, (v / 0x100000000) & 0xff, (v >>> 24) & 0xff, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff); +} +export default parse; diff --git a/node_modules/uuid/dist/esm-browser/regex.d.ts b/node_modules/uuid/dist/esm-browser/regex.d.ts new file mode 100644 index 0000000..d39fa3f --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/regex.d.ts @@ -0,0 +1,2 @@ +declare const _default: RegExp; +export default _default; diff --git a/node_modules/uuid/dist/esm-browser/regex.js b/node_modules/uuid/dist/esm-browser/regex.js new file mode 100644 index 0000000..3e38591 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/regex.js @@ -0,0 +1 @@ +export 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; diff --git a/node_modules/uuid/dist/esm-browser/rng.d.ts b/node_modules/uuid/dist/esm-browser/rng.d.ts new file mode 100644 index 0000000..73e60cf --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/rng.d.ts @@ -0,0 +1 @@ +export default function rng(): Uint8Array; diff --git a/node_modules/uuid/dist/esm-browser/rng.js b/node_modules/uuid/dist/esm-browser/rng.js new file mode 100644 index 0000000..770f2e2 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/rng.js @@ -0,0 +1,11 @@ +let getRandomValues; +const rnds8 = new Uint8Array(16); +export default function rng() { + if (!getRandomValues) { + if (typeof crypto === 'undefined' || !crypto.getRandomValues) { + throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); + } + getRandomValues = crypto.getRandomValues.bind(crypto); + } + return getRandomValues(rnds8); +} diff --git a/node_modules/uuid/dist/esm-browser/sha1.d.ts b/node_modules/uuid/dist/esm-browser/sha1.d.ts new file mode 100644 index 0000000..a6552e5 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/sha1.d.ts @@ -0,0 +1,2 @@ +declare function sha1(bytes: Uint8Array): Uint8Array; +export default sha1; diff --git a/node_modules/uuid/dist/esm-browser/sha1.js b/node_modules/uuid/dist/esm-browser/sha1.js new file mode 100644 index 0000000..dbb78ae --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/sha1.js @@ -0,0 +1,70 @@ +function f(s, x, y, z) { + switch (s) { + case 0: + return (x & y) ^ (~x & z); + case 1: + return x ^ y ^ z; + case 2: + return (x & y) ^ (x & z) ^ (y & z); + case 3: + return x ^ y ^ z; + } +} +function ROTL(x, n) { + return (x << n) | (x >>> (32 - n)); +} +function sha1(bytes) { + const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + const newBytes = new Uint8Array(bytes.length + 1); + newBytes.set(bytes); + newBytes[bytes.length] = 0x80; + bytes = newBytes; + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + for (let i = 0; i < N; ++i) { + const arr = new Uint32Array(16); + for (let j = 0; j < 16; ++j) { + arr[j] = + (bytes[i * 64 + j * 4] << 24) | + (bytes[i * 64 + j * 4 + 1] << 16) | + (bytes[i * 64 + j * 4 + 2] << 8) | + bytes[i * 64 + j * 4 + 3]; + } + M[i] = arr; + } + M[N - 1][14] = ((bytes.length - 1) * 8) / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = ((bytes.length - 1) * 8) & 0xffffffff; + for (let i = 0; i < N; ++i) { + const W = new Uint32Array(80); + for (let t = 0; t < 16; ++t) { + W[t] = M[i][t]; + } + for (let t = 16; t < 80; ++t) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = (ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t]) >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + H[0] = (H[0] + a) >>> 0; + H[1] = (H[1] + b) >>> 0; + H[2] = (H[2] + c) >>> 0; + H[3] = (H[3] + d) >>> 0; + H[4] = (H[4] + e) >>> 0; + } + return Uint8Array.of(H[0] >> 24, H[0] >> 16, H[0] >> 8, H[0], H[1] >> 24, H[1] >> 16, H[1] >> 8, H[1], H[2] >> 24, H[2] >> 16, H[2] >> 8, H[2], H[3] >> 24, H[3] >> 16, H[3] >> 8, H[3], H[4] >> 24, H[4] >> 16, H[4] >> 8, H[4]); +} +export default sha1; diff --git a/node_modules/uuid/dist/esm-browser/stringify.d.ts b/node_modules/uuid/dist/esm-browser/stringify.d.ts new file mode 100644 index 0000000..16cb008 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/stringify.d.ts @@ -0,0 +1,3 @@ +export declare function unsafeStringify(arr: Uint8Array, offset?: number): string; +declare function stringify(arr: Uint8Array, offset?: number): string; +export default stringify; diff --git a/node_modules/uuid/dist/esm-browser/stringify.js b/node_modules/uuid/dist/esm-browser/stringify.js new file mode 100644 index 0000000..962738c --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/stringify.js @@ -0,0 +1,35 @@ +import validate from './validate.js'; +const byteToHex = []; +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} +export function unsafeStringify(arr, offset = 0) { + return (byteToHex[arr[offset + 0]] + + byteToHex[arr[offset + 1]] + + byteToHex[arr[offset + 2]] + + byteToHex[arr[offset + 3]] + + '-' + + byteToHex[arr[offset + 4]] + + byteToHex[arr[offset + 5]] + + '-' + + byteToHex[arr[offset + 6]] + + byteToHex[arr[offset + 7]] + + '-' + + byteToHex[arr[offset + 8]] + + byteToHex[arr[offset + 9]] + + '-' + + byteToHex[arr[offset + 10]] + + byteToHex[arr[offset + 11]] + + byteToHex[arr[offset + 12]] + + byteToHex[arr[offset + 13]] + + byteToHex[arr[offset + 14]] + + byteToHex[arr[offset + 15]]).toLowerCase(); +} +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); + if (!validate(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + return uuid; +} +export default stringify; diff --git a/node_modules/uuid/dist/esm-browser/types.d.ts b/node_modules/uuid/dist/esm-browser/types.d.ts new file mode 100644 index 0000000..ecaed97 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/types.d.ts @@ -0,0 +1,21 @@ +export type UUIDTypes = string | TBuf; +export type Version1Options = { + node?: Uint8Array; + clockseq?: number; + random?: Uint8Array; + rng?: () => Uint8Array; + msecs?: number; + nsecs?: number; + _v6?: boolean; +}; +export type Version4Options = { + random?: Uint8Array; + rng?: () => Uint8Array; +}; +export type Version6Options = Version1Options; +export type Version7Options = { + random?: Uint8Array; + msecs?: number; + seq?: number; + rng?: () => Uint8Array; +}; diff --git a/node_modules/uuid/dist/esm-browser/types.js b/node_modules/uuid/dist/esm-browser/types.js new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/types.js @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/uuid/dist/esm-browser/uuid-bin.d.ts b/node_modules/uuid/dist/esm-browser/uuid-bin.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/uuid-bin.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/uuid/dist/esm-browser/uuid-bin.js b/node_modules/uuid/dist/esm-browser/uuid-bin.js new file mode 100644 index 0000000..30766fe --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/uuid-bin.js @@ -0,0 +1,70 @@ +import * as assert from 'assert'; +import v1 from './v1.js'; +import v3 from './v3.js'; +import v4 from './v4.js'; +import v5 from './v5.js'; +import v6 from './v6.js'; +import v7 from './v7.js'; +function usage() { + console.log('Usage:'); + console.log(' uuid'); + console.log(' uuid v1'); + console.log(' uuid v3 '); + console.log(' uuid v4'); + console.log(' uuid v5 '); + console.log(' uuid v6'); + console.log(' uuid v7'); + console.log(' uuid --help'); + console.log('\nNote: may be "URL" or "DNS" to use the corresponding UUIDs defined by RFC9562'); +} +const args = process.argv.slice(2); +if (args.indexOf('--help') >= 0) { + usage(); + process.exit(0); +} +const version = args.shift() || 'v4'; +switch (version) { + case 'v1': + console.log(v1()); + break; + case 'v3': { + const name = args.shift(); + let namespace = args.shift(); + assert.ok(name != null, 'v3 name not specified'); + assert.ok(namespace != null, 'v3 namespace not specified'); + if (namespace === 'URL') { + namespace = v3.URL; + } + if (namespace === 'DNS') { + namespace = v3.DNS; + } + console.log(v3(name, namespace)); + break; + } + case 'v4': + console.log(v4()); + break; + case 'v5': { + const name = args.shift(); + let namespace = args.shift(); + assert.ok(name != null, 'v5 name not specified'); + assert.ok(namespace != null, 'v5 namespace not specified'); + if (namespace === 'URL') { + namespace = v5.URL; + } + if (namespace === 'DNS') { + namespace = v5.DNS; + } + console.log(v5(name, namespace)); + break; + } + case 'v6': + console.log(v6()); + break; + case 'v7': + console.log(v7()); + break; + default: + usage(); + process.exit(1); +} diff --git a/node_modules/uuid/dist/esm-browser/v1.d.ts b/node_modules/uuid/dist/esm-browser/v1.d.ts new file mode 100644 index 0000000..d8ecee0 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v1.d.ts @@ -0,0 +1,11 @@ +import { Version1Options } from './types.js'; +type V1State = { + node?: Uint8Array; + clockseq?: number; + msecs?: number; + nsecs?: number; +}; +declare function v1(options?: Version1Options, buf?: undefined, offset?: number): string; +declare function v1(options: Version1Options | undefined, buf: Buf, offset?: number): Buf; +export declare function updateV1State(state: V1State, now: number, rnds: Uint8Array): V1State; +export default v1; diff --git a/node_modules/uuid/dist/esm-browser/v1.js b/node_modules/uuid/dist/esm-browser/v1.js new file mode 100644 index 0000000..65e3f68 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v1.js @@ -0,0 +1,83 @@ +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; +const _state = {}; +function v1(options, buf, offset) { + let bytes; + const isV6 = options?._v6 ?? false; + if (options) { + const optionsKeys = Object.keys(options); + if (optionsKeys.length === 1 && optionsKeys[0] === '_v6') { + options = undefined; + } + } + if (options) { + bytes = v1Bytes(options.random ?? options.rng?.() ?? rng(), options.msecs, options.nsecs, options.clockseq, options.node, buf, offset); + } + else { + const now = Date.now(); + const rnds = rng(); + updateV1State(_state, now, rnds); + bytes = v1Bytes(rnds, _state.msecs, _state.nsecs, isV6 ? undefined : _state.clockseq, isV6 ? undefined : _state.node, buf, offset); + } + return buf ?? unsafeStringify(bytes); +} +export function updateV1State(state, now, rnds) { + state.msecs ??= -Infinity; + state.nsecs ??= 0; + if (now === state.msecs) { + state.nsecs++; + if (state.nsecs >= 10000) { + state.node = undefined; + state.nsecs = 0; + } + } + else if (now > state.msecs) { + state.nsecs = 0; + } + else if (now < state.msecs) { + state.node = undefined; + } + if (!state.node) { + state.node = rnds.slice(10, 16); + state.node[0] |= 0x01; + state.clockseq = ((rnds[8] << 8) | rnds[9]) & 0x3fff; + } + state.msecs = now; + return state; +} +function v1Bytes(rnds, msecs, nsecs, clockseq, node, buf, offset = 0) { + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + if (!buf) { + buf = new Uint8Array(16); + offset = 0; + } + else { + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + } + msecs ??= Date.now(); + nsecs ??= 0; + clockseq ??= ((rnds[8] << 8) | rnds[9]) & 0x3fff; + node ??= rnds.slice(10, 16); + msecs += 12219292800000; + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + buf[offset++] = (tl >>> 24) & 0xff; + buf[offset++] = (tl >>> 16) & 0xff; + buf[offset++] = (tl >>> 8) & 0xff; + buf[offset++] = tl & 0xff; + const tmh = ((msecs / 0x100000000) * 10000) & 0xfffffff; + buf[offset++] = (tmh >>> 8) & 0xff; + buf[offset++] = tmh & 0xff; + buf[offset++] = ((tmh >>> 24) & 0xf) | 0x10; + buf[offset++] = (tmh >>> 16) & 0xff; + buf[offset++] = (clockseq >>> 8) | 0x80; + buf[offset++] = clockseq & 0xff; + for (let n = 0; n < 6; ++n) { + buf[offset++] = node[n]; + } + return buf; +} +export default v1; diff --git a/node_modules/uuid/dist/esm-browser/v1ToV6.d.ts b/node_modules/uuid/dist/esm-browser/v1ToV6.d.ts new file mode 100644 index 0000000..38eaaf0 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v1ToV6.d.ts @@ -0,0 +1,2 @@ +export default function v1ToV6(uuid: string): string; +export default function v1ToV6(uuid: Uint8Array): Uint8Array; diff --git a/node_modules/uuid/dist/esm-browser/v1ToV6.js b/node_modules/uuid/dist/esm-browser/v1ToV6.js new file mode 100644 index 0000000..da0f763 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v1ToV6.js @@ -0,0 +1,10 @@ +import parse from './parse.js'; +import { unsafeStringify } from './stringify.js'; +export default function v1ToV6(uuid) { + const v1Bytes = typeof uuid === 'string' ? parse(uuid) : uuid; + const v6Bytes = _v1ToV6(v1Bytes); + return typeof uuid === 'string' ? unsafeStringify(v6Bytes) : v6Bytes; +} +function _v1ToV6(v1Bytes) { + return Uint8Array.of(((v1Bytes[6] & 0x0f) << 4) | ((v1Bytes[7] >> 4) & 0x0f), ((v1Bytes[7] & 0x0f) << 4) | ((v1Bytes[4] & 0xf0) >> 4), ((v1Bytes[4] & 0x0f) << 4) | ((v1Bytes[5] & 0xf0) >> 4), ((v1Bytes[5] & 0x0f) << 4) | ((v1Bytes[0] & 0xf0) >> 4), ((v1Bytes[0] & 0x0f) << 4) | ((v1Bytes[1] & 0xf0) >> 4), ((v1Bytes[1] & 0x0f) << 4) | ((v1Bytes[2] & 0xf0) >> 4), 0x60 | (v1Bytes[2] & 0x0f), v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]); +} diff --git a/node_modules/uuid/dist/esm-browser/v3.d.ts b/node_modules/uuid/dist/esm-browser/v3.d.ts new file mode 100644 index 0000000..5d1c434 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v3.d.ts @@ -0,0 +1,9 @@ +import { UUIDTypes } from './types.js'; +export { DNS, URL } from './v35.js'; +declare function v3(value: string | Uint8Array, namespace: UUIDTypes, buf?: undefined, offset?: number): string; +declare function v3(value: string | Uint8Array, namespace: UUIDTypes, buf: TBuf, offset?: number): TBuf; +declare namespace v3 { + var DNS: string; + var URL: string; +} +export default v3; diff --git a/node_modules/uuid/dist/esm-browser/v3.js b/node_modules/uuid/dist/esm-browser/v3.js new file mode 100644 index 0000000..b5c3781 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v3.js @@ -0,0 +1,9 @@ +import md5 from './md5.js'; +import v35, { DNS, URL } from './v35.js'; +export { DNS, URL } from './v35.js'; +function v3(value, namespace, buf, offset) { + return v35(0x30, md5, value, namespace, buf, offset); +} +v3.DNS = DNS; +v3.URL = URL; +export default v3; diff --git a/node_modules/uuid/dist/esm-browser/v35.d.ts b/node_modules/uuid/dist/esm-browser/v35.d.ts new file mode 100644 index 0000000..4e6e9d5 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v35.d.ts @@ -0,0 +1,7 @@ +import { UUIDTypes } from './types.js'; +export declare function stringToBytes(str: string): Uint8Array; +export declare const DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; +export declare const URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; +type HashFunction = (bytes: Uint8Array) => Uint8Array; +export default function v35(version: 0x30 | 0x50, hash: HashFunction, value: string | Uint8Array, namespace: UUIDTypes, buf?: TBuf, offset?: number): UUIDTypes; +export {}; diff --git a/node_modules/uuid/dist/esm-browser/v35.js b/node_modules/uuid/dist/esm-browser/v35.js new file mode 100644 index 0000000..3fe6573 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v35.js @@ -0,0 +1,36 @@ +import parse from './parse.js'; +import { unsafeStringify } from './stringify.js'; +export function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); + const bytes = new Uint8Array(str.length); + for (let i = 0; i < str.length; ++i) { + bytes[i] = str.charCodeAt(i); + } + return bytes; +} +export const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +export const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +export default function v35(version, hash, value, namespace, buf, offset) { + const valueBytes = typeof value === 'string' ? stringToBytes(value) : value; + const namespaceBytes = typeof namespace === 'string' ? parse(namespace) : namespace; + if (typeof namespace === 'string') { + namespace = parse(namespace); + } + if (namespace?.length !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } + let bytes = new Uint8Array(16 + valueBytes.length); + bytes.set(namespaceBytes); + bytes.set(valueBytes, namespaceBytes.length); + bytes = hash(bytes); + bytes[6] = (bytes[6] & 0x0f) | version; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + if (buf) { + offset = offset || 0; + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + return buf; + } + return unsafeStringify(bytes); +} diff --git a/node_modules/uuid/dist/esm-browser/v4.d.ts b/node_modules/uuid/dist/esm-browser/v4.d.ts new file mode 100644 index 0000000..8205333 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v4.d.ts @@ -0,0 +1,4 @@ +import { Version4Options } from './types.js'; +declare function v4(options?: Version4Options, buf?: undefined, offset?: number): string; +declare function v4(options: Version4Options | undefined, buf: TBuf, offset?: number): TBuf; +export default v4; diff --git a/node_modules/uuid/dist/esm-browser/v4.js b/node_modules/uuid/dist/esm-browser/v4.js new file mode 100644 index 0000000..dd9067a --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v4.js @@ -0,0 +1,27 @@ +import native from './native.js'; +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; +function v4(options, buf, offset) { + if (native.randomUUID && !buf && !options) { + return native.randomUUID(); + } + options = options || {}; + const rnds = options.random ?? options.rng?.() ?? rng(); + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; + if (buf) { + offset = offset || 0; + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + return buf; + } + return unsafeStringify(rnds); +} +export default v4; diff --git a/node_modules/uuid/dist/esm-browser/v5.d.ts b/node_modules/uuid/dist/esm-browser/v5.d.ts new file mode 100644 index 0000000..0e2ff2f --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v5.d.ts @@ -0,0 +1,9 @@ +import { UUIDTypes } from './types.js'; +export { DNS, URL } from './v35.js'; +declare function v5(value: string | Uint8Array, namespace: UUIDTypes, buf?: undefined, offset?: number): string; +declare function v5(value: string | Uint8Array, namespace: UUIDTypes, buf: TBuf, offset?: number): TBuf; +declare namespace v5 { + var DNS: string; + var URL: string; +} +export default v5; diff --git a/node_modules/uuid/dist/esm-browser/v5.js b/node_modules/uuid/dist/esm-browser/v5.js new file mode 100644 index 0000000..bd470a4 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v5.js @@ -0,0 +1,9 @@ +import sha1 from './sha1.js'; +import v35, { DNS, URL } from './v35.js'; +export { DNS, URL } from './v35.js'; +function v5(value, namespace, buf, offset) { + return v35(0x50, sha1, value, namespace, buf, offset); +} +v5.DNS = DNS; +v5.URL = URL; +export default v5; diff --git a/node_modules/uuid/dist/esm-browser/v6.d.ts b/node_modules/uuid/dist/esm-browser/v6.d.ts new file mode 100644 index 0000000..cabf4a0 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v6.d.ts @@ -0,0 +1,4 @@ +import { Version6Options } from './types.js'; +declare function v6(options?: Version6Options, buf?: undefined, offset?: number): string; +declare function v6(options: Version6Options | undefined, buf: TBuf, offset?: number): TBuf; +export default v6; diff --git a/node_modules/uuid/dist/esm-browser/v6.js b/node_modules/uuid/dist/esm-browser/v6.js new file mode 100644 index 0000000..278a339 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v6.js @@ -0,0 +1,17 @@ +import { unsafeStringify } from './stringify.js'; +import v1 from './v1.js'; +import v1ToV6 from './v1ToV6.js'; +function v6(options, buf, offset) { + options ??= {}; + offset ??= 0; + let bytes = v1({ ...options, _v6: true }, new Uint8Array(16)); + bytes = v1ToV6(bytes); + if (buf) { + for (let i = 0; i < 16; i++) { + buf[offset + i] = bytes[i]; + } + return buf; + } + return unsafeStringify(bytes); +} +export default v6; diff --git a/node_modules/uuid/dist/esm-browser/v6ToV1.d.ts b/node_modules/uuid/dist/esm-browser/v6ToV1.d.ts new file mode 100644 index 0000000..3b3ffc2 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v6ToV1.d.ts @@ -0,0 +1,2 @@ +export default function v6ToV1(uuid: string): string; +export default function v6ToV1(uuid: Uint8Array): Uint8Array; diff --git a/node_modules/uuid/dist/esm-browser/v6ToV1.js b/node_modules/uuid/dist/esm-browser/v6ToV1.js new file mode 100644 index 0000000..bfd942f --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v6ToV1.js @@ -0,0 +1,10 @@ +import parse from './parse.js'; +import { unsafeStringify } from './stringify.js'; +export default function v6ToV1(uuid) { + const v6Bytes = typeof uuid === 'string' ? parse(uuid) : uuid; + const v1Bytes = _v6ToV1(v6Bytes); + return typeof uuid === 'string' ? unsafeStringify(v1Bytes) : v1Bytes; +} +function _v6ToV1(v6Bytes) { + return Uint8Array.of(((v6Bytes[3] & 0x0f) << 4) | ((v6Bytes[4] >> 4) & 0x0f), ((v6Bytes[4] & 0x0f) << 4) | ((v6Bytes[5] & 0xf0) >> 4), ((v6Bytes[5] & 0x0f) << 4) | (v6Bytes[6] & 0x0f), v6Bytes[7], ((v6Bytes[1] & 0x0f) << 4) | ((v6Bytes[2] & 0xf0) >> 4), ((v6Bytes[2] & 0x0f) << 4) | ((v6Bytes[3] & 0xf0) >> 4), 0x10 | ((v6Bytes[0] & 0xf0) >> 4), ((v6Bytes[0] & 0x0f) << 4) | ((v6Bytes[1] & 0xf0) >> 4), v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]); +} diff --git a/node_modules/uuid/dist/esm-browser/v7.d.ts b/node_modules/uuid/dist/esm-browser/v7.d.ts new file mode 100644 index 0000000..f49b03d --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v7.d.ts @@ -0,0 +1,9 @@ +import { Version7Options } from './types.js'; +type V7State = { + msecs?: number; + seq?: number; +}; +declare function v7(options?: Version7Options, buf?: undefined, offset?: number): string; +declare function v7(options: Version7Options | undefined, buf: TBuf, offset?: number): TBuf; +export declare function updateV7State(state: V7State, now: number, rnds: Uint8Array): V7State; +export default v7; diff --git a/node_modules/uuid/dist/esm-browser/v7.js b/node_modules/uuid/dist/esm-browser/v7.js new file mode 100644 index 0000000..276c9bf --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v7.js @@ -0,0 +1,65 @@ +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; +const _state = {}; +function v7(options, buf, offset) { + let bytes; + if (options) { + bytes = v7Bytes(options.random ?? options.rng?.() ?? rng(), options.msecs, options.seq, buf, offset); + } + else { + const now = Date.now(); + const rnds = rng(); + updateV7State(_state, now, rnds); + bytes = v7Bytes(rnds, _state.msecs, _state.seq, buf, offset); + } + return buf ?? unsafeStringify(bytes); +} +export function updateV7State(state, now, rnds) { + state.msecs ??= -Infinity; + state.seq ??= 0; + if (now > state.msecs) { + state.seq = (rnds[6] << 23) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9]; + state.msecs = now; + } + else { + state.seq = (state.seq + 1) | 0; + if (state.seq === 0) { + state.msecs++; + } + } + return state; +} +function v7Bytes(rnds, msecs, seq, buf, offset = 0) { + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + if (!buf) { + buf = new Uint8Array(16); + offset = 0; + } + else { + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + } + msecs ??= Date.now(); + seq ??= ((rnds[6] * 0x7f) << 24) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9]; + buf[offset++] = (msecs / 0x10000000000) & 0xff; + buf[offset++] = (msecs / 0x100000000) & 0xff; + buf[offset++] = (msecs / 0x1000000) & 0xff; + buf[offset++] = (msecs / 0x10000) & 0xff; + buf[offset++] = (msecs / 0x100) & 0xff; + buf[offset++] = msecs & 0xff; + buf[offset++] = 0x70 | ((seq >>> 28) & 0x0f); + buf[offset++] = (seq >>> 20) & 0xff; + buf[offset++] = 0x80 | ((seq >>> 14) & 0x3f); + buf[offset++] = (seq >>> 6) & 0xff; + buf[offset++] = ((seq << 2) & 0xff) | (rnds[10] & 0x03); + buf[offset++] = rnds[11]; + buf[offset++] = rnds[12]; + buf[offset++] = rnds[13]; + buf[offset++] = rnds[14]; + buf[offset++] = rnds[15]; + return buf; +} +export default v7; diff --git a/node_modules/uuid/dist/esm-browser/validate.d.ts b/node_modules/uuid/dist/esm-browser/validate.d.ts new file mode 100644 index 0000000..57da03d --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/validate.d.ts @@ -0,0 +1,2 @@ +declare function validate(uuid: unknown): boolean; +export default validate; diff --git a/node_modules/uuid/dist/esm-browser/validate.js b/node_modules/uuid/dist/esm-browser/validate.js new file mode 100644 index 0000000..444a1a2 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/validate.js @@ -0,0 +1,5 @@ +import REGEX from './regex.js'; +function validate(uuid) { + return typeof uuid === 'string' && REGEX.test(uuid); +} +export default validate; diff --git a/node_modules/uuid/dist/esm-browser/version.d.ts b/node_modules/uuid/dist/esm-browser/version.d.ts new file mode 100644 index 0000000..f1948dc --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/version.d.ts @@ -0,0 +1,2 @@ +declare function version(uuid: string): number; +export default version; diff --git a/node_modules/uuid/dist/esm-browser/version.js b/node_modules/uuid/dist/esm-browser/version.js new file mode 100644 index 0000000..bae91d3 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/version.js @@ -0,0 +1,8 @@ +import validate from './validate.js'; +function version(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + return parseInt(uuid.slice(14, 15), 16); +} +export default version; diff --git a/node_modules/uuid/dist/esm/bin/uuid b/node_modules/uuid/dist/esm/bin/uuid new file mode 100644 index 0000000..b4f612d --- /dev/null +++ b/node_modules/uuid/dist/esm/bin/uuid @@ -0,0 +1,2 @@ +#!/usr/bin/env node +import '../uuid-bin.js'; diff --git a/node_modules/uuid/dist/esm/index.d.ts b/node_modules/uuid/dist/esm/index.d.ts new file mode 100644 index 0000000..d7d4edc --- /dev/null +++ b/node_modules/uuid/dist/esm/index.d.ts @@ -0,0 +1,15 @@ +export type * from './types.js'; +export { default as MAX } from './max.js'; +export { default as NIL } from './nil.js'; +export { default as parse } from './parse.js'; +export { default as stringify } from './stringify.js'; +export { default as v1 } from './v1.js'; +export { default as v1ToV6 } from './v1ToV6.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as v6 } from './v6.js'; +export { default as v6ToV1 } from './v6ToV1.js'; +export { default as v7 } from './v7.js'; +export { default as validate } from './validate.js'; +export { default as version } from './version.js'; diff --git a/node_modules/uuid/dist/esm/index.js b/node_modules/uuid/dist/esm/index.js new file mode 100644 index 0000000..3193e9a --- /dev/null +++ b/node_modules/uuid/dist/esm/index.js @@ -0,0 +1,14 @@ +export { default as MAX } from './max.js'; +export { default as NIL } from './nil.js'; +export { default as parse } from './parse.js'; +export { default as stringify } from './stringify.js'; +export { default as v1 } from './v1.js'; +export { default as v1ToV6 } from './v1ToV6.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as v6 } from './v6.js'; +export { default as v6ToV1 } from './v6ToV1.js'; +export { default as v7 } from './v7.js'; +export { default as validate } from './validate.js'; +export { default as version } from './version.js'; diff --git a/node_modules/uuid/dist/esm/max.d.ts b/node_modules/uuid/dist/esm/max.d.ts new file mode 100644 index 0000000..7a1e972 --- /dev/null +++ b/node_modules/uuid/dist/esm/max.d.ts @@ -0,0 +1,2 @@ +declare const _default: "ffffffff-ffff-ffff-ffff-ffffffffffff"; +export default _default; diff --git a/node_modules/uuid/dist/esm/max.js b/node_modules/uuid/dist/esm/max.js new file mode 100644 index 0000000..58951f6 --- /dev/null +++ b/node_modules/uuid/dist/esm/max.js @@ -0,0 +1 @@ +export default 'ffffffff-ffff-ffff-ffff-ffffffffffff'; diff --git a/node_modules/uuid/dist/esm/md5.d.ts b/node_modules/uuid/dist/esm/md5.d.ts new file mode 100644 index 0000000..7d60244 --- /dev/null +++ b/node_modules/uuid/dist/esm/md5.d.ts @@ -0,0 +1,4 @@ +/// +/// +declare function md5(bytes: Uint8Array): Buffer; +export default md5; diff --git a/node_modules/uuid/dist/esm/md5.js b/node_modules/uuid/dist/esm/md5.js new file mode 100644 index 0000000..b922d98 --- /dev/null +++ b/node_modules/uuid/dist/esm/md5.js @@ -0,0 +1,11 @@ +import { createHash } from 'crypto'; +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } + else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + return createHash('md5').update(bytes).digest(); +} +export default md5; diff --git a/node_modules/uuid/dist/esm/native.d.ts b/node_modules/uuid/dist/esm/native.d.ts new file mode 100644 index 0000000..9e0d2ac --- /dev/null +++ b/node_modules/uuid/dist/esm/native.d.ts @@ -0,0 +1,6 @@ +/// +import { randomUUID } from 'crypto'; +declare const _default: { + randomUUID: typeof randomUUID; +}; +export default _default; diff --git a/node_modules/uuid/dist/esm/native.js b/node_modules/uuid/dist/esm/native.js new file mode 100644 index 0000000..ba74bca --- /dev/null +++ b/node_modules/uuid/dist/esm/native.js @@ -0,0 +1,2 @@ +import { randomUUID } from 'crypto'; +export default { randomUUID }; diff --git a/node_modules/uuid/dist/esm/nil.d.ts b/node_modules/uuid/dist/esm/nil.d.ts new file mode 100644 index 0000000..b03bb98 --- /dev/null +++ b/node_modules/uuid/dist/esm/nil.d.ts @@ -0,0 +1,2 @@ +declare const _default: "00000000-0000-0000-0000-000000000000"; +export default _default; diff --git a/node_modules/uuid/dist/esm/nil.js b/node_modules/uuid/dist/esm/nil.js new file mode 100644 index 0000000..de6f830 --- /dev/null +++ b/node_modules/uuid/dist/esm/nil.js @@ -0,0 +1 @@ +export default '00000000-0000-0000-0000-000000000000'; diff --git a/node_modules/uuid/dist/esm/parse.d.ts b/node_modules/uuid/dist/esm/parse.d.ts new file mode 100644 index 0000000..a316fb1 --- /dev/null +++ b/node_modules/uuid/dist/esm/parse.d.ts @@ -0,0 +1,2 @@ +declare function parse(uuid: string): Uint8Array; +export default parse; diff --git a/node_modules/uuid/dist/esm/parse.js b/node_modules/uuid/dist/esm/parse.js new file mode 100644 index 0000000..64ac401 --- /dev/null +++ b/node_modules/uuid/dist/esm/parse.js @@ -0,0 +1,9 @@ +import validate from './validate.js'; +function parse(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + let v; + return Uint8Array.of((v = parseInt(uuid.slice(0, 8), 16)) >>> 24, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff, (v = parseInt(uuid.slice(9, 13), 16)) >>> 8, v & 0xff, (v = parseInt(uuid.slice(14, 18), 16)) >>> 8, v & 0xff, (v = parseInt(uuid.slice(19, 23), 16)) >>> 8, v & 0xff, ((v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000) & 0xff, (v / 0x100000000) & 0xff, (v >>> 24) & 0xff, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff); +} +export default parse; diff --git a/node_modules/uuid/dist/esm/regex.d.ts b/node_modules/uuid/dist/esm/regex.d.ts new file mode 100644 index 0000000..d39fa3f --- /dev/null +++ b/node_modules/uuid/dist/esm/regex.d.ts @@ -0,0 +1,2 @@ +declare const _default: RegExp; +export default _default; diff --git a/node_modules/uuid/dist/esm/regex.js b/node_modules/uuid/dist/esm/regex.js new file mode 100644 index 0000000..3e38591 --- /dev/null +++ b/node_modules/uuid/dist/esm/regex.js @@ -0,0 +1 @@ +export 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; diff --git a/node_modules/uuid/dist/esm/rng.d.ts b/node_modules/uuid/dist/esm/rng.d.ts new file mode 100644 index 0000000..73e60cf --- /dev/null +++ b/node_modules/uuid/dist/esm/rng.d.ts @@ -0,0 +1 @@ +export default function rng(): Uint8Array; diff --git a/node_modules/uuid/dist/esm/rng.js b/node_modules/uuid/dist/esm/rng.js new file mode 100644 index 0000000..54c1cfe --- /dev/null +++ b/node_modules/uuid/dist/esm/rng.js @@ -0,0 +1,10 @@ +import { randomFillSync } from 'crypto'; +const rnds8Pool = new Uint8Array(256); +let poolPtr = rnds8Pool.length; +export default function rng() { + if (poolPtr > rnds8Pool.length - 16) { + randomFillSync(rnds8Pool); + poolPtr = 0; + } + return rnds8Pool.slice(poolPtr, (poolPtr += 16)); +} diff --git a/node_modules/uuid/dist/esm/sha1.d.ts b/node_modules/uuid/dist/esm/sha1.d.ts new file mode 100644 index 0000000..ebb1404 --- /dev/null +++ b/node_modules/uuid/dist/esm/sha1.d.ts @@ -0,0 +1,4 @@ +/// +/// +declare function sha1(bytes: Uint8Array): Buffer; +export default sha1; diff --git a/node_modules/uuid/dist/esm/sha1.js b/node_modules/uuid/dist/esm/sha1.js new file mode 100644 index 0000000..fda4aa3 --- /dev/null +++ b/node_modules/uuid/dist/esm/sha1.js @@ -0,0 +1,11 @@ +import { createHash } from 'crypto'; +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } + else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + return createHash('sha1').update(bytes).digest(); +} +export default sha1; diff --git a/node_modules/uuid/dist/esm/stringify.d.ts b/node_modules/uuid/dist/esm/stringify.d.ts new file mode 100644 index 0000000..16cb008 --- /dev/null +++ b/node_modules/uuid/dist/esm/stringify.d.ts @@ -0,0 +1,3 @@ +export declare function unsafeStringify(arr: Uint8Array, offset?: number): string; +declare function stringify(arr: Uint8Array, offset?: number): string; +export default stringify; diff --git a/node_modules/uuid/dist/esm/stringify.js b/node_modules/uuid/dist/esm/stringify.js new file mode 100644 index 0000000..962738c --- /dev/null +++ b/node_modules/uuid/dist/esm/stringify.js @@ -0,0 +1,35 @@ +import validate from './validate.js'; +const byteToHex = []; +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} +export function unsafeStringify(arr, offset = 0) { + return (byteToHex[arr[offset + 0]] + + byteToHex[arr[offset + 1]] + + byteToHex[arr[offset + 2]] + + byteToHex[arr[offset + 3]] + + '-' + + byteToHex[arr[offset + 4]] + + byteToHex[arr[offset + 5]] + + '-' + + byteToHex[arr[offset + 6]] + + byteToHex[arr[offset + 7]] + + '-' + + byteToHex[arr[offset + 8]] + + byteToHex[arr[offset + 9]] + + '-' + + byteToHex[arr[offset + 10]] + + byteToHex[arr[offset + 11]] + + byteToHex[arr[offset + 12]] + + byteToHex[arr[offset + 13]] + + byteToHex[arr[offset + 14]] + + byteToHex[arr[offset + 15]]).toLowerCase(); +} +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); + if (!validate(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + return uuid; +} +export default stringify; diff --git a/node_modules/uuid/dist/esm/types.d.ts b/node_modules/uuid/dist/esm/types.d.ts new file mode 100644 index 0000000..ecaed97 --- /dev/null +++ b/node_modules/uuid/dist/esm/types.d.ts @@ -0,0 +1,21 @@ +export type UUIDTypes = string | TBuf; +export type Version1Options = { + node?: Uint8Array; + clockseq?: number; + random?: Uint8Array; + rng?: () => Uint8Array; + msecs?: number; + nsecs?: number; + _v6?: boolean; +}; +export type Version4Options = { + random?: Uint8Array; + rng?: () => Uint8Array; +}; +export type Version6Options = Version1Options; +export type Version7Options = { + random?: Uint8Array; + msecs?: number; + seq?: number; + rng?: () => Uint8Array; +}; diff --git a/node_modules/uuid/dist/esm/types.js b/node_modules/uuid/dist/esm/types.js new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/uuid/dist/esm/types.js @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/uuid/dist/esm/uuid-bin.d.ts b/node_modules/uuid/dist/esm/uuid-bin.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/uuid/dist/esm/uuid-bin.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/uuid/dist/esm/uuid-bin.js b/node_modules/uuid/dist/esm/uuid-bin.js new file mode 100644 index 0000000..30766fe --- /dev/null +++ b/node_modules/uuid/dist/esm/uuid-bin.js @@ -0,0 +1,70 @@ +import * as assert from 'assert'; +import v1 from './v1.js'; +import v3 from './v3.js'; +import v4 from './v4.js'; +import v5 from './v5.js'; +import v6 from './v6.js'; +import v7 from './v7.js'; +function usage() { + console.log('Usage:'); + console.log(' uuid'); + console.log(' uuid v1'); + console.log(' uuid v3 '); + console.log(' uuid v4'); + console.log(' uuid v5 '); + console.log(' uuid v6'); + console.log(' uuid v7'); + console.log(' uuid --help'); + console.log('\nNote: may be "URL" or "DNS" to use the corresponding UUIDs defined by RFC9562'); +} +const args = process.argv.slice(2); +if (args.indexOf('--help') >= 0) { + usage(); + process.exit(0); +} +const version = args.shift() || 'v4'; +switch (version) { + case 'v1': + console.log(v1()); + break; + case 'v3': { + const name = args.shift(); + let namespace = args.shift(); + assert.ok(name != null, 'v3 name not specified'); + assert.ok(namespace != null, 'v3 namespace not specified'); + if (namespace === 'URL') { + namespace = v3.URL; + } + if (namespace === 'DNS') { + namespace = v3.DNS; + } + console.log(v3(name, namespace)); + break; + } + case 'v4': + console.log(v4()); + break; + case 'v5': { + const name = args.shift(); + let namespace = args.shift(); + assert.ok(name != null, 'v5 name not specified'); + assert.ok(namespace != null, 'v5 namespace not specified'); + if (namespace === 'URL') { + namespace = v5.URL; + } + if (namespace === 'DNS') { + namespace = v5.DNS; + } + console.log(v5(name, namespace)); + break; + } + case 'v6': + console.log(v6()); + break; + case 'v7': + console.log(v7()); + break; + default: + usage(); + process.exit(1); +} diff --git a/node_modules/uuid/dist/esm/v1.d.ts b/node_modules/uuid/dist/esm/v1.d.ts new file mode 100644 index 0000000..d8ecee0 --- /dev/null +++ b/node_modules/uuid/dist/esm/v1.d.ts @@ -0,0 +1,11 @@ +import { Version1Options } from './types.js'; +type V1State = { + node?: Uint8Array; + clockseq?: number; + msecs?: number; + nsecs?: number; +}; +declare function v1(options?: Version1Options, buf?: undefined, offset?: number): string; +declare function v1(options: Version1Options | undefined, buf: Buf, offset?: number): Buf; +export declare function updateV1State(state: V1State, now: number, rnds: Uint8Array): V1State; +export default v1; diff --git a/node_modules/uuid/dist/esm/v1.js b/node_modules/uuid/dist/esm/v1.js new file mode 100644 index 0000000..65e3f68 --- /dev/null +++ b/node_modules/uuid/dist/esm/v1.js @@ -0,0 +1,83 @@ +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; +const _state = {}; +function v1(options, buf, offset) { + let bytes; + const isV6 = options?._v6 ?? false; + if (options) { + const optionsKeys = Object.keys(options); + if (optionsKeys.length === 1 && optionsKeys[0] === '_v6') { + options = undefined; + } + } + if (options) { + bytes = v1Bytes(options.random ?? options.rng?.() ?? rng(), options.msecs, options.nsecs, options.clockseq, options.node, buf, offset); + } + else { + const now = Date.now(); + const rnds = rng(); + updateV1State(_state, now, rnds); + bytes = v1Bytes(rnds, _state.msecs, _state.nsecs, isV6 ? undefined : _state.clockseq, isV6 ? undefined : _state.node, buf, offset); + } + return buf ?? unsafeStringify(bytes); +} +export function updateV1State(state, now, rnds) { + state.msecs ??= -Infinity; + state.nsecs ??= 0; + if (now === state.msecs) { + state.nsecs++; + if (state.nsecs >= 10000) { + state.node = undefined; + state.nsecs = 0; + } + } + else if (now > state.msecs) { + state.nsecs = 0; + } + else if (now < state.msecs) { + state.node = undefined; + } + if (!state.node) { + state.node = rnds.slice(10, 16); + state.node[0] |= 0x01; + state.clockseq = ((rnds[8] << 8) | rnds[9]) & 0x3fff; + } + state.msecs = now; + return state; +} +function v1Bytes(rnds, msecs, nsecs, clockseq, node, buf, offset = 0) { + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + if (!buf) { + buf = new Uint8Array(16); + offset = 0; + } + else { + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + } + msecs ??= Date.now(); + nsecs ??= 0; + clockseq ??= ((rnds[8] << 8) | rnds[9]) & 0x3fff; + node ??= rnds.slice(10, 16); + msecs += 12219292800000; + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + buf[offset++] = (tl >>> 24) & 0xff; + buf[offset++] = (tl >>> 16) & 0xff; + buf[offset++] = (tl >>> 8) & 0xff; + buf[offset++] = tl & 0xff; + const tmh = ((msecs / 0x100000000) * 10000) & 0xfffffff; + buf[offset++] = (tmh >>> 8) & 0xff; + buf[offset++] = tmh & 0xff; + buf[offset++] = ((tmh >>> 24) & 0xf) | 0x10; + buf[offset++] = (tmh >>> 16) & 0xff; + buf[offset++] = (clockseq >>> 8) | 0x80; + buf[offset++] = clockseq & 0xff; + for (let n = 0; n < 6; ++n) { + buf[offset++] = node[n]; + } + return buf; +} +export default v1; diff --git a/node_modules/uuid/dist/esm/v1ToV6.d.ts b/node_modules/uuid/dist/esm/v1ToV6.d.ts new file mode 100644 index 0000000..38eaaf0 --- /dev/null +++ b/node_modules/uuid/dist/esm/v1ToV6.d.ts @@ -0,0 +1,2 @@ +export default function v1ToV6(uuid: string): string; +export default function v1ToV6(uuid: Uint8Array): Uint8Array; diff --git a/node_modules/uuid/dist/esm/v1ToV6.js b/node_modules/uuid/dist/esm/v1ToV6.js new file mode 100644 index 0000000..da0f763 --- /dev/null +++ b/node_modules/uuid/dist/esm/v1ToV6.js @@ -0,0 +1,10 @@ +import parse from './parse.js'; +import { unsafeStringify } from './stringify.js'; +export default function v1ToV6(uuid) { + const v1Bytes = typeof uuid === 'string' ? parse(uuid) : uuid; + const v6Bytes = _v1ToV6(v1Bytes); + return typeof uuid === 'string' ? unsafeStringify(v6Bytes) : v6Bytes; +} +function _v1ToV6(v1Bytes) { + return Uint8Array.of(((v1Bytes[6] & 0x0f) << 4) | ((v1Bytes[7] >> 4) & 0x0f), ((v1Bytes[7] & 0x0f) << 4) | ((v1Bytes[4] & 0xf0) >> 4), ((v1Bytes[4] & 0x0f) << 4) | ((v1Bytes[5] & 0xf0) >> 4), ((v1Bytes[5] & 0x0f) << 4) | ((v1Bytes[0] & 0xf0) >> 4), ((v1Bytes[0] & 0x0f) << 4) | ((v1Bytes[1] & 0xf0) >> 4), ((v1Bytes[1] & 0x0f) << 4) | ((v1Bytes[2] & 0xf0) >> 4), 0x60 | (v1Bytes[2] & 0x0f), v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]); +} diff --git a/node_modules/uuid/dist/esm/v3.d.ts b/node_modules/uuid/dist/esm/v3.d.ts new file mode 100644 index 0000000..5d1c434 --- /dev/null +++ b/node_modules/uuid/dist/esm/v3.d.ts @@ -0,0 +1,9 @@ +import { UUIDTypes } from './types.js'; +export { DNS, URL } from './v35.js'; +declare function v3(value: string | Uint8Array, namespace: UUIDTypes, buf?: undefined, offset?: number): string; +declare function v3(value: string | Uint8Array, namespace: UUIDTypes, buf: TBuf, offset?: number): TBuf; +declare namespace v3 { + var DNS: string; + var URL: string; +} +export default v3; diff --git a/node_modules/uuid/dist/esm/v3.js b/node_modules/uuid/dist/esm/v3.js new file mode 100644 index 0000000..b5c3781 --- /dev/null +++ b/node_modules/uuid/dist/esm/v3.js @@ -0,0 +1,9 @@ +import md5 from './md5.js'; +import v35, { DNS, URL } from './v35.js'; +export { DNS, URL } from './v35.js'; +function v3(value, namespace, buf, offset) { + return v35(0x30, md5, value, namespace, buf, offset); +} +v3.DNS = DNS; +v3.URL = URL; +export default v3; diff --git a/node_modules/uuid/dist/esm/v35.d.ts b/node_modules/uuid/dist/esm/v35.d.ts new file mode 100644 index 0000000..4e6e9d5 --- /dev/null +++ b/node_modules/uuid/dist/esm/v35.d.ts @@ -0,0 +1,7 @@ +import { UUIDTypes } from './types.js'; +export declare function stringToBytes(str: string): Uint8Array; +export declare const DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; +export declare const URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; +type HashFunction = (bytes: Uint8Array) => Uint8Array; +export default function v35(version: 0x30 | 0x50, hash: HashFunction, value: string | Uint8Array, namespace: UUIDTypes, buf?: TBuf, offset?: number): UUIDTypes; +export {}; diff --git a/node_modules/uuid/dist/esm/v35.js b/node_modules/uuid/dist/esm/v35.js new file mode 100644 index 0000000..3fe6573 --- /dev/null +++ b/node_modules/uuid/dist/esm/v35.js @@ -0,0 +1,36 @@ +import parse from './parse.js'; +import { unsafeStringify } from './stringify.js'; +export function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); + const bytes = new Uint8Array(str.length); + for (let i = 0; i < str.length; ++i) { + bytes[i] = str.charCodeAt(i); + } + return bytes; +} +export const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +export const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +export default function v35(version, hash, value, namespace, buf, offset) { + const valueBytes = typeof value === 'string' ? stringToBytes(value) : value; + const namespaceBytes = typeof namespace === 'string' ? parse(namespace) : namespace; + if (typeof namespace === 'string') { + namespace = parse(namespace); + } + if (namespace?.length !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } + let bytes = new Uint8Array(16 + valueBytes.length); + bytes.set(namespaceBytes); + bytes.set(valueBytes, namespaceBytes.length); + bytes = hash(bytes); + bytes[6] = (bytes[6] & 0x0f) | version; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + if (buf) { + offset = offset || 0; + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + return buf; + } + return unsafeStringify(bytes); +} diff --git a/node_modules/uuid/dist/esm/v4.d.ts b/node_modules/uuid/dist/esm/v4.d.ts new file mode 100644 index 0000000..8205333 --- /dev/null +++ b/node_modules/uuid/dist/esm/v4.d.ts @@ -0,0 +1,4 @@ +import { Version4Options } from './types.js'; +declare function v4(options?: Version4Options, buf?: undefined, offset?: number): string; +declare function v4(options: Version4Options | undefined, buf: TBuf, offset?: number): TBuf; +export default v4; diff --git a/node_modules/uuid/dist/esm/v4.js b/node_modules/uuid/dist/esm/v4.js new file mode 100644 index 0000000..dd9067a --- /dev/null +++ b/node_modules/uuid/dist/esm/v4.js @@ -0,0 +1,27 @@ +import native from './native.js'; +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; +function v4(options, buf, offset) { + if (native.randomUUID && !buf && !options) { + return native.randomUUID(); + } + options = options || {}; + const rnds = options.random ?? options.rng?.() ?? rng(); + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; + if (buf) { + offset = offset || 0; + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + return buf; + } + return unsafeStringify(rnds); +} +export default v4; diff --git a/node_modules/uuid/dist/esm/v5.d.ts b/node_modules/uuid/dist/esm/v5.d.ts new file mode 100644 index 0000000..0e2ff2f --- /dev/null +++ b/node_modules/uuid/dist/esm/v5.d.ts @@ -0,0 +1,9 @@ +import { UUIDTypes } from './types.js'; +export { DNS, URL } from './v35.js'; +declare function v5(value: string | Uint8Array, namespace: UUIDTypes, buf?: undefined, offset?: number): string; +declare function v5(value: string | Uint8Array, namespace: UUIDTypes, buf: TBuf, offset?: number): TBuf; +declare namespace v5 { + var DNS: string; + var URL: string; +} +export default v5; diff --git a/node_modules/uuid/dist/esm/v5.js b/node_modules/uuid/dist/esm/v5.js new file mode 100644 index 0000000..bd470a4 --- /dev/null +++ b/node_modules/uuid/dist/esm/v5.js @@ -0,0 +1,9 @@ +import sha1 from './sha1.js'; +import v35, { DNS, URL } from './v35.js'; +export { DNS, URL } from './v35.js'; +function v5(value, namespace, buf, offset) { + return v35(0x50, sha1, value, namespace, buf, offset); +} +v5.DNS = DNS; +v5.URL = URL; +export default v5; diff --git a/node_modules/uuid/dist/esm/v6.d.ts b/node_modules/uuid/dist/esm/v6.d.ts new file mode 100644 index 0000000..cabf4a0 --- /dev/null +++ b/node_modules/uuid/dist/esm/v6.d.ts @@ -0,0 +1,4 @@ +import { Version6Options } from './types.js'; +declare function v6(options?: Version6Options, buf?: undefined, offset?: number): string; +declare function v6(options: Version6Options | undefined, buf: TBuf, offset?: number): TBuf; +export default v6; diff --git a/node_modules/uuid/dist/esm/v6.js b/node_modules/uuid/dist/esm/v6.js new file mode 100644 index 0000000..278a339 --- /dev/null +++ b/node_modules/uuid/dist/esm/v6.js @@ -0,0 +1,17 @@ +import { unsafeStringify } from './stringify.js'; +import v1 from './v1.js'; +import v1ToV6 from './v1ToV6.js'; +function v6(options, buf, offset) { + options ??= {}; + offset ??= 0; + let bytes = v1({ ...options, _v6: true }, new Uint8Array(16)); + bytes = v1ToV6(bytes); + if (buf) { + for (let i = 0; i < 16; i++) { + buf[offset + i] = bytes[i]; + } + return buf; + } + return unsafeStringify(bytes); +} +export default v6; diff --git a/node_modules/uuid/dist/esm/v6ToV1.d.ts b/node_modules/uuid/dist/esm/v6ToV1.d.ts new file mode 100644 index 0000000..3b3ffc2 --- /dev/null +++ b/node_modules/uuid/dist/esm/v6ToV1.d.ts @@ -0,0 +1,2 @@ +export default function v6ToV1(uuid: string): string; +export default function v6ToV1(uuid: Uint8Array): Uint8Array; diff --git a/node_modules/uuid/dist/esm/v6ToV1.js b/node_modules/uuid/dist/esm/v6ToV1.js new file mode 100644 index 0000000..bfd942f --- /dev/null +++ b/node_modules/uuid/dist/esm/v6ToV1.js @@ -0,0 +1,10 @@ +import parse from './parse.js'; +import { unsafeStringify } from './stringify.js'; +export default function v6ToV1(uuid) { + const v6Bytes = typeof uuid === 'string' ? parse(uuid) : uuid; + const v1Bytes = _v6ToV1(v6Bytes); + return typeof uuid === 'string' ? unsafeStringify(v1Bytes) : v1Bytes; +} +function _v6ToV1(v6Bytes) { + return Uint8Array.of(((v6Bytes[3] & 0x0f) << 4) | ((v6Bytes[4] >> 4) & 0x0f), ((v6Bytes[4] & 0x0f) << 4) | ((v6Bytes[5] & 0xf0) >> 4), ((v6Bytes[5] & 0x0f) << 4) | (v6Bytes[6] & 0x0f), v6Bytes[7], ((v6Bytes[1] & 0x0f) << 4) | ((v6Bytes[2] & 0xf0) >> 4), ((v6Bytes[2] & 0x0f) << 4) | ((v6Bytes[3] & 0xf0) >> 4), 0x10 | ((v6Bytes[0] & 0xf0) >> 4), ((v6Bytes[0] & 0x0f) << 4) | ((v6Bytes[1] & 0xf0) >> 4), v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]); +} diff --git a/node_modules/uuid/dist/esm/v7.d.ts b/node_modules/uuid/dist/esm/v7.d.ts new file mode 100644 index 0000000..f49b03d --- /dev/null +++ b/node_modules/uuid/dist/esm/v7.d.ts @@ -0,0 +1,9 @@ +import { Version7Options } from './types.js'; +type V7State = { + msecs?: number; + seq?: number; +}; +declare function v7(options?: Version7Options, buf?: undefined, offset?: number): string; +declare function v7(options: Version7Options | undefined, buf: TBuf, offset?: number): TBuf; +export declare function updateV7State(state: V7State, now: number, rnds: Uint8Array): V7State; +export default v7; diff --git a/node_modules/uuid/dist/esm/v7.js b/node_modules/uuid/dist/esm/v7.js new file mode 100644 index 0000000..276c9bf --- /dev/null +++ b/node_modules/uuid/dist/esm/v7.js @@ -0,0 +1,65 @@ +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; +const _state = {}; +function v7(options, buf, offset) { + let bytes; + if (options) { + bytes = v7Bytes(options.random ?? options.rng?.() ?? rng(), options.msecs, options.seq, buf, offset); + } + else { + const now = Date.now(); + const rnds = rng(); + updateV7State(_state, now, rnds); + bytes = v7Bytes(rnds, _state.msecs, _state.seq, buf, offset); + } + return buf ?? unsafeStringify(bytes); +} +export function updateV7State(state, now, rnds) { + state.msecs ??= -Infinity; + state.seq ??= 0; + if (now > state.msecs) { + state.seq = (rnds[6] << 23) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9]; + state.msecs = now; + } + else { + state.seq = (state.seq + 1) | 0; + if (state.seq === 0) { + state.msecs++; + } + } + return state; +} +function v7Bytes(rnds, msecs, seq, buf, offset = 0) { + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + if (!buf) { + buf = new Uint8Array(16); + offset = 0; + } + else { + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + } + msecs ??= Date.now(); + seq ??= ((rnds[6] * 0x7f) << 24) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9]; + buf[offset++] = (msecs / 0x10000000000) & 0xff; + buf[offset++] = (msecs / 0x100000000) & 0xff; + buf[offset++] = (msecs / 0x1000000) & 0xff; + buf[offset++] = (msecs / 0x10000) & 0xff; + buf[offset++] = (msecs / 0x100) & 0xff; + buf[offset++] = msecs & 0xff; + buf[offset++] = 0x70 | ((seq >>> 28) & 0x0f); + buf[offset++] = (seq >>> 20) & 0xff; + buf[offset++] = 0x80 | ((seq >>> 14) & 0x3f); + buf[offset++] = (seq >>> 6) & 0xff; + buf[offset++] = ((seq << 2) & 0xff) | (rnds[10] & 0x03); + buf[offset++] = rnds[11]; + buf[offset++] = rnds[12]; + buf[offset++] = rnds[13]; + buf[offset++] = rnds[14]; + buf[offset++] = rnds[15]; + return buf; +} +export default v7; diff --git a/node_modules/uuid/dist/esm/validate.d.ts b/node_modules/uuid/dist/esm/validate.d.ts new file mode 100644 index 0000000..57da03d --- /dev/null +++ b/node_modules/uuid/dist/esm/validate.d.ts @@ -0,0 +1,2 @@ +declare function validate(uuid: unknown): boolean; +export default validate; diff --git a/node_modules/uuid/dist/esm/validate.js b/node_modules/uuid/dist/esm/validate.js new file mode 100644 index 0000000..444a1a2 --- /dev/null +++ b/node_modules/uuid/dist/esm/validate.js @@ -0,0 +1,5 @@ +import REGEX from './regex.js'; +function validate(uuid) { + return typeof uuid === 'string' && REGEX.test(uuid); +} +export default validate; diff --git a/node_modules/uuid/dist/esm/version.d.ts b/node_modules/uuid/dist/esm/version.d.ts new file mode 100644 index 0000000..f1948dc --- /dev/null +++ b/node_modules/uuid/dist/esm/version.d.ts @@ -0,0 +1,2 @@ +declare function version(uuid: string): number; +export default version; diff --git a/node_modules/uuid/dist/esm/version.js b/node_modules/uuid/dist/esm/version.js new file mode 100644 index 0000000..bae91d3 --- /dev/null +++ b/node_modules/uuid/dist/esm/version.js @@ -0,0 +1,8 @@ +import validate from './validate.js'; +function version(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + return parseInt(uuid.slice(14, 15), 16); +} +export default version; diff --git a/node_modules/uuid/package.json b/node_modules/uuid/package.json new file mode 100644 index 0000000..b0da6d9 --- /dev/null +++ b/node_modules/uuid/package.json @@ -0,0 +1,132 @@ +{ + "name": "uuid", + "version": "11.1.0", + "description": "RFC9562 UUIDs", + "type": "module", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "commitlint": { + "extends": [ + "@commitlint/config-conventional" + ] + }, + "keywords": [ + "uuid", + "guid", + "rfc4122", + "rfc9562" + ], + "license": "MIT", + "bin": { + "uuid": "./dist/esm/bin/uuid" + }, + "sideEffects": false, + "main": "./dist/cjs/index.js", + "exports": { + ".": { + "node": { + "import": "./dist/esm/index.js", + "require": "./dist/cjs/index.js" + }, + "browser": { + "import": "./dist/esm-browser/index.js", + "require": "./dist/cjs-browser/index.js" + }, + "default": "./dist/esm-browser/index.js" + }, + "./package.json": "./package.json" + }, + "module": "./dist/esm/index.js", + "browser": { + "./dist/esm/index.js": "./dist/esm-browser/index.js", + "./dist/cjs/index.js": "./dist/cjs-browser/index.js" + }, + "files": [ + "dist", + "!dist/**/test" + ], + "devDependencies": { + "@babel/eslint-parser": "7.25.9", + "@commitlint/cli": "19.6.1", + "@commitlint/config-conventional": "19.6.0", + "@eslint/js": "9.17.0", + "@types/eslint__js": "8.42.3", + "bundlewatch": "0.4.0", + "commander": "12.1.0", + "eslint": "9.17.0", + "eslint-config-prettier": "9.1.0", + "eslint-plugin-prettier": "5.2.1", + "globals": "15.14.0", + "husky": "9.1.7", + "jest": "29.7.0", + "lint-staged": "15.2.11", + "neostandard": "0.12.0", + "npm-run-all": "4.1.5", + "prettier": "3.4.2", + "release-please": "16.15.0", + "runmd": "1.4.1", + "standard-version": "9.5.0", + "typescript": "5.0.4", + "typescript-eslint": "8.18.2" + }, + "optionalDevDependencies": { + "@wdio/browserstack-service": "9.2.1", + "@wdio/cli": "9.2.1", + "@wdio/jasmine-framework": "9.2.1", + "@wdio/local-runner": "9.2.1", + "@wdio/spec-reporter": "9.1.3", + "@wdio/static-server-service": "9.1.3" + }, + "scripts": { + "build": "./scripts/build.sh", + "build:watch": "tsc --watch -p tsconfig.esm.json", + "bundlewatch": "npm run pretest:browser && bundlewatch --config bundlewatch.config.json", + "docs:diff": "npm run docs && git diff --quiet README.md", + "docs": "npm run build && npx runmd --output=README.md README_js.md", + "eslint:check": "eslint src/ test/ examples/ *.[jt]s", + "eslint:fix": "eslint --fix src/ test/ examples/ *.[jt]s", + "examples:browser:rollup:build": "cd examples/browser-rollup && npm run build", + "examples:browser:webpack:build": "cd examples/browser-webpack && npm run build", + "examples:node:commonjs:test": "cd examples/node-commonjs && npm test", + "examples:node:esmodules:test": "cd examples/node-esmodules && npm test", + "examples:node:jest:test": "cd examples/node-jest && npm test", + "examples:node:typescript:test": "cd examples/typescript && npm test", + "lint": "npm run eslint:check && npm run prettier:check", + "md": "runmd --watch --output=README.md README_js.md", + "prepack": "npm run build -- --no-pack", + "prepare": "husky", + "prepublishOnly": "npm run build", + "pretest:benchmark": "npm run build", + "pretest:browser": "./scripts/iodd && npm run build && npm-run-all --parallel examples:browser:**", + "pretest:node": "npm run build", + "pretest": "npm run build", + "prettier:check": "prettier --check .", + "prettier:fix": "prettier --write .", + "release": "standard-version --no-verify", + "test:benchmark": "cd examples/benchmark && npm test", + "test:browser": "wdio run ./wdio.conf.js", + "test:node": "npm-run-all --parallel examples:node:**", + "test:watch": "node --test --enable-source-maps --watch dist/esm/test/*.js", + "test": "node --test --enable-source-maps dist/esm/test/*.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/uuidjs/uuid.git" + }, + "lint-staged": { + "*": [ + "prettier --no-error-on-unmatched-pattern --write" + ], + "*.{js,jsx}": [ + "eslint --no-error-on-unmatched-pattern --fix" + ] + }, + "standard-version": { + "scripts": { + "postchangelog": "prettier --write CHANGELOG.md" + } + }, + "packageManager": "npm@11.0.0" +} diff --git a/node_modules/webidl-conversions/LICENSE.md b/node_modules/webidl-conversions/LICENSE.md new file mode 100644 index 0000000..d4a994f --- /dev/null +++ b/node_modules/webidl-conversions/LICENSE.md @@ -0,0 +1,12 @@ +# The BSD 2-Clause License + +Copyright (c) 2014, Domenic Denicola +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/webidl-conversions/README.md b/node_modules/webidl-conversions/README.md new file mode 100644 index 0000000..3657890 --- /dev/null +++ b/node_modules/webidl-conversions/README.md @@ -0,0 +1,53 @@ +# WebIDL Type Conversions on JavaScript Values + +This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [WebIDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types). + +The goal is that you should be able to write code like + +```js +const conversions = require("webidl-conversions"); + +function doStuff(x, y) { + x = conversions["boolean"](x); + y = conversions["unsigned long"](y); + // actual algorithm code here +} +``` + +and your function `doStuff` will behave the same as a WebIDL operation declared as + +```webidl +void doStuff(boolean x, unsigned long y); +``` + +## API + +This package's main module's default export is an object with a variety of methods, each corresponding to a different WebIDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the WebIDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the WebIDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float). + +## Status + +All of the numeric types are implemented (float being implemented as double) and some others are as well - check the source for all of them. This list will grow over time in service of the [HTML as Custom Elements](https://github.com/dglazkov/html-as-custom-elements) project, but in the meantime, pull requests welcome! + +I'm not sure yet what the strategy will be for modifiers, e.g. [`[Clamp]`](http://heycam.github.io/webidl/#Clamp). Maybe something like `conversions["unsigned long"](x, { clamp: true })`? We'll see. + +We might also want to extend the API to give better error messages, e.g. "Argument 1 of HTMLMediaElement.fastSeek is not a finite floating-point value" instead of "Argument is not a finite floating-point value." This would require passing in more information to the conversion functions than we currently do. + +## Background + +What's actually going on here, conceptually, is pretty weird. Let's try to explain. + +WebIDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on WebIDL values, i.e. instances of WebIDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a WebIDL value of [WebIDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules. + +Separately from its type system, WebIDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given WebIDL operation, how does that get converted into a WebIDL value? For example, a JavaScript `true` passed in the position of a WebIDL `boolean` argument becomes a WebIDL `true`. But, a JavaScript `true` passed in the position of a [WebIDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a WebIDL `1`. And so on. + +Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the WebIDL algorithms, they don't actually use WebIDL values, since those aren't "real" outside of specs. Instead, implementations apply the WebIDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`. + +The upside of all this is that implementations can abstract all the conversion logic away, letting WebIDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of WebIDL, in a nutshell. + +And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given WebIDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ WebIDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ WebIDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a WebIDL `1` in an unsigned long context, which then becomes a JavaScript `1`. + +## Don't Use This + +Seriously, why would you ever use this? You really shouldn't. WebIDL is … not great, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from WebIDL. In general, your JavaScript should not be trying to become more like WebIDL; if anything, we should fix WebIDL to make it more like JavaScript. + +The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in WebIDL. diff --git a/node_modules/webidl-conversions/lib/index.js b/node_modules/webidl-conversions/lib/index.js new file mode 100644 index 0000000..c5153a3 --- /dev/null +++ b/node_modules/webidl-conversions/lib/index.js @@ -0,0 +1,189 @@ +"use strict"; + +var conversions = {}; +module.exports = conversions; + +function sign(x) { + return x < 0 ? -1 : 1; +} + +function evenRound(x) { + // Round x to the nearest integer, choosing the even integer if it lies halfway between two. + if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor) + return Math.floor(x); + } else { + return Math.round(x); + } +} + +function createNumberConversion(bitLength, typeOpts) { + if (!typeOpts.unsigned) { + --bitLength; + } + const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength); + const upperBound = Math.pow(2, bitLength) - 1; + + const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength); + const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1); + + return function(V, opts) { + if (!opts) opts = {}; + + let x = +V; + + if (opts.enforceRange) { + if (!Number.isFinite(x)) { + throw new TypeError("Argument is not a finite number"); + } + + x = sign(x) * Math.floor(Math.abs(x)); + if (x < lowerBound || x > upperBound) { + throw new TypeError("Argument is not in byte range"); + } + + return x; + } + + if (!isNaN(x) && opts.clamp) { + x = evenRound(x); + + if (x < lowerBound) x = lowerBound; + if (x > upperBound) x = upperBound; + return x; + } + + if (!Number.isFinite(x) || x === 0) { + return 0; + } + + x = sign(x) * Math.floor(Math.abs(x)); + x = x % moduloVal; + + if (!typeOpts.unsigned && x >= moduloBound) { + return x - moduloVal; + } else if (typeOpts.unsigned) { + if (x < 0) { + x += moduloVal; + } else if (x === -0) { // don't return negative zero + return 0; + } + } + + return x; + } +} + +conversions["void"] = function () { + return undefined; +}; + +conversions["boolean"] = function (val) { + return !!val; +}; + +conversions["byte"] = createNumberConversion(8, { unsigned: false }); +conversions["octet"] = createNumberConversion(8, { unsigned: true }); + +conversions["short"] = createNumberConversion(16, { unsigned: false }); +conversions["unsigned short"] = createNumberConversion(16, { unsigned: true }); + +conversions["long"] = createNumberConversion(32, { unsigned: false }); +conversions["unsigned long"] = createNumberConversion(32, { unsigned: true }); + +conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 }); +conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 }); + +conversions["double"] = function (V) { + const x = +V; + + if (!Number.isFinite(x)) { + throw new TypeError("Argument is not a finite floating-point value"); + } + + return x; +}; + +conversions["unrestricted double"] = function (V) { + const x = +V; + + if (isNaN(x)) { + throw new TypeError("Argument is NaN"); + } + + return x; +}; + +// not quite valid, but good enough for JS +conversions["float"] = conversions["double"]; +conversions["unrestricted float"] = conversions["unrestricted double"]; + +conversions["DOMString"] = function (V, opts) { + if (!opts) opts = {}; + + if (opts.treatNullAsEmptyString && V === null) { + return ""; + } + + return String(V); +}; + +conversions["ByteString"] = function (V, opts) { + const x = String(V); + let c = undefined; + for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { + if (c > 255) { + throw new TypeError("Argument is not a valid bytestring"); + } + } + + return x; +}; + +conversions["USVString"] = function (V) { + const S = String(V); + const n = S.length; + const U = []; + for (let i = 0; i < n; ++i) { + const c = S.charCodeAt(i); + if (c < 0xD800 || c > 0xDFFF) { + U.push(String.fromCodePoint(c)); + } else if (0xDC00 <= c && c <= 0xDFFF) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + if (i === n - 1) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + const d = S.charCodeAt(i + 1); + if (0xDC00 <= d && d <= 0xDFFF) { + const a = c & 0x3FF; + const b = d & 0x3FF; + U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b)); + ++i; + } else { + U.push(String.fromCodePoint(0xFFFD)); + } + } + } + } + + return U.join(''); +}; + +conversions["Date"] = function (V, opts) { + if (!(V instanceof Date)) { + throw new TypeError("Argument is not a Date object"); + } + if (isNaN(V)) { + return undefined; + } + + return V; +}; + +conversions["RegExp"] = function (V, opts) { + if (!(V instanceof RegExp)) { + V = new RegExp(V); + } + + return V; +}; diff --git a/node_modules/webidl-conversions/package.json b/node_modules/webidl-conversions/package.json new file mode 100644 index 0000000..c31bc07 --- /dev/null +++ b/node_modules/webidl-conversions/package.json @@ -0,0 +1,23 @@ +{ + "name": "webidl-conversions", + "version": "3.0.1", + "description": "Implements the WebIDL algorithms for converting to and from JavaScript values", + "main": "lib/index.js", + "scripts": { + "test": "mocha test/*.js" + }, + "repository": "jsdom/webidl-conversions", + "keywords": [ + "webidl", + "web", + "types" + ], + "files": [ + "lib/" + ], + "author": "Domenic Denicola (https://domenic.me/)", + "license": "BSD-2-Clause", + "devDependencies": { + "mocha": "^1.21.4" + } +} diff --git a/node_modules/websocket-driver/CHANGELOG.md b/node_modules/websocket-driver/CHANGELOG.md new file mode 100644 index 0000000..cb3945f --- /dev/null +++ b/node_modules/websocket-driver/CHANGELOG.md @@ -0,0 +1,142 @@ +### 0.7.4 / 2020-05-22 + +- Avoid crashing if `process.version` does not contain any digits +- Emit `ping` and `pong` events from the `Server` driver +- Require http-parser-js >=0.5.1 which fixes the bug we addressed in 0.7.3 + +### 0.7.3 / 2019-06-13 + +- Cap version of http-parser-js below 0.4.11, which introduced a bug that + prevents us from handling messages that are part of the same input buffer as + the handshake response if chunked encoding is specified + +### 0.7.2 / 2019-06-13 + +(This version was pulled due to an error when publishing) + +### 0.7.1 / 2019-06-10 + +- Catch any exceptions produced while generating a handshake response and send a + `400 Bad Request` response to the client +- Pick the RFC-6455 protocol version if the request contains any of the headers + used by that version +- Use the `Buffer.alloc()` and `Buffer.from()` functions instead of the unsafe + `Buffer()` constructor +- Handle errors encountered while handling malformed draft-76 requests +- Change license from MIT to Apache 2.0 + +### 0.7.0 / 2017-09-11 + +- Add `ping` and `pong` to the set of events users can listen to +- Replace the bindings to Node's HTTP parser with `http-parser-js` + +### 0.6.5 / 2016-05-20 + +- Don't mutate buffers passed in by the application when masking + +### 0.6.4 / 2016-01-07 + +- If a number is given as input for a frame payload, send it as a string + +### 0.6.3 / 2015-11-06 + +- Reject draft-76 handshakes if their Sec-WebSocket-Key headers are invalid +- Throw a more helpful error if a client is created with an invalid URL + +### 0.6.2 / 2015-07-18 + +- When the peer sends a close frame with no error code, emit 1000 + +### 0.6.1 / 2015-07-13 + +- Use the `buffer.{read,write}UInt{16,32}BE` methods for reading/writing numbers + to buffers rather than including duplicate logic for this + +### 0.6.0 / 2015-07-08 + +- Allow the parser to recover cleanly if event listeners raise an error +- Add a `pong` method for sending unsolicited pong frames + +### 0.5.4 / 2015-03-29 + +- Don't emit extra close frames if we receive a close frame after we already + sent one +- Fail the connection when the driver receives an invalid + `Sec-WebSocket-Extensions` header + +### 0.5.3 / 2015-02-22 + +- Don't treat incoming data as WebSocket frames if a client driver is closed + before receiving the server handshake + +### 0.5.2 / 2015-02-19 + +- Fix compatibility with the HTTP parser on io.js +- Use `websocket-extensions` to make sure messages and close frames are kept in + order +- Don't emit multiple `error` events + +### 0.5.1 / 2014-12-18 + +- Don't allow drivers to be created with unrecognized options + +### 0.5.0 / 2014-12-13 + +- Support protocol extensions via the websocket-extensions module + +### 0.4.0 / 2014-11-08 + +- Support connection via HTTP proxies using `CONNECT` + +### 0.3.6 / 2014-10-04 + +- It is now possible to call `close()` before `start()` and close the driver + +### 0.3.5 / 2014-07-06 + +- Don't hold references to frame buffers after a message has been emitted +- Make sure that `protocol` and `version` are exposed properly by the TCP driver + +### 0.3.4 / 2014-05-08 + +- Don't hold memory-leaking references to I/O buffers after they have been + parsed + +### 0.3.3 / 2014-04-24 + +- Correct the draft-76 status line reason phrase + +### 0.3.2 / 2013-12-29 + +- Expand `maxLength` to cover sequences of continuation frames and + `draft-{75,76}` +- Decrease default maximum frame buffer size to 64MB +- Stop parsing when the protocol enters a failure mode, to save CPU cycles + +### 0.3.1 / 2013-12-03 + +- Add a `maxLength` option to limit allowed frame size +- Don't pre-allocate a message buffer until the whole frame has arrived +- Fix compatibility with Node v0.11 `HTTPParser` + +### 0.3.0 / 2013-09-09 + +- Support client URLs with Basic Auth credentials + +### 0.2.2 / 2013-07-05 + +- No functional changes, just updates to package.json + +### 0.2.1 / 2013-05-17 + +- Export the isSecureRequest() method since faye-websocket relies on it +- Queue sent messages in the client's initial state + +### 0.2.0 / 2013-05-12 + +- Add API for setting and reading headers +- Add Driver.server() method for getting a driver for TCP servers + +### 0.1.0 / 2013-05-04 + +- First stable release diff --git a/node_modules/websocket-driver/LICENSE.md b/node_modules/websocket-driver/LICENSE.md new file mode 100644 index 0000000..9475f06 --- /dev/null +++ b/node_modules/websocket-driver/LICENSE.md @@ -0,0 +1,12 @@ +Copyright 2010-2020 James Coglan + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. diff --git a/node_modules/websocket-driver/README.md b/node_modules/websocket-driver/README.md new file mode 100644 index 0000000..95c33c4 --- /dev/null +++ b/node_modules/websocket-driver/README.md @@ -0,0 +1,370 @@ +# websocket-driver [![Build Status](https://travis-ci.org/faye/websocket-driver-node.svg)](https://travis-ci.org/faye/websocket-driver-node) + +This module provides a complete implementation of the WebSocket protocols that +can be hooked up to any I/O stream. It aims to simplify things by decoupling the +protocol details from the I/O layer, such that users only need to implement code +to stream data in and out of it without needing to know anything about how the +protocol actually works. Think of it as a complete WebSocket system with +pluggable I/O. + +Due to this design, you get a lot of things for free. In particular, if you hook +this module up to some I/O object, it will do all of this for you: + +- Select the correct server-side driver to talk to the client +- Generate and send both server- and client-side handshakes +- Recognize when the handshake phase completes and the WS protocol begins +- Negotiate subprotocol selection based on `Sec-WebSocket-Protocol` +- Negotiate and use extensions via the + [websocket-extensions](https://github.com/faye/websocket-extensions-node) + module +- Buffer sent messages until the handshake process is finished +- Deal with proxies that defer delivery of the draft-76 handshake body +- Notify you when the socket is open and closed and when messages arrive +- Recombine fragmented messages +- Dispatch text, binary, ping, pong and close frames +- Manage the socket-closing handshake process +- Automatically reply to ping frames with a matching pong +- Apply masking to messages sent by the client + +This library was originally extracted from the [Faye](http://faye.jcoglan.com) +project but now aims to provide simple WebSocket support for any Node-based +project. + + +## Installation + +``` +$ npm install websocket-driver +``` + + +## Usage + +This module provides protocol drivers that have the same interface on the server +and on the client. A WebSocket driver is an object with two duplex streams +attached; one for incoming/outgoing messages and one for managing the wire +protocol over an I/O stream. The full API is described below. + + +### Server-side with HTTP + +A Node webserver emits a special event for 'upgrade' requests, and this is where +you should handle WebSockets. You first check whether the request is a +WebSocket, and if so you can create a driver and attach the request's I/O stream +to it. + +```js +var http = require('http'), + websocket = require('websocket-driver'); + +var server = http.createServer(); + +server.on('upgrade', function(request, socket, body) { + if (!websocket.isWebSocket(request)) return; + + var driver = websocket.http(request); + + driver.io.write(body); + socket.pipe(driver.io).pipe(socket); + + driver.messages.on('data', function(message) { + console.log('Got a message', message); + }); + + driver.start(); +}); +``` + +Note the line `driver.io.write(body)` - you must pass the `body` buffer to the +socket driver in order to make certain versions of the protocol work. + + +### Server-side with TCP + +You can also handle WebSocket connections in a bare TCP server, if you're not +using an HTTP server and don't want to implement HTTP parsing yourself. + +The driver will emit a `connect` event when a request is received, and at this +point you can detect whether it's a WebSocket and handle it as such. Here's an +example using the Node `net` module: + +```js +var net = require('net'), + websocket = require('websocket-driver'); + +var server = net.createServer(function(connection) { + var driver = websocket.server(); + + driver.on('connect', function() { + if (websocket.isWebSocket(driver)) { + driver.start(); + } else { + // handle other HTTP requests + } + }); + + driver.on('close', function() { connection.end() }); + connection.on('error', function() {}); + + connection.pipe(driver.io).pipe(connection); + + driver.messages.pipe(driver.messages); +}); + +server.listen(4180); +``` + +In the `connect` event, the driver gains several properties to describe the +request, similar to a Node request object, such as `method`, `url` and +`headers`. However you should remember it's not a real request object; you +cannot write data to it, it only tells you what request data we parsed from the +input. + +If the request has a body, it will be in the `driver.body` buffer, but only as +much of the body as has been piped into the driver when the `connect` event +fires. + + +### Client-side + +Similarly, to implement a WebSocket client you just need to make a driver by +passing in a URL. After this you use the driver API as described below to +process incoming data and send outgoing data. + + +```js +var net = require('net'), + websocket = require('websocket-driver'); + +var driver = websocket.client('ws://www.example.com/socket'), + tcp = net.connect(80, 'www.example.com'); + +tcp.pipe(driver.io).pipe(tcp); + +tcp.on('connect', function() { + driver.start(); +}); + +driver.messages.on('data', function(message) { + console.log('Got a message', message); +}); +``` + +Client drivers have two additional properties for reading the HTTP data that was +sent back by the server: + +- `driver.statusCode` - the integer value of the HTTP status code +- `driver.headers` - an object containing the response headers + + +### HTTP Proxies + +The client driver supports connections via HTTP proxies using the `CONNECT` +method. Instead of sending the WebSocket handshake immediately, it will send a +`CONNECT` request, wait for a `200` response, and then proceed as normal. + +To use this feature, call `driver.proxy(url)` where `url` is the origin of the +proxy, including a username and password if required. This produces a duplex +stream that you should pipe in and out of your TCP connection to the proxy +server. When the proxy emits `connect`, you can then pipe `driver.io` to your +TCP stream and call `driver.start()`. + +```js +var net = require('net'), + websocket = require('websocket-driver'); + +var driver = websocket.client('ws://www.example.com/socket'), + proxy = driver.proxy('http://username:password@proxy.example.com'), + tcp = net.connect(80, 'proxy.example.com'); + +tcp.pipe(proxy).pipe(tcp, { end: false }); + +tcp.on('connect', function() { + proxy.start(); +}); + +proxy.on('connect', function() { + driver.io.pipe(tcp).pipe(driver.io); + driver.start(); +}); + +driver.messages.on('data', function(message) { + console.log('Got a message', message); +}); +``` + +The proxy's `connect` event is also where you should perform a TLS handshake on +your TCP stream, if you are connecting to a `wss:` endpoint. + +In the event that proxy connection fails, `proxy` will emit an `error`. You can +inspect the proxy's response via `proxy.statusCode` and `proxy.headers`. + +```js +proxy.on('error', function(error) { + console.error(error.message); + console.log(proxy.statusCode); + console.log(proxy.headers); +}); +``` + +Before calling `proxy.start()` you can set custom headers using +`proxy.setHeader()`: + +```js +proxy.setHeader('User-Agent', 'node'); +proxy.start(); +``` + + +### Driver API + +Drivers are created using one of the following methods: + +```js +driver = websocket.http(request, options) +driver = websocket.server(options) +driver = websocket.client(url, options) +``` + +The `http` method returns a driver chosen using the headers from a Node HTTP +request object. The `server` method returns a driver that will parse an HTTP +request and then decide which driver to use for it using the `http` method. The +`client` method always returns a driver for the RFC version of the protocol with +masking enabled on outgoing frames. + +The `options` argument is optional, and is an object. It may contain the +following fields: + +- `maxLength` - the maximum allowed size of incoming message frames, in bytes. + The default value is `2^26 - 1`, or 1 byte short of 64 MiB. +- `protocols` - an array of strings representing acceptable subprotocols for use + over the socket. The driver will negotiate one of these to use via the + `Sec-WebSocket-Protocol` header if supported by the other peer. + +A driver has two duplex streams attached to it: + +- **`driver.io`** - this stream should be attached to an I/O socket like a TCP + stream. Pipe incoming TCP chunks to this stream for them to be parsed, and + pipe this stream back into TCP to send outgoing frames. +- **`driver.messages`** - this stream emits messages received over the + WebSocket. Writing to it sends messages to the other peer by emitting frames + via the `driver.io` stream. + +All drivers respond to the following API methods, but some of them are no-ops +depending on whether the client supports the behaviour. + +Note that most of these methods are commands: if they produce data that should +be sent over the socket, they will give this to you by emitting `data` events on +the `driver.io` stream. + +#### `driver.on('open', function(event) {})` + +Adds a callback to execute when the socket becomes open. + +#### `driver.on('message', function(event) {})` + +Adds a callback to execute when a message is received. `event` will have a +`data` attribute containing either a string in the case of a text message or a +`Buffer` in the case of a binary message. + +You can also listen for messages using the `driver.messages.on('data')` event, +which emits strings for text messages and buffers for binary messages. + +#### `driver.on('error', function(event) {})` + +Adds a callback to execute when a protocol error occurs due to the other peer +sending an invalid byte sequence. `event` will have a `message` attribute +describing the error. + +#### `driver.on('close', function(event) {})` + +Adds a callback to execute when the socket becomes closed. The `event` object +has `code` and `reason` attributes. + +#### `driver.on('ping', function(event) {})` + +Adds a callback block to execute when a ping is received. You do not need to +handle this by sending a pong frame yourself; the driver handles this for you. + +#### `driver.on('pong', function(event) {})` + +Adds a callback block to execute when a pong is received. If this was in +response to a ping you sent, you can also handle this event via the +`driver.ping(message, function() { ... })` callback. + +#### `driver.addExtension(extension)` + +Registers a protocol extension whose operation will be negotiated via the +`Sec-WebSocket-Extensions` header. `extension` is any extension compatible with +the [websocket-extensions](https://github.com/faye/websocket-extensions-node) +framework. + +#### `driver.setHeader(name, value)` + +Sets a custom header to be sent as part of the handshake response, either from +the server or from the client. Must be called before `start()`, since this is +when the headers are serialized and sent. + +#### `driver.start()` + +Initiates the protocol by sending the handshake - either the response for a +server-side driver or the request for a client-side one. This should be the +first method you invoke. Returns `true` if and only if a handshake was sent. + +#### `driver.parse(string)` + +Takes a string and parses it, potentially resulting in message events being +emitted (see `on('message')` above) or in data being sent to `driver.io`. You +should send all data you receive via I/O to this method by piping a stream into +`driver.io`. + +#### `driver.text(string)` + +Sends a text message over the socket. If the socket handshake is not yet +complete, the message will be queued until it is. Returns `true` if the message +was sent or queued, and `false` if the socket can no longer send messages. + +This method is equivalent to `driver.messages.write(string)`. + +#### `driver.binary(buffer)` + +Takes a `Buffer` and sends it as a binary message. Will queue and return `true` +or `false` the same way as the `text` method. It will also return `false` if the +driver does not support binary messages. + +This method is equivalent to `driver.messages.write(buffer)`. + +#### `driver.ping(string = '', function() {})` + +Sends a ping frame over the socket, queueing it if necessary. `string` and the +callback are both optional. If a callback is given, it will be invoked when the +socket receives a pong frame whose content matches `string`. Returns `false` if +frames can no longer be sent, or if the driver does not support ping/pong. + +#### `driver.pong(string = '')` + +Sends a pong frame over the socket, queueing it if necessary. `string` is +optional. Returns `false` if frames can no longer be sent, or if the driver does +not support ping/pong. + +You don't need to call this when a ping frame is received; pings are replied to +automatically by the driver. This method is for sending unsolicited pongs. + +#### `driver.close()` + +Initiates the closing handshake if the socket is still open. For drivers with no +closing handshake, this will result in the immediate execution of the +`on('close')` driver. For drivers with a closing handshake, this sends a closing +frame and `emit('close')` will execute when a response is received or a protocol +error occurs. + +#### `driver.version` + +Returns the WebSocket version in use as a string. Will either be `hixie-75`, +`hixie-76` or `hybi-$version`. + +#### `driver.protocol` + +Returns a string containing the selected subprotocol, if any was agreed upon +using the `Sec-WebSocket-Protocol` mechanism. This value becomes available after +`emit('open')` has fired. diff --git a/node_modules/websocket-driver/lib/websocket/driver.js b/node_modules/websocket-driver/lib/websocket/driver.js new file mode 100644 index 0000000..3d701cc --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver.js @@ -0,0 +1,43 @@ +'use strict'; + +// Protocol references: +// +// * http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75 +// * http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76 +// * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17 + +var Base = require('./driver/base'), + Client = require('./driver/client'), + Server = require('./driver/server'); + +var Driver = { + client: function(url, options) { + options = options || {}; + if (options.masking === undefined) options.masking = true; + return new Client(url, options); + }, + + server: function(options) { + options = options || {}; + if (options.requireMasking === undefined) options.requireMasking = true; + return new Server(options); + }, + + http: function() { + return Server.http.apply(Server, arguments); + }, + + isSecureRequest: function(request) { + return Server.isSecureRequest(request); + }, + + isWebSocket: function(request) { + return Base.isWebSocket(request); + }, + + validateOptions: function(options, validKeys) { + Base.validateOptions(options, validKeys); + } +}; + +module.exports = Driver; diff --git a/node_modules/websocket-driver/lib/websocket/driver/base.js b/node_modules/websocket-driver/lib/websocket/driver/base.js new file mode 100644 index 0000000..f05af5f --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/base.js @@ -0,0 +1,193 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer, + Emitter = require('events').EventEmitter, + util = require('util'), + streams = require('../streams'), + Headers = require('./headers'), + Reader = require('./stream_reader'); + +var Base = function(request, url, options) { + Emitter.call(this); + Base.validateOptions(options || {}, ['maxLength', 'masking', 'requireMasking', 'protocols']); + + this._request = request; + this._reader = new Reader(); + this._options = options || {}; + this._maxLength = this._options.maxLength || this.MAX_LENGTH; + this._headers = new Headers(); + this.__queue = []; + this.readyState = 0; + this.url = url; + + this.io = new streams.IO(this); + this.messages = new streams.Messages(this); + this._bindEventListeners(); +}; +util.inherits(Base, Emitter); + +Base.isWebSocket = function(request) { + var connection = request.headers.connection || '', + upgrade = request.headers.upgrade || ''; + + return request.method === 'GET' && + connection.toLowerCase().split(/ *, */).indexOf('upgrade') >= 0 && + upgrade.toLowerCase() === 'websocket'; +}; + +Base.validateOptions = function(options, validKeys) { + for (var key in options) { + if (validKeys.indexOf(key) < 0) + throw new Error('Unrecognized option: ' + key); + } +}; + +var instance = { + // This is 64MB, small enough for an average VPS to handle without + // crashing from process out of memory + MAX_LENGTH: 0x3ffffff, + + STATES: ['connecting', 'open', 'closing', 'closed'], + + _bindEventListeners: function() { + var self = this; + + // Protocol errors are informational and do not have to be handled + this.messages.on('error', function() {}); + + this.on('message', function(event) { + var messages = self.messages; + if (messages.readable) messages.emit('data', event.data); + }); + + this.on('error', function(error) { + var messages = self.messages; + if (messages.readable) messages.emit('error', error); + }); + + this.on('close', function() { + var messages = self.messages; + if (!messages.readable) return; + messages.readable = messages.writable = false; + messages.emit('end'); + }); + }, + + getState: function() { + return this.STATES[this.readyState] || null; + }, + + addExtension: function(extension) { + return false; + }, + + setHeader: function(name, value) { + if (this.readyState > 0) return false; + this._headers.set(name, value); + return true; + }, + + start: function() { + if (this.readyState !== 0) return false; + + if (!Base.isWebSocket(this._request)) + return this._failHandshake(new Error('Not a WebSocket request')); + + var response; + + try { + response = this._handshakeResponse(); + } catch (error) { + return this._failHandshake(error); + } + + this._write(response); + if (this._stage !== -1) this._open(); + return true; + }, + + _failHandshake: function(error) { + var headers = new Headers(); + headers.set('Content-Type', 'text/plain'); + headers.set('Content-Length', Buffer.byteLength(error.message, 'utf8')); + + headers = ['HTTP/1.1 400 Bad Request', headers.toString(), error.message]; + this._write(Buffer.from(headers.join('\r\n'), 'utf8')); + this._fail('protocol_error', error.message); + + return false; + }, + + text: function(message) { + return this.frame(message); + }, + + binary: function(message) { + return false; + }, + + ping: function() { + return false; + }, + + pong: function() { + return false; + }, + + close: function(reason, code) { + if (this.readyState !== 1) return false; + this.readyState = 3; + this.emit('close', new Base.CloseEvent(null, null)); + return true; + }, + + _open: function() { + this.readyState = 1; + this.__queue.forEach(function(args) { this.frame.apply(this, args) }, this); + this.__queue = []; + this.emit('open', new Base.OpenEvent()); + }, + + _queue: function(message) { + this.__queue.push(message); + return true; + }, + + _write: function(chunk) { + var io = this.io; + if (io.readable) io.emit('data', chunk); + }, + + _fail: function(type, message) { + this.readyState = 2; + this.emit('error', new Error(message)); + this.close(); + } +}; + +for (var key in instance) + Base.prototype[key] = instance[key]; + + +Base.ConnectEvent = function() {}; + +Base.OpenEvent = function() {}; + +Base.CloseEvent = function(code, reason) { + this.code = code; + this.reason = reason; +}; + +Base.MessageEvent = function(data) { + this.data = data; +}; + +Base.PingEvent = function(data) { + this.data = data; +}; + +Base.PongEvent = function(data) { + this.data = data; +}; + +module.exports = Base; diff --git a/node_modules/websocket-driver/lib/websocket/driver/client.js b/node_modules/websocket-driver/lib/websocket/driver/client.js new file mode 100644 index 0000000..f24d645 --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/client.js @@ -0,0 +1,142 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer, + crypto = require('crypto'), + url = require('url'), + util = require('util'), + HttpParser = require('../http_parser'), + Base = require('./base'), + Hybi = require('./hybi'), + Proxy = require('./proxy'); + +var Client = function(_url, options) { + this.version = 'hybi-' + Hybi.VERSION; + Hybi.call(this, null, _url, options); + + this.readyState = -1; + this._key = Client.generateKey(); + this._accept = Hybi.generateAccept(this._key); + this._http = new HttpParser('response'); + + var uri = url.parse(this.url), + auth = uri.auth && Buffer.from(uri.auth, 'utf8').toString('base64'); + + if (this.VALID_PROTOCOLS.indexOf(uri.protocol) < 0) + throw new Error(this.url + ' is not a valid WebSocket URL'); + + this._pathname = (uri.pathname || '/') + (uri.search || ''); + + this._headers.set('Host', uri.host); + this._headers.set('Upgrade', 'websocket'); + this._headers.set('Connection', 'Upgrade'); + this._headers.set('Sec-WebSocket-Key', this._key); + this._headers.set('Sec-WebSocket-Version', Hybi.VERSION); + + if (this._protocols.length > 0) + this._headers.set('Sec-WebSocket-Protocol', this._protocols.join(', ')); + + if (auth) + this._headers.set('Authorization', 'Basic ' + auth); +}; +util.inherits(Client, Hybi); + +Client.generateKey = function() { + return crypto.randomBytes(16).toString('base64'); +}; + +var instance = { + VALID_PROTOCOLS: ['ws:', 'wss:'], + + proxy: function(origin, options) { + return new Proxy(this, origin, options); + }, + + start: function() { + if (this.readyState !== -1) return false; + this._write(this._handshakeRequest()); + this.readyState = 0; + return true; + }, + + parse: function(chunk) { + if (this.readyState === 3) return; + if (this.readyState > 0) return Hybi.prototype.parse.call(this, chunk); + + this._http.parse(chunk); + if (!this._http.isComplete()) return; + + this._validateHandshake(); + if (this.readyState === 3) return; + + this._open(); + this.parse(this._http.body); + }, + + _handshakeRequest: function() { + var extensions = this._extensions.generateOffer(); + if (extensions) + this._headers.set('Sec-WebSocket-Extensions', extensions); + + var start = 'GET ' + this._pathname + ' HTTP/1.1', + headers = [start, this._headers.toString(), '']; + + return Buffer.from(headers.join('\r\n'), 'utf8'); + }, + + _failHandshake: function(message) { + message = 'Error during WebSocket handshake: ' + message; + this.readyState = 3; + this.emit('error', new Error(message)); + this.emit('close', new Base.CloseEvent(this.ERRORS.protocol_error, message)); + }, + + _validateHandshake: function() { + this.statusCode = this._http.statusCode; + this.headers = this._http.headers; + + if (this._http.error) + return this._failHandshake(this._http.error.message); + + if (this._http.statusCode !== 101) + return this._failHandshake('Unexpected response code: ' + this._http.statusCode); + + var headers = this._http.headers, + upgrade = headers['upgrade'] || '', + connection = headers['connection'] || '', + accept = headers['sec-websocket-accept'] || '', + protocol = headers['sec-websocket-protocol'] || ''; + + if (upgrade === '') + return this._failHandshake("'Upgrade' header is missing"); + if (upgrade.toLowerCase() !== 'websocket') + return this._failHandshake("'Upgrade' header value is not 'WebSocket'"); + + if (connection === '') + return this._failHandshake("'Connection' header is missing"); + if (connection.toLowerCase() !== 'upgrade') + return this._failHandshake("'Connection' header value is not 'Upgrade'"); + + if (accept !== this._accept) + return this._failHandshake('Sec-WebSocket-Accept mismatch'); + + this.protocol = null; + + if (protocol !== '') { + if (this._protocols.indexOf(protocol) < 0) + return this._failHandshake('Sec-WebSocket-Protocol mismatch'); + else + this.protocol = protocol; + } + + try { + this._extensions.activate(this.headers['sec-websocket-extensions']); + } catch (e) { + return this._failHandshake(e.message); + } + } +}; + +for (var key in instance) + Client.prototype[key] = instance[key]; + +module.exports = Client; diff --git a/node_modules/websocket-driver/lib/websocket/driver/draft75.js b/node_modules/websocket-driver/lib/websocket/driver/draft75.js new file mode 100644 index 0000000..583f985 --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/draft75.js @@ -0,0 +1,123 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer, + Base = require('./base'), + util = require('util'); + +var Draft75 = function(request, url, options) { + Base.apply(this, arguments); + this._stage = 0; + this.version = 'hixie-75'; + + this._headers.set('Upgrade', 'WebSocket'); + this._headers.set('Connection', 'Upgrade'); + this._headers.set('WebSocket-Origin', this._request.headers.origin); + this._headers.set('WebSocket-Location', this.url); +}; +util.inherits(Draft75, Base); + +var instance = { + close: function() { + if (this.readyState === 3) return false; + this.readyState = 3; + this.emit('close', new Base.CloseEvent(null, null)); + return true; + }, + + parse: function(chunk) { + if (this.readyState > 1) return; + + this._reader.put(chunk); + + this._reader.eachByte(function(octet) { + var message; + + switch (this._stage) { + case -1: + this._body.push(octet); + this._sendHandshakeBody(); + break; + + case 0: + this._parseLeadingByte(octet); + break; + + case 1: + this._length = (octet & 0x7F) + 128 * this._length; + + if (this._closing && this._length === 0) { + return this.close(); + } + else if ((octet & 0x80) !== 0x80) { + if (this._length === 0) { + this._stage = 0; + } + else { + this._skipped = 0; + this._stage = 2; + } + } + break; + + case 2: + if (octet === 0xFF) { + this._stage = 0; + message = Buffer.from(this._buffer).toString('utf8', 0, this._buffer.length); + this.emit('message', new Base.MessageEvent(message)); + } + else { + if (this._length) { + this._skipped += 1; + if (this._skipped === this._length) + this._stage = 0; + } else { + this._buffer.push(octet); + if (this._buffer.length > this._maxLength) return this.close(); + } + } + break; + } + }, this); + }, + + frame: function(buffer) { + if (this.readyState === 0) return this._queue([buffer]); + if (this.readyState > 1) return false; + + if (typeof buffer !== 'string') buffer = buffer.toString(); + + var length = Buffer.byteLength(buffer), + frame = Buffer.allocUnsafe(length + 2); + + frame[0] = 0x00; + frame.write(buffer, 1); + frame[frame.length - 1] = 0xFF; + + this._write(frame); + return true; + }, + + _handshakeResponse: function() { + var start = 'HTTP/1.1 101 Web Socket Protocol Handshake', + headers = [start, this._headers.toString(), '']; + + return Buffer.from(headers.join('\r\n'), 'utf8'); + }, + + _parseLeadingByte: function(octet) { + if ((octet & 0x80) === 0x80) { + this._length = 0; + this._stage = 1; + } else { + delete this._length; + delete this._skipped; + this._buffer = []; + this._stage = 2; + } + } +}; + +for (var key in instance) + Draft75.prototype[key] = instance[key]; + +module.exports = Draft75; diff --git a/node_modules/websocket-driver/lib/websocket/driver/draft76.js b/node_modules/websocket-driver/lib/websocket/driver/draft76.js new file mode 100644 index 0000000..bdaab31 --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/draft76.js @@ -0,0 +1,117 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer, + Base = require('./base'), + Draft75 = require('./draft75'), + crypto = require('crypto'), + util = require('util'); + + +var numberFromKey = function(key) { + return parseInt((key.match(/[0-9]/g) || []).join(''), 10); +}; + +var spacesInKey = function(key) { + return (key.match(/ /g) || []).length; +}; + + +var Draft76 = function(request, url, options) { + Draft75.apply(this, arguments); + this._stage = -1; + this._body = []; + this.version = 'hixie-76'; + + this._headers.clear(); + + this._headers.set('Upgrade', 'WebSocket'); + this._headers.set('Connection', 'Upgrade'); + this._headers.set('Sec-WebSocket-Origin', this._request.headers.origin); + this._headers.set('Sec-WebSocket-Location', this.url); +}; +util.inherits(Draft76, Draft75); + +var instance = { + BODY_SIZE: 8, + + start: function() { + if (!Draft75.prototype.start.call(this)) return false; + this._started = true; + this._sendHandshakeBody(); + return true; + }, + + close: function() { + if (this.readyState === 3) return false; + if (this.readyState === 1) this._write(Buffer.from([0xFF, 0x00])); + this.readyState = 3; + this.emit('close', new Base.CloseEvent(null, null)); + return true; + }, + + _handshakeResponse: function() { + var headers = this._request.headers, + key1 = headers['sec-websocket-key1'], + key2 = headers['sec-websocket-key2']; + + if (!key1) throw new Error('Missing required header: Sec-WebSocket-Key1'); + if (!key2) throw new Error('Missing required header: Sec-WebSocket-Key2'); + + var number1 = numberFromKey(key1), + spaces1 = spacesInKey(key1), + + number2 = numberFromKey(key2), + spaces2 = spacesInKey(key2); + + if (number1 % spaces1 !== 0 || number2 % spaces2 !== 0) + throw new Error('Client sent invalid Sec-WebSocket-Key headers'); + + this._keyValues = [number1 / spaces1, number2 / spaces2]; + + var start = 'HTTP/1.1 101 WebSocket Protocol Handshake', + headers = [start, this._headers.toString(), '']; + + return Buffer.from(headers.join('\r\n'), 'binary'); + }, + + _handshakeSignature: function() { + if (this._body.length < this.BODY_SIZE) return null; + + var md5 = crypto.createHash('md5'), + buffer = Buffer.allocUnsafe(8 + this.BODY_SIZE); + + buffer.writeUInt32BE(this._keyValues[0], 0); + buffer.writeUInt32BE(this._keyValues[1], 4); + Buffer.from(this._body).copy(buffer, 8, 0, this.BODY_SIZE); + + md5.update(buffer); + return Buffer.from(md5.digest('binary'), 'binary'); + }, + + _sendHandshakeBody: function() { + if (!this._started) return; + var signature = this._handshakeSignature(); + if (!signature) return; + + this._write(signature); + this._stage = 0; + this._open(); + + if (this._body.length > this.BODY_SIZE) + this.parse(this._body.slice(this.BODY_SIZE)); + }, + + _parseLeadingByte: function(octet) { + if (octet !== 0xFF) + return Draft75.prototype._parseLeadingByte.call(this, octet); + + this._closing = true; + this._length = 0; + this._stage = 1; + } +}; + +for (var key in instance) + Draft76.prototype[key] = instance[key]; + +module.exports = Draft76; diff --git a/node_modules/websocket-driver/lib/websocket/driver/headers.js b/node_modules/websocket-driver/lib/websocket/driver/headers.js new file mode 100644 index 0000000..bc96b7d --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/headers.js @@ -0,0 +1,35 @@ +'use strict'; + +var Headers = function() { + this.clear(); +}; + +Headers.prototype.ALLOWED_DUPLICATES = ['set-cookie', 'set-cookie2', 'warning', 'www-authenticate']; + +Headers.prototype.clear = function() { + this._sent = {}; + this._lines = []; +}; + +Headers.prototype.set = function(name, value) { + if (value === undefined) return; + + name = this._strip(name); + value = this._strip(value); + + var key = name.toLowerCase(); + if (!this._sent.hasOwnProperty(key) || this.ALLOWED_DUPLICATES.indexOf(key) >= 0) { + this._sent[key] = true; + this._lines.push(name + ': ' + value + '\r\n'); + } +}; + +Headers.prototype.toString = function() { + return this._lines.join(''); +}; + +Headers.prototype._strip = function(string) { + return string.toString().replace(/^ */, '').replace(/ *$/, ''); +}; + +module.exports = Headers; diff --git a/node_modules/websocket-driver/lib/websocket/driver/hybi.js b/node_modules/websocket-driver/lib/websocket/driver/hybi.js new file mode 100644 index 0000000..9027f90 --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/hybi.js @@ -0,0 +1,483 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer, + crypto = require('crypto'), + util = require('util'), + Extensions = require('websocket-extensions'), + Base = require('./base'), + Frame = require('./hybi/frame'), + Message = require('./hybi/message'); + +var Hybi = function(request, url, options) { + Base.apply(this, arguments); + + this._extensions = new Extensions(); + this._stage = 0; + this._masking = this._options.masking; + this._protocols = this._options.protocols || []; + this._requireMasking = this._options.requireMasking; + this._pingCallbacks = {}; + + if (typeof this._protocols === 'string') + this._protocols = this._protocols.split(/ *, */); + + if (!this._request) return; + + var protos = this._request.headers['sec-websocket-protocol'], + supported = this._protocols; + + if (protos !== undefined) { + if (typeof protos === 'string') protos = protos.split(/ *, */); + this.protocol = protos.filter(function(p) { return supported.indexOf(p) >= 0 })[0]; + } + + this.version = 'hybi-' + Hybi.VERSION; +}; +util.inherits(Hybi, Base); + +Hybi.VERSION = '13'; + +Hybi.mask = function(payload, mask, offset) { + if (!mask || mask.length === 0) return payload; + offset = offset || 0; + + for (var i = 0, n = payload.length - offset; i < n; i++) { + payload[offset + i] = payload[offset + i] ^ mask[i % 4]; + } + return payload; +}; + +Hybi.generateAccept = function(key) { + var sha1 = crypto.createHash('sha1'); + sha1.update(key + Hybi.GUID); + return sha1.digest('base64'); +}; + +Hybi.GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; + +var instance = { + FIN: 0x80, + MASK: 0x80, + RSV1: 0x40, + RSV2: 0x20, + RSV3: 0x10, + OPCODE: 0x0F, + LENGTH: 0x7F, + + OPCODES: { + continuation: 0, + text: 1, + binary: 2, + close: 8, + ping: 9, + pong: 10 + }, + + OPCODE_CODES: [0, 1, 2, 8, 9, 10], + MESSAGE_OPCODES: [0, 1, 2], + OPENING_OPCODES: [1, 2], + + ERRORS: { + normal_closure: 1000, + going_away: 1001, + protocol_error: 1002, + unacceptable: 1003, + encoding_error: 1007, + policy_violation: 1008, + too_large: 1009, + extension_error: 1010, + unexpected_condition: 1011 + }, + + ERROR_CODES: [1000, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011], + DEFAULT_ERROR_CODE: 1000, + MIN_RESERVED_ERROR: 3000, + MAX_RESERVED_ERROR: 4999, + + // http://www.w3.org/International/questions/qa-forms-utf-8.en.php + UTF8_MATCH: /^([\x00-\x7F]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2})*$/, + + addExtension: function(extension) { + this._extensions.add(extension); + return true; + }, + + parse: function(chunk) { + this._reader.put(chunk); + var buffer = true; + while (buffer) { + switch (this._stage) { + case 0: + buffer = this._reader.read(1); + if (buffer) this._parseOpcode(buffer[0]); + break; + + case 1: + buffer = this._reader.read(1); + if (buffer) this._parseLength(buffer[0]); + break; + + case 2: + buffer = this._reader.read(this._frame.lengthBytes); + if (buffer) this._parseExtendedLength(buffer); + break; + + case 3: + buffer = this._reader.read(4); + if (buffer) { + this._stage = 4; + this._frame.maskingKey = buffer; + } + break; + + case 4: + buffer = this._reader.read(this._frame.length); + if (buffer) { + this._stage = 0; + this._emitFrame(buffer); + } + break; + + default: + buffer = null; + } + } + }, + + text: function(message) { + if (this.readyState > 1) return false; + return this.frame(message, 'text'); + }, + + binary: function(message) { + if (this.readyState > 1) return false; + return this.frame(message, 'binary'); + }, + + ping: function(message, callback) { + if (this.readyState > 1) return false; + message = message || ''; + if (callback) this._pingCallbacks[message] = callback; + return this.frame(message, 'ping'); + }, + + pong: function(message) { + if (this.readyState > 1) return false; + message = message ||''; + return this.frame(message, 'pong'); + }, + + close: function(reason, code) { + reason = reason || ''; + code = code || this.ERRORS.normal_closure; + + if (this.readyState <= 0) { + this.readyState = 3; + this.emit('close', new Base.CloseEvent(code, reason)); + return true; + } else if (this.readyState === 1) { + this.readyState = 2; + this._extensions.close(function() { this.frame(reason, 'close', code) }, this); + return true; + } else { + return false; + } + }, + + frame: function(buffer, type, code) { + if (this.readyState <= 0) return this._queue([buffer, type, code]); + if (this.readyState > 2) return false; + + if (buffer instanceof Array) buffer = Buffer.from(buffer); + if (typeof buffer === 'number') buffer = buffer.toString(); + + var message = new Message(), + isText = (typeof buffer === 'string'), + payload, copy; + + message.rsv1 = message.rsv2 = message.rsv3 = false; + message.opcode = this.OPCODES[type || (isText ? 'text' : 'binary')]; + + payload = isText ? Buffer.from(buffer, 'utf8') : buffer; + + if (code) { + copy = payload; + payload = Buffer.allocUnsafe(2 + copy.length); + payload.writeUInt16BE(code, 0); + copy.copy(payload, 2); + } + message.data = payload; + + var onMessageReady = function(message) { + var frame = new Frame(); + + frame.final = true; + frame.rsv1 = message.rsv1; + frame.rsv2 = message.rsv2; + frame.rsv3 = message.rsv3; + frame.opcode = message.opcode; + frame.masked = !!this._masking; + frame.length = message.data.length; + frame.payload = message.data; + + if (frame.masked) frame.maskingKey = crypto.randomBytes(4); + + this._sendFrame(frame); + }; + + if (this.MESSAGE_OPCODES.indexOf(message.opcode) >= 0) + this._extensions.processOutgoingMessage(message, function(error, message) { + if (error) return this._fail('extension_error', error.message); + onMessageReady.call(this, message); + }, this); + else + onMessageReady.call(this, message); + + return true; + }, + + _sendFrame: function(frame) { + var length = frame.length, + header = (length <= 125) ? 2 : (length <= 65535 ? 4 : 10), + offset = header + (frame.masked ? 4 : 0), + buffer = Buffer.allocUnsafe(offset + length), + masked = frame.masked ? this.MASK : 0; + + buffer[0] = (frame.final ? this.FIN : 0) | + (frame.rsv1 ? this.RSV1 : 0) | + (frame.rsv2 ? this.RSV2 : 0) | + (frame.rsv3 ? this.RSV3 : 0) | + frame.opcode; + + if (length <= 125) { + buffer[1] = masked | length; + } else if (length <= 65535) { + buffer[1] = masked | 126; + buffer.writeUInt16BE(length, 2); + } else { + buffer[1] = masked | 127; + buffer.writeUInt32BE(Math.floor(length / 0x100000000), 2); + buffer.writeUInt32BE(length % 0x100000000, 6); + } + + frame.payload.copy(buffer, offset); + + if (frame.masked) { + frame.maskingKey.copy(buffer, header); + Hybi.mask(buffer, frame.maskingKey, offset); + } + + this._write(buffer); + }, + + _handshakeResponse: function() { + var secKey = this._request.headers['sec-websocket-key'], + version = this._request.headers['sec-websocket-version']; + + if (version !== Hybi.VERSION) + throw new Error('Unsupported WebSocket version: ' + version); + + if (typeof secKey !== 'string') + throw new Error('Missing handshake request header: Sec-WebSocket-Key'); + + this._headers.set('Upgrade', 'websocket'); + this._headers.set('Connection', 'Upgrade'); + this._headers.set('Sec-WebSocket-Accept', Hybi.generateAccept(secKey)); + + if (this.protocol) this._headers.set('Sec-WebSocket-Protocol', this.protocol); + + var extensions = this._extensions.generateResponse(this._request.headers['sec-websocket-extensions']); + if (extensions) this._headers.set('Sec-WebSocket-Extensions', extensions); + + var start = 'HTTP/1.1 101 Switching Protocols', + headers = [start, this._headers.toString(), '']; + + return Buffer.from(headers.join('\r\n'), 'utf8'); + }, + + _shutdown: function(code, reason, error) { + delete this._frame; + delete this._message; + this._stage = 5; + + var sendCloseFrame = (this.readyState === 1); + this.readyState = 2; + + this._extensions.close(function() { + if (sendCloseFrame) this.frame(reason, 'close', code); + this.readyState = 3; + if (error) this.emit('error', new Error(reason)); + this.emit('close', new Base.CloseEvent(code, reason)); + }, this); + }, + + _fail: function(type, message) { + if (this.readyState > 1) return; + this._shutdown(this.ERRORS[type], message, true); + }, + + _parseOpcode: function(octet) { + var rsvs = [this.RSV1, this.RSV2, this.RSV3].map(function(rsv) { + return (octet & rsv) === rsv; + }); + + var frame = this._frame = new Frame(); + + frame.final = (octet & this.FIN) === this.FIN; + frame.rsv1 = rsvs[0]; + frame.rsv2 = rsvs[1]; + frame.rsv3 = rsvs[2]; + frame.opcode = (octet & this.OPCODE); + + this._stage = 1; + + if (!this._extensions.validFrameRsv(frame)) + return this._fail('protocol_error', + 'One or more reserved bits are on: reserved1 = ' + (frame.rsv1 ? 1 : 0) + + ', reserved2 = ' + (frame.rsv2 ? 1 : 0) + + ', reserved3 = ' + (frame.rsv3 ? 1 : 0)); + + if (this.OPCODE_CODES.indexOf(frame.opcode) < 0) + return this._fail('protocol_error', 'Unrecognized frame opcode: ' + frame.opcode); + + if (this.MESSAGE_OPCODES.indexOf(frame.opcode) < 0 && !frame.final) + return this._fail('protocol_error', 'Received fragmented control frame: opcode = ' + frame.opcode); + + if (this._message && this.OPENING_OPCODES.indexOf(frame.opcode) >= 0) + return this._fail('protocol_error', 'Received new data frame but previous continuous frame is unfinished'); + }, + + _parseLength: function(octet) { + var frame = this._frame; + frame.masked = (octet & this.MASK) === this.MASK; + frame.length = (octet & this.LENGTH); + + if (frame.length >= 0 && frame.length <= 125) { + this._stage = frame.masked ? 3 : 4; + if (!this._checkFrameLength()) return; + } else { + this._stage = 2; + frame.lengthBytes = (frame.length === 126 ? 2 : 8); + } + + if (this._requireMasking && !frame.masked) + return this._fail('unacceptable', 'Received unmasked frame but masking is required'); + }, + + _parseExtendedLength: function(buffer) { + var frame = this._frame; + frame.length = this._readUInt(buffer); + + this._stage = frame.masked ? 3 : 4; + + if (this.MESSAGE_OPCODES.indexOf(frame.opcode) < 0 && frame.length > 125) + return this._fail('protocol_error', 'Received control frame having too long payload: ' + frame.length); + + if (!this._checkFrameLength()) return; + }, + + _checkFrameLength: function() { + var length = this._message ? this._message.length : 0; + + if (length + this._frame.length > this._maxLength) { + this._fail('too_large', 'WebSocket frame length too large'); + return false; + } else { + return true; + } + }, + + _emitFrame: function(buffer) { + var frame = this._frame, + payload = frame.payload = Hybi.mask(buffer, frame.maskingKey), + opcode = frame.opcode, + message, + code, reason, + callbacks, callback; + + delete this._frame; + + if (opcode === this.OPCODES.continuation) { + if (!this._message) return this._fail('protocol_error', 'Received unexpected continuation frame'); + this._message.pushFrame(frame); + } + + if (opcode === this.OPCODES.text || opcode === this.OPCODES.binary) { + this._message = new Message(); + this._message.pushFrame(frame); + } + + if (frame.final && this.MESSAGE_OPCODES.indexOf(opcode) >= 0) + return this._emitMessage(this._message); + + if (opcode === this.OPCODES.close) { + code = (payload.length >= 2) ? payload.readUInt16BE(0) : null; + reason = (payload.length > 2) ? this._encode(payload.slice(2)) : null; + + if (!(payload.length === 0) && + !(code !== null && code >= this.MIN_RESERVED_ERROR && code <= this.MAX_RESERVED_ERROR) && + this.ERROR_CODES.indexOf(code) < 0) + code = this.ERRORS.protocol_error; + + if (payload.length > 125 || (payload.length > 2 && !reason)) + code = this.ERRORS.protocol_error; + + this._shutdown(code || this.DEFAULT_ERROR_CODE, reason || ''); + } + + if (opcode === this.OPCODES.ping) { + this.frame(payload, 'pong'); + this.emit('ping', new Base.PingEvent(payload.toString())) + } + + if (opcode === this.OPCODES.pong) { + callbacks = this._pingCallbacks; + message = this._encode(payload); + callback = callbacks[message]; + + delete callbacks[message]; + if (callback) callback() + + this.emit('pong', new Base.PongEvent(payload.toString())) + } + }, + + _emitMessage: function(message) { + var message = this._message; + message.read(); + + delete this._message; + + this._extensions.processIncomingMessage(message, function(error, message) { + if (error) return this._fail('extension_error', error.message); + + var payload = message.data; + if (message.opcode === this.OPCODES.text) payload = this._encode(payload); + + if (payload === null) + return this._fail('encoding_error', 'Could not decode a text frame as UTF-8'); + else + this.emit('message', new Base.MessageEvent(payload)); + }, this); + }, + + _encode: function(buffer) { + try { + var string = buffer.toString('binary', 0, buffer.length); + if (!this.UTF8_MATCH.test(string)) return null; + } catch (e) {} + return buffer.toString('utf8', 0, buffer.length); + }, + + _readUInt: function(buffer) { + if (buffer.length === 2) return buffer.readUInt16BE(0); + + return buffer.readUInt32BE(0) * 0x100000000 + + buffer.readUInt32BE(4); + } +}; + +for (var key in instance) + Hybi.prototype[key] = instance[key]; + +module.exports = Hybi; diff --git a/node_modules/websocket-driver/lib/websocket/driver/hybi/frame.js b/node_modules/websocket-driver/lib/websocket/driver/hybi/frame.js new file mode 100644 index 0000000..0fb003f --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/hybi/frame.js @@ -0,0 +1,21 @@ +'use strict'; + +var Frame = function() {}; + +var instance = { + final: false, + rsv1: false, + rsv2: false, + rsv3: false, + opcode: null, + masked: false, + maskingKey: null, + lengthBytes: 1, + length: 0, + payload: null +}; + +for (var key in instance) + Frame.prototype[key] = instance[key]; + +module.exports = Frame; diff --git a/node_modules/websocket-driver/lib/websocket/driver/hybi/message.js b/node_modules/websocket-driver/lib/websocket/driver/hybi/message.js new file mode 100644 index 0000000..e881273 --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/hybi/message.js @@ -0,0 +1,34 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer; + +var Message = function() { + this.rsv1 = false; + this.rsv2 = false; + this.rsv3 = false; + this.opcode = null; + this.length = 0; + this._chunks = []; +}; + +var instance = { + read: function() { + return this.data = this.data || Buffer.concat(this._chunks, this.length); + }, + + pushFrame: function(frame) { + this.rsv1 = this.rsv1 || frame.rsv1; + this.rsv2 = this.rsv2 || frame.rsv2; + this.rsv3 = this.rsv3 || frame.rsv3; + + if (this.opcode === null) this.opcode = frame.opcode; + + this._chunks.push(frame.payload); + this.length += frame.length; + } +}; + +for (var key in instance) + Message.prototype[key] = instance[key]; + +module.exports = Message; diff --git a/node_modules/websocket-driver/lib/websocket/driver/proxy.js b/node_modules/websocket-driver/lib/websocket/driver/proxy.js new file mode 100644 index 0000000..2fdd32e --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/proxy.js @@ -0,0 +1,99 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer, + Stream = require('stream').Stream, + url = require('url'), + util = require('util'), + Base = require('./base'), + Headers = require('./headers'), + HttpParser = require('../http_parser'); + +var PORTS = { 'ws:': 80, 'wss:': 443 }; + +var Proxy = function(client, origin, options) { + this._client = client; + this._http = new HttpParser('response'); + this._origin = (typeof client.url === 'object') ? client.url : url.parse(client.url); + this._url = (typeof origin === 'object') ? origin : url.parse(origin); + this._options = options || {}; + this._state = 0; + + this.readable = this.writable = true; + this._paused = false; + + this._headers = new Headers(); + this._headers.set('Host', this._origin.host); + this._headers.set('Connection', 'keep-alive'); + this._headers.set('Proxy-Connection', 'keep-alive'); + + var auth = this._url.auth && Buffer.from(this._url.auth, 'utf8').toString('base64'); + if (auth) this._headers.set('Proxy-Authorization', 'Basic ' + auth); +}; +util.inherits(Proxy, Stream); + +var instance = { + setHeader: function(name, value) { + if (this._state !== 0) return false; + this._headers.set(name, value); + return true; + }, + + start: function() { + if (this._state !== 0) return false; + this._state = 1; + + var origin = this._origin, + port = origin.port || PORTS[origin.protocol], + start = 'CONNECT ' + origin.hostname + ':' + port + ' HTTP/1.1'; + + var headers = [start, this._headers.toString(), '']; + + this.emit('data', Buffer.from(headers.join('\r\n'), 'utf8')); + return true; + }, + + pause: function() { + this._paused = true; + }, + + resume: function() { + this._paused = false; + this.emit('drain'); + }, + + write: function(chunk) { + if (!this.writable) return false; + + this._http.parse(chunk); + if (!this._http.isComplete()) return !this._paused; + + this.statusCode = this._http.statusCode; + this.headers = this._http.headers; + + if (this.statusCode === 200) { + this.emit('connect', new Base.ConnectEvent()); + } else { + var message = "Can't establish a connection to the server at " + this._origin.href; + this.emit('error', new Error(message)); + } + this.end(); + return !this._paused; + }, + + end: function(chunk) { + if (!this.writable) return; + if (chunk !== undefined) this.write(chunk); + this.readable = this.writable = false; + this.emit('close'); + this.emit('end'); + }, + + destroy: function() { + this.end(); + } +}; + +for (var key in instance) + Proxy.prototype[key] = instance[key]; + +module.exports = Proxy; diff --git a/node_modules/websocket-driver/lib/websocket/driver/server.js b/node_modules/websocket-driver/lib/websocket/driver/server.js new file mode 100644 index 0000000..dc635b0 --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/server.js @@ -0,0 +1,112 @@ +'use strict'; + +var util = require('util'), + HttpParser = require('../http_parser'), + Base = require('./base'), + Draft75 = require('./draft75'), + Draft76 = require('./draft76'), + Hybi = require('./hybi'); + +var Server = function(options) { + Base.call(this, null, null, options); + this._http = new HttpParser('request'); +}; +util.inherits(Server, Base); + +var instance = { + EVENTS: ['open', 'message', 'error', 'close', 'ping', 'pong'], + + _bindEventListeners: function() { + this.messages.on('error', function() {}); + this.on('error', function() {}); + }, + + parse: function(chunk) { + if (this._delegate) return this._delegate.parse(chunk); + + this._http.parse(chunk); + if (!this._http.isComplete()) return; + + this.method = this._http.method; + this.url = this._http.url; + this.headers = this._http.headers; + this.body = this._http.body; + + var self = this; + this._delegate = Server.http(this, this._options); + this._delegate.messages = this.messages; + this._delegate.io = this.io; + this._open(); + + this.EVENTS.forEach(function(event) { + this._delegate.on(event, function(e) { self.emit(event, e) }); + }, this); + + this.protocol = this._delegate.protocol; + this.version = this._delegate.version; + + this.parse(this._http.body); + this.emit('connect', new Base.ConnectEvent()); + }, + + _open: function() { + this.__queue.forEach(function(msg) { + this._delegate[msg[0]].apply(this._delegate, msg[1]); + }, this); + this.__queue = []; + } +}; + +['addExtension', 'setHeader', 'start', 'frame', 'text', 'binary', 'ping', 'close'].forEach(function(method) { + instance[method] = function() { + if (this._delegate) { + return this._delegate[method].apply(this._delegate, arguments); + } else { + this.__queue.push([method, arguments]); + return true; + } + }; +}); + +for (var key in instance) + Server.prototype[key] = instance[key]; + +Server.isSecureRequest = function(request) { + if (request.connection && request.connection.authorized !== undefined) return true; + if (request.socket && request.socket.secure) return true; + + var headers = request.headers; + if (!headers) return false; + if (headers['https'] === 'on') return true; + if (headers['x-forwarded-ssl'] === 'on') return true; + if (headers['x-forwarded-scheme'] === 'https') return true; + if (headers['x-forwarded-proto'] === 'https') return true; + + return false; +}; + +Server.determineUrl = function(request) { + var scheme = this.isSecureRequest(request) ? 'wss:' : 'ws:'; + return scheme + '//' + request.headers.host + request.url; +}; + +Server.http = function(request, options) { + options = options || {}; + if (options.requireMasking === undefined) options.requireMasking = true; + + var headers = request.headers, + version = headers['sec-websocket-version'], + key = headers['sec-websocket-key'], + key1 = headers['sec-websocket-key1'], + key2 = headers['sec-websocket-key2'], + url = this.determineUrl(request); + + if (version || key) + return new Hybi(request, url, options); + else if (key1 || key2) + return new Draft76(request, url, options); + else + return new Draft75(request, url, options); +}; + +module.exports = Server; diff --git a/node_modules/websocket-driver/lib/websocket/driver/stream_reader.js b/node_modules/websocket-driver/lib/websocket/driver/stream_reader.js new file mode 100644 index 0000000..3564da8 --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/stream_reader.js @@ -0,0 +1,69 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer; + +var StreamReader = function() { + this._queue = []; + this._queueSize = 0; + this._offset = 0; +}; + +StreamReader.prototype.put = function(buffer) { + if (!buffer || buffer.length === 0) return; + if (!Buffer.isBuffer(buffer)) buffer = Buffer.from(buffer); + this._queue.push(buffer); + this._queueSize += buffer.length; +}; + +StreamReader.prototype.read = function(length) { + if (length > this._queueSize) return null; + if (length === 0) return Buffer.alloc(0); + + this._queueSize -= length; + + var queue = this._queue, + remain = length, + first = queue[0], + buffers, buffer; + + if (first.length >= length) { + if (first.length === length) { + return queue.shift(); + } else { + buffer = first.slice(0, length); + queue[0] = first.slice(length); + return buffer; + } + } + + for (var i = 0, n = queue.length; i < n; i++) { + if (remain < queue[i].length) break; + remain -= queue[i].length; + } + buffers = queue.splice(0, i); + + if (remain > 0 && queue.length > 0) { + buffers.push(queue[0].slice(0, remain)); + queue[0] = queue[0].slice(remain); + } + return Buffer.concat(buffers, length); +}; + +StreamReader.prototype.eachByte = function(callback, context) { + var buffer, n, index; + + while (this._queue.length > 0) { + buffer = this._queue[0]; + n = buffer.length; + + while (this._offset < n) { + index = this._offset; + this._offset += 1; + callback.call(context, buffer[index]); + } + this._offset = 0; + this._queue.shift(); + } +}; + +module.exports = StreamReader; diff --git a/node_modules/websocket-driver/lib/websocket/http_parser.js b/node_modules/websocket-driver/lib/websocket/http_parser.js new file mode 100644 index 0000000..1396656 --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/http_parser.js @@ -0,0 +1,135 @@ +'use strict'; + +var NodeHTTPParser = require('http-parser-js').HTTPParser, + Buffer = require('safe-buffer').Buffer; + +var TYPES = { + request: NodeHTTPParser.REQUEST || 'request', + response: NodeHTTPParser.RESPONSE || 'response' +}; + +var HttpParser = function(type) { + this._type = type; + this._parser = new NodeHTTPParser(TYPES[type]); + this._complete = false; + this.headers = {}; + + var current = null, + self = this; + + this._parser.onHeaderField = function(b, start, length) { + current = b.toString('utf8', start, start + length).toLowerCase(); + }; + + this._parser.onHeaderValue = function(b, start, length) { + var value = b.toString('utf8', start, start + length); + + if (self.headers.hasOwnProperty(current)) + self.headers[current] += ', ' + value; + else + self.headers[current] = value; + }; + + this._parser.onHeadersComplete = this._parser[NodeHTTPParser.kOnHeadersComplete] = + function(majorVersion, minorVersion, headers, method, pathname, statusCode) { + var info = arguments[0]; + + if (typeof info === 'object') { + method = info.method; + pathname = info.url; + statusCode = info.statusCode; + headers = info.headers; + } + + self.method = (typeof method === 'number') ? HttpParser.METHODS[method] : method; + self.statusCode = statusCode; + self.url = pathname; + + if (!headers) return; + + for (var i = 0, n = headers.length, key, value; i < n; i += 2) { + key = headers[i].toLowerCase(); + value = headers[i+1]; + if (self.headers.hasOwnProperty(key)) + self.headers[key] += ', ' + value; + else + self.headers[key] = value; + } + + self._complete = true; + }; +}; + +HttpParser.METHODS = { + 0: 'DELETE', + 1: 'GET', + 2: 'HEAD', + 3: 'POST', + 4: 'PUT', + 5: 'CONNECT', + 6: 'OPTIONS', + 7: 'TRACE', + 8: 'COPY', + 9: 'LOCK', + 10: 'MKCOL', + 11: 'MOVE', + 12: 'PROPFIND', + 13: 'PROPPATCH', + 14: 'SEARCH', + 15: 'UNLOCK', + 16: 'BIND', + 17: 'REBIND', + 18: 'UNBIND', + 19: 'ACL', + 20: 'REPORT', + 21: 'MKACTIVITY', + 22: 'CHECKOUT', + 23: 'MERGE', + 24: 'M-SEARCH', + 25: 'NOTIFY', + 26: 'SUBSCRIBE', + 27: 'UNSUBSCRIBE', + 28: 'PATCH', + 29: 'PURGE', + 30: 'MKCALENDAR', + 31: 'LINK', + 32: 'UNLINK' +}; + +var VERSION = process.version + ? process.version.match(/[0-9]+/g).map(function(n) { return parseInt(n, 10) }) + : []; + +if (VERSION[0] === 0 && VERSION[1] === 12) { + HttpParser.METHODS[16] = 'REPORT'; + HttpParser.METHODS[17] = 'MKACTIVITY'; + HttpParser.METHODS[18] = 'CHECKOUT'; + HttpParser.METHODS[19] = 'MERGE'; + HttpParser.METHODS[20] = 'M-SEARCH'; + HttpParser.METHODS[21] = 'NOTIFY'; + HttpParser.METHODS[22] = 'SUBSCRIBE'; + HttpParser.METHODS[23] = 'UNSUBSCRIBE'; + HttpParser.METHODS[24] = 'PATCH'; + HttpParser.METHODS[25] = 'PURGE'; +} + +HttpParser.prototype.isComplete = function() { + return this._complete; +}; + +HttpParser.prototype.parse = function(chunk) { + var consumed = this._parser.execute(chunk, 0, chunk.length); + + if (typeof consumed !== 'number') { + this.error = consumed; + this._complete = true; + return; + } + + if (this._complete) + this.body = (consumed < chunk.length) + ? chunk.slice(consumed) + : Buffer.alloc(0); +}; + +module.exports = HttpParser; diff --git a/node_modules/websocket-driver/lib/websocket/streams.js b/node_modules/websocket-driver/lib/websocket/streams.js new file mode 100644 index 0000000..96ab31f --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/streams.js @@ -0,0 +1,146 @@ +'use strict'; + +/** + +Streams in a WebSocket connection +--------------------------------- + +We model a WebSocket as two duplex streams: one stream is for the wire protocol +over an I/O socket, and the other is for incoming/outgoing messages. + + + +----------+ +---------+ +----------+ + [1] write(chunk) -->| ~~~~~~~~ +----->| parse() +----->| ~~~~~~~~ +--> emit('data') [2] + | | +----+----+ | | + | | | | | + | IO | | [5] | Messages | + | | V | | + | | +---------+ | | + [4] emit('data') <--+ ~~~~~~~~ |<-----+ frame() |<-----+ ~~~~~~~~ |<-- write(chunk) [3] + +----------+ +---------+ +----------+ + + +Message transfer in each direction is simple: IO receives a byte stream [1] and +sends this stream for parsing. The parser will periodically emit a complete +message text on the Messages stream [2]. Similarly, when messages are written +to the Messages stream [3], they are framed using the WebSocket wire format and +emitted via IO [4]. + +There is a feedback loop via [5] since some input from [1] will be things like +ping, pong and close frames. In these cases the protocol responds by emitting +responses directly back to [4] rather than emitting messages via [2]. + +For the purposes of flow control, we consider the sources of each Readable +stream to be as follows: + +* [2] receives input from [1] +* [4] receives input from [1] and [3] + +The classes below express the relationships described above without prescribing +anything about how parse() and frame() work, other than assuming they emit +'data' events to the IO and Messages streams. They will work with any protocol +driver having these two methods. +**/ + + +var Stream = require('stream').Stream, + util = require('util'); + + +var IO = function(driver) { + this.readable = this.writable = true; + this._paused = false; + this._driver = driver; +}; +util.inherits(IO, Stream); + +// The IO pause() and resume() methods will be called when the socket we are +// piping to gets backed up and drains. Since IO output [4] comes from IO input +// [1] and Messages input [3], we need to tell both of those to return false +// from write() when this stream is paused. + +IO.prototype.pause = function() { + this._paused = true; + this._driver.messages._paused = true; +}; + +IO.prototype.resume = function() { + this._paused = false; + this.emit('drain'); + + var messages = this._driver.messages; + messages._paused = false; + messages.emit('drain'); +}; + +// When we receive input from a socket, send it to the parser and tell the +// source whether to back off. +IO.prototype.write = function(chunk) { + if (!this.writable) return false; + this._driver.parse(chunk); + return !this._paused; +}; + +// The IO end() method will be called when the socket piping into it emits +// 'close' or 'end', i.e. the socket is closed. In this situation the Messages +// stream will not emit any more data so we emit 'end'. +IO.prototype.end = function(chunk) { + if (!this.writable) return; + if (chunk !== undefined) this.write(chunk); + this.writable = false; + + var messages = this._driver.messages; + if (messages.readable) { + messages.readable = messages.writable = false; + messages.emit('end'); + } +}; + +IO.prototype.destroy = function() { + this.end(); +}; + + +var Messages = function(driver) { + this.readable = this.writable = true; + this._paused = false; + this._driver = driver; +}; +util.inherits(Messages, Stream); + +// The Messages pause() and resume() methods will be called when the app that's +// processing the messages gets backed up and drains. If we're emitting +// messages too fast we should tell the source to slow down. Message output [2] +// comes from IO input [1]. + +Messages.prototype.pause = function() { + this._driver.io._paused = true; +}; + +Messages.prototype.resume = function() { + this._driver.io._paused = false; + this._driver.io.emit('drain'); +}; + +// When we receive messages from the user, send them to the formatter and tell +// the source whether to back off. +Messages.prototype.write = function(message) { + if (!this.writable) return false; + if (typeof message === 'string') this._driver.text(message); + else this._driver.binary(message); + return !this._paused; +}; + +// The Messages end() method will be called when a stream piping into it emits +// 'end'. Many streams may be piped into the WebSocket and one of them ending +// does not mean the whole socket is done, so just process the input and move +// on leaving the socket open. +Messages.prototype.end = function(message) { + if (message !== undefined) this.write(message); +}; + +Messages.prototype.destroy = function() {}; + + +exports.IO = IO; +exports.Messages = Messages; diff --git a/node_modules/websocket-driver/package.json b/node_modules/websocket-driver/package.json new file mode 100644 index 0000000..fab2506 --- /dev/null +++ b/node_modules/websocket-driver/package.json @@ -0,0 +1,35 @@ +{ + "name": "websocket-driver", + "description": "WebSocket protocol handler with pluggable I/O", + "homepage": "https://github.com/faye/websocket-driver-node", + "author": "James Coglan (http://jcoglan.com/)", + "keywords": [ + "websocket" + ], + "license": "Apache-2.0", + "version": "0.7.4", + "engines": { + "node": ">=0.8.0" + }, + "files": [ + "lib" + ], + "main": "./lib/websocket/driver", + "dependencies": { + "http-parser-js": ">=0.5.1", + "safe-buffer": ">=5.1.0", + "websocket-extensions": ">=0.1.1" + }, + "devDependencies": { + "jstest": "*", + "permessage-deflate": "*" + }, + "scripts": { + "test": "jstest spec/runner.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/faye/websocket-driver-node.git" + }, + "bugs": "https://github.com/faye/websocket-driver-node/issues" +} diff --git a/node_modules/websocket-extensions/CHANGELOG.md b/node_modules/websocket-extensions/CHANGELOG.md new file mode 100644 index 0000000..bb84f5a --- /dev/null +++ b/node_modules/websocket-extensions/CHANGELOG.md @@ -0,0 +1,28 @@ +### 0.1.4 / 2020-06-02 + +- Remove a ReDoS vulnerability in the header parser (CVE-2020-7662, reported by + Robert McLaughlin) +- Change license from MIT to Apache 2.0 + +### 0.1.3 / 2017-11-11 + +- Accept extension names and parameters including uppercase letters +- Handle extension names that clash with `Object.prototype` properties + +### 0.1.2 / 2017-09-10 + +- Catch synchronous exceptions thrown when calling an extension +- Fix race condition caused when a message is pushed after a cell has stopped + due to an error +- Fix failure of `close()` to return if a message that's queued after one that + produces an error never finishes being processed + +### 0.1.1 / 2015-02-19 + +- Prevent sessions being closed before they have finished processing messages +- Add a callback to `Extensions.close()` so the caller can tell when it's safe + to close the socket + +### 0.1.0 / 2014-12-12 + +- Initial release diff --git a/node_modules/websocket-extensions/LICENSE.md b/node_modules/websocket-extensions/LICENSE.md new file mode 100644 index 0000000..3a88e51 --- /dev/null +++ b/node_modules/websocket-extensions/LICENSE.md @@ -0,0 +1,12 @@ +Copyright 2014-2020 James Coglan + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. diff --git a/node_modules/websocket-extensions/README.md b/node_modules/websocket-extensions/README.md new file mode 100644 index 0000000..68694ea --- /dev/null +++ b/node_modules/websocket-extensions/README.md @@ -0,0 +1,331 @@ +# websocket-extensions [![Build status](https://secure.travis-ci.org/faye/websocket-extensions-node.svg)](http://travis-ci.org/faye/websocket-extensions-node) + +A minimal framework that supports the implementation of WebSocket extensions in +a way that's decoupled from the main protocol. This library aims to allow a +WebSocket extension to be written and used with any protocol library, by +defining abstract representations of frames and messages that allow modules to +co-operate. + +`websocket-extensions` provides a container for registering extension plugins, +and provides all the functions required to negotiate which extensions to use +during a session via the `Sec-WebSocket-Extensions` header. By implementing the +APIs defined in this document, an extension may be used by any WebSocket library +based on this framework. + +## Installation + +``` +$ npm install websocket-extensions +``` + +## Usage + +There are two main audiences for this library: authors implementing the +WebSocket protocol, and authors implementing extensions. End users of a +WebSocket library or an extension should be able to use any extension by passing +it as an argument to their chosen protocol library, without needing to know how +either of them work, or how the `websocket-extensions` framework operates. + +The library is designed with the aim that any protocol implementation and any +extension can be used together, so long as they support the same abstract +representation of frames and messages. + +### Data types + +The APIs provided by the framework rely on two data types; extensions will +expect to be given data and to be able to return data in these formats: + +#### *Frame* + +*Frame* is a structure representing a single WebSocket frame of any type. Frames +are simple objects that must have at least the following properties, which +represent the data encoded in the frame: + +| property | description | +| ------------ | ------------------------------------------------------------------ | +| `final` | `true` if the `FIN` bit is set, `false` otherwise | +| `rsv1` | `true` if the `RSV1` bit is set, `false` otherwise | +| `rsv2` | `true` if the `RSV2` bit is set, `false` otherwise | +| `rsv3` | `true` if the `RSV3` bit is set, `false` otherwise | +| `opcode` | the numeric opcode (`0`, `1`, `2`, `8`, `9`, or `10`) of the frame | +| `masked` | `true` if the `MASK` bit is set, `false` otherwise | +| `maskingKey` | a 4-byte `Buffer` if `masked` is `true`, otherwise `null` | +| `payload` | a `Buffer` containing the (unmasked) application data | + +#### *Message* + +A *Message* represents a complete application message, which can be formed from +text, binary and continuation frames. It has the following properties: + +| property | description | +| -------- | ----------------------------------------------------------------- | +| `rsv1` | `true` if the first frame of the message has the `RSV1` bit set | +| `rsv2` | `true` if the first frame of the message has the `RSV2` bit set | +| `rsv3` | `true` if the first frame of the message has the `RSV3` bit set | +| `opcode` | the numeric opcode (`1` or `2`) of the first frame of the message | +| `data` | the concatenation of all the frame payloads in the message | + +### For driver authors + +A driver author is someone implementing the WebSocket protocol proper, and who +wishes end users to be able to use WebSocket extensions with their library. + +At the start of a WebSocket session, on both the client and the server side, +they should begin by creating an extension container and adding whichever +extensions they want to use. + +```js +var Extensions = require('websocket-extensions'), + deflate = require('permessage-deflate'); + +var exts = new Extensions(); +exts.add(deflate); +``` + +In the following examples, `exts` refers to this `Extensions` instance. + +#### Client sessions + +Clients will use the methods `generateOffer()` and `activate(header)`. + +As part of the handshake process, the client must send a +`Sec-WebSocket-Extensions` header to advertise that it supports the registered +extensions. This header should be generated using: + +```js +request.headers['sec-websocket-extensions'] = exts.generateOffer(); +``` + +This returns a string, for example `"permessage-deflate; +client_max_window_bits"`, that represents all the extensions the client is +offering to use, and their parameters. This string may contain multiple offers +for the same extension. + +When the client receives the handshake response from the server, it should pass +the incoming `Sec-WebSocket-Extensions` header in to `exts` to activate the +extensions the server has accepted: + +```js +exts.activate(response.headers['sec-websocket-extensions']); +``` + +If the server has sent any extension responses that the client does not +recognize, or are in conflict with one another for use of RSV bits, or that use +invalid parameters for the named extensions, then `exts.activate()` will +`throw`. In this event, the client driver should fail the connection with +closing code `1010`. + +#### Server sessions + +Servers will use the method `generateResponse(header)`. + +A server session needs to generate a `Sec-WebSocket-Extensions` header to send +in its handshake response: + +```js +var clientOffer = request.headers['sec-websocket-extensions'], + extResponse = exts.generateResponse(clientOffer); + +response.headers['sec-websocket-extensions'] = extResponse; +``` + +Calling `exts.generateResponse(header)` activates those extensions the client +has asked to use, if they are registered, asks each extension for a set of +response parameters, and returns a string containing the response parameters for +all accepted extensions. + +#### In both directions + +Both clients and servers will use the methods `validFrameRsv(frame)`, +`processIncomingMessage(message)` and `processOutgoingMessage(message)`. + +The WebSocket protocol requires that frames do not have any of the `RSV` bits +set unless there is an extension in use that allows otherwise. When processing +an incoming frame, sessions should pass a *Frame* object to: + +```js +exts.validFrameRsv(frame) +``` + +If this method returns `false`, the session should fail the WebSocket connection +with closing code `1002`. + +To pass incoming messages through the extension stack, a session should +construct a *Message* object according to the above datatype definitions, and +call: + +```js +exts.processIncomingMessage(message, function(error, msg) { + // hand the message off to the application +}); +``` + +If any extensions fail to process the message, then the callback will yield an +error and the session should fail the WebSocket connection with closing code +`1010`. If `error` is `null`, then `msg` should be passed on to the application. + +To pass outgoing messages through the extension stack, a session should +construct a *Message* as before, and call: + +```js +exts.processOutgoingMessage(message, function(error, msg) { + // write message to the transport +}); +``` + +If any extensions fail to process the message, then the callback will yield an +error and the session should fail the WebSocket connection with closing code +`1010`. If `error` is `null`, then `message` should be converted into frames +(with the message's `rsv1`, `rsv2`, `rsv3` and `opcode` set on the first frame) +and written to the transport. + +At the end of the WebSocket session (either when the protocol is explicitly +ended or the transport connection disconnects), the driver should call: + +```js +exts.close(function() {}) +``` + +The callback is invoked when all extensions have finished processing any +messages in the pipeline and it's safe to close the socket. + +### For extension authors + +An extension author is someone implementing an extension that transforms +WebSocket messages passing between the client and server. They would like to +implement their extension once and have it work with any protocol library. + +Extension authors will not install `websocket-extensions` or call it directly. +Instead, they should implement the following API to allow their extension to +plug into the `websocket-extensions` framework. + +An `Extension` is any object that has the following properties: + +| property | description | +| -------- | ---------------------------------------------------------------------------- | +| `name` | a string containing the name of the extension as used in negotiation headers | +| `type` | a string, must be `"permessage"` | +| `rsv1` | either `true` if the extension uses the RSV1 bit, `false` otherwise | +| `rsv2` | either `true` if the extension uses the RSV2 bit, `false` otherwise | +| `rsv3` | either `true` if the extension uses the RSV3 bit, `false` otherwise | + +It must also implement the following methods: + +```js +ext.createClientSession() +``` + +This returns a *ClientSession*, whose interface is defined below. + +```js +ext.createServerSession(offers) +``` + +This takes an array of offer params and returns a *ServerSession*, whose +interface is defined below. For example, if the client handshake contains the +offer header: + +``` +Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover; server_max_window_bits=8, \ + permessage-deflate; server_max_window_bits=15 +``` + +then the `permessage-deflate` extension will receive the call: + +```js +ext.createServerSession([ + { server_no_context_takeover: true, server_max_window_bits: 8 }, + { server_max_window_bits: 15 } +]); +``` + +The extension must decide which set of parameters it wants to accept, if any, +and return a *ServerSession* if it wants to accept the parameters and `null` +otherwise. + +#### *ClientSession* + +A *ClientSession* is the type returned by `ext.createClientSession()`. It must +implement the following methods, as well as the *Session* API listed below. + +```js +clientSession.generateOffer() +// e.g. -> [ +// { server_no_context_takeover: true, server_max_window_bits: 8 }, +// { server_max_window_bits: 15 } +// ] +``` + +This must return a set of parameters to include in the client's +`Sec-WebSocket-Extensions` offer header. If the session wants to offer multiple +configurations, it can return an array of sets of parameters as shown above. + +```js +clientSession.activate(params) // -> true +``` + +This must take a single set of parameters from the server's handshake response +and use them to configure the client session. If the client accepts the given +parameters, then this method must return `true`. If it returns any other value, +the framework will interpret this as the client rejecting the response, and will +`throw`. + +#### *ServerSession* + +A *ServerSession* is the type returned by `ext.createServerSession(offers)`. It +must implement the following methods, as well as the *Session* API listed below. + +```js +serverSession.generateResponse() +// e.g. -> { server_max_window_bits: 8 } +``` + +This returns the set of parameters the server session wants to send in its +`Sec-WebSocket-Extensions` response header. Only one set of parameters is +returned to the client per extension. Server sessions that would confict on +their use of RSV bits are not activated. + +#### *Session* + +The *Session* API must be implemented by both client and server sessions. It +contains two methods, `processIncomingMessage(message)` and +`processOutgoingMessage(message)`. + +```js +session.processIncomingMessage(message, function(error, msg) { ... }) +``` + +The session must implement this method to take an incoming *Message* as defined +above, transform it in any way it needs, then return it via the callback. If +there is an error processing the message, this method should yield an error as +the first argument. + +```js +session.processOutgoingMessage(message, function(error, msg) { ... }) +``` + +The session must implement this method to take an outgoing *Message* as defined +above, transform it in any way it needs, then return it via the callback. If +there is an error processing the message, this method should yield an error as +the first argument. + +Note that both `processIncomingMessage()` and `processOutgoingMessage()` can +perform their logic asynchronously, are allowed to process multiple messages +concurrently, and are not required to complete working on messages in the same +order the messages arrive. `websocket-extensions` will reorder messages as your +extension emits them and will make sure every extension is given messages in the +order they arrive from the driver. This allows extensions to maintain state that +depends on the messages' wire order, for example keeping a DEFLATE compression +context between messages. + +```js +session.close() +``` + +The framework will call this method when the WebSocket session ends, allowing +the session to release any resources it's using. + +## Examples + +- Consumer: [websocket-driver](https://github.com/faye/websocket-driver-node) +- Provider: [permessage-deflate](https://github.com/faye/permessage-deflate-node) diff --git a/node_modules/websocket-extensions/lib/parser.js b/node_modules/websocket-extensions/lib/parser.js new file mode 100644 index 0000000..533767e --- /dev/null +++ b/node_modules/websocket-extensions/lib/parser.js @@ -0,0 +1,103 @@ +'use strict'; + +var TOKEN = /([!#\$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+)/, + NOTOKEN = /([^!#\$%&'\*\+\-\.\^_`\|~0-9A-Za-z])/g, + QUOTED = /"((?:\\[\x00-\x7f]|[^\x00-\x08\x0a-\x1f\x7f"\\])*)"/, + PARAM = new RegExp(TOKEN.source + '(?:=(?:' + TOKEN.source + '|' + QUOTED.source + '))?'), + EXT = new RegExp(TOKEN.source + '(?: *; *' + PARAM.source + ')*', 'g'), + EXT_LIST = new RegExp('^' + EXT.source + '(?: *, *' + EXT.source + ')*$'), + NUMBER = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?$/; + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +var Parser = { + parseHeader: function(header) { + var offers = new Offers(); + if (header === '' || header === undefined) return offers; + + if (!EXT_LIST.test(header)) + throw new SyntaxError('Invalid Sec-WebSocket-Extensions header: ' + header); + + var values = header.match(EXT); + + values.forEach(function(value) { + var params = value.match(new RegExp(PARAM.source, 'g')), + name = params.shift(), + offer = {}; + + params.forEach(function(param) { + var args = param.match(PARAM), key = args[1], data; + + if (args[2] !== undefined) { + data = args[2]; + } else if (args[3] !== undefined) { + data = args[3].replace(/\\/g, ''); + } else { + data = true; + } + if (NUMBER.test(data)) data = parseFloat(data); + + if (hasOwnProperty.call(offer, key)) { + offer[key] = [].concat(offer[key]); + offer[key].push(data); + } else { + offer[key] = data; + } + }, this); + offers.push(name, offer); + }, this); + + return offers; + }, + + serializeParams: function(name, params) { + var values = []; + + var print = function(key, value) { + if (value instanceof Array) { + value.forEach(function(v) { print(key, v) }); + } else if (value === true) { + values.push(key); + } else if (typeof value === 'number') { + values.push(key + '=' + value); + } else if (NOTOKEN.test(value)) { + values.push(key + '="' + value.replace(/"/g, '\\"') + '"'); + } else { + values.push(key + '=' + value); + } + }; + + for (var key in params) print(key, params[key]); + + return [name].concat(values).join('; '); + } +}; + +var Offers = function() { + this._byName = {}; + this._inOrder = []; +}; + +Offers.prototype.push = function(name, params) { + if (!hasOwnProperty.call(this._byName, name)) + this._byName[name] = []; + + this._byName[name].push(params); + this._inOrder.push({ name: name, params: params }); +}; + +Offers.prototype.eachOffer = function(callback, context) { + var list = this._inOrder; + for (var i = 0, n = list.length; i < n; i++) + callback.call(context, list[i].name, list[i].params); +}; + +Offers.prototype.byName = function(name) { + return this._byName[name] || []; +}; + +Offers.prototype.toArray = function() { + return this._inOrder.slice(); +}; + +module.exports = Parser; diff --git a/node_modules/websocket-extensions/lib/pipeline/README.md b/node_modules/websocket-extensions/lib/pipeline/README.md new file mode 100644 index 0000000..322a9c5 --- /dev/null +++ b/node_modules/websocket-extensions/lib/pipeline/README.md @@ -0,0 +1,607 @@ +# Extension pipelining + +`websocket-extensions` models the extension negotiation and processing pipeline +of the WebSocket protocol. Between the driver parsing messages from the TCP +stream and handing those messages off to the application, there may exist a +stack of extensions that transform the message somehow. + +In the parlance of this framework, a *session* refers to a single instance of an +extension, acting on a particular socket on either the server or the client +side. A session may transform messages both incoming to the application and +outgoing from the application, for example the `permessage-deflate` extension +compresses outgoing messages and decompresses incoming messages. Message streams +in either direction are independent; that is, incoming and outgoing messages +cannot be assumed to 'pair up' as in a request-response protocol. + +Asynchronous processing of messages poses a number of problems that this +pipeline construction is intended to solve. + + +## Overview + +Logically, we have the following: + + + +-------------+ out +---+ +---+ +---+ +--------+ + | |------>| |---->| |---->| |------>| | + | Application | | A | | B | | C | | Driver | + | |<------| |<----| |<----| |<------| | + +-------------+ in +---+ +---+ +---+ +--------+ + + \ / + +----------o----------+ + | + sessions + + +For outgoing messages, the driver receives the result of + + C.outgoing(B.outgoing(A.outgoing(message))) + + or, [A, B, C].reduce(((m, ext) => ext.outgoing(m)), message) + +For incoming messages, the application receives the result of + + A.incoming(B.incoming(C.incoming(message))) + + or, [C, B, A].reduce(((m, ext) => ext.incoming(m)), message) + +A session is of the following type, to borrow notation from pseudo-Haskell: + + type Session = { + incoming :: Message -> Message + outgoing :: Message -> Message + close :: () -> () + } + +(That `() -> ()` syntax is intended to mean that `close()` is a nullary void +method; I apologise to any Haskell readers for not using the right monad.) + +The `incoming()` and `outgoing()` methods perform message transformation in the +respective directions; `close()` is called when a socket closes so the session +can release any resources it's holding, for example a DEFLATE de/compression +context. + +However because this is JavaScript, the `incoming()` and `outgoing()` methods +may be asynchronous (indeed, `permessage-deflate` is based on `zlib`, whose API +is stream-based). So their interface is strictly: + + type Session = { + incoming :: Message -> Callback -> () + outgoing :: Message -> Callback -> () + close :: () -> () + } + + type Callback = Either Error Message -> () + +This means a message *m2* can be pushed into a session while it's still +processing the preceding message *m1*. The messages can be processed +concurrently but they *must* be given to the next session in line (or to the +application) in the same order they came in. Applications will expect to receive +messages in the order they arrived over the wire, and sessions require this too. +So ordering of messages must be preserved throughout the pipeline. + +Consider the following highly simplified extension that deflates messages on the +wire. `message` is a value conforming the type: + + type Message = { + rsv1 :: Boolean + rsv2 :: Boolean + rsv3 :: Boolean + opcode :: Number + data :: Buffer + } + +Here's the extension: + +```js +var zlib = require('zlib'); + +var deflate = { + outgoing: function(message, callback) { + zlib.deflateRaw(message.data, function(error, result) { + message.rsv1 = true; + message.data = result; + callback(error, message); + }); + }, + + incoming: function(message, callback) { + // decompress inbound messages (elided) + }, + + close: function() { + // no state to clean up + } +}; +``` + +We can call it with a large message followed by a small one, and the small one +will be returned first: + +```js +var crypto = require('crypto'), + large = crypto.randomBytes(1 << 14), + small = new Buffer('hi'); + +deflate.outgoing({ data: large }, function() { + console.log(1, 'large'); +}); + +deflate.outgoing({ data: small }, function() { + console.log(2, 'small'); +}); + +/* prints: 2 'small' + 1 'large' */ +``` + +So a session that processes messages asynchronously may fail to preserve message +ordering. + +Now, this extension is stateless, so it can process messages in any order and +still produce the same output. But some extensions are stateful and require +message order to be preserved. + +For example, when using `permessage-deflate` without `no_context_takeover` set, +the session retains a DEFLATE de/compression context between messages, which +accumulates state as it consumes data (later messages can refer to sections of +previous ones to improve compression). Reordering parts of the DEFLATE stream +will result in a failed decompression. Messages must be decompressed in the same +order they were compressed by the peer in order for the DEFLATE protocol to +work. + +Finally, there is the problem of closing a socket. When a WebSocket is closed by +the application, or receives a closing request from the other peer, there may be +messages outgoing from the application and incoming from the peer in the +pipeline. If we close the socket and pipeline immediately, two problems arise: + +* We may send our own closing frame to the peer before all prior messages we + sent have been written to the socket, and before we have finished processing + all prior messages from the peer +* The session may be instructed to close its resources (e.g. its de/compression + context) while it's in the middle of processing a message, or before it has + received messages that are upstream of it in the pipeline + +Essentially, we must defer closing the sessions and sending a closing frame +until after all prior messages have exited the pipeline. + + +## Design goals + +* Message order must be preserved between the protocol driver, the extension + sessions, and the application +* Messages should be handed off to sessions and endpoints as soon as possible, + to maximise throughput of stateless sessions +* The closing procedure should block any further messages from entering the + pipeline, and should allow all existing messages to drain +* Sessions should be closed as soon as possible to prevent them holding memory + and other resources when they have no more messages to handle +* The closing API should allow the caller to detect when the pipeline is empty + and it is safe to continue the WebSocket closing procedure +* Individual extensions should remain as simple as possible to facilitate + modularity and independent authorship + +The final point about modularity is an important one: this framework is designed +to facilitate extensions existing as plugins, by decoupling the protocol driver, +extensions, and application. In an ideal world, plugins should only need to +contain code for their specific functionality, and not solve these problems that +apply to all sessions. Also, solving some of these problems requires +consideration of all active sessions collectively, which an individual session +is incapable of doing. + +For example, it is entirely possible to take the simple `deflate` extension +above and wrap its `incoming()` and `outgoing()` methods in two `Transform` +streams, producing this type: + + type Session = { + incoming :: TransformStream + outtoing :: TransformStream + close :: () -> () + } + +The `Transform` class makes it easy to wrap an async function such that message +order is preserved: + +```js +var stream = require('stream'), + session = new stream.Transform({ objectMode: true }); + +session._transform = function(message, _, callback) { + var self = this; + deflate.outgoing(message, function(error, result) { + self.push(result); + callback(); + }); +}; +``` + +However, this has a negative impact on throughput: it works by deferring +`callback()` until the async function has 'returned', which blocks `Transform` +from passing further input into the `_transform()` method until the current +message is dealt with completely. This would prevent sessions from processing +messages concurrently, and would unnecessarily reduce the throughput of +stateless extensions. + +So, input should be handed off to sessions as soon as possible, and all we need +is a mechanism to reorder the output so that message order is preserved for the +next session in line. + + +## Solution + +We now describe the model implemented here and how it meets the above design +goals. The above diagram where a stack of extensions sit between the driver and +application describes the data flow, but not the object graph. That looks like +this: + + + +--------+ + | Driver | + +---o----+ + | + V + +------------+ +----------+ + | Extensions o----->| Pipeline | + +------------+ +-----o----+ + | + +---------------+---------------+ + | | | + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + + +A driver using this framework holds an instance of the `Extensions` class, which +it uses to register extension plugins, negotiate headers and transform messages. +The `Extensions` instance itself holds a `Pipeline`, which contains an array of +`Cell` objects, each of which wraps one of the sessions. + + +### Message processing + +Both the `Pipeline` and `Cell` classes have `incoming()` and `outgoing()` +methods; the `Pipeline` interface pushes messages into the pipe, delegates the +message to each `Cell` in turn, then returns it back to the driver. Outgoing +messages pass through `A` then `B` then `C`, and incoming messages in the +reverse order. + +Internally, a `Cell` contains two `Functor` objects. A `Functor` wraps an async +function and makes sure its output messages maintain the order of its input +messages. This name is due to [@fronx](https://github.com/fronx), on the basis +that, by preserving message order, the abstraction preserves the *mapping* +between input and output messages. To use our simple `deflate` extension from +above: + +```js +var functor = new Functor(deflate, 'outgoing'); + +functor.call({ data: large }, function() { + console.log(1, 'large'); +}); + +functor.call({ data: small }, function() { + console.log(2, 'small'); +}); + +/* -> 1 'large' + 2 'small' */ +``` + +A `Cell` contains two of these, one for each direction: + + + +-----------------------+ + +---->| Functor [A, incoming] | + +----------+ | +-----------------------+ + | Cell [A] o------+ + +----------+ | +-----------------------+ + +---->| Functor [A, outgoing] | + +-----------------------+ + + +This satisfies the message transformation requirements: the `Pipeline` simply +loops over the cells in the appropriate direction to transform each message. +Because each `Cell` will preserve message order, we can pass a message to the +next `Cell` in line as soon as the current `Cell` returns it. This gives each +`Cell` all the messages in order while maximising throughput. + + +### Session closing + +We want to close each session as soon as possible, after all existing messages +have drained. To do this, each `Cell` begins with a pending message counter in +each direction, labelled `in` and `out` below. + + + +----------+ + | Pipeline | + +-----o----+ + | + +---------------+---------------+ + | | | + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + in: 0 in: 0 in: 0 + out: 0 out: 0 out: 0 + + +When a message *m1* enters the pipeline, say in the `outgoing` direction, we +increment the `pending.out` counter on all cells immediately. + + + +----------+ + m1 => | Pipeline | + +-----o----+ + | + +---------------+---------------+ + | | | + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + in: 0 in: 0 in: 0 + out: 1 out: 1 out: 1 + + +*m1* is handed off to `A`, meanwhile a second message `m2` arrives in the same +direction. All `pending.out` counters are again incremented. + + + +----------+ + m2 => | Pipeline | + +-----o----+ + | + +---------------+---------------+ + m1 | | | + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + in: 0 in: 0 in: 0 + out: 2 out: 2 out: 2 + + +When the first cell's `A.outgoing` functor finishes processing *m1*, the first +`pending.out` counter is decremented and *m1* is handed off to cell `B`. + + + +----------+ + | Pipeline | + +-----o----+ + | + +---------------+---------------+ + m2 | m1 | | + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + in: 0 in: 0 in: 0 + out: 1 out: 2 out: 2 + + + +As `B` finishes with *m1*, and as `A` finishes with *m2*, the `pending.out` +counters continue to decrement. + + + +----------+ + | Pipeline | + +-----o----+ + | + +---------------+---------------+ + | m2 | m1 | + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + in: 0 in: 0 in: 0 + out: 0 out: 1 out: 2 + + + +Say `C` is a little slow, and begins processing *m2* while still processing +*m1*. That's fine, the `Functor` mechanism will keep *m1* ahead of *m2* in the +output. + + + +----------+ + | Pipeline | + +-----o----+ + | + +---------------+---------------+ + | | m2 | m1 + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + in: 0 in: 0 in: 0 + out: 0 out: 0 out: 2 + + +Once all messages are dealt with, the counters return to `0`. + + + +----------+ + | Pipeline | + +-----o----+ + | + +---------------+---------------+ + | | | + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + in: 0 in: 0 in: 0 + out: 0 out: 0 out: 0 + + +The same process applies in the `incoming` direction, the only difference being +that messages are passed to `C` first. + +This makes closing the sessions quite simple. When the driver wants to close the +socket, it calls `Pipeline.close()`. This *immediately* calls `close()` on all +the cells. If a cell has `in == out == 0`, then it immediately calls +`session.close()`. Otherwise, it stores the closing call and defers it until +`in` and `out` have both ticked down to zero. The pipeline will not accept new +messages after `close()` has been called, so we know the pending counts will not +increase after this point. + +This means each session is closed as soon as possible: `A` can close while the +slow `C` session is still working, because it knows there are no more messages +on the way. Similarly, `C` will defer closing if `close()` is called while *m1* +is still in `B`, and *m2* in `A`, because its pending count means it knows it +has work yet to do, even if it's not received those messages yet. This concern +cannot be addressed by extensions acting only on their own local state, unless +we pollute individual extensions by making them all implement this same +mechanism. + +The actual closing API at each level is slightly different: + + type Session = { + close :: () -> () + } + + type Cell = { + close :: () -> Promise () + } + + type Pipeline = { + close :: Callback -> () + } + +This might appear inconsistent so it's worth explaining. Remember that a +`Pipeline` holds a list of `Cell` objects, each wrapping a `Session`. The driver +talks (via the `Extensions` API) to the `Pipeline` interface, and it wants +`Pipeline.close()` to do two things: close all the sessions, and tell me when +it's safe to start the closing procedure (i.e. when all messages have drained +from the pipe and been handed off to the application or socket). A callback API +works well for that. + +At the other end of the stack, `Session.close()` is a nullary void method with +no callback or promise API because we don't care what it does, and whatever it +does do will not block the WebSocket protocol; we're not going to hold off +processing messages while a session closes its de/compression context. We just +tell it to close itself, and don't want to wait while it does that. + +In the middle, `Cell.close()` returns a promise rather than using a callback. +This is for two reasons. First, `Cell.close()` might not do anything +immediately, it might have to defer its effect while messages drain. So, if +given a callback, it would have to store it in a queue for later execution. +Callbacks work fine if your method does something and can then invoke the +callback itself, but if you need to store callbacks somewhere so another method +can execute them, a promise is a better fit. Second, it better serves the +purposes of `Pipeline.close()`: it wants to call `close()` on each of a list of +cells, and wait for all of them to finish. This is simple and idiomatic using +promises: + +```js +var closed = cells.map((cell) => cell.close()); +Promise.all(closed).then(callback); +``` + +(We don't actually use a full *Promises/A+* compatible promise here, we use a +much simplified construction that acts as a callback aggregater and resolves +synchronously and does not support chaining, but the principle is the same.) + + +### Error handling + +We've not mentioned error handling so far but it bears some explanation. The +above counter system still applies, but behaves slightly differently in the +presence of errors. + +Say we push three messages into the pipe in the outgoing direction: + + + +----------+ + m3, m2, m1 => | Pipeline | + +-----o----+ + | + +---------------+---------------+ + | | | + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + in: 0 in: 0 in: 0 + out: 3 out: 3 out: 3 + + +They pass through the cells successfully up to this point: + + + +----------+ + | Pipeline | + +-----o----+ + | + +---------------+---------------+ + m3 | m2 | m1 | + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + in: 0 in: 0 in: 0 + out: 1 out: 2 out: 3 + + +At this point, session `B` produces an error while processing *m2*, that is *m2* +becomes *e2*. *m1* is still in the pipeline, and *m3* is queued behind *m2*. +What ought to happen is that *m1* is handed off to the socket, then *m2* is +released to the driver, which will detect the error and begin closing the +socket. No further processing should be done on *m3* and it should not be +released to the driver after the error is emitted. + +To handle this, we allow errors to pass down the pipeline just like messages do, +to maintain ordering. But, once a cell sees its session produce an error, or it +receives an error from upstream, it should refuse to accept any further +messages. Session `B` might have begun processing *m3* by the time it produces +the error *e2*, but `C` will have been given *e2* before it receives *m3*, and +can simply drop *m3*. + +Now, say *e2* reaches the slow session `C` while *m1* is still present, +meanwhile *m3* has been dropped. `C` will never receive *m3* since it will have +been dropped upstream. Under the present model, its `out` counter will be `3` +but it is only going to emit two more values: *m1* and *e2*. In order for +closing to work, we need to decrement `out` to reflect this. The situation +should look like this: + + + +----------+ + | Pipeline | + +-----o----+ + | + +---------------+---------------+ + | | e2 | m1 + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + in: 0 in: 0 in: 0 + out: 0 out: 0 out: 2 + + +When a cell sees its session emit an error, or when it receives an error from +upstream, it sets its pending count in the appropriate direction to equal the +number of messages it is *currently* processing. It will not accept any messages +after it sees the error, so this will allow the counter to reach zero. + +Note that while *e2* is in the pipeline, `Pipeline` should drop any further +messages in the outgoing direction, but should continue to accept incoming +messages. Until *e2* makes it out of the pipe to the driver, behind previous +successful messages, the driver does not know an error has happened, and a +message may arrive over the socket and make it all the way through the incoming +pipe in the meantime. We only halt processing in the affected direction to avoid +doing unnecessary work since messages arriving after an error should not be +processed. + +Some unnecessary work may happen, for example any messages already in the +pipeline following *m2* will be processed by `A`, since it's upstream of the +error. Those messages will be dropped by `B`. + + +## Alternative ideas + +I am considering implementing `Functor` as an object-mode transform stream +rather than what is essentially an async function. Being object-mode, a stream +would preserve message boundaries and would also possibly help address +back-pressure. I'm not sure whether this would require external API changes so +that such streams could be connected to the downstream driver's streams. + + +## Acknowledgements + +Credit is due to [@mnowster](https://github.com/mnowster) for helping with the +design and to [@fronx](https://github.com/fronx) for helping name things. diff --git a/node_modules/websocket-extensions/lib/pipeline/cell.js b/node_modules/websocket-extensions/lib/pipeline/cell.js new file mode 100644 index 0000000..b2901ba --- /dev/null +++ b/node_modules/websocket-extensions/lib/pipeline/cell.js @@ -0,0 +1,53 @@ +'use strict'; + +var Functor = require('./functor'), + Pledge = require('./pledge'); + +var Cell = function(tuple) { + this._ext = tuple[0]; + this._session = tuple[1]; + + this._functors = { + incoming: new Functor(this._session, 'processIncomingMessage'), + outgoing: new Functor(this._session, 'processOutgoingMessage') + }; +}; + +Cell.prototype.pending = function(direction) { + var functor = this._functors[direction]; + if (!functor._stopped) functor.pending += 1; +}; + +Cell.prototype.incoming = function(error, message, callback, context) { + this._exec('incoming', error, message, callback, context); +}; + +Cell.prototype.outgoing = function(error, message, callback, context) { + this._exec('outgoing', error, message, callback, context); +}; + +Cell.prototype.close = function() { + this._closed = this._closed || new Pledge(); + this._doClose(); + return this._closed; +}; + +Cell.prototype._exec = function(direction, error, message, callback, context) { + this._functors[direction].call(error, message, function(err, msg) { + if (err) err.message = this._ext.name + ': ' + err.message; + callback.call(context, err, msg); + this._doClose(); + }, this); +}; + +Cell.prototype._doClose = function() { + var fin = this._functors.incoming, + fout = this._functors.outgoing; + + if (!this._closed || fin.pending + fout.pending !== 0) return; + if (this._session) this._session.close(); + this._session = null; + this._closed.done(); +}; + +module.exports = Cell; diff --git a/node_modules/websocket-extensions/lib/pipeline/functor.js b/node_modules/websocket-extensions/lib/pipeline/functor.js new file mode 100644 index 0000000..fadb49a --- /dev/null +++ b/node_modules/websocket-extensions/lib/pipeline/functor.js @@ -0,0 +1,72 @@ +'use strict'; + +var RingBuffer = require('./ring_buffer'); + +var Functor = function(session, method) { + this._session = session; + this._method = method; + this._queue = new RingBuffer(Functor.QUEUE_SIZE); + this._stopped = false; + this.pending = 0; +}; + +Functor.QUEUE_SIZE = 8; + +Functor.prototype.call = function(error, message, callback, context) { + if (this._stopped) return; + + var record = { error: error, message: message, callback: callback, context: context, done: false }, + called = false, + self = this; + + this._queue.push(record); + + if (record.error) { + record.done = true; + this._stop(); + return this._flushQueue(); + } + + var handler = function(err, msg) { + if (!(called ^ (called = true))) return; + + if (err) { + self._stop(); + record.error = err; + record.message = null; + } else { + record.message = msg; + } + + record.done = true; + self._flushQueue(); + }; + + try { + this._session[this._method](message, handler); + } catch (err) { + handler(err); + } +}; + +Functor.prototype._stop = function() { + this.pending = this._queue.length; + this._stopped = true; +}; + +Functor.prototype._flushQueue = function() { + var queue = this._queue, record; + + while (queue.length > 0 && queue.peek().done) { + record = queue.shift(); + if (record.error) { + this.pending = 0; + queue.clear(); + } else { + this.pending -= 1; + } + record.callback.call(record.context, record.error, record.message); + } +}; + +module.exports = Functor; diff --git a/node_modules/websocket-extensions/lib/pipeline/index.js b/node_modules/websocket-extensions/lib/pipeline/index.js new file mode 100644 index 0000000..930bbc8 --- /dev/null +++ b/node_modules/websocket-extensions/lib/pipeline/index.js @@ -0,0 +1,47 @@ +'use strict'; + +var Cell = require('./cell'), + Pledge = require('./pledge'); + +var Pipeline = function(sessions) { + this._cells = sessions.map(function(session) { return new Cell(session) }); + this._stopped = { incoming: false, outgoing: false }; +}; + +Pipeline.prototype.processIncomingMessage = function(message, callback, context) { + if (this._stopped.incoming) return; + this._loop('incoming', this._cells.length - 1, -1, -1, message, callback, context); +}; + +Pipeline.prototype.processOutgoingMessage = function(message, callback, context) { + if (this._stopped.outgoing) return; + this._loop('outgoing', 0, this._cells.length, 1, message, callback, context); +}; + +Pipeline.prototype.close = function(callback, context) { + this._stopped = { incoming: true, outgoing: true }; + + var closed = this._cells.map(function(a) { return a.close() }); + if (callback) + Pledge.all(closed).then(function() { callback.call(context) }); +}; + +Pipeline.prototype._loop = function(direction, start, end, step, message, callback, context) { + var cells = this._cells, + n = cells.length, + self = this; + + while (n--) cells[n].pending(direction); + + var pipe = function(index, error, msg) { + if (index === end) return callback.call(context, error, msg); + + cells[index][direction](error, msg, function(err, m) { + if (err) self._stopped[direction] = true; + pipe(index + step, err, m); + }); + }; + pipe(start, null, message); +}; + +module.exports = Pipeline; diff --git a/node_modules/websocket-extensions/lib/pipeline/pledge.js b/node_modules/websocket-extensions/lib/pipeline/pledge.js new file mode 100644 index 0000000..8a1f45d --- /dev/null +++ b/node_modules/websocket-extensions/lib/pipeline/pledge.js @@ -0,0 +1,37 @@ +'use strict'; + +var RingBuffer = require('./ring_buffer'); + +var Pledge = function() { + this._complete = false; + this._callbacks = new RingBuffer(Pledge.QUEUE_SIZE); +}; + +Pledge.QUEUE_SIZE = 4; + +Pledge.all = function(list) { + var pledge = new Pledge(), + pending = list.length, + n = pending; + + if (pending === 0) pledge.done(); + + while (n--) list[n].then(function() { + pending -= 1; + if (pending === 0) pledge.done(); + }); + return pledge; +}; + +Pledge.prototype.then = function(callback) { + if (this._complete) callback(); + else this._callbacks.push(callback); +}; + +Pledge.prototype.done = function() { + this._complete = true; + var callbacks = this._callbacks, callback; + while (callback = callbacks.shift()) callback(); +}; + +module.exports = Pledge; diff --git a/node_modules/websocket-extensions/lib/pipeline/ring_buffer.js b/node_modules/websocket-extensions/lib/pipeline/ring_buffer.js new file mode 100644 index 0000000..676ff94 --- /dev/null +++ b/node_modules/websocket-extensions/lib/pipeline/ring_buffer.js @@ -0,0 +1,66 @@ +'use strict'; + +var RingBuffer = function(bufferSize) { + this._bufferSize = bufferSize; + this.clear(); +}; + +RingBuffer.prototype.clear = function() { + this._buffer = new Array(this._bufferSize); + this._ringOffset = 0; + this._ringSize = this._bufferSize; + this._head = 0; + this._tail = 0; + this.length = 0; +}; + +RingBuffer.prototype.push = function(value) { + var expandBuffer = false, + expandRing = false; + + if (this._ringSize < this._bufferSize) { + expandBuffer = (this._tail === 0); + } else if (this._ringOffset === this._ringSize) { + expandBuffer = true; + expandRing = (this._tail === 0); + } + + if (expandBuffer) { + this._tail = this._bufferSize; + this._buffer = this._buffer.concat(new Array(this._bufferSize)); + this._bufferSize = this._buffer.length; + + if (expandRing) + this._ringSize = this._bufferSize; + } + + this._buffer[this._tail] = value; + this.length += 1; + if (this._tail < this._ringSize) this._ringOffset += 1; + this._tail = (this._tail + 1) % this._bufferSize; +}; + +RingBuffer.prototype.peek = function() { + if (this.length === 0) return void 0; + return this._buffer[this._head]; +}; + +RingBuffer.prototype.shift = function() { + if (this.length === 0) return void 0; + + var value = this._buffer[this._head]; + this._buffer[this._head] = void 0; + this.length -= 1; + this._ringOffset -= 1; + + if (this._ringOffset === 0 && this.length > 0) { + this._head = this._ringSize; + this._ringOffset = this.length; + this._ringSize = this._bufferSize; + } else { + this._head = (this._head + 1) % this._ringSize; + } + return value; +}; + +module.exports = RingBuffer; diff --git a/node_modules/websocket-extensions/lib/websocket_extensions.js b/node_modules/websocket-extensions/lib/websocket_extensions.js new file mode 100644 index 0000000..48adad8 --- /dev/null +++ b/node_modules/websocket-extensions/lib/websocket_extensions.js @@ -0,0 +1,162 @@ +'use strict'; + +var Parser = require('./parser'), + Pipeline = require('./pipeline'); + +var Extensions = function() { + this._rsv1 = this._rsv2 = this._rsv3 = null; + + this._byName = {}; + this._inOrder = []; + this._sessions = []; + this._index = {}; +}; + +Extensions.MESSAGE_OPCODES = [1, 2]; + +var instance = { + add: function(ext) { + if (typeof ext.name !== 'string') throw new TypeError('extension.name must be a string'); + if (ext.type !== 'permessage') throw new TypeError('extension.type must be "permessage"'); + + if (typeof ext.rsv1 !== 'boolean') throw new TypeError('extension.rsv1 must be true or false'); + if (typeof ext.rsv2 !== 'boolean') throw new TypeError('extension.rsv2 must be true or false'); + if (typeof ext.rsv3 !== 'boolean') throw new TypeError('extension.rsv3 must be true or false'); + + if (this._byName.hasOwnProperty(ext.name)) + throw new TypeError('An extension with name "' + ext.name + '" is already registered'); + + this._byName[ext.name] = ext; + this._inOrder.push(ext); + }, + + generateOffer: function() { + var sessions = [], + offer = [], + index = {}; + + this._inOrder.forEach(function(ext) { + var session = ext.createClientSession(); + if (!session) return; + + var record = [ext, session]; + sessions.push(record); + index[ext.name] = record; + + var offers = session.generateOffer(); + offers = offers ? [].concat(offers) : []; + + offers.forEach(function(off) { + offer.push(Parser.serializeParams(ext.name, off)); + }, this); + }, this); + + this._sessions = sessions; + this._index = index; + + return offer.length > 0 ? offer.join(', ') : null; + }, + + activate: function(header) { + var responses = Parser.parseHeader(header), + sessions = []; + + responses.eachOffer(function(name, params) { + var record = this._index[name]; + + if (!record) + throw new Error('Server sent an extension response for unknown extension "' + name + '"'); + + var ext = record[0], + session = record[1], + reserved = this._reserved(ext); + + if (reserved) + throw new Error('Server sent two extension responses that use the RSV' + + reserved[0] + ' bit: "' + + reserved[1] + '" and "' + ext.name + '"'); + + if (session.activate(params) !== true) + throw new Error('Server sent unacceptable extension parameters: ' + + Parser.serializeParams(name, params)); + + this._reserve(ext); + sessions.push(record); + }, this); + + this._sessions = sessions; + this._pipeline = new Pipeline(sessions); + }, + + generateResponse: function(header) { + var sessions = [], + response = [], + offers = Parser.parseHeader(header); + + this._inOrder.forEach(function(ext) { + var offer = offers.byName(ext.name); + if (offer.length === 0 || this._reserved(ext)) return; + + var session = ext.createServerSession(offer); + if (!session) return; + + this._reserve(ext); + sessions.push([ext, session]); + response.push(Parser.serializeParams(ext.name, session.generateResponse())); + }, this); + + this._sessions = sessions; + this._pipeline = new Pipeline(sessions); + + return response.length > 0 ? response.join(', ') : null; + }, + + validFrameRsv: function(frame) { + var allowed = { rsv1: false, rsv2: false, rsv3: false }, + ext; + + if (Extensions.MESSAGE_OPCODES.indexOf(frame.opcode) >= 0) { + for (var i = 0, n = this._sessions.length; i < n; i++) { + ext = this._sessions[i][0]; + allowed.rsv1 = allowed.rsv1 || ext.rsv1; + allowed.rsv2 = allowed.rsv2 || ext.rsv2; + allowed.rsv3 = allowed.rsv3 || ext.rsv3; + } + } + + return (allowed.rsv1 || !frame.rsv1) && + (allowed.rsv2 || !frame.rsv2) && + (allowed.rsv3 || !frame.rsv3); + }, + + processIncomingMessage: function(message, callback, context) { + this._pipeline.processIncomingMessage(message, callback, context); + }, + + processOutgoingMessage: function(message, callback, context) { + this._pipeline.processOutgoingMessage(message, callback, context); + }, + + close: function(callback, context) { + if (!this._pipeline) return callback.call(context); + this._pipeline.close(callback, context); + }, + + _reserve: function(ext) { + this._rsv1 = this._rsv1 || (ext.rsv1 && ext.name); + this._rsv2 = this._rsv2 || (ext.rsv2 && ext.name); + this._rsv3 = this._rsv3 || (ext.rsv3 && ext.name); + }, + + _reserved: function(ext) { + if (this._rsv1 && ext.rsv1) return [1, this._rsv1]; + if (this._rsv2 && ext.rsv2) return [2, this._rsv2]; + if (this._rsv3 && ext.rsv3) return [3, this._rsv3]; + return false; + } +}; + +for (var key in instance) + Extensions.prototype[key] = instance[key]; + +module.exports = Extensions; diff --git a/node_modules/websocket-extensions/package.json b/node_modules/websocket-extensions/package.json new file mode 100644 index 0000000..e4f2f91 --- /dev/null +++ b/node_modules/websocket-extensions/package.json @@ -0,0 +1,29 @@ +{ + "name": "websocket-extensions", + "description": "Generic extension manager for WebSocket connections", + "homepage": "http://github.com/faye/websocket-extensions-node", + "author": "James Coglan (http://jcoglan.com/)", + "keywords": [ + "websocket" + ], + "license": "Apache-2.0", + "version": "0.1.4", + "engines": { + "node": ">=0.8.0" + }, + "files": [ + "lib" + ], + "main": "./lib/websocket_extensions", + "devDependencies": { + "jstest": "*" + }, + "scripts": { + "test": "jstest spec/runner.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/faye/websocket-extensions-node.git" + }, + "bugs": "http://github.com/faye/websocket-extensions-node/issues" +} diff --git a/node_modules/whatwg-url/LICENSE.txt b/node_modules/whatwg-url/LICENSE.txt new file mode 100644 index 0000000..54dfac3 --- /dev/null +++ b/node_modules/whatwg-url/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015–2016 Sebastian Mayr + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/whatwg-url/README.md b/node_modules/whatwg-url/README.md new file mode 100644 index 0000000..4347a7f --- /dev/null +++ b/node_modules/whatwg-url/README.md @@ -0,0 +1,67 @@ +# whatwg-url + +whatwg-url is a full implementation of the WHATWG [URL Standard](https://url.spec.whatwg.org/). It can be used standalone, but it also exposes a lot of the internal algorithms that are useful for integrating a URL parser into a project like [jsdom](https://github.com/tmpvar/jsdom). + +## Current Status + +whatwg-url is currently up to date with the URL spec up to commit [a62223](https://github.com/whatwg/url/commit/a622235308342c9adc7fc2fd1659ff059f7d5e2a). + +## API + +### The `URL` Constructor + +The main API is the [`URL`](https://url.spec.whatwg.org/#url) export, which follows the spec's behavior in all ways (including e.g. `USVString` conversion). Most consumers of this library will want to use this. + +### Low-level URL Standard API + +The following methods are exported for use by places like jsdom that need to implement things like [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils). They operate on or return an "internal URL" or ["URL record"](https://url.spec.whatwg.org/#concept-url) type. + +- [URL parser](https://url.spec.whatwg.org/#concept-url-parser): `parseURL(input, { baseURL, encodingOverride })` +- [Basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser): `basicURLParse(input, { baseURL, encodingOverride, url, stateOverride })` +- [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer): `serializeURL(urlRecord, excludeFragment)` +- [Host serializer](https://url.spec.whatwg.org/#concept-host-serializer): `serializeHost(hostFromURLRecord)` +- [Serialize an integer](https://url.spec.whatwg.org/#serialize-an-integer): `serializeInteger(number)` +- [Origin](https://url.spec.whatwg.org/#concept-url-origin) [serializer](https://html.spec.whatwg.org/multipage/browsers.html#serialization-of-an-origin): `serializeURLOrigin(urlRecord)` +- [Set the username](https://url.spec.whatwg.org/#set-the-username): `setTheUsername(urlRecord, usernameString)` +- [Set the password](https://url.spec.whatwg.org/#set-the-password): `setThePassword(urlRecord, passwordString)` +- [Cannot have a username/password/port](https://url.spec.whatwg.org/#cannot-have-a-username-password-port): `cannotHaveAUsernamePasswordPort(urlRecord)` + +The `stateOverride` parameter is one of the following strings: + +- [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state) +- [`"scheme"`](https://url.spec.whatwg.org/#scheme-state) +- [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state) +- [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state) +- [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state) +- [`"relative"`](https://url.spec.whatwg.org/#relative-state) +- [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state) +- [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state) +- [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state) +- [`"authority"`](https://url.spec.whatwg.org/#authority-state) +- [`"host"`](https://url.spec.whatwg.org/#host-state) +- [`"hostname"`](https://url.spec.whatwg.org/#hostname-state) +- [`"port"`](https://url.spec.whatwg.org/#port-state) +- [`"file"`](https://url.spec.whatwg.org/#file-state) +- [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state) +- [`"file host"`](https://url.spec.whatwg.org/#file-host-state) +- [`"path start"`](https://url.spec.whatwg.org/#path-start-state) +- [`"path"`](https://url.spec.whatwg.org/#path-state) +- [`"cannot-be-a-base-URL path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state) +- [`"query"`](https://url.spec.whatwg.org/#query-state) +- [`"fragment"`](https://url.spec.whatwg.org/#fragment-state) + +The URL record type has the following API: + +- [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme) +- [`username`](https://url.spec.whatwg.org/#concept-url-username) +- [`password`](https://url.spec.whatwg.org/#concept-url-password) +- [`host`](https://url.spec.whatwg.org/#concept-url-host) +- [`port`](https://url.spec.whatwg.org/#concept-url-port) +- [`path`](https://url.spec.whatwg.org/#concept-url-path) (as an array) +- [`query`](https://url.spec.whatwg.org/#concept-url-query) +- [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment) +- [`cannotBeABaseURL`](https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag) (as a boolean) + +These properties should be treated with care, as in general changing them will cause the URL record to be in an inconsistent state until the appropriate invocation of `basicURLParse` is used to fix it up. You can see examples of this in the URL Standard, where there are many step sequences like "4. Set context object’s url’s fragment to the empty string. 5. Basic URL parse _input_ with context object’s url as _url_ and fragment state as _state override_." In between those two steps, a URL record is in an unusable state. + +The return value of "failure" in the spec is represented by the string `"failure"`. That is, functions like `parseURL` and `basicURLParse` can return _either_ a URL record _or_ the string `"failure"`. diff --git a/node_modules/whatwg-url/lib/URL-impl.js b/node_modules/whatwg-url/lib/URL-impl.js new file mode 100644 index 0000000..dc7452c --- /dev/null +++ b/node_modules/whatwg-url/lib/URL-impl.js @@ -0,0 +1,200 @@ +"use strict"; +const usm = require("./url-state-machine"); + +exports.implementation = class URLImpl { + constructor(constructorArgs) { + const url = constructorArgs[0]; + const base = constructorArgs[1]; + + let parsedBase = null; + if (base !== undefined) { + parsedBase = usm.basicURLParse(base); + if (parsedBase === "failure") { + throw new TypeError("Invalid base URL"); + } + } + + const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); + if (parsedURL === "failure") { + throw new TypeError("Invalid URL"); + } + + this._url = parsedURL; + + // TODO: query stuff + } + + get href() { + return usm.serializeURL(this._url); + } + + set href(v) { + const parsedURL = usm.basicURLParse(v); + if (parsedURL === "failure") { + throw new TypeError("Invalid URL"); + } + + this._url = parsedURL; + } + + get origin() { + return usm.serializeURLOrigin(this._url); + } + + get protocol() { + return this._url.scheme + ":"; + } + + set protocol(v) { + usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" }); + } + + get username() { + return this._url.username; + } + + set username(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + usm.setTheUsername(this._url, v); + } + + get password() { + return this._url.password; + } + + set password(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + usm.setThePassword(this._url, v); + } + + get host() { + const url = this._url; + + if (url.host === null) { + return ""; + } + + if (url.port === null) { + return usm.serializeHost(url.host); + } + + return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port); + } + + set host(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); + } + + get hostname() { + if (this._url.host === null) { + return ""; + } + + return usm.serializeHost(this._url.host); + } + + set hostname(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); + } + + get port() { + if (this._url.port === null) { + return ""; + } + + return usm.serializeInteger(this._url.port); + } + + set port(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + if (v === "") { + this._url.port = null; + } else { + usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); + } + } + + get pathname() { + if (this._url.cannotBeABaseURL) { + return this._url.path[0]; + } + + if (this._url.path.length === 0) { + return ""; + } + + return "/" + this._url.path.join("/"); + } + + set pathname(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + this._url.path = []; + usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); + } + + get search() { + if (this._url.query === null || this._url.query === "") { + return ""; + } + + return "?" + this._url.query; + } + + set search(v) { + // TODO: query stuff + + const url = this._url; + + if (v === "") { + url.query = null; + return; + } + + const input = v[0] === "?" ? v.substring(1) : v; + url.query = ""; + usm.basicURLParse(input, { url, stateOverride: "query" }); + } + + get hash() { + if (this._url.fragment === null || this._url.fragment === "") { + return ""; + } + + return "#" + this._url.fragment; + } + + set hash(v) { + if (v === "") { + this._url.fragment = null; + return; + } + + const input = v[0] === "#" ? v.substring(1) : v; + this._url.fragment = ""; + usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); + } + + toJSON() { + return this.href; + } +}; diff --git a/node_modules/whatwg-url/lib/URL.js b/node_modules/whatwg-url/lib/URL.js new file mode 100644 index 0000000..78c7207 --- /dev/null +++ b/node_modules/whatwg-url/lib/URL.js @@ -0,0 +1,196 @@ +"use strict"; + +const conversions = require("webidl-conversions"); +const utils = require("./utils.js"); +const Impl = require(".//URL-impl.js"); + +const impl = utils.implSymbol; + +function URL(url) { + if (!this || this[impl] || !(this instanceof URL)) { + throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); + } + if (arguments.length < 1) { + throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present."); + } + const args = []; + for (let i = 0; i < arguments.length && i < 2; ++i) { + args[i] = arguments[i]; + } + args[0] = conversions["USVString"](args[0]); + if (args[1] !== undefined) { + args[1] = conversions["USVString"](args[1]); + } + + module.exports.setup(this, args); +} + +URL.prototype.toJSON = function toJSON() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + const args = []; + for (let i = 0; i < arguments.length && i < 0; ++i) { + args[i] = arguments[i]; + } + return this[impl].toJSON.apply(this[impl], args); +}; +Object.defineProperty(URL.prototype, "href", { + get() { + return this[impl].href; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].href = V; + }, + enumerable: true, + configurable: true +}); + +URL.prototype.toString = function () { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + return this.href; +}; + +Object.defineProperty(URL.prototype, "origin", { + get() { + return this[impl].origin; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "protocol", { + get() { + return this[impl].protocol; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].protocol = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "username", { + get() { + return this[impl].username; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].username = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "password", { + get() { + return this[impl].password; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].password = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "host", { + get() { + return this[impl].host; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].host = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "hostname", { + get() { + return this[impl].hostname; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].hostname = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "port", { + get() { + return this[impl].port; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].port = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "pathname", { + get() { + return this[impl].pathname; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].pathname = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "search", { + get() { + return this[impl].search; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].search = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "hash", { + get() { + return this[impl].hash; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].hash = V; + }, + enumerable: true, + configurable: true +}); + + +module.exports = { + is(obj) { + return !!obj && obj[impl] instanceof Impl.implementation; + }, + create(constructorArgs, privateData) { + let obj = Object.create(URL.prototype); + this.setup(obj, constructorArgs, privateData); + return obj; + }, + setup(obj, constructorArgs, privateData) { + if (!privateData) privateData = {}; + privateData.wrapper = obj; + + obj[impl] = new Impl.implementation(constructorArgs, privateData); + obj[impl][utils.wrapperSymbol] = obj; + }, + interface: URL, + expose: { + Window: { URL: URL }, + Worker: { URL: URL } + } +}; + diff --git a/node_modules/whatwg-url/lib/public-api.js b/node_modules/whatwg-url/lib/public-api.js new file mode 100644 index 0000000..932dcad --- /dev/null +++ b/node_modules/whatwg-url/lib/public-api.js @@ -0,0 +1,11 @@ +"use strict"; + +exports.URL = require("./URL").interface; +exports.serializeURL = require("./url-state-machine").serializeURL; +exports.serializeURLOrigin = require("./url-state-machine").serializeURLOrigin; +exports.basicURLParse = require("./url-state-machine").basicURLParse; +exports.setTheUsername = require("./url-state-machine").setTheUsername; +exports.setThePassword = require("./url-state-machine").setThePassword; +exports.serializeHost = require("./url-state-machine").serializeHost; +exports.serializeInteger = require("./url-state-machine").serializeInteger; +exports.parseURL = require("./url-state-machine").parseURL; diff --git a/node_modules/whatwg-url/lib/url-state-machine.js b/node_modules/whatwg-url/lib/url-state-machine.js new file mode 100644 index 0000000..27d977a --- /dev/null +++ b/node_modules/whatwg-url/lib/url-state-machine.js @@ -0,0 +1,1297 @@ +"use strict"; +const punycode = require("punycode"); +const tr46 = require("tr46"); + +const specialSchemes = { + ftp: 21, + file: null, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443 +}; + +const failure = Symbol("failure"); + +function countSymbols(str) { + return punycode.ucs2.decode(str).length; +} + +function at(input, idx) { + const c = input[idx]; + return isNaN(c) ? undefined : String.fromCodePoint(c); +} + +function isASCIIDigit(c) { + return c >= 0x30 && c <= 0x39; +} + +function isASCIIAlpha(c) { + return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); +} + +function isASCIIAlphanumeric(c) { + return isASCIIAlpha(c) || isASCIIDigit(c); +} + +function isASCIIHex(c) { + return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); +} + +function isSingleDot(buffer) { + return buffer === "." || buffer.toLowerCase() === "%2e"; +} + +function isDoubleDot(buffer) { + buffer = buffer.toLowerCase(); + return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; +} + +function isWindowsDriveLetterCodePoints(cp1, cp2) { + return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); +} + +function isWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); +} + +function isNormalizedWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; +} + +function containsForbiddenHostCodePoint(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function containsForbiddenHostCodePointExcludingPercent(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function isSpecialScheme(scheme) { + return specialSchemes[scheme] !== undefined; +} + +function isSpecial(url) { + return isSpecialScheme(url.scheme); +} + +function defaultPort(scheme) { + return specialSchemes[scheme]; +} + +function percentEncode(c) { + let hex = c.toString(16).toUpperCase(); + if (hex.length === 1) { + hex = "0" + hex; + } + + return "%" + hex; +} + +function utf8PercentEncode(c) { + const buf = new Buffer(c); + + let str = ""; + + for (let i = 0; i < buf.length; ++i) { + str += percentEncode(buf[i]); + } + + return str; +} + +function utf8PercentDecode(str) { + const input = new Buffer(str); + const output = []; + for (let i = 0; i < input.length; ++i) { + if (input[i] !== 37) { + output.push(input[i]); + } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { + output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); + i += 2; + } else { + output.push(input[i]); + } + } + return new Buffer(output).toString(); +} + +function isC0ControlPercentEncode(c) { + return c <= 0x1F || c > 0x7E; +} + +const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); +function isPathPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); +} + +const extraUserinfoPercentEncodeSet = + new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); +function isUserinfoPercentEncode(c) { + return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); +} + +function percentEncodeChar(c, encodeSetPredicate) { + const cStr = String.fromCodePoint(c); + + if (encodeSetPredicate(c)) { + return utf8PercentEncode(cStr); + } + + return cStr; +} + +function parseIPv4Number(input) { + let R = 10; + + if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { + input = input.substring(2); + R = 16; + } else if (input.length >= 2 && input.charAt(0) === "0") { + input = input.substring(1); + R = 8; + } + + if (input === "") { + return 0; + } + + const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); + if (regex.test(input)) { + return failure; + } + + return parseInt(input, R); +} + +function parseIPv4(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length > 1) { + parts.pop(); + } + } + + if (parts.length > 4) { + return input; + } + + const numbers = []; + for (const part of parts) { + if (part === "") { + return input; + } + const n = parseIPv4Number(part); + if (n === failure) { + return input; + } + + numbers.push(n); + } + + for (let i = 0; i < numbers.length - 1; ++i) { + if (numbers[i] > 255) { + return failure; + } + } + if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { + return failure; + } + + let ipv4 = numbers.pop(); + let counter = 0; + + for (const n of numbers) { + ipv4 += n * Math.pow(256, 3 - counter); + ++counter; + } + + return ipv4; +} + +function serializeIPv4(address) { + let output = ""; + let n = address; + + for (let i = 1; i <= 4; ++i) { + output = String(n % 256) + output; + if (i !== 4) { + output = "." + output; + } + n = Math.floor(n / 256); + } + + return output; +} + +function parseIPv6(input) { + const address = [0, 0, 0, 0, 0, 0, 0, 0]; + let pieceIndex = 0; + let compress = null; + let pointer = 0; + + input = punycode.ucs2.decode(input); + + if (input[pointer] === 58) { + if (input[pointer + 1] !== 58) { + return failure; + } + + pointer += 2; + ++pieceIndex; + compress = pieceIndex; + } + + while (pointer < input.length) { + if (pieceIndex === 8) { + return failure; + } + + if (input[pointer] === 58) { + if (compress !== null) { + return failure; + } + ++pointer; + ++pieceIndex; + compress = pieceIndex; + continue; + } + + let value = 0; + let length = 0; + + while (length < 4 && isASCIIHex(input[pointer])) { + value = value * 0x10 + parseInt(at(input, pointer), 16); + ++pointer; + ++length; + } + + if (input[pointer] === 46) { + if (length === 0) { + return failure; + } + + pointer -= length; + + if (pieceIndex > 6) { + return failure; + } + + let numbersSeen = 0; + + while (input[pointer] !== undefined) { + let ipv4Piece = null; + + if (numbersSeen > 0) { + if (input[pointer] === 46 && numbersSeen < 4) { + ++pointer; + } else { + return failure; + } + } + + if (!isASCIIDigit(input[pointer])) { + return failure; + } + + while (isASCIIDigit(input[pointer])) { + const number = parseInt(at(input, pointer)); + if (ipv4Piece === null) { + ipv4Piece = number; + } else if (ipv4Piece === 0) { + return failure; + } else { + ipv4Piece = ipv4Piece * 10 + number; + } + if (ipv4Piece > 255) { + return failure; + } + ++pointer; + } + + address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; + + ++numbersSeen; + + if (numbersSeen === 2 || numbersSeen === 4) { + ++pieceIndex; + } + } + + if (numbersSeen !== 4) { + return failure; + } + + break; + } else if (input[pointer] === 58) { + ++pointer; + if (input[pointer] === undefined) { + return failure; + } + } else if (input[pointer] !== undefined) { + return failure; + } + + address[pieceIndex] = value; + ++pieceIndex; + } + + if (compress !== null) { + let swaps = pieceIndex - compress; + pieceIndex = 7; + while (pieceIndex !== 0 && swaps > 0) { + const temp = address[compress + swaps - 1]; + address[compress + swaps - 1] = address[pieceIndex]; + address[pieceIndex] = temp; + --pieceIndex; + --swaps; + } + } else if (compress === null && pieceIndex !== 8) { + return failure; + } + + return address; +} + +function serializeIPv6(address) { + let output = ""; + const seqResult = findLongestZeroSequence(address); + const compress = seqResult.idx; + let ignore0 = false; + + for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { + if (ignore0 && address[pieceIndex] === 0) { + continue; + } else if (ignore0) { + ignore0 = false; + } + + if (compress === pieceIndex) { + const separator = pieceIndex === 0 ? "::" : ":"; + output += separator; + ignore0 = true; + continue; + } + + output += address[pieceIndex].toString(16); + + if (pieceIndex !== 7) { + output += ":"; + } + } + + return output; +} + +function parseHost(input, isSpecialArg) { + if (input[0] === "[") { + if (input[input.length - 1] !== "]") { + return failure; + } + + return parseIPv6(input.substring(1, input.length - 1)); + } + + if (!isSpecialArg) { + return parseOpaqueHost(input); + } + + const domain = utf8PercentDecode(input); + const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false); + if (asciiDomain === null) { + return failure; + } + + if (containsForbiddenHostCodePoint(asciiDomain)) { + return failure; + } + + const ipv4Host = parseIPv4(asciiDomain); + if (typeof ipv4Host === "number" || ipv4Host === failure) { + return ipv4Host; + } + + return asciiDomain; +} + +function parseOpaqueHost(input) { + if (containsForbiddenHostCodePointExcludingPercent(input)) { + return failure; + } + + let output = ""; + const decoded = punycode.ucs2.decode(input); + for (let i = 0; i < decoded.length; ++i) { + output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); + } + return output; +} + +function findLongestZeroSequence(arr) { + let maxIdx = null; + let maxLen = 1; // only find elements > 1 + let currStart = null; + let currLen = 0; + + for (let i = 0; i < arr.length; ++i) { + if (arr[i] !== 0) { + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + currStart = null; + currLen = 0; + } else { + if (currStart === null) { + currStart = i; + } + ++currLen; + } + } + + // if trailing zeros + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + return { + idx: maxIdx, + len: maxLen + }; +} + +function serializeHost(host) { + if (typeof host === "number") { + return serializeIPv4(host); + } + + // IPv6 serializer + if (host instanceof Array) { + return "[" + serializeIPv6(host) + "]"; + } + + return host; +} + +function trimControlChars(url) { + return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); +} + +function trimTabAndNewline(url) { + return url.replace(/\u0009|\u000A|\u000D/g, ""); +} + +function shortenPath(url) { + const path = url.path; + if (path.length === 0) { + return; + } + if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { + return; + } + + path.pop(); +} + +function includesCredentials(url) { + return url.username !== "" || url.password !== ""; +} + +function cannotHaveAUsernamePasswordPort(url) { + return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; +} + +function isNormalizedWindowsDriveLetter(string) { + return /^[A-Za-z]:$/.test(string); +} + +function URLStateMachine(input, base, encodingOverride, url, stateOverride) { + this.pointer = 0; + this.input = input; + this.base = base || null; + this.encodingOverride = encodingOverride || "utf-8"; + this.stateOverride = stateOverride; + this.url = url; + this.failure = false; + this.parseError = false; + + if (!this.url) { + this.url = { + scheme: "", + username: "", + password: "", + host: null, + port: null, + path: [], + query: null, + fragment: null, + + cannotBeABaseURL: false + }; + + const res = trimControlChars(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + } + + const res = trimTabAndNewline(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + + this.state = stateOverride || "scheme start"; + + this.buffer = ""; + this.atFlag = false; + this.arrFlag = false; + this.passwordTokenSeenFlag = false; + + this.input = punycode.ucs2.decode(this.input); + + for (; this.pointer <= this.input.length; ++this.pointer) { + const c = this.input[this.pointer]; + const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); + + // exec state machine + const ret = this["parse " + this.state](c, cStr); + if (!ret) { + break; // terminate algorithm + } else if (ret === failure) { + this.failure = true; + break; + } + } +} + +URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { + if (isASCIIAlpha(c)) { + this.buffer += cStr.toLowerCase(); + this.state = "scheme"; + } else if (!this.stateOverride) { + this.state = "no scheme"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { + if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { + this.buffer += cStr.toLowerCase(); + } else if (c === 58) { + if (this.stateOverride) { + if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { + return false; + } + + if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { + return false; + } + + if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { + return false; + } + + if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { + return false; + } + } + this.url.scheme = this.buffer; + this.buffer = ""; + if (this.stateOverride) { + return false; + } + if (this.url.scheme === "file") { + if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { + this.parseError = true; + } + this.state = "file"; + } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { + this.state = "special relative or authority"; + } else if (isSpecial(this.url)) { + this.state = "special authority slashes"; + } else if (this.input[this.pointer + 1] === 47) { + this.state = "path or authority"; + ++this.pointer; + } else { + this.url.cannotBeABaseURL = true; + this.url.path.push(""); + this.state = "cannot-be-a-base-URL path"; + } + } else if (!this.stateOverride) { + this.buffer = ""; + this.state = "no scheme"; + this.pointer = -1; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { + if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { + return failure; + } else if (this.base.cannotBeABaseURL && c === 35) { + this.url.scheme = this.base.scheme; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.url.cannotBeABaseURL = true; + this.state = "fragment"; + } else if (this.base.scheme === "file") { + this.state = "file"; + --this.pointer; + } else { + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { + if (c === 47) { + this.state = "authority"; + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative"] = function parseRelative(c) { + this.url.scheme = this.base.scheme; + if (isNaN(c)) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 47) { + this.state = "relative slash"; + } else if (c === 63) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else if (isSpecial(this.url) && c === 92) { + this.parseError = true; + this.state = "relative slash"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(0, this.base.path.length - 1); + + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { + if (isSpecial(this.url) && (c === 47 || c === 92)) { + if (c === 92) { + this.parseError = true; + } + this.state = "special authority ignore slashes"; + } else if (c === 47) { + this.state = "authority"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "special authority ignore slashes"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { + if (c !== 47 && c !== 92) { + this.state = "authority"; + --this.pointer; + } else { + this.parseError = true; + } + + return true; +}; + +URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { + if (c === 64) { + this.parseError = true; + if (this.atFlag) { + this.buffer = "%40" + this.buffer; + } + this.atFlag = true; + + // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars + const len = countSymbols(this.buffer); + for (let pointer = 0; pointer < len; ++pointer) { + const codePoint = this.buffer.codePointAt(pointer); + + if (codePoint === 58 && !this.passwordTokenSeenFlag) { + this.passwordTokenSeenFlag = true; + continue; + } + const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); + if (this.passwordTokenSeenFlag) { + this.url.password += encodedCodePoints; + } else { + this.url.username += encodedCodePoints; + } + } + this.buffer = ""; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + if (this.atFlag && this.buffer === "") { + this.parseError = true; + return failure; + } + this.pointer -= countSymbols(this.buffer) + 1; + this.buffer = ""; + this.state = "host"; + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse hostname"] = +URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { + if (this.stateOverride && this.url.scheme === "file") { + --this.pointer; + this.state = "file host"; + } else if (c === 58 && !this.arrFlag) { + if (this.buffer === "") { + this.parseError = true; + return failure; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "port"; + if (this.stateOverride === "hostname") { + return false; + } + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + --this.pointer; + if (isSpecial(this.url) && this.buffer === "") { + this.parseError = true; + return failure; + } else if (this.stateOverride && this.buffer === "" && + (includesCredentials(this.url) || this.url.port !== null)) { + this.parseError = true; + return false; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "path start"; + if (this.stateOverride) { + return false; + } + } else { + if (c === 91) { + this.arrFlag = true; + } else if (c === 93) { + this.arrFlag = false; + } + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { + if (isASCIIDigit(c)) { + this.buffer += cStr; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92) || + this.stateOverride) { + if (this.buffer !== "") { + const port = parseInt(this.buffer); + if (port > Math.pow(2, 16) - 1) { + this.parseError = true; + return failure; + } + this.url.port = port === defaultPort(this.url.scheme) ? null : port; + this.buffer = ""; + } + if (this.stateOverride) { + return false; + } + this.state = "path start"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); + +URLStateMachine.prototype["parse file"] = function parseFile(c) { + this.url.scheme = "file"; + + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file slash"; + } else if (this.base !== null && this.base.scheme === "file") { + if (isNaN(c)) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 63) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else { + if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points + !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || + (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points + !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + shortenPath(this.url); + } else { + this.parseError = true; + } + + this.state = "path"; + --this.pointer; + } + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file host"; + } else { + if (this.base !== null && this.base.scheme === "file") { + if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { + this.url.path.push(this.base.path[0]); + } else { + this.url.host = this.base.host; + } + } + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { + if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { + --this.pointer; + if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { + this.parseError = true; + this.state = "path"; + } else if (this.buffer === "") { + this.url.host = ""; + if (this.stateOverride) { + return false; + } + this.state = "path start"; + } else { + let host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + if (host === "localhost") { + host = ""; + } + this.url.host = host; + + if (this.stateOverride) { + return false; + } + + this.buffer = ""; + this.state = "path start"; + } + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { + if (isSpecial(this.url)) { + if (c === 92) { + this.parseError = true; + } + this.state = "path"; + + if (c !== 47 && c !== 92) { + --this.pointer; + } + } else if (!this.stateOverride && c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (!this.stateOverride && c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (c !== undefined) { + this.state = "path"; + if (c !== 47) { + --this.pointer; + } + } + + return true; +}; + +URLStateMachine.prototype["parse path"] = function parsePath(c) { + if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || + (!this.stateOverride && (c === 63 || c === 35))) { + if (isSpecial(this.url) && c === 92) { + this.parseError = true; + } + + if (isDoubleDot(this.buffer)) { + shortenPath(this.url); + if (c !== 47 && !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } + } else if (isSingleDot(this.buffer) && c !== 47 && + !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } else if (!isSingleDot(this.buffer)) { + if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { + if (this.url.host !== "" && this.url.host !== null) { + this.parseError = true; + this.url.host = ""; + } + this.buffer = this.buffer[0] + ":"; + } + this.url.path.push(this.buffer); + } + this.buffer = ""; + if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { + while (this.url.path.length > 1 && this.url.path[0] === "") { + this.parseError = true; + this.url.path.shift(); + } + } + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += percentEncodeChar(c, isPathPercentEncode); + } + + return true; +}; + +URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else { + // TODO: Add: not a URL code point + if (!isNaN(c) && c !== 37) { + this.parseError = true; + } + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + if (!isNaN(c)) { + this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); + } + } + + return true; +}; + +URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { + if (isNaN(c) || (!this.stateOverride && c === 35)) { + if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { + this.encodingOverride = "utf-8"; + } + + const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead + for (let i = 0; i < buffer.length; ++i) { + if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || + buffer[i] === 0x3C || buffer[i] === 0x3E) { + this.url.query += percentEncode(buffer[i]); + } else { + this.url.query += String.fromCodePoint(buffer[i]); + } + } + + this.buffer = ""; + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { + if (isNaN(c)) { // do nothing + } else if (c === 0x0) { + this.parseError = true; + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); + } + + return true; +}; + +function serializeURL(url, excludeFragment) { + let output = url.scheme + ":"; + if (url.host !== null) { + output += "//"; + + if (url.username !== "" || url.password !== "") { + output += url.username; + if (url.password !== "") { + output += ":" + url.password; + } + output += "@"; + } + + output += serializeHost(url.host); + + if (url.port !== null) { + output += ":" + url.port; + } + } else if (url.host === null && url.scheme === "file") { + output += "//"; + } + + if (url.cannotBeABaseURL) { + output += url.path[0]; + } else { + for (const string of url.path) { + output += "/" + string; + } + } + + if (url.query !== null) { + output += "?" + url.query; + } + + if (!excludeFragment && url.fragment !== null) { + output += "#" + url.fragment; + } + + return output; +} + +function serializeOrigin(tuple) { + let result = tuple.scheme + "://"; + result += serializeHost(tuple.host); + + if (tuple.port !== null) { + result += ":" + tuple.port; + } + + return result; +} + +module.exports.serializeURL = serializeURL; + +module.exports.serializeURLOrigin = function (url) { + // https://url.spec.whatwg.org/#concept-url-origin + switch (url.scheme) { + case "blob": + try { + return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); + } catch (e) { + // serializing an opaque origin returns "null" + return "null"; + } + case "ftp": + case "gopher": + case "http": + case "https": + case "ws": + case "wss": + return serializeOrigin({ + scheme: url.scheme, + host: url.host, + port: url.port + }); + case "file": + // spec says "exercise to the reader", chrome says "file://" + return "file://"; + default: + // serializing an opaque origin returns "null" + return "null"; + } +}; + +module.exports.basicURLParse = function (input, options) { + if (options === undefined) { + options = {}; + } + + const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); + if (usm.failure) { + return "failure"; + } + + return usm.url; +}; + +module.exports.setTheUsername = function (url, username) { + url.username = ""; + const decoded = punycode.ucs2.decode(username); + for (let i = 0; i < decoded.length; ++i) { + url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.setThePassword = function (url, password) { + url.password = ""; + const decoded = punycode.ucs2.decode(password); + for (let i = 0; i < decoded.length; ++i) { + url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.serializeHost = serializeHost; + +module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; + +module.exports.serializeInteger = function (integer) { + return String(integer); +}; + +module.exports.parseURL = function (input, options) { + if (options === undefined) { + options = {}; + } + + // We don't handle blobs, so this just delegates: + return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); +}; diff --git a/node_modules/whatwg-url/lib/utils.js b/node_modules/whatwg-url/lib/utils.js new file mode 100644 index 0000000..a562009 --- /dev/null +++ b/node_modules/whatwg-url/lib/utils.js @@ -0,0 +1,20 @@ +"use strict"; + +module.exports.mixin = function mixin(target, source) { + const keys = Object.getOwnPropertyNames(source); + for (let i = 0; i < keys.length; ++i) { + Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i])); + } +}; + +module.exports.wrapperSymbol = Symbol("wrapper"); +module.exports.implSymbol = Symbol("impl"); + +module.exports.wrapperForImpl = function (impl) { + return impl[module.exports.wrapperSymbol]; +}; + +module.exports.implForWrapper = function (wrapper) { + return wrapper[module.exports.implSymbol]; +}; + diff --git a/node_modules/whatwg-url/package.json b/node_modules/whatwg-url/package.json new file mode 100644 index 0000000..fce35ae --- /dev/null +++ b/node_modules/whatwg-url/package.json @@ -0,0 +1,32 @@ +{ + "name": "whatwg-url", + "version": "5.0.0", + "description": "An implementation of the WHATWG URL Standard's URL API and parsing machinery", + "main": "lib/public-api.js", + "files": [ + "lib/" + ], + "author": "Sebastian Mayr ", + "license": "MIT", + "repository": "jsdom/whatwg-url", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + }, + "devDependencies": { + "eslint": "^2.6.0", + "istanbul": "~0.4.3", + "mocha": "^2.2.4", + "recast": "~0.10.29", + "request": "^2.55.0", + "webidl2js": "^3.0.2" + }, + "scripts": { + "build": "node scripts/transform.js && node scripts/convert-idl.js", + "coverage": "istanbul cover node_modules/mocha/bin/_mocha", + "lint": "eslint .", + "prepublish": "npm run build", + "pretest": "node scripts/get-latest-platform-tests.js && npm run build", + "test": "mocha" + } +} diff --git a/node_modules/wrap-ansi/index.js b/node_modules/wrap-ansi/index.js new file mode 100644 index 0000000..d502255 --- /dev/null +++ b/node_modules/wrap-ansi/index.js @@ -0,0 +1,216 @@ +'use strict'; +const stringWidth = require('string-width'); +const stripAnsi = require('strip-ansi'); +const ansiStyles = require('ansi-styles'); + +const ESCAPES = new Set([ + '\u001B', + '\u009B' +]); + +const END_CODE = 39; + +const ANSI_ESCAPE_BELL = '\u0007'; +const ANSI_CSI = '['; +const ANSI_OSC = ']'; +const ANSI_SGR_TERMINATOR = 'm'; +const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`; + +const wrapAnsi = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`; +const wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`; + +// Calculate the length of words split on ' ', ignoring +// the extra characters added by ansi escape codes +const wordLengths = string => string.split(' ').map(character => stringWidth(character)); + +// Wrap a long word across multiple rows +// Ansi escape codes do not count towards length +const wrapWord = (rows, word, columns) => { + const characters = [...word]; + + let isInsideEscape = false; + let isInsideLinkEscape = false; + let visible = stringWidth(stripAnsi(rows[rows.length - 1])); + + for (const [index, character] of characters.entries()) { + const characterLength = stringWidth(character); + + if (visible + characterLength <= columns) { + rows[rows.length - 1] += character; + } else { + rows.push(character); + visible = 0; + } + + if (ESCAPES.has(character)) { + isInsideEscape = true; + isInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK); + } + + if (isInsideEscape) { + if (isInsideLinkEscape) { + if (character === ANSI_ESCAPE_BELL) { + isInsideEscape = false; + isInsideLinkEscape = false; + } + } else if (character === ANSI_SGR_TERMINATOR) { + isInsideEscape = false; + } + + continue; + } + + visible += characterLength; + + if (visible === columns && index < characters.length - 1) { + rows.push(''); + visible = 0; + } + } + + // It's possible that the last row we copy over is only + // ansi escape characters, handle this edge-case + if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { + rows[rows.length - 2] += rows.pop(); + } +}; + +// Trims spaces from a string ignoring invisible sequences +const stringVisibleTrimSpacesRight = string => { + const words = string.split(' '); + let last = words.length; + + while (last > 0) { + if (stringWidth(words[last - 1]) > 0) { + break; + } + + last--; + } + + if (last === words.length) { + return string; + } + + return words.slice(0, last).join(' ') + words.slice(last).join(''); +}; + +// The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode +// +// 'hard' will never allow a string to take up more than columns characters +// +// 'soft' allows long words to expand past the column length +const exec = (string, columns, options = {}) => { + if (options.trim !== false && string.trim() === '') { + return ''; + } + + let returnValue = ''; + let escapeCode; + let escapeUrl; + + const lengths = wordLengths(string); + let rows = ['']; + + for (const [index, word] of string.split(' ').entries()) { + if (options.trim !== false) { + rows[rows.length - 1] = rows[rows.length - 1].trimStart(); + } + + let rowLength = stringWidth(rows[rows.length - 1]); + + if (index !== 0) { + if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { + // If we start with a new word but the current row length equals the length of the columns, add a new row + rows.push(''); + rowLength = 0; + } + + if (rowLength > 0 || options.trim === false) { + rows[rows.length - 1] += ' '; + rowLength++; + } + } + + // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns' + if (options.hard && lengths[index] > columns) { + const remainingColumns = (columns - rowLength); + const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); + const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); + if (breaksStartingNextLine < breaksStartingThisLine) { + rows.push(''); + } + + wrapWord(rows, word, columns); + continue; + } + + if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { + if (options.wordWrap === false && rowLength < columns) { + wrapWord(rows, word, columns); + continue; + } + + rows.push(''); + } + + if (rowLength + lengths[index] > columns && options.wordWrap === false) { + wrapWord(rows, word, columns); + continue; + } + + rows[rows.length - 1] += word; + } + + if (options.trim !== false) { + rows = rows.map(stringVisibleTrimSpacesRight); + } + + const pre = [...rows.join('\n')]; + + for (const [index, character] of pre.entries()) { + returnValue += character; + + if (ESCAPES.has(character)) { + const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?\\d+)m|\\${ANSI_ESCAPE_LINK}(?.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}}; + if (groups.code !== undefined) { + const code = Number.parseFloat(groups.code); + escapeCode = code === END_CODE ? undefined : code; + } else if (groups.uri !== undefined) { + escapeUrl = groups.uri.length === 0 ? undefined : groups.uri; + } + } + + const code = ansiStyles.codes.get(Number(escapeCode)); + + if (pre[index + 1] === '\n') { + if (escapeUrl) { + returnValue += wrapAnsiHyperlink(''); + } + + if (escapeCode && code) { + returnValue += wrapAnsi(code); + } + } else if (character === '\n') { + if (escapeCode && code) { + returnValue += wrapAnsi(escapeCode); + } + + if (escapeUrl) { + returnValue += wrapAnsiHyperlink(escapeUrl); + } + } + } + + return returnValue; +}; + +// For each newline, invoke the method separately +module.exports = (string, columns, options) => { + return String(string) + .normalize() + .replace(/\r\n/g, '\n') + .split('\n') + .map(line => exec(line, columns, options)) + .join('\n'); +}; diff --git a/node_modules/wrap-ansi/license b/node_modules/wrap-ansi/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/wrap-ansi/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/wrap-ansi/package.json b/node_modules/wrap-ansi/package.json new file mode 100644 index 0000000..dfb2f4f --- /dev/null +++ b/node_modules/wrap-ansi/package.json @@ -0,0 +1,62 @@ +{ + "name": "wrap-ansi", + "version": "7.0.0", + "description": "Wordwrap a string with ANSI escape codes", + "license": "MIT", + "repository": "chalk/wrap-ansi", + "funding": "https://github.com/chalk/wrap-ansi?sponsor=1", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && nyc ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "wrap", + "break", + "wordwrap", + "wordbreak", + "linewrap", + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "devDependencies": { + "ava": "^2.1.0", + "chalk": "^4.0.0", + "coveralls": "^3.0.3", + "has-ansi": "^4.0.0", + "nyc": "^15.0.1", + "xo": "^0.29.1" + } +} diff --git a/node_modules/wrap-ansi/readme.md b/node_modules/wrap-ansi/readme.md new file mode 100644 index 0000000..68779ba --- /dev/null +++ b/node_modules/wrap-ansi/readme.md @@ -0,0 +1,91 @@ +# wrap-ansi [![Build Status](https://travis-ci.com/chalk/wrap-ansi.svg?branch=master)](https://travis-ci.com/chalk/wrap-ansi) [![Coverage Status](https://coveralls.io/repos/github/chalk/wrap-ansi/badge.svg?branch=master)](https://coveralls.io/github/chalk/wrap-ansi?branch=master) + +> Wordwrap a string with [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) + +## Install + +``` +$ npm install wrap-ansi +``` + +## Usage + +```js +const chalk = require('chalk'); +const wrapAnsi = require('wrap-ansi'); + +const input = 'The quick brown ' + chalk.red('fox jumped over ') + + 'the lazy ' + chalk.green('dog and then ran away with the unicorn.'); + +console.log(wrapAnsi(input, 20)); +``` + + + +## API + +### wrapAnsi(string, columns, options?) + +Wrap words to the specified column width. + +#### string + +Type: `string` + +String with ANSI escape codes. Like one styled by [`chalk`](https://github.com/chalk/chalk). Newline characters will be normalized to `\n`. + +#### columns + +Type: `number` + +Number of columns to wrap the text to. + +#### options + +Type: `object` + +##### hard + +Type: `boolean`\ +Default: `false` + +By default the wrap is soft, meaning long words may extend past the column width. Setting this to `true` will make it hard wrap at the column width. + +##### wordWrap + +Type: `boolean`\ +Default: `true` + +By default, an attempt is made to split words at spaces, ensuring that they don't extend past the configured columns. If wordWrap is `false`, each column will instead be completely filled splitting words as necessary. + +##### trim + +Type: `boolean`\ +Default: `true` + +Whitespace on all lines is removed by default. Set this option to `false` if you don't want to trim. + +## Related + +- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes +- [cli-truncate](https://github.com/sindresorhus/cli-truncate) - Truncate a string to a specific width in the terminal +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right +- [jsesc](https://github.com/mathiasbynens/jsesc) - Generate ASCII-only output from Unicode strings. Useful for creating test fixtures. + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) +- [Benjamin Coe](https://github.com/bcoe) + +--- + +
                          + + Get professional support for this package with a Tidelift subscription + +
                          + + Tidelift helps make open source sustainable for maintainers while giving companies
                          assurances about security, maintenance, and licensing for their dependencies. +
                          +
                          diff --git a/node_modules/wrappy/LICENSE b/node_modules/wrappy/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/wrappy/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/wrappy/README.md b/node_modules/wrappy/README.md new file mode 100644 index 0000000..98eab25 --- /dev/null +++ b/node_modules/wrappy/README.md @@ -0,0 +1,36 @@ +# wrappy + +Callback wrapping utility + +## USAGE + +```javascript +var wrappy = require("wrappy") + +// var wrapper = wrappy(wrapperFunction) + +// make sure a cb is called only once +// See also: http://npm.im/once for this specific use case +var once = wrappy(function (cb) { + var called = false + return function () { + if (called) return + called = true + return cb.apply(this, arguments) + } +}) + +function printBoo () { + console.log('boo') +} +// has some rando property +printBoo.iAmBooPrinter = true + +var onlyPrintOnce = once(printBoo) + +onlyPrintOnce() // prints 'boo' +onlyPrintOnce() // does nothing + +// random property is retained! +assert.equal(onlyPrintOnce.iAmBooPrinter, true) +``` diff --git a/node_modules/wrappy/package.json b/node_modules/wrappy/package.json new file mode 100644 index 0000000..1307520 --- /dev/null +++ b/node_modules/wrappy/package.json @@ -0,0 +1,29 @@ +{ + "name": "wrappy", + "version": "1.0.2", + "description": "Callback wrapping utility", + "main": "wrappy.js", + "files": [ + "wrappy.js" + ], + "directories": { + "test": "test" + }, + "dependencies": {}, + "devDependencies": { + "tap": "^2.3.1" + }, + "scripts": { + "test": "tap --coverage test/*.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/npm/wrappy" + }, + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC", + "bugs": { + "url": "https://github.com/npm/wrappy/issues" + }, + "homepage": "https://github.com/npm/wrappy" +} diff --git a/node_modules/wrappy/wrappy.js b/node_modules/wrappy/wrappy.js new file mode 100644 index 0000000..bb7e7d6 --- /dev/null +++ b/node_modules/wrappy/wrappy.js @@ -0,0 +1,33 @@ +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +module.exports = wrappy +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) + + return wrapper + + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + var ret = fn.apply(this, args) + var cb = args[args.length-1] + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k] + }) + } + return ret + } +} diff --git a/node_modules/y18n/CHANGELOG.md b/node_modules/y18n/CHANGELOG.md new file mode 100644 index 0000000..244d838 --- /dev/null +++ b/node_modules/y18n/CHANGELOG.md @@ -0,0 +1,100 @@ +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +### [5.0.8](https://www.github.com/yargs/y18n/compare/v5.0.7...v5.0.8) (2021-04-07) + + +### Bug Fixes + +* **deno:** force modern release for Deno ([b1c215a](https://www.github.com/yargs/y18n/commit/b1c215aed714bee5830e76de3e335504dc2c4dab)) + +### [5.0.7](https://www.github.com/yargs/y18n/compare/v5.0.6...v5.0.7) (2021-04-07) + + +### Bug Fixes + +* **deno:** force release for deno ([#121](https://www.github.com/yargs/y18n/issues/121)) ([d3f2560](https://www.github.com/yargs/y18n/commit/d3f2560e6cedf2bfa2352e9eec044da53f9a06b2)) + +### [5.0.6](https://www.github.com/yargs/y18n/compare/v5.0.5...v5.0.6) (2021-04-05) + + +### Bug Fixes + +* **webpack:** skip readFileSync if not defined ([#117](https://www.github.com/yargs/y18n/issues/117)) ([6966fa9](https://www.github.com/yargs/y18n/commit/6966fa91d2881cc6a6c531e836099e01f4da1616)) + +### [5.0.5](https://www.github.com/yargs/y18n/compare/v5.0.4...v5.0.5) (2020-10-25) + + +### Bug Fixes + +* address prototype pollution issue ([#108](https://www.github.com/yargs/y18n/issues/108)) ([a9ac604](https://www.github.com/yargs/y18n/commit/a9ac604abf756dec9687be3843e2c93bfe581f25)) + +### [5.0.4](https://www.github.com/yargs/y18n/compare/v5.0.3...v5.0.4) (2020-10-16) + + +### Bug Fixes + +* **exports:** node 13.0 and 13.1 require the dotted object form _with_ a string fallback ([#105](https://www.github.com/yargs/y18n/issues/105)) ([4f85d80](https://www.github.com/yargs/y18n/commit/4f85d80dbaae6d2c7899ae394f7ad97805df4886)) + +### [5.0.3](https://www.github.com/yargs/y18n/compare/v5.0.2...v5.0.3) (2020-10-16) + + +### Bug Fixes + +* **exports:** node 13.0-13.6 require a string fallback ([#103](https://www.github.com/yargs/y18n/issues/103)) ([e39921e](https://www.github.com/yargs/y18n/commit/e39921e1017f88f5d8ea97ddea854ffe92d68e74)) + +### [5.0.2](https://www.github.com/yargs/y18n/compare/v5.0.1...v5.0.2) (2020-10-01) + + +### Bug Fixes + +* **deno:** update types for deno ^1.4.0 ([#100](https://www.github.com/yargs/y18n/issues/100)) ([3834d9a](https://www.github.com/yargs/y18n/commit/3834d9ab1332f2937c935ada5e76623290efae81)) + +### [5.0.1](https://www.github.com/yargs/y18n/compare/v5.0.0...v5.0.1) (2020-09-05) + + +### Bug Fixes + +* main had old index path ([#98](https://www.github.com/yargs/y18n/issues/98)) ([124f7b0](https://www.github.com/yargs/y18n/commit/124f7b047ba9596bdbdf64459988304e77f3de1b)) + +## [5.0.0](https://www.github.com/yargs/y18n/compare/v4.0.0...v5.0.0) (2020-09-05) + + +### ⚠ BREAKING CHANGES + +* exports maps are now used, which modifies import behavior. +* drops Node 6 and 4. begin following Node.js LTS schedule (#89) + +### Features + +* add support for ESM and Deno [#95](https://www.github.com/yargs/y18n/issues/95)) ([4d7ae94](https://www.github.com/yargs/y18n/commit/4d7ae94bcb42e84164e2180366474b1cd321ed94)) + + +### Build System + +* drops Node 6 and 4. begin following Node.js LTS schedule ([#89](https://www.github.com/yargs/y18n/issues/89)) ([3cc0c28](https://www.github.com/yargs/y18n/commit/3cc0c287240727b84eaf1927f903612ec80f5e43)) + +### 4.0.1 (2020-10-25) + + +### Bug Fixes + +* address prototype pollution issue ([#108](https://www.github.com/yargs/y18n/issues/108)) ([a9ac604](https://www.github.com/yargs/y18n/commit/7de58ca0d315990cdb38234e97fc66254cdbcd71)) + +## [4.0.0](https://github.com/yargs/y18n/compare/v3.2.1...v4.0.0) (2017-10-10) + + +### Bug Fixes + +* allow support for falsy values like 0 in tagged literal ([#45](https://github.com/yargs/y18n/issues/45)) ([c926123](https://github.com/yargs/y18n/commit/c926123)) + + +### Features + +* **__:** added tagged template literal support ([#44](https://github.com/yargs/y18n/issues/44)) ([0598daf](https://github.com/yargs/y18n/commit/0598daf)) + + +### BREAKING CHANGES + +* **__:** dropping Node 0.10/Node 0.12 support diff --git a/node_modules/y18n/LICENSE b/node_modules/y18n/LICENSE new file mode 100644 index 0000000..3c157f0 --- /dev/null +++ b/node_modules/y18n/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2015, Contributors + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. diff --git a/node_modules/y18n/README.md b/node_modules/y18n/README.md new file mode 100644 index 0000000..5102bb1 --- /dev/null +++ b/node_modules/y18n/README.md @@ -0,0 +1,127 @@ +# y18n + +[![NPM version][npm-image]][npm-url] +[![js-standard-style][standard-image]][standard-url] +[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) + +The bare-bones internationalization library used by yargs. + +Inspired by [i18n](https://www.npmjs.com/package/i18n). + +## Examples + +_simple string translation:_ + +```js +const __ = require('y18n')().__; + +console.log(__('my awesome string %s', 'foo')); +``` + +output: + +`my awesome string foo` + +_using tagged template literals_ + +```js +const __ = require('y18n')().__; + +const str = 'foo'; + +console.log(__`my awesome string ${str}`); +``` + +output: + +`my awesome string foo` + +_pluralization support:_ + +```js +const __n = require('y18n')().__n; + +console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')); +``` + +output: + +`2 fishes foo` + +## Deno Example + +As of `v5` `y18n` supports [Deno](https://github.com/denoland/deno): + +```typescript +import y18n from "https://deno.land/x/y18n/deno.ts"; + +const __ = y18n({ + locale: 'pirate', + directory: './test/locales' +}).__ + +console.info(__`Hi, ${'Ben'} ${'Coe'}!`) +``` + +You will need to run with `--allow-read` to load alternative locales. + +## JSON Language Files + +The JSON language files should be stored in a `./locales` folder. +File names correspond to locales, e.g., `en.json`, `pirate.json`. + +When strings are observed for the first time they will be +added to the JSON file corresponding to the current locale. + +## Methods + +### require('y18n')(config) + +Create an instance of y18n with the config provided, options include: + +* `directory`: the locale directory, default `./locales`. +* `updateFiles`: should newly observed strings be updated in file, default `true`. +* `locale`: what locale should be used. +* `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) + be allowed if a file matching the locale does not exist (e.g. `en_US.json`), + default `true`. + +### y18n.\_\_(str, arg, arg, arg) + +Print a localized string, `%s` will be replaced with `arg`s. + +This function can also be used as a tag for a template literal. You can use it +like this: __`hello ${'world'}`. This will be equivalent to +`__('hello %s', 'world')`. + +### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) + +Print a localized string with appropriate pluralization. If `%d` is provided +in the string, the `count` will replace this placeholder. + +### y18n.setLocale(str) + +Set the current locale being used. + +### y18n.getLocale() + +What locale is currently being used? + +### y18n.updateLocale(obj) + +Update the current locale with the key value pairs in `obj`. + +## Supported Node.js Versions + +Libraries in this ecosystem make a best effort to track +[Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a +post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). + +## License + +ISC + +[npm-url]: https://npmjs.org/package/y18n +[npm-image]: https://img.shields.io/npm/v/y18n.svg +[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg +[standard-url]: https://github.com/feross/standard diff --git a/node_modules/y18n/build/index.cjs b/node_modules/y18n/build/index.cjs new file mode 100644 index 0000000..b2731e1 --- /dev/null +++ b/node_modules/y18n/build/index.cjs @@ -0,0 +1,203 @@ +'use strict'; + +var fs = require('fs'); +var util = require('util'); +var path = require('path'); + +let shim; +class Y18N { + constructor(opts) { + // configurable options. + opts = opts || {}; + this.directory = opts.directory || './locales'; + this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true; + this.locale = opts.locale || 'en'; + this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true; + // internal stuff. + this.cache = Object.create(null); + this.writeQueue = []; + } + __(...args) { + if (typeof arguments[0] !== 'string') { + return this._taggedLiteral(arguments[0], ...arguments); + } + const str = args.shift(); + let cb = function () { }; // start with noop. + if (typeof args[args.length - 1] === 'function') + cb = args.pop(); + cb = cb || function () { }; // noop. + if (!this.cache[this.locale]) + this._readLocaleFile(); + // we've observed a new string, update the language file. + if (!this.cache[this.locale][str] && this.updateFiles) { + this.cache[this.locale][str] = str; + // include the current directory and locale, + // since these values could change before the + // write is performed. + this._enqueueWrite({ + directory: this.directory, + locale: this.locale, + cb + }); + } + else { + cb(); + } + return shim.format.apply(shim.format, [this.cache[this.locale][str] || str].concat(args)); + } + __n() { + const args = Array.prototype.slice.call(arguments); + const singular = args.shift(); + const plural = args.shift(); + const quantity = args.shift(); + let cb = function () { }; // start with noop. + if (typeof args[args.length - 1] === 'function') + cb = args.pop(); + if (!this.cache[this.locale]) + this._readLocaleFile(); + let str = quantity === 1 ? singular : plural; + if (this.cache[this.locale][singular]) { + const entry = this.cache[this.locale][singular]; + str = entry[quantity === 1 ? 'one' : 'other']; + } + // we've observed a new string, update the language file. + if (!this.cache[this.locale][singular] && this.updateFiles) { + this.cache[this.locale][singular] = { + one: singular, + other: plural + }; + // include the current directory and locale, + // since these values could change before the + // write is performed. + this._enqueueWrite({ + directory: this.directory, + locale: this.locale, + cb + }); + } + else { + cb(); + } + // if a %d placeholder is provided, add quantity + // to the arguments expanded by util.format. + const values = [str]; + if (~str.indexOf('%d')) + values.push(quantity); + return shim.format.apply(shim.format, values.concat(args)); + } + setLocale(locale) { + this.locale = locale; + } + getLocale() { + return this.locale; + } + updateLocale(obj) { + if (!this.cache[this.locale]) + this._readLocaleFile(); + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + this.cache[this.locale][key] = obj[key]; + } + } + } + _taggedLiteral(parts, ...args) { + let str = ''; + parts.forEach(function (part, i) { + const arg = args[i + 1]; + str += part; + if (typeof arg !== 'undefined') { + str += '%s'; + } + }); + return this.__.apply(this, [str].concat([].slice.call(args, 1))); + } + _enqueueWrite(work) { + this.writeQueue.push(work); + if (this.writeQueue.length === 1) + this._processWriteQueue(); + } + _processWriteQueue() { + const _this = this; + const work = this.writeQueue[0]; + // destructure the enqueued work. + const directory = work.directory; + const locale = work.locale; + const cb = work.cb; + const languageFile = this._resolveLocaleFile(directory, locale); + const serializedLocale = JSON.stringify(this.cache[locale], null, 2); + shim.fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) { + _this.writeQueue.shift(); + if (_this.writeQueue.length > 0) + _this._processWriteQueue(); + cb(err); + }); + } + _readLocaleFile() { + let localeLookup = {}; + const languageFile = this._resolveLocaleFile(this.directory, this.locale); + try { + // When using a bundler such as webpack, readFileSync may not be defined: + if (shim.fs.readFileSync) { + localeLookup = JSON.parse(shim.fs.readFileSync(languageFile, 'utf-8')); + } + } + catch (err) { + if (err instanceof SyntaxError) { + err.message = 'syntax error in ' + languageFile; + } + if (err.code === 'ENOENT') + localeLookup = {}; + else + throw err; + } + this.cache[this.locale] = localeLookup; + } + _resolveLocaleFile(directory, locale) { + let file = shim.resolve(directory, './', locale + '.json'); + if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) { + // attempt fallback to language only + const languageFile = shim.resolve(directory, './', locale.split('_')[0] + '.json'); + if (this._fileExistsSync(languageFile)) + file = languageFile; + } + return file; + } + _fileExistsSync(file) { + return shim.exists(file); + } +} +function y18n$1(opts, _shim) { + shim = _shim; + const y18n = new Y18N(opts); + return { + __: y18n.__.bind(y18n), + __n: y18n.__n.bind(y18n), + setLocale: y18n.setLocale.bind(y18n), + getLocale: y18n.getLocale.bind(y18n), + updateLocale: y18n.updateLocale.bind(y18n), + locale: y18n.locale + }; +} + +var nodePlatformShim = { + fs: { + readFileSync: fs.readFileSync, + writeFile: fs.writeFile + }, + format: util.format, + resolve: path.resolve, + exists: (file) => { + try { + return fs.statSync(file).isFile(); + } + catch (err) { + return false; + } + } +}; + +const y18n = (opts) => { + return y18n$1(opts, nodePlatformShim); +}; + +module.exports = y18n; diff --git a/node_modules/y18n/build/lib/cjs.js b/node_modules/y18n/build/lib/cjs.js new file mode 100644 index 0000000..ff58470 --- /dev/null +++ b/node_modules/y18n/build/lib/cjs.js @@ -0,0 +1,6 @@ +import { y18n as _y18n } from './index.js'; +import nodePlatformShim from './platform-shims/node.js'; +const y18n = (opts) => { + return _y18n(opts, nodePlatformShim); +}; +export default y18n; diff --git a/node_modules/y18n/build/lib/index.js b/node_modules/y18n/build/lib/index.js new file mode 100644 index 0000000..e38f335 --- /dev/null +++ b/node_modules/y18n/build/lib/index.js @@ -0,0 +1,174 @@ +let shim; +class Y18N { + constructor(opts) { + // configurable options. + opts = opts || {}; + this.directory = opts.directory || './locales'; + this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true; + this.locale = opts.locale || 'en'; + this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true; + // internal stuff. + this.cache = Object.create(null); + this.writeQueue = []; + } + __(...args) { + if (typeof arguments[0] !== 'string') { + return this._taggedLiteral(arguments[0], ...arguments); + } + const str = args.shift(); + let cb = function () { }; // start with noop. + if (typeof args[args.length - 1] === 'function') + cb = args.pop(); + cb = cb || function () { }; // noop. + if (!this.cache[this.locale]) + this._readLocaleFile(); + // we've observed a new string, update the language file. + if (!this.cache[this.locale][str] && this.updateFiles) { + this.cache[this.locale][str] = str; + // include the current directory and locale, + // since these values could change before the + // write is performed. + this._enqueueWrite({ + directory: this.directory, + locale: this.locale, + cb + }); + } + else { + cb(); + } + return shim.format.apply(shim.format, [this.cache[this.locale][str] || str].concat(args)); + } + __n() { + const args = Array.prototype.slice.call(arguments); + const singular = args.shift(); + const plural = args.shift(); + const quantity = args.shift(); + let cb = function () { }; // start with noop. + if (typeof args[args.length - 1] === 'function') + cb = args.pop(); + if (!this.cache[this.locale]) + this._readLocaleFile(); + let str = quantity === 1 ? singular : plural; + if (this.cache[this.locale][singular]) { + const entry = this.cache[this.locale][singular]; + str = entry[quantity === 1 ? 'one' : 'other']; + } + // we've observed a new string, update the language file. + if (!this.cache[this.locale][singular] && this.updateFiles) { + this.cache[this.locale][singular] = { + one: singular, + other: plural + }; + // include the current directory and locale, + // since these values could change before the + // write is performed. + this._enqueueWrite({ + directory: this.directory, + locale: this.locale, + cb + }); + } + else { + cb(); + } + // if a %d placeholder is provided, add quantity + // to the arguments expanded by util.format. + const values = [str]; + if (~str.indexOf('%d')) + values.push(quantity); + return shim.format.apply(shim.format, values.concat(args)); + } + setLocale(locale) { + this.locale = locale; + } + getLocale() { + return this.locale; + } + updateLocale(obj) { + if (!this.cache[this.locale]) + this._readLocaleFile(); + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + this.cache[this.locale][key] = obj[key]; + } + } + } + _taggedLiteral(parts, ...args) { + let str = ''; + parts.forEach(function (part, i) { + const arg = args[i + 1]; + str += part; + if (typeof arg !== 'undefined') { + str += '%s'; + } + }); + return this.__.apply(this, [str].concat([].slice.call(args, 1))); + } + _enqueueWrite(work) { + this.writeQueue.push(work); + if (this.writeQueue.length === 1) + this._processWriteQueue(); + } + _processWriteQueue() { + const _this = this; + const work = this.writeQueue[0]; + // destructure the enqueued work. + const directory = work.directory; + const locale = work.locale; + const cb = work.cb; + const languageFile = this._resolveLocaleFile(directory, locale); + const serializedLocale = JSON.stringify(this.cache[locale], null, 2); + shim.fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) { + _this.writeQueue.shift(); + if (_this.writeQueue.length > 0) + _this._processWriteQueue(); + cb(err); + }); + } + _readLocaleFile() { + let localeLookup = {}; + const languageFile = this._resolveLocaleFile(this.directory, this.locale); + try { + // When using a bundler such as webpack, readFileSync may not be defined: + if (shim.fs.readFileSync) { + localeLookup = JSON.parse(shim.fs.readFileSync(languageFile, 'utf-8')); + } + } + catch (err) { + if (err instanceof SyntaxError) { + err.message = 'syntax error in ' + languageFile; + } + if (err.code === 'ENOENT') + localeLookup = {}; + else + throw err; + } + this.cache[this.locale] = localeLookup; + } + _resolveLocaleFile(directory, locale) { + let file = shim.resolve(directory, './', locale + '.json'); + if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) { + // attempt fallback to language only + const languageFile = shim.resolve(directory, './', locale.split('_')[0] + '.json'); + if (this._fileExistsSync(languageFile)) + file = languageFile; + } + return file; + } + _fileExistsSync(file) { + return shim.exists(file); + } +} +export function y18n(opts, _shim) { + shim = _shim; + const y18n = new Y18N(opts); + return { + __: y18n.__.bind(y18n), + __n: y18n.__n.bind(y18n), + setLocale: y18n.setLocale.bind(y18n), + getLocale: y18n.getLocale.bind(y18n), + updateLocale: y18n.updateLocale.bind(y18n), + locale: y18n.locale + }; +} diff --git a/node_modules/y18n/build/lib/platform-shims/node.js b/node_modules/y18n/build/lib/platform-shims/node.js new file mode 100644 index 0000000..181208b --- /dev/null +++ b/node_modules/y18n/build/lib/platform-shims/node.js @@ -0,0 +1,19 @@ +import { readFileSync, statSync, writeFile } from 'fs'; +import { format } from 'util'; +import { resolve } from 'path'; +export default { + fs: { + readFileSync, + writeFile + }, + format, + resolve, + exists: (file) => { + try { + return statSync(file).isFile(); + } + catch (err) { + return false; + } + } +}; diff --git a/node_modules/y18n/index.mjs b/node_modules/y18n/index.mjs new file mode 100644 index 0000000..46c8213 --- /dev/null +++ b/node_modules/y18n/index.mjs @@ -0,0 +1,8 @@ +import shim from './build/lib/platform-shims/node.js' +import { y18n as _y18n } from './build/lib/index.js' + +const y18n = (opts) => { + return _y18n(opts, shim) +} + +export default y18n diff --git a/node_modules/y18n/package.json b/node_modules/y18n/package.json new file mode 100644 index 0000000..4e5c1ca --- /dev/null +++ b/node_modules/y18n/package.json @@ -0,0 +1,70 @@ +{ + "name": "y18n", + "version": "5.0.8", + "description": "the bare-bones internationalization library used by yargs", + "exports": { + ".": [ + { + "import": "./index.mjs", + "require": "./build/index.cjs" + }, + "./build/index.cjs" + ] + }, + "type": "module", + "module": "./build/lib/index.js", + "keywords": [ + "i18n", + "internationalization", + "yargs" + ], + "homepage": "https://github.com/yargs/y18n", + "bugs": { + "url": "https://github.com/yargs/y18n/issues" + }, + "repository": "yargs/y18n", + "license": "ISC", + "author": "Ben Coe ", + "main": "./build/index.cjs", + "scripts": { + "check": "standardx **/*.ts **/*.cjs **/*.mjs", + "fix": "standardx --fix **/*.ts **/*.cjs **/*.mjs", + "pretest": "rimraf build && tsc -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs", + "test": "c8 --reporter=text --reporter=html mocha test/*.cjs", + "test:esm": "c8 --reporter=text --reporter=html mocha test/esm/*.mjs", + "posttest": "npm run check", + "coverage": "c8 report --check-coverage", + "precompile": "rimraf build", + "compile": "tsc", + "postcompile": "npm run build:cjs", + "build:cjs": "rollup -c", + "prepare": "npm run compile" + }, + "devDependencies": { + "@types/node": "^14.6.4", + "@wessberg/rollup-plugin-ts": "^1.3.1", + "c8": "^7.3.0", + "chai": "^4.0.1", + "cross-env": "^7.0.2", + "gts": "^3.0.0", + "mocha": "^8.0.0", + "rimraf": "^3.0.2", + "rollup": "^2.26.10", + "standardx": "^7.0.0", + "ts-transform-default-export": "^1.0.2", + "typescript": "^4.0.0" + }, + "files": [ + "build", + "index.mjs", + "!*.d.ts" + ], + "engines": { + "node": ">=10" + }, + "standardx": { + "ignore": [ + "build" + ] + } +} diff --git a/node_modules/yallist/LICENSE b/node_modules/yallist/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/yallist/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/yallist/README.md b/node_modules/yallist/README.md new file mode 100644 index 0000000..f586101 --- /dev/null +++ b/node_modules/yallist/README.md @@ -0,0 +1,204 @@ +# yallist + +Yet Another Linked List + +There are many doubly-linked list implementations like it, but this +one is mine. + +For when an array would be too big, and a Map can't be iterated in +reverse order. + + +[![Build Status](https://travis-ci.org/isaacs/yallist.svg?branch=master)](https://travis-ci.org/isaacs/yallist) [![Coverage Status](https://coveralls.io/repos/isaacs/yallist/badge.svg?service=github)](https://coveralls.io/github/isaacs/yallist) + +## basic usage + +```javascript +var yallist = require('yallist') +var myList = yallist.create([1, 2, 3]) +myList.push('foo') +myList.unshift('bar') +// of course pop() and shift() are there, too +console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo'] +myList.forEach(function (k) { + // walk the list head to tail +}) +myList.forEachReverse(function (k, index, list) { + // walk the list tail to head +}) +var myDoubledList = myList.map(function (k) { + return k + k +}) +// now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo'] +// mapReverse is also a thing +var myDoubledListReverse = myList.mapReverse(function (k) { + return k + k +}) // ['foofoo', 6, 4, 2, 'barbar'] + +var reduced = myList.reduce(function (set, entry) { + set += entry + return set +}, 'start') +console.log(reduced) // 'startfoo123bar' +``` + +## api + +The whole API is considered "public". + +Functions with the same name as an Array method work more or less the +same way. + +There's reverse versions of most things because that's the point. + +### Yallist + +Default export, the class that holds and manages a list. + +Call it with either a forEach-able (like an array) or a set of +arguments, to initialize the list. + +The Array-ish methods all act like you'd expect. No magic length, +though, so if you change that it won't automatically prune or add +empty spots. + +### Yallist.create(..) + +Alias for Yallist function. Some people like factories. + +#### yallist.head + +The first node in the list + +#### yallist.tail + +The last node in the list + +#### yallist.length + +The number of nodes in the list. (Change this at your peril. It is +not magic like Array length.) + +#### yallist.toArray() + +Convert the list to an array. + +#### yallist.forEach(fn, [thisp]) + +Call a function on each item in the list. + +#### yallist.forEachReverse(fn, [thisp]) + +Call a function on each item in the list, in reverse order. + +#### yallist.get(n) + +Get the data at position `n` in the list. If you use this a lot, +probably better off just using an Array. + +#### yallist.getReverse(n) + +Get the data at position `n`, counting from the tail. + +#### yallist.map(fn, thisp) + +Create a new Yallist with the result of calling the function on each +item. + +#### yallist.mapReverse(fn, thisp) + +Same as `map`, but in reverse. + +#### yallist.pop() + +Get the data from the list tail, and remove the tail from the list. + +#### yallist.push(item, ...) + +Insert one or more items to the tail of the list. + +#### yallist.reduce(fn, initialValue) + +Like Array.reduce. + +#### yallist.reduceReverse + +Like Array.reduce, but in reverse. + +#### yallist.reverse + +Reverse the list in place. + +#### yallist.shift() + +Get the data from the list head, and remove the head from the list. + +#### yallist.slice([from], [to]) + +Just like Array.slice, but returns a new Yallist. + +#### yallist.sliceReverse([from], [to]) + +Just like yallist.slice, but the result is returned in reverse. + +#### yallist.toArray() + +Create an array representation of the list. + +#### yallist.toArrayReverse() + +Create a reversed array representation of the list. + +#### yallist.unshift(item, ...) + +Insert one or more items to the head of the list. + +#### yallist.unshiftNode(node) + +Move a Node object to the front of the list. (That is, pull it out of +wherever it lives, and make it the new head.) + +If the node belongs to a different list, then that list will remove it +first. + +#### yallist.pushNode(node) + +Move a Node object to the end of the list. (That is, pull it out of +wherever it lives, and make it the new tail.) + +If the node belongs to a list already, then that list will remove it +first. + +#### yallist.removeNode(node) + +Remove a node from the list, preserving referential integrity of head +and tail and other nodes. + +Will throw an error if you try to have a list remove a node that +doesn't belong to it. + +### Yallist.Node + +The class that holds the data and is actually the list. + +Call with `var n = new Node(value, previousNode, nextNode)` + +Note that if you do direct operations on Nodes themselves, it's very +easy to get into weird states where the list is broken. Be careful :) + +#### node.next + +The next node in the list. + +#### node.prev + +The previous node in the list. + +#### node.value + +The data the node contains. + +#### node.list + +The list to which this node belongs. (Null if it does not belong to +any list.) diff --git a/node_modules/yallist/iterator.js b/node_modules/yallist/iterator.js new file mode 100644 index 0000000..d41c97a --- /dev/null +++ b/node_modules/yallist/iterator.js @@ -0,0 +1,8 @@ +'use strict' +module.exports = function (Yallist) { + Yallist.prototype[Symbol.iterator] = function* () { + for (let walker = this.head; walker; walker = walker.next) { + yield walker.value + } + } +} diff --git a/node_modules/yallist/package.json b/node_modules/yallist/package.json new file mode 100644 index 0000000..8a08386 --- /dev/null +++ b/node_modules/yallist/package.json @@ -0,0 +1,29 @@ +{ + "name": "yallist", + "version": "4.0.0", + "description": "Yet Another Linked List", + "main": "yallist.js", + "directories": { + "test": "test" + }, + "files": [ + "yallist.js", + "iterator.js" + ], + "dependencies": {}, + "devDependencies": { + "tap": "^12.1.0" + }, + "scripts": { + "test": "tap test/*.js --100", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --all; git push origin --tags" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/yallist.git" + }, + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC" +} diff --git a/node_modules/yallist/yallist.js b/node_modules/yallist/yallist.js new file mode 100644 index 0000000..4e83ab1 --- /dev/null +++ b/node_modules/yallist/yallist.js @@ -0,0 +1,426 @@ +'use strict' +module.exports = Yallist + +Yallist.Node = Node +Yallist.create = Yallist + +function Yallist (list) { + var self = this + if (!(self instanceof Yallist)) { + self = new Yallist() + } + + self.tail = null + self.head = null + self.length = 0 + + if (list && typeof list.forEach === 'function') { + list.forEach(function (item) { + self.push(item) + }) + } else if (arguments.length > 0) { + for (var i = 0, l = arguments.length; i < l; i++) { + self.push(arguments[i]) + } + } + + return self +} + +Yallist.prototype.removeNode = function (node) { + if (node.list !== this) { + throw new Error('removing node which does not belong to this list') + } + + var next = node.next + var prev = node.prev + + if (next) { + next.prev = prev + } + + if (prev) { + prev.next = next + } + + if (node === this.head) { + this.head = next + } + if (node === this.tail) { + this.tail = prev + } + + node.list.length-- + node.next = null + node.prev = null + node.list = null + + return next +} + +Yallist.prototype.unshiftNode = function (node) { + if (node === this.head) { + return + } + + if (node.list) { + node.list.removeNode(node) + } + + var head = this.head + node.list = this + node.next = head + if (head) { + head.prev = node + } + + this.head = node + if (!this.tail) { + this.tail = node + } + this.length++ +} + +Yallist.prototype.pushNode = function (node) { + if (node === this.tail) { + return + } + + if (node.list) { + node.list.removeNode(node) + } + + var tail = this.tail + node.list = this + node.prev = tail + if (tail) { + tail.next = node + } + + this.tail = node + if (!this.head) { + this.head = node + } + this.length++ +} + +Yallist.prototype.push = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + push(this, arguments[i]) + } + return this.length +} + +Yallist.prototype.unshift = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + unshift(this, arguments[i]) + } + return this.length +} + +Yallist.prototype.pop = function () { + if (!this.tail) { + return undefined + } + + var res = this.tail.value + this.tail = this.tail.prev + if (this.tail) { + this.tail.next = null + } else { + this.head = null + } + this.length-- + return res +} + +Yallist.prototype.shift = function () { + if (!this.head) { + return undefined + } + + var res = this.head.value + this.head = this.head.next + if (this.head) { + this.head.prev = null + } else { + this.tail = null + } + this.length-- + return res +} + +Yallist.prototype.forEach = function (fn, thisp) { + thisp = thisp || this + for (var walker = this.head, i = 0; walker !== null; i++) { + fn.call(thisp, walker.value, i, this) + walker = walker.next + } +} + +Yallist.prototype.forEachReverse = function (fn, thisp) { + thisp = thisp || this + for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { + fn.call(thisp, walker.value, i, this) + walker = walker.prev + } +} + +Yallist.prototype.get = function (n) { + for (var i = 0, walker = this.head; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.next + } + if (i === n && walker !== null) { + return walker.value + } +} + +Yallist.prototype.getReverse = function (n) { + for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.prev + } + if (i === n && walker !== null) { + return walker.value + } +} + +Yallist.prototype.map = function (fn, thisp) { + thisp = thisp || this + var res = new Yallist() + for (var walker = this.head; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)) + walker = walker.next + } + return res +} + +Yallist.prototype.mapReverse = function (fn, thisp) { + thisp = thisp || this + var res = new Yallist() + for (var walker = this.tail; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)) + walker = walker.prev + } + return res +} + +Yallist.prototype.reduce = function (fn, initial) { + var acc + var walker = this.head + if (arguments.length > 1) { + acc = initial + } else if (this.head) { + walker = this.head.next + acc = this.head.value + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = 0; walker !== null; i++) { + acc = fn(acc, walker.value, i) + walker = walker.next + } + + return acc +} + +Yallist.prototype.reduceReverse = function (fn, initial) { + var acc + var walker = this.tail + if (arguments.length > 1) { + acc = initial + } else if (this.tail) { + walker = this.tail.prev + acc = this.tail.value + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = this.length - 1; walker !== null; i--) { + acc = fn(acc, walker.value, i) + walker = walker.prev + } + + return acc +} + +Yallist.prototype.toArray = function () { + var arr = new Array(this.length) + for (var i = 0, walker = this.head; walker !== null; i++) { + arr[i] = walker.value + walker = walker.next + } + return arr +} + +Yallist.prototype.toArrayReverse = function () { + var arr = new Array(this.length) + for (var i = 0, walker = this.tail; walker !== null; i++) { + arr[i] = walker.value + walker = walker.prev + } + return arr +} + +Yallist.prototype.slice = function (from, to) { + to = to || this.length + if (to < 0) { + to += this.length + } + from = from || 0 + if (from < 0) { + from += this.length + } + var ret = new Yallist() + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0 + } + if (to > this.length) { + to = this.length + } + for (var i = 0, walker = this.head; walker !== null && i < from; i++) { + walker = walker.next + } + for (; walker !== null && i < to; i++, walker = walker.next) { + ret.push(walker.value) + } + return ret +} + +Yallist.prototype.sliceReverse = function (from, to) { + to = to || this.length + if (to < 0) { + to += this.length + } + from = from || 0 + if (from < 0) { + from += this.length + } + var ret = new Yallist() + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0 + } + if (to > this.length) { + to = this.length + } + for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { + walker = walker.prev + } + for (; walker !== null && i > from; i--, walker = walker.prev) { + ret.push(walker.value) + } + return ret +} + +Yallist.prototype.splice = function (start, deleteCount, ...nodes) { + if (start > this.length) { + start = this.length - 1 + } + if (start < 0) { + start = this.length + start; + } + + for (var i = 0, walker = this.head; walker !== null && i < start; i++) { + walker = walker.next + } + + var ret = [] + for (var i = 0; walker && i < deleteCount; i++) { + ret.push(walker.value) + walker = this.removeNode(walker) + } + if (walker === null) { + walker = this.tail + } + + if (walker !== this.head && walker !== this.tail) { + walker = walker.prev + } + + for (var i = 0; i < nodes.length; i++) { + walker = insert(this, walker, nodes[i]) + } + return ret; +} + +Yallist.prototype.reverse = function () { + var head = this.head + var tail = this.tail + for (var walker = head; walker !== null; walker = walker.prev) { + var p = walker.prev + walker.prev = walker.next + walker.next = p + } + this.head = tail + this.tail = head + return this +} + +function insert (self, node, value) { + var inserted = node === self.head ? + new Node(value, null, node, self) : + new Node(value, node, node.next, self) + + if (inserted.next === null) { + self.tail = inserted + } + if (inserted.prev === null) { + self.head = inserted + } + + self.length++ + + return inserted +} + +function push (self, item) { + self.tail = new Node(item, self.tail, null, self) + if (!self.head) { + self.head = self.tail + } + self.length++ +} + +function unshift (self, item) { + self.head = new Node(item, null, self.head, self) + if (!self.tail) { + self.tail = self.head + } + self.length++ +} + +function Node (value, prev, next, list) { + if (!(this instanceof Node)) { + return new Node(value, prev, next, list) + } + + this.list = list + this.value = value + + if (prev) { + prev.next = this + this.prev = prev + } else { + this.prev = null + } + + if (next) { + next.prev = this + this.next = next + } else { + this.next = null + } +} + +try { + // add if support for Symbol.iterator is present + require('./iterator.js')(Yallist) +} catch (er) {} diff --git a/node_modules/yargs-parser/CHANGELOG.md b/node_modules/yargs-parser/CHANGELOG.md new file mode 100644 index 0000000..584eb86 --- /dev/null +++ b/node_modules/yargs-parser/CHANGELOG.md @@ -0,0 +1,308 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## [21.1.1](https://github.com/yargs/yargs-parser/compare/yargs-parser-v21.1.0...yargs-parser-v21.1.1) (2022-08-04) + + +### Bug Fixes + +* **typescript:** ignore .cts files during publish ([#454](https://github.com/yargs/yargs-parser/issues/454)) ([d69f9c3](https://github.com/yargs/yargs-parser/commit/d69f9c3a91c3ad2f9494d0a94e29a8b76c41b81b)), closes [#452](https://github.com/yargs/yargs-parser/issues/452) + +## [21.1.0](https://github.com/yargs/yargs-parser/compare/yargs-parser-v21.0.1...yargs-parser-v21.1.0) (2022-08-03) + + +### Features + +* allow the browser build to be imported ([#443](https://github.com/yargs/yargs-parser/issues/443)) ([a89259f](https://github.com/yargs/yargs-parser/commit/a89259ff41d6f5312b3ce8a30bef343a993f395a)) + + +### Bug Fixes + +* **halt-at-non-option:** prevent known args from being parsed when "unknown-options-as-args" is enabled ([#438](https://github.com/yargs/yargs-parser/issues/438)) ([c474bc1](https://github.com/yargs/yargs-parser/commit/c474bc10c3aa0ae864b95e5722730114ef15f573)) +* node version check now uses process.versions.node ([#450](https://github.com/yargs/yargs-parser/issues/450)) ([d07bcdb](https://github.com/yargs/yargs-parser/commit/d07bcdbe43075f7201fbe8a08e491217247fe1f1)) +* parse options ending with 3+ hyphens ([#434](https://github.com/yargs/yargs-parser/issues/434)) ([4f1060b](https://github.com/yargs/yargs-parser/commit/4f1060b50759fadbac3315c5117b0c3d65b0a7d8)) + +### [21.0.1](https://github.com/yargs/yargs-parser/compare/yargs-parser-v21.0.0...yargs-parser-v21.0.1) (2022-02-27) + + +### Bug Fixes + +* return deno env object ([#432](https://github.com/yargs/yargs-parser/issues/432)) ([b00eb87](https://github.com/yargs/yargs-parser/commit/b00eb87b4860a890dd2dab0d6058241bbfd2b3ec)) + +## [21.0.0](https://www.github.com/yargs/yargs-parser/compare/yargs-parser-v20.2.9...yargs-parser-v21.0.0) (2021-11-15) + + +### ⚠ BREAKING CHANGES + +* drops support for 10 (#421) + +### Bug Fixes + +* esm json import ([#416](https://www.github.com/yargs/yargs-parser/issues/416)) ([90f970a](https://www.github.com/yargs/yargs-parser/commit/90f970a6482dd4f5b5eb18d38596dd6f02d73edf)) +* parser should preserve inner quotes ([#407](https://www.github.com/yargs/yargs-parser/issues/407)) ([ae11f49](https://www.github.com/yargs/yargs-parser/commit/ae11f496a8318ea8885aa25015d429b33713c314)) + + +### Code Refactoring + +* drops support for 10 ([#421](https://www.github.com/yargs/yargs-parser/issues/421)) ([3aaf878](https://www.github.com/yargs/yargs-parser/commit/3aaf8784f5c7f2aec6108c1c6a55537fa7e3b5c1)) + +### [20.2.9](https://www.github.com/yargs/yargs-parser/compare/yargs-parser-v20.2.8...yargs-parser-v20.2.9) (2021-06-20) + + +### Bug Fixes + +* **build:** fixed automated release pipeline ([1fe9135](https://www.github.com/yargs/yargs-parser/commit/1fe9135884790a083615419b2861683e2597dac3)) + +### [20.2.8](https://www.github.com/yargs/yargs-parser/compare/yargs-parser-v20.2.7...yargs-parser-v20.2.8) (2021-06-20) + + +### Bug Fixes + +* **locale:** Turkish camelize and decamelize issues with toLocaleLowerCase/toLocaleUpperCase ([2617303](https://www.github.com/yargs/yargs-parser/commit/261730383e02448562f737b94bbd1f164aed5143)) +* **perf:** address slow parse when using unknown-options-as-args ([#394](https://www.github.com/yargs/yargs-parser/issues/394)) ([441f059](https://www.github.com/yargs/yargs-parser/commit/441f059d585d446551068ad213db79ac91daf83a)) +* **string-utils:** detect [0,1] ranged values as numbers ([#388](https://www.github.com/yargs/yargs-parser/issues/388)) ([efcc32c](https://www.github.com/yargs/yargs-parser/commit/efcc32c2d6b09aba31abfa2db9bd947befe5586b)) + +### [20.2.7](https://www.github.com/yargs/yargs-parser/compare/v20.2.6...v20.2.7) (2021-03-10) + + +### Bug Fixes + +* **deno:** force release for Deno ([6687c97](https://www.github.com/yargs/yargs-parser/commit/6687c972d0f3ca7865a97908dde3080b05f8b026)) + +### [20.2.6](https://www.github.com/yargs/yargs-parser/compare/v20.2.5...v20.2.6) (2021-02-22) + + +### Bug Fixes + +* **populate--:** -- should always be array ([#354](https://www.github.com/yargs/yargs-parser/issues/354)) ([585ae8f](https://www.github.com/yargs/yargs-parser/commit/585ae8ffad74cc02974f92d788e750137fd65146)) + +### [20.2.5](https://www.github.com/yargs/yargs-parser/compare/v20.2.4...v20.2.5) (2021-02-13) + + +### Bug Fixes + +* do not lowercase camel cased string ([#348](https://www.github.com/yargs/yargs-parser/issues/348)) ([5f4da1f](https://www.github.com/yargs/yargs-parser/commit/5f4da1f17d9d50542d2aaa206c9806ce3e320335)) + +### [20.2.4](https://www.github.com/yargs/yargs-parser/compare/v20.2.3...v20.2.4) (2020-11-09) + + +### Bug Fixes + +* **deno:** address import issues in Deno ([#339](https://www.github.com/yargs/yargs-parser/issues/339)) ([3b54e5e](https://www.github.com/yargs/yargs-parser/commit/3b54e5eef6e9a7b7c6eec7c12bab3ba3b8ba8306)) + +### [20.2.3](https://www.github.com/yargs/yargs-parser/compare/v20.2.2...v20.2.3) (2020-10-16) + + +### Bug Fixes + +* **exports:** node 13.0 and 13.1 require the dotted object form _with_ a string fallback ([#336](https://www.github.com/yargs/yargs-parser/issues/336)) ([3ae7242](https://www.github.com/yargs/yargs-parser/commit/3ae7242040ff876d28dabded60ac226e00150c88)) + +### [20.2.2](https://www.github.com/yargs/yargs-parser/compare/v20.2.1...v20.2.2) (2020-10-14) + + +### Bug Fixes + +* **exports:** node 13.0-13.6 require a string fallback ([#333](https://www.github.com/yargs/yargs-parser/issues/333)) ([291aeda](https://www.github.com/yargs/yargs-parser/commit/291aeda06b685b7a015d83bdf2558e180b37388d)) + +### [20.2.1](https://www.github.com/yargs/yargs-parser/compare/v20.2.0...v20.2.1) (2020-10-01) + + +### Bug Fixes + +* **deno:** update types for deno ^1.4.0 ([#330](https://www.github.com/yargs/yargs-parser/issues/330)) ([0ab92e5](https://www.github.com/yargs/yargs-parser/commit/0ab92e50b090f11196334c048c9c92cecaddaf56)) + +## [20.2.0](https://www.github.com/yargs/yargs-parser/compare/v20.1.0...v20.2.0) (2020-09-21) + + +### Features + +* **string-utils:** export looksLikeNumber helper ([#324](https://www.github.com/yargs/yargs-parser/issues/324)) ([c8580a2](https://www.github.com/yargs/yargs-parser/commit/c8580a2327b55f6342acecb6e72b62963d506750)) + + +### Bug Fixes + +* **unknown-options-as-args:** convert positionals that look like numbers ([#326](https://www.github.com/yargs/yargs-parser/issues/326)) ([f85ebb4](https://www.github.com/yargs/yargs-parser/commit/f85ebb4face9d4b0f56147659404cbe0002f3dad)) + +## [20.1.0](https://www.github.com/yargs/yargs-parser/compare/v20.0.0...v20.1.0) (2020-09-20) + + +### Features + +* adds parse-positional-numbers configuration ([#321](https://www.github.com/yargs/yargs-parser/issues/321)) ([9cec00a](https://www.github.com/yargs/yargs-parser/commit/9cec00a622251292ffb7dce6f78f5353afaa0d4c)) + + +### Bug Fixes + +* **build:** update release-please; make labels kick off builds ([#323](https://www.github.com/yargs/yargs-parser/issues/323)) ([09f448b](https://www.github.com/yargs/yargs-parser/commit/09f448b4cd66e25d2872544718df46dab8af062a)) + +## [20.0.0](https://www.github.com/yargs/yargs-parser/compare/v19.0.4...v20.0.0) (2020-09-09) + + +### ⚠ BREAKING CHANGES + +* do not ship type definitions (#318) + +### Bug Fixes + +* only strip camel case if hyphenated ([#316](https://www.github.com/yargs/yargs-parser/issues/316)) ([95a9e78](https://www.github.com/yargs/yargs-parser/commit/95a9e785127b9bbf2d1db1f1f808ca1fb100e82a)), closes [#315](https://www.github.com/yargs/yargs-parser/issues/315) + + +### Code Refactoring + +* do not ship type definitions ([#318](https://www.github.com/yargs/yargs-parser/issues/318)) ([8fbd56f](https://www.github.com/yargs/yargs-parser/commit/8fbd56f1d0b6c44c30fca62708812151ca0ce330)) + +### [19.0.4](https://www.github.com/yargs/yargs-parser/compare/v19.0.3...v19.0.4) (2020-08-27) + + +### Bug Fixes + +* **build:** fixing publication ([#310](https://www.github.com/yargs/yargs-parser/issues/310)) ([5d3c6c2](https://www.github.com/yargs/yargs-parser/commit/5d3c6c29a9126248ba601920d9cf87c78e161ff5)) + +### [19.0.3](https://www.github.com/yargs/yargs-parser/compare/v19.0.2...v19.0.3) (2020-08-27) + + +### Bug Fixes + +* **build:** switch to action for publish ([#308](https://www.github.com/yargs/yargs-parser/issues/308)) ([5c2f305](https://www.github.com/yargs/yargs-parser/commit/5c2f30585342bcd8aaf926407c863099d256d174)) + +### [19.0.2](https://www.github.com/yargs/yargs-parser/compare/v19.0.1...v19.0.2) (2020-08-27) + + +### Bug Fixes + +* **types:** envPrefix should be optional ([#305](https://www.github.com/yargs/yargs-parser/issues/305)) ([ae3f180](https://www.github.com/yargs/yargs-parser/commit/ae3f180e14df2de2fd962145f4518f9aa0e76523)) + +### [19.0.1](https://www.github.com/yargs/yargs-parser/compare/v19.0.0...v19.0.1) (2020-08-09) + + +### Bug Fixes + +* **build:** push tag created for deno ([2186a14](https://www.github.com/yargs/yargs-parser/commit/2186a14989749887d56189867602e39e6679f8b0)) + +## [19.0.0](https://www.github.com/yargs/yargs-parser/compare/v18.1.3...v19.0.0) (2020-08-09) + + +### ⚠ BREAKING CHANGES + +* adds support for ESM and Deno (#295) +* **ts:** projects using `@types/yargs-parser` may see variations in type definitions. +* drops Node 6. begin following Node.js LTS schedule (#278) + +### Features + +* adds support for ESM and Deno ([#295](https://www.github.com/yargs/yargs-parser/issues/295)) ([195bc4a](https://www.github.com/yargs/yargs-parser/commit/195bc4a7f20c2a8f8e33fbb6ba96ef6e9a0120a1)) +* expose camelCase and decamelize helpers ([#296](https://www.github.com/yargs/yargs-parser/issues/296)) ([39154ce](https://www.github.com/yargs/yargs-parser/commit/39154ceb5bdcf76b5f59a9219b34cedb79b67f26)) +* **deps:** update to latest camelcase/decamelize ([#281](https://www.github.com/yargs/yargs-parser/issues/281)) ([8931ab0](https://www.github.com/yargs/yargs-parser/commit/8931ab08f686cc55286f33a95a83537da2be5516)) + + +### Bug Fixes + +* boolean numeric short option ([#294](https://www.github.com/yargs/yargs-parser/issues/294)) ([f600082](https://www.github.com/yargs/yargs-parser/commit/f600082c959e092076caf420bbbc9d7a231e2418)) +* raise permission error for Deno if config load fails ([#298](https://www.github.com/yargs/yargs-parser/issues/298)) ([1174e2b](https://www.github.com/yargs/yargs-parser/commit/1174e2b3f0c845a1cd64e14ffc3703e730567a84)) +* **deps:** update dependency decamelize to v3 ([#274](https://www.github.com/yargs/yargs-parser/issues/274)) ([4d98698](https://www.github.com/yargs/yargs-parser/commit/4d98698bc6767e84ec54a0842908191739be73b7)) +* **types:** switch back to using Partial types ([#293](https://www.github.com/yargs/yargs-parser/issues/293)) ([bdc80ba](https://www.github.com/yargs/yargs-parser/commit/bdc80ba59fa13bc3025ce0a85e8bad9f9da24ea7)) + + +### Build System + +* drops Node 6. begin following Node.js LTS schedule ([#278](https://www.github.com/yargs/yargs-parser/issues/278)) ([9014ed7](https://www.github.com/yargs/yargs-parser/commit/9014ed722a32768b96b829e65a31705db5c1458a)) + + +### Code Refactoring + +* **ts:** move index.js to TypeScript ([#292](https://www.github.com/yargs/yargs-parser/issues/292)) ([f78d2b9](https://www.github.com/yargs/yargs-parser/commit/f78d2b97567ac4828624406e420b4047c710b789)) + +### [18.1.3](https://www.github.com/yargs/yargs-parser/compare/v18.1.2...v18.1.3) (2020-04-16) + + +### Bug Fixes + +* **setArg:** options using camel-case and dot-notation populated twice ([#268](https://www.github.com/yargs/yargs-parser/issues/268)) ([f7e15b9](https://www.github.com/yargs/yargs-parser/commit/f7e15b9800900b9856acac1a830a5f35847be73e)) + +### [18.1.2](https://www.github.com/yargs/yargs-parser/compare/v18.1.1...v18.1.2) (2020-03-26) + + +### Bug Fixes + +* **array, nargs:** support -o=--value and --option=--value format ([#262](https://www.github.com/yargs/yargs-parser/issues/262)) ([41d3f81](https://www.github.com/yargs/yargs-parser/commit/41d3f8139e116706b28de9b0de3433feb08d2f13)) + +### [18.1.1](https://www.github.com/yargs/yargs-parser/compare/v18.1.0...v18.1.1) (2020-03-16) + + +### Bug Fixes + +* \_\_proto\_\_ will now be replaced with \_\_\_proto\_\_\_ in parse ([#258](https://www.github.com/yargs/yargs-parser/issues/258)), patching a potential +prototype pollution vulnerability. This was reported by the Snyk Security Research Team.([63810ca](https://www.github.com/yargs/yargs-parser/commit/63810ca1ae1a24b08293a4d971e70e058c7a41e2)) + +## [18.1.0](https://www.github.com/yargs/yargs-parser/compare/v18.0.0...v18.1.0) (2020-03-07) + + +### Features + +* introduce single-digit boolean aliases ([#255](https://www.github.com/yargs/yargs-parser/issues/255)) ([9c60265](https://www.github.com/yargs/yargs-parser/commit/9c60265fd7a03cb98e6df3e32c8c5e7508d9f56f)) + +## [18.0.0](https://www.github.com/yargs/yargs-parser/compare/v17.1.0...v18.0.0) (2020-03-02) + + +### ⚠ BREAKING CHANGES + +* the narg count is now enforced when parsing arrays. + +### Features + +* NaN can now be provided as a value for nargs, indicating "at least" one value is expected for array ([#251](https://www.github.com/yargs/yargs-parser/issues/251)) ([9db4be8](https://www.github.com/yargs/yargs-parser/commit/9db4be81417a2c7097128db34d86fe70ef4af70c)) + +## [17.1.0](https://www.github.com/yargs/yargs-parser/compare/v17.0.1...v17.1.0) (2020-03-01) + + +### Features + +* introduce greedy-arrays config, for specifying whether arrays consume multiple positionals ([#249](https://www.github.com/yargs/yargs-parser/issues/249)) ([60e880a](https://www.github.com/yargs/yargs-parser/commit/60e880a837046314d89fa4725f923837fd33a9eb)) + +### [17.0.1](https://www.github.com/yargs/yargs-parser/compare/v17.0.0...v17.0.1) (2020-02-29) + + +### Bug Fixes + +* normalized keys were not enumerable ([#247](https://www.github.com/yargs/yargs-parser/issues/247)) ([57119f9](https://www.github.com/yargs/yargs-parser/commit/57119f9f17cf27499bd95e61c2f72d18314f11ba)) + +## [17.0.0](https://www.github.com/yargs/yargs-parser/compare/v16.1.0...v17.0.0) (2020-02-10) + + +### ⚠ BREAKING CHANGES + +* this reverts parsing behavior of booleans to that of yargs@14 +* objects used during parsing are now created with a null +prototype. There may be some scenarios where this change in behavior +leaks externally. + +### Features + +* boolean arguments will not be collected into an implicit array ([#236](https://www.github.com/yargs/yargs-parser/issues/236)) ([34c4e19](https://www.github.com/yargs/yargs-parser/commit/34c4e19bae4e7af63e3cb6fa654a97ed476e5eb5)) +* introduce nargs-eats-options config option ([#246](https://www.github.com/yargs/yargs-parser/issues/246)) ([d50822a](https://www.github.com/yargs/yargs-parser/commit/d50822ac10e1b05f2e9643671ca131ac251b6732)) + + +### Bug Fixes + +* address bugs with "uknown-options-as-args" ([bc023e3](https://www.github.com/yargs/yargs-parser/commit/bc023e3b13e20a118353f9507d1c999bf388a346)) +* array should take precedence over nargs, but enforce nargs ([#243](https://www.github.com/yargs/yargs-parser/issues/243)) ([4cbc188](https://www.github.com/yargs/yargs-parser/commit/4cbc188b7abb2249529a19c090338debdad2fe6c)) +* support keys that collide with object prototypes ([#234](https://www.github.com/yargs/yargs-parser/issues/234)) ([1587b6d](https://www.github.com/yargs/yargs-parser/commit/1587b6d91db853a9109f1be6b209077993fee4de)) +* unknown options terminated with digits now handled by unknown-options-as-args ([#238](https://www.github.com/yargs/yargs-parser/issues/238)) ([d36cdfa](https://www.github.com/yargs/yargs-parser/commit/d36cdfa854254d7c7e0fe1d583818332ac46c2a5)) + +## [16.1.0](https://www.github.com/yargs/yargs-parser/compare/v16.0.0...v16.1.0) (2019-11-01) + + +### ⚠ BREAKING CHANGES + +* populate error if incompatible narg/count or array/count options are used (#191) + +### Features + +* options that have had their default value used are now tracked ([#211](https://www.github.com/yargs/yargs-parser/issues/211)) ([a525234](https://www.github.com/yargs/yargs-parser/commit/a525234558c847deedd73f8792e0a3b77b26e2c0)) +* populate error if incompatible narg/count or array/count options are used ([#191](https://www.github.com/yargs/yargs-parser/issues/191)) ([84a401f](https://www.github.com/yargs/yargs-parser/commit/84a401f0fa3095e0a19661670d1570d0c3b9d3c9)) + + +### Reverts + +* revert 16.0.0 CHANGELOG entry ([920320a](https://www.github.com/yargs/yargs-parser/commit/920320ad9861bbfd58eda39221ae211540fc1daf)) diff --git a/node_modules/yargs-parser/LICENSE.txt b/node_modules/yargs-parser/LICENSE.txt new file mode 100644 index 0000000..836440b --- /dev/null +++ b/node_modules/yargs-parser/LICENSE.txt @@ -0,0 +1,14 @@ +Copyright (c) 2016, Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/yargs-parser/README.md b/node_modules/yargs-parser/README.md new file mode 100644 index 0000000..2614840 --- /dev/null +++ b/node_modules/yargs-parser/README.md @@ -0,0 +1,518 @@ +# yargs-parser + +![ci](https://github.com/yargs/yargs-parser/workflows/ci/badge.svg) +[![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) +[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) +![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/yargs-parser) + +The mighty option parser used by [yargs](https://github.com/yargs/yargs). + +visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. + + + +## Example + +```sh +npm i yargs-parser --save +``` + +```js +const argv = require('yargs-parser')(process.argv.slice(2)) +console.log(argv) +``` + +```console +$ node example.js --foo=33 --bar hello +{ _: [], foo: 33, bar: 'hello' } +``` + +_or parse a string!_ + +```js +const argv = require('yargs-parser')('--foo=99 --bar=33') +console.log(argv) +``` + +```console +{ _: [], foo: 99, bar: 33 } +``` + +Convert an array of mixed types before passing to `yargs-parser`: + +```js +const parse = require('yargs-parser') +parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string +parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings +``` + +## Deno Example + +As of `v19` `yargs-parser` supports [Deno](https://github.com/denoland/deno): + +```typescript +import parser from "https://deno.land/x/yargs_parser/deno.ts"; + +const argv = parser('--foo=99 --bar=9987930', { + string: ['bar'] +}) +console.log(argv) +``` + +## ESM Example + +As of `v19` `yargs-parser` supports ESM (_both in Node.js and in the browser_): + +**Node.js:** + +```js +import parser from 'yargs-parser' + +const argv = parser('--foo=99 --bar=9987930', { + string: ['bar'] +}) +console.log(argv) +``` + +**Browsers:** + +```html + + + + +``` + +## API + +### parser(args, opts={}) + +Parses command line arguments returning a simple mapping of keys and values. + +**expects:** + +* `args`: a string or array of strings representing the options to parse. +* `opts`: provide a set of hints indicating how `args` should be parsed: + * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. + * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.
                          + Indicate that keys should be parsed as an array and coerced to booleans / numbers:
                          + `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. + * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. + * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided + (or throws an error). For arrays the function is called only once for the entire array:
                          + `{coerce: {foo: function (arg) {return modifiedArg}}}`. + * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). + * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:
                          + `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`. + * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). + * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. + * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. + * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. + * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. + * `opts.normalize`: `path.normalize()` will be applied to values set to this key. + * `opts.number`: keys should be treated as numbers. + * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). + +**returns:** + +* `obj`: an object representing the parsed value of `args` + * `key/value`: key value pairs for each argument and their aliases. + * `_`: an array representing the positional arguments. + * [optional] `--`: an array with arguments after the end-of-options flag `--`. + +### require('yargs-parser').detailed(args, opts={}) + +Parses a command line string, returning detailed information required by the +yargs engine. + +**expects:** + +* `args`: a string or array of strings representing options to parse. +* `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. + +**returns:** + +* `argv`: an object representing the parsed value of `args` + * `key/value`: key value pairs for each argument and their aliases. + * `_`: an array representing the positional arguments. + * [optional] `--`: an array with arguments after the end-of-options flag `--`. +* `error`: populated with an error object if an exception occurred during parsing. +* `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. +* `newAliases`: any new aliases added via camel-case expansion: + * `boolean`: `{ fooBar: true }` +* `defaulted`: any new argument created by `opts.default`, no aliases included. + * `boolean`: `{ foo: true }` +* `configuration`: given by default settings and `opts.configuration`. + + + +### Configuration + +The yargs-parser applies several automated transformations on the keys provided +in `args`. These features can be turned on and off using the `configuration` field +of `opts`. + +```js +var parsed = parser(['--no-dice'], { + configuration: { + 'boolean-negation': false + } +}) +``` + +### short option groups + +* default: `true`. +* key: `short-option-groups`. + +Should a group of short-options be treated as boolean flags? + +```console +$ node example.js -abc +{ _: [], a: true, b: true, c: true } +``` + +_if disabled:_ + +```console +$ node example.js -abc +{ _: [], abc: true } +``` + +### camel-case expansion + +* default: `true`. +* key: `camel-case-expansion`. + +Should hyphenated arguments be expanded into camel-case aliases? + +```console +$ node example.js --foo-bar +{ _: [], 'foo-bar': true, fooBar: true } +``` + +_if disabled:_ + +```console +$ node example.js --foo-bar +{ _: [], 'foo-bar': true } +``` + +### dot-notation + +* default: `true` +* key: `dot-notation` + +Should keys that contain `.` be treated as objects? + +```console +$ node example.js --foo.bar +{ _: [], foo: { bar: true } } +``` + +_if disabled:_ + +```console +$ node example.js --foo.bar +{ _: [], "foo.bar": true } +``` + +### parse numbers + +* default: `true` +* key: `parse-numbers` + +Should keys that look like numbers be treated as such? + +```console +$ node example.js --foo=99.3 +{ _: [], foo: 99.3 } +``` + +_if disabled:_ + +```console +$ node example.js --foo=99.3 +{ _: [], foo: "99.3" } +``` + +### parse positional numbers + +* default: `true` +* key: `parse-positional-numbers` + +Should positional keys that look like numbers be treated as such. + +```console +$ node example.js 99.3 +{ _: [99.3] } +``` + +_if disabled:_ + +```console +$ node example.js 99.3 +{ _: ['99.3'] } +``` + +### boolean negation + +* default: `true` +* key: `boolean-negation` + +Should variables prefixed with `--no` be treated as negations? + +```console +$ node example.js --no-foo +{ _: [], foo: false } +``` + +_if disabled:_ + +```console +$ node example.js --no-foo +{ _: [], "no-foo": true } +``` + +### combine arrays + +* default: `false` +* key: `combine-arrays` + +Should arrays be combined when provided by both command line arguments and +a configuration file. + +### duplicate arguments array + +* default: `true` +* key: `duplicate-arguments-array` + +Should arguments be coerced into an array when duplicated: + +```console +$ node example.js -x 1 -x 2 +{ _: [], x: [1, 2] } +``` + +_if disabled:_ + +```console +$ node example.js -x 1 -x 2 +{ _: [], x: 2 } +``` + +### flatten duplicate arrays + +* default: `true` +* key: `flatten-duplicate-arrays` + +Should array arguments be coerced into a single array when duplicated: + +```console +$ node example.js -x 1 2 -x 3 4 +{ _: [], x: [1, 2, 3, 4] } +``` + +_if disabled:_ + +```console +$ node example.js -x 1 2 -x 3 4 +{ _: [], x: [[1, 2], [3, 4]] } +``` + +### greedy arrays + +* default: `true` +* key: `greedy-arrays` + +Should arrays consume more than one positional argument following their flag. + +```console +$ node example --arr 1 2 +{ _: [], arr: [1, 2] } +``` + +_if disabled:_ + +```console +$ node example --arr 1 2 +{ _: [2], arr: [1] } +``` + +**Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.** + +### nargs eats options + +* default: `false` +* key: `nargs-eats-options` + +Should nargs consume dash options as well as positional arguments. + +### negation prefix + +* default: `no-` +* key: `negation-prefix` + +The prefix to use for negated boolean variables. + +```console +$ node example.js --no-foo +{ _: [], foo: false } +``` + +_if set to `quux`:_ + +```console +$ node example.js --quuxfoo +{ _: [], foo: false } +``` + +### populate -- + +* default: `false`. +* key: `populate--` + +Should unparsed flags be stored in `--` or `_`. + +_If disabled:_ + +```console +$ node example.js a -b -- x y +{ _: [ 'a', 'x', 'y' ], b: true } +``` + +_If enabled:_ + +```console +$ node example.js a -b -- x y +{ _: [ 'a' ], '--': [ 'x', 'y' ], b: true } +``` + +### set placeholder key + +* default: `false`. +* key: `set-placeholder-key`. + +Should a placeholder be added for keys not set via the corresponding CLI argument? + +_If disabled:_ + +```console +$ node example.js -a 1 -c 2 +{ _: [], a: 1, c: 2 } +``` + +_If enabled:_ + +```console +$ node example.js -a 1 -c 2 +{ _: [], a: 1, b: undefined, c: 2 } +``` + +### halt at non-option + +* default: `false`. +* key: `halt-at-non-option`. + +Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line. + +_If disabled:_ + +```console +$ node example.js -a run b -x y +{ _: [ 'b' ], a: 'run', x: 'y' } +``` + +_If enabled:_ + +```console +$ node example.js -a run b -x y +{ _: [ 'b', '-x', 'y' ], a: 'run' } +``` + +### strip aliased + +* default: `false` +* key: `strip-aliased` + +Should aliases be removed before returning results? + +_If disabled:_ + +```console +$ node example.js --test-field 1 +{ _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } +``` + +_If enabled:_ + +```console +$ node example.js --test-field 1 +{ _: [], 'test-field': 1, testField: 1 } +``` + +### strip dashed + +* default: `false` +* key: `strip-dashed` + +Should dashed keys be removed before returning results? This option has no effect if +`camel-case-expansion` is disabled. + +_If disabled:_ + +```console +$ node example.js --test-field 1 +{ _: [], 'test-field': 1, testField: 1 } +``` + +_If enabled:_ + +```console +$ node example.js --test-field 1 +{ _: [], testField: 1 } +``` + +### unknown options as args + +* default: `false` +* key: `unknown-options-as-args` + +Should unknown options be treated like regular arguments? An unknown option is one that is not +configured in `opts`. + +_If disabled_ + +```console +$ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 +{ _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } +``` + +_If enabled_ + +```console +$ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 +{ _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } +``` + +## Supported Node.js Versions + +Libraries in this ecosystem make a best effort to track +[Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a +post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). + +## Special Thanks + +The yargs project evolves from optimist and minimist. It owes its +existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ + +## License + +ISC diff --git a/node_modules/yargs-parser/browser.js b/node_modules/yargs-parser/browser.js new file mode 100644 index 0000000..241202c --- /dev/null +++ b/node_modules/yargs-parser/browser.js @@ -0,0 +1,29 @@ +// Main entrypoint for ESM web browser environments. Avoids using Node.js +// specific libraries, such as "path". +// +// TODO: figure out reasonable web equivalents for "resolve", "normalize", etc. +import { camelCase, decamelize, looksLikeNumber } from './build/lib/string-utils.js' +import { YargsParser } from './build/lib/yargs-parser.js' +const parser = new YargsParser({ + cwd: () => { return '' }, + format: (str, arg) => { return str.replace('%s', arg) }, + normalize: (str) => { return str }, + resolve: (str) => { return str }, + require: () => { + throw Error('loading config from files not currently supported in browser') + }, + env: () => {} +}) + +const yargsParser = function Parser (args, opts) { + const result = parser.parse(args.slice(), opts) + return result.argv +} +yargsParser.detailed = function (args, opts) { + return parser.parse(args.slice(), opts) +} +yargsParser.camelCase = camelCase +yargsParser.decamelize = decamelize +yargsParser.looksLikeNumber = looksLikeNumber + +export default yargsParser diff --git a/node_modules/yargs-parser/build/index.cjs b/node_modules/yargs-parser/build/index.cjs new file mode 100644 index 0000000..cf6f50f --- /dev/null +++ b/node_modules/yargs-parser/build/index.cjs @@ -0,0 +1,1050 @@ +'use strict'; + +var util = require('util'); +var path = require('path'); +var fs = require('fs'); + +function camelCase(str) { + const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase(); + if (!isCamelCase) { + str = str.toLowerCase(); + } + if (str.indexOf('-') === -1 && str.indexOf('_') === -1) { + return str; + } + else { + let camelcase = ''; + let nextChrUpper = false; + const leadingHyphens = str.match(/^-+/); + for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) { + let chr = str.charAt(i); + if (nextChrUpper) { + nextChrUpper = false; + chr = chr.toUpperCase(); + } + if (i !== 0 && (chr === '-' || chr === '_')) { + nextChrUpper = true; + } + else if (chr !== '-' && chr !== '_') { + camelcase += chr; + } + } + return camelcase; + } +} +function decamelize(str, joinString) { + const lowercase = str.toLowerCase(); + joinString = joinString || '-'; + let notCamelcase = ''; + for (let i = 0; i < str.length; i++) { + const chrLower = lowercase.charAt(i); + const chrString = str.charAt(i); + if (chrLower !== chrString && i > 0) { + notCamelcase += `${joinString}${lowercase.charAt(i)}`; + } + else { + notCamelcase += chrString; + } + } + return notCamelcase; +} +function looksLikeNumber(x) { + if (x === null || x === undefined) + return false; + if (typeof x === 'number') + return true; + if (/^0x[0-9a-f]+$/i.test(x)) + return true; + if (/^0[^.]/.test(x)) + return false; + return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} + +function tokenizeArgString(argString) { + if (Array.isArray(argString)) { + return argString.map(e => typeof e !== 'string' ? e + '' : e); + } + argString = argString.trim(); + let i = 0; + let prevC = null; + let c = null; + let opening = null; + const args = []; + for (let ii = 0; ii < argString.length; ii++) { + prevC = c; + c = argString.charAt(ii); + if (c === ' ' && !opening) { + if (!(prevC === ' ')) { + i++; + } + continue; + } + if (c === opening) { + opening = null; + } + else if ((c === "'" || c === '"') && !opening) { + opening = c; + } + if (!args[i]) + args[i] = ''; + args[i] += c; + } + return args; +} + +var DefaultValuesForTypeKey; +(function (DefaultValuesForTypeKey) { + DefaultValuesForTypeKey["BOOLEAN"] = "boolean"; + DefaultValuesForTypeKey["STRING"] = "string"; + DefaultValuesForTypeKey["NUMBER"] = "number"; + DefaultValuesForTypeKey["ARRAY"] = "array"; +})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {})); + +let mixin; +class YargsParser { + constructor(_mixin) { + mixin = _mixin; + } + parse(argsInput, options) { + const opts = Object.assign({ + alias: undefined, + array: undefined, + boolean: undefined, + config: undefined, + configObjects: undefined, + configuration: undefined, + coerce: undefined, + count: undefined, + default: undefined, + envPrefix: undefined, + narg: undefined, + normalize: undefined, + string: undefined, + number: undefined, + __: undefined, + key: undefined + }, options); + const args = tokenizeArgString(argsInput); + const inputIsString = typeof argsInput === 'string'; + const aliases = combineAliases(Object.assign(Object.create(null), opts.alias)); + const configuration = Object.assign({ + 'boolean-negation': true, + 'camel-case-expansion': true, + 'combine-arrays': false, + 'dot-notation': true, + 'duplicate-arguments-array': true, + 'flatten-duplicate-arrays': true, + 'greedy-arrays': true, + 'halt-at-non-option': false, + 'nargs-eats-options': false, + 'negation-prefix': 'no-', + 'parse-numbers': true, + 'parse-positional-numbers': true, + 'populate--': false, + 'set-placeholder-key': false, + 'short-option-groups': true, + 'strip-aliased': false, + 'strip-dashed': false, + 'unknown-options-as-args': false + }, opts.configuration); + const defaults = Object.assign(Object.create(null), opts.default); + const configObjects = opts.configObjects || []; + const envPrefix = opts.envPrefix; + const notFlagsOption = configuration['populate--']; + const notFlagsArgv = notFlagsOption ? '--' : '_'; + const newAliases = Object.create(null); + const defaulted = Object.create(null); + const __ = opts.__ || mixin.format; + const flags = { + aliases: Object.create(null), + arrays: Object.create(null), + bools: Object.create(null), + strings: Object.create(null), + numbers: Object.create(null), + counts: Object.create(null), + normalize: Object.create(null), + configs: Object.create(null), + nargs: Object.create(null), + coercions: Object.create(null), + keys: [] + }; + const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/; + const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)'); + [].concat(opts.array || []).filter(Boolean).forEach(function (opt) { + const key = typeof opt === 'object' ? opt.key : opt; + const assignment = Object.keys(opt).map(function (key) { + const arrayFlagKeys = { + boolean: 'bools', + string: 'strings', + number: 'numbers' + }; + return arrayFlagKeys[key]; + }).filter(Boolean).pop(); + if (assignment) { + flags[assignment][key] = true; + } + flags.arrays[key] = true; + flags.keys.push(key); + }); + [].concat(opts.boolean || []).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + flags.keys.push(key); + }); + [].concat(opts.string || []).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + flags.keys.push(key); + }); + [].concat(opts.number || []).filter(Boolean).forEach(function (key) { + flags.numbers[key] = true; + flags.keys.push(key); + }); + [].concat(opts.count || []).filter(Boolean).forEach(function (key) { + flags.counts[key] = true; + flags.keys.push(key); + }); + [].concat(opts.normalize || []).filter(Boolean).forEach(function (key) { + flags.normalize[key] = true; + flags.keys.push(key); + }); + if (typeof opts.narg === 'object') { + Object.entries(opts.narg).forEach(([key, value]) => { + if (typeof value === 'number') { + flags.nargs[key] = value; + flags.keys.push(key); + } + }); + } + if (typeof opts.coerce === 'object') { + Object.entries(opts.coerce).forEach(([key, value]) => { + if (typeof value === 'function') { + flags.coercions[key] = value; + flags.keys.push(key); + } + }); + } + if (typeof opts.config !== 'undefined') { + if (Array.isArray(opts.config) || typeof opts.config === 'string') { + [].concat(opts.config).filter(Boolean).forEach(function (key) { + flags.configs[key] = true; + }); + } + else if (typeof opts.config === 'object') { + Object.entries(opts.config).forEach(([key, value]) => { + if (typeof value === 'boolean' || typeof value === 'function') { + flags.configs[key] = value; + } + }); + } + } + extendAliases(opts.key, aliases, opts.default, flags.arrays); + Object.keys(defaults).forEach(function (key) { + (flags.aliases[key] || []).forEach(function (alias) { + defaults[alias] = defaults[key]; + }); + }); + let error = null; + checkConfiguration(); + let notFlags = []; + const argv = Object.assign(Object.create(null), { _: [] }); + const argvReturn = {}; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + const truncatedArg = arg.replace(/^-{3,}/, '---'); + let broken; + let key; + let letters; + let m; + let next; + let value; + if (arg !== '--' && /^-/.test(arg) && isUnknownOptionAsArg(arg)) { + pushPositional(arg); + } + else if (truncatedArg.match(/^---+(=|$)/)) { + pushPositional(arg); + continue; + } + else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) { + m = arg.match(/^--?([^=]+)=([\s\S]*)$/); + if (m !== null && Array.isArray(m) && m.length >= 3) { + if (checkAllAliases(m[1], flags.arrays)) { + i = eatArray(i, m[1], args, m[2]); + } + else if (checkAllAliases(m[1], flags.nargs) !== false) { + i = eatNargs(i, m[1], args, m[2]); + } + else { + setArg(m[1], m[2], true); + } + } + } + else if (arg.match(negatedBoolean) && configuration['boolean-negation']) { + m = arg.match(negatedBoolean); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false); + } + } + else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) { + m = arg.match(/^--?(.+)/); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + if (checkAllAliases(key, flags.arrays)) { + i = eatArray(i, key, args); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + i = eatNargs(i, key, args); + } + else { + next = args[i + 1]; + if (next !== undefined && (!next.match(/^-/) || + next.match(negative)) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + } + else if (arg.match(/^-.\..+=/)) { + m = arg.match(/^-([^=]+)=([\s\S]*)$/); + if (m !== null && Array.isArray(m) && m.length >= 3) { + setArg(m[1], m[2]); + } + } + else if (arg.match(/^-.\..+/) && !arg.match(negative)) { + next = args[i + 1]; + m = arg.match(/^-(.\..+)/); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + if (next !== undefined && !next.match(/^-/) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + else if (arg.match(/^-[^-]+/) && !arg.match(negative)) { + letters = arg.slice(1, -1).split(''); + broken = false; + for (let j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + if (letters[j + 1] && letters[j + 1] === '=') { + value = arg.slice(j + 3); + key = letters[j]; + if (checkAllAliases(key, flags.arrays)) { + i = eatArray(i, key, args, value); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + i = eatNargs(i, key, args, value); + } + else { + setArg(key, value); + } + broken = true; + break; + } + if (next === '-') { + setArg(letters[j], next); + continue; + } + if (/[A-Za-z]/.test(letters[j]) && + /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) && + checkAllAliases(next, flags.bools) === false) { + setArg(letters[j], next); + broken = true; + break; + } + if (letters[j + 1] && letters[j + 1].match(/\W/)) { + setArg(letters[j], next); + broken = true; + break; + } + else { + setArg(letters[j], defaultValue(letters[j])); + } + } + key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if (checkAllAliases(key, flags.arrays)) { + i = eatArray(i, key, args); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + i = eatNargs(i, key, args); + } + else { + next = args[i + 1]; + if (next !== undefined && (!/^(-|--)[^-]/.test(next) || + next.match(negative)) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + } + else if (arg.match(/^-[0-9]$/) && + arg.match(negative) && + checkAllAliases(arg.slice(1), flags.bools)) { + key = arg.slice(1); + setArg(key, defaultValue(key)); + } + else if (arg === '--') { + notFlags = args.slice(i + 1); + break; + } + else if (configuration['halt-at-non-option']) { + notFlags = args.slice(i); + break; + } + else { + pushPositional(arg); + } + } + applyEnvVars(argv, true); + applyEnvVars(argv, false); + setConfig(argv); + setConfigObjects(); + applyDefaultsAndAliases(argv, flags.aliases, defaults, true); + applyCoercions(argv); + if (configuration['set-placeholder-key']) + setPlaceholderKeys(argv); + Object.keys(flags.counts).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) + setArg(key, 0); + }); + if (notFlagsOption && notFlags.length) + argv[notFlagsArgv] = []; + notFlags.forEach(function (key) { + argv[notFlagsArgv].push(key); + }); + if (configuration['camel-case-expansion'] && configuration['strip-dashed']) { + Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => { + delete argv[key]; + }); + } + if (configuration['strip-aliased']) { + [].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => { + if (configuration['camel-case-expansion'] && alias.includes('-')) { + delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')]; + } + delete argv[alias]; + }); + } + function pushPositional(arg) { + const maybeCoercedNumber = maybeCoerceNumber('_', arg); + if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') { + argv._.push(maybeCoercedNumber); + } + } + function eatNargs(i, key, args, argAfterEqualSign) { + let ii; + let toEat = checkAllAliases(key, flags.nargs); + toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat; + if (toEat === 0) { + if (!isUndefined(argAfterEqualSign)) { + error = Error(__('Argument unexpected for: %s', key)); + } + setArg(key, defaultValue(key)); + return i; + } + let available = isUndefined(argAfterEqualSign) ? 0 : 1; + if (configuration['nargs-eats-options']) { + if (args.length - (i + 1) + available < toEat) { + error = Error(__('Not enough arguments following: %s', key)); + } + available = toEat; + } + else { + for (ii = i + 1; ii < args.length; ii++) { + if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii])) + available++; + else + break; + } + if (available < toEat) + error = Error(__('Not enough arguments following: %s', key)); + } + let consumed = Math.min(available, toEat); + if (!isUndefined(argAfterEqualSign) && consumed > 0) { + setArg(key, argAfterEqualSign); + consumed--; + } + for (ii = i + 1; ii < (consumed + i + 1); ii++) { + setArg(key, args[ii]); + } + return (i + consumed); + } + function eatArray(i, key, args, argAfterEqualSign) { + let argsToSet = []; + let next = argAfterEqualSign || args[i + 1]; + const nargsCount = checkAllAliases(key, flags.nargs); + if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) { + argsToSet.push(true); + } + else if (isUndefined(next) || + (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) { + if (defaults[key] !== undefined) { + const defVal = defaults[key]; + argsToSet = Array.isArray(defVal) ? defVal : [defVal]; + } + } + else { + if (!isUndefined(argAfterEqualSign)) { + argsToSet.push(processValue(key, argAfterEqualSign, true)); + } + for (let ii = i + 1; ii < args.length; ii++) { + if ((!configuration['greedy-arrays'] && argsToSet.length > 0) || + (nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount)) + break; + next = args[ii]; + if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) + break; + i = ii; + argsToSet.push(processValue(key, next, inputIsString)); + } + } + if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) || + (isNaN(nargsCount) && argsToSet.length === 0))) { + error = Error(__('Not enough arguments following: %s', key)); + } + setArg(key, argsToSet); + return i; + } + function setArg(key, val, shouldStripQuotes = inputIsString) { + if (/-/.test(key) && configuration['camel-case-expansion']) { + const alias = key.split('.').map(function (prop) { + return camelCase(prop); + }).join('.'); + addNewAlias(key, alias); + } + const value = processValue(key, val, shouldStripQuotes); + const splitKey = key.split('.'); + setKey(argv, splitKey, value); + if (flags.aliases[key]) { + flags.aliases[key].forEach(function (x) { + const keyProperties = x.split('.'); + setKey(argv, keyProperties, value); + }); + } + if (splitKey.length > 1 && configuration['dot-notation']) { + (flags.aliases[splitKey[0]] || []).forEach(function (x) { + let keyProperties = x.split('.'); + const a = [].concat(splitKey); + a.shift(); + keyProperties = keyProperties.concat(a); + if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) { + setKey(argv, keyProperties, value); + } + }); + } + if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) { + const keys = [key].concat(flags.aliases[key] || []); + keys.forEach(function (key) { + Object.defineProperty(argvReturn, key, { + enumerable: true, + get() { + return val; + }, + set(value) { + val = typeof value === 'string' ? mixin.normalize(value) : value; + } + }); + }); + } + } + function addNewAlias(key, alias) { + if (!(flags.aliases[key] && flags.aliases[key].length)) { + flags.aliases[key] = [alias]; + newAliases[alias] = true; + } + if (!(flags.aliases[alias] && flags.aliases[alias].length)) { + addNewAlias(alias, key); + } + } + function processValue(key, val, shouldStripQuotes) { + if (shouldStripQuotes) { + val = stripQuotes(val); + } + if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) { + if (typeof val === 'string') + val = val === 'true'; + } + let value = Array.isArray(val) + ? val.map(function (v) { return maybeCoerceNumber(key, v); }) + : maybeCoerceNumber(key, val); + if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) { + value = increment(); + } + if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) { + if (Array.isArray(val)) + value = val.map((val) => { return mixin.normalize(val); }); + else + value = mixin.normalize(val); + } + return value; + } + function maybeCoerceNumber(key, value) { + if (!configuration['parse-positional-numbers'] && key === '_') + return value; + if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) { + const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`)))); + if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) { + value = Number(value); + } + } + return value; + } + function setConfig(argv) { + const configLookup = Object.create(null); + applyDefaultsAndAliases(configLookup, flags.aliases, defaults); + Object.keys(flags.configs).forEach(function (configKey) { + const configPath = argv[configKey] || configLookup[configKey]; + if (configPath) { + try { + let config = null; + const resolvedConfigPath = mixin.resolve(mixin.cwd(), configPath); + const resolveConfig = flags.configs[configKey]; + if (typeof resolveConfig === 'function') { + try { + config = resolveConfig(resolvedConfigPath); + } + catch (e) { + config = e; + } + if (config instanceof Error) { + error = config; + return; + } + } + else { + config = mixin.require(resolvedConfigPath); + } + setConfigObject(config); + } + catch (ex) { + if (ex.name === 'PermissionDenied') + error = ex; + else if (argv[configKey]) + error = Error(__('Invalid JSON config file: %s', configPath)); + } + } + }); + } + function setConfigObject(config, prev) { + Object.keys(config).forEach(function (key) { + const value = config[key]; + const fullKey = prev ? prev + '.' + key : key; + if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) { + setConfigObject(value, fullKey); + } + else { + if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) { + setArg(fullKey, value); + } + } + }); + } + function setConfigObjects() { + if (typeof configObjects !== 'undefined') { + configObjects.forEach(function (configObject) { + setConfigObject(configObject); + }); + } + } + function applyEnvVars(argv, configOnly) { + if (typeof envPrefix === 'undefined') + return; + const prefix = typeof envPrefix === 'string' ? envPrefix : ''; + const env = mixin.env(); + Object.keys(env).forEach(function (envVar) { + if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) { + const keys = envVar.split('__').map(function (key, i) { + if (i === 0) { + key = key.substring(prefix.length); + } + return camelCase(key); + }); + if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) { + setArg(keys.join('.'), env[envVar]); + } + } + }); + } + function applyCoercions(argv) { + let coerce; + const applied = new Set(); + Object.keys(argv).forEach(function (key) { + if (!applied.has(key)) { + coerce = checkAllAliases(key, flags.coercions); + if (typeof coerce === 'function') { + try { + const value = maybeCoerceNumber(key, coerce(argv[key])); + ([].concat(flags.aliases[key] || [], key)).forEach(ali => { + applied.add(ali); + argv[ali] = value; + }); + } + catch (err) { + error = err; + } + } + } + }); + } + function setPlaceholderKeys(argv) { + flags.keys.forEach((key) => { + if (~key.indexOf('.')) + return; + if (typeof argv[key] === 'undefined') + argv[key] = undefined; + }); + return argv; + } + function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) { + Object.keys(defaults).forEach(function (key) { + if (!hasKey(obj, key.split('.'))) { + setKey(obj, key.split('.'), defaults[key]); + if (canLog) + defaulted[key] = true; + (aliases[key] || []).forEach(function (x) { + if (hasKey(obj, x.split('.'))) + return; + setKey(obj, x.split('.'), defaults[key]); + }); + } + }); + } + function hasKey(obj, keys) { + let o = obj; + if (!configuration['dot-notation']) + keys = [keys.join('.')]; + keys.slice(0, -1).forEach(function (key) { + o = (o[key] || {}); + }); + const key = keys[keys.length - 1]; + if (typeof o !== 'object') + return false; + else + return key in o; + } + function setKey(obj, keys, value) { + let o = obj; + if (!configuration['dot-notation']) + keys = [keys.join('.')]; + keys.slice(0, -1).forEach(function (key) { + key = sanitizeKey(key); + if (typeof o === 'object' && o[key] === undefined) { + o[key] = {}; + } + if (typeof o[key] !== 'object' || Array.isArray(o[key])) { + if (Array.isArray(o[key])) { + o[key].push({}); + } + else { + o[key] = [o[key], {}]; + } + o = o[key][o[key].length - 1]; + } + else { + o = o[key]; + } + }); + const key = sanitizeKey(keys[keys.length - 1]); + const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays); + const isValueArray = Array.isArray(value); + let duplicate = configuration['duplicate-arguments-array']; + if (!duplicate && checkAllAliases(key, flags.nargs)) { + duplicate = true; + if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) { + o[key] = undefined; + } + } + if (value === increment()) { + o[key] = increment(o[key]); + } + else if (Array.isArray(o[key])) { + if (duplicate && isTypeArray && isValueArray) { + o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]); + } + else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) { + o[key] = value; + } + else { + o[key] = o[key].concat([value]); + } + } + else if (o[key] === undefined && isTypeArray) { + o[key] = isValueArray ? value : [value]; + } + else if (duplicate && !(o[key] === undefined || + checkAllAliases(key, flags.counts) || + checkAllAliases(key, flags.bools))) { + o[key] = [o[key], value]; + } + else { + o[key] = value; + } + } + function extendAliases(...args) { + args.forEach(function (obj) { + Object.keys(obj || {}).forEach(function (key) { + if (flags.aliases[key]) + return; + flags.aliases[key] = [].concat(aliases[key] || []); + flags.aliases[key].concat(key).forEach(function (x) { + if (/-/.test(x) && configuration['camel-case-expansion']) { + const c = camelCase(x); + if (c !== key && flags.aliases[key].indexOf(c) === -1) { + flags.aliases[key].push(c); + newAliases[c] = true; + } + } + }); + flags.aliases[key].concat(key).forEach(function (x) { + if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) { + const c = decamelize(x, '-'); + if (c !== key && flags.aliases[key].indexOf(c) === -1) { + flags.aliases[key].push(c); + newAliases[c] = true; + } + } + }); + flags.aliases[key].forEach(function (x) { + flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + }); + } + function checkAllAliases(key, flag) { + const toCheck = [].concat(flags.aliases[key] || [], key); + const keys = Object.keys(flag); + const setAlias = toCheck.find(key => keys.includes(key)); + return setAlias ? flag[setAlias] : false; + } + function hasAnyFlag(key) { + const flagsKeys = Object.keys(flags); + const toCheck = [].concat(flagsKeys.map(k => flags[k])); + return toCheck.some(function (flag) { + return Array.isArray(flag) ? flag.includes(key) : flag[key]; + }); + } + function hasFlagsMatching(arg, ...patterns) { + const toCheck = [].concat(...patterns); + return toCheck.some(function (pattern) { + const match = arg.match(pattern); + return match && hasAnyFlag(match[1]); + }); + } + function hasAllShortFlags(arg) { + if (arg.match(negative) || !arg.match(/^-[^-]+/)) { + return false; + } + let hasAllFlags = true; + let next; + const letters = arg.slice(1).split(''); + for (let j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + if (!hasAnyFlag(letters[j])) { + hasAllFlags = false; + break; + } + if ((letters[j + 1] && letters[j + 1] === '=') || + next === '-' || + (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) || + (letters[j + 1] && letters[j + 1].match(/\W/))) { + break; + } + } + return hasAllFlags; + } + function isUnknownOptionAsArg(arg) { + return configuration['unknown-options-as-args'] && isUnknownOption(arg); + } + function isUnknownOption(arg) { + arg = arg.replace(/^-{3,}/, '--'); + if (arg.match(negative)) { + return false; + } + if (hasAllShortFlags(arg)) { + return false; + } + const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/; + const normalFlag = /^-+([^=]+?)$/; + const flagEndingInHyphen = /^-+([^=]+?)-$/; + const flagEndingInDigits = /^-+([^=]+?\d+)$/; + const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/; + return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters); + } + function defaultValue(key) { + if (!checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts) && + `${key}` in defaults) { + return defaults[key]; + } + else { + return defaultForType(guessType(key)); + } + } + function defaultForType(type) { + const def = { + [DefaultValuesForTypeKey.BOOLEAN]: true, + [DefaultValuesForTypeKey.STRING]: '', + [DefaultValuesForTypeKey.NUMBER]: undefined, + [DefaultValuesForTypeKey.ARRAY]: [] + }; + return def[type]; + } + function guessType(key) { + let type = DefaultValuesForTypeKey.BOOLEAN; + if (checkAllAliases(key, flags.strings)) + type = DefaultValuesForTypeKey.STRING; + else if (checkAllAliases(key, flags.numbers)) + type = DefaultValuesForTypeKey.NUMBER; + else if (checkAllAliases(key, flags.bools)) + type = DefaultValuesForTypeKey.BOOLEAN; + else if (checkAllAliases(key, flags.arrays)) + type = DefaultValuesForTypeKey.ARRAY; + return type; + } + function isUndefined(num) { + return num === undefined; + } + function checkConfiguration() { + Object.keys(flags.counts).find(key => { + if (checkAllAliases(key, flags.arrays)) { + error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key)); + return true; + } + else if (checkAllAliases(key, flags.nargs)) { + error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key)); + return true; + } + return false; + }); + } + return { + aliases: Object.assign({}, flags.aliases), + argv: Object.assign(argvReturn, argv), + configuration: configuration, + defaulted: Object.assign({}, defaulted), + error: error, + newAliases: Object.assign({}, newAliases) + }; + } +} +function combineAliases(aliases) { + const aliasArrays = []; + const combined = Object.create(null); + let change = true; + Object.keys(aliases).forEach(function (key) { + aliasArrays.push([].concat(aliases[key], key)); + }); + while (change) { + change = false; + for (let i = 0; i < aliasArrays.length; i++) { + for (let ii = i + 1; ii < aliasArrays.length; ii++) { + const intersect = aliasArrays[i].filter(function (v) { + return aliasArrays[ii].indexOf(v) !== -1; + }); + if (intersect.length) { + aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]); + aliasArrays.splice(ii, 1); + change = true; + break; + } + } + } + } + aliasArrays.forEach(function (aliasArray) { + aliasArray = aliasArray.filter(function (v, i, self) { + return self.indexOf(v) === i; + }); + const lastAlias = aliasArray.pop(); + if (lastAlias !== undefined && typeof lastAlias === 'string') { + combined[lastAlias] = aliasArray; + } + }); + return combined; +} +function increment(orig) { + return orig !== undefined ? orig + 1 : 1; +} +function sanitizeKey(key) { + if (key === '__proto__') + return '___proto___'; + return key; +} +function stripQuotes(val) { + return (typeof val === 'string' && + (val[0] === "'" || val[0] === '"') && + val[val.length - 1] === val[0]) + ? val.substring(1, val.length - 1) + : val; +} + +var _a, _b, _c; +const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION) + ? Number(process.env.YARGS_MIN_NODE_VERSION) + : 12; +const nodeVersion = (_b = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1); +if (nodeVersion) { + const major = Number(nodeVersion.match(/^([^.]+)/)[1]); + if (major < minNodeVersion) { + throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`); + } +} +const env = process ? process.env : {}; +const parser = new YargsParser({ + cwd: process.cwd, + env: () => { + return env; + }, + format: util.format, + normalize: path.normalize, + resolve: path.resolve, + require: (path) => { + if (typeof require !== 'undefined') { + return require(path); + } + else if (path.match(/\.json$/)) { + return JSON.parse(fs.readFileSync(path, 'utf8')); + } + else { + throw Error('only .json config files are supported in ESM'); + } + } +}); +const yargsParser = function Parser(args, opts) { + const result = parser.parse(args.slice(), opts); + return result.argv; +}; +yargsParser.detailed = function (args, opts) { + return parser.parse(args.slice(), opts); +}; +yargsParser.camelCase = camelCase; +yargsParser.decamelize = decamelize; +yargsParser.looksLikeNumber = looksLikeNumber; + +module.exports = yargsParser; diff --git a/node_modules/yargs-parser/build/lib/index.js b/node_modules/yargs-parser/build/lib/index.js new file mode 100644 index 0000000..43ef485 --- /dev/null +++ b/node_modules/yargs-parser/build/lib/index.js @@ -0,0 +1,62 @@ +/** + * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js + * CJS and ESM environments. + * + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +var _a, _b, _c; +import { format } from 'util'; +import { normalize, resolve } from 'path'; +import { camelCase, decamelize, looksLikeNumber } from './string-utils.js'; +import { YargsParser } from './yargs-parser.js'; +import { readFileSync } from 'fs'; +// See https://github.com/yargs/yargs-parser#supported-nodejs-versions for our +// version support policy. The YARGS_MIN_NODE_VERSION is used for testing only. +const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION) + ? Number(process.env.YARGS_MIN_NODE_VERSION) + : 12; +const nodeVersion = (_b = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1); +if (nodeVersion) { + const major = Number(nodeVersion.match(/^([^.]+)/)[1]); + if (major < minNodeVersion) { + throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`); + } +} +// Creates a yargs-parser instance using Node.js standard libraries: +const env = process ? process.env : {}; +const parser = new YargsParser({ + cwd: process.cwd, + env: () => { + return env; + }, + format, + normalize, + resolve, + // TODO: figure out a way to combine ESM and CJS coverage, such that + // we can exercise all the lines below: + require: (path) => { + if (typeof require !== 'undefined') { + return require(path); + } + else if (path.match(/\.json$/)) { + // Addresses: https://github.com/yargs/yargs/issues/2040 + return JSON.parse(readFileSync(path, 'utf8')); + } + else { + throw Error('only .json config files are supported in ESM'); + } + } +}); +const yargsParser = function Parser(args, opts) { + const result = parser.parse(args.slice(), opts); + return result.argv; +}; +yargsParser.detailed = function (args, opts) { + return parser.parse(args.slice(), opts); +}; +yargsParser.camelCase = camelCase; +yargsParser.decamelize = decamelize; +yargsParser.looksLikeNumber = looksLikeNumber; +export default yargsParser; diff --git a/node_modules/yargs-parser/build/lib/string-utils.js b/node_modules/yargs-parser/build/lib/string-utils.js new file mode 100644 index 0000000..4e8bd99 --- /dev/null +++ b/node_modules/yargs-parser/build/lib/string-utils.js @@ -0,0 +1,65 @@ +/** + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +export function camelCase(str) { + // Handle the case where an argument is provided as camel case, e.g., fooBar. + // by ensuring that the string isn't already mixed case: + const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase(); + if (!isCamelCase) { + str = str.toLowerCase(); + } + if (str.indexOf('-') === -1 && str.indexOf('_') === -1) { + return str; + } + else { + let camelcase = ''; + let nextChrUpper = false; + const leadingHyphens = str.match(/^-+/); + for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) { + let chr = str.charAt(i); + if (nextChrUpper) { + nextChrUpper = false; + chr = chr.toUpperCase(); + } + if (i !== 0 && (chr === '-' || chr === '_')) { + nextChrUpper = true; + } + else if (chr !== '-' && chr !== '_') { + camelcase += chr; + } + } + return camelcase; + } +} +export function decamelize(str, joinString) { + const lowercase = str.toLowerCase(); + joinString = joinString || '-'; + let notCamelcase = ''; + for (let i = 0; i < str.length; i++) { + const chrLower = lowercase.charAt(i); + const chrString = str.charAt(i); + if (chrLower !== chrString && i > 0) { + notCamelcase += `${joinString}${lowercase.charAt(i)}`; + } + else { + notCamelcase += chrString; + } + } + return notCamelcase; +} +export function looksLikeNumber(x) { + if (x === null || x === undefined) + return false; + // if loaded from config, may already be a number. + if (typeof x === 'number') + return true; + // hexadecimal. + if (/^0x[0-9a-f]+$/i.test(x)) + return true; + // don't treat 0123 as a number; as it drops the leading '0'. + if (/^0[^.]/.test(x)) + return false; + return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} diff --git a/node_modules/yargs-parser/build/lib/tokenize-arg-string.js b/node_modules/yargs-parser/build/lib/tokenize-arg-string.js new file mode 100644 index 0000000..5e732ef --- /dev/null +++ b/node_modules/yargs-parser/build/lib/tokenize-arg-string.js @@ -0,0 +1,40 @@ +/** + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +// take an un-split argv string and tokenize it. +export function tokenizeArgString(argString) { + if (Array.isArray(argString)) { + return argString.map(e => typeof e !== 'string' ? e + '' : e); + } + argString = argString.trim(); + let i = 0; + let prevC = null; + let c = null; + let opening = null; + const args = []; + for (let ii = 0; ii < argString.length; ii++) { + prevC = c; + c = argString.charAt(ii); + // split on spaces unless we're in quotes. + if (c === ' ' && !opening) { + if (!(prevC === ' ')) { + i++; + } + continue; + } + // don't split the string if we're in matching + // opening or closing single and double quotes. + if (c === opening) { + opening = null; + } + else if ((c === "'" || c === '"') && !opening) { + opening = c; + } + if (!args[i]) + args[i] = ''; + args[i] += c; + } + return args; +} diff --git a/node_modules/yargs-parser/build/lib/yargs-parser-types.js b/node_modules/yargs-parser/build/lib/yargs-parser-types.js new file mode 100644 index 0000000..63b7c31 --- /dev/null +++ b/node_modules/yargs-parser/build/lib/yargs-parser-types.js @@ -0,0 +1,12 @@ +/** + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +export var DefaultValuesForTypeKey; +(function (DefaultValuesForTypeKey) { + DefaultValuesForTypeKey["BOOLEAN"] = "boolean"; + DefaultValuesForTypeKey["STRING"] = "string"; + DefaultValuesForTypeKey["NUMBER"] = "number"; + DefaultValuesForTypeKey["ARRAY"] = "array"; +})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {})); diff --git a/node_modules/yargs-parser/build/lib/yargs-parser.js b/node_modules/yargs-parser/build/lib/yargs-parser.js new file mode 100644 index 0000000..415d4bc --- /dev/null +++ b/node_modules/yargs-parser/build/lib/yargs-parser.js @@ -0,0 +1,1045 @@ +/** + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +import { tokenizeArgString } from './tokenize-arg-string.js'; +import { DefaultValuesForTypeKey } from './yargs-parser-types.js'; +import { camelCase, decamelize, looksLikeNumber } from './string-utils.js'; +let mixin; +export class YargsParser { + constructor(_mixin) { + mixin = _mixin; + } + parse(argsInput, options) { + const opts = Object.assign({ + alias: undefined, + array: undefined, + boolean: undefined, + config: undefined, + configObjects: undefined, + configuration: undefined, + coerce: undefined, + count: undefined, + default: undefined, + envPrefix: undefined, + narg: undefined, + normalize: undefined, + string: undefined, + number: undefined, + __: undefined, + key: undefined + }, options); + // allow a string argument to be passed in rather + // than an argv array. + const args = tokenizeArgString(argsInput); + // tokenizeArgString adds extra quotes to args if argsInput is a string + // only strip those extra quotes in processValue if argsInput is a string + const inputIsString = typeof argsInput === 'string'; + // aliases might have transitive relationships, normalize this. + const aliases = combineAliases(Object.assign(Object.create(null), opts.alias)); + const configuration = Object.assign({ + 'boolean-negation': true, + 'camel-case-expansion': true, + 'combine-arrays': false, + 'dot-notation': true, + 'duplicate-arguments-array': true, + 'flatten-duplicate-arrays': true, + 'greedy-arrays': true, + 'halt-at-non-option': false, + 'nargs-eats-options': false, + 'negation-prefix': 'no-', + 'parse-numbers': true, + 'parse-positional-numbers': true, + 'populate--': false, + 'set-placeholder-key': false, + 'short-option-groups': true, + 'strip-aliased': false, + 'strip-dashed': false, + 'unknown-options-as-args': false + }, opts.configuration); + const defaults = Object.assign(Object.create(null), opts.default); + const configObjects = opts.configObjects || []; + const envPrefix = opts.envPrefix; + const notFlagsOption = configuration['populate--']; + const notFlagsArgv = notFlagsOption ? '--' : '_'; + const newAliases = Object.create(null); + const defaulted = Object.create(null); + // allow a i18n handler to be passed in, default to a fake one (util.format). + const __ = opts.__ || mixin.format; + const flags = { + aliases: Object.create(null), + arrays: Object.create(null), + bools: Object.create(null), + strings: Object.create(null), + numbers: Object.create(null), + counts: Object.create(null), + normalize: Object.create(null), + configs: Object.create(null), + nargs: Object.create(null), + coercions: Object.create(null), + keys: [] + }; + const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/; + const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)'); + [].concat(opts.array || []).filter(Boolean).forEach(function (opt) { + const key = typeof opt === 'object' ? opt.key : opt; + // assign to flags[bools|strings|numbers] + const assignment = Object.keys(opt).map(function (key) { + const arrayFlagKeys = { + boolean: 'bools', + string: 'strings', + number: 'numbers' + }; + return arrayFlagKeys[key]; + }).filter(Boolean).pop(); + // assign key to be coerced + if (assignment) { + flags[assignment][key] = true; + } + flags.arrays[key] = true; + flags.keys.push(key); + }); + [].concat(opts.boolean || []).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + flags.keys.push(key); + }); + [].concat(opts.string || []).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + flags.keys.push(key); + }); + [].concat(opts.number || []).filter(Boolean).forEach(function (key) { + flags.numbers[key] = true; + flags.keys.push(key); + }); + [].concat(opts.count || []).filter(Boolean).forEach(function (key) { + flags.counts[key] = true; + flags.keys.push(key); + }); + [].concat(opts.normalize || []).filter(Boolean).forEach(function (key) { + flags.normalize[key] = true; + flags.keys.push(key); + }); + if (typeof opts.narg === 'object') { + Object.entries(opts.narg).forEach(([key, value]) => { + if (typeof value === 'number') { + flags.nargs[key] = value; + flags.keys.push(key); + } + }); + } + if (typeof opts.coerce === 'object') { + Object.entries(opts.coerce).forEach(([key, value]) => { + if (typeof value === 'function') { + flags.coercions[key] = value; + flags.keys.push(key); + } + }); + } + if (typeof opts.config !== 'undefined') { + if (Array.isArray(opts.config) || typeof opts.config === 'string') { + ; + [].concat(opts.config).filter(Boolean).forEach(function (key) { + flags.configs[key] = true; + }); + } + else if (typeof opts.config === 'object') { + Object.entries(opts.config).forEach(([key, value]) => { + if (typeof value === 'boolean' || typeof value === 'function') { + flags.configs[key] = value; + } + }); + } + } + // create a lookup table that takes into account all + // combinations of aliases: {f: ['foo'], foo: ['f']} + extendAliases(opts.key, aliases, opts.default, flags.arrays); + // apply default values to all aliases. + Object.keys(defaults).forEach(function (key) { + (flags.aliases[key] || []).forEach(function (alias) { + defaults[alias] = defaults[key]; + }); + }); + let error = null; + checkConfiguration(); + let notFlags = []; + const argv = Object.assign(Object.create(null), { _: [] }); + // TODO(bcoe): for the first pass at removing object prototype we didn't + // remove all prototypes from objects returned by this API, we might want + // to gradually move towards doing so. + const argvReturn = {}; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + const truncatedArg = arg.replace(/^-{3,}/, '---'); + let broken; + let key; + let letters; + let m; + let next; + let value; + // any unknown option (except for end-of-options, "--") + if (arg !== '--' && /^-/.test(arg) && isUnknownOptionAsArg(arg)) { + pushPositional(arg); + // ---, ---=, ----, etc, + } + else if (truncatedArg.match(/^---+(=|$)/)) { + // options without key name are invalid. + pushPositional(arg); + continue; + // -- separated by = + } + else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + m = arg.match(/^--?([^=]+)=([\s\S]*)$/); + // arrays format = '--f=a b c' + if (m !== null && Array.isArray(m) && m.length >= 3) { + if (checkAllAliases(m[1], flags.arrays)) { + i = eatArray(i, m[1], args, m[2]); + } + else if (checkAllAliases(m[1], flags.nargs) !== false) { + // nargs format = '--f=monkey washing cat' + i = eatNargs(i, m[1], args, m[2]); + } + else { + setArg(m[1], m[2], true); + } + } + } + else if (arg.match(negatedBoolean) && configuration['boolean-negation']) { + m = arg.match(negatedBoolean); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false); + } + // -- separated by space. + } + else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) { + m = arg.match(/^--?(.+)/); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + if (checkAllAliases(key, flags.arrays)) { + // array format = '--foo a b c' + i = eatArray(i, key, args); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + // nargs format = '--foo a b c' + // should be truthy even if: flags.nargs[key] === 0 + i = eatNargs(i, key, args); + } + else { + next = args[i + 1]; + if (next !== undefined && (!next.match(/^-/) || + next.match(negative)) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + // dot-notation flag separated by '='. + } + else if (arg.match(/^-.\..+=/)) { + m = arg.match(/^-([^=]+)=([\s\S]*)$/); + if (m !== null && Array.isArray(m) && m.length >= 3) { + setArg(m[1], m[2]); + } + // dot-notation flag separated by space. + } + else if (arg.match(/^-.\..+/) && !arg.match(negative)) { + next = args[i + 1]; + m = arg.match(/^-(.\..+)/); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + if (next !== undefined && !next.match(/^-/) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + else if (arg.match(/^-[^-]+/) && !arg.match(negative)) { + letters = arg.slice(1, -1).split(''); + broken = false; + for (let j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + if (letters[j + 1] && letters[j + 1] === '=') { + value = arg.slice(j + 3); + key = letters[j]; + if (checkAllAliases(key, flags.arrays)) { + // array format = '-f=a b c' + i = eatArray(i, key, args, value); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + // nargs format = '-f=monkey washing cat' + i = eatNargs(i, key, args, value); + } + else { + setArg(key, value); + } + broken = true; + break; + } + if (next === '-') { + setArg(letters[j], next); + continue; + } + // current letter is an alphabetic character and next value is a number + if (/[A-Za-z]/.test(letters[j]) && + /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) && + checkAllAliases(next, flags.bools) === false) { + setArg(letters[j], next); + broken = true; + break; + } + if (letters[j + 1] && letters[j + 1].match(/\W/)) { + setArg(letters[j], next); + broken = true; + break; + } + else { + setArg(letters[j], defaultValue(letters[j])); + } + } + key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if (checkAllAliases(key, flags.arrays)) { + // array format = '-f a b c' + i = eatArray(i, key, args); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + // nargs format = '-f a b c' + // should be truthy even if: flags.nargs[key] === 0 + i = eatNargs(i, key, args); + } + else { + next = args[i + 1]; + if (next !== undefined && (!/^(-|--)[^-]/.test(next) || + next.match(negative)) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + } + else if (arg.match(/^-[0-9]$/) && + arg.match(negative) && + checkAllAliases(arg.slice(1), flags.bools)) { + // single-digit boolean alias, e.g: xargs -0 + key = arg.slice(1); + setArg(key, defaultValue(key)); + } + else if (arg === '--') { + notFlags = args.slice(i + 1); + break; + } + else if (configuration['halt-at-non-option']) { + notFlags = args.slice(i); + break; + } + else { + pushPositional(arg); + } + } + // order of precedence: + // 1. command line arg + // 2. value from env var + // 3. value from config file + // 4. value from config objects + // 5. configured default value + applyEnvVars(argv, true); // special case: check env vars that point to config file + applyEnvVars(argv, false); + setConfig(argv); + setConfigObjects(); + applyDefaultsAndAliases(argv, flags.aliases, defaults, true); + applyCoercions(argv); + if (configuration['set-placeholder-key']) + setPlaceholderKeys(argv); + // for any counts either not in args or without an explicit default, set to 0 + Object.keys(flags.counts).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) + setArg(key, 0); + }); + // '--' defaults to undefined. + if (notFlagsOption && notFlags.length) + argv[notFlagsArgv] = []; + notFlags.forEach(function (key) { + argv[notFlagsArgv].push(key); + }); + if (configuration['camel-case-expansion'] && configuration['strip-dashed']) { + Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => { + delete argv[key]; + }); + } + if (configuration['strip-aliased']) { + ; + [].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => { + if (configuration['camel-case-expansion'] && alias.includes('-')) { + delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')]; + } + delete argv[alias]; + }); + } + // Push argument into positional array, applying numeric coercion: + function pushPositional(arg) { + const maybeCoercedNumber = maybeCoerceNumber('_', arg); + if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') { + argv._.push(maybeCoercedNumber); + } + } + // how many arguments should we consume, based + // on the nargs option? + function eatNargs(i, key, args, argAfterEqualSign) { + let ii; + let toEat = checkAllAliases(key, flags.nargs); + // NaN has a special meaning for the array type, indicating that one or + // more values are expected. + toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat; + if (toEat === 0) { + if (!isUndefined(argAfterEqualSign)) { + error = Error(__('Argument unexpected for: %s', key)); + } + setArg(key, defaultValue(key)); + return i; + } + let available = isUndefined(argAfterEqualSign) ? 0 : 1; + if (configuration['nargs-eats-options']) { + // classic behavior, yargs eats positional and dash arguments. + if (args.length - (i + 1) + available < toEat) { + error = Error(__('Not enough arguments following: %s', key)); + } + available = toEat; + } + else { + // nargs will not consume flag arguments, e.g., -abc, --foo, + // and terminates when one is observed. + for (ii = i + 1; ii < args.length; ii++) { + if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii])) + available++; + else + break; + } + if (available < toEat) + error = Error(__('Not enough arguments following: %s', key)); + } + let consumed = Math.min(available, toEat); + if (!isUndefined(argAfterEqualSign) && consumed > 0) { + setArg(key, argAfterEqualSign); + consumed--; + } + for (ii = i + 1; ii < (consumed + i + 1); ii++) { + setArg(key, args[ii]); + } + return (i + consumed); + } + // if an option is an array, eat all non-hyphenated arguments + // following it... YUM! + // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"] + function eatArray(i, key, args, argAfterEqualSign) { + let argsToSet = []; + let next = argAfterEqualSign || args[i + 1]; + // If both array and nargs are configured, enforce the nargs count: + const nargsCount = checkAllAliases(key, flags.nargs); + if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) { + argsToSet.push(true); + } + else if (isUndefined(next) || + (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) { + // for keys without value ==> argsToSet remains an empty [] + // set user default value, if available + if (defaults[key] !== undefined) { + const defVal = defaults[key]; + argsToSet = Array.isArray(defVal) ? defVal : [defVal]; + } + } + else { + // value in --option=value is eaten as is + if (!isUndefined(argAfterEqualSign)) { + argsToSet.push(processValue(key, argAfterEqualSign, true)); + } + for (let ii = i + 1; ii < args.length; ii++) { + if ((!configuration['greedy-arrays'] && argsToSet.length > 0) || + (nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount)) + break; + next = args[ii]; + if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) + break; + i = ii; + argsToSet.push(processValue(key, next, inputIsString)); + } + } + // If both array and nargs are configured, create an error if less than + // nargs positionals were found. NaN has special meaning, indicating + // that at least one value is required (more are okay). + if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) || + (isNaN(nargsCount) && argsToSet.length === 0))) { + error = Error(__('Not enough arguments following: %s', key)); + } + setArg(key, argsToSet); + return i; + } + function setArg(key, val, shouldStripQuotes = inputIsString) { + if (/-/.test(key) && configuration['camel-case-expansion']) { + const alias = key.split('.').map(function (prop) { + return camelCase(prop); + }).join('.'); + addNewAlias(key, alias); + } + const value = processValue(key, val, shouldStripQuotes); + const splitKey = key.split('.'); + setKey(argv, splitKey, value); + // handle populating aliases of the full key + if (flags.aliases[key]) { + flags.aliases[key].forEach(function (x) { + const keyProperties = x.split('.'); + setKey(argv, keyProperties, value); + }); + } + // handle populating aliases of the first element of the dot-notation key + if (splitKey.length > 1 && configuration['dot-notation']) { + ; + (flags.aliases[splitKey[0]] || []).forEach(function (x) { + let keyProperties = x.split('.'); + // expand alias with nested objects in key + const a = [].concat(splitKey); + a.shift(); // nuke the old key. + keyProperties = keyProperties.concat(a); + // populate alias only if is not already an alias of the full key + // (already populated above) + if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) { + setKey(argv, keyProperties, value); + } + }); + } + // Set normalize getter and setter when key is in 'normalize' but isn't an array + if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) { + const keys = [key].concat(flags.aliases[key] || []); + keys.forEach(function (key) { + Object.defineProperty(argvReturn, key, { + enumerable: true, + get() { + return val; + }, + set(value) { + val = typeof value === 'string' ? mixin.normalize(value) : value; + } + }); + }); + } + } + function addNewAlias(key, alias) { + if (!(flags.aliases[key] && flags.aliases[key].length)) { + flags.aliases[key] = [alias]; + newAliases[alias] = true; + } + if (!(flags.aliases[alias] && flags.aliases[alias].length)) { + addNewAlias(alias, key); + } + } + function processValue(key, val, shouldStripQuotes) { + // strings may be quoted, clean this up as we assign values. + if (shouldStripQuotes) { + val = stripQuotes(val); + } + // handle parsing boolean arguments --foo=true --bar false. + if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) { + if (typeof val === 'string') + val = val === 'true'; + } + let value = Array.isArray(val) + ? val.map(function (v) { return maybeCoerceNumber(key, v); }) + : maybeCoerceNumber(key, val); + // increment a count given as arg (either no value or value parsed as boolean) + if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) { + value = increment(); + } + // Set normalized value when key is in 'normalize' and in 'arrays' + if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) { + if (Array.isArray(val)) + value = val.map((val) => { return mixin.normalize(val); }); + else + value = mixin.normalize(val); + } + return value; + } + function maybeCoerceNumber(key, value) { + if (!configuration['parse-positional-numbers'] && key === '_') + return value; + if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) { + const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`)))); + if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) { + value = Number(value); + } + } + return value; + } + // set args from config.json file, this should be + // applied last so that defaults can be applied. + function setConfig(argv) { + const configLookup = Object.create(null); + // expand defaults/aliases, in-case any happen to reference + // the config.json file. + applyDefaultsAndAliases(configLookup, flags.aliases, defaults); + Object.keys(flags.configs).forEach(function (configKey) { + const configPath = argv[configKey] || configLookup[configKey]; + if (configPath) { + try { + let config = null; + const resolvedConfigPath = mixin.resolve(mixin.cwd(), configPath); + const resolveConfig = flags.configs[configKey]; + if (typeof resolveConfig === 'function') { + try { + config = resolveConfig(resolvedConfigPath); + } + catch (e) { + config = e; + } + if (config instanceof Error) { + error = config; + return; + } + } + else { + config = mixin.require(resolvedConfigPath); + } + setConfigObject(config); + } + catch (ex) { + // Deno will receive a PermissionDenied error if an attempt is + // made to load config without the --allow-read flag: + if (ex.name === 'PermissionDenied') + error = ex; + else if (argv[configKey]) + error = Error(__('Invalid JSON config file: %s', configPath)); + } + } + }); + } + // set args from config object. + // it recursively checks nested objects. + function setConfigObject(config, prev) { + Object.keys(config).forEach(function (key) { + const value = config[key]; + const fullKey = prev ? prev + '.' + key : key; + // if the value is an inner object and we have dot-notation + // enabled, treat inner objects in config the same as + // heavily nested dot notations (foo.bar.apple). + if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) { + // if the value is an object but not an array, check nested object + setConfigObject(value, fullKey); + } + else { + // setting arguments via CLI takes precedence over + // values within the config file. + if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) { + setArg(fullKey, value); + } + } + }); + } + // set all config objects passed in opts + function setConfigObjects() { + if (typeof configObjects !== 'undefined') { + configObjects.forEach(function (configObject) { + setConfigObject(configObject); + }); + } + } + function applyEnvVars(argv, configOnly) { + if (typeof envPrefix === 'undefined') + return; + const prefix = typeof envPrefix === 'string' ? envPrefix : ''; + const env = mixin.env(); + Object.keys(env).forEach(function (envVar) { + if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) { + // get array of nested keys and convert them to camel case + const keys = envVar.split('__').map(function (key, i) { + if (i === 0) { + key = key.substring(prefix.length); + } + return camelCase(key); + }); + if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) { + setArg(keys.join('.'), env[envVar]); + } + } + }); + } + function applyCoercions(argv) { + let coerce; + const applied = new Set(); + Object.keys(argv).forEach(function (key) { + if (!applied.has(key)) { // If we haven't already coerced this option via one of its aliases + coerce = checkAllAliases(key, flags.coercions); + if (typeof coerce === 'function') { + try { + const value = maybeCoerceNumber(key, coerce(argv[key])); + ([].concat(flags.aliases[key] || [], key)).forEach(ali => { + applied.add(ali); + argv[ali] = value; + }); + } + catch (err) { + error = err; + } + } + } + }); + } + function setPlaceholderKeys(argv) { + flags.keys.forEach((key) => { + // don't set placeholder keys for dot notation options 'foo.bar'. + if (~key.indexOf('.')) + return; + if (typeof argv[key] === 'undefined') + argv[key] = undefined; + }); + return argv; + } + function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) { + Object.keys(defaults).forEach(function (key) { + if (!hasKey(obj, key.split('.'))) { + setKey(obj, key.split('.'), defaults[key]); + if (canLog) + defaulted[key] = true; + (aliases[key] || []).forEach(function (x) { + if (hasKey(obj, x.split('.'))) + return; + setKey(obj, x.split('.'), defaults[key]); + }); + } + }); + } + function hasKey(obj, keys) { + let o = obj; + if (!configuration['dot-notation']) + keys = [keys.join('.')]; + keys.slice(0, -1).forEach(function (key) { + o = (o[key] || {}); + }); + const key = keys[keys.length - 1]; + if (typeof o !== 'object') + return false; + else + return key in o; + } + function setKey(obj, keys, value) { + let o = obj; + if (!configuration['dot-notation']) + keys = [keys.join('.')]; + keys.slice(0, -1).forEach(function (key) { + // TODO(bcoe): in the next major version of yargs, switch to + // Object.create(null) for dot notation: + key = sanitizeKey(key); + if (typeof o === 'object' && o[key] === undefined) { + o[key] = {}; + } + if (typeof o[key] !== 'object' || Array.isArray(o[key])) { + // ensure that o[key] is an array, and that the last item is an empty object. + if (Array.isArray(o[key])) { + o[key].push({}); + } + else { + o[key] = [o[key], {}]; + } + // we want to update the empty object at the end of the o[key] array, so set o to that object + o = o[key][o[key].length - 1]; + } + else { + o = o[key]; + } + }); + // TODO(bcoe): in the next major version of yargs, switch to + // Object.create(null) for dot notation: + const key = sanitizeKey(keys[keys.length - 1]); + const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays); + const isValueArray = Array.isArray(value); + let duplicate = configuration['duplicate-arguments-array']; + // nargs has higher priority than duplicate + if (!duplicate && checkAllAliases(key, flags.nargs)) { + duplicate = true; + if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) { + o[key] = undefined; + } + } + if (value === increment()) { + o[key] = increment(o[key]); + } + else if (Array.isArray(o[key])) { + if (duplicate && isTypeArray && isValueArray) { + o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]); + } + else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) { + o[key] = value; + } + else { + o[key] = o[key].concat([value]); + } + } + else if (o[key] === undefined && isTypeArray) { + o[key] = isValueArray ? value : [value]; + } + else if (duplicate && !(o[key] === undefined || + checkAllAliases(key, flags.counts) || + checkAllAliases(key, flags.bools))) { + o[key] = [o[key], value]; + } + else { + o[key] = value; + } + } + // extend the aliases list with inferred aliases. + function extendAliases(...args) { + args.forEach(function (obj) { + Object.keys(obj || {}).forEach(function (key) { + // short-circuit if we've already added a key + // to the aliases array, for example it might + // exist in both 'opts.default' and 'opts.key'. + if (flags.aliases[key]) + return; + flags.aliases[key] = [].concat(aliases[key] || []); + // For "--option-name", also set argv.optionName + flags.aliases[key].concat(key).forEach(function (x) { + if (/-/.test(x) && configuration['camel-case-expansion']) { + const c = camelCase(x); + if (c !== key && flags.aliases[key].indexOf(c) === -1) { + flags.aliases[key].push(c); + newAliases[c] = true; + } + } + }); + // For "--optionName", also set argv['option-name'] + flags.aliases[key].concat(key).forEach(function (x) { + if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) { + const c = decamelize(x, '-'); + if (c !== key && flags.aliases[key].indexOf(c) === -1) { + flags.aliases[key].push(c); + newAliases[c] = true; + } + } + }); + flags.aliases[key].forEach(function (x) { + flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + }); + } + function checkAllAliases(key, flag) { + const toCheck = [].concat(flags.aliases[key] || [], key); + const keys = Object.keys(flag); + const setAlias = toCheck.find(key => keys.includes(key)); + return setAlias ? flag[setAlias] : false; + } + function hasAnyFlag(key) { + const flagsKeys = Object.keys(flags); + const toCheck = [].concat(flagsKeys.map(k => flags[k])); + return toCheck.some(function (flag) { + return Array.isArray(flag) ? flag.includes(key) : flag[key]; + }); + } + function hasFlagsMatching(arg, ...patterns) { + const toCheck = [].concat(...patterns); + return toCheck.some(function (pattern) { + const match = arg.match(pattern); + return match && hasAnyFlag(match[1]); + }); + } + // based on a simplified version of the short flag group parsing logic + function hasAllShortFlags(arg) { + // if this is a negative number, or doesn't start with a single hyphen, it's not a short flag group + if (arg.match(negative) || !arg.match(/^-[^-]+/)) { + return false; + } + let hasAllFlags = true; + let next; + const letters = arg.slice(1).split(''); + for (let j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + if (!hasAnyFlag(letters[j])) { + hasAllFlags = false; + break; + } + if ((letters[j + 1] && letters[j + 1] === '=') || + next === '-' || + (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) || + (letters[j + 1] && letters[j + 1].match(/\W/))) { + break; + } + } + return hasAllFlags; + } + function isUnknownOptionAsArg(arg) { + return configuration['unknown-options-as-args'] && isUnknownOption(arg); + } + function isUnknownOption(arg) { + arg = arg.replace(/^-{3,}/, '--'); + // ignore negative numbers + if (arg.match(negative)) { + return false; + } + // if this is a short option group and all of them are configured, it isn't unknown + if (hasAllShortFlags(arg)) { + return false; + } + // e.g. '--count=2' + const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/; + // e.g. '-a' or '--arg' + const normalFlag = /^-+([^=]+?)$/; + // e.g. '-a-' + const flagEndingInHyphen = /^-+([^=]+?)-$/; + // e.g. '-abc123' + const flagEndingInDigits = /^-+([^=]+?\d+)$/; + // e.g. '-a/usr/local' + const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/; + // check the different types of flag styles, including negatedBoolean, a pattern defined near the start of the parse method + return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters); + } + // make a best effort to pick a default value + // for an option based on name and type. + function defaultValue(key) { + if (!checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts) && + `${key}` in defaults) { + return defaults[key]; + } + else { + return defaultForType(guessType(key)); + } + } + // return a default value, given the type of a flag., + function defaultForType(type) { + const def = { + [DefaultValuesForTypeKey.BOOLEAN]: true, + [DefaultValuesForTypeKey.STRING]: '', + [DefaultValuesForTypeKey.NUMBER]: undefined, + [DefaultValuesForTypeKey.ARRAY]: [] + }; + return def[type]; + } + // given a flag, enforce a default type. + function guessType(key) { + let type = DefaultValuesForTypeKey.BOOLEAN; + if (checkAllAliases(key, flags.strings)) + type = DefaultValuesForTypeKey.STRING; + else if (checkAllAliases(key, flags.numbers)) + type = DefaultValuesForTypeKey.NUMBER; + else if (checkAllAliases(key, flags.bools)) + type = DefaultValuesForTypeKey.BOOLEAN; + else if (checkAllAliases(key, flags.arrays)) + type = DefaultValuesForTypeKey.ARRAY; + return type; + } + function isUndefined(num) { + return num === undefined; + } + // check user configuration settings for inconsistencies + function checkConfiguration() { + // count keys should not be set as array/narg + Object.keys(flags.counts).find(key => { + if (checkAllAliases(key, flags.arrays)) { + error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key)); + return true; + } + else if (checkAllAliases(key, flags.nargs)) { + error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key)); + return true; + } + return false; + }); + } + return { + aliases: Object.assign({}, flags.aliases), + argv: Object.assign(argvReturn, argv), + configuration: configuration, + defaulted: Object.assign({}, defaulted), + error: error, + newAliases: Object.assign({}, newAliases) + }; + } +} +// if any aliases reference each other, we should +// merge them together. +function combineAliases(aliases) { + const aliasArrays = []; + const combined = Object.create(null); + let change = true; + // turn alias lookup hash {key: ['alias1', 'alias2']} into + // a simple array ['key', 'alias1', 'alias2'] + Object.keys(aliases).forEach(function (key) { + aliasArrays.push([].concat(aliases[key], key)); + }); + // combine arrays until zero changes are + // made in an iteration. + while (change) { + change = false; + for (let i = 0; i < aliasArrays.length; i++) { + for (let ii = i + 1; ii < aliasArrays.length; ii++) { + const intersect = aliasArrays[i].filter(function (v) { + return aliasArrays[ii].indexOf(v) !== -1; + }); + if (intersect.length) { + aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]); + aliasArrays.splice(ii, 1); + change = true; + break; + } + } + } + } + // map arrays back to the hash-lookup (de-dupe while + // we're at it). + aliasArrays.forEach(function (aliasArray) { + aliasArray = aliasArray.filter(function (v, i, self) { + return self.indexOf(v) === i; + }); + const lastAlias = aliasArray.pop(); + if (lastAlias !== undefined && typeof lastAlias === 'string') { + combined[lastAlias] = aliasArray; + } + }); + return combined; +} +// this function should only be called when a count is given as an arg +// it is NOT called to set a default value +// thus we can start the count at 1 instead of 0 +function increment(orig) { + return orig !== undefined ? orig + 1 : 1; +} +// TODO(bcoe): in the next major version of yargs, switch to +// Object.create(null) for dot notation: +function sanitizeKey(key) { + if (key === '__proto__') + return '___proto___'; + return key; +} +function stripQuotes(val) { + return (typeof val === 'string' && + (val[0] === "'" || val[0] === '"') && + val[val.length - 1] === val[0]) + ? val.substring(1, val.length - 1) + : val; +} diff --git a/node_modules/yargs-parser/package.json b/node_modules/yargs-parser/package.json new file mode 100644 index 0000000..decd0c3 --- /dev/null +++ b/node_modules/yargs-parser/package.json @@ -0,0 +1,92 @@ +{ + "name": "yargs-parser", + "version": "21.1.1", + "description": "the mighty option parser used by yargs", + "main": "build/index.cjs", + "exports": { + ".": [ + { + "import": "./build/lib/index.js", + "require": "./build/index.cjs" + }, + "./build/index.cjs" + ], + "./browser": [ + "./browser.js" + ] + }, + "type": "module", + "module": "./build/lib/index.js", + "scripts": { + "check": "standardx '**/*.ts' && standardx '**/*.js' && standardx '**/*.cjs'", + "fix": "standardx --fix '**/*.ts' && standardx --fix '**/*.js' && standardx --fix '**/*.cjs'", + "pretest": "rimraf build && tsc -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs", + "test": "c8 --reporter=text --reporter=html mocha test/*.cjs", + "test:esm": "c8 --reporter=text --reporter=html mocha test/*.mjs", + "test:browser": "start-server-and-test 'serve ./ -p 8080' http://127.0.0.1:8080/package.json 'node ./test/browser/yargs-test.cjs'", + "pretest:typescript": "npm run pretest", + "test:typescript": "c8 mocha ./build/test/typescript/*.js", + "coverage": "c8 report --check-coverage", + "precompile": "rimraf build", + "compile": "tsc", + "postcompile": "npm run build:cjs", + "build:cjs": "rollup -c", + "prepare": "npm run compile" + }, + "repository": { + "type": "git", + "url": "https://github.com/yargs/yargs-parser.git" + }, + "keywords": [ + "argument", + "parser", + "yargs", + "command", + "cli", + "parsing", + "option", + "args", + "argument" + ], + "author": "Ben Coe ", + "license": "ISC", + "devDependencies": { + "@types/chai": "^4.2.11", + "@types/mocha": "^9.0.0", + "@types/node": "^16.11.4", + "@typescript-eslint/eslint-plugin": "^3.10.1", + "@typescript-eslint/parser": "^3.10.1", + "c8": "^7.3.0", + "chai": "^4.2.0", + "cross-env": "^7.0.2", + "eslint": "^7.0.0", + "eslint-plugin-import": "^2.20.1", + "eslint-plugin-node": "^11.0.0", + "gts": "^3.0.0", + "mocha": "^10.0.0", + "puppeteer": "^16.0.0", + "rimraf": "^3.0.2", + "rollup": "^2.22.1", + "rollup-plugin-cleanup": "^3.1.1", + "rollup-plugin-ts": "^3.0.2", + "serve": "^14.0.0", + "standardx": "^7.0.0", + "start-server-and-test": "^1.11.2", + "ts-transform-default-export": "^1.0.2", + "typescript": "^4.0.0" + }, + "files": [ + "browser.js", + "build", + "!*.d.ts", + "!*.d.cts" + ], + "engines": { + "node": ">=12" + }, + "standardx": { + "ignore": [ + "build" + ] + } +} diff --git a/node_modules/yargs/LICENSE b/node_modules/yargs/LICENSE new file mode 100644 index 0000000..b0145ca --- /dev/null +++ b/node_modules/yargs/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright 2010 James Halliday (mail@substack.net); Modified work Copyright 2014 Contributors (ben@npmjs.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/yargs/README.md b/node_modules/yargs/README.md new file mode 100644 index 0000000..51f5b22 --- /dev/null +++ b/node_modules/yargs/README.md @@ -0,0 +1,204 @@ +

                          + +

                          +

                          Yargs

                          +

                          + Yargs be a node.js library fer hearties tryin' ter parse optstrings +

                          + +
                          + +![ci](https://github.com/yargs/yargs/workflows/ci/badge.svg) +[![NPM version][npm-image]][npm-url] +[![js-standard-style][standard-image]][standard-url] +[![Coverage][coverage-image]][coverage-url] +[![Conventional Commits][conventional-commits-image]][conventional-commits-url] +[![Slack][slack-image]][slack-url] + +## Description +Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. + +It gives you: + +* commands and (grouped) options (`my-program.js serve --port=5000`). +* a dynamically generated help menu based on your arguments: + +``` +mocha [spec..] + +Run tests with Mocha + +Commands + mocha inspect [spec..] Run tests with Mocha [default] + mocha init create a client-side Mocha setup at + +Rules & Behavior + --allow-uncaught Allow uncaught errors to propagate [boolean] + --async-only, -A Require all tests to use a callback (async) or + return a Promise [boolean] +``` + +* bash-completion shortcuts for commands and options. +* and [tons more](/docs/api.md). + +## Installation + +Stable version: +```bash +npm i yargs +``` + +Bleeding edge version with the most recent features: +```bash +npm i yargs@next +``` + +## Usage + +### Simple Example + +```javascript +#!/usr/bin/env node +const yargs = require('yargs/yargs') +const { hideBin } = require('yargs/helpers') +const argv = yargs(hideBin(process.argv)).argv + +if (argv.ships > 3 && argv.distance < 53.5) { + console.log('Plunder more riffiwobbles!') +} else { + console.log('Retreat from the xupptumblers!') +} +``` + +```bash +$ ./plunder.js --ships=4 --distance=22 +Plunder more riffiwobbles! + +$ ./plunder.js --ships 12 --distance 98.7 +Retreat from the xupptumblers! +``` + +> Note: `hideBin` is a shorthand for [`process.argv.slice(2)`](https://nodejs.org/en/knowledge/command-line/how-to-parse-command-line-arguments/). It has the benefit that it takes into account variations in some environments, e.g., [Electron](https://github.com/electron/electron/issues/4690). + +### Complex Example + +```javascript +#!/usr/bin/env node +const yargs = require('yargs/yargs') +const { hideBin } = require('yargs/helpers') + +yargs(hideBin(process.argv)) + .command('serve [port]', 'start the server', (yargs) => { + return yargs + .positional('port', { + describe: 'port to bind on', + default: 5000 + }) + }, (argv) => { + if (argv.verbose) console.info(`start server on :${argv.port}`) + serve(argv.port) + }) + .option('verbose', { + alias: 'v', + type: 'boolean', + description: 'Run with verbose logging' + }) + .parse() +``` + +Run the example above with `--help` to see the help for the application. + +## Supported Platforms + +### TypeScript + +yargs has type definitions at [@types/yargs][type-definitions]. + +``` +npm i @types/yargs --save-dev +``` + +See usage examples in [docs](/docs/typescript.md). + +### Deno + +As of `v16`, `yargs` supports [Deno](https://github.com/denoland/deno): + +```typescript +import yargs from 'https://deno.land/x/yargs/deno.ts' +import { Arguments } from 'https://deno.land/x/yargs/deno-types.ts' + +yargs(Deno.args) + .command('download ', 'download a list of files', (yargs: any) => { + return yargs.positional('files', { + describe: 'a list of files to do something with' + }) + }, (argv: Arguments) => { + console.info(argv) + }) + .strictCommands() + .demandCommand(1) + .parse() +``` + +### ESM + +As of `v16`,`yargs` supports ESM imports: + +```js +import yargs from 'yargs' +import { hideBin } from 'yargs/helpers' + +yargs(hideBin(process.argv)) + .command('curl ', 'fetch the contents of the URL', () => {}, (argv) => { + console.info(argv) + }) + .demandCommand(1) + .parse() +``` + +### Usage in Browser + +See examples of using yargs in the browser in [docs](/docs/browser.md). + +## Community + +Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com). + +## Documentation + +### Table of Contents + +* [Yargs' API](/docs/api.md) +* [Examples](/docs/examples.md) +* [Parsing Tricks](/docs/tricks.md) + * [Stop the Parser](/docs/tricks.md#stop) + * [Negating Boolean Arguments](/docs/tricks.md#negate) + * [Numbers](/docs/tricks.md#numbers) + * [Arrays](/docs/tricks.md#arrays) + * [Objects](/docs/tricks.md#objects) + * [Quotes](/docs/tricks.md#quotes) +* [Advanced Topics](/docs/advanced.md) + * [Composing Your App Using Commands](/docs/advanced.md#commands) + * [Building Configurable CLI Apps](/docs/advanced.md#configuration) + * [Customizing Yargs' Parser](/docs/advanced.md#customizing) + * [Bundling yargs](/docs/bundling.md) +* [Contributing](/contributing.md) + +## Supported Node.js Versions + +Libraries in this ecosystem make a best effort to track +[Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a +post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). + +[npm-url]: https://www.npmjs.com/package/yargs +[npm-image]: https://img.shields.io/npm/v/yargs.svg +[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg +[standard-url]: http://standardjs.com/ +[conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg +[conventional-commits-url]: https://conventionalcommits.org/ +[slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg +[slack-url]: http://devtoolscommunity.herokuapp.com +[type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs +[coverage-image]: https://img.shields.io/nycrc/yargs/yargs +[coverage-url]: https://github.com/yargs/yargs/blob/main/.nycrc diff --git a/node_modules/yargs/browser.d.ts b/node_modules/yargs/browser.d.ts new file mode 100644 index 0000000..21f3fc6 --- /dev/null +++ b/node_modules/yargs/browser.d.ts @@ -0,0 +1,5 @@ +import {YargsFactory} from './build/lib/yargs-factory'; + +declare const Yargs: ReturnType; + +export default Yargs; diff --git a/node_modules/yargs/browser.mjs b/node_modules/yargs/browser.mjs new file mode 100644 index 0000000..2d0d6e9 --- /dev/null +++ b/node_modules/yargs/browser.mjs @@ -0,0 +1,7 @@ +// Bootstrap yargs for browser: +import browserPlatformShim from './lib/platform-shims/browser.mjs'; +import {YargsFactory} from './build/lib/yargs-factory.js'; + +const Yargs = YargsFactory(browserPlatformShim); + +export default Yargs; diff --git a/node_modules/yargs/build/index.cjs b/node_modules/yargs/build/index.cjs new file mode 100644 index 0000000..e9cf013 --- /dev/null +++ b/node_modules/yargs/build/index.cjs @@ -0,0 +1 @@ +"use strict";var t=require("assert");class e extends Error{constructor(t){super(t||"yargs error"),this.name="YError",Error.captureStackTrace&&Error.captureStackTrace(this,e)}}let s,i=[];function n(t,o,a,h){s=h;let l={};if(Object.prototype.hasOwnProperty.call(t,"extends")){if("string"!=typeof t.extends)return l;const r=/\.json|\..*rc$/.test(t.extends);let h=null;if(r)h=function(t,e){return s.path.resolve(t,e)}(o,t.extends);else try{h=require.resolve(t.extends)}catch(e){return t}!function(t){if(i.indexOf(t)>-1)throw new e(`Circular extended configurations: '${t}'.`)}(h),i.push(h),l=r?JSON.parse(s.readFileSync(h,"utf8")):require(t.extends),delete t.extends,l=n(l,s.path.dirname(h),a,s)}return i=[],a?r(l,t):Object.assign({},l,t)}function r(t,e){const s={};function i(t){return t&&"object"==typeof t&&!Array.isArray(t)}Object.assign(s,t);for(const n of Object.keys(e))i(e[n])&&i(s[n])?s[n]=r(t[n],e[n]):s[n]=e[n];return s}function o(t){const e=t.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),s=/\.*[\][<>]/g,i=e.shift();if(!i)throw new Error(`No command found in: ${t}`);const n={cmd:i.replace(s,""),demanded:[],optional:[]};return e.forEach(((t,i)=>{let r=!1;t=t.replace(/\s/g,""),/\.+[\]>]/.test(t)&&i===e.length-1&&(r=!0),/^\[/.test(t)?n.optional.push({cmd:t.replace(s,"").split("|"),variadic:r}):n.demanded.push({cmd:t.replace(s,"").split("|"),variadic:r})})),n}const a=["first","second","third","fourth","fifth","sixth"];function h(t,s,i){try{let n=0;const[r,a,h]="object"==typeof t?[{demanded:[],optional:[]},t,s]:[o(`cmd ${t}`),s,i],f=[].slice.call(a);for(;f.length&&void 0===f[f.length-1];)f.pop();const d=h||f.length;if(du)throw new e(`Too many arguments provided. Expected max ${u} but received ${d}.`);r.demanded.forEach((t=>{const e=l(f.shift());0===t.cmd.filter((t=>t===e||"*"===t)).length&&c(e,t.cmd,n),n+=1})),r.optional.forEach((t=>{if(0===f.length)return;const e=l(f.shift());0===t.cmd.filter((t=>t===e||"*"===t)).length&&c(e,t.cmd,n),n+=1}))}catch(t){console.warn(t.stack)}}function l(t){return Array.isArray(t)?"array":null===t?"null":typeof t}function c(t,s,i){throw new e(`Invalid ${a[i]||"manyith"} argument. Expected ${s.join(" or ")} but received ${t}.`)}function f(t){return!!t&&!!t.then&&"function"==typeof t.then}function d(t,e,s,i){s.assert.notStrictEqual(t,e,i)}function u(t,e){e.assert.strictEqual(typeof t,"string")}function p(t){return Object.keys(t)}function g(t={},e=(()=>!0)){const s={};return p(t).forEach((i=>{e(i,t[i])&&(s[i]=t[i])})),s}function m(){return process.versions.electron&&!process.defaultApp?0:1}function y(){return process.argv[m()]}var b=Object.freeze({__proto__:null,hideBin:function(t){return t.slice(m()+1)},getProcessArgvBin:y});function v(t,e,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(t):i?i.value:e.get(t)}function O(t,e,s,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(t,s):n?n.value=s:e.set(t,s),s}class w{constructor(t){this.globalMiddleware=[],this.frozens=[],this.yargs=t}addMiddleware(t,e,s=!0,i=!1){if(h(" [boolean] [boolean] [boolean]",[t,e,s],arguments.length),Array.isArray(t)){for(let i=0;i{const i=[...s[e]||[],e];return!t.option||!i.includes(t.option)})),t.option=e,this.addMiddleware(t,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){const t=this.frozens.pop();void 0!==t&&(this.globalMiddleware=t)}reset(){this.globalMiddleware=this.globalMiddleware.filter((t=>t.global))}}function C(t,e,s,i){return s.reduce(((t,s)=>{if(s.applyBeforeValidation!==i)return t;if(s.mutates){if(s.applied)return t;s.applied=!0}if(f(t))return t.then((t=>Promise.all([t,s(t,e)]))).then((([t,e])=>Object.assign(t,e)));{const i=s(t,e);return f(i)?i.then((e=>Object.assign(t,e))):Object.assign(t,i)}}),t)}function j(t,e,s=(t=>{throw t})){try{const s="function"==typeof t?t():t;return f(s)?s.then((t=>e(t))):e(s)}catch(t){return s(t)}}const M=/(^\*)|(^\$0)/;class _{constructor(t,e,s,i){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=i,this.usage=t,this.globalMiddleware=s,this.validation=e}addDirectory(t,e,s,i){"boolean"!=typeof(i=i||{}).recurse&&(i.recurse=!1),Array.isArray(i.extensions)||(i.extensions=["js"]);const n="function"==typeof i.visit?i.visit:t=>t;i.visit=(t,e,s)=>{const i=n(t,e,s);if(i){if(this.requireCache.has(e))return i;this.requireCache.add(e),this.addHandler(i)}return i},this.shim.requireDirectory({require:e,filename:s},t,i)}addHandler(t,e,s,i,n,r){let a=[];const h=function(t){return t?t.map((t=>(t.applyBeforeValidation=!1,t))):[]}(n);if(i=i||(()=>{}),Array.isArray(t))if(function(t){return t.every((t=>"string"==typeof t))}(t))[t,...a]=t;else for(const e of t)this.addHandler(e);else{if(function(t){return"object"==typeof t&&!Array.isArray(t)}(t)){let e=Array.isArray(t.command)||"string"==typeof t.command?t.command:this.moduleName(t);return t.aliases&&(e=[].concat(e).concat(t.aliases)),void this.addHandler(e,this.extractDesc(t),t.builder,t.handler,t.middlewares,t.deprecated)}if(k(s))return void this.addHandler([t].concat(a),e,s.builder,s.handler,s.middlewares,s.deprecated)}if("string"==typeof t){const n=o(t);a=a.map((t=>o(t).cmd));let l=!1;const c=[n.cmd].concat(a).filter((t=>!M.test(t)||(l=!0,!1)));0===c.length&&l&&c.push("$0"),l&&(n.cmd=c[0],a=c.slice(1),t=t.replace(M,n.cmd)),a.forEach((t=>{this.aliasMap[t]=n.cmd})),!1!==e&&this.usage.command(t,e,l,a,r),this.handlers[n.cmd]={original:t,description:e,handler:i,builder:s||{},middlewares:h,deprecated:r,demanded:n.demanded,optional:n.optional},l&&(this.defaultCommand=this.handlers[n.cmd])}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(t,e,s,i,n,r){const o=this.handlers[t]||this.handlers[this.aliasMap[t]]||this.defaultCommand,a=e.getInternalMethods().getContext(),h=a.commands.slice(),l=!t;t&&(a.commands.push(t),a.fullCommands.push(o.original));const c=this.applyBuilderUpdateUsageAndParse(l,o,e,s.aliases,h,i,n,r);return f(c)?c.then((t=>this.applyMiddlewareAndGetResult(l,o,t.innerArgv,a,n,t.aliases,e))):this.applyMiddlewareAndGetResult(l,o,c.innerArgv,a,n,c.aliases,e)}applyBuilderUpdateUsageAndParse(t,e,s,i,n,r,o,a){const h=e.builder;let l=s;if(x(h)){s.getInternalMethods().getUsageInstance().freeze();const c=h(s.getInternalMethods().reset(i),a);if(f(c))return c.then((i=>{var a;return l=(a=i)&&"function"==typeof a.getInternalMethods?i:s,this.parseAndUpdateUsage(t,e,l,n,r,o)}))}else(function(t){return"object"==typeof t})(h)&&(s.getInternalMethods().getUsageInstance().freeze(),l=s.getInternalMethods().reset(i),Object.keys(e.builder).forEach((t=>{l.option(t,h[t])})));return this.parseAndUpdateUsage(t,e,l,n,r,o)}parseAndUpdateUsage(t,e,s,i,n,r){t&&s.getInternalMethods().getUsageInstance().unfreeze(!0),this.shouldUpdateUsage(s)&&s.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(i,e),e.description);const o=s.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,n,r);return f(o)?o.then((t=>({aliases:s.parsed.aliases,innerArgv:t}))):{aliases:s.parsed.aliases,innerArgv:o}}shouldUpdateUsage(t){return!t.getInternalMethods().getUsageInstance().getUsageDisabled()&&0===t.getInternalMethods().getUsageInstance().getUsage().length}usageFromParentCommandsCommandHandler(t,e){const s=M.test(e.original)?e.original.replace(M,"").trim():e.original,i=t.filter((t=>!M.test(t)));return i.push(s),`$0 ${i.join(" ")}`}handleValidationAndGetResult(t,e,s,i,n,r,o,a){if(!r.getInternalMethods().getHasOutput()){const e=r.getInternalMethods().runValidation(n,a,r.parsed.error,t);s=j(s,(t=>(e(t),t)))}if(e.handler&&!r.getInternalMethods().getHasOutput()){r.getInternalMethods().setHasOutput();const i=!!r.getOptions().configuration["populate--"];r.getInternalMethods().postProcess(s,i,!1,!1),s=j(s=C(s,r,o,!1),(t=>{const s=e.handler(t);return f(s)?s.then((()=>t)):t})),t||r.getInternalMethods().getUsageInstance().cacheHelpMessage(),f(s)&&!r.getInternalMethods().hasParseCallback()&&s.catch((t=>{try{r.getInternalMethods().getUsageInstance().fail(null,t)}catch(t){}}))}return t||(i.commands.pop(),i.fullCommands.pop()),s}applyMiddlewareAndGetResult(t,e,s,i,n,r,o){let a={};if(n)return s;o.getInternalMethods().getHasOutput()||(a=this.populatePositionals(e,s,i,o));const h=this.globalMiddleware.getMiddleware().slice(0).concat(e.middlewares),l=C(s,o,h,!0);return f(l)?l.then((s=>this.handleValidationAndGetResult(t,e,s,i,r,o,h,a))):this.handleValidationAndGetResult(t,e,l,i,r,o,h,a)}populatePositionals(t,e,s,i){e._=e._.slice(s.commands.length);const n=t.demanded.slice(0),r=t.optional.slice(0),o={};for(this.validation.positionalCount(n.length,e._.length);n.length;){const t=n.shift();this.populatePositional(t,e,o)}for(;r.length;){const t=r.shift();this.populatePositional(t,e,o)}return e._=s.commands.concat(e._.map((t=>""+t))),this.postProcessPositionals(e,o,this.cmdToParseOptions(t.original),i),o}populatePositional(t,e,s){const i=t.cmd[0];t.variadic?s[i]=e._.splice(0).map(String):e._.length&&(s[i]=[String(e._.shift())])}cmdToParseOptions(t){const e={array:[],default:{},alias:{},demand:{}},s=o(t);return s.demanded.forEach((t=>{const[s,...i]=t.cmd;t.variadic&&(e.array.push(s),e.default[s]=[]),e.alias[s]=i,e.demand[s]=!0})),s.optional.forEach((t=>{const[s,...i]=t.cmd;t.variadic&&(e.array.push(s),e.default[s]=[]),e.alias[s]=i})),e}postProcessPositionals(t,e,s,i){const n=Object.assign({},i.getOptions());n.default=Object.assign(s.default,n.default);for(const t of Object.keys(s.alias))n.alias[t]=(n.alias[t]||[]).concat(s.alias[t]);n.array=n.array.concat(s.array),n.config={};const r=[];if(Object.keys(e).forEach((t=>{e[t].map((e=>{n.configuration["unknown-options-as-args"]&&(n.key[t]=!0),r.push(`--${t}`),r.push(e)}))})),!r.length)return;const o=Object.assign({},n.configuration,{"populate--":!1}),a=this.shim.Parser.detailed(r,Object.assign({},n,{configuration:o}));if(a.error)i.getInternalMethods().getUsageInstance().fail(a.error.message,a.error);else{const s=Object.keys(e);Object.keys(e).forEach((t=>{s.push(...a.aliases[t])})),Object.keys(a.argv).forEach((n=>{s.includes(n)&&(e[n]||(e[n]=a.argv[n]),!this.isInConfigs(i,n)&&!this.isDefaulted(i,n)&&Object.prototype.hasOwnProperty.call(t,n)&&Object.prototype.hasOwnProperty.call(a.argv,n)&&(Array.isArray(t[n])||Array.isArray(a.argv[n]))?t[n]=[].concat(t[n],a.argv[n]):t[n]=a.argv[n])}))}}isDefaulted(t,e){const{default:s}=t.getOptions();return Object.prototype.hasOwnProperty.call(s,e)||Object.prototype.hasOwnProperty.call(s,this.shim.Parser.camelCase(e))}isInConfigs(t,e){const{configObjects:s}=t.getOptions();return s.some((t=>Object.prototype.hasOwnProperty.call(t,e)))||s.some((t=>Object.prototype.hasOwnProperty.call(t,this.shim.Parser.camelCase(e))))}runDefaultBuilderOn(t){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(t)){const e=M.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,"$0 ");t.getInternalMethods().getUsageInstance().usage(e,this.defaultCommand.description)}const e=this.defaultCommand.builder;if(x(e))return e(t,!0);k(e)||Object.keys(e).forEach((s=>{t.option(s,e[s])}))}moduleName(t){const e=function(t){if("undefined"==typeof require)return null;for(let e,s=0,i=Object.keys(require.cache);s{const s=e;s._handle&&s.isTTY&&"function"==typeof s._handle.setBlocking&&s._handle.setBlocking(t)}))}function A(t){return"boolean"==typeof t}function P(t,s){const i=s.y18n.__,n={},r=[];n.failFn=function(t){r.push(t)};let o=null,a=null,h=!0;n.showHelpOnFail=function(e=!0,s){const[i,r]="string"==typeof e?[!0,e]:[e,s];return t.getInternalMethods().isGlobalContext()&&(a=r),o=r,h=i,n};let l=!1;n.fail=function(s,i){const c=t.getInternalMethods().getLoggerInstance();if(!r.length){if(t.getExitProcess()&&E(!0),!l){l=!0,h&&(t.showHelp("error"),c.error()),(s||i)&&c.error(s||i);const e=o||a;e&&((s||i)&&c.error(""),c.error(e))}if(i=i||new e(s),t.getExitProcess())return t.exit(1);if(t.getInternalMethods().hasParseCallback())return t.exit(1,i);throw i}for(let t=r.length-1;t>=0;--t){const e=r[t];if(A(e)){if(i)throw i;if(s)throw Error(s)}else e(s,i,n)}};let c=[],f=!1;n.usage=(t,e)=>null===t?(f=!0,c=[],n):(f=!1,c.push([t,e||""]),n),n.getUsage=()=>c,n.getUsageDisabled=()=>f,n.getPositionalGroupName=()=>i("Positionals:");let d=[];n.example=(t,e)=>{d.push([t,e||""])};let u=[];n.command=function(t,e,s,i,n=!1){s&&(u=u.map((t=>(t[2]=!1,t)))),u.push([t,e||"",s,i,n])},n.getCommands=()=>u;let p={};n.describe=function(t,e){Array.isArray(t)?t.forEach((t=>{n.describe(t,e)})):"object"==typeof t?Object.keys(t).forEach((e=>{n.describe(e,t[e])})):p[t]=e},n.getDescriptions=()=>p;let m=[];n.epilog=t=>{m.push(t)};let y,b=!1;n.wrap=t=>{b=!0,y=t},n.getWrap=()=>s.getEnv("YARGS_DISABLE_WRAP")?null:(b||(y=function(){const t=80;return s.process.stdColumns?Math.min(t,s.process.stdColumns):t}(),b=!0),y);const v="__yargsString__:";function O(t,e,i){let n=0;return Array.isArray(t)||(t=Object.values(t).map((t=>[t]))),t.forEach((t=>{n=Math.max(s.stringWidth(i?`${i} ${I(t[0])}`:I(t[0]))+$(t[0]),n)})),e&&(n=Math.min(n,parseInt((.5*e).toString(),10))),n}let w;function C(e){return t.getOptions().hiddenOptions.indexOf(e)<0||t.parsed.argv[t.getOptions().showHiddenOpt]}function j(t,e){let s=`[${i("default:")} `;if(void 0===t&&!e)return null;if(e)s+=e;else switch(typeof t){case"string":s+=`"${t}"`;break;case"object":s+=JSON.stringify(t);break;default:s+=t}return`${s}]`}n.deferY18nLookup=t=>v+t,n.help=function(){if(w)return w;!function(){const e=t.getDemandedOptions(),s=t.getOptions();(Object.keys(s.alias)||[]).forEach((i=>{s.alias[i].forEach((r=>{p[r]&&n.describe(i,p[r]),r in e&&t.demandOption(i,e[r]),s.boolean.includes(r)&&t.boolean(i),s.count.includes(r)&&t.count(i),s.string.includes(r)&&t.string(i),s.normalize.includes(r)&&t.normalize(i),s.array.includes(r)&&t.array(i),s.number.includes(r)&&t.number(i)}))}))}();const e=t.customScriptName?t.$0:s.path.basename(t.$0),r=t.getDemandedOptions(),o=t.getDemandedCommands(),a=t.getDeprecatedOptions(),h=t.getGroups(),l=t.getOptions();let g=[];g=g.concat(Object.keys(p)),g=g.concat(Object.keys(r)),g=g.concat(Object.keys(o)),g=g.concat(Object.keys(l.default)),g=g.filter(C),g=Object.keys(g.reduce(((t,e)=>("_"!==e&&(t[e]=!0),t)),{}));const y=n.getWrap(),b=s.cliui({width:y,wrap:!!y});if(!f)if(c.length)c.forEach((t=>{b.div({text:`${t[0].replace(/\$0/g,e)}`}),t[1]&&b.div({text:`${t[1]}`,padding:[1,0,0,0]})})),b.div();else if(u.length){let t=null;t=o._?`${e} <${i("command")}>\n`:`${e} [${i("command")}]\n`,b.div(`${t}`)}if(u.length>1||1===u.length&&!u[0][2]){b.div(i("Commands:"));const s=t.getInternalMethods().getContext(),n=s.commands.length?`${s.commands.join(" ")} `:"";!0===t.getInternalMethods().getParserConfiguration()["sort-commands"]&&(u=u.sort(((t,e)=>t[0].localeCompare(e[0]))));const r=e?`${e} `:"";u.forEach((t=>{const s=`${r}${n}${t[0].replace(/^\$0 ?/,"")}`;b.span({text:s,padding:[0,2,0,2],width:O(u,y,`${e}${n}`)+4},{text:t[1]});const o=[];t[2]&&o.push(`[${i("default")}]`),t[3]&&t[3].length&&o.push(`[${i("aliases:")} ${t[3].join(", ")}]`),t[4]&&("string"==typeof t[4]?o.push(`[${i("deprecated: %s",t[4])}]`):o.push(`[${i("deprecated")}]`)),o.length?b.div({text:o.join(" "),padding:[0,0,0,2],align:"right"}):b.div()})),b.div()}const M=(Object.keys(l.alias)||[]).concat(Object.keys(t.parsed.newAliases)||[]);g=g.filter((e=>!t.parsed.newAliases[e]&&M.every((t=>-1===(l.alias[t]||[]).indexOf(e)))));const _=i("Options:");h[_]||(h[_]=[]),function(t,e,s,i){let n=[],r=null;Object.keys(s).forEach((t=>{n=n.concat(s[t])})),t.forEach((t=>{r=[t].concat(e[t]),r.some((t=>-1!==n.indexOf(t)))||s[i].push(t)}))}(g,l.alias,h,_);const k=t=>/^--/.test(I(t)),x=Object.keys(h).filter((t=>h[t].length>0)).map((t=>({groupName:t,normalizedKeys:h[t].filter(C).map((t=>{if(M.includes(t))return t;for(let e,s=0;void 0!==(e=M[s]);s++)if((l.alias[e]||[]).includes(t))return e;return t}))}))).filter((({normalizedKeys:t})=>t.length>0)).map((({groupName:t,normalizedKeys:e})=>{const s=e.reduce(((e,s)=>(e[s]=[s].concat(l.alias[s]||[]).map((e=>t===n.getPositionalGroupName()?e:(/^[0-9]$/.test(e)?l.boolean.includes(s)?"-":"--":e.length>1?"--":"-")+e)).sort(((t,e)=>k(t)===k(e)?0:k(t)?1:-1)).join(", "),e)),{});return{groupName:t,normalizedKeys:e,switches:s}}));if(x.filter((({groupName:t})=>t!==n.getPositionalGroupName())).some((({normalizedKeys:t,switches:e})=>!t.every((t=>k(e[t])))))&&x.filter((({groupName:t})=>t!==n.getPositionalGroupName())).forEach((({normalizedKeys:t,switches:e})=>{t.forEach((t=>{var s,i;k(e[t])&&(e[t]=(s=e[t],i=4,S(s)?{text:s.text,indentation:s.indentation+i}:{text:s,indentation:i}))}))})),x.forEach((({groupName:e,normalizedKeys:s,switches:o})=>{b.div(e),s.forEach((e=>{const s=o[e];let h=p[e]||"",c=null;h.includes(v)&&(h=i(h.substring(16))),l.boolean.includes(e)&&(c=`[${i("boolean")}]`),l.count.includes(e)&&(c=`[${i("count")}]`),l.string.includes(e)&&(c=`[${i("string")}]`),l.normalize.includes(e)&&(c=`[${i("string")}]`),l.array.includes(e)&&(c=`[${i("array")}]`),l.number.includes(e)&&(c=`[${i("number")}]`);const f=[e in a?(d=a[e],"string"==typeof d?`[${i("deprecated: %s",d)}]`:`[${i("deprecated")}]`):null,c,e in r?`[${i("required")}]`:null,l.choices&&l.choices[e]?`[${i("choices:")} ${n.stringifiedValues(l.choices[e])}]`:null,j(l.default[e],l.defaultDescription[e])].filter(Boolean).join(" ");var d;b.span({text:I(s),padding:[0,2,0,2+$(s)],width:O(o,y)+4},h);const u=!0===t.getInternalMethods().getUsageConfiguration()["hide-types"];f&&!u?b.div({text:f,padding:[0,0,0,2],align:"right"}):b.div()})),b.div()})),d.length&&(b.div(i("Examples:")),d.forEach((t=>{t[0]=t[0].replace(/\$0/g,e)})),d.forEach((t=>{""===t[1]?b.div({text:t[0],padding:[0,2,0,2]}):b.div({text:t[0],padding:[0,2,0,2],width:O(d,y)+4},{text:t[1]})})),b.div()),m.length>0){const t=m.map((t=>t.replace(/\$0/g,e))).join("\n");b.div(`${t}\n`)}return b.toString().replace(/\s*$/,"")},n.cacheHelpMessage=function(){w=this.help()},n.clearCachedHelpMessage=function(){w=void 0},n.hasCachedHelpMessage=function(){return!!w},n.showHelp=e=>{const s=t.getInternalMethods().getLoggerInstance();e||(e="error");("function"==typeof e?e:s[e])(n.help())},n.functionDescription=t=>["(",t.name?s.Parser.decamelize(t.name,"-"):i("generated-value"),")"].join(""),n.stringifiedValues=function(t,e){let s="";const i=e||", ",n=[].concat(t);return t&&n.length?(n.forEach((t=>{s.length&&(s+=i),s+=JSON.stringify(t)})),s):s};let M=null;n.version=t=>{M=t},n.showVersion=e=>{const s=t.getInternalMethods().getLoggerInstance();e||(e="error");("function"==typeof e?e:s[e])(M)},n.reset=function(t){return o=null,l=!1,c=[],f=!1,m=[],d=[],u=[],p=g(p,(e=>!t[e])),n};const _=[];return n.freeze=function(){_.push({failMessage:o,failureOutput:l,usages:c,usageDisabled:f,epilogs:m,examples:d,commands:u,descriptions:p})},n.unfreeze=function(t=!1){const e=_.pop();e&&(t?(p={...e.descriptions,...p},u=[...e.commands,...u],c=[...e.usages,...c],d=[...e.examples,...d],m=[...e.epilogs,...m]):({failMessage:o,failureOutput:l,usages:c,usageDisabled:f,epilogs:m,examples:d,commands:u,descriptions:p}=e))},n}function S(t){return"object"==typeof t}function $(t){return S(t)?t.indentation:0}function I(t){return S(t)?t.text:t}class D{constructor(t,e,s,i){var n,r,o;this.yargs=t,this.usage=e,this.command=s,this.shim=i,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=null!==(o=(null===(n=this.shim.getEnv("SHELL"))||void 0===n?void 0:n.includes("zsh"))||(null===(r=this.shim.getEnv("ZSH_NAME"))||void 0===r?void 0:r.includes("zsh")))&&void 0!==o&&o}defaultCompletion(t,e,s,i){const n=this.command.getCommandHandlers();for(let e=0,s=t.length;e{const i=o(s[0]).cmd;if(-1===e.indexOf(i))if(this.zshShell){const e=s[1]||"";t.push(i.replace(/:/g,"\\:")+":"+e)}else t.push(i)}))}optionCompletions(t,e,s,i){if((i.match(/^-/)||""===i&&0===t.length)&&!this.previousArgHasChoices(e)){const s=this.yargs.getOptions(),n=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(s.key).forEach((r=>{const o=!!s.configuration["boolean-negation"]&&s.boolean.includes(r);n.includes(r)||s.hiddenOptions.includes(r)||this.argsContainKey(e,r,o)||this.completeOptionKey(r,t,i,o&&!!s.default[r])}))}}choicesFromOptionsCompletions(t,e,s,i){if(this.previousArgHasChoices(e)){const s=this.getPreviousArgChoices(e);s&&s.length>0&&t.push(...s.map((t=>t.replace(/:/g,"\\:"))))}}choicesFromPositionalsCompletions(t,e,s,i){if(""===i&&t.length>0&&this.previousArgHasChoices(e))return;const n=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],r=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),o=n[s._.length-r-1];if(!o)return;const a=this.yargs.getOptions().choices[o]||[];for(const e of a)e.startsWith(i)&&t.push(e.replace(/:/g,"\\:"))}getPreviousArgChoices(t){if(t.length<1)return;let e=t[t.length-1],s="";if(!e.startsWith("-")&&t.length>1&&(s=e,e=t[t.length-2]),!e.startsWith("-"))return;const i=e.replace(/^-+/,""),n=this.yargs.getOptions(),r=[i,...this.yargs.getAliases()[i]||[]];let o;for(const t of r)if(Object.prototype.hasOwnProperty.call(n.key,t)&&Array.isArray(n.choices[t])){o=n.choices[t];break}return o?o.filter((t=>!s||t.startsWith(s))):void 0}previousArgHasChoices(t){const e=this.getPreviousArgChoices(t);return void 0!==e&&e.length>0}argsContainKey(t,e,s){const i=e=>-1!==t.indexOf((/^[^0-9]$/.test(e)?"-":"--")+e);if(i(e))return!0;if(s&&i(`no-${e}`))return!0;if(this.aliases)for(const t of this.aliases[e])if(i(t))return!0;return!1}completeOptionKey(t,e,s,i){var n,r,o,a;let h=t;if(this.zshShell){const e=this.usage.getDescriptions(),s=null===(r=null===(n=null==this?void 0:this.aliases)||void 0===n?void 0:n[t])||void 0===r?void 0:r.find((t=>{const s=e[t];return"string"==typeof s&&s.length>0})),i=s?e[s]:void 0,l=null!==(a=null!==(o=e[t])&&void 0!==o?o:i)&&void 0!==a?a:"";h=`${t.replace(/:/g,"\\:")}:${l.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}const l=!/^--/.test(s)&&(t=>/^[^0-9]$/.test(t))(t)?"-":"--";e.push(l+h),i&&e.push(l+"no-"+h)}customCompletion(t,e,s,i){if(d(this.customCompletionFunction,null,this.shim),this.customCompletionFunction.length<3){const t=this.customCompletionFunction(s,e);return f(t)?t.then((t=>{this.shim.process.nextTick((()=>{i(null,t)}))})).catch((t=>{this.shim.process.nextTick((()=>{i(t,void 0)}))})):i(null,t)}return function(t){return t.length>3}(this.customCompletionFunction)?this.customCompletionFunction(s,e,((n=i)=>this.defaultCompletion(t,e,s,n)),(t=>{i(null,t)})):this.customCompletionFunction(s,e,(t=>{i(null,t)}))}getCompletion(t,e){const s=t.length?t[t.length-1]:"",i=this.yargs.parse(t,!0),n=this.customCompletionFunction?i=>this.customCompletion(t,i,s,e):i=>this.defaultCompletion(t,i,s,e);return f(i)?i.then(n):n(i)}generateCompletionScript(t,e){let s=this.zshShell?'#compdef {{app_name}}\n###-begin-{{app_name}}-completions-###\n#\n# yargs command completion script\n#\n# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc\n# or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX.\n#\n_{{app_name}}_yargs_completions()\n{\n local reply\n local si=$IFS\n IFS=$\'\n\' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "${words[@]}"))\n IFS=$si\n _describe \'values\' reply\n}\ncompdef _{{app_name}}_yargs_completions {{app_name}}\n###-end-{{app_name}}-completions-###\n':'###-begin-{{app_name}}-completions-###\n#\n# yargs command completion script\n#\n# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc\n# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.\n#\n_{{app_name}}_yargs_completions()\n{\n local cur_word args type_list\n\n cur_word="${COMP_WORDS[COMP_CWORD]}"\n args=("${COMP_WORDS[@]}")\n\n # ask yargs to generate completions.\n type_list=$({{app_path}} --get-yargs-completions "${args[@]}")\n\n COMPREPLY=( $(compgen -W "${type_list}" -- ${cur_word}) )\n\n # if no match was found, fall back to filename completion\n if [ ${#COMPREPLY[@]} -eq 0 ]; then\n COMPREPLY=()\n fi\n\n return 0\n}\ncomplete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}\n###-end-{{app_name}}-completions-###\n';const i=this.shim.path.basename(t);return t.match(/\.js$/)&&(t=`./${t}`),s=s.replace(/{{app_name}}/g,i),s=s.replace(/{{completion_command}}/g,e),s.replace(/{{app_path}}/g,t)}registerFunction(t){this.customCompletionFunction=t}setParsed(t){this.aliases=t.aliases}}function N(t,e){if(0===t.length)return e.length;if(0===e.length)return t.length;const s=[];let i,n;for(i=0;i<=e.length;i++)s[i]=[i];for(n=0;n<=t.length;n++)s[0][n]=n;for(i=1;i<=e.length;i++)for(n=1;n<=t.length;n++)e.charAt(i-1)===t.charAt(n-1)?s[i][n]=s[i-1][n-1]:i>1&&n>1&&e.charAt(i-2)===t.charAt(n-1)&&e.charAt(i-1)===t.charAt(n-2)?s[i][n]=s[i-2][n-2]+1:s[i][n]=Math.min(s[i-1][n-1]+1,Math.min(s[i][n-1]+1,s[i-1][n]+1));return s[e.length][t.length]}const H=["$0","--","_"];var z,W,q,U,F,L,V,G,R,T,B,Y,K,J,Z,X,Q,tt,et,st,it,nt,rt,ot,at,ht,lt,ct,ft,dt,ut,pt,gt,mt,yt;const bt=Symbol("copyDoubleDash"),vt=Symbol("copyDoubleDash"),Ot=Symbol("deleteFromParserHintObject"),wt=Symbol("emitWarning"),Ct=Symbol("freeze"),jt=Symbol("getDollarZero"),Mt=Symbol("getParserConfiguration"),_t=Symbol("getUsageConfiguration"),kt=Symbol("guessLocale"),xt=Symbol("guessVersion"),Et=Symbol("parsePositionalNumbers"),At=Symbol("pkgUp"),Pt=Symbol("populateParserHintArray"),St=Symbol("populateParserHintSingleValueDictionary"),$t=Symbol("populateParserHintArrayDictionary"),It=Symbol("populateParserHintDictionary"),Dt=Symbol("sanitizeKey"),Nt=Symbol("setKey"),Ht=Symbol("unfreeze"),zt=Symbol("validateAsync"),Wt=Symbol("getCommandInstance"),qt=Symbol("getContext"),Ut=Symbol("getHasOutput"),Ft=Symbol("getLoggerInstance"),Lt=Symbol("getParseContext"),Vt=Symbol("getUsageInstance"),Gt=Symbol("getValidationInstance"),Rt=Symbol("hasParseCallback"),Tt=Symbol("isGlobalContext"),Bt=Symbol("postProcess"),Yt=Symbol("rebase"),Kt=Symbol("reset"),Jt=Symbol("runYargsParserAndExecuteCommands"),Zt=Symbol("runValidation"),Xt=Symbol("setHasOutput"),Qt=Symbol("kTrackManuallySetKeys");class te{constructor(t=[],e,s,i){this.customScriptName=!1,this.parsed=!1,z.set(this,void 0),W.set(this,void 0),q.set(this,{commands:[],fullCommands:[]}),U.set(this,null),F.set(this,null),L.set(this,"show-hidden"),V.set(this,null),G.set(this,!0),R.set(this,{}),T.set(this,!0),B.set(this,[]),Y.set(this,void 0),K.set(this,{}),J.set(this,!1),Z.set(this,null),X.set(this,!0),Q.set(this,void 0),tt.set(this,""),et.set(this,void 0),st.set(this,void 0),it.set(this,{}),nt.set(this,null),rt.set(this,null),ot.set(this,{}),at.set(this,{}),ht.set(this,void 0),lt.set(this,!1),ct.set(this,void 0),ft.set(this,!1),dt.set(this,!1),ut.set(this,!1),pt.set(this,void 0),gt.set(this,{}),mt.set(this,null),yt.set(this,void 0),O(this,ct,i,"f"),O(this,ht,t,"f"),O(this,W,e,"f"),O(this,st,s,"f"),O(this,Y,new w(this),"f"),this.$0=this[jt](),this[Kt](),O(this,z,v(this,z,"f"),"f"),O(this,pt,v(this,pt,"f"),"f"),O(this,yt,v(this,yt,"f"),"f"),O(this,et,v(this,et,"f"),"f"),v(this,et,"f").showHiddenOpt=v(this,L,"f"),O(this,Q,this[vt](),"f")}addHelpOpt(t,e){return h("[string|boolean] [string]",[t,e],arguments.length),v(this,Z,"f")&&(this[Ot](v(this,Z,"f")),O(this,Z,null,"f")),!1===t&&void 0===e||(O(this,Z,"string"==typeof t?t:"help","f"),this.boolean(v(this,Z,"f")),this.describe(v(this,Z,"f"),e||v(this,pt,"f").deferY18nLookup("Show help"))),this}help(t,e){return this.addHelpOpt(t,e)}addShowHiddenOpt(t,e){if(h("[string|boolean] [string]",[t,e],arguments.length),!1===t&&void 0===e)return this;const s="string"==typeof t?t:v(this,L,"f");return this.boolean(s),this.describe(s,e||v(this,pt,"f").deferY18nLookup("Show hidden options")),v(this,et,"f").showHiddenOpt=s,this}showHidden(t,e){return this.addShowHiddenOpt(t,e)}alias(t,e){return h(" [string|array]",[t,e],arguments.length),this[$t](this.alias.bind(this),"alias",t,e),this}array(t){return h("",[t],arguments.length),this[Pt]("array",t),this[Qt](t),this}boolean(t){return h("",[t],arguments.length),this[Pt]("boolean",t),this[Qt](t),this}check(t,e){return h(" [boolean]",[t,e],arguments.length),this.middleware(((e,s)=>j((()=>t(e,s.getOptions())),(s=>(s?("string"==typeof s||s instanceof Error)&&v(this,pt,"f").fail(s.toString(),s):v(this,pt,"f").fail(v(this,ct,"f").y18n.__("Argument check failed: %s",t.toString())),e)),(t=>(v(this,pt,"f").fail(t.message?t.message:t.toString(),t),e)))),!1,e),this}choices(t,e){return h(" [string|array]",[t,e],arguments.length),this[$t](this.choices.bind(this),"choices",t,e),this}coerce(t,s){if(h(" [function]",[t,s],arguments.length),Array.isArray(t)){if(!s)throw new e("coerce callback must be provided");for(const e of t)this.coerce(e,s);return this}if("object"==typeof t){for(const e of Object.keys(t))this.coerce(e,t[e]);return this}if(!s)throw new e("coerce callback must be provided");return v(this,et,"f").key[t]=!0,v(this,Y,"f").addCoerceMiddleware(((i,n)=>{let r;return Object.prototype.hasOwnProperty.call(i,t)?j((()=>(r=n.getAliases(),s(i[t]))),(e=>{i[t]=e;const s=n.getInternalMethods().getParserConfiguration()["strip-aliased"];if(r[t]&&!0!==s)for(const s of r[t])i[s]=e;return i}),(t=>{throw new e(t.message)})):i}),t),this}conflicts(t,e){return h(" [string|array]",[t,e],arguments.length),v(this,yt,"f").conflicts(t,e),this}config(t="config",e,s){return h("[object|string] [string|function] [function]",[t,e,s],arguments.length),"object"!=typeof t||Array.isArray(t)?("function"==typeof e&&(s=e,e=void 0),this.describe(t,e||v(this,pt,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(t)?t:[t]).forEach((t=>{v(this,et,"f").config[t]=s||!0})),this):(t=n(t,v(this,W,"f"),this[Mt]()["deep-merge-config"]||!1,v(this,ct,"f")),v(this,et,"f").configObjects=(v(this,et,"f").configObjects||[]).concat(t),this)}completion(t,e,s){return h("[string] [string|boolean|function] [function]",[t,e,s],arguments.length),"function"==typeof e&&(s=e,e=void 0),O(this,F,t||v(this,F,"f")||"completion","f"),e||!1===e||(e="generate completion script"),this.command(v(this,F,"f"),e),s&&v(this,U,"f").registerFunction(s),this}command(t,e,s,i,n,r){return h(" [string|boolean] [function|object] [function] [array] [boolean|string]",[t,e,s,i,n,r],arguments.length),v(this,z,"f").addHandler(t,e,s,i,n,r),this}commands(t,e,s,i,n,r){return this.command(t,e,s,i,n,r)}commandDir(t,e){h(" [object]",[t,e],arguments.length);const s=v(this,st,"f")||v(this,ct,"f").require;return v(this,z,"f").addDirectory(t,s,v(this,ct,"f").getCallerFile(),e),this}count(t){return h("",[t],arguments.length),this[Pt]("count",t),this[Qt](t),this}default(t,e,s){return h(" [*] [string]",[t,e,s],arguments.length),s&&(u(t,v(this,ct,"f")),v(this,et,"f").defaultDescription[t]=s),"function"==typeof e&&(u(t,v(this,ct,"f")),v(this,et,"f").defaultDescription[t]||(v(this,et,"f").defaultDescription[t]=v(this,pt,"f").functionDescription(e)),e=e.call()),this[St](this.default.bind(this),"default",t,e),this}defaults(t,e,s){return this.default(t,e,s)}demandCommand(t=1,e,s,i){return h("[number] [number|string] [string|null|undefined] [string|null|undefined]",[t,e,s,i],arguments.length),"number"!=typeof e&&(s=e,e=1/0),this.global("_",!1),v(this,et,"f").demandedCommands._={min:t,max:e,minMsg:s,maxMsg:i},this}demand(t,e,s){return Array.isArray(e)?(e.forEach((t=>{d(s,!0,v(this,ct,"f")),this.demandOption(t,s)})),e=1/0):"number"!=typeof e&&(s=e,e=1/0),"number"==typeof t?(d(s,!0,v(this,ct,"f")),this.demandCommand(t,e,s,s)):Array.isArray(t)?t.forEach((t=>{d(s,!0,v(this,ct,"f")),this.demandOption(t,s)})):"string"==typeof s?this.demandOption(t,s):!0!==s&&void 0!==s||this.demandOption(t),this}demandOption(t,e){return h(" [string]",[t,e],arguments.length),this[St](this.demandOption.bind(this),"demandedOptions",t,e),this}deprecateOption(t,e){return h(" [string|boolean]",[t,e],arguments.length),v(this,et,"f").deprecatedOptions[t]=e,this}describe(t,e){return h(" [string]",[t,e],arguments.length),this[Nt](t,!0),v(this,pt,"f").describe(t,e),this}detectLocale(t){return h("",[t],arguments.length),O(this,G,t,"f"),this}env(t){return h("[string|boolean]",[t],arguments.length),!1===t?delete v(this,et,"f").envPrefix:v(this,et,"f").envPrefix=t||"",this}epilogue(t){return h("",[t],arguments.length),v(this,pt,"f").epilog(t),this}epilog(t){return this.epilogue(t)}example(t,e){return h(" [string]",[t,e],arguments.length),Array.isArray(t)?t.forEach((t=>this.example(...t))):v(this,pt,"f").example(t,e),this}exit(t,e){O(this,J,!0,"f"),O(this,V,e,"f"),v(this,T,"f")&&v(this,ct,"f").process.exit(t)}exitProcess(t=!0){return h("[boolean]",[t],arguments.length),O(this,T,t,"f"),this}fail(t){if(h("",[t],arguments.length),"boolean"==typeof t&&!1!==t)throw new e("Invalid first argument. Expected function or boolean 'false'");return v(this,pt,"f").failFn(t),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(t,e){return h(" [function]",[t,e],arguments.length),e?v(this,U,"f").getCompletion(t,e):new Promise(((e,s)=>{v(this,U,"f").getCompletion(t,((t,i)=>{t?s(t):e(i)}))}))}getDemandedOptions(){return h([],0),v(this,et,"f").demandedOptions}getDemandedCommands(){return h([],0),v(this,et,"f").demandedCommands}getDeprecatedOptions(){return h([],0),v(this,et,"f").deprecatedOptions}getDetectLocale(){return v(this,G,"f")}getExitProcess(){return v(this,T,"f")}getGroups(){return Object.assign({},v(this,K,"f"),v(this,at,"f"))}getHelp(){if(O(this,J,!0,"f"),!v(this,pt,"f").hasCachedHelpMessage()){if(!this.parsed){const t=this[Jt](v(this,ht,"f"),void 0,void 0,0,!0);if(f(t))return t.then((()=>v(this,pt,"f").help()))}const t=v(this,z,"f").runDefaultBuilderOn(this);if(f(t))return t.then((()=>v(this,pt,"f").help()))}return Promise.resolve(v(this,pt,"f").help())}getOptions(){return v(this,et,"f")}getStrict(){return v(this,ft,"f")}getStrictCommands(){return v(this,dt,"f")}getStrictOptions(){return v(this,ut,"f")}global(t,e){return h(" [boolean]",[t,e],arguments.length),t=[].concat(t),!1!==e?v(this,et,"f").local=v(this,et,"f").local.filter((e=>-1===t.indexOf(e))):t.forEach((t=>{v(this,et,"f").local.includes(t)||v(this,et,"f").local.push(t)})),this}group(t,e){h(" ",[t,e],arguments.length);const s=v(this,at,"f")[e]||v(this,K,"f")[e];v(this,at,"f")[e]&&delete v(this,at,"f")[e];const i={};return v(this,K,"f")[e]=(s||[]).concat(t).filter((t=>!i[t]&&(i[t]=!0))),this}hide(t){return h("",[t],arguments.length),v(this,et,"f").hiddenOptions.push(t),this}implies(t,e){return h(" [number|string|array]",[t,e],arguments.length),v(this,yt,"f").implies(t,e),this}locale(t){return h("[string]",[t],arguments.length),void 0===t?(this[kt](),v(this,ct,"f").y18n.getLocale()):(O(this,G,!1,"f"),v(this,ct,"f").y18n.setLocale(t),this)}middleware(t,e,s){return v(this,Y,"f").addMiddleware(t,!!e,s)}nargs(t,e){return h(" [number]",[t,e],arguments.length),this[St](this.nargs.bind(this),"narg",t,e),this}normalize(t){return h("",[t],arguments.length),this[Pt]("normalize",t),this}number(t){return h("",[t],arguments.length),this[Pt]("number",t),this[Qt](t),this}option(t,e){if(h(" [object]",[t,e],arguments.length),"object"==typeof t)Object.keys(t).forEach((e=>{this.options(e,t[e])}));else{"object"!=typeof e&&(e={}),this[Qt](t),!v(this,mt,"f")||"version"!==t&&"version"!==(null==e?void 0:e.alias)||this[wt](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join("\n"),void 0,"versionWarning"),v(this,et,"f").key[t]=!0,e.alias&&this.alias(t,e.alias);const s=e.deprecate||e.deprecated;s&&this.deprecateOption(t,s);const i=e.demand||e.required||e.require;i&&this.demand(t,i),e.demandOption&&this.demandOption(t,"string"==typeof e.demandOption?e.demandOption:void 0),e.conflicts&&this.conflicts(t,e.conflicts),"default"in e&&this.default(t,e.default),void 0!==e.implies&&this.implies(t,e.implies),void 0!==e.nargs&&this.nargs(t,e.nargs),e.config&&this.config(t,e.configParser),e.normalize&&this.normalize(t),e.choices&&this.choices(t,e.choices),e.coerce&&this.coerce(t,e.coerce),e.group&&this.group(t,e.group),(e.boolean||"boolean"===e.type)&&(this.boolean(t),e.alias&&this.boolean(e.alias)),(e.array||"array"===e.type)&&(this.array(t),e.alias&&this.array(e.alias)),(e.number||"number"===e.type)&&(this.number(t),e.alias&&this.number(e.alias)),(e.string||"string"===e.type)&&(this.string(t),e.alias&&this.string(e.alias)),(e.count||"count"===e.type)&&this.count(t),"boolean"==typeof e.global&&this.global(t,e.global),e.defaultDescription&&(v(this,et,"f").defaultDescription[t]=e.defaultDescription),e.skipValidation&&this.skipValidation(t);const n=e.describe||e.description||e.desc,r=v(this,pt,"f").getDescriptions();Object.prototype.hasOwnProperty.call(r,t)&&"string"!=typeof n||this.describe(t,n),e.hidden&&this.hide(t),e.requiresArg&&this.requiresArg(t)}return this}options(t,e){return this.option(t,e)}parse(t,e,s){h("[string|array] [function|boolean|object] [function]",[t,e,s],arguments.length),this[Ct](),void 0===t&&(t=v(this,ht,"f")),"object"==typeof e&&(O(this,rt,e,"f"),e=s),"function"==typeof e&&(O(this,nt,e,"f"),e=!1),e||O(this,ht,t,"f"),v(this,nt,"f")&&O(this,T,!1,"f");const i=this[Jt](t,!!e),n=this.parsed;return v(this,U,"f").setParsed(this.parsed),f(i)?i.then((t=>(v(this,nt,"f")&&v(this,nt,"f").call(this,v(this,V,"f"),t,v(this,tt,"f")),t))).catch((t=>{throw v(this,nt,"f")&&v(this,nt,"f")(t,this.parsed.argv,v(this,tt,"f")),t})).finally((()=>{this[Ht](),this.parsed=n})):(v(this,nt,"f")&&v(this,nt,"f").call(this,v(this,V,"f"),i,v(this,tt,"f")),this[Ht](),this.parsed=n,i)}parseAsync(t,e,s){const i=this.parse(t,e,s);return f(i)?i:Promise.resolve(i)}parseSync(t,s,i){const n=this.parse(t,s,i);if(f(n))throw new e(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return n}parserConfiguration(t){return h("",[t],arguments.length),O(this,it,t,"f"),this}pkgConf(t,e){h(" [string]",[t,e],arguments.length);let s=null;const i=this[At](e||v(this,W,"f"));return i[t]&&"object"==typeof i[t]&&(s=n(i[t],e||v(this,W,"f"),this[Mt]()["deep-merge-config"]||!1,v(this,ct,"f")),v(this,et,"f").configObjects=(v(this,et,"f").configObjects||[]).concat(s)),this}positional(t,e){h(" ",[t,e],arguments.length);const s=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];e=g(e,((t,e)=>!("type"===t&&!["string","number","boolean"].includes(e))&&s.includes(t)));const i=v(this,q,"f").fullCommands[v(this,q,"f").fullCommands.length-1],n=i?v(this,z,"f").cmdToParseOptions(i):{array:[],alias:{},default:{},demand:{}};return p(n).forEach((s=>{const i=n[s];Array.isArray(i)?-1!==i.indexOf(t)&&(e[s]=!0):i[t]&&!(s in e)&&(e[s]=i[t])})),this.group(t,v(this,pt,"f").getPositionalGroupName()),this.option(t,e)}recommendCommands(t=!0){return h("[boolean]",[t],arguments.length),O(this,lt,t,"f"),this}required(t,e,s){return this.demand(t,e,s)}require(t,e,s){return this.demand(t,e,s)}requiresArg(t){return h(" [number]",[t],arguments.length),"string"==typeof t&&v(this,et,"f").narg[t]||this[St](this.requiresArg.bind(this),"narg",t,NaN),this}showCompletionScript(t,e){return h("[string] [string]",[t,e],arguments.length),t=t||this.$0,v(this,Q,"f").log(v(this,U,"f").generateCompletionScript(t,e||v(this,F,"f")||"completion")),this}showHelp(t){if(h("[string|function]",[t],arguments.length),O(this,J,!0,"f"),!v(this,pt,"f").hasCachedHelpMessage()){if(!this.parsed){const e=this[Jt](v(this,ht,"f"),void 0,void 0,0,!0);if(f(e))return e.then((()=>{v(this,pt,"f").showHelp(t)})),this}const e=v(this,z,"f").runDefaultBuilderOn(this);if(f(e))return e.then((()=>{v(this,pt,"f").showHelp(t)})),this}return v(this,pt,"f").showHelp(t),this}scriptName(t){return this.customScriptName=!0,this.$0=t,this}showHelpOnFail(t,e){return h("[boolean|string] [string]",[t,e],arguments.length),v(this,pt,"f").showHelpOnFail(t,e),this}showVersion(t){return h("[string|function]",[t],arguments.length),v(this,pt,"f").showVersion(t),this}skipValidation(t){return h("",[t],arguments.length),this[Pt]("skipValidation",t),this}strict(t){return h("[boolean]",[t],arguments.length),O(this,ft,!1!==t,"f"),this}strictCommands(t){return h("[boolean]",[t],arguments.length),O(this,dt,!1!==t,"f"),this}strictOptions(t){return h("[boolean]",[t],arguments.length),O(this,ut,!1!==t,"f"),this}string(t){return h("",[t],arguments.length),this[Pt]("string",t),this[Qt](t),this}terminalWidth(){return h([],0),v(this,ct,"f").process.stdColumns}updateLocale(t){return this.updateStrings(t)}updateStrings(t){return h("",[t],arguments.length),O(this,G,!1,"f"),v(this,ct,"f").y18n.updateLocale(t),this}usage(t,s,i,n){if(h(" [string|boolean] [function|object] [function]",[t,s,i,n],arguments.length),void 0!==s){if(d(t,null,v(this,ct,"f")),(t||"").match(/^\$0( |$)/))return this.command(t,s,i,n);throw new e(".usage() description must start with $0 if being used as alias for .command()")}return v(this,pt,"f").usage(t),this}usageConfiguration(t){return h("",[t],arguments.length),O(this,gt,t,"f"),this}version(t,e,s){const i="version";if(h("[boolean|string] [string] [string]",[t,e,s],arguments.length),v(this,mt,"f")&&(this[Ot](v(this,mt,"f")),v(this,pt,"f").version(void 0),O(this,mt,null,"f")),0===arguments.length)s=this[xt](),t=i;else if(1===arguments.length){if(!1===t)return this;s=t,t=i}else 2===arguments.length&&(s=e,e=void 0);return O(this,mt,"string"==typeof t?t:i,"f"),e=e||v(this,pt,"f").deferY18nLookup("Show version number"),v(this,pt,"f").version(s||void 0),this.boolean(v(this,mt,"f")),this.describe(v(this,mt,"f"),e),this}wrap(t){return h("",[t],arguments.length),v(this,pt,"f").wrap(t),this}[(z=new WeakMap,W=new WeakMap,q=new WeakMap,U=new WeakMap,F=new WeakMap,L=new WeakMap,V=new WeakMap,G=new WeakMap,R=new WeakMap,T=new WeakMap,B=new WeakMap,Y=new WeakMap,K=new WeakMap,J=new WeakMap,Z=new WeakMap,X=new WeakMap,Q=new WeakMap,tt=new WeakMap,et=new WeakMap,st=new WeakMap,it=new WeakMap,nt=new WeakMap,rt=new WeakMap,ot=new WeakMap,at=new WeakMap,ht=new WeakMap,lt=new WeakMap,ct=new WeakMap,ft=new WeakMap,dt=new WeakMap,ut=new WeakMap,pt=new WeakMap,gt=new WeakMap,mt=new WeakMap,yt=new WeakMap,bt)](t){if(!t._||!t["--"])return t;t._.push.apply(t._,t["--"]);try{delete t["--"]}catch(t){}return t}[vt](){return{log:(...t)=>{this[Rt]()||console.log(...t),O(this,J,!0,"f"),v(this,tt,"f").length&&O(this,tt,v(this,tt,"f")+"\n","f"),O(this,tt,v(this,tt,"f")+t.join(" "),"f")},error:(...t)=>{this[Rt]()||console.error(...t),O(this,J,!0,"f"),v(this,tt,"f").length&&O(this,tt,v(this,tt,"f")+"\n","f"),O(this,tt,v(this,tt,"f")+t.join(" "),"f")}}}[Ot](t){p(v(this,et,"f")).forEach((e=>{if("configObjects"===e)return;const s=v(this,et,"f")[e];Array.isArray(s)?s.includes(t)&&s.splice(s.indexOf(t),1):"object"==typeof s&&delete s[t]})),delete v(this,pt,"f").getDescriptions()[t]}[wt](t,e,s){v(this,R,"f")[s]||(v(this,ct,"f").process.emitWarning(t,e),v(this,R,"f")[s]=!0)}[Ct](){v(this,B,"f").push({options:v(this,et,"f"),configObjects:v(this,et,"f").configObjects.slice(0),exitProcess:v(this,T,"f"),groups:v(this,K,"f"),strict:v(this,ft,"f"),strictCommands:v(this,dt,"f"),strictOptions:v(this,ut,"f"),completionCommand:v(this,F,"f"),output:v(this,tt,"f"),exitError:v(this,V,"f"),hasOutput:v(this,J,"f"),parsed:this.parsed,parseFn:v(this,nt,"f"),parseContext:v(this,rt,"f")}),v(this,pt,"f").freeze(),v(this,yt,"f").freeze(),v(this,z,"f").freeze(),v(this,Y,"f").freeze()}[jt](){let t,e="";return t=/\b(node|iojs|electron)(\.exe)?$/.test(v(this,ct,"f").process.argv()[0])?v(this,ct,"f").process.argv().slice(1,2):v(this,ct,"f").process.argv().slice(0,1),e=t.map((t=>{const e=this[Yt](v(this,W,"f"),t);return t.match(/^(\/|([a-zA-Z]:)?\\)/)&&e.lengthe.includes("package.json")?"package.json":void 0));d(i,void 0,v(this,ct,"f")),s=JSON.parse(v(this,ct,"f").readFileSync(i,"utf8"))}catch(t){}return v(this,ot,"f")[e]=s||{},v(this,ot,"f")[e]}[Pt](t,e){(e=[].concat(e)).forEach((e=>{e=this[Dt](e),v(this,et,"f")[t].push(e)}))}[St](t,e,s,i){this[It](t,e,s,i,((t,e,s)=>{v(this,et,"f")[t][e]=s}))}[$t](t,e,s,i){this[It](t,e,s,i,((t,e,s)=>{v(this,et,"f")[t][e]=(v(this,et,"f")[t][e]||[]).concat(s)}))}[It](t,e,s,i,n){if(Array.isArray(s))s.forEach((e=>{t(e,i)}));else if((t=>"object"==typeof t)(s))for(const e of p(s))t(e,s[e]);else n(e,this[Dt](s),i)}[Dt](t){return"__proto__"===t?"___proto___":t}[Nt](t,e){return this[St](this[Nt].bind(this),"key",t,e),this}[Ht](){var t,e,s,i,n,r,o,a,h,l,c,f;const u=v(this,B,"f").pop();let p;d(u,void 0,v(this,ct,"f")),t=this,e=this,s=this,i=this,n=this,r=this,o=this,a=this,h=this,l=this,c=this,f=this,({options:{set value(e){O(t,et,e,"f")}}.value,configObjects:p,exitProcess:{set value(t){O(e,T,t,"f")}}.value,groups:{set value(t){O(s,K,t,"f")}}.value,output:{set value(t){O(i,tt,t,"f")}}.value,exitError:{set value(t){O(n,V,t,"f")}}.value,hasOutput:{set value(t){O(r,J,t,"f")}}.value,parsed:this.parsed,strict:{set value(t){O(o,ft,t,"f")}}.value,strictCommands:{set value(t){O(a,dt,t,"f")}}.value,strictOptions:{set value(t){O(h,ut,t,"f")}}.value,completionCommand:{set value(t){O(l,F,t,"f")}}.value,parseFn:{set value(t){O(c,nt,t,"f")}}.value,parseContext:{set value(t){O(f,rt,t,"f")}}.value}=u),v(this,et,"f").configObjects=p,v(this,pt,"f").unfreeze(),v(this,yt,"f").unfreeze(),v(this,z,"f").unfreeze(),v(this,Y,"f").unfreeze()}[zt](t,e){return j(e,(e=>(t(e),e)))}getInternalMethods(){return{getCommandInstance:this[Wt].bind(this),getContext:this[qt].bind(this),getHasOutput:this[Ut].bind(this),getLoggerInstance:this[Ft].bind(this),getParseContext:this[Lt].bind(this),getParserConfiguration:this[Mt].bind(this),getUsageConfiguration:this[_t].bind(this),getUsageInstance:this[Vt].bind(this),getValidationInstance:this[Gt].bind(this),hasParseCallback:this[Rt].bind(this),isGlobalContext:this[Tt].bind(this),postProcess:this[Bt].bind(this),reset:this[Kt].bind(this),runValidation:this[Zt].bind(this),runYargsParserAndExecuteCommands:this[Jt].bind(this),setHasOutput:this[Xt].bind(this)}}[Wt](){return v(this,z,"f")}[qt](){return v(this,q,"f")}[Ut](){return v(this,J,"f")}[Ft](){return v(this,Q,"f")}[Lt](){return v(this,rt,"f")||{}}[Vt](){return v(this,pt,"f")}[Gt](){return v(this,yt,"f")}[Rt](){return!!v(this,nt,"f")}[Tt](){return v(this,X,"f")}[Bt](t,e,s,i){if(s)return t;if(f(t))return t;e||(t=this[bt](t));return(this[Mt]()["parse-positional-numbers"]||void 0===this[Mt]()["parse-positional-numbers"])&&(t=this[Et](t)),i&&(t=C(t,this,v(this,Y,"f").getMiddleware(),!1)),t}[Kt](t={}){O(this,et,v(this,et,"f")||{},"f");const e={};e.local=v(this,et,"f").local||[],e.configObjects=v(this,et,"f").configObjects||[];const s={};e.local.forEach((e=>{s[e]=!0,(t[e]||[]).forEach((t=>{s[t]=!0}))})),Object.assign(v(this,at,"f"),Object.keys(v(this,K,"f")).reduce(((t,e)=>{const i=v(this,K,"f")[e].filter((t=>!(t in s)));return i.length>0&&(t[e]=i),t}),{})),O(this,K,{},"f");return["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"].forEach((t=>{e[t]=(v(this,et,"f")[t]||[]).filter((t=>!s[t]))})),["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"].forEach((t=>{e[t]=g(v(this,et,"f")[t],(t=>!s[t]))})),e.envPrefix=v(this,et,"f").envPrefix,O(this,et,e,"f"),O(this,pt,v(this,pt,"f")?v(this,pt,"f").reset(s):P(this,v(this,ct,"f")),"f"),O(this,yt,v(this,yt,"f")?v(this,yt,"f").reset(s):function(t,e,s){const i=s.y18n.__,n=s.y18n.__n,r={nonOptionCount:function(s){const i=t.getDemandedCommands(),r=s._.length+(s["--"]?s["--"].length:0)-t.getInternalMethods().getContext().commands.length;i._&&(ri._.max)&&(ri._.max&&(void 0!==i._.maxMsg?e.fail(i._.maxMsg?i._.maxMsg.replace(/\$0/g,r.toString()).replace(/\$1/,i._.max.toString()):null):e.fail(n("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",r,r.toString(),i._.max.toString()))))},positionalCount:function(t,s){s{H.includes(e)||Object.prototype.hasOwnProperty.call(o,e)||Object.prototype.hasOwnProperty.call(t.getInternalMethods().getParseContext(),e)||r.isValidAndSomeAliasIsNotNew(e,i)||f.push(e)})),h&&(d.commands.length>0||c.length>0||a)&&s._.slice(d.commands.length).forEach((t=>{c.includes(""+t)||f.push(""+t)})),h){const e=(null===(l=t.getDemandedCommands()._)||void 0===l?void 0:l.max)||0,i=d.commands.length+e;i{t=String(t),d.commands.includes(t)||f.includes(t)||f.push(t)}))}f.length&&e.fail(n("Unknown argument: %s","Unknown arguments: %s",f.length,f.map((t=>t.trim()?t:`"${t}"`)).join(", ")))},unknownCommands:function(s){const i=t.getInternalMethods().getCommandInstance().getCommands(),r=[],o=t.getInternalMethods().getContext();return(o.commands.length>0||i.length>0)&&s._.slice(o.commands.length).forEach((t=>{i.includes(""+t)||r.push(""+t)})),r.length>0&&(e.fail(n("Unknown command: %s","Unknown commands: %s",r.length,r.join(", "))),!0)},isValidAndSomeAliasIsNotNew:function(e,s){if(!Object.prototype.hasOwnProperty.call(s,e))return!1;const i=t.parsed.newAliases;return[e,...s[e]].some((t=>!Object.prototype.hasOwnProperty.call(i,t)||!i[e]))},limitedChoices:function(s){const n=t.getOptions(),r={};if(!Object.keys(n.choices).length)return;Object.keys(s).forEach((t=>{-1===H.indexOf(t)&&Object.prototype.hasOwnProperty.call(n.choices,t)&&[].concat(s[t]).forEach((e=>{-1===n.choices[t].indexOf(e)&&void 0!==e&&(r[t]=(r[t]||[]).concat(e))}))}));const o=Object.keys(r);if(!o.length)return;let a=i("Invalid values:");o.forEach((t=>{a+=`\n ${i("Argument: %s, Given: %s, Choices: %s",t,e.stringifiedValues(r[t]),e.stringifiedValues(n.choices[t]))}`})),e.fail(a)}};let o={};function a(t,e){const s=Number(e);return"number"==typeof(e=isNaN(s)?e:s)?e=t._.length>=e:e.match(/^--no-.+/)?(e=e.match(/^--no-(.+)/)[1],e=!Object.prototype.hasOwnProperty.call(t,e)):e=Object.prototype.hasOwnProperty.call(t,e),e}r.implies=function(e,i){h(" [array|number|string]",[e,i],arguments.length),"object"==typeof e?Object.keys(e).forEach((t=>{r.implies(t,e[t])})):(t.global(e),o[e]||(o[e]=[]),Array.isArray(i)?i.forEach((t=>r.implies(e,t))):(d(i,void 0,s),o[e].push(i)))},r.getImplied=function(){return o},r.implications=function(t){const s=[];if(Object.keys(o).forEach((e=>{const i=e;(o[e]||[]).forEach((e=>{let n=i;const r=e;n=a(t,n),e=a(t,e),n&&!e&&s.push(` ${i} -> ${r}`)}))})),s.length){let t=`${i("Implications failed:")}\n`;s.forEach((e=>{t+=e})),e.fail(t)}};let l={};r.conflicts=function(e,s){h(" [array|string]",[e,s],arguments.length),"object"==typeof e?Object.keys(e).forEach((t=>{r.conflicts(t,e[t])})):(t.global(e),l[e]||(l[e]=[]),Array.isArray(s)?s.forEach((t=>r.conflicts(e,t))):l[e].push(s))},r.getConflicting=()=>l,r.conflicting=function(n){Object.keys(n).forEach((t=>{l[t]&&l[t].forEach((s=>{s&&void 0!==n[t]&&void 0!==n[s]&&e.fail(i("Arguments %s and %s are mutually exclusive",t,s))}))})),t.getInternalMethods().getParserConfiguration()["strip-dashed"]&&Object.keys(l).forEach((t=>{l[t].forEach((r=>{r&&void 0!==n[s.Parser.camelCase(t)]&&void 0!==n[s.Parser.camelCase(r)]&&e.fail(i("Arguments %s and %s are mutually exclusive",t,r))}))}))},r.recommendCommands=function(t,s){s=s.sort(((t,e)=>e.length-t.length));let n=null,r=1/0;for(let e,i=0;void 0!==(e=s[i]);i++){const s=N(t,e);s<=3&&s!t[e])),l=g(l,(e=>!t[e])),r};const c=[];return r.freeze=function(){c.push({implied:o,conflicting:l})},r.unfreeze=function(){const t=c.pop();d(t,void 0,s),({implied:o,conflicting:l}=t)},r}(this,v(this,pt,"f"),v(this,ct,"f")),"f"),O(this,z,v(this,z,"f")?v(this,z,"f").reset():function(t,e,s,i){return new _(t,e,s,i)}(v(this,pt,"f"),v(this,yt,"f"),v(this,Y,"f"),v(this,ct,"f")),"f"),v(this,U,"f")||O(this,U,function(t,e,s,i){return new D(t,e,s,i)}(this,v(this,pt,"f"),v(this,z,"f"),v(this,ct,"f")),"f"),v(this,Y,"f").reset(),O(this,F,null,"f"),O(this,tt,"","f"),O(this,V,null,"f"),O(this,J,!1,"f"),this.parsed=!1,this}[Yt](t,e){return v(this,ct,"f").path.relative(t,e)}[Jt](t,s,i,n=0,r=!1){let o=!!i||r;t=t||v(this,ht,"f"),v(this,et,"f").__=v(this,ct,"f").y18n.__,v(this,et,"f").configuration=this[Mt]();const a=!!v(this,et,"f").configuration["populate--"],h=Object.assign({},v(this,et,"f").configuration,{"populate--":!0}),l=v(this,ct,"f").Parser.detailed(t,Object.assign({},v(this,et,"f"),{configuration:{"parse-positional-numbers":!1,...h}})),c=Object.assign(l.argv,v(this,rt,"f"));let d;const u=l.aliases;let p=!1,g=!1;Object.keys(c).forEach((t=>{t===v(this,Z,"f")&&c[t]?p=!0:t===v(this,mt,"f")&&c[t]&&(g=!0)})),c.$0=this.$0,this.parsed=l,0===n&&v(this,pt,"f").clearCachedHelpMessage();try{if(this[kt](),s)return this[Bt](c,a,!!i,!1);if(v(this,Z,"f")){[v(this,Z,"f")].concat(u[v(this,Z,"f")]||[]).filter((t=>t.length>1)).includes(""+c._[c._.length-1])&&(c._.pop(),p=!0)}O(this,X,!1,"f");const h=v(this,z,"f").getCommands(),m=v(this,U,"f").completionKey in c,y=p||m||r;if(c._.length){if(h.length){let t;for(let e,s=n||0;void 0!==c._[s];s++){if(e=String(c._[s]),h.includes(e)&&e!==v(this,F,"f")){const t=v(this,z,"f").runCommand(e,this,l,s+1,r,p||g||r);return this[Bt](t,a,!!i,!1)}if(!t&&e!==v(this,F,"f")){t=e;break}}!v(this,z,"f").hasDefaultCommand()&&v(this,lt,"f")&&t&&!y&&v(this,yt,"f").recommendCommands(t,h)}v(this,F,"f")&&c._.includes(v(this,F,"f"))&&!m&&(v(this,T,"f")&&E(!0),this.showCompletionScript(),this.exit(0))}if(v(this,z,"f").hasDefaultCommand()&&!y){const t=v(this,z,"f").runCommand(null,this,l,0,r,p||g||r);return this[Bt](t,a,!!i,!1)}if(m){v(this,T,"f")&&E(!0);const s=(t=[].concat(t)).slice(t.indexOf(`--${v(this,U,"f").completionKey}`)+1);return v(this,U,"f").getCompletion(s,((t,s)=>{if(t)throw new e(t.message);(s||[]).forEach((t=>{v(this,Q,"f").log(t)})),this.exit(0)})),this[Bt](c,!a,!!i,!1)}if(v(this,J,"f")||(p?(v(this,T,"f")&&E(!0),o=!0,this.showHelp("log"),this.exit(0)):g&&(v(this,T,"f")&&E(!0),o=!0,v(this,pt,"f").showVersion("log"),this.exit(0))),!o&&v(this,et,"f").skipValidation.length>0&&(o=Object.keys(c).some((t=>v(this,et,"f").skipValidation.indexOf(t)>=0&&!0===c[t]))),!o){if(l.error)throw new e(l.error.message);if(!m){const t=this[Zt](u,{},l.error);i||(d=C(c,this,v(this,Y,"f").getMiddleware(),!0)),d=this[zt](t,null!=d?d:c),f(d)&&!i&&(d=d.then((()=>C(c,this,v(this,Y,"f").getMiddleware(),!1))))}}}catch(t){if(!(t instanceof e))throw t;v(this,pt,"f").fail(t.message,t)}return this[Bt](null!=d?d:c,a,!!i,!0)}[Zt](t,s,i,n){const r={...this.getDemandedOptions()};return o=>{if(i)throw new e(i.message);v(this,yt,"f").nonOptionCount(o),v(this,yt,"f").requiredArguments(o,r);let a=!1;v(this,dt,"f")&&(a=v(this,yt,"f").unknownCommands(o)),v(this,ft,"f")&&!a?v(this,yt,"f").unknownArguments(o,t,s,!!n):v(this,ut,"f")&&v(this,yt,"f").unknownArguments(o,t,{},!1,!1),v(this,yt,"f").limitedChoices(o),v(this,yt,"f").implications(o),v(this,yt,"f").conflicting(o)}}[Xt](){O(this,J,!0,"f")}[Qt](t){if("string"==typeof t)v(this,et,"f").key[t]=!0;else for(const e of t)v(this,et,"f").key[e]=!0}}var ee,se;const{readFileSync:ie}=require("fs"),{inspect:ne}=require("util"),{resolve:re}=require("path"),oe=require("y18n"),ae=require("yargs-parser");var he,le={assert:{notStrictEqual:t.notStrictEqual,strictEqual:t.strictEqual},cliui:require("cliui"),findUp:require("escalade/sync"),getEnv:t=>process.env[t],getCallerFile:require("get-caller-file"),getProcessArgvBin:y,inspect:ne,mainFilename:null!==(se=null===(ee=null===require||void 0===require?void 0:require.main)||void 0===ee?void 0:ee.filename)&&void 0!==se?se:process.cwd(),Parser:ae,path:require("path"),process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(t,e)=>process.emitWarning(t,e),execPath:()=>process.execPath,exit:t=>{process.exit(t)},nextTick:process.nextTick,stdColumns:void 0!==process.stdout.columns?process.stdout.columns:null},readFileSync:ie,require:require,requireDirectory:require("require-directory"),stringWidth:require("string-width"),y18n:oe({directory:re(__dirname,"../locales"),updateFiles:!1})};const ce=(null===(he=null===process||void 0===process?void 0:process.env)||void 0===he?void 0:he.YARGS_MIN_NODE_VERSION)?Number(process.env.YARGS_MIN_NODE_VERSION):12;if(process&&process.version){if(Number(process.version.match(/v([^.]+)/)[1]){const i=new te(t,e,s,de);return Object.defineProperty(i,"argv",{get:()=>i.parse(),enumerable:!0}),i.help(),i.version(),i}),argsert:h,isPromise:f,objFilter:g,parseCommand:o,Parser:fe,processArgv:b,YError:e};module.exports=ue; diff --git a/node_modules/yargs/build/lib/argsert.js b/node_modules/yargs/build/lib/argsert.js new file mode 100644 index 0000000..be5b3aa --- /dev/null +++ b/node_modules/yargs/build/lib/argsert.js @@ -0,0 +1,62 @@ +import { YError } from './yerror.js'; +import { parseCommand } from './parse-command.js'; +const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']; +export function argsert(arg1, arg2, arg3) { + function parseArgs() { + return typeof arg1 === 'object' + ? [{ demanded: [], optional: [] }, arg1, arg2] + : [ + parseCommand(`cmd ${arg1}`), + arg2, + arg3, + ]; + } + try { + let position = 0; + const [parsed, callerArguments, _length] = parseArgs(); + const args = [].slice.call(callerArguments); + while (args.length && args[args.length - 1] === undefined) + args.pop(); + const length = _length || args.length; + if (length < parsed.demanded.length) { + throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`); + } + const totalCommands = parsed.demanded.length + parsed.optional.length; + if (length > totalCommands) { + throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`); + } + parsed.demanded.forEach(demanded => { + const arg = args.shift(); + const observedType = guessType(arg); + const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*'); + if (matchingTypes.length === 0) + argumentTypeError(observedType, demanded.cmd, position); + position += 1; + }); + parsed.optional.forEach(optional => { + if (args.length === 0) + return; + const arg = args.shift(); + const observedType = guessType(arg); + const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*'); + if (matchingTypes.length === 0) + argumentTypeError(observedType, optional.cmd, position); + position += 1; + }); + } + catch (err) { + console.warn(err.stack); + } +} +function guessType(arg) { + if (Array.isArray(arg)) { + return 'array'; + } + else if (arg === null) { + return 'null'; + } + return typeof arg; +} +function argumentTypeError(observedType, allowedTypes, position) { + throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`); +} diff --git a/node_modules/yargs/build/lib/command.js b/node_modules/yargs/build/lib/command.js new file mode 100644 index 0000000..47c1ed6 --- /dev/null +++ b/node_modules/yargs/build/lib/command.js @@ -0,0 +1,449 @@ +import { assertNotStrictEqual, } from './typings/common-types.js'; +import { isPromise } from './utils/is-promise.js'; +import { applyMiddleware, commandMiddlewareFactory, } from './middleware.js'; +import { parseCommand } from './parse-command.js'; +import { isYargsInstance, } from './yargs-factory.js'; +import { maybeAsyncResult } from './utils/maybe-async-result.js'; +import whichModule from './utils/which-module.js'; +const DEFAULT_MARKER = /(^\*)|(^\$0)/; +export class CommandInstance { + constructor(usage, validation, globalMiddleware, shim) { + this.requireCache = new Set(); + this.handlers = {}; + this.aliasMap = {}; + this.frozens = []; + this.shim = shim; + this.usage = usage; + this.globalMiddleware = globalMiddleware; + this.validation = validation; + } + addDirectory(dir, req, callerFile, opts) { + opts = opts || {}; + if (typeof opts.recurse !== 'boolean') + opts.recurse = false; + if (!Array.isArray(opts.extensions)) + opts.extensions = ['js']; + const parentVisit = typeof opts.visit === 'function' ? opts.visit : (o) => o; + opts.visit = (obj, joined, filename) => { + const visited = parentVisit(obj, joined, filename); + if (visited) { + if (this.requireCache.has(joined)) + return visited; + else + this.requireCache.add(joined); + this.addHandler(visited); + } + return visited; + }; + this.shim.requireDirectory({ require: req, filename: callerFile }, dir, opts); + } + addHandler(cmd, description, builder, handler, commandMiddleware, deprecated) { + let aliases = []; + const middlewares = commandMiddlewareFactory(commandMiddleware); + handler = handler || (() => { }); + if (Array.isArray(cmd)) { + if (isCommandAndAliases(cmd)) { + [cmd, ...aliases] = cmd; + } + else { + for (const command of cmd) { + this.addHandler(command); + } + } + } + else if (isCommandHandlerDefinition(cmd)) { + let command = Array.isArray(cmd.command) || typeof cmd.command === 'string' + ? cmd.command + : this.moduleName(cmd); + if (cmd.aliases) + command = [].concat(command).concat(cmd.aliases); + this.addHandler(command, this.extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated); + return; + } + else if (isCommandBuilderDefinition(builder)) { + this.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated); + return; + } + if (typeof cmd === 'string') { + const parsedCommand = parseCommand(cmd); + aliases = aliases.map(alias => parseCommand(alias).cmd); + let isDefault = false; + const parsedAliases = [parsedCommand.cmd].concat(aliases).filter(c => { + if (DEFAULT_MARKER.test(c)) { + isDefault = true; + return false; + } + return true; + }); + if (parsedAliases.length === 0 && isDefault) + parsedAliases.push('$0'); + if (isDefault) { + parsedCommand.cmd = parsedAliases[0]; + aliases = parsedAliases.slice(1); + cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd); + } + aliases.forEach(alias => { + this.aliasMap[alias] = parsedCommand.cmd; + }); + if (description !== false) { + this.usage.command(cmd, description, isDefault, aliases, deprecated); + } + this.handlers[parsedCommand.cmd] = { + original: cmd, + description, + handler, + builder: builder || {}, + middlewares, + deprecated, + demanded: parsedCommand.demanded, + optional: parsedCommand.optional, + }; + if (isDefault) + this.defaultCommand = this.handlers[parsedCommand.cmd]; + } + } + getCommandHandlers() { + return this.handlers; + } + getCommands() { + return Object.keys(this.handlers).concat(Object.keys(this.aliasMap)); + } + hasDefaultCommand() { + return !!this.defaultCommand; + } + runCommand(command, yargs, parsed, commandIndex, helpOnly, helpOrVersionSet) { + const commandHandler = this.handlers[command] || + this.handlers[this.aliasMap[command]] || + this.defaultCommand; + const currentContext = yargs.getInternalMethods().getContext(); + const parentCommands = currentContext.commands.slice(); + const isDefaultCommand = !command; + if (command) { + currentContext.commands.push(command); + currentContext.fullCommands.push(commandHandler.original); + } + const builderResult = this.applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, parsed.aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet); + return isPromise(builderResult) + ? builderResult.then(result => this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, result.innerArgv, currentContext, helpOnly, result.aliases, yargs)) + : this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, builderResult.innerArgv, currentContext, helpOnly, builderResult.aliases, yargs); + } + applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet) { + const builder = commandHandler.builder; + let innerYargs = yargs; + if (isCommandBuilderCallback(builder)) { + yargs.getInternalMethods().getUsageInstance().freeze(); + const builderOutput = builder(yargs.getInternalMethods().reset(aliases), helpOrVersionSet); + if (isPromise(builderOutput)) { + return builderOutput.then(output => { + innerYargs = isYargsInstance(output) ? output : yargs; + return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly); + }); + } + } + else if (isCommandBuilderOptionDefinitions(builder)) { + yargs.getInternalMethods().getUsageInstance().freeze(); + innerYargs = yargs.getInternalMethods().reset(aliases); + Object.keys(commandHandler.builder).forEach(key => { + innerYargs.option(key, builder[key]); + }); + } + return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly); + } + parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly) { + if (isDefaultCommand) + innerYargs.getInternalMethods().getUsageInstance().unfreeze(true); + if (this.shouldUpdateUsage(innerYargs)) { + innerYargs + .getInternalMethods() + .getUsageInstance() + .usage(this.usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description); + } + const innerArgv = innerYargs + .getInternalMethods() + .runYargsParserAndExecuteCommands(null, undefined, true, commandIndex, helpOnly); + return isPromise(innerArgv) + ? innerArgv.then(argv => ({ + aliases: innerYargs.parsed.aliases, + innerArgv: argv, + })) + : { + aliases: innerYargs.parsed.aliases, + innerArgv: innerArgv, + }; + } + shouldUpdateUsage(yargs) { + return (!yargs.getInternalMethods().getUsageInstance().getUsageDisabled() && + yargs.getInternalMethods().getUsageInstance().getUsage().length === 0); + } + usageFromParentCommandsCommandHandler(parentCommands, commandHandler) { + const c = DEFAULT_MARKER.test(commandHandler.original) + ? commandHandler.original.replace(DEFAULT_MARKER, '').trim() + : commandHandler.original; + const pc = parentCommands.filter(c => { + return !DEFAULT_MARKER.test(c); + }); + pc.push(c); + return `$0 ${pc.join(' ')}`; + } + handleValidationAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, aliases, yargs, middlewares, positionalMap) { + if (!yargs.getInternalMethods().getHasOutput()) { + const validation = yargs + .getInternalMethods() + .runValidation(aliases, positionalMap, yargs.parsed.error, isDefaultCommand); + innerArgv = maybeAsyncResult(innerArgv, result => { + validation(result); + return result; + }); + } + if (commandHandler.handler && !yargs.getInternalMethods().getHasOutput()) { + yargs.getInternalMethods().setHasOutput(); + const populateDoubleDash = !!yargs.getOptions().configuration['populate--']; + yargs + .getInternalMethods() + .postProcess(innerArgv, populateDoubleDash, false, false); + innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false); + innerArgv = maybeAsyncResult(innerArgv, result => { + const handlerResult = commandHandler.handler(result); + return isPromise(handlerResult) + ? handlerResult.then(() => result) + : result; + }); + if (!isDefaultCommand) { + yargs.getInternalMethods().getUsageInstance().cacheHelpMessage(); + } + if (isPromise(innerArgv) && + !yargs.getInternalMethods().hasParseCallback()) { + innerArgv.catch(error => { + try { + yargs.getInternalMethods().getUsageInstance().fail(null, error); + } + catch (_err) { + } + }); + } + } + if (!isDefaultCommand) { + currentContext.commands.pop(); + currentContext.fullCommands.pop(); + } + return innerArgv; + } + applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, helpOnly, aliases, yargs) { + let positionalMap = {}; + if (helpOnly) + return innerArgv; + if (!yargs.getInternalMethods().getHasOutput()) { + positionalMap = this.populatePositionals(commandHandler, innerArgv, currentContext, yargs); + } + const middlewares = this.globalMiddleware + .getMiddleware() + .slice(0) + .concat(commandHandler.middlewares); + const maybePromiseArgv = applyMiddleware(innerArgv, yargs, middlewares, true); + return isPromise(maybePromiseArgv) + ? maybePromiseArgv.then(resolvedInnerArgv => this.handleValidationAndGetResult(isDefaultCommand, commandHandler, resolvedInnerArgv, currentContext, aliases, yargs, middlewares, positionalMap)) + : this.handleValidationAndGetResult(isDefaultCommand, commandHandler, maybePromiseArgv, currentContext, aliases, yargs, middlewares, positionalMap); + } + populatePositionals(commandHandler, argv, context, yargs) { + argv._ = argv._.slice(context.commands.length); + const demanded = commandHandler.demanded.slice(0); + const optional = commandHandler.optional.slice(0); + const positionalMap = {}; + this.validation.positionalCount(demanded.length, argv._.length); + while (demanded.length) { + const demand = demanded.shift(); + this.populatePositional(demand, argv, positionalMap); + } + while (optional.length) { + const maybe = optional.shift(); + this.populatePositional(maybe, argv, positionalMap); + } + argv._ = context.commands.concat(argv._.map(a => '' + a)); + this.postProcessPositionals(argv, positionalMap, this.cmdToParseOptions(commandHandler.original), yargs); + return positionalMap; + } + populatePositional(positional, argv, positionalMap) { + const cmd = positional.cmd[0]; + if (positional.variadic) { + positionalMap[cmd] = argv._.splice(0).map(String); + } + else { + if (argv._.length) + positionalMap[cmd] = [String(argv._.shift())]; + } + } + cmdToParseOptions(cmdString) { + const parseOptions = { + array: [], + default: {}, + alias: {}, + demand: {}, + }; + const parsed = parseCommand(cmdString); + parsed.demanded.forEach(d => { + const [cmd, ...aliases] = d.cmd; + if (d.variadic) { + parseOptions.array.push(cmd); + parseOptions.default[cmd] = []; + } + parseOptions.alias[cmd] = aliases; + parseOptions.demand[cmd] = true; + }); + parsed.optional.forEach(o => { + const [cmd, ...aliases] = o.cmd; + if (o.variadic) { + parseOptions.array.push(cmd); + parseOptions.default[cmd] = []; + } + parseOptions.alias[cmd] = aliases; + }); + return parseOptions; + } + postProcessPositionals(argv, positionalMap, parseOptions, yargs) { + const options = Object.assign({}, yargs.getOptions()); + options.default = Object.assign(parseOptions.default, options.default); + for (const key of Object.keys(parseOptions.alias)) { + options.alias[key] = (options.alias[key] || []).concat(parseOptions.alias[key]); + } + options.array = options.array.concat(parseOptions.array); + options.config = {}; + const unparsed = []; + Object.keys(positionalMap).forEach(key => { + positionalMap[key].map(value => { + if (options.configuration['unknown-options-as-args']) + options.key[key] = true; + unparsed.push(`--${key}`); + unparsed.push(value); + }); + }); + if (!unparsed.length) + return; + const config = Object.assign({}, options.configuration, { + 'populate--': false, + }); + const parsed = this.shim.Parser.detailed(unparsed, Object.assign({}, options, { + configuration: config, + })); + if (parsed.error) { + yargs + .getInternalMethods() + .getUsageInstance() + .fail(parsed.error.message, parsed.error); + } + else { + const positionalKeys = Object.keys(positionalMap); + Object.keys(positionalMap).forEach(key => { + positionalKeys.push(...parsed.aliases[key]); + }); + Object.keys(parsed.argv).forEach(key => { + if (positionalKeys.includes(key)) { + if (!positionalMap[key]) + positionalMap[key] = parsed.argv[key]; + if (!this.isInConfigs(yargs, key) && + !this.isDefaulted(yargs, key) && + Object.prototype.hasOwnProperty.call(argv, key) && + Object.prototype.hasOwnProperty.call(parsed.argv, key) && + (Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))) { + argv[key] = [].concat(argv[key], parsed.argv[key]); + } + else { + argv[key] = parsed.argv[key]; + } + } + }); + } + } + isDefaulted(yargs, key) { + const { default: defaults } = yargs.getOptions(); + return (Object.prototype.hasOwnProperty.call(defaults, key) || + Object.prototype.hasOwnProperty.call(defaults, this.shim.Parser.camelCase(key))); + } + isInConfigs(yargs, key) { + const { configObjects } = yargs.getOptions(); + return (configObjects.some(c => Object.prototype.hasOwnProperty.call(c, key)) || + configObjects.some(c => Object.prototype.hasOwnProperty.call(c, this.shim.Parser.camelCase(key)))); + } + runDefaultBuilderOn(yargs) { + if (!this.defaultCommand) + return; + if (this.shouldUpdateUsage(yargs)) { + const commandString = DEFAULT_MARKER.test(this.defaultCommand.original) + ? this.defaultCommand.original + : this.defaultCommand.original.replace(/^[^[\]<>]*/, '$0 '); + yargs + .getInternalMethods() + .getUsageInstance() + .usage(commandString, this.defaultCommand.description); + } + const builder = this.defaultCommand.builder; + if (isCommandBuilderCallback(builder)) { + return builder(yargs, true); + } + else if (!isCommandBuilderDefinition(builder)) { + Object.keys(builder).forEach(key => { + yargs.option(key, builder[key]); + }); + } + return undefined; + } + moduleName(obj) { + const mod = whichModule(obj); + if (!mod) + throw new Error(`No command name given for module: ${this.shim.inspect(obj)}`); + return this.commandFromFilename(mod.filename); + } + commandFromFilename(filename) { + return this.shim.path.basename(filename, this.shim.path.extname(filename)); + } + extractDesc({ describe, description, desc }) { + for (const test of [describe, description, desc]) { + if (typeof test === 'string' || test === false) + return test; + assertNotStrictEqual(test, true, this.shim); + } + return false; + } + freeze() { + this.frozens.push({ + handlers: this.handlers, + aliasMap: this.aliasMap, + defaultCommand: this.defaultCommand, + }); + } + unfreeze() { + const frozen = this.frozens.pop(); + assertNotStrictEqual(frozen, undefined, this.shim); + ({ + handlers: this.handlers, + aliasMap: this.aliasMap, + defaultCommand: this.defaultCommand, + } = frozen); + } + reset() { + this.handlers = {}; + this.aliasMap = {}; + this.defaultCommand = undefined; + this.requireCache = new Set(); + return this; + } +} +export function command(usage, validation, globalMiddleware, shim) { + return new CommandInstance(usage, validation, globalMiddleware, shim); +} +export function isCommandBuilderDefinition(builder) { + return (typeof builder === 'object' && + !!builder.builder && + typeof builder.handler === 'function'); +} +function isCommandAndAliases(cmd) { + return cmd.every(c => typeof c === 'string'); +} +export function isCommandBuilderCallback(builder) { + return typeof builder === 'function'; +} +function isCommandBuilderOptionDefinitions(builder) { + return typeof builder === 'object'; +} +export function isCommandHandlerDefinition(cmd) { + return typeof cmd === 'object' && !Array.isArray(cmd); +} diff --git a/node_modules/yargs/build/lib/completion-templates.js b/node_modules/yargs/build/lib/completion-templates.js new file mode 100644 index 0000000..2c4dcb5 --- /dev/null +++ b/node_modules/yargs/build/lib/completion-templates.js @@ -0,0 +1,48 @@ +export const completionShTemplate = `###-begin-{{app_name}}-completions-### +# +# yargs command completion script +# +# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc +# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX. +# +_{{app_name}}_yargs_completions() +{ + local cur_word args type_list + + cur_word="\${COMP_WORDS[COMP_CWORD]}" + args=("\${COMP_WORDS[@]}") + + # ask yargs to generate completions. + type_list=$({{app_path}} --get-yargs-completions "\${args[@]}") + + COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) ) + + # if no match was found, fall back to filename completion + if [ \${#COMPREPLY[@]} -eq 0 ]; then + COMPREPLY=() + fi + + return 0 +} +complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}} +###-end-{{app_name}}-completions-### +`; +export const completionZshTemplate = `#compdef {{app_name}} +###-begin-{{app_name}}-completions-### +# +# yargs command completion script +# +# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc +# or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX. +# +_{{app_name}}_yargs_completions() +{ + local reply + local si=$IFS + IFS=$'\n' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}")) + IFS=$si + _describe 'values' reply +} +compdef _{{app_name}}_yargs_completions {{app_name}} +###-end-{{app_name}}-completions-### +`; diff --git a/node_modules/yargs/build/lib/completion.js b/node_modules/yargs/build/lib/completion.js new file mode 100644 index 0000000..cef2bbe --- /dev/null +++ b/node_modules/yargs/build/lib/completion.js @@ -0,0 +1,243 @@ +import { isCommandBuilderCallback } from './command.js'; +import { assertNotStrictEqual } from './typings/common-types.js'; +import * as templates from './completion-templates.js'; +import { isPromise } from './utils/is-promise.js'; +import { parseCommand } from './parse-command.js'; +export class Completion { + constructor(yargs, usage, command, shim) { + var _a, _b, _c; + this.yargs = yargs; + this.usage = usage; + this.command = command; + this.shim = shim; + this.completionKey = 'get-yargs-completions'; + this.aliases = null; + this.customCompletionFunction = null; + this.indexAfterLastReset = 0; + this.zshShell = + (_c = (((_a = this.shim.getEnv('SHELL')) === null || _a === void 0 ? void 0 : _a.includes('zsh')) || + ((_b = this.shim.getEnv('ZSH_NAME')) === null || _b === void 0 ? void 0 : _b.includes('zsh')))) !== null && _c !== void 0 ? _c : false; + } + defaultCompletion(args, argv, current, done) { + const handlers = this.command.getCommandHandlers(); + for (let i = 0, ii = args.length; i < ii; ++i) { + if (handlers[args[i]] && handlers[args[i]].builder) { + const builder = handlers[args[i]].builder; + if (isCommandBuilderCallback(builder)) { + this.indexAfterLastReset = i + 1; + const y = this.yargs.getInternalMethods().reset(); + builder(y, true); + return y.argv; + } + } + } + const completions = []; + this.commandCompletions(completions, args, current); + this.optionCompletions(completions, args, argv, current); + this.choicesFromOptionsCompletions(completions, args, argv, current); + this.choicesFromPositionalsCompletions(completions, args, argv, current); + done(null, completions); + } + commandCompletions(completions, args, current) { + const parentCommands = this.yargs + .getInternalMethods() + .getContext().commands; + if (!current.match(/^-/) && + parentCommands[parentCommands.length - 1] !== current && + !this.previousArgHasChoices(args)) { + this.usage.getCommands().forEach(usageCommand => { + const commandName = parseCommand(usageCommand[0]).cmd; + if (args.indexOf(commandName) === -1) { + if (!this.zshShell) { + completions.push(commandName); + } + else { + const desc = usageCommand[1] || ''; + completions.push(commandName.replace(/:/g, '\\:') + ':' + desc); + } + } + }); + } + } + optionCompletions(completions, args, argv, current) { + if ((current.match(/^-/) || (current === '' && completions.length === 0)) && + !this.previousArgHasChoices(args)) { + const options = this.yargs.getOptions(); + const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || []; + Object.keys(options.key).forEach(key => { + const negable = !!options.configuration['boolean-negation'] && + options.boolean.includes(key); + const isPositionalKey = positionalKeys.includes(key); + if (!isPositionalKey && + !options.hiddenOptions.includes(key) && + !this.argsContainKey(args, key, negable)) { + this.completeOptionKey(key, completions, current, negable && !!options.default[key]); + } + }); + } + } + choicesFromOptionsCompletions(completions, args, argv, current) { + if (this.previousArgHasChoices(args)) { + const choices = this.getPreviousArgChoices(args); + if (choices && choices.length > 0) { + completions.push(...choices.map(c => c.replace(/:/g, '\\:'))); + } + } + } + choicesFromPositionalsCompletions(completions, args, argv, current) { + if (current === '' && + completions.length > 0 && + this.previousArgHasChoices(args)) { + return; + } + const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || []; + const offset = Math.max(this.indexAfterLastReset, this.yargs.getInternalMethods().getContext().commands.length + + 1); + const positionalKey = positionalKeys[argv._.length - offset - 1]; + if (!positionalKey) { + return; + } + const choices = this.yargs.getOptions().choices[positionalKey] || []; + for (const choice of choices) { + if (choice.startsWith(current)) { + completions.push(choice.replace(/:/g, '\\:')); + } + } + } + getPreviousArgChoices(args) { + if (args.length < 1) + return; + let previousArg = args[args.length - 1]; + let filter = ''; + if (!previousArg.startsWith('-') && args.length > 1) { + filter = previousArg; + previousArg = args[args.length - 2]; + } + if (!previousArg.startsWith('-')) + return; + const previousArgKey = previousArg.replace(/^-+/, ''); + const options = this.yargs.getOptions(); + const possibleAliases = [ + previousArgKey, + ...(this.yargs.getAliases()[previousArgKey] || []), + ]; + let choices; + for (const possibleAlias of possibleAliases) { + if (Object.prototype.hasOwnProperty.call(options.key, possibleAlias) && + Array.isArray(options.choices[possibleAlias])) { + choices = options.choices[possibleAlias]; + break; + } + } + if (choices) { + return choices.filter(choice => !filter || choice.startsWith(filter)); + } + } + previousArgHasChoices(args) { + const choices = this.getPreviousArgChoices(args); + return choices !== undefined && choices.length > 0; + } + argsContainKey(args, key, negable) { + const argsContains = (s) => args.indexOf((/^[^0-9]$/.test(s) ? '-' : '--') + s) !== -1; + if (argsContains(key)) + return true; + if (negable && argsContains(`no-${key}`)) + return true; + if (this.aliases) { + for (const alias of this.aliases[key]) { + if (argsContains(alias)) + return true; + } + } + return false; + } + completeOptionKey(key, completions, current, negable) { + var _a, _b, _c, _d; + let keyWithDesc = key; + if (this.zshShell) { + const descs = this.usage.getDescriptions(); + const aliasKey = (_b = (_a = this === null || this === void 0 ? void 0 : this.aliases) === null || _a === void 0 ? void 0 : _a[key]) === null || _b === void 0 ? void 0 : _b.find(alias => { + const desc = descs[alias]; + return typeof desc === 'string' && desc.length > 0; + }); + const descFromAlias = aliasKey ? descs[aliasKey] : undefined; + const desc = (_d = (_c = descs[key]) !== null && _c !== void 0 ? _c : descFromAlias) !== null && _d !== void 0 ? _d : ''; + keyWithDesc = `${key.replace(/:/g, '\\:')}:${desc + .replace('__yargsString__:', '') + .replace(/(\r\n|\n|\r)/gm, ' ')}`; + } + const startsByTwoDashes = (s) => /^--/.test(s); + const isShortOption = (s) => /^[^0-9]$/.test(s); + const dashes = !startsByTwoDashes(current) && isShortOption(key) ? '-' : '--'; + completions.push(dashes + keyWithDesc); + if (negable) { + completions.push(dashes + 'no-' + keyWithDesc); + } + } + customCompletion(args, argv, current, done) { + assertNotStrictEqual(this.customCompletionFunction, null, this.shim); + if (isSyncCompletionFunction(this.customCompletionFunction)) { + const result = this.customCompletionFunction(current, argv); + if (isPromise(result)) { + return result + .then(list => { + this.shim.process.nextTick(() => { + done(null, list); + }); + }) + .catch(err => { + this.shim.process.nextTick(() => { + done(err, undefined); + }); + }); + } + return done(null, result); + } + else if (isFallbackCompletionFunction(this.customCompletionFunction)) { + return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args, argv, current, onCompleted), completions => { + done(null, completions); + }); + } + else { + return this.customCompletionFunction(current, argv, completions => { + done(null, completions); + }); + } + } + getCompletion(args, done) { + const current = args.length ? args[args.length - 1] : ''; + const argv = this.yargs.parse(args, true); + const completionFunction = this.customCompletionFunction + ? (argv) => this.customCompletion(args, argv, current, done) + : (argv) => this.defaultCompletion(args, argv, current, done); + return isPromise(argv) + ? argv.then(completionFunction) + : completionFunction(argv); + } + generateCompletionScript($0, cmd) { + let script = this.zshShell + ? templates.completionZshTemplate + : templates.completionShTemplate; + const name = this.shim.path.basename($0); + if ($0.match(/\.js$/)) + $0 = `./${$0}`; + script = script.replace(/{{app_name}}/g, name); + script = script.replace(/{{completion_command}}/g, cmd); + return script.replace(/{{app_path}}/g, $0); + } + registerFunction(fn) { + this.customCompletionFunction = fn; + } + setParsed(parsed) { + this.aliases = parsed.aliases; + } +} +export function completion(yargs, usage, command, shim) { + return new Completion(yargs, usage, command, shim); +} +function isSyncCompletionFunction(completionFunction) { + return completionFunction.length < 3; +} +function isFallbackCompletionFunction(completionFunction) { + return completionFunction.length > 3; +} diff --git a/node_modules/yargs/build/lib/middleware.js b/node_modules/yargs/build/lib/middleware.js new file mode 100644 index 0000000..4e561a7 --- /dev/null +++ b/node_modules/yargs/build/lib/middleware.js @@ -0,0 +1,88 @@ +import { argsert } from './argsert.js'; +import { isPromise } from './utils/is-promise.js'; +export class GlobalMiddleware { + constructor(yargs) { + this.globalMiddleware = []; + this.frozens = []; + this.yargs = yargs; + } + addMiddleware(callback, applyBeforeValidation, global = true, mutates = false) { + argsert(' [boolean] [boolean] [boolean]', [callback, applyBeforeValidation, global], arguments.length); + if (Array.isArray(callback)) { + for (let i = 0; i < callback.length; i++) { + if (typeof callback[i] !== 'function') { + throw Error('middleware must be a function'); + } + const m = callback[i]; + m.applyBeforeValidation = applyBeforeValidation; + m.global = global; + } + Array.prototype.push.apply(this.globalMiddleware, callback); + } + else if (typeof callback === 'function') { + const m = callback; + m.applyBeforeValidation = applyBeforeValidation; + m.global = global; + m.mutates = mutates; + this.globalMiddleware.push(callback); + } + return this.yargs; + } + addCoerceMiddleware(callback, option) { + const aliases = this.yargs.getAliases(); + this.globalMiddleware = this.globalMiddleware.filter(m => { + const toCheck = [...(aliases[option] || []), option]; + if (!m.option) + return true; + else + return !toCheck.includes(m.option); + }); + callback.option = option; + return this.addMiddleware(callback, true, true, true); + } + getMiddleware() { + return this.globalMiddleware; + } + freeze() { + this.frozens.push([...this.globalMiddleware]); + } + unfreeze() { + const frozen = this.frozens.pop(); + if (frozen !== undefined) + this.globalMiddleware = frozen; + } + reset() { + this.globalMiddleware = this.globalMiddleware.filter(m => m.global); + } +} +export function commandMiddlewareFactory(commandMiddleware) { + if (!commandMiddleware) + return []; + return commandMiddleware.map(middleware => { + middleware.applyBeforeValidation = false; + return middleware; + }); +} +export function applyMiddleware(argv, yargs, middlewares, beforeValidation) { + return middlewares.reduce((acc, middleware) => { + if (middleware.applyBeforeValidation !== beforeValidation) { + return acc; + } + if (middleware.mutates) { + if (middleware.applied) + return acc; + middleware.applied = true; + } + if (isPromise(acc)) { + return acc + .then(initialObj => Promise.all([initialObj, middleware(initialObj, yargs)])) + .then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj)); + } + else { + const result = middleware(acc, yargs); + return isPromise(result) + ? result.then(middlewareObj => Object.assign(acc, middlewareObj)) + : Object.assign(acc, result); + } + }, argv); +} diff --git a/node_modules/yargs/build/lib/parse-command.js b/node_modules/yargs/build/lib/parse-command.js new file mode 100644 index 0000000..4989f53 --- /dev/null +++ b/node_modules/yargs/build/lib/parse-command.js @@ -0,0 +1,32 @@ +export function parseCommand(cmd) { + const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' '); + const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/); + const bregex = /\.*[\][<>]/g; + const firstCommand = splitCommand.shift(); + if (!firstCommand) + throw new Error(`No command found in: ${cmd}`); + const parsedCommand = { + cmd: firstCommand.replace(bregex, ''), + demanded: [], + optional: [], + }; + splitCommand.forEach((cmd, i) => { + let variadic = false; + cmd = cmd.replace(/\s/g, ''); + if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1) + variadic = true; + if (/^\[/.test(cmd)) { + parsedCommand.optional.push({ + cmd: cmd.replace(bregex, '').split('|'), + variadic, + }); + } + else { + parsedCommand.demanded.push({ + cmd: cmd.replace(bregex, '').split('|'), + variadic, + }); + } + }); + return parsedCommand; +} diff --git a/node_modules/yargs/build/lib/typings/common-types.js b/node_modules/yargs/build/lib/typings/common-types.js new file mode 100644 index 0000000..73e1773 --- /dev/null +++ b/node_modules/yargs/build/lib/typings/common-types.js @@ -0,0 +1,9 @@ +export function assertNotStrictEqual(actual, expected, shim, message) { + shim.assert.notStrictEqual(actual, expected, message); +} +export function assertSingleKey(actual, shim) { + shim.assert.strictEqual(typeof actual, 'string'); +} +export function objectKeys(object) { + return Object.keys(object); +} diff --git a/node_modules/yargs/build/lib/typings/yargs-parser-types.js b/node_modules/yargs/build/lib/typings/yargs-parser-types.js new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/yargs/build/lib/typings/yargs-parser-types.js @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/yargs/build/lib/usage.js b/node_modules/yargs/build/lib/usage.js new file mode 100644 index 0000000..0127c13 --- /dev/null +++ b/node_modules/yargs/build/lib/usage.js @@ -0,0 +1,584 @@ +import { objFilter } from './utils/obj-filter.js'; +import { YError } from './yerror.js'; +import setBlocking from './utils/set-blocking.js'; +function isBoolean(fail) { + return typeof fail === 'boolean'; +} +export function usage(yargs, shim) { + const __ = shim.y18n.__; + const self = {}; + const fails = []; + self.failFn = function failFn(f) { + fails.push(f); + }; + let failMessage = null; + let globalFailMessage = null; + let showHelpOnFail = true; + self.showHelpOnFail = function showHelpOnFailFn(arg1 = true, arg2) { + const [enabled, message] = typeof arg1 === 'string' ? [true, arg1] : [arg1, arg2]; + if (yargs.getInternalMethods().isGlobalContext()) { + globalFailMessage = message; + } + failMessage = message; + showHelpOnFail = enabled; + return self; + }; + let failureOutput = false; + self.fail = function fail(msg, err) { + const logger = yargs.getInternalMethods().getLoggerInstance(); + if (fails.length) { + for (let i = fails.length - 1; i >= 0; --i) { + const fail = fails[i]; + if (isBoolean(fail)) { + if (err) + throw err; + else if (msg) + throw Error(msg); + } + else { + fail(msg, err, self); + } + } + } + else { + if (yargs.getExitProcess()) + setBlocking(true); + if (!failureOutput) { + failureOutput = true; + if (showHelpOnFail) { + yargs.showHelp('error'); + logger.error(); + } + if (msg || err) + logger.error(msg || err); + const globalOrCommandFailMessage = failMessage || globalFailMessage; + if (globalOrCommandFailMessage) { + if (msg || err) + logger.error(''); + logger.error(globalOrCommandFailMessage); + } + } + err = err || new YError(msg); + if (yargs.getExitProcess()) { + return yargs.exit(1); + } + else if (yargs.getInternalMethods().hasParseCallback()) { + return yargs.exit(1, err); + } + else { + throw err; + } + } + }; + let usages = []; + let usageDisabled = false; + self.usage = (msg, description) => { + if (msg === null) { + usageDisabled = true; + usages = []; + return self; + } + usageDisabled = false; + usages.push([msg, description || '']); + return self; + }; + self.getUsage = () => { + return usages; + }; + self.getUsageDisabled = () => { + return usageDisabled; + }; + self.getPositionalGroupName = () => { + return __('Positionals:'); + }; + let examples = []; + self.example = (cmd, description) => { + examples.push([cmd, description || '']); + }; + let commands = []; + self.command = function command(cmd, description, isDefault, aliases, deprecated = false) { + if (isDefault) { + commands = commands.map(cmdArray => { + cmdArray[2] = false; + return cmdArray; + }); + } + commands.push([cmd, description || '', isDefault, aliases, deprecated]); + }; + self.getCommands = () => commands; + let descriptions = {}; + self.describe = function describe(keyOrKeys, desc) { + if (Array.isArray(keyOrKeys)) { + keyOrKeys.forEach(k => { + self.describe(k, desc); + }); + } + else if (typeof keyOrKeys === 'object') { + Object.keys(keyOrKeys).forEach(k => { + self.describe(k, keyOrKeys[k]); + }); + } + else { + descriptions[keyOrKeys] = desc; + } + }; + self.getDescriptions = () => descriptions; + let epilogs = []; + self.epilog = msg => { + epilogs.push(msg); + }; + let wrapSet = false; + let wrap; + self.wrap = cols => { + wrapSet = true; + wrap = cols; + }; + self.getWrap = () => { + if (shim.getEnv('YARGS_DISABLE_WRAP')) { + return null; + } + if (!wrapSet) { + wrap = windowWidth(); + wrapSet = true; + } + return wrap; + }; + const deferY18nLookupPrefix = '__yargsString__:'; + self.deferY18nLookup = str => deferY18nLookupPrefix + str; + self.help = function help() { + if (cachedHelpMessage) + return cachedHelpMessage; + normalizeAliases(); + const base$0 = yargs.customScriptName + ? yargs.$0 + : shim.path.basename(yargs.$0); + const demandedOptions = yargs.getDemandedOptions(); + const demandedCommands = yargs.getDemandedCommands(); + const deprecatedOptions = yargs.getDeprecatedOptions(); + const groups = yargs.getGroups(); + const options = yargs.getOptions(); + let keys = []; + keys = keys.concat(Object.keys(descriptions)); + keys = keys.concat(Object.keys(demandedOptions)); + keys = keys.concat(Object.keys(demandedCommands)); + keys = keys.concat(Object.keys(options.default)); + keys = keys.filter(filterHiddenOptions); + keys = Object.keys(keys.reduce((acc, key) => { + if (key !== '_') + acc[key] = true; + return acc; + }, {})); + const theWrap = self.getWrap(); + const ui = shim.cliui({ + width: theWrap, + wrap: !!theWrap, + }); + if (!usageDisabled) { + if (usages.length) { + usages.forEach(usage => { + ui.div({ text: `${usage[0].replace(/\$0/g, base$0)}` }); + if (usage[1]) { + ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] }); + } + }); + ui.div(); + } + else if (commands.length) { + let u = null; + if (demandedCommands._) { + u = `${base$0} <${__('command')}>\n`; + } + else { + u = `${base$0} [${__('command')}]\n`; + } + ui.div(`${u}`); + } + } + if (commands.length > 1 || (commands.length === 1 && !commands[0][2])) { + ui.div(__('Commands:')); + const context = yargs.getInternalMethods().getContext(); + const parentCommands = context.commands.length + ? `${context.commands.join(' ')} ` + : ''; + if (yargs.getInternalMethods().getParserConfiguration()['sort-commands'] === + true) { + commands = commands.sort((a, b) => a[0].localeCompare(b[0])); + } + const prefix = base$0 ? `${base$0} ` : ''; + commands.forEach(command => { + const commandString = `${prefix}${parentCommands}${command[0].replace(/^\$0 ?/, '')}`; + ui.span({ + text: commandString, + padding: [0, 2, 0, 2], + width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4, + }, { text: command[1] }); + const hints = []; + if (command[2]) + hints.push(`[${__('default')}]`); + if (command[3] && command[3].length) { + hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`); + } + if (command[4]) { + if (typeof command[4] === 'string') { + hints.push(`[${__('deprecated: %s', command[4])}]`); + } + else { + hints.push(`[${__('deprecated')}]`); + } + } + if (hints.length) { + ui.div({ + text: hints.join(' '), + padding: [0, 0, 0, 2], + align: 'right', + }); + } + else { + ui.div(); + } + }); + ui.div(); + } + const aliasKeys = (Object.keys(options.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []); + keys = keys.filter(key => !yargs.parsed.newAliases[key] && + aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1)); + const defaultGroup = __('Options:'); + if (!groups[defaultGroup]) + groups[defaultGroup] = []; + addUngroupedKeys(keys, options.alias, groups, defaultGroup); + const isLongSwitch = (sw) => /^--/.test(getText(sw)); + const displayedGroups = Object.keys(groups) + .filter(groupName => groups[groupName].length > 0) + .map(groupName => { + const normalizedKeys = groups[groupName] + .filter(filterHiddenOptions) + .map(key => { + if (aliasKeys.includes(key)) + return key; + for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) { + if ((options.alias[aliasKey] || []).includes(key)) + return aliasKey; + } + return key; + }); + return { groupName, normalizedKeys }; + }) + .filter(({ normalizedKeys }) => normalizedKeys.length > 0) + .map(({ groupName, normalizedKeys }) => { + const switches = normalizedKeys.reduce((acc, key) => { + acc[key] = [key] + .concat(options.alias[key] || []) + .map(sw => { + if (groupName === self.getPositionalGroupName()) + return sw; + else { + return ((/^[0-9]$/.test(sw) + ? options.boolean.includes(key) + ? '-' + : '--' + : sw.length > 1 + ? '--' + : '-') + sw); + } + }) + .sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2) + ? 0 + : isLongSwitch(sw1) + ? 1 + : -1) + .join(', '); + return acc; + }, {}); + return { groupName, normalizedKeys, switches }; + }); + const shortSwitchesUsed = displayedGroups + .filter(({ groupName }) => groupName !== self.getPositionalGroupName()) + .some(({ normalizedKeys, switches }) => !normalizedKeys.every(key => isLongSwitch(switches[key]))); + if (shortSwitchesUsed) { + displayedGroups + .filter(({ groupName }) => groupName !== self.getPositionalGroupName()) + .forEach(({ normalizedKeys, switches }) => { + normalizedKeys.forEach(key => { + if (isLongSwitch(switches[key])) { + switches[key] = addIndentation(switches[key], '-x, '.length); + } + }); + }); + } + displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => { + ui.div(groupName); + normalizedKeys.forEach(key => { + const kswitch = switches[key]; + let desc = descriptions[key] || ''; + let type = null; + if (desc.includes(deferY18nLookupPrefix)) + desc = __(desc.substring(deferY18nLookupPrefix.length)); + if (options.boolean.includes(key)) + type = `[${__('boolean')}]`; + if (options.count.includes(key)) + type = `[${__('count')}]`; + if (options.string.includes(key)) + type = `[${__('string')}]`; + if (options.normalize.includes(key)) + type = `[${__('string')}]`; + if (options.array.includes(key)) + type = `[${__('array')}]`; + if (options.number.includes(key)) + type = `[${__('number')}]`; + const deprecatedExtra = (deprecated) => typeof deprecated === 'string' + ? `[${__('deprecated: %s', deprecated)}]` + : `[${__('deprecated')}]`; + const extra = [ + key in deprecatedOptions + ? deprecatedExtra(deprecatedOptions[key]) + : null, + type, + key in demandedOptions ? `[${__('required')}]` : null, + options.choices && options.choices[key] + ? `[${__('choices:')} ${self.stringifiedValues(options.choices[key])}]` + : null, + defaultString(options.default[key], options.defaultDescription[key]), + ] + .filter(Boolean) + .join(' '); + ui.span({ + text: getText(kswitch), + padding: [0, 2, 0, 2 + getIndentation(kswitch)], + width: maxWidth(switches, theWrap) + 4, + }, desc); + const shouldHideOptionExtras = yargs.getInternalMethods().getUsageConfiguration()['hide-types'] === + true; + if (extra && !shouldHideOptionExtras) + ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' }); + else + ui.div(); + }); + ui.div(); + }); + if (examples.length) { + ui.div(__('Examples:')); + examples.forEach(example => { + example[0] = example[0].replace(/\$0/g, base$0); + }); + examples.forEach(example => { + if (example[1] === '') { + ui.div({ + text: example[0], + padding: [0, 2, 0, 2], + }); + } + else { + ui.div({ + text: example[0], + padding: [0, 2, 0, 2], + width: maxWidth(examples, theWrap) + 4, + }, { + text: example[1], + }); + } + }); + ui.div(); + } + if (epilogs.length > 0) { + const e = epilogs + .map(epilog => epilog.replace(/\$0/g, base$0)) + .join('\n'); + ui.div(`${e}\n`); + } + return ui.toString().replace(/\s*$/, ''); + }; + function maxWidth(table, theWrap, modifier) { + let width = 0; + if (!Array.isArray(table)) { + table = Object.values(table).map(v => [v]); + } + table.forEach(v => { + width = Math.max(shim.stringWidth(modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])) + getIndentation(v[0]), width); + }); + if (theWrap) + width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10)); + return width; + } + function normalizeAliases() { + const demandedOptions = yargs.getDemandedOptions(); + const options = yargs.getOptions(); + (Object.keys(options.alias) || []).forEach(key => { + options.alias[key].forEach(alias => { + if (descriptions[alias]) + self.describe(key, descriptions[alias]); + if (alias in demandedOptions) + yargs.demandOption(key, demandedOptions[alias]); + if (options.boolean.includes(alias)) + yargs.boolean(key); + if (options.count.includes(alias)) + yargs.count(key); + if (options.string.includes(alias)) + yargs.string(key); + if (options.normalize.includes(alias)) + yargs.normalize(key); + if (options.array.includes(alias)) + yargs.array(key); + if (options.number.includes(alias)) + yargs.number(key); + }); + }); + } + let cachedHelpMessage; + self.cacheHelpMessage = function () { + cachedHelpMessage = this.help(); + }; + self.clearCachedHelpMessage = function () { + cachedHelpMessage = undefined; + }; + self.hasCachedHelpMessage = function () { + return !!cachedHelpMessage; + }; + function addUngroupedKeys(keys, aliases, groups, defaultGroup) { + let groupedKeys = []; + let toCheck = null; + Object.keys(groups).forEach(group => { + groupedKeys = groupedKeys.concat(groups[group]); + }); + keys.forEach(key => { + toCheck = [key].concat(aliases[key]); + if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) { + groups[defaultGroup].push(key); + } + }); + return groupedKeys; + } + function filterHiddenOptions(key) { + return (yargs.getOptions().hiddenOptions.indexOf(key) < 0 || + yargs.parsed.argv[yargs.getOptions().showHiddenOpt]); + } + self.showHelp = (level) => { + const logger = yargs.getInternalMethods().getLoggerInstance(); + if (!level) + level = 'error'; + const emit = typeof level === 'function' ? level : logger[level]; + emit(self.help()); + }; + self.functionDescription = fn => { + const description = fn.name + ? shim.Parser.decamelize(fn.name, '-') + : __('generated-value'); + return ['(', description, ')'].join(''); + }; + self.stringifiedValues = function stringifiedValues(values, separator) { + let string = ''; + const sep = separator || ', '; + const array = [].concat(values); + if (!values || !array.length) + return string; + array.forEach(value => { + if (string.length) + string += sep; + string += JSON.stringify(value); + }); + return string; + }; + function defaultString(value, defaultDescription) { + let string = `[${__('default:')} `; + if (value === undefined && !defaultDescription) + return null; + if (defaultDescription) { + string += defaultDescription; + } + else { + switch (typeof value) { + case 'string': + string += `"${value}"`; + break; + case 'object': + string += JSON.stringify(value); + break; + default: + string += value; + } + } + return `${string}]`; + } + function windowWidth() { + const maxWidth = 80; + if (shim.process.stdColumns) { + return Math.min(maxWidth, shim.process.stdColumns); + } + else { + return maxWidth; + } + } + let version = null; + self.version = ver => { + version = ver; + }; + self.showVersion = level => { + const logger = yargs.getInternalMethods().getLoggerInstance(); + if (!level) + level = 'error'; + const emit = typeof level === 'function' ? level : logger[level]; + emit(version); + }; + self.reset = function reset(localLookup) { + failMessage = null; + failureOutput = false; + usages = []; + usageDisabled = false; + epilogs = []; + examples = []; + commands = []; + descriptions = objFilter(descriptions, k => !localLookup[k]); + return self; + }; + const frozens = []; + self.freeze = function freeze() { + frozens.push({ + failMessage, + failureOutput, + usages, + usageDisabled, + epilogs, + examples, + commands, + descriptions, + }); + }; + self.unfreeze = function unfreeze(defaultCommand = false) { + const frozen = frozens.pop(); + if (!frozen) + return; + if (defaultCommand) { + descriptions = { ...frozen.descriptions, ...descriptions }; + commands = [...frozen.commands, ...commands]; + usages = [...frozen.usages, ...usages]; + examples = [...frozen.examples, ...examples]; + epilogs = [...frozen.epilogs, ...epilogs]; + } + else { + ({ + failMessage, + failureOutput, + usages, + usageDisabled, + epilogs, + examples, + commands, + descriptions, + } = frozen); + } + }; + return self; +} +function isIndentedText(text) { + return typeof text === 'object'; +} +function addIndentation(text, indent) { + return isIndentedText(text) + ? { text: text.text, indentation: text.indentation + indent } + : { text, indentation: indent }; +} +function getIndentation(text) { + return isIndentedText(text) ? text.indentation : 0; +} +function getText(text) { + return isIndentedText(text) ? text.text : text; +} diff --git a/node_modules/yargs/build/lib/utils/apply-extends.js b/node_modules/yargs/build/lib/utils/apply-extends.js new file mode 100644 index 0000000..0e593b4 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/apply-extends.js @@ -0,0 +1,59 @@ +import { YError } from '../yerror.js'; +let previouslyVisitedConfigs = []; +let shim; +export function applyExtends(config, cwd, mergeExtends, _shim) { + shim = _shim; + let defaultConfig = {}; + if (Object.prototype.hasOwnProperty.call(config, 'extends')) { + if (typeof config.extends !== 'string') + return defaultConfig; + const isPath = /\.json|\..*rc$/.test(config.extends); + let pathToDefault = null; + if (!isPath) { + try { + pathToDefault = require.resolve(config.extends); + } + catch (_err) { + return config; + } + } + else { + pathToDefault = getPathToDefaultConfig(cwd, config.extends); + } + checkForCircularExtends(pathToDefault); + previouslyVisitedConfigs.push(pathToDefault); + defaultConfig = isPath + ? JSON.parse(shim.readFileSync(pathToDefault, 'utf8')) + : require(config.extends); + delete config.extends; + defaultConfig = applyExtends(defaultConfig, shim.path.dirname(pathToDefault), mergeExtends, shim); + } + previouslyVisitedConfigs = []; + return mergeExtends + ? mergeDeep(defaultConfig, config) + : Object.assign({}, defaultConfig, config); +} +function checkForCircularExtends(cfgPath) { + if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) { + throw new YError(`Circular extended configurations: '${cfgPath}'.`); + } +} +function getPathToDefaultConfig(cwd, pathToExtend) { + return shim.path.resolve(cwd, pathToExtend); +} +function mergeDeep(config1, config2) { + const target = {}; + function isObject(obj) { + return obj && typeof obj === 'object' && !Array.isArray(obj); + } + Object.assign(target, config1); + for (const key of Object.keys(config2)) { + if (isObject(config2[key]) && isObject(target[key])) { + target[key] = mergeDeep(config1[key], config2[key]); + } + else { + target[key] = config2[key]; + } + } + return target; +} diff --git a/node_modules/yargs/build/lib/utils/is-promise.js b/node_modules/yargs/build/lib/utils/is-promise.js new file mode 100644 index 0000000..d250c08 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/is-promise.js @@ -0,0 +1,5 @@ +export function isPromise(maybePromise) { + return (!!maybePromise && + !!maybePromise.then && + typeof maybePromise.then === 'function'); +} diff --git a/node_modules/yargs/build/lib/utils/levenshtein.js b/node_modules/yargs/build/lib/utils/levenshtein.js new file mode 100644 index 0000000..60575ef --- /dev/null +++ b/node_modules/yargs/build/lib/utils/levenshtein.js @@ -0,0 +1,34 @@ +export function levenshtein(a, b) { + if (a.length === 0) + return b.length; + if (b.length === 0) + return a.length; + const matrix = []; + let i; + for (i = 0; i <= b.length; i++) { + matrix[i] = [i]; + } + let j; + for (j = 0; j <= a.length; j++) { + matrix[0][j] = j; + } + for (i = 1; i <= b.length; i++) { + for (j = 1; j <= a.length; j++) { + if (b.charAt(i - 1) === a.charAt(j - 1)) { + matrix[i][j] = matrix[i - 1][j - 1]; + } + else { + if (i > 1 && + j > 1 && + b.charAt(i - 2) === a.charAt(j - 1) && + b.charAt(i - 1) === a.charAt(j - 2)) { + matrix[i][j] = matrix[i - 2][j - 2] + 1; + } + else { + matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1)); + } + } + } + } + return matrix[b.length][a.length]; +} diff --git a/node_modules/yargs/build/lib/utils/maybe-async-result.js b/node_modules/yargs/build/lib/utils/maybe-async-result.js new file mode 100644 index 0000000..8c6a40c --- /dev/null +++ b/node_modules/yargs/build/lib/utils/maybe-async-result.js @@ -0,0 +1,17 @@ +import { isPromise } from './is-promise.js'; +export function maybeAsyncResult(getResult, resultHandler, errorHandler = (err) => { + throw err; +}) { + try { + const result = isFunction(getResult) ? getResult() : getResult; + return isPromise(result) + ? result.then((result) => resultHandler(result)) + : resultHandler(result); + } + catch (err) { + return errorHandler(err); + } +} +function isFunction(arg) { + return typeof arg === 'function'; +} diff --git a/node_modules/yargs/build/lib/utils/obj-filter.js b/node_modules/yargs/build/lib/utils/obj-filter.js new file mode 100644 index 0000000..cd68ad2 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/obj-filter.js @@ -0,0 +1,10 @@ +import { objectKeys } from '../typings/common-types.js'; +export function objFilter(original = {}, filter = () => true) { + const obj = {}; + objectKeys(original).forEach(key => { + if (filter(key, original[key])) { + obj[key] = original[key]; + } + }); + return obj; +} diff --git a/node_modules/yargs/build/lib/utils/process-argv.js b/node_modules/yargs/build/lib/utils/process-argv.js new file mode 100644 index 0000000..74dc9e4 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/process-argv.js @@ -0,0 +1,17 @@ +function getProcessArgvBinIndex() { + if (isBundledElectronApp()) + return 0; + return 1; +} +function isBundledElectronApp() { + return isElectronApp() && !process.defaultApp; +} +function isElectronApp() { + return !!process.versions.electron; +} +export function hideBin(argv) { + return argv.slice(getProcessArgvBinIndex() + 1); +} +export function getProcessArgvBin() { + return process.argv[getProcessArgvBinIndex()]; +} diff --git a/node_modules/yargs/build/lib/utils/set-blocking.js b/node_modules/yargs/build/lib/utils/set-blocking.js new file mode 100644 index 0000000..88fb806 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/set-blocking.js @@ -0,0 +1,12 @@ +export default function setBlocking(blocking) { + if (typeof process === 'undefined') + return; + [process.stdout, process.stderr].forEach(_stream => { + const stream = _stream; + if (stream._handle && + stream.isTTY && + typeof stream._handle.setBlocking === 'function') { + stream._handle.setBlocking(blocking); + } + }); +} diff --git a/node_modules/yargs/build/lib/utils/which-module.js b/node_modules/yargs/build/lib/utils/which-module.js new file mode 100644 index 0000000..5974e22 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/which-module.js @@ -0,0 +1,10 @@ +export default function whichModule(exported) { + if (typeof require === 'undefined') + return null; + for (let i = 0, files = Object.keys(require.cache), mod; i < files.length; i++) { + mod = require.cache[files[i]]; + if (mod.exports === exported) + return mod; + } + return null; +} diff --git a/node_modules/yargs/build/lib/validation.js b/node_modules/yargs/build/lib/validation.js new file mode 100644 index 0000000..bd2e1b8 --- /dev/null +++ b/node_modules/yargs/build/lib/validation.js @@ -0,0 +1,305 @@ +import { argsert } from './argsert.js'; +import { assertNotStrictEqual, } from './typings/common-types.js'; +import { levenshtein as distance } from './utils/levenshtein.js'; +import { objFilter } from './utils/obj-filter.js'; +const specialKeys = ['$0', '--', '_']; +export function validation(yargs, usage, shim) { + const __ = shim.y18n.__; + const __n = shim.y18n.__n; + const self = {}; + self.nonOptionCount = function nonOptionCount(argv) { + const demandedCommands = yargs.getDemandedCommands(); + const positionalCount = argv._.length + (argv['--'] ? argv['--'].length : 0); + const _s = positionalCount - yargs.getInternalMethods().getContext().commands.length; + if (demandedCommands._ && + (_s < demandedCommands._.min || _s > demandedCommands._.max)) { + if (_s < demandedCommands._.min) { + if (demandedCommands._.minMsg !== undefined) { + usage.fail(demandedCommands._.minMsg + ? demandedCommands._.minMsg + .replace(/\$0/g, _s.toString()) + .replace(/\$1/, demandedCommands._.min.toString()) + : null); + } + else { + usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', _s, _s.toString(), demandedCommands._.min.toString())); + } + } + else if (_s > demandedCommands._.max) { + if (demandedCommands._.maxMsg !== undefined) { + usage.fail(demandedCommands._.maxMsg + ? demandedCommands._.maxMsg + .replace(/\$0/g, _s.toString()) + .replace(/\$1/, demandedCommands._.max.toString()) + : null); + } + else { + usage.fail(__n('Too many non-option arguments: got %s, maximum of %s', 'Too many non-option arguments: got %s, maximum of %s', _s, _s.toString(), demandedCommands._.max.toString())); + } + } + } + }; + self.positionalCount = function positionalCount(required, observed) { + if (observed < required) { + usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', observed, observed + '', required + '')); + } + }; + self.requiredArguments = function requiredArguments(argv, demandedOptions) { + let missing = null; + for (const key of Object.keys(demandedOptions)) { + if (!Object.prototype.hasOwnProperty.call(argv, key) || + typeof argv[key] === 'undefined') { + missing = missing || {}; + missing[key] = demandedOptions[key]; + } + } + if (missing) { + const customMsgs = []; + for (const key of Object.keys(missing)) { + const msg = missing[key]; + if (msg && customMsgs.indexOf(msg) < 0) { + customMsgs.push(msg); + } + } + const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : ''; + usage.fail(__n('Missing required argument: %s', 'Missing required arguments: %s', Object.keys(missing).length, Object.keys(missing).join(', ') + customMsg)); + } + }; + self.unknownArguments = function unknownArguments(argv, aliases, positionalMap, isDefaultCommand, checkPositionals = true) { + var _a; + const commandKeys = yargs + .getInternalMethods() + .getCommandInstance() + .getCommands(); + const unknown = []; + const currentContext = yargs.getInternalMethods().getContext(); + Object.keys(argv).forEach(key => { + if (!specialKeys.includes(key) && + !Object.prototype.hasOwnProperty.call(positionalMap, key) && + !Object.prototype.hasOwnProperty.call(yargs.getInternalMethods().getParseContext(), key) && + !self.isValidAndSomeAliasIsNotNew(key, aliases)) { + unknown.push(key); + } + }); + if (checkPositionals && + (currentContext.commands.length > 0 || + commandKeys.length > 0 || + isDefaultCommand)) { + argv._.slice(currentContext.commands.length).forEach(key => { + if (!commandKeys.includes('' + key)) { + unknown.push('' + key); + } + }); + } + if (checkPositionals) { + const demandedCommands = yargs.getDemandedCommands(); + const maxNonOptDemanded = ((_a = demandedCommands._) === null || _a === void 0 ? void 0 : _a.max) || 0; + const expected = currentContext.commands.length + maxNonOptDemanded; + if (expected < argv._.length) { + argv._.slice(expected).forEach(key => { + key = String(key); + if (!currentContext.commands.includes(key) && + !unknown.includes(key)) { + unknown.push(key); + } + }); + } + } + if (unknown.length) { + usage.fail(__n('Unknown argument: %s', 'Unknown arguments: %s', unknown.length, unknown.map(s => (s.trim() ? s : `"${s}"`)).join(', '))); + } + }; + self.unknownCommands = function unknownCommands(argv) { + const commandKeys = yargs + .getInternalMethods() + .getCommandInstance() + .getCommands(); + const unknown = []; + const currentContext = yargs.getInternalMethods().getContext(); + if (currentContext.commands.length > 0 || commandKeys.length > 0) { + argv._.slice(currentContext.commands.length).forEach(key => { + if (!commandKeys.includes('' + key)) { + unknown.push('' + key); + } + }); + } + if (unknown.length > 0) { + usage.fail(__n('Unknown command: %s', 'Unknown commands: %s', unknown.length, unknown.join(', '))); + return true; + } + else { + return false; + } + }; + self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(key, aliases) { + if (!Object.prototype.hasOwnProperty.call(aliases, key)) { + return false; + } + const newAliases = yargs.parsed.newAliases; + return [key, ...aliases[key]].some(a => !Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]); + }; + self.limitedChoices = function limitedChoices(argv) { + const options = yargs.getOptions(); + const invalid = {}; + if (!Object.keys(options.choices).length) + return; + Object.keys(argv).forEach(key => { + if (specialKeys.indexOf(key) === -1 && + Object.prototype.hasOwnProperty.call(options.choices, key)) { + [].concat(argv[key]).forEach(value => { + if (options.choices[key].indexOf(value) === -1 && + value !== undefined) { + invalid[key] = (invalid[key] || []).concat(value); + } + }); + } + }); + const invalidKeys = Object.keys(invalid); + if (!invalidKeys.length) + return; + let msg = __('Invalid values:'); + invalidKeys.forEach(key => { + msg += `\n ${__('Argument: %s, Given: %s, Choices: %s', key, usage.stringifiedValues(invalid[key]), usage.stringifiedValues(options.choices[key]))}`; + }); + usage.fail(msg); + }; + let implied = {}; + self.implies = function implies(key, value) { + argsert(' [array|number|string]', [key, value], arguments.length); + if (typeof key === 'object') { + Object.keys(key).forEach(k => { + self.implies(k, key[k]); + }); + } + else { + yargs.global(key); + if (!implied[key]) { + implied[key] = []; + } + if (Array.isArray(value)) { + value.forEach(i => self.implies(key, i)); + } + else { + assertNotStrictEqual(value, undefined, shim); + implied[key].push(value); + } + } + }; + self.getImplied = function getImplied() { + return implied; + }; + function keyExists(argv, val) { + const num = Number(val); + val = isNaN(num) ? val : num; + if (typeof val === 'number') { + val = argv._.length >= val; + } + else if (val.match(/^--no-.+/)) { + val = val.match(/^--no-(.+)/)[1]; + val = !Object.prototype.hasOwnProperty.call(argv, val); + } + else { + val = Object.prototype.hasOwnProperty.call(argv, val); + } + return val; + } + self.implications = function implications(argv) { + const implyFail = []; + Object.keys(implied).forEach(key => { + const origKey = key; + (implied[key] || []).forEach(value => { + let key = origKey; + const origValue = value; + key = keyExists(argv, key); + value = keyExists(argv, value); + if (key && !value) { + implyFail.push(` ${origKey} -> ${origValue}`); + } + }); + }); + if (implyFail.length) { + let msg = `${__('Implications failed:')}\n`; + implyFail.forEach(value => { + msg += value; + }); + usage.fail(msg); + } + }; + let conflicting = {}; + self.conflicts = function conflicts(key, value) { + argsert(' [array|string]', [key, value], arguments.length); + if (typeof key === 'object') { + Object.keys(key).forEach(k => { + self.conflicts(k, key[k]); + }); + } + else { + yargs.global(key); + if (!conflicting[key]) { + conflicting[key] = []; + } + if (Array.isArray(value)) { + value.forEach(i => self.conflicts(key, i)); + } + else { + conflicting[key].push(value); + } + } + }; + self.getConflicting = () => conflicting; + self.conflicting = function conflictingFn(argv) { + Object.keys(argv).forEach(key => { + if (conflicting[key]) { + conflicting[key].forEach(value => { + if (value && argv[key] !== undefined && argv[value] !== undefined) { + usage.fail(__('Arguments %s and %s are mutually exclusive', key, value)); + } + }); + } + }); + if (yargs.getInternalMethods().getParserConfiguration()['strip-dashed']) { + Object.keys(conflicting).forEach(key => { + conflicting[key].forEach(value => { + if (value && + argv[shim.Parser.camelCase(key)] !== undefined && + argv[shim.Parser.camelCase(value)] !== undefined) { + usage.fail(__('Arguments %s and %s are mutually exclusive', key, value)); + } + }); + }); + } + }; + self.recommendCommands = function recommendCommands(cmd, potentialCommands) { + const threshold = 3; + potentialCommands = potentialCommands.sort((a, b) => b.length - a.length); + let recommended = null; + let bestDistance = Infinity; + for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) { + const d = distance(cmd, candidate); + if (d <= threshold && d < bestDistance) { + bestDistance = d; + recommended = candidate; + } + } + if (recommended) + usage.fail(__('Did you mean %s?', recommended)); + }; + self.reset = function reset(localLookup) { + implied = objFilter(implied, k => !localLookup[k]); + conflicting = objFilter(conflicting, k => !localLookup[k]); + return self; + }; + const frozens = []; + self.freeze = function freeze() { + frozens.push({ + implied, + conflicting, + }); + }; + self.unfreeze = function unfreeze() { + const frozen = frozens.pop(); + assertNotStrictEqual(frozen, undefined, shim); + ({ implied, conflicting } = frozen); + }; + return self; +} diff --git a/node_modules/yargs/build/lib/yargs-factory.js b/node_modules/yargs/build/lib/yargs-factory.js new file mode 100644 index 0000000..c4b1d50 --- /dev/null +++ b/node_modules/yargs/build/lib/yargs-factory.js @@ -0,0 +1,1512 @@ +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _YargsInstance_command, _YargsInstance_cwd, _YargsInstance_context, _YargsInstance_completion, _YargsInstance_completionCommand, _YargsInstance_defaultShowHiddenOpt, _YargsInstance_exitError, _YargsInstance_detectLocale, _YargsInstance_emittedWarnings, _YargsInstance_exitProcess, _YargsInstance_frozens, _YargsInstance_globalMiddleware, _YargsInstance_groups, _YargsInstance_hasOutput, _YargsInstance_helpOpt, _YargsInstance_isGlobalContext, _YargsInstance_logger, _YargsInstance_output, _YargsInstance_options, _YargsInstance_parentRequire, _YargsInstance_parserConfig, _YargsInstance_parseFn, _YargsInstance_parseContext, _YargsInstance_pkgs, _YargsInstance_preservedGroups, _YargsInstance_processArgs, _YargsInstance_recommendCommands, _YargsInstance_shim, _YargsInstance_strict, _YargsInstance_strictCommands, _YargsInstance_strictOptions, _YargsInstance_usage, _YargsInstance_usageConfig, _YargsInstance_versionOpt, _YargsInstance_validation; +import { command as Command, } from './command.js'; +import { assertNotStrictEqual, assertSingleKey, objectKeys, } from './typings/common-types.js'; +import { YError } from './yerror.js'; +import { usage as Usage } from './usage.js'; +import { argsert } from './argsert.js'; +import { completion as Completion, } from './completion.js'; +import { validation as Validation, } from './validation.js'; +import { objFilter } from './utils/obj-filter.js'; +import { applyExtends } from './utils/apply-extends.js'; +import { applyMiddleware, GlobalMiddleware, } from './middleware.js'; +import { isPromise } from './utils/is-promise.js'; +import { maybeAsyncResult } from './utils/maybe-async-result.js'; +import setBlocking from './utils/set-blocking.js'; +export function YargsFactory(_shim) { + return (processArgs = [], cwd = _shim.process.cwd(), parentRequire) => { + const yargs = new YargsInstance(processArgs, cwd, parentRequire, _shim); + Object.defineProperty(yargs, 'argv', { + get: () => { + return yargs.parse(); + }, + enumerable: true, + }); + yargs.help(); + yargs.version(); + return yargs; + }; +} +const kCopyDoubleDash = Symbol('copyDoubleDash'); +const kCreateLogger = Symbol('copyDoubleDash'); +const kDeleteFromParserHintObject = Symbol('deleteFromParserHintObject'); +const kEmitWarning = Symbol('emitWarning'); +const kFreeze = Symbol('freeze'); +const kGetDollarZero = Symbol('getDollarZero'); +const kGetParserConfiguration = Symbol('getParserConfiguration'); +const kGetUsageConfiguration = Symbol('getUsageConfiguration'); +const kGuessLocale = Symbol('guessLocale'); +const kGuessVersion = Symbol('guessVersion'); +const kParsePositionalNumbers = Symbol('parsePositionalNumbers'); +const kPkgUp = Symbol('pkgUp'); +const kPopulateParserHintArray = Symbol('populateParserHintArray'); +const kPopulateParserHintSingleValueDictionary = Symbol('populateParserHintSingleValueDictionary'); +const kPopulateParserHintArrayDictionary = Symbol('populateParserHintArrayDictionary'); +const kPopulateParserHintDictionary = Symbol('populateParserHintDictionary'); +const kSanitizeKey = Symbol('sanitizeKey'); +const kSetKey = Symbol('setKey'); +const kUnfreeze = Symbol('unfreeze'); +const kValidateAsync = Symbol('validateAsync'); +const kGetCommandInstance = Symbol('getCommandInstance'); +const kGetContext = Symbol('getContext'); +const kGetHasOutput = Symbol('getHasOutput'); +const kGetLoggerInstance = Symbol('getLoggerInstance'); +const kGetParseContext = Symbol('getParseContext'); +const kGetUsageInstance = Symbol('getUsageInstance'); +const kGetValidationInstance = Symbol('getValidationInstance'); +const kHasParseCallback = Symbol('hasParseCallback'); +const kIsGlobalContext = Symbol('isGlobalContext'); +const kPostProcess = Symbol('postProcess'); +const kRebase = Symbol('rebase'); +const kReset = Symbol('reset'); +const kRunYargsParserAndExecuteCommands = Symbol('runYargsParserAndExecuteCommands'); +const kRunValidation = Symbol('runValidation'); +const kSetHasOutput = Symbol('setHasOutput'); +const kTrackManuallySetKeys = Symbol('kTrackManuallySetKeys'); +export class YargsInstance { + constructor(processArgs = [], cwd, parentRequire, shim) { + this.customScriptName = false; + this.parsed = false; + _YargsInstance_command.set(this, void 0); + _YargsInstance_cwd.set(this, void 0); + _YargsInstance_context.set(this, { commands: [], fullCommands: [] }); + _YargsInstance_completion.set(this, null); + _YargsInstance_completionCommand.set(this, null); + _YargsInstance_defaultShowHiddenOpt.set(this, 'show-hidden'); + _YargsInstance_exitError.set(this, null); + _YargsInstance_detectLocale.set(this, true); + _YargsInstance_emittedWarnings.set(this, {}); + _YargsInstance_exitProcess.set(this, true); + _YargsInstance_frozens.set(this, []); + _YargsInstance_globalMiddleware.set(this, void 0); + _YargsInstance_groups.set(this, {}); + _YargsInstance_hasOutput.set(this, false); + _YargsInstance_helpOpt.set(this, null); + _YargsInstance_isGlobalContext.set(this, true); + _YargsInstance_logger.set(this, void 0); + _YargsInstance_output.set(this, ''); + _YargsInstance_options.set(this, void 0); + _YargsInstance_parentRequire.set(this, void 0); + _YargsInstance_parserConfig.set(this, {}); + _YargsInstance_parseFn.set(this, null); + _YargsInstance_parseContext.set(this, null); + _YargsInstance_pkgs.set(this, {}); + _YargsInstance_preservedGroups.set(this, {}); + _YargsInstance_processArgs.set(this, void 0); + _YargsInstance_recommendCommands.set(this, false); + _YargsInstance_shim.set(this, void 0); + _YargsInstance_strict.set(this, false); + _YargsInstance_strictCommands.set(this, false); + _YargsInstance_strictOptions.set(this, false); + _YargsInstance_usage.set(this, void 0); + _YargsInstance_usageConfig.set(this, {}); + _YargsInstance_versionOpt.set(this, null); + _YargsInstance_validation.set(this, void 0); + __classPrivateFieldSet(this, _YargsInstance_shim, shim, "f"); + __classPrivateFieldSet(this, _YargsInstance_processArgs, processArgs, "f"); + __classPrivateFieldSet(this, _YargsInstance_cwd, cwd, "f"); + __classPrivateFieldSet(this, _YargsInstance_parentRequire, parentRequire, "f"); + __classPrivateFieldSet(this, _YargsInstance_globalMiddleware, new GlobalMiddleware(this), "f"); + this.$0 = this[kGetDollarZero](); + this[kReset](); + __classPrivateFieldSet(this, _YargsInstance_command, __classPrivateFieldGet(this, _YargsInstance_command, "f"), "f"); + __classPrivateFieldSet(this, _YargsInstance_usage, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), "f"); + __classPrivateFieldSet(this, _YargsInstance_validation, __classPrivateFieldGet(this, _YargsInstance_validation, "f"), "f"); + __classPrivateFieldSet(this, _YargsInstance_options, __classPrivateFieldGet(this, _YargsInstance_options, "f"), "f"); + __classPrivateFieldGet(this, _YargsInstance_options, "f").showHiddenOpt = __classPrivateFieldGet(this, _YargsInstance_defaultShowHiddenOpt, "f"); + __classPrivateFieldSet(this, _YargsInstance_logger, this[kCreateLogger](), "f"); + } + addHelpOpt(opt, msg) { + const defaultHelpOpt = 'help'; + argsert('[string|boolean] [string]', [opt, msg], arguments.length); + if (__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")) { + this[kDeleteFromParserHintObject](__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")); + __classPrivateFieldSet(this, _YargsInstance_helpOpt, null, "f"); + } + if (opt === false && msg === undefined) + return this; + __classPrivateFieldSet(this, _YargsInstance_helpOpt, typeof opt === 'string' ? opt : defaultHelpOpt, "f"); + this.boolean(__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")); + this.describe(__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f"), msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show help')); + return this; + } + help(opt, msg) { + return this.addHelpOpt(opt, msg); + } + addShowHiddenOpt(opt, msg) { + argsert('[string|boolean] [string]', [opt, msg], arguments.length); + if (opt === false && msg === undefined) + return this; + const showHiddenOpt = typeof opt === 'string' ? opt : __classPrivateFieldGet(this, _YargsInstance_defaultShowHiddenOpt, "f"); + this.boolean(showHiddenOpt); + this.describe(showHiddenOpt, msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show hidden options')); + __classPrivateFieldGet(this, _YargsInstance_options, "f").showHiddenOpt = showHiddenOpt; + return this; + } + showHidden(opt, msg) { + return this.addShowHiddenOpt(opt, msg); + } + alias(key, value) { + argsert(' [string|array]', [key, value], arguments.length); + this[kPopulateParserHintArrayDictionary](this.alias.bind(this), 'alias', key, value); + return this; + } + array(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('array', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + boolean(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('boolean', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + check(f, global) { + argsert(' [boolean]', [f, global], arguments.length); + this.middleware((argv, _yargs) => { + return maybeAsyncResult(() => { + return f(argv, _yargs.getOptions()); + }, (result) => { + if (!result) { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(__classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.__('Argument check failed: %s', f.toString())); + } + else if (typeof result === 'string' || result instanceof Error) { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(result.toString(), result); + } + return argv; + }, (err) => { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(err.message ? err.message : err.toString(), err); + return argv; + }); + }, false, global); + return this; + } + choices(key, value) { + argsert(' [string|array]', [key, value], arguments.length); + this[kPopulateParserHintArrayDictionary](this.choices.bind(this), 'choices', key, value); + return this; + } + coerce(keys, value) { + argsert(' [function]', [keys, value], arguments.length); + if (Array.isArray(keys)) { + if (!value) { + throw new YError('coerce callback must be provided'); + } + for (const key of keys) { + this.coerce(key, value); + } + return this; + } + else if (typeof keys === 'object') { + for (const key of Object.keys(keys)) { + this.coerce(key, keys[key]); + } + return this; + } + if (!value) { + throw new YError('coerce callback must be provided'); + } + __classPrivateFieldGet(this, _YargsInstance_options, "f").key[keys] = true; + __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").addCoerceMiddleware((argv, yargs) => { + let aliases; + const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys); + if (!shouldCoerce) { + return argv; + } + return maybeAsyncResult(() => { + aliases = yargs.getAliases(); + return value(argv[keys]); + }, (result) => { + argv[keys] = result; + const stripAliased = yargs + .getInternalMethods() + .getParserConfiguration()['strip-aliased']; + if (aliases[keys] && stripAliased !== true) { + for (const alias of aliases[keys]) { + argv[alias] = result; + } + } + return argv; + }, (err) => { + throw new YError(err.message); + }); + }, keys); + return this; + } + conflicts(key1, key2) { + argsert(' [string|array]', [key1, key2], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").conflicts(key1, key2); + return this; + } + config(key = 'config', msg, parseFn) { + argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length); + if (typeof key === 'object' && !Array.isArray(key)) { + key = applyExtends(key, __classPrivateFieldGet(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()['deep-merge-config'] || false, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []).concat(key); + return this; + } + if (typeof msg === 'function') { + parseFn = msg; + msg = undefined; + } + this.describe(key, msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Path to JSON config file')); + (Array.isArray(key) ? key : [key]).forEach(k => { + __classPrivateFieldGet(this, _YargsInstance_options, "f").config[k] = parseFn || true; + }); + return this; + } + completion(cmd, desc, fn) { + argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length); + if (typeof desc === 'function') { + fn = desc; + desc = undefined; + } + __classPrivateFieldSet(this, _YargsInstance_completionCommand, cmd || __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") || 'completion', "f"); + if (!desc && desc !== false) { + desc = 'generate completion script'; + } + this.command(__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f"), desc); + if (fn) + __classPrivateFieldGet(this, _YargsInstance_completion, "f").registerFunction(fn); + return this; + } + command(cmd, description, builder, handler, middlewares, deprecated) { + argsert(' [string|boolean] [function|object] [function] [array] [boolean|string]', [cmd, description, builder, handler, middlewares, deprecated], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_command, "f").addHandler(cmd, description, builder, handler, middlewares, deprecated); + return this; + } + commands(cmd, description, builder, handler, middlewares, deprecated) { + return this.command(cmd, description, builder, handler, middlewares, deprecated); + } + commandDir(dir, opts) { + argsert(' [object]', [dir, opts], arguments.length); + const req = __classPrivateFieldGet(this, _YargsInstance_parentRequire, "f") || __classPrivateFieldGet(this, _YargsInstance_shim, "f").require; + __classPrivateFieldGet(this, _YargsInstance_command, "f").addDirectory(dir, req, __classPrivateFieldGet(this, _YargsInstance_shim, "f").getCallerFile(), opts); + return this; + } + count(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('count', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + default(key, value, defaultDescription) { + argsert(' [*] [string]', [key, value, defaultDescription], arguments.length); + if (defaultDescription) { + assertSingleKey(key, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = defaultDescription; + } + if (typeof value === 'function') { + assertSingleKey(key, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + if (!__classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key]) + __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = + __classPrivateFieldGet(this, _YargsInstance_usage, "f").functionDescription(value); + value = value.call(); + } + this[kPopulateParserHintSingleValueDictionary](this.default.bind(this), 'default', key, value); + return this; + } + defaults(key, value, defaultDescription) { + return this.default(key, value, defaultDescription); + } + demandCommand(min = 1, max, minMsg, maxMsg) { + argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length); + if (typeof max !== 'number') { + minMsg = max; + max = Infinity; + } + this.global('_', false); + __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedCommands._ = { + min, + max, + minMsg, + maxMsg, + }; + return this; + } + demand(keys, max, msg) { + if (Array.isArray(max)) { + max.forEach(key => { + assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + this.demandOption(key, msg); + }); + max = Infinity; + } + else if (typeof max !== 'number') { + msg = max; + max = Infinity; + } + if (typeof keys === 'number') { + assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + this.demandCommand(keys, max, msg, msg); + } + else if (Array.isArray(keys)) { + keys.forEach(key => { + assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + this.demandOption(key, msg); + }); + } + else { + if (typeof msg === 'string') { + this.demandOption(keys, msg); + } + else if (msg === true || typeof msg === 'undefined') { + this.demandOption(keys); + } + } + return this; + } + demandOption(keys, msg) { + argsert(' [string]', [keys, msg], arguments.length); + this[kPopulateParserHintSingleValueDictionary](this.demandOption.bind(this), 'demandedOptions', keys, msg); + return this; + } + deprecateOption(option, message) { + argsert(' [string|boolean]', [option, message], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_options, "f").deprecatedOptions[option] = message; + return this; + } + describe(keys, description) { + argsert(' [string]', [keys, description], arguments.length); + this[kSetKey](keys, true); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").describe(keys, description); + return this; + } + detectLocale(detect) { + argsert('', [detect], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_detectLocale, detect, "f"); + return this; + } + env(prefix) { + argsert('[string|boolean]', [prefix], arguments.length); + if (prefix === false) + delete __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix; + else + __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix = prefix || ''; + return this; + } + epilogue(msg) { + argsert('', [msg], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").epilog(msg); + return this; + } + epilog(msg) { + return this.epilogue(msg); + } + example(cmd, description) { + argsert(' [string]', [cmd, description], arguments.length); + if (Array.isArray(cmd)) { + cmd.forEach(exampleParams => this.example(...exampleParams)); + } + else { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").example(cmd, description); + } + return this; + } + exit(code, err) { + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + __classPrivateFieldSet(this, _YargsInstance_exitError, err, "f"); + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.exit(code); + } + exitProcess(enabled = true) { + argsert('[boolean]', [enabled], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_exitProcess, enabled, "f"); + return this; + } + fail(f) { + argsert('', [f], arguments.length); + if (typeof f === 'boolean' && f !== false) { + throw new YError("Invalid first argument. Expected function or boolean 'false'"); + } + __classPrivateFieldGet(this, _YargsInstance_usage, "f").failFn(f); + return this; + } + getAliases() { + return this.parsed ? this.parsed.aliases : {}; + } + async getCompletion(args, done) { + argsert(' [function]', [args, done], arguments.length); + if (!done) { + return new Promise((resolve, reject) => { + __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(args, (err, completions) => { + if (err) + reject(err); + else + resolve(completions); + }); + }); + } + else { + return __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(args, done); + } + } + getDemandedOptions() { + argsert([], 0); + return __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedOptions; + } + getDemandedCommands() { + argsert([], 0); + return __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedCommands; + } + getDeprecatedOptions() { + argsert([], 0); + return __classPrivateFieldGet(this, _YargsInstance_options, "f").deprecatedOptions; + } + getDetectLocale() { + return __classPrivateFieldGet(this, _YargsInstance_detectLocale, "f"); + } + getExitProcess() { + return __classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"); + } + getGroups() { + return Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_groups, "f"), __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")); + } + getHelp() { + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + if (!__classPrivateFieldGet(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) { + if (!this.parsed) { + const parse = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet(this, _YargsInstance_processArgs, "f"), undefined, undefined, 0, true); + if (isPromise(parse)) { + return parse.then(() => { + return __classPrivateFieldGet(this, _YargsInstance_usage, "f").help(); + }); + } + } + const builderResponse = __classPrivateFieldGet(this, _YargsInstance_command, "f").runDefaultBuilderOn(this); + if (isPromise(builderResponse)) { + return builderResponse.then(() => { + return __classPrivateFieldGet(this, _YargsInstance_usage, "f").help(); + }); + } + } + return Promise.resolve(__classPrivateFieldGet(this, _YargsInstance_usage, "f").help()); + } + getOptions() { + return __classPrivateFieldGet(this, _YargsInstance_options, "f"); + } + getStrict() { + return __classPrivateFieldGet(this, _YargsInstance_strict, "f"); + } + getStrictCommands() { + return __classPrivateFieldGet(this, _YargsInstance_strictCommands, "f"); + } + getStrictOptions() { + return __classPrivateFieldGet(this, _YargsInstance_strictOptions, "f"); + } + global(globals, global) { + argsert(' [boolean]', [globals, global], arguments.length); + globals = [].concat(globals); + if (global !== false) { + __classPrivateFieldGet(this, _YargsInstance_options, "f").local = __classPrivateFieldGet(this, _YargsInstance_options, "f").local.filter(l => globals.indexOf(l) === -1); + } + else { + globals.forEach(g => { + if (!__classPrivateFieldGet(this, _YargsInstance_options, "f").local.includes(g)) + __classPrivateFieldGet(this, _YargsInstance_options, "f").local.push(g); + }); + } + return this; + } + group(opts, groupName) { + argsert(' ', [opts, groupName], arguments.length); + const existing = __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName] || __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName]; + if (__classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName]) { + delete __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName]; + } + const seen = {}; + __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName] = (existing || []).concat(opts).filter(key => { + if (seen[key]) + return false; + return (seen[key] = true); + }); + return this; + } + hide(key) { + argsert('', [key], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_options, "f").hiddenOptions.push(key); + return this; + } + implies(key, value) { + argsert(' [number|string|array]', [key, value], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").implies(key, value); + return this; + } + locale(locale) { + argsert('[string]', [locale], arguments.length); + if (locale === undefined) { + this[kGuessLocale](); + return __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.getLocale(); + } + __classPrivateFieldSet(this, _YargsInstance_detectLocale, false, "f"); + __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.setLocale(locale); + return this; + } + middleware(callback, applyBeforeValidation, global) { + return __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").addMiddleware(callback, !!applyBeforeValidation, global); + } + nargs(key, value) { + argsert(' [number]', [key, value], arguments.length); + this[kPopulateParserHintSingleValueDictionary](this.nargs.bind(this), 'narg', key, value); + return this; + } + normalize(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('normalize', keys); + return this; + } + number(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('number', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + option(key, opt) { + argsert(' [object]', [key, opt], arguments.length); + if (typeof key === 'object') { + Object.keys(key).forEach(k => { + this.options(k, key[k]); + }); + } + else { + if (typeof opt !== 'object') { + opt = {}; + } + this[kTrackManuallySetKeys](key); + if (__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f") && (key === 'version' || (opt === null || opt === void 0 ? void 0 : opt.alias) === 'version')) { + this[kEmitWarning]([ + '"version" is a reserved word.', + 'Please do one of the following:', + '- Disable version with `yargs.version(false)` if using "version" as an option', + '- Use the built-in `yargs.version` method instead (if applicable)', + '- Use a different option key', + 'https://yargs.js.org/docs/#api-reference-version', + ].join('\n'), undefined, 'versionWarning'); + } + __classPrivateFieldGet(this, _YargsInstance_options, "f").key[key] = true; + if (opt.alias) + this.alias(key, opt.alias); + const deprecate = opt.deprecate || opt.deprecated; + if (deprecate) { + this.deprecateOption(key, deprecate); + } + const demand = opt.demand || opt.required || opt.require; + if (demand) { + this.demand(key, demand); + } + if (opt.demandOption) { + this.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined); + } + if (opt.conflicts) { + this.conflicts(key, opt.conflicts); + } + if ('default' in opt) { + this.default(key, opt.default); + } + if (opt.implies !== undefined) { + this.implies(key, opt.implies); + } + if (opt.nargs !== undefined) { + this.nargs(key, opt.nargs); + } + if (opt.config) { + this.config(key, opt.configParser); + } + if (opt.normalize) { + this.normalize(key); + } + if (opt.choices) { + this.choices(key, opt.choices); + } + if (opt.coerce) { + this.coerce(key, opt.coerce); + } + if (opt.group) { + this.group(key, opt.group); + } + if (opt.boolean || opt.type === 'boolean') { + this.boolean(key); + if (opt.alias) + this.boolean(opt.alias); + } + if (opt.array || opt.type === 'array') { + this.array(key); + if (opt.alias) + this.array(opt.alias); + } + if (opt.number || opt.type === 'number') { + this.number(key); + if (opt.alias) + this.number(opt.alias); + } + if (opt.string || opt.type === 'string') { + this.string(key); + if (opt.alias) + this.string(opt.alias); + } + if (opt.count || opt.type === 'count') { + this.count(key); + } + if (typeof opt.global === 'boolean') { + this.global(key, opt.global); + } + if (opt.defaultDescription) { + __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = opt.defaultDescription; + } + if (opt.skipValidation) { + this.skipValidation(key); + } + const desc = opt.describe || opt.description || opt.desc; + const descriptions = __classPrivateFieldGet(this, _YargsInstance_usage, "f").getDescriptions(); + if (!Object.prototype.hasOwnProperty.call(descriptions, key) || + typeof desc === 'string') { + this.describe(key, desc); + } + if (opt.hidden) { + this.hide(key); + } + if (opt.requiresArg) { + this.requiresArg(key); + } + } + return this; + } + options(key, opt) { + return this.option(key, opt); + } + parse(args, shortCircuit, _parseFn) { + argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length); + this[kFreeze](); + if (typeof args === 'undefined') { + args = __classPrivateFieldGet(this, _YargsInstance_processArgs, "f"); + } + if (typeof shortCircuit === 'object') { + __classPrivateFieldSet(this, _YargsInstance_parseContext, shortCircuit, "f"); + shortCircuit = _parseFn; + } + if (typeof shortCircuit === 'function') { + __classPrivateFieldSet(this, _YargsInstance_parseFn, shortCircuit, "f"); + shortCircuit = false; + } + if (!shortCircuit) + __classPrivateFieldSet(this, _YargsInstance_processArgs, args, "f"); + if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) + __classPrivateFieldSet(this, _YargsInstance_exitProcess, false, "f"); + const parsed = this[kRunYargsParserAndExecuteCommands](args, !!shortCircuit); + const tmpParsed = this.parsed; + __classPrivateFieldGet(this, _YargsInstance_completion, "f").setParsed(this.parsed); + if (isPromise(parsed)) { + return parsed + .then(argv => { + if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) + __classPrivateFieldGet(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), argv, __classPrivateFieldGet(this, _YargsInstance_output, "f")); + return argv; + }) + .catch(err => { + if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) { + __classPrivateFieldGet(this, _YargsInstance_parseFn, "f")(err, this.parsed.argv, __classPrivateFieldGet(this, _YargsInstance_output, "f")); + } + throw err; + }) + .finally(() => { + this[kUnfreeze](); + this.parsed = tmpParsed; + }); + } + else { + if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) + __classPrivateFieldGet(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), parsed, __classPrivateFieldGet(this, _YargsInstance_output, "f")); + this[kUnfreeze](); + this.parsed = tmpParsed; + } + return parsed; + } + parseAsync(args, shortCircuit, _parseFn) { + const maybePromise = this.parse(args, shortCircuit, _parseFn); + return !isPromise(maybePromise) + ? Promise.resolve(maybePromise) + : maybePromise; + } + parseSync(args, shortCircuit, _parseFn) { + const maybePromise = this.parse(args, shortCircuit, _parseFn); + if (isPromise(maybePromise)) { + throw new YError('.parseSync() must not be used with asynchronous builders, handlers, or middleware'); + } + return maybePromise; + } + parserConfiguration(config) { + argsert('', [config], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_parserConfig, config, "f"); + return this; + } + pkgConf(key, rootPath) { + argsert(' [string]', [key, rootPath], arguments.length); + let conf = null; + const obj = this[kPkgUp](rootPath || __classPrivateFieldGet(this, _YargsInstance_cwd, "f")); + if (obj[key] && typeof obj[key] === 'object') { + conf = applyExtends(obj[key], rootPath || __classPrivateFieldGet(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()['deep-merge-config'] || false, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []).concat(conf); + } + return this; + } + positional(key, opts) { + argsert(' ', [key, opts], arguments.length); + const supportedOpts = [ + 'default', + 'defaultDescription', + 'implies', + 'normalize', + 'choices', + 'conflicts', + 'coerce', + 'type', + 'describe', + 'desc', + 'description', + 'alias', + ]; + opts = objFilter(opts, (k, v) => { + if (k === 'type' && !['string', 'number', 'boolean'].includes(v)) + return false; + return supportedOpts.includes(k); + }); + const fullCommand = __classPrivateFieldGet(this, _YargsInstance_context, "f").fullCommands[__classPrivateFieldGet(this, _YargsInstance_context, "f").fullCommands.length - 1]; + const parseOptions = fullCommand + ? __classPrivateFieldGet(this, _YargsInstance_command, "f").cmdToParseOptions(fullCommand) + : { + array: [], + alias: {}, + default: {}, + demand: {}, + }; + objectKeys(parseOptions).forEach(pk => { + const parseOption = parseOptions[pk]; + if (Array.isArray(parseOption)) { + if (parseOption.indexOf(key) !== -1) + opts[pk] = true; + } + else { + if (parseOption[key] && !(pk in opts)) + opts[pk] = parseOption[key]; + } + }); + this.group(key, __classPrivateFieldGet(this, _YargsInstance_usage, "f").getPositionalGroupName()); + return this.option(key, opts); + } + recommendCommands(recommend = true) { + argsert('[boolean]', [recommend], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_recommendCommands, recommend, "f"); + return this; + } + required(keys, max, msg) { + return this.demand(keys, max, msg); + } + require(keys, max, msg) { + return this.demand(keys, max, msg); + } + requiresArg(keys) { + argsert(' [number]', [keys], arguments.length); + if (typeof keys === 'string' && __classPrivateFieldGet(this, _YargsInstance_options, "f").narg[keys]) { + return this; + } + else { + this[kPopulateParserHintSingleValueDictionary](this.requiresArg.bind(this), 'narg', keys, NaN); + } + return this; + } + showCompletionScript($0, cmd) { + argsert('[string] [string]', [$0, cmd], arguments.length); + $0 = $0 || this.$0; + __classPrivateFieldGet(this, _YargsInstance_logger, "f").log(__classPrivateFieldGet(this, _YargsInstance_completion, "f").generateCompletionScript($0, cmd || __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") || 'completion')); + return this; + } + showHelp(level) { + argsert('[string|function]', [level], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + if (!__classPrivateFieldGet(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) { + if (!this.parsed) { + const parse = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet(this, _YargsInstance_processArgs, "f"), undefined, undefined, 0, true); + if (isPromise(parse)) { + parse.then(() => { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); + }); + return this; + } + } + const builderResponse = __classPrivateFieldGet(this, _YargsInstance_command, "f").runDefaultBuilderOn(this); + if (isPromise(builderResponse)) { + builderResponse.then(() => { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); + }); + return this; + } + } + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); + return this; + } + scriptName(scriptName) { + this.customScriptName = true; + this.$0 = scriptName; + return this; + } + showHelpOnFail(enabled, message) { + argsert('[boolean|string] [string]', [enabled, message], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelpOnFail(enabled, message); + return this; + } + showVersion(level) { + argsert('[string|function]', [level], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showVersion(level); + return this; + } + skipValidation(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('skipValidation', keys); + return this; + } + strict(enabled) { + argsert('[boolean]', [enabled], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_strict, enabled !== false, "f"); + return this; + } + strictCommands(enabled) { + argsert('[boolean]', [enabled], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_strictCommands, enabled !== false, "f"); + return this; + } + strictOptions(enabled) { + argsert('[boolean]', [enabled], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_strictOptions, enabled !== false, "f"); + return this; + } + string(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('string', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + terminalWidth() { + argsert([], 0); + return __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.stdColumns; + } + updateLocale(obj) { + return this.updateStrings(obj); + } + updateStrings(obj) { + argsert('', [obj], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_detectLocale, false, "f"); + __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.updateLocale(obj); + return this; + } + usage(msg, description, builder, handler) { + argsert(' [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length); + if (description !== undefined) { + assertNotStrictEqual(msg, null, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + if ((msg || '').match(/^\$0( |$)/)) { + return this.command(msg, description, builder, handler); + } + else { + throw new YError('.usage() description must start with $0 if being used as alias for .command()'); + } + } + else { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").usage(msg); + return this; + } + } + usageConfiguration(config) { + argsert('', [config], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_usageConfig, config, "f"); + return this; + } + version(opt, msg, ver) { + const defaultVersionOpt = 'version'; + argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length); + if (__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")) { + this[kDeleteFromParserHintObject](__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").version(undefined); + __classPrivateFieldSet(this, _YargsInstance_versionOpt, null, "f"); + } + if (arguments.length === 0) { + ver = this[kGuessVersion](); + opt = defaultVersionOpt; + } + else if (arguments.length === 1) { + if (opt === false) { + return this; + } + ver = opt; + opt = defaultVersionOpt; + } + else if (arguments.length === 2) { + ver = msg; + msg = undefined; + } + __classPrivateFieldSet(this, _YargsInstance_versionOpt, typeof opt === 'string' ? opt : defaultVersionOpt, "f"); + msg = msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show version number'); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").version(ver || undefined); + this.boolean(__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")); + this.describe(__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f"), msg); + return this; + } + wrap(cols) { + argsert('', [cols], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").wrap(cols); + return this; + } + [(_YargsInstance_command = new WeakMap(), _YargsInstance_cwd = new WeakMap(), _YargsInstance_context = new WeakMap(), _YargsInstance_completion = new WeakMap(), _YargsInstance_completionCommand = new WeakMap(), _YargsInstance_defaultShowHiddenOpt = new WeakMap(), _YargsInstance_exitError = new WeakMap(), _YargsInstance_detectLocale = new WeakMap(), _YargsInstance_emittedWarnings = new WeakMap(), _YargsInstance_exitProcess = new WeakMap(), _YargsInstance_frozens = new WeakMap(), _YargsInstance_globalMiddleware = new WeakMap(), _YargsInstance_groups = new WeakMap(), _YargsInstance_hasOutput = new WeakMap(), _YargsInstance_helpOpt = new WeakMap(), _YargsInstance_isGlobalContext = new WeakMap(), _YargsInstance_logger = new WeakMap(), _YargsInstance_output = new WeakMap(), _YargsInstance_options = new WeakMap(), _YargsInstance_parentRequire = new WeakMap(), _YargsInstance_parserConfig = new WeakMap(), _YargsInstance_parseFn = new WeakMap(), _YargsInstance_parseContext = new WeakMap(), _YargsInstance_pkgs = new WeakMap(), _YargsInstance_preservedGroups = new WeakMap(), _YargsInstance_processArgs = new WeakMap(), _YargsInstance_recommendCommands = new WeakMap(), _YargsInstance_shim = new WeakMap(), _YargsInstance_strict = new WeakMap(), _YargsInstance_strictCommands = new WeakMap(), _YargsInstance_strictOptions = new WeakMap(), _YargsInstance_usage = new WeakMap(), _YargsInstance_usageConfig = new WeakMap(), _YargsInstance_versionOpt = new WeakMap(), _YargsInstance_validation = new WeakMap(), kCopyDoubleDash)](argv) { + if (!argv._ || !argv['--']) + return argv; + argv._.push.apply(argv._, argv['--']); + try { + delete argv['--']; + } + catch (_err) { } + return argv; + } + [kCreateLogger]() { + return { + log: (...args) => { + if (!this[kHasParseCallback]()) + console.log(...args); + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + if (__classPrivateFieldGet(this, _YargsInstance_output, "f").length) + __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + '\n', "f"); + __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + args.join(' '), "f"); + }, + error: (...args) => { + if (!this[kHasParseCallback]()) + console.error(...args); + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + if (__classPrivateFieldGet(this, _YargsInstance_output, "f").length) + __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + '\n', "f"); + __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + args.join(' '), "f"); + }, + }; + } + [kDeleteFromParserHintObject](optionKey) { + objectKeys(__classPrivateFieldGet(this, _YargsInstance_options, "f")).forEach((hintKey) => { + if (((key) => key === 'configObjects')(hintKey)) + return; + const hint = __classPrivateFieldGet(this, _YargsInstance_options, "f")[hintKey]; + if (Array.isArray(hint)) { + if (hint.includes(optionKey)) + hint.splice(hint.indexOf(optionKey), 1); + } + else if (typeof hint === 'object') { + delete hint[optionKey]; + } + }); + delete __classPrivateFieldGet(this, _YargsInstance_usage, "f").getDescriptions()[optionKey]; + } + [kEmitWarning](warning, type, deduplicationId) { + if (!__classPrivateFieldGet(this, _YargsInstance_emittedWarnings, "f")[deduplicationId]) { + __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.emitWarning(warning, type); + __classPrivateFieldGet(this, _YargsInstance_emittedWarnings, "f")[deduplicationId] = true; + } + } + [kFreeze]() { + __classPrivateFieldGet(this, _YargsInstance_frozens, "f").push({ + options: __classPrivateFieldGet(this, _YargsInstance_options, "f"), + configObjects: __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects.slice(0), + exitProcess: __classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"), + groups: __classPrivateFieldGet(this, _YargsInstance_groups, "f"), + strict: __classPrivateFieldGet(this, _YargsInstance_strict, "f"), + strictCommands: __classPrivateFieldGet(this, _YargsInstance_strictCommands, "f"), + strictOptions: __classPrivateFieldGet(this, _YargsInstance_strictOptions, "f"), + completionCommand: __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f"), + output: __classPrivateFieldGet(this, _YargsInstance_output, "f"), + exitError: __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), + hasOutput: __classPrivateFieldGet(this, _YargsInstance_hasOutput, "f"), + parsed: this.parsed, + parseFn: __classPrivateFieldGet(this, _YargsInstance_parseFn, "f"), + parseContext: __classPrivateFieldGet(this, _YargsInstance_parseContext, "f"), + }); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").freeze(); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").freeze(); + __classPrivateFieldGet(this, _YargsInstance_command, "f").freeze(); + __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").freeze(); + } + [kGetDollarZero]() { + let $0 = ''; + let default$0; + if (/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv()[0])) { + default$0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv().slice(1, 2); + } + else { + default$0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv().slice(0, 1); + } + $0 = default$0 + .map(x => { + const b = this[kRebase](__classPrivateFieldGet(this, _YargsInstance_cwd, "f"), x); + return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x; + }) + .join(' ') + .trim(); + if (__classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('_') && + __classPrivateFieldGet(this, _YargsInstance_shim, "f").getProcessArgvBin() === __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('_')) { + $0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f") + .getEnv('_') + .replace(`${__classPrivateFieldGet(this, _YargsInstance_shim, "f").path.dirname(__classPrivateFieldGet(this, _YargsInstance_shim, "f").process.execPath())}/`, ''); + } + return $0; + } + [kGetParserConfiguration]() { + return __classPrivateFieldGet(this, _YargsInstance_parserConfig, "f"); + } + [kGetUsageConfiguration]() { + return __classPrivateFieldGet(this, _YargsInstance_usageConfig, "f"); + } + [kGuessLocale]() { + if (!__classPrivateFieldGet(this, _YargsInstance_detectLocale, "f")) + return; + const locale = __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LC_ALL') || + __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LC_MESSAGES') || + __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LANG') || + __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LANGUAGE') || + 'en_US'; + this.locale(locale.replace(/[.:].*/, '')); + } + [kGuessVersion]() { + const obj = this[kPkgUp](); + return obj.version || 'unknown'; + } + [kParsePositionalNumbers](argv) { + const args = argv['--'] ? argv['--'] : argv._; + for (let i = 0, arg; (arg = args[i]) !== undefined; i++) { + if (__classPrivateFieldGet(this, _YargsInstance_shim, "f").Parser.looksLikeNumber(arg) && + Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))) { + args[i] = Number(arg); + } + } + return argv; + } + [kPkgUp](rootPath) { + const npath = rootPath || '*'; + if (__classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]) + return __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]; + let obj = {}; + try { + let startDir = rootPath || __classPrivateFieldGet(this, _YargsInstance_shim, "f").mainFilename; + if (!rootPath && __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.extname(startDir)) { + startDir = __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.dirname(startDir); + } + const pkgJsonPath = __classPrivateFieldGet(this, _YargsInstance_shim, "f").findUp(startDir, (dir, names) => { + if (names.includes('package.json')) { + return 'package.json'; + } + else { + return undefined; + } + }); + assertNotStrictEqual(pkgJsonPath, undefined, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + obj = JSON.parse(__classPrivateFieldGet(this, _YargsInstance_shim, "f").readFileSync(pkgJsonPath, 'utf8')); + } + catch (_noop) { } + __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath] = obj || {}; + return __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]; + } + [kPopulateParserHintArray](type, keys) { + keys = [].concat(keys); + keys.forEach(key => { + key = this[kSanitizeKey](key); + __classPrivateFieldGet(this, _YargsInstance_options, "f")[type].push(key); + }); + } + [kPopulateParserHintSingleValueDictionary](builder, type, key, value) { + this[kPopulateParserHintDictionary](builder, type, key, value, (type, key, value) => { + __classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] = value; + }); + } + [kPopulateParserHintArrayDictionary](builder, type, key, value) { + this[kPopulateParserHintDictionary](builder, type, key, value, (type, key, value) => { + __classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] = (__classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] || []).concat(value); + }); + } + [kPopulateParserHintDictionary](builder, type, key, value, singleKeyHandler) { + if (Array.isArray(key)) { + key.forEach(k => { + builder(k, value); + }); + } + else if (((key) => typeof key === 'object')(key)) { + for (const k of objectKeys(key)) { + builder(k, key[k]); + } + } + else { + singleKeyHandler(type, this[kSanitizeKey](key), value); + } + } + [kSanitizeKey](key) { + if (key === '__proto__') + return '___proto___'; + return key; + } + [kSetKey](key, set) { + this[kPopulateParserHintSingleValueDictionary](this[kSetKey].bind(this), 'key', key, set); + return this; + } + [kUnfreeze]() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; + const frozen = __classPrivateFieldGet(this, _YargsInstance_frozens, "f").pop(); + assertNotStrictEqual(frozen, undefined, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + let configObjects; + (_a = this, _b = this, _c = this, _d = this, _e = this, _f = this, _g = this, _h = this, _j = this, _k = this, _l = this, _m = this, { + options: ({ set value(_o) { __classPrivateFieldSet(_a, _YargsInstance_options, _o, "f"); } }).value, + configObjects, + exitProcess: ({ set value(_o) { __classPrivateFieldSet(_b, _YargsInstance_exitProcess, _o, "f"); } }).value, + groups: ({ set value(_o) { __classPrivateFieldSet(_c, _YargsInstance_groups, _o, "f"); } }).value, + output: ({ set value(_o) { __classPrivateFieldSet(_d, _YargsInstance_output, _o, "f"); } }).value, + exitError: ({ set value(_o) { __classPrivateFieldSet(_e, _YargsInstance_exitError, _o, "f"); } }).value, + hasOutput: ({ set value(_o) { __classPrivateFieldSet(_f, _YargsInstance_hasOutput, _o, "f"); } }).value, + parsed: this.parsed, + strict: ({ set value(_o) { __classPrivateFieldSet(_g, _YargsInstance_strict, _o, "f"); } }).value, + strictCommands: ({ set value(_o) { __classPrivateFieldSet(_h, _YargsInstance_strictCommands, _o, "f"); } }).value, + strictOptions: ({ set value(_o) { __classPrivateFieldSet(_j, _YargsInstance_strictOptions, _o, "f"); } }).value, + completionCommand: ({ set value(_o) { __classPrivateFieldSet(_k, _YargsInstance_completionCommand, _o, "f"); } }).value, + parseFn: ({ set value(_o) { __classPrivateFieldSet(_l, _YargsInstance_parseFn, _o, "f"); } }).value, + parseContext: ({ set value(_o) { __classPrivateFieldSet(_m, _YargsInstance_parseContext, _o, "f"); } }).value, + } = frozen); + __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = configObjects; + __classPrivateFieldGet(this, _YargsInstance_usage, "f").unfreeze(); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").unfreeze(); + __classPrivateFieldGet(this, _YargsInstance_command, "f").unfreeze(); + __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").unfreeze(); + } + [kValidateAsync](validation, argv) { + return maybeAsyncResult(argv, result => { + validation(result); + return result; + }); + } + getInternalMethods() { + return { + getCommandInstance: this[kGetCommandInstance].bind(this), + getContext: this[kGetContext].bind(this), + getHasOutput: this[kGetHasOutput].bind(this), + getLoggerInstance: this[kGetLoggerInstance].bind(this), + getParseContext: this[kGetParseContext].bind(this), + getParserConfiguration: this[kGetParserConfiguration].bind(this), + getUsageConfiguration: this[kGetUsageConfiguration].bind(this), + getUsageInstance: this[kGetUsageInstance].bind(this), + getValidationInstance: this[kGetValidationInstance].bind(this), + hasParseCallback: this[kHasParseCallback].bind(this), + isGlobalContext: this[kIsGlobalContext].bind(this), + postProcess: this[kPostProcess].bind(this), + reset: this[kReset].bind(this), + runValidation: this[kRunValidation].bind(this), + runYargsParserAndExecuteCommands: this[kRunYargsParserAndExecuteCommands].bind(this), + setHasOutput: this[kSetHasOutput].bind(this), + }; + } + [kGetCommandInstance]() { + return __classPrivateFieldGet(this, _YargsInstance_command, "f"); + } + [kGetContext]() { + return __classPrivateFieldGet(this, _YargsInstance_context, "f"); + } + [kGetHasOutput]() { + return __classPrivateFieldGet(this, _YargsInstance_hasOutput, "f"); + } + [kGetLoggerInstance]() { + return __classPrivateFieldGet(this, _YargsInstance_logger, "f"); + } + [kGetParseContext]() { + return __classPrivateFieldGet(this, _YargsInstance_parseContext, "f") || {}; + } + [kGetUsageInstance]() { + return __classPrivateFieldGet(this, _YargsInstance_usage, "f"); + } + [kGetValidationInstance]() { + return __classPrivateFieldGet(this, _YargsInstance_validation, "f"); + } + [kHasParseCallback]() { + return !!__classPrivateFieldGet(this, _YargsInstance_parseFn, "f"); + } + [kIsGlobalContext]() { + return __classPrivateFieldGet(this, _YargsInstance_isGlobalContext, "f"); + } + [kPostProcess](argv, populateDoubleDash, calledFromCommand, runGlobalMiddleware) { + if (calledFromCommand) + return argv; + if (isPromise(argv)) + return argv; + if (!populateDoubleDash) { + argv = this[kCopyDoubleDash](argv); + } + const parsePositionalNumbers = this[kGetParserConfiguration]()['parse-positional-numbers'] || + this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined; + if (parsePositionalNumbers) { + argv = this[kParsePositionalNumbers](argv); + } + if (runGlobalMiddleware) { + argv = applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false); + } + return argv; + } + [kReset](aliases = {}) { + __classPrivateFieldSet(this, _YargsInstance_options, __classPrivateFieldGet(this, _YargsInstance_options, "f") || {}, "f"); + const tmpOptions = {}; + tmpOptions.local = __classPrivateFieldGet(this, _YargsInstance_options, "f").local || []; + tmpOptions.configObjects = __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []; + const localLookup = {}; + tmpOptions.local.forEach(l => { + localLookup[l] = true; + (aliases[l] || []).forEach(a => { + localLookup[a] = true; + }); + }); + Object.assign(__classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f"), Object.keys(__classPrivateFieldGet(this, _YargsInstance_groups, "f")).reduce((acc, groupName) => { + const keys = __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName].filter(key => !(key in localLookup)); + if (keys.length > 0) { + acc[groupName] = keys; + } + return acc; + }, {})); + __classPrivateFieldSet(this, _YargsInstance_groups, {}, "f"); + const arrayOptions = [ + 'array', + 'boolean', + 'string', + 'skipValidation', + 'count', + 'normalize', + 'number', + 'hiddenOptions', + ]; + const objectOptions = [ + 'narg', + 'key', + 'alias', + 'default', + 'defaultDescription', + 'config', + 'choices', + 'demandedOptions', + 'demandedCommands', + 'deprecatedOptions', + ]; + arrayOptions.forEach(k => { + tmpOptions[k] = (__classPrivateFieldGet(this, _YargsInstance_options, "f")[k] || []).filter((k) => !localLookup[k]); + }); + objectOptions.forEach((k) => { + tmpOptions[k] = objFilter(__classPrivateFieldGet(this, _YargsInstance_options, "f")[k], k => !localLookup[k]); + }); + tmpOptions.envPrefix = __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix; + __classPrivateFieldSet(this, _YargsInstance_options, tmpOptions, "f"); + __classPrivateFieldSet(this, _YargsInstance_usage, __classPrivateFieldGet(this, _YargsInstance_usage, "f") + ? __classPrivateFieldGet(this, _YargsInstance_usage, "f").reset(localLookup) + : Usage(this, __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); + __classPrivateFieldSet(this, _YargsInstance_validation, __classPrivateFieldGet(this, _YargsInstance_validation, "f") + ? __classPrivateFieldGet(this, _YargsInstance_validation, "f").reset(localLookup) + : Validation(this, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); + __classPrivateFieldSet(this, _YargsInstance_command, __classPrivateFieldGet(this, _YargsInstance_command, "f") + ? __classPrivateFieldGet(this, _YargsInstance_command, "f").reset() + : Command(__classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_validation, "f"), __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); + if (!__classPrivateFieldGet(this, _YargsInstance_completion, "f")) + __classPrivateFieldSet(this, _YargsInstance_completion, Completion(this, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_command, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); + __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").reset(); + __classPrivateFieldSet(this, _YargsInstance_completionCommand, null, "f"); + __classPrivateFieldSet(this, _YargsInstance_output, '', "f"); + __classPrivateFieldSet(this, _YargsInstance_exitError, null, "f"); + __classPrivateFieldSet(this, _YargsInstance_hasOutput, false, "f"); + this.parsed = false; + return this; + } + [kRebase](base, dir) { + return __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.relative(base, dir); + } + [kRunYargsParserAndExecuteCommands](args, shortCircuit, calledFromCommand, commandIndex = 0, helpOnly = false) { + let skipValidation = !!calledFromCommand || helpOnly; + args = args || __classPrivateFieldGet(this, _YargsInstance_processArgs, "f"); + __classPrivateFieldGet(this, _YargsInstance_options, "f").__ = __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.__; + __classPrivateFieldGet(this, _YargsInstance_options, "f").configuration = this[kGetParserConfiguration](); + const populateDoubleDash = !!__classPrivateFieldGet(this, _YargsInstance_options, "f").configuration['populate--']; + const config = Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_options, "f").configuration, { + 'populate--': true, + }); + const parsed = __classPrivateFieldGet(this, _YargsInstance_shim, "f").Parser.detailed(args, Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_options, "f"), { + configuration: { 'parse-positional-numbers': false, ...config }, + })); + const argv = Object.assign(parsed.argv, __classPrivateFieldGet(this, _YargsInstance_parseContext, "f")); + let argvPromise = undefined; + const aliases = parsed.aliases; + let helpOptSet = false; + let versionOptSet = false; + Object.keys(argv).forEach(key => { + if (key === __classPrivateFieldGet(this, _YargsInstance_helpOpt, "f") && argv[key]) { + helpOptSet = true; + } + else if (key === __classPrivateFieldGet(this, _YargsInstance_versionOpt, "f") && argv[key]) { + versionOptSet = true; + } + }); + argv.$0 = this.$0; + this.parsed = parsed; + if (commandIndex === 0) { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").clearCachedHelpMessage(); + } + try { + this[kGuessLocale](); + if (shortCircuit) { + return this[kPostProcess](argv, populateDoubleDash, !!calledFromCommand, false); + } + if (__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")) { + const helpCmds = [__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")] + .concat(aliases[__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")] || []) + .filter(k => k.length > 1); + if (helpCmds.includes('' + argv._[argv._.length - 1])) { + argv._.pop(); + helpOptSet = true; + } + } + __classPrivateFieldSet(this, _YargsInstance_isGlobalContext, false, "f"); + const handlerKeys = __classPrivateFieldGet(this, _YargsInstance_command, "f").getCommands(); + const requestCompletions = __classPrivateFieldGet(this, _YargsInstance_completion, "f").completionKey in argv; + const skipRecommendation = helpOptSet || requestCompletions || helpOnly; + if (argv._.length) { + if (handlerKeys.length) { + let firstUnknownCommand; + for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) { + cmd = String(argv._[i]); + if (handlerKeys.includes(cmd) && cmd !== __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) { + const innerArgv = __classPrivateFieldGet(this, _YargsInstance_command, "f").runCommand(cmd, this, parsed, i + 1, helpOnly, helpOptSet || versionOptSet || helpOnly); + return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false); + } + else if (!firstUnknownCommand && + cmd !== __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) { + firstUnknownCommand = cmd; + break; + } + } + if (!__classPrivateFieldGet(this, _YargsInstance_command, "f").hasDefaultCommand() && + __classPrivateFieldGet(this, _YargsInstance_recommendCommands, "f") && + firstUnknownCommand && + !skipRecommendation) { + __classPrivateFieldGet(this, _YargsInstance_validation, "f").recommendCommands(firstUnknownCommand, handlerKeys); + } + } + if (__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") && + argv._.includes(__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) && + !requestCompletions) { + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + setBlocking(true); + this.showCompletionScript(); + this.exit(0); + } + } + if (__classPrivateFieldGet(this, _YargsInstance_command, "f").hasDefaultCommand() && !skipRecommendation) { + const innerArgv = __classPrivateFieldGet(this, _YargsInstance_command, "f").runCommand(null, this, parsed, 0, helpOnly, helpOptSet || versionOptSet || helpOnly); + return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false); + } + if (requestCompletions) { + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + setBlocking(true); + args = [].concat(args); + const completionArgs = args.slice(args.indexOf(`--${__classPrivateFieldGet(this, _YargsInstance_completion, "f").completionKey}`) + 1); + __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(completionArgs, (err, completions) => { + if (err) + throw new YError(err.message); + (completions || []).forEach(completion => { + __classPrivateFieldGet(this, _YargsInstance_logger, "f").log(completion); + }); + this.exit(0); + }); + return this[kPostProcess](argv, !populateDoubleDash, !!calledFromCommand, false); + } + if (!__classPrivateFieldGet(this, _YargsInstance_hasOutput, "f")) { + if (helpOptSet) { + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + setBlocking(true); + skipValidation = true; + this.showHelp('log'); + this.exit(0); + } + else if (versionOptSet) { + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + setBlocking(true); + skipValidation = true; + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showVersion('log'); + this.exit(0); + } + } + if (!skipValidation && __classPrivateFieldGet(this, _YargsInstance_options, "f").skipValidation.length > 0) { + skipValidation = Object.keys(argv).some(key => __classPrivateFieldGet(this, _YargsInstance_options, "f").skipValidation.indexOf(key) >= 0 && argv[key] === true); + } + if (!skipValidation) { + if (parsed.error) + throw new YError(parsed.error.message); + if (!requestCompletions) { + const validation = this[kRunValidation](aliases, {}, parsed.error); + if (!calledFromCommand) { + argvPromise = applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), true); + } + argvPromise = this[kValidateAsync](validation, argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv); + if (isPromise(argvPromise) && !calledFromCommand) { + argvPromise = argvPromise.then(() => { + return applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false); + }); + } + } + } + } + catch (err) { + if (err instanceof YError) + __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(err.message, err); + else + throw err; + } + return this[kPostProcess](argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv, populateDoubleDash, !!calledFromCommand, true); + } + [kRunValidation](aliases, positionalMap, parseErrors, isDefaultCommand) { + const demandedOptions = { ...this.getDemandedOptions() }; + return (argv) => { + if (parseErrors) + throw new YError(parseErrors.message); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").nonOptionCount(argv); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").requiredArguments(argv, demandedOptions); + let failedStrictCommands = false; + if (__classPrivateFieldGet(this, _YargsInstance_strictCommands, "f")) { + failedStrictCommands = __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownCommands(argv); + } + if (__classPrivateFieldGet(this, _YargsInstance_strict, "f") && !failedStrictCommands) { + __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, positionalMap, !!isDefaultCommand); + } + else if (__classPrivateFieldGet(this, _YargsInstance_strictOptions, "f")) { + __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, {}, false, false); + } + __classPrivateFieldGet(this, _YargsInstance_validation, "f").limitedChoices(argv); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").implications(argv); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").conflicting(argv); + }; + } + [kSetHasOutput]() { + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + } + [kTrackManuallySetKeys](keys) { + if (typeof keys === 'string') { + __classPrivateFieldGet(this, _YargsInstance_options, "f").key[keys] = true; + } + else { + for (const k of keys) { + __classPrivateFieldGet(this, _YargsInstance_options, "f").key[k] = true; + } + } + } +} +export function isYargsInstance(y) { + return !!y && typeof y.getInternalMethods === 'function'; +} diff --git a/node_modules/yargs/build/lib/yerror.js b/node_modules/yargs/build/lib/yerror.js new file mode 100644 index 0000000..7a36684 --- /dev/null +++ b/node_modules/yargs/build/lib/yerror.js @@ -0,0 +1,9 @@ +export class YError extends Error { + constructor(msg) { + super(msg || 'yargs error'); + this.name = 'YError'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, YError); + } + } +} diff --git a/node_modules/yargs/helpers/helpers.mjs b/node_modules/yargs/helpers/helpers.mjs new file mode 100644 index 0000000..3f96b3d --- /dev/null +++ b/node_modules/yargs/helpers/helpers.mjs @@ -0,0 +1,10 @@ +import {applyExtends as _applyExtends} from '../build/lib/utils/apply-extends.js'; +import {hideBin} from '../build/lib/utils/process-argv.js'; +import Parser from 'yargs-parser'; +import shim from '../lib/platform-shims/esm.mjs'; + +const applyExtends = (config, cwd, mergeExtends) => { + return _applyExtends(config, cwd, mergeExtends, shim); +}; + +export {applyExtends, hideBin, Parser}; diff --git a/node_modules/yargs/helpers/index.js b/node_modules/yargs/helpers/index.js new file mode 100644 index 0000000..8ab79a3 --- /dev/null +++ b/node_modules/yargs/helpers/index.js @@ -0,0 +1,14 @@ +const { + applyExtends, + cjsPlatformShim, + Parser, + processArgv, +} = require('../build/index.cjs'); + +module.exports = { + applyExtends: (config, cwd, mergeExtends) => { + return applyExtends(config, cwd, mergeExtends, cjsPlatformShim); + }, + hideBin: processArgv.hideBin, + Parser, +}; diff --git a/node_modules/yargs/helpers/package.json b/node_modules/yargs/helpers/package.json new file mode 100644 index 0000000..5bbefff --- /dev/null +++ b/node_modules/yargs/helpers/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/yargs/index.cjs b/node_modules/yargs/index.cjs new file mode 100644 index 0000000..d1eee82 --- /dev/null +++ b/node_modules/yargs/index.cjs @@ -0,0 +1,53 @@ +'use strict'; +// classic singleton yargs API, to use yargs +// without running as a singleton do: +// require('yargs/yargs')(process.argv.slice(2)) +const {Yargs, processArgv} = require('./build/index.cjs'); + +Argv(processArgv.hideBin(process.argv)); + +module.exports = Argv; + +function Argv(processArgs, cwd) { + const argv = Yargs(processArgs, cwd, require); + singletonify(argv); + // TODO(bcoe): warn if argv.parse() or argv.argv is used directly. + return argv; +} + +function defineGetter(obj, key, getter) { + Object.defineProperty(obj, key, { + configurable: true, + enumerable: true, + get: getter, + }); +} +function lookupGetter(obj, key) { + const desc = Object.getOwnPropertyDescriptor(obj, key); + if (typeof desc !== 'undefined') { + return desc.get; + } +} + +/* Hack an instance of Argv with process.argv into Argv + so people can do + require('yargs')(['--beeble=1','-z','zizzle']).argv + to parse a list of args and + require('yargs').argv + to get a parsed version of process.argv. +*/ +function singletonify(inst) { + [ + ...Object.keys(inst), + ...Object.getOwnPropertyNames(inst.constructor.prototype), + ].forEach(key => { + if (key === 'argv') { + defineGetter(Argv, key, lookupGetter(inst, key)); + } else if (typeof inst[key] === 'function') { + Argv[key] = inst[key].bind(inst); + } else { + defineGetter(Argv, '$0', () => inst.$0); + defineGetter(Argv, 'parsed', () => inst.parsed); + } + }); +} diff --git a/node_modules/yargs/index.mjs b/node_modules/yargs/index.mjs new file mode 100644 index 0000000..c6440b9 --- /dev/null +++ b/node_modules/yargs/index.mjs @@ -0,0 +1,8 @@ +'use strict'; + +// Bootstraps yargs for ESM: +import esmPlatformShim from './lib/platform-shims/esm.mjs'; +import {YargsFactory} from './build/lib/yargs-factory.js'; + +const Yargs = YargsFactory(esmPlatformShim); +export default Yargs; diff --git a/node_modules/yargs/lib/platform-shims/browser.mjs b/node_modules/yargs/lib/platform-shims/browser.mjs new file mode 100644 index 0000000..5f8ec61 --- /dev/null +++ b/node_modules/yargs/lib/platform-shims/browser.mjs @@ -0,0 +1,95 @@ +/* eslint-disable no-unused-vars */ +'use strict'; + +import cliui from 'https://unpkg.com/cliui@7.0.1/index.mjs'; // eslint-disable-line +import Parser from 'https://unpkg.com/yargs-parser@19.0.0/browser.js'; // eslint-disable-line +import {getProcessArgvBin} from '../../build/lib/utils/process-argv.js'; +import {YError} from '../../build/lib/yerror.js'; + +const REQUIRE_ERROR = 'require is not supported in browser'; +const REQUIRE_DIRECTORY_ERROR = + 'loading a directory of commands is not supported in browser'; + +export default { + assert: { + notStrictEqual: (a, b) => { + // noop. + }, + strictEqual: (a, b) => { + // noop. + }, + }, + cliui, + findUp: () => undefined, + getEnv: key => { + // There is no environment in browser: + return undefined; + }, + inspect: console.log, + getCallerFile: () => { + throw new YError(REQUIRE_DIRECTORY_ERROR); + }, + getProcessArgvBin, + mainFilename: 'yargs', + Parser, + path: { + basename: str => str, + dirname: str => str, + extname: str => str, + relative: str => str, + }, + process: { + argv: () => [], + cwd: () => '', + emitWarning: (warning, name) => {}, + execPath: () => '', + // exit is noop browser: + exit: () => {}, + nextTick: cb => { + // eslint-disable-next-line no-undef + window.setTimeout(cb, 1); + }, + stdColumns: 80, + }, + readFileSync: () => { + return ''; + }, + require: () => { + throw new YError(REQUIRE_ERROR); + }, + requireDirectory: () => { + throw new YError(REQUIRE_DIRECTORY_ERROR); + }, + stringWidth: str => { + return [...str].length; + }, + // TODO: replace this with y18n once it's ported to ESM: + y18n: { + __: (...str) => { + if (str.length === 0) return ''; + const args = str.slice(1); + return sprintf(str[0], ...args); + }, + __n: (str1, str2, count, ...args) => { + if (count === 1) { + return sprintf(str1, ...args); + } else { + return sprintf(str2, ...args); + } + }, + getLocale: () => { + return 'en_US'; + }, + setLocale: () => {}, + updateLocale: () => {}, + }, +}; + +function sprintf(_str, ...args) { + let str = ''; + const split = _str.split('%s'); + split.forEach((token, i) => { + str += `${token}${split[i + 1] !== undefined && args[i] ? args[i] : ''}`; + }); + return str; +} diff --git a/node_modules/yargs/lib/platform-shims/esm.mjs b/node_modules/yargs/lib/platform-shims/esm.mjs new file mode 100644 index 0000000..c25baa5 --- /dev/null +++ b/node_modules/yargs/lib/platform-shims/esm.mjs @@ -0,0 +1,73 @@ +'use strict' + +import { notStrictEqual, strictEqual } from 'assert' +import cliui from 'cliui' +import escalade from 'escalade/sync' +import { inspect } from 'util' +import { readFileSync } from 'fs' +import { fileURLToPath } from 'url'; +import Parser from 'yargs-parser' +import { basename, dirname, extname, relative, resolve } from 'path' +import { getProcessArgvBin } from '../../build/lib/utils/process-argv.js' +import { YError } from '../../build/lib/yerror.js' +import y18n from 'y18n' + +const REQUIRE_ERROR = 'require is not supported by ESM' +const REQUIRE_DIRECTORY_ERROR = 'loading a directory of commands is not supported yet for ESM' + +let __dirname; +try { + __dirname = fileURLToPath(import.meta.url); +} catch (e) { + __dirname = process.cwd(); +} +const mainFilename = __dirname.substring(0, __dirname.lastIndexOf('node_modules')); + +export default { + assert: { + notStrictEqual, + strictEqual + }, + cliui, + findUp: escalade, + getEnv: (key) => { + return process.env[key] + }, + inspect, + getCallerFile: () => { + throw new YError(REQUIRE_DIRECTORY_ERROR) + }, + getProcessArgvBin, + mainFilename: mainFilename || process.cwd(), + Parser, + path: { + basename, + dirname, + extname, + relative, + resolve + }, + process: { + argv: () => process.argv, + cwd: process.cwd, + emitWarning: (warning, type) => process.emitWarning(warning, type), + execPath: () => process.execPath, + exit: process.exit, + nextTick: process.nextTick, + stdColumns: typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null + }, + readFileSync, + require: () => { + throw new YError(REQUIRE_ERROR) + }, + requireDirectory: () => { + throw new YError(REQUIRE_DIRECTORY_ERROR) + }, + stringWidth: (str) => { + return [...str].length + }, + y18n: y18n({ + directory: resolve(__dirname, '../../../locales'), + updateFiles: false + }) +} diff --git a/node_modules/yargs/locales/be.json b/node_modules/yargs/locales/be.json new file mode 100644 index 0000000..e28fa30 --- /dev/null +++ b/node_modules/yargs/locales/be.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Каманды:", + "Options:": "Опцыі:", + "Examples:": "Прыклады:", + "boolean": "булевы тып", + "count": "падлік", + "string": "радковы тып", + "number": "лік", + "array": "масіў", + "required": "неабходна", + "default": "па змаўчанні", + "default:": "па змаўчанні:", + "choices:": "магчымасці:", + "aliases:": "аліасы:", + "generated-value": "згенераванае значэнне", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Недастаткова неапцыйных аргументаў: ёсць %s, трэба як мінімум %s", + "other": "Недастаткова неапцыйных аргументаў: ёсць %s, трэба як мінімум %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Занадта шмат неапцыйных аргументаў: ёсць %s, максімум дапушчальна %s", + "other": "Занадта шмат неапцыйных аргументаў: ёсць %s, максімум дапушчальна %s" + }, + "Missing argument value: %s": { + "one": "Не хапае значэння аргументу: %s", + "other": "Не хапае значэнняў аргументаў: %s" + }, + "Missing required argument: %s": { + "one": "Не хапае неабходнага аргументу: %s", + "other": "Не хапае неабходных аргументаў: %s" + }, + "Unknown argument: %s": { + "one": "Невядомы аргумент: %s", + "other": "Невядомыя аргументы: %s" + }, + "Invalid values:": "Несапраўдныя значэння:", + "Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Дадзенае значэнне: %s, Магчымасці: %s", + "Argument check failed: %s": "Праверка аргументаў не ўдалася: %s", + "Implications failed:": "Дадзены аргумент патрабуе наступны дадатковы аргумент:", + "Not enough arguments following: %s": "Недастаткова наступных аргументаў: %s", + "Invalid JSON config file: %s": "Несапраўдны файл канфігурацыі JSON: %s", + "Path to JSON config file": "Шлях да файла канфігурацыі JSON", + "Show help": "Паказаць дапамогу", + "Show version number": "Паказаць нумар версіі", + "Did you mean %s?": "Вы мелі на ўвазе %s?" +} diff --git a/node_modules/yargs/locales/cs.json b/node_modules/yargs/locales/cs.json new file mode 100644 index 0000000..6394875 --- /dev/null +++ b/node_modules/yargs/locales/cs.json @@ -0,0 +1,51 @@ +{ + "Commands:": "Příkazy:", + "Options:": "Možnosti:", + "Examples:": "Příklady:", + "boolean": "logická hodnota", + "count": "počet", + "string": "řetězec", + "number": "číslo", + "array": "pole", + "required": "povinné", + "default": "výchozí", + "default:": "výchozí:", + "choices:": "volby:", + "aliases:": "aliasy:", + "generated-value": "generovaná-hodnota", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Nedostatek argumentů: zadáno %s, je potřeba alespoň %s", + "other": "Nedostatek argumentů: zadáno %s, je potřeba alespoň %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Příliš mnoho argumentů: zadáno %s, maximálně %s", + "other": "Příliš mnoho argumentů: zadáno %s, maximálně %s" + }, + "Missing argument value: %s": { + "one": "Chybí hodnota argumentu: %s", + "other": "Chybí hodnoty argumentů: %s" + }, + "Missing required argument: %s": { + "one": "Chybí požadovaný argument: %s", + "other": "Chybí požadované argumenty: %s" + }, + "Unknown argument: %s": { + "one": "Neznámý argument: %s", + "other": "Neznámé argumenty: %s" + }, + "Invalid values:": "Neplatné hodnoty:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Zadáno: %s, Možnosti: %s", + "Argument check failed: %s": "Kontrola argumentů se nezdařila: %s", + "Implications failed:": "Chybí závislé argumenty:", + "Not enough arguments following: %s": "Následuje nedostatek argumentů: %s", + "Invalid JSON config file: %s": "Neplatný konfigurační soubor JSON: %s", + "Path to JSON config file": "Cesta ke konfiguračnímu souboru JSON", + "Show help": "Zobrazit nápovědu", + "Show version number": "Zobrazit číslo verze", + "Did you mean %s?": "Měl jste na mysli %s?", + "Arguments %s and %s are mutually exclusive" : "Argumenty %s a %s se vzájemně vylučují", + "Positionals:": "Poziční:", + "command": "příkaz", + "deprecated": "zastaralé", + "deprecated: %s": "zastaralé: %s" +} diff --git a/node_modules/yargs/locales/de.json b/node_modules/yargs/locales/de.json new file mode 100644 index 0000000..dc73ec3 --- /dev/null +++ b/node_modules/yargs/locales/de.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Kommandos:", + "Options:": "Optionen:", + "Examples:": "Beispiele:", + "boolean": "boolean", + "count": "Zähler", + "string": "string", + "number": "Zahl", + "array": "array", + "required": "erforderlich", + "default": "Standard", + "default:": "Standard:", + "choices:": "Möglichkeiten:", + "aliases:": "Aliase:", + "generated-value": "Generierter-Wert", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Nicht genügend Argumente ohne Optionen: %s vorhanden, mindestens %s benötigt", + "other": "Nicht genügend Argumente ohne Optionen: %s vorhanden, mindestens %s benötigt" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Zu viele Argumente ohne Optionen: %s vorhanden, maximal %s erlaubt", + "other": "Zu viele Argumente ohne Optionen: %s vorhanden, maximal %s erlaubt" + }, + "Missing argument value: %s": { + "one": "Fehlender Argumentwert: %s", + "other": "Fehlende Argumentwerte: %s" + }, + "Missing required argument: %s": { + "one": "Fehlendes Argument: %s", + "other": "Fehlende Argumente: %s" + }, + "Unknown argument: %s": { + "one": "Unbekanntes Argument: %s", + "other": "Unbekannte Argumente: %s" + }, + "Invalid values:": "Unzulässige Werte:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gegeben: %s, Möglichkeiten: %s", + "Argument check failed: %s": "Argumente-Check fehlgeschlagen: %s", + "Implications failed:": "Fehlende abhängige Argumente:", + "Not enough arguments following: %s": "Nicht genügend Argumente nach: %s", + "Invalid JSON config file: %s": "Fehlerhafte JSON-Config Datei: %s", + "Path to JSON config file": "Pfad zur JSON-Config Datei", + "Show help": "Hilfe anzeigen", + "Show version number": "Version anzeigen", + "Did you mean %s?": "Meintest du %s?" +} diff --git a/node_modules/yargs/locales/en.json b/node_modules/yargs/locales/en.json new file mode 100644 index 0000000..af096a1 --- /dev/null +++ b/node_modules/yargs/locales/en.json @@ -0,0 +1,55 @@ +{ + "Commands:": "Commands:", + "Options:": "Options:", + "Examples:": "Examples:", + "boolean": "boolean", + "count": "count", + "string": "string", + "number": "number", + "array": "array", + "required": "required", + "default": "default", + "default:": "default:", + "choices:": "choices:", + "aliases:": "aliases:", + "generated-value": "generated-value", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Not enough non-option arguments: got %s, need at least %s", + "other": "Not enough non-option arguments: got %s, need at least %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Too many non-option arguments: got %s, maximum of %s", + "other": "Too many non-option arguments: got %s, maximum of %s" + }, + "Missing argument value: %s": { + "one": "Missing argument value: %s", + "other": "Missing argument values: %s" + }, + "Missing required argument: %s": { + "one": "Missing required argument: %s", + "other": "Missing required arguments: %s" + }, + "Unknown argument: %s": { + "one": "Unknown argument: %s", + "other": "Unknown arguments: %s" + }, + "Unknown command: %s": { + "one": "Unknown command: %s", + "other": "Unknown commands: %s" + }, + "Invalid values:": "Invalid values:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Given: %s, Choices: %s", + "Argument check failed: %s": "Argument check failed: %s", + "Implications failed:": "Missing dependent arguments:", + "Not enough arguments following: %s": "Not enough arguments following: %s", + "Invalid JSON config file: %s": "Invalid JSON config file: %s", + "Path to JSON config file": "Path to JSON config file", + "Show help": "Show help", + "Show version number": "Show version number", + "Did you mean %s?": "Did you mean %s?", + "Arguments %s and %s are mutually exclusive" : "Arguments %s and %s are mutually exclusive", + "Positionals:": "Positionals:", + "command": "command", + "deprecated": "deprecated", + "deprecated: %s": "deprecated: %s" +} diff --git a/node_modules/yargs/locales/es.json b/node_modules/yargs/locales/es.json new file mode 100644 index 0000000..d77b461 --- /dev/null +++ b/node_modules/yargs/locales/es.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Comandos:", + "Options:": "Opciones:", + "Examples:": "Ejemplos:", + "boolean": "booleano", + "count": "cuenta", + "string": "cadena de caracteres", + "number": "número", + "array": "tabla", + "required": "requerido", + "default": "defecto", + "default:": "defecto:", + "choices:": "selección:", + "aliases:": "alias:", + "generated-value": "valor-generado", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Hacen falta argumentos no-opcionales: Número recibido %s, necesita por lo menos %s", + "other": "Hacen falta argumentos no-opcionales: Número recibido %s, necesita por lo menos %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Demasiados argumentos no-opcionales: Número recibido %s, máximo es %s", + "other": "Demasiados argumentos no-opcionales: Número recibido %s, máximo es %s" + }, + "Missing argument value: %s": { + "one": "Falta argumento: %s", + "other": "Faltan argumentos: %s" + }, + "Missing required argument: %s": { + "one": "Falta argumento requerido: %s", + "other": "Faltan argumentos requeridos: %s" + }, + "Unknown argument: %s": { + "one": "Argumento desconocido: %s", + "other": "Argumentos desconocidos: %s" + }, + "Invalid values:": "Valores inválidos:", + "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Recibido: %s, Seleccionados: %s", + "Argument check failed: %s": "Verificación de argumento ha fallado: %s", + "Implications failed:": "Implicaciones fallidas:", + "Not enough arguments following: %s": "No hay suficientes argumentos después de: %s", + "Invalid JSON config file: %s": "Archivo de configuración JSON inválido: %s", + "Path to JSON config file": "Ruta al archivo de configuración JSON", + "Show help": "Muestra ayuda", + "Show version number": "Muestra número de versión", + "Did you mean %s?": "Quisiste decir %s?" +} diff --git a/node_modules/yargs/locales/fi.json b/node_modules/yargs/locales/fi.json new file mode 100644 index 0000000..481feb7 --- /dev/null +++ b/node_modules/yargs/locales/fi.json @@ -0,0 +1,49 @@ +{ + "Commands:": "Komennot:", + "Options:": "Valinnat:", + "Examples:": "Esimerkkejä:", + "boolean": "totuusarvo", + "count": "lukumäärä", + "string": "merkkijono", + "number": "numero", + "array": "taulukko", + "required": "pakollinen", + "default": "oletusarvo", + "default:": "oletusarvo:", + "choices:": "vaihtoehdot:", + "aliases:": "aliakset:", + "generated-value": "generoitu-arvo", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Liian vähän argumentteja, jotka eivät ole valintoja: annettu %s, vaaditaan vähintään %s", + "other": "Liian vähän argumentteja, jotka eivät ole valintoja: annettu %s, vaaditaan vähintään %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Liikaa argumentteja, jotka eivät ole valintoja: annettu %s, sallitaan enintään %s", + "other": "Liikaa argumentteja, jotka eivät ole valintoja: annettu %s, sallitaan enintään %s" + }, + "Missing argument value: %s": { + "one": "Argumentin arvo puuttuu: %s", + "other": "Argumentin arvot puuttuvat: %s" + }, + "Missing required argument: %s": { + "one": "Pakollinen argumentti puuttuu: %s", + "other": "Pakollisia argumentteja puuttuu: %s" + }, + "Unknown argument: %s": { + "one": "Tuntematon argumentti: %s", + "other": "Tuntemattomia argumentteja: %s" + }, + "Invalid values:": "Virheelliset arvot:", + "Argument: %s, Given: %s, Choices: %s": "Argumentti: %s, Annettu: %s, Vaihtoehdot: %s", + "Argument check failed: %s": "Argumentin tarkistus epäonnistui: %s", + "Implications failed:": "Riippuvia argumentteja puuttuu:", + "Not enough arguments following: %s": "Argumentin perässä ei ole tarpeeksi argumentteja: %s", + "Invalid JSON config file: %s": "Epävalidi JSON-asetustiedosto: %s", + "Path to JSON config file": "JSON-asetustiedoston polku", + "Show help": "Näytä ohje", + "Show version number": "Näytä versionumero", + "Did you mean %s?": "Tarkoititko %s?", + "Arguments %s and %s are mutually exclusive" : "Argumentit %s ja %s eivät ole yhteensopivat", + "Positionals:": "Sijaintiparametrit:", + "command": "komento" +} diff --git a/node_modules/yargs/locales/fr.json b/node_modules/yargs/locales/fr.json new file mode 100644 index 0000000..edd743f --- /dev/null +++ b/node_modules/yargs/locales/fr.json @@ -0,0 +1,53 @@ +{ + "Commands:": "Commandes :", + "Options:": "Options :", + "Examples:": "Exemples :", + "boolean": "booléen", + "count": "compteur", + "string": "chaîne de caractères", + "number": "nombre", + "array": "tableau", + "required": "requis", + "default": "défaut", + "default:": "défaut :", + "choices:": "choix :", + "aliases:": "alias :", + "generated-value": "valeur générée", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Pas assez d'arguments (hors options) : reçu %s, besoin d'au moins %s", + "other": "Pas assez d'arguments (hors options) : reçus %s, besoin d'au moins %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Trop d'arguments (hors options) : reçu %s, maximum de %s", + "other": "Trop d'arguments (hors options) : reçus %s, maximum de %s" + }, + "Missing argument value: %s": { + "one": "Argument manquant : %s", + "other": "Arguments manquants : %s" + }, + "Missing required argument: %s": { + "one": "Argument requis manquant : %s", + "other": "Arguments requis manquants : %s" + }, + "Unknown argument: %s": { + "one": "Argument inconnu : %s", + "other": "Arguments inconnus : %s" + }, + "Unknown command: %s": { + "one": "Commande inconnue : %s", + "other": "Commandes inconnues : %s" + }, + "Invalid values:": "Valeurs invalides :", + "Argument: %s, Given: %s, Choices: %s": "Argument : %s, donné : %s, choix : %s", + "Argument check failed: %s": "Echec de la vérification de l'argument : %s", + "Implications failed:": "Arguments dépendants manquants :", + "Not enough arguments following: %s": "Pas assez d'arguments après : %s", + "Invalid JSON config file: %s": "Fichier de configuration JSON invalide : %s", + "Path to JSON config file": "Chemin du fichier de configuration JSON", + "Show help": "Affiche l'aide", + "Show version number": "Affiche le numéro de version", + "Did you mean %s?": "Vouliez-vous dire %s ?", + "Arguments %s and %s are mutually exclusive" : "Les arguments %s et %s sont mutuellement exclusifs", + "Positionals:": "Arguments positionnels :", + "command": "commande" +} diff --git a/node_modules/yargs/locales/hi.json b/node_modules/yargs/locales/hi.json new file mode 100644 index 0000000..a9de77c --- /dev/null +++ b/node_modules/yargs/locales/hi.json @@ -0,0 +1,49 @@ +{ + "Commands:": "आदेश:", + "Options:": "विकल्प:", + "Examples:": "उदाहरण:", + "boolean": "सत्यता", + "count": "संख्या", + "string": "वर्णों का तार ", + "number": "अंक", + "array": "सरणी", + "required": "आवश्यक", + "default": "डिफॉल्ट", + "default:": "डिफॉल्ट:", + "choices:": "विकल्प:", + "aliases:": "उपनाम:", + "generated-value": "उत्पन्न-मूल्य", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "पर्याप्त गैर-विकल्प तर्क प्राप्त नहीं: %s प्राप्त, कम से कम %s की आवश्यकता है", + "other": "पर्याप्त गैर-विकल्प तर्क प्राप्त नहीं: %s प्राप्त, कम से कम %s की आवश्यकता है" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "बहुत सारे गैर-विकल्प तर्क: %s प्राप्त, अधिकतम %s मान्य", + "other": "बहुत सारे गैर-विकल्प तर्क: %s प्राप्त, अधिकतम %s मान्य" + }, + "Missing argument value: %s": { + "one": "कुछ तर्को के मूल्य गुम हैं: %s", + "other": "कुछ तर्को के मूल्य गुम हैं: %s" + }, + "Missing required argument: %s": { + "one": "आवश्यक तर्क गुम हैं: %s", + "other": "आवश्यक तर्क गुम हैं: %s" + }, + "Unknown argument: %s": { + "one": "अज्ञात तर्क प्राप्त: %s", + "other": "अज्ञात तर्क प्राप्त: %s" + }, + "Invalid values:": "अमान्य मूल्य:", + "Argument: %s, Given: %s, Choices: %s": "तर्क: %s, प्राप्त: %s, विकल्प: %s", + "Argument check failed: %s": "तर्क जांच विफल: %s", + "Implications failed:": "दिए गए तर्क के लिए अतिरिक्त तर्क की अपेक्षा है:", + "Not enough arguments following: %s": "निम्नलिखित के बाद पर्याप्त तर्क नहीं प्राप्त: %s", + "Invalid JSON config file: %s": "अमान्य JSON config फाइल: %s", + "Path to JSON config file": "JSON config फाइल का पथ", + "Show help": "सहायता दिखाएँ", + "Show version number": "Version संख्या दिखाएँ", + "Did you mean %s?": "क्या आपका मतलब है %s?", + "Arguments %s and %s are mutually exclusive" : "तर्क %s और %s परस्पर अनन्य हैं", + "Positionals:": "स्थानीय:", + "command": "आदेश" +} diff --git a/node_modules/yargs/locales/hu.json b/node_modules/yargs/locales/hu.json new file mode 100644 index 0000000..21492d0 --- /dev/null +++ b/node_modules/yargs/locales/hu.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Parancsok:", + "Options:": "Opciók:", + "Examples:": "Példák:", + "boolean": "boolean", + "count": "számláló", + "string": "szöveg", + "number": "szám", + "array": "tömb", + "required": "kötelező", + "default": "alapértelmezett", + "default:": "alapértelmezett:", + "choices:": "lehetőségek:", + "aliases:": "aliaszok:", + "generated-value": "generált-érték", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Nincs elég nem opcionális argumentum: %s van, legalább %s kell", + "other": "Nincs elég nem opcionális argumentum: %s van, legalább %s kell" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Túl sok nem opciánlis argumentum van: %s van, maximum %s lehet", + "other": "Túl sok nem opciánlis argumentum van: %s van, maximum %s lehet" + }, + "Missing argument value: %s": { + "one": "Hiányzó argumentum érték: %s", + "other": "Hiányzó argumentum értékek: %s" + }, + "Missing required argument: %s": { + "one": "Hiányzó kötelező argumentum: %s", + "other": "Hiányzó kötelező argumentumok: %s" + }, + "Unknown argument: %s": { + "one": "Ismeretlen argumentum: %s", + "other": "Ismeretlen argumentumok: %s" + }, + "Invalid values:": "Érvénytelen érték:", + "Argument: %s, Given: %s, Choices: %s": "Argumentum: %s, Megadott: %s, Lehetőségek: %s", + "Argument check failed: %s": "Argumentum ellenőrzés sikertelen: %s", + "Implications failed:": "Implikációk sikertelenek:", + "Not enough arguments following: %s": "Nem elég argumentum követi: %s", + "Invalid JSON config file: %s": "Érvénytelen JSON konfigurációs file: %s", + "Path to JSON config file": "JSON konfigurációs file helye", + "Show help": "Súgo megjelenítése", + "Show version number": "Verziószám megjelenítése", + "Did you mean %s?": "Erre gondoltál %s?" +} diff --git a/node_modules/yargs/locales/id.json b/node_modules/yargs/locales/id.json new file mode 100644 index 0000000..125867c --- /dev/null +++ b/node_modules/yargs/locales/id.json @@ -0,0 +1,50 @@ + +{ + "Commands:": "Perintah:", + "Options:": "Pilihan:", + "Examples:": "Contoh:", + "boolean": "boolean", + "count": "jumlah", + "number": "nomor", + "string": "string", + "array": "larik", + "required": "diperlukan", + "default": "bawaan", + "default:": "bawaan:", + "aliases:": "istilah lain:", + "choices:": "pilihan:", + "generated-value": "nilai-yang-dihasilkan", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Argumen wajib kurang: hanya %s, minimal %s", + "other": "Argumen wajib kurang: hanya %s, minimal %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Terlalu banyak argumen wajib: ada %s, maksimal %s", + "other": "Terlalu banyak argumen wajib: ada %s, maksimal %s" + }, + "Missing argument value: %s": { + "one": "Kurang argumen: %s", + "other": "Kurang argumen: %s" + }, + "Missing required argument: %s": { + "one": "Kurang argumen wajib: %s", + "other": "Kurang argumen wajib: %s" + }, + "Unknown argument: %s": { + "one": "Argumen tak diketahui: %s", + "other": "Argumen tak diketahui: %s" + }, + "Invalid values:": "Nilai-nilai tidak valid:", + "Argument: %s, Given: %s, Choices: %s": "Argumen: %s, Diberikan: %s, Pilihan: %s", + "Argument check failed: %s": "Pemeriksaan argument gagal: %s", + "Implications failed:": "Implikasi gagal:", + "Not enough arguments following: %s": "Kurang argumen untuk: %s", + "Invalid JSON config file: %s": "Berkas konfigurasi JSON tidak valid: %s", + "Path to JSON config file": "Alamat berkas konfigurasi JSON", + "Show help": "Lihat bantuan", + "Show version number": "Lihat nomor versi", + "Did you mean %s?": "Maksud Anda: %s?", + "Arguments %s and %s are mutually exclusive" : "Argumen %s dan %s saling eksklusif", + "Positionals:": "Posisional-posisional:", + "command": "perintah" +} diff --git a/node_modules/yargs/locales/it.json b/node_modules/yargs/locales/it.json new file mode 100644 index 0000000..fde5756 --- /dev/null +++ b/node_modules/yargs/locales/it.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Comandi:", + "Options:": "Opzioni:", + "Examples:": "Esempi:", + "boolean": "booleano", + "count": "contatore", + "string": "stringa", + "number": "numero", + "array": "vettore", + "required": "richiesto", + "default": "predefinito", + "default:": "predefinito:", + "choices:": "scelte:", + "aliases:": "alias:", + "generated-value": "valore generato", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Numero insufficiente di argomenti non opzione: inseriti %s, richiesti almeno %s", + "other": "Numero insufficiente di argomenti non opzione: inseriti %s, richiesti almeno %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Troppi argomenti non opzione: inseriti %s, massimo possibile %s", + "other": "Troppi argomenti non opzione: inseriti %s, massimo possibile %s" + }, + "Missing argument value: %s": { + "one": "Argomento mancante: %s", + "other": "Argomenti mancanti: %s" + }, + "Missing required argument: %s": { + "one": "Argomento richiesto mancante: %s", + "other": "Argomenti richiesti mancanti: %s" + }, + "Unknown argument: %s": { + "one": "Argomento sconosciuto: %s", + "other": "Argomenti sconosciuti: %s" + }, + "Invalid values:": "Valori non validi:", + "Argument: %s, Given: %s, Choices: %s": "Argomento: %s, Richiesto: %s, Scelte: %s", + "Argument check failed: %s": "Controllo dell'argomento fallito: %s", + "Implications failed:": "Argomenti dipendenti mancanti:", + "Not enough arguments following: %s": "Argomenti insufficienti dopo: %s", + "Invalid JSON config file: %s": "File di configurazione JSON non valido: %s", + "Path to JSON config file": "Percorso del file di configurazione JSON", + "Show help": "Mostra la schermata di aiuto", + "Show version number": "Mostra il numero di versione", + "Did you mean %s?": "Intendi forse %s?" +} diff --git a/node_modules/yargs/locales/ja.json b/node_modules/yargs/locales/ja.json new file mode 100644 index 0000000..3954ae6 --- /dev/null +++ b/node_modules/yargs/locales/ja.json @@ -0,0 +1,51 @@ +{ + "Commands:": "コマンド:", + "Options:": "オプション:", + "Examples:": "例:", + "boolean": "真偽", + "count": "カウント", + "string": "文字列", + "number": "数値", + "array": "配列", + "required": "必須", + "default": "デフォルト", + "default:": "デフォルト:", + "choices:": "選択してください:", + "aliases:": "エイリアス:", + "generated-value": "生成された値", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "オプションではない引数が %s 個では不足しています。少なくとも %s 個の引数が必要です:", + "other": "オプションではない引数が %s 個では不足しています。少なくとも %s 個の引数が必要です:" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "オプションではない引数が %s 個では多すぎます。最大で %s 個までです:", + "other": "オプションではない引数が %s 個では多すぎます。最大で %s 個までです:" + }, + "Missing argument value: %s": { + "one": "引数の値が見つかりません: %s", + "other": "引数の値が見つかりません: %s" + }, + "Missing required argument: %s": { + "one": "必須の引数が見つかりません: %s", + "other": "必須の引数が見つかりません: %s" + }, + "Unknown argument: %s": { + "one": "未知の引数です: %s", + "other": "未知の引数です: %s" + }, + "Invalid values:": "不正な値です:", + "Argument: %s, Given: %s, Choices: %s": "引数は %s です。与えられた値: %s, 選択してください: %s", + "Argument check failed: %s": "引数のチェックに失敗しました: %s", + "Implications failed:": "オプションの組み合わせで不正が生じました:", + "Not enough arguments following: %s": "次の引数が不足しています。: %s", + "Invalid JSON config file: %s": "JSONの設定ファイルが不正です: %s", + "Path to JSON config file": "JSONの設定ファイルまでのpath", + "Show help": "ヘルプを表示", + "Show version number": "バージョンを表示", + "Did you mean %s?": "もしかして %s?", + "Arguments %s and %s are mutually exclusive" : "引数 %s と %s は同時に指定できません", + "Positionals:": "位置:", + "command": "コマンド", + "deprecated": "非推奨", + "deprecated: %s": "非推奨: %s" +} diff --git a/node_modules/yargs/locales/ko.json b/node_modules/yargs/locales/ko.json new file mode 100644 index 0000000..746bc89 --- /dev/null +++ b/node_modules/yargs/locales/ko.json @@ -0,0 +1,49 @@ +{ + "Commands:": "명령:", + "Options:": "옵션:", + "Examples:": "예시:", + "boolean": "불리언", + "count": "개수", + "string": "문자열", + "number": "숫자", + "array": "배열", + "required": "필수", + "default": "기본값", + "default:": "기본값:", + "choices:": "선택지:", + "aliases:": "별칭:", + "generated-value": "생성된 값", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "옵션이 아닌 인수가 충분하지 않습니다: %s개 입력받음, 최소 %s개 입력 필요", + "other": "옵션이 아닌 인수가 충분하지 않습니다: %s개 입력받음, 최소 %s개 입력 필요" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "옵션이 아닌 인수가 너무 많습니다: %s개 입력받음, 최대 %s개 입력 가능", + "other": "옵션이 아닌 인수가 너무 많습니다: %s개 입력받음, 최대 %s개 입력 가능" + }, + "Missing argument value: %s": { + "one": "인수가 주어지지 않았습니다: %s", + "other": "인수가 주어지지 않았습니다: %s" + }, + "Missing required argument: %s": { + "one": "필수 인수가 주어지지 않았습니다: %s", + "other": "필수 인수가 주어지지 않았습니다: %s" + }, + "Unknown argument: %s": { + "one": "알 수 없는 인수입니다: %s", + "other": "알 수 없는 인수입니다: %s" + }, + "Invalid values:": "유효하지 않은 값:", + "Argument: %s, Given: %s, Choices: %s": "인수: %s, 주어진 값: %s, 선택지: %s", + "Argument check failed: %s": "인수 체크에 실패했습니다: %s", + "Implications failed:": "주어진 인수에 필요한 추가 인수가 주어지지 않았습니다:", + "Not enough arguments following: %s": "다음 인수가 주어지지 않았습니다: %s", + "Invalid JSON config file: %s": "유효하지 않은 JSON 설정 파일: %s", + "Path to JSON config file": "JSON 설정 파일 경로", + "Show help": "도움말 표시", + "Show version number": "버전 표시", + "Did you mean %s?": "%s을(를) 찾으시나요?", + "Arguments %s and %s are mutually exclusive" : "인수 %s과(와) %s은(는) 동시에 지정할 수 없습니다", + "Positionals:": "위치:", + "command": "명령" +} diff --git a/node_modules/yargs/locales/nb.json b/node_modules/yargs/locales/nb.json new file mode 100644 index 0000000..6f410ed --- /dev/null +++ b/node_modules/yargs/locales/nb.json @@ -0,0 +1,44 @@ +{ + "Commands:": "Kommandoer:", + "Options:": "Alternativer:", + "Examples:": "Eksempler:", + "boolean": "boolsk", + "count": "antall", + "string": "streng", + "number": "nummer", + "array": "matrise", + "required": "obligatorisk", + "default": "standard", + "default:": "standard:", + "choices:": "valg:", + "generated-value": "generert-verdi", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Ikke nok ikke-alternativ argumenter: fikk %s, trenger minst %s", + "other": "Ikke nok ikke-alternativ argumenter: fikk %s, trenger minst %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "For mange ikke-alternativ argumenter: fikk %s, maksimum %s", + "other": "For mange ikke-alternativ argumenter: fikk %s, maksimum %s" + }, + "Missing argument value: %s": { + "one": "Mangler argument verdi: %s", + "other": "Mangler argument verdier: %s" + }, + "Missing required argument: %s": { + "one": "Mangler obligatorisk argument: %s", + "other": "Mangler obligatoriske argumenter: %s" + }, + "Unknown argument: %s": { + "one": "Ukjent argument: %s", + "other": "Ukjente argumenter: %s" + }, + "Invalid values:": "Ugyldige verdier:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gitt: %s, Valg: %s", + "Argument check failed: %s": "Argumentsjekk mislyktes: %s", + "Implications failed:": "Konsekvensene mislyktes:", + "Not enough arguments following: %s": "Ikke nok følgende argumenter: %s", + "Invalid JSON config file: %s": "Ugyldig JSON konfigurasjonsfil: %s", + "Path to JSON config file": "Bane til JSON konfigurasjonsfil", + "Show help": "Vis hjelp", + "Show version number": "Vis versjonsnummer" +} diff --git a/node_modules/yargs/locales/nl.json b/node_modules/yargs/locales/nl.json new file mode 100644 index 0000000..9ff95c5 --- /dev/null +++ b/node_modules/yargs/locales/nl.json @@ -0,0 +1,49 @@ +{ + "Commands:": "Commando's:", + "Options:": "Opties:", + "Examples:": "Voorbeelden:", + "boolean": "booleaans", + "count": "aantal", + "string": "string", + "number": "getal", + "array": "lijst", + "required": "verplicht", + "default": "standaard", + "default:": "standaard:", + "choices:": "keuzes:", + "aliases:": "aliassen:", + "generated-value": "gegenereerde waarde", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Niet genoeg niet-optie-argumenten: %s gekregen, minstens %s nodig", + "other": "Niet genoeg niet-optie-argumenten: %s gekregen, minstens %s nodig" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Te veel niet-optie-argumenten: %s gekregen, maximum is %s", + "other": "Te veel niet-optie-argumenten: %s gekregen, maximum is %s" + }, + "Missing argument value: %s": { + "one": "Missende argumentwaarde: %s", + "other": "Missende argumentwaarden: %s" + }, + "Missing required argument: %s": { + "one": "Missend verplicht argument: %s", + "other": "Missende verplichte argumenten: %s" + }, + "Unknown argument: %s": { + "one": "Onbekend argument: %s", + "other": "Onbekende argumenten: %s" + }, + "Invalid values:": "Ongeldige waarden:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gegeven: %s, Keuzes: %s", + "Argument check failed: %s": "Argumentcontrole mislukt: %s", + "Implications failed:": "Ontbrekende afhankelijke argumenten:", + "Not enough arguments following: %s": "Niet genoeg argumenten na: %s", + "Invalid JSON config file: %s": "Ongeldig JSON-config-bestand: %s", + "Path to JSON config file": "Pad naar JSON-config-bestand", + "Show help": "Toon help", + "Show version number": "Toon versienummer", + "Did you mean %s?": "Bedoelde u misschien %s?", + "Arguments %s and %s are mutually exclusive": "Argumenten %s en %s kunnen niet tegelijk gebruikt worden", + "Positionals:": "Positie-afhankelijke argumenten", + "command": "commando" +} diff --git a/node_modules/yargs/locales/nn.json b/node_modules/yargs/locales/nn.json new file mode 100644 index 0000000..24479ac --- /dev/null +++ b/node_modules/yargs/locales/nn.json @@ -0,0 +1,44 @@ +{ + "Commands:": "Kommandoar:", + "Options:": "Alternativ:", + "Examples:": "Døme:", + "boolean": "boolsk", + "count": "mengd", + "string": "streng", + "number": "nummer", + "array": "matrise", + "required": "obligatorisk", + "default": "standard", + "default:": "standard:", + "choices:": "val:", + "generated-value": "generert-verdi", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Ikkje nok ikkje-alternativ argument: fekk %s, treng minst %s", + "other": "Ikkje nok ikkje-alternativ argument: fekk %s, treng minst %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "For mange ikkje-alternativ argument: fekk %s, maksimum %s", + "other": "For mange ikkje-alternativ argument: fekk %s, maksimum %s" + }, + "Missing argument value: %s": { + "one": "Manglar argumentverdi: %s", + "other": "Manglar argumentverdiar: %s" + }, + "Missing required argument: %s": { + "one": "Manglar obligatorisk argument: %s", + "other": "Manglar obligatoriske argument: %s" + }, + "Unknown argument: %s": { + "one": "Ukjent argument: %s", + "other": "Ukjende argument: %s" + }, + "Invalid values:": "Ugyldige verdiar:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gjeve: %s, Val: %s", + "Argument check failed: %s": "Argumentsjekk mislukkast: %s", + "Implications failed:": "Konsekvensane mislukkast:", + "Not enough arguments following: %s": "Ikkje nok fylgjande argument: %s", + "Invalid JSON config file: %s": "Ugyldig JSON konfigurasjonsfil: %s", + "Path to JSON config file": "Bane til JSON konfigurasjonsfil", + "Show help": "Vis hjelp", + "Show version number": "Vis versjonsnummer" +} diff --git a/node_modules/yargs/locales/pirate.json b/node_modules/yargs/locales/pirate.json new file mode 100644 index 0000000..dcb5cb7 --- /dev/null +++ b/node_modules/yargs/locales/pirate.json @@ -0,0 +1,13 @@ +{ + "Commands:": "Choose yer command:", + "Options:": "Options for me hearties!", + "Examples:": "Ex. marks the spot:", + "required": "requi-yar-ed", + "Missing required argument: %s": { + "one": "Ye be havin' to set the followin' argument land lubber: %s", + "other": "Ye be havin' to set the followin' arguments land lubber: %s" + }, + "Show help": "Parlay this here code of conduct", + "Show version number": "'Tis the version ye be askin' fer", + "Arguments %s and %s are mutually exclusive" : "Yon scurvy dogs %s and %s be as bad as rum and a prudish wench" +} diff --git a/node_modules/yargs/locales/pl.json b/node_modules/yargs/locales/pl.json new file mode 100644 index 0000000..a41d4bd --- /dev/null +++ b/node_modules/yargs/locales/pl.json @@ -0,0 +1,49 @@ +{ + "Commands:": "Polecenia:", + "Options:": "Opcje:", + "Examples:": "Przykłady:", + "boolean": "boolean", + "count": "ilość", + "string": "ciąg znaków", + "number": "liczba", + "array": "tablica", + "required": "wymagany", + "default": "domyślny", + "default:": "domyślny:", + "choices:": "dostępne:", + "aliases:": "aliasy:", + "generated-value": "wygenerowana-wartość", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Niewystarczająca ilość argumentów: otrzymano %s, wymagane co najmniej %s", + "other": "Niewystarczająca ilość argumentów: otrzymano %s, wymagane co najmniej %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Zbyt duża ilość argumentów: otrzymano %s, wymagane co najwyżej %s", + "other": "Zbyt duża ilość argumentów: otrzymano %s, wymagane co najwyżej %s" + }, + "Missing argument value: %s": { + "one": "Brak wartości dla argumentu: %s", + "other": "Brak wartości dla argumentów: %s" + }, + "Missing required argument: %s": { + "one": "Brak wymaganego argumentu: %s", + "other": "Brak wymaganych argumentów: %s" + }, + "Unknown argument: %s": { + "one": "Nieznany argument: %s", + "other": "Nieznane argumenty: %s" + }, + "Invalid values:": "Nieprawidłowe wartości:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Otrzymano: %s, Dostępne: %s", + "Argument check failed: %s": "Weryfikacja argumentów nie powiodła się: %s", + "Implications failed:": "Założenia nie zostały spełnione:", + "Not enough arguments following: %s": "Niewystarczająca ilość argumentów następujących po: %s", + "Invalid JSON config file: %s": "Nieprawidłowy plik konfiguracyjny JSON: %s", + "Path to JSON config file": "Ścieżka do pliku konfiguracyjnego JSON", + "Show help": "Pokaż pomoc", + "Show version number": "Pokaż numer wersji", + "Did you mean %s?": "Czy chodziło Ci o %s?", + "Arguments %s and %s are mutually exclusive": "Argumenty %s i %s wzajemnie się wykluczają", + "Positionals:": "Pozycyjne:", + "command": "polecenie" +} diff --git a/node_modules/yargs/locales/pt.json b/node_modules/yargs/locales/pt.json new file mode 100644 index 0000000..0c8ac99 --- /dev/null +++ b/node_modules/yargs/locales/pt.json @@ -0,0 +1,45 @@ +{ + "Commands:": "Comandos:", + "Options:": "Opções:", + "Examples:": "Exemplos:", + "boolean": "boolean", + "count": "contagem", + "string": "cadeia de caracteres", + "number": "número", + "array": "arranjo", + "required": "requerido", + "default": "padrão", + "default:": "padrão:", + "choices:": "escolhas:", + "generated-value": "valor-gerado", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Argumentos insuficientes não opcionais: Argumento %s, necessário pelo menos %s", + "other": "Argumentos insuficientes não opcionais: Argumento %s, necessário pelo menos %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Excesso de argumentos não opcionais: recebido %s, máximo de %s", + "other": "Excesso de argumentos não opcionais: recebido %s, máximo de %s" + }, + "Missing argument value: %s": { + "one": "Falta valor de argumento: %s", + "other": "Falta valores de argumento: %s" + }, + "Missing required argument: %s": { + "one": "Falta argumento obrigatório: %s", + "other": "Faltando argumentos obrigatórios: %s" + }, + "Unknown argument: %s": { + "one": "Argumento desconhecido: %s", + "other": "Argumentos desconhecidos: %s" + }, + "Invalid values:": "Valores inválidos:", + "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Dado: %s, Escolhas: %s", + "Argument check failed: %s": "Verificação de argumento falhou: %s", + "Implications failed:": "Implicações falharam:", + "Not enough arguments following: %s": "Insuficientes argumentos a seguir: %s", + "Invalid JSON config file: %s": "Arquivo de configuração em JSON esta inválido: %s", + "Path to JSON config file": "Caminho para o arquivo de configuração em JSON", + "Show help": "Mostra ajuda", + "Show version number": "Mostra número de versão", + "Arguments %s and %s are mutually exclusive" : "Argumentos %s e %s são mutualmente exclusivos" +} diff --git a/node_modules/yargs/locales/pt_BR.json b/node_modules/yargs/locales/pt_BR.json new file mode 100644 index 0000000..eae1ec6 --- /dev/null +++ b/node_modules/yargs/locales/pt_BR.json @@ -0,0 +1,48 @@ +{ + "Commands:": "Comandos:", + "Options:": "Opções:", + "Examples:": "Exemplos:", + "boolean": "booleano", + "count": "contagem", + "string": "string", + "number": "número", + "array": "array", + "required": "obrigatório", + "default:": "padrão:", + "choices:": "opções:", + "aliases:": "sinônimos:", + "generated-value": "valor-gerado", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Argumentos insuficientes: Argumento %s, necessário pelo menos %s", + "other": "Argumentos insuficientes: Argumento %s, necessário pelo menos %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Excesso de argumentos: recebido %s, máximo de %s", + "other": "Excesso de argumentos: recebido %s, máximo de %s" + }, + "Missing argument value: %s": { + "one": "Falta valor de argumento: %s", + "other": "Falta valores de argumento: %s" + }, + "Missing required argument: %s": { + "one": "Falta argumento obrigatório: %s", + "other": "Faltando argumentos obrigatórios: %s" + }, + "Unknown argument: %s": { + "one": "Argumento desconhecido: %s", + "other": "Argumentos desconhecidos: %s" + }, + "Invalid values:": "Valores inválidos:", + "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Dado: %s, Opções: %s", + "Argument check failed: %s": "Verificação de argumento falhou: %s", + "Implications failed:": "Implicações falharam:", + "Not enough arguments following: %s": "Argumentos insuficientes a seguir: %s", + "Invalid JSON config file: %s": "Arquivo JSON de configuração inválido: %s", + "Path to JSON config file": "Caminho para o arquivo JSON de configuração", + "Show help": "Exibe ajuda", + "Show version number": "Exibe a versão", + "Did you mean %s?": "Você quis dizer %s?", + "Arguments %s and %s are mutually exclusive" : "Argumentos %s e %s são mutualmente exclusivos", + "Positionals:": "Posicionais:", + "command": "comando" +} diff --git a/node_modules/yargs/locales/ru.json b/node_modules/yargs/locales/ru.json new file mode 100644 index 0000000..d5c9e32 --- /dev/null +++ b/node_modules/yargs/locales/ru.json @@ -0,0 +1,51 @@ +{ + "Commands:": "Команды:", + "Options:": "Опции:", + "Examples:": "Примеры:", + "boolean": "булевый тип", + "count": "подсчет", + "string": "строковой тип", + "number": "число", + "array": "массив", + "required": "необходимо", + "default": "по умолчанию", + "default:": "по умолчанию:", + "choices:": "возможности:", + "aliases:": "алиасы:", + "generated-value": "генерированное значение", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Недостаточно неопционных аргументов: есть %s, нужно как минимум %s", + "other": "Недостаточно неопционных аргументов: есть %s, нужно как минимум %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Слишком много неопционных аргументов: есть %s, максимум допустимо %s", + "other": "Слишком много неопционных аргументов: есть %s, максимум допустимо %s" + }, + "Missing argument value: %s": { + "one": "Не хватает значения аргумента: %s", + "other": "Не хватает значений аргументов: %s" + }, + "Missing required argument: %s": { + "one": "Не хватает необходимого аргумента: %s", + "other": "Не хватает необходимых аргументов: %s" + }, + "Unknown argument: %s": { + "one": "Неизвестный аргумент: %s", + "other": "Неизвестные аргументы: %s" + }, + "Invalid values:": "Недействительные значения:", + "Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Данное значение: %s, Возможности: %s", + "Argument check failed: %s": "Проверка аргументов не удалась: %s", + "Implications failed:": "Данный аргумент требует следующий дополнительный аргумент:", + "Not enough arguments following: %s": "Недостаточно следующих аргументов: %s", + "Invalid JSON config file: %s": "Недействительный файл конфигурации JSON: %s", + "Path to JSON config file": "Путь к файлу конфигурации JSON", + "Show help": "Показать помощь", + "Show version number": "Показать номер версии", + "Did you mean %s?": "Вы имели в виду %s?", + "Arguments %s and %s are mutually exclusive": "Аргументы %s и %s являются взаимоисключающими", + "Positionals:": "Позиционные аргументы:", + "command": "команда", + "deprecated": "устар.", + "deprecated: %s": "устар.: %s" +} diff --git a/node_modules/yargs/locales/th.json b/node_modules/yargs/locales/th.json new file mode 100644 index 0000000..33b048e --- /dev/null +++ b/node_modules/yargs/locales/th.json @@ -0,0 +1,46 @@ +{ + "Commands:": "คอมมาน", + "Options:": "ออฟชั่น", + "Examples:": "ตัวอย่าง", + "boolean": "บูลีน", + "count": "นับ", + "string": "สตริง", + "number": "ตัวเลข", + "array": "อาเรย์", + "required": "จำเป็น", + "default": "ค่าเริ่มต้", + "default:": "ค่าเริ่มต้น", + "choices:": "ตัวเลือก", + "aliases:": "เอเลียส", + "generated-value": "ค่าที่ถูกสร้างขึ้น", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "ใส่อาร์กิวเมนต์ไม่ครบตามจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการอย่างน้อย %s ค่า", + "other": "ใส่อาร์กิวเมนต์ไม่ครบตามจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการอย่างน้อย %s ค่า" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "ใส่อาร์กิวเมนต์เกินจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการมากที่สุด %s ค่า", + "other": "ใส่อาร์กิวเมนต์เกินจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการมากที่สุด %s ค่า" + }, + "Missing argument value: %s": { + "one": "ค่าอาร์กิวเมนต์ที่ขาดไป: %s", + "other": "ค่าอาร์กิวเมนต์ที่ขาดไป: %s" + }, + "Missing required argument: %s": { + "one": "อาร์กิวเมนต์จำเป็นที่ขาดไป: %s", + "other": "อาร์กิวเมนต์จำเป็นที่ขาดไป: %s" + }, + "Unknown argument: %s": { + "one": "อาร์กิวเมนต์ที่ไม่รู้จัก: %s", + "other": "อาร์กิวเมนต์ที่ไม่รู้จัก: %s" + }, + "Invalid values:": "ค่าไม่ถูกต้อง:", + "Argument: %s, Given: %s, Choices: %s": "อาร์กิวเมนต์: %s, ได้รับ: %s, ตัวเลือก: %s", + "Argument check failed: %s": "ตรวจสอบพบอาร์กิวเมนต์ที่ไม่ถูกต้อง: %s", + "Implications failed:": "Implications ไม่สำเร็จ:", + "Not enough arguments following: %s": "ใส่อาร์กิวเมนต์ไม่ครบ: %s", + "Invalid JSON config file: %s": "ไฟล์คอนฟิค JSON ไม่ถูกต้อง: %s", + "Path to JSON config file": "พาทไฟล์คอนฟิค JSON", + "Show help": "ขอความช่วยเหลือ", + "Show version number": "แสดงตัวเลขเวอร์ชั่น", + "Did you mean %s?": "คุณหมายถึง %s?" +} diff --git a/node_modules/yargs/locales/tr.json b/node_modules/yargs/locales/tr.json new file mode 100644 index 0000000..0d0d2cc --- /dev/null +++ b/node_modules/yargs/locales/tr.json @@ -0,0 +1,48 @@ +{ + "Commands:": "Komutlar:", + "Options:": "Seçenekler:", + "Examples:": "Örnekler:", + "boolean": "boolean", + "count": "sayı", + "string": "string", + "number": "numara", + "array": "array", + "required": "zorunlu", + "default": "varsayılan", + "default:": "varsayılan:", + "choices:": "seçimler:", + "aliases:": "takma adlar:", + "generated-value": "oluşturulan-değer", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Seçenek dışı argümanlar yetersiz: %s bulundu, %s gerekli", + "other": "Seçenek dışı argümanlar yetersiz: %s bulundu, %s gerekli" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Seçenek dışı argümanlar gereğinden fazla: %s bulundu, azami %s", + "other": "Seçenek dışı argümanlar gereğinden fazla: %s bulundu, azami %s" + }, + "Missing argument value: %s": { + "one": "Eksik argüman değeri: %s", + "other": "Eksik argüman değerleri: %s" + }, + "Missing required argument: %s": { + "one": "Eksik zorunlu argüman: %s", + "other": "Eksik zorunlu argümanlar: %s" + }, + "Unknown argument: %s": { + "one": "Bilinmeyen argüman: %s", + "other": "Bilinmeyen argümanlar: %s" + }, + "Invalid values:": "Geçersiz değerler:", + "Argument: %s, Given: %s, Choices: %s": "Argüman: %s, Verilen: %s, Seçimler: %s", + "Argument check failed: %s": "Argüman kontrolü başarısız oldu: %s", + "Implications failed:": "Sonuçlar başarısız oldu:", + "Not enough arguments following: %s": "%s için yeterli argüman bulunamadı", + "Invalid JSON config file: %s": "Geçersiz JSON yapılandırma dosyası: %s", + "Path to JSON config file": "JSON yapılandırma dosya konumu", + "Show help": "Yardım detaylarını göster", + "Show version number": "Versiyon detaylarını göster", + "Did you mean %s?": "Bunu mu demek istediniz: %s?", + "Positionals:": "Sıralılar:", + "command": "komut" +} diff --git a/node_modules/yargs/locales/uk_UA.json b/node_modules/yargs/locales/uk_UA.json new file mode 100644 index 0000000..0af0e99 --- /dev/null +++ b/node_modules/yargs/locales/uk_UA.json @@ -0,0 +1,51 @@ +{ + "Commands:": "Команди:", + "Options:": "Опції:", + "Examples:": "Приклади:", + "boolean": "boolean", + "count": "кількість", + "string": "строка", + "number": "число", + "array": "масива", + "required": "обов'язково", + "default": "за замовчуванням", + "default:": "за замовчуванням:", + "choices:": "доступні варіанти:", + "aliases:": "псевдоніми:", + "generated-value": "згенероване значення", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Недостатньо аргументів: наразі %s, потрібно %s або більше", + "other": "Недостатньо аргументів: наразі %s, потрібно %s або більше" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Забагато аргументів: наразі %s, максимум %s", + "other": "Too many non-option arguments: наразі %s, максимум of %s" + }, + "Missing argument value: %s": { + "one": "Відсутнє значення для аргументу: %s", + "other": "Відсутні значення для аргументу: %s" + }, + "Missing required argument: %s": { + "one": "Відсутній обов'язковий аргумент: %s", + "other": "Відсутні обов'язкові аргументи: %s" + }, + "Unknown argument: %s": { + "one": "Аргумент %s не підтримується", + "other": "Аргументи %s не підтримуються" + }, + "Invalid values:": "Некоректні значення:", + "Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Введено: %s, Доступні варіанти: %s", + "Argument check failed: %s": "Аргумент не пройшов перевірку: %s", + "Implications failed:": "Відсутні залежні аргументи:", + "Not enough arguments following: %s": "Не достатньо аргументів після: %s", + "Invalid JSON config file: %s": "Некоректний JSON-файл конфігурації: %s", + "Path to JSON config file": "Шлях до JSON-файлу конфігурації", + "Show help": "Показати довідку", + "Show version number": "Показати версію", + "Did you mean %s?": "Можливо, ви мали на увазі %s?", + "Arguments %s and %s are mutually exclusive" : "Аргументи %s та %s взаємовиключні", + "Positionals:": "Позиційні:", + "command": "команда", + "deprecated": "застарілий", + "deprecated: %s": "застарілий: %s" +} diff --git a/node_modules/yargs/locales/uz.json b/node_modules/yargs/locales/uz.json new file mode 100644 index 0000000..0d07168 --- /dev/null +++ b/node_modules/yargs/locales/uz.json @@ -0,0 +1,52 @@ +{ + "Commands:": "Buyruqlar:", + "Options:": "Imkoniyatlar:", + "Examples:": "Misollar:", + "boolean": "boolean", + "count": "sanoq", + "string": "satr", + "number": "raqam", + "array": "massiv", + "required": "majburiy", + "default": "boshlang'ich", + "default:": "boshlang'ich:", + "choices:": "tanlovlar:", + "aliases:": "taxalluslar:", + "generated-value": "yaratilgan-qiymat", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "No-imkoniyat argumentlar yetarli emas: berilgan %s, minimum %s", + "other": "No-imkoniyat argumentlar yetarli emas: berilgan %s, minimum %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "No-imkoniyat argumentlar juda ko'p: berilgan %s, maksimum %s", + "other": "No-imkoniyat argumentlar juda ko'p: got %s, maksimum %s" + }, + "Missing argument value: %s": { + "one": "Argument qiymati berilmagan: %s", + "other": "Argument qiymatlari berilmagan: %s" + }, + "Missing required argument: %s": { + "one": "Majburiy argument berilmagan: %s", + "other": "Majburiy argumentlar berilmagan: %s" + }, + "Unknown argument: %s": { + "one": "Noma'lum argument berilmagan: %s", + "other": "Noma'lum argumentlar berilmagan: %s" + }, + "Invalid values:": "Nosoz qiymatlar:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Berilgan: %s, Tanlovlar: %s", + "Argument check failed: %s": "Muvaffaqiyatsiz argument tekshiruvi: %s", + "Implications failed:": "Bog'liq argumentlar berilmagan:", + "Not enough arguments following: %s": "Quyidagi argumentlar yetarli emas: %s", + "Invalid JSON config file: %s": "Nosoz JSON konfiguratsiya fayli: %s", + "Path to JSON config file": "JSON konfiguratsiya fayli joylashuvi", + "Show help": "Yordam ko'rsatish", + "Show version number": "Versiyani ko'rsatish", + "Did you mean %s?": "%s ni nazarda tutyapsizmi?", + "Arguments %s and %s are mutually exclusive" : "%s va %s argumentlari alohida", + "Positionals:": "Positsionallar:", + "command": "buyruq", + "deprecated": "eskirgan", + "deprecated: %s": "eskirgan: %s" + } + \ No newline at end of file diff --git a/node_modules/yargs/locales/zh_CN.json b/node_modules/yargs/locales/zh_CN.json new file mode 100644 index 0000000..257d26b --- /dev/null +++ b/node_modules/yargs/locales/zh_CN.json @@ -0,0 +1,48 @@ +{ + "Commands:": "命令:", + "Options:": "选项:", + "Examples:": "示例:", + "boolean": "布尔", + "count": "计数", + "string": "字符串", + "number": "数字", + "array": "数组", + "required": "必需", + "default": "默认值", + "default:": "默认值:", + "choices:": "可选值:", + "generated-value": "生成的值", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "缺少 non-option 参数:传入了 %s 个, 至少需要 %s 个", + "other": "缺少 non-option 参数:传入了 %s 个, 至少需要 %s 个" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "non-option 参数过多:传入了 %s 个, 最大允许 %s 个", + "other": "non-option 参数过多:传入了 %s 个, 最大允许 %s 个" + }, + "Missing argument value: %s": { + "one": "没有给此选项指定值:%s", + "other": "没有给这些选项指定值:%s" + }, + "Missing required argument: %s": { + "one": "缺少必须的选项:%s", + "other": "缺少这些必须的选项:%s" + }, + "Unknown argument: %s": { + "one": "无法识别的选项:%s", + "other": "无法识别这些选项:%s" + }, + "Invalid values:": "无效的选项值:", + "Argument: %s, Given: %s, Choices: %s": "选项名称: %s, 传入的值: %s, 可选的值:%s", + "Argument check failed: %s": "选项值验证失败:%s", + "Implications failed:": "缺少依赖的选项:", + "Not enough arguments following: %s": "没有提供足够的值给此选项:%s", + "Invalid JSON config file: %s": "无效的 JSON 配置文件:%s", + "Path to JSON config file": "JSON 配置文件的路径", + "Show help": "显示帮助信息", + "Show version number": "显示版本号", + "Did you mean %s?": "是指 %s?", + "Arguments %s and %s are mutually exclusive" : "选项 %s 和 %s 是互斥的", + "Positionals:": "位置:", + "command": "命令" +} diff --git a/node_modules/yargs/locales/zh_TW.json b/node_modules/yargs/locales/zh_TW.json new file mode 100644 index 0000000..e38495d --- /dev/null +++ b/node_modules/yargs/locales/zh_TW.json @@ -0,0 +1,51 @@ +{ + "Commands:": "命令:", + "Options:": "選項:", + "Examples:": "範例:", + "boolean": "布林", + "count": "次數", + "string": "字串", + "number": "數字", + "array": "陣列", + "required": "必填", + "default": "預設值", + "default:": "預設值:", + "choices:": "可選值:", + "aliases:": "別名:", + "generated-value": "生成的值", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "non-option 引數不足:只傳入了 %s 個, 至少要 %s 個", + "other": "non-option 引數不足:只傳入了 %s 個, 至少要 %s 個" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "non-option 引數過多:傳入了 %s 個, 但最多 %s 個", + "other": "non-option 引數過多:傳入了 %s 個, 但最多 %s 個" + }, + "Missing argument value: %s": { + "one": "此引數無指定值:%s", + "other": "這些引數無指定值:%s" + }, + "Missing required argument: %s": { + "one": "缺少必須的引數:%s", + "other": "缺少這些必須的引數:%s" + }, + "Unknown argument: %s": { + "one": "未知的引數:%s", + "other": "未知的引數:%s" + }, + "Invalid values:": "無效的選項值:", + "Argument: %s, Given: %s, Choices: %s": "引數名稱: %s, 傳入的值: %s, 可選的值:%s", + "Argument check failed: %s": "引數驗證失敗:%s", + "Implications failed:": "缺少依賴引數:", + "Not enough arguments following: %s": "沒有提供足夠的值給此引數:%s", + "Invalid JSON config file: %s": "無效的 JSON 設置文件:%s", + "Path to JSON config file": "JSON 設置文件的路徑", + "Show help": "顯示說明", + "Show version number": "顯示版本", + "Did you mean %s?": "您是指 %s 嗎?", + "Arguments %s and %s are mutually exclusive" : "引數 %s 和 %s 互斥", + "Positionals:": "位置:", + "command": "命令", + "deprecated": "已淘汰", + "deprecated: %s": "已淘汰:%s" + } diff --git a/node_modules/yargs/package.json b/node_modules/yargs/package.json new file mode 100644 index 0000000..389cc6b --- /dev/null +++ b/node_modules/yargs/package.json @@ -0,0 +1,123 @@ +{ + "name": "yargs", + "version": "17.7.2", + "description": "yargs the modern, pirate-themed, successor to optimist.", + "main": "./index.cjs", + "exports": { + "./package.json": "./package.json", + ".": [ + { + "import": "./index.mjs", + "require": "./index.cjs" + }, + "./index.cjs" + ], + "./helpers": { + "import": "./helpers/helpers.mjs", + "require": "./helpers/index.js" + }, + "./browser": { + "import": "./browser.mjs", + "types": "./browser.d.ts" + }, + "./yargs": [ + { + "import": "./yargs.mjs", + "require": "./yargs" + }, + "./yargs" + ] + }, + "type": "module", + "module": "./index.mjs", + "contributors": [ + { + "name": "Yargs Contributors", + "url": "https://github.com/yargs/yargs/graphs/contributors" + } + ], + "files": [ + "browser.mjs", + "browser.d.ts", + "index.cjs", + "helpers/*.js", + "helpers/*", + "index.mjs", + "yargs", + "yargs.mjs", + "build", + "locales", + "LICENSE", + "lib/platform-shims/*.mjs", + "!*.d.ts", + "!**/*.d.ts" + ], + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "devDependencies": { + "@types/chai": "^4.2.11", + "@types/mocha": "^9.0.0", + "@types/node": "^18.0.0", + "c8": "^7.7.0", + "chai": "^4.2.0", + "chalk": "^4.0.0", + "coveralls": "^3.0.9", + "cpr": "^3.0.1", + "cross-env": "^7.0.2", + "cross-spawn": "^7.0.0", + "eslint": "^7.23.0", + "gts": "^3.0.0", + "hashish": "0.0.4", + "mocha": "^9.0.0", + "rimraf": "^3.0.2", + "rollup": "^2.23.0", + "rollup-plugin-cleanup": "^3.1.1", + "rollup-plugin-terser": "^7.0.2", + "rollup-plugin-ts": "^2.0.4", + "typescript": "^4.0.2", + "which": "^2.0.0", + "yargs-test-extends": "^1.0.1" + }, + "scripts": { + "fix": "gts fix && npm run fix:js", + "fix:js": "eslint . --ext cjs --ext mjs --ext js --fix", + "posttest": "npm run check", + "test": "c8 mocha --enable-source-maps ./test/*.cjs --require ./test/before.cjs --timeout=12000 --check-leaks", + "test:esm": "c8 mocha --enable-source-maps ./test/esm/*.mjs --check-leaks", + "coverage": "c8 report --check-coverage", + "prepare": "npm run compile", + "pretest": "npm run compile -- -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs", + "compile": "rimraf build && tsc", + "postcompile": "npm run build:cjs", + "build:cjs": "rollup -c rollup.config.cjs", + "postbuild:cjs": "rimraf ./build/index.cjs.d.ts", + "check": "gts lint && npm run check:js", + "check:js": "eslint . --ext cjs --ext mjs --ext js", + "clean": "gts clean" + }, + "repository": { + "type": "git", + "url": "https://github.com/yargs/yargs.git" + }, + "homepage": "https://yargs.js.org/", + "keywords": [ + "argument", + "args", + "option", + "parser", + "parsing", + "cli", + "command" + ], + "license": "MIT", + "engines": { + "node": ">=12" + } +} diff --git a/node_modules/yargs/yargs b/node_modules/yargs/yargs new file mode 100644 index 0000000..8460d10 --- /dev/null +++ b/node_modules/yargs/yargs @@ -0,0 +1,9 @@ +// TODO: consolidate on using a helpers file at some point in the future, which +// is the approach currently used to export Parser and applyExtends for ESM: +const {applyExtends, cjsPlatformShim, Parser, Yargs, processArgv} = require('./build/index.cjs') +Yargs.applyExtends = (config, cwd, mergeExtends) => { + return applyExtends(config, cwd, mergeExtends, cjsPlatformShim) +} +Yargs.hideBin = processArgv.hideBin +Yargs.Parser = Parser +module.exports = Yargs diff --git a/node_modules/yargs/yargs.mjs b/node_modules/yargs/yargs.mjs new file mode 100644 index 0000000..6d9f390 --- /dev/null +++ b/node_modules/yargs/yargs.mjs @@ -0,0 +1,10 @@ +// TODO: consolidate on using a helpers file at some point in the future, which +// is the approach currently used to export Parser and applyExtends for ESM: +import pkg from './build/index.cjs'; +const {applyExtends, cjsPlatformShim, Parser, processArgv, Yargs} = pkg; +Yargs.applyExtends = (config, cwd, mergeExtends) => { + return applyExtends(config, cwd, mergeExtends, cjsPlatformShim); +}; +Yargs.hideBin = processArgv.hideBin; +Yargs.Parser = Parser; +export default Yargs; diff --git a/node_modules/yocto-queue/index.d.ts b/node_modules/yocto-queue/index.d.ts new file mode 100644 index 0000000..9541986 --- /dev/null +++ b/node_modules/yocto-queue/index.d.ts @@ -0,0 +1,56 @@ +declare class Queue implements Iterable { + /** + The size of the queue. + */ + readonly size: number; + + /** + Tiny queue data structure. + + The instance is an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols), which means you can iterate over the queue front to back with a “for…of” loop, or use spreading to convert the queue to an array. Don't do this unless you really need to though, since it's slow. + + @example + ``` + import Queue = require('yocto-queue'); + + const queue = new Queue(); + + queue.enqueue('🦄'); + queue.enqueue('🌈'); + + console.log(queue.size); + //=> 2 + + console.log(...queue); + //=> '🦄 🌈' + + console.log(queue.dequeue()); + //=> '🦄' + + console.log(queue.dequeue()); + //=> '🌈' + ``` + */ + constructor(); + + [Symbol.iterator](): IterableIterator; + + /** + Add a value to the queue. + */ + enqueue(value: ValueType): void; + + /** + Remove the next value in the queue. + + @returns The removed value or `undefined` if the queue is empty. + */ + dequeue(): ValueType | undefined; + + /** + Clear the queue. + */ + clear(): void; +} + +export = Queue; diff --git a/node_modules/yocto-queue/index.js b/node_modules/yocto-queue/index.js new file mode 100644 index 0000000..2f3e6dc --- /dev/null +++ b/node_modules/yocto-queue/index.js @@ -0,0 +1,68 @@ +class Node { + /// value; + /// next; + + constructor(value) { + this.value = value; + + // TODO: Remove this when targeting Node.js 12. + this.next = undefined; + } +} + +class Queue { + // TODO: Use private class fields when targeting Node.js 12. + // #_head; + // #_tail; + // #_size; + + constructor() { + this.clear(); + } + + enqueue(value) { + const node = new Node(value); + + if (this._head) { + this._tail.next = node; + this._tail = node; + } else { + this._head = node; + this._tail = node; + } + + this._size++; + } + + dequeue() { + const current = this._head; + if (!current) { + return; + } + + this._head = this._head.next; + this._size--; + return current.value; + } + + clear() { + this._head = undefined; + this._tail = undefined; + this._size = 0; + } + + get size() { + return this._size; + } + + * [Symbol.iterator]() { + let current = this._head; + + while (current) { + yield current.value; + current = current.next; + } + } +} + +module.exports = Queue; diff --git a/node_modules/yocto-queue/license b/node_modules/yocto-queue/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/yocto-queue/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/yocto-queue/package.json b/node_modules/yocto-queue/package.json new file mode 100644 index 0000000..71a9101 --- /dev/null +++ b/node_modules/yocto-queue/package.json @@ -0,0 +1,43 @@ +{ + "name": "yocto-queue", + "version": "0.1.0", + "description": "Tiny queue data structure", + "license": "MIT", + "repository": "sindresorhus/yocto-queue", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "queue", + "data", + "structure", + "algorithm", + "queues", + "queuing", + "list", + "array", + "linkedlist", + "fifo", + "enqueue", + "dequeue", + "data-structure" + ], + "devDependencies": { + "ava": "^2.4.0", + "tsd": "^0.13.1", + "xo": "^0.35.0" + } +} diff --git a/node_modules/yocto-queue/readme.md b/node_modules/yocto-queue/readme.md new file mode 100644 index 0000000..c72fefc --- /dev/null +++ b/node_modules/yocto-queue/readme.md @@ -0,0 +1,64 @@ +# yocto-queue [![](https://badgen.net/bundlephobia/minzip/yocto-queue)](https://bundlephobia.com/result?p=yocto-queue) + +> Tiny queue data structure + +You should use this package instead of an array if you do a lot of `Array#push()` and `Array#shift()` on large arrays, since `Array#shift()` has [linear time complexity](https://medium.com/@ariel.salem1989/an-easy-to-use-guide-to-big-o-time-complexity-5dcf4be8a444#:~:text=O(N)%E2%80%94Linear%20Time) *O(n)* while `Queue#dequeue()` has [constant time complexity](https://medium.com/@ariel.salem1989/an-easy-to-use-guide-to-big-o-time-complexity-5dcf4be8a444#:~:text=O(1)%20%E2%80%94%20Constant%20Time) *O(1)*. That makes a huge difference for large arrays. + +> A [queue](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) is an ordered list of elements where an element is inserted at the end of the queue and is removed from the front of the queue. A queue works based on the first-in, first-out ([FIFO](https://en.wikipedia.org/wiki/FIFO_(computing_and_electronics))) principle. + +## Install + +``` +$ npm install yocto-queue +``` + +## Usage + +```js +const Queue = require('yocto-queue'); + +const queue = new Queue(); + +queue.enqueue('🦄'); +queue.enqueue('🌈'); + +console.log(queue.size); +//=> 2 + +console.log(...queue); +//=> '🦄 🌈' + +console.log(queue.dequeue()); +//=> '🦄' + +console.log(queue.dequeue()); +//=> '🌈' +``` + +## API + +### `queue = new Queue()` + +The instance is an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols), which means you can iterate over the queue front to back with a “for…of” loop, or use spreading to convert the queue to an array. Don't do this unless you really need to though, since it's slow. + +#### `.enqueue(value)` + +Add a value to the queue. + +#### `.dequeue()` + +Remove the next value in the queue. + +Returns the removed value or `undefined` if the queue is empty. + +#### `.clear()` + +Clear the queue. + +#### `.size` + +The size of the queue. + +## Related + +- [quick-lru](https://github.com/sindresorhus/quick-lru) - Simple “Least Recently Used” (LRU) cache diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..cf929e2 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1969 @@ +{ + "name": "Psychology-Apps", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "firebase-admin": "^13.6.0" + } + }, + "node_modules/@fastify/busboy": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-3.2.0.tgz", + "integrity": "sha512-m9FVDXU3GT2ITSe0UaMA5rU3QkfC/UXtCU8y0gSN/GugTqtVldOBWIB5V6V3sbmenVZUIpU6f+mPEO2+m5iTaA==", + "license": "MIT" + }, + "node_modules/@firebase/app-check-interop-types": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/@firebase/app-check-interop-types/-/app-check-interop-types-0.3.3.tgz", + "integrity": "sha512-gAlxfPLT2j8bTI/qfe3ahl2I2YcBQ8cFIBdhAQA4I2f3TndcO+22YizyGYuttLHPQEpWkhmpFW60VCFEPg4g5A==", + "license": "Apache-2.0" + }, + "node_modules/@firebase/app-types": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/@firebase/app-types/-/app-types-0.9.3.tgz", + "integrity": "sha512-kRVpIl4vVGJ4baogMDINbyrIOtOxqhkZQg4jTq3l8Lw6WSk0xfpEYzezFu+Kl4ve4fbPl79dvwRtaFqAC/ucCw==", + "license": "Apache-2.0" + }, + "node_modules/@firebase/auth-interop-types": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/@firebase/auth-interop-types/-/auth-interop-types-0.2.4.tgz", + "integrity": "sha512-JPgcXKCuO+CWqGDnigBtvo09HeBs5u/Ktc2GaFj2m01hLarbxthLNm7Fk8iOP1aqAtXV+fnnGj7U28xmk7IwVA==", + "license": "Apache-2.0" + }, + "node_modules/@firebase/component": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/@firebase/component/-/component-0.7.0.tgz", + "integrity": "sha512-wR9En2A+WESUHexjmRHkqtaVH94WLNKt6rmeqZhSLBybg4Wyf0Umk04SZsS6sBq4102ZsDBFwoqMqJYj2IoDSg==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/util": "1.13.0", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@firebase/database": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@firebase/database/-/database-1.1.0.tgz", + "integrity": "sha512-gM6MJFae3pTyNLoc9VcJNuaUDej0ctdjn3cVtILo3D5lpp0dmUHHLFN/pUKe7ImyeB1KAvRlEYxvIHNF04Filg==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/app-check-interop-types": "0.3.3", + "@firebase/auth-interop-types": "0.2.4", + "@firebase/component": "0.7.0", + "@firebase/logger": "0.5.0", + "@firebase/util": "1.13.0", + "faye-websocket": "0.11.4", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@firebase/database-compat": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@firebase/database-compat/-/database-compat-2.1.0.tgz", + "integrity": "sha512-8nYc43RqxScsePVd1qe1xxvWNf0OBnbwHxmXJ7MHSuuTVYFO3eLyLW3PiCKJ9fHnmIz4p4LbieXwz+qtr9PZDg==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/component": "0.7.0", + "@firebase/database": "1.1.0", + "@firebase/database-types": "1.0.16", + "@firebase/logger": "0.5.0", + "@firebase/util": "1.13.0", + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@firebase/database-types": { + "version": "1.0.16", + "resolved": "https://registry.npmjs.org/@firebase/database-types/-/database-types-1.0.16.tgz", + "integrity": "sha512-xkQLQfU5De7+SPhEGAXFBnDryUWhhlFXelEg2YeZOQMCdoe7dL64DDAd77SQsR+6uoXIZY5MB4y/inCs4GTfcw==", + "license": "Apache-2.0", + "dependencies": { + "@firebase/app-types": "0.9.3", + "@firebase/util": "1.13.0" + } + }, + "node_modules/@firebase/logger": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@firebase/logger/-/logger-0.5.0.tgz", + "integrity": "sha512-cGskaAvkrnh42b3BA3doDWeBmuHFO/Mx5A83rbRDYakPjO9bJtRL3dX7javzc2Rr/JHZf4HlterTW2lUkfeN4g==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@firebase/util": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@firebase/util/-/util-1.13.0.tgz", + "integrity": "sha512-0AZUyYUfpMNcztR5l09izHwXkZpghLgCUaAGjtMwXnCg3bj4ml5VgiwqOMOxJ+Nw4qN/zJAaOQBcJ7KGkWStqQ==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@google-cloud/firestore": { + "version": "7.11.6", + "resolved": "https://registry.npmjs.org/@google-cloud/firestore/-/firestore-7.11.6.tgz", + "integrity": "sha512-EW/O8ktzwLfyWBOsNuhRoMi8lrC3clHM5LVFhGvO1HCsLozCOOXRAlHrYBoE6HL42Sc8yYMuCb2XqcnJ4OOEpw==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@opentelemetry/api": "^1.3.0", + "fast-deep-equal": "^3.1.1", + "functional-red-black-tree": "^1.0.1", + "google-gax": "^4.3.3", + "protobufjs": "^7.2.6" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@google-cloud/paginator": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@google-cloud/paginator/-/paginator-5.0.2.tgz", + "integrity": "sha512-DJS3s0OVH4zFDB1PzjxAsHqJT6sKVbRwwML0ZBP9PbU7Yebtu/7SWMRzvO2J3nUi9pRNITCfu4LJeooM2w4pjg==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "arrify": "^2.0.0", + "extend": "^3.0.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@google-cloud/projectify": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@google-cloud/projectify/-/projectify-4.0.0.tgz", + "integrity": "sha512-MmaX6HeSvyPbWGwFq7mXdo0uQZLGBYCwziiLIGq5JVX+/bdI3SAq6bP98trV5eTWfLuvsMcIC1YJOF2vfteLFA==", + "license": "Apache-2.0", + "optional": true, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@google-cloud/promisify": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@google-cloud/promisify/-/promisify-4.0.0.tgz", + "integrity": "sha512-Orxzlfb9c67A15cq2JQEyVc7wEsmFBmHjZWZYQMUyJ1qivXyMwdyNOs9odi79hze+2zqdTtu1E19IM/FtqZ10g==", + "license": "Apache-2.0", + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@google-cloud/storage": { + "version": "7.18.0", + "resolved": "https://registry.npmjs.org/@google-cloud/storage/-/storage-7.18.0.tgz", + "integrity": "sha512-r3ZwDMiz4nwW6R922Z1pwpePxyRwE5GdevYX63hRmAQUkUQJcBH/79EnQPDv5cOv1mFBgevdNWQfi3tie3dHrQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@google-cloud/paginator": "^5.0.0", + "@google-cloud/projectify": "^4.0.0", + "@google-cloud/promisify": "<4.1.0", + "abort-controller": "^3.0.0", + "async-retry": "^1.3.3", + "duplexify": "^4.1.3", + "fast-xml-parser": "^4.4.1", + "gaxios": "^6.0.2", + "google-auth-library": "^9.6.3", + "html-entities": "^2.5.2", + "mime": "^3.0.0", + "p-limit": "^3.0.1", + "retry-request": "^7.0.0", + "teeny-request": "^9.0.0", + "uuid": "^8.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@google-cloud/storage/node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "license": "MIT", + "optional": true, + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/@grpc/grpc-js": { + "version": "1.14.2", + "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.2.tgz", + "integrity": "sha512-QzVUtEFyu05UNx2xr0fCQmStUO17uVQhGNowtxs00IgTZT6/W2PBLfUkj30s0FKJ29VtTa3ArVNIhNP6akQhqA==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@grpc/proto-loader": "^0.8.0", + "@js-sdsl/ordered-map": "^4.4.2" + }, + "engines": { + "node": ">=12.10.0" + } + }, + "node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.8.0.tgz", + "integrity": "sha512-rc1hOQtjIWGxcxpb9aHAfLpIctjEnsDehj0DAiVfBlmT84uvR0uUtN2hEi/ecvWVjXUGf5qPF4qEgiLOx1YIMQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "lodash.camelcase": "^4.3.0", + "long": "^5.0.0", + "protobufjs": "^7.5.3", + "yargs": "^17.7.2" + }, + "bin": { + "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@grpc/proto-loader": { + "version": "0.7.15", + "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.7.15.tgz", + "integrity": "sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "lodash.camelcase": "^4.3.0", + "long": "^5.0.0", + "protobufjs": "^7.2.5", + "yargs": "^17.7.2" + }, + "bin": { + "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@js-sdsl/ordered-map": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@js-sdsl/ordered-map/-/ordered-map-4.4.2.tgz", + "integrity": "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw==", + "license": "MIT", + "optional": true, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/js-sdsl" + } + }, + "node_modules/@opentelemetry/api": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz", + "integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==", + "license": "Apache-2.0", + "optional": true, + "engines": { + "node": ">=8.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", + "optional": true + }, + "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", + "optional": true + }, + "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", + "optional": true + }, + "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", + "optional": true + }, + "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", + "optional": true, + "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", + "optional": true + }, + "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", + "optional": true + }, + "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", + "optional": true + }, + "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", + "optional": true + }, + "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", + "optional": true + }, + "node_modules/@tootallnate/once": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", + "integrity": "sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 10" + } + }, + "node_modules/@types/body-parser": { + "version": "1.19.6", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", + "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==", + "license": "MIT", + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/caseless": { + "version": "0.12.5", + "resolved": "https://registry.npmjs.org/@types/caseless/-/caseless-0.12.5.tgz", + "integrity": "sha512-hWtVTC2q7hc7xZ/RLbxapMvDMgUnDvKvMOpKal4DrMyfGBUfB1oKaZlIRr6mJL+If3bAP6sV/QneGzF6tJjZDg==", + "license": "MIT", + "optional": true + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/express": { + "version": "4.17.25", + "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.25.tgz", + "integrity": "sha512-dVd04UKsfpINUnK0yBoYHDF3xu7xVH4BuDotC/xGuycx4CgbP48X/KF/586bcObxT0HENHXEU8Nqtu6NR+eKhw==", + "license": "MIT", + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "^1" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "4.19.7", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.7.tgz", + "integrity": "sha512-FvPtiIf1LfhzsaIXhv/PHan/2FeQBbtBDtfX2QfvPxdUelMDEckK08SM6nqo1MIZY3RUlfA+HV8+hFUSio78qg==", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/http-errors": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", + "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==", + "license": "MIT" + }, + "node_modules/@types/jsonwebtoken": { + "version": "9.0.10", + "resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.10.tgz", + "integrity": "sha512-asx5hIG9Qmf/1oStypjanR7iKTv0gXQ1Ov/jfrX6kS/EO0OFni8orbmGCn0672NHR3kXHwpAwR+B368ZGN/2rA==", + "license": "MIT", + "dependencies": { + "@types/ms": "*", + "@types/node": "*" + } + }, + "node_modules/@types/long": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/long/-/long-4.0.2.tgz", + "integrity": "sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA==", + "license": "MIT", + "optional": true + }, + "node_modules/@types/mime": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", + "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==", + "license": "MIT" + }, + "node_modules/@types/ms": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz", + "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.19.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.2.tgz", + "integrity": "sha512-LPM2G3Syo1GLzXLGJAKdqoU35XvrWzGJ21/7sgZTUpbkBaOasTj8tjwn6w+hCkqaa1TfJ/w67rJSwYItlJ2mYw==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/qs": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ==", + "license": "MIT" + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", + "license": "MIT" + }, + "node_modules/@types/request": { + "version": "2.48.13", + "resolved": "https://registry.npmjs.org/@types/request/-/request-2.48.13.tgz", + "integrity": "sha512-FGJ6udDNUCjd19pp0Q3iTiDkwhYup7J8hpMW9c4k53NrccQFFWKRho6hvtPPEhnXWKvukfwAlB6DbDz4yhH5Gg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@types/caseless": "*", + "@types/node": "*", + "@types/tough-cookie": "*", + "form-data": "^2.5.5" + } + }, + "node_modules/@types/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz", + "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "1.15.10", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.10.tgz", + "integrity": "sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw==", + "license": "MIT", + "dependencies": { + "@types/http-errors": "*", + "@types/node": "*", + "@types/send": "<1" + } + }, + "node_modules/@types/serve-static/node_modules/@types/send": { + "version": "0.17.6", + "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.6.tgz", + "integrity": "sha512-Uqt8rPBE8SY0RK8JB1EzVOIZ32uqy8HwdxCnoCOsYrvnswqmFZ/k+9Ikidlk/ImhsdvBsloHbAlewb2IEBV/Og==", + "license": "MIT", + "dependencies": { + "@types/mime": "^1", + "@types/node": "*" + } + }, + "node_modules/@types/tough-cookie": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.5.tgz", + "integrity": "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==", + "license": "MIT", + "optional": true + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "license": "MIT", + "optional": true, + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "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", + "optional": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/arrify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-2.0.1.tgz", + "integrity": "sha512-3duEwti880xqi4eAMN8AyR4a0ByT90zoYdLlevfrvU43vb0YZwZVfxOgxWrLXXXpyugL0hNZc9G6BiB5B3nUug==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/async-retry": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/async-retry/-/async-retry-1.3.3.tgz", + "integrity": "sha512-wfr/jstw9xNi/0teMHrRW7dsz3Lt5ARhYNZ2ewpadnhaIp5mbALhOAP+EAdsC7t4Z6wqsDVv9+W6gm1Dk9mEyw==", + "license": "MIT", + "optional": true, + "dependencies": { + "retry": "0.13.1" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT", + "optional": true + }, + "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/bignumber.js": { + "version": "9.3.1", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz", + "integrity": "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==", + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "license": "ISC", + "optional": true, + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "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", + "optional": true, + "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", + "optional": true + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "optional": true, + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "optional": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/duplexify": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-4.1.3.tgz", + "integrity": "sha512-M3BmBhwJRZsSx38lZyhE53Csddgzl5R7xGJNk7CVddZD6CcmwMCH8J+7AprIrQKH7TonKxaCjcv27Qmf+sQ+oA==", + "license": "MIT", + "optional": true, + "dependencies": { + "end-of-stream": "^1.4.1", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1", + "stream-shift": "^1.0.2" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT", + "optional": true + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "optional": true, + "dependencies": { + "once": "^1.4.0" + } + }, + "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", + "optional": true, + "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", + "optional": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "optional": true, + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "optional": true, + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "license": "MIT" + }, + "node_modules/farmhash-modern": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/farmhash-modern/-/farmhash-modern-1.1.0.tgz", + "integrity": "sha512-6ypT4XfgqJk/F3Yuv4SX26I3doUjt0GTG4a+JgWxXQpxXzTBq8fPUeGHfcYMMDPHJHm3yPOSjaeBwBGAHWXCdA==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-xml-parser": { + "version": "4.5.3", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.5.3.tgz", + "integrity": "sha512-RKihhV+SHsIUGXObeVy9AXiBbFwkVk7Syp8XgwN5U3JV416+Gwp/GO9i0JYKmikykgz/UHRrrV4ROuZEo/T0ig==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "optional": true, + "dependencies": { + "strnum": "^1.1.1" + }, + "bin": { + "fxparser": "src/cli/cli.js" + } + }, + "node_modules/faye-websocket": { + "version": "0.11.4", + "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.11.4.tgz", + "integrity": "sha512-CzbClwlXAuiRQAlUyfqPgvPoNKTckTPGfwZV4ZdAhVcP2lh9KUxJg2b5GkE7XbjKQ3YJnQ9z6D9ntLAlB+tP8g==", + "license": "Apache-2.0", + "dependencies": { + "websocket-driver": ">=0.5.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/firebase-admin": { + "version": "13.6.0", + "resolved": "https://registry.npmjs.org/firebase-admin/-/firebase-admin-13.6.0.tgz", + "integrity": "sha512-GdPA/t0+Cq8p1JnjFRBmxRxAGvF/kl2yfdhALl38PrRp325YxyQ5aNaHui0XmaKcKiGRFIJ/EgBNWFoDP0onjw==", + "license": "Apache-2.0", + "dependencies": { + "@fastify/busboy": "^3.0.0", + "@firebase/database-compat": "^2.0.0", + "@firebase/database-types": "^1.0.6", + "@types/node": "^22.8.7", + "farmhash-modern": "^1.1.0", + "fast-deep-equal": "^3.1.1", + "google-auth-library": "^9.14.2", + "jsonwebtoken": "^9.0.0", + "jwks-rsa": "^3.1.0", + "node-forge": "^1.3.1", + "uuid": "^11.0.2" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@google-cloud/firestore": "^7.11.0", + "@google-cloud/storage": "^7.14.0" + } + }, + "node_modules/form-data": { + "version": "2.5.5", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.5.5.tgz", + "integrity": "sha512-jqdObeR2rxZZbPSGL+3VckHMYtu+f9//KXBsVny6JSX/pa38Fy+bGjuG8eW/H6USNQWhLi8Num++cU2yOCNz4A==", + "license": "MIT", + "optional": true, + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", + "mime-types": "^2.1.35", + "safe-buffer": "^5.2.1" + }, + "engines": { + "node": ">= 0.12" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "optional": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/functional-red-black-tree": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", + "integrity": "sha512-dsKNQNdj6xA3T+QlADDA7mOSlX0qiMINjn0cgr+eGHGsbSHzTabcIogz2+p/iqP1Xs6EP/sS2SbqH+brGTbq0g==", + "license": "MIT", + "optional": true + }, + "node_modules/gaxios": { + "version": "6.7.1", + "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-6.7.1.tgz", + "integrity": "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ==", + "license": "Apache-2.0", + "dependencies": { + "extend": "^3.0.2", + "https-proxy-agent": "^7.0.1", + "is-stream": "^2.0.0", + "node-fetch": "^2.6.9", + "uuid": "^9.0.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/gaxios/node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/gcp-metadata": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-6.1.1.tgz", + "integrity": "sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A==", + "license": "Apache-2.0", + "dependencies": { + "gaxios": "^6.1.1", + "google-logging-utils": "^0.0.2", + "json-bigint": "^1.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "optional": true, + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "optional": true, + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/google-auth-library": { + "version": "9.15.1", + "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-9.15.1.tgz", + "integrity": "sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng==", + "license": "Apache-2.0", + "dependencies": { + "base64-js": "^1.3.0", + "ecdsa-sig-formatter": "^1.0.11", + "gaxios": "^6.1.1", + "gcp-metadata": "^6.1.0", + "gtoken": "^7.0.0", + "jws": "^4.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/google-gax": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/google-gax/-/google-gax-4.6.1.tgz", + "integrity": "sha512-V6eky/xz2mcKfAd1Ioxyd6nmA61gao3n01C+YeuIwu3vzM9EDR6wcVzMSIbLMDXWeoi9SHYctXuKYC5uJUT3eQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@grpc/grpc-js": "^1.10.9", + "@grpc/proto-loader": "^0.7.13", + "@types/long": "^4.0.0", + "abort-controller": "^3.0.0", + "duplexify": "^4.0.0", + "google-auth-library": "^9.3.0", + "node-fetch": "^2.7.0", + "object-hash": "^3.0.0", + "proto3-json-serializer": "^2.0.2", + "protobufjs": "^7.3.2", + "retry-request": "^7.0.0", + "uuid": "^9.0.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/google-gax/node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "optional": true, + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/google-logging-utils": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-0.0.2.tgz", + "integrity": "sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gtoken": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-7.1.0.tgz", + "integrity": "sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==", + "license": "MIT", + "dependencies": { + "gaxios": "^6.0.0", + "jws": "^4.0.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "optional": true, + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/html-entities": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/html-entities/-/html-entities-2.6.0.tgz", + "integrity": "sha512-kig+rMn/QOVRvr7c86gQ8lWXq+Hkv6CbAH1hLu+RG338StTpE8Z0b44SDVaqVu7HGKf27frdmUYEs9hTUX/cLQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/mdevils" + }, + { + "type": "patreon", + "url": "https://patreon.com/mdevils" + } + ], + "license": "MIT", + "optional": true + }, + "node_modules/http-parser-js": { + "version": "0.5.10", + "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.10.tgz", + "integrity": "sha512-Pysuw9XpUq5dVc/2SMHpuTY01RFl8fttgcyunjL7eEMhGM3cI4eOmiCycJDVCo/7O7ClfQD3SaI6ftDzqOXYMA==", + "license": "MIT" + }, + "node_modules/http-proxy-agent": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz", + "integrity": "sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==", + "license": "MIT", + "optional": true, + "dependencies": { + "@tootallnate/once": "2", + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/http-proxy-agent/node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC", + "optional": true + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jose": { + "version": "4.15.9", + "resolved": "https://registry.npmjs.org/jose/-/jose-4.15.9.tgz", + "integrity": "sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/json-bigint": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz", + "integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==", + "license": "MIT", + "dependencies": { + "bignumber.js": "^9.0.0" + } + }, + "node_modules/jsonwebtoken": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz", + "integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==", + "license": "MIT", + "dependencies": { + "jws": "^4.0.1", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, + "node_modules/jwa": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", + "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jwks-rsa": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/jwks-rsa/-/jwks-rsa-3.2.0.tgz", + "integrity": "sha512-PwchfHcQK/5PSydeKCs1ylNym0w/SSv8a62DgHJ//7x2ZclCoinlsjAfDxAAbpoTPybOum/Jgy+vkvMmKz89Ww==", + "license": "MIT", + "dependencies": { + "@types/express": "^4.17.20", + "@types/jsonwebtoken": "^9.0.4", + "debug": "^4.3.4", + "jose": "^4.15.4", + "limiter": "^1.1.5", + "lru-memoizer": "^2.2.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/jws": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", + "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", + "license": "MIT", + "dependencies": { + "jwa": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/limiter": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/limiter/-/limiter-1.1.5.tgz", + "integrity": "sha512-FWWMIEOxz3GwUI4Ts/IvgVy6LPvoMPgjMdQ185nN6psJyBJ4yOpzqm695/h5umdLJg2vW3GR5iG11MAkR2AzJA==" + }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", + "license": "MIT", + "optional": true + }, + "node_modules/lodash.clonedeep": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz", + "integrity": "sha512-H5ZhCF25riFd9uB5UCkVKo61m3S/xZk1x4wA6yp/L3RFP6Z/eHH1ymQcGLo7J3GMPfm0V/7m1tryHuGVxpqEBQ==", + "license": "MIT" + }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", + "license": "MIT" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", + "license": "MIT" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "license": "MIT" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", + "license": "MIT" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", + "license": "MIT" + }, + "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", + "optional": true + }, + "node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/lru-memoizer": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/lru-memoizer/-/lru-memoizer-2.3.0.tgz", + "integrity": "sha512-GXn7gyHAMhO13WSKrIiNfztwxodVsP8IoZ3XfrJV4yH2x0/OeTO/FIaAHTY5YekdGgW94njfuKmyyt1E0mR6Ug==", + "license": "MIT", + "dependencies": { + "lodash.clonedeep": "^4.5.0", + "lru-cache": "6.0.0" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/mime": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz", + "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==", + "license": "MIT", + "optional": true, + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "optional": true, + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/node-forge": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.3.tgz", + "integrity": "sha512-rLvcdSyRCyouf6jcOIPe/BgwG/d7hKjzMKOas33/pHEr6gbq18IK9zV7DiPvzsz0oBJPme6qr6H6kGZuI9/DZg==", + "license": "(BSD-3-Clause OR GPL-2.0)", + "engines": { + "node": ">= 6.13.0" + } + }, + "node_modules/object-hash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz", + "integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 6" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "optional": true, + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/proto3-json-serializer": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/proto3-json-serializer/-/proto3-json-serializer-2.0.2.tgz", + "integrity": "sha512-SAzp/O4Yh02jGdRc+uIrGoe87dkN/XtwxfZ4ZyafJHymd79ozp5VG5nyZ7ygqPM5+cpLDjjGnYFUkngonyDPOQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "protobufjs": "^7.2.5" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "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", + "optional": true, + "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/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "optional": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/retry": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", + "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/retry-request": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/retry-request/-/retry-request-7.0.2.tgz", + "integrity": "sha512-dUOvLMJ0/JJYEn8NrpOaGNE7X3vpI5XlZS/u0ANjqtcZVKnIxP7IgCFwrKTxENw29emmwug53awKtaMm4i9g5w==", + "license": "MIT", + "optional": true, + "dependencies": { + "@types/request": "^2.48.8", + "extend": "^3.0.2", + "teeny-request": "^9.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/stream-events": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/stream-events/-/stream-events-1.0.5.tgz", + "integrity": "sha512-E1GUzBSgvct8Jsb3v2X15pjzN1tYebtbLaMg+eBOUOAxgbLoSbT2NS91ckc5lJD1KfLjId+jXJRgo0qnV5Nerg==", + "license": "MIT", + "optional": true, + "dependencies": { + "stubs": "^3.0.0" + } + }, + "node_modules/stream-shift": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.3.tgz", + "integrity": "sha512-76ORR0DO1o1hlKwTbi/DM3EXWGf3ZJYO8cXX5RJwnul2DEg2oyoZyjLNoQM8WsvZiFKCRfC1O0J7iCvie3RZmQ==", + "license": "MIT", + "optional": true + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "optional": true, + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "optional": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "optional": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strnum": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-1.1.2.tgz", + "integrity": "sha512-vrN+B7DBIoTTZjnPNewwhx6cBA/H+IS7rfW68n7XxC1y7uoiGQBxaKzqucGUgavX15dJgiGztLJ8vxuEzwqBdA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "optional": true + }, + "node_modules/stubs": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/stubs/-/stubs-3.0.0.tgz", + "integrity": "sha512-PdHt7hHUJKxvTCgbKX9C1V/ftOcjJQgz8BZwNfV5c4B6dcGqlpelTbJ999jBGZ2jYiPAwcX5dP6oBwVlBlUbxw==", + "license": "MIT", + "optional": true + }, + "node_modules/teeny-request": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/teeny-request/-/teeny-request-9.0.0.tgz", + "integrity": "sha512-resvxdc6Mgb7YEThw6G6bExlXKkv6+YbuzGg9xuXxSgxJF7Ozs+o8Y9+2R3sArdWdW8nOokoQb1yrpFB0pQK2g==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "http-proxy-agent": "^5.0.0", + "https-proxy-agent": "^5.0.0", + "node-fetch": "^2.6.9", + "stream-events": "^1.0.5", + "uuid": "^9.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/teeny-request/node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/teeny-request/node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "license": "MIT", + "optional": true, + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/teeny-request/node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "optional": true, + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, + "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/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "license": "MIT" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT", + "optional": true + }, + "node_modules/uuid": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz", + "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/esm/bin/uuid" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/websocket-driver": { + "version": "0.7.4", + "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.4.tgz", + "integrity": "sha512-b17KeDIQVjvb0ssuSDF2cYXSg2iztliJ4B9WdsuB6J952qCPKmnVq4DyW5motImXHDC1cBT/1UezrJVsKw5zjg==", + "license": "Apache-2.0", + "dependencies": { + "http-parser-js": ">=0.5.1", + "safe-buffer": ">=5.1.0", + "websocket-extensions": ">=0.1.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/websocket-extensions": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.4.tgz", + "integrity": "sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "optional": true, + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC", + "optional": true + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "license": "ISC", + "optional": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "license": "ISC" + }, + "node_modules/yargs": { + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "license": "MIT", + "optional": true, + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "license": "ISC", + "optional": true, + "engines": { + "node": ">=12" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..53756d4 --- /dev/null +++ b/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "firebase-admin": "^13.6.0" + } +} From 7d20ade632c4703ff9967b91fe29ed60c4c9ec10 Mon Sep 17 00:00:00 2001 From: Muhammad Ikhsan Nur Rafid <57042450+Ikhsaaan334@users.noreply.github.com> Date: Tue, 16 Dec 2025 20:56:08 +0700 Subject: [PATCH 3/3] Update readme.MD --- readme.MD | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/readme.MD b/readme.MD index b0cdebc..2c8b031 100644 --- a/readme.MD +++ b/readme.MD @@ -70,12 +70,6 @@ Ditenagai oleh **Google Gemini 2.5 Flash**, Flanella menawarkan percakapan cerda - `cors`: Middleware untuk mengaktifkan Cross-Origin Resource Sharing pada server Express. - `axios`: Klien HTTP berbasis Promise untuk melakukan permintaan ke layanan eksternal jika diperlukan. -## 📸 Tangkapan Layar - -| Halaman Utama | Halaman Obrolan | Halaman Jurnal | -|:---:|:---:|:---:| -| | | | - ## 🚀 Cara Memulai Ikuti langkah-langkah berikut untuk menjalankan proyek ini di lingkungan lokal Anda. @@ -152,3 +146,4 @@ Psychology-Apps-main/ │ └── readme.MD # Dokumentasi Proyek ``` +

Visible for testing + */ +export declare const RANDOM_FACTOR = 0.5; + +export declare function safeGet(obj: T, key: K): T[K] | undefined; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview SHA-1 cryptographic hash. + * Variable names follow the notation in FIPS PUB 180-3: + * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf. + * + * Usage: + * var sha1 = new sha1(); + * sha1.update(bytes); + * var hash = sha1.digest(); + * + * Performance: + * Chrome 23: ~400 Mbit/s + * Firefox 16: ~250 Mbit/s + * + */ +/** + * SHA-1 cryptographic hash constructor. + * + * The properties declared here are discussed in the above algorithm document. + * @constructor + * @final + * @struct + */ +export declare class Sha1 { + /** + * Holds the previous values of accumulated variables a-e in the compress_ + * function. + * @private + */ + private chain_; + /** + * A buffer holding the partially computed hash result. + * @private + */ + private buf_; + /** + * An array of 80 bytes, each a part of the message to be hashed. Referred to + * as the message schedule in the docs. + * @private + */ + private W_; + /** + * Contains data needed to pad messages less than 64 bytes. + * @private + */ + private pad_; + /** + * @private {number} + */ + private inbuf_; + /** + * @private {number} + */ + private total_; + blockSize: number; + constructor(); + reset(): void; + /** + * Internal compress helper function. + * @param buf Block to compress. + * @param offset Offset of the block in the buffer. + * @private + */ + compress_(buf: number[] | Uint8Array | string, offset?: number): void; + update(bytes?: number[] | Uint8Array | string, length?: number): void; + /** @override */ + digest(): number[]; +} + +/** + * Returns JSON representing a javascript object. + * @param {*} data JavaScript object to be stringified. + * @return {string} The JSON contents of the object. + */ +export declare function stringify(data: unknown): string; + +/** + * Calculate length without actually converting; useful for doing cheaper validation. + * @param {string} str + * @return {number} + */ +export declare const stringLength: (str: string) => number; + +export declare interface StringLike { + toString(): string; +} + +/** + * @param {string} str + * @return {Array} + */ +export declare const stringToByteArray: (str: string) => number[]; + +/** + * The Subscribe interface has two forms - passing the inline function + * callbacks, or a object interface with callback properties. + */ +export declare interface Subscribe { + (next?: NextFn, error?: ErrorFn, complete?: CompleteFn): Unsubscribe; + (observer: PartialObserver): Unsubscribe; +} + +export declare type Unsubscribe = () => void; + +/** + * Updates Emulator Banner. Primarily used for Firebase Studio + * @param name + * @param isRunningEmulator + * @public + */ +export declare function updateEmulatorBanner(name: string, isRunningEmulator: boolean): void; + +/** + * Check to make sure the appropriate number of arguments are provided for a public function. + * Throws an error if it fails. + * + * @param fnName The function name + * @param minCount The minimum number of arguments to allow for the function call + * @param maxCount The maximum number of argument to allow for the function call + * @param argCount The actual number of arguments provided. + */ +export declare const validateArgCount: (fnName: string, minCount: number, maxCount: number, argCount: number) => void; + +export declare function validateCallback(fnName: string, argumentName: string, callback: Function, optional: boolean): void; + +export declare function validateContextObject(fnName: string, argumentName: string, context: unknown, optional: boolean): void; + +/** + * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject + * if errors occur during the database open operation. + * + * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox + * private browsing) + */ +export declare function validateIndexedDBOpenable(): Promise; + +/** + * @param fnName + * @param argumentNumber + * @param namespace + * @param optional + */ +export declare function validateNamespace(fnName: string, namespace: string, optional: boolean): void; + +export { } diff --git a/node_modules/@firebase/util/package.json b/node_modules/@firebase/util/package.json new file mode 100644 index 0000000..f168d94 --- /dev/null +++ b/node_modules/@firebase/util/package.json @@ -0,0 +1,73 @@ +{ + "name": "@firebase/util", + "version": "1.13.0", + "description": "", + "author": "Firebase (https://firebase.google.com/)", + "main": "dist/index.node.cjs.js", + "browser": "dist/index.esm.js", + "module": "dist/index.esm.js", + "exports": { + ".": { + "types": "./dist/util-public.d.ts", + "node": { + "import": "./dist/node-esm/index.node.esm.js", + "require": "./dist/index.node.cjs.js" + }, + "browser": { + "require": "./dist/index.cjs.js", + "import": "./dist/index.esm.js" + }, + "default": "./dist/index.esm.js" + }, + "./package.json": "./package.json" + }, + "files": [ + "dist", + "postinstall.js" + ], + "scripts": { + "lint": "eslint -c .eslintrc.js '**/*.ts' --ignore-path '../../.gitignore'", + "lint:fix": "eslint --fix -c .eslintrc.js '**/*.ts' --ignore-path '../../.gitignore'", + "build": "rollup -c && yarn api-report", + "build:deps": "lerna run --scope @firebase/util --include-dependencies build", + "dev": "rollup -c -w", + "prettier": "prettier --write 'src/**/*.ts' 'test/**/*.ts'", + "test": "run-p --npm-path npm lint test:all", + "test:ci": "node ../../scripts/run_tests_in_ci.js -s test:all", + "test:all": "run-p --npm-path npm test:browser test:node", + "test:browser": "karma start", + "test:node": "TS_NODE_CACHE=NO TS_NODE_COMPILER_OPTIONS='{\"module\":\"commonjs\"}' nyc --reporter lcovonly -- mocha test/**/*.test.* --config ../../config/mocharc.node.js", + "trusted-type-check": "tsec -p tsconfig.json --noEmit", + "api-report": "api-extractor run --local --verbose", + "typings:public": "node ../../scripts/build/use_typings.js ./dist/util-public.d.ts", + "postinstall": "node ./postinstall.js" + }, + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + }, + "devDependencies": { + "@rollup/plugin-replace": "6.0.2", + "rollup": "2.79.2", + "rollup-plugin-typescript2": "0.36.0", + "typescript": "5.5.4" + }, + "repository": { + "directory": "packages/util", + "type": "git", + "url": "git+https://github.com/firebase/firebase-js-sdk.git" + }, + "bugs": { + "url": "https://github.com/firebase/firebase-js-sdk/issues" + }, + "typings": "./dist/util-public.d.ts", + "nyc": { + "extension": [ + ".ts" + ], + "reportDir": "./coverage/node" + }, + "engines": { + "node": ">=20.0.0" + } +} diff --git a/node_modules/@firebase/util/postinstall.js b/node_modules/@firebase/util/postinstall.js new file mode 100644 index 0000000..6987d13 --- /dev/null +++ b/node_modules/@firebase/util/postinstall.js @@ -0,0 +1,153 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const { writeFile, readFile } = require('node:fs/promises'); +const { pathToFileURL } = require('node:url'); +const { isAbsolute, join } = require('node:path'); + +const ENV_VARIABLE = 'FIREBASE_WEBAPP_CONFIG'; + +async function getPartialConfig() { + const envVariable = process.env[ENV_VARIABLE]?.trim(); + + if (!envVariable) { + return undefined; + } + + // Like FIREBASE_CONFIG (admin autoinit) FIREBASE_WEBAPP_CONFIG can be + // either a JSON representation of FirebaseOptions or the path to a filename + if (envVariable.startsWith('{"')) { + try { + return JSON.parse(envVariable); + } catch (e) { + console.warn( + `JSON payload in \$${ENV_VARIABLE} could not be parsed, ignoring.\n`, + e + ); + return undefined; + } + } + + const fileURL = pathToFileURL( + isAbsolute(envVariable) ? envVariable : join(process.cwd(), envVariable) + ); + + try { + const fileContents = await readFile(fileURL, 'utf-8'); + return JSON.parse(fileContents); + } catch (e) { + console.warn( + `Contents of "${envVariable}" could not be parsed, ignoring \$${ENV_VARIABLE}.\n`, + e + ); + return undefined; + } +} + +async function getFinalConfig(partialConfig) { + if (!partialConfig) { + return undefined; + } + // In Firebase App Hosting the config provided to the environment variable is up-to-date and + // "complete" we should not reach out to the webConfig endpoint to freshen it + if (process.env.X_GOOGLE_TARGET_PLATFORM === 'fah') { + return partialConfig; + } + const projectId = partialConfig.projectId || '-'; + // If the projectId starts with demo- this is an demo project from the firebase emulators + // treat the config as whole + if (projectId.startsWith('demo-')) { + return partialConfig; + } + const appId = partialConfig.appId; + const apiKey = partialConfig.apiKey; + if (!appId || !apiKey) { + console.warn( + `Unable to fetch Firebase config, appId and apiKey are required, ignoring \$${ENV_VARIABLE}.` + ); + return undefined; + } + + const url = `https://firebase.googleapis.com/v1alpha/projects/${projectId}/apps/${appId}/webConfig`; + + try { + const response = await fetch(url, { + headers: { 'x-goog-api-key': apiKey } + }); + if (!response.ok) { + console.warn( + `Unable to fetch Firebase config, ignoring \$${ENV_VARIABLE}.` + ); + console.warn( + `${url} returned ${response.statusText} (${response.status})` + ); + try { + console.warn((await response.json()).error.message); + } catch (e) {} + return undefined; + } + const json = await response.json(); + return { ...json, apiKey }; + } catch (e) { + console.warn( + `Unable to fetch Firebase config, ignoring \$${ENV_VARIABLE}.\n`, + e + ); + return undefined; + } +} + +function handleUnexpectedError(e) { + console.warn( + `Unexpected error encountered in @firebase/util postinstall script, ignoring \$${ENV_VARIABLE}.` + ); + console.warn(e); + process.exit(0); +} + +getPartialConfig() + .catch(handleUnexpectedError) + .then(getFinalConfig) + .catch(handleUnexpectedError) + .then(async finalConfig => { + const defaults = finalConfig && { + config: finalConfig, + emulatorHosts: { + firestore: process.env.FIRESTORE_EMULATOR_HOST, + database: process.env.FIREBASE_DATABASE_EMULATOR_HOST, + storage: process.env.FIREBASE_STORAGE_EMULATOR_HOST, + auth: process.env.FIREBASE_AUTH_EMULATOR_HOST + } + }; + + await Promise.all([ + writeFile( + join(__dirname, 'dist', 'postinstall.js'), + `'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.getDefaultsFromPostinstall = () => (${JSON.stringify(defaults)});` + ), + writeFile( + join(__dirname, 'dist', 'postinstall.mjs'), + `const getDefaultsFromPostinstall = () => (${JSON.stringify(defaults)}); +export { getDefaultsFromPostinstall };` + ) + ]); + + process.exit(0); + }) + .catch(handleUnexpectedError); diff --git a/node_modules/@google-cloud/firestore/LICENSE b/node_modules/@google-cloud/firestore/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/@google-cloud/firestore/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@google-cloud/firestore/README.md b/node_modules/@google-cloud/firestore/README.md new file mode 100644 index 0000000..e4a5684 --- /dev/null +++ b/node_modules/@google-cloud/firestore/README.md @@ -0,0 +1,181 @@ +[//]: # "This README.md file is auto-generated, all changes to this file will be lost." +[//]: # "To regenerate it, use `python -m synthtool`." +Google Cloud Platform logo + +# [Cloud Firestore: Node.js Client](https://github.com/googleapis/nodejs-firestore) + +[![release level](https://img.shields.io/badge/release%20level-stable-brightgreen.svg?style=flat)](https://cloud.google.com/terms/launch-stages) +[![npm version](https://img.shields.io/npm/v/@google-cloud/firestore.svg)](https://www.npmjs.org/package/@google-cloud/firestore) + + + + +This is the Node.js Server SDK for [Google Cloud Firestore](https://firebase.google.com/docs/firestore/). Google Cloud Firestore is a NoSQL document database built for automatic scaling, high performance, and ease of application development. + +This Cloud Firestore Server SDK uses Google’s Cloud Identity and Access Management for authentication and should only be used in trusted environments. Your Cloud Identity credentials allow you bypass all access restrictions and provide read and write access to all data in your Cloud Firestore project. + +The Cloud Firestore Server SDKs are designed to manage the full set of data in your Cloud Firestore project and work best with reliable network connectivity. Data operations performed via these SDKs directly access the Cloud Firestore backend and all document reads and writes are optimized for high throughput. + +Applications that use Google's Server SDKs should not be used in end-user environments, such as on phones or on publicly hosted websites. If you are developing a Web or Node.js application that accesses Cloud Firestore on behalf of end users, use the firebase Client SDK. + +**Note:** This Cloud Firestore Server SDK does not support Firestore databases created in [Datastore mode](https://cloud.google.com/datastore/docs/firestore-or-datastore#in_datastore_mode). To access these databases, use the [Datastore SDK](https://www.npmjs.com/package/@google-cloud/datastore). + + +A comprehensive list of changes in each version may be found in +[the CHANGELOG](https://github.com/googleapis/nodejs-firestore/blob/main/CHANGELOG.md). + +* [Cloud Firestore Node.js Client API Reference][client-docs] +* [Cloud Firestore Documentation][product-docs] +* [github.com/googleapis/nodejs-firestore](https://github.com/googleapis/nodejs-firestore) + +Read more about the client libraries for Cloud APIs, including the older +Google APIs Client Libraries, in [Client Libraries Explained][explained]. + +[explained]: https://cloud.google.com/apis/docs/client-libraries-explained + +**Table of contents:** + + +* [Quickstart](#quickstart) + * [Before you begin](#before-you-begin) + * [Installing the client library](#installing-the-client-library) + * [Using the client library](#using-the-client-library) +* [Samples](#samples) +* [Versioning](#versioning) +* [Contributing](#contributing) +* [License](#license) + +## Quickstart + +### Before you begin + +1. [Select or create a Cloud Platform project][projects]. +1. [Enable the Cloud Firestore API][enable_api]. +1. [Set up authentication][auth] so you can access the + API from your local workstation. + +### Installing the client library + +```bash +npm install @google-cloud/firestore +``` + + +### Using the client library + +```javascript +const {Firestore} = require('@google-cloud/firestore'); + +// Create a new client +const firestore = new Firestore(); + +async function quickstart() { + // Obtain a document reference. + const document = firestore.doc('posts/intro-to-firestore'); + + // Enter new data into the document. + await document.set({ + title: 'Welcome to Firestore', + body: 'Hello World', + }); + console.log('Entered new data into the document'); + + // Update an existing document. + await document.update({ + body: 'My first Firestore app', + }); + console.log('Updated an existing document'); + + // Read the document. + const doc = await document.get(); + console.log('Read the document'); + + // Delete the document. + await document.delete(); + console.log('Deleted the document'); +} +quickstart(); + +``` + + + +## Samples + +Samples are in the [`samples/`](https://github.com/googleapis/nodejs-firestore/tree/main/samples) directory. Each sample's `README.md` has instructions for running its sample. + +| Sample | Source Code | Try it | +| --------------------------- | --------------------------------- | ------ | +| Limit-to-last-query | [source code](https://github.com/googleapis/nodejs-firestore/blob/main/samples/limit-to-last-query.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-firestore&page=editor&open_in_editor=samples/limit-to-last-query.js,samples/README.md) | +| Quickstart | [source code](https://github.com/googleapis/nodejs-firestore/blob/main/samples/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-firestore&page=editor&open_in_editor=samples/quickstart.js,samples/README.md) | +| Solution-counters | [source code](https://github.com/googleapis/nodejs-firestore/blob/main/samples/solution-counters.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-firestore&page=editor&open_in_editor=samples/solution-counters.js,samples/README.md) | + + + +The [Cloud Firestore Node.js Client API Reference][client-docs] documentation +also contains samples. + +## Supported Node.js Versions + +Our client libraries follow the [Node.js release schedule](https://github.com/nodejs/release#release-schedule). +Libraries are compatible with all current _active_ and _maintenance_ versions of +Node.js. +If you are using an end-of-life version of Node.js, we recommend that you update +as soon as possible to an actively supported LTS version. + +Google's client libraries support legacy versions of Node.js runtimes on a +best-efforts basis with the following warnings: + +* Legacy versions are not tested in continuous integration. +* Some security patches and features cannot be backported. +* Dependencies cannot be kept up-to-date. + +Client libraries targeting some end-of-life versions of Node.js are available, and +can be installed through npm [dist-tags](https://docs.npmjs.com/cli/dist-tag). +The dist-tags follow the naming convention `legacy-(version)`. +For example, `npm install @google-cloud/firestore@legacy-8` installs client libraries +for versions compatible with Node.js 8. + +## Versioning + +This library follows [Semantic Versioning](http://semver.org/). + + + +This library is considered to be **stable**. The code surface will not change in backwards-incompatible ways +unless absolutely necessary (e.g. because of critical security issues) or with +an extensive deprecation period. Issues and requests against **stable** libraries +are addressed with the highest priority. + + + + + + +More Information: [Google Cloud Platform Launch Stages][launch_stages] + +[launch_stages]: https://cloud.google.com/terms/launch-stages + +## Contributing + +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/nodejs-firestore/blob/main/CONTRIBUTING.md). + +Please note that this `README.md`, the `samples/README.md`, +and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) +are generated from a central template. To edit one of these files, make an edit +to its templates in +[directory](https://github.com/googleapis/synthtool). + +## License + +Apache Version 2.0 + +See [LICENSE](https://github.com/googleapis/nodejs-firestore/blob/main/LICENSE) + +[client-docs]: https://cloud.google.com/nodejs/docs/reference/firestore/latest +[product-docs]: https://cloud.google.com/firestore +[shell_img]: https://gstatic.com/cloudssh/images/open-btn.png +[projects]: https://console.cloud.google.com/project +[billing]: https://support.google.com/cloud/answer/6293499#enable-billing +[enable_api]: https://console.cloud.google.com/flows/enableapi?apiid=firestore.googleapis.com +[auth]: https://cloud.google.com/docs/authentication/external/set-up-adc-local diff --git a/node_modules/@google-cloud/firestore/build/protos/admin_v1.json b/node_modules/@google-cloud/firestore/build/protos/admin_v1.json new file mode 100644 index 0000000..a5175f2 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/admin_v1.json @@ -0,0 +1 @@ +{"options":{"syntax":"proto3"},"nested":{"google":{"nested":{"firestore":{"nested":{"admin":{"nested":{"v1":{"options":{"csharp_namespace":"Google.Cloud.Firestore.Admin.V1","go_package":"cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb","java_multiple_files":true,"java_outer_classname":"LocationProto","java_package":"com.google.firestore.admin.v1","objc_class_prefix":"GCFS","php_namespace":"Google\\Cloud\\Firestore\\Admin\\V1","ruby_package":"Google::Cloud::Firestore::Admin::V1","(google.api.resource_definition).type":"firestore.googleapis.com/CollectionGroup","(google.api.resource_definition).pattern":"projects/{project}/databases/{database}/collectionGroups/{collection}"},"nested":{"Backup":{"options":{"(google.api.resource).type":"firestore.googleapis.com/Backup","(google.api.resource).pattern":"projects/{project}/locations/{location}/backups/{backup}"},"fields":{"name":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}},"database":{"type":"string","id":2,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY","(google.api.resource_reference).type":"firestore.googleapis.com/Database"}},"databaseUid":{"type":"string","id":7,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}},"snapshotTime":{"type":"google.protobuf.Timestamp","id":3,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}},"expireTime":{"type":"google.protobuf.Timestamp","id":4,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}},"stats":{"type":"Stats","id":6,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}},"state":{"type":"State","id":8,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}}},"nested":{"Stats":{"fields":{"sizeBytes":{"type":"int64","id":1,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}},"documentCount":{"type":"int64","id":2,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}},"indexCount":{"type":"int64","id":3,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}}}},"State":{"values":{"STATE_UNSPECIFIED":0,"CREATING":1,"READY":2,"NOT_AVAILABLE":3}}}},"Database":{"options":{"(google.api.resource).type":"firestore.googleapis.com/Database","(google.api.resource).pattern":"projects/{project}/databases/{database}","(google.api.resource).style":"DECLARATIVE_FRIENDLY"},"fields":{"name":{"type":"string","id":1},"uid":{"type":"string","id":3,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}},"createTime":{"type":"google.protobuf.Timestamp","id":5,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}},"updateTime":{"type":"google.protobuf.Timestamp","id":6,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}},"deleteTime":{"type":"google.protobuf.Timestamp","id":7,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}},"locationId":{"type":"string","id":9},"type":{"type":"DatabaseType","id":10},"concurrencyMode":{"type":"ConcurrencyMode","id":15},"versionRetentionPeriod":{"type":"google.protobuf.Duration","id":17,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}},"earliestVersionTime":{"type":"google.protobuf.Timestamp","id":18,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}},"pointInTimeRecoveryEnablement":{"type":"PointInTimeRecoveryEnablement","id":21},"appEngineIntegrationMode":{"type":"AppEngineIntegrationMode","id":19},"keyPrefix":{"type":"string","id":20,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}},"deleteProtectionState":{"type":"DeleteProtectionState","id":22},"cmekConfig":{"type":"CmekConfig","id":23,"options":{"(google.api.field_behavior)":"OPTIONAL"}},"previousId":{"type":"string","id":25,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}},"sourceInfo":{"type":"SourceInfo","id":26,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}},"etag":{"type":"string","id":99}},"nested":{"DatabaseType":{"values":{"DATABASE_TYPE_UNSPECIFIED":0,"FIRESTORE_NATIVE":1,"DATASTORE_MODE":2}},"ConcurrencyMode":{"values":{"CONCURRENCY_MODE_UNSPECIFIED":0,"OPTIMISTIC":1,"PESSIMISTIC":2,"OPTIMISTIC_WITH_ENTITY_GROUPS":3}},"PointInTimeRecoveryEnablement":{"values":{"POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED":0,"POINT_IN_TIME_RECOVERY_ENABLED":1,"POINT_IN_TIME_RECOVERY_DISABLED":2}},"AppEngineIntegrationMode":{"values":{"APP_ENGINE_INTEGRATION_MODE_UNSPECIFIED":0,"ENABLED":1,"DISABLED":2}},"DeleteProtectionState":{"values":{"DELETE_PROTECTION_STATE_UNSPECIFIED":0,"DELETE_PROTECTION_DISABLED":1,"DELETE_PROTECTION_ENABLED":2}},"CmekConfig":{"fields":{"kmsKeyName":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"activeKeyVersion":{"rule":"repeated","type":"string","id":2,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}}}},"SourceInfo":{"oneofs":{"source":{"oneof":["backup"]}},"fields":{"backup":{"type":"BackupSource","id":1},"operation":{"type":"string","id":3,"options":{"(google.api.resource_reference).type":"firestore.googleapis.com/Operation"}}},"nested":{"BackupSource":{"fields":{"backup":{"type":"string","id":1,"options":{"(google.api.resource_reference).type":"firestore.googleapis.com/Backup"}}}}}},"EncryptionConfig":{"oneofs":{"encryptionType":{"oneof":["googleDefaultEncryption","useSourceEncryption","customerManagedEncryption"]}},"fields":{"googleDefaultEncryption":{"type":"GoogleDefaultEncryptionOptions","id":1},"useSourceEncryption":{"type":"SourceEncryptionOptions","id":2},"customerManagedEncryption":{"type":"CustomerManagedEncryptionOptions","id":3}},"nested":{"GoogleDefaultEncryptionOptions":{"fields":{}},"SourceEncryptionOptions":{"fields":{}},"CustomerManagedEncryptionOptions":{"fields":{"kmsKeyName":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}}}}}}}},"Field":{"options":{"(google.api.resource).type":"firestore.googleapis.com/Field","(google.api.resource).pattern":"projects/{project}/databases/{database}/collectionGroups/{collection}/fields/{field}"},"fields":{"name":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"indexConfig":{"type":"IndexConfig","id":2},"ttlConfig":{"type":"TtlConfig","id":3}},"nested":{"IndexConfig":{"fields":{"indexes":{"rule":"repeated","type":"Index","id":1},"usesAncestorConfig":{"type":"bool","id":2},"ancestorField":{"type":"string","id":3},"reverting":{"type":"bool","id":4}}},"TtlConfig":{"fields":{"state":{"type":"State","id":1,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}}},"nested":{"State":{"values":{"STATE_UNSPECIFIED":0,"CREATING":1,"ACTIVE":2,"NEEDS_REPAIR":3}}}}}},"Index":{"options":{"(google.api.resource).type":"firestore.googleapis.com/Index","(google.api.resource).pattern":"projects/{project}/databases/{database}/collectionGroups/{collection}/indexes/{index}"},"fields":{"name":{"type":"string","id":1},"queryScope":{"type":"QueryScope","id":2},"apiScope":{"type":"ApiScope","id":5},"fields":{"rule":"repeated","type":"IndexField","id":3},"state":{"type":"State","id":4}},"nested":{"QueryScope":{"values":{"QUERY_SCOPE_UNSPECIFIED":0,"COLLECTION":1,"COLLECTION_GROUP":2,"COLLECTION_RECURSIVE":3}},"ApiScope":{"values":{"ANY_API":0,"DATASTORE_MODE_API":1}},"IndexField":{"oneofs":{"valueMode":{"oneof":["order","arrayConfig","vectorConfig"]}},"fields":{"fieldPath":{"type":"string","id":1},"order":{"type":"Order","id":2},"arrayConfig":{"type":"ArrayConfig","id":3},"vectorConfig":{"type":"VectorConfig","id":4}},"nested":{"Order":{"values":{"ORDER_UNSPECIFIED":0,"ASCENDING":1,"DESCENDING":2}},"ArrayConfig":{"values":{"ARRAY_CONFIG_UNSPECIFIED":0,"CONTAINS":1}},"VectorConfig":{"oneofs":{"type":{"oneof":["flat"]}},"fields":{"dimension":{"type":"int32","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"flat":{"type":"FlatIndex","id":2}},"nested":{"FlatIndex":{"fields":{}}}}}},"State":{"values":{"STATE_UNSPECIFIED":0,"CREATING":1,"READY":2,"NEEDS_REPAIR":3}}}},"FirestoreAdmin":{"options":{"(google.api.default_host)":"firestore.googleapis.com","(google.api.oauth_scopes)":"https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/datastore"},"methods":{"CreateIndex":{"requestType":"CreateIndexRequest","responseType":"google.longrunning.Operation","options":{"(google.api.http).post":"/v1/{parent=projects/*/databases/*/collectionGroups/*}/indexes","(google.api.http).body":"index","(google.api.method_signature)":"parent,index","(google.longrunning.operation_info).response_type":"Index","(google.longrunning.operation_info).metadata_type":"IndexOperationMetadata"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{parent=projects/*/databases/*/collectionGroups/*}/indexes","body":"index"}},{"(google.api.method_signature)":"parent,index"},{"(google.longrunning.operation_info)":{"response_type":"Index","metadata_type":"IndexOperationMetadata"}}]},"ListIndexes":{"requestType":"ListIndexesRequest","responseType":"ListIndexesResponse","options":{"(google.api.http).get":"/v1/{parent=projects/*/databases/*/collectionGroups/*}/indexes","(google.api.method_signature)":"parent"},"parsedOptions":[{"(google.api.http)":{"get":"/v1/{parent=projects/*/databases/*/collectionGroups/*}/indexes"}},{"(google.api.method_signature)":"parent"}]},"GetIndex":{"requestType":"GetIndexRequest","responseType":"Index","options":{"(google.api.http).get":"/v1/{name=projects/*/databases/*/collectionGroups/*/indexes/*}","(google.api.method_signature)":"name"},"parsedOptions":[{"(google.api.http)":{"get":"/v1/{name=projects/*/databases/*/collectionGroups/*/indexes/*}"}},{"(google.api.method_signature)":"name"}]},"DeleteIndex":{"requestType":"DeleteIndexRequest","responseType":"google.protobuf.Empty","options":{"(google.api.http).delete":"/v1/{name=projects/*/databases/*/collectionGroups/*/indexes/*}","(google.api.method_signature)":"name"},"parsedOptions":[{"(google.api.http)":{"delete":"/v1/{name=projects/*/databases/*/collectionGroups/*/indexes/*}"}},{"(google.api.method_signature)":"name"}]},"GetField":{"requestType":"GetFieldRequest","responseType":"Field","options":{"(google.api.http).get":"/v1/{name=projects/*/databases/*/collectionGroups/*/fields/*}","(google.api.method_signature)":"name"},"parsedOptions":[{"(google.api.http)":{"get":"/v1/{name=projects/*/databases/*/collectionGroups/*/fields/*}"}},{"(google.api.method_signature)":"name"}]},"UpdateField":{"requestType":"UpdateFieldRequest","responseType":"google.longrunning.Operation","options":{"(google.api.http).patch":"/v1/{field.name=projects/*/databases/*/collectionGroups/*/fields/*}","(google.api.http).body":"field","(google.api.method_signature)":"field","(google.longrunning.operation_info).response_type":"Field","(google.longrunning.operation_info).metadata_type":"FieldOperationMetadata"},"parsedOptions":[{"(google.api.http)":{"patch":"/v1/{field.name=projects/*/databases/*/collectionGroups/*/fields/*}","body":"field"}},{"(google.api.method_signature)":"field"},{"(google.longrunning.operation_info)":{"response_type":"Field","metadata_type":"FieldOperationMetadata"}}]},"ListFields":{"requestType":"ListFieldsRequest","responseType":"ListFieldsResponse","options":{"(google.api.http).get":"/v1/{parent=projects/*/databases/*/collectionGroups/*}/fields","(google.api.method_signature)":"parent"},"parsedOptions":[{"(google.api.http)":{"get":"/v1/{parent=projects/*/databases/*/collectionGroups/*}/fields"}},{"(google.api.method_signature)":"parent"}]},"ExportDocuments":{"requestType":"ExportDocumentsRequest","responseType":"google.longrunning.Operation","options":{"(google.api.http).post":"/v1/{name=projects/*/databases/*}:exportDocuments","(google.api.http).body":"*","(google.api.method_signature)":"name","(google.longrunning.operation_info).response_type":"ExportDocumentsResponse","(google.longrunning.operation_info).metadata_type":"ExportDocumentsMetadata"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{name=projects/*/databases/*}:exportDocuments","body":"*"}},{"(google.api.method_signature)":"name"},{"(google.longrunning.operation_info)":{"response_type":"ExportDocumentsResponse","metadata_type":"ExportDocumentsMetadata"}}]},"ImportDocuments":{"requestType":"ImportDocumentsRequest","responseType":"google.longrunning.Operation","options":{"(google.api.http).post":"/v1/{name=projects/*/databases/*}:importDocuments","(google.api.http).body":"*","(google.api.method_signature)":"name","(google.longrunning.operation_info).response_type":"google.protobuf.Empty","(google.longrunning.operation_info).metadata_type":"ImportDocumentsMetadata"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{name=projects/*/databases/*}:importDocuments","body":"*"}},{"(google.api.method_signature)":"name"},{"(google.longrunning.operation_info)":{"response_type":"google.protobuf.Empty","metadata_type":"ImportDocumentsMetadata"}}]},"BulkDeleteDocuments":{"requestType":"BulkDeleteDocumentsRequest","responseType":"google.longrunning.Operation","options":{"(google.api.http).post":"/v1/{name=projects/*/databases/*}:bulkDeleteDocuments","(google.api.http).body":"*","(google.api.method_signature)":"name","(google.longrunning.operation_info).response_type":"BulkDeleteDocumentsResponse","(google.longrunning.operation_info).metadata_type":"BulkDeleteDocumentsMetadata"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{name=projects/*/databases/*}:bulkDeleteDocuments","body":"*"}},{"(google.api.method_signature)":"name"},{"(google.longrunning.operation_info)":{"response_type":"BulkDeleteDocumentsResponse","metadata_type":"BulkDeleteDocumentsMetadata"}}]},"CreateDatabase":{"requestType":"CreateDatabaseRequest","responseType":"google.longrunning.Operation","options":{"(google.api.http).post":"/v1/{parent=projects/*}/databases","(google.api.http).body":"database","(google.api.method_signature)":"parent,database,database_id","(google.longrunning.operation_info).response_type":"Database","(google.longrunning.operation_info).metadata_type":"CreateDatabaseMetadata"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{parent=projects/*}/databases","body":"database"}},{"(google.api.method_signature)":"parent,database,database_id"},{"(google.longrunning.operation_info)":{"response_type":"Database","metadata_type":"CreateDatabaseMetadata"}}]},"GetDatabase":{"requestType":"GetDatabaseRequest","responseType":"Database","options":{"(google.api.http).get":"/v1/{name=projects/*/databases/*}","(google.api.method_signature)":"name"},"parsedOptions":[{"(google.api.http)":{"get":"/v1/{name=projects/*/databases/*}"}},{"(google.api.method_signature)":"name"}]},"ListDatabases":{"requestType":"ListDatabasesRequest","responseType":"ListDatabasesResponse","options":{"(google.api.http).get":"/v1/{parent=projects/*}/databases","(google.api.method_signature)":"parent"},"parsedOptions":[{"(google.api.http)":{"get":"/v1/{parent=projects/*}/databases"}},{"(google.api.method_signature)":"parent"}]},"UpdateDatabase":{"requestType":"UpdateDatabaseRequest","responseType":"google.longrunning.Operation","options":{"(google.api.http).patch":"/v1/{database.name=projects/*/databases/*}","(google.api.http).body":"database","(google.api.method_signature)":"database,update_mask","(google.longrunning.operation_info).response_type":"Database","(google.longrunning.operation_info).metadata_type":"UpdateDatabaseMetadata"},"parsedOptions":[{"(google.api.http)":{"patch":"/v1/{database.name=projects/*/databases/*}","body":"database"}},{"(google.api.method_signature)":"database,update_mask"},{"(google.longrunning.operation_info)":{"response_type":"Database","metadata_type":"UpdateDatabaseMetadata"}}]},"DeleteDatabase":{"requestType":"DeleteDatabaseRequest","responseType":"google.longrunning.Operation","options":{"(google.api.http).delete":"/v1/{name=projects/*/databases/*}","(google.api.method_signature)":"name","(google.longrunning.operation_info).response_type":"Database","(google.longrunning.operation_info).metadata_type":"DeleteDatabaseMetadata"},"parsedOptions":[{"(google.api.http)":{"delete":"/v1/{name=projects/*/databases/*}"}},{"(google.api.method_signature)":"name"},{"(google.longrunning.operation_info)":{"response_type":"Database","metadata_type":"DeleteDatabaseMetadata"}}]},"GetBackup":{"requestType":"GetBackupRequest","responseType":"Backup","options":{"(google.api.http).get":"/v1/{name=projects/*/locations/*/backups/*}","(google.api.method_signature)":"name"},"parsedOptions":[{"(google.api.http)":{"get":"/v1/{name=projects/*/locations/*/backups/*}"}},{"(google.api.method_signature)":"name"}]},"ListBackups":{"requestType":"ListBackupsRequest","responseType":"ListBackupsResponse","options":{"(google.api.http).get":"/v1/{parent=projects/*/locations/*}/backups","(google.api.method_signature)":"parent"},"parsedOptions":[{"(google.api.http)":{"get":"/v1/{parent=projects/*/locations/*}/backups"}},{"(google.api.method_signature)":"parent"}]},"DeleteBackup":{"requestType":"DeleteBackupRequest","responseType":"google.protobuf.Empty","options":{"(google.api.http).delete":"/v1/{name=projects/*/locations/*/backups/*}","(google.api.method_signature)":"name"},"parsedOptions":[{"(google.api.http)":{"delete":"/v1/{name=projects/*/locations/*/backups/*}"}},{"(google.api.method_signature)":"name"}]},"RestoreDatabase":{"requestType":"RestoreDatabaseRequest","responseType":"google.longrunning.Operation","options":{"(google.api.http).post":"/v1/{parent=projects/*}/databases:restore","(google.api.http).body":"*","(google.longrunning.operation_info).response_type":"Database","(google.longrunning.operation_info).metadata_type":"RestoreDatabaseMetadata"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{parent=projects/*}/databases:restore","body":"*"}},{"(google.longrunning.operation_info)":{"response_type":"Database","metadata_type":"RestoreDatabaseMetadata"}}]},"CreateBackupSchedule":{"requestType":"CreateBackupScheduleRequest","responseType":"BackupSchedule","options":{"(google.api.http).post":"/v1/{parent=projects/*/databases/*}/backupSchedules","(google.api.http).body":"backup_schedule","(google.api.method_signature)":"parent,backup_schedule"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{parent=projects/*/databases/*}/backupSchedules","body":"backup_schedule"}},{"(google.api.method_signature)":"parent,backup_schedule"}]},"GetBackupSchedule":{"requestType":"GetBackupScheduleRequest","responseType":"BackupSchedule","options":{"(google.api.http).get":"/v1/{name=projects/*/databases/*/backupSchedules/*}","(google.api.method_signature)":"name"},"parsedOptions":[{"(google.api.http)":{"get":"/v1/{name=projects/*/databases/*/backupSchedules/*}"}},{"(google.api.method_signature)":"name"}]},"ListBackupSchedules":{"requestType":"ListBackupSchedulesRequest","responseType":"ListBackupSchedulesResponse","options":{"(google.api.http).get":"/v1/{parent=projects/*/databases/*}/backupSchedules","(google.api.method_signature)":"parent"},"parsedOptions":[{"(google.api.http)":{"get":"/v1/{parent=projects/*/databases/*}/backupSchedules"}},{"(google.api.method_signature)":"parent"}]},"UpdateBackupSchedule":{"requestType":"UpdateBackupScheduleRequest","responseType":"BackupSchedule","options":{"(google.api.http).patch":"/v1/{backup_schedule.name=projects/*/databases/*/backupSchedules/*}","(google.api.http).body":"backup_schedule","(google.api.method_signature)":"backup_schedule,update_mask"},"parsedOptions":[{"(google.api.http)":{"patch":"/v1/{backup_schedule.name=projects/*/databases/*/backupSchedules/*}","body":"backup_schedule"}},{"(google.api.method_signature)":"backup_schedule,update_mask"}]},"DeleteBackupSchedule":{"requestType":"DeleteBackupScheduleRequest","responseType":"google.protobuf.Empty","options":{"(google.api.http).delete":"/v1/{name=projects/*/databases/*/backupSchedules/*}","(google.api.method_signature)":"name"},"parsedOptions":[{"(google.api.http)":{"delete":"/v1/{name=projects/*/databases/*/backupSchedules/*}"}},{"(google.api.method_signature)":"name"}]}}},"ListDatabasesRequest":{"fields":{"parent":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).child_type":"firestore.googleapis.com/Database"}},"showDeleted":{"type":"bool","id":4}}},"CreateDatabaseRequest":{"fields":{"parent":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).child_type":"firestore.googleapis.com/Database"}},"database":{"type":"Database","id":2,"options":{"(google.api.field_behavior)":"REQUIRED"}},"databaseId":{"type":"string","id":3,"options":{"(google.api.field_behavior)":"REQUIRED"}}}},"CreateDatabaseMetadata":{"fields":{}},"ListDatabasesResponse":{"fields":{"databases":{"rule":"repeated","type":"Database","id":1},"unreachable":{"rule":"repeated","type":"string","id":3}}},"GetDatabaseRequest":{"fields":{"name":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"firestore.googleapis.com/Database"}}}},"UpdateDatabaseRequest":{"fields":{"database":{"type":"Database","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"updateMask":{"type":"google.protobuf.FieldMask","id":2}}},"UpdateDatabaseMetadata":{"fields":{}},"DeleteDatabaseRequest":{"fields":{"name":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"firestore.googleapis.com/Database"}},"etag":{"type":"string","id":3}}},"DeleteDatabaseMetadata":{"fields":{}},"CreateBackupScheduleRequest":{"fields":{"parent":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"firestore.googleapis.com/Database"}},"backupSchedule":{"type":"BackupSchedule","id":2,"options":{"(google.api.field_behavior)":"REQUIRED"}}}},"GetBackupScheduleRequest":{"fields":{"name":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"firestore.googleapis.com/BackupSchedule"}}}},"UpdateBackupScheduleRequest":{"fields":{"backupSchedule":{"type":"BackupSchedule","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"updateMask":{"type":"google.protobuf.FieldMask","id":2}}},"ListBackupSchedulesRequest":{"fields":{"parent":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"firestore.googleapis.com/Database"}}}},"ListBackupSchedulesResponse":{"fields":{"backupSchedules":{"rule":"repeated","type":"BackupSchedule","id":1}}},"DeleteBackupScheduleRequest":{"fields":{"name":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"firestore.googleapis.com/BackupSchedule"}}}},"CreateIndexRequest":{"fields":{"parent":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"firestore.googleapis.com/CollectionGroup"}},"index":{"type":"Index","id":2,"options":{"(google.api.field_behavior)":"REQUIRED"}}}},"ListIndexesRequest":{"fields":{"parent":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"firestore.googleapis.com/CollectionGroup"}},"filter":{"type":"string","id":2},"pageSize":{"type":"int32","id":3},"pageToken":{"type":"string","id":4}}},"ListIndexesResponse":{"fields":{"indexes":{"rule":"repeated","type":"Index","id":1},"nextPageToken":{"type":"string","id":2}}},"GetIndexRequest":{"fields":{"name":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"firestore.googleapis.com/Index"}}}},"DeleteIndexRequest":{"fields":{"name":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"firestore.googleapis.com/Index"}}}},"UpdateFieldRequest":{"fields":{"field":{"type":"Field","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"updateMask":{"type":"google.protobuf.FieldMask","id":2}}},"GetFieldRequest":{"fields":{"name":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"firestore.googleapis.com/Field"}}}},"ListFieldsRequest":{"fields":{"parent":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"firestore.googleapis.com/CollectionGroup"}},"filter":{"type":"string","id":2},"pageSize":{"type":"int32","id":3},"pageToken":{"type":"string","id":4}}},"ListFieldsResponse":{"fields":{"fields":{"rule":"repeated","type":"Field","id":1},"nextPageToken":{"type":"string","id":2}}},"ExportDocumentsRequest":{"fields":{"name":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"firestore.googleapis.com/Database"}},"collectionIds":{"rule":"repeated","type":"string","id":2},"outputUriPrefix":{"type":"string","id":3},"namespaceIds":{"rule":"repeated","type":"string","id":4},"snapshotTime":{"type":"google.protobuf.Timestamp","id":5}}},"ImportDocumentsRequest":{"fields":{"name":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"firestore.googleapis.com/Database"}},"collectionIds":{"rule":"repeated","type":"string","id":2},"inputUriPrefix":{"type":"string","id":3},"namespaceIds":{"rule":"repeated","type":"string","id":4}}},"BulkDeleteDocumentsRequest":{"fields":{"name":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"firestore.googleapis.com/Database"}},"collectionIds":{"rule":"repeated","type":"string","id":2,"options":{"(google.api.field_behavior)":"OPTIONAL"}},"namespaceIds":{"rule":"repeated","type":"string","id":3,"options":{"(google.api.field_behavior)":"OPTIONAL"}}}},"BulkDeleteDocumentsResponse":{"fields":{}},"GetBackupRequest":{"fields":{"name":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"firestore.googleapis.com/Backup"}}}},"ListBackupsRequest":{"fields":{"parent":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"firestore.googleapis.com/Location"}},"filter":{"type":"string","id":2}}},"ListBackupsResponse":{"fields":{"backups":{"rule":"repeated","type":"Backup","id":1},"unreachable":{"rule":"repeated","type":"string","id":3}}},"DeleteBackupRequest":{"fields":{"name":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"firestore.googleapis.com/Backup"}}}},"RestoreDatabaseRequest":{"fields":{"parent":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).child_type":"firestore.googleapis.com/Database"}},"databaseId":{"type":"string","id":2,"options":{"(google.api.field_behavior)":"REQUIRED"}},"backup":{"type":"string","id":3,"options":{"(google.api.field_behavior)":"REQUIRED","(google.api.resource_reference).type":"firestore.googleapis.com/Backup"}},"encryptionConfig":{"type":"Database.EncryptionConfig","id":9,"options":{"(google.api.field_behavior)":"OPTIONAL"}}}},"IndexOperationMetadata":{"fields":{"startTime":{"type":"google.protobuf.Timestamp","id":1},"endTime":{"type":"google.protobuf.Timestamp","id":2},"index":{"type":"string","id":3},"state":{"type":"OperationState","id":4},"progressDocuments":{"type":"Progress","id":5},"progressBytes":{"type":"Progress","id":6}}},"FieldOperationMetadata":{"fields":{"startTime":{"type":"google.protobuf.Timestamp","id":1},"endTime":{"type":"google.protobuf.Timestamp","id":2},"field":{"type":"string","id":3},"indexConfigDeltas":{"rule":"repeated","type":"IndexConfigDelta","id":4},"state":{"type":"OperationState","id":5},"progressDocuments":{"type":"Progress","id":6},"progressBytes":{"type":"Progress","id":7},"ttlConfigDelta":{"type":"TtlConfigDelta","id":8}},"nested":{"IndexConfigDelta":{"fields":{"changeType":{"type":"ChangeType","id":1},"index":{"type":"Index","id":2}},"nested":{"ChangeType":{"values":{"CHANGE_TYPE_UNSPECIFIED":0,"ADD":1,"REMOVE":2}}}},"TtlConfigDelta":{"fields":{"changeType":{"type":"ChangeType","id":1}},"nested":{"ChangeType":{"values":{"CHANGE_TYPE_UNSPECIFIED":0,"ADD":1,"REMOVE":2}}}}}},"ExportDocumentsMetadata":{"fields":{"startTime":{"type":"google.protobuf.Timestamp","id":1},"endTime":{"type":"google.protobuf.Timestamp","id":2},"operationState":{"type":"OperationState","id":3},"progressDocuments":{"type":"Progress","id":4},"progressBytes":{"type":"Progress","id":5},"collectionIds":{"rule":"repeated","type":"string","id":6},"outputUriPrefix":{"type":"string","id":7},"namespaceIds":{"rule":"repeated","type":"string","id":8},"snapshotTime":{"type":"google.protobuf.Timestamp","id":9}}},"ImportDocumentsMetadata":{"fields":{"startTime":{"type":"google.protobuf.Timestamp","id":1},"endTime":{"type":"google.protobuf.Timestamp","id":2},"operationState":{"type":"OperationState","id":3},"progressDocuments":{"type":"Progress","id":4},"progressBytes":{"type":"Progress","id":5},"collectionIds":{"rule":"repeated","type":"string","id":6},"inputUriPrefix":{"type":"string","id":7},"namespaceIds":{"rule":"repeated","type":"string","id":8}}},"BulkDeleteDocumentsMetadata":{"fields":{"startTime":{"type":"google.protobuf.Timestamp","id":1},"endTime":{"type":"google.protobuf.Timestamp","id":2},"operationState":{"type":"OperationState","id":3},"progressDocuments":{"type":"Progress","id":4},"progressBytes":{"type":"Progress","id":5},"collectionIds":{"rule":"repeated","type":"string","id":6},"namespaceIds":{"rule":"repeated","type":"string","id":7},"snapshotTime":{"type":"google.protobuf.Timestamp","id":8}}},"ExportDocumentsResponse":{"fields":{"outputUriPrefix":{"type":"string","id":1}}},"RestoreDatabaseMetadata":{"fields":{"startTime":{"type":"google.protobuf.Timestamp","id":1},"endTime":{"type":"google.protobuf.Timestamp","id":2},"operationState":{"type":"OperationState","id":3},"database":{"type":"string","id":4,"options":{"(google.api.resource_reference).type":"firestore.googleapis.com/Database"}},"backup":{"type":"string","id":5,"options":{"(google.api.resource_reference).type":"firestore.googleapis.com/Backup"}},"progressPercentage":{"type":"Progress","id":8}}},"Progress":{"fields":{"estimatedWork":{"type":"int64","id":1},"completedWork":{"type":"int64","id":2}}},"OperationState":{"values":{"OPERATION_STATE_UNSPECIFIED":0,"INITIALIZING":1,"PROCESSING":2,"CANCELLING":3,"FINALIZING":4,"SUCCESSFUL":5,"FAILED":6,"CANCELLED":7}},"BackupSchedule":{"options":{"(google.api.resource).type":"firestore.googleapis.com/BackupSchedule","(google.api.resource).pattern":"projects/{project}/databases/{database}/backupSchedules/{backup_schedule}"},"oneofs":{"recurrence":{"oneof":["dailyRecurrence","weeklyRecurrence"]}},"fields":{"name":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}},"createTime":{"type":"google.protobuf.Timestamp","id":3,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}},"updateTime":{"type":"google.protobuf.Timestamp","id":10,"options":{"(google.api.field_behavior)":"OUTPUT_ONLY"}},"retention":{"type":"google.protobuf.Duration","id":6},"dailyRecurrence":{"type":"DailyRecurrence","id":7},"weeklyRecurrence":{"type":"WeeklyRecurrence","id":8}}},"DailyRecurrence":{"fields":{}},"WeeklyRecurrence":{"fields":{"day":{"type":"google.type.DayOfWeek","id":2}}},"LocationMetadata":{"fields":{}}}}}}}},"api":{"options":{"go_package":"google.golang.org/genproto/googleapis/api;api","java_multiple_files":true,"java_outer_classname":"LaunchStageProto","java_package":"com.google.api","objc_class_prefix":"GAPI","cc_enable_arenas":true},"nested":{"fieldBehavior":{"rule":"repeated","type":"google.api.FieldBehavior","id":1052,"extend":"google.protobuf.FieldOptions","options":{"packed":false}},"FieldBehavior":{"values":{"FIELD_BEHAVIOR_UNSPECIFIED":0,"OPTIONAL":1,"REQUIRED":2,"OUTPUT_ONLY":3,"INPUT_ONLY":4,"IMMUTABLE":5,"UNORDERED_LIST":6,"NON_EMPTY_DEFAULT":7,"IDENTIFIER":8}},"resourceReference":{"type":"google.api.ResourceReference","id":1055,"extend":"google.protobuf.FieldOptions"},"resourceDefinition":{"rule":"repeated","type":"google.api.ResourceDescriptor","id":1053,"extend":"google.protobuf.FileOptions"},"resource":{"type":"google.api.ResourceDescriptor","id":1053,"extend":"google.protobuf.MessageOptions"},"ResourceDescriptor":{"fields":{"type":{"type":"string","id":1},"pattern":{"rule":"repeated","type":"string","id":2},"nameField":{"type":"string","id":3},"history":{"type":"History","id":4},"plural":{"type":"string","id":5},"singular":{"type":"string","id":6},"style":{"rule":"repeated","type":"Style","id":10}},"nested":{"History":{"values":{"HISTORY_UNSPECIFIED":0,"ORIGINALLY_SINGLE_PATTERN":1,"FUTURE_MULTI_PATTERN":2}},"Style":{"values":{"STYLE_UNSPECIFIED":0,"DECLARATIVE_FRIENDLY":1}}}},"ResourceReference":{"fields":{"type":{"type":"string","id":1},"childType":{"type":"string","id":2}}},"http":{"type":"HttpRule","id":72295728,"extend":"google.protobuf.MethodOptions"},"Http":{"fields":{"rules":{"rule":"repeated","type":"HttpRule","id":1},"fullyDecodeReservedExpansion":{"type":"bool","id":2}}},"HttpRule":{"oneofs":{"pattern":{"oneof":["get","put","post","delete","patch","custom"]}},"fields":{"selector":{"type":"string","id":1},"get":{"type":"string","id":2},"put":{"type":"string","id":3},"post":{"type":"string","id":4},"delete":{"type":"string","id":5},"patch":{"type":"string","id":6},"custom":{"type":"CustomHttpPattern","id":8},"body":{"type":"string","id":7},"responseBody":{"type":"string","id":12},"additionalBindings":{"rule":"repeated","type":"HttpRule","id":11}}},"CustomHttpPattern":{"fields":{"kind":{"type":"string","id":1},"path":{"type":"string","id":2}}},"methodSignature":{"rule":"repeated","type":"string","id":1051,"extend":"google.protobuf.MethodOptions"},"defaultHost":{"type":"string","id":1049,"extend":"google.protobuf.ServiceOptions"},"oauthScopes":{"type":"string","id":1050,"extend":"google.protobuf.ServiceOptions"},"apiVersion":{"type":"string","id":525000001,"extend":"google.protobuf.ServiceOptions"},"CommonLanguageSettings":{"fields":{"referenceDocsUri":{"type":"string","id":1,"options":{"deprecated":true}},"destinations":{"rule":"repeated","type":"ClientLibraryDestination","id":2},"selectiveGapicGeneration":{"type":"SelectiveGapicGeneration","id":3}}},"ClientLibrarySettings":{"fields":{"version":{"type":"string","id":1},"launchStage":{"type":"LaunchStage","id":2},"restNumericEnums":{"type":"bool","id":3},"javaSettings":{"type":"JavaSettings","id":21},"cppSettings":{"type":"CppSettings","id":22},"phpSettings":{"type":"PhpSettings","id":23},"pythonSettings":{"type":"PythonSettings","id":24},"nodeSettings":{"type":"NodeSettings","id":25},"dotnetSettings":{"type":"DotnetSettings","id":26},"rubySettings":{"type":"RubySettings","id":27},"goSettings":{"type":"GoSettings","id":28}}},"Publishing":{"fields":{"methodSettings":{"rule":"repeated","type":"MethodSettings","id":2},"newIssueUri":{"type":"string","id":101},"documentationUri":{"type":"string","id":102},"apiShortName":{"type":"string","id":103},"githubLabel":{"type":"string","id":104},"codeownerGithubTeams":{"rule":"repeated","type":"string","id":105},"docTagPrefix":{"type":"string","id":106},"organization":{"type":"ClientLibraryOrganization","id":107},"librarySettings":{"rule":"repeated","type":"ClientLibrarySettings","id":109},"protoReferenceDocumentationUri":{"type":"string","id":110},"restReferenceDocumentationUri":{"type":"string","id":111}}},"JavaSettings":{"fields":{"libraryPackage":{"type":"string","id":1},"serviceClassNames":{"keyType":"string","type":"string","id":2},"common":{"type":"CommonLanguageSettings","id":3}}},"CppSettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1}}},"PhpSettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1}}},"PythonSettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1},"experimentalFeatures":{"type":"ExperimentalFeatures","id":2}},"nested":{"ExperimentalFeatures":{"fields":{"restAsyncIoEnabled":{"type":"bool","id":1},"protobufPythonicTypesEnabled":{"type":"bool","id":2}}}}},"NodeSettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1}}},"DotnetSettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1},"renamedServices":{"keyType":"string","type":"string","id":2},"renamedResources":{"keyType":"string","type":"string","id":3},"ignoredResources":{"rule":"repeated","type":"string","id":4},"forcedNamespaceAliases":{"rule":"repeated","type":"string","id":5},"handwrittenSignatures":{"rule":"repeated","type":"string","id":6}}},"RubySettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1}}},"GoSettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1},"renamedServices":{"keyType":"string","type":"string","id":2}}},"MethodSettings":{"fields":{"selector":{"type":"string","id":1},"longRunning":{"type":"LongRunning","id":2},"autoPopulatedFields":{"rule":"repeated","type":"string","id":3}},"nested":{"LongRunning":{"fields":{"initialPollDelay":{"type":"google.protobuf.Duration","id":1},"pollDelayMultiplier":{"type":"float","id":2},"maxPollDelay":{"type":"google.protobuf.Duration","id":3},"totalPollTimeout":{"type":"google.protobuf.Duration","id":4}}}}},"ClientLibraryOrganization":{"values":{"CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED":0,"CLOUD":1,"ADS":2,"PHOTOS":3,"STREET_VIEW":4,"SHOPPING":5,"GEO":6,"GENERATIVE_AI":7}},"ClientLibraryDestination":{"values":{"CLIENT_LIBRARY_DESTINATION_UNSPECIFIED":0,"GITHUB":10,"PACKAGE_MANAGER":20}},"SelectiveGapicGeneration":{"fields":{"methods":{"rule":"repeated","type":"string","id":1},"generateOmittedAsInternal":{"type":"bool","id":2}}},"LaunchStage":{"values":{"LAUNCH_STAGE_UNSPECIFIED":0,"UNIMPLEMENTED":6,"PRELAUNCH":7,"EARLY_ACCESS":1,"ALPHA":2,"BETA":3,"GA":4,"DEPRECATED":5}}}},"protobuf":{"options":{"go_package":"google.golang.org/protobuf/types/descriptorpb","java_package":"com.google.protobuf","java_outer_classname":"DescriptorProtos","csharp_namespace":"Google.Protobuf.Reflection","objc_class_prefix":"GPB","cc_enable_arenas":true,"optimize_for":"SPEED"},"nested":{"FileDescriptorSet":{"fields":{"file":{"rule":"repeated","type":"FileDescriptorProto","id":1}}},"Edition":{"values":{"EDITION_UNKNOWN":0,"EDITION_PROTO2":998,"EDITION_PROTO3":999,"EDITION_2023":1e3,"EDITION_2024":1001,"EDITION_1_TEST_ONLY":1,"EDITION_2_TEST_ONLY":2,"EDITION_99997_TEST_ONLY":99997,"EDITION_99998_TEST_ONLY":99998,"EDITION_99999_TEST_ONLY":99999,"EDITION_MAX":2147483647}},"FileDescriptorProto":{"fields":{"name":{"type":"string","id":1},"package":{"type":"string","id":2},"dependency":{"rule":"repeated","type":"string","id":3},"publicDependency":{"rule":"repeated","type":"int32","id":10,"options":{"packed":false}},"weakDependency":{"rule":"repeated","type":"int32","id":11,"options":{"packed":false}},"messageType":{"rule":"repeated","type":"DescriptorProto","id":4},"enumType":{"rule":"repeated","type":"EnumDescriptorProto","id":5},"service":{"rule":"repeated","type":"ServiceDescriptorProto","id":6},"extension":{"rule":"repeated","type":"FieldDescriptorProto","id":7},"options":{"type":"FileOptions","id":8},"sourceCodeInfo":{"type":"SourceCodeInfo","id":9},"syntax":{"type":"string","id":12},"edition":{"type":"Edition","id":14}}},"DescriptorProto":{"fields":{"name":{"type":"string","id":1},"field":{"rule":"repeated","type":"FieldDescriptorProto","id":2},"extension":{"rule":"repeated","type":"FieldDescriptorProto","id":6},"nestedType":{"rule":"repeated","type":"DescriptorProto","id":3},"enumType":{"rule":"repeated","type":"EnumDescriptorProto","id":4},"extensionRange":{"rule":"repeated","type":"ExtensionRange","id":5},"oneofDecl":{"rule":"repeated","type":"OneofDescriptorProto","id":8},"options":{"type":"MessageOptions","id":7},"reservedRange":{"rule":"repeated","type":"ReservedRange","id":9},"reservedName":{"rule":"repeated","type":"string","id":10}},"nested":{"ExtensionRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2},"options":{"type":"ExtensionRangeOptions","id":3}}},"ReservedRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2}}}}},"ExtensionRangeOptions":{"fields":{"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999},"declaration":{"rule":"repeated","type":"Declaration","id":2,"options":{"retention":"RETENTION_SOURCE"}},"features":{"type":"FeatureSet","id":50},"verification":{"type":"VerificationState","id":3,"options":{"default":"UNVERIFIED","retention":"RETENTION_SOURCE"}}},"extensions":[[1e3,536870911]],"nested":{"Declaration":{"fields":{"number":{"type":"int32","id":1},"fullName":{"type":"string","id":2},"type":{"type":"string","id":3},"reserved":{"type":"bool","id":5},"repeated":{"type":"bool","id":6}},"reserved":[[4,4]]},"VerificationState":{"values":{"DECLARATION":0,"UNVERIFIED":1}}}},"FieldDescriptorProto":{"fields":{"name":{"type":"string","id":1},"number":{"type":"int32","id":3},"label":{"type":"Label","id":4},"type":{"type":"Type","id":5},"typeName":{"type":"string","id":6},"extendee":{"type":"string","id":2},"defaultValue":{"type":"string","id":7},"oneofIndex":{"type":"int32","id":9},"jsonName":{"type":"string","id":10},"options":{"type":"FieldOptions","id":8},"proto3Optional":{"type":"bool","id":17}},"nested":{"Type":{"values":{"TYPE_DOUBLE":1,"TYPE_FLOAT":2,"TYPE_INT64":3,"TYPE_UINT64":4,"TYPE_INT32":5,"TYPE_FIXED64":6,"TYPE_FIXED32":7,"TYPE_BOOL":8,"TYPE_STRING":9,"TYPE_GROUP":10,"TYPE_MESSAGE":11,"TYPE_BYTES":12,"TYPE_UINT32":13,"TYPE_ENUM":14,"TYPE_SFIXED32":15,"TYPE_SFIXED64":16,"TYPE_SINT32":17,"TYPE_SINT64":18}},"Label":{"values":{"LABEL_OPTIONAL":1,"LABEL_REPEATED":3,"LABEL_REQUIRED":2}}}},"OneofDescriptorProto":{"fields":{"name":{"type":"string","id":1},"options":{"type":"OneofOptions","id":2}}},"EnumDescriptorProto":{"fields":{"name":{"type":"string","id":1},"value":{"rule":"repeated","type":"EnumValueDescriptorProto","id":2},"options":{"type":"EnumOptions","id":3},"reservedRange":{"rule":"repeated","type":"EnumReservedRange","id":4},"reservedName":{"rule":"repeated","type":"string","id":5}},"nested":{"EnumReservedRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2}}}}},"EnumValueDescriptorProto":{"fields":{"name":{"type":"string","id":1},"number":{"type":"int32","id":2},"options":{"type":"EnumValueOptions","id":3}}},"ServiceDescriptorProto":{"fields":{"name":{"type":"string","id":1},"method":{"rule":"repeated","type":"MethodDescriptorProto","id":2},"options":{"type":"ServiceOptions","id":3}}},"MethodDescriptorProto":{"fields":{"name":{"type":"string","id":1},"inputType":{"type":"string","id":2},"outputType":{"type":"string","id":3},"options":{"type":"MethodOptions","id":4},"clientStreaming":{"type":"bool","id":5,"options":{"default":false}},"serverStreaming":{"type":"bool","id":6,"options":{"default":false}}}},"FileOptions":{"fields":{"javaPackage":{"type":"string","id":1},"javaOuterClassname":{"type":"string","id":8},"javaMultipleFiles":{"type":"bool","id":10,"options":{"default":false}},"javaGenerateEqualsAndHash":{"type":"bool","id":20,"options":{"deprecated":true}},"javaStringCheckUtf8":{"type":"bool","id":27,"options":{"default":false}},"optimizeFor":{"type":"OptimizeMode","id":9,"options":{"default":"SPEED"}},"goPackage":{"type":"string","id":11},"ccGenericServices":{"type":"bool","id":16,"options":{"default":false}},"javaGenericServices":{"type":"bool","id":17,"options":{"default":false}},"pyGenericServices":{"type":"bool","id":18,"options":{"default":false}},"deprecated":{"type":"bool","id":23,"options":{"default":false}},"ccEnableArenas":{"type":"bool","id":31,"options":{"default":true}},"objcClassPrefix":{"type":"string","id":36},"csharpNamespace":{"type":"string","id":37},"swiftPrefix":{"type":"string","id":39},"phpClassPrefix":{"type":"string","id":40},"phpNamespace":{"type":"string","id":41},"phpMetadataNamespace":{"type":"string","id":44},"rubyPackage":{"type":"string","id":45},"features":{"type":"FeatureSet","id":50},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"reserved":[[42,42],[38,38]],"nested":{"OptimizeMode":{"values":{"SPEED":1,"CODE_SIZE":2,"LITE_RUNTIME":3}}}},"MessageOptions":{"fields":{"messageSetWireFormat":{"type":"bool","id":1,"options":{"default":false}},"noStandardDescriptorAccessor":{"type":"bool","id":2,"options":{"default":false}},"deprecated":{"type":"bool","id":3,"options":{"default":false}},"mapEntry":{"type":"bool","id":7},"deprecatedLegacyJsonFieldConflicts":{"type":"bool","id":11,"options":{"deprecated":true}},"features":{"type":"FeatureSet","id":12},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"reserved":[[4,4],[5,5],[6,6],[8,8],[9,9]]},"FieldOptions":{"fields":{"ctype":{"type":"CType","id":1,"options":{"default":"STRING"}},"packed":{"type":"bool","id":2},"jstype":{"type":"JSType","id":6,"options":{"default":"JS_NORMAL"}},"lazy":{"type":"bool","id":5,"options":{"default":false}},"unverifiedLazy":{"type":"bool","id":15,"options":{"default":false}},"deprecated":{"type":"bool","id":3,"options":{"default":false}},"weak":{"type":"bool","id":10,"options":{"default":false}},"debugRedact":{"type":"bool","id":16,"options":{"default":false}},"retention":{"type":"OptionRetention","id":17},"targets":{"rule":"repeated","type":"OptionTargetType","id":19,"options":{"packed":false}},"editionDefaults":{"rule":"repeated","type":"EditionDefault","id":20},"features":{"type":"FeatureSet","id":21},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"reserved":[[4,4],[18,18]],"nested":{"CType":{"values":{"STRING":0,"CORD":1,"STRING_PIECE":2}},"JSType":{"values":{"JS_NORMAL":0,"JS_STRING":1,"JS_NUMBER":2}},"OptionRetention":{"values":{"RETENTION_UNKNOWN":0,"RETENTION_RUNTIME":1,"RETENTION_SOURCE":2}},"OptionTargetType":{"values":{"TARGET_TYPE_UNKNOWN":0,"TARGET_TYPE_FILE":1,"TARGET_TYPE_EXTENSION_RANGE":2,"TARGET_TYPE_MESSAGE":3,"TARGET_TYPE_FIELD":4,"TARGET_TYPE_ONEOF":5,"TARGET_TYPE_ENUM":6,"TARGET_TYPE_ENUM_ENTRY":7,"TARGET_TYPE_SERVICE":8,"TARGET_TYPE_METHOD":9}},"EditionDefault":{"fields":{"edition":{"type":"Edition","id":3},"value":{"type":"string","id":2}}}}},"OneofOptions":{"fields":{"features":{"type":"FeatureSet","id":1},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]]},"EnumOptions":{"fields":{"allowAlias":{"type":"bool","id":2},"deprecated":{"type":"bool","id":3,"options":{"default":false}},"deprecatedLegacyJsonFieldConflicts":{"type":"bool","id":6,"options":{"deprecated":true}},"features":{"type":"FeatureSet","id":7},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"reserved":[[5,5]]},"EnumValueOptions":{"fields":{"deprecated":{"type":"bool","id":1,"options":{"default":false}},"features":{"type":"FeatureSet","id":2},"debugRedact":{"type":"bool","id":3,"options":{"default":false}},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]]},"ServiceOptions":{"fields":{"features":{"type":"FeatureSet","id":34},"deprecated":{"type":"bool","id":33,"options":{"default":false}},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]]},"MethodOptions":{"fields":{"deprecated":{"type":"bool","id":33,"options":{"default":false}},"idempotencyLevel":{"type":"IdempotencyLevel","id":34,"options":{"default":"IDEMPOTENCY_UNKNOWN"}},"features":{"type":"FeatureSet","id":35},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"nested":{"IdempotencyLevel":{"values":{"IDEMPOTENCY_UNKNOWN":0,"NO_SIDE_EFFECTS":1,"IDEMPOTENT":2}}}},"UninterpretedOption":{"fields":{"name":{"rule":"repeated","type":"NamePart","id":2},"identifierValue":{"type":"string","id":3},"positiveIntValue":{"type":"uint64","id":4},"negativeIntValue":{"type":"int64","id":5},"doubleValue":{"type":"double","id":6},"stringValue":{"type":"bytes","id":7},"aggregateValue":{"type":"string","id":8}},"nested":{"NamePart":{"fields":{"namePart":{"rule":"required","type":"string","id":1},"isExtension":{"rule":"required","type":"bool","id":2}}}}},"FeatureSet":{"fields":{"fieldPresence":{"type":"FieldPresence","id":1,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","edition_defaults.edition":"EDITION_2023","edition_defaults.value":"EXPLICIT"}},"enumType":{"type":"EnumType","id":2,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"OPEN"}},"repeatedFieldEncoding":{"type":"RepeatedFieldEncoding","id":3,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"PACKED"}},"utf8Validation":{"type":"Utf8Validation","id":4,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"VERIFY"}},"messageEncoding":{"type":"MessageEncoding","id":5,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","edition_defaults.edition":"EDITION_PROTO2","edition_defaults.value":"LENGTH_PREFIXED"}},"jsonFormat":{"type":"JsonFormat","id":6,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"ALLOW"}}},"extensions":[[1e3,1e3],[1001,1001],[1002,1002],[9995,9999],[1e4,1e4]],"reserved":[[999,999]],"nested":{"FieldPresence":{"values":{"FIELD_PRESENCE_UNKNOWN":0,"EXPLICIT":1,"IMPLICIT":2,"LEGACY_REQUIRED":3}},"EnumType":{"values":{"ENUM_TYPE_UNKNOWN":0,"OPEN":1,"CLOSED":2}},"RepeatedFieldEncoding":{"values":{"REPEATED_FIELD_ENCODING_UNKNOWN":0,"PACKED":1,"EXPANDED":2}},"Utf8Validation":{"values":{"UTF8_VALIDATION_UNKNOWN":0,"VERIFY":2,"NONE":3}},"MessageEncoding":{"values":{"MESSAGE_ENCODING_UNKNOWN":0,"LENGTH_PREFIXED":1,"DELIMITED":2}},"JsonFormat":{"values":{"JSON_FORMAT_UNKNOWN":0,"ALLOW":1,"LEGACY_BEST_EFFORT":2}}}},"FeatureSetDefaults":{"fields":{"defaults":{"rule":"repeated","type":"FeatureSetEditionDefault","id":1},"minimumEdition":{"type":"Edition","id":4},"maximumEdition":{"type":"Edition","id":5}},"nested":{"FeatureSetEditionDefault":{"fields":{"edition":{"type":"Edition","id":3},"features":{"type":"FeatureSet","id":2}}}}},"SourceCodeInfo":{"fields":{"location":{"rule":"repeated","type":"Location","id":1}},"nested":{"Location":{"fields":{"path":{"rule":"repeated","type":"int32","id":1},"span":{"rule":"repeated","type":"int32","id":2},"leadingComments":{"type":"string","id":3},"trailingComments":{"type":"string","id":4},"leadingDetachedComments":{"rule":"repeated","type":"string","id":6}}}}},"GeneratedCodeInfo":{"fields":{"annotation":{"rule":"repeated","type":"Annotation","id":1}},"nested":{"Annotation":{"fields":{"path":{"rule":"repeated","type":"int32","id":1},"sourceFile":{"type":"string","id":2},"begin":{"type":"int32","id":3},"end":{"type":"int32","id":4},"semantic":{"type":"Semantic","id":5}},"nested":{"Semantic":{"values":{"NONE":0,"SET":1,"ALIAS":2}}}}}},"Timestamp":{"fields":{"seconds":{"type":"int64","id":1},"nanos":{"type":"int32","id":2}}},"Duration":{"fields":{"seconds":{"type":"int64","id":1},"nanos":{"type":"int32","id":2}}},"Any":{"fields":{"type_url":{"type":"string","id":1},"value":{"type":"bytes","id":2}}},"Empty":{"fields":{}},"FieldMask":{"fields":{"paths":{"rule":"repeated","type":"string","id":1}}},"Struct":{"fields":{"fields":{"keyType":"string","type":"Value","id":1}}},"Value":{"oneofs":{"kind":{"oneof":["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},"fields":{"nullValue":{"type":"NullValue","id":1},"numberValue":{"type":"double","id":2},"stringValue":{"type":"string","id":3},"boolValue":{"type":"bool","id":4},"structValue":{"type":"Struct","id":5},"listValue":{"type":"ListValue","id":6}}},"NullValue":{"values":{"NULL_VALUE":0}},"ListValue":{"fields":{"values":{"rule":"repeated","type":"Value","id":1}}},"DoubleValue":{"fields":{"value":{"type":"double","id":1}}},"FloatValue":{"fields":{"value":{"type":"float","id":1}}},"Int64Value":{"fields":{"value":{"type":"int64","id":1}}},"UInt64Value":{"fields":{"value":{"type":"uint64","id":1}}},"Int32Value":{"fields":{"value":{"type":"int32","id":1}}},"UInt32Value":{"fields":{"value":{"type":"uint32","id":1}}},"BoolValue":{"fields":{"value":{"type":"bool","id":1}}},"StringValue":{"fields":{"value":{"type":"string","id":1}}},"BytesValue":{"fields":{"value":{"type":"bytes","id":1}}}}},"type":{"options":{"go_package":"google.golang.org/genproto/googleapis/type/latlng;latlng","java_multiple_files":true,"java_outer_classname":"LatLngProto","java_package":"com.google.type","objc_class_prefix":"GTP","cc_enable_arenas":true},"nested":{"DayOfWeek":{"values":{"DAY_OF_WEEK_UNSPECIFIED":0,"MONDAY":1,"TUESDAY":2,"WEDNESDAY":3,"THURSDAY":4,"FRIDAY":5,"SATURDAY":6,"SUNDAY":7}},"LatLng":{"fields":{"latitude":{"type":"double","id":1},"longitude":{"type":"double","id":2}}}}},"longrunning":{"options":{"cc_enable_arenas":true,"csharp_namespace":"Google.LongRunning","go_package":"cloud.google.com/go/longrunning/autogen/longrunningpb;longrunningpb","java_multiple_files":true,"java_outer_classname":"OperationsProto","java_package":"com.google.longrunning","objc_class_prefix":"GLRUN","php_namespace":"Google\\LongRunning"},"nested":{"operationInfo":{"type":"google.longrunning.OperationInfo","id":1049,"extend":"google.protobuf.MethodOptions"},"Operations":{"options":{"(google.api.default_host)":"longrunning.googleapis.com"},"methods":{"ListOperations":{"requestType":"ListOperationsRequest","responseType":"ListOperationsResponse","options":{"(google.api.http).get":"/v1/{name=operations}","(google.api.method_signature)":"name,filter"},"parsedOptions":[{"(google.api.http)":{"get":"/v1/{name=operations}"}},{"(google.api.method_signature)":"name,filter"}]},"GetOperation":{"requestType":"GetOperationRequest","responseType":"Operation","options":{"(google.api.http).get":"/v1/{name=operations/**}","(google.api.method_signature)":"name"},"parsedOptions":[{"(google.api.http)":{"get":"/v1/{name=operations/**}"}},{"(google.api.method_signature)":"name"}]},"DeleteOperation":{"requestType":"DeleteOperationRequest","responseType":"google.protobuf.Empty","options":{"(google.api.http).delete":"/v1/{name=operations/**}","(google.api.method_signature)":"name"},"parsedOptions":[{"(google.api.http)":{"delete":"/v1/{name=operations/**}"}},{"(google.api.method_signature)":"name"}]},"CancelOperation":{"requestType":"CancelOperationRequest","responseType":"google.protobuf.Empty","options":{"(google.api.http).post":"/v1/{name=operations/**}:cancel","(google.api.http).body":"*","(google.api.method_signature)":"name"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{name=operations/**}:cancel","body":"*"}},{"(google.api.method_signature)":"name"}]},"WaitOperation":{"requestType":"WaitOperationRequest","responseType":"Operation"}}},"Operation":{"oneofs":{"result":{"oneof":["error","response"]}},"fields":{"name":{"type":"string","id":1},"metadata":{"type":"google.protobuf.Any","id":2},"done":{"type":"bool","id":3},"error":{"type":"google.rpc.Status","id":4},"response":{"type":"google.protobuf.Any","id":5}}},"GetOperationRequest":{"fields":{"name":{"type":"string","id":1}}},"ListOperationsRequest":{"fields":{"name":{"type":"string","id":4},"filter":{"type":"string","id":1},"pageSize":{"type":"int32","id":2},"pageToken":{"type":"string","id":3}}},"ListOperationsResponse":{"fields":{"operations":{"rule":"repeated","type":"Operation","id":1},"nextPageToken":{"type":"string","id":2}}},"CancelOperationRequest":{"fields":{"name":{"type":"string","id":1}}},"DeleteOperationRequest":{"fields":{"name":{"type":"string","id":1}}},"WaitOperationRequest":{"fields":{"name":{"type":"string","id":1},"timeout":{"type":"google.protobuf.Duration","id":2}}},"OperationInfo":{"fields":{"responseType":{"type":"string","id":1},"metadataType":{"type":"string","id":2}}}}},"rpc":{"options":{"cc_enable_arenas":true,"go_package":"google.golang.org/genproto/googleapis/rpc/status;status","java_multiple_files":true,"java_outer_classname":"StatusProto","java_package":"com.google.rpc","objc_class_prefix":"RPC"},"nested":{"Status":{"fields":{"code":{"type":"int32","id":1},"message":{"type":"string","id":2},"details":{"rule":"repeated","type":"google.protobuf.Any","id":3}}}}}}}}} \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/protos/firestore/bundle.proto b/node_modules/@google-cloud/firestore/build/protos/firestore/bundle.proto new file mode 100644 index 0000000..22bbd8a --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/firestore/bundle.proto @@ -0,0 +1,120 @@ +// Copyright 2020 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +// This file defines the format of Firestore bundle file/stream. It is not a part of the +// Firestore API, only a specification used by Server and Client SDK to write and read +// bundles. + +syntax = "proto3"; + +package firestore; + +import "google/firestore/v1/document.proto"; +import "google/firestore/v1/query.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Firestore.Proto"; +option go_package = "google.golang.org/genproto/firestore/proto;firestore"; +option java_multiple_files = true; +option java_outer_classname = "BundleProto"; +option java_package = "com.google.firestore.proto"; +option objc_class_prefix = "FSTPB"; +option php_namespace = "Firestore\\Proto"; + +// Encodes a query saved in the bundle. +message BundledQuery { + // The parent resource name. + string parent = 1; + + // The query to run. + oneof query_type { + // A structured query. + google.firestore.v1.StructuredQuery structured_query = 2; + } + + // If the query is a limit query, should the limit be applied to the beginning or + // the end of results. + enum LimitType { + FIRST = 0; + LAST = 1; + } + LimitType limit_type = 3; +} + +// A Query associated with a name, created as part of the bundle file, and can be read +// by client SDKs once the bundle containing them is loaded. +message NamedQuery { + // Name of the query, such that client can use the name to load this query + // from bundle, and resume from when the query results are materialized + // into this bundle. + string name = 1; + + // The query saved in the bundle. + BundledQuery bundled_query = 2; + + // The read time of the query, when it is used to build the bundle. This is useful to + // resume the query from the bundle, once it is loaded by client SDKs. + google.protobuf.Timestamp read_time = 3; +} + +// Metadata describing a Firestore document saved in the bundle. +message BundledDocumentMetadata { + // The document key of a bundled document. + string name = 1; + + // The snapshot version of the document data bundled. + google.protobuf.Timestamp read_time = 2; + + // Whether the document exists. + bool exists = 3; + + // The names of the queries in this bundle that this document matches to. + repeated string queries = 4; +} + +// Metadata describing the bundle file/stream. +message BundleMetadata { + // The ID of the bundle. + string id = 1; + + // Time at which the documents snapshot is taken for this bundle. + google.protobuf.Timestamp create_time = 2; + + // The schema version of the bundle. + uint32 version = 3; + + // The number of documents in the bundle. + uint32 total_documents = 4; + + // The size of the bundle in bytes, excluding this `BundleMetadata`. + uint64 total_bytes = 5; +} + +// A Firestore bundle is a length-prefixed stream of JSON representations of +// `BundleElement`. +// Only one `BundleMetadata` is expected, and it should be the first element. +// The named queries follow after `metadata`. Every `document_metadata` is +// immediately followed by a `document`. +message BundleElement { + oneof element_type { + BundleMetadata metadata = 1; + + NamedQuery named_query = 2; + + BundledDocumentMetadata document_metadata = 3; + + google.firestore.v1.Document document = 4; + } +} diff --git a/node_modules/@google-cloud/firestore/build/protos/firestore_admin_v1_proto_api.d.ts b/node_modules/@google-cloud/firestore/build/protos/firestore_admin_v1_proto_api.d.ts new file mode 100644 index 0000000..4240ac5 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/firestore_admin_v1_proto_api.d.ts @@ -0,0 +1,9761 @@ +/*! + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as $protobuf from "protobufjs"; +/** Namespace google. */ +export namespace google { + + /** Namespace firestore. */ + namespace firestore { + + /** Namespace admin. */ + namespace admin { + + /** Namespace v1. */ + namespace v1 { + + /** Properties of a Backup. */ + interface IBackup { + + /** Backup name */ + name?: (string|null); + + /** Backup database */ + database?: (string|null); + + /** Backup databaseUid */ + databaseUid?: (string|null); + + /** Backup snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + + /** Backup expireTime */ + expireTime?: (google.protobuf.ITimestamp|null); + + /** Backup stats */ + stats?: (google.firestore.admin.v1.Backup.IStats|null); + + /** Backup state */ + state?: (google.firestore.admin.v1.Backup.State|null); + } + + /** Represents a Backup. */ + class Backup implements IBackup { + + /** + * Constructs a new Backup. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBackup); + + /** Backup name. */ + public name: string; + + /** Backup database. */ + public database: string; + + /** Backup databaseUid. */ + public databaseUid: string; + + /** Backup snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** Backup expireTime. */ + public expireTime?: (google.protobuf.ITimestamp|null); + + /** Backup stats. */ + public stats?: (google.firestore.admin.v1.Backup.IStats|null); + + /** Backup state. */ + public state: google.firestore.admin.v1.Backup.State; + + /** + * Creates a Backup message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Backup + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Backup; + + /** + * Creates a plain object from a Backup message. Also converts values to other types if specified. + * @param message Backup + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Backup, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Backup to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Backup + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Backup { + + /** Properties of a Stats. */ + interface IStats { + + /** Stats sizeBytes */ + sizeBytes?: (number|string|null); + + /** Stats documentCount */ + documentCount?: (number|string|null); + + /** Stats indexCount */ + indexCount?: (number|string|null); + } + + /** Represents a Stats. */ + class Stats implements IStats { + + /** + * Constructs a new Stats. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Backup.IStats); + + /** Stats sizeBytes. */ + public sizeBytes: (number|string); + + /** Stats documentCount. */ + public documentCount: (number|string); + + /** Stats indexCount. */ + public indexCount: (number|string); + + /** + * Creates a Stats message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Stats + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Backup.Stats; + + /** + * Creates a plain object from a Stats message. Also converts values to other types if specified. + * @param message Stats + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Backup.Stats, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Stats to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Stats + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** State enum. */ + type State = + "STATE_UNSPECIFIED"| "CREATING"| "READY"| "NOT_AVAILABLE"; + } + + /** Properties of a Database. */ + interface IDatabase { + + /** Database name */ + name?: (string|null); + + /** Database uid */ + uid?: (string|null); + + /** Database createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** Database updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** Database deleteTime */ + deleteTime?: (google.protobuf.ITimestamp|null); + + /** Database locationId */ + locationId?: (string|null); + + /** Database type */ + type?: (google.firestore.admin.v1.Database.DatabaseType|null); + + /** Database concurrencyMode */ + concurrencyMode?: (google.firestore.admin.v1.Database.ConcurrencyMode|null); + + /** Database versionRetentionPeriod */ + versionRetentionPeriod?: (google.protobuf.IDuration|null); + + /** Database earliestVersionTime */ + earliestVersionTime?: (google.protobuf.ITimestamp|null); + + /** Database pointInTimeRecoveryEnablement */ + pointInTimeRecoveryEnablement?: (google.firestore.admin.v1.Database.PointInTimeRecoveryEnablement|null); + + /** Database appEngineIntegrationMode */ + appEngineIntegrationMode?: (google.firestore.admin.v1.Database.AppEngineIntegrationMode|null); + + /** Database keyPrefix */ + keyPrefix?: (string|null); + + /** Database deleteProtectionState */ + deleteProtectionState?: (google.firestore.admin.v1.Database.DeleteProtectionState|null); + + /** Database cmekConfig */ + cmekConfig?: (google.firestore.admin.v1.Database.ICmekConfig|null); + + /** Database previousId */ + previousId?: (string|null); + + /** Database sourceInfo */ + sourceInfo?: (google.firestore.admin.v1.Database.ISourceInfo|null); + + /** Database etag */ + etag?: (string|null); + } + + /** Represents a Database. */ + class Database implements IDatabase { + + /** + * Constructs a new Database. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDatabase); + + /** Database name. */ + public name: string; + + /** Database uid. */ + public uid: string; + + /** Database createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** Database updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** Database deleteTime. */ + public deleteTime?: (google.protobuf.ITimestamp|null); + + /** Database locationId. */ + public locationId: string; + + /** Database type. */ + public type: google.firestore.admin.v1.Database.DatabaseType; + + /** Database concurrencyMode. */ + public concurrencyMode: google.firestore.admin.v1.Database.ConcurrencyMode; + + /** Database versionRetentionPeriod. */ + public versionRetentionPeriod?: (google.protobuf.IDuration|null); + + /** Database earliestVersionTime. */ + public earliestVersionTime?: (google.protobuf.ITimestamp|null); + + /** Database pointInTimeRecoveryEnablement. */ + public pointInTimeRecoveryEnablement: google.firestore.admin.v1.Database.PointInTimeRecoveryEnablement; + + /** Database appEngineIntegrationMode. */ + public appEngineIntegrationMode: google.firestore.admin.v1.Database.AppEngineIntegrationMode; + + /** Database keyPrefix. */ + public keyPrefix: string; + + /** Database deleteProtectionState. */ + public deleteProtectionState: google.firestore.admin.v1.Database.DeleteProtectionState; + + /** Database cmekConfig. */ + public cmekConfig?: (google.firestore.admin.v1.Database.ICmekConfig|null); + + /** Database previousId. */ + public previousId: string; + + /** Database sourceInfo. */ + public sourceInfo?: (google.firestore.admin.v1.Database.ISourceInfo|null); + + /** Database etag. */ + public etag: string; + + /** + * Creates a Database message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Database + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database; + + /** + * Creates a plain object from a Database message. Also converts values to other types if specified. + * @param message Database + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Database to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Database + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Database { + + /** DatabaseType enum. */ + type DatabaseType = + "DATABASE_TYPE_UNSPECIFIED"| "FIRESTORE_NATIVE"| "DATASTORE_MODE"; + + /** ConcurrencyMode enum. */ + type ConcurrencyMode = + "CONCURRENCY_MODE_UNSPECIFIED"| "OPTIMISTIC"| "PESSIMISTIC"| "OPTIMISTIC_WITH_ENTITY_GROUPS"; + + /** PointInTimeRecoveryEnablement enum. */ + type PointInTimeRecoveryEnablement = + "POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED"| "POINT_IN_TIME_RECOVERY_ENABLED"| "POINT_IN_TIME_RECOVERY_DISABLED"; + + /** AppEngineIntegrationMode enum. */ + type AppEngineIntegrationMode = + "APP_ENGINE_INTEGRATION_MODE_UNSPECIFIED"| "ENABLED"| "DISABLED"; + + /** DeleteProtectionState enum. */ + type DeleteProtectionState = + "DELETE_PROTECTION_STATE_UNSPECIFIED"| "DELETE_PROTECTION_DISABLED"| "DELETE_PROTECTION_ENABLED"; + + /** Properties of a CmekConfig. */ + interface ICmekConfig { + + /** CmekConfig kmsKeyName */ + kmsKeyName?: (string|null); + + /** CmekConfig activeKeyVersion */ + activeKeyVersion?: (string[]|null); + } + + /** Represents a CmekConfig. */ + class CmekConfig implements ICmekConfig { + + /** + * Constructs a new CmekConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.ICmekConfig); + + /** CmekConfig kmsKeyName. */ + public kmsKeyName: string; + + /** CmekConfig activeKeyVersion. */ + public activeKeyVersion: string[]; + + /** + * Creates a CmekConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CmekConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.CmekConfig; + + /** + * Creates a plain object from a CmekConfig message. Also converts values to other types if specified. + * @param message CmekConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.CmekConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CmekConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CmekConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a SourceInfo. */ + interface ISourceInfo { + + /** SourceInfo backup */ + backup?: (google.firestore.admin.v1.Database.SourceInfo.IBackupSource|null); + + /** SourceInfo operation */ + operation?: (string|null); + } + + /** Represents a SourceInfo. */ + class SourceInfo implements ISourceInfo { + + /** + * Constructs a new SourceInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.ISourceInfo); + + /** SourceInfo backup. */ + public backup?: (google.firestore.admin.v1.Database.SourceInfo.IBackupSource|null); + + /** SourceInfo operation. */ + public operation: string; + + /** SourceInfo source. */ + public source?: "backup"; + + /** + * Creates a SourceInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceInfo + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.SourceInfo; + + /** + * Creates a plain object from a SourceInfo message. Also converts values to other types if specified. + * @param message SourceInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.SourceInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace SourceInfo { + + /** Properties of a BackupSource. */ + interface IBackupSource { + + /** BackupSource backup */ + backup?: (string|null); + } + + /** Represents a BackupSource. */ + class BackupSource implements IBackupSource { + + /** + * Constructs a new BackupSource. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.SourceInfo.IBackupSource); + + /** BackupSource backup. */ + public backup: string; + + /** + * Creates a BackupSource message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BackupSource + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.SourceInfo.BackupSource; + + /** + * Creates a plain object from a BackupSource message. Also converts values to other types if specified. + * @param message BackupSource + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.SourceInfo.BackupSource, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BackupSource to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BackupSource + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an EncryptionConfig. */ + interface IEncryptionConfig { + + /** EncryptionConfig googleDefaultEncryption */ + googleDefaultEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.IGoogleDefaultEncryptionOptions|null); + + /** EncryptionConfig useSourceEncryption */ + useSourceEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.ISourceEncryptionOptions|null); + + /** EncryptionConfig customerManagedEncryption */ + customerManagedEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.ICustomerManagedEncryptionOptions|null); + } + + /** Represents an EncryptionConfig. */ + class EncryptionConfig implements IEncryptionConfig { + + /** + * Constructs a new EncryptionConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.IEncryptionConfig); + + /** EncryptionConfig googleDefaultEncryption. */ + public googleDefaultEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.IGoogleDefaultEncryptionOptions|null); + + /** EncryptionConfig useSourceEncryption. */ + public useSourceEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.ISourceEncryptionOptions|null); + + /** EncryptionConfig customerManagedEncryption. */ + public customerManagedEncryption?: (google.firestore.admin.v1.Database.EncryptionConfig.ICustomerManagedEncryptionOptions|null); + + /** EncryptionConfig encryptionType. */ + public encryptionType?: ("googleDefaultEncryption"|"useSourceEncryption"|"customerManagedEncryption"); + + /** + * Creates an EncryptionConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EncryptionConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.EncryptionConfig; + + /** + * Creates a plain object from an EncryptionConfig message. Also converts values to other types if specified. + * @param message EncryptionConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.EncryptionConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EncryptionConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EncryptionConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace EncryptionConfig { + + /** Properties of a GoogleDefaultEncryptionOptions. */ + interface IGoogleDefaultEncryptionOptions { + } + + /** Represents a GoogleDefaultEncryptionOptions. */ + class GoogleDefaultEncryptionOptions implements IGoogleDefaultEncryptionOptions { + + /** + * Constructs a new GoogleDefaultEncryptionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.EncryptionConfig.IGoogleDefaultEncryptionOptions); + + /** + * Creates a GoogleDefaultEncryptionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GoogleDefaultEncryptionOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.EncryptionConfig.GoogleDefaultEncryptionOptions; + + /** + * Creates a plain object from a GoogleDefaultEncryptionOptions message. Also converts values to other types if specified. + * @param message GoogleDefaultEncryptionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.EncryptionConfig.GoogleDefaultEncryptionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GoogleDefaultEncryptionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GoogleDefaultEncryptionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a SourceEncryptionOptions. */ + interface ISourceEncryptionOptions { + } + + /** Represents a SourceEncryptionOptions. */ + class SourceEncryptionOptions implements ISourceEncryptionOptions { + + /** + * Constructs a new SourceEncryptionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.EncryptionConfig.ISourceEncryptionOptions); + + /** + * Creates a SourceEncryptionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceEncryptionOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.EncryptionConfig.SourceEncryptionOptions; + + /** + * Creates a plain object from a SourceEncryptionOptions message. Also converts values to other types if specified. + * @param message SourceEncryptionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.EncryptionConfig.SourceEncryptionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceEncryptionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceEncryptionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CustomerManagedEncryptionOptions. */ + interface ICustomerManagedEncryptionOptions { + + /** CustomerManagedEncryptionOptions kmsKeyName */ + kmsKeyName?: (string|null); + } + + /** Represents a CustomerManagedEncryptionOptions. */ + class CustomerManagedEncryptionOptions implements ICustomerManagedEncryptionOptions { + + /** + * Constructs a new CustomerManagedEncryptionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Database.EncryptionConfig.ICustomerManagedEncryptionOptions); + + /** CustomerManagedEncryptionOptions kmsKeyName. */ + public kmsKeyName: string; + + /** + * Creates a CustomerManagedEncryptionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomerManagedEncryptionOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Database.EncryptionConfig.CustomerManagedEncryptionOptions; + + /** + * Creates a plain object from a CustomerManagedEncryptionOptions message. Also converts values to other types if specified. + * @param message CustomerManagedEncryptionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Database.EncryptionConfig.CustomerManagedEncryptionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomerManagedEncryptionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CustomerManagedEncryptionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + + /** Properties of a Field. */ + interface IField { + + /** Field name */ + name?: (string|null); + + /** Field indexConfig */ + indexConfig?: (google.firestore.admin.v1.Field.IIndexConfig|null); + + /** Field ttlConfig */ + ttlConfig?: (google.firestore.admin.v1.Field.ITtlConfig|null); + } + + /** Represents a Field. */ + class Field implements IField { + + /** + * Constructs a new Field. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IField); + + /** Field name. */ + public name: string; + + /** Field indexConfig. */ + public indexConfig?: (google.firestore.admin.v1.Field.IIndexConfig|null); + + /** Field ttlConfig. */ + public ttlConfig?: (google.firestore.admin.v1.Field.ITtlConfig|null); + + /** + * Creates a Field message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Field + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Field; + + /** + * Creates a plain object from a Field message. Also converts values to other types if specified. + * @param message Field + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Field, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Field to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Field + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Field { + + /** Properties of an IndexConfig. */ + interface IIndexConfig { + + /** IndexConfig indexes */ + indexes?: (google.firestore.admin.v1.IIndex[]|null); + + /** IndexConfig usesAncestorConfig */ + usesAncestorConfig?: (boolean|null); + + /** IndexConfig ancestorField */ + ancestorField?: (string|null); + + /** IndexConfig reverting */ + reverting?: (boolean|null); + } + + /** Represents an IndexConfig. */ + class IndexConfig implements IIndexConfig { + + /** + * Constructs a new IndexConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Field.IIndexConfig); + + /** IndexConfig indexes. */ + public indexes: google.firestore.admin.v1.IIndex[]; + + /** IndexConfig usesAncestorConfig. */ + public usesAncestorConfig: boolean; + + /** IndexConfig ancestorField. */ + public ancestorField: string; + + /** IndexConfig reverting. */ + public reverting: boolean; + + /** + * Creates an IndexConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IndexConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Field.IndexConfig; + + /** + * Creates a plain object from an IndexConfig message. Also converts values to other types if specified. + * @param message IndexConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Field.IndexConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IndexConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IndexConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a TtlConfig. */ + interface ITtlConfig { + + /** TtlConfig state */ + state?: (google.firestore.admin.v1.Field.TtlConfig.State|null); + } + + /** Represents a TtlConfig. */ + class TtlConfig implements ITtlConfig { + + /** + * Constructs a new TtlConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Field.ITtlConfig); + + /** TtlConfig state. */ + public state: google.firestore.admin.v1.Field.TtlConfig.State; + + /** + * Creates a TtlConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TtlConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Field.TtlConfig; + + /** + * Creates a plain object from a TtlConfig message. Also converts values to other types if specified. + * @param message TtlConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Field.TtlConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TtlConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TtlConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TtlConfig { + + /** State enum. */ + type State = + "STATE_UNSPECIFIED"| "CREATING"| "ACTIVE"| "NEEDS_REPAIR"; + } + } + + /** Properties of an Index. */ + interface IIndex { + + /** Index name */ + name?: (string|null); + + /** Index queryScope */ + queryScope?: (google.firestore.admin.v1.Index.QueryScope|null); + + /** Index apiScope */ + apiScope?: (google.firestore.admin.v1.Index.ApiScope|null); + + /** Index fields */ + fields?: (google.firestore.admin.v1.Index.IIndexField[]|null); + + /** Index state */ + state?: (google.firestore.admin.v1.Index.State|null); + } + + /** Represents an Index. */ + class Index implements IIndex { + + /** + * Constructs a new Index. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IIndex); + + /** Index name. */ + public name: string; + + /** Index queryScope. */ + public queryScope: google.firestore.admin.v1.Index.QueryScope; + + /** Index apiScope. */ + public apiScope: google.firestore.admin.v1.Index.ApiScope; + + /** Index fields. */ + public fields: google.firestore.admin.v1.Index.IIndexField[]; + + /** Index state. */ + public state: google.firestore.admin.v1.Index.State; + + /** + * Creates an Index message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Index + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index; + + /** + * Creates a plain object from an Index message. Also converts values to other types if specified. + * @param message Index + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Index, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Index to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Index + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Index { + + /** QueryScope enum. */ + type QueryScope = + "QUERY_SCOPE_UNSPECIFIED"| "COLLECTION"| "COLLECTION_GROUP"| "COLLECTION_RECURSIVE"; + + /** ApiScope enum. */ + type ApiScope = + "ANY_API"| "DATASTORE_MODE_API"; + + /** Properties of an IndexField. */ + interface IIndexField { + + /** IndexField fieldPath */ + fieldPath?: (string|null); + + /** IndexField order */ + order?: (google.firestore.admin.v1.Index.IndexField.Order|null); + + /** IndexField arrayConfig */ + arrayConfig?: (google.firestore.admin.v1.Index.IndexField.ArrayConfig|null); + + /** IndexField vectorConfig */ + vectorConfig?: (google.firestore.admin.v1.Index.IndexField.IVectorConfig|null); + } + + /** Represents an IndexField. */ + class IndexField implements IIndexField { + + /** + * Constructs a new IndexField. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Index.IIndexField); + + /** IndexField fieldPath. */ + public fieldPath: string; + + /** IndexField order. */ + public order?: (google.firestore.admin.v1.Index.IndexField.Order|null); + + /** IndexField arrayConfig. */ + public arrayConfig?: (google.firestore.admin.v1.Index.IndexField.ArrayConfig|null); + + /** IndexField vectorConfig. */ + public vectorConfig?: (google.firestore.admin.v1.Index.IndexField.IVectorConfig|null); + + /** IndexField valueMode. */ + public valueMode?: ("order"|"arrayConfig"|"vectorConfig"); + + /** + * Creates an IndexField message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IndexField + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index.IndexField; + + /** + * Creates a plain object from an IndexField message. Also converts values to other types if specified. + * @param message IndexField + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Index.IndexField, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IndexField to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IndexField + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace IndexField { + + /** Order enum. */ + type Order = + "ORDER_UNSPECIFIED"| "ASCENDING"| "DESCENDING"; + + /** ArrayConfig enum. */ + type ArrayConfig = + "ARRAY_CONFIG_UNSPECIFIED"| "CONTAINS"; + + /** Properties of a VectorConfig. */ + interface IVectorConfig { + + /** VectorConfig dimension */ + dimension?: (number|null); + + /** VectorConfig flat */ + flat?: (google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex|null); + } + + /** Represents a VectorConfig. */ + class VectorConfig implements IVectorConfig { + + /** + * Constructs a new VectorConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Index.IndexField.IVectorConfig); + + /** VectorConfig dimension. */ + public dimension: number; + + /** VectorConfig flat. */ + public flat?: (google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex|null); + + /** VectorConfig type. */ + public type?: "flat"; + + /** + * Creates a VectorConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns VectorConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index.IndexField.VectorConfig; + + /** + * Creates a plain object from a VectorConfig message. Also converts values to other types if specified. + * @param message VectorConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Index.IndexField.VectorConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this VectorConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for VectorConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace VectorConfig { + + /** Properties of a FlatIndex. */ + interface IFlatIndex { + } + + /** Represents a FlatIndex. */ + class FlatIndex implements IFlatIndex { + + /** + * Constructs a new FlatIndex. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex); + + /** + * Creates a FlatIndex message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FlatIndex + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex; + + /** + * Creates a plain object from a FlatIndex message. Also converts values to other types if specified. + * @param message FlatIndex + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FlatIndex to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FlatIndex + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + + /** State enum. */ + type State = + "STATE_UNSPECIFIED"| "CREATING"| "READY"| "NEEDS_REPAIR"; + } + + /** Represents a FirestoreAdmin */ + class FirestoreAdmin extends $protobuf.rpc.Service { + + /** + * Constructs a new FirestoreAdmin service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls CreateIndex. + * @param request CreateIndexRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public createIndex(request: google.firestore.admin.v1.ICreateIndexRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CreateIndexCallback): void; + + /** + * Calls CreateIndex. + * @param request CreateIndexRequest message or plain object + * @returns Promise + */ + public createIndex(request: google.firestore.admin.v1.ICreateIndexRequest): Promise; + + /** + * Calls ListIndexes. + * @param request ListIndexesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListIndexesResponse + */ + public listIndexes(request: google.firestore.admin.v1.IListIndexesRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListIndexesCallback): void; + + /** + * Calls ListIndexes. + * @param request ListIndexesRequest message or plain object + * @returns Promise + */ + public listIndexes(request: google.firestore.admin.v1.IListIndexesRequest): Promise; + + /** + * Calls GetIndex. + * @param request GetIndexRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Index + */ + public getIndex(request: google.firestore.admin.v1.IGetIndexRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetIndexCallback): void; + + /** + * Calls GetIndex. + * @param request GetIndexRequest message or plain object + * @returns Promise + */ + public getIndex(request: google.firestore.admin.v1.IGetIndexRequest): Promise; + + /** + * Calls DeleteIndex. + * @param request DeleteIndexRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteIndex(request: google.firestore.admin.v1.IDeleteIndexRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteIndexCallback): void; + + /** + * Calls DeleteIndex. + * @param request DeleteIndexRequest message or plain object + * @returns Promise + */ + public deleteIndex(request: google.firestore.admin.v1.IDeleteIndexRequest): Promise; + + /** + * Calls GetField. + * @param request GetFieldRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Field + */ + public getField(request: google.firestore.admin.v1.IGetFieldRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetFieldCallback): void; + + /** + * Calls GetField. + * @param request GetFieldRequest message or plain object + * @returns Promise + */ + public getField(request: google.firestore.admin.v1.IGetFieldRequest): Promise; + + /** + * Calls UpdateField. + * @param request UpdateFieldRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public updateField(request: google.firestore.admin.v1.IUpdateFieldRequest, callback: google.firestore.admin.v1.FirestoreAdmin.UpdateFieldCallback): void; + + /** + * Calls UpdateField. + * @param request UpdateFieldRequest message or plain object + * @returns Promise + */ + public updateField(request: google.firestore.admin.v1.IUpdateFieldRequest): Promise; + + /** + * Calls ListFields. + * @param request ListFieldsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListFieldsResponse + */ + public listFields(request: google.firestore.admin.v1.IListFieldsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListFieldsCallback): void; + + /** + * Calls ListFields. + * @param request ListFieldsRequest message or plain object + * @returns Promise + */ + public listFields(request: google.firestore.admin.v1.IListFieldsRequest): Promise; + + /** + * Calls ExportDocuments. + * @param request ExportDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public exportDocuments(request: google.firestore.admin.v1.IExportDocumentsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ExportDocumentsCallback): void; + + /** + * Calls ExportDocuments. + * @param request ExportDocumentsRequest message or plain object + * @returns Promise + */ + public exportDocuments(request: google.firestore.admin.v1.IExportDocumentsRequest): Promise; + + /** + * Calls ImportDocuments. + * @param request ImportDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public importDocuments(request: google.firestore.admin.v1.IImportDocumentsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ImportDocumentsCallback): void; + + /** + * Calls ImportDocuments. + * @param request ImportDocumentsRequest message or plain object + * @returns Promise + */ + public importDocuments(request: google.firestore.admin.v1.IImportDocumentsRequest): Promise; + + /** + * Calls BulkDeleteDocuments. + * @param request BulkDeleteDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public bulkDeleteDocuments(request: google.firestore.admin.v1.IBulkDeleteDocumentsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.BulkDeleteDocumentsCallback): void; + + /** + * Calls BulkDeleteDocuments. + * @param request BulkDeleteDocumentsRequest message or plain object + * @returns Promise + */ + public bulkDeleteDocuments(request: google.firestore.admin.v1.IBulkDeleteDocumentsRequest): Promise; + + /** + * Calls CreateDatabase. + * @param request CreateDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public createDatabase(request: google.firestore.admin.v1.ICreateDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CreateDatabaseCallback): void; + + /** + * Calls CreateDatabase. + * @param request CreateDatabaseRequest message or plain object + * @returns Promise + */ + public createDatabase(request: google.firestore.admin.v1.ICreateDatabaseRequest): Promise; + + /** + * Calls GetDatabase. + * @param request GetDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Database + */ + public getDatabase(request: google.firestore.admin.v1.IGetDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetDatabaseCallback): void; + + /** + * Calls GetDatabase. + * @param request GetDatabaseRequest message or plain object + * @returns Promise + */ + public getDatabase(request: google.firestore.admin.v1.IGetDatabaseRequest): Promise; + + /** + * Calls ListDatabases. + * @param request ListDatabasesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListDatabasesResponse + */ + public listDatabases(request: google.firestore.admin.v1.IListDatabasesRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListDatabasesCallback): void; + + /** + * Calls ListDatabases. + * @param request ListDatabasesRequest message or plain object + * @returns Promise + */ + public listDatabases(request: google.firestore.admin.v1.IListDatabasesRequest): Promise; + + /** + * Calls UpdateDatabase. + * @param request UpdateDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public updateDatabase(request: google.firestore.admin.v1.IUpdateDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.UpdateDatabaseCallback): void; + + /** + * Calls UpdateDatabase. + * @param request UpdateDatabaseRequest message or plain object + * @returns Promise + */ + public updateDatabase(request: google.firestore.admin.v1.IUpdateDatabaseRequest): Promise; + + /** + * Calls DeleteDatabase. + * @param request DeleteDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public deleteDatabase(request: google.firestore.admin.v1.IDeleteDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteDatabaseCallback): void; + + /** + * Calls DeleteDatabase. + * @param request DeleteDatabaseRequest message or plain object + * @returns Promise + */ + public deleteDatabase(request: google.firestore.admin.v1.IDeleteDatabaseRequest): Promise; + + /** + * Calls GetBackup. + * @param request GetBackupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Backup + */ + public getBackup(request: google.firestore.admin.v1.IGetBackupRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetBackupCallback): void; + + /** + * Calls GetBackup. + * @param request GetBackupRequest message or plain object + * @returns Promise + */ + public getBackup(request: google.firestore.admin.v1.IGetBackupRequest): Promise; + + /** + * Calls ListBackups. + * @param request ListBackupsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListBackupsResponse + */ + public listBackups(request: google.firestore.admin.v1.IListBackupsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListBackupsCallback): void; + + /** + * Calls ListBackups. + * @param request ListBackupsRequest message or plain object + * @returns Promise + */ + public listBackups(request: google.firestore.admin.v1.IListBackupsRequest): Promise; + + /** + * Calls DeleteBackup. + * @param request DeleteBackupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteBackup(request: google.firestore.admin.v1.IDeleteBackupRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteBackupCallback): void; + + /** + * Calls DeleteBackup. + * @param request DeleteBackupRequest message or plain object + * @returns Promise + */ + public deleteBackup(request: google.firestore.admin.v1.IDeleteBackupRequest): Promise; + + /** + * Calls RestoreDatabase. + * @param request RestoreDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public restoreDatabase(request: google.firestore.admin.v1.IRestoreDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.RestoreDatabaseCallback): void; + + /** + * Calls RestoreDatabase. + * @param request RestoreDatabaseRequest message or plain object + * @returns Promise + */ + public restoreDatabase(request: google.firestore.admin.v1.IRestoreDatabaseRequest): Promise; + + /** + * Calls CreateBackupSchedule. + * @param request CreateBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BackupSchedule + */ + public createBackupSchedule(request: google.firestore.admin.v1.ICreateBackupScheduleRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CreateBackupScheduleCallback): void; + + /** + * Calls CreateBackupSchedule. + * @param request CreateBackupScheduleRequest message or plain object + * @returns Promise + */ + public createBackupSchedule(request: google.firestore.admin.v1.ICreateBackupScheduleRequest): Promise; + + /** + * Calls GetBackupSchedule. + * @param request GetBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BackupSchedule + */ + public getBackupSchedule(request: google.firestore.admin.v1.IGetBackupScheduleRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetBackupScheduleCallback): void; + + /** + * Calls GetBackupSchedule. + * @param request GetBackupScheduleRequest message or plain object + * @returns Promise + */ + public getBackupSchedule(request: google.firestore.admin.v1.IGetBackupScheduleRequest): Promise; + + /** + * Calls ListBackupSchedules. + * @param request ListBackupSchedulesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListBackupSchedulesResponse + */ + public listBackupSchedules(request: google.firestore.admin.v1.IListBackupSchedulesRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListBackupSchedulesCallback): void; + + /** + * Calls ListBackupSchedules. + * @param request ListBackupSchedulesRequest message or plain object + * @returns Promise + */ + public listBackupSchedules(request: google.firestore.admin.v1.IListBackupSchedulesRequest): Promise; + + /** + * Calls UpdateBackupSchedule. + * @param request UpdateBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BackupSchedule + */ + public updateBackupSchedule(request: google.firestore.admin.v1.IUpdateBackupScheduleRequest, callback: google.firestore.admin.v1.FirestoreAdmin.UpdateBackupScheduleCallback): void; + + /** + * Calls UpdateBackupSchedule. + * @param request UpdateBackupScheduleRequest message or plain object + * @returns Promise + */ + public updateBackupSchedule(request: google.firestore.admin.v1.IUpdateBackupScheduleRequest): Promise; + + /** + * Calls DeleteBackupSchedule. + * @param request DeleteBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteBackupSchedule(request: google.firestore.admin.v1.IDeleteBackupScheduleRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteBackupScheduleCallback): void; + + /** + * Calls DeleteBackupSchedule. + * @param request DeleteBackupScheduleRequest message or plain object + * @returns Promise + */ + public deleteBackupSchedule(request: google.firestore.admin.v1.IDeleteBackupScheduleRequest): Promise; + } + + namespace FirestoreAdmin { + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createIndex}. + * @param error Error, if any + * @param [response] Operation + */ + type CreateIndexCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listIndexes}. + * @param error Error, if any + * @param [response] ListIndexesResponse + */ + type ListIndexesCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListIndexesResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getIndex}. + * @param error Error, if any + * @param [response] Index + */ + type GetIndexCallback = (error: (Error|null), response?: google.firestore.admin.v1.Index) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteIndex}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteIndexCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getField}. + * @param error Error, if any + * @param [response] Field + */ + type GetFieldCallback = (error: (Error|null), response?: google.firestore.admin.v1.Field) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#updateField}. + * @param error Error, if any + * @param [response] Operation + */ + type UpdateFieldCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listFields}. + * @param error Error, if any + * @param [response] ListFieldsResponse + */ + type ListFieldsCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListFieldsResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#exportDocuments}. + * @param error Error, if any + * @param [response] Operation + */ + type ExportDocumentsCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#importDocuments}. + * @param error Error, if any + * @param [response] Operation + */ + type ImportDocumentsCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#bulkDeleteDocuments}. + * @param error Error, if any + * @param [response] Operation + */ + type BulkDeleteDocumentsCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type CreateDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getDatabase}. + * @param error Error, if any + * @param [response] Database + */ + type GetDatabaseCallback = (error: (Error|null), response?: google.firestore.admin.v1.Database) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listDatabases}. + * @param error Error, if any + * @param [response] ListDatabasesResponse + */ + type ListDatabasesCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListDatabasesResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#updateDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type UpdateDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type DeleteDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getBackup}. + * @param error Error, if any + * @param [response] Backup + */ + type GetBackupCallback = (error: (Error|null), response?: google.firestore.admin.v1.Backup) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listBackups}. + * @param error Error, if any + * @param [response] ListBackupsResponse + */ + type ListBackupsCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListBackupsResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteBackup}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteBackupCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#restoreDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type RestoreDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createBackupSchedule}. + * @param error Error, if any + * @param [response] BackupSchedule + */ + type CreateBackupScheduleCallback = (error: (Error|null), response?: google.firestore.admin.v1.BackupSchedule) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getBackupSchedule}. + * @param error Error, if any + * @param [response] BackupSchedule + */ + type GetBackupScheduleCallback = (error: (Error|null), response?: google.firestore.admin.v1.BackupSchedule) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listBackupSchedules}. + * @param error Error, if any + * @param [response] ListBackupSchedulesResponse + */ + type ListBackupSchedulesCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListBackupSchedulesResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#updateBackupSchedule}. + * @param error Error, if any + * @param [response] BackupSchedule + */ + type UpdateBackupScheduleCallback = (error: (Error|null), response?: google.firestore.admin.v1.BackupSchedule) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteBackupSchedule}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteBackupScheduleCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + } + + /** Properties of a ListDatabasesRequest. */ + interface IListDatabasesRequest { + + /** ListDatabasesRequest parent */ + parent?: (string|null); + + /** ListDatabasesRequest showDeleted */ + showDeleted?: (boolean|null); + } + + /** Represents a ListDatabasesRequest. */ + class ListDatabasesRequest implements IListDatabasesRequest { + + /** + * Constructs a new ListDatabasesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListDatabasesRequest); + + /** ListDatabasesRequest parent. */ + public parent: string; + + /** ListDatabasesRequest showDeleted. */ + public showDeleted: boolean; + + /** + * Creates a ListDatabasesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDatabasesRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListDatabasesRequest; + + /** + * Creates a plain object from a ListDatabasesRequest message. Also converts values to other types if specified. + * @param message ListDatabasesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListDatabasesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDatabasesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDatabasesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDatabaseRequest. */ + interface ICreateDatabaseRequest { + + /** CreateDatabaseRequest parent */ + parent?: (string|null); + + /** CreateDatabaseRequest database */ + database?: (google.firestore.admin.v1.IDatabase|null); + + /** CreateDatabaseRequest databaseId */ + databaseId?: (string|null); + } + + /** Represents a CreateDatabaseRequest. */ + class CreateDatabaseRequest implements ICreateDatabaseRequest { + + /** + * Constructs a new CreateDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateDatabaseRequest); + + /** CreateDatabaseRequest parent. */ + public parent: string; + + /** CreateDatabaseRequest database. */ + public database?: (google.firestore.admin.v1.IDatabase|null); + + /** CreateDatabaseRequest databaseId. */ + public databaseId: string; + + /** + * Creates a CreateDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateDatabaseRequest; + + /** + * Creates a plain object from a CreateDatabaseRequest message. Also converts values to other types if specified. + * @param message CreateDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDatabaseMetadata. */ + interface ICreateDatabaseMetadata { + } + + /** Represents a CreateDatabaseMetadata. */ + class CreateDatabaseMetadata implements ICreateDatabaseMetadata { + + /** + * Constructs a new CreateDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateDatabaseMetadata); + + /** + * Creates a CreateDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateDatabaseMetadata; + + /** + * Creates a plain object from a CreateDatabaseMetadata message. Also converts values to other types if specified. + * @param message CreateDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDatabasesResponse. */ + interface IListDatabasesResponse { + + /** ListDatabasesResponse databases */ + databases?: (google.firestore.admin.v1.IDatabase[]|null); + + /** ListDatabasesResponse unreachable */ + unreachable?: (string[]|null); + } + + /** Represents a ListDatabasesResponse. */ + class ListDatabasesResponse implements IListDatabasesResponse { + + /** + * Constructs a new ListDatabasesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListDatabasesResponse); + + /** ListDatabasesResponse databases. */ + public databases: google.firestore.admin.v1.IDatabase[]; + + /** ListDatabasesResponse unreachable. */ + public unreachable: string[]; + + /** + * Creates a ListDatabasesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDatabasesResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListDatabasesResponse; + + /** + * Creates a plain object from a ListDatabasesResponse message. Also converts values to other types if specified. + * @param message ListDatabasesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListDatabasesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDatabasesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDatabasesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetDatabaseRequest. */ + interface IGetDatabaseRequest { + + /** GetDatabaseRequest name */ + name?: (string|null); + } + + /** Represents a GetDatabaseRequest. */ + class GetDatabaseRequest implements IGetDatabaseRequest { + + /** + * Constructs a new GetDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetDatabaseRequest); + + /** GetDatabaseRequest name. */ + public name: string; + + /** + * Creates a GetDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetDatabaseRequest; + + /** + * Creates a plain object from a GetDatabaseRequest message. Also converts values to other types if specified. + * @param message GetDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDatabaseRequest. */ + interface IUpdateDatabaseRequest { + + /** UpdateDatabaseRequest database */ + database?: (google.firestore.admin.v1.IDatabase|null); + + /** UpdateDatabaseRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateDatabaseRequest. */ + class UpdateDatabaseRequest implements IUpdateDatabaseRequest { + + /** + * Constructs a new UpdateDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateDatabaseRequest); + + /** UpdateDatabaseRequest database. */ + public database?: (google.firestore.admin.v1.IDatabase|null); + + /** UpdateDatabaseRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates an UpdateDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateDatabaseRequest; + + /** + * Creates a plain object from an UpdateDatabaseRequest message. Also converts values to other types if specified. + * @param message UpdateDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDatabaseMetadata. */ + interface IUpdateDatabaseMetadata { + } + + /** Represents an UpdateDatabaseMetadata. */ + class UpdateDatabaseMetadata implements IUpdateDatabaseMetadata { + + /** + * Constructs a new UpdateDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateDatabaseMetadata); + + /** + * Creates an UpdateDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateDatabaseMetadata; + + /** + * Creates a plain object from an UpdateDatabaseMetadata message. Also converts values to other types if specified. + * @param message UpdateDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDatabaseRequest. */ + interface IDeleteDatabaseRequest { + + /** DeleteDatabaseRequest name */ + name?: (string|null); + + /** DeleteDatabaseRequest etag */ + etag?: (string|null); + } + + /** Represents a DeleteDatabaseRequest. */ + class DeleteDatabaseRequest implements IDeleteDatabaseRequest { + + /** + * Constructs a new DeleteDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteDatabaseRequest); + + /** DeleteDatabaseRequest name. */ + public name: string; + + /** DeleteDatabaseRequest etag. */ + public etag: string; + + /** + * Creates a DeleteDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteDatabaseRequest; + + /** + * Creates a plain object from a DeleteDatabaseRequest message. Also converts values to other types if specified. + * @param message DeleteDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDatabaseMetadata. */ + interface IDeleteDatabaseMetadata { + } + + /** Represents a DeleteDatabaseMetadata. */ + class DeleteDatabaseMetadata implements IDeleteDatabaseMetadata { + + /** + * Constructs a new DeleteDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteDatabaseMetadata); + + /** + * Creates a DeleteDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteDatabaseMetadata; + + /** + * Creates a plain object from a DeleteDatabaseMetadata message. Also converts values to other types if specified. + * @param message DeleteDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateBackupScheduleRequest. */ + interface ICreateBackupScheduleRequest { + + /** CreateBackupScheduleRequest parent */ + parent?: (string|null); + + /** CreateBackupScheduleRequest backupSchedule */ + backupSchedule?: (google.firestore.admin.v1.IBackupSchedule|null); + } + + /** Represents a CreateBackupScheduleRequest. */ + class CreateBackupScheduleRequest implements ICreateBackupScheduleRequest { + + /** + * Constructs a new CreateBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateBackupScheduleRequest); + + /** CreateBackupScheduleRequest parent. */ + public parent: string; + + /** CreateBackupScheduleRequest backupSchedule. */ + public backupSchedule?: (google.firestore.admin.v1.IBackupSchedule|null); + + /** + * Creates a CreateBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateBackupScheduleRequest; + + /** + * Creates a plain object from a CreateBackupScheduleRequest message. Also converts values to other types if specified. + * @param message CreateBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetBackupScheduleRequest. */ + interface IGetBackupScheduleRequest { + + /** GetBackupScheduleRequest name */ + name?: (string|null); + } + + /** Represents a GetBackupScheduleRequest. */ + class GetBackupScheduleRequest implements IGetBackupScheduleRequest { + + /** + * Constructs a new GetBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetBackupScheduleRequest); + + /** GetBackupScheduleRequest name. */ + public name: string; + + /** + * Creates a GetBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetBackupScheduleRequest; + + /** + * Creates a plain object from a GetBackupScheduleRequest message. Also converts values to other types if specified. + * @param message GetBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateBackupScheduleRequest. */ + interface IUpdateBackupScheduleRequest { + + /** UpdateBackupScheduleRequest backupSchedule */ + backupSchedule?: (google.firestore.admin.v1.IBackupSchedule|null); + + /** UpdateBackupScheduleRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateBackupScheduleRequest. */ + class UpdateBackupScheduleRequest implements IUpdateBackupScheduleRequest { + + /** + * Constructs a new UpdateBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateBackupScheduleRequest); + + /** UpdateBackupScheduleRequest backupSchedule. */ + public backupSchedule?: (google.firestore.admin.v1.IBackupSchedule|null); + + /** UpdateBackupScheduleRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates an UpdateBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateBackupScheduleRequest; + + /** + * Creates a plain object from an UpdateBackupScheduleRequest message. Also converts values to other types if specified. + * @param message UpdateBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupSchedulesRequest. */ + interface IListBackupSchedulesRequest { + + /** ListBackupSchedulesRequest parent */ + parent?: (string|null); + } + + /** Represents a ListBackupSchedulesRequest. */ + class ListBackupSchedulesRequest implements IListBackupSchedulesRequest { + + /** + * Constructs a new ListBackupSchedulesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListBackupSchedulesRequest); + + /** ListBackupSchedulesRequest parent. */ + public parent: string; + + /** + * Creates a ListBackupSchedulesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupSchedulesRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListBackupSchedulesRequest; + + /** + * Creates a plain object from a ListBackupSchedulesRequest message. Also converts values to other types if specified. + * @param message ListBackupSchedulesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListBackupSchedulesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupSchedulesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupSchedulesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupSchedulesResponse. */ + interface IListBackupSchedulesResponse { + + /** ListBackupSchedulesResponse backupSchedules */ + backupSchedules?: (google.firestore.admin.v1.IBackupSchedule[]|null); + } + + /** Represents a ListBackupSchedulesResponse. */ + class ListBackupSchedulesResponse implements IListBackupSchedulesResponse { + + /** + * Constructs a new ListBackupSchedulesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListBackupSchedulesResponse); + + /** ListBackupSchedulesResponse backupSchedules. */ + public backupSchedules: google.firestore.admin.v1.IBackupSchedule[]; + + /** + * Creates a ListBackupSchedulesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupSchedulesResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListBackupSchedulesResponse; + + /** + * Creates a plain object from a ListBackupSchedulesResponse message. Also converts values to other types if specified. + * @param message ListBackupSchedulesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListBackupSchedulesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupSchedulesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupSchedulesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteBackupScheduleRequest. */ + interface IDeleteBackupScheduleRequest { + + /** DeleteBackupScheduleRequest name */ + name?: (string|null); + } + + /** Represents a DeleteBackupScheduleRequest. */ + class DeleteBackupScheduleRequest implements IDeleteBackupScheduleRequest { + + /** + * Constructs a new DeleteBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteBackupScheduleRequest); + + /** DeleteBackupScheduleRequest name. */ + public name: string; + + /** + * Creates a DeleteBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteBackupScheduleRequest; + + /** + * Creates a plain object from a DeleteBackupScheduleRequest message. Also converts values to other types if specified. + * @param message DeleteBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateIndexRequest. */ + interface ICreateIndexRequest { + + /** CreateIndexRequest parent */ + parent?: (string|null); + + /** CreateIndexRequest index */ + index?: (google.firestore.admin.v1.IIndex|null); + } + + /** Represents a CreateIndexRequest. */ + class CreateIndexRequest implements ICreateIndexRequest { + + /** + * Constructs a new CreateIndexRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateIndexRequest); + + /** CreateIndexRequest parent. */ + public parent: string; + + /** CreateIndexRequest index. */ + public index?: (google.firestore.admin.v1.IIndex|null); + + /** + * Creates a CreateIndexRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateIndexRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateIndexRequest; + + /** + * Creates a plain object from a CreateIndexRequest message. Also converts values to other types if specified. + * @param message CreateIndexRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateIndexRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateIndexRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateIndexRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListIndexesRequest. */ + interface IListIndexesRequest { + + /** ListIndexesRequest parent */ + parent?: (string|null); + + /** ListIndexesRequest filter */ + filter?: (string|null); + + /** ListIndexesRequest pageSize */ + pageSize?: (number|null); + + /** ListIndexesRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListIndexesRequest. */ + class ListIndexesRequest implements IListIndexesRequest { + + /** + * Constructs a new ListIndexesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListIndexesRequest); + + /** ListIndexesRequest parent. */ + public parent: string; + + /** ListIndexesRequest filter. */ + public filter: string; + + /** ListIndexesRequest pageSize. */ + public pageSize: number; + + /** ListIndexesRequest pageToken. */ + public pageToken: string; + + /** + * Creates a ListIndexesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListIndexesRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListIndexesRequest; + + /** + * Creates a plain object from a ListIndexesRequest message. Also converts values to other types if specified. + * @param message ListIndexesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListIndexesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListIndexesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListIndexesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListIndexesResponse. */ + interface IListIndexesResponse { + + /** ListIndexesResponse indexes */ + indexes?: (google.firestore.admin.v1.IIndex[]|null); + + /** ListIndexesResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListIndexesResponse. */ + class ListIndexesResponse implements IListIndexesResponse { + + /** + * Constructs a new ListIndexesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListIndexesResponse); + + /** ListIndexesResponse indexes. */ + public indexes: google.firestore.admin.v1.IIndex[]; + + /** ListIndexesResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListIndexesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListIndexesResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListIndexesResponse; + + /** + * Creates a plain object from a ListIndexesResponse message. Also converts values to other types if specified. + * @param message ListIndexesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListIndexesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListIndexesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListIndexesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetIndexRequest. */ + interface IGetIndexRequest { + + /** GetIndexRequest name */ + name?: (string|null); + } + + /** Represents a GetIndexRequest. */ + class GetIndexRequest implements IGetIndexRequest { + + /** + * Constructs a new GetIndexRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetIndexRequest); + + /** GetIndexRequest name. */ + public name: string; + + /** + * Creates a GetIndexRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetIndexRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetIndexRequest; + + /** + * Creates a plain object from a GetIndexRequest message. Also converts values to other types if specified. + * @param message GetIndexRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetIndexRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetIndexRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetIndexRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteIndexRequest. */ + interface IDeleteIndexRequest { + + /** DeleteIndexRequest name */ + name?: (string|null); + } + + /** Represents a DeleteIndexRequest. */ + class DeleteIndexRequest implements IDeleteIndexRequest { + + /** + * Constructs a new DeleteIndexRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteIndexRequest); + + /** DeleteIndexRequest name. */ + public name: string; + + /** + * Creates a DeleteIndexRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteIndexRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteIndexRequest; + + /** + * Creates a plain object from a DeleteIndexRequest message. Also converts values to other types if specified. + * @param message DeleteIndexRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteIndexRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteIndexRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteIndexRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateFieldRequest. */ + interface IUpdateFieldRequest { + + /** UpdateFieldRequest field */ + field?: (google.firestore.admin.v1.IField|null); + + /** UpdateFieldRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateFieldRequest. */ + class UpdateFieldRequest implements IUpdateFieldRequest { + + /** + * Constructs a new UpdateFieldRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateFieldRequest); + + /** UpdateFieldRequest field. */ + public field?: (google.firestore.admin.v1.IField|null); + + /** UpdateFieldRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates an UpdateFieldRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateFieldRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateFieldRequest; + + /** + * Creates a plain object from an UpdateFieldRequest message. Also converts values to other types if specified. + * @param message UpdateFieldRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateFieldRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateFieldRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateFieldRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetFieldRequest. */ + interface IGetFieldRequest { + + /** GetFieldRequest name */ + name?: (string|null); + } + + /** Represents a GetFieldRequest. */ + class GetFieldRequest implements IGetFieldRequest { + + /** + * Constructs a new GetFieldRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetFieldRequest); + + /** GetFieldRequest name. */ + public name: string; + + /** + * Creates a GetFieldRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetFieldRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetFieldRequest; + + /** + * Creates a plain object from a GetFieldRequest message. Also converts values to other types if specified. + * @param message GetFieldRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetFieldRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetFieldRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetFieldRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListFieldsRequest. */ + interface IListFieldsRequest { + + /** ListFieldsRequest parent */ + parent?: (string|null); + + /** ListFieldsRequest filter */ + filter?: (string|null); + + /** ListFieldsRequest pageSize */ + pageSize?: (number|null); + + /** ListFieldsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListFieldsRequest. */ + class ListFieldsRequest implements IListFieldsRequest { + + /** + * Constructs a new ListFieldsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListFieldsRequest); + + /** ListFieldsRequest parent. */ + public parent: string; + + /** ListFieldsRequest filter. */ + public filter: string; + + /** ListFieldsRequest pageSize. */ + public pageSize: number; + + /** ListFieldsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a ListFieldsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListFieldsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListFieldsRequest; + + /** + * Creates a plain object from a ListFieldsRequest message. Also converts values to other types if specified. + * @param message ListFieldsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListFieldsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListFieldsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListFieldsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListFieldsResponse. */ + interface IListFieldsResponse { + + /** ListFieldsResponse fields */ + fields?: (google.firestore.admin.v1.IField[]|null); + + /** ListFieldsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListFieldsResponse. */ + class ListFieldsResponse implements IListFieldsResponse { + + /** + * Constructs a new ListFieldsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListFieldsResponse); + + /** ListFieldsResponse fields. */ + public fields: google.firestore.admin.v1.IField[]; + + /** ListFieldsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListFieldsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListFieldsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListFieldsResponse; + + /** + * Creates a plain object from a ListFieldsResponse message. Also converts values to other types if specified. + * @param message ListFieldsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListFieldsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListFieldsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListFieldsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExportDocumentsRequest. */ + interface IExportDocumentsRequest { + + /** ExportDocumentsRequest name */ + name?: (string|null); + + /** ExportDocumentsRequest collectionIds */ + collectionIds?: (string[]|null); + + /** ExportDocumentsRequest outputUriPrefix */ + outputUriPrefix?: (string|null); + + /** ExportDocumentsRequest namespaceIds */ + namespaceIds?: (string[]|null); + + /** ExportDocumentsRequest snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an ExportDocumentsRequest. */ + class ExportDocumentsRequest implements IExportDocumentsRequest { + + /** + * Constructs a new ExportDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IExportDocumentsRequest); + + /** ExportDocumentsRequest name. */ + public name: string; + + /** ExportDocumentsRequest collectionIds. */ + public collectionIds: string[]; + + /** ExportDocumentsRequest outputUriPrefix. */ + public outputUriPrefix: string; + + /** ExportDocumentsRequest namespaceIds. */ + public namespaceIds: string[]; + + /** ExportDocumentsRequest snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates an ExportDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExportDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ExportDocumentsRequest; + + /** + * Creates a plain object from an ExportDocumentsRequest message. Also converts values to other types if specified. + * @param message ExportDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ExportDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExportDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExportDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ImportDocumentsRequest. */ + interface IImportDocumentsRequest { + + /** ImportDocumentsRequest name */ + name?: (string|null); + + /** ImportDocumentsRequest collectionIds */ + collectionIds?: (string[]|null); + + /** ImportDocumentsRequest inputUriPrefix */ + inputUriPrefix?: (string|null); + + /** ImportDocumentsRequest namespaceIds */ + namespaceIds?: (string[]|null); + } + + /** Represents an ImportDocumentsRequest. */ + class ImportDocumentsRequest implements IImportDocumentsRequest { + + /** + * Constructs a new ImportDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IImportDocumentsRequest); + + /** ImportDocumentsRequest name. */ + public name: string; + + /** ImportDocumentsRequest collectionIds. */ + public collectionIds: string[]; + + /** ImportDocumentsRequest inputUriPrefix. */ + public inputUriPrefix: string; + + /** ImportDocumentsRequest namespaceIds. */ + public namespaceIds: string[]; + + /** + * Creates an ImportDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ImportDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ImportDocumentsRequest; + + /** + * Creates a plain object from an ImportDocumentsRequest message. Also converts values to other types if specified. + * @param message ImportDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ImportDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ImportDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ImportDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BulkDeleteDocumentsRequest. */ + interface IBulkDeleteDocumentsRequest { + + /** BulkDeleteDocumentsRequest name */ + name?: (string|null); + + /** BulkDeleteDocumentsRequest collectionIds */ + collectionIds?: (string[]|null); + + /** BulkDeleteDocumentsRequest namespaceIds */ + namespaceIds?: (string[]|null); + } + + /** Represents a BulkDeleteDocumentsRequest. */ + class BulkDeleteDocumentsRequest implements IBulkDeleteDocumentsRequest { + + /** + * Constructs a new BulkDeleteDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBulkDeleteDocumentsRequest); + + /** BulkDeleteDocumentsRequest name. */ + public name: string; + + /** BulkDeleteDocumentsRequest collectionIds. */ + public collectionIds: string[]; + + /** BulkDeleteDocumentsRequest namespaceIds. */ + public namespaceIds: string[]; + + /** + * Creates a BulkDeleteDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BulkDeleteDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BulkDeleteDocumentsRequest; + + /** + * Creates a plain object from a BulkDeleteDocumentsRequest message. Also converts values to other types if specified. + * @param message BulkDeleteDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.BulkDeleteDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BulkDeleteDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BulkDeleteDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BulkDeleteDocumentsResponse. */ + interface IBulkDeleteDocumentsResponse { + } + + /** Represents a BulkDeleteDocumentsResponse. */ + class BulkDeleteDocumentsResponse implements IBulkDeleteDocumentsResponse { + + /** + * Constructs a new BulkDeleteDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBulkDeleteDocumentsResponse); + + /** + * Creates a BulkDeleteDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BulkDeleteDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BulkDeleteDocumentsResponse; + + /** + * Creates a plain object from a BulkDeleteDocumentsResponse message. Also converts values to other types if specified. + * @param message BulkDeleteDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.BulkDeleteDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BulkDeleteDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BulkDeleteDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetBackupRequest. */ + interface IGetBackupRequest { + + /** GetBackupRequest name */ + name?: (string|null); + } + + /** Represents a GetBackupRequest. */ + class GetBackupRequest implements IGetBackupRequest { + + /** + * Constructs a new GetBackupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetBackupRequest); + + /** GetBackupRequest name. */ + public name: string; + + /** + * Creates a GetBackupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetBackupRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetBackupRequest; + + /** + * Creates a plain object from a GetBackupRequest message. Also converts values to other types if specified. + * @param message GetBackupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetBackupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetBackupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetBackupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupsRequest. */ + interface IListBackupsRequest { + + /** ListBackupsRequest parent */ + parent?: (string|null); + + /** ListBackupsRequest filter */ + filter?: (string|null); + } + + /** Represents a ListBackupsRequest. */ + class ListBackupsRequest implements IListBackupsRequest { + + /** + * Constructs a new ListBackupsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListBackupsRequest); + + /** ListBackupsRequest parent. */ + public parent: string; + + /** ListBackupsRequest filter. */ + public filter: string; + + /** + * Creates a ListBackupsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListBackupsRequest; + + /** + * Creates a plain object from a ListBackupsRequest message. Also converts values to other types if specified. + * @param message ListBackupsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListBackupsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupsResponse. */ + interface IListBackupsResponse { + + /** ListBackupsResponse backups */ + backups?: (google.firestore.admin.v1.IBackup[]|null); + + /** ListBackupsResponse unreachable */ + unreachable?: (string[]|null); + } + + /** Represents a ListBackupsResponse. */ + class ListBackupsResponse implements IListBackupsResponse { + + /** + * Constructs a new ListBackupsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListBackupsResponse); + + /** ListBackupsResponse backups. */ + public backups: google.firestore.admin.v1.IBackup[]; + + /** ListBackupsResponse unreachable. */ + public unreachable: string[]; + + /** + * Creates a ListBackupsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListBackupsResponse; + + /** + * Creates a plain object from a ListBackupsResponse message. Also converts values to other types if specified. + * @param message ListBackupsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListBackupsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteBackupRequest. */ + interface IDeleteBackupRequest { + + /** DeleteBackupRequest name */ + name?: (string|null); + } + + /** Represents a DeleteBackupRequest. */ + class DeleteBackupRequest implements IDeleteBackupRequest { + + /** + * Constructs a new DeleteBackupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteBackupRequest); + + /** DeleteBackupRequest name. */ + public name: string; + + /** + * Creates a DeleteBackupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteBackupRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteBackupRequest; + + /** + * Creates a plain object from a DeleteBackupRequest message. Also converts values to other types if specified. + * @param message DeleteBackupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteBackupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteBackupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteBackupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RestoreDatabaseRequest. */ + interface IRestoreDatabaseRequest { + + /** RestoreDatabaseRequest parent */ + parent?: (string|null); + + /** RestoreDatabaseRequest databaseId */ + databaseId?: (string|null); + + /** RestoreDatabaseRequest backup */ + backup?: (string|null); + + /** RestoreDatabaseRequest encryptionConfig */ + encryptionConfig?: (google.firestore.admin.v1.Database.IEncryptionConfig|null); + } + + /** Represents a RestoreDatabaseRequest. */ + class RestoreDatabaseRequest implements IRestoreDatabaseRequest { + + /** + * Constructs a new RestoreDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IRestoreDatabaseRequest); + + /** RestoreDatabaseRequest parent. */ + public parent: string; + + /** RestoreDatabaseRequest databaseId. */ + public databaseId: string; + + /** RestoreDatabaseRequest backup. */ + public backup: string; + + /** RestoreDatabaseRequest encryptionConfig. */ + public encryptionConfig?: (google.firestore.admin.v1.Database.IEncryptionConfig|null); + + /** + * Creates a RestoreDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RestoreDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.RestoreDatabaseRequest; + + /** + * Creates a plain object from a RestoreDatabaseRequest message. Also converts values to other types if specified. + * @param message RestoreDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.RestoreDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RestoreDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RestoreDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an IndexOperationMetadata. */ + interface IIndexOperationMetadata { + + /** IndexOperationMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** IndexOperationMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** IndexOperationMetadata index */ + index?: (string|null); + + /** IndexOperationMetadata state */ + state?: (google.firestore.admin.v1.OperationState|null); + + /** IndexOperationMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** IndexOperationMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + } + + /** Represents an IndexOperationMetadata. */ + class IndexOperationMetadata implements IIndexOperationMetadata { + + /** + * Constructs a new IndexOperationMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IIndexOperationMetadata); + + /** IndexOperationMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** IndexOperationMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** IndexOperationMetadata index. */ + public index: string; + + /** IndexOperationMetadata state. */ + public state: google.firestore.admin.v1.OperationState; + + /** IndexOperationMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** IndexOperationMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** + * Creates an IndexOperationMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IndexOperationMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.IndexOperationMetadata; + + /** + * Creates a plain object from an IndexOperationMetadata message. Also converts values to other types if specified. + * @param message IndexOperationMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.IndexOperationMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IndexOperationMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IndexOperationMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldOperationMetadata. */ + interface IFieldOperationMetadata { + + /** FieldOperationMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** FieldOperationMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** FieldOperationMetadata field */ + field?: (string|null); + + /** FieldOperationMetadata indexConfigDeltas */ + indexConfigDeltas?: (google.firestore.admin.v1.FieldOperationMetadata.IIndexConfigDelta[]|null); + + /** FieldOperationMetadata state */ + state?: (google.firestore.admin.v1.OperationState|null); + + /** FieldOperationMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** FieldOperationMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** FieldOperationMetadata ttlConfigDelta */ + ttlConfigDelta?: (google.firestore.admin.v1.FieldOperationMetadata.ITtlConfigDelta|null); + } + + /** Represents a FieldOperationMetadata. */ + class FieldOperationMetadata implements IFieldOperationMetadata { + + /** + * Constructs a new FieldOperationMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IFieldOperationMetadata); + + /** FieldOperationMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** FieldOperationMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** FieldOperationMetadata field. */ + public field: string; + + /** FieldOperationMetadata indexConfigDeltas. */ + public indexConfigDeltas: google.firestore.admin.v1.FieldOperationMetadata.IIndexConfigDelta[]; + + /** FieldOperationMetadata state. */ + public state: google.firestore.admin.v1.OperationState; + + /** FieldOperationMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** FieldOperationMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** FieldOperationMetadata ttlConfigDelta. */ + public ttlConfigDelta?: (google.firestore.admin.v1.FieldOperationMetadata.ITtlConfigDelta|null); + + /** + * Creates a FieldOperationMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOperationMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.FieldOperationMetadata; + + /** + * Creates a plain object from a FieldOperationMetadata message. Also converts values to other types if specified. + * @param message FieldOperationMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.FieldOperationMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldOperationMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldOperationMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldOperationMetadata { + + /** Properties of an IndexConfigDelta. */ + interface IIndexConfigDelta { + + /** IndexConfigDelta changeType */ + changeType?: (google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta.ChangeType|null); + + /** IndexConfigDelta index */ + index?: (google.firestore.admin.v1.IIndex|null); + } + + /** Represents an IndexConfigDelta. */ + class IndexConfigDelta implements IIndexConfigDelta { + + /** + * Constructs a new IndexConfigDelta. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.FieldOperationMetadata.IIndexConfigDelta); + + /** IndexConfigDelta changeType. */ + public changeType: google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta.ChangeType; + + /** IndexConfigDelta index. */ + public index?: (google.firestore.admin.v1.IIndex|null); + + /** + * Creates an IndexConfigDelta message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IndexConfigDelta + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta; + + /** + * Creates a plain object from an IndexConfigDelta message. Also converts values to other types if specified. + * @param message IndexConfigDelta + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IndexConfigDelta to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IndexConfigDelta + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace IndexConfigDelta { + + /** ChangeType enum. */ + type ChangeType = + "CHANGE_TYPE_UNSPECIFIED"| "ADD"| "REMOVE"; + } + + /** Properties of a TtlConfigDelta. */ + interface ITtlConfigDelta { + + /** TtlConfigDelta changeType */ + changeType?: (google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta.ChangeType|null); + } + + /** Represents a TtlConfigDelta. */ + class TtlConfigDelta implements ITtlConfigDelta { + + /** + * Constructs a new TtlConfigDelta. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.FieldOperationMetadata.ITtlConfigDelta); + + /** TtlConfigDelta changeType. */ + public changeType: google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta.ChangeType; + + /** + * Creates a TtlConfigDelta message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TtlConfigDelta + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta; + + /** + * Creates a plain object from a TtlConfigDelta message. Also converts values to other types if specified. + * @param message TtlConfigDelta + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TtlConfigDelta to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TtlConfigDelta + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TtlConfigDelta { + + /** ChangeType enum. */ + type ChangeType = + "CHANGE_TYPE_UNSPECIFIED"| "ADD"| "REMOVE"; + } + } + + /** Properties of an ExportDocumentsMetadata. */ + interface IExportDocumentsMetadata { + + /** ExportDocumentsMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** ExportDocumentsMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** ExportDocumentsMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** ExportDocumentsMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** ExportDocumentsMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** ExportDocumentsMetadata collectionIds */ + collectionIds?: (string[]|null); + + /** ExportDocumentsMetadata outputUriPrefix */ + outputUriPrefix?: (string|null); + + /** ExportDocumentsMetadata namespaceIds */ + namespaceIds?: (string[]|null); + + /** ExportDocumentsMetadata snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an ExportDocumentsMetadata. */ + class ExportDocumentsMetadata implements IExportDocumentsMetadata { + + /** + * Constructs a new ExportDocumentsMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IExportDocumentsMetadata); + + /** ExportDocumentsMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** ExportDocumentsMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** ExportDocumentsMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** ExportDocumentsMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** ExportDocumentsMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** ExportDocumentsMetadata collectionIds. */ + public collectionIds: string[]; + + /** ExportDocumentsMetadata outputUriPrefix. */ + public outputUriPrefix: string; + + /** ExportDocumentsMetadata namespaceIds. */ + public namespaceIds: string[]; + + /** ExportDocumentsMetadata snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates an ExportDocumentsMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExportDocumentsMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ExportDocumentsMetadata; + + /** + * Creates a plain object from an ExportDocumentsMetadata message. Also converts values to other types if specified. + * @param message ExportDocumentsMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ExportDocumentsMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExportDocumentsMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExportDocumentsMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ImportDocumentsMetadata. */ + interface IImportDocumentsMetadata { + + /** ImportDocumentsMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** ImportDocumentsMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** ImportDocumentsMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** ImportDocumentsMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** ImportDocumentsMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** ImportDocumentsMetadata collectionIds */ + collectionIds?: (string[]|null); + + /** ImportDocumentsMetadata inputUriPrefix */ + inputUriPrefix?: (string|null); + + /** ImportDocumentsMetadata namespaceIds */ + namespaceIds?: (string[]|null); + } + + /** Represents an ImportDocumentsMetadata. */ + class ImportDocumentsMetadata implements IImportDocumentsMetadata { + + /** + * Constructs a new ImportDocumentsMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IImportDocumentsMetadata); + + /** ImportDocumentsMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** ImportDocumentsMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** ImportDocumentsMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** ImportDocumentsMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** ImportDocumentsMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** ImportDocumentsMetadata collectionIds. */ + public collectionIds: string[]; + + /** ImportDocumentsMetadata inputUriPrefix. */ + public inputUriPrefix: string; + + /** ImportDocumentsMetadata namespaceIds. */ + public namespaceIds: string[]; + + /** + * Creates an ImportDocumentsMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ImportDocumentsMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ImportDocumentsMetadata; + + /** + * Creates a plain object from an ImportDocumentsMetadata message. Also converts values to other types if specified. + * @param message ImportDocumentsMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ImportDocumentsMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ImportDocumentsMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ImportDocumentsMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BulkDeleteDocumentsMetadata. */ + interface IBulkDeleteDocumentsMetadata { + + /** BulkDeleteDocumentsMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** BulkDeleteDocumentsMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata collectionIds */ + collectionIds?: (string[]|null); + + /** BulkDeleteDocumentsMetadata namespaceIds */ + namespaceIds?: (string[]|null); + + /** BulkDeleteDocumentsMetadata snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BulkDeleteDocumentsMetadata. */ + class BulkDeleteDocumentsMetadata implements IBulkDeleteDocumentsMetadata { + + /** + * Constructs a new BulkDeleteDocumentsMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBulkDeleteDocumentsMetadata); + + /** BulkDeleteDocumentsMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** BulkDeleteDocumentsMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata collectionIds. */ + public collectionIds: string[]; + + /** BulkDeleteDocumentsMetadata namespaceIds. */ + public namespaceIds: string[]; + + /** BulkDeleteDocumentsMetadata snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a BulkDeleteDocumentsMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BulkDeleteDocumentsMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BulkDeleteDocumentsMetadata; + + /** + * Creates a plain object from a BulkDeleteDocumentsMetadata message. Also converts values to other types if specified. + * @param message BulkDeleteDocumentsMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.BulkDeleteDocumentsMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BulkDeleteDocumentsMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BulkDeleteDocumentsMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExportDocumentsResponse. */ + interface IExportDocumentsResponse { + + /** ExportDocumentsResponse outputUriPrefix */ + outputUriPrefix?: (string|null); + } + + /** Represents an ExportDocumentsResponse. */ + class ExportDocumentsResponse implements IExportDocumentsResponse { + + /** + * Constructs a new ExportDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IExportDocumentsResponse); + + /** ExportDocumentsResponse outputUriPrefix. */ + public outputUriPrefix: string; + + /** + * Creates an ExportDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExportDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ExportDocumentsResponse; + + /** + * Creates a plain object from an ExportDocumentsResponse message. Also converts values to other types if specified. + * @param message ExportDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ExportDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExportDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExportDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RestoreDatabaseMetadata. */ + interface IRestoreDatabaseMetadata { + + /** RestoreDatabaseMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** RestoreDatabaseMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** RestoreDatabaseMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** RestoreDatabaseMetadata database */ + database?: (string|null); + + /** RestoreDatabaseMetadata backup */ + backup?: (string|null); + + /** RestoreDatabaseMetadata progressPercentage */ + progressPercentage?: (google.firestore.admin.v1.IProgress|null); + } + + /** Represents a RestoreDatabaseMetadata. */ + class RestoreDatabaseMetadata implements IRestoreDatabaseMetadata { + + /** + * Constructs a new RestoreDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IRestoreDatabaseMetadata); + + /** RestoreDatabaseMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** RestoreDatabaseMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** RestoreDatabaseMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** RestoreDatabaseMetadata database. */ + public database: string; + + /** RestoreDatabaseMetadata backup. */ + public backup: string; + + /** RestoreDatabaseMetadata progressPercentage. */ + public progressPercentage?: (google.firestore.admin.v1.IProgress|null); + + /** + * Creates a RestoreDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RestoreDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.RestoreDatabaseMetadata; + + /** + * Creates a plain object from a RestoreDatabaseMetadata message. Also converts values to other types if specified. + * @param message RestoreDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.RestoreDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RestoreDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RestoreDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Progress. */ + interface IProgress { + + /** Progress estimatedWork */ + estimatedWork?: (number|string|null); + + /** Progress completedWork */ + completedWork?: (number|string|null); + } + + /** Represents a Progress. */ + class Progress implements IProgress { + + /** + * Constructs a new Progress. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IProgress); + + /** Progress estimatedWork. */ + public estimatedWork: (number|string); + + /** Progress completedWork. */ + public completedWork: (number|string); + + /** + * Creates a Progress message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Progress + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Progress; + + /** + * Creates a plain object from a Progress message. Also converts values to other types if specified. + * @param message Progress + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Progress, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Progress to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Progress + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** OperationState enum. */ + type OperationState = + "OPERATION_STATE_UNSPECIFIED"| "INITIALIZING"| "PROCESSING"| "CANCELLING"| "FINALIZING"| "SUCCESSFUL"| "FAILED"| "CANCELLED"; + + /** Properties of a BackupSchedule. */ + interface IBackupSchedule { + + /** BackupSchedule name */ + name?: (string|null); + + /** BackupSchedule createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** BackupSchedule updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** BackupSchedule retention */ + retention?: (google.protobuf.IDuration|null); + + /** BackupSchedule dailyRecurrence */ + dailyRecurrence?: (google.firestore.admin.v1.IDailyRecurrence|null); + + /** BackupSchedule weeklyRecurrence */ + weeklyRecurrence?: (google.firestore.admin.v1.IWeeklyRecurrence|null); + } + + /** Represents a BackupSchedule. */ + class BackupSchedule implements IBackupSchedule { + + /** + * Constructs a new BackupSchedule. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBackupSchedule); + + /** BackupSchedule name. */ + public name: string; + + /** BackupSchedule createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** BackupSchedule updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** BackupSchedule retention. */ + public retention?: (google.protobuf.IDuration|null); + + /** BackupSchedule dailyRecurrence. */ + public dailyRecurrence?: (google.firestore.admin.v1.IDailyRecurrence|null); + + /** BackupSchedule weeklyRecurrence. */ + public weeklyRecurrence?: (google.firestore.admin.v1.IWeeklyRecurrence|null); + + /** BackupSchedule recurrence. */ + public recurrence?: ("dailyRecurrence"|"weeklyRecurrence"); + + /** + * Creates a BackupSchedule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BackupSchedule + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BackupSchedule; + + /** + * Creates a plain object from a BackupSchedule message. Also converts values to other types if specified. + * @param message BackupSchedule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.BackupSchedule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BackupSchedule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BackupSchedule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DailyRecurrence. */ + interface IDailyRecurrence { + } + + /** Represents a DailyRecurrence. */ + class DailyRecurrence implements IDailyRecurrence { + + /** + * Constructs a new DailyRecurrence. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDailyRecurrence); + + /** + * Creates a DailyRecurrence message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DailyRecurrence + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DailyRecurrence; + + /** + * Creates a plain object from a DailyRecurrence message. Also converts values to other types if specified. + * @param message DailyRecurrence + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DailyRecurrence, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DailyRecurrence to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DailyRecurrence + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WeeklyRecurrence. */ + interface IWeeklyRecurrence { + + /** WeeklyRecurrence day */ + day?: (google.type.DayOfWeek|null); + } + + /** Represents a WeeklyRecurrence. */ + class WeeklyRecurrence implements IWeeklyRecurrence { + + /** + * Constructs a new WeeklyRecurrence. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IWeeklyRecurrence); + + /** WeeklyRecurrence day. */ + public day: google.type.DayOfWeek; + + /** + * Creates a WeeklyRecurrence message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WeeklyRecurrence + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.WeeklyRecurrence; + + /** + * Creates a plain object from a WeeklyRecurrence message. Also converts values to other types if specified. + * @param message WeeklyRecurrence + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.WeeklyRecurrence, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WeeklyRecurrence to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WeeklyRecurrence + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a LocationMetadata. */ + interface ILocationMetadata { + } + + /** Represents a LocationMetadata. */ + class LocationMetadata implements ILocationMetadata { + + /** + * Constructs a new LocationMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ILocationMetadata); + + /** + * Creates a LocationMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LocationMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.LocationMetadata; + + /** + * Creates a plain object from a LocationMetadata message. Also converts values to other types if specified. + * @param message LocationMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.LocationMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LocationMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LocationMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + } + + /** Namespace api. */ + namespace api { + + /** FieldBehavior enum. */ + type FieldBehavior = + "FIELD_BEHAVIOR_UNSPECIFIED"| "OPTIONAL"| "REQUIRED"| "OUTPUT_ONLY"| "INPUT_ONLY"| "IMMUTABLE"| "UNORDERED_LIST"| "NON_EMPTY_DEFAULT"| "IDENTIFIER"; + + /** Properties of a ResourceDescriptor. */ + interface IResourceDescriptor { + + /** ResourceDescriptor type */ + type?: (string|null); + + /** ResourceDescriptor pattern */ + pattern?: (string[]|null); + + /** ResourceDescriptor nameField */ + nameField?: (string|null); + + /** ResourceDescriptor history */ + history?: (google.api.ResourceDescriptor.History|null); + + /** ResourceDescriptor plural */ + plural?: (string|null); + + /** ResourceDescriptor singular */ + singular?: (string|null); + + /** ResourceDescriptor style */ + style?: (google.api.ResourceDescriptor.Style[]|null); + } + + /** Represents a ResourceDescriptor. */ + class ResourceDescriptor implements IResourceDescriptor { + + /** + * Constructs a new ResourceDescriptor. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceDescriptor); + + /** ResourceDescriptor type. */ + public type: string; + + /** ResourceDescriptor pattern. */ + public pattern: string[]; + + /** ResourceDescriptor nameField. */ + public nameField: string; + + /** ResourceDescriptor history. */ + public history: google.api.ResourceDescriptor.History; + + /** ResourceDescriptor plural. */ + public plural: string; + + /** ResourceDescriptor singular. */ + public singular: string; + + /** ResourceDescriptor style. */ + public style: google.api.ResourceDescriptor.Style[]; + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceDescriptor + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @param message ResourceDescriptor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceDescriptor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceDescriptor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ResourceDescriptor { + + /** History enum. */ + type History = + "HISTORY_UNSPECIFIED"| "ORIGINALLY_SINGLE_PATTERN"| "FUTURE_MULTI_PATTERN"; + + /** Style enum. */ + type Style = + "STYLE_UNSPECIFIED"| "DECLARATIVE_FRIENDLY"; + } + + /** Properties of a ResourceReference. */ + interface IResourceReference { + + /** ResourceReference type */ + type?: (string|null); + + /** ResourceReference childType */ + childType?: (string|null); + } + + /** Represents a ResourceReference. */ + class ResourceReference implements IResourceReference { + + /** + * Constructs a new ResourceReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceReference); + + /** ResourceReference type. */ + public type: string; + + /** ResourceReference childType. */ + public childType: string; + + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceReference + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; + + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @param message ResourceReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Http. */ + interface IHttp { + + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); + + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); + } + + /** Represents a Http. */ + class Http implements IHttp { + + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); + + /** Http rules. */ + public rules: google.api.IHttpRule[]; + + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Http + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a HttpRule. */ + interface IHttpRule { + + /** HttpRule selector */ + selector?: (string|null); + + /** HttpRule get */ + get?: (string|null); + + /** HttpRule put */ + put?: (string|null); + + /** HttpRule post */ + post?: (string|null); + + /** HttpRule delete */ + "delete"?: (string|null); + + /** HttpRule patch */ + patch?: (string|null); + + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body */ + body?: (string|null); + + /** HttpRule responseBody */ + responseBody?: (string|null); + + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); + } + + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { + + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); + + /** HttpRule selector. */ + public selector: string; + + /** HttpRule get. */ + public get?: (string|null); + + /** HttpRule put. */ + public put?: (string|null); + + /** HttpRule post. */ + public post?: (string|null); + + /** HttpRule delete. */ + public delete?: (string|null); + + /** HttpRule patch. */ + public patch?: (string|null); + + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body. */ + public body: string; + + /** HttpRule responseBody. */ + public responseBody: string; + + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; + + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for HttpRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { + + /** CustomHttpPattern kind */ + kind?: (string|null); + + /** CustomHttpPattern path */ + path?: (string|null); + } + + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { + + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); + + /** CustomHttpPattern kind. */ + public kind: string; + + /** CustomHttpPattern path. */ + public path: string; + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CustomHttpPattern + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommonLanguageSettings. */ + interface ICommonLanguageSettings { + + /** CommonLanguageSettings referenceDocsUri */ + referenceDocsUri?: (string|null); + + /** CommonLanguageSettings destinations */ + destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + } + + /** Represents a CommonLanguageSettings. */ + class CommonLanguageSettings implements ICommonLanguageSettings { + + /** + * Constructs a new CommonLanguageSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICommonLanguageSettings); + + /** CommonLanguageSettings referenceDocsUri. */ + public referenceDocsUri: string; + + /** CommonLanguageSettings destinations. */ + public destinations: google.api.ClientLibraryDestination[]; + + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommonLanguageSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CommonLanguageSettings; + + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @param message CommonLanguageSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CommonLanguageSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommonLanguageSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommonLanguageSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ClientLibrarySettings. */ + interface IClientLibrarySettings { + + /** ClientLibrarySettings version */ + version?: (string|null); + + /** ClientLibrarySettings launchStage */ + launchStage?: (google.api.LaunchStage|null); + + /** ClientLibrarySettings restNumericEnums */ + restNumericEnums?: (boolean|null); + + /** ClientLibrarySettings javaSettings */ + javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings */ + cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings */ + phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings */ + pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings */ + nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings */ + dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings */ + rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings */ + goSettings?: (google.api.IGoSettings|null); + } + + /** Represents a ClientLibrarySettings. */ + class ClientLibrarySettings implements IClientLibrarySettings { + + /** + * Constructs a new ClientLibrarySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IClientLibrarySettings); + + /** ClientLibrarySettings version. */ + public version: string; + + /** ClientLibrarySettings launchStage. */ + public launchStage: google.api.LaunchStage; + + /** ClientLibrarySettings restNumericEnums. */ + public restNumericEnums: boolean; + + /** ClientLibrarySettings javaSettings. */ + public javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings. */ + public cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings. */ + public phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings. */ + public pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings. */ + public nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings. */ + public dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings. */ + public rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings. */ + public goSettings?: (google.api.IGoSettings|null); + + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ClientLibrarySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.ClientLibrarySettings; + + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @param message ClientLibrarySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ClientLibrarySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ClientLibrarySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ClientLibrarySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Publishing. */ + interface IPublishing { + + /** Publishing methodSettings */ + methodSettings?: (google.api.IMethodSettings[]|null); + + /** Publishing newIssueUri */ + newIssueUri?: (string|null); + + /** Publishing documentationUri */ + documentationUri?: (string|null); + + /** Publishing apiShortName */ + apiShortName?: (string|null); + + /** Publishing githubLabel */ + githubLabel?: (string|null); + + /** Publishing codeownerGithubTeams */ + codeownerGithubTeams?: (string[]|null); + + /** Publishing docTagPrefix */ + docTagPrefix?: (string|null); + + /** Publishing organization */ + organization?: (google.api.ClientLibraryOrganization|null); + + /** Publishing librarySettings */ + librarySettings?: (google.api.IClientLibrarySettings[]|null); + + /** Publishing protoReferenceDocumentationUri */ + protoReferenceDocumentationUri?: (string|null); + + /** Publishing restReferenceDocumentationUri */ + restReferenceDocumentationUri?: (string|null); + } + + /** Represents a Publishing. */ + class Publishing implements IPublishing { + + /** + * Constructs a new Publishing. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPublishing); + + /** Publishing methodSettings. */ + public methodSettings: google.api.IMethodSettings[]; + + /** Publishing newIssueUri. */ + public newIssueUri: string; + + /** Publishing documentationUri. */ + public documentationUri: string; + + /** Publishing apiShortName. */ + public apiShortName: string; + + /** Publishing githubLabel. */ + public githubLabel: string; + + /** Publishing codeownerGithubTeams. */ + public codeownerGithubTeams: string[]; + + /** Publishing docTagPrefix. */ + public docTagPrefix: string; + + /** Publishing organization. */ + public organization: google.api.ClientLibraryOrganization; + + /** Publishing librarySettings. */ + public librarySettings: google.api.IClientLibrarySettings[]; + + /** Publishing protoReferenceDocumentationUri. */ + public protoReferenceDocumentationUri: string; + + /** Publishing restReferenceDocumentationUri. */ + public restReferenceDocumentationUri: string; + + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Publishing + */ + public static fromObject(object: { [k: string]: any }): google.api.Publishing; + + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @param message Publishing + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Publishing, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Publishing to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Publishing + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a JavaSettings. */ + interface IJavaSettings { + + /** JavaSettings libraryPackage */ + libraryPackage?: (string|null); + + /** JavaSettings serviceClassNames */ + serviceClassNames?: ({ [k: string]: string }|null); + + /** JavaSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a JavaSettings. */ + class JavaSettings implements IJavaSettings { + + /** + * Constructs a new JavaSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IJavaSettings); + + /** JavaSettings libraryPackage. */ + public libraryPackage: string; + + /** JavaSettings serviceClassNames. */ + public serviceClassNames: { [k: string]: string }; + + /** JavaSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns JavaSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.JavaSettings; + + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @param message JavaSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.JavaSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this JavaSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for JavaSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CppSettings. */ + interface ICppSettings { + + /** CppSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a CppSettings. */ + class CppSettings implements ICppSettings { + + /** + * Constructs a new CppSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICppSettings); + + /** CppSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CppSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CppSettings; + + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @param message CppSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CppSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CppSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CppSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PhpSettings. */ + interface IPhpSettings { + + /** PhpSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a PhpSettings. */ + class PhpSettings implements IPhpSettings { + + /** + * Constructs a new PhpSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPhpSettings); + + /** PhpSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PhpSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PhpSettings; + + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @param message PhpSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PhpSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PhpSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PhpSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PythonSettings. */ + interface IPythonSettings { + + /** PythonSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + } + + /** Represents a PythonSettings. */ + class PythonSettings implements IPythonSettings { + + /** + * Constructs a new PythonSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPythonSettings); + + /** PythonSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PythonSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings; + + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @param message PythonSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PythonSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PythonSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace PythonSettings { + + /** Properties of an ExperimentalFeatures. */ + interface IExperimentalFeatures { + + /** ExperimentalFeatures restAsyncIoEnabled */ + restAsyncIoEnabled?: (boolean|null); + + /** ExperimentalFeatures protobufPythonicTypesEnabled */ + protobufPythonicTypesEnabled?: (boolean|null); + } + + /** Represents an ExperimentalFeatures. */ + class ExperimentalFeatures implements IExperimentalFeatures { + + /** + * Constructs a new ExperimentalFeatures. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.PythonSettings.IExperimentalFeatures); + + /** ExperimentalFeatures restAsyncIoEnabled. */ + public restAsyncIoEnabled: boolean; + + /** ExperimentalFeatures protobufPythonicTypesEnabled. */ + public protobufPythonicTypesEnabled: boolean; + + /** + * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExperimentalFeatures + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. + * @param message ExperimentalFeatures + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings.ExperimentalFeatures, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExperimentalFeatures to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExperimentalFeatures + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a NodeSettings. */ + interface INodeSettings { + + /** NodeSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a NodeSettings. */ + class NodeSettings implements INodeSettings { + + /** + * Constructs a new NodeSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.INodeSettings); + + /** NodeSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NodeSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.NodeSettings; + + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @param message NodeSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.NodeSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NodeSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NodeSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DotnetSettings. */ + interface IDotnetSettings { + + /** DotnetSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + + /** DotnetSettings renamedResources */ + renamedResources?: ({ [k: string]: string }|null); + + /** DotnetSettings ignoredResources */ + ignoredResources?: (string[]|null); + + /** DotnetSettings forcedNamespaceAliases */ + forcedNamespaceAliases?: (string[]|null); + + /** DotnetSettings handwrittenSignatures */ + handwrittenSignatures?: (string[]|null); + } + + /** Represents a DotnetSettings. */ + class DotnetSettings implements IDotnetSettings { + + /** + * Constructs a new DotnetSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IDotnetSettings); + + /** DotnetSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** DotnetSettings renamedResources. */ + public renamedResources: { [k: string]: string }; + + /** DotnetSettings ignoredResources. */ + public ignoredResources: string[]; + + /** DotnetSettings forcedNamespaceAliases. */ + public forcedNamespaceAliases: string[]; + + /** DotnetSettings handwrittenSignatures. */ + public handwrittenSignatures: string[]; + + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DotnetSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.DotnetSettings; + + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @param message DotnetSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.DotnetSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DotnetSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DotnetSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RubySettings. */ + interface IRubySettings { + + /** RubySettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a RubySettings. */ + class RubySettings implements IRubySettings { + + /** + * Constructs a new RubySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRubySettings); + + /** RubySettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RubySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.RubySettings; + + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @param message RubySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RubySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RubySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RubySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GoSettings. */ + interface IGoSettings { + + /** GoSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + } + + /** Represents a GoSettings. */ + class GoSettings implements IGoSettings { + + /** + * Constructs a new GoSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IGoSettings); + + /** GoSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GoSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.GoSettings; + + /** + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @param message GoSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.GoSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GoSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GoSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodSettings. */ + interface IMethodSettings { + + /** MethodSettings selector */ + selector?: (string|null); + + /** MethodSettings longRunning */ + longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields */ + autoPopulatedFields?: (string[]|null); + } + + /** Represents a MethodSettings. */ + class MethodSettings implements IMethodSettings { + + /** + * Constructs a new MethodSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IMethodSettings); + + /** MethodSettings selector. */ + public selector: string; + + /** MethodSettings longRunning. */ + public longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields. */ + public autoPopulatedFields: string[]; + + /** + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings; + + /** + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @param message MethodSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodSettings { + + /** Properties of a LongRunning. */ + interface ILongRunning { + + /** LongRunning initialPollDelay */ + initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier */ + pollDelayMultiplier?: (number|null); + + /** LongRunning maxPollDelay */ + maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout */ + totalPollTimeout?: (google.protobuf.IDuration|null); + } + + /** Represents a LongRunning. */ + class LongRunning implements ILongRunning { + + /** + * Constructs a new LongRunning. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.MethodSettings.ILongRunning); + + /** LongRunning initialPollDelay. */ + public initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier. */ + public pollDelayMultiplier: number; + + /** LongRunning maxPollDelay. */ + public maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout. */ + public totalPollTimeout?: (google.protobuf.IDuration|null); + + /** + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LongRunning + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings.LongRunning; + + /** + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @param message LongRunning + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings.LongRunning, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LongRunning to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LongRunning + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** ClientLibraryOrganization enum. */ + type ClientLibraryOrganization = + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"| "CLOUD"| "ADS"| "PHOTOS"| "STREET_VIEW"| "SHOPPING"| "GEO"| "GENERATIVE_AI"; + + /** ClientLibraryDestination enum. */ + type ClientLibraryDestination = + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"| "GITHUB"| "PACKAGE_MANAGER"; + + /** Properties of a SelectiveGapicGeneration. */ + interface ISelectiveGapicGeneration { + + /** SelectiveGapicGeneration methods */ + methods?: (string[]|null); + + /** SelectiveGapicGeneration generateOmittedAsInternal */ + generateOmittedAsInternal?: (boolean|null); + } + + /** Represents a SelectiveGapicGeneration. */ + class SelectiveGapicGeneration implements ISelectiveGapicGeneration { + + /** + * Constructs a new SelectiveGapicGeneration. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ISelectiveGapicGeneration); + + /** SelectiveGapicGeneration methods. */ + public methods: string[]; + + /** SelectiveGapicGeneration generateOmittedAsInternal. */ + public generateOmittedAsInternal: boolean; + + /** + * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SelectiveGapicGeneration + */ + public static fromObject(object: { [k: string]: any }): google.api.SelectiveGapicGeneration; + + /** + * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. + * @param message SelectiveGapicGeneration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.SelectiveGapicGeneration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SelectiveGapicGeneration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SelectiveGapicGeneration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** LaunchStage enum. */ + type LaunchStage = + "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; + } + + /** Namespace protobuf. */ + namespace protobuf { + + /** Properties of a FileDescriptorSet. */ + interface IFileDescriptorSet { + + /** FileDescriptorSet file */ + file?: (google.protobuf.IFileDescriptorProto[]|null); + } + + /** Represents a FileDescriptorSet. */ + class FileDescriptorSet implements IFileDescriptorSet { + + /** + * Constructs a new FileDescriptorSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorSet); + + /** FileDescriptorSet file. */ + public file: google.protobuf.IFileDescriptorProto[]; + + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; + + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @param message FileDescriptorSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Edition enum. */ + type Edition = + "EDITION_UNKNOWN"| "EDITION_PROTO2"| "EDITION_PROTO3"| "EDITION_2023"| "EDITION_2024"| "EDITION_1_TEST_ONLY"| "EDITION_2_TEST_ONLY"| "EDITION_99997_TEST_ONLY"| "EDITION_99998_TEST_ONLY"| "EDITION_99999_TEST_ONLY"| "EDITION_MAX"; + + /** Properties of a FileDescriptorProto. */ + interface IFileDescriptorProto { + + /** FileDescriptorProto name */ + name?: (string|null); + + /** FileDescriptorProto package */ + "package"?: (string|null); + + /** FileDescriptorProto dependency */ + dependency?: (string[]|null); + + /** FileDescriptorProto publicDependency */ + publicDependency?: (number[]|null); + + /** FileDescriptorProto weakDependency */ + weakDependency?: (number[]|null); + + /** FileDescriptorProto messageType */ + messageType?: (google.protobuf.IDescriptorProto[]|null); + + /** FileDescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** FileDescriptorProto service */ + service?: (google.protobuf.IServiceDescriptorProto[]|null); + + /** FileDescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** FileDescriptorProto options */ + options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo */ + sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax */ + syntax?: (string|null); + + /** FileDescriptorProto edition */ + edition?: (google.protobuf.Edition|null); + } + + /** Represents a FileDescriptorProto. */ + class FileDescriptorProto implements IFileDescriptorProto { + + /** + * Constructs a new FileDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorProto); + + /** FileDescriptorProto name. */ + public name: string; + + /** FileDescriptorProto package. */ + public package: string; + + /** FileDescriptorProto dependency. */ + public dependency: string[]; + + /** FileDescriptorProto publicDependency. */ + public publicDependency: number[]; + + /** FileDescriptorProto weakDependency. */ + public weakDependency: number[]; + + /** FileDescriptorProto messageType. */ + public messageType: google.protobuf.IDescriptorProto[]; + + /** FileDescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** FileDescriptorProto service. */ + public service: google.protobuf.IServiceDescriptorProto[]; + + /** FileDescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** FileDescriptorProto options. */ + public options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo. */ + public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax. */ + public syntax: string; + + /** FileDescriptorProto edition. */ + public edition: google.protobuf.Edition; + + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; + + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @param message FileDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DescriptorProto. */ + interface IDescriptorProto { + + /** DescriptorProto name */ + name?: (string|null); + + /** DescriptorProto field */ + field?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto nestedType */ + nestedType?: (google.protobuf.IDescriptorProto[]|null); + + /** DescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** DescriptorProto extensionRange */ + extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); + + /** DescriptorProto oneofDecl */ + oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); + + /** DescriptorProto options */ + options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange */ + reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); + + /** DescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents a DescriptorProto. */ + class DescriptorProto implements IDescriptorProto { + + /** + * Constructs a new DescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDescriptorProto); + + /** DescriptorProto name. */ + public name: string; + + /** DescriptorProto field. */ + public field: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto nestedType. */ + public nestedType: google.protobuf.IDescriptorProto[]; + + /** DescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** DescriptorProto extensionRange. */ + public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; + + /** DescriptorProto oneofDecl. */ + public oneofDecl: google.protobuf.IOneofDescriptorProto[]; + + /** DescriptorProto options. */ + public options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange. */ + public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; + + /** DescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; + + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @param message DescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DescriptorProto { + + /** Properties of an ExtensionRange. */ + interface IExtensionRange { + + /** ExtensionRange start */ + start?: (number|null); + + /** ExtensionRange end */ + end?: (number|null); + + /** ExtensionRange options */ + options?: (google.protobuf.IExtensionRangeOptions|null); + } + + /** Represents an ExtensionRange. */ + class ExtensionRange implements IExtensionRange { + + /** + * Constructs a new ExtensionRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); + + /** ExtensionRange start. */ + public start: number; + + /** ExtensionRange end. */ + public end: number; + + /** ExtensionRange options. */ + public options?: (google.protobuf.IExtensionRangeOptions|null); + + /** + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @param message ExtensionRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReservedRange. */ + interface IReservedRange { + + /** ReservedRange start */ + start?: (number|null); + + /** ReservedRange end */ + end?: (number|null); + } + + /** Represents a ReservedRange. */ + class ReservedRange implements IReservedRange { + + /** + * Constructs a new ReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); + + /** ReservedRange start. */ + public start: number; + + /** ReservedRange end. */ + public end: number; + + /** + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @param message ReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an ExtensionRangeOptions. */ + interface IExtensionRangeOptions { + + /** ExtensionRangeOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ExtensionRangeOptions declaration */ + declaration?: (google.protobuf.ExtensionRangeOptions.IDeclaration[]|null); + + /** ExtensionRangeOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification */ + verification?: (google.protobuf.ExtensionRangeOptions.VerificationState|null); + } + + /** Represents an ExtensionRangeOptions. */ + class ExtensionRangeOptions implements IExtensionRangeOptions { + + /** + * Constructs a new ExtensionRangeOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IExtensionRangeOptions); + + /** ExtensionRangeOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** ExtensionRangeOptions declaration. */ + public declaration: google.protobuf.ExtensionRangeOptions.IDeclaration[]; + + /** ExtensionRangeOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification. */ + public verification: google.protobuf.ExtensionRangeOptions.VerificationState; + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRangeOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @param message ExtensionRangeOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRangeOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ExtensionRangeOptions { + + /** Properties of a Declaration. */ + interface IDeclaration { + + /** Declaration number */ + number?: (number|null); + + /** Declaration fullName */ + fullName?: (string|null); + + /** Declaration type */ + type?: (string|null); + + /** Declaration reserved */ + reserved?: (boolean|null); + + /** Declaration repeated */ + repeated?: (boolean|null); + } + + /** Represents a Declaration. */ + class Declaration implements IDeclaration { + + /** + * Constructs a new Declaration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ExtensionRangeOptions.IDeclaration); + + /** Declaration number. */ + public number: number; + + /** Declaration fullName. */ + public fullName: string; + + /** Declaration type. */ + public type: string; + + /** Declaration reserved. */ + public reserved: boolean; + + /** Declaration repeated. */ + public repeated: boolean; + + /** + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Declaration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions.Declaration; + + /** + * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * @param message Declaration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions.Declaration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Declaration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Declaration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** VerificationState enum. */ + type VerificationState = + "DECLARATION"| "UNVERIFIED"; + } + + /** Properties of a FieldDescriptorProto. */ + interface IFieldDescriptorProto { + + /** FieldDescriptorProto name */ + name?: (string|null); + + /** FieldDescriptorProto number */ + number?: (number|null); + + /** FieldDescriptorProto label */ + label?: (google.protobuf.FieldDescriptorProto.Label|null); + + /** FieldDescriptorProto type */ + type?: (google.protobuf.FieldDescriptorProto.Type|null); + + /** FieldDescriptorProto typeName */ + typeName?: (string|null); + + /** FieldDescriptorProto extendee */ + extendee?: (string|null); + + /** FieldDescriptorProto defaultValue */ + defaultValue?: (string|null); + + /** FieldDescriptorProto oneofIndex */ + oneofIndex?: (number|null); + + /** FieldDescriptorProto jsonName */ + jsonName?: (string|null); + + /** FieldDescriptorProto options */ + options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional */ + proto3Optional?: (boolean|null); + } + + /** Represents a FieldDescriptorProto. */ + class FieldDescriptorProto implements IFieldDescriptorProto { + + /** + * Constructs a new FieldDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldDescriptorProto); + + /** FieldDescriptorProto name. */ + public name: string; + + /** FieldDescriptorProto number. */ + public number: number; + + /** FieldDescriptorProto label. */ + public label: google.protobuf.FieldDescriptorProto.Label; + + /** FieldDescriptorProto type. */ + public type: google.protobuf.FieldDescriptorProto.Type; + + /** FieldDescriptorProto typeName. */ + public typeName: string; + + /** FieldDescriptorProto extendee. */ + public extendee: string; + + /** FieldDescriptorProto defaultValue. */ + public defaultValue: string; + + /** FieldDescriptorProto oneofIndex. */ + public oneofIndex: number; + + /** FieldDescriptorProto jsonName. */ + public jsonName: string; + + /** FieldDescriptorProto options. */ + public options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional. */ + public proto3Optional: boolean; + + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @param message FieldDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldDescriptorProto { + + /** Type enum. */ + type Type = + "TYPE_DOUBLE"| "TYPE_FLOAT"| "TYPE_INT64"| "TYPE_UINT64"| "TYPE_INT32"| "TYPE_FIXED64"| "TYPE_FIXED32"| "TYPE_BOOL"| "TYPE_STRING"| "TYPE_GROUP"| "TYPE_MESSAGE"| "TYPE_BYTES"| "TYPE_UINT32"| "TYPE_ENUM"| "TYPE_SFIXED32"| "TYPE_SFIXED64"| "TYPE_SINT32"| "TYPE_SINT64"; + + /** Label enum. */ + type Label = + "LABEL_OPTIONAL"| "LABEL_REPEATED"| "LABEL_REQUIRED"; + } + + /** Properties of an OneofDescriptorProto. */ + interface IOneofDescriptorProto { + + /** OneofDescriptorProto name */ + name?: (string|null); + + /** OneofDescriptorProto options */ + options?: (google.protobuf.IOneofOptions|null); + } + + /** Represents an OneofDescriptorProto. */ + class OneofDescriptorProto implements IOneofDescriptorProto { + + /** + * Constructs a new OneofDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofDescriptorProto); + + /** OneofDescriptorProto name. */ + public name: string; + + /** OneofDescriptorProto options. */ + public options?: (google.protobuf.IOneofOptions|null); + + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; + + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @param message OneofDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumDescriptorProto. */ + interface IEnumDescriptorProto { + + /** EnumDescriptorProto name */ + name?: (string|null); + + /** EnumDescriptorProto value */ + value?: (google.protobuf.IEnumValueDescriptorProto[]|null); + + /** EnumDescriptorProto options */ + options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange */ + reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); + + /** EnumDescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents an EnumDescriptorProto. */ + class EnumDescriptorProto implements IEnumDescriptorProto { + + /** + * Constructs a new EnumDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumDescriptorProto); + + /** EnumDescriptorProto name. */ + public name: string; + + /** EnumDescriptorProto value. */ + public value: google.protobuf.IEnumValueDescriptorProto[]; + + /** EnumDescriptorProto options. */ + public options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange. */ + public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; + + /** EnumDescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; + + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @param message EnumDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace EnumDescriptorProto { + + /** Properties of an EnumReservedRange. */ + interface IEnumReservedRange { + + /** EnumReservedRange start */ + start?: (number|null); + + /** EnumReservedRange end */ + end?: (number|null); + } + + /** Represents an EnumReservedRange. */ + class EnumReservedRange implements IEnumReservedRange { + + /** + * Constructs a new EnumReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); + + /** EnumReservedRange start. */ + public start: number; + + /** EnumReservedRange end. */ + public end: number; + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @param message EnumReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an EnumValueDescriptorProto. */ + interface IEnumValueDescriptorProto { + + /** EnumValueDescriptorProto name */ + name?: (string|null); + + /** EnumValueDescriptorProto number */ + number?: (number|null); + + /** EnumValueDescriptorProto options */ + options?: (google.protobuf.IEnumValueOptions|null); + } + + /** Represents an EnumValueDescriptorProto. */ + class EnumValueDescriptorProto implements IEnumValueDescriptorProto { + + /** + * Constructs a new EnumValueDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueDescriptorProto); + + /** EnumValueDescriptorProto name. */ + public name: string; + + /** EnumValueDescriptorProto number. */ + public number: number; + + /** EnumValueDescriptorProto options. */ + public options?: (google.protobuf.IEnumValueOptions|null); + + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; + + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @param message EnumValueDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceDescriptorProto. */ + interface IServiceDescriptorProto { + + /** ServiceDescriptorProto name */ + name?: (string|null); + + /** ServiceDescriptorProto method */ + method?: (google.protobuf.IMethodDescriptorProto[]|null); + + /** ServiceDescriptorProto options */ + options?: (google.protobuf.IServiceOptions|null); + } + + /** Represents a ServiceDescriptorProto. */ + class ServiceDescriptorProto implements IServiceDescriptorProto { + + /** + * Constructs a new ServiceDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceDescriptorProto); + + /** ServiceDescriptorProto name. */ + public name: string; + + /** ServiceDescriptorProto method. */ + public method: google.protobuf.IMethodDescriptorProto[]; + + /** ServiceDescriptorProto options. */ + public options?: (google.protobuf.IServiceOptions|null); + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @param message ServiceDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodDescriptorProto. */ + interface IMethodDescriptorProto { + + /** MethodDescriptorProto name */ + name?: (string|null); + + /** MethodDescriptorProto inputType */ + inputType?: (string|null); + + /** MethodDescriptorProto outputType */ + outputType?: (string|null); + + /** MethodDescriptorProto options */ + options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming */ + clientStreaming?: (boolean|null); + + /** MethodDescriptorProto serverStreaming */ + serverStreaming?: (boolean|null); + } + + /** Represents a MethodDescriptorProto. */ + class MethodDescriptorProto implements IMethodDescriptorProto { + + /** + * Constructs a new MethodDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodDescriptorProto); + + /** MethodDescriptorProto name. */ + public name: string; + + /** MethodDescriptorProto inputType. */ + public inputType: string; + + /** MethodDescriptorProto outputType. */ + public outputType: string; + + /** MethodDescriptorProto options. */ + public options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming. */ + public clientStreaming: boolean; + + /** MethodDescriptorProto serverStreaming. */ + public serverStreaming: boolean; + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @param message MethodDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FileOptions. */ + interface IFileOptions { + + /** FileOptions javaPackage */ + javaPackage?: (string|null); + + /** FileOptions javaOuterClassname */ + javaOuterClassname?: (string|null); + + /** FileOptions javaMultipleFiles */ + javaMultipleFiles?: (boolean|null); + + /** FileOptions javaGenerateEqualsAndHash */ + javaGenerateEqualsAndHash?: (boolean|null); + + /** FileOptions javaStringCheckUtf8 */ + javaStringCheckUtf8?: (boolean|null); + + /** FileOptions optimizeFor */ + optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); + + /** FileOptions goPackage */ + goPackage?: (string|null); + + /** FileOptions ccGenericServices */ + ccGenericServices?: (boolean|null); + + /** FileOptions javaGenericServices */ + javaGenericServices?: (boolean|null); + + /** FileOptions pyGenericServices */ + pyGenericServices?: (boolean|null); + + /** FileOptions deprecated */ + deprecated?: (boolean|null); + + /** FileOptions ccEnableArenas */ + ccEnableArenas?: (boolean|null); + + /** FileOptions objcClassPrefix */ + objcClassPrefix?: (string|null); + + /** FileOptions csharpNamespace */ + csharpNamespace?: (string|null); + + /** FileOptions swiftPrefix */ + swiftPrefix?: (string|null); + + /** FileOptions phpClassPrefix */ + phpClassPrefix?: (string|null); + + /** FileOptions phpNamespace */ + phpNamespace?: (string|null); + + /** FileOptions phpMetadataNamespace */ + phpMetadataNamespace?: (string|null); + + /** FileOptions rubyPackage */ + rubyPackage?: (string|null); + + /** FileOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FileOptions .google.api.resourceDefinition */ + ".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null); + } + + /** Represents a FileOptions. */ + class FileOptions implements IFileOptions { + + /** + * Constructs a new FileOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileOptions); + + /** FileOptions javaPackage. */ + public javaPackage: string; + + /** FileOptions javaOuterClassname. */ + public javaOuterClassname: string; + + /** FileOptions javaMultipleFiles. */ + public javaMultipleFiles: boolean; + + /** FileOptions javaGenerateEqualsAndHash. */ + public javaGenerateEqualsAndHash: boolean; + + /** FileOptions javaStringCheckUtf8. */ + public javaStringCheckUtf8: boolean; + + /** FileOptions optimizeFor. */ + public optimizeFor: google.protobuf.FileOptions.OptimizeMode; + + /** FileOptions goPackage. */ + public goPackage: string; + + /** FileOptions ccGenericServices. */ + public ccGenericServices: boolean; + + /** FileOptions javaGenericServices. */ + public javaGenericServices: boolean; + + /** FileOptions pyGenericServices. */ + public pyGenericServices: boolean; + + /** FileOptions deprecated. */ + public deprecated: boolean; + + /** FileOptions ccEnableArenas. */ + public ccEnableArenas: boolean; + + /** FileOptions objcClassPrefix. */ + public objcClassPrefix: string; + + /** FileOptions csharpNamespace. */ + public csharpNamespace: string; + + /** FileOptions swiftPrefix. */ + public swiftPrefix: string; + + /** FileOptions phpClassPrefix. */ + public phpClassPrefix: string; + + /** FileOptions phpNamespace. */ + public phpNamespace: string; + + /** FileOptions phpMetadataNamespace. */ + public phpMetadataNamespace: string; + + /** FileOptions rubyPackage. */ + public rubyPackage: string; + + /** FileOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; + + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @param message FileOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FileOptions { + + /** OptimizeMode enum. */ + type OptimizeMode = + "SPEED"| "CODE_SIZE"| "LITE_RUNTIME"; + } + + /** Properties of a MessageOptions. */ + interface IMessageOptions { + + /** MessageOptions messageSetWireFormat */ + messageSetWireFormat?: (boolean|null); + + /** MessageOptions noStandardDescriptorAccessor */ + noStandardDescriptorAccessor?: (boolean|null); + + /** MessageOptions deprecated */ + deprecated?: (boolean|null); + + /** MessageOptions mapEntry */ + mapEntry?: (boolean|null); + + /** MessageOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** MessageOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MessageOptions .google.api.resource */ + ".google.api.resource"?: (google.api.IResourceDescriptor|null); + } + + /** Represents a MessageOptions. */ + class MessageOptions implements IMessageOptions { + + /** + * Constructs a new MessageOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMessageOptions); + + /** MessageOptions messageSetWireFormat. */ + public messageSetWireFormat: boolean; + + /** MessageOptions noStandardDescriptorAccessor. */ + public noStandardDescriptorAccessor: boolean; + + /** MessageOptions deprecated. */ + public deprecated: boolean; + + /** MessageOptions mapEntry. */ + public mapEntry: boolean; + + /** MessageOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** MessageOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MessageOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; + + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @param message MessageOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MessageOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MessageOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldOptions. */ + interface IFieldOptions { + + /** FieldOptions ctype */ + ctype?: (google.protobuf.FieldOptions.CType|null); + + /** FieldOptions packed */ + packed?: (boolean|null); + + /** FieldOptions jstype */ + jstype?: (google.protobuf.FieldOptions.JSType|null); + + /** FieldOptions lazy */ + lazy?: (boolean|null); + + /** FieldOptions unverifiedLazy */ + unverifiedLazy?: (boolean|null); + + /** FieldOptions deprecated */ + deprecated?: (boolean|null); + + /** FieldOptions weak */ + weak?: (boolean|null); + + /** FieldOptions debugRedact */ + debugRedact?: (boolean|null); + + /** FieldOptions retention */ + retention?: (google.protobuf.FieldOptions.OptionRetention|null); + + /** FieldOptions targets */ + targets?: (google.protobuf.FieldOptions.OptionTargetType[]|null); + + /** FieldOptions editionDefaults */ + editionDefaults?: (google.protobuf.FieldOptions.IEditionDefault[]|null); + + /** FieldOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FieldOptions .google.api.fieldBehavior */ + ".google.api.fieldBehavior"?: (google.api.FieldBehavior[]|null); + + /** FieldOptions .google.api.resourceReference */ + ".google.api.resourceReference"?: (google.api.IResourceReference|null); + } + + /** Represents a FieldOptions. */ + class FieldOptions implements IFieldOptions { + + /** + * Constructs a new FieldOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldOptions); + + /** FieldOptions ctype. */ + public ctype: google.protobuf.FieldOptions.CType; + + /** FieldOptions packed. */ + public packed: boolean; + + /** FieldOptions jstype. */ + public jstype: google.protobuf.FieldOptions.JSType; + + /** FieldOptions lazy. */ + public lazy: boolean; + + /** FieldOptions unverifiedLazy. */ + public unverifiedLazy: boolean; + + /** FieldOptions deprecated. */ + public deprecated: boolean; + + /** FieldOptions weak. */ + public weak: boolean; + + /** FieldOptions debugRedact. */ + public debugRedact: boolean; + + /** FieldOptions retention. */ + public retention: google.protobuf.FieldOptions.OptionRetention; + + /** FieldOptions targets. */ + public targets: google.protobuf.FieldOptions.OptionTargetType[]; + + /** FieldOptions editionDefaults. */ + public editionDefaults: google.protobuf.FieldOptions.IEditionDefault[]; + + /** FieldOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; + + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @param message FieldOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldOptions { + + /** CType enum. */ + type CType = + "STRING"| "CORD"| "STRING_PIECE"; + + /** JSType enum. */ + type JSType = + "JS_NORMAL"| "JS_STRING"| "JS_NUMBER"; + + /** OptionRetention enum. */ + type OptionRetention = + "RETENTION_UNKNOWN"| "RETENTION_RUNTIME"| "RETENTION_SOURCE"; + + /** OptionTargetType enum. */ + type OptionTargetType = + "TARGET_TYPE_UNKNOWN"| "TARGET_TYPE_FILE"| "TARGET_TYPE_EXTENSION_RANGE"| "TARGET_TYPE_MESSAGE"| "TARGET_TYPE_FIELD"| "TARGET_TYPE_ONEOF"| "TARGET_TYPE_ENUM"| "TARGET_TYPE_ENUM_ENTRY"| "TARGET_TYPE_SERVICE"| "TARGET_TYPE_METHOD"; + + /** Properties of an EditionDefault. */ + interface IEditionDefault { + + /** EditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** EditionDefault value */ + value?: (string|null); + } + + /** Represents an EditionDefault. */ + class EditionDefault implements IEditionDefault { + + /** + * Constructs a new EditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FieldOptions.IEditionDefault); + + /** EditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** EditionDefault value. */ + public value: string; + + /** + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.EditionDefault; + + /** + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * @param message EditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions.EditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an OneofOptions. */ + interface IOneofOptions { + + /** OneofOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an OneofOptions. */ + class OneofOptions implements IOneofOptions { + + /** + * Constructs a new OneofOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofOptions); + + /** OneofOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @param message OneofOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumOptions. */ + interface IEnumOptions { + + /** EnumOptions allowAlias */ + allowAlias?: (boolean|null); + + /** EnumOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** EnumOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumOptions. */ + class EnumOptions implements IEnumOptions { + + /** + * Constructs a new EnumOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumOptions); + + /** EnumOptions allowAlias. */ + public allowAlias: boolean; + + /** EnumOptions deprecated. */ + public deprecated: boolean; + + /** EnumOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** EnumOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @param message EnumOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumValueOptions. */ + interface IEnumValueOptions { + + /** EnumValueOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumValueOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact */ + debugRedact?: (boolean|null); + + /** EnumValueOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumValueOptions. */ + class EnumValueOptions implements IEnumValueOptions { + + /** + * Constructs a new EnumValueOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueOptions); + + /** EnumValueOptions deprecated. */ + public deprecated: boolean; + + /** EnumValueOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact. */ + public debugRedact: boolean; + + /** EnumValueOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; + + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @param message EnumValueOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceOptions. */ + interface IServiceOptions { + + /** ServiceOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated */ + deprecated?: (boolean|null); + + /** ServiceOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ServiceOptions .google.api.defaultHost */ + ".google.api.defaultHost"?: (string|null); + + /** ServiceOptions .google.api.oauthScopes */ + ".google.api.oauthScopes"?: (string|null); + + /** ServiceOptions .google.api.apiVersion */ + ".google.api.apiVersion"?: (string|null); + } + + /** Represents a ServiceOptions. */ + class ServiceOptions implements IServiceOptions { + + /** + * Constructs a new ServiceOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceOptions); + + /** ServiceOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated. */ + public deprecated: boolean; + + /** ServiceOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @param message ServiceOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodOptions. */ + interface IMethodOptions { + + /** MethodOptions deprecated */ + deprecated?: (boolean|null); + + /** MethodOptions idempotencyLevel */ + idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); + + /** MethodOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MethodOptions .google.api.http */ + ".google.api.http"?: (google.api.IHttpRule|null); + + /** MethodOptions .google.api.methodSignature */ + ".google.api.methodSignature"?: (string[]|null); + + /** MethodOptions .google.longrunning.operationInfo */ + ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); + } + + /** Represents a MethodOptions. */ + class MethodOptions implements IMethodOptions { + + /** + * Constructs a new MethodOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodOptions); + + /** MethodOptions deprecated. */ + public deprecated: boolean; + + /** MethodOptions idempotencyLevel. */ + public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; + + /** MethodOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; + + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @param message MethodOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodOptions { + + /** IdempotencyLevel enum. */ + type IdempotencyLevel = + "IDEMPOTENCY_UNKNOWN"| "NO_SIDE_EFFECTS"| "IDEMPOTENT"; + } + + /** Properties of an UninterpretedOption. */ + interface IUninterpretedOption { + + /** UninterpretedOption name */ + name?: (google.protobuf.UninterpretedOption.INamePart[]|null); + + /** UninterpretedOption identifierValue */ + identifierValue?: (string|null); + + /** UninterpretedOption positiveIntValue */ + positiveIntValue?: (number|string|null); + + /** UninterpretedOption negativeIntValue */ + negativeIntValue?: (number|string|null); + + /** UninterpretedOption doubleValue */ + doubleValue?: (number|null); + + /** UninterpretedOption stringValue */ + stringValue?: (Uint8Array|null); + + /** UninterpretedOption aggregateValue */ + aggregateValue?: (string|null); + } + + /** Represents an UninterpretedOption. */ + class UninterpretedOption implements IUninterpretedOption { + + /** + * Constructs a new UninterpretedOption. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUninterpretedOption); + + /** UninterpretedOption name. */ + public name: google.protobuf.UninterpretedOption.INamePart[]; + + /** UninterpretedOption identifierValue. */ + public identifierValue: string; + + /** UninterpretedOption positiveIntValue. */ + public positiveIntValue: (number|string); + + /** UninterpretedOption negativeIntValue. */ + public negativeIntValue: (number|string); + + /** UninterpretedOption doubleValue. */ + public doubleValue: number; + + /** UninterpretedOption stringValue. */ + public stringValue: Uint8Array; + + /** UninterpretedOption aggregateValue. */ + public aggregateValue: string; + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UninterpretedOption + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @param message UninterpretedOption + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UninterpretedOption to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UninterpretedOption + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UninterpretedOption { + + /** Properties of a NamePart. */ + interface INamePart { + + /** NamePart namePart */ + namePart: string; + + /** NamePart isExtension */ + isExtension: boolean; + } + + /** Represents a NamePart. */ + class NamePart implements INamePart { + + /** + * Constructs a new NamePart. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.UninterpretedOption.INamePart); + + /** NamePart namePart. */ + public namePart: string; + + /** NamePart isExtension. */ + public isExtension: boolean; + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamePart + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @param message NamePart + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamePart to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NamePart + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a FeatureSet. */ + interface IFeatureSet { + + /** FeatureSet fieldPresence */ + fieldPresence?: (google.protobuf.FeatureSet.FieldPresence|null); + + /** FeatureSet enumType */ + enumType?: (google.protobuf.FeatureSet.EnumType|null); + + /** FeatureSet repeatedFieldEncoding */ + repeatedFieldEncoding?: (google.protobuf.FeatureSet.RepeatedFieldEncoding|null); + + /** FeatureSet utf8Validation */ + utf8Validation?: (google.protobuf.FeatureSet.Utf8Validation|null); + + /** FeatureSet messageEncoding */ + messageEncoding?: (google.protobuf.FeatureSet.MessageEncoding|null); + + /** FeatureSet jsonFormat */ + jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|null); + } + + /** Represents a FeatureSet. */ + class FeatureSet implements IFeatureSet { + + /** + * Constructs a new FeatureSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSet); + + /** FeatureSet fieldPresence. */ + public fieldPresence: google.protobuf.FeatureSet.FieldPresence; + + /** FeatureSet enumType. */ + public enumType: google.protobuf.FeatureSet.EnumType; + + /** FeatureSet repeatedFieldEncoding. */ + public repeatedFieldEncoding: google.protobuf.FeatureSet.RepeatedFieldEncoding; + + /** FeatureSet utf8Validation. */ + public utf8Validation: google.protobuf.FeatureSet.Utf8Validation; + + /** FeatureSet messageEncoding. */ + public messageEncoding: google.protobuf.FeatureSet.MessageEncoding; + + /** FeatureSet jsonFormat. */ + public jsonFormat: google.protobuf.FeatureSet.JsonFormat; + + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet; + + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @param message FeatureSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSet { + + /** FieldPresence enum. */ + type FieldPresence = + "FIELD_PRESENCE_UNKNOWN"| "EXPLICIT"| "IMPLICIT"| "LEGACY_REQUIRED"; + + /** EnumType enum. */ + type EnumType = + "ENUM_TYPE_UNKNOWN"| "OPEN"| "CLOSED"; + + /** RepeatedFieldEncoding enum. */ + type RepeatedFieldEncoding = + "REPEATED_FIELD_ENCODING_UNKNOWN"| "PACKED"| "EXPANDED"; + + /** Utf8Validation enum. */ + type Utf8Validation = + "UTF8_VALIDATION_UNKNOWN"| "VERIFY"| "NONE"; + + /** MessageEncoding enum. */ + type MessageEncoding = + "MESSAGE_ENCODING_UNKNOWN"| "LENGTH_PREFIXED"| "DELIMITED"; + + /** JsonFormat enum. */ + type JsonFormat = + "JSON_FORMAT_UNKNOWN"| "ALLOW"| "LEGACY_BEST_EFFORT"; + } + + /** Properties of a FeatureSetDefaults. */ + interface IFeatureSetDefaults { + + /** FeatureSetDefaults defaults */ + defaults?: (google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]|null); + + /** FeatureSetDefaults minimumEdition */ + minimumEdition?: (google.protobuf.Edition|null); + + /** FeatureSetDefaults maximumEdition */ + maximumEdition?: (google.protobuf.Edition|null); + } + + /** Represents a FeatureSetDefaults. */ + class FeatureSetDefaults implements IFeatureSetDefaults { + + /** + * Constructs a new FeatureSetDefaults. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSetDefaults); + + /** FeatureSetDefaults defaults. */ + public defaults: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]; + + /** FeatureSetDefaults minimumEdition. */ + public minimumEdition: google.protobuf.Edition; + + /** FeatureSetDefaults maximumEdition. */ + public maximumEdition: google.protobuf.Edition; + + /** + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetDefaults + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults; + + /** + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @param message FeatureSetDefaults + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetDefaults to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetDefaults + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSetDefaults { + + /** Properties of a FeatureSetEditionDefault. */ + interface IFeatureSetEditionDefault { + + /** FeatureSetEditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** FeatureSetEditionDefault features */ + features?: (google.protobuf.IFeatureSet|null); + } + + /** Represents a FeatureSetEditionDefault. */ + class FeatureSetEditionDefault implements IFeatureSetEditionDefault { + + /** + * Constructs a new FeatureSetEditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault); + + /** FeatureSetEditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** FeatureSetEditionDefault features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetEditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault; + + /** + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * @param message FeatureSetEditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetEditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetEditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a SourceCodeInfo. */ + interface ISourceCodeInfo { + + /** SourceCodeInfo location */ + location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); + } + + /** Represents a SourceCodeInfo. */ + class SourceCodeInfo implements ISourceCodeInfo { + + /** + * Constructs a new SourceCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ISourceCodeInfo); + + /** SourceCodeInfo location. */ + public location: google.protobuf.SourceCodeInfo.ILocation[]; + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @param message SourceCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace SourceCodeInfo { + + /** Properties of a Location. */ + interface ILocation { + + /** Location path */ + path?: (number[]|null); + + /** Location span */ + span?: (number[]|null); + + /** Location leadingComments */ + leadingComments?: (string|null); + + /** Location trailingComments */ + trailingComments?: (string|null); + + /** Location leadingDetachedComments */ + leadingDetachedComments?: (string[]|null); + } + + /** Represents a Location. */ + class Location implements ILocation { + + /** + * Constructs a new Location. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); + + /** Location path. */ + public path: number[]; + + /** Location span. */ + public span: number[]; + + /** Location leadingComments. */ + public leadingComments: string; + + /** Location trailingComments. */ + public trailingComments: string; + + /** Location leadingDetachedComments. */ + public leadingDetachedComments: string[]; + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Location + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @param message Location + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Location to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Location + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a GeneratedCodeInfo. */ + interface IGeneratedCodeInfo { + + /** GeneratedCodeInfo annotation */ + annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); + } + + /** Represents a GeneratedCodeInfo. */ + class GeneratedCodeInfo implements IGeneratedCodeInfo { + + /** + * Constructs a new GeneratedCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IGeneratedCodeInfo); + + /** GeneratedCodeInfo annotation. */ + public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; + + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GeneratedCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; + + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @param message GeneratedCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GeneratedCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace GeneratedCodeInfo { + + /** Properties of an Annotation. */ + interface IAnnotation { + + /** Annotation path */ + path?: (number[]|null); + + /** Annotation sourceFile */ + sourceFile?: (string|null); + + /** Annotation begin */ + begin?: (number|null); + + /** Annotation end */ + end?: (number|null); + + /** Annotation semantic */ + semantic?: (google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null); + } + + /** Represents an Annotation. */ + class Annotation implements IAnnotation { + + /** + * Constructs a new Annotation. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); + + /** Annotation path. */ + public path: number[]; + + /** Annotation sourceFile. */ + public sourceFile: string; + + /** Annotation begin. */ + public begin: number; + + /** Annotation end. */ + public end: number; + + /** Annotation semantic. */ + public semantic: google.protobuf.GeneratedCodeInfo.Annotation.Semantic; + + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Annotation + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @param message Annotation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Annotation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Annotation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Annotation { + + /** Semantic enum. */ + type Semantic = + "NONE"| "SET"| "ALIAS"; + } + } + + /** Properties of a Timestamp. */ + interface ITimestamp { + + /** Timestamp seconds */ + seconds?: (number|string|null); + + /** Timestamp nanos */ + nanos?: (number|null); + } + + /** Represents a Timestamp. */ + class Timestamp implements ITimestamp { + + /** + * Constructs a new Timestamp. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ITimestamp); + + /** Timestamp seconds. */ + public seconds: (number|string); + + /** Timestamp nanos. */ + public nanos: number; + + /** + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Timestamp + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; + + /** + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * @param message Timestamp + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Timestamp to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Timestamp + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Duration. */ + interface IDuration { + + /** Duration seconds */ + seconds?: (number|string|null); + + /** Duration nanos */ + nanos?: (number|null); + } + + /** Represents a Duration. */ + class Duration implements IDuration { + + /** + * Constructs a new Duration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDuration); + + /** Duration seconds. */ + public seconds: (number|string); + + /** Duration nanos. */ + public nanos: number; + + /** + * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Duration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; + + /** + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @param message Duration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Duration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Duration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Any. */ + interface IAny { + + /** Any type_url */ + type_url?: (string|null); + + /** Any value */ + value?: (Uint8Array|null); + } + + /** Represents an Any. */ + class Any implements IAny { + + /** + * Constructs a new Any. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IAny); + + /** Any type_url. */ + public type_url: string; + + /** Any value. */ + public value: Uint8Array; + + /** + * Creates an Any message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Any + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Any; + + /** + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @param message Any + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Any to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Any + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Empty. */ + interface IEmpty { + } + + /** Represents an Empty. */ + class Empty implements IEmpty { + + /** + * Constructs a new Empty. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEmpty); + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Empty + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @param message Empty + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Empty to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Empty + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldMask. */ + interface IFieldMask { + + /** FieldMask paths */ + paths?: (string[]|null); + } + + /** Represents a FieldMask. */ + class FieldMask implements IFieldMask { + + /** + * Constructs a new FieldMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldMask); + + /** FieldMask paths. */ + public paths: string[]; + + /** + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldMask + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; + + /** + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @param message FieldMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Struct. */ + interface IStruct { + + /** Struct fields */ + fields?: ({ [k: string]: google.protobuf.IValue }|null); + } + + /** Represents a Struct. */ + class Struct implements IStruct { + + /** + * Constructs a new Struct. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStruct); + + /** Struct fields. */ + public fields: { [k: string]: google.protobuf.IValue }; + + /** + * Creates a Struct message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Struct + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; + + /** + * Creates a plain object from a Struct message. Also converts values to other types if specified. + * @param message Struct + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Struct to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Struct + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Value. */ + interface IValue { + + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue */ + numberValue?: (number|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value boolValue */ + boolValue?: (boolean|null); + + /** Value structValue */ + structValue?: (google.protobuf.IStruct|null); + + /** Value listValue */ + listValue?: (google.protobuf.IListValue|null); + } + + /** Represents a Value. */ + class Value implements IValue { + + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IValue); + + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue. */ + public numberValue?: (number|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value boolValue. */ + public boolValue?: (boolean|null); + + /** Value structValue. */ + public structValue?: (google.protobuf.IStruct|null); + + /** Value listValue. */ + public listValue?: (google.protobuf.IListValue|null); + + /** Value kind. */ + public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Value; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** NullValue enum. */ + type NullValue = + "NULL_VALUE"; + + /** Properties of a ListValue. */ + interface IListValue { + + /** ListValue values */ + values?: (google.protobuf.IValue[]|null); + } + + /** Represents a ListValue. */ + class ListValue implements IListValue { + + /** + * Constructs a new ListValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IListValue); + + /** ListValue values. */ + public values: google.protobuf.IValue[]; + + /** + * Creates a ListValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; + + /** + * Creates a plain object from a ListValue message. Also converts values to other types if specified. + * @param message ListValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DoubleValue. */ + interface IDoubleValue { + + /** DoubleValue value */ + value?: (number|null); + } + + /** Represents a DoubleValue. */ + class DoubleValue implements IDoubleValue { + + /** + * Constructs a new DoubleValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDoubleValue); + + /** DoubleValue value. */ + public value: number; + + /** + * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DoubleValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DoubleValue; + + /** + * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. + * @param message DoubleValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DoubleValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DoubleValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DoubleValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FloatValue. */ + interface IFloatValue { + + /** FloatValue value */ + value?: (number|null); + } + + /** Represents a FloatValue. */ + class FloatValue implements IFloatValue { + + /** + * Constructs a new FloatValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFloatValue); + + /** FloatValue value. */ + public value: number; + + /** + * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FloatValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FloatValue; + + /** + * Creates a plain object from a FloatValue message. Also converts values to other types if specified. + * @param message FloatValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FloatValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FloatValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FloatValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int64Value. */ + interface IInt64Value { + + /** Int64Value value */ + value?: (number|string|null); + } + + /** Represents an Int64Value. */ + class Int64Value implements IInt64Value { + + /** + * Constructs a new Int64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt64Value); + + /** Int64Value value. */ + public value: (number|string); + + /** + * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int64Value; + + /** + * Creates a plain object from an Int64Value message. Also converts values to other types if specified. + * @param message Int64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt64Value. */ + interface IUInt64Value { + + /** UInt64Value value */ + value?: (number|string|null); + } + + /** Represents a UInt64Value. */ + class UInt64Value implements IUInt64Value { + + /** + * Constructs a new UInt64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt64Value); + + /** UInt64Value value. */ + public value: (number|string); + + /** + * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt64Value; + + /** + * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. + * @param message UInt64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int32Value. */ + interface IInt32Value { + + /** Int32Value value */ + value?: (number|null); + } + + /** Represents an Int32Value. */ + class Int32Value implements IInt32Value { + + /** + * Constructs a new Int32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt32Value); + + /** Int32Value value. */ + public value: number; + + /** + * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int32Value; + + /** + * Creates a plain object from an Int32Value message. Also converts values to other types if specified. + * @param message Int32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt32Value. */ + interface IUInt32Value { + + /** UInt32Value value */ + value?: (number|null); + } + + /** Represents a UInt32Value. */ + class UInt32Value implements IUInt32Value { + + /** + * Constructs a new UInt32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt32Value); + + /** UInt32Value value. */ + public value: number; + + /** + * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt32Value; + + /** + * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. + * @param message UInt32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BoolValue. */ + interface IBoolValue { + + /** BoolValue value */ + value?: (boolean|null); + } + + /** Represents a BoolValue. */ + class BoolValue implements IBoolValue { + + /** + * Constructs a new BoolValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBoolValue); + + /** BoolValue value. */ + public value: boolean; + + /** + * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BoolValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BoolValue; + + /** + * Creates a plain object from a BoolValue message. Also converts values to other types if specified. + * @param message BoolValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BoolValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BoolValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BoolValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StringValue. */ + interface IStringValue { + + /** StringValue value */ + value?: (string|null); + } + + /** Represents a StringValue. */ + class StringValue implements IStringValue { + + /** + * Constructs a new StringValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStringValue); + + /** StringValue value. */ + public value: string; + + /** + * Creates a StringValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StringValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.StringValue; + + /** + * Creates a plain object from a StringValue message. Also converts values to other types if specified. + * @param message StringValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.StringValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StringValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StringValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BytesValue. */ + interface IBytesValue { + + /** BytesValue value */ + value?: (Uint8Array|null); + } + + /** Represents a BytesValue. */ + class BytesValue implements IBytesValue { + + /** + * Constructs a new BytesValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBytesValue); + + /** BytesValue value. */ + public value: Uint8Array; + + /** + * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BytesValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BytesValue; + + /** + * Creates a plain object from a BytesValue message. Also converts values to other types if specified. + * @param message BytesValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BytesValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BytesValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BytesValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace type. */ + namespace type { + + /** DayOfWeek enum. */ + type DayOfWeek = + "DAY_OF_WEEK_UNSPECIFIED"| "MONDAY"| "TUESDAY"| "WEDNESDAY"| "THURSDAY"| "FRIDAY"| "SATURDAY"| "SUNDAY"; + + /** Properties of a LatLng. */ + interface ILatLng { + + /** LatLng latitude */ + latitude?: (number|null); + + /** LatLng longitude */ + longitude?: (number|null); + } + + /** Represents a LatLng. */ + class LatLng implements ILatLng { + + /** + * Constructs a new LatLng. + * @param [properties] Properties to set + */ + constructor(properties?: google.type.ILatLng); + + /** LatLng latitude. */ + public latitude: number; + + /** LatLng longitude. */ + public longitude: number; + + /** + * Creates a LatLng message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LatLng + */ + public static fromObject(object: { [k: string]: any }): google.type.LatLng; + + /** + * Creates a plain object from a LatLng message. Also converts values to other types if specified. + * @param message LatLng + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.type.LatLng, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LatLng to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LatLng + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace longrunning. */ + namespace longrunning { + + /** Represents an Operations */ + class Operations extends $protobuf.rpc.Service { + + /** + * Constructs a new Operations service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListOperationsResponse + */ + public listOperations(request: google.longrunning.IListOperationsRequest, callback: google.longrunning.Operations.ListOperationsCallback): void; + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @returns Promise + */ + public listOperations(request: google.longrunning.IListOperationsRequest): Promise; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public getOperation(request: google.longrunning.IGetOperationRequest, callback: google.longrunning.Operations.GetOperationCallback): void; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @returns Promise + */ + public getOperation(request: google.longrunning.IGetOperationRequest): Promise; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest, callback: google.longrunning.Operations.DeleteOperationCallback): void; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @returns Promise + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest): Promise; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest, callback: google.longrunning.Operations.CancelOperationCallback): void; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @returns Promise + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest): Promise; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest, callback: google.longrunning.Operations.WaitOperationCallback): void; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @returns Promise + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest): Promise; + } + + namespace Operations { + + /** + * Callback as used by {@link google.longrunning.Operations#listOperations}. + * @param error Error, if any + * @param [response] ListOperationsResponse + */ + type ListOperationsCallback = (error: (Error|null), response?: google.longrunning.ListOperationsResponse) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#getOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type GetOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#deleteOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#cancelOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type CancelOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#waitOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type WaitOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + } + + /** Properties of an Operation. */ + interface IOperation { + + /** Operation name */ + name?: (string|null); + + /** Operation metadata */ + metadata?: (google.protobuf.IAny|null); + + /** Operation done */ + done?: (boolean|null); + + /** Operation error */ + error?: (google.rpc.IStatus|null); + + /** Operation response */ + response?: (google.protobuf.IAny|null); + } + + /** Represents an Operation. */ + class Operation implements IOperation { + + /** + * Constructs a new Operation. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperation); + + /** Operation name. */ + public name: string; + + /** Operation metadata. */ + public metadata?: (google.protobuf.IAny|null); + + /** Operation done. */ + public done: boolean; + + /** Operation error. */ + public error?: (google.rpc.IStatus|null); + + /** Operation response. */ + public response?: (google.protobuf.IAny|null); + + /** Operation result. */ + public result?: ("error"|"response"); + + /** + * Creates an Operation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Operation + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.Operation; + + /** + * Creates a plain object from an Operation message. Also converts values to other types if specified. + * @param message Operation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.Operation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Operation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Operation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetOperationRequest. */ + interface IGetOperationRequest { + + /** GetOperationRequest name */ + name?: (string|null); + } + + /** Represents a GetOperationRequest. */ + class GetOperationRequest implements IGetOperationRequest { + + /** + * Constructs a new GetOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IGetOperationRequest); + + /** GetOperationRequest name. */ + public name: string; + + /** + * Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.GetOperationRequest; + + /** + * Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified. + * @param message GetOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.GetOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsRequest. */ + interface IListOperationsRequest { + + /** ListOperationsRequest name */ + name?: (string|null); + + /** ListOperationsRequest filter */ + filter?: (string|null); + + /** ListOperationsRequest pageSize */ + pageSize?: (number|null); + + /** ListOperationsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListOperationsRequest. */ + class ListOperationsRequest implements IListOperationsRequest { + + /** + * Constructs a new ListOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsRequest); + + /** ListOperationsRequest name. */ + public name: string; + + /** ListOperationsRequest filter. */ + public filter: string; + + /** ListOperationsRequest pageSize. */ + public pageSize: number; + + /** ListOperationsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsRequest; + + /** + * Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified. + * @param message ListOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsResponse. */ + interface IListOperationsResponse { + + /** ListOperationsResponse operations */ + operations?: (google.longrunning.IOperation[]|null); + + /** ListOperationsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListOperationsResponse. */ + class ListOperationsResponse implements IListOperationsResponse { + + /** + * Constructs a new ListOperationsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsResponse); + + /** ListOperationsResponse operations. */ + public operations: google.longrunning.IOperation[]; + + /** ListOperationsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsResponse + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsResponse; + + /** + * Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified. + * @param message ListOperationsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CancelOperationRequest. */ + interface ICancelOperationRequest { + + /** CancelOperationRequest name */ + name?: (string|null); + } + + /** Represents a CancelOperationRequest. */ + class CancelOperationRequest implements ICancelOperationRequest { + + /** + * Constructs a new CancelOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.ICancelOperationRequest); + + /** CancelOperationRequest name. */ + public name: string; + + /** + * Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CancelOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.CancelOperationRequest; + + /** + * Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified. + * @param message CancelOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.CancelOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CancelOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CancelOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteOperationRequest. */ + interface IDeleteOperationRequest { + + /** DeleteOperationRequest name */ + name?: (string|null); + } + + /** Represents a DeleteOperationRequest. */ + class DeleteOperationRequest implements IDeleteOperationRequest { + + /** + * Constructs a new DeleteOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IDeleteOperationRequest); + + /** DeleteOperationRequest name. */ + public name: string; + + /** + * Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.DeleteOperationRequest; + + /** + * Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified. + * @param message DeleteOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.DeleteOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WaitOperationRequest. */ + interface IWaitOperationRequest { + + /** WaitOperationRequest name */ + name?: (string|null); + + /** WaitOperationRequest timeout */ + timeout?: (google.protobuf.IDuration|null); + } + + /** Represents a WaitOperationRequest. */ + class WaitOperationRequest implements IWaitOperationRequest { + + /** + * Constructs a new WaitOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IWaitOperationRequest); + + /** WaitOperationRequest name. */ + public name: string; + + /** WaitOperationRequest timeout. */ + public timeout?: (google.protobuf.IDuration|null); + + /** + * Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WaitOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.WaitOperationRequest; + + /** + * Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified. + * @param message WaitOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.WaitOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WaitOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WaitOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an OperationInfo. */ + interface IOperationInfo { + + /** OperationInfo responseType */ + responseType?: (string|null); + + /** OperationInfo metadataType */ + metadataType?: (string|null); + } + + /** Represents an OperationInfo. */ + class OperationInfo implements IOperationInfo { + + /** + * Constructs a new OperationInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperationInfo); + + /** OperationInfo responseType. */ + public responseType: string; + + /** OperationInfo metadataType. */ + public metadataType: string; + + /** + * Creates an OperationInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OperationInfo + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.OperationInfo; + + /** + * Creates a plain object from an OperationInfo message. Also converts values to other types if specified. + * @param message OperationInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.OperationInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OperationInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OperationInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace rpc. */ + namespace rpc { + + /** Properties of a Status. */ + interface IStatus { + + /** Status code */ + code?: (number|null); + + /** Status message */ + message?: (string|null); + + /** Status details */ + details?: (google.protobuf.IAny[]|null); + } + + /** Represents a Status. */ + class Status implements IStatus { + + /** + * Constructs a new Status. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IStatus); + + /** Status code. */ + public code: number; + + /** Status message. */ + public message: string; + + /** Status details. */ + public details: google.protobuf.IAny[]; + + /** + * Creates a Status message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Status + */ + public static fromObject(object: { [k: string]: any }): google.rpc.Status; + + /** + * Creates a plain object from a Status message. Also converts values to other types if specified. + * @param message Status + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Status to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Status + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } +} diff --git a/node_modules/@google-cloud/firestore/build/protos/firestore_admin_v1_proto_api.js b/node_modules/@google-cloud/firestore/build/protos/firestore_admin_v1_proto_api.js new file mode 100644 index 0000000..edcb221 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/firestore_admin_v1_proto_api.js @@ -0,0 +1 @@ +(e=>{"function"==typeof define&&define.amd?define(["protobufjs/minimal"],e):"function"==typeof require&&"object"==typeof module&&module&&module.exports&&(module.exports=e(require("protobufjs/minimal")))})(function(r){var e,t,o,n,i,L,a=r.util,s=r.roots.firestore_admin_v1||(r.roots.firestore_admin_v1={});function l(e){if(e)for(var t=Object.keys(e),o=0;o>>0,e.sizeBytes.high>>>0).toNumber())),null!=e.documentCount&&(a.Long?(t.documentCount=a.Long.fromValue(e.documentCount)).unsigned=!1:"string"==typeof e.documentCount?t.documentCount=parseInt(e.documentCount,10):"number"==typeof e.documentCount?t.documentCount=e.documentCount:"object"==typeof e.documentCount&&(t.documentCount=new a.LongBits(e.documentCount.low>>>0,e.documentCount.high>>>0).toNumber())),null!=e.indexCount&&(a.Long?(t.indexCount=a.Long.fromValue(e.indexCount)).unsigned=!1:"string"==typeof e.indexCount?t.indexCount=parseInt(e.indexCount,10):"number"==typeof e.indexCount?t.indexCount=e.indexCount:"object"==typeof e.indexCount&&(t.indexCount=new a.LongBits(e.indexCount.low>>>0,e.indexCount.high>>>0).toNumber())),t)},F.toObject=function(e,t){var o,r={};return(t=t||{}).defaults&&(a.Long?(o=new a.Long(0,0,!1),r.sizeBytes=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.sizeBytes=t.longs===String?"0":0,a.Long?(o=new a.Long(0,0,!1),r.documentCount=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.documentCount=t.longs===String?"0":0,a.Long?(o=new a.Long(0,0,!1),r.indexCount=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.indexCount=t.longs===String?"0":0),null!=e.sizeBytes&&e.hasOwnProperty("sizeBytes")&&("number"==typeof e.sizeBytes?r.sizeBytes=t.longs===String?String(e.sizeBytes):e.sizeBytes:r.sizeBytes=t.longs===String?a.Long.prototype.toString.call(e.sizeBytes):t.longs===Number?new a.LongBits(e.sizeBytes.low>>>0,e.sizeBytes.high>>>0).toNumber():e.sizeBytes),null!=e.documentCount&&e.hasOwnProperty("documentCount")&&("number"==typeof e.documentCount?r.documentCount=t.longs===String?String(e.documentCount):e.documentCount:r.documentCount=t.longs===String?a.Long.prototype.toString.call(e.documentCount):t.longs===Number?new a.LongBits(e.documentCount.low>>>0,e.documentCount.high>>>0).toNumber():e.documentCount),null!=e.indexCount&&e.hasOwnProperty("indexCount")&&("number"==typeof e.indexCount?r.indexCount=t.longs===String?String(e.indexCount):e.indexCount:r.indexCount=t.longs===String?a.Long.prototype.toString.call(e.indexCount):t.longs===Number?new a.LongBits(e.indexCount.low>>>0,e.indexCount.high>>>0).toNumber():e.indexCount),r},F.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},F.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.firestore.admin.v1.Backup.Stats"},F),l.State=(i={},(t=Object.create(i))[i[0]="STATE_UNSPECIFIED"]="STATE_UNSPECIFIED",t[i[1]="CREATING"]="CREATING",t[i[2]="READY"]="READY",t[i[3]="NOT_AVAILABLE"]="NOT_AVAILABLE",t),l),e.Database=(p.prototype.name="",p.prototype.uid="",p.prototype.createTime=null,p.prototype.updateTime=null,p.prototype.deleteTime=null,p.prototype.locationId="",p.prototype.type=0,p.prototype.concurrencyMode=0,p.prototype.versionRetentionPeriod=null,p.prototype.earliestVersionTime=null,p.prototype.pointInTimeRecoveryEnablement=0,p.prototype.appEngineIntegrationMode=0,p.prototype.keyPrefix="",p.prototype.deleteProtectionState=0,p.prototype.cmekConfig=null,p.prototype.previousId="",p.prototype.sourceInfo=null,p.prototype.etag="",p.fromObject=function(e){if(e instanceof s.google.firestore.admin.v1.Database)return e;var t=new s.google.firestore.admin.v1.Database;if(null!=e.name&&(t.name=String(e.name)),null!=e.uid&&(t.uid=String(e.uid)),null!=e.createTime){if("object"!=typeof e.createTime)throw TypeError(".google.firestore.admin.v1.Database.createTime: object expected");t.createTime=s.google.protobuf.Timestamp.fromObject(e.createTime)}if(null!=e.updateTime){if("object"!=typeof e.updateTime)throw TypeError(".google.firestore.admin.v1.Database.updateTime: object expected");t.updateTime=s.google.protobuf.Timestamp.fromObject(e.updateTime)}if(null!=e.deleteTime){if("object"!=typeof e.deleteTime)throw TypeError(".google.firestore.admin.v1.Database.deleteTime: object expected");t.deleteTime=s.google.protobuf.Timestamp.fromObject(e.deleteTime)}switch(null!=e.locationId&&(t.locationId=String(e.locationId)),e.type){default:"number"==typeof e.type&&(t.type=e.type);break;case"DATABASE_TYPE_UNSPECIFIED":case 0:t.type=0;break;case"FIRESTORE_NATIVE":case 1:t.type=1;break;case"DATASTORE_MODE":case 2:t.type=2}switch(e.concurrencyMode){default:"number"==typeof e.concurrencyMode&&(t.concurrencyMode=e.concurrencyMode);break;case"CONCURRENCY_MODE_UNSPECIFIED":case 0:t.concurrencyMode=0;break;case"OPTIMISTIC":case 1:t.concurrencyMode=1;break;case"PESSIMISTIC":case 2:t.concurrencyMode=2;break;case"OPTIMISTIC_WITH_ENTITY_GROUPS":case 3:t.concurrencyMode=3}if(null!=e.versionRetentionPeriod){if("object"!=typeof e.versionRetentionPeriod)throw TypeError(".google.firestore.admin.v1.Database.versionRetentionPeriod: object expected");t.versionRetentionPeriod=s.google.protobuf.Duration.fromObject(e.versionRetentionPeriod)}if(null!=e.earliestVersionTime){if("object"!=typeof e.earliestVersionTime)throw TypeError(".google.firestore.admin.v1.Database.earliestVersionTime: object expected");t.earliestVersionTime=s.google.protobuf.Timestamp.fromObject(e.earliestVersionTime)}switch(e.pointInTimeRecoveryEnablement){default:"number"==typeof e.pointInTimeRecoveryEnablement&&(t.pointInTimeRecoveryEnablement=e.pointInTimeRecoveryEnablement);break;case"POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED":case 0:t.pointInTimeRecoveryEnablement=0;break;case"POINT_IN_TIME_RECOVERY_ENABLED":case 1:t.pointInTimeRecoveryEnablement=1;break;case"POINT_IN_TIME_RECOVERY_DISABLED":case 2:t.pointInTimeRecoveryEnablement=2}switch(e.appEngineIntegrationMode){default:"number"==typeof e.appEngineIntegrationMode&&(t.appEngineIntegrationMode=e.appEngineIntegrationMode);break;case"APP_ENGINE_INTEGRATION_MODE_UNSPECIFIED":case 0:t.appEngineIntegrationMode=0;break;case"ENABLED":case 1:t.appEngineIntegrationMode=1;break;case"DISABLED":case 2:t.appEngineIntegrationMode=2}switch(null!=e.keyPrefix&&(t.keyPrefix=String(e.keyPrefix)),e.deleteProtectionState){default:"number"==typeof e.deleteProtectionState&&(t.deleteProtectionState=e.deleteProtectionState);break;case"DELETE_PROTECTION_STATE_UNSPECIFIED":case 0:t.deleteProtectionState=0;break;case"DELETE_PROTECTION_DISABLED":case 1:t.deleteProtectionState=1;break;case"DELETE_PROTECTION_ENABLED":case 2:t.deleteProtectionState=2}if(null!=e.cmekConfig){if("object"!=typeof e.cmekConfig)throw TypeError(".google.firestore.admin.v1.Database.cmekConfig: object expected");t.cmekConfig=s.google.firestore.admin.v1.Database.CmekConfig.fromObject(e.cmekConfig)}if(null!=e.previousId&&(t.previousId=String(e.previousId)),null!=e.sourceInfo){if("object"!=typeof e.sourceInfo)throw TypeError(".google.firestore.admin.v1.Database.sourceInfo: object expected");t.sourceInfo=s.google.firestore.admin.v1.Database.SourceInfo.fromObject(e.sourceInfo)}return null!=e.etag&&(t.etag=String(e.etag)),t},p.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.name="",o.uid="",o.createTime=null,o.updateTime=null,o.deleteTime=null,o.locationId="",o.type=t.enums===String?"DATABASE_TYPE_UNSPECIFIED":0,o.concurrencyMode=t.enums===String?"CONCURRENCY_MODE_UNSPECIFIED":0,o.versionRetentionPeriod=null,o.earliestVersionTime=null,o.appEngineIntegrationMode=t.enums===String?"APP_ENGINE_INTEGRATION_MODE_UNSPECIFIED":0,o.keyPrefix="",o.pointInTimeRecoveryEnablement=t.enums===String?"POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED":0,o.deleteProtectionState=t.enums===String?"DELETE_PROTECTION_STATE_UNSPECIFIED":0,o.cmekConfig=null,o.previousId="",o.sourceInfo=null,o.etag=""),null!=e.name&&e.hasOwnProperty("name")&&(o.name=e.name),null!=e.uid&&e.hasOwnProperty("uid")&&(o.uid=e.uid),null!=e.createTime&&e.hasOwnProperty("createTime")&&(o.createTime=s.google.protobuf.Timestamp.toObject(e.createTime,t)),null!=e.updateTime&&e.hasOwnProperty("updateTime")&&(o.updateTime=s.google.protobuf.Timestamp.toObject(e.updateTime,t)),null!=e.deleteTime&&e.hasOwnProperty("deleteTime")&&(o.deleteTime=s.google.protobuf.Timestamp.toObject(e.deleteTime,t)),null!=e.locationId&&e.hasOwnProperty("locationId")&&(o.locationId=e.locationId),null!=e.type&&e.hasOwnProperty("type")&&(o.type=t.enums!==String||void 0===s.google.firestore.admin.v1.Database.DatabaseType[e.type]?e.type:s.google.firestore.admin.v1.Database.DatabaseType[e.type]),null!=e.concurrencyMode&&e.hasOwnProperty("concurrencyMode")&&(o.concurrencyMode=t.enums!==String||void 0===s.google.firestore.admin.v1.Database.ConcurrencyMode[e.concurrencyMode]?e.concurrencyMode:s.google.firestore.admin.v1.Database.ConcurrencyMode[e.concurrencyMode]),null!=e.versionRetentionPeriod&&e.hasOwnProperty("versionRetentionPeriod")&&(o.versionRetentionPeriod=s.google.protobuf.Duration.toObject(e.versionRetentionPeriod,t)),null!=e.earliestVersionTime&&e.hasOwnProperty("earliestVersionTime")&&(o.earliestVersionTime=s.google.protobuf.Timestamp.toObject(e.earliestVersionTime,t)),null!=e.appEngineIntegrationMode&&e.hasOwnProperty("appEngineIntegrationMode")&&(o.appEngineIntegrationMode=t.enums!==String||void 0===s.google.firestore.admin.v1.Database.AppEngineIntegrationMode[e.appEngineIntegrationMode]?e.appEngineIntegrationMode:s.google.firestore.admin.v1.Database.AppEngineIntegrationMode[e.appEngineIntegrationMode]),null!=e.keyPrefix&&e.hasOwnProperty("keyPrefix")&&(o.keyPrefix=e.keyPrefix),null!=e.pointInTimeRecoveryEnablement&&e.hasOwnProperty("pointInTimeRecoveryEnablement")&&(o.pointInTimeRecoveryEnablement=t.enums!==String||void 0===s.google.firestore.admin.v1.Database.PointInTimeRecoveryEnablement[e.pointInTimeRecoveryEnablement]?e.pointInTimeRecoveryEnablement:s.google.firestore.admin.v1.Database.PointInTimeRecoveryEnablement[e.pointInTimeRecoveryEnablement]),null!=e.deleteProtectionState&&e.hasOwnProperty("deleteProtectionState")&&(o.deleteProtectionState=t.enums!==String||void 0===s.google.firestore.admin.v1.Database.DeleteProtectionState[e.deleteProtectionState]?e.deleteProtectionState:s.google.firestore.admin.v1.Database.DeleteProtectionState[e.deleteProtectionState]),null!=e.cmekConfig&&e.hasOwnProperty("cmekConfig")&&(o.cmekConfig=s.google.firestore.admin.v1.Database.CmekConfig.toObject(e.cmekConfig,t)),null!=e.previousId&&e.hasOwnProperty("previousId")&&(o.previousId=e.previousId),null!=e.sourceInfo&&e.hasOwnProperty("sourceInfo")&&(o.sourceInfo=s.google.firestore.admin.v1.Database.SourceInfo.toObject(e.sourceInfo,t)),null!=e.etag&&e.hasOwnProperty("etag")&&(o.etag=e.etag),o},p.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},p.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.firestore.admin.v1.Database"},p.DatabaseType=(i={},(t=Object.create(i))[i[0]="DATABASE_TYPE_UNSPECIFIED"]="DATABASE_TYPE_UNSPECIFIED",t[i[1]="FIRESTORE_NATIVE"]="FIRESTORE_NATIVE",t[i[2]="DATASTORE_MODE"]="DATASTORE_MODE",t),p.ConcurrencyMode=(i={},(t=Object.create(i))[i[0]="CONCURRENCY_MODE_UNSPECIFIED"]="CONCURRENCY_MODE_UNSPECIFIED",t[i[1]="OPTIMISTIC"]="OPTIMISTIC",t[i[2]="PESSIMISTIC"]="PESSIMISTIC",t[i[3]="OPTIMISTIC_WITH_ENTITY_GROUPS"]="OPTIMISTIC_WITH_ENTITY_GROUPS",t),p.PointInTimeRecoveryEnablement=(i={},(t=Object.create(i))[i[0]="POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED"]="POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED",t[i[1]="POINT_IN_TIME_RECOVERY_ENABLED"]="POINT_IN_TIME_RECOVERY_ENABLED",t[i[2]="POINT_IN_TIME_RECOVERY_DISABLED"]="POINT_IN_TIME_RECOVERY_DISABLED",t),p.AppEngineIntegrationMode=(i={},(t=Object.create(i))[i[0]="APP_ENGINE_INTEGRATION_MODE_UNSPECIFIED"]="APP_ENGINE_INTEGRATION_MODE_UNSPECIFIED",t[i[1]="ENABLED"]="ENABLED",t[i[2]="DISABLED"]="DISABLED",t),p.DeleteProtectionState=(i={},(t=Object.create(i))[i[0]="DELETE_PROTECTION_STATE_UNSPECIFIED"]="DELETE_PROTECTION_STATE_UNSPECIFIED",t[i[1]="DELETE_PROTECTION_DISABLED"]="DELETE_PROTECTION_DISABLED",t[i[2]="DELETE_PROTECTION_ENABLED"]="DELETE_PROTECTION_ENABLED",t),p.CmekConfig=(U.prototype.kmsKeyName="",U.prototype.activeKeyVersion=a.emptyArray,U.fromObject=function(e){if(e instanceof s.google.firestore.admin.v1.Database.CmekConfig)return e;var t=new s.google.firestore.admin.v1.Database.CmekConfig;if(null!=e.kmsKeyName&&(t.kmsKeyName=String(e.kmsKeyName)),e.activeKeyVersion){if(!Array.isArray(e.activeKeyVersion))throw TypeError(".google.firestore.admin.v1.Database.CmekConfig.activeKeyVersion: array expected");t.activeKeyVersion=[];for(var o=0;o>>0,e.estimatedWork.high>>>0).toNumber())),null!=e.completedWork&&(a.Long?(t.completedWork=a.Long.fromValue(e.completedWork)).unsigned=!1:"string"==typeof e.completedWork?t.completedWork=parseInt(e.completedWork,10):"number"==typeof e.completedWork?t.completedWork=e.completedWork:"object"==typeof e.completedWork&&(t.completedWork=new a.LongBits(e.completedWork.low>>>0,e.completedWork.high>>>0).toNumber())),t)},Re.toObject=function(e,t){var o,r={};return(t=t||{}).defaults&&(a.Long?(o=new a.Long(0,0,!1),r.estimatedWork=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.estimatedWork=t.longs===String?"0":0,a.Long?(o=new a.Long(0,0,!1),r.completedWork=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.completedWork=t.longs===String?"0":0),null!=e.estimatedWork&&e.hasOwnProperty("estimatedWork")&&("number"==typeof e.estimatedWork?r.estimatedWork=t.longs===String?String(e.estimatedWork):e.estimatedWork:r.estimatedWork=t.longs===String?a.Long.prototype.toString.call(e.estimatedWork):t.longs===Number?new a.LongBits(e.estimatedWork.low>>>0,e.estimatedWork.high>>>0).toNumber():e.estimatedWork),null!=e.completedWork&&e.hasOwnProperty("completedWork")&&("number"==typeof e.completedWork?r.completedWork=t.longs===String?String(e.completedWork):e.completedWork:r.completedWork=t.longs===String?a.Long.prototype.toString.call(e.completedWork):t.longs===Number?new a.LongBits(e.completedWork.low>>>0,e.completedWork.high>>>0).toNumber():e.completedWork),r},Re.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Re.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.firestore.admin.v1.Progress"},Re),e.OperationState=(t={},(i=Object.create(t))[t[0]="OPERATION_STATE_UNSPECIFIED"]="OPERATION_STATE_UNSPECIFIED",i[t[1]="INITIALIZING"]="INITIALIZING",i[t[2]="PROCESSING"]="PROCESSING",i[t[3]="CANCELLING"]="CANCELLING",i[t[4]="FINALIZING"]="FINALIZING",i[t[5]="SUCCESSFUL"]="SUCCESSFUL",i[t[6]="FAILED"]="FAILED",i[t[7]="CANCELLED"]="CANCELLED",i),e.BackupSchedule=(S.prototype.name="",S.prototype.createTime=null,S.prototype.updateTime=null,S.prototype.retention=null,S.prototype.dailyRecurrence=null,S.prototype.weeklyRecurrence=null,Object.defineProperty(S.prototype,"recurrence",{get:a.oneOfGetter(t=["dailyRecurrence","weeklyRecurrence"]),set:a.oneOfSetter(t)}),S.fromObject=function(e){if(e instanceof s.google.firestore.admin.v1.BackupSchedule)return e;var t=new s.google.firestore.admin.v1.BackupSchedule;if(null!=e.name&&(t.name=String(e.name)),null!=e.createTime){if("object"!=typeof e.createTime)throw TypeError(".google.firestore.admin.v1.BackupSchedule.createTime: object expected");t.createTime=s.google.protobuf.Timestamp.fromObject(e.createTime)}if(null!=e.updateTime){if("object"!=typeof e.updateTime)throw TypeError(".google.firestore.admin.v1.BackupSchedule.updateTime: object expected");t.updateTime=s.google.protobuf.Timestamp.fromObject(e.updateTime)}if(null!=e.retention){if("object"!=typeof e.retention)throw TypeError(".google.firestore.admin.v1.BackupSchedule.retention: object expected");t.retention=s.google.protobuf.Duration.fromObject(e.retention)}if(null!=e.dailyRecurrence){if("object"!=typeof e.dailyRecurrence)throw TypeError(".google.firestore.admin.v1.BackupSchedule.dailyRecurrence: object expected");t.dailyRecurrence=s.google.firestore.admin.v1.DailyRecurrence.fromObject(e.dailyRecurrence)}if(null!=e.weeklyRecurrence){if("object"!=typeof e.weeklyRecurrence)throw TypeError(".google.firestore.admin.v1.BackupSchedule.weeklyRecurrence: object expected");t.weeklyRecurrence=s.google.firestore.admin.v1.WeeklyRecurrence.fromObject(e.weeklyRecurrence)}return t},S.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.name="",o.createTime=null,o.retention=null,o.updateTime=null),null!=e.name&&e.hasOwnProperty("name")&&(o.name=e.name),null!=e.createTime&&e.hasOwnProperty("createTime")&&(o.createTime=s.google.protobuf.Timestamp.toObject(e.createTime,t)),null!=e.retention&&e.hasOwnProperty("retention")&&(o.retention=s.google.protobuf.Duration.toObject(e.retention,t)),null!=e.dailyRecurrence&&e.hasOwnProperty("dailyRecurrence")&&(o.dailyRecurrence=s.google.firestore.admin.v1.DailyRecurrence.toObject(e.dailyRecurrence,t),t.oneofs)&&(o.recurrence="dailyRecurrence"),null!=e.weeklyRecurrence&&e.hasOwnProperty("weeklyRecurrence")&&(o.weeklyRecurrence=s.google.firestore.admin.v1.WeeklyRecurrence.toObject(e.weeklyRecurrence,t),t.oneofs)&&(o.recurrence="weeklyRecurrence"),null!=e.updateTime&&e.hasOwnProperty("updateTime")&&(o.updateTime=s.google.protobuf.Timestamp.toObject(e.updateTime,t)),o},S.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},S.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.firestore.admin.v1.BackupSchedule"},S),e.DailyRecurrence=(Ce.fromObject=function(e){return e instanceof s.google.firestore.admin.v1.DailyRecurrence?e:new s.google.firestore.admin.v1.DailyRecurrence},Ce.toObject=function(){return{}},Ce.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Ce.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.firestore.admin.v1.DailyRecurrence"},Ce),e.WeeklyRecurrence=(xe.prototype.day=0,xe.fromObject=function(e){if(e instanceof s.google.firestore.admin.v1.WeeklyRecurrence)return e;var t=new s.google.firestore.admin.v1.WeeklyRecurrence;switch(e.day){default:"number"==typeof e.day&&(t.day=e.day);break;case"DAY_OF_WEEK_UNSPECIFIED":case 0:t.day=0;break;case"MONDAY":case 1:t.day=1;break;case"TUESDAY":case 2:t.day=2;break;case"WEDNESDAY":case 3:t.day=3;break;case"THURSDAY":case 4:t.day=4;break;case"FRIDAY":case 5:t.day=5;break;case"SATURDAY":case 6:t.day=6;break;case"SUNDAY":case 7:t.day=7}return t},xe.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.day=t.enums===String?"DAY_OF_WEEK_UNSPECIFIED":0),null!=e.day&&e.hasOwnProperty("day")&&(o.day=t.enums!==String||void 0===s.google.type.DayOfWeek[e.day]?e.day:s.google.type.DayOfWeek[e.day]),o},xe.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},xe.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.firestore.admin.v1.WeeklyRecurrence"},xe),e.LocationMetadata=(Ae.fromObject=function(e){return e instanceof s.google.firestore.admin.v1.LocationMetadata?e:new s.google.firestore.admin.v1.LocationMetadata},Ae.toObject=function(){return{}},Ae.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Ae.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.firestore.admin.v1.LocationMetadata"},Ae),e),o),n),L.api=((i={}).FieldBehavior=(t={},(e=Object.create(t))[t[0]="FIELD_BEHAVIOR_UNSPECIFIED"]="FIELD_BEHAVIOR_UNSPECIFIED",e[t[1]="OPTIONAL"]="OPTIONAL",e[t[2]="REQUIRED"]="REQUIRED",e[t[3]="OUTPUT_ONLY"]="OUTPUT_ONLY",e[t[4]="INPUT_ONLY"]="INPUT_ONLY",e[t[5]="IMMUTABLE"]="IMMUTABLE",e[t[6]="UNORDERED_LIST"]="UNORDERED_LIST",e[t[7]="NON_EMPTY_DEFAULT"]="NON_EMPTY_DEFAULT",e[t[8]="IDENTIFIER"]="IDENTIFIER",e),i.ResourceDescriptor=(v.prototype.type="",v.prototype.pattern=a.emptyArray,v.prototype.nameField="",v.prototype.history=0,v.prototype.plural="",v.prototype.singular="",v.prototype.style=a.emptyArray,v.fromObject=function(e){if(e instanceof s.google.api.ResourceDescriptor)return e;var t=new s.google.api.ResourceDescriptor;if(null!=e.type&&(t.type=String(e.type)),e.pattern){if(!Array.isArray(e.pattern))throw TypeError(".google.api.ResourceDescriptor.pattern: array expected");t.pattern=[];for(var o=0;o>>0,e.positiveIntValue.high>>>0).toNumber(!0))),null!=e.negativeIntValue&&(a.Long?(t.negativeIntValue=a.Long.fromValue(e.negativeIntValue)).unsigned=!1:"string"==typeof e.negativeIntValue?t.negativeIntValue=parseInt(e.negativeIntValue,10):"number"==typeof e.negativeIntValue?t.negativeIntValue=e.negativeIntValue:"object"==typeof e.negativeIntValue&&(t.negativeIntValue=new a.LongBits(e.negativeIntValue.low>>>0,e.negativeIntValue.high>>>0).toNumber())),null!=e.doubleValue&&(t.doubleValue=Number(e.doubleValue)),null!=e.stringValue&&("string"==typeof e.stringValue?a.base64.decode(e.stringValue,t.stringValue=a.newBuffer(a.base64.length(e.stringValue)),0):0<=e.stringValue.length&&(t.stringValue=e.stringValue)),null!=e.aggregateValue&&(t.aggregateValue=String(e.aggregateValue)),t},x.toObject=function(e,t){var o,r={};if(((t=t||{}).arrays||t.defaults)&&(r.name=[]),t.defaults&&(r.identifierValue="",a.Long?(o=new a.Long(0,0,!0),r.positiveIntValue=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.positiveIntValue=t.longs===String?"0":0,a.Long?(o=new a.Long(0,0,!1),r.negativeIntValue=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.negativeIntValue=t.longs===String?"0":0,r.doubleValue=0,t.bytes===String?r.stringValue="":(r.stringValue=[],t.bytes!==Array&&(r.stringValue=a.newBuffer(r.stringValue))),r.aggregateValue=""),e.name&&e.name.length){r.name=[];for(var n=0;n>>0,e.positiveIntValue.high>>>0).toNumber(!0):e.positiveIntValue),null!=e.negativeIntValue&&e.hasOwnProperty("negativeIntValue")&&("number"==typeof e.negativeIntValue?r.negativeIntValue=t.longs===String?String(e.negativeIntValue):e.negativeIntValue:r.negativeIntValue=t.longs===String?a.Long.prototype.toString.call(e.negativeIntValue):t.longs===Number?new a.LongBits(e.negativeIntValue.low>>>0,e.negativeIntValue.high>>>0).toNumber():e.negativeIntValue),null!=e.doubleValue&&e.hasOwnProperty("doubleValue")&&(r.doubleValue=t.json&&!isFinite(e.doubleValue)?String(e.doubleValue):e.doubleValue),null!=e.stringValue&&e.hasOwnProperty("stringValue")&&(r.stringValue=t.bytes===String?a.base64.encode(e.stringValue,0,e.stringValue.length):t.bytes===Array?Array.prototype.slice.call(e.stringValue):e.stringValue),null!=e.aggregateValue&&e.hasOwnProperty("aggregateValue")&&(r.aggregateValue=e.aggregateValue),r},x.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},x.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.UninterpretedOption"},x.NamePart=(gt.prototype.namePart="",gt.prototype.isExtension=!1,gt.fromObject=function(e){var t;return e instanceof s.google.protobuf.UninterpretedOption.NamePart?e:(t=new s.google.protobuf.UninterpretedOption.NamePart,null!=e.namePart&&(t.namePart=String(e.namePart)),null!=e.isExtension&&(t.isExtension=Boolean(e.isExtension)),t)},gt.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.namePart="",o.isExtension=!1),null!=e.namePart&&e.hasOwnProperty("namePart")&&(o.namePart=e.namePart),null!=e.isExtension&&e.hasOwnProperty("isExtension")&&(o.isExtension=e.isExtension),o},gt.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},gt.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.UninterpretedOption.NamePart"},gt),x),o.FeatureSet=(A.prototype.fieldPresence=0,A.prototype.enumType=0,A.prototype.repeatedFieldEncoding=0,A.prototype.utf8Validation=0,A.prototype.messageEncoding=0,A.prototype.jsonFormat=0,A.fromObject=function(e){if(e instanceof s.google.protobuf.FeatureSet)return e;var t=new s.google.protobuf.FeatureSet;switch(e.fieldPresence){default:"number"==typeof e.fieldPresence&&(t.fieldPresence=e.fieldPresence);break;case"FIELD_PRESENCE_UNKNOWN":case 0:t.fieldPresence=0;break;case"EXPLICIT":case 1:t.fieldPresence=1;break;case"IMPLICIT":case 2:t.fieldPresence=2;break;case"LEGACY_REQUIRED":case 3:t.fieldPresence=3}switch(e.enumType){default:"number"==typeof e.enumType&&(t.enumType=e.enumType);break;case"ENUM_TYPE_UNKNOWN":case 0:t.enumType=0;break;case"OPEN":case 1:t.enumType=1;break;case"CLOSED":case 2:t.enumType=2}switch(e.repeatedFieldEncoding){default:"number"==typeof e.repeatedFieldEncoding&&(t.repeatedFieldEncoding=e.repeatedFieldEncoding);break;case"REPEATED_FIELD_ENCODING_UNKNOWN":case 0:t.repeatedFieldEncoding=0;break;case"PACKED":case 1:t.repeatedFieldEncoding=1;break;case"EXPANDED":case 2:t.repeatedFieldEncoding=2}switch(e.utf8Validation){default:"number"==typeof e.utf8Validation&&(t.utf8Validation=e.utf8Validation);break;case"UTF8_VALIDATION_UNKNOWN":case 0:t.utf8Validation=0;break;case"VERIFY":case 2:t.utf8Validation=2;break;case"NONE":case 3:t.utf8Validation=3}switch(e.messageEncoding){default:"number"==typeof e.messageEncoding&&(t.messageEncoding=e.messageEncoding);break;case"MESSAGE_ENCODING_UNKNOWN":case 0:t.messageEncoding=0;break;case"LENGTH_PREFIXED":case 1:t.messageEncoding=1;break;case"DELIMITED":case 2:t.messageEncoding=2}switch(e.jsonFormat){default:"number"==typeof e.jsonFormat&&(t.jsonFormat=e.jsonFormat);break;case"JSON_FORMAT_UNKNOWN":case 0:t.jsonFormat=0;break;case"ALLOW":case 1:t.jsonFormat=1;break;case"LEGACY_BEST_EFFORT":case 2:t.jsonFormat=2}return t},A.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.fieldPresence=t.enums===String?"FIELD_PRESENCE_UNKNOWN":0,o.enumType=t.enums===String?"ENUM_TYPE_UNKNOWN":0,o.repeatedFieldEncoding=t.enums===String?"REPEATED_FIELD_ENCODING_UNKNOWN":0,o.utf8Validation=t.enums===String?"UTF8_VALIDATION_UNKNOWN":0,o.messageEncoding=t.enums===String?"MESSAGE_ENCODING_UNKNOWN":0,o.jsonFormat=t.enums===String?"JSON_FORMAT_UNKNOWN":0),null!=e.fieldPresence&&e.hasOwnProperty("fieldPresence")&&(o.fieldPresence=t.enums!==String||void 0===s.google.protobuf.FeatureSet.FieldPresence[e.fieldPresence]?e.fieldPresence:s.google.protobuf.FeatureSet.FieldPresence[e.fieldPresence]),null!=e.enumType&&e.hasOwnProperty("enumType")&&(o.enumType=t.enums!==String||void 0===s.google.protobuf.FeatureSet.EnumType[e.enumType]?e.enumType:s.google.protobuf.FeatureSet.EnumType[e.enumType]),null!=e.repeatedFieldEncoding&&e.hasOwnProperty("repeatedFieldEncoding")&&(o.repeatedFieldEncoding=t.enums!==String||void 0===s.google.protobuf.FeatureSet.RepeatedFieldEncoding[e.repeatedFieldEncoding]?e.repeatedFieldEncoding:s.google.protobuf.FeatureSet.RepeatedFieldEncoding[e.repeatedFieldEncoding]),null!=e.utf8Validation&&e.hasOwnProperty("utf8Validation")&&(o.utf8Validation=t.enums!==String||void 0===s.google.protobuf.FeatureSet.Utf8Validation[e.utf8Validation]?e.utf8Validation:s.google.protobuf.FeatureSet.Utf8Validation[e.utf8Validation]),null!=e.messageEncoding&&e.hasOwnProperty("messageEncoding")&&(o.messageEncoding=t.enums!==String||void 0===s.google.protobuf.FeatureSet.MessageEncoding[e.messageEncoding]?e.messageEncoding:s.google.protobuf.FeatureSet.MessageEncoding[e.messageEncoding]),null!=e.jsonFormat&&e.hasOwnProperty("jsonFormat")&&(o.jsonFormat=t.enums!==String||void 0===s.google.protobuf.FeatureSet.JsonFormat[e.jsonFormat]?e.jsonFormat:s.google.protobuf.FeatureSet.JsonFormat[e.jsonFormat]),o},A.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},A.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.FeatureSet"},A.FieldPresence=(n={},(e=Object.create(n))[n[0]="FIELD_PRESENCE_UNKNOWN"]="FIELD_PRESENCE_UNKNOWN",e[n[1]="EXPLICIT"]="EXPLICIT",e[n[2]="IMPLICIT"]="IMPLICIT",e[n[3]="LEGACY_REQUIRED"]="LEGACY_REQUIRED",e),A.EnumType=(n={},(e=Object.create(n))[n[0]="ENUM_TYPE_UNKNOWN"]="ENUM_TYPE_UNKNOWN",e[n[1]="OPEN"]="OPEN",e[n[2]="CLOSED"]="CLOSED",e),A.RepeatedFieldEncoding=(n={},(e=Object.create(n))[n[0]="REPEATED_FIELD_ENCODING_UNKNOWN"]="REPEATED_FIELD_ENCODING_UNKNOWN",e[n[1]="PACKED"]="PACKED",e[n[2]="EXPANDED"]="EXPANDED",e),A.Utf8Validation=(n={},(e=Object.create(n))[n[0]="UTF8_VALIDATION_UNKNOWN"]="UTF8_VALIDATION_UNKNOWN",e[n[2]="VERIFY"]="VERIFY",e[n[3]="NONE"]="NONE",e),A.MessageEncoding=(n={},(e=Object.create(n))[n[0]="MESSAGE_ENCODING_UNKNOWN"]="MESSAGE_ENCODING_UNKNOWN",e[n[1]="LENGTH_PREFIXED"]="LENGTH_PREFIXED",e[n[2]="DELIMITED"]="DELIMITED",e),A.JsonFormat=(n={},(e=Object.create(n))[n[0]="JSON_FORMAT_UNKNOWN"]="JSON_FORMAT_UNKNOWN",e[n[1]="ALLOW"]="ALLOW",e[n[2]="LEGACY_BEST_EFFORT"]="LEGACY_BEST_EFFORT",e),A),o.FeatureSetDefaults=(ft.prototype.defaults=a.emptyArray,ft.prototype.minimumEdition=0,ft.prototype.maximumEdition=0,ft.fromObject=function(e){if(e instanceof s.google.protobuf.FeatureSetDefaults)return e;var t=new s.google.protobuf.FeatureSetDefaults;if(e.defaults){if(!Array.isArray(e.defaults))throw TypeError(".google.protobuf.FeatureSetDefaults.defaults: array expected");t.defaults=[];for(var o=0;o>>0,e.seconds.high>>>0).toNumber())),null!=e.nanos&&(t.nanos=0|e.nanos),t)},ht.toObject=function(e,t){var o,r={};return(t=t||{}).defaults&&(a.Long?(o=new a.Long(0,0,!1),r.seconds=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.seconds=t.longs===String?"0":0,r.nanos=0),null!=e.seconds&&e.hasOwnProperty("seconds")&&("number"==typeof e.seconds?r.seconds=t.longs===String?String(e.seconds):e.seconds:r.seconds=t.longs===String?a.Long.prototype.toString.call(e.seconds):t.longs===Number?new a.LongBits(e.seconds.low>>>0,e.seconds.high>>>0).toNumber():e.seconds),null!=e.nanos&&e.hasOwnProperty("nanos")&&(r.nanos=e.nanos),r},ht.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},ht.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.Timestamp"},ht),o.Duration=(St.prototype.seconds=a.Long?a.Long.fromBits(0,0,!1):0,St.prototype.nanos=0,St.fromObject=function(e){var t;return e instanceof s.google.protobuf.Duration?e:(t=new s.google.protobuf.Duration,null!=e.seconds&&(a.Long?(t.seconds=a.Long.fromValue(e.seconds)).unsigned=!1:"string"==typeof e.seconds?t.seconds=parseInt(e.seconds,10):"number"==typeof e.seconds?t.seconds=e.seconds:"object"==typeof e.seconds&&(t.seconds=new a.LongBits(e.seconds.low>>>0,e.seconds.high>>>0).toNumber())),null!=e.nanos&&(t.nanos=0|e.nanos),t)},St.toObject=function(e,t){var o,r={};return(t=t||{}).defaults&&(a.Long?(o=new a.Long(0,0,!1),r.seconds=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.seconds=t.longs===String?"0":0,r.nanos=0),null!=e.seconds&&e.hasOwnProperty("seconds")&&("number"==typeof e.seconds?r.seconds=t.longs===String?String(e.seconds):e.seconds:r.seconds=t.longs===String?a.Long.prototype.toString.call(e.seconds):t.longs===Number?new a.LongBits(e.seconds.low>>>0,e.seconds.high>>>0).toNumber():e.seconds),null!=e.nanos&&e.hasOwnProperty("nanos")&&(r.nanos=e.nanos),r},St.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},St.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.Duration"},St),o.Any=(vt.prototype.type_url="",vt.prototype.value=a.newBuffer([]),vt.fromObject=function(e){var t;return e instanceof s.google.protobuf.Any?e:(t=new s.google.protobuf.Any,null!=e.type_url&&(t.type_url=String(e.type_url)),null!=e.value&&("string"==typeof e.value?a.base64.decode(e.value,t.value=a.newBuffer(a.base64.length(e.value)),0):0<=e.value.length&&(t.value=e.value)),t)},vt.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.type_url="",t.bytes===String?o.value="":(o.value=[],t.bytes!==Array&&(o.value=a.newBuffer(o.value)))),null!=e.type_url&&e.hasOwnProperty("type_url")&&(o.type_url=e.type_url),null!=e.value&&e.hasOwnProperty("value")&&(o.value=t.bytes===String?a.base64.encode(e.value,0,e.value.length):t.bytes===Array?Array.prototype.slice.call(e.value):e.value),o},vt.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},vt.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.Any"},vt),o.Empty=(Et.fromObject=function(e){return e instanceof s.google.protobuf.Empty?e:new s.google.protobuf.Empty},Et.toObject=function(){return{}},Et.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Et.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.Empty"},Et),o.FieldMask=(Tt.prototype.paths=a.emptyArray,Tt.fromObject=function(e){if(e instanceof s.google.protobuf.FieldMask)return e;var t=new s.google.protobuf.FieldMask;if(e.paths){if(!Array.isArray(e.paths))throw TypeError(".google.protobuf.FieldMask.paths: array expected");t.paths=[];for(var o=0;o>>0,e.value.high>>>0).toNumber())),t)},Dt.toObject=function(e,t){var o,r={};return(t=t||{}).defaults&&(a.Long?(o=new a.Long(0,0,!1),r.value=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.value=t.longs===String?"0":0),null!=e.value&&e.hasOwnProperty("value")&&("number"==typeof e.value?r.value=t.longs===String?String(e.value):e.value:r.value=t.longs===String?a.Long.prototype.toString.call(e.value):t.longs===Number?new a.LongBits(e.value.low>>>0,e.value.high>>>0).toNumber():e.value),r},Dt.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Dt.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.Int64Value"},Dt),o.UInt64Value=(wt.prototype.value=a.Long?a.Long.fromBits(0,0,!0):0,wt.fromObject=function(e){var t;return e instanceof s.google.protobuf.UInt64Value?e:(t=new s.google.protobuf.UInt64Value,null!=e.value&&(a.Long?(t.value=a.Long.fromValue(e.value)).unsigned=!0:"string"==typeof e.value?t.value=parseInt(e.value,10):"number"==typeof e.value?t.value=e.value:"object"==typeof e.value&&(t.value=new a.LongBits(e.value.low>>>0,e.value.high>>>0).toNumber(!0))),t)},wt.toObject=function(e,t){var o,r={};return(t=t||{}).defaults&&(a.Long?(o=new a.Long(0,0,!0),r.value=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.value=t.longs===String?"0":0),null!=e.value&&e.hasOwnProperty("value")&&("number"==typeof e.value?r.value=t.longs===String?String(e.value):e.value:r.value=t.longs===String?a.Long.prototype.toString.call(e.value):t.longs===Number?new a.LongBits(e.value.low>>>0,e.value.high>>>0).toNumber(!0):e.value),r},wt.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},wt.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.UInt64Value"},wt),o.Int32Value=(kt.prototype.value=0,kt.fromObject=function(e){var t;return e instanceof s.google.protobuf.Int32Value?e:(t=new s.google.protobuf.Int32Value,null!=e.value&&(t.value=0|e.value),t)},kt.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.value=0),null!=e.value&&e.hasOwnProperty("value")&&(o.value=e.value),o},kt.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},kt.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.Int32Value"},kt),o.UInt32Value=(Rt.prototype.value=0,Rt.fromObject=function(e){var t;return e instanceof s.google.protobuf.UInt32Value?e:(t=new s.google.protobuf.UInt32Value,null!=e.value&&(t.value=e.value>>>0),t)},Rt.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.value=0),null!=e.value&&e.hasOwnProperty("value")&&(o.value=e.value),o},Rt.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Rt.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.UInt32Value"},Rt),o.BoolValue=(Ct.prototype.value=!1,Ct.fromObject=function(e){var t;return e instanceof s.google.protobuf.BoolValue?e:(t=new s.google.protobuf.BoolValue,null!=e.value&&(t.value=Boolean(e.value)),t)},Ct.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.value=!1),null!=e.value&&e.hasOwnProperty("value")&&(o.value=e.value),o},Ct.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Ct.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.BoolValue"},Ct),o.StringValue=(xt.prototype.value="",xt.fromObject=function(e){var t;return e instanceof s.google.protobuf.StringValue?e:(t=new s.google.protobuf.StringValue,null!=e.value&&(t.value=String(e.value)),t)},xt.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.value=""),null!=e.value&&e.hasOwnProperty("value")&&(o.value=e.value),o},xt.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},xt.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.StringValue"},xt),o.BytesValue=(At.prototype.value=a.newBuffer([]),At.fromObject=function(e){var t;return e instanceof s.google.protobuf.BytesValue?e:(t=new s.google.protobuf.BytesValue,null!=e.value&&("string"==typeof e.value?a.base64.decode(e.value,t.value=a.newBuffer(a.base64.length(e.value)),0):0<=e.value.length&&(t.value=e.value)),t)},At.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(t.bytes===String?o.value="":(o.value=[],t.bytes!==Array&&(o.value=a.newBuffer(o.value)))),null!=e.value&&e.hasOwnProperty("value")&&(o.value=t.bytes===String?a.base64.encode(e.value,0,e.value.length):t.bytes===Array?Array.prototype.slice.call(e.value):e.value),o},At.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},At.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.BytesValue"},At),o),L.type=((t={}).DayOfWeek=(i={},(e=Object.create(i))[i[0]="DAY_OF_WEEK_UNSPECIFIED"]="DAY_OF_WEEK_UNSPECIFIED",e[i[1]="MONDAY"]="MONDAY",e[i[2]="TUESDAY"]="TUESDAY",e[i[3]="WEDNESDAY"]="WEDNESDAY",e[i[4]="THURSDAY"]="THURSDAY",e[i[5]="FRIDAY"]="FRIDAY",e[i[6]="SATURDAY"]="SATURDAY",e[i[7]="SUNDAY"]="SUNDAY",e),t.LatLng=(_t.prototype.latitude=0,_t.prototype.longitude=0,_t.fromObject=function(e){var t;return e instanceof s.google.type.LatLng?e:(t=new s.google.type.LatLng,null!=e.latitude&&(t.latitude=Number(e.latitude)),null!=e.longitude&&(t.longitude=Number(e.longitude)),t)},_t.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.latitude=0,o.longitude=0),null!=e.latitude&&e.hasOwnProperty("latitude")&&(o.latitude=t.json&&!isFinite(e.latitude)?String(e.latitude):e.latitude),null!=e.longitude&&e.hasOwnProperty("longitude")&&(o.longitude=t.json&&!isFinite(e.longitude)?String(e.longitude):e.longitude),o},_t.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},_t.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.type.LatLng"},_t),t),L.longrunning=((n={}).Operations=((Lt.prototype=Object.create(r.rpc.Service.prototype)).constructor=Lt,Object.defineProperty(Lt.prototype.listOperations=function e(t,o){return this.rpcCall(e,s.google.longrunning.ListOperationsRequest,s.google.longrunning.ListOperationsResponse,t,o)},"name",{value:"ListOperations"}),Object.defineProperty(Lt.prototype.getOperation=function e(t,o){return this.rpcCall(e,s.google.longrunning.GetOperationRequest,s.google.longrunning.Operation,t,o)},"name",{value:"GetOperation"}),Object.defineProperty(Lt.prototype.deleteOperation=function e(t,o){return this.rpcCall(e,s.google.longrunning.DeleteOperationRequest,s.google.protobuf.Empty,t,o)},"name",{value:"DeleteOperation"}),Object.defineProperty(Lt.prototype.cancelOperation=function e(t,o){return this.rpcCall(e,s.google.longrunning.CancelOperationRequest,s.google.protobuf.Empty,t,o)},"name",{value:"CancelOperation"}),Object.defineProperty(Lt.prototype.waitOperation=function e(t,o){return this.rpcCall(e,s.google.longrunning.WaitOperationRequest,s.google.longrunning.Operation,t,o)},"name",{value:"WaitOperation"}),Lt),n.Operation=(Ft.prototype.name="",Ft.prototype.metadata=null,Ft.prototype.done=!1,Ft.prototype.error=null,Ft.prototype.response=null,Object.defineProperty(Ft.prototype,"result",{get:a.oneOfGetter(o=["error","response"]),set:a.oneOfSetter(o)}),Ft.fromObject=function(e){if(e instanceof s.google.longrunning.Operation)return e;var t=new s.google.longrunning.Operation;if(null!=e.name&&(t.name=String(e.name)),null!=e.metadata){if("object"!=typeof e.metadata)throw TypeError(".google.longrunning.Operation.metadata: object expected");t.metadata=s.google.protobuf.Any.fromObject(e.metadata)}if(null!=e.done&&(t.done=Boolean(e.done)),null!=e.error){if("object"!=typeof e.error)throw TypeError(".google.longrunning.Operation.error: object expected");t.error=s.google.rpc.Status.fromObject(e.error)}if(null!=e.response){if("object"!=typeof e.response)throw TypeError(".google.longrunning.Operation.response: object expected");t.response=s.google.protobuf.Any.fromObject(e.response)}return t},Ft.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.name="",o.metadata=null,o.done=!1),null!=e.name&&e.hasOwnProperty("name")&&(o.name=e.name),null!=e.metadata&&e.hasOwnProperty("metadata")&&(o.metadata=s.google.protobuf.Any.toObject(e.metadata,t)),null!=e.done&&e.hasOwnProperty("done")&&(o.done=e.done),null!=e.error&&e.hasOwnProperty("error")&&(o.error=s.google.rpc.Status.toObject(e.error,t),t.oneofs)&&(o.result="error"),null!=e.response&&e.hasOwnProperty("response")&&(o.response=s.google.protobuf.Any.toObject(e.response,t),t.oneofs)&&(o.result="response"),o},Ft.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Ft.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.longrunning.Operation"},Ft),n.GetOperationRequest=(Ut.prototype.name="",Ut.fromObject=function(e){var t;return e instanceof s.google.longrunning.GetOperationRequest?e:(t=new s.google.longrunning.GetOperationRequest,null!=e.name&&(t.name=String(e.name)),t)},Ut.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.name=""),null!=e.name&&e.hasOwnProperty("name")&&(o.name=e.name),o},Ut.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Ut.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.longrunning.GetOperationRequest"},Ut),n.ListOperationsRequest=(Bt.prototype.name="",Bt.prototype.filter="",Bt.prototype.pageSize=0,Bt.prototype.pageToken="",Bt.fromObject=function(e){var t;return e instanceof s.google.longrunning.ListOperationsRequest?e:(t=new s.google.longrunning.ListOperationsRequest,null!=e.name&&(t.name=String(e.name)),null!=e.filter&&(t.filter=String(e.filter)),null!=e.pageSize&&(t.pageSize=0|e.pageSize),null!=e.pageToken&&(t.pageToken=String(e.pageToken)),t)},Bt.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.filter="",o.pageSize=0,o.pageToken="",o.name=""),null!=e.filter&&e.hasOwnProperty("filter")&&(o.filter=e.filter),null!=e.pageSize&&e.hasOwnProperty("pageSize")&&(o.pageSize=e.pageSize),null!=e.pageToken&&e.hasOwnProperty("pageToken")&&(o.pageToken=e.pageToken),null!=e.name&&e.hasOwnProperty("name")&&(o.name=e.name),o},Bt.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Bt.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.longrunning.ListOperationsRequest"},Bt),n.ListOperationsResponse=(Mt.prototype.operations=a.emptyArray,Mt.prototype.nextPageToken="",Mt.fromObject=function(e){if(e instanceof s.google.longrunning.ListOperationsResponse)return e;var t=new s.google.longrunning.ListOperationsResponse;if(e.operations){if(!Array.isArray(e.operations))throw TypeError(".google.longrunning.ListOperationsResponse.operations: array expected");t.operations=[];for(var o=0;o; + + /** + * Calls ListDocuments. + * @param request ListDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListDocumentsResponse + */ + public listDocuments(request: google.firestore.v1.IListDocumentsRequest, callback: google.firestore.v1.Firestore.ListDocumentsCallback): void; + + /** + * Calls ListDocuments. + * @param request ListDocumentsRequest message or plain object + * @returns Promise + */ + public listDocuments(request: google.firestore.v1.IListDocumentsRequest): Promise; + + /** + * Calls UpdateDocument. + * @param request UpdateDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public updateDocument(request: google.firestore.v1.IUpdateDocumentRequest, callback: google.firestore.v1.Firestore.UpdateDocumentCallback): void; + + /** + * Calls UpdateDocument. + * @param request UpdateDocumentRequest message or plain object + * @returns Promise + */ + public updateDocument(request: google.firestore.v1.IUpdateDocumentRequest): Promise; + + /** + * Calls DeleteDocument. + * @param request DeleteDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteDocument(request: google.firestore.v1.IDeleteDocumentRequest, callback: google.firestore.v1.Firestore.DeleteDocumentCallback): void; + + /** + * Calls DeleteDocument. + * @param request DeleteDocumentRequest message or plain object + * @returns Promise + */ + public deleteDocument(request: google.firestore.v1.IDeleteDocumentRequest): Promise; + + /** + * Calls BatchGetDocuments. + * @param request BatchGetDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchGetDocumentsResponse + */ + public batchGetDocuments(request: google.firestore.v1.IBatchGetDocumentsRequest, callback: google.firestore.v1.Firestore.BatchGetDocumentsCallback): void; + + /** + * Calls BatchGetDocuments. + * @param request BatchGetDocumentsRequest message or plain object + * @returns Promise + */ + public batchGetDocuments(request: google.firestore.v1.IBatchGetDocumentsRequest): Promise; + + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BeginTransactionResponse + */ + public beginTransaction(request: google.firestore.v1.IBeginTransactionRequest, callback: google.firestore.v1.Firestore.BeginTransactionCallback): void; + + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @returns Promise + */ + public beginTransaction(request: google.firestore.v1.IBeginTransactionRequest): Promise; + + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @param callback Node-style callback called with the error, if any, and CommitResponse + */ + public commit(request: google.firestore.v1.ICommitRequest, callback: google.firestore.v1.Firestore.CommitCallback): void; + + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @returns Promise + */ + public commit(request: google.firestore.v1.ICommitRequest): Promise; + + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public rollback(request: google.firestore.v1.IRollbackRequest, callback: google.firestore.v1.Firestore.RollbackCallback): void; + + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @returns Promise + */ + public rollback(request: google.firestore.v1.IRollbackRequest): Promise; + + /** + * Calls RunQuery. + * @param request RunQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and RunQueryResponse + */ + public runQuery(request: google.firestore.v1.IRunQueryRequest, callback: google.firestore.v1.Firestore.RunQueryCallback): void; + + /** + * Calls RunQuery. + * @param request RunQueryRequest message or plain object + * @returns Promise + */ + public runQuery(request: google.firestore.v1.IRunQueryRequest): Promise; + + /** + * Calls RunAggregationQuery. + * @param request RunAggregationQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and RunAggregationQueryResponse + */ + public runAggregationQuery(request: google.firestore.v1.IRunAggregationQueryRequest, callback: google.firestore.v1.Firestore.RunAggregationQueryCallback): void; + + /** + * Calls RunAggregationQuery. + * @param request RunAggregationQueryRequest message or plain object + * @returns Promise + */ + public runAggregationQuery(request: google.firestore.v1.IRunAggregationQueryRequest): Promise; + + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and PartitionQueryResponse + */ + public partitionQuery(request: google.firestore.v1.IPartitionQueryRequest, callback: google.firestore.v1.Firestore.PartitionQueryCallback): void; + + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @returns Promise + */ + public partitionQuery(request: google.firestore.v1.IPartitionQueryRequest): Promise; + + /** + * Calls Write. + * @param request WriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and WriteResponse + */ + public write(request: google.firestore.v1.IWriteRequest, callback: google.firestore.v1.Firestore.WriteCallback): void; + + /** + * Calls Write. + * @param request WriteRequest message or plain object + * @returns Promise + */ + public write(request: google.firestore.v1.IWriteRequest): Promise; + + /** + * Calls Listen. + * @param request ListenRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListenResponse + */ + public listen(request: google.firestore.v1.IListenRequest, callback: google.firestore.v1.Firestore.ListenCallback): void; + + /** + * Calls Listen. + * @param request ListenRequest message or plain object + * @returns Promise + */ + public listen(request: google.firestore.v1.IListenRequest): Promise; + + /** + * Calls ListCollectionIds. + * @param request ListCollectionIdsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListCollectionIdsResponse + */ + public listCollectionIds(request: google.firestore.v1.IListCollectionIdsRequest, callback: google.firestore.v1.Firestore.ListCollectionIdsCallback): void; + + /** + * Calls ListCollectionIds. + * @param request ListCollectionIdsRequest message or plain object + * @returns Promise + */ + public listCollectionIds(request: google.firestore.v1.IListCollectionIdsRequest): Promise; + + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchWriteResponse + */ + public batchWrite(request: google.firestore.v1.IBatchWriteRequest, callback: google.firestore.v1.Firestore.BatchWriteCallback): void; + + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @returns Promise + */ + public batchWrite(request: google.firestore.v1.IBatchWriteRequest): Promise; + + /** + * Calls CreateDocument. + * @param request CreateDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public createDocument(request: google.firestore.v1.ICreateDocumentRequest, callback: google.firestore.v1.Firestore.CreateDocumentCallback): void; + + /** + * Calls CreateDocument. + * @param request CreateDocumentRequest message or plain object + * @returns Promise + */ + public createDocument(request: google.firestore.v1.ICreateDocumentRequest): Promise; + } + + namespace Firestore { + + /** + * Callback as used by {@link google.firestore.v1.Firestore#getDocument}. + * @param error Error, if any + * @param [response] Document + */ + type GetDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#listDocuments}. + * @param error Error, if any + * @param [response] ListDocumentsResponse + */ + type ListDocumentsCallback = (error: (Error|null), response?: google.firestore.v1.ListDocumentsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#updateDocument}. + * @param error Error, if any + * @param [response] Document + */ + type UpdateDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#deleteDocument}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteDocumentCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#batchGetDocuments}. + * @param error Error, if any + * @param [response] BatchGetDocumentsResponse + */ + type BatchGetDocumentsCallback = (error: (Error|null), response?: google.firestore.v1.BatchGetDocumentsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#beginTransaction}. + * @param error Error, if any + * @param [response] BeginTransactionResponse + */ + type BeginTransactionCallback = (error: (Error|null), response?: google.firestore.v1.BeginTransactionResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#commit}. + * @param error Error, if any + * @param [response] CommitResponse + */ + type CommitCallback = (error: (Error|null), response?: google.firestore.v1.CommitResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#rollback}. + * @param error Error, if any + * @param [response] Empty + */ + type RollbackCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#runQuery}. + * @param error Error, if any + * @param [response] RunQueryResponse + */ + type RunQueryCallback = (error: (Error|null), response?: google.firestore.v1.RunQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#runAggregationQuery}. + * @param error Error, if any + * @param [response] RunAggregationQueryResponse + */ + type RunAggregationQueryCallback = (error: (Error|null), response?: google.firestore.v1.RunAggregationQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#partitionQuery}. + * @param error Error, if any + * @param [response] PartitionQueryResponse + */ + type PartitionQueryCallback = (error: (Error|null), response?: google.firestore.v1.PartitionQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#write}. + * @param error Error, if any + * @param [response] WriteResponse + */ + type WriteCallback = (error: (Error|null), response?: google.firestore.v1.WriteResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#listen}. + * @param error Error, if any + * @param [response] ListenResponse + */ + type ListenCallback = (error: (Error|null), response?: google.firestore.v1.ListenResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#listCollectionIds}. + * @param error Error, if any + * @param [response] ListCollectionIdsResponse + */ + type ListCollectionIdsCallback = (error: (Error|null), response?: google.firestore.v1.ListCollectionIdsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#batchWrite}. + * @param error Error, if any + * @param [response] BatchWriteResponse + */ + type BatchWriteCallback = (error: (Error|null), response?: google.firestore.v1.BatchWriteResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#createDocument}. + * @param error Error, if any + * @param [response] Document + */ + type CreateDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + } + + /** Properties of a GetDocumentRequest. */ + interface IGetDocumentRequest { + + /** GetDocumentRequest name */ + name?: (string|null); + + /** GetDocumentRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + + /** GetDocumentRequest transaction */ + transaction?: (Uint8Array|null); + + /** GetDocumentRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a GetDocumentRequest. */ + class GetDocumentRequest implements IGetDocumentRequest { + + /** + * Constructs a new GetDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IGetDocumentRequest); + + /** GetDocumentRequest name. */ + public name: string; + + /** GetDocumentRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** GetDocumentRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** GetDocumentRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** GetDocumentRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"readTime"); + + /** + * Creates a GetDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.GetDocumentRequest; + + /** + * Creates a plain object from a GetDocumentRequest message. Also converts values to other types if specified. + * @param message GetDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.GetDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDocumentsRequest. */ + interface IListDocumentsRequest { + + /** ListDocumentsRequest parent */ + parent?: (string|null); + + /** ListDocumentsRequest collectionId */ + collectionId?: (string|null); + + /** ListDocumentsRequest pageSize */ + pageSize?: (number|null); + + /** ListDocumentsRequest pageToken */ + pageToken?: (string|null); + + /** ListDocumentsRequest orderBy */ + orderBy?: (string|null); + + /** ListDocumentsRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + + /** ListDocumentsRequest transaction */ + transaction?: (Uint8Array|null); + + /** ListDocumentsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** ListDocumentsRequest showMissing */ + showMissing?: (boolean|null); + } + + /** Represents a ListDocumentsRequest. */ + class ListDocumentsRequest implements IListDocumentsRequest { + + /** + * Constructs a new ListDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListDocumentsRequest); + + /** ListDocumentsRequest parent. */ + public parent: string; + + /** ListDocumentsRequest collectionId. */ + public collectionId: string; + + /** ListDocumentsRequest pageSize. */ + public pageSize: number; + + /** ListDocumentsRequest pageToken. */ + public pageToken: string; + + /** ListDocumentsRequest orderBy. */ + public orderBy: string; + + /** ListDocumentsRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** ListDocumentsRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** ListDocumentsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ListDocumentsRequest showMissing. */ + public showMissing: boolean; + + /** ListDocumentsRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"readTime"); + + /** + * Creates a ListDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListDocumentsRequest; + + /** + * Creates a plain object from a ListDocumentsRequest message. Also converts values to other types if specified. + * @param message ListDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDocumentsResponse. */ + interface IListDocumentsResponse { + + /** ListDocumentsResponse documents */ + documents?: (google.firestore.v1.IDocument[]|null); + + /** ListDocumentsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListDocumentsResponse. */ + class ListDocumentsResponse implements IListDocumentsResponse { + + /** + * Constructs a new ListDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListDocumentsResponse); + + /** ListDocumentsResponse documents. */ + public documents: google.firestore.v1.IDocument[]; + + /** ListDocumentsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListDocumentsResponse; + + /** + * Creates a plain object from a ListDocumentsResponse message. Also converts values to other types if specified. + * @param message ListDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDocumentRequest. */ + interface ICreateDocumentRequest { + + /** CreateDocumentRequest parent */ + parent?: (string|null); + + /** CreateDocumentRequest collectionId */ + collectionId?: (string|null); + + /** CreateDocumentRequest documentId */ + documentId?: (string|null); + + /** CreateDocumentRequest document */ + document?: (google.firestore.v1.IDocument|null); + + /** CreateDocumentRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + } + + /** Represents a CreateDocumentRequest. */ + class CreateDocumentRequest implements ICreateDocumentRequest { + + /** + * Constructs a new CreateDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICreateDocumentRequest); + + /** CreateDocumentRequest parent. */ + public parent: string; + + /** CreateDocumentRequest collectionId. */ + public collectionId: string; + + /** CreateDocumentRequest documentId. */ + public documentId: string; + + /** CreateDocumentRequest document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** CreateDocumentRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** + * Creates a CreateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.CreateDocumentRequest; + + /** + * Creates a plain object from a CreateDocumentRequest message. Also converts values to other types if specified. + * @param message CreateDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.CreateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDocumentRequest. */ + interface IUpdateDocumentRequest { + + /** UpdateDocumentRequest document */ + document?: (google.firestore.v1.IDocument|null); + + /** UpdateDocumentRequest updateMask */ + updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest currentDocument */ + currentDocument?: (google.firestore.v1.IPrecondition|null); + } + + /** Represents an UpdateDocumentRequest. */ + class UpdateDocumentRequest implements IUpdateDocumentRequest { + + /** + * Constructs a new UpdateDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IUpdateDocumentRequest); + + /** UpdateDocumentRequest document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** UpdateDocumentRequest updateMask. */ + public updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest currentDocument. */ + public currentDocument?: (google.firestore.v1.IPrecondition|null); + + /** + * Creates an UpdateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.UpdateDocumentRequest; + + /** + * Creates a plain object from an UpdateDocumentRequest message. Also converts values to other types if specified. + * @param message UpdateDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.UpdateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDocumentRequest. */ + interface IDeleteDocumentRequest { + + /** DeleteDocumentRequest name */ + name?: (string|null); + + /** DeleteDocumentRequest currentDocument */ + currentDocument?: (google.firestore.v1.IPrecondition|null); + } + + /** Represents a DeleteDocumentRequest. */ + class DeleteDocumentRequest implements IDeleteDocumentRequest { + + /** + * Constructs a new DeleteDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDeleteDocumentRequest); + + /** DeleteDocumentRequest name. */ + public name: string; + + /** DeleteDocumentRequest currentDocument. */ + public currentDocument?: (google.firestore.v1.IPrecondition|null); + + /** + * Creates a DeleteDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DeleteDocumentRequest; + + /** + * Creates a plain object from a DeleteDocumentRequest message. Also converts values to other types if specified. + * @param message DeleteDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DeleteDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchGetDocumentsRequest. */ + interface IBatchGetDocumentsRequest { + + /** BatchGetDocumentsRequest database */ + database?: (string|null); + + /** BatchGetDocumentsRequest documents */ + documents?: (string[]|null); + + /** BatchGetDocumentsRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + + /** BatchGetDocumentsRequest transaction */ + transaction?: (Uint8Array|null); + + /** BatchGetDocumentsRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** BatchGetDocumentsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BatchGetDocumentsRequest. */ + class BatchGetDocumentsRequest implements IBatchGetDocumentsRequest { + + /** + * Constructs a new BatchGetDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchGetDocumentsRequest); + + /** BatchGetDocumentsRequest database. */ + public database: string; + + /** BatchGetDocumentsRequest documents. */ + public documents: string[]; + + /** BatchGetDocumentsRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** BatchGetDocumentsRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** BatchGetDocumentsRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** BatchGetDocumentsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BatchGetDocumentsRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a BatchGetDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchGetDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchGetDocumentsRequest; + + /** + * Creates a plain object from a BatchGetDocumentsRequest message. Also converts values to other types if specified. + * @param message BatchGetDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchGetDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchGetDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchGetDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchGetDocumentsResponse. */ + interface IBatchGetDocumentsResponse { + + /** BatchGetDocumentsResponse found */ + found?: (google.firestore.v1.IDocument|null); + + /** BatchGetDocumentsResponse missing */ + missing?: (string|null); + + /** BatchGetDocumentsResponse transaction */ + transaction?: (Uint8Array|null); + + /** BatchGetDocumentsResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BatchGetDocumentsResponse. */ + class BatchGetDocumentsResponse implements IBatchGetDocumentsResponse { + + /** + * Constructs a new BatchGetDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchGetDocumentsResponse); + + /** BatchGetDocumentsResponse found. */ + public found?: (google.firestore.v1.IDocument|null); + + /** BatchGetDocumentsResponse missing. */ + public missing?: (string|null); + + /** BatchGetDocumentsResponse transaction. */ + public transaction: Uint8Array; + + /** BatchGetDocumentsResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BatchGetDocumentsResponse result. */ + public result?: ("found"|"missing"); + + /** + * Creates a BatchGetDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchGetDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchGetDocumentsResponse; + + /** + * Creates a plain object from a BatchGetDocumentsResponse message. Also converts values to other types if specified. + * @param message BatchGetDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchGetDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchGetDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchGetDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BeginTransactionRequest. */ + interface IBeginTransactionRequest { + + /** BeginTransactionRequest database */ + database?: (string|null); + + /** BeginTransactionRequest options */ + options?: (google.firestore.v1.ITransactionOptions|null); + } + + /** Represents a BeginTransactionRequest. */ + class BeginTransactionRequest implements IBeginTransactionRequest { + + /** + * Constructs a new BeginTransactionRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBeginTransactionRequest); + + /** BeginTransactionRequest database. */ + public database: string; + + /** BeginTransactionRequest options. */ + public options?: (google.firestore.v1.ITransactionOptions|null); + + /** + * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BeginTransactionRequest; + + /** + * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. + * @param message BeginTransactionRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BeginTransactionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BeginTransactionRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BeginTransactionResponse. */ + interface IBeginTransactionResponse { + + /** BeginTransactionResponse transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a BeginTransactionResponse. */ + class BeginTransactionResponse implements IBeginTransactionResponse { + + /** + * Constructs a new BeginTransactionResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBeginTransactionResponse); + + /** BeginTransactionResponse transaction. */ + public transaction: Uint8Array; + + /** + * Creates a BeginTransactionResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BeginTransactionResponse; + + /** + * Creates a plain object from a BeginTransactionResponse message. Also converts values to other types if specified. + * @param message BeginTransactionResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BeginTransactionResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BeginTransactionResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommitRequest. */ + interface ICommitRequest { + + /** CommitRequest database */ + database?: (string|null); + + /** CommitRequest writes */ + writes?: (google.firestore.v1.IWrite[]|null); + + /** CommitRequest transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a CommitRequest. */ + class CommitRequest implements ICommitRequest { + + /** + * Constructs a new CommitRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICommitRequest); + + /** CommitRequest database. */ + public database: string; + + /** CommitRequest writes. */ + public writes: google.firestore.v1.IWrite[]; + + /** CommitRequest transaction. */ + public transaction: Uint8Array; + + /** + * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.CommitRequest; + + /** + * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. + * @param message CommitRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.CommitRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommitResponse. */ + interface ICommitResponse { + + /** CommitResponse writeResults */ + writeResults?: (google.firestore.v1.IWriteResult[]|null); + + /** CommitResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a CommitResponse. */ + class CommitResponse implements ICommitResponse { + + /** + * Constructs a new CommitResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICommitResponse); + + /** CommitResponse writeResults. */ + public writeResults: google.firestore.v1.IWriteResult[]; + + /** CommitResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.CommitResponse; + + /** + * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. + * @param message CommitResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.CommitResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RollbackRequest. */ + interface IRollbackRequest { + + /** RollbackRequest database */ + database?: (string|null); + + /** RollbackRequest transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a RollbackRequest. */ + class RollbackRequest implements IRollbackRequest { + + /** + * Constructs a new RollbackRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRollbackRequest); + + /** RollbackRequest database. */ + public database: string; + + /** RollbackRequest transaction. */ + public transaction: Uint8Array; + + /** + * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RollbackRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RollbackRequest; + + /** + * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. + * @param message RollbackRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RollbackRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RollbackRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RollbackRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunQueryRequest. */ + interface IRunQueryRequest { + + /** RunQueryRequest parent */ + parent?: (string|null); + + /** RunQueryRequest structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** RunQueryRequest transaction */ + transaction?: (Uint8Array|null); + + /** RunQueryRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** RunQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryRequest explainOptions */ + explainOptions?: (google.firestore.v1.IExplainOptions|null); + } + + /** Represents a RunQueryRequest. */ + class RunQueryRequest implements IRunQueryRequest { + + /** + * Constructs a new RunQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunQueryRequest); + + /** RunQueryRequest parent. */ + public parent: string; + + /** RunQueryRequest structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** RunQueryRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** RunQueryRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** RunQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryRequest explainOptions. */ + public explainOptions?: (google.firestore.v1.IExplainOptions|null); + + /** RunQueryRequest queryType. */ + public queryType?: "structuredQuery"; + + /** RunQueryRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunQueryRequest; + + /** + * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. + * @param message RunQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunQueryResponse. */ + interface IRunQueryResponse { + + /** RunQueryResponse transaction */ + transaction?: (Uint8Array|null); + + /** RunQueryResponse document */ + document?: (google.firestore.v1.IDocument|null); + + /** RunQueryResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryResponse skippedResults */ + skippedResults?: (number|null); + + /** RunQueryResponse done */ + done?: (boolean|null); + + /** RunQueryResponse explainMetrics */ + explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + } + + /** Represents a RunQueryResponse. */ + class RunQueryResponse implements IRunQueryResponse { + + /** + * Constructs a new RunQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunQueryResponse); + + /** RunQueryResponse transaction. */ + public transaction: Uint8Array; + + /** RunQueryResponse document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** RunQueryResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryResponse skippedResults. */ + public skippedResults: number; + + /** RunQueryResponse done. */ + public done?: (boolean|null); + + /** RunQueryResponse explainMetrics. */ + public explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + + /** RunQueryResponse continuationSelector. */ + public continuationSelector?: "done"; + + /** + * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunQueryResponse; + + /** + * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. + * @param message RunQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunAggregationQueryRequest. */ + interface IRunAggregationQueryRequest { + + /** RunAggregationQueryRequest parent */ + parent?: (string|null); + + /** RunAggregationQueryRequest structuredAggregationQuery */ + structuredAggregationQuery?: (google.firestore.v1.IStructuredAggregationQuery|null); + + /** RunAggregationQueryRequest transaction */ + transaction?: (Uint8Array|null); + + /** RunAggregationQueryRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** RunAggregationQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryRequest explainOptions */ + explainOptions?: (google.firestore.v1.IExplainOptions|null); + } + + /** Represents a RunAggregationQueryRequest. */ + class RunAggregationQueryRequest implements IRunAggregationQueryRequest { + + /** + * Constructs a new RunAggregationQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunAggregationQueryRequest); + + /** RunAggregationQueryRequest parent. */ + public parent: string; + + /** RunAggregationQueryRequest structuredAggregationQuery. */ + public structuredAggregationQuery?: (google.firestore.v1.IStructuredAggregationQuery|null); + + /** RunAggregationQueryRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** RunAggregationQueryRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** RunAggregationQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryRequest explainOptions. */ + public explainOptions?: (google.firestore.v1.IExplainOptions|null); + + /** RunAggregationQueryRequest queryType. */ + public queryType?: "structuredAggregationQuery"; + + /** RunAggregationQueryRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a RunAggregationQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunAggregationQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunAggregationQueryRequest; + + /** + * Creates a plain object from a RunAggregationQueryRequest message. Also converts values to other types if specified. + * @param message RunAggregationQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunAggregationQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunAggregationQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunAggregationQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunAggregationQueryResponse. */ + interface IRunAggregationQueryResponse { + + /** RunAggregationQueryResponse result */ + result?: (google.firestore.v1.IAggregationResult|null); + + /** RunAggregationQueryResponse transaction */ + transaction?: (Uint8Array|null); + + /** RunAggregationQueryResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryResponse explainMetrics */ + explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + } + + /** Represents a RunAggregationQueryResponse. */ + class RunAggregationQueryResponse implements IRunAggregationQueryResponse { + + /** + * Constructs a new RunAggregationQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunAggregationQueryResponse); + + /** RunAggregationQueryResponse result. */ + public result?: (google.firestore.v1.IAggregationResult|null); + + /** RunAggregationQueryResponse transaction. */ + public transaction: Uint8Array; + + /** RunAggregationQueryResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryResponse explainMetrics. */ + public explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + + /** + * Creates a RunAggregationQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunAggregationQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunAggregationQueryResponse; + + /** + * Creates a plain object from a RunAggregationQueryResponse message. Also converts values to other types if specified. + * @param message RunAggregationQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunAggregationQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunAggregationQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunAggregationQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionQueryRequest. */ + interface IPartitionQueryRequest { + + /** PartitionQueryRequest parent */ + parent?: (string|null); + + /** PartitionQueryRequest structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** PartitionQueryRequest partitionCount */ + partitionCount?: (number|string|null); + + /** PartitionQueryRequest pageToken */ + pageToken?: (string|null); + + /** PartitionQueryRequest pageSize */ + pageSize?: (number|null); + + /** PartitionQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a PartitionQueryRequest. */ + class PartitionQueryRequest implements IPartitionQueryRequest { + + /** + * Constructs a new PartitionQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPartitionQueryRequest); + + /** PartitionQueryRequest parent. */ + public parent: string; + + /** PartitionQueryRequest structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** PartitionQueryRequest partitionCount. */ + public partitionCount: (number|string); + + /** PartitionQueryRequest pageToken. */ + public pageToken: string; + + /** PartitionQueryRequest pageSize. */ + public pageSize: number; + + /** PartitionQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** PartitionQueryRequest queryType. */ + public queryType?: "structuredQuery"; + + /** PartitionQueryRequest consistencySelector. */ + public consistencySelector?: "readTime"; + + /** + * Creates a PartitionQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.PartitionQueryRequest; + + /** + * Creates a plain object from a PartitionQueryRequest message. Also converts values to other types if specified. + * @param message PartitionQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.PartitionQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionQueryResponse. */ + interface IPartitionQueryResponse { + + /** PartitionQueryResponse partitions */ + partitions?: (google.firestore.v1.ICursor[]|null); + + /** PartitionQueryResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a PartitionQueryResponse. */ + class PartitionQueryResponse implements IPartitionQueryResponse { + + /** + * Constructs a new PartitionQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPartitionQueryResponse); + + /** PartitionQueryResponse partitions. */ + public partitions: google.firestore.v1.ICursor[]; + + /** PartitionQueryResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a PartitionQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.PartitionQueryResponse; + + /** + * Creates a plain object from a PartitionQueryResponse message. Also converts values to other types if specified. + * @param message PartitionQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.PartitionQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WriteRequest. */ + interface IWriteRequest { + + /** WriteRequest database */ + database?: (string|null); + + /** WriteRequest streamId */ + streamId?: (string|null); + + /** WriteRequest writes */ + writes?: (google.firestore.v1.IWrite[]|null); + + /** WriteRequest streamToken */ + streamToken?: (Uint8Array|null); + + /** WriteRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a WriteRequest. */ + class WriteRequest implements IWriteRequest { + + /** + * Constructs a new WriteRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWriteRequest); + + /** WriteRequest database. */ + public database: string; + + /** WriteRequest streamId. */ + public streamId: string; + + /** WriteRequest writes. */ + public writes: google.firestore.v1.IWrite[]; + + /** WriteRequest streamToken. */ + public streamToken: Uint8Array; + + /** WriteRequest labels. */ + public labels: { [k: string]: string }; + + /** + * Creates a WriteRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteRequest; + + /** + * Creates a plain object from a WriteRequest message. Also converts values to other types if specified. + * @param message WriteRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.WriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WriteResponse. */ + interface IWriteResponse { + + /** WriteResponse streamId */ + streamId?: (string|null); + + /** WriteResponse streamToken */ + streamToken?: (Uint8Array|null); + + /** WriteResponse writeResults */ + writeResults?: (google.firestore.v1.IWriteResult[]|null); + + /** WriteResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a WriteResponse. */ + class WriteResponse implements IWriteResponse { + + /** + * Constructs a new WriteResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWriteResponse); + + /** WriteResponse streamId. */ + public streamId: string; + + /** WriteResponse streamToken. */ + public streamToken: Uint8Array; + + /** WriteResponse writeResults. */ + public writeResults: google.firestore.v1.IWriteResult[]; + + /** WriteResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a WriteResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteResponse; + + /** + * Creates a plain object from a WriteResponse message. Also converts values to other types if specified. + * @param message WriteResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.WriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListenRequest. */ + interface IListenRequest { + + /** ListenRequest database */ + database?: (string|null); + + /** ListenRequest addTarget */ + addTarget?: (google.firestore.v1.ITarget|null); + + /** ListenRequest removeTarget */ + removeTarget?: (number|null); + + /** ListenRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a ListenRequest. */ + class ListenRequest implements IListenRequest { + + /** + * Constructs a new ListenRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListenRequest); + + /** ListenRequest database. */ + public database: string; + + /** ListenRequest addTarget. */ + public addTarget?: (google.firestore.v1.ITarget|null); + + /** ListenRequest removeTarget. */ + public removeTarget?: (number|null); + + /** ListenRequest labels. */ + public labels: { [k: string]: string }; + + /** ListenRequest targetChange. */ + public targetChange?: ("addTarget"|"removeTarget"); + + /** + * Creates a ListenRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListenRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListenRequest; + + /** + * Creates a plain object from a ListenRequest message. Also converts values to other types if specified. + * @param message ListenRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListenRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListenRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListenRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListenResponse. */ + interface IListenResponse { + + /** ListenResponse targetChange */ + targetChange?: (google.firestore.v1.ITargetChange|null); + + /** ListenResponse documentChange */ + documentChange?: (google.firestore.v1.IDocumentChange|null); + + /** ListenResponse documentDelete */ + documentDelete?: (google.firestore.v1.IDocumentDelete|null); + + /** ListenResponse documentRemove */ + documentRemove?: (google.firestore.v1.IDocumentRemove|null); + + /** ListenResponse filter */ + filter?: (google.firestore.v1.IExistenceFilter|null); + } + + /** Represents a ListenResponse. */ + class ListenResponse implements IListenResponse { + + /** + * Constructs a new ListenResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListenResponse); + + /** ListenResponse targetChange. */ + public targetChange?: (google.firestore.v1.ITargetChange|null); + + /** ListenResponse documentChange. */ + public documentChange?: (google.firestore.v1.IDocumentChange|null); + + /** ListenResponse documentDelete. */ + public documentDelete?: (google.firestore.v1.IDocumentDelete|null); + + /** ListenResponse documentRemove. */ + public documentRemove?: (google.firestore.v1.IDocumentRemove|null); + + /** ListenResponse filter. */ + public filter?: (google.firestore.v1.IExistenceFilter|null); + + /** ListenResponse responseType. */ + public responseType?: ("targetChange"|"documentChange"|"documentDelete"|"documentRemove"|"filter"); + + /** + * Creates a ListenResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListenResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListenResponse; + + /** + * Creates a plain object from a ListenResponse message. Also converts values to other types if specified. + * @param message ListenResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListenResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListenResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListenResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Target. */ + interface ITarget { + + /** Target query */ + query?: (google.firestore.v1.Target.IQueryTarget|null); + + /** Target documents */ + documents?: (google.firestore.v1.Target.IDocumentsTarget|null); + + /** Target resumeToken */ + resumeToken?: (Uint8Array|null); + + /** Target readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** Target targetId */ + targetId?: (number|null); + + /** Target once */ + once?: (boolean|null); + + /** Target expectedCount */ + expectedCount?: (google.protobuf.IInt32Value|null); + } + + /** Represents a Target. */ + class Target implements ITarget { + + /** + * Constructs a new Target. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ITarget); + + /** Target query. */ + public query?: (google.firestore.v1.Target.IQueryTarget|null); + + /** Target documents. */ + public documents?: (google.firestore.v1.Target.IDocumentsTarget|null); + + /** Target resumeToken. */ + public resumeToken?: (Uint8Array|null); + + /** Target readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** Target targetId. */ + public targetId: number; + + /** Target once. */ + public once: boolean; + + /** Target expectedCount. */ + public expectedCount?: (google.protobuf.IInt32Value|null); + + /** Target targetType. */ + public targetType?: ("query"|"documents"); + + /** Target resumeType. */ + public resumeType?: ("resumeToken"|"readTime"); + + /** + * Creates a Target message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Target + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target; + + /** + * Creates a plain object from a Target message. Also converts values to other types if specified. + * @param message Target + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Target, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Target to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Target + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Target { + + /** Properties of a DocumentsTarget. */ + interface IDocumentsTarget { + + /** DocumentsTarget documents */ + documents?: (string[]|null); + } + + /** Represents a DocumentsTarget. */ + class DocumentsTarget implements IDocumentsTarget { + + /** + * Constructs a new DocumentsTarget. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.Target.IDocumentsTarget); + + /** DocumentsTarget documents. */ + public documents: string[]; + + /** + * Creates a DocumentsTarget message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentsTarget + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target.DocumentsTarget; + + /** + * Creates a plain object from a DocumentsTarget message. Also converts values to other types if specified. + * @param message DocumentsTarget + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Target.DocumentsTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentsTarget to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentsTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a QueryTarget. */ + interface IQueryTarget { + + /** QueryTarget parent */ + parent?: (string|null); + + /** QueryTarget structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + } + + /** Represents a QueryTarget. */ + class QueryTarget implements IQueryTarget { + + /** + * Constructs a new QueryTarget. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.Target.IQueryTarget); + + /** QueryTarget parent. */ + public parent: string; + + /** QueryTarget structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** QueryTarget queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a QueryTarget message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns QueryTarget + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target.QueryTarget; + + /** + * Creates a plain object from a QueryTarget message. Also converts values to other types if specified. + * @param message QueryTarget + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Target.QueryTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this QueryTarget to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for QueryTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a TargetChange. */ + interface ITargetChange { + + /** TargetChange targetChangeType */ + targetChangeType?: (google.firestore.v1.TargetChange.TargetChangeType|null); + + /** TargetChange targetIds */ + targetIds?: (number[]|null); + + /** TargetChange cause */ + cause?: (google.rpc.IStatus|null); + + /** TargetChange resumeToken */ + resumeToken?: (Uint8Array|null); + + /** TargetChange readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a TargetChange. */ + class TargetChange implements ITargetChange { + + /** + * Constructs a new TargetChange. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ITargetChange); + + /** TargetChange targetChangeType. */ + public targetChangeType: google.firestore.v1.TargetChange.TargetChangeType; + + /** TargetChange targetIds. */ + public targetIds: number[]; + + /** TargetChange cause. */ + public cause?: (google.rpc.IStatus|null); + + /** TargetChange resumeToken. */ + public resumeToken: Uint8Array; + + /** TargetChange readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a TargetChange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TargetChange + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TargetChange; + + /** + * Creates a plain object from a TargetChange message. Also converts values to other types if specified. + * @param message TargetChange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.TargetChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TargetChange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TargetChange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TargetChange { + + /** TargetChangeType enum. */ + type TargetChangeType = + "NO_CHANGE"| "ADD"| "REMOVE"| "CURRENT"| "RESET"; + } + + /** Properties of a ListCollectionIdsRequest. */ + interface IListCollectionIdsRequest { + + /** ListCollectionIdsRequest parent */ + parent?: (string|null); + + /** ListCollectionIdsRequest pageSize */ + pageSize?: (number|null); + + /** ListCollectionIdsRequest pageToken */ + pageToken?: (string|null); + + /** ListCollectionIdsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a ListCollectionIdsRequest. */ + class ListCollectionIdsRequest implements IListCollectionIdsRequest { + + /** + * Constructs a new ListCollectionIdsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListCollectionIdsRequest); + + /** ListCollectionIdsRequest parent. */ + public parent: string; + + /** ListCollectionIdsRequest pageSize. */ + public pageSize: number; + + /** ListCollectionIdsRequest pageToken. */ + public pageToken: string; + + /** ListCollectionIdsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ListCollectionIdsRequest consistencySelector. */ + public consistencySelector?: "readTime"; + + /** + * Creates a ListCollectionIdsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCollectionIdsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListCollectionIdsRequest; + + /** + * Creates a plain object from a ListCollectionIdsRequest message. Also converts values to other types if specified. + * @param message ListCollectionIdsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListCollectionIdsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCollectionIdsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCollectionIdsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListCollectionIdsResponse. */ + interface IListCollectionIdsResponse { + + /** ListCollectionIdsResponse collectionIds */ + collectionIds?: (string[]|null); + + /** ListCollectionIdsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListCollectionIdsResponse. */ + class ListCollectionIdsResponse implements IListCollectionIdsResponse { + + /** + * Constructs a new ListCollectionIdsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListCollectionIdsResponse); + + /** ListCollectionIdsResponse collectionIds. */ + public collectionIds: string[]; + + /** ListCollectionIdsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListCollectionIdsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCollectionIdsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListCollectionIdsResponse; + + /** + * Creates a plain object from a ListCollectionIdsResponse message. Also converts values to other types if specified. + * @param message ListCollectionIdsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListCollectionIdsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCollectionIdsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCollectionIdsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchWriteRequest. */ + interface IBatchWriteRequest { + + /** BatchWriteRequest database */ + database?: (string|null); + + /** BatchWriteRequest writes */ + writes?: (google.firestore.v1.IWrite[]|null); + + /** BatchWriteRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a BatchWriteRequest. */ + class BatchWriteRequest implements IBatchWriteRequest { + + /** + * Constructs a new BatchWriteRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchWriteRequest); + + /** BatchWriteRequest database. */ + public database: string; + + /** BatchWriteRequest writes. */ + public writes: google.firestore.v1.IWrite[]; + + /** BatchWriteRequest labels. */ + public labels: { [k: string]: string }; + + /** + * Creates a BatchWriteRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchWriteRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchWriteRequest; + + /** + * Creates a plain object from a BatchWriteRequest message. Also converts values to other types if specified. + * @param message BatchWriteRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchWriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchWriteRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchWriteResponse. */ + interface IBatchWriteResponse { + + /** BatchWriteResponse writeResults */ + writeResults?: (google.firestore.v1.IWriteResult[]|null); + + /** BatchWriteResponse status */ + status?: (google.rpc.IStatus[]|null); + } + + /** Represents a BatchWriteResponse. */ + class BatchWriteResponse implements IBatchWriteResponse { + + /** + * Constructs a new BatchWriteResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchWriteResponse); + + /** BatchWriteResponse writeResults. */ + public writeResults: google.firestore.v1.IWriteResult[]; + + /** BatchWriteResponse status. */ + public status: google.rpc.IStatus[]; + + /** + * Creates a BatchWriteResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchWriteResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchWriteResponse; + + /** + * Creates a plain object from a BatchWriteResponse message. Also converts values to other types if specified. + * @param message BatchWriteResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchWriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchWriteResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StructuredQuery. */ + interface IStructuredQuery { + + /** StructuredQuery select */ + select?: (google.firestore.v1.StructuredQuery.IProjection|null); + + /** StructuredQuery from */ + from?: (google.firestore.v1.StructuredQuery.ICollectionSelector[]|null); + + /** StructuredQuery where */ + where?: (google.firestore.v1.StructuredQuery.IFilter|null); + + /** StructuredQuery orderBy */ + orderBy?: (google.firestore.v1.StructuredQuery.IOrder[]|null); + + /** StructuredQuery startAt */ + startAt?: (google.firestore.v1.ICursor|null); + + /** StructuredQuery endAt */ + endAt?: (google.firestore.v1.ICursor|null); + + /** StructuredQuery offset */ + offset?: (number|null); + + /** StructuredQuery limit */ + limit?: (google.protobuf.IInt32Value|null); + + /** StructuredQuery findNearest */ + findNearest?: (google.firestore.v1.StructuredQuery.IFindNearest|null); + } + + /** Represents a StructuredQuery. */ + class StructuredQuery implements IStructuredQuery { + + /** + * Constructs a new StructuredQuery. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IStructuredQuery); + + /** StructuredQuery select. */ + public select?: (google.firestore.v1.StructuredQuery.IProjection|null); + + /** StructuredQuery from. */ + public from: google.firestore.v1.StructuredQuery.ICollectionSelector[]; + + /** StructuredQuery where. */ + public where?: (google.firestore.v1.StructuredQuery.IFilter|null); + + /** StructuredQuery orderBy. */ + public orderBy: google.firestore.v1.StructuredQuery.IOrder[]; + + /** StructuredQuery startAt. */ + public startAt?: (google.firestore.v1.ICursor|null); + + /** StructuredQuery endAt. */ + public endAt?: (google.firestore.v1.ICursor|null); + + /** StructuredQuery offset. */ + public offset: number; + + /** StructuredQuery limit. */ + public limit?: (google.protobuf.IInt32Value|null); + + /** StructuredQuery findNearest. */ + public findNearest?: (google.firestore.v1.StructuredQuery.IFindNearest|null); + + /** + * Creates a StructuredQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StructuredQuery + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery; + + /** + * Creates a plain object from a StructuredQuery message. Also converts values to other types if specified. + * @param message StructuredQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StructuredQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StructuredQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace StructuredQuery { + + /** Properties of a CollectionSelector. */ + interface ICollectionSelector { + + /** CollectionSelector collectionId */ + collectionId?: (string|null); + + /** CollectionSelector allDescendants */ + allDescendants?: (boolean|null); + } + + /** Represents a CollectionSelector. */ + class CollectionSelector implements ICollectionSelector { + + /** + * Constructs a new CollectionSelector. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.ICollectionSelector); + + /** CollectionSelector collectionId. */ + public collectionId: string; + + /** CollectionSelector allDescendants. */ + public allDescendants: boolean; + + /** + * Creates a CollectionSelector message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CollectionSelector + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.CollectionSelector; + + /** + * Creates a plain object from a CollectionSelector message. Also converts values to other types if specified. + * @param message CollectionSelector + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.CollectionSelector, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CollectionSelector to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CollectionSelector + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Filter. */ + interface IFilter { + + /** Filter compositeFilter */ + compositeFilter?: (google.firestore.v1.StructuredQuery.ICompositeFilter|null); + + /** Filter fieldFilter */ + fieldFilter?: (google.firestore.v1.StructuredQuery.IFieldFilter|null); + + /** Filter unaryFilter */ + unaryFilter?: (google.firestore.v1.StructuredQuery.IUnaryFilter|null); + } + + /** Represents a Filter. */ + class Filter implements IFilter { + + /** + * Constructs a new Filter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFilter); + + /** Filter compositeFilter. */ + public compositeFilter?: (google.firestore.v1.StructuredQuery.ICompositeFilter|null); + + /** Filter fieldFilter. */ + public fieldFilter?: (google.firestore.v1.StructuredQuery.IFieldFilter|null); + + /** Filter unaryFilter. */ + public unaryFilter?: (google.firestore.v1.StructuredQuery.IUnaryFilter|null); + + /** Filter filterType. */ + public filterType?: ("compositeFilter"|"fieldFilter"|"unaryFilter"); + + /** + * Creates a Filter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Filter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Filter; + + /** + * Creates a plain object from a Filter message. Also converts values to other types if specified. + * @param message Filter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.Filter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Filter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Filter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CompositeFilter. */ + interface ICompositeFilter { + + /** CompositeFilter op */ + op?: (google.firestore.v1.StructuredQuery.CompositeFilter.Operator|null); + + /** CompositeFilter filters */ + filters?: (google.firestore.v1.StructuredQuery.IFilter[]|null); + } + + /** Represents a CompositeFilter. */ + class CompositeFilter implements ICompositeFilter { + + /** + * Constructs a new CompositeFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.ICompositeFilter); + + /** CompositeFilter op. */ + public op: google.firestore.v1.StructuredQuery.CompositeFilter.Operator; + + /** CompositeFilter filters. */ + public filters: google.firestore.v1.StructuredQuery.IFilter[]; + + /** + * Creates a CompositeFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CompositeFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.CompositeFilter; + + /** + * Creates a plain object from a CompositeFilter message. Also converts values to other types if specified. + * @param message CompositeFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.CompositeFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CompositeFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CompositeFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace CompositeFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "AND"| "OR"; + } + + /** Properties of a FieldFilter. */ + interface IFieldFilter { + + /** FieldFilter field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** FieldFilter op */ + op?: (google.firestore.v1.StructuredQuery.FieldFilter.Operator|null); + + /** FieldFilter value */ + value?: (google.firestore.v1.IValue|null); + } + + /** Represents a FieldFilter. */ + class FieldFilter implements IFieldFilter { + + /** + * Constructs a new FieldFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFieldFilter); + + /** FieldFilter field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** FieldFilter op. */ + public op: google.firestore.v1.StructuredQuery.FieldFilter.Operator; + + /** FieldFilter value. */ + public value?: (google.firestore.v1.IValue|null); + + /** + * Creates a FieldFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FieldFilter; + + /** + * Creates a plain object from a FieldFilter message. Also converts values to other types if specified. + * @param message FieldFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.FieldFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "LESS_THAN"| "LESS_THAN_OR_EQUAL"| "GREATER_THAN"| "GREATER_THAN_OR_EQUAL"| "EQUAL"| "NOT_EQUAL"| "ARRAY_CONTAINS"| "IN"| "ARRAY_CONTAINS_ANY"| "NOT_IN"; + } + + /** Properties of an UnaryFilter. */ + interface IUnaryFilter { + + /** UnaryFilter op */ + op?: (google.firestore.v1.StructuredQuery.UnaryFilter.Operator|null); + + /** UnaryFilter field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + } + + /** Represents an UnaryFilter. */ + class UnaryFilter implements IUnaryFilter { + + /** + * Constructs a new UnaryFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IUnaryFilter); + + /** UnaryFilter op. */ + public op: google.firestore.v1.StructuredQuery.UnaryFilter.Operator; + + /** UnaryFilter field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** UnaryFilter operandType. */ + public operandType?: "field"; + + /** + * Creates an UnaryFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UnaryFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.UnaryFilter; + + /** + * Creates a plain object from an UnaryFilter message. Also converts values to other types if specified. + * @param message UnaryFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.UnaryFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UnaryFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UnaryFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UnaryFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "IS_NAN"| "IS_NULL"| "IS_NOT_NAN"| "IS_NOT_NULL"; + } + + /** Properties of an Order. */ + interface IOrder { + + /** Order field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** Order direction */ + direction?: (google.firestore.v1.StructuredQuery.Direction|null); + } + + /** Represents an Order. */ + class Order implements IOrder { + + /** + * Constructs a new Order. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IOrder); + + /** Order field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** Order direction. */ + public direction: google.firestore.v1.StructuredQuery.Direction; + + /** + * Creates an Order message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Order + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Order; + + /** + * Creates a plain object from an Order message. Also converts values to other types if specified. + * @param message Order + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.Order, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Order to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Order + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Direction enum. */ + type Direction = + "DIRECTION_UNSPECIFIED"| "ASCENDING"| "DESCENDING"; + + /** Properties of a FieldReference. */ + interface IFieldReference { + + /** FieldReference fieldPath */ + fieldPath?: (string|null); + } + + /** Represents a FieldReference. */ + class FieldReference implements IFieldReference { + + /** + * Constructs a new FieldReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFieldReference); + + /** FieldReference fieldPath. */ + public fieldPath: string; + + /** + * Creates a FieldReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldReference + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FieldReference; + + /** + * Creates a plain object from a FieldReference message. Also converts values to other types if specified. + * @param message FieldReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.FieldReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Projection. */ + interface IProjection { + + /** Projection fields */ + fields?: (google.firestore.v1.StructuredQuery.IFieldReference[]|null); + } + + /** Represents a Projection. */ + class Projection implements IProjection { + + /** + * Constructs a new Projection. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IProjection); + + /** Projection fields. */ + public fields: google.firestore.v1.StructuredQuery.IFieldReference[]; + + /** + * Creates a Projection message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Projection + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Projection; + + /** + * Creates a plain object from a Projection message. Also converts values to other types if specified. + * @param message Projection + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.Projection, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Projection to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Projection + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FindNearest. */ + interface IFindNearest { + + /** FindNearest vectorField */ + vectorField?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** FindNearest queryVector */ + queryVector?: (google.firestore.v1.IValue|null); + + /** FindNearest distanceMeasure */ + distanceMeasure?: (google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure|null); + + /** FindNearest limit */ + limit?: (google.protobuf.IInt32Value|null); + + /** FindNearest distanceResultField */ + distanceResultField?: (string|null); + + /** FindNearest distanceThreshold */ + distanceThreshold?: (google.protobuf.IDoubleValue|null); + } + + /** Represents a FindNearest. */ + class FindNearest implements IFindNearest { + + /** + * Constructs a new FindNearest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFindNearest); + + /** FindNearest vectorField. */ + public vectorField?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** FindNearest queryVector. */ + public queryVector?: (google.firestore.v1.IValue|null); + + /** FindNearest distanceMeasure. */ + public distanceMeasure: google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure; + + /** FindNearest limit. */ + public limit?: (google.protobuf.IInt32Value|null); + + /** FindNearest distanceResultField. */ + public distanceResultField: string; + + /** FindNearest distanceThreshold. */ + public distanceThreshold?: (google.protobuf.IDoubleValue|null); + + /** + * Creates a FindNearest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FindNearest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FindNearest; + + /** + * Creates a plain object from a FindNearest message. Also converts values to other types if specified. + * @param message FindNearest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.FindNearest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FindNearest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FindNearest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FindNearest { + + /** DistanceMeasure enum. */ + type DistanceMeasure = + "DISTANCE_MEASURE_UNSPECIFIED"| "EUCLIDEAN"| "COSINE"| "DOT_PRODUCT"; + } + } + + /** Properties of a StructuredAggregationQuery. */ + interface IStructuredAggregationQuery { + + /** StructuredAggregationQuery structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** StructuredAggregationQuery aggregations */ + aggregations?: (google.firestore.v1.StructuredAggregationQuery.IAggregation[]|null); + } + + /** Represents a StructuredAggregationQuery. */ + class StructuredAggregationQuery implements IStructuredAggregationQuery { + + /** + * Constructs a new StructuredAggregationQuery. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IStructuredAggregationQuery); + + /** StructuredAggregationQuery structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** StructuredAggregationQuery aggregations. */ + public aggregations: google.firestore.v1.StructuredAggregationQuery.IAggregation[]; + + /** StructuredAggregationQuery queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a StructuredAggregationQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StructuredAggregationQuery + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery; + + /** + * Creates a plain object from a StructuredAggregationQuery message. Also converts values to other types if specified. + * @param message StructuredAggregationQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StructuredAggregationQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StructuredAggregationQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace StructuredAggregationQuery { + + /** Properties of an Aggregation. */ + interface IAggregation { + + /** Aggregation count */ + count?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null); + + /** Aggregation sum */ + sum?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null); + + /** Aggregation avg */ + avg?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null); + + /** Aggregation alias */ + alias?: (string|null); + } + + /** Represents an Aggregation. */ + class Aggregation implements IAggregation { + + /** + * Constructs a new Aggregation. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.IAggregation); + + /** Aggregation count. */ + public count?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null); + + /** Aggregation sum. */ + public sum?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null); + + /** Aggregation avg. */ + public avg?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null); + + /** Aggregation alias. */ + public alias: string; + + /** Aggregation operator. */ + public operator?: ("count"|"sum"|"avg"); + + /** + * Creates an Aggregation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Aggregation + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation; + + /** + * Creates a plain object from an Aggregation message. Also converts values to other types if specified. + * @param message Aggregation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Aggregation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Aggregation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Aggregation { + + /** Properties of a Count. */ + interface ICount { + + /** Count upTo */ + upTo?: (google.protobuf.IInt64Value|null); + } + + /** Represents a Count. */ + class Count implements ICount { + + /** + * Constructs a new Count. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount); + + /** Count upTo. */ + public upTo?: (google.protobuf.IInt64Value|null); + + /** + * Creates a Count message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Count + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Count; + + /** + * Creates a plain object from a Count message. Also converts values to other types if specified. + * @param message Count + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Count, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Count to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Count + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Sum. */ + interface ISum { + + /** Sum field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + } + + /** Represents a Sum. */ + class Sum implements ISum { + + /** + * Constructs a new Sum. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum); + + /** Sum field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** + * Creates a Sum message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Sum + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum; + + /** + * Creates a plain object from a Sum message. Also converts values to other types if specified. + * @param message Sum + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Sum to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Sum + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Avg. */ + interface IAvg { + + /** Avg field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + } + + /** Represents an Avg. */ + class Avg implements IAvg { + + /** + * Constructs a new Avg. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg); + + /** Avg field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** + * Creates an Avg message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Avg + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg; + + /** + * Creates a plain object from an Avg message. Also converts values to other types if specified. + * @param message Avg + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Avg to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Avg + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + + /** Properties of a Cursor. */ + interface ICursor { + + /** Cursor values */ + values?: (google.firestore.v1.IValue[]|null); + + /** Cursor before */ + before?: (boolean|null); + } + + /** Represents a Cursor. */ + class Cursor implements ICursor { + + /** + * Constructs a new Cursor. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICursor); + + /** Cursor values. */ + public values: google.firestore.v1.IValue[]; + + /** Cursor before. */ + public before: boolean; + + /** + * Creates a Cursor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Cursor + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Cursor; + + /** + * Creates a plain object from a Cursor message. Also converts values to other types if specified. + * @param message Cursor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Cursor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Cursor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Cursor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExplainOptions. */ + interface IExplainOptions { + + /** ExplainOptions analyze */ + analyze?: (boolean|null); + } + + /** Represents an ExplainOptions. */ + class ExplainOptions implements IExplainOptions { + + /** + * Constructs a new ExplainOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExplainOptions); + + /** ExplainOptions analyze. */ + public analyze: boolean; + + /** + * Creates an ExplainOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExplainOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExplainOptions; + + /** + * Creates a plain object from an ExplainOptions message. Also converts values to other types if specified. + * @param message ExplainOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExplainOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExplainOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExplainOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExplainMetrics. */ + interface IExplainMetrics { + + /** ExplainMetrics planSummary */ + planSummary?: (google.firestore.v1.IPlanSummary|null); + + /** ExplainMetrics executionStats */ + executionStats?: (google.firestore.v1.IExecutionStats|null); + } + + /** Represents an ExplainMetrics. */ + class ExplainMetrics implements IExplainMetrics { + + /** + * Constructs a new ExplainMetrics. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExplainMetrics); + + /** ExplainMetrics planSummary. */ + public planSummary?: (google.firestore.v1.IPlanSummary|null); + + /** ExplainMetrics executionStats. */ + public executionStats?: (google.firestore.v1.IExecutionStats|null); + + /** + * Creates an ExplainMetrics message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExplainMetrics + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExplainMetrics; + + /** + * Creates a plain object from an ExplainMetrics message. Also converts values to other types if specified. + * @param message ExplainMetrics + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExplainMetrics, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExplainMetrics to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExplainMetrics + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PlanSummary. */ + interface IPlanSummary { + + /** PlanSummary indexesUsed */ + indexesUsed?: (google.protobuf.IStruct[]|null); + } + + /** Represents a PlanSummary. */ + class PlanSummary implements IPlanSummary { + + /** + * Constructs a new PlanSummary. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPlanSummary); + + /** PlanSummary indexesUsed. */ + public indexesUsed: google.protobuf.IStruct[]; + + /** + * Creates a PlanSummary message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PlanSummary + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.PlanSummary; + + /** + * Creates a plain object from a PlanSummary message. Also converts values to other types if specified. + * @param message PlanSummary + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.PlanSummary, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PlanSummary to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PlanSummary + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExecutionStats. */ + interface IExecutionStats { + + /** ExecutionStats resultsReturned */ + resultsReturned?: (number|string|null); + + /** ExecutionStats executionDuration */ + executionDuration?: (google.protobuf.IDuration|null); + + /** ExecutionStats readOperations */ + readOperations?: (number|string|null); + + /** ExecutionStats debugStats */ + debugStats?: (google.protobuf.IStruct|null); + } + + /** Represents an ExecutionStats. */ + class ExecutionStats implements IExecutionStats { + + /** + * Constructs a new ExecutionStats. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExecutionStats); + + /** ExecutionStats resultsReturned. */ + public resultsReturned: (number|string); + + /** ExecutionStats executionDuration. */ + public executionDuration?: (google.protobuf.IDuration|null); + + /** ExecutionStats readOperations. */ + public readOperations: (number|string); + + /** ExecutionStats debugStats. */ + public debugStats?: (google.protobuf.IStruct|null); + + /** + * Creates an ExecutionStats message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExecutionStats + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExecutionStats; + + /** + * Creates a plain object from an ExecutionStats message. Also converts values to other types if specified. + * @param message ExecutionStats + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExecutionStats, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExecutionStats to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExecutionStats + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Write. */ + interface IWrite { + + /** Write update */ + update?: (google.firestore.v1.IDocument|null); + + /** Write delete */ + "delete"?: (string|null); + + /** Write transform */ + transform?: (google.firestore.v1.IDocumentTransform|null); + + /** Write updateMask */ + updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** Write updateTransforms */ + updateTransforms?: (google.firestore.v1.DocumentTransform.IFieldTransform[]|null); + + /** Write currentDocument */ + currentDocument?: (google.firestore.v1.IPrecondition|null); + } + + /** Represents a Write. */ + class Write implements IWrite { + + /** + * Constructs a new Write. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWrite); + + /** Write update. */ + public update?: (google.firestore.v1.IDocument|null); + + /** Write delete. */ + public delete?: (string|null); + + /** Write transform. */ + public transform?: (google.firestore.v1.IDocumentTransform|null); + + /** Write updateMask. */ + public updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** Write updateTransforms. */ + public updateTransforms: google.firestore.v1.DocumentTransform.IFieldTransform[]; + + /** Write currentDocument. */ + public currentDocument?: (google.firestore.v1.IPrecondition|null); + + /** Write operation. */ + public operation?: ("update"|"delete"|"transform"); + + /** + * Creates a Write message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Write + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Write; + + /** + * Creates a plain object from a Write message. Also converts values to other types if specified. + * @param message Write + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Write, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Write to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Write + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentTransform. */ + interface IDocumentTransform { + + /** DocumentTransform document */ + document?: (string|null); + + /** DocumentTransform fieldTransforms */ + fieldTransforms?: (google.firestore.v1.DocumentTransform.IFieldTransform[]|null); + } + + /** Represents a DocumentTransform. */ + class DocumentTransform implements IDocumentTransform { + + /** + * Constructs a new DocumentTransform. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentTransform); + + /** DocumentTransform document. */ + public document: string; + + /** DocumentTransform fieldTransforms. */ + public fieldTransforms: google.firestore.v1.DocumentTransform.IFieldTransform[]; + + /** + * Creates a DocumentTransform message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentTransform + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentTransform; + + /** + * Creates a plain object from a DocumentTransform message. Also converts values to other types if specified. + * @param message DocumentTransform + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentTransform to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DocumentTransform { + + /** Properties of a FieldTransform. */ + interface IFieldTransform { + + /** FieldTransform fieldPath */ + fieldPath?: (string|null); + + /** FieldTransform setToServerValue */ + setToServerValue?: (google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null); + + /** FieldTransform increment */ + increment?: (google.firestore.v1.IValue|null); + + /** FieldTransform maximum */ + maximum?: (google.firestore.v1.IValue|null); + + /** FieldTransform minimum */ + minimum?: (google.firestore.v1.IValue|null); + + /** FieldTransform appendMissingElements */ + appendMissingElements?: (google.firestore.v1.IArrayValue|null); + + /** FieldTransform removeAllFromArray */ + removeAllFromArray?: (google.firestore.v1.IArrayValue|null); + } + + /** Represents a FieldTransform. */ + class FieldTransform implements IFieldTransform { + + /** + * Constructs a new FieldTransform. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.DocumentTransform.IFieldTransform); + + /** FieldTransform fieldPath. */ + public fieldPath: string; + + /** FieldTransform setToServerValue. */ + public setToServerValue?: (google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null); + + /** FieldTransform increment. */ + public increment?: (google.firestore.v1.IValue|null); + + /** FieldTransform maximum. */ + public maximum?: (google.firestore.v1.IValue|null); + + /** FieldTransform minimum. */ + public minimum?: (google.firestore.v1.IValue|null); + + /** FieldTransform appendMissingElements. */ + public appendMissingElements?: (google.firestore.v1.IArrayValue|null); + + /** FieldTransform removeAllFromArray. */ + public removeAllFromArray?: (google.firestore.v1.IArrayValue|null); + + /** FieldTransform transformType. */ + public transformType?: ("setToServerValue"|"increment"|"maximum"|"minimum"|"appendMissingElements"|"removeAllFromArray"); + + /** + * Creates a FieldTransform message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldTransform + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentTransform.FieldTransform; + + /** + * Creates a plain object from a FieldTransform message. Also converts values to other types if specified. + * @param message FieldTransform + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentTransform.FieldTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldTransform to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldTransform { + + /** ServerValue enum. */ + type ServerValue = + "SERVER_VALUE_UNSPECIFIED"| "REQUEST_TIME"; + } + } + + /** Properties of a WriteResult. */ + interface IWriteResult { + + /** WriteResult updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** WriteResult transformResults */ + transformResults?: (google.firestore.v1.IValue[]|null); + } + + /** Represents a WriteResult. */ + class WriteResult implements IWriteResult { + + /** + * Constructs a new WriteResult. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWriteResult); + + /** WriteResult updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** WriteResult transformResults. */ + public transformResults: google.firestore.v1.IValue[]; + + /** + * Creates a WriteResult message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteResult + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteResult; + + /** + * Creates a plain object from a WriteResult message. Also converts values to other types if specified. + * @param message WriteResult + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.WriteResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteResult to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteResult + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentChange. */ + interface IDocumentChange { + + /** DocumentChange document */ + document?: (google.firestore.v1.IDocument|null); + + /** DocumentChange targetIds */ + targetIds?: (number[]|null); + + /** DocumentChange removedTargetIds */ + removedTargetIds?: (number[]|null); + } + + /** Represents a DocumentChange. */ + class DocumentChange implements IDocumentChange { + + /** + * Constructs a new DocumentChange. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentChange); + + /** DocumentChange document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** DocumentChange targetIds. */ + public targetIds: number[]; + + /** DocumentChange removedTargetIds. */ + public removedTargetIds: number[]; + + /** + * Creates a DocumentChange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentChange + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentChange; + + /** + * Creates a plain object from a DocumentChange message. Also converts values to other types if specified. + * @param message DocumentChange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentChange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentChange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentDelete. */ + interface IDocumentDelete { + + /** DocumentDelete document */ + document?: (string|null); + + /** DocumentDelete removedTargetIds */ + removedTargetIds?: (number[]|null); + + /** DocumentDelete readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a DocumentDelete. */ + class DocumentDelete implements IDocumentDelete { + + /** + * Constructs a new DocumentDelete. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentDelete); + + /** DocumentDelete document. */ + public document: string; + + /** DocumentDelete removedTargetIds. */ + public removedTargetIds: number[]; + + /** DocumentDelete readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a DocumentDelete message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentDelete + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentDelete; + + /** + * Creates a plain object from a DocumentDelete message. Also converts values to other types if specified. + * @param message DocumentDelete + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentDelete, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentDelete to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentDelete + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentRemove. */ + interface IDocumentRemove { + + /** DocumentRemove document */ + document?: (string|null); + + /** DocumentRemove removedTargetIds */ + removedTargetIds?: (number[]|null); + + /** DocumentRemove readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a DocumentRemove. */ + class DocumentRemove implements IDocumentRemove { + + /** + * Constructs a new DocumentRemove. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentRemove); + + /** DocumentRemove document. */ + public document: string; + + /** DocumentRemove removedTargetIds. */ + public removedTargetIds: number[]; + + /** DocumentRemove readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a DocumentRemove message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentRemove + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentRemove; + + /** + * Creates a plain object from a DocumentRemove message. Also converts values to other types if specified. + * @param message DocumentRemove + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentRemove, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentRemove to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentRemove + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExistenceFilter. */ + interface IExistenceFilter { + + /** ExistenceFilter targetId */ + targetId?: (number|null); + + /** ExistenceFilter count */ + count?: (number|null); + + /** ExistenceFilter unchangedNames */ + unchangedNames?: (google.firestore.v1.IBloomFilter|null); + } + + /** Represents an ExistenceFilter. */ + class ExistenceFilter implements IExistenceFilter { + + /** + * Constructs a new ExistenceFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExistenceFilter); + + /** ExistenceFilter targetId. */ + public targetId: number; + + /** ExistenceFilter count. */ + public count: number; + + /** ExistenceFilter unchangedNames. */ + public unchangedNames?: (google.firestore.v1.IBloomFilter|null); + + /** + * Creates an ExistenceFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExistenceFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExistenceFilter; + + /** + * Creates a plain object from an ExistenceFilter message. Also converts values to other types if specified. + * @param message ExistenceFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExistenceFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExistenceFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExistenceFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + + /** Namespace api. */ + namespace api { + + /** FieldBehavior enum. */ + type FieldBehavior = + "FIELD_BEHAVIOR_UNSPECIFIED"| "OPTIONAL"| "REQUIRED"| "OUTPUT_ONLY"| "INPUT_ONLY"| "IMMUTABLE"| "UNORDERED_LIST"| "NON_EMPTY_DEFAULT"| "IDENTIFIER"; + + /** Properties of a Http. */ + interface IHttp { + + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); + + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); + } + + /** Represents a Http. */ + class Http implements IHttp { + + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); + + /** Http rules. */ + public rules: google.api.IHttpRule[]; + + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Http + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a HttpRule. */ + interface IHttpRule { + + /** HttpRule selector */ + selector?: (string|null); + + /** HttpRule get */ + get?: (string|null); + + /** HttpRule put */ + put?: (string|null); + + /** HttpRule post */ + post?: (string|null); + + /** HttpRule delete */ + "delete"?: (string|null); + + /** HttpRule patch */ + patch?: (string|null); + + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body */ + body?: (string|null); + + /** HttpRule responseBody */ + responseBody?: (string|null); + + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); + } + + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { + + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); + + /** HttpRule selector. */ + public selector: string; + + /** HttpRule get. */ + public get?: (string|null); + + /** HttpRule put. */ + public put?: (string|null); + + /** HttpRule post. */ + public post?: (string|null); + + /** HttpRule delete. */ + public delete?: (string|null); + + /** HttpRule patch. */ + public patch?: (string|null); + + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body. */ + public body: string; + + /** HttpRule responseBody. */ + public responseBody: string; + + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; + + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for HttpRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { + + /** CustomHttpPattern kind */ + kind?: (string|null); + + /** CustomHttpPattern path */ + path?: (string|null); + } + + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { + + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); + + /** CustomHttpPattern kind. */ + public kind: string; + + /** CustomHttpPattern path. */ + public path: string; + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CustomHttpPattern + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommonLanguageSettings. */ + interface ICommonLanguageSettings { + + /** CommonLanguageSettings referenceDocsUri */ + referenceDocsUri?: (string|null); + + /** CommonLanguageSettings destinations */ + destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + } + + /** Represents a CommonLanguageSettings. */ + class CommonLanguageSettings implements ICommonLanguageSettings { + + /** + * Constructs a new CommonLanguageSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICommonLanguageSettings); + + /** CommonLanguageSettings referenceDocsUri. */ + public referenceDocsUri: string; + + /** CommonLanguageSettings destinations. */ + public destinations: google.api.ClientLibraryDestination[]; + + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommonLanguageSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CommonLanguageSettings; + + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @param message CommonLanguageSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CommonLanguageSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommonLanguageSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommonLanguageSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ClientLibrarySettings. */ + interface IClientLibrarySettings { + + /** ClientLibrarySettings version */ + version?: (string|null); + + /** ClientLibrarySettings launchStage */ + launchStage?: (google.api.LaunchStage|null); + + /** ClientLibrarySettings restNumericEnums */ + restNumericEnums?: (boolean|null); + + /** ClientLibrarySettings javaSettings */ + javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings */ + cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings */ + phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings */ + pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings */ + nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings */ + dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings */ + rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings */ + goSettings?: (google.api.IGoSettings|null); + } + + /** Represents a ClientLibrarySettings. */ + class ClientLibrarySettings implements IClientLibrarySettings { + + /** + * Constructs a new ClientLibrarySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IClientLibrarySettings); + + /** ClientLibrarySettings version. */ + public version: string; + + /** ClientLibrarySettings launchStage. */ + public launchStage: google.api.LaunchStage; + + /** ClientLibrarySettings restNumericEnums. */ + public restNumericEnums: boolean; + + /** ClientLibrarySettings javaSettings. */ + public javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings. */ + public cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings. */ + public phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings. */ + public pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings. */ + public nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings. */ + public dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings. */ + public rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings. */ + public goSettings?: (google.api.IGoSettings|null); + + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ClientLibrarySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.ClientLibrarySettings; + + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @param message ClientLibrarySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ClientLibrarySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ClientLibrarySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ClientLibrarySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Publishing. */ + interface IPublishing { + + /** Publishing methodSettings */ + methodSettings?: (google.api.IMethodSettings[]|null); + + /** Publishing newIssueUri */ + newIssueUri?: (string|null); + + /** Publishing documentationUri */ + documentationUri?: (string|null); + + /** Publishing apiShortName */ + apiShortName?: (string|null); + + /** Publishing githubLabel */ + githubLabel?: (string|null); + + /** Publishing codeownerGithubTeams */ + codeownerGithubTeams?: (string[]|null); + + /** Publishing docTagPrefix */ + docTagPrefix?: (string|null); + + /** Publishing organization */ + organization?: (google.api.ClientLibraryOrganization|null); + + /** Publishing librarySettings */ + librarySettings?: (google.api.IClientLibrarySettings[]|null); + + /** Publishing protoReferenceDocumentationUri */ + protoReferenceDocumentationUri?: (string|null); + + /** Publishing restReferenceDocumentationUri */ + restReferenceDocumentationUri?: (string|null); + } + + /** Represents a Publishing. */ + class Publishing implements IPublishing { + + /** + * Constructs a new Publishing. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPublishing); + + /** Publishing methodSettings. */ + public methodSettings: google.api.IMethodSettings[]; + + /** Publishing newIssueUri. */ + public newIssueUri: string; + + /** Publishing documentationUri. */ + public documentationUri: string; + + /** Publishing apiShortName. */ + public apiShortName: string; + + /** Publishing githubLabel. */ + public githubLabel: string; + + /** Publishing codeownerGithubTeams. */ + public codeownerGithubTeams: string[]; + + /** Publishing docTagPrefix. */ + public docTagPrefix: string; + + /** Publishing organization. */ + public organization: google.api.ClientLibraryOrganization; + + /** Publishing librarySettings. */ + public librarySettings: google.api.IClientLibrarySettings[]; + + /** Publishing protoReferenceDocumentationUri. */ + public protoReferenceDocumentationUri: string; + + /** Publishing restReferenceDocumentationUri. */ + public restReferenceDocumentationUri: string; + + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Publishing + */ + public static fromObject(object: { [k: string]: any }): google.api.Publishing; + + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @param message Publishing + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Publishing, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Publishing to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Publishing + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a JavaSettings. */ + interface IJavaSettings { + + /** JavaSettings libraryPackage */ + libraryPackage?: (string|null); + + /** JavaSettings serviceClassNames */ + serviceClassNames?: ({ [k: string]: string }|null); + + /** JavaSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a JavaSettings. */ + class JavaSettings implements IJavaSettings { + + /** + * Constructs a new JavaSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IJavaSettings); + + /** JavaSettings libraryPackage. */ + public libraryPackage: string; + + /** JavaSettings serviceClassNames. */ + public serviceClassNames: { [k: string]: string }; + + /** JavaSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns JavaSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.JavaSettings; + + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @param message JavaSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.JavaSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this JavaSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for JavaSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CppSettings. */ + interface ICppSettings { + + /** CppSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a CppSettings. */ + class CppSettings implements ICppSettings { + + /** + * Constructs a new CppSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICppSettings); + + /** CppSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CppSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CppSettings; + + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @param message CppSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CppSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CppSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CppSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PhpSettings. */ + interface IPhpSettings { + + /** PhpSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a PhpSettings. */ + class PhpSettings implements IPhpSettings { + + /** + * Constructs a new PhpSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPhpSettings); + + /** PhpSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PhpSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PhpSettings; + + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @param message PhpSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PhpSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PhpSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PhpSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PythonSettings. */ + interface IPythonSettings { + + /** PythonSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + } + + /** Represents a PythonSettings. */ + class PythonSettings implements IPythonSettings { + + /** + * Constructs a new PythonSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPythonSettings); + + /** PythonSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PythonSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings; + + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @param message PythonSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PythonSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PythonSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace PythonSettings { + + /** Properties of an ExperimentalFeatures. */ + interface IExperimentalFeatures { + + /** ExperimentalFeatures restAsyncIoEnabled */ + restAsyncIoEnabled?: (boolean|null); + + /** ExperimentalFeatures protobufPythonicTypesEnabled */ + protobufPythonicTypesEnabled?: (boolean|null); + } + + /** Represents an ExperimentalFeatures. */ + class ExperimentalFeatures implements IExperimentalFeatures { + + /** + * Constructs a new ExperimentalFeatures. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.PythonSettings.IExperimentalFeatures); + + /** ExperimentalFeatures restAsyncIoEnabled. */ + public restAsyncIoEnabled: boolean; + + /** ExperimentalFeatures protobufPythonicTypesEnabled. */ + public protobufPythonicTypesEnabled: boolean; + + /** + * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExperimentalFeatures + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. + * @param message ExperimentalFeatures + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings.ExperimentalFeatures, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExperimentalFeatures to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExperimentalFeatures + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a NodeSettings. */ + interface INodeSettings { + + /** NodeSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a NodeSettings. */ + class NodeSettings implements INodeSettings { + + /** + * Constructs a new NodeSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.INodeSettings); + + /** NodeSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NodeSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.NodeSettings; + + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @param message NodeSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.NodeSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NodeSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NodeSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DotnetSettings. */ + interface IDotnetSettings { + + /** DotnetSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + + /** DotnetSettings renamedResources */ + renamedResources?: ({ [k: string]: string }|null); + + /** DotnetSettings ignoredResources */ + ignoredResources?: (string[]|null); + + /** DotnetSettings forcedNamespaceAliases */ + forcedNamespaceAliases?: (string[]|null); + + /** DotnetSettings handwrittenSignatures */ + handwrittenSignatures?: (string[]|null); + } + + /** Represents a DotnetSettings. */ + class DotnetSettings implements IDotnetSettings { + + /** + * Constructs a new DotnetSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IDotnetSettings); + + /** DotnetSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** DotnetSettings renamedResources. */ + public renamedResources: { [k: string]: string }; + + /** DotnetSettings ignoredResources. */ + public ignoredResources: string[]; + + /** DotnetSettings forcedNamespaceAliases. */ + public forcedNamespaceAliases: string[]; + + /** DotnetSettings handwrittenSignatures. */ + public handwrittenSignatures: string[]; + + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DotnetSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.DotnetSettings; + + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @param message DotnetSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.DotnetSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DotnetSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DotnetSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RubySettings. */ + interface IRubySettings { + + /** RubySettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a RubySettings. */ + class RubySettings implements IRubySettings { + + /** + * Constructs a new RubySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRubySettings); + + /** RubySettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RubySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.RubySettings; + + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @param message RubySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RubySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RubySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RubySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GoSettings. */ + interface IGoSettings { + + /** GoSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + } + + /** Represents a GoSettings. */ + class GoSettings implements IGoSettings { + + /** + * Constructs a new GoSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IGoSettings); + + /** GoSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GoSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.GoSettings; + + /** + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @param message GoSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.GoSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GoSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GoSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodSettings. */ + interface IMethodSettings { + + /** MethodSettings selector */ + selector?: (string|null); + + /** MethodSettings longRunning */ + longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields */ + autoPopulatedFields?: (string[]|null); + } + + /** Represents a MethodSettings. */ + class MethodSettings implements IMethodSettings { + + /** + * Constructs a new MethodSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IMethodSettings); + + /** MethodSettings selector. */ + public selector: string; + + /** MethodSettings longRunning. */ + public longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields. */ + public autoPopulatedFields: string[]; + + /** + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings; + + /** + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @param message MethodSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodSettings { + + /** Properties of a LongRunning. */ + interface ILongRunning { + + /** LongRunning initialPollDelay */ + initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier */ + pollDelayMultiplier?: (number|null); + + /** LongRunning maxPollDelay */ + maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout */ + totalPollTimeout?: (google.protobuf.IDuration|null); + } + + /** Represents a LongRunning. */ + class LongRunning implements ILongRunning { + + /** + * Constructs a new LongRunning. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.MethodSettings.ILongRunning); + + /** LongRunning initialPollDelay. */ + public initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier. */ + public pollDelayMultiplier: number; + + /** LongRunning maxPollDelay. */ + public maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout. */ + public totalPollTimeout?: (google.protobuf.IDuration|null); + + /** + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LongRunning + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings.LongRunning; + + /** + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @param message LongRunning + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings.LongRunning, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LongRunning to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LongRunning + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** ClientLibraryOrganization enum. */ + type ClientLibraryOrganization = + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"| "CLOUD"| "ADS"| "PHOTOS"| "STREET_VIEW"| "SHOPPING"| "GEO"| "GENERATIVE_AI"; + + /** ClientLibraryDestination enum. */ + type ClientLibraryDestination = + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"| "GITHUB"| "PACKAGE_MANAGER"; + + /** Properties of a SelectiveGapicGeneration. */ + interface ISelectiveGapicGeneration { + + /** SelectiveGapicGeneration methods */ + methods?: (string[]|null); + + /** SelectiveGapicGeneration generateOmittedAsInternal */ + generateOmittedAsInternal?: (boolean|null); + } + + /** Represents a SelectiveGapicGeneration. */ + class SelectiveGapicGeneration implements ISelectiveGapicGeneration { + + /** + * Constructs a new SelectiveGapicGeneration. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ISelectiveGapicGeneration); + + /** SelectiveGapicGeneration methods. */ + public methods: string[]; + + /** SelectiveGapicGeneration generateOmittedAsInternal. */ + public generateOmittedAsInternal: boolean; + + /** + * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SelectiveGapicGeneration + */ + public static fromObject(object: { [k: string]: any }): google.api.SelectiveGapicGeneration; + + /** + * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. + * @param message SelectiveGapicGeneration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.SelectiveGapicGeneration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SelectiveGapicGeneration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SelectiveGapicGeneration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** LaunchStage enum. */ + type LaunchStage = + "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; + + /** Properties of a ResourceDescriptor. */ + interface IResourceDescriptor { + + /** ResourceDescriptor type */ + type?: (string|null); + + /** ResourceDescriptor pattern */ + pattern?: (string[]|null); + + /** ResourceDescriptor nameField */ + nameField?: (string|null); + + /** ResourceDescriptor history */ + history?: (google.api.ResourceDescriptor.History|null); + + /** ResourceDescriptor plural */ + plural?: (string|null); + + /** ResourceDescriptor singular */ + singular?: (string|null); + + /** ResourceDescriptor style */ + style?: (google.api.ResourceDescriptor.Style[]|null); + } + + /** Represents a ResourceDescriptor. */ + class ResourceDescriptor implements IResourceDescriptor { + + /** + * Constructs a new ResourceDescriptor. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceDescriptor); + + /** ResourceDescriptor type. */ + public type: string; + + /** ResourceDescriptor pattern. */ + public pattern: string[]; + + /** ResourceDescriptor nameField. */ + public nameField: string; + + /** ResourceDescriptor history. */ + public history: google.api.ResourceDescriptor.History; + + /** ResourceDescriptor plural. */ + public plural: string; + + /** ResourceDescriptor singular. */ + public singular: string; + + /** ResourceDescriptor style. */ + public style: google.api.ResourceDescriptor.Style[]; + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceDescriptor + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @param message ResourceDescriptor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceDescriptor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceDescriptor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ResourceDescriptor { + + /** History enum. */ + type History = + "HISTORY_UNSPECIFIED"| "ORIGINALLY_SINGLE_PATTERN"| "FUTURE_MULTI_PATTERN"; + + /** Style enum. */ + type Style = + "STYLE_UNSPECIFIED"| "DECLARATIVE_FRIENDLY"; + } + + /** Properties of a ResourceReference. */ + interface IResourceReference { + + /** ResourceReference type */ + type?: (string|null); + + /** ResourceReference childType */ + childType?: (string|null); + } + + /** Represents a ResourceReference. */ + class ResourceReference implements IResourceReference { + + /** + * Constructs a new ResourceReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceReference); + + /** ResourceReference type. */ + public type: string; + + /** ResourceReference childType. */ + public childType: string; + + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceReference + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; + + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @param message ResourceReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace protobuf. */ + namespace protobuf { + + /** Properties of a FileDescriptorSet. */ + interface IFileDescriptorSet { + + /** FileDescriptorSet file */ + file?: (google.protobuf.IFileDescriptorProto[]|null); + } + + /** Represents a FileDescriptorSet. */ + class FileDescriptorSet implements IFileDescriptorSet { + + /** + * Constructs a new FileDescriptorSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorSet); + + /** FileDescriptorSet file. */ + public file: google.protobuf.IFileDescriptorProto[]; + + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; + + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @param message FileDescriptorSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Edition enum. */ + type Edition = + "EDITION_UNKNOWN"| "EDITION_PROTO2"| "EDITION_PROTO3"| "EDITION_2023"| "EDITION_2024"| "EDITION_1_TEST_ONLY"| "EDITION_2_TEST_ONLY"| "EDITION_99997_TEST_ONLY"| "EDITION_99998_TEST_ONLY"| "EDITION_99999_TEST_ONLY"| "EDITION_MAX"; + + /** Properties of a FileDescriptorProto. */ + interface IFileDescriptorProto { + + /** FileDescriptorProto name */ + name?: (string|null); + + /** FileDescriptorProto package */ + "package"?: (string|null); + + /** FileDescriptorProto dependency */ + dependency?: (string[]|null); + + /** FileDescriptorProto publicDependency */ + publicDependency?: (number[]|null); + + /** FileDescriptorProto weakDependency */ + weakDependency?: (number[]|null); + + /** FileDescriptorProto messageType */ + messageType?: (google.protobuf.IDescriptorProto[]|null); + + /** FileDescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** FileDescriptorProto service */ + service?: (google.protobuf.IServiceDescriptorProto[]|null); + + /** FileDescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** FileDescriptorProto options */ + options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo */ + sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax */ + syntax?: (string|null); + + /** FileDescriptorProto edition */ + edition?: (google.protobuf.Edition|null); + } + + /** Represents a FileDescriptorProto. */ + class FileDescriptorProto implements IFileDescriptorProto { + + /** + * Constructs a new FileDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorProto); + + /** FileDescriptorProto name. */ + public name: string; + + /** FileDescriptorProto package. */ + public package: string; + + /** FileDescriptorProto dependency. */ + public dependency: string[]; + + /** FileDescriptorProto publicDependency. */ + public publicDependency: number[]; + + /** FileDescriptorProto weakDependency. */ + public weakDependency: number[]; + + /** FileDescriptorProto messageType. */ + public messageType: google.protobuf.IDescriptorProto[]; + + /** FileDescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** FileDescriptorProto service. */ + public service: google.protobuf.IServiceDescriptorProto[]; + + /** FileDescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** FileDescriptorProto options. */ + public options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo. */ + public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax. */ + public syntax: string; + + /** FileDescriptorProto edition. */ + public edition: google.protobuf.Edition; + + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; + + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @param message FileDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DescriptorProto. */ + interface IDescriptorProto { + + /** DescriptorProto name */ + name?: (string|null); + + /** DescriptorProto field */ + field?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto nestedType */ + nestedType?: (google.protobuf.IDescriptorProto[]|null); + + /** DescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** DescriptorProto extensionRange */ + extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); + + /** DescriptorProto oneofDecl */ + oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); + + /** DescriptorProto options */ + options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange */ + reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); + + /** DescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents a DescriptorProto. */ + class DescriptorProto implements IDescriptorProto { + + /** + * Constructs a new DescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDescriptorProto); + + /** DescriptorProto name. */ + public name: string; + + /** DescriptorProto field. */ + public field: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto nestedType. */ + public nestedType: google.protobuf.IDescriptorProto[]; + + /** DescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** DescriptorProto extensionRange. */ + public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; + + /** DescriptorProto oneofDecl. */ + public oneofDecl: google.protobuf.IOneofDescriptorProto[]; + + /** DescriptorProto options. */ + public options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange. */ + public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; + + /** DescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; + + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @param message DescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DescriptorProto { + + /** Properties of an ExtensionRange. */ + interface IExtensionRange { + + /** ExtensionRange start */ + start?: (number|null); + + /** ExtensionRange end */ + end?: (number|null); + + /** ExtensionRange options */ + options?: (google.protobuf.IExtensionRangeOptions|null); + } + + /** Represents an ExtensionRange. */ + class ExtensionRange implements IExtensionRange { + + /** + * Constructs a new ExtensionRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); + + /** ExtensionRange start. */ + public start: number; + + /** ExtensionRange end. */ + public end: number; + + /** ExtensionRange options. */ + public options?: (google.protobuf.IExtensionRangeOptions|null); + + /** + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @param message ExtensionRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReservedRange. */ + interface IReservedRange { + + /** ReservedRange start */ + start?: (number|null); + + /** ReservedRange end */ + end?: (number|null); + } + + /** Represents a ReservedRange. */ + class ReservedRange implements IReservedRange { + + /** + * Constructs a new ReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); + + /** ReservedRange start. */ + public start: number; + + /** ReservedRange end. */ + public end: number; + + /** + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @param message ReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an ExtensionRangeOptions. */ + interface IExtensionRangeOptions { + + /** ExtensionRangeOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ExtensionRangeOptions declaration */ + declaration?: (google.protobuf.ExtensionRangeOptions.IDeclaration[]|null); + + /** ExtensionRangeOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification */ + verification?: (google.protobuf.ExtensionRangeOptions.VerificationState|null); + } + + /** Represents an ExtensionRangeOptions. */ + class ExtensionRangeOptions implements IExtensionRangeOptions { + + /** + * Constructs a new ExtensionRangeOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IExtensionRangeOptions); + + /** ExtensionRangeOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** ExtensionRangeOptions declaration. */ + public declaration: google.protobuf.ExtensionRangeOptions.IDeclaration[]; + + /** ExtensionRangeOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification. */ + public verification: google.protobuf.ExtensionRangeOptions.VerificationState; + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRangeOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @param message ExtensionRangeOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRangeOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ExtensionRangeOptions { + + /** Properties of a Declaration. */ + interface IDeclaration { + + /** Declaration number */ + number?: (number|null); + + /** Declaration fullName */ + fullName?: (string|null); + + /** Declaration type */ + type?: (string|null); + + /** Declaration reserved */ + reserved?: (boolean|null); + + /** Declaration repeated */ + repeated?: (boolean|null); + } + + /** Represents a Declaration. */ + class Declaration implements IDeclaration { + + /** + * Constructs a new Declaration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ExtensionRangeOptions.IDeclaration); + + /** Declaration number. */ + public number: number; + + /** Declaration fullName. */ + public fullName: string; + + /** Declaration type. */ + public type: string; + + /** Declaration reserved. */ + public reserved: boolean; + + /** Declaration repeated. */ + public repeated: boolean; + + /** + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Declaration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions.Declaration; + + /** + * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * @param message Declaration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions.Declaration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Declaration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Declaration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** VerificationState enum. */ + type VerificationState = + "DECLARATION"| "UNVERIFIED"; + } + + /** Properties of a FieldDescriptorProto. */ + interface IFieldDescriptorProto { + + /** FieldDescriptorProto name */ + name?: (string|null); + + /** FieldDescriptorProto number */ + number?: (number|null); + + /** FieldDescriptorProto label */ + label?: (google.protobuf.FieldDescriptorProto.Label|null); + + /** FieldDescriptorProto type */ + type?: (google.protobuf.FieldDescriptorProto.Type|null); + + /** FieldDescriptorProto typeName */ + typeName?: (string|null); + + /** FieldDescriptorProto extendee */ + extendee?: (string|null); + + /** FieldDescriptorProto defaultValue */ + defaultValue?: (string|null); + + /** FieldDescriptorProto oneofIndex */ + oneofIndex?: (number|null); + + /** FieldDescriptorProto jsonName */ + jsonName?: (string|null); + + /** FieldDescriptorProto options */ + options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional */ + proto3Optional?: (boolean|null); + } + + /** Represents a FieldDescriptorProto. */ + class FieldDescriptorProto implements IFieldDescriptorProto { + + /** + * Constructs a new FieldDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldDescriptorProto); + + /** FieldDescriptorProto name. */ + public name: string; + + /** FieldDescriptorProto number. */ + public number: number; + + /** FieldDescriptorProto label. */ + public label: google.protobuf.FieldDescriptorProto.Label; + + /** FieldDescriptorProto type. */ + public type: google.protobuf.FieldDescriptorProto.Type; + + /** FieldDescriptorProto typeName. */ + public typeName: string; + + /** FieldDescriptorProto extendee. */ + public extendee: string; + + /** FieldDescriptorProto defaultValue. */ + public defaultValue: string; + + /** FieldDescriptorProto oneofIndex. */ + public oneofIndex: number; + + /** FieldDescriptorProto jsonName. */ + public jsonName: string; + + /** FieldDescriptorProto options. */ + public options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional. */ + public proto3Optional: boolean; + + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @param message FieldDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldDescriptorProto { + + /** Type enum. */ + type Type = + "TYPE_DOUBLE"| "TYPE_FLOAT"| "TYPE_INT64"| "TYPE_UINT64"| "TYPE_INT32"| "TYPE_FIXED64"| "TYPE_FIXED32"| "TYPE_BOOL"| "TYPE_STRING"| "TYPE_GROUP"| "TYPE_MESSAGE"| "TYPE_BYTES"| "TYPE_UINT32"| "TYPE_ENUM"| "TYPE_SFIXED32"| "TYPE_SFIXED64"| "TYPE_SINT32"| "TYPE_SINT64"; + + /** Label enum. */ + type Label = + "LABEL_OPTIONAL"| "LABEL_REPEATED"| "LABEL_REQUIRED"; + } + + /** Properties of an OneofDescriptorProto. */ + interface IOneofDescriptorProto { + + /** OneofDescriptorProto name */ + name?: (string|null); + + /** OneofDescriptorProto options */ + options?: (google.protobuf.IOneofOptions|null); + } + + /** Represents an OneofDescriptorProto. */ + class OneofDescriptorProto implements IOneofDescriptorProto { + + /** + * Constructs a new OneofDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofDescriptorProto); + + /** OneofDescriptorProto name. */ + public name: string; + + /** OneofDescriptorProto options. */ + public options?: (google.protobuf.IOneofOptions|null); + + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; + + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @param message OneofDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumDescriptorProto. */ + interface IEnumDescriptorProto { + + /** EnumDescriptorProto name */ + name?: (string|null); + + /** EnumDescriptorProto value */ + value?: (google.protobuf.IEnumValueDescriptorProto[]|null); + + /** EnumDescriptorProto options */ + options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange */ + reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); + + /** EnumDescriptorProto reservedName */ + reservedName?: (string[]|null); + } + + /** Represents an EnumDescriptorProto. */ + class EnumDescriptorProto implements IEnumDescriptorProto { + + /** + * Constructs a new EnumDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumDescriptorProto); + + /** EnumDescriptorProto name. */ + public name: string; + + /** EnumDescriptorProto value. */ + public value: google.protobuf.IEnumValueDescriptorProto[]; + + /** EnumDescriptorProto options. */ + public options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange. */ + public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; + + /** EnumDescriptorProto reservedName. */ + public reservedName: string[]; + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; + + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @param message EnumDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace EnumDescriptorProto { + + /** Properties of an EnumReservedRange. */ + interface IEnumReservedRange { + + /** EnumReservedRange start */ + start?: (number|null); + + /** EnumReservedRange end */ + end?: (number|null); + } + + /** Represents an EnumReservedRange. */ + class EnumReservedRange implements IEnumReservedRange { + + /** + * Constructs a new EnumReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); + + /** EnumReservedRange start. */ + public start: number; + + /** EnumReservedRange end. */ + public end: number; + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @param message EnumReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an EnumValueDescriptorProto. */ + interface IEnumValueDescriptorProto { + + /** EnumValueDescriptorProto name */ + name?: (string|null); + + /** EnumValueDescriptorProto number */ + number?: (number|null); + + /** EnumValueDescriptorProto options */ + options?: (google.protobuf.IEnumValueOptions|null); + } + + /** Represents an EnumValueDescriptorProto. */ + class EnumValueDescriptorProto implements IEnumValueDescriptorProto { + + /** + * Constructs a new EnumValueDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueDescriptorProto); + + /** EnumValueDescriptorProto name. */ + public name: string; + + /** EnumValueDescriptorProto number. */ + public number: number; + + /** EnumValueDescriptorProto options. */ + public options?: (google.protobuf.IEnumValueOptions|null); + + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; + + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @param message EnumValueDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceDescriptorProto. */ + interface IServiceDescriptorProto { + + /** ServiceDescriptorProto name */ + name?: (string|null); + + /** ServiceDescriptorProto method */ + method?: (google.protobuf.IMethodDescriptorProto[]|null); + + /** ServiceDescriptorProto options */ + options?: (google.protobuf.IServiceOptions|null); + } + + /** Represents a ServiceDescriptorProto. */ + class ServiceDescriptorProto implements IServiceDescriptorProto { + + /** + * Constructs a new ServiceDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceDescriptorProto); + + /** ServiceDescriptorProto name. */ + public name: string; + + /** ServiceDescriptorProto method. */ + public method: google.protobuf.IMethodDescriptorProto[]; + + /** ServiceDescriptorProto options. */ + public options?: (google.protobuf.IServiceOptions|null); + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @param message ServiceDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodDescriptorProto. */ + interface IMethodDescriptorProto { + + /** MethodDescriptorProto name */ + name?: (string|null); + + /** MethodDescriptorProto inputType */ + inputType?: (string|null); + + /** MethodDescriptorProto outputType */ + outputType?: (string|null); + + /** MethodDescriptorProto options */ + options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming */ + clientStreaming?: (boolean|null); + + /** MethodDescriptorProto serverStreaming */ + serverStreaming?: (boolean|null); + } + + /** Represents a MethodDescriptorProto. */ + class MethodDescriptorProto implements IMethodDescriptorProto { + + /** + * Constructs a new MethodDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodDescriptorProto); + + /** MethodDescriptorProto name. */ + public name: string; + + /** MethodDescriptorProto inputType. */ + public inputType: string; + + /** MethodDescriptorProto outputType. */ + public outputType: string; + + /** MethodDescriptorProto options. */ + public options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming. */ + public clientStreaming: boolean; + + /** MethodDescriptorProto serverStreaming. */ + public serverStreaming: boolean; + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @param message MethodDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FileOptions. */ + interface IFileOptions { + + /** FileOptions javaPackage */ + javaPackage?: (string|null); + + /** FileOptions javaOuterClassname */ + javaOuterClassname?: (string|null); + + /** FileOptions javaMultipleFiles */ + javaMultipleFiles?: (boolean|null); + + /** FileOptions javaGenerateEqualsAndHash */ + javaGenerateEqualsAndHash?: (boolean|null); + + /** FileOptions javaStringCheckUtf8 */ + javaStringCheckUtf8?: (boolean|null); + + /** FileOptions optimizeFor */ + optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); + + /** FileOptions goPackage */ + goPackage?: (string|null); + + /** FileOptions ccGenericServices */ + ccGenericServices?: (boolean|null); + + /** FileOptions javaGenericServices */ + javaGenericServices?: (boolean|null); + + /** FileOptions pyGenericServices */ + pyGenericServices?: (boolean|null); + + /** FileOptions deprecated */ + deprecated?: (boolean|null); + + /** FileOptions ccEnableArenas */ + ccEnableArenas?: (boolean|null); + + /** FileOptions objcClassPrefix */ + objcClassPrefix?: (string|null); + + /** FileOptions csharpNamespace */ + csharpNamespace?: (string|null); + + /** FileOptions swiftPrefix */ + swiftPrefix?: (string|null); + + /** FileOptions phpClassPrefix */ + phpClassPrefix?: (string|null); + + /** FileOptions phpNamespace */ + phpNamespace?: (string|null); + + /** FileOptions phpMetadataNamespace */ + phpMetadataNamespace?: (string|null); + + /** FileOptions rubyPackage */ + rubyPackage?: (string|null); + + /** FileOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FileOptions .google.api.resourceDefinition */ + ".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null); + } + + /** Represents a FileOptions. */ + class FileOptions implements IFileOptions { + + /** + * Constructs a new FileOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileOptions); + + /** FileOptions javaPackage. */ + public javaPackage: string; + + /** FileOptions javaOuterClassname. */ + public javaOuterClassname: string; + + /** FileOptions javaMultipleFiles. */ + public javaMultipleFiles: boolean; + + /** FileOptions javaGenerateEqualsAndHash. */ + public javaGenerateEqualsAndHash: boolean; + + /** FileOptions javaStringCheckUtf8. */ + public javaStringCheckUtf8: boolean; + + /** FileOptions optimizeFor. */ + public optimizeFor: google.protobuf.FileOptions.OptimizeMode; + + /** FileOptions goPackage. */ + public goPackage: string; + + /** FileOptions ccGenericServices. */ + public ccGenericServices: boolean; + + /** FileOptions javaGenericServices. */ + public javaGenericServices: boolean; + + /** FileOptions pyGenericServices. */ + public pyGenericServices: boolean; + + /** FileOptions deprecated. */ + public deprecated: boolean; + + /** FileOptions ccEnableArenas. */ + public ccEnableArenas: boolean; + + /** FileOptions objcClassPrefix. */ + public objcClassPrefix: string; + + /** FileOptions csharpNamespace. */ + public csharpNamespace: string; + + /** FileOptions swiftPrefix. */ + public swiftPrefix: string; + + /** FileOptions phpClassPrefix. */ + public phpClassPrefix: string; + + /** FileOptions phpNamespace. */ + public phpNamespace: string; + + /** FileOptions phpMetadataNamespace. */ + public phpMetadataNamespace: string; + + /** FileOptions rubyPackage. */ + public rubyPackage: string; + + /** FileOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; + + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @param message FileOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FileOptions { + + /** OptimizeMode enum. */ + type OptimizeMode = + "SPEED"| "CODE_SIZE"| "LITE_RUNTIME"; + } + + /** Properties of a MessageOptions. */ + interface IMessageOptions { + + /** MessageOptions messageSetWireFormat */ + messageSetWireFormat?: (boolean|null); + + /** MessageOptions noStandardDescriptorAccessor */ + noStandardDescriptorAccessor?: (boolean|null); + + /** MessageOptions deprecated */ + deprecated?: (boolean|null); + + /** MessageOptions mapEntry */ + mapEntry?: (boolean|null); + + /** MessageOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** MessageOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MessageOptions .google.api.resource */ + ".google.api.resource"?: (google.api.IResourceDescriptor|null); + } + + /** Represents a MessageOptions. */ + class MessageOptions implements IMessageOptions { + + /** + * Constructs a new MessageOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMessageOptions); + + /** MessageOptions messageSetWireFormat. */ + public messageSetWireFormat: boolean; + + /** MessageOptions noStandardDescriptorAccessor. */ + public noStandardDescriptorAccessor: boolean; + + /** MessageOptions deprecated. */ + public deprecated: boolean; + + /** MessageOptions mapEntry. */ + public mapEntry: boolean; + + /** MessageOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** MessageOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MessageOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; + + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @param message MessageOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MessageOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MessageOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldOptions. */ + interface IFieldOptions { + + /** FieldOptions ctype */ + ctype?: (google.protobuf.FieldOptions.CType|null); + + /** FieldOptions packed */ + packed?: (boolean|null); + + /** FieldOptions jstype */ + jstype?: (google.protobuf.FieldOptions.JSType|null); + + /** FieldOptions lazy */ + lazy?: (boolean|null); + + /** FieldOptions unverifiedLazy */ + unverifiedLazy?: (boolean|null); + + /** FieldOptions deprecated */ + deprecated?: (boolean|null); + + /** FieldOptions weak */ + weak?: (boolean|null); + + /** FieldOptions debugRedact */ + debugRedact?: (boolean|null); + + /** FieldOptions retention */ + retention?: (google.protobuf.FieldOptions.OptionRetention|null); + + /** FieldOptions targets */ + targets?: (google.protobuf.FieldOptions.OptionTargetType[]|null); + + /** FieldOptions editionDefaults */ + editionDefaults?: (google.protobuf.FieldOptions.IEditionDefault[]|null); + + /** FieldOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FieldOptions .google.api.fieldBehavior */ + ".google.api.fieldBehavior"?: (google.api.FieldBehavior[]|null); + + /** FieldOptions .google.api.resourceReference */ + ".google.api.resourceReference"?: (google.api.IResourceReference|null); + } + + /** Represents a FieldOptions. */ + class FieldOptions implements IFieldOptions { + + /** + * Constructs a new FieldOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldOptions); + + /** FieldOptions ctype. */ + public ctype: google.protobuf.FieldOptions.CType; + + /** FieldOptions packed. */ + public packed: boolean; + + /** FieldOptions jstype. */ + public jstype: google.protobuf.FieldOptions.JSType; + + /** FieldOptions lazy. */ + public lazy: boolean; + + /** FieldOptions unverifiedLazy. */ + public unverifiedLazy: boolean; + + /** FieldOptions deprecated. */ + public deprecated: boolean; + + /** FieldOptions weak. */ + public weak: boolean; + + /** FieldOptions debugRedact. */ + public debugRedact: boolean; + + /** FieldOptions retention. */ + public retention: google.protobuf.FieldOptions.OptionRetention; + + /** FieldOptions targets. */ + public targets: google.protobuf.FieldOptions.OptionTargetType[]; + + /** FieldOptions editionDefaults. */ + public editionDefaults: google.protobuf.FieldOptions.IEditionDefault[]; + + /** FieldOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; + + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @param message FieldOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldOptions { + + /** CType enum. */ + type CType = + "STRING"| "CORD"| "STRING_PIECE"; + + /** JSType enum. */ + type JSType = + "JS_NORMAL"| "JS_STRING"| "JS_NUMBER"; + + /** OptionRetention enum. */ + type OptionRetention = + "RETENTION_UNKNOWN"| "RETENTION_RUNTIME"| "RETENTION_SOURCE"; + + /** OptionTargetType enum. */ + type OptionTargetType = + "TARGET_TYPE_UNKNOWN"| "TARGET_TYPE_FILE"| "TARGET_TYPE_EXTENSION_RANGE"| "TARGET_TYPE_MESSAGE"| "TARGET_TYPE_FIELD"| "TARGET_TYPE_ONEOF"| "TARGET_TYPE_ENUM"| "TARGET_TYPE_ENUM_ENTRY"| "TARGET_TYPE_SERVICE"| "TARGET_TYPE_METHOD"; + + /** Properties of an EditionDefault. */ + interface IEditionDefault { + + /** EditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** EditionDefault value */ + value?: (string|null); + } + + /** Represents an EditionDefault. */ + class EditionDefault implements IEditionDefault { + + /** + * Constructs a new EditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FieldOptions.IEditionDefault); + + /** EditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** EditionDefault value. */ + public value: string; + + /** + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.EditionDefault; + + /** + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * @param message EditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions.EditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an OneofOptions. */ + interface IOneofOptions { + + /** OneofOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an OneofOptions. */ + class OneofOptions implements IOneofOptions { + + /** + * Constructs a new OneofOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofOptions); + + /** OneofOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @param message OneofOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumOptions. */ + interface IEnumOptions { + + /** EnumOptions allowAlias */ + allowAlias?: (boolean|null); + + /** EnumOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** EnumOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumOptions. */ + class EnumOptions implements IEnumOptions { + + /** + * Constructs a new EnumOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumOptions); + + /** EnumOptions allowAlias. */ + public allowAlias: boolean; + + /** EnumOptions deprecated. */ + public deprecated: boolean; + + /** EnumOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** EnumOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @param message EnumOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumValueOptions. */ + interface IEnumValueOptions { + + /** EnumValueOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumValueOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact */ + debugRedact?: (boolean|null); + + /** EnumValueOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumValueOptions. */ + class EnumValueOptions implements IEnumValueOptions { + + /** + * Constructs a new EnumValueOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueOptions); + + /** EnumValueOptions deprecated. */ + public deprecated: boolean; + + /** EnumValueOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact. */ + public debugRedact: boolean; + + /** EnumValueOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; + + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @param message EnumValueOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceOptions. */ + interface IServiceOptions { + + /** ServiceOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated */ + deprecated?: (boolean|null); + + /** ServiceOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ServiceOptions .google.api.defaultHost */ + ".google.api.defaultHost"?: (string|null); + + /** ServiceOptions .google.api.oauthScopes */ + ".google.api.oauthScopes"?: (string|null); + + /** ServiceOptions .google.api.apiVersion */ + ".google.api.apiVersion"?: (string|null); + } + + /** Represents a ServiceOptions. */ + class ServiceOptions implements IServiceOptions { + + /** + * Constructs a new ServiceOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceOptions); + + /** ServiceOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated. */ + public deprecated: boolean; + + /** ServiceOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @param message ServiceOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodOptions. */ + interface IMethodOptions { + + /** MethodOptions deprecated */ + deprecated?: (boolean|null); + + /** MethodOptions idempotencyLevel */ + idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); + + /** MethodOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MethodOptions .google.api.http */ + ".google.api.http"?: (google.api.IHttpRule|null); + + /** MethodOptions .google.api.methodSignature */ + ".google.api.methodSignature"?: (string[]|null); + + /** MethodOptions .google.longrunning.operationInfo */ + ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); + } + + /** Represents a MethodOptions. */ + class MethodOptions implements IMethodOptions { + + /** + * Constructs a new MethodOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodOptions); + + /** MethodOptions deprecated. */ + public deprecated: boolean; + + /** MethodOptions idempotencyLevel. */ + public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; + + /** MethodOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; + + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @param message MethodOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodOptions { + + /** IdempotencyLevel enum. */ + type IdempotencyLevel = + "IDEMPOTENCY_UNKNOWN"| "NO_SIDE_EFFECTS"| "IDEMPOTENT"; + } + + /** Properties of an UninterpretedOption. */ + interface IUninterpretedOption { + + /** UninterpretedOption name */ + name?: (google.protobuf.UninterpretedOption.INamePart[]|null); + + /** UninterpretedOption identifierValue */ + identifierValue?: (string|null); + + /** UninterpretedOption positiveIntValue */ + positiveIntValue?: (number|string|null); + + /** UninterpretedOption negativeIntValue */ + negativeIntValue?: (number|string|null); + + /** UninterpretedOption doubleValue */ + doubleValue?: (number|null); + + /** UninterpretedOption stringValue */ + stringValue?: (Uint8Array|null); + + /** UninterpretedOption aggregateValue */ + aggregateValue?: (string|null); + } + + /** Represents an UninterpretedOption. */ + class UninterpretedOption implements IUninterpretedOption { + + /** + * Constructs a new UninterpretedOption. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUninterpretedOption); + + /** UninterpretedOption name. */ + public name: google.protobuf.UninterpretedOption.INamePart[]; + + /** UninterpretedOption identifierValue. */ + public identifierValue: string; + + /** UninterpretedOption positiveIntValue. */ + public positiveIntValue: (number|string); + + /** UninterpretedOption negativeIntValue. */ + public negativeIntValue: (number|string); + + /** UninterpretedOption doubleValue. */ + public doubleValue: number; + + /** UninterpretedOption stringValue. */ + public stringValue: Uint8Array; + + /** UninterpretedOption aggregateValue. */ + public aggregateValue: string; + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UninterpretedOption + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @param message UninterpretedOption + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UninterpretedOption to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UninterpretedOption + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UninterpretedOption { + + /** Properties of a NamePart. */ + interface INamePart { + + /** NamePart namePart */ + namePart: string; + + /** NamePart isExtension */ + isExtension: boolean; + } + + /** Represents a NamePart. */ + class NamePart implements INamePart { + + /** + * Constructs a new NamePart. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.UninterpretedOption.INamePart); + + /** NamePart namePart. */ + public namePart: string; + + /** NamePart isExtension. */ + public isExtension: boolean; + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamePart + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @param message NamePart + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamePart to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NamePart + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a FeatureSet. */ + interface IFeatureSet { + + /** FeatureSet fieldPresence */ + fieldPresence?: (google.protobuf.FeatureSet.FieldPresence|null); + + /** FeatureSet enumType */ + enumType?: (google.protobuf.FeatureSet.EnumType|null); + + /** FeatureSet repeatedFieldEncoding */ + repeatedFieldEncoding?: (google.protobuf.FeatureSet.RepeatedFieldEncoding|null); + + /** FeatureSet utf8Validation */ + utf8Validation?: (google.protobuf.FeatureSet.Utf8Validation|null); + + /** FeatureSet messageEncoding */ + messageEncoding?: (google.protobuf.FeatureSet.MessageEncoding|null); + + /** FeatureSet jsonFormat */ + jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|null); + } + + /** Represents a FeatureSet. */ + class FeatureSet implements IFeatureSet { + + /** + * Constructs a new FeatureSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSet); + + /** FeatureSet fieldPresence. */ + public fieldPresence: google.protobuf.FeatureSet.FieldPresence; + + /** FeatureSet enumType. */ + public enumType: google.protobuf.FeatureSet.EnumType; + + /** FeatureSet repeatedFieldEncoding. */ + public repeatedFieldEncoding: google.protobuf.FeatureSet.RepeatedFieldEncoding; + + /** FeatureSet utf8Validation. */ + public utf8Validation: google.protobuf.FeatureSet.Utf8Validation; + + /** FeatureSet messageEncoding. */ + public messageEncoding: google.protobuf.FeatureSet.MessageEncoding; + + /** FeatureSet jsonFormat. */ + public jsonFormat: google.protobuf.FeatureSet.JsonFormat; + + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet; + + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @param message FeatureSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSet { + + /** FieldPresence enum. */ + type FieldPresence = + "FIELD_PRESENCE_UNKNOWN"| "EXPLICIT"| "IMPLICIT"| "LEGACY_REQUIRED"; + + /** EnumType enum. */ + type EnumType = + "ENUM_TYPE_UNKNOWN"| "OPEN"| "CLOSED"; + + /** RepeatedFieldEncoding enum. */ + type RepeatedFieldEncoding = + "REPEATED_FIELD_ENCODING_UNKNOWN"| "PACKED"| "EXPANDED"; + + /** Utf8Validation enum. */ + type Utf8Validation = + "UTF8_VALIDATION_UNKNOWN"| "VERIFY"| "NONE"; + + /** MessageEncoding enum. */ + type MessageEncoding = + "MESSAGE_ENCODING_UNKNOWN"| "LENGTH_PREFIXED"| "DELIMITED"; + + /** JsonFormat enum. */ + type JsonFormat = + "JSON_FORMAT_UNKNOWN"| "ALLOW"| "LEGACY_BEST_EFFORT"; + } + + /** Properties of a FeatureSetDefaults. */ + interface IFeatureSetDefaults { + + /** FeatureSetDefaults defaults */ + defaults?: (google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]|null); + + /** FeatureSetDefaults minimumEdition */ + minimumEdition?: (google.protobuf.Edition|null); + + /** FeatureSetDefaults maximumEdition */ + maximumEdition?: (google.protobuf.Edition|null); + } + + /** Represents a FeatureSetDefaults. */ + class FeatureSetDefaults implements IFeatureSetDefaults { + + /** + * Constructs a new FeatureSetDefaults. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSetDefaults); + + /** FeatureSetDefaults defaults. */ + public defaults: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]; + + /** FeatureSetDefaults minimumEdition. */ + public minimumEdition: google.protobuf.Edition; + + /** FeatureSetDefaults maximumEdition. */ + public maximumEdition: google.protobuf.Edition; + + /** + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetDefaults + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults; + + /** + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @param message FeatureSetDefaults + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetDefaults to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetDefaults + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSetDefaults { + + /** Properties of a FeatureSetEditionDefault. */ + interface IFeatureSetEditionDefault { + + /** FeatureSetEditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** FeatureSetEditionDefault features */ + features?: (google.protobuf.IFeatureSet|null); + } + + /** Represents a FeatureSetEditionDefault. */ + class FeatureSetEditionDefault implements IFeatureSetEditionDefault { + + /** + * Constructs a new FeatureSetEditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault); + + /** FeatureSetEditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** FeatureSetEditionDefault features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetEditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault; + + /** + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * @param message FeatureSetEditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetEditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetEditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a SourceCodeInfo. */ + interface ISourceCodeInfo { + + /** SourceCodeInfo location */ + location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); + } + + /** Represents a SourceCodeInfo. */ + class SourceCodeInfo implements ISourceCodeInfo { + + /** + * Constructs a new SourceCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ISourceCodeInfo); + + /** SourceCodeInfo location. */ + public location: google.protobuf.SourceCodeInfo.ILocation[]; + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @param message SourceCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace SourceCodeInfo { + + /** Properties of a Location. */ + interface ILocation { + + /** Location path */ + path?: (number[]|null); + + /** Location span */ + span?: (number[]|null); + + /** Location leadingComments */ + leadingComments?: (string|null); + + /** Location trailingComments */ + trailingComments?: (string|null); + + /** Location leadingDetachedComments */ + leadingDetachedComments?: (string[]|null); + } + + /** Represents a Location. */ + class Location implements ILocation { + + /** + * Constructs a new Location. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); + + /** Location path. */ + public path: number[]; + + /** Location span. */ + public span: number[]; + + /** Location leadingComments. */ + public leadingComments: string; + + /** Location trailingComments. */ + public trailingComments: string; + + /** Location leadingDetachedComments. */ + public leadingDetachedComments: string[]; + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Location + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @param message Location + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Location to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Location + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a GeneratedCodeInfo. */ + interface IGeneratedCodeInfo { + + /** GeneratedCodeInfo annotation */ + annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); + } + + /** Represents a GeneratedCodeInfo. */ + class GeneratedCodeInfo implements IGeneratedCodeInfo { + + /** + * Constructs a new GeneratedCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IGeneratedCodeInfo); + + /** GeneratedCodeInfo annotation. */ + public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; + + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GeneratedCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; + + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @param message GeneratedCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GeneratedCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace GeneratedCodeInfo { + + /** Properties of an Annotation. */ + interface IAnnotation { + + /** Annotation path */ + path?: (number[]|null); + + /** Annotation sourceFile */ + sourceFile?: (string|null); + + /** Annotation begin */ + begin?: (number|null); + + /** Annotation end */ + end?: (number|null); + + /** Annotation semantic */ + semantic?: (google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null); + } + + /** Represents an Annotation. */ + class Annotation implements IAnnotation { + + /** + * Constructs a new Annotation. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); + + /** Annotation path. */ + public path: number[]; + + /** Annotation sourceFile. */ + public sourceFile: string; + + /** Annotation begin. */ + public begin: number; + + /** Annotation end. */ + public end: number; + + /** Annotation semantic. */ + public semantic: google.protobuf.GeneratedCodeInfo.Annotation.Semantic; + + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Annotation + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @param message Annotation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Annotation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Annotation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Annotation { + + /** Semantic enum. */ + type Semantic = + "NONE"| "SET"| "ALIAS"; + } + } + + /** Properties of a Struct. */ + interface IStruct { + + /** Struct fields */ + fields?: ({ [k: string]: google.protobuf.IValue }|null); + } + + /** Represents a Struct. */ + class Struct implements IStruct { + + /** + * Constructs a new Struct. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStruct); + + /** Struct fields. */ + public fields: { [k: string]: google.protobuf.IValue }; + + /** + * Creates a Struct message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Struct + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; + + /** + * Creates a plain object from a Struct message. Also converts values to other types if specified. + * @param message Struct + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Struct to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Struct + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Value. */ + interface IValue { + + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue */ + numberValue?: (number|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value boolValue */ + boolValue?: (boolean|null); + + /** Value structValue */ + structValue?: (google.protobuf.IStruct|null); + + /** Value listValue */ + listValue?: (google.protobuf.IListValue|null); + } + + /** Represents a Value. */ + class Value implements IValue { + + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IValue); + + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue. */ + public numberValue?: (number|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value boolValue. */ + public boolValue?: (boolean|null); + + /** Value structValue. */ + public structValue?: (google.protobuf.IStruct|null); + + /** Value listValue. */ + public listValue?: (google.protobuf.IListValue|null); + + /** Value kind. */ + public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Value; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** NullValue enum. */ + type NullValue = + "NULL_VALUE"; + + /** Properties of a ListValue. */ + interface IListValue { + + /** ListValue values */ + values?: (google.protobuf.IValue[]|null); + } + + /** Represents a ListValue. */ + class ListValue implements IListValue { + + /** + * Constructs a new ListValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IListValue); + + /** ListValue values. */ + public values: google.protobuf.IValue[]; + + /** + * Creates a ListValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; + + /** + * Creates a plain object from a ListValue message. Also converts values to other types if specified. + * @param message ListValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Timestamp. */ + interface ITimestamp { + + /** Timestamp seconds */ + seconds?: (number|string|null); + + /** Timestamp nanos */ + nanos?: (number|null); + } + + /** Represents a Timestamp. */ + class Timestamp implements ITimestamp { + + /** + * Constructs a new Timestamp. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ITimestamp); + + /** Timestamp seconds. */ + public seconds: (number|string); + + /** Timestamp nanos. */ + public nanos: number; + + /** + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Timestamp + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; + + /** + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * @param message Timestamp + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Timestamp to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Timestamp + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Duration. */ + interface IDuration { + + /** Duration seconds */ + seconds?: (number|string|null); + + /** Duration nanos */ + nanos?: (number|null); + } + + /** Represents a Duration. */ + class Duration implements IDuration { + + /** + * Constructs a new Duration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDuration); + + /** Duration seconds. */ + public seconds: (number|string); + + /** Duration nanos. */ + public nanos: number; + + /** + * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Duration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; + + /** + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @param message Duration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Duration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Duration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DoubleValue. */ + interface IDoubleValue { + + /** DoubleValue value */ + value?: (number|null); + } + + /** Represents a DoubleValue. */ + class DoubleValue implements IDoubleValue { + + /** + * Constructs a new DoubleValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDoubleValue); + + /** DoubleValue value. */ + public value: number; + + /** + * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DoubleValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DoubleValue; + + /** + * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. + * @param message DoubleValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DoubleValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DoubleValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DoubleValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FloatValue. */ + interface IFloatValue { + + /** FloatValue value */ + value?: (number|null); + } + + /** Represents a FloatValue. */ + class FloatValue implements IFloatValue { + + /** + * Constructs a new FloatValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFloatValue); + + /** FloatValue value. */ + public value: number; + + /** + * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FloatValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FloatValue; + + /** + * Creates a plain object from a FloatValue message. Also converts values to other types if specified. + * @param message FloatValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FloatValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FloatValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FloatValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int64Value. */ + interface IInt64Value { + + /** Int64Value value */ + value?: (number|string|null); + } + + /** Represents an Int64Value. */ + class Int64Value implements IInt64Value { + + /** + * Constructs a new Int64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt64Value); + + /** Int64Value value. */ + public value: (number|string); + + /** + * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int64Value; + + /** + * Creates a plain object from an Int64Value message. Also converts values to other types if specified. + * @param message Int64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt64Value. */ + interface IUInt64Value { + + /** UInt64Value value */ + value?: (number|string|null); + } + + /** Represents a UInt64Value. */ + class UInt64Value implements IUInt64Value { + + /** + * Constructs a new UInt64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt64Value); + + /** UInt64Value value. */ + public value: (number|string); + + /** + * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt64Value; + + /** + * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. + * @param message UInt64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Int32Value. */ + interface IInt32Value { + + /** Int32Value value */ + value?: (number|null); + } + + /** Represents an Int32Value. */ + class Int32Value implements IInt32Value { + + /** + * Constructs a new Int32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt32Value); + + /** Int32Value value. */ + public value: number; + + /** + * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int32Value; + + /** + * Creates a plain object from an Int32Value message. Also converts values to other types if specified. + * @param message Int32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Int32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UInt32Value. */ + interface IUInt32Value { + + /** UInt32Value value */ + value?: (number|null); + } + + /** Represents a UInt32Value. */ + class UInt32Value implements IUInt32Value { + + /** + * Constructs a new UInt32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt32Value); + + /** UInt32Value value. */ + public value: number; + + /** + * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt32Value; + + /** + * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. + * @param message UInt32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UInt32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BoolValue. */ + interface IBoolValue { + + /** BoolValue value */ + value?: (boolean|null); + } + + /** Represents a BoolValue. */ + class BoolValue implements IBoolValue { + + /** + * Constructs a new BoolValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBoolValue); + + /** BoolValue value. */ + public value: boolean; + + /** + * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BoolValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BoolValue; + + /** + * Creates a plain object from a BoolValue message. Also converts values to other types if specified. + * @param message BoolValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BoolValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BoolValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BoolValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StringValue. */ + interface IStringValue { + + /** StringValue value */ + value?: (string|null); + } + + /** Represents a StringValue. */ + class StringValue implements IStringValue { + + /** + * Constructs a new StringValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStringValue); + + /** StringValue value. */ + public value: string; + + /** + * Creates a StringValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StringValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.StringValue; + + /** + * Creates a plain object from a StringValue message. Also converts values to other types if specified. + * @param message StringValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.StringValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StringValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StringValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BytesValue. */ + interface IBytesValue { + + /** BytesValue value */ + value?: (Uint8Array|null); + } + + /** Represents a BytesValue. */ + class BytesValue implements IBytesValue { + + /** + * Constructs a new BytesValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IBytesValue); + + /** BytesValue value. */ + public value: Uint8Array; + + /** + * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BytesValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BytesValue; + + /** + * Creates a plain object from a BytesValue message. Also converts values to other types if specified. + * @param message BytesValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BytesValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BytesValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BytesValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Empty. */ + interface IEmpty { + } + + /** Represents an Empty. */ + class Empty implements IEmpty { + + /** + * Constructs a new Empty. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEmpty); + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Empty + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @param message Empty + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Empty to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Empty + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Any. */ + interface IAny { + + /** Any type_url */ + type_url?: (string|null); + + /** Any value */ + value?: (Uint8Array|null); + } + + /** Represents an Any. */ + class Any implements IAny { + + /** + * Constructs a new Any. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IAny); + + /** Any type_url. */ + public type_url: string; + + /** Any value. */ + public value: Uint8Array; + + /** + * Creates an Any message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Any + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Any; + + /** + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @param message Any + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Any to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Any + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldMask. */ + interface IFieldMask { + + /** FieldMask paths */ + paths?: (string[]|null); + } + + /** Represents a FieldMask. */ + class FieldMask implements IFieldMask { + + /** + * Constructs a new FieldMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldMask); + + /** FieldMask paths. */ + public paths: string[]; + + /** + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldMask + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; + + /** + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @param message FieldMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace type. */ + namespace type { + + /** Properties of a LatLng. */ + interface ILatLng { + + /** LatLng latitude */ + latitude?: (number|null); + + /** LatLng longitude */ + longitude?: (number|null); + } + + /** Represents a LatLng. */ + class LatLng implements ILatLng { + + /** + * Constructs a new LatLng. + * @param [properties] Properties to set + */ + constructor(properties?: google.type.ILatLng); + + /** LatLng latitude. */ + public latitude: number; + + /** LatLng longitude. */ + public longitude: number; + + /** + * Creates a LatLng message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LatLng + */ + public static fromObject(object: { [k: string]: any }): google.type.LatLng; + + /** + * Creates a plain object from a LatLng message. Also converts values to other types if specified. + * @param message LatLng + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.type.LatLng, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LatLng to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LatLng + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** DayOfWeek enum. */ + type DayOfWeek = + "DAY_OF_WEEK_UNSPECIFIED"| "MONDAY"| "TUESDAY"| "WEDNESDAY"| "THURSDAY"| "FRIDAY"| "SATURDAY"| "SUNDAY"; + } + + /** Namespace rpc. */ + namespace rpc { + + /** Properties of a Status. */ + interface IStatus { + + /** Status code */ + code?: (number|null); + + /** Status message */ + message?: (string|null); + + /** Status details */ + details?: (google.protobuf.IAny[]|null); + } + + /** Represents a Status. */ + class Status implements IStatus { + + /** + * Constructs a new Status. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IStatus); + + /** Status code. */ + public code: number; + + /** Status message. */ + public message: string; + + /** Status details. */ + public details: google.protobuf.IAny[]; + + /** + * Creates a Status message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Status + */ + public static fromObject(object: { [k: string]: any }): google.rpc.Status; + + /** + * Creates a plain object from a Status message. Also converts values to other types if specified. + * @param message Status + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Status to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Status + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace longrunning. */ + namespace longrunning { + + /** Represents an Operations */ + class Operations extends $protobuf.rpc.Service { + + /** + * Constructs a new Operations service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListOperationsResponse + */ + public listOperations(request: google.longrunning.IListOperationsRequest, callback: google.longrunning.Operations.ListOperationsCallback): void; + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @returns Promise + */ + public listOperations(request: google.longrunning.IListOperationsRequest): Promise; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public getOperation(request: google.longrunning.IGetOperationRequest, callback: google.longrunning.Operations.GetOperationCallback): void; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @returns Promise + */ + public getOperation(request: google.longrunning.IGetOperationRequest): Promise; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest, callback: google.longrunning.Operations.DeleteOperationCallback): void; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @returns Promise + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest): Promise; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest, callback: google.longrunning.Operations.CancelOperationCallback): void; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @returns Promise + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest): Promise; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest, callback: google.longrunning.Operations.WaitOperationCallback): void; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @returns Promise + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest): Promise; + } + + namespace Operations { + + /** + * Callback as used by {@link google.longrunning.Operations#listOperations}. + * @param error Error, if any + * @param [response] ListOperationsResponse + */ + type ListOperationsCallback = (error: (Error|null), response?: google.longrunning.ListOperationsResponse) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#getOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type GetOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#deleteOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#cancelOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type CancelOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#waitOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type WaitOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + } + + /** Properties of an Operation. */ + interface IOperation { + + /** Operation name */ + name?: (string|null); + + /** Operation metadata */ + metadata?: (google.protobuf.IAny|null); + + /** Operation done */ + done?: (boolean|null); + + /** Operation error */ + error?: (google.rpc.IStatus|null); + + /** Operation response */ + response?: (google.protobuf.IAny|null); + } + + /** Represents an Operation. */ + class Operation implements IOperation { + + /** + * Constructs a new Operation. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperation); + + /** Operation name. */ + public name: string; + + /** Operation metadata. */ + public metadata?: (google.protobuf.IAny|null); + + /** Operation done. */ + public done: boolean; + + /** Operation error. */ + public error?: (google.rpc.IStatus|null); + + /** Operation response. */ + public response?: (google.protobuf.IAny|null); + + /** Operation result. */ + public result?: ("error"|"response"); + + /** + * Creates an Operation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Operation + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.Operation; + + /** + * Creates a plain object from an Operation message. Also converts values to other types if specified. + * @param message Operation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.Operation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Operation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Operation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetOperationRequest. */ + interface IGetOperationRequest { + + /** GetOperationRequest name */ + name?: (string|null); + } + + /** Represents a GetOperationRequest. */ + class GetOperationRequest implements IGetOperationRequest { + + /** + * Constructs a new GetOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IGetOperationRequest); + + /** GetOperationRequest name. */ + public name: string; + + /** + * Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.GetOperationRequest; + + /** + * Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified. + * @param message GetOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.GetOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsRequest. */ + interface IListOperationsRequest { + + /** ListOperationsRequest name */ + name?: (string|null); + + /** ListOperationsRequest filter */ + filter?: (string|null); + + /** ListOperationsRequest pageSize */ + pageSize?: (number|null); + + /** ListOperationsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListOperationsRequest. */ + class ListOperationsRequest implements IListOperationsRequest { + + /** + * Constructs a new ListOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsRequest); + + /** ListOperationsRequest name. */ + public name: string; + + /** ListOperationsRequest filter. */ + public filter: string; + + /** ListOperationsRequest pageSize. */ + public pageSize: number; + + /** ListOperationsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsRequest; + + /** + * Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified. + * @param message ListOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsResponse. */ + interface IListOperationsResponse { + + /** ListOperationsResponse operations */ + operations?: (google.longrunning.IOperation[]|null); + + /** ListOperationsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListOperationsResponse. */ + class ListOperationsResponse implements IListOperationsResponse { + + /** + * Constructs a new ListOperationsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsResponse); + + /** ListOperationsResponse operations. */ + public operations: google.longrunning.IOperation[]; + + /** ListOperationsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsResponse + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsResponse; + + /** + * Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified. + * @param message ListOperationsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CancelOperationRequest. */ + interface ICancelOperationRequest { + + /** CancelOperationRequest name */ + name?: (string|null); + } + + /** Represents a CancelOperationRequest. */ + class CancelOperationRequest implements ICancelOperationRequest { + + /** + * Constructs a new CancelOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.ICancelOperationRequest); + + /** CancelOperationRequest name. */ + public name: string; + + /** + * Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CancelOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.CancelOperationRequest; + + /** + * Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified. + * @param message CancelOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.CancelOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CancelOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CancelOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteOperationRequest. */ + interface IDeleteOperationRequest { + + /** DeleteOperationRequest name */ + name?: (string|null); + } + + /** Represents a DeleteOperationRequest. */ + class DeleteOperationRequest implements IDeleteOperationRequest { + + /** + * Constructs a new DeleteOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IDeleteOperationRequest); + + /** DeleteOperationRequest name. */ + public name: string; + + /** + * Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.DeleteOperationRequest; + + /** + * Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified. + * @param message DeleteOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.DeleteOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WaitOperationRequest. */ + interface IWaitOperationRequest { + + /** WaitOperationRequest name */ + name?: (string|null); + + /** WaitOperationRequest timeout */ + timeout?: (google.protobuf.IDuration|null); + } + + /** Represents a WaitOperationRequest. */ + class WaitOperationRequest implements IWaitOperationRequest { + + /** + * Constructs a new WaitOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IWaitOperationRequest); + + /** WaitOperationRequest name. */ + public name: string; + + /** WaitOperationRequest timeout. */ + public timeout?: (google.protobuf.IDuration|null); + + /** + * Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WaitOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.WaitOperationRequest; + + /** + * Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified. + * @param message WaitOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.WaitOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WaitOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WaitOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an OperationInfo. */ + interface IOperationInfo { + + /** OperationInfo responseType */ + responseType?: (string|null); + + /** OperationInfo metadataType */ + metadataType?: (string|null); + } + + /** Represents an OperationInfo. */ + class OperationInfo implements IOperationInfo { + + /** + * Constructs a new OperationInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperationInfo); + + /** OperationInfo responseType. */ + public responseType: string; + + /** OperationInfo metadataType. */ + public metadataType: string; + + /** + * Creates an OperationInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OperationInfo + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.OperationInfo; + + /** + * Creates a plain object from an OperationInfo message. Also converts values to other types if specified. + * @param message OperationInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.OperationInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OperationInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OperationInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } +} diff --git a/node_modules/@google-cloud/firestore/build/protos/firestore_v1_proto_api.js b/node_modules/@google-cloud/firestore/build/protos/firestore_v1_proto_api.js new file mode 100644 index 0000000..5ebb5d8 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/firestore_v1_proto_api.js @@ -0,0 +1 @@ +(e=>{"function"==typeof define&&define.amd?define(["protobufjs/minimal"],e):"function"==typeof require&&"object"==typeof module&&module&&module.exports&&(module.exports=e(require("protobufjs/minimal")))})(function(r){var e,t,o,n,C,i=r.util,a=r.roots.firestore_v1||(r.roots.firestore_v1={});function V(e){if(e)for(var t=Object.keys(e),o=0;o>>0),null!=e.totalDocuments&&(t.totalDocuments=e.totalDocuments>>>0),null!=e.totalBytes&&(i.Long?(t.totalBytes=i.Long.fromValue(e.totalBytes)).unsigned=!0:"string"==typeof e.totalBytes?t.totalBytes=parseInt(e.totalBytes,10):"number"==typeof e.totalBytes?t.totalBytes=e.totalBytes:"object"==typeof e.totalBytes&&(t.totalBytes=new i.LongBits(e.totalBytes.low>>>0,e.totalBytes.high>>>0).toNumber(!0))),t},B.toObject=function(e,t){var o,r={};return(t=t||{}).defaults&&(r.id="",r.createTime=null,r.version=0,r.totalDocuments=0,i.Long?(o=new i.Long(0,0,!0),r.totalBytes=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.totalBytes=t.longs===String?"0":0),null!=e.id&&e.hasOwnProperty("id")&&(r.id=e.id),null!=e.createTime&&e.hasOwnProperty("createTime")&&(r.createTime=a.google.protobuf.Timestamp.toObject(e.createTime,t)),null!=e.version&&e.hasOwnProperty("version")&&(r.version=e.version),null!=e.totalDocuments&&e.hasOwnProperty("totalDocuments")&&(r.totalDocuments=e.totalDocuments),null!=e.totalBytes&&e.hasOwnProperty("totalBytes")&&("number"==typeof e.totalBytes?r.totalBytes=t.longs===String?String(e.totalBytes):e.totalBytes:r.totalBytes=t.longs===String?i.Long.prototype.toString.call(e.totalBytes):t.longs===Number?new i.LongBits(e.totalBytes.low>>>0,e.totalBytes.high>>>0).toNumber(!0):e.totalBytes),r},B.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},B.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/firestore.BundleMetadata"},B),o.BundleElement=(J.prototype.metadata=null,J.prototype.namedQuery=null,J.prototype.documentMetadata=null,J.prototype.document=null,Object.defineProperty(J.prototype,"elementType",{get:i.oneOfGetter(t=["metadata","namedQuery","documentMetadata","document"]),set:i.oneOfSetter(t)}),J.fromObject=function(e){if(e instanceof a.firestore.BundleElement)return e;var t=new a.firestore.BundleElement;if(null!=e.metadata){if("object"!=typeof e.metadata)throw TypeError(".firestore.BundleElement.metadata: object expected");t.metadata=a.firestore.BundleMetadata.fromObject(e.metadata)}if(null!=e.namedQuery){if("object"!=typeof e.namedQuery)throw TypeError(".firestore.BundleElement.namedQuery: object expected");t.namedQuery=a.firestore.NamedQuery.fromObject(e.namedQuery)}if(null!=e.documentMetadata){if("object"!=typeof e.documentMetadata)throw TypeError(".firestore.BundleElement.documentMetadata: object expected");t.documentMetadata=a.firestore.BundledDocumentMetadata.fromObject(e.documentMetadata)}if(null!=e.document){if("object"!=typeof e.document)throw TypeError(".firestore.BundleElement.document: object expected");t.document=a.google.firestore.v1.Document.fromObject(e.document)}return t},J.toObject=function(e,t){t=t||{};var o={};return null!=e.metadata&&e.hasOwnProperty("metadata")&&(o.metadata=a.firestore.BundleMetadata.toObject(e.metadata,t),t.oneofs)&&(o.elementType="metadata"),null!=e.namedQuery&&e.hasOwnProperty("namedQuery")&&(o.namedQuery=a.firestore.NamedQuery.toObject(e.namedQuery,t),t.oneofs)&&(o.elementType="namedQuery"),null!=e.documentMetadata&&e.hasOwnProperty("documentMetadata")&&(o.documentMetadata=a.firestore.BundledDocumentMetadata.toObject(e.documentMetadata,t),t.oneofs)&&(o.elementType="documentMetadata"),null!=e.document&&e.hasOwnProperty("document")&&(o.document=a.google.firestore.v1.Document.toObject(e.document,t),t.oneofs)&&(o.elementType="document"),o},J.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},J.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/firestore.BundleElement"},J),o),a.google=((C={}).firestore=((t={}).v1=((o={}).AggregationResult=(Q.prototype.aggregateFields=i.emptyObject,Q.fromObject=function(e){if(e instanceof a.google.firestore.v1.AggregationResult)return e;var t=new a.google.firestore.v1.AggregationResult;if(e.aggregateFields){if("object"!=typeof e.aggregateFields)throw TypeError(".google.firestore.v1.AggregationResult.aggregateFields: object expected");t.aggregateFields={};for(var o=Object.keys(e.aggregateFields),r=0;r>>0,e.integerValue.high>>>0).toNumber())),null!=e.doubleValue&&(t.doubleValue=Number(e.doubleValue)),null!=e.timestampValue){if("object"!=typeof e.timestampValue)throw TypeError(".google.firestore.v1.Value.timestampValue: object expected");t.timestampValue=a.google.protobuf.Timestamp.fromObject(e.timestampValue)}if(null!=e.stringValue&&(t.stringValue=String(e.stringValue)),null!=e.bytesValue&&("string"==typeof e.bytesValue?i.base64.decode(e.bytesValue,t.bytesValue=i.newBuffer(i.base64.length(e.bytesValue)),0):0<=e.bytesValue.length&&(t.bytesValue=e.bytesValue)),null!=e.referenceValue&&(t.referenceValue=String(e.referenceValue)),null!=e.geoPointValue){if("object"!=typeof e.geoPointValue)throw TypeError(".google.firestore.v1.Value.geoPointValue: object expected");t.geoPointValue=a.google.type.LatLng.fromObject(e.geoPointValue)}if(null!=e.arrayValue){if("object"!=typeof e.arrayValue)throw TypeError(".google.firestore.v1.Value.arrayValue: object expected");t.arrayValue=a.google.firestore.v1.ArrayValue.fromObject(e.arrayValue)}if(null!=e.mapValue){if("object"!=typeof e.mapValue)throw TypeError(".google.firestore.v1.Value.mapValue: object expected");t.mapValue=a.google.firestore.v1.MapValue.fromObject(e.mapValue)}return t},s.toObject=function(e,t){t=t||{};var o={};return null!=e.booleanValue&&e.hasOwnProperty("booleanValue")&&(o.booleanValue=e.booleanValue,t.oneofs)&&(o.valueType="booleanValue"),null!=e.integerValue&&e.hasOwnProperty("integerValue")&&("number"==typeof e.integerValue?o.integerValue=t.longs===String?String(e.integerValue):e.integerValue:o.integerValue=t.longs===String?i.Long.prototype.toString.call(e.integerValue):t.longs===Number?new i.LongBits(e.integerValue.low>>>0,e.integerValue.high>>>0).toNumber():e.integerValue,t.oneofs)&&(o.valueType="integerValue"),null!=e.doubleValue&&e.hasOwnProperty("doubleValue")&&(o.doubleValue=t.json&&!isFinite(e.doubleValue)?String(e.doubleValue):e.doubleValue,t.oneofs)&&(o.valueType="doubleValue"),null!=e.referenceValue&&e.hasOwnProperty("referenceValue")&&(o.referenceValue=e.referenceValue,t.oneofs)&&(o.valueType="referenceValue"),null!=e.mapValue&&e.hasOwnProperty("mapValue")&&(o.mapValue=a.google.firestore.v1.MapValue.toObject(e.mapValue,t),t.oneofs)&&(o.valueType="mapValue"),null!=e.geoPointValue&&e.hasOwnProperty("geoPointValue")&&(o.geoPointValue=a.google.type.LatLng.toObject(e.geoPointValue,t),t.oneofs)&&(o.valueType="geoPointValue"),null!=e.arrayValue&&e.hasOwnProperty("arrayValue")&&(o.arrayValue=a.google.firestore.v1.ArrayValue.toObject(e.arrayValue,t),t.oneofs)&&(o.valueType="arrayValue"),null!=e.timestampValue&&e.hasOwnProperty("timestampValue")&&(o.timestampValue=a.google.protobuf.Timestamp.toObject(e.timestampValue,t),t.oneofs)&&(o.valueType="timestampValue"),null!=e.nullValue&&e.hasOwnProperty("nullValue")&&(o.nullValue=t.enums!==String||void 0===a.google.protobuf.NullValue[e.nullValue]?e.nullValue:a.google.protobuf.NullValue[e.nullValue],t.oneofs)&&(o.valueType="nullValue"),null!=e.stringValue&&e.hasOwnProperty("stringValue")&&(o.stringValue=e.stringValue,t.oneofs)&&(o.valueType="stringValue"),null!=e.bytesValue&&e.hasOwnProperty("bytesValue")&&(o.bytesValue=t.bytes===String?i.base64.encode(e.bytesValue,0,e.bytesValue.length):t.bytes===Array?Array.prototype.slice.call(e.bytesValue):e.bytesValue,t.oneofs)&&(o.valueType="bytesValue"),o},s.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},s.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.firestore.v1.Value"},s),o.ArrayValue=(G.prototype.values=i.emptyArray,G.fromObject=function(e){if(e instanceof a.google.firestore.v1.ArrayValue)return e;var t=new a.google.firestore.v1.ArrayValue;if(e.values){if(!Array.isArray(e.values))throw TypeError(".google.firestore.v1.ArrayValue.values: array expected");t.values=[];for(var o=0;o>>0,e.partitionCount.high>>>0).toNumber())),null!=e.pageToken&&(t.pageToken=String(e.pageToken)),null!=e.pageSize&&(t.pageSize=0|e.pageSize),null!=e.readTime){if("object"!=typeof e.readTime)throw TypeError(".google.firestore.v1.PartitionQueryRequest.readTime: object expected");t.readTime=a.google.protobuf.Timestamp.fromObject(e.readTime)}return t},d.toObject=function(e,t){var o,r={};return(t=t||{}).defaults&&(r.parent="",i.Long?(o=new i.Long(0,0,!1),r.partitionCount=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.partitionCount=t.longs===String?"0":0,r.pageToken="",r.pageSize=0),null!=e.parent&&e.hasOwnProperty("parent")&&(r.parent=e.parent),null!=e.structuredQuery&&e.hasOwnProperty("structuredQuery")&&(r.structuredQuery=a.google.firestore.v1.StructuredQuery.toObject(e.structuredQuery,t),t.oneofs)&&(r.queryType="structuredQuery"),null!=e.partitionCount&&e.hasOwnProperty("partitionCount")&&("number"==typeof e.partitionCount?r.partitionCount=t.longs===String?String(e.partitionCount):e.partitionCount:r.partitionCount=t.longs===String?i.Long.prototype.toString.call(e.partitionCount):t.longs===Number?new i.LongBits(e.partitionCount.low>>>0,e.partitionCount.high>>>0).toNumber():e.partitionCount),null!=e.pageToken&&e.hasOwnProperty("pageToken")&&(r.pageToken=e.pageToken),null!=e.pageSize&&e.hasOwnProperty("pageSize")&&(r.pageSize=e.pageSize),null!=e.readTime&&e.hasOwnProperty("readTime")&&(r.readTime=a.google.protobuf.Timestamp.toObject(e.readTime,t),t.oneofs)&&(r.consistencySelector="readTime"),r},d.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},d.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.firestore.v1.PartitionQueryRequest"},d),o.PartitionQueryResponse=(ce.prototype.partitions=i.emptyArray,ce.prototype.nextPageToken="",ce.fromObject=function(e){if(e instanceof a.google.firestore.v1.PartitionQueryResponse)return e;var t=new a.google.firestore.v1.PartitionQueryResponse;if(e.partitions){if(!Array.isArray(e.partitions))throw TypeError(".google.firestore.v1.PartitionQueryResponse.partitions: array expected");t.partitions=[];for(var o=0;o>>0,e.resultsReturned.high>>>0).toNumber())),null!=e.executionDuration){if("object"!=typeof e.executionDuration)throw TypeError(".google.firestore.v1.ExecutionStats.executionDuration: object expected");t.executionDuration=a.google.protobuf.Duration.fromObject(e.executionDuration)}if(null!=e.readOperations&&(i.Long?(t.readOperations=i.Long.fromValue(e.readOperations)).unsigned=!1:"string"==typeof e.readOperations?t.readOperations=parseInt(e.readOperations,10):"number"==typeof e.readOperations?t.readOperations=e.readOperations:"object"==typeof e.readOperations&&(t.readOperations=new i.LongBits(e.readOperations.low>>>0,e.readOperations.high>>>0).toNumber())),null!=e.debugStats){if("object"!=typeof e.debugStats)throw TypeError(".google.firestore.v1.ExecutionStats.debugStats: object expected");t.debugStats=a.google.protobuf.Struct.fromObject(e.debugStats)}return t},Le.toObject=function(e,t){var o,r={};return(t=t||{}).defaults&&(i.Long?(o=new i.Long(0,0,!1),r.resultsReturned=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.resultsReturned=t.longs===String?"0":0,r.executionDuration=null,i.Long?(o=new i.Long(0,0,!1),r.readOperations=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.readOperations=t.longs===String?"0":0,r.debugStats=null),null!=e.resultsReturned&&e.hasOwnProperty("resultsReturned")&&("number"==typeof e.resultsReturned?r.resultsReturned=t.longs===String?String(e.resultsReturned):e.resultsReturned:r.resultsReturned=t.longs===String?i.Long.prototype.toString.call(e.resultsReturned):t.longs===Number?new i.LongBits(e.resultsReturned.low>>>0,e.resultsReturned.high>>>0).toNumber():e.resultsReturned),null!=e.executionDuration&&e.hasOwnProperty("executionDuration")&&(r.executionDuration=a.google.protobuf.Duration.toObject(e.executionDuration,t)),null!=e.readOperations&&e.hasOwnProperty("readOperations")&&("number"==typeof e.readOperations?r.readOperations=t.longs===String?String(e.readOperations):e.readOperations:r.readOperations=t.longs===String?i.Long.prototype.toString.call(e.readOperations):t.longs===Number?new i.LongBits(e.readOperations.low>>>0,e.readOperations.high>>>0).toNumber():e.readOperations),null!=e.debugStats&&e.hasOwnProperty("debugStats")&&(r.debugStats=a.google.protobuf.Struct.toObject(e.debugStats,t)),r},Le.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Le.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.firestore.v1.ExecutionStats"},Le),o.Write=(v.prototype.update=null,v.prototype.delete=null,v.prototype.transform=null,v.prototype.updateMask=null,v.prototype.updateTransforms=i.emptyArray,v.prototype.currentDocument=null,Object.defineProperty(v.prototype,"operation",{get:i.oneOfGetter(n=["update","delete","transform"]),set:i.oneOfSetter(n)}),v.fromObject=function(e){if(e instanceof a.google.firestore.v1.Write)return e;var t=new a.google.firestore.v1.Write;if(null!=e.update){if("object"!=typeof e.update)throw TypeError(".google.firestore.v1.Write.update: object expected");t.update=a.google.firestore.v1.Document.fromObject(e.update)}if(null!=e.delete&&(t.delete=String(e.delete)),null!=e.transform){if("object"!=typeof e.transform)throw TypeError(".google.firestore.v1.Write.transform: object expected");t.transform=a.google.firestore.v1.DocumentTransform.fromObject(e.transform)}if(null!=e.updateMask){if("object"!=typeof e.updateMask)throw TypeError(".google.firestore.v1.Write.updateMask: object expected");t.updateMask=a.google.firestore.v1.DocumentMask.fromObject(e.updateMask)}if(e.updateTransforms){if(!Array.isArray(e.updateTransforms))throw TypeError(".google.firestore.v1.Write.updateTransforms: array expected");t.updateTransforms=[];for(var o=0;o>>0,e.positiveIntValue.high>>>0).toNumber(!0))),null!=e.negativeIntValue&&(i.Long?(t.negativeIntValue=i.Long.fromValue(e.negativeIntValue)).unsigned=!1:"string"==typeof e.negativeIntValue?t.negativeIntValue=parseInt(e.negativeIntValue,10):"number"==typeof e.negativeIntValue?t.negativeIntValue=e.negativeIntValue:"object"==typeof e.negativeIntValue&&(t.negativeIntValue=new i.LongBits(e.negativeIntValue.low>>>0,e.negativeIntValue.high>>>0).toNumber())),null!=e.doubleValue&&(t.doubleValue=Number(e.doubleValue)),null!=e.stringValue&&("string"==typeof e.stringValue?i.base64.decode(e.stringValue,t.stringValue=i.newBuffer(i.base64.length(e.stringValue)),0):0<=e.stringValue.length&&(t.stringValue=e.stringValue)),null!=e.aggregateValue&&(t.aggregateValue=String(e.aggregateValue)),t},x.toObject=function(e,t){var o,r={};if(((t=t||{}).arrays||t.defaults)&&(r.name=[]),t.defaults&&(r.identifierValue="",i.Long?(o=new i.Long(0,0,!0),r.positiveIntValue=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.positiveIntValue=t.longs===String?"0":0,i.Long?(o=new i.Long(0,0,!1),r.negativeIntValue=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.negativeIntValue=t.longs===String?"0":0,r.doubleValue=0,t.bytes===String?r.stringValue="":(r.stringValue=[],t.bytes!==Array&&(r.stringValue=i.newBuffer(r.stringValue))),r.aggregateValue=""),e.name&&e.name.length){r.name=[];for(var n=0;n>>0,e.positiveIntValue.high>>>0).toNumber(!0):e.positiveIntValue),null!=e.negativeIntValue&&e.hasOwnProperty("negativeIntValue")&&("number"==typeof e.negativeIntValue?r.negativeIntValue=t.longs===String?String(e.negativeIntValue):e.negativeIntValue:r.negativeIntValue=t.longs===String?i.Long.prototype.toString.call(e.negativeIntValue):t.longs===Number?new i.LongBits(e.negativeIntValue.low>>>0,e.negativeIntValue.high>>>0).toNumber():e.negativeIntValue),null!=e.doubleValue&&e.hasOwnProperty("doubleValue")&&(r.doubleValue=t.json&&!isFinite(e.doubleValue)?String(e.doubleValue):e.doubleValue),null!=e.stringValue&&e.hasOwnProperty("stringValue")&&(r.stringValue=t.bytes===String?i.base64.encode(e.stringValue,0,e.stringValue.length):t.bytes===Array?Array.prototype.slice.call(e.stringValue):e.stringValue),null!=e.aggregateValue&&e.hasOwnProperty("aggregateValue")&&(r.aggregateValue=e.aggregateValue),r},x.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},x.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.UninterpretedOption"},x.NamePart=(jt.prototype.namePart="",jt.prototype.isExtension=!1,jt.fromObject=function(e){var t;return e instanceof a.google.protobuf.UninterpretedOption.NamePart?e:(t=new a.google.protobuf.UninterpretedOption.NamePart,null!=e.namePart&&(t.namePart=String(e.namePart)),null!=e.isExtension&&(t.isExtension=Boolean(e.isExtension)),t)},jt.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.namePart="",o.isExtension=!1),null!=e.namePart&&e.hasOwnProperty("namePart")&&(o.namePart=e.namePart),null!=e.isExtension&&e.hasOwnProperty("isExtension")&&(o.isExtension=e.isExtension),o},jt.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},jt.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.UninterpretedOption.NamePart"},jt),x),t.FeatureSet=(F.prototype.fieldPresence=0,F.prototype.enumType=0,F.prototype.repeatedFieldEncoding=0,F.prototype.utf8Validation=0,F.prototype.messageEncoding=0,F.prototype.jsonFormat=0,F.fromObject=function(e){if(e instanceof a.google.protobuf.FeatureSet)return e;var t=new a.google.protobuf.FeatureSet;switch(e.fieldPresence){default:"number"==typeof e.fieldPresence&&(t.fieldPresence=e.fieldPresence);break;case"FIELD_PRESENCE_UNKNOWN":case 0:t.fieldPresence=0;break;case"EXPLICIT":case 1:t.fieldPresence=1;break;case"IMPLICIT":case 2:t.fieldPresence=2;break;case"LEGACY_REQUIRED":case 3:t.fieldPresence=3}switch(e.enumType){default:"number"==typeof e.enumType&&(t.enumType=e.enumType);break;case"ENUM_TYPE_UNKNOWN":case 0:t.enumType=0;break;case"OPEN":case 1:t.enumType=1;break;case"CLOSED":case 2:t.enumType=2}switch(e.repeatedFieldEncoding){default:"number"==typeof e.repeatedFieldEncoding&&(t.repeatedFieldEncoding=e.repeatedFieldEncoding);break;case"REPEATED_FIELD_ENCODING_UNKNOWN":case 0:t.repeatedFieldEncoding=0;break;case"PACKED":case 1:t.repeatedFieldEncoding=1;break;case"EXPANDED":case 2:t.repeatedFieldEncoding=2}switch(e.utf8Validation){default:"number"==typeof e.utf8Validation&&(t.utf8Validation=e.utf8Validation);break;case"UTF8_VALIDATION_UNKNOWN":case 0:t.utf8Validation=0;break;case"VERIFY":case 2:t.utf8Validation=2;break;case"NONE":case 3:t.utf8Validation=3}switch(e.messageEncoding){default:"number"==typeof e.messageEncoding&&(t.messageEncoding=e.messageEncoding);break;case"MESSAGE_ENCODING_UNKNOWN":case 0:t.messageEncoding=0;break;case"LENGTH_PREFIXED":case 1:t.messageEncoding=1;break;case"DELIMITED":case 2:t.messageEncoding=2}switch(e.jsonFormat){default:"number"==typeof e.jsonFormat&&(t.jsonFormat=e.jsonFormat);break;case"JSON_FORMAT_UNKNOWN":case 0:t.jsonFormat=0;break;case"ALLOW":case 1:t.jsonFormat=1;break;case"LEGACY_BEST_EFFORT":case 2:t.jsonFormat=2}return t},F.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.fieldPresence=t.enums===String?"FIELD_PRESENCE_UNKNOWN":0,o.enumType=t.enums===String?"ENUM_TYPE_UNKNOWN":0,o.repeatedFieldEncoding=t.enums===String?"REPEATED_FIELD_ENCODING_UNKNOWN":0,o.utf8Validation=t.enums===String?"UTF8_VALIDATION_UNKNOWN":0,o.messageEncoding=t.enums===String?"MESSAGE_ENCODING_UNKNOWN":0,o.jsonFormat=t.enums===String?"JSON_FORMAT_UNKNOWN":0),null!=e.fieldPresence&&e.hasOwnProperty("fieldPresence")&&(o.fieldPresence=t.enums!==String||void 0===a.google.protobuf.FeatureSet.FieldPresence[e.fieldPresence]?e.fieldPresence:a.google.protobuf.FeatureSet.FieldPresence[e.fieldPresence]),null!=e.enumType&&e.hasOwnProperty("enumType")&&(o.enumType=t.enums!==String||void 0===a.google.protobuf.FeatureSet.EnumType[e.enumType]?e.enumType:a.google.protobuf.FeatureSet.EnumType[e.enumType]),null!=e.repeatedFieldEncoding&&e.hasOwnProperty("repeatedFieldEncoding")&&(o.repeatedFieldEncoding=t.enums!==String||void 0===a.google.protobuf.FeatureSet.RepeatedFieldEncoding[e.repeatedFieldEncoding]?e.repeatedFieldEncoding:a.google.protobuf.FeatureSet.RepeatedFieldEncoding[e.repeatedFieldEncoding]),null!=e.utf8Validation&&e.hasOwnProperty("utf8Validation")&&(o.utf8Validation=t.enums!==String||void 0===a.google.protobuf.FeatureSet.Utf8Validation[e.utf8Validation]?e.utf8Validation:a.google.protobuf.FeatureSet.Utf8Validation[e.utf8Validation]),null!=e.messageEncoding&&e.hasOwnProperty("messageEncoding")&&(o.messageEncoding=t.enums!==String||void 0===a.google.protobuf.FeatureSet.MessageEncoding[e.messageEncoding]?e.messageEncoding:a.google.protobuf.FeatureSet.MessageEncoding[e.messageEncoding]),null!=e.jsonFormat&&e.hasOwnProperty("jsonFormat")&&(o.jsonFormat=t.enums!==String||void 0===a.google.protobuf.FeatureSet.JsonFormat[e.jsonFormat]?e.jsonFormat:a.google.protobuf.FeatureSet.JsonFormat[e.jsonFormat]),o},F.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},F.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.FeatureSet"},F.FieldPresence=(o={},(n=Object.create(o))[o[0]="FIELD_PRESENCE_UNKNOWN"]="FIELD_PRESENCE_UNKNOWN",n[o[1]="EXPLICIT"]="EXPLICIT",n[o[2]="IMPLICIT"]="IMPLICIT",n[o[3]="LEGACY_REQUIRED"]="LEGACY_REQUIRED",n),F.EnumType=(o={},(n=Object.create(o))[o[0]="ENUM_TYPE_UNKNOWN"]="ENUM_TYPE_UNKNOWN",n[o[1]="OPEN"]="OPEN",n[o[2]="CLOSED"]="CLOSED",n),F.RepeatedFieldEncoding=(o={},(n=Object.create(o))[o[0]="REPEATED_FIELD_ENCODING_UNKNOWN"]="REPEATED_FIELD_ENCODING_UNKNOWN",n[o[1]="PACKED"]="PACKED",n[o[2]="EXPANDED"]="EXPANDED",n),F.Utf8Validation=(o={},(n=Object.create(o))[o[0]="UTF8_VALIDATION_UNKNOWN"]="UTF8_VALIDATION_UNKNOWN",n[o[2]="VERIFY"]="VERIFY",n[o[3]="NONE"]="NONE",n),F.MessageEncoding=(o={},(n=Object.create(o))[o[0]="MESSAGE_ENCODING_UNKNOWN"]="MESSAGE_ENCODING_UNKNOWN",n[o[1]="LENGTH_PREFIXED"]="LENGTH_PREFIXED",n[o[2]="DELIMITED"]="DELIMITED",n),F.JsonFormat=(o={},(n=Object.create(o))[o[0]="JSON_FORMAT_UNKNOWN"]="JSON_FORMAT_UNKNOWN",n[o[1]="ALLOW"]="ALLOW",n[o[2]="LEGACY_BEST_EFFORT"]="LEGACY_BEST_EFFORT",n),F),t.FeatureSetDefaults=(Et.prototype.defaults=i.emptyArray,Et.prototype.minimumEdition=0,Et.prototype.maximumEdition=0,Et.fromObject=function(e){if(e instanceof a.google.protobuf.FeatureSetDefaults)return e;var t=new a.google.protobuf.FeatureSetDefaults;if(e.defaults){if(!Array.isArray(e.defaults))throw TypeError(".google.protobuf.FeatureSetDefaults.defaults: array expected");t.defaults=[];for(var o=0;o>>0,e.seconds.high>>>0).toNumber())),null!=e.nanos&&(t.nanos=0|e.nanos),t)},kt.toObject=function(e,t){var o,r={};return(t=t||{}).defaults&&(i.Long?(o=new i.Long(0,0,!1),r.seconds=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.seconds=t.longs===String?"0":0,r.nanos=0),null!=e.seconds&&e.hasOwnProperty("seconds")&&("number"==typeof e.seconds?r.seconds=t.longs===String?String(e.seconds):e.seconds:r.seconds=t.longs===String?i.Long.prototype.toString.call(e.seconds):t.longs===Number?new i.LongBits(e.seconds.low>>>0,e.seconds.high>>>0).toNumber():e.seconds),null!=e.nanos&&e.hasOwnProperty("nanos")&&(r.nanos=e.nanos),r},kt.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},kt.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.Timestamp"},kt),t.Duration=(xt.prototype.seconds=i.Long?i.Long.fromBits(0,0,!1):0,xt.prototype.nanos=0,xt.fromObject=function(e){var t;return e instanceof a.google.protobuf.Duration?e:(t=new a.google.protobuf.Duration,null!=e.seconds&&(i.Long?(t.seconds=i.Long.fromValue(e.seconds)).unsigned=!1:"string"==typeof e.seconds?t.seconds=parseInt(e.seconds,10):"number"==typeof e.seconds?t.seconds=e.seconds:"object"==typeof e.seconds&&(t.seconds=new i.LongBits(e.seconds.low>>>0,e.seconds.high>>>0).toNumber())),null!=e.nanos&&(t.nanos=0|e.nanos),t)},xt.toObject=function(e,t){var o,r={};return(t=t||{}).defaults&&(i.Long?(o=new i.Long(0,0,!1),r.seconds=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.seconds=t.longs===String?"0":0,r.nanos=0),null!=e.seconds&&e.hasOwnProperty("seconds")&&("number"==typeof e.seconds?r.seconds=t.longs===String?String(e.seconds):e.seconds:r.seconds=t.longs===String?i.Long.prototype.toString.call(e.seconds):t.longs===Number?new i.LongBits(e.seconds.low>>>0,e.seconds.high>>>0).toNumber():e.seconds),null!=e.nanos&&e.hasOwnProperty("nanos")&&(r.nanos=e.nanos),r},xt.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},xt.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.Duration"},xt),t.DoubleValue=(Ft.prototype.value=0,Ft.fromObject=function(e){var t;return e instanceof a.google.protobuf.DoubleValue?e:(t=new a.google.protobuf.DoubleValue,null!=e.value&&(t.value=Number(e.value)),t)},Ft.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.value=0),null!=e.value&&e.hasOwnProperty("value")&&(o.value=t.json&&!isFinite(e.value)?String(e.value):e.value),o},Ft.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Ft.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.DoubleValue"},Ft),t.FloatValue=(_t.prototype.value=0,_t.fromObject=function(e){var t;return e instanceof a.google.protobuf.FloatValue?e:(t=new a.google.protobuf.FloatValue,null!=e.value&&(t.value=Number(e.value)),t)},_t.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.value=0),null!=e.value&&e.hasOwnProperty("value")&&(o.value=t.json&&!isFinite(e.value)?String(e.value):e.value),o},_t.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},_t.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.FloatValue"},_t),t.Int64Value=(Ct.prototype.value=i.Long?i.Long.fromBits(0,0,!1):0,Ct.fromObject=function(e){var t;return e instanceof a.google.protobuf.Int64Value?e:(t=new a.google.protobuf.Int64Value,null!=e.value&&(i.Long?(t.value=i.Long.fromValue(e.value)).unsigned=!1:"string"==typeof e.value?t.value=parseInt(e.value,10):"number"==typeof e.value?t.value=e.value:"object"==typeof e.value&&(t.value=new i.LongBits(e.value.low>>>0,e.value.high>>>0).toNumber())),t)},Ct.toObject=function(e,t){var o,r={};return(t=t||{}).defaults&&(i.Long?(o=new i.Long(0,0,!1),r.value=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.value=t.longs===String?"0":0),null!=e.value&&e.hasOwnProperty("value")&&("number"==typeof e.value?r.value=t.longs===String?String(e.value):e.value:r.value=t.longs===String?i.Long.prototype.toString.call(e.value):t.longs===Number?new i.LongBits(e.value.low>>>0,e.value.high>>>0).toNumber():e.value),r},Ct.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Ct.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.Int64Value"},Ct),t.UInt64Value=(Vt.prototype.value=i.Long?i.Long.fromBits(0,0,!0):0,Vt.fromObject=function(e){var t;return e instanceof a.google.protobuf.UInt64Value?e:(t=new a.google.protobuf.UInt64Value,null!=e.value&&(i.Long?(t.value=i.Long.fromValue(e.value)).unsigned=!0:"string"==typeof e.value?t.value=parseInt(e.value,10):"number"==typeof e.value?t.value=e.value:"object"==typeof e.value&&(t.value=new i.LongBits(e.value.low>>>0,e.value.high>>>0).toNumber(!0))),t)},Vt.toObject=function(e,t){var o,r={};return(t=t||{}).defaults&&(i.Long?(o=new i.Long(0,0,!0),r.value=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.value=t.longs===String?"0":0),null!=e.value&&e.hasOwnProperty("value")&&("number"==typeof e.value?r.value=t.longs===String?String(e.value):e.value:r.value=t.longs===String?i.Long.prototype.toString.call(e.value):t.longs===Number?new i.LongBits(e.value.low>>>0,e.value.high>>>0).toNumber(!0):e.value),r},Vt.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Vt.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.UInt64Value"},Vt),t.Int32Value=(Lt.prototype.value=0,Lt.fromObject=function(e){var t;return e instanceof a.google.protobuf.Int32Value?e:(t=new a.google.protobuf.Int32Value,null!=e.value&&(t.value=0|e.value),t)},Lt.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.value=0),null!=e.value&&e.hasOwnProperty("value")&&(o.value=e.value),o},Lt.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Lt.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.Int32Value"},Lt),t.UInt32Value=(Ut.prototype.value=0,Ut.fromObject=function(e){var t;return e instanceof a.google.protobuf.UInt32Value?e:(t=new a.google.protobuf.UInt32Value,null!=e.value&&(t.value=e.value>>>0),t)},Ut.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.value=0),null!=e.value&&e.hasOwnProperty("value")&&(o.value=e.value),o},Ut.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Ut.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.UInt32Value"},Ut),t.BoolValue=(Bt.prototype.value=!1,Bt.fromObject=function(e){var t;return e instanceof a.google.protobuf.BoolValue?e:(t=new a.google.protobuf.BoolValue,null!=e.value&&(t.value=Boolean(e.value)),t)},Bt.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.value=!1),null!=e.value&&e.hasOwnProperty("value")&&(o.value=e.value),o},Bt.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Bt.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.BoolValue"},Bt),t.StringValue=(Jt.prototype.value="",Jt.fromObject=function(e){var t;return e instanceof a.google.protobuf.StringValue?e:(t=new a.google.protobuf.StringValue,null!=e.value&&(t.value=String(e.value)),t)},Jt.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.value=""),null!=e.value&&e.hasOwnProperty("value")&&(o.value=e.value),o},Jt.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Jt.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.StringValue"},Jt),t.BytesValue=(Qt.prototype.value=i.newBuffer([]),Qt.fromObject=function(e){var t;return e instanceof a.google.protobuf.BytesValue?e:(t=new a.google.protobuf.BytesValue,null!=e.value&&("string"==typeof e.value?i.base64.decode(e.value,t.value=i.newBuffer(i.base64.length(e.value)),0):0<=e.value.length&&(t.value=e.value)),t)},Qt.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(t.bytes===String?o.value="":(o.value=[],t.bytes!==Array&&(o.value=i.newBuffer(o.value)))),null!=e.value&&e.hasOwnProperty("value")&&(o.value=t.bytes===String?i.base64.encode(e.value,0,e.value.length):t.bytes===Array?Array.prototype.slice.call(e.value):e.value),o},Qt.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Qt.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.BytesValue"},Qt),t.Empty=(Mt.fromObject=function(e){return e instanceof a.google.protobuf.Empty?e:new a.google.protobuf.Empty},Mt.toObject=function(){return{}},Mt.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Mt.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.Empty"},Mt),t.Any=(Gt.prototype.type_url="",Gt.prototype.value=i.newBuffer([]),Gt.fromObject=function(e){var t;return e instanceof a.google.protobuf.Any?e:(t=new a.google.protobuf.Any,null!=e.type_url&&(t.type_url=String(e.type_url)),null!=e.value&&("string"==typeof e.value?i.base64.decode(e.value,t.value=i.newBuffer(i.base64.length(e.value)),0):0<=e.value.length&&(t.value=e.value)),t)},Gt.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.type_url="",t.bytes===String?o.value="":(o.value=[],t.bytes!==Array&&(o.value=i.newBuffer(o.value)))),null!=e.type_url&&e.hasOwnProperty("type_url")&&(o.type_url=e.type_url),null!=e.value&&e.hasOwnProperty("value")&&(o.value=t.bytes===String?i.base64.encode(e.value,0,e.value.length):t.bytes===Array?Array.prototype.slice.call(e.value):e.value),o},Gt.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Gt.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.Any"},Gt),t.FieldMask=(qt.prototype.paths=i.emptyArray,qt.fromObject=function(e){if(e instanceof a.google.protobuf.FieldMask)return e;var t=new a.google.protobuf.FieldMask;if(e.paths){if(!Array.isArray(e.paths))throw TypeError(".google.protobuf.FieldMask.paths: array expected");t.paths=[];for(var o=0;o; + + /** + * Calls ListDocuments. + * @param request ListDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListDocumentsResponse + */ + public listDocuments(request: google.firestore.v1beta1.IListDocumentsRequest, callback: google.firestore.v1beta1.Firestore.ListDocumentsCallback): void; + + /** + * Calls ListDocuments. + * @param request ListDocumentsRequest message or plain object + * @returns Promise + */ + public listDocuments(request: google.firestore.v1beta1.IListDocumentsRequest): Promise; + + /** + * Calls UpdateDocument. + * @param request UpdateDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public updateDocument(request: google.firestore.v1beta1.IUpdateDocumentRequest, callback: google.firestore.v1beta1.Firestore.UpdateDocumentCallback): void; + + /** + * Calls UpdateDocument. + * @param request UpdateDocumentRequest message or plain object + * @returns Promise + */ + public updateDocument(request: google.firestore.v1beta1.IUpdateDocumentRequest): Promise; + + /** + * Calls DeleteDocument. + * @param request DeleteDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteDocument(request: google.firestore.v1beta1.IDeleteDocumentRequest, callback: google.firestore.v1beta1.Firestore.DeleteDocumentCallback): void; + + /** + * Calls DeleteDocument. + * @param request DeleteDocumentRequest message or plain object + * @returns Promise + */ + public deleteDocument(request: google.firestore.v1beta1.IDeleteDocumentRequest): Promise; + + /** + * Calls BatchGetDocuments. + * @param request BatchGetDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchGetDocumentsResponse + */ + public batchGetDocuments(request: google.firestore.v1beta1.IBatchGetDocumentsRequest, callback: google.firestore.v1beta1.Firestore.BatchGetDocumentsCallback): void; + + /** + * Calls BatchGetDocuments. + * @param request BatchGetDocumentsRequest message or plain object + * @returns Promise + */ + public batchGetDocuments(request: google.firestore.v1beta1.IBatchGetDocumentsRequest): Promise; + + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BeginTransactionResponse + */ + public beginTransaction(request: google.firestore.v1beta1.IBeginTransactionRequest, callback: google.firestore.v1beta1.Firestore.BeginTransactionCallback): void; + + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @returns Promise + */ + public beginTransaction(request: google.firestore.v1beta1.IBeginTransactionRequest): Promise; + + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @param callback Node-style callback called with the error, if any, and CommitResponse + */ + public commit(request: google.firestore.v1beta1.ICommitRequest, callback: google.firestore.v1beta1.Firestore.CommitCallback): void; + + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @returns Promise + */ + public commit(request: google.firestore.v1beta1.ICommitRequest): Promise; + + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public rollback(request: google.firestore.v1beta1.IRollbackRequest, callback: google.firestore.v1beta1.Firestore.RollbackCallback): void; + + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @returns Promise + */ + public rollback(request: google.firestore.v1beta1.IRollbackRequest): Promise; + + /** + * Calls RunQuery. + * @param request RunQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and RunQueryResponse + */ + public runQuery(request: google.firestore.v1beta1.IRunQueryRequest, callback: google.firestore.v1beta1.Firestore.RunQueryCallback): void; + + /** + * Calls RunQuery. + * @param request RunQueryRequest message or plain object + * @returns Promise + */ + public runQuery(request: google.firestore.v1beta1.IRunQueryRequest): Promise; + + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and PartitionQueryResponse + */ + public partitionQuery(request: google.firestore.v1beta1.IPartitionQueryRequest, callback: google.firestore.v1beta1.Firestore.PartitionQueryCallback): void; + + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @returns Promise + */ + public partitionQuery(request: google.firestore.v1beta1.IPartitionQueryRequest): Promise; + + /** + * Calls Write. + * @param request WriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and WriteResponse + */ + public write(request: google.firestore.v1beta1.IWriteRequest, callback: google.firestore.v1beta1.Firestore.WriteCallback): void; + + /** + * Calls Write. + * @param request WriteRequest message or plain object + * @returns Promise + */ + public write(request: google.firestore.v1beta1.IWriteRequest): Promise; + + /** + * Calls Listen. + * @param request ListenRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListenResponse + */ + public listen(request: google.firestore.v1beta1.IListenRequest, callback: google.firestore.v1beta1.Firestore.ListenCallback): void; + + /** + * Calls Listen. + * @param request ListenRequest message or plain object + * @returns Promise + */ + public listen(request: google.firestore.v1beta1.IListenRequest): Promise; + + /** + * Calls ListCollectionIds. + * @param request ListCollectionIdsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListCollectionIdsResponse + */ + public listCollectionIds(request: google.firestore.v1beta1.IListCollectionIdsRequest, callback: google.firestore.v1beta1.Firestore.ListCollectionIdsCallback): void; + + /** + * Calls ListCollectionIds. + * @param request ListCollectionIdsRequest message or plain object + * @returns Promise + */ + public listCollectionIds(request: google.firestore.v1beta1.IListCollectionIdsRequest): Promise; + + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchWriteResponse + */ + public batchWrite(request: google.firestore.v1beta1.IBatchWriteRequest, callback: google.firestore.v1beta1.Firestore.BatchWriteCallback): void; + + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @returns Promise + */ + public batchWrite(request: google.firestore.v1beta1.IBatchWriteRequest): Promise; + + /** + * Calls CreateDocument. + * @param request CreateDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public createDocument(request: google.firestore.v1beta1.ICreateDocumentRequest, callback: google.firestore.v1beta1.Firestore.CreateDocumentCallback): void; + + /** + * Calls CreateDocument. + * @param request CreateDocumentRequest message or plain object + * @returns Promise + */ + public createDocument(request: google.firestore.v1beta1.ICreateDocumentRequest): Promise; + } + + namespace Firestore { + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#getDocument}. + * @param error Error, if any + * @param [response] Document + */ + type GetDocumentCallback = (error: (Error|null), response?: google.firestore.v1beta1.Document) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#listDocuments}. + * @param error Error, if any + * @param [response] ListDocumentsResponse + */ + type ListDocumentsCallback = (error: (Error|null), response?: google.firestore.v1beta1.ListDocumentsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#updateDocument}. + * @param error Error, if any + * @param [response] Document + */ + type UpdateDocumentCallback = (error: (Error|null), response?: google.firestore.v1beta1.Document) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#deleteDocument}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteDocumentCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#batchGetDocuments}. + * @param error Error, if any + * @param [response] BatchGetDocumentsResponse + */ + type BatchGetDocumentsCallback = (error: (Error|null), response?: google.firestore.v1beta1.BatchGetDocumentsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#beginTransaction}. + * @param error Error, if any + * @param [response] BeginTransactionResponse + */ + type BeginTransactionCallback = (error: (Error|null), response?: google.firestore.v1beta1.BeginTransactionResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#commit}. + * @param error Error, if any + * @param [response] CommitResponse + */ + type CommitCallback = (error: (Error|null), response?: google.firestore.v1beta1.CommitResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#rollback}. + * @param error Error, if any + * @param [response] Empty + */ + type RollbackCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#runQuery}. + * @param error Error, if any + * @param [response] RunQueryResponse + */ + type RunQueryCallback = (error: (Error|null), response?: google.firestore.v1beta1.RunQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#partitionQuery}. + * @param error Error, if any + * @param [response] PartitionQueryResponse + */ + type PartitionQueryCallback = (error: (Error|null), response?: google.firestore.v1beta1.PartitionQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#write}. + * @param error Error, if any + * @param [response] WriteResponse + */ + type WriteCallback = (error: (Error|null), response?: google.firestore.v1beta1.WriteResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#listen}. + * @param error Error, if any + * @param [response] ListenResponse + */ + type ListenCallback = (error: (Error|null), response?: google.firestore.v1beta1.ListenResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#listCollectionIds}. + * @param error Error, if any + * @param [response] ListCollectionIdsResponse + */ + type ListCollectionIdsCallback = (error: (Error|null), response?: google.firestore.v1beta1.ListCollectionIdsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#batchWrite}. + * @param error Error, if any + * @param [response] BatchWriteResponse + */ + type BatchWriteCallback = (error: (Error|null), response?: google.firestore.v1beta1.BatchWriteResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1beta1.Firestore#createDocument}. + * @param error Error, if any + * @param [response] Document + */ + type CreateDocumentCallback = (error: (Error|null), response?: google.firestore.v1beta1.Document) => void; + } + + /** Properties of a GetDocumentRequest. */ + interface IGetDocumentRequest { + + /** GetDocumentRequest name */ + name?: (string|null); + + /** GetDocumentRequest mask */ + mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** GetDocumentRequest transaction */ + transaction?: (Uint8Array|null); + + /** GetDocumentRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a GetDocumentRequest. */ + class GetDocumentRequest implements IGetDocumentRequest { + + /** + * Constructs a new GetDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IGetDocumentRequest); + + /** GetDocumentRequest name. */ + public name: string; + + /** GetDocumentRequest mask. */ + public mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** GetDocumentRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** GetDocumentRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** GetDocumentRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"readTime"); + + /** + * Creates a GetDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.GetDocumentRequest; + + /** + * Creates a plain object from a GetDocumentRequest message. Also converts values to other types if specified. + * @param message GetDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.GetDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDocumentsRequest. */ + interface IListDocumentsRequest { + + /** ListDocumentsRequest parent */ + parent?: (string|null); + + /** ListDocumentsRequest collectionId */ + collectionId?: (string|null); + + /** ListDocumentsRequest pageSize */ + pageSize?: (number|null); + + /** ListDocumentsRequest pageToken */ + pageToken?: (string|null); + + /** ListDocumentsRequest orderBy */ + orderBy?: (string|null); + + /** ListDocumentsRequest mask */ + mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** ListDocumentsRequest transaction */ + transaction?: (Uint8Array|null); + + /** ListDocumentsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** ListDocumentsRequest showMissing */ + showMissing?: (boolean|null); + } + + /** Represents a ListDocumentsRequest. */ + class ListDocumentsRequest implements IListDocumentsRequest { + + /** + * Constructs a new ListDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListDocumentsRequest); + + /** ListDocumentsRequest parent. */ + public parent: string; + + /** ListDocumentsRequest collectionId. */ + public collectionId: string; + + /** ListDocumentsRequest pageSize. */ + public pageSize: number; + + /** ListDocumentsRequest pageToken. */ + public pageToken: string; + + /** ListDocumentsRequest orderBy. */ + public orderBy: string; + + /** ListDocumentsRequest mask. */ + public mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** ListDocumentsRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** ListDocumentsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ListDocumentsRequest showMissing. */ + public showMissing: boolean; + + /** ListDocumentsRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"readTime"); + + /** + * Creates a ListDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListDocumentsRequest; + + /** + * Creates a plain object from a ListDocumentsRequest message. Also converts values to other types if specified. + * @param message ListDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDocumentsResponse. */ + interface IListDocumentsResponse { + + /** ListDocumentsResponse documents */ + documents?: (google.firestore.v1beta1.IDocument[]|null); + + /** ListDocumentsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListDocumentsResponse. */ + class ListDocumentsResponse implements IListDocumentsResponse { + + /** + * Constructs a new ListDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListDocumentsResponse); + + /** ListDocumentsResponse documents. */ + public documents: google.firestore.v1beta1.IDocument[]; + + /** ListDocumentsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListDocumentsResponse; + + /** + * Creates a plain object from a ListDocumentsResponse message. Also converts values to other types if specified. + * @param message ListDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDocumentRequest. */ + interface ICreateDocumentRequest { + + /** CreateDocumentRequest parent */ + parent?: (string|null); + + /** CreateDocumentRequest collectionId */ + collectionId?: (string|null); + + /** CreateDocumentRequest documentId */ + documentId?: (string|null); + + /** CreateDocumentRequest document */ + document?: (google.firestore.v1beta1.IDocument|null); + + /** CreateDocumentRequest mask */ + mask?: (google.firestore.v1beta1.IDocumentMask|null); + } + + /** Represents a CreateDocumentRequest. */ + class CreateDocumentRequest implements ICreateDocumentRequest { + + /** + * Constructs a new CreateDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ICreateDocumentRequest); + + /** CreateDocumentRequest parent. */ + public parent: string; + + /** CreateDocumentRequest collectionId. */ + public collectionId: string; + + /** CreateDocumentRequest documentId. */ + public documentId: string; + + /** CreateDocumentRequest document. */ + public document?: (google.firestore.v1beta1.IDocument|null); + + /** CreateDocumentRequest mask. */ + public mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** + * Creates a CreateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.CreateDocumentRequest; + + /** + * Creates a plain object from a CreateDocumentRequest message. Also converts values to other types if specified. + * @param message CreateDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.CreateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDocumentRequest. */ + interface IUpdateDocumentRequest { + + /** UpdateDocumentRequest document */ + document?: (google.firestore.v1beta1.IDocument|null); + + /** UpdateDocumentRequest updateMask */ + updateMask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** UpdateDocumentRequest mask */ + mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** UpdateDocumentRequest currentDocument */ + currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + } + + /** Represents an UpdateDocumentRequest. */ + class UpdateDocumentRequest implements IUpdateDocumentRequest { + + /** + * Constructs a new UpdateDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IUpdateDocumentRequest); + + /** UpdateDocumentRequest document. */ + public document?: (google.firestore.v1beta1.IDocument|null); + + /** UpdateDocumentRequest updateMask. */ + public updateMask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** UpdateDocumentRequest mask. */ + public mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** UpdateDocumentRequest currentDocument. */ + public currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + + /** + * Creates an UpdateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.UpdateDocumentRequest; + + /** + * Creates a plain object from an UpdateDocumentRequest message. Also converts values to other types if specified. + * @param message UpdateDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.UpdateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDocumentRequest. */ + interface IDeleteDocumentRequest { + + /** DeleteDocumentRequest name */ + name?: (string|null); + + /** DeleteDocumentRequest currentDocument */ + currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + } + + /** Represents a DeleteDocumentRequest. */ + class DeleteDocumentRequest implements IDeleteDocumentRequest { + + /** + * Constructs a new DeleteDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDeleteDocumentRequest); + + /** DeleteDocumentRequest name. */ + public name: string; + + /** DeleteDocumentRequest currentDocument. */ + public currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + + /** + * Creates a DeleteDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DeleteDocumentRequest; + + /** + * Creates a plain object from a DeleteDocumentRequest message. Also converts values to other types if specified. + * @param message DeleteDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DeleteDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchGetDocumentsRequest. */ + interface IBatchGetDocumentsRequest { + + /** BatchGetDocumentsRequest database */ + database?: (string|null); + + /** BatchGetDocumentsRequest documents */ + documents?: (string[]|null); + + /** BatchGetDocumentsRequest mask */ + mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** BatchGetDocumentsRequest transaction */ + transaction?: (Uint8Array|null); + + /** BatchGetDocumentsRequest newTransaction */ + newTransaction?: (google.firestore.v1beta1.ITransactionOptions|null); + + /** BatchGetDocumentsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BatchGetDocumentsRequest. */ + class BatchGetDocumentsRequest implements IBatchGetDocumentsRequest { + + /** + * Constructs a new BatchGetDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBatchGetDocumentsRequest); + + /** BatchGetDocumentsRequest database. */ + public database: string; + + /** BatchGetDocumentsRequest documents. */ + public documents: string[]; + + /** BatchGetDocumentsRequest mask. */ + public mask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** BatchGetDocumentsRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** BatchGetDocumentsRequest newTransaction. */ + public newTransaction?: (google.firestore.v1beta1.ITransactionOptions|null); + + /** BatchGetDocumentsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BatchGetDocumentsRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a BatchGetDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchGetDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BatchGetDocumentsRequest; + + /** + * Creates a plain object from a BatchGetDocumentsRequest message. Also converts values to other types if specified. + * @param message BatchGetDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BatchGetDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchGetDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchGetDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchGetDocumentsResponse. */ + interface IBatchGetDocumentsResponse { + + /** BatchGetDocumentsResponse found */ + found?: (google.firestore.v1beta1.IDocument|null); + + /** BatchGetDocumentsResponse missing */ + missing?: (string|null); + + /** BatchGetDocumentsResponse transaction */ + transaction?: (Uint8Array|null); + + /** BatchGetDocumentsResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BatchGetDocumentsResponse. */ + class BatchGetDocumentsResponse implements IBatchGetDocumentsResponse { + + /** + * Constructs a new BatchGetDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBatchGetDocumentsResponse); + + /** BatchGetDocumentsResponse found. */ + public found?: (google.firestore.v1beta1.IDocument|null); + + /** BatchGetDocumentsResponse missing. */ + public missing?: (string|null); + + /** BatchGetDocumentsResponse transaction. */ + public transaction: Uint8Array; + + /** BatchGetDocumentsResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BatchGetDocumentsResponse result. */ + public result?: ("found"|"missing"); + + /** + * Creates a BatchGetDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchGetDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BatchGetDocumentsResponse; + + /** + * Creates a plain object from a BatchGetDocumentsResponse message. Also converts values to other types if specified. + * @param message BatchGetDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BatchGetDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchGetDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchGetDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BeginTransactionRequest. */ + interface IBeginTransactionRequest { + + /** BeginTransactionRequest database */ + database?: (string|null); + + /** BeginTransactionRequest options */ + options?: (google.firestore.v1beta1.ITransactionOptions|null); + } + + /** Represents a BeginTransactionRequest. */ + class BeginTransactionRequest implements IBeginTransactionRequest { + + /** + * Constructs a new BeginTransactionRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBeginTransactionRequest); + + /** BeginTransactionRequest database. */ + public database: string; + + /** BeginTransactionRequest options. */ + public options?: (google.firestore.v1beta1.ITransactionOptions|null); + + /** + * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BeginTransactionRequest; + + /** + * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. + * @param message BeginTransactionRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BeginTransactionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BeginTransactionRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BeginTransactionResponse. */ + interface IBeginTransactionResponse { + + /** BeginTransactionResponse transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a BeginTransactionResponse. */ + class BeginTransactionResponse implements IBeginTransactionResponse { + + /** + * Constructs a new BeginTransactionResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBeginTransactionResponse); + + /** BeginTransactionResponse transaction. */ + public transaction: Uint8Array; + + /** + * Creates a BeginTransactionResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BeginTransactionResponse; + + /** + * Creates a plain object from a BeginTransactionResponse message. Also converts values to other types if specified. + * @param message BeginTransactionResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BeginTransactionResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BeginTransactionResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommitRequest. */ + interface ICommitRequest { + + /** CommitRequest database */ + database?: (string|null); + + /** CommitRequest writes */ + writes?: (google.firestore.v1beta1.IWrite[]|null); + + /** CommitRequest transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a CommitRequest. */ + class CommitRequest implements ICommitRequest { + + /** + * Constructs a new CommitRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ICommitRequest); + + /** CommitRequest database. */ + public database: string; + + /** CommitRequest writes. */ + public writes: google.firestore.v1beta1.IWrite[]; + + /** CommitRequest transaction. */ + public transaction: Uint8Array; + + /** + * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.CommitRequest; + + /** + * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. + * @param message CommitRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.CommitRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommitResponse. */ + interface ICommitResponse { + + /** CommitResponse writeResults */ + writeResults?: (google.firestore.v1beta1.IWriteResult[]|null); + + /** CommitResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a CommitResponse. */ + class CommitResponse implements ICommitResponse { + + /** + * Constructs a new CommitResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ICommitResponse); + + /** CommitResponse writeResults. */ + public writeResults: google.firestore.v1beta1.IWriteResult[]; + + /** CommitResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.CommitResponse; + + /** + * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. + * @param message CommitResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.CommitResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RollbackRequest. */ + interface IRollbackRequest { + + /** RollbackRequest database */ + database?: (string|null); + + /** RollbackRequest transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a RollbackRequest. */ + class RollbackRequest implements IRollbackRequest { + + /** + * Constructs a new RollbackRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IRollbackRequest); + + /** RollbackRequest database. */ + public database: string; + + /** RollbackRequest transaction. */ + public transaction: Uint8Array; + + /** + * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RollbackRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.RollbackRequest; + + /** + * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. + * @param message RollbackRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.RollbackRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RollbackRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RollbackRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunQueryRequest. */ + interface IRunQueryRequest { + + /** RunQueryRequest parent */ + parent?: (string|null); + + /** RunQueryRequest structuredQuery */ + structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + + /** RunQueryRequest transaction */ + transaction?: (Uint8Array|null); + + /** RunQueryRequest newTransaction */ + newTransaction?: (google.firestore.v1beta1.ITransactionOptions|null); + + /** RunQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a RunQueryRequest. */ + class RunQueryRequest implements IRunQueryRequest { + + /** + * Constructs a new RunQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IRunQueryRequest); + + /** RunQueryRequest parent. */ + public parent: string; + + /** RunQueryRequest structuredQuery. */ + public structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + + /** RunQueryRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** RunQueryRequest newTransaction. */ + public newTransaction?: (google.firestore.v1beta1.ITransactionOptions|null); + + /** RunQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryRequest queryType. */ + public queryType?: "structuredQuery"; + + /** RunQueryRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.RunQueryRequest; + + /** + * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. + * @param message RunQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.RunQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunQueryResponse. */ + interface IRunQueryResponse { + + /** RunQueryResponse transaction */ + transaction?: (Uint8Array|null); + + /** RunQueryResponse document */ + document?: (google.firestore.v1beta1.IDocument|null); + + /** RunQueryResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryResponse skippedResults */ + skippedResults?: (number|null); + } + + /** Represents a RunQueryResponse. */ + class RunQueryResponse implements IRunQueryResponse { + + /** + * Constructs a new RunQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IRunQueryResponse); + + /** RunQueryResponse transaction. */ + public transaction: Uint8Array; + + /** RunQueryResponse document. */ + public document?: (google.firestore.v1beta1.IDocument|null); + + /** RunQueryResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryResponse skippedResults. */ + public skippedResults: number; + + /** + * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.RunQueryResponse; + + /** + * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. + * @param message RunQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.RunQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionQueryRequest. */ + interface IPartitionQueryRequest { + + /** PartitionQueryRequest parent */ + parent?: (string|null); + + /** PartitionQueryRequest structuredQuery */ + structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + + /** PartitionQueryRequest partitionCount */ + partitionCount?: (number|string|null); + + /** PartitionQueryRequest pageToken */ + pageToken?: (string|null); + + /** PartitionQueryRequest pageSize */ + pageSize?: (number|null); + } + + /** Represents a PartitionQueryRequest. */ + class PartitionQueryRequest implements IPartitionQueryRequest { + + /** + * Constructs a new PartitionQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IPartitionQueryRequest); + + /** PartitionQueryRequest parent. */ + public parent: string; + + /** PartitionQueryRequest structuredQuery. */ + public structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + + /** PartitionQueryRequest partitionCount. */ + public partitionCount: (number|string); + + /** PartitionQueryRequest pageToken. */ + public pageToken: string; + + /** PartitionQueryRequest pageSize. */ + public pageSize: number; + + /** PartitionQueryRequest queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a PartitionQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.PartitionQueryRequest; + + /** + * Creates a plain object from a PartitionQueryRequest message. Also converts values to other types if specified. + * @param message PartitionQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.PartitionQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionQueryResponse. */ + interface IPartitionQueryResponse { + + /** PartitionQueryResponse partitions */ + partitions?: (google.firestore.v1beta1.ICursor[]|null); + + /** PartitionQueryResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a PartitionQueryResponse. */ + class PartitionQueryResponse implements IPartitionQueryResponse { + + /** + * Constructs a new PartitionQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IPartitionQueryResponse); + + /** PartitionQueryResponse partitions. */ + public partitions: google.firestore.v1beta1.ICursor[]; + + /** PartitionQueryResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a PartitionQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.PartitionQueryResponse; + + /** + * Creates a plain object from a PartitionQueryResponse message. Also converts values to other types if specified. + * @param message PartitionQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.PartitionQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WriteRequest. */ + interface IWriteRequest { + + /** WriteRequest database */ + database?: (string|null); + + /** WriteRequest streamId */ + streamId?: (string|null); + + /** WriteRequest writes */ + writes?: (google.firestore.v1beta1.IWrite[]|null); + + /** WriteRequest streamToken */ + streamToken?: (Uint8Array|null); + + /** WriteRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a WriteRequest. */ + class WriteRequest implements IWriteRequest { + + /** + * Constructs a new WriteRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IWriteRequest); + + /** WriteRequest database. */ + public database: string; + + /** WriteRequest streamId. */ + public streamId: string; + + /** WriteRequest writes. */ + public writes: google.firestore.v1beta1.IWrite[]; + + /** WriteRequest streamToken. */ + public streamToken: Uint8Array; + + /** WriteRequest labels. */ + public labels: { [k: string]: string }; + + /** + * Creates a WriteRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.WriteRequest; + + /** + * Creates a plain object from a WriteRequest message. Also converts values to other types if specified. + * @param message WriteRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.WriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WriteResponse. */ + interface IWriteResponse { + + /** WriteResponse streamId */ + streamId?: (string|null); + + /** WriteResponse streamToken */ + streamToken?: (Uint8Array|null); + + /** WriteResponse writeResults */ + writeResults?: (google.firestore.v1beta1.IWriteResult[]|null); + + /** WriteResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a WriteResponse. */ + class WriteResponse implements IWriteResponse { + + /** + * Constructs a new WriteResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IWriteResponse); + + /** WriteResponse streamId. */ + public streamId: string; + + /** WriteResponse streamToken. */ + public streamToken: Uint8Array; + + /** WriteResponse writeResults. */ + public writeResults: google.firestore.v1beta1.IWriteResult[]; + + /** WriteResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a WriteResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.WriteResponse; + + /** + * Creates a plain object from a WriteResponse message. Also converts values to other types if specified. + * @param message WriteResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.WriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListenRequest. */ + interface IListenRequest { + + /** ListenRequest database */ + database?: (string|null); + + /** ListenRequest addTarget */ + addTarget?: (google.firestore.v1beta1.ITarget|null); + + /** ListenRequest removeTarget */ + removeTarget?: (number|null); + + /** ListenRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a ListenRequest. */ + class ListenRequest implements IListenRequest { + + /** + * Constructs a new ListenRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListenRequest); + + /** ListenRequest database. */ + public database: string; + + /** ListenRequest addTarget. */ + public addTarget?: (google.firestore.v1beta1.ITarget|null); + + /** ListenRequest removeTarget. */ + public removeTarget?: (number|null); + + /** ListenRequest labels. */ + public labels: { [k: string]: string }; + + /** ListenRequest targetChange. */ + public targetChange?: ("addTarget"|"removeTarget"); + + /** + * Creates a ListenRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListenRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListenRequest; + + /** + * Creates a plain object from a ListenRequest message. Also converts values to other types if specified. + * @param message ListenRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListenRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListenRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListenRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListenResponse. */ + interface IListenResponse { + + /** ListenResponse targetChange */ + targetChange?: (google.firestore.v1beta1.ITargetChange|null); + + /** ListenResponse documentChange */ + documentChange?: (google.firestore.v1beta1.IDocumentChange|null); + + /** ListenResponse documentDelete */ + documentDelete?: (google.firestore.v1beta1.IDocumentDelete|null); + + /** ListenResponse documentRemove */ + documentRemove?: (google.firestore.v1beta1.IDocumentRemove|null); + + /** ListenResponse filter */ + filter?: (google.firestore.v1beta1.IExistenceFilter|null); + } + + /** Represents a ListenResponse. */ + class ListenResponse implements IListenResponse { + + /** + * Constructs a new ListenResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListenResponse); + + /** ListenResponse targetChange. */ + public targetChange?: (google.firestore.v1beta1.ITargetChange|null); + + /** ListenResponse documentChange. */ + public documentChange?: (google.firestore.v1beta1.IDocumentChange|null); + + /** ListenResponse documentDelete. */ + public documentDelete?: (google.firestore.v1beta1.IDocumentDelete|null); + + /** ListenResponse documentRemove. */ + public documentRemove?: (google.firestore.v1beta1.IDocumentRemove|null); + + /** ListenResponse filter. */ + public filter?: (google.firestore.v1beta1.IExistenceFilter|null); + + /** ListenResponse responseType. */ + public responseType?: ("targetChange"|"documentChange"|"documentDelete"|"documentRemove"|"filter"); + + /** + * Creates a ListenResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListenResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListenResponse; + + /** + * Creates a plain object from a ListenResponse message. Also converts values to other types if specified. + * @param message ListenResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListenResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListenResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListenResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Target. */ + interface ITarget { + + /** Target query */ + query?: (google.firestore.v1beta1.Target.IQueryTarget|null); + + /** Target documents */ + documents?: (google.firestore.v1beta1.Target.IDocumentsTarget|null); + + /** Target resumeToken */ + resumeToken?: (Uint8Array|null); + + /** Target readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** Target targetId */ + targetId?: (number|null); + + /** Target once */ + once?: (boolean|null); + } + + /** Represents a Target. */ + class Target implements ITarget { + + /** + * Constructs a new Target. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ITarget); + + /** Target query. */ + public query?: (google.firestore.v1beta1.Target.IQueryTarget|null); + + /** Target documents. */ + public documents?: (google.firestore.v1beta1.Target.IDocumentsTarget|null); + + /** Target resumeToken. */ + public resumeToken?: (Uint8Array|null); + + /** Target readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** Target targetId. */ + public targetId: number; + + /** Target once. */ + public once: boolean; + + /** Target targetType. */ + public targetType?: ("query"|"documents"); + + /** Target resumeType. */ + public resumeType?: ("resumeToken"|"readTime"); + + /** + * Creates a Target message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Target + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Target; + + /** + * Creates a plain object from a Target message. Also converts values to other types if specified. + * @param message Target + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Target, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Target to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Target + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Target { + + /** Properties of a DocumentsTarget. */ + interface IDocumentsTarget { + + /** DocumentsTarget documents */ + documents?: (string[]|null); + } + + /** Represents a DocumentsTarget. */ + class DocumentsTarget implements IDocumentsTarget { + + /** + * Constructs a new DocumentsTarget. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.Target.IDocumentsTarget); + + /** DocumentsTarget documents. */ + public documents: string[]; + + /** + * Creates a DocumentsTarget message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentsTarget + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Target.DocumentsTarget; + + /** + * Creates a plain object from a DocumentsTarget message. Also converts values to other types if specified. + * @param message DocumentsTarget + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Target.DocumentsTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentsTarget to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentsTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a QueryTarget. */ + interface IQueryTarget { + + /** QueryTarget parent */ + parent?: (string|null); + + /** QueryTarget structuredQuery */ + structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + } + + /** Represents a QueryTarget. */ + class QueryTarget implements IQueryTarget { + + /** + * Constructs a new QueryTarget. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.Target.IQueryTarget); + + /** QueryTarget parent. */ + public parent: string; + + /** QueryTarget structuredQuery. */ + public structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); + + /** QueryTarget queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a QueryTarget message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns QueryTarget + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Target.QueryTarget; + + /** + * Creates a plain object from a QueryTarget message. Also converts values to other types if specified. + * @param message QueryTarget + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Target.QueryTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this QueryTarget to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for QueryTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a TargetChange. */ + interface ITargetChange { + + /** TargetChange targetChangeType */ + targetChangeType?: (google.firestore.v1beta1.TargetChange.TargetChangeType|null); + + /** TargetChange targetIds */ + targetIds?: (number[]|null); + + /** TargetChange cause */ + cause?: (google.rpc.IStatus|null); + + /** TargetChange resumeToken */ + resumeToken?: (Uint8Array|null); + + /** TargetChange readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a TargetChange. */ + class TargetChange implements ITargetChange { + + /** + * Constructs a new TargetChange. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ITargetChange); + + /** TargetChange targetChangeType. */ + public targetChangeType: google.firestore.v1beta1.TargetChange.TargetChangeType; + + /** TargetChange targetIds. */ + public targetIds: number[]; + + /** TargetChange cause. */ + public cause?: (google.rpc.IStatus|null); + + /** TargetChange resumeToken. */ + public resumeToken: Uint8Array; + + /** TargetChange readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a TargetChange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TargetChange + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.TargetChange; + + /** + * Creates a plain object from a TargetChange message. Also converts values to other types if specified. + * @param message TargetChange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.TargetChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TargetChange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TargetChange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TargetChange { + + /** TargetChangeType enum. */ + type TargetChangeType = + "NO_CHANGE"| "ADD"| "REMOVE"| "CURRENT"| "RESET"; + } + + /** Properties of a ListCollectionIdsRequest. */ + interface IListCollectionIdsRequest { + + /** ListCollectionIdsRequest parent */ + parent?: (string|null); + + /** ListCollectionIdsRequest pageSize */ + pageSize?: (number|null); + + /** ListCollectionIdsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListCollectionIdsRequest. */ + class ListCollectionIdsRequest implements IListCollectionIdsRequest { + + /** + * Constructs a new ListCollectionIdsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListCollectionIdsRequest); + + /** ListCollectionIdsRequest parent. */ + public parent: string; + + /** ListCollectionIdsRequest pageSize. */ + public pageSize: number; + + /** ListCollectionIdsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a ListCollectionIdsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCollectionIdsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListCollectionIdsRequest; + + /** + * Creates a plain object from a ListCollectionIdsRequest message. Also converts values to other types if specified. + * @param message ListCollectionIdsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListCollectionIdsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCollectionIdsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCollectionIdsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListCollectionIdsResponse. */ + interface IListCollectionIdsResponse { + + /** ListCollectionIdsResponse collectionIds */ + collectionIds?: (string[]|null); + + /** ListCollectionIdsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListCollectionIdsResponse. */ + class ListCollectionIdsResponse implements IListCollectionIdsResponse { + + /** + * Constructs a new ListCollectionIdsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IListCollectionIdsResponse); + + /** ListCollectionIdsResponse collectionIds. */ + public collectionIds: string[]; + + /** ListCollectionIdsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListCollectionIdsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCollectionIdsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListCollectionIdsResponse; + + /** + * Creates a plain object from a ListCollectionIdsResponse message. Also converts values to other types if specified. + * @param message ListCollectionIdsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ListCollectionIdsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCollectionIdsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCollectionIdsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchWriteRequest. */ + interface IBatchWriteRequest { + + /** BatchWriteRequest database */ + database?: (string|null); + + /** BatchWriteRequest writes */ + writes?: (google.firestore.v1beta1.IWrite[]|null); + + /** BatchWriteRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a BatchWriteRequest. */ + class BatchWriteRequest implements IBatchWriteRequest { + + /** + * Constructs a new BatchWriteRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBatchWriteRequest); + + /** BatchWriteRequest database. */ + public database: string; + + /** BatchWriteRequest writes. */ + public writes: google.firestore.v1beta1.IWrite[]; + + /** BatchWriteRequest labels. */ + public labels: { [k: string]: string }; + + /** + * Creates a BatchWriteRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchWriteRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BatchWriteRequest; + + /** + * Creates a plain object from a BatchWriteRequest message. Also converts values to other types if specified. + * @param message BatchWriteRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BatchWriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchWriteRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchWriteResponse. */ + interface IBatchWriteResponse { + + /** BatchWriteResponse writeResults */ + writeResults?: (google.firestore.v1beta1.IWriteResult[]|null); + + /** BatchWriteResponse status */ + status?: (google.rpc.IStatus[]|null); + } + + /** Represents a BatchWriteResponse. */ + class BatchWriteResponse implements IBatchWriteResponse { + + /** + * Constructs a new BatchWriteResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IBatchWriteResponse); + + /** BatchWriteResponse writeResults. */ + public writeResults: google.firestore.v1beta1.IWriteResult[]; + + /** BatchWriteResponse status. */ + public status: google.rpc.IStatus[]; + + /** + * Creates a BatchWriteResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchWriteResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BatchWriteResponse; + + /** + * Creates a plain object from a BatchWriteResponse message. Also converts values to other types if specified. + * @param message BatchWriteResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.BatchWriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchWriteResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StructuredQuery. */ + interface IStructuredQuery { + + /** StructuredQuery select */ + select?: (google.firestore.v1beta1.StructuredQuery.IProjection|null); + + /** StructuredQuery from */ + from?: (google.firestore.v1beta1.StructuredQuery.ICollectionSelector[]|null); + + /** StructuredQuery where */ + where?: (google.firestore.v1beta1.StructuredQuery.IFilter|null); + + /** StructuredQuery orderBy */ + orderBy?: (google.firestore.v1beta1.StructuredQuery.IOrder[]|null); + + /** StructuredQuery startAt */ + startAt?: (google.firestore.v1beta1.ICursor|null); + + /** StructuredQuery endAt */ + endAt?: (google.firestore.v1beta1.ICursor|null); + + /** StructuredQuery offset */ + offset?: (number|null); + + /** StructuredQuery limit */ + limit?: (google.protobuf.IInt32Value|null); + } + + /** Represents a StructuredQuery. */ + class StructuredQuery implements IStructuredQuery { + + /** + * Constructs a new StructuredQuery. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IStructuredQuery); + + /** StructuredQuery select. */ + public select?: (google.firestore.v1beta1.StructuredQuery.IProjection|null); + + /** StructuredQuery from. */ + public from: google.firestore.v1beta1.StructuredQuery.ICollectionSelector[]; + + /** StructuredQuery where. */ + public where?: (google.firestore.v1beta1.StructuredQuery.IFilter|null); + + /** StructuredQuery orderBy. */ + public orderBy: google.firestore.v1beta1.StructuredQuery.IOrder[]; + + /** StructuredQuery startAt. */ + public startAt?: (google.firestore.v1beta1.ICursor|null); + + /** StructuredQuery endAt. */ + public endAt?: (google.firestore.v1beta1.ICursor|null); + + /** StructuredQuery offset. */ + public offset: number; + + /** StructuredQuery limit. */ + public limit?: (google.protobuf.IInt32Value|null); + + /** + * Creates a StructuredQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StructuredQuery + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery; + + /** + * Creates a plain object from a StructuredQuery message. Also converts values to other types if specified. + * @param message StructuredQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StructuredQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StructuredQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace StructuredQuery { + + /** Properties of a CollectionSelector. */ + interface ICollectionSelector { + + /** CollectionSelector collectionId */ + collectionId?: (string|null); + + /** CollectionSelector allDescendants */ + allDescendants?: (boolean|null); + } + + /** Represents a CollectionSelector. */ + class CollectionSelector implements ICollectionSelector { + + /** + * Constructs a new CollectionSelector. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.ICollectionSelector); + + /** CollectionSelector collectionId. */ + public collectionId: string; + + /** CollectionSelector allDescendants. */ + public allDescendants: boolean; + + /** + * Creates a CollectionSelector message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CollectionSelector + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.CollectionSelector; + + /** + * Creates a plain object from a CollectionSelector message. Also converts values to other types if specified. + * @param message CollectionSelector + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.CollectionSelector, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CollectionSelector to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CollectionSelector + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Filter. */ + interface IFilter { + + /** Filter compositeFilter */ + compositeFilter?: (google.firestore.v1beta1.StructuredQuery.ICompositeFilter|null); + + /** Filter fieldFilter */ + fieldFilter?: (google.firestore.v1beta1.StructuredQuery.IFieldFilter|null); + + /** Filter unaryFilter */ + unaryFilter?: (google.firestore.v1beta1.StructuredQuery.IUnaryFilter|null); + } + + /** Represents a Filter. */ + class Filter implements IFilter { + + /** + * Constructs a new Filter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IFilter); + + /** Filter compositeFilter. */ + public compositeFilter?: (google.firestore.v1beta1.StructuredQuery.ICompositeFilter|null); + + /** Filter fieldFilter. */ + public fieldFilter?: (google.firestore.v1beta1.StructuredQuery.IFieldFilter|null); + + /** Filter unaryFilter. */ + public unaryFilter?: (google.firestore.v1beta1.StructuredQuery.IUnaryFilter|null); + + /** Filter filterType. */ + public filterType?: ("compositeFilter"|"fieldFilter"|"unaryFilter"); + + /** + * Creates a Filter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Filter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.Filter; + + /** + * Creates a plain object from a Filter message. Also converts values to other types if specified. + * @param message Filter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.Filter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Filter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Filter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CompositeFilter. */ + interface ICompositeFilter { + + /** CompositeFilter op */ + op?: (google.firestore.v1beta1.StructuredQuery.CompositeFilter.Operator|null); + + /** CompositeFilter filters */ + filters?: (google.firestore.v1beta1.StructuredQuery.IFilter[]|null); + } + + /** Represents a CompositeFilter. */ + class CompositeFilter implements ICompositeFilter { + + /** + * Constructs a new CompositeFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.ICompositeFilter); + + /** CompositeFilter op. */ + public op: google.firestore.v1beta1.StructuredQuery.CompositeFilter.Operator; + + /** CompositeFilter filters. */ + public filters: google.firestore.v1beta1.StructuredQuery.IFilter[]; + + /** + * Creates a CompositeFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CompositeFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.CompositeFilter; + + /** + * Creates a plain object from a CompositeFilter message. Also converts values to other types if specified. + * @param message CompositeFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.CompositeFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CompositeFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CompositeFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace CompositeFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "AND"; + } + + /** Properties of a FieldFilter. */ + interface IFieldFilter { + + /** FieldFilter field */ + field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + + /** FieldFilter op */ + op?: (google.firestore.v1beta1.StructuredQuery.FieldFilter.Operator|null); + + /** FieldFilter value */ + value?: (google.firestore.v1beta1.IValue|null); + } + + /** Represents a FieldFilter. */ + class FieldFilter implements IFieldFilter { + + /** + * Constructs a new FieldFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IFieldFilter); + + /** FieldFilter field. */ + public field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + + /** FieldFilter op. */ + public op: google.firestore.v1beta1.StructuredQuery.FieldFilter.Operator; + + /** FieldFilter value. */ + public value?: (google.firestore.v1beta1.IValue|null); + + /** + * Creates a FieldFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.FieldFilter; + + /** + * Creates a plain object from a FieldFilter message. Also converts values to other types if specified. + * @param message FieldFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.FieldFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "LESS_THAN"| "LESS_THAN_OR_EQUAL"| "GREATER_THAN"| "GREATER_THAN_OR_EQUAL"| "EQUAL"| "NOT_EQUAL"| "ARRAY_CONTAINS"| "IN"| "ARRAY_CONTAINS_ANY"| "NOT_IN"; + } + + /** Properties of an UnaryFilter. */ + interface IUnaryFilter { + + /** UnaryFilter op */ + op?: (google.firestore.v1beta1.StructuredQuery.UnaryFilter.Operator|null); + + /** UnaryFilter field */ + field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + } + + /** Represents an UnaryFilter. */ + class UnaryFilter implements IUnaryFilter { + + /** + * Constructs a new UnaryFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IUnaryFilter); + + /** UnaryFilter op. */ + public op: google.firestore.v1beta1.StructuredQuery.UnaryFilter.Operator; + + /** UnaryFilter field. */ + public field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + + /** UnaryFilter operandType. */ + public operandType?: "field"; + + /** + * Creates an UnaryFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UnaryFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.UnaryFilter; + + /** + * Creates a plain object from an UnaryFilter message. Also converts values to other types if specified. + * @param message UnaryFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.UnaryFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UnaryFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UnaryFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UnaryFilter { + + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "IS_NAN"| "IS_NULL"| "IS_NOT_NAN"| "IS_NOT_NULL"; + } + + /** Properties of a FieldReference. */ + interface IFieldReference { + + /** FieldReference fieldPath */ + fieldPath?: (string|null); + } + + /** Represents a FieldReference. */ + class FieldReference implements IFieldReference { + + /** + * Constructs a new FieldReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IFieldReference); + + /** FieldReference fieldPath. */ + public fieldPath: string; + + /** + * Creates a FieldReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldReference + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.FieldReference; + + /** + * Creates a plain object from a FieldReference message. Also converts values to other types if specified. + * @param message FieldReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.FieldReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Order. */ + interface IOrder { + + /** Order field */ + field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + + /** Order direction */ + direction?: (google.firestore.v1beta1.StructuredQuery.Direction|null); + } + + /** Represents an Order. */ + class Order implements IOrder { + + /** + * Constructs a new Order. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IOrder); + + /** Order field. */ + public field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); + + /** Order direction. */ + public direction: google.firestore.v1beta1.StructuredQuery.Direction; + + /** + * Creates an Order message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Order + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.Order; + + /** + * Creates a plain object from an Order message. Also converts values to other types if specified. + * @param message Order + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.Order, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Order to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Order + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Projection. */ + interface IProjection { + + /** Projection fields */ + fields?: (google.firestore.v1beta1.StructuredQuery.IFieldReference[]|null); + } + + /** Represents a Projection. */ + class Projection implements IProjection { + + /** + * Constructs a new Projection. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.StructuredQuery.IProjection); + + /** Projection fields. */ + public fields: google.firestore.v1beta1.StructuredQuery.IFieldReference[]; + + /** + * Creates a Projection message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Projection + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.Projection; + + /** + * Creates a plain object from a Projection message. Also converts values to other types if specified. + * @param message Projection + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.StructuredQuery.Projection, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Projection to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Projection + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Direction enum. */ + type Direction = + "DIRECTION_UNSPECIFIED"| "ASCENDING"| "DESCENDING"; + } + + /** Properties of a Cursor. */ + interface ICursor { + + /** Cursor values */ + values?: (google.firestore.v1beta1.IValue[]|null); + + /** Cursor before */ + before?: (boolean|null); + } + + /** Represents a Cursor. */ + class Cursor implements ICursor { + + /** + * Constructs a new Cursor. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.ICursor); + + /** Cursor values. */ + public values: google.firestore.v1beta1.IValue[]; + + /** Cursor before. */ + public before: boolean; + + /** + * Creates a Cursor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Cursor + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Cursor; + + /** + * Creates a plain object from a Cursor message. Also converts values to other types if specified. + * @param message Cursor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Cursor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Cursor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Cursor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Write. */ + interface IWrite { + + /** Write update */ + update?: (google.firestore.v1beta1.IDocument|null); + + /** Write delete */ + "delete"?: (string|null); + + /** Write transform */ + transform?: (google.firestore.v1beta1.IDocumentTransform|null); + + /** Write updateMask */ + updateMask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** Write updateTransforms */ + updateTransforms?: (google.firestore.v1beta1.DocumentTransform.IFieldTransform[]|null); + + /** Write currentDocument */ + currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + } + + /** Represents a Write. */ + class Write implements IWrite { + + /** + * Constructs a new Write. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IWrite); + + /** Write update. */ + public update?: (google.firestore.v1beta1.IDocument|null); + + /** Write delete. */ + public delete?: (string|null); + + /** Write transform. */ + public transform?: (google.firestore.v1beta1.IDocumentTransform|null); + + /** Write updateMask. */ + public updateMask?: (google.firestore.v1beta1.IDocumentMask|null); + + /** Write updateTransforms. */ + public updateTransforms: google.firestore.v1beta1.DocumentTransform.IFieldTransform[]; + + /** Write currentDocument. */ + public currentDocument?: (google.firestore.v1beta1.IPrecondition|null); + + /** Write operation. */ + public operation?: ("update"|"delete"|"transform"); + + /** + * Creates a Write message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Write + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Write; + + /** + * Creates a plain object from a Write message. Also converts values to other types if specified. + * @param message Write + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.Write, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Write to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Write + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentTransform. */ + interface IDocumentTransform { + + /** DocumentTransform document */ + document?: (string|null); + + /** DocumentTransform fieldTransforms */ + fieldTransforms?: (google.firestore.v1beta1.DocumentTransform.IFieldTransform[]|null); + } + + /** Represents a DocumentTransform. */ + class DocumentTransform implements IDocumentTransform { + + /** + * Constructs a new DocumentTransform. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocumentTransform); + + /** DocumentTransform document. */ + public document: string; + + /** DocumentTransform fieldTransforms. */ + public fieldTransforms: google.firestore.v1beta1.DocumentTransform.IFieldTransform[]; + + /** + * Creates a DocumentTransform message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentTransform + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentTransform; + + /** + * Creates a plain object from a DocumentTransform message. Also converts values to other types if specified. + * @param message DocumentTransform + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentTransform to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DocumentTransform { + + /** Properties of a FieldTransform. */ + interface IFieldTransform { + + /** FieldTransform fieldPath */ + fieldPath?: (string|null); + + /** FieldTransform setToServerValue */ + setToServerValue?: (google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue|null); + + /** FieldTransform increment */ + increment?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform maximum */ + maximum?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform minimum */ + minimum?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform appendMissingElements */ + appendMissingElements?: (google.firestore.v1beta1.IArrayValue|null); + + /** FieldTransform removeAllFromArray */ + removeAllFromArray?: (google.firestore.v1beta1.IArrayValue|null); + } + + /** Represents a FieldTransform. */ + class FieldTransform implements IFieldTransform { + + /** + * Constructs a new FieldTransform. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.DocumentTransform.IFieldTransform); + + /** FieldTransform fieldPath. */ + public fieldPath: string; + + /** FieldTransform setToServerValue. */ + public setToServerValue?: (google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue|null); + + /** FieldTransform increment. */ + public increment?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform maximum. */ + public maximum?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform minimum. */ + public minimum?: (google.firestore.v1beta1.IValue|null); + + /** FieldTransform appendMissingElements. */ + public appendMissingElements?: (google.firestore.v1beta1.IArrayValue|null); + + /** FieldTransform removeAllFromArray. */ + public removeAllFromArray?: (google.firestore.v1beta1.IArrayValue|null); + + /** FieldTransform transformType. */ + public transformType?: ("setToServerValue"|"increment"|"maximum"|"minimum"|"appendMissingElements"|"removeAllFromArray"); + + /** + * Creates a FieldTransform message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldTransform + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentTransform.FieldTransform; + + /** + * Creates a plain object from a FieldTransform message. Also converts values to other types if specified. + * @param message FieldTransform + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentTransform.FieldTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldTransform to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldTransform { + + /** ServerValue enum. */ + type ServerValue = + "SERVER_VALUE_UNSPECIFIED"| "REQUEST_TIME"; + } + } + + /** Properties of a WriteResult. */ + interface IWriteResult { + + /** WriteResult updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** WriteResult transformResults */ + transformResults?: (google.firestore.v1beta1.IValue[]|null); + } + + /** Represents a WriteResult. */ + class WriteResult implements IWriteResult { + + /** + * Constructs a new WriteResult. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IWriteResult); + + /** WriteResult updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** WriteResult transformResults. */ + public transformResults: google.firestore.v1beta1.IValue[]; + + /** + * Creates a WriteResult message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteResult + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.WriteResult; + + /** + * Creates a plain object from a WriteResult message. Also converts values to other types if specified. + * @param message WriteResult + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.WriteResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteResult to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteResult + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentChange. */ + interface IDocumentChange { + + /** DocumentChange document */ + document?: (google.firestore.v1beta1.IDocument|null); + + /** DocumentChange targetIds */ + targetIds?: (number[]|null); + + /** DocumentChange removedTargetIds */ + removedTargetIds?: (number[]|null); + } + + /** Represents a DocumentChange. */ + class DocumentChange implements IDocumentChange { + + /** + * Constructs a new DocumentChange. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocumentChange); + + /** DocumentChange document. */ + public document?: (google.firestore.v1beta1.IDocument|null); + + /** DocumentChange targetIds. */ + public targetIds: number[]; + + /** DocumentChange removedTargetIds. */ + public removedTargetIds: number[]; + + /** + * Creates a DocumentChange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentChange + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentChange; + + /** + * Creates a plain object from a DocumentChange message. Also converts values to other types if specified. + * @param message DocumentChange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentChange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentChange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentDelete. */ + interface IDocumentDelete { + + /** DocumentDelete document */ + document?: (string|null); + + /** DocumentDelete removedTargetIds */ + removedTargetIds?: (number[]|null); + + /** DocumentDelete readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a DocumentDelete. */ + class DocumentDelete implements IDocumentDelete { + + /** + * Constructs a new DocumentDelete. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocumentDelete); + + /** DocumentDelete document. */ + public document: string; + + /** DocumentDelete removedTargetIds. */ + public removedTargetIds: number[]; + + /** DocumentDelete readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a DocumentDelete message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentDelete + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentDelete; + + /** + * Creates a plain object from a DocumentDelete message. Also converts values to other types if specified. + * @param message DocumentDelete + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentDelete, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentDelete to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentDelete + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentRemove. */ + interface IDocumentRemove { + + /** DocumentRemove document */ + document?: (string|null); + + /** DocumentRemove removedTargetIds */ + removedTargetIds?: (number[]|null); + + /** DocumentRemove readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a DocumentRemove. */ + class DocumentRemove implements IDocumentRemove { + + /** + * Constructs a new DocumentRemove. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IDocumentRemove); + + /** DocumentRemove document. */ + public document: string; + + /** DocumentRemove removedTargetIds. */ + public removedTargetIds: number[]; + + /** DocumentRemove readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a DocumentRemove message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentRemove + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentRemove; + + /** + * Creates a plain object from a DocumentRemove message. Also converts values to other types if specified. + * @param message DocumentRemove + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.DocumentRemove, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentRemove to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentRemove + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExistenceFilter. */ + interface IExistenceFilter { + + /** ExistenceFilter targetId */ + targetId?: (number|null); + + /** ExistenceFilter count */ + count?: (number|null); + } + + /** Represents an ExistenceFilter. */ + class ExistenceFilter implements IExistenceFilter { + + /** + * Constructs a new ExistenceFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IExistenceFilter); + + /** ExistenceFilter targetId. */ + public targetId: number; + + /** ExistenceFilter count. */ + public count: number; + + /** + * Creates an ExistenceFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExistenceFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ExistenceFilter; + + /** + * Creates a plain object from an ExistenceFilter message. Also converts values to other types if specified. + * @param message ExistenceFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.ExistenceFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExistenceFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExistenceFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UndeliverableFirstGenEvent. */ + interface IUndeliverableFirstGenEvent { + + /** UndeliverableFirstGenEvent message */ + message?: (string|null); + + /** UndeliverableFirstGenEvent reason */ + reason?: (google.firestore.v1beta1.UndeliverableFirstGenEvent.Reason|null); + + /** UndeliverableFirstGenEvent documentName */ + documentName?: (string|null); + + /** UndeliverableFirstGenEvent documentChangeType */ + documentChangeType?: (google.firestore.v1beta1.UndeliverableFirstGenEvent.DocumentChangeType|null); + + /** UndeliverableFirstGenEvent functionName */ + functionName?: (string[]|null); + + /** UndeliverableFirstGenEvent triggeredTime */ + triggeredTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an UndeliverableFirstGenEvent. */ + class UndeliverableFirstGenEvent implements IUndeliverableFirstGenEvent { + + /** + * Constructs a new UndeliverableFirstGenEvent. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IUndeliverableFirstGenEvent); + + /** UndeliverableFirstGenEvent message. */ + public message: string; + + /** UndeliverableFirstGenEvent reason. */ + public reason: google.firestore.v1beta1.UndeliverableFirstGenEvent.Reason; + + /** UndeliverableFirstGenEvent documentName. */ + public documentName: string; + + /** UndeliverableFirstGenEvent documentChangeType. */ + public documentChangeType: google.firestore.v1beta1.UndeliverableFirstGenEvent.DocumentChangeType; + + /** UndeliverableFirstGenEvent functionName. */ + public functionName: string[]; + + /** UndeliverableFirstGenEvent triggeredTime. */ + public triggeredTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates an UndeliverableFirstGenEvent message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UndeliverableFirstGenEvent + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.UndeliverableFirstGenEvent; + + /** + * Creates a plain object from an UndeliverableFirstGenEvent message. Also converts values to other types if specified. + * @param message UndeliverableFirstGenEvent + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.UndeliverableFirstGenEvent, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UndeliverableFirstGenEvent to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UndeliverableFirstGenEvent + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UndeliverableFirstGenEvent { + + /** Reason enum. */ + type Reason = + "REASON_UNSPECIFIED"| "EXCEEDING_SIZE_LIMIT"; + + /** DocumentChangeType enum. */ + type DocumentChangeType = + "DOCUMENT_CHANGE_TYPE_UNSPECIFIED"| "CREATE"| "DELETE"| "UPDATE"; + } + } + } + + /** Namespace type. */ + namespace type { + + /** Properties of a LatLng. */ + interface ILatLng { + + /** LatLng latitude */ + latitude?: (number|null); + + /** LatLng longitude */ + longitude?: (number|null); + } + + /** Represents a LatLng. */ + class LatLng implements ILatLng { + + /** + * Constructs a new LatLng. + * @param [properties] Properties to set + */ + constructor(properties?: google.type.ILatLng); + + /** LatLng latitude. */ + public latitude: number; + + /** LatLng longitude. */ + public longitude: number; + + /** + * Creates a LatLng message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LatLng + */ + public static fromObject(object: { [k: string]: any }): google.type.LatLng; + + /** + * Creates a plain object from a LatLng message. Also converts values to other types if specified. + * @param message LatLng + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.type.LatLng, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LatLng to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LatLng + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** DayOfWeek enum. */ + type DayOfWeek = + "DAY_OF_WEEK_UNSPECIFIED"| "MONDAY"| "TUESDAY"| "WEDNESDAY"| "THURSDAY"| "FRIDAY"| "SATURDAY"| "SUNDAY"; + } + + /** Namespace api. */ + namespace api { + + /** Properties of a Http. */ + interface IHttp { + + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); + + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); + } + + /** Represents a Http. */ + class Http implements IHttp { + + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); + + /** Http rules. */ + public rules: google.api.IHttpRule[]; + + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Http + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a HttpRule. */ + interface IHttpRule { + + /** HttpRule selector */ + selector?: (string|null); + + /** HttpRule get */ + get?: (string|null); + + /** HttpRule put */ + put?: (string|null); + + /** HttpRule post */ + post?: (string|null); + + /** HttpRule delete */ + "delete"?: (string|null); + + /** HttpRule patch */ + patch?: (string|null); + + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body */ + body?: (string|null); + + /** HttpRule responseBody */ + responseBody?: (string|null); + + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); + } + + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { + + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); + + /** HttpRule selector. */ + public selector: string; + + /** HttpRule get. */ + public get?: (string|null); + + /** HttpRule put. */ + public put?: (string|null); + + /** HttpRule post. */ + public post?: (string|null); + + /** HttpRule delete. */ + public delete?: (string|null); + + /** HttpRule patch. */ + public patch?: (string|null); + + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body. */ + public body: string; + + /** HttpRule responseBody. */ + public responseBody: string; + + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; + + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for HttpRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { + + /** CustomHttpPattern kind */ + kind?: (string|null); + + /** CustomHttpPattern path */ + path?: (string|null); + } + + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { + + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); + + /** CustomHttpPattern kind. */ + public kind: string; + + /** CustomHttpPattern path. */ + public path: string; + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CustomHttpPattern + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommonLanguageSettings. */ + interface ICommonLanguageSettings { + + /** CommonLanguageSettings referenceDocsUri */ + referenceDocsUri?: (string|null); + + /** CommonLanguageSettings destinations */ + destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + } + + /** Represents a CommonLanguageSettings. */ + class CommonLanguageSettings implements ICommonLanguageSettings { + + /** + * Constructs a new CommonLanguageSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICommonLanguageSettings); + + /** CommonLanguageSettings referenceDocsUri. */ + public referenceDocsUri: string; + + /** CommonLanguageSettings destinations. */ + public destinations: google.api.ClientLibraryDestination[]; + + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommonLanguageSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CommonLanguageSettings; + + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @param message CommonLanguageSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CommonLanguageSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommonLanguageSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommonLanguageSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ClientLibrarySettings. */ + interface IClientLibrarySettings { + + /** ClientLibrarySettings version */ + version?: (string|null); + + /** ClientLibrarySettings launchStage */ + launchStage?: (google.api.LaunchStage|null); + + /** ClientLibrarySettings restNumericEnums */ + restNumericEnums?: (boolean|null); + + /** ClientLibrarySettings javaSettings */ + javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings */ + cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings */ + phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings */ + pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings */ + nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings */ + dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings */ + rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings */ + goSettings?: (google.api.IGoSettings|null); + } + + /** Represents a ClientLibrarySettings. */ + class ClientLibrarySettings implements IClientLibrarySettings { + + /** + * Constructs a new ClientLibrarySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IClientLibrarySettings); + + /** ClientLibrarySettings version. */ + public version: string; + + /** ClientLibrarySettings launchStage. */ + public launchStage: google.api.LaunchStage; + + /** ClientLibrarySettings restNumericEnums. */ + public restNumericEnums: boolean; + + /** ClientLibrarySettings javaSettings. */ + public javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings. */ + public cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings. */ + public phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings. */ + public pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings. */ + public nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings. */ + public dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings. */ + public rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings. */ + public goSettings?: (google.api.IGoSettings|null); + + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ClientLibrarySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.ClientLibrarySettings; + + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @param message ClientLibrarySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ClientLibrarySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ClientLibrarySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ClientLibrarySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Publishing. */ + interface IPublishing { + + /** Publishing methodSettings */ + methodSettings?: (google.api.IMethodSettings[]|null); + + /** Publishing newIssueUri */ + newIssueUri?: (string|null); + + /** Publishing documentationUri */ + documentationUri?: (string|null); + + /** Publishing apiShortName */ + apiShortName?: (string|null); + + /** Publishing githubLabel */ + githubLabel?: (string|null); + + /** Publishing codeownerGithubTeams */ + codeownerGithubTeams?: (string[]|null); + + /** Publishing docTagPrefix */ + docTagPrefix?: (string|null); + + /** Publishing organization */ + organization?: (google.api.ClientLibraryOrganization|null); + + /** Publishing librarySettings */ + librarySettings?: (google.api.IClientLibrarySettings[]|null); + + /** Publishing protoReferenceDocumentationUri */ + protoReferenceDocumentationUri?: (string|null); + + /** Publishing restReferenceDocumentationUri */ + restReferenceDocumentationUri?: (string|null); + } + + /** Represents a Publishing. */ + class Publishing implements IPublishing { + + /** + * Constructs a new Publishing. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPublishing); + + /** Publishing methodSettings. */ + public methodSettings: google.api.IMethodSettings[]; + + /** Publishing newIssueUri. */ + public newIssueUri: string; + + /** Publishing documentationUri. */ + public documentationUri: string; + + /** Publishing apiShortName. */ + public apiShortName: string; + + /** Publishing githubLabel. */ + public githubLabel: string; + + /** Publishing codeownerGithubTeams. */ + public codeownerGithubTeams: string[]; + + /** Publishing docTagPrefix. */ + public docTagPrefix: string; + + /** Publishing organization. */ + public organization: google.api.ClientLibraryOrganization; + + /** Publishing librarySettings. */ + public librarySettings: google.api.IClientLibrarySettings[]; + + /** Publishing protoReferenceDocumentationUri. */ + public protoReferenceDocumentationUri: string; + + /** Publishing restReferenceDocumentationUri. */ + public restReferenceDocumentationUri: string; + + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Publishing + */ + public static fromObject(object: { [k: string]: any }): google.api.Publishing; + + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @param message Publishing + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Publishing, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Publishing to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Publishing + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a JavaSettings. */ + interface IJavaSettings { + + /** JavaSettings libraryPackage */ + libraryPackage?: (string|null); + + /** JavaSettings serviceClassNames */ + serviceClassNames?: ({ [k: string]: string }|null); + + /** JavaSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a JavaSettings. */ + class JavaSettings implements IJavaSettings { + + /** + * Constructs a new JavaSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IJavaSettings); + + /** JavaSettings libraryPackage. */ + public libraryPackage: string; + + /** JavaSettings serviceClassNames. */ + public serviceClassNames: { [k: string]: string }; + + /** JavaSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns JavaSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.JavaSettings; + + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @param message JavaSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.JavaSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this JavaSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for JavaSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CppSettings. */ + interface ICppSettings { + + /** CppSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a CppSettings. */ + class CppSettings implements ICppSettings { + + /** + * Constructs a new CppSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICppSettings); + + /** CppSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CppSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CppSettings; + + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @param message CppSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CppSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CppSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CppSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PhpSettings. */ + interface IPhpSettings { + + /** PhpSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a PhpSettings. */ + class PhpSettings implements IPhpSettings { + + /** + * Constructs a new PhpSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPhpSettings); + + /** PhpSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PhpSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PhpSettings; + + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @param message PhpSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PhpSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PhpSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PhpSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PythonSettings. */ + interface IPythonSettings { + + /** PythonSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + } + + /** Represents a PythonSettings. */ + class PythonSettings implements IPythonSettings { + + /** + * Constructs a new PythonSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPythonSettings); + + /** PythonSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PythonSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings; + + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @param message PythonSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PythonSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PythonSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace PythonSettings { + + /** Properties of an ExperimentalFeatures. */ + interface IExperimentalFeatures { + + /** ExperimentalFeatures restAsyncIoEnabled */ + restAsyncIoEnabled?: (boolean|null); + + /** ExperimentalFeatures protobufPythonicTypesEnabled */ + protobufPythonicTypesEnabled?: (boolean|null); + } + + /** Represents an ExperimentalFeatures. */ + class ExperimentalFeatures implements IExperimentalFeatures { + + /** + * Constructs a new ExperimentalFeatures. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.PythonSettings.IExperimentalFeatures); + + /** ExperimentalFeatures restAsyncIoEnabled. */ + public restAsyncIoEnabled: boolean; + + /** ExperimentalFeatures protobufPythonicTypesEnabled. */ + public protobufPythonicTypesEnabled: boolean; + + /** + * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExperimentalFeatures + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. + * @param message ExperimentalFeatures + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings.ExperimentalFeatures, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExperimentalFeatures to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExperimentalFeatures + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a NodeSettings. */ + interface INodeSettings { + + /** NodeSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a NodeSettings. */ + class NodeSettings implements INodeSettings { + + /** + * Constructs a new NodeSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.INodeSettings); + + /** NodeSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NodeSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.NodeSettings; + + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @param message NodeSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.NodeSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NodeSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NodeSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DotnetSettings. */ + interface IDotnetSettings { + + /** DotnetSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + + /** DotnetSettings renamedResources */ + renamedResources?: ({ [k: string]: string }|null); + + /** DotnetSettings ignoredResources */ + ignoredResources?: (string[]|null); + + /** DotnetSettings forcedNamespaceAliases */ + forcedNamespaceAliases?: (string[]|null); + + /** DotnetSettings handwrittenSignatures */ + handwrittenSignatures?: (string[]|null); + } + + /** Represents a DotnetSettings. */ + class DotnetSettings implements IDotnetSettings { + + /** + * Constructs a new DotnetSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IDotnetSettings); + + /** DotnetSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** DotnetSettings renamedResources. */ + public renamedResources: { [k: string]: string }; + + /** DotnetSettings ignoredResources. */ + public ignoredResources: string[]; + + /** DotnetSettings forcedNamespaceAliases. */ + public forcedNamespaceAliases: string[]; + + /** DotnetSettings handwrittenSignatures. */ + public handwrittenSignatures: string[]; + + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DotnetSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.DotnetSettings; + + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @param message DotnetSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.DotnetSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DotnetSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DotnetSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RubySettings. */ + interface IRubySettings { + + /** RubySettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a RubySettings. */ + class RubySettings implements IRubySettings { + + /** + * Constructs a new RubySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRubySettings); + + /** RubySettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RubySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.RubySettings; + + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @param message RubySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RubySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RubySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RubySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GoSettings. */ + interface IGoSettings { + + /** GoSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + } + + /** Represents a GoSettings. */ + class GoSettings implements IGoSettings { + + /** + * Constructs a new GoSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IGoSettings); + + /** GoSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GoSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.GoSettings; + + /** + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @param message GoSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.GoSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GoSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GoSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodSettings. */ + interface IMethodSettings { + + /** MethodSettings selector */ + selector?: (string|null); + + /** MethodSettings longRunning */ + longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields */ + autoPopulatedFields?: (string[]|null); + } + + /** Represents a MethodSettings. */ + class MethodSettings implements IMethodSettings { + + /** + * Constructs a new MethodSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IMethodSettings); + + /** MethodSettings selector. */ + public selector: string; + + /** MethodSettings longRunning. */ + public longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields. */ + public autoPopulatedFields: string[]; + + /** + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings; + + /** + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @param message MethodSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodSettings { + + /** Properties of a LongRunning. */ + interface ILongRunning { + + /** LongRunning initialPollDelay */ + initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier */ + pollDelayMultiplier?: (number|null); + + /** LongRunning maxPollDelay */ + maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout */ + totalPollTimeout?: (google.protobuf.IDuration|null); + } + + /** Represents a LongRunning. */ + class LongRunning implements ILongRunning { + + /** + * Constructs a new LongRunning. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.MethodSettings.ILongRunning); + + /** LongRunning initialPollDelay. */ + public initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier. */ + public pollDelayMultiplier: number; + + /** LongRunning maxPollDelay. */ + public maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout. */ + public totalPollTimeout?: (google.protobuf.IDuration|null); + + /** + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LongRunning + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings.LongRunning; + + /** + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @param message LongRunning + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings.LongRunning, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LongRunning to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LongRunning + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** ClientLibraryOrganization enum. */ + type ClientLibraryOrganization = + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"| "CLOUD"| "ADS"| "PHOTOS"| "STREET_VIEW"| "SHOPPING"| "GEO"| "GENERATIVE_AI"; + + /** ClientLibraryDestination enum. */ + type ClientLibraryDestination = + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"| "GITHUB"| "PACKAGE_MANAGER"; + + /** Properties of a SelectiveGapicGeneration. */ + interface ISelectiveGapicGeneration { + + /** SelectiveGapicGeneration methods */ + methods?: (string[]|null); + + /** SelectiveGapicGeneration generateOmittedAsInternal */ + generateOmittedAsInternal?: (boolean|null); + } + + /** Represents a SelectiveGapicGeneration. */ + class SelectiveGapicGeneration implements ISelectiveGapicGeneration { + + /** + * Constructs a new SelectiveGapicGeneration. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ISelectiveGapicGeneration); + + /** SelectiveGapicGeneration methods. */ + public methods: string[]; + + /** SelectiveGapicGeneration generateOmittedAsInternal. */ + public generateOmittedAsInternal: boolean; + + /** + * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SelectiveGapicGeneration + */ + public static fromObject(object: { [k: string]: any }): google.api.SelectiveGapicGeneration; + + /** + * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. + * @param message SelectiveGapicGeneration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.SelectiveGapicGeneration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SelectiveGapicGeneration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SelectiveGapicGeneration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** LaunchStage enum. */ + type LaunchStage = + "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; + + /** FieldBehavior enum. */ + type FieldBehavior = + "FIELD_BEHAVIOR_UNSPECIFIED"| "OPTIONAL"| "REQUIRED"| "OUTPUT_ONLY"| "INPUT_ONLY"| "IMMUTABLE"| "UNORDERED_LIST"| "NON_EMPTY_DEFAULT"| "IDENTIFIER"; + + /** Properties of a ResourceDescriptor. */ + interface IResourceDescriptor { + + /** ResourceDescriptor type */ + type?: (string|null); + + /** ResourceDescriptor pattern */ + pattern?: (string[]|null); + + /** ResourceDescriptor nameField */ + nameField?: (string|null); + + /** ResourceDescriptor history */ + history?: (google.api.ResourceDescriptor.History|null); + + /** ResourceDescriptor plural */ + plural?: (string|null); + + /** ResourceDescriptor singular */ + singular?: (string|null); + + /** ResourceDescriptor style */ + style?: (google.api.ResourceDescriptor.Style[]|null); + } + + /** Represents a ResourceDescriptor. */ + class ResourceDescriptor implements IResourceDescriptor { + + /** + * Constructs a new ResourceDescriptor. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceDescriptor); + + /** ResourceDescriptor type. */ + public type: string; + + /** ResourceDescriptor pattern. */ + public pattern: string[]; + + /** ResourceDescriptor nameField. */ + public nameField: string; + + /** ResourceDescriptor history. */ + public history: google.api.ResourceDescriptor.History; + + /** ResourceDescriptor plural. */ + public plural: string; + + /** ResourceDescriptor singular. */ + public singular: string; + + /** ResourceDescriptor style. */ + public style: google.api.ResourceDescriptor.Style[]; + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceDescriptor + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @param message ResourceDescriptor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceDescriptor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceDescriptor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ResourceDescriptor { + + /** History enum. */ + type History = + "HISTORY_UNSPECIFIED"| "ORIGINALLY_SINGLE_PATTERN"| "FUTURE_MULTI_PATTERN"; + + /** Style enum. */ + type Style = + "STYLE_UNSPECIFIED"| "DECLARATIVE_FRIENDLY"; + } + + /** Properties of a ResourceReference. */ + interface IResourceReference { + + /** ResourceReference type */ + type?: (string|null); + + /** ResourceReference childType */ + childType?: (string|null); + } + + /** Represents a ResourceReference. */ + class ResourceReference implements IResourceReference { + + /** + * Constructs a new ResourceReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceReference); + + /** ResourceReference type. */ + public type: string; + + /** ResourceReference childType. */ + public childType: string; + + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceReference + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; + + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @param message ResourceReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace rpc. */ + namespace rpc { + + /** Properties of a Status. */ + interface IStatus { + + /** Status code */ + code?: (number|null); + + /** Status message */ + message?: (string|null); + + /** Status details */ + details?: (google.protobuf.IAny[]|null); + } + + /** Represents a Status. */ + class Status implements IStatus { + + /** + * Constructs a new Status. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IStatus); + + /** Status code. */ + public code: number; + + /** Status message. */ + public message: string; + + /** Status details. */ + public details: google.protobuf.IAny[]; + + /** + * Creates a Status message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Status + */ + public static fromObject(object: { [k: string]: any }): google.rpc.Status; + + /** + * Creates a plain object from a Status message. Also converts values to other types if specified. + * @param message Status + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Status to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Status + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace longrunning. */ + namespace longrunning { + + /** Represents an Operations */ + class Operations extends $protobuf.rpc.Service { + + /** + * Constructs a new Operations service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListOperationsResponse + */ + public listOperations(request: google.longrunning.IListOperationsRequest, callback: google.longrunning.Operations.ListOperationsCallback): void; + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @returns Promise + */ + public listOperations(request: google.longrunning.IListOperationsRequest): Promise; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public getOperation(request: google.longrunning.IGetOperationRequest, callback: google.longrunning.Operations.GetOperationCallback): void; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @returns Promise + */ + public getOperation(request: google.longrunning.IGetOperationRequest): Promise; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest, callback: google.longrunning.Operations.DeleteOperationCallback): void; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @returns Promise + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest): Promise; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest, callback: google.longrunning.Operations.CancelOperationCallback): void; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @returns Promise + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest): Promise; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest, callback: google.longrunning.Operations.WaitOperationCallback): void; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @returns Promise + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest): Promise; + } + + namespace Operations { + + /** + * Callback as used by {@link google.longrunning.Operations#listOperations}. + * @param error Error, if any + * @param [response] ListOperationsResponse + */ + type ListOperationsCallback = (error: (Error|null), response?: google.longrunning.ListOperationsResponse) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#getOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type GetOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#deleteOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#cancelOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type CancelOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations#waitOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type WaitOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + } + + /** Properties of an Operation. */ + interface IOperation { + + /** Operation name */ + name?: (string|null); + + /** Operation metadata */ + metadata?: (google.protobuf.IAny|null); + + /** Operation done */ + done?: (boolean|null); + + /** Operation error */ + error?: (google.rpc.IStatus|null); + + /** Operation response */ + response?: (google.protobuf.IAny|null); + } + + /** Represents an Operation. */ + class Operation implements IOperation { + + /** + * Constructs a new Operation. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperation); + + /** Operation name. */ + public name: string; + + /** Operation metadata. */ + public metadata?: (google.protobuf.IAny|null); + + /** Operation done. */ + public done: boolean; + + /** Operation error. */ + public error?: (google.rpc.IStatus|null); + + /** Operation response. */ + public response?: (google.protobuf.IAny|null); + + /** Operation result. */ + public result?: ("error"|"response"); + + /** + * Creates an Operation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Operation + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.Operation; + + /** + * Creates a plain object from an Operation message. Also converts values to other types if specified. + * @param message Operation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.Operation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Operation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Operation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetOperationRequest. */ + interface IGetOperationRequest { + + /** GetOperationRequest name */ + name?: (string|null); + } + + /** Represents a GetOperationRequest. */ + class GetOperationRequest implements IGetOperationRequest { + + /** + * Constructs a new GetOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IGetOperationRequest); + + /** GetOperationRequest name. */ + public name: string; + + /** + * Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.GetOperationRequest; + + /** + * Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified. + * @param message GetOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.GetOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsRequest. */ + interface IListOperationsRequest { + + /** ListOperationsRequest name */ + name?: (string|null); + + /** ListOperationsRequest filter */ + filter?: (string|null); + + /** ListOperationsRequest pageSize */ + pageSize?: (number|null); + + /** ListOperationsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListOperationsRequest. */ + class ListOperationsRequest implements IListOperationsRequest { + + /** + * Constructs a new ListOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsRequest); + + /** ListOperationsRequest name. */ + public name: string; + + /** ListOperationsRequest filter. */ + public filter: string; + + /** ListOperationsRequest pageSize. */ + public pageSize: number; + + /** ListOperationsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsRequest; + + /** + * Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified. + * @param message ListOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsResponse. */ + interface IListOperationsResponse { + + /** ListOperationsResponse operations */ + operations?: (google.longrunning.IOperation[]|null); + + /** ListOperationsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListOperationsResponse. */ + class ListOperationsResponse implements IListOperationsResponse { + + /** + * Constructs a new ListOperationsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsResponse); + + /** ListOperationsResponse operations. */ + public operations: google.longrunning.IOperation[]; + + /** ListOperationsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsResponse + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsResponse; + + /** + * Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified. + * @param message ListOperationsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CancelOperationRequest. */ + interface ICancelOperationRequest { + + /** CancelOperationRequest name */ + name?: (string|null); + } + + /** Represents a CancelOperationRequest. */ + class CancelOperationRequest implements ICancelOperationRequest { + + /** + * Constructs a new CancelOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.ICancelOperationRequest); + + /** CancelOperationRequest name. */ + public name: string; + + /** + * Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CancelOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.CancelOperationRequest; + + /** + * Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified. + * @param message CancelOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.CancelOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CancelOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CancelOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteOperationRequest. */ + interface IDeleteOperationRequest { + + /** DeleteOperationRequest name */ + name?: (string|null); + } + + /** Represents a DeleteOperationRequest. */ + class DeleteOperationRequest implements IDeleteOperationRequest { + + /** + * Constructs a new DeleteOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IDeleteOperationRequest); + + /** DeleteOperationRequest name. */ + public name: string; + + /** + * Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.DeleteOperationRequest; + + /** + * Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified. + * @param message DeleteOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.DeleteOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WaitOperationRequest. */ + interface IWaitOperationRequest { + + /** WaitOperationRequest name */ + name?: (string|null); + + /** WaitOperationRequest timeout */ + timeout?: (google.protobuf.IDuration|null); + } + + /** Represents a WaitOperationRequest. */ + class WaitOperationRequest implements IWaitOperationRequest { + + /** + * Constructs a new WaitOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IWaitOperationRequest); + + /** WaitOperationRequest name. */ + public name: string; + + /** WaitOperationRequest timeout. */ + public timeout?: (google.protobuf.IDuration|null); + + /** + * Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WaitOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.WaitOperationRequest; + + /** + * Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified. + * @param message WaitOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.WaitOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WaitOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WaitOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an OperationInfo. */ + interface IOperationInfo { + + /** OperationInfo responseType */ + responseType?: (string|null); + + /** OperationInfo metadataType */ + metadataType?: (string|null); + } + + /** Represents an OperationInfo. */ + class OperationInfo implements IOperationInfo { + + /** + * Constructs a new OperationInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperationInfo); + + /** OperationInfo responseType. */ + public responseType: string; + + /** OperationInfo metadataType. */ + public metadataType: string; + + /** + * Creates an OperationInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OperationInfo + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.OperationInfo; + + /** + * Creates a plain object from an OperationInfo message. Also converts values to other types if specified. + * @param message OperationInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.OperationInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OperationInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OperationInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } +} diff --git a/node_modules/@google-cloud/firestore/build/protos/firestore_v1beta1_proto_api.js b/node_modules/@google-cloud/firestore/build/protos/firestore_v1beta1_proto_api.js new file mode 100644 index 0000000..d853af1 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/firestore_v1beta1_proto_api.js @@ -0,0 +1 @@ +(e=>{"function"==typeof define&&define.amd?define(["protobufjs/minimal"],e):"function"==typeof require&&"object"==typeof module&&module&&module.exports&&(module.exports=e(require("protobufjs/minimal")))})(function(r){var e,t,o,n,x,i=r.util,a=r.roots.firestore_v1beta1||(r.roots.firestore_v1beta1={});function V(e){if(e)for(var t=Object.keys(e),o=0;o>>0,e.seconds.high>>>0).toNumber())),null!=e.nanos&&(t.nanos=0|e.nanos),t)},V.toObject=function(e,t){var o,r={};return(t=t||{}).defaults&&(i.Long?(o=new i.Long(0,0,!1),r.seconds=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.seconds=t.longs===String?"0":0,r.nanos=0),null!=e.seconds&&e.hasOwnProperty("seconds")&&("number"==typeof e.seconds?r.seconds=t.longs===String?String(e.seconds):e.seconds:r.seconds=t.longs===String?i.Long.prototype.toString.call(e.seconds):t.longs===Number?new i.LongBits(e.seconds.low>>>0,e.seconds.high>>>0).toNumber():e.seconds),null!=e.nanos&&e.hasOwnProperty("nanos")&&(r.nanos=e.nanos),r},V.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},V.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.Timestamp"},V),n.Struct=(L.prototype.fields=i.emptyObject,L.fromObject=function(e){if(e instanceof a.google.protobuf.Struct)return e;var t=new a.google.protobuf.Struct;if(e.fields){if("object"!=typeof e.fields)throw TypeError(".google.protobuf.Struct.fields: object expected");t.fields={};for(var o=Object.keys(e.fields),r=0;r>>0,e.positiveIntValue.high>>>0).toNumber(!0))),null!=e.negativeIntValue&&(i.Long?(t.negativeIntValue=i.Long.fromValue(e.negativeIntValue)).unsigned=!1:"string"==typeof e.negativeIntValue?t.negativeIntValue=parseInt(e.negativeIntValue,10):"number"==typeof e.negativeIntValue?t.negativeIntValue=e.negativeIntValue:"object"==typeof e.negativeIntValue&&(t.negativeIntValue=new i.LongBits(e.negativeIntValue.low>>>0,e.negativeIntValue.high>>>0).toNumber())),null!=e.doubleValue&&(t.doubleValue=Number(e.doubleValue)),null!=e.stringValue&&("string"==typeof e.stringValue?i.base64.decode(e.stringValue,t.stringValue=i.newBuffer(i.base64.length(e.stringValue)),0):0<=e.stringValue.length&&(t.stringValue=e.stringValue)),null!=e.aggregateValue&&(t.aggregateValue=String(e.aggregateValue)),t},h.toObject=function(e,t){var o,r={};if(((t=t||{}).arrays||t.defaults)&&(r.name=[]),t.defaults&&(r.identifierValue="",i.Long?(o=new i.Long(0,0,!0),r.positiveIntValue=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.positiveIntValue=t.longs===String?"0":0,i.Long?(o=new i.Long(0,0,!1),r.negativeIntValue=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.negativeIntValue=t.longs===String?"0":0,r.doubleValue=0,t.bytes===String?r.stringValue="":(r.stringValue=[],t.bytes!==Array&&(r.stringValue=i.newBuffer(r.stringValue))),r.aggregateValue=""),e.name&&e.name.length){r.name=[];for(var n=0;n>>0,e.positiveIntValue.high>>>0).toNumber(!0):e.positiveIntValue),null!=e.negativeIntValue&&e.hasOwnProperty("negativeIntValue")&&("number"==typeof e.negativeIntValue?r.negativeIntValue=t.longs===String?String(e.negativeIntValue):e.negativeIntValue:r.negativeIntValue=t.longs===String?i.Long.prototype.toString.call(e.negativeIntValue):t.longs===Number?new i.LongBits(e.negativeIntValue.low>>>0,e.negativeIntValue.high>>>0).toNumber():e.negativeIntValue),null!=e.doubleValue&&e.hasOwnProperty("doubleValue")&&(r.doubleValue=t.json&&!isFinite(e.doubleValue)?String(e.doubleValue):e.doubleValue),null!=e.stringValue&&e.hasOwnProperty("stringValue")&&(r.stringValue=t.bytes===String?i.base64.encode(e.stringValue,0,e.stringValue.length):t.bytes===Array?Array.prototype.slice.call(e.stringValue):e.stringValue),null!=e.aggregateValue&&e.hasOwnProperty("aggregateValue")&&(r.aggregateValue=e.aggregateValue),r},h.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},h.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.UninterpretedOption"},h.NamePart=(Z.prototype.namePart="",Z.prototype.isExtension=!1,Z.fromObject=function(e){var t;return e instanceof a.google.protobuf.UninterpretedOption.NamePart?e:(t=new a.google.protobuf.UninterpretedOption.NamePart,null!=e.namePart&&(t.namePart=String(e.namePart)),null!=e.isExtension&&(t.isExtension=Boolean(e.isExtension)),t)},Z.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.namePart="",o.isExtension=!1),null!=e.namePart&&e.hasOwnProperty("namePart")&&(o.namePart=e.namePart),null!=e.isExtension&&e.hasOwnProperty("isExtension")&&(o.isExtension=e.isExtension),o},Z.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Z.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.UninterpretedOption.NamePart"},Z),h),n.FeatureSet=(v.prototype.fieldPresence=0,v.prototype.enumType=0,v.prototype.repeatedFieldEncoding=0,v.prototype.utf8Validation=0,v.prototype.messageEncoding=0,v.prototype.jsonFormat=0,v.fromObject=function(e){if(e instanceof a.google.protobuf.FeatureSet)return e;var t=new a.google.protobuf.FeatureSet;switch(e.fieldPresence){default:"number"==typeof e.fieldPresence&&(t.fieldPresence=e.fieldPresence);break;case"FIELD_PRESENCE_UNKNOWN":case 0:t.fieldPresence=0;break;case"EXPLICIT":case 1:t.fieldPresence=1;break;case"IMPLICIT":case 2:t.fieldPresence=2;break;case"LEGACY_REQUIRED":case 3:t.fieldPresence=3}switch(e.enumType){default:"number"==typeof e.enumType&&(t.enumType=e.enumType);break;case"ENUM_TYPE_UNKNOWN":case 0:t.enumType=0;break;case"OPEN":case 1:t.enumType=1;break;case"CLOSED":case 2:t.enumType=2}switch(e.repeatedFieldEncoding){default:"number"==typeof e.repeatedFieldEncoding&&(t.repeatedFieldEncoding=e.repeatedFieldEncoding);break;case"REPEATED_FIELD_ENCODING_UNKNOWN":case 0:t.repeatedFieldEncoding=0;break;case"PACKED":case 1:t.repeatedFieldEncoding=1;break;case"EXPANDED":case 2:t.repeatedFieldEncoding=2}switch(e.utf8Validation){default:"number"==typeof e.utf8Validation&&(t.utf8Validation=e.utf8Validation);break;case"UTF8_VALIDATION_UNKNOWN":case 0:t.utf8Validation=0;break;case"VERIFY":case 2:t.utf8Validation=2;break;case"NONE":case 3:t.utf8Validation=3}switch(e.messageEncoding){default:"number"==typeof e.messageEncoding&&(t.messageEncoding=e.messageEncoding);break;case"MESSAGE_ENCODING_UNKNOWN":case 0:t.messageEncoding=0;break;case"LENGTH_PREFIXED":case 1:t.messageEncoding=1;break;case"DELIMITED":case 2:t.messageEncoding=2}switch(e.jsonFormat){default:"number"==typeof e.jsonFormat&&(t.jsonFormat=e.jsonFormat);break;case"JSON_FORMAT_UNKNOWN":case 0:t.jsonFormat=0;break;case"ALLOW":case 1:t.jsonFormat=1;break;case"LEGACY_BEST_EFFORT":case 2:t.jsonFormat=2}return t},v.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.fieldPresence=t.enums===String?"FIELD_PRESENCE_UNKNOWN":0,o.enumType=t.enums===String?"ENUM_TYPE_UNKNOWN":0,o.repeatedFieldEncoding=t.enums===String?"REPEATED_FIELD_ENCODING_UNKNOWN":0,o.utf8Validation=t.enums===String?"UTF8_VALIDATION_UNKNOWN":0,o.messageEncoding=t.enums===String?"MESSAGE_ENCODING_UNKNOWN":0,o.jsonFormat=t.enums===String?"JSON_FORMAT_UNKNOWN":0),null!=e.fieldPresence&&e.hasOwnProperty("fieldPresence")&&(o.fieldPresence=t.enums!==String||void 0===a.google.protobuf.FeatureSet.FieldPresence[e.fieldPresence]?e.fieldPresence:a.google.protobuf.FeatureSet.FieldPresence[e.fieldPresence]),null!=e.enumType&&e.hasOwnProperty("enumType")&&(o.enumType=t.enums!==String||void 0===a.google.protobuf.FeatureSet.EnumType[e.enumType]?e.enumType:a.google.protobuf.FeatureSet.EnumType[e.enumType]),null!=e.repeatedFieldEncoding&&e.hasOwnProperty("repeatedFieldEncoding")&&(o.repeatedFieldEncoding=t.enums!==String||void 0===a.google.protobuf.FeatureSet.RepeatedFieldEncoding[e.repeatedFieldEncoding]?e.repeatedFieldEncoding:a.google.protobuf.FeatureSet.RepeatedFieldEncoding[e.repeatedFieldEncoding]),null!=e.utf8Validation&&e.hasOwnProperty("utf8Validation")&&(o.utf8Validation=t.enums!==String||void 0===a.google.protobuf.FeatureSet.Utf8Validation[e.utf8Validation]?e.utf8Validation:a.google.protobuf.FeatureSet.Utf8Validation[e.utf8Validation]),null!=e.messageEncoding&&e.hasOwnProperty("messageEncoding")&&(o.messageEncoding=t.enums!==String||void 0===a.google.protobuf.FeatureSet.MessageEncoding[e.messageEncoding]?e.messageEncoding:a.google.protobuf.FeatureSet.MessageEncoding[e.messageEncoding]),null!=e.jsonFormat&&e.hasOwnProperty("jsonFormat")&&(o.jsonFormat=t.enums!==String||void 0===a.google.protobuf.FeatureSet.JsonFormat[e.jsonFormat]?e.jsonFormat:a.google.protobuf.FeatureSet.JsonFormat[e.jsonFormat]),o},v.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},v.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.FeatureSet"},v.FieldPresence=(e={},(o=Object.create(e))[e[0]="FIELD_PRESENCE_UNKNOWN"]="FIELD_PRESENCE_UNKNOWN",o[e[1]="EXPLICIT"]="EXPLICIT",o[e[2]="IMPLICIT"]="IMPLICIT",o[e[3]="LEGACY_REQUIRED"]="LEGACY_REQUIRED",o),v.EnumType=(e={},(o=Object.create(e))[e[0]="ENUM_TYPE_UNKNOWN"]="ENUM_TYPE_UNKNOWN",o[e[1]="OPEN"]="OPEN",o[e[2]="CLOSED"]="CLOSED",o),v.RepeatedFieldEncoding=(e={},(o=Object.create(e))[e[0]="REPEATED_FIELD_ENCODING_UNKNOWN"]="REPEATED_FIELD_ENCODING_UNKNOWN",o[e[1]="PACKED"]="PACKED",o[e[2]="EXPANDED"]="EXPANDED",o),v.Utf8Validation=(e={},(o=Object.create(e))[e[0]="UTF8_VALIDATION_UNKNOWN"]="UTF8_VALIDATION_UNKNOWN",o[e[2]="VERIFY"]="VERIFY",o[e[3]="NONE"]="NONE",o),v.MessageEncoding=(e={},(o=Object.create(e))[e[0]="MESSAGE_ENCODING_UNKNOWN"]="MESSAGE_ENCODING_UNKNOWN",o[e[1]="LENGTH_PREFIXED"]="LENGTH_PREFIXED",o[e[2]="DELIMITED"]="DELIMITED",o),v.JsonFormat=(e={},(o=Object.create(e))[e[0]="JSON_FORMAT_UNKNOWN"]="JSON_FORMAT_UNKNOWN",o[e[1]="ALLOW"]="ALLOW",o[e[2]="LEGACY_BEST_EFFORT"]="LEGACY_BEST_EFFORT",o),v),n.FeatureSetDefaults=($.prototype.defaults=i.emptyArray,$.prototype.minimumEdition=0,$.prototype.maximumEdition=0,$.fromObject=function(e){if(e instanceof a.google.protobuf.FeatureSetDefaults)return e;var t=new a.google.protobuf.FeatureSetDefaults;if(e.defaults){if(!Array.isArray(e.defaults))throw TypeError(".google.protobuf.FeatureSetDefaults.defaults: array expected");t.defaults=[];for(var o=0;o>>0,e.seconds.high>>>0).toNumber())),null!=e.nanos&&(t.nanos=0|e.nanos),t)},ne.toObject=function(e,t){var o,r={};return(t=t||{}).defaults&&(i.Long?(o=new i.Long(0,0,!1),r.seconds=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.seconds=t.longs===String?"0":0,r.nanos=0),null!=e.seconds&&e.hasOwnProperty("seconds")&&("number"==typeof e.seconds?r.seconds=t.longs===String?String(e.seconds):e.seconds:r.seconds=t.longs===String?i.Long.prototype.toString.call(e.seconds):t.longs===Number?new i.LongBits(e.seconds.low>>>0,e.seconds.high>>>0).toNumber():e.seconds),null!=e.nanos&&e.hasOwnProperty("nanos")&&(r.nanos=e.nanos),r},ne.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},ne.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.Duration"},ne),n.DoubleValue=(ie.prototype.value=0,ie.fromObject=function(e){var t;return e instanceof a.google.protobuf.DoubleValue?e:(t=new a.google.protobuf.DoubleValue,null!=e.value&&(t.value=Number(e.value)),t)},ie.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.value=0),null!=e.value&&e.hasOwnProperty("value")&&(o.value=t.json&&!isFinite(e.value)?String(e.value):e.value),o},ie.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},ie.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.DoubleValue"},ie),n.FloatValue=(ae.prototype.value=0,ae.fromObject=function(e){var t;return e instanceof a.google.protobuf.FloatValue?e:(t=new a.google.protobuf.FloatValue,null!=e.value&&(t.value=Number(e.value)),t)},ae.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.value=0),null!=e.value&&e.hasOwnProperty("value")&&(o.value=t.json&&!isFinite(e.value)?String(e.value):e.value),o},ae.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},ae.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.FloatValue"},ae),n.Int64Value=(se.prototype.value=i.Long?i.Long.fromBits(0,0,!1):0,se.fromObject=function(e){var t;return e instanceof a.google.protobuf.Int64Value?e:(t=new a.google.protobuf.Int64Value,null!=e.value&&(i.Long?(t.value=i.Long.fromValue(e.value)).unsigned=!1:"string"==typeof e.value?t.value=parseInt(e.value,10):"number"==typeof e.value?t.value=e.value:"object"==typeof e.value&&(t.value=new i.LongBits(e.value.low>>>0,e.value.high>>>0).toNumber())),t)},se.toObject=function(e,t){var o,r={};return(t=t||{}).defaults&&(i.Long?(o=new i.Long(0,0,!1),r.value=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.value=t.longs===String?"0":0),null!=e.value&&e.hasOwnProperty("value")&&("number"==typeof e.value?r.value=t.longs===String?String(e.value):e.value:r.value=t.longs===String?i.Long.prototype.toString.call(e.value):t.longs===Number?new i.LongBits(e.value.low>>>0,e.value.high>>>0).toNumber():e.value),r},se.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},se.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.Int64Value"},se),n.UInt64Value=(le.prototype.value=i.Long?i.Long.fromBits(0,0,!0):0,le.fromObject=function(e){var t;return e instanceof a.google.protobuf.UInt64Value?e:(t=new a.google.protobuf.UInt64Value,null!=e.value&&(i.Long?(t.value=i.Long.fromValue(e.value)).unsigned=!0:"string"==typeof e.value?t.value=parseInt(e.value,10):"number"==typeof e.value?t.value=e.value:"object"==typeof e.value&&(t.value=new i.LongBits(e.value.low>>>0,e.value.high>>>0).toNumber(!0))),t)},le.toObject=function(e,t){var o,r={};return(t=t||{}).defaults&&(i.Long?(o=new i.Long(0,0,!0),r.value=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.value=t.longs===String?"0":0),null!=e.value&&e.hasOwnProperty("value")&&("number"==typeof e.value?r.value=t.longs===String?String(e.value):e.value:r.value=t.longs===String?i.Long.prototype.toString.call(e.value):t.longs===Number?new i.LongBits(e.value.low>>>0,e.value.high>>>0).toNumber(!0):e.value),r},le.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},le.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.UInt64Value"},le),n.Int32Value=(ue.prototype.value=0,ue.fromObject=function(e){var t;return e instanceof a.google.protobuf.Int32Value?e:(t=new a.google.protobuf.Int32Value,null!=e.value&&(t.value=0|e.value),t)},ue.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.value=0),null!=e.value&&e.hasOwnProperty("value")&&(o.value=e.value),o},ue.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},ue.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.Int32Value"},ue),n.UInt32Value=(pe.prototype.value=0,pe.fromObject=function(e){var t;return e instanceof a.google.protobuf.UInt32Value?e:(t=new a.google.protobuf.UInt32Value,null!=e.value&&(t.value=e.value>>>0),t)},pe.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.value=0),null!=e.value&&e.hasOwnProperty("value")&&(o.value=e.value),o},pe.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},pe.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.UInt32Value"},pe),n.BoolValue=(ce.prototype.value=!1,ce.fromObject=function(e){var t;return e instanceof a.google.protobuf.BoolValue?e:(t=new a.google.protobuf.BoolValue,null!=e.value&&(t.value=Boolean(e.value)),t)},ce.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.value=!1),null!=e.value&&e.hasOwnProperty("value")&&(o.value=e.value),o},ce.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},ce.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.BoolValue"},ce),n.StringValue=(ge.prototype.value="",ge.fromObject=function(e){var t;return e instanceof a.google.protobuf.StringValue?e:(t=new a.google.protobuf.StringValue,null!=e.value&&(t.value=String(e.value)),t)},ge.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.value=""),null!=e.value&&e.hasOwnProperty("value")&&(o.value=e.value),o},ge.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},ge.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.StringValue"},ge),n.BytesValue=(fe.prototype.value=i.newBuffer([]),fe.fromObject=function(e){var t;return e instanceof a.google.protobuf.BytesValue?e:(t=new a.google.protobuf.BytesValue,null!=e.value&&("string"==typeof e.value?i.base64.decode(e.value,t.value=i.newBuffer(i.base64.length(e.value)),0):0<=e.value.length&&(t.value=e.value)),t)},fe.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(t.bytes===String?o.value="":(o.value=[],t.bytes!==Array&&(o.value=i.newBuffer(o.value)))),null!=e.value&&e.hasOwnProperty("value")&&(o.value=t.bytes===String?i.base64.encode(e.value,0,e.value.length):t.bytes===Array?Array.prototype.slice.call(e.value):e.value),o},fe.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},fe.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.BytesValue"},fe),n.Empty=(de.fromObject=function(e){return e instanceof a.google.protobuf.Empty?e:new a.google.protobuf.Empty},de.toObject=function(){return{}},de.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},de.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.Empty"},de),n.Any=(ye.prototype.type_url="",ye.prototype.value=i.newBuffer([]),ye.fromObject=function(e){var t;return e instanceof a.google.protobuf.Any?e:(t=new a.google.protobuf.Any,null!=e.type_url&&(t.type_url=String(e.type_url)),null!=e.value&&("string"==typeof e.value?i.base64.decode(e.value,t.value=i.newBuffer(i.base64.length(e.value)),0):0<=e.value.length&&(t.value=e.value)),t)},ye.toObject=function(e,t){var o={};return(t=t||{}).defaults&&(o.type_url="",t.bytes===String?o.value="":(o.value=[],t.bytes!==Array&&(o.value=i.newBuffer(o.value)))),null!=e.type_url&&e.hasOwnProperty("type_url")&&(o.type_url=e.type_url),null!=e.value&&e.hasOwnProperty("value")&&(o.value=t.bytes===String?i.base64.encode(e.value,0,e.value.length):t.bytes===Array?Array.prototype.slice.call(e.value):e.value),o},ye.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},ye.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.protobuf.Any"},ye),n.FieldMask=(me.prototype.paths=i.emptyArray,me.fromObject=function(e){if(e instanceof a.google.protobuf.FieldMask)return e;var t=new a.google.protobuf.FieldMask;if(e.paths){if(!Array.isArray(e.paths))throw TypeError(".google.protobuf.FieldMask.paths: array expected");t.paths=[];for(var o=0;o>>0,e.integerValue.high>>>0).toNumber())),null!=e.doubleValue&&(t.doubleValue=Number(e.doubleValue)),null!=e.timestampValue){if("object"!=typeof e.timestampValue)throw TypeError(".google.firestore.v1beta1.Value.timestampValue: object expected");t.timestampValue=a.google.protobuf.Timestamp.fromObject(e.timestampValue)}if(null!=e.stringValue&&(t.stringValue=String(e.stringValue)),null!=e.bytesValue&&("string"==typeof e.bytesValue?i.base64.decode(e.bytesValue,t.bytesValue=i.newBuffer(i.base64.length(e.bytesValue)),0):0<=e.bytesValue.length&&(t.bytesValue=e.bytesValue)),null!=e.referenceValue&&(t.referenceValue=String(e.referenceValue)),null!=e.geoPointValue){if("object"!=typeof e.geoPointValue)throw TypeError(".google.firestore.v1beta1.Value.geoPointValue: object expected");t.geoPointValue=a.google.type.LatLng.fromObject(e.geoPointValue)}if(null!=e.arrayValue){if("object"!=typeof e.arrayValue)throw TypeError(".google.firestore.v1beta1.Value.arrayValue: object expected");t.arrayValue=a.google.firestore.v1beta1.ArrayValue.fromObject(e.arrayValue)}if(null!=e.mapValue){if("object"!=typeof e.mapValue)throw TypeError(".google.firestore.v1beta1.Value.mapValue: object expected");t.mapValue=a.google.firestore.v1beta1.MapValue.fromObject(e.mapValue)}return t},S.toObject=function(e,t){t=t||{};var o={};return null!=e.booleanValue&&e.hasOwnProperty("booleanValue")&&(o.booleanValue=e.booleanValue,t.oneofs)&&(o.valueType="booleanValue"),null!=e.integerValue&&e.hasOwnProperty("integerValue")&&("number"==typeof e.integerValue?o.integerValue=t.longs===String?String(e.integerValue):e.integerValue:o.integerValue=t.longs===String?i.Long.prototype.toString.call(e.integerValue):t.longs===Number?new i.LongBits(e.integerValue.low>>>0,e.integerValue.high>>>0).toNumber():e.integerValue,t.oneofs)&&(o.valueType="integerValue"),null!=e.doubleValue&&e.hasOwnProperty("doubleValue")&&(o.doubleValue=t.json&&!isFinite(e.doubleValue)?String(e.doubleValue):e.doubleValue,t.oneofs)&&(o.valueType="doubleValue"),null!=e.referenceValue&&e.hasOwnProperty("referenceValue")&&(o.referenceValue=e.referenceValue,t.oneofs)&&(o.valueType="referenceValue"),null!=e.mapValue&&e.hasOwnProperty("mapValue")&&(o.mapValue=a.google.firestore.v1beta1.MapValue.toObject(e.mapValue,t),t.oneofs)&&(o.valueType="mapValue"),null!=e.geoPointValue&&e.hasOwnProperty("geoPointValue")&&(o.geoPointValue=a.google.type.LatLng.toObject(e.geoPointValue,t),t.oneofs)&&(o.valueType="geoPointValue"),null!=e.arrayValue&&e.hasOwnProperty("arrayValue")&&(o.arrayValue=a.google.firestore.v1beta1.ArrayValue.toObject(e.arrayValue,t),t.oneofs)&&(o.valueType="arrayValue"),null!=e.timestampValue&&e.hasOwnProperty("timestampValue")&&(o.timestampValue=a.google.protobuf.Timestamp.toObject(e.timestampValue,t),t.oneofs)&&(o.valueType="timestampValue"),null!=e.nullValue&&e.hasOwnProperty("nullValue")&&(o.nullValue=t.enums!==String||void 0===a.google.protobuf.NullValue[e.nullValue]?e.nullValue:a.google.protobuf.NullValue[e.nullValue],t.oneofs)&&(o.valueType="nullValue"),null!=e.stringValue&&e.hasOwnProperty("stringValue")&&(o.stringValue=e.stringValue,t.oneofs)&&(o.valueType="stringValue"),null!=e.bytesValue&&e.hasOwnProperty("bytesValue")&&(o.bytesValue=t.bytes===String?i.base64.encode(e.bytesValue,0,e.bytesValue.length):t.bytes===Array?Array.prototype.slice.call(e.bytesValue):e.bytesValue,t.oneofs)&&(o.valueType="bytesValue"),o},S.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},S.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.firestore.v1beta1.Value"},S),o.ArrayValue=(je.prototype.values=i.emptyArray,je.fromObject=function(e){if(e instanceof a.google.firestore.v1beta1.ArrayValue)return e;var t=new a.google.firestore.v1beta1.ArrayValue;if(e.values){if(!Array.isArray(e.values))throw TypeError(".google.firestore.v1beta1.ArrayValue.values: array expected");t.values=[];for(var o=0;o>>0,e.partitionCount.high>>>0).toNumber())),null!=e.pageToken&&(t.pageToken=String(e.pageToken)),null!=e.pageSize&&(t.pageSize=0|e.pageSize),t},Ve.toObject=function(e,t){var o,r={};return(t=t||{}).defaults&&(r.parent="",i.Long?(o=new i.Long(0,0,!1),r.partitionCount=t.longs===String?o.toString():t.longs===Number?o.toNumber():o):r.partitionCount=t.longs===String?"0":0,r.pageToken="",r.pageSize=0),null!=e.parent&&e.hasOwnProperty("parent")&&(r.parent=e.parent),null!=e.structuredQuery&&e.hasOwnProperty("structuredQuery")&&(r.structuredQuery=a.google.firestore.v1beta1.StructuredQuery.toObject(e.structuredQuery,t),t.oneofs)&&(r.queryType="structuredQuery"),null!=e.partitionCount&&e.hasOwnProperty("partitionCount")&&("number"==typeof e.partitionCount?r.partitionCount=t.longs===String?String(e.partitionCount):e.partitionCount:r.partitionCount=t.longs===String?i.Long.prototype.toString.call(e.partitionCount):t.longs===Number?new i.LongBits(e.partitionCount.low>>>0,e.partitionCount.high>>>0).toNumber():e.partitionCount),null!=e.pageToken&&e.hasOwnProperty("pageToken")&&(r.pageToken=e.pageToken),null!=e.pageSize&&e.hasOwnProperty("pageSize")&&(r.pageSize=e.pageSize),r},Ve.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},Ve.getTypeUrl=function(e){return(e=void 0===e?"type.googleapis.com":e)+"/google.firestore.v1beta1.PartitionQueryRequest"},Ve),o.PartitionQueryResponse=(Le.prototype.partitions=i.emptyArray,Le.prototype.nextPageToken="",Le.fromObject=function(e){if(e instanceof a.google.firestore.v1beta1.PartitionQueryResponse)return e;var t=new a.google.firestore.v1beta1.PartitionQueryResponse;if(e.partitions){if(!Array.isArray(e.partitions))throw TypeError(".google.firestore.v1beta1.PartitionQueryResponse.partitions: array expected");t.partitions=[];for(var o=0;o service_class_names = 2; + + // Some settings. + CommonLanguageSettings common = 3; +} + +// Settings for C++ client libraries. +message CppSettings { + // Some settings. + CommonLanguageSettings common = 1; +} + +// Settings for Php client libraries. +message PhpSettings { + // Some settings. + CommonLanguageSettings common = 1; +} + +// Settings for Python client libraries. +message PythonSettings { + // Experimental features to be included during client library generation. + // These fields will be deprecated once the feature graduates and is enabled + // by default. + message ExperimentalFeatures { + // Enables generation of asynchronous REST clients if `rest` transport is + // enabled. By default, asynchronous REST clients will not be generated. + // This feature will be enabled by default 1 month after launching the + // feature in preview packages. + bool rest_async_io_enabled = 1; + + // Enables generation of protobuf code using new types that are more + // Pythonic which are included in `protobuf>=5.29.x`. This feature will be + // enabled by default 1 month after launching the feature in preview + // packages. + bool protobuf_pythonic_types_enabled = 2; + } + + // Some settings. + CommonLanguageSettings common = 1; + + // Experimental features to be included during client library generation. + ExperimentalFeatures experimental_features = 2; +} + +// Settings for Node client libraries. +message NodeSettings { + // Some settings. + CommonLanguageSettings common = 1; +} + +// Settings for Dotnet client libraries. +message DotnetSettings { + // Some settings. + CommonLanguageSettings common = 1; + + // Map from original service names to renamed versions. + // This is used when the default generated types + // would cause a naming conflict. (Neither name is + // fully-qualified.) + // Example: Subscriber to SubscriberServiceApi. + map renamed_services = 2; + + // Map from full resource types to the effective short name + // for the resource. This is used when otherwise resource + // named from different services would cause naming collisions. + // Example entry: + // "datalabeling.googleapis.com/Dataset": "DataLabelingDataset" + map renamed_resources = 3; + + // List of full resource types to ignore during generation. + // This is typically used for API-specific Location resources, + // which should be handled by the generator as if they were actually + // the common Location resources. + // Example entry: "documentai.googleapis.com/Location" + repeated string ignored_resources = 4; + + // Namespaces which must be aliased in snippets due to + // a known (but non-generator-predictable) naming collision + repeated string forced_namespace_aliases = 5; + + // Method signatures (in the form "service.method(signature)") + // which are provided separately, so shouldn't be generated. + // Snippets *calling* these methods are still generated, however. + repeated string handwritten_signatures = 6; +} + +// Settings for Ruby client libraries. +message RubySettings { + // Some settings. + CommonLanguageSettings common = 1; +} + +// Settings for Go client libraries. +message GoSettings { + // Some settings. + CommonLanguageSettings common = 1; + + // Map of service names to renamed services. Keys are the package relative + // service names and values are the name to be used for the service client + // and call options. + // + // publishing: + // go_settings: + // renamed_services: + // Publisher: TopicAdmin + map renamed_services = 2; +} + +// Describes the generator configuration for a method. +message MethodSettings { + // Describes settings to use when generating API methods that use the + // long-running operation pattern. + // All default values below are from those used in the client library + // generators (e.g. + // [Java](https://github.com/googleapis/gapic-generator-java/blob/04c2faa191a9b5a10b92392fe8482279c4404803/src/main/java/com/google/api/generator/gapic/composer/common/RetrySettingsComposer.java)). + message LongRunning { + // Initial delay after which the first poll request will be made. + // Default value: 5 seconds. + google.protobuf.Duration initial_poll_delay = 1; + + // Multiplier to gradually increase delay between subsequent polls until it + // reaches max_poll_delay. + // Default value: 1.5. + float poll_delay_multiplier = 2; + + // Maximum time between two subsequent poll requests. + // Default value: 45 seconds. + google.protobuf.Duration max_poll_delay = 3; + + // Total polling timeout. + // Default value: 5 minutes. + google.protobuf.Duration total_poll_timeout = 4; + } + + // The fully qualified name of the method, for which the options below apply. + // This is used to find the method to apply the options. + // + // Example: + // + // publishing: + // method_settings: + // - selector: google.storage.control.v2.StorageControl.CreateFolder + // # method settings for CreateFolder... + string selector = 1; + + // Describes settings to use for long-running operations when generating + // API methods for RPCs. Complements RPCs that use the annotations in + // google/longrunning/operations.proto. + // + // Example of a YAML configuration:: + // + // publishing: + // method_settings: + // - selector: google.cloud.speech.v2.Speech.BatchRecognize + // long_running: + // initial_poll_delay: 60s # 1 minute + // poll_delay_multiplier: 1.5 + // max_poll_delay: 360s # 6 minutes + // total_poll_timeout: 54000s # 90 minutes + LongRunning long_running = 2; + + // List of top-level fields of the request message, that should be + // automatically populated by the client libraries based on their + // (google.api.field_info).format. Currently supported format: UUID4. + // + // Example of a YAML configuration: + // + // publishing: + // method_settings: + // - selector: google.example.v1.ExampleService.CreateExample + // auto_populated_fields: + // - request_id + repeated string auto_populated_fields = 3; +} + +// The organization for which the client libraries are being published. +// Affects the url where generated docs are published, etc. +enum ClientLibraryOrganization { + // Not useful. + CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED = 0; + + // Google Cloud Platform Org. + CLOUD = 1; + + // Ads (Advertising) Org. + ADS = 2; + + // Photos Org. + PHOTOS = 3; + + // Street View Org. + STREET_VIEW = 4; + + // Shopping Org. + SHOPPING = 5; + + // Geo Org. + GEO = 6; + + // Generative AI - https://developers.generativeai.google + GENERATIVE_AI = 7; +} + +// To where should client libraries be published? +enum ClientLibraryDestination { + // Client libraries will neither be generated nor published to package + // managers. + CLIENT_LIBRARY_DESTINATION_UNSPECIFIED = 0; + + // Generate the client library in a repo under github.com/googleapis, + // but don't publish it to package managers. + GITHUB = 10; + + // Publish the library to package managers like nuget.org and npmjs.com. + PACKAGE_MANAGER = 20; +} + +// This message is used to configure the generation of a subset of the RPCs in +// a service for client libraries. +message SelectiveGapicGeneration { + // An allowlist of the fully qualified names of RPCs that should be included + // on public client surfaces. + repeated string methods = 1; + + // Setting this to true indicates to the client generators that methods + // that would be excluded from the generation should instead be generated + // in a way that indicates these methods should not be consumed by + // end users. How this is expressed is up to individual language + // implementations to decide. Some examples may be: added annotations, + // obfuscated identifiers, or other language idiomatic patterns. + bool generate_omitted_as_internal = 2; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/api/field_behavior.proto b/node_modules/@google-cloud/firestore/build/protos/google/api/field_behavior.proto new file mode 100644 index 0000000..2865ba0 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/api/field_behavior.proto @@ -0,0 +1,104 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/protobuf/descriptor.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "FieldBehaviorProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +extend google.protobuf.FieldOptions { + // A designation of a specific field behavior (required, output only, etc.) + // in protobuf messages. + // + // Examples: + // + // string name = 1 [(google.api.field_behavior) = REQUIRED]; + // State state = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + // google.protobuf.Duration ttl = 1 + // [(google.api.field_behavior) = INPUT_ONLY]; + // google.protobuf.Timestamp expire_time = 1 + // [(google.api.field_behavior) = OUTPUT_ONLY, + // (google.api.field_behavior) = IMMUTABLE]; + repeated google.api.FieldBehavior field_behavior = 1052 [packed = false]; +} + +// An indicator of the behavior of a given field (for example, that a field +// is required in requests, or given as output but ignored as input). +// This **does not** change the behavior in protocol buffers itself; it only +// denotes the behavior and may affect how API tooling handles the field. +// +// Note: This enum **may** receive new values in the future. +enum FieldBehavior { + // Conventional default for enums. Do not use this. + FIELD_BEHAVIOR_UNSPECIFIED = 0; + + // Specifically denotes a field as optional. + // While all fields in protocol buffers are optional, this may be specified + // for emphasis if appropriate. + OPTIONAL = 1; + + // Denotes a field as required. + // This indicates that the field **must** be provided as part of the request, + // and failure to do so will cause an error (usually `INVALID_ARGUMENT`). + REQUIRED = 2; + + // Denotes a field as output only. + // This indicates that the field is provided in responses, but including the + // field in a request does nothing (the server *must* ignore it and + // *must not* throw an error as a result of the field's presence). + OUTPUT_ONLY = 3; + + // Denotes a field as input only. + // This indicates that the field is provided in requests, and the + // corresponding field is not included in output. + INPUT_ONLY = 4; + + // Denotes a field as immutable. + // This indicates that the field may be set once in a request to create a + // resource, but may not be changed thereafter. + IMMUTABLE = 5; + + // Denotes that a (repeated) field is an unordered list. + // This indicates that the service may provide the elements of the list + // in any arbitrary order, rather than the order the user originally + // provided. Additionally, the list's order may or may not be stable. + UNORDERED_LIST = 6; + + // Denotes that this field returns a non-empty default value if not set. + // This indicates that if the user provides the empty value in a request, + // a non-empty value will be returned. The user will not be aware of what + // non-empty value to expect. + NON_EMPTY_DEFAULT = 7; + + // Denotes that the field in a resource (a message annotated with + // google.api.resource) is used in the resource name to uniquely identify the + // resource. For AIP-compliant APIs, this should only be applied to the + // `name` field on the resource. + // + // This behavior should not be applied to references to other resources within + // the message. + // + // The identifier field of resources often have different field behavior + // depending on the request it is embedded in (e.g. for Create methods name + // is optional and unused, while for Update methods it is required). Instead + // of method-specific annotations, only `IDENTIFIER` is required. + IDENTIFIER = 8; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/api/http.proto b/node_modules/@google-cloud/firestore/build/protos/google/api/http.proto new file mode 100644 index 0000000..e327037 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/api/http.proto @@ -0,0 +1,371 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "HttpProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Defines the HTTP configuration for an API service. It contains a list of +// [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method +// to one or more HTTP REST API methods. +message Http { + // A list of HTTP configuration rules that apply to individual API methods. + // + // **NOTE:** All service configuration rules follow "last one wins" order. + repeated HttpRule rules = 1; + + // When set to true, URL path parameters will be fully URI-decoded except in + // cases of single segment matches in reserved expansion, where "%2F" will be + // left encoded. + // + // The default behavior is to not decode RFC 6570 reserved characters in multi + // segment matches. + bool fully_decode_reserved_expansion = 2; +} + +// gRPC Transcoding +// +// gRPC Transcoding is a feature for mapping between a gRPC method and one or +// more HTTP REST endpoints. It allows developers to build a single API service +// that supports both gRPC APIs and REST APIs. Many systems, including [Google +// APIs](https://github.com/googleapis/googleapis), +// [Cloud Endpoints](https://cloud.google.com/endpoints), [gRPC +// Gateway](https://github.com/grpc-ecosystem/grpc-gateway), +// and [Envoy](https://github.com/envoyproxy/envoy) proxy support this feature +// and use it for large scale production services. +// +// `HttpRule` defines the schema of the gRPC/REST mapping. The mapping specifies +// how different portions of the gRPC request message are mapped to the URL +// path, URL query parameters, and HTTP request body. It also controls how the +// gRPC response message is mapped to the HTTP response body. `HttpRule` is +// typically specified as an `google.api.http` annotation on the gRPC method. +// +// Each mapping specifies a URL path template and an HTTP method. The path +// template may refer to one or more fields in the gRPC request message, as long +// as each field is a non-repeated field with a primitive (non-message) type. +// The path template controls how fields of the request message are mapped to +// the URL path. +// +// Example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get: "/v1/{name=messages/*}" +// }; +// } +// } +// message GetMessageRequest { +// string name = 1; // Mapped to URL path. +// } +// message Message { +// string text = 1; // The resource content. +// } +// +// This enables an HTTP REST to gRPC mapping as below: +// +// - HTTP: `GET /v1/messages/123456` +// - gRPC: `GetMessage(name: "messages/123456")` +// +// Any fields in the request message which are not bound by the path template +// automatically become HTTP query parameters if there is no HTTP request body. +// For example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get:"/v1/messages/{message_id}" +// }; +// } +// } +// message GetMessageRequest { +// message SubMessage { +// string subfield = 1; +// } +// string message_id = 1; // Mapped to URL path. +// int64 revision = 2; // Mapped to URL query parameter `revision`. +// SubMessage sub = 3; // Mapped to URL query parameter `sub.subfield`. +// } +// +// This enables a HTTP JSON to RPC mapping as below: +// +// - HTTP: `GET /v1/messages/123456?revision=2&sub.subfield=foo` +// - gRPC: `GetMessage(message_id: "123456" revision: 2 sub: +// SubMessage(subfield: "foo"))` +// +// Note that fields which are mapped to URL query parameters must have a +// primitive type or a repeated primitive type or a non-repeated message type. +// In the case of a repeated type, the parameter can be repeated in the URL +// as `...?param=A¶m=B`. In the case of a message type, each field of the +// message is mapped to a separate parameter, such as +// `...?foo.a=A&foo.b=B&foo.c=C`. +// +// For HTTP methods that allow a request body, the `body` field +// specifies the mapping. Consider a REST update method on the +// message resource collection: +// +// service Messaging { +// rpc UpdateMessage(UpdateMessageRequest) returns (Message) { +// option (google.api.http) = { +// patch: "/v1/messages/{message_id}" +// body: "message" +// }; +// } +// } +// message UpdateMessageRequest { +// string message_id = 1; // mapped to the URL +// Message message = 2; // mapped to the body +// } +// +// The following HTTP JSON to RPC mapping is enabled, where the +// representation of the JSON in the request body is determined by +// protos JSON encoding: +// +// - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }` +// - gRPC: `UpdateMessage(message_id: "123456" message { text: "Hi!" })` +// +// The special name `*` can be used in the body mapping to define that +// every field not bound by the path template should be mapped to the +// request body. This enables the following alternative definition of +// the update method: +// +// service Messaging { +// rpc UpdateMessage(Message) returns (Message) { +// option (google.api.http) = { +// patch: "/v1/messages/{message_id}" +// body: "*" +// }; +// } +// } +// message Message { +// string message_id = 1; +// string text = 2; +// } +// +// +// The following HTTP JSON to RPC mapping is enabled: +// +// - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }` +// - gRPC: `UpdateMessage(message_id: "123456" text: "Hi!")` +// +// Note that when using `*` in the body mapping, it is not possible to +// have HTTP parameters, as all fields not bound by the path end in +// the body. This makes this option more rarely used in practice when +// defining REST APIs. The common usage of `*` is in custom methods +// which don't use the URL at all for transferring data. +// +// It is possible to define multiple HTTP methods for one RPC by using +// the `additional_bindings` option. Example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get: "/v1/messages/{message_id}" +// additional_bindings { +// get: "/v1/users/{user_id}/messages/{message_id}" +// } +// }; +// } +// } +// message GetMessageRequest { +// string message_id = 1; +// string user_id = 2; +// } +// +// This enables the following two alternative HTTP JSON to RPC mappings: +// +// - HTTP: `GET /v1/messages/123456` +// - gRPC: `GetMessage(message_id: "123456")` +// +// - HTTP: `GET /v1/users/me/messages/123456` +// - gRPC: `GetMessage(user_id: "me" message_id: "123456")` +// +// Rules for HTTP mapping +// +// 1. Leaf request fields (recursive expansion nested messages in the request +// message) are classified into three categories: +// - Fields referred by the path template. They are passed via the URL path. +// - Fields referred by the [HttpRule.body][google.api.HttpRule.body]. They +// are passed via the HTTP +// request body. +// - All other fields are passed via the URL query parameters, and the +// parameter name is the field path in the request message. A repeated +// field can be represented as multiple query parameters under the same +// name. +// 2. If [HttpRule.body][google.api.HttpRule.body] is "*", there is no URL +// query parameter, all fields +// are passed via URL path and HTTP request body. +// 3. If [HttpRule.body][google.api.HttpRule.body] is omitted, there is no HTTP +// request body, all +// fields are passed via URL path and URL query parameters. +// +// Path template syntax +// +// Template = "/" Segments [ Verb ] ; +// Segments = Segment { "/" Segment } ; +// Segment = "*" | "**" | LITERAL | Variable ; +// Variable = "{" FieldPath [ "=" Segments ] "}" ; +// FieldPath = IDENT { "." IDENT } ; +// Verb = ":" LITERAL ; +// +// The syntax `*` matches a single URL path segment. The syntax `**` matches +// zero or more URL path segments, which must be the last part of the URL path +// except the `Verb`. +// +// The syntax `Variable` matches part of the URL path as specified by its +// template. A variable template must not contain other variables. If a variable +// matches a single path segment, its template may be omitted, e.g. `{var}` +// is equivalent to `{var=*}`. +// +// The syntax `LITERAL` matches literal text in the URL path. If the `LITERAL` +// contains any reserved character, such characters should be percent-encoded +// before the matching. +// +// If a variable contains exactly one path segment, such as `"{var}"` or +// `"{var=*}"`, when such a variable is expanded into a URL path on the client +// side, all characters except `[-_.~0-9a-zA-Z]` are percent-encoded. The +// server side does the reverse decoding. Such variables show up in the +// [Discovery +// Document](https://developers.google.com/discovery/v1/reference/apis) as +// `{var}`. +// +// If a variable contains multiple path segments, such as `"{var=foo/*}"` +// or `"{var=**}"`, when such a variable is expanded into a URL path on the +// client side, all characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. +// The server side does the reverse decoding, except "%2F" and "%2f" are left +// unchanged. Such variables show up in the +// [Discovery +// Document](https://developers.google.com/discovery/v1/reference/apis) as +// `{+var}`. +// +// Using gRPC API Service Configuration +// +// gRPC API Service Configuration (service config) is a configuration language +// for configuring a gRPC service to become a user-facing product. The +// service config is simply the YAML representation of the `google.api.Service` +// proto message. +// +// As an alternative to annotating your proto file, you can configure gRPC +// transcoding in your service config YAML files. You do this by specifying a +// `HttpRule` that maps the gRPC method to a REST endpoint, achieving the same +// effect as the proto annotation. This can be particularly useful if you +// have a proto that is reused in multiple services. Note that any transcoding +// specified in the service config will override any matching transcoding +// configuration in the proto. +// +// The following example selects a gRPC method and applies an `HttpRule` to it: +// +// http: +// rules: +// - selector: example.v1.Messaging.GetMessage +// get: /v1/messages/{message_id}/{sub.subfield} +// +// Special notes +// +// When gRPC Transcoding is used to map a gRPC to JSON REST endpoints, the +// proto to JSON conversion must follow the [proto3 +// specification](https://developers.google.com/protocol-buffers/docs/proto3#json). +// +// While the single segment variable follows the semantics of +// [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 Simple String +// Expansion, the multi segment variable **does not** follow RFC 6570 Section +// 3.2.3 Reserved Expansion. The reason is that the Reserved Expansion +// does not expand special characters like `?` and `#`, which would lead +// to invalid URLs. As the result, gRPC Transcoding uses a custom encoding +// for multi segment variables. +// +// The path variables **must not** refer to any repeated or mapped field, +// because client libraries are not capable of handling such variable expansion. +// +// The path variables **must not** capture the leading "/" character. The reason +// is that the most common use case "{var}" does not capture the leading "/" +// character. For consistency, all path variables must share the same behavior. +// +// Repeated message fields must not be mapped to URL query parameters, because +// no client library can support such complicated mapping. +// +// If an API needs to use a JSON array for request or response body, it can map +// the request or response body to a repeated field. However, some gRPC +// Transcoding implementations may not support this feature. +message HttpRule { + // Selects a method to which this rule applies. + // + // Refer to [selector][google.api.DocumentationRule.selector] for syntax + // details. + string selector = 1; + + // Determines the URL pattern is matched by this rules. This pattern can be + // used with any of the {get|put|post|delete|patch} methods. A custom method + // can be defined using the 'custom' field. + oneof pattern { + // Maps to HTTP GET. Used for listing and getting information about + // resources. + string get = 2; + + // Maps to HTTP PUT. Used for replacing a resource. + string put = 3; + + // Maps to HTTP POST. Used for creating a resource or performing an action. + string post = 4; + + // Maps to HTTP DELETE. Used for deleting a resource. + string delete = 5; + + // Maps to HTTP PATCH. Used for updating a resource. + string patch = 6; + + // The custom pattern is used for specifying an HTTP method that is not + // included in the `pattern` field, such as HEAD, or "*" to leave the + // HTTP method unspecified for this rule. The wild-card rule is useful + // for services that provide content to Web (HTML) clients. + CustomHttpPattern custom = 8; + } + + // The name of the request field whose value is mapped to the HTTP request + // body, or `*` for mapping all request fields not captured by the path + // pattern to the HTTP body, or omitted for not having any HTTP request body. + // + // NOTE: the referred field must be present at the top-level of the request + // message type. + string body = 7; + + // Optional. The name of the response field whose value is mapped to the HTTP + // response body. When omitted, the entire response message will be used + // as the HTTP response body. + // + // NOTE: The referred field must be present at the top-level of the response + // message type. + string response_body = 12; + + // Additional HTTP bindings for the selector. Nested bindings must + // not contain an `additional_bindings` field themselves (that is, + // the nesting may only be one level deep). + repeated HttpRule additional_bindings = 11; +} + +// A custom pattern is used for defining custom HTTP verb. +message CustomHttpPattern { + // The name of this custom HTTP verb. + string kind = 1; + + // The path matched by this custom verb. + string path = 2; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/api/launch_stage.proto b/node_modules/@google-cloud/firestore/build/protos/google/api/launch_stage.proto new file mode 100644 index 0000000..9863fc2 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/api/launch_stage.proto @@ -0,0 +1,72 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option go_package = "google.golang.org/genproto/googleapis/api;api"; +option java_multiple_files = true; +option java_outer_classname = "LaunchStageProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// The launch stage as defined by [Google Cloud Platform +// Launch Stages](https://cloud.google.com/terms/launch-stages). +enum LaunchStage { + // Do not use this default value. + LAUNCH_STAGE_UNSPECIFIED = 0; + + // The feature is not yet implemented. Users can not use it. + UNIMPLEMENTED = 6; + + // Prelaunch features are hidden from users and are only visible internally. + PRELAUNCH = 7; + + // Early Access features are limited to a closed group of testers. To use + // these features, you must sign up in advance and sign a Trusted Tester + // agreement (which includes confidentiality provisions). These features may + // be unstable, changed in backward-incompatible ways, and are not + // guaranteed to be released. + EARLY_ACCESS = 1; + + // Alpha is a limited availability test for releases before they are cleared + // for widespread use. By Alpha, all significant design issues are resolved + // and we are in the process of verifying functionality. Alpha customers + // need to apply for access, agree to applicable terms, and have their + // projects allowlisted. Alpha releases don't have to be feature complete, + // no SLAs are provided, and there are no technical support obligations, but + // they will be far enough along that customers can actually use them in + // test environments or for limited-use tests -- just like they would in + // normal production cases. + ALPHA = 2; + + // Beta is the point at which we are ready to open a release for any + // customer to use. There are no SLA or technical support obligations in a + // Beta release. Products will be complete from a feature perspective, but + // may have some open outstanding issues. Beta releases are suitable for + // limited production use cases. + BETA = 3; + + // GA features are open to all developers and are considered stable and + // fully qualified for production use. + GA = 4; + + // Deprecated features are scheduled to be shut down and removed. For more + // information, see the "Deprecation Policy" section of our [Terms of + // Service](https://cloud.google.com/terms/) + // and the [Google Cloud Platform Subject to the Deprecation + // Policy](https://cloud.google.com/terms/deprecation) documentation. + DEPRECATED = 5; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/api/resource.proto b/node_modules/@google-cloud/firestore/build/protos/google/api/resource.proto new file mode 100644 index 0000000..3762af8 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/api/resource.proto @@ -0,0 +1,243 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/protobuf/descriptor.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "ResourceProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +extend google.protobuf.FieldOptions { + // An annotation that describes a resource reference, see + // [ResourceReference][]. + google.api.ResourceReference resource_reference = 1055; +} + +extend google.protobuf.FileOptions { + // An annotation that describes a resource definition without a corresponding + // message; see [ResourceDescriptor][]. + repeated google.api.ResourceDescriptor resource_definition = 1053; +} + +extend google.protobuf.MessageOptions { + // An annotation that describes a resource definition, see + // [ResourceDescriptor][]. + google.api.ResourceDescriptor resource = 1053; +} + +// A simple descriptor of a resource type. +// +// ResourceDescriptor annotates a resource message (either by means of a +// protobuf annotation or use in the service config), and associates the +// resource's schema, the resource type, and the pattern of the resource name. +// +// Example: +// +// message Topic { +// // Indicates this message defines a resource schema. +// // Declares the resource type in the format of {service}/{kind}. +// // For Kubernetes resources, the format is {api group}/{kind}. +// option (google.api.resource) = { +// type: "pubsub.googleapis.com/Topic" +// pattern: "projects/{project}/topics/{topic}" +// }; +// } +// +// The ResourceDescriptor Yaml config will look like: +// +// resources: +// - type: "pubsub.googleapis.com/Topic" +// pattern: "projects/{project}/topics/{topic}" +// +// Sometimes, resources have multiple patterns, typically because they can +// live under multiple parents. +// +// Example: +// +// message LogEntry { +// option (google.api.resource) = { +// type: "logging.googleapis.com/LogEntry" +// pattern: "projects/{project}/logs/{log}" +// pattern: "folders/{folder}/logs/{log}" +// pattern: "organizations/{organization}/logs/{log}" +// pattern: "billingAccounts/{billing_account}/logs/{log}" +// }; +// } +// +// The ResourceDescriptor Yaml config will look like: +// +// resources: +// - type: 'logging.googleapis.com/LogEntry' +// pattern: "projects/{project}/logs/{log}" +// pattern: "folders/{folder}/logs/{log}" +// pattern: "organizations/{organization}/logs/{log}" +// pattern: "billingAccounts/{billing_account}/logs/{log}" +message ResourceDescriptor { + // A description of the historical or future-looking state of the + // resource pattern. + enum History { + // The "unset" value. + HISTORY_UNSPECIFIED = 0; + + // The resource originally had one pattern and launched as such, and + // additional patterns were added later. + ORIGINALLY_SINGLE_PATTERN = 1; + + // The resource has one pattern, but the API owner expects to add more + // later. (This is the inverse of ORIGINALLY_SINGLE_PATTERN, and prevents + // that from being necessary once there are multiple patterns.) + FUTURE_MULTI_PATTERN = 2; + } + + // A flag representing a specific style that a resource claims to conform to. + enum Style { + // The unspecified value. Do not use. + STYLE_UNSPECIFIED = 0; + + // This resource is intended to be "declarative-friendly". + // + // Declarative-friendly resources must be more strictly consistent, and + // setting this to true communicates to tools that this resource should + // adhere to declarative-friendly expectations. + // + // Note: This is used by the API linter (linter.aip.dev) to enable + // additional checks. + DECLARATIVE_FRIENDLY = 1; + } + + // The resource type. It must be in the format of + // {service_name}/{resource_type_kind}. The `resource_type_kind` must be + // singular and must not include version numbers. + // + // Example: `storage.googleapis.com/Bucket` + // + // The value of the resource_type_kind must follow the regular expression + // /[A-Za-z][a-zA-Z0-9]+/. It should start with an upper case character and + // should use PascalCase (UpperCamelCase). The maximum number of + // characters allowed for the `resource_type_kind` is 100. + string type = 1; + + // Optional. The relative resource name pattern associated with this resource + // type. The DNS prefix of the full resource name shouldn't be specified here. + // + // The path pattern must follow the syntax, which aligns with HTTP binding + // syntax: + // + // Template = Segment { "/" Segment } ; + // Segment = LITERAL | Variable ; + // Variable = "{" LITERAL "}" ; + // + // Examples: + // + // - "projects/{project}/topics/{topic}" + // - "projects/{project}/knowledgeBases/{knowledge_base}" + // + // The components in braces correspond to the IDs for each resource in the + // hierarchy. It is expected that, if multiple patterns are provided, + // the same component name (e.g. "project") refers to IDs of the same + // type of resource. + repeated string pattern = 2; + + // Optional. The field on the resource that designates the resource name + // field. If omitted, this is assumed to be "name". + string name_field = 3; + + // Optional. The historical or future-looking state of the resource pattern. + // + // Example: + // + // // The InspectTemplate message originally only supported resource + // // names with organization, and project was added later. + // message InspectTemplate { + // option (google.api.resource) = { + // type: "dlp.googleapis.com/InspectTemplate" + // pattern: + // "organizations/{organization}/inspectTemplates/{inspect_template}" + // pattern: "projects/{project}/inspectTemplates/{inspect_template}" + // history: ORIGINALLY_SINGLE_PATTERN + // }; + // } + History history = 4; + + // The plural name used in the resource name and permission names, such as + // 'projects' for the resource name of 'projects/{project}' and the permission + // name of 'cloudresourcemanager.googleapis.com/projects.get'. One exception + // to this is for Nested Collections that have stuttering names, as defined + // in [AIP-122](https://google.aip.dev/122#nested-collections), where the + // collection ID in the resource name pattern does not necessarily directly + // match the `plural` value. + // + // It is the same concept of the `plural` field in k8s CRD spec + // https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/ + // + // Note: The plural form is required even for singleton resources. See + // https://aip.dev/156 + string plural = 5; + + // The same concept of the `singular` field in k8s CRD spec + // https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/ + // Such as "project" for the `resourcemanager.googleapis.com/Project` type. + string singular = 6; + + // Style flag(s) for this resource. + // These indicate that a resource is expected to conform to a given + // style. See the specific style flags for additional information. + repeated Style style = 10; +} + +// Defines a proto annotation that describes a string field that refers to +// an API resource. +message ResourceReference { + // The resource type that the annotated field references. + // + // Example: + // + // message Subscription { + // string topic = 2 [(google.api.resource_reference) = { + // type: "pubsub.googleapis.com/Topic" + // }]; + // } + // + // Occasionally, a field may reference an arbitrary resource. In this case, + // APIs use the special value * in their resource reference. + // + // Example: + // + // message GetIamPolicyRequest { + // string resource = 2 [(google.api.resource_reference) = { + // type: "*" + // }]; + // } + string type = 1; + + // The resource type of a child collection that the annotated field + // references. This is useful for annotating the `parent` field that + // doesn't have a fixed resource type. + // + // Example: + // + // message ListLogEntriesRequest { + // string parent = 1 [(google.api.resource_reference) = { + // child_type: "logging.googleapis.com/LogEntry" + // }; + // } + string child_type = 2; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/backup.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/backup.proto new file mode 100644 index 0000000..45f3adc --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/backup.proto @@ -0,0 +1,107 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.admin.v1; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.Admin.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb"; +option java_multiple_files = true; +option java_outer_classname = "BackupProto"; +option java_package = "com.google.firestore.admin.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\Admin\\V1"; +option ruby_package = "Google::Cloud::Firestore::Admin::V1"; + +// A Backup of a Cloud Firestore Database. +// +// The backup contains all documents and index configurations for the given +// database at a specific point in time. +message Backup { + option (google.api.resource) = { + type: "firestore.googleapis.com/Backup" + pattern: "projects/{project}/locations/{location}/backups/{backup}" + }; + + // Backup specific statistics. + message Stats { + // Output only. Summation of the size of all documents and index entries in + // the backup, measured in bytes. + int64 size_bytes = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The total number of documents contained in the backup. + int64 document_count = 2 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The total number of index entries contained in the backup. + int64 index_count = 3 [(google.api.field_behavior) = OUTPUT_ONLY]; + } + + // Indicate the current state of the backup. + enum State { + // The state is unspecified. + STATE_UNSPECIFIED = 0; + + // The pending backup is still being created. Operations on the + // backup will be rejected in this state. + CREATING = 1; + + // The backup is complete and ready to use. + READY = 2; + + // The backup is not available at this moment. + NOT_AVAILABLE = 3; + } + + // Output only. The unique resource name of the Backup. + // + // Format is `projects/{project}/locations/{location}/backups/{backup}`. + string name = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Name of the Firestore database that the backup is from. + // + // Format is `projects/{project}/databases/{database}`. + string database = 2 [ + (google.api.field_behavior) = OUTPUT_ONLY, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + } + ]; + + // Output only. The system-generated UUID4 for the Firestore database that the + // backup is from. + string database_uid = 7 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The backup contains an externally consistent copy of the + // database at this time. + google.protobuf.Timestamp snapshot_time = 3 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The timestamp at which this backup expires. + google.protobuf.Timestamp expire_time = 4 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Statistics about the backup. + // + // This data only becomes available after the backup is fully materialized to + // secondary storage. This field will be empty till then. + Stats stats = 6 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The current state of the backup. + State state = 8 [(google.api.field_behavior) = OUTPUT_ONLY]; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/database.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/database.proto new file mode 100644 index 0000000..848e2ec --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/database.proto @@ -0,0 +1,321 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.admin.v1; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.Admin.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb"; +option java_multiple_files = true; +option java_outer_classname = "DatabaseProto"; +option java_package = "com.google.firestore.admin.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\Admin\\V1"; +option ruby_package = "Google::Cloud::Firestore::Admin::V1"; +option (google.api.resource_definition) = { + type: "firestore.googleapis.com/Operation" + pattern: "projects/{project}/databases/{database}/operations/{operation}" +}; + +// A Cloud Firestore Database. +message Database { + option (google.api.resource) = { + type: "firestore.googleapis.com/Database" + pattern: "projects/{project}/databases/{database}" + style: DECLARATIVE_FRIENDLY + }; + + // The type of the database. + // See https://cloud.google.com/datastore/docs/firestore-or-datastore for + // information about how to choose. + // + // Mode changes are only allowed if the database is empty. + enum DatabaseType { + // Not used. + DATABASE_TYPE_UNSPECIFIED = 0; + + // Firestore Native Mode + FIRESTORE_NATIVE = 1; + + // Firestore in Datastore Mode. + DATASTORE_MODE = 2; + } + + // The type of concurrency control mode for transactions. + enum ConcurrencyMode { + // Not used. + CONCURRENCY_MODE_UNSPECIFIED = 0; + + // Use optimistic concurrency control by default. This mode is available + // for Cloud Firestore databases. + OPTIMISTIC = 1; + + // Use pessimistic concurrency control by default. This mode is available + // for Cloud Firestore databases. + // + // This is the default setting for Cloud Firestore. + PESSIMISTIC = 2; + + // Use optimistic concurrency control with entity groups by default. + // + // This is the only available mode for Cloud Datastore. + // + // This mode is also available for Cloud Firestore with Datastore Mode but + // is not recommended. + OPTIMISTIC_WITH_ENTITY_GROUPS = 3; + } + + // Point In Time Recovery feature enablement. + enum PointInTimeRecoveryEnablement { + // Not used. + POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED = 0; + + // Reads are supported on selected versions of the data from within the past + // 7 days: + // + // * Reads against any timestamp within the past hour + // * Reads against 1-minute snapshots beyond 1 hour and within 7 days + // + // `version_retention_period` and `earliest_version_time` can be + // used to determine the supported versions. + POINT_IN_TIME_RECOVERY_ENABLED = 1; + + // Reads are supported on any version of the data from within the past 1 + // hour. + POINT_IN_TIME_RECOVERY_DISABLED = 2; + } + + // The type of App Engine integration mode. + enum AppEngineIntegrationMode { + // Not used. + APP_ENGINE_INTEGRATION_MODE_UNSPECIFIED = 0; + + // If an App Engine application exists in the same region as this database, + // App Engine configuration will impact this database. This includes + // disabling of the application & database, as well as disabling writes to + // the database. + ENABLED = 1; + + // App Engine has no effect on the ability of this database to serve + // requests. + // + // This is the default setting for databases created with the Firestore API. + DISABLED = 2; + } + + // The delete protection state of the database. + enum DeleteProtectionState { + // The default value. Delete protection type is not specified + DELETE_PROTECTION_STATE_UNSPECIFIED = 0; + + // Delete protection is disabled + DELETE_PROTECTION_DISABLED = 1; + + // Delete protection is enabled + DELETE_PROTECTION_ENABLED = 2; + } + + // The CMEK (Customer Managed Encryption Key) configuration for a Firestore + // database. If not present, the database is secured by the default Google + // encryption key. + message CmekConfig { + // Required. Only keys in the same location as this database are allowed to + // be used for encryption. + // + // For Firestore's nam5 multi-region, this corresponds to Cloud KMS + // multi-region us. For Firestore's eur3 multi-region, this corresponds to + // Cloud KMS multi-region europe. See + // https://cloud.google.com/kms/docs/locations. + // + // The expected format is + // `projects/{project_id}/locations/{kms_location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}`. + string kms_key_name = 1 [(google.api.field_behavior) = REQUIRED]; + + // Output only. Currently in-use [KMS key + // versions](https://cloud.google.com/kms/docs/resource-hierarchy#key_versions). + // During [key rotation](https://cloud.google.com/kms/docs/key-rotation), + // there can be multiple in-use key versions. + // + // The expected format is + // `projects/{project_id}/locations/{kms_location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{key_version}`. + repeated string active_key_version = 2 + [(google.api.field_behavior) = OUTPUT_ONLY]; + } + + // Information about the provenance of this database. + message SourceInfo { + // Information about a backup that was used to restore a database. + message BackupSource { + // The resource name of the backup that was used to restore this + // database. Format: + // `projects/{project}/locations/{location}/backups/{backup}`. + string backup = 1 [(google.api.resource_reference) = { + type: "firestore.googleapis.com/Backup" + }]; + } + + // The source from which this database is derived. + oneof source { + // If set, this database was restored from the specified backup (or a + // snapshot thereof). + BackupSource backup = 1; + } + + // The associated long-running operation. This field may not be set after + // the operation has completed. Format: + // `projects/{project}/databases/{database}/operations/{operation}`. + string operation = 3 [(google.api.resource_reference) = { + type: "firestore.googleapis.com/Operation" + }]; + } + + // Encryption configuration for a new database being created from another + // source. + // + // The source could be a [Backup][google.firestore.admin.v1.Backup] . + message EncryptionConfig { + // The configuration options for using Google default encryption. + message GoogleDefaultEncryptionOptions {} + + // The configuration options for using the same encryption method as the + // source. + message SourceEncryptionOptions {} + + // The configuration options for using CMEK (Customer Managed Encryption + // Key) encryption. + message CustomerManagedEncryptionOptions { + // Required. Only keys in the same location as the database are allowed to + // be used for encryption. + // + // For Firestore's nam5 multi-region, this corresponds to Cloud KMS + // multi-region us. For Firestore's eur3 multi-region, this corresponds to + // Cloud KMS multi-region europe. See + // https://cloud.google.com/kms/docs/locations. + // + // The expected format is + // `projects/{project_id}/locations/{kms_location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}`. + string kms_key_name = 1 [(google.api.field_behavior) = REQUIRED]; + } + + // The method for encrypting the database. + oneof encryption_type { + // Use Google default encryption. + GoogleDefaultEncryptionOptions google_default_encryption = 1; + + // The database will use the same encryption configuration as the source. + SourceEncryptionOptions use_source_encryption = 2; + + // Use Customer Managed Encryption Keys (CMEK) for encryption. + CustomerManagedEncryptionOptions customer_managed_encryption = 3; + } + } + + // The resource name of the Database. + // Format: `projects/{project}/databases/{database}` + string name = 1; + + // Output only. The system-generated UUID4 for this Database. + string uid = 3 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The timestamp at which this database was created. Databases + // created before 2016 do not populate create_time. + google.protobuf.Timestamp create_time = 5 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The timestamp at which this database was most recently + // updated. Note this only includes updates to the database resource and not + // data contained by the database. + google.protobuf.Timestamp update_time = 6 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The timestamp at which this database was deleted. Only set if + // the database has been deleted. + google.protobuf.Timestamp delete_time = 7 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // The location of the database. Available locations are listed at + // https://cloud.google.com/firestore/docs/locations. + string location_id = 9; + + // The type of the database. + // See https://cloud.google.com/datastore/docs/firestore-or-datastore for + // information about how to choose. + DatabaseType type = 10; + + // The concurrency control mode to use for this database. + ConcurrencyMode concurrency_mode = 15; + + // Output only. The period during which past versions of data are retained in + // the database. + // + // Any [read][google.firestore.v1.GetDocumentRequest.read_time] + // or [query][google.firestore.v1.ListDocumentsRequest.read_time] can specify + // a `read_time` within this window, and will read the state of the database + // at that time. + // + // If the PITR feature is enabled, the retention period is 7 days. Otherwise, + // the retention period is 1 hour. + google.protobuf.Duration version_retention_period = 17 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The earliest timestamp at which older versions of the data can + // be read from the database. See [version_retention_period] above; this field + // is populated with `now - version_retention_period`. + // + // This value is continuously updated, and becomes stale the moment it is + // queried. If you are using this value to recover data, make sure to account + // for the time from the moment when the value is queried to the moment when + // you initiate the recovery. + google.protobuf.Timestamp earliest_version_time = 18 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Whether to enable the PITR feature on this database. + PointInTimeRecoveryEnablement point_in_time_recovery_enablement = 21; + + // The App Engine integration mode to use for this database. + AppEngineIntegrationMode app_engine_integration_mode = 19; + + // Output only. The key_prefix for this database. This key_prefix is used, in + // combination with the project ID ("~") to construct + // the application ID that is returned from the Cloud Datastore APIs in Google + // App Engine first generation runtimes. + // + // This value may be empty in which case the appid to use for URL-encoded keys + // is the project_id (eg: foo instead of v~foo). + string key_prefix = 20 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // State of delete protection for the database. + DeleteProtectionState delete_protection_state = 22; + + // Optional. Presence indicates CMEK is enabled for this database. + CmekConfig cmek_config = 23 [(google.api.field_behavior) = OPTIONAL]; + + // Output only. The database resource's prior database ID. This field is only + // populated for deleted databases. + string previous_id = 25 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Information about the provenance of this database. + SourceInfo source_info = 26 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // This checksum is computed by the server based on the value of other + // fields, and may be sent on update and delete requests to ensure the + // client has an up-to-date value before proceeding. + string etag = 99; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/field.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/field.proto new file mode 100644 index 0000000..e187b45 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/field.proto @@ -0,0 +1,137 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.admin.v1; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/firestore/admin/v1/index.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.Admin.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb"; +option java_multiple_files = true; +option java_outer_classname = "FieldProto"; +option java_package = "com.google.firestore.admin.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\Admin\\V1"; +option ruby_package = "Google::Cloud::Firestore::Admin::V1"; + +// Represents a single field in the database. +// +// Fields are grouped by their "Collection Group", which represent all +// collections in the database with the same ID. +message Field { + option (google.api.resource) = { + type: "firestore.googleapis.com/Field" + pattern: "projects/{project}/databases/{database}/collectionGroups/{collection}/fields/{field}" + }; + + // The index configuration for this field. + message IndexConfig { + // The indexes supported for this field. + repeated Index indexes = 1; + + // Output only. When true, the `Field`'s index configuration is set from the + // configuration specified by the `ancestor_field`. + // When false, the `Field`'s index configuration is defined explicitly. + bool uses_ancestor_config = 2; + + // Output only. Specifies the resource name of the `Field` from which this + // field's index configuration is set (when `uses_ancestor_config` is true), + // or from which it *would* be set if this field had no index configuration + // (when `uses_ancestor_config` is false). + string ancestor_field = 3; + + // Output only + // When true, the `Field`'s index configuration is in the process of being + // reverted. Once complete, the index config will transition to the same + // state as the field specified by `ancestor_field`, at which point + // `uses_ancestor_config` will be `true` and `reverting` will be `false`. + bool reverting = 4; + } + + // The TTL (time-to-live) configuration for documents that have this `Field` + // set. + // + // Storing a timestamp value into a TTL-enabled field will be treated as + // the document's absolute expiration time. Timestamp values in the past + // indicate that the document is eligible for immediate expiration. Using any + // other data type or leaving the field absent will disable expiration for the + // individual document. + message TtlConfig { + // The state of applying the TTL configuration to all documents. + enum State { + // The state is unspecified or unknown. + STATE_UNSPECIFIED = 0; + + // The TTL is being applied. There is an active long-running operation to + // track the change. Newly written documents will have TTLs applied as + // requested. Requested TTLs on existing documents are still being + // processed. When TTLs on all existing documents have been processed, the + // state will move to 'ACTIVE'. + CREATING = 1; + + // The TTL is active for all documents. + ACTIVE = 2; + + // The TTL configuration could not be enabled for all existing documents. + // Newly written documents will continue to have their TTL applied. + // The LRO returned when last attempting to enable TTL for this `Field` + // has failed, and may have more details. + NEEDS_REPAIR = 3; + } + + // Output only. The state of the TTL configuration. + State state = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + } + + // Required. A field name of the form: + // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_path}` + // + // A field path can be a simple field name, e.g. `address` or a path to fields + // within `map_value` , e.g. `address.city`, + // or a special field path. The only valid special field is `*`, which + // represents any field. + // + // Field paths can be quoted using `` ` `` (backtick). The only character that + // must be escaped within a quoted field path is the backtick character + // itself, escaped using a backslash. Special characters in field paths that + // must be quoted include: `*`, `.`, + // `` ` `` (backtick), `[`, `]`, as well as any ascii symbolic characters. + // + // Examples: + // `` `address.city` `` represents a field named `address.city`, not the map + // key `city` in the field `address`. `` `*` `` represents a field named `*`, + // not any field. + // + // A special `Field` contains the default indexing settings for all fields. + // This field's resource name is: + // `projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/*` + // Indexes defined on this `Field` will be applied to all fields which do not + // have their own `Field` index configuration. + string name = 1 [(google.api.field_behavior) = REQUIRED]; + + // The index configuration for this field. If unset, field indexing will + // revert to the configuration defined by the `ancestor_field`. To + // explicitly remove all indexes for this field, specify an index config + // with an empty list of indexes. + IndexConfig index_config = 2; + + // The TTL configuration for this `Field`. + // Setting or unsetting this will enable or disable the TTL for + // documents that have this `Field`. + TtlConfig ttl_config = 3; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/firestore_admin.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/firestore_admin.proto new file mode 100644 index 0000000..84026ce --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/firestore_admin.proto @@ -0,0 +1,958 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.admin.v1; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/firestore/admin/v1/backup.proto"; +import "google/firestore/admin/v1/database.proto"; +import "google/firestore/admin/v1/field.proto"; +import "google/firestore/admin/v1/index.proto"; +import "google/firestore/admin/v1/operation.proto"; +import "google/firestore/admin/v1/schedule.proto"; +import "google/longrunning/operations.proto"; +import "google/protobuf/empty.proto"; +import "google/protobuf/field_mask.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.Admin.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb"; +option java_multiple_files = true; +option java_outer_classname = "FirestoreAdminProto"; +option java_package = "com.google.firestore.admin.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\Admin\\V1"; +option ruby_package = "Google::Cloud::Firestore::Admin::V1"; +option (google.api.resource_definition) = { + type: "firestore.googleapis.com/Location" + pattern: "projects/{project}/locations/{location}" +}; +option (google.api.resource_definition) = { + type: "firestore.googleapis.com/CollectionGroup" + pattern: "projects/{project}/databases/{database}/collectionGroups/{collection}" +}; + +// The Cloud Firestore Admin API. +// +// This API provides several administrative services for Cloud Firestore. +// +// Project, Database, Namespace, Collection, Collection Group, and Document are +// used as defined in the Google Cloud Firestore API. +// +// Operation: An Operation represents work being performed in the background. +// +// The index service manages Cloud Firestore indexes. +// +// Index creation is performed asynchronously. +// An Operation resource is created for each such asynchronous operation. +// The state of the operation (including any errors encountered) +// may be queried via the Operation resource. +// +// The Operations collection provides a record of actions performed for the +// specified Project (including any Operations in progress). Operations are not +// created directly but through calls on other collections or resources. +// +// An Operation that is done may be deleted so that it is no longer listed as +// part of the Operation collection. Operations are garbage collected after +// 30 days. By default, ListOperations will only return in progress and failed +// operations. To list completed operation, issue a ListOperations request with +// the filter `done: true`. +// +// Operations are created by service `FirestoreAdmin`, but are accessed via +// service `google.longrunning.Operations`. +service FirestoreAdmin { + option (google.api.default_host) = "firestore.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/datastore"; + + // Creates a composite index. This returns a + // [google.longrunning.Operation][google.longrunning.Operation] which may be + // used to track the status of the creation. The metadata for the operation + // will be the type + // [IndexOperationMetadata][google.firestore.admin.v1.IndexOperationMetadata]. + rpc CreateIndex(CreateIndexRequest) returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/databases/*/collectionGroups/*}/indexes" + body: "index" + }; + option (google.api.method_signature) = "parent,index"; + option (google.longrunning.operation_info) = { + response_type: "Index" + metadata_type: "IndexOperationMetadata" + }; + } + + // Lists composite indexes. + rpc ListIndexes(ListIndexesRequest) returns (ListIndexesResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/databases/*/collectionGroups/*}/indexes" + }; + option (google.api.method_signature) = "parent"; + } + + // Gets a composite index. + rpc GetIndex(GetIndexRequest) returns (Index) { + option (google.api.http) = { + get: "/v1/{name=projects/*/databases/*/collectionGroups/*/indexes/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Deletes a composite index. + rpc DeleteIndex(DeleteIndexRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=projects/*/databases/*/collectionGroups/*/indexes/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Gets the metadata and configuration for a Field. + rpc GetField(GetFieldRequest) returns (Field) { + option (google.api.http) = { + get: "/v1/{name=projects/*/databases/*/collectionGroups/*/fields/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Updates a field configuration. Currently, field updates apply only to + // single field index configuration. However, calls to + // [FirestoreAdmin.UpdateField][google.firestore.admin.v1.FirestoreAdmin.UpdateField] + // should provide a field mask to avoid changing any configuration that the + // caller isn't aware of. The field mask should be specified as: `{ paths: + // "index_config" }`. + // + // This call returns a + // [google.longrunning.Operation][google.longrunning.Operation] which may be + // used to track the status of the field update. The metadata for the + // operation will be the type + // [FieldOperationMetadata][google.firestore.admin.v1.FieldOperationMetadata]. + // + // To configure the default field settings for the database, use + // the special `Field` with resource name: + // `projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/*`. + rpc UpdateField(UpdateFieldRequest) returns (google.longrunning.Operation) { + option (google.api.http) = { + patch: "/v1/{field.name=projects/*/databases/*/collectionGroups/*/fields/*}" + body: "field" + }; + option (google.api.method_signature) = "field"; + option (google.longrunning.operation_info) = { + response_type: "Field" + metadata_type: "FieldOperationMetadata" + }; + } + + // Lists the field configuration and metadata for this database. + // + // Currently, + // [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields] + // only supports listing fields that have been explicitly overridden. To issue + // this query, call + // [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields] + // with the filter set to `indexConfig.usesAncestorConfig:false` or + // `ttlConfig:*`. + rpc ListFields(ListFieldsRequest) returns (ListFieldsResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/databases/*/collectionGroups/*}/fields" + }; + option (google.api.method_signature) = "parent"; + } + + // Exports a copy of all or a subset of documents from Google Cloud Firestore + // to another storage system, such as Google Cloud Storage. Recent updates to + // documents may not be reflected in the export. The export occurs in the + // background and its progress can be monitored and managed via the + // Operation resource that is created. The output of an export may only be + // used once the associated operation is done. If an export operation is + // cancelled before completion it may leave partial data behind in Google + // Cloud Storage. + // + // For more details on export behavior and output format, refer to: + // https://cloud.google.com/firestore/docs/manage-data/export-import + rpc ExportDocuments(ExportDocumentsRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{name=projects/*/databases/*}:exportDocuments" + body: "*" + }; + option (google.api.method_signature) = "name"; + option (google.longrunning.operation_info) = { + response_type: "ExportDocumentsResponse" + metadata_type: "ExportDocumentsMetadata" + }; + } + + // Imports documents into Google Cloud Firestore. Existing documents with the + // same name are overwritten. The import occurs in the background and its + // progress can be monitored and managed via the Operation resource that is + // created. If an ImportDocuments operation is cancelled, it is possible + // that a subset of the data has already been imported to Cloud Firestore. + rpc ImportDocuments(ImportDocumentsRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{name=projects/*/databases/*}:importDocuments" + body: "*" + }; + option (google.api.method_signature) = "name"; + option (google.longrunning.operation_info) = { + response_type: "google.protobuf.Empty" + metadata_type: "ImportDocumentsMetadata" + }; + } + + // Bulk deletes a subset of documents from Google Cloud Firestore. + // Documents created or updated after the underlying system starts to process + // the request will not be deleted. The bulk delete occurs in the background + // and its progress can be monitored and managed via the Operation resource + // that is created. + // + // For more details on bulk delete behavior, refer to: + // https://cloud.google.com/firestore/docs/manage-data/bulk-delete + rpc BulkDeleteDocuments(BulkDeleteDocumentsRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{name=projects/*/databases/*}:bulkDeleteDocuments" + body: "*" + }; + option (google.api.method_signature) = "name"; + option (google.longrunning.operation_info) = { + response_type: "BulkDeleteDocumentsResponse" + metadata_type: "BulkDeleteDocumentsMetadata" + }; + } + + // Create a database. + rpc CreateDatabase(CreateDatabaseRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{parent=projects/*}/databases" + body: "database" + }; + option (google.api.method_signature) = "parent,database,database_id"; + option (google.longrunning.operation_info) = { + response_type: "Database" + metadata_type: "CreateDatabaseMetadata" + }; + } + + // Gets information about a database. + rpc GetDatabase(GetDatabaseRequest) returns (Database) { + option (google.api.http) = { + get: "/v1/{name=projects/*/databases/*}" + }; + option (google.api.method_signature) = "name"; + } + + // List all the databases in the project. + rpc ListDatabases(ListDatabasesRequest) returns (ListDatabasesResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*}/databases" + }; + option (google.api.method_signature) = "parent"; + } + + // Updates a database. + rpc UpdateDatabase(UpdateDatabaseRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + patch: "/v1/{database.name=projects/*/databases/*}" + body: "database" + }; + option (google.api.method_signature) = "database,update_mask"; + option (google.longrunning.operation_info) = { + response_type: "Database" + metadata_type: "UpdateDatabaseMetadata" + }; + } + + // Deletes a database. + rpc DeleteDatabase(DeleteDatabaseRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + delete: "/v1/{name=projects/*/databases/*}" + }; + option (google.api.method_signature) = "name"; + option (google.longrunning.operation_info) = { + response_type: "Database" + metadata_type: "DeleteDatabaseMetadata" + }; + } + + // Gets information about a backup. + rpc GetBackup(GetBackupRequest) returns (Backup) { + option (google.api.http) = { + get: "/v1/{name=projects/*/locations/*/backups/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Lists all the backups. + rpc ListBackups(ListBackupsRequest) returns (ListBackupsResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/locations/*}/backups" + }; + option (google.api.method_signature) = "parent"; + } + + // Deletes a backup. + rpc DeleteBackup(DeleteBackupRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=projects/*/locations/*/backups/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Creates a new database by restoring from an existing backup. + // + // The new database must be in the same cloud region or multi-region location + // as the existing backup. This behaves similar to + // [FirestoreAdmin.CreateDatabase][google.firestore.admin.v1.FirestoreAdmin.CreateDatabase] + // except instead of creating a new empty database, a new database is created + // with the database type, index configuration, and documents from an existing + // backup. + // + // The [long-running operation][google.longrunning.Operation] can be used to + // track the progress of the restore, with the Operation's + // [metadata][google.longrunning.Operation.metadata] field type being the + // [RestoreDatabaseMetadata][google.firestore.admin.v1.RestoreDatabaseMetadata]. + // The [response][google.longrunning.Operation.response] type is the + // [Database][google.firestore.admin.v1.Database] if the restore was + // successful. The new database is not readable or writeable until the LRO has + // completed. + rpc RestoreDatabase(RestoreDatabaseRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{parent=projects/*}/databases:restore" + body: "*" + }; + option (google.longrunning.operation_info) = { + response_type: "Database" + metadata_type: "RestoreDatabaseMetadata" + }; + } + + // Creates a backup schedule on a database. + // At most two backup schedules can be configured on a database, one daily + // backup schedule and one weekly backup schedule. + rpc CreateBackupSchedule(CreateBackupScheduleRequest) + returns (BackupSchedule) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/databases/*}/backupSchedules" + body: "backup_schedule" + }; + option (google.api.method_signature) = "parent,backup_schedule"; + } + + // Gets information about a backup schedule. + rpc GetBackupSchedule(GetBackupScheduleRequest) returns (BackupSchedule) { + option (google.api.http) = { + get: "/v1/{name=projects/*/databases/*/backupSchedules/*}" + }; + option (google.api.method_signature) = "name"; + } + + // List backup schedules. + rpc ListBackupSchedules(ListBackupSchedulesRequest) + returns (ListBackupSchedulesResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/databases/*}/backupSchedules" + }; + option (google.api.method_signature) = "parent"; + } + + // Updates a backup schedule. + rpc UpdateBackupSchedule(UpdateBackupScheduleRequest) + returns (BackupSchedule) { + option (google.api.http) = { + patch: "/v1/{backup_schedule.name=projects/*/databases/*/backupSchedules/*}" + body: "backup_schedule" + }; + option (google.api.method_signature) = "backup_schedule,update_mask"; + } + + // Deletes a backup schedule. + rpc DeleteBackupSchedule(DeleteBackupScheduleRequest) + returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=projects/*/databases/*/backupSchedules/*}" + }; + option (google.api.method_signature) = "name"; + } +} + +// A request to list the Firestore Databases in all locations for a project. +message ListDatabasesRequest { + // Required. A parent name of the form + // `projects/{project_id}` + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "firestore.googleapis.com/Database" + } + ]; + + // If true, also returns deleted resources. + bool show_deleted = 4; +} + +// The request for +// [FirestoreAdmin.CreateDatabase][google.firestore.admin.v1.FirestoreAdmin.CreateDatabase]. +message CreateDatabaseRequest { + // Required. A parent name of the form + // `projects/{project_id}` + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "firestore.googleapis.com/Database" + } + ]; + + // Required. The Database to create. + Database database = 2 [(google.api.field_behavior) = REQUIRED]; + + // Required. The ID to use for the database, which will become the final + // component of the database's resource name. + // + // This value should be 4-63 characters. Valid characters are /[a-z][0-9]-/ + // with first character a letter and the last a letter or a number. Must not + // be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + // + // "(default)" database ID is also valid. + string database_id = 3 [(google.api.field_behavior) = REQUIRED]; +} + +// Metadata related to the create database operation. +message CreateDatabaseMetadata {} + +// The list of databases for a project. +message ListDatabasesResponse { + // The databases in the project. + repeated Database databases = 1; + + // In the event that data about individual databases cannot be listed they + // will be recorded here. + // + // An example entry might be: projects/some_project/locations/some_location + // This can happen if the Cloud Region that the Database resides in is + // currently unavailable. In this case we can't fetch all the details about + // the database. You may be able to get a more detailed error message + // (or possibly fetch the resource) by sending a 'Get' request for the + // resource or a 'List' request for the specific location. + repeated string unreachable = 3; +} + +// The request for +// [FirestoreAdmin.GetDatabase][google.firestore.admin.v1.FirestoreAdmin.GetDatabase]. +message GetDatabaseRequest { + // Required. A name of the form + // `projects/{project_id}/databases/{database_id}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + } + ]; +} + +// The request for +// [FirestoreAdmin.UpdateDatabase][google.firestore.admin.v1.FirestoreAdmin.UpdateDatabase]. +message UpdateDatabaseRequest { + // Required. The database to update. + Database database = 1 [(google.api.field_behavior) = REQUIRED]; + + // The list of fields to be updated. + google.protobuf.FieldMask update_mask = 2; +} + +// Metadata related to the update database operation. +message UpdateDatabaseMetadata {} + +// The request for +// [FirestoreAdmin.DeleteDatabase][google.firestore.admin.v1.FirestoreAdmin.DeleteDatabase]. +message DeleteDatabaseRequest { + // Required. A name of the form + // `projects/{project_id}/databases/{database_id}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + } + ]; + + // The current etag of the Database. + // If an etag is provided and does not match the current etag of the database, + // deletion will be blocked and a FAILED_PRECONDITION error will be returned. + string etag = 3; +} + +// Metadata related to the delete database operation. +message DeleteDatabaseMetadata {} + +// The request for +// [FirestoreAdmin.CreateBackupSchedule][google.firestore.admin.v1.FirestoreAdmin.CreateBackupSchedule]. +message CreateBackupScheduleRequest { + // Required. The parent database. + // + // Format `projects/{project}/databases/{database}` + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + } + ]; + + // Required. The backup schedule to create. + BackupSchedule backup_schedule = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// The request for +// [FirestoreAdmin.GetBackupSchedule][google.firestore.admin.v1.FirestoreAdmin.GetBackupSchedule]. +message GetBackupScheduleRequest { + // Required. The name of the backup schedule. + // + // Format + // `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/BackupSchedule" + } + ]; +} + +// The request for +// [FirestoreAdmin.UpdateBackupSchedule][google.firestore.admin.v1.FirestoreAdmin.UpdateBackupSchedule]. +message UpdateBackupScheduleRequest { + // Required. The backup schedule to update. + BackupSchedule backup_schedule = 1 [(google.api.field_behavior) = REQUIRED]; + + // The list of fields to be updated. + google.protobuf.FieldMask update_mask = 2; +} + +// The request for +// [FirestoreAdmin.ListBackupSchedules][google.firestore.admin.v1.FirestoreAdmin.ListBackupSchedules]. +message ListBackupSchedulesRequest { + // Required. The parent database. + // + // Format is `projects/{project}/databases/{database}`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + } + ]; +} + +// The response for +// [FirestoreAdmin.ListBackupSchedules][google.firestore.admin.v1.FirestoreAdmin.ListBackupSchedules]. +message ListBackupSchedulesResponse { + // List of all backup schedules. + repeated BackupSchedule backup_schedules = 1; +} + +// The request for [FirestoreAdmin.DeleteBackupSchedules][]. +message DeleteBackupScheduleRequest { + // Required. The name of the backup schedule. + // + // Format + // `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/BackupSchedule" + } + ]; +} + +// The request for +// [FirestoreAdmin.CreateIndex][google.firestore.admin.v1.FirestoreAdmin.CreateIndex]. +message CreateIndexRequest { + // Required. A parent name of the form + // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/CollectionGroup" + } + ]; + + // Required. The composite index to create. + Index index = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// The request for +// [FirestoreAdmin.ListIndexes][google.firestore.admin.v1.FirestoreAdmin.ListIndexes]. +message ListIndexesRequest { + // Required. A parent name of the form + // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/CollectionGroup" + } + ]; + + // The filter to apply to list results. + string filter = 2; + + // The number of results to return. + int32 page_size = 3; + + // A page token, returned from a previous call to + // [FirestoreAdmin.ListIndexes][google.firestore.admin.v1.FirestoreAdmin.ListIndexes], + // that may be used to get the next page of results. + string page_token = 4; +} + +// The response for +// [FirestoreAdmin.ListIndexes][google.firestore.admin.v1.FirestoreAdmin.ListIndexes]. +message ListIndexesResponse { + // The requested indexes. + repeated Index indexes = 1; + + // A page token that may be used to request another page of results. If blank, + // this is the last page. + string next_page_token = 2; +} + +// The request for +// [FirestoreAdmin.GetIndex][google.firestore.admin.v1.FirestoreAdmin.GetIndex]. +message GetIndexRequest { + // Required. A name of the form + // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "firestore.googleapis.com/Index" } + ]; +} + +// The request for +// [FirestoreAdmin.DeleteIndex][google.firestore.admin.v1.FirestoreAdmin.DeleteIndex]. +message DeleteIndexRequest { + // Required. A name of the form + // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "firestore.googleapis.com/Index" } + ]; +} + +// The request for +// [FirestoreAdmin.UpdateField][google.firestore.admin.v1.FirestoreAdmin.UpdateField]. +message UpdateFieldRequest { + // Required. The field to be updated. + Field field = 1 [(google.api.field_behavior) = REQUIRED]; + + // A mask, relative to the field. If specified, only configuration specified + // by this field_mask will be updated in the field. + google.protobuf.FieldMask update_mask = 2; +} + +// The request for +// [FirestoreAdmin.GetField][google.firestore.admin.v1.FirestoreAdmin.GetField]. +message GetFieldRequest { + // Required. A name of the form + // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_id}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "firestore.googleapis.com/Field" } + ]; +} + +// The request for +// [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields]. +message ListFieldsRequest { + // Required. A parent name of the form + // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/CollectionGroup" + } + ]; + + // The filter to apply to list results. Currently, + // [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields] + // only supports listing fields that have been explicitly overridden. To issue + // this query, call + // [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields] + // with a filter that includes `indexConfig.usesAncestorConfig:false` or + // `ttlConfig:*`. + string filter = 2; + + // The number of results to return. + int32 page_size = 3; + + // A page token, returned from a previous call to + // [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields], + // that may be used to get the next page of results. + string page_token = 4; +} + +// The response for +// [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields]. +message ListFieldsResponse { + // The requested fields. + repeated Field fields = 1; + + // A page token that may be used to request another page of results. If blank, + // this is the last page. + string next_page_token = 2; +} + +// The request for +// [FirestoreAdmin.ExportDocuments][google.firestore.admin.v1.FirestoreAdmin.ExportDocuments]. +message ExportDocumentsRequest { + // Required. Database to export. Should be of the form: + // `projects/{project_id}/databases/{database_id}`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + } + ]; + + // Which collection IDs to export. Unspecified means all collections. Each + // collection ID in this list must be unique. + repeated string collection_ids = 2; + + // The output URI. Currently only supports Google Cloud Storage URIs of the + // form: `gs://BUCKET_NAME[/NAMESPACE_PATH]`, where `BUCKET_NAME` is the name + // of the Google Cloud Storage bucket and `NAMESPACE_PATH` is an optional + // Google Cloud Storage namespace path. When + // choosing a name, be sure to consider Google Cloud Storage naming + // guidelines: https://cloud.google.com/storage/docs/naming. + // If the URI is a bucket (without a namespace path), a prefix will be + // generated based on the start time. + string output_uri_prefix = 3; + + // An empty list represents all namespaces. This is the preferred + // usage for databases that don't use namespaces. + // + // An empty string element represents the default namespace. This should be + // used if the database has data in non-default namespaces, but doesn't want + // to include them. Each namespace in this list must be unique. + repeated string namespace_ids = 4; + + // The timestamp that corresponds to the version of the database to be + // exported. The timestamp must be in the past, rounded to the minute and not + // older than + // [earliestVersionTime][google.firestore.admin.v1.Database.earliest_version_time]. + // If specified, then the exported documents will represent a consistent view + // of the database at the provided time. Otherwise, there are no guarantees + // about the consistency of the exported documents. + google.protobuf.Timestamp snapshot_time = 5; +} + +// The request for +// [FirestoreAdmin.ImportDocuments][google.firestore.admin.v1.FirestoreAdmin.ImportDocuments]. +message ImportDocumentsRequest { + // Required. Database to import into. Should be of the form: + // `projects/{project_id}/databases/{database_id}`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + } + ]; + + // Which collection IDs to import. Unspecified means all collections included + // in the import. Each collection ID in this list must be unique. + repeated string collection_ids = 2; + + // Location of the exported files. + // This must match the output_uri_prefix of an ExportDocumentsResponse from + // an export that has completed successfully. + // See: + // [google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix][google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix]. + string input_uri_prefix = 3; + + // An empty list represents all namespaces. This is the preferred + // usage for databases that don't use namespaces. + // + // An empty string element represents the default namespace. This should be + // used if the database has data in non-default namespaces, but doesn't want + // to include them. Each namespace in this list must be unique. + repeated string namespace_ids = 4; +} + +// The request for +// [FirestoreAdmin.BulkDeleteDocuments][google.firestore.admin.v1.FirestoreAdmin.BulkDeleteDocuments]. +// +// When both collection_ids and namespace_ids are set, only documents satisfying +// both conditions will be deleted. +// +// Requests with namespace_ids and collection_ids both empty will be rejected. +// Please use +// [FirestoreAdmin.DeleteDatabase][google.firestore.admin.v1.FirestoreAdmin.DeleteDatabase] +// instead. +message BulkDeleteDocumentsRequest { + // Required. Database to operate. Should be of the form: + // `projects/{project_id}/databases/{database_id}`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + } + ]; + + // Optional. IDs of the collection groups to delete. Unspecified means all + // collection groups. + // + // Each collection group in this list must be unique. + repeated string collection_ids = 2 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Namespaces to delete. + // + // An empty list means all namespaces. This is the recommended + // usage for databases that don't use namespaces. + // + // An empty string element represents the default namespace. This should be + // used if the database has data in non-default namespaces, but doesn't want + // to delete from them. + // + // Each namespace in this list must be unique. + repeated string namespace_ids = 3 [(google.api.field_behavior) = OPTIONAL]; +} + +// The response for +// [FirestoreAdmin.BulkDeleteDocuments][google.firestore.admin.v1.FirestoreAdmin.BulkDeleteDocuments]. +message BulkDeleteDocumentsResponse {} + +// The request for +// [FirestoreAdmin.GetBackup][google.firestore.admin.v1.FirestoreAdmin.GetBackup]. +message GetBackupRequest { + // Required. Name of the backup to fetch. + // + // Format is `projects/{project}/locations/{location}/backups/{backup}`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Backup" + } + ]; +} + +// The request for +// [FirestoreAdmin.ListBackups][google.firestore.admin.v1.FirestoreAdmin.ListBackups]. +message ListBackupsRequest { + // Required. The location to list backups from. + // + // Format is `projects/{project}/locations/{location}`. + // Use `{location} = '-'` to list backups from all locations for the given + // project. This allows listing backups from a single location or from all + // locations. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Location" + } + ]; + + // An expression that filters the list of returned backups. + // + // A filter expression consists of a field name, a comparison operator, and a + // value for filtering. + // The value must be a string, a number, or a boolean. The comparison operator + // must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + // Colon `:` is the contains operator. Filter rules are not case sensitive. + // + // The following fields in the [Backup][google.firestore.admin.v1.Backup] are + // eligible for filtering: + // + // * `database_uid` (supports `=` only) + string filter = 2; +} + +// The response for +// [FirestoreAdmin.ListBackups][google.firestore.admin.v1.FirestoreAdmin.ListBackups]. +message ListBackupsResponse { + // List of all backups for the project. + repeated Backup backups = 1; + + // List of locations that existing backups were not able to be fetched from. + // + // Instead of failing the entire requests when a single location is + // unreachable, this response returns a partial result set and list of + // locations unable to be reached here. The request can be retried against a + // single location to get a concrete error. + repeated string unreachable = 3; +} + +// The request for +// [FirestoreAdmin.DeleteBackup][google.firestore.admin.v1.FirestoreAdmin.DeleteBackup]. +message DeleteBackupRequest { + // Required. Name of the backup to delete. + // + // format is `projects/{project}/locations/{location}/backups/{backup}`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Backup" + } + ]; +} + +// The request message for +// [FirestoreAdmin.RestoreDatabase][google.firestore.admin.v1.FirestoreAdmin.RestoreDatabase]. +message RestoreDatabaseRequest { + // Required. The project to restore the database in. Format is + // `projects/{project_id}`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "firestore.googleapis.com/Database" + } + ]; + + // Required. The ID to use for the database, which will become the final + // component of the database's resource name. This database ID must not be + // associated with an existing database. + // + // This value should be 4-63 characters. Valid characters are /[a-z][0-9]-/ + // with first character a letter and the last a letter or a number. Must not + // be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + // + // "(default)" database ID is also valid. + string database_id = 2 [(google.api.field_behavior) = REQUIRED]; + + // Required. Backup to restore from. Must be from the same project as the + // parent. + // + // The restored database will be created in the same location as the source + // backup. + // + // Format is: `projects/{project_id}/locations/{location}/backups/{backup}` + string backup = 3 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Backup" + } + ]; + + // Optional. Encryption configuration for the restored database. + // + // If this field is not specified, the restored database will use + // the same encryption configuration as the backup, namely + // [use_source_encryption][google.firestore.admin.v1.Database.EncryptionConfig.use_source_encryption]. + Database.EncryptionConfig encryption_config = 9 + [(google.api.field_behavior) = OPTIONAL]; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/index.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/index.proto new file mode 100644 index 0000000..1b8b0a4 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/index.proto @@ -0,0 +1,198 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.admin.v1; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.Admin.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb"; +option java_multiple_files = true; +option java_outer_classname = "IndexProto"; +option java_package = "com.google.firestore.admin.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\Admin\\V1"; +option ruby_package = "Google::Cloud::Firestore::Admin::V1"; + +// Cloud Firestore indexes enable simple and complex queries against +// documents in a database. +message Index { + option (google.api.resource) = { + type: "firestore.googleapis.com/Index" + pattern: "projects/{project}/databases/{database}/collectionGroups/{collection}/indexes/{index}" + }; + + // Query Scope defines the scope at which a query is run. This is specified on + // a StructuredQuery's `from` field. + enum QueryScope { + // The query scope is unspecified. Not a valid option. + QUERY_SCOPE_UNSPECIFIED = 0; + + // Indexes with a collection query scope specified allow queries + // against a collection that is the child of a specific document, specified + // at query time, and that has the collection ID specified by the index. + COLLECTION = 1; + + // Indexes with a collection group query scope specified allow queries + // against all collections that has the collection ID specified by the + // index. + COLLECTION_GROUP = 2; + + // Include all the collections's ancestor in the index. Only available for + // Datastore Mode databases. + COLLECTION_RECURSIVE = 3; + } + + // API Scope defines the APIs (Firestore Native, or Firestore in + // Datastore Mode) that are supported for queries. + enum ApiScope { + // The index can only be used by the Firestore Native query API. + // This is the default. + ANY_API = 0; + + // The index can only be used by the Firestore in Datastore Mode query API. + DATASTORE_MODE_API = 1; + } + + // A field in an index. + // The field_path describes which field is indexed, the value_mode describes + // how the field value is indexed. + message IndexField { + // The supported orderings. + enum Order { + // The ordering is unspecified. Not a valid option. + ORDER_UNSPECIFIED = 0; + + // The field is ordered by ascending field value. + ASCENDING = 1; + + // The field is ordered by descending field value. + DESCENDING = 2; + } + + // The supported array value configurations. + enum ArrayConfig { + // The index does not support additional array queries. + ARRAY_CONFIG_UNSPECIFIED = 0; + + // The index supports array containment queries. + CONTAINS = 1; + } + + // The index configuration to support vector search operations + message VectorConfig { + // An index that stores vectors in a flat data structure, and supports + // exhaustive search. + message FlatIndex {} + + // Required. The vector dimension this configuration applies to. + // + // The resulting index will only include vectors of this dimension, and + // can be used for vector search with the same dimension. + int32 dimension = 1 [(google.api.field_behavior) = REQUIRED]; + + // The type of index used. + oneof type { + // Indicates the vector index is a flat index. + FlatIndex flat = 2; + } + } + + // Can be __name__. + // For single field indexes, this must match the name of the field or may + // be omitted. + string field_path = 1; + + // How the field value is indexed. + oneof value_mode { + // Indicates that this field supports ordering by the specified order or + // comparing using =, !=, <, <=, >, >=. + Order order = 2; + + // Indicates that this field supports operations on `array_value`s. + ArrayConfig array_config = 3; + + // Indicates that this field supports nearest neighbor and distance + // operations on vector. + VectorConfig vector_config = 4; + } + } + + // The state of an index. During index creation, an index will be in the + // `CREATING` state. If the index is created successfully, it will transition + // to the `READY` state. If the index creation encounters a problem, the index + // will transition to the `NEEDS_REPAIR` state. + enum State { + // The state is unspecified. + STATE_UNSPECIFIED = 0; + + // The index is being created. + // There is an active long-running operation for the index. + // The index is updated when writing a document. + // Some index data may exist. + CREATING = 1; + + // The index is ready to be used. + // The index is updated when writing a document. + // The index is fully populated from all stored documents it applies to. + READY = 2; + + // The index was being created, but something went wrong. + // There is no active long-running operation for the index, + // and the most recently finished long-running operation failed. + // The index is not updated when writing a document. + // Some index data may exist. + // Use the google.longrunning.Operations API to determine why the operation + // that last attempted to create this index failed, then re-create the + // index. + NEEDS_REPAIR = 3; + } + + // Output only. A server defined name for this index. + // The form of this name for composite indexes will be: + // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{composite_index_id}` + // For single field indexes, this field will be empty. + string name = 1; + + // Indexes with a collection query scope specified allow queries + // against a collection that is the child of a specific document, specified at + // query time, and that has the same collection ID. + // + // Indexes with a collection group query scope specified allow queries against + // all collections descended from a specific document, specified at query + // time, and that have the same collection ID as this index. + QueryScope query_scope = 2; + + // The API scope supported by this index. + ApiScope api_scope = 5; + + // The fields supported by this index. + // + // For composite indexes, this requires a minimum of 2 and a maximum of 100 + // fields. The last field entry is always for the field path `__name__`. If, + // on creation, `__name__` was not specified as the last field, it will be + // added automatically with the same direction as that of the last field + // defined. If the final field in a composite index is not directional, the + // `__name__` will be ordered ASCENDING (unless explicitly specified). + // + // For single field indexes, this will always be exactly one entry with a + // field path equal to the field path of the associated field. + repeated IndexField fields = 3; + + // Output only. The serving state of the index. + State state = 4; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/location.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/location.proto new file mode 100644 index 0000000..4a1154f --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/location.proto @@ -0,0 +1,30 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.admin.v1; + +option csharp_namespace = "Google.Cloud.Firestore.Admin.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb"; +option java_multiple_files = true; +option java_outer_classname = "LocationProto"; +option java_package = "com.google.firestore.admin.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\Admin\\V1"; +option ruby_package = "Google::Cloud::Firestore::Admin::V1"; + +// The metadata message for +// [google.cloud.location.Location.metadata][google.cloud.location.Location.metadata]. +message LocationMetadata {} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/operation.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/operation.proto new file mode 100644 index 0000000..39a20ec --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/operation.proto @@ -0,0 +1,300 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.admin.v1; + +import "google/api/resource.proto"; +import "google/firestore/admin/v1/index.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.Admin.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb"; +option java_multiple_files = true; +option java_outer_classname = "OperationProto"; +option java_package = "com.google.firestore.admin.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\Admin\\V1"; +option ruby_package = "Google::Cloud::Firestore::Admin::V1"; + +// Metadata for [google.longrunning.Operation][google.longrunning.Operation] +// results from +// [FirestoreAdmin.CreateIndex][google.firestore.admin.v1.FirestoreAdmin.CreateIndex]. +message IndexOperationMetadata { + // The time this operation started. + google.protobuf.Timestamp start_time = 1; + + // The time this operation completed. Will be unset if operation still in + // progress. + google.protobuf.Timestamp end_time = 2; + + // The index resource that this operation is acting on. For example: + // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` + string index = 3; + + // The state of the operation. + OperationState state = 4; + + // The progress, in documents, of this operation. + Progress progress_documents = 5; + + // The progress, in bytes, of this operation. + Progress progress_bytes = 6; +} + +// Metadata for [google.longrunning.Operation][google.longrunning.Operation] +// results from +// [FirestoreAdmin.UpdateField][google.firestore.admin.v1.FirestoreAdmin.UpdateField]. +message FieldOperationMetadata { + // Information about an index configuration change. + message IndexConfigDelta { + // Specifies how the index is changing. + enum ChangeType { + // The type of change is not specified or known. + CHANGE_TYPE_UNSPECIFIED = 0; + + // The single field index is being added. + ADD = 1; + + // The single field index is being removed. + REMOVE = 2; + } + + // Specifies how the index is changing. + ChangeType change_type = 1; + + // The index being changed. + Index index = 2; + } + + // Information about a TTL configuration change. + message TtlConfigDelta { + // Specifies how the TTL config is changing. + enum ChangeType { + // The type of change is not specified or known. + CHANGE_TYPE_UNSPECIFIED = 0; + + // The TTL config is being added. + ADD = 1; + + // The TTL config is being removed. + REMOVE = 2; + } + + // Specifies how the TTL configuration is changing. + ChangeType change_type = 1; + } + + // The time this operation started. + google.protobuf.Timestamp start_time = 1; + + // The time this operation completed. Will be unset if operation still in + // progress. + google.protobuf.Timestamp end_time = 2; + + // The field resource that this operation is acting on. For example: + // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_path}` + string field = 3; + + // A list of + // [IndexConfigDelta][google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta], + // which describe the intent of this operation. + repeated IndexConfigDelta index_config_deltas = 4; + + // The state of the operation. + OperationState state = 5; + + // The progress, in documents, of this operation. + Progress progress_documents = 6; + + // The progress, in bytes, of this operation. + Progress progress_bytes = 7; + + // Describes the deltas of TTL configuration. + TtlConfigDelta ttl_config_delta = 8; +} + +// Metadata for [google.longrunning.Operation][google.longrunning.Operation] +// results from +// [FirestoreAdmin.ExportDocuments][google.firestore.admin.v1.FirestoreAdmin.ExportDocuments]. +message ExportDocumentsMetadata { + // The time this operation started. + google.protobuf.Timestamp start_time = 1; + + // The time this operation completed. Will be unset if operation still in + // progress. + google.protobuf.Timestamp end_time = 2; + + // The state of the export operation. + OperationState operation_state = 3; + + // The progress, in documents, of this operation. + Progress progress_documents = 4; + + // The progress, in bytes, of this operation. + Progress progress_bytes = 5; + + // Which collection IDs are being exported. + repeated string collection_ids = 6; + + // Where the documents are being exported to. + string output_uri_prefix = 7; + + // Which namespace IDs are being exported. + repeated string namespace_ids = 8; + + // The timestamp that corresponds to the version of the database that is being + // exported. If unspecified, there are no guarantees about the consistency of + // the documents being exported. + google.protobuf.Timestamp snapshot_time = 9; +} + +// Metadata for [google.longrunning.Operation][google.longrunning.Operation] +// results from +// [FirestoreAdmin.ImportDocuments][google.firestore.admin.v1.FirestoreAdmin.ImportDocuments]. +message ImportDocumentsMetadata { + // The time this operation started. + google.protobuf.Timestamp start_time = 1; + + // The time this operation completed. Will be unset if operation still in + // progress. + google.protobuf.Timestamp end_time = 2; + + // The state of the import operation. + OperationState operation_state = 3; + + // The progress, in documents, of this operation. + Progress progress_documents = 4; + + // The progress, in bytes, of this operation. + Progress progress_bytes = 5; + + // Which collection IDs are being imported. + repeated string collection_ids = 6; + + // The location of the documents being imported. + string input_uri_prefix = 7; + + // Which namespace IDs are being imported. + repeated string namespace_ids = 8; +} + +// Metadata for [google.longrunning.Operation][google.longrunning.Operation] +// results from +// [FirestoreAdmin.BulkDeleteDocuments][google.firestore.admin.v1.FirestoreAdmin.BulkDeleteDocuments]. +message BulkDeleteDocumentsMetadata { + // The time this operation started. + google.protobuf.Timestamp start_time = 1; + + // The time this operation completed. Will be unset if operation still in + // progress. + google.protobuf.Timestamp end_time = 2; + + // The state of the operation. + OperationState operation_state = 3; + + // The progress, in documents, of this operation. + Progress progress_documents = 4; + + // The progress, in bytes, of this operation. + Progress progress_bytes = 5; + + // The IDs of the collection groups that are being deleted. + repeated string collection_ids = 6; + + // Which namespace IDs are being deleted. + repeated string namespace_ids = 7; + + // The timestamp that corresponds to the version of the database that is being + // read to get the list of documents to delete. This time can also be used as + // the timestamp of PITR in case of disaster recovery (subject to PITR window + // limit). + google.protobuf.Timestamp snapshot_time = 8; +} + +// Returned in the [google.longrunning.Operation][google.longrunning.Operation] +// response field. +message ExportDocumentsResponse { + // Location of the output files. This can be used to begin an import + // into Cloud Firestore (this project or another project) after the operation + // completes successfully. + string output_uri_prefix = 1; +} + +// Metadata for the [long-running operation][google.longrunning.Operation] from +// the [RestoreDatabase][google.firestore.admin.v1.RestoreDatabase] request. +message RestoreDatabaseMetadata { + // The time the restore was started. + google.protobuf.Timestamp start_time = 1; + + // The time the restore finished, unset for ongoing restores. + google.protobuf.Timestamp end_time = 2; + + // The operation state of the restore. + OperationState operation_state = 3; + + // The name of the database being restored to. + string database = 4 [(google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + }]; + + // The name of the backup restoring from. + string backup = 5 [(google.api.resource_reference) = { + type: "firestore.googleapis.com/Backup" + }]; + + // How far along the restore is as an estimated percentage of remaining time. + Progress progress_percentage = 8; +} + +// Describes the progress of the operation. +// Unit of work is generic and must be interpreted based on where +// [Progress][google.firestore.admin.v1.Progress] is used. +message Progress { + // The amount of work estimated. + int64 estimated_work = 1; + + // The amount of work completed. + int64 completed_work = 2; +} + +// Describes the state of the operation. +enum OperationState { + // Unspecified. + OPERATION_STATE_UNSPECIFIED = 0; + + // Request is being prepared for processing. + INITIALIZING = 1; + + // Request is actively being processed. + PROCESSING = 2; + + // Request is in the process of being cancelled after user called + // google.longrunning.Operations.CancelOperation on the operation. + CANCELLING = 3; + + // Request has been processed and is in its finalization stage. + FINALIZING = 4; + + // Request has completed successfully. + SUCCESSFUL = 5; + + // Request has finished being processed, but encountered an error. + FAILED = 6; + + // Request has finished being cancelled after user called + // google.longrunning.Operations.CancelOperation. + CANCELLED = 7; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/schedule.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/schedule.proto new file mode 100644 index 0000000..46bc039 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/admin/v1/schedule.proto @@ -0,0 +1,95 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.admin.v1; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/timestamp.proto"; +import "google/type/dayofweek.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.Admin.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb"; +option java_multiple_files = true; +option java_outer_classname = "ScheduleProto"; +option java_package = "com.google.firestore.admin.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\Admin\\V1"; +option ruby_package = "Google::Cloud::Firestore::Admin::V1"; + +// A backup schedule for a Cloud Firestore Database. +// +// This resource is owned by the database it is backing up, and is deleted along +// with the database. The actual backups are not though. +message BackupSchedule { + option (google.api.resource) = { + type: "firestore.googleapis.com/BackupSchedule" + pattern: "projects/{project}/databases/{database}/backupSchedules/{backup_schedule}" + }; + + // Output only. The unique backup schedule identifier across all locations and + // databases for the given project. + // + // This will be auto-assigned. + // + // Format is + // `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` + string name = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The timestamp at which this backup schedule was created and + // effective since. + // + // No backups will be created for this schedule before this time. + google.protobuf.Timestamp create_time = 3 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The timestamp at which this backup schedule was most recently + // updated. When a backup schedule is first created, this is the same as + // create_time. + google.protobuf.Timestamp update_time = 10 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // At what relative time in the future, compared to its creation time, + // the backup should be deleted, e.g. keep backups for 7 days. + // + // The maximum supported retention period is 14 weeks. + google.protobuf.Duration retention = 6; + + // A oneof field to represent when backups will be taken. + oneof recurrence { + // For a schedule that runs daily. + DailyRecurrence daily_recurrence = 7; + + // For a schedule that runs weekly on a specific day. + WeeklyRecurrence weekly_recurrence = 8; + } +} + +// Represents a recurring schedule that runs every day. +// +// The time zone is UTC. +message DailyRecurrence {} + +// Represents a recurring schedule that runs on a specified day of the week. +// +// The time zone is UTC. +message WeeklyRecurrence { + // The day of week to run. + // + // DAY_OF_WEEK_UNSPECIFIED is not allowed. + google.type.DayOfWeek day = 2; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/aggregation_result.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/aggregation_result.proto new file mode 100644 index 0000000..25e5d2e --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/aggregation_result.proto @@ -0,0 +1,43 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1; + +import "google/firestore/v1/document.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "AggregationResultProto"; +option java_package = "com.google.firestore.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; + +// The result of a single bucket from a Firestore aggregation query. +// +// The keys of `aggregate_fields` are the same for all results in an aggregation +// query, unlike document queries which can have different fields present for +// each result. +message AggregationResult { + // The result of the aggregation functions, ex: `COUNT(*) AS total_docs`. + // + // The key is the + // [alias][google.firestore.v1.StructuredAggregationQuery.Aggregation.alias] + // assigned to the aggregation function on input and the size of this map + // equals the number of aggregation functions in the query. + map aggregate_fields = 2; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/bloom_filter.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/bloom_filter.proto new file mode 100644 index 0000000..1b9eb37 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/bloom_filter.proto @@ -0,0 +1,73 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1; + +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "BloomFilterProto"; +option java_package = "com.google.firestore.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; + +// A sequence of bits, encoded in a byte array. +// +// Each byte in the `bitmap` byte array stores 8 bits of the sequence. The only +// exception is the last byte, which may store 8 _or fewer_ bits. The `padding` +// defines the number of bits of the last byte to be ignored as "padding". The +// values of these "padding" bits are unspecified and must be ignored. +// +// To retrieve the first bit, bit 0, calculate: `(bitmap[0] & 0x01) != 0`. +// To retrieve the second bit, bit 1, calculate: `(bitmap[0] & 0x02) != 0`. +// To retrieve the third bit, bit 2, calculate: `(bitmap[0] & 0x04) != 0`. +// To retrieve the fourth bit, bit 3, calculate: `(bitmap[0] & 0x08) != 0`. +// To retrieve bit n, calculate: `(bitmap[n / 8] & (0x01 << (n % 8))) != 0`. +// +// The "size" of a `BitSequence` (the number of bits it contains) is calculated +// by this formula: `(bitmap.length * 8) - padding`. +message BitSequence { + // The bytes that encode the bit sequence. + // May have a length of zero. + bytes bitmap = 1; + + // The number of bits of the last byte in `bitmap` to ignore as "padding". + // If the length of `bitmap` is zero, then this value must be `0`. + // Otherwise, this value must be between 0 and 7, inclusive. + int32 padding = 2; +} + +// A bloom filter (https://en.wikipedia.org/wiki/Bloom_filter). +// +// The bloom filter hashes the entries with MD5 and treats the resulting 128-bit +// hash as 2 distinct 64-bit hash values, interpreted as unsigned integers +// using 2's complement encoding. +// +// These two hash values, named `h1` and `h2`, are then used to compute the +// `hash_count` hash values using the formula, starting at `i=0`: +// +// h(i) = h1 + (i * h2) +// +// These resulting values are then taken modulo the number of bits in the bloom +// filter to get the bits of the bloom filter to test for the given entry. +message BloomFilter { + // The bloom filter data. + BitSequence bits = 1; + + // The number of hashes used by the algorithm. + int32 hash_count = 2; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/common.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/common.proto new file mode 100644 index 0000000..fcb0f49 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/common.proto @@ -0,0 +1,90 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1; + +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "CommonProto"; +option java_package = "com.google.firestore.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; + +// A set of field paths on a document. +// Used to restrict a get or update operation on a document to a subset of its +// fields. +// This is different from standard field masks, as this is always scoped to a +// [Document][google.firestore.v1.Document], and takes in account the dynamic +// nature of [Value][google.firestore.v1.Value]. +message DocumentMask { + // The list of field paths in the mask. See + // [Document.fields][google.firestore.v1.Document.fields] for a field path + // syntax reference. + repeated string field_paths = 1; +} + +// A precondition on a document, used for conditional operations. +message Precondition { + // The type of precondition. + oneof condition_type { + // When set to `true`, the target document must exist. + // When set to `false`, the target document must not exist. + bool exists = 1; + + // When set, the target document must exist and have been last updated at + // that time. Timestamp must be microsecond aligned. + google.protobuf.Timestamp update_time = 2; + } +} + +// Options for creating a new transaction. +message TransactionOptions { + // Options for a transaction that can be used to read and write documents. + // + // Firestore does not allow 3rd party auth requests to create read-write. + // transactions. + message ReadWrite { + // An optional transaction to retry. + bytes retry_transaction = 1; + } + + // Options for a transaction that can only be used to read documents. + message ReadOnly { + // The consistency mode for this transaction. If not set, defaults to strong + // consistency. + oneof consistency_selector { + // Reads documents at the given time. + // + // This must be a microsecond precision timestamp within the past one + // hour, or if Point-in-Time Recovery is enabled, can additionally be a + // whole minute timestamp within the past 7 days. + google.protobuf.Timestamp read_time = 2; + } + } + + // The mode of the transaction. + oneof mode { + // The transaction can only be used for read operations. + ReadOnly read_only = 2; + + // The transaction can be used for both read and write operations. + ReadWrite read_write = 3; + } +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/document.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/document.proto new file mode 100644 index 0000000..52dc85c --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/document.proto @@ -0,0 +1,150 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1; + +import "google/api/field_behavior.proto"; +import "google/protobuf/struct.proto"; +import "google/protobuf/timestamp.proto"; +import "google/type/latlng.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "DocumentProto"; +option java_package = "com.google.firestore.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; + +// A Firestore document. +// +// Must not exceed 1 MiB - 4 bytes. +message Document { + // The resource name of the document, for example + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string name = 1; + + // The document's fields. + // + // The map keys represent field names. + // + // Field names matching the regular expression `__.*__` are reserved. Reserved + // field names are forbidden except in certain documented contexts. The field + // names, represented as UTF-8, must not exceed 1,500 bytes and cannot be + // empty. + // + // Field paths may be used in other contexts to refer to structured fields + // defined here. For `map_value`, the field path is represented by a + // dot-delimited (`.`) string of segments. Each segment is either a simple + // field name (defined below) or a quoted field name. For example, the + // structured field `"foo" : { map_value: { "x&y" : { string_value: "hello" + // }}}` would be represented by the field path `` foo.`x&y` ``. + // + // A simple field name contains only characters `a` to `z`, `A` to `Z`, + // `0` to `9`, or `_`, and must not start with `0` to `9`. For example, + // `foo_bar_17`. + // + // A quoted field name starts and ends with `` ` `` and + // may contain any character. Some characters, including `` ` ``, must be + // escaped using a `\`. For example, `` `x&y` `` represents `x&y` and + // `` `bak\`tik` `` represents `` bak`tik ``. + map fields = 2; + + // Output only. The time at which the document was created. + // + // This value increases monotonically when a document is deleted then + // recreated. It can also be compared to values from other documents and + // the `read_time` of a query. + google.protobuf.Timestamp create_time = 3; + + // Output only. The time at which the document was last changed. + // + // This value is initially set to the `create_time` then increases + // monotonically with each change to the document. It can also be + // compared to values from other documents and the `read_time` of a query. + google.protobuf.Timestamp update_time = 4; +} + +// A message that can hold any of the supported value types. +message Value { + // Must have a value set. + oneof value_type { + // A null value. + google.protobuf.NullValue null_value = 11; + + // A boolean value. + bool boolean_value = 1; + + // An integer value. + int64 integer_value = 2; + + // A double value. + double double_value = 3; + + // A timestamp value. + // + // Precise only to microseconds. When stored, any additional precision is + // rounded down. + google.protobuf.Timestamp timestamp_value = 10; + + // A string value. + // + // The string, represented as UTF-8, must not exceed 1 MiB - 89 bytes. + // Only the first 1,500 bytes of the UTF-8 representation are considered by + // queries. + string string_value = 17; + + // A bytes value. + // + // Must not exceed 1 MiB - 89 bytes. + // Only the first 1,500 bytes are considered by queries. + bytes bytes_value = 18; + + // A reference to a document. For example: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string reference_value = 5; + + // A geo point value representing a point on the surface of Earth. + google.type.LatLng geo_point_value = 8; + + // An array value. + // + // Cannot directly contain another array value, though can contain a + // map which contains another array. + ArrayValue array_value = 9; + + // A map value. + MapValue map_value = 6; + } +} + +// An array value. +message ArrayValue { + // Values in the array. + repeated Value values = 1; +} + +// A map value. +message MapValue { + // The map's fields. + // + // The map keys represent field names. Field names matching the regular + // expression `__.*__` are reserved. Reserved field names are forbidden except + // in certain documented contexts. The map keys, represented as UTF-8, must + // not exceed 1,500 bytes and cannot be empty. + map fields = 1; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/firestore.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/firestore.proto new file mode 100644 index 0000000..2ed6bf0 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/firestore.proto @@ -0,0 +1,1128 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/firestore/v1/aggregation_result.proto"; +import "google/firestore/v1/common.proto"; +import "google/firestore/v1/document.proto"; +import "google/firestore/v1/query.proto"; +import "google/firestore/v1/query_profile.proto"; +import "google/firestore/v1/write.proto"; +import "google/protobuf/empty.proto"; +import "google/protobuf/timestamp.proto"; +import "google/protobuf/wrappers.proto"; +import "google/rpc/status.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "FirestoreProto"; +option java_package = "com.google.firestore.v1"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; + +// Specification of the Firestore API. + +// The Cloud Firestore service. +// +// Cloud Firestore is a fast, fully managed, serverless, cloud-native NoSQL +// document database that simplifies storing, syncing, and querying data for +// your mobile, web, and IoT apps at global scale. Its client libraries provide +// live synchronization and offline support, while its security features and +// integrations with Firebase and Google Cloud Platform accelerate building +// truly serverless apps. +service Firestore { + option (google.api.default_host) = "firestore.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/datastore"; + + // Gets a single document. + rpc GetDocument(GetDocumentRequest) returns (Document) { + option (google.api.http) = { + get: "/v1/{name=projects/*/databases/*/documents/*/**}" + }; + } + + // Lists documents. + rpc ListDocuments(ListDocumentsRequest) returns (ListDocumentsResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}" + additional_bindings { + get: "/v1/{parent=projects/*/databases/*/documents}/{collection_id}" + } + }; + } + + // Updates or inserts a document. + rpc UpdateDocument(UpdateDocumentRequest) returns (Document) { + option (google.api.http) = { + patch: "/v1/{document.name=projects/*/databases/*/documents/*/**}" + body: "document" + }; + option (google.api.method_signature) = "document,update_mask"; + } + + // Deletes a document. + rpc DeleteDocument(DeleteDocumentRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=projects/*/databases/*/documents/*/**}" + }; + option (google.api.method_signature) = "name"; + } + + // Gets multiple documents. + // + // Documents returned by this method are not guaranteed to be returned in the + // same order that they were requested. + rpc BatchGetDocuments(BatchGetDocumentsRequest) + returns (stream BatchGetDocumentsResponse) { + option (google.api.http) = { + post: "/v1/{database=projects/*/databases/*}/documents:batchGet" + body: "*" + }; + } + + // Starts a new transaction. + rpc BeginTransaction(BeginTransactionRequest) + returns (BeginTransactionResponse) { + option (google.api.http) = { + post: "/v1/{database=projects/*/databases/*}/documents:beginTransaction" + body: "*" + }; + option (google.api.method_signature) = "database"; + } + + // Commits a transaction, while optionally updating documents. + rpc Commit(CommitRequest) returns (CommitResponse) { + option (google.api.http) = { + post: "/v1/{database=projects/*/databases/*}/documents:commit" + body: "*" + }; + option (google.api.method_signature) = "database,writes"; + } + + // Rolls back a transaction. + rpc Rollback(RollbackRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + post: "/v1/{database=projects/*/databases/*}/documents:rollback" + body: "*" + }; + option (google.api.method_signature) = "database,transaction"; + } + + // Runs a query. + rpc RunQuery(RunQueryRequest) returns (stream RunQueryResponse) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/databases/*/documents}:runQuery" + body: "*" + additional_bindings { + post: "/v1/{parent=projects/*/databases/*/documents/*/**}:runQuery" + body: "*" + } + }; + } + + // Runs an aggregation query. + // + // Rather than producing [Document][google.firestore.v1.Document] results like + // [Firestore.RunQuery][google.firestore.v1.Firestore.RunQuery], this API + // allows running an aggregation to produce a series of + // [AggregationResult][google.firestore.v1.AggregationResult] server-side. + // + // High-Level Example: + // + // ``` + // -- Return the number of documents in table given a filter. + // SELECT COUNT(*) FROM ( SELECT * FROM k where a = true ); + // ``` + rpc RunAggregationQuery(RunAggregationQueryRequest) + returns (stream RunAggregationQueryResponse) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/databases/*/documents}:runAggregationQuery" + body: "*" + additional_bindings { + post: "/v1/{parent=projects/*/databases/*/documents/*/**}:runAggregationQuery" + body: "*" + } + }; + } + + // Partitions a query by returning partition cursors that can be used to run + // the query in parallel. The returned partition cursors are split points that + // can be used by RunQuery as starting/end points for the query results. + rpc PartitionQuery(PartitionQueryRequest) returns (PartitionQueryResponse) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/databases/*/documents}:partitionQuery" + body: "*" + additional_bindings { + post: "/v1/{parent=projects/*/databases/*/documents/*/**}:partitionQuery" + body: "*" + } + }; + } + + // Streams batches of document updates and deletes, in order. This method is + // only available via gRPC or WebChannel (not REST). + rpc Write(stream WriteRequest) returns (stream WriteResponse) { + option (google.api.http) = { + post: "/v1/{database=projects/*/databases/*}/documents:write" + body: "*" + }; + } + + // Listens to changes. This method is only available via gRPC or WebChannel + // (not REST). + rpc Listen(stream ListenRequest) returns (stream ListenResponse) { + option (google.api.http) = { + post: "/v1/{database=projects/*/databases/*}/documents:listen" + body: "*" + }; + } + + // Lists all the collection IDs underneath a document. + rpc ListCollectionIds(ListCollectionIdsRequest) + returns (ListCollectionIdsResponse) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/databases/*/documents}:listCollectionIds" + body: "*" + additional_bindings { + post: "/v1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds" + body: "*" + } + }; + option (google.api.method_signature) = "parent"; + } + + // Applies a batch of write operations. + // + // The BatchWrite method does not apply the write operations atomically + // and can apply them out of order. Method does not allow more than one write + // per document. Each write succeeds or fails independently. See the + // [BatchWriteResponse][google.firestore.v1.BatchWriteResponse] for the + // success status of each write. + // + // If you require an atomically applied set of writes, use + // [Commit][google.firestore.v1.Firestore.Commit] instead. + rpc BatchWrite(BatchWriteRequest) returns (BatchWriteResponse) { + option (google.api.http) = { + post: "/v1/{database=projects/*/databases/*}/documents:batchWrite" + body: "*" + }; + } + + // Creates a new document. + rpc CreateDocument(CreateDocumentRequest) returns (Document) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/databases/*/documents/**}/{collection_id}" + body: "document" + }; + } +} + +// The request for +// [Firestore.GetDocument][google.firestore.v1.Firestore.GetDocument]. +message GetDocumentRequest { + // Required. The resource name of the Document to get. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string name = 1 [(google.api.field_behavior) = REQUIRED]; + + // The fields to return. If not set, returns all fields. + // + // If the document has a field that is not present in this mask, that field + // will not be returned in the response. + DocumentMask mask = 2; + + // The consistency mode for this transaction. + // If not set, defaults to strong consistency. + oneof consistency_selector { + // Reads the document in a transaction. + bytes transaction = 3; + + // Reads the version of the document at the given time. + // + // This must be a microsecond precision timestamp within the past one hour, + // or if Point-in-Time Recovery is enabled, can additionally be a whole + // minute timestamp within the past 7 days. + google.protobuf.Timestamp read_time = 5; + } +} + +// The request for +// [Firestore.ListDocuments][google.firestore.v1.Firestore.ListDocuments]. +message ListDocumentsRequest { + // Required. The parent resource name. In the format: + // `projects/{project_id}/databases/{database_id}/documents` or + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + // + // For example: + // `projects/my-project/databases/my-database/documents` or + // `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // Optional. The collection ID, relative to `parent`, to list. + // + // For example: `chatrooms` or `messages`. + // + // This is optional, and when not provided, Firestore will list documents + // from all collections under the provided `parent`. + string collection_id = 2 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The maximum number of documents to return in a single response. + // + // Firestore may return fewer than this value. + int32 page_size = 3 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. A page token, received from a previous `ListDocuments` response. + // + // Provide this to retrieve the subsequent page. When paginating, all other + // parameters (with the exception of `page_size`) must match the values set + // in the request that generated the page token. + string page_token = 4 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The optional ordering of the documents to return. + // + // For example: `priority desc, __name__ desc`. + // + // This mirrors the [`ORDER BY`][google.firestore.v1.StructuredQuery.order_by] + // used in Firestore queries but in a string representation. When absent, + // documents are ordered based on `__name__ ASC`. + string order_by = 6 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The fields to return. If not set, returns all fields. + // + // If a document has a field that is not present in this mask, that field + // will not be returned in the response. + DocumentMask mask = 7 [(google.api.field_behavior) = OPTIONAL]; + + // The consistency mode for this transaction. + // If not set, defaults to strong consistency. + oneof consistency_selector { + // Perform the read as part of an already active transaction. + bytes transaction = 8; + + // Perform the read at the provided time. + // + // This must be a microsecond precision timestamp within the past one hour, + // or if Point-in-Time Recovery is enabled, can additionally be a whole + // minute timestamp within the past 7 days. + google.protobuf.Timestamp read_time = 10; + } + + // If the list should show missing documents. + // + // A document is missing if it does not exist, but there are sub-documents + // nested underneath it. When true, such missing documents will be returned + // with a key but will not have fields, + // [`create_time`][google.firestore.v1.Document.create_time], or + // [`update_time`][google.firestore.v1.Document.update_time] set. + // + // Requests with `show_missing` may not specify `where` or `order_by`. + bool show_missing = 12; +} + +// The response for +// [Firestore.ListDocuments][google.firestore.v1.Firestore.ListDocuments]. +message ListDocumentsResponse { + // The Documents found. + repeated Document documents = 1; + + // A token to retrieve the next page of documents. + // + // If this field is omitted, there are no subsequent pages. + string next_page_token = 2; +} + +// The request for +// [Firestore.CreateDocument][google.firestore.v1.Firestore.CreateDocument]. +message CreateDocumentRequest { + // Required. The parent resource. For example: + // `projects/{project_id}/databases/{database_id}/documents` or + // `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The collection ID, relative to `parent`, to list. For example: + // `chatrooms`. + string collection_id = 2 [(google.api.field_behavior) = REQUIRED]; + + // The client-assigned document ID to use for this document. + // + // Optional. If not specified, an ID will be assigned by the service. + string document_id = 3; + + // Required. The document to create. `name` must not be set. + Document document = 4 [(google.api.field_behavior) = REQUIRED]; + + // The fields to return. If not set, returns all fields. + // + // If the document has a field that is not present in this mask, that field + // will not be returned in the response. + DocumentMask mask = 5; +} + +// The request for +// [Firestore.UpdateDocument][google.firestore.v1.Firestore.UpdateDocument]. +message UpdateDocumentRequest { + // Required. The updated document. + // Creates the document if it does not already exist. + Document document = 1 [(google.api.field_behavior) = REQUIRED]; + + // The fields to update. + // None of the field paths in the mask may contain a reserved name. + // + // If the document exists on the server and has fields not referenced in the + // mask, they are left unchanged. + // Fields referenced in the mask, but not present in the input document, are + // deleted from the document on the server. + DocumentMask update_mask = 2; + + // The fields to return. If not set, returns all fields. + // + // If the document has a field that is not present in this mask, that field + // will not be returned in the response. + DocumentMask mask = 3; + + // An optional precondition on the document. + // The request will fail if this is set and not met by the target document. + Precondition current_document = 4; +} + +// The request for +// [Firestore.DeleteDocument][google.firestore.v1.Firestore.DeleteDocument]. +message DeleteDocumentRequest { + // Required. The resource name of the Document to delete. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string name = 1 [(google.api.field_behavior) = REQUIRED]; + + // An optional precondition on the document. + // The request will fail if this is set and not met by the target document. + Precondition current_document = 2; +} + +// The request for +// [Firestore.BatchGetDocuments][google.firestore.v1.Firestore.BatchGetDocuments]. +message BatchGetDocumentsRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // The names of the documents to retrieve. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + // The request will fail if any of the document is not a child resource of the + // given `database`. Duplicate names will be elided. + repeated string documents = 2; + + // The fields to return. If not set, returns all fields. + // + // If a document has a field that is not present in this mask, that field will + // not be returned in the response. + DocumentMask mask = 3; + + // The consistency mode for this transaction. + // If not set, defaults to strong consistency. + oneof consistency_selector { + // Reads documents in a transaction. + bytes transaction = 4; + + // Starts a new transaction and reads the documents. + // Defaults to a read-only transaction. + // The new transaction ID will be returned as the first response in the + // stream. + TransactionOptions new_transaction = 5; + + // Reads documents as they were at the given time. + // + // This must be a microsecond precision timestamp within the past one hour, + // or if Point-in-Time Recovery is enabled, can additionally be a whole + // minute timestamp within the past 7 days. + google.protobuf.Timestamp read_time = 7; + } +} + +// The streamed response for +// [Firestore.BatchGetDocuments][google.firestore.v1.Firestore.BatchGetDocuments]. +message BatchGetDocumentsResponse { + // A single result. + // This can be empty if the server is just returning a transaction. + oneof result { + // A document that was requested. + Document found = 1; + + // A document name that was requested but does not exist. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string missing = 2; + } + + // The transaction that was started as part of this request. + // Will only be set in the first response, and only if + // [BatchGetDocumentsRequest.new_transaction][google.firestore.v1.BatchGetDocumentsRequest.new_transaction] + // was set in the request. + bytes transaction = 3; + + // The time at which the document was read. + // This may be monotically increasing, in this case the previous documents in + // the result stream are guaranteed not to have changed between their + // read_time and this one. + google.protobuf.Timestamp read_time = 4; +} + +// The request for +// [Firestore.BeginTransaction][google.firestore.v1.Firestore.BeginTransaction]. +message BeginTransactionRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // The options for the transaction. + // Defaults to a read-write transaction. + TransactionOptions options = 2; +} + +// The response for +// [Firestore.BeginTransaction][google.firestore.v1.Firestore.BeginTransaction]. +message BeginTransactionResponse { + // The transaction that was started. + bytes transaction = 1; +} + +// The request for [Firestore.Commit][google.firestore.v1.Firestore.Commit]. +message CommitRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // The writes to apply. + // + // Always executed atomically and in order. + repeated Write writes = 2; + + // If set, applies all writes in this transaction, and commits it. + bytes transaction = 3; +} + +// The response for [Firestore.Commit][google.firestore.v1.Firestore.Commit]. +message CommitResponse { + // The result of applying the writes. + // + // This i-th write result corresponds to the i-th write in the + // request. + repeated WriteResult write_results = 1; + + // The time at which the commit occurred. Any read with an equal or greater + // `read_time` is guaranteed to see the effects of the commit. + google.protobuf.Timestamp commit_time = 2; +} + +// The request for [Firestore.Rollback][google.firestore.v1.Firestore.Rollback]. +message RollbackRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The transaction to roll back. + bytes transaction = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// The request for [Firestore.RunQuery][google.firestore.v1.Firestore.RunQuery]. +message RunQueryRequest { + // Required. The parent resource name. In the format: + // `projects/{project_id}/databases/{database_id}/documents` or + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + // For example: + // `projects/my-project/databases/my-database/documents` or + // `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // The query to run. + oneof query_type { + // A structured query. + StructuredQuery structured_query = 2; + } + + // The consistency mode for this transaction. + // If not set, defaults to strong consistency. + oneof consistency_selector { + // Run the query within an already active transaction. + // + // The value here is the opaque transaction ID to execute the query in. + bytes transaction = 5; + + // Starts a new transaction and reads the documents. + // Defaults to a read-only transaction. + // The new transaction ID will be returned as the first response in the + // stream. + TransactionOptions new_transaction = 6; + + // Reads documents as they were at the given time. + // + // This must be a microsecond precision timestamp within the past one hour, + // or if Point-in-Time Recovery is enabled, can additionally be a whole + // minute timestamp within the past 7 days. + google.protobuf.Timestamp read_time = 7; + } + + // Optional. Explain options for the query. If set, additional query + // statistics will be returned. If not, only query results will be returned. + ExplainOptions explain_options = 10 [(google.api.field_behavior) = OPTIONAL]; +} + +// The response for +// [Firestore.RunQuery][google.firestore.v1.Firestore.RunQuery]. +message RunQueryResponse { + // The transaction that was started as part of this request. + // Can only be set in the first response, and only if + // [RunQueryRequest.new_transaction][google.firestore.v1.RunQueryRequest.new_transaction] + // was set in the request. If set, no other fields will be set in this + // response. + bytes transaction = 2; + + // A query result, not set when reporting partial progress. + Document document = 1; + + // The time at which the document was read. This may be monotonically + // increasing; in this case, the previous documents in the result stream are + // guaranteed not to have changed between their `read_time` and this one. + // + // If the query returns no results, a response with `read_time` and no + // `document` will be sent, and this represents the time at which the query + // was run. + google.protobuf.Timestamp read_time = 3; + + // The number of results that have been skipped due to an offset between + // the last response and the current response. + int32 skipped_results = 4; + + // The continuation mode for the query. If present, it indicates the current + // query response stream has finished. This can be set with or without a + // `document` present, but when set, no more results are returned. + oneof continuation_selector { + // If present, Firestore has completely finished the request and no more + // documents will be returned. + bool done = 6; + } + + // Query explain metrics. This is only present when the + // [RunQueryRequest.explain_options][google.firestore.v1.RunQueryRequest.explain_options] + // is provided, and it is sent only once with the last response in the stream. + ExplainMetrics explain_metrics = 11; +} + +// The request for +// [Firestore.RunAggregationQuery][google.firestore.v1.Firestore.RunAggregationQuery]. +message RunAggregationQueryRequest { + // Required. The parent resource name. In the format: + // `projects/{project_id}/databases/{database_id}/documents` or + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + // For example: + // `projects/my-project/databases/my-database/documents` or + // `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // The query to run. + oneof query_type { + // An aggregation query. + StructuredAggregationQuery structured_aggregation_query = 2; + } + + // The consistency mode for the query, defaults to strong consistency. + oneof consistency_selector { + // Run the aggregation within an already active transaction. + // + // The value here is the opaque transaction ID to execute the query in. + bytes transaction = 4; + + // Starts a new transaction as part of the query, defaulting to read-only. + // + // The new transaction ID will be returned as the first response in the + // stream. + TransactionOptions new_transaction = 5; + + // Executes the query at the given timestamp. + // + // This must be a microsecond precision timestamp within the past one hour, + // or if Point-in-Time Recovery is enabled, can additionally be a whole + // minute timestamp within the past 7 days. + google.protobuf.Timestamp read_time = 6; + } + + // Optional. Explain options for the query. If set, additional query + // statistics will be returned. If not, only query results will be returned. + ExplainOptions explain_options = 8 [(google.api.field_behavior) = OPTIONAL]; +} + +// The response for +// [Firestore.RunAggregationQuery][google.firestore.v1.Firestore.RunAggregationQuery]. +message RunAggregationQueryResponse { + // A single aggregation result. + // + // Not present when reporting partial progress. + AggregationResult result = 1; + + // The transaction that was started as part of this request. + // + // Only present on the first response when the request requested to start + // a new transaction. + bytes transaction = 2; + + // The time at which the aggregate result was computed. This is always + // monotonically increasing; in this case, the previous AggregationResult in + // the result stream are guaranteed not to have changed between their + // `read_time` and this one. + // + // If the query returns no results, a response with `read_time` and no + // `result` will be sent, and this represents the time at which the query + // was run. + google.protobuf.Timestamp read_time = 3; + + // Query explain metrics. This is only present when the + // [RunAggregationQueryRequest.explain_options][google.firestore.v1.RunAggregationQueryRequest.explain_options] + // is provided, and it is sent only once with the last response in the stream. + ExplainMetrics explain_metrics = 10; +} + +// The request for +// [Firestore.PartitionQuery][google.firestore.v1.Firestore.PartitionQuery]. +message PartitionQueryRequest { + // Required. The parent resource name. In the format: + // `projects/{project_id}/databases/{database_id}/documents`. + // Document resource names are not supported; only database resource names + // can be specified. + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // The query to partition. + oneof query_type { + // A structured query. + // Query must specify collection with all descendants and be ordered by name + // ascending. Other filters, order bys, limits, offsets, and start/end + // cursors are not supported. + StructuredQuery structured_query = 2; + } + + // The desired maximum number of partition points. + // The partitions may be returned across multiple pages of results. + // The number must be positive. The actual number of partitions + // returned may be fewer. + // + // For example, this may be set to one fewer than the number of parallel + // queries to be run, or in running a data pipeline job, one fewer than the + // number of workers or compute instances available. + int64 partition_count = 3; + + // The `next_page_token` value returned from a previous call to + // PartitionQuery that may be used to get an additional set of results. + // There are no ordering guarantees between sets of results. Thus, using + // multiple sets of results will require merging the different result sets. + // + // For example, two subsequent calls using a page_token may return: + // + // * cursor B, cursor M, cursor Q + // * cursor A, cursor U, cursor W + // + // To obtain a complete result set ordered with respect to the results of the + // query supplied to PartitionQuery, the results sets should be merged: + // cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + string page_token = 4; + + // The maximum number of partitions to return in this call, subject to + // `partition_count`. + // + // For example, if `partition_count` = 10 and `page_size` = 8, the first call + // to PartitionQuery will return up to 8 partitions and a `next_page_token` + // if more results exist. A second call to PartitionQuery will return up to + // 2 partitions, to complete the total of 10 specified in `partition_count`. + int32 page_size = 5; + + // The consistency mode for this request. + // If not set, defaults to strong consistency. + oneof consistency_selector { + // Reads documents as they were at the given time. + // + // This must be a microsecond precision timestamp within the past one hour, + // or if Point-in-Time Recovery is enabled, can additionally be a whole + // minute timestamp within the past 7 days. + google.protobuf.Timestamp read_time = 6; + } +} + +// The response for +// [Firestore.PartitionQuery][google.firestore.v1.Firestore.PartitionQuery]. +message PartitionQueryResponse { + // Partition results. + // Each partition is a split point that can be used by RunQuery as a starting + // or end point for the query results. The RunQuery requests must be made with + // the same query supplied to this PartitionQuery request. The partition + // cursors will be ordered according to same ordering as the results of the + // query supplied to PartitionQuery. + // + // For example, if a PartitionQuery request returns partition cursors A and B, + // running the following three queries will return the entire result set of + // the original query: + // + // * query, end_at A + // * query, start_at A, end_at B + // * query, start_at B + // + // An empty result may indicate that the query has too few results to be + // partitioned, or that the query is not yet supported for partitioning. + repeated Cursor partitions = 1; + + // A page token that may be used to request an additional set of results, up + // to the number specified by `partition_count` in the PartitionQuery request. + // If blank, there are no more results. + string next_page_token = 2; +} + +// The request for [Firestore.Write][google.firestore.v1.Firestore.Write]. +// +// The first request creates a stream, or resumes an existing one from a token. +// +// When creating a new stream, the server replies with a response containing +// only an ID and a token, to use in the next request. +// +// When resuming a stream, the server first streams any responses later than the +// given token, then a response containing only an up-to-date token, to use in +// the next request. +message WriteRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + // This is only required in the first message. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // The ID of the write stream to resume. + // This may only be set in the first message. When left empty, a new write + // stream will be created. + string stream_id = 2; + + // The writes to apply. + // + // Always executed atomically and in order. + // This must be empty on the first request. + // This may be empty on the last request. + // This must not be empty on all other requests. + repeated Write writes = 3; + + // A stream token that was previously sent by the server. + // + // The client should set this field to the token from the most recent + // [WriteResponse][google.firestore.v1.WriteResponse] it has received. This + // acknowledges that the client has received responses up to this token. After + // sending this token, earlier tokens may not be used anymore. + // + // The server may close the stream if there are too many unacknowledged + // responses. + // + // Leave this field unset when creating a new stream. To resume a stream at + // a specific point, set this field and the `stream_id` field. + // + // Leave this field unset when creating a new stream. + bytes stream_token = 4; + + // Labels associated with this write request. + map labels = 5; +} + +// The response for [Firestore.Write][google.firestore.v1.Firestore.Write]. +message WriteResponse { + // The ID of the stream. + // Only set on the first message, when a new stream was created. + string stream_id = 1; + + // A token that represents the position of this response in the stream. + // This can be used by a client to resume the stream at this point. + // + // This field is always set. + bytes stream_token = 2; + + // The result of applying the writes. + // + // This i-th write result corresponds to the i-th write in the + // request. + repeated WriteResult write_results = 3; + + // The time at which the commit occurred. Any read with an equal or greater + // `read_time` is guaranteed to see the effects of the write. + google.protobuf.Timestamp commit_time = 4; +} + +// A request for [Firestore.Listen][google.firestore.v1.Firestore.Listen] +message ListenRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // The supported target changes. + oneof target_change { + // A target to add to this stream. + Target add_target = 2; + + // The ID of a target to remove from this stream. + int32 remove_target = 3; + } + + // Labels associated with this target change. + map labels = 4; +} + +// The response for [Firestore.Listen][google.firestore.v1.Firestore.Listen]. +message ListenResponse { + // The supported responses. + oneof response_type { + // Targets have changed. + TargetChange target_change = 2; + + // A [Document][google.firestore.v1.Document] has changed. + DocumentChange document_change = 3; + + // A [Document][google.firestore.v1.Document] has been deleted. + DocumentDelete document_delete = 4; + + // A [Document][google.firestore.v1.Document] has been removed from a target + // (because it is no longer relevant to that target). + DocumentRemove document_remove = 6; + + // A filter to apply to the set of documents previously returned for the + // given target. + // + // Returned when documents may have been removed from the given target, but + // the exact documents are unknown. + ExistenceFilter filter = 5; + } +} + +// A specification of a set of documents to listen to. +message Target { + // A target specified by a set of documents names. + message DocumentsTarget { + // The names of the documents to retrieve. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + // The request will fail if any of the document is not a child resource of + // the given `database`. Duplicate names will be elided. + repeated string documents = 2; + } + + // A target specified by a query. + message QueryTarget { + // The parent resource name. In the format: + // `projects/{project_id}/databases/{database_id}/documents` or + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + // For example: + // `projects/my-project/databases/my-database/documents` or + // `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + string parent = 1; + + // The query to run. + oneof query_type { + // A structured query. + StructuredQuery structured_query = 2; + } + } + + // The type of target to listen to. + oneof target_type { + // A target specified by a query. + QueryTarget query = 2; + + // A target specified by a set of document names. + DocumentsTarget documents = 3; + } + + // When to start listening. + // + // If specified, only the matching Documents that have been updated AFTER the + // `resume_token` or `read_time` will be returned. Otherwise, all matching + // Documents are returned before any subsequent changes. + oneof resume_type { + // A resume token from a prior + // [TargetChange][google.firestore.v1.TargetChange] for an identical target. + // + // Using a resume token with a different target is unsupported and may fail. + bytes resume_token = 4; + + // Start listening after a specific `read_time`. + // + // The client must know the state of matching documents at this time. + google.protobuf.Timestamp read_time = 11; + } + + // The target ID that identifies the target on the stream. Must be a positive + // number and non-zero. + // + // If `target_id` is 0 (or unspecified), the server will assign an ID for this + // target and return that in a `TargetChange::ADD` event. Once a target with + // `target_id=0` is added, all subsequent targets must also have + // `target_id=0`. If an `AddTarget` request with `target_id != 0` is + // sent to the server after a target with `target_id=0` is added, the server + // will immediately send a response with a `TargetChange::Remove` event. + // + // Note that if the client sends multiple `AddTarget` requests + // without an ID, the order of IDs returned in `TargetChage.target_ids` are + // undefined. Therefore, clients should provide a target ID instead of relying + // on the server to assign one. + // + // If `target_id` is non-zero, there must not be an existing active target on + // this stream with the same ID. + int32 target_id = 5; + + // If the target should be removed once it is current and consistent. + bool once = 6; + + // The number of documents that last matched the query at the resume token or + // read time. + // + // This value is only relevant when a `resume_type` is provided. This value + // being present and greater than zero signals that the client wants + // `ExistenceFilter.unchanged_names` to be included in the response. + google.protobuf.Int32Value expected_count = 12; +} + +// Targets being watched have changed. +message TargetChange { + // The type of change. + enum TargetChangeType { + // No change has occurred. Used only to send an updated `resume_token`. + NO_CHANGE = 0; + + // The targets have been added. + ADD = 1; + + // The targets have been removed. + REMOVE = 2; + + // The targets reflect all changes committed before the targets were added + // to the stream. + // + // This will be sent after or with a `read_time` that is greater than or + // equal to the time at which the targets were added. + // + // Listeners can wait for this change if read-after-write semantics + // are desired. + CURRENT = 3; + + // The targets have been reset, and a new initial state for the targets + // will be returned in subsequent changes. + // + // After the initial state is complete, `CURRENT` will be returned even + // if the target was previously indicated to be `CURRENT`. + RESET = 4; + } + + // The type of change that occurred. + TargetChangeType target_change_type = 1; + + // The target IDs of targets that have changed. + // + // If empty, the change applies to all targets. + // + // The order of the target IDs is not defined. + repeated int32 target_ids = 2; + + // The error that resulted in this change, if applicable. + google.rpc.Status cause = 3; + + // A token that can be used to resume the stream for the given `target_ids`, + // or all targets if `target_ids` is empty. + // + // Not set on every target change. + bytes resume_token = 4; + + // The consistent `read_time` for the given `target_ids` (omitted when the + // target_ids are not at a consistent snapshot). + // + // The stream is guaranteed to send a `read_time` with `target_ids` empty + // whenever the entire stream reaches a new consistent snapshot. ADD, + // CURRENT, and RESET messages are guaranteed to (eventually) result in a + // new consistent snapshot (while NO_CHANGE and REMOVE messages are not). + // + // For a given stream, `read_time` is guaranteed to be monotonically + // increasing. + google.protobuf.Timestamp read_time = 6; +} + +// The request for +// [Firestore.ListCollectionIds][google.firestore.v1.Firestore.ListCollectionIds]. +message ListCollectionIdsRequest { + // Required. The parent document. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + // For example: + // `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // The maximum number of results to return. + int32 page_size = 2; + + // A page token. Must be a value from + // [ListCollectionIdsResponse][google.firestore.v1.ListCollectionIdsResponse]. + string page_token = 3; + + // The consistency mode for this request. + // If not set, defaults to strong consistency. + oneof consistency_selector { + // Reads documents as they were at the given time. + // + // This must be a microsecond precision timestamp within the past one hour, + // or if Point-in-Time Recovery is enabled, can additionally be a whole + // minute timestamp within the past 7 days. + google.protobuf.Timestamp read_time = 4; + } +} + +// The response from +// [Firestore.ListCollectionIds][google.firestore.v1.Firestore.ListCollectionIds]. +message ListCollectionIdsResponse { + // The collection ids. + repeated string collection_ids = 1; + + // A page token that may be used to continue the list. + string next_page_token = 2; +} + +// The request for +// [Firestore.BatchWrite][google.firestore.v1.Firestore.BatchWrite]. +message BatchWriteRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // The writes to apply. + // + // Method does not apply writes atomically and does not guarantee ordering. + // Each write succeeds or fails independently. You cannot write to the same + // document more than once per request. + repeated Write writes = 2; + + // Labels associated with this batch write. + map labels = 3; +} + +// The response from +// [Firestore.BatchWrite][google.firestore.v1.Firestore.BatchWrite]. +message BatchWriteResponse { + // The result of applying the writes. + // + // This i-th write result corresponds to the i-th write in the + // request. + repeated WriteResult write_results = 1; + + // The status of applying the writes. + // + // This i-th write status corresponds to the i-th write in the + // request. + repeated google.rpc.Status status = 2; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/query.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/query.proto new file mode 100644 index 0000000..3b22800 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/query.proto @@ -0,0 +1,589 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1; + +import "google/api/field_behavior.proto"; +import "google/firestore/v1/document.proto"; +import "google/protobuf/wrappers.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "QueryProto"; +option java_package = "com.google.firestore.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; + +// A Firestore query. +// +// The query stages are executed in the following order: +// 1. from +// 2. where +// 3. select +// 4. order_by + start_at + end_at +// 5. offset +// 6. limit +message StructuredQuery { + // A selection of a collection, such as `messages as m1`. + message CollectionSelector { + // The collection ID. + // When set, selects only collections with this ID. + string collection_id = 2; + + // When false, selects only collections that are immediate children of + // the `parent` specified in the containing `RunQueryRequest`. + // When true, selects all descendant collections. + bool all_descendants = 3; + } + + // A filter. + message Filter { + // The type of filter. + oneof filter_type { + // A composite filter. + CompositeFilter composite_filter = 1; + + // A filter on a document field. + FieldFilter field_filter = 2; + + // A filter that takes exactly one argument. + UnaryFilter unary_filter = 3; + } + } + + // A filter that merges multiple other filters using the given operator. + message CompositeFilter { + // A composite filter operator. + enum Operator { + // Unspecified. This value must not be used. + OPERATOR_UNSPECIFIED = 0; + + // Documents are required to satisfy all of the combined filters. + AND = 1; + + // Documents are required to satisfy at least one of the combined filters. + OR = 2; + } + + // The operator for combining multiple filters. + Operator op = 1; + + // The list of filters to combine. + // + // Requires: + // + // * At least one filter is present. + repeated Filter filters = 2; + } + + // A filter on a specific field. + message FieldFilter { + // A field filter operator. + enum Operator { + // Unspecified. This value must not be used. + OPERATOR_UNSPECIFIED = 0; + + // The given `field` is less than the given `value`. + // + // Requires: + // + // * That `field` come first in `order_by`. + LESS_THAN = 1; + + // The given `field` is less than or equal to the given `value`. + // + // Requires: + // + // * That `field` come first in `order_by`. + LESS_THAN_OR_EQUAL = 2; + + // The given `field` is greater than the given `value`. + // + // Requires: + // + // * That `field` come first in `order_by`. + GREATER_THAN = 3; + + // The given `field` is greater than or equal to the given `value`. + // + // Requires: + // + // * That `field` come first in `order_by`. + GREATER_THAN_OR_EQUAL = 4; + + // The given `field` is equal to the given `value`. + EQUAL = 5; + + // The given `field` is not equal to the given `value`. + // + // Requires: + // + // * No other `NOT_EQUAL`, `NOT_IN`, `IS_NOT_NULL`, or `IS_NOT_NAN`. + // * That `field` comes first in the `order_by`. + NOT_EQUAL = 6; + + // The given `field` is an array that contains the given `value`. + ARRAY_CONTAINS = 7; + + // The given `field` is equal to at least one value in the given array. + // + // Requires: + // + // * That `value` is a non-empty `ArrayValue`, subject to disjunction + // limits. + // * No `NOT_IN` filters in the same query. + IN = 8; + + // The given `field` is an array that contains any of the values in the + // given array. + // + // Requires: + // + // * That `value` is a non-empty `ArrayValue`, subject to disjunction + // limits. + // * No other `ARRAY_CONTAINS_ANY` filters within the same disjunction. + // * No `NOT_IN` filters in the same query. + ARRAY_CONTAINS_ANY = 9; + + // The value of the `field` is not in the given array. + // + // Requires: + // + // * That `value` is a non-empty `ArrayValue` with at most 10 values. + // * No other `OR`, `IN`, `ARRAY_CONTAINS_ANY`, `NOT_IN`, `NOT_EQUAL`, + // `IS_NOT_NULL`, or `IS_NOT_NAN`. + // * That `field` comes first in the `order_by`. + NOT_IN = 10; + } + + // The field to filter by. + FieldReference field = 1; + + // The operator to filter by. + Operator op = 2; + + // The value to compare to. + Value value = 3; + } + + // A filter with a single operand. + message UnaryFilter { + // A unary operator. + enum Operator { + // Unspecified. This value must not be used. + OPERATOR_UNSPECIFIED = 0; + + // The given `field` is equal to `NaN`. + IS_NAN = 2; + + // The given `field` is equal to `NULL`. + IS_NULL = 3; + + // The given `field` is not equal to `NaN`. + // + // Requires: + // + // * No other `NOT_EQUAL`, `NOT_IN`, `IS_NOT_NULL`, or `IS_NOT_NAN`. + // * That `field` comes first in the `order_by`. + IS_NOT_NAN = 4; + + // The given `field` is not equal to `NULL`. + // + // Requires: + // + // * A single `NOT_EQUAL`, `NOT_IN`, `IS_NOT_NULL`, or `IS_NOT_NAN`. + // * That `field` comes first in the `order_by`. + IS_NOT_NULL = 5; + } + + // The unary operator to apply. + Operator op = 1; + + // The argument to the filter. + oneof operand_type { + // The field to which to apply the operator. + FieldReference field = 2; + } + } + + // An order on a field. + message Order { + // The field to order by. + FieldReference field = 1; + + // The direction to order by. Defaults to `ASCENDING`. + Direction direction = 2; + } + + // A sort direction. + enum Direction { + // Unspecified. + DIRECTION_UNSPECIFIED = 0; + + // Ascending. + ASCENDING = 1; + + // Descending. + DESCENDING = 2; + } + + // A reference to a field in a document, ex: `stats.operations`. + message FieldReference { + // A reference to a field in a document. + // + // Requires: + // + // * MUST be a dot-delimited (`.`) string of segments, where each segment + // conforms to [document field name][google.firestore.v1.Document.fields] + // limitations. + string field_path = 2; + } + + // The projection of document's fields to return. + message Projection { + // The fields to return. + // + // If empty, all fields are returned. To only return the name + // of the document, use `['__name__']`. + repeated FieldReference fields = 2; + } + + // Nearest Neighbors search config. The ordering provided by FindNearest + // supersedes the order_by stage. If multiple documents have the same vector + // distance, the returned document order is not guaranteed to be stable + // between queries. + message FindNearest { + // The distance measure to use when comparing vectors. + enum DistanceMeasure { + // Should not be set. + DISTANCE_MEASURE_UNSPECIFIED = 0; + + // Measures the EUCLIDEAN distance between the vectors. See + // [Euclidean](https://en.wikipedia.org/wiki/Euclidean_distance) to learn + // more. The resulting distance decreases the more similar two vectors + // are. + EUCLIDEAN = 1; + + // COSINE distance compares vectors based on the angle between them, which + // allows you to measure similarity that isn't based on the vectors + // magnitude. We recommend using DOT_PRODUCT with unit normalized vectors + // instead of COSINE distance, which is mathematically equivalent with + // better performance. See [Cosine + // Similarity](https://en.wikipedia.org/wiki/Cosine_similarity) to learn + // more about COSINE similarity and COSINE distance. The resulting + // COSINE distance decreases the more similar two vectors are. + COSINE = 2; + + // Similar to cosine but is affected by the magnitude of the vectors. See + // [Dot Product](https://en.wikipedia.org/wiki/Dot_product) to learn more. + // The resulting distance increases the more similar two vectors are. + DOT_PRODUCT = 3; + } + + // Required. An indexed vector field to search upon. Only documents which + // contain vectors whose dimensionality match the query_vector can be + // returned. + FieldReference vector_field = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The query vector that we are searching on. Must be a vector of + // no more than 2048 dimensions. + Value query_vector = 2 [(google.api.field_behavior) = REQUIRED]; + + // Required. The distance measure to use, required. + DistanceMeasure distance_measure = 3 + [(google.api.field_behavior) = REQUIRED]; + + // Required. The number of nearest neighbors to return. Must be a positive + // integer of no more than 1000. + google.protobuf.Int32Value limit = 4 + [(google.api.field_behavior) = REQUIRED]; + + // Optional. Optional name of the field to output the result of the vector + // distance calculation. Must conform to [document field + // name][google.firestore.v1.Document.fields] limitations. + string distance_result_field = 5 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Option to specify a threshold for which no less similar + // documents will be returned. The behavior of the specified + // `distance_measure` will affect the meaning of the distance threshold. + // Since DOT_PRODUCT distances increase when the vectors are more similar, + // the comparison is inverted. + // + // For EUCLIDEAN, COSINE: WHERE distance <= distance_threshold + // For DOT_PRODUCT: WHERE distance >= distance_threshold + google.protobuf.DoubleValue distance_threshold = 6 + [(google.api.field_behavior) = OPTIONAL]; + } + + // Optional sub-set of the fields to return. + // + // This acts as a [DocumentMask][google.firestore.v1.DocumentMask] over the + // documents returned from a query. When not set, assumes that the caller + // wants all fields returned. + Projection select = 1; + + // The collections to query. + repeated CollectionSelector from = 2; + + // The filter to apply. + Filter where = 3; + + // The order to apply to the query results. + // + // Firestore allows callers to provide a full ordering, a partial ordering, or + // no ordering at all. In all cases, Firestore guarantees a stable ordering + // through the following rules: + // + // * The `order_by` is required to reference all fields used with an + // inequality filter. + // * All fields that are required to be in the `order_by` but are not already + // present are appended in lexicographical ordering of the field name. + // * If an order on `__name__` is not specified, it is appended by default. + // + // Fields are appended with the same sort direction as the last order + // specified, or 'ASCENDING' if no order was specified. For example: + // + // * `ORDER BY a` becomes `ORDER BY a ASC, __name__ ASC` + // * `ORDER BY a DESC` becomes `ORDER BY a DESC, __name__ DESC` + // * `WHERE a > 1` becomes `WHERE a > 1 ORDER BY a ASC, __name__ ASC` + // * `WHERE __name__ > ... AND a > 1` becomes + // `WHERE __name__ > ... AND a > 1 ORDER BY a ASC, __name__ ASC` + repeated Order order_by = 4; + + // A potential prefix of a position in the result set to start the query at. + // + // The ordering of the result set is based on the `ORDER BY` clause of the + // original query. + // + // ``` + // SELECT * FROM k WHERE a = 1 AND b > 2 ORDER BY b ASC, __name__ ASC; + // ``` + // + // This query's results are ordered by `(b ASC, __name__ ASC)`. + // + // Cursors can reference either the full ordering or a prefix of the location, + // though it cannot reference more fields than what are in the provided + // `ORDER BY`. + // + // Continuing off the example above, attaching the following start cursors + // will have varying impact: + // + // - `START BEFORE (2, /k/123)`: start the query right before `a = 1 AND + // b > 2 AND __name__ > /k/123`. + // - `START AFTER (10)`: start the query right after `a = 1 AND b > 10`. + // + // Unlike `OFFSET` which requires scanning over the first N results to skip, + // a start cursor allows the query to begin at a logical position. This + // position is not required to match an actual result, it will scan forward + // from this position to find the next document. + // + // Requires: + // + // * The number of values cannot be greater than the number of fields + // specified in the `ORDER BY` clause. + Cursor start_at = 7; + + // A potential prefix of a position in the result set to end the query at. + // + // This is similar to `START_AT` but with it controlling the end position + // rather than the start position. + // + // Requires: + // + // * The number of values cannot be greater than the number of fields + // specified in the `ORDER BY` clause. + Cursor end_at = 8; + + // The number of documents to skip before returning the first result. + // + // This applies after the constraints specified by the `WHERE`, `START AT`, & + // `END AT` but before the `LIMIT` clause. + // + // Requires: + // + // * The value must be greater than or equal to zero if specified. + int32 offset = 6; + + // The maximum number of results to return. + // + // Applies after all other constraints. + // + // Requires: + // + // * The value must be greater than or equal to zero if specified. + google.protobuf.Int32Value limit = 5; + + // Optional. A potential nearest neighbors search. + // + // Applies after all other filters and ordering. + // + // Finds the closest vector embeddings to the given query vector. + FindNearest find_nearest = 9 [(google.api.field_behavior) = OPTIONAL]; +} + +// Firestore query for running an aggregation over a +// [StructuredQuery][google.firestore.v1.StructuredQuery]. +message StructuredAggregationQuery { + // Defines an aggregation that produces a single result. + message Aggregation { + // Count of documents that match the query. + // + // The `COUNT(*)` aggregation function operates on the entire document + // so it does not require a field reference. + message Count { + // Optional. Optional constraint on the maximum number of documents to + // count. + // + // This provides a way to set an upper bound on the number of documents + // to scan, limiting latency, and cost. + // + // Unspecified is interpreted as no bound. + // + // High-Level Example: + // + // ``` + // AGGREGATE COUNT_UP_TO(1000) OVER ( SELECT * FROM k ); + // ``` + // + // Requires: + // + // * Must be greater than zero when present. + google.protobuf.Int64Value up_to = 1 + [(google.api.field_behavior) = OPTIONAL]; + } + + // Sum of the values of the requested field. + // + // * Only numeric values will be aggregated. All non-numeric values + // including `NULL` are skipped. + // + // * If the aggregated values contain `NaN`, returns `NaN`. Infinity math + // follows IEEE-754 standards. + // + // * If the aggregated value set is empty, returns 0. + // + // * Returns a 64-bit integer if all aggregated numbers are integers and the + // sum result does not overflow. Otherwise, the result is returned as a + // double. Note that even if all the aggregated values are integers, the + // result is returned as a double if it cannot fit within a 64-bit signed + // integer. When this occurs, the returned value will lose precision. + // + // * When underflow occurs, floating-point aggregation is non-deterministic. + // This means that running the same query repeatedly without any changes to + // the underlying values could produce slightly different results each + // time. In those cases, values should be stored as integers over + // floating-point numbers. + message Sum { + // The field to aggregate on. + StructuredQuery.FieldReference field = 1; + } + + // Average of the values of the requested field. + // + // * Only numeric values will be aggregated. All non-numeric values + // including `NULL` are skipped. + // + // * If the aggregated values contain `NaN`, returns `NaN`. Infinity math + // follows IEEE-754 standards. + // + // * If the aggregated value set is empty, returns `NULL`. + // + // * Always returns the result as a double. + message Avg { + // The field to aggregate on. + StructuredQuery.FieldReference field = 1; + } + + // The type of aggregation to perform, required. + oneof operator { + // Count aggregator. + Count count = 1; + + // Sum aggregator. + Sum sum = 2; + + // Average aggregator. + Avg avg = 3; + } + + // Optional. Optional name of the field to store the result of the + // aggregation into. + // + // If not provided, Firestore will pick a default name following the format + // `field_`. For example: + // + // ``` + // AGGREGATE + // COUNT_UP_TO(1) AS count_up_to_1, + // COUNT_UP_TO(2), + // COUNT_UP_TO(3) AS count_up_to_3, + // COUNT(*) + // OVER ( + // ... + // ); + // ``` + // + // becomes: + // + // ``` + // AGGREGATE + // COUNT_UP_TO(1) AS count_up_to_1, + // COUNT_UP_TO(2) AS field_1, + // COUNT_UP_TO(3) AS count_up_to_3, + // COUNT(*) AS field_2 + // OVER ( + // ... + // ); + // ``` + // + // Requires: + // + // * Must be unique across all aggregation aliases. + // * Conform to [document field name][google.firestore.v1.Document.fields] + // limitations. + string alias = 7 [(google.api.field_behavior) = OPTIONAL]; + } + + // The base query to aggregate over. + oneof query_type { + // Nested structured query. + StructuredQuery structured_query = 1; + } + + // Optional. Series of aggregations to apply over the results of the + // `structured_query`. + // + // Requires: + // + // * A minimum of one and maximum of five aggregations per query. + repeated Aggregation aggregations = 3 + [(google.api.field_behavior) = OPTIONAL]; +} + +// A position in a query result set. +message Cursor { + // The values that represent a position, in the order they appear in + // the order by clause of a query. + // + // Can contain fewer values than specified in the order by clause. + repeated Value values = 1; + + // If the position is just before or just after the given values, relative + // to the sort order defined by the query. + bool before = 2; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/query_profile.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/query_profile.proto new file mode 100644 index 0000000..de27144 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/query_profile.proto @@ -0,0 +1,92 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1; + +import "google/api/field_behavior.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/struct.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "QueryProfileProto"; +option java_package = "com.google.firestore.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; + +// Specification of the Firestore Query Profile fields. + +// Explain options for the query. +message ExplainOptions { + // Optional. Whether to execute this query. + // + // When false (the default), the query will be planned, returning only + // metrics from the planning stages. + // + // When true, the query will be planned and executed, returning the full + // query results along with both planning and execution stage metrics. + bool analyze = 1 [(google.api.field_behavior) = OPTIONAL]; +} + +// Explain metrics for the query. +message ExplainMetrics { + // Planning phase information for the query. + PlanSummary plan_summary = 1; + + // Aggregated stats from the execution of the query. Only present when + // [ExplainOptions.analyze][google.firestore.v1.ExplainOptions.analyze] is set + // to true. + ExecutionStats execution_stats = 2; +} + +// Planning phase information for the query. +message PlanSummary { + // The indexes selected for the query. For example: + // [ + // {"query_scope": "Collection", "properties": "(foo ASC, __name__ ASC)"}, + // {"query_scope": "Collection", "properties": "(bar ASC, __name__ ASC)"} + // ] + repeated google.protobuf.Struct indexes_used = 1; +} + +// Execution statistics for the query. +message ExecutionStats { + // Total number of results returned, including documents, projections, + // aggregation results, keys. + int64 results_returned = 1; + + // Total time to execute the query in the backend. + google.protobuf.Duration execution_duration = 3; + + // Total billable read operations. + int64 read_operations = 4; + + // Debugging statistics from the execution of the query. Note that the + // debugging stats are subject to change as Firestore evolves. It could + // include: + // { + // "indexes_entries_scanned": "1000", + // "documents_scanned": "20", + // "billing_details" : { + // "documents_billable": "20", + // "index_entries_billable": "1000", + // "min_query_cost": "0" + // } + // } + google.protobuf.Struct debug_stats = 5; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/write.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/write.proto new file mode 100644 index 0000000..fca7fab --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1/write.proto @@ -0,0 +1,286 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1; + +import "google/firestore/v1/bloom_filter.proto"; +import "google/firestore/v1/common.proto"; +import "google/firestore/v1/document.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "WriteProto"; +option java_package = "com.google.firestore.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; + +// A write on a document. +message Write { + // The operation to execute. + oneof operation { + // A document to write. + Document update = 1; + + // A document name to delete. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string delete = 2; + + // Applies a transformation to a document. + DocumentTransform transform = 6; + } + + // The fields to update in this write. + // + // This field can be set only when the operation is `update`. + // If the mask is not set for an `update` and the document exists, any + // existing data will be overwritten. + // If the mask is set and the document on the server has fields not covered by + // the mask, they are left unchanged. + // Fields referenced in the mask, but not present in the input document, are + // deleted from the document on the server. + // The field paths in this mask must not contain a reserved field name. + DocumentMask update_mask = 3; + + // The transforms to perform after update. + // + // This field can be set only when the operation is `update`. If present, this + // write is equivalent to performing `update` and `transform` to the same + // document atomically and in order. + repeated DocumentTransform.FieldTransform update_transforms = 7; + + // An optional precondition on the document. + // + // The write will fail if this is set and not met by the target document. + Precondition current_document = 4; +} + +// A transformation of a document. +message DocumentTransform { + // A transformation of a field of the document. + message FieldTransform { + // A value that is calculated by the server. + enum ServerValue { + // Unspecified. This value must not be used. + SERVER_VALUE_UNSPECIFIED = 0; + + // The time at which the server processed the request, with millisecond + // precision. If used on multiple fields (same or different documents) in + // a transaction, all the fields will get the same server timestamp. + REQUEST_TIME = 1; + } + + // The path of the field. See + // [Document.fields][google.firestore.v1.Document.fields] for the field path + // syntax reference. + string field_path = 1; + + // The transformation to apply on the field. + oneof transform_type { + // Sets the field to the given server value. + ServerValue set_to_server_value = 2; + + // Adds the given value to the field's current value. + // + // This must be an integer or a double value. + // If the field is not an integer or double, or if the field does not yet + // exist, the transformation will set the field to the given value. + // If either of the given value or the current field value are doubles, + // both values will be interpreted as doubles. Double arithmetic and + // representation of double values follow IEEE 754 semantics. + // If there is positive/negative integer overflow, the field is resolved + // to the largest magnitude positive/negative integer. + Value increment = 3; + + // Sets the field to the maximum of its current value and the given value. + // + // This must be an integer or a double value. + // If the field is not an integer or double, or if the field does not yet + // exist, the transformation will set the field to the given value. + // If a maximum operation is applied where the field and the input value + // are of mixed types (that is - one is an integer and one is a double) + // the field takes on the type of the larger operand. If the operands are + // equivalent (e.g. 3 and 3.0), the field does not change. + // 0, 0.0, and -0.0 are all zero. The maximum of a zero stored value and + // zero input value is always the stored value. + // The maximum of any numeric value x and NaN is NaN. + Value maximum = 4; + + // Sets the field to the minimum of its current value and the given value. + // + // This must be an integer or a double value. + // If the field is not an integer or double, or if the field does not yet + // exist, the transformation will set the field to the input value. + // If a minimum operation is applied where the field and the input value + // are of mixed types (that is - one is an integer and one is a double) + // the field takes on the type of the smaller operand. If the operands are + // equivalent (e.g. 3 and 3.0), the field does not change. + // 0, 0.0, and -0.0 are all zero. The minimum of a zero stored value and + // zero input value is always the stored value. + // The minimum of any numeric value x and NaN is NaN. + Value minimum = 5; + + // Append the given elements in order if they are not already present in + // the current field value. + // If the field is not an array, or if the field does not yet exist, it is + // first set to the empty array. + // + // Equivalent numbers of different types (e.g. 3L and 3.0) are + // considered equal when checking if a value is missing. + // NaN is equal to NaN, and Null is equal to Null. + // If the input contains multiple equivalent values, only the first will + // be considered. + // + // The corresponding transform_result will be the null value. + ArrayValue append_missing_elements = 6; + + // Remove all of the given elements from the array in the field. + // If the field is not an array, or if the field does not yet exist, it is + // set to the empty array. + // + // Equivalent numbers of the different types (e.g. 3L and 3.0) are + // considered equal when deciding whether an element should be removed. + // NaN is equal to NaN, and Null is equal to Null. + // This will remove all equivalent values if there are duplicates. + // + // The corresponding transform_result will be the null value. + ArrayValue remove_all_from_array = 7; + } + } + + // The name of the document to transform. + string document = 1; + + // The list of transformations to apply to the fields of the document, in + // order. + // This must not be empty. + repeated FieldTransform field_transforms = 2; +} + +// The result of applying a write. +message WriteResult { + // The last update time of the document after applying the write. Not set + // after a `delete`. + // + // If the write did not actually change the document, this will be the + // previous update_time. + google.protobuf.Timestamp update_time = 1; + + // The results of applying each + // [DocumentTransform.FieldTransform][google.firestore.v1.DocumentTransform.FieldTransform], + // in the same order. + repeated Value transform_results = 2; +} + +// A [Document][google.firestore.v1.Document] has changed. +// +// May be the result of multiple [writes][google.firestore.v1.Write], including +// deletes, that ultimately resulted in a new value for the +// [Document][google.firestore.v1.Document]. +// +// Multiple [DocumentChange][google.firestore.v1.DocumentChange] messages may be +// returned for the same logical change, if multiple targets are affected. +message DocumentChange { + // The new state of the [Document][google.firestore.v1.Document]. + // + // If `mask` is set, contains only fields that were updated or added. + Document document = 1; + + // A set of target IDs of targets that match this document. + repeated int32 target_ids = 5; + + // A set of target IDs for targets that no longer match this document. + repeated int32 removed_target_ids = 6; +} + +// A [Document][google.firestore.v1.Document] has been deleted. +// +// May be the result of multiple [writes][google.firestore.v1.Write], including +// updates, the last of which deleted the +// [Document][google.firestore.v1.Document]. +// +// Multiple [DocumentDelete][google.firestore.v1.DocumentDelete] messages may be +// returned for the same logical delete, if multiple targets are affected. +message DocumentDelete { + // The resource name of the [Document][google.firestore.v1.Document] that was + // deleted. + string document = 1; + + // A set of target IDs for targets that previously matched this entity. + repeated int32 removed_target_ids = 6; + + // The read timestamp at which the delete was observed. + // + // Greater or equal to the `commit_time` of the delete. + google.protobuf.Timestamp read_time = 4; +} + +// A [Document][google.firestore.v1.Document] has been removed from the view of +// the targets. +// +// Sent if the document is no longer relevant to a target and is out of view. +// Can be sent instead of a DocumentDelete or a DocumentChange if the server +// can not send the new value of the document. +// +// Multiple [DocumentRemove][google.firestore.v1.DocumentRemove] messages may be +// returned for the same logical write or delete, if multiple targets are +// affected. +message DocumentRemove { + // The resource name of the [Document][google.firestore.v1.Document] that has + // gone out of view. + string document = 1; + + // A set of target IDs for targets that previously matched this document. + repeated int32 removed_target_ids = 2; + + // The read timestamp at which the remove was observed. + // + // Greater or equal to the `commit_time` of the change/delete/remove. + google.protobuf.Timestamp read_time = 4; +} + +// A digest of all the documents that match a given target. +message ExistenceFilter { + // The target ID to which this filter applies. + int32 target_id = 1; + + // The total count of documents that match + // [target_id][google.firestore.v1.ExistenceFilter.target_id]. + // + // If different from the count of documents in the client that match, the + // client must manually determine which documents no longer match the target. + // + // The client can use the `unchanged_names` bloom filter to assist with + // this determination by testing ALL the document names against the filter; + // if the document name is NOT in the filter, it means the document no + // longer matches the target. + int32 count = 2; + + // A bloom filter that, despite its name, contains the UTF-8 byte encodings of + // the resource names of ALL the documents that match + // [target_id][google.firestore.v1.ExistenceFilter.target_id], in the form + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + // + // This bloom filter may be omitted at the server's discretion, such as if it + // is deemed that the client will not make use of it or if it is too + // computationally expensive to calculate or transmit. Clients must gracefully + // handle this field being absent by falling back to the logic used before + // this field existed; that is, re-add the target without a resume token to + // figure out which documents in the client's cache are out of sync. + BloomFilter unchanged_names = 3; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/common.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/common.proto new file mode 100644 index 0000000..0418e82 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/common.proto @@ -0,0 +1,82 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1beta1; + +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1Beta1"; +option go_package = "cloud.google.com/go/firestore/apiv1beta1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "CommonProto"; +option java_package = "com.google.firestore.v1beta1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1beta1"; +option ruby_package = "Google::Cloud::Firestore::V1beta1"; + +// A set of field paths on a document. +// Used to restrict a get or update operation on a document to a subset of its +// fields. +// This is different from standard field masks, as this is always scoped to a +// [Document][google.firestore.v1beta1.Document], and takes in account the dynamic nature of [Value][google.firestore.v1beta1.Value]. +message DocumentMask { + // The list of field paths in the mask. See [Document.fields][google.firestore.v1beta1.Document.fields] for a field + // path syntax reference. + repeated string field_paths = 1; +} + +// A precondition on a document, used for conditional operations. +message Precondition { + // The type of precondition. + oneof condition_type { + // When set to `true`, the target document must exist. + // When set to `false`, the target document must not exist. + bool exists = 1; + + // When set, the target document must exist and have been last updated at + // that time. + google.protobuf.Timestamp update_time = 2; + } +} + +// Options for creating a new transaction. +message TransactionOptions { + // Options for a transaction that can be used to read and write documents. + message ReadWrite { + // An optional transaction to retry. + bytes retry_transaction = 1; + } + + // Options for a transaction that can only be used to read documents. + message ReadOnly { + // The consistency mode for this transaction. If not set, defaults to strong + // consistency. + oneof consistency_selector { + // Reads documents at the given time. + // This may not be older than 60 seconds. + google.protobuf.Timestamp read_time = 2; + } + } + + // The mode of the transaction. + oneof mode { + // The transaction can only be used for read operations. + ReadOnly read_only = 2; + + // The transaction can be used for both read and write operations. + ReadWrite read_write = 3; + } +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/document.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/document.proto new file mode 100644 index 0000000..962d95c --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/document.proto @@ -0,0 +1,149 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1beta1; + +import "google/protobuf/struct.proto"; +import "google/protobuf/timestamp.proto"; +import "google/type/latlng.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1Beta1"; +option go_package = "cloud.google.com/go/firestore/apiv1beta1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "DocumentProto"; +option java_package = "com.google.firestore.v1beta1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1beta1"; +option ruby_package = "Google::Cloud::Firestore::V1beta1"; + +// A Firestore document. +// +// Must not exceed 1 MiB - 4 bytes. +message Document { + // The resource name of the document, for example + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string name = 1; + + // The document's fields. + // + // The map keys represent field names. + // + // A simple field name contains only characters `a` to `z`, `A` to `Z`, + // `0` to `9`, or `_`, and must not start with `0` to `9`. For example, + // `foo_bar_17`. + // + // Field names matching the regular expression `__.*__` are reserved. Reserved + // field names are forbidden except in certain documented contexts. The map + // keys, represented as UTF-8, must not exceed 1,500 bytes and cannot be + // empty. + // + // Field paths may be used in other contexts to refer to structured fields + // defined here. For `map_value`, the field path is represented by the simple + // or quoted field names of the containing fields, delimited by `.`. For + // example, the structured field + // `"foo" : { map_value: { "x&y" : { string_value: "hello" }}}` would be + // represented by the field path `foo.x&y`. + // + // Within a field path, a quoted field name starts and ends with `` ` `` and + // may contain any character. Some characters, including `` ` ``, must be + // escaped using a `\`. For example, `` `x&y` `` represents `x&y` and + // `` `bak\`tik` `` represents `` bak`tik ``. + map fields = 2; + + // Output only. The time at which the document was created. + // + // This value increases monotonically when a document is deleted then + // recreated. It can also be compared to values from other documents and + // the `read_time` of a query. + google.protobuf.Timestamp create_time = 3; + + // Output only. The time at which the document was last changed. + // + // This value is initially set to the `create_time` then increases + // monotonically with each change to the document. It can also be + // compared to values from other documents and the `read_time` of a query. + google.protobuf.Timestamp update_time = 4; +} + +// A message that can hold any of the supported value types. +message Value { + // Must have a value set. + oneof value_type { + // A null value. + google.protobuf.NullValue null_value = 11; + + // A boolean value. + bool boolean_value = 1; + + // An integer value. + int64 integer_value = 2; + + // A double value. + double double_value = 3; + + // A timestamp value. + // + // Precise only to microseconds. When stored, any additional precision is + // rounded down. + google.protobuf.Timestamp timestamp_value = 10; + + // A string value. + // + // The string, represented as UTF-8, must not exceed 1 MiB - 89 bytes. + // Only the first 1,500 bytes of the UTF-8 representation are considered by + // queries. + string string_value = 17; + + // A bytes value. + // + // Must not exceed 1 MiB - 89 bytes. + // Only the first 1,500 bytes are considered by queries. + bytes bytes_value = 18; + + // A reference to a document. For example: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string reference_value = 5; + + // A geo point value representing a point on the surface of Earth. + google.type.LatLng geo_point_value = 8; + + // An array value. + // + // Cannot directly contain another array value, though can contain an + // map which contains another array. + ArrayValue array_value = 9; + + // A map value. + MapValue map_value = 6; + } +} + +// An array value. +message ArrayValue { + // Values in the array. + repeated Value values = 1; +} + +// A map value. +message MapValue { + // The map's fields. + // + // The map keys represent field names. Field names matching the regular + // expression `__.*__` are reserved. Reserved field names are forbidden except + // in certain documented contexts. The map keys, represented as UTF-8, must + // not exceed 1,500 bytes and cannot be empty. + map fields = 1; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/firestore.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/firestore.proto new file mode 100644 index 0000000..6741939 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/firestore.proto @@ -0,0 +1,900 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1beta1; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/firestore/v1beta1/common.proto"; +import "google/firestore/v1beta1/document.proto"; +import "google/firestore/v1beta1/query.proto"; +import "google/firestore/v1beta1/write.proto"; +import "google/protobuf/empty.proto"; +import "google/protobuf/timestamp.proto"; +import "google/rpc/status.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1Beta1"; +option go_package = "cloud.google.com/go/firestore/apiv1beta1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "FirestoreProto"; +option java_package = "com.google.firestore.v1beta1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1beta1"; +option ruby_package = "Google::Cloud::Firestore::V1beta1"; + +// Specification of the Firestore API. + +// The Cloud Firestore service. +// +// Cloud Firestore is a fast, fully managed, serverless, cloud-native NoSQL +// document database that simplifies storing, syncing, and querying data for +// your mobile, web, and IoT apps at global scale. Its client libraries provide +// live synchronization and offline support, while its security features and +// integrations with Firebase and Google Cloud Platform (GCP) accelerate +// building truly serverless apps. +service Firestore { + option (google.api.default_host) = "firestore.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/datastore"; + + // Gets a single document. + rpc GetDocument(GetDocumentRequest) returns (Document) { + option (google.api.http) = { + get: "/v1beta1/{name=projects/*/databases/*/documents/*/**}" + }; + } + + // Lists documents. + rpc ListDocuments(ListDocumentsRequest) returns (ListDocumentsResponse) { + option (google.api.http) = { + get: "/v1beta1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}" + }; + } + + // Updates or inserts a document. + rpc UpdateDocument(UpdateDocumentRequest) returns (Document) { + option (google.api.http) = { + patch: "/v1beta1/{document.name=projects/*/databases/*/documents/*/**}" + body: "document" + }; + option (google.api.method_signature) = "document,update_mask"; + } + + // Deletes a document. + rpc DeleteDocument(DeleteDocumentRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1beta1/{name=projects/*/databases/*/documents/*/**}" + }; + option (google.api.method_signature) = "name"; + } + + // Gets multiple documents. + // + // Documents returned by this method are not guaranteed to be returned in the + // same order that they were requested. + rpc BatchGetDocuments(BatchGetDocumentsRequest) returns (stream BatchGetDocumentsResponse) { + option (google.api.http) = { + post: "/v1beta1/{database=projects/*/databases/*}/documents:batchGet" + body: "*" + }; + } + + // Starts a new transaction. + rpc BeginTransaction(BeginTransactionRequest) returns (BeginTransactionResponse) { + option (google.api.http) = { + post: "/v1beta1/{database=projects/*/databases/*}/documents:beginTransaction" + body: "*" + }; + option (google.api.method_signature) = "database"; + } + + // Commits a transaction, while optionally updating documents. + rpc Commit(CommitRequest) returns (CommitResponse) { + option (google.api.http) = { + post: "/v1beta1/{database=projects/*/databases/*}/documents:commit" + body: "*" + }; + option (google.api.method_signature) = "database,writes"; + } + + // Rolls back a transaction. + rpc Rollback(RollbackRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + post: "/v1beta1/{database=projects/*/databases/*}/documents:rollback" + body: "*" + }; + option (google.api.method_signature) = "database,transaction"; + } + + // Runs a query. + rpc RunQuery(RunQueryRequest) returns (stream RunQueryResponse) { + option (google.api.http) = { + post: "/v1beta1/{parent=projects/*/databases/*/documents}:runQuery" + body: "*" + additional_bindings { + post: "/v1beta1/{parent=projects/*/databases/*/documents/*/**}:runQuery" + body: "*" + } + }; + } + + // Partitions a query by returning partition cursors that can be used to run + // the query in parallel. The returned partition cursors are split points that + // can be used by RunQuery as starting/end points for the query results. + rpc PartitionQuery(PartitionQueryRequest) returns (PartitionQueryResponse) { + option (google.api.http) = { + post: "/v1beta1/{parent=projects/*/databases/*/documents}:partitionQuery" + body: "*" + additional_bindings { + post: "/v1beta1/{parent=projects/*/databases/*/documents/*/**}:partitionQuery" + body: "*" + } + }; + } + + // Streams batches of document updates and deletes, in order. + rpc Write(stream WriteRequest) returns (stream WriteResponse) { + option (google.api.http) = { + post: "/v1beta1/{database=projects/*/databases/*}/documents:write" + body: "*" + }; + } + + // Listens to changes. + rpc Listen(stream ListenRequest) returns (stream ListenResponse) { + option (google.api.http) = { + post: "/v1beta1/{database=projects/*/databases/*}/documents:listen" + body: "*" + }; + } + + // Lists all the collection IDs underneath a document. + rpc ListCollectionIds(ListCollectionIdsRequest) returns (ListCollectionIdsResponse) { + option (google.api.http) = { + post: "/v1beta1/{parent=projects/*/databases/*/documents}:listCollectionIds" + body: "*" + additional_bindings { + post: "/v1beta1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds" + body: "*" + } + }; + option (google.api.method_signature) = "parent"; + } + + // Applies a batch of write operations. + // + // The BatchWrite method does not apply the write operations atomically + // and can apply them out of order. Method does not allow more than one write + // per document. Each write succeeds or fails independently. See the + // [BatchWriteResponse][google.firestore.v1beta1.BatchWriteResponse] for the success status of each write. + // + // If you require an atomically applied set of writes, use + // [Commit][google.firestore.v1beta1.Firestore.Commit] instead. + rpc BatchWrite(BatchWriteRequest) returns (BatchWriteResponse) { + option (google.api.http) = { + post: "/v1beta1/{database=projects/*/databases/*}/documents:batchWrite" + body: "*" + }; + } + + // Creates a new document. + rpc CreateDocument(CreateDocumentRequest) returns (Document) { + option (google.api.http) = { + post: "/v1beta1/{parent=projects/*/databases/*/documents/**}/{collection_id}" + body: "document" + }; + } +} + +// The request for [Firestore.GetDocument][google.firestore.v1beta1.Firestore.GetDocument]. +message GetDocumentRequest { + // Required. The resource name of the Document to get. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string name = 1 [(google.api.field_behavior) = REQUIRED]; + + // The fields to return. If not set, returns all fields. + // + // If the document has a field that is not present in this mask, that field + // will not be returned in the response. + DocumentMask mask = 2; + + // The consistency mode for this transaction. + // If not set, defaults to strong consistency. + oneof consistency_selector { + // Reads the document in a transaction. + bytes transaction = 3; + + // Reads the version of the document at the given time. + // This may not be older than 270 seconds. + google.protobuf.Timestamp read_time = 5; + } +} + +// The request for [Firestore.ListDocuments][google.firestore.v1beta1.Firestore.ListDocuments]. +message ListDocumentsRequest { + // Required. The parent resource name. In the format: + // `projects/{project_id}/databases/{database_id}/documents` or + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + // For example: + // `projects/my-project/databases/my-database/documents` or + // `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` + // or `messages`. + string collection_id = 2 [(google.api.field_behavior) = REQUIRED]; + + // The maximum number of documents to return. + int32 page_size = 3; + + // The `next_page_token` value returned from a previous List request, if any. + string page_token = 4; + + // The order to sort results by. For example: `priority desc, name`. + string order_by = 6; + + // The fields to return. If not set, returns all fields. + // + // If a document has a field that is not present in this mask, that field + // will not be returned in the response. + DocumentMask mask = 7; + + // The consistency mode for this transaction. + // If not set, defaults to strong consistency. + oneof consistency_selector { + // Reads documents in a transaction. + bytes transaction = 8; + + // Reads documents as they were at the given time. + // This may not be older than 270 seconds. + google.protobuf.Timestamp read_time = 10; + } + + // If the list should show missing documents. A missing document is a + // document that does not exist but has sub-documents. These documents will + // be returned with a key but will not have fields, [Document.create_time][google.firestore.v1beta1.Document.create_time], + // or [Document.update_time][google.firestore.v1beta1.Document.update_time] set. + // + // Requests with `show_missing` may not specify `where` or + // `order_by`. + bool show_missing = 12; +} + +// The response for [Firestore.ListDocuments][google.firestore.v1beta1.Firestore.ListDocuments]. +message ListDocumentsResponse { + // The Documents found. + repeated Document documents = 1; + + // The next page token. + string next_page_token = 2; +} + +// The request for [Firestore.CreateDocument][google.firestore.v1beta1.Firestore.CreateDocument]. +message CreateDocumentRequest { + // Required. The parent resource. For example: + // `projects/{project_id}/databases/{database_id}/documents` or + // `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The collection ID, relative to `parent`, to list. For example: `chatrooms`. + string collection_id = 2 [(google.api.field_behavior) = REQUIRED]; + + // The client-assigned document ID to use for this document. + // + // Optional. If not specified, an ID will be assigned by the service. + string document_id = 3; + + // Required. The document to create. `name` must not be set. + Document document = 4 [(google.api.field_behavior) = REQUIRED]; + + // The fields to return. If not set, returns all fields. + // + // If the document has a field that is not present in this mask, that field + // will not be returned in the response. + DocumentMask mask = 5; +} + +// The request for [Firestore.UpdateDocument][google.firestore.v1beta1.Firestore.UpdateDocument]. +message UpdateDocumentRequest { + // Required. The updated document. + // Creates the document if it does not already exist. + Document document = 1 [(google.api.field_behavior) = REQUIRED]; + + // The fields to update. + // None of the field paths in the mask may contain a reserved name. + // + // If the document exists on the server and has fields not referenced in the + // mask, they are left unchanged. + // Fields referenced in the mask, but not present in the input document, are + // deleted from the document on the server. + DocumentMask update_mask = 2; + + // The fields to return. If not set, returns all fields. + // + // If the document has a field that is not present in this mask, that field + // will not be returned in the response. + DocumentMask mask = 3; + + // An optional precondition on the document. + // The request will fail if this is set and not met by the target document. + Precondition current_document = 4; +} + +// The request for [Firestore.DeleteDocument][google.firestore.v1beta1.Firestore.DeleteDocument]. +message DeleteDocumentRequest { + // Required. The resource name of the Document to delete. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string name = 1 [(google.api.field_behavior) = REQUIRED]; + + // An optional precondition on the document. + // The request will fail if this is set and not met by the target document. + Precondition current_document = 2; +} + +// The request for [Firestore.BatchGetDocuments][google.firestore.v1beta1.Firestore.BatchGetDocuments]. +message BatchGetDocumentsRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // The names of the documents to retrieve. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + // The request will fail if any of the document is not a child resource of the + // given `database`. Duplicate names will be elided. + repeated string documents = 2; + + // The fields to return. If not set, returns all fields. + // + // If a document has a field that is not present in this mask, that field will + // not be returned in the response. + DocumentMask mask = 3; + + // The consistency mode for this transaction. + // If not set, defaults to strong consistency. + oneof consistency_selector { + // Reads documents in a transaction. + bytes transaction = 4; + + // Starts a new transaction and reads the documents. + // Defaults to a read-only transaction. + // The new transaction ID will be returned as the first response in the + // stream. + TransactionOptions new_transaction = 5; + + // Reads documents as they were at the given time. + // This may not be older than 270 seconds. + google.protobuf.Timestamp read_time = 7; + } +} + +// The streamed response for [Firestore.BatchGetDocuments][google.firestore.v1beta1.Firestore.BatchGetDocuments]. +message BatchGetDocumentsResponse { + // A single result. + // This can be empty if the server is just returning a transaction. + oneof result { + // A document that was requested. + Document found = 1; + + // A document name that was requested but does not exist. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string missing = 2; + } + + // The transaction that was started as part of this request. + // Will only be set in the first response, and only if + // [BatchGetDocumentsRequest.new_transaction][google.firestore.v1beta1.BatchGetDocumentsRequest.new_transaction] was set in the request. + bytes transaction = 3; + + // The time at which the document was read. + // This may be monotically increasing, in this case the previous documents in + // the result stream are guaranteed not to have changed between their + // read_time and this one. + google.protobuf.Timestamp read_time = 4; +} + +// The request for [Firestore.BeginTransaction][google.firestore.v1beta1.Firestore.BeginTransaction]. +message BeginTransactionRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // The options for the transaction. + // Defaults to a read-write transaction. + TransactionOptions options = 2; +} + +// The response for [Firestore.BeginTransaction][google.firestore.v1beta1.Firestore.BeginTransaction]. +message BeginTransactionResponse { + // The transaction that was started. + bytes transaction = 1; +} + +// The request for [Firestore.Commit][google.firestore.v1beta1.Firestore.Commit]. +message CommitRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // The writes to apply. + // + // Always executed atomically and in order. + repeated Write writes = 2; + + // If set, applies all writes in this transaction, and commits it. + bytes transaction = 3; +} + +// The response for [Firestore.Commit][google.firestore.v1beta1.Firestore.Commit]. +message CommitResponse { + // The result of applying the writes. + // + // This i-th write result corresponds to the i-th write in the + // request. + repeated WriteResult write_results = 1; + + // The time at which the commit occurred. Any read with an equal or greater + // `read_time` is guaranteed to see the effects of the commit. + google.protobuf.Timestamp commit_time = 2; +} + +// The request for [Firestore.Rollback][google.firestore.v1beta1.Firestore.Rollback]. +message RollbackRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The transaction to roll back. + bytes transaction = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// The request for [Firestore.RunQuery][google.firestore.v1beta1.Firestore.RunQuery]. +message RunQueryRequest { + // Required. The parent resource name. In the format: + // `projects/{project_id}/databases/{database_id}/documents` or + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + // For example: + // `projects/my-project/databases/my-database/documents` or + // `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // The query to run. + oneof query_type { + // A structured query. + StructuredQuery structured_query = 2; + } + + // The consistency mode for this transaction. + // If not set, defaults to strong consistency. + oneof consistency_selector { + // Reads documents in a transaction. + bytes transaction = 5; + + // Starts a new transaction and reads the documents. + // Defaults to a read-only transaction. + // The new transaction ID will be returned as the first response in the + // stream. + TransactionOptions new_transaction = 6; + + // Reads documents as they were at the given time. + // This may not be older than 270 seconds. + google.protobuf.Timestamp read_time = 7; + } +} + +// The response for [Firestore.RunQuery][google.firestore.v1beta1.Firestore.RunQuery]. +message RunQueryResponse { + // The transaction that was started as part of this request. + // Can only be set in the first response, and only if + // [RunQueryRequest.new_transaction][google.firestore.v1beta1.RunQueryRequest.new_transaction] was set in the request. + // If set, no other fields will be set in this response. + bytes transaction = 2; + + // A query result. + // Not set when reporting partial progress. + Document document = 1; + + // The time at which the document was read. This may be monotonically + // increasing; in this case, the previous documents in the result stream are + // guaranteed not to have changed between their `read_time` and this one. + // + // If the query returns no results, a response with `read_time` and no + // `document` will be sent, and this represents the time at which the query + // was run. + google.protobuf.Timestamp read_time = 3; + + // The number of results that have been skipped due to an offset between + // the last response and the current response. + int32 skipped_results = 4; +} + +// The request for [Firestore.PartitionQuery][google.firestore.v1beta1.Firestore.PartitionQuery]. +message PartitionQueryRequest { + // Required. The parent resource name. In the format: + // `projects/{project_id}/databases/{database_id}/documents`. + // Document resource names are not supported; only database resource names + // can be specified. + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // The query to partition. + oneof query_type { + // A structured query. + // Query must specify collection with all descendants and be ordered by name + // ascending. Other filters, order bys, limits, offsets, and start/end + // cursors are not supported. + StructuredQuery structured_query = 2; + } + + // The desired maximum number of partition points. + // The partitions may be returned across multiple pages of results. + // The number must be positive. The actual number of partitions + // returned may be fewer. + // + // For example, this may be set to one fewer than the number of parallel + // queries to be run, or in running a data pipeline job, one fewer than the + // number of workers or compute instances available. + int64 partition_count = 3; + + // The `next_page_token` value returned from a previous call to + // PartitionQuery that may be used to get an additional set of results. + // There are no ordering guarantees between sets of results. Thus, using + // multiple sets of results will require merging the different result sets. + // + // For example, two subsequent calls using a page_token may return: + // + // * cursor B, cursor M, cursor Q + // * cursor A, cursor U, cursor W + // + // To obtain a complete result set ordered with respect to the results of the + // query supplied to PartitionQuery, the results sets should be merged: + // cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + string page_token = 4; + + // The maximum number of partitions to return in this call, subject to + // `partition_count`. + // + // For example, if `partition_count` = 10 and `page_size` = 8, the first call + // to PartitionQuery will return up to 8 partitions and a `next_page_token` + // if more results exist. A second call to PartitionQuery will return up to + // 2 partitions, to complete the total of 10 specified in `partition_count`. + int32 page_size = 5; +} + +// The response for [Firestore.PartitionQuery][google.firestore.v1beta1.Firestore.PartitionQuery]. +message PartitionQueryResponse { + // Partition results. + // Each partition is a split point that can be used by RunQuery as a starting + // or end point for the query results. The RunQuery requests must be made with + // the same query supplied to this PartitionQuery request. The partition + // cursors will be ordered according to same ordering as the results of the + // query supplied to PartitionQuery. + // + // For example, if a PartitionQuery request returns partition cursors A and B, + // running the following three queries will return the entire result set of + // the original query: + // + // * query, end_at A + // * query, start_at A, end_at B + // * query, start_at B + // + // An empty result may indicate that the query has too few results to be + // partitioned. + repeated Cursor partitions = 1; + + // A page token that may be used to request an additional set of results, up + // to the number specified by `partition_count` in the PartitionQuery request. + // If blank, there are no more results. + string next_page_token = 2; +} + +// The request for [Firestore.Write][google.firestore.v1beta1.Firestore.Write]. +// +// The first request creates a stream, or resumes an existing one from a token. +// +// When creating a new stream, the server replies with a response containing +// only an ID and a token, to use in the next request. +// +// When resuming a stream, the server first streams any responses later than the +// given token, then a response containing only an up-to-date token, to use in +// the next request. +message WriteRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + // This is only required in the first message. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // The ID of the write stream to resume. + // This may only be set in the first message. When left empty, a new write + // stream will be created. + string stream_id = 2; + + // The writes to apply. + // + // Always executed atomically and in order. + // This must be empty on the first request. + // This may be empty on the last request. + // This must not be empty on all other requests. + repeated Write writes = 3; + + // A stream token that was previously sent by the server. + // + // The client should set this field to the token from the most recent + // [WriteResponse][google.firestore.v1beta1.WriteResponse] it has received. This acknowledges that the client has + // received responses up to this token. After sending this token, earlier + // tokens may not be used anymore. + // + // The server may close the stream if there are too many unacknowledged + // responses. + // + // Leave this field unset when creating a new stream. To resume a stream at + // a specific point, set this field and the `stream_id` field. + // + // Leave this field unset when creating a new stream. + bytes stream_token = 4; + + // Labels associated with this write request. + map labels = 5; +} + +// The response for [Firestore.Write][google.firestore.v1beta1.Firestore.Write]. +message WriteResponse { + // The ID of the stream. + // Only set on the first message, when a new stream was created. + string stream_id = 1; + + // A token that represents the position of this response in the stream. + // This can be used by a client to resume the stream at this point. + // + // This field is always set. + bytes stream_token = 2; + + // The result of applying the writes. + // + // This i-th write result corresponds to the i-th write in the + // request. + repeated WriteResult write_results = 3; + + // The time at which the commit occurred. Any read with an equal or greater + // `read_time` is guaranteed to see the effects of the write. + google.protobuf.Timestamp commit_time = 4; +} + +// A request for [Firestore.Listen][google.firestore.v1beta1.Firestore.Listen] +message ListenRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // The supported target changes. + oneof target_change { + // A target to add to this stream. + Target add_target = 2; + + // The ID of a target to remove from this stream. + int32 remove_target = 3; + } + + // Labels associated with this target change. + map labels = 4; +} + +// The response for [Firestore.Listen][google.firestore.v1beta1.Firestore.Listen]. +message ListenResponse { + // The supported responses. + oneof response_type { + // Targets have changed. + TargetChange target_change = 2; + + // A [Document][google.firestore.v1beta1.Document] has changed. + DocumentChange document_change = 3; + + // A [Document][google.firestore.v1beta1.Document] has been deleted. + DocumentDelete document_delete = 4; + + // A [Document][google.firestore.v1beta1.Document] has been removed from a target (because it is no longer + // relevant to that target). + DocumentRemove document_remove = 6; + + // A filter to apply to the set of documents previously returned for the + // given target. + // + // Returned when documents may have been removed from the given target, but + // the exact documents are unknown. + ExistenceFilter filter = 5; + } +} + +// A specification of a set of documents to listen to. +message Target { + // A target specified by a set of documents names. + message DocumentsTarget { + // The names of the documents to retrieve. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + // The request will fail if any of the document is not a child resource of + // the given `database`. Duplicate names will be elided. + repeated string documents = 2; + } + + // A target specified by a query. + message QueryTarget { + // The parent resource name. In the format: + // `projects/{project_id}/databases/{database_id}/documents` or + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + // For example: + // `projects/my-project/databases/my-database/documents` or + // `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + string parent = 1; + + // The query to run. + oneof query_type { + // A structured query. + StructuredQuery structured_query = 2; + } + } + + // The type of target to listen to. + oneof target_type { + // A target specified by a query. + QueryTarget query = 2; + + // A target specified by a set of document names. + DocumentsTarget documents = 3; + } + + // When to start listening. + // + // If not specified, all matching Documents are returned before any + // subsequent changes. + oneof resume_type { + // A resume token from a prior [TargetChange][google.firestore.v1beta1.TargetChange] for an identical target. + // + // Using a resume token with a different target is unsupported and may fail. + bytes resume_token = 4; + + // Start listening after a specific `read_time`. + // + // The client must know the state of matching documents at this time. + google.protobuf.Timestamp read_time = 11; + } + + // The target ID that identifies the target on the stream. Must be a positive + // number and non-zero. + int32 target_id = 5; + + // If the target should be removed once it is current and consistent. + bool once = 6; +} + +// Targets being watched have changed. +message TargetChange { + // The type of change. + enum TargetChangeType { + // No change has occurred. Used only to send an updated `resume_token`. + NO_CHANGE = 0; + + // The targets have been added. + ADD = 1; + + // The targets have been removed. + REMOVE = 2; + + // The targets reflect all changes committed before the targets were added + // to the stream. + // + // This will be sent after or with a `read_time` that is greater than or + // equal to the time at which the targets were added. + // + // Listeners can wait for this change if read-after-write semantics + // are desired. + CURRENT = 3; + + // The targets have been reset, and a new initial state for the targets + // will be returned in subsequent changes. + // + // After the initial state is complete, `CURRENT` will be returned even + // if the target was previously indicated to be `CURRENT`. + RESET = 4; + } + + // The type of change that occurred. + TargetChangeType target_change_type = 1; + + // The target IDs of targets that have changed. + // + // If empty, the change applies to all targets. + // + // The order of the target IDs is not defined. + repeated int32 target_ids = 2; + + // The error that resulted in this change, if applicable. + google.rpc.Status cause = 3; + + // A token that can be used to resume the stream for the given `target_ids`, + // or all targets if `target_ids` is empty. + // + // Not set on every target change. + bytes resume_token = 4; + + // The consistent `read_time` for the given `target_ids` (omitted when the + // target_ids are not at a consistent snapshot). + // + // The stream is guaranteed to send a `read_time` with `target_ids` empty + // whenever the entire stream reaches a new consistent snapshot. ADD, + // CURRENT, and RESET messages are guaranteed to (eventually) result in a + // new consistent snapshot (while NO_CHANGE and REMOVE messages are not). + // + // For a given stream, `read_time` is guaranteed to be monotonically + // increasing. + google.protobuf.Timestamp read_time = 6; +} + +// The request for [Firestore.ListCollectionIds][google.firestore.v1beta1.Firestore.ListCollectionIds]. +message ListCollectionIdsRequest { + // Required. The parent document. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + // For example: + // `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // The maximum number of results to return. + int32 page_size = 2; + + // A page token. Must be a value from + // [ListCollectionIdsResponse][google.firestore.v1beta1.ListCollectionIdsResponse]. + string page_token = 3; +} + +// The response from [Firestore.ListCollectionIds][google.firestore.v1beta1.Firestore.ListCollectionIds]. +message ListCollectionIdsResponse { + // The collection ids. + repeated string collection_ids = 1; + + // A page token that may be used to continue the list. + string next_page_token = 2; +} + +// The request for [Firestore.BatchWrite][google.firestore.v1beta1.Firestore.BatchWrite]. +message BatchWriteRequest { + // Required. The database name. In the format: + // `projects/{project_id}/databases/{database_id}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; + + // The writes to apply. + // + // Method does not apply writes atomically and does not guarantee ordering. + // Each write succeeds or fails independently. You cannot write to the same + // document more than once per request. + repeated Write writes = 2; + + // Labels associated with this batch write. + map labels = 3; +} + +// The response from [Firestore.BatchWrite][google.firestore.v1beta1.Firestore.BatchWrite]. +message BatchWriteResponse { + // The result of applying the writes. + // + // This i-th write result corresponds to the i-th write in the + // request. + repeated WriteResult write_results = 1; + + // The status of applying the writes. + // + // This i-th write status corresponds to the i-th write in the + // request. + repeated google.rpc.Status status = 2; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/query.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/query.proto new file mode 100644 index 0000000..868c8ef --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/query.proto @@ -0,0 +1,300 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1beta1; + +import "google/firestore/v1beta1/document.proto"; +import "google/protobuf/wrappers.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1Beta1"; +option go_package = "cloud.google.com/go/firestore/apiv1beta1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "QueryProto"; +option java_package = "com.google.firestore.v1beta1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1beta1"; +option ruby_package = "Google::Cloud::Firestore::V1beta1"; + +// A Firestore query. +message StructuredQuery { + // A selection of a collection, such as `messages as m1`. + message CollectionSelector { + // The collection ID. + // When set, selects only collections with this ID. + string collection_id = 2; + + // When false, selects only collections that are immediate children of + // the `parent` specified in the containing `RunQueryRequest`. + // When true, selects all descendant collections. + bool all_descendants = 3; + } + + // A filter. + message Filter { + // The type of filter. + oneof filter_type { + // A composite filter. + CompositeFilter composite_filter = 1; + + // A filter on a document field. + FieldFilter field_filter = 2; + + // A filter that takes exactly one argument. + UnaryFilter unary_filter = 3; + } + } + + // A filter that merges multiple other filters using the given operator. + message CompositeFilter { + // A composite filter operator. + enum Operator { + // Unspecified. This value must not be used. + OPERATOR_UNSPECIFIED = 0; + + // The results are required to satisfy each of the combined filters. + AND = 1; + } + + // The operator for combining multiple filters. + Operator op = 1; + + // The list of filters to combine. + // Must contain at least one filter. + repeated Filter filters = 2; + } + + // A filter on a specific field. + message FieldFilter { + // A field filter operator. + enum Operator { + // Unspecified. This value must not be used. + OPERATOR_UNSPECIFIED = 0; + + // The given `field` is less than the given `value`. + // + // Requires: + // + // * That `field` come first in `order_by`. + LESS_THAN = 1; + + // The given `field` is less than or equal to the given `value`. + // + // Requires: + // + // * That `field` come first in `order_by`. + LESS_THAN_OR_EQUAL = 2; + + // The given `field` is greater than the given `value`. + // + // Requires: + // + // * That `field` come first in `order_by`. + GREATER_THAN = 3; + + // The given `field` is greater than or equal to the given `value`. + // + // Requires: + // + // * That `field` come first in `order_by`. + GREATER_THAN_OR_EQUAL = 4; + + // The given `field` is equal to the given `value`. + EQUAL = 5; + + // The given `field` is not equal to the given `value`. + // + // Requires: + // + // * No other `NOT_EQUAL`, `NOT_IN`, `IS_NOT_NULL`, or `IS_NOT_NAN`. + // * That `field` comes first in the `order_by`. + NOT_EQUAL = 6; + + // The given `field` is an array that contains the given `value`. + ARRAY_CONTAINS = 7; + + // The given `field` is equal to at least one value in the given array. + // + // Requires: + // + // * That `value` is a non-empty `ArrayValue` with at most 10 values. + // * No other `IN` or `ARRAY_CONTAINS_ANY` or `NOT_IN`. + IN = 8; + + // The given `field` is an array that contains any of the values in the + // given array. + // + // Requires: + // + // * That `value` is a non-empty `ArrayValue` with at most 10 values. + // * No other `IN` or `ARRAY_CONTAINS_ANY` or `NOT_IN`. + ARRAY_CONTAINS_ANY = 9; + + // The value of the `field` is not in the given array. + // + // Requires: + // + // * That `value` is a non-empty `ArrayValue` with at most 10 values. + // * No other `IN`, `ARRAY_CONTAINS_ANY`, `NOT_IN`, `NOT_EQUAL`, + // `IS_NOT_NULL`, or `IS_NOT_NAN`. + // * That `field` comes first in the `order_by`. + NOT_IN = 10; + } + + // The field to filter by. + FieldReference field = 1; + + // The operator to filter by. + Operator op = 2; + + // The value to compare to. + Value value = 3; + } + + // A filter with a single operand. + message UnaryFilter { + // A unary operator. + enum Operator { + // Unspecified. This value must not be used. + OPERATOR_UNSPECIFIED = 0; + + // The given `field` is equal to `NaN`. + IS_NAN = 2; + + // The given `field` is equal to `NULL`. + IS_NULL = 3; + + // The given `field` is not equal to `NaN`. + // + // Requires: + // + // * No other `NOT_EQUAL`, `NOT_IN`, `IS_NOT_NULL`, or `IS_NOT_NAN`. + // * That `field` comes first in the `order_by`. + IS_NOT_NAN = 4; + + // The given `field` is not equal to `NULL`. + // + // Requires: + // + // * A single `NOT_EQUAL`, `NOT_IN`, `IS_NOT_NULL`, or `IS_NOT_NAN`. + // * That `field` comes first in the `order_by`. + IS_NOT_NULL = 5; + } + + // The unary operator to apply. + Operator op = 1; + + // The argument to the filter. + oneof operand_type { + // The field to which to apply the operator. + FieldReference field = 2; + } + } + + // A reference to a field, such as `max(messages.time) as max_time`. + message FieldReference { + string field_path = 2; + } + + // An order on a field. + message Order { + // The field to order by. + FieldReference field = 1; + + // The direction to order by. Defaults to `ASCENDING`. + Direction direction = 2; + } + + // The projection of document's fields to return. + message Projection { + // The fields to return. + // + // If empty, all fields are returned. To only return the name + // of the document, use `['__name__']`. + repeated FieldReference fields = 2; + } + + // A sort direction. + enum Direction { + // Unspecified. + DIRECTION_UNSPECIFIED = 0; + + // Ascending. + ASCENDING = 1; + + // Descending. + DESCENDING = 2; + } + + // The projection to return. + Projection select = 1; + + // The collections to query. + repeated CollectionSelector from = 2; + + // The filter to apply. + Filter where = 3; + + // The order to apply to the query results. + // + // Firestore guarantees a stable ordering through the following rules: + // + // * Any field required to appear in `order_by`, that is not already + // specified in `order_by`, is appended to the order in field name order + // by default. + // * If an order on `__name__` is not specified, it is appended by default. + // + // Fields are appended with the same sort direction as the last order + // specified, or 'ASCENDING' if no order was specified. For example: + // + // * `SELECT * FROM Foo ORDER BY A` becomes + // `SELECT * FROM Foo ORDER BY A, __name__` + // * `SELECT * FROM Foo ORDER BY A DESC` becomes + // `SELECT * FROM Foo ORDER BY A DESC, __name__ DESC` + // * `SELECT * FROM Foo WHERE A > 1` becomes + // `SELECT * FROM Foo WHERE A > 1 ORDER BY A, __name__` + repeated Order order_by = 4; + + // A starting point for the query results. + Cursor start_at = 7; + + // A end point for the query results. + Cursor end_at = 8; + + // The number of results to skip. + // + // Applies before limit, but after all other constraints. Must be >= 0 if + // specified. + int32 offset = 6; + + // The maximum number of results to return. + // + // Applies after all other constraints. + // Must be >= 0 if specified. + google.protobuf.Int32Value limit = 5; +} + +// A position in a query result set. +message Cursor { + // The values that represent a position, in the order they appear in + // the order by clause of a query. + // + // Can contain fewer values than specified in the order by clause. + repeated Value values = 1; + + // If the position is just before or just after the given values, relative + // to the sort order defined by the query. + bool before = 2; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/undeliverable_first_gen_event.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/undeliverable_first_gen_event.proto new file mode 100644 index 0000000..e0e9b17 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/undeliverable_first_gen_event.proto @@ -0,0 +1,75 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1beta1; + +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1Beta1"; +option go_package = "cloud.google.com/go/firestore/apiv1beta1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "UndeliverableFirstGenEventProto"; +option java_package = "com.google.firestore.v1beta1"; +option php_namespace = "Google\\Cloud\\Firestore\\V1beta1"; +option ruby_package = "Google::Cloud::Firestore::V1beta1"; + +// A message signifying an event that cannot be delivered to Cloud Functions +// from Firestore using [Cloud Firestore triggers 1st +// gen](https://cloud.google.com/functions/docs/calling/cloud-firestore) +message UndeliverableFirstGenEvent { + // Reason for events being undeliverable. + enum Reason { + // Unspecified. + REASON_UNSPECIFIED = 0; + + // Exceeding maximum event size limit + EXCEEDING_SIZE_LIMIT = 1; + } + + // Document change type. + enum DocumentChangeType { + // Unspecified. + DOCUMENT_CHANGE_TYPE_UNSPECIFIED = 0; + + // Represent creation operation. + CREATE = 1; + + // Represent delete operation. + DELETE = 2; + + // Represent update operation. + UPDATE = 3; + } + + // Error message for events being undeliverable. + string message = 1; + + // Reason for events being undeliverable. + Reason reason = 2; + + // The resource name of the changed document, in the format of + // `projects/{projectId}/databases/{databaseId}/documents/{document_path}`. + string document_name = 3; + + // The type of the document change. + DocumentChangeType document_change_type = 4; + + // The names of the functions that were supposed to be triggered. + repeated string function_name = 5; + + // The commit time of triggered write operation. + google.protobuf.Timestamp triggered_time = 6; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/write.proto b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/write.proto new file mode 100644 index 0000000..00ba29a --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/write.proto @@ -0,0 +1,258 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.firestore.v1beta1; + +import "google/firestore/v1beta1/common.proto"; +import "google/firestore/v1beta1/document.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1Beta1"; +option go_package = "cloud.google.com/go/firestore/apiv1beta1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "WriteProto"; +option java_package = "com.google.firestore.v1beta1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1beta1"; +option ruby_package = "Google::Cloud::Firestore::V1beta1"; + +// A write on a document. +message Write { + // The operation to execute. + oneof operation { + // A document to write. + Document update = 1; + + // A document name to delete. In the format: + // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + string delete = 2; + + // Applies a transformation to a document. + DocumentTransform transform = 6; + } + + // The fields to update in this write. + // + // This field can be set only when the operation is `update`. + // If the mask is not set for an `update` and the document exists, any + // existing data will be overwritten. + // If the mask is set and the document on the server has fields not covered by + // the mask, they are left unchanged. + // Fields referenced in the mask, but not present in the input document, are + // deleted from the document on the server. + // The field paths in this mask must not contain a reserved field name. + DocumentMask update_mask = 3; + + // The transforms to perform after update. + // + // This field can be set only when the operation is `update`. If present, this + // write is equivalent to performing `update` and `transform` to the same + // document atomically and in order. + repeated DocumentTransform.FieldTransform update_transforms = 7; + + // An optional precondition on the document. + // + // The write will fail if this is set and not met by the target document. + Precondition current_document = 4; +} + +// A transformation of a document. +message DocumentTransform { + // A transformation of a field of the document. + message FieldTransform { + // A value that is calculated by the server. + enum ServerValue { + // Unspecified. This value must not be used. + SERVER_VALUE_UNSPECIFIED = 0; + + // The time at which the server processed the request, with millisecond + // precision. If used on multiple fields (same or different documents) in + // a transaction, all the fields will get the same server timestamp. + REQUEST_TIME = 1; + } + + // The path of the field. See [Document.fields][google.firestore.v1beta1.Document.fields] for the field path syntax + // reference. + string field_path = 1; + + // The transformation to apply on the field. + oneof transform_type { + // Sets the field to the given server value. + ServerValue set_to_server_value = 2; + + // Adds the given value to the field's current value. + // + // This must be an integer or a double value. + // If the field is not an integer or double, or if the field does not yet + // exist, the transformation will set the field to the given value. + // If either of the given value or the current field value are doubles, + // both values will be interpreted as doubles. Double arithmetic and + // representation of double values follow IEEE 754 semantics. + // If there is positive/negative integer overflow, the field is resolved + // to the largest magnitude positive/negative integer. + Value increment = 3; + + // Sets the field to the maximum of its current value and the given value. + // + // This must be an integer or a double value. + // If the field is not an integer or double, or if the field does not yet + // exist, the transformation will set the field to the given value. + // If a maximum operation is applied where the field and the input value + // are of mixed types (that is - one is an integer and one is a double) + // the field takes on the type of the larger operand. If the operands are + // equivalent (e.g. 3 and 3.0), the field does not change. + // 0, 0.0, and -0.0 are all zero. The maximum of a zero stored value and + // zero input value is always the stored value. + // The maximum of any numeric value x and NaN is NaN. + Value maximum = 4; + + // Sets the field to the minimum of its current value and the given value. + // + // This must be an integer or a double value. + // If the field is not an integer or double, or if the field does not yet + // exist, the transformation will set the field to the input value. + // If a minimum operation is applied where the field and the input value + // are of mixed types (that is - one is an integer and one is a double) + // the field takes on the type of the smaller operand. If the operands are + // equivalent (e.g. 3 and 3.0), the field does not change. + // 0, 0.0, and -0.0 are all zero. The minimum of a zero stored value and + // zero input value is always the stored value. + // The minimum of any numeric value x and NaN is NaN. + Value minimum = 5; + + // Append the given elements in order if they are not already present in + // the current field value. + // If the field is not an array, or if the field does not yet exist, it is + // first set to the empty array. + // + // Equivalent numbers of different types (e.g. 3L and 3.0) are + // considered equal when checking if a value is missing. + // NaN is equal to NaN, and Null is equal to Null. + // If the input contains multiple equivalent values, only the first will + // be considered. + // + // The corresponding transform_result will be the null value. + ArrayValue append_missing_elements = 6; + + // Remove all of the given elements from the array in the field. + // If the field is not an array, or if the field does not yet exist, it is + // set to the empty array. + // + // Equivalent numbers of the different types (e.g. 3L and 3.0) are + // considered equal when deciding whether an element should be removed. + // NaN is equal to NaN, and Null is equal to Null. + // This will remove all equivalent values if there are duplicates. + // + // The corresponding transform_result will be the null value. + ArrayValue remove_all_from_array = 7; + } + } + + // The name of the document to transform. + string document = 1; + + // The list of transformations to apply to the fields of the document, in + // order. + // This must not be empty. + repeated FieldTransform field_transforms = 2; +} + +// The result of applying a write. +message WriteResult { + // The last update time of the document after applying the write. Not set + // after a `delete`. + // + // If the write did not actually change the document, this will be the + // previous update_time. + google.protobuf.Timestamp update_time = 1; + + // The results of applying each [DocumentTransform.FieldTransform][google.firestore.v1beta1.DocumentTransform.FieldTransform], in the + // same order. + repeated Value transform_results = 2; +} + +// A [Document][google.firestore.v1beta1.Document] has changed. +// +// May be the result of multiple [writes][google.firestore.v1beta1.Write], including deletes, that +// ultimately resulted in a new value for the [Document][google.firestore.v1beta1.Document]. +// +// Multiple [DocumentChange][google.firestore.v1beta1.DocumentChange] messages may be returned for the same logical +// change, if multiple targets are affected. +message DocumentChange { + // The new state of the [Document][google.firestore.v1beta1.Document]. + // + // If `mask` is set, contains only fields that were updated or added. + Document document = 1; + + // A set of target IDs of targets that match this document. + repeated int32 target_ids = 5; + + // A set of target IDs for targets that no longer match this document. + repeated int32 removed_target_ids = 6; +} + +// A [Document][google.firestore.v1beta1.Document] has been deleted. +// +// May be the result of multiple [writes][google.firestore.v1beta1.Write], including updates, the +// last of which deleted the [Document][google.firestore.v1beta1.Document]. +// +// Multiple [DocumentDelete][google.firestore.v1beta1.DocumentDelete] messages may be returned for the same logical +// delete, if multiple targets are affected. +message DocumentDelete { + // The resource name of the [Document][google.firestore.v1beta1.Document] that was deleted. + string document = 1; + + // A set of target IDs for targets that previously matched this entity. + repeated int32 removed_target_ids = 6; + + // The read timestamp at which the delete was observed. + // + // Greater or equal to the `commit_time` of the delete. + google.protobuf.Timestamp read_time = 4; +} + +// A [Document][google.firestore.v1beta1.Document] has been removed from the view of the targets. +// +// Sent if the document is no longer relevant to a target and is out of view. +// Can be sent instead of a DocumentDelete or a DocumentChange if the server +// can not send the new value of the document. +// +// Multiple [DocumentRemove][google.firestore.v1beta1.DocumentRemove] messages may be returned for the same logical +// write or delete, if multiple targets are affected. +message DocumentRemove { + // The resource name of the [Document][google.firestore.v1beta1.Document] that has gone out of view. + string document = 1; + + // A set of target IDs for targets that previously matched this document. + repeated int32 removed_target_ids = 2; + + // The read timestamp at which the remove was observed. + // + // Greater or equal to the `commit_time` of the change/delete/remove. + google.protobuf.Timestamp read_time = 4; +} + +// A digest of all the documents that match a given target. +message ExistenceFilter { + // The target ID to which this filter applies. + int32 target_id = 1; + + // The total count of documents that match [target_id][google.firestore.v1beta1.ExistenceFilter.target_id]. + // + // If different from the count of documents in the client that match, the + // client must manually determine which documents no longer match the target. + int32 count = 2; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/longrunning/operations.proto b/node_modules/@google-cloud/firestore/build/protos/google/longrunning/operations.proto new file mode 100644 index 0000000..bb42620 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/longrunning/operations.proto @@ -0,0 +1,246 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.longrunning; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/protobuf/any.proto"; +import "google/protobuf/descriptor.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/empty.proto"; +import "google/rpc/status.proto"; + +option cc_enable_arenas = true; +option csharp_namespace = "Google.LongRunning"; +option go_package = "cloud.google.com/go/longrunning/autogen/longrunningpb;longrunningpb"; +option java_multiple_files = true; +option java_outer_classname = "OperationsProto"; +option java_package = "com.google.longrunning"; +option objc_class_prefix = "GLRUN"; +option php_namespace = "Google\\LongRunning"; + +extend google.protobuf.MethodOptions { + // Additional information regarding long-running operations. + // In particular, this specifies the types that are returned from + // long-running operations. + // + // Required for methods that return `google.longrunning.Operation`; invalid + // otherwise. + google.longrunning.OperationInfo operation_info = 1049; +} + +// Manages long-running operations with an API service. +// +// When an API method normally takes long time to complete, it can be designed +// to return [Operation][google.longrunning.Operation] to the client, and the +// client can use this interface to receive the real response asynchronously by +// polling the operation resource, or pass the operation resource to another API +// (such as Pub/Sub API) to receive the response. Any API service that returns +// long-running operations should implement the `Operations` interface so +// developers can have a consistent client experience. +service Operations { + option (google.api.default_host) = "longrunning.googleapis.com"; + + // Lists operations that match the specified filter in the request. If the + // server doesn't support this method, it returns `UNIMPLEMENTED`. + rpc ListOperations(ListOperationsRequest) returns (ListOperationsResponse) { + option (google.api.http) = { + get: "/v1/{name=operations}" + }; + option (google.api.method_signature) = "name,filter"; + } + + // Gets the latest state of a long-running operation. Clients can use this + // method to poll the operation result at intervals as recommended by the API + // service. + rpc GetOperation(GetOperationRequest) returns (Operation) { + option (google.api.http) = { + get: "/v1/{name=operations/**}" + }; + option (google.api.method_signature) = "name"; + } + + // Deletes a long-running operation. This method indicates that the client is + // no longer interested in the operation result. It does not cancel the + // operation. If the server doesn't support this method, it returns + // `google.rpc.Code.UNIMPLEMENTED`. + rpc DeleteOperation(DeleteOperationRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=operations/**}" + }; + option (google.api.method_signature) = "name"; + } + + // Starts asynchronous cancellation on a long-running operation. The server + // makes a best effort to cancel the operation, but success is not + // guaranteed. If the server doesn't support this method, it returns + // `google.rpc.Code.UNIMPLEMENTED`. Clients can use + // [Operations.GetOperation][google.longrunning.Operations.GetOperation] or + // other methods to check whether the cancellation succeeded or whether the + // operation completed despite cancellation. On successful cancellation, + // the operation is not deleted; instead, it becomes an operation with + // an [Operation.error][google.longrunning.Operation.error] value with a + // [google.rpc.Status.code][google.rpc.Status.code] of `1`, corresponding to + // `Code.CANCELLED`. + rpc CancelOperation(CancelOperationRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + post: "/v1/{name=operations/**}:cancel" + body: "*" + }; + option (google.api.method_signature) = "name"; + } + + // Waits until the specified long-running operation is done or reaches at most + // a specified timeout, returning the latest state. If the operation is + // already done, the latest state is immediately returned. If the timeout + // specified is greater than the default HTTP/RPC timeout, the HTTP/RPC + // timeout is used. If the server does not support this method, it returns + // `google.rpc.Code.UNIMPLEMENTED`. + // Note that this method is on a best-effort basis. It may return the latest + // state before the specified timeout (including immediately), meaning even an + // immediate response is no guarantee that the operation is done. + rpc WaitOperation(WaitOperationRequest) returns (Operation) {} +} + +// This resource represents a long-running operation that is the result of a +// network API call. +message Operation { + // The server-assigned name, which is only unique within the same service that + // originally returns it. If you use the default HTTP mapping, the + // `name` should be a resource name ending with `operations/{unique_id}`. + string name = 1; + + // Service-specific metadata associated with the operation. It typically + // contains progress information and common metadata such as create time. + // Some services might not provide such metadata. Any method that returns a + // long-running operation should document the metadata type, if any. + google.protobuf.Any metadata = 2; + + // If the value is `false`, it means the operation is still in progress. + // If `true`, the operation is completed, and either `error` or `response` is + // available. + bool done = 3; + + // The operation result, which can be either an `error` or a valid `response`. + // If `done` == `false`, neither `error` nor `response` is set. + // If `done` == `true`, exactly one of `error` or `response` can be set. + // Some services might not provide the result. + oneof result { + // The error result of the operation in case of failure or cancellation. + google.rpc.Status error = 4; + + // The normal, successful response of the operation. If the original + // method returns no data on success, such as `Delete`, the response is + // `google.protobuf.Empty`. If the original method is standard + // `Get`/`Create`/`Update`, the response should be the resource. For other + // methods, the response should have the type `XxxResponse`, where `Xxx` + // is the original method name. For example, if the original method name + // is `TakeSnapshot()`, the inferred response type is + // `TakeSnapshotResponse`. + google.protobuf.Any response = 5; + } +} + +// The request message for +// [Operations.GetOperation][google.longrunning.Operations.GetOperation]. +message GetOperationRequest { + // The name of the operation resource. + string name = 1; +} + +// The request message for +// [Operations.ListOperations][google.longrunning.Operations.ListOperations]. +message ListOperationsRequest { + // The name of the operation's parent resource. + string name = 4; + + // The standard list filter. + string filter = 1; + + // The standard list page size. + int32 page_size = 2; + + // The standard list page token. + string page_token = 3; +} + +// The response message for +// [Operations.ListOperations][google.longrunning.Operations.ListOperations]. +message ListOperationsResponse { + // A list of operations that matches the specified filter in the request. + repeated Operation operations = 1; + + // The standard List next-page token. + string next_page_token = 2; +} + +// The request message for +// [Operations.CancelOperation][google.longrunning.Operations.CancelOperation]. +message CancelOperationRequest { + // The name of the operation resource to be cancelled. + string name = 1; +} + +// The request message for +// [Operations.DeleteOperation][google.longrunning.Operations.DeleteOperation]. +message DeleteOperationRequest { + // The name of the operation resource to be deleted. + string name = 1; +} + +// The request message for +// [Operations.WaitOperation][google.longrunning.Operations.WaitOperation]. +message WaitOperationRequest { + // The name of the operation resource to wait on. + string name = 1; + + // The maximum duration to wait before timing out. If left blank, the wait + // will be at most the time permitted by the underlying HTTP/RPC protocol. + // If RPC context deadline is also specified, the shorter one will be used. + google.protobuf.Duration timeout = 2; +} + +// A message representing the message types used by a long-running operation. +// +// Example: +// +// rpc Export(ExportRequest) returns (google.longrunning.Operation) { +// option (google.longrunning.operation_info) = { +// response_type: "ExportResponse" +// metadata_type: "ExportMetadata" +// }; +// } +message OperationInfo { + // Required. The message name of the primary return type for this + // long-running operation. + // This type will be used to deserialize the LRO's response. + // + // If the response is in a different package from the rpc, a fully-qualified + // message name must be used (e.g. `google.protobuf.Struct`). + // + // Note: Altering this value constitutes a breaking change. + string response_type = 1; + + // Required. The message name of the metadata type for this long-running + // operation. + // + // If the response is in a different package from the rpc, a fully-qualified + // message name must be used (e.g. `google.protobuf.Struct`). + // + // Note: Altering this value constitutes a breaking change. + string metadata_type = 2; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/protobuf/any.proto b/node_modules/@google-cloud/firestore/build/protos/google/protobuf/any.proto new file mode 100644 index 0000000..eff44e5 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/protobuf/any.proto @@ -0,0 +1,162 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option go_package = "google.golang.org/protobuf/types/known/anypb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "AnyProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; + +// `Any` contains an arbitrary serialized protocol buffer message along with a +// URL that describes the type of the serialized message. +// +// Protobuf library provides support to pack/unpack Any values in the form +// of utility functions or additional generated methods of the Any type. +// +// Example 1: Pack and unpack a message in C++. +// +// Foo foo = ...; +// Any any; +// any.PackFrom(foo); +// ... +// if (any.UnpackTo(&foo)) { +// ... +// } +// +// Example 2: Pack and unpack a message in Java. +// +// Foo foo = ...; +// Any any = Any.pack(foo); +// ... +// if (any.is(Foo.class)) { +// foo = any.unpack(Foo.class); +// } +// // or ... +// if (any.isSameTypeAs(Foo.getDefaultInstance())) { +// foo = any.unpack(Foo.getDefaultInstance()); +// } +// +// Example 3: Pack and unpack a message in Python. +// +// foo = Foo(...) +// any = Any() +// any.Pack(foo) +// ... +// if any.Is(Foo.DESCRIPTOR): +// any.Unpack(foo) +// ... +// +// Example 4: Pack and unpack a message in Go +// +// foo := &pb.Foo{...} +// any, err := anypb.New(foo) +// if err != nil { +// ... +// } +// ... +// foo := &pb.Foo{} +// if err := any.UnmarshalTo(foo); err != nil { +// ... +// } +// +// The pack methods provided by protobuf library will by default use +// 'type.googleapis.com/full.type.name' as the type URL and the unpack +// methods only use the fully qualified type name after the last '/' +// in the type URL, for example "foo.bar.com/x/y.z" will yield type +// name "y.z". +// +// JSON +// ==== +// The JSON representation of an `Any` value uses the regular +// representation of the deserialized, embedded message, with an +// additional field `@type` which contains the type URL. Example: +// +// package google.profile; +// message Person { +// string first_name = 1; +// string last_name = 2; +// } +// +// { +// "@type": "type.googleapis.com/google.profile.Person", +// "firstName": , +// "lastName": +// } +// +// If the embedded message type is well-known and has a custom JSON +// representation, that representation will be embedded adding a field +// `value` which holds the custom JSON in addition to the `@type` +// field. Example (for message [google.protobuf.Duration][]): +// +// { +// "@type": "type.googleapis.com/google.protobuf.Duration", +// "value": "1.212s" +// } +// +message Any { + // A URL/resource name that uniquely identifies the type of the serialized + // protocol buffer message. This string must contain at least + // one "/" character. The last segment of the URL's path must represent + // the fully qualified name of the type (as in + // `path/google.protobuf.Duration`). The name should be in a canonical form + // (e.g., leading "." is not accepted). + // + // In practice, teams usually precompile into the binary all types that they + // expect it to use in the context of Any. However, for URLs which use the + // scheme `http`, `https`, or no scheme, one can optionally set up a type + // server that maps type URLs to message definitions as follows: + // + // * If no scheme is provided, `https` is assumed. + // * An HTTP GET on the URL must yield a [google.protobuf.Type][] + // value in binary format, or produce an error. + // * Applications are allowed to cache lookup results based on the + // URL, or have them precompiled into a binary to avoid any + // lookup. Therefore, binary compatibility needs to be preserved + // on changes to types. (Use versioned type names to manage + // breaking changes.) + // + // Note: this functionality is not currently available in the official + // protobuf release, and it is not used for type URLs beginning with + // type.googleapis.com. As of May 2023, there are no widely used type server + // implementations and no plans to implement one. + // + // Schemes other than `http`, `https` (or the empty scheme) might be + // used with implementation specific semantics. + // + string type_url = 1; + + // Must be a valid serialized protocol buffer of the above specified type. + bytes value = 2; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/protobuf/descriptor.proto b/node_modules/@google-cloud/firestore/build/protos/google/protobuf/descriptor.proto new file mode 100644 index 0000000..8f619e8 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/protobuf/descriptor.proto @@ -0,0 +1,1219 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. +// +// The messages in this file describe the definitions found in .proto files. +// A valid .proto file can be translated directly to a FileDescriptorProto +// without any other information (e.g. without reading its imports). + +syntax = "proto2"; + +package google.protobuf; + +option go_package = "google.golang.org/protobuf/types/descriptorpb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "DescriptorProtos"; +option csharp_namespace = "Google.Protobuf.Reflection"; +option objc_class_prefix = "GPB"; +option cc_enable_arenas = true; + +// descriptor.proto must be optimized for speed because reflection-based +// algorithms don't work during bootstrapping. +option optimize_for = SPEED; + +// The protocol compiler can output a FileDescriptorSet containing the .proto +// files it parses. +message FileDescriptorSet { + repeated FileDescriptorProto file = 1; +} + +// The full set of known editions. +enum Edition { + // A placeholder for an unknown edition value. + EDITION_UNKNOWN = 0; + + // Legacy syntax "editions". These pre-date editions, but behave much like + // distinct editions. These can't be used to specify the edition of proto + // files, but feature definitions must supply proto2/proto3 defaults for + // backwards compatibility. + EDITION_PROTO2 = 998; + EDITION_PROTO3 = 999; + + // Editions that have been released. The specific values are arbitrary and + // should not be depended on, but they will always be time-ordered for easy + // comparison. + EDITION_2023 = 1000; + EDITION_2024 = 1001; + + // Placeholder editions for testing feature resolution. These should not be + // used or relyed on outside of tests. + EDITION_1_TEST_ONLY = 1; + EDITION_2_TEST_ONLY = 2; + EDITION_99997_TEST_ONLY = 99997; + EDITION_99998_TEST_ONLY = 99998; + EDITION_99999_TEST_ONLY = 99999; + + // Placeholder for specifying unbounded edition support. This should only + // ever be used by plugins that can expect to never require any changes to + // support a new edition. + EDITION_MAX = 0x7FFFFFFF; +} + +// Describes a complete .proto file. +message FileDescriptorProto { + optional string name = 1; // file name, relative to root of source tree + optional string package = 2; // e.g. "foo", "foo.bar", etc. + + // Names of files imported by this file. + repeated string dependency = 3; + // Indexes of the public imported files in the dependency list above. + repeated int32 public_dependency = 10; + // Indexes of the weak imported files in the dependency list. + // For Google-internal migration only. Do not use. + repeated int32 weak_dependency = 11; + + // All top-level definitions in this file. + repeated DescriptorProto message_type = 4; + repeated EnumDescriptorProto enum_type = 5; + repeated ServiceDescriptorProto service = 6; + repeated FieldDescriptorProto extension = 7; + + optional FileOptions options = 8; + + // This field contains optional information about the original source code. + // You may safely remove this entire field without harming runtime + // functionality of the descriptors -- the information is needed only by + // development tools. + optional SourceCodeInfo source_code_info = 9; + + // The syntax of the proto file. + // The supported values are "proto2", "proto3", and "editions". + // + // If `edition` is present, this value must be "editions". + optional string syntax = 12; + + // The edition of the proto file. + optional Edition edition = 14; +} + +// Describes a message type. +message DescriptorProto { + optional string name = 1; + + repeated FieldDescriptorProto field = 2; + repeated FieldDescriptorProto extension = 6; + + repeated DescriptorProto nested_type = 3; + repeated EnumDescriptorProto enum_type = 4; + + message ExtensionRange { + optional int32 start = 1; // Inclusive. + optional int32 end = 2; // Exclusive. + + optional ExtensionRangeOptions options = 3; + } + repeated ExtensionRange extension_range = 5; + + repeated OneofDescriptorProto oneof_decl = 8; + + optional MessageOptions options = 7; + + // Range of reserved tag numbers. Reserved tag numbers may not be used by + // fields or extension ranges in the same message. Reserved ranges may + // not overlap. + message ReservedRange { + optional int32 start = 1; // Inclusive. + optional int32 end = 2; // Exclusive. + } + repeated ReservedRange reserved_range = 9; + // Reserved field names, which may not be used by fields in the same message. + // A given name may only be reserved once. + repeated string reserved_name = 10; +} + +message ExtensionRangeOptions { + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + message Declaration { + // The extension number declared within the extension range. + optional int32 number = 1; + + // The fully-qualified name of the extension field. There must be a leading + // dot in front of the full name. + optional string full_name = 2; + + // The fully-qualified type name of the extension field. Unlike + // Metadata.type, Declaration.type must have a leading dot for messages + // and enums. + optional string type = 3; + + // If true, indicates that the number is reserved in the extension range, + // and any extension field with the number will fail to compile. Set this + // when a declared extension field is deleted. + optional bool reserved = 5; + + // If true, indicates that the extension must be defined as repeated. + // Otherwise the extension must be defined as optional. + optional bool repeated = 6; + + reserved 4; // removed is_repeated + } + + // For external users: DO NOT USE. We are in the process of open sourcing + // extension declaration and executing internal cleanups before it can be + // used externally. + repeated Declaration declaration = 2 [retention = RETENTION_SOURCE]; + + // Any features defined in the specific edition. + optional FeatureSet features = 50; + + // The verification state of the extension range. + enum VerificationState { + // All the extensions of the range must be declared. + DECLARATION = 0; + UNVERIFIED = 1; + } + + // The verification state of the range. + // TODO: flip the default to DECLARATION once all empty ranges + // are marked as UNVERIFIED. + optional VerificationState verification = 3 + [default = UNVERIFIED, retention = RETENTION_SOURCE]; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +// Describes a field within a message. +message FieldDescriptorProto { + enum Type { + // 0 is reserved for errors. + // Order is weird for historical reasons. + TYPE_DOUBLE = 1; + TYPE_FLOAT = 2; + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if + // negative values are likely. + TYPE_INT64 = 3; + TYPE_UINT64 = 4; + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if + // negative values are likely. + TYPE_INT32 = 5; + TYPE_FIXED64 = 6; + TYPE_FIXED32 = 7; + TYPE_BOOL = 8; + TYPE_STRING = 9; + // Tag-delimited aggregate. + // Group type is deprecated and not supported after google.protobuf. However, Proto3 + // implementations should still be able to parse the group wire format and + // treat group fields as unknown fields. In Editions, the group wire format + // can be enabled via the `message_encoding` feature. + TYPE_GROUP = 10; + TYPE_MESSAGE = 11; // Length-delimited aggregate. + + // New in version 2. + TYPE_BYTES = 12; + TYPE_UINT32 = 13; + TYPE_ENUM = 14; + TYPE_SFIXED32 = 15; + TYPE_SFIXED64 = 16; + TYPE_SINT32 = 17; // Uses ZigZag encoding. + TYPE_SINT64 = 18; // Uses ZigZag encoding. + } + + enum Label { + // 0 is reserved for errors + LABEL_OPTIONAL = 1; + LABEL_REPEATED = 3; + // The required label is only allowed in google.protobuf. In proto3 and Editions + // it's explicitly prohibited. In Editions, the `field_presence` feature + // can be used to get this behavior. + LABEL_REQUIRED = 2; + } + + optional string name = 1; + optional int32 number = 3; + optional Label label = 4; + + // If type_name is set, this need not be set. If both this and type_name + // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. + optional Type type = 5; + + // For message and enum types, this is the name of the type. If the name + // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping + // rules are used to find the type (i.e. first the nested types within this + // message are searched, then within the parent, on up to the root + // namespace). + optional string type_name = 6; + + // For extensions, this is the name of the type being extended. It is + // resolved in the same manner as type_name. + optional string extendee = 2; + + // For numeric types, contains the original text representation of the value. + // For booleans, "true" or "false". + // For strings, contains the default text contents (not escaped in any way). + // For bytes, contains the C escaped value. All bytes >= 128 are escaped. + optional string default_value = 7; + + // If set, gives the index of a oneof in the containing type's oneof_decl + // list. This field is a member of that oneof. + optional int32 oneof_index = 9; + + // JSON name of this field. The value is set by protocol compiler. If the + // user has set a "json_name" option on this field, that option's value + // will be used. Otherwise, it's deduced from the field's name by converting + // it to camelCase. + optional string json_name = 10; + + optional FieldOptions options = 8; + + // If true, this is a proto3 "optional". When a proto3 field is optional, it + // tracks presence regardless of field type. + // + // When proto3_optional is true, this field must belong to a oneof to signal + // to old proto3 clients that presence is tracked for this field. This oneof + // is known as a "synthetic" oneof, and this field must be its sole member + // (each proto3 optional field gets its own synthetic oneof). Synthetic oneofs + // exist in the descriptor only, and do not generate any API. Synthetic oneofs + // must be ordered after all "real" oneofs. + // + // For message fields, proto3_optional doesn't create any semantic change, + // since non-repeated message fields always track presence. However it still + // indicates the semantic detail of whether the user wrote "optional" or not. + // This can be useful for round-tripping the .proto file. For consistency we + // give message fields a synthetic oneof also, even though it is not required + // to track presence. This is especially important because the parser can't + // tell if a field is a message or an enum, so it must always create a + // synthetic oneof. + // + // Proto2 optional fields do not set this flag, because they already indicate + // optional with `LABEL_OPTIONAL`. + optional bool proto3_optional = 17; +} + +// Describes a oneof. +message OneofDescriptorProto { + optional string name = 1; + optional OneofOptions options = 2; +} + +// Describes an enum type. +message EnumDescriptorProto { + optional string name = 1; + + repeated EnumValueDescriptorProto value = 2; + + optional EnumOptions options = 3; + + // Range of reserved numeric values. Reserved values may not be used by + // entries in the same enum. Reserved ranges may not overlap. + // + // Note that this is distinct from DescriptorProto.ReservedRange in that it + // is inclusive such that it can appropriately represent the entire int32 + // domain. + message EnumReservedRange { + optional int32 start = 1; // Inclusive. + optional int32 end = 2; // Inclusive. + } + + // Range of reserved numeric values. Reserved numeric values may not be used + // by enum values in the same enum declaration. Reserved ranges may not + // overlap. + repeated EnumReservedRange reserved_range = 4; + + // Reserved enum value names, which may not be reused. A given name may only + // be reserved once. + repeated string reserved_name = 5; +} + +// Describes a value within an enum. +message EnumValueDescriptorProto { + optional string name = 1; + optional int32 number = 2; + + optional EnumValueOptions options = 3; +} + +// Describes a service. +message ServiceDescriptorProto { + optional string name = 1; + repeated MethodDescriptorProto method = 2; + + optional ServiceOptions options = 3; +} + +// Describes a method of a service. +message MethodDescriptorProto { + optional string name = 1; + + // Input and output type names. These are resolved in the same way as + // FieldDescriptorProto.type_name, but must refer to a message type. + optional string input_type = 2; + optional string output_type = 3; + + optional MethodOptions options = 4; + + // Identifies if client streams multiple client messages + optional bool client_streaming = 5 [default = false]; + // Identifies if server streams multiple server messages + optional bool server_streaming = 6 [default = false]; +} + +// =================================================================== +// Options + +// Each of the definitions above may have "options" attached. These are +// just annotations which may cause code to be generated slightly differently +// or may contain hints for code that manipulates protocol messages. +// +// Clients may define custom options as extensions of the *Options messages. +// These extensions may not yet be known at parsing time, so the parser cannot +// store the values in them. Instead it stores them in a field in the *Options +// message called uninterpreted_option. This field must have the same name +// across all *Options messages. We then use this field to populate the +// extensions when we build a descriptor, at which point all protos have been +// parsed and so all extensions are known. +// +// Extension numbers for custom options may be chosen as follows: +// * For options which will only be used within a single application or +// organization, or for experimental options, use field numbers 50000 +// through 99999. It is up to you to ensure that you do not use the +// same number for multiple options. +// * For options which will be published and used publicly by multiple +// independent entities, e-mail protobuf-global-extension-registry@google.com +// to reserve extension numbers. Simply provide your project name (e.g. +// Objective-C plugin) and your project website (if available) -- there's no +// need to explain how you intend to use them. Usually you only need one +// extension number. You can declare multiple options with only one extension +// number by putting them in a sub-message. See the Custom Options section of +// the docs for examples: +// https://developers.google.com/protocol-buffers/docs/proto#options +// If this turns out to be popular, a web service will be set up +// to automatically assign option numbers. + +message FileOptions { + + // Sets the Java package where classes generated from this .proto will be + // placed. By default, the proto package is used, but this is often + // inappropriate because proto packages do not normally start with backwards + // domain names. + optional string java_package = 1; + + // Controls the name of the wrapper Java class generated for the .proto file. + // That class will always contain the .proto file's getDescriptor() method as + // well as any top-level extensions defined in the .proto file. + // If java_multiple_files is disabled, then all the other classes from the + // .proto file will be nested inside the single wrapper outer class. + optional string java_outer_classname = 8; + + // If enabled, then the Java code generator will generate a separate .java + // file for each top-level message, enum, and service defined in the .proto + // file. Thus, these types will *not* be nested inside the wrapper class + // named by java_outer_classname. However, the wrapper class will still be + // generated to contain the file's getDescriptor() method as well as any + // top-level extensions defined in the file. + optional bool java_multiple_files = 10 [default = false]; + + // This option does nothing. + optional bool java_generate_equals_and_hash = 20 [deprecated=true]; + + // If set true, then the Java2 code generator will generate code that + // throws an exception whenever an attempt is made to assign a non-UTF-8 + // byte sequence to a string field. + // Message reflection will do the same. + // However, an extension field still accepts non-UTF-8 byte sequences. + // This option has no effect on when used with the lite runtime. + optional bool java_string_check_utf8 = 27 [default = false]; + + // Generated classes can be optimized for speed or code size. + enum OptimizeMode { + SPEED = 1; // Generate complete code for parsing, serialization, + // etc. + CODE_SIZE = 2; // Use ReflectionOps to implement these methods. + LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime. + } + optional OptimizeMode optimize_for = 9 [default = SPEED]; + + // Sets the Go package where structs generated from this .proto will be + // placed. If omitted, the Go package will be derived from the following: + // - The basename of the package import path, if provided. + // - Otherwise, the package statement in the .proto file, if present. + // - Otherwise, the basename of the .proto file, without extension. + optional string go_package = 11; + + // Should generic services be generated in each language? "Generic" services + // are not specific to any particular RPC system. They are generated by the + // main code generators in each language (without additional plugins). + // Generic services were the only kind of service generation supported by + // early versions of google.protobuf. + // + // Generic services are now considered deprecated in favor of using plugins + // that generate code specific to your particular RPC system. Therefore, + // these default to false. Old code which depends on generic services should + // explicitly set them to true. + optional bool cc_generic_services = 16 [default = false]; + optional bool java_generic_services = 17 [default = false]; + optional bool py_generic_services = 18 [default = false]; + reserved 42; // removed php_generic_services + + // Is this file deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for everything in the file, or it will be completely ignored; in the very + // least, this is a formalization for deprecating files. + optional bool deprecated = 23 [default = false]; + + // Enables the use of arenas for the proto messages in this file. This applies + // only to generated classes for C++. + optional bool cc_enable_arenas = 31 [default = true]; + + // Sets the objective c class prefix which is prepended to all objective c + // generated classes from this .proto. There is no default. + optional string objc_class_prefix = 36; + + // Namespace for generated classes; defaults to the package. + optional string csharp_namespace = 37; + + // By default Swift generators will take the proto package and CamelCase it + // replacing '.' with underscore and use that to prefix the types/symbols + // defined. When this options is provided, they will use this value instead + // to prefix the types/symbols defined. + optional string swift_prefix = 39; + + // Sets the php class prefix which is prepended to all php generated classes + // from this .proto. Default is empty. + optional string php_class_prefix = 40; + + // Use this option to change the namespace of php generated classes. Default + // is empty. When this option is empty, the package name will be used for + // determining the namespace. + optional string php_namespace = 41; + + // Use this option to change the namespace of php generated metadata classes. + // Default is empty. When this option is empty, the proto file name will be + // used for determining the namespace. + optional string php_metadata_namespace = 44; + + // Use this option to change the package of ruby generated classes. Default + // is empty. When this option is not set, the package name will be used for + // determining the ruby package. + optional string ruby_package = 45; + + // Any features defined in the specific edition. + optional FeatureSet features = 50; + + // The parser stores options it doesn't recognize here. + // See the documentation for the "Options" section above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. + // See the documentation for the "Options" section above. + extensions 1000 to max; + + reserved 38; +} + +message MessageOptions { + // Set true to use the old proto1 MessageSet wire format for extensions. + // This is provided for backwards-compatibility with the MessageSet wire + // format. You should not use this for any other reason: It's less + // efficient, has fewer features, and is more complicated. + // + // The message must be defined exactly as follows: + // message Foo { + // option message_set_wire_format = true; + // extensions 4 to max; + // } + // Note that the message cannot have any defined fields; MessageSets only + // have extensions. + // + // All extensions of your type must be singular messages; e.g. they cannot + // be int32s, enums, or repeated messages. + // + // Because this is an option, the above two restrictions are not enforced by + // the protocol compiler. + optional bool message_set_wire_format = 1 [default = false]; + + // Disables the generation of the standard "descriptor()" accessor, which can + // conflict with a field of the same name. This is meant to make migration + // from proto1 easier; new code should avoid fields named "descriptor". + optional bool no_standard_descriptor_accessor = 2 [default = false]; + + // Is this message deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the message, or it will be completely ignored; in the very least, + // this is a formalization for deprecating messages. + optional bool deprecated = 3 [default = false]; + + reserved 4, 5, 6; + + // Whether the message is an automatically generated map entry type for the + // maps field. + // + // For maps fields: + // map map_field = 1; + // The parsed descriptor looks like: + // message MapFieldEntry { + // option map_entry = true; + // optional KeyType key = 1; + // optional ValueType value = 2; + // } + // repeated MapFieldEntry map_field = 1; + // + // Implementations may choose not to generate the map_entry=true message, but + // use a native map in the target language to hold the keys and values. + // The reflection APIs in such implementations still need to work as + // if the field is a repeated message field. + // + // NOTE: Do not set the option in .proto files. Always use the maps syntax + // instead. The option should only be implicitly set by the proto compiler + // parser. + optional bool map_entry = 7; + + reserved 8; // javalite_serializable + reserved 9; // javanano_as_lite + + // Enable the legacy handling of JSON field name conflicts. This lowercases + // and strips underscored from the fields before comparison in proto3 only. + // The new behavior takes `json_name` into account and applies to proto2 as + // well. + // + // This should only be used as a temporary measure against broken builds due + // to the change in behavior for JSON field name conflicts. + // + // TODO This is legacy behavior we plan to remove once downstream + // teams have had time to migrate. + optional bool deprecated_legacy_json_field_conflicts = 11 [deprecated = true]; + + // Any features defined in the specific edition. + optional FeatureSet features = 12; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message FieldOptions { + // The ctype option instructs the C++ code generator to use a different + // representation of the field than it normally would. See the specific + // options below. This option is only implemented to support use of + // [ctype=CORD] and [ctype=STRING] (the default) on non-repeated fields of + // type "bytes" in the open source release -- sorry, we'll try to include + // other types in a future version! + optional CType ctype = 1 [default = STRING]; + enum CType { + // Default mode. + STRING = 0; + + // The option [ctype=CORD] may be applied to a non-repeated field of type + // "bytes". It indicates that in C++, the data should be stored in a Cord + // instead of a string. For very large strings, this may reduce memory + // fragmentation. It may also allow better performance when parsing from a + // Cord, or when parsing with aliasing enabled, as the parsed Cord may then + // alias the original buffer. + CORD = 1; + + STRING_PIECE = 2; + } + // The packed option can be enabled for repeated primitive fields to enable + // a more efficient representation on the wire. Rather than repeatedly + // writing the tag and type for each element, the entire array is encoded as + // a single length-delimited blob. In proto3, only explicit setting it to + // false will avoid using packed encoding. This option is prohibited in + // Editions, but the `repeated_field_encoding` feature can be used to control + // the behavior. + optional bool packed = 2; + + // The jstype option determines the JavaScript type used for values of the + // field. The option is permitted only for 64 bit integral and fixed types + // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING + // is represented as JavaScript string, which avoids loss of precision that + // can happen when a large value is converted to a floating point JavaScript. + // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to + // use the JavaScript "number" type. The behavior of the default option + // JS_NORMAL is implementation dependent. + // + // This option is an enum to permit additional types to be added, e.g. + // goog.math.Integer. + optional JSType jstype = 6 [default = JS_NORMAL]; + enum JSType { + // Use the default type. + JS_NORMAL = 0; + + // Use JavaScript strings. + JS_STRING = 1; + + // Use JavaScript numbers. + JS_NUMBER = 2; + } + + // Should this field be parsed lazily? Lazy applies only to message-type + // fields. It means that when the outer message is initially parsed, the + // inner message's contents will not be parsed but instead stored in encoded + // form. The inner message will actually be parsed when it is first accessed. + // + // This is only a hint. Implementations are free to choose whether to use + // eager or lazy parsing regardless of the value of this option. However, + // setting this option true suggests that the protocol author believes that + // using lazy parsing on this field is worth the additional bookkeeping + // overhead typically needed to implement it. + // + // This option does not affect the public interface of any generated code; + // all method signatures remain the same. Furthermore, thread-safety of the + // interface is not affected by this option; const methods remain safe to + // call from multiple threads concurrently, while non-const methods continue + // to require exclusive access. + // + // Note that lazy message fields are still eagerly verified to check + // ill-formed wireformat or missing required fields. Calling IsInitialized() + // on the outer message would fail if the inner message has missing required + // fields. Failed verification would result in parsing failure (except when + // uninitialized messages are acceptable). + optional bool lazy = 5 [default = false]; + + // unverified_lazy does no correctness checks on the byte stream. This should + // only be used where lazy with verification is prohibitive for performance + // reasons. + optional bool unverified_lazy = 15 [default = false]; + + // Is this field deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for accessors, or it will be completely ignored; in the very least, this + // is a formalization for deprecating fields. + optional bool deprecated = 3 [default = false]; + + // For Google-internal migration only. Do not use. + optional bool weak = 10 [default = false]; + + // Indicate that the field value should not be printed out when using debug + // formats, e.g. when the field contains sensitive credentials. + optional bool debug_redact = 16 [default = false]; + + // If set to RETENTION_SOURCE, the option will be omitted from the binary. + // Note: as of January 2023, support for this is in progress and does not yet + // have an effect (b/264593489). + enum OptionRetention { + RETENTION_UNKNOWN = 0; + RETENTION_RUNTIME = 1; + RETENTION_SOURCE = 2; + } + + optional OptionRetention retention = 17; + + // This indicates the types of entities that the field may apply to when used + // as an option. If it is unset, then the field may be freely used as an + // option on any kind of entity. Note: as of January 2023, support for this is + // in progress and does not yet have an effect (b/264593489). + enum OptionTargetType { + TARGET_TYPE_UNKNOWN = 0; + TARGET_TYPE_FILE = 1; + TARGET_TYPE_EXTENSION_RANGE = 2; + TARGET_TYPE_MESSAGE = 3; + TARGET_TYPE_FIELD = 4; + TARGET_TYPE_ONEOF = 5; + TARGET_TYPE_ENUM = 6; + TARGET_TYPE_ENUM_ENTRY = 7; + TARGET_TYPE_SERVICE = 8; + TARGET_TYPE_METHOD = 9; + } + + repeated OptionTargetType targets = 19; + + message EditionDefault { + optional Edition edition = 3; + optional string value = 2; // Textproto value. + } + repeated EditionDefault edition_defaults = 20; + + // Any features defined in the specific edition. + optional FeatureSet features = 21; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; + + reserved 4; // removed jtype + reserved 18; // reserve target, target_obsolete_do_not_use +} + +message OneofOptions { + // Any features defined in the specific edition. + optional FeatureSet features = 1; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message EnumOptions { + + // Set this option to true to allow mapping different tag names to the same + // value. + optional bool allow_alias = 2; + + // Is this enum deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the enum, or it will be completely ignored; in the very least, this + // is a formalization for deprecating enums. + optional bool deprecated = 3 [default = false]; + + reserved 5; // javanano_as_lite + + // Enable the legacy handling of JSON field name conflicts. This lowercases + // and strips underscored from the fields before comparison in proto3 only. + // The new behavior takes `json_name` into account and applies to proto2 as + // well. + // TODO Remove this legacy behavior once downstream teams have + // had time to migrate. + optional bool deprecated_legacy_json_field_conflicts = 6 [deprecated = true]; + + // Any features defined in the specific edition. + optional FeatureSet features = 7; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message EnumValueOptions { + // Is this enum value deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the enum value, or it will be completely ignored; in the very least, + // this is a formalization for deprecating enum values. + optional bool deprecated = 1 [default = false]; + + // Any features defined in the specific edition. + optional FeatureSet features = 2; + + // Indicate that fields annotated with this enum value should not be printed + // out when using debug formats, e.g. when the field contains sensitive + // credentials. + optional bool debug_redact = 3 [default = false]; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message ServiceOptions { + + // Any features defined in the specific edition. + optional FeatureSet features = 34; + + // Note: Field numbers 1 through 32 are reserved for Google's internal RPC + // framework. We apologize for hoarding these numbers to ourselves, but + // we were already using them long before we decided to release Protocol + // Buffers. + + // Is this service deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the service, or it will be completely ignored; in the very least, + // this is a formalization for deprecating services. + optional bool deprecated = 33 [default = false]; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message MethodOptions { + + // Note: Field numbers 1 through 32 are reserved for Google's internal RPC + // framework. We apologize for hoarding these numbers to ourselves, but + // we were already using them long before we decided to release Protocol + // Buffers. + + // Is this method deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the method, or it will be completely ignored; in the very least, + // this is a formalization for deprecating methods. + optional bool deprecated = 33 [default = false]; + + // Is this method side-effect-free (or safe in HTTP parlance), or idempotent, + // or neither? HTTP based RPC implementation may choose GET verb for safe + // methods, and PUT verb for idempotent methods instead of the default POST. + enum IdempotencyLevel { + IDEMPOTENCY_UNKNOWN = 0; + NO_SIDE_EFFECTS = 1; // implies idempotent + IDEMPOTENT = 2; // idempotent, but may have side effects + } + optional IdempotencyLevel idempotency_level = 34 + [default = IDEMPOTENCY_UNKNOWN]; + + // Any features defined in the specific edition. + optional FeatureSet features = 35; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +// A message representing a option the parser does not recognize. This only +// appears in options protos created by the compiler::Parser class. +// DescriptorPool resolves these when building Descriptor objects. Therefore, +// options protos in descriptor objects (e.g. returned by Descriptor::options(), +// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions +// in them. +message UninterpretedOption { + // The name of the uninterpreted option. Each string represents a segment in + // a dot-separated name. is_extension is true iff a segment represents an + // extension (denoted with parentheses in options specs in .proto files). + // E.g.,{ ["foo", false], ["bar.baz", true], ["moo", false] } represents + // "foo.(bar.baz).moo". + message NamePart { + required string name_part = 1; + required bool is_extension = 2; + } + repeated NamePart name = 2; + + // The value of the uninterpreted option, in whatever type the tokenizer + // identified it as during parsing. Exactly one of these should be set. + optional string identifier_value = 3; + optional uint64 positive_int_value = 4; + optional int64 negative_int_value = 5; + optional double double_value = 6; + optional bytes string_value = 7; + optional string aggregate_value = 8; +} + +// =================================================================== +// Features + +// TODO Enums in C++ gencode (and potentially other languages) are +// not well scoped. This means that each of the feature enums below can clash +// with each other. The short names we've chosen maximize call-site +// readability, but leave us very open to this scenario. A future feature will +// be designed and implemented to handle this, hopefully before we ever hit a +// conflict here. +message FeatureSet { + enum FieldPresence { + FIELD_PRESENCE_UNKNOWN = 0; + EXPLICIT = 1; + IMPLICIT = 2; + LEGACY_REQUIRED = 3; + } + optional FieldPresence field_presence = 1 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_FIELD, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "EXPLICIT" }, + edition_defaults = { edition: EDITION_PROTO3, value: "IMPLICIT" }, + edition_defaults = { edition: EDITION_2023, value: "EXPLICIT" } + ]; + + enum EnumType { + ENUM_TYPE_UNKNOWN = 0; + OPEN = 1; + CLOSED = 2; + } + optional EnumType enum_type = 2 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_ENUM, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "CLOSED" }, + edition_defaults = { edition: EDITION_PROTO3, value: "OPEN" } + ]; + + enum RepeatedFieldEncoding { + REPEATED_FIELD_ENCODING_UNKNOWN = 0; + PACKED = 1; + EXPANDED = 2; + } + optional RepeatedFieldEncoding repeated_field_encoding = 3 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_FIELD, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "EXPANDED" }, + edition_defaults = { edition: EDITION_PROTO3, value: "PACKED" } + ]; + + enum Utf8Validation { + UTF8_VALIDATION_UNKNOWN = 0; + VERIFY = 2; + NONE = 3; + } + optional Utf8Validation utf8_validation = 4 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_FIELD, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "NONE" }, + edition_defaults = { edition: EDITION_PROTO3, value: "VERIFY" } + ]; + + enum MessageEncoding { + MESSAGE_ENCODING_UNKNOWN = 0; + LENGTH_PREFIXED = 1; + DELIMITED = 2; + } + optional MessageEncoding message_encoding = 5 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_FIELD, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "LENGTH_PREFIXED" } + ]; + + enum JsonFormat { + JSON_FORMAT_UNKNOWN = 0; + ALLOW = 1; + LEGACY_BEST_EFFORT = 2; + } + optional JsonFormat json_format = 6 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_MESSAGE, + targets = TARGET_TYPE_ENUM, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "LEGACY_BEST_EFFORT" }, + edition_defaults = { edition: EDITION_PROTO3, value: "ALLOW" } + ]; + + reserved 999; + + extensions 1000; // for Protobuf C++ + extensions 1001; // for Protobuf Java + extensions 1002; // for Protobuf Go + + extensions 9995 to 9999; // For internal testing + extensions 10000; // for https://github.com/bufbuild/protobuf-es +} + +// A compiled specification for the defaults of a set of features. These +// messages are generated from FeatureSet extensions and can be used to seed +// feature resolution. The resolution with this object becomes a simple search +// for the closest matching edition, followed by proto merges. +message FeatureSetDefaults { + // A map from every known edition with a unique set of defaults to its + // defaults. Not all editions may be contained here. For a given edition, + // the defaults at the closest matching edition ordered at or before it should + // be used. This field must be in strict ascending order by edition. + message FeatureSetEditionDefault { + optional Edition edition = 3; + optional FeatureSet features = 2; + } + repeated FeatureSetEditionDefault defaults = 1; + + // The minimum supported edition (inclusive) when this was constructed. + // Editions before this will not have defaults. + optional Edition minimum_edition = 4; + + // The maximum known edition (inclusive) when this was constructed. Editions + // after this will not have reliable defaults. + optional Edition maximum_edition = 5; +} + +// =================================================================== +// Optional source code info + +// Encapsulates information about the original source file from which a +// FileDescriptorProto was generated. +message SourceCodeInfo { + // A Location identifies a piece of source code in a .proto file which + // corresponds to a particular definition. This information is intended + // to be useful to IDEs, code indexers, documentation generators, and similar + // tools. + // + // For example, say we have a file like: + // message Foo { + // optional string foo = 1; + // } + // Let's look at just the field definition: + // optional string foo = 1; + // ^ ^^ ^^ ^ ^^^ + // a bc de f ghi + // We have the following locations: + // span path represents + // [a,i) [ 4, 0, 2, 0 ] The whole field definition. + // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). + // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). + // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). + // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). + // + // Notes: + // - A location may refer to a repeated field itself (i.e. not to any + // particular index within it). This is used whenever a set of elements are + // logically enclosed in a single code segment. For example, an entire + // extend block (possibly containing multiple extension definitions) will + // have an outer location whose path refers to the "extensions" repeated + // field without an index. + // - Multiple locations may have the same path. This happens when a single + // logical declaration is spread out across multiple places. The most + // obvious example is the "extend" block again -- there may be multiple + // extend blocks in the same scope, each of which will have the same path. + // - A location's span is not always a subset of its parent's span. For + // example, the "extendee" of an extension declaration appears at the + // beginning of the "extend" block and is shared by all extensions within + // the block. + // - Just because a location's span is a subset of some other location's span + // does not mean that it is a descendant. For example, a "group" defines + // both a type and a field in a single declaration. Thus, the locations + // corresponding to the type and field and their components will overlap. + // - Code which tries to interpret locations should probably be designed to + // ignore those that it doesn't understand, as more types of locations could + // be recorded in the future. + repeated Location location = 1; + message Location { + // Identifies which part of the FileDescriptorProto was defined at this + // location. + // + // Each element is a field number or an index. They form a path from + // the root FileDescriptorProto to the place where the definition appears. + // For example, this path: + // [ 4, 3, 2, 7, 1 ] + // refers to: + // file.message_type(3) // 4, 3 + // .field(7) // 2, 7 + // .name() // 1 + // This is because FileDescriptorProto.message_type has field number 4: + // repeated DescriptorProto message_type = 4; + // and DescriptorProto.field has field number 2: + // repeated FieldDescriptorProto field = 2; + // and FieldDescriptorProto.name has field number 1: + // optional string name = 1; + // + // Thus, the above path gives the location of a field name. If we removed + // the last element: + // [ 4, 3, 2, 7 ] + // this path refers to the whole field declaration (from the beginning + // of the label to the terminating semicolon). + repeated int32 path = 1 [packed = true]; + + // Always has exactly three or four elements: start line, start column, + // end line (optional, otherwise assumed same as start line), end column. + // These are packed into a single field for efficiency. Note that line + // and column numbers are zero-based -- typically you will want to add + // 1 to each before displaying to a user. + repeated int32 span = 2 [packed = true]; + + // If this SourceCodeInfo represents a complete declaration, these are any + // comments appearing before and after the declaration which appear to be + // attached to the declaration. + // + // A series of line comments appearing on consecutive lines, with no other + // tokens appearing on those lines, will be treated as a single comment. + // + // leading_detached_comments will keep paragraphs of comments that appear + // before (but not connected to) the current element. Each paragraph, + // separated by empty lines, will be one comment element in the repeated + // field. + // + // Only the comment content is provided; comment markers (e.g. //) are + // stripped out. For block comments, leading whitespace and an asterisk + // will be stripped from the beginning of each line other than the first. + // Newlines are included in the output. + // + // Examples: + // + // optional int32 foo = 1; // Comment attached to foo. + // // Comment attached to bar. + // optional int32 bar = 2; + // + // optional string baz = 3; + // // Comment attached to baz. + // // Another line attached to baz. + // + // // Comment attached to moo. + // // + // // Another line attached to moo. + // optional double moo = 4; + // + // // Detached comment for corge. This is not leading or trailing comments + // // to moo or corge because there are blank lines separating it from + // // both. + // + // // Detached comment for corge paragraph 2. + // + // optional string corge = 5; + // /* Block comment attached + // * to corge. Leading asterisks + // * will be removed. */ + // /* Block comment attached to + // * grault. */ + // optional int32 grault = 6; + // + // // ignored detached comments. + optional string leading_comments = 3; + optional string trailing_comments = 4; + repeated string leading_detached_comments = 6; + } +} + +// Describes the relationship between generated code and its original source +// file. A GeneratedCodeInfo message is associated with only one generated +// source file, but may contain references to different source .proto files. +message GeneratedCodeInfo { + // An Annotation connects some span of text in generated code to an element + // of its generating .proto file. + repeated Annotation annotation = 1; + message Annotation { + // Identifies the element in the original source .proto file. This field + // is formatted the same as SourceCodeInfo.Location.path. + repeated int32 path = 1 [packed = true]; + + // Identifies the filesystem path to the original source .proto. + optional string source_file = 2; + + // Identifies the starting offset in bytes in the generated code + // that relates to the identified object. + optional int32 begin = 3; + + // Identifies the ending offset in bytes in the generated code that + // relates to the identified object. The end offset should be one past + // the last relevant byte (so the length of the text = end - begin). + optional int32 end = 4; + + // Represents the identified object's effect on the element in the original + // .proto file. + enum Semantic { + // There is no effect or the effect is indescribable. + NONE = 0; + // The element is set or otherwise mutated. + SET = 1; + // An alias to the element is returned. + ALIAS = 2; + } + optional Semantic semantic = 5; + } +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/protobuf/duration.proto b/node_modules/@google-cloud/firestore/build/protos/google/protobuf/duration.proto new file mode 100644 index 0000000..41f40c2 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/protobuf/duration.proto @@ -0,0 +1,115 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/protobuf/types/known/durationpb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "DurationProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; + +// A Duration represents a signed, fixed-length span of time represented +// as a count of seconds and fractions of seconds at nanosecond +// resolution. It is independent of any calendar and concepts like "day" +// or "month". It is related to Timestamp in that the difference between +// two Timestamp values is a Duration and it can be added or subtracted +// from a Timestamp. Range is approximately +-10,000 years. +// +// # Examples +// +// Example 1: Compute Duration from two Timestamps in pseudo code. +// +// Timestamp start = ...; +// Timestamp end = ...; +// Duration duration = ...; +// +// duration.seconds = end.seconds - start.seconds; +// duration.nanos = end.nanos - start.nanos; +// +// if (duration.seconds < 0 && duration.nanos > 0) { +// duration.seconds += 1; +// duration.nanos -= 1000000000; +// } else if (duration.seconds > 0 && duration.nanos < 0) { +// duration.seconds -= 1; +// duration.nanos += 1000000000; +// } +// +// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. +// +// Timestamp start = ...; +// Duration duration = ...; +// Timestamp end = ...; +// +// end.seconds = start.seconds + duration.seconds; +// end.nanos = start.nanos + duration.nanos; +// +// if (end.nanos < 0) { +// end.seconds -= 1; +// end.nanos += 1000000000; +// } else if (end.nanos >= 1000000000) { +// end.seconds += 1; +// end.nanos -= 1000000000; +// } +// +// Example 3: Compute Duration from datetime.timedelta in Python. +// +// td = datetime.timedelta(days=3, minutes=10) +// duration = Duration() +// duration.FromTimedelta(td) +// +// # JSON Mapping +// +// In JSON format, the Duration type is encoded as a string rather than an +// object, where the string ends in the suffix "s" (indicating seconds) and +// is preceded by the number of seconds, with nanoseconds expressed as +// fractional seconds. For example, 3 seconds with 0 nanoseconds should be +// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should +// be expressed in JSON format as "3.000000001s", and 3 seconds and 1 +// microsecond should be expressed in JSON format as "3.000001s". +// +message Duration { + // Signed seconds of the span of time. Must be from -315,576,000,000 + // to +315,576,000,000 inclusive. Note: these bounds are computed from: + // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years + int64 seconds = 1; + + // Signed fractions of a second at nanosecond resolution of the span + // of time. Durations less than one second are represented with a 0 + // `seconds` field and a positive or negative `nanos` field. For durations + // of one second or more, a non-zero value for the `nanos` field must be + // of the same sign as the `seconds` field. Must be from -999,999,999 + // to +999,999,999 inclusive. + int32 nanos = 2; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/protobuf/empty.proto b/node_modules/@google-cloud/firestore/build/protos/google/protobuf/empty.proto new file mode 100644 index 0000000..b87c89d --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/protobuf/empty.proto @@ -0,0 +1,51 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option go_package = "google.golang.org/protobuf/types/known/emptypb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "EmptyProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; +option cc_enable_arenas = true; + +// A generic empty message that you can re-use to avoid defining duplicated +// empty messages in your APIs. A typical example is to use it as the request +// or the response type of an API method. For instance: +// +// service Foo { +// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); +// } +// +message Empty {} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/protobuf/field_mask.proto b/node_modules/@google-cloud/firestore/build/protos/google/protobuf/field_mask.proto new file mode 100644 index 0000000..b28334b --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/protobuf/field_mask.proto @@ -0,0 +1,245 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option java_package = "com.google.protobuf"; +option java_outer_classname = "FieldMaskProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; +option go_package = "google.golang.org/protobuf/types/known/fieldmaskpb"; +option cc_enable_arenas = true; + +// `FieldMask` represents a set of symbolic field paths, for example: +// +// paths: "f.a" +// paths: "f.b.d" +// +// Here `f` represents a field in some root message, `a` and `b` +// fields in the message found in `f`, and `d` a field found in the +// message in `f.b`. +// +// Field masks are used to specify a subset of fields that should be +// returned by a get operation or modified by an update operation. +// Field masks also have a custom JSON encoding (see below). +// +// # Field Masks in Projections +// +// When used in the context of a projection, a response message or +// sub-message is filtered by the API to only contain those fields as +// specified in the mask. For example, if the mask in the previous +// example is applied to a response message as follows: +// +// f { +// a : 22 +// b { +// d : 1 +// x : 2 +// } +// y : 13 +// } +// z: 8 +// +// The result will not contain specific values for fields x,y and z +// (their value will be set to the default, and omitted in proto text +// output): +// +// +// f { +// a : 22 +// b { +// d : 1 +// } +// } +// +// A repeated field is not allowed except at the last position of a +// paths string. +// +// If a FieldMask object is not present in a get operation, the +// operation applies to all fields (as if a FieldMask of all fields +// had been specified). +// +// Note that a field mask does not necessarily apply to the +// top-level response message. In case of a REST get operation, the +// field mask applies directly to the response, but in case of a REST +// list operation, the mask instead applies to each individual message +// in the returned resource list. In case of a REST custom method, +// other definitions may be used. Where the mask applies will be +// clearly documented together with its declaration in the API. In +// any case, the effect on the returned resource/resources is required +// behavior for APIs. +// +// # Field Masks in Update Operations +// +// A field mask in update operations specifies which fields of the +// targeted resource are going to be updated. The API is required +// to only change the values of the fields as specified in the mask +// and leave the others untouched. If a resource is passed in to +// describe the updated values, the API ignores the values of all +// fields not covered by the mask. +// +// If a repeated field is specified for an update operation, new values will +// be appended to the existing repeated field in the target resource. Note that +// a repeated field is only allowed in the last position of a `paths` string. +// +// If a sub-message is specified in the last position of the field mask for an +// update operation, then new value will be merged into the existing sub-message +// in the target resource. +// +// For example, given the target message: +// +// f { +// b { +// d: 1 +// x: 2 +// } +// c: [1] +// } +// +// And an update message: +// +// f { +// b { +// d: 10 +// } +// c: [2] +// } +// +// then if the field mask is: +// +// paths: ["f.b", "f.c"] +// +// then the result will be: +// +// f { +// b { +// d: 10 +// x: 2 +// } +// c: [1, 2] +// } +// +// An implementation may provide options to override this default behavior for +// repeated and message fields. +// +// In order to reset a field's value to the default, the field must +// be in the mask and set to the default value in the provided resource. +// Hence, in order to reset all fields of a resource, provide a default +// instance of the resource and set all fields in the mask, or do +// not provide a mask as described below. +// +// If a field mask is not present on update, the operation applies to +// all fields (as if a field mask of all fields has been specified). +// Note that in the presence of schema evolution, this may mean that +// fields the client does not know and has therefore not filled into +// the request will be reset to their default. If this is unwanted +// behavior, a specific service may require a client to always specify +// a field mask, producing an error if not. +// +// As with get operations, the location of the resource which +// describes the updated values in the request message depends on the +// operation kind. In any case, the effect of the field mask is +// required to be honored by the API. +// +// ## Considerations for HTTP REST +// +// The HTTP kind of an update operation which uses a field mask must +// be set to PATCH instead of PUT in order to satisfy HTTP semantics +// (PUT must only be used for full updates). +// +// # JSON Encoding of Field Masks +// +// In JSON, a field mask is encoded as a single string where paths are +// separated by a comma. Fields name in each path are converted +// to/from lower-camel naming conventions. +// +// As an example, consider the following message declarations: +// +// message Profile { +// User user = 1; +// Photo photo = 2; +// } +// message User { +// string display_name = 1; +// string address = 2; +// } +// +// In proto a field mask for `Profile` may look as such: +// +// mask { +// paths: "user.display_name" +// paths: "photo" +// } +// +// In JSON, the same mask is represented as below: +// +// { +// mask: "user.displayName,photo" +// } +// +// # Field Masks and Oneof Fields +// +// Field masks treat fields in oneofs just as regular fields. Consider the +// following message: +// +// message SampleMessage { +// oneof test_oneof { +// string name = 4; +// SubMessage sub_message = 9; +// } +// } +// +// The field mask can be: +// +// mask { +// paths: "name" +// } +// +// Or: +// +// mask { +// paths: "sub_message" +// } +// +// Note that oneof type names ("test_oneof" in this case) cannot be used in +// paths. +// +// ## Field Mask Verification +// +// The implementation of any API method which has a FieldMask type field in the +// request should verify the included field paths, and return an +// `INVALID_ARGUMENT` error if any path is unmappable. +message FieldMask { + // The set of field mask paths. + repeated string paths = 1; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/protobuf/struct.proto b/node_modules/@google-cloud/firestore/build/protos/google/protobuf/struct.proto new file mode 100644 index 0000000..1bf0c1a --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/protobuf/struct.proto @@ -0,0 +1,95 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/protobuf/types/known/structpb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "StructProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; + +// `Struct` represents a structured data value, consisting of fields +// which map to dynamically typed values. In some languages, `Struct` +// might be supported by a native representation. For example, in +// scripting languages like JS a struct is represented as an +// object. The details of that representation are described together +// with the proto support for the language. +// +// The JSON representation for `Struct` is JSON object. +message Struct { + // Unordered map of dynamically typed values. + map fields = 1; +} + +// `Value` represents a dynamically typed value which can be either +// null, a number, a string, a boolean, a recursive struct value, or a +// list of values. A producer of value is expected to set one of these +// variants. Absence of any variant indicates an error. +// +// The JSON representation for `Value` is JSON value. +message Value { + // The kind of value. + oneof kind { + // Represents a null value. + NullValue null_value = 1; + // Represents a double value. + double number_value = 2; + // Represents a string value. + string string_value = 3; + // Represents a boolean value. + bool bool_value = 4; + // Represents a structured value. + Struct struct_value = 5; + // Represents a repeated `Value`. + ListValue list_value = 6; + } +} + +// `NullValue` is a singleton enumeration to represent the null value for the +// `Value` type union. +// +// The JSON representation for `NullValue` is JSON `null`. +enum NullValue { + // Null value. + NULL_VALUE = 0; +} + +// `ListValue` is a wrapper around a repeated field of values. +// +// The JSON representation for `ListValue` is JSON array. +message ListValue { + // Repeated field of dynamically typed values. + repeated Value values = 1; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/protobuf/timestamp.proto b/node_modules/@google-cloud/firestore/build/protos/google/protobuf/timestamp.proto new file mode 100644 index 0000000..fd0bc07 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/protobuf/timestamp.proto @@ -0,0 +1,144 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/protobuf/types/known/timestamppb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "TimestampProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; + +// A Timestamp represents a point in time independent of any time zone or local +// calendar, encoded as a count of seconds and fractions of seconds at +// nanosecond resolution. The count is relative to an epoch at UTC midnight on +// January 1, 1970, in the proleptic Gregorian calendar which extends the +// Gregorian calendar backwards to year one. +// +// All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap +// second table is needed for interpretation, using a [24-hour linear +// smear](https://developers.google.com/time/smear). +// +// The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By +// restricting to that range, we ensure that we can convert to and from [RFC +// 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings. +// +// # Examples +// +// Example 1: Compute Timestamp from POSIX `time()`. +// +// Timestamp timestamp; +// timestamp.set_seconds(time(NULL)); +// timestamp.set_nanos(0); +// +// Example 2: Compute Timestamp from POSIX `gettimeofday()`. +// +// struct timeval tv; +// gettimeofday(&tv, NULL); +// +// Timestamp timestamp; +// timestamp.set_seconds(tv.tv_sec); +// timestamp.set_nanos(tv.tv_usec * 1000); +// +// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. +// +// FILETIME ft; +// GetSystemTimeAsFileTime(&ft); +// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; +// +// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z +// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. +// Timestamp timestamp; +// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); +// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); +// +// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. +// +// long millis = System.currentTimeMillis(); +// +// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) +// .setNanos((int) ((millis % 1000) * 1000000)).build(); +// +// Example 5: Compute Timestamp from Java `Instant.now()`. +// +// Instant now = Instant.now(); +// +// Timestamp timestamp = +// Timestamp.newBuilder().setSeconds(now.getEpochSecond()) +// .setNanos(now.getNano()).build(); +// +// Example 6: Compute Timestamp from current time in Python. +// +// timestamp = Timestamp() +// timestamp.GetCurrentTime() +// +// # JSON Mapping +// +// In JSON format, the Timestamp type is encoded as a string in the +// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the +// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" +// where {year} is always expressed using four digits while {month}, {day}, +// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional +// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), +// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone +// is required. A proto3 JSON serializer should always use UTC (as indicated by +// "Z") when printing the Timestamp type and a proto3 JSON parser should be +// able to accept both UTC and other timezones (as indicated by an offset). +// +// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past +// 01:30 UTC on January 15, 2017. +// +// In JavaScript, one can convert a Date object to this format using the +// standard +// [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) +// method. In Python, a standard `datetime.datetime` object can be converted +// to this format using +// [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with +// the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use +// the Joda Time's [`ISODateTimeFormat.dateTime()`]( +// http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime() +// ) to obtain a formatter capable of generating timestamps in this format. +// +message Timestamp { + // Represents seconds of UTC time since Unix epoch + // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + // 9999-12-31T23:59:59Z inclusive. + int64 seconds = 1; + + // Non-negative fractions of a second at nanosecond resolution. Negative + // second values with fractions must still have non-negative nanos values + // that count forward in time. Must be from 0 to 999,999,999 + // inclusive. + int32 nanos = 2; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/protobuf/wrappers.proto b/node_modules/@google-cloud/firestore/build/protos/google/protobuf/wrappers.proto new file mode 100644 index 0000000..1959fa5 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/protobuf/wrappers.proto @@ -0,0 +1,123 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Wrappers for primitive (non-message) types. These types are useful +// for embedding primitives in the `google.protobuf.Any` type and for places +// where we need to distinguish between the absence of a primitive +// typed field and its default value. +// +// These wrappers have no meaningful use within repeated fields as they lack +// the ability to detect presence on individual elements. +// These wrappers have no meaningful use within a map or a oneof since +// individual entries of a map or fields of a oneof can already detect presence. + +syntax = "proto3"; + +package google.protobuf; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/protobuf/types/known/wrapperspb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "WrappersProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; + +// Wrapper message for `double`. +// +// The JSON representation for `DoubleValue` is JSON number. +message DoubleValue { + // The double value. + double value = 1; +} + +// Wrapper message for `float`. +// +// The JSON representation for `FloatValue` is JSON number. +message FloatValue { + // The float value. + float value = 1; +} + +// Wrapper message for `int64`. +// +// The JSON representation for `Int64Value` is JSON string. +message Int64Value { + // The int64 value. + int64 value = 1; +} + +// Wrapper message for `uint64`. +// +// The JSON representation for `UInt64Value` is JSON string. +message UInt64Value { + // The uint64 value. + uint64 value = 1; +} + +// Wrapper message for `int32`. +// +// The JSON representation for `Int32Value` is JSON number. +message Int32Value { + // The int32 value. + int32 value = 1; +} + +// Wrapper message for `uint32`. +// +// The JSON representation for `UInt32Value` is JSON number. +message UInt32Value { + // The uint32 value. + uint32 value = 1; +} + +// Wrapper message for `bool`. +// +// The JSON representation for `BoolValue` is JSON `true` and `false`. +message BoolValue { + // The bool value. + bool value = 1; +} + +// Wrapper message for `string`. +// +// The JSON representation for `StringValue` is JSON string. +message StringValue { + // The string value. + string value = 1; +} + +// Wrapper message for `bytes`. +// +// The JSON representation for `BytesValue` is JSON string. +message BytesValue { + // The bytes value. + bytes value = 1; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/rpc/status.proto b/node_modules/@google-cloud/firestore/build/protos/google/rpc/status.proto new file mode 100644 index 0000000..90b70dd --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/rpc/status.proto @@ -0,0 +1,49 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.rpc; + +import "google/protobuf/any.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/rpc/status;status"; +option java_multiple_files = true; +option java_outer_classname = "StatusProto"; +option java_package = "com.google.rpc"; +option objc_class_prefix = "RPC"; + +// The `Status` type defines a logical error model that is suitable for +// different programming environments, including REST APIs and RPC APIs. It is +// used by [gRPC](https://github.com/grpc). Each `Status` message contains +// three pieces of data: error code, error message, and error details. +// +// You can find out more about this error model and how to work with it in the +// [API Design Guide](https://cloud.google.com/apis/design/errors). +message Status { + // The status code, which should be an enum value of + // [google.rpc.Code][google.rpc.Code]. + int32 code = 1; + + // A developer-facing error message, which should be in English. Any + // user-facing error message should be localized and sent in the + // [google.rpc.Status.details][google.rpc.Status.details] field, or localized + // by the client. + string message = 2; + + // A list of messages that carry the error details. There is a common set of + // message types for APIs to use. + repeated google.protobuf.Any details = 3; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/type/dayofweek.proto b/node_modules/@google-cloud/firestore/build/protos/google/type/dayofweek.proto new file mode 100644 index 0000000..e16c194 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/type/dayofweek.proto @@ -0,0 +1,50 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/dayofweek;dayofweek"; +option java_multiple_files = true; +option java_outer_classname = "DayOfWeekProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents a day of the week. +enum DayOfWeek { + // The day of the week is unspecified. + DAY_OF_WEEK_UNSPECIFIED = 0; + + // Monday + MONDAY = 1; + + // Tuesday + TUESDAY = 2; + + // Wednesday + WEDNESDAY = 3; + + // Thursday + THURSDAY = 4; + + // Friday + FRIDAY = 5; + + // Saturday + SATURDAY = 6; + + // Sunday + SUNDAY = 7; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/google/type/latlng.proto b/node_modules/@google-cloud/firestore/build/protos/google/type/latlng.proto new file mode 100644 index 0000000..daeba48 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/google/type/latlng.proto @@ -0,0 +1,37 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.type; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/type/latlng;latlng"; +option java_multiple_files = true; +option java_outer_classname = "LatLngProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// An object that represents a latitude/longitude pair. This is expressed as a +// pair of doubles to represent degrees latitude and degrees longitude. Unless +// specified otherwise, this must conform to the +// WGS84 +// standard. Values must be within normalized ranges. +message LatLng { + // The latitude in degrees. It must be in the range [-90.0, +90.0]. + double latitude = 1; + + // The longitude in degrees. It must be in the range [-180.0, +180.0]. + double longitude = 2; +} diff --git a/node_modules/@google-cloud/firestore/build/protos/update.sh b/node_modules/@google-cloud/firestore/build/protos/update.sh new file mode 100644 index 0000000..028d8fd --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/update.sh @@ -0,0 +1,144 @@ +#!/bin/bash + +# Copyright 2018 Google Inc. +# +# 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. + +set -euo pipefail +IFS=$'\n\t' + +echo "Running update.sh" +echo $(npm --version) +# Variables +PROTOS_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +WORK_DIR=`mktemp -d` +cd ${PROTOS_DIR} + +# deletes the temp directory on exit +function cleanup { + rm -rf "$WORK_DIR" + echo "Deleted temp working directory $WORK_DIR" +} + +# register the cleanup function to be called on the EXIT signal +trap cleanup EXIT + +# Capture location of pbjs / pbts before we pushd. +PBJS="$(npm root)/.bin/pbjs" +PBTS="$(npm root)/.bin/pbts" + +# Enter work dir +pushd "$WORK_DIR" + +# Clone necessary git repos. +git clone --depth 1 https://github.com/googleapis/googleapis.git +# Protobuf may have breaking changes, so it will be pinned to a specific release. +# TODO(version) nodejs-firestore should maintain the version number of protobuf manually +git clone --single-branch --branch v26.1 --depth 1 https://github.com/google/protobuf.git + +# Copy necessary protos. +mkdir -p "${PROTOS_DIR}/google/api" +cp googleapis/google/api/{annotations,client,field_behavior,http,launch_stage,resource}.proto \ + "${PROTOS_DIR}/google/api/" + +mkdir -p "${PROTOS_DIR}/google/firestore/v1" +cp googleapis/google/firestore/v1/*.proto \ + "${PROTOS_DIR}/google/firestore/v1/" + +mkdir -p "${PROTOS_DIR}/google/firestore/v1beta1" +cp googleapis/google/firestore/v1beta1/*.proto \ + "${PROTOS_DIR}/google/firestore/v1beta1/" + +mkdir -p "${PROTOS_DIR}/google/firestore/admin/v1" +cp googleapis/google/firestore/admin/v1/*.proto \ + "${PROTOS_DIR}/google/firestore/admin/v1/" + +mkdir -p "${PROTOS_DIR}/google/longrunning" +cp googleapis/google/longrunning/operations.proto \ + "${PROTOS_DIR}/google/longrunning/" + +mkdir -p "${PROTOS_DIR}/google/rpc" +cp googleapis/google/rpc/status.proto \ + "${PROTOS_DIR}/google/rpc/" + +mkdir -p "${PROTOS_DIR}/google/type" +cp googleapis/google/type/{latlng,dayofweek}.proto \ + "${PROTOS_DIR}/google/type/" + +mkdir -p "${PROTOS_DIR}/google/protobuf" +cp protobuf/src/google/protobuf/{any,descriptor,empty,field_mask,struct,timestamp,wrappers,duration}.proto \ + "${PROTOS_DIR}/google/protobuf/" + +popd + +# Generate the Protobuf typings +PBJS_ARGS=( -p . \ + --js_out=import_style=commonjs,binary:library \ + --target=static-module \ + --no-create \ + --no-encode \ + --no-decode \ + --no-verify \ + --no-delimited \ + --force-enum-string) + +"${PBJS}" "${PBJS_ARGS[@]}" -o firestore_v1_proto_api.js \ + -r firestore_v1 \ + "google/firestore/v1/*.proto" \ + "firestore/*.proto" \ + "google/protobuf/*.proto" "google/type/*.proto" \ + "google/rpc/*.proto" "google/api/*.proto" \ + "google/longrunning/*.proto" +perl -pi -e 's/number\|Long/number\|string/g' firestore_v1_proto_api.js +"${PBTS}" -o firestore_v1_proto_api.d.ts firestore_v1_proto_api.js + +"${PBJS}" "${PBJS_ARGS[@]}" -o firestore_admin_v1_proto_api.js \ + -r firestore_admin_v1 \ + "google/firestore/admin/v1/*.proto" \ + "google/protobuf/*.proto" "google/type/*.proto" \ + "google/rpc/*.proto" "google/api/*.proto" \ + "google/longrunning/*.proto" +perl -pi -e 's/number\|Long/number\|string/g' firestore_admin_v1_proto_api.js +"${PBTS}" -o firestore_admin_v1_proto_api.d.ts firestore_admin_v1_proto_api.js + +"${PBJS}" "${PBJS_ARGS[@]}" -o firestore_v1beta1_proto_api.js \ + -r firestore_v1beta1 \ + "google/firestore/v1beta1/*.proto" \ + "google/protobuf/*.proto" "google/type/*.proto" \ + "google/rpc/*.proto" "google/api/*.proto" \ + "google/longrunning/*.proto" +perl -pi -e 's/number\|Long/number\|string/g' firestore_v1beta1_proto_api.js +"${PBTS}" -o firestore_v1beta1_proto_api.d.ts firestore_v1beta1_proto_api.js + +"${PBJS}" -p . --target=json -o v1.json \ + -r firestore_v1 \ + "google/firestore/v1/*.proto" \ + "google/protobuf/*.proto" "google/type/*.proto" \ + "google/rpc/*.proto" "google/api/*.proto" + +"${PBJS}" -p . --target=json -o admin_v1.json \ + -r firestore_admin_v1 \ + "google/firestore/admin/v1/*.proto" \ + "google/protobuf/*.proto" "google/type/*.proto" \ + "google/rpc/*.proto" "google/api/*.proto" \ + "google/longrunning/*.proto" + +"${PBJS}" -p . --target=json -o v1beta1.json \ + -r firestore_v1beta1 \ + "google/firestore/v1beta1/*.proto" \ + "google/protobuf/*.proto" "google/type/*.proto" \ + "google/rpc/*.proto" "google/api/*.proto" + +echo "Finished running update.sh" + +node ../../scripts/license.js ../../build ../protos diff --git a/node_modules/@google-cloud/firestore/build/protos/v1.json b/node_modules/@google-cloud/firestore/build/protos/v1.json new file mode 100644 index 0000000..3eb2bfc --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/v1.json @@ -0,0 +1 @@ +{"options":{"syntax":"proto3"},"nested":{"google":{"nested":{"firestore":{"nested":{"v1":{"options":{"csharp_namespace":"Google.Cloud.Firestore.V1","go_package":"cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb","java_multiple_files":true,"java_outer_classname":"WriteProto","java_package":"com.google.firestore.v1","objc_class_prefix":"GCFS","php_namespace":"Google\\Cloud\\Firestore\\V1","ruby_package":"Google::Cloud::Firestore::V1"},"nested":{"AggregationResult":{"fields":{"aggregateFields":{"keyType":"string","type":"Value","id":2}}},"Document":{"fields":{"name":{"type":"string","id":1},"fields":{"keyType":"string","type":"Value","id":2},"createTime":{"type":"google.protobuf.Timestamp","id":3},"updateTime":{"type":"google.protobuf.Timestamp","id":4}}},"Value":{"oneofs":{"valueType":{"oneof":["nullValue","booleanValue","integerValue","doubleValue","timestampValue","stringValue","bytesValue","referenceValue","geoPointValue","arrayValue","mapValue"]}},"fields":{"nullValue":{"type":"google.protobuf.NullValue","id":11},"booleanValue":{"type":"bool","id":1},"integerValue":{"type":"int64","id":2},"doubleValue":{"type":"double","id":3},"timestampValue":{"type":"google.protobuf.Timestamp","id":10},"stringValue":{"type":"string","id":17},"bytesValue":{"type":"bytes","id":18},"referenceValue":{"type":"string","id":5},"geoPointValue":{"type":"google.type.LatLng","id":8},"arrayValue":{"type":"ArrayValue","id":9},"mapValue":{"type":"MapValue","id":6}}},"ArrayValue":{"fields":{"values":{"rule":"repeated","type":"Value","id":1}}},"MapValue":{"fields":{"fields":{"keyType":"string","type":"Value","id":1}}},"BitSequence":{"fields":{"bitmap":{"type":"bytes","id":1},"padding":{"type":"int32","id":2}}},"BloomFilter":{"fields":{"bits":{"type":"BitSequence","id":1},"hashCount":{"type":"int32","id":2}}},"DocumentMask":{"fields":{"fieldPaths":{"rule":"repeated","type":"string","id":1}}},"Precondition":{"oneofs":{"conditionType":{"oneof":["exists","updateTime"]}},"fields":{"exists":{"type":"bool","id":1},"updateTime":{"type":"google.protobuf.Timestamp","id":2}}},"TransactionOptions":{"oneofs":{"mode":{"oneof":["readOnly","readWrite"]}},"fields":{"readOnly":{"type":"ReadOnly","id":2},"readWrite":{"type":"ReadWrite","id":3}},"nested":{"ReadWrite":{"fields":{"retryTransaction":{"type":"bytes","id":1}}},"ReadOnly":{"oneofs":{"consistencySelector":{"oneof":["readTime"]}},"fields":{"readTime":{"type":"google.protobuf.Timestamp","id":2}}}}},"Firestore":{"options":{"(google.api.default_host)":"firestore.googleapis.com","(google.api.oauth_scopes)":"https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/datastore"},"methods":{"GetDocument":{"requestType":"GetDocumentRequest","responseType":"Document","options":{"(google.api.http).get":"/v1/{name=projects/*/databases/*/documents/*/**}"},"parsedOptions":[{"(google.api.http)":{"get":"/v1/{name=projects/*/databases/*/documents/*/**}"}}]},"ListDocuments":{"requestType":"ListDocumentsRequest","responseType":"ListDocumentsResponse","options":{"(google.api.http).get":"/v1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}","(google.api.http).additional_bindings.get":"/v1/{parent=projects/*/databases/*/documents}/{collection_id}"},"parsedOptions":[{"(google.api.http)":{"get":"/v1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}","additional_bindings":{"get":"/v1/{parent=projects/*/databases/*/documents}/{collection_id}"}}}]},"UpdateDocument":{"requestType":"UpdateDocumentRequest","responseType":"Document","options":{"(google.api.http).patch":"/v1/{document.name=projects/*/databases/*/documents/*/**}","(google.api.http).body":"document","(google.api.method_signature)":"document,update_mask"},"parsedOptions":[{"(google.api.http)":{"patch":"/v1/{document.name=projects/*/databases/*/documents/*/**}","body":"document"}},{"(google.api.method_signature)":"document,update_mask"}]},"DeleteDocument":{"requestType":"DeleteDocumentRequest","responseType":"google.protobuf.Empty","options":{"(google.api.http).delete":"/v1/{name=projects/*/databases/*/documents/*/**}","(google.api.method_signature)":"name"},"parsedOptions":[{"(google.api.http)":{"delete":"/v1/{name=projects/*/databases/*/documents/*/**}"}},{"(google.api.method_signature)":"name"}]},"BatchGetDocuments":{"requestType":"BatchGetDocumentsRequest","responseType":"BatchGetDocumentsResponse","responseStream":true,"options":{"(google.api.http).post":"/v1/{database=projects/*/databases/*}/documents:batchGet","(google.api.http).body":"*"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{database=projects/*/databases/*}/documents:batchGet","body":"*"}}]},"BeginTransaction":{"requestType":"BeginTransactionRequest","responseType":"BeginTransactionResponse","options":{"(google.api.http).post":"/v1/{database=projects/*/databases/*}/documents:beginTransaction","(google.api.http).body":"*","(google.api.method_signature)":"database"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{database=projects/*/databases/*}/documents:beginTransaction","body":"*"}},{"(google.api.method_signature)":"database"}]},"Commit":{"requestType":"CommitRequest","responseType":"CommitResponse","options":{"(google.api.http).post":"/v1/{database=projects/*/databases/*}/documents:commit","(google.api.http).body":"*","(google.api.method_signature)":"database,writes"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{database=projects/*/databases/*}/documents:commit","body":"*"}},{"(google.api.method_signature)":"database,writes"}]},"Rollback":{"requestType":"RollbackRequest","responseType":"google.protobuf.Empty","options":{"(google.api.http).post":"/v1/{database=projects/*/databases/*}/documents:rollback","(google.api.http).body":"*","(google.api.method_signature)":"database,transaction"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{database=projects/*/databases/*}/documents:rollback","body":"*"}},{"(google.api.method_signature)":"database,transaction"}]},"RunQuery":{"requestType":"RunQueryRequest","responseType":"RunQueryResponse","responseStream":true,"options":{"(google.api.http).post":"/v1/{parent=projects/*/databases/*/documents}:runQuery","(google.api.http).body":"*","(google.api.http).additional_bindings.post":"/v1/{parent=projects/*/databases/*/documents/*/**}:runQuery","(google.api.http).additional_bindings.body":"*"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{parent=projects/*/databases/*/documents}:runQuery","body":"*","additional_bindings":{"post":"/v1/{parent=projects/*/databases/*/documents/*/**}:runQuery","body":"*"}}}]},"RunAggregationQuery":{"requestType":"RunAggregationQueryRequest","responseType":"RunAggregationQueryResponse","responseStream":true,"options":{"(google.api.http).post":"/v1/{parent=projects/*/databases/*/documents}:runAggregationQuery","(google.api.http).body":"*","(google.api.http).additional_bindings.post":"/v1/{parent=projects/*/databases/*/documents/*/**}:runAggregationQuery","(google.api.http).additional_bindings.body":"*"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{parent=projects/*/databases/*/documents}:runAggregationQuery","body":"*","additional_bindings":{"post":"/v1/{parent=projects/*/databases/*/documents/*/**}:runAggregationQuery","body":"*"}}}]},"PartitionQuery":{"requestType":"PartitionQueryRequest","responseType":"PartitionQueryResponse","options":{"(google.api.http).post":"/v1/{parent=projects/*/databases/*/documents}:partitionQuery","(google.api.http).body":"*","(google.api.http).additional_bindings.post":"/v1/{parent=projects/*/databases/*/documents/*/**}:partitionQuery","(google.api.http).additional_bindings.body":"*"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{parent=projects/*/databases/*/documents}:partitionQuery","body":"*","additional_bindings":{"post":"/v1/{parent=projects/*/databases/*/documents/*/**}:partitionQuery","body":"*"}}}]},"Write":{"requestType":"WriteRequest","requestStream":true,"responseType":"WriteResponse","responseStream":true,"options":{"(google.api.http).post":"/v1/{database=projects/*/databases/*}/documents:write","(google.api.http).body":"*"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{database=projects/*/databases/*}/documents:write","body":"*"}}]},"Listen":{"requestType":"ListenRequest","requestStream":true,"responseType":"ListenResponse","responseStream":true,"options":{"(google.api.http).post":"/v1/{database=projects/*/databases/*}/documents:listen","(google.api.http).body":"*"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{database=projects/*/databases/*}/documents:listen","body":"*"}}]},"ListCollectionIds":{"requestType":"ListCollectionIdsRequest","responseType":"ListCollectionIdsResponse","options":{"(google.api.http).post":"/v1/{parent=projects/*/databases/*/documents}:listCollectionIds","(google.api.http).body":"*","(google.api.http).additional_bindings.post":"/v1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds","(google.api.http).additional_bindings.body":"*","(google.api.method_signature)":"parent"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{parent=projects/*/databases/*/documents}:listCollectionIds","body":"*","additional_bindings":{"post":"/v1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds","body":"*"}}},{"(google.api.method_signature)":"parent"}]},"BatchWrite":{"requestType":"BatchWriteRequest","responseType":"BatchWriteResponse","options":{"(google.api.http).post":"/v1/{database=projects/*/databases/*}/documents:batchWrite","(google.api.http).body":"*"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{database=projects/*/databases/*}/documents:batchWrite","body":"*"}}]},"CreateDocument":{"requestType":"CreateDocumentRequest","responseType":"Document","options":{"(google.api.http).post":"/v1/{parent=projects/*/databases/*/documents/**}/{collection_id}","(google.api.http).body":"document"},"parsedOptions":[{"(google.api.http)":{"post":"/v1/{parent=projects/*/databases/*/documents/**}/{collection_id}","body":"document"}}]}}},"GetDocumentRequest":{"oneofs":{"consistencySelector":{"oneof":["transaction","readTime"]}},"fields":{"name":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"mask":{"type":"DocumentMask","id":2},"transaction":{"type":"bytes","id":3},"readTime":{"type":"google.protobuf.Timestamp","id":5}}},"ListDocumentsRequest":{"oneofs":{"consistencySelector":{"oneof":["transaction","readTime"]}},"fields":{"parent":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"collectionId":{"type":"string","id":2,"options":{"(google.api.field_behavior)":"OPTIONAL"}},"pageSize":{"type":"int32","id":3,"options":{"(google.api.field_behavior)":"OPTIONAL"}},"pageToken":{"type":"string","id":4,"options":{"(google.api.field_behavior)":"OPTIONAL"}},"orderBy":{"type":"string","id":6,"options":{"(google.api.field_behavior)":"OPTIONAL"}},"mask":{"type":"DocumentMask","id":7,"options":{"(google.api.field_behavior)":"OPTIONAL"}},"transaction":{"type":"bytes","id":8},"readTime":{"type":"google.protobuf.Timestamp","id":10},"showMissing":{"type":"bool","id":12}}},"ListDocumentsResponse":{"fields":{"documents":{"rule":"repeated","type":"Document","id":1},"nextPageToken":{"type":"string","id":2}}},"CreateDocumentRequest":{"fields":{"parent":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"collectionId":{"type":"string","id":2,"options":{"(google.api.field_behavior)":"REQUIRED"}},"documentId":{"type":"string","id":3},"document":{"type":"Document","id":4,"options":{"(google.api.field_behavior)":"REQUIRED"}},"mask":{"type":"DocumentMask","id":5}}},"UpdateDocumentRequest":{"fields":{"document":{"type":"Document","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"updateMask":{"type":"DocumentMask","id":2},"mask":{"type":"DocumentMask","id":3},"currentDocument":{"type":"Precondition","id":4}}},"DeleteDocumentRequest":{"fields":{"name":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"currentDocument":{"type":"Precondition","id":2}}},"BatchGetDocumentsRequest":{"oneofs":{"consistencySelector":{"oneof":["transaction","newTransaction","readTime"]}},"fields":{"database":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"documents":{"rule":"repeated","type":"string","id":2},"mask":{"type":"DocumentMask","id":3},"transaction":{"type":"bytes","id":4},"newTransaction":{"type":"TransactionOptions","id":5},"readTime":{"type":"google.protobuf.Timestamp","id":7}}},"BatchGetDocumentsResponse":{"oneofs":{"result":{"oneof":["found","missing"]}},"fields":{"found":{"type":"Document","id":1},"missing":{"type":"string","id":2},"transaction":{"type":"bytes","id":3},"readTime":{"type":"google.protobuf.Timestamp","id":4}}},"BeginTransactionRequest":{"fields":{"database":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"options":{"type":"TransactionOptions","id":2}}},"BeginTransactionResponse":{"fields":{"transaction":{"type":"bytes","id":1}}},"CommitRequest":{"fields":{"database":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"writes":{"rule":"repeated","type":"Write","id":2},"transaction":{"type":"bytes","id":3}}},"CommitResponse":{"fields":{"writeResults":{"rule":"repeated","type":"WriteResult","id":1},"commitTime":{"type":"google.protobuf.Timestamp","id":2}}},"RollbackRequest":{"fields":{"database":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"transaction":{"type":"bytes","id":2,"options":{"(google.api.field_behavior)":"REQUIRED"}}}},"RunQueryRequest":{"oneofs":{"queryType":{"oneof":["structuredQuery"]},"consistencySelector":{"oneof":["transaction","newTransaction","readTime"]}},"fields":{"parent":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"structuredQuery":{"type":"StructuredQuery","id":2},"transaction":{"type":"bytes","id":5},"newTransaction":{"type":"TransactionOptions","id":6},"readTime":{"type":"google.protobuf.Timestamp","id":7},"explainOptions":{"type":"ExplainOptions","id":10,"options":{"(google.api.field_behavior)":"OPTIONAL"}}}},"RunQueryResponse":{"oneofs":{"continuationSelector":{"oneof":["done"]}},"fields":{"transaction":{"type":"bytes","id":2},"document":{"type":"Document","id":1},"readTime":{"type":"google.protobuf.Timestamp","id":3},"skippedResults":{"type":"int32","id":4},"done":{"type":"bool","id":6},"explainMetrics":{"type":"ExplainMetrics","id":11}}},"RunAggregationQueryRequest":{"oneofs":{"queryType":{"oneof":["structuredAggregationQuery"]},"consistencySelector":{"oneof":["transaction","newTransaction","readTime"]}},"fields":{"parent":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"structuredAggregationQuery":{"type":"StructuredAggregationQuery","id":2},"transaction":{"type":"bytes","id":4},"newTransaction":{"type":"TransactionOptions","id":5},"readTime":{"type":"google.protobuf.Timestamp","id":6},"explainOptions":{"type":"ExplainOptions","id":8,"options":{"(google.api.field_behavior)":"OPTIONAL"}}}},"RunAggregationQueryResponse":{"fields":{"result":{"type":"AggregationResult","id":1},"transaction":{"type":"bytes","id":2},"readTime":{"type":"google.protobuf.Timestamp","id":3},"explainMetrics":{"type":"ExplainMetrics","id":10}}},"PartitionQueryRequest":{"oneofs":{"queryType":{"oneof":["structuredQuery"]},"consistencySelector":{"oneof":["readTime"]}},"fields":{"parent":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"structuredQuery":{"type":"StructuredQuery","id":2},"partitionCount":{"type":"int64","id":3},"pageToken":{"type":"string","id":4},"pageSize":{"type":"int32","id":5},"readTime":{"type":"google.protobuf.Timestamp","id":6}}},"PartitionQueryResponse":{"fields":{"partitions":{"rule":"repeated","type":"Cursor","id":1},"nextPageToken":{"type":"string","id":2}}},"WriteRequest":{"fields":{"database":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"streamId":{"type":"string","id":2},"writes":{"rule":"repeated","type":"Write","id":3},"streamToken":{"type":"bytes","id":4},"labels":{"keyType":"string","type":"string","id":5}}},"WriteResponse":{"fields":{"streamId":{"type":"string","id":1},"streamToken":{"type":"bytes","id":2},"writeResults":{"rule":"repeated","type":"WriteResult","id":3},"commitTime":{"type":"google.protobuf.Timestamp","id":4}}},"ListenRequest":{"oneofs":{"targetChange":{"oneof":["addTarget","removeTarget"]}},"fields":{"database":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"addTarget":{"type":"Target","id":2},"removeTarget":{"type":"int32","id":3},"labels":{"keyType":"string","type":"string","id":4}}},"ListenResponse":{"oneofs":{"responseType":{"oneof":["targetChange","documentChange","documentDelete","documentRemove","filter"]}},"fields":{"targetChange":{"type":"TargetChange","id":2},"documentChange":{"type":"DocumentChange","id":3},"documentDelete":{"type":"DocumentDelete","id":4},"documentRemove":{"type":"DocumentRemove","id":6},"filter":{"type":"ExistenceFilter","id":5}}},"Target":{"oneofs":{"targetType":{"oneof":["query","documents"]},"resumeType":{"oneof":["resumeToken","readTime"]}},"fields":{"query":{"type":"QueryTarget","id":2},"documents":{"type":"DocumentsTarget","id":3},"resumeToken":{"type":"bytes","id":4},"readTime":{"type":"google.protobuf.Timestamp","id":11},"targetId":{"type":"int32","id":5},"once":{"type":"bool","id":6},"expectedCount":{"type":"google.protobuf.Int32Value","id":12}},"nested":{"DocumentsTarget":{"fields":{"documents":{"rule":"repeated","type":"string","id":2}}},"QueryTarget":{"oneofs":{"queryType":{"oneof":["structuredQuery"]}},"fields":{"parent":{"type":"string","id":1},"structuredQuery":{"type":"StructuredQuery","id":2}}}}},"TargetChange":{"fields":{"targetChangeType":{"type":"TargetChangeType","id":1},"targetIds":{"rule":"repeated","type":"int32","id":2},"cause":{"type":"google.rpc.Status","id":3},"resumeToken":{"type":"bytes","id":4},"readTime":{"type":"google.protobuf.Timestamp","id":6}},"nested":{"TargetChangeType":{"values":{"NO_CHANGE":0,"ADD":1,"REMOVE":2,"CURRENT":3,"RESET":4}}}},"ListCollectionIdsRequest":{"oneofs":{"consistencySelector":{"oneof":["readTime"]}},"fields":{"parent":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"pageSize":{"type":"int32","id":2},"pageToken":{"type":"string","id":3},"readTime":{"type":"google.protobuf.Timestamp","id":4}}},"ListCollectionIdsResponse":{"fields":{"collectionIds":{"rule":"repeated","type":"string","id":1},"nextPageToken":{"type":"string","id":2}}},"BatchWriteRequest":{"fields":{"database":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"writes":{"rule":"repeated","type":"Write","id":2},"labels":{"keyType":"string","type":"string","id":3}}},"BatchWriteResponse":{"fields":{"writeResults":{"rule":"repeated","type":"WriteResult","id":1},"status":{"rule":"repeated","type":"google.rpc.Status","id":2}}},"StructuredQuery":{"fields":{"select":{"type":"Projection","id":1},"from":{"rule":"repeated","type":"CollectionSelector","id":2},"where":{"type":"Filter","id":3},"orderBy":{"rule":"repeated","type":"Order","id":4},"startAt":{"type":"Cursor","id":7},"endAt":{"type":"Cursor","id":8},"offset":{"type":"int32","id":6},"limit":{"type":"google.protobuf.Int32Value","id":5},"findNearest":{"type":"FindNearest","id":9,"options":{"(google.api.field_behavior)":"OPTIONAL"}}},"nested":{"CollectionSelector":{"fields":{"collectionId":{"type":"string","id":2},"allDescendants":{"type":"bool","id":3}}},"Filter":{"oneofs":{"filterType":{"oneof":["compositeFilter","fieldFilter","unaryFilter"]}},"fields":{"compositeFilter":{"type":"CompositeFilter","id":1},"fieldFilter":{"type":"FieldFilter","id":2},"unaryFilter":{"type":"UnaryFilter","id":3}}},"CompositeFilter":{"fields":{"op":{"type":"Operator","id":1},"filters":{"rule":"repeated","type":"Filter","id":2}},"nested":{"Operator":{"values":{"OPERATOR_UNSPECIFIED":0,"AND":1,"OR":2}}}},"FieldFilter":{"fields":{"field":{"type":"FieldReference","id":1},"op":{"type":"Operator","id":2},"value":{"type":"Value","id":3}},"nested":{"Operator":{"values":{"OPERATOR_UNSPECIFIED":0,"LESS_THAN":1,"LESS_THAN_OR_EQUAL":2,"GREATER_THAN":3,"GREATER_THAN_OR_EQUAL":4,"EQUAL":5,"NOT_EQUAL":6,"ARRAY_CONTAINS":7,"IN":8,"ARRAY_CONTAINS_ANY":9,"NOT_IN":10}}}},"UnaryFilter":{"oneofs":{"operandType":{"oneof":["field"]}},"fields":{"op":{"type":"Operator","id":1},"field":{"type":"FieldReference","id":2}},"nested":{"Operator":{"values":{"OPERATOR_UNSPECIFIED":0,"IS_NAN":2,"IS_NULL":3,"IS_NOT_NAN":4,"IS_NOT_NULL":5}}}},"Order":{"fields":{"field":{"type":"FieldReference","id":1},"direction":{"type":"Direction","id":2}}},"Direction":{"values":{"DIRECTION_UNSPECIFIED":0,"ASCENDING":1,"DESCENDING":2}},"FieldReference":{"fields":{"fieldPath":{"type":"string","id":2}}},"Projection":{"fields":{"fields":{"rule":"repeated","type":"FieldReference","id":2}}},"FindNearest":{"fields":{"vectorField":{"type":"FieldReference","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"queryVector":{"type":"Value","id":2,"options":{"(google.api.field_behavior)":"REQUIRED"}},"distanceMeasure":{"type":"DistanceMeasure","id":3,"options":{"(google.api.field_behavior)":"REQUIRED"}},"limit":{"type":"google.protobuf.Int32Value","id":4,"options":{"(google.api.field_behavior)":"REQUIRED"}},"distanceResultField":{"type":"string","id":5,"options":{"(google.api.field_behavior)":"OPTIONAL"}},"distanceThreshold":{"type":"google.protobuf.DoubleValue","id":6,"options":{"(google.api.field_behavior)":"OPTIONAL"}}},"nested":{"DistanceMeasure":{"values":{"DISTANCE_MEASURE_UNSPECIFIED":0,"EUCLIDEAN":1,"COSINE":2,"DOT_PRODUCT":3}}}}}},"StructuredAggregationQuery":{"oneofs":{"queryType":{"oneof":["structuredQuery"]}},"fields":{"structuredQuery":{"type":"StructuredQuery","id":1},"aggregations":{"rule":"repeated","type":"Aggregation","id":3,"options":{"(google.api.field_behavior)":"OPTIONAL"}}},"nested":{"Aggregation":{"oneofs":{"operator":{"oneof":["count","sum","avg"]}},"fields":{"count":{"type":"Count","id":1},"sum":{"type":"Sum","id":2},"avg":{"type":"Avg","id":3},"alias":{"type":"string","id":7,"options":{"(google.api.field_behavior)":"OPTIONAL"}}},"nested":{"Count":{"fields":{"upTo":{"type":"google.protobuf.Int64Value","id":1,"options":{"(google.api.field_behavior)":"OPTIONAL"}}}},"Sum":{"fields":{"field":{"type":"StructuredQuery.FieldReference","id":1}}},"Avg":{"fields":{"field":{"type":"StructuredQuery.FieldReference","id":1}}}}}}},"Cursor":{"fields":{"values":{"rule":"repeated","type":"Value","id":1},"before":{"type":"bool","id":2}}},"ExplainOptions":{"fields":{"analyze":{"type":"bool","id":1,"options":{"(google.api.field_behavior)":"OPTIONAL"}}}},"ExplainMetrics":{"fields":{"planSummary":{"type":"PlanSummary","id":1},"executionStats":{"type":"ExecutionStats","id":2}}},"PlanSummary":{"fields":{"indexesUsed":{"rule":"repeated","type":"google.protobuf.Struct","id":1}}},"ExecutionStats":{"fields":{"resultsReturned":{"type":"int64","id":1},"executionDuration":{"type":"google.protobuf.Duration","id":3},"readOperations":{"type":"int64","id":4},"debugStats":{"type":"google.protobuf.Struct","id":5}}},"Write":{"oneofs":{"operation":{"oneof":["update","delete","transform"]}},"fields":{"update":{"type":"Document","id":1},"delete":{"type":"string","id":2},"transform":{"type":"DocumentTransform","id":6},"updateMask":{"type":"DocumentMask","id":3},"updateTransforms":{"rule":"repeated","type":"DocumentTransform.FieldTransform","id":7},"currentDocument":{"type":"Precondition","id":4}}},"DocumentTransform":{"fields":{"document":{"type":"string","id":1},"fieldTransforms":{"rule":"repeated","type":"FieldTransform","id":2}},"nested":{"FieldTransform":{"oneofs":{"transformType":{"oneof":["setToServerValue","increment","maximum","minimum","appendMissingElements","removeAllFromArray"]}},"fields":{"fieldPath":{"type":"string","id":1},"setToServerValue":{"type":"ServerValue","id":2},"increment":{"type":"Value","id":3},"maximum":{"type":"Value","id":4},"minimum":{"type":"Value","id":5},"appendMissingElements":{"type":"ArrayValue","id":6},"removeAllFromArray":{"type":"ArrayValue","id":7}},"nested":{"ServerValue":{"values":{"SERVER_VALUE_UNSPECIFIED":0,"REQUEST_TIME":1}}}}}},"WriteResult":{"fields":{"updateTime":{"type":"google.protobuf.Timestamp","id":1},"transformResults":{"rule":"repeated","type":"Value","id":2}}},"DocumentChange":{"fields":{"document":{"type":"Document","id":1},"targetIds":{"rule":"repeated","type":"int32","id":5},"removedTargetIds":{"rule":"repeated","type":"int32","id":6}}},"DocumentDelete":{"fields":{"document":{"type":"string","id":1},"removedTargetIds":{"rule":"repeated","type":"int32","id":6},"readTime":{"type":"google.protobuf.Timestamp","id":4}}},"DocumentRemove":{"fields":{"document":{"type":"string","id":1},"removedTargetIds":{"rule":"repeated","type":"int32","id":2},"readTime":{"type":"google.protobuf.Timestamp","id":4}}},"ExistenceFilter":{"fields":{"targetId":{"type":"int32","id":1},"count":{"type":"int32","id":2},"unchangedNames":{"type":"BloomFilter","id":3}}}}}}},"api":{"options":{"go_package":"google.golang.org/genproto/googleapis/api/annotations;annotations","java_multiple_files":true,"java_outer_classname":"ResourceProto","java_package":"com.google.api","objc_class_prefix":"GAPI","cc_enable_arenas":true},"nested":{"fieldBehavior":{"rule":"repeated","type":"google.api.FieldBehavior","id":1052,"extend":"google.protobuf.FieldOptions","options":{"packed":false}},"FieldBehavior":{"values":{"FIELD_BEHAVIOR_UNSPECIFIED":0,"OPTIONAL":1,"REQUIRED":2,"OUTPUT_ONLY":3,"INPUT_ONLY":4,"IMMUTABLE":5,"UNORDERED_LIST":6,"NON_EMPTY_DEFAULT":7,"IDENTIFIER":8}},"http":{"type":"HttpRule","id":72295728,"extend":"google.protobuf.MethodOptions"},"Http":{"fields":{"rules":{"rule":"repeated","type":"HttpRule","id":1},"fullyDecodeReservedExpansion":{"type":"bool","id":2}}},"HttpRule":{"oneofs":{"pattern":{"oneof":["get","put","post","delete","patch","custom"]}},"fields":{"selector":{"type":"string","id":1},"get":{"type":"string","id":2},"put":{"type":"string","id":3},"post":{"type":"string","id":4},"delete":{"type":"string","id":5},"patch":{"type":"string","id":6},"custom":{"type":"CustomHttpPattern","id":8},"body":{"type":"string","id":7},"responseBody":{"type":"string","id":12},"additionalBindings":{"rule":"repeated","type":"HttpRule","id":11}}},"CustomHttpPattern":{"fields":{"kind":{"type":"string","id":1},"path":{"type":"string","id":2}}},"methodSignature":{"rule":"repeated","type":"string","id":1051,"extend":"google.protobuf.MethodOptions"},"defaultHost":{"type":"string","id":1049,"extend":"google.protobuf.ServiceOptions"},"oauthScopes":{"type":"string","id":1050,"extend":"google.protobuf.ServiceOptions"},"apiVersion":{"type":"string","id":525000001,"extend":"google.protobuf.ServiceOptions"},"CommonLanguageSettings":{"fields":{"referenceDocsUri":{"type":"string","id":1,"options":{"deprecated":true}},"destinations":{"rule":"repeated","type":"ClientLibraryDestination","id":2},"selectiveGapicGeneration":{"type":"SelectiveGapicGeneration","id":3}}},"ClientLibrarySettings":{"fields":{"version":{"type":"string","id":1},"launchStage":{"type":"LaunchStage","id":2},"restNumericEnums":{"type":"bool","id":3},"javaSettings":{"type":"JavaSettings","id":21},"cppSettings":{"type":"CppSettings","id":22},"phpSettings":{"type":"PhpSettings","id":23},"pythonSettings":{"type":"PythonSettings","id":24},"nodeSettings":{"type":"NodeSettings","id":25},"dotnetSettings":{"type":"DotnetSettings","id":26},"rubySettings":{"type":"RubySettings","id":27},"goSettings":{"type":"GoSettings","id":28}}},"Publishing":{"fields":{"methodSettings":{"rule":"repeated","type":"MethodSettings","id":2},"newIssueUri":{"type":"string","id":101},"documentationUri":{"type":"string","id":102},"apiShortName":{"type":"string","id":103},"githubLabel":{"type":"string","id":104},"codeownerGithubTeams":{"rule":"repeated","type":"string","id":105},"docTagPrefix":{"type":"string","id":106},"organization":{"type":"ClientLibraryOrganization","id":107},"librarySettings":{"rule":"repeated","type":"ClientLibrarySettings","id":109},"protoReferenceDocumentationUri":{"type":"string","id":110},"restReferenceDocumentationUri":{"type":"string","id":111}}},"JavaSettings":{"fields":{"libraryPackage":{"type":"string","id":1},"serviceClassNames":{"keyType":"string","type":"string","id":2},"common":{"type":"CommonLanguageSettings","id":3}}},"CppSettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1}}},"PhpSettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1}}},"PythonSettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1},"experimentalFeatures":{"type":"ExperimentalFeatures","id":2}},"nested":{"ExperimentalFeatures":{"fields":{"restAsyncIoEnabled":{"type":"bool","id":1},"protobufPythonicTypesEnabled":{"type":"bool","id":2}}}}},"NodeSettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1}}},"DotnetSettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1},"renamedServices":{"keyType":"string","type":"string","id":2},"renamedResources":{"keyType":"string","type":"string","id":3},"ignoredResources":{"rule":"repeated","type":"string","id":4},"forcedNamespaceAliases":{"rule":"repeated","type":"string","id":5},"handwrittenSignatures":{"rule":"repeated","type":"string","id":6}}},"RubySettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1}}},"GoSettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1},"renamedServices":{"keyType":"string","type":"string","id":2}}},"MethodSettings":{"fields":{"selector":{"type":"string","id":1},"longRunning":{"type":"LongRunning","id":2},"autoPopulatedFields":{"rule":"repeated","type":"string","id":3}},"nested":{"LongRunning":{"fields":{"initialPollDelay":{"type":"google.protobuf.Duration","id":1},"pollDelayMultiplier":{"type":"float","id":2},"maxPollDelay":{"type":"google.protobuf.Duration","id":3},"totalPollTimeout":{"type":"google.protobuf.Duration","id":4}}}}},"ClientLibraryOrganization":{"values":{"CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED":0,"CLOUD":1,"ADS":2,"PHOTOS":3,"STREET_VIEW":4,"SHOPPING":5,"GEO":6,"GENERATIVE_AI":7}},"ClientLibraryDestination":{"values":{"CLIENT_LIBRARY_DESTINATION_UNSPECIFIED":0,"GITHUB":10,"PACKAGE_MANAGER":20}},"SelectiveGapicGeneration":{"fields":{"methods":{"rule":"repeated","type":"string","id":1},"generateOmittedAsInternal":{"type":"bool","id":2}}},"LaunchStage":{"values":{"LAUNCH_STAGE_UNSPECIFIED":0,"UNIMPLEMENTED":6,"PRELAUNCH":7,"EARLY_ACCESS":1,"ALPHA":2,"BETA":3,"GA":4,"DEPRECATED":5}},"resourceReference":{"type":"google.api.ResourceReference","id":1055,"extend":"google.protobuf.FieldOptions"},"resourceDefinition":{"rule":"repeated","type":"google.api.ResourceDescriptor","id":1053,"extend":"google.protobuf.FileOptions"},"resource":{"type":"google.api.ResourceDescriptor","id":1053,"extend":"google.protobuf.MessageOptions"},"ResourceDescriptor":{"fields":{"type":{"type":"string","id":1},"pattern":{"rule":"repeated","type":"string","id":2},"nameField":{"type":"string","id":3},"history":{"type":"History","id":4},"plural":{"type":"string","id":5},"singular":{"type":"string","id":6},"style":{"rule":"repeated","type":"Style","id":10}},"nested":{"History":{"values":{"HISTORY_UNSPECIFIED":0,"ORIGINALLY_SINGLE_PATTERN":1,"FUTURE_MULTI_PATTERN":2}},"Style":{"values":{"STYLE_UNSPECIFIED":0,"DECLARATIVE_FRIENDLY":1}}}},"ResourceReference":{"fields":{"type":{"type":"string","id":1},"childType":{"type":"string","id":2}}}}},"protobuf":{"options":{"go_package":"google.golang.org/protobuf/types/descriptorpb","java_package":"com.google.protobuf","java_outer_classname":"DescriptorProtos","csharp_namespace":"Google.Protobuf.Reflection","objc_class_prefix":"GPB","cc_enable_arenas":true,"optimize_for":"SPEED"},"nested":{"FileDescriptorSet":{"fields":{"file":{"rule":"repeated","type":"FileDescriptorProto","id":1}}},"Edition":{"values":{"EDITION_UNKNOWN":0,"EDITION_PROTO2":998,"EDITION_PROTO3":999,"EDITION_2023":1e3,"EDITION_2024":1001,"EDITION_1_TEST_ONLY":1,"EDITION_2_TEST_ONLY":2,"EDITION_99997_TEST_ONLY":99997,"EDITION_99998_TEST_ONLY":99998,"EDITION_99999_TEST_ONLY":99999,"EDITION_MAX":2147483647}},"FileDescriptorProto":{"fields":{"name":{"type":"string","id":1},"package":{"type":"string","id":2},"dependency":{"rule":"repeated","type":"string","id":3},"publicDependency":{"rule":"repeated","type":"int32","id":10,"options":{"packed":false}},"weakDependency":{"rule":"repeated","type":"int32","id":11,"options":{"packed":false}},"messageType":{"rule":"repeated","type":"DescriptorProto","id":4},"enumType":{"rule":"repeated","type":"EnumDescriptorProto","id":5},"service":{"rule":"repeated","type":"ServiceDescriptorProto","id":6},"extension":{"rule":"repeated","type":"FieldDescriptorProto","id":7},"options":{"type":"FileOptions","id":8},"sourceCodeInfo":{"type":"SourceCodeInfo","id":9},"syntax":{"type":"string","id":12},"edition":{"type":"Edition","id":14}}},"DescriptorProto":{"fields":{"name":{"type":"string","id":1},"field":{"rule":"repeated","type":"FieldDescriptorProto","id":2},"extension":{"rule":"repeated","type":"FieldDescriptorProto","id":6},"nestedType":{"rule":"repeated","type":"DescriptorProto","id":3},"enumType":{"rule":"repeated","type":"EnumDescriptorProto","id":4},"extensionRange":{"rule":"repeated","type":"ExtensionRange","id":5},"oneofDecl":{"rule":"repeated","type":"OneofDescriptorProto","id":8},"options":{"type":"MessageOptions","id":7},"reservedRange":{"rule":"repeated","type":"ReservedRange","id":9},"reservedName":{"rule":"repeated","type":"string","id":10}},"nested":{"ExtensionRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2},"options":{"type":"ExtensionRangeOptions","id":3}}},"ReservedRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2}}}}},"ExtensionRangeOptions":{"fields":{"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999},"declaration":{"rule":"repeated","type":"Declaration","id":2,"options":{"retention":"RETENTION_SOURCE"}},"features":{"type":"FeatureSet","id":50},"verification":{"type":"VerificationState","id":3,"options":{"default":"UNVERIFIED","retention":"RETENTION_SOURCE"}}},"extensions":[[1e3,536870911]],"nested":{"Declaration":{"fields":{"number":{"type":"int32","id":1},"fullName":{"type":"string","id":2},"type":{"type":"string","id":3},"reserved":{"type":"bool","id":5},"repeated":{"type":"bool","id":6}},"reserved":[[4,4]]},"VerificationState":{"values":{"DECLARATION":0,"UNVERIFIED":1}}}},"FieldDescriptorProto":{"fields":{"name":{"type":"string","id":1},"number":{"type":"int32","id":3},"label":{"type":"Label","id":4},"type":{"type":"Type","id":5},"typeName":{"type":"string","id":6},"extendee":{"type":"string","id":2},"defaultValue":{"type":"string","id":7},"oneofIndex":{"type":"int32","id":9},"jsonName":{"type":"string","id":10},"options":{"type":"FieldOptions","id":8},"proto3Optional":{"type":"bool","id":17}},"nested":{"Type":{"values":{"TYPE_DOUBLE":1,"TYPE_FLOAT":2,"TYPE_INT64":3,"TYPE_UINT64":4,"TYPE_INT32":5,"TYPE_FIXED64":6,"TYPE_FIXED32":7,"TYPE_BOOL":8,"TYPE_STRING":9,"TYPE_GROUP":10,"TYPE_MESSAGE":11,"TYPE_BYTES":12,"TYPE_UINT32":13,"TYPE_ENUM":14,"TYPE_SFIXED32":15,"TYPE_SFIXED64":16,"TYPE_SINT32":17,"TYPE_SINT64":18}},"Label":{"values":{"LABEL_OPTIONAL":1,"LABEL_REPEATED":3,"LABEL_REQUIRED":2}}}},"OneofDescriptorProto":{"fields":{"name":{"type":"string","id":1},"options":{"type":"OneofOptions","id":2}}},"EnumDescriptorProto":{"fields":{"name":{"type":"string","id":1},"value":{"rule":"repeated","type":"EnumValueDescriptorProto","id":2},"options":{"type":"EnumOptions","id":3},"reservedRange":{"rule":"repeated","type":"EnumReservedRange","id":4},"reservedName":{"rule":"repeated","type":"string","id":5}},"nested":{"EnumReservedRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2}}}}},"EnumValueDescriptorProto":{"fields":{"name":{"type":"string","id":1},"number":{"type":"int32","id":2},"options":{"type":"EnumValueOptions","id":3}}},"ServiceDescriptorProto":{"fields":{"name":{"type":"string","id":1},"method":{"rule":"repeated","type":"MethodDescriptorProto","id":2},"options":{"type":"ServiceOptions","id":3}}},"MethodDescriptorProto":{"fields":{"name":{"type":"string","id":1},"inputType":{"type":"string","id":2},"outputType":{"type":"string","id":3},"options":{"type":"MethodOptions","id":4},"clientStreaming":{"type":"bool","id":5,"options":{"default":false}},"serverStreaming":{"type":"bool","id":6,"options":{"default":false}}}},"FileOptions":{"fields":{"javaPackage":{"type":"string","id":1},"javaOuterClassname":{"type":"string","id":8},"javaMultipleFiles":{"type":"bool","id":10,"options":{"default":false}},"javaGenerateEqualsAndHash":{"type":"bool","id":20,"options":{"deprecated":true}},"javaStringCheckUtf8":{"type":"bool","id":27,"options":{"default":false}},"optimizeFor":{"type":"OptimizeMode","id":9,"options":{"default":"SPEED"}},"goPackage":{"type":"string","id":11},"ccGenericServices":{"type":"bool","id":16,"options":{"default":false}},"javaGenericServices":{"type":"bool","id":17,"options":{"default":false}},"pyGenericServices":{"type":"bool","id":18,"options":{"default":false}},"deprecated":{"type":"bool","id":23,"options":{"default":false}},"ccEnableArenas":{"type":"bool","id":31,"options":{"default":true}},"objcClassPrefix":{"type":"string","id":36},"csharpNamespace":{"type":"string","id":37},"swiftPrefix":{"type":"string","id":39},"phpClassPrefix":{"type":"string","id":40},"phpNamespace":{"type":"string","id":41},"phpMetadataNamespace":{"type":"string","id":44},"rubyPackage":{"type":"string","id":45},"features":{"type":"FeatureSet","id":50},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"reserved":[[42,42],[38,38]],"nested":{"OptimizeMode":{"values":{"SPEED":1,"CODE_SIZE":2,"LITE_RUNTIME":3}}}},"MessageOptions":{"fields":{"messageSetWireFormat":{"type":"bool","id":1,"options":{"default":false}},"noStandardDescriptorAccessor":{"type":"bool","id":2,"options":{"default":false}},"deprecated":{"type":"bool","id":3,"options":{"default":false}},"mapEntry":{"type":"bool","id":7},"deprecatedLegacyJsonFieldConflicts":{"type":"bool","id":11,"options":{"deprecated":true}},"features":{"type":"FeatureSet","id":12},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"reserved":[[4,4],[5,5],[6,6],[8,8],[9,9]]},"FieldOptions":{"fields":{"ctype":{"type":"CType","id":1,"options":{"default":"STRING"}},"packed":{"type":"bool","id":2},"jstype":{"type":"JSType","id":6,"options":{"default":"JS_NORMAL"}},"lazy":{"type":"bool","id":5,"options":{"default":false}},"unverifiedLazy":{"type":"bool","id":15,"options":{"default":false}},"deprecated":{"type":"bool","id":3,"options":{"default":false}},"weak":{"type":"bool","id":10,"options":{"default":false}},"debugRedact":{"type":"bool","id":16,"options":{"default":false}},"retention":{"type":"OptionRetention","id":17},"targets":{"rule":"repeated","type":"OptionTargetType","id":19,"options":{"packed":false}},"editionDefaults":{"rule":"repeated","type":"EditionDefault","id":20},"features":{"type":"FeatureSet","id":21},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"reserved":[[4,4],[18,18]],"nested":{"CType":{"values":{"STRING":0,"CORD":1,"STRING_PIECE":2}},"JSType":{"values":{"JS_NORMAL":0,"JS_STRING":1,"JS_NUMBER":2}},"OptionRetention":{"values":{"RETENTION_UNKNOWN":0,"RETENTION_RUNTIME":1,"RETENTION_SOURCE":2}},"OptionTargetType":{"values":{"TARGET_TYPE_UNKNOWN":0,"TARGET_TYPE_FILE":1,"TARGET_TYPE_EXTENSION_RANGE":2,"TARGET_TYPE_MESSAGE":3,"TARGET_TYPE_FIELD":4,"TARGET_TYPE_ONEOF":5,"TARGET_TYPE_ENUM":6,"TARGET_TYPE_ENUM_ENTRY":7,"TARGET_TYPE_SERVICE":8,"TARGET_TYPE_METHOD":9}},"EditionDefault":{"fields":{"edition":{"type":"Edition","id":3},"value":{"type":"string","id":2}}}}},"OneofOptions":{"fields":{"features":{"type":"FeatureSet","id":1},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]]},"EnumOptions":{"fields":{"allowAlias":{"type":"bool","id":2},"deprecated":{"type":"bool","id":3,"options":{"default":false}},"deprecatedLegacyJsonFieldConflicts":{"type":"bool","id":6,"options":{"deprecated":true}},"features":{"type":"FeatureSet","id":7},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"reserved":[[5,5]]},"EnumValueOptions":{"fields":{"deprecated":{"type":"bool","id":1,"options":{"default":false}},"features":{"type":"FeatureSet","id":2},"debugRedact":{"type":"bool","id":3,"options":{"default":false}},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]]},"ServiceOptions":{"fields":{"features":{"type":"FeatureSet","id":34},"deprecated":{"type":"bool","id":33,"options":{"default":false}},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]]},"MethodOptions":{"fields":{"deprecated":{"type":"bool","id":33,"options":{"default":false}},"idempotencyLevel":{"type":"IdempotencyLevel","id":34,"options":{"default":"IDEMPOTENCY_UNKNOWN"}},"features":{"type":"FeatureSet","id":35},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"nested":{"IdempotencyLevel":{"values":{"IDEMPOTENCY_UNKNOWN":0,"NO_SIDE_EFFECTS":1,"IDEMPOTENT":2}}}},"UninterpretedOption":{"fields":{"name":{"rule":"repeated","type":"NamePart","id":2},"identifierValue":{"type":"string","id":3},"positiveIntValue":{"type":"uint64","id":4},"negativeIntValue":{"type":"int64","id":5},"doubleValue":{"type":"double","id":6},"stringValue":{"type":"bytes","id":7},"aggregateValue":{"type":"string","id":8}},"nested":{"NamePart":{"fields":{"namePart":{"rule":"required","type":"string","id":1},"isExtension":{"rule":"required","type":"bool","id":2}}}}},"FeatureSet":{"fields":{"fieldPresence":{"type":"FieldPresence","id":1,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","edition_defaults.edition":"EDITION_2023","edition_defaults.value":"EXPLICIT"}},"enumType":{"type":"EnumType","id":2,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"OPEN"}},"repeatedFieldEncoding":{"type":"RepeatedFieldEncoding","id":3,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"PACKED"}},"utf8Validation":{"type":"Utf8Validation","id":4,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"VERIFY"}},"messageEncoding":{"type":"MessageEncoding","id":5,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","edition_defaults.edition":"EDITION_PROTO2","edition_defaults.value":"LENGTH_PREFIXED"}},"jsonFormat":{"type":"JsonFormat","id":6,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"ALLOW"}}},"extensions":[[1e3,1e3],[1001,1001],[1002,1002],[9995,9999],[1e4,1e4]],"reserved":[[999,999]],"nested":{"FieldPresence":{"values":{"FIELD_PRESENCE_UNKNOWN":0,"EXPLICIT":1,"IMPLICIT":2,"LEGACY_REQUIRED":3}},"EnumType":{"values":{"ENUM_TYPE_UNKNOWN":0,"OPEN":1,"CLOSED":2}},"RepeatedFieldEncoding":{"values":{"REPEATED_FIELD_ENCODING_UNKNOWN":0,"PACKED":1,"EXPANDED":2}},"Utf8Validation":{"values":{"UTF8_VALIDATION_UNKNOWN":0,"VERIFY":2,"NONE":3}},"MessageEncoding":{"values":{"MESSAGE_ENCODING_UNKNOWN":0,"LENGTH_PREFIXED":1,"DELIMITED":2}},"JsonFormat":{"values":{"JSON_FORMAT_UNKNOWN":0,"ALLOW":1,"LEGACY_BEST_EFFORT":2}}}},"FeatureSetDefaults":{"fields":{"defaults":{"rule":"repeated","type":"FeatureSetEditionDefault","id":1},"minimumEdition":{"type":"Edition","id":4},"maximumEdition":{"type":"Edition","id":5}},"nested":{"FeatureSetEditionDefault":{"fields":{"edition":{"type":"Edition","id":3},"features":{"type":"FeatureSet","id":2}}}}},"SourceCodeInfo":{"fields":{"location":{"rule":"repeated","type":"Location","id":1}},"nested":{"Location":{"fields":{"path":{"rule":"repeated","type":"int32","id":1},"span":{"rule":"repeated","type":"int32","id":2},"leadingComments":{"type":"string","id":3},"trailingComments":{"type":"string","id":4},"leadingDetachedComments":{"rule":"repeated","type":"string","id":6}}}}},"GeneratedCodeInfo":{"fields":{"annotation":{"rule":"repeated","type":"Annotation","id":1}},"nested":{"Annotation":{"fields":{"path":{"rule":"repeated","type":"int32","id":1},"sourceFile":{"type":"string","id":2},"begin":{"type":"int32","id":3},"end":{"type":"int32","id":4},"semantic":{"type":"Semantic","id":5}},"nested":{"Semantic":{"values":{"NONE":0,"SET":1,"ALIAS":2}}}}}},"Struct":{"fields":{"fields":{"keyType":"string","type":"Value","id":1}}},"Value":{"oneofs":{"kind":{"oneof":["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},"fields":{"nullValue":{"type":"NullValue","id":1},"numberValue":{"type":"double","id":2},"stringValue":{"type":"string","id":3},"boolValue":{"type":"bool","id":4},"structValue":{"type":"Struct","id":5},"listValue":{"type":"ListValue","id":6}}},"NullValue":{"values":{"NULL_VALUE":0}},"ListValue":{"fields":{"values":{"rule":"repeated","type":"Value","id":1}}},"Timestamp":{"fields":{"seconds":{"type":"int64","id":1},"nanos":{"type":"int32","id":2}}},"Duration":{"fields":{"seconds":{"type":"int64","id":1},"nanos":{"type":"int32","id":2}}},"DoubleValue":{"fields":{"value":{"type":"double","id":1}}},"FloatValue":{"fields":{"value":{"type":"float","id":1}}},"Int64Value":{"fields":{"value":{"type":"int64","id":1}}},"UInt64Value":{"fields":{"value":{"type":"uint64","id":1}}},"Int32Value":{"fields":{"value":{"type":"int32","id":1}}},"UInt32Value":{"fields":{"value":{"type":"uint32","id":1}}},"BoolValue":{"fields":{"value":{"type":"bool","id":1}}},"StringValue":{"fields":{"value":{"type":"string","id":1}}},"BytesValue":{"fields":{"value":{"type":"bytes","id":1}}},"Empty":{"fields":{}},"Any":{"fields":{"type_url":{"type":"string","id":1},"value":{"type":"bytes","id":2}}},"FieldMask":{"fields":{"paths":{"rule":"repeated","type":"string","id":1}}}}},"type":{"options":{"cc_enable_arenas":true,"go_package":"google.golang.org/genproto/googleapis/type/dayofweek;dayofweek","java_multiple_files":true,"java_outer_classname":"DayOfWeekProto","java_package":"com.google.type","objc_class_prefix":"GTP"},"nested":{"LatLng":{"fields":{"latitude":{"type":"double","id":1},"longitude":{"type":"double","id":2}}},"DayOfWeek":{"values":{"DAY_OF_WEEK_UNSPECIFIED":0,"MONDAY":1,"TUESDAY":2,"WEDNESDAY":3,"THURSDAY":4,"FRIDAY":5,"SATURDAY":6,"SUNDAY":7}}}},"rpc":{"options":{"cc_enable_arenas":true,"go_package":"google.golang.org/genproto/googleapis/rpc/status;status","java_multiple_files":true,"java_outer_classname":"StatusProto","java_package":"com.google.rpc","objc_class_prefix":"RPC"},"nested":{"Status":{"fields":{"code":{"type":"int32","id":1},"message":{"type":"string","id":2},"details":{"rule":"repeated","type":"google.protobuf.Any","id":3}}}}}}}}} \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/protos/v1beta1.json b/node_modules/@google-cloud/firestore/build/protos/v1beta1.json new file mode 100644 index 0000000..b867945 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/protos/v1beta1.json @@ -0,0 +1 @@ +{"options":{"syntax":"proto3"},"nested":{"google":{"nested":{"protobuf":{"options":{"go_package":"google.golang.org/protobuf/types/descriptorpb","java_package":"com.google.protobuf","java_outer_classname":"DescriptorProtos","csharp_namespace":"Google.Protobuf.Reflection","objc_class_prefix":"GPB","cc_enable_arenas":true,"optimize_for":"SPEED"},"nested":{"Timestamp":{"fields":{"seconds":{"type":"int64","id":1},"nanos":{"type":"int32","id":2}}},"Struct":{"fields":{"fields":{"keyType":"string","type":"Value","id":1}}},"Value":{"oneofs":{"kind":{"oneof":["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},"fields":{"nullValue":{"type":"NullValue","id":1},"numberValue":{"type":"double","id":2},"stringValue":{"type":"string","id":3},"boolValue":{"type":"bool","id":4},"structValue":{"type":"Struct","id":5},"listValue":{"type":"ListValue","id":6}}},"NullValue":{"values":{"NULL_VALUE":0}},"ListValue":{"fields":{"values":{"rule":"repeated","type":"Value","id":1}}},"FileDescriptorSet":{"fields":{"file":{"rule":"repeated","type":"FileDescriptorProto","id":1}}},"Edition":{"values":{"EDITION_UNKNOWN":0,"EDITION_PROTO2":998,"EDITION_PROTO3":999,"EDITION_2023":1e3,"EDITION_2024":1001,"EDITION_1_TEST_ONLY":1,"EDITION_2_TEST_ONLY":2,"EDITION_99997_TEST_ONLY":99997,"EDITION_99998_TEST_ONLY":99998,"EDITION_99999_TEST_ONLY":99999,"EDITION_MAX":2147483647}},"FileDescriptorProto":{"fields":{"name":{"type":"string","id":1},"package":{"type":"string","id":2},"dependency":{"rule":"repeated","type":"string","id":3},"publicDependency":{"rule":"repeated","type":"int32","id":10,"options":{"packed":false}},"weakDependency":{"rule":"repeated","type":"int32","id":11,"options":{"packed":false}},"messageType":{"rule":"repeated","type":"DescriptorProto","id":4},"enumType":{"rule":"repeated","type":"EnumDescriptorProto","id":5},"service":{"rule":"repeated","type":"ServiceDescriptorProto","id":6},"extension":{"rule":"repeated","type":"FieldDescriptorProto","id":7},"options":{"type":"FileOptions","id":8},"sourceCodeInfo":{"type":"SourceCodeInfo","id":9},"syntax":{"type":"string","id":12},"edition":{"type":"Edition","id":14}}},"DescriptorProto":{"fields":{"name":{"type":"string","id":1},"field":{"rule":"repeated","type":"FieldDescriptorProto","id":2},"extension":{"rule":"repeated","type":"FieldDescriptorProto","id":6},"nestedType":{"rule":"repeated","type":"DescriptorProto","id":3},"enumType":{"rule":"repeated","type":"EnumDescriptorProto","id":4},"extensionRange":{"rule":"repeated","type":"ExtensionRange","id":5},"oneofDecl":{"rule":"repeated","type":"OneofDescriptorProto","id":8},"options":{"type":"MessageOptions","id":7},"reservedRange":{"rule":"repeated","type":"ReservedRange","id":9},"reservedName":{"rule":"repeated","type":"string","id":10}},"nested":{"ExtensionRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2},"options":{"type":"ExtensionRangeOptions","id":3}}},"ReservedRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2}}}}},"ExtensionRangeOptions":{"fields":{"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999},"declaration":{"rule":"repeated","type":"Declaration","id":2,"options":{"retention":"RETENTION_SOURCE"}},"features":{"type":"FeatureSet","id":50},"verification":{"type":"VerificationState","id":3,"options":{"default":"UNVERIFIED","retention":"RETENTION_SOURCE"}}},"extensions":[[1e3,536870911]],"nested":{"Declaration":{"fields":{"number":{"type":"int32","id":1},"fullName":{"type":"string","id":2},"type":{"type":"string","id":3},"reserved":{"type":"bool","id":5},"repeated":{"type":"bool","id":6}},"reserved":[[4,4]]},"VerificationState":{"values":{"DECLARATION":0,"UNVERIFIED":1}}}},"FieldDescriptorProto":{"fields":{"name":{"type":"string","id":1},"number":{"type":"int32","id":3},"label":{"type":"Label","id":4},"type":{"type":"Type","id":5},"typeName":{"type":"string","id":6},"extendee":{"type":"string","id":2},"defaultValue":{"type":"string","id":7},"oneofIndex":{"type":"int32","id":9},"jsonName":{"type":"string","id":10},"options":{"type":"FieldOptions","id":8},"proto3Optional":{"type":"bool","id":17}},"nested":{"Type":{"values":{"TYPE_DOUBLE":1,"TYPE_FLOAT":2,"TYPE_INT64":3,"TYPE_UINT64":4,"TYPE_INT32":5,"TYPE_FIXED64":6,"TYPE_FIXED32":7,"TYPE_BOOL":8,"TYPE_STRING":9,"TYPE_GROUP":10,"TYPE_MESSAGE":11,"TYPE_BYTES":12,"TYPE_UINT32":13,"TYPE_ENUM":14,"TYPE_SFIXED32":15,"TYPE_SFIXED64":16,"TYPE_SINT32":17,"TYPE_SINT64":18}},"Label":{"values":{"LABEL_OPTIONAL":1,"LABEL_REPEATED":3,"LABEL_REQUIRED":2}}}},"OneofDescriptorProto":{"fields":{"name":{"type":"string","id":1},"options":{"type":"OneofOptions","id":2}}},"EnumDescriptorProto":{"fields":{"name":{"type":"string","id":1},"value":{"rule":"repeated","type":"EnumValueDescriptorProto","id":2},"options":{"type":"EnumOptions","id":3},"reservedRange":{"rule":"repeated","type":"EnumReservedRange","id":4},"reservedName":{"rule":"repeated","type":"string","id":5}},"nested":{"EnumReservedRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2}}}}},"EnumValueDescriptorProto":{"fields":{"name":{"type":"string","id":1},"number":{"type":"int32","id":2},"options":{"type":"EnumValueOptions","id":3}}},"ServiceDescriptorProto":{"fields":{"name":{"type":"string","id":1},"method":{"rule":"repeated","type":"MethodDescriptorProto","id":2},"options":{"type":"ServiceOptions","id":3}}},"MethodDescriptorProto":{"fields":{"name":{"type":"string","id":1},"inputType":{"type":"string","id":2},"outputType":{"type":"string","id":3},"options":{"type":"MethodOptions","id":4},"clientStreaming":{"type":"bool","id":5,"options":{"default":false}},"serverStreaming":{"type":"bool","id":6,"options":{"default":false}}}},"FileOptions":{"fields":{"javaPackage":{"type":"string","id":1},"javaOuterClassname":{"type":"string","id":8},"javaMultipleFiles":{"type":"bool","id":10,"options":{"default":false}},"javaGenerateEqualsAndHash":{"type":"bool","id":20,"options":{"deprecated":true}},"javaStringCheckUtf8":{"type":"bool","id":27,"options":{"default":false}},"optimizeFor":{"type":"OptimizeMode","id":9,"options":{"default":"SPEED"}},"goPackage":{"type":"string","id":11},"ccGenericServices":{"type":"bool","id":16,"options":{"default":false}},"javaGenericServices":{"type":"bool","id":17,"options":{"default":false}},"pyGenericServices":{"type":"bool","id":18,"options":{"default":false}},"deprecated":{"type":"bool","id":23,"options":{"default":false}},"ccEnableArenas":{"type":"bool","id":31,"options":{"default":true}},"objcClassPrefix":{"type":"string","id":36},"csharpNamespace":{"type":"string","id":37},"swiftPrefix":{"type":"string","id":39},"phpClassPrefix":{"type":"string","id":40},"phpNamespace":{"type":"string","id":41},"phpMetadataNamespace":{"type":"string","id":44},"rubyPackage":{"type":"string","id":45},"features":{"type":"FeatureSet","id":50},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"reserved":[[42,42],[38,38]],"nested":{"OptimizeMode":{"values":{"SPEED":1,"CODE_SIZE":2,"LITE_RUNTIME":3}}}},"MessageOptions":{"fields":{"messageSetWireFormat":{"type":"bool","id":1,"options":{"default":false}},"noStandardDescriptorAccessor":{"type":"bool","id":2,"options":{"default":false}},"deprecated":{"type":"bool","id":3,"options":{"default":false}},"mapEntry":{"type":"bool","id":7},"deprecatedLegacyJsonFieldConflicts":{"type":"bool","id":11,"options":{"deprecated":true}},"features":{"type":"FeatureSet","id":12},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"reserved":[[4,4],[5,5],[6,6],[8,8],[9,9]]},"FieldOptions":{"fields":{"ctype":{"type":"CType","id":1,"options":{"default":"STRING"}},"packed":{"type":"bool","id":2},"jstype":{"type":"JSType","id":6,"options":{"default":"JS_NORMAL"}},"lazy":{"type":"bool","id":5,"options":{"default":false}},"unverifiedLazy":{"type":"bool","id":15,"options":{"default":false}},"deprecated":{"type":"bool","id":3,"options":{"default":false}},"weak":{"type":"bool","id":10,"options":{"default":false}},"debugRedact":{"type":"bool","id":16,"options":{"default":false}},"retention":{"type":"OptionRetention","id":17},"targets":{"rule":"repeated","type":"OptionTargetType","id":19,"options":{"packed":false}},"editionDefaults":{"rule":"repeated","type":"EditionDefault","id":20},"features":{"type":"FeatureSet","id":21},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"reserved":[[4,4],[18,18]],"nested":{"CType":{"values":{"STRING":0,"CORD":1,"STRING_PIECE":2}},"JSType":{"values":{"JS_NORMAL":0,"JS_STRING":1,"JS_NUMBER":2}},"OptionRetention":{"values":{"RETENTION_UNKNOWN":0,"RETENTION_RUNTIME":1,"RETENTION_SOURCE":2}},"OptionTargetType":{"values":{"TARGET_TYPE_UNKNOWN":0,"TARGET_TYPE_FILE":1,"TARGET_TYPE_EXTENSION_RANGE":2,"TARGET_TYPE_MESSAGE":3,"TARGET_TYPE_FIELD":4,"TARGET_TYPE_ONEOF":5,"TARGET_TYPE_ENUM":6,"TARGET_TYPE_ENUM_ENTRY":7,"TARGET_TYPE_SERVICE":8,"TARGET_TYPE_METHOD":9}},"EditionDefault":{"fields":{"edition":{"type":"Edition","id":3},"value":{"type":"string","id":2}}}}},"OneofOptions":{"fields":{"features":{"type":"FeatureSet","id":1},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]]},"EnumOptions":{"fields":{"allowAlias":{"type":"bool","id":2},"deprecated":{"type":"bool","id":3,"options":{"default":false}},"deprecatedLegacyJsonFieldConflicts":{"type":"bool","id":6,"options":{"deprecated":true}},"features":{"type":"FeatureSet","id":7},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"reserved":[[5,5]]},"EnumValueOptions":{"fields":{"deprecated":{"type":"bool","id":1,"options":{"default":false}},"features":{"type":"FeatureSet","id":2},"debugRedact":{"type":"bool","id":3,"options":{"default":false}},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]]},"ServiceOptions":{"fields":{"features":{"type":"FeatureSet","id":34},"deprecated":{"type":"bool","id":33,"options":{"default":false}},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]]},"MethodOptions":{"fields":{"deprecated":{"type":"bool","id":33,"options":{"default":false}},"idempotencyLevel":{"type":"IdempotencyLevel","id":34,"options":{"default":"IDEMPOTENCY_UNKNOWN"}},"features":{"type":"FeatureSet","id":35},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1e3,536870911]],"nested":{"IdempotencyLevel":{"values":{"IDEMPOTENCY_UNKNOWN":0,"NO_SIDE_EFFECTS":1,"IDEMPOTENT":2}}}},"UninterpretedOption":{"fields":{"name":{"rule":"repeated","type":"NamePart","id":2},"identifierValue":{"type":"string","id":3},"positiveIntValue":{"type":"uint64","id":4},"negativeIntValue":{"type":"int64","id":5},"doubleValue":{"type":"double","id":6},"stringValue":{"type":"bytes","id":7},"aggregateValue":{"type":"string","id":8}},"nested":{"NamePart":{"fields":{"namePart":{"rule":"required","type":"string","id":1},"isExtension":{"rule":"required","type":"bool","id":2}}}}},"FeatureSet":{"fields":{"fieldPresence":{"type":"FieldPresence","id":1,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","edition_defaults.edition":"EDITION_2023","edition_defaults.value":"EXPLICIT"}},"enumType":{"type":"EnumType","id":2,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"OPEN"}},"repeatedFieldEncoding":{"type":"RepeatedFieldEncoding","id":3,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"PACKED"}},"utf8Validation":{"type":"Utf8Validation","id":4,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"VERIFY"}},"messageEncoding":{"type":"MessageEncoding","id":5,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","edition_defaults.edition":"EDITION_PROTO2","edition_defaults.value":"LENGTH_PREFIXED"}},"jsonFormat":{"type":"JsonFormat","id":6,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"ALLOW"}}},"extensions":[[1e3,1e3],[1001,1001],[1002,1002],[9995,9999],[1e4,1e4]],"reserved":[[999,999]],"nested":{"FieldPresence":{"values":{"FIELD_PRESENCE_UNKNOWN":0,"EXPLICIT":1,"IMPLICIT":2,"LEGACY_REQUIRED":3}},"EnumType":{"values":{"ENUM_TYPE_UNKNOWN":0,"OPEN":1,"CLOSED":2}},"RepeatedFieldEncoding":{"values":{"REPEATED_FIELD_ENCODING_UNKNOWN":0,"PACKED":1,"EXPANDED":2}},"Utf8Validation":{"values":{"UTF8_VALIDATION_UNKNOWN":0,"VERIFY":2,"NONE":3}},"MessageEncoding":{"values":{"MESSAGE_ENCODING_UNKNOWN":0,"LENGTH_PREFIXED":1,"DELIMITED":2}},"JsonFormat":{"values":{"JSON_FORMAT_UNKNOWN":0,"ALLOW":1,"LEGACY_BEST_EFFORT":2}}}},"FeatureSetDefaults":{"fields":{"defaults":{"rule":"repeated","type":"FeatureSetEditionDefault","id":1},"minimumEdition":{"type":"Edition","id":4},"maximumEdition":{"type":"Edition","id":5}},"nested":{"FeatureSetEditionDefault":{"fields":{"edition":{"type":"Edition","id":3},"features":{"type":"FeatureSet","id":2}}}}},"SourceCodeInfo":{"fields":{"location":{"rule":"repeated","type":"Location","id":1}},"nested":{"Location":{"fields":{"path":{"rule":"repeated","type":"int32","id":1},"span":{"rule":"repeated","type":"int32","id":2},"leadingComments":{"type":"string","id":3},"trailingComments":{"type":"string","id":4},"leadingDetachedComments":{"rule":"repeated","type":"string","id":6}}}}},"GeneratedCodeInfo":{"fields":{"annotation":{"rule":"repeated","type":"Annotation","id":1}},"nested":{"Annotation":{"fields":{"path":{"rule":"repeated","type":"int32","id":1},"sourceFile":{"type":"string","id":2},"begin":{"type":"int32","id":3},"end":{"type":"int32","id":4},"semantic":{"type":"Semantic","id":5}},"nested":{"Semantic":{"values":{"NONE":0,"SET":1,"ALIAS":2}}}}}},"Duration":{"fields":{"seconds":{"type":"int64","id":1},"nanos":{"type":"int32","id":2}}},"DoubleValue":{"fields":{"value":{"type":"double","id":1}}},"FloatValue":{"fields":{"value":{"type":"float","id":1}}},"Int64Value":{"fields":{"value":{"type":"int64","id":1}}},"UInt64Value":{"fields":{"value":{"type":"uint64","id":1}}},"Int32Value":{"fields":{"value":{"type":"int32","id":1}}},"UInt32Value":{"fields":{"value":{"type":"uint32","id":1}}},"BoolValue":{"fields":{"value":{"type":"bool","id":1}}},"StringValue":{"fields":{"value":{"type":"string","id":1}}},"BytesValue":{"fields":{"value":{"type":"bytes","id":1}}},"Empty":{"fields":{}},"Any":{"fields":{"type_url":{"type":"string","id":1},"value":{"type":"bytes","id":2}}},"FieldMask":{"fields":{"paths":{"rule":"repeated","type":"string","id":1}}}}},"firestore":{"nested":{"v1beta1":{"options":{"csharp_namespace":"Google.Cloud.Firestore.V1Beta1","go_package":"cloud.google.com/go/firestore/apiv1beta1/firestorepb;firestorepb","java_multiple_files":true,"java_outer_classname":"UndeliverableFirstGenEventProto","java_package":"com.google.firestore.v1beta1","objc_class_prefix":"GCFS","php_namespace":"Google\\Cloud\\Firestore\\V1beta1","ruby_package":"Google::Cloud::Firestore::V1beta1"},"nested":{"DocumentMask":{"fields":{"fieldPaths":{"rule":"repeated","type":"string","id":1}}},"Precondition":{"oneofs":{"conditionType":{"oneof":["exists","updateTime"]}},"fields":{"exists":{"type":"bool","id":1},"updateTime":{"type":"google.protobuf.Timestamp","id":2}}},"TransactionOptions":{"oneofs":{"mode":{"oneof":["readOnly","readWrite"]}},"fields":{"readOnly":{"type":"ReadOnly","id":2},"readWrite":{"type":"ReadWrite","id":3}},"nested":{"ReadWrite":{"fields":{"retryTransaction":{"type":"bytes","id":1}}},"ReadOnly":{"oneofs":{"consistencySelector":{"oneof":["readTime"]}},"fields":{"readTime":{"type":"google.protobuf.Timestamp","id":2}}}}},"Document":{"fields":{"name":{"type":"string","id":1},"fields":{"keyType":"string","type":"Value","id":2},"createTime":{"type":"google.protobuf.Timestamp","id":3},"updateTime":{"type":"google.protobuf.Timestamp","id":4}}},"Value":{"oneofs":{"valueType":{"oneof":["nullValue","booleanValue","integerValue","doubleValue","timestampValue","stringValue","bytesValue","referenceValue","geoPointValue","arrayValue","mapValue"]}},"fields":{"nullValue":{"type":"google.protobuf.NullValue","id":11},"booleanValue":{"type":"bool","id":1},"integerValue":{"type":"int64","id":2},"doubleValue":{"type":"double","id":3},"timestampValue":{"type":"google.protobuf.Timestamp","id":10},"stringValue":{"type":"string","id":17},"bytesValue":{"type":"bytes","id":18},"referenceValue":{"type":"string","id":5},"geoPointValue":{"type":"google.type.LatLng","id":8},"arrayValue":{"type":"ArrayValue","id":9},"mapValue":{"type":"MapValue","id":6}}},"ArrayValue":{"fields":{"values":{"rule":"repeated","type":"Value","id":1}}},"MapValue":{"fields":{"fields":{"keyType":"string","type":"Value","id":1}}},"Firestore":{"options":{"(google.api.default_host)":"firestore.googleapis.com","(google.api.oauth_scopes)":"https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/datastore"},"methods":{"GetDocument":{"requestType":"GetDocumentRequest","responseType":"Document","options":{"(google.api.http).get":"/v1beta1/{name=projects/*/databases/*/documents/*/**}"},"parsedOptions":[{"(google.api.http)":{"get":"/v1beta1/{name=projects/*/databases/*/documents/*/**}"}}]},"ListDocuments":{"requestType":"ListDocumentsRequest","responseType":"ListDocumentsResponse","options":{"(google.api.http).get":"/v1beta1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}"},"parsedOptions":[{"(google.api.http)":{"get":"/v1beta1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}"}}]},"UpdateDocument":{"requestType":"UpdateDocumentRequest","responseType":"Document","options":{"(google.api.http).patch":"/v1beta1/{document.name=projects/*/databases/*/documents/*/**}","(google.api.http).body":"document","(google.api.method_signature)":"document,update_mask"},"parsedOptions":[{"(google.api.http)":{"patch":"/v1beta1/{document.name=projects/*/databases/*/documents/*/**}","body":"document"}},{"(google.api.method_signature)":"document,update_mask"}]},"DeleteDocument":{"requestType":"DeleteDocumentRequest","responseType":"google.protobuf.Empty","options":{"(google.api.http).delete":"/v1beta1/{name=projects/*/databases/*/documents/*/**}","(google.api.method_signature)":"name"},"parsedOptions":[{"(google.api.http)":{"delete":"/v1beta1/{name=projects/*/databases/*/documents/*/**}"}},{"(google.api.method_signature)":"name"}]},"BatchGetDocuments":{"requestType":"BatchGetDocumentsRequest","responseType":"BatchGetDocumentsResponse","responseStream":true,"options":{"(google.api.http).post":"/v1beta1/{database=projects/*/databases/*}/documents:batchGet","(google.api.http).body":"*"},"parsedOptions":[{"(google.api.http)":{"post":"/v1beta1/{database=projects/*/databases/*}/documents:batchGet","body":"*"}}]},"BeginTransaction":{"requestType":"BeginTransactionRequest","responseType":"BeginTransactionResponse","options":{"(google.api.http).post":"/v1beta1/{database=projects/*/databases/*}/documents:beginTransaction","(google.api.http).body":"*","(google.api.method_signature)":"database"},"parsedOptions":[{"(google.api.http)":{"post":"/v1beta1/{database=projects/*/databases/*}/documents:beginTransaction","body":"*"}},{"(google.api.method_signature)":"database"}]},"Commit":{"requestType":"CommitRequest","responseType":"CommitResponse","options":{"(google.api.http).post":"/v1beta1/{database=projects/*/databases/*}/documents:commit","(google.api.http).body":"*","(google.api.method_signature)":"database,writes"},"parsedOptions":[{"(google.api.http)":{"post":"/v1beta1/{database=projects/*/databases/*}/documents:commit","body":"*"}},{"(google.api.method_signature)":"database,writes"}]},"Rollback":{"requestType":"RollbackRequest","responseType":"google.protobuf.Empty","options":{"(google.api.http).post":"/v1beta1/{database=projects/*/databases/*}/documents:rollback","(google.api.http).body":"*","(google.api.method_signature)":"database,transaction"},"parsedOptions":[{"(google.api.http)":{"post":"/v1beta1/{database=projects/*/databases/*}/documents:rollback","body":"*"}},{"(google.api.method_signature)":"database,transaction"}]},"RunQuery":{"requestType":"RunQueryRequest","responseType":"RunQueryResponse","responseStream":true,"options":{"(google.api.http).post":"/v1beta1/{parent=projects/*/databases/*/documents}:runQuery","(google.api.http).body":"*","(google.api.http).additional_bindings.post":"/v1beta1/{parent=projects/*/databases/*/documents/*/**}:runQuery","(google.api.http).additional_bindings.body":"*"},"parsedOptions":[{"(google.api.http)":{"post":"/v1beta1/{parent=projects/*/databases/*/documents}:runQuery","body":"*","additional_bindings":{"post":"/v1beta1/{parent=projects/*/databases/*/documents/*/**}:runQuery","body":"*"}}}]},"PartitionQuery":{"requestType":"PartitionQueryRequest","responseType":"PartitionQueryResponse","options":{"(google.api.http).post":"/v1beta1/{parent=projects/*/databases/*/documents}:partitionQuery","(google.api.http).body":"*","(google.api.http).additional_bindings.post":"/v1beta1/{parent=projects/*/databases/*/documents/*/**}:partitionQuery","(google.api.http).additional_bindings.body":"*"},"parsedOptions":[{"(google.api.http)":{"post":"/v1beta1/{parent=projects/*/databases/*/documents}:partitionQuery","body":"*","additional_bindings":{"post":"/v1beta1/{parent=projects/*/databases/*/documents/*/**}:partitionQuery","body":"*"}}}]},"Write":{"requestType":"WriteRequest","requestStream":true,"responseType":"WriteResponse","responseStream":true,"options":{"(google.api.http).post":"/v1beta1/{database=projects/*/databases/*}/documents:write","(google.api.http).body":"*"},"parsedOptions":[{"(google.api.http)":{"post":"/v1beta1/{database=projects/*/databases/*}/documents:write","body":"*"}}]},"Listen":{"requestType":"ListenRequest","requestStream":true,"responseType":"ListenResponse","responseStream":true,"options":{"(google.api.http).post":"/v1beta1/{database=projects/*/databases/*}/documents:listen","(google.api.http).body":"*"},"parsedOptions":[{"(google.api.http)":{"post":"/v1beta1/{database=projects/*/databases/*}/documents:listen","body":"*"}}]},"ListCollectionIds":{"requestType":"ListCollectionIdsRequest","responseType":"ListCollectionIdsResponse","options":{"(google.api.http).post":"/v1beta1/{parent=projects/*/databases/*/documents}:listCollectionIds","(google.api.http).body":"*","(google.api.http).additional_bindings.post":"/v1beta1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds","(google.api.http).additional_bindings.body":"*","(google.api.method_signature)":"parent"},"parsedOptions":[{"(google.api.http)":{"post":"/v1beta1/{parent=projects/*/databases/*/documents}:listCollectionIds","body":"*","additional_bindings":{"post":"/v1beta1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds","body":"*"}}},{"(google.api.method_signature)":"parent"}]},"BatchWrite":{"requestType":"BatchWriteRequest","responseType":"BatchWriteResponse","options":{"(google.api.http).post":"/v1beta1/{database=projects/*/databases/*}/documents:batchWrite","(google.api.http).body":"*"},"parsedOptions":[{"(google.api.http)":{"post":"/v1beta1/{database=projects/*/databases/*}/documents:batchWrite","body":"*"}}]},"CreateDocument":{"requestType":"CreateDocumentRequest","responseType":"Document","options":{"(google.api.http).post":"/v1beta1/{parent=projects/*/databases/*/documents/**}/{collection_id}","(google.api.http).body":"document"},"parsedOptions":[{"(google.api.http)":{"post":"/v1beta1/{parent=projects/*/databases/*/documents/**}/{collection_id}","body":"document"}}]}}},"GetDocumentRequest":{"oneofs":{"consistencySelector":{"oneof":["transaction","readTime"]}},"fields":{"name":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"mask":{"type":"DocumentMask","id":2},"transaction":{"type":"bytes","id":3},"readTime":{"type":"google.protobuf.Timestamp","id":5}}},"ListDocumentsRequest":{"oneofs":{"consistencySelector":{"oneof":["transaction","readTime"]}},"fields":{"parent":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"collectionId":{"type":"string","id":2,"options":{"(google.api.field_behavior)":"REQUIRED"}},"pageSize":{"type":"int32","id":3},"pageToken":{"type":"string","id":4},"orderBy":{"type":"string","id":6},"mask":{"type":"DocumentMask","id":7},"transaction":{"type":"bytes","id":8},"readTime":{"type":"google.protobuf.Timestamp","id":10},"showMissing":{"type":"bool","id":12}}},"ListDocumentsResponse":{"fields":{"documents":{"rule":"repeated","type":"Document","id":1},"nextPageToken":{"type":"string","id":2}}},"CreateDocumentRequest":{"fields":{"parent":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"collectionId":{"type":"string","id":2,"options":{"(google.api.field_behavior)":"REQUIRED"}},"documentId":{"type":"string","id":3},"document":{"type":"Document","id":4,"options":{"(google.api.field_behavior)":"REQUIRED"}},"mask":{"type":"DocumentMask","id":5}}},"UpdateDocumentRequest":{"fields":{"document":{"type":"Document","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"updateMask":{"type":"DocumentMask","id":2},"mask":{"type":"DocumentMask","id":3},"currentDocument":{"type":"Precondition","id":4}}},"DeleteDocumentRequest":{"fields":{"name":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"currentDocument":{"type":"Precondition","id":2}}},"BatchGetDocumentsRequest":{"oneofs":{"consistencySelector":{"oneof":["transaction","newTransaction","readTime"]}},"fields":{"database":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"documents":{"rule":"repeated","type":"string","id":2},"mask":{"type":"DocumentMask","id":3},"transaction":{"type":"bytes","id":4},"newTransaction":{"type":"TransactionOptions","id":5},"readTime":{"type":"google.protobuf.Timestamp","id":7}}},"BatchGetDocumentsResponse":{"oneofs":{"result":{"oneof":["found","missing"]}},"fields":{"found":{"type":"Document","id":1},"missing":{"type":"string","id":2},"transaction":{"type":"bytes","id":3},"readTime":{"type":"google.protobuf.Timestamp","id":4}}},"BeginTransactionRequest":{"fields":{"database":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"options":{"type":"TransactionOptions","id":2}}},"BeginTransactionResponse":{"fields":{"transaction":{"type":"bytes","id":1}}},"CommitRequest":{"fields":{"database":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"writes":{"rule":"repeated","type":"Write","id":2},"transaction":{"type":"bytes","id":3}}},"CommitResponse":{"fields":{"writeResults":{"rule":"repeated","type":"WriteResult","id":1},"commitTime":{"type":"google.protobuf.Timestamp","id":2}}},"RollbackRequest":{"fields":{"database":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"transaction":{"type":"bytes","id":2,"options":{"(google.api.field_behavior)":"REQUIRED"}}}},"RunQueryRequest":{"oneofs":{"queryType":{"oneof":["structuredQuery"]},"consistencySelector":{"oneof":["transaction","newTransaction","readTime"]}},"fields":{"parent":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"structuredQuery":{"type":"StructuredQuery","id":2},"transaction":{"type":"bytes","id":5},"newTransaction":{"type":"TransactionOptions","id":6},"readTime":{"type":"google.protobuf.Timestamp","id":7}}},"RunQueryResponse":{"fields":{"transaction":{"type":"bytes","id":2},"document":{"type":"Document","id":1},"readTime":{"type":"google.protobuf.Timestamp","id":3},"skippedResults":{"type":"int32","id":4}}},"PartitionQueryRequest":{"oneofs":{"queryType":{"oneof":["structuredQuery"]}},"fields":{"parent":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"structuredQuery":{"type":"StructuredQuery","id":2},"partitionCount":{"type":"int64","id":3},"pageToken":{"type":"string","id":4},"pageSize":{"type":"int32","id":5}}},"PartitionQueryResponse":{"fields":{"partitions":{"rule":"repeated","type":"Cursor","id":1},"nextPageToken":{"type":"string","id":2}}},"WriteRequest":{"fields":{"database":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"streamId":{"type":"string","id":2},"writes":{"rule":"repeated","type":"Write","id":3},"streamToken":{"type":"bytes","id":4},"labels":{"keyType":"string","type":"string","id":5}}},"WriteResponse":{"fields":{"streamId":{"type":"string","id":1},"streamToken":{"type":"bytes","id":2},"writeResults":{"rule":"repeated","type":"WriteResult","id":3},"commitTime":{"type":"google.protobuf.Timestamp","id":4}}},"ListenRequest":{"oneofs":{"targetChange":{"oneof":["addTarget","removeTarget"]}},"fields":{"database":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"addTarget":{"type":"Target","id":2},"removeTarget":{"type":"int32","id":3},"labels":{"keyType":"string","type":"string","id":4}}},"ListenResponse":{"oneofs":{"responseType":{"oneof":["targetChange","documentChange","documentDelete","documentRemove","filter"]}},"fields":{"targetChange":{"type":"TargetChange","id":2},"documentChange":{"type":"DocumentChange","id":3},"documentDelete":{"type":"DocumentDelete","id":4},"documentRemove":{"type":"DocumentRemove","id":6},"filter":{"type":"ExistenceFilter","id":5}}},"Target":{"oneofs":{"targetType":{"oneof":["query","documents"]},"resumeType":{"oneof":["resumeToken","readTime"]}},"fields":{"query":{"type":"QueryTarget","id":2},"documents":{"type":"DocumentsTarget","id":3},"resumeToken":{"type":"bytes","id":4},"readTime":{"type":"google.protobuf.Timestamp","id":11},"targetId":{"type":"int32","id":5},"once":{"type":"bool","id":6}},"nested":{"DocumentsTarget":{"fields":{"documents":{"rule":"repeated","type":"string","id":2}}},"QueryTarget":{"oneofs":{"queryType":{"oneof":["structuredQuery"]}},"fields":{"parent":{"type":"string","id":1},"structuredQuery":{"type":"StructuredQuery","id":2}}}}},"TargetChange":{"fields":{"targetChangeType":{"type":"TargetChangeType","id":1},"targetIds":{"rule":"repeated","type":"int32","id":2},"cause":{"type":"google.rpc.Status","id":3},"resumeToken":{"type":"bytes","id":4},"readTime":{"type":"google.protobuf.Timestamp","id":6}},"nested":{"TargetChangeType":{"values":{"NO_CHANGE":0,"ADD":1,"REMOVE":2,"CURRENT":3,"RESET":4}}}},"ListCollectionIdsRequest":{"fields":{"parent":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"pageSize":{"type":"int32","id":2},"pageToken":{"type":"string","id":3}}},"ListCollectionIdsResponse":{"fields":{"collectionIds":{"rule":"repeated","type":"string","id":1},"nextPageToken":{"type":"string","id":2}}},"BatchWriteRequest":{"fields":{"database":{"type":"string","id":1,"options":{"(google.api.field_behavior)":"REQUIRED"}},"writes":{"rule":"repeated","type":"Write","id":2},"labels":{"keyType":"string","type":"string","id":3}}},"BatchWriteResponse":{"fields":{"writeResults":{"rule":"repeated","type":"WriteResult","id":1},"status":{"rule":"repeated","type":"google.rpc.Status","id":2}}},"StructuredQuery":{"fields":{"select":{"type":"Projection","id":1},"from":{"rule":"repeated","type":"CollectionSelector","id":2},"where":{"type":"Filter","id":3},"orderBy":{"rule":"repeated","type":"Order","id":4},"startAt":{"type":"Cursor","id":7},"endAt":{"type":"Cursor","id":8},"offset":{"type":"int32","id":6},"limit":{"type":"google.protobuf.Int32Value","id":5}},"nested":{"CollectionSelector":{"fields":{"collectionId":{"type":"string","id":2},"allDescendants":{"type":"bool","id":3}}},"Filter":{"oneofs":{"filterType":{"oneof":["compositeFilter","fieldFilter","unaryFilter"]}},"fields":{"compositeFilter":{"type":"CompositeFilter","id":1},"fieldFilter":{"type":"FieldFilter","id":2},"unaryFilter":{"type":"UnaryFilter","id":3}}},"CompositeFilter":{"fields":{"op":{"type":"Operator","id":1},"filters":{"rule":"repeated","type":"Filter","id":2}},"nested":{"Operator":{"values":{"OPERATOR_UNSPECIFIED":0,"AND":1}}}},"FieldFilter":{"fields":{"field":{"type":"FieldReference","id":1},"op":{"type":"Operator","id":2},"value":{"type":"Value","id":3}},"nested":{"Operator":{"values":{"OPERATOR_UNSPECIFIED":0,"LESS_THAN":1,"LESS_THAN_OR_EQUAL":2,"GREATER_THAN":3,"GREATER_THAN_OR_EQUAL":4,"EQUAL":5,"NOT_EQUAL":6,"ARRAY_CONTAINS":7,"IN":8,"ARRAY_CONTAINS_ANY":9,"NOT_IN":10}}}},"UnaryFilter":{"oneofs":{"operandType":{"oneof":["field"]}},"fields":{"op":{"type":"Operator","id":1},"field":{"type":"FieldReference","id":2}},"nested":{"Operator":{"values":{"OPERATOR_UNSPECIFIED":0,"IS_NAN":2,"IS_NULL":3,"IS_NOT_NAN":4,"IS_NOT_NULL":5}}}},"FieldReference":{"fields":{"fieldPath":{"type":"string","id":2}}},"Order":{"fields":{"field":{"type":"FieldReference","id":1},"direction":{"type":"Direction","id":2}}},"Projection":{"fields":{"fields":{"rule":"repeated","type":"FieldReference","id":2}}},"Direction":{"values":{"DIRECTION_UNSPECIFIED":0,"ASCENDING":1,"DESCENDING":2}}}},"Cursor":{"fields":{"values":{"rule":"repeated","type":"Value","id":1},"before":{"type":"bool","id":2}}},"Write":{"oneofs":{"operation":{"oneof":["update","delete","transform"]}},"fields":{"update":{"type":"Document","id":1},"delete":{"type":"string","id":2},"transform":{"type":"DocumentTransform","id":6},"updateMask":{"type":"DocumentMask","id":3},"updateTransforms":{"rule":"repeated","type":"DocumentTransform.FieldTransform","id":7},"currentDocument":{"type":"Precondition","id":4}}},"DocumentTransform":{"fields":{"document":{"type":"string","id":1},"fieldTransforms":{"rule":"repeated","type":"FieldTransform","id":2}},"nested":{"FieldTransform":{"oneofs":{"transformType":{"oneof":["setToServerValue","increment","maximum","minimum","appendMissingElements","removeAllFromArray"]}},"fields":{"fieldPath":{"type":"string","id":1},"setToServerValue":{"type":"ServerValue","id":2},"increment":{"type":"Value","id":3},"maximum":{"type":"Value","id":4},"minimum":{"type":"Value","id":5},"appendMissingElements":{"type":"ArrayValue","id":6},"removeAllFromArray":{"type":"ArrayValue","id":7}},"nested":{"ServerValue":{"values":{"SERVER_VALUE_UNSPECIFIED":0,"REQUEST_TIME":1}}}}}},"WriteResult":{"fields":{"updateTime":{"type":"google.protobuf.Timestamp","id":1},"transformResults":{"rule":"repeated","type":"Value","id":2}}},"DocumentChange":{"fields":{"document":{"type":"Document","id":1},"targetIds":{"rule":"repeated","type":"int32","id":5},"removedTargetIds":{"rule":"repeated","type":"int32","id":6}}},"DocumentDelete":{"fields":{"document":{"type":"string","id":1},"removedTargetIds":{"rule":"repeated","type":"int32","id":6},"readTime":{"type":"google.protobuf.Timestamp","id":4}}},"DocumentRemove":{"fields":{"document":{"type":"string","id":1},"removedTargetIds":{"rule":"repeated","type":"int32","id":2},"readTime":{"type":"google.protobuf.Timestamp","id":4}}},"ExistenceFilter":{"fields":{"targetId":{"type":"int32","id":1},"count":{"type":"int32","id":2}}},"UndeliverableFirstGenEvent":{"fields":{"message":{"type":"string","id":1},"reason":{"type":"Reason","id":2},"documentName":{"type":"string","id":3},"documentChangeType":{"type":"DocumentChangeType","id":4},"functionName":{"rule":"repeated","type":"string","id":5},"triggeredTime":{"type":"google.protobuf.Timestamp","id":6}},"nested":{"Reason":{"values":{"REASON_UNSPECIFIED":0,"EXCEEDING_SIZE_LIMIT":1}},"DocumentChangeType":{"values":{"DOCUMENT_CHANGE_TYPE_UNSPECIFIED":0,"CREATE":1,"DELETE":2,"UPDATE":3}}}}}}}},"type":{"options":{"cc_enable_arenas":true,"go_package":"google.golang.org/genproto/googleapis/type/dayofweek;dayofweek","java_multiple_files":true,"java_outer_classname":"DayOfWeekProto","java_package":"com.google.type","objc_class_prefix":"GTP"},"nested":{"LatLng":{"fields":{"latitude":{"type":"double","id":1},"longitude":{"type":"double","id":2}}},"DayOfWeek":{"values":{"DAY_OF_WEEK_UNSPECIFIED":0,"MONDAY":1,"TUESDAY":2,"WEDNESDAY":3,"THURSDAY":4,"FRIDAY":5,"SATURDAY":6,"SUNDAY":7}}}},"api":{"options":{"go_package":"google.golang.org/genproto/googleapis/api/annotations;annotations","java_multiple_files":true,"java_outer_classname":"ResourceProto","java_package":"com.google.api","objc_class_prefix":"GAPI","cc_enable_arenas":true},"nested":{"http":{"type":"HttpRule","id":72295728,"extend":"google.protobuf.MethodOptions"},"Http":{"fields":{"rules":{"rule":"repeated","type":"HttpRule","id":1},"fullyDecodeReservedExpansion":{"type":"bool","id":2}}},"HttpRule":{"oneofs":{"pattern":{"oneof":["get","put","post","delete","patch","custom"]}},"fields":{"selector":{"type":"string","id":1},"get":{"type":"string","id":2},"put":{"type":"string","id":3},"post":{"type":"string","id":4},"delete":{"type":"string","id":5},"patch":{"type":"string","id":6},"custom":{"type":"CustomHttpPattern","id":8},"body":{"type":"string","id":7},"responseBody":{"type":"string","id":12},"additionalBindings":{"rule":"repeated","type":"HttpRule","id":11}}},"CustomHttpPattern":{"fields":{"kind":{"type":"string","id":1},"path":{"type":"string","id":2}}},"methodSignature":{"rule":"repeated","type":"string","id":1051,"extend":"google.protobuf.MethodOptions"},"defaultHost":{"type":"string","id":1049,"extend":"google.protobuf.ServiceOptions"},"oauthScopes":{"type":"string","id":1050,"extend":"google.protobuf.ServiceOptions"},"apiVersion":{"type":"string","id":525000001,"extend":"google.protobuf.ServiceOptions"},"CommonLanguageSettings":{"fields":{"referenceDocsUri":{"type":"string","id":1,"options":{"deprecated":true}},"destinations":{"rule":"repeated","type":"ClientLibraryDestination","id":2},"selectiveGapicGeneration":{"type":"SelectiveGapicGeneration","id":3}}},"ClientLibrarySettings":{"fields":{"version":{"type":"string","id":1},"launchStage":{"type":"LaunchStage","id":2},"restNumericEnums":{"type":"bool","id":3},"javaSettings":{"type":"JavaSettings","id":21},"cppSettings":{"type":"CppSettings","id":22},"phpSettings":{"type":"PhpSettings","id":23},"pythonSettings":{"type":"PythonSettings","id":24},"nodeSettings":{"type":"NodeSettings","id":25},"dotnetSettings":{"type":"DotnetSettings","id":26},"rubySettings":{"type":"RubySettings","id":27},"goSettings":{"type":"GoSettings","id":28}}},"Publishing":{"fields":{"methodSettings":{"rule":"repeated","type":"MethodSettings","id":2},"newIssueUri":{"type":"string","id":101},"documentationUri":{"type":"string","id":102},"apiShortName":{"type":"string","id":103},"githubLabel":{"type":"string","id":104},"codeownerGithubTeams":{"rule":"repeated","type":"string","id":105},"docTagPrefix":{"type":"string","id":106},"organization":{"type":"ClientLibraryOrganization","id":107},"librarySettings":{"rule":"repeated","type":"ClientLibrarySettings","id":109},"protoReferenceDocumentationUri":{"type":"string","id":110},"restReferenceDocumentationUri":{"type":"string","id":111}}},"JavaSettings":{"fields":{"libraryPackage":{"type":"string","id":1},"serviceClassNames":{"keyType":"string","type":"string","id":2},"common":{"type":"CommonLanguageSettings","id":3}}},"CppSettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1}}},"PhpSettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1}}},"PythonSettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1},"experimentalFeatures":{"type":"ExperimentalFeatures","id":2}},"nested":{"ExperimentalFeatures":{"fields":{"restAsyncIoEnabled":{"type":"bool","id":1},"protobufPythonicTypesEnabled":{"type":"bool","id":2}}}}},"NodeSettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1}}},"DotnetSettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1},"renamedServices":{"keyType":"string","type":"string","id":2},"renamedResources":{"keyType":"string","type":"string","id":3},"ignoredResources":{"rule":"repeated","type":"string","id":4},"forcedNamespaceAliases":{"rule":"repeated","type":"string","id":5},"handwrittenSignatures":{"rule":"repeated","type":"string","id":6}}},"RubySettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1}}},"GoSettings":{"fields":{"common":{"type":"CommonLanguageSettings","id":1},"renamedServices":{"keyType":"string","type":"string","id":2}}},"MethodSettings":{"fields":{"selector":{"type":"string","id":1},"longRunning":{"type":"LongRunning","id":2},"autoPopulatedFields":{"rule":"repeated","type":"string","id":3}},"nested":{"LongRunning":{"fields":{"initialPollDelay":{"type":"google.protobuf.Duration","id":1},"pollDelayMultiplier":{"type":"float","id":2},"maxPollDelay":{"type":"google.protobuf.Duration","id":3},"totalPollTimeout":{"type":"google.protobuf.Duration","id":4}}}}},"ClientLibraryOrganization":{"values":{"CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED":0,"CLOUD":1,"ADS":2,"PHOTOS":3,"STREET_VIEW":4,"SHOPPING":5,"GEO":6,"GENERATIVE_AI":7}},"ClientLibraryDestination":{"values":{"CLIENT_LIBRARY_DESTINATION_UNSPECIFIED":0,"GITHUB":10,"PACKAGE_MANAGER":20}},"SelectiveGapicGeneration":{"fields":{"methods":{"rule":"repeated","type":"string","id":1},"generateOmittedAsInternal":{"type":"bool","id":2}}},"LaunchStage":{"values":{"LAUNCH_STAGE_UNSPECIFIED":0,"UNIMPLEMENTED":6,"PRELAUNCH":7,"EARLY_ACCESS":1,"ALPHA":2,"BETA":3,"GA":4,"DEPRECATED":5}},"fieldBehavior":{"rule":"repeated","type":"google.api.FieldBehavior","id":1052,"extend":"google.protobuf.FieldOptions","options":{"packed":false}},"FieldBehavior":{"values":{"FIELD_BEHAVIOR_UNSPECIFIED":0,"OPTIONAL":1,"REQUIRED":2,"OUTPUT_ONLY":3,"INPUT_ONLY":4,"IMMUTABLE":5,"UNORDERED_LIST":6,"NON_EMPTY_DEFAULT":7,"IDENTIFIER":8}},"resourceReference":{"type":"google.api.ResourceReference","id":1055,"extend":"google.protobuf.FieldOptions"},"resourceDefinition":{"rule":"repeated","type":"google.api.ResourceDescriptor","id":1053,"extend":"google.protobuf.FileOptions"},"resource":{"type":"google.api.ResourceDescriptor","id":1053,"extend":"google.protobuf.MessageOptions"},"ResourceDescriptor":{"fields":{"type":{"type":"string","id":1},"pattern":{"rule":"repeated","type":"string","id":2},"nameField":{"type":"string","id":3},"history":{"type":"History","id":4},"plural":{"type":"string","id":5},"singular":{"type":"string","id":6},"style":{"rule":"repeated","type":"Style","id":10}},"nested":{"History":{"values":{"HISTORY_UNSPECIFIED":0,"ORIGINALLY_SINGLE_PATTERN":1,"FUTURE_MULTI_PATTERN":2}},"Style":{"values":{"STYLE_UNSPECIFIED":0,"DECLARATIVE_FRIENDLY":1}}}},"ResourceReference":{"fields":{"type":{"type":"string","id":1},"childType":{"type":"string","id":2}}}}},"rpc":{"options":{"cc_enable_arenas":true,"go_package":"google.golang.org/genproto/googleapis/rpc/status;status","java_multiple_files":true,"java_outer_classname":"StatusProto","java_package":"com.google.rpc","objc_class_prefix":"RPC"},"nested":{"Status":{"fields":{"code":{"type":"int32","id":1},"message":{"type":"string","id":2},"details":{"rule":"repeated","type":"google.protobuf.Any","id":3}}}}}}}}} \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/aggregate.d.ts b/node_modules/@google-cloud/firestore/build/src/aggregate.d.ts new file mode 100644 index 0000000..3f2efea --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/aggregate.d.ts @@ -0,0 +1,95 @@ +/** + * Copyright 2023 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. + */ +import * as firestore from '@google-cloud/firestore'; +import { FieldPath } from './path'; +import { google } from '../protos/firestore_v1_proto_api'; +import IAggregation = google.firestore.v1.StructuredAggregationQuery.IAggregation; +/** + * Concrete implementation of the Aggregate type. + */ +export declare class Aggregate { + readonly alias: string; + readonly aggregateType: AggregateType; + readonly fieldPath?: (string | FieldPath) | undefined; + constructor(alias: string, aggregateType: AggregateType, fieldPath?: (string | FieldPath) | undefined); + /** + * Converts this object to the proto representation of an Aggregate. + * @internal + */ + toProto(): IAggregation; +} +/** + * Represents an aggregation that can be performed by Firestore. + */ +export declare class AggregateField implements firestore.AggregateField { + readonly aggregateType: AggregateType; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateField"; + /** + * The field on which the aggregation is performed. + * @internal + **/ + readonly _field?: string | FieldPath; + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param field Optionally specifies the field that is aggregated. + * @internal + */ + private constructor(); + /** + * Compares this object with the given object for equality. + * + * This object is considered "equal" to the other object if and only if + * `other` performs the same kind of aggregation on the same field (if any). + * + * @param other The object to compare to this object for equality. + * @return `true` if this object is "equal" to the given object, as + * defined above, or `false` otherwise. + */ + isEqual(other: AggregateField): boolean; + /** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ + static count(): AggregateField; + /** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ + static average(field: string | FieldPath): AggregateField; + /** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ + static sum(field: string | FieldPath): AggregateField; +} +/** + * A type whose property values are all `AggregateField` objects. + */ +export interface AggregateSpec { + [field: string]: AggregateFieldType; +} +/** + * The union of all `AggregateField` types that are supported by Firestore. + */ +export type AggregateFieldType = ReturnType | ReturnType | ReturnType; +/** + * Union type representing the aggregate type to be performed. + */ +export type AggregateType = 'count' | 'avg' | 'sum'; diff --git a/node_modules/@google-cloud/firestore/build/src/aggregate.js b/node_modules/@google-cloud/firestore/build/src/aggregate.js new file mode 100644 index 0000000..01c675b --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/aggregate.js @@ -0,0 +1,122 @@ +"use strict"; +/** + * Copyright 2023 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AggregateField = exports.Aggregate = void 0; +const path_1 = require("./path"); +const assert = require("assert"); +/** + * Concrete implementation of the Aggregate type. + */ +class Aggregate { + constructor(alias, aggregateType, fieldPath) { + this.alias = alias; + this.aggregateType = aggregateType; + this.fieldPath = fieldPath; + } + /** + * Converts this object to the proto representation of an Aggregate. + * @internal + */ + toProto() { + const proto = {}; + if (this.aggregateType === 'count') { + proto.count = {}; + } + else if (this.aggregateType === 'sum') { + assert(this.fieldPath !== undefined, 'Missing field path for sum aggregation.'); + proto.sum = { + field: { + fieldPath: path_1.FieldPath.fromArgument(this.fieldPath).formattedName, + }, + }; + } + else if (this.aggregateType === 'avg') { + assert(this.fieldPath !== undefined, 'Missing field path for average aggregation.'); + proto.avg = { + field: { + fieldPath: path_1.FieldPath.fromArgument(this.fieldPath).formattedName, + }, + }; + } + else { + throw new Error(`Aggregate type ${this.aggregateType} unimplemented.`); + } + proto.alias = this.alias; + return proto; + } +} +exports.Aggregate = Aggregate; +/** + * Represents an aggregation that can be performed by Firestore. + */ +class AggregateField { + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param field Optionally specifies the field that is aggregated. + * @internal + */ + constructor(aggregateType, field) { + this.aggregateType = aggregateType; + /** A type string to uniquely identify instances of this class. */ + this.type = 'AggregateField'; + this._field = field; + } + /** + * Compares this object with the given object for equality. + * + * This object is considered "equal" to the other object if and only if + * `other` performs the same kind of aggregation on the same field (if any). + * + * @param other The object to compare to this object for equality. + * @return `true` if this object is "equal" to the given object, as + * defined above, or `false` otherwise. + */ + isEqual(other) { + return (other instanceof AggregateField && + this.aggregateType === other.aggregateType && + ((this._field === undefined && other._field === undefined) || + (this._field !== undefined && + other._field !== undefined && + path_1.FieldPath.fromArgument(this._field).isEqual(path_1.FieldPath.fromArgument(other._field))))); + } + /** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ + static count() { + return new AggregateField('count'); + } + /** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ + static average(field) { + return new AggregateField('avg', field); + } + /** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ + static sum(field) { + return new AggregateField('sum', field); + } +} +exports.AggregateField = AggregateField; +//# sourceMappingURL=aggregate.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/backoff.d.ts b/node_modules/@google-cloud/firestore/build/src/backoff.d.ts new file mode 100644 index 0000000..4338371 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/backoff.d.ts @@ -0,0 +1,177 @@ +/*! + * Copyright 2017 Google Inc. 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. + */ +/*! + * The default initial backoff time in milliseconds after an error. + * Set to 1s according to https://cloud.google.com/apis/design/errors. + */ +export declare const DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000; +/*! + * The default maximum backoff time in milliseconds. + */ +export declare const DEFAULT_BACKOFF_MAX_DELAY_MS: number; +/*! + * The default factor to increase the backup by after each failed attempt. + */ +export declare const DEFAULT_BACKOFF_FACTOR = 1.5; +/*! + * The maximum number of retries that will be attempted by backoff + * before stopping all retry attempts. + */ +export declare const MAX_RETRY_ATTEMPTS = 10; +/*! + * The timeout handler used by `ExponentialBackoff` and `BulkWriter`. + */ +export declare let delayExecution: (f: () => void, ms: number) => NodeJS.Timeout; +/** + * Allows overriding of the timeout handler used by the exponential backoff + * implementation. If not invoked, we default to `setTimeout()`. + * + * Used only in testing. + * + * @private + * @internal + * @param {function} handler A handler than matches the API of `setTimeout()`. + */ +export declare function setTimeoutHandler(handler: (f: () => void, ms: number) => void): void; +/** + * Configuration object to adjust the delays of the exponential backoff + * algorithm. + * + * @private + * @internal + */ +export interface ExponentialBackoffSetting { + /** Optional override for the initial retry delay. */ + initialDelayMs?: number; + /** Optional override for the exponential backoff factor. */ + backoffFactor?: number; + /** Optional override for the maximum retry delay. */ + maxDelayMs?: number; + /** + * Optional override to control the itter factor by which to randomize + * attempts (0 means no randomization, 1.0 means +/-50% randomization). It is + * suggested not to exceed this range. + */ + jitterFactor?: number; +} +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a "jitter" (+/- 50% by default) that is calculated and + * added to the base delay. This prevents clients from accidentally + * synchronizing their delays causing spikes of load to the backend. + * + * @private + * @internal + */ +export declare class ExponentialBackoff { + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs (based on a jitter factor of 1.0). + * + * @private + * @internal + */ + private readonly initialDelayMs; + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + * + * @private + * @internal + */ + private readonly backoffFactor; + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs (based on a jitter factor of 1.0). + * + * @private + * @internal + */ + private readonly maxDelayMs; + /** + * The jitter factor that controls the random distribution of the backoff + * points. + * + * @private + * @internal + */ + private readonly jitterFactor; + /** + * The number of retries that has been attempted. + * + * @private + * @internal + */ + private _retryCount; + /** + * The backoff delay of the current attempt. + * + * @private + * @internal + */ + private currentBaseMs; + /** + * Whether we are currently waiting for backoff to complete. + * + * @private + * @internal + */ + private awaitingBackoffCompletion; + constructor(options?: ExponentialBackoffSetting); + /** + * Resets the backoff delay and retry count. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + * + * @private + * @internal + */ + reset(): void; + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + * + * @private + * @internal + */ + resetToMax(): void; + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. + * + * @return A Promise that resolves when the current delay elapsed. + * @private + * @internal + */ + backoffAndWait(): Promise; + get retryCount(): number; + /** + * Returns a randomized "jitter" delay based on the current base and jitter + * factor. + * + * @returns {number} The jitter to apply based on the current delay. + * @private + * @internal + */ + private jitterDelayMs; +} diff --git a/node_modules/@google-cloud/firestore/build/src/backoff.js b/node_modules/@google-cloud/firestore/build/src/backoff.js new file mode 100644 index 0000000..5748f7a --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/backoff.js @@ -0,0 +1,225 @@ +"use strict"; +/*! + * Copyright 2017 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ExponentialBackoff = exports.delayExecution = exports.MAX_RETRY_ATTEMPTS = exports.DEFAULT_BACKOFF_FACTOR = exports.DEFAULT_BACKOFF_MAX_DELAY_MS = exports.DEFAULT_BACKOFF_INITIAL_DELAY_MS = void 0; +exports.setTimeoutHandler = setTimeoutHandler; +const logger_1 = require("./logger"); +/* + * @module firestore/backoff + * @private + * @internal + * + * Contains backoff logic to facilitate RPC error handling. This class derives + * its implementation from the Firestore Mobile Web Client. + * + * @see https://github.com/firebase/firebase-js-sdk/blob/master/packages/firestore/src/remote/backoff.ts + */ +/*! + * The default initial backoff time in milliseconds after an error. + * Set to 1s according to https://cloud.google.com/apis/design/errors. + */ +exports.DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000; +/*! + * The default maximum backoff time in milliseconds. + */ +exports.DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000; +/*! + * The default factor to increase the backup by after each failed attempt. + */ +exports.DEFAULT_BACKOFF_FACTOR = 1.5; +/*! + * The default jitter to distribute the backoff attempts by (0 means no + * randomization, 1.0 means +/-50% randomization). + */ +const DEFAULT_JITTER_FACTOR = 1.0; +/*! + * The maximum number of retries that will be attempted by backoff + * before stopping all retry attempts. + */ +exports.MAX_RETRY_ATTEMPTS = 10; +/*! + * The timeout handler used by `ExponentialBackoff` and `BulkWriter`. + */ +exports.delayExecution = setTimeout; +/** + * Allows overriding of the timeout handler used by the exponential backoff + * implementation. If not invoked, we default to `setTimeout()`. + * + * Used only in testing. + * + * @private + * @internal + * @param {function} handler A handler than matches the API of `setTimeout()`. + */ +function setTimeoutHandler(handler) { + exports.delayExecution = (f, ms) => { + handler(f, ms); + const timeout = { + hasRef: () => { + throw new Error('For tests only. Not Implemented'); + }, + ref: () => { + throw new Error('For tests only. Not Implemented'); + }, + refresh: () => { + throw new Error('For tests only. Not Implemented'); + }, + unref: () => { + throw new Error('For tests only. Not Implemented'); + }, + [Symbol.toPrimitive]: () => { + throw new Error('For tests only. Not Implemented'); + }, + }; + // `NodeJS.Timeout` type signature change: + // https://github.com/DefinitelyTyped/DefinitelyTyped/pull/66176/files#diff-e838d0ace9cd5f6516bacfbd3ad00d02cd37bd60f9993ce6223f52d889a1fdbaR122-R126 + // + // Adding `[Symbol.dispose](): void;` cannot be done on older versions of + // NodeJS. So we simply cast to `NodeJS.Timeout`. + return timeout; + }; +} +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a "jitter" (+/- 50% by default) that is calculated and + * added to the base delay. This prevents clients from accidentally + * synchronizing their delays causing spikes of load to the backend. + * + * @private + * @internal + */ +class ExponentialBackoff { + constructor(options = {}) { + /** + * The number of retries that has been attempted. + * + * @private + * @internal + */ + this._retryCount = 0; + /** + * The backoff delay of the current attempt. + * + * @private + * @internal + */ + this.currentBaseMs = 0; + /** + * Whether we are currently waiting for backoff to complete. + * + * @private + * @internal + */ + this.awaitingBackoffCompletion = false; + this.initialDelayMs = + options.initialDelayMs !== undefined + ? options.initialDelayMs + : exports.DEFAULT_BACKOFF_INITIAL_DELAY_MS; + this.backoffFactor = + options.backoffFactor !== undefined + ? options.backoffFactor + : exports.DEFAULT_BACKOFF_FACTOR; + this.maxDelayMs = + options.maxDelayMs !== undefined + ? options.maxDelayMs + : exports.DEFAULT_BACKOFF_MAX_DELAY_MS; + this.jitterFactor = + options.jitterFactor !== undefined + ? options.jitterFactor + : DEFAULT_JITTER_FACTOR; + } + /** + * Resets the backoff delay and retry count. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + * + * @private + * @internal + */ + reset() { + this._retryCount = 0; + this.currentBaseMs = 0; + } + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + * + * @private + * @internal + */ + resetToMax() { + this.currentBaseMs = this.maxDelayMs; + } + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. + * + * @return A Promise that resolves when the current delay elapsed. + * @private + * @internal + */ + backoffAndWait() { + if (this.awaitingBackoffCompletion) { + return Promise.reject(new Error('A backoff operation is already in progress.')); + } + if (this.retryCount > exports.MAX_RETRY_ATTEMPTS) { + return Promise.reject(new Error('Exceeded maximum number of retries allowed.')); + } + // First schedule using the current base (which may be 0 and should be + // honored as such). + const delayWithJitterMs = this.currentBaseMs + this.jitterDelayMs(); + if (this.currentBaseMs > 0) { + (0, logger_1.logger)('ExponentialBackoff.backoffAndWait', null, `Backing off for ${delayWithJitterMs} ms ` + + `(base delay: ${this.currentBaseMs} ms)`); + } + // Apply backoff factor to determine next delay and ensure it is within + // bounds. + this.currentBaseMs *= this.backoffFactor; + this.currentBaseMs = Math.max(this.currentBaseMs, this.initialDelayMs); + this.currentBaseMs = Math.min(this.currentBaseMs, this.maxDelayMs); + this._retryCount += 1; + return new Promise(resolve => { + this.awaitingBackoffCompletion = true; + (0, exports.delayExecution)(() => { + this.awaitingBackoffCompletion = false; + resolve(); + }, delayWithJitterMs); + }); + } + // Visible for testing. + get retryCount() { + return this._retryCount; + } + /** + * Returns a randomized "jitter" delay based on the current base and jitter + * factor. + * + * @returns {number} The jitter to apply based on the current delay. + * @private + * @internal + */ + jitterDelayMs() { + return (Math.random() - 0.5) * this.jitterFactor * this.currentBaseMs; + } +} +exports.ExponentialBackoff = ExponentialBackoff; +//# sourceMappingURL=backoff.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/bulk-writer.d.ts b/node_modules/@google-cloud/firestore/build/src/bulk-writer.d.ts new file mode 100644 index 0000000..c3ab8cb --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/bulk-writer.d.ts @@ -0,0 +1,529 @@ +/*! + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as firestore from '@google-cloud/firestore'; +import type { GoogleError } from 'google-gax'; +import { FieldPath, Firestore } from '.'; +import { RateLimiter } from './rate-limiter'; +import { Timestamp } from './timestamp'; +import { WriteBatch, WriteResult } from './write-batch'; +import GrpcStatus = FirebaseFirestore.GrpcStatus; +/*! + * The maximum number of writes can be can in a single batch that is being retried. + */ +export declare const RETRY_MAX_BATCH_SIZE = 10; +/*! + * The starting maximum number of operations per second as allowed by the + * 500/50/5 rule. + * + * https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic. + */ +export declare const DEFAULT_INITIAL_OPS_PER_SECOND_LIMIT = 500; +/*! + * The maximum number of operations per second as allowed by the 500/50/5 rule. + * By default the rate limiter will not exceed this value. + * + * https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic. + */ +export declare const DEFAULT_MAXIMUM_OPS_PER_SECOND_LIMIT = 10000; +/*! + * The default jitter to apply to the exponential backoff used in retries. For + * example, a factor of 0.3 means a 30% jitter is applied. + */ +export declare const DEFAULT_JITTER_FACTOR = 0.3; +/** + * Represents a single write for BulkWriter, encapsulating operation dispatch + * and error handling. + * @private + * @internal + */ +declare class BulkWriterOperation { + readonly ref: firestore.DocumentReference; + private readonly type; + private readonly sendFn; + private readonly errorFn; + private readonly successFn; + private deferred; + private failedAttempts; + private lastStatus?; + private _backoffDuration; + /** Whether flush() was called when this was the last enqueued operation. */ + private _flushed; + /** + * @param ref The document reference being written to. + * @param type The type of operation that created this write. + * @param sendFn A callback to invoke when the operation should be sent. + * @param errorFn The user provided global error callback. + * @param successFn The user provided global success callback. + */ + constructor(ref: firestore.DocumentReference, type: 'create' | 'set' | 'update' | 'delete', sendFn: (op: BulkWriterOperation) => void, errorFn: (error: BulkWriterError) => boolean, successFn: (ref: firestore.DocumentReference, result: WriteResult) => void); + get promise(): Promise; + get backoffDuration(): number; + markFlushed(): void; + get flushed(): boolean; + onError(error: GoogleError): void; + private updateBackoffDuration; + onSuccess(result: WriteResult): void; +} +/** + * Used to represent a batch on the BatchQueue. + * + * @private + * @internal + */ +declare class BulkCommitBatch extends WriteBatch { + readonly docPaths: Set; + readonly pendingOps: Array; + private _maxBatchSize; + constructor(firestore: Firestore, maxBatchSize: number); + get maxBatchSize(): number; + setMaxBatchSize(size: number): void; + has(documentRef: firestore.DocumentReference): boolean; + bulkCommit(options?: { + requestTag?: string; + }): Promise; + /** + * Helper to update data structures associated with the operation and returns + * the result. + */ + processLastOperation(op: BulkWriterOperation): void; +} +/** + * The error thrown when a BulkWriter operation fails. + * + * @class BulkWriterError + */ +export declare class BulkWriterError extends Error { + /** The status code of the error. */ + readonly code: GrpcStatus; + /** The error message of the error. */ + readonly message: string; + /** The document reference the operation was performed on. */ + readonly documentRef: firestore.DocumentReference; + /** The type of operation performed. */ + readonly operationType: 'create' | 'set' | 'update' | 'delete'; + /** How many times this operation has been attempted unsuccessfully. */ + readonly failedAttempts: number; + /** + * @private + * @internal + */ + constructor( + /** The status code of the error. */ + code: GrpcStatus, + /** The error message of the error. */ + message: string, + /** The document reference the operation was performed on. */ + documentRef: firestore.DocumentReference, + /** The type of operation performed. */ + operationType: 'create' | 'set' | 'update' | 'delete', + /** How many times this operation has been attempted unsuccessfully. */ + failedAttempts: number); +} +/** + * A Firestore BulkWriter that can be used to perform a large number of writes + * in parallel. + * + * @class BulkWriter + */ +export declare class BulkWriter { + private readonly firestore; + /** + * The maximum number of writes that can be in a single batch. + * Visible for testing. + * @private + * @internal + */ + private _maxBatchSize; + /** + * The batch that is currently used to schedule operations. Once this batch + * reaches maximum capacity, a new batch is created. + * @private + * @internal + */ + private _bulkCommitBatch; + /** + * A pointer to the tail of all active BulkWriter operations. This pointer + * is advanced every time a new write is enqueued. + * @private + * @internal + */ + private _lastOp; + /** + * When this BulkWriter instance has started to close, a flush promise is + * saved. Afterwards, no new operations can be enqueued, except for retry + * operations scheduled by the error handler. + * @private + * @internal + */ + private _closePromise; + /** + * Rate limiter used to throttle requests as per the 500/50/5 rule. + * Visible for testing. + * @private + * @internal + */ + readonly _rateLimiter: RateLimiter; + /** + * The number of pending operations enqueued on this BulkWriter instance. + * An operation is considered pending if BulkWriter has sent it via RPC and + * is awaiting the result. + * @private + * @internal + */ + private _pendingOpsCount; + /** + * An array containing buffered BulkWriter operations after the maximum number + * of pending operations has been enqueued. + * @private + * @internal + */ + private _bufferedOperations; + /** + * Whether a custom error handler has been set. BulkWriter only swallows + * errors if an error handler is set. Otherwise, an UnhandledPromiseRejection + * is thrown by Node if an operation promise is rejected without being + * handled. + * @private + * @internal + */ + private _errorHandlerSet; + /** + * @private + * @internal + */ + _getBufferedOperationsCount(): number; + /** + * @private + * @internal + */ + _setMaxBatchSize(size: number): void; + /** + * The maximum number of pending operations that can be enqueued onto this + * BulkWriter instance. Once the this number of writes have been enqueued, + * subsequent writes are buffered. + * @private + * @internal + */ + private _maxPendingOpCount; + /** + * @private + * @internal + */ + _setMaxPendingOpCount(newMax: number): void; + /** + * The user-provided callback to be run every time a BulkWriter operation + * successfully completes. + * @private + * @internal + */ + private _successFn; + /** + * The user-provided callback to be run every time a BulkWriter operation + * fails. + * @private + * @internal + */ + private _errorFn; + /** @private */ + constructor(firestore: Firestore, options?: firestore.BulkWriterOptions); + /** + * Create a document with the provided data. This single operation will fail + * if a document exists at its location. + * + * @param {DocumentReference} documentRef A reference to the document to be + * created. + * @param {T} data The object to serialize as the document. + * @throws {Error} If the provided input is not a valid Firestore document. + * @returns {Promise} A promise that resolves with the result of + * the write. If the write fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + * + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * let documentRef = firestore.collection('col').doc(); + * + * bulkWriter + * .create(documentRef, {foo: 'bar'}) + * .then(result => { + * console.log('Successfully executed write at: ', result); + * }) + * .catch(err => { + * console.log('Write failed with: ', err); + * }); + * }); + * ``` + */ + create(documentRef: firestore.DocumentReference, data: firestore.WithFieldValue): Promise; + /** + * Delete a document from the database. + * + * @param {DocumentReference} documentRef A reference to the document to be + * deleted. + * @param {Precondition=} precondition A precondition to enforce for this + * delete. + * @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the + * document was last updated at lastUpdateTime. Fails the batch if the + * document doesn't exist or was last updated at a different time. + * @returns {Promise} A promise that resolves with the result of + * the delete. If the delete fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + * + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * let documentRef = firestore.doc('col/doc'); + * + * bulkWriter + * .delete(documentRef) + * .then(result => { + * console.log('Successfully deleted document'); + * }) + * .catch(err => { + * console.log('Delete failed with: ', err); + * }); + * }); + * ``` + */ + delete(documentRef: firestore.DocumentReference, precondition?: firestore.Precondition): Promise; + set(documentRef: firestore.DocumentReference, data: Partial, options: firestore.SetOptions): Promise; + set(documentRef: firestore.DocumentReference, data: AppModelType): Promise; + /** + * Update fields of the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. If the document doesn't yet + * exist, the update fails and the entire batch will be rejected. + * + * The update() method accepts either an object with field paths encoded as + * keys and field values encoded as values, or a variable number of arguments + * that alternate between field paths and field values. Nested fields can be + * updated by providing dot-separated field path strings or by providing + * FieldPath objects. + * + * + * A Precondition restricting this update can be specified as the last + * argument. + * + * @param {DocumentReference} documentRef A reference to the document to be + * updated. + * @param {UpdateData|string|FieldPath} dataOrField An object containing the + * fields and values with which to update the document or the path of the + * first field to update. + * @param {...(Precondition|*|string|FieldPath)} preconditionOrValues - An + * alternating list of field paths and values to update or a Precondition to + * restrict this update + * @throws {Error} If the provided input is not valid Firestore data. + * @returns {Promise} A promise that resolves with the result of + * the write. If the write fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + * + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * let documentRef = firestore.doc('col/doc'); + * + * bulkWriter + * .update(documentRef, {foo: 'bar'}) + * .then(result => { + * console.log('Successfully executed write at: ', result); + * }) + * .catch(err => { + * console.log('Write failed with: ', err); + * }); + * }); + * ``` + */ + update(documentRef: firestore.DocumentReference, dataOrField: firestore.UpdateData | string | FieldPath, ...preconditionOrValues: Array<{ + lastUpdateTime?: Timestamp; + } | unknown | string | FieldPath>): Promise; + /** + * Callback function set by {@link BulkWriter#onWriteResult} that is run + * every time a {@link BulkWriter} operation successfully completes. + * + * @callback BulkWriter~successCallback + * @param {DocumentReference} documentRef The document reference the + * operation was performed on + * @param {WriteResult} result The server write time of the operation. + */ + /** + * Attaches a listener that is run every time a BulkWriter operation + * successfully completes. + * + * @param {BulkWriter~successCallback} successCallback A callback to be + * called every time a BulkWriter operation successfully completes. + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * + * bulkWriter + * .onWriteResult((documentRef, result) => { + * console.log( + * 'Successfully executed write on document: ', + * documentRef, + * ' at: ', + * result + * ); + * }); + * ``` + */ + onWriteResult(successCallback: (documentRef: firestore.DocumentReference, result: WriteResult) => void): void; + /** + * Callback function set by {@link BulkWriter#onWriteError} that is run when + * a write fails in order to determine whether {@link BulkWriter} should + * retry the operation. + * + * @callback BulkWriter~shouldRetryCallback + * @param {BulkWriterError} error The error object with information about the + * operation and error. + * @returns {boolean} Whether or not to retry the failed operation. Returning + * `true` retries the operation. Returning `false` will stop the retry loop. + */ + /** + * Attaches an error handler listener that is run every time a BulkWriter + * operation fails. + * + * BulkWriter has a default error handler that retries UNAVAILABLE and + * ABORTED errors up to a maximum of 10 failed attempts. When an error + * handler is specified, the default error handler will be overwritten. + * + * @param shouldRetryCallback {BulkWriter~shouldRetryCallback} A callback to + * be called every time a BulkWriter operation fails. Returning `true` will + * retry the operation. Returning `false` will stop the retry loop. + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * + * bulkWriter + * .onWriteError((error) => { + * if ( + * error.code === GrpcStatus.UNAVAILABLE && + * error.failedAttempts < MAX_RETRY_ATTEMPTS + * ) { + * return true; + * } else { + * console.log('Failed write at document: ', error.documentRef); + * return false; + * } + * }); + * ``` + */ + onWriteError(shouldRetryCallback: (error: BulkWriterError) => boolean): void; + /** + * Commits all writes that have been enqueued up to this point in parallel. + * + * Returns a Promise that resolves when all currently queued operations have + * been committed. The Promise will never be rejected since the results for + * each individual operation are conveyed via their individual Promises. + * + * The Promise resolves immediately if there are no pending writes. Otherwise, + * the Promise waits for all previously issued writes, but it does not wait + * for writes that were added after the method is called. If you want to wait + * for additional writes, call `flush()` again. + * + * @return {Promise} A promise that resolves when all enqueued writes + * up to this point have been committed. + * + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * + * bulkWriter.create(documentRef, {foo: 'bar'}); + * bulkWriter.update(documentRef2, {foo: 'bar'}); + * bulkWriter.delete(documentRef3); + * await flush().then(() => { + * console.log('Executed all writes'); + * }); + * ``` + */ + flush(): Promise; + /** + * Commits all enqueued writes and marks the BulkWriter instance as closed. + * + * After calling `close()`, calling any method will throw an error. Any + * retries scheduled as part of an `onWriteError()` handler will be run + * before the `close()` promise resolves. + * + * Returns a Promise that resolves when there are no more pending writes. The + * Promise will never be rejected. Calling this method will send all requests. + * The promise resolves immediately if there are no pending writes. + * + * @return {Promise} A promise that resolves when all enqueued writes + * up to this point have been committed. + * + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * + * bulkWriter.create(documentRef, {foo: 'bar'}); + * bulkWriter.update(documentRef2, {foo: 'bar'}); + * bulkWriter.delete(documentRef3); + * await close().then(() => { + * console.log('Executed all writes'); + * }); + * ``` + */ + close(): Promise; + /** + * Throws an error if the BulkWriter instance has been closed. + * @private + * @internal + */ + _verifyNotClosed(): void; + /** + * Sends the current batch and resets `this._bulkCommitBatch`. + * + * @param flush If provided, keeps re-sending operations until no more + * operations are enqueued. This allows retries to resolve as part of a + * `flush()` or `close()` call. + * @private + * @internal + */ + private _scheduleCurrentBatch; + /** + * Sends the provided batch once the rate limiter does not require any delay. + * @private + * @internal + */ + private _sendBatch; + /** + * Adds a 30% jitter to the provided backoff. + * + * @private + * @internal + */ + private static _applyJitter; + /** + * Schedules and runs the provided operation on the next available batch. + * @private + * @internal + */ + private _enqueue; + /** + * Manages the pending operation counter and schedules the next BulkWriter + * operation if we're under the maximum limit. + * @private + * @internal + */ + private _processBufferedOps; + /** + * Schedules the provided operations on current BulkCommitBatch. + * Sends the BulkCommitBatch if it reaches maximum capacity. + * + * @private + * @internal + */ + _sendFn(enqueueOnBatchCallback: (bulkCommitBatch: BulkCommitBatch) => void, op: BulkWriterOperation): void; +} +export {}; diff --git a/node_modules/@google-cloud/firestore/build/src/bulk-writer.js b/node_modules/@google-cloud/firestore/build/src/bulk-writer.js new file mode 100644 index 0000000..9b0af53 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/bulk-writer.js @@ -0,0 +1,915 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BulkWriter = exports.BulkWriterError = exports.DEFAULT_JITTER_FACTOR = exports.DEFAULT_MAXIMUM_OPS_PER_SECOND_LIMIT = exports.DEFAULT_INITIAL_OPS_PER_SECOND_LIMIT = exports.RETRY_MAX_BATCH_SIZE = void 0; +const assert = require("assert"); +const backoff_1 = require("./backoff"); +const rate_limiter_1 = require("./rate-limiter"); +const timestamp_1 = require("./timestamp"); +const util_1 = require("./util"); +const write_batch_1 = require("./write-batch"); +const validate_1 = require("./validate"); +const logger_1 = require("./logger"); +const trace_util_1 = require("./telemetry/trace-util"); +/*! + * The maximum number of writes that can be in a single batch. + */ +const MAX_BATCH_SIZE = 20; +/*! + * The maximum number of writes can be can in a single batch that is being retried. + */ +exports.RETRY_MAX_BATCH_SIZE = 10; +/*! + * The starting maximum number of operations per second as allowed by the + * 500/50/5 rule. + * + * https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic. + */ +exports.DEFAULT_INITIAL_OPS_PER_SECOND_LIMIT = 500; +/*! + * The maximum number of operations per second as allowed by the 500/50/5 rule. + * By default the rate limiter will not exceed this value. + * + * https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic. + */ +exports.DEFAULT_MAXIMUM_OPS_PER_SECOND_LIMIT = 10000; +/*! + * The default jitter to apply to the exponential backoff used in retries. For + * example, a factor of 0.3 means a 30% jitter is applied. + */ +exports.DEFAULT_JITTER_FACTOR = 0.3; +/*! + * The rate by which to increase the capacity as specified by the 500/50/5 rule. + */ +const RATE_LIMITER_MULTIPLIER = 1.5; +/*! + * How often the operations per second capacity should increase in milliseconds + * as specified by the 500/50/5 rule. + */ +const RATE_LIMITER_MULTIPLIER_MILLIS = 5 * 60 * 1000; +/*! + * The default maximum number of pending operations that can be enqueued onto a + * BulkWriter instance. An operation is considered pending if BulkWriter has + * sent it via RPC and is awaiting the result. BulkWriter buffers additional + * writes after this many pending operations in order to avoiding going OOM. + */ +const DEFAULT_MAXIMUM_PENDING_OPERATIONS_COUNT = 500; +/** + * Represents a single write for BulkWriter, encapsulating operation dispatch + * and error handling. + * @private + * @internal + */ +class BulkWriterOperation { + /** + * @param ref The document reference being written to. + * @param type The type of operation that created this write. + * @param sendFn A callback to invoke when the operation should be sent. + * @param errorFn The user provided global error callback. + * @param successFn The user provided global success callback. + */ + constructor(ref, type, sendFn, errorFn, successFn) { + this.ref = ref; + this.type = type; + this.sendFn = sendFn; + this.errorFn = errorFn; + this.successFn = successFn; + this.deferred = new util_1.Deferred(); + this.failedAttempts = 0; + this._backoffDuration = 0; + /** Whether flush() was called when this was the last enqueued operation. */ + this._flushed = false; + } + get promise() { + return this.deferred.promise; + } + get backoffDuration() { + return this._backoffDuration; + } + markFlushed() { + this._flushed = true; + } + get flushed() { + return this._flushed; + } + onError(error) { + ++this.failedAttempts; + try { + const bulkWriterError = new BulkWriterError(error.code, error.message, this.ref, this.type, this.failedAttempts); + const shouldRetry = this.errorFn(bulkWriterError); + (0, logger_1.logger)('BulkWriter.errorFn', null, 'Ran error callback on error code:', error.code, ', shouldRetry:', shouldRetry, ' for document:', this.ref.path); + if (shouldRetry) { + this.lastStatus = error.code; + this.updateBackoffDuration(); + this.sendFn(this); + } + else { + this.deferred.reject(bulkWriterError); + } + } + catch (userCallbackError) { + this.deferred.reject(userCallbackError); + } + } + updateBackoffDuration() { + if (this.lastStatus === 8 /* StatusCode.RESOURCE_EXHAUSTED */) { + this._backoffDuration = backoff_1.DEFAULT_BACKOFF_MAX_DELAY_MS; + } + else if (this._backoffDuration === 0) { + this._backoffDuration = backoff_1.DEFAULT_BACKOFF_INITIAL_DELAY_MS; + } + else { + this._backoffDuration *= backoff_1.DEFAULT_BACKOFF_FACTOR; + } + } + onSuccess(result) { + try { + this.successFn(this.ref, result); + this.deferred.resolve(result); + } + catch (userCallbackError) { + this.deferred.reject(userCallbackError); + } + } +} +/** + * Used to represent a batch on the BatchQueue. + * + * @private + * @internal + */ +class BulkCommitBatch extends write_batch_1.WriteBatch { + constructor(firestore, maxBatchSize) { + super(firestore); + // The set of document reference paths present in the WriteBatch. + this.docPaths = new Set(); + // An array of pending write operations. Only contains writes that have not + // been resolved. + this.pendingOps = []; + this._maxBatchSize = maxBatchSize; + } + get maxBatchSize() { + return this._maxBatchSize; + } + setMaxBatchSize(size) { + assert(this.pendingOps.length <= size, 'New batch size cannot be less than the number of enqueued writes'); + this._maxBatchSize = size; + } + has(documentRef) { + return this.docPaths.has(documentRef.path); + } + async bulkCommit(options = {}) { + return this._firestore._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_BULK_WRITER_COMMIT, async () => { + var _a; + const tag = (_a = options === null || options === void 0 ? void 0 : options.requestTag) !== null && _a !== void 0 ? _a : (0, util_1.requestTag)(); + // Capture the error stack to preserve stack tracing across async calls. + const stack = Error().stack; + let response; + try { + (0, logger_1.logger)('BulkCommitBatch.bulkCommit', tag, `Sending next batch with ${this._opCount} writes`); + const retryCodes = (0, util_1.getRetryCodes)('batchWrite'); + response = await this._commit({ retryCodes, methodName: 'batchWrite', requestTag: tag }); + } + catch (err) { + // Map the failure to each individual write's result. + const ops = Array.from({ length: this.pendingOps.length }); + response = { + writeResults: ops.map(() => { + return {}; + }), + status: ops.map(() => err), + }; + } + for (let i = 0; i < (response.writeResults || []).length; ++i) { + // Since delete operations currently do not have write times, use a + // sentinel Timestamp value. + // TODO(b/158502664): Use actual delete timestamp. + const DELETE_TIMESTAMP_SENTINEL = timestamp_1.Timestamp.fromMillis(0); + const status = (response.status || [])[i]; + if (status.code === 0 /* StatusCode.OK */) { + const updateTime = timestamp_1.Timestamp.fromProto(response.writeResults[i].updateTime || DELETE_TIMESTAMP_SENTINEL); + this.pendingOps[i].onSuccess(new write_batch_1.WriteResult(updateTime)); + } + else { + const error = new (require('google-gax/build/src/fallback').GoogleError)(status.message || undefined); + error.code = status.code; + this.pendingOps[i].onError((0, util_1.wrapError)(error, stack)); + } + } + }, { + [trace_util_1.ATTRIBUTE_KEY_DOC_COUNT]: this._opCount, + }); + } + /** + * Helper to update data structures associated with the operation and returns + * the result. + */ + processLastOperation(op) { + assert(!this.docPaths.has(op.ref.path), 'Batch should not contain writes to the same document'); + this.docPaths.add(op.ref.path); + this.pendingOps.push(op); + } +} +/** + * Used to represent a buffered BulkWriterOperation. + * + * @private + * @internal + */ +class BufferedOperation { + constructor(operation, sendFn) { + this.operation = operation; + this.sendFn = sendFn; + } +} +/** + * The error thrown when a BulkWriter operation fails. + * + * @class BulkWriterError + */ +class BulkWriterError extends Error { + /** + * @private + * @internal + */ + constructor( + /** The status code of the error. */ + code, + /** The error message of the error. */ + message, + /** The document reference the operation was performed on. */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + documentRef, + /** The type of operation performed. */ + operationType, + /** How many times this operation has been attempted unsuccessfully. */ + failedAttempts) { + super(message); + this.code = code; + this.message = message; + this.documentRef = documentRef; + this.operationType = operationType; + this.failedAttempts = failedAttempts; + } +} +exports.BulkWriterError = BulkWriterError; +/** + * A Firestore BulkWriter that can be used to perform a large number of writes + * in parallel. + * + * @class BulkWriter + */ +class BulkWriter { + // Visible for testing. + /** + * @private + * @internal + */ + _getBufferedOperationsCount() { + return this._bufferedOperations.length; + } + // Visible for testing. + /** + * @private + * @internal + */ + _setMaxBatchSize(size) { + assert(this._bulkCommitBatch.pendingOps.length === 0, 'BulkCommitBatch should be empty'); + this._maxBatchSize = size; + this._bulkCommitBatch = new BulkCommitBatch(this.firestore, size); + } + // Visible for testing. + /** + * @private + * @internal + */ + _setMaxPendingOpCount(newMax) { + this._maxPendingOpCount = newMax; + } + /** @private */ + constructor(firestore, options) { + var _a, _b; + this.firestore = firestore; + /** + * The maximum number of writes that can be in a single batch. + * Visible for testing. + * @private + * @internal + */ + this._maxBatchSize = MAX_BATCH_SIZE; + /** + * The batch that is currently used to schedule operations. Once this batch + * reaches maximum capacity, a new batch is created. + * @private + * @internal + */ + this._bulkCommitBatch = new BulkCommitBatch(this.firestore, this._maxBatchSize); + /** + * A pointer to the tail of all active BulkWriter operations. This pointer + * is advanced every time a new write is enqueued. + * @private + * @internal + */ + this._lastOp = Promise.resolve(); + /** + * The number of pending operations enqueued on this BulkWriter instance. + * An operation is considered pending if BulkWriter has sent it via RPC and + * is awaiting the result. + * @private + * @internal + */ + this._pendingOpsCount = 0; + /** + * An array containing buffered BulkWriter operations after the maximum number + * of pending operations has been enqueued. + * @private + * @internal + */ + this._bufferedOperations = []; + /** + * Whether a custom error handler has been set. BulkWriter only swallows + * errors if an error handler is set. Otherwise, an UnhandledPromiseRejection + * is thrown by Node if an operation promise is rejected without being + * handled. + * @private + * @internal + */ + this._errorHandlerSet = false; + /** + * The maximum number of pending operations that can be enqueued onto this + * BulkWriter instance. Once the this number of writes have been enqueued, + * subsequent writes are buffered. + * @private + * @internal + */ + this._maxPendingOpCount = DEFAULT_MAXIMUM_PENDING_OPERATIONS_COUNT; + /** + * The user-provided callback to be run every time a BulkWriter operation + * successfully completes. + * @private + * @internal + */ + this._successFn = () => { }; + /** + * The user-provided callback to be run every time a BulkWriter operation + * fails. + * @private + * @internal + */ + this._errorFn = error => { + const isRetryableDeleteError = error.operationType === 'delete' && + error.code === 13 /* StatusCode.INTERNAL */; + const retryCodes = (0, util_1.getRetryCodes)('batchWrite'); + return ((retryCodes.includes(error.code) || isRetryableDeleteError) && + error.failedAttempts < backoff_1.MAX_RETRY_ATTEMPTS); + }; + this.firestore._incrementBulkWritersCount(); + validateBulkWriterOptions(options); + if ((options === null || options === void 0 ? void 0 : options.throttling) === false) { + this._rateLimiter = new rate_limiter_1.RateLimiter(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY); + } + else { + let startingRate = exports.DEFAULT_INITIAL_OPS_PER_SECOND_LIMIT; + let maxRate = exports.DEFAULT_MAXIMUM_OPS_PER_SECOND_LIMIT; + if (typeof (options === null || options === void 0 ? void 0 : options.throttling) !== 'boolean') { + if (((_a = options === null || options === void 0 ? void 0 : options.throttling) === null || _a === void 0 ? void 0 : _a.maxOpsPerSecond) !== undefined) { + maxRate = options.throttling.maxOpsPerSecond; + } + if (((_b = options === null || options === void 0 ? void 0 : options.throttling) === null || _b === void 0 ? void 0 : _b.initialOpsPerSecond) !== undefined) { + startingRate = options.throttling.initialOpsPerSecond; + } + // The initial validation step ensures that the maxOpsPerSecond is + // greater than initialOpsPerSecond. If this inequality is true, that + // means initialOpsPerSecond was not set and maxOpsPerSecond is less + // than the default starting rate. + if (maxRate < startingRate) { + startingRate = maxRate; + } + // Ensure that the batch size is not larger than the number of allowed + // operations per second. + if (startingRate < this._maxBatchSize) { + this._maxBatchSize = startingRate; + } + } + this._rateLimiter = new rate_limiter_1.RateLimiter(startingRate, RATE_LIMITER_MULTIPLIER, RATE_LIMITER_MULTIPLIER_MILLIS, maxRate); + } + } + /** + * Create a document with the provided data. This single operation will fail + * if a document exists at its location. + * + * @param {DocumentReference} documentRef A reference to the document to be + * created. + * @param {T} data The object to serialize as the document. + * @throws {Error} If the provided input is not a valid Firestore document. + * @returns {Promise} A promise that resolves with the result of + * the write. If the write fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + * + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * let documentRef = firestore.collection('col').doc(); + * + * bulkWriter + * .create(documentRef, {foo: 'bar'}) + * .then(result => { + * console.log('Successfully executed write at: ', result); + * }) + * .catch(err => { + * console.log('Write failed with: ', err); + * }); + * }); + * ``` + */ + create(documentRef, data) { + this._verifyNotClosed(); + return this._enqueue(documentRef, 'create', bulkCommitBatch => bulkCommitBatch.create(documentRef, data)); + } + /** + * Delete a document from the database. + * + * @param {DocumentReference} documentRef A reference to the document to be + * deleted. + * @param {Precondition=} precondition A precondition to enforce for this + * delete. + * @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the + * document was last updated at lastUpdateTime. Fails the batch if the + * document doesn't exist or was last updated at a different time. + * @returns {Promise} A promise that resolves with the result of + * the delete. If the delete fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + * + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * let documentRef = firestore.doc('col/doc'); + * + * bulkWriter + * .delete(documentRef) + * .then(result => { + * console.log('Successfully deleted document'); + * }) + * .catch(err => { + * console.log('Delete failed with: ', err); + * }); + * }); + * ``` + */ + delete(documentRef, precondition) { + this._verifyNotClosed(); + return this._enqueue(documentRef, 'delete', bulkCommitBatch => bulkCommitBatch.delete(documentRef, precondition)); + } + /** + * Write to the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. If the document does not + * exist yet, it will be created. If you pass [SetOptions]{@link SetOptions}., + * the provided data can be merged into the existing document. + * + * @param {DocumentReference} documentRef A reference to the document to be + * set. + * @param {T} data The object to serialize as the document. + * @param {SetOptions=} options An object to configure the set behavior. + * @throws {Error} If the provided input is not a valid Firestore document. + * @param {boolean=} options.merge - If true, set() merges the values + * specified in its data argument. Fields omitted from this set() call remain + * untouched. If your input sets any field to an empty map, all nested fields + * are overwritten. + * @param {Array.=} options.mergeFields - If provided, set() + * only replaces the specified field paths. Any field path that is not + * specified is ignored and remains untouched. If your input sets any field to + * an empty map, all nested fields are overwritten. + * @returns {Promise} A promise that resolves with the result of + * the write. If the write fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + * + * + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * let documentRef = firestore.collection('col').doc(); + * + * bulkWriter + * .set(documentRef, {foo: 'bar'}) + * .then(result => { + * console.log('Successfully executed write at: ', result); + * }) + * .catch(err => { + * console.log('Write failed with: ', err); + * }); + * }); + * ``` + */ + set(documentRef, data, options) { + this._verifyNotClosed(); + return this._enqueue(documentRef, 'set', bulkCommitBatch => { + if (options) { + return bulkCommitBatch.set(documentRef, data, options); + } + else { + return bulkCommitBatch.set(documentRef, data); + } + }); + } + /** + * Update fields of the document referred to by the provided + * [DocumentReference]{@link DocumentReference}. If the document doesn't yet + * exist, the update fails and the entire batch will be rejected. + * + * The update() method accepts either an object with field paths encoded as + * keys and field values encoded as values, or a variable number of arguments + * that alternate between field paths and field values. Nested fields can be + * updated by providing dot-separated field path strings or by providing + * FieldPath objects. + * + * + * A Precondition restricting this update can be specified as the last + * argument. + * + * @param {DocumentReference} documentRef A reference to the document to be + * updated. + * @param {UpdateData|string|FieldPath} dataOrField An object containing the + * fields and values with which to update the document or the path of the + * first field to update. + * @param {...(Precondition|*|string|FieldPath)} preconditionOrValues - An + * alternating list of field paths and values to update or a Precondition to + * restrict this update + * @throws {Error} If the provided input is not valid Firestore data. + * @returns {Promise} A promise that resolves with the result of + * the write. If the write fails, the promise is rejected with a + * [BulkWriterError]{@link BulkWriterError}. + * + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * let documentRef = firestore.doc('col/doc'); + * + * bulkWriter + * .update(documentRef, {foo: 'bar'}) + * .then(result => { + * console.log('Successfully executed write at: ', result); + * }) + * .catch(err => { + * console.log('Write failed with: ', err); + * }); + * }); + * ``` + */ + update(documentRef, dataOrField, ...preconditionOrValues) { + this._verifyNotClosed(); + return this._enqueue(documentRef, 'update', bulkCommitBatch => bulkCommitBatch.update(documentRef, dataOrField, ...preconditionOrValues)); + } + /** + * Callback function set by {@link BulkWriter#onWriteResult} that is run + * every time a {@link BulkWriter} operation successfully completes. + * + * @callback BulkWriter~successCallback + * @param {DocumentReference} documentRef The document reference the + * operation was performed on + * @param {WriteResult} result The server write time of the operation. + */ + /** + * Attaches a listener that is run every time a BulkWriter operation + * successfully completes. + * + * @param {BulkWriter~successCallback} successCallback A callback to be + * called every time a BulkWriter operation successfully completes. + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * + * bulkWriter + * .onWriteResult((documentRef, result) => { + * console.log( + * 'Successfully executed write on document: ', + * documentRef, + * ' at: ', + * result + * ); + * }); + * ``` + */ + onWriteResult(successCallback) { + this._successFn = successCallback; + } + /** + * Callback function set by {@link BulkWriter#onWriteError} that is run when + * a write fails in order to determine whether {@link BulkWriter} should + * retry the operation. + * + * @callback BulkWriter~shouldRetryCallback + * @param {BulkWriterError} error The error object with information about the + * operation and error. + * @returns {boolean} Whether or not to retry the failed operation. Returning + * `true` retries the operation. Returning `false` will stop the retry loop. + */ + /** + * Attaches an error handler listener that is run every time a BulkWriter + * operation fails. + * + * BulkWriter has a default error handler that retries UNAVAILABLE and + * ABORTED errors up to a maximum of 10 failed attempts. When an error + * handler is specified, the default error handler will be overwritten. + * + * @param shouldRetryCallback {BulkWriter~shouldRetryCallback} A callback to + * be called every time a BulkWriter operation fails. Returning `true` will + * retry the operation. Returning `false` will stop the retry loop. + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * + * bulkWriter + * .onWriteError((error) => { + * if ( + * error.code === GrpcStatus.UNAVAILABLE && + * error.failedAttempts < MAX_RETRY_ATTEMPTS + * ) { + * return true; + * } else { + * console.log('Failed write at document: ', error.documentRef); + * return false; + * } + * }); + * ``` + */ + onWriteError(shouldRetryCallback) { + this._errorHandlerSet = true; + this._errorFn = shouldRetryCallback; + } + /** + * Commits all writes that have been enqueued up to this point in parallel. + * + * Returns a Promise that resolves when all currently queued operations have + * been committed. The Promise will never be rejected since the results for + * each individual operation are conveyed via their individual Promises. + * + * The Promise resolves immediately if there are no pending writes. Otherwise, + * the Promise waits for all previously issued writes, but it does not wait + * for writes that were added after the method is called. If you want to wait + * for additional writes, call `flush()` again. + * + * @return {Promise} A promise that resolves when all enqueued writes + * up to this point have been committed. + * + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * + * bulkWriter.create(documentRef, {foo: 'bar'}); + * bulkWriter.update(documentRef2, {foo: 'bar'}); + * bulkWriter.delete(documentRef3); + * await flush().then(() => { + * console.log('Executed all writes'); + * }); + * ``` + */ + flush() { + this._verifyNotClosed(); + this._scheduleCurrentBatch(/* flush= */ true); + // Mark the most recent operation as flushed to ensure that the batch + // containing it will be sent once it's popped from the buffer. + if (this._bufferedOperations.length > 0) { + this._bufferedOperations[this._bufferedOperations.length - 1].operation.markFlushed(); + } + return this._lastOp; + } + /** + * Commits all enqueued writes and marks the BulkWriter instance as closed. + * + * After calling `close()`, calling any method will throw an error. Any + * retries scheduled as part of an `onWriteError()` handler will be run + * before the `close()` promise resolves. + * + * Returns a Promise that resolves when there are no more pending writes. The + * Promise will never be rejected. Calling this method will send all requests. + * The promise resolves immediately if there are no pending writes. + * + * @return {Promise} A promise that resolves when all enqueued writes + * up to this point have been committed. + * + * @example + * ``` + * let bulkWriter = firestore.bulkWriter(); + * + * bulkWriter.create(documentRef, {foo: 'bar'}); + * bulkWriter.update(documentRef2, {foo: 'bar'}); + * bulkWriter.delete(documentRef3); + * await close().then(() => { + * console.log('Executed all writes'); + * }); + * ``` + */ + close() { + if (!this._closePromise) { + this._closePromise = this.flush(); + this.firestore._decrementBulkWritersCount(); + } + return this._closePromise; + } + /** + * Throws an error if the BulkWriter instance has been closed. + * @private + * @internal + */ + _verifyNotClosed() { + if (this._closePromise) { + throw new Error('BulkWriter has already been closed.'); + } + } + /** + * Sends the current batch and resets `this._bulkCommitBatch`. + * + * @param flush If provided, keeps re-sending operations until no more + * operations are enqueued. This allows retries to resolve as part of a + * `flush()` or `close()` call. + * @private + * @internal + */ + _scheduleCurrentBatch(flush = false) { + if (this._bulkCommitBatch._opCount === 0) + return; + const pendingBatch = this._bulkCommitBatch; + this._bulkCommitBatch = new BulkCommitBatch(this.firestore, this._maxBatchSize); + // Use the write with the longest backoff duration when determining backoff. + const highestBackoffDuration = pendingBatch.pendingOps.reduce((prev, cur) => (prev.backoffDuration > cur.backoffDuration ? prev : cur)).backoffDuration; + const backoffMsWithJitter = BulkWriter._applyJitter(highestBackoffDuration); + const delayedExecution = new util_1.Deferred(); + if (backoffMsWithJitter > 0) { + (0, backoff_1.delayExecution)(() => delayedExecution.resolve(), backoffMsWithJitter); + } + else { + delayedExecution.resolve(); + } + delayedExecution.promise.then(() => this._sendBatch(pendingBatch, flush)); + } + /** + * Sends the provided batch once the rate limiter does not require any delay. + * @private + * @internal + */ + async _sendBatch(batch, flush = false) { + const tag = (0, util_1.requestTag)(); + // Send the batch if it is does not require any delay, or schedule another + // attempt after the appropriate timeout. + const underRateLimit = this._rateLimiter.tryMakeRequest(batch._opCount); + if (underRateLimit) { + await batch.bulkCommit({ requestTag: tag }); + if (flush) + this._scheduleCurrentBatch(flush); + } + else { + const delayMs = this._rateLimiter.getNextRequestDelayMs(batch._opCount); + (0, logger_1.logger)('BulkWriter._sendBatch', tag, `Backing off for ${delayMs} seconds`); + (0, backoff_1.delayExecution)(() => this._sendBatch(batch, flush), delayMs); + } + } + /** + * Adds a 30% jitter to the provided backoff. + * + * @private + * @internal + */ + static _applyJitter(backoffMs) { + if (backoffMs === 0) + return 0; + // Random value in [-0.3, 0.3]. + const jitter = exports.DEFAULT_JITTER_FACTOR * (Math.random() * 2 - 1); + return Math.min(backoff_1.DEFAULT_BACKOFF_MAX_DELAY_MS, backoffMs + jitter * backoffMs); + } + /** + * Schedules and runs the provided operation on the next available batch. + * @private + * @internal + */ + _enqueue(ref, type, enqueueOnBatchCallback) { + const bulkWriterOp = new BulkWriterOperation(ref, type, this._sendFn.bind(this, enqueueOnBatchCallback), this._errorFn.bind(this), this._successFn.bind(this)); + // Swallow the error if the developer has set an error listener. This + // prevents UnhandledPromiseRejections from being thrown if a floating + // BulkWriter operation promise fails when an error handler is specified. + // + // This is done here in order to chain the caught promise onto `lastOp`, + // which ensures that flush() resolves after the operation promise. + const userPromise = bulkWriterOp.promise.catch(err => { + if (!this._errorHandlerSet) { + throw err; + } + else { + return bulkWriterOp.promise; + } + }); + // Advance the `_lastOp` pointer. This ensures that `_lastOp` only resolves + // when both the previous and the current write resolve. + this._lastOp = this._lastOp.then(() => (0, util_1.silencePromise)(userPromise)); + // Schedule the operation if the BulkWriter has fewer than the maximum + // number of allowed pending operations, or add the operation to the + // buffer. + if (this._pendingOpsCount < this._maxPendingOpCount) { + this._pendingOpsCount++; + this._sendFn(enqueueOnBatchCallback, bulkWriterOp); + } + else { + this._bufferedOperations.push(new BufferedOperation(bulkWriterOp, () => { + this._pendingOpsCount++; + this._sendFn(enqueueOnBatchCallback, bulkWriterOp); + })); + } + // Chain the BulkWriter operation promise with the buffer processing logic + // in order to ensure that it runs and that subsequent operations are + // enqueued before the next batch is scheduled in `_sendBatch()`. + return userPromise + .then(res => { + this._pendingOpsCount--; + this._processBufferedOps(); + return res; + }) + .catch(err => { + this._pendingOpsCount--; + this._processBufferedOps(); + throw err; + }); + } + /** + * Manages the pending operation counter and schedules the next BulkWriter + * operation if we're under the maximum limit. + * @private + * @internal + */ + _processBufferedOps() { + if (this._pendingOpsCount < this._maxPendingOpCount && + this._bufferedOperations.length > 0) { + const nextOp = this._bufferedOperations.shift(); + nextOp.sendFn(); + } + } + /** + * Schedules the provided operations on current BulkCommitBatch. + * Sends the BulkCommitBatch if it reaches maximum capacity. + * + * @private + * @internal + */ + _sendFn(enqueueOnBatchCallback, op) { + // A backoff duration greater than 0 implies that this batch is a retry. + // Retried writes are sent with a batch size of 10 in order to guarantee + // that the batch is under the 10MiB limit. + if (op.backoffDuration > 0) { + if (this._bulkCommitBatch.pendingOps.length >= exports.RETRY_MAX_BATCH_SIZE) { + this._scheduleCurrentBatch(/* flush= */ false); + } + this._bulkCommitBatch.setMaxBatchSize(exports.RETRY_MAX_BATCH_SIZE); + } + if (this._bulkCommitBatch.has(op.ref)) { + // Create a new batch since the backend doesn't support batches with two + // writes to the same document. + this._scheduleCurrentBatch(); + } + enqueueOnBatchCallback(this._bulkCommitBatch); + this._bulkCommitBatch.processLastOperation(op); + if (this._bulkCommitBatch._opCount === this._bulkCommitBatch.maxBatchSize) { + this._scheduleCurrentBatch(); + } + else if (op.flushed) { + // If flush() was called before this operation was enqueued into a batch, + // we still need to schedule it. + this._scheduleCurrentBatch(/* flush= */ true); + } + } +} +exports.BulkWriter = BulkWriter; +/** + * Validates the use of 'value' as BulkWriterOptions. + * + * @private + * @internal + * @param value The BulkWriterOptions object to validate. + * @throws if the input is not a valid BulkWriterOptions object. + */ +function validateBulkWriterOptions(value) { + if ((0, validate_1.validateOptional)(value, { optional: true })) { + return; + } + const argName = 'options'; + if (!(0, util_1.isObject)(value)) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(argName, 'bulkWriter() options argument')} Input is not an object.`); + } + const options = value; + if (options.throttling === undefined || + typeof options.throttling === 'boolean') { + return; + } + if (options.throttling.initialOpsPerSecond !== undefined) { + (0, validate_1.validateInteger)('initialOpsPerSecond', options.throttling.initialOpsPerSecond, { + minValue: 1, + }); + } + if (options.throttling.maxOpsPerSecond !== undefined) { + (0, validate_1.validateInteger)('maxOpsPerSecond', options.throttling.maxOpsPerSecond, { + minValue: 1, + }); + if (options.throttling.initialOpsPerSecond !== undefined && + options.throttling.initialOpsPerSecond > + options.throttling.maxOpsPerSecond) { + throw new Error(`${(0, validate_1.invalidArgumentMessage)(argName, 'bulkWriter() options argument')} "maxOpsPerSecond" cannot be less than "initialOpsPerSecond".`); + } + } +} +//# sourceMappingURL=bulk-writer.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/bundle.d.ts b/node_modules/@google-cloud/firestore/build/src/bundle.d.ts new file mode 100644 index 0000000..3b477fd --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/bundle.d.ts @@ -0,0 +1,24 @@ +import { DocumentSnapshot } from './document'; +import { QuerySnapshot } from './reference/query-snapshot'; +/** + * Builds a Firestore data bundle with results from the given document and query snapshots. + */ +export declare class BundleBuilder { + readonly bundleId: string; + private documents; + private namedQueries; + private latestReadTime; + constructor(bundleId: string); + add(documentSnapshot: DocumentSnapshot): BundleBuilder; + add(queryName: string, querySnapshot: QuerySnapshot): BundleBuilder; + private addBundledDocument; + private addNamedQuery; + /** + * Converts a IBundleElement to a Buffer whose content is the length prefixed JSON representation + * of the element. + * @private + * @internal + */ + private elementToLengthPrefixedBuffer; + build(): Buffer; +} diff --git a/node_modules/@google-cloud/firestore/build/src/bundle.js b/node_modules/@google-cloud/firestore/build/src/bundle.js new file mode 100644 index 0000000..6cb5a30 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/bundle.js @@ -0,0 +1,207 @@ +"use strict"; +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BundleBuilder = void 0; +const document_1 = require("./document"); +const query_snapshot_1 = require("./reference/query-snapshot"); +const timestamp_1 = require("./timestamp"); +const validate_1 = require("./validate"); +const BUNDLE_VERSION = 1; +/** + * Builds a Firestore data bundle with results from the given document and query snapshots. + */ +class BundleBuilder { + constructor(bundleId) { + this.bundleId = bundleId; + // Resulting documents for the bundle, keyed by full document path. + this.documents = new Map(); + // Named queries saved in the bundle, keyed by query name. + this.namedQueries = new Map(); + // The latest read time among all bundled documents and queries. + this.latestReadTime = new timestamp_1.Timestamp(0, 0); + } + /** + * Adds a Firestore document snapshot or query snapshot to the bundle. + * Both the documents data and the query read time will be included in the bundle. + * + * @param {DocumentSnapshot | string} documentOrName A document snapshot to add or a name of a query. + * @param {Query=} querySnapshot A query snapshot to add to the bundle, if provided. + * @returns {BundleBuilder} This instance. + * + * @example + * ``` + * const bundle = firestore.bundle('data-bundle'); + * const docSnapshot = await firestore.doc('abc/123').get(); + * const querySnapshot = await firestore.collection('coll').get(); + * + * const bundleBuffer = bundle.add(docSnapshot) // Add a document + * .add('coll-query', querySnapshot) // Add a named query. + * .build() + * // Save `bundleBuffer` to CDN or stream it to clients. + * ``` + */ + add(documentOrName, querySnapshot) { + // eslint-disable-next-line prefer-rest-params + (0, validate_1.validateMinNumberOfArguments)('BundleBuilder.add', arguments, 1); + // eslint-disable-next-line prefer-rest-params + (0, validate_1.validateMaxNumberOfArguments)('BundleBuilder.add', arguments, 2); + if (arguments.length === 1) { + validateDocumentSnapshot('documentOrName', documentOrName); + this.addBundledDocument(documentOrName); + } + else { + (0, validate_1.validateString)('documentOrName', documentOrName); + validateQuerySnapshot('querySnapshot', querySnapshot); + this.addNamedQuery(documentOrName, querySnapshot); + } + return this; + } + addBundledDocument(snap, queryName) { + const originalDocument = this.documents.get(snap.ref.path); + const originalQueries = originalDocument === null || originalDocument === void 0 ? void 0 : originalDocument.metadata.queries; + // Update with document built from `snap` because it is newer. + if (!originalDocument || + timestamp_1.Timestamp.fromProto(originalDocument.metadata.readTime) < snap.readTime) { + const docProto = snap.toDocumentProto(); + this.documents.set(snap.ref.path, { + document: snap.exists ? docProto : undefined, + metadata: { + name: docProto.name, + readTime: snap.readTime.toProto().timestampValue, + exists: snap.exists, + }, + }); + } + // Update `queries` to include both original and `queryName`. + const newDocument = this.documents.get(snap.ref.path); + newDocument.metadata.queries = originalQueries || []; + if (queryName) { + newDocument.metadata.queries.push(queryName); + } + if (snap.readTime > this.latestReadTime) { + this.latestReadTime = snap.readTime; + } + } + addNamedQuery(name, querySnap) { + if (this.namedQueries.has(name)) { + throw new Error(`Query name conflict: ${name} has already been added.`); + } + this.namedQueries.set(name, { + name, + bundledQuery: querySnap.query._toBundledQuery(), + readTime: querySnap.readTime.toProto().timestampValue, + }); + for (const snap of querySnap.docs) { + this.addBundledDocument(snap, name); + } + if (querySnap.readTime > this.latestReadTime) { + this.latestReadTime = querySnap.readTime; + } + } + /** + * Converts a IBundleElement to a Buffer whose content is the length prefixed JSON representation + * of the element. + * @private + * @internal + */ + elementToLengthPrefixedBuffer(bundleElement) { + // Convert to a valid proto message object then take its JSON representation. + // This take cares of stuff like converting internal byte array fields + // to Base64 encodings. + // We lazy-load the Proto file to reduce cold-start times. + const message = require('../protos/firestore_v1_proto_api') + .firestore.BundleElement.fromObject(bundleElement) + .toJSON(); + const buffer = Buffer.from(JSON.stringify(message), 'utf-8'); + const lengthBuffer = Buffer.from(buffer.length.toString()); + return Buffer.concat([lengthBuffer, buffer]); + } + build() { + let bundleBuffer = Buffer.alloc(0); + for (const namedQuery of this.namedQueries.values()) { + bundleBuffer = Buffer.concat([ + bundleBuffer, + this.elementToLengthPrefixedBuffer({ namedQuery }), + ]); + } + for (const bundledDocument of this.documents.values()) { + const documentMetadata = bundledDocument.metadata; + bundleBuffer = Buffer.concat([ + bundleBuffer, + this.elementToLengthPrefixedBuffer({ documentMetadata }), + ]); + // Write to the bundle if document exists. + const document = bundledDocument.document; + if (document) { + bundleBuffer = Buffer.concat([ + bundleBuffer, + this.elementToLengthPrefixedBuffer({ document }), + ]); + } + } + const metadata = { + id: this.bundleId, + createTime: this.latestReadTime.toProto().timestampValue, + version: BUNDLE_VERSION, + totalDocuments: this.documents.size, + totalBytes: bundleBuffer.length, + }; + // Prepends the metadata element to the bundleBuffer: `bundleBuffer` is the second argument to `Buffer.concat`. + bundleBuffer = Buffer.concat([ + this.elementToLengthPrefixedBuffer({ metadata }), + bundleBuffer, + ]); + return bundleBuffer; + } +} +exports.BundleBuilder = BundleBuilder; +/** + * Convenient class to hold both the metadata and the actual content of a document to be bundled. + * @private + * @internal + */ +class BundledDocument { + constructor(metadata, document) { + this.metadata = metadata; + this.document = document; + } +} +/** + * Validates that 'value' is DocumentSnapshot. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + */ +function validateDocumentSnapshot(arg, value) { + if (!(value instanceof document_1.DocumentSnapshot)) { + throw new Error((0, validate_1.invalidArgumentMessage)(arg, 'DocumentSnapshot')); + } +} +/** + * Validates that 'value' is QuerySnapshot. + * + * @private + * @internal + * @param arg The argument name or argument index (for varargs methods). + * @param value The input to validate. + */ +function validateQuerySnapshot(arg, value) { + if (!(value instanceof query_snapshot_1.QuerySnapshot)) { + throw new Error((0, validate_1.invalidArgumentMessage)(arg, 'QuerySnapshot')); + } +} +//# sourceMappingURL=bundle.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/collection-group.d.ts b/node_modules/@google-cloud/firestore/build/src/collection-group.d.ts new file mode 100644 index 0000000..d6e4890 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/collection-group.d.ts @@ -0,0 +1,90 @@ +import * as firestore from '@google-cloud/firestore'; +import { QueryPartition } from './query-partition'; +import { Query } from './reference/query'; +import { Firestore } from './index'; +/** + * A `CollectionGroup` refers to all documents that are contained in a + * collection or subcollection with a specific collection ID. + * + * @class CollectionGroup + */ +export declare class CollectionGroup extends Query implements firestore.CollectionGroup { + /** @private */ + constructor(firestore: Firestore, collectionId: string, converter: firestore.FirestoreDataConverter | undefined); + /** + * Partitions a query by returning partition cursors that can be used to run + * the query in parallel. The returned cursors are split points that can be + * used as starting and end points for individual query invocations. + * + * @example + * ``` + * const query = firestore.collectionGroup('collectionId'); + * for await (const partition of query.getPartitions(42)) { + * const partitionedQuery = partition.toQuery(); + * const querySnapshot = await partitionedQuery.get(); + * console.log(`Partition contained ${querySnapshot.length} documents`); + * } + * + * ``` + * @param {number} desiredPartitionCount The desired maximum number of + * partition points. The number must be strictly positive. The actual number + * of partitions returned may be fewer. + * @return {AsyncIterable} An AsyncIterable of + * `QueryPartition`s. + */ + getPartitions(desiredPartitionCount: number): AsyncIterable>; + /** + * Applies a custom data converter to this `CollectionGroup`, allowing you + * to use your own custom model objects with Firestore. When you call get() + * on the returned `CollectionGroup`, the provided converter will convert + * between Firestore data of type `NewDbModelType` and your custom type + * `NewAppModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * Passing in `null` as the converter parameter removes the current + * converter. + * + * @example + * ``` + * class Post { + * constructor(readonly title: string, readonly author: string) {} + * + * toString(): string { + * return this.title + ', by ' + this.author; + * } + * } + * + * const postConverter = { + * toFirestore(post: Post): FirebaseFirestore.DocumentData { + * return {title: post.title, author: post.author}; + * }, + * fromFirestore( + * snapshot: FirebaseFirestore.QueryDocumentSnapshot + * ): Post { + * const data = snapshot.data(); + * return new Post(data.title, data.author); + * } + * }; + * + * const querySnapshot = await Firestore() + * .collectionGroup('posts') + * .withConverter(postConverter) + * .get(); + * for (const doc of querySnapshot.docs) { + * const post = doc.data(); + * post.title; // string + * post.toString(); // Should be defined + * post.someNonExistentProperty; // TS error + * } + * + * ``` + * @param {FirestoreDataConverter | null} converter Converts objects to and + * from Firestore. Passing in `null` removes the current converter. + * @return {CollectionGroup} A `CollectionGroup` that uses the provided + * converter. + */ + withConverter(converter: null): CollectionGroup; + withConverter(converter: firestore.FirestoreDataConverter): CollectionGroup; +} diff --git a/node_modules/@google-cloud/firestore/build/src/collection-group.js b/node_modules/@google-cloud/firestore/build/src/collection-group.js new file mode 100644 index 0000000..3b322da --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/collection-group.js @@ -0,0 +1,99 @@ +"use strict"; +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CollectionGroup = void 0; +const query_partition_1 = require("./query-partition"); +const util_1 = require("./util"); +const logger_1 = require("./logger"); +const query_1 = require("./reference/query"); +const query_options_1 = require("./reference/query-options"); +const path_1 = require("./path"); +const validate_1 = require("./validate"); +const types_1 = require("./types"); +const order_1 = require("./order"); +const trace_util_1 = require("./telemetry/trace-util"); +/** + * A `CollectionGroup` refers to all documents that are contained in a + * collection or subcollection with a specific collection ID. + * + * @class CollectionGroup + */ +class CollectionGroup extends query_1.Query { + /** @private */ + constructor(firestore, collectionId, converter) { + super(firestore, query_options_1.QueryOptions.forCollectionGroupQuery(collectionId, converter)); + } + /** + * Partitions a query by returning partition cursors that can be used to run + * the query in parallel. The returned cursors are split points that can be + * used as starting and end points for individual query invocations. + * + * @example + * ``` + * const query = firestore.collectionGroup('collectionId'); + * for await (const partition of query.getPartitions(42)) { + * const partitionedQuery = partition.toQuery(); + * const querySnapshot = await partitionedQuery.get(); + * console.log(`Partition contained ${querySnapshot.length} documents`); + * } + * + * ``` + * @param {number} desiredPartitionCount The desired maximum number of + * partition points. The number must be strictly positive. The actual number + * of partitions returned may be fewer. + * @return {AsyncIterable} An AsyncIterable of + * `QueryPartition`s. + */ + async *getPartitions(desiredPartitionCount) { + const partitions = []; + await this._firestore._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_PARTITION_QUERY, async () => { + var _a; + (0, validate_1.validateInteger)('desiredPartitionCount', desiredPartitionCount, { + minValue: 1, + }); + const tag = (0, util_1.requestTag)(); + await this.firestore.initializeIfNeeded(tag); + if (desiredPartitionCount > 1) { + // Partition queries require explicit ordering by __name__. + const queryWithDefaultOrder = this.orderBy(path_1.FieldPath.documentId()); + const request = queryWithDefaultOrder.toProto(); + // Since we are always returning an extra partition (with an empty endBefore + // cursor), we reduce the desired partition count by one. + request.partitionCount = desiredPartitionCount - 1; + const stream = await this.firestore.requestStream('partitionQueryStream', + /* bidirectional= */ false, request, tag); + stream.resume(); + for await (const currentCursor of stream) { + partitions.push((_a = currentCursor.values) !== null && _a !== void 0 ? _a : []); + } + } + (0, logger_1.logger)('Firestore.getPartitions', tag, 'Received %d partitions', partitions.length); + // Sort the partitions as they may not be ordered if responses are paged. + partitions.sort((l, r) => (0, order_1.compareArrays)(l, r)); + }); + for (let i = 0; i < partitions.length; ++i) { + yield new query_partition_1.QueryPartition(this._firestore, this._queryOptions.collectionId, this._queryOptions.converter, i > 0 ? partitions[i - 1] : undefined, partitions[i]); + } + // Return the extra partition with the empty cursor. + yield new query_partition_1.QueryPartition(this._firestore, this._queryOptions.collectionId, this._queryOptions.converter, partitions.pop(), undefined); + } + withConverter(converter) { + return new CollectionGroup(this.firestore, this._queryOptions.collectionId, converter !== null && converter !== void 0 ? converter : (0, types_1.defaultConverter)()); + } +} +exports.CollectionGroup = CollectionGroup; +//# sourceMappingURL=collection-group.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/convert.d.ts b/node_modules/@google-cloud/firestore/build/src/convert.d.ts new file mode 100644 index 0000000..83278b3 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/convert.d.ts @@ -0,0 +1,81 @@ +/*! + * Copyright 2019 Google Inc. 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. + */ +import { google } from '../protos/firestore_v1_proto_api'; +import { ApiMapValue, ProtobufJsValue } from './types'; +import api = google.firestore.v1; +/*! + * @module firestore/convert + * @private + * @internal + * + * This module contains utility functions to convert + * `firestore.v1.Documents` from Proto3 JSON to their equivalent + * representation in Protobuf JS. Protobuf JS is the only encoding supported by + * this client, and dependencies that use Proto3 JSON (such as the Google Cloud + * Functions SDK) are supported through this conversion and its usage in + * {@see Firestore#snapshot_}. + */ +/** + * Converts an ISO 8601 or google.protobuf.Timestamp proto into Protobuf JS. + * + * @private + * @internal + * @param timestampValue The value to convert. + * @param argumentName The argument name to use in the error message if the + * conversion fails. If omitted, 'timestampValue' is used. + * @return The value as expected by Protobuf JS or undefined if no input was + * provided. + */ +export declare function timestampFromJson(timestampValue?: string | google.protobuf.ITimestamp, argumentName?: string): google.protobuf.ITimestamp | undefined; +/** + * Detects 'valueType' from a Proto3 JSON `firestore.v1.Value` proto. + * + * @private + * @internal + * @param proto The `firestore.v1.Value` proto. + * @return The string value for 'valueType'. + */ +export declare function detectValueType(proto: ProtobufJsValue): string; +/** + * Detects the value kind from a Proto3 JSON `google.protobuf.Value` proto. + * + * @private + * @internal + * @param proto The `firestore.v1.Value` proto. + * @return The string value for 'valueType'. + */ +export declare function detectGoogleProtobufValueType(proto: google.protobuf.IValue): string; +/** + * Converts a `firestore.v1.Value` in Proto3 JSON encoding into the + * Protobuf JS format expected by this client. + * + * @private + * @internal + * @param fieldValue The `firestore.v1.Value` in Proto3 JSON format. + * @return The `firestore.v1.Value` in Protobuf JS format. + */ +export declare function valueFromJson(fieldValue: api.IValue): api.IValue; +/** + * Converts a map of IValues in Proto3 JSON encoding into the Protobuf JS format + * expected by this client. This conversion creates a copy of the underlying + * fields. + * + * @private + * @internal + * @param document An object with IValues in Proto3 JSON format. + * @return The object in Protobuf JS format. + */ +export declare function fieldsFromJson(document: ApiMapValue): ApiMapValue; diff --git a/node_modules/@google-cloud/firestore/build/src/convert.js b/node_modules/@google-cloud/firestore/build/src/convert.js new file mode 100644 index 0000000..fef8982 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/convert.js @@ -0,0 +1,267 @@ +"use strict"; +/*! + * Copyright 2019 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.timestampFromJson = timestampFromJson; +exports.detectValueType = detectValueType; +exports.detectGoogleProtobufValueType = detectGoogleProtobufValueType; +exports.valueFromJson = valueFromJson; +exports.fieldsFromJson = fieldsFromJson; +const validate_1 = require("./validate"); +const map_type_1 = require("./map-type"); +/*! + * @module firestore/convert + * @private + * @internal + * + * This module contains utility functions to convert + * `firestore.v1.Documents` from Proto3 JSON to their equivalent + * representation in Protobuf JS. Protobuf JS is the only encoding supported by + * this client, and dependencies that use Proto3 JSON (such as the Google Cloud + * Functions SDK) are supported through this conversion and its usage in + * {@see Firestore#snapshot_}. + */ +/** + * Converts an ISO 8601 or google.protobuf.Timestamp proto into Protobuf JS. + * + * @private + * @internal + * @param timestampValue The value to convert. + * @param argumentName The argument name to use in the error message if the + * conversion fails. If omitted, 'timestampValue' is used. + * @return The value as expected by Protobuf JS or undefined if no input was + * provided. + */ +function timestampFromJson(timestampValue, argumentName) { + let timestampProto = {}; + if (typeof timestampValue === 'string') { + const date = new Date(timestampValue); + const seconds = Math.floor(date.getTime() / 1000); + let nanos = 0; + if (timestampValue.length > 20) { + const nanoString = timestampValue.substring(20, timestampValue.length - 1); + const trailingZeroes = 9 - nanoString.length; + nanos = Number(nanoString) * Math.pow(10, trailingZeroes); + } + if (isNaN(seconds) || isNaN(nanos)) { + argumentName = argumentName || 'timestampValue'; + throw new Error(`Specify a valid ISO 8601 timestamp for "${argumentName}".`); + } + timestampProto = { + seconds: seconds || undefined, + nanos: nanos || undefined, + }; + } + else if (timestampValue !== undefined) { + (0, validate_1.validateObject)('timestampValue', timestampValue); + timestampProto = { + seconds: timestampValue.seconds || undefined, + nanos: timestampValue.nanos || undefined, + }; + } + return timestampProto; +} +/** + * Converts a Proto3 JSON 'bytesValue' field into Protobuf JS. + * + * @private + * @internal + * @param bytesValue The value to convert. + * @return The value as expected by Protobuf JS. + */ +function bytesFromJson(bytesValue) { + if (typeof bytesValue === 'string') { + return Buffer.from(bytesValue, 'base64'); + } + else { + return bytesValue; + } +} +/** + * Detects 'valueType' from a Proto3 JSON `firestore.v1.Value` proto. + * + * @private + * @internal + * @param proto The `firestore.v1.Value` proto. + * @return The string value for 'valueType'. + */ +function detectValueType(proto) { + var _a; + let valueType; + if (proto.valueType) { + valueType = proto.valueType; + } + else { + const detectedValues = []; + if (proto.stringValue !== undefined) { + detectedValues.push('stringValue'); + } + if (proto.booleanValue !== undefined) { + detectedValues.push('booleanValue'); + } + if (proto.integerValue !== undefined) { + detectedValues.push('integerValue'); + } + if (proto.doubleValue !== undefined) { + detectedValues.push('doubleValue'); + } + if (proto.timestampValue !== undefined) { + detectedValues.push('timestampValue'); + } + if (proto.referenceValue !== undefined) { + detectedValues.push('referenceValue'); + } + if (proto.arrayValue !== undefined) { + detectedValues.push('arrayValue'); + } + if (proto.nullValue !== undefined) { + detectedValues.push('nullValue'); + } + if (proto.mapValue !== undefined) { + detectedValues.push('mapValue'); + } + if (proto.geoPointValue !== undefined) { + detectedValues.push('geoPointValue'); + } + if (proto.bytesValue !== undefined) { + detectedValues.push('bytesValue'); + } + if (detectedValues.length !== 1) { + throw new Error(`Unable to infer type value from '${JSON.stringify(proto)}'.`); + } + valueType = detectedValues[0]; + } + // Special handling of mapValues used to represent other data types + if (valueType === 'mapValue') { + const fields = (_a = proto.mapValue) === null || _a === void 0 ? void 0 : _a.fields; + if (fields) { + const props = Object.keys(fields); + if (props.indexOf(map_type_1.RESERVED_MAP_KEY) !== -1 && + detectValueType(fields[map_type_1.RESERVED_MAP_KEY]) === 'stringValue' && + fields[map_type_1.RESERVED_MAP_KEY].stringValue === map_type_1.RESERVED_MAP_KEY_VECTOR_VALUE) { + valueType = 'vectorValue'; + } + } + } + return valueType; +} +/** + * Detects the value kind from a Proto3 JSON `google.protobuf.Value` proto. + * + * @private + * @internal + * @param proto The `firestore.v1.Value` proto. + * @return The string value for 'valueType'. + */ +function detectGoogleProtobufValueType(proto) { + const detectedValues = []; + if (proto.nullValue !== undefined) { + detectedValues.push('nullValue'); + } + if (proto.numberValue !== undefined) { + detectedValues.push('numberValue'); + } + if (proto.stringValue !== undefined) { + detectedValues.push('stringValue'); + } + if (proto.boolValue !== undefined) { + detectedValues.push('boolValue'); + } + if (proto.structValue !== undefined) { + detectedValues.push('structValue'); + } + if (proto.listValue !== undefined) { + detectedValues.push('listValue'); + } + if (detectedValues.length !== 1) { + throw new Error(`Unable to infer type value from '${JSON.stringify(proto)}'.`); + } + return detectedValues[0]; +} +/** + * Converts a `firestore.v1.Value` in Proto3 JSON encoding into the + * Protobuf JS format expected by this client. + * + * @private + * @internal + * @param fieldValue The `firestore.v1.Value` in Proto3 JSON format. + * @return The `firestore.v1.Value` in Protobuf JS format. + */ +function valueFromJson(fieldValue) { + const valueType = detectValueType(fieldValue); + switch (valueType) { + case 'timestampValue': + return { + timestampValue: timestampFromJson(fieldValue.timestampValue), + }; + case 'bytesValue': + return { + bytesValue: bytesFromJson(fieldValue.bytesValue), + }; + case 'doubleValue': + return { + doubleValue: Number(fieldValue.doubleValue), + }; + case 'arrayValue': { + const arrayValue = []; + if (Array.isArray(fieldValue.arrayValue.values)) { + for (const value of fieldValue.arrayValue.values) { + arrayValue.push(valueFromJson(value)); + } + } + return { + arrayValue: { + values: arrayValue, + }, + }; + } + case 'mapValue': + case 'vectorValue': { + const mapValue = {}; + const fields = fieldValue.mapValue.fields; + if (fields) { + for (const prop of Object.keys(fields)) { + mapValue[prop] = valueFromJson(fieldValue.mapValue.fields[prop]); + } + } + return { + mapValue: { + fields: mapValue, + }, + }; + } + default: + return fieldValue; + } +} +/** + * Converts a map of IValues in Proto3 JSON encoding into the Protobuf JS format + * expected by this client. This conversion creates a copy of the underlying + * fields. + * + * @private + * @internal + * @param document An object with IValues in Proto3 JSON format. + * @return The object in Protobuf JS format. + */ +function fieldsFromJson(document) { + const result = {}; + for (const prop of Object.keys(document)) { + result[prop] = valueFromJson(document[prop]); + } + return result; +} +//# sourceMappingURL=convert.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/document-change.d.ts b/node_modules/@google-cloud/firestore/build/src/document-change.d.ts new file mode 100644 index 0000000..d857b68 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/document-change.d.ts @@ -0,0 +1,155 @@ +/*! + * Copyright 2018 Google Inc. 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. + */ +import * as firestore from '@google-cloud/firestore'; +import { QueryDocumentSnapshot } from './document'; +export type DocumentChangeType = 'added' | 'removed' | 'modified'; +/** + * A DocumentChange represents a change to the documents matching a query. + * It contains the document affected and the type of change that occurred. + * + * @class DocumentChange + */ +export declare class DocumentChange implements firestore.DocumentChange { + private readonly _type; + private readonly _document; + private readonly _oldIndex; + private readonly _newIndex; + /** + * @private + * + * @param {string} type 'added' | 'removed' | 'modified'. + * @param {QueryDocumentSnapshot} document The document. + * @param {number} oldIndex The index in the documents array prior to this + * change. + * @param {number} newIndex The index in the documents array after this + * change. + */ + constructor(type: DocumentChangeType, document: QueryDocumentSnapshot, oldIndex: number, newIndex: number); + /** + * The type of change ('added', 'modified', or 'removed'). + * + * @type {string} + * @name DocumentChange#type + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * let docsArray = []; + * + * let unsubscribe = query.onSnapshot(querySnapshot => { + * for (let change of querySnapshot.docChanges) { + * console.log(`Type of change is ${change.type}`); + * } + * }); + * + * // Remove this listener. + * unsubscribe(); + * ``` + */ + get type(): DocumentChangeType; + /** + * The document affected by this change. + * + * @type {QueryDocumentSnapshot} + * @name DocumentChange#doc + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * let unsubscribe = query.onSnapshot(querySnapshot => { + * for (let change of querySnapshot.docChanges) { + * console.log(change.doc.data()); + * } + * }); + * + * // Remove this listener. + * unsubscribe(); + * ``` + */ + get doc(): QueryDocumentSnapshot; + /** + * The index of the changed document in the result set immediately prior to + * this DocumentChange (i.e. supposing that all prior DocumentChange objects + * have been applied). Is -1 for 'added' events. + * + * @type {number} + * @name DocumentChange#oldIndex + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * let docsArray = []; + * + * let unsubscribe = query.onSnapshot(querySnapshot => { + * for (let change of querySnapshot.docChanges) { + * if (change.oldIndex !== -1) { + * docsArray.splice(change.oldIndex, 1); + * } + * if (change.newIndex !== -1) { + * docsArray.splice(change.newIndex, 0, change.doc); + * } + * } + * }); + * + * // Remove this listener. + * unsubscribe(); + * ``` + */ + get oldIndex(): number; + /** + * The index of the changed document in the result set immediately after + * this DocumentChange (i.e. supposing that all prior DocumentChange + * objects and the current DocumentChange object have been applied). + * Is -1 for 'removed' events. + * + * @type {number} + * @name DocumentChange#newIndex + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * let docsArray = []; + * + * let unsubscribe = query.onSnapshot(querySnapshot => { + * for (let change of querySnapshot.docChanges) { + * if (change.oldIndex !== -1) { + * docsArray.splice(change.oldIndex, 1); + * } + * if (change.newIndex !== -1) { + * docsArray.splice(change.newIndex, 0, change.doc); + * } + * } + * }); + * + * // Remove this listener. + * unsubscribe(); + * ``` + */ + get newIndex(): number; + /** + * Returns true if the data in this `DocumentChange` is equal to the provided + * value. + * + * @param {*} other The value to compare against. + * @return true if this `DocumentChange` is equal to the provided value. + */ + isEqual(other: firestore.DocumentChange): boolean; +} diff --git a/node_modules/@google-cloud/firestore/build/src/document-change.js b/node_modules/@google-cloud/firestore/build/src/document-change.js new file mode 100644 index 0000000..c970c46 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/document-change.js @@ -0,0 +1,175 @@ +"use strict"; +/*! + * Copyright 2018 Google Inc. 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DocumentChange = void 0; +/** + * A DocumentChange represents a change to the documents matching a query. + * It contains the document affected and the type of change that occurred. + * + * @class DocumentChange + */ +class DocumentChange { + /** + * @private + * + * @param {string} type 'added' | 'removed' | 'modified'. + * @param {QueryDocumentSnapshot} document The document. + * @param {number} oldIndex The index in the documents array prior to this + * change. + * @param {number} newIndex The index in the documents array after this + * change. + */ + constructor(type, document, oldIndex, newIndex) { + this._type = type; + this._document = document; + this._oldIndex = oldIndex; + this._newIndex = newIndex; + } + /** + * The type of change ('added', 'modified', or 'removed'). + * + * @type {string} + * @name DocumentChange#type + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * let docsArray = []; + * + * let unsubscribe = query.onSnapshot(querySnapshot => { + * for (let change of querySnapshot.docChanges) { + * console.log(`Type of change is ${change.type}`); + * } + * }); + * + * // Remove this listener. + * unsubscribe(); + * ``` + */ + get type() { + return this._type; + } + /** + * The document affected by this change. + * + * @type {QueryDocumentSnapshot} + * @name DocumentChange#doc + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * + * let unsubscribe = query.onSnapshot(querySnapshot => { + * for (let change of querySnapshot.docChanges) { + * console.log(change.doc.data()); + * } + * }); + * + * // Remove this listener. + * unsubscribe(); + * ``` + */ + get doc() { + return this._document; + } + /** + * The index of the changed document in the result set immediately prior to + * this DocumentChange (i.e. supposing that all prior DocumentChange objects + * have been applied). Is -1 for 'added' events. + * + * @type {number} + * @name DocumentChange#oldIndex + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * let docsArray = []; + * + * let unsubscribe = query.onSnapshot(querySnapshot => { + * for (let change of querySnapshot.docChanges) { + * if (change.oldIndex !== -1) { + * docsArray.splice(change.oldIndex, 1); + * } + * if (change.newIndex !== -1) { + * docsArray.splice(change.newIndex, 0, change.doc); + * } + * } + * }); + * + * // Remove this listener. + * unsubscribe(); + * ``` + */ + get oldIndex() { + return this._oldIndex; + } + /** + * The index of the changed document in the result set immediately after + * this DocumentChange (i.e. supposing that all prior DocumentChange + * objects and the current DocumentChange object have been applied). + * Is -1 for 'removed' events. + * + * @type {number} + * @name DocumentChange#newIndex + * @readonly + * + * @example + * ``` + * let query = firestore.collection('col').where('foo', '==', 'bar'); + * let docsArray = []; + * + * let unsubscribe = query.onSnapshot(querySnapshot => { + * for (let change of querySnapshot.docChanges) { + * if (change.oldIndex !== -1) { + * docsArray.splice(change.oldIndex, 1); + * } + * if (change.newIndex !== -1) { + * docsArray.splice(change.newIndex, 0, change.doc); + * } + * } + * }); + * + * // Remove this listener. + * unsubscribe(); + * ``` + */ + get newIndex() { + return this._newIndex; + } + /** + * Returns true if the data in this `DocumentChange` is equal to the provided + * value. + * + * @param {*} other The value to compare against. + * @return true if this `DocumentChange` is equal to the provided value. + */ + isEqual(other) { + if (this === other) { + return true; + } + return (other instanceof DocumentChange && + this._type === other._type && + this._oldIndex === other._oldIndex && + this._newIndex === other._newIndex && + this._document.isEqual(other._document)); + } +} +exports.DocumentChange = DocumentChange; +//# sourceMappingURL=document-change.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/document-reader.d.ts b/node_modules/@google-cloud/firestore/build/src/document-reader.d.ts new file mode 100644 index 0000000..32d8a53 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/document-reader.d.ts @@ -0,0 +1,74 @@ +/*! + * 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. + */ +import { DocumentSnapshot } from './document'; +import { DocumentReference } from './reference/document-reference'; +import { FieldPath } from './path'; +import { google } from '../protos/firestore_v1_proto_api'; +import { Firestore } from './index'; +import { Timestamp } from './timestamp'; +import { DocumentData } from '@google-cloud/firestore'; +import api = google.firestore.v1; +interface BatchGetResponse { + result: Array>; + /** + * The transaction that was started as part of this request. Will only be if + * `DocumentReader.transactionIdOrNewTransaction` was `api.ITransactionOptions`. + */ + transaction?: Uint8Array; +} +/** + * A wrapper around BatchGetDocumentsRequest that retries request upon stream + * failure and returns ordered results. + * + * @private + * @internal + */ +export declare class DocumentReader { + private readonly firestore; + private readonly allDocuments; + private readonly fieldMask?; + private readonly transactionOrReadTime?; + private readonly outstandingDocuments; + private readonly retrievedDocuments; + private retrievedTransactionId?; + /** + * Creates a new DocumentReader that fetches the provided documents (via + * `get()`). + * + * @param firestore The Firestore instance to use. + * @param allDocuments The documents to get. + * @param fieldMask An optional field mask to apply to this read + * @param transactionOrReadTime An optional transaction ID to use for this + * read or options for beginning a new transaction with this read + */ + constructor(firestore: Firestore, allDocuments: ReadonlyArray>, fieldMask?: FieldPath[] | undefined, transactionOrReadTime?: (Uint8Array | api.ITransactionOptions | Timestamp) | undefined); + /** + * Invokes the BatchGetDocuments RPC and returns the results as an array of + * documents. + * + * @param requestTag A unique client-assigned identifier for this request. + */ + get(requestTag: string): Promise>>; + /** + * Invokes the BatchGetDocuments RPC and returns the results with transaction + * metadata. + * + * @param requestTag A unique client-assigned identifier for this request. + */ + _get(requestTag: string): Promise>; + private fetchDocuments; +} +export {}; diff --git a/node_modules/@google-cloud/firestore/build/src/document-reader.js b/node_modules/@google-cloud/firestore/build/src/document-reader.js new file mode 100644 index 0000000..c968d51 --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/document-reader.js @@ -0,0 +1,167 @@ +"use strict"; +/*! + * 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DocumentReader = void 0; +const document_1 = require("./document"); +const util_1 = require("./util"); +const logger_1 = require("./logger"); +const timestamp_1 = require("./timestamp"); +/** + * A wrapper around BatchGetDocumentsRequest that retries request upon stream + * failure and returns ordered results. + * + * @private + * @internal + */ +class DocumentReader { + /** + * Creates a new DocumentReader that fetches the provided documents (via + * `get()`). + * + * @param firestore The Firestore instance to use. + * @param allDocuments The documents to get. + * @param fieldMask An optional field mask to apply to this read + * @param transactionOrReadTime An optional transaction ID to use for this + * read or options for beginning a new transaction with this read + */ + constructor(firestore, allDocuments, fieldMask, transactionOrReadTime) { + this.firestore = firestore; + this.allDocuments = allDocuments; + this.fieldMask = fieldMask; + this.transactionOrReadTime = transactionOrReadTime; + this.outstandingDocuments = new Set(); + this.retrievedDocuments = new Map(); + for (const docRef of this.allDocuments) { + this.outstandingDocuments.add(docRef.formattedName); + } + } + /** + * Invokes the BatchGetDocuments RPC and returns the results as an array of + * documents. + * + * @param requestTag A unique client-assigned identifier for this request. + */ + async get(requestTag) { + const { result } = await this._get(requestTag); + return result; + } + /** + * Invokes the BatchGetDocuments RPC and returns the results with transaction + * metadata. + * + * @param requestTag A unique client-assigned identifier for this request. + */ + async _get(requestTag) { + await this.fetchDocuments(requestTag); + // BatchGetDocuments doesn't preserve document order. We use the request + // order to sort the resulting documents. + const orderedDocuments = []; + for (const docRef of this.allDocuments) { + const document = this.retrievedDocuments.get(docRef.formattedName); + if (document !== undefined) { + // Recreate the DocumentSnapshot with the DocumentReference + // containing the original converter. + const finalDoc = new document_1.DocumentSnapshotBuilder(docRef); + finalDoc.fieldsProto = document._fieldsProto; + finalDoc.readTime = document.readTime; + finalDoc.createTime = document.createTime; + finalDoc.updateTime = document.updateTime; + orderedDocuments.push(finalDoc.build()); + } + else { + throw new Error(`Did not receive document for "${docRef.path}".`); + } + } + return { + result: orderedDocuments, + transaction: this.retrievedTransactionId, + }; + } + async fetchDocuments(requestTag) { + var _a; + if (!this.outstandingDocuments.size) { + return; + } + const request = { + database: this.firestore.formattedName, + documents: Array.from(this.outstandingDocuments), + }; + if (this.transactionOrReadTime instanceof Uint8Array) { + request.transaction = this.transactionOrReadTime; + } + else if (this.transactionOrReadTime instanceof timestamp_1.Timestamp) { + request.readTime = this.transactionOrReadTime.toProto().timestampValue; + } + else if (this.transactionOrReadTime) { + request.newTransaction = this.transactionOrReadTime; + } + if (this.fieldMask) { + const fieldPaths = this.fieldMask.map(fieldPath => fieldPath.formattedName); + request.mask = { fieldPaths }; + } + let resultCount = 0; + try { + const stream = await this.firestore.requestStream('batchGetDocuments', + /* bidirectional= */ false, request, requestTag); + stream.resume(); + for await (const response of stream) { + // Proto comes with zero-length buffer by default + if ((_a = response.transaction) === null || _a === void 0 ? void 0 : _a.length) { + this.retrievedTransactionId = response.transaction; + } + let snapshot; + if (response.found) { + (0, logger_1.logger)('DocumentReader.fetchDocuments', requestTag, 'Received document: %s', response.found.name); + snapshot = this.firestore.snapshot_(response.found, response.readTime); + } + else if (response.missing) { + (0, logger_1.logger)('DocumentReader.fetchDocuments', requestTag, 'Document missing: %s', response.missing); + snapshot = this.firestore.snapshot_(response.missing, response.readTime); + } + if (snapshot) { + const path = snapshot.ref.formattedName; + this.outstandingDocuments.delete(path); + this.retrievedDocuments.set(path, snapshot); + ++resultCount; + } + } + } + catch (error) { + const shouldRetry = + // Transactional reads are retried via the transaction runner. + !request.transaction && + !request.newTransaction && + // Only retry if we made progress. + resultCount > 0 && + // Don't retry permanent errors. + error.code !== undefined && + !(0, util_1.isPermanentRpcError)(error, 'batchGetDocuments'); + (0, logger_1.logger)('DocumentReader.fetchDocuments', requestTag, 'BatchGetDocuments failed with error: %s. Retrying: %s', error, shouldRetry); + if (shouldRetry) { + return this.fetchDocuments(requestTag); + } + else { + throw error; + } + } + finally { + (0, logger_1.logger)('DocumentReader.fetchDocuments', requestTag, 'Received %d results', resultCount); + } + } +} +exports.DocumentReader = DocumentReader; +//# sourceMappingURL=document-reader.js.map \ No newline at end of file diff --git a/node_modules/@google-cloud/firestore/build/src/document.d.ts b/node_modules/@google-cloud/firestore/build/src/document.d.ts new file mode 100644 index 0000000..f87b91f --- /dev/null +++ b/node_modules/@google-cloud/firestore/build/src/document.d.ts @@ -0,0 +1,594 @@ +/*! + * Copyright 2019 Google Inc. 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. + */ +import * as firestore from '@google-cloud/firestore'; +import { google } from '../protos/firestore_v1_proto_api'; +import { FieldTransform } from './field-value'; +import { FieldPath } from './path'; +import { DocumentReference } from './reference/document-reference'; +import { Serializer } from './serializer'; +import { Timestamp } from './timestamp'; +import { ApiMapValue, UpdateMap } from './types'; +import api = google.firestore.v1; +/** + * Returns a builder for DocumentSnapshot and QueryDocumentSnapshot instances. + * Invoke `.build()' to assemble the final snapshot. + * + * @private + * @internal + */ +export declare class DocumentSnapshotBuilder { + readonly ref: DocumentReference; + /** The fields of the Firestore `Document` Protobuf backing this document. */ + fieldsProto?: ApiMapValue; + /** The time when this document was read. */ + readTime?: Timestamp; + /** The time when this document was created. */ + createTime?: Timestamp; + /** The time when this document was last updated. */ + updateTime?: Timestamp; + constructor(ref: DocumentReference); + /** + * Builds the DocumentSnapshot. + * + * @private + * @internal + * @returns Returns either a QueryDocumentSnapshot (if `fieldsProto` was + * provided) or a DocumentSnapshot. + */ + build(): QueryDocumentSnapshot | DocumentSnapshot; +} +/** + * A DocumentSnapshot is an immutable representation for a document in a + * Firestore database. The data can be extracted with + * [data()]{@link DocumentSnapshot#data} or + * [get(fieldPath)]{@link DocumentSnapshot#get} to get a + * specific field. + * + *